diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..cfa8c3674e --- /dev/null +++ b/.clang-format @@ -0,0 +1,10 @@ +--- +BasedOnStyle: LLVM +UseTab: Always +TabWidth: 4 +IndentWidth: 4 +ColumnLimit: 160 +SortIncludes: Never +--- +Language: Cpp +Standard: c++11 diff --git a/code/Ratl/ratl.cpp b/code/Ratl/ratl.cpp index b6830ddc02..acacd15cb4 100644 --- a/code/Ratl/ratl.cpp +++ b/code/Ratl/ratl.cpp @@ -23,7 +23,7 @@ along with this program; if not, see . #include "../qcommon/q_shared.h" #if !defined(RATL_COMMON_INC) - #include "ratl_common.h" +#include "ratl_common.h" #endif #if 0 @@ -43,85 +43,69 @@ along with this program; if not, see . #endif #if !defined(CTYPE_H_INC) - #include - #define CTYPE_H_INC +#include +#define CTYPE_H_INC #endif #if !defined(STDARG_H_INC) - #include - #define STDARG_H_INC +#include +#define STDARG_H_INC #endif #if !defined(STDIO_H_INC) - #include - #define STDIO_H_INC +#include +#define STDIO_H_INC #endif - #if !defined(RUFL_HFILE_INC) - #include "../Rufl/hfile.h" +#include "../Rufl/hfile.h" #endif +void (*ratl::ratl_base::OutputPrint)(const char *) = 0; -void (*ratl::ratl_base::OutputPrint)(const char*) = 0; - - - -namespace ratl -{ +namespace ratl { #ifdef _DEBUG - int HandleSaltValue=1027; //this is used in debug for global uniqueness of handles - int FoolTheOptimizer=5; //this is used to make sure certain things aren't optimized out +int HandleSaltValue = 1027; // this is used in debug for global uniqueness of handles +int FoolTheOptimizer = 5; // this is used to make sure certain things aren't optimized out #endif +void ratl_base::save(hfile &file) {} -void ratl_base::save(hfile& file) -{ -} - -void ratl_base::load(hfile& file) -{ -} +void ratl_base::load(hfile &file) {} //////////////////////////////////////////////////////////////////////////////////////// // A Profile Print Function //////////////////////////////////////////////////////////////////////////////////////// #if !defined(FINAL_BUILD) -void ratl_base::ProfilePrint(const char * format, ...) -{ - static char string[2][1024]; // in case this is called by nested functions - static int index = 0; - static char nFormat[300]; - char* buf; +void ratl_base::ProfilePrint(const char *format, ...) { + static char string[2][1024]; // in case this is called by nested functions + static int index = 0; + static char nFormat[300]; + char *buf; // Tack On The Standard Format Around The Given Format //----------------------------------------------------- sprintf(nFormat, "[PROFILE] %s\n", format); - // Resolve Remaining Elipsis Parameters Into Newly Formated String //----------------------------------------------------------------- buf = string[index & 1]; index++; - va_list argptr; - va_start (argptr, format); - vsprintf (buf, nFormat, argptr); - va_end (argptr); + va_list argptr; + va_start(argptr, format); + vsprintf(buf, nFormat, argptr); + va_end(argptr); // Print It To Debug Output Console //---------------------------------- - if (OutputPrint!=0) - { - void (*OutputPrintFcn)(const char* text) = (void (*)(const char*))OutputPrint; + if (OutputPrint != 0) { + void (*OutputPrintFcn)(const char *text) = (void (*)(const char *))OutputPrint; OutputPrintFcn(buf); } } #else -void ratl_base::ProfilePrint(const char * format, ...) -{ -} +void ratl_base::ProfilePrint(const char *format, ...) {} #endif -} - +} // namespace ratl diff --git a/code/Ravl/CBounds.cpp b/code/Ravl/CBounds.cpp index a341527568..23d20decaf 100644 --- a/code/Ravl/CBounds.cpp +++ b/code/Ravl/CBounds.cpp @@ -47,9 +47,6 @@ along with this program; if not, see . #include #include "CBounds.h" - - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// @@ -79,55 +76,43 @@ along with this program; if not, see . } }*/ - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float CBBox::LargestAxisSize() const -{ - CVec3 Work(mMax); - Work-=mMin; +float CBBox::LargestAxisSize() const { + CVec3 Work(mMax); + Work -= mMin; return Work.MaxElement(); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float CBBox::DistanceEstimate(const CVec3 &p) const -{ - float ret=0.0f; +float CBBox::DistanceEstimate(const CVec3 &p) const { + float ret = 0.0f; // X Axis //-------- - if (p[0]>mMax[0]) - { - ret=p[0]-mMax[0]; - } - else if (p[0] mMax[0]) { + ret = p[0] - mMax[0]; + } else if (p[0] < mMin[0]) { + ret = mMax[0] - p[0]; } // Y Axis //-------- - if (p[1]>mMax[1]) - { - ret+=p[1]-mMax[1]; - } - else if (p[1] mMax[1]) { + ret += p[1] - mMax[1]; + } else if (p[1] < mMin[1]) { + ret += mMax[1] - p[1]; } // Z Axis //-------- - if (p[2]>mMax[2]) - { - ret+=p[2]-mMax[2]; - } - else if (p[2] mMax[2]) { + ret += p[2] - mMax[2]; + } else if (p[2] < mMin[2]) { + ret += mMax[2] - p[2]; } return ret; } @@ -135,22 +120,18 @@ float CBBox::DistanceEstimate(const CVec3 &p) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float CBBox::AreaEstimate(const CVec3 &p) const -{ - float Distance=DistanceEstimate(p); - if (Distance) - { - return LargestAxisSize()/Distance; +float CBBox::AreaEstimate(const CVec3 &p) const { + float Distance = DistanceEstimate(p); + if (Distance) { + return LargestAxisSize() / Distance; } return 0; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CBBox::Intersect(const CBBox &b2) -{ +void CBBox::Intersect(const CBBox &b2) { mMin.Max(b2.mMin); mMax.Min(b2.mMax); Validate(); @@ -159,21 +140,17 @@ void CBBox::Intersect(const CBBox &b2) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CBBox::Union(const CBBox &b2) -{ +void CBBox::Union(const CBBox &b2) { mMin.Min(b2.mMin); mMax.Max(b2.mMax); Validate(); } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -ESide CBBox::InOutTest(const CVec3 &v) const -{ - if (v>mMin && v mMin && v < mMax) { return Side_In; } return Side_Out; @@ -182,18 +159,13 @@ ESide CBBox::InOutTest(const CVec3 &v) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -ESide CBBox::InOutTest(const CVec3 &v,float tolout,float tolin) const -{ - if (v[0]mMax[0]+tolout|| - v[1]mMax[1]+tolout|| - v[2]mMax[2]+tolout) - { +ESide CBBox::InOutTest(const CVec3 &v, float tolout, float tolin) const { + if (v[0] < mMin[0] - tolout || v[0] > mMax[0] + tolout || v[1] < mMin[1] - tolout || v[1] > mMax[1] + tolout || v[2] < mMin[2] - tolout || + v[2] > mMax[2] + tolout) { return Side_Out; } - if (v[0]>mMin[0]+tolin&&v[0]mMin[1]+tolin&&v[1]mMin[2]+tolin&&v[2] mMin[0] + tolin && v[0] < mMax[0] - tolin && v[1] > mMin[1] + tolin && v[1] < mMax[1] - tolin && v[2] > mMin[2] + tolin && + v[2] < mMax[2] - tolin) { return Side_In; } return Side_None; @@ -202,28 +174,19 @@ ESide CBBox::InOutTest(const CVec3 &v,float tolout,float tolin) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool CBBox::BoxTouchTest(const CBBox &b2,float tolout) const -{ - if (mMin[0]-tolout>b2.mMax[0] || - mMin[1]-tolout>b2.mMax[1] || - mMin[2]-tolout>b2.mMax[2] || - b2.mMin[0]-tolout>mMax[0] || - b2.mMin[1]-tolout>mMax[1] || - b2.mMin[2]-tolout>mMax[2]) - { +bool CBBox::BoxTouchTest(const CBBox &b2, float tolout) const { + if (mMin[0] - tolout > b2.mMax[0] || mMin[1] - tolout > b2.mMax[1] || mMin[2] - tolout > b2.mMax[2] || b2.mMin[0] - tolout > mMax[0] || + b2.mMin[1] - tolout > mMax[1] || b2.mMin[2] - tolout > mMax[2]) { return false; } - return true; + return true; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool CBBox::SphereTouchTest(const CVec3 &v,float rad) const -{ - if (v[0]mMax[0]+rad|| - v[1]mMax[1]+rad|| - v[2]mMax[2]+rad) +bool CBBox::SphereTouchTest(const CVec3 &v, float rad) const { + if (v[0] < mMin[0] - rad || v[0] > mMax[0] + rad || v[1] < mMin[1] - rad || v[1] > mMax[1] + rad || v[2] < mMin[2] - rad || v[2] > mMax[2] + rad) return false; return true; } @@ -231,32 +194,22 @@ bool CBBox::SphereTouchTest(const CVec3 &v,float rad) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -TPlanes CBBox::PlaneFlags(const CVec3 &p) -{ - TPlanes ret=0; - if (p[0]mMax[0]) - { - ret|=2; - } - if (p[1] mMax[0]) { + ret |= 2; } - else if (p[1]>mMax[1]) - { - ret|=8; + if (p[1] < mMin[1]) { + ret |= 4; + } else if (p[1] > mMax[1]) { + ret |= 8; } - if (p[2]mMax[2]) - { - ret|=32; + if (p[2] < mMin[2]) { + ret |= 16; + } else if (p[2] > mMax[2]) { + ret |= 32; } return ret; } @@ -265,38 +218,31 @@ TPlanes CBBox::PlaneFlags(const CVec3 &p) // // return true if the segment intersect the box, in that case, return the first contact. //////////////////////////////////////////////////////////////////////////////////////// -bool CBBox::HitTest(CBTrace& Tr) const -{ +bool CBBox::HitTest(CBTrace &Tr) const { // Quick Box Cull //---------------- CBBox tmp; tmp.AddPoint(Tr.mStart); tmp.AddPoint(Tr.mStop); - if (!BoxTouchTest(tmp)) - { + if (!BoxTouchTest(tmp)) { return false; } - // Initialize Our Ranges //----------------------- - Tr.mRange =-1E30f; - Tr.mRangeMax = 1E30f; - + Tr.mRange = -1E30f; + Tr.mRangeMax = 1E30f; // For Each Non Zero Axis Of The Aim Vector //------------------------------------------ - float tmax,tmin,temp; - for (int axis=0; axis<3; axis++) - { - if (fabs(Tr.mAim[axis])>1E-6f) - { + float tmax, tmin, temp; + for (int axis = 0; axis < 3; axis++) { + if (fabs(Tr.mAim[axis]) > 1E-6f) { // Find Mins And Maxs From The Start Along The Axis Of Aim //--------------------------------------------------------- - tmax = ((mMax[axis]-Tr.mStart[axis])/Tr.mAim[axis]); - tmin = ((mMin[axis]-Tr.mStart[axis])/Tr.mAim[axis]); - if (tmaxTr.mRange) - { - Tr.mRange=tmin; + if (tmin > Tr.mRange) { + Tr.mRange = tmin; Tr.mNormal.Clear(); - Tr.mNormal[axis]=-1.0f; + Tr.mNormal[axis] = -1.0f; } } } - // Missed? //--------- - if (Tr.mRangeMaxTr.mLength) - { + if (Tr.mRangeMax < Tr.mRange || Tr.mRangeMax < 0.0f || Tr.mRange > Tr.mLength) { return false; } - // Start Solid Conditions //------------------------ - if (Tr.mRange<0.0f) - { + if (Tr.mRange < 0.0f) { Tr.mRange = 0.0f; Tr.mPoint = Tr.mStart; return true; } - // Calculate The End Point //------------------------- - Tr.mPoint = Tr.mAim; + Tr.mPoint = Tr.mAim; Tr.mPoint *= Tr.mRange; Tr.mPoint += Tr.mStart; return true; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CBBox::FromStr(const char *s) -{ +void CBBox::FromStr(const char *s) { assert(s && s[0]); - char MinS[256]; - char MaxS[266]; + char MinS[256]; + char MaxS[266]; sscanf(s, "(%s|%s)", MinS, MaxS); mMin.FromStr(MinS); @@ -366,12 +303,11 @@ void CBBox::FromStr(const char *s) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CBBox::ToStr(char* s) -{ +void CBBox::ToStr(char *s) { assert(s && s[0]); - char MinS[256]; - char MaxS[266]; + char MinS[256]; + char MaxS[266]; mMin.ToStr(MinS); mMax.ToStr(MaxS); @@ -381,8 +317,4 @@ void CBBox::ToStr(char* s) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CBBox::Validate() -{ - assert(mMax>=mMin); -} - +void CBBox::Validate() { assert(mMax >= mMin); } diff --git a/code/Ravl/CVec.cpp b/code/Ravl/CVec.cpp index 48d00d529f..99ea972853 100644 --- a/code/Ravl/CVec.cpp +++ b/code/Ravl/CVec.cpp @@ -36,50 +36,35 @@ along with this program; if not, see . #include #include "CVec.h" -//using namespace ravl; - - +// using namespace ravl; //////////////////////////////////////////////////////////////////////////////////////// // Static Class Member Initialization //////////////////////////////////////////////////////////////////////////////////////// -const CVec4 CVec4::mX(1.f, 0.f, 0.f, 0.f); -const CVec4 CVec4::mY(0.f, 1.f, 0.f, 0.f); -const CVec4 CVec4::mZ(0.f, 0.f, 1.f, 0.f); -const CVec4 CVec4::mW(0.f, 0.f, 0.f, 1.f); -const CVec4 CVec4::mZero(0.f, 0.f, 0.f, 0.f); - - - +const CVec4 CVec4::mX(1.f, 0.f, 0.f, 0.f); +const CVec4 CVec4::mY(0.f, 1.f, 0.f, 0.f); +const CVec4 CVec4::mZ(0.f, 0.f, 1.f, 0.f); +const CVec4 CVec4::mW(0.f, 0.f, 0.f, 1.f); +const CVec4 CVec4::mZero(0.f, 0.f, 0.f, 0.f); //////////////////////////////////////////////////////////////////////////////////////// // Length //////////////////////////////////////////////////////////////////////////////////////// -float CVec4::Len() const -{ - return sqrtf(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]+v[3]*v[3]); -} - +float CVec4::Len() const { return sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3]); } //////////////////////////////////////////////////////////////////////////////////////// // Distance To Other Point //////////////////////////////////////////////////////////////////////////////////////// -float CVec4::Dist(const CVec4& t) const -{ - return sqrtf( - (t.v[0]-v[0])*(t.v[0]-v[0]) + - (t.v[1]-v[1])*(t.v[1]-v[1]) + - (t.v[2]-v[2])*(t.v[2]-v[2]) + - (t.v[3]-v[3])*(t.v[3]-v[3])); +float CVec4::Dist(const CVec4 &t) const { + return sqrtf((t.v[0] - v[0]) * (t.v[0] - v[0]) + (t.v[1] - v[1]) * (t.v[1] - v[1]) + (t.v[2] - v[2]) * (t.v[2] - v[2]) + (t.v[3] - v[3]) * (t.v[3] - v[3])); } //////////////////////////////////////////////////////////////////////////////////////// // Normalize //////////////////////////////////////////////////////////////////////////////////////// -float CVec4::Norm() -{ - float L = Len(); - (*this)/=L; +float CVec4::Norm() { + float L = Len(); + (*this) /= L; return L; } @@ -87,15 +72,13 @@ float CVec4::Norm() // Safe Normalize // Do Not Normalize If Length Is Too Small //////////////////////////////////////////////////////////////////////////////////////// -float CVec4::SafeNorm() -{ - float d=this->Len(); - if (d>1E-10) - { - (*this)/=d; +float CVec4::SafeNorm() { + float d = this->Len(); + if (d > 1E-10) { + (*this) /= d; return d; } - (*this)=0.0f; + (*this) = 0.0f; return 0; } @@ -103,19 +86,24 @@ float CVec4::SafeNorm() // Angular Normalize // All floats Exist(-180, +180) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::AngleNorm() -{ - v[0]= fmodf(v[0],360.0f); - if (v[0]<-180.f) v[0]+=360.0f; - if (v[0]>180.f) v[0]-=360.0f; +void CVec4::AngleNorm() { + v[0] = fmodf(v[0], 360.0f); + if (v[0] < -180.f) + v[0] += 360.0f; + if (v[0] > 180.f) + v[0] -= 360.0f; - v[1]= fmodf(v[1],360.0f); - if (v[1]<-180.f) v[1]+=360.0f; - if (v[1]>180.f) v[1]-=360.0f; + v[1] = fmodf(v[1], 360.0f); + if (v[1] < -180.f) + v[1] += 360.0f; + if (v[1] > 180.f) + v[1] -= 360.0f; - v[2]= fmodf(v[2],360.0f); - if (v[2]<-180.f) v[2]+=360.0f; - if (v[2]>180.f) v[2]-=360.0f; + v[2] = fmodf(v[2], 360.0f); + if (v[2] < -180.f) + v[2] += 360.0f; + if (v[2] > 180.f) + v[2] -= 360.0f; } //////////////////////////////////////////////////////////////////////////////////////// @@ -124,28 +112,25 @@ void CVec4::AngleNorm() // This implimentation is a bit slow, needs some optimization work... // //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::Perp() -{ - float rlen,tlen; - CVec4 r,t; +void CVec4::Perp() { + float rlen, tlen; + CVec4 r, t; r = (*this); r.Cross(mX); - rlen=r.Len(); + rlen = r.Len(); t = (*this); t.Cross(mY); - tlen=t.Len(); - if (tlen>rlen) - { - r=t; - rlen=tlen; + tlen = t.Len(); + if (tlen > rlen) { + r = t; + rlen = tlen; } t = (*this); t.Cross(mZ); - tlen=t.Len(); - if (tlen>rlen) - { - r=t; - rlen=tlen; + tlen = t.Len(); + if (tlen > rlen) { + r = t; + rlen = tlen; } (*this) = r; } @@ -153,14 +138,11 @@ void CVec4::Perp() //////////////////////////////////////////////////////////////////////////////////////// // Find Largest Element (Ignores 4th component for now) //////////////////////////////////////////////////////////////////////////////////////// -int CVec4::MaxElementIndex() const -{ - if (fabs(v[0])>fabs(v[1]) && fabs(v[0])>fabs(v[2])) - { +int CVec4::MaxElementIndex() const { + if (fabs(v[0]) > fabs(v[1]) && fabs(v[0]) > fabs(v[2])) { return 0; } - if (fabs(v[1])>fabs(v[2])) - { + if (fabs(v[1]) > fabs(v[2])) { return 1; } return 2; @@ -169,65 +151,55 @@ int CVec4::MaxElementIndex() const //////////////////////////////////////////////////////////////////////////////////////// // Convert To {Pitch, Yaw} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::VecToAng() -{ - float yaw; - float pitch; +void CVec4::VecToAng() { + float yaw; + float pitch; - if (!v[1] && !v[0]) - { - yaw = 0; - pitch = (v[2]>0) ? (90.0f):(270.0f); - } - else - { + if (!v[1] && !v[0]) { + yaw = 0; + pitch = (v[2] > 0) ? (90.0f) : (270.0f); + } else { // Calculate Yaw //--------------- - if (v[0]) - { + if (v[0]) { yaw = (RAVL_VEC_RADTODEG(atan2f(v[1], v[0]))); - if (yaw<0) - { + if (yaw < 0) { yaw += 360; } - } - else - { - yaw = (v[1]>0) ? (90.0f):(270.0f); + } else { + yaw = (v[1] > 0) ? (90.0f) : (270.0f); } // Calculate Pitch //----------------- - float forward = (sqrtf(v[0]*v[0] + v[1]*v[1])); - pitch = (RAVL_VEC_RADTODEG(atan2f(v[2], forward))); - if (pitch<0) - { + float forward = (sqrtf(v[0] * v[0] + v[1] * v[1])); + pitch = (RAVL_VEC_RADTODEG(atan2f(v[2], forward))); + if (pitch < 0) { pitch += 360; } } // Copy Over Current Vector //-------------------------- - v[0] = -pitch; - v[1] = yaw; - v[2] = 0; - v[3] = 0; + v[0] = -pitch; + v[1] = yaw; + v[2] = 0; + v[3] = 0; } //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::AngToVec() -{ - float angle; - float sp, sy, cp, cy; +void CVec4::AngToVec() { + float angle; + float sp, sy, cp, cy; - angle = yaw() * (RAVL_VEC_DEGTORADCONST); - sy = sinf(angle); - cy = cosf(angle); - angle = pitch() * (RAVL_VEC_DEGTORADCONST); - sp = sinf(angle); - cp = cosf(angle); + angle = yaw() * (RAVL_VEC_DEGTORADCONST); + sy = sinf(angle); + cy = cosf(angle); + angle = pitch() * (RAVL_VEC_DEGTORADCONST); + sp = sinf(angle); + cp = cosf(angle); v[0] = cp * cy; v[1] = cp * sy; @@ -238,20 +210,19 @@ void CVec4::AngToVec() //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw, Roll} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::AngToVec(CVec4& Right, CVec4& Up) -{ - float angle; - float sr, sp, sy, cr, cp, cy; - - angle = yaw() * (RAVL_VEC_DEGTORADCONST); - sy = sinf(angle); - cy = cosf(angle); - angle = pitch() * (RAVL_VEC_DEGTORADCONST); - sp = sinf(angle); - cp = cosf(angle); - angle = roll() * (RAVL_VEC_DEGTORADCONST); - sr = sinf(angle); - cr = cosf(angle); +void CVec4::AngToVec(CVec4 &Right, CVec4 &Up) { + float angle; + float sr, sp, sy, cr, cp, cy; + + angle = yaw() * (RAVL_VEC_DEGTORADCONST); + sy = sinf(angle); + cy = cosf(angle); + angle = pitch() * (RAVL_VEC_DEGTORADCONST); + sp = sinf(angle); + cp = cosf(angle); + angle = roll() * (RAVL_VEC_DEGTORADCONST); + sr = sinf(angle); + cr = cosf(angle); // Forward Vector Is Stored Here v[0] = cp * cy; @@ -272,60 +243,49 @@ void CVec4::AngToVec(CVec4& Right, CVec4& Up) Up.v[3] = 0; } - - - /////////////////////////////////////////////////////////////////////////////////////// // Convert To {Pitch, Yaw} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::VecToAngRad() -{ - float yaw; - float pitch; +void CVec4::VecToAngRad() { + float yaw; + float pitch; - if (!v[1] && !v[0]) - { - yaw = 0; - pitch = (v[2]>0) ? (RAVL_VEC_PI*0.5f):(RAVL_VEC_PI*1.5f); - } - else - { + if (!v[1] && !v[0]) { + yaw = 0; + pitch = (v[2] > 0) ? (RAVL_VEC_PI * 0.5f) : (RAVL_VEC_PI * 1.5f); + } else { // Calculate Yaw //--------------- - if (v[0]) - { + if (v[0]) { yaw = (atan2f(v[1], v[0])); - } - else - { - yaw = (v[1]>0) ? (RAVL_VEC_PI*0.5f):(RAVL_VEC_PI*1.5f); + } else { + yaw = (v[1] > 0) ? (RAVL_VEC_PI * 0.5f) : (RAVL_VEC_PI * 1.5f); } // Calculate Pitch //----------------- - float forward = (sqrtf(v[0]*v[0] + v[1]*v[1])); - pitch = (atan2f(v[2], forward)); + float forward = (sqrtf(v[0] * v[0] + v[1] * v[1])); + pitch = (atan2f(v[2], forward)); } // Copy Over Current Vector //-------------------------- - v[0] = -pitch; - v[1] = yaw; - v[2] = 0; - v[3] = 0; + v[0] = -pitch; + v[1] = yaw; + v[2] = 0; + v[3] = 0; } //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::AngToVecRad() -{ - float sp, sy, cp, cy; +void CVec4::AngToVecRad() { + float sp, sy, cp, cy; - sy = sinf(yaw()); - cy = cosf(yaw()); - sp = sinf(pitch()); - cp = cosf(pitch()); + sy = sinf(yaw()); + cy = cosf(yaw()); + sp = sinf(pitch()); + cp = cosf(pitch()); v[0] = cp * cy; v[1] = cp * sy; @@ -336,16 +296,15 @@ void CVec4::AngToVecRad() //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw, Roll} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::AngToVecRad(CVec4& Right, CVec4& Up) -{ - float sr, sp, sy, cr, cp, cy; +void CVec4::AngToVecRad(CVec4 &Right, CVec4 &Up) { + float sr, sp, sy, cr, cp, cy; - sy = sinf(yaw()); - cy = cosf(yaw()); - sp = sinf(pitch()); - cp = cosf(pitch()); - sr = sinf(roll()); - cr = cosf(roll()); + sy = sinf(yaw()); + cy = cosf(yaw()); + sp = sinf(pitch()); + cp = cosf(pitch()); + sr = sinf(roll()); + cr = cosf(roll()); // Forward Vector Is Stored Here v[0] = cp * cy; @@ -366,12 +325,10 @@ void CVec4::AngToVecRad(CVec4& Right, CVec4& Up) Up.v[3] = 0; } - //////////////////////////////////////////////////////////////////////////////////////// // Convert To Radians //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::ToRadians() -{ +void CVec4::ToRadians() { v[0] = RAVL_VEC_DEGTORAD(v[0]); v[1] = RAVL_VEC_DEGTORAD(v[1]); v[2] = RAVL_VEC_DEGTORAD(v[2]); @@ -380,46 +337,36 @@ void CVec4::ToRadians() //////////////////////////////////////////////////////////////////////////////////////// // Convert To Degrees //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::ToDegrees() -{ +void CVec4::ToDegrees() { v[0] = RAVL_VEC_RADTODEG(v[0]); v[1] = RAVL_VEC_RADTODEG(v[1]); v[2] = RAVL_VEC_RADTODEG(v[2]); } - - - - //////////////////////////////////////////////////////////////////////////////////////// // Copy Values From String //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::FromStr(const char *s) -{ -// assert(s && s[0]); +void CVec4::FromStr(const char *s) { + // assert(s && s[0]); sscanf(s, "(%f %f %f %f)", &v[0], &v[1], &v[2], &v[3]); } //////////////////////////////////////////////////////////////////////////////////////// // Write Values To A String //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::ToStr(char* s) const -{ -// assert(s); +void CVec4::ToStr(char *s) const { + // assert(s); sprintf(s, "(%3.3f %3.3f %3.3f %3.3f)", v[0], v[1], v[2], v[3]); } - - #ifdef _DEBUG //////////////////////////////////////////////////////////////////////////////////////// // Make Sure Entire Vector Has Valid Numbers //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::IsFinite() -{ +bool CVec4::IsFinite() { #if defined(_MSC_VER) - return (_finite(v[0]) && _finite(v[1]) && _finite(v[2]) && _finite(v[3])); + return (_finite(v[0]) && _finite(v[1]) && _finite(v[2]) && _finite(v[3])); #else return isfinite(v[0]) && isfinite(v[1]) && isfinite(v[2]); #endif @@ -428,16 +375,10 @@ bool CVec4::IsFinite() //////////////////////////////////////////////////////////////////////////////////////// // Make Sure Vector Has Been Initialized //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::IsInitialized() -{ - return (v[0]!=RAVL_VEC_UDF && v[1]!=RAVL_VEC_UDF && v[2]!=RAVL_VEC_UDF && v[3]!=RAVL_VEC_UDF); -} +bool CVec4::IsInitialized() { return (v[0] != RAVL_VEC_UDF && v[1] != RAVL_VEC_UDF && v[2] != RAVL_VEC_UDF && v[3] != RAVL_VEC_UDF); } #endif - - - //////////////////////////////////////////////////////////////////////////////////////// // Point In Circumscribed Circle (True/False) // @@ -452,38 +393,40 @@ bool CVec4::IsInitialized() // \_______/ // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::PtInCircle(const CVec4 &A, const CVec4 &B, const CVec4 &C) const -{ - float vol; - float ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; - float bxdx, bydy, bzdz, cxdx, cydy, czdz; +bool CVec4::PtInCircle(const CVec4 &A, const CVec4 &B, const CVec4 &C) const { + float vol; + float ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; + float bxdx, bydy, bzdz, cxdx, cydy, czdz; - float tolerance=0.00000005f; + float tolerance = 0.00000005f; ax = A.v[0]; ay = A.v[1]; - az = ax*ax + ay*ay; + az = ax * ax + ay * ay; bx = B.v[0]; by = B.v[1]; - bz = bx*bx + by*by; + bz = bx * bx + by * by; cx = C.v[0]; cy = C.v[1]; - cz = cx*cx + cy*cy; + cz = cx * cx + cy * cy; dx = v[0]; dy = v[1]; - dz = dx*dx + dy*dy; - - bxdx=bx-dx; - bydy=by-dy; - bzdz=bz-dz; - cxdx=cx-dx; - cydy=cy-dy; - czdz=cz-dz; - vol = (az-dz)*(bxdx*cydy-bydy*cxdx) + (ay-dy)*(bzdz*cxdx-bxdx*czdz) + (ax-dx)*(bydy*czdz-bzdz*cydy); - - if ( vol > tolerance) return true; - else if ( vol < -1*tolerance) return false; - else return false; + dz = dx * dx + dy * dy; + + bxdx = bx - dx; + bydy = by - dy; + bzdz = bz - dz; + cxdx = cx - dx; + cydy = cy - dy; + czdz = cz - dz; + vol = (az - dz) * (bxdx * cydy - bydy * cxdx) + (ay - dy) * (bzdz * cxdx - bxdx * czdz) + (ax - dx) * (bydy * czdz - bzdz * cydy); + + if (vol > tolerance) + return true; + else if (vol < -1 * tolerance) + return false; + else + return false; } //////////////////////////////////////////////////////////////////////////////////////// @@ -499,14 +442,7 @@ bool CVec4::PtInCircle(const CVec4 &A, const CVec4 &B, const CVec4 &C) const // \_______/ // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::PtInCircle(const CVec4 &Circle, float Radius) const -{ - return (Dist2(Circle)<(Radius*Radius)); -} - - - - +bool CVec4::PtInCircle(const CVec4 &Circle, float Radius) const { return (Dist2(Circle) < (Radius * Radius)); } //////////////////////////////////////////////////////////////////////////////////////// // Line Intersects Circle (True/False) @@ -528,16 +464,14 @@ bool CVec4::PtInCircle(const CVec4 &Circle, float Radius) const // A // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r, CVec4 &P) -{ +bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r, CVec4 &P) { P = (*this); - float Scale = P.ProjectToLine(A, B); + float Scale = P.ProjectToLine(A, B); // If The Projected Position Is Not On The Line Segment, // Check If It Is Within Radius Of Endpoints A and B. //------------------------------------------------------- - if (Scale<0 || Scale>1) - { + if (Scale < 0 || Scale > 1) { return (PtInCircle(A, r) || PtInCircle(B, r)); } @@ -549,16 +483,14 @@ bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r, CVec4 &P) //////////////////////////////////////////////////////////////////////////////////////// // Same As Test Above, Just Don't Bother Returning P //////////////////////////////////////////////////////////////////////////////////////// -bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r) -{ - CVec4 P(*this); - float Scale = P.ProjectToLine(A, B); +bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r) { + CVec4 P(*this); + float Scale = P.ProjectToLine(A, B); // If The Projected Position Is Not On The Line Segment, // Check If It Is Within Radius Of Endpoints A and B. //------------------------------------------------------- - if (Scale<0 || Scale>1) - { + if (Scale < 0 || Scale > 1) { return (PtInCircle(A, r) || PtInCircle(B, r)); } @@ -567,28 +499,24 @@ bool CVec4::LineInCircle(const CVec4 &A, const CVec4 &B, float r) return (PtInCircle(P, r)); } - //////////////////////////////////////////////////////////////////////////////////////// // Rotate //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::RotatePoint(const CVec4 &, const CVec4 &) -{ +void CVec4::RotatePoint(const CVec4 &, const CVec4 &) { // TO DO: Use Matrix Code To Rotate } //////////////////////////////////////////////////////////////////////////////////////// // Reposition //////////////////////////////////////////////////////////////////////////////////////// -void CVec4::Reposition(const CVec4 &Translation, float RotationDegrees) -{ +void CVec4::Reposition(const CVec4 &Translation, float RotationDegrees) { // Apply Any Rotation First //-------------------------- - if (RotationDegrees) - { + if (RotationDegrees) { CVec4 Old(*this); float Rotation = RAVL_VEC_DEGTORAD(RotationDegrees); - v[0] = Old.v[0]*cosf(Rotation) - Old.v[1]*sinf(Rotation); - v[1] = Old.v[0]*sinf(Rotation) + Old.v[1]*cosf(Rotation); + v[0] = Old.v[0] * cosf(Rotation) - Old.v[1] * sinf(Rotation); + v[1] = Old.v[0] * sinf(Rotation) + Old.v[1] * cosf(Rotation); } // Now Apply Translation @@ -596,56 +524,32 @@ void CVec4::Reposition(const CVec4 &Translation, float RotationDegrees) (*this) += Translation; } - - - - - - - - - - - - //////////////////////////////////////////////////////////////////////////////////////// // Static Class Member Initialization //////////////////////////////////////////////////////////////////////////////////////// -const CVec3 CVec3::mX(1.f, 0.f, 0.f); -const CVec3 CVec3::mY(0.f, 1.f, 0.f); -const CVec3 CVec3::mZ(0.f, 0.f, 1.f); -const CVec3 CVec3::mZero(0.f, 0.f, 0.f); - - - +const CVec3 CVec3::mX(1.f, 0.f, 0.f); +const CVec3 CVec3::mY(0.f, 1.f, 0.f); +const CVec3 CVec3::mZ(0.f, 0.f, 1.f); +const CVec3 CVec3::mZero(0.f, 0.f, 0.f); //////////////////////////////////////////////////////////////////////////////////////// // Length //////////////////////////////////////////////////////////////////////////////////////// -float CVec3::Len() const -{ - return sqrtf(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); -} - +float CVec3::Len() const { return sqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); } //////////////////////////////////////////////////////////////////////////////////////// // Distance To Other Point //////////////////////////////////////////////////////////////////////////////////////// -float CVec3::Dist(const CVec3& t) const -{ - return sqrtf( - (t.v[0]-v[0])*(t.v[0]-v[0]) + - (t.v[1]-v[1])*(t.v[1]-v[1]) + - (t.v[2]-v[2])*(t.v[2]-v[2])); +float CVec3::Dist(const CVec3 &t) const { + return sqrtf((t.v[0] - v[0]) * (t.v[0] - v[0]) + (t.v[1] - v[1]) * (t.v[1] - v[1]) + (t.v[2] - v[2]) * (t.v[2] - v[2])); } //////////////////////////////////////////////////////////////////////////////////////// // Normalize //////////////////////////////////////////////////////////////////////////////////////// -float CVec3::Norm() -{ - float L = Len(); - (*this)/=L; +float CVec3::Norm() { + float L = Len(); + (*this) /= L; return L; } @@ -653,15 +557,13 @@ float CVec3::Norm() // Safe Normalize // Do Not Normalize If Length Is Too Small //////////////////////////////////////////////////////////////////////////////////////// -float CVec3::SafeNorm() -{ - float d=this->Len(); - if (d>1E-10) - { - (*this)/=d; +float CVec3::SafeNorm() { + float d = this->Len(); + if (d > 1E-10) { + (*this) /= d; return d; } - (*this)=0.0f; + (*this) = 0.0f; return 0; } @@ -669,30 +571,33 @@ float CVec3::SafeNorm() // Angular Normalize // All floats Exist(-180, +180) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::AngleNorm() -{ - v[0]= fmodf(v[0],360.0f); - if (v[0]<-180.f) v[0]+=360.0f; - if (v[0]>180.f) v[0]-=360.0f; +void CVec3::AngleNorm() { + v[0] = fmodf(v[0], 360.0f); + if (v[0] < -180.f) + v[0] += 360.0f; + if (v[0] > 180.f) + v[0] -= 360.0f; - v[1]= fmodf(v[1],360.0f); - if (v[1]<-180.f) v[1]+=360.0f; - if (v[1]>180.f) v[1]-=360.0f; + v[1] = fmodf(v[1], 360.0f); + if (v[1] < -180.f) + v[1] += 360.0f; + if (v[1] > 180.f) + v[1] -= 360.0f; - v[2]= fmodf(v[2],360.0f); - if (v[2]<-180.f) v[2]+=360.0f; - if (v[2]>180.f) v[2]-=360.0f; + v[2] = fmodf(v[2], 360.0f); + if (v[2] < -180.f) + v[2] += 360.0f; + if (v[2] > 180.f) + v[2] -= 360.0f; } //////////////////////////////////////////////////////////////////////////////////////// // Angular Normalize // All floats Exist(-180, +180) //////////////////////////////////////////////////////////////////////////////////////// -float CVec3::Truncate(float maxlen) -{ - float len=this->Len(); - if (len>maxlen && len>1E-10) - { +float CVec3::Truncate(float maxlen) { + float len = this->Len(); + if (len > maxlen && len > 1E-10) { len = maxlen / len; v[0] *= len; v[1] *= len; @@ -709,28 +614,25 @@ float CVec3::Truncate(float maxlen) // This implimentation is a bit slow, needs some optimization work... // //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::Perp() -{ - float rlen,tlen; - CVec3 r,t; +void CVec3::Perp() { + float rlen, tlen; + CVec3 r, t; r = (*this); r.Cross(mX); - rlen=r.Len(); + rlen = r.Len(); t = (*this); t.Cross(mY); - tlen=t.Len(); - if (tlen>rlen) - { - r=t; - rlen=tlen; + tlen = t.Len(); + if (tlen > rlen) { + r = t; + rlen = tlen; } t = (*this); t.Cross(mZ); - tlen=t.Len(); - if (tlen>rlen) - { - r=t; - rlen=tlen; + tlen = t.Len(); + if (tlen > rlen) { + r = t; + rlen = tlen; } (*this) = r; } @@ -738,14 +640,11 @@ void CVec3::Perp() //////////////////////////////////////////////////////////////////////////////////////// // Find Largest Element (Ignores 4th component for now) //////////////////////////////////////////////////////////////////////////////////////// -int CVec3::MaxElementIndex() const -{ - if (fabs(v[0])>fabs(v[1]) && fabs(v[0])>fabs(v[2])) - { +int CVec3::MaxElementIndex() const { + if (fabs(v[0]) > fabs(v[1]) && fabs(v[0]) > fabs(v[2])) { return 0; } - if (fabs(v[1])>fabs(v[2])) - { + if (fabs(v[1]) > fabs(v[2])) { return 1; } return 2; @@ -754,64 +653,54 @@ int CVec3::MaxElementIndex() const //////////////////////////////////////////////////////////////////////////////////////// // Convert To {Pitch, Yaw} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::VecToAng() -{ - float yaw; - float pitch; +void CVec3::VecToAng() { + float yaw; + float pitch; - if (!v[1] && !v[0]) - { - yaw = 0; - pitch = (v[2]>0) ? (90.0f):(270.0f); - } - else - { + if (!v[1] && !v[0]) { + yaw = 0; + pitch = (v[2] > 0) ? (90.0f) : (270.0f); + } else { // Calculate Yaw //--------------- - if (v[0]) - { + if (v[0]) { yaw = (RAVL_VEC_RADTODEG(atan2f(v[1], v[0]))); - if (yaw<0) - { + if (yaw < 0) { yaw += 360; } - } - else - { - yaw = (v[1]>0) ? (90.0f):(270.0f); + } else { + yaw = (v[1] > 0) ? (90.0f) : (270.0f); } // Calculate Pitch //----------------- - float forward = (sqrtf(v[0]*v[0] + v[1]*v[1])); - pitch = (RAVL_VEC_RADTODEG(atan2f(v[2], forward))); - if (pitch<0) - { + float forward = (sqrtf(v[0] * v[0] + v[1] * v[1])); + pitch = (RAVL_VEC_RADTODEG(atan2f(v[2], forward))); + if (pitch < 0) { pitch += 360; } } // Copy Over Current Vector //-------------------------- - v[0] = -pitch; - v[1] = yaw; - v[2] = 0; + v[0] = -pitch; + v[1] = yaw; + v[2] = 0; } //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::AngToVec() -{ - float angle; - float sp, sy, cp, cy; +void CVec3::AngToVec() { + float angle; + float sp, sy, cp, cy; - angle = yaw() * (RAVL_VEC_DEGTORADCONST); - sy = sinf(angle); - cy = cosf(angle); - angle = pitch() * (RAVL_VEC_DEGTORADCONST); - sp = sinf(angle); - cp = cosf(angle); + angle = yaw() * (RAVL_VEC_DEGTORADCONST); + sy = sinf(angle); + cy = cosf(angle); + angle = pitch() * (RAVL_VEC_DEGTORADCONST); + sp = sinf(angle); + cp = cosf(angle); v[0] = cp * cy; v[1] = cp * sy; @@ -821,20 +710,19 @@ void CVec3::AngToVec() //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw, Roll} (DEGREES) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::AngToVec(CVec3& Right, CVec3& Up) -{ - float angle; - float sr, sp, sy, cr, cp, cy; - - angle = yaw() * (RAVL_VEC_DEGTORADCONST); - sy = sinf(angle); - cy = cosf(angle); - angle = pitch() * (RAVL_VEC_DEGTORADCONST); - sp = sinf(angle); - cp = cosf(angle); - angle = roll() * (RAVL_VEC_DEGTORADCONST); - sr = sinf(angle); - cr = cosf(angle); +void CVec3::AngToVec(CVec3 &Right, CVec3 &Up) { + float angle; + float sr, sp, sy, cr, cp, cy; + + angle = yaw() * (RAVL_VEC_DEGTORADCONST); + sy = sinf(angle); + cy = cosf(angle); + angle = pitch() * (RAVL_VEC_DEGTORADCONST); + sp = sinf(angle); + cp = cosf(angle); + angle = roll() * (RAVL_VEC_DEGTORADCONST); + sr = sinf(angle); + cr = cosf(angle); // Forward Vector Is Stored Here v[0] = cp * cy; @@ -852,59 +740,48 @@ void CVec3::AngToVec(CVec3& Right, CVec3& Up) Up.v[2] = cr * cp; } - - - /////////////////////////////////////////////////////////////////////////////////////// // Convert To {Pitch, Yaw} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::VecToAngRad() -{ - float yaw; - float pitch; +void CVec3::VecToAngRad() { + float yaw; + float pitch; - if (!v[1] && !v[0]) - { - yaw = 0; - pitch = (v[2]>0) ? (RAVL_VEC_PI*0.5f):(RAVL_VEC_PI*1.5f); - } - else - { + if (!v[1] && !v[0]) { + yaw = 0; + pitch = (v[2] > 0) ? (RAVL_VEC_PI * 0.5f) : (RAVL_VEC_PI * 1.5f); + } else { // Calculate Yaw //--------------- - if (v[0]) - { + if (v[0]) { yaw = (atan2f(v[1], v[0])); - } - else - { - yaw = (v[1]>0) ? (RAVL_VEC_PI*0.5f):(RAVL_VEC_PI*1.5f); + } else { + yaw = (v[1] > 0) ? (RAVL_VEC_PI * 0.5f) : (RAVL_VEC_PI * 1.5f); } // Calculate Pitch //----------------- - float forward = (sqrtf(v[0]*v[0] + v[1]*v[1])); - pitch = (atan2f(v[2], forward)); + float forward = (sqrtf(v[0] * v[0] + v[1] * v[1])); + pitch = (atan2f(v[2], forward)); } // Copy Over Current Vector //-------------------------- - v[0] = -pitch; - v[1] = yaw; - v[2] = 0; + v[0] = -pitch; + v[1] = yaw; + v[2] = 0; } //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::AngToVecRad() -{ - float sp, sy, cp, cy; +void CVec3::AngToVecRad() { + float sp, sy, cp, cy; - sy = sinf(yaw()); - cy = cosf(yaw()); - sp = sinf(pitch()); - cp = cosf(pitch()); + sy = sinf(yaw()); + cy = cosf(yaw()); + sp = sinf(pitch()); + cp = cosf(pitch()); v[0] = cp * cy; v[1] = cp * sy; @@ -914,16 +791,15 @@ void CVec3::AngToVecRad() //////////////////////////////////////////////////////////////////////////////////////// // Convert From {Picth, Yaw, Roll} (RADIANS) //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::AngToVecRad(CVec3& Right, CVec3& Up) -{ - float sr, sp, sy, cr, cp, cy; +void CVec3::AngToVecRad(CVec3 &Right, CVec3 &Up) { + float sr, sp, sy, cr, cp, cy; - sy = sinf(yaw()); - cy = cosf(yaw()); - sp = sinf(pitch()); - cp = cosf(pitch()); - sr = sinf(roll()); - cr = cosf(roll()); + sy = sinf(yaw()); + cy = cosf(yaw()); + sp = sinf(pitch()); + cp = cosf(pitch()); + sr = sinf(roll()); + cr = cosf(roll()); // Forward Vector Is Stored Here v[0] = cp * cy; @@ -941,12 +817,10 @@ void CVec3::AngToVecRad(CVec3& Right, CVec3& Up) Up.v[2] = cr * cp; } - //////////////////////////////////////////////////////////////////////////////////////// // Convert To Radians //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::ToRadians() -{ +void CVec3::ToRadians() { v[0] = RAVL_VEC_DEGTORAD(v[0]); v[1] = RAVL_VEC_DEGTORAD(v[1]); v[2] = RAVL_VEC_DEGTORAD(v[2]); @@ -955,22 +829,16 @@ void CVec3::ToRadians() //////////////////////////////////////////////////////////////////////////////////////// // Convert To Degrees //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::ToDegrees() -{ +void CVec3::ToDegrees() { v[0] = RAVL_VEC_RADTODEG(v[0]); v[1] = RAVL_VEC_RADTODEG(v[1]); v[2] = RAVL_VEC_RADTODEG(v[2]); } - - - - //////////////////////////////////////////////////////////////////////////////////////// // Copy Values From String //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::FromStr(const char *s) -{ +void CVec3::FromStr(const char *s) { assert(s && s[0]); sscanf(s, "(%f %f %f)", &v[0], &v[1], &v[2]); } @@ -978,41 +846,31 @@ void CVec3::FromStr(const char *s) //////////////////////////////////////////////////////////////////////////////////////// // Write Values To A String //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::ToStr(char* s) const -{ +void CVec3::ToStr(char *s) const { assert(s); sprintf(s, "(%3.3f %3.3f %3.3f)", v[0], v[1], v[2]); } - - #ifdef _DEBUG //////////////////////////////////////////////////////////////////////////////////////// // Make Sure Entire Vector Has Valid Numbers //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::IsFinite() -{ +bool CVec3::IsFinite() { #if defined(_MSC_VER) - return (_finite(v[0]) && _finite(v[1]) && _finite(v[2])); + return (_finite(v[0]) && _finite(v[1]) && _finite(v[2])); #else - return isfinite(v[0]) && isfinite(v[1]) && isfinite(v[2]); + return isfinite(v[0]) && isfinite(v[1]) && isfinite(v[2]); #endif } //////////////////////////////////////////////////////////////////////////////////////// // Make Sure Vector Has Been Initialized //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::IsInitialized() -{ - return (v[0]!=RAVL_VEC_UDF && v[1]!=RAVL_VEC_UDF && v[2]!=RAVL_VEC_UDF); -} +bool CVec3::IsInitialized() { return (v[0] != RAVL_VEC_UDF && v[1] != RAVL_VEC_UDF && v[2] != RAVL_VEC_UDF); } #endif - - - //////////////////////////////////////////////////////////////////////////////////////// // Point In Circumscribed Circle (True/False) // @@ -1027,38 +885,40 @@ bool CVec3::IsInitialized() // \_______/ // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::PtInCircle(const CVec3 &A, const CVec3 &B, const CVec3 &C) const -{ - float vol; - float ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; - float bxdx, bydy, bzdz, cxdx, cydy, czdz; +bool CVec3::PtInCircle(const CVec3 &A, const CVec3 &B, const CVec3 &C) const { + float vol; + float ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; + float bxdx, bydy, bzdz, cxdx, cydy, czdz; - float tolerance=0.00000005f; + float tolerance = 0.00000005f; ax = A.v[0]; ay = A.v[1]; - az = ax*ax + ay*ay; + az = ax * ax + ay * ay; bx = B.v[0]; by = B.v[1]; - bz = bx*bx + by*by; + bz = bx * bx + by * by; cx = C.v[0]; cy = C.v[1]; - cz = cx*cx + cy*cy; + cz = cx * cx + cy * cy; dx = v[0]; dy = v[1]; - dz = dx*dx + dy*dy; - - bxdx=bx-dx; - bydy=by-dy; - bzdz=bz-dz; - cxdx=cx-dx; - cydy=cy-dy; - czdz=cz-dz; - vol = (az-dz)*(bxdx*cydy-bydy*cxdx) + (ay-dy)*(bzdz*cxdx-bxdx*czdz) + (ax-dx)*(bydy*czdz-bzdz*cydy); - - if ( vol > tolerance) return true; - else if ( vol < -1*tolerance) return false; - else return false; + dz = dx * dx + dy * dy; + + bxdx = bx - dx; + bydy = by - dy; + bzdz = bz - dz; + cxdx = cx - dx; + cydy = cy - dy; + czdz = cz - dz; + vol = (az - dz) * (bxdx * cydy - bydy * cxdx) + (ay - dy) * (bzdz * cxdx - bxdx * czdz) + (ax - dx) * (bydy * czdz - bzdz * cydy); + + if (vol > tolerance) + return true; + else if (vol < -1 * tolerance) + return false; + else + return false; } //////////////////////////////////////////////////////////////////////////////////////// @@ -1074,14 +934,7 @@ bool CVec3::PtInCircle(const CVec3 &A, const CVec3 &B, const CVec3 &C) const // \_______/ // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::PtInCircle(const CVec3 &Circle, float Radius) const -{ - return (Dist2(Circle)<(Radius*Radius)); -} - - - - +bool CVec3::PtInCircle(const CVec3 &Circle, float Radius) const { return (Dist2(Circle) < (Radius * Radius)); } //////////////////////////////////////////////////////////////////////////////////////// // Line Intersects Circle (True/False) @@ -1103,16 +956,14 @@ bool CVec3::PtInCircle(const CVec3 &Circle, float Radius) const // A // //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r, CVec3 &P) -{ +bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r, CVec3 &P) { P = (*this); - float Scale = P.ProjectToLine(A, B); + float Scale = P.ProjectToLine(A, B); // If The Projected Position Is Not On The Line Segment, // Check If It Is Within Radius Of Endpoints A and B. //------------------------------------------------------- - if (Scale<0 || Scale>1) - { + if (Scale < 0 || Scale > 1) { return (PtInCircle(A, r) || PtInCircle(B, r)); } @@ -1124,16 +975,14 @@ bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r, CVec3 &P) //////////////////////////////////////////////////////////////////////////////////////// // Same As Test Above, Just Don't Bother Returning P //////////////////////////////////////////////////////////////////////////////////////// -bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r) -{ - CVec3 P(*this); - float Scale = P.ProjectToLine(A, B); +bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r) { + CVec3 P(*this); + float Scale = P.ProjectToLine(A, B); // If The Projected Position Is Not On The Line Segment, // Check If It Is Within Radius Of Endpoints A and B. //------------------------------------------------------- - if (Scale<0 || Scale>1) - { + if (Scale < 0 || Scale > 1) { return (PtInCircle(A, r) || PtInCircle(B, r)); } @@ -1142,32 +991,27 @@ bool CVec3::LineInCircle(const CVec3 &A, const CVec3 &B, float r) return (PtInCircle(P, r)); } - //////////////////////////////////////////////////////////////////////////////////////// // Rotate //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::RotatePoint(const CVec3 &, const CVec3 &) -{ +void CVec3::RotatePoint(const CVec3 &, const CVec3 &) { // TO DO: Use Matrix Code To Rotate } //////////////////////////////////////////////////////////////////////////////////////// // Reposition //////////////////////////////////////////////////////////////////////////////////////// -void CVec3::Reposition(const CVec3 &Translation, float RotationDegrees) -{ +void CVec3::Reposition(const CVec3 &Translation, float RotationDegrees) { // Apply Any Rotation First //-------------------------- - if (RotationDegrees) - { + if (RotationDegrees) { CVec3 Old(*this); float Rotation = RAVL_VEC_DEGTORAD(RotationDegrees); - v[0] = Old.v[0]*cosf(Rotation) - Old.v[1]*sinf(Rotation); - v[1] = Old.v[0]*sinf(Rotation) + Old.v[1]*cosf(Rotation); + v[0] = Old.v[0] * cosf(Rotation) - Old.v[1] * sinf(Rotation); + v[1] = Old.v[0] * sinf(Rotation) + Old.v[1] * cosf(Rotation); } // Now Apply Translation //----------------------- (*this) += Translation; } - diff --git a/code/Rufl/hfile.cpp b/code/Rufl/hfile.cpp index f5003cbd8f..c4c4391fcc 100644 --- a/code/Rufl/hfile.cpp +++ b/code/Rufl/hfile.cpp @@ -30,8 +30,6 @@ along with this program; if not, see . // //////////////////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////////////// @@ -41,81 +39,63 @@ along with this program; if not, see . #endif #include "hfile.h" #if !defined(RATL_HANDLE_POOL_VS_INC) - #include "../Ratl/handle_pool_vs.h" +#include "../Ratl/handle_pool_vs.h" #endif #if !defined(RATL_VECTOR_VS_INC) - #include "../Ratl/vector_vs.h" +#include "../Ratl/vector_vs.h" #endif #if !defined(RUFL_HSTRING_INC) - #include "hstring.h" +#include "hstring.h" #endif - - - -extern bool HFILEopen_read(int& handle, const char* filepath); -extern bool HFILEopen_write(int& handle, const char* filepath); -extern bool HFILEread(int& handle, void* data, int size); -extern bool HFILEwrite(int& handle, const void* data, int size); -extern bool HFILEclose(int& handle); - - - - +extern bool HFILEopen_read(int &handle, const char *filepath); +extern bool HFILEopen_write(int &handle, const char *filepath); +extern bool HFILEread(int &handle, void *data, int size); +extern bool HFILEwrite(int &handle, const void *data, int size); +extern bool HFILEclose(int &handle); //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define MAX_OPEN_FILES 20 - +#define MAX_OPEN_FILES 20 //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -struct SOpenFile -{ - hstring mPath; - bool mForRead; - int mHandle; - float mVersion; - int mChecksum; +struct SOpenFile { + hstring mPath; + bool mForRead; + int mHandle; + float mVersion; + int mChecksum; }; -typedef ratl::handle_pool_vs TFilePool; +typedef ratl::handle_pool_vs TFilePool; -static TFilePool& Pool() -{ +static TFilePool &Pool() { static TFilePool TFP; return TFP; } - - - - - - //////////////////////////////////////////////////////////////////////////////////////// // Constructor // // Allocates a new OpenFile structure and initializes it. DOES NOT OPEN! // //////////////////////////////////////////////////////////////////////////////////////// -hfile::hfile(const char* file) -{ - if (Pool().full()) - { +hfile::hfile(const char *file) { + if (Pool().full()) { mHandle = 0; - assert("HFILE: Too Many Files Open, Unable To Grab An Unused Handle"==0); + assert("HFILE: Too Many Files Open, Unable To Grab An Unused Handle" == 0); return; } mHandle = Pool().alloc(); - SOpenFile& sfile = Pool()[mHandle]; + SOpenFile &sfile = Pool()[mHandle]; - sfile.mPath = file; - sfile.mHandle = 0; - sfile.mForRead = true; + sfile.mPath = file; + sfile.mHandle = 0; + sfile.mForRead = true; } //////////////////////////////////////////////////////////////////////////////////////// @@ -124,15 +104,12 @@ hfile::hfile(const char* file) // Releases the open file structure for resue. Also closes the file if open. // //////////////////////////////////////////////////////////////////////////////////////// -hfile::~hfile() -{ - if (is_open()) - { +hfile::~hfile() { + if (is_open()) { close(); } - if (mHandle && Pool().is_used(mHandle)) - { + if (mHandle && Pool().is_used(mHandle)) { Pool().free(mHandle); } mHandle = 0; @@ -141,11 +118,9 @@ hfile::~hfile() //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool hfile::is_open(void) const -{ - if (mHandle && Pool().is_used(mHandle)) - { - return (Pool()[mHandle].mHandle!=0); +bool hfile::is_open(void) const { + if (mHandle && Pool().is_used(mHandle)) { + return (Pool()[mHandle].mHandle != 0); } return false; } @@ -153,12 +128,10 @@ bool hfile::is_open(void) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool hfile::is_open_for_read(void) const -{ - if (mHandle && Pool().is_used(mHandle)) - { - SOpenFile& sfile = Pool()[mHandle]; - return (sfile.mHandle!=0 && sfile.mForRead); +bool hfile::is_open_for_read(void) const { + if (mHandle && Pool().is_used(mHandle)) { + SOpenFile &sfile = Pool()[mHandle]; + return (sfile.mHandle != 0 && sfile.mForRead); } return false; } @@ -166,100 +139,80 @@ bool hfile::is_open_for_read(void) const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool hfile::is_open_for_write(void) const -{ - if (mHandle && Pool().is_used(mHandle)) - { - SOpenFile& sfile = Pool()[mHandle]; - return (sfile.mHandle!=0 && !sfile.mForRead); +bool hfile::is_open_for_write(void) const { + if (mHandle && Pool().is_used(mHandle)) { + SOpenFile &sfile = Pool()[mHandle]; + return (sfile.mHandle != 0 && !sfile.mForRead); } return false; } - //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -bool hfile::open(float version, int checksum, bool read) -{ +bool hfile::open(float version, int checksum, bool read) { // Make Sure This Is A Valid Handle //---------------------------------- - if (!mHandle || !Pool().is_used(mHandle)) - { - assert("HFILE: Invalid Handle"==0); + if (!mHandle || !Pool().is_used(mHandle)) { + assert("HFILE: Invalid Handle" == 0); return false; } // Make Sure The File Is Not ALREADY Open //---------------------------------------- - SOpenFile& sfile = Pool()[mHandle]; - if (sfile.mHandle!=0) - { - assert("HFILE: Attempt To Open An Already Open File"==0); + SOpenFile &sfile = Pool()[mHandle]; + if (sfile.mHandle != 0) { + assert("HFILE: Attempt To Open An Already Open File" == 0); return false; } sfile.mForRead = read; - if (read) - { + if (read) { HFILEopen_read(sfile.mHandle, *sfile.mPath); - } - else - { + } else { HFILEopen_write(sfile.mHandle, *sfile.mPath); } // If The Open Failed, Report It And Free The SOpenFile //------------------------------------------------------ - if (sfile.mHandle==0) - { - if (!read) - { - assert("HFILE: Unable To Open File"==0); + if (sfile.mHandle == 0) { + if (!read) { + assert("HFILE: Unable To Open File" == 0); } return false; } - // Read The File's Header //------------------------ - if (read) - { - if (!HFILEread(sfile.mHandle, &sfile.mVersion, sizeof(sfile.mVersion))) - { - assert("HFILE: Unable To Read File Header"==0); + if (read) { + if (!HFILEread(sfile.mHandle, &sfile.mVersion, sizeof(sfile.mVersion))) { + assert("HFILE: Unable To Read File Header" == 0); close(); return false; } - if (!HFILEread(sfile.mHandle, &sfile.mChecksum, sizeof(sfile.mChecksum))) - { - assert("HFILE: Unable To Read File Header"==0); + if (!HFILEread(sfile.mHandle, &sfile.mChecksum, sizeof(sfile.mChecksum))) { + assert("HFILE: Unable To Read File Header" == 0); close(); return false; } // Make Sure The Checksum & Version Match //---------------------------------------- - if (sfile.mVersion!=version || sfile.mChecksum!=checksum) - { + if (sfile.mVersion != version || sfile.mChecksum != checksum) { close(); - return false; // Failed To Match Checksum Or Version Number -> Old Data + return false; // Failed To Match Checksum Or Version Number -> Old Data } - } - else - { + } else { sfile.mVersion = version; sfile.mChecksum = checksum; - if (!HFILEwrite(sfile.mHandle, &sfile.mVersion, sizeof(sfile.mVersion))) - { - assert("HFILE: Unable To Write File Header"==0); + if (!HFILEwrite(sfile.mHandle, &sfile.mVersion, sizeof(sfile.mVersion))) { + assert("HFILE: Unable To Write File Header" == 0); close(); return false; } - if (!HFILEwrite(sfile.mHandle, &sfile.mChecksum, sizeof(sfile.mChecksum))) - { - assert("HFILE: Unable To Write File Header"==0); + if (!HFILEwrite(sfile.mHandle, &sfile.mChecksum, sizeof(sfile.mChecksum))) { + assert("HFILE: Unable To Write File Header" == 0); close(); return false; } @@ -271,25 +224,21 @@ bool hfile::open(float version, int checksum, bool read) //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -bool hfile::close() -{ - if (!mHandle || !Pool().is_used(mHandle)) - { - assert("HFILE: Invalid Handle"==0); +bool hfile::close() { + if (!mHandle || !Pool().is_used(mHandle)) { + assert("HFILE: Invalid Handle" == 0); return false; } - SOpenFile& sfile = Pool()[mHandle]; - if (sfile.mHandle==0) - { - assert("HFILE: Unable TO Close Unopened File"==0); + SOpenFile &sfile = Pool()[mHandle]; + if (sfile.mHandle == 0) { + assert("HFILE: Unable TO Close Unopened File" == 0); return false; } - if (!HFILEclose(sfile.mHandle)) - { + if (!HFILEclose(sfile.mHandle)) { sfile.mHandle = 0; - assert("HFILE: Unable To Close File"==0); + assert("HFILE: Unable To Close File" == 0); return false; } sfile.mHandle = 0; @@ -300,15 +249,12 @@ bool hfile::close() //////////////////////////////////////////////////////////////////////////////////// // Searches for the first block with the matching data size, and reads it in. //////////////////////////////////////////////////////////////////////////////////// -bool hfile::load(void* data, int datasize) -{ +bool hfile::load(void *data, int datasize) { // Go Ahead And Open The File For Reading //---------------------------------------- bool auto_opened = false; - if (!is_open()) - { - if (!open_read()) - { + if (!is_open()) { + if (!open_read()) { return false; } auto_opened = true; @@ -316,25 +262,20 @@ bool hfile::load(void* data, int datasize) // Make Sure That The File Is Readable //------------------------------------- - SOpenFile& sfile = Pool()[mHandle]; - if (!sfile.mForRead) - { - assert("HFILE: Unable to load from a file that is opened for save"==0); - if (auto_opened) - { + SOpenFile &sfile = Pool()[mHandle]; + if (!sfile.mForRead) { + assert("HFILE: Unable to load from a file that is opened for save" == 0); + if (auto_opened) { close(); } return false; } - // Now Read It //------------- - if (!HFILEread(sfile.mHandle, data, datasize)) - { - assert("HFILE: Unable To Read Object"==0); - if (auto_opened) - { + if (!HFILEread(sfile.mHandle, data, datasize)) { + assert("HFILE: Unable To Read Object" == 0); + if (auto_opened) { close(); } return false; @@ -342,8 +283,7 @@ bool hfile::load(void* data, int datasize) // Success! //---------- - if (auto_opened) - { + if (auto_opened) { close(); } return true; @@ -352,15 +292,12 @@ bool hfile::load(void* data, int datasize) //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -bool hfile::save(void* data, int datasize) -{ +bool hfile::save(void *data, int datasize) { // Go Ahead And Open The File For Reading //---------------------------------------- bool auto_opened = false; - if (!is_open()) - { - if (!open_write()) - { + if (!is_open()) { + if (!open_write()) { return false; } auto_opened = true; @@ -368,32 +305,26 @@ bool hfile::save(void* data, int datasize) // Make Sure That The File Is Readable //------------------------------------- - SOpenFile& sfile = Pool()[mHandle]; - if (sfile.mForRead) - { - assert("HFILE: Unable to save to a file that is opened for read"==0); - if (auto_opened) - { + SOpenFile &sfile = Pool()[mHandle]; + if (sfile.mForRead) { + assert("HFILE: Unable to save to a file that is opened for read" == 0); + if (auto_opened) { close(); } return false; } - // Write The Actual Object //------------------------- - if (!HFILEwrite(sfile.mHandle, data, datasize)) - { - assert("HFILE: Unable To Write File Data"==0); - if (auto_opened) - { + if (!HFILEwrite(sfile.mHandle, data, datasize)) { + assert("HFILE: Unable To Write File Data" == 0); + if (auto_opened) { close(); } return false; } - if (auto_opened) - { + if (auto_opened) { close(); } return true; diff --git a/code/Rufl/hstring.cpp b/code/Rufl/hstring.cpp index 0c328e8cf7..410d5b272b 100644 --- a/code/Rufl/hstring.cpp +++ b/code/Rufl/hstring.cpp @@ -36,8 +36,6 @@ along with this program; if not, see . // //////////////////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////////////// @@ -46,71 +44,52 @@ along with this program; if not, see . #include #include "../Ratl/hash_pool_vs.h" - - //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define MAX_HASH 16384 // How Many Hash -#define BLOCK_SIZE 65536 // Size of a string storage block in bytes. - - - - - - +#define MAX_HASH 16384 // How Many Hash +#define BLOCK_SIZE 65536 // Size of a string storage block in bytes. //////////////////////////////////////////////////////////////////////////////////////// // The Hash Pool //////////////////////////////////////////////////////////////////////////////////////// -typedef ratl::hash_pool TStrPool; +typedef ratl::hash_pool TStrPool; - -static TStrPool& Pool() -{ +static TStrPool &Pool() { static TStrPool TSP; return TSP; } - - //////////////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////////////// -hstring::hstring() -{ - mHandle = 0; +hstring::hstring() { + mHandle = 0; #ifdef _DEBUG - mStr = 0; + mStr = 0; #endif } //////////////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////////////// -hstring::hstring(const char *str) -{ - init(str); -} +hstring::hstring(const char *str) { init(str); } //////////////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////////////// -hstring::hstring(const hstring &str) -{ +hstring::hstring(const hstring &str) { mHandle = str.mHandle; #ifdef _DEBUG - mStr = str.mStr; + mStr = str.mStr; #endif } - //////////////////////////////////////////////////////////////////////////////////////// // Assignment //////////////////////////////////////////////////////////////////////////////////////// -hstring& hstring::operator= (const char *str) -{ +hstring &hstring::operator=(const char *str) { init(str); return *this; } @@ -118,81 +97,61 @@ hstring& hstring::operator= (const char *str) //////////////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////////////// -hstring& hstring::operator= (const hstring &str) -{ +hstring &hstring::operator=(const hstring &str) { mHandle = str.mHandle; #ifdef _DEBUG - mStr = str.mStr; + mStr = str.mStr; #endif return *this; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const char* hstring::c_str(void) const -{ - if (!mHandle) - { - return(""); +const char *hstring::c_str(void) const { + if (!mHandle) { + return (""); } - return ((const char*)Pool()[mHandle]); + return ((const char *)Pool()[mHandle]); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const char* hstring::operator *(void) const -{ - return c_str(); -} +const char *hstring::operator*(void) const { return c_str(); } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -int hstring::length() const -{ - return strlen(c_str()); -} +int hstring::length() const { return strlen(c_str()); } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -int hstring::handle() const -{ - return mHandle; -} - - +int hstring::handle() const { return mHandle; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// -void hstring::init(const char *str) -{ - if (!str) - { +void hstring::init(const char *str) { + if (!str) { mHandle = 0; + } else { + mHandle = Pool().get_handle(str, strlen(str) + 1); // +1 for null character } - else - { - mHandle = Pool().get_handle(str, strlen(str)+1); // +1 for null character - } - #ifdef _DEBUG - mStr = (char*)Pool()[mHandle]; - #endif +#ifdef _DEBUG + mStr = (char *)Pool()[mHandle]; +#endif } - //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG -float hstring::ave_collisions() {return Pool().average_collisions();} -int hstring::total_strings() {return Pool().total_allocs();} -int hstring::total_bytes() {return Pool().size();} -int hstring::total_finds() {return Pool().total_finds();} -int hstring::total_collisions() {return Pool().total_collisions();} +float hstring::ave_collisions() { return Pool().average_collisions(); } +int hstring::total_strings() { return Pool().total_allocs(); } +int hstring::total_bytes() { return Pool().size(); } +int hstring::total_finds() { return Pool().total_finds(); } +int hstring::total_collisions() { return Pool().total_collisions(); } #endif diff --git a/code/cgame/FX_ATSTMain.cpp b/code/cgame/FX_ATSTMain.cpp index 04d7ac1227..68aac0b846 100644 --- a/code/cgame/FX_ATSTMain.cpp +++ b/code/cgame/FX_ATSTMain.cpp @@ -27,20 +27,16 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* --------------------------- FX_ATSTMainProjectileThink --------------------------- */ -void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -48,19 +44,17 @@ void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *wea // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 30 ) - { - if ( dif < 0 ) - { + if (dif < 30) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 30.0f ) * 0.95f + 0.05f; + float scale = (dif / 30.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "atst/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/shot", cent->lerpOrigin, forward); } /* @@ -68,25 +62,18 @@ void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *wea FX_ATSTMainHitWall --------------------------- */ -void FX_ATSTMainHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "atst/wall_impact", origin, normal ); -} +void FX_ATSTMainHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("atst/wall_impact", origin, normal); } /* --------------------------- FX_ATSTMainHitPlayer --------------------------- */ -void FX_ATSTMainHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - theFxScheduler.PlayEffect( "atst/flesh_impact", origin, normal ); - } - else - { - theFxScheduler.PlayEffect( "atst/droid_impact", origin, normal ); +void FX_ATSTMainHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + theFxScheduler.PlayEffect("atst/flesh_impact", origin, normal); + } else { + theFxScheduler.PlayEffect("atst/droid_impact", origin, normal); } } @@ -95,16 +82,14 @@ void FX_ATSTMainHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_ATSTSideAltProjectileThink --------------------------- */ -void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTSideAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "atst/side_alt_shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/side_alt_shot", cent->lerpOrigin, forward); } /* @@ -112,14 +97,12 @@ void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s * FX_ATSTSideMainProjectileThink --------------------------- */ -void FX_ATSTSideMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTSideMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "atst/side_main_shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/side_main_shot", cent->lerpOrigin, forward); } diff --git a/code/cgame/FX_Blaster.cpp b/code/cgame/FX_Blaster.cpp index 840b98594c..28bce37583 100644 --- a/code/cgame/FX_Blaster.cpp +++ b/code/cgame/FX_Blaster.cpp @@ -34,20 +34,14 @@ FX_BlasterProjectileThink ------------------------- */ -void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BlasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if (cent->currentState.eFlags & EF_USE_ANGLEDELTA) - { + if (cent->currentState.eFlags & EF_USE_ANGLEDELTA) { AngleVectors(cent->currentState.angles, forward, 0, 0); - } - else - { - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + } else { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -56,25 +50,20 @@ void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weap // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0 ) - { - theFxScheduler.PlayEffect( "blaster/NPCshot", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( cgs.effects.blasterShotEffect, cent->lerpOrigin, forward ); + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0) { + theFxScheduler.PlayEffect("blaster/NPCshot", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect(cgs.effects.blasterShotEffect, cent->lerpOrigin, forward); } } @@ -83,34 +72,26 @@ void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weap FX_BlasterAltFireThink ------------------------- */ -void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ - FX_BlasterProjectileThink( cent, weapon ); -} +void FX_BlasterAltFireThink(centity_t *cent, const struct weaponInfo_s *weapon) { FX_BlasterProjectileThink(cent, weapon); } /* ------------------------- FX_BlasterWeaponHitWall ------------------------- */ -void FX_BlasterWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.blasterWallImpactEffect, origin, normal ); -} +void FX_BlasterWeaponHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.blasterWallImpactEffect, origin, normal); } /* ------------------------- FX_BlasterWeaponHitPlayer ------------------------- */ -void FX_BlasterWeaponHitPlayer( gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - //temporary? just testing out the damage skin stuff -rww - if ( hit && hit->client && hit->ghoul2.size() ) - { - CG_AddGhoul2Mark(cgs.media.bdecal_burnmark1, flrand(3.5, 4.0), origin, normal, hit->s.number, - hit->client->ps.origin, hit->client->renderInfo.legsYaw, hit->ghoul2, hit->s.modelScale, Q_irand(10000, 13000)); +void FX_BlasterWeaponHitPlayer(gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid) { + // temporary? just testing out the damage skin stuff -rww + if (hit && hit->client && hit->ghoul2.size()) { + CG_AddGhoul2Mark(cgs.media.bdecal_burnmark1, flrand(3.5, 4.0), origin, normal, hit->s.number, hit->client->ps.origin, hit->client->renderInfo.legsYaw, + hit->ghoul2, hit->s.modelScale, Q_irand(10000, 13000)); } - theFxScheduler.PlayEffect( cgs.effects.blasterFleshImpactEffect, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.blasterFleshImpactEffect, origin, normal); } diff --git a/code/cgame/FX_Bowcaster.cpp b/code/cgame/FX_Bowcaster.cpp index 36f14302b2..8e7483e899 100644 --- a/code/cgame/FX_Bowcaster.cpp +++ b/code/cgame/FX_Bowcaster.cpp @@ -33,14 +33,11 @@ FX_BowcasterProjectileThink --------------------------- */ -void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BowcasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -48,19 +45,17 @@ void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *we // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward); } /* @@ -69,10 +64,7 @@ FX_BowcasterHitWall --------------------------- */ -void FX_BowcasterHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.bowcasterImpactEffect, origin, normal ); -} +void FX_BowcasterHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.bowcasterImpactEffect, origin, normal); } /* --------------------------- @@ -80,7 +72,4 @@ FX_BowcasterHitPlayer --------------------------- */ -void FX_BowcasterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bowcasterImpactEffect, origin, normal ); -} +void FX_BowcasterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bowcasterImpactEffect, origin, normal); } diff --git a/code/cgame/FX_BryarPistol.cpp b/code/cgame/FX_BryarPistol.cpp index 8e8fb0af1f..997c60098b 100644 --- a/code/cgame/FX_BryarPistol.cpp +++ b/code/cgame/FX_BryarPistol.cpp @@ -36,14 +36,11 @@ along with this program; if not, see . FX_BryarProjectileThink ------------------------- */ -void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -51,25 +48,20 @@ void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0 ) - { - theFxScheduler.PlayEffect( "bryar/NPCshot", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward ); + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0) { + theFxScheduler.PlayEffect("bryar/NPCshot", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward); } } @@ -78,21 +70,14 @@ void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo FX_BryarHitWall ------------------------- */ -void FX_BryarHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect, origin, normal ); -} +void FX_BryarHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect, origin, normal); } /* ------------------------- FX_BryarHitPlayer ------------------------- */ -void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarFleshImpactEffect, origin, normal ); -} - +void FX_BryarHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bryarFleshImpactEffect, origin, normal); } /* ------------------------- @@ -103,14 +88,11 @@ void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_BryarAltProjectileThink ------------------------- */ -void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -118,26 +100,23 @@ void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *we // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } // see if we have some sort of extra charge going on - for ( int t = 1; t < cent->gent->count; t++ ) - { + for (int t = 1; t < cent->gent->count; t++) { // just add ourselves over, and over, and over when we are charged - theFxScheduler.PlayEffect( cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward); } - theFxScheduler.PlayEffect( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward); } /* @@ -145,22 +124,20 @@ void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_BryarAltHitWall ------------------------- */ -void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) -{ - switch( power ) - { +void FX_BryarAltHitWall(vec3_t origin, vec3_t normal, int power) { + switch (power) { case 4: case 5: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect3, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect3, origin, normal); break; case 2: case 3: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect2, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect2, origin, normal); break; default: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect, origin, normal); break; } } @@ -170,7 +147,4 @@ void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) FX_BryarAltHitPlayer ------------------------- */ -void FX_BryarAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarFleshImpactEffect, origin, normal ); -} +void FX_BryarAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bryarFleshImpactEffect, origin, normal); } diff --git a/code/cgame/FX_Concussion.cpp b/code/cgame/FX_Concussion.cpp index 91244693d3..5d24f91be0 100644 --- a/code/cgame/FX_Concussion.cpp +++ b/code/cgame/FX_Concussion.cpp @@ -33,16 +33,14 @@ FX_ConcProjectileThink --------------------------- */ -void FX_ConcProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ConcProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "concussion/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("concussion/shot", cent->lerpOrigin, forward); } /* @@ -51,10 +49,7 @@ FX_ConcHitWall --------------------------- */ -void FX_ConcHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "concussion/explosion", origin, normal ); -} +void FX_ConcHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("concussion/explosion", origin, normal); } /* --------------------------- @@ -62,57 +57,46 @@ FX_ConcHitPlayer --------------------------- */ -void FX_ConcHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "concussion/explosion", origin, normal ); -} +void FX_ConcHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect("concussion/explosion", origin, normal); } /* --------------------------- FX_ConcAltShot --------------------------- */ -static vec3_t WHITE ={1.0f,1.0f,1.0f}; +static vec3_t WHITE = {1.0f, 1.0f, 1.0f}; -void FX_ConcAltShot( vec3_t start, vec3_t end ) -{ +void FX_ConcAltShot(vec3_t start, vec3_t end) { //"concussion/beam" - FX_AddLine( -1, start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, cgi_R_RegisterShader( "gfx/effects/blueLine" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + FX_AddLine(-1, start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, cgi_R_RegisterShader("gfx/effects/blueLine"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); - vec3_t BRIGHT={0.75f,0.5f,1.0f}; + vec3_t BRIGHT = {0.75f, 0.5f, 1.0f}; // add some beef - FX_AddLine( -1, start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - BRIGHT, BRIGHT, 0.0f, - 150, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + FX_AddLine(-1, start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, BRIGHT, BRIGHT, 0.0f, 150, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } - /* --------------------------- FX_ConcAltMiss --------------------------- */ -void FX_ConcAltMiss( vec3_t origin, vec3_t normal ) -{ +void FX_ConcAltMiss(vec3_t origin, vec3_t normal) { vec3_t pos, c1, c2; - VectorMA( origin, 4.0f, normal, c1 ); - VectorCopy( c1, c2 ); + VectorMA(origin, 4.0f, normal, c1); + VectorCopy(c1, c2); c1[2] += 4; c2[2] += 12; - VectorAdd( origin, normal, pos ); + VectorAdd(origin, normal, pos); pos[2] += 28; - FX_AddBezier( origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, cgi_R_RegisterShader( "gfx/effects/smokeTrail" ), FX_ALPHA_WAVE ); + FX_AddBezier(origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, + cgi_R_RegisterShader("gfx/effects/smokeTrail"), FX_ALPHA_WAVE); - theFxScheduler.PlayEffect( "concussion/alt_miss", origin, normal ); + theFxScheduler.PlayEffect("concussion/alt_miss", origin, normal); } diff --git a/code/cgame/FX_DEMP2.cpp b/code/cgame/FX_DEMP2.cpp index f5430c47ec..e69f839b56 100644 --- a/code/cgame/FX_DEMP2.cpp +++ b/code/cgame/FX_DEMP2.cpp @@ -34,18 +34,16 @@ FX_DEMP2_ProjectileThink --------------------------- */ -void FX_DEMP2_ProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_DEMP2_ProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } -// theFxScheduler.PlayEffect( "demp2/shot", cent->lerpOrigin, forward ); -// theFxScheduler.PlayEffect( "demp2/shot2", cent->lerpOrigin, forward ); - theFxScheduler.PlayEffect( "demp2/projectile", cent->lerpOrigin, forward ); + // theFxScheduler.PlayEffect( "demp2/shot", cent->lerpOrigin, forward ); + // theFxScheduler.PlayEffect( "demp2/shot2", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("demp2/projectile", cent->lerpOrigin, forward); } /* @@ -54,10 +52,7 @@ FX_DEMP2_HitWall --------------------------- */ -void FX_DEMP2_HitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "demp2/wall_impact", origin, normal ); -} +void FX_DEMP2_HitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("demp2/wall_impact", origin, normal); } /* --------------------------- @@ -65,10 +60,7 @@ FX_DEMP2_HitPlayer --------------------------- */ -void FX_DEMP2_HitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "demp2/flesh_impact", origin, normal ); -} +void FX_DEMP2_HitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect("demp2/flesh_impact", origin, normal); } /* --------------------------- @@ -76,26 +68,23 @@ FX_DEMP2_AltProjectileThink --------------------------- */ -void FX_DEMP2_AltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_DEMP2_AltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "demp2/projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("demp2/projectile", cent->lerpOrigin, forward); } //--------------------------------------------- -void FX_DEMP2_AltDetonate( vec3_t org, float size ) -{ - localEntity_t *ex; +void FX_DEMP2_AltDetonate(vec3_t org, float size) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_FADE_SCALE_MODEL; - memset( &ex->refEntity, 0, sizeof( refEntity_t )); + memset(&ex->refEntity, 0, sizeof(refEntity_t)); ex->refEntity.renderfx |= RF_VOLUMETRIC; @@ -103,10 +92,10 @@ void FX_DEMP2_AltDetonate( vec3_t org, float size ) ex->endTime = ex->startTime + 1300; ex->radius = size; - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/demp2shell" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/demp2shell"); - ex->refEntity.hModel = cgi_R_RegisterModel( "models/items/sphere.md3" ); - VectorCopy( org, ex->refEntity.origin ); + ex->refEntity.hModel = cgi_R_RegisterModel("models/items/sphere.md3"); + VectorCopy(org, ex->refEntity.origin); ex->color[0] = ex->color[1] = ex->color[2] = 255.0f; } diff --git a/code/cgame/FX_Disruptor.cpp b/code/cgame/FX_Disruptor.cpp index 33881f2b0f..ec26634ade 100644 --- a/code/cgame/FX_Disruptor.cpp +++ b/code/cgame/FX_Disruptor.cpp @@ -27,47 +27,33 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* --------------------------- FX_DisruptorMainShot --------------------------- */ -static vec3_t WHITE ={1.0f,1.0f,1.0f}; - -void FX_DisruptorMainShot( vec3_t start, vec3_t end ) -{ - FX_AddLine( -1, start, end, 0.1f, 4.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 120, cgi_R_RegisterShader( "gfx/effects/redLine" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); -} +static vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +void FX_DisruptorMainShot(vec3_t start, vec3_t end) { + FX_AddLine(-1, start, end, 0.1f, 4.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 120, cgi_R_RegisterShader("gfx/effects/redLine"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); +} /* --------------------------- FX_DisruptorAltShot --------------------------- */ -void FX_DisruptorAltShot( vec3_t start, vec3_t end, qboolean fullCharge ) -{ - FX_AddLine( -1, start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, cgi_R_RegisterShader( "gfx/effects/redLine" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); - - if ( fullCharge ) - { - vec3_t YELLER={0.8f,0.7f,0.0f}; +void FX_DisruptorAltShot(vec3_t start, vec3_t end, qboolean fullCharge) { + FX_AddLine(-1, start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, cgi_R_RegisterShader("gfx/effects/redLine"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); + + if (fullCharge) { + vec3_t YELLER = {0.8f, 0.7f, 0.0f}; // add some beef - FX_AddLine( -1, start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - YELLER, YELLER, 0.0f, - 150, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + FX_AddLine(-1, start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, YELLER, YELLER, 0.0f, 150, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } } @@ -77,21 +63,21 @@ FX_DisruptorAltMiss --------------------------- */ -void FX_DisruptorAltMiss( vec3_t origin, vec3_t normal ) -{ +void FX_DisruptorAltMiss(vec3_t origin, vec3_t normal) { vec3_t pos, c1, c2; - VectorMA( origin, 4.0f, normal, c1 ); - VectorCopy( c1, c2 ); + VectorMA(origin, 4.0f, normal, c1); + VectorCopy(c1, c2); c1[2] += 4; c2[2] += 12; - VectorAdd( origin, normal, pos ); + VectorAdd(origin, normal, pos); pos[2] += 28; - FX_AddBezier( origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, cgi_R_RegisterShader( "gfx/effects/smokeTrail" ), FX_ALPHA_WAVE ); + FX_AddBezier(origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, + cgi_R_RegisterShader("gfx/effects/smokeTrail"), FX_ALPHA_WAVE); - theFxScheduler.PlayEffect( "disruptor/alt_miss", origin, normal ); + theFxScheduler.PlayEffect("disruptor/alt_miss", origin, normal); } /* @@ -99,20 +85,13 @@ void FX_DisruptorAltMiss( vec3_t origin, vec3_t normal ) FX_KothosBeam --------------------------- */ -void FX_KothosBeam( vec3_t start, vec3_t end ) -{ - FX_AddLine( -1, start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, cgi_R_RegisterShader( "gfx/misc/dr1" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); +void FX_KothosBeam(vec3_t start, vec3_t end) { + FX_AddLine(-1, start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, cgi_R_RegisterShader("gfx/misc/dr1"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); - vec3_t YELLER={0.8f,0.7f,0.0f}; + vec3_t YELLER = {0.8f, 0.7f, 0.0f}; // add some beef - FX_AddLine( -1, start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - YELLER, YELLER, 0.0f, - 150, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), - 0, FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + FX_AddLine(-1, start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, YELLER, YELLER, 0.0f, 150, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } diff --git a/code/cgame/FX_Emplaced.cpp b/code/cgame/FX_Emplaced.cpp index 5d24e9fd65..feef3e239d 100644 --- a/code/cgame/FX_Emplaced.cpp +++ b/code/cgame/FX_Emplaced.cpp @@ -33,14 +33,11 @@ FX_EmplacedProjectileThink --------------------------- */ -void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_EmplacedProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -48,47 +45,33 @@ void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *wea // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } // If tie-fighter missle use green shot. - if ( cent->currentState.weapon == WP_TIE_FIGHTER ) - { - theFxScheduler.PlayEffect( "ships/imp_blastershot", cent->lerpOrigin, forward ); - } - else - { - if ( cent->gent && cent->gent->owner && cent->gent->owner->activator && cent->gent->owner->activator->s.number > 0 ) - { + if (cent->currentState.weapon == WP_TIE_FIGHTER) { + theFxScheduler.PlayEffect("ships/imp_blastershot", cent->lerpOrigin, forward); + } else { + if (cent->gent && cent->gent->owner && cent->gent->owner->activator && cent->gent->owner->activator->s.number > 0) { // NPC's do short shot - if ( cent->gent->alt_fire ) - { - theFxScheduler.PlayEffect( "eweb/shotNPC", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( "emplaced/shotNPC", cent->lerpOrigin, forward ); + if (cent->gent->alt_fire) { + theFxScheduler.PlayEffect("eweb/shotNPC", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect("emplaced/shotNPC", cent->lerpOrigin, forward); } - } - else - { + } else { // players do long shot - if ( cent->gent && cent->gent->alt_fire ) - { - theFxScheduler.PlayEffect( "eweb/shotNPC", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( "emplaced/shot", cent->lerpOrigin, forward ); + if (cent->gent && cent->gent->alt_fire) { + theFxScheduler.PlayEffect("eweb/shotNPC", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect("emplaced/shot", cent->lerpOrigin, forward); } } } @@ -100,15 +83,11 @@ FX_EmplacedHitWall --------------------------- */ -void FX_EmplacedHitWall( vec3_t origin, vec3_t normal, qboolean eweb ) -{ - if ( eweb ) - { - theFxScheduler.PlayEffect( "eweb/wall_impact", origin, normal ); - } - else - { - theFxScheduler.PlayEffect( "emplaced/wall_impact", origin, normal ); +void FX_EmplacedHitWall(vec3_t origin, vec3_t normal, qboolean eweb) { + if (eweb) { + theFxScheduler.PlayEffect("eweb/wall_impact", origin, normal); + } else { + theFxScheduler.PlayEffect("emplaced/wall_impact", origin, normal); } } @@ -118,15 +97,11 @@ FX_EmplacedHitPlayer --------------------------- */ -void FX_EmplacedHitPlayer( vec3_t origin, vec3_t normal, qboolean eweb ) -{ - if ( eweb ) - { - theFxScheduler.PlayEffect( "eweb/flesh_impact", origin, normal ); - } - else - { - theFxScheduler.PlayEffect( "emplaced/wall_impact", origin, normal ); +void FX_EmplacedHitPlayer(vec3_t origin, vec3_t normal, qboolean eweb) { + if (eweb) { + theFxScheduler.PlayEffect("eweb/flesh_impact", origin, normal); + } else { + theFxScheduler.PlayEffect("emplaced/wall_impact", origin, normal); } } /* @@ -135,14 +110,11 @@ FX_TurretProjectileThink --------------------------- */ -void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_TurretProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -150,17 +122,15 @@ void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "turret/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("turret/shot", cent->lerpOrigin, forward); } diff --git a/code/cgame/FX_Flechette.cpp b/code/cgame/FX_Flechette.cpp index 424418704d..eca4afe79e 100644 --- a/code/cgame/FX_Flechette.cpp +++ b/code/cgame/FX_Flechette.cpp @@ -33,18 +33,16 @@ FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - EvaluateTrajectoryDelta( ¢->gent->s.pos, cg.time, forward ); + EvaluateTrajectoryDelta(¢->gent->s.pos, cg.time, forward); - if ( VectorNormalize( forward ) == 0.0f ) - { + if (VectorNormalize(forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward); } /* @@ -52,26 +50,22 @@ void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_FlechetteWeaponHitWall ------------------------- */ -void FX_FlechetteWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.flechetteShotDeathEffect, origin, normal ); -} +void FX_FlechetteWeaponHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.flechetteShotDeathEffect, origin, normal); } /* ------------------------- FX_BlasterWeaponHitPlayer ------------------------- */ -void FX_FlechetteWeaponHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ -// if ( humanoid ) -// { - theFxScheduler.PlayEffect( cgs.effects.flechetteFleshImpactEffect, origin, normal ); -// } -// else -// { -// theFxScheduler.PlayEffect( "blaster/droid_impact", origin, normal ); -// } +void FX_FlechetteWeaponHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + // if ( humanoid ) + // { + theFxScheduler.PlayEffect(cgs.effects.flechetteFleshImpactEffect, origin, normal); + // } + // else + // { + // theFxScheduler.PlayEffect( "blaster/droid_impact", origin, normal ); + // } } /* @@ -80,14 +74,12 @@ FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward); } diff --git a/code/cgame/FX_HeavyRepeater.cpp b/code/cgame/FX_HeavyRepeater.cpp index 4c1e758506..96f02ad921 100644 --- a/code/cgame/FX_HeavyRepeater.cpp +++ b/code/cgame/FX_HeavyRepeater.cpp @@ -33,16 +33,14 @@ FX_RepeaterProjectileThink --------------------------- */ -void FX_RepeaterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "repeater/projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("repeater/projectile", cent->lerpOrigin, forward); } /* @@ -51,10 +49,7 @@ FX_RepeaterHitWall ------------------------ */ -void FX_RepeaterHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "repeater/wall_impact", origin, normal ); -} +void FX_RepeaterHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("repeater/wall_impact", origin, normal); } /* ------------------------ @@ -62,10 +57,9 @@ FX_RepeaterHitPlayer ------------------------ */ -void FX_RepeaterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "repeater/wall_impact", origin, normal ); -// theFxScheduler.PlayEffect( "repeater/flesh_impact", origin, normal ); +void FX_RepeaterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + theFxScheduler.PlayEffect("repeater/wall_impact", origin, normal); + // theFxScheduler.PlayEffect( "repeater/flesh_impact", origin, normal ); } /* @@ -74,17 +68,15 @@ FX_RepeaterAltProjectileThink ----------------------------- */ -void FX_RepeaterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); -// theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("repeater/alt_projectile", cent->lerpOrigin, forward); + // theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); } /* @@ -93,10 +85,9 @@ FX_RepeaterAltHitWall ------------------------ */ -void FX_RepeaterAltHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "repeater/concussion", origin, normal ); -// theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); +void FX_RepeaterAltHitWall(vec3_t origin, vec3_t normal) { + theFxScheduler.PlayEffect("repeater/concussion", origin, normal); + // theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); } /* @@ -105,8 +96,7 @@ FX_RepeaterAltHitPlayer ------------------------ */ -void FX_RepeaterAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "repeater/concussion", origin ); -// theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); +void FX_RepeaterAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + theFxScheduler.PlayEffect("repeater/concussion", origin); + // theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); } diff --git a/code/cgame/FX_NoghriShot.cpp b/code/cgame/FX_NoghriShot.cpp index 8f8a07de68..604d17bab7 100644 --- a/code/cgame/FX_NoghriShot.cpp +++ b/code/cgame/FX_NoghriShot.cpp @@ -34,14 +34,11 @@ FX_NoghriShotProjectileThink ------------------------- */ -void FX_NoghriShotProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_NoghriShotProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -49,19 +46,17 @@ void FX_NoghriShotProjectileThink( centity_t *cent, const struct weaponInfo_s *w // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "noghri_stick/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("noghri_stick/shot", cent->lerpOrigin, forward); } /* @@ -69,18 +64,16 @@ void FX_NoghriShotProjectileThink( centity_t *cent, const struct weaponInfo_s *w FX_NoghriShotWeaponHitWall ------------------------- */ -void FX_NoghriShotWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "noghri_stick/flesh_impact", origin, normal );//no "noghri/wall_impact"? +void FX_NoghriShotWeaponHitWall(vec3_t origin, vec3_t normal) { + theFxScheduler.PlayEffect("noghri_stick/flesh_impact", origin, normal); // no "noghri/wall_impact"? } /* ------------------------- FX_NoghriShotWeaponHitPlayer ------------------------- */ -void FX_NoghriShotWeaponHitPlayer( gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - //temporary? just testing out the damage skin stuff -rww +void FX_NoghriShotWeaponHitPlayer(gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid) { + // temporary? just testing out the damage skin stuff -rww /* if ( hit && hit->client && hit->ghoul2.size() ) { @@ -89,5 +82,5 @@ void FX_NoghriShotWeaponHitPlayer( gentity_t *hit, vec3_t origin, vec3_t normal, } */ - theFxScheduler.PlayEffect( "noghri_stick/flesh_impact", origin, normal ); + theFxScheduler.PlayEffect("noghri_stick/flesh_impact", origin, normal); } diff --git a/code/cgame/FX_RocketLauncher.cpp b/code/cgame/FX_RocketLauncher.cpp index 4b4ce4a380..1eec8912c2 100644 --- a/code/cgame/FX_RocketLauncher.cpp +++ b/code/cgame/FX_RocketLauncher.cpp @@ -32,16 +32,14 @@ FX_RocketProjectileThink --------------------------- */ -void FX_RocketProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "rocket/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("rocket/shot", cent->lerpOrigin, forward); } /* @@ -50,10 +48,7 @@ FX_RocketHitWall --------------------------- */ -void FX_RocketHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "rocket/explosion", origin, normal ); -} +void FX_RocketHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("rocket/explosion", origin, normal); } /* --------------------------- @@ -61,10 +56,7 @@ FX_RocketHitPlayer --------------------------- */ -void FX_RocketHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "rocket/explosion", origin, normal ); -} +void FX_RocketHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect("rocket/explosion", origin, normal); } /* --------------------------- @@ -72,14 +64,12 @@ FX_RocketAltProjectileThink --------------------------- */ -void FX_RocketAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "rocket/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("rocket/shot", cent->lerpOrigin, forward); } diff --git a/code/cgame/FX_TuskenShot.cpp b/code/cgame/FX_TuskenShot.cpp index 68be530623..6688d5cd9d 100644 --- a/code/cgame/FX_TuskenShot.cpp +++ b/code/cgame/FX_TuskenShot.cpp @@ -34,14 +34,11 @@ FX_TuskenShotProjectileThink ------------------------- */ -void FX_TuskenShotProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_TuskenShotProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -49,19 +46,17 @@ void FX_TuskenShotProjectileThink( centity_t *cent, const struct weaponInfo_s *w // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "tusken/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("tusken/shot", cent->lerpOrigin, forward); } /* @@ -69,23 +64,18 @@ void FX_TuskenShotProjectileThink( centity_t *cent, const struct weaponInfo_s *w FX_TuskenShotWeaponHitWall ------------------------- */ -void FX_TuskenShotWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "tusken/hitwall", origin, normal ); -} +void FX_TuskenShotWeaponHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("tusken/hitwall", origin, normal); } /* ------------------------- FX_TuskenShotWeaponHitPlayer ------------------------- */ -void FX_TuskenShotWeaponHitPlayer( gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - //temporary? just testing out the damage skin stuff -rww - if ( hit && hit->client && hit->ghoul2.size() ) - { - CG_AddGhoul2Mark(cgs.media.bdecal_burnmark1, flrand(3.5, 4.0), origin, normal, hit->s.number, - hit->client->ps.origin, hit->client->renderInfo.legsYaw, hit->ghoul2, hit->s.modelScale, Q_irand(10000, 13000)); +void FX_TuskenShotWeaponHitPlayer(gentity_t *hit, vec3_t origin, vec3_t normal, qboolean humanoid) { + // temporary? just testing out the damage skin stuff -rww + if (hit && hit->client && hit->ghoul2.size()) { + CG_AddGhoul2Mark(cgs.media.bdecal_burnmark1, flrand(3.5, 4.0), origin, normal, hit->s.number, hit->client->ps.origin, hit->client->renderInfo.legsYaw, + hit->ghoul2, hit->s.modelScale, Q_irand(10000, 13000)); } - theFxScheduler.PlayEffect( "tusken/hit", origin, normal ); + theFxScheduler.PlayEffect("tusken/hit", origin, normal); } diff --git a/code/cgame/FxPrimitives.cpp b/code/cgame/FxPrimitives.cpp index 74dc874a88..337e155c31 100644 --- a/code/cgame/FxPrimitives.cpp +++ b/code/cgame/FxPrimitives.cpp @@ -23,7 +23,7 @@ along with this program; if not, see . #include "common_headers.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #include "cg_media.h" @@ -34,25 +34,20 @@ extern int mOParticles; extern int mLines; extern int mTails; -extern vmCvar_t fx_expensivePhysics; +extern vmCvar_t fx_expensivePhysics; // Helper function //------------------------- -void ClampVec( vec3_t dat, byte *res ) -{ +void ClampVec(vec3_t dat, byte *res) { int r; // clamp all vec values, then multiply the normalized values by 255 to maximize the result - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { r = Q_ftol(dat[i] * 255.0f); - if ( r < 0 ) - { + if (r < 0) { r = 0; - } - else if ( r > 255 ) - { + } else if (r > 255) { r = 255; } @@ -60,28 +55,22 @@ void ClampVec( vec3_t dat, byte *res ) } } -void GetOrigin( int clientID, vec3_t org ) -{ - if ( clientID >=0 ) - { +void GetOrigin(int clientID, vec3_t org) { + if (clientID >= 0) { centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - VectorCopy( cent->gent->client->renderInfo.muzzlePoint, org ); + if (cent && cent->gent && cent->gent->client) { + VectorCopy(cent->gent->client->renderInfo.muzzlePoint, org); } } } -void GetDir( int clientID, vec3_t org ) -{ - if ( clientID >=0 ) - { +void GetDir(int clientID, vec3_t org) { + if (clientID >= 0) { centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - VectorCopy( cent->gent->client->renderInfo.muzzleDir, org ); + if (cent && cent->gent && cent->gent->client) { + VectorCopy(cent->gent->client->renderInfo.muzzleDir, org); } } } @@ -92,46 +81,40 @@ void GetDir( int clientID, vec3_t org ) // //-------------------------- - //-------------------------- // // Derived Particle Class // //-------------------------- -void CParticle::Die() -{ - if ( mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT) ) - { - vec3_t norm; +void CParticle::Die() { + if (mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT)) { + vec3_t norm; // Man, this just seems so, like, uncool and stuff... - VectorSet( norm, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); - VectorNormalize( norm ); + VectorSet(norm, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); + VectorNormalize(norm); - theFxScheduler.PlayEffect( mDeathFxID, mOrigin1, norm ); + theFxScheduler.PlayEffect(mDeathFxID, mOrigin1, norm); } } //---------------------------- -bool CParticle::Cull() -{ - vec3_t dir; +bool CParticle::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 16 * 16 ) - { + if (len < 16 * 16) { return true; } @@ -139,17 +122,15 @@ bool CParticle::Cull() } //---------------------------- -void CParticle::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CParticle::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); - theFxHelper.AddFxToScene( &mRefEnt ); + VectorCopy(mOrigin1, mRefEnt.origin); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mParticles++; @@ -158,80 +139,69 @@ void CParticle::Draw() //---------------------------- // Update //---------------------------- -bool CParticle::Update() -{ +bool CParticle::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t org; - vec3_t ax[3]; + vec3_t org; + vec3_t ax[3]; // Get our current position and direction - if (mModelNum>=0 && mBoltNum>=0) //bolt style + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } - } - else - {//fixme change this to bolt style... + } else { // fixme change this to bolt style... vec3_t dir, ang; - GetOrigin( mClientID, org ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, org); + GetDir(mClientID, dir); - vectoangles( dir, ang ); - AngleVectors( ang, ax[0], ax[1], ax[2] ); + vectoangles(dir, ang); + AngleVectors(ang, ax[0], ax[1], ax[2]); } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // calc the real velocity and accel vectors - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); realVel[2] += 0.5f * mGravity * time; - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); + VectorMA(org, time, realVel, mOrigin1); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull()) - { + if (!Cull()) { UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -246,111 +216,89 @@ bool CParticle::Update() //---------------------------- // Update Origin //---------------------------- -bool CParticle::UpdateOrigin() -{ - vec3_t new_origin; -// float ftime, time2; +bool CParticle::UpdateOrigin() { + vec3_t new_origin; + // float ftime, time2; UpdateVelocity(); // Calc the time differences -// ftime = theFxHelper.mFrameTime * 0.001f; - //time2 = ftime * ftime * 0.5f; -// time2=0; + // ftime = theFxHelper.mFrameTime * 0.001f; + // time2 = ftime * ftime * 0.5f; + // time2=0; // Predict the new position - new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0];// + time2 * mVel[0]; - new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1];// + time2 * mVel[1]; - new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2];// + time2 * mVel[2]; + new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0]; // + time2 * mVel[0]; + new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1]; // + time2 * mVel[1]; + new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2]; // + time2 * mVel[2]; // Only perform physics if this object is tagged to do so - if ( (mFlags & FX_APPLY_PHYSICS) ) - { + if ((mFlags & FX_APPLY_PHYSICS)) { bool solid; - if ( (mFlags&FX_EXPENSIVE_PHYSICS) - && fx_expensivePhysics.integer ) - { + if ((mFlags & FX_EXPENSIVE_PHYSICS) && fx_expensivePhysics.integer) { solid = true; // by setting this to true, we force a real trace to happen - } - else - { + } else { // if this returns solid, we need to do a trace - solid = !!(CG_PointContents( new_origin, ENTITYNUM_WORLD ) & ( MASK_SHOT | CONTENTS_WATER )); + solid = !!(CG_PointContents(new_origin, ENTITYNUM_WORLD) & (MASK_SHOT | CONTENTS_WATER)); } - if ( solid ) - { - trace_t trace; - float dot; - - if ( mFlags & FX_USE_BBOX ) - { - if (mFlags & FX_GHOUL2_TRACE) - { - theFxHelper.G2Trace( &trace, mOrigin1, mMin, mMax, new_origin, ENTITYNUM_NONE, ( MASK_SHOT | CONTENTS_WATER ) ); - } - else - { - theFxHelper.Trace( &trace, mOrigin1, mMin, mMax, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) ); - } - } - else - { - if (mFlags & FX_GHOUL2_TRACE) - { - theFxHelper.G2Trace( &trace, mOrigin1, NULL, NULL, new_origin, ENTITYNUM_NONE, ( MASK_SHOT | CONTENTS_WATER ) ); + if (solid) { + trace_t trace; + float dot; + + if (mFlags & FX_USE_BBOX) { + if (mFlags & FX_GHOUL2_TRACE) { + theFxHelper.G2Trace(&trace, mOrigin1, mMin, mMax, new_origin, ENTITYNUM_NONE, (MASK_SHOT | CONTENTS_WATER)); + } else { + theFxHelper.Trace(&trace, mOrigin1, mMin, mMax, new_origin, -1, (MASK_SHOT | CONTENTS_WATER)); } - else - { - theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) ); + } else { + if (mFlags & FX_GHOUL2_TRACE) { + theFxHelper.G2Trace(&trace, mOrigin1, NULL, NULL, new_origin, ENTITYNUM_NONE, (MASK_SHOT | CONTENTS_WATER)); + } else { + theFxHelper.Trace(&trace, mOrigin1, NULL, NULL, new_origin, -1, (MASK_SHOT | CONTENTS_WATER)); } } - if ( trace.startsolid || trace.allsolid || trace.fraction == 1.0) - { - } - else - { + if (trace.startsolid || trace.allsolid || trace.fraction == 1.0) { + } else { // Hit something - if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT )) - { - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal ); + if (mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT)) { + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, trace.plane.normal); } - if ( mFlags & FX_KILL_ON_IMPACT ) - { + if (mFlags & FX_KILL_ON_IMPACT) { // time to die return false; } - VectorMA( mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel ); + VectorMA(mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel); - dot = DotProduct( mVel, trace.plane.normal ); + dot = DotProduct(mVel, trace.plane.normal); - VectorMA( mVel, -2 * dot, trace.plane.normal, mVel ); + VectorMA(mVel, -2 * dot, trace.plane.normal, mVel); - VectorScale( mVel, mElasticity, mVel ); + VectorScale(mVel, mElasticity, mVel); // If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid // doing expensive operations when they aren't needed - if ( trace.plane.normal[2] > 0 && mVel[2] < 4 ) - { - VectorClear( mVel ); - VectorClear( mAccel ); + if (trace.plane.normal[2] > 0 && mVel[2] < 4) { + VectorClear(mVel); + VectorClear(mAccel); - mFlags &= ~(FX_APPLY_PHYSICS|FX_IMPACT_RUNS_FX); + mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX); } // Set the origin to the exact impact point - VectorCopy( trace.endpos, mOrigin1 ); + VectorCopy(trace.endpos, mOrigin1); return true; } } } // No physics were done to this object, move it - VectorCopy( new_origin, mOrigin1 ); + VectorCopy(new_origin, mOrigin1); return true; } @@ -358,72 +306,51 @@ bool CParticle::UpdateOrigin() //---------------------------- // Update Size //---------------------------- -void CParticle::UpdateSize() -{ +void CParticle::UpdateSize() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) - / (float)(mTimeEnd - mSizeParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSizeParm - theFxHelper.mTime) - / (float)(mSizeParm - mTimeStart); - } - else - { + perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if (( mFlags & FX_SIZE_RAND )) - { + if ((mFlags & FX_SIZE_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -434,144 +361,102 @@ void CParticle::UpdateSize() //---------------------------- // Update RGB //---------------------------- -void CParticle::UpdateRGB() -{ +void CParticle::UpdateRGB() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) - / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) - / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mRGBParm - theFxHelper.mTime) - / (float)(mRGBParm - mTimeStart); - } - else - { + perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if (( mFlags & FX_RGB_LINEAR )) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if (( mFlags & FX_RGB_RAND )) - { + if ((mFlags & FX_RGB_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); - VectorMA( res, (1.0f - perc1), mRGBEnd, mRefEnt.angles ); // angles is a temp storage, will get clamped to a byte in the UpdateAlpha section + VectorScale(mRGBStart, perc1, res); + VectorMA(res, (1.0f - perc1), mRGBEnd, mRefEnt.angles); // angles is a temp storage, will get clamped to a byte in the UpdateAlpha section } - //---------------------------- // Update Alpha //---------------------------- -void CParticle::UpdateAlpha() -{ +void CParticle::UpdateAlpha() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_NONLINEAR ) - { - if ( theFxHelper.mTime > mAlphaParm ) - { + if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_NONLINEAR) { + if (theFxHelper.mTime > mAlphaParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) - / (float)(mTimeEnd - mAlphaParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) / (float)(mTimeEnd - mAlphaParm); } - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mAlphaParm ); - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_CLAMP ) - { - if ( theFxHelper.mTime < mAlphaParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mAlphaParm); + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_CLAMP) { + if (theFxHelper.mTime < mAlphaParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mAlphaParm - theFxHelper.mTime) - / (float)(mAlphaParm - mTimeStart); - } - else - { + perc2 = (float)(mAlphaParm - theFxHelper.mTime) / (float)(mAlphaParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } @@ -580,33 +465,26 @@ void CParticle::UpdateAlpha() perc1 = (mAlphaStart * perc1) + (mAlphaEnd * (1.0f - perc1)); // We should be in the right range, but clamp to ensure - if ( perc1 < 0.0f ) - { + if (perc1 < 0.0f) { perc1 = 0.0f; - } - else if ( perc1 > 1.0f ) - { + } else if (perc1 > 1.0f) { perc1 = 1.0f; } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( (mFlags & FX_ALPHA_RAND) ) - { + if ((mFlags & FX_ALPHA_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } - if ( mFlags & FX_USE_ALPHA ) - { + if (mFlags & FX_USE_ALPHA) { // should use this when using art that has an alpha channel - ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) ); - mRefEnt.shaderRGBA[3] = (byte)(perc1 * 0xff); - } - else - { + ClampVec(mRefEnt.angles, (byte *)(&mRefEnt.shaderRGBA)); + mRefEnt.shaderRGBA[3] = (byte)(perc1 * 0xff); + } else { // Modulate the rgb fields by the alpha value to do the fade, works fine for additive blending - VectorScale( mRefEnt.angles, perc1, mRefEnt.angles ); - ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) ); + VectorScale(mRefEnt.angles, perc1, mRefEnt.angles); + ClampVec(mRefEnt.angles, (byte *)(&mRefEnt.shaderRGBA)); } } @@ -616,26 +494,22 @@ void CParticle::UpdateAlpha() // //-------------------------------- - //---------------------------- -bool COrientedParticle::Cull() -{ - vec3_t dir; +bool COrientedParticle::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 24 * 24 ) - { + if (len < 24 * 24) { return true; } @@ -643,18 +517,16 @@ bool COrientedParticle::Cull() } //---------------------------- -void COrientedParticle::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void COrientedParticle::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mNormal, mRefEnt.axis[0] ); - theFxHelper.AddFxToScene( &mRefEnt ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mNormal, mRefEnt.axis[0]); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mOParticles++; @@ -663,87 +535,76 @@ void COrientedParticle::Draw() //---------------------------- // Update //---------------------------- -bool COrientedParticle::Update() -{ +bool COrientedParticle::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t org; - vec3_t ax[3]; + vec3_t org; + vec3_t ax[3]; // Get our current position and direction - if (mModelNum>=0 && mBoltNum>=0) //bolt style + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } - } - else - {//fixme change this to bolt style... + } else { // fixme change this to bolt style... vec3_t dir, ang; - GetOrigin( mClientID, org ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, org); + GetDir(mClientID, dir); - vectoangles( dir, ang ); - AngleVectors( ang, ax[0], ax[1], ax[2] ); + vectoangles(dir, ang); + AngleVectors(ang, ax[0], ax[1], ax[2]); } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // calc the real velocity and accel vectors - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); realVel[2] += 0.5f * mGravity * time; - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); - - //use the normalOffset and add that to the actual normal of the bolt - //NOTE: not tested!!! - vec3_t boltAngles, offsetAngles, transformedAngles; - vectoangles( ax[0], boltAngles ); - vectoangles( mNormalOffset, offsetAngles ); - VectorAdd( boltAngles, offsetAngles, transformedAngles ); - AngleVectors( transformedAngles, mNormal, NULL, NULL ); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + VectorMA(org, time, realVel, mOrigin1); + + // use the normalOffset and add that to the actual normal of the bolt + // NOTE: not tested!!! + vec3_t boltAngles, offsetAngles, transformedAngles; + vectoangles(ax[0], boltAngles); + vectoangles(mNormalOffset, offsetAngles); + VectorAdd(boltAngles, offsetAngles, transformedAngles); + AngleVectors(transformedAngles, mNormal, NULL, NULL); + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull()) - { + if (!Cull()) { UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -755,7 +616,6 @@ bool COrientedParticle::Update() return true; } - //---------------------------- // // Derived Line Class @@ -763,83 +623,69 @@ bool COrientedParticle::Update() //---------------------------- //---------------------------- -void CLine::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CLine::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mLines++; } //---------------------------- -bool CLine::Update() -{ +bool CLine::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t ax[3] = {}; + vec3_t ax[3] = {}; // Get our current position and direction - if (mModelNum>=0 && mBoltNum>=0) //bolt style + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - } - else - {//fixme change this to bolt style... + } else { // fixme change this to bolt style... // Get our current position and direction - GetOrigin( mClientID, mOrigin1 ); - GetDir( mClientID, ax[0] ); + GetOrigin(mClientID, mOrigin1); + GetDir(mClientID, ax[0]); } - VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point + VectorAdd(mOrigin1, mOrgOffset, mOrigin1); // add the offset to the bolt point - vec3_t end; - trace_t trace; - if ( mFlags & FX_APPLY_PHYSICS ) - { - VectorMA( mOrigin1, 2048, ax[0], end ); + vec3_t end; + trace_t trace; + if (mFlags & FX_APPLY_PHYSICS) { + VectorMA(mOrigin1, 2048, ax[0], end); - theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, end, mClientID, MASK_SHOT ); + theFxHelper.Trace(&trace, mOrigin1, NULL, NULL, end, mClientID, MASK_SHOT); - VectorCopy( trace.endpos, mOrigin2 ); + VectorCopy(trace.endpos, mOrigin2); - if ( mImpactFxID > 0 ) - { - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal ); + if (mImpactFxID > 0) { + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, trace.plane.normal); } - } - else - { - VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 ); - VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 ); - VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 ); + } else { + VectorMA(mOrigin1, mVel[0], ax[0], mOrigin2); + VectorMA(mOrigin2, mVel[1], ax[1], mOrigin2); + VectorMA(mOrigin2, mVel[2], ax[2], mOrigin2); } } @@ -852,100 +698,85 @@ bool CLine::Update() return true; } - //---------------------------- // // Derived Electricity Class // //---------------------------- -void CElectricity::Initialize() -{ +void CElectricity::Initialize() { mRefEnt.frame = Q_flrand(0.0f, 1.0f) * 1265536; mRefEnt.endTime = cg.time + (mTimeEnd - mTimeStart); - if ( mFlags & FX_DEPTH_HACK ) - { + if (mFlags & FX_DEPTH_HACK) { mRefEnt.renderfx |= RF_DEPTHHACK; } - if ( mFlags & FX_BRANCH ) - { + if (mFlags & FX_BRANCH) { mRefEnt.renderfx |= RF_FORKED; } - if ( mFlags & FX_TAPER ) - { + if (mFlags & FX_TAPER) { mRefEnt.renderfx |= RF_TAPERED; } - if ( mFlags & FX_GROW ) - { + if (mFlags & FX_GROW) { mRefEnt.renderfx |= RF_GROW; } } //---------------------------- -void CElectricity::Draw() -{ - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); +void CElectricity::Draw() { + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); mRefEnt.angles[0] = mChaos; mRefEnt.angles[1] = mTimeEnd - mTimeStart; - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mLines++; // NOT REALLY A LINE! } //---------------------------- -bool CElectricity::Update() -{ +bool CElectricity::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - //Handle Relative and Bolted Effects - if ( mFlags & FX_RELATIVE ) - {//add mOrgOffset to bolt position and store in mOrigin1 - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + // Handle Relative and Bolted Effects + if (mFlags & FX_RELATIVE) { // add mOrgOffset to bolt position and store in mOrigin1 + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t ax[3] = {}; + vec3_t ax[3] = {}; // Get our current position and direction - if (mModelNum>=0 && mBoltNum>=0) //bolt style + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - } - else - {//fixme change this to bolt style... + } else { // fixme change this to bolt style... // Get our current position and direction - GetOrigin( mClientID, mOrigin1 ); - GetDir( mClientID, ax[0] ); + GetOrigin(mClientID, mOrigin1); + GetDir(mClientID, ax[0]); } - //add the offset to the bolt point + // add the offset to the bolt point VectorAdd(mOrigin1, mOrgOffset, mOrigin1); - //add the endpoint offset to the start to get the final offset - VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 ); - VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 ); - VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 ); + // add the endpoint offset to the start to get the final offset + VectorMA(mOrigin1, mVel[0], ax[0], mOrigin2); + VectorMA(mOrigin2, mVel[1], ax[1], mOrigin2); + VectorMA(mOrigin2, mVel[2], ax[2], mOrigin2); } - //else just uses the static origin1 & origin2 as start and end + // else just uses the static origin1 & origin2 as start and end UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -955,22 +786,19 @@ bool CElectricity::Update() return true; } - //---------------------------- // // Derived Tail Class // //---------------------------- -bool CTail::Cull() -{ - vec3_t dir; +bool CTail::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } @@ -978,105 +806,92 @@ bool CTail::Cull() } //---------------------------- -void CTail::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CTail::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mTails++; } //---------------------------- -bool CTail::Update() -{ +bool CTail::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( !fx_freeze.integer ) - { - VectorCopy( mOrigin1, mOldOrigin ); + if (!fx_freeze.integer) { + VectorCopy(mOrigin1, mOldOrigin); } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t org; - vec3_t ax[3]; - if (mModelNum>=0 && mBoltNum>=0) //bolt style + vec3_t org; + vec3_t ax[3]; + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } - } - else - { - vec3_t dir; + } else { + vec3_t dir; // Get our current position and direction - GetOrigin( mClientID, org ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, org); + GetDir(mClientID, dir); vec3_t ang; - vectoangles( dir, ang ); - AngleVectors( ang, ax[0], ax[1], ax[2] ); + vectoangles(dir, ang); + AngleVectors(ang, ax[0], ax[1], ax[2]); } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); // calc the real velocity and accel vectors - // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra work - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra + // work + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // Get our real velocity at the current time, taking into account the effects of acceleration. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); + VectorMA(org, time, realVel, mOrigin1); // Just calc an old point some time in the past, doesn't really matter when - VectorMA( org, (time - 0.003f), realVel, mOldOrigin ); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + VectorMA(org, (time - 0.003f), realVel, mOldOrigin); + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull() ) - { + if (!Cull()) { UpdateSize(); UpdateLength(); UpdateRGB(); @@ -1091,72 +906,51 @@ bool CTail::Update() } //---------------------------- -void CTail::UpdateLength() -{ +void CTail::UpdateLength() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_NONLINEAR ) - { - if ( theFxHelper.mTime > mLengthParm ) - { + if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_NONLINEAR) { + if (theFxHelper.mTime > mLengthParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) - / (float)(mTimeEnd - mLengthParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) / (float)(mTimeEnd - mLengthParm); } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mLengthParm ); - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_CLAMP ) - { - if ( theFxHelper.mTime < mLengthParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mLengthParm); + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_CLAMP) { + if (theFxHelper.mTime < mLengthParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mLengthParm - theFxHelper.mTime) - / (float)(mLengthParm - mTimeStart); - } - else - { + perc2 = (float)(mLengthParm - theFxHelper.mTime) / (float)(mLengthParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_LENGTH_RAND ) - { + if (mFlags & FX_LENGTH_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -1165,37 +959,33 @@ void CTail::UpdateLength() } //---------------------------- -void CTail::CalcNewEndpoint() -{ +void CTail::CalcNewEndpoint() { vec3_t temp; // FIXME: Hmmm, this looks dumb when physics are on and a bounce happens - VectorSubtract( mOldOrigin, mOrigin1, temp ); + VectorSubtract(mOldOrigin, mOrigin1, temp); // I wish we didn't have to do a VectorNormalize every frame..... - VectorNormalize( temp ); + VectorNormalize(temp); - VectorMA( mOrigin1, mLength, temp, mRefEnt.oldorigin ); + VectorMA(mOrigin1, mLength, temp, mRefEnt.oldorigin); } - //---------------------------- // // Derived Cylinder Class // //---------------------------- -void CCylinder::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CCylinder::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorMA( mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorMA(mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } @@ -1203,72 +993,51 @@ void CCylinder::Draw() //---------------------------- // Update Size2 //---------------------------- -void CCylinder::UpdateSize2() -{ +void CCylinder::UpdateSize2() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_NONLINEAR ) - { - if ( theFxHelper.mTime > mSize2Parm ) - { + if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_NONLINEAR) { + if (theFxHelper.mTime > mSize2Parm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) - / (float)(mTimeEnd - mSize2Parm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) / (float)(mTimeEnd - mSize2Parm); } - if ( (mFlags & FX_SIZE2_LINEAR) ) - { + if ((mFlags & FX_SIZE2_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSize2Parm ); - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_CLAMP ) - { - if ( theFxHelper.mTime < mSize2Parm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSize2Parm); + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_CLAMP) { + if (theFxHelper.mTime < mSize2Parm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSize2Parm - theFxHelper.mTime) - / (float)(mSize2Parm - mTimeStart); - } - else - { + perc2 = (float)(mSize2Parm - theFxHelper.mTime) / (float)(mSize2Parm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE2_RAND ) - { + if (mFlags & FX_SIZE2_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -1277,47 +1046,39 @@ void CCylinder::UpdateSize2() } //---------------------------- -bool CCylinder::Update() -{ +bool CCylinder::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { // we are somehow not bolted even though the flag is on? + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t ax[3] = {}; + vec3_t ax[3] = {}; // Get our current position and direction - if (mModelNum>=0 && mBoltNum>=0) //bolt style + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { const centity_t ¢ = cg_entities[mClientID]; - if (!cent.gent->ghoul2.IsValid()) - { + if (!cent.gent->ghoul2.IsValid()) { return false; } - if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(cent, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - } - else - {//fixme change this to bolt style... + } else { // fixme change this to bolt style... // Get our current position and direction - GetOrigin( mClientID, mOrigin1 ); - GetDir( mClientID, ax[0] ); + GetOrigin(mClientID, mOrigin1); + GetDir(mClientID, ax[0]); } - VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point + VectorAdd(mOrigin1, mOrgOffset, mOrigin1); // add the offset to the bolt point - VectorCopy( ax[0], mRefEnt.axis[0] ); - //FIXME: should mNormal be a modifier on the forward axis? + VectorCopy(ax[0], mRefEnt.axis[0]); + // FIXME: should mNormal be a modifier on the forward axis? /* VectorMA( mOrigin1, mNormal[0], ax[0], mOrigin2 ); VectorMA( mOrigin2, mNormal[1], ax[1], mOrigin2 ); @@ -1336,7 +1097,6 @@ bool CCylinder::Update() return true; } - //---------------------------- // // Derived Emitter Class @@ -1346,34 +1106,29 @@ bool CCylinder::Update() //---------------------------- // Draw //---------------------------- -void CEmitter::Draw() -{ +void CEmitter::Draw() { // Emitters don't draw themselves, but they may need to add an attached model - if ( mFlags & FX_ATTACHED_MODEL ) - { + if (mFlags & FX_ATTACHED_MODEL) { mRefEnt.nonNormalizedAxes = qtrue; - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); // ensure that we are sized - for ( int i = 0; i < 3; i++ ) - { - VectorScale( mRefEnt.axis[i], mRefEnt.radius, mRefEnt.axis[i] ); + for (int i = 0; i < 3; i++) { + VectorScale(mRefEnt.axis[i], mRefEnt.radius, mRefEnt.axis[i]); } - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); } // If we are emitting effects, we had better be careful because just calling it every cgame frame could // either choke up the effects system on a fast machine, or look really nasty on a low end one. - if ( mFlags & FX_EMIT_FX ) - { - vec3_t org, v; - float ftime, time2, - step; - int i, t, dif; + if (mFlags & FX_EMIT_FX) { + vec3_t org, v; + float ftime, time2, step; + int i, t, dif; -#define TRAIL_RATE 8 // we "think" at about a 60hz rate +#define TRAIL_RATE 8 // we "think" at about a 60hz rate // Pick a target step distance and square it step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance; @@ -1381,72 +1136,59 @@ void CEmitter::Draw() dif = 0; - for ( t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE ) - { + for (t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE) { dif += TRAIL_RATE; // ?Not sure if it's better to update this before or after updating the origin - VectorMA( mOldVelocity, dif * 0.001f, mAccel, v ); + VectorMA(mOldVelocity, dif * 0.001f, mAccel, v); // Calc the time differences ftime = dif * 0.001f; time2 = ftime * ftime * 0.5f; // Predict the new position - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { org[i] = mOldOrigin[i] + ftime * v[i] + time2 * v[i]; } // Only perform physics if this object is tagged to do so - if ( (mFlags & FX_APPLY_PHYSICS) ) - { + if ((mFlags & FX_APPLY_PHYSICS)) { bool solid; - if ( (mFlags&FX_EXPENSIVE_PHYSICS) - && fx_expensivePhysics.integer ) - { + if ((mFlags & FX_EXPENSIVE_PHYSICS) && fx_expensivePhysics.integer) { solid = true; // by setting this to true, we force a real trace to happen - } - else - { + } else { // if this returns solid, we need to do a trace - solid = !!(CG_PointContents( org, ENTITYNUM_WORLD ) & MASK_SHOT); + solid = !!(CG_PointContents(org, ENTITYNUM_WORLD) & MASK_SHOT); } - if ( solid ) - { - trace_t trace; + if (solid) { + trace_t trace; - if ( mFlags & FX_USE_BBOX ) - { - theFxHelper.Trace( &trace, mOldOrigin, mMin, mMax, org, -1, MASK_SHOT ); - } - else - { - theFxHelper.Trace( &trace, mOldOrigin, NULL, NULL, org, -1, MASK_SHOT ); + if (mFlags & FX_USE_BBOX) { + theFxHelper.Trace(&trace, mOldOrigin, mMin, mMax, org, -1, MASK_SHOT); + } else { + theFxHelper.Trace(&trace, mOldOrigin, NULL, NULL, org, -1, MASK_SHOT); } // Hit something - if ( trace.fraction < 1.0f || trace.startsolid || trace.allsolid ) - { + if (trace.fraction < 1.0f || trace.startsolid || trace.allsolid) { return; } } } // Is it time to draw an effect? - if ( DistanceSquared( org, mOldOrigin ) >= step ) - { + if (DistanceSquared(org, mOldOrigin) >= step) { // Pick a new target step distance and square it step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance; step *= step; // We met the step criteria so, we should add in the effect - theFxScheduler.PlayEffect( mEmitterFxID, org, mRefEnt.axis ); + theFxScheduler.PlayEffect(mEmitterFxID, org, mRefEnt.axis); - VectorCopy( org, mOldOrigin ); - VectorCopy( v, mOldVelocity ); + VectorCopy(org, mOldOrigin); + VectorCopy(v, mOldVelocity); dif = 0; mOldTime = t; } @@ -1457,15 +1199,13 @@ void CEmitter::Draw() } //---------------------------- -bool CEmitter::Update() -{ +bool CEmitter::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - //FIXME: Handle Relative and Bolted Effects + // FIXME: Handle Relative and Bolted Effects /* if ( mFlags & FX_RELATIVE ) { @@ -1481,25 +1221,23 @@ bool CEmitter::Update() } */ // Use this to track if we've stopped moving - VectorCopy( mOrigin1, mOldOrigin ); - VectorCopy( mVel, mOldVelocity ); + VectorCopy(mOrigin1, mOldOrigin); + VectorCopy(mVel, mOldVelocity); - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { // we are marked for death + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } // If the thing is no longer moving, kill the angle delta, but don't do it too quickly or it will // look very artificial. Don't do it too slowly or it will look like there is no friction. - if ( VectorCompare( mOldOrigin, mOrigin1 )) - { - VectorScale( mAngleDelta, 0.6f, mAngleDelta ); + if (VectorCompare(mOldOrigin, mOrigin1)) { + VectorScale(mAngleDelta, 0.6f, mAngleDelta); } UpdateAngles(); UpdateSize(); -// UpdateRGB(); // had wanted to do something slick whereby an emitted effect could somehow inherit these -// UpdateAlpha(); // values, but it's not a priority right now. + // UpdateRGB(); // had wanted to do something slick whereby an emitted effect could somehow inherit these + // UpdateAlpha(); // values, but it's not a priority right now. Draw(); @@ -1507,13 +1245,12 @@ bool CEmitter::Update() } //---------------------------- -void CEmitter::UpdateAngles() -{ - VectorMA( mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, mAngles ); // was 0.001f, but then you really have to jack up the delta to even notice anything - AnglesToAxis( mAngles, mRefEnt.axis ); +void CEmitter::UpdateAngles() { + VectorMA(mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, + mAngles); // was 0.001f, but then you really have to jack up the delta to even notice anything + AnglesToAxis(mAngles, mRefEnt.axis); } - //-------------------------- // // Derived Light Class @@ -1522,15 +1259,13 @@ void CEmitter::UpdateAngles() //---------------------------- // Update //---------------------------- -bool CLight::Update() -{ +bool CLight::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - //FIXME: Handle Relative and Bolted Effects + // FIXME: Handle Relative and Bolted Effects /* if ( mFlags & FX_RELATIVE ) { @@ -1556,72 +1291,51 @@ bool CLight::Update() //---------------------------- // Update Size //---------------------------- -void CLight::UpdateSize() -{ +void CLight::UpdateSize() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) - / (float)(mTimeEnd - mSizeParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSizeParm - theFxHelper.mTime) - / (float)(mSizeParm - mTimeStart); - } - else - { + perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE_RAND ) - { + if (mFlags & FX_SIZE_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -1632,120 +1346,97 @@ void CLight::UpdateSize() //---------------------------- // Update RGB //---------------------------- -void CLight::UpdateRGB() -{ +void CLight::UpdateRGB() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) - / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) - / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mRGBParm - theFxHelper.mTime) - / (float)(mRGBParm - mTimeStart); - } - else - { + perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_RGB_RAND ) - { + if (mFlags & FX_RGB_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); + VectorScale(mRGBStart, perc1, res); - mRefEnt.lightingOrigin[0] = res[0] + ( 1.0f - perc1 ) * mRGBEnd[0]; - mRefEnt.lightingOrigin[1] = res[1] + ( 1.0f - perc1 ) * mRGBEnd[1]; - mRefEnt.lightingOrigin[2] = res[2] + ( 1.0f - perc1 ) * mRGBEnd[2]; + mRefEnt.lightingOrigin[0] = res[0] + (1.0f - perc1) * mRGBEnd[0]; + mRefEnt.lightingOrigin[1] = res[1] + (1.0f - perc1) * mRGBEnd[1]; + mRefEnt.lightingOrigin[2] = res[2] + (1.0f - perc1) * mRGBEnd[2]; } - //-------------------------- // // Derived Trail Class // //-------------------------- -#define NEW_MUZZLE 0 -#define NEW_TIP 1 -#define OLD_TIP 2 -#define OLD_MUZZLE 3 +#define NEW_MUZZLE 0 +#define NEW_TIP 1 +#define OLD_TIP 2 +#define OLD_MUZZLE 3 //---------------------------- -void CTrail::Draw() -{ - polyVert_t verts[3]; -// vec3_t color; +void CTrail::Draw() { + polyVert_t verts[3]; + // vec3_t color; // build the first tri out of the new muzzle...new tip...old muzzle - VectorCopy( mVerts[NEW_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[2].xyz ); + VectorCopy(mVerts[NEW_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[2].xyz); -// VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[NEW_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[NEW_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[NEW_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[NEW_MUZZLE].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[1].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[1].modulate[2] = mVerts[NEW_TIP].rgb[2]; verts[1].modulate[3] = mVerts[NEW_TIP].alpha; -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[2].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[2].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[2].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; @@ -1759,26 +1450,26 @@ void CTrail::Draw() verts[2].st[1] = mVerts[OLD_MUZZLE].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); // build the second tri out of the old muzzle...old tip...new tip - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[OLD_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[2].xyz ); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[OLD_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[2].xyz); -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[OLD_MUZZLE].alpha; -// VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); + // VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[OLD_TIP].rgb[0]; verts[1].modulate[1] = mVerts[OLD_TIP].rgb[1]; verts[1].modulate[2] = mVerts[OLD_TIP].rgb[2]; verts[0].modulate[3] = mVerts[OLD_TIP].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[2].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[2].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[2].modulate[2] = mVerts[NEW_TIP].rgb[2]; @@ -1792,7 +1483,7 @@ void CTrail::Draw() verts[2].st[1] = mVerts[NEW_TIP].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); drawnFx++; } @@ -1800,15 +1491,13 @@ void CTrail::Draw() //---------------------------- // Update //---------------------------- -bool CTrail::Update() -{ +bool CTrail::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - //FIXME: Handle Relative and Bolted Effects + // FIXME: Handle Relative and Bolted Effects /* if ( mFlags & FX_RELATIVE ) { @@ -1825,22 +1514,20 @@ bool CTrail::Update() */ float perc = (float)(mTimeEnd - theFxHelper.mTime) / (float)(mTimeEnd - mTimeStart); - for ( int t = 0; t < 4; t++ ) - { -// mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); -// if ( mVerts[t].curAlpha < 0.0f ) -// { -// mVerts[t].curAlpha = 0.0f; -// } - -// VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); -// VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); - mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * ( 1.0f - perc ); - if ( mVerts[t].curST[0] > 1.0f ) - { + for (int t = 0; t < 4; t++) { + // mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); + // if ( mVerts[t].curAlpha < 0.0f ) + // { + // mVerts[t].curAlpha = 0.0f; + // } + + // VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); + // VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); + mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * (1.0f - perc); + if (mVerts[t].curST[0] > 1.0f) { mVerts[t].curST[0] = 1.0f; } - mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * ( 1.0f - perc ); + mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * (1.0f - perc); } Draw(); @@ -1848,30 +1535,26 @@ bool CTrail::Update() return true; } - //-------------------------- // // Derived Poly Class // //-------------------------- -bool CPoly::Cull() -{ - vec3_t dir; +bool CPoly::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 24 * 24 ) - { + if (len < 24 * 24) { return true; } @@ -1879,50 +1562,47 @@ bool CPoly::Cull() } //---------------------------- -void CPoly::Draw() -{ - polyVert_t verts[MAX_CPOLY_VERTS]; +void CPoly::Draw() { + polyVert_t verts[MAX_CPOLY_VERTS]; - for ( int i = 0; i < mCount; i++ ) - { + for (int i = 0; i < mCount; i++) { // Add our midpoint and vert offset to get the actual vertex - VectorAdd( mOrigin1, mOrg[i], verts[i].xyz ); + VectorAdd(mOrigin1, mOrg[i], verts[i].xyz); // Assign the same color to each vert - for ( int k=0; k<4; k++ ) + for (int k = 0; k < 4; k++) verts[i].modulate[k] = mRefEnt.shaderRGBA[k]; // Copy the ST coords - VectorCopy2( mST[i], verts[i].st ); + VectorCopy2(mST[i], verts[i].st); } // Add this poly - theFxHelper.AddPolyToScene( mRefEnt.customShader, mCount, verts ); + theFxHelper.AddPolyToScene(mRefEnt.customShader, mCount, verts); drawnFx++; } //---------------------------- -void CPoly::CalcRotateMatrix() -{ - float cosX, cosZ; - float sinX, sinZ; - float rad; +void CPoly::CalcRotateMatrix() { + float cosX, cosZ; + float sinX, sinZ; + float rad; // rotate around Z - rad = DEG2RAD( mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f ); - cosZ = cos( rad ); - sinZ = sin( rad ); + rad = DEG2RAD(mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f); + cosZ = cos(rad); + sinZ = sin(rad); // rotate around X - rad = DEG2RAD( mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f ); - cosX = cos( rad ); - sinX = sin( rad ); - -/*Pitch - aroundx Yaw - around z -1 0 0 c -s 0 -0 c -s s c 0 -0 s c 0 0 1 -*/ + rad = DEG2RAD(mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f); + cosX = cos(rad); + sinX = sin(rad); + + /*Pitch - aroundx Yaw - around z + 1 0 0 c -s 0 + 0 c -s s c 0 + 0 s c 0 0 1 + */ mRot[0][0] = cosZ; mRot[1][0] = -sinZ; mRot[2][0] = 0; @@ -1932,45 +1612,41 @@ void CPoly::CalcRotateMatrix() mRot[0][2] = sinX * sinZ; mRot[1][2] = sinX * cosZ; mRot[2][2] = cosX; -/* -// ROLL is not supported unless anyone complains, if it needs to be added, use this format -Roll + /* + // ROLL is not supported unless anyone complains, if it needs to be added, use this format + Roll - c 0 s - 0 1 0 --s 0 c -*/ + c 0 s + 0 1 0 + -s 0 c + */ mLastFrameTime = theFxHelper.mFrameTime; } //-------------------------------- -void CPoly::Rotate() -{ - vec3_t temp[MAX_CPOLY_VERTS]; - float dif = abs(mLastFrameTime - theFxHelper.mFrameTime); +void CPoly::Rotate() { + vec3_t temp[MAX_CPOLY_VERTS]; + float dif = abs(mLastFrameTime - theFxHelper.mFrameTime); // Very generous check with frameTimes - if ( dif > 0.5f * mLastFrameTime ) - { + if (dif > 0.5f * mLastFrameTime) { CalcRotateMatrix(); } // Multiply our rotation matrix by each of the offset verts to get their new position - for ( int i = 0; i < mCount; i++ ) - { - VectorRotate( mOrg[i], mRot, temp[i] ); - VectorCopy( temp[i], mOrg[i] ); + for (int i = 0; i < mCount; i++) { + VectorRotate(mOrg[i], mRot, temp[i]); + VectorCopy(temp[i], mOrg[i]); } } //---------------------------- // Update //---------------------------- -bool CPoly::Update() -{ - vec3_t mOldOrigin = { 0.0f }; +bool CPoly::Update() { + vec3_t mOldOrigin = {0.0f}; - //FIXME: Handle Relative and Bolted Effects + // FIXME: Handle Relative and Bolted Effects /* if ( mFlags & FX_RELATIVE ) { @@ -1986,31 +1662,25 @@ bool CPoly::Update() } */ // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } // If our timestamp hasn't exired yet, we won't even consider doing any kind of motion - if ( theFxHelper.mTime > mTimeStamp ) - { - VectorCopy( mOrigin1, mOldOrigin ); + if (theFxHelper.mTime > mTimeStamp) { + VectorCopy(mOrigin1, mOldOrigin); - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } } - if ( !Cull() ) - { + if (!Cull()) { // only rotate when our start timestamp has expired - if ( theFxHelper.mTime > mTimeStamp ) - { + if (theFxHelper.mTime > mTimeStamp) { // Only rotate whilst moving - if ( !VectorCompare( mOldOrigin, mOrigin1 )) - { + if (!VectorCompare(mOldOrigin, mOrigin1)) { Rotate(); } } @@ -2025,32 +1695,28 @@ bool CPoly::Update() } //---------------------------- -void CPoly::PolyInit() -{ - if ( mCount < 3 ) - { +void CPoly::PolyInit() { + if (mCount < 3) { return; } - int i; - vec3_t org={0,0,0}; + int i; + vec3_t org = {0, 0, 0}; // Find our midpoint - for ( i = 0; i < mCount; i++ ) - { - VectorAdd( org, mOrg[i], org ); + for (i = 0; i < mCount; i++) { + VectorAdd(org, mOrg[i], org); } - VectorScale( org, (float)(1.0f / mCount), org ); + VectorScale(org, (float)(1.0f / mCount), org); // now store our midpoint for physics purposes - VectorCopy( org, mOrigin1 ); + VectorCopy(org, mOrigin1); // Now we process the passed in points and make it so that they aren't actually the point... // rather, they are the offset from mOrigin1. - for ( i = 0; i < mCount; i++ ) - { - VectorSubtract( mOrg[i], mOrigin1, mOrg[i] ); + for (i = 0; i < mCount; i++) { + VectorSubtract(mOrg[i], mOrigin1, mOrg[i]); } CalcRotateMatrix(); @@ -2064,11 +1730,10 @@ Bezier curve line ------------------------- */ //---------------------------- -bool CBezier::Update( void ) -{ - float ftime, time2; +bool CBezier::Update(void) { + float ftime, time2; - //FIXME: Handle Relative and Bolted Effects + // FIXME: Handle Relative and Bolted Effects /* if ( mFlags & FX_RELATIVE ) { @@ -2086,8 +1751,7 @@ bool CBezier::Update( void ) ftime = cg.frametime * 0.001f; time2 = ftime * ftime * 0.5f; - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { mControl1[i] = mControl1[i] + ftime * mControl1Vel[i] + time2 * mControl1Vel[i]; mControl2[i] = mControl2[i] + ftime * mControl2Vel[i] + time2 * mControl2Vel[i]; } @@ -2102,49 +1766,44 @@ bool CBezier::Update( void ) } //---------------------------- -void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texcoord2 ) -{ - vec3_t lineDir, cross, viewDir; - static vec3_t lastEnd[2]; - polyVert_t verts[4]; - float scale; - - VectorSubtract( end, start, lineDir ); - VectorSubtract( end, cg.refdef.vieworg, viewDir ); - CrossProduct( lineDir, viewDir, cross ); - VectorNormalize( cross ); +void CBezier::DrawSegment(vec3_t start, vec3_t end, float texcoord1, float texcoord2) { + vec3_t lineDir, cross, viewDir; + static vec3_t lastEnd[2]; + polyVert_t verts[4]; + float scale; + + VectorSubtract(end, start, lineDir); + VectorSubtract(end, cg.refdef.vieworg, viewDir); + CrossProduct(lineDir, viewDir, cross); + VectorNormalize(cross); scale = mRefEnt.radius * 0.5f; - //Construct the oriented quad - if ( mInit ) - { - VectorCopy( lastEnd[0], verts[0].xyz ); - VectorCopy( lastEnd[1], verts[1].xyz ); - } - else - { - VectorMA( start, -scale, cross, verts[0].xyz ); - VectorMA( start, scale, cross, verts[1].xyz ); + // Construct the oriented quad + if (mInit) { + VectorCopy(lastEnd[0], verts[0].xyz); + VectorCopy(lastEnd[1], verts[1].xyz); + } else { + VectorMA(start, -scale, cross, verts[0].xyz); + VectorMA(start, scale, cross, verts[1].xyz); } verts[0].st[0] = 0.0f; verts[0].st[1] = texcoord1; - verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[0].modulate[3] = mRefEnt.shaderRGBA[3]; verts[1].st[0] = 1.0f; verts[1].st[1] = texcoord1; - verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[1].modulate[3] = mRefEnt.shaderRGBA[3]; - if ( texcoord1 == 0.0f ) - { + if (texcoord1 == 0.0f) { verts[0].modulate[0] = 0; verts[0].modulate[1] = 0; verts[0].modulate[2] = 0; @@ -2155,83 +1814,80 @@ void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texc verts[1].modulate[3] = 0; } - VectorMA( end, scale, cross, verts[2].xyz ); + VectorMA(end, scale, cross, verts[2].xyz); verts[2].st[0] = 1.0f; verts[2].st[1] = texcoord2; - verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[2].modulate[3] = mRefEnt.shaderRGBA[3]; - VectorMA( end, -scale, cross, verts[3].xyz ); + VectorMA(end, -scale, cross, verts[3].xyz); verts[3].st[0] = 0.0f; verts[3].st[1] = texcoord2; - verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[3].modulate[3] = mRefEnt.shaderRGBA[3]; - cgi_R_AddPolyToScene( mRefEnt.customShader, 4, verts ); + cgi_R_AddPolyToScene(mRefEnt.customShader, 4, verts); - VectorCopy( verts[2].xyz, lastEnd[1] ); - VectorCopy( verts[3].xyz, lastEnd[0] ); + VectorCopy(verts[2].xyz, lastEnd[1]); + VectorCopy(verts[3].xyz, lastEnd[0]); mInit = true; } -const float BEZIER_RESOLUTION = 16.0f; +const float BEZIER_RESOLUTION = 16.0f; //---------------------------- -void CBezier::Draw( void ) -{ - vec3_t pos, old_pos; - float mu, mum1; - float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; - int i; +void CBezier::Draw(void) { + vec3_t pos, old_pos; + float mu, mum1; + float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; + int i; - VectorCopy( mOrigin1, old_pos ); + VectorCopy(mOrigin1, old_pos); - mInit = false; //Signify a new batch for vert gluing + mInit = false; // Signify a new batch for vert gluing // Calculate the texture coords so the texture can stretch along the whole bezier -// if ( mFlags & FXF_WRAP ) -// { -// tex = m_stScale / 1.0f; -// } + // if ( mFlags & FXF_WRAP ) + // { + // tex = m_stScale / 1.0f; + // } float mum13, mu3, group1, group2; tc1 = 0.0f; - for ( mu = incr; mu <= 1.0f; mu += incr ) - { - //Four point curve - mum1 = 1 - mu; - mum13 = mum1 * mum1 * mum1; - mu3 = mu * mu * mu; - group1 = 3 * mu * mum1 * mum1; - group2 = 3 * mu * mu *mum1; - - for ( i = 0; i < 3; i++ ) - { + for (mu = incr; mu <= 1.0f; mu += incr) { + // Four point curve + mum1 = 1 - mu; + mum13 = mum1 * mum1 * mum1; + mu3 = mu * mu * mu; + group1 = 3 * mu * mum1 * mum1; + group2 = 3 * mu * mu * mum1; + + for (i = 0; i < 3; i++) { pos[i] = mum13 * mOrigin1[i] + group1 * mControl1[i] + group2 * mControl2[i] + mu3 * mOrigin2[i]; } -// if ( m_flags & FXF_WRAP ) -// { - tc2 = mu * tex; -// } -// else -// { -// // Texture will get mapped onto each segement -// tc1 = 0.0f; -// tc2 = 1.0f; -// } - - //Draw it - DrawSegment( old_pos, pos, tc1, tc2 ); - - VectorCopy( pos, old_pos ); + // if ( m_flags & FXF_WRAP ) + // { + tc2 = mu * tex; + // } + // else + // { + // // Texture will get mapped onto each segement + // tc1 = 0.0f; + // tc2 = 1.0f; + // } + + // Draw it + DrawSegment(old_pos, pos, tc1, tc2); + + VectorCopy(pos, old_pos); tc1 = tc2; } @@ -2248,8 +1904,7 @@ Full screen flash */ //---------------------------- -bool CFlash::Update( void ) -{ +bool CFlash::Update(void) { UpdateRGB(); Draw(); @@ -2257,48 +1912,39 @@ bool CFlash::Update( void ) } //---------------------------- -void CFlash::Init( void ) -{ - vec3_t dif; - float mod = 1.0f, dis; +void CFlash::Init(void) { + vec3_t dif; + float mod = 1.0f, dis; - VectorSubtract( mOrigin1, cg.refdef.vieworg, dif ); - dis = VectorNormalize( dif ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dif); + dis = VectorNormalize(dif); - mod = DotProduct( dif, cg.refdef.viewaxis[0] ); + mod = DotProduct(dif, cg.refdef.viewaxis[0]); - if ( dis > 600 || ( mod < 0.5f && dis > 100 )) - { + if (dis > 600 || (mod < 0.5f && dis > 100)) { mod = 0.0f; - } - else if ( mod < 0.5f && dis <= 100 ) - { + } else if (mod < 0.5f && dis <= 100) { mod += 1.1f; } mod *= (1.0f - ((dis * dis) / (600.0f * 600.0f))); - VectorScale( mRGBStart, mod, mRGBStart ); - VectorScale( mRGBEnd, mod, mRGBEnd ); + VectorScale(mRGBStart, mod, mRGBStart); + VectorScale(mRGBEnd, mod, mRGBEnd); } //---------------------------- -void CFlash::Draw( void ) -{ - // Interestingly, if znear is set > than this, then the flash - // doesn't appear at all. - const float FLASH_DISTANCE_FROM_VIEWER = 8.0f; +void CFlash::Draw(void) { + // Interestingly, if znear is set > than this, then the flash + // doesn't appear at all. + const float FLASH_DISTANCE_FROM_VIEWER = 8.0f; mRefEnt.reType = RT_SPRITE; - for ( int i = 0; i < 3; i++ ) - { - if ( mRefEnt.lightingOrigin[i] > 1.0f ) - { + for (int i = 0; i < 3; i++) { + if (mRefEnt.lightingOrigin[i] > 1.0f) { mRefEnt.lightingOrigin[i] = 1.0f; - } - else if ( mRefEnt.lightingOrigin[i] < 0.0f ) - { + } else if (mRefEnt.lightingOrigin[i] < 0.0f) { mRefEnt.lightingOrigin[i] = 0.0f; } } @@ -2307,13 +1953,13 @@ void CFlash::Draw( void ) mRefEnt.shaderRGBA[2] = mRefEnt.lightingOrigin[2] * 255; mRefEnt.shaderRGBA[3] = 255; - VectorCopy( cg.refdef.vieworg, mRefEnt.origin ); - VectorMA( mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, cg.refdef.viewaxis[0], mRefEnt.origin ); + VectorCopy(cg.refdef.vieworg, mRefEnt.origin); + VectorMA(mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, cg.refdef.viewaxis[0], mRefEnt.origin); - // This is assuming that the screen is wider than it is tall. - mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan (DEG2RAD (cg.refdef.fov_x * 0.5f)); + // This is assuming that the screen is wider than it is tall. + mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan(DEG2RAD(cg.refdef.fov_x * 0.5f)); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } diff --git a/code/cgame/FxScheduler.cpp b/code/cgame/FxScheduler.cpp index 2b91ef1871..b27ef7055b 100644 --- a/code/cgame/FxScheduler.cpp +++ b/code/cgame/FxScheduler.cpp @@ -22,63 +22,55 @@ along with this program; if not, see . #include "common_headers.h" - #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #if !defined(GHOUL2_SHARED_H_INC) - #include "../game/ghoul2_shared.h" //for CGhoul2Info_v +#include "../game/ghoul2_shared.h" //for CGhoul2Info_v #endif #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif #if !defined(__Q_SHARED_H) - #include "../qcommon/q_shared.h" +#include "../qcommon/q_shared.h" #endif #include "qcommon/safe/string.h" #include #include "qcommon/ojk_saved_game_helper.h" -CFxScheduler theFxScheduler; +CFxScheduler theFxScheduler; // don't even ask,. it's to do with loadsave... // -std::vector < sstring_t > g_vstrEffectsNeededPerSlot; -SLoopedEffect gLoopedEffectArray[MAX_LOOPED_FX]; // must be in sync with CFxScheduler::mLoopedEffectArray -void CFxScheduler::FX_CopeWithAnyLoadedSaveGames(void) -{ - if ( !g_vstrEffectsNeededPerSlot.empty() ) - { - memcpy( mLoopedEffectArray, gLoopedEffectArray, sizeof(mLoopedEffectArray) ); - assert( g_vstrEffectsNeededPerSlot.size() == MAX_LOOPED_FX ); - - for (size_t iFX = 0; iFX < g_vstrEffectsNeededPerSlot.size(); iFX++) - { +std::vector g_vstrEffectsNeededPerSlot; +SLoopedEffect gLoopedEffectArray[MAX_LOOPED_FX]; // must be in sync with CFxScheduler::mLoopedEffectArray +void CFxScheduler::FX_CopeWithAnyLoadedSaveGames(void) { + if (!g_vstrEffectsNeededPerSlot.empty()) { + memcpy(mLoopedEffectArray, gLoopedEffectArray, sizeof(mLoopedEffectArray)); + assert(g_vstrEffectsNeededPerSlot.size() == MAX_LOOPED_FX); + + for (size_t iFX = 0; iFX < g_vstrEffectsNeededPerSlot.size(); iFX++) { const char *psFX_Filename = g_vstrEffectsNeededPerSlot[iFX].c_str(); - if ( psFX_Filename[0] ) - { + if (psFX_Filename[0]) { // register it... // - mLoopedEffectArray[ iFX ].mId = RegisterEffect( psFX_Filename ); + mLoopedEffectArray[iFX].mId = RegisterEffect(psFX_Filename); // // cope with any relative stop time... // - if ( mLoopedEffectArray[ iFX ].mLoopStopTime ) - { - mLoopedEffectArray[ iFX ].mLoopStopTime -= mLoopedEffectArray[ iFX ].mNextTime; + if (mLoopedEffectArray[iFX].mLoopStopTime) { + mLoopedEffectArray[iFX].mLoopStopTime -= mLoopedEffectArray[iFX].mNextTime; } // // and finally reset the time to be the newly-zeroed game time... // - mLoopedEffectArray[ iFX ].mNextTime = 0; // otherwise it won't process until game time catches up - } - else - { - mLoopedEffectArray[ iFX ].mId = 0; + mLoopedEffectArray[iFX].mNextTime = 0; // otherwise it won't process until game time catches up + } else { + mLoopedEffectArray[iFX].mId = 0; } } @@ -86,62 +78,42 @@ void CFxScheduler::FX_CopeWithAnyLoadedSaveGames(void) } } -void FX_CopeWithAnyLoadedSaveGames(void) -{ - theFxScheduler.FX_CopeWithAnyLoadedSaveGames(); -} +void FX_CopeWithAnyLoadedSaveGames(void) { theFxScheduler.FX_CopeWithAnyLoadedSaveGames(); } // for loadsave... // -void FX_Read( void ) -{ - theFxScheduler.LoadSave_Read(); -} +void FX_Read(void) { theFxScheduler.LoadSave_Read(); } // for loadsave... // -void FX_Write( void ) -{ - theFxScheduler.LoadSave_Write(); -} +void FX_Write(void) { theFxScheduler.LoadSave_Write(); } -void CFxScheduler::LoadSave_Read() -{ - Clean(); // need to get rid of old pre-cache handles, or it thinks it has some older effects when it doesn't - g_vstrEffectsNeededPerSlot.clear(); // jic +void CFxScheduler::LoadSave_Read() { + Clean(); // need to get rid of old pre-cache handles, or it thinks it has some older effects when it doesn't + g_vstrEffectsNeededPerSlot.clear(); // jic - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('F', 'X', 'L', 'E'), - ::gLoopedEffectArray); + saved_game.read_chunk(INT_ID('F', 'X', 'L', 'E'), ::gLoopedEffectArray); // // now read in and re-register the effects we need for those structs... // - for (int iFX = 0; iFX < MAX_LOOPED_FX; iFX++) - { + for (int iFX = 0; iFX < MAX_LOOPED_FX; iFX++) { char sFX_Filename[MAX_QPATH]; - saved_game.read_chunk( - INT_ID('F', 'X', 'F', 'N'), - sFX_Filename); + saved_game.read_chunk(INT_ID('F', 'X', 'F', 'N'), sFX_Filename); - g_vstrEffectsNeededPerSlot.push_back( sFX_Filename ); + g_vstrEffectsNeededPerSlot.push_back(sFX_Filename); } } -void CFxScheduler::LoadSave_Write() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void CFxScheduler::LoadSave_Write() { + ojk::SavedGameHelper saved_game(::gi.saved_game); // bsave the data we need... // - saved_game.write_chunk( - INT_ID('F', 'X', 'L', 'E'), - mLoopedEffectArray); + saved_game.write_chunk(INT_ID('F', 'X', 'L', 'E'), mLoopedEffectArray); // // then cope with the fact that the mID field in each struct of the array we've just saved will not @@ -151,22 +123,19 @@ void CFxScheduler::LoadSave_Write() // since this is only for savegames, and I've got < 2 hours to finish this and test it I'm going to be lazy // with the ondisk data... (besides, the RLE compression will kill most of this anyway) // - for (int iFX = 0; iFX < MAX_LOOPED_FX; iFX++) - { + for (int iFX = 0; iFX < MAX_LOOPED_FX; iFX++) { char sFX_Filename[MAX_QPATH]; - memset(sFX_Filename,0,sizeof(sFX_Filename)); // instead of "sFX_Filename[0]=0;" so RLE will squash whole array to nothing, not just stop at '\0' then have old crap after it to compress + memset(sFX_Filename, 0, sizeof(sFX_Filename)); // instead of "sFX_Filename[0]=0;" so RLE will squash whole array to nothing, not just stop at '\0' then + // have old crap after it to compress - int &iID = mLoopedEffectArray[ iFX ].mId; - if ( iID ) - { + int &iID = mLoopedEffectArray[iFX].mId; + if (iID) { // now we need to look up what string this represents, unfortunately the existing // lookup table is backwards (keywise) for our needs, so parse the whole thing... // - for (TEffectID::iterator it = mEffectIDs.begin(); it != mEffectIDs.end(); ++it) - { - if ( (*it).second == iID ) - { - Q_strncpyz( sFX_Filename, (*it).first.c_str(), sizeof(sFX_Filename) ); + for (TEffectID::iterator it = mEffectIDs.begin(); it != mEffectIDs.end(); ++it) { + if ((*it).second == iID) { + Q_strncpyz(sFX_Filename, (*it).first.c_str(), sizeof(sFX_Filename)); break; } } @@ -174,45 +143,34 @@ void CFxScheduler::LoadSave_Write() // write out this string... // - saved_game.write_chunk( - INT_ID('F', 'X', 'F', 'N'), - sFX_Filename); + saved_game.write_chunk(INT_ID('F', 'X', 'F', 'N'), sFX_Filename); } } - //----------------------------------------------------------- -void CMediaHandles::operator=(const CMediaHandles &that ) -{ +void CMediaHandles::operator=(const CMediaHandles &that) { mMediaList.clear(); - for ( size_t i = 0; i < that.mMediaList.size(); i++ ) - { - mMediaList.push_back( that.mMediaList[i] ); + for (size_t i = 0; i < that.mMediaList.size(); i++) { + mMediaList.push_back(that.mMediaList[i]); } } //------------------------------------------------------ -CFxScheduler::CFxScheduler() -{ - memset( &mEffectTemplates, 0, sizeof( mEffectTemplates )); - memset( &mLoopedEffectArray, 0, sizeof( mLoopedEffectArray )); +CFxScheduler::CFxScheduler() { + memset(&mEffectTemplates, 0, sizeof(mEffectTemplates)); + memset(&mLoopedEffectArray, 0, sizeof(mLoopedEffectArray)); } -int CFxScheduler::ScheduleLoopedEffect( int id, int boltInfo, bool isPortal, int iLoopTime, bool isRelative ) -{ +int CFxScheduler::ScheduleLoopedEffect(int id, int boltInfo, bool isPortal, int iLoopTime, bool isRelative) { int i; assert(id); - assert(boltInfo!=-1); + assert(boltInfo != -1); - for (i=0;i> ENTITY_SHIFT ) & ENTITY_AND; - if ( cg_entities[entNum].gent->inuse ) - {// only play the looped effect when the ent is still inUse.... - PlayEffect( mLoopedEffectArray[i].mId, cg_entities[entNum].lerpOrigin, 0, mLoopedEffectArray[i].mBoltInfo, -1, mLoopedEffectArray[i].mPortalEffect, false, mLoopedEffectArray[i].mIsRelative ); //very important to send FALSE looptime to not recursively add me! + for (i = 0; i < MAX_LOOPED_FX; i++) { + if (mLoopedEffectArray[i].mId && mLoopedEffectArray[i].mNextTime < theFxHelper.mTime) { + const int entNum = (mLoopedEffectArray[i].mBoltInfo >> ENTITY_SHIFT) & ENTITY_AND; + if (cg_entities[entNum].gent->inuse) { // only play the looped effect when the ent is still inUse.... + PlayEffect(mLoopedEffectArray[i].mId, cg_entities[entNum].lerpOrigin, 0, mLoopedEffectArray[i].mBoltInfo, -1, + mLoopedEffectArray[i].mPortalEffect, false, + mLoopedEffectArray[i].mIsRelative); // very important to send FALSE looptime to not recursively add me! mLoopedEffectArray[i].mNextTime = theFxHelper.mTime + mEffectTemplates[mLoopedEffectArray[i].mId].mRepeatDelay; - } - else - { - theFxHelper.Print( "CFxScheduler::AddLoopedEffects- entity was removed without stopping any looping fx it owned." ); - memset( &mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i]) ); + } else { + theFxHelper.Print("CFxScheduler::AddLoopedEffects- entity was removed without stopping any looping fx it owned."); + memset(&mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i])); continue; } - if ( mLoopedEffectArray[i].mLoopStopTime && mLoopedEffectArray[i].mLoopStopTime < theFxHelper.mTime ) //time's up - {//kill this entry - memset( &mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i]) ); + if (mLoopedEffectArray[i].mLoopStopTime && mLoopedEffectArray[i].mLoopStopTime < theFxHelper.mTime) // time's up + { // kill this entry + memset(&mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i])); } } } - } //----------------------------------------------------------- -void SEffectTemplate::operator=(const SEffectTemplate &that) -{ +void SEffectTemplate::operator=(const SEffectTemplate &that) { mCopy = true; - strcpy( mEffectName, that.mEffectName ); + strcpy(mEffectName, that.mEffectName); mPrimitiveCount = that.mPrimitiveCount; - for( int i = 0; i < mPrimitiveCount; i++ ) - { + for (int i = 0; i < mPrimitiveCount; i++) { mPrimitives[i] = new CPrimitiveTemplate; *(mPrimitives[i]) = *(that.mPrimitives[i]); // Mark use as a copy so that we know that we should be chucked when used up @@ -336,40 +277,33 @@ void SEffectTemplate::operator=(const SEffectTemplate &that) // None // //------------------------------------------------------ -void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) -{ - int i, j; - TScheduledEffect::iterator itr, next; +void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) { + int i, j; + TScheduledEffect::iterator itr, next; // Ditch any scheduled effects itr = mFxSchedule.begin(); - while ( itr != mFxSchedule.end() ) - { + while (itr != mFxSchedule.end()) { next = itr; ++next; - mScheduledEffectsPool.Free (*itr); + mScheduledEffectsPool.Free(*itr); mFxSchedule.erase(itr); itr = next; } - if (bRemoveTemplates) - { + if (bRemoveTemplates) { // Ditch any effect templates - for ( i = 1; i < FX_MAX_EFFECTS; i++ ) - { - if ( i == idToPreserve) - { + for (i = 1; i < FX_MAX_EFFECTS; i++) { + if (i == idToPreserve) { continue; } - if ( mEffectTemplates[i].mInUse ) - { + if (mEffectTemplates[i].mInUse) { // Ditch the primitives - for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) - { + for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) { delete mEffectTemplates[i].mPrimitives[j]; } } @@ -377,21 +311,16 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= mEffectTemplates[i].mInUse = false; } - if (idToPreserve == 0) - { + if (idToPreserve == 0) { mEffectIDs.clear(); - } - else - { + } else { // Clear the effect names, but first get the name of the effect to preserve, // and restore it after clearing. fxString_t str; TEffectID::iterator iter; - for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) - { - if ((*iter).second == idToPreserve) - { + for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) { + if ((*iter).second == idToPreserve) { str = (*iter).first; break; } @@ -415,80 +344,67 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= // Return: // int handle to the effect //------------------------------------------------------ -int CFxScheduler::RegisterEffect( const char *path, bool bHasCorrectPath /*= false*/ ) -{ +int CFxScheduler::RegisterEffect(const char *path, bool bHasCorrectPath /*= false*/) { // Dealing with file names: // File names can come from two places - the editor, in which case we should use the given // path as is, and the effect file, in which case we should add the correct path and extension. // In either case we create a stripped file name to use for naming effects. // - // FIXME: this could maybe be a cstring_view, if mEffectIDs were to use a transparent comparator, but those were only added in C++14, which we don't support yet (sigh) + // FIXME: this could maybe be a cstring_view, if mEffectIDs were to use a transparent comparator, but those were only added in C++14, which we don't support + // yet (sigh) char filenameNoExt[MAX_QPATH]; // Get an extension stripped version of the file - if (bHasCorrectPath) - { + if (bHasCorrectPath) { // FIXME: this is basically COM_SkipPath, except it also accepts '\\' instead of '/' const char *last = path, *p = path; - while (*p != '\0') - { - if ((*p == '/') || (*p == '\\')) - { + while (*p != '\0') { + if ((*p == '/') || (*p == '\\')) { last = p + 1; } p++; } - COM_StripExtension( last, filenameNoExt, sizeof( filenameNoExt ) ); - } - else - { - COM_StripExtension( path, filenameNoExt, sizeof( filenameNoExt ) ); + COM_StripExtension(last, filenameNoExt, sizeof(filenameNoExt)); + } else { + COM_StripExtension(path, filenameNoExt, sizeof(filenameNoExt)); } // see if the specified file is already registered. If it is, just return the id of that file TEffectID::iterator itr; - itr = mEffectIDs.find( filenameNoExt ); + itr = mEffectIDs.find(filenameNoExt); - if ( itr != mEffectIDs.end() ) - { + if (itr != mEffectIDs.end()) { return (*itr).second; } - char correctFilenameBuffer[MAX_QPATH]; - const char *pfile; - if (bHasCorrectPath) - { + char correctFilenameBuffer[MAX_QPATH]; + const char *pfile; + if (bHasCorrectPath) { pfile = path; - } - else - { + } else { // Add on our extension and prepend the file with the default path - Com_sprintf( correctFilenameBuffer, sizeof( correctFilenameBuffer ), "%s/%s.efx", FX_FILE_PATH, filenameNoExt ); + Com_sprintf(correctFilenameBuffer, sizeof(correctFilenameBuffer), "%s/%s.efx", FX_FILE_PATH, filenameNoExt); pfile = correctFilenameBuffer; } // Let the generic parser process the whole file - CGenericParser2 parser; - if( !parser.Parse( pfile ) ) - { - if( !parser.ValidFile() ) - { - theFxHelper.Print( "RegisterEffect: INVALID file: %s\n", pfile ); + CGenericParser2 parser; + if (!parser.Parse(pfile)) { + if (!parser.ValidFile()) { + theFxHelper.Print("RegisterEffect: INVALID file: %s\n", pfile); } return false; - if( parser.ValidFile() ) - { + if (parser.ValidFile()) { return false; } } // Lets convert the effect file into something that we can work with - return ParseEffect( filenameNoExt, parser.GetBaseParseGroup() ); + return ParseEffect(filenameNoExt, parser.GetBaseParseGroup()); } - //------------------------------------------------------ // ParseEffect // Starts at ground zero, using each group header to @@ -503,59 +419,43 @@ int CFxScheduler::RegisterEffect( const char *path, bool bHasCorrectPath /*= fal // int handle of the effect //------------------------------------------------------ -int CFxScheduler::ParseEffect( const char *file, const CGPGroup& base ) -{ +int CFxScheduler::ParseEffect(const char *file, const CGPGroup &base) { int handle; - SEffectTemplate* effect = GetNewEffectTemplate( &handle, file ); + SEffectTemplate *effect = GetNewEffectTemplate(&handle, file); - if ( !handle || !effect ) - { + if (!handle || !effect) { // failure return 0; } - for( auto& property : base.GetProperties() ) - { - if( Q::stricmp( property.GetName(), CSTRING_VIEW( "repeatDelay" ) ) == Q::Ordering::EQ ) - { - effect->mRepeatDelay = Q::svtoi( property.GetTopValue() ); + for (auto &property : base.GetProperties()) { + if (Q::stricmp(property.GetName(), CSTRING_VIEW("repeatDelay")) == Q::Ordering::EQ) { + effect->mRepeatDelay = Q::svtoi(property.GetTopValue()); } } - for( const auto& primitiveGroup : base.GetSubGroups() ) - { - static std::map< gsl::cstring_span, EPrimType, Q::CStringViewILess > primitiveTypes{ - { CSTRING_VIEW( "particle" ), Particle }, - { CSTRING_VIEW( "line" ), Line }, - { CSTRING_VIEW( "tail" ), Tail }, - { CSTRING_VIEW( "sound" ), Sound }, - { CSTRING_VIEW( "cylinder" ), Cylinder }, - { CSTRING_VIEW( "electricity" ), Electricity }, - { CSTRING_VIEW( "emitter" ), Emitter }, - { CSTRING_VIEW( "decal" ), Decal }, - { CSTRING_VIEW( "orientedparticle" ), OrientedParticle }, - { CSTRING_VIEW( "fxrunner" ), FxRunner }, - { CSTRING_VIEW( "light" ), Light }, - { CSTRING_VIEW( "cameraShake" ), CameraShake }, - { CSTRING_VIEW( "flash" ), ScreenFlash } - }; - auto pos = primitiveTypes.find( primitiveGroup.GetName() ); - if( pos != primitiveTypes.end() ) - { + for (const auto &primitiveGroup : base.GetSubGroups()) { + static std::map primitiveTypes{ + {CSTRING_VIEW("particle"), Particle}, {CSTRING_VIEW("line"), Line}, {CSTRING_VIEW("tail"), Tail}, + {CSTRING_VIEW("sound"), Sound}, {CSTRING_VIEW("cylinder"), Cylinder}, {CSTRING_VIEW("electricity"), Electricity}, + {CSTRING_VIEW("emitter"), Emitter}, {CSTRING_VIEW("decal"), Decal}, {CSTRING_VIEW("orientedparticle"), OrientedParticle}, + {CSTRING_VIEW("fxrunner"), FxRunner}, {CSTRING_VIEW("light"), Light}, {CSTRING_VIEW("cameraShake"), CameraShake}, + {CSTRING_VIEW("flash"), ScreenFlash}}; + auto pos = primitiveTypes.find(primitiveGroup.GetName()); + if (pos != primitiveTypes.end()) { CPrimitiveTemplate *prim = new CPrimitiveTemplate; prim->mType = pos->second; - prim->ParsePrimitive( primitiveGroup ); + prim->ParsePrimitive(primitiveGroup); // Add our primitive template to the effect list - AddPrimitiveToEffect( effect, prim ); + AddPrimitiveToEffect(effect, prim); } } return handle; } - //------------------------------------------------------ // AddPrimitiveToEffect // Takes a primitive and attaches it to the effect. @@ -567,16 +467,12 @@ int CFxScheduler::ParseEffect( const char *file, const CGPGroup& base ) // Return: // None //------------------------------------------------------ -void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate *prim ) -{ +void CFxScheduler::AddPrimitiveToEffect(SEffectTemplate *fx, CPrimitiveTemplate *prim) { int ct = fx->mPrimitiveCount; - if ( ct >= FX_MAX_EFFECT_COMPONENTS ) - { - theFxHelper.Print( "FxScheduler: Error--too many primitives in an effect\n" ); - } - else - { + if (ct >= FX_MAX_EFFECT_COMPONENTS) { + theFxHelper.Print("FxScheduler: Error--too many primitives in an effect\n"); + } else { fx->mPrimitives[ct] = prim; fx->mPrimitiveCount++; } @@ -594,25 +490,21 @@ void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate // Return: // the id of the added effect template //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) -{ +SEffectTemplate *CFxScheduler::GetNewEffectTemplate(int *id, const char *file) { SEffectTemplate *effect; // wanted zero to be a bogus effect ID, so we just skip it. - for ( int i = 1; i < FX_MAX_EFFECTS; i++ ) - { + for (int i = 1; i < FX_MAX_EFFECTS; i++) { effect = &mEffectTemplates[i]; - if ( !effect->mInUse ) - { + if (!effect->mInUse) { *id = i; - memset( effect, 0, sizeof( SEffectTemplate )); + memset(effect, 0, sizeof(SEffectTemplate)); // If we are a copy, we really won't have a name that we care about saving for later - if ( file ) - { + if (file) { mEffectIDs[file] = i; - strcpy( effect->mEffectName, file ); + strcpy(effect->mEffectName, file); } effect->mInUse = true; @@ -621,7 +513,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) } } - theFxHelper.Print( "FxScheduler: Error--reached max effects\n" ); + theFxHelper.Print("FxScheduler: Error--reached max effects\n"); *id = 0; return nullptr; } @@ -639,10 +531,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) -{ - return ( GetEffectCopy( mEffectIDs[file], newHandle ) ); -} +SEffectTemplate *CFxScheduler::GetEffectCopy(const char *file, int *newHandle) { return (GetEffectCopy(mEffectIDs[file], newHandle)); } //------------------------------------------------------ // GetEffectCopy @@ -657,28 +546,24 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) -{ - if ( fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS || !mEffectTemplates[fxHandle].mInUse ) - { +SEffectTemplate *CFxScheduler::GetEffectCopy(int fxHandle, int *newHandle) { + if (fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS || !mEffectTemplates[fxHandle].mInUse) { // Didn't even request a valid effect to copy!!! - theFxHelper.Print( "FxScheduler: Bad effect file copy request\n" ); + theFxHelper.Print("FxScheduler: Bad effect file copy request\n"); *newHandle = 0; return 0; } // never get a copy when time is frozen - if ( fx_freeze.integer ) - { + if (fx_freeze.integer) { return 0; } // Copies shouldn't have names, otherwise they could trash our stl map used for getting ID from name - SEffectTemplate *copy = GetNewEffectTemplate( newHandle, NULL ); + SEffectTemplate *copy = GetNewEffectTemplate(newHandle, NULL); - if ( copy && *newHandle ) - { + if (copy && *newHandle) { // do the effect copy and mark us as what we are *copy = mEffectTemplates[fxHandle]; copy->mCopy = true; @@ -703,17 +588,13 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) // Return: // the pointer to the desired primitive //------------------------------------------------------ -CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, const char *componentName ) -{ - if ( !effectCopy || !effectCopy->mInUse ) - { +CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy(SEffectTemplate *effectCopy, const char *componentName) { + if (!effectCopy || !effectCopy->mInUse) { return NULL; } - for ( int i = 0; i < effectCopy->mPrimitiveCount; i++ ) - { - if ( !Q_stricmp( effectCopy->mPrimitives[i]->mName, componentName )) - { + for (int i = 0; i < effectCopy->mPrimitiveCount; i++) { + if (!Q_stricmp(effectCopy->mPrimitives[i]->mName, componentName)) { // we found a match, so return it return effectCopy->mPrimitives[i]; } @@ -724,14 +605,12 @@ CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, } //------------------------------------------------------ -static void ReportPlayEffectError(int id) -{ +static void ReportPlayEffectError(int id) { #ifdef _DEBUG - theFxHelper.Print( "CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id ); + theFxHelper.Print("CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id); #endif } - //------------------------------------------------------ // PlayEffect // Handles scheduling an effect so all the components @@ -744,15 +623,14 @@ static void ReportPlayEffectError(int id) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, bool isPortal ) -{ - vec3_t axis[3]; +void CFxScheduler::PlayEffect(int id, vec3_t origin, bool isPortal) { + vec3_t axis[3]; - VectorSet( axis[0], 0, 0, 1 ); - VectorSet( axis[1], 1, 0, 0 ); - VectorSet( axis[2], 0, 1, 0 ); + VectorSet(axis[0], 0, 0, 1); + VectorSet(axis[1], 1, 0, 0); + VectorSet(axis[2], 0, 1, 0); - PlayEffect( id, origin, axis, -1, -1, isPortal ); + PlayEffect(id, origin, axis, -1, -1, isPortal); } //------------------------------------------------------ @@ -767,15 +645,14 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, bool isPortal ) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward, bool isPortal ) -{ - vec3_t axis[3]; +void CFxScheduler::PlayEffect(int id, vec3_t origin, vec3_t forward, bool isPortal) { + vec3_t axis[3]; // Take the forward vector and create two arbitrary but perpendicular vectors - VectorCopy( forward, axis[0] ); - MakeNormalVectors( forward, axis[1], axis[2] ); + VectorCopy(forward, axis[0]); + MakeNormalVectors(forward, axis[1], axis[2]); - PlayEffect( id, origin, axis, -1, -1, isPortal ); + PlayEffect(id, origin, axis, -1, -1, isPortal); } //------------------------------------------------------ @@ -791,29 +668,27 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward, bool isPor // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum, bool isPortal, int iLoopTime, bool isRelative ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum, bool isPortal, int iLoopTime, + bool isRelative) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); // This is a horribly dumb thing to have to do, but QuakeIII might not have calc'd the lerpOrigin // for the entity we may be trying to bolt onto. We like having the correct origin, so we are // forced to call this function.... - if ( entNum > -1 ) - { - CG_CalcEntityLerpPositions( &cg_entities[entNum] ); + if (entNum > -1) { + CG_CalcEntityLerpPositions(&cg_entities[entNum]); } #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile); } #endif - PlayEffect( mEffectIDs[sfile], origin, axis, boltInfo, entNum, isPortal, iLoopTime, isRelative ); + PlayEffect(mEffectIDs[sfile], origin, axis, boltInfo, entNum, isPortal, iLoopTime, isRelative); } //------------------------------------------------------ @@ -829,30 +704,27 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t axis[3], // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, int clientID, bool isPortal ) -{ - char sfile[MAX_QPATH]; - int id; +void CFxScheduler::PlayEffect(const char *file, int clientID, bool isPortal) { + char sfile[MAX_QPATH]; + int id; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); id = mEffectIDs[sfile]; #ifndef FINAL_BUILD - if ( id == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (id == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif - SEffectTemplate *fx; - CPrimitiveTemplate *prim; - int i = 0; - int count = 0, delay = 0; - float factor = 0.0f; + SEffectTemplate *fx; + CPrimitiveTemplate *prim; + int i = 0; + int count = 0, delay = 0; + float factor = 0.0f; - if ( id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse ) - { + if (id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse) { // Now you've done it! ReportPlayEffectError(id); return; @@ -864,78 +736,63 @@ void CFxScheduler::PlayEffect( const char *file, int clientID, bool isPortal ) fx = &mEffectTemplates[id]; // Loop through the primitives and schedule each bit - for ( i = 0; i < fx->mPrimitiveCount; i++ ) - { + for (i = 0; i < fx->mPrimitiveCount; i++) { prim = fx->mPrimitives[i]; count = prim->mSpawnCount.GetRoundedVal(); - if ( prim->mCopy ) - { + if (prim->mCopy) { // If we are a copy, we need to store a "how many references count" so that we // can keep the primitive template around for the correct amount of time. prim->mRefCount = count; } - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { factor = abs(prim->mSpawnDelay.GetMax() - prim->mSpawnDelay.GetMin()) / (float)count; } // Schedule the random number of bits - for ( int t = 0; t < count; t++ ) - { - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + for (int t = 0; t < count; t++) { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { delay = t * factor; - } - else - { + } else { delay = prim->mSpawnDelay.GetVal(); } // if the delay is so small, we may as well just create this bit right now - if ( delay < 1 && !isPortal ) - { - CreateEffect( prim, clientID, -delay ); - } - else - { - SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); + if (delay < 1 && !isPortal) { + CreateEffect(prim, clientID, -delay); + } else { + SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); - if ( sfx == NULL ) - { - Com_Error (ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); + if (sfx == NULL) { + Com_Error(ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); return; } sfx->mStartTime = theFxHelper.mTime + delay; sfx->mpTemplate = prim; - sfx->mClientID = clientID; + sfx->mClientID = clientID; - if (isPortal) - { + if (isPortal) { sfx->mPortalEffect = true; - } - else - { + } else { sfx->mPortalEffect = false; } - mFxSchedule.push_front( sfx ); + mFxSchedule.push_front(sfx); } } } // We track effect templates and primitive templates separately. - if ( fx->mCopy ) - { + if (fx->mCopy) { // We don't use dynamic memory allocation, so just mark us as dead fx->mInUse = false; } } -bool gEffectsInPortal = false; //this is just because I don't want to have to add an mPortalEffect field to every actual effect. +bool gEffectsInPortal = false; // this is just because I don't want to have to add an mPortalEffect field to every actual effect. //------------------------------------------------------ // CreateEffect @@ -950,136 +807,111 @@ bool gEffectsInPortal = false; //this is just because I don't want to have to ad // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay ) -{ - vec3_t sRGB, eRGB; - vec3_t vel, accel; - vec3_t org,org2; - int flags = 0; +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, int clientID, int delay) { + vec3_t sRGB, eRGB; + vec3_t vel, accel; + vec3_t org, org2; + int flags = 0; // Origin calculations -- completely ignores most things //------------------------------------- - VectorSet( org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal() ); - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); + VectorSet(org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal()); + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); // handle RGB color - if ( fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP ) - { + if (fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP) { float perc = Q_flrand(0.0f, 1.0f); - VectorSet( sRGB, fx->mRedStart.GetVal( perc ), fx->mGreenStart.GetVal( perc ), fx->mBlueStart.GetVal( perc ) ); - VectorSet( eRGB, fx->mRedEnd.GetVal( perc ), fx->mGreenEnd.GetVal( perc ), fx->mBlueEnd.GetVal( perc ) ); - } - else - { - VectorSet( sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal() ); - VectorSet( eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal() ); + VectorSet(sRGB, fx->mRedStart.GetVal(perc), fx->mGreenStart.GetVal(perc), fx->mBlueStart.GetVal(perc)); + VectorSet(eRGB, fx->mRedEnd.GetVal(perc), fx->mGreenEnd.GetVal(perc), fx->mBlueEnd.GetVal(perc)); + } else { + VectorSet(sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal()); + VectorSet(eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal()); } // NOTE: This completely disregards a few specialty flags. - VectorSet( vel, fx->mVelX.GetVal( ), fx->mVelY.GetVal( ), fx->mVelZ.GetVal( ) ); - VectorSet( accel, fx->mAccelX.GetVal( ), fx->mAccelY.GetVal( ), fx->mAccelZ.GetVal( ) ); + VectorSet(vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal()); + VectorSet(accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal()); // If depth hack ISN'T already on, then turn it on. Otherwise, we treat a pre-existing depth_hack flag as NOT being depth_hack. // This is done because muzzle flash fx files are shared amongst all shooters, but for the player we need to do depth hack in first person.... - if ( !( fx->mFlags & FX_DEPTH_HACK ) && !cg.renderingThirdPerson ) // hack! + if (!(fx->mFlags & FX_DEPTH_HACK) && !cg.renderingThirdPerson) // hack! { flags = fx->mFlags | FX_RELATIVE | FX_DEPTH_HACK; - } - else - { + } else { flags = (fx->mFlags | FX_RELATIVE) & ~FX_DEPTH_HACK; } // We only support particles for now //------------------------ - switch( fx->mType ) - { + switch (fx->mType) { //--------- case Particle: - //--------- + //--------- - FX_AddParticle( clientID, org, vel, accel, fx->mGravity.GetVal(), - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags ); + FX_AddParticle(clientID, org, vel, accel, fx->mGravity.GetVal(), fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), + fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), + fx->mRotationDelta.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags); break; //--------- case Line: - //--------- + //--------- - FX_AddLine( clientID, org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), flags ); + FX_AddLine(clientID, org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), flags); break; //--------- case Tail: - //--------- + //--------- - FX_AddTail( clientID, org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags ); + FX_AddTail(clientID, org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mLengthStart.GetVal(), + fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, + fx->mRGBParm.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), + fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags); break; - //--------- case Sound: - //--------- + //--------- - if (gEffectsInPortal) - { //could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so just make it a local sound. - theFxHelper.PlayLocalSound( fx->mMediaHandles.GetHandle(), CHAN_AUTO ); - } - else - { + if (gEffectsInPortal) { // could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so + // just make it a local sound. + theFxHelper.PlayLocalSound(fx->mMediaHandles.GetHandle(), CHAN_AUTO); + } else { // bolted sounds actually play on the client.... - theFxHelper.PlaySound( NULL, clientID, CHAN_WEAPON, fx->mMediaHandles.GetHandle() ); + theFxHelper.PlaySound(NULL, clientID, CHAN_WEAPON, fx->mMediaHandles.GetHandle()); } break; //--------- case Light: - //--------- + //--------- // don't much care if the light stays bolted...so just add it. - if ( clientID >= 0 && clientID < ENTITYNUM_WORLD ) - { + if (clientID >= 0 && clientID < ENTITYNUM_WORLD) { // ..um, ok..... centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - FX_AddLight( cent->gent->client->renderInfo.muzzlePoint, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mFlags ); + if (cent && cent->gent && cent->gent->client) { + FX_AddLight(cent->gent->client->renderInfo.muzzlePoint, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), sRGB, eRGB, + fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mFlags); } } break; //--------- case CameraShake: - //--------- + //--------- - if ( clientID >= 0 && clientID < ENTITYNUM_WORLD ) - { + if (clientID >= 0 && clientID < ENTITYNUM_WORLD) { // ..um, ok..... centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - theFxHelper.CameraShake( cent->gent->currentOrigin, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal() ); + if (cent && cent->gent && cent->gent->client) { + theFxHelper.CameraShake(cent->gent->currentOrigin, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal()); } } break; @@ -1089,12 +921,10 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay } // Track when we need to clean ourselves up if we are a copy - if ( fx->mCopy ) - { + if (fx->mCopy) { fx->mRefCount--; - if ( fx->mRefCount <= 0 ) - { + if (fx->mRefCount <= 0) { delete fx; } } @@ -1113,59 +943,52 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum, bool isPortal, int iLoopTime, bool isRelative ) -{ - SEffectTemplate *fx; - CPrimitiveTemplate *prim; - int i = 0; - int count = 0, delay = 0; - float factor = 0.0f; - bool forceScheduling = false; - - if ( id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse ) - { +void CFxScheduler::PlayEffect(int id, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum, bool isPortal, int iLoopTime, bool isRelative) { + SEffectTemplate *fx; + CPrimitiveTemplate *prim; + int i = 0; + int count = 0, delay = 0; + float factor = 0.0f; + bool forceScheduling = false; + + if (id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse) { // Now you've done it! ReportPlayEffectError(id); return; } // Don't bother scheduling the effect if the system is currently frozen - if ( fx_freeze.integer ) - { + if (fx_freeze.integer) { return; } - int modelNum = 0, boltNum = -1; - int entityNum = entNum; + int modelNum = 0, boltNum = -1; + int entityNum = entNum; - if ( boltInfo > 0 ) - { + if (boltInfo > 0) { // extract the wraith ID from the bolt info - modelNum = ( boltInfo >> MODEL_SHIFT ) & MODEL_AND; - boltNum = ( boltInfo >> BOLT_SHIFT ) & BOLT_AND; - entityNum = ( boltInfo >> ENTITY_SHIFT ) & ENTITY_AND; + modelNum = (boltInfo >> MODEL_SHIFT) & MODEL_AND; + boltNum = (boltInfo >> BOLT_SHIFT) & BOLT_AND; + entityNum = (boltInfo >> ENTITY_SHIFT) & ENTITY_AND; // We always force ghoul bolted objects to be scheduled so that they don't play right away. forceScheduling = true; - if (iLoopTime)//0 = not looping, 1 for infinite, else duration - {//store off the id to reschedule every frame + if (iLoopTime) // 0 = not looping, 1 for infinite, else duration + { // store off the id to reschedule every frame ScheduleLoopedEffect(id, boltInfo, isPortal, iLoopTime, isRelative); } } - // Get the effect. fx = &mEffectTemplates[id]; // Loop through the primitives and schedule each bit - for ( i = 0; i < fx->mPrimitiveCount; i++ ) - { + for (i = 0; i < fx->mPrimitiveCount; i++) { prim = fx->mPrimitives[i]; - if ( prim->mCullRange ) - { - if ( DistanceSquared( origin, cg.refdef.vieworg ) > prim->mCullRange ) // cull range has already been squared + if (prim->mCullRange) { + if (DistanceSquared(origin, cg.refdef.vieworg) > prim->mCullRange) // cull range has already been squared { // is too far away, so don't add this primitive group continue; @@ -1174,50 +997,37 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int count = prim->mSpawnCount.GetRoundedVal(); - if ( prim->mCopy ) - { + if (prim->mCopy) { // If we are a copy, we need to store a "how many references count" so that we // can keep the primitive template around for the correct amount of time. prim->mRefCount = count; } - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { factor = abs(prim->mSpawnDelay.GetMax() - prim->mSpawnDelay.GetMin()) / (float)count; } // Schedule the random number of bits - for ( int t = 0; t < count; t++ ) - { - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + for (int t = 0; t < count; t++) { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { delay = t * factor; - } - else - { + } else { delay = prim->mSpawnDelay.GetVal(); } // if the delay is so small, we may as well just create this bit right now - if ( delay < 1 && !forceScheduling && !isPortal ) - { - if ( boltInfo == -1 && entNum != -1 ) - { + if (delay < 1 && !forceScheduling && !isPortal) { + if (boltInfo == -1 && entNum != -1) { // Find out where the entity currently is - CreateEffect( prim, cg_entities[entNum].lerpOrigin, axis, -delay ); + CreateEffect(prim, cg_entities[entNum].lerpOrigin, axis, -delay); + } else { + CreateEffect(prim, origin, axis, -delay); } - else - { - CreateEffect( prim, origin, axis, -delay ); - } - } - else - { - SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); + } else { + SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); - if ( sfx == NULL ) - { - Com_Error (ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); + if (sfx == NULL) { + Com_Error(ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); return; } @@ -1225,40 +1035,31 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int sfx->mpTemplate = prim; sfx->mClientID = -1; sfx->mIsRelative = isRelative; - sfx->mEntNum = entityNum; //ent if bolted, else -1 for none, or -2 for _Immersion client 0 + sfx->mEntNum = entityNum; // ent if bolted, else -1 for none, or -2 for _Immersion client 0 sfx->mPortalEffect = isPortal; - if ( boltInfo == -1 ) - { - if ( entNum == -1 ) - { + if (boltInfo == -1) { + if (entNum == -1) { // we aren't bolting, so make sure the spawn system knows this by putting -1's in these fields sfx->mBoltNum = -1; sfx->mModelNum = 0; - if ( origin ) - { - VectorCopy( origin, sfx->mOrigin ); - } - else - { - VectorClear( sfx->mOrigin ); + if (origin) { + VectorCopy(origin, sfx->mOrigin); + } else { + VectorClear(sfx->mOrigin); } - AxisCopy( axis, sfx->mAxis ); - } - else - { + AxisCopy(axis, sfx->mAxis); + } else { // we are doing bolting onto the origin of the entity, so use a cheaper method sfx->mBoltNum = -1; sfx->mModelNum = 0; - AxisCopy( axis, sfx->mAxis ); + AxisCopy(axis, sfx->mAxis); } - } - else - { + } else { // we are bolting, so store the extra info sfx->mBoltNum = boltNum; sfx->mModelNum = modelNum; @@ -1267,14 +1068,13 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int sfx->mStartTime++; } - mFxSchedule.push_front( sfx ); + mFxSchedule.push_front(sfx); } } } // We track effect templates and primitive templates separately. - if ( fx->mCopy ) - { + if (fx->mCopy) { // We don't use dynamic memory allocation, so just mark us as dead fx->mInUse = false; } @@ -1292,19 +1092,17 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, bool isPortal ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, bool isPortal) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); - PlayEffect( mEffectIDs[sfile], origin, isPortal ); + PlayEffect(mEffectIDs[sfile], origin, isPortal); #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif } @@ -1321,19 +1119,17 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, bool isPortal ) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward, bool isPortal ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, vec3_t forward, bool isPortal) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); - PlayEffect( mEffectIDs[sfile], origin, forward, isPortal ); + PlayEffect(mEffectIDs[sfile], origin, forward, isPortal); #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif } @@ -1350,62 +1146,40 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward, // Return: // none //------------------------------------------------------ -void CFxScheduler::AddScheduledEffects( bool portal ) -{ - TScheduledEffect::iterator itr, next; - vec3_t origin; - vec3_t axis[3]; - int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; - qboolean doesBoltExist = qfalse; - - if (portal) - { +void CFxScheduler::AddScheduledEffects(bool portal) { + TScheduledEffect::iterator itr, next; + vec3_t origin; + vec3_t axis[3]; + int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; + qboolean doesBoltExist = qfalse; + + if (portal) { gEffectsInPortal = true; - } - else - { + } else { AddLoopedEffects(); } - for ( itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */ ) - { + for (itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */) { SScheduledEffect *effect = *itr; - if (portal == effect->mPortalEffect && effect->mStartTime <= theFxHelper.mTime ) - { - if ( effect->mClientID >= 0 ) - { - CreateEffect( effect->mpTemplate, effect->mClientID, - theFxHelper.mTime - effect->mStartTime ); - } - else if (effect->mBoltNum == -1) - {// normal effect - if ( effect->mEntNum != -1 ) // -1 + if (portal == effect->mPortalEffect && effect->mStartTime <= theFxHelper.mTime) { + if (effect->mClientID >= 0) { + CreateEffect(effect->mpTemplate, effect->mClientID, theFxHelper.mTime - effect->mStartTime); + } else if (effect->mBoltNum == -1) { // normal effect + if (effect->mEntNum != -1) // -1 { // Find out where the entity currently is - CreateEffect( effect->mpTemplate, - cg_entities[effect->mEntNum].lerpOrigin, effect->mAxis, - theFxHelper.mTime - (*itr)->mStartTime ); - } - else - { - CreateEffect( effect->mpTemplate, - effect->mOrigin, effect->mAxis, - theFxHelper.mTime - effect->mStartTime ); + CreateEffect(effect->mpTemplate, cg_entities[effect->mEntNum].lerpOrigin, effect->mAxis, theFxHelper.mTime - (*itr)->mStartTime); + } else { + CreateEffect(effect->mpTemplate, effect->mOrigin, effect->mAxis, theFxHelper.mTime - effect->mStartTime); } - } - else - { //bolted on effect + } else { // bolted on effect // do we need to go and re-get the bolt matrix again? Since it takes time lets try to do it only once - if ((effect->mModelNum != oldModelNum) || (effect->mEntNum != oldEntNum) || (effect->mBoltNum != oldBoltIndex)) - { + if ((effect->mModelNum != oldModelNum) || (effect->mEntNum != oldEntNum) || (effect->mBoltNum != oldBoltIndex)) { const centity_t ¢ = cg_entities[effect->mEntNum]; - if (cent.gent->ghoul2.IsValid()) - { - if (effect->mModelNum>=0&&effect->mModelNumghoul2.size()) - { - if (cent.gent->ghoul2[effect->mModelNum].mModelindex>=0) - { + if (cent.gent->ghoul2.IsValid()) { + if (effect->mModelNum >= 0 && effect->mModelNum < cent.gent->ghoul2.size()) { + if (cent.gent->ghoul2[effect->mModelNum].mModelindex >= 0) { doesBoltExist = (qboolean)(theFxHelper.GetOriginAxisFromBolt(cent, effect->mModelNum, effect->mBoltNum, origin, axis) != 0); } } @@ -1417,28 +1191,18 @@ void CFxScheduler::AddScheduledEffects( bool portal ) } // only do this if we found the bolt - if (doesBoltExist) - { - if (effect->mIsRelative ) - { - CreateEffect( effect->mpTemplate, - vec3_origin, axis, - 0, effect->mEntNum, effect->mModelNum, effect->mBoltNum ); - } - else - { - CreateEffect( effect->mpTemplate, - origin, axis, - theFxHelper.mTime - effect->mStartTime ); + if (doesBoltExist) { + if (effect->mIsRelative) { + CreateEffect(effect->mpTemplate, vec3_origin, axis, 0, effect->mEntNum, effect->mModelNum, effect->mBoltNum); + } else { + CreateEffect(effect->mpTemplate, origin, axis, theFxHelper.mTime - effect->mStartTime); } } } - mScheduledEffectsPool.Free( effect ); - itr = mFxSchedule.erase( itr ); - } - else - { + mScheduledEffectsPool.Free(effect); + itr = mFxSchedule.erase(itr); + } else { ++itr; } } @@ -1462,129 +1226,105 @@ void CFxScheduler::AddScheduledEffects( bool portal ) // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, vec3_t axis[3], int lateTime, int clientID, int modelNum, int boltNum ) -{ - vec3_t org, org2, temp, - vel, accel, - sRGB, eRGB, - ang, angDelta, - ax[3]; - trace_t tr; - int emitterModel; +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, const vec3_t origin, vec3_t axis[3], int lateTime, int clientID, int modelNum, int boltNum) { + vec3_t org, org2, temp, vel, accel, sRGB, eRGB, ang, angDelta, ax[3]; + trace_t tr; + int emitterModel; // We may modify the axis, so make a work copy - AxisCopy( axis, ax ); + AxisCopy(axis, ax); int flags = fx->mFlags; - if (clientID>=0 && modelNum>=0 && boltNum>=0) - {//since you passed in these values, mark as relative to use them + if (clientID >= 0 && modelNum >= 0 && boltNum >= 0) { // since you passed in these values, mark as relative to use them flags |= FX_RELATIVE; } - if( fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD ) - { - RotatePointAroundVector( ax[1], ax[0], axis[1], Q_flrand(0.0f, 1.0f)*360.0f ); - CrossProduct( ax[0], ax[1], ax[2] ); + if (fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD) { + RotatePointAroundVector(ax[1], ax[0], axis[1], Q_flrand(0.0f, 1.0f) * 360.0f); + CrossProduct(ax[0], ax[1], ax[2]); } // Origin calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_CHEAP_ORG_CALC || flags & FX_RELATIVE ) - { // let's take the easy way out - VectorSet( org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal() ); - } - else - { // time for some extra work - VectorScale( ax[0], fx->mOrigin1X.GetVal(), org ); - VectorMA( org, fx->mOrigin1Y.GetVal(), ax[1], org ); - VectorMA( org, fx->mOrigin1Z.GetVal(), ax[2], org ); + if (fx->mSpawnFlags & FX_CHEAP_ORG_CALC || flags & FX_RELATIVE) { // let's take the easy way out + VectorSet(org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal()); + } else { // time for some extra work + VectorScale(ax[0], fx->mOrigin1X.GetVal(), org); + VectorMA(org, fx->mOrigin1Y.GetVal(), ax[1], org); + VectorMA(org, fx->mOrigin1Z.GetVal(), ax[2], org); } // We always add our calculated offset to the passed in origin... - VectorAdd( org, origin, org ); + VectorAdd(org, origin, org); // Now, we may need to calc a point on a sphere/ellipsoid/cylinder/disk and add that to it //---------------------------------------------------------------- - if ( fx->mSpawnFlags & FX_ORG_ON_SPHERE ) - { + if (fx->mSpawnFlags & FX_ORG_ON_SPHERE) { float x, y; float width, height; - x = DEG2RAD( Q_flrand(0.0f, 1.0f) * 360.0f ); - y = DEG2RAD( Q_flrand(0.0f, 1.0f) * 180.0f ); + x = DEG2RAD(Q_flrand(0.0f, 1.0f) * 360.0f); + y = DEG2RAD(Q_flrand(0.0f, 1.0f) * 180.0f); width = fx->mRadius.GetVal(); height = fx->mHeight.GetVal(); // calculate point on ellipse - VectorSet( temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height ); // sinx * siny, cosx * siny, cosy - VectorAdd( org, temp, org ); + VectorSet(temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height); // sinx * siny, cosx * siny, cosy + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); - MakeNormalVectors( ax[0], ax[1], ax[2] ); + VectorNormalize2(temp, ax[0]); + MakeNormalVectors(ax[0], ax[1], ax[2]); } - } - else if ( fx->mSpawnFlags & FX_ORG_ON_CYLINDER ) - { - vec3_t pt; + } else if (fx->mSpawnFlags & FX_ORG_ON_CYLINDER) { + vec3_t pt; // set up our point, then rotate around the current direction to. Make unrotated cylinder centered around 0,0,0 - VectorScale( ax[1], fx->mRadius.GetVal(), pt ); - VectorMA( pt, Q_flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt ); - RotatePointAroundVector( temp, ax[0], pt, Q_flrand(0.0f, 1.0f) * 360.0f ); + VectorScale(ax[1], fx->mRadius.GetVal(), pt); + VectorMA(pt, Q_flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt); + RotatePointAroundVector(temp, ax[0], pt, Q_flrand(0.0f, 1.0f) * 360.0f); - VectorAdd( org, temp, org ); + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { - vec3_t up={0,0,1}; + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { + vec3_t up = {0, 0, 1}; // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); + VectorNormalize2(temp, ax[0]); - if ( ax[0][2] == 1.0f ) - { + if (ax[0][2] == 1.0f) { // readjust up - VectorSet( up, 0, 1, 0 ); + VectorSet(up, 0, 1, 0); } - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); } } - // There are only a few types that really use velocity and acceleration, so do extra work for those types //-------------------------------------------------------------------------------------------------------- - if ( fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter ) - { + if (fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter) { // Velocity calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE || flags & FX_RELATIVE ) - { - VectorSet( vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal() ); - } - else - { // bah, do some extra work to coerce it - VectorScale( ax[0], fx->mVelX.GetVal(), vel ); - VectorMA( vel, fx->mVelY.GetVal(), ax[1], vel ); - VectorMA( vel, fx->mVelZ.GetVal(), ax[2], vel ); + if (fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE || flags & FX_RELATIVE) { + VectorSet(vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal()); + } else { // bah, do some extra work to coerce it + VectorScale(ax[0], fx->mVelX.GetVal(), vel); + VectorMA(vel, fx->mVelY.GetVal(), ax[1], vel); + VectorMA(vel, fx->mVelZ.GetVal(), ax[2], vel); } // Acceleration calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE || flags & FX_RELATIVE ) - { - VectorSet( accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal() ); - } - else - { - VectorScale( ax[0], fx->mAccelX.GetVal(), accel ); - VectorMA( accel, fx->mAccelY.GetVal(), ax[1], accel ); - VectorMA( accel, fx->mAccelZ.GetVal(), ax[2], accel ); + if (fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE || flags & FX_RELATIVE) { + VectorSet(accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal()); + } else { + VectorScale(ax[0], fx->mAccelX.GetVal(), accel); + VectorMA(accel, fx->mAccelY.GetVal(), ax[1], accel); + VectorMA(accel, fx->mAccelZ.GetVal(), ax[2], accel); } // Gravity is completely decoupled from acceleration since it is __always__ absolute @@ -1593,17 +1333,15 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve // There may be a lag between when the effect should be created and when it actually gets created. // Since we know what the discrepancy is, we can attempt to compensate... - if ( lateTime > 0 ) - { + if (lateTime > 0) { // Calc the time differences float ftime = lateTime * 0.001f; float time2 = ftime * ftime * 0.5f; - VectorMA( vel, ftime, accel, vel ); + VectorMA(vel, ftime, accel, vel); // Predict the new position - for ( int i = 0 ; i < 3 ; i++ ) - { + for (int i = 0; i < 3; i++) { org[i] = org[i] + ftime * vel[i] + time2 * vel[i]; } } @@ -1611,232 +1349,172 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve // Line type primitives work with an origin2, so do the extra work for them //-------------------------------------------------------------------------- - if ( fx->mType == Line || fx->mType == Electricity ) - { + if (fx->mType == Line || fx->mType == Electricity) { // We may have to do a trace to find our endpoint - if ( fx->mSpawnFlags & FX_ORG2_FROM_TRACE ) - { - VectorMA( org, FX_MAX_TRACE_DIST, ax[0], temp ); + if (fx->mSpawnFlags & FX_ORG2_FROM_TRACE) { + VectorMA(org, FX_MAX_TRACE_DIST, ax[0], temp); - if ( fx->mSpawnFlags & FX_ORG2_IS_OFFSET ) - { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much + if (fx->mSpawnFlags & FX_ORG2_IS_OFFSET) { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much // we also do this pre-trace as opposed to post trace since we may have to render an impact effect // and we will want the normal at the exact endpos... - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); - VectorAdd( org2, temp, temp ); - } - else - { // I can only imagine a few cases where you might want to do this... - VectorMA( temp, fx->mOrigin2X.GetVal(), ax[0], temp ); - VectorMA( temp, fx->mOrigin2Y.GetVal(), ax[1], temp ); - VectorMA( temp, fx->mOrigin2Z.GetVal(), ax[2], temp ); + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + VectorAdd(org2, temp, temp); + } else { // I can only imagine a few cases where you might want to do this... + VectorMA(temp, fx->mOrigin2X.GetVal(), ax[0], temp); + VectorMA(temp, fx->mOrigin2Y.GetVal(), ax[1], temp); + VectorMA(temp, fx->mOrigin2Z.GetVal(), ax[2], temp); } } - theFxHelper.Trace( &tr, org, NULL, NULL, temp, -1, CONTENTS_SOLID | CONTENTS_SHOTCLIP );//MASK_SHOT ); + theFxHelper.Trace(&tr, org, NULL, NULL, temp, -1, CONTENTS_SOLID | CONTENTS_SHOTCLIP); // MASK_SHOT ); - if ( tr.startsolid || tr.allsolid ) - { - VectorCopy( org, org2 ); // this is not a very good solution - } - else - { - VectorCopy( tr.endpos, org2 ); + if (tr.startsolid || tr.allsolid) { + VectorCopy(org, org2); // this is not a very good solution + } else { + VectorCopy(tr.endpos, org2); } - if ( fx->mSpawnFlags & FX_TRACE_IMPACT_FX ) - { - PlayEffect( fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal ); + if (fx->mSpawnFlags & FX_TRACE_IMPACT_FX) { + PlayEffect(fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal); } - } - else - { - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); - } - else - { - VectorScale( ax[0], fx->mOrigin2X.GetVal(), org2 ); - VectorMA( org2, fx->mOrigin2Y.GetVal(), ax[1], org2 ); - VectorMA( org2, fx->mOrigin2Z.GetVal(), ax[2], org2 ); - - VectorAdd( org2, origin, org2 ); + } else { + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + } else { + VectorScale(ax[0], fx->mOrigin2X.GetVal(), org2); + VectorMA(org2, fx->mOrigin2Y.GetVal(), ax[1], org2); + VectorMA(org2, fx->mOrigin2Z.GetVal(), ax[2], org2); + + VectorAdd(org2, origin, org2); } - } } // end special org2 types // handle RGB color, but only for types that will use it //--------------------------------------------------------------------------- - if ( fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake ) - { - if ( fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP ) - { + if (fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake) { + if (fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP) { float perc = Q_flrand(0.0f, 1.0f); - VectorSet( sRGB, fx->mRedStart.GetVal( perc ), fx->mGreenStart.GetVal( perc ), fx->mBlueStart.GetVal( perc ) ); - VectorSet( eRGB, fx->mRedEnd.GetVal( perc ), fx->mGreenEnd.GetVal( perc ), fx->mBlueEnd.GetVal( perc ) ); - } - else - { - VectorSet( sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal() ); - VectorSet( eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal() ); + VectorSet(sRGB, fx->mRedStart.GetVal(perc), fx->mGreenStart.GetVal(perc), fx->mBlueStart.GetVal(perc)); + VectorSet(eRGB, fx->mRedEnd.GetVal(perc), fx->mGreenEnd.GetVal(perc), fx->mBlueEnd.GetVal(perc)); + } else { + VectorSet(sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal()); + VectorSet(eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal()); } } // Now create the appropriate effect entity //------------------------ - switch( fx->mType ) - { + switch (fx->mType) { //--------- case Particle: - //--------- + //--------- - FX_AddParticle( clientID, org, vel, accel, fx->mGravity.GetVal(), - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddParticle(clientID, org, vel, accel, fx->mGravity.GetVal(), fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), + fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), + fx->mRotationDelta.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum); break; //--------- case Line: - //--------- + //--------- - FX_AddLine( clientID, org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddLine(clientID, org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), flags, modelNum, boltNum); break; //--------- case Tail: - //--------- + //--------- - FX_AddTail( clientID, org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddTail(clientID, org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mLengthStart.GetVal(), + fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, + fx->mRGBParm.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), + fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum); break; //---------------- case Electricity: - //---------------- + //---------------- - FX_AddElectricity( clientID, org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mElasticity.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddElectricity(clientID, org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mElasticity.GetVal(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum); break; //--------- case Cylinder: - //--------- + //--------- - FX_AddCylinder( clientID, org, ax[0], - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mSize2Start.GetVal(), fx->mSize2End.GetVal(), fx->mSize2Parm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddCylinder(clientID, org, ax[0], fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mSize2Start.GetVal(), + fx->mSize2End.GetVal(), fx->mSize2Parm.GetVal(), fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), + fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum); break; //--------- case Emitter: - //--------- + //--------- // for chunk angles, you don't really need much control over the end result...you just want variation.. - VectorSet( ang, - fx->mAngle1.GetVal(), - fx->mAngle2.GetVal(), - fx->mAngle3.GetVal() ); + VectorSet(ang, fx->mAngle1.GetVal(), fx->mAngle2.GetVal(), fx->mAngle3.GetVal()); - vectoangles( ax[0], temp ); - VectorAdd( ang, temp, ang ); + vectoangles(ax[0], temp); + VectorAdd(ang, temp, ang); - VectorSet( angDelta, - fx->mAngle1Delta.GetVal(), - fx->mAngle2Delta.GetVal(), - fx->mAngle3Delta.GetVal() ); + VectorSet(angDelta, fx->mAngle1Delta.GetVal(), fx->mAngle2Delta.GetVal(), fx->mAngle3Delta.GetVal()); emitterModel = fx->mMediaHandles.GetHandle(); - FX_AddEmitter( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - ang, angDelta, - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mEmitterFxHandles.GetHandle(), - fx->mDensity.GetVal(), fx->mVariance.GetVal(), - fx->mLife.GetVal(), emitterModel, flags ); + FX_AddEmitter(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), ang, angDelta, fx->mMin, fx->mMax, fx->mElasticity.GetVal(), + fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mEmitterFxHandles.GetHandle(), fx->mDensity.GetVal(), + fx->mVariance.GetVal(), fx->mLife.GetVal(), emitterModel, flags); break; //--------- case Decal: - //--------- + //--------- // I'm calling this function ( at least for now ) because it handles projecting // the decal mark onto the surfaces properly. This is especially important for large marks. // The downside is that it's much less flexible.... - CG_ImpactMark( fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), - sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), - qtrue, fx->mSizeStart.GetVal(), qfalse ); + CG_ImpactMark(fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), qtrue, + fx->mSizeStart.GetVal(), qfalse); - if (fx->mFlags & FX_GHOUL2_DECALS) - { - trace_t tr; - vec3_t end; + if (fx->mFlags & FX_GHOUL2_DECALS) { + trace_t tr; + vec3_t end; VectorMA(org, 64, ax[0], end); theFxHelper.G2Trace(&tr, org, NULL, NULL, end, ENTITYNUM_NONE, MASK_PLAYERSOLID); - if (tr.entityNum < ENTITYNUM_WORLD && - g_entities[tr.entityNum].ghoul2.size()) - { + if (tr.entityNum < ENTITYNUM_WORLD && g_entities[tr.entityNum].ghoul2.size()) { gentity_t *ent = &g_entities[tr.entityNum]; - if ( ent != NULL ) - { + if (ent != NULL) { vec3_t entOrg, hitDir; float entYaw; float firstModel = 0; - if ( !(ent->s.eFlags&EF_NODRAW) ) - {//not drawn, no marks - if ( ent->client ) - { - VectorCopy( ent->client->ps.origin, entOrg ); - } - else - { - VectorCopy( ent->currentOrigin, entOrg ); + if (!(ent->s.eFlags & EF_NODRAW)) { // not drawn, no marks + if (ent->client) { + VectorCopy(ent->client->ps.origin, entOrg); + } else { + VectorCopy(ent->currentOrigin, entOrg); } - if ( ent->client ) - { + if (ent->client) { entYaw = ent->client->ps.viewangles[YAW]; - } - else - { + } else { entYaw = ent->currentAngles[YAW]; } - //if ( VectorCompare( tr.plane.normal, vec3_origin ) ) - {//hunh, no plane? Use trace dir - VectorCopy( ax[0], hitDir ); + // if ( VectorCompare( tr.plane.normal, vec3_origin ) ) + { // hunh, no plane? Use trace dir + VectorCopy(ax[0], hitDir); } /* else @@ -1845,9 +1523,8 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve } */ - CG_AddGhoul2Mark(fx->mMediaHandles.GetHandle(), fx->mSizeStart.GetVal(), tr.endpos, tr.plane.normal, - tr.entityNum, entOrg, entYaw, - ent->ghoul2, ent->s.modelScale, Q_irand(40000, 60000), firstModel); + CG_AddGhoul2Mark(fx->mMediaHandles.GetHandle(), fx->mSizeStart.GetVal(), tr.endpos, tr.plane.normal, tr.entityNum, entOrg, entYaw, + ent->ghoul2, ent->s.modelScale, Q_irand(40000, 60000), firstModel); } } } @@ -1856,66 +1533,56 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve //------------------- case OrientedParticle: - //------------------- + //------------------- - FX_AddOrientedParticle( clientID, org, ax[0], vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, modelNum, boltNum ); + FX_AddOrientedParticle(clientID, org, ax[0], vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), + fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), + fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), + fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, + modelNum, boltNum); break; //--------- case Sound: - //--------- - if (gEffectsInPortal) - { //could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so just make it a local sound. - theFxHelper.PlayLocalSound( fx->mMediaHandles.GetHandle(), CHAN_AUTO ); - } - else if ( fx->mSpawnFlags & FX_SND_LESS_ATTENUATION ) - { - theFxHelper.PlaySound( org, ENTITYNUM_NONE, CHAN_LESS_ATTEN, fx->mMediaHandles.GetHandle() ); - } - else - { - theFxHelper.PlaySound( org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle() ); + //--------- + if (gEffectsInPortal) { // could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so + // just make it a local sound. + theFxHelper.PlayLocalSound(fx->mMediaHandles.GetHandle(), CHAN_AUTO); + } else if (fx->mSpawnFlags & FX_SND_LESS_ATTENUATION) { + theFxHelper.PlaySound(org, ENTITYNUM_NONE, CHAN_LESS_ATTEN, fx->mMediaHandles.GetHandle()); + } else { + theFxHelper.PlaySound(org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle()); } break; //--------- case FxRunner: - //--------- + //--------- - PlayEffect( fx->mPlayFxHandles.GetHandle(), org, ax ); + PlayEffect(fx->mPlayFxHandles.GetHandle(), org, ax); break; //--------- case Light: - //--------- + //--------- - FX_AddLight( org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mFlags ); + FX_AddLight(org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), + fx->mFlags); break; //--------- case CameraShake: - //--------- + //--------- // It calculates how intense the shake should be based on how close you are to the origin you pass in here // elasticity is actually the intensity...radius is the distance in which the shake will have some effect // life is how long the effect lasts. - theFxHelper.CameraShake( org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal() ); + theFxHelper.CameraShake(org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal()); break; //-------------- case ScreenFlash: - //-------------- + //-------------- - FX_AddFlash( org, - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddFlash(org, sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags); break; default: @@ -1923,12 +1590,10 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve } // Track when we need to clean ourselves up if we are a copy - if ( fx->mCopy ) - { + if (fx->mCopy) { fx->mRefCount--; - if ( fx->mRefCount <= 0 ) - { + if (fx->mRefCount <= 0) { delete fx; } } diff --git a/code/cgame/FxSystem.cpp b/code/cgame/FxSystem.cpp index 0a0112d136..c08a5473c2 100644 --- a/code/cgame/FxSystem.cpp +++ b/code/cgame/FxSystem.cpp @@ -23,54 +23,45 @@ along with this program; if not, see . #include "common_headers.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif -#include "cg_media.h" //for cgs.model_draw for G2 +#include "cg_media.h" //for cgs.model_draw for G2 -extern vmCvar_t fx_debug; -extern vmCvar_t fx_freeze; +extern vmCvar_t fx_debug; +extern vmCvar_t fx_freeze; -extern void CG_ExplosionEffects( vec3_t origin, float intensity, int radius, int time ); +extern void CG_ExplosionEffects(vec3_t origin, float intensity, int radius, int time); // Stuff for the FxHelper //------------------------------------------------------ -void SFxHelper::Init() -{ - mTime = 0; -} +void SFxHelper::Init() { mTime = 0; } //------------------------------------------------------ -void SFxHelper::Print( const char *msg, ... ) -{ +void SFxHelper::Print(const char *msg, ...) { #ifndef FINAL_BUILD - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start( argptr, msg ); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end( argptr ); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - gi.Printf( text ); + gi.Printf(text); #endif } //------------------------------------------------------ -void SFxHelper::AdjustTime( int frameTime ) -{ - if ( fx_freeze.integer || ( frameTime <= 0 )) - { +void SFxHelper::AdjustTime(int frameTime) { + if (fx_freeze.integer || (frameTime <= 0)) { // Allow no time progression when we are paused. mFrameTime = 0; mFloatFrameTime = 0.0f; - } - else - { - if ( !cg_paused.integer ) - { - if ( frameTime > 300 ) // hack for returning from paused and time bursts + } else { + if (!cg_paused.integer) { + if (frameTime > 300) // hack for returning from paused and time bursts { frameTime = 300; } @@ -83,128 +74,88 @@ void SFxHelper::AdjustTime( int frameTime ) } //------------------------------------------------------ -int SFxHelper::OpenFile( const char *file, fileHandle_t *fh, int mode ) -{ -// char path[256]; +int SFxHelper::OpenFile(const char *file, fileHandle_t *fh, int mode) { + // char path[256]; -// sprintf( path, "%s/%s", FX_FILE_PATH, file ); - return cgi_FS_FOpenFile( file, fh, FS_READ ); + // sprintf( path, "%s/%s", FX_FILE_PATH, file ); + return cgi_FS_FOpenFile(file, fh, FS_READ); } //------------------------------------------------------ -int SFxHelper::ReadFile( void *data, int len, fileHandle_t fh ) -{ - return cgi_FS_Read( data, len, fh ); -} +int SFxHelper::ReadFile(void *data, int len, fileHandle_t fh) { return cgi_FS_Read(data, len, fh); } //------------------------------------------------------ -void SFxHelper::CloseFile( fileHandle_t fh ) -{ - cgi_FS_FCloseFile( fh ); -} +void SFxHelper::CloseFile(fileHandle_t fh) { cgi_FS_FCloseFile(fh); } //------------------------------------------------------ -void SFxHelper::PlaySound( const vec3_t org, int entityNum, int entchannel, int sfxHandle ) -{ - cgi_S_StartSound( org, entityNum, entchannel, sfxHandle ); -} +void SFxHelper::PlaySound(const vec3_t org, int entityNum, int entchannel, int sfxHandle) { cgi_S_StartSound(org, entityNum, entchannel, sfxHandle); } //------------------------------------------------------ -void SFxHelper::PlayLocalSound( int sfxHandle, int channelNum ) -{ - cgi_S_StartLocalSound(sfxHandle, channelNum); -} +void SFxHelper::PlayLocalSound(int sfxHandle, int channelNum) { cgi_S_StartLocalSound(sfxHandle, channelNum); } //------------------------------------------------------ -void SFxHelper::Trace( trace_t *tr, vec3_t start, vec3_t min, vec3_t max, - vec3_t end, int skipEntNum, int flags ) -{ - CG_Trace( tr, start, min, max, end, skipEntNum, flags ); +void SFxHelper::Trace(trace_t *tr, vec3_t start, vec3_t min, vec3_t max, vec3_t end, int skipEntNum, int flags) { + CG_Trace(tr, start, min, max, end, skipEntNum, flags); } -void SFxHelper::G2Trace( trace_t *tr, vec3_t start, vec3_t min, vec3_t max, - vec3_t end, int skipEntNum, int flags ) -{ - //CG_Trace( tr, start, min, max, end, skipEntNum, flags, G2_COLLIDE ); +void SFxHelper::G2Trace(trace_t *tr, vec3_t start, vec3_t min, vec3_t max, vec3_t end, int skipEntNum, int flags) { + // CG_Trace( tr, start, min, max, end, skipEntNum, flags, G2_COLLIDE ); gi.trace(tr, start, NULL, NULL, end, skipEntNum, flags, G2_COLLIDE, 0); } //------------------------------------------------------ -void SFxHelper::AddFxToScene( refEntity_t *ent ) -{ - cgi_R_AddRefEntityToScene( ent ); -} +void SFxHelper::AddFxToScene(refEntity_t *ent) { cgi_R_AddRefEntityToScene(ent); } //------------------------------------------------------ -int SFxHelper::RegisterShader( const gsl::cstring_span& shader ) -{ +int SFxHelper::RegisterShader(const gsl::cstring_span &shader) { // TODO: it would be nice to change the ABI here to allow for passing of string views - return cgi_R_RegisterShader( std::string( shader.begin(), shader.end() ).c_str() ); + return cgi_R_RegisterShader(std::string(shader.begin(), shader.end()).c_str()); } //------------------------------------------------------ -int SFxHelper::RegisterSound( const gsl::cstring_span& sound ) -{ +int SFxHelper::RegisterSound(const gsl::cstring_span &sound) { // TODO: it would be nice to change the ABI here to allow for passing of string views - return cgi_S_RegisterSound( std::string( sound.begin(), sound.end() ).c_str() ); + return cgi_S_RegisterSound(std::string(sound.begin(), sound.end()).c_str()); } //------------------------------------------------------ -int SFxHelper::RegisterModel( const gsl::cstring_span& model ) -{ - return cgi_R_RegisterModel( std::string( model.begin(), model.end() ).c_str() ); -} +int SFxHelper::RegisterModel(const gsl::cstring_span &model) { return cgi_R_RegisterModel(std::string(model.begin(), model.end()).c_str()); } //------------------------------------------------------ -void SFxHelper::AddLightToScene( vec3_t org, float radius, float red, float green, float blue ) -{ - cgi_R_AddLightToScene( org, radius, red, green, blue ); -} +void SFxHelper::AddLightToScene(vec3_t org, float radius, float red, float green, float blue) { cgi_R_AddLightToScene(org, radius, red, green, blue); } //------------------------------------------------------ -void SFxHelper::AddPolyToScene( int shader, int count, polyVert_t *verts ) -{ - cgi_R_AddPolyToScene( shader, count, verts ); -} +void SFxHelper::AddPolyToScene(int shader, int count, polyVert_t *verts) { cgi_R_AddPolyToScene(shader, count, verts); } //------------------------------------------------------ -void SFxHelper::CameraShake( vec3_t origin, float intensity, int radius, int time ) -{ - CG_ExplosionEffects( origin, intensity, radius, time ); -} +void SFxHelper::CameraShake(vec3_t origin, float intensity, int radius, int time) { CG_ExplosionEffects(origin, intensity, radius, time); } //------------------------------------------------------ -int SFxHelper::GetOriginAxisFromBolt(const centity_t ¢, int modelNum, int boltNum, vec3_t /*out*/origin, vec3_t /*out*/axis[3]) -{ - if ((cg.time-cent.snapShotTime) > 200) - { //you were added more than 200ms ago, so I say you are no longer valid/in our snapshot. +int SFxHelper::GetOriginAxisFromBolt(const centity_t ¢, int modelNum, int boltNum, vec3_t /*out*/ origin, vec3_t /*out*/ axis[3]) { + if ((cg.time - cent.snapShotTime) > 200) { // you were added more than 200ms ago, so I say you are no longer valid/in our snapshot. return 0; } int doesBoltExist; - mdxaBone_t boltMatrix; - vec3_t G2Angles = {cent.lerpAngles[0] , cent.lerpAngles[1], cent.lerpAngles[2]}; - if ( cent.currentState.eType == ET_PLAYER ) - {//players use cent.renderAngles - VectorCopy( cent.renderAngles, G2Angles ); - - if ( cent.gent //has a game entity - && cent.gent->s.m_iVehicleNum != 0 //in a vehicle - && cent.gent->m_pVehicle //have a valid vehicle pointer - && cent.gent->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER //it's not a fighter - && cent.gent->m_pVehicle->m_pVehicleInfo->type != VH_SPEEDER //not a speeder - ) - { - G2Angles[PITCH]=0; - G2Angles[ROLL] =0; + mdxaBone_t boltMatrix; + vec3_t G2Angles = {cent.lerpAngles[0], cent.lerpAngles[1], cent.lerpAngles[2]}; + if (cent.currentState.eType == ET_PLAYER) { // players use cent.renderAngles + VectorCopy(cent.renderAngles, G2Angles); + + if (cent.gent // has a game entity + && cent.gent->s.m_iVehicleNum != 0 // in a vehicle + && cent.gent->m_pVehicle // have a valid vehicle pointer + && cent.gent->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER // it's not a fighter + && cent.gent->m_pVehicle->m_pVehicleInfo->type != VH_SPEEDER // not a speeder + ) { + G2Angles[PITCH] = 0; + G2Angles[ROLL] = 0; } } // go away and get me the bolt position for this frame please - doesBoltExist = gi.G2API_GetBoltMatrix(cent.gent->ghoul2, modelNum, - boltNum, &boltMatrix, G2Angles, - cent.lerpOrigin, cg.time, cgs.model_draw, - cent.currentState.modelScale); + doesBoltExist = gi.G2API_GetBoltMatrix(cent.gent->ghoul2, modelNum, boltNum, &boltMatrix, G2Angles, cent.lerpOrigin, cg.time, cgs.model_draw, + cent.currentState.modelScale); // set up the axis and origin we need for the actual effect spawning origin[0] = boltMatrix.matrix[0][3]; origin[1] = boltMatrix.matrix[1][3]; diff --git a/code/cgame/FxTemplate.cpp b/code/cgame/FxTemplate.cpp index 78b3503fc2..633140b4ca 100644 --- a/code/cgame/FxTemplate.cpp +++ b/code/cgame/FxTemplate.cpp @@ -23,7 +23,7 @@ along with this program; if not, see . #include "common_headers.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #include "../game/genericparser2.h" @@ -41,8 +41,7 @@ along with this program; if not, see . // Return: // none //------------------------------------------------------ -CPrimitiveTemplate::CPrimitiveTemplate() -{ +CPrimitiveTemplate::CPrimitiveTemplate() { // We never start out as a copy or with a name mCopy = false; mName[0] = 0; @@ -50,134 +49,133 @@ CPrimitiveTemplate::CPrimitiveTemplate() mFlags = mSpawnFlags = 0; - mLife.SetRange( 50.0f, 50.0f ); - mSpawnCount.SetRange( 1.0f, 1.0f ); - mRadius.SetRange( 10.0f, 10.0f ); - mHeight.SetRange( 10.0f, 10.0f ); - mWindModifier.SetRange( 1.0f, 1.0f ); + mLife.SetRange(50.0f, 50.0f); + mSpawnCount.SetRange(1.0f, 1.0f); + mRadius.SetRange(10.0f, 10.0f); + mHeight.SetRange(10.0f, 10.0f); + mWindModifier.SetRange(1.0f, 1.0f); - VectorSet( mMin, 0.0f, 0.0f, 0.0f ); - VectorSet( mMax, 0.0f, 0.0f, 0.0f ); + VectorSet(mMin, 0.0f, 0.0f, 0.0f); + VectorSet(mMax, 0.0f, 0.0f, 0.0f); - mRedStart.SetRange( 1.0f, 1.0f ); - mGreenStart.SetRange( 1.0f, 1.0f ); - mBlueStart.SetRange( 1.0f, 1.0f ); + mRedStart.SetRange(1.0f, 1.0f); + mGreenStart.SetRange(1.0f, 1.0f); + mBlueStart.SetRange(1.0f, 1.0f); - mRedEnd.SetRange( 1.0f, 1.0f ); - mGreenEnd.SetRange( 1.0f, 1.0f ); - mBlueEnd.SetRange( 1.0f, 1.0f ); + mRedEnd.SetRange(1.0f, 1.0f); + mGreenEnd.SetRange(1.0f, 1.0f); + mBlueEnd.SetRange(1.0f, 1.0f); - mAlphaStart.SetRange( 1.0f, 1.0f ); - mAlphaEnd.SetRange( 1.0f, 1.0f ); + mAlphaStart.SetRange(1.0f, 1.0f); + mAlphaEnd.SetRange(1.0f, 1.0f); - mSizeStart.SetRange( 1.0f, 1.0f ); - mSizeEnd.SetRange( 1.0f, 1.0f ); + mSizeStart.SetRange(1.0f, 1.0f); + mSizeEnd.SetRange(1.0f, 1.0f); - mSize2Start.SetRange( 1.0f, 1.0f ); - mSize2End.SetRange( 1.0f, 1.0f ); + mSize2Start.SetRange(1.0f, 1.0f); + mSize2End.SetRange(1.0f, 1.0f); - mLengthStart.SetRange( 1.0f, 1.0f ); - mLengthEnd.SetRange( 1.0f, 1.0f ); + mLengthStart.SetRange(1.0f, 1.0f); + mLengthEnd.SetRange(1.0f, 1.0f); - mTexCoordS.SetRange( 1.0f, 1.0f ); - mTexCoordT.SetRange( 1.0f, 1.0f ); + mTexCoordS.SetRange(1.0f, 1.0f); + mTexCoordT.SetRange(1.0f, 1.0f); - mVariance.SetRange( 1.0f, 1.0f ); - mDensity.SetRange( 10.0f, 10.0f );// default this high so it doesn't do bad things + mVariance.SetRange(1.0f, 1.0f); + mDensity.SetRange(10.0f, 10.0f); // default this high so it doesn't do bad things } //----------------------------------------------------------- -void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) -{ +void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) { // I'm assuming that doing a memcpy wouldn't work here // If you are looking at this and know a better way to do this, please tell me. - strcpy( mName, that.mName ); + strcpy(mName, that.mName); - mType = that.mType; + mType = that.mType; - mSpawnDelay = that.mSpawnDelay; - mSpawnCount = that.mSpawnCount; - mLife = that.mLife; - mCullRange = that.mCullRange; + mSpawnDelay = that.mSpawnDelay; + mSpawnCount = that.mSpawnCount; + mLife = that.mLife; + mCullRange = that.mCullRange; - mMediaHandles = that.mMediaHandles; - mImpactFxHandles = that.mImpactFxHandles; - mDeathFxHandles = that.mDeathFxHandles; - mEmitterFxHandles = that.mEmitterFxHandles; - mPlayFxHandles = that.mPlayFxHandles; + mMediaHandles = that.mMediaHandles; + mImpactFxHandles = that.mImpactFxHandles; + mDeathFxHandles = that.mDeathFxHandles; + mEmitterFxHandles = that.mEmitterFxHandles; + mPlayFxHandles = that.mPlayFxHandles; - mFlags = that.mFlags; - mSpawnFlags = that.mSpawnFlags; + mFlags = that.mFlags; + mSpawnFlags = that.mSpawnFlags; - VectorCopy( that.mMin, mMin ); - VectorCopy( that.mMax, mMax ); + VectorCopy(that.mMin, mMin); + VectorCopy(that.mMax, mMax); - mOrigin1X = that.mOrigin1X; - mOrigin1Y = that.mOrigin1Y; - mOrigin1Z = that.mOrigin1Z; + mOrigin1X = that.mOrigin1X; + mOrigin1Y = that.mOrigin1Y; + mOrigin1Z = that.mOrigin1Z; - mOrigin2X = that.mOrigin2X; - mOrigin2Y = that.mOrigin2Y; - mOrigin2Z = that.mOrigin2Z; + mOrigin2X = that.mOrigin2X; + mOrigin2Y = that.mOrigin2Y; + mOrigin2Z = that.mOrigin2Z; - mRadius = that.mRadius; - mHeight = that.mHeight; - mWindModifier = that.mWindModifier; + mRadius = that.mRadius; + mHeight = that.mHeight; + mWindModifier = that.mWindModifier; - mRotation = that.mRotation; - mRotationDelta = that.mRotationDelta; + mRotation = that.mRotation; + mRotationDelta = that.mRotationDelta; - mAngle1 = that.mAngle1; - mAngle2 = that.mAngle2; - mAngle3 = that.mAngle3; + mAngle1 = that.mAngle1; + mAngle2 = that.mAngle2; + mAngle3 = that.mAngle3; - mAngle1Delta = that.mAngle1Delta; - mAngle2Delta = that.mAngle2Delta; - mAngle3Delta = that.mAngle3Delta; + mAngle1Delta = that.mAngle1Delta; + mAngle2Delta = that.mAngle2Delta; + mAngle3Delta = that.mAngle3Delta; - mVelX = that.mVelX; - mVelY = that.mVelY; - mVelZ = that.mVelZ; + mVelX = that.mVelX; + mVelY = that.mVelY; + mVelZ = that.mVelZ; - mAccelX = that.mAccelX; - mAccelY = that.mAccelY; - mAccelZ = that.mAccelZ; + mAccelX = that.mAccelX; + mAccelY = that.mAccelY; + mAccelZ = that.mAccelZ; - mGravity = that.mGravity; + mGravity = that.mGravity; - mDensity = that.mDensity; - mVariance = that.mVariance; + mDensity = that.mDensity; + mVariance = that.mVariance; - mRedStart = that.mRedStart; - mGreenStart = that.mGreenStart; - mBlueStart = that.mBlueStart; + mRedStart = that.mRedStart; + mGreenStart = that.mGreenStart; + mBlueStart = that.mBlueStart; - mRedEnd = that.mRedEnd; - mGreenEnd = that.mGreenEnd; - mBlueEnd = that.mBlueEnd; + mRedEnd = that.mRedEnd; + mGreenEnd = that.mGreenEnd; + mBlueEnd = that.mBlueEnd; - mRGBParm = that.mRGBParm; + mRGBParm = that.mRGBParm; - mAlphaStart = that.mAlphaStart; - mAlphaEnd = that.mAlphaEnd; - mAlphaParm = that.mAlphaParm; + mAlphaStart = that.mAlphaStart; + mAlphaEnd = that.mAlphaEnd; + mAlphaParm = that.mAlphaParm; - mSizeStart = that.mSizeStart; - mSizeEnd = that.mSizeEnd; - mSizeParm = that.mSizeParm; + mSizeStart = that.mSizeStart; + mSizeEnd = that.mSizeEnd; + mSizeParm = that.mSizeParm; - mSize2Start = that.mSize2Start; - mSize2End = that.mSize2End; - mSize2Parm = that.mSize2Parm; + mSize2Start = that.mSize2Start; + mSize2End = that.mSize2End; + mSize2Parm = that.mSize2Parm; - mLengthStart = that.mLengthStart; - mLengthEnd = that.mLengthEnd; - mLengthParm = that.mLengthParm; + mLengthStart = that.mLengthStart; + mLengthEnd = that.mLengthEnd; + mLengthParm = that.mLengthParm; - mTexCoordS = that.mTexCoordS; - mTexCoordT = that.mTexCoordT; + mTexCoordS = that.mTexCoordS; + mTexCoordT = that.mTexCoordT; - mElasticity = that.mElasticity; + mElasticity = that.mElasticity; } //------------------------------------------------------ @@ -193,24 +191,19 @@ void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFloat( const gsl::cstring_span& val, float& min, float& max ) -{ +bool CPrimitiveTemplate::ParseFloat(const gsl::cstring_span &val, float &min, float &max) { // attempt to read out the values - int v = Q::sscanf( val, min, max ); + int v = Q::sscanf(val, min, max); - if ( v == 0 ) - { // nothing was there, failure + if (v == 0) { // nothing was there, failure return false; - } - else if ( v == 1 ) - { // only one field entered, this is ok, but we should copy min into max + } else if (v == 1) { // only one field entered, this is ok, but we should copy min into max max = min; } return true; } - //------------------------------------------------------ // ParseVector // Removes up to six values from a passed in string and @@ -224,60 +217,44 @@ bool CPrimitiveTemplate::ParseFloat( const gsl::cstring_span& val, float& min, f // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVector( const gsl::cstring_span& val, vec3_t min, vec3_t max ) -{ +bool CPrimitiveTemplate::ParseVector(const gsl::cstring_span &val, vec3_t min, vec3_t max) { // we don't allow passing in a null - if ( min == nullptr || max == nullptr ) - { + if (min == nullptr || max == nullptr) { return false; } // attempt to read out our values - int v = Q::sscanf( val, min[0], min[1], min[2], max[0], max[1], max[2] ); + int v = Q::sscanf(val, min[0], min[1], min[2], max[0], max[1], max[2]); // Check for completeness - if ( v < 3 || v == 4 || v == 5 ) - { // not a complete value + if (v < 3 || v == 4 || v == 5) { // not a complete value return false; - } - else if ( v == 3 ) - { // only a min was entered, so copy the result into max - VectorCopy( min, max ); + } else if (v == 3) { // only a min was entered, so copy the result into max + VectorCopy(min, max); } return true; } -namespace detail -{ - // calls Q::sscanf with the elements of the given array as arguments +namespace detail { +// calls Q::sscanf with the elements of the given array as arguments - template< std::size_t remaining > - struct ScanStrings - { - template< std::size_t count, typename... Args > - static int call( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr, Args&... args ) - { - return ScanStrings< remaining - 1 >::call( val, arr, arr[ remaining - 1 ], args... ); - } - }; +template struct ScanStrings { + template static int call(const gsl::cstring_span &val, std::array &arr, Args &...args) { + return ScanStrings::call(val, arr, arr[remaining - 1], args...); + } +}; - template<> - struct ScanStrings< 0 > - { - template< std::size_t count, typename... Args > - static int call( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr, Args&... args ) - { - return Q::sscanf( val, args... ); - } - }; -} +template <> struct ScanStrings<0> { + template static int call(const gsl::cstring_span &val, std::array &arr, Args &...args) { + return Q::sscanf(val, args...); + } +}; +} // namespace detail -template< std::size_t count > -static gsl::span< gsl::cstring_span > scanStrings( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr ) -{ - int numParsed = detail::ScanStrings< count >::call( val, arr ); - return{ arr.data(), arr.data() + numParsed }; +template static gsl::span scanStrings(const gsl::cstring_span &val, std::array &arr) { + int numParsed = detail::ScanStrings::call(val, arr); + return {arr.data(), arr.data() + numParsed}; } //------------------------------------------------------ @@ -293,34 +270,26 @@ static gsl::span< gsl::cstring_span > scanStrings( const gsl::cstring_span& val, // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGroupFlags( const gsl::cstring_span& val, int& flags ) -{ +bool CPrimitiveTemplate::ParseGroupFlags(const gsl::cstring_span &val, int &flags) { // For a sub group, really you probably only have one or two flags set - std::array< gsl::cstring_span, 4 > flag; + std::array flag; - const auto availableFlag = scanStrings( val, flag ); + const auto availableFlag = scanStrings(val, flag); // Clear out the flags field, then convert the flag string to an actual value ( use generic flags ) flags = 0; bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "linear" ), FX_LINEAR }, - { CSTRING_VIEW( "nonlinear" ), FX_NONLINEAR }, - { CSTRING_VIEW( "wave" ), FX_WAVE }, - { CSTRING_VIEW( "random" ), FX_RAND }, - { CSTRING_VIEW( "clamp" ), FX_CLAMP }, + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("linear"), FX_LINEAR}, {CSTRING_VIEW("nonlinear"), FX_NONLINEAR}, {CSTRING_VIEW("wave"), FX_WAVE}, + {CSTRING_VIEW("random"), FX_RAND}, {CSTRING_VIEW("clamp"), FX_CLAMP}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { ok = false; - } - else - { + } else { flags |= pos->second; } } @@ -338,13 +307,11 @@ bool CPrimitiveTemplate::ParseGroupFlags( const gsl::cstring_span& val, int& fla // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMin( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseMin(const gsl::cstring_span &val) { vec3_t min; - if ( ParseVector( val, min, min ) == true ) - { - VectorCopy( min, mMin ); + if (ParseVector(val, min, min) == true) { + VectorCopy(min, mMin); // We assume that if a min is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -364,13 +331,11 @@ bool CPrimitiveTemplate::ParseMin( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMax( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseMax(const gsl::cstring_span &val) { vec3_t max; - if ( ParseVector( val, max, max ) == true ) - { - VectorCopy( max, mMax ); + if (ParseVector(val, max, max) == true) { + VectorCopy(max, mMax); // We assume that if a max is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -390,13 +355,11 @@ bool CPrimitiveTemplate::ParseMax( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLife( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLife(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLife.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLife.SetRange(min, max); return true; } @@ -413,13 +376,11 @@ bool CPrimitiveTemplate::ParseLife( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDelay( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseDelay(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSpawnDelay.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSpawnDelay.SetRange(min, max); return true; } @@ -436,13 +397,11 @@ bool CPrimitiveTemplate::ParseDelay( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseCount( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseCount(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSpawnCount.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSpawnCount.SetRange(min, max); return true; } @@ -459,17 +418,15 @@ bool CPrimitiveTemplate::ParseCount( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseElasticity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseElasticity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mElasticity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mElasticity.SetRange(min, max); // We assume that if elasticity is set that we are using physics, but don't assume we are // using a bounding box unless a min/max are explicitly set -// mFlags |= FX_APPLY_PHYSICS; + // mFlags |= FX_APPLY_PHYSICS; return true; } @@ -486,15 +443,13 @@ bool CPrimitiveTemplate::ParseElasticity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin1( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseOrigin1(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin1X.SetRange( min[0], max[0] ); - mOrigin1Y.SetRange( min[1], max[1] ); - mOrigin1Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin1X.SetRange(min[0], max[0]); + mOrigin1Y.SetRange(min[1], max[1]); + mOrigin1Z.SetRange(min[2], max[2]); return true; } @@ -511,15 +466,13 @@ bool CPrimitiveTemplate::ParseOrigin1( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin2( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseOrigin2(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin2X.SetRange( min[0], max[0] ); - mOrigin2Y.SetRange( min[1], max[1] ); - mOrigin2Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin2X.SetRange(min[0], max[0]); + mOrigin2Y.SetRange(min[1], max[1]); + mOrigin2Z.SetRange(min[2], max[2]); return true; } @@ -536,13 +489,11 @@ bool CPrimitiveTemplate::ParseOrigin2( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRadius( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRadius(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mRadius.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mRadius.SetRange(min, max); return true; } @@ -559,13 +510,11 @@ bool CPrimitiveTemplate::ParseRadius( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseHeight( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseHeight(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mHeight.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mHeight.SetRange(min, max); return true; } @@ -582,13 +531,11 @@ bool CPrimitiveTemplate::ParseHeight( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseWindModifier( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseWindModifier(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mWindModifier.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mWindModifier.SetRange(min, max); return true; } @@ -605,13 +552,11 @@ bool CPrimitiveTemplate::ParseWindModifier( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotation( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRotation(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == qtrue ) - { - mRotation.SetRange( min, max ); + if (ParseFloat(val, min, max) == qtrue) { + mRotation.SetRange(min, max); return true; } @@ -628,13 +573,11 @@ bool CPrimitiveTemplate::ParseRotation( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotationDelta( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRotationDelta(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == qtrue ) - { - mRotationDelta.SetRange( min, max ); + if (ParseFloat(val, min, max) == qtrue) { + mRotationDelta.SetRange(min, max); return true; } @@ -651,15 +594,13 @@ bool CPrimitiveTemplate::ParseRotationDelta( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngle( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAngle(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1.SetRange( min[0], max[0] ); - mAngle2.SetRange( min[1], max[1] ); - mAngle3.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1.SetRange(min[0], max[0]); + mAngle2.SetRange(min[1], max[1]); + mAngle3.SetRange(min[2], max[2]); return true; } @@ -676,15 +617,13 @@ bool CPrimitiveTemplate::ParseAngle( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngleDelta( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAngleDelta(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1Delta.SetRange( min[0], max[0] ); - mAngle2Delta.SetRange( min[1], max[1] ); - mAngle3Delta.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1Delta.SetRange(min[0], max[0]); + mAngle2Delta.SetRange(min[1], max[1]); + mAngle3Delta.SetRange(min[2], max[2]); return true; } @@ -701,15 +640,13 @@ bool CPrimitiveTemplate::ParseAngleDelta( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVelocity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseVelocity(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mVelX.SetRange( min[0], max[0] ); - mVelY.SetRange( min[1], max[1] ); - mVelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mVelX.SetRange(min[0], max[0]); + mVelY.SetRange(min[1], max[1]); + mVelZ.SetRange(min[2], max[2]); return true; } @@ -727,41 +664,36 @@ bool CPrimitiveTemplate::ParseVelocity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseFlags(const gsl::cstring_span &val) { // For a primitive, really you probably only have two or less flags set - std::array< gsl::cstring_span, 7 > flag; - - const auto availableFlag = scanStrings( val, flag ); - - bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "useModel" ), FX_ATTACHED_MODEL }, - { CSTRING_VIEW( "useBBox" ), FX_USE_BBOX }, - { CSTRING_VIEW( "usePhysics" ), FX_APPLY_PHYSICS }, - { CSTRING_VIEW( "expensivePhysics" ), FX_EXPENSIVE_PHYSICS }, - //rww - begin g2 stuff - { CSTRING_VIEW( "ghoul2Collision" ), ( FX_GHOUL2_TRACE | FX_APPLY_PHYSICS | FX_EXPENSIVE_PHYSICS ) }, - { CSTRING_VIEW( "ghoul2Decals" ), FX_GHOUL2_DECALS }, - //rww - end - { CSTRING_VIEW( "impactKills" ), FX_KILL_ON_IMPACT }, - { CSTRING_VIEW( "impactFx" ), FX_IMPACT_RUNS_FX }, - { CSTRING_VIEW( "deathFx" ), FX_DEATH_RUNS_FX }, - { CSTRING_VIEW( "useAlpha" ), FX_USE_ALPHA }, - { CSTRING_VIEW( "emitFx" ), FX_EMIT_FX }, - { CSTRING_VIEW( "depthHack" ), FX_DEPTH_HACK }, - { CSTRING_VIEW( "setShaderTime" ), FX_SET_SHADER_TIME }, + std::array flag; + + const auto availableFlag = scanStrings(val, flag); + + bool ok = true; + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("useModel"), FX_ATTACHED_MODEL}, + {CSTRING_VIEW("useBBox"), FX_USE_BBOX}, + {CSTRING_VIEW("usePhysics"), FX_APPLY_PHYSICS}, + {CSTRING_VIEW("expensivePhysics"), FX_EXPENSIVE_PHYSICS}, + // rww - begin g2 stuff + {CSTRING_VIEW("ghoul2Collision"), (FX_GHOUL2_TRACE | FX_APPLY_PHYSICS | FX_EXPENSIVE_PHYSICS)}, + {CSTRING_VIEW("ghoul2Decals"), FX_GHOUL2_DECALS}, + // rww - end + {CSTRING_VIEW("impactKills"), FX_KILL_ON_IMPACT}, + {CSTRING_VIEW("impactFx"), FX_IMPACT_RUNS_FX}, + {CSTRING_VIEW("deathFx"), FX_DEATH_RUNS_FX}, + {CSTRING_VIEW("useAlpha"), FX_USE_ALPHA}, + {CSTRING_VIEW("emitFx"), FX_EMIT_FX}, + {CSTRING_VIEW("depthHack"), FX_DEPTH_HACK}, + {CSTRING_VIEW("setShaderTime"), FX_SET_SHADER_TIME}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { // we have badness going on, but continue on in case there are any valid fields in here + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { // we have badness going on, but continue on in case there are any valid fields in here ok = false; - } - else - { + } else { mFlags |= pos->second; } } @@ -780,39 +712,34 @@ bool CPrimitiveTemplate::ParseFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSpawnFlags( const gsl::cstring_span& val ) -{ - std::array< gsl::cstring_span, 7 > flag; +bool CPrimitiveTemplate::ParseSpawnFlags(const gsl::cstring_span &val) { + std::array flag; // For a primitive, really you probably only have two or less flags set - const auto availableFlag = scanStrings( val, flag ); + const auto availableFlag = scanStrings(val, flag); bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "org2fromTrace" ), FX_ORG2_FROM_TRACE }, - { CSTRING_VIEW( "traceImpactFx" ), FX_TRACE_IMPACT_FX }, - { CSTRING_VIEW( "org2isOffset" ), FX_ORG2_IS_OFFSET }, - { CSTRING_VIEW( "cheapOrgCalc" ), FX_CHEAP_ORG_CALC }, - { CSTRING_VIEW( "cheapOrg2Calc" ), FX_CHEAP_ORG2_CALC }, - { CSTRING_VIEW( "absoluteVel" ), FX_VEL_IS_ABSOLUTE }, - { CSTRING_VIEW( "absoluteAccel" ), FX_ACCEL_IS_ABSOLUTE }, - { CSTRING_VIEW( "orgOnSphere" ), FX_ORG_ON_SPHERE }, - { CSTRING_VIEW( "orgOnCylinder" ), FX_ORG_ON_CYLINDER }, - { CSTRING_VIEW( "axisFromSphere" ), FX_AXIS_FROM_SPHERE }, - { CSTRING_VIEW( "randrotaroundfwd" ), FX_RAND_ROT_AROUND_FWD }, - { CSTRING_VIEW( "evenDistribution" ), FX_EVEN_DISTRIBUTION }, - { CSTRING_VIEW( "rgbComponentInterpolation" ), FX_RGB_COMPONENT_INTERP }, - { CSTRING_VIEW( "lessAttenuation" ), FX_SND_LESS_ATTENUATION }, + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("org2fromTrace"), FX_ORG2_FROM_TRACE}, + {CSTRING_VIEW("traceImpactFx"), FX_TRACE_IMPACT_FX}, + {CSTRING_VIEW("org2isOffset"), FX_ORG2_IS_OFFSET}, + {CSTRING_VIEW("cheapOrgCalc"), FX_CHEAP_ORG_CALC}, + {CSTRING_VIEW("cheapOrg2Calc"), FX_CHEAP_ORG2_CALC}, + {CSTRING_VIEW("absoluteVel"), FX_VEL_IS_ABSOLUTE}, + {CSTRING_VIEW("absoluteAccel"), FX_ACCEL_IS_ABSOLUTE}, + {CSTRING_VIEW("orgOnSphere"), FX_ORG_ON_SPHERE}, + {CSTRING_VIEW("orgOnCylinder"), FX_ORG_ON_CYLINDER}, + {CSTRING_VIEW("axisFromSphere"), FX_AXIS_FROM_SPHERE}, + {CSTRING_VIEW("randrotaroundfwd"), FX_RAND_ROT_AROUND_FWD}, + {CSTRING_VIEW("evenDistribution"), FX_EVEN_DISTRIBUTION}, + {CSTRING_VIEW("rgbComponentInterpolation"), FX_RGB_COMPONENT_INTERP}, + {CSTRING_VIEW("lessAttenuation"), FX_SND_LESS_ATTENUATION}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { ok = false; - } - else - { + } else { mSpawnFlags |= pos->second; } } @@ -830,15 +757,13 @@ bool CPrimitiveTemplate::ParseSpawnFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAcceleration( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAcceleration(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAccelX.SetRange( min[0], max[0] ); - mAccelY.SetRange( min[1], max[1] ); - mAccelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAccelX.SetRange(min[0], max[0]); + mAccelY.SetRange(min[1], max[1]); + mAccelZ.SetRange(min[2], max[2]); return true; } @@ -855,13 +780,11 @@ bool CPrimitiveTemplate::ParseAcceleration( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGravity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseGravity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mGravity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mGravity.SetRange(min, max); return true; } @@ -880,13 +803,11 @@ bool CPrimitiveTemplate::ParseGravity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDensity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseDensity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mDensity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mDensity.SetRange(min, max); return true; } @@ -906,13 +827,11 @@ bool CPrimitiveTemplate::ParseDensity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVariance( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseVariance(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mVariance.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mVariance.SetRange(min, max); return true; } @@ -929,15 +848,13 @@ bool CPrimitiveTemplate::ParseVariance( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBStart(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedStart.SetRange( min[0], max[0] ); - mGreenStart.SetRange( min[1], max[1] ); - mBlueStart.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedStart.SetRange(min[0], max[0]); + mGreenStart.SetRange(min[1], max[1]); + mBlueStart.SetRange(min[2], max[2]); return true; } @@ -954,15 +871,13 @@ bool CPrimitiveTemplate::ParseRGBStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBEnd(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedEnd.SetRange( min[0], max[0] ); - mGreenEnd.SetRange( min[1], max[1] ); - mBlueEnd.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedEnd.SetRange(min[0], max[0]); + mGreenEnd.SetRange(min[1], max[1]); + mBlueEnd.SetRange(min[2], max[2]); return true; } @@ -979,13 +894,11 @@ bool CPrimitiveTemplate::ParseRGBEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mRGBParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mRGBParm.SetRange(min, max); return true; } @@ -1002,14 +915,12 @@ bool CPrimitiveTemplate::ParseRGBParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_RGB_SHIFT ); + mFlags |= (flags << FX_RGB_SHIFT); return true; } @@ -1026,13 +937,11 @@ bool CPrimitiveTemplate::ParseRGBFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaStart.SetRange(min, max); return true; } @@ -1049,13 +958,11 @@ bool CPrimitiveTemplate::ParseAlphaStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaEnd.SetRange(min, max); return true; } @@ -1072,13 +979,11 @@ bool CPrimitiveTemplate::ParseAlphaEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaParm.SetRange(min, max); return true; } @@ -1095,14 +1000,12 @@ bool CPrimitiveTemplate::ParseAlphaParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_ALPHA_SHIFT ); + mFlags |= (flags << FX_ALPHA_SHIFT); return true; } @@ -1119,13 +1022,11 @@ bool CPrimitiveTemplate::ParseAlphaFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeStart.SetRange(min, max); return true; } @@ -1142,13 +1043,11 @@ bool CPrimitiveTemplate::ParseSizeStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeEnd.SetRange(min, max); return true; } @@ -1165,13 +1064,11 @@ bool CPrimitiveTemplate::ParseSizeEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeParm.SetRange(min, max); return true; } @@ -1188,14 +1085,12 @@ bool CPrimitiveTemplate::ParseSizeParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE_SHIFT ); + mFlags |= (flags << FX_SIZE_SHIFT); return true; } @@ -1212,13 +1107,11 @@ bool CPrimitiveTemplate::ParseSizeFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Start( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Start(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2Start.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2Start.SetRange(min, max); return true; } @@ -1235,13 +1128,11 @@ bool CPrimitiveTemplate::ParseSize2Start( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2End( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2End(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2End.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2End.SetRange(min, max); return true; } @@ -1258,13 +1149,11 @@ bool CPrimitiveTemplate::ParseSize2End( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Parm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Parm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2Parm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2Parm.SetRange(min, max); return true; } @@ -1281,14 +1170,12 @@ bool CPrimitiveTemplate::ParseSize2Parm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Flags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Flags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE2_SHIFT ); + mFlags |= (flags << FX_SIZE2_SHIFT); return true; } @@ -1305,13 +1192,11 @@ bool CPrimitiveTemplate::ParseSize2Flags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthStart.SetRange(min, max); return true; } @@ -1328,13 +1213,11 @@ bool CPrimitiveTemplate::ParseLengthStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthEnd.SetRange(min, max); return true; } @@ -1351,13 +1234,11 @@ bool CPrimitiveTemplate::ParseLengthEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthParm.SetRange(min, max); return true; } @@ -1374,14 +1255,12 @@ bool CPrimitiveTemplate::ParseLengthParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_LENGTH_SHIFT ); + mFlags |= (flags << FX_LENGTH_SHIFT); return true; } @@ -1398,22 +1277,18 @@ bool CPrimitiveTemplate::ParseLengthFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseShaders( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseShaders(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterShader( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterShader(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseShaders called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseShaders called with an empty list!\n"); return false; } return true; @@ -1429,22 +1304,18 @@ bool CPrimitiveTemplate::ParseShaders( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSounds( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseSounds(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterSound( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterSound(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseSounds called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseSounds called with an empty list!\n"); return false; } return true; @@ -1460,52 +1331,42 @@ bool CPrimitiveTemplate::ParseSounds( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseModels( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseModels(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterModel( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterModel(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseModels called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseModels called with an empty list!\n"); return false; } mFlags |= FX_ATTACHED_MODEL; return true; } -static bool ParseFX( const CGPProperty& grp, CFxScheduler& scheduler, CMediaHandles& handles, SFxHelper& helper, int& flags, int successFlags, gsl::czstring loadError, gsl::czstring emptyError ) -{ +static bool ParseFX(const CGPProperty &grp, CFxScheduler &scheduler, CMediaHandles &handles, SFxHelper &helper, int &flags, int successFlags, + gsl::czstring loadError, gsl::czstring emptyError) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; // TODO: string_view parameter - int handle = scheduler.RegisterEffect( std::string( value.begin(), value.end() ).c_str() ); - if( handle ) - { - handles.AddHandle( handle ); + int handle = scheduler.RegisterEffect(std::string(value.begin(), value.end()).c_str()); + if (handle) { + handles.AddHandle(handle); flags |= successFlags; - } - else - { - helper.Print( "%s", loadError ); + } else { + helper.Print("%s", loadError); } } } - if( !any ) - { - helper.Print( "%s", emptyError ); + if (!any) { + helper.Print("%s", emptyError); } return any; } @@ -1520,15 +1381,9 @@ static bool ParseFX( const CGPProperty& grp, CFxScheduler& scheduler, CMediaHand // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseImpactFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mImpactFxHandles, theFxHelper, - mFlags, FX_IMPACT_RUNS_FX | FX_APPLY_PHYSICS, - "FxTemplate: Impact effect file not found.\n", - "CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseImpactFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mImpactFxHandles, theFxHelper, mFlags, FX_IMPACT_RUNS_FX | FX_APPLY_PHYSICS, + "FxTemplate: Impact effect file not found.\n", "CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1541,15 +1396,9 @@ bool CPrimitiveTemplate::ParseImpactFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDeathFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mDeathFxHandles, theFxHelper, - mFlags, FX_DEATH_RUNS_FX, - "FxTemplate: Death effect file not found.\n", - "CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseDeathFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mDeathFxHandles, theFxHelper, mFlags, FX_DEATH_RUNS_FX, "FxTemplate: Death effect file not found.\n", + "CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1562,15 +1411,9 @@ bool CPrimitiveTemplate::ParseDeathFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseEmitterFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mEmitterFxHandles, theFxHelper, - mFlags, FX_EMIT_FX, - "FxTemplate: Emitter effect file not found.\n", - "CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseEmitterFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mEmitterFxHandles, theFxHelper, mFlags, FX_EMIT_FX, "FxTemplate: Emitter effect file not found.\n", + "CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1583,30 +1426,19 @@ bool CPrimitiveTemplate::ParseEmitterFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePlayFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mPlayFxHandles, theFxHelper, - mFlags, 0, - "FxTemplate: Effect file not found.\n", - "CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParsePlayFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mPlayFxHandles, theFxHelper, mFlags, 0, "FxTemplate: Effect file not found.\n", + "CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n"); } -bool CPrimitiveTemplate::ParseGroup( const CGPGroup& grp, const StringViewIMap< ParseMethod >& parseMethods, gsl::czstring name ) -{ - for( auto& cur : grp.GetProperties() ) - { - auto pos = parseMethods.find( cur.GetName() ); - if( pos == parseMethods.end() ) - { - theFxHelper.Print( "Unknown key parsing %s group!", name ); - } - else - { +bool CPrimitiveTemplate::ParseGroup(const CGPGroup &grp, const StringViewIMap &parseMethods, gsl::czstring name) { + for (auto &cur : grp.GetProperties()) { + auto pos = parseMethods.find(cur.GetName()); + if (pos == parseMethods.end()) { + theFxHelper.Print("Unknown key parsing %s group!", name); + } else { ParseMethod method = pos->second; - ( this->*method )( cur.GetTopValue() ); + (this->*method)(cur.GetTopValue()); } } return true; @@ -1623,20 +1455,17 @@ bool CPrimitiveTemplate::ParseGroup( const CGPGroup& grp, const StringViewIMap< // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGB( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseRGBStart }, +bool CPrimitiveTemplate::ParseRGB(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseRGBStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseRGBEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseRGBEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseRGBParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseRGBParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseRGBParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseRGBParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseRGBFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseRGBFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseRGBFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseRGBFlags}, }; - return ParseGroup( grp, parseMethods, "RGB" ); + return ParseGroup(grp, parseMethods, "RGB"); } //------------------------------------------------------ @@ -1650,20 +1479,17 @@ bool CPrimitiveTemplate::ParseRGB( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlpha( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseAlphaStart }, +bool CPrimitiveTemplate::ParseAlpha(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseAlphaStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseAlphaEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseAlphaEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseAlphaParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseAlphaParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseAlphaParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseAlphaParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseAlphaFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseAlphaFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseAlphaFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseAlphaFlags}, }; - return ParseGroup( grp, parseMethods, "Alpha" ); + return ParseGroup(grp, parseMethods, "Alpha"); } //------------------------------------------------------ @@ -1677,20 +1503,17 @@ bool CPrimitiveTemplate::ParseAlpha( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseSizeStart }, +bool CPrimitiveTemplate::ParseSize(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseSizeStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseSizeEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseSizeEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseSizeParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseSizeParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseSizeParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseSizeParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseSizeFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseSizeFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseSizeFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseSizeFlags}, }; - return ParseGroup( grp, parseMethods, "Size" ); + return ParseGroup(grp, parseMethods, "Size"); } //------------------------------------------------------ @@ -1704,20 +1527,17 @@ bool CPrimitiveTemplate::ParseSize( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseSize2Start }, +bool CPrimitiveTemplate::ParseSize2(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseSize2Start}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseSize2End }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseSize2End}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseSize2Parm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseSize2Parm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseSize2Parm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseSize2Parm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseSize2Flags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseSize2Flags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseSize2Flags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseSize2Flags}, }; - return ParseGroup( grp, parseMethods, "Size2" ); + return ParseGroup(grp, parseMethods, "Size2"); } //------------------------------------------------------ @@ -1731,144 +1551,124 @@ bool CPrimitiveTemplate::ParseSize2( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLength( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseLengthStart }, +bool CPrimitiveTemplate::ParseLength(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseLengthStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseLengthEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseLengthEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseLengthParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseLengthParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseLengthParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseLengthParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseLengthFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseLengthFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseLengthFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseLengthFlags}, }; - return ParseGroup( grp, parseMethods, "Length" ); + return ParseGroup(grp, parseMethods, "Length"); } - // Parse a primitive, apply defaults first, grab any base level // key pairs, then process any sub groups we may contain. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePrimitive( const CGPGroup& grp ) -{ +bool CPrimitiveTemplate::ParsePrimitive(const CGPGroup &grp) { // Property - for( auto& prop : grp.GetProperties() ) - { + for (auto &prop : grp.GetProperties()) { // Single Value Parsing { - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "count" ), &CPrimitiveTemplate::ParseCount }, - { CSTRING_VIEW( "life" ), &CPrimitiveTemplate::ParseLife }, - { CSTRING_VIEW( "delay" ), &CPrimitiveTemplate::ParseDelay }, - { CSTRING_VIEW( "bounce" ), &CPrimitiveTemplate::ParseElasticity }, - { CSTRING_VIEW( "intensity" ), &CPrimitiveTemplate::ParseElasticity }, - { CSTRING_VIEW( "min" ), &CPrimitiveTemplate::ParseMin }, - { CSTRING_VIEW( "max" ), &CPrimitiveTemplate::ParseMax }, - { CSTRING_VIEW( "angle" ), &CPrimitiveTemplate::ParseAngle }, - { CSTRING_VIEW( "angles" ), &CPrimitiveTemplate::ParseAngle }, - { CSTRING_VIEW( "angleDelta" ), &CPrimitiveTemplate::ParseAngleDelta }, - { CSTRING_VIEW( "velocity" ), &CPrimitiveTemplate::ParseVelocity }, - { CSTRING_VIEW( "vel" ), &CPrimitiveTemplate::ParseVelocity }, - { CSTRING_VIEW( "acceleration" ), &CPrimitiveTemplate::ParseAcceleration }, - { CSTRING_VIEW( "accel" ), &CPrimitiveTemplate::ParseAcceleration }, - { CSTRING_VIEW( "gravity" ), &CPrimitiveTemplate::ParseGravity }, - { CSTRING_VIEW( "density" ), &CPrimitiveTemplate::ParseDensity }, - { CSTRING_VIEW( "variance" ), &CPrimitiveTemplate::ParseVariance }, - { CSTRING_VIEW( "origin" ), &CPrimitiveTemplate::ParseOrigin1 }, - { CSTRING_VIEW( "origin2" ), &CPrimitiveTemplate::ParseOrigin2 }, - { CSTRING_VIEW( "radius" ), &CPrimitiveTemplate::ParseRadius }, - { CSTRING_VIEW( "height" ), &CPrimitiveTemplate::ParseHeight }, - { CSTRING_VIEW( "wind" ), &CPrimitiveTemplate::ParseWindModifier }, - { CSTRING_VIEW( "rotation" ), &CPrimitiveTemplate::ParseRotation }, - { CSTRING_VIEW( "rotationDelta" ), &CPrimitiveTemplate::ParseRotationDelta }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseFlags }, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseFlags }, - { CSTRING_VIEW( "spawnFlags" ), &CPrimitiveTemplate::ParseSpawnFlags }, - { CSTRING_VIEW( "spawnFlag" ), &CPrimitiveTemplate::ParseSpawnFlags }, + static StringViewIMap parseMethods{ + {CSTRING_VIEW("count"), &CPrimitiveTemplate::ParseCount}, + {CSTRING_VIEW("life"), &CPrimitiveTemplate::ParseLife}, + {CSTRING_VIEW("delay"), &CPrimitiveTemplate::ParseDelay}, + {CSTRING_VIEW("bounce"), &CPrimitiveTemplate::ParseElasticity}, + {CSTRING_VIEW("intensity"), &CPrimitiveTemplate::ParseElasticity}, + {CSTRING_VIEW("min"), &CPrimitiveTemplate::ParseMin}, + {CSTRING_VIEW("max"), &CPrimitiveTemplate::ParseMax}, + {CSTRING_VIEW("angle"), &CPrimitiveTemplate::ParseAngle}, + {CSTRING_VIEW("angles"), &CPrimitiveTemplate::ParseAngle}, + {CSTRING_VIEW("angleDelta"), &CPrimitiveTemplate::ParseAngleDelta}, + {CSTRING_VIEW("velocity"), &CPrimitiveTemplate::ParseVelocity}, + {CSTRING_VIEW("vel"), &CPrimitiveTemplate::ParseVelocity}, + {CSTRING_VIEW("acceleration"), &CPrimitiveTemplate::ParseAcceleration}, + {CSTRING_VIEW("accel"), &CPrimitiveTemplate::ParseAcceleration}, + {CSTRING_VIEW("gravity"), &CPrimitiveTemplate::ParseGravity}, + {CSTRING_VIEW("density"), &CPrimitiveTemplate::ParseDensity}, + {CSTRING_VIEW("variance"), &CPrimitiveTemplate::ParseVariance}, + {CSTRING_VIEW("origin"), &CPrimitiveTemplate::ParseOrigin1}, + {CSTRING_VIEW("origin2"), &CPrimitiveTemplate::ParseOrigin2}, + {CSTRING_VIEW("radius"), &CPrimitiveTemplate::ParseRadius}, + {CSTRING_VIEW("height"), &CPrimitiveTemplate::ParseHeight}, + {CSTRING_VIEW("wind"), &CPrimitiveTemplate::ParseWindModifier}, + {CSTRING_VIEW("rotation"), &CPrimitiveTemplate::ParseRotation}, + {CSTRING_VIEW("rotationDelta"), &CPrimitiveTemplate::ParseRotationDelta}, + {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseFlags}, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseFlags}, + {CSTRING_VIEW("spawnFlags"), &CPrimitiveTemplate::ParseSpawnFlags}, + {CSTRING_VIEW("spawnFlag"), &CPrimitiveTemplate::ParseSpawnFlags}, }; - auto pos = parseMethods.find( prop.GetName() ); - if( pos != parseMethods.end() ) - { + auto pos = parseMethods.find(prop.GetName()); + if (pos != parseMethods.end()) { ParseMethod method = pos->second; - ( this->*method )( prop.GetTopValue() ); + (this->*method)(prop.GetTopValue()); continue; } } // Property Parsing { - using PropertyParseMethod = bool( CPrimitiveTemplate::* )( const CGPProperty& ); - static StringViewIMap< PropertyParseMethod > parseMethods{ - { CSTRING_VIEW( "shaders" ), &CPrimitiveTemplate::ParseShaders }, - { CSTRING_VIEW( "shader" ), &CPrimitiveTemplate::ParseShaders }, - { CSTRING_VIEW( "models" ), &CPrimitiveTemplate::ParseModels }, - { CSTRING_VIEW( "model" ), &CPrimitiveTemplate::ParseModels }, - { CSTRING_VIEW( "sounds" ), &CPrimitiveTemplate::ParseSounds }, - { CSTRING_VIEW( "sound" ), &CPrimitiveTemplate::ParseSounds }, - { CSTRING_VIEW( "impactfx" ), &CPrimitiveTemplate::ParseImpactFxStrings }, - { CSTRING_VIEW( "deathfx" ), &CPrimitiveTemplate::ParseDeathFxStrings }, - { CSTRING_VIEW( "emitfx" ), &CPrimitiveTemplate::ParseEmitterFxStrings }, - { CSTRING_VIEW( "playfx" ), &CPrimitiveTemplate::ParsePlayFxStrings }, + using PropertyParseMethod = bool (CPrimitiveTemplate::*)(const CGPProperty &); + static StringViewIMap parseMethods{ + {CSTRING_VIEW("shaders"), &CPrimitiveTemplate::ParseShaders}, + {CSTRING_VIEW("shader"), &CPrimitiveTemplate::ParseShaders}, + {CSTRING_VIEW("models"), &CPrimitiveTemplate::ParseModels}, + {CSTRING_VIEW("model"), &CPrimitiveTemplate::ParseModels}, + {CSTRING_VIEW("sounds"), &CPrimitiveTemplate::ParseSounds}, + {CSTRING_VIEW("sound"), &CPrimitiveTemplate::ParseSounds}, + {CSTRING_VIEW("impactfx"), &CPrimitiveTemplate::ParseImpactFxStrings}, + {CSTRING_VIEW("deathfx"), &CPrimitiveTemplate::ParseDeathFxStrings}, + {CSTRING_VIEW("emitfx"), &CPrimitiveTemplate::ParseEmitterFxStrings}, + {CSTRING_VIEW("playfx"), &CPrimitiveTemplate::ParsePlayFxStrings}, }; - auto pos = parseMethods.find( prop.GetName() ); - if( pos != parseMethods.end() ) - { + auto pos = parseMethods.find(prop.GetName()); + if (pos != parseMethods.end()) { PropertyParseMethod method = pos->second; - ( this->*method )( prop ); + (this->*method)(prop); continue; } } // Special Cases - if( Q::stricmp( prop.GetName(), CSTRING_VIEW( "cullrange" ) ) == Q::Ordering::EQ ) - { - mCullRange = Q::svtoi( prop.GetTopValue() ); + if (Q::stricmp(prop.GetName(), CSTRING_VIEW("cullrange")) == Q::Ordering::EQ) { + mCullRange = Q::svtoi(prop.GetTopValue()); mCullRange *= mCullRange; // Square - } - else if( Q::stricmp( prop.GetName(), CSTRING_VIEW( "name" ) ) == Q::Ordering::EQ ) - { - if( !prop.GetTopValue().empty() ) - { + } else if (Q::stricmp(prop.GetName(), CSTRING_VIEW("name")) == Q::Ordering::EQ) { + if (!prop.GetTopValue().empty()) { // just stash the descriptive name of the primitive - std::size_t len = std::min< std::size_t >( prop.GetTopValue().size(), FX_MAX_PRIM_NAME - 1 ); + std::size_t len = std::min(prop.GetTopValue().size(), FX_MAX_PRIM_NAME - 1); auto begin = prop.GetTopValue().begin(); - std::copy( begin, begin + len, &mName[ 0 ] ); - mName[ len ] = '\0'; + std::copy(begin, begin + len, &mName[0]); + mName[len] = '\0'; } } // Error - else - { - theFxHelper.Print( "Unknown key parsing an effect primitive!\n" ); + else { + theFxHelper.Print("Unknown key parsing an effect primitive!\n"); } } - for( auto& subGrp : grp.GetSubGroups() ) - { - using GroupParseMethod = bool ( CPrimitiveTemplate::* )( const CGPGroup& ); - static StringViewIMap< GroupParseMethod > parseMethods{ - { CSTRING_VIEW( "rgb" ), &CPrimitiveTemplate::ParseRGB }, + for (auto &subGrp : grp.GetSubGroups()) { + using GroupParseMethod = bool (CPrimitiveTemplate::*)(const CGPGroup &); + static StringViewIMap parseMethods{ + {CSTRING_VIEW("rgb"), &CPrimitiveTemplate::ParseRGB}, - { CSTRING_VIEW( "alpha" ), &CPrimitiveTemplate::ParseAlpha }, + {CSTRING_VIEW("alpha"), &CPrimitiveTemplate::ParseAlpha}, - { CSTRING_VIEW( "size" ), &CPrimitiveTemplate::ParseSize }, - { CSTRING_VIEW( "width" ), &CPrimitiveTemplate::ParseSize }, + {CSTRING_VIEW("size"), &CPrimitiveTemplate::ParseSize}, {CSTRING_VIEW("width"), &CPrimitiveTemplate::ParseSize}, - { CSTRING_VIEW( "size2" ), &CPrimitiveTemplate::ParseSize2 }, - { CSTRING_VIEW( "width2" ), &CPrimitiveTemplate::ParseSize2 }, + {CSTRING_VIEW("size2"), &CPrimitiveTemplate::ParseSize2}, {CSTRING_VIEW("width2"), &CPrimitiveTemplate::ParseSize2}, - { CSTRING_VIEW( "length" ), &CPrimitiveTemplate::ParseLength }, - { CSTRING_VIEW( "height" ), &CPrimitiveTemplate::ParseLength }, + {CSTRING_VIEW("length"), &CPrimitiveTemplate::ParseLength}, {CSTRING_VIEW("height"), &CPrimitiveTemplate::ParseLength}, }; - auto pos = parseMethods.find( subGrp.GetName() ); - if( pos == parseMethods.end() ) - { - theFxHelper.Print( "Unknown group key parsing a particle!\n" ); - } - else - { + auto pos = parseMethods.find(subGrp.GetName()); + if (pos == parseMethods.end()) { + theFxHelper.Print("Unknown group key parsing a particle!\n"); + } else { GroupParseMethod method = pos->second; - ( this->*method )( subGrp ); + (this->*method)(subGrp); } } return true; diff --git a/code/cgame/FxUtil.cpp b/code/cgame/FxUtil.cpp index 499dad065c..7f13582ebb 100644 --- a/code/cgame/FxUtil.cpp +++ b/code/cgame/FxUtil.cpp @@ -23,45 +23,41 @@ along with this program; if not, see . #include "common_headers.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif -vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +vec3_t WHITE = {1.0f, 1.0f, 1.0f}; -struct SEffectList -{ +struct SEffectList { CEffect *mEffect; - int mKillTime; - bool mPortal; + int mKillTime; + bool mPortal; }; -#define PI 3.14159f +#define PI 3.14159f -SEffectList effectList[MAX_EFFECTS]; -SEffectList *nextValidEffect; -SFxHelper theFxHelper; +SEffectList effectList[MAX_EFFECTS]; +SEffectList *nextValidEffect; +SFxHelper theFxHelper; -int activeFx = 0; -int mMax = 0; -int mMaxTime = 0; -int drawnFx; -int mParticles; -int mOParticles; -int mLines; -int mTails; -qboolean fxInitialized = qfalse; +int activeFx = 0; +int mMax = 0; +int mMaxTime = 0; +int drawnFx; +int mParticles; +int mOParticles; +int mLines; +int mTails; +qboolean fxInitialized = qfalse; //------------------------- // FX_Free // // Frees all FX //------------------------- -bool FX_Free( void ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +bool FX_Free(void) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -79,12 +75,9 @@ bool FX_Free( void ) // // Frees all active FX but leaves the templates //------------------------- -void FX_Stop( void ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +void FX_Stop(void) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -101,14 +94,11 @@ void FX_Stop( void ) // // Preps system for use //------------------------- -int FX_Init( void ) -{ - if ( fxInitialized == qfalse ) - { +int FX_Init(void) { + if (fxInitialized == qfalse) { fxInitialized = qtrue; - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { + for (int i = 0; i < MAX_EFFECTS; i++) { effectList[i].mEffect = 0; } } @@ -129,12 +119,10 @@ int FX_Init( void ) return true; } - //------------------------- // FX_FreeMember //------------------------- -static void FX_FreeMember( SEffectList *obj ) -{ +static void FX_FreeMember(SEffectList *obj) { obj->mEffect->Die(); delete obj->mEffect; obj->mEffect = 0; @@ -145,7 +133,6 @@ static void FX_FreeMember( SEffectList *obj ) activeFx--; } - //------------------------- // FX_GetValidEffect // @@ -154,58 +141,48 @@ static void FX_FreeMember( SEffectList *obj ) // Note - in the editor, this function may return NULL, indicating that all // effects are being stopped. //------------------------- -static SEffectList *FX_GetValidEffect() -{ - if ( nextValidEffect->mEffect == 0 ) - { +static SEffectList *FX_GetValidEffect() { + if (nextValidEffect->mEffect == 0) { return nextValidEffect; } - int i; - SEffectList *ef; + int i; + SEffectList *ef; // Blah..plow through the list till we find something that is currently untainted - for ( i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++ ) - { - if ( ef->mEffect == 0 ) - { + for (i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++) { + if (ef->mEffect == 0) { return ef; } } // report the error. #ifndef FINAL_BUILD - theFxHelper.Print( "FX system out of effects\n" ); + theFxHelper.Print("FX system out of effects\n"); #endif // Hmmm.. just trashing the first effect in the list is a poor approach - FX_FreeMember( &effectList[0] ); + FX_FreeMember(&effectList[0]); // Recursive call return nextValidEffect; } - //------------------------- // FX_ActiveFx // // Returns whether these are any active or scheduled effects //------------------------- -bool FX_ActiveFx(void) -{ - return ((activeFx > 0) || (theFxScheduler.NumScheduledFx() > 0)); -} - +bool FX_ActiveFx(void) { return ((activeFx > 0) || (theFxScheduler.NumScheduledFx() > 0)); } //------------------------- // FX_Add // // Adds all fx to the view //------------------------- -void FX_Add( bool portal ) -{ - int i; - SEffectList *ef; +void FX_Add(bool portal) { + int i; + SEffectList *ef; drawnFx = 0; mParticles = 0; @@ -213,362 +190,271 @@ void FX_Add( bool portal ) mLines = 0; mTails = 0; - int numFx = activeFx; //but stop when there can't be any more left! - for ( i = 0, ef = effectList; i < MAX_EFFECTS && numFx; i++, ef++ ) - { - if ( ef->mEffect != 0) - { + int numFx = activeFx; // but stop when there can't be any more left! + for (i = 0, ef = effectList; i < MAX_EFFECTS && numFx; i++, ef++) { + if (ef->mEffect != 0) { --numFx; - if (portal != ef->mPortal) - { - continue; //this one does not render in this scene + if (portal != ef->mPortal) { + continue; // this one does not render in this scene } // Effect is active - if ( theFxHelper.mTime > ef->mKillTime ) - { + if (theFxHelper.mTime > ef->mKillTime) { // Clean up old effects, calling any death effects as needed // this flag just has to be cleared otherwise death effects might not happen correctly - ef->mEffect->ClearFlags( FX_KILL_ON_IMPACT ); - FX_FreeMember( ef ); - } - else - { - if ( ef->mEffect->Update() == false ) - { + ef->mEffect->ClearFlags(FX_KILL_ON_IMPACT); + FX_FreeMember(ef); + } else { + if (ef->mEffect->Update() == false) { // We've been marked for death - FX_FreeMember( ef ); + FX_FreeMember(ef); continue; } } } } - if ( fx_debug.integer == 2 && !portal ) - { + if (fx_debug.integer == 2 && !portal) { if (theFxHelper.mFrameTime > 100 || theFxHelper.mFrameTime < 5) - theFxHelper.Print( "theFxHelper.mFrameTime = %i\n", theFxHelper.mFrameTime ); + theFxHelper.Print("theFxHelper.mFrameTime = %i\n", theFxHelper.mFrameTime); } - if ( fx_debug.integer == 1 && !portal ) - { - if ( theFxHelper.mTime > mMaxTime ) - { + if (fx_debug.integer == 1 && !portal) { + if (theFxHelper.mTime > mMaxTime) { // decay pretty harshly when we do it mMax *= 0.9f; mMaxTime = theFxHelper.mTime + 200; // decay 5 times a second if we haven't set a new max } - if ( activeFx > mMax ) - { + if (activeFx > mMax) { // but we can never be less that the current activeFx count mMax = activeFx; mMaxTime = theFxHelper.mTime + 4000; // since we just increased the max, hold it for at least 4 seconds } // Particles - if ( mParticles > 500 ) - { - theFxHelper.Print( ">Particles ^1%4i ", mParticles ); - } - else if ( mParticles > 250 ) - { - theFxHelper.Print( ">Particles ^3%4i ", mParticles ); - } - else - { - theFxHelper.Print( ">Particles %4i ", mParticles ); + if (mParticles > 500) { + theFxHelper.Print(">Particles ^1%4i ", mParticles); + } else if (mParticles > 250) { + theFxHelper.Print(">Particles ^3%4i ", mParticles); + } else { + theFxHelper.Print(">Particles %4i ", mParticles); } // Lines - if ( mLines > 500 ) - { - theFxHelper.Print( ">Lines ^1%4i\n", mLines ); - } - else if ( mLines > 250 ) - { - theFxHelper.Print( ">Lines ^3%4i\n", mLines ); - } - else - { - theFxHelper.Print( ">Lines %4i\n", mLines ); + if (mLines > 500) { + theFxHelper.Print(">Lines ^1%4i\n", mLines); + } else if (mLines > 250) { + theFxHelper.Print(">Lines ^3%4i\n", mLines); + } else { + theFxHelper.Print(">Lines %4i\n", mLines); } // OParticles - if ( mOParticles > 500 ) - { - theFxHelper.Print( ">OParticles ^1%4i ", mOParticles ); - } - else if ( mOParticles > 250 ) - { - theFxHelper.Print( ">OParticles ^3%4i ", mOParticles ); - } - else - { - theFxHelper.Print( ">OParticles %4i ", mOParticles ); + if (mOParticles > 500) { + theFxHelper.Print(">OParticles ^1%4i ", mOParticles); + } else if (mOParticles > 250) { + theFxHelper.Print(">OParticles ^3%4i ", mOParticles); + } else { + theFxHelper.Print(">OParticles %4i ", mOParticles); } // Tails - if ( mTails > 400 ) - { - theFxHelper.Print( ">Tails ^1%4i\n", mTails ); - } - else if ( mTails > 200 ) - { - theFxHelper.Print( ">Tails ^3%4i\n", mTails ); - } - else - { - theFxHelper.Print( ">Tails %4i\n", mTails ); + if (mTails > 400) { + theFxHelper.Print(">Tails ^1%4i\n", mTails); + } else if (mTails > 200) { + theFxHelper.Print(">Tails ^3%4i\n", mTails); + } else { + theFxHelper.Print(">Tails %4i\n", mTails); } // Active - if ( activeFx > 600 ) - { - theFxHelper.Print( ">Active ^1%4i ", activeFx ); - } - else if ( activeFx > 400 ) - { - theFxHelper.Print( ">Active ^3%4i ", activeFx ); - } - else - { - theFxHelper.Print( ">Active %4i ", activeFx ); + if (activeFx > 600) { + theFxHelper.Print(">Active ^1%4i ", activeFx); + } else if (activeFx > 400) { + theFxHelper.Print(">Active ^3%4i ", activeFx); + } else { + theFxHelper.Print(">Active %4i ", activeFx); } // Drawn - if ( drawnFx > 600 ) - { - theFxHelper.Print( ">Drawn ^1%4i ", drawnFx ); - } - else if ( drawnFx > 400 ) - { - theFxHelper.Print( ">Drawn ^3%4i ", drawnFx ); - } - else - { - theFxHelper.Print( ">Drawn %4i ", drawnFx ); + if (drawnFx > 600) { + theFxHelper.Print(">Drawn ^1%4i ", drawnFx); + } else if (drawnFx > 400) { + theFxHelper.Print(">Drawn ^3%4i ", drawnFx); + } else { + theFxHelper.Print(">Drawn %4i ", drawnFx); } // Max - if ( mMax > 600 ) - { - theFxHelper.Print( ">Max ^1%4i ", mMax ); - } - else if ( mMax > 400 ) - { - theFxHelper.Print( ">Max ^3%4i ", mMax ); - } - else - { - theFxHelper.Print( ">Max %4i ", mMax ); + if (mMax > 600) { + theFxHelper.Print(">Max ^1%4i ", mMax); + } else if (mMax > 400) { + theFxHelper.Print(">Max ^3%4i ", mMax); + } else { + theFxHelper.Print(">Max %4i ", mMax); } // Scheduled - if ( theFxScheduler.NumScheduledFx() > 100 ) - { - theFxHelper.Print( ">Scheduled ^1%4i\n", theFxScheduler.NumScheduledFx() ); - } - else if ( theFxScheduler.NumScheduledFx() > 50 ) - { - theFxHelper.Print( ">Scheduled ^3%4i\n", theFxScheduler.NumScheduledFx() ); - } - else - { - theFxHelper.Print( ">Scheduled %4i\n", theFxScheduler.NumScheduledFx() ); + if (theFxScheduler.NumScheduledFx() > 100) { + theFxHelper.Print(">Scheduled ^1%4i\n", theFxScheduler.NumScheduledFx()); + } else if (theFxScheduler.NumScheduledFx() > 50) { + theFxHelper.Print(">Scheduled ^3%4i\n", theFxScheduler.NumScheduledFx()); + } else { + theFxHelper.Print(">Scheduled %4i\n", theFxScheduler.NumScheduledFx()); } } } - //------------------------- // FX_AddPrimitive // // Note - in the editor, this function may change *pEffect to NULL, indicating that // all effects are being stopped. //------------------------- -extern bool gEffectsInPortal; //from FXScheduler.cpp so i don't have to pass it in on EVERY FX_ADD* -void FX_AddPrimitive( CEffect **pEffect, int killTime ) -{ +extern bool gEffectsInPortal; // from FXScheduler.cpp so i don't have to pass it in on EVERY FX_ADD* +void FX_AddPrimitive(CEffect **pEffect, int killTime) { SEffectList *item = FX_GetValidEffect(); item->mEffect = *pEffect; item->mKillTime = theFxHelper.mTime + killTime; - item->mPortal = gEffectsInPortal; //global set in AddScheduledEffects + item->mPortal = gEffectsInPortal; // global set in AddScheduledEffects activeFx++; // Stash these in the primitive so it has easy access to the vals - (*pEffect)->SetTimeStart( theFxHelper.mTime ); - (*pEffect)->SetTimeEnd( theFxHelper.mTime + killTime ); + (*pEffect)->SetTimeStart(theFxHelper.mTime); + (*pEffect)->SetTimeEnd(theFxHelper.mTime + killTime); } - //------------------------- // FX_AddParticle //------------------------- -CParticle *FX_AddParticle( int clientID, const vec3_t org, const vec3_t vel, const vec3_t accel, float gravity, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - const vec3_t sRGB, const vec3_t eRGB, float rgbParm, - float rotation, float rotationDelta, - const vec3_t min, const vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CParticle *FX_AddParticle(int clientID, const vec3_t org, const vec3_t vel, const vec3_t accel, float gravity, float size1, float size2, float sizeParm, + float alpha1, float alpha2, float alphaParm, const vec3_t sRGB, const vec3_t eRGB, float rgbParm, float rotation, float rotationDelta, + const vec3_t min, const vec3_t max, float elasticity, int deathID, int impactID, int killTime, qhandle_t shader, int flags, + int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CParticle *fx = new CParticle; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } - fx->SetVel( vel ); - fx->SetAccel( accel ); - fx->SetGravity( gravity ); + fx->SetVel(vel); + fx->SetAccel(accel); + fx->SetGravity(gravity); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); - - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); + + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddLine //------------------------- -CLine *FX_AddLine( int clientID, vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int impactFX_id, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CLine *FX_AddLine(int clientID, vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, + vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int impactFX_id, int flags, int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CLine *fx = new CLine; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start ); //offset from bolt pos - fx->SetVel( end ); //vel is the vector offset from bolt+orgOffset - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset from bolt pos + fx->SetVel(end); // vel is the vector offset from bolt+orgOffset + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(start); + fx->SetOrigin2(end); } // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetImpactFxID( impactFX_id ); + fx->SetSTScale(1.0f, 1.0f); + fx->SetImpactFxID(impactFX_id); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -578,83 +464,65 @@ CLine *FX_AddLine( int clientID, vec3_t start, vec3_t end, float size1, float si //------------------------- // FX_AddElectricity //------------------------- -CElectricity *FX_AddElectricity( int clientID, vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - float chaos, int killTime, qhandle_t shader, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CElectricity *FX_AddElectricity(int clientID, vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, + vec3_t sRGB, vec3_t eRGB, float rgbParm, float chaos, int killTime, qhandle_t shader, int flags, int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CElectricity *fx = new CElectricity; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start );//offset - fx->SetVel( end ); //vel is the vector offset from bolt+orgOffset - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset + fx->SetVel(end); // vel is the vector offset from bolt+orgOffset + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(start); + fx->SetOrigin2(end); } // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); - fx->SetChaos( chaos ); + fx->SetShader(shader); + fx->SetFlags(flags); + fx->SetChaos(chaos); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL? - if ( fx ) - { + if (fx) { fx->Initialize(); } } @@ -662,103 +530,79 @@ CElectricity *FX_AddElectricity( int clientID, vec3_t start, vec3_t end, float s return fx; } - //------------------------- // FX_AddTail //------------------------- -CTail *FX_AddTail( int clientID, vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CTail *FX_AddTail(int clientID, vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float length1, float length2, float lengthParm, + float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int killTime, qhandle_t shader, int flags, int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CTail *fx = new CTail; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Length---------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetSTScale(1.0f, 1.0f); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -768,107 +612,82 @@ CTail *FX_AddTail( int clientID, vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddCylinder //------------------------- -CCylinder *FX_AddCylinder( int clientID, vec3_t start, vec3_t normal, - float size1s, float size1e, float sizeParm, - float size2s, float size2e, float size2Parm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, qhandle_t shader, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CCylinder *FX_AddCylinder(int clientID, vec3_t start, vec3_t normal, float size1s, float size1e, float sizeParm, float size2s, float size2e, float size2Parm, + float length1, float length2, float lengthParm, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, + int killTime, qhandle_t shader, int flags, int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CCylinder *fx = new CCylinder; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start );//offset - //NOTE: relative version doesn't ever use normal! - //fx->SetNormal( normal ); - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); - fx->SetNormal( normal ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset + // NOTE: relative version doesn't ever use normal! + // fx->SetNormal( normal ); + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(start); + fx->SetNormal(normal); } // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size1---------------- - fx->SetSizeStart( size1s ); - fx->SetSizeEnd( size1e ); + fx->SetSizeStart(size1s); + fx->SetSizeEnd(size1e); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Size2---------------- - fx->SetSize2Start( size2s ); - fx->SetSize2End( size2e ); + fx->SetSize2Start(size2s); + fx->SetSize2End(size2e); - if (( flags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { - fx->SetSize2Parm( size2Parm * PI * 0.001f ); - } - else if ( flags & FX_SIZE2_PARM_MASK ) - { - fx->SetSize2Parm( size2Parm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { + fx->SetSize2Parm(size2Parm * PI * 0.001f); + } else if (flags & FX_SIZE2_PARM_MASK) { + fx->SetSize2Parm(size2Parm * 0.01f * killTime + theFxHelper.mTime); } // Length1--------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -877,87 +696,69 @@ CCylinder *FX_AddCylinder( int clientID, vec3_t start, vec3_t normal, //------------------------- // FX_AddEmitter //------------------------- -CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t angs, vec3_t deltaAngs, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, int emitterID, - float density, float variance, - int killTime, qhandle_t model, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CEmitter *FX_AddEmitter(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, + vec3_t rgb1, vec3_t rgb2, float rgbParm, vec3_t angs, vec3_t deltaAngs, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int emitterID, float density, float variance, int killTime, qhandle_t model, int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CEmitter *fx = new CEmitter; - if ( fx ) - { - fx->SetOrigin1( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); - - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetAngles( angs ); - fx->SetAngleDelta( deltaAngs ); - fx->SetFlags( flags ); - fx->SetModel( model ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - fx->SetEmitterFxID( emitterID ); - fx->SetDensity( density ); - fx->SetVariance( variance ); - fx->SetOldTime( theFxHelper.mTime ); - - fx->SetLastOrg( org ); - fx->SetLastVel( vel ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); + + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetAngles(angs); + fx->SetAngleDelta(deltaAngs); + fx->SetFlags(flags); + fx->SetModel(model); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + fx->SetEmitterFxID(emitterID); + fx->SetDensity(density); + fx->SetVariance(variance); + fx->SetOldTime(theFxHelper.mTime); + + fx->SetLastOrg(org); + fx->SetLastVel(vel); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -967,299 +768,235 @@ CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddLight //------------------------- -CLight *FX_AddLight( vec3_t org, float size1, float size2, float sizeParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CLight *FX_AddLight(vec3_t org, float size1, float size2, float sizeParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, int killTime, int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CLight *fx = new CLight; - if ( fx ) - { - fx->SetOrigin1( org ); + if (fx) { + fx->SetOrigin1(org); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; - } - //------------------------- // FX_AddOrientedParticle //------------------------- -COrientedParticle *FX_AddOrientedParticle( int clientID, vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - float rotation, float rotationDelta, - vec3_t min, vec3_t max, float bounce, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags, int modelNum, int boltNum ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +COrientedParticle *FX_AddOrientedParticle(int clientID, vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, + float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, float rotation, + float rotationDelta, vec3_t min, vec3_t max, float bounce, int deathID, int impactID, int killTime, qhandle_t shader, + int flags, int modelNum, int boltNum) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } COrientedParticle *fx = new COrientedParticle; - if ( fx ) - { - if (flags&FX_RELATIVE && clientID>=0) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org );//offset - fx->SetNormalOffset( norm ); - fx->SetClient( clientID, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); - fx->SetNormal( norm ); + if (fx) { + if (flags & FX_RELATIVE && clientID >= 0) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); // offset + fx->SetNormalOffset(norm); + fx->SetClient(clientID, modelNum, boltNum); + } else { + fx->SetOrigin1(org); + fx->SetNormal(norm); } - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); - - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); + + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddPoly //------------------------- -CPoly *FX_AddPoly( vec3_t *verts, vec2_t *st, int numVerts, - vec3_t vel, vec3_t accel, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t rotationDelta, float bounce, int motionDelay, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 || !verts ) - { // disallow adding effects when the system is paused or the user doesn't pass in a vert array +CPoly *FX_AddPoly(vec3_t *verts, vec2_t *st, int numVerts, vec3_t vel, vec3_t accel, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, + float rgbParm, vec3_t rotationDelta, float bounce, int motionDelay, int killTime, qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1 || !verts) { // disallow adding effects when the system is paused or the user doesn't pass in a vert array return 0; } CPoly *fx = new CPoly; - if ( fx ) - { + if (fx) { // Do a cheesy copy of the verts and texture coords into our own structure - for ( int i = 0; i < numVerts; i++ ) - { - VectorCopy( verts[i], fx->mOrg[i] ); - VectorCopy2( st[i], fx->mST[i] ); + for (int i = 0; i < numVerts; i++) { + VectorCopy(verts[i], fx->mOrg[i]); + VectorCopy2(st[i], fx->mST[i]); } - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRot( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMotionTimeStamp( motionDelay ); - fx->SetNumVerts( numVerts ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRot(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMotionTimeStamp(motionDelay); + fx->SetNumVerts(numVerts); // Now that we've set our data up, let's process it into a useful format fx->PolyInit(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddBezier //------------------------- -CBezier *FX_AddBezier( const vec3_t start, const vec3_t end, - const vec3_t control1, const vec3_t control1Vel, - const vec3_t control2, const vec3_t control2Vel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - const vec3_t sRGB, const vec3_t eRGB, const float rgbParm, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CBezier *FX_AddBezier(const vec3_t start, const vec3_t end, const vec3_t control1, const vec3_t control1Vel, const vec3_t control2, const vec3_t control2Vel, + float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, const vec3_t sRGB, const vec3_t eRGB, + const float rgbParm, int killTime, qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CBezier *fx = new CBezier; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + fx->SetOrigin1(start); + fx->SetOrigin2(end); - fx->SetControlPoints( control1, control2 ); - fx->SetControlVel( control1Vel, control2Vel ); + fx->SetControlPoints(control1, control2); + fx->SetControlVel(control1Vel, control2Vel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1268,68 +1005,61 @@ CBezier *FX_AddBezier( const vec3_t start, const vec3_t end, //------------------------- // FX_AddFlash //------------------------- -CFlash *FX_AddFlash( vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CFlash *FX_AddFlash(vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CFlash *fx = new CFlash; - if ( fx ) - { - fx->SetOrigin1( origin ); + if (fx) { + fx->SetOrigin1(origin); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } -/* // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + /* // Alpha---------------- + fx->SetAlphaStart( alpha1 ); + fx->SetAlphaEnd( alpha2 ); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); - } + if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) + { + fx->SetAlphaParm( alphaParm * PI * 0.001f ); + } + else if ( flags & FX_ALPHA_PARM_MASK ) + { + fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + } - // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + // Size---------------- + fx->SetSizeStart( size1 ); + fx->SetSizeEnd( size2 ); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } -*/ - fx->SetShader( shader ); - fx->SetFlags( flags ); + if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) + { + fx->SetSizeParm( sizeParm * PI * 0.001f ); + } + else if ( flags & FX_SIZE_PARM_MASK ) + { + fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + } + */ + fx->SetShader(shader); + fx->SetFlags(flags); -// fx->SetSTScale( 1.0f, 1.0f ); + // fx->SetSTScale( 1.0f, 1.0f ); fx->Init(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1345,76 +1075,33 @@ CFlash *FX_AddFlash( vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, //------------------------------------------------------- //--------------------------------------------------- -void FX_AddSprite( vec3_t origin, vec3_t vel, vec3_t accel, - float scale, float dscale, - float sAlpha, float eAlpha, - float rotation, float bounce, - int life, qhandle_t shader, int flags ) -{ - FX_AddParticle( -1, origin, vel, accel, 0, scale, scale, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - WHITE, WHITE, 0, - rotation, 0, - vec3_origin, vec3_origin, bounce, - 0, 0, - life, shader, flags ); +void FX_AddSprite(vec3_t origin, vec3_t vel, vec3_t accel, float scale, float dscale, float sAlpha, float eAlpha, float rotation, float bounce, int life, + qhandle_t shader, int flags) { + FX_AddParticle(-1, origin, vel, accel, 0, scale, scale, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, WHITE, WHITE, 0, rotation, 0, vec3_origin, vec3_origin, bounce, + 0, 0, life, shader, flags); } //--------------------------------------------------- -void FX_AddSprite( vec3_t origin, vec3_t vel, vec3_t accel, - float scale, float dscale, - float sAlpha, float eAlpha, - vec3_t sRGB, vec3_t eRGB, - float rotation, float bounce, - int life, qhandle_t shader, int flags ) -{ - FX_AddParticle( -1, origin, vel, accel, 0, scale, scale, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - sRGB, eRGB, 0, - rotation, 0, - vec3_origin, vec3_origin, bounce, - 0, 0, - life, shader, flags ); +void FX_AddSprite(vec3_t origin, vec3_t vel, vec3_t accel, float scale, float dscale, float sAlpha, float eAlpha, vec3_t sRGB, vec3_t eRGB, float rotation, + float bounce, int life, qhandle_t shader, int flags) { + FX_AddParticle(-1, origin, vel, accel, 0, scale, scale, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, sRGB, eRGB, 0, rotation, 0, vec3_origin, vec3_origin, bounce, 0, + 0, life, shader, flags); } //--------------------------------------------------- -void FX_AddLine( vec3_t start, vec3_t end, float stScale, - float width, float dwidth, - float sAlpha, float eAlpha, - int life, qhandle_t shader, int flags ) -{ - FX_AddLine( -1, start, end, width, width, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - WHITE, WHITE, 0, - life, shader, 0, 0 ); +void FX_AddLine(vec3_t start, vec3_t end, float stScale, float width, float dwidth, float sAlpha, float eAlpha, int life, qhandle_t shader, int flags) { + FX_AddLine(-1, start, end, width, width, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, WHITE, WHITE, 0, life, shader, 0, 0); } //--------------------------------------------------- -void FX_AddLine( vec3_t start, vec3_t end, float stScale, - float width, float dwidth, - float sAlpha, float eAlpha, - vec3_t sRGB, vec3_t eRGB, - int life, qhandle_t shader, int flags ) -{ - FX_AddLine( -1, start, end, width, width, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - sRGB, eRGB, 0, - life, shader, 0, flags ); +void FX_AddLine(vec3_t start, vec3_t end, float stScale, float width, float dwidth, float sAlpha, float eAlpha, vec3_t sRGB, vec3_t eRGB, int life, + qhandle_t shader, int flags) { + FX_AddLine(-1, start, end, width, width, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, sRGB, eRGB, 0, life, shader, 0, flags); } //--------------------------------------------------- -void FX_AddQuad( vec3_t origin, vec3_t normal, - vec3_t vel, vec3_t accel, - float sradius, float eradius, - float salpha, float ealpha, - vec3_t sRGB, vec3_t eRGB, - float rotation, int life, qhandle_t shader, int flags ) -{ - FX_AddOrientedParticle( -1, origin, normal, vel, accel, - sradius, eradius, 0.0f, - salpha, ealpha, 0.0f, - sRGB, eRGB, 0.0f, - rotation, 0.0f, - NULL, NULL, 0.0f, 0, 0, life, - shader, 0 ); +void FX_AddQuad(vec3_t origin, vec3_t normal, vec3_t vel, vec3_t accel, float sradius, float eradius, float salpha, float ealpha, vec3_t sRGB, vec3_t eRGB, + float rotation, int life, qhandle_t shader, int flags) { + FX_AddOrientedParticle(-1, origin, normal, vel, accel, sradius, eradius, 0.0f, salpha, ealpha, 0.0f, sRGB, eRGB, 0.0f, rotation, 0.0f, NULL, NULL, 0.0f, 0, + 0, life, shader, 0); } diff --git a/code/cgame/cg_camera.cpp b/code/cgame/cg_camera.cpp index 878a17dd3e..8683dcedb6 100644 --- a/code/cgame/cg_camera.cpp +++ b/code/cgame/cg_camera.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//Client camera controls for cinematics +// Client camera controls for cinematics #include "cg_headers.h" @@ -28,18 +28,18 @@ along with this program; if not, see . #include "../game/g_roff.h" -bool in_camera = false; -camera_t client_camera={}; -extern qboolean player_locked; +bool in_camera = false; +camera_t client_camera = {}; +extern qboolean player_locked; -extern gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match); -extern void G_UseTargets (gentity_t *ent, gentity_t *activator); -void CGCam_FollowDisable( void ); -void CGCam_TrackDisable( void ); -void CGCam_Distance( float distance, qboolean initLerp ); -void CGCam_DistanceDisable( void ); -extern qboolean CG_CalcFOVFromX( float fov_x ); -extern void WP_SaberCatch( gentity_t *self, gentity_t *saber, qboolean switchToSaber ); +extern gentity_t *G_Find(gentity_t *from, int fieldofs, const char *match); +extern void G_UseTargets(gentity_t *ent, gentity_t *activator); +void CGCam_FollowDisable(void); +void CGCam_TrackDisable(void); +void CGCam_Distance(float distance, qboolean initLerp); +void CGCam_DistanceDisable(void); +extern qboolean CG_CalcFOVFromX(float fov_x); +extern void WP_SaberCatch(gentity_t *self, gentity_t *saber, qboolean switchToSaber); /* TODO: @@ -59,12 +59,10 @@ CGCam_Init ------------------------- */ -void CGCam_Init( void ) -{ +void CGCam_Init(void) { extern qboolean qbVidRestartOccured; - if (!qbVidRestartOccured) - { - memset( &client_camera, 0, sizeof ( camera_t ) ); + if (!qbVidRestartOccured) { + memset(&client_camera, 0, sizeof(camera_t)); } } @@ -74,8 +72,7 @@ CGCam_Enable ------------------------- */ extern void CG_CalcVrect(void); -void CGCam_Enable( void ) -{ +void CGCam_Enable(void) { client_camera.bar_alpha = 0.0f; client_camera.bar_time = cg.time; @@ -83,46 +80,40 @@ void CGCam_Enable( void ) client_camera.bar_alpha_dest = 1.0f; client_camera.bar_height_source = 0.0f; - client_camera.bar_height_dest = 480/10; + client_camera.bar_height_dest = 480 / 10; client_camera.bar_height = 0.0f; client_camera.info_state |= CAMERA_BAR_FADING; - client_camera.FOV = CAMERA_DEFAULT_FOV; - client_camera.FOV2 = CAMERA_DEFAULT_FOV; + client_camera.FOV = CAMERA_DEFAULT_FOV; + client_camera.FOV2 = CAMERA_DEFAULT_FOV; in_camera = true; client_camera.next_roff_time = 0; - if ( g_entities[0].inuse && g_entities[0].client ) - { - //Player zero not allowed to do anything - VectorClear( g_entities[0].client->ps.velocity ); + if (g_entities[0].inuse && g_entities[0].client) { + // Player zero not allowed to do anything + VectorClear(g_entities[0].client->ps.velocity); g_entities[0].contents = 0; - if ( cg.zoomMode ) - { + if (cg.zoomMode) { // need to shut off some form of zooming cg.zoomMode = 0; } - if ( g_entities[0].client->ps.saberInFlight && g_entities[0].client->ps.saber[0].Active() ) - {//saber is out + if (g_entities[0].client->ps.saberInFlight && g_entities[0].client->ps.saber[0].Active()) { // saber is out gentity_t *saberent = &g_entities[g_entities[0].client->ps.saberEntityNum]; - if ( saberent ) - { - WP_SaberCatch( &g_entities[0], saberent, qfalse ); + if (saberent) { + WP_SaberCatch(&g_entities[0], saberent, qfalse); } } - for ( int i = 0; i < NUM_FORCE_POWERS; i++ ) - {//deactivate any active force powers + for (int i = 0; i < NUM_FORCE_POWERS; i++) { // deactivate any active force powers g_entities[0].client->ps.forcePowerDuration[i] = 0; -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); - if ( g_entities[0].client->ps.forcePowerDuration[i] || (g_entities[0].client->ps.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerStop( &g_entities[0], (forcePowers_t)i ); + extern void WP_ForcePowerStop(gentity_t * self, forcePowers_t forcePower); + if (g_entities[0].client->ps.forcePowerDuration[i] || (g_entities[0].client->ps.forcePowersActive & (1 << i))) { + WP_ForcePowerStop(&g_entities[0], (forcePowers_t)i); } } } @@ -133,8 +124,7 @@ CGCam_Disable ------------------------- */ -void CGCam_Disable( void ) -{ +void CGCam_Disable(void) { in_camera = false; client_camera.bar_alpha = 1.0f; @@ -143,27 +133,26 @@ void CGCam_Disable( void ) client_camera.bar_alpha_source = 1.0f; client_camera.bar_alpha_dest = 0.0f; - client_camera.bar_height_source = 480/10; + client_camera.bar_height_source = 480 / 10; client_camera.bar_height_dest = 0.0f; client_camera.info_state |= CAMERA_BAR_FADING; - if ( g_entities[0].inuse && g_entities[0].client ) - { - g_entities[0].contents = CONTENTS_BODY;//MASK_PLAYERSOLID; + if (g_entities[0].inuse && g_entities[0].client) { + g_entities[0].contents = CONTENTS_BODY; // MASK_PLAYERSOLID; } - gi.SendServerCommand( 0, "cts"); + gi.SendServerCommand(0, "cts"); - //if ( cg_skippingcin.integer ) - {//We're skipping the cinematic and it's over now + // if ( cg_skippingcin.integer ) + { // We're skipping the cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } - //we just came out of camera, so update cg.refdef.vieworg out of the camera's origin so the snapshot will know our new ori - VectorCopy( g_entities[0].currentOrigin, cg.refdef.vieworg); - VectorCopy( g_entities[0].client->ps.viewangles, cg.refdefViewAngles ); + // we just came out of camera, so update cg.refdef.vieworg out of the camera's origin so the snapshot will know our new ori + VectorCopy(g_entities[0].currentOrigin, cg.refdef.vieworg); + VectorCopy(g_entities[0].client->ps.viewangles, cg.refdefViewAngles); } /* @@ -172,10 +161,9 @@ CGCam_SetPosition ------------------------- */ -void CGCam_SetPosition( vec3_t org ) -{ - VectorCopy( org, client_camera.origin ); - VectorCopy( client_camera.origin, cg.refdef.vieworg ); +void CGCam_SetPosition(vec3_t org) { + VectorCopy(org, client_camera.origin); + VectorCopy(client_camera.origin, cg.refdef.vieworg); } /* @@ -184,26 +172,23 @@ CGCam_Move ------------------------- */ -void CGCam_Move( vec3_t dest, float duration ) -{ - if ( client_camera.info_state & CAMERA_ROFFING ) - { +void CGCam_Move(vec3_t dest, float duration) { + if (client_camera.info_state & CAMERA_ROFFING) { client_camera.info_state &= ~CAMERA_ROFFING; } CGCam_TrackDisable(); CGCam_DistanceDisable(); - if ( !duration ) - { + if (!duration) { client_camera.info_state &= ~CAMERA_MOVING; - CGCam_SetPosition( dest ); + CGCam_SetPosition(dest); return; } client_camera.info_state |= CAMERA_MOVING; - VectorCopy( dest, client_camera.origin2 ); + VectorCopy(dest, client_camera.origin2); client_camera.move_duration = duration; client_camera.move_time = cg.time; @@ -215,10 +200,9 @@ CGCam_SetAngles ------------------------- */ -void CGCam_SetAngles( vec3_t ang ) -{ - VectorCopy( ang, client_camera.angles ); - VectorCopy(client_camera.angles, cg.refdefViewAngles ); +void CGCam_SetAngles(vec3_t ang) { + VectorCopy(ang, client_camera.angles); + VectorCopy(client_camera.angles, cg.refdefViewAngles); } /* @@ -227,81 +211,57 @@ CGCam_Pan ------------------------- */ -void CGCam_Pan( vec3_t dest, vec3_t panDirection, float duration ) -{ - //vec3_t panDirection = {0, 0, 0}; - int i; - float delta1 , delta2; +void CGCam_Pan(vec3_t dest, vec3_t panDirection, float duration) { + // vec3_t panDirection = {0, 0, 0}; + int i; + float delta1, delta2; CGCam_FollowDisable(); CGCam_DistanceDisable(); - if ( !duration ) - { - CGCam_SetAngles( dest ); + if (!duration) { + CGCam_SetAngles(dest); client_camera.info_state &= ~CAMERA_PANNING; return; } - //FIXME: make the dest an absolute value, and pass in a - //panDirection as well. If a panDirection's axis value is - //zero, find the shortest difference for that axis. - //Store the delta in client_camera.angles2. - for( i = 0; i < 3; i++ ) - { - dest[i] = AngleNormalize360( dest[i] ); - delta1 = dest[i] - AngleNormalize360( client_camera.angles[i] ); - if ( delta1 < 0 ) - { + // FIXME: make the dest an absolute value, and pass in a + // panDirection as well. If a panDirection's axis value is + // zero, find the shortest difference for that axis. + // Store the delta in client_camera.angles2. + for (i = 0; i < 3; i++) { + dest[i] = AngleNormalize360(dest[i]); + delta1 = dest[i] - AngleNormalize360(client_camera.angles[i]); + if (delta1 < 0) { delta2 = delta1 + 360; - } - else - { + } else { delta2 = delta1 - 360; } - if ( !panDirection[i] ) - {//Didn't specify a direction, pick shortest - if( Q_fabs(delta1) < Q_fabs(delta2) ) - { + if (!panDirection[i]) { // Didn't specify a direction, pick shortest + if (Q_fabs(delta1) < Q_fabs(delta2)) { client_camera.angles2[i] = delta1; - } - else - { + } else { client_camera.angles2[i] = delta2; } - } - else if ( panDirection[i] < 0 ) - { - if( delta1 < 0 ) - { + } else if (panDirection[i] < 0) { + if (delta1 < 0) { client_camera.angles2[i] = delta1; - } - else if( delta1 > 0 ) - { + } else if (delta1 > 0) { client_camera.angles2[i] = delta2; - } - else - {//exact + } else { // exact client_camera.angles2[i] = 0; } - } - else if ( panDirection[i] > 0 ) - { - if( delta1 > 0 ) - { + } else if (panDirection[i] > 0) { + if (delta1 > 0) { client_camera.angles2[i] = delta1; - } - else if( delta1 < 0 ) - { + } else if (delta1 < 0) { client_camera.angles2[i] = delta2; - } - else - {//exact + } else { // exact client_camera.angles2[i] = 0; } } } - //VectorCopy( dest, client_camera.angles2 ); + // VectorCopy( dest, client_camera.angles2 ); client_camera.info_state |= CAMERA_PANNING; @@ -315,10 +275,7 @@ CGCam_SetRoll ------------------------- */ -void CGCam_SetRoll( float roll ) -{ - client_camera.angles[2] = roll; -} +void CGCam_SetRoll(float roll) { client_camera.angles[2] = roll; } /* ------------------------- @@ -326,19 +283,17 @@ CGCam_Roll ------------------------- */ -void CGCam_Roll( float dest, float duration ) -{ - if ( !duration ) - { - CGCam_SetRoll( dest ); +void CGCam_Roll(float dest, float duration) { + if (!duration) { + CGCam_SetRoll(dest); return; } - //FIXME/NOTE: this will override current panning!!! + // FIXME/NOTE: this will override current panning!!! client_camera.info_state |= CAMERA_PANNING; - VectorCopy( client_camera.angles, client_camera.angles2 ); - client_camera.angles2[2] = AngleDelta( dest, client_camera.angles[2] ); + VectorCopy(client_camera.angles, client_camera.angles2); + client_camera.angles2[2] = AngleDelta(dest, client_camera.angles[2]); client_camera.pan_duration = duration; client_camera.pan_time = cg.time; @@ -350,10 +305,7 @@ CGCam_SetFOV ------------------------- */ -void CGCam_SetFOV( float FOV ) -{ - client_camera.FOV = FOV; -} +void CGCam_SetFOV(float FOV) { client_camera.FOV = FOV; } /* ------------------------- @@ -361,46 +313,40 @@ CGCam_Zoom ------------------------- */ -void CGCam_Zoom( float FOV, float duration ) -{ - if ( !duration ) - { - CGCam_SetFOV( FOV ); +void CGCam_Zoom(float FOV, float duration) { + if (!duration) { + CGCam_SetFOV(FOV); return; } client_camera.info_state |= CAMERA_ZOOMING; - client_camera.FOV_time = cg.time; - client_camera.FOV2 = FOV; + client_camera.FOV_time = cg.time; + client_camera.FOV2 = FOV; client_camera.FOV_duration = duration; } -void CGCam_Zoom2( float FOV, float FOV2, float duration ) -{ - if ( !duration ) - { - CGCam_SetFOV( FOV2 ); +void CGCam_Zoom2(float FOV, float FOV2, float duration) { + if (!duration) { + CGCam_SetFOV(FOV2); return; } client_camera.info_state |= CAMERA_ZOOMING; - client_camera.FOV_time = cg.time; + client_camera.FOV_time = cg.time; client_camera.FOV = FOV; - client_camera.FOV2 = FOV2; + client_camera.FOV2 = FOV2; client_camera.FOV_duration = duration; } -void CGCam_ZoomAccel( float initialFOV, float fovVelocity, float fovAccel, float duration) -{ - if ( !duration ) - { +void CGCam_ZoomAccel(float initialFOV, float fovVelocity, float fovAccel, float duration) { + if (!duration) { return; } client_camera.info_state |= CAMERA_ACCEL; - client_camera.FOV_time = cg.time; + client_camera.FOV_time = cg.time; client_camera.FOV2 = initialFOV; client_camera.FOV_vel = fovVelocity; client_camera.FOV_acc = fovAccel; @@ -414,12 +360,11 @@ CGCam_Fade ------------------------- */ -void CGCam_SetFade( vec4_t dest ) -{//Instant completion +void CGCam_SetFade(vec4_t dest) { // Instant completion client_camera.info_state &= ~CAMERA_FADING; client_camera.fade_duration = 0; - VectorCopy4( dest, client_camera.fade_source ); - VectorCopy4( dest, client_camera.fade_color ); + VectorCopy4(dest, client_camera.fade_source); + VectorCopy4(dest, client_camera.fade_color); } /* @@ -428,16 +373,14 @@ CGCam_Fade ------------------------- */ -void CGCam_Fade( vec4_t source, vec4_t dest, float duration ) -{ - if ( !duration ) - { - CGCam_SetFade( dest ); +void CGCam_Fade(vec4_t source, vec4_t dest, float duration) { + if (!duration) { + CGCam_SetFade(dest); return; } - VectorCopy4( source, client_camera.fade_source ); - VectorCopy4( dest, client_camera.fade_dest ); + VectorCopy4(source, client_camera.fade_source); + VectorCopy4(dest, client_camera.fade_dest); client_camera.fade_duration = duration; client_camera.fade_time = cg.time; @@ -445,72 +388,57 @@ void CGCam_Fade( vec4_t source, vec4_t dest, float duration ) client_camera.info_state |= CAMERA_FADING; } -void CGCam_FollowDisable( void ) -{ +void CGCam_FollowDisable(void) { client_camera.info_state &= ~CAMERA_FOLLOWING; client_camera.cameraGroup[0] = 0; client_camera.cameraGroupZOfs = 0; client_camera.cameraGroupTag[0] = 0; } -void CGCam_TrackDisable( void ) -{ +void CGCam_TrackDisable(void) { client_camera.info_state &= ~CAMERA_TRACKING; client_camera.trackEntNum = ENTITYNUM_WORLD; } -void CGCam_DistanceDisable( void ) -{ - client_camera.distance = 0; -} +void CGCam_DistanceDisable(void) { client_camera.distance = 0; } /* ------------------------- CGCam_Follow ------------------------- */ -void CGCam_Follow( const char *cameraGroup, float speed, float initLerp ) -{ - //Clear any previous +void CGCam_Follow(const char *cameraGroup, float speed, float initLerp) { + // Clear any previous CGCam_FollowDisable(); - if(!cameraGroup || !cameraGroup[0]) - { + if (!cameraGroup || !cameraGroup[0]) { return; } - if ( Q_stricmp("none", (char *)cameraGroup) == 0 ) - {//Turn off all aiming + if (Q_stricmp("none", (char *)cameraGroup) == 0) { // Turn off all aiming return; } - if ( Q_stricmp("NULL", (char *)cameraGroup) == 0 ) - {//Turn off all aiming + if (Q_stricmp("NULL", (char *)cameraGroup) == 0) { // Turn off all aiming return; } - //NOTE: if this interrupts a pan before it's done, need to copy the cg.refdef.viewAngles to the camera.angles! + // NOTE: if this interrupts a pan before it's done, need to copy the cg.refdef.viewAngles to the camera.angles! client_camera.info_state |= CAMERA_FOLLOWING; client_camera.info_state &= ~CAMERA_PANNING; - //NULL terminate last char in case they type a name too long - Q_strncpyz( client_camera.cameraGroup, cameraGroup, sizeof(client_camera.cameraGroup) ); + // NULL terminate last char in case they type a name too long + Q_strncpyz(client_camera.cameraGroup, cameraGroup, sizeof(client_camera.cameraGroup)); - if ( speed ) - { + if (speed) { client_camera.followSpeed = speed; - } - else - { + } else { client_camera.followSpeed = 100.0f; } - if ( initLerp ) - { + if (initLerp) { client_camera.followInitLerp = qtrue; - } - else - { + } else { client_camera.followInitLerp = qfalse; } } @@ -526,8 +454,7 @@ Q3_CameraAutoAim ------------------------- */ -void CG_CameraAutoAim( const char *name ) -{ +void CG_CameraAutoAim(const char *name) { /* gentity_t *aimEnt = NULL; @@ -559,24 +486,21 @@ void CG_CameraAutoAim( const char *name ) CGCam_Track ------------------------- */ -void CGCam_Track( const char *trackName, float speed, float initLerp ) -{ - gentity_t *trackEnt = NULL; +void CGCam_Track(const char *trackName, float speed, float initLerp) { + gentity_t *trackEnt = NULL; CGCam_TrackDisable(); - if(Q_stricmp("none", (char *)trackName) == 0) - {//turn off tracking + if (Q_stricmp("none", (char *)trackName) == 0) { // turn off tracking return; } - //NOTE: if this interrupts a move before it's done, need to copy the cg.refdef.vieworg to the camera.origin! - //This will find a path_corner now, not a misc_camera_track + // NOTE: if this interrupts a move before it's done, need to copy the cg.refdef.vieworg to the camera.origin! + // This will find a path_corner now, not a misc_camera_track trackEnt = G_Find(NULL, FOFS(targetname), (char *)trackName); - if ( !trackEnt ) - { - gi.Printf(S_COLOR_RED"ERROR: %s camera track target not found\n", trackName); + if (!trackEnt) { + gi.Printf(S_COLOR_RED "ERROR: %s camera track target not found\n", trackName); return; } @@ -584,16 +508,13 @@ void CGCam_Track( const char *trackName, float speed, float initLerp ) client_camera.info_state &= ~CAMERA_MOVING; client_camera.trackEntNum = trackEnt->s.number; - client_camera.initSpeed = speed/10.0f; + client_camera.initSpeed = speed / 10.0f; client_camera.speed = speed; client_camera.nextTrackEntUpdateTime = cg.time; - if ( initLerp ) - { + if (initLerp) { client_camera.trackInitLerp = qtrue; - } - else - { + } else { client_camera.trackInitLerp = qfalse; } /* @@ -602,27 +523,24 @@ void CGCam_Track( const char *trackName, float speed, float initLerp ) } */ - //Set a moveDir - VectorSubtract( trackEnt->currentOrigin, client_camera.origin, client_camera.moveDir ); + // Set a moveDir + VectorSubtract(trackEnt->currentOrigin, client_camera.origin, client_camera.moveDir); - if ( !client_camera.trackInitLerp ) - {//want to snap to first position - //Snap to trackEnt's origin - VectorCopy( trackEnt->currentOrigin, client_camera.origin ); + if (!client_camera.trackInitLerp) { // want to snap to first position + // Snap to trackEnt's origin + VectorCopy(trackEnt->currentOrigin, client_camera.origin); - //Set new moveDir if trackEnt has a next path_corner - //Possible that track has no next point, in which case we won't be moving anyway - if ( trackEnt->target && trackEnt->target[0] ) - { - gentity_t *newTrackEnt = G_Find( NULL, FOFS(targetname), trackEnt->target ); - if ( newTrackEnt ) - { - VectorSubtract( newTrackEnt->currentOrigin, client_camera.origin, client_camera.moveDir ); + // Set new moveDir if trackEnt has a next path_corner + // Possible that track has no next point, in which case we won't be moving anyway + if (trackEnt->target && trackEnt->target[0]) { + gentity_t *newTrackEnt = G_Find(NULL, FOFS(targetname), trackEnt->target); + if (newTrackEnt) { + VectorSubtract(newTrackEnt->currentOrigin, client_camera.origin, client_camera.moveDir); } } } - VectorNormalize( client_camera.moveDir ); + VectorNormalize(client_camera.moveDir); } /* @@ -638,8 +556,7 @@ Q3_CameraAutoTrack ------------------------- */ -void CG_CameraAutoTrack( const char *name ) -{ +void CG_CameraAutoTrack(const char *name) { /* gentity_t *trackEnt = NULL; @@ -672,36 +589,28 @@ CGCam_Distance ------------------------- */ -void CGCam_Distance( float distance, float initLerp ) -{ +void CGCam_Distance(float distance, float initLerp) { client_camera.distance = distance; - if ( initLerp ) - { + if (initLerp) { client_camera.distanceInitLerp = qtrue; - } - else - { + } else { client_camera.distanceInitLerp = qfalse; } } //======================================================================================== +void CGCam_FollowUpdate(void) { + vec3_t center, dir, cameraAngles, vec, focus[MAX_CAMERA_GROUP_SUBJECTS]; // No more than 16 subjects in a cameraGroup + gentity_t *from = NULL; + centity_t *fromCent = NULL; + int num_subjects = 0, i; + qboolean focused = qfalse; -void CGCam_FollowUpdate ( void ) -{ - vec3_t center, dir, cameraAngles, vec, focus[MAX_CAMERA_GROUP_SUBJECTS];//No more than 16 subjects in a cameraGroup - gentity_t *from = NULL; - centity_t *fromCent = NULL; - int num_subjects = 0, i; - qboolean focused = qfalse; - - if ( client_camera.cameraGroup[0] ) - { - //Stay centered in my cameraGroup, if I have one - while( NULL != (from = G_Find(from, FOFS(cameraGroup), client_camera.cameraGroup))) - { + if (client_camera.cameraGroup[0]) { + // Stay centered in my cameraGroup, if I have one + while (NULL != (from = G_Find(from, FOFS(cameraGroup), client_camera.cameraGroup))) { /* if ( from->s.number == client_camera.aimEntNum ) {//This is the misc_camera_focus, we'll be removing this ent altogether eventually @@ -709,93 +618,80 @@ void CGCam_FollowUpdate ( void ) } */ - if ( num_subjects >= MAX_CAMERA_GROUP_SUBJECTS ) - { - gi.Printf(S_COLOR_RED"ERROR: Too many subjects in shot composition %s", client_camera.cameraGroup); + if (num_subjects >= MAX_CAMERA_GROUP_SUBJECTS) { + gi.Printf(S_COLOR_RED "ERROR: Too many subjects in shot composition %s", client_camera.cameraGroup); break; } fromCent = &cg_entities[from->s.number]; - if ( !fromCent ) - { + if (!fromCent) { continue; } focused = qfalse; - if ( from->client && client_camera.cameraGroupTag[0] && fromCent->gent->ghoul2.size() ) - { - int newBolt = gi.G2API_AddBolt( &fromCent->gent->ghoul2[from->playerModel], client_camera.cameraGroupTag ); - if ( newBolt != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t fromAngles = {0,from->client->ps.legsYaw,0}; + if (from->client && client_camera.cameraGroupTag[0] && fromCent->gent->ghoul2.size()) { + int newBolt = gi.G2API_AddBolt(&fromCent->gent->ghoul2[from->playerModel], client_camera.cameraGroupTag); + if (newBolt != -1) { + mdxaBone_t boltMatrix; + vec3_t fromAngles = {0, from->client->ps.legsYaw, 0}; - gi.G2API_GetBoltMatrix( fromCent->gent->ghoul2, from->playerModel, newBolt, &boltMatrix, fromAngles, fromCent->lerpOrigin, cg.time, cgs.model_draw, fromCent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, focus[num_subjects] ); + gi.G2API_GetBoltMatrix(fromCent->gent->ghoul2, from->playerModel, newBolt, &boltMatrix, fromAngles, fromCent->lerpOrigin, cg.time, + cgs.model_draw, fromCent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, focus[num_subjects]); focused = qtrue; } } - if ( !focused ) - { - if ( from->s.pos.trType != TR_STATIONARY ) -// if ( from->s.pos.trType == TR_INTERPOLATE ) - {//use interpolated origin? - if ( !VectorCompare( vec3_origin, fromCent->lerpOrigin ) ) - {//hunh? Somehow we've never seen this gentity on the client, so there is no lerpOrigin, so cheat over to the game and use the currentOrigin - VectorCopy( from->currentOrigin, focus[num_subjects] ); + if (!focused) { + if (from->s.pos.trType != TR_STATIONARY) + // if ( from->s.pos.trType == TR_INTERPOLATE ) + { // use interpolated origin? + if (!VectorCompare(vec3_origin, fromCent->lerpOrigin)) { // hunh? Somehow we've never seen this gentity on the client, so there is no + // lerpOrigin, so cheat over to the game and use the currentOrigin + VectorCopy(from->currentOrigin, focus[num_subjects]); + } else { + VectorCopy(fromCent->lerpOrigin, focus[num_subjects]); } - else - { - VectorCopy( fromCent->lerpOrigin, focus[num_subjects] ); - } - } - else - { + } else { VectorCopy(from->currentOrigin, focus[num_subjects]); } - //FIXME: make a list here of their s.numbers instead so we can do other stuff with the list below - if ( from->client ) - {//Track to their eyes - FIXME: maybe go off a tag? - //FIXME: - //Based on FOV and distance to subject from camera, pick the point that - //keeps eyes 3/4 up from bottom of screen... what about bars? + // FIXME: make a list here of their s.numbers instead so we can do other stuff with the list below + if (from->client) { // Track to their eyes - FIXME: maybe go off a tag? + // FIXME: + // Based on FOV and distance to subject from camera, pick the point that + // keeps eyes 3/4 up from bottom of screen... what about bars? focus[num_subjects][2] += from->client->ps.viewheight; } } - if ( client_camera.cameraGroupZOfs ) - { + if (client_camera.cameraGroupZOfs) { focus[num_subjects][2] += client_camera.cameraGroupZOfs; } num_subjects++; } - if ( !num_subjects ) // Bad cameragroup + if (!num_subjects) // Bad cameragroup { #ifndef FINAL_BUILD - gi.Printf(S_COLOR_RED"ERROR: Camera Focus unable to locate cameragroup: %s\n", client_camera.cameraGroup); + gi.Printf(S_COLOR_RED "ERROR: Camera Focus unable to locate cameragroup: %s\n", client_camera.cameraGroup); #endif return; } - //Now average all points - VectorCopy( focus[0], center ); - for( i = 1; i < num_subjects; i++ ) - { - VectorAdd( focus[i], center, center ); + // Now average all points + VectorCopy(focus[0], center); + for (i = 1; i < num_subjects; i++) { + VectorAdd(focus[i], center, center); } - VectorScale( center, 1.0f/((float)num_subjects), center ); - } - else - { + VectorScale(center, 1.0f / ((float)num_subjects), center); + } else { return; } - //Need to set a speed to keep a distance from - //the subject- fixme: only do this if have a distance - //set - VectorSubtract( client_camera.subjectPos, center, vec ); - client_camera.subjectSpeed = VectorLengthSquared( vec ) * 100.0f / cg.frametime; + // Need to set a speed to keep a distance from + // the subject- fixme: only do this if have a distance + // set + VectorSubtract(client_camera.subjectPos, center, vec); + client_camera.subjectSpeed = VectorLengthSquared(vec) * 100.0f / cg.frametime; /* if ( !cg_skippingcin.integer ) @@ -803,232 +699,183 @@ void CGCam_FollowUpdate ( void ) Com_Printf( S_COLOR_RED"org: %s\n", vtos(center) ); } */ - VectorCopy( center, client_camera.subjectPos ); + VectorCopy(center, client_camera.subjectPos); - VectorSubtract( center, cg.refdef.vieworg, dir );//can't use client_camera.origin because it's not updated until the end of the move. + VectorSubtract(center, cg.refdef.vieworg, dir); // can't use client_camera.origin because it's not updated until the end of the move. - //Get desired angle + // Get desired angle vectoangles(dir, cameraAngles); - if ( client_camera.followInitLerp ) - {//Lerping - float frac = cg.frametime/100.0f * client_camera.followSpeed/100.f; - for( i = 0; i < 3; i++ ) - { - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); - cameraAngles[i] = AngleNormalize180( client_camera.angles[i] + frac * AngleNormalize180(cameraAngles[i] - client_camera.angles[i]) ); - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); + if (client_camera.followInitLerp) { // Lerping + float frac = cg.frametime / 100.0f * client_camera.followSpeed / 100.f; + for (i = 0; i < 3; i++) { + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); + cameraAngles[i] = AngleNormalize180(client_camera.angles[i] + frac * AngleNormalize180(cameraAngles[i] - client_camera.angles[i])); + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); } #if 0 Com_Printf( "%s\n", vtos(cameraAngles) ); #endif - } - else - {//Snapping, should do this first time if follow_lerp_to_start_duration is zero - //will lerp from this point on + } else { // Snapping, should do this first time if follow_lerp_to_start_duration is zero + // will lerp from this point on client_camera.followInitLerp = qtrue; - for( i = 0; i < 3; i++ ) - {//normalize so that when we start lerping, it doesn't freak out - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); + for (i = 0; i < 3; i++) { // normalize so that when we start lerping, it doesn't freak out + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); } - //So tracker doesn't move right away thinking the first angle change - //is the subject moving... FIXME: shouldn't set this until lerp done OR snapped? + // So tracker doesn't move right away thinking the first angle change + // is the subject moving... FIXME: shouldn't set this until lerp done OR snapped? client_camera.subjectSpeed = 0; } - //Point camera to lerp angles + // Point camera to lerp angles /* if ( !cg_skippingcin.integer ) { Com_Printf( "ang: %s\n", vtos(cameraAngles) ); } */ - VectorCopy( cameraAngles, client_camera.angles ); + VectorCopy(cameraAngles, client_camera.angles); } -void CGCam_TrackEntUpdate ( void ) -{//FIXME: only do every 100 ms - gentity_t *trackEnt = NULL; - gentity_t *newTrackEnt = NULL; - qboolean reached = qfalse; - vec3_t vec; - float dist; +void CGCam_TrackEntUpdate(void) { // FIXME: only do every 100 ms + gentity_t *trackEnt = NULL; + gentity_t *newTrackEnt = NULL; + qboolean reached = qfalse; + vec3_t vec; + float dist; - if ( client_camera.trackEntNum >= 0 && client_camera.trackEntNum < ENTITYNUM_WORLD ) - {//We're already heading to a path_corner + if (client_camera.trackEntNum >= 0 && client_camera.trackEntNum < ENTITYNUM_WORLD) { // We're already heading to a path_corner trackEnt = &g_entities[client_camera.trackEntNum]; - VectorSubtract( trackEnt->currentOrigin, client_camera.origin, vec ); - dist = VectorLengthSquared( vec ); - if ( dist < 256 )//16 squared - {//FIXME: who should be doing the using here? - G_UseTargets( trackEnt, trackEnt ); + VectorSubtract(trackEnt->currentOrigin, client_camera.origin, vec); + dist = VectorLengthSquared(vec); + if (dist < 256) // 16 squared + { // FIXME: who should be doing the using here? + G_UseTargets(trackEnt, trackEnt); reached = qtrue; } } - if ( trackEnt && reached ) - { + if (trackEnt && reached) { - if ( trackEnt->target && trackEnt->target[0] ) - {//Find our next path_corner - newTrackEnt = G_Find( NULL, FOFS(targetname), trackEnt->target ); - if ( newTrackEnt ) - { - if ( newTrackEnt->radius < 0 ) - {//Don't bother trying to maintain a radius + if (trackEnt->target && trackEnt->target[0]) { // Find our next path_corner + newTrackEnt = G_Find(NULL, FOFS(targetname), trackEnt->target); + if (newTrackEnt) { + if (newTrackEnt->radius < 0) { // Don't bother trying to maintain a radius client_camera.distance = 0; client_camera.speed = client_camera.initSpeed; - } - else if ( newTrackEnt->radius > 0 ) - { + } else if (newTrackEnt->radius > 0) { client_camera.distance = newTrackEnt->radius; } - if ( newTrackEnt->speed < 0 ) - {//go back to our default speed + if (newTrackEnt->speed < 0) { // go back to our default speed client_camera.speed = client_camera.initSpeed; - } - else if ( newTrackEnt->speed > 0 ) - { - client_camera.speed = newTrackEnt->speed/10.0f; + } else if (newTrackEnt->speed > 0) { + client_camera.speed = newTrackEnt->speed / 10.0f; } } - } - else - {//stop thinking if this is the last one + } else { // stop thinking if this is the last one CGCam_TrackDisable(); } } - if ( newTrackEnt ) - {//Update will lerp this + if (newTrackEnt) { // Update will lerp this client_camera.info_state |= CAMERA_TRACKING; client_camera.trackEntNum = newTrackEnt->s.number; - VectorCopy( newTrackEnt->currentOrigin, client_camera.trackToOrg ); + VectorCopy(newTrackEnt->currentOrigin, client_camera.trackToOrg); } client_camera.nextTrackEntUpdateTime = cg.time + 100; } -void CGCam_TrackUpdate ( void ) -{ - vec3_t goalVec, curVec, trackPos, vec; - float goalDist, dist; - //qboolean slowDown = qfalse; +void CGCam_TrackUpdate(void) { + vec3_t goalVec, curVec, trackPos, vec; + float goalDist, dist; + // qboolean slowDown = qfalse; - if ( client_camera.nextTrackEntUpdateTime <= cg.time ) - { + if (client_camera.nextTrackEntUpdateTime <= cg.time) { CGCam_TrackEntUpdate(); } - VectorSubtract( client_camera.trackToOrg, client_camera.origin, goalVec ); - goalDist = VectorNormalize( goalVec ); - if ( goalDist > 100 ) - { + VectorSubtract(client_camera.trackToOrg, client_camera.origin, goalVec); + goalDist = VectorNormalize(goalVec); + if (goalDist > 100) { goalDist = 100; - } - else if ( goalDist < 10 ) - { + } else if (goalDist < 10) { goalDist = 10; } - if ( client_camera.distance && client_camera.info_state & CAMERA_FOLLOWING ) - { - float adjust = 0.0f, desiredSpeed = 0.0f; - float dot; + if (client_camera.distance && client_camera.info_state & CAMERA_FOLLOWING) { + float adjust = 0.0f, desiredSpeed = 0.0f; + float dot; - if ( !client_camera.distanceInitLerp ) - { - VectorSubtract( client_camera.origin, client_camera.subjectPos, vec ); - VectorNormalize( vec ); - //FIXME: use client_camera.moveDir here? - VectorMA( client_camera.subjectPos, client_camera.distance, vec, client_camera.origin ); - //Snap to first time only + if (!client_camera.distanceInitLerp) { + VectorSubtract(client_camera.origin, client_camera.subjectPos, vec); + VectorNormalize(vec); + // FIXME: use client_camera.moveDir here? + VectorMA(client_camera.subjectPos, client_camera.distance, vec, client_camera.origin); + // Snap to first time only client_camera.distanceInitLerp = qtrue; return; - } - else if ( client_camera.subjectSpeed > 0.05f ) - {//Don't start moving until subject moves - VectorSubtract( client_camera.subjectPos, client_camera.origin, vec ); + } else if (client_camera.subjectSpeed > 0.05f) { // Don't start moving until subject moves + VectorSubtract(client_camera.subjectPos, client_camera.origin, vec); dist = VectorNormalize(vec); dot = DotProduct(goalVec, vec); - if ( dist > client_camera.distance ) - {//too far away - if ( dot > 0 ) - {//Camera is moving toward the subject - adjust = (dist - client_camera.distance);//Speed up - } - else if ( dot < 0 ) - {//Camera is moving away from the subject - adjust = (dist - client_camera.distance) * -1.0f;//Slow down + if (dist > client_camera.distance) { // too far away + if (dot > 0) { // Camera is moving toward the subject + adjust = (dist - client_camera.distance); // Speed up + } else if (dot < 0) { // Camera is moving away from the subject + adjust = (dist - client_camera.distance) * -1.0f; // Slow down } - } - else if ( dist < client_camera.distance ) - {//too close - if(dot > 0) - {//Camera is moving toward the subject - adjust = (client_camera.distance - dist) * -1.0f;//Slow down - } - else if(dot < 0) - {//Camera is moving away from the subject - adjust = (client_camera.distance - dist);//Speed up + } else if (dist < client_camera.distance) { // too close + if (dot > 0) { // Camera is moving toward the subject + adjust = (client_camera.distance - dist) * -1.0f; // Slow down + } else if (dot < 0) { // Camera is moving away from the subject + adjust = (client_camera.distance - dist); // Speed up } } - //Speed of the focus + our error - //desiredSpeed = aimCent->gent->speed + (adjust * cg.frametime/100.0f);//cg.frameInterpolation); - desiredSpeed = (adjust);// * cg.frametime/100.0f);//cg.frameInterpolation); + // Speed of the focus + our error + // desiredSpeed = aimCent->gent->speed + (adjust * cg.frametime/100.0f);//cg.frameInterpolation); + desiredSpeed = (adjust); // * cg.frametime/100.0f);//cg.frameInterpolation); - //self->moveInfo.speed = desiredSpeed; + // self->moveInfo.speed = desiredSpeed; - //Don't change speeds faster than 10 every 10th of a second - float max_allowed_accel = MAX_ACCEL_PER_FRAME * (cg.frametime/100.0f); + // Don't change speeds faster than 10 every 10th of a second + float max_allowed_accel = MAX_ACCEL_PER_FRAME * (cg.frametime / 100.0f); - if ( !client_camera.subjectSpeed ) - {//full stop + if (!client_camera.subjectSpeed) { // full stop client_camera.speed = desiredSpeed; - } - else if ( client_camera.speed - desiredSpeed > max_allowed_accel ) - {//new speed much slower, slow down at max accel + } else if (client_camera.speed - desiredSpeed > max_allowed_accel) { // new speed much slower, slow down at max accel client_camera.speed -= max_allowed_accel; - } - else if ( desiredSpeed - client_camera.speed > max_allowed_accel ) - {//new speed much faster, speed up at max accel + } else if (desiredSpeed - client_camera.speed > max_allowed_accel) { // new speed much faster, speed up at max accel client_camera.speed += max_allowed_accel; - } - else - {//remember this speed + } else { // remember this speed client_camera.speed = desiredSpeed; } - //Com_Printf("Speed: %4.2f (%4.2f)\n", self->moveInfo.speed, aimCent->gent->speed); + // Com_Printf("Speed: %4.2f (%4.2f)\n", self->moveInfo.speed, aimCent->gent->speed); } + } else { + // slowDown = qtrue; } - else - { - //slowDown = qtrue; - } - - //FIXME: this probably isn't right, round it out more - VectorScale( goalVec, cg.frametime/100.0f, goalVec ); - VectorScale( client_camera.moveDir, (100.0f - cg.frametime)/100.0f, curVec ); - VectorAdd( goalVec, curVec, client_camera.moveDir ); - VectorNormalize( client_camera.moveDir ); + // FIXME: this probably isn't right, round it out more + VectorScale(goalVec, cg.frametime / 100.0f, goalVec); + VectorScale(client_camera.moveDir, (100.0f - cg.frametime) / 100.0f, curVec); + VectorAdd(goalVec, curVec, client_camera.moveDir); + VectorNormalize(client_camera.moveDir); /*if(slowDown) { VectorMA( client_camera.origin, client_camera.speed * goalDist/100.0f * cg.frametime/100.0f, client_camera.moveDir, trackPos ); } else*/ - { - VectorMA( client_camera.origin, client_camera.speed * cg.frametime/100.0f , client_camera.moveDir, trackPos ); - } + { VectorMA(client_camera.origin, client_camera.speed * cg.frametime / 100.0f, client_camera.moveDir, trackPos); } - //FIXME: Implement - //Need to find point on camera's path that is closest to the desired distance from subject - //OR: Need to intelligently pick this desired distance based on framing... - VectorCopy( trackPos, client_camera.origin ); + // FIXME: Implement + // Need to find point on camera's path that is closest to the desired distance from subject + // OR: Need to intelligently pick this desired distance based on framing... + VectorCopy(trackPos, client_camera.origin); } //========================================================================================= @@ -1039,18 +886,18 @@ CGCam_UpdateBarFade ------------------------- */ -void CGCam_UpdateBarFade( void ) -{ - if ( client_camera.bar_time + BAR_DURATION < cg.time ) - { +void CGCam_UpdateBarFade(void) { + if (client_camera.bar_time + BAR_DURATION < cg.time) { client_camera.bar_alpha = client_camera.bar_alpha_dest; client_camera.info_state &= ~CAMERA_BAR_FADING; client_camera.bar_height = client_camera.bar_height_dest; - } - else - { - client_camera.bar_alpha = client_camera.bar_alpha_source + ( ( client_camera.bar_alpha_dest - client_camera.bar_alpha_source ) / BAR_DURATION ) * ( cg.time - client_camera.bar_time );; - client_camera.bar_height = client_camera.bar_height_source + ( ( client_camera.bar_height_dest - client_camera.bar_height_source ) / BAR_DURATION ) * ( cg.time - client_camera.bar_time );; + } else { + client_camera.bar_alpha = client_camera.bar_alpha_source + + ((client_camera.bar_alpha_dest - client_camera.bar_alpha_source) / BAR_DURATION) * (cg.time - client_camera.bar_time); + ; + client_camera.bar_height = client_camera.bar_height_source + + ((client_camera.bar_height_dest - client_camera.bar_height_source) / BAR_DURATION) * (cg.time - client_camera.bar_time); + ; } } @@ -1060,20 +907,16 @@ CGCam_UpdateFade ------------------------- */ -void CGCam_UpdateFade( void ) -{ - if ( client_camera.info_state & CAMERA_FADING ) - { - if ( client_camera.fade_time + client_camera.fade_duration < cg.time ) - { - VectorCopy4( client_camera.fade_dest, client_camera.fade_color ); +void CGCam_UpdateFade(void) { + if (client_camera.info_state & CAMERA_FADING) { + if (client_camera.fade_time + client_camera.fade_duration < cg.time) { + VectorCopy4(client_camera.fade_dest, client_camera.fade_color); client_camera.info_state &= ~CAMERA_FADING; - } - else - { - for ( int i = 0; i < 4; i++ ) - { - client_camera.fade_color[i] = client_camera.fade_source[i] + (( ( client_camera.fade_dest[i] - client_camera.fade_source[i] ) ) / client_camera.fade_duration ) * ( cg.time - client_camera.fade_time ); + } else { + for (int i = 0; i < 4; i++) { + client_camera.fade_color[i] = + client_camera.fade_source[i] + + (((client_camera.fade_dest[i] - client_camera.fade_source[i])) / client_camera.fade_duration) * (cg.time - client_camera.fade_time); } } } @@ -1083,228 +926,173 @@ void CGCam_UpdateFade( void ) CGCam_Update ------------------------- */ -static void CGCam_Roff( void ); +static void CGCam_Roff(void); -void CGCam_Update( void ) -{ - int i; - qboolean checkFollow = qfalse; - qboolean checkTrack = qfalse; +void CGCam_Update(void) { + int i; + qboolean checkFollow = qfalse; + qboolean checkTrack = qfalse; // Apply new roff data to the camera as needed - if ( client_camera.info_state & CAMERA_ROFFING ) - { + if (client_camera.info_state & CAMERA_ROFFING) { CGCam_Roff(); } - //Check for a zoom - if (client_camera.info_state & CAMERA_ACCEL) - { + // Check for a zoom + if (client_camera.info_state & CAMERA_ACCEL) { // x = x0 + vt + 0.5*a*t*t - float actualFOV_X = client_camera.FOV; - float sanityMin = 1, sanityMax = 180; - float t = (cg.time - client_camera.FOV_time)*0.001; // mult by 0.001 cuz otherwise t is too darned big - float fovDuration = client_camera.FOV_duration; + float actualFOV_X = client_camera.FOV; + float sanityMin = 1, sanityMax = 180; + float t = (cg.time - client_camera.FOV_time) * 0.001; // mult by 0.001 cuz otherwise t is too darned big + float fovDuration = client_camera.FOV_duration; #ifndef FINAL_BUILD - if (cg_roffval4.integer) - { + if (cg_roffval4.integer) { fovDuration = cg_roffval4.integer; } #endif - if ( client_camera.FOV_time + fovDuration < cg.time ) - { + if (client_camera.FOV_time + fovDuration < cg.time) { client_camera.info_state &= ~CAMERA_ACCEL; - } - else - { - float initialPosVal = client_camera.FOV2; - float velVal = client_camera.FOV_vel; - float accVal = client_camera.FOV_acc; + } else { + float initialPosVal = client_camera.FOV2; + float velVal = client_camera.FOV_vel; + float accVal = client_camera.FOV_acc; #ifndef FINAL_BUILD - if (cg_roffdebug.integer) - { - if (fabs(cg_roffval1.value) > 0.001f) - { + if (cg_roffdebug.integer) { + if (fabs(cg_roffval1.value) > 0.001f) { initialPosVal = cg_roffval1.value; } - if (fabs(cg_roffval2.value) > 0.001f) - { + if (fabs(cg_roffval2.value) > 0.001f) { velVal = cg_roffval2.value; } - if (fabs(cg_roffval3.value) > 0.001f) - { + if (fabs(cg_roffval3.value) > 0.001f) { accVal = cg_roffval3.value; } } #endif - float initialPos = initialPosVal; - float vel = velVal*t; - float acc = 0.5*accVal*t*t; + float initialPos = initialPosVal; + float vel = velVal * t; + float acc = 0.5 * accVal * t * t; actualFOV_X = initialPos + vel + acc; - if (cg_roffdebug.integer) - { - Com_Printf("%d: fovaccel from %2.1f using vel = %2.4f, acc = %2.4f (current fov calc = %5.6f)\n", - cg.time, initialPosVal, velVal, accVal, actualFOV_X); + if (cg_roffdebug.integer) { + Com_Printf("%d: fovaccel from %2.1f using vel = %2.4f, acc = %2.4f (current fov calc = %5.6f)\n", cg.time, initialPosVal, velVal, accVal, + actualFOV_X); } - if (actualFOV_X < sanityMin) - { + if (actualFOV_X < sanityMin) { actualFOV_X = sanityMin; - } - else if (actualFOV_X > sanityMax) - { + } else if (actualFOV_X > sanityMax) { actualFOV_X = sanityMax; } client_camera.FOV = actualFOV_X; } - CG_CalcFOVFromX( actualFOV_X ); - } - else if ( client_camera.info_state & CAMERA_ZOOMING ) - { - float actualFOV_X; + CG_CalcFOVFromX(actualFOV_X); + } else if (client_camera.info_state & CAMERA_ZOOMING) { + float actualFOV_X; - if ( client_camera.FOV_time + client_camera.FOV_duration < cg.time ) - { + if (client_camera.FOV_time + client_camera.FOV_duration < cg.time) { actualFOV_X = client_camera.FOV = client_camera.FOV2; client_camera.info_state &= ~CAMERA_ZOOMING; + } else { + actualFOV_X = client_camera.FOV + (((client_camera.FOV2 - client_camera.FOV)) / client_camera.FOV_duration) * (cg.time - client_camera.FOV_time); } - else - { - actualFOV_X = client_camera.FOV + (( ( client_camera.FOV2 - client_camera.FOV ) ) / client_camera.FOV_duration ) * ( cg.time - client_camera.FOV_time ); - } - CG_CalcFOVFromX( actualFOV_X ); - } - else - { - CG_CalcFOVFromX( client_camera.FOV ); + CG_CalcFOVFromX(actualFOV_X); + } else { + CG_CalcFOVFromX(client_camera.FOV); } - //Check for roffing angles - if ( (client_camera.info_state & CAMERA_ROFFING) && !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - if (client_camera.info_state & CAMERA_CUT) - { + // Check for roffing angles + if ((client_camera.info_state & CAMERA_ROFFING) && !(client_camera.info_state & CAMERA_FOLLOWING)) { + if (client_camera.info_state & CAMERA_CUT) { // we're doing a cut, so just go to the new angles. none of this hifalutin lerping business. - for ( i = 0; i < 3; i++ ) - { - cg.refdefViewAngles[i] = AngleNormalize360( ( client_camera.angles[i] + client_camera.angles2[i] ) ); + for (i = 0; i < 3; i++) { + cg.refdefViewAngles[i] = AngleNormalize360((client_camera.angles[i] + client_camera.angles2[i])); } - } - else - { - for ( i = 0; i < 3; i++ ) - { - cg.refdefViewAngles[i] = client_camera.angles[i] + ( client_camera.angles2[i] / client_camera.pan_duration ) * ( cg.time - client_camera.pan_time ); + } else { + for (i = 0; i < 3; i++) { + cg.refdefViewAngles[i] = client_camera.angles[i] + (client_camera.angles2[i] / client_camera.pan_duration) * (cg.time - client_camera.pan_time); } } - } - else if ( client_camera.info_state & CAMERA_PANNING ) - { - if (client_camera.info_state & CAMERA_CUT) - { + } else if (client_camera.info_state & CAMERA_PANNING) { + if (client_camera.info_state & CAMERA_CUT) { // we're doing a cut, so just go to the new angles. none of this hifalutin lerping business. - for ( i = 0; i < 3; i++ ) - { - cg.refdefViewAngles[i] = AngleNormalize360( ( client_camera.angles[i] + client_camera.angles2[i] ) ); + for (i = 0; i < 3; i++) { + cg.refdefViewAngles[i] = AngleNormalize360((client_camera.angles[i] + client_camera.angles2[i])); } - } - else - { - //Note: does not actually change the camera's angles until the pan time is done! - if ( client_camera.pan_time + client_camera.pan_duration < cg.time ) - {//finished panning - for ( i = 0; i < 3; i++ ) - { - client_camera.angles[i] = AngleNormalize360( ( client_camera.angles[i] + client_camera.angles2[i] ) ); + } else { + // Note: does not actually change the camera's angles until the pan time is done! + if (client_camera.pan_time + client_camera.pan_duration < cg.time) { // finished panning + for (i = 0; i < 3; i++) { + client_camera.angles[i] = AngleNormalize360((client_camera.angles[i] + client_camera.angles2[i])); } client_camera.info_state &= ~CAMERA_PANNING; - VectorCopy(client_camera.angles, cg.refdefViewAngles ); - } - else - {//still panning - for ( i = 0; i < 3; i++ ) - { - //NOTE: does not store the resultant angle in client_camera.angles until pan is done - cg.refdefViewAngles[i] = client_camera.angles[i] + ( client_camera.angles2[i] / client_camera.pan_duration ) * ( cg.time - client_camera.pan_time ); + VectorCopy(client_camera.angles, cg.refdefViewAngles); + } else { // still panning + for (i = 0; i < 3; i++) { + // NOTE: does not store the resultant angle in client_camera.angles until pan is done + cg.refdefViewAngles[i] = + client_camera.angles[i] + (client_camera.angles2[i] / client_camera.pan_duration) * (cg.time - client_camera.pan_time); } } } - } - else - { + } else { checkFollow = qtrue; } - //Check for movement - if ( client_camera.info_state & CAMERA_MOVING ) - { - //NOTE: does not actually move the camera until the movement time is done! - if ( client_camera.move_time + client_camera.move_duration < cg.time ) - { - VectorCopy( client_camera.origin2, client_camera.origin ); + // Check for movement + if (client_camera.info_state & CAMERA_MOVING) { + // NOTE: does not actually move the camera until the movement time is done! + if (client_camera.move_time + client_camera.move_duration < cg.time) { + VectorCopy(client_camera.origin2, client_camera.origin); client_camera.info_state &= ~CAMERA_MOVING; - VectorCopy( client_camera.origin, cg.refdef.vieworg ); - } - else - { - if (client_camera.info_state & CAMERA_CUT) - { + VectorCopy(client_camera.origin, cg.refdef.vieworg); + } else { + if (client_camera.info_state & CAMERA_CUT) { // we're doing a cut, so just go to the new origin. none of this fancypants lerping stuff. - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { cg.refdef.vieworg[i] = client_camera.origin2[i]; } - } - else - { - for ( i = 0; i < 3; i++ ) - { - cg.refdef.vieworg[i] = client_camera.origin[i] + (( ( client_camera.origin2[i] - client_camera.origin[i] ) ) / client_camera.move_duration ) * ( cg.time - client_camera.move_time ); + } else { + for (i = 0; i < 3; i++) { + cg.refdef.vieworg[i] = client_camera.origin[i] + (((client_camera.origin2[i] - client_camera.origin[i])) / client_camera.move_duration) * + (cg.time - client_camera.move_time); } } } - } - else - { + } else { checkTrack = qtrue; } - if ( checkFollow ) - { - if ( client_camera.info_state & CAMERA_FOLLOWING ) - {//This needs to be done after camera movement + if (checkFollow) { + if (client_camera.info_state & CAMERA_FOLLOWING) { // This needs to be done after camera movement CGCam_FollowUpdate(); } - VectorCopy(client_camera.angles, cg.refdefViewAngles ); + VectorCopy(client_camera.angles, cg.refdefViewAngles); } - if ( checkTrack ) - { - if ( client_camera.info_state & CAMERA_TRACKING ) - {//This has to run AFTER Follow if the camera is following a cameraGroup + if (checkTrack) { + if (client_camera.info_state & CAMERA_TRACKING) { // This has to run AFTER Follow if the camera is following a cameraGroup CGCam_TrackUpdate(); } - VectorCopy( client_camera.origin, cg.refdef.vieworg ); + VectorCopy(client_camera.origin, cg.refdef.vieworg); } - //Bar fading - if ( client_camera.info_state & CAMERA_BAR_FADING ) - { + // Bar fading + if (client_camera.info_state & CAMERA_BAR_FADING) { CGCam_UpdateBarFade(); } - //Normal fading - separate call because can finish after camera is disabled + // Normal fading - separate call because can finish after camera is disabled CGCam_UpdateFade(); - //Update shaking if there's any - //CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); - CGCam_UpdateShake( cg.refdef.vieworg, cg.refdefViewAngles ); - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + // Update shaking if there's any + // CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); + CGCam_UpdateShake(cg.refdef.vieworg, cg.refdefViewAngles); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); } /* @@ -1313,27 +1101,25 @@ CGCam_DrawWideScreen ------------------------- */ -void CGCam_DrawWideScreen( void ) -{ - vec4_t modulate; +void CGCam_DrawWideScreen(void) { + vec4_t modulate; - //Only draw if visible - if ( client_camera.bar_alpha ) - { + // Only draw if visible + if (client_camera.bar_alpha) { CGCam_UpdateBarFade(); modulate[0] = modulate[1] = modulate[2] = 0.0f; modulate[3] = client_camera.bar_alpha; - CG_FillRect( cg.refdef.x, cg.refdef.y, 640, client_camera.bar_height, modulate ); - CG_FillRect( cg.refdef.x, cg.refdef.y + 480 - client_camera.bar_height, 640, client_camera.bar_height, modulate ); + CG_FillRect(cg.refdef.x, cg.refdef.y, 640, client_camera.bar_height, modulate); + CG_FillRect(cg.refdef.x, cg.refdef.y + 480 - client_camera.bar_height, 640, client_camera.bar_height, modulate); } - //NOTENOTE: Camera always draws the fades unless the alpha is 0 - if ( client_camera.fade_color[3] == 0.0f ) + // NOTENOTE: Camera always draws the fades unless the alpha is 0 + if (client_camera.fade_color[3] == 0.0f) return; - CG_FillRect( cg.refdef.x, cg.refdef.y, 640, 480, client_camera.fade_color ); + CG_FillRect(cg.refdef.x, cg.refdef.y, 640, 480, client_camera.fade_color); } /* @@ -1341,8 +1127,7 @@ void CGCam_DrawWideScreen( void ) CGCam_RenderScene ------------------------- */ -void CGCam_RenderScene( void ) -{ +void CGCam_RenderScene(void) { CGCam_Update(); CG_CalcVrect(); } @@ -1353,9 +1138,8 @@ CGCam_Shake ------------------------- */ -void CGCam_Shake( float intensity, int duration ) -{ - if ( intensity > MAX_SHAKE_INTENSITY ) +void CGCam_Shake(float intensity, int duration) { + if (intensity > MAX_SHAKE_INTENSITY) intensity = MAX_SHAKE_INTENSITY; client_camera.shake_intensity = intensity; @@ -1371,51 +1155,47 @@ This doesn't actually affect the camera's info, but passed information instead ------------------------- */ -void CGCam_UpdateShake( vec3_t origin, vec3_t angles ) -{ - vec3_t moveDir; - float intensity_scale, intensity; +void CGCam_UpdateShake(vec3_t origin, vec3_t angles) { + vec3_t moveDir; + float intensity_scale, intensity; - if ( client_camera.shake_duration <= 0 ) + if (client_camera.shake_duration <= 0) return; - if ( cg.time > ( client_camera.shake_start + client_camera.shake_duration ) ) - { + if (cg.time > (client_camera.shake_start + client_camera.shake_duration)) { client_camera.shake_intensity = 0; client_camera.shake_duration = 0; client_camera.shake_start = 0; return; } - //intensity_scale now also takes into account FOV with 90.0 as normal - intensity_scale = 1.0f - ( (float) ( cg.time - client_camera.shake_start ) / (float) client_camera.shake_duration ) * (((client_camera.FOV+client_camera.FOV2)/2.0f)/90.0f); + // intensity_scale now also takes into account FOV with 90.0 as normal + intensity_scale = 1.0f - ((float)(cg.time - client_camera.shake_start) / (float)client_camera.shake_duration) * + (((client_camera.FOV + client_camera.FOV2) / 2.0f) / 90.0f); intensity = client_camera.shake_intensity * intensity_scale; - for ( int i = 0; i < 3; i++ ) - { - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (int i = 0; i < 3; i++) { + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); } - //FIXME: Lerp + // FIXME: Lerp - //Move the camera - VectorAdd( origin, moveDir, origin ); + // Move the camera + VectorAdd(origin, moveDir, origin); - for ( int i = 0; i < 2; i++ ) // Don't do ROLL - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (int i = 0; i < 2; i++) // Don't do ROLL + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); - //FIXME: Lerp + // FIXME: Lerp - //Move the angles - VectorAdd( angles, moveDir, angles ); + // Move the angles + VectorAdd(angles, moveDir, angles); } -void CGCam_Smooth( float intensity, int duration ) -{ - client_camera.smooth_active=false; // means smooth_origin and angles are valid - if ( intensity>1.0f||intensity==0.0f||duration<1) - { +void CGCam_Smooth(float intensity, int duration) { + client_camera.smooth_active = false; // means smooth_origin and angles are valid + if (intensity > 1.0f || intensity == 0.0f || duration < 1) { client_camera.info_state &= ~CAMERA_SMOOTHING; return; } @@ -1425,80 +1205,65 @@ void CGCam_Smooth( float intensity, int duration ) client_camera.smooth_start = cg.time; } -void CGCam_UpdateSmooth( vec3_t origin, vec3_t angles ) -{ - if (!(client_camera.info_state&CAMERA_SMOOTHING)||cg.time > ( client_camera.smooth_start + client_camera.smooth_duration )) - { +void CGCam_UpdateSmooth(vec3_t origin, vec3_t angles) { + if (!(client_camera.info_state & CAMERA_SMOOTHING) || cg.time > (client_camera.smooth_start + client_camera.smooth_duration)) { client_camera.info_state &= ~CAMERA_SMOOTHING; return; } - if (!client_camera.smooth_active) - { - client_camera.smooth_active=true; - VectorCopy(origin,client_camera.smooth_origin); + if (!client_camera.smooth_active) { + client_camera.smooth_active = true; + VectorCopy(origin, client_camera.smooth_origin); return; } - float factor=client_camera.smooth_intensity; - if (client_camera.smooth_duration>200&&cg.time > ( client_camera.smooth_start + client_camera.smooth_duration-100 )) - { - factor+=(1.0f-client_camera.smooth_intensity)* - (100.0f-(client_camera.smooth_start + client_camera.smooth_duration-cg.time))/100.0f; + float factor = client_camera.smooth_intensity; + if (client_camera.smooth_duration > 200 && cg.time > (client_camera.smooth_start + client_camera.smooth_duration - 100)) { + factor += (1.0f - client_camera.smooth_intensity) * (100.0f - (client_camera.smooth_start + client_camera.smooth_duration - cg.time)) / 100.0f; } int i; - for (i=0;i<3;i++) - { - client_camera.smooth_origin[i]*=(1.0f-factor); - client_camera.smooth_origin[i]+=factor*origin[i]; - origin[i]=client_camera.smooth_origin[i]; + for (i = 0; i < 3; i++) { + client_camera.smooth_origin[i] *= (1.0f - factor); + client_camera.smooth_origin[i] += factor * origin[i]; + origin[i] = client_camera.smooth_origin[i]; } } -void CGCam_NotetrackProcessFov(const char *addlArg) -{ +void CGCam_NotetrackProcessFov(const char *addlArg) { int a = 0; char t[64]; - if (!addlArg || !addlArg[0]) - { + if (!addlArg || !addlArg[0]) { Com_Printf("camera roff 'fov' notetrack missing fov argument\n", addlArg); return; } - if (isdigit(addlArg[a])) - { + if (isdigit(addlArg[a])) { // "fov " int d = 0, tsize = 64; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our desired fov float newFov = atof(t); #ifndef FINAL_BUILD - if (cg_roffdebug.integer) - { - if (fabs(cg_roffval1.value) > 0.001f) - { + if (cg_roffdebug.integer) { + if (fabs(cg_roffval1.value) > 0.001f) { newFov = cg_roffval1.value; } } #endif - if (cg_roffdebug.integer) - { + if (cg_roffdebug.integer) { Com_Printf("notetrack: 'fov %2.2f' on frame %d\n", newFov, client_camera.roff_frame); } CGCam_Zoom(newFov, 0); } } -void CGCam_NotetrackProcessFovZoom(const char *addlArg) -{ - int a = 0; - float beginFOV = 0, endFOV = 0, fovTime = 0; +void CGCam_NotetrackProcessFovZoom(const char *addlArg) { + int a = 0; + float beginFOV = 0, endFOV = 0, fovTime = 0; - if (!addlArg || !addlArg[0]) - { + if (!addlArg || !addlArg[0]) { Com_Printf("camera roff 'fovzoom' notetrack missing arguments\n", addlArg); return; } @@ -1508,96 +1273,75 @@ void CGCam_NotetrackProcessFovZoom(const char *addlArg) char t[64]; int d = 0, tsize = 64; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } - if (!isdigit(t[0])) - { + if (!isdigit(t[0])) { // assume a non-number here means we should start from our current fov beginFOV = client_camera.FOV; - } - else - { + } else { // now the contents of t represent our beginning fov beginFOV = atof(t); } // eat leading whitespace - while (addlArg[a] && addlArg[a] == ' ') - { + while (addlArg[a] && addlArg[a] == ' ') { a++; } - if (addlArg[a]) - { + if (addlArg[a]) { d = 0; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our end fov endFOV = atof(t); // eat leading whitespace - while (addlArg[a] && addlArg[a] == ' ') - { + while (addlArg[a] && addlArg[a] == ' ') { a++; } - if (addlArg[a]) - { + if (addlArg[a]) { d = 0; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our time fovTime = atof(t); - } - else - { + } else { Com_Printf("camera roff 'fovzoom' notetrack missing 'time' argument\n", addlArg); return; } #ifndef FINAL_BUILD - if (cg_roffdebug.integer) - { - if (fabs(cg_roffval1.value) > 0.001f) - { + if (cg_roffdebug.integer) { + if (fabs(cg_roffval1.value) > 0.001f) { beginFOV = cg_roffval1.value; } - if (fabs(cg_roffval2.value) > 0.001f) - { + if (fabs(cg_roffval2.value) > 0.001f) { endFOV = cg_roffval2.value; } - if (fabs(cg_roffval3.value) > 0.001f) - { + if (fabs(cg_roffval3.value) > 0.001f) { fovTime = cg_roffval3.value; } } #endif - if (cg_roffdebug.integer) - { + if (cg_roffdebug.integer) { Com_Printf("notetrack: 'fovzoom %2.2f %2.2f %5.1f' on frame %d\n", beginFOV, endFOV, fovTime, client_camera.roff_frame); } CGCam_Zoom2(beginFOV, endFOV, fovTime); - } - else - { + } else { Com_Printf("camera roff 'fovzoom' notetrack missing 'end fov' argument\n", addlArg); return; } } -void CGCam_NotetrackProcessFovAccel(const char *addlArg) -{ - int a = 0; - float beginFOV = 0, fovDelta = 0, fovDelta2 = 0, fovTime = 0; +void CGCam_NotetrackProcessFovAccel(const char *addlArg) { + int a = 0; + float beginFOV = 0, fovDelta = 0, fovDelta2 = 0, fovTime = 0; - if (!addlArg || !addlArg[0]) - { + if (!addlArg || !addlArg[0]) { Com_Printf("camera roff 'fovaccel' notetrack missing arguments\n", addlArg); return; } @@ -1608,149 +1352,124 @@ void CGCam_NotetrackProcessFovAccel(const char *addlArg) char t[64]; int d = 0, tsize = 64; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } - if (!isdigit(t[0])) - { + if (!isdigit(t[0])) { // assume a non-number here means we should start from our current fov beginFOV = client_camera.FOV; - } - else - { + } else { // now the contents of t represent our beginning fov beginFOV = atof(t); } // eat leading whitespace - while (addlArg[a] && addlArg[a] == ' ') - { + while (addlArg[a] && addlArg[a] == ' ') { a++; } - if (addlArg[a]) - { + if (addlArg[a]) { d = 0; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our delta fovDelta = atof(t); // eat leading whitespace - while (addlArg[a] && addlArg[a] == ' ') - { + while (addlArg[a] && addlArg[a] == ' ') { a++; } - if (addlArg[a]) - { + if (addlArg[a]) { d = 0; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our fovDelta2 fovDelta2 = atof(t); // eat leading whitespace - while (addlArg[a] && addlArg[a] == ' ') - { + while (addlArg[a] && addlArg[a] == ' ') { a++; } - if (addlArg[a]) - { + if (addlArg[a]) { d = 0; - memset(t, 0, tsize*sizeof(char)); - while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) - { + memset(t, 0, tsize * sizeof(char)); + while (addlArg[a] && !isspace(addlArg[a]) && d < tsize) { t[d++] = addlArg[a++]; } // now the contents of t represent our time fovTime = atof(t); - } - else - { + } else { Com_Printf("camera roff 'fovaccel' notetrack missing 'time' argument\n", addlArg); return; } - if (cg_roffdebug.integer) - { + if (cg_roffdebug.integer) { Com_Printf("notetrack: 'fovaccel %2.2f %3.5f %3.5f %d' on frame %d\n", beginFOV, fovDelta, fovDelta2, fovTime, client_camera.roff_frame); } CGCam_ZoomAccel(beginFOV, fovDelta, fovDelta2, fovTime); - } - else - { + } else { Com_Printf("camera roff 'fovaccel' notetrack missing 'delta2' argument\n", addlArg); return; } - } - else - { + } else { Com_Printf("camera roff 'fovaccel' notetrack missing 'delta' argument\n", addlArg); return; } } // 3/18/03 kef -- blatantly thieved from G_RoffNotetrackCallback -static void CG_RoffNotetrackCallback(const char *notetrack) -{ +static void CG_RoffNotetrackCallback(const char *notetrack) { int i = 0, r = 0; char type[256]; -// char argument[512]; + // char argument[512]; char addlArg[512]; int addlArgs = 0; - if (!notetrack) - { + if (!notetrack) { return; } - //notetrack = "fov 65"; + // notetrack = "fov 65"; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - //if (notetrack[i] != ' ') + // if (notetrack[i] != ' ') //{ //didn't pass in a valid notetrack type, or forgot the argument for it // return; - //} + // } -/* i++; + /* i++; - while (notetrack[i] && notetrack[i] != ' ') - { - if (notetrack[i] != '\n' && notetrack[i] != '\r') - { //don't read line ends for an argument - argument[r] = notetrack[i]; - r++; + while (notetrack[i] && notetrack[i] != ' ') + { + if (notetrack[i] != '\n' && notetrack[i] != '\r') + { //don't read line ends for an argument + argument[r] = notetrack[i]; + r++; + } + i++; } - i++; - } - argument[r] = '\0'; - if (!r) - { - return; - } -*/ + argument[r] = '\0'; + if (!r) + { + return; + } + */ - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -1758,42 +1477,30 @@ static void CG_RoffNotetrackCallback(const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "cut") == 0) - { + if (strcmp(type, "cut") == 0) { client_camera.info_state |= CAMERA_CUT; - if (cg_roffdebug.integer) - { + if (cg_roffdebug.integer) { Com_Printf("notetrack: 'cut' on frame %d\n", client_camera.roff_frame); } // this is just a really hacky way of getting a cut and a fov command on the same frame - if (addlArgs) - { + if (addlArgs) { CG_RoffNotetrackCallback(addlArg); } - } - else if (strcmp(type, "fov") == 0) - { - if (addlArgs) - { + } else if (strcmp(type, "fov") == 0) { + if (addlArgs) { CGCam_NotetrackProcessFov(addlArg); return; } Com_Printf("camera roff 'fov' notetrack missing fov argument\n", addlArg); - } - else if (strcmp(type, "fovzoom") == 0) - { - if (addlArgs) - { + } else if (strcmp(type, "fovzoom") == 0) { + if (addlArgs) { CGCam_NotetrackProcessFovZoom(addlArg); return; } Com_Printf("camera roff 'fovzoom' notetrack missing 'begin fov' argument\n", addlArg); - } - else if (strcmp(type, "fovaccel") == 0) - { - if (addlArgs) - { + } else if (strcmp(type, "fovaccel") == 0) { + if (addlArgs) { CGCam_NotetrackProcessFovAccel(addlArg); return; } @@ -1810,8 +1517,7 @@ a rof file ------------------------- */ -void CGCam_StartRoff( char *roff ) -{ +void CGCam_StartRoff(char *roff) { CGCam_FollowDisable(); CGCam_TrackDisable(); @@ -1820,18 +1526,17 @@ void CGCam_StartRoff( char *roff ) client_camera.info_state |= CAMERA_MOVING; client_camera.info_state |= CAMERA_PANNING; - if ( !G_LoadRoff( roff ) ) - { + if (!G_LoadRoff(roff)) { // The load failed so don't turn on the roff playback... - Com_Printf( S_COLOR_RED"ROFF camera playback failed\n" ); + Com_Printf(S_COLOR_RED "ROFF camera playback failed\n"); return; }; client_camera.info_state |= CAMERA_ROFFING; - Q_strncpyz(client_camera.sRoff,roff,sizeof(client_camera.sRoff)); + Q_strncpyz(client_camera.sRoff, roff, sizeof(client_camera.sRoff)); client_camera.roff_frame = 0; - client_camera.next_roff_time = cg.time; // I can work right away + client_camera.next_roff_time = cg.time; // I can work right away } /* @@ -1842,8 +1547,7 @@ Stops camera rof ------------------------- */ -static void CGCam_StopRoff( void ) -{ +static void CGCam_StopRoff(void) { // Clear the roff flag client_camera.info_state &= ~CAMERA_ROFFING; client_camera.info_state &= ~CAMERA_MOVING; @@ -1861,96 +1565,81 @@ so often...or maybe I'm just on crack. ------------------------------------------------------ */ -static void CGCam_Roff( void ) -{ - while ( client_camera.next_roff_time <= cg.time ) - { - // Make sure that the roff is cached - const int roff_id = G_LoadRoff( client_camera.sRoff ); +static void CGCam_Roff(void) { + while (client_camera.next_roff_time <= cg.time) { + // Make sure that the roff is cached + const int roff_id = G_LoadRoff(client_camera.sRoff); - if ( !roff_id ) - { - return; - } + if (!roff_id) { + return; + } - // The ID is one higher than the array index - const roff_list_t *roff = &roffs[ roff_id - 1 ]; - vec3_t org, ang; + // The ID is one higher than the array index + const roff_list_t *roff = &roffs[roff_id - 1]; + vec3_t org, ang; - if ( roff->type == 2 ) - { - move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ client_camera.roff_frame ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); + if (roff->type == 2) { + move_rotate2_t *data = &((move_rotate2_t *)roff->data)[client_camera.roff_frame]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); - // since we just hit a new frame, clear our CUT flag - client_camera.info_state &= ~CAMERA_CUT; + // since we just hit a new frame, clear our CUT flag + client_camera.info_state &= ~CAMERA_CUT; - if (data->mStartNote != -1 || data->mNumNotes) - { - CG_RoffNotetrackCallback(roffs[roff_id - 1].mNoteTrackIndexes[data->mStartNote]); + if (data->mStartNote != -1 || data->mNumNotes) { + CG_RoffNotetrackCallback(roffs[roff_id - 1].mNoteTrackIndexes[data->mStartNote]); + } + } else { + move_rotate_t *data = &((move_rotate_t *)roff->data)[client_camera.roff_frame]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); } - } - else - { - move_rotate_t *data = &((move_rotate_t *)roff->data)[ client_camera.roff_frame ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); - } - // Yeah, um, I guess this just has to be negated? - //ang[PITCH] =- ang[PITCH]; - ang[ROLL] = -ang[ROLL]; - // might need to to yaw as well. need a test... + // Yeah, um, I guess this just has to be negated? + // ang[PITCH] =- ang[PITCH]; + ang[ROLL] = -ang[ROLL]; + // might need to to yaw as well. need a test... - if ( cg_developer.integer ) - { - Com_Printf( S_COLOR_GREEN"CamROFF: frame: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", - client_camera.roff_frame, - org[0], org[1], org[2], - ang[0], ang[1], ang[2] ); - } + if (cg_developer.integer) { + Com_Printf(S_COLOR_GREEN "CamROFF: frame: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", client_camera.roff_frame, org[0], org[1], org[2], ang[0], + ang[1], ang[2]); + } - if ( client_camera.roff_frame ) - { - // Don't mess with angles if we are following - if ( !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - VectorAdd( client_camera.angles, client_camera.angles2, client_camera.angles ); + if (client_camera.roff_frame) { + // Don't mess with angles if we are following + if (!(client_camera.info_state & CAMERA_FOLLOWING)) { + VectorAdd(client_camera.angles, client_camera.angles2, client_camera.angles); + } + + VectorCopy(client_camera.origin2, client_camera.origin); } - VectorCopy( client_camera.origin2, client_camera.origin ); - } + // Don't mess with angles if we are following + if (!(client_camera.info_state & CAMERA_FOLLOWING)) { + VectorCopy(ang, client_camera.angles2); + client_camera.pan_time = cg.time; + client_camera.pan_duration = roff->mFrameTime; + } - // Don't mess with angles if we are following - if ( !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - VectorCopy( ang, client_camera.angles2 ); - client_camera.pan_time = cg.time; - client_camera.pan_duration = roff->mFrameTime; - } + VectorAdd(client_camera.origin, org, client_camera.origin2); - VectorAdd( client_camera.origin, org, client_camera.origin2 ); + client_camera.move_time = cg.time; + client_camera.move_duration = roff->mFrameTime; - client_camera.move_time = cg.time; - client_camera.move_duration = roff->mFrameTime; + if (++client_camera.roff_frame >= roff->frames) { + CGCam_StopRoff(); + return; + } - if ( ++client_camera.roff_frame >= roff->frames ) - { - CGCam_StopRoff(); - return; + // Check back in frameTime to get the next roff entry + client_camera.next_roff_time += roff->mFrameTime; } - - // Check back in frameTime to get the next roff entry - client_camera.next_roff_time += roff->mFrameTime; - } } -void CMD_CGCam_Disable( void ) -{ - vec4_t fade = {0, 0, 0, 0}; +void CMD_CGCam_Disable(void) { + vec4_t fade = {0, 0, 0, 0}; CGCam_Disable(); - CGCam_SetFade( fade ); + CGCam_SetFade(fade); player_locked = qfalse; } diff --git a/code/cgame/cg_consolecmds.cpp b/code/cgame/cg_consolecmds.cpp index eb4b79a7aa..40da97e486 100644 --- a/code/cgame/cg_consolecmds.cpp +++ b/code/cgame/cg_consolecmds.cpp @@ -26,15 +26,15 @@ along with this program; if not, see . #include "cg_headers.h" -#include "cg_media.h" //just for cgs.... +#include "cg_media.h" //just for cgs.... -void CG_TargetCommand_f( void ); -extern qboolean player_locked; -extern void CMD_CGCam_Disable( void ); -void CG_NextInventory_f( void ); -void CG_PrevInventory_f( void ); -void CG_NextForcePower_f( void ); -void CG_PrevForcePower_f( void ); +void CG_TargetCommand_f(void); +extern qboolean player_locked; +extern void CMD_CGCam_Disable(void); +void CG_NextInventory_f(void); +void CG_PrevInventory_f(void); +void CG_NextForcePower_f(void); +void CG_PrevForcePower_f(void); /* ================= @@ -42,17 +42,17 @@ CG_TargetCommand_f ================= */ -void CG_TargetCommand_f( void ) { - int targetNum; - char test[4]; +void CG_TargetCommand_f(void) { + int targetNum; + char test[4]; targetNum = CG_CrosshairPlayer(); - if ( targetNum == -1 ) { + if (targetNum == -1) { return; } - cgi_Argv( 1, test, 4 ); - cgi_SendClientCommand( va( "gc %i %i", targetNum, atoi( test ) ) ); + cgi_Argv(1, test, 4); + cgi_SendClientCommand(va("gc %i %i", targetNum, atoi(test))); } /* @@ -62,56 +62,50 @@ CG_Viewpos_f Debugging command to print the current position ============= */ -static void CG_Viewpos_f (void) { - CG_Printf ("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], - (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], - (int)cg.refdefViewAngles[YAW]); +static void CG_Viewpos_f(void) { + CG_Printf("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], + (int)cg.refdefViewAngles[YAW]); } -void CG_WriteCam_f (void) -{ - char text[1024]; - const char *targetname; - static int numCams; +void CG_WriteCam_f(void) { + char text[1024]; + const char *targetname; + static int numCams; numCams++; targetname = CG_Argv(1); - if( !targetname || !targetname[0] ) - { + if (!targetname || !targetname[0]) { targetname = "nameme!"; } - CG_Printf( "Camera #%d ('%s') written to: ", numCams, targetname ); - Com_sprintf( text, sizeof(text), "//entity %d\n{\n\"classname\" \"ref_tag\"\n\"targetname\" \"%s\"\n\"origin\" \"%i %i %i\"\n\"angles\" \"%i %i %i\"\n\"fov\" \"%i\"\n}\n", numCams, targetname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], (int)cg.refdefViewAngles[0], (int)cg.refdefViewAngles[1], (int)cg.refdefViewAngles[2], cg_fov.integer ); - gi.WriteCam( text ); + CG_Printf("Camera #%d ('%s') written to: ", numCams, targetname); + Com_sprintf(text, sizeof(text), + "//entity %d\n{\n\"classname\" \"ref_tag\"\n\"targetname\" \"%s\"\n\"origin\" \"%i %i %i\"\n\"angles\" \"%i %i %i\"\n\"fov\" \"%i\"\n}\n", + numCams, targetname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], (int)cg.refdefViewAngles[0], + (int)cg.refdefViewAngles[1], (int)cg.refdefViewAngles[2], cg_fov.integer); + gi.WriteCam(text); } -void Lock_Disable ( void ) -{ - player_locked = qfalse; -} +void Lock_Disable(void) { player_locked = qfalse; } -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp -void CG_ToggleBinoculars( void ) -{ - if ( in_camera || !cg.snap ) - { +void CG_ToggleBinoculars(void) { + if (in_camera || !cg.snap) { return; } - if ( cg.zoomMode == 0 || cg.zoomMode >= 2 ) // not zoomed or currently zoomed with the disruptor or LA goggles + if (cg.zoomMode == 0 || cg.zoomMode >= 2) // not zoomed or currently zoomed with the disruptor or LA goggles { - if ( (cg.snap->ps.saber[0].Active() && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) - {//can't select binoculars when throwing saber - //FIXME: indicate this to the player + if ((cg.snap->ps.saber[0].Active() && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) { // can't select binoculars when throwing + // saber + // FIXME: indicate this to the player return; } - if ( cg.snap->ps.viewEntity || ( cg_entities[cg.snap->ps.clientNum].currentState.eFlags & ( EF_LOCKED_TO_WEAPON | EF_IN_ATST ))) - { + if (cg.snap->ps.viewEntity || (cg_entities[cg.snap->ps.clientNum].currentState.eFlags & (EF_LOCKED_TO_WEAPON | EF_IN_ATST))) { // can't zoom when you have a viewEntity or driving an atst or in an emplaced gun return; } @@ -119,142 +113,123 @@ void CG_ToggleBinoculars( void ) cg.zoomMode = 1; cg.zoomLocked = qfalse; - if ( cg.weaponSelect == WP_SABER ) - { + if (cg.weaponSelect == WP_SABER) { cg.weaponSelect = WP_NONE; } - if ( cg.snap->ps.batteryCharge ) - { + if (cg.snap->ps.batteryCharge) { // when you have batteries, you can actually zoom in cg_zoomFov = 40.0f; - } - else if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + } else if (cg.overrides.active & CG_OVERRIDE_FOV) { cg_zoomFov = cg.overrides.fov; - } - else - { + } else { cg_zoomFov = cg_fov.value; } - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart ); - } - else - { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart); + } else { cg.zoomMode = 0; cg.zoomTime = cg.time; - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd ); + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd); - if( cg.weaponSelect == WP_NONE && cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << WP_SABER ) ) - { + if (cg.weaponSelect == WP_NONE && cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { // FIXME: this is pretty damn ugly but whatever cg.weaponSelect = WP_SABER; } } } -void CG_ToggleLAGoggles( void ) -{ - if ( in_camera || !cg.snap) - { +void CG_ToggleLAGoggles(void) { + if (in_camera || !cg.snap) { return; } - if ( cg.zoomMode == 0 || cg.zoomMode < 3 ) // not zoomed or currently zoomed with the disruptor or regular binoculars + if (cg.zoomMode == 0 || cg.zoomMode < 3) // not zoomed or currently zoomed with the disruptor or regular binoculars { - if ( (cg.snap->ps.saber[0].Active() && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - {//can't select binoculars when throwing saber - //FIXME: indicate this to the player + if ((cg.snap->ps.saber[0].Active() && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) { // can't select binoculars when throwing + // saber + // FIXME: indicate this to the player return; } - if ( cg.snap->ps.viewEntity || ( cg_entities[cg.snap->ps.clientNum].currentState.eFlags & ( EF_LOCKED_TO_WEAPON | EF_IN_ATST ))) - { + if (cg.snap->ps.viewEntity || (cg_entities[cg.snap->ps.clientNum].currentState.eFlags & (EF_LOCKED_TO_WEAPON | EF_IN_ATST))) { // can't zoom when you have a viewEntity or driving an atst or in an emplaced gun return; } cg.zoomMode = 3; cg.zoomLocked = qfalse; - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + if (cg.overrides.active & CG_OVERRIDE_FOV) { cg_zoomFov = cg.overrides.fov; - } - else - { + } else { cg_zoomFov = cg_fov.value; // does not zoom!! } - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart ); - } - else - { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart); + } else { cg.zoomMode = 0; cg.zoomTime = cg.time; - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd ); + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd); } } -void CG_LoadHud_f( void ) { +void CG_LoadHud_f(void) { const char *hudSet = cg_hudFiles.string; - if ( hudSet[0] == '\0' ) { + if (hudSet[0] == '\0') { hudSet = "ui/jahud.txt"; } - //cgi_UI_String_Init(); - //cgi_UI_Menu_Reset(); - CG_LoadMenus( hudSet ); + // cgi_UI_String_Init(); + // cgi_UI_Menu_Reset(); + CG_LoadMenus(hudSet); } typedef struct { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } consoleCommand_t; -int cmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((consoleCommand_t*)b)->cmd ); -} +int cmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((consoleCommand_t *)b)->cmd); } /* This array MUST be sorted correctly by alphabetical name field */ -static consoleCommand_t commands[] = { - { "cam_disable", CMD_CGCam_Disable }, //gets out of camera mode for debuggin - { "cam_enable", CGCam_Enable }, //gets into camera mode for precise camera placement - { "dpforcenext", CG_DPNextForcePower_f }, - { "dpforceprev", CG_DPPrevForcePower_f }, - { "dpinvnext", CG_DPNextInventory_f }, - { "dpinvprev", CG_DPPrevInventory_f }, - { "dpweapnext", CG_DPNextWeapon_f }, - { "dpweapprev", CG_DPPrevWeapon_f }, - { "forcenext", CG_NextForcePower_f }, - { "forceprev", CG_PrevForcePower_f }, - { "invnext", CG_NextInventory_f }, - { "invprev", CG_PrevInventory_f }, - { "la_zoom", CG_ToggleLAGoggles }, - { "loadhud", CG_LoadHud_f }, - { "lock_disable", Lock_Disable }, //player can move now - { "nextframe", CG_TestModelNextFrame_f }, - { "nextskin", CG_TestModelNextSkin_f }, - { "prevframe", CG_TestModelPrevFrame_f }, - { "prevskin", CG_TestModelPrevSkin_f }, - { "tcmd", CG_TargetCommand_f }, - { "testG2Model", CG_TestG2Model_f}, - { "testanglespost", CG_TestModelSetAnglespost_f}, - { "testanglespre", CG_TestModelSetAnglespre_f}, - { "testanimate", CG_TestModelAnimate_f}, - { "testlistbones", CG_ListModelBones_f}, - { "testlistsurfaces", CG_ListModelSurfaces_f}, - { "testmodel", CG_TestModel_f }, - { "testsurface", CG_TestModelSurfaceOnOff_f }, - { "viewpos", CG_Viewpos_f }, - { "weapnext", CG_NextWeapon_f }, - { "weapon", CG_Weapon_f }, - { "weapprev", CG_PrevWeapon_f }, - { "writecam", CG_WriteCam_f }, - { "zoom", CG_ToggleBinoculars }, +static consoleCommand_t commands[] = { + {"cam_disable", CMD_CGCam_Disable}, // gets out of camera mode for debuggin + {"cam_enable", CGCam_Enable}, // gets into camera mode for precise camera placement + {"dpforcenext", CG_DPNextForcePower_f}, + {"dpforceprev", CG_DPPrevForcePower_f}, + {"dpinvnext", CG_DPNextInventory_f}, + {"dpinvprev", CG_DPPrevInventory_f}, + {"dpweapnext", CG_DPNextWeapon_f}, + {"dpweapprev", CG_DPPrevWeapon_f}, + {"forcenext", CG_NextForcePower_f}, + {"forceprev", CG_PrevForcePower_f}, + {"invnext", CG_NextInventory_f}, + {"invprev", CG_PrevInventory_f}, + {"la_zoom", CG_ToggleLAGoggles}, + {"loadhud", CG_LoadHud_f}, + {"lock_disable", Lock_Disable}, // player can move now + {"nextframe", CG_TestModelNextFrame_f}, + {"nextskin", CG_TestModelNextSkin_f}, + {"prevframe", CG_TestModelPrevFrame_f}, + {"prevskin", CG_TestModelPrevSkin_f}, + {"tcmd", CG_TargetCommand_f}, + {"testG2Model", CG_TestG2Model_f}, + {"testanglespost", CG_TestModelSetAnglespost_f}, + {"testanglespre", CG_TestModelSetAnglespre_f}, + {"testanimate", CG_TestModelAnimate_f}, + {"testlistbones", CG_ListModelBones_f}, + {"testlistsurfaces", CG_ListModelSurfaces_f}, + {"testmodel", CG_TestModel_f}, + {"testsurface", CG_TestModelSurfaceOnOff_f}, + {"viewpos", CG_Viewpos_f}, + {"weapnext", CG_NextWeapon_f}, + {"weapon", CG_Weapon_f}, + {"weapprev", CG_PrevWeapon_f}, + {"writecam", CG_WriteCam_f}, + {"zoom", CG_ToggleBinoculars}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -264,66 +239,64 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -qboolean CG_ConsoleCommand( void ) { - consoleCommand_t *command = NULL; +qboolean CG_ConsoleCommand(void) { + consoleCommand_t *command = NULL; - command = (consoleCommand_t *)Q_LinearSearch( CG_Argv( 0 ), commands, numCommands, sizeof( commands[0] ), cmdcmp ); + command = (consoleCommand_t *)Q_LinearSearch(CG_Argv(0), commands, numCommands, sizeof(commands[0]), cmdcmp); - if ( !command ) + if (!command) return qfalse; command->func(); return qtrue; } -static const char *gcmds[] = { - "bow", - "entitylist", - "difficulty", - "flourish", - "force_absorb", - "force_distract", - "force_grip", - "force_heal", - "force_protect", - "force_pull", - "force_rage", - "force_sight", - "force_speed", - "force_throw", - "give", - "gloat", - "god", - "invuse", - "kill", - "meditate", - "nav", - "noclip", - "notarget", - "npc", - "playermodel", - "playerteam", - "playertint", - "runscript", - "saber", - "saberAttackCycle", - "saberColor", - "saberblade", - "secrets", - "setForceAll", - "setSaberAll", - "setobjective", - "setviewpos", - "taunt", - "undying", - "use_bacta", - "use_electrobinoculars", - "use_lightamp_goggles", - "use_seeker", - "use_sentry", - "viewobjective" -}; -static const size_t numgcmds = ARRAY_LEN( gcmds ); +static const char *gcmds[] = {"bow", + "entitylist", + "difficulty", + "flourish", + "force_absorb", + "force_distract", + "force_grip", + "force_heal", + "force_protect", + "force_pull", + "force_rage", + "force_sight", + "force_speed", + "force_throw", + "give", + "gloat", + "god", + "invuse", + "kill", + "meditate", + "nav", + "noclip", + "notarget", + "npc", + "playermodel", + "playerteam", + "playertint", + "runscript", + "saber", + "saberAttackCycle", + "saberColor", + "saberblade", + "secrets", + "setForceAll", + "setSaberAll", + "setobjective", + "setviewpos", + "taunt", + "undying", + "use_bacta", + "use_electrobinoculars", + "use_lightamp_goggles", + "use_seeker", + "use_sentry", + "viewobjective"}; +static const size_t numgcmds = ARRAY_LEN(gcmds); /* ================= @@ -333,16 +306,16 @@ Let the client system know about all of our commands so it can perform tab completion ================= */ -void CG_InitConsoleCommands( void ) { +void CG_InitConsoleCommands(void) { size_t i; - for ( i = 0 ; i < numCommands ; i++ ) - cgi_AddCommand( commands[i].cmd ); + for (i = 0; i < numCommands; i++) + cgi_AddCommand(commands[i].cmd); // // the game server will interpret these commands, which will be automatically // forwarded to the server after they are not recognized locally // - for( i = 0; i < numgcmds; i++ ) - cgi_AddCommand( gcmds[i] ); + for (i = 0; i < numgcmds; i++) + cgi_AddCommand(gcmds[i]); } diff --git a/code/cgame/cg_credits.cpp b/code/cgame/cg_credits.cpp index 68ff647634..eb54866dd1 100644 --- a/code/cgame/cg_credits.cpp +++ b/code/cgame/cg_credits.cpp @@ -28,10 +28,9 @@ along with this program; if not, see . #include "cg_media.h" -#define fCARD_FADESECONDS 1.0f // fade up time, also fade down time -#define fCARD_SUSTAINSECONDS 2.0f // hold time before fade down -#define fLINE_SECONDTOSCROLLUP 15.0f // how long one line takes to scroll up the screen - +#define fCARD_FADESECONDS 1.0f // fade up time, also fade down time +#define fCARD_SUSTAINSECONDS 2.0f // hold time before fade down +#define fLINE_SECONDTOSCROLLUP 15.0f // how long one line takes to scroll up the screen #define MAX_LINE_BYTES 2048 @@ -39,97 +38,76 @@ qhandle_t ghFontHandle = 0; float gfFontScale = 1.0f; vec4_t gv4Color = {0}; -struct StringAndSize_t -{ +struct StringAndSize_t { int iStrLenPixels; std::string str; - StringAndSize_t() - { + StringAndSize_t() { iStrLenPixels = -1; str = ""; } - StringAndSize_t(const char *psString) - { + StringAndSize_t(const char *psString) { iStrLenPixels = -1; str = psString; } - StringAndSize_t & operator = (const char *psString) - { + StringAndSize_t &operator=(const char *psString) { iStrLenPixels = -1; str = psString; return *this; } - const char *c_str(void) - { - return str.c_str(); - } + const char *c_str(void) { return str.c_str(); } - int GetPixelLength(void) - { - if (iStrLenPixels == -1) - { + int GetPixelLength(void) { + if (iStrLenPixels == -1) { iStrLenPixels = cgi_R_Font_StrLenPixels(str.c_str(), ghFontHandle, gfFontScale); } return iStrLenPixels; } - bool IsEmpty(void) - { - return str.empty(); - } + bool IsEmpty(void) { return str.empty(); } }; -struct CreditCard_t -{ - int iTime; - StringAndSize_t strTitle; +struct CreditCard_t { + int iTime; + StringAndSize_t strTitle; std::vector vstrText; - CreditCard_t() - { - iTime = -1; // flag "not set yet" + CreditCard_t() { + iTime = -1; // flag "not set yet" } }; -struct CreditLine_t -{ - int iLine; - StringAndSize_t strText; +struct CreditLine_t { + int iLine; + StringAndSize_t strText; std::vector vstrText; - bool bDotted; + bool bDotted; }; -typedef std::list CreditLines_t; -typedef std::list CreditCards_t; +typedef std::list CreditLines_t; +typedef std::list CreditCards_t; -struct CreditData_t -{ - int iStartTime; +struct CreditData_t { + int iStartTime; CreditCards_t CreditCards; CreditLines_t CreditLines; - qboolean Running(void) - { - return (qboolean)( CreditCards.size() || CreditLines.size() ); - } + qboolean Running(void) { return (qboolean)(CreditCards.size() || CreditLines.size()); } }; CreditData_t CreditData; - -static const char *Capitalize(const char *psTest) -{ +static const char *Capitalize(const char *psTest) { static char sTemp[MAX_LINE_BYTES]; Q_strncpyz(sTemp, psTest, sizeof(sTemp)); -// if (!cgi_Language_IsAsian()) // we don't have asian credits, so this is ok to do now + // if (!cgi_Language_IsAsian()) // we don't have asian credits, so this is ok to do now { - Q_strupr(sTemp); // capitalise titles (if not asian!!!!) + Q_strupr(sTemp); // capitalise titles (if not asian!!!!) } return sTemp; @@ -137,71 +115,62 @@ static const char *Capitalize(const char *psTest) // cope with hyphenated names and initials (awkward gits)... // -static bool CountsAsWhiteSpaceForCaps( unsigned /* avoid euro-char sign-extend assert within isspace()*/char c ) -{ - return !!(isspace(c) || c == '-' || c == '.' || c == '(' || c == ')' || c=='\''); +static bool CountsAsWhiteSpaceForCaps(unsigned /* avoid euro-char sign-extend assert within isspace()*/ char c) { + return !!(isspace(c) || c == '-' || c == '.' || c == '(' || c == ')' || c == '\''); } -static const char *UpperCaseFirstLettersOnly(const char *psTest) -{ +static const char *UpperCaseFirstLettersOnly(const char *psTest) { static char sTemp[MAX_LINE_BYTES]; Q_strncpyz(sTemp, psTest, sizeof(sTemp)); -// if (!cgi_Language_IsAsian()) // we don't have asian credits, so this is ok to do now + // if (!cgi_Language_IsAsian()) // we don't have asian credits, so this is ok to do now { Q_strlwr(sTemp); char *p = sTemp; - while (*p) - { - while (*p && CountsAsWhiteSpaceForCaps(*p)) p++; - if (*p) - { + while (*p) { + while (*p && CountsAsWhiteSpaceForCaps(*p)) + p++; + if (*p) { *p = toupper(*p); - while (*p && !CountsAsWhiteSpaceForCaps(*p)) p++; + while (*p && !CountsAsWhiteSpaceForCaps(*p)) + p++; } } } // now restore any weird stuff... // - char *p = strstr(sTemp," Mc"); // eg "Mcfarrell" should be "McFarrell" - if (p && isalpha(p[3])) - { + char *p = strstr(sTemp, " Mc"); // eg "Mcfarrell" should be "McFarrell" + if (p && isalpha(p[3])) { p[3] = toupper(p[3]); } - p = strstr(sTemp," O'"); // eg "O'flaherty" should be "O'Flaherty" (this is probably done automatically now, but wtf. - if (p && isalpha(p[3])) - { + p = strstr(sTemp, " O'"); // eg "O'flaherty" should be "O'Flaherty" (this is probably done automatically now, but wtf. + if (p && isalpha(p[3])) { p[3] = toupper(p[3]); } - p = strstr(sTemp,"Lucasarts"); - if (p) - { - p[5] = 'A'; // capitalise the 'A' in LucasArts (jeez...) + p = strstr(sTemp, "Lucasarts"); + if (p) { + p[5] = 'A'; // capitalise the 'A' in LucasArts (jeez...) } return sTemp; } -static const char *GetSubString(std::string &strResult) -{ +static const char *GetSubString(std::string &strResult) { static char sTemp[MAX_LINE_BYTES]; if (!strlen(strResult.c_str())) return NULL; - Q_strncpyz(sTemp,strResult.c_str(),sizeof(sTemp)); + Q_strncpyz(sTemp, strResult.c_str(), sizeof(sTemp)); - char *psSemiColon = strchr(sTemp,';'); - if ( psSemiColon) - { - *psSemiColon = '\0'; + char *psSemiColon = strchr(sTemp, ';'); + if (psSemiColon) { + *psSemiColon = '\0'; - strResult.erase(0,(psSemiColon-sTemp)+1); - } - else - { + strResult.erase(0, (psSemiColon - sTemp) + 1); + } else { // no semicolon found, probably last entry? (though i think even those have them on, oh well) // strResult.erase(); @@ -212,28 +181,21 @@ static const char *GetSubString(std::string &strResult) // sort entries by their last name (starts at back of string and moves forward until start or just before whitespace) // ... -static bool SortBySurname(const StringAndSize_t &str1, const StringAndSize_t &str2) -{ +static bool SortBySurname(const StringAndSize_t &str1, const StringAndSize_t &str2) { std::string::const_reverse_iterator rstart1 = std::find_if(str1.str.rbegin(), str1.str.rend(), isspace); std::string::const_reverse_iterator rstart2 = std::find_if(str2.str.rbegin(), str2.str.rend(), isspace); - return Q_stricmp(&*rstart1.base(), &*rstart2.base()) < 0; } - - -void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) -{ +void CG_Credits_Init(const char *psStripReference, vec4_t *pv4Color) { // Play the light side end credits music. - if ( g_entities[0].client->sess.mission_objectives[0].status != 2 ) - { - cgi_S_StartBackgroundTrack( "music/endcredits.mp3", NULL, qfalse ); + if (g_entities[0].client->sess.mission_objectives[0].status != 2) { + cgi_S_StartBackgroundTrack("music/endcredits.mp3", NULL, qfalse); } // Play the dark side end credits music. - else - { - cgi_S_StartBackgroundTrack( "music/vjun3/vjun3_explore.mp3", NULL, qfalse ); + else { + cgi_S_StartBackgroundTrack("music/vjun3/vjun3_explore.mp3", NULL, qfalse); } // could make these into parameters later, but for now... @@ -241,13 +203,12 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) ghFontHandle = cgs.media.qhFontMedium; gfFontScale = 1.0f; - memcpy(gv4Color,pv4Color,sizeof(gv4Color)); // memcpy so we can poke into alpha channel + memcpy(gv4Color, pv4Color, sizeof(gv4Color)); // memcpy so we can poke into alpha channel // first, ask the strlen of the final string... // - int iStrLen = cgi_SP_GetStringTextString( psStripReference, NULL, 0 ); - if (!iStrLen) - { + int iStrLen = cgi_SP_GetStringTextString(psStripReference, NULL, 0); + if (!iStrLen) { #ifndef FINAL_BUILD Com_Printf("WARNING: CG_Credits_Init(): invalid text key :'%s'\n", psStripReference); #endif @@ -256,15 +217,14 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) // // malloc space to hold it... // - char *psMallocText = (char *) cgi_Z_Malloc( iStrLen+1, TAG_TEMP_WORKSPACE ); + char *psMallocText = (char *)cgi_Z_Malloc(iStrLen + 1, TAG_TEMP_WORKSPACE); // // now get the string... // - iStrLen = cgi_SP_GetStringTextString( psStripReference, psMallocText, iStrLen+1 ); - //ensure we found a match - if (!iStrLen) - { - assert(0); // should never get here now, but wtf? + iStrLen = cgi_SP_GetStringTextString(psStripReference, psMallocText, iStrLen + 1); + // ensure we found a match + if (!iStrLen) { + assert(0); // should never get here now, but wtf? cgi_Z_Free(psMallocText); #ifndef FINAL_BUILD Com_Printf("WARNING: CG_Credits_Init(): invalid text key :'%s'\n", psStripReference); @@ -274,8 +234,7 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) // read whole string in and process as cards, lines etc... // - typedef enum - { + typedef enum { eNothing = 0, eLine, eDotEntry, @@ -288,15 +247,13 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) qboolean bCardsFinished = qfalse; int iLineNumber = 0; const char *psTextParse = psMallocText; - while (*psTextParse != '\0') - { + while (*psTextParse != '\0') { // read a line... // char sLine[MAX_LINE_BYTES]; - sLine[0]='\0'; + sLine[0] = '\0'; qboolean bWasCommand = qtrue; - while (1) - { + while (1) { qboolean bIsTrailingPunctuation; int iAdvanceCount; unsigned int uiLetter = cgi_AnyLanguage_ReadCharFromString(psTextParse, &iAdvanceCount, &bIsTrailingPunctuation); @@ -304,187 +261,142 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) // concat onto string so far... // - if (uiLetter == 32 && sLine[0] == '\0') - { - continue; // unless it's a space at the start of a line, in which case ignore it. + if (uiLetter == 32 && sLine[0] == '\0') { + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter == '\n' || uiLetter == '\0' ) - { + if (uiLetter == '\n' || uiLetter == '\0') { // have we got a command word?... // - if (!Q_stricmpn(sLine,"(#",2)) - { + if (!Q_stricmpn(sLine, "(#", 2)) { // yep... // - if (!Q_stricmp(sLine, "(#CARD)")) - { - if (!bCardsFinished) - { + if (!Q_stricmp(sLine, "(#CARD)")) { + if (!bCardsFinished) { eMode = eCard; - } - else - { - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW "CG_Credits_Init(): No current support for cards after scroll!\n" ); - #endif + } else { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "CG_Credits_Init(): No current support for cards after scroll!\n"); +#endif eMode = eNothing; } break; - } - else - if (!Q_stricmp(sLine, "(#TITLE)")) - { + } else if (!Q_stricmp(sLine, "(#TITLE)")) { eMode = eTitle; bCardsFinished = qtrue; break; - } - else - if (!Q_stricmp(sLine, "(#LINE)")) - { + } else if (!Q_stricmp(sLine, "(#LINE)")) { eMode = eLine; bCardsFinished = qtrue; break; - } - else - if (!Q_stricmp(sLine, "(#DOTENTRY)")) - { + } else if (!Q_stricmp(sLine, "(#DOTENTRY)")) { eMode = eDotEntry; bCardsFinished = qtrue; break; - } - else - { - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW "CG_Credits_Init(): bad keyword \"%s\"!\n", sLine ); - #endif + } else { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "CG_Credits_Init(): bad keyword \"%s\"!\n", sLine); +#endif eMode = eNothing; } - } - else - { + } else { // I guess not... // bWasCommand = qfalse; break; } - } - else - { + } else { // must be a letter... // - if (uiLetter > 255) - { - assert(0); // this means we're attempting to display asian credits, and we don't - // support these now because the auto-capitalisation rules etc would have to - // be inhibited. - Q_strcat(sLine, sizeof(sLine), va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLine, sizeof(sLine), va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + assert(0); // this means we're attempting to display asian credits, and we don't + // support these now because the auto-capitalisation rules etc would have to + // be inhibited. + Q_strcat(sLine, sizeof(sLine), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLine, sizeof(sLine), va("%c", uiLetter & 0xFF)); } } } // command?... // - if (bWasCommand) - { + if (bWasCommand) { // this'll just be a mode change, so ignore... // - } - else - { + } else { // else we've got some text to display... // - switch (eMode) - { - case eNothing: break; - case eLine: - { - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber++; - CreditLine.strText = sLine; - - CreditData.CreditLines.push_back( CreditLine ); - } + switch (eMode) { + case eNothing: break; - - case eDotEntry: - { - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber; - CreditLine.bDotted = true; - - std::string strResult(sLine); - const char *p; - while ((p=GetSubString(strResult)) != NULL) - { - if (CreditLine.strText.IsEmpty()) - { - CreditLine.strText = p; - } - else - { - CreditLine.vstrText.push_back( UpperCaseFirstLettersOnly(p) ); - } + case eLine: { + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber++; + CreditLine.strText = sLine; + + CreditData.CreditLines.push_back(CreditLine); + } break; + + case eDotEntry: { + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber; + CreditLine.bDotted = true; + + std::string strResult(sLine); + const char *p; + while ((p = GetSubString(strResult)) != NULL) { + if (CreditLine.strText.IsEmpty()) { + CreditLine.strText = p; + } else { + CreditLine.vstrText.push_back(UpperCaseFirstLettersOnly(p)); } + } - if (!CreditLine.strText.IsEmpty() && CreditLine.vstrText.size()) - { - // sort entries RHS dotted entries by alpha... - // - std::sort( CreditLine.vstrText.begin(), CreditLine.vstrText.end(), SortBySurname ); + if (!CreditLine.strText.IsEmpty() && CreditLine.vstrText.size()) { + // sort entries RHS dotted entries by alpha... + // + std::sort(CreditLine.vstrText.begin(), CreditLine.vstrText.end(), SortBySurname); - CreditData.CreditLines.push_back( CreditLine ); - iLineNumber += CreditLine.vstrText.size(); - } + CreditData.CreditLines.push_back(CreditLine); + iLineNumber += CreditLine.vstrText.size(); } - break; + } break; - case eTitle: - { - iLineNumber++; // leading blank line + case eTitle: { + iLineNumber++; // leading blank line - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber++; - CreditLine.strText = Capitalize(sLine); + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber++; + CreditLine.strText = Capitalize(sLine); - CreditData.CreditLines.push_back( CreditLine ); + CreditData.CreditLines.push_back(CreditLine); - iLineNumber++; // trailing blank line - break; - } - case eCard: - { - CreditCard_t CreditCard; - - std::string strResult(sLine); - const char *p; - while ((p=GetSubString(strResult)) != NULL) - { - if (CreditCard.strTitle.IsEmpty()) - { - CreditCard.strTitle = Capitalize( p ); - } - else - { - CreditCard.vstrText.push_back( UpperCaseFirstLettersOnly( p ) ); - } + iLineNumber++; // trailing blank line + break; + } + case eCard: { + CreditCard_t CreditCard; + + std::string strResult(sLine); + const char *p; + while ((p = GetSubString(strResult)) != NULL) { + if (CreditCard.strTitle.IsEmpty()) { + CreditCard.strTitle = Capitalize(p); + } else { + CreditCard.vstrText.push_back(UpperCaseFirstLettersOnly(p)); } + } - if (!CreditCard.strTitle.IsEmpty()) - { - // sort entries by alpha... - // - std::sort( CreditCard.vstrText.begin(), CreditCard.vstrText.end(), SortBySurname ); + if (!CreditCard.strTitle.IsEmpty()) { + // sort entries by alpha... + // + std::sort(CreditCard.vstrText.begin(), CreditCard.vstrText.end(), SortBySurname); - CreditData.CreditCards.push_back(CreditCard); - } + CreditData.CreditCards.push_back(CreditCard); } - break; - default: + } break; + default: break; } } @@ -494,31 +406,24 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color) CreditData.iStartTime = cg.time; } -qboolean CG_Credits_Running( void ) -{ - return CreditData.Running(); -} +qboolean CG_Credits_Running(void) { return CreditData.Running(); } // returns qtrue if still drawing... // -qboolean CG_Credits_Draw( void ) -{ - if ( CG_Credits_Running() ) - { - const int iFontHeight = (int) (1.5f * (float) cgi_R_Font_HeightPixels(ghFontHandle, gfFontScale)); // taiwanese & japanese need 1.5 fontheight spacing +qboolean CG_Credits_Draw(void) { + if (CG_Credits_Running()) { + const int iFontHeight = (int)(1.5f * (float)cgi_R_Font_HeightPixels(ghFontHandle, gfFontScale)); // taiwanese & japanese need 1.5 fontheight spacing -// cgi_R_SetColor( *gpv4Color ); + // cgi_R_SetColor( *gpv4Color ); // display cards first... // - if (CreditData.CreditCards.size()) - { + if (CreditData.CreditCards.size()) { // grab first card off the list (we know there's at least one here, so...) // CreditCard_t &CreditCard = (*CreditData.CreditCards.begin()); - if (CreditCard.iTime == -1) - { + if (CreditCard.iTime == -1) { // onceonly time init... // CreditCard.iTime = cg.time; @@ -527,65 +432,56 @@ qboolean CG_Credits_Draw( void ) // play with the alpha channel for fade up/down... // const float fMilliSecondsElapsed = cg.time - CreditCard.iTime; - const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; - if (fSecondsElapsed < fCARD_FADESECONDS) - { + const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; + if (fSecondsElapsed < fCARD_FADESECONDS) { // fading up... // gv4Color[3] = fSecondsElapsed / fCARD_FADESECONDS; -// OutputDebugString(va("fade up: %f\n",gv4Color[3])); - } - else - if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS) - { + // OutputDebugString(va("fade up: %f\n",gv4Color[3])); + } else if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS) { // fading down... // const float fFadeDownSeconds = fSecondsElapsed - (fCARD_FADESECONDS + fCARD_SUSTAINSECONDS); gv4Color[3] = 1.0f - (fFadeDownSeconds / fCARD_FADESECONDS); -// OutputDebugString(va("fade dw: %f\n",gv4Color[3])); - } - else - { + // OutputDebugString(va("fade dw: %f\n",gv4Color[3])); + } else { gv4Color[3] = 1.0f; -// OutputDebugString(va("normal: %f\n",gv4Color[3])); + // OutputDebugString(va("normal: %f\n",gv4Color[3])); } if (gv4Color[3] < 0.0f) - gv4Color[3] = 0.0f; // ... otherwise numbers that have dipped slightly -ve flash up fullbright after fade down + gv4Color[3] = 0.0f; // ... otherwise numbers that have dipped slightly -ve flash up fullbright after fade down // // how many lines is it? // - int iLines = CreditCard.vstrText.size() + 2; // +2 for title itself & one seperator line + int iLines = CreditCard.vstrText.size() + 2; // +2 for title itself & one seperator line // - int iYpos = (SCREEN_HEIGHT - (iLines * iFontHeight))/2; + int iYpos = (SCREEN_HEIGHT - (iLines * iFontHeight)) / 2; // // draw it, title first... // int iWidth = CreditCard.strTitle.GetPixelLength(); - int iXpos = (SCREEN_WIDTH - iWidth)/2; + int iXpos = (SCREEN_WIDTH - iWidth) / 2; cgi_R_Font_DrawString(iXpos, iYpos, CreditCard.strTitle.c_str(), gv4Color, ghFontHandle, -1, gfFontScale); // - iYpos += iFontHeight*2; // skip blank line then move to main pos + iYpos += iFontHeight * 2; // skip blank line then move to main pos // - for (size_t i=0; i fCARD_FADESECONDS + fCARD_SUSTAINSECONDS + fCARD_FADESECONDS) - { + if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS + fCARD_FADESECONDS) { // yep, so erase the first entry (which will trigger the next one to be initialised on re-entry)... // - CreditData.CreditCards.erase( CreditData.CreditCards.begin() ); + CreditData.CreditCards.erase(CreditData.CreditCards.begin()); - if (!CreditData.CreditCards.size()) - { + if (!CreditData.CreditCards.size()) { // all cards gone, so re-init timer for lines... // CreditData.iStartTime = cg.time; @@ -593,46 +489,38 @@ qboolean CG_Credits_Draw( void ) } // return qtrue; - } - else - { + } else { // doing scroll text... // - if (CreditData.CreditLines.size()) - { + if (CreditData.CreditLines.size()) { // process all lines... // const float fMilliSecondsElapsed = cg.time - CreditData.iStartTime; - const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; + const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; bool bEraseOccured = false; - for (CreditLines_t::iterator it = CreditData.CreditLines.begin(); it != CreditData.CreditLines.end(); bEraseOccured ? it : ++it) - { + for (CreditLines_t::iterator it = CreditData.CreditLines.begin(); it != CreditData.CreditLines.end(); bEraseOccured ? it : ++it) { CreditLine_t &CreditLine = (*it); bEraseOccured = false; static const float fPixelsPerSecond = ((float)SCREEN_HEIGHT / fLINE_SECONDTOSCROLLUP); int iYpos = SCREEN_HEIGHT + (CreditLine.iLine * iFontHeight); - iYpos-= (int) (fPixelsPerSecond * fSecondsElapsed); + iYpos -= (int)(fPixelsPerSecond * fSecondsElapsed); - int iTextLinesThisItem = Q_max( (int)CreditLine.vstrText.size(), 1); - if (iYpos + (iTextLinesThisItem * iFontHeight) < 0) - { + int iTextLinesThisItem = Q_max((int)CreditLine.vstrText.size(), 1); + if (iYpos + (iTextLinesThisItem * iFontHeight) < 0) { // scrolled off top of screen, so erase it... // - it = CreditData.CreditLines.erase( it ); + it = CreditData.CreditLines.erase(it); bEraseOccured = true; - } - else - if (iYpos < SCREEN_HEIGHT) - { + } else if (iYpos < SCREEN_HEIGHT) { // onscreen, so print it... // - bool bIsDotted = !!CreditLine.vstrText.size(); // eg "STUNTS ...................... MR ED" + bool bIsDotted = !!CreditLine.vstrText.size(); // eg "STUNTS ...................... MR ED" int iWidth = CreditLine.strText.GetPixelLength(); - int iXpos = bIsDotted ? 4 : (SCREEN_WIDTH - iWidth)/2; + int iXpos = bIsDotted ? 4 : (SCREEN_WIDTH - iWidth) / 2; gv4Color[3] = 1.0f; @@ -640,11 +528,10 @@ qboolean CG_Credits_Draw( void ) // now print any dotted members... // - for (size_t i=0; i. #include "../game/objectives.h" #include "../game/g_vehicles.h" -extern vmCvar_t cg_debugHealthBars; +extern vmCvar_t cg_debugHealthBars; -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); void CG_DrawIconBackground(void); -void CG_DrawMissionInformation( void ); -void CG_DrawInventorySelect( void ); -void CG_DrawForceSelect( void ); +void CG_DrawMissionInformation(void); +void CG_DrawInventorySelect(void); +void CG_DrawForceSelect(void); qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y); qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y); @@ -52,13 +52,13 @@ extern int g_rocketLockEntNum; extern int g_rocketLockTime; extern int g_rocketSlackTime; -vec3_t vfwd; -vec3_t vright; -vec3_t vup; -vec3_t vfwd_n; -vec3_t vright_n; -vec3_t vup_n; -int infoStringCount; +vec3_t vfwd; +vec3_t vright; +vec3_t vup; +vec3_t vfwd_n; +vec3_t vright_n; +vec3_t vup_n; +int infoStringCount; int cgRageTime = 0; int cgRageFadeTime = 0; @@ -77,22 +77,17 @@ int cgProtectFadeTime = 0; float cgProtectFadeVal = 0; //=============================================================== - /* ================ CG_DrawMessageLit ================ */ -static void CG_DrawMessageLit(centity_t *cent,int x,int y) -{ +static void CG_DrawMessageLit(centity_t *cent, int x, int y) { cgi_R_SetColor(colorTable[CT_WHITE]); - if (cg.missionInfoFlashTime > cg.time ) - { - if (!((cg.time / 600 ) & 1)) - { - if (!cg.messageLitActive) - { + if (cg.missionInfoFlashTime > cg.time) { + if (!((cg.time / 600) & 1)) { + if (!cg.messageLitActive) { /* kef 4/16/03 -- as fun as this was, its time has passed. I will, however, hijack this cvar at James' @@ -107,17 +102,14 @@ static void CG_DrawMessageLit(centity_t *cent,int x,int y) } cgi_R_SetColor(colorTable[CT_HUD_RED]); - CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOn); - } - else - { + CG_DrawPic(x + 33, y + 41, 16, 16, cgs.media.messageLitOn); + } else { cg.messageLitActive = qfalse; } } cgi_R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOff); - + CG_DrawPic(x + 33, y + 41, 16, 16, cgs.media.messageLitOff); } /* @@ -128,126 +120,90 @@ Draw the force power graphics (tics) and the force power numeric amount. Any tic be alphaed out. ================ */ -static void CG_DrawForcePower(const centity_t *cent,const int xPos,const int yPos) -{ - int i; - qboolean flash=qfalse; - vec4_t calcColor; - float value,extra=0,inc,percent; +static void CG_DrawForcePower(const centity_t *cent, const int xPos, const int yPos) { + int i; + qboolean flash = qfalse; + vec4_t calcColor; + float value, extra = 0, inc, percent; - if ( !cent->gent->client->ps.forcePowersKnown ) - { + if (!cent->gent->client->ps.forcePowersKnown) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time - if (cg.forceHUDTotalFlashTime > cg.time ) - { + if (cg.forceHUDTotalFlashTime > cg.time) { flash = qtrue; - if (cg.forceHUDNextFlashTime < cg.time) - { + if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; - cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.noforceSound ); - if (cg.forceHUDActive) - { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.noforceSound); + if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; - } - else - { + } else { cg.forceHUDActive = qtrue; } - } - } - else // turn HUD back on if it had just finished flashing time. + } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; } // I left the funtionality for flashing in because I might be needed yet. -// if (!cg.forceHUDActive) -// { -// return; -// } + // if (!cg.forceHUDActive) + // { + // return; + // } - inc = (float) cent->gent->client->ps.forcePowerMax / MAX_HUD_TICS; + inc = (float)cent->gent->client->ps.forcePowerMax / MAX_HUD_TICS; value = cent->gent->client->ps.forcePower; - if ( value > cent->gent->client->ps.forcePowerMax ) - {//supercharged with force + if (value > cent->gent->client->ps.forcePowerMax) { // supercharged with force extra = value - cent->gent->client->ps.forcePowerMax; value = cent->gent->client->ps.forcePowerMax; } - for (i=MAX_HUD_TICS-1;i>=0;i--) - { - if ( extra ) - {//supercharged + for (i = MAX_HUD_TICS - 1; i >= 0; i--) { + if (extra) { // supercharged memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - percent = 0.75f + (sin( cg.time * 0.005f )*((extra/cent->gent->client->ps.forcePowerMax)*0.25f)); + percent = 0.75f + (sin(cg.time * 0.005f) * ((extra / cent->gent->client->ps.forcePowerMax) * 0.25f)); calcColor[0] *= percent; calcColor[1] *= percent; calcColor[2] *= percent; - } - else if ( value <= 0 ) // no more + } else if (value <= 0) // no more { break; - } - else if (value < inc) // partial tic + } else if (value < inc) // partial tic { - if (flash) - { - memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); - } - else - { - memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + if (flash) { + memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); + } else { + memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } percent = value / inc; calcColor[3] = percent; - } - else - { - if (flash) - { - memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); - } - else - { - memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + } else { + if (flash) { + memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); + } else { + memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } } - cgi_R_SetColor( calcColor); - CG_DrawPic( forceTics[i].xPos, - forceTics[i].yPos, - forceTics[i].width, - forceTics[i].height, - forceTics[i].background ); + cgi_R_SetColor(calcColor); + CG_DrawPic(forceTics[i].xPos, forceTics[i].yPos, forceTics[i].width, forceTics[i].height, forceTics[i].background); value -= inc; } - if (flash) - { - cgi_R_SetColor( colorTable[CT_RED] ); - } - else - { - cgi_R_SetColor( otherHUDBits[OHB_FORCEAMOUNT].color ); + if (flash) { + cgi_R_SetColor(colorTable[CT_RED]); + } else { + cgi_R_SetColor(otherHUDBits[OHB_FORCEAMOUNT].color); } // Print force numeric amount - CG_DrawNumField ( - otherHUDBits[OHB_FORCEAMOUNT].xPos, - otherHUDBits[OHB_FORCEAMOUNT].yPos, - 3, - cent->gent->client->ps.forcePower, - otherHUDBits[OHB_FORCEAMOUNT].width, - otherHUDBits[OHB_FORCEAMOUNT].height, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(otherHUDBits[OHB_FORCEAMOUNT].xPos, otherHUDBits[OHB_FORCEAMOUNT].yPos, 3, cent->gent->client->ps.forcePower, + otherHUDBits[OHB_FORCEAMOUNT].width, otherHUDBits[OHB_FORCEAMOUNT].height, NUM_FONT_SMALL, qfalse); } /* @@ -258,54 +214,36 @@ If the weapon is a light saber (which needs no ammo) then draw a graphic showing the saber style (fast, medium, strong) ================ */ -static void CG_DrawSaberStyle(const centity_t *cent,const int xPos,const int yPos) -{ +static void CG_DrawSaberStyle(const centity_t *cent, const int xPos, const int yPos) { int index; - if (!cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon != WP_SABER || !cent->gent ) - { + if (cent->currentState.weapon != WP_SABER || !cent->gent) { return; } - cgi_R_SetColor( colorTable[CT_WHITE] ); + cgi_R_SetColor(colorTable[CT_WHITE]); - if ( !cg.saberAnimLevelPending && cent->gent->client ) - {//uninitialized after a loadgame, cheat across and get it + if (!cg.saberAnimLevelPending && cent->gent->client) { // uninitialized after a loadgame, cheat across and get it cg.saberAnimLevelPending = cent->gent->client->ps.saberAnimLevel; } // don't need to draw ammo, but we will draw the current saber style in this window - if (cg.saberAnimLevelPending == SS_FAST - || cg.saberAnimLevelPending == SS_TAVION ) - { + if (cg.saberAnimLevelPending == SS_FAST || cg.saberAnimLevelPending == SS_TAVION) { index = OHB_SABERSTYLE_FAST; - } - else if (cg.saberAnimLevelPending == SS_MEDIUM - || cg.saberAnimLevelPending == SS_DUAL - || cg.saberAnimLevelPending == SS_STAFF ) - { + } else if (cg.saberAnimLevelPending == SS_MEDIUM || cg.saberAnimLevelPending == SS_DUAL || cg.saberAnimLevelPending == SS_STAFF) { index = OHB_SABERSTYLE_MEDIUM; - } - else - { + } else { index = OHB_SABERSTYLE_STRONG; } - cgi_R_SetColor( otherHUDBits[index].color); - - CG_DrawPic( - otherHUDBits[index].xPos, - otherHUDBits[index].yPos, - otherHUDBits[index].width, - otherHUDBits[index].height, - otherHUDBits[index].background - ); + cgi_R_SetColor(otherHUDBits[index].color); + CG_DrawPic(otherHUDBits[index].xPos, otherHUDBits[index].yPos, otherHUDBits[index].width, otherHUDBits[index].height, otherHUDBits[index].background); } /* @@ -316,20 +254,18 @@ Draw the ammo graphics (tics) and the ammo numeric amount. Any tics that are par be alphaed out. ================ */ -static void CG_DrawAmmo(const centity_t *cent,const int xPos,const int yPos) -{ - playerState_t *ps; - int i; - vec4_t calcColor; - float currValue=0,inc; +static void CG_DrawAmmo(const centity_t *cent, const int xPos, const int yPos) { + playerState_t *ps; + int i; + vec4_t calcColor; + float currValue = 0, inc; - if (!cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon == WP_STUN_BATON ) - { + if (cent->currentState.weapon == WP_STUN_BATON) { return; } @@ -337,154 +273,106 @@ static void CG_DrawAmmo(const centity_t *cent,const int xPos,const int yPos) currValue = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; - if (currValue < 0) // No ammo + if (currValue < 0) // No ammo { return; } - // // ammo // - if (cg.oldammo < currValue) - { + if (cg.oldammo < currValue) { cg.oldAmmoTime = cg.time + 200; } cg.oldammo = currValue; - // Determine the color of the numeric field // Firing or reloading? - if (( cg.predicted_player_state.weaponstate == WEAPON_FIRING - && cg.predicted_player_state.weaponTime > 100 )) - { + if ((cg.predicted_player_state.weaponstate == WEAPON_FIRING && cg.predicted_player_state.weaponTime > 100)) { memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t)); - } - else - { - if ( currValue > 0 ) - { - if (cg.oldAmmoTime > cg.time) - { + } else { + if (currValue > 0) { + if (cg.oldAmmoTime > cg.time) { memcpy(calcColor, colorTable[CT_YELLOW], sizeof(vec4_t)); - } - else - { + } else { memcpy(calcColor, otherHUDBits[OHB_AMMOAMOUNT].color, sizeof(vec4_t)); } - } - else - { + } else { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } } // Print number amount - cgi_R_SetColor( calcColor ); + cgi_R_SetColor(calcColor); - CG_DrawNumField ( - otherHUDBits[OHB_AMMOAMOUNT].xPos, - otherHUDBits[OHB_AMMOAMOUNT].yPos, - 3, - ps->ammo[weaponData[cent->currentState.weapon].ammoIndex], - otherHUDBits[OHB_AMMOAMOUNT].width, - otherHUDBits[OHB_AMMOAMOUNT].height, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(otherHUDBits[OHB_AMMOAMOUNT].xPos, otherHUDBits[OHB_AMMOAMOUNT].yPos, 3, ps->ammo[weaponData[cent->currentState.weapon].ammoIndex], + otherHUDBits[OHB_AMMOAMOUNT].width, otherHUDBits[OHB_AMMOAMOUNT].height, NUM_FONT_SMALL, qfalse); - - - inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; - currValue =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; + inc = (float)ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; + currValue = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - for (i=MAX_HUD_TICS-1;i>=0;i--) - { + for (i = MAX_HUD_TICS - 1; i >= 0; i--) { - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, ammoTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; calcColor[3] *= percent; } - cgi_R_SetColor( calcColor); - CG_DrawPic( ammoTics[i].xPos, - ammoTics[i].yPos, - ammoTics[i].width, - ammoTics[i].height, - ammoTics[i].background ); + cgi_R_SetColor(calcColor); + CG_DrawPic(ammoTics[i].xPos, ammoTics[i].yPos, ammoTics[i].width, ammoTics[i].height, ammoTics[i].background); currValue -= inc; } - } - /* ================ CG_DrawHealth ================ */ -static void CG_DrawHealth(const int x,const int y,const int w,const int h) -{ - vec4_t calcColor; - playerState_t *ps = &cg.snap->ps; +static void CG_DrawHealth(const int x, const int y, const int w, const int h) { + vec4_t calcColor; + playerState_t *ps = &cg.snap->ps; // Print all the tics of the health graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - float inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; + float inc = (float)ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; float currValue = ps->stats[STAT_HEALTH]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); int i; - for (i=(MAX_HUD_TICS-1);i>=0;i--) - { + for (i = (MAX_HUD_TICS - 1); i >= 0; i--) { - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, healthTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( - healthTics[i].xPos, - healthTics[i].yPos, - healthTics[i].width, - healthTics[i].height, - healthTics[i].background - ); + CG_DrawPic(healthTics[i].xPos, healthTics[i].yPos, healthTics[i].width, healthTics[i].height, healthTics[i].background); currValue -= inc; } - // Print force health amount - cgi_R_SetColor( otherHUDBits[OHB_HEALTHAMOUNT].color ); - - CG_DrawNumField ( - otherHUDBits[OHB_HEALTHAMOUNT].xPos, - otherHUDBits[OHB_HEALTHAMOUNT].yPos, - 3, - ps->stats[STAT_HEALTH], - otherHUDBits[OHB_HEALTHAMOUNT].width, - otherHUDBits[OHB_HEALTHAMOUNT].height, - NUM_FONT_SMALL, - qfalse); + cgi_R_SetColor(otherHUDBits[OHB_HEALTHAMOUNT].color); + CG_DrawNumField(otherHUDBits[OHB_HEALTHAMOUNT].xPos, otherHUDBits[OHB_HEALTHAMOUNT].yPos, 3, ps->stats[STAT_HEALTH], otherHUDBits[OHB_HEALTHAMOUNT].width, + otherHUDBits[OHB_HEALTHAMOUNT].height, NUM_FONT_SMALL, qfalse); } /* @@ -495,108 +383,74 @@ Draw the armor graphics (tics) and the armor numeric amount. Any tics that are p be alphaed out. ================ */ -static void CG_DrawArmor(const int x,const int y,const int w,const int h) -{ - vec4_t calcColor; - playerState_t *ps = &cg.snap->ps; +static void CG_DrawArmor(const int x, const int y, const int w, const int h) { + vec4_t calcColor; + playerState_t *ps = &cg.snap->ps; // Print all the tics of the armor graphic // Look at the amount of armor left and show only as much of the graphic as there is armor. // Use alpha to fade out partial section of armor // MAX_HEALTH is the same thing as max armor - float inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; + float inc = (float)ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; float currValue = ps->stats[STAT_ARMOR]; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); int i; - for (i=(MAX_HUD_TICS-1);i>=0;i--) - { + for (i = (MAX_HUD_TICS - 1); i >= 0; i--) { - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { memcpy(calcColor, armorTics[i].color, sizeof(vec4_t)); float percent = currValue / inc; calcColor[3] *= percent; } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - if ((i==(MAX_HUD_TICS-1)) && (currValue < inc)) - { - if (cg.HUDArmorFlag) - { - CG_DrawPic( - armorTics[i].xPos, - armorTics[i].yPos, - armorTics[i].width, - armorTics[i].height, - armorTics[i].background - ); + if ((i == (MAX_HUD_TICS - 1)) && (currValue < inc)) { + if (cg.HUDArmorFlag) { + CG_DrawPic(armorTics[i].xPos, armorTics[i].yPos, armorTics[i].width, armorTics[i].height, armorTics[i].background); } - } - else - { - CG_DrawPic( - armorTics[i].xPos, - armorTics[i].yPos, - armorTics[i].width, - armorTics[i].height, - armorTics[i].background - ); + } else { + CG_DrawPic(armorTics[i].xPos, armorTics[i].yPos, armorTics[i].width, armorTics[i].height, armorTics[i].background); } currValue -= inc; } // Print armor amount - cgi_R_SetColor( otherHUDBits[OHB_ARMORAMOUNT].color ); - - CG_DrawNumField ( - otherHUDBits[OHB_ARMORAMOUNT].xPos, - otherHUDBits[OHB_ARMORAMOUNT].yPos, - 3, - ps->stats[STAT_ARMOR], - otherHUDBits[OHB_ARMORAMOUNT].width, - otherHUDBits[OHB_ARMORAMOUNT].height, - NUM_FONT_SMALL, - qfalse); + cgi_R_SetColor(otherHUDBits[OHB_ARMORAMOUNT].color); + CG_DrawNumField(otherHUDBits[OHB_ARMORAMOUNT].xPos, otherHUDBits[OHB_ARMORAMOUNT].yPos, 3, ps->stats[STAT_ARMOR], otherHUDBits[OHB_ARMORAMOUNT].width, + otherHUDBits[OHB_ARMORAMOUNT].height, NUM_FONT_SMALL, qfalse); // If armor is low, flash a graphic to warn the player - if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC + if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC { - float quarterArmor = (float) (ps->stats[STAT_MAX_HEALTH] / 4.0f); + float quarterArmor = (float)(ps->stats[STAT_MAX_HEALTH] / 4.0f); // Make tic flash if armor is at 25% of full armor - if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says + if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says { - if (cg.HUDTickFlashTime < cg.time) // Flip at the same time + if (cg.HUDTickFlashTime < cg.time) // Flip at the same time { cg.HUDTickFlashTime = cg.time + 400; - if (cg.HUDArmorFlag) - { + if (cg.HUDArmorFlag) { cg.HUDArmorFlag = qfalse; - } - else - { + } else { cg.HUDArmorFlag = qtrue; } } + } else { + cg.HUDArmorFlag = qtrue; } - else - { - cg.HUDArmorFlag=qtrue; - } - } - else // No armor? Don't show it. + } else // No armor? Don't show it. { - cg.HUDArmorFlag=qfalse; + cg.HUDArmorFlag = qfalse; } - } #define MAX_VHUD_SHIELD_TICS 12 @@ -604,150 +458,101 @@ static void CG_DrawArmor(const int x,const int y,const int w,const int h) #define MAX_VHUD_ARMOR_TICS 5 #define MAX_VHUD_AMMO_TICS 5 -static void CG_DrawVehicleSheild( const centity_t *cent, const Vehicle_t *pVeh ) -{ - int xPos,yPos,width,height,i; - vec4_t color,calcColor; - qhandle_t background; +static void CG_DrawVehicleSheild(const centity_t *cent, const Vehicle_t *pVeh) { + int xPos, yPos, width, height, i; + vec4_t color, calcColor; + qhandle_t background; char itemName[64]; - float inc, currValue,maxHealth; + float inc, currValue, maxHealth; - //riding some kind of living creature - if ( pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_FLIER ) - { + // riding some kind of living creature + if (pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_FLIER) { maxHealth = 100.0f; currValue = pVeh->m_pParentEntity->health; - } - else //normal vehicle + } else // normal vehicle { maxHealth = pVeh->m_pVehicleInfo->armor; currValue = pVeh->m_iArmor; } - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "shieldbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; - for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "shield_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxHealth / MAX_VHUD_SHIELD_TICS; + for (i = 1; i <= MAX_VHUD_SHIELD_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "shield_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo("swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } } // The HUD.menu file has the graphic print with a negative height, so it will print from the bottom up. -static void CG_DrawVehicleTurboRecharge( const centity_t *cent, const Vehicle_t *pVeh ) -{ - int xPos,yPos,width,height; - qhandle_t background; - vec4_t color; - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "turborecharge", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - float percent=0.0f; - int diff = ( cg.time - pVeh->m_iTurboTime ); +static void CG_DrawVehicleTurboRecharge(const centity_t *cent, const Vehicle_t *pVeh) { + int xPos, yPos, width, height; + qhandle_t background; + vec4_t color; + + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "turborecharge", &xPos, &yPos, &width, &height, color, &background)) { + float percent = 0.0f; + int diff = (cg.time - pVeh->m_iTurboTime); // Calc max time - if (diff > pVeh->m_pVehicleInfo->turboRecharge) - { + if (diff > pVeh->m_pVehicleInfo->turboRecharge) { percent = 1.0f; - cgi_R_SetColor( colorTable[CT_GREEN] ); - } - else - { - percent = (float) diff / pVeh->m_pVehicleInfo->turboRecharge; - if (percent < 0.0f) - { + cgi_R_SetColor(colorTable[CT_GREEN]); + } else { + percent = (float)diff / pVeh->m_pVehicleInfo->turboRecharge; + if (percent < 0.0f) { percent = 0.0f; } - cgi_R_SetColor( colorTable[CT_RED] ); + cgi_R_SetColor(colorTable[CT_RED]); } height *= percent; - CG_DrawPic(xPos,yPos, width, height, cgs.media.whiteShader); // Top + CG_DrawPic(xPos, yPos, width, height, cgs.media.whiteShader); // Top } - - } -static void CG_DrawVehicleSpeed( const centity_t *cent, const Vehicle_t *pVeh, const char *entHud ) -{ - int xPos,yPos,width,height; - qhandle_t background; +static void CG_DrawVehicleSpeed(const centity_t *cent, const Vehicle_t *pVeh, const char *entHud) { + int xPos, yPos, width, height; + qhandle_t background; gentity_t *parent = pVeh->m_pParentEntity; playerState_t *parentPS = &parent->client->ps; - float currValue,maxSpeed; - vec4_t color,calcColor; + float currValue, maxSpeed; + vec4_t color, calcColor; float inc; int i; char itemName[64]; - if (cgi_UI_GetMenuItemInfo( - entHud, - "speedbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo(entHud, "speedbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } maxSpeed = pVeh->m_pVehicleInfo->speedMax; @@ -756,93 +561,61 @@ static void CG_DrawVehicleSpeed( const centity_t *cent, const Vehicle_t *pVeh, c // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxSpeed / MAX_VHUD_SPEED_TICS; - for (i=1;i<=MAX_VHUD_SPEED_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "speed_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - entHud, - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxSpeed / MAX_VHUD_SPEED_TICS; + for (i = 1; i <= MAX_VHUD_SPEED_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "speed_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo(entHud, itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } - if ( level.time > pVeh->m_iTurboTime ) - { + if (level.time > pVeh->m_iTurboTime) { memcpy(calcColor, color, sizeof(vec4_t)); - } - else // In turbo mode + } else // In turbo mode { - if (cg.VHUDFlashTime < cg.time) - { + if (cg.VHUDFlashTime < cg.time) { cg.VHUDFlashTime = cg.time + 400; - if (cg.VHUDTurboFlag) - { + if (cg.VHUDTurboFlag) { cg.VHUDTurboFlag = qfalse; - } - else - { + } else { cg.VHUDTurboFlag = qtrue; } } - if (cg.VHUDTurboFlag) - { + if (cg.VHUDTurboFlag) { memcpy(calcColor, colorTable[CT_LTRED1], sizeof(vec4_t)); - } - else - { + } else { memcpy(calcColor, color, sizeof(vec4_t)); } } - - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } - } -static void CG_DrawVehicleArmor( const centity_t *cent, const Vehicle_t *pVeh ) -{ - int xPos,yPos,width,height,i; - qhandle_t background; +static void CG_DrawVehicleArmor(const centity_t *cent, const Vehicle_t *pVeh) { + int xPos, yPos, width, height, i; + qhandle_t background; char itemName[64]; - float inc, currValue,maxArmor; - vec4_t color,calcColor; - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "armorbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + float inc, currValue, maxArmor; + vec4_t color, calcColor; + + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "armorbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } maxArmor = pVeh->m_iArmor; @@ -851,768 +624,497 @@ static void CG_DrawVehicleArmor( const centity_t *cent, const Vehicle_t *pVeh ) // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxArmor / MAX_VHUD_ARMOR_TICS; - for (i=1;i<=MAX_VHUD_ARMOR_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "armor_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxArmor / MAX_VHUD_ARMOR_TICS; + for (i = 1; i <= MAX_VHUD_ARMOR_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "armor_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo("swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } } -static void CG_DrawVehicleAmmo( const centity_t *cent, const Vehicle_t *pVeh ) -{ - int xPos,yPos,width,height,i; - qhandle_t background; +static void CG_DrawVehicleAmmo(const centity_t *cent, const Vehicle_t *pVeh) { + int xPos, yPos, width, height, i; + qhandle_t background; char itemName[64]; - float inc, currValue,maxAmmo; - vec4_t color,calcColor; - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "ammobackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + float inc, currValue, maxAmmo; + vec4_t color, calcColor; + + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "ammobackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } maxAmmo = pVeh->m_pVehicleInfo->weapon[0].ammoMax; currValue = pVeh->weaponStatus[0].ammo; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;i<=MAX_VHUD_AMMO_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "ammo_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxAmmo / MAX_VHUD_AMMO_TICS; + for (i = 1; i <= MAX_VHUD_AMMO_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "ammo_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo("swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor ); - CG_DrawPic( xPos, yPos, width, height, background ); + cgi_R_SetColor(calcColor); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } } - -static void CG_DrawVehicleAmmoUpper( const centity_t *cent, const Vehicle_t *pVeh ) -{ - int xPos,yPos,width,height,i; - qhandle_t background; +static void CG_DrawVehicleAmmoUpper(const centity_t *cent, const Vehicle_t *pVeh) { + int xPos, yPos, width, height, i; + qhandle_t background; char itemName[64]; - float inc, currValue,maxAmmo; - vec4_t color,calcColor; - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "ammoupperbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + float inc, currValue, maxAmmo; + vec4_t color, calcColor; + + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "ammoupperbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } maxAmmo = pVeh->m_pVehicleInfo->weapon[0].ammoMax; currValue = pVeh->weaponStatus[0].ammo; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;im_pVehicleInfo->weapon[1].ammoMax; currValue = pVeh->weaponStatus[1].ammo; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;igent && cent->gent->owner ) - { - if (( cent->gent->owner->flags & FL_GODMODE )) - { + if (cent->gent && cent->gent->owner) { + if ((cent->gent->owner->flags & FL_GODMODE)) { // chair is in godmode, so render the health of the player instead health = cent->gent->health; - } - else - { + } else { // render the chair health health = cent->gent->owner->health; } - } - else - { + } else { return; } - //riding some kind of living creature + // riding some kind of living creature maxHealth = (float)cent->gent->max_health; currValue = health; - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "shieldbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; - for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "shield_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxHealth / MAX_VHUD_SHIELD_TICS; + for (i = 1; i <= MAX_VHUD_SHIELD_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "shield_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo("swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } } -static void CG_DrawEmplacedGunHud( const centity_t *cent ) -{ - int xPos,yPos,width,height; - vec4_t color; - qhandle_t background; +static void CG_DrawEmplacedGunHud(const centity_t *cent) { + int xPos, yPos, width, height; + vec4_t color; + qhandle_t background; // Draw frame - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "leftframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); - } - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "rightframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } - CG_DrawEmplacedGunHealth( cent ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); + } + CG_DrawEmplacedGunHealth(cent); } - -static void CG_DrawItemHealth( float currValue, float maxHealth ) -{ - int xPos,yPos,width,height,i; - vec4_t color,calcColor; - qhandle_t background; +static void CG_DrawItemHealth(float currValue, float maxHealth) { + int xPos, yPos, width, height, i; + vec4_t color, calcColor; + qhandle_t background; char itemName[64]; float inc; - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "shieldbackground", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "shieldbackground", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxHealth / MAX_VHUD_SHIELD_TICS; - for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) - { - Com_sprintf( itemName, sizeof(itemName), "shield_tic%d", i ); - - if (!cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - itemName, - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { + inc = (float)maxHealth / MAX_VHUD_SHIELD_TICS; + for (i = 1; i <= MAX_VHUD_SHIELD_TICS; i++) { + Com_sprintf(itemName, sizeof(itemName), "shield_tic%d", i); + + if (!cgi_UI_GetMenuItemInfo("swoopvehiclehud", itemName, &xPos, &yPos, &width, &height, color, &background)) { continue; } memcpy(calcColor, color, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); currValue -= inc; } } -static void CG_DrawPanelTurretHud( void ) -{ - int xPos,yPos,width,height; - vec4_t color; - qhandle_t background; +static void CG_DrawPanelTurretHud(void) { + int xPos, yPos, width, height; + vec4_t color; + qhandle_t background; // Draw frame - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "leftframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); - } - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "rightframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } - CG_DrawItemHealth( - g_entities[cg.snap->ps.viewEntity].health, - (float)g_entities[cg.snap->ps.viewEntity].max_health - ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); + } + CG_DrawItemHealth(g_entities[cg.snap->ps.viewEntity].health, (float)g_entities[cg.snap->ps.viewEntity].max_health); } -static void CG_DrawATSTHud( centity_t *cent ) -{ - int xPos,yPos,width,height; - vec4_t color; - qhandle_t background; - float health; +static void CG_DrawATSTHud(centity_t *cent) { + int xPos, yPos, width, height; + vec4_t color; + qhandle_t background; + float health; - if ( !cg.snap - ||!g_entities[cg.snap->ps.viewEntity].activator ) - { + if (!cg.snap || !g_entities[cg.snap->ps.viewEntity].activator) { return; } // Draw frame - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "leftframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); - } - - if (cgi_UI_GetMenuItemInfo( - "swoopvehiclehud", - "rightframe", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "leftframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } - // we just calc the display value from the sum of health and armor - if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health - { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ); + if (cgi_UI_GetMenuItemInfo("swoopvehiclehud", "rightframe", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } - else + + // we just calc the display value from the sum of health and armor + if (g_entities[cg.snap->ps.viewEntity].activator) // ensure we can look back to the atst_drivable to get the max health { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ); + health = (g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]); + } else { + health = (g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]); } - CG_DrawItemHealth(health,g_entities[cg.snap->ps.viewEntity].activator->max_health ); + CG_DrawItemHealth(health, g_entities[cg.snap->ps.viewEntity].activator->max_health); - if (cgi_UI_GetMenuItemInfo( - "atsthud", - "background", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); + if (cgi_UI_GetMenuItemInfo("atsthud", "background", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); } - if (cgi_UI_GetMenuItemInfo( - "atsthud", - "outer_frame", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); - } - - if (cgi_UI_GetMenuItemInfo( - "atsthud", - "left_pic", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); + if (cgi_UI_GetMenuItemInfo("atsthud", "outer_frame", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); + } + + if (cgi_UI_GetMenuItemInfo("atsthud", "left_pic", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); - CG_DrawPic( xPos, yPos, width, height, background ); + CG_DrawPic(xPos, yPos, width, height, background); } } //----------------------------------------------------- -static qboolean CG_DrawCustomHealthHud( centity_t *cent ) -{ +static qboolean CG_DrawCustomHealthHud(centity_t *cent) { Vehicle_t *pVeh; // In a Weapon? - if (( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { + if ((cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { CG_DrawEmplacedGunHud(cent); // DRAW emplaced HUD -/* color[0] = color[1] = color[2] = 0.0f; - color[3] = 0.3f; + /* color[0] = color[1] = color[2] = 0.0f; + color[3] = 0.3f; - cgi_R_SetColor( color ); - CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); + cgi_R_SetColor( color ); + CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); - // NOTE: this looks ugly - if ( cent->gent && cent->gent->owner ) - { - if (( cent->gent->owner->flags & FL_GODMODE )) - { - // chair is in godmode, so render the health of the player instead - health = cent->gent->health / (float)cent->gent->max_health; - } - else - { - // render the chair health - health = cent->gent->owner->health / (float)cent->gent->owner->max_health; - } - } + // NOTE: this looks ugly + if ( cent->gent && cent->gent->owner ) + { + if (( cent->gent->owner->flags & FL_GODMODE )) + { + // chair is in godmode, so render the health of the player instead + health = cent->gent->health / (float)cent->gent->max_health; + } + else + { + // render the chair health + health = cent->gent->owner->health / (float)cent->gent->owner->max_health; + } + } - color[0] = 1.0f; - color[3] = 0.5f; + color[0] = 1.0f; + color[3] = 0.5f; - cgi_R_SetColor( color ); - CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); + cgi_R_SetColor( color ); + CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); -*/ + cgi_R_SetColor( colorTable[CT_WHITE] ); + CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); + */ return qfalse; // drew this hud, so don't draw the player one } // In an ATST - else if (( cent->currentState.eFlags & EF_IN_ATST )) - { + else if ((cent->currentState.eFlags & EF_IN_ATST)) { -/* - // we are an ATST... - color[0] = color[1] = color[2] = 0.0f; - color[3] = 0.3f; + /* + // we are an ATST... + color[0] = color[1] = color[2] = 0.0f; + color[3] = 0.3f; - cgi_R_SetColor( color ); - CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); + cgi_R_SetColor( color ); + CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); - // we just calc the display value from the sum of health and armor - if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health - { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ) / - (float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health ); - } - else - { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / - (float)(g_entities[cg.snap->ps.viewEntity].max_health + 800 ); // hacked max armor since we don't have an activator...should never happen - } + // we just calc the display value from the sum of health and armor + if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health + { + health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ) / + (float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health ); + } + else + { + health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / + (float)(g_entities[cg.snap->ps.viewEntity].max_health + 800 ); // hacked max armor since we don't have an activator...should never + happen + } - color[1] = 0.25f; // blue-green - color[2] = 1.0f; - color[3] = 0.5f; + color[1] = 0.25f; // blue-green + color[2] = 1.0f; + color[3] = 0.5f; - cgi_R_SetColor( color ); - CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); + cgi_R_SetColor( color ); + CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); -*/ + cgi_R_SetColor( colorTable[CT_WHITE] ); + CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); + */ CG_DrawATSTHud(cent); return qfalse; // drew this hud, so don't draw the player one } // In a vehicle - else if ( (pVeh = G_IsRidingVehicle( cent->gent ) ) != 0 ) - { + else if ((pVeh = G_IsRidingVehicle(cent->gent)) != 0) { - //riding some kind of living creature - if ( pVeh->m_pVehicleInfo->type == VH_ANIMAL ) - { - CG_DrawTauntaunHud( cent, pVeh ); - } - else - { - CG_DrawVehicleHud( cent, pVeh ); + // riding some kind of living creature + if (pVeh->m_pVehicleInfo->type == VH_ANIMAL) { + CG_DrawTauntaunHud(cent, pVeh); + } else { + CG_DrawVehicleHud(cent, pVeh); } return qtrue; // draw this hud AND the player one } // Other? - else if ( cg.snap->ps.viewEntity && ( g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD )) - { + else if (cg.snap->ps.viewEntity && (g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD)) { CG_DrawPanelTurretHud(); return qfalse; // drew this hud, so don't draw the player one } @@ -1621,100 +1123,90 @@ static qboolean CG_DrawCustomHealthHud( centity_t *cent ) } //-------------------------------------- -static void CG_DrawBatteryCharge( void ) -{ - if ( cg.batteryChargeTime > cg.time ) - { +static void CG_DrawBatteryCharge(void) { + if (cg.batteryChargeTime > cg.time) { vec4_t color; // FIXME: drawing it here will overwrite zoom masks...find a better place - if ( cg.batteryChargeTime < cg.time + 1000 ) - { + if (cg.batteryChargeTime < cg.time + 1000) { // fading out for the last second color[0] = color[1] = color[2] = 1.0f; color[3] = (cg.batteryChargeTime - cg.time) / 1000.0f; - } - else - { + } else { // draw full color[0] = color[1] = color[2] = color[3] = 1.0f; } - cgi_R_SetColor( color ); + cgi_R_SetColor(color); // batteries were just charged - CG_DrawPic( 605, 295, 24, 32, cgs.media.batteryChargeShader ); + CG_DrawPic(605, 295, 24, 32, cgs.media.batteryChargeShader); } } -#define SimpleHud_DrawString( x, y, str, color ) cgi_R_Font_DrawString( x, y, str, color, (int)0x80000000 | cgs.media.qhFontSmall, -1, 1.0f ) +#define SimpleHud_DrawString(x, y, str, color) cgi_R_Font_DrawString(x, y, str, color, (int)0x80000000 | cgs.media.qhFontSmall, -1, 1.0f) -static void CG_DrawSimpleSaberStyle( const centity_t *cent ) -{ - uint32_t calcColor; - char num[7] = { 0 }; - int weapX = 16; +static void CG_DrawSimpleSaberStyle(const centity_t *cent) { + uint32_t calcColor; + char num[7] = {0}; + int weapX = 16; - if ( !cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon != WP_SABER || !cent->gent ) - { + if (cent->currentState.weapon != WP_SABER || !cent->gent) { return; } - if ( !cg.saberAnimLevelPending && cent->gent && cent->gent->client ) - {//uninitialized after a loadgame, cheat across and get it + if (!cg.saberAnimLevelPending && cent->gent && cent->gent->client) { // uninitialized after a loadgame, cheat across and get it cg.saberAnimLevelPending = cent->gent->client->ps.saberAnimLevel; } - switch ( cg.saberAnimLevelPending ) - { + switch (cg.saberAnimLevelPending) { default: case SS_FAST: - Com_sprintf( num, sizeof( num ), "FAST" ); + Com_sprintf(num, sizeof(num), "FAST"); calcColor = CT_ICON_BLUE; weapX = 0; break; case SS_MEDIUM: - Com_sprintf( num, sizeof( num ), "MEDIUM" ); + Com_sprintf(num, sizeof(num), "MEDIUM"); calcColor = CT_YELLOW; break; case SS_STRONG: - Com_sprintf( num, sizeof( num ), "STRONG" ); + Com_sprintf(num, sizeof(num), "STRONG"); calcColor = CT_HUD_RED; break; case SS_DESANN: - Com_sprintf( num, sizeof( num ), "DESANN" ); + Com_sprintf(num, sizeof(num), "DESANN"); calcColor = CT_HUD_RED; break; case SS_TAVION: - Com_sprintf( num, sizeof( num ), "TAVION" ); + Com_sprintf(num, sizeof(num), "TAVION"); calcColor = CT_ICON_BLUE; break; case SS_DUAL: - Com_sprintf( num, sizeof( num ), "AKIMBO" ); + Com_sprintf(num, sizeof(num), "AKIMBO"); calcColor = CT_HUD_ORANGE; break; case SS_STAFF: - Com_sprintf( num, sizeof( num ), "STAFF" ); + Com_sprintf(num, sizeof(num), "STAFF"); calcColor = CT_HUD_ORANGE; break; } - SimpleHud_DrawString( SCREEN_WIDTH - (weapX + 16 + 32), (SCREEN_HEIGHT - 80) + 40, num, colorTable[calcColor] ); + SimpleHud_DrawString(SCREEN_WIDTH - (weapX + 16 + 32), (SCREEN_HEIGHT - 80) + 40, num, colorTable[calcColor]); } -static void CG_DrawSimpleAmmo( const centity_t *cent ) -{ - playerState_t *ps; - uint32_t calcColor; - int currValue = 0; - char num[16] = { 0 }; +static void CG_DrawSimpleAmmo(const centity_t *cent) { + playerState_t *ps; + uint32_t calcColor; + int currValue = 0; + char num[16] = {0}; - if ( !cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } @@ -1724,86 +1216,64 @@ static void CG_DrawSimpleAmmo( const centity_t *cent ) currValue = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; // No ammo - if ( currValue < 0 || (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0) ) - { - SimpleHud_DrawString( SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, "--", colorTable[CT_HUD_ORANGE] ); + if (currValue < 0 || (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0)) { + SimpleHud_DrawString(SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, "--", colorTable[CT_HUD_ORANGE]); return; } // // ammo // - if ( cg.oldammo < currValue ) - { + if (cg.oldammo < currValue) { cg.oldAmmoTime = cg.time + 200; } cg.oldammo = currValue; - // Determine the color of the numeric field // Firing or reloading? - if ( (cg.predicted_player_state.weaponstate == WEAPON_FIRING - && cg.predicted_player_state.weaponTime > 100) ) - { + if ((cg.predicted_player_state.weaponstate == WEAPON_FIRING && cg.predicted_player_state.weaponTime > 100)) { calcColor = CT_LTGREY; - } - else - { - if ( currValue > 0 ) - { - if ( cg.oldAmmoTime > cg.time ) - { + } else { + if (currValue > 0) { + if (cg.oldAmmoTime > cg.time) { calcColor = CT_YELLOW; - } - else - { + } else { calcColor = CT_HUD_ORANGE; } - } - else - { + } else { calcColor = CT_RED; } } - Com_sprintf( num, sizeof( num ), "%i", currValue ); + Com_sprintf(num, sizeof(num), "%i", currValue); - SimpleHud_DrawString( SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, num, colorTable[calcColor] ); + SimpleHud_DrawString(SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, num, colorTable[calcColor]); } -static void CG_DrawSimpleForcePower( const centity_t *cent ) -{ - uint32_t calcColor; - char num[16] = { 0 }; - qboolean flash = qfalse; +static void CG_DrawSimpleForcePower(const centity_t *cent) { + uint32_t calcColor; + char num[16] = {0}; + qboolean flash = qfalse; - if ( !cent->gent || !cent->gent->client->ps.forcePowersKnown ) - { + if (!cent->gent || !cent->gent->client->ps.forcePowersKnown) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time - if ( cg.forceHUDTotalFlashTime > cg.time ) - { + if (cg.forceHUDTotalFlashTime > cg.time) { flash = qtrue; - if ( cg.forceHUDNextFlashTime < cg.time ) - { + if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; - cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.noforceSound ); - if ( cg.forceHUDActive ) - { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.noforceSound); + if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; - } - else - { + } else { cg.forceHUDActive = qtrue; } - } - } - else // turn HUD back on if it had just finished flashing time. + } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; @@ -1812,9 +1282,9 @@ static void CG_DrawSimpleForcePower( const centity_t *cent ) // Determine the color of the numeric field calcColor = flash ? CT_RED : CT_ICON_BLUE; - Com_sprintf( num, sizeof( num ), "%i", cent->gent->client->ps.forcePower ); + Com_sprintf(num, sizeof(num), "%i", cent->gent->client->ps.forcePower); - SimpleHud_DrawString( SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40 + 14, num, colorTable[calcColor] ); + SimpleHud_DrawString(SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40 + 14, num, colorTable[calcColor]); } /* @@ -1822,121 +1292,89 @@ static void CG_DrawSimpleForcePower( const centity_t *cent ) CG_DrawHUD ================ */ -static void CG_DrawHUD( centity_t *cent ) -{ +static void CG_DrawHUD(centity_t *cent) { int value; - int sectionXPos,sectionYPos,sectionWidth,sectionHeight; + int sectionXPos, sectionYPos, sectionWidth, sectionHeight; - if ( cg_hudFiles.integer ) - { + if (cg_hudFiles.integer) { int x = 0; int y = SCREEN_HEIGHT - 80; - SimpleHud_DrawString( x + 16, y + 40, va( "%i", cg.snap->ps.stats[STAT_HEALTH] ), colorTable[CT_HUD_RED] ); + SimpleHud_DrawString(x + 16, y + 40, va("%i", cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_RED]); - SimpleHud_DrawString( x + 18 + 14, y + 40 + 14, va( "%i", cg.snap->ps.stats[STAT_ARMOR] ), colorTable[CT_HUD_GREEN] ); + SimpleHud_DrawString(x + 18 + 14, y + 40 + 14, va("%i", cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN]); - CG_DrawSimpleForcePower( cent ); + CG_DrawSimpleForcePower(cent); - if ( cent->currentState.weapon == WP_SABER ) - CG_DrawSimpleSaberStyle( cent ); + if (cent->currentState.weapon == WP_SABER) + CG_DrawSimpleSaberStyle(cent); else - CG_DrawSimpleAmmo( cent ); + CG_DrawSimpleAmmo(cent); return; } // Draw the lower left section of the HUD - if (cgi_UI_GetMenuInfo("lefthud",§ionXPos,§ionYPos,§ionWidth,§ionHeight)) - { + if (cgi_UI_GetMenuInfo("lefthud", §ionXPos, §ionYPos, §ionWidth, §ionHeight)) { // Draw all the HUD elements --eez - cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "lefthud" ), qtrue ); + cgi_UI_Menu_Paint(cgi_UI_GetMenuByName("lefthud"), qtrue); // Draw armor & health values - if ( cg_drawStatus.integer == 2 ) - { - CG_DrawSmallStringColor(sectionXPos+5, sectionYPos - 60,va("Armor:%d",cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN] ); - CG_DrawSmallStringColor(sectionXPos+5, sectionYPos - 40,va("Health:%d",cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN] ); + if (cg_drawStatus.integer == 2) { + CG_DrawSmallStringColor(sectionXPos + 5, sectionYPos - 60, va("Armor:%d", cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN]); + CG_DrawSmallStringColor(sectionXPos + 5, sectionYPos - 40, va("Health:%d", cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN]); } // Print scanline - cgi_R_SetColor( otherHUDBits[OHB_SCANLINE_LEFT].color); + cgi_R_SetColor(otherHUDBits[OHB_SCANLINE_LEFT].color); - CG_DrawPic( - otherHUDBits[OHB_SCANLINE_LEFT].xPos, - otherHUDBits[OHB_SCANLINE_LEFT].yPos, - otherHUDBits[OHB_SCANLINE_LEFT].width, - otherHUDBits[OHB_SCANLINE_LEFT].height, - otherHUDBits[OHB_SCANLINE_LEFT].background - ); + CG_DrawPic(otherHUDBits[OHB_SCANLINE_LEFT].xPos, otherHUDBits[OHB_SCANLINE_LEFT].yPos, otherHUDBits[OHB_SCANLINE_LEFT].width, + otherHUDBits[OHB_SCANLINE_LEFT].height, otherHUDBits[OHB_SCANLINE_LEFT].background); // Print frame - cgi_R_SetColor( otherHUDBits[OHB_FRAME_LEFT].color); - CG_DrawPic( - otherHUDBits[OHB_FRAME_LEFT].xPos, - otherHUDBits[OHB_FRAME_LEFT].yPos, - otherHUDBits[OHB_FRAME_LEFT].width, - otherHUDBits[OHB_FRAME_LEFT].height, - otherHUDBits[OHB_FRAME_LEFT].background - ); + cgi_R_SetColor(otherHUDBits[OHB_FRAME_LEFT].color); + CG_DrawPic(otherHUDBits[OHB_FRAME_LEFT].xPos, otherHUDBits[OHB_FRAME_LEFT].yPos, otherHUDBits[OHB_FRAME_LEFT].width, + otherHUDBits[OHB_FRAME_LEFT].height, otherHUDBits[OHB_FRAME_LEFT].background); - CG_DrawArmor(sectionXPos,sectionYPos,sectionWidth,sectionHeight); + CG_DrawArmor(sectionXPos, sectionYPos, sectionWidth, sectionHeight); - CG_DrawHealth(sectionXPos,sectionYPos,sectionWidth,sectionHeight); + CG_DrawHealth(sectionXPos, sectionYPos, sectionWidth, sectionHeight); } - // Draw the lower right section of the HUD - if (cgi_UI_GetMenuInfo("righthud",§ionXPos,§ionYPos,§ionWidth,§ionHeight)) - { + if (cgi_UI_GetMenuInfo("righthud", §ionXPos, §ionYPos, §ionWidth, §ionHeight)) { // Draw all the HUD elements --eez - cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "righthud" ), qtrue ); + cgi_UI_Menu_Paint(cgi_UI_GetMenuByName("righthud"), qtrue); // Draw armor & health values - if ( cg_drawStatus.integer == 2 ) - { - if ( cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent ) - { + if (cg_drawStatus.integer == 2) { + if (cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent) { value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; - CG_DrawSmallStringColor(sectionXPos, sectionYPos - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] ); + CG_DrawSmallStringColor(sectionXPos, sectionYPos - 60, va("Ammo:%d", value), colorTable[CT_HUD_GREEN]); } - CG_DrawSmallStringColor(sectionXPos, sectionYPos - 40,va("Force:%d",cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN] ); + CG_DrawSmallStringColor(sectionXPos, sectionYPos - 40, va("Force:%d", cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN]); } // Print scanline - cgi_R_SetColor( otherHUDBits[OHB_SCANLINE_RIGHT].color); - - CG_DrawPic( - otherHUDBits[OHB_SCANLINE_RIGHT].xPos, - otherHUDBits[OHB_SCANLINE_RIGHT].yPos, - otherHUDBits[OHB_SCANLINE_RIGHT].width, - otherHUDBits[OHB_SCANLINE_RIGHT].height, - otherHUDBits[OHB_SCANLINE_RIGHT].background - ); + cgi_R_SetColor(otherHUDBits[OHB_SCANLINE_RIGHT].color); + CG_DrawPic(otherHUDBits[OHB_SCANLINE_RIGHT].xPos, otherHUDBits[OHB_SCANLINE_RIGHT].yPos, otherHUDBits[OHB_SCANLINE_RIGHT].width, + otherHUDBits[OHB_SCANLINE_RIGHT].height, otherHUDBits[OHB_SCANLINE_RIGHT].background); // Print frame - cgi_R_SetColor( otherHUDBits[OHB_FRAME_RIGHT].color); - CG_DrawPic( - otherHUDBits[OHB_FRAME_RIGHT].xPos, - otherHUDBits[OHB_FRAME_RIGHT].yPos, - otherHUDBits[OHB_FRAME_RIGHT].width, - otherHUDBits[OHB_FRAME_RIGHT].height, - otherHUDBits[OHB_FRAME_RIGHT].background - ); + cgi_R_SetColor(otherHUDBits[OHB_FRAME_RIGHT].color); + CG_DrawPic(otherHUDBits[OHB_FRAME_RIGHT].xPos, otherHUDBits[OHB_FRAME_RIGHT].yPos, otherHUDBits[OHB_FRAME_RIGHT].width, + otherHUDBits[OHB_FRAME_RIGHT].height, otherHUDBits[OHB_FRAME_RIGHT].background); - CG_DrawForcePower(cent,sectionXPos,sectionYPos); + CG_DrawForcePower(cent, sectionXPos, sectionYPos); // Draw ammo tics or saber style - if ( cent->currentState.weapon == WP_SABER ) - { - CG_DrawSaberStyle(cent,sectionXPos,sectionYPos); - } - else - { - CG_DrawAmmo(cent,sectionXPos,sectionYPos); + if (cent->currentState.weapon == WP_SABER) { + CG_DrawSaberStyle(cent, sectionXPos, sectionYPos); + } else { + CG_DrawAmmo(cent, sectionXPos, sectionYPos); } -// CG_DrawMessageLit(cent,x,y); + // CG_DrawMessageLit(cent,x,y); } } @@ -1945,17 +1383,16 @@ static void CG_DrawHUD( centity_t *cent ) CG_ClearDataPadCvars ================ */ -void CG_ClearDataPadCvars( void ) -{ - cgi_Cvar_Set( "cg_updatedDataPadForcePower1", "0" ); - cgi_Cvar_Update( &cg_updatedDataPadForcePower1 ); - cgi_Cvar_Set( "cg_updatedDataPadForcePower2", "0" ); - cgi_Cvar_Update( &cg_updatedDataPadForcePower2 ); - cgi_Cvar_Set( "cg_updatedDataPadForcePower3", "0" ); - cgi_Cvar_Update( &cg_updatedDataPadForcePower3 ); - - cgi_Cvar_Set( "cg_updatedDataPadObjective", "0" ); - cgi_Cvar_Update( &cg_updatedDataPadObjective ); +void CG_ClearDataPadCvars(void) { + cgi_Cvar_Set("cg_updatedDataPadForcePower1", "0"); + cgi_Cvar_Update(&cg_updatedDataPadForcePower1); + cgi_Cvar_Set("cg_updatedDataPadForcePower2", "0"); + cgi_Cvar_Update(&cg_updatedDataPadForcePower2); + cgi_Cvar_Set("cg_updatedDataPadForcePower3", "0"); + cgi_Cvar_Update(&cg_updatedDataPadForcePower3); + + cgi_Cvar_Set("cg_updatedDataPadObjective", "0"); + cgi_Cvar_Update(&cg_updatedDataPadObjective); } /* @@ -1963,19 +1400,17 @@ void CG_ClearDataPadCvars( void ) CG_DrawDataPadHUD ================ */ -void CG_DrawDataPadHUD( centity_t *cent ) -{ - int x,y; +void CG_DrawDataPadHUD(centity_t *cent) { + int x, y; x = 34; y = 286; - CG_DrawHealth(x,y,80,80); + CG_DrawHealth(x, y, 80, 80); x = 526; - if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer))) - { + if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer))) { // Stop flashing light cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; @@ -1983,73 +1418,63 @@ void CG_DrawDataPadHUD( centity_t *cent ) // Set which force power to show. // cg_updatedDataPadForcePower is set from Q3_Interface, because force powers would only be given // from a script. - if (cg_updatedDataPadForcePower1.integer) - { + if (cg_updatedDataPadForcePower1.integer) { cg.DataPadforcepowerSelect = cg_updatedDataPadForcePower1.integer - 1; // Not pretty, I know - if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) - { //duh - cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS-1; - } - else if (cg.DataPadforcepowerSelect<0) - { - cg.DataPadforcepowerSelect=0; + if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) { // duh + cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS - 1; + } else if (cg.DataPadforcepowerSelect < 0) { + cg.DataPadforcepowerSelect = 0; } } -// CG_ClearDataPadCvars(); + // CG_ClearDataPadCvars(); } - CG_DrawForcePower(cent,x,y); - CG_DrawAmmo(cent,x,y); - CG_DrawMessageLit(cent,x,y); - - cgi_R_SetColor( colorTable[CT_WHITE]); - CG_DrawPic( 0, 0, 640, 480, cgs.media.dataPadFrame ); + CG_DrawForcePower(cent, x, y); + CG_DrawAmmo(cent, x, y); + CG_DrawMessageLit(cent, x, y); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(0, 0, 640, 480, cgs.media.dataPadFrame); } //------------------------ // CG_DrawZoomMask //------------------------ -static void CG_DrawBinocularNumbers( qboolean power ) -{ +static void CG_DrawBinocularNumbers(qboolean power) { vec4_t color1; - cgi_R_SetColor( colorTable[CT_BLACK]); - CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_BLACK]); + CG_DrawPic(212, 367, 200, 40, cgs.media.whiteShader); - if ( power ) - { + if (power) { // Numbers should be kind of greenish color1[0] = 0.2f; color1[1] = 0.4f; color1[2] = 0.2f; color1[3] = 0.3f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); // Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked // up with a bunch of magic numbers..... int val = ((int)((cg.refdefViewAngles[YAW] + 180) / 10)) * 10; float off = (cg.refdefViewAngles[YAW] + 180) - val; - for ( int i = -10; i < 30; i += 10 ) - { + for (int i = -10; i < 30; i += 10) { val -= 10; - if ( val < 0 ) - { + if (val < 0) { val += 360; } // we only want to draw the very far left one some of the time, if it's too far to the left it will poke outside the mask. - if (( off > 3.0f && i == -10 ) || i > -10 ) - { + if ((off > 3.0f && i == -10) || i > -10) { // draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like - CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue ); - CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader ); + CG_DrawNumField(155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue); + CG_DrawPic(245 + (i - 1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader); } } - CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay ); + CG_DrawPic(212, 367, 200, 28, cgs.media.binocularOverlay); } } @@ -2059,136 +1484,116 @@ CG_DrawZoomMask ================ */ -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp -static void CG_DrawZoomMask( void ) -{ - vec4_t color1; - centity_t *cent; - float level; - static qboolean flip = qtrue; - float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage - qboolean power = qfalse; +static void CG_DrawZoomMask(void) { + vec4_t color1; + centity_t *cent; + float level; + static qboolean flip = qtrue; + float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage + qboolean power = qfalse; cent = &cg_entities[0]; - if ( charge > 0.0f ) - { + if (charge > 0.0f) { power = qtrue; } //------------- // Binoculars //-------------------------------- - if ( cg.zoomMode == 1 ) - { - CG_RegisterItemVisuals( ITM_BINOCULARS_PICKUP ); + if (cg.zoomMode == 1) { + CG_RegisterItemVisuals(ITM_BINOCULARS_PICKUP); // zoom level level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } // Using a magic number to convert the zoom level to scale amount level *= 162.0f; - if ( power ) - { + if (power) { // draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(34, 48, 570, 362, cgs.media.binocularStatic); } - CG_DrawBinocularNumbers( power ); + CG_DrawBinocularNumbers(power); // Black out the area behind the battery display - cgi_R_SetColor( colorTable[CT_DKGREY]); - CG_DrawPic( 50, 389, 161, 16, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_DKGREY]); + CG_DrawPic(50, 389, 161, 16, cgs.media.whiteShader); - if ( power ) - { - color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; + if (power) { + color1[0] = sin(cg.time * 0.01f) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle ); + CG_DrawPic(82, 94, 16, 16, cgs.media.binocularCircle); } - CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask ); + CG_DrawPic(0, 0, 640, 480, cgs.media.binocularMask); - if ( power ) - { + if (power) { // Flickery color color1[0] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[1] = 0.8f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[2] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow ); - } - else - { + CG_DrawPic(4, 282 - level, 16, 16, cgs.media.binocularArrow); + } else { // No power color color1[0] = 0.15f; color1[1] = 0.15f; color1[2] = 0.15f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); } // The top triangle bit randomly flips when the power is on - if ( flip && power ) - { - CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri ); - } - else - { - CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri ); + if (flip && power) { + CG_DrawPic(330, 60, -26, -30, cgs.media.binocularTri); + } else { + CG_DrawPic(307, 40, 26, 30, cgs.media.binocularTri); } - if ( Q_flrand(0.0f, 1.0f) > 0.98f && ( cg.time & 1024 )) - { + if (Q_flrand(0.0f, 1.0f) > 0.98f && (cg.time & 1024)) { flip = (qboolean)!flip; } - if ( power ) - { - color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); + if (power) { + color1[0] = 1.0f * (charge < 0.2f ? !!(cg.time & 256) : 1); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.2f; - cgi_R_SetColor( color1 ); - CG_DrawPic( 60, 394.5f, charge * 141, 5, cgs.media.whiteShader ); + cgi_R_SetColor(color1); + CG_DrawPic(60, 394.5f, charge * 141, 5, cgs.media.whiteShader); } } //------------ // Disruptor //-------------------------------- - else if ( cg.zoomMode == 2 ) - { + else if (cg.zoomMode == 2) { level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } @@ -2196,31 +1601,29 @@ static void CG_DrawZoomMask( void ) level *= 103.0f; // Draw target mask - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(0, 0, 640, 480, cgs.media.disruptorMask); // apparently 99.0f is the full zoom level - if ( level >= 99 ) - { + if (level >= 99) { // Fully zoomed, so make the rotating insert pulse color1[0] = 1.0f; color1[1] = 1.0f; color1[2] = 1.0f; - color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f; + color1[3] = 0.7f + sin(cg.time * 0.01f) * 0.3f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); } // Draw rotating insert - CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert ); + CG_DrawRotatePic2(320, 240, 640, 480, -level, cgs.media.disruptorInsert); float cx, cy; float max; max = cg_entities[0].gent->client->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max; - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } @@ -2230,112 +1633,105 @@ static void CG_DrawZoomMask( void ) color1[3] = 1.0f; // If we are low on ammo, make us flash - if ( max < 0.15f && ( cg.time & 512 )) - { - VectorClear( color1 ); + if (max < 0.15f && (cg.time & 512)) { + VectorClear(color1); } - if ( color1[0] > 1.0f ) - { + if (color1[0] > 1.0f) { color1[0] = 1.0f; } - if ( color1[1] > 1.0f ) - { + if (color1[1] > 1.0f) { color1[1] = 1.0f; } - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); max *= 58.0f; - for ( float i = 18.5f; i <= 18.5f + max; i+= 3 ) // going from 15 to 45 degrees, with 5 degree increments + for (float i = 18.5f; i <= 18.5f + max; i += 3) // going from 15 to 45 degrees, with 5 degree increments { - cx = 320 + sin( (i+90.0f)/57.296f ) * 190; - cy = 240 + cos( (i+90.0f)/57.296f ) * 190; + cx = 320 + sin((i + 90.0f) / 57.296f) * 190; + cy = 240 + cos((i + 90.0f) / 57.296f) * 190; - CG_DrawRotatePic2( cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick ); + CG_DrawRotatePic2(cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick); } // FIXME: doesn't know about ammo!! which is bad because it draws charge beyond what ammo you may have.. - if ( cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT ) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); + if (cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT) { + cgi_R_SetColor(colorTable[CT_WHITE]); // draw the charge level - max = ( cg.time - cg_entities[0].gent->client->ps.weaponChargeTime ) / ( 150.0f * 10.0f ); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed. + max = (cg.time - cg_entities[0].gent->client->ps.weaponChargeTime) / + (150.0f * 10.0f); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed. - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } - CG_DrawPic2( 257, 435, 134 * max, 34, 0,0,max,1,cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" )); + CG_DrawPic2(257, 435, 134 * max, 34, 0, 0, max, 1, cgi_R_RegisterShaderNoMip("gfx/2d/crop_charge")); } } //----------- // Light Amp //-------------------------------- - else if ( cg.zoomMode == 3 ) - { - CG_RegisterItemVisuals( ITM_LA_GOGGLES_PICKUP ); + else if (cg.zoomMode == 3) { + CG_RegisterItemVisuals(ITM_LA_GOGGLES_PICKUP); - if ( power ) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 34, 29, 580, 410, cgs.media.laGogglesStatic ); + if (power) { + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(34, 29, 580, 410, cgs.media.laGogglesStatic); - CG_DrawPic( 570, 140, 12, 160, cgs.media.laGogglesSideBit ); + CG_DrawPic(570, 140, 12, 160, cgs.media.laGogglesSideBit); - float light = (128-cent->gent->lightLevel) * 0.5f; + float light = (128 - cent->gent->lightLevel) * 0.5f; - if ( light < -81 ) // saber can really jack up local light levels....?magic number?? + if (light < -81) // saber can really jack up local light levels....?magic number?? { light = -81; } float pos1 = 220 + light; - float pos2 = 220 + cos( cg.time * 0.0004f + light * 0.05f ) * 40 + sin( cg.time * 0.0013f + 1 ) * 20 + sin( cg.time * 0.0021f ) * 5; + float pos2 = 220 + cos(cg.time * 0.0004f + light * 0.05f) * 40 + sin(cg.time * 0.0013f + 1) * 20 + sin(cg.time * 0.0021f) * 5; // Flickery color color1[0] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[1] = 0.8f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[2] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 565, pos1, 22, 8, cgs.media.laGogglesBracket ); - CG_DrawPic( 558, pos2, 14, 5, cgs.media.laGogglesArrow ); + CG_DrawPic(565, pos1, 22, 8, cgs.media.laGogglesBracket); + CG_DrawPic(558, pos2, 14, 5, cgs.media.laGogglesArrow); } // Black out the area behind the battery display - cgi_R_SetColor( colorTable[CT_DKGREY]); - CG_DrawPic( 236, 357, 164, 16, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_DKGREY]); + CG_DrawPic(236, 357, 164, 16, cgs.media.whiteShader); - if ( power ) - { + if (power) { // Power bar - color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); + color1[0] = 1.0f * (charge < 0.2f ? !!(cg.time & 256) : 1); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.4f; - cgi_R_SetColor( color1 ); - CG_DrawPic( 247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader ); + cgi_R_SetColor(color1); + CG_DrawPic(247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader); // pulsing dot bit - color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; + color1[0] = sin(cg.time * 0.01f) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 65, 94, 16, 16, cgs.media.binocularCircle ); + CG_DrawPic(65, 94, 16, 16, cgs.media.binocularCircle); } - CG_DrawPic( 0, 0, 640, 480, cgs.media.laGogglesMask ); + CG_DrawPic(0, 0, 640, 480, cgs.media.laGogglesMask); } } @@ -2345,20 +1741,18 @@ CG_DrawStats ================ */ -static void CG_DrawStats( void ) -{ - centity_t *cent; +static void CG_DrawStats(void) { + centity_t *cent; - if ( cg_drawStatus.integer == 0 ) { + if (cg_drawStatus.integer == 0) { return; } cent = &cg_entities[cg.snap->ps.clientNum]; - if ((cg.snap->ps.viewEntity>0&&cg.snap->ps.viewEntityps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { // MIGHT try and draw a custom hud if it wants... - CG_DrawCustomHealthHud( cent ); + CG_DrawCustomHealthHud(cent); return; } @@ -2366,165 +1760,142 @@ static void CG_DrawStats( void ) qboolean drawHud = qtrue; - if ( cent && cent->gent ) - { - drawHud = CG_DrawCustomHealthHud( cent ); + if (cent && cent->gent) { + drawHud = CG_DrawCustomHealthHud(cent); } - if (( drawHud ) && ( cg_drawHUD.integer )) - { - CG_DrawHUD( cent ); + if ((drawHud) && (cg_drawHUD.integer)) { + CG_DrawHUD(cent); } } - /* =================== CG_DrawPickupItem =================== */ -static void CG_DrawPickupItem( void ) { - int value; - float *fadeColor; +static void CG_DrawPickupItem(void) { + int value; + float *fadeColor; value = cg.itemPickup; - if ( value && cg_items[ value ].icon != -1 ) - { - fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 ); - if ( fadeColor ) - { - CG_RegisterItemVisuals( value ); - cgi_R_SetColor( fadeColor ); - CG_DrawPic( 573, 320, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon ); - //CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] ); - //CG_DrawProportionalString( ICON_SIZE + 16, 398, + if (value && cg_items[value].icon != -1) { + fadeColor = CG_FadeColor(cg.itemPickupTime, 3000); + if (fadeColor) { + CG_RegisterItemVisuals(value); + cgi_R_SetColor(fadeColor); + CG_DrawPic(573, 320, ICON_SIZE, ICON_SIZE, cg_items[value].icon); + // CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] ); + // CG_DrawProportionalString( ICON_SIZE + 16, 398, // bg_itemlist[ value ].classname, CG_SMALLFONT,fadeColor ); - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } } } -void CMD_CGCam_Disable( void ); +void CMD_CGCam_Disable(void); /* =================== CG_DrawPickupItem =================== */ -void CG_DrawCredits(void) -{ - if (!cg.creditsStart) - { +void CG_DrawCredits(void) { + if (!cg.creditsStart) { // cg.creditsStart = qtrue; CG_Credits_Init("CREDITS_RAVEN", &colorTable[CT_ICON_BLUE]); - if ( cg_skippingcin.integer ) - {//Were skipping a cinematic and it's over now + if (cg_skippingcin.integer) { // Were skipping a cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } } - - if (cg.creditsStart) - { - if ( !CG_Credits_Running() ) - { - cgi_Cvar_Set( "cg_endcredits", "0" ); + if (cg.creditsStart) { + if (!CG_Credits_Running()) { + cgi_Cvar_Set("cg_endcredits", "0"); CMD_CGCam_Disable(); cgi_SendConsoleCommand("disconnect\n"); } } } -//draw the health bar based on current "health" and maxhealth -void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) -{ +// draw the health bar based on current "health" and maxhealth +void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t cColor; - float x = chX-(chW/2); - float y = chY-chH; + float x = chX - (chW / 2); + float y = chY - chH; float percent = 0.0f; - if ( !cent || !cent->gent ) - { + if (!cent || !cent->gent) { return; } - percent = ((float)cent->gent->health/(float)cent->gent->max_health); - if (percent <= 0) - { + percent = ((float)cent->gent->health / (float)cent->gent->max_health); + if (percent <= 0) { return; } - //color of the bar - //hostile + // color of the bar + // hostile aColor[0] = 1.0f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - //color of greyed out "missing health" + // color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, chW, chH, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f, (percent*chW)-1.0f, chH-1.0f, aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f, (percent * chW) - 1.0f, chH - 1.0f, aColor); - //then draw the other part greyed out - CG_FillRect(x+(percent*chW), y+1.0f, chW-(percent*chW)-1.0f, chH-1.0f, cColor); + // then draw the other part greyed out + CG_FillRect(x + (percent * chW), y + 1.0f, chW - (percent * chW) - 1.0f, chH - 1.0f, cColor); } #define MAX_HEALTH_BAR_ENTS 32 int cg_numHealthBarEnts = 0; int cg_healthBarEnts[MAX_HEALTH_BAR_ENTS]; -#define HEALTH_BAR_WIDTH 50 -#define HEALTH_BAR_HEIGHT 5 +#define HEALTH_BAR_WIDTH 50 +#define HEALTH_BAR_HEIGHT 5 -void CG_DrawHealthBars( void ) -{ - float chX=0, chY=0; +void CG_DrawHealthBars(void) { + float chX = 0, chY = 0; centity_t *cent; vec3_t pos; - for ( int i = 0; i < cg_numHealthBarEnts; i++ ) - { + for (int i = 0; i < cg_numHealthBarEnts; i++) { cent = &cg_entities[cg_healthBarEnts[i]]; - if ( cent && cent->gent ) - { - VectorCopy( cent->lerpOrigin, pos ); - pos[2] += cent->gent->maxs[2]+HEALTH_BAR_HEIGHT+8; - if ( CG_WorldCoordToScreenCoordFloat( pos, &chX, &chY ) ) - {//on screen - CG_DrawHealthBar( cent, chX, chY, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT ); + if (cent && cent->gent) { + VectorCopy(cent->lerpOrigin, pos); + pos[2] += cent->gent->maxs[2] + HEALTH_BAR_HEIGHT + 8; + if (CG_WorldCoordToScreenCoordFloat(pos, &chX, &chY)) { // on screen + CG_DrawHealthBar(cent, chX, chY, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT); } } } } #define HEALTHBARRANGE 422 -void CG_AddHealthBarEnt( int entNum ) -{ - if ( cg_numHealthBarEnts >= MAX_HEALTH_BAR_ENTS ) - {//FIXME: Debug error message? +void CG_AddHealthBarEnt(int entNum) { + if (cg_numHealthBarEnts >= MAX_HEALTH_BAR_ENTS) { // FIXME: Debug error message? return; } - if (DistanceSquared( cg_entities[entNum].lerpOrigin, g_entities[0].client->renderInfo.eyePoint ) < (HEALTHBARRANGE*HEALTHBARRANGE) ) - { + if (DistanceSquared(cg_entities[entNum].lerpOrigin, g_entities[0].client->renderInfo.eyePoint) < (HEALTHBARRANGE * HEALTHBARRANGE)) { cg_healthBarEnts[cg_numHealthBarEnts++] = entNum; } } -void CG_ClearHealthBarEnts( void ) -{ - if ( cg_numHealthBarEnts ) - { +void CG_ClearHealthBarEnts(void) { + if (cg_numHealthBarEnts) { cg_numHealthBarEnts = 0; - memset( &cg_healthBarEnts, 0, sizeof(cg_healthBarEnts) ); + memset(&cg_healthBarEnts, 0, sizeof(cg_healthBarEnts)); } } /* @@ -2535,190 +1906,147 @@ CROSSHAIR ================================================================================ */ - /* ================= CG_DrawCrosshair ================= */ -static void CG_DrawCrosshair( vec3_t worldPoint ) -{ - float w, h; - qhandle_t hShader; - qboolean corona = qfalse; - vec4_t ecolor; - float f; - float x, y; - - if ( !cg_drawCrosshair.integer ) - { +static void CG_DrawCrosshair(vec3_t worldPoint) { + float w, h; + qhandle_t hShader; + qboolean corona = qfalse; + vec4_t ecolor; + float f; + float x, y; + + if (!cg_drawCrosshair.integer) { return; } - if ( cg.zoomMode > 0 && cg.zoomMode < 3 ) - { - //not while scoped + if (cg.zoomMode > 0 && cg.zoomMode < 3) { + // not while scoped return; } - //set color based on what kind of ent is under crosshair - if ( g_crosshairEntNum >= ENTITYNUM_WORLD ) - { + // set color based on what kind of ent is under crosshair + if (g_crosshairEntNum >= ENTITYNUM_WORLD) { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; - } - else if ( cg_forceCrosshair && cg_crosshairForceHint.integer ) - { + } else if (cg_forceCrosshair && cg_crosshairForceHint.integer) { ecolor[0] = 0.2f; ecolor[1] = 0.5f; ecolor[2] = 1.0f; corona = qtrue; - } - else if ( cg_crosshairIdentifyTarget.integer ) - { + } else if (cg_crosshairIdentifyTarget.integer) { gentity_t *crossEnt = &g_entities[g_crosshairEntNum]; - if ( crossEnt->client ) - { - if ( crossEnt->client->ps.powerups[PW_CLOAKED] ) - {//cloaked don't show up - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B - } - else if ( g_entities[0].client && g_entities[0].client->playerTeam == TEAM_FREE ) - {//evil player: everyone is red - //Enemies are red - ecolor[0] = 1.0f;//R - ecolor[1] = 0.1f;//G - ecolor[2] = 0.1f;//B - } - else if ( crossEnt->client->playerTeam == TEAM_PLAYER ) - { - //Allies are green - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else if ( crossEnt->client->playerTeam == TEAM_NEUTRAL ) - { + if (crossEnt->client) { + if (crossEnt->client->ps.powerups[PW_CLOAKED]) { // cloaked don't show up + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B + } else if (g_entities[0].client && g_entities[0].client->playerTeam == TEAM_FREE) { // evil player: everyone is red + // Enemies are red + ecolor[0] = 1.0f; // R + ecolor[1] = 0.1f; // G + ecolor[2] = 0.1f; // B + } else if (crossEnt->client->playerTeam == TEAM_PLAYER) { + // Allies are green + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else if (crossEnt->client->playerTeam == TEAM_NEUTRAL) { // NOTE: was yellow, but making it white unless they really decide they want to see colors - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B + } else { + // Enemies are red + ecolor[0] = 1.0f; // R + ecolor[1] = 0.1f; // G + ecolor[2] = 0.1f; // B } - else - { - //Enemies are red - ecolor[0] = 1.0f;//R - ecolor[1] = 0.1f;//G - ecolor[2] = 0.1f;//B - } - } - else if ( crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags&SVF_NONNPC_ENEMY) ) - { + } else if (crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags & SVF_NONNPC_ENEMY)) { // a turret - if ( crossEnt->noDamageTeam == TEAM_PLAYER ) - { + if (crossEnt->noDamageTeam == TEAM_PLAYER) { // mine are green - ecolor[0] = 0.0;//R - ecolor[1] = 1.0;//G - ecolor[2] = 0.0;//B - } - else - { + ecolor[0] = 0.0; // R + ecolor[1] = 1.0; // G + ecolor[2] = 0.0; // B + } else { // hostile ones are red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B } - } - else if ( crossEnt->s.weapon == WP_TRIP_MINE ) - { + } else if (crossEnt->s.weapon == WP_TRIP_MINE) { // tripmines are red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B - } - else if ( (crossEnt->flags&FL_RED_CROSSHAIR) ) - {//special case flagged to turn crosshair red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B - } - else - { - VectorCopy( crossEnt->startRGBA, ecolor ); - - if ( !ecolor[0] && !ecolor[1] && !ecolor[2] ) - { + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B + } else if ((crossEnt->flags & FL_RED_CROSSHAIR)) { // special case flagged to turn crosshair red + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B + } else { + VectorCopy(crossEnt->startRGBA, ecolor); + + if (!ecolor[0] && !ecolor[1] && !ecolor[2]) { // We don't want a black crosshair, so use white since it will show up better - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B } } - } - else // cg_crosshairIdentifyTarget is not on, so make it white + } else // cg_crosshairIdentifyTarget is not on, so make it white { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; } ecolor[3] = 1.0; - cgi_R_SetColor( ecolor ); + cgi_R_SetColor(ecolor); - if ( cg.forceCrosshairStartTime ) - { + if (cg.forceCrosshairStartTime) { // both of these calcs will fade the corona in one direction - if ( cg.forceCrosshairEndTime ) - { + if (cg.forceCrosshairEndTime) { ecolor[3] = (cg.time - cg.forceCrosshairEndTime) / 500.0f; - } - else - { + } else { ecolor[3] = (cg.time - cg.forceCrosshairStartTime) / 300.0f; } // clamp - if ( ecolor[3] < 0 ) - { + if (ecolor[3] < 0) { ecolor[3] = 0; - } - else if ( ecolor[3] > 1.0f ) - { + } else if (ecolor[3] > 1.0f) { ecolor[3] = 1.0f; } - if ( !cg.forceCrosshairEndTime ) - { + if (!cg.forceCrosshairEndTime) { // but for the other direction, we'll need to reverse it ecolor[3] = 1.0f - ecolor[3]; } } - if ( corona ) // we are pointing at a crosshair item + if (corona) // we are pointing at a crosshair item { - if ( !cg.forceCrosshairStartTime ) - { + if (!cg.forceCrosshairStartTime) { // must have just happened because we are not fading in yet...start it now cg.forceCrosshairStartTime = cg.time; cg.forceCrosshairEndTime = 0; } - if ( cg.forceCrosshairEndTime ) - { + if (cg.forceCrosshairEndTime) { // must have just gone over a force thing again...and we were in the process of fading out. Set fade in level to the level where the fade left off - cg.forceCrosshairStartTime = cg.time - ( 1.0f - ecolor[3] ) * 300.0f; + cg.forceCrosshairStartTime = cg.time - (1.0f - ecolor[3]) * 300.0f; cg.forceCrosshairEndTime = 0; } - } - else // not pointing at a crosshair item + } else // not pointing at a crosshair item { - if ( cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime ) // were currently fading in + if (cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime) // were currently fading in { // must fade back out, but we will have to set the fadeout time to be equal to the current level of faded-in-edness cg.forceCrosshairEndTime = cg.time - ecolor[3] * 500.0f; } - if ( cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f ) // not pointing at anything and fade out is totally done + if (cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f) // not pointing at anything and fade out is totally done { // reset everything cg.forceCrosshairStartTime = 0; @@ -2730,65 +2058,49 @@ static void CG_DrawCrosshair( vec3_t worldPoint ) // pulse the size of the crosshair when picking up items f = cg.time - cg.itemPickupBlendTime; - if ( f > 0 && f < ITEM_BLOB_TIME ) { + if (f > 0 && f < ITEM_BLOB_TIME) { f /= ITEM_BLOB_TIME; - w *= ( 1 + f ); - h *= ( 1 + f ); + w *= (1 + f); + h *= (1 + f); } - if ( worldPoint && VectorLength( worldPoint ) ) - { - if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) ) - {//off screen, don't draw it - cgi_R_SetColor( NULL ); + if (worldPoint && VectorLength(worldPoint)) { + if (!CG_WorldCoordToScreenCoordFloat(worldPoint, &x, &y)) { // off screen, don't draw it + cgi_R_SetColor(NULL); return; } - x -= 320;//???? - y -= 240;//???? - } - else - { + x -= 320; //???? + y -= 240; //???? + } else { x = cg_crosshairX.integer; y = cg_crosshairY.integer; } - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) - { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (!Q_stricmp("misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname)) { // draws a custom crosshair that is twice as large as normal - cgi_R_DrawStretchPic( x + cg.refdef.x + 320 - w, - y + cg.refdef.y + 240 - h, - w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader ); - + cgi_R_DrawStretchPic(x + cg.refdef.x + 320 - w, y + cg.refdef.y + 240 - h, w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader); } - } - else - { - hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ]; + } else { + hShader = cgs.media.crosshairShader[cg_drawCrosshair.integer % NUM_CROSSHAIRS]; - cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w), - y + cg.refdef.y + 0.5 * (480 - h), - w, h, 0, 0, 1, 1, hShader ); + cgi_R_DrawStretchPic(x + cg.refdef.x + 0.5 * (640 - w), y + cg.refdef.y + 0.5 * (480 - h), w, h, 0, 0, 1, 1, hShader); } - if ( cg.forceCrosshairStartTime && cg_crosshairForceHint.integer ) // drawing extra bits + if (cg.forceCrosshairStartTime && cg_crosshairForceHint.integer) // drawing extra bits { - ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color + ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * (sin(cg.time * 0.001f) * 0.08f + 0.35f); // don't draw full color ecolor[3] = 1.0f; - cgi_R_SetColor( ecolor ); + cgi_R_SetColor(ecolor); w *= 2.0f; h *= 2.0f; - cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5f * ( 640 - w ), y + cg.refdef.y + 0.5f * ( 480 - h ), - w, h, - 0, 0, 1, 1, - cgs.media.forceCoronaShader ); + cgi_R_DrawStretchPic(x + cg.refdef.x + 0.5f * (640 - w), y + cg.refdef.y + 0.5f * (480 - h), w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader); } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -2796,36 +2108,35 @@ qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) Take any world coord and convert it to a 2D virtual 640x480 screen coord */ -qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) -{ - vec3_t trans; - float xc, yc; - float px, py; - float z; +qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { + vec3_t trans; + float xc, yc; + float px, py; + float z; - px = tan(cg.refdef.fov_x * (M_PI / 360) ); - py = tan(cg.refdef.fov_y * (M_PI / 360) ); + px = tan(cg.refdef.fov_x * (M_PI / 360)); + py = tan(cg.refdef.fov_y * (M_PI / 360)); - VectorSubtract(worldCoord, cg.refdef.vieworg, trans); + VectorSubtract(worldCoord, cg.refdef.vieworg, trans); - xc = 640 / 2.0; - yc = 480 / 2.0; + xc = 640 / 2.0; + yc = 480 / 2.0; // z = how far is the object in our forward direction - z = DotProduct(trans, cg.refdef.viewaxis[0]); - if (z <= 0.001) - return qfalse; + z = DotProduct(trans, cg.refdef.viewaxis[0]); + if (z <= 0.001) + return qfalse; - *x = xc - DotProduct(trans, cg.refdef.viewaxis[1])*xc/(z*px); - *y = yc - DotProduct(trans, cg.refdef.viewaxis[2])*yc/(z*py); + *x = xc - DotProduct(trans, cg.refdef.viewaxis[1]) * xc / (z * px); + *y = yc - DotProduct(trans, cg.refdef.viewaxis[2]) * yc / (z * py); - return qtrue; + return qtrue; } -qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { +qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) { float xF, yF; - if ( CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ) ) { + if (CG_WorldCoordToScreenCoordFloat(worldCoord, &xF, &yF)) { *x = (int)xF; *y = (int)yF; return qtrue; @@ -2836,74 +2147,62 @@ qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { // I'm keeping the rocket tracking code separate for now since I may want to do different logic...but it still uses trace info from scanCrosshairEnt //----------------------------------------- -static void CG_ScanForRocketLock( void ) +static void CG_ScanForRocketLock(void) //----------------------------------------- { - gentity_t *traceEnt; + gentity_t *traceEnt; static qboolean tempLock = qfalse; // this will break if anything else uses this locking code ( other than the player ) traceEnt = &g_entities[g_crosshairEntNum]; - if ( !traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET ) || !traceEnt->health - || ( traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED] )) - { + if (!traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET) || + !traceEnt->health || (traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED])) { // see how much locking we have - int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); + int dif = (cg.time - g_rocketLockTime) / (1200.0f / 8.0f); // 8 is full locking....also if we just traced onto the world, // give them 1/2 second of slop before dropping the lock - if ( dif < 8 && g_rocketSlackTime + 500 < cg.time ) - { + if (dif < 8 && g_rocketSlackTime + 500 < cg.time) { // didn't have a full lock and not in grace period, so drop the lock g_rocketLockTime = 0; g_rocketSlackTime = 0; tempLock = qfalse; } - if ( g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD ) - { + if (g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD) { // were locked onto an ent, aren't right now.....but still within the slop grace period // keep the current lock amount g_rocketLockTime += cg.frametime; } - if ( !tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8 ) - { + if (!tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8) { tempLock = qtrue; - if ( g_rocketLockTime + 1200 < cg.time ) - { + if (g_rocketLockTime + 1200 < cg.time) { g_rocketLockTime = cg.time - 1200; // doh, hacking the time so the targetting still gets drawn full } } // keep locking to this thing for one second after it gets out of view - if ( g_rocketLockTime + 2000.0f < cg.time ) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms + if (g_rocketLockTime + 2000.0f < cg.time) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms { // too bad, you had your chance g_rocketLockEntNum = ENTITYNUM_NONE; g_rocketSlackTime = 0; g_rocketLockTime = 0; } - } - else - { + } else { tempLock = qfalse; - if ( g_rocketLockEntNum >= ENTITYNUM_WORLD ) - { - if ( g_rocketSlackTime + 500 < cg.time ) - { + if (g_rocketLockEntNum >= ENTITYNUM_WORLD) { + if (g_rocketSlackTime + 500 < cg.time) { // we just locked onto something, start the lock at the current time g_rocketLockEntNum = g_crosshairEntNum; g_rocketLockTime = cg.time; g_rocketSlackTime = cg.time; } - } - else - { - if ( g_rocketLockEntNum != g_crosshairEntNum ) - { + } else { + if (g_rocketLockEntNum != g_crosshairEntNum) { g_rocketLockTime = cg.time; } @@ -2919,110 +2218,88 @@ static void CG_ScanForRocketLock( void ) CG_ScanForCrosshairEntity ================= */ -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); extern float forcePushPullRadius[]; -static void CG_ScanForCrosshairEntity( qboolean scanAll ) -{ - trace_t trace; - gentity_t *traceEnt = NULL; - vec3_t start, end; - int content; - int ignoreEnt = cg.snap->ps.clientNum; +static void CG_ScanForCrosshairEntity(qboolean scanAll) { + trace_t trace; + gentity_t *traceEnt = NULL; + vec3_t start, end; + int content; + int ignoreEnt = cg.snap->ps.clientNum; Vehicle_t *pVeh = NULL; - //FIXME: debounce this to about 10fps? + // FIXME: debounce this to about 10fps? cg_forceCrosshair = qfalse; - if ( cg_entities[0].gent && cg_entities[0].gent->client ) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer && - {//try to check for force-affectable stuff first + if (cg_entities[0].gent && cg_entities[0].gent->client) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer && + { // try to check for force-affectable stuff first vec3_t d_f, d_rt, d_up; // If you're riding a vehicle and not being drawn. - if ( ( pVeh = G_IsRidingVehicle( cg_entities[0].gent ) ) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW ) - { - VectorCopy( cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start ); - AngleVectors( cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up ); - } - else - { - VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); + if ((pVeh = G_IsRidingVehicle(cg_entities[0].gent)) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW) { + VectorCopy(cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start); + AngleVectors(cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up); + } else { + VectorCopy(g_entities[0].client->renderInfo.eyePoint, start); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); } - VectorMA( start, 2048, d_f, end );//4028 is max for mind trick + VectorMA(start, 2048, d_f, end); // 4028 is max for mind trick - //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. - gi.trace( &trace, start, vec3_origin, vec3_origin, end, - ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_TERRAIN, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... + // YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. + gi.trace(&trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE | CONTENTS_SHOTCLIP | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_TERRAIN, + G2_NOCOLLIDE, 10); // ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys + // aren't shown, could just remove their body earlier too... - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit something + if (trace.entityNum < ENTITYNUM_WORLD) { // hit something traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt ) - { + if (traceEnt) { // Check for mind trickable-guys - if ( traceEnt->client ) - {//is a client - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK]) ) - {//I have the ability to mind-trick and he is alive and he has a mind trick script - //NOTE: no need to check range since it's always 2048 + if (traceEnt->client) { // is a client + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && + VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK])) { // I have the ability to mind-trick and he is alive and he has a mind trick script + // NOTE: no need to check range since it's always 2048 cg_forceCrosshair = qtrue; } } // No? Check for force-push/pullable doors and func_statics - else if ( traceEnt->s.eType == ET_MOVER ) - {//hit a mover - if ( !Q_stricmp( "func_door", traceEnt->classname ) ) - {//it's a func_door - if ( traceEnt->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/ ) - {//it's force-usable - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//player has push or pull + else if (traceEnt->s.eType == ET_MOVER) { // hit a mover + if (!Q_stricmp("func_door", traceEnt->classname)) { // it's a func_door + if (traceEnt->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/) { // it's force-usable + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // player has push or pull float maxRange; - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//use the better range + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; - } - else - {//use the better range + } else { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( maxRange >= trace.fraction * 2048 ) - {//actually close enough to use one of our force powers on it + if (maxRange >= trace.fraction * 2048) { // actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } } } - } - else if ( !Q_stricmp( "func_static", traceEnt->classname ) ) - {//it's a func_static - if ( (traceEnt->spawnflags & 1/*F_PUSH*/) && (traceEnt->spawnflags & 2/*F_PULL*/) ) - {//push or pullable + } else if (!Q_stricmp("func_static", traceEnt->classname)) { // it's a func_static + if ((traceEnt->spawnflags & 1 /*F_PUSH*/) && (traceEnt->spawnflags & 2 /*F_PULL*/)) { // push or pullable float maxRange; - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//use the better range + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; - } - else - {//use the better range + } else { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( maxRange >= trace.fraction * 2048 ) - {//actually close enough to use one of our force powers on it + if (maxRange >= trace.fraction * 2048) { // actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } - } - else if ( (traceEnt->spawnflags & 1/*F_PUSH*/) ) - {//pushable only - if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= trace.fraction * 2048 ) - {//actually close enough to use force push on it + } else if ((traceEnt->spawnflags & 1 /*F_PUSH*/)) { // pushable only + if (forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= + trace.fraction * 2048) { // actually close enough to use force push on it cg_forceCrosshair = qtrue; } - } - else if ( (traceEnt->spawnflags & 2/*F_PULL*/) ) - {//pullable only - if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= trace.fraction * 2048 ) - {//actually close enough to use force pull on it + } else if ((traceEnt->spawnflags & 2 /*F_PULL*/)) { // pullable only + if (forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= + trace.fraction * 2048) { // actually close enough to use force pull on it cg_forceCrosshair = qtrue; } } @@ -3031,65 +2308,50 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) } } } - if ( !cg_forceCrosshair ) - { - if ( cg_dynamicCrosshair.integer ) - {//100% accurate + if (!cg_forceCrosshair) { + if (cg_dynamicCrosshair.integer) { // 100% accurate vec3_t d_f, d_rt, d_up; // If you're riding a vehicle and not being drawn. - if ( ( pVeh = G_IsRidingVehicle( cg_entities[0].gent ) ) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW ) - { - VectorCopy( cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start ); - AngleVectors( cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up ); - } - else if ( cg.snap->ps.weapon == WP_NONE || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON ) - { - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in camera ent view + if ((pVeh = G_IsRidingVehicle(cg_entities[0].gent)) != NULL && cg_entities[0].currentState.eFlags & EF_NODRAW) { + VectorCopy(cg_entities[pVeh->m_pParentEntity->s.number].lerpOrigin, start); + AngleVectors(cg_entities[pVeh->m_pParentEntity->s.number].lerpAngles, d_f, d_rt, d_up); + } else if (cg.snap->ps.weapon == WP_NONE || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON) { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in camera ent view ignoreEnt = cg.snap->ps.viewEntity; - if ( g_entities[cg.snap->ps.viewEntity].client ) - { - VectorCopy( g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start ); + if (g_entities[cg.snap->ps.viewEntity].client) { + VectorCopy(g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start); + } else { + VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start); } - else - { - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start ); - } - AngleVectors( cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up ); - } - else - { - VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); + AngleVectors(cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up); + } else { + VectorCopy(g_entities[0].client->renderInfo.eyePoint, start); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); } + } else { + extern void CalcMuzzlePoint(gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); + CalcMuzzlePoint(&g_entities[0], d_f, d_rt, d_up, start, 0); } - else - { - extern void CalcMuzzlePoint( gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); - CalcMuzzlePoint( &g_entities[0], d_f, d_rt, d_up, start , 0 ); - } - //VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start ); - //FIXME: increase this? Increase when zoom in? - VectorMA( start, 4096, d_f, end );//was 8192 - } - else - {//old way - VectorCopy( cg.refdef.vieworg, start ); - //FIXME: increase this? Increase when zoom in? - VectorMA( start, 131072, cg.refdef.viewaxis[0], end );//was 8192 - } - //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. - gi.trace( &trace, start, vec3_origin, vec3_origin, end, - ignoreEnt, MASK_OPAQUE|CONTENTS_TERRAIN|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... + // VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start ); + // FIXME: increase this? Increase when zoom in? + VectorMA(start, 4096, d_f, end); // was 8192 + } else { // old way + VectorCopy(cg.refdef.vieworg, start); + // FIXME: increase this? Increase when zoom in? + VectorMA(start, 131072, cg.refdef.viewaxis[0], end); // was 8192 + } + // YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. + gi.trace(&trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE | CONTENTS_TERRAIN | CONTENTS_SHOTCLIP | CONTENTS_BODY | CONTENTS_ITEM, + G2_NOCOLLIDE, 10); // ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys + // aren't shown, could just remove their body earlier too... /* CG_Trace( &trace, start, vec3_origin, vec3_origin, end, cg.snap->ps.clientNum, MASK_PLAYERSOLID|CONTENTS_CORPSE|CONTENTS_ITEM ); */ - //FIXME: pick up corpses - if ( trace.startsolid || trace.allsolid ) - { + // FIXME: pick up corpses + if (trace.startsolid || trace.allsolid) { // trace should not be allowed to pick up anything if it started solid. I tried actually moving the trace start back, which also worked, // but the dynamic cursor drawing caused it to render around the clip of the gun when I pushed the blaster all the way into a wall. // It looked quite horrible...but, if this is bad for some reason that I don't know @@ -3099,68 +2361,54 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) traceEnt = &g_entities[trace.entityNum]; } - // if the object is "dead", don't show it -/* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 ) - { - cg.crosshairClientNum = 0; - return; - } -*/ - //draw crosshair at endpoint - CG_DrawCrosshair( trace.endpos ); + /* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 ) + { + cg.crosshairClientNum = 0; + return; + } + */ + // draw crosshair at endpoint + CG_DrawCrosshair(trace.endpos); g_crosshairEntNum = trace.entityNum; - g_crosshairEntDist = 4096*trace.fraction; + g_crosshairEntDist = 4096 * trace.fraction; - if ( !traceEnt ) - { - //not looking at anything + if (!traceEnt) { + // not looking at anything g_crosshairSameEntTime = 0; g_crosshairEntTime = 0; - } - else - {//looking at a valid ent - //store the distance - if ( trace.entityNum != g_crosshairEntNum ) - {//new crosshair ent + } else { // looking at a valid ent + // store the distance + if (trace.entityNum != g_crosshairEntNum) { // new crosshair ent g_crosshairSameEntTime = 0; - } - else if ( g_crosshairEntDist < 256 ) - {//close enough to start counting how long you've been looking + } else if (g_crosshairEntDist < 256) { // close enough to start counting how long you've been looking g_crosshairSameEntTime += cg.frametime; } - //remember the last time you looked at the person + // remember the last time you looked at the person g_crosshairEntTime = cg.time; } - if ( !traceEnt ) - { - if ( traceEnt && scanAll ) - { - } - else - { + if (!traceEnt) { + if (traceEnt && scanAll) { + } else { return; } } // if the player is in fog, don't show it - content = cgi_CM_PointContents( trace.endpos, 0 ); - if ( content & CONTENTS_FOG ) - { + content = cgi_CM_PointContents(trace.endpos, 0); + if (content & CONTENTS_FOG) { return; } // if the player is cloaked, don't show it - if ( cg_entities[ trace.entityNum ].currentState.powerups & ( 1 << PW_CLOAKED )) - { + if (cg_entities[trace.entityNum].currentState.powerups & (1 << PW_CLOAKED)) { return; } // update the fade timer - if ( cg.crosshairClientNum != trace.entityNum ) - { + if (cg.crosshairClientNum != trace.entityNum) { infoStringCount = 0; } @@ -3168,37 +2416,32 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) cg.crosshairClientTime = cg.time; } - /* ===================== CG_DrawCrosshairNames ===================== */ -static void CG_DrawCrosshairNames( void ) -{ - qboolean scanAll = qfalse; - centity_t *player = &cg_entities[0]; +static void CG_DrawCrosshairNames(void) { + qboolean scanAll = qfalse; + centity_t *player = &cg_entities[0]; - if ( cg_dynamicCrosshair.integer ) - { + if (cg_dynamicCrosshair.integer) { // still need to scan for dynamic crosshair - CG_ScanForCrosshairEntity( scanAll ); + CG_ScanForCrosshairEntity(scanAll); return; } - if ( !player->gent ) - { + if (!player->gent) { return; } - if ( !player->gent->client ) - { + if (!player->gent->client) { return; } // scan the known entities to see if the crosshair is sighted on one // This is currently being called by the rocket tracking code, so we don't necessarily want to do duplicate traces :) - CG_ScanForCrosshairEntity( scanAll ); + CG_ScanForCrosshairEntity(scanAll); } //-------------------------------------------------------------- @@ -3206,14 +2449,13 @@ static void CG_DrawActivePowers(void) //-------------------------------------------------------------- { int icon_size = 40; - int startx = icon_size*2+16; - int starty = SCREEN_HEIGHT - icon_size*2; + int startx = icon_size * 2 + 16; + int starty = SCREEN_HEIGHT - icon_size * 2; int endx = icon_size; int endy = icon_size; - if (cg.zoomMode) - { //don't display over zoom mask + if (cg.zoomMode) { // don't display over zoom mask return; } @@ -3238,138 +2480,113 @@ static void CG_DrawActivePowers(void) } */ - //additionally, draw an icon force force rage recovery - if (cg.snap->ps.forceRageRecoveryTime > cg.time) - { - CG_DrawPic( startx, starty, endx, endy, cgs.media.rageRecShader); + // additionally, draw an icon force force rage recovery + if (cg.snap->ps.forceRageRecoveryTime > cg.time) { + CG_DrawPic(startx, starty, endx, endy, cgs.media.rageRecShader); } } //-------------------------------------------------------------- -static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) +static void CG_DrawRocketLocking(int lockEntNum, int lockTime) //-------------------------------------------------------------- { gentity_t *gent = &g_entities[lockEntNum]; - if ( !gent ) - { + if (!gent) { return; } - int cx, cy; - vec3_t org; - static int oldDif = 0; + int cx, cy; + vec3_t org; + static int oldDif = 0; - VectorCopy( gent->currentOrigin, org ); + VectorCopy(gent->currentOrigin, org); org[2] += (gent->mins[2] + gent->maxs[2]) * 0.5f; - if ( CG_WorldCoordToScreenCoord( org, &cx, &cy )) - { + if (CG_WorldCoordToScreenCoord(org, &cx, &cy)) { // we care about distance from enemy to eye, so this is good enough - float sz = Distance( gent->currentOrigin, cg.refdef.vieworg ) / 1024.0f; + float sz = Distance(gent->currentOrigin, cg.refdef.vieworg) / 1024.0f; - if ( cg.zoomMode > 0 ) - { - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { - sz -= ( cg.overrides.fov - cg_zoomFov ) / 80.0f; - } - else - { - sz -= ( cg_fov.value - cg_zoomFov ) / 80.0f; + if (cg.zoomMode > 0) { + if (cg.overrides.active & CG_OVERRIDE_FOV) { + sz -= (cg.overrides.fov - cg_zoomFov) / 80.0f; + } else { + sz -= (cg_fov.value - cg_zoomFov) / 80.0f; } } - if ( sz > 1.0f ) - { + if (sz > 1.0f) { sz = 1.0f; - } - else if ( sz < 0.0f ) - { + } else if (sz < 0.0f) { sz = 0.0f; } sz = (1.0f - sz) * (1.0f - sz) * 32 + 6; - vec4_t color={0.0f,0.0f,0.0f,0.0f}; + vec4_t color = {0.0f, 0.0f, 0.0f, 0.0f}; cy += sz * 0.5f; // well now, take our current lock time and divide that by 8 wedge slices to get the current lock amount - int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); + int dif = (cg.time - g_rocketLockTime) / (1200.0f / 8.0f); - if ( dif < 0 ) - { + if (dif < 0) { oldDif = 0; return; - } - else if ( dif > 8 ) - { + } else if (dif > 8) { dif = 8; } // do sounds - if ( oldDif != dif ) - { - if ( dif == 8 ) - { - cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" )); - } - else - { - cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" )); + if (oldDif != dif) { + if (dif == 8) { + cgi_S_StartSound(org, 0, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/rocket/lock.wav")); + } else { + cgi_S_StartSound(org, 0, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/rocket/tick.wav")); } } oldDif = dif; - for ( int i = 0; i < dif; i++ ) - { + for (int i = 0; i < dif; i++) { color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; color[3] = 0.1f * i + 0.2f; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); // our slices are offset by about 45 degrees. - CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" )); + CG_DrawRotatePic(cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip("gfx/2d/wedge")); } // we are locked and loaded baby - if ( dif == 8 ) - { - color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f; + if (dif == 8) { + color[0] = color[1] = color[2] = sin(cg.time * 0.05f) * 0.5f + 0.5f; color[3] = 1.0f; // this art is additive, so the alpha value does nothing - cgi_R_SetColor( color ); + cgi_R_SetColor(color); - CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip( "gfx/2d/lock" )); + CG_DrawPic(cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip("gfx/2d/lock")); } } } - //------------------------------------ -static void CG_RunRocketLocking( void ) +static void CG_RunRocketLocking(void) //------------------------------------ { - centity_t *player = &cg_entities[0]; + centity_t *player = &cg_entities[0]; // Only bother with this when the player is holding down the alt-fire button of the rocket launcher - if ( player->currentState.weapon == WP_ROCKET_LAUNCHER ) - { - if ( player->currentState.eFlags & EF_ALT_FIRING ) - { + if (player->currentState.weapon == WP_ROCKET_LAUNCHER) { + if (player->currentState.eFlags & EF_ALT_FIRING) { CG_ScanForRocketLock(); - if ( g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0 ) - { - CG_DrawRocketLocking( g_rocketLockEntNum, g_rocketLockTime ); + if (g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0) { + CG_DrawRocketLocking(g_rocketLockEntNum, g_rocketLockTime); } - } - else - { + } else { // disengage any residual locking g_rocketLockEntNum = ENTITYNUM_WORLD; g_rocketLockTime = 0; @@ -3382,51 +2599,46 @@ static void CG_RunRocketLocking( void ) CG_DrawIntermission ================= */ -static void CG_DrawIntermission( void ) { - CG_DrawScoreboard(); -} - +static void CG_DrawIntermission(void) { CG_DrawScoreboard(); } /* ================== CG_DrawSnapshot ================== */ -static float CG_DrawSnapshot( float y ) { - char *s; - int w; +static float CG_DrawSnapshot(float y) { + char *s; + int w; - s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime, - cg.latestSnapshotNum, cgs.serverCommandSequence ); + s = va("time:%i snap:%i cmd:%i", cg.snap->serverTime, cg.latestSnapshotNum, cgs.serverCommandSequence); w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(635 - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } - /* ================== CG_DrawFPS ================== */ -#define FPS_FRAMES 16 -static float CG_DrawFPS( float y ) { - char *s; +#define FPS_FRAMES 16 +static float CG_DrawFPS(float y) { + char *s; static unsigned short previousTimes[FPS_FRAMES]; static unsigned short index; - static int previous, lastupdate; - int t, i, fps, total; + static int previous, lastupdate; + int t, i, fps, total; unsigned short frameTime; - const int xOffset = 0; + const int xOffset = 0; // don't use serverTime, because that will be drifting to // correct for internet lag changes, timescales, timedemos, etc t = cgi_Milliseconds(); frameTime = t - previous; previous = t; - if (t - lastupdate > 50) //don't sample faster than this + if (t - lastupdate > 50) // don't sample faster than this { lastupdate = t; previousTimes[index % FPS_FRAMES] = frameTime; @@ -3434,17 +2646,17 @@ static float CG_DrawFPS( float y ) { } // average multiple frames together to smooth changes out a bit total = 0; - for ( i = 0 ; i < FPS_FRAMES ; i++ ) { + for (i = 0; i < FPS_FRAMES; i++) { total += previousTimes[i]; } - if ( !total ) { + if (!total) { total = 1; } fps = 1000 * FPS_FRAMES / total; - s = va( "%ifps", fps ); + s = va("%ifps", fps); const int w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635-xOffset - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(635 - xOffset - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } @@ -3454,10 +2666,10 @@ static float CG_DrawFPS( float y ) { CG_DrawTimer ================= */ -static float CG_DrawTimer( float y ) { - char *s; - int w; - int mins, seconds, tens; +static float CG_DrawTimer(float y) { + char *s; + int w; + int mins, seconds, tens; seconds = cg.time / 1000; mins = seconds / 60; @@ -3465,83 +2677,72 @@ static float CG_DrawTimer( float y ) { tens = seconds / 10; seconds -= tens * 10; - s = va( "%i:%i%i", mins, tens, seconds ); + s = va("%i:%i%i", mins, tens, seconds); w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(635 - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } - /* ================= CG_DrawAmmoWarning ================= */ -static void CG_DrawAmmoWarning( void ) { - char text[1024]={0}; - int w; +static void CG_DrawAmmoWarning(void) { + char text[1024] = {0}; + int w; - if ( cg_drawAmmoWarning.integer == 0 ) { + if (cg_drawAmmoWarning.integer == 0) { return; } - if ( !cg.lowAmmoWarning ) { + if (!cg.lowAmmoWarning) { return; } - if ( weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE ) - {//doesn't use ammo, so no warning + if (weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE) { // doesn't use ammo, so no warning return; } - if ( cg.lowAmmoWarning == 2 ) { - cgi_SP_GetStringTextString( "SP_INGAME_INSUFFICIENTENERGY", text, sizeof(text) ); + if (cg.lowAmmoWarning == 2) { + cgi_SP_GetStringTextString("SP_INGAME_INSUFFICIENTENERGY", text, sizeof(text)); } else { return; - //s = "LOW AMMO WARNING"; + // s = "LOW AMMO WARNING"; } w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - cgi_R_Font_DrawString(320 - w/2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); + cgi_R_Font_DrawString(320 - w / 2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); } //--------------------------------------- -static qboolean CG_RenderingFromMiscCamera() -{ - //centity_t *cent; +static qboolean CG_RenderingFromMiscCamera() { + // centity_t *cent; - //cent = &cg_entities[cg.snap->ps.clientNum]; + // cent = &cg_entities[cg.snap->ps.clientNum]; - if ( cg.snap->ps.viewEntity > 0 && - cg.snap->ps.viewEntity < ENTITYNUM_WORLD )// cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity) + if (cg.snap->ps.viewEntity > 0 && + cg.snap->ps.viewEntity < ENTITYNUM_WORLD) // cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity) { // Only check viewEntities - if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname )) - { + if (!Q_stricmp("misc_camera", g_entities[cg.snap->ps.viewEntity].classname)) { // Only doing a misc_camera, so check health. - if ( g_entities[cg.snap->ps.viewEntity].health > 0 ) - { - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/workingCamera" )); - } - else - { - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/brokenCamera" )); + if (g_entities[cg.snap->ps.viewEntity].health > 0) { + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/workingCamera")); + } else { + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/brokenCamera")); } // don't render other 2d stuff return qtrue; - } - else if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) - { + } else if (!Q_stricmp("misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname)) { // could do a panel turret screen overlay...this is a cheesy placeholder - CG_DrawPic( 30, 90, 128, 300, cgs.media.turretComputerOverlayShader ); - CG_DrawPic( 610, 90, -128, 300, cgs.media.turretComputerOverlayShader ); - } - else - { + CG_DrawPic(30, 90, 128, 300, cgs.media.turretComputerOverlayShader); + CG_DrawPic(610, 90, -128, 300, cgs.media.turretComputerOverlayShader); + } else { // FIXME: make sure that this assumption is correct...because I'm assuming that I must be a droid. - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/droid_view" )); + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/droid_view")); } } @@ -3550,26 +2751,21 @@ static qboolean CG_RenderingFromMiscCamera() } qboolean cg_usingInFrontOf = qfalse; -qboolean CanUseInfrontOf(gentity_t*); -static void CG_UseIcon() -{ +qboolean CanUseInfrontOf(gentity_t *); +static void CG_UseIcon() { cg_usingInFrontOf = CanUseInfrontOf(cg_entities[cg.snap->ps.clientNum].gent); - if (cg_usingInFrontOf) - { - cgi_R_SetColor( NULL ); - CG_DrawPic( 50, 285, 64, 64, cgs.media.useableHint ); + if (cg_usingInFrontOf) { + cgi_R_SetColor(NULL); + CG_DrawPic(50, 285, 64, 64, cgs.media.useableHint); } } -static void CG_Draw2DScreenTints( void ) -{ - float rageTime, rageRecTime, absorbTime, protectTime; - vec4_t hcolor; - //force effects - if (cg.snap->ps.forcePowersActive & (1 << FP_RAGE)) - { - if (!cgRageTime) - { +static void CG_Draw2DScreenTints(void) { + float rageTime, rageRecTime, absorbTime, protectTime; + vec4_t hcolor; + // force effects + if (cg.snap->ps.forcePowersActive & (1 << FP_RAGE)) { + if (!cgRageTime) { cgRageTime = cg.time; } @@ -3577,12 +2773,10 @@ static void CG_Draw2DScreenTints( void ) rageTime /= 9000; - if ( rageTime < 0 ) - { + if (rageTime < 0) { rageTime = 0; } - if ( rageTime > 0.15f ) - { + if (rageTime > 0.15f) { rageTime = 0.15f; } @@ -3591,82 +2785,64 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0; hcolor[2] = 0; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageFadeTime = 0; cgRageFadeVal = 0; - } - else if (cgRageTime) - { - if (!cgRageFadeTime) - { + } else if (cgRageTime) { + if (!cgRageFadeTime) { cgRageFadeTime = cg.time; cgRageFadeVal = 0.15f; } rageTime = cgRageFadeVal; - cgRageFadeVal -= (cg.time - cgRageFadeTime)*0.000005; + cgRageFadeVal -= (cg.time - cgRageFadeTime) * 0.000005; - if (rageTime < 0) - { + if (rageTime < 0) { rageTime = 0; } - if ( rageTime > 0.15f ) - { + if (rageTime > 0.15f) { rageTime = 0.15f; } - if ( cg.snap->ps.forceRageRecoveryTime > cg.time ) - { + if (cg.snap->ps.forceRageRecoveryTime > cg.time) { float checkRageRecTime = rageTime; - if ( checkRageRecTime < 0.15f ) - { + if (checkRageRecTime < 0.15f) { checkRageRecTime = 0.15f; } hcolor[3] = checkRageRecTime; - hcolor[0] = rageTime*4; - if ( hcolor[0] < 0.2f ) - { + hcolor[0] = rageTime * 4; + if (hcolor[0] < 0.2f) { hcolor[0] = 0.2f; } hcolor[1] = 0.2f; hcolor[2] = 0.2f; - } - else - { + } else { hcolor[3] = rageTime; hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; } - if (!cg.renderingThirdPerson && rageTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { - if (cg.snap->ps.forceRageRecoveryTime > cg.time) - { + if (!cg.renderingThirdPerson && rageTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { + if (cg.snap->ps.forceRageRecoveryTime > cg.time) { hcolor[3] = 0.15f; hcolor[0] = 0.2f; hcolor[1] = 0.2f; hcolor[2] = 0.2f; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageTime = 0; } - } - else if (cg.snap->ps.forceRageRecoveryTime > cg.time) - { - if (!cgRageRecTime) - { + } else if (cg.snap->ps.forceRageRecoveryTime > cg.time) { + if (!cgRageRecTime) { cgRageRecTime = cg.time; } @@ -3674,12 +2850,11 @@ static void CG_Draw2DScreenTints( void ) rageRecTime /= 9000; - if ( rageRecTime < 0.15f )//0) + if (rageRecTime < 0.15f) // 0) { - rageRecTime = 0.15f;//0; + rageRecTime = 0.15f; // 0; } - if ( rageRecTime > 0.15f ) - { + if (rageRecTime > 0.15f) { rageRecTime = 0.15f; } @@ -3688,32 +2863,26 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0.2f; hcolor[2] = 0.2f; - if ( !cg.renderingThirdPerson ) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageRecFadeTime = 0; cgRageRecFadeVal = 0; - } - else if (cgRageRecTime) - { - if (!cgRageRecFadeTime) - { + } else if (cgRageRecTime) { + if (!cgRageRecFadeTime) { cgRageRecFadeTime = cg.time; cgRageRecFadeVal = 0.15f; } rageRecTime = cgRageRecFadeVal; - cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime)*0.000005; + cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime) * 0.000005; - if (rageRecTime < 0) - { + if (rageRecTime < 0) { rageRecTime = 0; } - if ( rageRecTime > 0.15f ) - { + if (rageRecTime > 0.15f) { rageRecTime = 0.15f; } @@ -3722,20 +2891,15 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0.2f; hcolor[2] = 0.2f; - if (!cg.renderingThirdPerson && rageRecTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && rageRecTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgRageRecTime = 0; } } - if (cg.snap->ps.forcePowersActive & (1 << FP_ABSORB)) - { - if (!cgAbsorbTime) - { + if (cg.snap->ps.forcePowersActive & (1 << FP_ABSORB)) { + if (!cgAbsorbTime) { cgAbsorbTime = cg.time; } @@ -3743,68 +2907,55 @@ static void CG_Draw2DScreenTints( void ) absorbTime /= 9000; - if ( absorbTime < 0 ) - { + if (absorbTime < 0) { absorbTime = 0; } - if ( absorbTime > 0.15f ) - { + if (absorbTime > 0.15f) { absorbTime = 0.15f; } - hcolor[3] = absorbTime/2; + hcolor[3] = absorbTime / 2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; - if ( !cg.renderingThirdPerson ) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgAbsorbFadeTime = 0; cgAbsorbFadeVal = 0; - } - else if (cgAbsorbTime) - { - if (!cgAbsorbFadeTime) - { + } else if (cgAbsorbTime) { + if (!cgAbsorbFadeTime) { cgAbsorbFadeTime = cg.time; cgAbsorbFadeVal = 0.15f; } absorbTime = cgAbsorbFadeVal; - cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime)*0.000005; + cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime) * 0.000005; - if ( absorbTime < 0 ) - { + if (absorbTime < 0) { absorbTime = 0; } - if ( absorbTime > 0.15f ) - { + if (absorbTime > 0.15f) { absorbTime = 0.15f; } - hcolor[3] = absorbTime/2; + hcolor[3] = absorbTime / 2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; - if ( !cg.renderingThirdPerson && absorbTime ) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && absorbTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgAbsorbTime = 0; } } - if (cg.snap->ps.forcePowersActive & (1 << FP_PROTECT)) - { - if (!cgProtectTime) - { + if (cg.snap->ps.forcePowersActive & (1 << FP_PROTECT)) { + if (!cgProtectTime) { cgProtectTime = cg.time; } @@ -3812,93 +2963,77 @@ static void CG_Draw2DScreenTints( void ) protectTime /= 9000; - if (protectTime < 0) - { + if (protectTime < 0) { protectTime = 0; } - if ( protectTime > 0.15f ) - { + if (protectTime > 0.15f) { protectTime = 0.15f; } - hcolor[3] = protectTime/2; + hcolor[3] = protectTime / 2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - if ( !cg.renderingThirdPerson ) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgProtectFadeTime = 0; cgProtectFadeVal = 0; - } - else if ( cgProtectTime ) - { - if ( !cgProtectFadeTime ) - { + } else if (cgProtectTime) { + if (!cgProtectFadeTime) { cgProtectFadeTime = cg.time; cgProtectFadeVal = 0.15f; } protectTime = cgProtectFadeVal; - cgProtectFadeVal -= (cg.time - cgProtectFadeTime)*0.000005; + cgProtectFadeVal -= (cg.time - cgProtectFadeTime) * 0.000005; - if (protectTime < 0) - { + if (protectTime < 0) { protectTime = 0; } - if (protectTime > 0.15f) - { + if (protectTime > 0.15f) { protectTime = 0.15f; } - hcolor[3] = protectTime/2; + hcolor[3] = protectTime / 2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - if ( !cg.renderingThirdPerson && protectTime ) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && protectTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgProtectTime = 0; } } - if ( (cg.refdef.viewContents&CONTENTS_LAVA) ) - {//tint screen red + if ((cg.refdef.viewContents & CONTENTS_LAVA)) { // tint screen red float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.5 + (0.15f*sin( phase )); + hcolor[3] = 0.5 + (0.15f * sin(phase)); hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else if ( (cg.refdef.viewContents&CONTENTS_SLIME) ) - {//tint screen green + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else if ((cg.refdef.viewContents & CONTENTS_SLIME)) { // tint screen green float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.4 + (0.1f*sin( phase )); + hcolor[3] = 0.4 + (0.1f * sin(phase)); hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else if ( (cg.refdef.viewContents&CONTENTS_WATER) ) - {//tint screen light blue -- FIXME: check to see if in fog? + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else if ((cg.refdef.viewContents & CONTENTS_WATER)) { // tint screen light blue -- FIXME: check to see if in fog? float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.3 + (0.05f*sin( phase )); + hcolor[3] = 0.3 + (0.05f * sin(phase)); hcolor[0] = 0; hcolor[1] = 0.2f; hcolor[2] = 0.8f; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } } /* @@ -3906,38 +3041,32 @@ static void CG_Draw2DScreenTints( void ) CG_Draw2D ================= */ -extern void CG_SaberClashFlare( void ); -static void CG_Draw2D( void ) -{ - char text[1024]={0}; - int w,y_pos; +extern void CG_SaberClashFlare(void); +static void CG_Draw2D(void) { + char text[1024] = {0}; + int w, y_pos; centity_t *cent = &cg_entities[cg.snap->ps.clientNum]; // if we are taking a levelshot for the menu, don't draw anything - if ( cg.levelShot ) - { + if (cg.levelShot) { return; } - if ( cg_draw2D.integer == 0 ) - { + if (cg_draw2D.integer == 0) { return; } - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) - { + if (cg.snap->ps.pm_type == PM_INTERMISSION) { CG_DrawIntermission(); return; } CG_Draw2DScreenTints(); - //end credits - if (cg_endcredits.integer) - { - if (!CG_Credits_Draw()) - { - CG_DrawCredits(); // will probably get rid of this soon + // end credits + if (cg_endcredits.integer) { + if (!CG_Credits_Draw()) { + CG_DrawCredits(); // will probably get rid of this soon } } @@ -3945,28 +3074,24 @@ static void CG_Draw2D( void ) CG_DrawBatteryCharge(); - if (cg.snap->ps.forcePowersActive || cg.snap->ps.forceRageRecoveryTime > cg.time) - { + if (cg.snap->ps.forcePowersActive || cg.snap->ps.forceRageRecoveryTime > cg.time) { CG_DrawActivePowers(); } // Draw this before the text so that any text won't get clipped off - if ( !in_camera ) - { + if (!in_camera) { CG_DrawZoomMask(); } CG_DrawScrollText(); CG_DrawCaptionText(); - if ( in_camera ) - {//still draw the saber clash flare, but nothing else + if (in_camera) { // still draw the saber clash flare, but nothing else CG_SaberClashFlare(); return; } - if ( CG_RenderingFromMiscCamera()) - { + if (CG_RenderingFromMiscCamera()) { // purposely doing an early out when in a misc_camera, change it if needed. // allowing center print when in camera mode, probably just an alpha thing - dmv @@ -3974,40 +3099,34 @@ static void CG_Draw2D( void ) return; } - if ( (cg.snap->ps.forcePowersActive&(1<ps.forcePowersActive & (1 << FP_SEE))) { // force sight is on + // indicate this with sight cone thingy + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/jsense")); CG_DrawHealthBars(); - } - else if ( cg_debugHealthBars.integer ) - { + } else if (cg_debugHealthBars.integer) { CG_DrawHealthBars(); } - // don't draw any status if dead - if ( cg.snap->ps.stats[STAT_HEALTH] > 0 ) - { - if ( !(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON )))//|EF_IN_ATST + if (cg.snap->ps.stats[STAT_HEALTH] > 0) { + if (!(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON))) //|EF_IN_ATST { - //CG_DrawIconBackground(); + // CG_DrawIconBackground(); } CG_DrawWeaponSelect(); - if ( cg.zoomMode == 0 ) - { + if (cg.zoomMode == 0) { CG_DrawStats(); } CG_DrawAmmoWarning(); - //CROSSHAIR is now done from the crosshair ent trace - //if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person draws its own crosshair + // CROSSHAIR is now done from the crosshair ent trace + // if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person + // draws its own crosshair //{ // CG_DrawCrosshair( NULL ); - //} - + // } CG_DrawCrosshairNames(); @@ -4025,51 +3144,48 @@ static void CG_Draw2D( void ) float y = 0; if (cg_drawSnapshot.integer) { - y=CG_DrawSnapshot(y); + y = CG_DrawSnapshot(y); } if (cg_drawFPS.integer) { - y=CG_DrawFPS(y); + y = CG_DrawFPS(y); } if (cg_drawTimer.integer) { - y=CG_DrawTimer(y); + y = CG_DrawTimer(y); } // don't draw center string if scoreboard is up - if ( !CG_DrawScoreboard() ) { + if (!CG_DrawScoreboard()) { CG_DrawCenterString(); } -/* if (cg.showInformation) - { -// CG_DrawMissionInformation(); - } - else -*/ - if (missionInfo_Updated) - { - if (cg.predicted_player_state.pm_type != PM_DEAD) + /* if (cg.showInformation) { + // CG_DrawMissionInformation(); + } + else + */ + if (missionInfo_Updated) { + if (cg.predicted_player_state.pm_type != PM_DEAD) { // Was a objective given? -/* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer)) - { - // How long has the game been running? If within 15 seconds of starting, throw up the datapad. - if (cg.dataPadLevelStartTime>cg.time) - { - // Make it pop up - if (!in_camera) - { - cgi_SendConsoleCommand( "datapad" ); - cg.dataPadLevelStartTime=cg.time; //and don't do it again this level! - } - } - } -*/ - if (!cg.missionInfoFlashTime) - { - cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer; + /* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer)) + { + // How long has the game been running? If within 15 seconds of starting, throw up the datapad. + if (cg.dataPadLevelStartTime>cg.time) + { + // Make it pop up + if (!in_camera) + { + cgi_SendConsoleCommand( "datapad" ); + cg.dataPadLevelStartTime=cg.time; //and don't do it again this level! + } + } + } + */ + if (!cg.missionInfoFlashTime) { + cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer; } - if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it. + if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it. { cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; @@ -4077,26 +3193,25 @@ static void CG_Draw2D( void ) CG_ClearDataPadCvars(); } - cgi_SP_GetStringTextString( "SP_INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text) ); + cgi_SP_GetStringTextString("SP_INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text)); int x_pos = 0; y_pos = 20; - w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontMedium, 1.0f); - x_pos = (SCREEN_WIDTH/2)-(w/2); - cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.0f); + x_pos = (SCREEN_WIDTH / 2) - (w / 2); + cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); } } - if (cg.weaponPickupTextTime > cg.time ) - { + if (cg.weaponPickupTextTime > cg.time) { int x_pos = 0; y_pos = 5; - gi.Cvar_VariableStringBuffer( "cg_WeaponPickupText", text, sizeof(text) ); + gi.Cvar_VariableStringBuffer("cg_WeaponPickupText", text, sizeof(text)); - w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontMedium, 0.8f); - x_pos = (SCREEN_WIDTH/2)-(w/2); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 0.8f); + x_pos = (SCREEN_WIDTH / 2) - (w / 2); - cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 0.8f); + cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 0.8f); } } @@ -4108,115 +3223,92 @@ Choose the proper background for the icons, scale it depending on if your openin closing the icon section of the HU =================== */ -void CG_DrawIconBackground(void) -{ - int backgroundXPos,backgroundYPos; - int backgroundWidth,backgroundHeight; - qhandle_t background; - const float shutdownTime = 130.0f; +void CG_DrawIconBackground(void) { + int backgroundXPos, backgroundYPos; + int backgroundWidth, backgroundHeight; + qhandle_t background; + const float shutdownTime = 130.0f; - if ( cg_hudFiles.integer ) - { //simple hud + if (cg_hudFiles.integer) { // simple hud return; } // Are we in zoom mode or the HUD is turned off? - if (( cg.zoomMode != 0 ) || !( cg_drawHUD.integer )) - { + if ((cg.zoomMode != 0) || !(cg_drawHUD.integer)) { return; } - if ((cg.snap->ps.viewEntity>0 && cg.snap->ps.viewEntityps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } // Get size and location of bakcround specified in the HUD.MENU file - if (!cgi_UI_GetMenuInfo("iconbackground",&backgroundXPos,&backgroundYPos,&backgroundWidth,&backgroundHeight)) - { + if (!cgi_UI_GetMenuInfo("iconbackground", &backgroundXPos, &backgroundYPos, &backgroundWidth, &backgroundHeight)) { return; } // Use inventory background? - if (((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_INVENTORY)) - { + if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || (cgs.media.currentBackground == ICON_INVENTORY)) { background = cgs.media.inventoryIconBackground; } // Use weapon background? - else if (((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_WEAPONS)) - { + else if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || (cgs.media.currentBackground == ICON_WEAPONS)) { background = 0; - //background = cgs.media.weaponIconBackground; + // background = cgs.media.weaponIconBackground; } // Use force background? - else - { + else { background = cgs.media.forceIconBackground; } // Time is up, shutdown the icon section of the HUD - if ((cg.iconSelectTime+WEAPON_SELECT_TIME)1.0f) - { + if (cg.iconHUDPercent > 1.0f) { cg.iconHUDActive = qtrue; - cg.iconHUDPercent=1.0f; - } - else if (cg.iconHUDPercent<0.0f) - { - cg.iconHUDPercent=0.0f; + cg.iconHUDPercent = 1.0f; + } else if (cg.iconHUDPercent < 0.0f) { + cg.iconHUDPercent = 0.0f; } - } - else - { - cg.iconHUDPercent=1.0f; + } else { + cg.iconHUDPercent = 1.0f; } // Print the background - if (background) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); - float holdFloat = (float) backgroundHeight; - backgroundHeight = (int) (holdFloat*cg.iconHUDPercent); - CG_DrawPic( backgroundXPos, backgroundYPos, backgroundWidth, -backgroundHeight, background); // Top half - CG_DrawPic( backgroundXPos, backgroundYPos,backgroundWidth, backgroundHeight, background); // Bottom half - } - if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) - { + if (background) { + cgi_R_SetColor(colorTable[CT_WHITE]); + float holdFloat = (float)backgroundHeight; + backgroundHeight = (int)(holdFloat * cg.iconHUDPercent); + CG_DrawPic(backgroundXPos, backgroundYPos, backgroundWidth, -backgroundHeight, background); // Top half + CG_DrawPic(backgroundXPos, backgroundYPos, backgroundWidth, backgroundHeight, background); // Bottom half + } + if ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) { cgs.media.currentBackground = ICON_INVENTORY; - } - else if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) - { + } else if ((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) { cgs.media.currentBackground = ICON_WEAPONS; - } - else - { + } else { cgs.media.currentBackground = ICON_FORCE; } } @@ -4228,26 +3320,26 @@ CG_DrawActive Perform all drawing needed to completely fill the screen ===================== */ -void CG_DrawActive( stereoFrame_t stereoView ) { - float separation; - vec3_t baseOrg; +void CG_DrawActive(stereoFrame_t stereoView) { + float separation; + vec3_t baseOrg; // optionally draw the info screen instead - if ( !cg.snap ) { + if (!cg.snap) { CG_DrawInformation(); return; } - //FIXME: these globals done once at start of frame for various funcs - AngleVectors (cg.refdefViewAngles, vfwd, vright, vup); - VectorCopy( vfwd, vfwd_n ); - VectorCopy( vright, vright_n ); - VectorCopy( vup, vup_n ); - VectorNormalize( vfwd_n ); - VectorNormalize( vright_n ); - VectorNormalize( vup_n ); + // FIXME: these globals done once at start of frame for various funcs + AngleVectors(cg.refdefViewAngles, vfwd, vright, vup); + VectorCopy(vfwd, vfwd_n); + VectorCopy(vright, vright_n); + VectorCopy(vup, vup_n); + VectorNormalize(vfwd_n); + VectorNormalize(vright_n); + VectorNormalize(vup_n); - switch ( stereoView ) { + switch (stereoView) { case STEREO_CENTER: separation = 0; break; @@ -4259,41 +3351,37 @@ void CG_DrawActive( stereoFrame_t stereoView ) { break; default: separation = 0; - CG_Error( "CG_DrawActive: Undefined stereoView" ); + CG_Error("CG_DrawActive: Undefined stereoView"); } - // clear around the rendered view if sized down CG_TileClear(); // offset vieworg appropriately if we're doing stereo separation - VectorCopy( cg.refdef.vieworg, baseOrg ); - if ( separation != 0 ) { - VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg ); + VectorCopy(cg.refdef.vieworg, baseOrg); + if (separation != 0) { + VectorMA(cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg); } - if ( cg.zoomMode == 3 && cg.snap->ps.batteryCharge ) // doing the Light amp goggles thing + if (cg.zoomMode == 3 && cg.snap->ps.batteryCharge) // doing the Light amp goggles thing { cgi_R_LAGoggles(); } - if ( (cg.snap->ps.forcePowersActive&(1<ps.forcePowersActive & (1 << FP_SEE))) { cg.refdef.rdflags |= RDF_ForceSightOn; } cg.refdef.rdflags |= RDF_DRAWSKYBOX; // draw 3D view - cgi_R_RenderScene( &cg.refdef ); + cgi_R_RenderScene(&cg.refdef); // restore original viewpoint if running stereo - if ( separation != 0 ) { - VectorCopy( baseOrg, cg.refdef.vieworg ); + if (separation != 0) { + VectorCopy(baseOrg, cg.refdef.vieworg); } // draw status bar and other floating elements CG_Draw2D(); - } - diff --git a/code/cgame/cg_drawtools.cpp b/code/cgame/cg_drawtools.cpp index a49607c12f..f17d1bb3c3 100644 --- a/code/cgame/cg_drawtools.cpp +++ b/code/cgame/cg_drawtools.cpp @@ -33,15 +33,15 @@ Coords are virtual 640x480 ================ */ void CG_DrawSides(float x, float y, float w, float h, float size) { - //size *= cgs.screenXScale; - cgi_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); - cgi_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); + // size *= cgs.screenXScale; + cgi_R_DrawStretchPic(x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader); + cgi_R_DrawStretchPic(x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader); } void CG_DrawTopBottom(float x, float y, float w, float h, float size) { - //size *= cgs.screenYScale; - cgi_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); - cgi_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); + // size *= cgs.screenYScale; + cgi_R_DrawStretchPic(x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader); + cgi_R_DrawStretchPic(x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader); } /* @@ -51,13 +51,13 @@ CG_DrawRect Coordinates are 640*480 virtual values ================= */ -void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) { - cgi_R_SetColor( color ); +void CG_DrawRect(float x, float y, float width, float height, float size, const float *color) { + cgi_R_SetColor(color); CG_DrawTopBottom(x, y, width, height, size); CG_DrawSides(x, y, width, height, size); - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -67,13 +67,12 @@ CG_FillRect Coordinates are 640*480 virtual values ================= */ -void CG_FillRect( float x, float y, float width, float height, const float *color ) { - cgi_R_SetColor( color ); - cgi_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); - cgi_R_SetColor( NULL ); +void CG_FillRect(float x, float y, float width, float height, const float *color) { + cgi_R_SetColor(color); + cgi_R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); + cgi_R_SetColor(NULL); } - /* ================ CG_Scissor @@ -81,13 +80,7 @@ CG_Scissor Coordinates are 640*480 virtual values ================= */ -void CG_Scissor( float x, float y, float width, float height) -{ - - cgi_R_Scissor( x, y, width, height); - -} - +void CG_Scissor(float x, float y, float width, float height) { cgi_R_Scissor(x, y, width, height); } /* ================ @@ -97,9 +90,7 @@ Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ -void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { - cgi_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); -} +void CG_DrawPic(float x, float y, float width, float height, qhandle_t hShader) { cgi_R_DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } /* ================ @@ -110,9 +101,8 @@ A width of 0 will draw with the original image width Can also specify the exact texture coordinates ================= */ -void CG_DrawPic2( float x, float y, float width, float height, float s1, float t1, float s2, float t2, qhandle_t hShader ) -{ - cgi_R_DrawStretchPic( x, y, width, height, s1, t1, s2, t2, hShader ); +void CG_DrawPic2(float x, float y, float width, float height, float s1, float t1, float s2, float t2, qhandle_t hShader) { + cgi_R_DrawStretchPic(x, y, width, height, s1, t1, s2, t2, hShader); } /* @@ -124,8 +114,8 @@ A width of 0 will draw with the original image width rotates around the upper right corner of the passed in point ================= */ -void CG_DrawRotatePic( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - cgi_R_DrawRotatePic( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic(float x, float y, float width, float height, float angle, qhandle_t hShader) { + cgi_R_DrawRotatePic(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -137,8 +127,8 @@ A width of 0 will draw with the original image width Actually rotates around the center point of the passed in coordinates ================= */ -void CG_DrawRotatePic2( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - cgi_R_DrawRotatePic2( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic2(float x, float y, float width, float height, float angle, qhandle_t hShader) { + cgi_R_DrawRotatePic2(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -148,15 +138,15 @@ CG_DrawChar Coordinates and size in 640*480 virtual screen size =============== */ -void CG_DrawChar( int x, int y, int width, int height, int ch ) { +void CG_DrawChar(int x, int y, int width, int height, int ch) { int row, col; float frow, fcol; float size; - float ax, ay, aw, ah; + float ax, ay, aw, ah; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } @@ -165,32 +155,29 @@ void CG_DrawChar( int x, int y, int width, int height, int ch ) { aw = width; ah = height; - row = ch>>4; - col = ch&15; -/* - frow = row*0.0625; - fcol = col*0.0625; - size = 0.0625; - - cgi_R_DrawStretchPic( ax, ay, aw, ah, - fcol, frow, - fcol + size, frow + size, - cgs.media.charsetShader ); -*/ + row = ch >> 4; + col = ch & 15; + /* + frow = row*0.0625; + fcol = col*0.0625; + size = 0.0625; + + cgi_R_DrawStretchPic( ax, ay, aw, ah, + fcol, frow, + fcol + size, frow + size, + cgs.media.charsetShader ); + */ float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - cgi_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, - cgs.media.charsetShader ); - + cgi_R_DrawStretchPic(ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader); } - /* ================== CG_DrawStringExt @@ -201,25 +188,24 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, - qboolean forceColor, qboolean shadow, int charWidth, int charHeight ) { - vec4_t color; - const char *s; - int xx; +void CG_DrawStringExt(int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight) { + vec4_t color; + const char *s; + int xx; // draw the drop shadow if (shadow) { color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); s = string; xx = x; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; continue; } - CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s ); + CG_DrawChar(xx + 2, y + 2, charWidth, charHeight, *s); xx += charWidth; s++; } @@ -228,28 +214,25 @@ void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, // draw the colored text s = string; xx = x; - cgi_R_SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + cgi_R_SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); } s += 2; continue; } - CG_DrawChar( xx, y, charWidth, charHeight, *s ); + CG_DrawChar(xx, y, charWidth, charHeight, *s); xx += charWidth; s++; } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - -void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) { - CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT ); -} +void CG_DrawSmallStringColor(int x, int y, const char *s, vec4_t color) { CG_DrawStringExt(x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT); } /* ================= @@ -258,12 +241,12 @@ CG_DrawStrlen Returns character count, skiping color escape codes ================= */ -int CG_DrawStrlen( const char *str ) { +int CG_DrawStrlen(const char *str) { const char *s = str; int count = 0; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; } else { count++; @@ -282,18 +265,16 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) { - float s1, t1, s2, t2; - - s1 = x/64.0; - t1 = y/64.0; - s2 = (x+w)/64.0; - t2 = (y+h)/64.0; - cgi_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); +static void CG_TileClearBox(int x, int y, int w, int h, qhandle_t hShader) { + float s1, t1, s2, t2; + + s1 = x / 64.0; + t1 = y / 64.0; + s2 = (x + w) / 64.0; + t2 = (y + h) / 64.0; + cgi_R_DrawStretchPic(x, y, w, h, s1, t1, s2, t2, hShader); } - - /* ============== CG_TileClear @@ -301,60 +282,57 @@ CG_TileClear Clear around a sized down screen ============== */ -void CG_TileClear( void ) { - int top, bottom, left, right; - int w, h; +void CG_TileClear(void) { + int top, bottom, left, right; + int w, h; w = cgs.glconfig.vidWidth; h = cgs.glconfig.vidHeight; - if ( cg.refdef.x == 0 && cg.refdef.y == 0 && - cg.refdef.width == w && cg.refdef.height == h ) { - return; // full screen rendering + if (cg.refdef.x == 0 && cg.refdef.y == 0 && cg.refdef.width == w && cg.refdef.height == h) { + return; // full screen rendering } top = cg.refdef.y; - bottom = top + cg.refdef.height-1; + bottom = top + cg.refdef.height - 1; left = cg.refdef.x; - right = left + cg.refdef.width-1; + right = left + cg.refdef.width - 1; // clear above view screen - CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader ); + CG_TileClearBox(0, 0, w, top, cgs.media.backTileShader); // clear below view screen - CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader ); + CG_TileClearBox(0, bottom, w, h - bottom, cgs.media.backTileShader); // clear left of view screen - CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(0, top, left, bottom - top + 1, cgs.media.backTileShader); // clear right of view screen - CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(right, top, w - right, bottom - top + 1, cgs.media.backTileShader); } - - /* ================ CG_FadeColor ================ */ -float *CG_FadeColor( int startMsec, int totalMsec ) { - static vec4_t color; - int t; +float *CG_FadeColor(int startMsec, int totalMsec) { + static vec4_t color; + int t; - if ( startMsec == 0 ) { + if (startMsec == 0) { return NULL; } t = cg.time - startMsec; - if ( t >= totalMsec ) { + if (t >= totalMsec) { return NULL; } // fade out - if ( totalMsec - t < FADE_TIME ) { - color[3] = ( totalMsec - t ) * 1.0/FADE_TIME; + if (totalMsec - t < FADE_TIME) { + color[3] = (totalMsec - t) * 1.0 / FADE_TIME; } else { color[3] = 1.0; } @@ -371,12 +349,11 @@ Take x,y positions as if 640 x 480 and scales them to the proper resolution ============== */ -void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charHeight,int style,qboolean zeroFill) -{ - char num[16], *ptr; - int l; - int frame; - int xWidth; +void CG_DrawNumField(int x, int y, int width, int value, int charWidth, int charHeight, int style, qboolean zeroFill) { + char num[16], *ptr; + int l; + int frame; + int xWidth; if (width < 1) { return; @@ -387,7 +364,7 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH width = 5; } - switch ( width ) { + switch (width) { case 1: value = value > 9 ? 9 : value; value = value < 0 ? 0 : value; @@ -406,71 +383,63 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH break; } - Com_sprintf (num, sizeof(num), "%i", value); + Com_sprintf(num, sizeof(num), "%i", value); l = strlen(num); if (l > width) l = width; // FIXME: Might need to do something different for the chunky font?? - switch(style) - { + switch (style) { case NUM_FONT_SMALL: xWidth = charWidth; break; case NUM_FONT_CHUNKY: - xWidth = (charWidth/1.2f) + 2; + xWidth = (charWidth / 1.2f) + 2; break; default: case NUM_FONT_BIG: - xWidth = (charWidth/2) + 7;//(charWidth/6); + xWidth = (charWidth / 2) + 7; //(charWidth/6); break; } - if ( zeroFill ) - { - for (int i = 0; i < (width - l); i++ ) - { - switch(style) - { + if (zeroFill) { + for (int i = 0; i < (width - l); i++) { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[0]); break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[0]); break; } x += 2 + (xWidth); } - } - else - { - x += 2 + (xWidth)*(width - l); + } else { + x += 2 + (xWidth) * (width - l); } ptr = num; - while (*ptr && l) - { + while (*ptr && l) { if (*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - switch(style) - { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[frame] ); - x++; // For a one line gap + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[frame]); + x++; // For a one line gap break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[frame]); break; } @@ -478,7 +447,6 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH ptr++; l--; } - } /* @@ -486,8 +454,7 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH CG_DrawProportionalString ================= */ -void CG_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) -{ - //assert(!style);//call this directly if you need style (OR it into the font handle) - cgi_R_Font_DrawString (x, y, str, color, cgs.media.qhFontMedium, -1, 1.0f); +void CG_DrawProportionalString(int x, int y, const char *str, int style, vec4_t color) { + // assert(!style);//call this directly if you need style (OR it into the font handle) + cgi_R_Font_DrawString(x, y, str, color, cgs.media.qhFontMedium, -1, 1.0f); } \ No newline at end of file diff --git a/code/cgame/cg_effects.cpp b/code/cgame/cg_effects.cpp index bd58dc4fa1..a34b2536e0 100644 --- a/code/cgame/cg_effects.cpp +++ b/code/cgame/cg_effects.cpp @@ -28,7 +28,7 @@ along with this program; if not, see . #include "cg_media.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif /* @@ -107,7 +107,7 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, } */ // When calling this version, just pass in a zero for the flags -//localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, +// localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, // qhandle_t hModel, int numFrames, qhandle_t shader, // int msec, qboolean isSprite, float scale ) { // return CG_MakeExplosion( origin, dir, hModel, numFrames, shader, msec, isSprite, scale, 0 ); @@ -118,12 +118,11 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, CG_AddTempLight ==================== */ -localEntity_t *CG_AddTempLight( vec3_t origin, float scale, vec3_t color, int msec ) -{ - localEntity_t *ex; +localEntity_t *CG_AddTempLight(vec3_t origin, float scale, vec3_t color, int msec) { + localEntity_t *ex; - if ( msec <= 0 ) { - CG_Error( "CG_AddTempLight: msec = %i", msec ); + if (msec <= 0) { + CG_Error("CG_AddTempLight: msec = %i", msec); } ex = CG_AllocLocalEntity(); @@ -134,10 +133,10 @@ localEntity_t *CG_AddTempLight( vec3_t origin, float scale, vec3_t color, int ms ex->endTime = ex->startTime + msec; // set origin - VectorCopy ( origin, ex->refEntity.origin); - VectorCopy ( origin, ex->refEntity.oldorigin ); + VectorCopy(origin, ex->refEntity.origin); + VectorCopy(origin, ex->refEntity.oldorigin); - VectorCopy( color, ex->lightColor ); + VectorCopy(color, ex->lightColor); ex->light = scale; return ex; @@ -152,29 +151,27 @@ intensity ranges from 1 (minor tremble) to 16 (major quake) ------------------------- */ -void CG_ExplosionEffects( vec3_t origin, float intensity, int radius, int time ) -{ - //FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s +void CG_ExplosionEffects(vec3_t origin, float intensity, int radius, int time) { + // FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s - vec3_t dir; - float dist, intensityScale; - float realIntensity; + vec3_t dir; + float dist, intensityScale; + float realIntensity; - VectorSubtract( cg.refdef.vieworg, origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(cg.refdef.vieworg, origin, dir); + dist = VectorNormalize(dir); - //Use the dir to add kick to the explosion + // Use the dir to add kick to the explosion - if ( dist > radius ) + if (dist > radius) return; - intensityScale = 1 - ( dist / (float) radius ); + intensityScale = 1 - (dist / (float)radius); realIntensity = intensity * intensityScale; - CGCam_Shake( realIntensity, time ); + CGCam_Shake(realIntensity, time); } - /* ------------------------- CG_SurfaceExplosion @@ -232,8 +229,9 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak for ( i = 0; i < 4; i++ ) { - VectorSet( temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[2] + (Q_flrand(0.0f, 1.0f) * 4.0f) ); - VectorSet( temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[2] + (Q_flrand(-1.0f, 1.0f) * 8.0f) ); + VectorSet( temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[2] + (Q_flrand(0.0f, 1.0f) +* 4.0f) ); VectorSet( temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[2] + (Q_flrand(-1.0f, 1.0f) +* 8.0f) ); FX_AddSprite( temp_org, temp_vel, @@ -255,14 +253,14 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak VectorNormalize( direction ); //Tag the last one with a light - le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, radius * 0.02f + (Q_flrand(0.0f, 1.0f) * 0.3f) ); - le->light = 150; - VectorSet( le->lightColor, 0.9f, 0.8f, 0.5f ); + le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, radius * 0.02f + (Q_flrand(0.0f, 1.0f) +* 0.3f) ); le->light = 150; VectorSet( le->lightColor, 0.9f, 0.8f, 0.5f ); for ( i = 0; i < NUM_EXPLOSIONS-1; i ++) { - VectorSet( new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)) ); - le = CG_MakeExplosion( new_org, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, radius * 0.05f + (Q_flrand(-1.0f, 1.0f) *0.3f) ); + VectorSet( new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * +8))*Q_flrand(-1.0f, 1.0f)), (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)) ); le = CG_MakeExplosion( new_org, direction, +cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, radius * 0.05f + (Q_flrand(-1.0f, 1.0f) *0.3f) ); } //Shake the camera @@ -290,18 +288,16 @@ Adds an explosion to a misc model breakables ------------------------- */ -void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ) -{ - int ct = 13; - float r; - vec3_t org, mid, dir; - char *effect = NULL, *effect2 = NULL; +void CG_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType) { + int ct = 13; + float r; + vec3_t org, mid, dir; + char *effect = NULL, *effect2 = NULL; - VectorAdd( mins, maxs, mid ); - VectorScale( mid, 0.5f, mid ); + VectorAdd(mins, maxs, mid); + VectorScale(mid, 0.5f, mid); - switch( chunkType ) - { + switch (chunkType) { case MAT_GLASS: effect = "chunks/glassbreak"; ct = 5; @@ -332,12 +328,11 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk ct = 20; effect = "chunks/ropebreak"; break; - case MAT_WHITE_METAL: //not sure what this crap is really supposed to be.. + case MAT_WHITE_METAL: // not sure what this crap is really supposed to be.. case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: - switch( size ) - { + switch (size) { case 2: effect = "chunks/rockbreaklg"; break; @@ -350,42 +345,35 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk break; } - if ( !effect ) - { + if (!effect) { return; } ct += 7 * size; // FIXME: real precache .. VERify that these need to be here...don't think they would because the effects should be registered in g_breakable - theFxScheduler.RegisterEffect( effect ); + theFxScheduler.RegisterEffect(effect); - if ( effect2 ) - { + if (effect2) { // FIXME: real precache - theFxScheduler.RegisterEffect( effect2 ); + theFxScheduler.RegisterEffect(effect2); } // spawn chunk roughly in the bbox of the thing.. - for ( int i = 0; i < ct; i++ ) - { - for( int j = 0; j < 3; j++ ) - { + for (int i = 0; i < ct; i++) { + for (int j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - org[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + org[j] = (r * mins[j] + (1 - r) * maxs[j]); } // shoot effect away from center - VectorSubtract( org, mid, dir ); - VectorNormalize( dir ); + VectorSubtract(org, mid, dir); + VectorNormalize(dir); - if ( effect2 && ( rand() & 1 )) - { - theFxScheduler.PlayEffect( effect2, org, dir ); - } - else - { - theFxScheduler.PlayEffect( effect, org, dir ); + if (effect2 && (rand() & 1)) { + theFxScheduler.PlayEffect(effect2, org, dir); + } else { + theFxScheduler.PlayEffect(effect, org, dir); } } } @@ -398,87 +386,76 @@ Fun chunk spewer ------------------------- */ -void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale, int customSound = 0 ) -{ - localEntity_t *le; - refEntity_t *re; - vec3_t dir; - int i, j, k; - int chunkModel = 0; - leBounceSound_t bounce = LEBS_NONE; - float r, speedMod = 1.0f; - qboolean chunk = qfalse; - - if ( chunkType == MAT_NONE ) - { +void CG_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale, int customSound = 0) { + localEntity_t *le; + refEntity_t *re; + vec3_t dir; + int i, j, k; + int chunkModel = 0; + leBounceSound_t bounce = LEBS_NONE; + float r, speedMod = 1.0f; + qboolean chunk = qfalse; + + if (chunkType == MAT_NONE) { // Well, we should do nothing return; } - if ( customSound ) - { - if ( cgs.sound_precache[customSound] ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.sound_precache[customSound] ); + if (customSound) { + if (cgs.sound_precache[customSound]) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.sound_precache[customSound]); } } - // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with effects instead of models - switch( chunkType ) - { + // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with + // effects instead of models + switch (chunkType) { case MAT_GLASS: - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); } return; break; case MAT_GRATE1: - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.grateSound ); + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.grateSound); } return; break; - case MAT_ELECTRICAL:// (sparks) - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound (va("sound/ambience/spark%d.wav", Q_irand(1, 6))) ); + case MAT_ELECTRICAL: // (sparks) + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgi_S_RegisterSound(va("sound/ambience/spark%d.wav", Q_irand(1, 6)))); } return; break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: - case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.rockBreakSound ); + case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.rockBreakSound); bounce = LEBS_ROCK; } speedMod = 0.5f; // rock blows up less break; case MAT_GLASS_METAL: - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); // FIXME: should probably have a custom sound + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); // FIXME: should probably have a custom sound bounce = LEBS_METAL; } break; case MAT_CRATE1: case MAT_CRATE2: - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0,1)] ); + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0, 1)]); } break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: - case MAT_ELEC_METAL:// FIXME: maybe have its own sound? - if ( !customSound ) - { - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.chunkSound ); + case MAT_ELEC_METAL: // FIXME: maybe have its own sound? + if (!customSound) { + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.chunkSound); bounce = LEBS_METAL; } speedMod = 0.8f; // metal blows up a bit more @@ -495,62 +472,53 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins break; } - if ( baseScale <= 0.0f ) - { + if (baseScale <= 0.0f) { baseScale = 1.0f; } // Chunks - for( i = 0; i < numChunks; i++ ) - { - if ( customChunk > 0 ) - { + for (i = 0; i < numChunks; i++) { + if (customChunk > 0) { // Try to use a custom chunk. - if ( cgs.model_draw[customChunk] ) - { + if (cgs.model_draw[customChunk]) { chunk = qtrue; chunkModel = cgs.model_draw[customChunk]; } } - if ( !chunk ) - { + if (!chunk) { // No custom chunk. Pick a random chunk type at run-time so we don't get the same chunks - switch( chunkType ) - { - case MAT_METAL2: //bluegrey + switch (chunkType) { + case MAT_METAL2: // bluegrey chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; break; - case MAT_GREY_STONE://gray + case MAT_GREY_STONE: // gray chunkModel = cgs.media.chunkModels[CHUNK_ROCK1][Q_irand(0, 3)]; break; - case MAT_LT_STONE: //tan + case MAT_LT_STONE: // tan chunkModel = cgs.media.chunkModels[CHUNK_ROCK2][Q_irand(0, 3)]; break; - case MAT_DRK_STONE://brown + case MAT_DRK_STONE: // brown chunkModel = cgs.media.chunkModels[CHUNK_ROCK3][Q_irand(0, 3)]; break; case MAT_WHITE_METAL: chunkModel = cgs.media.chunkModels[CHUNK_WHITE_METAL][Q_irand(0, 3)]; break; - case MAT_CRATE1://yellow multi-colored crate chunks + case MAT_CRATE1: // yellow multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE1][Q_irand(0, 3)]; break; - case MAT_CRATE2://red multi-colored crate chunks + case MAT_CRATE2: // red multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE2][Q_irand(0, 3)]; break; case MAT_ELEC_METAL: case MAT_GLASS_METAL: - case MAT_METAL://grey + case MAT_METAL: // grey chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; break; case MAT_METAL3: - if ( rand() & 1 ) - { + if (rand() & 1) { chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; - } - else - { + } else { chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; } break; @@ -560,8 +528,7 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins } // It wouldn't look good to throw a bunch of RGB axis models...so make sure we have something to work with. - if ( chunkModel ) - { + if (chunkModel) { le = CG_AllocLocalEntity(); re = &le->refEntity; @@ -570,26 +537,25 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins le->endTime = cg.time + 1300 + Q_flrand(0.0f, 1.0f) * 900; // spawn chunk roughly in the bbox of the thing...bias towards center in case thing blowing up doesn't complete fill its bbox. - for( j = 0; j < 3; j++ ) - { + for (j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - re->origin[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + re->origin[j] = (r * mins[j] + (1 - r) * maxs[j]); } - VectorCopy( re->origin, le->pos.trBase ); + VectorCopy(re->origin, le->pos.trBase); // Move out from center of thing, otherwise you can end up things moving across the brush in an undesirable direction. Visually looks wrong - VectorSubtract( re->origin, origin, dir ); - VectorNormalize( dir ); - VectorScale( dir, Q_flrand( speed * 0.5f, speed * 1.25f ) * speedMod, le->pos.trDelta ); + VectorSubtract(re->origin, origin, dir); + VectorNormalize(dir); + VectorScale(dir, Q_flrand(speed * 0.5f, speed * 1.25f) * speedMod, le->pos.trDelta); // Angular Velocity - VectorSet( le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360 ); + VectorSet(le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360); le->angles.trDelta[0] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[1] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[2] = 0; // don't do roll - VectorScale( le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta ); + VectorScale(le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta); le->pos.trType = TR_GRAVITY; le->angles.trType = TR_LINEAR; @@ -600,52 +566,47 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins le->leBounceSoundType = bounce; // Make sure that we have the desired start size set - le->radius = Q_flrand( baseScale * 0.75f, baseScale * 1.25f ); + le->radius = Q_flrand(baseScale * 0.75f, baseScale * 1.25f); re->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, re->axis ); // could do an angles to axis, but this is cheaper and works ok - for( k = 0; k < 3; k++ ) - { - VectorScale( re->axis[k], le->radius, re->axis[k] ); + AxisCopy(axisDefault, re->axis); // could do an angles to axis, but this is cheaper and works ok + for (k = 0; k < 3; k++) { + VectorScale(re->axis[k], le->radius, re->axis[k]); } } } } -void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int radius ) -{ - localEntity_t *le; - refEntity_t *re; +void CG_TestLine(vec3_t start, vec3_t end, int time, unsigned int color, int radius) { + localEntity_t *le; + refEntity_t *re; le = CG_AllocLocalEntity(); le->leType = LE_LINE; le->startTime = cg.time; le->endTime = cg.time + time; - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + le->lifeRate = 1.0 / (le->endTime - le->startTime); re = &le->refEntity; - VectorCopy( start, re->origin ); - VectorCopy( end, re->oldorigin); + VectorCopy(start, re->origin); + VectorCopy(end, re->oldorigin); re->shaderTime = cg.time / 1000.0f; re->reType = RT_LINE; - re->radius = 0.5*radius; - re->customShader = cgs.media.whiteShader; //trap_R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); + re->radius = 0.5 * radius; + re->customShader = cgs.media.whiteShader; // trap_R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); re->shaderTexCoord[0] = re->shaderTexCoord[1] = 1.0f; - if (color==0) - { + if (color == 0) { re->shaderRGBA[0] = re->shaderRGBA[1] = re->shaderRGBA[2] = re->shaderRGBA[3] = 0xff; - } - else - { + } else { re->shaderRGBA[0] = color & 0xff; color >>= 8; re->shaderRGBA[1] = color & 0xff; color >>= 8; re->shaderRGBA[2] = color & 0xff; -// color >>= 8; -// re->shaderRGBA[3] = color & 0xff; + // color >>= 8; + // re->shaderRGBA[3] = color & 0xff; re->shaderRGBA[3] = 0xff; } @@ -661,300 +622,256 @@ void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int ra // Since we have shared verts when we tesselate the glass sheet, it helps to have a // random offset table set up up front...so that we can have more random looking breaks. -static float offX[20][20], - offZ[20][20]; +static float offX[20][20], offZ[20][20]; -static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], bool stick, int time, vec3_t dmgDir ) -{ - float bounce; - vec3_t rotDelta; - vec3_t vel, accel; - vec3_t rgb1; +static void CG_DoGlassQuad(vec3_t p[4], vec2_t uv[4], bool stick, int time, vec3_t dmgDir) { + float bounce; + vec3_t rotDelta; + vec3_t vel, accel; + vec3_t rgb1; - VectorSet( vel, Q_flrand(-1.0f, 1.0f) * 12, Q_flrand(-1.0f, 1.0f) * 12, -1 ); + VectorSet(vel, Q_flrand(-1.0f, 1.0f) * 12, Q_flrand(-1.0f, 1.0f) * 12, -1); - if ( !stick ) - { + if (!stick) { // We aren't a motion delayed chunk, so let us move quickly - VectorMA( vel, 0.3f, dmgDir, vel ); + VectorMA(vel, 0.3f, dmgDir, vel); } // Set up acceleration due to gravity, 800 is standard QuakeIII gravity, so let's use something close - VectorSet( accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f ) ); + VectorSet(accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f)); - VectorSet( rgb1, 1.0f, 1.0f, 1.0f ); + VectorSet(rgb1, 1.0f, 1.0f, 1.0f); // Being glass, we don't want to bounce much bounce = Q_flrand(0.0f, 1.0f) * 0.2f + 0.15f; // Set up our random rotate, we only do PITCH and YAW, not ROLL. This is something like degrees per second - VectorSet( rotDelta, Q_flrand(-1.0f, 1.0f) * 40.0f, Q_flrand(-1.0f, 1.0f) * 40.0f, 0.0f ); - - CPoly *pol = FX_AddPoly(p, uv, 4, // verts, ST, vertCount - vel, accel, // motion - 0.15f, 0.0f, 85.0f, // alpha start, alpha end, alpha parm ( begin alpha fade when 85% of life is complete ) - rgb1, rgb1, 0.0f, // rgb start, rgb end, rgb parm ( not used ) - rotDelta, bounce, time, // rotation amount, bounce, and time to delay motion for ( zero if no delay ); - 3500 + Q_flrand(0.0f, 1.0f) * 1000, // life - cgi_R_RegisterShader( "gfx/misc/test_crackle" ), - FX_APPLY_PHYSICS | FX_ALPHA_NONLINEAR | FX_USE_ALPHA ); - - if ( Q_flrand(0.0f, 1.0f) > 0.95f && pol ) - { - pol->AddFlags( FX_IMPACT_RUNS_FX | FX_KILL_ON_IMPACT ); - pol->SetImpactFxID( theFxScheduler.RegisterEffect( "misc/glass_impact" )); + VectorSet(rotDelta, Q_flrand(-1.0f, 1.0f) * 40.0f, Q_flrand(-1.0f, 1.0f) * 40.0f, 0.0f); + + CPoly *pol = FX_AddPoly(p, uv, 4, // verts, ST, vertCount + vel, accel, // motion + 0.15f, 0.0f, 85.0f, // alpha start, alpha end, alpha parm ( begin alpha fade when 85% of life is complete ) + rgb1, rgb1, 0.0f, // rgb start, rgb end, rgb parm ( not used ) + rotDelta, bounce, time, // rotation amount, bounce, and time to delay motion for ( zero if no delay ); + 3500 + Q_flrand(0.0f, 1.0f) * 1000, // life + cgi_R_RegisterShader("gfx/misc/test_crackle"), FX_APPLY_PHYSICS | FX_ALPHA_NONLINEAR | FX_USE_ALPHA); + + if (Q_flrand(0.0f, 1.0f) > 0.95f && pol) { + pol->AddFlags(FX_IMPACT_RUNS_FX | FX_KILL_ON_IMPACT); + pol->SetImpactFxID(theFxScheduler.RegisterEffect("misc/glass_impact")); } } -static void CG_CalcBiLerp( vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4] ) -{ - vec3_t temp; +static void CG_CalcBiLerp(vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4]) { + vec3_t temp; // Nasty crap - VectorScale( verts[0], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[1], subVerts[0] ); - VectorScale( subVerts[0], 1.0f - uv[0][1], temp ); - VectorScale( verts[3], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[2], subVerts[0] ); - VectorMA( temp, uv[0][1], subVerts[0], subVerts[0] ); - - VectorScale( verts[0], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[1], subVerts[1] ); - VectorScale( subVerts[1], 1.0f - uv[1][1], temp ); - VectorScale( verts[3], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[2], subVerts[1] ); - VectorMA( temp, uv[1][1], subVerts[1], subVerts[1] ); - - VectorScale( verts[0], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[1], subVerts[2] ); - VectorScale( subVerts[2], 1.0f - uv[2][1], temp ); - VectorScale( verts[3], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[2], subVerts[2] ); - VectorMA( temp, uv[2][1], subVerts[2], subVerts[2] ); - - VectorScale( verts[0], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[1], subVerts[3] ); - VectorScale( subVerts[3], 1.0f - uv[3][1], temp ); - VectorScale( verts[3], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[2], subVerts[3] ); - VectorMA( temp, uv[3][1], subVerts[3], subVerts[3] ); + VectorScale(verts[0], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[1], subVerts[0]); + VectorScale(subVerts[0], 1.0f - uv[0][1], temp); + VectorScale(verts[3], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[2], subVerts[0]); + VectorMA(temp, uv[0][1], subVerts[0], subVerts[0]); + + VectorScale(verts[0], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[1], subVerts[1]); + VectorScale(subVerts[1], 1.0f - uv[1][1], temp); + VectorScale(verts[3], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[2], subVerts[1]); + VectorMA(temp, uv[1][1], subVerts[1], subVerts[1]); + + VectorScale(verts[0], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[1], subVerts[2]); + VectorScale(subVerts[2], 1.0f - uv[2][1], temp); + VectorScale(verts[3], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[2], subVerts[2]); + VectorMA(temp, uv[2][1], subVerts[2], subVerts[2]); + + VectorScale(verts[0], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[1], subVerts[3]); + VectorScale(subVerts[3], 1.0f - uv[3][1], temp); + VectorScale(verts[3], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[2], subVerts[3]); + VectorMA(temp, uv[3][1], subVerts[3], subVerts[3]); } // bilinear -//f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. - - -static void CG_CalcHeightWidth( vec3_t verts[4], float *height, float *width ) -{ - vec3_t dir1, dir2, cross; - - VectorSubtract( verts[3], verts[0], dir1 ); // v - VectorSubtract( verts[1], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v +// f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. + +static void CG_CalcHeightWidth(vec3_t verts[4], float *height, float *width) { + vec3_t dir1, dir2, cross; + + VectorSubtract(verts[3], verts[0], dir1); // v + VectorSubtract(verts[1], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width += VectorNormalize(cross) / VectorNormalize(dir1); // v *width *= 0.5f; - VectorSubtract( verts[1], verts[0], dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[3], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v + VectorSubtract(verts[1], verts[0], dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[3], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height += VectorNormalize(cross) / VectorNormalize(dir1); // v *height *= 0.5f; } -//Consider a line in 3D with position vector "a" and direction vector "v" and -// let "p" be the position vector of an arbitrary point in 3D -//dist = len( crossprod(p-a,v) ) / len(v); +// Consider a line in 3D with position vector "a" and direction vector "v" and +// let "p" be the position vector of an arbitrary point in 3D +// dist = len( crossprod(p-a,v) ) / len(v); -void CG_InitGlass( void ) -{ +void CG_InitGlass(void) { int i, t; // Build a table first, so that we can do a more unpredictable crack scheme // do it once, up front to save a bit of time. - for ( i = 0; i < 20; i++ ) - { - for ( t = 0; t < 20; t++ ) - { + for (i = 0; i < 20; i++) { + for (t = 0; t < 20; t++) { offX[t][i] = Q_flrand(-1.0f, 1.0f) * 0.03f; offZ[i][t] = Q_flrand(-1.0f, 1.0f) * 0.03f; } } } -#define TIME_DECAY_SLOW 0.1f -#define TIME_DECAY_MED 0.04f -#define TIME_DECAY_FAST 0.009f +#define TIME_DECAY_SLOW 0.1f +#define TIME_DECAY_MED 0.04f +#define TIME_DECAY_FAST 0.009f -void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius ) -{ - int i, t; - int mxHeight, mxWidth; - float height, width; - float stepWidth, stepHeight; - float timeDecay; - float x, z; - float xx, zz; - int time = 0; - bool stick = true; - vec3_t subVerts[4]; - vec2_t biPoints[4]; +void CG_DoGlass(vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius) { + int i, t; + int mxHeight, mxWidth; + float height, width; + float stepWidth, stepHeight; + float timeDecay; + float x, z; + float xx, zz; + int time = 0; + bool stick = true; + vec3_t subVerts[4]; + vec2_t biPoints[4]; // To do a smarter tesselation, we should figure out the relative height and width of the brush face, // then use this to pick a lod value from 1-3 in each axis. This will give us 1-9 lod levels, which will // hopefully be sufficient. - CG_CalcHeightWidth( verts, &height, &width ); + CG_CalcHeightWidth(verts, &height, &width); - cgi_S_StartSound( dmgPt, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/glassbreak1.wav")); + cgi_S_StartSound(dmgPt, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/glassbreak1.wav")); // Pick "LOD" for height - if ( height < 100 ) - { + if (height < 100) { stepHeight = 0.2f; mxHeight = 5; timeDecay = TIME_DECAY_SLOW; } -/* else if ( height > 220 ) // was originally mxHeight = 20....but removing this whole section because it causes huge number of chunks...which is bad - { - stepHeight = 0.075f; - mxHeight = 15; - timeDecay = TIME_DECAY_FAST; - }*/ - else - { + /* else if ( height > 220 ) // was originally mxHeight = 20....but removing this whole section because it causes huge number of chunks...which is bad + { + stepHeight = 0.075f; + mxHeight = 15; + timeDecay = TIME_DECAY_FAST; + }*/ + else { stepHeight = 0.1f; mxHeight = 10; timeDecay = TIME_DECAY_MED; } // Pick "LOD" for width - if ( width < 100 ) - { + if (width < 100) { stepWidth = 0.2f; mxWidth = 5; - timeDecay = ( timeDecay + TIME_DECAY_SLOW ) * 0.5f; + timeDecay = (timeDecay + TIME_DECAY_SLOW) * 0.5f; } -/* else if ( width > 220 ) // don't do this because it causes too much chug with large glass panes...especially when more than one pane can be broken at a time - { - stepWidth = 0.075f; - mxWidth = 15; - timeDecay = ( timeDecay + TIME_DECAY_FAST ) * 0.5f; - }*/ - else - { + /* else if ( width > 220 ) // don't do this because it causes too much chug with large glass panes...especially when more than one pane can be broken at a + time + { + stepWidth = 0.075f; + mxWidth = 15; + timeDecay = ( timeDecay + TIME_DECAY_FAST ) * 0.5f; + }*/ + else { stepWidth = 0.1f; mxWidth = 10; - timeDecay = ( timeDecay + TIME_DECAY_MED ) * 0.5f; + timeDecay = (timeDecay + TIME_DECAY_MED) * 0.5f; } - for ( z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++ ) - { - for ( x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++ ) - { + for (z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++) { + for (x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++) { // This is nasty..we do this because we don't want to add a random offset on the edge of the glass brush // ...but we do in the center, otherwise the breaking scheme looks way too orderly - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i][t]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[0], xx, zz ); + VectorSet2(biPoints[0], xx, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i][t + 1]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t + 1][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[1], xx + stepWidth, zz ); + VectorSet2(biPoints[1], xx + stepWidth, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i + 1][t + 1]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t + 1][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[2], xx + stepWidth, zz + stepHeight); + VectorSet2(biPoints[2], xx + stepWidth, zz + stepHeight); - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i + 1][t]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[3], xx, zz + stepHeight ); + VectorSet2(biPoints[3], xx, zz + stepHeight); - CG_CalcBiLerp( verts, subVerts, biPoints ); + CG_CalcBiLerp(verts, subVerts, biPoints); - float dif = DistanceSquared( subVerts[0], dmgPt ) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; + float dif = DistanceSquared(subVerts[0], dmgPt) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; // If we decrease dif, we are increasing the impact area, making it more likely to blow out large holes dif -= dmgRadius * dmgRadius; - if ( dif > 1 ) - { + if (dif > 1) { stick = true; time = dif + Q_flrand(0.0f, 1.0f) * 200; - } - else - { + } else { stick = false; time = 0; } - CG_DoGlassQuad( subVerts, biPoints, stick, time, dmgDir ); + CG_DoGlassQuad(subVerts, biPoints, stick, time, dmgDir); } } } @@ -999,113 +916,92 @@ CG_Seeker } */ //------------------------------------------------------------------------------------------ -void CG_DrawTargetBeam( vec3_t start, vec3_t end, vec3_t norm, const char *beamFx, const char *impactFx ) -{ - int handle = 0; - vec3_t dir; - SEffectTemplate *temp; +void CG_DrawTargetBeam(vec3_t start, vec3_t end, vec3_t norm, const char *beamFx, const char *impactFx) { + int handle = 0; + vec3_t dir; + SEffectTemplate *temp; // overriding the effect, so give us a copy first - temp = theFxScheduler.GetEffectCopy( beamFx, &handle ); + temp = theFxScheduler.GetEffectCopy(beamFx, &handle); - VectorSubtract( start, end, dir ); - VectorNormalize( dir ); + VectorSubtract(start, end, dir); + VectorNormalize(dir); - if ( temp ) - { + if (temp) { // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "beam" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "beam"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( end[0], end[0] ); - prim->mOrigin2Y.SetRange( end[1], end[1] ); - prim->mOrigin2Z.SetRange( end[2], end[2] ); + prim->mOrigin2X.SetRange(end[0], end[0]); + prim->mOrigin2Y.SetRange(end[1], end[1]); + prim->mOrigin2Z.SetRange(end[2], end[2]); // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "glow" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "glow"); // glow is not required - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( end[0], end[0] ); - prim->mOrigin2Y.SetRange( end[1], end[1] ); - prim->mOrigin2Z.SetRange( end[2], end[2] ); + prim->mOrigin2X.SetRange(end[0], end[0]); + prim->mOrigin2Y.SetRange(end[1], end[1]); + prim->mOrigin2Z.SetRange(end[2], end[2]); } // play the modified effect - theFxScheduler.PlayEffect( handle, start, dir ); + theFxScheduler.PlayEffect(handle, start, dir); } } - if ( impactFx ) - { - theFxScheduler.PlayEffect( impactFx, end, norm ); + if (impactFx) { + theFxScheduler.PlayEffect(impactFx, end, norm); } } -void CG_PlayEffectBolted( const char *fxName, const int modelIndex, const int boltIndex, const int entNum, vec3_t origin, int iLoopTime, const bool isRelative ) -{ - vec3_t axis[3];//FIXME: shouldn't this be initialized to something? It isn't in the EV_PLAY_EFFECT call... irrelevant? - int boltInfo; - - //pack the data into boltInfo as if we were going to send it over the network - gi.G2API_AttachEnt(&boltInfo, - &g_entities[entNum].ghoul2[modelIndex], - boltIndex, - entNum, - modelIndex); - //send direcly to FX scheduler - theFxScheduler.PlayEffect( fxName, - origin, - axis, - boltInfo, - -1, - false, - iLoopTime, - isRelative ); //iLoopTime 0 = not looping, 1 for infinite, else duration +void CG_PlayEffectBolted(const char *fxName, const int modelIndex, const int boltIndex, const int entNum, vec3_t origin, int iLoopTime, const bool isRelative) { + vec3_t axis[3]; // FIXME: shouldn't this be initialized to something? It isn't in the EV_PLAY_EFFECT call... irrelevant? + int boltInfo; + + // pack the data into boltInfo as if we were going to send it over the network + gi.G2API_AttachEnt(&boltInfo, &g_entities[entNum].ghoul2[modelIndex], boltIndex, entNum, modelIndex); + // send direcly to FX scheduler + theFxScheduler.PlayEffect(fxName, origin, axis, boltInfo, -1, false, iLoopTime, + isRelative); // iLoopTime 0 = not looping, 1 for infinite, else duration } -void CG_PlayEffectIDBolted( const int fxID, const int modelIndex, const int boltIndex, const int entNum, vec3_t origin, int iLoopTime, const bool isRelative ) -{ - const char *fxName = CG_ConfigString( CS_EFFECTS + fxID ); - CG_PlayEffectBolted( fxName, modelIndex, boltIndex, entNum, origin, iLoopTime, isRelative ); +void CG_PlayEffectIDBolted(const int fxID, const int modelIndex, const int boltIndex, const int entNum, vec3_t origin, int iLoopTime, const bool isRelative) { + const char *fxName = CG_ConfigString(CS_EFFECTS + fxID); + CG_PlayEffectBolted(fxName, modelIndex, boltIndex, entNum, origin, iLoopTime, isRelative); } -void CG_PlayEffectOnEnt( const char *fxName, const int clientNum, vec3_t origin, const vec3_t fwd ) -{ - vec3_t temp, axis[3]; +void CG_PlayEffectOnEnt(const char *fxName, const int clientNum, vec3_t origin, const vec3_t fwd) { + vec3_t temp, axis[3]; // Assume angles, we'll do a cross product to finish up - VectorCopy( fwd, axis[0] ); - MakeNormalVectors( fwd, axis[1], temp ); - CrossProduct( axis[0], axis[1], axis[2] ); - //call FX scheduler directly - theFxScheduler.PlayEffect( fxName, origin, axis, -1, clientNum, false ); + VectorCopy(fwd, axis[0]); + MakeNormalVectors(fwd, axis[1], temp); + CrossProduct(axis[0], axis[1], axis[2]); + // call FX scheduler directly + theFxScheduler.PlayEffect(fxName, origin, axis, -1, clientNum, false); } -void CG_PlayEffectIDOnEnt( const int fxID, const int clientNum, vec3_t origin, const vec3_t fwd ) -{ - const char *fxName = CG_ConfigString( CS_EFFECTS + fxID ); - CG_PlayEffectOnEnt( fxName, clientNum, origin, fwd ); +void CG_PlayEffectIDOnEnt(const int fxID, const int clientNum, vec3_t origin, const vec3_t fwd) { + const char *fxName = CG_ConfigString(CS_EFFECTS + fxID); + CG_PlayEffectOnEnt(fxName, clientNum, origin, fwd); } -void CG_PlayEffect( const char *fxName, vec3_t origin, const vec3_t fwd ) -{ - vec3_t temp, axis[3]; +void CG_PlayEffect(const char *fxName, vec3_t origin, const vec3_t fwd) { + vec3_t temp, axis[3]; // Assume angles, we'll do a cross product to finish up - VectorCopy( fwd, axis[0] ); - MakeNormalVectors( fwd, axis[1], temp ); - CrossProduct( axis[0], axis[1], axis[2] ); - //call FX scheduler directly - theFxScheduler.PlayEffect( fxName, origin, axis, -1, -1, false ); + VectorCopy(fwd, axis[0]); + MakeNormalVectors(fwd, axis[1], temp); + CrossProduct(axis[0], axis[1], axis[2]); + // call FX scheduler directly + theFxScheduler.PlayEffect(fxName, origin, axis, -1, -1, false); } -void CG_PlayEffectID( const int fxID, vec3_t origin, const vec3_t fwd ) -{ - const char *fxName = CG_ConfigString( CS_EFFECTS + fxID ); - CG_PlayEffect( fxName, origin, fwd ); +void CG_PlayEffectID(const int fxID, vec3_t origin, const vec3_t fwd) { + const char *fxName = CG_ConfigString(CS_EFFECTS + fxID); + CG_PlayEffect(fxName, origin, fwd); } diff --git a/code/cgame/cg_ents.cpp b/code/cgame/cg_ents.cpp index 4c8ea97538..989cf163a0 100644 --- a/code/cgame/cg_ents.cpp +++ b/code/cgame/cg_ents.cpp @@ -32,12 +32,12 @@ along with this program; if not, see . #include "../game/wp_saber.h" #include "../game/g_vehicles.h" -extern void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles); -extern void CG_CheckSaberInWater( centity_t *cent, centity_t *scent, int saberNum, int modelIndex, vec3_t origin, vec3_t angles ); -extern void CG_ForcePushBlur( const vec3_t org, qboolean darkSide = qfalse ); -extern void CG_AddForceSightShell( refEntity_t *ent, centity_t *cent ); -extern qboolean CG_PlayerCanSeeCent( centity_t *cent ); -extern cvar_t *debug_subdivision; +extern void CG_AddSaberBlade(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles); +extern void CG_CheckSaberInWater(centity_t *cent, centity_t *scent, int saberNum, int modelIndex, vec3_t origin, vec3_t angles); +extern void CG_ForcePushBlur(const vec3_t org, qboolean darkSide = qfalse); +extern void CG_AddForceSightShell(refEntity_t *ent, centity_t *cent); +extern qboolean CG_PlayerCanSeeCent(centity_t *cent); +extern cvar_t *debug_subdivision; /* ====================== @@ -47,24 +47,21 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName ) { - int i; - orientation_t lerped; +void CG_PositionEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName) { + int i; + orientation_t lerped; // lerp the tag - cgi_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0f - parent->backlerp, tagName ); + cgi_R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0f - parent->backlerp, tagName); // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } // had to cast away the const to avoid compiler problems... - MatrixMultiply( lerped.axis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(lerped.axis, ((refEntity_t *)parent)->axis, entity->axis); entity->backlerp = parent->backlerp; } @@ -76,37 +73,31 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName, orientation_t *tagOrient ) { - int i; - orientation_t lerped; - vec3_t tempAxis[3]; +void CG_PositionRotatedEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName, orientation_t *tagOrient) { + int i; + orientation_t lerped; + vec3_t tempAxis[3]; // lerp the tag - cgi_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0f - parent->backlerp, tagName ); + cgi_R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0f - parent->backlerp, tagName); - if ( tagOrient ) - { - VectorCopy( lerped.origin, tagOrient->origin ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorCopy( lerped.axis[i], tagOrient->axis[i] ); + if (tagOrient) { + VectorCopy(lerped.origin, tagOrient->origin); + for (i = 0; i < 3; i++) { + VectorCopy(lerped.axis[i], tagOrient->axis[i]); } } // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } - MatrixMultiply( entity->axis, lerped.axis, tempAxis ); - MatrixMultiply( tempAxis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(entity->axis, lerped.axis, tempAxis); + MatrixMultiply(tempAxis, ((refEntity_t *)parent)->axis, entity->axis); } - - /* ========================================================================== @@ -122,31 +113,26 @@ CG_SetEntitySoundPosition Also called by event processing code ====================== */ -vec3_t *CG_SetEntitySoundPosition( centity_t *cent ) { +vec3_t *CG_SetEntitySoundPosition(centity_t *cent) { static vec3_t v3Return; - if ( cent->currentState.solid == SOLID_BMODEL ) { - vec3_t origin; - float *v; + if (cent->currentState.solid == SOLID_BMODEL) { + vec3_t origin; + float *v; - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, origin ); - cgi_S_UpdateEntityPosition( cent->currentState.number, origin ); + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, origin); + cgi_S_UpdateEntityPosition(cent->currentState.number, origin); VectorCopy(origin, v3Return); } else { - if ( cent->currentState.eType == ET_PLAYER - && cent->gent - && cent->gent->client - && cent->gent->ghoul2.IsValid() - && cent->gent->ghoul2[0].animModelIndexOffset )//If it has an animOffset it's a cinematic anim - {//I might be running out of my bounding box, so use my headPoint from the last render frame...? - //NOTE: if I'm not rendered, will this not update correctly? Would cent->lerpOrigin be any more updated? + if (cent->currentState.eType == ET_PLAYER && cent->gent && cent->gent->client && cent->gent->ghoul2.IsValid() && + cent->gent->ghoul2[0].animModelIndexOffset) // If it has an animOffset it's a cinematic anim + { // I might be running out of my bounding box, so use my headPoint from the last render frame...? + // NOTE: if I'm not rendered, will this not update correctly? Would cent->lerpOrigin be any more updated? VectorCopy(cent->gent->client->renderInfo.eyePoint, v3Return); - } - else - {//just use my org + } else { // just use my org VectorCopy(cent->lerpOrigin, v3Return); } - cgi_S_UpdateEntityPosition( cent->currentState.number, v3Return ); + cgi_S_UpdateEntityPosition(cent->currentState.number, v3Return); } return &v3Return; @@ -159,149 +145,136 @@ CG_EntityEffects Add continuous entity effects, like local entity emission and lighting ================== */ -static void CG_EntityEffects( centity_t *cent ) { +static void CG_EntityEffects(centity_t *cent) { // update sound origins vec3_t v3Origin; - VectorCopy(*CG_SetEntitySoundPosition( cent ),v3Origin); + VectorCopy(*CG_SetEntitySoundPosition(cent), v3Origin); // add loop sound - if ( cent->currentState.loopSound ) - { + if (cent->currentState.loopSound) { soundChannel_t chan = CHAN_AUTO; gentity_t *ent = cent->gent; - if ( ent->s.eFlags & EF_LESS_ATTEN ) - { + if (ent->s.eFlags & EF_LESS_ATTEN) { chan = CHAN_LESS_ATTEN; } - sfxHandle_t sfx = ( cent->currentState.eType == ET_MOVER ) ? cent->currentState.loopSound : cgs.sound_precache[ cent->currentState.loopSound ]; + sfxHandle_t sfx = (cent->currentState.eType == ET_MOVER) ? cent->currentState.loopSound : cgs.sound_precache[cent->currentState.loopSound]; // Only play sound if being drawn. - if ( !( ent->s.eFlags & EF_NODRAW ) ) - { - cgi_S_AddLoopingSound( cent->currentState.number, v3Origin/*cent->lerpOrigin*/, vec3_origin, sfx, chan ); + if (!(ent->s.eFlags & EF_NODRAW)) { + cgi_S_AddLoopingSound(cent->currentState.number, v3Origin /*cent->lerpOrigin*/, vec3_origin, sfx, chan); } } // constant light glow - if ( cent->currentState.constantLight ) { - int cl; - float i, r, g, b; + if (cent->currentState.constantLight) { + int cl; + float i, r, g, b; cl = cent->currentState.constantLight; - r = (float) (cl & 0xFF) / 255.0; - g = (float) ((cl >> 8) & 0xFF) / 255.0; - b = (float) ((cl >> 16) & 0xFF) / 255.0; - i = (float) ((cl >> 24) & 0xFF) * 4.0; - cgi_R_AddLightToScene( cent->lerpOrigin, i, r, g, b ); + r = (float)(cl & 0xFF) / 255.0; + g = (float)((cl >> 8) & 0xFF) / 255.0; + b = (float)((cl >> 16) & 0xFF) / 255.0; + i = (float)((cl >> 24) & 0xFF) * 4.0; + cgi_R_AddLightToScene(cent->lerpOrigin, i, r, g, b); } } -void CG_AddRefEntWithTransportEffect ( centity_t *cent, refEntity_t *ent ) -{ +void CG_AddRefEntWithTransportEffect(centity_t *cent, refEntity_t *ent) { // We are a normal thing.... - cgi_R_AddRefEntityToScene (ent); + cgi_R_AddRefEntityToScene(ent); - if ( ent->renderfx & RF_PULSATE && cent->gent->owner && cent->gent->owner->health && - !cent->gent->owner->s.number && cent->gent->owner->client && //only for player - cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && - cent->currentState.saberActive == qfalse ) - { + if (ent->renderfx & RF_PULSATE && cent->gent->owner && cent->gent->owner->health && !cent->gent->owner->s.number && + cent->gent->owner->client && // only for player + cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && cent->currentState.saberActive == qfalse) { // if we are the saber and we have been dropped, do a glow so it can be spotted easier - float wv; - vec3_t org; + float wv; + vec3_t org; - ent->customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); + ent->customShader = cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); ent->renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.003f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.003f) * 0.08f + 0.1f; ent->shaderRGBA[0] = wv * 255; ent->shaderRGBA[1] = wv * 255; ent->shaderRGBA[2] = wv * 0; - cgi_R_AddRefEntityToScene (ent); + cgi_R_AddRefEntityToScene(ent); - for ( int i = -4; i < 10; i += 1 ) - { - VectorMA( ent->origin, -i, ent->axis[2], org ); + for (int i = -4; i < 10; i += 1) { + VectorMA(ent->origin, -i, ent->axis[2], org); - FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + FX_AddSprite(org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000); } - if ( cent->gent->owner->s.weapon == WP_SABER ) - {//he's still controlling me - FX_AddSprite( cent->gent->owner->client->renderInfo.handRPoint, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + if (cent->gent->owner->s.weapon == WP_SABER) { // he's still controlling me + FX_AddSprite(cent->gent->owner->client->renderInfo.handRPoint, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, + 0x08000000); } } } - /* Ghoul2 Insert Start */ // Copy the ghoul2 data into the ref ent correctly -void CG_SetGhoul2Info( refEntity_t *ent, centity_t *cent) -{ +void CG_SetGhoul2Info(refEntity_t *ent, centity_t *cent) { ent->ghoul2 = ¢->gent->ghoul2; - VectorCopy( cent->currentState.modelScale, ent->modelScale); + VectorCopy(cent->currentState.modelScale, ent->modelScale); ent->radius = cent->currentState.radius; - VectorCopy (cent->lerpAngles, ent->angles); + VectorCopy(cent->lerpAngles, ent->angles); } - // write in the axis and stuff -void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) -{ - // extract the wraith ID from the bolt info +void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) { + // extract the wraith ID from the bolt info int modelNum = cent->currentState.boltInfo >> MODEL_SHIFT; modelNum &= MODEL_AND; - int boltNum = cent->currentState.boltInfo >> BOLT_SHIFT; + int boltNum = cent->currentState.boltInfo >> BOLT_SHIFT; boltNum &= BOLT_AND; - int entNum = cent->currentState.boltInfo >> ENTITY_SHIFT; + int entNum = cent->currentState.boltInfo >> ENTITY_SHIFT; entNum &= ENTITY_AND; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - // go away and get me the bolt position for this frame please - gi.G2API_GetBoltMatrix(cent->gent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, cg.time, cgs.model_draw, cent->currentState.modelScale); + // go away and get me the bolt position for this frame please + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, + cg.time, cgs.model_draw, cent->currentState.modelScale); // set up the axis and origin we need for the actual effect spawning - ent->origin[0] = boltMatrix.matrix[0][3]; - ent->origin[1] = boltMatrix.matrix[1][3]; - ent->origin[2] = boltMatrix.matrix[2][3]; + ent->origin[0] = boltMatrix.matrix[0][3]; + ent->origin[1] = boltMatrix.matrix[1][3]; + ent->origin[2] = boltMatrix.matrix[2][3]; - ent->axis[0][0] = boltMatrix.matrix[0][0]; - ent->axis[0][1] = boltMatrix.matrix[1][0]; - ent->axis[0][2] = boltMatrix.matrix[2][0]; + ent->axis[0][0] = boltMatrix.matrix[0][0]; + ent->axis[0][1] = boltMatrix.matrix[1][0]; + ent->axis[0][2] = boltMatrix.matrix[2][0]; - ent->axis[1][0] = boltMatrix.matrix[0][1]; - ent->axis[1][1] = boltMatrix.matrix[1][1]; - ent->axis[1][2] = boltMatrix.matrix[2][1]; + ent->axis[1][0] = boltMatrix.matrix[0][1]; + ent->axis[1][1] = boltMatrix.matrix[1][1]; + ent->axis[1][2] = boltMatrix.matrix[2][1]; - ent->axis[2][0] = boltMatrix.matrix[0][2]; - ent->axis[2][1] = boltMatrix.matrix[1][2]; - ent->axis[2][2] = boltMatrix.matrix[2][2]; + ent->axis[2][0] = boltMatrix.matrix[0][2]; + ent->axis[2][1] = boltMatrix.matrix[1][2]; + ent->axis[2][2] = boltMatrix.matrix[2][2]; } -void ScaleModelAxis(refEntity_t *ent) +void ScaleModelAxis(refEntity_t *ent) -{ // scale the model should we need to - if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) - { - VectorScale( ent->axis[0], ent->modelScale[0] , ent->axis[0] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) - { - VectorScale( ent->axis[1], ent->modelScale[1] , ent->axis[1] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) - { - VectorScale( ent->axis[2], ent->modelScale[2] , ent->axis[2] ); - ent->nonNormalizedAxes = qtrue; - } +{ // scale the model should we need to + if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) { + VectorScale(ent->axis[0], ent->modelScale[0], ent->axis[0]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) { + VectorScale(ent->axis[1], ent->modelScale[1], ent->axis[1]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) { + VectorScale(ent->axis[2], ent->modelScale[2], ent->axis[2]); + ent->nonNormalizedAxes = qtrue; + } } /* Ghoul2 Insert End @@ -312,325 +285,255 @@ Ghoul2 Insert End CG_General ================== */ -static void CG_General( centity_t *cent ) -{ - refEntity_t ent; - entityState_t *s1; +static void CG_General(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // if set to invisible, skip - if (!s1->modelindex && !cent->gent->ghoul2.IsValid() ) { + if (!s1->modelindex && !cent->gent->ghoul2.IsValid()) { return; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if ( s1->eFlags & EF_NODRAW ) - { + if (s1->eFlags & EF_NODRAW) { // If you don't like it doing NODRAW, then don't set the flag return; } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); // set frame - if ( cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM ) - { + if (cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM) { // by setting the shader time to the current time, we can force an animating shader to not animate ent.shaderTime = cg.time * 0.001f; } - if ( s1->eFlags & EF_SHADER_ANIM ) - { + if (s1->eFlags & EF_SHADER_ANIM) { // Deliberately setting it up so that shader anim will completely override any kind of model animation frame setting. - ent.renderfx|=RF_SETANIMINDEX; + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - } - else if ( s1->eFlags & EF_ANIM_ONCE ) - { - //s1->frame++; - //ent.frame = s1->frame; + } else if (s1->eFlags & EF_ANIM_ONCE) { + // s1->frame++; + // ent.frame = s1->frame; ent.frame = cent->gent->s.frame; - ent.renderfx|=RF_CAP_FRAMES; - } - else if ( s1->eFlags & EF_ANIM_ALLFAST ) - { + ent.renderfx |= RF_CAP_FRAMES; + } else if (s1->eFlags & EF_ANIM_ALLFAST) { ent.frame = (cg.time / 100); - ent.renderfx|=RF_WRAP_FRAMES; - } - else - { + ent.renderfx |= RF_WRAP_FRAMES; + } else { ent.frame = s1->frame; } ent.oldframe = ent.frame; ent.backlerp = 0; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); ent.hModel = cgs.model_draw[s1->modelindex]; - if ( !ent.radius ) - {// Set default g2 cull radius. + if (!ent.radius) { // Set default g2 cull radius. ent.radius = 60; } - if ( s1->eFlags & EF_AUTO_SIZE && cent->gent ) - { - cgi_R_ModelBounds( ent.hModel, cent->gent->mins, cent->gent->maxs ); - //Only do this once + if (s1->eFlags & EF_AUTO_SIZE && cent->gent) { + cgi_R_ModelBounds(ent.hModel, cent->gent->mins, cent->gent->maxs); + // Only do this once cent->gent->s.eFlags &= ~EF_AUTO_SIZE; } // player model - if (s1->number == cg.snap->ps.clientNum) - { - ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors + if (s1->number == cg.snap->ps.clientNum) { + ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // are we bolted to a Ghoul2 model? - if (s1->boltInfo) - { + if (s1->boltInfo) { G2_BoltToGhoul2Model(cent, &ent); - } - else - { + } else { //------------------------------------------------------- // Start of chair //------------------------------------------------------- - if ( cent->gent->s.weapon == WP_EMPLACED_GUN || ( cent->gent->activator && cent->gent->activator->owner && - cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON )) - { - vec3_t temp; + if (cent->gent->s.weapon == WP_EMPLACED_GUN || + (cent->gent->activator && cent->gent->activator->owner && cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON)) { + vec3_t temp; - if ( cent->gent->health <= 0 && cent->gent->e_ThinkFunc == thinkF_NULL ) - { - if ( !cent->gent->bounceCount ) - {//not an EWeb - ent.customShader = cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg" ); + if (cent->gent->health <= 0 && cent->gent->e_ThinkFunc == thinkF_NULL) { + if (!cent->gent->bounceCount) { // not an EWeb + ent.customShader = cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg"); } - VectorSet( temp, 0, 0, 1 ); + VectorSet(temp, 0, 0, 1); // add a big scorch mark under the gun - CG_ImpactMark( cgs.media.scavMarkShader, cent->lerpOrigin, temp, - 0, 1,1,1, 1.0f, qfalse, 92, qtrue ); - CG_ImpactMark( cgs.media.scavMarkShader, cent->lerpOrigin, temp, - 90, 1,1,1, 1.0f, qfalse, 48, qtrue ); - } - else - { - VectorSet( temp, 0, 0, 1 ); - - if ( !( cent->gent->svFlags & SVF_INACTIVE )) - { - if ( !cent->gent->bounceCount ) - {//not an EWeb - ent.customShader = cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_on" ); + CG_ImpactMark(cgs.media.scavMarkShader, cent->lerpOrigin, temp, 0, 1, 1, 1, 1.0f, qfalse, 92, qtrue); + CG_ImpactMark(cgs.media.scavMarkShader, cent->lerpOrigin, temp, 90, 1, 1, 1, 1.0f, qfalse, 48, qtrue); + } else { + VectorSet(temp, 0, 0, 1); + + if (!(cent->gent->svFlags & SVF_INACTIVE)) { + if (!cent->gent->bounceCount) { // not an EWeb + ent.customShader = cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_on"); } } // shadow under the gun - CG_ImpactMark( cgs.media.shadowMarkShader, cent->lerpOrigin, temp, - 0, 1,1,1, 1.0f, qfalse, 32, qtrue ); + CG_ImpactMark(cgs.media.shadowMarkShader, cent->lerpOrigin, temp, 0, 1, 1, 1, 1.0f, qfalse, 32, qtrue); } } - if ( cent->gent->activator && cent->gent->activator->owner && - cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON && - cent->gent->activator->owner->s.number == cent->currentState.number ) // gun number must be same as current entities number + if (cent->gent->activator && cent->gent->activator->owner && cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON && + cent->gent->activator->owner->s.number == cent->currentState.number) // gun number must be same as current entities number { centity_t *cc = &cg_entities[cent->gent->activator->s.number]; -const weaponData_t *wData = NULL; + const weaponData_t *wData = NULL; - if ( cc->currentState.weapon ) - { + if (cc->currentState.weapon) { wData = &weaponData[cc->currentState.weapon]; } - if ( !( cc->currentState.eFlags & EF_FIRING ) && !( cc->currentState.eFlags & EF_ALT_FIRING )) - { + if (!(cc->currentState.eFlags & EF_FIRING) && !(cc->currentState.eFlags & EF_ALT_FIRING)) { // not animating..pausing was leaving the barrels in a bad state - gi.G2API_PauseBoneAnim( ¢->gent->ghoul2[cent->gent->playerModel], "model_root", cg.time ); + gi.G2API_PauseBoneAnim(¢->gent->ghoul2[cent->gent->playerModel], "model_root", cg.time); -// gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, -// 0, 0, BONE_ANIM_OVERRIDE, 1.0f, cg.time ); + // gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, + // 0, 0, BONE_ANIM_OVERRIDE, 1.0f, cg.time ); } // get alternating muzzle end bolts - int bolt = cent->gent->handRBolt; - mdxaBone_t boltMatrix; + int bolt = cent->gent->handRBolt; + mdxaBone_t boltMatrix; - if ( !cc->gent->fxID || bolt == -1 ) - { + if (!cc->gent->fxID || bolt == -1) { bolt = cent->gent->handLBolt; } - if ( bolt == -1 ) - { + if (bolt == -1) { bolt = 0; } - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, 0, bolt, - &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, 0, bolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // store the muzzle point and direction so that we can fire in the right direction - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cc->gent->client->renderInfo.muzzlePoint ); - if ( cent->gent->bounceCount ) - {//EWeb - *sigh* the muzzle tag on this is not aligned like th eone on the emplaced gun... consistency anyone...? - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, cc->gent->client->renderInfo.muzzleDir ); - } - else - {//Emplaced gun - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, cc->gent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cc->gent->client->renderInfo.muzzlePoint); + if (cent->gent->bounceCount) { // EWeb - *sigh* the muzzle tag on this is not aligned like th eone on the emplaced gun... consistency anyone...? + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, cc->gent->client->renderInfo.muzzleDir); + } else { // Emplaced gun + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, cc->gent->client->renderInfo.muzzleDir); } cc->gent->client->renderInfo.mPCalcTime = cg.time; // HACK: adding in muzzle flashes - if ( cc->muzzleFlashTime > 0 && wData ) - { + if (cc->muzzleFlashTime > 0 && wData) { const char *effect = NULL; cc->muzzleFlashTime = 0; // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cc->currentState.eFlags & EF_ALT_FIRING ) - { + if (cc->currentState.eFlags & EF_ALT_FIRING) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if ( cc->currentState.eFlags & EF_FIRING || cc->currentState.eFlags & EF_ALT_FIRING ) - { - if ( cent->gent->bounceCount ) - {//EWeb - gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, - 2, 4, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); - } - else - {//Emplaced Gun - gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, - 0, 3, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); + if (cc->currentState.eFlags & EF_FIRING || cc->currentState.eFlags & EF_ALT_FIRING) { + if (cent->gent->bounceCount) { // EWeb + gi.G2API_SetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, 2, 4, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, + cg.time, -1, -1); + } else { // Emplaced Gun + gi.G2API_SetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, 0, 3, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, + cg.time, -1, -1); } - if ( effect ) - { + if (effect) { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cc->gent->client->renderInfo.muzzlePoint, - cc->gent->client->renderInfo.muzzleDir ); + theFxScheduler.PlayEffect(effect, cc->gent->client->renderInfo.muzzlePoint, cc->gent->client->renderInfo.muzzleDir); } } } - VectorCopy( cent->gent->s.apos.trBase, cent->lerpAngles ); + VectorCopy(cent->gent->s.apos.trBase, cent->lerpAngles); } //------------------------------------------------------- // End of chair //------------------------------------------------------- - AnglesToAxis( cent->lerpAngles, ent.axis ); + AnglesToAxis(cent->lerpAngles, ent.axis); } - //copy modelscale, if any - VectorCopy( cent->currentState.modelScale, ent.modelScale ); - //apply modelscale, if any + // copy modelscale, if any + VectorCopy(cent->currentState.modelScale, ent.modelScale); + // apply modelscale, if any ScaleModelAxis(&ent); - if (cent->gent->ghoul2.size()) - { - //FIXME: use a flag for this, not a strcmp - if ( cent->gent->classname && Q_stricmp( "limb", cent->gent->classname ) == 0 ) - {//limb, copy RGB + if (cent->gent->ghoul2.size()) { + // FIXME: use a flag for this, not a strcmp + if (cent->gent->classname && Q_stricmp("limb", cent->gent->classname) == 0) { // limb, copy RGB ent.shaderRGBA[0] = cent->gent->startRGBA[0]; ent.shaderRGBA[1] = cent->gent->startRGBA[1]; ent.shaderRGBA[2] = cent->gent->startRGBA[2]; } - if ( s1->weapon == WP_SABER && cent->gent && cent->gent->owner && cent->gent->owner->inuse ) - {//flying lightsaber - //FIXME: better way to tell what it is would be nice - if ( cent->gent->classname && !Q_stricmp( "limb", cent->gent->classname ) ) - {//limb, just add blade - if ( cent->gent->owner->client ) - { - if ( cent->gent->owner->client->ps.saber[0].Length() > 0 ) - { - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], NULL, ent.renderfx, - cent->gent->weaponModel[0], cent->lerpOrigin, cent->lerpAngles ); - } - else if ( cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER ) - { - CG_CheckSaberInWater( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], 0, cent->gent->weaponModel[0], - cent->lerpOrigin, cent->lerpAngles ); + if (s1->weapon == WP_SABER && cent->gent && cent->gent->owner && cent->gent->owner->inuse) { // flying lightsaber + // FIXME: better way to tell what it is would be nice + if (cent->gent->classname && !Q_stricmp("limb", cent->gent->classname)) { // limb, just add blade + if (cent->gent->owner->client) { + if (cent->gent->owner->client->ps.saber[0].Length() > 0) { + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], NULL, ent.renderfx, + cent->gent->weaponModel[0], cent->lerpOrigin, cent->lerpAngles); + } else if (cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER) { + CG_CheckSaberInWater(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], 0, cent->gent->weaponModel[0], + cent->lerpOrigin, cent->lerpAngles); } } - } - else - {//thrown saber - //light? sound? - if ( cent->gent->owner->client && g_entities[cent->currentState.otherEntityNum].client && g_entities[cent->currentState.otherEntityNum].client->ps.saber[0].Active() ) - {//saber is in-flight and active, play a sound on it - if ( cent->gent->owner->client->ps.saberEntityState == SES_RETURNING - && cent->gent->owner->client->ps.saber[0].type != SABER_STAR ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, vec3_origin, - cgs.sound_precache[g_entities[cent->currentState.clientNum].client->ps.saber[0].soundLoop] ); - } - else - { + } else { // thrown saber + // light? sound? + if (cent->gent->owner->client && g_entities[cent->currentState.otherEntityNum].client && + g_entities[cent->currentState.otherEntityNum].client->ps.saber[0].Active()) { // saber is in-flight and active, play a sound on it + if (cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && cent->gent->owner->client->ps.saber[0].type != SABER_STAR) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, + cgs.sound_precache[g_entities[cent->currentState.clientNum].client->ps.saber[0].soundLoop]); + } else { int spinSound; - if ( cent->gent->owner->client->ps.saber[0].spinSound - && cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound] ) - { + if (cent->gent->owner->client->ps.saber[0].spinSound && cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound]) { spinSound = cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound]; - } - else if ( cent->gent->owner->client->ps.saber[0].type == SABER_SITH_SWORD ) - { - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); - } - else - { - switch ( cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW] ) - { + } else if (cent->gent->owner->client->ps.saber[0].type == SABER_SITH_SWORD) { + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); + } else { + switch (cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW]) { case FORCE_LEVEL_1: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; case FORCE_LEVEL_2: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; default: case FORCE_LEVEL_3: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; } } - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, - vec3_origin, spinSound ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, spinSound); /* if ( cg_weapons[WP_SABER].missileSound ) { @@ -639,75 +542,50 @@ const weaponData_t *wData = NULL; */ } } - if ( cent->gent->owner->client ) - { - if ( cent->gent->owner->client->ps.saber[0].Length() > 0 ) - {//only add the blade if it's on - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], NULL, ent.renderfx, - 0, cent->lerpOrigin, cent->lerpAngles ); - } - else if ( cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER ) - { - CG_CheckSaberInWater( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], 0, 0, cent->lerpOrigin, - cent->lerpAngles ); + if (cent->gent->owner->client) { + if (cent->gent->owner->client->ps.saber[0].Length() > 0) { // only add the blade if it's on + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], NULL, ent.renderfx, 0, cent->lerpOrigin, + cent->lerpAngles); + } else if (cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER) { + CG_CheckSaberInWater(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], 0, 0, cent->lerpOrigin, + cent->lerpAngles); } } - if ( cent->gent->owner->health ) - { - //make sure we can always be seen + if (cent->gent->owner->health) { + // make sure we can always be seen ent.renderfx |= RF_PULSATE; } } } - } - else - { - if ( s1->weapon == WP_SABER && cent->gent && cent->gent->owner ) - {//flying lightsaber - //light? sound? - if ( cent->gent->owner->client && cent->currentState.saberActive ) - {//saber is in-flight and active, play a sound on it - if ( cent->gent->owner->client->ps.saberEntityState == SES_RETURNING - && cent->gent->owner->client->ps.saber[0].type != SABER_STAR ) - { - if ( cg_weapons[WP_SABER].firingSound ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, vec3_origin, cg_weapons[WP_SABER].firingSound ); + } else { + if (s1->weapon == WP_SABER && cent->gent && cent->gent->owner) { // flying lightsaber + // light? sound? + if (cent->gent->owner->client && cent->currentState.saberActive) { // saber is in-flight and active, play a sound on it + if (cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && cent->gent->owner->client->ps.saber[0].type != SABER_STAR) { + if (cg_weapons[WP_SABER].firingSound) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, cg_weapons[WP_SABER].firingSound); } - } - else - { + } else { int spinSound; - if ( cent->gent->owner->client->ps.saber[0].spinSound - && cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound] ) - { + if (cent->gent->owner->client->ps.saber[0].spinSound && cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound]) { spinSound = cgs.sound_precache[cent->gent->owner->client->ps.saber[0].spinSound]; - } - else if ( cent->gent->owner->client->ps.saber[0].type == SABER_SITH_SWORD ) - { - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); - } - else - { - switch ( cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW] ) - { + } else if (cent->gent->owner->client->ps.saber[0].type == SABER_SITH_SWORD) { + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); + } else { + switch (cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW]) { case FORCE_LEVEL_1: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; case FORCE_LEVEL_2: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; default: case FORCE_LEVEL_3: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; } } - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, - vec3_origin, spinSound ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, spinSound); /* if ( cg_weapons[WP_SABER].missileSound ) { @@ -716,152 +594,130 @@ const weaponData_t *wData = NULL; */ } } - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - NULL, &ent, ent.renderfx, 0, NULL, NULL ); + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], NULL, &ent, ent.renderfx, 0, NULL, NULL); - if ( cent->gent->owner->health ) - { - //make sure we can always be seen + if (cent->gent->owner->health) { + // make sure we can always be seen ent.renderfx |= RF_PULSATE; } } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if ( cent->gent && cent->gent->forcePushTime > cg.time ) - {//FIXME: if I'm a rather large model, this will look kind of stupid... - CG_ForcePushBlur( cent->lerpOrigin ); + if (cent->gent && cent->gent->forcePushTime > cg.time) { // FIXME: if I'm a rather large model, this will look kind of stupid... + CG_ForcePushBlur(cent->lerpOrigin); } - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); - if ( cent->gent->health <= 0 - && cent->gent->s.weapon == WP_EMPLACED_GUN - && cent->gent->e_ThinkFunc ) - { + if (cent->gent->health <= 0 && cent->gent->s.weapon == WP_EMPLACED_GUN && cent->gent->e_ThinkFunc) { // make the gun pulse red to warn about it exploding - float val = (1.0f - (float)(cent->gent->nextthink - cg.time) / 3200.0f ) * 0.3f; + float val = (1.0f - (float)(cent->gent->nextthink - cg.time) / 3200.0f) * 0.3f; - ent.customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite" ); - ent.shaderRGBA[0] = (sin( cg.time * 0.04f ) * val * 0.4f + val) * 255; + ent.customShader = cgi_R_RegisterShader("gfx/effects/solidWhite"); + ent.shaderRGBA[0] = (sin(cg.time * 0.04f) * val * 0.4f + val) * 255; ent.shaderRGBA[1] = ent.shaderRGBA[2] = 0; ent.renderfx |= RF_RGB_TINT; - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } //-------------------------- - if ( s1->eFlags & EF_FIRING && cent->gent->inuse ) - { - //special code for adding the beam to the attached tripwire mine - vec3_t beamOrg; - int handle = 0; - SEffectTemplate *temp; + if (s1->eFlags & EF_FIRING && cent->gent->inuse) { + // special code for adding the beam to the attached tripwire mine + vec3_t beamOrg; + int handle = 0; + SEffectTemplate *temp; - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward // overriding the effect, so give us a copy first - temp = theFxScheduler.GetEffectCopy( "tripMine/laser", &handle ); + temp = theFxScheduler.GetEffectCopy("tripMine/laser", &handle); - if ( temp ) - { + if (temp) { // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "line1" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "line1"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( cent->gent->pos4[0], cent->gent->pos4[0] ); - prim->mOrigin2Y.SetRange( cent->gent->pos4[1], cent->gent->pos4[1] ); - prim->mOrigin2Z.SetRange( cent->gent->pos4[2], cent->gent->pos4[2] ); + prim->mOrigin2X.SetRange(cent->gent->pos4[0], cent->gent->pos4[0]); + prim->mOrigin2Y.SetRange(cent->gent->pos4[1], cent->gent->pos4[1]); + prim->mOrigin2Z.SetRange(cent->gent->pos4[2], cent->gent->pos4[2]); // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "line2" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "line2"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the cent->gent->pos3point - prim->mOrigin2X.SetRange( cent->gent->pos4[0], cent->gent->pos4[0] ); - prim->mOrigin2Y.SetRange( cent->gent->pos4[1], cent->gent->pos4[1] ); - prim->mOrigin2Z.SetRange( cent->gent->pos4[2], cent->gent->pos4[2] ); + prim->mOrigin2X.SetRange(cent->gent->pos4[0], cent->gent->pos4[0]); + prim->mOrigin2Y.SetRange(cent->gent->pos4[1], cent->gent->pos4[1]); + prim->mOrigin2Z.SetRange(cent->gent->pos4[2], cent->gent->pos4[2]); // play the modified effect - theFxScheduler.PlayEffect( handle, beamOrg, ent.axis[0] ); + theFxScheduler.PlayEffect(handle, beamOrg, ent.axis[0]); } } } - theFxScheduler.PlayEffect( "tripMine/laserImpactGlow", cent->gent->pos4, ent.axis[0] ); + theFxScheduler.PlayEffect("tripMine/laserImpactGlow", cent->gent->pos4, ent.axis[0]); } + if (s1->eFlags & EF_PROX_TRIP) { + // special code for adding the glow end to proximity tripmine + vec3_t beamOrg; - if ( s1->eFlags & EF_PROX_TRIP ) - { - //special code for adding the glow end to proximity tripmine - vec3_t beamOrg; - - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward - theFxScheduler.PlayEffect( "tripMine/glowBit", beamOrg, ent.axis[0] ); + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward + theFxScheduler.PlayEffect("tripMine/glowBit", beamOrg, ent.axis[0]); } - if ( s1->eFlags & EF_ALT_FIRING ) - { + if (s1->eFlags & EF_ALT_FIRING) { // hack for the spotlight - vec3_t org, axis[3], dir; + vec3_t org, axis[3], dir; - AngleVectors( cent->lerpAngles, dir, NULL, NULL ); + AngleVectors(cent->lerpAngles, dir, NULL, NULL); - CG_GetTagWorldPosition( &ent, "tag_flash", org, axis ); + CG_GetTagWorldPosition(&ent, "tag_flash", org, axis); - theFxScheduler.PlayEffect( "env/light_cone", org, axis[0] ); + theFxScheduler.PlayEffect("env/light_cone", org, axis[0]); - VectorMA( cent->lerpOrigin, cent->gent->radius - 5, dir, org ); // stay a bit back from the impact point...this may not be enough? + VectorMA(cent->lerpOrigin, cent->gent->radius - 5, dir, org); // stay a bit back from the impact point...this may not be enough? - cgi_R_AddLightToScene( org, 225, 1.0f, 1.0f, 1.0f ); + cgi_R_AddLightToScene(org, 225, 1.0f, 1.0f, 1.0f); } //----------------------------------------------------------- - if ( cent->gent->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED )) - { + if (cent->gent->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED)) { // Dumb assumption, but I guess we must be a shielded ion_cannon?? We should probably verify // if it's an ion_cannon that's Heavy Weapon only, we don't want to make it shielded do we...? - if ( (!strcmp( "misc_ion_cannon", cent->gent->classname )) && (cent->gent->flags & FL_SHIELDED )) - { + if ((!strcmp("misc_ion_cannon", cent->gent->classname)) && (cent->gent->flags & FL_SHIELDED)) { // must be doing "pain"....er, impact - if ( cent->gent->painDebounceTime > cg.time ) - { - float t = (float)(cent->gent->painDebounceTime - cg.time ) / 1000.0f; + if (cent->gent->painDebounceTime > cg.time) { + float t = (float)(cent->gent->painDebounceTime - cg.time) / 1000.0f; // Only display when we have damage - if ( t >= 0.0f && t <= 1.0f ) - { + if (t >= 0.0f && t <= 1.0f) { t *= Q_flrand(0.0f, 1.0f); ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = 255.0f * t; ent.shaderRGBA[3] = 255; ent.renderfx &= ~RF_ALPHA_FADE; ent.renderfx |= RF_RGB_TINT; - ent.customShader = cgi_R_RegisterShader( "gfx/misc/ion_shield" ); + ent.customShader = cgi_R_RegisterShader("gfx/misc/ion_shield"); - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } } } } - //draw force sight shell around it, too - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && CG_PlayerCanSeeCent( cent ) ) - {//so player can see dark missiles/explosives - if ( s1->weapon == WP_THERMAL - || s1->weapon == WP_DET_PACK - || s1->weapon == WP_TRIP_MINE - || (cent->gent&¢->gent->e_UseFunc==useF_ammo_power_converter_use) - || (cent->gent&¢->gent->e_UseFunc==useF_shield_power_converter_use) - || (s1->eFlags&EF_FORCE_VISIBLE) ) - {//really, we only need to do this for things like thermals, detpacks and tripmines, no? - CG_AddForceSightShell( &ent, cent ); + // draw force sight shell around it, too + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + CG_PlayerCanSeeCent(cent)) { // so player can see dark missiles/explosives + if (s1->weapon == WP_THERMAL || s1->weapon == WP_DET_PACK || s1->weapon == WP_TRIP_MINE || + (cent->gent && cent->gent->e_UseFunc == useF_ammo_power_converter_use) || + (cent->gent && cent->gent->e_UseFunc == useF_shield_power_converter_use) || + (s1->eFlags & EF_FORCE_VISIBLE)) { // really, we only need to do this for things like thermals, detpacks and tripmines, no? + CG_AddForceSightShell(&ent, cent); } } } @@ -873,16 +729,16 @@ CG_Speaker Speaker entities can automatically play sounds ================== */ -static void CG_Speaker( centity_t *cent ) { - if ( ! cent->currentState.clientNum ) { // FIXME: use something other than clientNum... - return; // not auto triggering +static void CG_Speaker(centity_t *cent) { + if (!cent->currentState.clientNum) { // FIXME: use something other than clientNum... + return; // not auto triggering } - if ( cg.time < cent->miscTime ) { + if (cg.time < cent->miscTime) { return; } - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.sound_precache[cent->currentState.eventParm] ); + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_ITEM, cgs.sound_precache[cent->currentState.eventParm]); // ent->s.frame = ent->wait * 10; // ent->s.clientNum = ent->random * 10; @@ -894,45 +750,40 @@ static void CG_Speaker( centity_t *cent ) { CG_Item ================== */ -static void CG_Item( centity_t *cent ) -{ - refEntity_t ent; - entityState_t *es; - gitem_t *item; -// int msec; -// float frac; - float scale; +static void CG_Item(centity_t *cent) { + refEntity_t ent; + entityState_t *es; + gitem_t *item; + // int msec; + // float frac; + float scale; es = ¢->currentState; - if ( es->modelindex >= bg_numItems ) - { - CG_Error( "Bad item index %i on entity", es->modelindex ); + if (es->modelindex >= bg_numItems) { + CG_Error("Bad item index %i on entity", es->modelindex); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // if set to invisible, skip - if ( (!es->modelindex && !cent->gent->ghoul2.IsValid() ) || ( es->eFlags & EF_NODRAW ) ) - { + if ((!es->modelindex && !cent->gent->ghoul2.IsValid()) || (es->eFlags & EF_NODRAW)) { return; } -/* -Ghoul2 Insert End -*/ - if ( cent->gent && !cent->gent->inuse ) - { + /* + Ghoul2 Insert End + */ + if (cent->gent && !cent->gent->inuse) { // Yeah, I know....items were being freed on touch, but it could still get here and draw incorrectly... return; } - item = &bg_itemlist[ es->modelindex ]; + item = &bg_itemlist[es->modelindex]; - if ( cg_simpleItems.integer ) - { - memset( &ent, 0, sizeof( ent ) ); + if (cg_simpleItems.integer) { + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); ent.origin[2] += 16; ent.radius = 14; ent.customShader = cg_items[es->modelindex].icon; @@ -945,153 +796,129 @@ Ghoul2 Insert End return; } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); // items bob up and down continuously - if( item->giType == IT_HOLOCRON ) - { + if (item->giType == IT_HOLOCRON) { scale = 0.005f + cent->currentState.number * 0.00001f; - cent->lerpOrigin[2] += (float)(4 + cos( ( cg.time + 1000 ) * scale ) * 3)+8; // just raised them up a bit + cent->lerpOrigin[2] += (float)(4 + cos((cg.time + 1000) * scale) * 3) + 8; // just raised them up a bit } - - // autorotate at one of two speeds -// if ( item->giType == IT_HEALTH ) { -// VectorCopy( cg.autoAnglesFast, cent->lerpAngles ); -// AxisCopy( cg.autoAxisFast, ent.axis ); -// } else { - if( item->giType == IT_HOLOCRON ) - { - VectorCopy( cg.autoAngles, cent->lerpAngles ); - AxisCopy( cg.autoAxis, ent.axis ); + // if ( item->giType == IT_HEALTH ) { + // VectorCopy( cg.autoAnglesFast, cent->lerpAngles ); + // AxisCopy( cg.autoAxisFast, ent.axis ); + // } else { + if (item->giType == IT_HOLOCRON) { + VectorCopy(cg.autoAngles, cent->lerpAngles); + AxisCopy(cg.autoAxis, ent.axis); } - // the weapons have their origin where they attatch to player // models, so we need to offset them or they will rotate // eccentricly -// if ( item->giType == IT_WEAPON ) { -// weaponInfo_t *wi; -// -// wi = &cg_weapons[item->giTag]; -// cent->lerpOrigin[0] -= -// wi->weaponMidpoint[0] * ent.axis[0][0] + -// wi->weaponMidpoint[1] * ent.axis[1][0] + -// wi->weaponMidpoint[2] * ent.axis[2][0]; -// cent->lerpOrigin[1] -= -// wi->weaponMidpoint[0] * ent.axis[0][1] + -// wi->weaponMidpoint[1] * ent.axis[1][1] + -// wi->weaponMidpoint[2] * ent.axis[2][1]; -// cent->lerpOrigin[2] -= -// wi->weaponMidpoint[0] * ent.axis[0][2] + -// wi->weaponMidpoint[1] * ent.axis[1][2] + -// wi->weaponMidpoint[2] * ent.axis[2][2]; - -// cent->lerpOrigin[2] += 8; // an extra height boost -// } + // if ( item->giType == IT_WEAPON ) { + // weaponInfo_t *wi; + // + // wi = &cg_weapons[item->giTag]; + // cent->lerpOrigin[0] -= + // wi->weaponMidpoint[0] * ent.axis[0][0] + + // wi->weaponMidpoint[1] * ent.axis[1][0] + + // wi->weaponMidpoint[2] * ent.axis[2][0]; + // cent->lerpOrigin[1] -= + // wi->weaponMidpoint[0] * ent.axis[0][1] + + // wi->weaponMidpoint[1] * ent.axis[1][1] + + // wi->weaponMidpoint[2] * ent.axis[2][1]; + // cent->lerpOrigin[2] -= + // wi->weaponMidpoint[0] * ent.axis[0][2] + + // wi->weaponMidpoint[1] * ent.axis[1][2] + + // wi->weaponMidpoint[2] * ent.axis[2][2]; + + // cent->lerpOrigin[2] += 8; // an extra height boost + // } vec3_t spinAngles; - //AxisClear( ent.axis ); - VectorCopy( cent->gent->s.angles, spinAngles ); + // AxisClear( ent.axis ); + VectorCopy(cent->gent->s.angles, spinAngles); - if ( cent->gent->ghoul2.IsValid() - && cent->gent->ghoul2.size() ) - {//since modelindex is used by items as an index into items(not models), we need to ignore the hModel here to force it to use the ghoul2 model if we have one + if (cent->gent->ghoul2.IsValid() && cent->gent->ghoul2.size()) { // since modelindex is used by items as an index into items(not models), we need to ignore + // the hModel here to force it to use the ghoul2 model if we have one ent.hModel = cgs.model_draw[0]; - } - else - { + } else { ent.hModel = cg_items[es->modelindex].models; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); ent.nonNormalizedAxes = qfalse; // lovely...this is for weapons that should be oriented vertically. For weapons lockers and such. - if ( cent->gent->spawnflags & 16 ) - { //VectorClear( spinAngles ); - if ( item->giType == IT_WEAPON - && item->giTag == WP_SABER ) - { - if ( cent->gent->random ) - {//pitch specified + if (cent->gent->spawnflags & 16) { // VectorClear( spinAngles ); + if (item->giType == IT_WEAPON && item->giTag == WP_SABER) { + if (cent->gent->random) { // pitch specified spinAngles[PITCH] += cent->gent->random; - } - else - { + } else { spinAngles[PITCH] -= 20; } - } - else - { + } else { spinAngles[PITCH] -= 75; } } - if( item->giType != IT_HOLOCRON ) - { - AnglesToAxis( spinAngles, ent.axis ); + if (item->giType != IT_HOLOCRON) { + AnglesToAxis(spinAngles, ent.axis); } // items without glow textures need to keep a minimum light value // so they are always visible -/* if (( item->giType == IT_WEAPON ) || ( item->giType == IT_ARMOR )) - { - ent.renderfx |= RF_MINLIGHT; - } -*/ + /* if (( item->giType == IT_WEAPON ) || ( item->giType == IT_ARMOR )) + { + ent.renderfx |= RF_MINLIGHT; + } + */ // increase the size of the weapons when they are presented as items -// if ( item->giType == IT_WEAPON ) { -// VectorScale( ent.axis[0], 1.5f, ent.axis[0] ); -// VectorScale( ent.axis[1], 1.5f, ent.axis[1] ); -// VectorScale( ent.axis[2], 1.5f, ent.axis[2] ); -// ent.nonNormalizedAxes = qtrue; -// } + // if ( item->giType == IT_WEAPON ) { + // VectorScale( ent.axis[0], 1.5f, ent.axis[0] ); + // VectorScale( ent.axis[1], 1.5f, ent.axis[1] ); + // VectorScale( ent.axis[2], 1.5f, ent.axis[2] ); + // ent.nonNormalizedAxes = qtrue; + // } // add to refresh list cgi_R_AddRefEntityToScene(&ent); - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && CG_PlayerCanSeeCent( cent ) ) - { - CG_AddForceSightShell( &ent, cent ); + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && CG_PlayerCanSeeCent(cent)) { + CG_AddForceSightShell(&ent, cent); } - if ( item->giType == IT_WEAPON - && item->giTag == WP_SABER - && (!cent->gent || !(cent->gent->spawnflags&64/*ITMSF_NOGLOW*/)) ) - { + if (item->giType == IT_WEAPON && item->giTag == WP_SABER && (!cent->gent || !(cent->gent->spawnflags & 64 /*ITMSF_NOGLOW*/))) { // saber pickup item needs to be more visible - float wv; - vec3_t org; + float wv; + vec3_t org; - ent.customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); + ent.customShader = cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); ent.renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.002f ) * 0.08f + 0.2f; + wv = sin(cg.time * 0.002f) * 0.08f + 0.2f; ent.shaderRGBA[0] = ent.shaderRGBA[1] = wv * 255; ent.shaderRGBA[2] = 0; cgi_R_AddRefEntityToScene(&ent); - for ( int i = -4; i < 10; i += 1 ) - { - VectorMA( ent.origin, -i, ent.axis[2], org ); + for (int i = -4; i < 10; i += 1) { + VectorMA(ent.origin, -i, ent.axis[2], org); - FX_AddSprite( org, NULL, NULL, 10.0f, 10.0f, wv * 0.5f, wv * 0.5f, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + FX_AddSprite(org, NULL, NULL, 10.0f, 10.0f, wv * 0.5f, wv * 0.5f, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000); } // THIS light looks crappy...maybe it should just be removed... - cgi_R_AddLightToScene( ent.origin, wv * 350 + 180, 1.0f, 1.0f, 0.0f ); + cgi_R_AddLightToScene(ent.origin, wv * 350 + 180, 1.0f, 1.0f, 0.0f); } } @@ -1102,181 +929,156 @@ Ghoul2 Insert End CG_Missile =============== */ -static void CG_Missile( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; - const weaponInfo_t *weapon; - const weaponData_t *wData; +static void CG_Missile(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; + const weaponInfo_t *weapon; + const weaponData_t *wData; - if ( !cent->gent->inuse ) + if (!cent->gent->inuse) return; s1 = ¢->currentState; - if ( s1->weapon >= WP_NUM_WEAPONS ) { + if (s1->weapon >= WP_NUM_WEAPONS) { s1->weapon = 0; } weapon = &cg_weapons[s1->weapon]; wData = &weaponData[s1->weapon]; - if ( s1->pos.trType != TR_INTERPOLATE ) - { + if (s1->pos.trType != TR_INTERPOLATE) { // calculate the axis - VectorCopy( s1->angles, cent->lerpAngles ); + VectorCopy(s1->angles, cent->lerpAngles); } - if ( s1->otherEntityNum2 && (g_vehWeaponInfo[s1->otherEntityNum2].iShotFX || g_vehWeaponInfo[s1->otherEntityNum2].iModel) ) - { + if (s1->otherEntityNum2 && (g_vehWeaponInfo[s1->otherEntityNum2].iShotFX || g_vehWeaponInfo[s1->otherEntityNum2].iModel)) { vec3_t forward; - if (s1->eFlags & EF_USE_ANGLEDELTA) - { + if (s1->eFlags & EF_USE_ANGLEDELTA) { AngleVectors(cent->currentState.angles, forward, 0, 0); - } - else - { - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( s1->pos.trDelta, forward ) == 0.0f ) - { + } else { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(s1->pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } } - // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly + // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so + // harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } CG_PlayEffectID(g_vehWeaponInfo[s1->otherEntityNum2].iShotFX, cent->lerpOrigin, forward); - if ( g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound ) - { - vec3_t velocity; - EvaluateTrajectoryDelta( ¢->currentState.pos, cg.time, velocity ); - if (cgs.sound_precache[g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound] != NULL_SFX) - { - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, cgs.sound_precache[g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound] ); + if (g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound) { + vec3_t velocity; + EvaluateTrajectoryDelta(¢->currentState.pos, cg.time, velocity); + if (cgs.sound_precache[g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound] != NULL_SFX) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, velocity, + cgs.sound_precache[g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound]); } } - //add custom model - if ( !g_vehWeaponInfo[s1->otherEntityNum2].iModel ) - { + // add custom model + if (!g_vehWeaponInfo[s1->otherEntityNum2].iModel) { return; } - } - else if ( cent->gent->alt_fire ) - { + } else if (cent->gent->alt_fire) { // add trails - if ( weapon->alt_missileTrailFunc ) - weapon->alt_missileTrailFunc( cent, weapon ); + if (weapon->alt_missileTrailFunc) + weapon->alt_missileTrailFunc(cent, weapon); // add dynamic light - if ( wData->alt_missileDlight ) - cgi_R_AddLightToScene(cent->lerpOrigin, wData->alt_missileDlight, - wData->alt_missileDlightColor[0], wData->alt_missileDlightColor[1], wData->alt_missileDlightColor[2] ); + if (wData->alt_missileDlight) + cgi_R_AddLightToScene(cent->lerpOrigin, wData->alt_missileDlight, wData->alt_missileDlightColor[0], wData->alt_missileDlightColor[1], + wData->alt_missileDlightColor[2]); // add missile sound - if ( weapon->alt_missileSound ) - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->alt_missileSound ); + if (weapon->alt_missileSound) + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->alt_missileSound); - //Don't draw something without a model - if ( weapon->alt_missileModel == NULL_HANDLE ) + // Don't draw something without a model + if (weapon->alt_missileModel == NULL_HANDLE) return; - } - else - { + } else { // add trails - if ( weapon->missileTrailFunc ) - weapon->missileTrailFunc( cent, weapon ); + if (weapon->missileTrailFunc) + weapon->missileTrailFunc(cent, weapon); // add dynamic light - if ( wData->missileDlight ) - cgi_R_AddLightToScene(cent->lerpOrigin, wData->missileDlight, - wData->missileDlightColor[0], wData->missileDlightColor[1], wData->missileDlightColor[2] ); + if (wData->missileDlight) + cgi_R_AddLightToScene(cent->lerpOrigin, wData->missileDlight, wData->missileDlightColor[0], wData->missileDlightColor[1], + wData->missileDlightColor[2]); // add missile sound - if ( weapon->missileSound ) - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->missileSound ); + if (weapon->missileSound) + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->missileSound); - //Don't draw something without a model - if ( weapon->missileModel == NULL_HANDLE ) + // Don't draw something without a model + if (weapon->missileModel == NULL_HANDLE) return; } // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); -/* -Ghoul2 Insert Start -*/ + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // flicker between two skins ent.skinNum = cg.clientFrame & 1; - ent.renderfx = /*weapon->missileRenderfx | */RF_NOSHADOW; + ent.renderfx = /*weapon->missileRenderfx | */ RF_NOSHADOW; - if ( s1->otherEntityNum2 && g_vehWeaponInfo[s1->otherEntityNum2].iModel && cgs.model_draw[g_vehWeaponInfo[s1->otherEntityNum2].iModel] != NULL_HANDLE) + if (s1->otherEntityNum2 && g_vehWeaponInfo[s1->otherEntityNum2].iModel && cgs.model_draw[g_vehWeaponInfo[s1->otherEntityNum2].iModel] != NULL_HANDLE) ent.hModel = cgs.model_draw[g_vehWeaponInfo[s1->otherEntityNum2].iModel]; - else if ( cent->gent->alt_fire ) + else if (cent->gent->alt_fire) ent.hModel = weapon->alt_missileModel; else ent.hModel = weapon->missileModel; // spin as it moves - if ( s1->apos.trType != TR_INTERPOLATE ) - { + if (s1->apos.trType != TR_INTERPOLATE) { // convert direction of travel into axis - if ( VectorNormalize2( s1->pos.trDelta, ent.axis[0] ) == 0 ) { + if (VectorNormalize2(s1->pos.trDelta, ent.axis[0]) == 0) { ent.axis[0][2] = 1; } - if ( s1->pos.trType != TR_STATIONARY ) - { - if ( s1->eFlags & EF_MISSILE_STICK ) - RotateAroundDirection( ent.axis, cg.time * 0.5f );//Did this so regular missiles don't get broken + if (s1->pos.trType != TR_STATIONARY) { + if (s1->eFlags & EF_MISSILE_STICK) + RotateAroundDirection(ent.axis, cg.time * 0.5f); // Did this so regular missiles don't get broken else - RotateAroundDirection( ent.axis, cg.time * 0.25f );//JFM:FLOAT FIX - } - else - { - if ( s1->eFlags & EF_MISSILE_STICK ) - RotateAroundDirection( ent.axis, (float)s1->pos.trTime * 0.5f ); + RotateAroundDirection(ent.axis, cg.time * 0.25f); // JFM:FLOAT FIX + } else { + if (s1->eFlags & EF_MISSILE_STICK) + RotateAroundDirection(ent.axis, (float)s1->pos.trTime * 0.5f); else - RotateAroundDirection( ent.axis, (float)s1->time ); + RotateAroundDirection(ent.axis, (float)s1->time); } - } - else - { - AnglesToAxis( cent->lerpAngles, ent.axis ); + } else { + AnglesToAxis(cent->lerpAngles, ent.axis); } // add to refresh list, possibly with quad glow - CG_AddRefEntityWithPowerups( &ent, s1->powerups, NULL ); + CG_AddRefEntityWithPowerups(&ent, s1->powerups, NULL); - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && CG_PlayerCanSeeCent( cent ) ) - {//so player can see dark missiles/explosives - if ( s1->weapon == WP_THERMAL - || s1->weapon == WP_DET_PACK - || s1->weapon == WP_TRIP_MINE - || (s1->eFlags&EF_FORCE_VISIBLE) ) - {//really, we only need to do this for things like thermals, detpacks and tripmines, no? - CG_AddForceSightShell( &ent, cent ); + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + CG_PlayerCanSeeCent(cent)) { // so player can see dark missiles/explosives + if (s1->weapon == WP_THERMAL || s1->weapon == WP_DET_PACK || s1->weapon == WP_TRIP_MINE || + (s1->eFlags & EF_FORCE_VISIBLE)) { // really, we only need to do this for things like thermals, detpacks and tripmines, no? + CG_AddForceSightShell(&ent, cent); } } } @@ -1287,121 +1089,107 @@ CG_Mover =============== */ -#define DOOR_OPENING 1 -#define DOOR_CLOSING 2 -#define DOOR_OPEN 3 -#define DOOR_CLOSED 4 +#define DOOR_OPENING 1 +#define DOOR_CLOSING 2 +#define DOOR_OPEN 3 +#define DOOR_CLOSED 4 -static void CG_Mover( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Mover(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - //FIXME: why are these always 0, 0, 0???! - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); - AnglesToAxis( cent->lerpAngles, ent.axis ); -/* -Ghoul2 Insert Start -*/ + memset(&ent, 0, sizeof(ent)); + // FIXME: why are these always 0, 0, 0???! + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + AnglesToAxis(cent->lerpAngles, ent.axis); + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ ent.renderfx = RF_NOSHADOW; // flicker between two skins (FIXME?) - ent.skinNum = ( cg.time >> 6 ) & 1; + ent.skinNum = (cg.time >> 6) & 1; // get the model, either as a bmodel or a modelindex - if ( s1->solid == SOLID_BMODEL ) { + if (s1->solid == SOLID_BMODEL) { ent.hModel = cgs.inlineDrawModel[s1->modelindex]; } else { ent.hModel = cgs.model_draw[s1->modelindex]; } // If there isn't an hModel for this mover, an RGB axis model will get drawn. - if ( !ent.hModel ) - { + if (!ent.hModel) { return; } - if ( cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM ) - { + if (cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM) { // by setting the shader time to the current time, we can force an animating shader to not animate ent.shaderTime = cg.time * 0.001f; } // add the secondary model - if ( s1->solid == SOLID_BMODEL && s1->modelindex2 ) - { -// vec3_t org; - if ( !(s1->eFlags & EF_NODRAW) ) - { + if (s1->solid == SOLID_BMODEL && s1->modelindex2) { + // vec3_t org; + if (!(s1->eFlags & EF_NODRAW)) { // add to refresh list - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); } -/* // Um, this does not interpolate nicely? Not sure why it was here.... - VectorAdd(cent->gent->absmin, cent->gent->absmax, org); - VectorScale(org, 0.5, org); - VectorCopy( org, ent.origin); - VectorCopy( org, ent.oldorigin); -*/ - if ( !VectorCompare( vec3_origin, cent->gent->modelAngles ) ) - {//we have a rotational offset for the model for this brush + /* // Um, this does not interpolate nicely? Not sure why it was here.... + VectorAdd(cent->gent->absmin, cent->gent->absmax, org); + VectorScale(org, 0.5, org); + VectorCopy( org, ent.origin); + VectorCopy( org, ent.oldorigin); + */ + if (!VectorCompare(vec3_origin, cent->gent->modelAngles)) { // we have a rotational offset for the model for this brush vec3_t modelAngles; - VectorAdd( cent->lerpAngles, cent->gent->modelAngles, modelAngles ); - AnglesToAxis( modelAngles, ent.axis ); + VectorAdd(cent->lerpAngles, cent->gent->modelAngles, modelAngles); + AnglesToAxis(modelAngles, ent.axis); } ent.hModel = cgs.model_draw[s1->modelindex2]; } // I changed it to always do it because nodraw seemed like it should actually do what it says. Be aware that if you change this, // the movers for the shooting gallery on doom_detention will break. - if ( (s1->eFlags & EF_NODRAW) ) - { + if ((s1->eFlags & EF_NODRAW)) { return; } - //fall through and render the hModel or... + // fall through and render the hModel or... - //We're a normal model being moved, animate our model + // We're a normal model being moved, animate our model ent.skinNum = 0; - if ( s1->eFlags & EF_ANIM_ONCE ) - {//FIXME: needs to anim at once per 100 ms + if (s1->eFlags & EF_ANIM_ONCE) { // FIXME: needs to anim at once per 100 ms ent.frame = cent->gent->s.frame; - ent.renderfx|=RF_CAP_FRAMES; - } - else if ( s1->eFlags & EF_ANIM_ALLFAST ) - { + ent.renderfx |= RF_CAP_FRAMES; + } else if (s1->eFlags & EF_ANIM_ALLFAST) { ent.frame = (cg.time / 100); - ent.renderfx|=RF_WRAP_FRAMES; - } - else - { + ent.renderfx |= RF_WRAP_FRAMES; + } else { ent.frame = s1->frame; } - if ( s1->eFlags & EF_SHADER_ANIM ) - { - ent.renderfx|=RF_SETANIMINDEX; + if (s1->eFlags & EF_SHADER_ANIM) { + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - //ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames + // ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames } // add to refresh list - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && (s1->eFlags&EF_FORCE_VISIBLE) ) - {//so player can see func_breakables - CG_AddForceSightShell( &ent, cent ); + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + (s1->eFlags & EF_FORCE_VISIBLE)) { // so player can see func_breakables + CG_AddForceSightShell(&ent, cent); } } @@ -1412,51 +1200,44 @@ CG_Beam Also called as an event =============== */ -void CG_Beam( centity_t *cent, int color ) { - refEntity_t ent; - entityState_t *s1; +void CG_Beam(centity_t *cent, int color) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( s1->pos.trBase, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - AxisClear( ent.axis ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(s1->pos.trBase, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + AxisClear(ent.axis); ent.reType = RT_BEAM; ent.skinNum = color; ent.renderfx = RF_NOSHADOW; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // add to refresh list cgi_R_AddRefEntityToScene(&ent); } -static vec2_t st[] = -{ - { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } -}; +static vec2_t st[] = {{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}}; -void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) -{ - vec3_t point[4], rot={0,0,0}; - int vec[3]; - int axis, i; +void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha) { + vec3_t point[4], rot = {0, 0, 0}; + int vec[3]; + int axis, i; - for ( axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++ ) - { - for ( i = 0; i < 3; i++ ) - { - if ( vec[i] > 2 ) - { + for (axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++) { + for (i = 0; i < 3; i++) { + if (vec[i] > 2) { vec[i] = 0; } } @@ -1476,31 +1257,23 @@ void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) //- face point[0][vec[0]] = point[1][vec[0]] = point[2][vec[0]] = point[3][vec[0]] = mins[vec[0]]; - FX_AddPoly( point, st, 4, NULL, NULL, alpha, alpha, 0.0f, - color, color, 0.0f, rot, 0.0f, 0.0f, - 100, cgs.media.solidWhiteShader, 0 ); + FX_AddPoly(point, st, 4, NULL, NULL, alpha, alpha, 0.0f, color, color, 0.0f, rot, 0.0f, 0.0f, 100, cgs.media.solidWhiteShader, 0); //+ face point[0][vec[0]] = point[1][vec[0]] = point[2][vec[0]] = point[3][vec[0]] = maxs[vec[0]]; - FX_AddPoly( point, st, 4, NULL, NULL, alpha, alpha, 0.0f, - color, color, 0.0f, rot, 0.0f, 0.0f, - 100, cgs.media.solidWhiteShader, 0 ); + FX_AddPoly(point, st, 4, NULL, NULL, alpha, alpha, 0.0f, color, color, 0.0f, rot, 0.0f, 0.0f, 100, cgs.media.solidWhiteShader, 0); } } -void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ) -{ - vec3_t point1, point2, point3, point4; - int vec[3]; - int axis, i; +void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha) { + vec3_t point1, point2, point3, point4; + int vec[3]; + int axis, i; - for ( axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++ ) - { - for ( i = 0; i < 3; i++ ) - { - if ( vec[i] > 2 ) - { + for (axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++) { + for (i = 0; i < 3; i++) { + if (vec[i] > 2) { vec[i] = 0; } } @@ -1520,23 +1293,22 @@ void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, flo //- face point1[vec[0]] = point2[vec[0]] = point3[vec[0]] = point4[vec[0]] = mins[vec[0]]; - CG_TestLine( point1, point2, time, color, 1 ); - CG_TestLine( point2, point3, time, color, 1 ); - CG_TestLine( point1, point4, time, color, 1 ); - CG_TestLine( point4, point3, time, color, 1 ); + CG_TestLine(point1, point2, time, color, 1); + CG_TestLine(point2, point3, time, color, 1); + CG_TestLine(point1, point4, time, color, 1); + CG_TestLine(point4, point3, time, color, 1); //+ face point1[vec[0]] = point2[vec[0]] = point3[vec[0]] = point4[vec[0]] = maxs[vec[0]]; - CG_TestLine( point1, point2, time, color, 1 ); - CG_TestLine( point2, point3, time, color, 1 ); - CG_TestLine( point1, point4, time, color, 1 ); - CG_TestLine( point4, point1, time, color, 1 ); + CG_TestLine(point1, point2, time, color, 1); + CG_TestLine(point2, point3, time, color, 1); + CG_TestLine(point1, point4, time, color, 1); + CG_TestLine(point4, point1, time, color, 1); } } -void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) -{ +void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha) { /*FX_AddLine( start, end, 1.0f, @@ -1555,47 +1327,45 @@ void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) CG_Portal =============== */ -static void CG_Portal( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Portal(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; - //FIXME: this tends to give a bad axis[1], perhaps we - //should just do the VectorSubtraction here rather than - //on the game side. Would also allow camera to follow - //a moving target. + // FIXME: this tends to give a bad axis[1], perhaps we + // should just do the VectorSubtraction here rather than + // on the game side. Would also allow camera to follow + // a moving target. // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - ByteToDir( s1->eventParm, ent.axis[0] ); - PerpendicularVector( ent.axis[1], ent.axis[0] ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + ByteToDir(s1->eventParm, ent.axis[0]); + PerpendicularVector(ent.axis[1], ent.axis[0]); // negating this tends to get the directions like they want // we really should have a camera roll value - VectorSubtract( vec3_origin, ent.axis[1], ent.axis[1] ); + VectorSubtract(vec3_origin, ent.axis[1], ent.axis[1]); - CrossProduct( ent.axis[0], ent.axis[1], ent.axis[2] ); + CrossProduct(ent.axis[0], ent.axis[1], ent.axis[2]); ent.reType = RT_PORTALSURFACE; - ent.frame = s1->frame; // rotation speed - ent.skinNum = (int)(s1->clientNum/256.0 * 360); // roll offset + ent.frame = s1->frame; // rotation speed + ent.skinNum = (int)(s1->clientNum / 256.0 * 360); // roll offset -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert End + */ // add to refresh list cgi_R_AddRefEntityToScene(&ent); } - /* ========================= CG_AdjustPositionForMover @@ -1603,33 +1373,32 @@ CG_AdjustPositionForMover Also called by client movement prediction code ========================= */ -void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int atTime, vec3_t out ) { - centity_t *cent; - vec3_t oldOrigin, origin, deltaOrigin; -// vec3_t oldAngles, angles, deltaAngles; +void CG_AdjustPositionForMover(const vec3_t in, int moverNum, int atTime, vec3_t out) { + centity_t *cent; + vec3_t oldOrigin, origin, deltaOrigin; + // vec3_t oldAngles, angles, deltaAngles; - if ( moverNum <= 0 ) { - VectorCopy( in, out ); + if (moverNum <= 0) { + VectorCopy(in, out); return; } - cent = &cg_entities[ moverNum ]; - if ( cent->currentState.eType != ET_MOVER ) { - VectorCopy( in, out ); + cent = &cg_entities[moverNum]; + if (cent->currentState.eType != ET_MOVER) { + VectorCopy(in, out); return; } - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, oldOrigin ); -// EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, oldAngles ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, oldOrigin); + // EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, oldAngles ); - EvaluateTrajectory( ¢->currentState.pos, atTime, origin ); -// EvaluateTrajectory( ¢->currentState.apos, atTime, angles ); + EvaluateTrajectory(¢->currentState.pos, atTime, origin); + // EvaluateTrajectory( ¢->currentState.apos, atTime, angles ); - VectorSubtract( origin, oldOrigin, deltaOrigin ); -// VectorSubtract( angles, oldAngles, deltaAngles ); + VectorSubtract(origin, oldOrigin, deltaOrigin); + // VectorSubtract( angles, oldAngles, deltaAngles ); - - VectorAdd( in, deltaOrigin, out ); + VectorAdd(in, deltaOrigin, out); // FIXME: origin change when on a rotating object } @@ -1639,57 +1408,55 @@ CG_CalcEntityLerpPositions =============== */ -extern char *vtos( const vec3_t v ); +extern char *vtos(const vec3_t v); #if 1 -void CG_CalcEntityLerpPositions( centity_t *cent ) { - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE && cent->nextState ) //cent->currentState.vehicleIndex != VEHICLE_NONE ) +void CG_CalcEntityLerpPositions(centity_t *cent) { + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE && + cent->nextState) // cent->currentState.vehicleIndex != VEHICLE_NONE ) { - float f = cg.frameInterpolation; + float f = cg.frameInterpolation; - cent->currentState.vehicleAngles[0] = LerpAngle( cent->currentState.vehicleAngles[0], cent->nextState->vehicleAngles[0], f ); - cent->currentState.vehicleAngles[1] = LerpAngle( cent->currentState.vehicleAngles[1], cent->nextState->vehicleAngles[1], f ); - cent->currentState.vehicleAngles[2] = LerpAngle( cent->currentState.vehicleAngles[2], cent->nextState->vehicleAngles[2], f ); + cent->currentState.vehicleAngles[0] = LerpAngle(cent->currentState.vehicleAngles[0], cent->nextState->vehicleAngles[0], f); + cent->currentState.vehicleAngles[1] = LerpAngle(cent->currentState.vehicleAngles[1], cent->nextState->vehicleAngles[1], f); + cent->currentState.vehicleAngles[2] = LerpAngle(cent->currentState.vehicleAngles[2], cent->nextState->vehicleAngles[2], f); } - if ( cent->currentState.number == cg.snap->ps.clientNum) - { + if (cent->currentState.number == cg.snap->ps.clientNum) { // if the player, take position from prediction - VectorCopy( cg.predicted_player_state.origin, cent->lerpOrigin ); - VectorCopy( cg.predicted_player_state.viewangles, cent->lerpAngles ); -/* -Ghoul2 Insert Start -*/ -// LerpBoneAngleOverrides(cent); -/* -Ghoul2 Insert End -*/ + VectorCopy(cg.predicted_player_state.origin, cent->lerpOrigin); + VectorCopy(cg.predicted_player_state.viewangles, cent->lerpAngles); + /* + Ghoul2 Insert Start + */ + // LerpBoneAngleOverrides(cent); + /* + Ghoul2 Insert End + */ return; } - //FIXME: prediction on clients in timescale results in jerky positional translation - if ( cent->interpolate ) - { + // FIXME: prediction on clients in timescale results in jerky positional translation + if (cent->interpolate) { // if the entity has a valid next state, interpolate a value between the frames // unless it is a mover with a known start and stop - vec3_t current, next; - float f; + vec3_t current, next; + float f; // it would be an internal error to find an entity that interpolates without // a snapshot ahead of the current one - if ( cg.nextSnap == NULL ) { - CG_Error( "CG_AddCEntity: cg.nextSnap == NULL" ); + if (cg.nextSnap == NULL) { + CG_Error("CG_AddCEntity: cg.nextSnap == NULL"); } f = cg.frameInterpolation; - if ( cent->currentState.apos.trType == TR_INTERPOLATE && cent->nextState ) - { - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState->apos, cg.nextSnap->serverTime, next ); + if (cent->currentState.apos.trType == TR_INTERPOLATE && cent->nextState) { + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState->apos, cg.nextSnap->serverTime, next); - cent->lerpAngles[0] = LerpAngle( current[0], next[0], f ); - cent->lerpAngles[1] = LerpAngle( current[1], next[1], f ); - cent->lerpAngles[2] = LerpAngle( current[2], next[2], f ); + cent->lerpAngles[0] = LerpAngle(current[0], next[0], f); + cent->lerpAngles[1] = LerpAngle(current[1], next[1], f); + cent->lerpAngles[2] = LerpAngle(current[2], next[2], f); /* if(cent->gent && cent->currentState.clientNum != 0 && !VectorCompare(current, next)) @@ -1697,9 +1464,9 @@ Ghoul2 Insert End Com_Printf("%s last/next/lerp apos %s/%s/%s, f = %4.2f\n", cent->gent->script_targetname, vtos(current), vtos(next), vtos(cent->lerpAngles), f); } */ - /* - Ghoul2 Insert Start - */ + /* + Ghoul2 Insert Start + */ // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent /* if (cent->gent->ghoul2.size()) @@ -1707,20 +1474,19 @@ Ghoul2 Insert End LerpBoneAngleOverrides(cent); } */ - /* - Ghoul2 Insert End - */ + /* + Ghoul2 Insert End + */ } - if ( cent->currentState.pos.trType == TR_INTERPOLATE && cent->nextState ) - { + if (cent->currentState.pos.trType == TR_INTERPOLATE && cent->nextState) { // this will linearize a sine or parabolic curve, but it is important // to not extrapolate player positions if more recent data is available - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState->pos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState->pos, cg.nextSnap->serverTime, next); - cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] ); - cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] ); - cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] ); + cent->lerpOrigin[0] = current[0] + f * (next[0] - current[0]); + cent->lerpOrigin[1] = current[1] + f * (next[1] - current[1]); + cent->lerpOrigin[2] = current[2] + f * (next[2] - current[2]); /* if ( cent->gent && cent->currentState.clientNum != 0 ) @@ -1728,18 +1494,14 @@ Ghoul2 Insert End Com_Printf("%s last/next/lerp pos %s/%s/%s, f = %4.2f\n", cent->gent->script_targetname, vtos(current), vtos(next), vtos(cent->lerpOrigin), f); } */ - return;//FIXME: should this be outside this if? + return; // FIXME: should this be outside this if? } - } - else - { - if ( cent->currentState.apos.trType == TR_INTERPOLATE ) - { - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, cent->lerpAngles ); + } else { + if (cent->currentState.apos.trType == TR_INTERPOLATE) { + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, cent->lerpAngles); } - if ( cent->currentState.pos.trType == TR_INTERPOLATE ) - { - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); + if (cent->currentState.pos.trType == TR_INTERPOLATE) { + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); /* if(cent->gent && cent->currentState.clientNum != 0 ) { @@ -1758,115 +1520,88 @@ Ghoul2 Insert End { gentity_t *ent = &g_entities[cent->currentState.number]; - if ( ent && ent->inuse) - { - if ( ent->s.eFlags & EF_BLOCKED_MOVER || ent->s.pos.trType == TR_STATIONARY ) - {//this mover has stopped moving and is going to wig out if we predict it - //based on last frame's info- cut across the network and use the currentOrigin - VectorCopy( ent->currentOrigin, cent->lerpOrigin ); + if (ent && ent->inuse) { + if (ent->s.eFlags & EF_BLOCKED_MOVER || + ent->s.pos.trType == TR_STATIONARY) { // this mover has stopped moving and is going to wig out if we predict it + // based on last frame's info- cut across the network and use the currentOrigin + VectorCopy(ent->currentOrigin, cent->lerpOrigin); posData = NULL; - } - else - { + } else { posData = &ent->s.pos; } } } - if ( posData ) - { - EvaluateTrajectory( posData, cg.time, cent->lerpOrigin ); + if (posData) { + EvaluateTrajectory(posData, cg.time, cent->lerpOrigin); } // FIXME: this will stomp an apos trType of TR_INTERPOLATE!! - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); // adjust for riding a mover - CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin ); -/* -Ghoul2 Insert Start -*/ - // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent + CG_AdjustPositionForMover(cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin); + /* + Ghoul2 Insert Start + */ + // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent /* if (cent->gent->ghoul2.size()) { LerpBoneAngleOverrides(cent); } */ -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // FIXME: perform general error decay? } #else -void CG_CalcEntityLerpPositions( centity_t *cent ) -{ - if ( cent->currentState.number == cg.snap->ps.clientNum) - { +void CG_CalcEntityLerpPositions(centity_t *cent) { + if (cent->currentState.number == cg.snap->ps.clientNum) { // if the player, take position from prediction - VectorCopy( cg.predicted_player_state.origin, cent->lerpOrigin ); - VectorCopy( cg.predicted_player_state.viewangles, cent->lerpAngles ); -OutputDebugString(va("b=(%6.2f,%6.2f,%6.2f)\n",cent->lerpOrigin[0],cent->lerpOrigin[1],cent->lerpOrigin[2])); + VectorCopy(cg.predicted_player_state.origin, cent->lerpOrigin); + VectorCopy(cg.predicted_player_state.viewangles, cent->lerpAngles); + OutputDebugString(va("b=(%6.2f,%6.2f,%6.2f)\n", cent->lerpOrigin[0], cent->lerpOrigin[1], cent->lerpOrigin[2])); return; } - -if (cent->currentState.number != cg.snap->ps.clientNum&¢->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE) -{ - if (cent->interpolate) - { -OutputDebugString(va("[%3d] interp %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", - cent->currentState.number, - cg.frameInterpolation, - cg.time, - cg.snap->serverTime, - cg.nextSnap->serverTime, - cent->currentState.pos.trBase[0], - cent->nextState.pos.trBase[0])); - } - else - { -OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", - cent->currentState.number, - cg.frameInterpolation, - cg.time, - cg.snap->serverTime, - 0, - cent->currentState.pos.trBase[0], - 0.0f)); + if (cent->currentState.number != cg.snap->ps.clientNum && cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE) { + if (cent->interpolate) { + OutputDebugString(va("[%3d] interp %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", cent->currentState.number, cg.frameInterpolation, + cg.time, cg.snap->serverTime, cg.nextSnap->serverTime, cent->currentState.pos.trBase[0], cent->nextState.pos.trBase[0])); + } else { + OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", cent->currentState.number, cg.frameInterpolation, + cg.time, cg.snap->serverTime, 0, cent->currentState.pos.trBase[0], 0.0f)); + } } -} - //FIXME: prediction on clients in timescale results in jerky positional translation - if (cent->interpolate && - (cent->currentState.number == cg.snap->ps.clientNum || - cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE ) ) - { - vec3_t current, next; - float f; + // FIXME: prediction on clients in timescale results in jerky positional translation + if (cent->interpolate && (cent->currentState.number == cg.snap->ps.clientNum || cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE)) { + vec3_t current, next; + float f; // it would be an internal error to find an entity that interpolates without // a snapshot ahead of the current one - if ( cg.nextSnap == NULL ) - { - CG_Error( "CG_AddCEntity: cg.nextSnap == NULL" ); + if (cg.nextSnap == NULL) { + CG_Error("CG_AddCEntity: cg.nextSnap == NULL"); } f = cg.frameInterpolation; - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.apos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.apos, cg.nextSnap->serverTime, next); - cent->lerpAngles[0] = LerpAngle( current[0], next[0], f ); - cent->lerpAngles[1] = LerpAngle( current[1], next[1], f ); - cent->lerpAngles[2] = LerpAngle( current[2], next[2], f ); + cent->lerpAngles[0] = LerpAngle(current[0], next[0], f); + cent->lerpAngles[1] = LerpAngle(current[1], next[1], f); + cent->lerpAngles[2] = LerpAngle(current[2], next[2], f); - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.pos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.pos, cg.nextSnap->serverTime, next); - cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] ); - cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] ); - cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] ); + cent->lerpOrigin[0] = current[0] + f * (next[0] - current[0]); + cent->lerpOrigin[1] = current[1] + f * (next[1] - current[1]); + cent->lerpOrigin[2] = current[2] + f * (next[2] - current[2]); return; } // just use the current frame and evaluate as best we can @@ -1874,29 +1609,24 @@ OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f { gentity_t *ent = &g_entities[cent->currentState.number]; - if ( ent && ent->inuse) - { - if ( ent->s.eFlags & EF_BLOCKED_MOVER || ent->s.pos.trType == TR_STATIONARY ) - {//this mover has stopped moving and is going to wig out if we predict it - //based on last frame's info- cut across the network and use the currentOrigin - VectorCopy( ent->currentOrigin, cent->lerpOrigin ); + if (ent && ent->inuse) { + if (ent->s.eFlags & EF_BLOCKED_MOVER || + ent->s.pos.trType == TR_STATIONARY) { // this mover has stopped moving and is going to wig out if we predict it + // based on last frame's info- cut across the network and use the currentOrigin + VectorCopy(ent->currentOrigin, cent->lerpOrigin); posData = NULL; - } - else - { + } else { posData = &ent->s.pos; - EvaluateTrajectory(&ent->s.pos,cg.time, cent->lerpOrigin ); + EvaluateTrajectory(&ent->s.pos, cg.time, cent->lerpOrigin); } - } - else - { - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); + } else { + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); } } - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); // adjust for riding a mover - CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin ); + CG_AdjustPositionForMover(cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin); } #endif /* @@ -1905,9 +1635,8 @@ CG_AddLocalSet =============== */ -static void CG_AddLocalSet( centity_t *cent ) -{ - cent->gent->setTime = cgi_S_AddLocalSet( cent->gent->soundSet, cg.refdef.vieworg, cent->lerpOrigin, cent->gent->s.number, cent->gent->setTime ); +static void CG_AddLocalSet(centity_t *cent) { + cent->gent->setTime = cgi_S_AddLocalSet(cent->gent->soundSet, cg.refdef.vieworg, cent->lerpOrigin, cent->gent->s.number, cent->gent->setTime); } /* @@ -1916,58 +1645,46 @@ CAS_GetBModelSound ------------------------- */ -sfxHandle_t CAS_GetBModelSound( const char *name, int stage ) -{ - return cgi_AS_GetBModelSound( name, stage ); -} +sfxHandle_t CAS_GetBModelSound(const char *name, int stage) { return cgi_AS_GetBModelSound(name, stage); } -void CG_DLightThink ( centity_t *cent ) -{ - if(cent->gent) - { - float tDelta = cg.time - cent->gent->painDebounceTime; - float percentage = ( tDelta/((float)cent->gent->speed) ); - vec3_t org; - vec4_t currentRGBA; - gentity_t *owner = NULL; - int i; - - if ( percentage >= 1.0f ) - {//We hit the end +void CG_DLightThink(centity_t *cent) { + if (cent->gent) { + float tDelta = cg.time - cent->gent->painDebounceTime; + float percentage = (tDelta / ((float)cent->gent->speed)); + vec3_t org; + vec4_t currentRGBA; + gentity_t *owner = NULL; + int i; + + if (percentage >= 1.0f) { // We hit the end percentage = 1.0f; - switch( cent->gent->pushDebounceTime ) - { - case 0://Fading from start to final - if ( cent->gent->spawnflags & 8 ) - {//PULSER - if ( tDelta - cent->gent->speed - cent->gent->wait >= 0 ) - {//Time to start fading down + switch (cent->gent->pushDebounceTime) { + case 0: // Fading from start to final + if (cent->gent->spawnflags & 8) { // PULSER + if (tDelta - cent->gent->speed - cent->gent->wait >= 0) { // Time to start fading down cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 1; percentage = 0.0f; } - } - else - {//Stick on startRGBA + } else { // Stick on startRGBA percentage = 0.0f; } break; - case 1://Fading from final to start - if ( tDelta - cent->gent->speed - cent->gent->radius >= 0 ) - {//Time to start fading up + case 1: // Fading from final to start + if (tDelta - cent->gent->speed - cent->gent->radius >= 0) { // Time to start fading up cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 0; percentage = 0.0f; } break; - case 2://Fading from 0 intensity to start intensity - //Time to start fading from start to final + case 2: // Fading from 0 intensity to start intensity + // Time to start fading from start to final cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 0; percentage = 0.0f; break; - case 3://Fading from current intensity to 0 intensity - //Time to turn off + case 3: // Fading from current intensity to 0 intensity + // Time to turn off cent->gent->misc_dlight_active = qfalse; cent->gent->e_clThinkFunc = clThinkF_NULL; cent->gent->s.eType = ET_GENERAL; @@ -1979,30 +1696,25 @@ void CG_DLightThink ( centity_t *cent ) } } - switch( cent->gent->pushDebounceTime ) - { - case 0://Fading from start to final - for ( i = 0; i < 4; i++ ) - { - currentRGBA[i] = cent->gent->startRGBA[i] + ( (cent->gent->finalRGBA[i] - cent->gent->startRGBA[i]) * percentage ); + switch (cent->gent->pushDebounceTime) { + case 0: // Fading from start to final + for (i = 0; i < 4; i++) { + currentRGBA[i] = cent->gent->startRGBA[i] + ((cent->gent->finalRGBA[i] - cent->gent->startRGBA[i]) * percentage); } break; - case 1://Fading from final to start - for ( i = 0; i < 4; i++ ) - { - currentRGBA[i] = cent->gent->finalRGBA[i] + ( (cent->gent->startRGBA[i] - cent->gent->finalRGBA[i]) * percentage ); + case 1: // Fading from final to start + for (i = 0; i < 4; i++) { + currentRGBA[i] = cent->gent->finalRGBA[i] + ((cent->gent->startRGBA[i] - cent->gent->finalRGBA[i]) * percentage); } break; - case 2://Fading from 0 intensity to start - for ( i = 0; i < 3; i++ ) - { + case 2: // Fading from 0 intensity to start + for (i = 0; i < 3; i++) { currentRGBA[i] = cent->gent->startRGBA[i]; } currentRGBA[3] = cent->gent->startRGBA[3] * percentage; break; - case 3://Fading from current intensity to 0 - for ( i = 0; i < 3; i++ ) - {//FIXME: use last + case 3: // Fading from current intensity to 0 + for (i = 0; i < 3; i++) { // FIXME: use last currentRGBA[i] = cent->gent->startRGBA[i]; } currentRGBA[3] = cent->gent->startRGBA[3] - (cent->gent->startRGBA[3] * percentage); @@ -2012,48 +1724,36 @@ void CG_DLightThink ( centity_t *cent ) break; } - if ( cent->gent->owner ) - { + if (cent->gent->owner) { owner = cent->gent->owner; - } - else - { + } else { owner = cent->gent; } - if ( owner->s.pos.trType == TR_INTERPOLATE ) - { - VectorCopy( cg_entities[owner->s.number].lerpOrigin, org ); - } - else - { - VectorCopy( owner->currentOrigin, org ); + if (owner->s.pos.trType == TR_INTERPOLATE) { + VectorCopy(cg_entities[owner->s.number].lerpOrigin, org); + } else { + VectorCopy(owner->currentOrigin, org); } - cgi_R_AddLightToScene(org, currentRGBA[3]*10, currentRGBA[0], currentRGBA[1], currentRGBA[2] ); + cgi_R_AddLightToScene(org, currentRGBA[3] * 10, currentRGBA[0], currentRGBA[1], currentRGBA[2]); } } -void CG_Limb ( centity_t *cent ) -{//first time we're drawn, remove us from the owner ent - if ( cent->gent && cent->gent->owner && cent->gent->owner->ghoul2.size() ) - { - gentity_t *owner = cent->gent->owner; - if ( cent->gent->aimDebounceTime ) - {//done with dismemberment, just waiting to mark owner dismemberable again - if ( cent->gent->aimDebounceTime > cg.time ) - {//still waiting +void CG_Limb(centity_t *cent) { // first time we're drawn, remove us from the owner ent + if (cent->gent && cent->gent->owner && cent->gent->owner->ghoul2.size()) { + gentity_t *owner = cent->gent->owner; + if (cent->gent->aimDebounceTime) { // done with dismemberment, just waiting to mark owner dismemberable again + if (cent->gent->aimDebounceTime > cg.time) { // still waiting return; } - //done! + // done! owner->client->dismembered = false; - //done! + // done! cent->gent->e_clThinkFunc = clThinkF_NULL; - } - else - { -extern cvar_t *g_saberRealisticCombat; - //3) turn off w/descendants that surf in original model + } else { + extern cvar_t *g_saberRealisticCombat; + // 3) turn off w/descendants that surf in original model #if 0 if ( cent->gent->target )//stubTagName ) {//add smoke to cap surf, spawn effect @@ -2068,251 +1768,197 @@ extern cvar_t *g_saberRealisticCombat; } } #endif - if ( cent->gent->target2 )//limbName - {//turn the limb off - //NOTE: MUST use G2SURFACEFLAG_NODESCENDANTS - gi.G2API_SetSurfaceOnOff( &owner->ghoul2[owner->playerModel], cent->gent->target2, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS + if (cent->gent->target2) // limbName + { // turn the limb off + // NOTE: MUST use G2SURFACEFLAG_NODESCENDANTS + gi.G2API_SetSurfaceOnOff(&owner->ghoul2[owner->playerModel], cent->gent->target2, 0x00000100); // G2SURFACEFLAG_NODESCENDANTS } - if ( cent->gent->target3 )//stubCapName ) - {//turn on caps - gi.G2API_SetSurfaceOnOff( &owner->ghoul2[owner->playerModel], cent->gent->target3, 0 ); + if (cent->gent->target3) // stubCapName ) + { // turn on caps + gi.G2API_SetSurfaceOnOff(&owner->ghoul2[owner->playerModel], cent->gent->target3, 0); } - if ( owner->weaponModel[0] > 0 ) - {//the corpse hasn't dropped their weapon - if ( cent->gent->count == BOTH_DISMEMBER_RARM || cent->gent->count == BOTH_DISMEMBER_TORSO1 )//&& ent->s.weapon == WP_SABER && ent->weaponModel[0] != -1 ) - {//FIXME: is this first check needed with this lower one? - gi.G2API_RemoveGhoul2Model( owner->ghoul2, owner->weaponModel[0] ); + if (owner->weaponModel[0] > 0) { // the corpse hasn't dropped their weapon + if (cent->gent->count == BOTH_DISMEMBER_RARM || + cent->gent->count == BOTH_DISMEMBER_TORSO1) //&& ent->s.weapon == WP_SABER && ent->weaponModel[0] != -1 ) + { // FIXME: is this first check needed with this lower one? + gi.G2API_RemoveGhoul2Model(owner->ghoul2, owner->weaponModel[0]); owner->weaponModel[0] = -1; } } - if ( owner->client->NPC_class == CLASS_PROTOCOL - || debug_subdivision->integer - || g_saberRealisticCombat->integer ) - { - //wait 100ms before allowing owner to be dismembered again + if (owner->client->NPC_class == CLASS_PROTOCOL || debug_subdivision->integer || g_saberRealisticCombat->integer) { + // wait 100ms before allowing owner to be dismembered again cent->gent->aimDebounceTime = cg.time + 100; return; - } - else - { - //done! + } else { + // done! cent->gent->e_clThinkFunc = clThinkF_NULL; } } } } -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -qboolean MatrixMode = qfalse; -extern cvar_t *g_skippingcin; -void CG_MatrixEffect ( centity_t *cent ) -{ - float MATRIX_EFFECT_TIME = 1000.0f; - if ( (cent->currentState.boltInfo&MEF_MULTI_SPIN) ) - {//multiple spins - if ( cent->currentState.time2 > 0 ) - {//with a custom amount of time per spin +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +qboolean MatrixMode = qfalse; +extern cvar_t *g_skippingcin; +void CG_MatrixEffect(centity_t *cent) { + float MATRIX_EFFECT_TIME = 1000.0f; + if ((cent->currentState.boltInfo & MEF_MULTI_SPIN)) { // multiple spins + if (cent->currentState.time2 > 0) { // with a custom amount of time per spin MATRIX_EFFECT_TIME = cent->currentState.time2; } - } - else - { - if ( cent->currentState.eventParm - && cent->currentState.eventParm != MATRIX_EFFECT_TIME ) - {//not a falling multi-spin, so stretch out the effect over the whole desired length (or: condenses it, too) + } else { + if (cent->currentState.eventParm && + cent->currentState.eventParm != + MATRIX_EFFECT_TIME) { // not a falling multi-spin, so stretch out the effect over the whole desired length (or: condenses it, too) MATRIX_EFFECT_TIME = cent->currentState.eventParm; } } - //VectorCopy( cent->lerpOrigin, cg.refdef.vieworg ); + // VectorCopy( cent->lerpOrigin, cg.refdef.vieworg ); float totalElapsedTime = (float)(cg.time - cent->currentState.time); float elapsedTime = totalElapsedTime; - bool stopEffect = ((totalElapsedTime > cent->currentState.eventParm) || cg.missionStatusShow || in_camera); + bool stopEffect = ((totalElapsedTime > cent->currentState.eventParm) || cg.missionStatusShow || in_camera); - if (!stopEffect && (cent->currentState.boltInfo&MEF_HIT_GROUND_STOP) && g_entities[cent->currentState.otherEntityNum].client) - { - if (g_entities[cent->currentState.otherEntityNum].client->ps.groundEntityNum!=ENTITYNUM_NONE) - { + if (!stopEffect && (cent->currentState.boltInfo & MEF_HIT_GROUND_STOP) && g_entities[cent->currentState.otherEntityNum].client) { + if (g_entities[cent->currentState.otherEntityNum].client->ps.groundEntityNum != ENTITYNUM_NONE) { stopEffect = true; - } - else if (g_entities[cent->currentState.otherEntityNum].client->NPC_class == CLASS_VEHICLE) - { - Vehicle_t* pVeh = g_entities[cent->currentState.otherEntityNum].m_pVehicle; - if (pVeh && !(pVeh->m_ulFlags&VEH_FLYING)) - { + } else if (g_entities[cent->currentState.otherEntityNum].client->NPC_class == CLASS_VEHICLE) { + Vehicle_t *pVeh = g_entities[cent->currentState.otherEntityNum].m_pVehicle; + if (pVeh && !(pVeh->m_ulFlags & VEH_FLYING)) { stopEffect = true; } } } - if (!stopEffect && (cent->currentState.boltInfo&MEF_LOOK_AT_ENEMY)) - { - if (!g_entities[cent->currentState.otherEntityNum].lastEnemy || - !g_entities[cent->currentState.otherEntityNum].lastEnemy->inuse) - { + if (!stopEffect && (cent->currentState.boltInfo & MEF_LOOK_AT_ENEMY)) { + if (!g_entities[cent->currentState.otherEntityNum].lastEnemy || !g_entities[cent->currentState.otherEntityNum].lastEnemy->inuse) { stopEffect = true; } } - if (stopEffect) - {//time is up or this is a falling spin and they hit the ground or mission end screen is up - cg.overrides.active &= ~(/*CG_OVERRIDE_3RD_PERSON_ENT|*/CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_ANG|CG_OVERRIDE_3RD_PERSON_POF); - //cg.overrides.thirdPersonEntity = 0; + if (stopEffect) { // time is up or this is a falling spin and they hit the ground or mission end screen is up + cg.overrides.active &= ~(/*CG_OVERRIDE_3RD_PERSON_ENT|*/ CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_ANG | CG_OVERRIDE_3RD_PERSON_POF); + // cg.overrides.thirdPersonEntity = 0; cg.overrides.thirdPersonAngle = 0; cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonRange = 0; - if ( g_skippingcin->integer ) - {//skipping? don't mess with timescale + if (g_skippingcin->integer) { // skipping? don't mess with timescale /* if ( g_timescale->integer < 100 ) {//something messed up timescale, reset it? cgi_Cvar_Set( "timescale", "100" ); } */ - } - else - {//set it back to 1 - cgi_Cvar_Set( "timescale", "1.0" ); + } else { // set it back to 1 + cgi_Cvar_Set("timescale", "1.0"); } MatrixMode = qfalse; cent->gent->e_clThinkFunc = clThinkF_NULL; cent->gent->e_ThinkFunc = thinkF_G_FreeEntity; cent->gent->nextthink = cg.time + 500; return; - } - else - { - while ( elapsedTime > MATRIX_EFFECT_TIME ) - { + } else { + while (elapsedTime > MATRIX_EFFECT_TIME) { elapsedTime -= MATRIX_EFFECT_TIME; } } MatrixMode = qtrue; - //FIXME: move the position towards them and back? - //cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ENT; - //cg.overrides.thirdPersonEntity = cent->currentState.otherEntityNum; + // FIXME: move the position towards them and back? + // cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ENT; + // cg.overrides.thirdPersonEntity = cent->currentState.otherEntityNum; - if (cent->currentState.boltInfo&MEF_LOOK_AT_ENEMY) - { - vec3_t toEnemy; - vec3_t toEnemyAngles; + if (cent->currentState.boltInfo & MEF_LOOK_AT_ENEMY) { + vec3_t toEnemy; + vec3_t toEnemyAngles; VectorCopy(cg_entities[g_entities[cent->currentState.otherEntityNum].lastEnemy->s.number].lerpOrigin, toEnemy); -// CG_DrawEdge(cg_entities[cent->currentState.otherEntityNum].lerpOrigin, toEnemy, EDGE_NORMAL); + // CG_DrawEdge(cg_entities[cent->currentState.otherEntityNum].lerpOrigin, toEnemy, EDGE_NORMAL); VectorSubtract(cg_entities[cent->currentState.otherEntityNum].lerpOrigin, toEnemy, toEnemy); vectoangles(toEnemy, toEnemyAngles); + cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; + cg.overrides.thirdPersonAngle = toEnemyAngles[1] - cg_entities[cent->currentState.otherEntityNum].lerpAngles[1] + 145.0f; + cg.overrides.thirdPersonAngle = AngleNormalize180(cg.overrides.thirdPersonAngle); - cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = - toEnemyAngles[1] - - cg_entities[cent->currentState.otherEntityNum].lerpAngles[1] + - 145.0f; - cg.overrides.thirdPersonAngle = AngleNormalize180(cg.overrides.thirdPersonAngle); - - float MATRIX_EFFECT_TIME_HALF = MATRIX_EFFECT_TIME/2.0f; - float X = 1.0f; - if (elapsedTime>MATRIX_EFFECT_TIME_HALF) - { - X -= ((elapsedTime - MATRIX_EFFECT_TIME_HALF)/MATRIX_EFFECT_TIME_HALF); + float MATRIX_EFFECT_TIME_HALF = MATRIX_EFFECT_TIME / 2.0f; + float X = 1.0f; + if (elapsedTime > MATRIX_EFFECT_TIME_HALF) { + X -= ((elapsedTime - MATRIX_EFFECT_TIME_HALF) / MATRIX_EFFECT_TIME_HALF); } - cg.overrides.thirdPersonAngle *= X; + cg.overrides.thirdPersonAngle *= X; - // gi.Printf("%f\n", cg.overrides.thirdPersonAngle); - cg.overrides.thirdPersonPitchOffset = 0.0f; - cg.overrides.thirdPersonRange = cg_thirdPersonRange.value * 3.0f; + // gi.Printf("%f\n", cg.overrides.thirdPersonAngle); + cg.overrides.thirdPersonPitchOffset = 0.0f; + cg.overrides.thirdPersonRange = cg_thirdPersonRange.value * 3.0f; } - if ( !(cent->currentState.boltInfo&MEF_NO_SPIN) ) - {//rotate around them - //rotate + if (!(cent->currentState.boltInfo & MEF_NO_SPIN)) { // rotate around them + // rotate cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = 360.0f*elapsedTime/MATRIX_EFFECT_TIME; - if ( (cent->currentState.boltInfo&MEF_REVERSE_SPIN) ) - { + cg.overrides.thirdPersonAngle = 360.0f * elapsedTime / MATRIX_EFFECT_TIME; + if ((cent->currentState.boltInfo & MEF_REVERSE_SPIN)) { cg.overrides.thirdPersonAngle *= -1; } } - //do all the slowdown and vert bob stuff - if ( cent->currentState.angles2[0] ) - { - cgi_Cvar_Set( "timescale", va("%4.2f",cent->currentState.angles2[0]) ); - } - else if ( !(cent->currentState.boltInfo&MEF_NO_TIMESCALE) ) - {//ramp the timescale - //slowdown - float timescale = (elapsedTime/MATRIX_EFFECT_TIME); - if ( timescale < 0.01f ) - { + // do all the slowdown and vert bob stuff + if (cent->currentState.angles2[0]) { + cgi_Cvar_Set("timescale", va("%4.2f", cent->currentState.angles2[0])); + } else if (!(cent->currentState.boltInfo & MEF_NO_TIMESCALE)) { // ramp the timescale + // slowdown + float timescale = (elapsedTime / MATRIX_EFFECT_TIME); + if (timescale < 0.01f) { timescale = 0.01f; } - cgi_Cvar_Set( "timescale", va("%4.2f",timescale) ); - } - else - {//FIXME: MEF_HIT_GROUND_STOP: if they're on the ground, stop spinning and stop timescale - //FIXME: if they go to the menu, restore timescale? - //cgi_Cvar_Set( "timescale", "1.0ff" ); + cgi_Cvar_Set("timescale", va("%4.2f", timescale)); + } else { // FIXME: MEF_HIT_GROUND_STOP: if they're on the ground, stop spinning and stop timescale + // FIXME: if they go to the menu, restore timescale? + // cgi_Cvar_Set( "timescale", "1.0ff" ); } - if ( !(cent->currentState.boltInfo&MEF_NO_VERTBOB) ) - {//bob the pitch - //pitch - //dip - FIXME: use pitchOffet? + if (!(cent->currentState.boltInfo & MEF_NO_VERTBOB)) { // bob the pitch + // pitch + // dip - FIXME: use pitchOffet? cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_POF; cg.overrides.thirdPersonPitchOffset = cg_thirdPersonPitchOffset.value; - if ( elapsedTime < MATRIX_EFFECT_TIME*0.33f ) - { - cg.overrides.thirdPersonPitchOffset -= 30.0f*elapsedTime/(MATRIX_EFFECT_TIME*0.33); - } - else if ( elapsedTime > MATRIX_EFFECT_TIME*0.66f ) - { - cg.overrides.thirdPersonPitchOffset -= 30.0f*(MATRIX_EFFECT_TIME-elapsedTime)/(MATRIX_EFFECT_TIME*0.33); - } - else - { + if (elapsedTime < MATRIX_EFFECT_TIME * 0.33f) { + cg.overrides.thirdPersonPitchOffset -= 30.0f * elapsedTime / (MATRIX_EFFECT_TIME * 0.33); + } else if (elapsedTime > MATRIX_EFFECT_TIME * 0.66f) { + cg.overrides.thirdPersonPitchOffset -= 30.0f * (MATRIX_EFFECT_TIME - elapsedTime) / (MATRIX_EFFECT_TIME * 0.33); + } else { cg.overrides.thirdPersonPitchOffset -= 30.0f; } } - if ( !(cent->currentState.boltInfo&MEF_NO_RANGEVAR) ) - {//vary the camera range - //pull back + if (!(cent->currentState.boltInfo & MEF_NO_RANGEVAR)) { // vary the camera range + // pull back cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = cg_thirdPersonRange.value; - if ( elapsedTime < MATRIX_EFFECT_TIME*0.33 ) - { - cg.overrides.thirdPersonRange += 80.0f*elapsedTime/(MATRIX_EFFECT_TIME*0.33); - } - else if ( elapsedTime > MATRIX_EFFECT_TIME*0.66 ) - { - cg.overrides.thirdPersonRange += 80.0f*(MATRIX_EFFECT_TIME-elapsedTime)/(MATRIX_EFFECT_TIME*0.33); - } - else - { + if (elapsedTime < MATRIX_EFFECT_TIME * 0.33) { + cg.overrides.thirdPersonRange += 80.0f * elapsedTime / (MATRIX_EFFECT_TIME * 0.33); + } else if (elapsedTime > MATRIX_EFFECT_TIME * 0.66) { + cg.overrides.thirdPersonRange += 80.0f * (MATRIX_EFFECT_TIME - elapsedTime) / (MATRIX_EFFECT_TIME * 0.33); + } else { cg.overrides.thirdPersonRange += 80.0f; } } } -static void CG_Think ( centity_t *cent ) -{ - if(!cent->gent) - { +static void CG_Think(centity_t *cent) { + if (!cent->gent) { return; } - CEntity_ThinkFunc(cent); // cent->gent->clThink(cent); + CEntity_ThinkFunc(cent); // cent->gent->clThink(cent); } -static void CG_Clouds( centity_t *cent ) -{ - refEntity_t ent; +static void CG_Clouds(centity_t *cent) { + refEntity_t ent; // create the render entity - memset( &ent, 0, sizeof( ent )); + memset(&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = ent.shaderRGBA[3] = 255; @@ -2321,22 +1967,20 @@ static void CG_Clouds( centity_t *cent ) ent.reType = RT_CLOUDS; - if ( cent->gent->spawnflags & 1 ) // TUBE type, the one with a hole in the middle + if (cent->gent->spawnflags & 1) // TUBE type, the one with a hole in the middle { ent.rotation = cent->gent->random; - ent.renderfx = RF_GROW;// tube flag + ent.renderfx = RF_GROW; // tube flag } - if ( cent->gent->spawnflags & 2 ) // ALT type, uses a different shader - { - ent.customShader = cgi_R_RegisterShader( "gfx/world/haze2" ); - } - else + if (cent->gent->spawnflags & 2) // ALT type, uses a different shader { - ent.customShader = cgi_R_RegisterShader( "gfx/world/haze" ); + ent.customShader = cgi_R_RegisterShader("gfx/world/haze2"); + } else { + ent.customShader = cgi_R_RegisterShader("gfx/world/haze"); } - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } /* @@ -2345,48 +1989,44 @@ CG_AddCEntity =============== */ -static void CG_AddCEntity( centity_t *cent ) -{ +static void CG_AddCEntity(centity_t *cent) { // event-only entities will have been dealt with already - if ( cent->currentState.eType >= ET_EVENTS ) { + if (cent->currentState.eType >= ET_EVENTS) { return; } - //we must have restarted the game - if (!cent->gent) - { + // we must have restarted the game + if (!cent->gent) { return; } cent->snapShotTime = cg.time; // calculate the current origin - CG_CalcEntityLerpPositions( cent ); + CG_CalcEntityLerpPositions(cent); // add automatic effects - CG_EntityEffects( cent ); + CG_EntityEffects(cent); // add local sound set if any - if ( cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] && cent->currentState.eType != ET_MOVER ) - { - CG_AddLocalSet( cent ); + if (cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] && cent->currentState.eType != ET_MOVER) { + CG_AddLocalSet(cent); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // do this before we copy the data to refEnts - if (cent->gent->ghoul2.IsValid()) - { + if (cent->gent->ghoul2.IsValid()) { trap_G2_SetGhoul2ModelIndexes(cent->gent->ghoul2, cgs.model_draw, cgs.skins); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - switch ( cent->currentState.eType ) { + switch (cent->currentState.eType) { default: - CG_Error( "Bad entity type: %i\n", cent->currentState.eType ); + CG_Error("Bad entity type: %i\n", cent->currentState.eType); break; case ET_INVISIBLE: case ET_PUSH_TRIGGER: @@ -2394,39 +2034,38 @@ Ghoul2 Insert End case ET_TERRAIN: break; case ET_GENERAL: - CG_General( cent ); + CG_General(cent); break; case ET_PLAYER: - CG_Player( cent ); + CG_Player(cent); break; case ET_ITEM: - CG_Item( cent ); + CG_Item(cent); break; case ET_MISSILE: - CG_Missile( cent ); + CG_Missile(cent); break; case ET_MOVER: - CG_Mover( cent ); + CG_Mover(cent); break; case ET_BEAM: - CG_Beam( cent, 0 ); + CG_Beam(cent, 0); break; case ET_PORTAL: - CG_Portal( cent ); + CG_Portal(cent); break; case ET_SPEAKER: - if ( cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] ) - { + if (cent->gent && cent->gent->soundSet && cent->gent->soundSet[0]) { break; } - CG_Speaker( cent ); + CG_Speaker(cent); break; case ET_THINKER: - CG_General( cent ); - CG_Think( cent ); + CG_General(cent); + CG_Think(cent); break; case ET_CLOUD: // dumb - CG_Clouds( cent ); + CG_Clouds(cent); break; } } @@ -2437,87 +2076,75 @@ CG_AddPacketEntities =============== */ -void CG_AddPacketEntities( qboolean isPortal ) { - int num; - centity_t *cent; - playerState_t *ps; +void CG_AddPacketEntities(qboolean isPortal) { + int num; + centity_t *cent; + playerState_t *ps; - if (isPortal) - { - for ( num = 0 ; num < cg.snap->numEntities ; num++ ) - { - cent = &cg_entities[ cg.snap->entities[ num ].number ]; + if (isPortal) { + for (num = 0; num < cg.snap->numEntities; num++) { + cent = &cg_entities[cg.snap->entities[num].number]; - if (cent->currentState.isPortalEnt) - { - CG_AddCEntity( cent ); + if (cent->currentState.isPortalEnt) { + CG_AddCEntity(cent); } } return; } // set cg.frameInterpolation - if ( cg.nextSnap ) - { - int delta; + if (cg.nextSnap) { + int delta; delta = (cg.nextSnap->serverTime - cg.snap->serverTime); - if ( delta == 0 ) - { + if (delta == 0) { cg.frameInterpolation = 0; + } else { + cg.frameInterpolation = (float)(cg.time - cg.snap->serverTime) / delta; } - else - { - cg.frameInterpolation = (float)( cg.time - cg.snap->serverTime ) / delta; - } -//OutputDebugString(va("interp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,cg.nextSnap->serverTime,cg.snap->serverTime)); - } - else - { - cg.frameInterpolation = 0; // actually, it should never be used, because - // no entities should be marked as interpolating -//OutputDebugString(va("noterp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,0,cg.snap->serverTime)); + // OutputDebugString(va("interp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,cg.nextSnap->serverTime,cg.snap->serverTime)); + } else { + cg.frameInterpolation = 0; // actually, it should never be used, because + // no entities should be marked as interpolating + // OutputDebugString(va("noterp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,0,cg.snap->serverTime)); } // the auto-rotating items will all have the same axis cg.autoAngles[0] = 0; - cg.autoAngles[1] = ( cg.time & 2047 ) * 360 / 2048.0f; + cg.autoAngles[1] = (cg.time & 2047) * 360 / 2048.0f; cg.autoAngles[2] = 0; cg.autoAnglesFast[0] = 0; - cg.autoAnglesFast[1] = ( cg.time & 1023 ) * 360 / 1024.0f; + cg.autoAnglesFast[1] = (cg.time & 1023) * 360 / 1024.0f; cg.autoAnglesFast[2] = 0; - AnglesToAxis( cg.autoAngles, cg.autoAxis ); - AnglesToAxis( cg.autoAnglesFast, cg.autoAxisFast ); + AnglesToAxis(cg.autoAngles, cg.autoAxis); + AnglesToAxis(cg.autoAnglesFast, cg.autoAxisFast); // generate and add the entity from the playerstate ps = &cg.predicted_player_state; - PlayerStateToEntityState( ps, &cg_entities[ ps->clientNum ].currentState ); -// cent = &cg_entities[ ps->clientNum ]; // not needed now that player is in the snap packet -// CG_AddCEntity( cent ); // + PlayerStateToEntityState(ps, &cg_entities[ps->clientNum].currentState); + // cent = &cg_entities[ ps->clientNum ]; // not needed now that player is in the snap packet + // CG_AddCEntity( cent ); // // add each entity sent over by the server - for ( num = 0 ; num < cg.snap->numEntities ; num++ ) { - cent = &cg_entities[ cg.snap->entities[ num ].number ]; + for (num = 0; num < cg.snap->numEntities; num++) { + cent = &cg_entities[cg.snap->entities[num].number]; - CG_AddCEntity( cent ); + CG_AddCEntity(cent); } - for(num=0;numcurrentValid) - { - CG_AddCEntity( cent ); + if (cent->currentValid) { + CG_AddCEntity(cent); } } } -//rww - This function is not currently called. Use it as the client-side ROFF -//callback once that's implemented fully. -void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) -{ +// rww - This function is not currently called. Use it as the client-side ROFF +// callback once that's implemented fully. +void CG_ROFF_NotetrackCallback(centity_t *cent, const char *notetrack) { int i = 0, r = 0, objectID = 0, anglesGathered = 0, posoffsetGathered = 0; char type[256]; char argument[512]; @@ -2527,49 +2154,42 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) int addlArgs = 0; vec3_t parsedAngles, parsedOffset, useAngles, useOrigin, forward, right, up; - if (!cent || !notetrack) - { + if (!cent || !notetrack) { return; } - //notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; + // notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (notetrack[i] != ' ') - { //didn't pass in a valid notetrack type, or forgot the argument for it + if (notetrack[i] != ' ') { // didn't pass in a valid notetrack type, or forgot the argument for it return; } i++; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { argument[r] = notetrack[i]; r++; i++; } argument[r] = '\0'; - if (!r) - { + if (!r) { return; } - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -2577,33 +2197,28 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "effect") == 0) - { - if (!addlArgs) - { - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (strcmp(type, "effect") == 0) { + if (!addlArgs) { + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); goto defaultoffsetposition; } i = 0; - while (posoffsetGathered < 3) - { + while (posoffsetGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') - { + while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') { t[r] = addlArg[i]; r++; i++; } t[r] = '\0'; i++; - if (!r) - { //failure.. - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (!r) { // failure.. + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); i = 0; goto defaultoffsetposition; @@ -2612,33 +2227,27 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) posoffsetGathered++; } - if (posoffsetGathered < 3) - { + if (posoffsetGathered < 3) { Q_strncpyz(errMsg, "Offset position argument for 'effect' type is invalid.", sizeof(errMsg)); goto functionend; } i--; - if (addlArg[i] != ' ') - { + if (addlArg[i] != ' ') { addlArgs = 0; } -defaultoffsetposition: + defaultoffsetposition: objectID = theFxScheduler.RegisterEffect(argument); - if (objectID) - { - if (addlArgs) - { //if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE + if (objectID) { + if (addlArgs) { // if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE i++; - while (anglesGathered < 3) - { + while (anglesGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '-') - { + while (addlArg[i] && addlArg[i] != '-') { t[r] = addlArg[i]; r++; i++; @@ -2646,8 +2255,7 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) t[r] = '\0'; i++; - if (!r) - { //failed to get a new part of the vector + if (!r) { // failed to get a new part of the vector anglesGathered = 0; break; } @@ -2656,17 +2264,12 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) anglesGathered++; } - if (anglesGathered) - { + if (anglesGathered) { VectorCopy(parsedAngles, useAngles); - } - else - { //failed to parse angles from the extra argument provided.. + } else { // failed to parse angles from the extra argument provided.. VectorCopy(cent->lerpAngles, useAngles); } - } - else - { //if no constant angles, play in direction entity is facing + } else { // if no constant angles, play in direction entity is facing VectorCopy(cent->lerpAngles, useAngles); } @@ -2674,42 +2277,34 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) VectorCopy(cent->lerpOrigin, useOrigin); - //forward - useOrigin[0] += forward[0]*parsedOffset[0]; - useOrigin[1] += forward[1]*parsedOffset[0]; - useOrigin[2] += forward[2]*parsedOffset[0]; + // forward + useOrigin[0] += forward[0] * parsedOffset[0]; + useOrigin[1] += forward[1] * parsedOffset[0]; + useOrigin[2] += forward[2] * parsedOffset[0]; - //right - useOrigin[0] += right[0]*parsedOffset[1]; - useOrigin[1] += right[1]*parsedOffset[1]; - useOrigin[2] += right[2]*parsedOffset[1]; + // right + useOrigin[0] += right[0] * parsedOffset[1]; + useOrigin[1] += right[1] * parsedOffset[1]; + useOrigin[2] += right[2] * parsedOffset[1]; - //up - useOrigin[0] += up[0]*parsedOffset[2]; - useOrigin[1] += up[1]*parsedOffset[2]; - useOrigin[2] += up[2]*parsedOffset[2]; + // up + useOrigin[0] += up[0] * parsedOffset[2]; + useOrigin[1] += up[1] * parsedOffset[2]; + useOrigin[2] += up[2] * parsedOffset[2]; theFxScheduler.PlayEffect(objectID, useOrigin, useAngles); } - } - else if (strcmp(type, "sound") == 0) - { + } else if (strcmp(type, "sound") == 0) { objectID = cgi_S_RegisterSound(argument); cgi_S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_BODY, objectID); - } - else if (strcmp(type, "loop") == 0) - { //handled server-side + } else if (strcmp(type, "loop") == 0) { // handled server-side return; } - //else if ... - else - { - if (type[0]) - { + // else if ... + else { + if (type[0]) { Com_Printf("^3Warning: \"%s\" is an invalid ROFF notetrack function\n", type); - } - else - { + } else { Com_Printf("^3Warning: Notetrack is missing function and/or arguments\n"); } } diff --git a/code/cgame/cg_event.cpp b/code/cgame/cg_event.cpp index 635dfe14d9..3a967f1b6f 100644 --- a/code/cgame/cg_event.cpp +++ b/code/cgame/cg_event.cpp @@ -30,58 +30,57 @@ along with this program; if not, see . #include "../game/anims.h" -extern qboolean CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ); -extern void FX_KothosBeam( vec3_t start, vec3_t end ); +extern qboolean CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet); +extern void FX_KothosBeam(vec3_t start, vec3_t end); //========================================================================== -qboolean CG_IsFemale( const char *infostring ) { - const char *sex; +qboolean CG_IsFemale(const char *infostring) { + const char *sex; - sex = Info_ValueForKey( infostring, "s" ); + sex = Info_ValueForKey(infostring, "s"); if (sex[0] == 'f' || sex[0] == 'F') return qtrue; return qfalse; } -const char *CG_PlaceString( int rank ) { - static char str[64]; - char *s, *t; +const char *CG_PlaceString(int rank) { + static char str[64]; + char *s, *t; - if ( rank & RANK_TIED_FLAG ) { + if (rank & RANK_TIED_FLAG) { rank &= ~RANK_TIED_FLAG; t = "Tied for "; } else { t = ""; } - if ( rank == 1 ) { - s = "\03341st\0337"; // draw in blue - } else if ( rank == 2 ) { - s = "\03312nd\0337"; // draw in red - } else if ( rank == 3 ) { - s = "\03333rd\0337"; // draw in yellow - } else if ( rank == 11 ) { + if (rank == 1) { + s = "\03341st\0337"; // draw in blue + } else if (rank == 2) { + s = "\03312nd\0337"; // draw in red + } else if (rank == 3) { + s = "\03333rd\0337"; // draw in yellow + } else if (rank == 11) { s = "11th"; - } else if ( rank == 12 ) { + } else if (rank == 12) { s = "12th"; - } else if ( rank == 13 ) { + } else if (rank == 13) { s = "13th"; - } else if ( rank % 10 == 1 ) { + } else if (rank % 10 == 1) { s = va("%ist", rank); - } else if ( rank % 10 == 2 ) { + } else if (rank % 10 == 2) { s = va("%ind", rank); - } else if ( rank % 10 == 3 ) { + } else if (rank % 10 == 3) { s = va("%ird", rank); } else { s = va("%ith", rank); } - Com_sprintf( str, sizeof( str ), "%s%s", t, s ); + Com_sprintf(str, sizeof(str), "%s%s", t, s); return str; } - /* ================ CG_ItemPickup @@ -89,34 +88,29 @@ CG_ItemPickup A new item was picked up this frame ================ */ -void CG_ItemPickup( int itemNum, qboolean bHadItem ) { +void CG_ItemPickup(int itemNum, qboolean bHadItem) { cg.itemPickup = itemNum; cg.itemPickupTime = cg.time; cg.itemPickupBlendTime = cg.time; - if (bg_itemlist[itemNum].classname && bg_itemlist[itemNum].classname[0]) - { + if (bg_itemlist[itemNum].classname && bg_itemlist[itemNum].classname[0]) { char text[1024], data[1024]; - if (cgi_SP_GetStringTextString("SP_INGAME_PICKUPLINE",text, sizeof(text)) ) - { - if ( cgi_SP_GetStringTextString( va("SP_INGAME_%s",bg_itemlist[itemNum].classname ), data, sizeof( data ))) - { -// Com_Printf("%s %s\n", text, data ); - cgi_Cvar_Set( "cg_WeaponPickupText", va("%s %s\n", text, data)); - cg.weaponPickupTextTime = cg.time + 5000; + if (cgi_SP_GetStringTextString("SP_INGAME_PICKUPLINE", text, sizeof(text))) { + if (cgi_SP_GetStringTextString(va("SP_INGAME_%s", bg_itemlist[itemNum].classname), data, sizeof(data))) { + // Com_Printf("%s %s\n", text, data ); + cgi_Cvar_Set("cg_WeaponPickupText", va("%s %s\n", text, data)); + cg.weaponPickupTextTime = cg.time + 5000; } } } // see if it should be the grabbed weapon - if ( bg_itemlist[itemNum].giType == IT_WEAPON ) - { + if (bg_itemlist[itemNum].giType == IT_WEAPON) { const int nCurWpn = cg.predicted_player_state.weapon; const int nNewWpn = bg_itemlist[itemNum].giTag; - if ( nCurWpn == WP_SABER || bHadItem) - {//never switch away from the saber! + if (nCurWpn == WP_SABER || bHadItem) { // never switch away from the saber! return; } @@ -129,38 +123,25 @@ void CG_ItemPickup( int itemNum, qboolean bHadItem ) { // NOTE: automatically switching to any weapon you pick up is stupid and annoying and we won't do it. // - if ( nNewWpn == WP_SABER ) - {//always switch to saber + if (nNewWpn == WP_SABER) { // always switch to saber SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; - } - else if (0 == cg_autoswitch.integer) - { + } else if (0 == cg_autoswitch.integer) { // don't switch - } - else if (1 == cg_autoswitch.integer) - { + } else if (1 == cg_autoswitch.integer) { // safe switching - if ( (nNewWpn > nCurWpn) && - !(nNewWpn == WP_DET_PACK) && - !(nNewWpn == WP_TRIP_MINE) && - !(nNewWpn == WP_THERMAL) && - !(nNewWpn == WP_ROCKET_LAUNCHER) && - !(nNewWpn == WP_CONCUSSION) ) - { + if ((nNewWpn > nCurWpn) && !(nNewWpn == WP_DET_PACK) && !(nNewWpn == WP_TRIP_MINE) && !(nNewWpn == WP_THERMAL) && + !(nNewWpn == WP_ROCKET_LAUNCHER) && !(nNewWpn == WP_CONCUSSION)) { // switch to new wpn -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; } - } - else if (2 == cg_autoswitch.integer) - { + } else if (2 == cg_autoswitch.integer) { // best - if (nNewWpn > nCurWpn) - { + if (nNewWpn > nCurWpn) { // switch to new wpn -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; } @@ -168,23 +149,20 @@ void CG_ItemPickup( int itemNum, qboolean bHadItem ) { } } - /* =============== UseItem =============== */ -extern void CG_ToggleBinoculars( void ); -extern void CG_ToggleLAGoggles( void ); +extern void CG_ToggleBinoculars(void); +extern void CG_ToggleLAGoggles(void); -void UseItem(int itemNum) -{ - centity_t *cent; +void UseItem(int itemNum) { + centity_t *cent; cent = &cg_entities[cg.snap->ps.clientNum]; - switch ( itemNum ) - { + switch (itemNum) { case INV_ELECTROBINOCULARS: CG_ToggleBinoculars(); break; @@ -192,14 +170,12 @@ void UseItem(int itemNum) CG_ToggleLAGoggles(); break; case INV_GOODIE_KEY: - if (cent->gent->client->ps.inventory[INV_GOODIE_KEY]) - { + if (cent->gent->client->ps.inventory[INV_GOODIE_KEY]) { cent->gent->client->ps.inventory[INV_GOODIE_KEY]--; } break; case INV_SECURITY_KEY: - if (cent->gent->client->ps.inventory[INV_SECURITY_KEY]) - { + if (cent->gent->client->ps.inventory[INV_SECURITY_KEY]) { cent->gent->client->ps.inventory[INV_SECURITY_KEY]--; } break; @@ -211,10 +187,9 @@ void UseItem(int itemNum) CG_UseForce =============== */ -static void CG_UseForce( centity_t *cent ) -{ - //FIXME: sound or graphic change or something? - //actual force power action is on game/pm side +static void CG_UseForce(centity_t *cent) { + // FIXME: sound or graphic change or something? + // actual force power action is on game/pm side } /* @@ -222,38 +197,30 @@ static void CG_UseForce( centity_t *cent ) CG_UseItem =============== */ -static void CG_UseItem( centity_t *cent ) -{ - int itemNum; +static void CG_UseItem(centity_t *cent) { + int itemNum; entityState_t *es; es = ¢->currentState; itemNum = cg.inventorySelect; - if ( itemNum < 0 || itemNum > INV_MAX ) - { + if (itemNum < 0 || itemNum > INV_MAX) { itemNum = 0; } // print a message if the local player - if ( es->number == cg.snap->ps.clientNum ) - { - if ( !itemNum ) - { -// CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); - } - else - { -// item = BG_FindItemForHoldable( itemNum ); -// CG_CenterPrint( va("Use %s", item->pickup_name), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + if (es->number == cg.snap->ps.clientNum) { + if (!itemNum) { + // CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + } else { + // item = BG_FindItemForHoldable( itemNum ); + // CG_CenterPrint( va("Use %s", item->pickup_name), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); } } UseItem(itemNum); - } - /* ============== CG_EntityEvent @@ -261,223 +228,219 @@ CG_EntityEvent An entity has an event value ============== */ -#define DEBUGNAME(x) if(cg_debugEvents.integer){CG_Printf(x"\n");} -void CG_EntityEvent( centity_t *cent, vec3_t position ) { - entityState_t *es; - int event; - vec3_t axis[3]; - const char *s, *s2; - int clientNum; - //clientInfo_t *ci; +#define DEBUGNAME(x) \ + if (cg_debugEvents.integer) { \ + CG_Printf(x "\n"); \ + } +void CG_EntityEvent(centity_t *cent, vec3_t position) { + entityState_t *es; + int event; + vec3_t axis[3]; + const char *s, *s2; + int clientNum; + // clientInfo_t *ci; es = ¢->currentState; event = es->event & ~EV_EVENT_BITS; - if ( cg_debugEvents.integer ) { - CG_Printf( "ent:%3i event:%3i ", es->number, event ); + if (cg_debugEvents.integer) { + CG_Printf("ent:%3i event:%3i ", es->number, event); } - if ( !event ) { + if (!event) { DEBUGNAME("ZEROEVENT"); return; } - if ( !cent->gent )//|| !cent->gent->client ) + if (!cent->gent) //|| !cent->gent->client ) { return; } - //ci = ¢->gent->client->clientInfo; + // ci = ¢->gent->client->clientInfo; clientNum = cent->gent->s.number; - switch ( event ) { + switch (event) { // // movement generated events // case EV_FOOTSPLASH: DEBUGNAME("EV_FOOTSPLASH"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SPLASH][rand() & 3]); } break; case EV_FOOTWADE: DEBUGNAME("EV_FOOTWADE"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.footsteps[ FOOTSTEP_WADE ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_WADE][rand() & 3]); } break; case EV_SWIM: DEBUGNAME("EV_SWIM"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.footsteps[ FOOTSTEP_SWIM ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SWIM][rand() & 3]); } break; - case EV_FALL_SHORT: DEBUGNAME("EV_FALL_SHORT"); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); - if ( clientNum == cg.predicted_player_state.clientNum ) { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -8; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_FALL_MEDIUM: DEBUGNAME("EV_FALL_MEDIUM"); // use normal pain sound - - if ( g_entities[es->number].health <= 0 ) - {//dead - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); + if (g_entities[es->number].health <= 0) { // dead + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + } else if (g_entities[es->number].s.weapon == WP_SABER || + (g_entities[es->number].client && (g_entities[es->number].client->ps.forcePowersKnown & + (1 << FP_LEVITATION)))) { // jedi or someone who has force jump (so probably took no damage) + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC); + } else { // still alive + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*pain100.wav", CS_BASIC); } - else if ( g_entities[es->number].s.weapon == WP_SABER - || (g_entities[es->number].client && (g_entities[es->number].client->ps.forcePowersKnown&(1<number, CHAN_BODY, "*land1.wav", CS_BASIC ); - } - else - {//still alive - CG_TryPlayCustomSound( NULL, es->number, CHAN_BODY, "*pain100.wav", CS_BASIC ); - } - if ( clientNum == cg.predicted_player_state.clientNum ) { + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -16; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_FALL_FAR: DEBUGNAME("EV_FALL_FAR"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC ); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); - cent->pe.painTime = cg.time; // don't play a pain sound right after this - if ( clientNum == cg.predicted_player_state.clientNum ) { + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + cent->pe.painTime = cg.time; // don't play a pain sound right after this + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -24; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_STEP_4: case EV_STEP_8: case EV_STEP_12: - case EV_STEP_16: // smooth out step up transitions + case EV_STEP_16: // smooth out step up transitions DEBUGNAME("EV_STEP"); - { - float oldStep; - int delta; - int step; - - if ( clientNum != cg.predicted_player_state.clientNum ) { - break; - } - // if we are interpolating, we don't need to smooth steps - if ( cg_timescale.value >= 1.0f ) { - break; - } - // check for stepping up before a previous step is completed - delta = cg.time - cg.stepTime; - if (delta < STEP_TIME) { - oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; - } else { - oldStep = 0; - } + float oldStep; + int delta; + int step; - // add this amount - step = 4 * (event - EV_STEP_4 + 1 ); - cg.stepChange = oldStep + step; - if ( cg.stepChange > MAX_STEP_CHANGE ) { - cg.stepChange = MAX_STEP_CHANGE; + if (clientNum != cg.predicted_player_state.clientNum) { + break; + } + // if we are interpolating, we don't need to smooth steps + if (cg_timescale.value >= 1.0f) { + break; + } + // check for stepping up before a previous step is completed + delta = cg.time - cg.stepTime; + if (delta < STEP_TIME) { + oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; + } else { + oldStep = 0; + } + + // add this amount + step = 4 * (event - EV_STEP_4 + 1); + cg.stepChange = oldStep + step; + if (cg.stepChange > MAX_STEP_CHANGE) { + cg.stepChange = MAX_STEP_CHANGE; + } + cg.stepTime = cg.time; + break; } - cg.stepTime = cg.time; - break; - } case EV_JUMP: DEBUGNAME("EV_JUMP"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC );//CHAN_VOICE + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC); // CHAN_VOICE break; case EV_ROLL: DEBUGNAME("EV_ROLL"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC );//CHAN_VOICE - cgi_S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.rollSound );//CHAN_AUTO - //FIXME: need some sort of body impact on ground sound and maybe kick up some dust? + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC); // CHAN_VOICE + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.rollSound); // CHAN_AUTO + // FIXME: need some sort of body impact on ground sound and maybe kick up some dust? break; case EV_LAVA_TOUCH: DEBUGNAME("EV_LAVA_TOUCH"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.lavaInSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.lavaInSound); break; case EV_LAVA_LEAVE: DEBUGNAME("EV_LAVA_LEAVE"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.lavaOutSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.lavaOutSound); break; case EV_LAVA_UNDER: DEBUGNAME("EV_LAVA_UNDER"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.lavaUnSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.lavaUnSound); break; case EV_WATER_TOUCH: DEBUGNAME("EV_WATER_TOUCH"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrInSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrInSound); break; case EV_WATER_LEAVE: DEBUGNAME("EV_WATER_LEAVE"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound); break; case EV_WATER_UNDER: DEBUGNAME("EV_WATER_UNDER"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound); break; case EV_WATER_CLEAR: DEBUGNAME("EV_WATER_CLEAR"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*gasp.wav", CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*gasp.wav", CS_BASIC); break; case EV_WATER_GURP1: case EV_WATER_GURP2: DEBUGNAME("EV_WATER_GURPx"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, va("*gurp%d.wav",event-EV_WATER_GURP1+1), CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, va("*gurp%d.wav", event - EV_WATER_GURP1 + 1), CS_BASIC); break; case EV_WATER_DROWN: DEBUGNAME("EV_WATER_DROWN"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*drown.wav", CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*drown.wav", CS_BASIC); break; case EV_ITEM_PICKUP: DEBUGNAME("EV_ITEM_PICKUP"); { - gitem_t *item; - int index; + gitem_t *item; + int index; qboolean bHadItem = qfalse; - index = es->eventParm; // player predicted + index = es->eventParm; // player predicted - if ( (char)index < 0 ) - { + if ((char)index < 0) { index = -(char)index; bHadItem = qtrue; } - if ( index >= bg_numItems ) { + if (index >= bg_numItems) { break; } - item = &bg_itemlist[ index ]; - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( item->pickup_sound ) ); + item = &bg_itemlist[index]; + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound(item->pickup_sound)); // show icon and name on status bar - if ( es->number == cg.snap->ps.clientNum ) { - CG_ItemPickup( index, bHadItem ); + if (es->number == cg.snap->ps.clientNum) { + CG_ItemPickup(index, bHadItem); } } break; @@ -487,105 +450,99 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // case EV_NOAMMO: DEBUGNAME("EV_NOAMMO"); - //cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); - if ( es->number == cg.snap->ps.clientNum ) { + // cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); + if (es->number == cg.snap->ps.clientNum) { CG_OutOfAmmoChange(); } break; case EV_CHANGE_WEAPON: DEBUGNAME("EV_CHANGE_WEAPON"); - if ( es->weapon == WP_SABER ) - { + if (es->weapon == WP_SABER) { /* if ( !cent->gent || !cent->gent->client || (cent->currentState.saberInFlight == qfalse && cent->currentState.saberActive == qtrue) ) { cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" ) ); } */ - if ( cent->gent && cent->gent->client ) - { - //if ( cent->gent->client->ps.saberInFlight ) - {//if it's not in flight or lying around, turn it off! + if (cent->gent && cent->gent->client) { + // if ( cent->gent->client->ps.saberInFlight ) + { // if it's not in flight or lying around, turn it off! cent->currentState.saberActive = qfalse; } } } // FIXME: if it happens that you don't want the saber to play the switch sounds, feel free to modify this bit. - if ( weaponData[cg.weaponSelect].selectSnd[0] ) - { + if (weaponData[cg.weaponSelect].selectSnd[0]) { // custom select sound - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( weaponData[cg.weaponSelect].selectSnd )); - } - else - { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound(weaponData[cg.weaponSelect].selectSnd)); + } else { // generic sound - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.selectSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.selectSound); } break; case EV_FIRE_WEAPON: DEBUGNAME("EV_FIRE_WEAPON"); - CG_FireWeapon( cent, qfalse ); + CG_FireWeapon(cent, qfalse); break; case EV_ALT_FIRE: DEBUGNAME("EV_ALT_FIRE"); - CG_FireWeapon( cent, qtrue ); + CG_FireWeapon(cent, qtrue); break; case EV_DISRUPTOR_MAIN_SHOT: DEBUGNAME("EV_DISRUPTOR_MAIN_SHOT"); - FX_DisruptorMainShot( cent->currentState.origin2, cent->lerpOrigin ); + FX_DisruptorMainShot(cent->currentState.origin2, cent->lerpOrigin); break; case EV_DISRUPTOR_SNIPER_SHOT: DEBUGNAME("EV_DISRUPTOR_SNIPER_SHOT"); - FX_DisruptorAltShot( cent->currentState.origin2, cent->lerpOrigin, cent->gent->alt_fire ); + FX_DisruptorAltShot(cent->currentState.origin2, cent->lerpOrigin, cent->gent->alt_fire); break; case EV_DISRUPTOR_SNIPER_MISS: DEBUGNAME("EV_DISRUPTOR_SNIPER_MISS"); - FX_DisruptorAltMiss( cent->lerpOrigin, cent->gent->pos1 ); + FX_DisruptorAltMiss(cent->lerpOrigin, cent->gent->pos1); break; case EV_DEMP2_ALT_IMPACT: - FX_DEMP2_AltDetonate( cent->lerpOrigin, es->eventParm ); + FX_DEMP2_AltDetonate(cent->lerpOrigin, es->eventParm); break; case EV_CONC_ALT_SHOT: DEBUGNAME("EV_CONC_ALT_SHOT"); - FX_ConcAltShot( cent->currentState.origin2, cent->lerpOrigin ); + FX_ConcAltShot(cent->currentState.origin2, cent->lerpOrigin); break; case EV_CONC_ALT_MISS: DEBUGNAME("EV_CONC_ALT_MISS"); - FX_ConcAltMiss( cent->lerpOrigin, cent->gent->pos1 ); + FX_ConcAltMiss(cent->lerpOrigin, cent->gent->pos1); break; -// case EV_POWERUP_SEEKER_FIRE: -// DEBUGNAME("EV_POWERUP_SEEKER_FIRE"); -// CG_FireSeeker( cent ); -// break; + // case EV_POWERUP_SEEKER_FIRE: + // DEBUGNAME("EV_POWERUP_SEEKER_FIRE"); + // CG_FireSeeker( cent ); + // break; case EV_POWERUP_BATTLESUIT: DEBUGNAME("EV_POWERUP_BATTLESUIT"); - if ( es->number == cg.snap->ps.clientNum ) { + if (es->number == cg.snap->ps.clientNum) { cg.powerupActive = PW_BATTLESUIT; cg.powerupTime = cg.time; } - //cgi_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.invulnoProtectSound ); + // cgi_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.invulnoProtectSound ); break; case EV_KOTHOS_BEAM: DEBUGNAME("EV_KOTHOS_BEAM"); - if ( Q_irand( 0, 1 ) ) - { - FX_KothosBeam( cg_entities[cent->currentState.otherEntityNum].gent->client->renderInfo.handRPoint, cg_entities[cent->currentState.otherEntityNum2].lerpOrigin ); - } - else - { - FX_KothosBeam( cg_entities[cent->currentState.otherEntityNum].gent->client->renderInfo.handLPoint, cg_entities[cent->currentState.otherEntityNum2].lerpOrigin ); + if (Q_irand(0, 1)) { + FX_KothosBeam(cg_entities[cent->currentState.otherEntityNum].gent->client->renderInfo.handRPoint, + cg_entities[cent->currentState.otherEntityNum2].lerpOrigin); + } else { + FX_KothosBeam(cg_entities[cent->currentState.otherEntityNum].gent->client->renderInfo.handLPoint, + cg_entities[cent->currentState.otherEntityNum2].lerpOrigin); } break; //================================================================= @@ -595,201 +552,176 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // case EV_REPLICATOR: DEBUGNAME("EV_REPLICATOR"); -// FX_Replicator( cent, position ); + // FX_Replicator( cent, position ); break; case EV_BATTERIES_CHARGED: cg.batteryChargeTime = cg.time + 3000; - cgi_S_StartSound( vec3_origin, es->number, CHAN_AUTO, cgs.media.batteryChargeSound ); - break; - - case EV_DISINTEGRATION: - { - DEBUGNAME("EV_DISINTEGRATION"); - qboolean makeNotSolid = qfalse; - int disintPW = es->eventParm; - int disintEffect = 0; - int disintLength = 0; - qhandle_t disintSound1 = NULL_HANDLE; - qhandle_t disintSound2 = NULL_HANDLE; - //qhandle_t disintSound3 = NULL_HANDLE; - - switch( disintPW ) - { - case PW_DISRUPTION:// sniper rifle - disintEffect = EF_DISINTEGRATION;//ef_ - disintSound1 = cgs.media.disintegrateSound;//with scream - disintSound2 = cgs.media.disintegrate2Sound;//no scream - //disintSound3 = cgs.media.disintegrate3Sound;//with inhuman scream - disintLength = 2000; - makeNotSolid = qtrue; - break; -/* case PW_SHOCKED:// arc welder - disintEffect = EF_DISINT_1;//ef_ - disintSound1 = NULL;//with scream - disintSound2 = NULL;//no scream - disintSound3 = NULL;//with inhuman scream - disintLength = 4000; - break; -*/ - default: - return; - break; - } + cgi_S_StartSound(vec3_origin, es->number, CHAN_AUTO, cgs.media.batteryChargeSound); + break; + + case EV_DISINTEGRATION: { + DEBUGNAME("EV_DISINTEGRATION"); + qboolean makeNotSolid = qfalse; + int disintPW = es->eventParm; + int disintEffect = 0; + int disintLength = 0; + qhandle_t disintSound1 = NULL_HANDLE; + qhandle_t disintSound2 = NULL_HANDLE; + // qhandle_t disintSound3 = NULL_HANDLE; + + switch (disintPW) { + case PW_DISRUPTION: // sniper rifle + disintEffect = EF_DISINTEGRATION; // ef_ + disintSound1 = cgs.media.disintegrateSound; // with scream + disintSound2 = cgs.media.disintegrate2Sound; // no scream + // disintSound3 = cgs.media.disintegrate3Sound;//with inhuman scream + disintLength = 2000; + makeNotSolid = qtrue; + break; + /* case PW_SHOCKED:// arc welder + disintEffect = EF_DISINT_1;//ef_ + disintSound1 = NULL;//with scream + disintSound2 = NULL;//no scream + disintSound3 = NULL;//with inhuman scream + disintLength = 4000; + break; + */ + default: + return; + break; + } - if ( cent->gent->owner ) - { - cent->gent->owner->fx_time = cg.time; - if ( cent->gent->owner->client ) - { - if ( disintSound1 && disintSound2 ) - {//play an extra sound - // listed all the non-humanoids, because there's a lot more humanoids - class_t npc_class = cent->gent->owner->client->NPC_class; - if( npc_class != CLASS_ATST && npc_class != CLASS_GONK && - npc_class != CLASS_INTERROGATOR && npc_class != CLASS_MARK1 && - npc_class != CLASS_MARK2 && npc_class != CLASS_MOUSE && - npc_class != CLASS_PROBE && npc_class != CLASS_PROTOCOL && - npc_class != CLASS_R2D2 && npc_class != CLASS_R5D2 && - npc_class != CLASS_SEEKER && npc_class != CLASS_SENTRY) - {//Only the humanoids scream - cgi_S_StartSound ( NULL, cent->gent->owner->s.number, CHAN_VOICE, disintSound1 ); - } - // no more forge or 8472 + if (cent->gent->owner) { + cent->gent->owner->fx_time = cg.time; + if (cent->gent->owner->client) { + if (disintSound1 && disintSound2) { // play an extra sound + // listed all the non-humanoids, because there's a lot more humanoids + class_t npc_class = cent->gent->owner->client->NPC_class; + if (npc_class != CLASS_ATST && npc_class != CLASS_GONK && npc_class != CLASS_INTERROGATOR && npc_class != CLASS_MARK1 && + npc_class != CLASS_MARK2 && npc_class != CLASS_MOUSE && npc_class != CLASS_PROBE && npc_class != CLASS_PROTOCOL && + npc_class != CLASS_R2D2 && npc_class != CLASS_R5D2 && npc_class != CLASS_SEEKER && + npc_class != CLASS_SENTRY) { // Only the humanoids scream + cgi_S_StartSound(NULL, cent->gent->owner->s.number, CHAN_VOICE, disintSound1); + } + // no more forge or 8472 // else if ( cent->gent->owner->client->playerTeam == TEAM_FORGE || // cent->gent->owner->client->playerTeam == TEAM_8472 ) // { // cgi_S_StartSound ( NULL, cent->gent->s.number, CHAN_VOICE, disintSound3 ); // } - else - { - cgi_S_StartSound ( NULL, cent->gent->s.number, CHAN_AUTO, disintSound2 ); - } - } - cent->gent->owner->s.powerups |= ( 1 << disintPW ); - cent->gent->owner->client->ps.powerups[disintPW] = cg.time + disintLength; - - // Things that are being disintegrated should probably not be solid... - if ( makeNotSolid && cent->gent->owner->client->playerTeam != TEAM_NEUTRAL ) - { - cent->gent->contents = CONTENTS_NONE; + else { + cgi_S_StartSound(NULL, cent->gent->s.number, CHAN_AUTO, disintSound2); } } - else - { - cent->gent->owner->s.eFlags = disintEffect;//FIXME: |= ? - cent->gent->owner->delay = cg.time + disintLength; + cent->gent->owner->s.powerups |= (1 << disintPW); + cent->gent->owner->client->ps.powerups[disintPW] = cg.time + disintLength; + + // Things that are being disintegrated should probably not be solid... + if (makeNotSolid && cent->gent->owner->client->playerTeam != TEAM_NEUTRAL) { + cent->gent->contents = CONTENTS_NONE; } + } else { + cent->gent->owner->s.eFlags = disintEffect; // FIXME: |= ? + cent->gent->owner->delay = cg.time + disintLength; } } - break; + } break; // This does not necessarily have to be from a grenade... case EV_GRENADE_BOUNCE: DEBUGNAME("EV_GRENADE_BOUNCE"); - CG_BounceEffect( cent, es->weapon, position, cent->gent->pos1 ); + CG_BounceEffect(cent, es->weapon, position, cent->gent->pos1); break; - // - // missile impacts - // + // + // missile impacts + // case EV_MISSILE_STICK: DEBUGNAME("EV_MISSILE_STICK"); - CG_MissileStick( cent, es->weapon, position ); + CG_MissileStick(cent, es->weapon, position); break; case EV_MISSILE_HIT: DEBUGNAME("EV_MISSILE_HIT"); - if ( CG_VehicleWeaponImpact( cent ) ) - { - } - else - { - CG_MissileHitPlayer( cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire ); + if (CG_VehicleWeaponImpact(cent)) { + } else { + CG_MissileHitPlayer(cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire); } break; case EV_MISSILE_MISS: DEBUGNAME("EV_MISSILE_MISS"); - if ( CG_VehicleWeaponImpact( cent ) ) - { - } - else - { - CG_MissileHitWall( cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire ); + if (CG_VehicleWeaponImpact(cent)) { + } else { + CG_MissileHitWall(cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire); } break; case EV_BMODEL_SOUND: DEBUGNAME("EV_BMODEL_SOUND"); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, es->eventParm ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, es->eventParm); break; case EV_GENERAL_SOUND: DEBUGNAME("EV_GENERAL_SOUND"); - if ( cgs.sound_precache[ es->eventParm ] ) - { - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.sound_precache[ es->eventParm ] ); - } - else - { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, s, CS_BASIC ); + if (cgs.sound_precache[es->eventParm]) { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.sound_precache[es->eventParm]); + } else { + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, s, CS_BASIC); } break; - case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes + case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes DEBUGNAME("EV_GLOBAL_SOUND"); - if ( cgs.sound_precache[ es->eventParm ] ) { - cgi_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[ es->eventParm ] ); + if (cgs.sound_precache[es->eventParm]) { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[es->eventParm]); } else { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - CG_TryPlayCustomSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, s, CS_BASIC ); + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + CG_TryPlayCustomSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, s, CS_BASIC); } break; case EV_DRUGGED: DEBUGNAME("EV_DRUGGED"); - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number == 0 ) - { - // Only allow setting up the wonky vision on the player..do it for 10 seconds...must be synchronized with calcs done in cg_view. Just search for cg.wonkyTime to find 'em. + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number == 0) { + // Only allow setting up the wonky vision on the player..do it for 10 seconds...must be synchronized with calcs done in cg_view. Just search for + // cg.wonkyTime to find 'em. cg.wonkyTime = cg.time + 10000; } break; - case EV_PAIN: - { - char *snd; + case EV_PAIN: { + char *snd; const int health = es->eventParm; - if ( cent->gent && cent->gent->NPC && (cent->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT) ) - { + if (cent->gent && cent->gent->NPC && (cent->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { return; } - //FIXME: don't do this if we're falling to our deaths... + // FIXME: don't do this if we're falling to our deaths... DEBUGNAME("EV_PAIN"); // don't do more than two pain sounds a second - if ( cg.time - cent->pe.painTime < 500 ) { + if (cg.time - cent->pe.painTime < 500) { return; } - if ( health < 25 ) { + if (health < 25) { snd = "*pain100.wav"; - } else if ( health < 50 ) { + } else if (health < 50) { snd = "*pain75.wav"; - } else if ( health < 75 ) { + } else if (health < 75) { snd = "*pain50.wav"; } else { snd = "*pain25.wav"; } - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, snd, CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, snd, CS_BASIC); // save pain time for programitic twitch animation cent->pe.painTime = cg.time; cent->pe.painDirection ^= 1; - } - break; + } break; case EV_DEATH1: case EV_DEATH2: @@ -801,48 +733,43 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { return; } */ - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*death%i.wav", event - EV_DEATH1 + 1), CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*death%i.wav", event - EV_DEATH1 + 1), CS_BASIC); break; // Called by the FxRunner entity...usually for Environmental FX Events case EV_PLAY_EFFECT: DEBUGNAME("EV_PLAY_EFFECT"); { - const bool portalEnt = !!es->isPortalEnt; //the fxrunner spawning this effect is within a skyportal, so only render this effect within that portal. + const bool portalEnt = !!es->isPortalEnt; // the fxrunner spawning this effect is within a skyportal, so only render this effect within that portal. - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); - // Ghoul2 Insert Start - if (es->boltInfo != 0) - { + s = CG_ConfigString(CS_EFFECTS + es->eventParm); + // Ghoul2 Insert Start + if (es->boltInfo != 0) { const bool isRelative = !!es->weapon; - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, es->boltInfo, -1, portalEnt, es->loopSound, isRelative ); //loopSound 0 = not looping, 1 for infinite, else duration - } - else - { - VectorCopy( cent->gent->pos3, axis[0] ); - VectorCopy( cent->gent->pos4, axis[1] ); - CrossProduct( axis[0], axis[1], axis[2] ); + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, es->boltInfo, -1, portalEnt, es->loopSound, + isRelative); // loopSound 0 = not looping, 1 for infinite, else duration + } else { + VectorCopy(cent->gent->pos3, axis[0]); + VectorCopy(cent->gent->pos4, axis[1]); + CrossProduct(axis[0], axis[1], axis[2]); // the entNum the effect may be attached to - if ( es->otherEntityNum ) - { - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, -1, es->otherEntityNum, portalEnt ); - } - else - { - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, -1, -1, portalEnt ); + if (es->otherEntityNum) { + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, -1, es->otherEntityNum, portalEnt); + } else { + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, -1, -1, portalEnt); } } } -// Ghoul2 Insert End + // Ghoul2 Insert End break; // play an effect bolted onto a muzzle case EV_PLAY_MUZZLE_EFFECT: DEBUGNAME("EV_PLAY_MUZZLE_EFFECT"); - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); + s = CG_ConfigString(CS_EFFECTS + es->eventParm); - theFxScheduler.PlayEffect( s, es->otherEntityNum ); + theFxScheduler.PlayEffect(s, es->otherEntityNum); break; case EV_STOP_EFFECT: @@ -850,97 +777,90 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { bool portalEnt = false; - if ( es->isPortalEnt ) - { //the fxrunner spawning this effect is within a skyportal, so only render this effect within that portal. + if (es->isPortalEnt) { // the fxrunner spawning this effect is within a skyportal, so only render this effect within that portal. portalEnt = true; } - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); - if ( es->boltInfo != 0 ) - { - theFxScheduler.StopEffect( s, es->boltInfo, portalEnt ); + s = CG_ConfigString(CS_EFFECTS + es->eventParm); + if (es->boltInfo != 0) { + theFxScheduler.StopEffect(s, es->boltInfo, portalEnt); } } break; case EV_TARGET_BEAM_DRAW: DEBUGNAME("EV_TARGET_BEAM_DRAW"); - if ( cent->gent ) - { - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); + if (cent->gent) { + s = CG_ConfigString(CS_EFFECTS + es->eventParm); - if ( s && s[0] ) - { - if ( cent->gent->delay ) - { - s2 = CG_ConfigString( CS_EFFECTS + cent->gent->delay ); - } - else - { + if (s && s[0]) { + if (cent->gent->delay) { + s2 = CG_ConfigString(CS_EFFECTS + cent->gent->delay); + } else { s2 = NULL; } - CG_DrawTargetBeam( cent->lerpOrigin, cent->gent->s.origin2, cent->gent->pos1, s, s2 ); - } -/* else - { - int gack = 0; // this is bad if it get's here + CG_DrawTargetBeam(cent->lerpOrigin, cent->gent->s.origin2, cent->gent->pos1, s, s2); } -*/ + /* else + { + int gack = 0; // this is bad if it get's here + } + */ } break; - case EV_ANGER1: //Say when acquire an enemy when didn't have one before + case EV_ANGER1: // Say when acquire an enemy when didn't have one before case EV_ANGER2: case EV_ANGER3: DEBUGNAME("EV_ANGERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT); break; - case EV_VICTORY1: //Say when killed an enemy + case EV_VICTORY1: // Say when killed an enemy case EV_VICTORY2: case EV_VICTORY3: DEBUGNAME("EV_VICTORYx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT); break; - case EV_CONFUSE1: //Say when confused + case EV_CONFUSE1: // Say when confused case EV_CONFUSE2: case EV_CONFUSE3: DEBUGNAME("EV_CONFUSEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT); break; - case EV_PUSHED1: //Say when pushed + case EV_PUSHED1: // Say when pushed case EV_PUSHED2: case EV_PUSHED3: DEBUGNAME("EV_PUSHEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT); break; - case EV_CHOKE1: //Say when choking + case EV_CHOKE1: // Say when choking case EV_CHOKE2: case EV_CHOKE3: DEBUGNAME("EV_CHOKEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT); break; - case EV_FFWARN: //Warn ally to stop shooting you + case EV_FFWARN: // Warn ally to stop shooting you DEBUGNAME("EV_FFWARN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT); break; - case EV_FFTURN: //Turn on ally after being shot by them + case EV_FFTURN: // Turn on ally after being shot by them DEBUGNAME("EV_FFTURN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT); break; - //extra sounds for ST + // extra sounds for ST case EV_CHASE1: case EV_CHASE2: case EV_CHASE3: DEBUGNAME("EV_CHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA); break; case EV_COVER1: case EV_COVER2: @@ -948,7 +868,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_COVER4: case EV_COVER5: DEBUGNAME("EV_COVERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA); break; case EV_DETECTED1: case EV_DETECTED2: @@ -956,46 +876,46 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DETECTED4: case EV_DETECTED5: DEBUGNAME("EV_DETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA); break; case EV_GIVEUP1: case EV_GIVEUP2: case EV_GIVEUP3: case EV_GIVEUP4: DEBUGNAME("EV_GIVEUPx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA); break; case EV_LOOK1: case EV_LOOK2: DEBUGNAME("EV_LOOKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA); break; case EV_LOST1: DEBUGNAME("EV_LOST1"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*lost1.wav", CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*lost1.wav", CS_EXTRA); break; case EV_OUTFLANK1: case EV_OUTFLANK2: DEBUGNAME("EV_OUTFLANKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA); break; case EV_ESCAPING1: case EV_ESCAPING2: case EV_ESCAPING3: DEBUGNAME("EV_ESCAPINGx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA); break; case EV_SIGHT1: case EV_SIGHT2: case EV_SIGHT3: DEBUGNAME("EV_SIGHTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA); break; case EV_SOUND1: case EV_SOUND2: case EV_SOUND3: DEBUGNAME("EV_SOUNDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA); break; case EV_SUSPICIOUS1: case EV_SUSPICIOUS2: @@ -1003,89 +923,89 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SUSPICIOUS4: case EV_SUSPICIOUS5: DEBUGNAME("EV_SUSPICIOUSx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA); break; - //extra sounds for Jedi + // extra sounds for Jedi case EV_COMBAT1: case EV_COMBAT2: case EV_COMBAT3: DEBUGNAME("EV_COMBATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI); break; case EV_JDETECTED1: case EV_JDETECTED2: case EV_JDETECTED3: DEBUGNAME("EV_JDETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI); break; case EV_TAUNT1: case EV_TAUNT2: case EV_TAUNT3: DEBUGNAME("EV_TAUNTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI); break; case EV_JCHASE1: case EV_JCHASE2: case EV_JCHASE3: DEBUGNAME("EV_JCHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI); break; case EV_JLOST1: case EV_JLOST2: case EV_JLOST3: DEBUGNAME("EV_JLOSTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI); break; case EV_DEFLECT1: case EV_DEFLECT2: case EV_DEFLECT3: DEBUGNAME("EV_DEFLECTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI); break; case EV_GLOAT1: case EV_GLOAT2: case EV_GLOAT3: DEBUGNAME("EV_GLOATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI); break; case EV_PUSHFAIL: DEBUGNAME("EV_PUSHFAIL"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*pushfail.wav", CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*pushfail.wav", CS_JEDI); break; case EV_USE_FORCE: DEBUGNAME("EV_USE_FORCEITEM"); - CG_UseForce( cent ); + CG_UseForce(cent); break; case EV_USE_ITEM: DEBUGNAME("EV_USE_ITEM"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_INV_BINOCULARS: DEBUGNAME("EV_USE_INV_BINOCULARS"); - UseItem(INV_ELECTROBINOCULARS ); + UseItem(INV_ELECTROBINOCULARS); break; case EV_USE_INV_BACTA: DEBUGNAME("EV_USE_INV_BACTA"); - UseItem(INV_BACTA_CANISTER ); + UseItem(INV_BACTA_CANISTER); break; case EV_USE_INV_SEEKER: DEBUGNAME("EV_USE_INV_SEEKER"); - UseItem(INV_SEEKER ); + UseItem(INV_SEEKER); break; case EV_USE_INV_LIGHTAMP_GOGGLES: DEBUGNAME("EV_USE_INV_LIGHTAMP_GOGGLES"); - UseItem(INV_LIGHTAMP_GOGGLES ); + UseItem(INV_LIGHTAMP_GOGGLES); break; case EV_USE_INV_SENTRY: DEBUGNAME("EV_USE_INV_SENTRY"); - UseItem(INV_SENTRY ); + UseItem(INV_SENTRY); break; case EV_DEBUG_LINE: @@ -1095,43 +1015,40 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { default: DEBUGNAME("UNKNOWN"); - CG_Error( "Unknown event: %i", event ); + CG_Error("Unknown event: %i", event); break; } - } - /* ============== CG_CheckEvents ============== */ -void CG_CheckEvents( centity_t *cent ) { +void CG_CheckEvents(centity_t *cent) { // check for event-only entities - if ( cent->currentState.eType > ET_EVENTS ) { - if ( cent->previousEvent ) { - return; // already fired + if (cent->currentState.eType > ET_EVENTS) { + if (cent->previousEvent) { + return; // already fired } cent->previousEvent = 1; cent->currentState.event = cent->currentState.eType - ET_EVENTS; } else { // check for events riding with another entity - if ( cent->currentState.event == cent->previousEvent ) { + if (cent->currentState.event == cent->previousEvent) { return; } cent->previousEvent = cent->currentState.event; - if ( ( cent->currentState.event & ~EV_EVENT_BITS ) == 0 ) { + if ((cent->currentState.event & ~EV_EVENT_BITS) == 0) { return; } } // calculate the position at exactly the frame time - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); - CG_SetEntitySoundPosition( cent ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); + CG_SetEntitySoundPosition(cent); - CG_EntityEvent( cent, cent->lerpOrigin ); + CG_EntityEvent(cent, cent->lerpOrigin); } - diff --git a/code/cgame/cg_headers.cpp b/code/cgame/cg_headers.cpp index d39130e306..126fb51828 100644 --- a/code/cgame/cg_headers.cpp +++ b/code/cgame/cg_headers.cpp @@ -21,4 +21,3 @@ along with this program; if not, see . */ #include "cg_headers.h" - diff --git a/code/cgame/cg_info.cpp b/code/cgame/cg_info.cpp index 17abcfee02..38cced8ea8 100644 --- a/code/cgame/cg_info.cpp +++ b/code/cgame/cg_info.cpp @@ -26,27 +26,15 @@ along with this program; if not, see . #include "cg_media.h" #include "../game/objectives.h" - // For printing objectives -static const short objectiveStartingYpos = 75; // Y starting position for objective text -static const short objectiveStartingXpos = 60; // X starting position for objective text -static const int objectiveTextBoxWidth = 500; // Width (in pixels) of text box -static const int objectiveTextBoxHeight = 300; // Height (in pixels) of text box - -const char *showLoadPowersName[] = -{ - "SP_INGAME_HEAL2", - "SP_INGAME_JUMP2", - "SP_INGAME_SPEED2", - "SP_INGAME_PUSH2", - "SP_INGAME_PULL2", - "SP_INGAME_MINDTRICK2", - "SP_INGAME_GRIP2", - "SP_INGAME_LIGHTNING2", - "SP_INGAME_SABER_THROW2", - "SP_INGAME_SABER_OFFENSE2", - "SP_INGAME_SABER_DEFENSE2", - NULL, +static const short objectiveStartingYpos = 75; // Y starting position for objective text +static const short objectiveStartingXpos = 60; // X starting position for objective text +static const int objectiveTextBoxWidth = 500; // Width (in pixels) of text box +static const int objectiveTextBoxHeight = 300; // Height (in pixels) of text box + +const char *showLoadPowersName[] = { + "SP_INGAME_HEAL2", "SP_INGAME_JUMP2", "SP_INGAME_SPEED2", "SP_INGAME_PUSH2", "SP_INGAME_PULL2", "SP_INGAME_MINDTRICK2", + "SP_INGAME_GRIP2", "SP_INGAME_LIGHTNING2", "SP_INGAME_SABER_THROW2", "SP_INGAME_SABER_OFFENSE2", "SP_INGAME_SABER_DEFENSE2", NULL, }; #define MAX_OBJ_GRAPHICS 4 @@ -62,126 +50,102 @@ ObjectivePrint_Line Print a single mission objective ==================== */ -static void ObjectivePrint_Line(const int color, const int objectIndex, int &missionYcnt) -{ - char *str,*strBegin; - int y,pixelLen,charLen,i; +static void ObjectivePrint_Line(const int color, const int objectIndex, int &missionYcnt) { + char *str, *strBegin; + int y, pixelLen, charLen, i; const int maxHoldText = 1024; char holdText[maxHoldText]; char finalText[2048]; - qhandle_t graphic; + qhandle_t graphic; int iYPixelsPerLine = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f); - cgi_SP_GetStringTextString( va("OBJECTIVES_%s",objectiveTable[objectIndex].name) , finalText, sizeof(finalText) ); + cgi_SP_GetStringTextString(va("OBJECTIVES_%s", objectiveTable[objectIndex].name), finalText, sizeof(finalText)); // A hack to be able to count prisoners - if (objectIndex==T2_RANCOR_OBJ5) - { + if (objectIndex == T2_RANCOR_OBJ5) { char value[64]; - int currTotal, minTotal; + int currTotal, minTotal; - gi.Cvar_VariableStringBuffer("ui_prisonerobj_currtotal",value,sizeof(value)); + gi.Cvar_VariableStringBuffer("ui_prisonerobj_currtotal", value, sizeof(value)); currTotal = atoi(value); - gi.Cvar_VariableStringBuffer("ui_prisonerobj_maxtotal",value,sizeof(value)); + gi.Cvar_VariableStringBuffer("ui_prisonerobj_maxtotal", value, sizeof(value)); minTotal = atoi(value); - Q_strncpyz(finalText, va(finalText,currTotal,minTotal), sizeof(finalText)); + Q_strncpyz(finalText, va(finalText, currTotal, minTotal), sizeof(finalText)); } pixelLen = cgi_R_Font_StrLenPixels(finalText, cgs.media.qhFontMedium, 1.0f); str = finalText; - if (cgi_Language_IsAsian()) - { + if (cgi_Language_IsAsian()) { // this is execrable, and should NOT have had to've been done now, but... // - extern const char *CG_DisplayBoxedText( int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color); + extern const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, + const vec4_t v4Color); extern int giLinesOutput; extern float gfAdvanceHack; - gfAdvanceHack = 1.0f; // override internal vertical advance + gfAdvanceHack = 1.0f; // override internal vertical advance y = objectiveStartingYpos + (iYPixelsPerLine * missionYcnt); // Advance line if a graphic has printed - for (i=0;i objectiveTextBoxWidth ) - { //Reached max length of this line - //step back until we find a space - while ((charLen>10) && (*str != ' ' )) - { + if (pixelLen > objectiveTextBoxWidth) { // Reached max length of this line + // step back until we find a space + while ((charLen > 10) && (*str != ' ')) { --str; --charLen; } - if (*str==' ') - { - ++str; // To get past space + if (*str == ' ') { + ++str; // To get past space } - assert( charLengent->client->sess.mission_objectives[i].display) - { + if (cent->gent->client->sess.mission_objectives[i].display) { // Calculate the Y position - totalY = objectiveStartingYpos + (iYPixelsPerLine * (missionYcnt))+(iYPixelsPerLine/2); + totalY = objectiveStartingYpos + (iYPixelsPerLine * (missionYcnt)) + (iYPixelsPerLine / 2); // Draw graphics that show if mission has been accomplished or not cgi_R_SetColor(colorTable[CT_BLUE3]); - CG_DrawPic( (graphicXpos), (totalY-graphicYOffset), graphic_size, graphic_size, cgs.media.messageObjCircle); // Circle in front - if (cent->gent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_SUCCEEDED) - { - CG_DrawPic( (graphicXpos), (totalY-graphicYOffset), graphic_size, graphic_size, cgs.media.messageLitOn); // Center Dot + CG_DrawPic((graphicXpos), (totalY - graphicYOffset), graphic_size, graphic_size, cgs.media.messageObjCircle); // Circle in front + if (cent->gent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_SUCCEEDED) { + CG_DrawPic((graphicXpos), (totalY - graphicYOffset), graphic_size, graphic_size, cgs.media.messageLitOn); // Center Dot } // Print current objective text - ObjectivePrint_Line(CT_WHITE, i, missionYcnt ); + ObjectivePrint_Line(CT_WHITE, i, missionYcnt); } } // No mission text? - if (!missionYcnt) - { + if (!missionYcnt) { // Set the message a quarter of the way down and in the center of the text box int messageYPosition = objectiveStartingYpos + (objectiveTextBoxHeight / 4); - cgi_SP_GetStringTextString( "SP_INGAME_OBJNONE", text, sizeof(text) ); - int messageXPosition = objectiveStartingXpos + (objectiveTextBoxWidth/2) - (cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.0f) /2); + cgi_SP_GetStringTextString("SP_INGAME_OBJNONE", text, sizeof(text)); + int messageXPosition = objectiveStartingXpos + (objectiveTextBoxWidth / 2) - (cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.0f) / 2); - cgi_R_Font_DrawString ( - messageXPosition, - messageYPosition, - text, - colorTable[CT_WHITE], - cgs.media.qhFontMedium, - -1, - 1.0f); + cgi_R_Font_DrawString(messageXPosition, messageYPosition, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); } } @@ -409,16 +343,15 @@ static void CG_LoadScreen_PersonalInfo(void) } */ -static void CG_LoadBar(void) -{ +static void CG_LoadBar(void) { const int numticks = 9, tickwidth = 40, tickheight = 8; const int tickpadx = 20, tickpady = 12; const int capwidth = 8; - const int barwidth = numticks*tickwidth+tickpadx*2+capwidth*2, barleft = ((640-barwidth)/2); - const int barheight = tickheight + tickpady*2, bartop = 475-barheight; - const int capleft = barleft+tickpadx, tickleft = capleft+capwidth, ticktop = bartop+tickpady; + const int barwidth = numticks * tickwidth + tickpadx * 2 + capwidth * 2, barleft = ((640 - barwidth) / 2); + const int barheight = tickheight + tickpady * 2, bartop = 475 - barheight; + const int capleft = barleft + tickpadx, tickleft = capleft + capwidth, ticktop = bartop + tickpady; - cgi_R_SetColor( colorTable[CT_WHITE]); + cgi_R_SetColor(colorTable[CT_WHITE]); // Draw background CG_DrawPic(barleft, bartop, barwidth, barheight, cgs.media.levelLoad); @@ -426,82 +359,67 @@ static void CG_LoadBar(void) CG_DrawPic(tickleft, ticktop, -capwidth, tickheight, cgs.media.loadTickCap); // Draw bar - CG_DrawPic(tickleft, ticktop, tickwidth*cg.loadLCARSStage, tickheight, cgs.media.loadTick); + CG_DrawPic(tickleft, ticktop, tickwidth * cg.loadLCARSStage, tickheight, cgs.media.loadTick); // Draw right cap - CG_DrawPic(tickleft+tickwidth*cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadTickCap); + CG_DrawPic(tickleft + tickwidth * cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadTickCap); } -int CG_WeaponCheck( int weaponIndex ); +int CG_WeaponCheck(int weaponIndex); // For printing load screen icons -const int MAXLOADICONSPERROW = 8; // Max icons displayed per row -const int MAXLOADWEAPONS = 16; -const int MAXLOAD_FORCEICONSIZE = 40; // Size of force power icons -const int MAXLOAD_FORCEICONPAD = 12; // Padding space between icons +const int MAXLOADICONSPERROW = 8; // Max icons displayed per row +const int MAXLOADWEAPONS = 16; +const int MAXLOAD_FORCEICONSIZE = 40; // Size of force power icons +const int MAXLOAD_FORCEICONPAD = 12; // Padding space between icons -static int CG_DrawLoadWeaponsPrintRow( const char *itemName, int weaponsBits,int rowIconCnt, int startIndex) -{ - int i,endIndex=0, printedIconCnt=0; - int iconSize; - int holdX,x,y,pad; - int yOffset = 0; - int width,height; - vec4_t color; - qhandle_t background; - - if (!cgi_UI_GetMenuItemInfo( - "loadScreen", - itemName, - &x, - &y, - &width, - &height, - color, - &background)) - { - return(0); +static int CG_DrawLoadWeaponsPrintRow(const char *itemName, int weaponsBits, int rowIconCnt, int startIndex) { + int i, endIndex = 0, printedIconCnt = 0; + int iconSize; + int holdX, x, y, pad; + int yOffset = 0; + int width, height; + vec4_t color; + qhandle_t background; + + if (!cgi_UI_GetMenuItemInfo("loadScreen", itemName, &x, &y, &width, &height, color, &background)) { + return (0); } - cgi_R_SetColor( color ); + cgi_R_SetColor(color); iconSize = 60; pad = 12; // calculate placement of weapon icons - holdX = x + (width - ((iconSize*rowIconCnt) + (pad * (rowIconCnt-1))))/2; + holdX = x + (width - ((iconSize * rowIconCnt) + (pad * (rowIconCnt - 1)))) / 2; - for (i=startIndex;iweaponIconNoAmmo ); - // } - // else - { - CG_DrawPic( holdX, y+yOffset, iconSize, iconSize, weaponInfo->weaponIcon ); - } + // NOTE : during loading screen always show the have ammo icon + // if (!CG_WeaponCheck(i)) + // { + // CG_DrawPic( holdX, y+yOffset, iconSize, iconSize, weaponInfo->weaponIconNoAmmo ); + // } + // else + { CG_DrawPic(holdX, y + yOffset, iconSize, iconSize, weaponInfo->weaponIcon); } printedIconCnt++; - if (printedIconCnt==MAXLOADICONSPERROW) - { + if (printedIconCnt == MAXLOADICONSPERROW) { break; } - holdX += (iconSize+pad); + holdX += (iconSize + pad); } } @@ -510,110 +428,89 @@ static int CG_DrawLoadWeaponsPrintRow( const char *itemName, int weaponsBits,int // Print weapons the player is carrying // Two rows print if there are too many -static void CG_DrawLoadWeapons( int weaponBits ) -{ - int i,endIndex=0; - int iconCnt,rowIconCnt; +static void CG_DrawLoadWeapons(int weaponBits) { + int i, endIndex = 0; + int iconCnt, rowIconCnt; // count the number of weapons owned iconCnt = 0; - for ( i = 1 ; i < MAXLOADWEAPONS ; i++ ) - { - if ( weaponBits & ( 1 << i ) ) - { + for (i = 1; i < MAXLOADWEAPONS; i++) { + if (weaponBits & (1 << i)) { iconCnt++; } } - if (!iconCnt) // If no weapons, don't display + if (!iconCnt) // If no weapons, don't display { return; } // Single line of icons - if (iconCnt<=MAXLOADICONSPERROW) - { - CG_DrawLoadWeaponsPrintRow("weaponicons_singlerow", weaponBits, iconCnt,0); + if (iconCnt <= MAXLOADICONSPERROW) { + CG_DrawLoadWeaponsPrintRow("weaponicons_singlerow", weaponBits, iconCnt, 0); } // Two lines of icons - else - { + else { // Print top row - endIndex = CG_DrawLoadWeaponsPrintRow("weaponicons_row1", weaponBits, MAXLOADICONSPERROW,0); + endIndex = CG_DrawLoadWeaponsPrintRow("weaponicons_row1", weaponBits, MAXLOADICONSPERROW, 0); // Print second row rowIconCnt = iconCnt - MAXLOADICONSPERROW; - CG_DrawLoadWeaponsPrintRow("weaponicons_row2", weaponBits, rowIconCnt,endIndex+1); + CG_DrawLoadWeaponsPrintRow("weaponicons_row2", weaponBits, rowIconCnt, endIndex + 1); } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } +static int CG_DrawLoadForcePrintRow(const char *itemName, int forceBits, int rowIconCnt, int startIndex) { + int i, endIndex = 0, printedIconCnt = 0; + int holdX, x, y; + int yOffset = 0; + int width, height; + vec4_t color; + qhandle_t background; -static int CG_DrawLoadForcePrintRow( const char *itemName, int forceBits,int rowIconCnt, int startIndex) -{ - int i,endIndex=0, printedIconCnt=0; - int holdX,x,y; - int yOffset = 0; - int width,height; - vec4_t color; - qhandle_t background; - - if (!cgi_UI_GetMenuItemInfo( - "loadScreen", - itemName, - &x, - &y, - &width, - &height, - color, - &background)) - { - return(0); + if (!cgi_UI_GetMenuItemInfo("loadScreen", itemName, &x, &y, &width, &height, color, &background)) { + return (0); } - cgi_R_SetColor( color ); + cgi_R_SetColor(color); // calculate placement of weapon icons - holdX = x + (width - ((MAXLOAD_FORCEICONSIZE*rowIconCnt) + (MAXLOAD_FORCEICONPAD * (rowIconCnt-1))))/2; + holdX = x + (width - ((MAXLOAD_FORCEICONSIZE * rowIconCnt) + (MAXLOAD_FORCEICONPAD * (rowIconCnt - 1)))) / 2; - for (i=startIndex;ips.stats[STAT_HEALTH], - &iDummy, // &client->ps.stats[STAT_ARMOR], - &*weaponBits,// &client->ps.stats[STAT_WEAPONS], - &iDummy, // &client->ps.stats[STAT_ITEMS], - &iDummy, // &client->ps.weapon, - &iDummy, // &client->ps.weaponstate, - &iDummy, // &client->ps.batteryCharge, - &fDummy, // &client->ps.viewangles[0], - &fDummy, // &client->ps.viewangles[1], - &fDummy, // &client->ps.viewangles[2], - //force power data - &*forceBits, // &client->ps.forcePowersKnown, - &iDummy // &client->ps.forcePower, - - ); + if (s[0]) { + // |general info |-force powers + sscanf(s, "%i %i %i %i %i %i %i %f %f %f %i %i", + &iDummy, // &client->ps.stats[STAT_HEALTH], + &iDummy, // &client->ps.stats[STAT_ARMOR], + &*weaponBits, // &client->ps.stats[STAT_WEAPONS], + &iDummy, // &client->ps.stats[STAT_ITEMS], + &iDummy, // &client->ps.weapon, + &iDummy, // &client->ps.weaponstate, + &iDummy, // &client->ps.batteryCharge, + &fDummy, // &client->ps.viewangles[0], + &fDummy, // &client->ps.viewangles[1], + &fDummy, // &client->ps.viewangles[2], + // force power data + &*forceBits, // &client->ps.forcePowersKnown, + &iDummy // &client->ps.forcePower, + + ); } // the new JK2 stuff - force powers, etc... // - gi.Cvar_VariableStringBuffer( "playerfplvl", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { + gi.Cvar_VariableStringBuffer("playerfplvl", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { /* While there are tokens in "s" */ loadForcePowerLevel[i++] = atoi(var); /* Get next token: */ - var = strtok( NULL, " " ); + var = strtok(NULL, " "); } } @@ -714,73 +603,49 @@ CG_DrawLoadingScreen Load screen displays the map pic, the mission briefing and weapons/force powers ==================== */ -static void CG_DrawLoadingScreen( qhandle_t levelshot ,const char *mapName) -{ - int xPos,yPos,width,height; - vec4_t color; - qhandle_t background; - int weapons=0, forcepowers=0; +static void CG_DrawLoadingScreen(qhandle_t levelshot, const char *mapName) { + int xPos, yPos, width, height; + vec4_t color; + qhandle_t background; + int weapons = 0, forcepowers = 0; // Get mission briefing for load screen - if (cgi_SP_GetStringTextString( va("BRIEFINGS_%s",mapName), NULL, 0 ) == 0) - { - cgi_Cvar_Set( "ui_missionbriefing", "@BRIEFINGS_NONE" ); - } - else - { - cgi_Cvar_Set( "ui_missionbriefing", va("@BRIEFINGS_%s",mapName) ); + if (cgi_SP_GetStringTextString(va("BRIEFINGS_%s", mapName), NULL, 0) == 0) { + cgi_Cvar_Set("ui_missionbriefing", "@BRIEFINGS_NONE"); + } else { + cgi_Cvar_Set("ui_missionbriefing", va("@BRIEFINGS_%s", mapName)); } // Print background - if (cgi_UI_GetMenuItemInfo( - "loadScreen", - "background", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, background ); + if (cgi_UI_GetMenuItemInfo("loadScreen", "background", &xPos, &yPos, &width, &height, color, &background)) { + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, background); } // Print level pic - if (cgi_UI_GetMenuItemInfo( - "loadScreen", - "mappic", - &xPos, - &yPos, - &width, - &height, - color, - &background)) - { - //if (!levelshot) + if (cgi_UI_GetMenuItemInfo("loadScreen", "mappic", &xPos, &yPos, &width, &height, color, &background)) { + // if (!levelshot) //{// No level shot so use screenshot. - // CG_DrawPic( xPos, yPos, 1, 1, 0); //force the tess to flush + // CG_DrawPic( xPos, yPos, 1, 1, 0); //force the tess to flush // cgi_R_DrawScreenShot( xPos, yPos+height, width, -height ); //} - //else + // else { - cgi_R_SetColor( color ); - CG_DrawPic( xPos, yPos, width, height, levelshot ); + cgi_R_SetColor(color); + CG_DrawPic(xPos, yPos, width, height, levelshot); } } // Get player weapons and force power info - CG_GetLoadScreenInfo(&weapons,&forcepowers); + CG_GetLoadScreenInfo(&weapons, &forcepowers); // Print weapon icons - if (weapons) - { + if (weapons) { CG_DrawLoadWeapons(weapons); } // Print force power icons - if (forcepowers) - { + if (forcepowers) { CG_DrawLoadForcePowers(forcepowers); } } @@ -792,66 +657,62 @@ CG_DrawInformation Draw all the status / pacifier stuff during level loading ==================== */ -void CG_DrawInformation( void ) { - int y; +void CG_DrawInformation(void) { + int y; // draw the dialog background - const char *info = CG_ConfigString( CS_SERVERINFO ); - const char *s = Info_ValueForKey( info, "mapname" ); - - qhandle_t levelshot; - - extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; // hack! (hey, it's the last week of coding, ok? -// if ( g_eSavedGameJustLoaded == eFULL ) -// { -// levelshot = 0; //use the loaded thumbnail instead of the levelshot -// } -// else - { - levelshot = cgi_R_RegisterShaderNoMip( va( "levelshots/%s", s ) ); - #ifndef FINAL_BUILD - if (!levelshot && !strncmp(s, "work/",5) ) - { - levelshot = cgi_R_RegisterShaderNoMip( va( "levelshots/%s", s+5 ) ); + const char *info = CG_ConfigString(CS_SERVERINFO); + const char *s = Info_ValueForKey(info, "mapname"); + + qhandle_t levelshot; + + extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; // hack! (hey, it's the last week of coding, ok? + // if ( g_eSavedGameJustLoaded == eFULL ) + // { + // levelshot = 0; //use the loaded thumbnail instead of the levelshot + // } + // else + { + levelshot = cgi_R_RegisterShaderNoMip(va("levelshots/%s", s)); +#ifndef FINAL_BUILD + if (!levelshot && !strncmp(s, "work/", 5)) { + levelshot = cgi_R_RegisterShaderNoMip(va("levelshots/%s", s + 5)); } - #endif +#endif if (!levelshot) { - levelshot = cgi_R_RegisterShaderNoMip( "menu/art/unknownmap" ); + levelshot = cgi_R_RegisterShaderNoMip("menu/art/unknownmap"); } } - if ( g_eSavedGameJustLoaded != eFULL && !strcmp(s,"yavin1") )//special case for first map! + if (g_eSavedGameJustLoaded != eFULL && !strcmp(s, "yavin1")) // special case for first map! { - char text[1024]={0}; + char text[1024] = {0}; // - cgi_R_SetColor( colorTable[CT_BLACK] ); - CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_BLACK]); + CG_DrawPic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, cgs.media.whiteShader); - cgi_SP_GetStringTextString( "SP_INGAME_ALONGTIME", text, sizeof(text) ); + cgi_SP_GetStringTextString("SP_INGAME_ALONGTIME", text, sizeof(text)); - int w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString((320)-(w/2), 140, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontMedium, -1, 1.0f); - } - else - { + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.0f); + cgi_R_Font_DrawString((320) - (w / 2), 140, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontMedium, -1, 1.0f); + } else { CG_DrawLoadingScreen(levelshot, s); - cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "loadscreen" ), qtrue ); - //cgi_UI_MenuPaintAll(); + cgi_UI_Menu_Paint(cgi_UI_GetMenuByName("loadscreen"), qtrue); + // cgi_UI_MenuPaintAll(); } CG_LoadBar(); - // the first 150 rows are reserved for the client connection // screen to write into -// if ( cg.processedSnapshotNum == 0 ) + // if ( cg.processedSnapshotNum == 0 ) { // still loading // print the current item being loaded #ifdef _DEBUG - cgi_R_Font_DrawString( 40, 416, va("LOADING ... %s",cg.infoScreenText),colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f ); + cgi_R_Font_DrawString(40, 416, va("LOADING ... %s", cg.infoScreenText), colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); #endif } @@ -859,19 +720,15 @@ void CG_DrawInformation( void ) { y = 20; // map-specific message (long map name) - s = CG_ConfigString( CS_MESSAGE ); - - if ( s[0] ) - { - if (s[0] == '@') - { - char text[1024]={0}; - cgi_SP_GetStringTextString( s+1, text, sizeof(text) ); - cgi_R_Font_DrawString( 15, y, va("\"%s\"",text),colorTable[CT_WHITE],cgs.media.qhFontMedium, -1, 1.0f ); - } - else - { - cgi_R_Font_DrawString( 15, y, va("\"%s\"",s),colorTable[CT_WHITE],cgs.media.qhFontMedium, -1, 1.0f ); + s = CG_ConfigString(CS_MESSAGE); + + if (s[0]) { + if (s[0] == '@') { + char text[1024] = {0}; + cgi_SP_GetStringTextString(s + 1, text, sizeof(text)); + cgi_R_Font_DrawString(15, y, va("\"%s\"", text), colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); + } else { + cgi_R_Font_DrawString(15, y, va("\"%s\"", s), colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); } y += 20; } diff --git a/code/cgame/cg_lights.cpp b/code/cgame/cg_lights.cpp index 4891e135af..7086a9583f 100644 --- a/code/cgame/cg_lights.cpp +++ b/code/cgame/cg_lights.cpp @@ -23,29 +23,27 @@ along with this program; if not, see . #include "cg_headers.h" typedef struct clightstyle_s { - int length; - color4ub_t value; - color4ub_t map[MAX_QPATH]; + int length; + color4ub_t value; + color4ub_t map[MAX_QPATH]; } clightstyle_t; -static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; -static int lastofs; +static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; +static int lastofs; /* ================ FX_ClearLightStyles ================ */ -void CG_ClearLightStyles (void) -{ - int i; +void CG_ClearLightStyles(void) { + int i; - memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); + memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); lastofs = -1; - for(i=0;ilength) - { + for (i = 0, ls = cl_lightstyle; i < MAX_LIGHT_STYLES; i++, ls++) { + if (!ls->length) { ls->value[0] = ls->value[1] = ls->value[2] = ls->value[3] = 255; - } - else if (ls->length == 1) - { + } else if (ls->length == 1) { ls->value[0] = ls->map[0][0]; ls->value[1] = ls->map[0][1]; ls->value[2] = ls->map[0][2]; - ls->value[3] = 255; //ls->map[0][3]; - } - else - { - ls->value[0] = ls->map[ofs%ls->length][0]; - ls->value[1] = ls->map[ofs%ls->length][1]; - ls->value[2] = ls->map[ofs%ls->length][2]; - ls->value[3] = 255; //ls->map[ofs%ls->length][3]; + ls->value[3] = 255; // ls->map[0][3]; + } else { + ls->value[0] = ls->map[ofs % ls->length][0]; + ls->value[1] = ls->map[ofs % ls->length][1]; + ls->value[2] = ls->map[ofs % ls->length][2]; + ls->value[3] = 255; // ls->map[ofs%ls->length][3]; } const byteAlias_t *ba = (byteAlias_t *)&ls->value; - trap_R_SetLightStyle( i, ba->i ); + trap_R_SetLightStyle(i, ba->i); } } -void CG_SetLightstyle (int i) -{ - const char *s; - int j, k; +void CG_SetLightstyle(int i) { + const char *s; + int j, k; - s = CG_ConfigString( i+CS_LIGHT_STYLES ); - j = strlen (s); - if (j >= MAX_QPATH) - { - Com_Error (ERR_DROP, "svc_lightstyle length=%i", j); + s = CG_ConfigString(i + CS_LIGHT_STYLES); + j = strlen(s); + if (j >= MAX_QPATH) { + Com_Error(ERR_DROP, "svc_lightstyle length=%i", j); } - cl_lightstyle[(i/3)].length = j; - for (k=0 ; k. #include "cg_headers.h" - #include "cg_media.h" -#define MAX_LOCAL_ENTITIES 512 -localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; -localEntity_t cg_activeLocalEntities; // double linked list -localEntity_t *cg_freeLocalEntities; // single linked list +#define MAX_LOCAL_ENTITIES 512 +localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; +localEntity_t cg_activeLocalEntities; // double linked list +localEntity_t *cg_freeLocalEntities; // single linked list /* =================== @@ -42,27 +41,26 @@ This is called at startup and for tournement restarts =================== */ -void CG_InitLocalEntities( void ) { - int i; +void CG_InitLocalEntities(void) { + int i; - memset( cg_localEntities, 0, sizeof( cg_localEntities ) ); + memset(cg_localEntities, 0, sizeof(cg_localEntities)); cg_activeLocalEntities.next = &cg_activeLocalEntities; cg_activeLocalEntities.prev = &cg_activeLocalEntities; cg_freeLocalEntities = cg_localEntities; - for ( i = 0 ; i < MAX_LOCAL_ENTITIES - 1 ; i++ ) { - cg_localEntities[i].next = &cg_localEntities[i+1]; + for (i = 0; i < MAX_LOCAL_ENTITIES - 1; i++) { + cg_localEntities[i].next = &cg_localEntities[i + 1]; } } - /* ================== CG_FreeLocalEntity ================== */ -void CG_FreeLocalEntity( localEntity_t *le ) { - if ( !le->prev ) { - CG_Error( "CG_FreeLocalEntity: not active" ); +void CG_FreeLocalEntity(localEntity_t *le) { + if (!le->prev) { + CG_Error("CG_FreeLocalEntity: not active"); } // remove from the doubly linked active list @@ -81,19 +79,19 @@ CG_AllocLocalEntity Will allways succeed, even if it requires freeing an old active entity =================== */ -localEntity_t *CG_AllocLocalEntity( void ) { - localEntity_t *le; +localEntity_t *CG_AllocLocalEntity(void) { + localEntity_t *le; - if ( !cg_freeLocalEntities ) { + if (!cg_freeLocalEntities) { // no free entities, so free the one at the end of the chain // remove the oldest active entity - CG_FreeLocalEntity( cg_activeLocalEntities.prev ); + CG_FreeLocalEntity(cg_activeLocalEntities.prev); } le = cg_freeLocalEntities; cg_freeLocalEntities = cg_freeLocalEntities->next; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->next = cg_activeLocalEntities.next; @@ -104,7 +102,6 @@ localEntity_t *CG_AllocLocalEntity( void ) { return le; } - /* ==================================================================================== @@ -116,76 +113,64 @@ or generates more localentities along a trail. ==================================================================================== */ - /* ================ CG_FragmentBounceSound ================ */ -void CG_FragmentBounceSound( localEntity_t *le, trace_t *trace ) -{ +void CG_FragmentBounceSound(localEntity_t *le, trace_t *trace) { // half the fragments will make a bounce sounds - if ( rand() & 1 ) - { - sfxHandle_t s = 0; + if (rand() & 1) { + sfxHandle_t s = 0; - switch( le->leBounceSoundType ) - { + switch (le->leBounceSoundType) { case LEBS_ROCK: - s = cgs.media.rockBounceSound[Q_irand(0,1)]; + s = cgs.media.rockBounceSound[Q_irand(0, 1)]; break; case LEBS_METAL: - s = cgs.media.metalBounceSound[Q_irand(0,1)];// FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... + s = cgs.media.metalBounceSound[Q_irand(0, 1)]; // FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... break; default: break; } - if ( s ) - { - cgi_S_StartSound( trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s ); + if (s) { + cgi_S_StartSound(trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s); } // bouncers only make the sound once... // FIXME: arbitrary...change if it bugs you le->leBounceSoundType = LEBS_NONE; - } - else if ( rand() & 1 ) - { + } else if (rand() & 1) { // we may end up bouncing again, but each bounce reduces the chance of playing the sound again or they may make a lot of noise when they settle // FIXME: maybe just always do this?? le->leBounceSoundType = LEBS_NONE; } } - /* ================ CG_ReflectVelocity ================ */ -void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) -{ - vec3_t velocity; - float dot; - int hitTime; +void CG_ReflectVelocity(localEntity_t *le, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane hitTime = cg.time - cg.frametime + cg.frametime * trace->fraction; - EvaluateTrajectoryDelta( &le->pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, le->pos.trDelta ); + EvaluateTrajectoryDelta(&le->pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, le->pos.trDelta); - VectorScale( le->pos.trDelta, le->bounceFactor, le->pos.trDelta ); + VectorScale(le->pos.trDelta, le->bounceFactor, le->pos.trDelta); - VectorCopy( trace->endpos, le->pos.trBase ); + VectorCopy(trace->endpos, le->pos.trBase); le->pos.trTime = cg.time; // check for stop, making sure that even on low FPS systems it doesn't bobble - if ( trace->allsolid || - ( trace->plane.normal[2] > 0 && - ( le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2] ) ) ) - { + if (trace->allsolid || (trace->plane.normal[2] > 0 && (le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2]))) { le->pos.trType = TR_STATIONARY; } } @@ -195,63 +180,57 @@ void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) CG_AddFragment ================ */ -void CG_AddFragment( localEntity_t *le ) -{ - vec3_t newOrigin; - trace_t trace; +void CG_AddFragment(localEntity_t *le) { + vec3_t newOrigin; + trace_t trace; // used to sink into the ground, but it looks better to maybe just fade them out - int t; + int t; t = le->endTime - cg.time; - if ( t < FRAG_FADE_TIME ) - { + if (t < FRAG_FADE_TIME) { le->refEntity.renderfx |= RF_ALPHA_FADE; le->refEntity.shaderRGBA[0] = le->refEntity.shaderRGBA[1] = le->refEntity.shaderRGBA[2] = 255; le->refEntity.shaderRGBA[3] = ((float)t / FRAG_FADE_TIME) * 255.0f; } - if ( le->pos.trType == TR_STATIONARY ) - { - if ( !(cgi_CM_PointContents( le->refEntity.origin, 0 ) & CONTENTS_SOLID )) - { + if (le->pos.trType == TR_STATIONARY) { + if (!(cgi_CM_PointContents(le->refEntity.origin, 0) & CONTENTS_SOLID)) { // thing is no longer in solid, so let gravity take it back - VectorCopy( le->refEntity.origin, le->pos.trBase ); - VectorClear( le->pos.trDelta ); + VectorCopy(le->refEntity.origin, le->pos.trBase); + VectorClear(le->pos.trDelta); le->pos.trTime = cg.time; le->pos.trType = TR_GRAVITY; } - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); return; } // calculate new position - EvaluateTrajectory( &le->pos, cg.time, newOrigin ); + EvaluateTrajectory(&le->pos, cg.time, newOrigin); le->refEntity.renderfx |= RF_LIGHTING_ORIGIN; - VectorCopy( newOrigin, le->refEntity.lightingOrigin ); + VectorCopy(newOrigin, le->refEntity.lightingOrigin); // trace a line from previous position to new position - CG_Trace( &trace, le->refEntity.origin, NULL, NULL, newOrigin, le->ownerGentNum, CONTENTS_SOLID ); - if ( trace.fraction == 1.0 ) { + CG_Trace(&trace, le->refEntity.origin, NULL, NULL, newOrigin, le->ownerGentNum, CONTENTS_SOLID); + if (trace.fraction == 1.0) { // still in free fall - VectorCopy( newOrigin, le->refEntity.origin ); + VectorCopy(newOrigin, le->refEntity.origin); - if ( le->leFlags & LEF_TUMBLE ) { + if (le->leFlags & LEF_TUMBLE) { vec3_t angles; - EvaluateTrajectory( &le->angles, cg.time, angles ); - AnglesToAxis( angles, le->refEntity.axis ); - for(int k = 0; k < 3; k++) - { + EvaluateTrajectory(&le->angles, cg.time, angles); + AnglesToAxis(angles, le->refEntity.axis); + for (int k = 0; k < 3; k++) { VectorScale(le->refEntity.axis[k], le->radius, le->refEntity.axis[k]); } - } - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); return; } @@ -259,20 +238,19 @@ void CG_AddFragment( localEntity_t *le ) // if it is in a nodrop zone, remove it // this keeps gibs from waiting at the bottom of pits of death // and floating levels - if ( cgi_CM_PointContents( trace.endpos, 0 ) & CONTENTS_NODROP ) - { - CG_FreeLocalEntity( le ); + if (cgi_CM_PointContents(trace.endpos, 0) & CONTENTS_NODROP) { + CG_FreeLocalEntity(le); return; } // do a bouncy sound - CG_FragmentBounceSound( le, &trace ); + CG_FragmentBounceSound(le, &trace); // reflect the velocity on the trace plane - CG_ReflectVelocity( le, &trace ); - //FIXME: if LEF_TUMBLE, change avelocity too? + CG_ReflectVelocity(le, &trace); + // FIXME: if LEF_TUMBLE, change avelocity too? - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); } /* @@ -287,32 +265,29 @@ These only do simple scaling or modulation before passing to the renderer /* ** CG_AddTeleporterEffect */ -void CG_AddTeleporterEffect( localEntity_t *le ) { +void CG_AddTeleporterEffect(localEntity_t *le) { refEntity_t *re; float c; re = &le->refEntity; - c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime ); + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); - re->shaderRGBA[0] = - re->shaderRGBA[1] = - re->shaderRGBA[2] = - re->shaderRGBA[3] = 0xff * c; + re->shaderRGBA[0] = re->shaderRGBA[1] = re->shaderRGBA[2] = re->shaderRGBA[3] = 0xff * c; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* ** CG_AddFadeRGB */ -void CG_AddFadeRGB( localEntity_t *le ) { +void CG_AddFadeRGB(localEntity_t *le) { refEntity_t *re; float c; re = &le->refEntity; - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; c *= 0xff; re->shaderRGBA[0] = le->color[0] * c; @@ -320,7 +295,7 @@ void CG_AddFadeRGB( localEntity_t *le ) { re->shaderRGBA[2] = le->color[2] * c; re->shaderRGBA[3] = le->color[3] * c; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* @@ -328,37 +303,37 @@ void CG_AddFadeRGB( localEntity_t *le ) { CG_AddPuff ================== */ -static void CG_AddPuff( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddPuff(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; // fade / grow time - c = ( le->endTime - cg.time ) / (float)( le->endTime - le->startTime ); + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); re->shaderRGBA[0] = le->color[0] * c; re->shaderRGBA[1] = le->color[1] * c; re->shaderRGBA[2] = le->color[2] * c; - if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) { - re->radius = le->radius * ( 1.0 - c ) + 8; + if (!(le->leFlags & LEF_PUFF_DONT_SCALE)) { + re->radius = le->radius * (1.0 - c) + 8; } - EvaluateTrajectory( &le->pos, cg.time, re->origin ); + EvaluateTrajectory(&le->pos, cg.time, re->origin); // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* @@ -366,71 +341,63 @@ static void CG_AddPuff( localEntity_t *le ) { CG_AddLocalLight ================ */ -static void CG_AddLocalLight( localEntity_t *le ) -{ +static void CG_AddLocalLight(localEntity_t *le) { // There should be a light if this is being used, but hey... - if ( le->light ) - { - float light; + if (le->light) { + float light; - light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime ); + light = (float)(cg.time - le->startTime) / (le->endTime - le->startTime); - if ( light < 0.5 ) - { + if (light < 0.5) { light = 1.0; - } - else - { - light = 1.0 - ( light - 0.5 ) * 2; + } else { + light = 1.0 - (light - 0.5) * 2; } light = le->light * light; - cgi_R_AddLightToScene( le->refEntity.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] ); + cgi_R_AddLightToScene(le->refEntity.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2]); } } //--------------------------------------------------- -static void CG_AddFadeModel( localEntity_t *le ) -{ - refEntity_t *ent = &le->refEntity; +static void CG_AddFadeModel(localEntity_t *le) { + refEntity_t *ent = &le->refEntity; - if ( cg.time < le->startTime ) - { - CG_FreeLocalEntity( le ); + if (cg.time < le->startTime) { + CG_FreeLocalEntity(le); return; } - float frac = 1.0f - ((float)( cg.time - le->startTime )/(float)( le->endTime - le->startTime )); + float frac = 1.0f - ((float)(cg.time - le->startTime) / (float)(le->endTime - le->startTime)); ent->shaderRGBA[0] = le->color[0] * frac; ent->shaderRGBA[1] = le->color[1] * frac; ent->shaderRGBA[2] = le->color[2] * frac; ent->shaderRGBA[3] = le->color[3] * frac; - EvaluateTrajectory( &le->pos, cg.time, ent->origin ); + EvaluateTrajectory(&le->pos, cg.time, ent->origin); // add the entity - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } // NOTE: this is 100% for the demp2 alt-fire effect, so changes to the visual effect will affect game side demp2 code //--------------------------------------------------- -static void CG_AddFadeScaleModel( localEntity_t *le ) -{ - refEntity_t *ent = &le->refEntity; +static void CG_AddFadeScaleModel(localEntity_t *le) { + refEntity_t *ent = &le->refEntity; - float frac = ( cg.time - le->startTime )/((float)( le->endTime - le->startTime )); + float frac = (cg.time - le->startTime) / ((float)(le->endTime - le->startTime)); frac *= frac * frac; // yes, this is completely ridiculous...but it causes the shell to grow slowly then "explode" at the end ent->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, ent->axis ); + AxisCopy(axisDefault, ent->axis); - VectorScale( ent->axis[0], le->radius * frac, ent->axis[0] ); - VectorScale( ent->axis[1], le->radius * frac, ent->axis[1] ); - VectorScale( ent->axis[2], le->radius * 0.5f * frac, ent->axis[2] ); + VectorScale(ent->axis[0], le->radius * frac, ent->axis[0]); + VectorScale(ent->axis[1], le->radius * frac, ent->axis[1]); + VectorScale(ent->axis[2], le->radius * 0.5f * frac, ent->axis[2]); frac = 1.0f - frac; @@ -440,89 +407,85 @@ static void CG_AddFadeScaleModel( localEntity_t *le ) ent->shaderRGBA[3] = le->color[3] * frac; // add the entity - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } // create a quad that doesn't use a refEnt. Currently only for use with the DebugNav drawing so it doesn't have to use fx //------------------------------------------ -static void CG_AddQuad( localEntity_t *le ) -{ - polyVert_t verts[4]; +static void CG_AddQuad(localEntity_t *le) { + polyVert_t verts[4]; - VectorCopy( le->refEntity.origin, verts[0].xyz ); + VectorCopy(le->refEntity.origin, verts[0].xyz); verts[0].xyz[0] -= le->radius; verts[0].xyz[1] -= le->radius; verts[0].st[0] = 0; verts[0].st[1] = 0; - for ( int i = 0; i < 4; i++ ) - { + for (int i = 0; i < 4; i++) { verts[i].modulate[0] = le->color[0]; verts[i].modulate[1] = le->color[1]; verts[i].modulate[2] = le->color[2]; verts[i].modulate[3] = le->color[3]; } - VectorCopy( le->refEntity.origin, verts[1].xyz ); + VectorCopy(le->refEntity.origin, verts[1].xyz); verts[1].xyz[0] -= le->radius; verts[1].xyz[1] += le->radius; verts[1].st[0] = 0; verts[1].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[2].xyz ); + VectorCopy(le->refEntity.origin, verts[2].xyz); verts[2].xyz[0] += le->radius; verts[2].xyz[1] += le->radius; verts[2].st[0] = 1; verts[2].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[3].xyz ); + VectorCopy(le->refEntity.origin, verts[3].xyz); verts[3].xyz[0] += le->radius; verts[3].xyz[1] -= le->radius; verts[3].st[0] = 1; verts[3].st[1] = 0; - cgi_R_AddPolyToScene( le->refEntity.customShader, 4, verts ); + cgi_R_AddPolyToScene(le->refEntity.customShader, 4, verts); } // create a sprite that doesn't use a refEnt. Currently only for use with the DebugNav drawing so it doesn't have to use fx //------------------------------------------ -static void CG_AddSprite( localEntity_t *le ) -{ - polyVert_t verts[4]; +static void CG_AddSprite(localEntity_t *le) { + polyVert_t verts[4]; - VectorCopy( le->refEntity.origin, verts[0].xyz ); - VectorMA( verts[0].xyz, -le->radius, cg.refdef.viewaxis[2], verts[0].xyz ); - VectorMA( verts[0].xyz, -le->radius, cg.refdef.viewaxis[1], verts[0].xyz ); + VectorCopy(le->refEntity.origin, verts[0].xyz); + VectorMA(verts[0].xyz, -le->radius, cg.refdef.viewaxis[2], verts[0].xyz); + VectorMA(verts[0].xyz, -le->radius, cg.refdef.viewaxis[1], verts[0].xyz); verts[0].st[0] = 0; verts[0].st[1] = 0; - for ( int i = 0; i < 4; i++ ) - { + for (int i = 0; i < 4; i++) { verts[i].modulate[0] = le->color[0]; verts[i].modulate[1] = le->color[1]; verts[i].modulate[2] = le->color[2]; verts[i].modulate[3] = le->color[3]; } - VectorCopy( le->refEntity.origin, verts[1].xyz ); - VectorMA( verts[1].xyz, -le->radius, cg.refdef.viewaxis[2], verts[1].xyz ); - VectorMA( verts[1].xyz, le->radius, cg.refdef.viewaxis[1], verts[1].xyz ); + VectorCopy(le->refEntity.origin, verts[1].xyz); + VectorMA(verts[1].xyz, -le->radius, cg.refdef.viewaxis[2], verts[1].xyz); + VectorMA(verts[1].xyz, le->radius, cg.refdef.viewaxis[1], verts[1].xyz); verts[1].st[0] = 0; verts[1].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[2].xyz ); - VectorMA( verts[2].xyz, le->radius, cg.refdef.viewaxis[2], verts[2].xyz ); - VectorMA( verts[2].xyz, le->radius, cg.refdef.viewaxis[1], verts[2].xyz ); + VectorCopy(le->refEntity.origin, verts[2].xyz); + VectorMA(verts[2].xyz, le->radius, cg.refdef.viewaxis[2], verts[2].xyz); + VectorMA(verts[2].xyz, le->radius, cg.refdef.viewaxis[1], verts[2].xyz); verts[2].st[0] = 1; verts[2].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[3].xyz ); - VectorMA( verts[3].xyz, le->radius, cg.refdef.viewaxis[2], verts[3].xyz ); - VectorMA( verts[3].xyz, -le->radius, cg.refdef.viewaxis[1], verts[3].xyz ); + VectorCopy(le->refEntity.origin, verts[3].xyz); + VectorMA(verts[3].xyz, le->radius, cg.refdef.viewaxis[2], verts[3].xyz); + VectorMA(verts[3].xyz, -le->radius, cg.refdef.viewaxis[1], verts[3].xyz); verts[3].st[0] = 1; verts[3].st[1] = 0; - cgi_R_AddPolyToScene( le->refEntity.customShader, 4, verts ); + cgi_R_AddPolyToScene(le->refEntity.customShader, 4, verts); } /* @@ -532,15 +495,14 @@ CG_AddLine for beams and the like. =================== */ -void CG_AddLine( localEntity_t *le ) -{ - refEntity_t *re; +void CG_AddLine(localEntity_t *le) { + refEntity_t *re; re = &le->refEntity; re->reType = RT_LINE; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } //============================================================================== @@ -551,69 +513,64 @@ CG_AddLocalEntities =================== */ -void CG_AddLocalEntities( void ) -{ - localEntity_t *le, *next; +void CG_AddLocalEntities(void) { + localEntity_t *le, *next; // walk the list backwards, so any new local entities generated // (trails, marks, etc) will be present this frame le = cg_activeLocalEntities.prev; - for ( ; le != &cg_activeLocalEntities ; le = next ) { + for (; le != &cg_activeLocalEntities; le = next) { // grab next now, so if the local entity is freed we // still have it next = le->prev; - if ( cg.time >= le->endTime ) { - CG_FreeLocalEntity( le ); + if (cg.time >= le->endTime) { + CG_FreeLocalEntity(le); continue; } - switch ( le->leType ) { + switch (le->leType) { default: - CG_Error( "Bad leType: %i", le->leType ); + CG_Error("Bad leType: %i", le->leType); break; case LE_MARK: break; case LE_FADE_MODEL: - CG_AddFadeModel( le ); + CG_AddFadeModel(le); break; case LE_FADE_SCALE_MODEL: - CG_AddFadeScaleModel( le ); + CG_AddFadeScaleModel(le); break; case LE_FRAGMENT: - CG_AddFragment( le ); + CG_AddFragment(le); break; case LE_PUFF: - CG_AddPuff( le ); + CG_AddPuff(le); break; - case LE_FADE_RGB: // teleporters, railtrails - CG_AddFadeRGB( le ); + case LE_FADE_RGB: // teleporters, railtrails + CG_AddFadeRGB(le); break; case LE_LIGHT: - CG_AddLocalLight( le ); + CG_AddLocalLight(le); break; - case LE_LINE: // oriented lines for FX - CG_AddLine( le ); + case LE_LINE: // oriented lines for FX + CG_AddLine(le); break; // Use for debug only case LE_QUAD: - CG_AddQuad( le ); + CG_AddQuad(le); break; case LE_SPRITE: - CG_AddSprite( le ); + CG_AddSprite(le); } } } - - - - diff --git a/code/cgame/cg_main.cpp b/code/cgame/cg_main.cpp index 86bf1a0c78..15ebac05e0 100644 --- a/code/cgame/cg_main.cpp +++ b/code/cgame/cg_main.cpp @@ -30,25 +30,23 @@ along with this program; if not, see . #include "../qcommon/sstring.h" #include "qcommon/ojk_saved_game_helper.h" -//NOTENOTE: Be sure to change the mirrored code in g_shared.h -typedef std::map< sstring_t, unsigned char > namePrecache_m; -extern namePrecache_m *as_preCacheMap; -extern void CG_RegisterNPCCustomSounds( clientInfo_t *ci ); -extern qboolean G_AddSexToMunroString ( char *string, qboolean qDoBoth ); -extern int G_ParseAnimFileSet( const char *skeletonName, const char *modelName=0); -extern void CG_DrawDataPadInventorySelect( void ); - -void CG_Init( int serverCommandSequence ); -qboolean CG_ConsoleCommand( void ); -void CG_Shutdown( void ); -int CG_GetCameraPos( vec3_t camerapos ); -int CG_GetCameraAng( vec3_t cameraang ); +// NOTENOTE: Be sure to change the mirrored code in g_shared.h +typedef std::map namePrecache_m; +extern namePrecache_m *as_preCacheMap; +extern void CG_RegisterNPCCustomSounds(clientInfo_t *ci); +extern qboolean G_AddSexToMunroString(char *string, qboolean qDoBoth); +extern int G_ParseAnimFileSet(const char *skeletonName, const char *modelName = 0); +extern void CG_DrawDataPadInventorySelect(void); + +void CG_Init(int serverCommandSequence); +qboolean CG_ConsoleCommand(void); +void CG_Shutdown(void); +int CG_GetCameraPos(vec3_t camerapos); +int CG_GetCameraAng(vec3_t cameraang); void UseItem(int itemNum); -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color); +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color); -#define NUM_CHUNKS 6 +#define NUM_CHUNKS 6 /* Ghoul2 Insert Start */ @@ -62,36 +60,20 @@ void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount); Ghoul2 Insert End */ - void CG_LoadHudMenu(void); int inv_icons[INV_MAX]; -const char *inv_names[] = -{ -"ELECTROBINOCULARS", -"BACTA CANISTER", -"SEEKER", -"LIGHT AMP GOGGLES", -"ASSAULT SENTRY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", +const char *inv_names[] = { + "ELECTROBINOCULARS", "BACTA CANISTER", "SEEKER", "LIGHT AMP GOGGLES", "ASSAULT SENTRY", "GOODIE KEY", "GOODIE KEY", "GOODIE KEY", + "GOODIE KEY", "GOODIE KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", }; -int force_icons[NUM_FORCE_POWERS]; - +int force_icons[NUM_FORCE_POWERS]; -void CG_DrawDataPadHUD( centity_t *cent ); -void CG_DrawDataPadObjectives(const centity_t *cent ); +void CG_DrawDataPadHUD(centity_t *cent); +void CG_DrawDataPadObjectives(const centity_t *cent); void CG_DrawDataPadIconBackground(const int backgroundType); -void CG_DrawDataPadWeaponSelect( void ); -void CG_DrawDataPadForceSelect( void ); +void CG_DrawDataPadWeaponSelect(void); +void CG_DrawDataPadForceSelect(void); /* ================ @@ -101,12 +83,13 @@ This is the only way control passes into the cgame module. This must be the very first function compiled into the .q3vm file ================ */ -extern "C" Q_EXPORT intptr_t QDECL vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7 ) { - centity_t *cent; +extern "C" Q_EXPORT intptr_t QDECL vmMain(int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, + intptr_t arg7) { + centity_t *cent; - switch ( command ) { + switch (command) { case CG_INIT: - CG_Init( arg0 ); + CG_Init(arg0); return 0; case CG_SHUTDOWN: CG_Shutdown(); @@ -114,17 +97,17 @@ extern "C" Q_EXPORT intptr_t QDECL vmMain( int command, intptr_t arg0, intptr_t case CG_CONSOLE_COMMAND: return CG_ConsoleCommand(); case CG_DRAW_ACTIVE_FRAME: - CG_DrawActiveFrame( arg0, (stereoFrame_t) arg1 ); + CG_DrawActiveFrame(arg0, (stereoFrame_t)arg1); return 0; case CG_CROSSHAIR_PLAYER: return CG_CrosshairPlayer(); case CG_CAMERA_POS: - return CG_GetCameraPos( (float*)arg0); + return CG_GetCameraPos((float *)arg0); case CG_CAMERA_ANG: - return CG_GetCameraAng( (float*)arg0); -/* -Ghoul2 Insert Start -*/ + return CG_GetCameraAng((float *)arg0); + /* + Ghoul2 Insert Start + */ case CG_RESIZE_G2: CG_ResizeG2((CGhoul2Info_v *)arg0, arg1); return 0; @@ -141,42 +124,37 @@ Ghoul2 Insert Start CG_ResizeG2TempBone((mdxaBone_v *)arg0, arg1); return 0; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ case CG_DRAW_DATAPAD_HUD: - if (cg.snap) - { + if (cg.snap) { cent = &cg_entities[cg.snap->ps.clientNum]; CG_DrawDataPadHUD(cent); } return 0; case CG_DRAW_DATAPAD_OBJECTIVES: - if (cg.snap) - { + if (cg.snap) { cent = &cg_entities[cg.snap->ps.clientNum]; CG_DrawDataPadObjectives(cent); } return 0; case CG_DRAW_DATAPAD_WEAPONS: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_WEAPONS); CG_DrawDataPadWeaponSelect(); } return 0; case CG_DRAW_DATAPAD_INVENTORY: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_INVENTORY); CG_DrawDataPadInventorySelect(); } return 0; case CG_DRAW_DATAPAD_FORCEPOWERS: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_FORCE); CG_DrawDataPadForceSelect(); } @@ -189,291 +167,276 @@ Ghoul2 Insert End Ghoul2 Insert Start */ -void CG_ResizeG2Bolt(boltInfo_v *bolt, int newCount) -{ - bolt->resize(newCount); -} +void CG_ResizeG2Bolt(boltInfo_v *bolt, int newCount) { bolt->resize(newCount); } -void CG_ResizeG2Surface(surfaceInfo_v *surface, int newCount) -{ - surface->resize(newCount); -} +void CG_ResizeG2Surface(surfaceInfo_v *surface, int newCount) { surface->resize(newCount); } -void CG_ResizeG2Bone(boneInfo_v *bone, int newCount) -{ - bone->resize(newCount); -} +void CG_ResizeG2Bone(boneInfo_v *bone, int newCount) { bone->resize(newCount); } -void CG_ResizeG2(CGhoul2Info_v *ghoul2, int newCount) -{ - ghoul2->resize(newCount); -} +void CG_ResizeG2(CGhoul2Info_v *ghoul2, int newCount) { ghoul2->resize(newCount); } -void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount) -{ - tempBone->resize(newCount); -} +void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount) { tempBone->resize(newCount); } /* Ghoul2 Insert End */ -cg_t cg; -cgs_t cgs; -centity_t cg_entities[MAX_GENTITIES]; +cg_t cg; +cgs_t cgs; +centity_t cg_entities[MAX_GENTITIES]; -centity_t *cg_permanents[MAX_GENTITIES]; -int cg_numpermanents = 0; +centity_t *cg_permanents[MAX_GENTITIES]; +int cg_numpermanents = 0; -weaponInfo_t cg_weapons[MAX_WEAPONS]; -itemInfo_t cg_items[MAX_ITEMS]; +weaponInfo_t cg_weapons[MAX_WEAPONS]; +itemInfo_t cg_items[MAX_ITEMS]; typedef struct { - qboolean registered; // Has the player picked it up - qboolean active; // Is it the chosen inventory item - int count; // Count of items. - char description[128]; + qboolean registered; // Has the player picked it up + qboolean active; // Is it the chosen inventory item + int count; // Count of items. + char description[128]; } inventoryInfo_t; -inventoryInfo_t cg_inventory[INV_MAX]; - -vmCvar_t cg_runpitch; -vmCvar_t cg_runroll; -vmCvar_t cg_bobup; -vmCvar_t cg_bobpitch; -vmCvar_t cg_bobroll; -vmCvar_t cg_shadows; -vmCvar_t cg_renderToTextureFX; -vmCvar_t cg_shadowCullDistance; -vmCvar_t cg_footsteps; -vmCvar_t cg_saberEntMarks; -vmCvar_t cg_paused; -vmCvar_t cg_drawTimer; -vmCvar_t cg_drawFPS; -vmCvar_t cg_drawSnapshot; -vmCvar_t cg_drawAmmoWarning; -vmCvar_t cg_drawCrosshair; -vmCvar_t cg_crosshairIdentifyTarget; -vmCvar_t cg_dynamicCrosshair; -vmCvar_t cg_crosshairForceHint; -vmCvar_t cg_crosshairX; -vmCvar_t cg_crosshairY; -vmCvar_t cg_crosshairSize; -vmCvar_t cg_draw2D; -vmCvar_t cg_drawStatus; -vmCvar_t cg_drawHUD; -vmCvar_t cg_debugAnim; +inventoryInfo_t cg_inventory[INV_MAX]; + +vmCvar_t cg_runpitch; +vmCvar_t cg_runroll; +vmCvar_t cg_bobup; +vmCvar_t cg_bobpitch; +vmCvar_t cg_bobroll; +vmCvar_t cg_shadows; +vmCvar_t cg_renderToTextureFX; +vmCvar_t cg_shadowCullDistance; +vmCvar_t cg_footsteps; +vmCvar_t cg_saberEntMarks; +vmCvar_t cg_paused; +vmCvar_t cg_drawTimer; +vmCvar_t cg_drawFPS; +vmCvar_t cg_drawSnapshot; +vmCvar_t cg_drawAmmoWarning; +vmCvar_t cg_drawCrosshair; +vmCvar_t cg_crosshairIdentifyTarget; +vmCvar_t cg_dynamicCrosshair; +vmCvar_t cg_crosshairForceHint; +vmCvar_t cg_crosshairX; +vmCvar_t cg_crosshairY; +vmCvar_t cg_crosshairSize; +vmCvar_t cg_draw2D; +vmCvar_t cg_drawStatus; +vmCvar_t cg_drawHUD; +vmCvar_t cg_debugAnim; #ifndef FINAL_BUILD -vmCvar_t cg_debugAnimTarget; -vmCvar_t cg_gun_frame; +vmCvar_t cg_debugAnimTarget; +vmCvar_t cg_gun_frame; #endif -vmCvar_t cg_gun_x; -vmCvar_t cg_gun_y; -vmCvar_t cg_gun_z; -vmCvar_t cg_debugSaber; -vmCvar_t cg_debugEvents; -vmCvar_t cg_errorDecay; -vmCvar_t cg_addMarks; -vmCvar_t cg_drawGun; -vmCvar_t cg_autoswitch; -vmCvar_t cg_simpleItems; -vmCvar_t cg_fov; -vmCvar_t cg_fovAspectAdjust; -vmCvar_t cg_endcredits; -vmCvar_t cg_updatedDataPadForcePower1; -vmCvar_t cg_updatedDataPadForcePower2; -vmCvar_t cg_updatedDataPadForcePower3; -vmCvar_t cg_updatedDataPadObjective; -vmCvar_t cg_drawBreath; -vmCvar_t cg_roffdebug; +vmCvar_t cg_gun_x; +vmCvar_t cg_gun_y; +vmCvar_t cg_gun_z; +vmCvar_t cg_debugSaber; +vmCvar_t cg_debugEvents; +vmCvar_t cg_errorDecay; +vmCvar_t cg_addMarks; +vmCvar_t cg_drawGun; +vmCvar_t cg_autoswitch; +vmCvar_t cg_simpleItems; +vmCvar_t cg_fov; +vmCvar_t cg_fovAspectAdjust; +vmCvar_t cg_endcredits; +vmCvar_t cg_updatedDataPadForcePower1; +vmCvar_t cg_updatedDataPadForcePower2; +vmCvar_t cg_updatedDataPadForcePower3; +vmCvar_t cg_updatedDataPadObjective; +vmCvar_t cg_drawBreath; +vmCvar_t cg_roffdebug; #ifndef FINAL_BUILD -vmCvar_t cg_roffval1; -vmCvar_t cg_roffval2; -vmCvar_t cg_roffval3; -vmCvar_t cg_roffval4; +vmCvar_t cg_roffval1; +vmCvar_t cg_roffval2; +vmCvar_t cg_roffval3; +vmCvar_t cg_roffval4; #endif -vmCvar_t cg_thirdPerson; -vmCvar_t cg_thirdPersonRange; -vmCvar_t cg_thirdPersonMaxRange; -vmCvar_t cg_thirdPersonAngle; -vmCvar_t cg_thirdPersonPitchOffset; -vmCvar_t cg_thirdPersonVertOffset; -vmCvar_t cg_thirdPersonCameraDamp; -vmCvar_t cg_thirdPersonTargetDamp; -vmCvar_t cg_gunAutoFirst; - -vmCvar_t cg_thirdPersonAlpha; -vmCvar_t cg_thirdPersonAutoAlpha; -vmCvar_t cg_thirdPersonHorzOffset; - -vmCvar_t cg_stereoSeparation; -vmCvar_t cg_developer; -vmCvar_t cg_timescale; -vmCvar_t cg_skippingcin; - -vmCvar_t cg_pano; -vmCvar_t cg_panoNumShots; - -vmCvar_t fx_freeze; -vmCvar_t fx_debug; - -vmCvar_t cg_missionInfoFlashTime; -vmCvar_t cg_hudFiles; - -vmCvar_t cg_neverHearThatDumbBeepingSoundAgain; - -vmCvar_t cg_VariantSoundCap; // 0 = no capping, else cap to (n) max (typically just 1, but allows more) -vmCvar_t cg_turnAnims; -vmCvar_t cg_motionBoneComp; -vmCvar_t cg_distributeMBCorrection; -vmCvar_t cg_reliableAnimEvents; - -vmCvar_t cg_smoothPlayerPos; -vmCvar_t cg_smoothPlayerPlat; -vmCvar_t cg_smoothPlayerPlatAccel; -vmCvar_t cg_g2Marks; -vmCvar_t fx_expensivePhysics; -vmCvar_t cg_debugHealthBars; - -vmCvar_t cg_smoothCamera; -vmCvar_t cg_speedTrail; -vmCvar_t cg_fovViewmodel; -vmCvar_t cg_fovViewmodelAdjust; - -vmCvar_t cg_scaleVehicleSensitivity; +vmCvar_t cg_thirdPerson; +vmCvar_t cg_thirdPersonRange; +vmCvar_t cg_thirdPersonMaxRange; +vmCvar_t cg_thirdPersonAngle; +vmCvar_t cg_thirdPersonPitchOffset; +vmCvar_t cg_thirdPersonVertOffset; +vmCvar_t cg_thirdPersonCameraDamp; +vmCvar_t cg_thirdPersonTargetDamp; +vmCvar_t cg_gunAutoFirst; + +vmCvar_t cg_thirdPersonAlpha; +vmCvar_t cg_thirdPersonAutoAlpha; +vmCvar_t cg_thirdPersonHorzOffset; + +vmCvar_t cg_stereoSeparation; +vmCvar_t cg_developer; +vmCvar_t cg_timescale; +vmCvar_t cg_skippingcin; + +vmCvar_t cg_pano; +vmCvar_t cg_panoNumShots; + +vmCvar_t fx_freeze; +vmCvar_t fx_debug; + +vmCvar_t cg_missionInfoFlashTime; +vmCvar_t cg_hudFiles; + +vmCvar_t cg_neverHearThatDumbBeepingSoundAgain; + +vmCvar_t cg_VariantSoundCap; // 0 = no capping, else cap to (n) max (typically just 1, but allows more) +vmCvar_t cg_turnAnims; +vmCvar_t cg_motionBoneComp; +vmCvar_t cg_distributeMBCorrection; +vmCvar_t cg_reliableAnimEvents; + +vmCvar_t cg_smoothPlayerPos; +vmCvar_t cg_smoothPlayerPlat; +vmCvar_t cg_smoothPlayerPlatAccel; +vmCvar_t cg_g2Marks; +vmCvar_t fx_expensivePhysics; +vmCvar_t cg_debugHealthBars; + +vmCvar_t cg_smoothCamera; +vmCvar_t cg_speedTrail; +vmCvar_t cg_fovViewmodel; +vmCvar_t cg_fovViewmodelAdjust; + +vmCvar_t cg_scaleVehicleSensitivity; typedef struct { - vmCvar_t *vmCvar; - const char *cvarName; - const char *defaultString; - int cvarFlags; + vmCvar_t *vmCvar; + const char *cvarName; + const char *defaultString; + int cvarFlags; } cvarTable_t; static cvarTable_t cvarTable[] = { - { &cg_autoswitch, "cg_autoswitch", "1", CVAR_ARCHIVE }, - { &cg_drawGun, "cg_drawGun", "1", CVAR_ARCHIVE }, - { &cg_fov, "cg_fov", "80", CVAR_ARCHIVE }, - { &cg_fovAspectAdjust, "cg_fovAspectAdjust", "0", CVAR_ARCHIVE }, - { &cg_stereoSeparation, "cg_stereoSeparation", "0.4", CVAR_ARCHIVE }, - { &cg_shadows, "cg_shadows", "1", CVAR_ARCHIVE }, - { &cg_renderToTextureFX, "cg_renderToTextureFX", "1", CVAR_ARCHIVE }, - { &cg_shadowCullDistance, "r_shadowRange", "1000", CVAR_ARCHIVE }, - { &cg_footsteps, "cg_footsteps", "3", CVAR_ARCHIVE },//1 = sounds, 2 = sounds & effects, 3 = sounds, effects & marks, 4 = always - { &cg_saberEntMarks, "cg_saberEntMarks", "1", CVAR_ARCHIVE }, - - { &cg_draw2D, "cg_draw2D", "1", CVAR_ARCHIVE }, - { &cg_drawStatus, "cg_drawStatus", "1", CVAR_ARCHIVE }, - { &cg_drawHUD, "cg_drawHUD", "1", 0 }, - { &cg_drawTimer, "cg_drawTimer", "0", CVAR_ARCHIVE }, - { &cg_drawFPS, "cg_drawFPS", "0", CVAR_ARCHIVE }, - { &cg_drawSnapshot, "cg_drawSnapshot", "0", CVAR_ARCHIVE }, - { &cg_drawAmmoWarning, "cg_drawAmmoWarning", "1", CVAR_ARCHIVE }, - { &cg_drawCrosshair, "cg_drawCrosshair", "1", CVAR_ARCHIVE }, - { &cg_dynamicCrosshair, "cg_dynamicCrosshair", "1", CVAR_ARCHIVE }, + {&cg_autoswitch, "cg_autoswitch", "1", CVAR_ARCHIVE}, + {&cg_drawGun, "cg_drawGun", "1", CVAR_ARCHIVE}, + {&cg_fov, "cg_fov", "80", CVAR_ARCHIVE}, + {&cg_fovAspectAdjust, "cg_fovAspectAdjust", "0", CVAR_ARCHIVE}, + {&cg_stereoSeparation, "cg_stereoSeparation", "0.4", CVAR_ARCHIVE}, + {&cg_shadows, "cg_shadows", "1", CVAR_ARCHIVE}, + {&cg_renderToTextureFX, "cg_renderToTextureFX", "1", CVAR_ARCHIVE}, + {&cg_shadowCullDistance, "r_shadowRange", "1000", CVAR_ARCHIVE}, + {&cg_footsteps, "cg_footsteps", "3", CVAR_ARCHIVE}, // 1 = sounds, 2 = sounds & effects, 3 = sounds, effects & marks, 4 = always + {&cg_saberEntMarks, "cg_saberEntMarks", "1", CVAR_ARCHIVE}, + + {&cg_draw2D, "cg_draw2D", "1", CVAR_ARCHIVE}, + {&cg_drawStatus, "cg_drawStatus", "1", CVAR_ARCHIVE}, + {&cg_drawHUD, "cg_drawHUD", "1", 0}, + {&cg_drawTimer, "cg_drawTimer", "0", CVAR_ARCHIVE}, + {&cg_drawFPS, "cg_drawFPS", "0", CVAR_ARCHIVE}, + {&cg_drawSnapshot, "cg_drawSnapshot", "0", CVAR_ARCHIVE}, + {&cg_drawAmmoWarning, "cg_drawAmmoWarning", "1", CVAR_ARCHIVE}, + {&cg_drawCrosshair, "cg_drawCrosshair", "1", CVAR_ARCHIVE}, + {&cg_dynamicCrosshair, "cg_dynamicCrosshair", "1", CVAR_ARCHIVE}, // NOTE : I also create this in UI_Init() - { &cg_crosshairIdentifyTarget, "cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE }, - { &cg_crosshairForceHint, "cg_crosshairForceHint", "1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART }, - { &cg_endcredits, "cg_endcredits", "0", 0}, - { &cg_updatedDataPadForcePower1, "cg_updatedDataPadForcePower1", "0", 0}, - { &cg_updatedDataPadForcePower2, "cg_updatedDataPadForcePower2", "0", 0}, - { &cg_updatedDataPadForcePower3, "cg_updatedDataPadForcePower3", "0", 0}, - { &cg_updatedDataPadObjective, "cg_updatedDataPadObjective", "0", 0}, - - { &cg_crosshairSize, "cg_crosshairSize", "24", CVAR_ARCHIVE }, - { &cg_crosshairX, "cg_crosshairX", "0", CVAR_ARCHIVE }, - { &cg_crosshairY, "cg_crosshairY", "0", CVAR_ARCHIVE }, - { &cg_simpleItems, "cg_simpleItems", "0", CVAR_ARCHIVE }, + {&cg_crosshairIdentifyTarget, "cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE}, + {&cg_crosshairForceHint, "cg_crosshairForceHint", "1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART}, + {&cg_endcredits, "cg_endcredits", "0", 0}, + {&cg_updatedDataPadForcePower1, "cg_updatedDataPadForcePower1", "0", 0}, + {&cg_updatedDataPadForcePower2, "cg_updatedDataPadForcePower2", "0", 0}, + {&cg_updatedDataPadForcePower3, "cg_updatedDataPadForcePower3", "0", 0}, + {&cg_updatedDataPadObjective, "cg_updatedDataPadObjective", "0", 0}, + + {&cg_crosshairSize, "cg_crosshairSize", "24", CVAR_ARCHIVE}, + {&cg_crosshairX, "cg_crosshairX", "0", CVAR_ARCHIVE}, + {&cg_crosshairY, "cg_crosshairY", "0", CVAR_ARCHIVE}, + {&cg_simpleItems, "cg_simpleItems", "0", CVAR_ARCHIVE}, // NOTE : I also create this in UI_Init() - { &cg_addMarks, "cg_marks", "1", CVAR_ARCHIVE }, + {&cg_addMarks, "cg_marks", "1", CVAR_ARCHIVE}, // NOTE : I also create these weapon sway cvars in UI_Init() - { &cg_runpitch, "cg_runpitch", "0.002", CVAR_ARCHIVE}, - { &cg_runroll, "cg_runroll", "0.005", CVAR_ARCHIVE }, - { &cg_bobup , "cg_bobup", "0.005", CVAR_ARCHIVE }, - { &cg_bobpitch, "cg_bobpitch", "0.002", CVAR_ARCHIVE }, - { &cg_bobroll, "cg_bobroll", "0.002", CVAR_ARCHIVE }, + {&cg_runpitch, "cg_runpitch", "0.002", CVAR_ARCHIVE}, + {&cg_runroll, "cg_runroll", "0.005", CVAR_ARCHIVE}, + {&cg_bobup, "cg_bobup", "0.005", CVAR_ARCHIVE}, + {&cg_bobpitch, "cg_bobpitch", "0.002", CVAR_ARCHIVE}, + {&cg_bobroll, "cg_bobroll", "0.002", CVAR_ARCHIVE}, - { &cg_debugAnim, "cg_debuganim", "0", CVAR_CHEAT }, + {&cg_debugAnim, "cg_debuganim", "0", CVAR_CHEAT}, #ifndef FINAL_BUILD - { &cg_gun_frame, "gun_frame", "0", CVAR_CHEAT }, - { &cg_debugAnimTarget, "cg_debugAnimTarget", "0", CVAR_CHEAT }, + {&cg_gun_frame, "gun_frame", "0", CVAR_CHEAT}, + {&cg_debugAnimTarget, "cg_debugAnimTarget", "0", CVAR_CHEAT}, #endif - { &cg_gun_x, "cg_gunX", "0", CVAR_ARCHIVE }, - { &cg_gun_y, "cg_gunY", "0", CVAR_ARCHIVE }, - { &cg_gun_z, "cg_gunZ", "0", CVAR_ARCHIVE }, - { &cg_debugSaber, "cg_debugsaber", "0", CVAR_CHEAT }, - { &cg_debugEvents, "cg_debugevents", "0", CVAR_CHEAT }, - { &cg_errorDecay, "cg_errordecay", "100", 0 }, - - { &cg_drawBreath, "cg_drawBreath", "0", CVAR_ARCHIVE }, // Added 11/07/02 - { &cg_roffdebug, "cg_roffdebug", "0" }, + {&cg_gun_x, "cg_gunX", "0", CVAR_ARCHIVE}, + {&cg_gun_y, "cg_gunY", "0", CVAR_ARCHIVE}, + {&cg_gun_z, "cg_gunZ", "0", CVAR_ARCHIVE}, + {&cg_debugSaber, "cg_debugsaber", "0", CVAR_CHEAT}, + {&cg_debugEvents, "cg_debugevents", "0", CVAR_CHEAT}, + {&cg_errorDecay, "cg_errordecay", "100", 0}, + + {&cg_drawBreath, "cg_drawBreath", "0", CVAR_ARCHIVE}, // Added 11/07/02 + {&cg_roffdebug, "cg_roffdebug", "0"}, #ifndef FINAL_BUILD - { &cg_roffval1, "cg_roffval1", "0" }, - { &cg_roffval2, "cg_roffval2", "0" }, - { &cg_roffval3, "cg_roffval3", "0" }, - { &cg_roffval4, "cg_roffval4", "0" }, + {&cg_roffval1, "cg_roffval1", "0"}, + {&cg_roffval2, "cg_roffval2", "0"}, + {&cg_roffval3, "cg_roffval3", "0"}, + {&cg_roffval4, "cg_roffval4", "0"}, #endif - { &cg_thirdPerson, "cg_thirdPerson", "1", CVAR_SAVEGAME }, - { &cg_thirdPersonRange, "cg_thirdPersonRange", "80", CVAR_ARCHIVE }, - { &cg_thirdPersonMaxRange, "cg_thirdPersonMaxRange", "150", 0 }, - { &cg_thirdPersonAngle, "cg_thirdPersonAngle", "0", 0 }, - { &cg_thirdPersonPitchOffset, "cg_thirdPersonPitchOffset", "0", 0 }, - { &cg_thirdPersonVertOffset, "cg_thirdPersonVertOffset", "16", 0}, - { &cg_thirdPersonCameraDamp, "cg_thirdPersonCameraDamp", "0.3", 0}, - { &cg_thirdPersonTargetDamp, "cg_thirdPersonTargetDamp", "0.5", 0}, - - { &cg_thirdPersonHorzOffset, "cg_thirdPersonHorzOffset", "0", 0}, - { &cg_thirdPersonAlpha, "cg_thirdPersonAlpha", "1.0", CVAR_ARCHIVE }, - { &cg_thirdPersonAutoAlpha, "cg_thirdPersonAutoAlpha", "0", 0 }, + {&cg_thirdPerson, "cg_thirdPerson", "1", CVAR_SAVEGAME}, + {&cg_thirdPersonRange, "cg_thirdPersonRange", "80", CVAR_ARCHIVE}, + {&cg_thirdPersonMaxRange, "cg_thirdPersonMaxRange", "150", 0}, + {&cg_thirdPersonAngle, "cg_thirdPersonAngle", "0", 0}, + {&cg_thirdPersonPitchOffset, "cg_thirdPersonPitchOffset", "0", 0}, + {&cg_thirdPersonVertOffset, "cg_thirdPersonVertOffset", "16", 0}, + {&cg_thirdPersonCameraDamp, "cg_thirdPersonCameraDamp", "0.3", 0}, + {&cg_thirdPersonTargetDamp, "cg_thirdPersonTargetDamp", "0.5", 0}, + + {&cg_thirdPersonHorzOffset, "cg_thirdPersonHorzOffset", "0", 0}, + {&cg_thirdPersonAlpha, "cg_thirdPersonAlpha", "1.0", CVAR_ARCHIVE}, + {&cg_thirdPersonAutoAlpha, "cg_thirdPersonAutoAlpha", "0", 0}, // NOTE: also declare this in UI_Init - { &cg_gunAutoFirst, "cg_gunAutoFirst", "1", CVAR_ARCHIVE }, + {&cg_gunAutoFirst, "cg_gunAutoFirst", "1", CVAR_ARCHIVE}, - { &cg_pano, "pano", "0", 0 }, - { &cg_panoNumShots, "panoNumShots", "10", 0 }, + {&cg_pano, "pano", "0", 0}, + {&cg_panoNumShots, "panoNumShots", "10", 0}, - { &fx_freeze, "fx_freeze", "0", 0 }, - { &fx_debug, "fx_debug", "0", 0 }, + {&fx_freeze, "fx_freeze", "0", 0}, + {&fx_debug, "fx_debug", "0", 0}, // the following variables are created in other parts of the system, // but we also reference them here - { &cg_paused, "cl_paused", "0", CVAR_ROM }, - { &cg_developer, "developer", "", 0 }, - { &cg_timescale, "timescale", "1", 0 }, - { &cg_skippingcin, "skippingCinematic", "0", CVAR_ROM}, - { &cg_missionInfoFlashTime, "cg_missionInfoFlashTime", "10000", 0 }, - { &cg_hudFiles, "cg_hudFiles", "ui/jahud.txt", CVAR_ARCHIVE}, - - { &cg_VariantSoundCap, "cg_VariantSoundCap", "0", 0 }, - { &cg_turnAnims, "cg_turnAnims", "0", 0 }, - { &cg_motionBoneComp, "cg_motionBoneComp", "2", 0 }, - { &cg_distributeMBCorrection, "cg_distributeMBCorrection", "1", 0 }, - { &cg_reliableAnimEvents, "cg_reliableAnimEvents", "1", CVAR_ARCHIVE }, - { &cg_smoothPlayerPos, "cg_smoothPlayerPos", "0.5", 0}, - { &cg_smoothPlayerPlat, "cg_smoothPlayerPlat", "0.75", 0}, - { &cg_smoothPlayerPlatAccel, "cg_smoothPlayerPlatAccel", "3.25", 0}, - { &cg_g2Marks, "cg_g2Marks", "1", CVAR_ARCHIVE }, - { &fx_expensivePhysics, "fx_expensivePhysics", "1", CVAR_ARCHIVE }, - { &cg_debugHealthBars, "cg_debugHealthBars", "0", CVAR_CHEAT }, - - { &cg_smoothCamera, "cg_smoothCamera", "1", CVAR_ARCHIVE }, - { &cg_speedTrail, "cg_speedTrail", "1", CVAR_ARCHIVE }, - { &cg_fovViewmodel, "cg_fovViewmodel", "0", CVAR_ARCHIVE }, - { &cg_fovViewmodelAdjust, "cg_fovViewmodelAdjust", "1", CVAR_ARCHIVE }, - - { &cg_scaleVehicleSensitivity, "cg_scaleVehicleSensitivity", "1", CVAR_ARCHIVE }, + {&cg_paused, "cl_paused", "0", CVAR_ROM}, + {&cg_developer, "developer", "", 0}, + {&cg_timescale, "timescale", "1", 0}, + {&cg_skippingcin, "skippingCinematic", "0", CVAR_ROM}, + {&cg_missionInfoFlashTime, "cg_missionInfoFlashTime", "10000", 0}, + {&cg_hudFiles, "cg_hudFiles", "ui/jahud.txt", CVAR_ARCHIVE}, + + {&cg_VariantSoundCap, "cg_VariantSoundCap", "0", 0}, + {&cg_turnAnims, "cg_turnAnims", "0", 0}, + {&cg_motionBoneComp, "cg_motionBoneComp", "2", 0}, + {&cg_distributeMBCorrection, "cg_distributeMBCorrection", "1", 0}, + {&cg_reliableAnimEvents, "cg_reliableAnimEvents", "1", CVAR_ARCHIVE}, + {&cg_smoothPlayerPos, "cg_smoothPlayerPos", "0.5", 0}, + {&cg_smoothPlayerPlat, "cg_smoothPlayerPlat", "0.75", 0}, + {&cg_smoothPlayerPlatAccel, "cg_smoothPlayerPlatAccel", "3.25", 0}, + {&cg_g2Marks, "cg_g2Marks", "1", CVAR_ARCHIVE}, + {&fx_expensivePhysics, "fx_expensivePhysics", "1", CVAR_ARCHIVE}, + {&cg_debugHealthBars, "cg_debugHealthBars", "0", CVAR_CHEAT}, + + {&cg_smoothCamera, "cg_smoothCamera", "1", CVAR_ARCHIVE}, + {&cg_speedTrail, "cg_speedTrail", "1", CVAR_ARCHIVE}, + {&cg_fovViewmodel, "cg_fovViewmodel", "0", CVAR_ARCHIVE}, + {&cg_fovViewmodelAdjust, "cg_fovViewmodelAdjust", "1", CVAR_ARCHIVE}, + + {&cg_scaleVehicleSensitivity, "cg_scaleVehicleSensitivity", "1", CVAR_ARCHIVE}, }; -static const size_t cvarTableSize = ARRAY_LEN( cvarTable ); +static const size_t cvarTableSize = ARRAY_LEN(cvarTable); /* ================= CG_RegisterCvars ================= */ -void CG_RegisterCvars( void ) { - size_t i; - cvarTable_t *cv; +void CG_RegisterCvars(void) { + size_t i; + cvarTable_t *cv; - for ( i=0, cv=cvarTable; ivmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + cgi_Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); } } @@ -482,43 +445,38 @@ void CG_RegisterCvars( void ) { CG_UpdateCvars ================= */ -void CG_UpdateCvars( void ) { - size_t i; - cvarTable_t *cv; +void CG_UpdateCvars(void) { + size_t i; + cvarTable_t *cv; - for ( i=0, cv=cvarTable; ivmCvar ) { - cgi_Cvar_Update( cv->vmCvar ); + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + if (cv->vmCvar) { + cgi_Cvar_Update(cv->vmCvar); } } } -int CG_CrosshairPlayer( void ) -{ - if ( cg.time > ( cg.crosshairClientTime + 1000 ) ) - { +int CG_CrosshairPlayer(void) { + if (cg.time > (cg.crosshairClientTime + 1000)) { return -1; } return cg.crosshairClientNum; } -int CG_GetCameraPos( vec3_t camerapos ) { - if ( in_camera) { +int CG_GetCameraPos(vec3_t camerapos) { + if (in_camera) { VectorCopy(client_camera.origin, camerapos); return 1; - } - else if ( cg_entities[0].gent && cg_entities[0].gent->client && cg_entities[0].gent->client->ps.viewEntity > 0 && cg_entities[0].gent->client->ps.viewEntity < ENTITYNUM_WORLD ) - //else if ( cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view - if ( g_entities[cg_entities[0].gent->client->ps.viewEntity].client && cg.renderingThirdPerson ) - { - VectorCopy( g_entities[cg_entities[0].gent->client->ps.viewEntity].client->renderInfo.eyePoint, camerapos ); - } - else - { - VectorCopy( g_entities[cg_entities[0].gent->client->ps.viewEntity].currentOrigin, camerapos ); - } - //VectorCopy( cg_entities[cg_entities[0].gent->client->ps.viewEntity].lerpOrigin, camerapos ); + } else if (cg_entities[0].gent && cg_entities[0].gent->client && cg_entities[0].gent->client->ps.viewEntity > 0 && + cg_entities[0].gent->client->ps.viewEntity < ENTITYNUM_WORLD) + // else if ( cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) + { // in an entity camera view + if (g_entities[cg_entities[0].gent->client->ps.viewEntity].client && cg.renderingThirdPerson) { + VectorCopy(g_entities[cg_entities[0].gent->client->ps.viewEntity].client->renderInfo.eyePoint, camerapos); + } else { + VectorCopy(g_entities[cg_entities[0].gent->client->ps.viewEntity].currentOrigin, camerapos); + } + // VectorCopy( cg_entities[cg_entities[0].gent->client->ps.viewEntity].lerpOrigin, camerapos ); /* if ( g_entities[cg.snap->ps.viewEntity].client && cg.renderingThirdPerson ) { @@ -530,55 +488,48 @@ int CG_GetCameraPos( vec3_t camerapos ) { } */ return 1; - } - else if ( cg.renderingThirdPerson ) - {//in third person - //FIXME: what about hacks that render in third person regardless of this value? - VectorCopy( cg.refdef.vieworg, camerapos ); + } else if (cg.renderingThirdPerson) { // in third person + // FIXME: what about hacks that render in third person regardless of this value? + VectorCopy(cg.refdef.vieworg, camerapos); return 1; - } - else if (cg.snap && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//implied: !cg.renderingThirdPerson - {//first person saber hack - VectorCopy( cg.refdef.vieworg, camerapos ); + } else if (cg.snap && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // implied: !cg.renderingThirdPerson + { // first person saber hack + VectorCopy(cg.refdef.vieworg, camerapos); return 1; } return 0; } -int CG_GetCameraAng( vec3_t cameraang ) -{ - if ( in_camera) - { +int CG_GetCameraAng(vec3_t cameraang) { + if (in_camera) { VectorCopy(client_camera.angles, cameraang); return 1; - } - else - { - VectorCopy( cg.refdefViewAngles, cameraang ); + } else { + VectorCopy(cg.refdefViewAngles, cameraang); return 1; } } -void CG_Printf( const char *msg, ... ) { - va_list argptr; - char text[1024]; +void CG_Printf(const char *msg, ...) { + va_list argptr; + char text[1024]; - va_start (argptr, msg); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end (argptr); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - cgi_Printf( text ); + cgi_Printf(text); } -NORETURN void CG_Error( const char *msg, ... ) { - va_list argptr; - char text[1024]; +NORETURN void CG_Error(const char *msg, ...) { + va_list argptr; + char text[1024]; - va_start (argptr, msg); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end (argptr); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - cgi_Error( text ); + cgi_Error(text); } /* @@ -586,10 +537,10 @@ NORETURN void CG_Error( const char *msg, ... ) { CG_Argv ================ */ -const char *CG_Argv( int arg ) { - static char buffer[MAX_STRING_CHARS]; +const char *CG_Argv(int arg) { + static char buffer[MAX_STRING_CHARS]; - cgi_Argv( arg, buffer, sizeof( buffer ) ); + cgi_Argv(arg, buffer, sizeof(buffer)); return buffer; } @@ -603,17 +554,16 @@ CG_RegisterItemSounds The server says this item is used on this level ================= */ -void CG_RegisterItemSounds( int itemNum ) { - gitem_t *item; - char data[MAX_QPATH]; - const char *s, *start; - int len; +void CG_RegisterItemSounds(int itemNum) { + gitem_t *item; + char data[MAX_QPATH]; + const char *s, *start; + int len; - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - if (item->pickup_sound) - { - cgi_S_RegisterSound( item->pickup_sound ); + if (item->pickup_sound) { + cgi_S_RegisterSound(item->pickup_sound); } // parse the space seperated precache string for other media @@ -627,20 +577,19 @@ void CG_RegisterItemSounds( int itemNum ) { s++; } - len = s-start; + len = s - start; if (len >= MAX_QPATH || len < 5) { - CG_Error( "PrecacheItem: %s has bad precache string", - item->classname); + CG_Error("PrecacheItem: %s has bad precache string", item->classname); return; } - memcpy (data, start, len); + memcpy(data, start, len); data[len] = 0; - if ( *s ) { + if (*s) { s++; } - if ( !strcmp(data+len-3, "wav" )) { - cgi_S_RegisterSound( data ); + if (!strcmp(data + len - 3, "wav")) { + cgi_S_RegisterSound(data); } } } @@ -651,26 +600,22 @@ CG_LoadingString ====================== */ -void CG_LoadingString( const char *s ) { - Q_strncpyz( cg.infoScreenText, s, sizeof( cg.infoScreenText ) ); +void CG_LoadingString(const char *s) { + Q_strncpyz(cg.infoScreenText, s, sizeof(cg.infoScreenText)); cgi_UpdateScreen(); } -static inline void CG_AS_Register(void) -{ - CG_LoadingString( "ambient sound sets" ); +static inline void CG_AS_Register(void) { + CG_LoadingString("ambient sound sets"); assert(as_preCacheMap); - //Load the ambient sets + // Load the ambient sets - cgi_AS_AddPrecacheEntry( "#clear" ); // ;-) - //FIXME: Don't ask... I had to get around a really nasty MS error in the templates with this... - namePrecache_m::iterator pi; - STL_ITERATE( pi, (*as_preCacheMap) ) - { - cgi_AS_AddPrecacheEntry( ((*pi).first).c_str() ); - } + cgi_AS_AddPrecacheEntry("#clear"); // ;-) + // FIXME: Don't ask... I had to get around a really nasty MS error in the templates with this... + namePrecache_m::iterator pi; + STL_ITERATE(pi, (*as_preCacheMap)) { cgi_AS_AddPrecacheEntry(((*pi).first).c_str()); } cgi_AS_ParseSets(); } @@ -682,160 +627,159 @@ CG_RegisterSounds called during a precache command ================= */ -static void CG_RegisterSounds( void ) { - int i; - char name[MAX_QPATH]; - const char *soundName; +static void CG_RegisterSounds(void) { + int i; + char name[MAX_QPATH]; + const char *soundName; CG_AS_Register(); - CG_LoadingString( "general sounds" ); + CG_LoadingString("general sounds"); - //FIXME: add to cg.media? - cgi_S_RegisterSound( "sound/player/fallsplat.wav" ); + // FIXME: add to cg.media? + cgi_S_RegisterSound("sound/player/fallsplat.wav"); - cgs.media.selectSound = cgi_S_RegisterSound( "sound/weapons/change.wav" ); - cgs.media.selectSound2 = cgi_S_RegisterSound( "sound/interface/sub_select.wav" ); -// cgs.media.useNothingSound = cgi_S_RegisterSound( "sound/items/use_nothing.wav" ); + cgs.media.selectSound = cgi_S_RegisterSound("sound/weapons/change.wav"); + cgs.media.selectSound2 = cgi_S_RegisterSound("sound/interface/sub_select.wav"); + // cgs.media.useNothingSound = cgi_S_RegisterSound( "sound/items/use_nothing.wav" ); - cgs.media.noAmmoSound = cgi_S_RegisterSound( "sound/weapons/noammo.wav" ); -// cgs.media.talkSound = cgi_S_RegisterSound( "sound/interface/communicator.wav" ); - cgs.media.landSound = cgi_S_RegisterSound( "sound/player/land1.wav"); - cgs.media.rollSound = cgi_S_RegisterSound( "sound/player/roll1.wav"); - theFxScheduler.RegisterEffect( "env/slide_dust" ); + cgs.media.noAmmoSound = cgi_S_RegisterSound("sound/weapons/noammo.wav"); + // cgs.media.talkSound = cgi_S_RegisterSound( "sound/interface/communicator.wav" ); + cgs.media.landSound = cgi_S_RegisterSound("sound/player/land1.wav"); + cgs.media.rollSound = cgi_S_RegisterSound("sound/player/roll1.wav"); + theFxScheduler.RegisterEffect("env/slide_dust"); - cgs.media.overchargeFastSound = cgi_S_RegisterSound("sound/weapons/overchargeFast.wav" ); - cgs.media.overchargeSlowSound = cgi_S_RegisterSound("sound/weapons/overchargeSlow.wav" ); - cgs.media.overchargeLoopSound = cgi_S_RegisterSound("sound/weapons/overchargeLoop.wav"); - cgs.media.overchargeEndSound = cgi_S_RegisterSound("sound/weapons/overchargeEnd.wav"); + cgs.media.overchargeFastSound = cgi_S_RegisterSound("sound/weapons/overchargeFast.wav"); + cgs.media.overchargeSlowSound = cgi_S_RegisterSound("sound/weapons/overchargeSlow.wav"); + cgs.media.overchargeLoopSound = cgi_S_RegisterSound("sound/weapons/overchargeLoop.wav"); + cgs.media.overchargeEndSound = cgi_S_RegisterSound("sound/weapons/overchargeEnd.wav"); - cgs.media.batteryChargeSound = cgi_S_RegisterSound( "sound/interface/pickup_battery.wav" ); + cgs.media.batteryChargeSound = cgi_S_RegisterSound("sound/interface/pickup_battery.wav"); -// cgs.media.tedTextSound = cgi_S_RegisterSound( "sound/interface/tedtext.wav" ); - cgs.media.messageLitSound = cgi_S_RegisterSound( "sound/interface/update" ); + // cgs.media.tedTextSound = cgi_S_RegisterSound( "sound/interface/tedtext.wav" ); + cgs.media.messageLitSound = cgi_S_RegisterSound("sound/interface/update"); - cgs.media.noforceSound = cgi_S_RegisterSound( "sound/weapons/force/noforce" ); + cgs.media.noforceSound = cgi_S_RegisterSound("sound/weapons/force/noforce"); - cgs.media.watrInSound = cgi_S_RegisterSound ("sound/player/watr_in.wav"); - cgs.media.watrOutSound = cgi_S_RegisterSound ("sound/player/watr_out.wav"); - cgs.media.watrUnSound = cgi_S_RegisterSound ("sound/player/watr_un.wav"); + cgs.media.watrInSound = cgi_S_RegisterSound("sound/player/watr_in.wav"); + cgs.media.watrOutSound = cgi_S_RegisterSound("sound/player/watr_out.wav"); + cgs.media.watrUnSound = cgi_S_RegisterSound("sound/player/watr_un.wav"); - if ( (gi.totalMapContents()&CONTENTS_LAVA) ) - { - cgs.media.lavaInSound = cgi_S_RegisterSound ("sound/player/inlava.wav"); - cgs.media.lavaOutSound = cgi_S_RegisterSound ("sound/player/watr_out.wav"); - cgs.media.lavaUnSound = cgi_S_RegisterSound ("sound/player/muckexit.wav"); + if ((gi.totalMapContents() & CONTENTS_LAVA)) { + cgs.media.lavaInSound = cgi_S_RegisterSound("sound/player/inlava.wav"); + cgs.media.lavaOutSound = cgi_S_RegisterSound("sound/player/watr_out.wav"); + cgs.media.lavaUnSound = cgi_S_RegisterSound("sound/player/muckexit.wav"); } // Zoom - cgs.media.zoomStart = cgi_S_RegisterSound( "sound/interface/zoomstart.wav" ); - cgs.media.zoomLoop = cgi_S_RegisterSound( "sound/interface/zoomloop.wav" ); - cgs.media.zoomEnd = cgi_S_RegisterSound( "sound/interface/zoomend.wav" ); - - cgi_S_RegisterSound( "sound/chars/turret/startup.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/shutdown.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/ping.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/move.wav" ); - cgi_S_RegisterSound( "sound/player/use_sentry" ); - cgi_R_RegisterModel( "models/items/psgun.glm" ); - theFxScheduler.RegisterEffect( "turret/explode" ); - theFxScheduler.RegisterEffect( "sparks/spark_exp_nosnd" ); - - for (i=0 ; i<4 ; i++) { - Com_sprintf (name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_STONEWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/stone_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_STONERUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_METALWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/metal_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_METALRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/pipe_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_PIPEWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/pipe_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_PIPERUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SPLASH][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WADE][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SWIM][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/snow_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SNOWWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/snow_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SNOWRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/sand_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SANDWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/sand_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SANDRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/grass_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRASSWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/grass_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRASSRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/dirt_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_DIRTWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/dirt_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_DIRTRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/mud_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_MUDWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/mud_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_MUDRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/gravel_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRAVELWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/gravel_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRAVELRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/rug_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_RUGWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/rug_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_RUGRUN][i] = cgi_S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/wood_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WOODWALK][i] = cgi_S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/wood_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WOODRUN][i] = cgi_S_RegisterSound (name); + cgs.media.zoomStart = cgi_S_RegisterSound("sound/interface/zoomstart.wav"); + cgs.media.zoomLoop = cgi_S_RegisterSound("sound/interface/zoomloop.wav"); + cgs.media.zoomEnd = cgi_S_RegisterSound("sound/interface/zoomend.wav"); + + cgi_S_RegisterSound("sound/chars/turret/startup.wav"); + cgi_S_RegisterSound("sound/chars/turret/shutdown.wav"); + cgi_S_RegisterSound("sound/chars/turret/ping.wav"); + cgi_S_RegisterSound("sound/chars/turret/move.wav"); + cgi_S_RegisterSound("sound/player/use_sentry"); + cgi_R_RegisterModel("models/items/psgun.glm"); + theFxScheduler.RegisterEffect("turret/explode"); + theFxScheduler.RegisterEffect("sparks/spark_exp_nosnd"); + + for (i = 0; i < 4; i++) { + Com_sprintf(name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_STONEWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/stone_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_STONERUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_METALWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/metal_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_METALRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/pipe_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_PIPEWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/pipe_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_PIPERUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SPLASH][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WADE][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SWIM][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/snow_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SNOWWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/snow_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SNOWRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/sand_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SANDWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/sand_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SANDRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/grass_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRASSWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/grass_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRASSRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/dirt_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_DIRTWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/dirt_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_DIRTRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/mud_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_MUDWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/mud_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_MUDRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/gravel_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRAVELWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/gravel_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRAVELRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/rug_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_RUGWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/rug_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_RUGRUN][i] = cgi_S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/wood_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WOODWALK][i] = cgi_S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/wood_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WOODRUN][i] = cgi_S_RegisterSound(name); } cg.loadLCARSStage = 1; - CG_LoadingString( "item sounds" ); + CG_LoadingString("item sounds"); // only register the items that the server says we need - char items[MAX_ITEMS+1]; - //Raz: Fixed buffer overflow + char items[MAX_ITEMS + 1]; + // Raz: Fixed buffer overflow Q_strncpyz(items, CG_ConfigString(CS_ITEMS), sizeof(items)); - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( items[ i ] == '1' ) //even with sound pooling, don't clutter it for low end machines + for (i = 1; i < bg_numItems; i++) { + if (items[i] == '1') // even with sound pooling, don't clutter it for low end machines { - CG_RegisterItemSounds( i ); + CG_RegisterItemSounds(i); } } cg.loadLCARSStage = 2; - CG_LoadingString( "preregistered sounds" ); + CG_LoadingString("preregistered sounds"); - for ( i = 1 ; i < MAX_SOUNDS ; i++ ) { - soundName = CG_ConfigString( CS_SOUNDS+i ); - if ( !soundName[0] ) { + for (i = 1; i < MAX_SOUNDS; i++) { + soundName = CG_ConfigString(CS_SOUNDS + i); + if (!soundName[0]) { break; } - if ( soundName[0] == '*' ) { - continue; // custom sound + if (soundName[0] == '*') { + continue; // custom sound } - if (!(i&7)) { - CG_LoadingString( soundName ); + if (!(i & 7)) { + CG_LoadingString(soundName); } - cgs.sound_precache[i] = cgi_S_RegisterSound( soundName ); + cgs.sound_precache[i] = cgi_S_RegisterSound(soundName); } } @@ -852,44 +796,36 @@ CLIENT INFO CG_RegisterClientSkin ========================== */ -qboolean CG_RegisterClientSkin( clientInfo_t *ci, - const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName) -{ - char hfilename[MAX_QPATH]; - char tfilename[MAX_QPATH]; - char lfilename[MAX_QPATH]; - - Com_sprintf( lfilename, sizeof( lfilename ), "models/players/%s/lower_%s.skin", legsModelName, legsSkinName ); - ci->legsSkin = cgi_R_RegisterSkin( lfilename ); - - if ( !ci->legsSkin ) - { -// Com_Printf( "Failed to load skin file: %s : %s\n", legsModelName, legsSkinName ); - //return qfalse; +qboolean CG_RegisterClientSkin(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, const char *torsoSkinName, + const char *legsModelName, const char *legsSkinName) { + char hfilename[MAX_QPATH]; + char tfilename[MAX_QPATH]; + char lfilename[MAX_QPATH]; + + Com_sprintf(lfilename, sizeof(lfilename), "models/players/%s/lower_%s.skin", legsModelName, legsSkinName); + ci->legsSkin = cgi_R_RegisterSkin(lfilename); + + if (!ci->legsSkin) { + // Com_Printf( "Failed to load skin file: %s : %s\n", legsModelName, legsSkinName ); + // return qfalse; } - if(torsoModelName && torsoSkinName && torsoModelName[0] && torsoSkinName[0]) - { - Com_sprintf( tfilename, sizeof( tfilename ), "models/players/%s/upper_%s.skin", torsoModelName, torsoSkinName ); - ci->torsoSkin = cgi_R_RegisterSkin( tfilename ); + if (torsoModelName && torsoSkinName && torsoModelName[0] && torsoSkinName[0]) { + Com_sprintf(tfilename, sizeof(tfilename), "models/players/%s/upper_%s.skin", torsoModelName, torsoSkinName); + ci->torsoSkin = cgi_R_RegisterSkin(tfilename); - if ( !ci->torsoSkin ) - { - Com_Printf( "Failed to load skin file: %s : %s\n", torsoModelName, torsoSkinName ); + if (!ci->torsoSkin) { + Com_Printf("Failed to load skin file: %s : %s\n", torsoModelName, torsoSkinName); return qfalse; } } - if(headModelName && headSkinName && headModelName[0] && headSkinName[0]) - { - Com_sprintf( hfilename, sizeof( hfilename ), "models/players/%s/head_%s.skin", headModelName, headSkinName ); - ci->headSkin = cgi_R_RegisterSkin( hfilename ); + if (headModelName && headSkinName && headModelName[0] && headSkinName[0]) { + Com_sprintf(hfilename, sizeof(hfilename), "models/players/%s/head_%s.skin", headModelName, headSkinName); + ci->headSkin = cgi_R_RegisterSkin(hfilename); - if ( !ci->headSkin ) - { - Com_Printf( "Failed to load skin file: %s : %s\n", headModelName, headSkinName ); + if (!ci->headSkin) { + Com_Printf("Failed to load skin file: %s : %s\n", headModelName, headSkinName); return qfalse; } } @@ -902,174 +838,136 @@ qboolean CG_RegisterClientSkin( clientInfo_t *ci, CG_RegisterClientModelname ========================== */ -qboolean CG_RegisterClientModelname( clientInfo_t *ci, - const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName ) -{ +qboolean CG_RegisterClientModelname(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, + const char *torsoSkinName, const char *legsModelName, const char *legsSkinName) { /* Ghoul2 Insert Start */ #if 1 - char filename[MAX_QPATH]; + char filename[MAX_QPATH]; - - if ( !legsModelName || !legsModelName[0] ) - { + if (!legsModelName || !legsModelName[0]) { return qtrue; } - Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.mdr", legsModelName ); - ci->legsModel = cgi_R_RegisterModel( filename ); - if ( !ci->legsModel ) - {//he's not skeletal, try the old way - Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.md3", legsModelName ); - ci->legsModel = cgi_R_RegisterModel( filename ); - if ( !ci->legsModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + Com_sprintf(filename, sizeof(filename), "models/players/%s/lower.mdr", legsModelName); + ci->legsModel = cgi_R_RegisterModel(filename); + if (!ci->legsModel) { // he's not skeletal, try the old way + Com_sprintf(filename, sizeof(filename), "models/players/%s/lower.md3", legsModelName); + ci->legsModel = cgi_R_RegisterModel(filename); + if (!ci->legsModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } } - if(torsoModelName && torsoModelName[0]) - {//You are trying to set one - Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.mdr", torsoModelName ); - ci->torsoModel = cgi_R_RegisterModel( filename ); - if ( !ci->torsoModel ) - {//he's not skeletal, try the old way - Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.md3", torsoModelName ); - ci->torsoModel = cgi_R_RegisterModel( filename ); - if ( !ci->torsoModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + if (torsoModelName && torsoModelName[0]) { // You are trying to set one + Com_sprintf(filename, sizeof(filename), "models/players/%s/upper.mdr", torsoModelName); + ci->torsoModel = cgi_R_RegisterModel(filename); + if (!ci->torsoModel) { // he's not skeletal, try the old way + Com_sprintf(filename, sizeof(filename), "models/players/%s/upper.md3", torsoModelName); + ci->torsoModel = cgi_R_RegisterModel(filename); + if (!ci->torsoModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } } - } - else - { + } else { ci->torsoModel = 0; } - if(headModelName && headModelName[0]) - {//You are trying to set one - Com_sprintf( filename, sizeof( filename ), "models/players/%s/head.md3", headModelName ); - ci->headModel = cgi_R_RegisterModel( filename ); - if ( !ci->headModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + if (headModelName && headModelName[0]) { // You are trying to set one + Com_sprintf(filename, sizeof(filename), "models/players/%s/head.md3", headModelName); + ci->headModel = cgi_R_RegisterModel(filename); + if (!ci->headModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } - } - else - { + } else { ci->headModel = 0; } - // if any skins failed to load, return failure - if ( !CG_RegisterClientSkin( ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName ) ) - { - //Com_Printf( "Failed to load skin file: %s : %s/%s : %s/%s : %s\n", headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName ); + if (!CG_RegisterClientSkin(ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName)) { + // Com_Printf( "Failed to load skin file: %s : %s/%s : %s/%s : %s\n", headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, + // legsSkinName ); return qfalse; } - //FIXME: for now, uses the legs model dir for anim cfg, but should we set this in some sort of NPCs.cfg? - // load the animation file set + // FIXME: for now, uses the legs model dir for anim cfg, but should we set this in some sort of NPCs.cfg? + // load the animation file set ci->animFileIndex = G_ParseAnimFileSet(legsModelName); - if (ci->animFileIndex<0) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/%s\n", legsModelName ); + if (ci->animFileIndex < 0) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/%s\n", legsModelName); return qfalse; } #endif -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ return qtrue; } +void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) { + char *slash; + char headModelName[MAX_QPATH]; + char torsoModelName[MAX_QPATH]; + char legsModelName[MAX_QPATH]; + char headSkinName[MAX_QPATH]; + char torsoSkinName[MAX_QPATH]; + char legsSkinName[MAX_QPATH]; -void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) -{ - char *slash; - char headModelName[MAX_QPATH]; - char torsoModelName[MAX_QPATH]; - char legsModelName[MAX_QPATH]; - char headSkinName[MAX_QPATH]; - char torsoSkinName[MAX_QPATH]; - char legsSkinName[MAX_QPATH]; - - if(!ri->legsModelName[0]) - {//Must have at LEAST a legs model + if (!ri->legsModelName[0]) { // Must have at LEAST a legs model return; } - Q_strncpyz( legsModelName, ri->legsModelName, sizeof( legsModelName ) ); - //Legs skin - slash = strchr( legsModelName, '/' ); - if ( !slash ) - { + Q_strncpyz(legsModelName, ri->legsModelName, sizeof(legsModelName)); + // Legs skin + slash = strchr(legsModelName, '/'); + if (!slash) { // modelName didn not include a skin name - Q_strncpyz( legsSkinName, "default", sizeof( legsSkinName ) ); - } - else - { - Q_strncpyz( legsSkinName, slash + 1, sizeof( legsSkinName ) ); + Q_strncpyz(legsSkinName, "default", sizeof(legsSkinName)); + } else { + Q_strncpyz(legsSkinName, slash + 1, sizeof(legsSkinName)); // truncate modelName *slash = 0; } - if(ri->torsoModelName[0]) - { - Q_strncpyz( torsoModelName, ri->torsoModelName, sizeof( torsoModelName ) ); - //Torso skin - slash = strchr( torsoModelName, '/' ); - if ( !slash ) - { + if (ri->torsoModelName[0]) { + Q_strncpyz(torsoModelName, ri->torsoModelName, sizeof(torsoModelName)); + // Torso skin + slash = strchr(torsoModelName, '/'); + if (!slash) { // modelName didn't include a skin name - Q_strncpyz( torsoSkinName, "default", sizeof( torsoSkinName ) ); - } - else - { - Q_strncpyz( torsoSkinName, slash + 1, sizeof( torsoSkinName ) ); + Q_strncpyz(torsoSkinName, "default", sizeof(torsoSkinName)); + } else { + Q_strncpyz(torsoSkinName, slash + 1, sizeof(torsoSkinName)); // truncate modelName *slash = 0; } - } - else - { + } else { torsoModelName[0] = 0; } - //Head - if(ri->headModelName[0]) - { - Q_strncpyz( headModelName, ri->headModelName, sizeof( headModelName ) ); - //Head skin - slash = strchr( headModelName, '/' ); - if ( !slash ) - { + // Head + if (ri->headModelName[0]) { + Q_strncpyz(headModelName, ri->headModelName, sizeof(headModelName)); + // Head skin + slash = strchr(headModelName, '/'); + if (!slash) { // modelName didn not include a skin name - Q_strncpyz( headSkinName, "default", sizeof( headSkinName ) ); - } - else - { - Q_strncpyz( headSkinName, slash + 1, sizeof( headSkinName ) ); + Q_strncpyz(headSkinName, "default", sizeof(headSkinName)); + } else { + Q_strncpyz(headSkinName, slash + 1, sizeof(headSkinName)); // truncate modelName *slash = 0; } - } - else - { + } else { headModelName[0] = 0; } - if ( !CG_RegisterClientModelname( ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName) ) - { - if ( !CG_RegisterClientModelname( ci, DEFAULT_HEADMODEL, "default", DEFAULT_TORSOMODEL, "default", DEFAULT_LEGSMODEL, "default" ) ) - { - CG_Error( "DEFAULT_MODELS failed to register"); + if (!CG_RegisterClientModelname(ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName)) { + if (!CG_RegisterClientModelname(ci, DEFAULT_HEADMODEL, "default", DEFAULT_TORSOMODEL, "default", DEFAULT_LEGSMODEL, "default")) { + CG_Error("DEFAULT_MODELS failed to register"); } } } @@ -1081,79 +979,69 @@ void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) // and any shader, model, or sound // files an effect may use. //------------------------------------- -extern void CG_InitGlass( void ); -extern void cgi_R_WorldEffectCommand( const char *command ); +extern void CG_InitGlass(void); +extern void cgi_R_WorldEffectCommand(const char *command); extern cvar_t *g_delayedShutdown; -static void CG_RegisterEffects( void ) -{ - char *effectName; - int i, numFailed=0; +static void CG_RegisterEffects(void) { + char *effectName; + int i, numFailed = 0; // Register external effects - for ( i = 1 ; i < MAX_FX ; i++ ) - { - effectName = ( char *)CG_ConfigString( CS_EFFECTS + i ); + for (i = 1; i < MAX_FX; i++) { + effectName = (char *)CG_ConfigString(CS_EFFECTS + i); - if ( !effectName[0] ) - { + if (!effectName[0]) { break; } - if (!theFxScheduler.RegisterEffect( (const char*)effectName )) - { - //assert(0); + if (!theFxScheduler.RegisterEffect((const char *)effectName)) { + // assert(0); numFailed++; } } - if (numFailed && g_delayedShutdown->integer) - { - //assert(0); - //CG_Error( "CG_RegisterEffects: %i Effects failed to load. Please fix, or ask Aurelio.", numFailed ); + if (numFailed && g_delayedShutdown->integer) { + // assert(0); + // CG_Error( "CG_RegisterEffects: %i Effects failed to load. Please fix, or ask Aurelio.", numFailed ); } // Start world effects - for ( i = 1 ; i < MAX_WORLD_FX ; i++ ) - { - effectName = ( char *)CG_ConfigString( CS_WORLD_FX + i ); + for (i = 1; i < MAX_WORLD_FX; i++) { + effectName = (char *)CG_ConfigString(CS_WORLD_FX + i); - if ( !effectName[0] ) - { + if (!effectName[0]) { break; } - cgi_R_WorldEffectCommand( effectName ); + cgi_R_WorldEffectCommand(effectName); } // Set up the glass effects mini-system. CG_InitGlass(); - //footstep effects - cgs.effects.footstepMud = theFxScheduler.RegisterEffect( "materials/mud" ); - cgs.effects.footstepSand = theFxScheduler.RegisterEffect( "materials/sand" ); - cgs.effects.footstepSnow = theFxScheduler.RegisterEffect( "materials/snow" ); - cgs.effects.footstepGravel = theFxScheduler.RegisterEffect( "materials/gravel" ); - //landing effects - cgs.effects.landingMud = theFxScheduler.RegisterEffect( "materials/mud_large" ); - cgs.effects.landingSand = theFxScheduler.RegisterEffect( "materials/sand_large" ); - cgs.effects.landingDirt = theFxScheduler.RegisterEffect( "materials/dirt_large" ); - cgs.effects.landingSnow = theFxScheduler.RegisterEffect( "materials/snow_large" ); - cgs.effects.landingGravel = theFxScheduler.RegisterEffect( "materials/gravel_large" ); - //splashes - if ( (gi.totalMapContents()&CONTENTS_WATER) ) - { - theFxScheduler.RegisterEffect( "env/water_impact" ); - theFxScheduler.RegisterEffect( "misc/waterbreath" ); + // footstep effects + cgs.effects.footstepMud = theFxScheduler.RegisterEffect("materials/mud"); + cgs.effects.footstepSand = theFxScheduler.RegisterEffect("materials/sand"); + cgs.effects.footstepSnow = theFxScheduler.RegisterEffect("materials/snow"); + cgs.effects.footstepGravel = theFxScheduler.RegisterEffect("materials/gravel"); + // landing effects + cgs.effects.landingMud = theFxScheduler.RegisterEffect("materials/mud_large"); + cgs.effects.landingSand = theFxScheduler.RegisterEffect("materials/sand_large"); + cgs.effects.landingDirt = theFxScheduler.RegisterEffect("materials/dirt_large"); + cgs.effects.landingSnow = theFxScheduler.RegisterEffect("materials/snow_large"); + cgs.effects.landingGravel = theFxScheduler.RegisterEffect("materials/gravel_large"); + // splashes + if ((gi.totalMapContents() & CONTENTS_WATER)) { + theFxScheduler.RegisterEffect("env/water_impact"); + theFxScheduler.RegisterEffect("misc/waterbreath"); } - if ( (gi.totalMapContents()&CONTENTS_LAVA) ) - { - theFxScheduler.RegisterEffect( "env/lava_splash" ); + if ((gi.totalMapContents() & CONTENTS_LAVA)) { + theFxScheduler.RegisterEffect("env/lava_splash"); } - if ( (gi.totalMapContents()&CONTENTS_SLIME) ) - { - theFxScheduler.RegisterEffect( "env/acid_splash" ); + if ((gi.totalMapContents() & CONTENTS_SLIME)) { + theFxScheduler.RegisterEffect("env/acid_splash"); } - theFxScheduler.RegisterEffect( "misc/breath" ); + theFxScheduler.RegisterEffect("misc/breath"); } /* @@ -1163,86 +1051,74 @@ Only call if clientInfo->infoValid is not true For players and NPCs to register their models */ -void CG_RegisterClientModels (int entityNum) -{ - gentity_t *ent; +void CG_RegisterClientModels(int entityNum) { + gentity_t *ent; - if(entityNum < 0 || entityNum > ENTITYNUM_WORLD) - { + if (entityNum < 0 || entityNum > ENTITYNUM_WORLD) { return; } ent = &g_entities[entityNum]; - if(!ent->client) - { + if (!ent->client) { return; } ent->client->clientInfo.infoValid = qtrue; - if ( ent->playerModel != -1 && ent->ghoul2.size() ) - { + if (ent->playerModel != -1 && ent->ghoul2.size()) { return; } CG_RegisterClientRenderInfo(&ent->client->clientInfo, &ent->client->renderInfo); - if(entityNum < MAX_CLIENTS) - { + if (entityNum < MAX_CLIENTS) { memcpy(&cgs.clientinfo[entityNum], &ent->client->clientInfo, sizeof(clientInfo_t)); } } //=================================================================================== - -HUDMenuItem_t forceTics[] = -{ - { "rightHUD", "force_tic1", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "force_tic2", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "force_tic3", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "force_tic4", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top +HUDMenuItem_t forceTics[] = { + {"rightHUD", "force_tic1", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "force_tic2", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "force_tic3", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "force_tic4", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top }; -HUDMenuItem_t ammoTics[] = -{ - { "rightHUD", "ammo_tic1", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "ammo_tic2", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "ammo_tic3", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "rightHUD", "ammo_tic4", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top +HUDMenuItem_t ammoTics[] = { + {"rightHUD", "ammo_tic1", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "ammo_tic2", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "ammo_tic3", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"rightHUD", "ammo_tic4", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top }; -HUDMenuItem_t armorTics[] = -{ - { "leftHUD", "armor_tic1", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "leftHUD", "armor_tic2", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, - { "leftHUD", "armor_tic3", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, - { "leftHUD", "armor_tic4", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, +HUDMenuItem_t armorTics[] = { + {"leftHUD", "armor_tic1", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"leftHUD", "armor_tic2", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, + {"leftHUD", "armor_tic3", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, + {"leftHUD", "armor_tic4", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, }; -HUDMenuItem_t healthTics[] = -{ - { "leftHUD", "health_tic1", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Top - { "leftHUD", "health_tic2", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // - { "leftHUD", "health_tic3", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // - { "leftHUD", "health_tic4", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // Bottom +HUDMenuItem_t healthTics[] = { + {"leftHUD", "health_tic1", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Top + {"leftHUD", "health_tic2", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // + {"leftHUD", "health_tic3", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // + {"leftHUD", "health_tic4", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // Bottom }; - -HUDMenuItem_t otherHUDBits[] = -{ - { "lefthud", "healthamount", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_HEALTHAMOUNT - { "lefthud", "armoramount", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_ARMORAMOUNT - { "righthud", "forceamount", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_FORCEAMOUNT - { "righthud", "ammoamount", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_AMMOAMOUNT - { "righthud", "saberstyle_strong", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_SABERSTYLE_STRONG - { "righthud", "saberstyle_medium", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_SABERSTYLE_MEDIUM - { "righthud", "saberstyle_fast", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_SABERSTYLE_FAST - { "lefthud", "scanline", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_SCANLINE_LEFT - { "righthud", "scanline", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_SCANLINE_RIGHT - { "lefthud", "frame", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_FRAME_LEFT - { "righthud", "frame", 0, 0, 0, 0, { 0.0f, 0.0f, 0.0f, 0.0f }, NULL_HANDLE }, // OHB_FRAME_RIGHT +HUDMenuItem_t otherHUDBits[] = { + {"lefthud", "healthamount", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_HEALTHAMOUNT + {"lefthud", "armoramount", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_ARMORAMOUNT + {"righthud", "forceamount", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_FORCEAMOUNT + {"righthud", "ammoamount", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_AMMOAMOUNT + {"righthud", "saberstyle_strong", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_SABERSTYLE_STRONG + {"righthud", "saberstyle_medium", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_SABERSTYLE_MEDIUM + {"righthud", "saberstyle_fast", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_SABERSTYLE_FAST + {"lefthud", "scanline", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_SCANLINE_LEFT + {"righthud", "scanline", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_SCANLINE_RIGHT + {"lefthud", "frame", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_FRAME_LEFT + {"righthud", "frame", 0, 0, 0, 0, {0.0f, 0.0f, 0.0f, 0.0f}, NULL_HANDLE}, // OHB_FRAME_RIGHT }; /*const char *HolocronIcons[] = { @@ -1266,7 +1142,7 @@ HUDMenuItem_t otherHUDBits[] = "gfx/mp/f_icon_saber_throw" //FP_SABERTHROW }; */ -extern void CG_NPC_Precache ( gentity_t *spawner ); +extern void CG_NPC_Precache(gentity_t *spawner); qboolean NPCsPrecached = qfalse; /* ================= @@ -1277,395 +1153,310 @@ This function may execute for a couple of minutes with a slow disk. ================= */ void CG_CreateMiscEnts(void); -static void CG_RegisterGraphics( void ) { - int i; - char items[MAX_ITEMS+1]; - int breakPoint = 0; - const char *sb_nums[11] = { - "gfx/2d/numbers/zero", - "gfx/2d/numbers/one", - "gfx/2d/numbers/two", - "gfx/2d/numbers/three", - "gfx/2d/numbers/four", - "gfx/2d/numbers/five", - "gfx/2d/numbers/six", - "gfx/2d/numbers/seven", - "gfx/2d/numbers/eight", - "gfx/2d/numbers/nine", - "gfx/2d/numbers/minus", +static void CG_RegisterGraphics(void) { + int i; + char items[MAX_ITEMS + 1]; + int breakPoint = 0; + const char *sb_nums[11] = { + "gfx/2d/numbers/zero", "gfx/2d/numbers/one", "gfx/2d/numbers/two", "gfx/2d/numbers/three", "gfx/2d/numbers/four", "gfx/2d/numbers/five", + "gfx/2d/numbers/six", "gfx/2d/numbers/seven", "gfx/2d/numbers/eight", "gfx/2d/numbers/nine", "gfx/2d/numbers/minus", }; - const char *sb_t_nums[11] = { - "gfx/2d/numbers/t_zero", - "gfx/2d/numbers/t_one", - "gfx/2d/numbers/t_two", - "gfx/2d/numbers/t_three", - "gfx/2d/numbers/t_four", - "gfx/2d/numbers/t_five", - "gfx/2d/numbers/t_six", - "gfx/2d/numbers/t_seven", - "gfx/2d/numbers/t_eight", - "gfx/2d/numbers/t_nine", - "gfx/2d/numbers/t_minus", + const char *sb_t_nums[11] = { + "gfx/2d/numbers/t_zero", "gfx/2d/numbers/t_one", "gfx/2d/numbers/t_two", "gfx/2d/numbers/t_three", + "gfx/2d/numbers/t_four", "gfx/2d/numbers/t_five", "gfx/2d/numbers/t_six", "gfx/2d/numbers/t_seven", + "gfx/2d/numbers/t_eight", "gfx/2d/numbers/t_nine", "gfx/2d/numbers/t_minus", }; - const char *sb_c_nums[11] = { - "gfx/2d/numbers/c_zero", - "gfx/2d/numbers/c_one", - "gfx/2d/numbers/c_two", - "gfx/2d/numbers/c_three", - "gfx/2d/numbers/c_four", - "gfx/2d/numbers/c_five", - "gfx/2d/numbers/c_six", - "gfx/2d/numbers/c_seven", - "gfx/2d/numbers/c_eight", - "gfx/2d/numbers/c_nine", + const char *sb_c_nums[11] = { + "gfx/2d/numbers/c_zero", "gfx/2d/numbers/c_one", "gfx/2d/numbers/c_two", "gfx/2d/numbers/c_three", "gfx/2d/numbers/c_four", + "gfx/2d/numbers/c_five", "gfx/2d/numbers/c_six", "gfx/2d/numbers/c_seven", "gfx/2d/numbers/c_eight", "gfx/2d/numbers/c_nine", "gfx/2d/numbers/t_minus", //????? }; // Clean, then register...rinse...repeat... - CG_LoadingString( "effects" ); + CG_LoadingString("effects"); FX_Init(); CG_RegisterEffects(); // clear any references to old media - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); cgi_R_ClearScene(); cg.loadLCARSStage = 3; - CG_LoadingString( cgs.mapname ); + CG_LoadingString(cgs.mapname); - cgi_R_LoadWorldMap( cgs.mapname ); + cgi_R_LoadWorldMap(cgs.mapname); cg.loadLCARSStage = 4; - CG_LoadingString( "game media shaders" ); + CG_LoadingString("game media shaders"); - for ( i=0; i < 11; i++ ) - { - cgs.media.numberShaders[i] = cgi_R_RegisterShaderNoMip( sb_nums[i] ); - cgs.media.smallnumberShaders[i] = cgi_R_RegisterShaderNoMip( sb_t_nums[i] ); - cgs.media.chunkyNumberShaders[i] = cgi_R_RegisterShaderNoMip( sb_c_nums[i] ); + for (i = 0; i < 11; i++) { + cgs.media.numberShaders[i] = cgi_R_RegisterShaderNoMip(sb_nums[i]); + cgs.media.smallnumberShaders[i] = cgi_R_RegisterShaderNoMip(sb_t_nums[i]); + cgs.media.chunkyNumberShaders[i] = cgi_R_RegisterShaderNoMip(sb_c_nums[i]); } // FIXME: conditionally do this?? Something must be wrong with inventory item caching..? - cgi_R_RegisterModel( "models/items/remote.md3" ); + cgi_R_RegisterModel("models/items/remote.md3"); - cgs.media.explosionModel = cgi_R_RegisterModel ( "models/weaphits/explosion.md3" ); - cgs.media.surfaceExplosionShader = cgi_R_RegisterShader( "surfaceExplosion" ); + cgs.media.explosionModel = cgi_R_RegisterModel("models/weaphits/explosion.md3"); + cgs.media.surfaceExplosionShader = cgi_R_RegisterShader("surfaceExplosion"); - cgs.media.halfShieldModel = cgi_R_RegisterModel( "models/weaphits/testboom.md3" ); + cgs.media.halfShieldModel = cgi_R_RegisterModel("models/weaphits/testboom.md3"); - cgs.media.solidWhiteShader = cgi_R_RegisterShader( "gfx/effects/solidWhite" ); - cgs.media.refractShader = cgi_R_RegisterShader( "effects/refraction" ); + cgs.media.solidWhiteShader = cgi_R_RegisterShader("gfx/effects/solidWhite"); + cgs.media.refractShader = cgi_R_RegisterShader("effects/refraction"); - //on players - cgs.media.personalShieldShader = cgi_R_RegisterShader( "gfx/misc/personalshield" ); - cgs.media.cloakedShader = cgi_R_RegisterShader( "gfx/effects/cloakedShader" ); - cgi_R_RegisterShader( "gfx/misc/ion_shield" ); + // on players + cgs.media.personalShieldShader = cgi_R_RegisterShader("gfx/misc/personalshield"); + cgs.media.cloakedShader = cgi_R_RegisterShader("gfx/effects/cloakedShader"); + cgi_R_RegisterShader("gfx/misc/ion_shield"); - cgs.media.boltShader = cgi_R_RegisterShader( "gfx/misc/blueLine" ); + cgs.media.boltShader = cgi_R_RegisterShader("gfx/misc/blueLine"); // FIXME: do these conditionally - cgi_R_RegisterShader( "gfx/2d/workingCamera" ); - cgi_R_RegisterShader( "gfx/2d/brokenCamera" ); - //cgi_R_RegisterShader( "gfx/effects/irid_shield" ); // for galak, but he doesn't have his own weapon so I can't register the shader there. + cgi_R_RegisterShader("gfx/2d/workingCamera"); + cgi_R_RegisterShader("gfx/2d/brokenCamera"); + // cgi_R_RegisterShader( "gfx/effects/irid_shield" ); // for galak, but he doesn't have his own weapon so I can't register the shader there. - //interface - for ( i = 0 ; i < NUM_CROSSHAIRS ; i++ ) { - cgs.media.crosshairShader[i] = cgi_R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a'+i) ); + // interface + for (i = 0; i < NUM_CROSSHAIRS; i++) { + cgs.media.crosshairShader[i] = cgi_R_RegisterShaderNoMip(va("gfx/2d/crosshair%c", 'a' + i)); } - cgs.media.backTileShader = cgi_R_RegisterShader( "gfx/2d/backtile" ); -// cgs.media.noammoShader = cgi_R_RegisterShaderNoMip( "gfx/hud/noammo"); - cgs.media.weaponIconBackground = cgi_R_RegisterShaderNoMip( "gfx/hud/background"); - cgs.media.forceIconBackground = cgi_R_RegisterShaderNoMip( "gfx/hud/background_f"); - cgs.media.inventoryIconBackground= cgi_R_RegisterShaderNoMip( "gfx/hud/background_i"); - cgs.media.dataPadFrame = cgi_R_RegisterShaderNoMip( "gfx/menus/datapad"); + cgs.media.backTileShader = cgi_R_RegisterShader("gfx/2d/backtile"); + // cgs.media.noammoShader = cgi_R_RegisterShaderNoMip( "gfx/hud/noammo"); + cgs.media.weaponIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background"); + cgs.media.forceIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background_f"); + cgs.media.inventoryIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background_i"); + cgs.media.dataPadFrame = cgi_R_RegisterShaderNoMip("gfx/menus/datapad"); - //gore decal shaders -rww - cgs.media.bdecal_burnmark1 = cgi_R_RegisterShader( "gfx/damage/burnmark1" ); - cgs.media.bdecal_saberglowmark = cgi_R_RegisterShader( "gfx/damage/saberglowmark" ); + // gore decal shaders -rww + cgs.media.bdecal_burnmark1 = cgi_R_RegisterShader("gfx/damage/burnmark1"); + cgs.media.bdecal_saberglowmark = cgi_R_RegisterShader("gfx/damage/saberglowmark"); cg.loadLCARSStage = 5; - CG_LoadingString( "game media models" ); + CG_LoadingString("game media models"); // Chunk models - //FIXME: jfm:? bother to conditionally load these if an ent has this material type? - for ( i = 0; i < NUM_CHUNK_MODELS; i++ ) - { - cgs.media.chunkModels[CHUNK_METAL2][i] = cgi_R_RegisterModel( va( "models/chunks/metal/metal1_%i.md3", i+1 ) ); //_ /switched\ _ - cgs.media.chunkModels[CHUNK_METAL1][i] = cgi_R_RegisterModel( va( "models/chunks/metal/metal2_%i.md3", i+1 ) ); // \switched/ - cgs.media.chunkModels[CHUNK_ROCK1][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK2][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK3][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock3_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE1][i] = cgi_R_RegisterModel( va( "models/chunks/crate/crate1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE2][i] = cgi_R_RegisterModel( va( "models/chunks/crate/crate2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = cgi_R_RegisterModel( va( "models/chunks/metal/wmetal1_%i.md3", i+1 ) ); - } - - cgs.media.chunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glasslcar"); - cgs.media.grateSound = cgi_S_RegisterSound( "sound/effects/grate_destroy" ); - cgs.media.rockBreakSound = cgi_S_RegisterSound("sound/effects/wall_smash"); - cgs.media.rockBounceSound[0] = cgi_S_RegisterSound("sound/effects/stone_bounce"); - cgs.media.rockBounceSound[1] = cgi_S_RegisterSound("sound/effects/stone_bounce2"); - cgs.media.metalBounceSound[0] = cgi_S_RegisterSound("sound/effects/metal_bounce"); - cgs.media.metalBounceSound[1] = cgi_S_RegisterSound("sound/effects/metal_bounce2"); - cgs.media.glassChunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glassbreak1"); - cgs.media.crateBreakSound[0] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust1" ); - cgs.media.crateBreakSound[1] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust2" ); - - cgs.media.weaponbox = cgi_R_RegisterShaderNoMip( "gfx/interface/weapon_box"); - - //Models & Shaders - cgs.media.damageBlendBlobShader = cgi_R_RegisterShader( "gfx/misc/borgeyeflare" ); + // FIXME: jfm:? bother to conditionally load these if an ent has this material type? + for (i = 0; i < NUM_CHUNK_MODELS; i++) { + cgs.media.chunkModels[CHUNK_METAL2][i] = cgi_R_RegisterModel(va("models/chunks/metal/metal1_%i.md3", i + 1)); //_ /switched\ _ + cgs.media.chunkModels[CHUNK_METAL1][i] = cgi_R_RegisterModel(va("models/chunks/metal/metal2_%i.md3", i + 1)); // \switched/ + cgs.media.chunkModels[CHUNK_ROCK1][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK2][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK3][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock3_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE1][i] = cgi_R_RegisterModel(va("models/chunks/crate/crate1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE2][i] = cgi_R_RegisterModel(va("models/chunks/crate/crate2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = cgi_R_RegisterModel(va("models/chunks/metal/wmetal1_%i.md3", i + 1)); + } + + cgs.media.chunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glasslcar"); + cgs.media.grateSound = cgi_S_RegisterSound("sound/effects/grate_destroy"); + cgs.media.rockBreakSound = cgi_S_RegisterSound("sound/effects/wall_smash"); + cgs.media.rockBounceSound[0] = cgi_S_RegisterSound("sound/effects/stone_bounce"); + cgs.media.rockBounceSound[1] = cgi_S_RegisterSound("sound/effects/stone_bounce2"); + cgs.media.metalBounceSound[0] = cgi_S_RegisterSound("sound/effects/metal_bounce"); + cgs.media.metalBounceSound[1] = cgi_S_RegisterSound("sound/effects/metal_bounce2"); + cgs.media.glassChunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glassbreak1"); + cgs.media.crateBreakSound[0] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust1"); + cgs.media.crateBreakSound[1] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust2"); + + cgs.media.weaponbox = cgi_R_RegisterShaderNoMip("gfx/interface/weapon_box"); + + // Models & Shaders + cgs.media.damageBlendBlobShader = cgi_R_RegisterShader("gfx/misc/borgeyeflare"); cg.loadLCARSStage = 6; - cgs.media.messageLitOn = cgi_R_RegisterShaderNoMip( "gfx/hud/message_on" ); - cgs.media.messageLitOff = cgi_R_RegisterShaderNoMip( "gfx/hud/message_off" ); - cgs.media.messageObjCircle = cgi_R_RegisterShaderNoMip( "gfx/hud/objective_circle" ); + cgs.media.messageLitOn = cgi_R_RegisterShaderNoMip("gfx/hud/message_on"); + cgs.media.messageLitOff = cgi_R_RegisterShaderNoMip("gfx/hud/message_off"); + cgs.media.messageObjCircle = cgi_R_RegisterShaderNoMip("gfx/hud/objective_circle"); - cgs.media.DPForcePowerOverlay = cgi_R_RegisterShader( "gfx/hud/force_swirl" ); + cgs.media.DPForcePowerOverlay = cgi_R_RegisterShader("gfx/hud/force_swirl"); - //NOTE: we should only cache this if there is a vehicle or emplaced gun somewhere on the map - cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip( "gfx/hud/health_frame" ); + // NOTE: we should only cache this if there is a vehicle or emplaced gun somewhere on the map + cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip("gfx/hud/health_frame"); // battery charge shader when using a gonk - cgs.media.batteryChargeShader = cgi_R_RegisterShader( "gfx/2d/battery" ); - cgi_R_RegisterShader( "gfx/2d/droid_view" ); + cgs.media.batteryChargeShader = cgi_R_RegisterShader("gfx/2d/battery"); + cgi_R_RegisterShader("gfx/2d/droid_view"); cgs.media.useableHint = cgi_R_RegisterShader("gfx/hud/useableHint"); // Load up other HUD bits - for (i=0;iclientInfo.infoValid) - //We presume this + for (i = 0; i < ENTITYNUM_WORLD; i++) { + if (g_entities[i].inuse) { + if (g_entities[i].client) { + // if(!g_entities[i].client->clientInfo.infoValid) + // We presume this { - CG_LoadingString( va("client %s", g_entities[i].client->clientInfo.name ) ); + CG_LoadingString(va("client %s", g_entities[i].client->clientInfo.name)); CG_RegisterClientModels(i); - if ( i != 0 ) - {//Client weapons already precached - CG_RegisterWeapon( g_entities[i].client->ps.weapon ); - if ( g_entities[i].client->ps.saber[0].g2MarksShader[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[0].g2MarksShader ); + if (i != 0) { // Client weapons already precached + CG_RegisterWeapon(g_entities[i].client->ps.weapon); + if (g_entities[i].client->ps.saber[0].g2MarksShader[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[0].g2MarksShader); } - if ( g_entities[i].client->ps.saber[0].g2MarksShader2[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[0].g2MarksShader2 ); + if (g_entities[i].client->ps.saber[0].g2MarksShader2[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[0].g2MarksShader2); } - if ( g_entities[i].client->ps.saber[0].g2WeaponMarkShader[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[0].g2WeaponMarkShader ); + if (g_entities[i].client->ps.saber[0].g2WeaponMarkShader[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[0].g2WeaponMarkShader); } - if ( g_entities[i].client->ps.saber[0].g2WeaponMarkShader2[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[0].g2WeaponMarkShader2 ); + if (g_entities[i].client->ps.saber[0].g2WeaponMarkShader2[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[0].g2WeaponMarkShader2); } - if ( g_entities[i].client->ps.saber[1].g2MarksShader[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[1].g2MarksShader ); + if (g_entities[i].client->ps.saber[1].g2MarksShader[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[1].g2MarksShader); } - if ( g_entities[i].client->ps.saber[1].g2MarksShader2[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[1].g2MarksShader2 ); + if (g_entities[i].client->ps.saber[1].g2MarksShader2[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[1].g2MarksShader2); } - if ( g_entities[i].client->ps.saber[1].g2WeaponMarkShader[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[1].g2WeaponMarkShader ); + if (g_entities[i].client->ps.saber[1].g2WeaponMarkShader[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[1].g2WeaponMarkShader); } - if ( g_entities[i].client->ps.saber[1].g2WeaponMarkShader2[0] ) - { - cgi_R_RegisterShader( g_entities[i].client->ps.saber[1].g2WeaponMarkShader2 ); + if (g_entities[i].client->ps.saber[1].g2WeaponMarkShader2[0]) { + cgi_R_RegisterShader(g_entities[i].client->ps.saber[1].g2WeaponMarkShader2); } - CG_RegisterNPCCustomSounds( &g_entities[i].client->clientInfo ); - //CG_RegisterNPCEffects( g_entities[i].client->playerTeam ); + CG_RegisterNPCCustomSounds(&g_entities[i].client->clientInfo); + // CG_RegisterNPCEffects( g_entities[i].client->playerTeam ); } } - } - else if ( g_entities[i].svFlags & SVF_NPC_PRECACHE && g_entities[i].NPC_type && g_entities[i].NPC_type[0] ) - {//Precache the NPC_type - //FIXME: make sure we didn't precache this NPC_type already - CG_LoadingString( va("NPC %s", g_entities[i].NPC_type ) ); + } else if (g_entities[i].svFlags & SVF_NPC_PRECACHE && g_entities[i].NPC_type && g_entities[i].NPC_type[0]) { // Precache the NPC_type + // FIXME: make sure we didn't precache this NPC_type already + CG_LoadingString(va("NPC %s", g_entities[i].NPC_type)); /* if (g_entities[i].classname && g_entities[i].classname[0] && Q_stricmp( g_entities[i].classname, "NPC_Vehicle" ) == 0) { @@ -1674,77 +1465,67 @@ Ghoul2 Insert End } else */ - { - CG_NPC_Precache( &g_entities[i] ); - } + { CG_NPC_Precache(&g_entities[i]); } } } } - CG_LoadingString( "static models" ); + CG_LoadingString("static models"); CG_CreateMiscEnts(); cg.loadLCARSStage = 9; NPCsPrecached = qtrue; - extern cvar_t *com_buildScript; + extern cvar_t *com_buildScript; if (com_buildScript->integer) { - cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ); - cgi_R_RegisterShader( "gfx/misc/nav_line" ); - cgi_R_RegisterShader( "gfx/misc/nav_arrow" ); - cgi_R_RegisterShader( "gfx/misc/nav_node" ); + cgi_R_RegisterShader("gfx/misc/nav_cpoint"); + cgi_R_RegisterShader("gfx/misc/nav_line"); + cgi_R_RegisterShader("gfx/misc/nav_arrow"); + cgi_R_RegisterShader("gfx/misc/nav_node"); } - for(i = 1; i < MAX_SUB_BSP; i++) - { - const char *bspName = 0; - vec3_t mins, maxs; - int j = 0; - int sub = 0; - char temp[MAX_QPATH]; - - bspName = CG_ConfigString( CS_BSP_MODELS+i ); - if ( !bspName[0] ) - { + for (i = 1; i < MAX_SUB_BSP; i++) { + const char *bspName = 0; + vec3_t mins, maxs; + int j = 0; + int sub = 0; + char temp[MAX_QPATH]; + + bspName = CG_ConfigString(CS_BSP_MODELS + i); + if (!bspName[0]) { break; } - CG_LoadingString( "BSP instances" ); + CG_LoadingString("BSP instances"); - cgi_CM_LoadMap( bspName, qtrue ); - cgs.inlineDrawModel[breakPoint] = cgi_R_RegisterModel( bspName ); - cgi_R_ModelBounds( cgs.inlineDrawModel[breakPoint], mins, maxs ); - for ( j = 0 ; j < 3 ; j++ ) - { - cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * ( maxs[j] - mins[j] ); + cgi_CM_LoadMap(bspName, qtrue); + cgs.inlineDrawModel[breakPoint] = cgi_R_RegisterModel(bspName); + cgi_R_ModelBounds(cgs.inlineDrawModel[breakPoint], mins, maxs); + for (j = 0; j < 3; j++) { + cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * (maxs[j] - mins[j]); } breakPoint++; - for(sub=1;sub= MAX_CONFIGSTRINGS ) { - CG_Error( "CG_ConfigString: bad index: %i", index ); +const char *CG_ConfigString(int index) { + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + CG_Error("CG_ConfigString: bad index: %i", index); } - return cgs.gameState.stringData + cgs.gameState.stringOffsets[ index ]; + return cgs.gameState.stringData + cgs.gameState.stringOffsets[index]; } //================================================================== -void CG_LinkCentsToGents(void) -{ - int i; +void CG_LinkCentsToGents(void) { + int i; - for(i = 0; i < MAX_GENTITIES; i++) - { + for (i = 0; i < MAX_GENTITIES; i++) { cg_entities[i].gent = &g_entities[i]; } } @@ -1790,18 +1569,18 @@ CG_StartMusic ====================== */ -void CG_StartMusic( qboolean bForceStart ) { - const char *s; - char parm1[MAX_QPATH], parm2[MAX_QPATH]; +void CG_StartMusic(qboolean bForceStart) { + const char *s; + char parm1[MAX_QPATH], parm2[MAX_QPATH]; // start the background music - s = (char *)CG_ConfigString( CS_MUSIC ); + s = (char *)CG_ConfigString(CS_MUSIC); COM_BeginParseSession(); - Q_strncpyz( parm1, COM_Parse( &s ), sizeof( parm1 ) ); - Q_strncpyz( parm2, COM_Parse( &s ), sizeof( parm2 ) ); + Q_strncpyz(parm1, COM_Parse(&s), sizeof(parm1)); + Q_strncpyz(parm2, COM_Parse(&s), sizeof(parm2)); COM_EndParseSession(); - cgi_S_StartBackgroundTrack( parm1, parm2, (qboolean)!bForceStart ); + cgi_S_StartBackgroundTrack(parm1, parm2, (qboolean)!bForceStart); } /* @@ -1812,83 +1591,79 @@ Displays the info screen while loading media ====================== */ -int iCGResetCount=0; +int iCGResetCount = 0; qboolean qbVidRestartOccured = qfalse; //=================== -qboolean gbUseTheseValuesFromLoadSave = qfalse; // MUST default to this +qboolean gbUseTheseValuesFromLoadSave = qfalse; // MUST default to this int gi_cg_forcepowerSelect; int gi_cg_inventorySelect; //=================== - -static void CG_GameStateReceived( void ) { +static void CG_GameStateReceived(void) { // clear everything - extern void CG_ClearAnimEvtCache( void ); - CG_ClearAnimEvtCache(); // else sound handles wrong after vid_restart + extern void CG_ClearAnimEvtCache(void); + CG_ClearAnimEvtCache(); // else sound handles wrong after vid_restart qbVidRestartOccured = qtrue; iCGResetCount++; - if (iCGResetCount == 1) // this will only equal 1 first time, after each vid_restart it just gets higher. + if (iCGResetCount == 1) // this will only equal 1 first time, after each vid_restart it just gets higher. { // This non-clear is so the user can vid_restart during scrolling text without losing it. qbVidRestartOccured = qfalse; } - if (!qbVidRestartOccured) - { + if (!qbVidRestartOccured) { CG_Init_CG(); cg.weaponSelect = WP_NONE; cg.forcepowerSelect = FP_HEAL; } - memset( cg_weapons, 0, sizeof(cg_weapons) ); - memset( cg_items, 0, sizeof(cg_items) ); + memset(cg_weapons, 0, sizeof(cg_weapons)); + memset(cg_items, 0, sizeof(cg_items)); CG_LinkCentsToGents(); - if (gbUseTheseValuesFromLoadSave) - { - gbUseTheseValuesFromLoadSave = qfalse; // ack + if (gbUseTheseValuesFromLoadSave) { + gbUseTheseValuesFromLoadSave = qfalse; // ack cg.forcepowerSelect = gi_cg_forcepowerSelect; - cg.inventorySelect = gi_cg_inventorySelect; + cg.inventorySelect = gi_cg_inventorySelect; } - // get the rendering configuration from the client system - cgi_GetGlconfig( &cgs.glconfig ); + cgi_GetGlconfig(&cgs.glconfig); -/* cgs.charScale = cgs.glconfig.vidHeight * (1.0/480.0); - if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) { - // wide screen - cgs.bias = 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * (640.0/480.0) ) ); - } - else { - // no wide screen - cgs.bias = 0; - } -*/ + /* cgs.charScale = cgs.glconfig.vidHeight * (1.0/480.0); + if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) { + // wide screen + cgs.bias = 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * (640.0/480.0) ) ); + } + else { + // no wide screen + cgs.bias = 0; + } + */ // get the gamestate from the client system - cgi_GetGameState( &cgs.gameState ); + cgi_GetGameState(&cgs.gameState); CG_ParseServerinfo(); // load the new map - cgs.media.levelLoad = cgi_R_RegisterShaderNoMip( "gfx/hud/mp_levelload" ); - CG_LoadingString( "collision map" ); + cgs.media.levelLoad = cgi_R_RegisterShaderNoMip("gfx/hud/mp_levelload"); + CG_LoadingString("collision map"); - cgi_CM_LoadMap( cgs.mapname, qfalse ); + cgi_CM_LoadMap(cgs.mapname, qfalse); CG_RegisterSounds(); CG_RegisterGraphics(); - //jfm: moved down to preinit -// CG_InitLocalEntities(); -// CG_InitMarkPolys(); + // jfm: moved down to preinit + // CG_InitLocalEntities(); + // CG_InitMarkPolys(); - CG_LoadingString( "music" ); - CG_StartMusic( qfalse ); + CG_LoadingString("music"); + CG_StartMusic(qfalse); // remove the last loading update cg.infoScreenText[0] = 0; @@ -1902,35 +1677,22 @@ static void CG_GameStateReceived( void ) { cg.forceHUDActive = qtrue; cg.forceHUDTotalFlashTime = 0; cg.forceHUDNextFlashTime = 0; - } -void CG_WriteTheEvilCGHackStuff() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void CG_WriteTheEvilCGHackStuff() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('F', 'P', 'S', 'L'), - ::cg.forcepowerSelect); + saved_game.write_chunk(INT_ID('F', 'P', 'S', 'L'), ::cg.forcepowerSelect); - saved_game.write_chunk( - INT_ID('I', 'V', 'S', 'L'), - ::cg.inventorySelect); + saved_game.write_chunk(INT_ID('I', 'V', 'S', 'L'), ::cg.inventorySelect); } -void CG_ReadTheEvilCGHackStuff() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void CG_ReadTheEvilCGHackStuff() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('F', 'P', 'S', 'L'), - ::gi_cg_forcepowerSelect); + saved_game.read_chunk(INT_ID('F', 'P', 'S', 'L'), ::gi_cg_forcepowerSelect); - saved_game.read_chunk( - INT_ID('I', 'V', 'S', 'L'), - ::gi_cg_inventorySelect); + saved_game.read_chunk(INT_ID('I', 'V', 'S', 'L'), ::gi_cg_inventorySelect); gbUseTheseValuesFromLoadSave = qtrue; } @@ -1940,72 +1702,60 @@ Ghoul2 Insert Start */ // initialise the cg_entities structure -void CG_Init_CG(void) -{ - memset( &cg, 0, sizeof(cg)); -} - - -#define MAX_MISC_ENTS 2000 - -typedef struct cgMiscEntData_s -{ - char model[MAX_QPATH]; - qhandle_t hModel; - vec3_t origin; - vec3_t angles; - vec3_t scale; - float radius; - float zOffset; //some models need a z offset for culling, because of stupid wrong model origins +void CG_Init_CG(void) { memset(&cg, 0, sizeof(cg)); } + +#define MAX_MISC_ENTS 2000 + +typedef struct cgMiscEntData_s { + char model[MAX_QPATH]; + qhandle_t hModel; + vec3_t origin; + vec3_t angles; + vec3_t scale; + float radius; + float zOffset; // some models need a z offset for culling, because of stupid wrong model origins } cgMiscEntData_t; -static cgMiscEntData_t MiscEnts[MAX_MISC_ENTS]; //statically allocated for now. -static int NumMiscEnts=0; +static cgMiscEntData_t MiscEnts[MAX_MISC_ENTS]; // statically allocated for now. +static int NumMiscEnts = 0; -void CG_CreateMiscEntFromGent(gentity_t *ent, const vec3_t scale, float zOff) -{ //store the model data - if (NumMiscEnts == MAX_MISC_ENTS) - { - Com_Error(ERR_DROP,"Maximum misc_model_static reached (%d)\n",MAX_MISC_ENTS); +void CG_CreateMiscEntFromGent(gentity_t *ent, const vec3_t scale, float zOff) { // store the model data + if (NumMiscEnts == MAX_MISC_ENTS) { + Com_Error(ERR_DROP, "Maximum misc_model_static reached (%d)\n", MAX_MISC_ENTS); return; } - if (!ent || !ent->model || !ent->model[0]) - { + if (!ent || !ent->model || !ent->model[0]) { Com_Error(ERR_DROP, "misc_model_static with no model."); return; } const size_t len = strlen(ent->model); - if (len < 4 || Q_stricmp(&ent->model[len-4],".md3")!=0) - { - Com_Error(ERR_DROP, "misc_model_static model(%s) is not an md3.",ent->model); + if (len < 4 || Q_stricmp(&ent->model[len - 4], ".md3") != 0) { + Com_Error(ERR_DROP, "misc_model_static model(%s) is not an md3.", ent->model); return; } - cgMiscEntData_t *MiscEnt = &MiscEnts[NumMiscEnts++]; + cgMiscEntData_t *MiscEnt = &MiscEnts[NumMiscEnts++]; memset(MiscEnt, 0, sizeof(*MiscEnt)); strcpy(MiscEnt->model, ent->model); - VectorCopy(ent->s.angles, MiscEnt->angles); - VectorCopy(scale, MiscEnt->scale); - VectorCopy(ent->s.origin, MiscEnt->origin); + VectorCopy(ent->s.angles, MiscEnt->angles); + VectorCopy(scale, MiscEnt->scale); + VectorCopy(ent->s.origin, MiscEnt->origin); MiscEnt->zOffset = zOff; } -#define VectorScaleVector(a,b,c) (((c)[0]=(a)[0]*(b)[0]),((c)[1]=(a)[1]*(b)[1]),((c)[2]=(a)[2]*(b)[2])) -//call on standard model load to spawn the queued stuff -void CG_CreateMiscEnts(void) -{ - vec3_t mins, maxs; +#define VectorScaleVector(a, b, c) (((c)[0] = (a)[0] * (b)[0]), ((c)[1] = (a)[1] * (b)[1]), ((c)[2] = (a)[2] * (b)[2])) +// call on standard model load to spawn the queued stuff +void CG_CreateMiscEnts(void) { + vec3_t mins, maxs; int i; - for (i=0; i < NumMiscEnts; i++) - { - cgMiscEntData_t *MiscEnt = &MiscEnts[i]; + for (i = 0; i < NumMiscEnts; i++) { + cgMiscEntData_t *MiscEnt = &MiscEnts[i]; MiscEnt->hModel = cgi_R_RegisterModel(MiscEnt->model); - if (MiscEnt->hModel == 0) - { - Com_Error(ERR_DROP, "misc_model_static failed to load model '%s'",MiscEnt->model); + if (MiscEnt->hModel == 0) { + Com_Error(ERR_DROP, "misc_model_static failed to load model '%s'", MiscEnt->model); continue; } @@ -2017,30 +1767,27 @@ void CG_CreateMiscEnts(void) } } -void CG_DrawMiscEnts(void) -{ - int i; - cgMiscEntData_t *MiscEnt = MiscEnts; - refEntity_t refEnt; - vec3_t difference; - vec3_t cullOrigin; +void CG_DrawMiscEnts(void) { + int i; + cgMiscEntData_t *MiscEnt = MiscEnts; + refEntity_t refEnt; + vec3_t difference; + vec3_t cullOrigin; - memset (&refEnt, 0, sizeof(refEnt)); + memset(&refEnt, 0, sizeof(refEnt)); refEnt.reType = RT_MODEL; refEnt.frame = 0; refEnt.renderfx = RF_LIGHTING_ORIGIN; - for(i=0;iorigin, cullOrigin); - cullOrigin[2] += MiscEnt->zOffset+1.0f; + cullOrigin[2] += MiscEnt->zOffset + 1.0f; - if (gi.inPVS(cg.refdef.vieworg, cullOrigin)) - { + if (gi.inPVS(cg.refdef.vieworg, cullOrigin)) { VectorSubtract(MiscEnt->origin, cg.refdef.vieworg, difference); - if (VectorLengthSquared(difference)-(MiscEnt->radius) <= 8192*8192/*RMG_distancecull.value*/) - { //fixme: need access to the real cull dist here + if (VectorLengthSquared(difference) - (MiscEnt->radius) <= 8192 * 8192 /*RMG_distancecull.value*/) { // fixme: need access to the real cull dist + // here refEnt.hModel = MiscEnt->hModel; - AnglesToAxis( MiscEnt->angles, refEnt.axis ); + AnglesToAxis(MiscEnt->angles, refEnt.axis); VectorCopy(MiscEnt->scale, refEnt.modelScale); VectorCopy(MiscEnt->origin, refEnt.origin); VectorCopy(cullOrigin, refEnt.lightingOrigin); @@ -2052,19 +1799,16 @@ void CG_DrawMiscEnts(void) } } -void CG_TransitionPermanent(void) -{ - centity_t *cent = cg_entities; - int i; +void CG_TransitionPermanent(void) { + centity_t *cent = cg_entities; + int i; cg_numpermanents = 0; - for(i=0;icurrentState)) - { + for (i = 0; i < MAX_GENTITIES; i++, cent++) { + if (cgi_GetDefaultState(i, ¢->currentState)) { cent->nextState = ¢->currentState; - VectorCopy (cent->currentState.origin, cent->lerpOrigin); - VectorCopy (cent->currentState.angles, cent->lerpAngles); + VectorCopy(cent->currentState.origin, cent->lerpOrigin); + VectorCopy(cent->currentState.angles, cent->lerpAngles); cent->currentValid = qtrue; cg_permanents[cg_numpermanents++] = cent; @@ -2076,7 +1820,6 @@ void CG_TransitionPermanent(void) Ghoul2 Insert End */ - /* ================= CG_PreInit @@ -2087,12 +1830,12 @@ Called when DLL loads (after subsystem restart, but before gamestate is received void CG_PreInit() { CG_Init_CG(); - memset( &cgs, 0, sizeof( cgs ) ); + memset(&cgs, 0, sizeof(cgs)); iCGResetCount = 0; CG_RegisterCvars(); -//moved from CG_GameStateReceived because it's loaded sooner now + // moved from CG_GameStateReceived because it's loaded sooner now CG_InitLocalEntities(); CG_InitMarkPolys(); @@ -2105,61 +1848,59 @@ CG_Init Called after every level change or subsystem restart ================= */ -void CG_Init( int serverCommandSequence ) { +void CG_Init(int serverCommandSequence) { cgs.serverCommandSequence = serverCommandSequence; - cgi_Cvar_Set( "cg_drawHUD", "1" ); + cgi_Cvar_Set("cg_drawHUD", "1"); // fonts... // cgs.media.charsetShader = cgi_R_RegisterShaderNoMip("gfx/2d/charsgrid_med"); cgs.media.qhFontSmall = cgi_R_RegisterFont("ocr_a"); - cgs.media.qhFontMedium= cgi_R_RegisterFont("ergoec"); - - cgs.media.whiteShader = cgi_R_RegisterShader( "white" ); - cgs.media.loadTick = cgi_R_RegisterShaderNoMip( "gfx/hud/load_tick" ); - cgs.media.loadTickCap = cgi_R_RegisterShaderNoMip( "gfx/hud/load_tick_cap" ); - - const char *force_icon_files[NUM_FORCE_POWERS] = - {//icons matching enums forcePowers_t - "gfx/mp/f_icon_lt_heal", //FP_HEAL, - "gfx/mp/f_icon_levitation", //FP_LEVITATION, - "gfx/mp/f_icon_speed", //FP_SPEED, - "gfx/mp/f_icon_push", //FP_PUSH, - "gfx/mp/f_icon_pull", //FP_PULL, - "gfx/mp/f_icon_lt_telepathy", //FP_TELEPATHY, - "gfx/mp/f_icon_dk_grip", //FP_GRIP, - "gfx/mp/f_icon_dk_l1", //FP_LIGHTNING, - "gfx/mp/f_icon_saber_throw", //FP_SABERTHROW - "gfx/mp/f_icon_saber_defend", //FP_SABERDEFEND, - "gfx/mp/f_icon_saber_attack", //FP_SABERATTACK, - "gfx/mp/f_icon_dk_rage", //FP_RAGE, - "gfx/mp/f_icon_lt_protect", //FP_PROTECT, - "gfx/mp/f_icon_lt_absorb", //FP_ABSORB, - "gfx/mp/f_icon_dk_drain", //FP_DRAIN, - "gfx/mp/f_icon_sight", //FP_SEE, + cgs.media.qhFontMedium = cgi_R_RegisterFont("ergoec"); + + cgs.media.whiteShader = cgi_R_RegisterShader("white"); + cgs.media.loadTick = cgi_R_RegisterShaderNoMip("gfx/hud/load_tick"); + cgs.media.loadTickCap = cgi_R_RegisterShaderNoMip("gfx/hud/load_tick_cap"); + + const char *force_icon_files[NUM_FORCE_POWERS] = { + // icons matching enums forcePowers_t + "gfx/mp/f_icon_lt_heal", // FP_HEAL, + "gfx/mp/f_icon_levitation", // FP_LEVITATION, + "gfx/mp/f_icon_speed", // FP_SPEED, + "gfx/mp/f_icon_push", // FP_PUSH, + "gfx/mp/f_icon_pull", // FP_PULL, + "gfx/mp/f_icon_lt_telepathy", // FP_TELEPATHY, + "gfx/mp/f_icon_dk_grip", // FP_GRIP, + "gfx/mp/f_icon_dk_l1", // FP_LIGHTNING, + "gfx/mp/f_icon_saber_throw", // FP_SABERTHROW + "gfx/mp/f_icon_saber_defend", // FP_SABERDEFEND, + "gfx/mp/f_icon_saber_attack", // FP_SABERATTACK, + "gfx/mp/f_icon_dk_rage", // FP_RAGE, + "gfx/mp/f_icon_lt_protect", // FP_PROTECT, + "gfx/mp/f_icon_lt_absorb", // FP_ABSORB, + "gfx/mp/f_icon_dk_drain", // FP_DRAIN, + "gfx/mp/f_icon_sight", // FP_SEE, }; // Precache inventory icons - for ( int i=0;ileType = LE_SPRITE; ex->startTime = cg.time; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_node" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_node"); - float scale = 16.0f; + float scale = 16.0f; - switch ( type ) - { + switch (type) { case NODE_NORMAL: ex->color[0] = 255; ex->color[1] = 255; @@ -2246,9 +1984,8 @@ CG_DrawRadius ------------------------- */ -void CG_DrawRadius( vec3_t origin, unsigned int radius, int type ) -{ - localEntity_t *ex; +void CG_DrawRadius(vec3_t origin, unsigned int radius, int type) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); @@ -2256,12 +1993,11 @@ void CG_DrawRadius( vec3_t origin, unsigned int radius, int type ) ex->radius = radius; ex->startTime = cg.time; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_radius" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_radius"); - switch ( type ) - { + switch (type) { case NODE_NORMAL: ex->color[0] = 255; ex->color[1] = 255; @@ -2294,184 +2030,127 @@ CG_DrawEdge ------------------------- */ -void CG_DrawEdge( vec3_t start, vec3_t end, int type ) -{ - switch ( type ) - { +void CG_DrawEdge(vec3_t start, vec3_t end, int type) { + switch (type) { // NAVIGATION EDGES BETWEEN POINTS //===================================== - case EDGE_NORMAL: - { - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_LARGE: - { - FX_AddLine( start, end, 8.0f, 15.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_BLOCKED: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_FLY: - { - vec3_t color = { 0, 255, 255 };// GREEN - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_JUMP: - { - vec3_t color = { 0, 0, 255 }; // BLUE - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - - + case EDGE_NORMAL: { + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_LARGE: { + FX_AddLine(start, end, 8.0f, 15.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_BLOCKED: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_FLY: { + vec3_t color = {0, 255, 255}; // GREEN + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_JUMP: { + vec3_t color = {0, 0, 255}; // BLUE + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; // EDGE NODES //===================================== - case EDGE_NODE_NORMAL: - { - vec3_t color = { 155, 155, 155 }; - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_NODE_FLOATING: - { - vec3_t color = { 155, 155, 0 }; - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_NODE_GOAL: - { - vec3_t color = { 0, 0, 155 }; - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_NODE_COMBAT: - { - vec3_t color = { 155, 0, 0 }; - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - - - + case EDGE_NODE_NORMAL: { + vec3_t color = {155, 155, 155}; + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_NODE_FLOATING: { + vec3_t color = {155, 155, 0}; + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_NODE_GOAL: { + vec3_t color = {0, 0, 155}; + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_NODE_COMBAT: { + vec3_t color = {155, 0, 0}; + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; // NEAREST NAV //===================================== - case EDGE_NEARESTVALID: - { - vec3_t color = { 155, 155, 155 }; // WHITE - FX_AddLine( -1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0, 0 ); - } - break; - - case EDGE_NEARESTINVALID: - { - vec3_t color = { 155, 0, 0 }; // WHITE - FX_AddLine( -1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0, 0 ); - } - break; + case EDGE_NEARESTVALID: { + vec3_t color = {155, 155, 155}; // WHITE + FX_AddLine(-1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, 0); + } break; + case EDGE_NEARESTINVALID: { + vec3_t color = {155, 0, 0}; // WHITE + FX_AddLine(-1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, 0); + } break; // NEAREST NAV CELLS //===================================== - case EDGE_CELL: - { - vec3_t color = { 155, 155, 155 }; // WHITE - FX_AddLine( -1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0, 0 ); - } - break; - case EDGE_CELL_EMPTY: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( -1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0, 0 ); - } - break; - + case EDGE_CELL: { + vec3_t color = {155, 155, 155}; // WHITE + FX_AddLine(-1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, 0); + } break; + case EDGE_CELL_EMPTY: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(-1, start, end, 1.0f, 1.0f, 0, 1.0f, 1.0f, FX_ALPHA_LINEAR, color, color, 0, 51, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0, 0); + } break; // ACTOR PATHS //============= - case EDGE_PATH: - { - vec3_t color = { 0, 0, 155 }; // WHITE - FX_AddLine( start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/nav_arrow_new" ), 0 ); - } + case EDGE_PATH: { + vec3_t color = {0, 0, 155}; // WHITE + FX_AddLine(start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader("gfx/misc/nav_arrow_new"), 0); + } break; + + case EDGE_PATHBLOCKED: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader("gfx/misc/nav_arrow_new"), 0); break; + } - case EDGE_PATHBLOCKED: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/nav_arrow_new" ), 0 ); - break; - } - - case EDGE_FOLLOWPOS: - { - vec3_t color = { 0, 255, 0 }; // GREEN - FX_AddLine( start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/nav_arrow_new" ), 0 ); - break; - } - + case EDGE_FOLLOWPOS: { + vec3_t color = {0, 255, 0}; // GREEN + FX_AddLine(start, end, 5.0f, 5.0f, 0.0f, 0.5f, 0.5f, color, color, 151, cgi_R_RegisterShader("gfx/misc/nav_arrow_new"), 0); + break; + } // STEERING //===================================== - case EDGE_IMPACT_SAFE: - { - vec3_t color = { 155, 155, 155 }; // WHITE - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_IMPACT_POSSIBLE: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_VELOCITY: - { - vec3_t color = { 0, 255, 0 }; // GREEN - FX_AddLine( start, end, 4.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_THRUST: - { - vec3_t color = { 0, 0, 255 }; // BLUE - FX_AddLine( start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - + case EDGE_IMPACT_SAFE: { + vec3_t color = {155, 155, 155}; // WHITE + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_IMPACT_POSSIBLE: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(start, end, 2.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_VELOCITY: { + vec3_t color = {0, 255, 0}; // GREEN + FX_AddLine(start, end, 4.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_THRUST: { + vec3_t color = {0, 0, 255}; // BLUE + FX_AddLine(start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 151, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; // MISC Colored Lines //===================================== - case EDGE_WHITE_ONESECOND: - { - vec3_t color = { 155, 155, 155 }; // WHITE - FX_AddLine( start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 1051, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_WHITE_TWOSECOND: - { - vec3_t color = { 155, 155, 155 }; // WHITE - FX_AddLine( start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 1051, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_RED_ONESECOND: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 2051, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; - case EDGE_RED_TWOSECOND: - { - vec3_t color = { 255, 0, 0 }; // RED - FX_AddLine( start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 2051, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), 0 ); - } - break; + case EDGE_WHITE_ONESECOND: { + vec3_t color = {155, 155, 155}; // WHITE + FX_AddLine(start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 1051, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_WHITE_TWOSECOND: { + vec3_t color = {155, 155, 155}; // WHITE + FX_AddLine(start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 1051, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_RED_ONESECOND: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 2051, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; + case EDGE_RED_TWOSECOND: { + vec3_t color = {255, 0, 0}; // RED + FX_AddLine(start, end, 3.0f, 1.0f, 0.0f, 1.0f, 1.0f, color, color, 2051, cgi_R_RegisterShader("gfx/misc/whiteline2"), 0); + } break; default: break; @@ -2484,9 +2163,8 @@ CG_DrawCombatPoint ------------------------- */ -void CG_DrawCombatPoint( vec3_t origin, int type ) -{ - localEntity_t *ex; +void CG_DrawCombatPoint(vec3_t origin, int type) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); @@ -2494,23 +2172,23 @@ void CG_DrawCombatPoint( vec3_t origin, int type ) ex->startTime = cg.time; ex->radius = 8; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_cpoint"); ex->color[0] = 255; - ex->color[1] = 0; - ex->color[2] = 255; - -/* - switch( type ) - { - case 0: //FIXME: To shut up the compiler warning (more will be added here later of course) - default: - FX_AddSprite( origin, NULL, NULL, 8.0f, 0.0f, 1.0f, 1.0f, color, color, 0.0f, 0.0f, 51, cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ) ); - break; - } -*/ + ex->color[1] = 0; + ex->color[2] = 255; + + /* + switch( type ) + { + case 0: //FIXME: To shut up the compiler warning (more will be added here later of course) + default: + FX_AddSprite( origin, NULL, NULL, 8.0f, 0.0f, 1.0f, 1.0f, color, color, 0.0f, 0.0f, 51, cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ) ); + break; + } + */ } /* @@ -2519,226 +2197,194 @@ CG_DrawAlert ------------------------- */ -void CG_DrawAlert( vec3_t origin, float rating ) -{ - vec3_t drawPos; +void CG_DrawAlert(vec3_t origin, float rating) { + vec3_t drawPos; - VectorCopy( origin, drawPos ); + VectorCopy(origin, drawPos); drawPos[2] += 48; - vec3_t startRGB; + vec3_t startRGB; - //Fades from green at 0, to red at 1 + // Fades from green at 0, to red at 1 startRGB[0] = rating; startRGB[1] = 1 - rating; startRGB[2] = 0; - FX_AddSprite( drawPos, NULL, NULL, 16, 0.0f, 1.0f, 1.0f, startRGB, startRGB, 0, 0, 50, cgs.media.whiteShader ); + FX_AddSprite(drawPos, NULL, NULL, 16, 0.0f, 1.0f, 1.0f, startRGB, startRGB, 0, 0, 50, cgs.media.whiteShader); } - -#define MAX_MENUDEFFILE 4096 +#define MAX_MENUDEFFILE 4096 // // ============================== // new hud stuff ( mission pack ) // ============================== // -qboolean CG_Asset_Parse(const char **p) -{ +qboolean CG_Asset_Parse(const char **p) { const char *token; const char *tempStr; int pointSize; token = COM_ParseExt(p, qtrue); - if (!token) - { + if (!token) { return qfalse; } - if (Q_stricmp(token, "{") != 0) - { + if (Q_stricmp(token, "{") != 0) { return qfalse; } - while ( 1 ) - { + while (1) { token = COM_ParseExt(p, qtrue); - if (!token) - { + if (!token) { return qfalse; } - if (Q_stricmp(token, "}") == 0) - { + if (Q_stricmp(token, "}") == 0) { return qtrue; } // font - if (Q_stricmp(token, "font") == 0) - { -/* - int pointSize; + if (Q_stricmp(token, "font") == 0) { + /* + int pointSize; - cgi_UI_Parse_String(tempStr); - cgi_UI_Parse_Int(&pointSize); + cgi_UI_Parse_String(tempStr); + cgi_UI_Parse_Int(&pointSize); - if (!tempStr || !pointSize) - { - return qfalse; - } -*/ -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.textFont); + if (!tempStr || !pointSize) + { + return qfalse; + } + */ + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.textFont); continue; } // smallFont - if (Q_stricmp(token, "smallFont") == 0) - { - if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) - { + if (Q_stricmp(token, "smallFont") == 0) { + if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) { return qfalse; } -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); continue; } // smallFont - because the HUD file needs it for MP. - if (Q_stricmp(token, "small2Font") == 0) - { - if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) - { + if (Q_stricmp(token, "small2Font") == 0) { + if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) { return qfalse; } -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); continue; } // font - if (Q_stricmp(token, "bigfont") == 0) - { + if (Q_stricmp(token, "bigfont") == 0) { int pointSize; - if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) - { + if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) { return qfalse; } -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.bigFont); + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.bigFont); continue; } // gradientbar - if (Q_stricmp(token, "gradientbar") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "gradientbar") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr); + // cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr); continue; } // enterMenuSound - if (Q_stricmp(token, "menuEnterSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuEnterSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr ); continue; } // exitMenuSound - if (Q_stricmp(token, "menuExitSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuExitSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr ); continue; } // itemFocusSound - if (Q_stricmp(token, "itemFocusSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "itemFocusSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr ); continue; } // menuBuzzSound - if (Q_stricmp(token, "menuBuzzSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuBuzzSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr ); continue; } - if (Q_stricmp(token, "cursor") == 0) - { -// if (!COM_ParseString(p, &cgDC.Assets.cursorStr)) -// { -// return qfalse; -// } -// cgDC.Assets.cursor = trap_R_RegisterShaderNoMip( cgDC.Assets.cursorStr); + if (Q_stricmp(token, "cursor") == 0) { + // if (!COM_ParseString(p, &cgDC.Assets.cursorStr)) + // { + // return qfalse; + // } + // cgDC.Assets.cursor = trap_R_RegisterShaderNoMip( cgDC.Assets.cursorStr); continue; } - if (Q_stricmp(token, "fadeClamp") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.fadeClamp)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeClamp") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.fadeClamp)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "fadeCycle") == 0) - { -// if (!COM_ParseInt(p, &cgDC.Assets.fadeCycle)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeCycle") == 0) { + // if (!COM_ParseInt(p, &cgDC.Assets.fadeCycle)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "fadeAmount") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.fadeAmount)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeAmount") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.fadeAmount)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowX") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.shadowX)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "shadowX") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.shadowX)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowY") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.shadowY)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "shadowY") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.shadowY)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowColor") == 0) - { + if (Q_stricmp(token, "shadowColor") == 0) { /* if (!PC_Color_Parse(handle, &cgDC.Assets.shadowColor)) { @@ -2759,55 +2405,50 @@ void cgi_UI_EndParseSession(char *buf); CG_ParseMenu(); ================= */ -void CG_ParseMenu(const char *menuFile) -{ - char *token; - int result; - char *buf,*p; +void CG_ParseMenu(const char *menuFile) { + char *token; + int result; + char *buf, *p; - //Com_Printf("Parsing menu file:%s\n", menuFile); + // Com_Printf("Parsing menu file:%s\n", menuFile); - result = cgi_UI_StartParseSession((char *) menuFile,&buf); + result = cgi_UI_StartParseSession((char *)menuFile, &buf); - if (!result) - { + if (!result) { Com_Printf("Unable to load hud menu file:%s. Using default ui/testhud.menu.\n", menuFile); - result = cgi_UI_StartParseSession("ui/testhud.menu",&buf); - if (!result) - { + result = cgi_UI_StartParseSession("ui/testhud.menu", &buf); + if (!result) { Com_Printf("Unable to load default ui/testhud.menu.\n"); - cgi_UI_EndParseSession (buf); + cgi_UI_EndParseSession(buf); return; } } p = buf; - while ( 1 ) - { + while (1) { cgi_UI_ParseExt(&token); - if (!*token) // All done? + if (!*token) // All done? { break; } - //if ( Q_stricmp( token, "{" ) ) { + // if ( Q_stricmp( token, "{" ) ) { // Com_Printf( "Missing { in menu file\n" ); // break; - //} + // } - //if ( menuCount == MAX_MENUS ) { + // if ( menuCount == MAX_MENUS ) { // Com_Printf( "Too many menus!\n" ); // break; - //} + // } -// if ( *token == '}' ) -// { -// break; -// } + // if ( *token == '}' ) + // { + // break; + // } - if (Q_stricmp(token, "assetGlobalDef") == 0) - { + if (Q_stricmp(token, "assetGlobalDef") == 0) { /* if (CG_Asset_Parse(handle)) { @@ -2820,16 +2461,13 @@ void CG_ParseMenu(const char *menuFile) */ } - - if (Q_stricmp(token, "menudef") == 0) - { + if (Q_stricmp(token, "menudef") == 0) { // start a new menu cgi_UI_Menu_New(p); } } cgi_UI_EndParseSession(buf); - } /* @@ -2838,29 +2476,24 @@ CG_Load_Menu(); ================= */ -qboolean CG_Load_Menu( const char **p) -{ +qboolean CG_Load_Menu(const char **p) { const char *token; token = COM_ParseExt(p, qtrue); - if (token[0] != '{') - { + if (token[0] != '{') { return qfalse; } - while ( 1 ) - { + while (1) { token = COM_ParseExt(p, qtrue); - if (Q_stricmp(token, "}") == 0) - { + if (Q_stricmp(token, "}") == 0) { return qtrue; } - if ( !token || token[0] == 0 ) - { + if (!token || token[0] == 0) { return qfalse; } @@ -2875,77 +2508,66 @@ CG_LoadMenus(); ================= */ -void CG_LoadMenus(const char *menuFile) -{ - const char *token; - const char *p; - int len/*, start*/; - fileHandle_t f; +void CG_LoadMenus(const char *menuFile) { + const char *token; + const char *p; + int len /*, start*/; + fileHandle_t f; char buf[MAX_MENUDEFFILE]; - //start = cgi_Milliseconds(); + // start = cgi_Milliseconds(); - len = cgi_FS_FOpenFile( menuFile, &f, FS_READ ); - if ( !f ) - { - if ( Q_isanumber( menuFile ) ) // cg_hudFiles 1 - CG_Printf( S_COLOR_GREEN "hud menu file skipped, using default\n" ); + len = cgi_FS_FOpenFile(menuFile, &f, FS_READ); + if (!f) { + if (Q_isanumber(menuFile)) // cg_hudFiles 1 + CG_Printf(S_COLOR_GREEN "hud menu file skipped, using default\n"); else - CG_Printf( S_COLOR_YELLOW "hud menu file not found: %s, using default\n", menuFile ); + CG_Printf(S_COLOR_YELLOW "hud menu file not found: %s, using default\n", menuFile); - len = cgi_FS_FOpenFile( "ui/jahud.txt", &f, FS_READ ); - if (!f) - { - cgi_Error( S_COLOR_RED "default menu file not found: ui/hud.txt, unable to continue!\n" ); + len = cgi_FS_FOpenFile("ui/jahud.txt", &f, FS_READ); + if (!f) { + cgi_Error(S_COLOR_RED "default menu file not found: ui/hud.txt, unable to continue!\n"); } } - if ( len >= MAX_MENUDEFFILE ) - { - cgi_FS_FCloseFile( f ); - cgi_Error( va( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE ) ); + if (len >= MAX_MENUDEFFILE) { + cgi_FS_FCloseFile(f); + cgi_Error(va(S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE)); return; } - cgi_FS_Read( buf, len, f ); + cgi_FS_Read(buf, len, f); buf[len] = 0; - cgi_FS_FCloseFile( f ); + cgi_FS_FCloseFile(f); -// COM_Compress(buf); + // COM_Compress(buf); -// cgi_UI_Menu_Reset(); + // cgi_UI_Menu_Reset(); p = buf; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if( !token || token[0] == 0 || token[0] == '}') - { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token || token[0] == 0 || token[0] == '}') { break; } - if ( Q_stricmp( token, "}" ) == 0 ) - { + if (Q_stricmp(token, "}") == 0) { break; } - if (Q_stricmp(token, "loadmenu") == 0) - { - if (CG_Load_Menu(&p)) - { + if (Q_stricmp(token, "loadmenu") == 0) { + if (CG_Load_Menu(&p)) { continue; - } - else - { + } else { break; } } } COM_EndParseSession(); - //Com_Printf("UI menu load time = %d milli seconds\n", cgi_Milliseconds() - start); + // Com_Printf("UI menu load time = %d milli seconds\n", cgi_Milliseconds() - start); } /* @@ -2954,69 +2576,66 @@ CG_LoadHudMenu(); ================= */ -void CG_LoadHudMenu(void) -{ +void CG_LoadHudMenu(void) { const char *hudSet; -/* - cgDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip; - cgDC.setColor = &trap_R_SetColor; - cgDC.drawHandlePic = &CG_DrawPic; - cgDC.drawStretchPic = &trap_R_DrawStretchPic; - cgDC.drawText = &CG_Text_Paint; - cgDC.textWidth = &CG_Text_Width; - cgDC.textHeight = &CG_Text_Height; - cgDC.registerModel = &trap_R_RegisterModel; - cgDC.modelBounds = &trap_R_ModelBounds; - cgDC.fillRect = &CG_FillRect; - cgDC.drawRect = &CG_DrawRect; - cgDC.drawSides = &CG_DrawSides; - cgDC.drawTopBottom = &CG_DrawTopBottom; - cgDC.clearScene = &trap_R_ClearScene; - cgDC.addRefEntityToScene = &trap_R_AddRefEntityToScene; - cgDC.renderScene = &trap_R_RenderScene; - cgDC.registerFont = &trap_R_RegisterFont; - cgDC.ownerDrawItem = &CG_OwnerDraw; - cgDC.getValue = &CG_GetValue; - cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; - cgDC.runScript = &CG_RunMenuScript; - cgDC.getTeamColor = &CG_GetTeamColor; - cgDC.setCVar = trap_Cvar_Set; - cgDC.getCVarString = trap_Cvar_VariableStringBuffer; - cgDC.getCVarValue = CG_Cvar_Get; - cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; - cgDC.startLocalSound = &trap_S_StartLocalSound; - cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; - cgDC.feederCount = &CG_FeederCount; - cgDC.feederItemImage = &CG_FeederItemImage; - cgDC.feederItemText = &CG_FeederItemText; - cgDC.feederSelection = &CG_FeederSelection; - cgDC.Error = &Com_Error; - cgDC.Print = &Com_Printf; - cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; - cgDC.registerSound = &trap_S_RegisterSound; - cgDC.startBackgroundTrack = &trap_S_StartBackgroundTrack; - cgDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack; - cgDC.playCinematic = &CG_PlayCinematic; - cgDC.stopCinematic = &CG_StopCinematic; - cgDC.drawCinematic = &CG_DrawCinematic; - cgDC.runCinematicFrame = &CG_RunCinematicFrame; -*/ -// Init_Display(&cgDC); - -// cgi_UI_String_Init(); - -// cgi_UI_Menu_Reset(); + /* + cgDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip; + cgDC.setColor = &trap_R_SetColor; + cgDC.drawHandlePic = &CG_DrawPic; + cgDC.drawStretchPic = &trap_R_DrawStretchPic; + cgDC.drawText = &CG_Text_Paint; + cgDC.textWidth = &CG_Text_Width; + cgDC.textHeight = &CG_Text_Height; + cgDC.registerModel = &trap_R_RegisterModel; + cgDC.modelBounds = &trap_R_ModelBounds; + cgDC.fillRect = &CG_FillRect; + cgDC.drawRect = &CG_DrawRect; + cgDC.drawSides = &CG_DrawSides; + cgDC.drawTopBottom = &CG_DrawTopBottom; + cgDC.clearScene = &trap_R_ClearScene; + cgDC.addRefEntityToScene = &trap_R_AddRefEntityToScene; + cgDC.renderScene = &trap_R_RenderScene; + cgDC.registerFont = &trap_R_RegisterFont; + cgDC.ownerDrawItem = &CG_OwnerDraw; + cgDC.getValue = &CG_GetValue; + cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; + cgDC.runScript = &CG_RunMenuScript; + cgDC.getTeamColor = &CG_GetTeamColor; + cgDC.setCVar = trap_Cvar_Set; + cgDC.getCVarString = trap_Cvar_VariableStringBuffer; + cgDC.getCVarValue = CG_Cvar_Get; + cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; + cgDC.startLocalSound = &trap_S_StartLocalSound; + cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; + cgDC.feederCount = &CG_FeederCount; + cgDC.feederItemImage = &CG_FeederItemImage; + cgDC.feederItemText = &CG_FeederItemText; + cgDC.feederSelection = &CG_FeederSelection; + cgDC.Error = &Com_Error; + cgDC.Print = &Com_Printf; + cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; + cgDC.registerSound = &trap_S_RegisterSound; + cgDC.startBackgroundTrack = &trap_S_StartBackgroundTrack; + cgDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack; + cgDC.playCinematic = &CG_PlayCinematic; + cgDC.stopCinematic = &CG_StopCinematic; + cgDC.drawCinematic = &CG_DrawCinematic; + cgDC.runCinematicFrame = &CG_RunCinematicFrame; + */ + // Init_Display(&cgDC); + + // cgi_UI_String_Init(); + + // cgi_UI_Menu_Reset(); hudSet = cg_hudFiles.string; - if (hudSet[0] == '\0') - { + if (hudSet[0] == '\0') { hudSet = "ui/jahud.txt"; } CG_LoadMenus(hudSet); } - /* ============================================================================== @@ -3030,9 +2649,8 @@ INVENTORY SELECTION CG_InventorySelectable =============== */ -static inline qboolean CG_InventorySelectable( int index) -{ - if (cg.snap->ps.inventory[index]) // Is there any in the inventory? +static inline qboolean CG_InventorySelectable(int index) { + if (cg.snap->ps.inventory[index]) // Is there any in the inventory? { return qtrue; } @@ -3040,23 +2658,19 @@ static inline qboolean CG_InventorySelectable( int index) return qfalse; } - /* =============== SetInventoryTime =============== */ -static inline void SetInventoryTime(void) -{ +static inline void SetInventoryTime(void) { if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD - ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD + ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD { cg.weaponSelectTime = 0; cg.forcepowerSelectTime = 0; cg.inventorySelectTime = cg.time + 130.0f; - } - else - { + } else { cg.inventorySelectTime = cg.time; } } @@ -3066,28 +2680,23 @@ static inline void SetInventoryTime(void) CG_DPPrevInventory_f =============== */ -void CG_DPPrevInventory_f( void ) -{ - int i; +void CG_DPPrevInventory_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } const int original = cg.DataPadInventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.DataPadInventorySelect--; - if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) - { + if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) { cg.DataPadInventorySelect = (INV_MAX - 1); } - if ( CG_InventorySelectable( cg.DataPadInventorySelect ) ) - { + if (CG_InventorySelectable(cg.DataPadInventorySelect)) { return; } } @@ -3099,28 +2708,23 @@ void CG_DPPrevInventory_f( void ) CG_DPNextInventory_f =============== */ -void CG_DPNextInventory_f( void ) -{ - int i; +void CG_DPNextInventory_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } const int original = cg.DataPadInventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.DataPadInventorySelect++; - if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) - { + if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) { cg.DataPadInventorySelect = INV_ELECTROBINOCULARS; } - if ( CG_InventorySelectable( cg.DataPadInventorySelect ) && (inv_icons[cg.DataPadInventorySelect])) - { + if (CG_InventorySelectable(cg.DataPadInventorySelect) && (inv_icons[cg.DataPadInventorySelect])) { return; } } @@ -3133,38 +2737,32 @@ void CG_DPNextInventory_f( void ) CG_NextInventory_f =============== */ -void CG_NextInventory_f( void ) -{ - int i; - float *color; +void CG_NextInventory_f(void) { + int i; + float *color; - if ( !cg.snap ) - { + if (!cg.snap) { return; } // The first time it's been hit so just show inventory but don't advance in inventory. - color = CG_FadeColor( cg.inventorySelectTime, WEAPON_SELECT_TIME ); - if ( !color ) - { + color = CG_FadeColor(cg.inventorySelectTime, WEAPON_SELECT_TIME); + if (!color) { SetInventoryTime(); return; } const int original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.inventorySelect++; - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = INV_ELECTROBINOCULARS; } - if ( CG_InventorySelectable( cg.inventorySelect ) && (inv_icons[cg.inventorySelect])) - { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + if (CG_InventorySelectable(cg.inventorySelect) && (inv_icons[cg.inventorySelect])) { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); SetInventoryTime(); return; } @@ -3187,38 +2785,32 @@ this func was moved to Cmd_UseInventory_f in g_cmds.cpp CG_PrevInventory_f =============== */ -void CG_PrevInventory_f( void ) -{ - int i; - float *color; +void CG_PrevInventory_f(void) { + int i; + float *color; - if ( !cg.snap ) - { + if (!cg.snap) { return; } // The first time it's been hit so just show inventory but don't advance in inventory. - color = CG_FadeColor( cg.inventorySelectTime, WEAPON_SELECT_TIME ); - if ( !color ) - { + color = CG_FadeColor(cg.inventorySelectTime, WEAPON_SELECT_TIME); + if (!color) { SetInventoryTime(); return; } const int original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.inventorySelect--; - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = (INV_MAX - 1); } - if ( CG_InventorySelectable( cg.inventorySelect ) && (inv_icons[cg.inventorySelect])) - { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + if (CG_InventorySelectable(cg.inventorySelect) && (inv_icons[cg.inventorySelect])) { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); SetInventoryTime(); return; } @@ -3227,19 +2819,17 @@ void CG_PrevInventory_f( void ) cg.inventorySelect = original; } - /* =================== FindInventoryItemTag =================== */ -gitem_t *FindInventoryItemTag(int tag) -{ - int i; +gitem_t *FindInventoryItemTag(int tag) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) - { - if ( bg_itemlist[i].giTag == tag && bg_itemlist[i].giType == IT_HOLDABLE ) // I guess giTag's aren't unique amongst items..must also make sure it's a holdable + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giTag == tag && + bg_itemlist[i].giType == IT_HOLDABLE) // I guess giTag's aren't unique amongst items..must also make sure it's a holdable { return &bg_itemlist[i]; } @@ -3248,41 +2838,35 @@ gitem_t *FindInventoryItemTag(int tag) return (0); } - - - /* =================== CG_DrawInventorySelect =================== */ -void CG_DrawInventorySelect( void ) -{ - int i; - int holdCount,iconCnt; - int sideLeftIconCnt,sideRightIconCnt; - int count; - int holdX; - //int height; -// int tag; - float addX; - vec4_t textColor = { .312f, .75f, .621f, 1.0f }; - char text[1024]={0}; +void CG_DrawInventorySelect(void) { + int i; + int holdCount, iconCnt; + int sideLeftIconCnt, sideRightIconCnt; + int count; + int holdX; + // int height; + // int tag; + float addX; + vec4_t textColor = {.312f, .75f, .621f, 1.0f}; + char text[1024] = {0}; // don't display if dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )) - { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } - if ((cg.inventorySelectTime+WEAPON_SELECT_TIME) (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.inventorySelect - 1; - if (i<0) - { - i = INV_MAX-1; + if (i < 0) { + i = INV_MAX - 1; } const int smallIconSize = 40; @@ -3345,188 +2923,154 @@ void CG_DrawInventorySelect( void ) // Left side ICONS // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; - for (iconCnt=0;iconCntps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; - if (inv_icons[cg.inventorySelect]) - { + // height = bigIconSize * cg.iconHUDPercent; + if (inv_icons[cg.inventorySelect]) { cgi_R_SetColor(NULL); - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, inv_icons[cg.inventorySelect] ); - addX = (float) bigIconSize * .75; + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, inv_icons[cg.inventorySelect]); + addX = (float)bigIconSize * .75; cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField ((x-(bigIconSize/2)) + addX, y, 2, cg.snap->ps.inventory[cg.inventorySelect], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField((x - (bigIconSize / 2)) + addX, y, 2, cg.snap->ps.inventory[cg.inventorySelect], 6, 12, NUM_FONT_SMALL, qfalse); - if (inv_names[cg.inventorySelect]) - { + if (inv_names[cg.inventorySelect]) { // FIXME: This is ONLY a temp solution, the icon stuff, etc, should all just use items.dat for everything - gitem_t *item = FindInventoryItemTag( cg.inventorySelect ); + gitem_t *item = FindInventoryItemTag(cg.inventorySelect); - if ( item && item->classname && item->classname[0] ) - { + if (item && item->classname && item->classname[0]) { char itemName[256], data[1024]; // FIXME: do these really need to be this large?? does it matter? - Com_sprintf( itemName, sizeof(itemName), "SP_INGAME_%s", item->classname ); + Com_sprintf(itemName, sizeof(itemName), "SP_INGAME_%s", item->classname); - if ( cgi_SP_GetStringTextString( itemName, data, sizeof( data ))) - { - int w = cgi_R_Font_StrLenPixels( data, cgs.media.qhFontSmall, 1.0f ); - int x = ( SCREEN_WIDTH - w ) / 2; + if (cgi_SP_GetStringTextString(itemName, data, sizeof(data))) { + int w = cgi_R_Font_StrLenPixels(data, cgs.media.qhFontSmall, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; - cgi_R_Font_DrawString( x, (SCREEN_HEIGHT - 24), data, textColor, cgs.media.qhFontSmall, -1, 1.0f); + cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24), data, textColor, cgs.media.qhFontSmall, -1, 1.0f); } } } } i = cg.inventorySelect + 1; - if (i> INV_MAX-1) - { + if (i > INV_MAX - 1) { i = 0; } // Right side ICONS // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCnt INV_MAX-1) - { + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; + for (iconCnt = 0; iconCnt < sideRightIconCnt; i++) { + if (i > INV_MAX - 1) { i = 0; } - if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) - { + if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (inv_icons[i]) - { + if (inv_icons[i]) { cgi_R_SetColor(NULL); - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, inv_icons[i] ); + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, inv_icons[i]); cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField (holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char *text); - -const char *inventoryDesc[15] = -{ -"NEURO_SAAV_DESC", -"BACTA_DESC", -"INQUISITOR_DESC", -"LA_GOGGLES_DESC", -"PORTABLE_SENTRY_DESC", -"GOODIE_KEY_DESC", -"SECURITY_KEY_DP_DESC", -}; +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text); +const char *inventoryDesc[15] = { + "NEURO_SAAV_DESC", "BACTA_DESC", "INQUISITOR_DESC", "LA_GOGGLES_DESC", "PORTABLE_SENTRY_DESC", "GOODIE_KEY_DESC", "SECURITY_KEY_DP_DESC", +}; /* =================== CG_DrawDataPadInventorySelect =================== */ -void CG_DrawDataPadInventorySelect( void ) -{ - int i; - int holdCount,iconCnt; - int sideLeftIconCnt,sideRightIconCnt; - int count; - int holdX; - //int height; - float addX; - char text[1024]={0}; - vec4_t textColor = { .312f, .75f, .621f, 1.0f }; - +void CG_DrawDataPadInventorySelect(void) { + int i; + int holdCount, iconCnt; + int sideLeftIconCnt, sideRightIconCnt; + int count; + int holdX; + // int height; + float addX; + char text[1024] = {0}; + vec4_t textColor = {.312f, .75f, .621f, 1.0f}; // count the number of items owned count = 0; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if (CG_InventorySelectable(i) && inv_icons[i]) - { + for (i = 0; i < INV_MAX; i++) { + if (CG_InventorySelectable(i) && inv_icons[i]) { count++; } } - - if (!count) - { - cgi_SP_GetStringTextString("SP_INGAME_EMPTY_INV",text, sizeof(text) ); - int w = cgi_R_Font_StrLenPixels( text, cgs.media.qhFontSmall, 1.0f ); - int x = ( SCREEN_WIDTH - w ) / 2; + if (!count) { + cgi_SP_GetStringTextString("SP_INGAME_EMPTY_INV", text, sizeof(text)); + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; CG_DrawProportionalString(x, 300 + 22, text, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); return; } - const int sideMax = 3; // Max number of icons on the side + const int sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.DataPadInventorySelect - 1; - if (i<0) - { - i = INV_MAX-1; + if (i < 0) { + i = INV_MAX - 1; } - const int smallIconSize = 40; const int bigIconSize = 80; const int bigPad = 64; @@ -3535,103 +3079,84 @@ void CG_DrawDataPadInventorySelect( void ) const int centerXPos = 320; const int graphicYPos = 340; - // Left side ICONS // Work backwards from current icon - holdX = centerXPos - ((bigIconSize/2) + bigPad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; + holdX = centerXPos - ((bigIconSize / 2) + bigPad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; - for (iconCnt=0;iconCntps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, graphicYPos + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; - if (inv_icons[cg.DataPadInventorySelect]) - { + // height = bigIconSize * cg.iconHUDPercent; + if (inv_icons[cg.DataPadInventorySelect]) { cgi_R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( centerXPos-(bigIconSize/2), (graphicYPos-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, inv_icons[cg.DataPadInventorySelect] ); - addX = (float) bigIconSize * .75; + CG_DrawPic(centerXPos - (bigIconSize / 2), (graphicYPos - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, + inv_icons[cg.DataPadInventorySelect]); + addX = (float)bigIconSize * .75; cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField ((centerXPos-(bigIconSize/2)) + addX, graphicYPos, 2, cg.snap->ps.inventory[cg.DataPadInventorySelect], 6, 12, - NUM_FONT_SMALL,qfalse); - + CG_DrawNumField((centerXPos - (bigIconSize / 2)) + addX, graphicYPos, 2, cg.snap->ps.inventory[cg.DataPadInventorySelect], 6, 12, NUM_FONT_SMALL, + qfalse); } i = cg.DataPadInventorySelect + 1; - if (i> INV_MAX-1) - { + if (i > INV_MAX - 1) { i = 0; } // Right side ICONS // Work forwards from current icon - holdX = centerXPos + (bigIconSize/2) + bigPad; - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCnt INV_MAX-1) - { + holdX = centerXPos + (bigIconSize / 2) + bigPad; + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; + for (iconCnt = 0; iconCnt < sideRightIconCnt; i++) { + if (i > INV_MAX - 1) { i = 0; } - if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) - { + if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (inv_icons[i]) - { + if (inv_icons[i]) { cgi_R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( holdX, graphicYPos+10, smallIconSize, smallIconSize, inv_icons[i] ); + CG_DrawPic(holdX, graphicYPos + 10, smallIconSize, smallIconSize, inv_icons[i]); cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField (holdX + addX, graphicYPos + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, graphicYPos + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } // draw the weapon description - if ((cg.DataPadInventorySelect>=0) && (cg.DataPadInventorySelect<13)) - { - cgi_SP_GetStringTextString( va("SP_INGAME_%s",inventoryDesc[cg.DataPadInventorySelect]), text, sizeof(text) ); + if ((cg.DataPadInventorySelect >= 0) && (cg.DataPadInventorySelect < 13)) { + cgi_SP_GetStringTextString(va("SP_INGAME_%s", inventoryDesc[cg.DataPadInventorySelect]), text, sizeof(text)); - if (text[0]) - { - CG_DisplayBoxedText(70,50,500,300,text, - cgs.media.qhFontSmall, - 0.7f, - textColor - ); + if (text[0]) { + CG_DisplayBoxedText(70, 50, 500, 300, text, cgs.media.qhFontSmall, 0.7f, textColor); } } } @@ -3641,60 +3166,36 @@ void CG_DrawDataPadInventorySelect( void ) SetForcePowerTime =============== */ -void SetForcePowerTime(void) -{ - if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD - ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Inventory HUD was currently active to just swap it out with Force HUD +void SetForcePowerTime(void) { + if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD + ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Inventory HUD was currently active to just swap it out with Force HUD { cg.weaponSelectTime = 0; cg.inventorySelectTime = 0; cg.forcepowerSelectTime = cg.time + 130.0f; - } - else - { + } else { cg.forcepowerSelectTime = cg.time; } } -int showPowers[MAX_SHOWPOWERS] = -{ - FP_ABSORB, - FP_HEAL, - FP_PROTECT, - FP_TELEPATHY, +int showPowers[MAX_SHOWPOWERS] = { + FP_ABSORB, FP_HEAL, FP_PROTECT, FP_TELEPATHY, - FP_SPEED, - FP_PUSH, - FP_PULL, - FP_SEE, + FP_SPEED, FP_PUSH, FP_PULL, FP_SEE, - FP_DRAIN, - FP_LIGHTNING, - FP_RAGE, - FP_GRIP, + FP_DRAIN, FP_LIGHTNING, FP_RAGE, FP_GRIP, }; -const char *showPowersName[MAX_SHOWPOWERS] = -{ - "SP_INGAME_ABSORB2", - "SP_INGAME_HEAL2", - "SP_INGAME_PROTECT2", - "SP_INGAME_MINDTRICK2", - - "SP_INGAME_SPEED2", - "SP_INGAME_PUSH2", - "SP_INGAME_PULL2", - "SP_INGAME_SEEING2", - - "SP_INGAME_DRAIN2", - "SP_INGAME_LIGHTNING2", - "SP_INGAME_DARK_RAGE2", - "SP_INGAME_GRIP2", +const char *showPowersName[MAX_SHOWPOWERS] = { + "SP_INGAME_ABSORB2", "SP_INGAME_HEAL2", "SP_INGAME_PROTECT2", "SP_INGAME_MINDTRICK2", + + "SP_INGAME_SPEED2", "SP_INGAME_PUSH2", "SP_INGAME_PULL2", "SP_INGAME_SEEING2", + + "SP_INGAME_DRAIN2", "SP_INGAME_LIGHTNING2", "SP_INGAME_DARK_RAGE2", "SP_INGAME_GRIP2", }; // Keep these with groups light side, core, and dark side -int showDataPadPowers[MAX_DPSHOWPOWERS] = -{ +int showDataPadPowers[MAX_DPSHOWPOWERS] = { // Light side FP_ABSORB, FP_HEAL, @@ -3711,7 +3212,7 @@ int showDataPadPowers[MAX_DPSHOWPOWERS] = FP_SABER_OFFENSE, FP_SEE, - //Dark Side + // Dark Side FP_DRAIN, FP_LIGHTNING, FP_RAGE, @@ -3723,14 +3224,13 @@ int showDataPadPowers[MAX_DPSHOWPOWERS] = ForcePower_Valid =============== */ -qboolean ForcePower_Valid(int index) -{ - gentity_t *player = &g_entities[0]; +qboolean ForcePower_Valid(int index) { + gentity_t *player = &g_entities[0]; - assert (MAX_SHOWPOWERS == ( sizeof(showPowers)/sizeof(showPowers[0]) )); - assert (index < MAX_SHOWPOWERS ); //is this a valid index? + assert(MAX_SHOWPOWERS == (sizeof(showPowers) / sizeof(showPowers[0]))); + assert(index < MAX_SHOWPOWERS); // is this a valid index? if (player->client->ps.forcePowersKnown & (1 << showPowers[index]) && - player->client->ps.forcePowerLevel[showPowers[index]]) // Does he have the force power? + player->client->ps.forcePowerLevel[showPowers[index]]) // Does he have the force power? { return qtrue; } @@ -3743,36 +3243,31 @@ qboolean ForcePower_Valid(int index) CG_NextForcePower_f =============== */ -void CG_NextForcePower_f( void ) -{ - int i; +void CG_NextForcePower_f(void) { + int i; - if ( !cg.snap || in_camera ) - { + if (!cg.snap || in_camera) { return; } SetForcePowerTime(); - if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) - { + if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) { return; } const int original = cg.forcepowerSelect; - for ( i = 0; i < MAX_SHOWPOWERS; i++ ) - { + for (i = 0; i < MAX_SHOWPOWERS; i++) { cg.forcepowerSelect++; - if (cg.forcepowerSelect >= MAX_SHOWPOWERS) - { + if (cg.forcepowerSelect >= MAX_SHOWPOWERS) { cg.forcepowerSelect = 0; } - if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? + if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); return; } } @@ -3785,41 +3280,35 @@ void CG_NextForcePower_f( void ) CG_PrevForcePower_f =============== */ -void CG_PrevForcePower_f( void ) -{ - int i; +void CG_PrevForcePower_f(void) { + int i; - if ( !cg.snap || in_camera ) - { + if (!cg.snap || in_camera) { return; } SetForcePowerTime(); - if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) - { + if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) { return; } const int original = cg.forcepowerSelect; - for ( i = 0; i < MAX_SHOWPOWERS; i++ ) - { + for (i = 0; i < MAX_SHOWPOWERS; i++) { cg.forcepowerSelect--; - if (cg.forcepowerSelect < 0) - { + if (cg.forcepowerSelect < 0) { cg.forcepowerSelect = MAX_SHOWPOWERS - 1; } - if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? + if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); return; } } - cg.forcepowerSelect = original; } @@ -3828,24 +3317,21 @@ void CG_PrevForcePower_f( void ) CG_DrawForceSelect =================== */ -void CG_DrawForceSelect( void ) -{ - int i; - int count; - int holdX; - int sideLeftIconCnt,sideRightIconCnt; - int holdCount,iconCnt; - char text[1024]={0}; - int yOffset = 0; - +void CG_DrawForceSelect(void) { + int i; + int count; + int holdX; + int sideLeftIconCnt, sideRightIconCnt; + int holdCount, iconCnt; + char text[1024] = {0}; + int yOffset = 0; // don't display if dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )) - { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } - if ((cg.forcepowerSelectTime+WEAPON_SELECT_TIME) (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } @@ -3906,77 +3388,67 @@ void CG_DrawForceSelect( void ) const int y = 425; i = cg.forcepowerSelect - 1; - if (i < 0) - { - i = MAX_SHOWPOWERS-1; + if (i < 0) { + i = MAX_SHOWPOWERS - 1; } cgi_R_SetColor(NULL); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i < 0) - { - i = MAX_SHOWPOWERS-1; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 0) { + i = MAX_SHOWPOWERS - 1; } - if (!ForcePower_Valid(i)) // Does he have this power? + if (!ForcePower_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showPowers[i]]) - { - CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, force_icons[showPowers[i]] ); - holdX -= (smallIconSize+pad); + if (force_icons[showPowers[i]]) { + CG_DrawPic(holdX, y + yOffset, smallIconSize, smallIconSize, force_icons[showPowers[i]]); + holdX -= (smallIconSize + pad); } } // Current Center Icon - if (force_icons[showPowers[cg.forcepowerSelect]]) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)) + yOffset, bigIconSize, bigIconSize, force_icons[showPowers[cg.forcepowerSelect]] ); + if (force_icons[showPowers[cg.forcepowerSelect]]) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + yOffset, bigIconSize, bigIconSize, + force_icons[showPowers[cg.forcepowerSelect]]); } - i = cg.forcepowerSelect + 1; - if (i>=MAX_SHOWPOWERS) - { + if (i >= MAX_SHOWPOWERS) { i = 0; } // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>=MAX_SHOWPOWERS) - { + holdX = x + (bigIconSize / 2) + pad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i >= MAX_SHOWPOWERS) { i = 0; } - if (!ForcePower_Valid(i)) // Does he have this power? + if (!ForcePower_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showPowers[i]]) - { - CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, force_icons[showPowers[i]] ); - holdX += (smallIconSize+pad); + if (force_icons[showPowers[i]]) { + CG_DrawPic(holdX, y + yOffset, smallIconSize, smallIconSize, force_icons[showPowers[i]]); + holdX += (smallIconSize + pad); } } // This only a temp solution. - if (cgi_SP_GetStringTextString( showPowersName[cg.forcepowerSelect], text, sizeof(text) )) - { - int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - int x = ( SCREEN_WIDTH - w ) / 2; - cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24) + yOffset, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontSmall, -1, 1.0f); + if (cgi_SP_GetStringTextString(showPowersName[cg.forcepowerSelect], text, sizeof(text))) { + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; + cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24) + yOffset, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontSmall, -1, 1.0f); } } @@ -3985,13 +3457,12 @@ void CG_DrawForceSelect( void ) ForcePowerDataPad_Valid =============== */ -qboolean ForcePowerDataPad_Valid(int index) -{ - gentity_t *player = &g_entities[0]; +qboolean ForcePowerDataPad_Valid(int index) { + gentity_t *player = &g_entities[0]; - assert (index < MAX_DPSHOWPOWERS); + assert(index < MAX_DPSHOWPOWERS); if (player->client->ps.forcePowersKnown & (1 << showDataPadPowers[index]) && - player->client->ps.forcePowerLevel[showDataPadPowers[index]]) // Does he have the force power? + player->client->ps.forcePowerLevel[showDataPadPowers[index]]) // Does he have the force power? { return qtrue; } @@ -4004,28 +3475,24 @@ qboolean ForcePowerDataPad_Valid(int index) CG_DPNextForcePower_f =============== */ -void CG_DPNextForcePower_f( void ) -{ - int i; - int original; +void CG_DPNextForcePower_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } original = cg.DataPadforcepowerSelect; - for ( i = 0; i= MAX_DPSHOWPOWERS) - { + if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) { cg.DataPadforcepowerSelect = 0; } - if (ForcePowerDataPad_Valid(cg.DataPadforcepowerSelect)) // Does he have the force power? + if (ForcePowerDataPad_Valid(cg.DataPadforcepowerSelect)) // Does he have the force power? { return; } @@ -4039,124 +3506,66 @@ void CG_DPNextForcePower_f( void ) CG_DPPrevForcePower_f =============== */ -void CG_DPPrevForcePower_f( void ) -{ - int i; - int original; +void CG_DPPrevForcePower_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } original = cg.DataPadforcepowerSelect; - for ( i = 0; i (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } - const int smallIconSize = 40; const int bigIconSize = 70; const int bigPad = 64; @@ -4226,137 +3628,112 @@ void CG_DrawDataPadForceSelect( void ) const int graphicYPos = 340; i = cg.DataPadforcepowerSelect - 1; - if (i < 0) - { - i = MAX_DPSHOWPOWERS-1; + if (i < 0) { + i = MAX_DPSHOWPOWERS - 1; } // Print icons to the left of the center cgi_R_SetColor(colorTable[CT_WHITE]); // Work backwards from current icon - holdX = centerXPos - ((bigIconSize/2) + bigPad + smallIconSize); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i < 0) - { - i = MAX_DPSHOWPOWERS-1; + holdX = centerXPos - ((bigIconSize / 2) + bigPad + smallIconSize); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 0) { + i = MAX_DPSHOWPOWERS - 1; } - if (!ForcePowerDataPad_Valid(i)) // Does he have this power? + if (!ForcePowerDataPad_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showDataPadPowers[i]]) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]] ); + if (force_icons[showDataPadPowers[i]]) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]]); } // A new force power - if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay ); + if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay); } - if (force_icons[showDataPadPowers[i]]) - { - holdX -= (smallIconSize+pad); + if (force_icons[showDataPadPowers[i]]) { + holdX -= (smallIconSize + pad); } } // Current Center Icon - if (force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]) - { + if (force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]) { cgi_R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( centerXPos-(bigIconSize/2), (graphicYPos-((bigIconSize-smallIconSize)/2)), bigIconSize, bigIconSize, force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]] ); + CG_DrawPic(centerXPos - (bigIconSize / 2), (graphicYPos - ((bigIconSize - smallIconSize) / 2)), bigIconSize, bigIconSize, + force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]); // New force power if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect])) - { - CG_DrawPic( centerXPos-(bigIconSize/2), (graphicYPos-((bigIconSize-smallIconSize)/2)), bigIconSize, bigIconSize, cgs.media.DPForcePowerOverlay ); + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect])) { + CG_DrawPic(centerXPos - (bigIconSize / 2), (graphicYPos - ((bigIconSize - smallIconSize) / 2)), bigIconSize, bigIconSize, + cgs.media.DPForcePowerOverlay); } } - i = cg.DataPadforcepowerSelect + 1; - if (i>=MAX_DPSHOWPOWERS) - { + if (i >= MAX_DPSHOWPOWERS) { i = 0; } cgi_R_SetColor(colorTable[CT_WHITE]); // Work forwards from current icon - holdX = centerXPos + (bigIconSize/2) + bigPad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>=MAX_DPSHOWPOWERS) - { + holdX = centerXPos + (bigIconSize / 2) + bigPad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i >= MAX_DPSHOWPOWERS) { i = 0; } - if (!ForcePowerDataPad_Valid(i)) // Does he have this power? + if (!ForcePowerDataPad_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showDataPadPowers[i]]) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]] ); + if (force_icons[showDataPadPowers[i]]) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]]); } // A new force power - if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay ); + if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay); } - if (force_icons[showDataPadPowers[i]]) - { - holdX += (smallIconSize+pad); + if (force_icons[showDataPadPowers[i]]) { + holdX += (smallIconSize + pad); } } - cgi_SP_GetStringTextString( va("SP_INGAME_%s",forcepowerDesc[cg.DataPadforcepowerSelect]), text, sizeof(text) ); + cgi_SP_GetStringTextString(va("SP_INGAME_%s", forcepowerDesc[cg.DataPadforcepowerSelect]), text, sizeof(text)); - if (player->client->ps.forcePowerLevel[showDataPadPowers[cg.DataPadforcepowerSelect]]==1) - { - cgi_SP_GetStringTextString( va("SP_INGAME_%s",forcepowerLvl1Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); - } - else if (player->client->ps.forcePowerLevel[showDataPadPowers[cg.DataPadforcepowerSelect]]==2) - { - cgi_SP_GetStringTextString( va("SP_INGAME_%s",forcepowerLvl2Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); - } - else - { - cgi_SP_GetStringTextString( va("SP_INGAME_%s",forcepowerLvl3Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); + if (player->client->ps.forcePowerLevel[showDataPadPowers[cg.DataPadforcepowerSelect]] == 1) { + cgi_SP_GetStringTextString(va("SP_INGAME_%s", forcepowerLvl1Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); + } else if (player->client->ps.forcePowerLevel[showDataPadPowers[cg.DataPadforcepowerSelect]] == 2) { + cgi_SP_GetStringTextString(va("SP_INGAME_%s", forcepowerLvl2Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); + } else { + cgi_SP_GetStringTextString(va("SP_INGAME_%s", forcepowerLvl3Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); } - if (text[0]) - { + if (text[0]) { const short textboxXPos = 40; const short textboxYPos = 60; - const int textboxWidth = 560; - const int textboxHeight = 300; - const float textScale = 1.0f; + const int textboxWidth = 560; + const int textboxHeight = 300; + const float textScale = 1.0f; - CG_DisplayBoxedText(textboxXPos,textboxYPos,textboxWidth,textboxHeight,va("%s%s",text,text2), - 4, - textScale, - colorTable[CT_WHITE] - ); + CG_DisplayBoxedText(textboxXPos, textboxYPos, textboxWidth, textboxHeight, va("%s%s", text, text2), 4, textScale, colorTable[CT_WHITE]); } } @@ -4384,7 +3761,3 @@ static void CG_RunCinematicFrame(int handle) { } #pragma warning ( default : 4505) */ - - - - diff --git a/code/cgame/cg_marks.cpp b/code/cgame/cg_marks.cpp index 525e0e0790..1b1226d5a3 100644 --- a/code/cgame/cg_marks.cpp +++ b/code/cgame/cg_marks.cpp @@ -25,7 +25,6 @@ along with this program; if not, see . #include "cg_headers.h" - #include "cg_media.h" /* @@ -36,10 +35,9 @@ MARK POLYS =================================================================== */ - -markPoly_t cg_activeMarkPolys; // double linked list -markPoly_t *cg_freeMarkPolys; // single linked list -markPoly_t cg_markPolys[MAX_MARK_POLYS]; +markPoly_t cg_activeMarkPolys; // double linked list +markPoly_t *cg_freeMarkPolys; // single linked list +markPoly_t cg_markPolys[MAX_MARK_POLYS]; /* =================== @@ -48,28 +46,27 @@ CG_InitMarkPolys This is called at startup and for tournement restarts =================== */ -void CG_InitMarkPolys( void ) { - int i; +void CG_InitMarkPolys(void) { + int i; - memset( cg_markPolys, 0, sizeof(cg_markPolys) ); + memset(cg_markPolys, 0, sizeof(cg_markPolys)); cg_activeMarkPolys.nextMark = &cg_activeMarkPolys; cg_activeMarkPolys.prevMark = &cg_activeMarkPolys; cg_freeMarkPolys = cg_markPolys; - for ( i = 0 ; i < MAX_MARK_POLYS - 1 ; i++ ) { - cg_markPolys[i].nextMark = &cg_markPolys[i+1]; + for (i = 0; i < MAX_MARK_POLYS - 1; i++) { + cg_markPolys[i].nextMark = &cg_markPolys[i + 1]; } } - /* ================== CG_FreeMarkPoly ================== */ -void CG_FreeMarkPoly( markPoly_t *le ) { - if ( !le->prevMark ) { - CG_Error( "CG_FreeLocalEntity: not active" ); +void CG_FreeMarkPoly(markPoly_t *le) { + if (!le->prevMark) { + CG_Error("CG_FreeLocalEntity: not active"); } // remove from the doubly linked active list @@ -88,23 +85,23 @@ CG_AllocMark Will allways succeed, even if it requires freeing an old active mark =================== */ -markPoly_t *CG_AllocMark( void ) { - markPoly_t *le; +markPoly_t *CG_AllocMark(void) { + markPoly_t *le; int time; - if ( !cg_freeMarkPolys ) { + if (!cg_freeMarkPolys) { // no free entities, so free the one at the end of the chain // remove the oldest active entity time = cg_activeMarkPolys.prevMark->time; while (cg_activeMarkPolys.prevMark && time == cg_activeMarkPolys.prevMark->time) { - CG_FreeMarkPoly( cg_activeMarkPolys.prevMark ); + CG_FreeMarkPoly(cg_activeMarkPolys.prevMark); } } le = cg_freeMarkPolys; cg_freeMarkPolys = cg_freeMarkPolys->nextMark; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->nextMark = cg_activeMarkPolys.nextMark; @@ -114,8 +111,6 @@ markPoly_t *CG_AllocMark( void ) { return le; } - - /* ================= CG_ImpactMark @@ -127,40 +122,39 @@ temporary marks will not be stored or randomly oriented, but immediately passed to the renderer. ================= */ -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 - -void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, float orientation, float red, - float green, float blue, float alpha, qboolean alphaFade, float radius, qboolean temporary ) -{ - vec3_t axis[3]; - float texCoordScale; - vec3_t originalPoints[4]; - byte colors[4]; - int i, j; - int numFragments; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - vec3_t markPoints[MAX_MARK_POINTS]; - vec3_t projection; - - if ( !cg_addMarks.integer ) { +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 + +void CG_ImpactMark(qhandle_t markShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, + qboolean alphaFade, float radius, qboolean temporary) { + vec3_t axis[3]; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j; + int numFragments; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; + vec3_t markPoints[MAX_MARK_POINTS]; + vec3_t projection; + + if (!cg_addMarks.integer) { return; } - if ( radius <= 0 ) { - CG_Error( "CG_ImpactMark called with <= 0 radius" ); + if (radius <= 0) { + CG_Error("CG_ImpactMark called with <= 0 radius"); } // create the texture axis - VectorNormalize2( dir, axis[0] ); - PerpendicularVector( axis[1], axis[0] ); - RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); - CrossProduct( axis[0], axis[2], axis[1] ); + VectorNormalize2(dir, axis[0]); + PerpendicularVector(axis[1], axis[0]); + RotatePointAroundVector(axis[2], axis[0], axis[1], orientation); + CrossProduct(axis[0], axis[2], axis[1]); texCoordScale = 0.5 * 1.0 / radius; // create the full polygon - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; @@ -168,42 +162,40 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, } // get the fragments - VectorScale( dir, -20, projection ); - numFragments = cgi_CM_MarkFragments( 4, (const float (*)[3])originalPoints, - projection, MAX_MARK_POINTS, markPoints[0], - MAX_MARK_FRAGMENTS, markFragments ); + VectorScale(dir, -20, projection); + numFragments = cgi_CM_MarkFragments(4, (const float(*)[3])originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); colors[0] = red * 255; colors[1] = green * 255; colors[2] = blue * 255; colors[3] = alpha * 255; - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) { - polyVert_t *v; - polyVert_t verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; // we have an upper limit on the complexity of polygons // that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) { + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { vec3_t delta; - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); - VectorSubtract( v->xyz, origin, delta ); - v->st[0] = 0.5f + DotProduct( delta, axis[1] ) * texCoordScale; - v->st[1] = 0.5f + DotProduct( delta, axis[2] ) * texCoordScale; - for ( int k = 0; k < 4; k++ ) { + VectorSubtract(v->xyz, origin, delta); + v->st[0] = 0.5f + DotProduct(delta, axis[1]) * texCoordScale; + v->st[1] = 0.5f + DotProduct(delta, axis[2]) * texCoordScale; + for (int k = 0; k < 4; k++) { v->modulate[k] = colors[k]; } } // if it is a temporary (shadow) mark, add it immediately and forget about it - if ( temporary ) { - cgi_R_AddPolyToScene( markShader, mf->numPoints, verts ); + if (temporary) { + cgi_R_AddPolyToScene(markShader, mf->numPoints, verts); continue; } @@ -213,75 +205,68 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, mark->alphaFade = alphaFade; mark->markShader = markShader; mark->poly.numVerts = mf->numPoints; - mark->color[0] = colors[0];//red; - mark->color[1] = colors[1];//green; - mark->color[2] = colors[2];//blue; - mark->color[3] = colors[3];//alpha; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + mark->color[0] = colors[0]; // red; + mark->color[1] = colors[1]; // green; + mark->color[2] = colors[2]; // blue; + mark->color[3] = colors[3]; // alpha; + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); } } - /* =============== CG_AddMarks =============== */ -#define MARK_TOTAL_TIME 10000 -#define MARK_FADE_TIME 1000 +#define MARK_TOTAL_TIME 10000 +#define MARK_FADE_TIME 1000 -void CG_AddMarks( void ) { - int j; - markPoly_t *mp, *next; - int t; - int fade; +void CG_AddMarks(void) { + int j; + markPoly_t *mp, *next; + int t; + int fade; - if ( !cg_addMarks.integer ) { + if (!cg_addMarks.integer) { return; } mp = cg_activeMarkPolys.nextMark; - for ( ; mp != &cg_activeMarkPolys ; mp = next ) { + for (; mp != &cg_activeMarkPolys; mp = next) { // grab next now, so if the local entity is freed we // still have it next = mp->nextMark; // see if it is time to completely remove it - if ( cg.time > mp->time + MARK_TOTAL_TIME ) { - CG_FreeMarkPoly( mp ); + if (cg.time > mp->time + MARK_TOTAL_TIME) { + CG_FreeMarkPoly(mp); continue; } // fade all marks out with time t = mp->time + MARK_TOTAL_TIME - cg.time; - if ( t < MARK_FADE_TIME ) { + if (t < MARK_FADE_TIME) { fade = 255 * t / MARK_FADE_TIME; - if ( mp->alphaFade ) { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + if (mp->alphaFade) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[3] = fade; } - } - else - { + } else { float f = (float)t / MARK_FADE_TIME; - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0] * f; mp->verts[j].modulate[1] = mp->color[1] * f; mp->verts[j].modulate[2] = mp->color[2] * f; } } - } - else - { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + } else { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0]; mp->verts[j].modulate[1] = mp->color[1]; mp->verts[j].modulate[2] = mp->color[2]; } } - - cgi_R_AddPolyToScene( mp->markShader, mp->poly.numVerts, mp->verts ); + cgi_R_AddPolyToScene(mp->markShader, mp->poly.numVerts, mp->verts); } } - diff --git a/code/cgame/cg_players.cpp b/code/cgame/cg_players.cpp index 9a6e6aa4f8..9ba9eda39f 100644 --- a/code/cgame/cg_players.cpp +++ b/code/cgame/cg_players.cpp @@ -23,7 +23,7 @@ along with this program; if not, see . #include "cg_headers.h" -#define CG_PLAYERS_CPP +#define CG_PLAYERS_CPP #include "cg_media.h" #include "FxScheduler.h" #include "../game/ghoul2_shared.h" @@ -32,15 +32,15 @@ along with this program; if not, see . #include "../game/g_vehicles.h" #include "../Rufl/hstring.h" -#define LOOK_SWING_SCALE 0.5f -#define CG_SWINGSPEED 0.3f +#define LOOK_SWING_SCALE 0.5f +#define CG_SWINGSPEED 0.3f #include "animtable.h" -extern qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); -extern void WP_SaberSwingSound( gentity_t *ent, int saberNum, swingType_t swingType ); +extern qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); +extern void WP_SaberSwingSound(gentity_t *ent, int saberNum, swingType_t swingType); -extern vmCvar_t cg_debugHealthBars; +extern vmCvar_t cg_debugHealthBars; /* player entities generate a great deal of information from implicit ques @@ -48,24 +48,22 @@ taken from the entityState_t */ -//rww - generic function for applying a shader to the skin. -extern vmCvar_t cg_g2Marks; -void CG_AddGhoul2Mark(int type, float size, vec3_t hitloc, vec3_t hitdirection, - int entnum, vec3_t entposition, float entangle, CGhoul2Info_v &ghoul2, vec3_t modelScale, int lifeTime, int firstModel, vec3_t uaxis ) -{ - if ( !cg_g2Marks.integer ) - {//don't want these +// rww - generic function for applying a shader to the skin. +extern vmCvar_t cg_g2Marks; +void CG_AddGhoul2Mark(int type, float size, vec3_t hitloc, vec3_t hitdirection, int entnum, vec3_t entposition, float entangle, CGhoul2Info_v &ghoul2, + vec3_t modelScale, int lifeTime, int firstModel, vec3_t uaxis) { + if (!cg_g2Marks.integer) { // don't want these return; } static SSkinGoreData goreSkin; - memset ( &goreSkin, 0, sizeof(goreSkin) ); + memset(&goreSkin, 0, sizeof(goreSkin)); - goreSkin.growDuration = -1; // do not grow + goreSkin.growDuration = -1; // do not grow goreSkin.goreScaleStartFraction = 1.0; // default start scale - goreSkin.frontFaces = true; // yes front - goreSkin.backFaces = false; // no back + goreSkin.frontFaces = true; // yes front + goreSkin.backFaces = false; // no back goreSkin.lifeTime = lifeTime; goreSkin.firstModel = firstModel; /* @@ -78,227 +76,136 @@ void CG_AddGhoul2Mark(int type, float size, vec3_t hitloc, vec3_t hitdirection, */ goreSkin.currentTime = cg.time; - goreSkin.entNum = entnum; - goreSkin.SSize = size; - goreSkin.TSize = size; - goreSkin.shader = type; - goreSkin.theta = flrand(0.0f,6.28f); + goreSkin.entNum = entnum; + goreSkin.SSize = size; + goreSkin.TSize = size; + goreSkin.shader = type; + goreSkin.theta = flrand(0.0f, 6.28f); - if (uaxis) - { + if (uaxis) { goreSkin.backFaces = true; - goreSkin.SSize = 6; - goreSkin.TSize = 3; - goreSkin.depthStart = -10; //arbitrary depths, just limiting marks to near hit loc - goreSkin.depthEnd = 15; + goreSkin.SSize = 6; + goreSkin.TSize = 3; + goreSkin.depthStart = -10; // arbitrary depths, just limiting marks to near hit loc + goreSkin.depthEnd = 15; goreSkin.useTheta = false; VectorCopy(uaxis, goreSkin.uaxis); - if( VectorNormalize(goreSkin.uaxis) < 0.001f ) - {//too short to make a mark + if (VectorNormalize(goreSkin.uaxis) < 0.001f) { // too short to make a mark return; } - } - else - { + } else { goreSkin.depthStart = -1000; - goreSkin.depthEnd = 1000; + goreSkin.depthEnd = 1000; goreSkin.useTheta = true; } VectorCopy(modelScale, goreSkin.scale); - if ( VectorCompare( hitdirection, vec3_origin ) ) - {//wtf, no dir? Make one up - VectorSubtract( entposition, hitloc, goreSkin.rayDirection); - VectorNormalize( goreSkin.rayDirection ); - } - else - {//use passed in value - VectorCopy ( hitdirection, goreSkin.rayDirection); + if (VectorCompare(hitdirection, vec3_origin)) { // wtf, no dir? Make one up + VectorSubtract(entposition, hitloc, goreSkin.rayDirection); + VectorNormalize(goreSkin.rayDirection); + } else { // use passed in value + VectorCopy(hitdirection, goreSkin.rayDirection); } - VectorCopy ( hitloc, goreSkin.hitLocation ); - VectorCopy ( entposition, goreSkin.position ); + VectorCopy(hitloc, goreSkin.hitLocation); + VectorCopy(entposition, goreSkin.position); goreSkin.angles[YAW] = entangle; - gi.G2API_AddSkinGore(ghoul2,goreSkin); + gi.G2API_AddSkinGore(ghoul2, goreSkin); } -qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName ); - -static void CG_PlayerFootsteps( centity_t *const cent, footstepType_t footStepType ); -static void CG_PlayerAnimEvents( int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum ); -extern void BG_G2SetBoneAngles( centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, qhandle_t *modelList ); -extern void FX_BorgDeathSparkParticles( vec3_t origin, vec3_t angles, vec3_t vel, vec3_t user ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern int PM_GetTurnAnim( gentity_t *gent, int anim ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern qboolean PM_SuperBreakWinAnim( int anim ); - -//Basic set of custom sounds that everyone needs -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customBasicSoundNames[MAX_CUSTOM_BASIC_SOUNDS] = -{ - "*death1.wav", - "*death2.wav", - "*death3.wav", - "*jump1.wav", - "*pain25.wav", - "*pain50.wav", - "*pain75.wav", - "*pain100.wav", - "*gurp1.wav", - "*gurp2.wav", - "*drown.wav", - "*gasp.wav", - "*land1.wav", - "*falling1.wav", +qboolean CG_RegisterClientModelname(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, + const char *torsoSkinName, const char *legsModelName, const char *legsSkinName); + +static void CG_PlayerFootsteps(centity_t *const cent, footstepType_t footStepType); +static void CG_PlayerAnimEvents(int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum); +extern void BG_G2SetBoneAngles(centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList); +extern void FX_BorgDeathSparkParticles(vec3_t origin, vec3_t angles, vec3_t vel, vec3_t user); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern int PM_GetTurnAnim(gentity_t *gent, int anim); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InRoll(playerState_t *ps); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern qboolean PM_SuperBreakWinAnim(int anim); + +// Basic set of custom sounds that everyone needs +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customBasicSoundNames[MAX_CUSTOM_BASIC_SOUNDS] = { + "*death1.wav", "*death2.wav", "*death3.wav", "*jump1.wav", "*pain25.wav", "*pain50.wav", "*pain75.wav", + "*pain100.wav", "*gurp1.wav", "*gurp2.wav", "*drown.wav", "*gasp.wav", "*land1.wav", "*falling1.wav", }; -//Used as a supplement to the basic set for enemies and hazard team -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = -{ - "*anger1.wav", //Say when acquire an enemy when didn't have one before - "*anger2.wav", - "*anger3.wav", - "*victory1.wav", //Say when killed an enemy - "*victory2.wav", - "*victory3.wav", - "*confuse1.wav", //Say when confused - "*confuse2.wav", - "*confuse3.wav", - "*pushed1.wav", //Say when force-pushed - "*pushed2.wav", - "*pushed3.wav", - "*choke1.wav", - "*choke2.wav", - "*choke3.wav", - "*ffwarn.wav", - "*ffturn.wav", +// Used as a supplement to the basic set for enemies and hazard team +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = { + "*anger1.wav", // Say when acquire an enemy when didn't have one before + "*anger2.wav", "*anger3.wav", + "*victory1.wav", // Say when killed an enemy + "*victory2.wav", "*victory3.wav", + "*confuse1.wav", // Say when confused + "*confuse2.wav", "*confuse3.wav", + "*pushed1.wav", // Say when force-pushed + "*pushed2.wav", "*pushed3.wav", "*choke1.wav", "*choke2.wav", "*choke3.wav", "*ffwarn.wav", "*ffturn.wav", }; -//Used as a supplement to the basic set for stormtroopers -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = -{ - "*chase1.wav", - "*chase2.wav", - "*chase3.wav", - "*cover1.wav", - "*cover2.wav", - "*cover3.wav", - "*cover4.wav", - "*cover5.wav", - "*detected1.wav", - "*detected2.wav", - "*detected3.wav", - "*detected4.wav", - "*detected5.wav", - "*lost1.wav", - "*outflank1.wav", - "*outflank2.wav", - "*escaping1.wav", - "*escaping2.wav", - "*escaping3.wav", - "*giveup1.wav", - "*giveup2.wav", - "*giveup3.wav", - "*giveup4.wav", - "*look1.wav", - "*look2.wav", - "*sight1.wav", - "*sight2.wav", - "*sight3.wav", - "*sound1.wav", - "*sound2.wav", - "*sound3.wav", - "*suspicious1.wav", - "*suspicious2.wav", - "*suspicious3.wav", - "*suspicious4.wav", - "*suspicious5.wav", +// Used as a supplement to the basic set for stormtroopers +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = { + "*chase1.wav", "*chase2.wav", "*chase3.wav", "*cover1.wav", "*cover2.wav", "*cover3.wav", "*cover4.wav", "*cover5.wav", + "*detected1.wav", "*detected2.wav", "*detected3.wav", "*detected4.wav", "*detected5.wav", "*lost1.wav", "*outflank1.wav", "*outflank2.wav", + "*escaping1.wav", "*escaping2.wav", "*escaping3.wav", "*giveup1.wav", "*giveup2.wav", "*giveup3.wav", "*giveup4.wav", "*look1.wav", + "*look2.wav", "*sight1.wav", "*sight2.wav", "*sight3.wav", "*sound1.wav", "*sound2.wav", "*sound3.wav", "*suspicious1.wav", + "*suspicious2.wav", "*suspicious3.wav", "*suspicious4.wav", "*suspicious5.wav", }; -//Used as a supplement to the basic set for jedi -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = -{ - "*combat1.wav", - "*combat2.wav", - "*combat3.wav", - "*jdetected1.wav", - "*jdetected2.wav", - "*jdetected3.wav", - "*taunt1.wav", - "*taunt2.wav", - "*taunt3.wav", - "*jchase1.wav", - "*jchase2.wav", - "*jchase3.wav", - "*jlost1.wav", - "*jlost2.wav", - "*jlost3.wav", - "*deflect1.wav", - "*deflect2.wav", - "*deflect3.wav", - "*gloat1.wav", - "*gloat2.wav", - "*gloat3.wav", - "*pushfail.wav", +// Used as a supplement to the basic set for jedi +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = { + "*combat1.wav", "*combat2.wav", "*combat3.wav", "*jdetected1.wav", "*jdetected2.wav", "*jdetected3.wav", "*taunt1.wav", "*taunt2.wav", + "*taunt3.wav", "*jchase1.wav", "*jchase2.wav", "*jchase3.wav", "*jlost1.wav", "*jlost2.wav", "*jlost3.wav", "*deflect1.wav", + "*deflect2.wav", "*deflect3.wav", "*gloat1.wav", "*gloat2.wav", "*gloat3.wav", "*pushfail.wav", }; - // done at registration time only... // // cuts down on sound-variant registration for low end machines, // eg *gloat1.wav (plus...2,...3) can be capped to all be just *gloat1.wav // -static const char *GetCustomSound_VariantCapped(const char *ppsTable[], int iEntryNum, qboolean bForceVariant1) -{ - extern vmCvar_t cg_VariantSoundCap; +static const char *GetCustomSound_VariantCapped(const char *ppsTable[], int iEntryNum, qboolean bForceVariant1) { + extern vmCvar_t cg_VariantSoundCap; -// const int iVariantCap = 2; // test + // const int iVariantCap = 2; // test const int &iVariantCap = cg_VariantSoundCap.integer; - if (iVariantCap || bForceVariant1) - { - char *p = (char *)strchr(ppsTable[iEntryNum],'.'); - if (p && p-2 > ppsTable[iEntryNum] && isdigit(p[-1]) && !isdigit(p[-2])) - { - int iThisVariant = p[-1]-'0'; + if (iVariantCap || bForceVariant1) { + char *p = (char *)strchr(ppsTable[iEntryNum], '.'); + if (p && p - 2 > ppsTable[iEntryNum] && isdigit(p[-1]) && !isdigit(p[-2])) { + int iThisVariant = p[-1] - '0'; - if (iThisVariant > iVariantCap || bForceVariant1) - { + if (iThisVariant > iVariantCap || bForceVariant1) { // ok, let's not load this variant, so pick a random one below the cap value... // - for (int i=0; i<2; i++) // 1st pass, choose random, 2nd pass (if random not in list), choose xxx1, else fall through... + for (int i = 0; i < 2; i++) // 1st pass, choose random, 2nd pass (if random not in list), choose xxx1, else fall through... { char sName[MAX_QPATH]; Q_strncpyz(sName, ppsTable[iEntryNum], sizeof(sName)); - p = strchr(sName,'.'); - if (p) - { + p = strchr(sName, '.'); + if (p) { *p = '\0'; - sName[strlen(sName)-1] = '\0'; // strip the digit + sName[strlen(sName) - 1] = '\0'; // strip the digit - int iRandom = bForceVariant1 ? 1 : (!i ? Q_irand(1,iVariantCap) : 1); + int iRandom = bForceVariant1 ? 1 : (!i ? Q_irand(1, iVariantCap) : 1); - strcat(sName,va("%d",iRandom)); + strcat(sName, va("%d", iRandom)); // does this exist in the entries before the original one?... // - for (int iScanNum=0; iScanNumstring[0] == 'f' ) - { - hSFX = cgi_S_RegisterSound( va("sound/chars/%s/misc/%s_f.wav", psDir, s + 1) ); + if (g_sex->string[0] == 'f') { + hSFX = cgi_S_RegisterSound(va("sound/chars/%s/misc/%s_f.wav", psDir, s + 1)); } - if (hSFX == 0 || com_buildScript->integer) - { - hSFX = cgi_S_RegisterSound( va("sound/chars/%s/misc/%s.wav", psDir, s + 1) ); + if (hSFX == 0 || com_buildScript->integer) { + hSFX = cgi_S_RegisterSound(va("sound/chars/%s/misc/%s.wav", psDir, s + 1)); } - if (hSFX == 0) - { + if (hSFX == 0) { // hmmm... variant in table was missing, so forcibly-retry with %1 version (which we may have just tried, but wtf?)... // - pS = GetCustomSound_VariantCapped(ppsTable,i, qtrue); - COM_StripExtension( pS, s, sizeof(s) ); - if ( g_sex->string[0] == 'f' ) - { - hSFX = cgi_S_RegisterSound( va("sound/chars/%s/misc/%s_f.wav", psDir, s + 1) ); + pS = GetCustomSound_VariantCapped(ppsTable, i, qtrue); + COM_StripExtension(pS, s, sizeof(s)); + if (g_sex->string[0] == 'f') { + hSFX = cgi_S_RegisterSound(va("sound/chars/%s/misc/%s_f.wav", psDir, s + 1)); } - if (hSFX == 0 || com_buildScript->integer) - { - hSFX = cgi_S_RegisterSound( va("sound/chars/%s/misc/%s.wav", psDir, s + 1) ); + if (hSFX == 0 || com_buildScript->integer) { + hSFX = cgi_S_RegisterSound(va("sound/chars/%s/misc/%s.wav", psDir, s + 1)); } // // and fall through regardless... @@ -361,8 +259,6 @@ static void CG_RegisterCustomSounds(clientInfo_t *ci, int iSoundEntryBase, } } - - /* ================ CG_CustomSound @@ -373,41 +269,32 @@ CG_CustomSound ================ */ -static sfxHandle_t CG_CustomSound( int entityNum, const char *soundName, int customSoundSet ) -{ +static sfxHandle_t CG_CustomSound(int entityNum, const char *soundName, int customSoundSet) { clientInfo_t *ci; - int i; + int i; - if ( soundName[0] != '*' ) - { - return cgi_S_RegisterSound( soundName ); + if (soundName[0] != '*') { + return cgi_S_RegisterSound(soundName); } - if ( !g_entities[entityNum].client ) - { + if (!g_entities[entityNum].client) { // No client, this should never happen, so just don't #ifndef FINAL_BUILD // CG_Printf( "custom sound not on client: %s", soundName ); #endif return 0; - } - else - { + } else { ci = &g_entities[entityNum].client->clientInfo; } - //FIXME: if the sound you want to play could not be found, pick another from the same - //general grouping? ie: if you want ff_2c and there is none, try ff_2b or ff_2a... - switch ( customSoundSet ) - { + // FIXME: if the sound you want to play could not be found, pick another from the same + // general grouping? ie: if you want ff_2c and there is none, try ff_2b or ff_2a... + switch (customSoundSet) { case CS_BASIC: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customBasicSoundNames[i] ) ) - { + if (ci) { + for (i = 0; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customBasicSoundNames[i])) { return ci->sounds[i]; } } @@ -415,74 +302,56 @@ static sfxHandle_t CG_CustomSound( int entityNum, const char *soundName, int cus break; case CS_COMBAT: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customCombatSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customCombatSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS]; } } } break; case CS_EXTRA: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customExtraSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customExtraSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS]; } } } break; case CS_JEDI: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customJediSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customJediSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS]; } } } break; case CS_TRY_ALL: default: - //no set specified, search all - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customBasicSoundNames[i] ) ) - { + // no set specified, search all + if (ci) { + for (i = 0; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customBasicSoundNames[i])) { return ci->sounds[i]; } } - for ( i = 0 ; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customCombatSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customCombatSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS]; } } - for ( i = 0 ; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customExtraSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customExtraSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS]; } } - for ( i = 0 ; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customJediSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customJediSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS]; } } } @@ -490,22 +359,20 @@ static sfxHandle_t CG_CustomSound( int entityNum, const char *soundName, int cus } #ifdef FINAL_BUILD - CG_Printf( "Unknown custom sound: %s", soundName ); + CG_Printf("Unknown custom sound: %s", soundName); #else - CG_Error( "Unknown custom sound: %s", soundName ); + CG_Error("Unknown custom sound: %s", soundName); #endif return 0; } -qboolean CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ) -{ - sfxHandle_t soundIndex = CG_CustomSound( entityNum, soundName, customSoundSet ); - if ( !soundIndex ) - { +qboolean CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet) { + sfxHandle_t soundIndex = CG_CustomSound(entityNum, soundName, customSoundSet); + if (!soundIndex) { return qfalse; } - cgi_S_StartSound( origin, entityNum, channel, soundIndex ); + cgi_S_StartSound(origin, entityNum, channel, soundIndex); return qtrue; } /* @@ -515,127 +382,116 @@ CG_NewClientinfo For player only, NPCs get them through NPC_stats and G_ModelIndex ====================== */ -void CG_NewClientinfo( int clientNum ) -{ +void CG_NewClientinfo(int clientNum) { clientInfo_t *ci; - const char *configstring; - const char *v; -// const char *s; -// int i; + const char *configstring; + const char *v; + // const char *s; + // int i; - configstring = CG_ConfigString( clientNum + CS_PLAYERS ); + configstring = CG_ConfigString(clientNum + CS_PLAYERS); - if ( !configstring[0] ) - { - return; // player just left + if (!configstring[0]) { + return; // player just left } - //ci = &cgs.clientinfo[clientNum]; - if ( !(g_entities[clientNum].client) ) - { + // ci = &cgs.clientinfo[clientNum]; + if (!(g_entities[clientNum].client)) { return; } ci = &g_entities[clientNum].client->clientInfo; // isolate the player's name v = Info_ValueForKey(configstring, "n"); - Q_strncpyz( ci->name, v, sizeof( ci->name ) ); + Q_strncpyz(ci->name, v, sizeof(ci->name)); // handicap - v = Info_ValueForKey( configstring, "hc" ); - ci->handicap = atoi( v ); + v = Info_ValueForKey(configstring, "hc"); + ci->handicap = atoi(v); // team - v = Info_ValueForKey( configstring, "t" ); - ci->team = (team_t) atoi( v ); + v = Info_ValueForKey(configstring, "t"); + ci->team = (team_t)atoi(v); // legsModel - v = Info_ValueForKey( configstring, "legsModel" ); + v = Info_ValueForKey(configstring, "legsModel"); - Q_strncpyz( g_entities[clientNum].client->renderInfo.legsModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.legsModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.legsModelName, v, sizeof(g_entities[clientNum].client->renderInfo.legsModelName)); // torsoModel - v = Info_ValueForKey( configstring, "torsoModel" ); + v = Info_ValueForKey(configstring, "torsoModel"); - Q_strncpyz( g_entities[clientNum].client->renderInfo.torsoModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.torsoModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.torsoModelName, v, sizeof(g_entities[clientNum].client->renderInfo.torsoModelName)); // headModel - v = Info_ValueForKey( configstring, "headModel" ); + v = Info_ValueForKey(configstring, "headModel"); - Q_strncpyz( g_entities[clientNum].client->renderInfo.headModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.headModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.headModelName, v, sizeof(g_entities[clientNum].client->renderInfo.headModelName)); // sounds - v = Info_ValueForKey( configstring, "snd" ); + v = Info_ValueForKey(configstring, "snd"); - ci->customBasicSoundDir = G_NewString( v ); + ci->customBasicSoundDir = G_NewString(v); - //player uses only the basic custom and combat sound sets, not the extra or jedi + // player uses only the basic custom and combat sound sets, not the extra or jedi CG_RegisterCustomSounds(ci, - 0, // int iSoundEntryBase, - MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, - cg_customBasicSoundNames, // const char *ppsTable[], - ci->customBasicSoundDir // const char *psDir - ); + 0, // int iSoundEntryBase, + MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, + cg_customBasicSoundNames, // const char *ppsTable[], + ci->customBasicSoundDir // const char *psDir + ); CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, - cg_customCombatSoundNames, // const char *ppsTable[], - ci->customBasicSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, + cg_customCombatSoundNames, // const char *ppsTable[], + ci->customBasicSoundDir // const char *psDir + ); ci->infoValid = qfalse; } /* CG_RegisterNPCCustomSounds */ -void CG_RegisterNPCCustomSounds( clientInfo_t *ci ) -{ -// const char *s; -// int i; +void CG_RegisterNPCCustomSounds(clientInfo_t *ci) { + // const char *s; + // int i; // sounds - if ( ci->customBasicSoundDir && ci->customBasicSoundDir[0] ) - { + if (ci->customBasicSoundDir && ci->customBasicSoundDir[0]) { CG_RegisterCustomSounds(ci, - 0, // int iSoundEntryBase, - MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, - cg_customBasicSoundNames, // const char *ppsTable[], - ci->customBasicSoundDir // const char *psDir - ); + 0, // int iSoundEntryBase, + MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, + cg_customBasicSoundNames, // const char *ppsTable[], + ci->customBasicSoundDir // const char *psDir + ); } - if ( ci->customCombatSoundDir && ci->customCombatSoundDir[0] ) - { + if (ci->customCombatSoundDir && ci->customCombatSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, - cg_customCombatSoundNames, // const char *ppsTable[], - ci->customCombatSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, + cg_customCombatSoundNames, // const char *ppsTable[], + ci->customCombatSoundDir // const char *psDir + ); } - if ( ci->customExtraSoundDir && ci->customExtraSoundDir[0] ) - { + if (ci->customExtraSoundDir && ci->customExtraSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_EXTRA_SOUNDS, // int iTableEntries, - cg_customExtraSoundNames, // const char *ppsTable[], - ci->customExtraSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_EXTRA_SOUNDS, // int iTableEntries, + cg_customExtraSoundNames, // const char *ppsTable[], + ci->customExtraSoundDir // const char *psDir + ); } - if ( ci->customJediSoundDir && ci->customJediSoundDir[0] ) - { + if (ci->customJediSoundDir && ci->customJediSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_JEDI_SOUNDS, // int iTableEntries, - cg_customJediSoundNames, // const char *ppsTable[], - ci->customJediSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_JEDI_SOUNDS, // int iTableEntries, + cg_customJediSoundNames, // const char *ppsTable[], + ci->customJediSoundDir // const char *psDir + ); } } @@ -676,18 +532,15 @@ PLAYER ANIMATION ============================================================================= */ -qboolean ValidAnimFileIndex ( int index ) -{ - if ( index < 0 || index >= level.numKnownAnimFileSets ) - { - Com_Printf( S_COLOR_RED "Bad animFileIndex: %d\n", index ); +qboolean ValidAnimFileIndex(int index) { + if (index < 0 || index >= level.numKnownAnimFileSets) { + Com_Printf(S_COLOR_RED "Bad animFileIndex: %d\n", index); return qfalse; } return qtrue; } - /* ====================== CG_ClearAnimEvtCache @@ -695,13 +548,11 @@ CG_ClearAnimEvtCache resets all the eventcache so that a vid restart will recache them ====================== */ -void CG_ClearAnimEvtCache( void ) -{ +void CG_ClearAnimEvtCache(void) { int i; - for (i=0; i < level.numKnownAnimFileSets; i++) - { + for (i = 0; i < level.numKnownAnimFileSets; i++) { // TODO: Make this work again? - // level.knownAnimFileSets[i].eventsParsed = qfalse; + // level.knownAnimFileSets[i].eventsParsed = qfalse; } } @@ -710,31 +561,28 @@ void CG_ClearAnimEvtCache( void ) CG_SetLerpFrameAnimation =============== */ -static void CG_SetLerpFrameAnimation( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation ) -{ - animation_t *anim; +static void CG_SetLerpFrameAnimation(clientInfo_t *ci, lerpFrame_t *lf, int newAnimation) { + animation_t *anim; - if ( newAnimation < 0 || newAnimation >= MAX_ANIMATIONS ) - { + if (newAnimation < 0 || newAnimation >= MAX_ANIMATIONS) { #ifdef FINAL_BUILD newAnimation = 0; #else - CG_Error( "Bad animation number: %i for ", newAnimation, ci->name ); + CG_Error("Bad animation number: %i for ", newAnimation, ci->name); #endif } lf->animationNumber = newAnimation; - if ( !ValidAnimFileIndex( ci->animFileIndex ) ) - { + if (!ValidAnimFileIndex(ci->animFileIndex)) { #ifdef FINAL_BUILD ci->animFileIndex = 0; #else - CG_Error( "Bad animFileIndex: %i for %s", ci->animFileIndex, ci->name); + CG_Error("Bad animFileIndex: %i for %s", ci->animFileIndex, ci->name); #endif } - anim = &level.knownAnimFileSets[ci->animFileIndex].animations[ newAnimation ]; + anim = &level.knownAnimFileSets[ci->animFileIndex].animations[newAnimation]; lf->animation = anim; lf->animationTime = lf->frameTime + abs(anim->frameLerp); @@ -748,33 +596,30 @@ Sets cg.snap, cg.oldFrame, and cg.backlerp cg.time should be between oldFrameTime and frameTime after exit =============== */ -static qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float fpsMod, int entNum ) { - int f, animFrameTime; - animation_t *anim; - qboolean newFrame = qfalse; +static qboolean CG_RunLerpFrame(clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float fpsMod, int entNum) { + int f, animFrameTime; + animation_t *anim; + qboolean newFrame = qfalse; - if(fpsMod > 2 || fpsMod < 0.5) - {//should have been set right + if (fpsMod > 2 || fpsMod < 0.5) { // should have been set right fpsMod = 1.0f; } // see if the animation sequence is switching - //FIXME: allow multiple-frame overlapped lerping between sequences? - Possibly last 3 of last seq and first 3 of next seq? - if ( newAnimation != lf->animationNumber || !lf->animation ) - { - CG_SetLerpFrameAnimation( ci, lf, newAnimation ); + // FIXME: allow multiple-frame overlapped lerping between sequences? - Possibly last 3 of last seq and first 3 of next seq? + if (newAnimation != lf->animationNumber || !lf->animation) { + CG_SetLerpFrameAnimation(ci, lf, newAnimation); } // if we have passed the current frame, move it to // oldFrame and calculate a new frame - if ( cg.time >= lf->frameTime ) - { + if (cg.time >= lf->frameTime) { lf->oldFrame = lf->frame; lf->oldFrameTime = lf->frameTime; // get the next frame based on the animation anim = lf->animation; - //Do we need to speed up or slow down the anim? + // Do we need to speed up or slow down the anim? /*if(fpsMod != 1.0) {//Note! despite it's name, a higher fpsMod slows down the anim, a lower one speeds it up animFrameTime = ceil(lf->frameTime * fpsMod); @@ -783,47 +628,35 @@ static qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnima { animFrameTime = abs(anim->frameLerp); - //special hack for player to ensure quick weapon change - if ( entNum == 0 ) - { - if ( lf->animationNumber == TORSO_DROPWEAP1 || lf->animationNumber == TORSO_RAISEWEAP1 ) - { + // special hack for player to ensure quick weapon change + if (entNum == 0) { + if (lf->animationNumber == TORSO_DROPWEAP1 || lf->animationNumber == TORSO_RAISEWEAP1) { animFrameTime = 50; } } } - if ( cg.time < lf->animationTime ) - { - lf->frameTime = lf->animationTime; // initial lerp - } - else - { + if (cg.time < lf->animationTime) { + lf->frameTime = lf->animationTime; // initial lerp + } else { lf->frameTime = lf->oldFrameTime + animFrameTime; } - f = ( lf->frameTime - lf->animationTime ) / animFrameTime; - if ( f >= anim->numFrames ) - {//Reached the end of the anim - //FIXME: Need to set a flag here to TASK_COMPLETE + f = (lf->frameTime - lf->animationTime) / animFrameTime; + if (f >= anim->numFrames) { // Reached the end of the anim + // FIXME: Need to set a flag here to TASK_COMPLETE f -= anim->numFrames; - if ( anim->loopFrames != -1 ) //Before 0 meant no loop + if (anim->loopFrames != -1) // Before 0 meant no loop { - if(anim->numFrames - anim->loopFrames == 0) - { + if (anim->numFrames - anim->loopFrames == 0) { f %= anim->numFrames; - } - else - { + } else { f %= (anim->numFrames - anim->loopFrames); } f += anim->loopFrames; - } - else - { + } else { f = anim->numFrames - 1; - if (f<0) - { + if (f < 0) { f = 0; } // the animation is stuck at the end, so it @@ -832,61 +665,47 @@ static qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnima } } - if ( anim->frameLerp < 0 ) - { + if (anim->frameLerp < 0) { lf->frame = anim->firstFrame + anim->numFrames - 1 - f; - } - else - { + } else { lf->frame = anim->firstFrame + f; } - if ( cg.time > lf->frameTime ) - { + if (cg.time > lf->frameTime) { lf->frameTime = cg.time; } newFrame = qtrue; } - if ( lf->frameTime > cg.time + 200 ) - { + if (lf->frameTime > cg.time + 200) { lf->frameTime = cg.time; } - if ( lf->oldFrameTime > cg.time ) - { + if (lf->oldFrameTime > cg.time) { lf->oldFrameTime = cg.time; } // calculate current lerp value - if ( lf->frameTime == lf->oldFrameTime ) - { + if (lf->frameTime == lf->oldFrameTime) { lf->backlerp = 0; - } - else - { - lf->backlerp = 1.0 - (float)( cg.time - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime ); + } else { + lf->backlerp = 1.0 - (float)(cg.time - lf->oldFrameTime) / (lf->frameTime - lf->oldFrameTime); } return newFrame; } - /* =============== CG_ClearLerpFrame =============== */ -static void CG_ClearLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int animationNumber ) -{ +static void CG_ClearLerpFrame(clientInfo_t *ci, lerpFrame_t *lf, int animationNumber) { lf->frameTime = lf->oldFrameTime = cg.time; - CG_SetLerpFrameAnimation( ci, lf, animationNumber ); - if ( lf->animation->frameLerp < 0 ) - {//Plays backwards + CG_SetLerpFrameAnimation(ci, lf, animationNumber); + if (lf->animation->frameLerp < 0) { // Plays backwards lf->oldFrame = lf->frame = (lf->animation->firstFrame + lf->animation->numFrames); - } - else - { + } else { lf->oldFrame = lf->frame = lf->animation->firstFrame; } } @@ -896,264 +715,211 @@ static void CG_ClearLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int animationN CG_PlayerAnimation =============== */ -static void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, - int *torsoOld, int *torso, float *torsoBackLerp ) { - clientInfo_t *ci; - int legsAnim; - int legsTurnAnim = -1; - qboolean newLegsFrame = qfalse; - qboolean newTorsoFrame = qfalse; +static void CG_PlayerAnimation(centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, int *torsoOld, int *torso, float *torsoBackLerp) { + clientInfo_t *ci; + int legsAnim; + int legsTurnAnim = -1; + qboolean newLegsFrame = qfalse; + qboolean newTorsoFrame = qfalse; ci = ¢->gent->client->clientInfo; - //Changed this from cent->currentState.legsAnim to cent->gent->client->ps.legsAnim because it was screwing up our timers when we've just changed anims while turning + // Changed this from cent->currentState.legsAnim to cent->gent->client->ps.legsAnim because it was screwing up our timers when we've just changed anims + // while turning legsAnim = cent->gent->client->ps.legsAnim; // do the shuffle turn frames locally (MAN this is an Fugly-ass hack!) - if ( cent->pe.legs.yawing ) - { - legsTurnAnim = PM_GetTurnAnim( cent->gent, legsAnim ); + if (cent->pe.legs.yawing) { + legsTurnAnim = PM_GetTurnAnim(cent->gent, legsAnim); } - if ( legsTurnAnim != -1 ) - { - newLegsFrame = CG_RunLerpFrame( ci, ¢->pe.legs, legsTurnAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number ); - //This line doesn't seem to serve any useful purpose, rather it - //breaks things since any task waiting for a lower anim to complete - //never will finish if this happens!!! - //cent->gent->client->ps.legsAnimTimer = 0; - } - else - { - newLegsFrame = CG_RunLerpFrame( ci, ¢->pe.legs, legsAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); + if (legsTurnAnim != -1) { + newLegsFrame = CG_RunLerpFrame(ci, ¢->pe.legs, legsTurnAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); + // This line doesn't seem to serve any useful purpose, rather it + // breaks things since any task waiting for a lower anim to complete + // never will finish if this happens!!! + // cent->gent->client->ps.legsAnimTimer = 0; + } else { + newLegsFrame = CG_RunLerpFrame(ci, ¢->pe.legs, legsAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); } *legsOld = cent->pe.legs.oldFrame; *legs = cent->pe.legs.frame; *legsBackLerp = cent->pe.legs.backlerp; - if( newLegsFrame ) - { - if ( ValidAnimFileIndex( ci->animFileIndex ) ) - { - CG_PlayerAnimEvents( ci->animFileIndex, qfalse, cent->pe.legs.frame, cent->pe.legs.frame, cent->currentState.number ); + if (newLegsFrame) { + if (ValidAnimFileIndex(ci->animFileIndex)) { + CG_PlayerAnimEvents(ci->animFileIndex, qfalse, cent->pe.legs.frame, cent->pe.legs.frame, cent->currentState.number); } } - newTorsoFrame = CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); + newTorsoFrame = CG_RunLerpFrame(ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number); *torsoOld = cent->pe.torso.oldFrame; *torso = cent->pe.torso.frame; *torsoBackLerp = cent->pe.torso.backlerp; - if( newTorsoFrame ) - { - if ( ValidAnimFileIndex( ci->animFileIndex ) ) - { - CG_PlayerAnimEvents(ci->animFileIndex, qtrue, cent->pe.torso.frame, cent->pe.torso.frame, cent->currentState.number ); + if (newTorsoFrame) { + if (ValidAnimFileIndex(ci->animFileIndex)) { + CG_PlayerAnimEvents(ci->animFileIndex, qtrue, cent->pe.torso.frame, cent->pe.torso.frame, cent->currentState.number); } } } - -extern int PM_LegsAnimForFrame( gentity_t *ent, int legsFrame ); -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -static void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) -{ - //FIXME: pass in event, switch off the type - if ( cent == NULL || animEvent == NULL ) - { +extern int PM_LegsAnimForFrame(gentity_t *ent, int legsFrame); +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +static void CG_PlayerAnimEventDo(centity_t *cent, animevent_t *animEvent) { + // FIXME: pass in event, switch off the type + if (cent == NULL || animEvent == NULL) { return; } soundChannel_t channel = CHAN_AUTO; - switch ( animEvent->eventType ) - { + switch (animEvent->eventType) { case AEV_SOUNDCHAN: channel = (soundChannel_t)animEvent->eventData[AED_SOUNDCHANNEL]; case AEV_SOUND: // are there variations on the sound? { - const int holdSnd = animEvent->eventData[ AED_SOUNDINDEX_START+Q_irand( 0, animEvent->eventData[AED_SOUND_NUMRANDOMSNDS] ) ]; - if ( holdSnd > 0 ) - { - if ( cgs.sound_precache[ holdSnd ] ) - { - cgi_S_StartSound( NULL, cent->currentState.clientNum, channel, cgs.sound_precache[holdSnd ] ); - } - else - {//try a custom sound - const char *s = CG_ConfigString( CS_SOUNDS + holdSnd ); - CG_TryPlayCustomSound(NULL, cent->currentState.clientNum, channel, va("%s.wav",s), CS_TRY_ALL ); + const int holdSnd = animEvent->eventData[AED_SOUNDINDEX_START + Q_irand(0, animEvent->eventData[AED_SOUND_NUMRANDOMSNDS])]; + if (holdSnd > 0) { + if (cgs.sound_precache[holdSnd]) { + cgi_S_StartSound(NULL, cent->currentState.clientNum, channel, cgs.sound_precache[holdSnd]); + } else { // try a custom sound + const char *s = CG_ConfigString(CS_SOUNDS + holdSnd); + CG_TryPlayCustomSound(NULL, cent->currentState.clientNum, channel, va("%s.wav", s), CS_TRY_ALL); } } } break; case AEV_SABER_SWING: - if ( cent->gent ) - {//cheat over to game side and play sound from there... - WP_SaberSwingSound( cent->gent, animEvent->eventData[AED_SABER_SWING_SABERNUM], (swingType_t)animEvent->eventData[AED_SABER_SWING_TYPE] ); + if (cent->gent) { // cheat over to game side and play sound from there... + WP_SaberSwingSound(cent->gent, animEvent->eventData[AED_SABER_SWING_SABERNUM], (swingType_t)animEvent->eventData[AED_SABER_SWING_TYPE]); } break; case AEV_SABER_SPIN: - if ( cent->gent - && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { saberInfo_t *saber = ¢->gent->client->ps.saber[animEvent->eventData[AED_SABER_SPIN_SABERNUM]]; - if ( saber ) - { + if (saber) { int spinSound = 0; - if ( saber->spinSound - && cgs.sound_precache[saber->spinSound] ) - {//use override + if (saber->spinSound && cgs.sound_precache[saber->spinSound]) { // use override spinSound = cgs.sound_precache[saber->spinSound]; - } - else - { - switch ( animEvent->eventData[AED_SABER_SPIN_TYPE] ) - { - case 0://saberspinoff - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); + } else { + switch (animEvent->eventData[AED_SABER_SPIN_TYPE]) { + case 0: // saberspinoff + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); break; - case 1://saberspin - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin.wav" ); + case 1: // saberspin + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin.wav"); break; - case 2://saberspin1 - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + case 2: // saberspin1 + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; - case 3://saberspin2 - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + case 3: // saberspin2 + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; - case 4://saberspin3 - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + case 4: // saberspin3 + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; - default://random saberspin1-3 - spinSound = cgi_S_RegisterSound( va( "sound/weapons/saber/saberspin%d.wav", Q_irand(1,3)) ); + default: // random saberspin1-3 + spinSound = cgi_S_RegisterSound(va("sound/weapons/saber/saberspin%d.wav", Q_irand(1, 3))); break; } } - if ( spinSound ) - { - cgi_S_StartSound( NULL, cent->currentState.clientNum, CHAN_AUTO, spinSound ); + if (spinSound) { + cgi_S_StartSound(NULL, cent->currentState.clientNum, CHAN_AUTO, spinSound); } } } break; case AEV_FOOTSTEP: - CG_PlayerFootsteps( cent, (footstepType_t)animEvent->eventData[AED_FOOTSTEP_TYPE] ); + CG_PlayerFootsteps(cent, (footstepType_t)animEvent->eventData[AED_FOOTSTEP_TYPE]); break; case AEV_EFFECT: - if ( animEvent->eventData[AED_EFFECTINDEX] == -1 ) - {//invalid effect - if ( animEvent->stringData != NULL - && animEvent->stringData[0] ) - {//some sort of hard-coded effect - if ( Q_stricmp( "push_l", animEvent->stringData ) == 0 ) - { - cgi_S_StartSound ( cent->lerpOrigin, cent->currentState.clientNum, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/force/push.wav" ) ); - cent->gent->client->ps.powerups[PW_FORCE_PUSH] = cg.time + animEvent->eventData[AED_EFFECT_PROBABILITY];//AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last + if (animEvent->eventData[AED_EFFECTINDEX] == -1) { // invalid effect + if (animEvent->stringData != NULL && animEvent->stringData[0]) { // some sort of hard-coded effect + if (Q_stricmp("push_l", animEvent->stringData) == 0) { + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.clientNum, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/force/push.wav")); + cent->gent->client->ps.powerups[PW_FORCE_PUSH] = + cg.time + + animEvent->eventData[AED_EFFECT_PROBABILITY]; // AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last cent->gent->client->pushEffectFadeTime = 0; - } - else if ( Q_stricmp( "push_r", animEvent->stringData ) == 0 ) - { - cgi_S_StartSound ( cent->lerpOrigin, cent->currentState.clientNum, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/force/push.wav" ) ); - cent->gent->client->ps.powerups[PW_FORCE_PUSH_RHAND] = cg.time + animEvent->eventData[AED_EFFECT_PROBABILITY];//AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last + } else if (Q_stricmp("push_r", animEvent->stringData) == 0) { + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.clientNum, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/force/push.wav")); + cent->gent->client->ps.powerups[PW_FORCE_PUSH_RHAND] = + cg.time + + animEvent->eventData[AED_EFFECT_PROBABILITY]; // AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last cent->gent->client->pushEffectFadeTime = 0; - } - else if ( Q_stricmp( "scepter_beam", animEvent->stringData ) == 0 ) - { + } else if (Q_stricmp("scepter_beam", animEvent->stringData) == 0) { int modelIndex = cent->gent->weaponModel[1]; - if ( modelIndex <= 0 ) - { + if (modelIndex <= 0) { modelIndex = cent->gent->cinematicModel; } - if ( modelIndex > 0 ) - {//we have a cinematic model - int boltIndex = gi.G2API_AddBolt( ¢->gent->ghoul2[modelIndex], "*flash" ); - if ( boltIndex > -1 ) - {//cinematic model has a flash bolt - CG_PlayEffectBolted( "scepter/beam.efx", modelIndex, boltIndex, cent->currentState.clientNum, cent->lerpOrigin, animEvent->eventData[AED_EFFECT_PROBABILITY], qtrue );//AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last + if (modelIndex > 0) { // we have a cinematic model + int boltIndex = gi.G2API_AddBolt(¢->gent->ghoul2[modelIndex], "*flash"); + if (boltIndex > -1) { // cinematic model has a flash bolt + CG_PlayEffectBolted("scepter/beam.efx", modelIndex, boltIndex, cent->currentState.clientNum, cent->lerpOrigin, + animEvent->eventData[AED_EFFECT_PROBABILITY], + qtrue); // AED_EFFECT_PROBABILITY in this case is the number of ms for the effect to last } } } - //FIXME: add more + // FIXME: add more } - } - else - { - //add bolt, play effect - if ( animEvent->stringData != NULL && cent && cent->gent && cent->gent->ghoul2.size() ) - {//have a bolt name we want to use + } else { + // add bolt, play effect + if (animEvent->stringData != NULL && cent && cent->gent && cent->gent->ghoul2.size()) { // have a bolt name we want to use animEvent->eventData[AED_MODELINDEX] = cent->gent->playerModel; - if ( ( Q_stricmpn( "*blade", animEvent->stringData, 6 ) == 0 - || Q_stricmp( "*flash", animEvent->stringData ) == 0 ) - && cent->gent->weaponModel[0] > 0 ) - {//must be a weapon, try weapon 0? - animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->weaponModel[0]], animEvent->stringData ); - if ( animEvent->eventData[AED_BOLTINDEX] != -1 ) - {//found it! + if ((Q_stricmpn("*blade", animEvent->stringData, 6) == 0 || Q_stricmp("*flash", animEvent->stringData) == 0) && + cent->gent->weaponModel[0] > 0) { // must be a weapon, try weapon 0? + animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt(¢->gent->ghoul2[cent->gent->weaponModel[0]], animEvent->stringData); + if (animEvent->eventData[AED_BOLTINDEX] != -1) { // found it! animEvent->eventData[AED_MODELINDEX] = cent->gent->weaponModel[0]; + } else { // hmm, just try on the player model, then? + animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt(¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData); } - else - {//hmm, just try on the player model, then? - animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); - } - } - else - { - animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); + } else { + animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt(¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData); } - animEvent->stringData = NULL;//so we don't try to do this again - } - if ( animEvent->eventData[AED_BOLTINDEX] != -1 ) - {//have a bolt we want to play the effect on - CG_PlayEffectIDBolted( animEvent->eventData[AED_EFFECTINDEX], - animEvent->eventData[AED_MODELINDEX], - animEvent->eventData[AED_BOLTINDEX], - cent->currentState.clientNum, - cent->lerpOrigin ); + animEvent->stringData = NULL; // so we don't try to do this again } - else - {//play at origin? FIXME: maybe allow a fwd/rt/up offset? - const vec3_t up = {0,0,1}; - CG_PlayEffectID( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, up ); - //G_PlayEffect( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, up ); - //theFxScheduler.PlayEffect( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, qfalse ); + if (animEvent->eventData[AED_BOLTINDEX] != -1) { // have a bolt we want to play the effect on + CG_PlayEffectIDBolted(animEvent->eventData[AED_EFFECTINDEX], animEvent->eventData[AED_MODELINDEX], animEvent->eventData[AED_BOLTINDEX], + cent->currentState.clientNum, cent->lerpOrigin); + } else { // play at origin? FIXME: maybe allow a fwd/rt/up offset? + const vec3_t up = {0, 0, 1}; + CG_PlayEffectID(animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, up); + // G_PlayEffect( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, up ); + // theFxScheduler.PlayEffect( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, qfalse ); } } break; case AEV_FIRE: - //add fire event - if ( animEvent->eventData[AED_FIRE_ALT] ) - { - G_AddEvent( cent->gent, EV_ALT_FIRE, 0 ); - } - else - { - G_AddEvent( cent->gent, EV_FIRE_WEAPON, 0 ); + // add fire event + if (animEvent->eventData[AED_FIRE_ALT]) { + G_AddEvent(cent->gent, EV_ALT_FIRE, 0); + } else { + G_AddEvent(cent->gent, EV_FIRE_WEAPON, 0); } break; case AEV_MOVE: - //make him jump - if ( cent && cent->gent && cent->gent->client ) - { - if ( cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on something - vec3_t fwd, rt, up, angles = {0, cent->gent->client->ps.viewangles[YAW], 0}; - AngleVectors( angles, fwd, rt, up ); - //FIXME: set or add to velocity? - VectorScale( fwd, animEvent->eventData[AED_MOVE_FWD], cent->gent->client->ps.velocity ); - VectorMA( cent->gent->client->ps.velocity, animEvent->eventData[AED_MOVE_RT], rt, cent->gent->client->ps.velocity ); - VectorMA( cent->gent->client->ps.velocity, animEvent->eventData[AED_MOVE_UP], up, cent->gent->client->ps.velocity ); - - if ( animEvent->eventData[AED_MOVE_UP] > 0 ) - {//a jump + // make him jump + if (cent && cent->gent && cent->gent->client) { + if (cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on something + vec3_t fwd, rt, up, angles = {0, cent->gent->client->ps.viewangles[YAW], 0}; + AngleVectors(angles, fwd, rt, up); + // FIXME: set or add to velocity? + VectorScale(fwd, animEvent->eventData[AED_MOVE_FWD], cent->gent->client->ps.velocity); + VectorMA(cent->gent->client->ps.velocity, animEvent->eventData[AED_MOVE_RT], rt, cent->gent->client->ps.velocity); + VectorMA(cent->gent->client->ps.velocity, animEvent->eventData[AED_MOVE_UP], up, cent->gent->client->ps.velocity); + + if (animEvent->eventData[AED_MOVE_UP] > 0) { // a jump cent->gent->client->ps.pm_flags |= PMF_JUMPING; - G_AddEvent( cent->gent, EV_JUMP, 0 ); - //FIXME: if have force jump, do this? or specify sound in the event data? - //cent->gent->client->ps.forceJumpZStart = cent->gent->client->ps.origin[2];//so we don't take damage if we land at same height - //G_SoundOnEnt( cent->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + G_AddEvent(cent->gent, EV_JUMP, 0); + // FIXME: if have force jump, do this? or specify sound in the event data? + // cent->gent->client->ps.forceJumpZStart = cent->gent->client->ps.origin[2];//so we don't take damage if we land at same height + // G_SoundOnEnt( cent->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); } } } @@ -1164,122 +930,86 @@ static void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) } } -static void CG_PlayerAnimEvents( int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum ) -{ - int i; - int firstFrame = 0, lastFrame = 0; - qboolean doEvent = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; +static void CG_PlayerAnimEvents(int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum) { + int i; + int firstFrame = 0, lastFrame = 0; + qboolean doEvent = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; animevent_t *animEvents = NULL; - int glaIndex = -1; + int glaIndex = -1; - if ( g_entities[entNum].ghoul2.size() ) - { + if (g_entities[entNum].ghoul2.size()) { glaIndex = gi.G2API_GetAnimIndex(&(g_entities[entNum].ghoul2[0])); } - if ( torso ) - { + if (torso) { animEvents = level.knownAnimFileSets[animFileIndex].torsoAnimEvents; - } - else - { + } else { animEvents = level.knownAnimFileSets[animFileIndex].legsAnimEvents; } - if ( abs(oldFrame-frame) > 1 ) - {//given a range, see if keyFrame falls in that range + if (abs(oldFrame - frame) > 1) { // given a range, see if keyFrame falls in that range int oldAnim, anim; - if ( torso ) - { - //more precise, slower - oldAnim = PM_TorsoAnimForFrame( &g_entities[entNum], oldFrame ); - anim = PM_TorsoAnimForFrame( &g_entities[entNum], frame ); - } - else - { - //more precise, slower - oldAnim = PM_LegsAnimForFrame( &g_entities[entNum], oldFrame ); - anim = PM_LegsAnimForFrame( &g_entities[entNum], frame ); + if (torso) { + // more precise, slower + oldAnim = PM_TorsoAnimForFrame(&g_entities[entNum], oldFrame); + anim = PM_TorsoAnimForFrame(&g_entities[entNum], frame); + } else { + // more precise, slower + oldAnim = PM_LegsAnimForFrame(&g_entities[entNum], oldFrame); + anim = PM_LegsAnimForFrame(&g_entities[entNum], frame); } - if ( anim != oldAnim ) - {//not in same anim + if (anim != oldAnim) { // not in same anim inSameAnim = qfalse; - //FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... - } - else - {//still in same anim, check for looping anim + // FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... + } else { // still in same anim, check for looping anim inSameAnim = qtrue; animation_t *animation = &level.knownAnimFileSets[animFileIndex].animations[anim]; - animBackward = (qboolean)(animation->frameLerp<0); - if ( animation->loopFrames != -1 ) - {//a looping anim! + animBackward = (qboolean)(animation->frameLerp < 0); + if (animation->loopFrames != -1) { // a looping anim! loopAnim = qtrue; firstFrame = animation->firstFrame; - lastFrame = animation->firstFrame+animation->numFrames; + lastFrame = animation->firstFrame + animation->numFrames; } } } - hstring myModel = g_entities[entNum].NPC_type; //apparently NPC_type is always the same as the model name??? + hstring myModel = g_entities[entNum].NPC_type; // apparently NPC_type is always the same as the model name??? // Check for anim event - for ( i=0; i < MAX_ANIM_EVENTS; ++i ) - { - if ( animEvents[i].eventType == AEV_NONE ) // No event, end of list + for (i = 0; i < MAX_ANIM_EVENTS; ++i) { + if (animEvents[i].eventType == AEV_NONE) // No event, end of list { break; } - if (glaIndex != -1 && animEvents[i].glaIndex!=glaIndex) - { + if (glaIndex != -1 && animEvents[i].glaIndex != glaIndex) { continue; } match = qfalse; - if (animEvents[i].modelOnly==0 || animEvents[i].modelOnly==myModel.handle()) - { - if ( animEvents[i].keyFrame == frame ) - {//exact match + if (animEvents[i].modelOnly == 0 || animEvents[i].modelOnly == myModel.handle()) { + if (animEvents[i].keyFrame == frame) { // exact match match = qtrue; - } - else if ( abs(oldFrame-frame) > 1 )//&& cg_reliableAnimEvents.integer ) - {//given a range, see if keyFrame falls in that range - if ( inSameAnim ) - {//if changed anims altogether, sorry, the sound is lost - if ( abs(oldFrame-animEvents[i].keyFrame) <= 3 - || abs(frame-animEvents[i].keyFrame) <= 3 ) - {//must be at least close to the keyframe - if ( animBackward ) - {//animation plays backwards - if ( oldFrame > animEvents[i].keyFrame && frame < animEvents[i].keyFrame ) - {//old to new passed through keyframe + } else if (abs(oldFrame - frame) > 1) //&& cg_reliableAnimEvents.integer ) + { // given a range, see if keyFrame falls in that range + if (inSameAnim) { // if changed anims altogether, sorry, the sound is lost + if (abs(oldFrame - animEvents[i].keyFrame) <= 3 || abs(frame - animEvents[i].keyFrame) <= 3) { // must be at least close to the keyframe + if (animBackward) { // animation plays backwards + if (oldFrame > animEvents[i].keyFrame && frame < animEvents[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame > animEvents[i].keyFrame - && frame > oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame > animEvents[i].keyFrame && frame > oldFrame) { // old to new passed through keyframe match = qtrue; } } } - } - else - {//anim plays forwards - if ( oldFrame < animEvents[i].keyFrame && frame > animEvents[i].keyFrame ) - {//old to new passed through keyframe + } else { // anim plays forwards + if (oldFrame < animEvents[i].keyFrame && frame > animEvents[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame < animEvents[i].keyFrame - && frame < oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame < animEvents[i].keyFrame && frame < oldFrame) { // old to new passed through keyframe match = qtrue; } } @@ -1288,75 +1018,62 @@ static void CG_PlayerAnimEvents( int animFileIndex, qboolean torso, int oldFrame } } } - if ( match ) - { - switch ( animEvents[i].eventType ) - { + if (match) { + switch (animEvents[i].eventType) { case AEV_SOUNDCHAN: case AEV_SOUND: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SOUND_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SOUND_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SOUND_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SOUND_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_SABER_SWING: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SABER_SWING_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SABER_SWING_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SABER_SWING_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SABER_SWING_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_SABER_SPIN: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_FOOTSTEP: // Determine probability of playing sound - //Com_Printf( "Footstep event on frame %d, even should be on frame %d, off by %d\n", frame, animEvents[i].keyFrame, frame-animEvents[i].keyFrame ); - if (!animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY]) // 100% + // Com_Printf( "Footstep event on frame %d, even should be on frame %d, off by %d\n", frame, animEvents[i].keyFrame, + // frame-animEvents[i].keyFrame ); + if (!animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_EFFECT: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_EFFECT_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_EFFECT_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_EFFECT_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_EFFECT_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_FIRE: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_FIRE_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_FIRE_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_FIRE_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_FIRE_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; @@ -1364,54 +1081,49 @@ static void CG_PlayerAnimEvents( int animFileIndex, qboolean torso, int oldFrame doEvent = qtrue; break; default: - //doEvent = qfalse;//implicit + // doEvent = qfalse;//implicit break; } // do event - if ( doEvent ) - { - CG_PlayerAnimEventDo( &cg_entities[entNum], &animEvents[i] ); + if (doEvent) { + CG_PlayerAnimEventDo(&cg_entities[entNum], &animEvents[i]); } - }// end if event matches - }// end if model matches - }// end for + } // end if event matches + } // end if model matches + } // end for } -static void CGG2_AnimEvents( centity_t *cent ) -{ - if ( !cent || !cent->gent || !cent->gent->client) - { +static void CGG2_AnimEvents(centity_t *cent) { + if (!cent || !cent->gent || !cent->gent->client) { return; } - if ( !cent->gent->ghoul2.size() ) - {//sorry, ghoul2 models only + if (!cent->gent->ghoul2.size()) { // sorry, ghoul2 models only return; } - assert(cent->gent->playerModel>=0&¢->gent->playerModelgent->ghoul2.size()); - if ( ValidAnimFileIndex( cent->gent->client->clientInfo.animFileIndex ) ) - { - int junk, curFrame=0; - float currentFrame=0, animSpeed; + assert(cent->gent->playerModel >= 0 && cent->gent->playerModel < cent->gent->ghoul2.size()); + if (ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) { + int junk, curFrame = 0; + float currentFrame = 0, animSpeed; - if (cent->gent->rootBone>=0&&gi.G2API_GetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, cg.time, ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw )) - { + if (cent->gent->rootBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, cg.time, ¤tFrame, + &junk, &junk, &junk, &animSpeed, cgs.model_draw)) { // the above may have failed, not sure what to do about it, current frame will be zero in that case - curFrame = floor( currentFrame ); + curFrame = floor(currentFrame); } - if ( curFrame != cent->gent->client->renderInfo.legsFrame ) - { - CG_PlayerAnimEvents( cent->gent->client->clientInfo.animFileIndex, qfalse, cent->gent->client->renderInfo.legsFrame, curFrame, cent->currentState.clientNum ); + if (curFrame != cent->gent->client->renderInfo.legsFrame) { + CG_PlayerAnimEvents(cent->gent->client->clientInfo.animFileIndex, qfalse, cent->gent->client->renderInfo.legsFrame, curFrame, + cent->currentState.clientNum); } cent->gent->client->renderInfo.legsFrame = curFrame; cent->pe.legs.frame = curFrame; - if (cent->gent->lowerLumbarBone>=0&& gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw ) ) - { - curFrame = floor( currentFrame ); + if (cent->gent->lowerLumbarBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, + ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw)) { + curFrame = floor(currentFrame); } - if ( curFrame != cent->gent->client->renderInfo.torsoFrame ) - { - CG_PlayerAnimEvents( cent->gent->client->clientInfo.animFileIndex, qtrue, cent->gent->client->renderInfo.torsoFrame, curFrame, cent->currentState.clientNum ); + if (curFrame != cent->gent->client->renderInfo.torsoFrame) { + CG_PlayerAnimEvents(cent->gent->client->clientInfo.animFileIndex, qtrue, cent->gent->client->renderInfo.torsoFrame, curFrame, + cent->currentState.clientNum); } cent->gent->client->renderInfo.torsoFrame = curFrame; cent->pe.torso.frame = curFrame; @@ -1431,91 +1143,65 @@ CG_UpdateAngleClamp Turn curAngle toward destAngle at angleSpeed, but stay within clampMin and Max ================== */ -static void CG_UpdateAngleClamp( float destAngle, float clampMin, float clampMax, float angleSpeed, float *curAngle, float normalAngle) -{ - float swing; - float move; - float scale; - float actualSpeed; +static void CG_UpdateAngleClamp(float destAngle, float clampMin, float clampMax, float angleSpeed, float *curAngle, float normalAngle) { + float swing; + float move; + float scale; + float actualSpeed; - swing = AngleSubtract( destAngle, *curAngle ); + swing = AngleSubtract(destAngle, *curAngle); - if(swing == 0) - {//Don't have to turn + if (swing == 0) { // Don't have to turn return; } // modify the angleSpeed depending on the delta // so it doesn't seem so linear - scale = fabs( swing ); - if (swing > 0) - { - if ( swing < clampMax * 0.25 ) - {//Pretty small way to go + scale = fabs(swing); + if (swing > 0) { + if (swing < clampMax * 0.25) { // Pretty small way to go scale = 0.25; - } - else if ( swing > clampMax * 2.0 ) - {//Way out of our range + } else if (swing > clampMax * 2.0) { // Way out of our range scale = 2.0; + } else { // Scale it smoothly + scale = swing / clampMax; } - else - {//Scale it smoothly - scale = swing/clampMax; - } - } - else// if (swing < 0) + } else // if (swing < 0) { - if ( swing > clampMin * 0.25 ) - {//Pretty small way to go + if (swing > clampMin * 0.25) { // Pretty small way to go scale = 0.5; - } - else if ( swing < clampMin * 2.0 ) - {//Way out of our range + } else if (swing < clampMin * 2.0) { // Way out of our range scale = 2.0; - } - else - {//Scale it smoothly - scale = swing/clampMin; + } else { // Scale it smoothly + scale = swing / clampMin; } } actualSpeed = scale * angleSpeed; // swing towards the destination angle - if ( swing >= 0 ) - { + if (swing >= 0) { move = cg.frametime * actualSpeed; - if ( move >= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move >= swing) { // our turnspeed is so fast, no need to swing, just match *curAngle = destAngle; + } else { + *curAngle = AngleNormalize360(*curAngle + move); } - else - { - *curAngle = AngleNormalize360( *curAngle + move ); - } - } - else if ( swing < 0 ) - { + } else if (swing < 0) { move = cg.frametime * -actualSpeed; - if ( move <= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move <= swing) { // our turnspeed is so fast, no need to swing, just match *curAngle = destAngle; - } - else - { - *curAngle = AngleNormalize180( *curAngle + move ); + } else { + *curAngle = AngleNormalize180(*curAngle + move); } } - swing = AngleSubtract( *curAngle, normalAngle ); + swing = AngleSubtract(*curAngle, normalAngle); // clamp to no more than normalAngle + tolerance - if ( swing > clampMax ) - { - *curAngle = AngleNormalize180( normalAngle + clampMax ); - } - else if ( swing < clampMin ) - { - *curAngle = AngleNormalize180( normalAngle + clampMin ); + if (swing > clampMax) { + *curAngle = AngleNormalize180(normalAngle + clampMax); + } else if (swing < clampMin) { + *curAngle = AngleNormalize180(normalAngle + clampMin); } } /* @@ -1535,107 +1221,77 @@ CG_SwingAngles locked mode (Don't turn unless you exceed the swing/clamp tolerance) ================== */ -static void CG_SwingAngles( float destAngle, - float swingTolMin, float swingTolMax, - float clampMin, float clampMax, - float angleSpeed, float *curAngle, - qboolean *turning ) -{ - float swing; - float move; - float scale; +static void CG_SwingAngles(float destAngle, float swingTolMin, float swingTolMax, float clampMin, float clampMax, float angleSpeed, float *curAngle, + qboolean *turning) { + float swing; + float move; + float scale; - swing = AngleSubtract( destAngle, *curAngle ); + swing = AngleSubtract(destAngle, *curAngle); - if(swing == 0) - {//Don't have to turn + if (swing == 0) { // Don't have to turn *turning = qfalse; - } - else - { + } else { *turning = qtrue; } - //If we're not turning, then we're done - if ( *turning == qfalse) + // If we're not turning, then we're done + if (*turning == qfalse) return; // modify the angleSpeed depending on the delta // so it doesn't seem so linear - scale = fabs( swing ); + scale = fabs(swing); - if (swing > 0) - { - if ( clampMax <= 0 ) - { + if (swing > 0) { + if (clampMax <= 0) { *curAngle = destAngle; return; } - if ( swing < swingTolMax * 0.5 ) - {//Pretty small way to go + if (swing < swingTolMax * 0.5) { // Pretty small way to go scale = 0.5; - } - else if ( scale < swingTolMax ) - {//More than halfway to go + } else if (scale < swingTolMax) { // More than halfway to go scale = 1.0; - } - else - {//Way out of our range + } else { // Way out of our range scale = 2.0; } - } - else// if (swing < 0) + } else // if (swing < 0) { - if ( clampMin >= 0 ) - { + if (clampMin >= 0) { *curAngle = destAngle; return; } - if ( swing > swingTolMin * 0.5 ) - {//Pretty small way to go + if (swing > swingTolMin * 0.5) { // Pretty small way to go scale = 0.5; - } - else if ( scale > swingTolMin ) - {//More than halfway to go + } else if (scale > swingTolMin) { // More than halfway to go scale = 1.0; - } - else - {//Way out of our range + } else { // Way out of our range scale = 2.0; } } // swing towards the destination angle - if ( swing >= 0 ) - { + if (swing >= 0) { move = cg.frametime * scale * angleSpeed; - if ( move >= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move >= swing) { // our turnspeed is so fast, no need to swing, just match move = swing; } - *curAngle = AngleNormalize360( *curAngle + move ); - } - else if ( swing < 0 ) - { + *curAngle = AngleNormalize360(*curAngle + move); + } else if (swing < 0) { move = cg.frametime * scale * -angleSpeed; - if ( move <= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move <= swing) { // our turnspeed is so fast, no need to swing, just match move = swing; } - *curAngle = AngleNormalize360( *curAngle + move ); + *curAngle = AngleNormalize360(*curAngle + move); } - // clamp to no more than tolerance - if ( swing > clampMax ) - { - *curAngle = AngleNormalize360( destAngle - (clampMax - 1) ); - } - else if ( swing < clampMin ) - { - *curAngle = AngleNormalize360( destAngle + (-clampMin - 1) ); + if (swing > clampMax) { + *curAngle = AngleNormalize360(destAngle - (clampMax - 1)); + } else if (swing < clampMin) { + *curAngle = AngleNormalize360(destAngle + (-clampMin - 1)); } } @@ -1646,9 +1302,8 @@ CG_BreathPuffs Description: Makes the player appear to have breath puffs (from the cold). Added 11/06/02 by Aurelio Reis. */ -extern vmCvar_t cg_drawBreath; -static void CG_BreathPuffs( centity_t *cent, vec3_t angles, vec3_t origin ) -{ +extern vmCvar_t cg_drawBreath; +static void CG_BreathPuffs(centity_t *cent, vec3_t angles, vec3_t origin) { gclient_t *client = cent->gent->client; /* cg_drawBreath.integer == 0 - Don't draw at all. @@ -1656,148 +1311,116 @@ static void CG_BreathPuffs( centity_t *cent, vec3_t angles, vec3_t origin ) == 2 - Draw only cold breath. == 3 - Draw only under water bubbles (when under water) */ - if ( !client - || cg_drawBreath.integer == 0 - || !cg.renderingThirdPerson - || client->ps.pm_type == PM_DEAD - || client->breathPuffTime > cg.time ) - { + if (!client || cg_drawBreath.integer == 0 || !cg.renderingThirdPerson || client->ps.pm_type == PM_DEAD || client->breathPuffTime > cg.time) { return; } // Get the head-front bolt/tag. - int bolt = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], "*head_front" ); - if ( bolt == -1 ) - { + int bolt = gi.G2API_AddBolt(¢->gent->ghoul2[cent->gent->playerModel], "*head_front"); + if (bolt == -1) { return; } vec3_t vEffectOrigin; - mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, vEffectOrigin ); + mdxaBone_t boltMatrix; + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, vEffectOrigin); - int contents = cgi_CM_PointContents( vEffectOrigin, 0 ); - if ( contents & ( CONTENTS_SLIME | CONTENTS_LAVA ) ) // If they're submerged in something bad, leave. + int contents = cgi_CM_PointContents(vEffectOrigin, 0); + if (contents & (CONTENTS_SLIME | CONTENTS_LAVA)) // If they're submerged in something bad, leave. { return; } // Show bubbles effect if we're under water. - if ( (contents & CONTENTS_WATER) && ( cg_drawBreath.integer == 1 || cg_drawBreath.integer == 3 ) ) - { - CG_PlayEffectBolted( "misc/waterbreath", cent->gent->playerModel, bolt, cent->currentState.clientNum, vEffectOrigin ); + if ((contents & CONTENTS_WATER) && (cg_drawBreath.integer == 1 || cg_drawBreath.integer == 3)) { + CG_PlayEffectBolted("misc/waterbreath", cent->gent->playerModel, bolt, cent->currentState.clientNum, vEffectOrigin); } // Draw cold breath effect. - else if ( cg_drawBreath.integer == 1 || cg_drawBreath.integer == 2 ) - { - CG_PlayEffectBolted( "misc/breath", cent->gent->playerModel, bolt, cent->currentState.clientNum, vEffectOrigin ); + else if (cg_drawBreath.integer == 1 || cg_drawBreath.integer == 2) { + CG_PlayEffectBolted("misc/breath", cent->gent->playerModel, bolt, cent->currentState.clientNum, vEffectOrigin); } // TODO: It'd be nice if they breath faster when they're more damaged or when running... - if ( gi.VoiceVolume[cent->currentState.number] > 0 ) - {//make breath when talking - client->breathPuffTime = cg.time + 300; // every 200 ms - } - else - { + if (gi.VoiceVolume[cent->currentState.number] > 0) { // make breath when talking + client->breathPuffTime = cg.time + 300; // every 200 ms + } else { client->breathPuffTime = cg.time + 3000; // every 3 seconds. } } -#define LOOK_DEFAULT_SPEED 0.15f -#define LOOK_TALKING_SPEED 0.15f +#define LOOK_DEFAULT_SPEED 0.15f +#define LOOK_TALKING_SPEED 0.15f -static qboolean CG_CheckLookTarget( centity_t *cent, vec3_t lookAngles, float *lookingSpeed ) -{ - if ( !cent->gent->ghoul2.size() ) - { - if ( !cent->gent->client->clientInfo.torsoModel || !cent->gent->client->clientInfo.headModel ) - { +static qboolean CG_CheckLookTarget(centity_t *cent, vec3_t lookAngles, float *lookingSpeed) { + if (!cent->gent->ghoul2.size()) { + if (!cent->gent->client->clientInfo.torsoModel || !cent->gent->client->clientInfo.headModel) { return qfalse; } } - //FIXME: also clamp the lookAngles based on the clamp + the existing difference between + // FIXME: also clamp the lookAngles based on the clamp + the existing difference between // headAngles and torsoAngles? But often the tag_torso is straight but the torso itself // is deformed to not face straight... sigh... - //Now calc head angle to lookTarget, if any - if ( cent->gent->client->renderInfo.lookTarget >= 0 && cent->gent->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - { - vec3_t lookDir, lookOrg = { 0.0f }, eyeOrg; - if ( cent->gent->client->renderInfo.lookMode == LM_ENT ) - { - centity_t *lookCent = &cg_entities[cent->gent->client->renderInfo.lookTarget]; - if ( lookCent && lookCent->gent ) - { - if ( lookCent->gent != cent->gent->enemy ) - {//We turn heads faster than headbob speed, but not as fast as if watching an enemy - if ( cent->gent->client->NPC_class == CLASS_ROCKETTROOPER ) - {//they look around slowly and deliberately - *lookingSpeed = LOOK_DEFAULT_SPEED*0.25f; - } - else - { + // Now calc head angle to lookTarget, if any + if (cent->gent->client->renderInfo.lookTarget >= 0 && cent->gent->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { + vec3_t lookDir, lookOrg = {0.0f}, eyeOrg; + if (cent->gent->client->renderInfo.lookMode == LM_ENT) { + centity_t *lookCent = &cg_entities[cent->gent->client->renderInfo.lookTarget]; + if (lookCent && lookCent->gent) { + if (lookCent->gent != cent->gent->enemy) { // We turn heads faster than headbob speed, but not as fast as if watching an enemy + if (cent->gent->client->NPC_class == CLASS_ROCKETTROOPER) { // they look around slowly and deliberately + *lookingSpeed = LOOK_DEFAULT_SPEED * 0.25f; + } else { *lookingSpeed = LOOK_DEFAULT_SPEED; } } - //FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? + // FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? - if ( cent->gent->client->renderInfo.lookTarget == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) - {//Special case- use cg.refdef.vieworg if looking at player and not in third person view - VectorCopy( cg.refdef.vieworg, lookOrg ); - } - else if ( lookCent->gent->client ) - { - VectorCopy( lookCent->gent->client->renderInfo.eyePoint, lookOrg ); + if (cent->gent->client->renderInfo.lookTarget == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) + { // Special case- use cg.refdef.vieworg if looking at player and not in third person view + VectorCopy(cg.refdef.vieworg, lookOrg); + } else if (lookCent->gent->client) { + VectorCopy(lookCent->gent->client->renderInfo.eyePoint, lookOrg); + } else if (lookCent->gent->s.pos.trType == TR_INTERPOLATE) { + VectorCopy(lookCent->lerpOrigin, lookOrg); + } else if (lookCent->gent->inuse && !VectorCompare(lookCent->gent->currentOrigin, vec3_origin)) { + VectorCopy(lookCent->gent->currentOrigin, lookOrg); + } else { // at origin of world + return qfalse; } - else if ( lookCent->gent->s.pos.trType == TR_INTERPOLATE ) - { - VectorCopy( lookCent->lerpOrigin, lookOrg ); - } - else if ( lookCent->gent->inuse && !VectorCompare( lookCent->gent->currentOrigin, vec3_origin ) ) - { - VectorCopy( lookCent->gent->currentOrigin, lookOrg ); - } - else - {//at origin of world - return qfalse; - } - //Look in dir of lookTarget + // Look in dir of lookTarget } - } - else if ( cent->gent->client->renderInfo.lookMode == LM_INTEREST && cent->gent->client->renderInfo.lookTarget > -1 && cent->gent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS ) - { - VectorCopy( level.interestPoints[cent->gent->client->renderInfo.lookTarget].origin, lookOrg ); - } - else - { + } else if (cent->gent->client->renderInfo.lookMode == LM_INTEREST && cent->gent->client->renderInfo.lookTarget > -1 && + cent->gent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS) { + VectorCopy(level.interestPoints[cent->gent->client->renderInfo.lookTarget].origin, lookOrg); + } else { return qfalse; } - VectorCopy( cent->gent->client->renderInfo.eyePoint, eyeOrg ); + VectorCopy(cent->gent->client->renderInfo.eyePoint, eyeOrg); - VectorSubtract( lookOrg, eyeOrg, lookDir ); + VectorSubtract(lookOrg, eyeOrg, lookDir); #if 1 - vectoangles( lookDir, lookAngles ); + vectoangles(lookDir, lookAngles); #else - //FIXME: get the angle of the head tag and account for that when finding the lookAngles- + // FIXME: get the angle of the head tag and account for that when finding the lookAngles- // so if they're lying on their back we get an accurate lookAngle... - vec3_t headDirs[3]; - vec3_t finalDir; + vec3_t headDirs[3]; + vec3_t finalDir; - AnglesToAxis( cent->gent->client->renderInfo.headAngles, headDirs ); - VectorRotate( lookDir, headDirs, finalDir ); - vectoangles( finalDir, lookAngles ); + AnglesToAxis(cent->gent->client->renderInfo.headAngles, headDirs); + VectorRotate(lookDir, headDirs, finalDir); + vectoangles(finalDir, lookAngles); #endif - for ( int i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize180( lookAngles[i] ); - cent->gent->client->renderInfo.eyeAngles[i] = AngleNormalize180( cent->gent->client->renderInfo.eyeAngles[i] ); + for (int i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize180(lookAngles[i]); + cent->gent->client->renderInfo.eyeAngles[i] = AngleNormalize180(cent->gent->client->renderInfo.eyeAngles[i]); } - AnglesSubtract( lookAngles, cent->gent->client->renderInfo.eyeAngles, lookAngles ); + AnglesSubtract(lookAngles, cent->gent->client->renderInfo.eyeAngles, lookAngles); return qtrue; } @@ -1809,50 +1432,42 @@ static qboolean CG_CheckLookTarget( centity_t *cent, vec3_t lookAngles, float *l CG_AddHeadBob ================= */ -static qboolean CG_AddHeadBob( centity_t *cent, vec3_t addTo ) -{ - renderInfo_t *renderInfo = ¢->gent->client->renderInfo; - const int volume = gi.VoiceVolume[cent->gent->s.clientNum]; - const int volChange = volume - renderInfo->lastVoiceVolume;//was *3 because voice fromLA was too low - int i; +static qboolean CG_AddHeadBob(centity_t *cent, vec3_t addTo) { + renderInfo_t *renderInfo = ¢->gent->client->renderInfo; + const int volume = gi.VoiceVolume[cent->gent->s.clientNum]; + const int volChange = volume - renderInfo->lastVoiceVolume; // was *3 because voice fromLA was too low + int i; renderInfo->lastVoiceVolume = volume; - if ( !volume ) - { + if (!volume) { // Not talking, set our target to be the normal head position - VectorClear( renderInfo->targetHeadBobAngles ); + VectorClear(renderInfo->targetHeadBobAngles); - if ( VectorLengthSquared( renderInfo->headBobAngles ) < 1.0f ) - { + if (VectorLengthSquared(renderInfo->headBobAngles) < 1.0f) { // We are close enough to being back to our normal head position, so we are done for now return qfalse; } - } - else if ( volChange > 2 ) - { + } else if (volChange > 2) { // a big positive change in volume - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { // Move our head angle target a bit - renderInfo->targetHeadBobAngles[i] += Q_flrand( -1.0 * volChange, 1.0 * volChange ); + renderInfo->targetHeadBobAngles[i] += Q_flrand(-1.0 * volChange, 1.0 * volChange); // Clamp so we don't get too out of hand - if ( renderInfo->targetHeadBobAngles[i] > 7.0f ) + if (renderInfo->targetHeadBobAngles[i] > 7.0f) renderInfo->targetHeadBobAngles[i] = 7.0f; - if ( renderInfo->targetHeadBobAngles[i] < -7.0f ) + if (renderInfo->targetHeadBobAngles[i] < -7.0f) renderInfo->targetHeadBobAngles[i] = -7.0f; } } - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { // Always try to move head angles towards our target - renderInfo->headBobAngles[i] += ( renderInfo->targetHeadBobAngles[i] - renderInfo->headBobAngles[i] ) * ( cg.frametime / 150.0f ); - if ( addTo ) - { - addTo[i] = AngleNormalize180( addTo[i] + AngleNormalize180( renderInfo->headBobAngles[i] ) ); + renderInfo->headBobAngles[i] += (renderInfo->targetHeadBobAngles[i] - renderInfo->headBobAngles[i]) * (cg.frametime / 150.0f); + if (addTo) { + addTo[i] = AngleNormalize180(addTo[i] + AngleNormalize180(renderInfo->headBobAngles[i])); } } @@ -1860,170 +1475,129 @@ static qboolean CG_AddHeadBob( centity_t *cent, vec3_t addTo ) return qtrue; } -extern float vectoyaw( const vec3_t vec ); -static qboolean CG_PlayerLegsYawFromMovement( centity_t *cent, const vec3_t velocity, float *yaw, float fwdAngle, float swingTolMin, float swingTolMax, qboolean alwaysFace ) -{ +extern float vectoyaw(const vec3_t vec); +static qboolean CG_PlayerLegsYawFromMovement(centity_t *cent, const vec3_t velocity, float *yaw, float fwdAngle, float swingTolMin, float swingTolMax, + qboolean alwaysFace) { float newAddAngle, angleDiff, turnRate = 10, addAngle = 0; - //figure out what the offset, if any, should be - if ( velocity[0] || velocity[1] ) - { - float moveYaw; - moveYaw = vectoyaw( velocity ); - addAngle = AngleDelta( cent->lerpAngles[YAW], moveYaw )*-1; - if ( addAngle > 150 || addAngle < -150 ) - { + // figure out what the offset, if any, should be + if (velocity[0] || velocity[1]) { + float moveYaw; + moveYaw = vectoyaw(velocity); + addAngle = AngleDelta(cent->lerpAngles[YAW], moveYaw) * -1; + if (addAngle > 150 || addAngle < -150) { addAngle = 0; - } - else - { - //FIXME: use actual swing/clamp tolerances - if ( addAngle > swingTolMax ) - { + } else { + // FIXME: use actual swing/clamp tolerances + if (addAngle > swingTolMax) { addAngle = swingTolMax; - } - else if ( addAngle < swingTolMin ) - { + } else if (addAngle < swingTolMin) { addAngle = swingTolMin; } - if ( cent->gent->client->ps.pm_flags&PMF_BACKWARDS_RUN ) - { + if (cent->gent->client->ps.pm_flags & PMF_BACKWARDS_RUN) { addAngle *= -1; } turnRate = 5; } - } - else if ( !alwaysFace ) - { + } else if (!alwaysFace) { return qfalse; } - if ( cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED) ) - {//using force speed - //scale up the turning speed + if (cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { // using force speed + // scale up the turning speed turnRate /= cg_timescale.value; } - //lerp the legs angle to the new angle - angleDiff = AngleDelta( cent->pe.legs.yawAngle, (*yaw+addAngle) ); - newAddAngle = angleDiff*cg.frameInterpolation*-1; - if ( fabs(newAddAngle) > fabs(angleDiff) ) - { - newAddAngle = angleDiff*-1; + // lerp the legs angle to the new angle + angleDiff = AngleDelta(cent->pe.legs.yawAngle, (*yaw + addAngle)); + newAddAngle = angleDiff * cg.frameInterpolation * -1; + if (fabs(newAddAngle) > fabs(angleDiff)) { + newAddAngle = angleDiff * -1; } - if ( newAddAngle > turnRate ) - { + if (newAddAngle > turnRate) { newAddAngle = turnRate; - } - else if ( newAddAngle < -turnRate ) - { + } else if (newAddAngle < -turnRate) { newAddAngle = -turnRate; } *yaw = cent->pe.legs.yawAngle + newAddAngle; - //Now clamp - angleDiff = AngleDelta( fwdAngle, *yaw ); - if ( angleDiff > swingTolMax ) - { + // Now clamp + angleDiff = AngleDelta(fwdAngle, *yaw); + if (angleDiff > swingTolMax) { *yaw = fwdAngle - swingTolMax; - } - else if ( angleDiff < swingTolMin ) - { + } else if (angleDiff < swingTolMin) { *yaw = fwdAngle - swingTolMin; } return qtrue; } -static void CG_ATSTLegsYaw( centity_t *cent, vec3_t trailingLegsAngles ) -{ +static void CG_ATSTLegsYaw(centity_t *cent, vec3_t trailingLegsAngles) { float ATSTLegsYaw = cent->lerpAngles[YAW]; - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &ATSTLegsYaw, cent->lerpAngles[YAW], -60, 60, qtrue ); + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &ATSTLegsYaw, cent->lerpAngles[YAW], -60, 60, qtrue); float legAngleDiff = AngleNormalize180(ATSTLegsYaw) - AngleNormalize180(cent->pe.legs.yawAngle); int legsAnim = cent->currentState.legsAnim; qboolean moving = (qboolean)!VectorCompare(cent->gent->client->ps.velocity, vec3_origin); - if ( moving || legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 || fabs(legAngleDiff) > 45 ) - {//moving or turning or beyond the turn allowance - if ( legsAnim == BOTH_STAND1 && !moving ) - {//standing - if ( legAngleDiff > 0 ) - { - NPC_SetAnim( cent->gent, SETANIM_LEGS, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( cent->gent, SETANIM_LEGS, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (moving || legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 || fabs(legAngleDiff) > 45) { // moving or turning or beyond the turn allowance + if (legsAnim == BOTH_STAND1 && !moving) { // standing + if (legAngleDiff > 0) { + NPC_SetAnim(cent->gent, SETANIM_LEGS, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(cent->gent, SETANIM_LEGS, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0 ); + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0); cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; - } - else if ( legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 ) - {//turning - legAngleDiff = AngleSubtract( ATSTLegsYaw, cent->gent->client->renderInfo.legsYaw ); + } else if (legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1) { // turning + legAngleDiff = AngleSubtract(ATSTLegsYaw, cent->gent->client->renderInfo.legsYaw); float add = 0; - if ( legAngleDiff > 50 ) - { + if (legAngleDiff > 50) { cent->pe.legs.yawAngle += legAngleDiff - 50; - } - else if ( legAngleDiff < -50 ) - { + } else if (legAngleDiff < -50) { cent->pe.legs.yawAngle += legAngleDiff + 50; } - float animLength = PM_AnimLength( cent->gent->client->clientInfo.animFileIndex, (animNumber_t)legsAnim ); - legAngleDiff *= ( animLength - cent->gent->client->ps.legsAnimTimer)/animLength; - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle+legAngleDiff+add, 0 ); - if ( !cent->gent->client->ps.legsAnimTimer ) - {//FIXME: if start turning in the middle of this, our legs pop back to the old cent->pe.legs.yawAngle... + float animLength = PM_AnimLength(cent->gent->client->clientInfo.animFileIndex, (animNumber_t)legsAnim); + legAngleDiff *= (animLength - cent->gent->client->ps.legsAnimTimer) / animLength; + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle + legAngleDiff + add, 0); + if (!cent->gent->client->ps.legsAnimTimer) { // FIXME: if start turning in the middle of this, our legs pop back to the old + // cent->pe.legs.yawAngle... cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; } - } - else - {//moving - legAngleDiff = AngleSubtract( ATSTLegsYaw, cent->pe.legs.yawAngle ); - //FIXME: framerate dependant!!! - if ( legAngleDiff > 50 ) - { + } else { // moving + legAngleDiff = AngleSubtract(ATSTLegsYaw, cent->pe.legs.yawAngle); + // FIXME: framerate dependant!!! + if (legAngleDiff > 50) { legAngleDiff -= 50; - } - else if ( legAngleDiff > 5 ) - { + } else if (legAngleDiff > 5) { legAngleDiff = 5; - } - else if ( legAngleDiff < -50 ) - { + } else if (legAngleDiff < -50) { legAngleDiff += 50; - } - else if ( legAngleDiff < -5 ) - { + } else if (legAngleDiff < -5) { legAngleDiff = -5; } legAngleDiff *= cg.frameInterpolation; - VectorSet( trailingLegsAngles, 0, AngleNormalize180(cent->pe.legs.yawAngle + legAngleDiff), 0 ); + VectorSet(trailingLegsAngles, 0, AngleNormalize180(cent->pe.legs.yawAngle + legAngleDiff), 0); cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; } cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = trailingLegsAngles[YAW]; cent->pe.legs.yawing = qtrue; - } - else - { - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0 ); + } else { + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0); cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = trailingLegsAngles[YAW]; cent->pe.legs.yawing = qfalse; } return; } -extern qboolean G_ClassHasBadBones( int NPC_class ); -extern void G_BoneOrientationsForClass( int NPC_class, const char *boneName, Eorientations *oUp, Eorientations *oRt, Eorientations *oFwd ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -static CGhoul2Info_v dummyGhoul2; -static int dummyRootBone; -static int dummyHipsBolt; -static void CG_G2ClientSpineAngles( centity_t *cent, vec3_t viewAngles, const vec3_t angles, vec3_t thoracicAngles, vec3_t ulAngles, vec3_t llAngles ) -{ - vec3_t motionBoneCorrectAngles = {0}; +extern qboolean G_ClassHasBadBones(int NPC_class); +extern void G_BoneOrientationsForClass(int NPC_class, const char *boneName, Eorientations *oUp, Eorientations *oRt, Eorientations *oFwd); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +static CGhoul2Info_v dummyGhoul2; +static int dummyRootBone; +static int dummyHipsBolt; +static void CG_G2ClientSpineAngles(centity_t *cent, vec3_t viewAngles, const vec3_t angles, vec3_t thoracicAngles, vec3_t ulAngles, vec3_t llAngles) { + vec3_t motionBoneCorrectAngles = {0}; cent->pe.torso.pitchAngle = viewAngles[PITCH]; - viewAngles[YAW] = AngleDelta( cent->lerpAngles[YAW], angles[YAW] ); + viewAngles[YAW] = AngleDelta(cent->lerpAngles[YAW], angles[YAW]); cent->pe.torso.yawAngle = viewAngles[YAW]; /* @@ -2032,177 +1606,163 @@ static void CG_G2ClientSpineAngles( centity_t *cent, vec3_t viewAngles, const ve VectorClear( thoracicAngles ); VectorClear( ulAngles ); VectorClear( llAngles ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Y, POSITIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Y, POSITIVE_Z, cgs.model_draw ); - return; + BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Y, POSITIVE_Z, cgs.model_draw + ); BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Y, POSITIVE_Z, cgs.model_draw + ); return; } */ - if ( cent->gent->client->NPC_class == CLASS_SABER_DROID ) - {//don't use lower bones - VectorClear( thoracicAngles ); - VectorClear( ulAngles ); - VectorClear( llAngles ); + if (cent->gent->client->NPC_class == CLASS_SABER_DROID) { // don't use lower bones + VectorClear(thoracicAngles); + VectorClear(ulAngles); + VectorClear(llAngles); return; } - if ( cg_motionBoneComp.integer - && !PM_FlippingAnim( cent->currentState.legsAnim ) - && !PM_SpinningSaberAnim( cent->currentState.legsAnim ) - && !PM_SpinningSaberAnim( cent->currentState.torsoAnim ) - && cent->currentState.legsAnim != cent->currentState.torsoAnim //NOTE: presumes your legs & torso are on the same frame, though they *should* be because PM_SetAnimFinal tries to keep them in synch - && !G_ClassHasBadBones( cent->gent->client->NPC_class ) )//these guys' bones are so fucked up we shouldn't even bother with this motion bone comp... - {//FIXME: no need to do this if legs and torso on are same frame - mdxaBone_t boltMatrix; - - if ( cg_motionBoneComp.integer > 2 && cent->gent->rootBone >= 0 && cent->gent->lowerLumbarBone >= 0 ) - {//expensive version - //have a local ghoul2 instance to mess with for this stuff... :/ - //remember the frame the lower is on - float upperFrame, animSpeed; - int junk; - vec3_t llFwd, llRt, destPAngles, curPAngles, tempAng; - - if ( !dummyGhoul2.size() ) - {//set it up - int dummyHModel = cgi_R_RegisterModel( "models/players/_humanoid/_humanoid.glm" ); - gi.G2API_InitGhoul2Model( dummyGhoul2, "models/players/_humanoid/_humanoid.glm", dummyHModel, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - dummyRootBone = gi.G2API_GetBoneIndex( &dummyGhoul2[0], "model_root", qtrue ); - dummyHipsBolt = gi.G2API_AddBolt( &dummyGhoul2[0], "pelvis" ); - } - - gi.G2API_GetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, &upperFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw ); - //set the dummyGhoul2 lower body to same frame as upper - gi.G2API_SetBoneAnimIndex(&dummyGhoul2[0], dummyRootBone, upperFrame, upperFrame, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, upperFrame, 0 ); - //get the dummyGhoul2 lower_lumbar orientation - gi.G2API_GetBoltMatrix( dummyGhoul2, 0, dummyHipsBolt, &boltMatrix, vec3_origin, vec3_origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, llFwd ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, llRt ); - vectoangles( llFwd, destPAngles ); - vectoangles( llRt, tempAng ); + if (cg_motionBoneComp.integer && !PM_FlippingAnim(cent->currentState.legsAnim) && !PM_SpinningSaberAnim(cent->currentState.legsAnim) && + !PM_SpinningSaberAnim(cent->currentState.torsoAnim) && + cent->currentState.legsAnim != cent->currentState.torsoAnim // NOTE: presumes your legs & torso are on the same frame, though they *should* be because + // PM_SetAnimFinal tries to keep them in synch + && !G_ClassHasBadBones(cent->gent->client->NPC_class)) // these guys' bones are so fucked up we shouldn't even bother with this motion bone comp... + { // FIXME: no need to do this if legs and torso on are same frame + mdxaBone_t boltMatrix; + + if (cg_motionBoneComp.integer > 2 && cent->gent->rootBone >= 0 && cent->gent->lowerLumbarBone >= 0) { // expensive version + // have a local ghoul2 instance to mess with for this stuff... :/ + // remember the frame the lower is on + float upperFrame, animSpeed; + int junk; + vec3_t llFwd, llRt, destPAngles, curPAngles, tempAng; + + if (!dummyGhoul2.size()) { // set it up + int dummyHModel = cgi_R_RegisterModel("models/players/_humanoid/_humanoid.glm"); + gi.G2API_InitGhoul2Model(dummyGhoul2, "models/players/_humanoid/_humanoid.glm", dummyHModel, NULL_HANDLE, NULL_HANDLE, 0, 0); + dummyRootBone = gi.G2API_GetBoneIndex(&dummyGhoul2[0], "model_root", qtrue); + dummyHipsBolt = gi.G2API_AddBolt(&dummyGhoul2[0], "pelvis"); + } + + gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, &upperFrame, &junk, &junk, &junk, + &animSpeed, cgs.model_draw); + // set the dummyGhoul2 lower body to same frame as upper + gi.G2API_SetBoneAnimIndex(&dummyGhoul2[0], dummyRootBone, upperFrame, upperFrame, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, upperFrame, 0); + // get the dummyGhoul2 lower_lumbar orientation + gi.G2API_GetBoltMatrix(dummyGhoul2, 0, dummyHipsBolt, &boltMatrix, vec3_origin, vec3_origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, llFwd); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, llRt); + vectoangles(llFwd, destPAngles); + vectoangles(llRt, tempAng); destPAngles[ROLL] = -tempAng[PITCH]; - //get my lower_lumbar - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, vec3_origin, vec3_origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, llFwd ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, llRt ); - vectoangles( llFwd, curPAngles ); - vectoangles( llRt, tempAng ); + // get my lower_lumbar + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, vec3_origin, vec3_origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, llFwd); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, llRt); + vectoangles(llFwd, curPAngles); + vectoangles(llRt, tempAng); curPAngles[ROLL] = -tempAng[PITCH]; - //get the difference - for ( int ang = 0; ang < 3; ang++ ) - { - motionBoneCorrectAngles[ang] = AngleNormalize180( AngleDelta( AngleNormalize180( destPAngles[ang] ), AngleNormalize180( curPAngles[ang]) ) ); + // get the difference + for (int ang = 0; ang < 3; ang++) { + motionBoneCorrectAngles[ang] = AngleNormalize180(AngleDelta(AngleNormalize180(destPAngles[ang]), AngleNormalize180(curPAngles[ang]))); } #ifdef _DEBUG - Com_Printf( "motion bone correction: %4.2f %4.2f %4.2f\n", motionBoneCorrectAngles[PITCH], motionBoneCorrectAngles[YAW], motionBoneCorrectAngles[ROLL] ); -#endif// _DEBUG + Com_Printf("motion bone correction: %4.2f %4.2f %4.2f\n", motionBoneCorrectAngles[PITCH], motionBoneCorrectAngles[YAW], + motionBoneCorrectAngles[ROLL]); +#endif // _DEBUG /* for ( int ang = 0; ang < 3; ang++ ) { viewAngles[ang] = AngleNormalize180( viewAngles[ang] - AngleNormalize180( destLLAngles[ang] ) ); } */ - } - else - { - //adjust for motion offset - vec3_t motionFwd, motionAngles; - - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->motionBolt, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, motionFwd ); - vectoangles( motionFwd, motionAngles ); - if ( cg_motionBoneComp.integer > 1 ) - {//do roll, too + } else { + // adjust for motion offset + vec3_t motionFwd, motionAngles; + + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->motionBolt, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, motionFwd); + vectoangles(motionFwd, motionAngles); + if (cg_motionBoneComp.integer > 1) { // do roll, too vec3_t motionRt, tempAng; - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, motionRt ); - vectoangles( motionRt, tempAng ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, motionRt); + vectoangles(motionRt, tempAng); motionAngles[ROLL] = -tempAng[PITCH]; } - for ( int ang = 0; ang < 3; ang++ ) - { - viewAngles[ang] = AngleNormalize180( viewAngles[ang] - AngleNormalize180( motionAngles[ang] ) ); + for (int ang = 0; ang < 3; ang++) { + viewAngles[ang] = AngleNormalize180(viewAngles[ang] - AngleNormalize180(motionAngles[ang])); } } } - //distribute the angles differently up the spine - //NOTE: each of these distributions must add up to 1.0f - if ( cent->gent->client->NPC_class == CLASS_HAZARD_TROOPER ) - {//only uses lower_lumbar and upper_lumbar to look around - VectorClear( thoracicAngles ); - ulAngles[PITCH] = viewAngles[PITCH]*0.50f; - llAngles[PITCH] = viewAngles[PITCH]*0.50f+motionBoneCorrectAngles[PITCH]; + // distribute the angles differently up the spine + // NOTE: each of these distributions must add up to 1.0f + if (cent->gent->client->NPC_class == CLASS_HAZARD_TROOPER) { // only uses lower_lumbar and upper_lumbar to look around + VectorClear(thoracicAngles); + ulAngles[PITCH] = viewAngles[PITCH] * 0.50f; + llAngles[PITCH] = viewAngles[PITCH] * 0.50f + motionBoneCorrectAngles[PITCH]; - ulAngles[YAW] = viewAngles[YAW]*0.45f; - llAngles[YAW] = viewAngles[YAW]*0.55f+motionBoneCorrectAngles[YAW]; + ulAngles[YAW] = viewAngles[YAW] * 0.45f; + llAngles[YAW] = viewAngles[YAW] * 0.55f + motionBoneCorrectAngles[YAW]; - ulAngles[ROLL] = viewAngles[ROLL]*0.45f; - llAngles[ROLL] = viewAngles[ROLL]*0.55f+motionBoneCorrectAngles[ROLL]; - } - else if ( cent->gent->client->NPC_class == CLASS_ASSASSIN_DROID ) - {//each bone has only 1 axis of rotation! - //upper lumbar does not pitch - thoracicAngles[PITCH] = viewAngles[PITCH]*0.40f; + ulAngles[ROLL] = viewAngles[ROLL] * 0.45f; + llAngles[ROLL] = viewAngles[ROLL] * 0.55f + motionBoneCorrectAngles[ROLL]; + } else if (cent->gent->client->NPC_class == CLASS_ASSASSIN_DROID) { // each bone has only 1 axis of rotation! + // upper lumbar does not pitch + thoracicAngles[PITCH] = viewAngles[PITCH] * 0.40f; ulAngles[PITCH] = 0.0f; - llAngles[PITCH] = viewAngles[PITCH]*0.60f+motionBoneCorrectAngles[PITCH]; - //only upper lumbar yaws + llAngles[PITCH] = viewAngles[PITCH] * 0.60f + motionBoneCorrectAngles[PITCH]; + // only upper lumbar yaws thoracicAngles[YAW] = 0.0f; ulAngles[YAW] = viewAngles[YAW]; llAngles[YAW] = motionBoneCorrectAngles[YAW]; - //no bone is capable of rolling + // no bone is capable of rolling thoracicAngles[ROLL] = 0.0f; ulAngles[ROLL] = 0.0f; llAngles[ROLL] = motionBoneCorrectAngles[ROLL]; - } - else - {//use all 3 bones - thoracicAngles[PITCH] = viewAngles[PITCH]*0.20f; - ulAngles[PITCH] = viewAngles[PITCH]*0.40f; - llAngles[PITCH] = viewAngles[PITCH]*0.40f+motionBoneCorrectAngles[PITCH]; + } else { // use all 3 bones + thoracicAngles[PITCH] = viewAngles[PITCH] * 0.20f; + ulAngles[PITCH] = viewAngles[PITCH] * 0.40f; + llAngles[PITCH] = viewAngles[PITCH] * 0.40f + motionBoneCorrectAngles[PITCH]; - thoracicAngles[YAW] = viewAngles[YAW]*0.20f; - ulAngles[YAW] = viewAngles[YAW]*0.35f; - llAngles[YAW] = viewAngles[YAW]*0.45f+motionBoneCorrectAngles[YAW]; + thoracicAngles[YAW] = viewAngles[YAW] * 0.20f; + ulAngles[YAW] = viewAngles[YAW] * 0.35f; + llAngles[YAW] = viewAngles[YAW] * 0.45f + motionBoneCorrectAngles[YAW]; - thoracicAngles[ROLL] = viewAngles[ROLL]*0.20f; - ulAngles[ROLL] = viewAngles[ROLL]*0.35f; - llAngles[ROLL] = viewAngles[ROLL]*0.45f+motionBoneCorrectAngles[ROLL]; + thoracicAngles[ROLL] = viewAngles[ROLL] * 0.20f; + ulAngles[ROLL] = viewAngles[ROLL] * 0.35f; + llAngles[ROLL] = viewAngles[ROLL] * 0.45f + motionBoneCorrectAngles[ROLL]; } - if ( G_IsRidingVehicle( cent->gent ) )// && type == VH_SPEEDER ? - {//aim torso forward too + if (G_IsRidingVehicle(cent->gent)) // && type == VH_SPEEDER ? + { // aim torso forward too ulAngles[YAW] = llAngles[YAW] = 0; // Only if they have weapon can they pitch forward/back. - if ( cent->gent->client->ps.weapon == WP_NONE || cent->gent->client->ps.weapon == WP_SABER ) - { + if (cent->gent->client->ps.weapon == WP_NONE || cent->gent->client->ps.weapon == WP_SABER) { ulAngles[PITCH] = llAngles[PITCH] = 0; } } - //thoracic is added modified again by neckAngle calculations, so don't set it until then - if ( G_ClassHasBadBones( cent->gent->client->NPC_class ) ) - { + // thoracic is added modified again by neckAngle calculations, so don't set it until then + if (G_ClassHasBadBones(cent->gent->client->NPC_class)) { Eorientations oUp, oRt, oFwd; - if ( cent->gent->client->NPC_class == CLASS_RANCOR ) - { + if (cent->gent->client->NPC_class == CLASS_RANCOR) { llAngles[YAW] = llAngles[ROLL] = 0.0f; ulAngles[YAW] = ulAngles[ROLL] = 0.0f; } - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); - } - else - { - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + } else { + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); } } -static void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, vec3_t headClampMinAngles, vec3_t headClampMaxAngles ) -{ +static void CG_G2ClientNeckAngles(centity_t *cent, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, + vec3_t headClampMinAngles, vec3_t headClampMaxAngles) { /* if ( G_ClassHasBadBones( cent->gent->client->NPC_class ) ) {//don't use lower bones @@ -2215,101 +1775,74 @@ static void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec return; } */ - if ( cent->gent->client->NPC_class == CLASS_HAZARD_TROOPER ) - {//don't use upper bones + if (cent->gent->client->NPC_class == CLASS_HAZARD_TROOPER) { // don't use upper bones return; } - vec3_t lA; - VectorCopy( lookAngles, lA ); - //clamp the headangles (which should now be relative to the cervical (neck) angles - if ( lA[PITCH] < headClampMinAngles[PITCH] ) - { + vec3_t lA; + VectorCopy(lookAngles, lA); + // clamp the headangles (which should now be relative to the cervical (neck) angles + if (lA[PITCH] < headClampMinAngles[PITCH]) { lA[PITCH] = headClampMinAngles[PITCH]; - } - else if ( lA[PITCH] > headClampMaxAngles[PITCH] ) - { + } else if (lA[PITCH] > headClampMaxAngles[PITCH]) { lA[PITCH] = headClampMaxAngles[PITCH]; } - if ( lA[YAW] < headClampMinAngles[YAW] ) - { + if (lA[YAW] < headClampMinAngles[YAW]) { lA[YAW] = headClampMinAngles[YAW]; - } - else if ( lA[YAW] > headClampMaxAngles[YAW] ) - { + } else if (lA[YAW] > headClampMaxAngles[YAW]) { lA[YAW] = headClampMaxAngles[YAW]; } - if ( lA[ROLL] < headClampMinAngles[ROLL] ) - { + if (lA[ROLL] < headClampMinAngles[ROLL]) { lA[ROLL] = headClampMinAngles[ROLL]; - } - else if ( lA[ROLL] > headClampMaxAngles[ROLL] ) - { + } else if (lA[ROLL] > headClampMaxAngles[ROLL]) { lA[ROLL] = headClampMaxAngles[ROLL]; } - //split it up between the neck and cranium - if ( cent->gent->client->NPC_class == CLASS_ASSASSIN_DROID ) - {//each bone has only 1 axis of rotation! - //thoracic only pitches, split with cervical - if ( thoracicAngles[PITCH] ) - {//already been set above, blend them + // split it up between the neck and cranium + if (cent->gent->client->NPC_class == CLASS_ASSASSIN_DROID) { // each bone has only 1 axis of rotation! + // thoracic only pitches, split with cervical + if (thoracicAngles[PITCH]) { // already been set above, blend them thoracicAngles[PITCH] = (thoracicAngles[PITCH] + (lA[PITCH] * 0.5f)) * 0.5f; - } - else - { + } else { thoracicAngles[PITCH] = lA[PITCH] * 0.5f; } thoracicAngles[YAW] = thoracicAngles[ROLL] = 0.0f; - //cervical only pitches, split with thoracis + // cervical only pitches, split with thoracis neckAngles[PITCH] = lA[PITCH] * 0.5f; neckAngles[YAW] = 0.0f; neckAngles[ROLL] = 0.0f; - //cranium only yaws + // cranium only yaws headAngles[PITCH] = 0.0f; headAngles[YAW] = lA[YAW]; headAngles[ROLL] = 0.0f; - //no bones roll - } - else if ( cent->gent->client->NPC_class == CLASS_SABER_DROID ) - {//each bone has only 1 axis of rotation! - //no thoracic - VectorClear( thoracicAngles ); - //cervical only yaws + // no bones roll + } else if (cent->gent->client->NPC_class == CLASS_SABER_DROID) { // each bone has only 1 axis of rotation! + // no thoracic + VectorClear(thoracicAngles); + // cervical only yaws neckAngles[PITCH] = 0.0f; neckAngles[YAW] = lA[YAW]; neckAngles[ROLL] = 0.0f; - //cranium only pitches + // cranium only pitches headAngles[PITCH] = lA[PITCH]; headAngles[YAW] = 0.0f; headAngles[ROLL] = 0.0f; - //none of the bones roll - } - else - { - if ( thoracicAngles[PITCH] ) - {//already been set above, blend them + // none of the bones roll + } else { + if (thoracicAngles[PITCH]) { // already been set above, blend them thoracicAngles[PITCH] = (thoracicAngles[PITCH] + (lA[PITCH] * 0.4f)) * 0.5f; - } - else - { + } else { thoracicAngles[PITCH] = lA[PITCH] * 0.4f; } - if ( thoracicAngles[YAW] ) - {//already been set above, blend them + if (thoracicAngles[YAW]) { // already been set above, blend them thoracicAngles[YAW] = (thoracicAngles[YAW] + (lA[YAW] * 0.1f)) * 0.5f; - } - else - { + } else { thoracicAngles[YAW] = lA[YAW] * 0.1f; } - if ( thoracicAngles[ROLL] ) - {//already been set above, blend them + if (thoracicAngles[ROLL]) { // already been set above, blend them thoracicAngles[ROLL] = (thoracicAngles[ROLL] + (lA[ROLL] * 0.1f)) * 0.5f; - } - else - { + } else { thoracicAngles[ROLL] = lA[ROLL] * 0.1f; } @@ -2322,13 +1855,12 @@ static void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec headAngles[ROLL] = lA[ROLL] * 0.6f; } - if ( G_IsRidingVehicle( cent->gent ) )// && type == VH_SPEEDER ? - {//aim torso forward too + if (G_IsRidingVehicle(cent->gent)) // && type == VH_SPEEDER ? + { // aim torso forward too headAngles[YAW] = neckAngles[YAW] = thoracicAngles[YAW] = 0; // Only if they have weapon can they pitch forward/back. - if ( cent->gent->client->ps.weapon == WP_NONE || cent->gent->client->ps.weapon == WP_SABER ) - { + if (cent->gent->client->ps.weapon == WP_NONE || cent->gent->client->ps.weapon == WP_SABER) { thoracicAngles[PITCH] = 0; } @@ -2351,8 +1883,8 @@ static void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec mdxaBone_t boltMatrix; vec3_t boltAngles; - gi.G2API_GetBoltMatrix( actor->ghoul2, actor->playerModel, actor->humerusRBone, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, actorPos ); + gi.G2API_GetBoltMatrix( actor->ghoul2, actor->playerModel, actor->humerusRBone, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, cgs.model_draw, + cent->currentState.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, actorPos ); VectorSubtract(actorPos, actor->enemy->currentOrigin, toEnemy); toEnemyDistance = VectorNormalize(toEnemy); @@ -2374,89 +1906,71 @@ static void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec } }*/ } - if ( G_ClassHasBadBones( cent->gent->client->NPC_class ) ) - { + if (G_ClassHasBadBones(cent->gent->client->NPC_class)) { Eorientations oUp, oRt, oFwd; - if ( cent->gent->client->NPC_class != CLASS_RANCOR ) - {//Rancor doesn't use cranium and cervical - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw ); - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "cervical", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); - } - if ( cent->gent->client->NPC_class != CLASS_SABER_DROID ) - {//saber droid doesn't use thoracic - if ( cent->gent->client->NPC_class == CLASS_RANCOR ) - { + if (cent->gent->client->NPC_class != CLASS_RANCOR) { // Rancor doesn't use cranium and cervical + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "cervical", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + } + if (cent->gent->client->NPC_class != CLASS_SABER_DROID) { // saber droid doesn't use thoracic + if (cent->gent->client->NPC_class == CLASS_RANCOR) { thoracicAngles[YAW] = thoracicAngles[ROLL] = 0.0f; } - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); } - } - else - { - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + } else { + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); } } -static void CG_UpdateLookAngles( centity_t *cent, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, float maxRoll ) -{ - if ( !cent || !cent->gent || !cent->gent->client ) - { +static void CG_UpdateLookAngles(centity_t *cent, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, + float maxRoll) { + if (!cent || !cent->gent || !cent->gent->client) { return; } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { - //clamp so don't get "Exorcist" effect - if ( lookAngles[PITCH] > maxPitch ) - { + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { + // clamp so don't get "Exorcist" effect + if (lookAngles[PITCH] > maxPitch) { lookAngles[PITCH] = maxPitch; - } - else if ( lookAngles[PITCH] < minPitch ) - { + } else if (lookAngles[PITCH] < minPitch) { lookAngles[PITCH] = minPitch; } - if ( lookAngles[YAW] > maxYaw ) - { + if (lookAngles[YAW] > maxYaw) { lookAngles[YAW] = maxYaw; - } - else if ( lookAngles[YAW] < minYaw ) - { + } else if (lookAngles[YAW] < minYaw) { lookAngles[YAW] = minYaw; } - if ( lookAngles[ROLL] > maxRoll ) - { + if (lookAngles[ROLL] > maxRoll) { lookAngles[ROLL] = maxRoll; - } - else if ( lookAngles[ROLL] < minRoll ) - { + } else if (lookAngles[ROLL] < minRoll) { lookAngles[ROLL] = minRoll; } - //slowly lerp to this new value - //Remember last headAngles - vec3_t oldLookAngles; - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles ); + // slowly lerp to this new value + // Remember last headAngles + vec3_t oldLookAngles; + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles); vec3_t lookAnglesDiff; - VectorSubtract( lookAngles, oldLookAngles, lookAnglesDiff ); + VectorSubtract(lookAngles, oldLookAngles, lookAnglesDiff); - for ( int ang = 0; ang < 3; ang++ ) - { - lookAnglesDiff[ang] = AngleNormalize180( lookAnglesDiff[ang] ); + for (int ang = 0; ang < 3; ang++) { + lookAnglesDiff[ang] = AngleNormalize180(lookAnglesDiff[ang]); } - if( VectorLengthSquared( lookAnglesDiff ) ) - { - lookAngles[PITCH] = AngleNormalize180( oldLookAngles[PITCH]+(lookAnglesDiff[PITCH]*cg.frameInterpolation*lookSpeed) ); - lookAngles[YAW] = AngleNormalize180( oldLookAngles[YAW]+(lookAnglesDiff[YAW]*cg.frameInterpolation*lookSpeed) ); - lookAngles[ROLL] = AngleNormalize180( oldLookAngles[ROLL]+(lookAnglesDiff[ROLL]*cg.frameInterpolation*lookSpeed) ); + if (VectorLengthSquared(lookAnglesDiff)) { + lookAngles[PITCH] = AngleNormalize180(oldLookAngles[PITCH] + (lookAnglesDiff[PITCH] * cg.frameInterpolation * lookSpeed)); + lookAngles[YAW] = AngleNormalize180(oldLookAngles[YAW] + (lookAnglesDiff[YAW] * cg.frameInterpolation * lookSpeed)); + lookAngles[ROLL] = AngleNormalize180(oldLookAngles[ROLL] + (lookAnglesDiff[ROLL] * cg.frameInterpolation * lookSpeed)); } } - //Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); + // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); } /* @@ -2474,15 +1988,14 @@ Handles seperate torso motion =============== */ -extern int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ); -extern float PM_GetTimeScaleMod( gentity_t *gent ); -static void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) -{ - vec3_t headAngles, neckAngles, chestAngles, thoracicAngles = {0,0,0};//legsAngles, torsoAngles, - vec3_t ulAngles, llAngles; - //float speed; - //vec3_t velocity; - vec3_t lookAngles, viewAngles; +extern int PM_TurnAnimForLegsAnim(gentity_t *gent, int anim); +extern float PM_GetTimeScaleMod(gentity_t *gent); +static void CG_G2PlayerAngles(centity_t *cent, vec3_t legs[3], vec3_t angles) { + vec3_t headAngles, neckAngles, chestAngles, thoracicAngles = {0, 0, 0}; // legsAngles, torsoAngles, + vec3_t ulAngles, llAngles; + // float speed; + // vec3_t velocity; + vec3_t lookAngles, viewAngles; /* float headYawClampMin, headYawClampMax; float headPitchClampMin, headPitchClampMax; @@ -2493,150 +2006,120 @@ static void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) float legsYawSwingTolMin, legsYawSwingTolMax; float yawSpeed, maxYawSpeed, lookingSpeed; */ - float lookAngleSpeed = LOOK_TALKING_SPEED;//shut up the compiler - //float swing, scale; - //int i; - qboolean looking = qfalse, talking = qfalse; - - if ( cent->gent - && (cent->gent->flags&FL_NO_ANGLES) ) - {//flatten out all bone angles we might have been overriding + float lookAngleSpeed = LOOK_TALKING_SPEED; // shut up the compiler + // float swing, scale; + // int i; + qboolean looking = qfalse, talking = qfalse; + + if (cent->gent && (cent->gent->flags & FL_NO_ANGLES)) { // flatten out all bone angles we might have been overriding cent->lerpAngles[PITCH] = cent->lerpAngles[ROLL] = 0; - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); cent->pe.torso.pitchAngle = 0; cent->pe.torso.yawAngle = 0; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); cent->pe.legs.pitchAngle = angles[0]; cent->pe.legs.yawAngle = angles[1]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[1]; } - AnglesToAxis( angles, legs ); + AnglesToAxis(angles, legs); return; } // Dead entity - if ( cent->gent && cent->gent->health <= 0 ) - { - if ( cent->gent->hipsBone != -1 ) - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + if (cent->gent && cent->gent->health <= 0) { + if (cent->gent->hipsBone != -1) { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); cent->pe.torso.pitchAngle = 0; cent->pe.torso.yawAngle = 0; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); cent->pe.legs.pitchAngle = angles[0]; cent->pe.legs.yawAngle = angles[1]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[1]; } - AnglesToAxis( angles, legs ); + AnglesToAxis(angles, legs); return; } - if ( cent->gent && cent->gent->client - && (cent->gent->client->NPC_class != CLASS_GONK ) - && (cent->gent->client->NPC_class != CLASS_INTERROGATOR) - && (cent->gent->client->NPC_class != CLASS_SENTRY) - && (cent->gent->client->NPC_class != CLASS_PROBE ) - && (cent->gent->client->NPC_class != CLASS_R2D2 ) - && (cent->gent->client->NPC_class != CLASS_R5D2) - && (cent->gent->client->NPC_class != CLASS_ATST||!cent->gent->s.number) ) - {// If we are rendering third person, we should just force the player body to always fully face + if (cent->gent && cent->gent->client && (cent->gent->client->NPC_class != CLASS_GONK) && (cent->gent->client->NPC_class != CLASS_INTERROGATOR) && + (cent->gent->client->NPC_class != CLASS_SENTRY) && (cent->gent->client->NPC_class != CLASS_PROBE) && (cent->gent->client->NPC_class != CLASS_R2D2) && + (cent->gent->client->NPC_class != CLASS_R5D2) && + (cent->gent->client->NPC_class != CLASS_ATST || + !cent->gent->s.number)) { // If we are rendering third person, we should just force the player body to always fully face // whatever way they are looking, otherwise, you can end up with gun shots coming off of the // gun at angles that just look really wrong. - //NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso - //should pitch *some* when looking up and down... - VectorCopy( cent->lerpAngles, angles ); + // NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso + // should pitch *some* when looking up and down... + VectorCopy(cent->lerpAngles, angles); angles[PITCH] = 0; - if ( cent->gent->client ) - { - if ( cent->gent->client->NPC_class != CLASS_ATST ) - { - if ( !PM_SpinningSaberAnim( cent->currentState.legsAnim ) ) - {//don't turn legs if in a spinning saber transition - //FIXME: use actual swing/clamp tolerances? - if ( cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_InRoll( ¢->gent->client->ps ) ) - {//on the ground - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); - } - else - {//face legs to front - CG_PlayerLegsYawFromMovement( cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); + if (cent->gent->client) { + if (cent->gent->client->NPC_class != CLASS_ATST) { + if (!PM_SpinningSaberAnim(cent->currentState.legsAnim)) { // don't turn legs if in a spinning saber transition + // FIXME: use actual swing/clamp tolerances? + if (cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_InRoll(¢->gent->client->ps)) { // on the ground + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); + } else { // face legs to front + CG_PlayerLegsYawFromMovement(cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); } } } } - //VectorClear( viewAngles ); - VectorCopy( cent->lerpAngles, viewAngles ); + // VectorClear( viewAngles ); + VectorCopy(cent->lerpAngles, viewAngles); viewAngles[YAW] = viewAngles[ROLL] = 0; - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_RANCOR ) - {//rancor uses full pitch - if ( cent->gent->count ) - {//don't look up or down at enemy when he's in your hand... + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_RANCOR) { // rancor uses full pitch + if (cent->gent->count) { // don't look up or down at enemy when he's in your hand... viewAngles[PITCH] = 0.0f; - } - else if ( cent->gent->enemy ) - { - if ( cent->gent->enemy->s.solid == SOLID_BMODEL ) - {//don't look up or down at architecture? + } else if (cent->gent->enemy) { + if (cent->gent->enemy->s.solid == SOLID_BMODEL) { // don't look up or down at architecture? viewAngles[PITCH] = 0.0f; - } - else if ( cent->gent->client->ps.legsAnim == BOTH_MELEE1 ) - {//don't look up or down when smashing the ground + } else if (cent->gent->client->ps.legsAnim == BOTH_MELEE1) { // don't look up or down when smashing the ground viewAngles[PITCH] = 0.0f; - } - else - { + } else { vec3_t eDir, eAngles, lookFrom; - VectorCopy( cent->lerpOrigin, lookFrom ); - lookFrom[2] += cent->gent->maxs[2]*0.6f; - VectorSubtract( cg_entities[cent->gent->enemy->s.number].lerpOrigin, lookFrom, eDir ); - vectoangles( eDir, eAngles ); + VectorCopy(cent->lerpOrigin, lookFrom); + lookFrom[2] += cent->gent->maxs[2] * 0.6f; + VectorSubtract(cg_entities[cent->gent->enemy->s.number].lerpOrigin, lookFrom, eDir); + vectoangles(eDir, eAngles); viewAngles[PITCH] = AngleNormalize180(eAngles[0]); - if ( cent->gent->client->ps.legsAnim == BOTH_ATTACK2 ) - {//swinging at something on the ground - if ( viewAngles[PITCH] > 0.0f ) - {//don't look down + if (cent->gent->client->ps.legsAnim == BOTH_ATTACK2) { // swinging at something on the ground + if (viewAngles[PITCH] > 0.0f) { // don't look down viewAngles[PITCH] = 0.0f; } - } - else if ( cent->gent->client->ps.legsAnim == BOTH_ATTACK4 ) - {//in breath attack anim - if ( viewAngles[PITCH] > 0.0f ) - {//don't look down + } else if (cent->gent->client->ps.legsAnim == BOTH_ATTACK4) { // in breath attack anim + if (viewAngles[PITCH] > 0.0f) { // don't look down viewAngles[PITCH] = 0.0f; - } - else - {//exaggerate looking up + } else { // exaggerate looking up viewAngles[PITCH] *= 2.0f; } - } - else if ( viewAngles[PITCH] > 0.0f ) - {//reduce looking down + } else if (viewAngles[PITCH] > 0.0f) { // reduce looking down viewAngles[PITCH] *= 0.5f; } - //clamp? + // clamp? /* if ( viewAngles[PITCH] > 30.0f ) { @@ -2648,74 +2131,60 @@ static void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) } */ } - } - else - { + } else { viewAngles[PITCH] = 0.0f; } - } - else - { + } else { viewAngles[PITCH] *= 0.5; } - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); - // if ( cent->gent && !Q_stricmp( "atst", cent->gent->NPC_type ) ) - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { + // if ( cent->gent && !Q_stricmp( "atst", cent->gent->NPC_type ) ) + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { lookAngles[YAW] = 0; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - VectorCopy( viewAngles, lookAngles ); - } - else - { - if ( cg_turnAnims.integer && !in_camera && cent->gent->hipsBone >= 0 ) - { - //override the hips bone with a turn anim when turning - //and clear it when we're not... does blend from and to parent actually work? + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + VectorCopy(viewAngles, lookAngles); + } else { + if (cg_turnAnims.integer && !in_camera && cent->gent->hipsBone >= 0) { + // override the hips bone with a turn anim when turning + // and clear it when we're not... does blend from and to parent actually work? int startFrame, endFrame; - const qboolean animatingHips = gi.G2API_GetAnimRangeIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, &startFrame, &endFrame ); - - //FIXME: make legs lag behind when turning in place, only play turn anim when legs have to catch up - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); - } - else if ( VectorCompare( vec3_origin, cent->gent->client->ps.velocity ) ) - {//FIXME: because of LegsYawFromMovement, we play the turnAnims when we stop running, which looks really bad. - int turnAnim = PM_TurnAnimForLegsAnim( cent->gent, cent->gent->client->ps.legsAnim ); - if ( turnAnim != -1 && cent->gent->health > 0 ) - { + const qboolean animatingHips = + gi.G2API_GetAnimRangeIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, &startFrame, &endFrame); + + // FIXME: make legs lag behind when turning in place, only play turn anim when legs have to catch up + if (angles[YAW] == cent->pe.legs.yawAngle) { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); + } else if (VectorCompare(vec3_origin, cent->gent->client->ps.velocity)) { // FIXME: because of LegsYawFromMovement, we play the turnAnims when + // we stop running, which looks really bad. + int turnAnim = PM_TurnAnimForLegsAnim(cent->gent, cent->gent->client->ps.legsAnim); + if (turnAnim != -1 && cent->gent->health > 0) { animation_t *animations = level.knownAnimFileSets[cent->gent->client->clientInfo.animFileIndex].animations; - if ( !animatingHips || ( animations[turnAnim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again + if (!animatingHips || + (animations[turnAnim].firstFrame != startFrame)) // only set the anim if we aren't going to do the same animation again { - float animSpeed = 50.0f / animations[turnAnim].frameLerp * PM_GetTimeScaleMod( cent->gent ); + float animSpeed = 50.0f / animations[turnAnim].frameLerp * PM_GetTimeScaleMod(cent->gent); - gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, - animations[turnAnim].firstFrame, animations[turnAnim].firstFrame+animations[turnAnim].numFrames, - BONE_ANIM_OVERRIDE_LOOP/*|BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND*/, animSpeed, cg.time, -1, 100 ); + gi.G2API_SetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, animations[turnAnim].firstFrame, + animations[turnAnim].firstFrame + animations[turnAnim].numFrames, + BONE_ANIM_OVERRIDE_LOOP /*|BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND*/, animSpeed, cg.time, -1, 100); } + } else { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } - else - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); - } - } - else - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + } else { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } } - CG_G2ClientSpineAngles( cent, viewAngles, angles, thoracicAngles, ulAngles, llAngles ); + CG_G2ClientSpineAngles(cent, viewAngles, angles, thoracicAngles, ulAngles, llAngles); } - vec3_t trailingLegsAngles; - if ( cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - CG_ATSTLegsYaw( cent, trailingLegsAngles ); - AnglesToAxis( trailingLegsAngles, legs ); + vec3_t trailingLegsAngles; + if (cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + CG_ATSTLegsYaw(cent, trailingLegsAngles); + AnglesToAxis(trailingLegsAngles, legs); angles[YAW] = trailingLegsAngles[YAW]; } /* @@ -2727,201 +2196,154 @@ static void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) } */ // either riding a vehicle or we are a vehicle - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE ) - {//you are a vehicle, just use your lerpAngles which comes from m_vOrientation + if (cent->gent && cent->gent->client && + cent->gent->client->NPC_class == CLASS_VEHICLE) { // you are a vehicle, just use your lerpAngles which comes from m_vOrientation cent->pe.legs.yawing = qfalse; cent->pe.legs.yawAngle = cent->lerpAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = cent->lerpAngles[YAW]; } - AnglesToAxis( cent->lerpAngles, legs ); - if ( cent->gent->m_pVehicle ) - { - if ( cent->gent->m_pVehicle->m_pVehicleInfo ) - { - if ( cent->gent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER - || cent->gent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER ) - { - VectorCopy( cent->lerpAngles, angles ); + AnglesToAxis(cent->lerpAngles, legs); + if (cent->gent->m_pVehicle) { + if (cent->gent->m_pVehicle->m_pVehicleInfo) { + if (cent->gent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER || cent->gent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) { + VectorCopy(cent->lerpAngles, angles); } } } - } - else if ( G_IsRidingVehicle( cent->gent ) ) - {//riding a vehicle, get the vehicle's lerpAngles (which comes from m_vOrientation) + } else if (G_IsRidingVehicle(cent->gent)) { // riding a vehicle, get the vehicle's lerpAngles (which comes from m_vOrientation) cent->pe.legs.yawing = qfalse; cent->pe.legs.yawAngle = cg_entities[cent->gent->owner->s.number].lerpAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = cg_entities[cent->gent->owner->s.number].lerpAngles[YAW]; } - AnglesToAxis( cg_entities[cent->gent->owner->s.number].lerpAngles, legs ); - } - else - { + AnglesToAxis(cg_entities[cent->gent->owner->s.number].lerpAngles, legs); + } else { - //set the legs.yawing field so we play the turning anim when turning in place - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { + // set the legs.yawing field so we play the turning anim when turning in place + if (angles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = angles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[YAW]; } - if ( ((cent->gent->client->ps.eFlags&EF_FORCE_GRIPPED)||((cent->gent->client->NPC_class == CLASS_BOBAFETT||cent->gent->client->NPC_class == CLASS_ROCKETTROOPER)&¢->gent->client->moveType==MT_FLYSWIM)) - && cent->gent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { - vec3_t centFwd, centRt; - float divFactor = 1.0f; - if ( (cent->gent->client->NPC_class == CLASS_BOBAFETT||cent->gent->client->NPC_class == CLASS_ROCKETTROOPER) - && cent->gent->client->moveType == MT_FLYSWIM ) - { + if (((cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED) || + ((cent->gent->client->NPC_class == CLASS_BOBAFETT || cent->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + cent->gent->client->moveType == MT_FLYSWIM)) && + cent->gent->client->ps.groundEntityNum == ENTITYNUM_NONE) { + vec3_t centFwd, centRt; + float divFactor = 1.0f; + if ((cent->gent->client->NPC_class == CLASS_BOBAFETT || cent->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + cent->gent->client->moveType == MT_FLYSWIM) { divFactor = 3.0f; } - AngleVectors( cent->lerpAngles, centFwd, centRt, NULL ); - angles[PITCH] = AngleNormalize180( DotProduct( cent->gent->client->ps.velocity, centFwd )/(2*divFactor) ); - if ( angles[PITCH] > 90 ) - { + AngleVectors(cent->lerpAngles, centFwd, centRt, NULL); + angles[PITCH] = AngleNormalize180(DotProduct(cent->gent->client->ps.velocity, centFwd) / (2 * divFactor)); + if (angles[PITCH] > 90) { angles[PITCH] = 90; - } - else if ( angles[PITCH] < -90 ) - { + } else if (angles[PITCH] < -90) { angles[PITCH] = -90; } - angles[ROLL] = AngleNormalize180( DotProduct( cent->gent->client->ps.velocity, centRt )/(10*divFactor) ); - if ( angles[ROLL] > 90 ) - { + angles[ROLL] = AngleNormalize180(DotProduct(cent->gent->client->ps.velocity, centRt) / (10 * divFactor)); + if (angles[ROLL] > 90) { angles[ROLL] = 90; - } - else if ( angles[ROLL] < -90 ) - { + } else if (angles[ROLL] < -90) { angles[ROLL] = -90; } } - AnglesToAxis( angles, legs ); + AnglesToAxis(angles, legs); } - //clamp relative to forward of cervical bone! - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { + // clamp relative to forward of cervical bone! + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { looking = qfalse; - VectorCopy( vec3_origin, chestAngles ); - } - else - { - //look at lookTarget! - float lookingSpeed = 0.3f; - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); - //Now add head bob when talking - talking = CG_AddHeadBob( cent, lookAngles ); - - //NOTE: previously, lookAngleSpeed was always 0.25f for the player - //Figure out how fast head should be turning - if ( cent->pe.torso.yawing || cent->pe.torso.pitching ) - {//If torso is turning, we want to turn head just as fast - if ( cent->gent->NPC ) - { - lookAngleSpeed = cent->gent->NPC->stats.yawSpeed/150;//about 0.33 normally - } - else - { + VectorCopy(vec3_origin, chestAngles); + } else { + // look at lookTarget! + float lookingSpeed = 0.3f; + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); + // Now add head bob when talking + talking = CG_AddHeadBob(cent, lookAngles); + + // NOTE: previously, lookAngleSpeed was always 0.25f for the player + // Figure out how fast head should be turning + if (cent->pe.torso.yawing || cent->pe.torso.pitching) { // If torso is turning, we want to turn head just as fast + if (cent->gent->NPC) { + lookAngleSpeed = cent->gent->NPC->stats.yawSpeed / 150; // about 0.33 normally + } else { lookAngleSpeed = CG_SWINGSPEED; } - } - else if ( talking ) - {//Slow for head bobbing + } else if (talking) { // Slow for head bobbing lookAngleSpeed = LOOK_TALKING_SPEED; - } - else if ( looking ) - {//Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary + } else if (looking) { // Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary lookAngleSpeed = lookingSpeed; - } - else if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - {//Not looking, not talking, head is returning from a talking head bob, use talking speed + } else if (cent->gent->client->renderInfo.lookingDebounceTime > + cg.time) { // Not looking, not talking, head is returning from a talking head bob, use talking speed lookAngleSpeed = LOOK_TALKING_SPEED; } - if ( looking || talking ) - {//want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) - //we should have a relative look angle, normalized to 180 + if (looking || talking) { // want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) + // we should have a relative look angle, normalized to 180 cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; - } - else - { - //still have a relative look angle from above + } else { + // still have a relative look angle from above } - if ( cent->gent->client->NPC_class == CLASS_RANCOR ) - {//always use the viewAngles we calced - VectorCopy( viewAngles, lookAngles ); + if (cent->gent->client->NPC_class == CLASS_RANCOR) { // always use the viewAngles we calced + VectorCopy(viewAngles, lookAngles); } - CG_UpdateLookAngles( cent, lookAngles, lookAngleSpeed, -50.0f, 50.0f, -70.0f, 70.0f, -30.0f, 30.0f ); + CG_UpdateLookAngles(cent, lookAngles, lookAngleSpeed, -50.0f, 50.0f, -70.0f, 70.0f, -30.0f, 30.0f); } - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - VectorCopy( cent->lerpAngles, lookAngles ); + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[0] = lookAngles[2] = 0; lookAngles[YAW] -= trailingLegsAngles[YAW]; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - } - else - { - vec3_t headClampMinAngles = {-25,-55,-10}, headClampMaxAngles = {50,50,10}; - CG_G2ClientNeckAngles( cent, lookAngles, headAngles, neckAngles, thoracicAngles, headClampMinAngles, headClampMaxAngles ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); + } else { + vec3_t headClampMinAngles = {-25, -55, -10}, headClampMaxAngles = {50, 50, 10}; + CG_G2ClientNeckAngles(cent, lookAngles, headAngles, neckAngles, thoracicAngles, headClampMinAngles, headClampMaxAngles); } return; } // All other entities - else if ( cent->gent && cent->gent->client ) - { - if ( (cent->gent->client->NPC_class == CLASS_PROBE ) - || (cent->gent->client->NPC_class == CLASS_R2D2 ) - || (cent->gent->client->NPC_class == CLASS_R5D2) - || (cent->gent->client->NPC_class == CLASS_RANCOR) - || (cent->gent->client->NPC_class == CLASS_WAMPA) - || (cent->gent->client->NPC_class == CLASS_ATST) ) - { - VectorCopy( cent->lerpAngles, angles ); + else if (cent->gent && cent->gent->client) { + if ((cent->gent->client->NPC_class == CLASS_PROBE) || (cent->gent->client->NPC_class == CLASS_R2D2) || (cent->gent->client->NPC_class == CLASS_R5D2) || + (cent->gent->client->NPC_class == CLASS_RANCOR) || (cent->gent->client->NPC_class == CLASS_WAMPA) || + (cent->gent->client->NPC_class == CLASS_ATST)) { + VectorCopy(cent->lerpAngles, angles); angles[PITCH] = 0; - //FIXME: use actual swing/clamp tolerances? - if ( cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); - } - else - {//face legs to front - CG_PlayerLegsYawFromMovement( cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); + // FIXME: use actual swing/clamp tolerances? + if (cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on the ground + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); + } else { // face legs to front + CG_PlayerLegsYawFromMovement(cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); } - VectorCopy( cent->lerpAngles, viewAngles ); -// viewAngles[YAW] = viewAngles[ROLL] = 0; + VectorCopy(cent->lerpAngles, viewAngles); + // viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); lookAngles[1] = 0; - if ( cent->gent->client->NPC_class == CLASS_ATST ) - {//body pitch - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT,POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + if (cent->gent->client->NPC_class == CLASS_ATST) { // body pitch + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); } - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); - vec3_t trailingLegsAngles; - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - CG_ATSTLegsYaw( cent, trailingLegsAngles ); - AnglesToAxis( trailingLegsAngles, legs ); + vec3_t trailingLegsAngles; + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + CG_ATSTLegsYaw(cent, trailingLegsAngles); + AnglesToAxis(trailingLegsAngles, legs); } /* else if ( cent->gent->client @@ -2931,182 +2353,160 @@ static void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) AnglesToAxis( trailingLegsAngles, legs ); } */ - else - { - //FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { + else { + // FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in + // place + if (angles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = angles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[YAW]; } - AnglesToAxis( angles, legs ); - } - -// if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) -// { -// looking = qfalse; -// } -// else - { //look at lookTarget! - //FIXME: snaps to side when lets go of lookTarget... ? - float lookingSpeed = 0.3f; - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); - lookAngles[PITCH] = lookAngles[ROLL] = 0;//droids can't pitch or roll their heads - if ( looking ) - {//want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) + AnglesToAxis(angles, legs); + } + + // if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) + // { + // looking = qfalse; + // } + // else + { // look at lookTarget! + // FIXME: snaps to side when lets go of lookTarget... ? + float lookingSpeed = 0.3f; + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); + lookAngles[PITCH] = lookAngles[ROLL] = 0; // droids can't pitch or roll their heads + if (looking) { // want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; } } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { //adjust for current body orientation + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { // adjust for current body orientation lookAngles[YAW] -= cent->pe.torso.yawAngle; lookAngles[YAW] -= cent->pe.legs.yawAngle; - //normalize - lookAngles[YAW] = AngleNormalize180( lookAngles[YAW] ); - - //slowly lerp to this new value - //Remember last headAngles - vec3_t oldLookAngles; - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles ); - if( VectorCompare( oldLookAngles, lookAngles ) == qfalse ) - { - //FIXME: This clamp goes off viewAngles, - //but really should go off the tag_torso's axis[0] angles, no? - lookAngles[YAW] = oldLookAngles[YAW]+(lookAngles[YAW]-oldLookAngles[YAW])*cg.frameInterpolation*0.25; - } - //Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); - } - else - {//Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); - } - if ( cent->gent->client->NPC_class == CLASS_ATST ) - { - VectorCopy( cent->lerpAngles, lookAngles ); + // normalize + lookAngles[YAW] = AngleNormalize180(lookAngles[YAW]); + + // slowly lerp to this new value + // Remember last headAngles + vec3_t oldLookAngles; + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles); + if (VectorCompare(oldLookAngles, lookAngles) == qfalse) { + // FIXME: This clamp goes off viewAngles, + // but really should go off the tag_torso's axis[0] angles, no? + lookAngles[YAW] = oldLookAngles[YAW] + (lookAngles[YAW] - oldLookAngles[YAW]) * cg.frameInterpolation * 0.25; + } + // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); + } else { // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); + } + if (cent->gent->client->NPC_class == CLASS_ATST) { + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[0] = lookAngles[2] = 0; lookAngles[YAW] -= trailingLegsAngles[YAW]; - } - else - { + } else { lookAngles[PITCH] = lookAngles[ROLL] = 0; lookAngles[YAW] -= cent->pe.legs.yawAngle; } - if ( cent->gent->client->NPC_class == CLASS_WAMPA ) - { + if (cent->gent->client->NPC_class == CLASS_WAMPA) { Eorientations oUp, oRt, oFwd; - G_BoneOrientationsForClass( cent->gent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw ); - } - else - { - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + G_BoneOrientationsForClass(cent->gent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, cgs.model_draw); + } else { + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); } - //return; - } - else//if ( (cent->gent->client->NPC_class == CLASS_GONK ) || (cent->gent->client->NPC_class == CLASS_INTERROGATOR) || (cent->gent->client->NPC_class == CLASS_SENTRY) ) + // return; + } else // if ( (cent->gent->client->NPC_class == CLASS_GONK ) || (cent->gent->client->NPC_class == CLASS_INTERROGATOR) || (cent->gent->client->NPC_class + // == CLASS_SENTRY) ) { - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); cent->pe.torso.pitchAngle = 0; cent->pe.torso.yawAngle = 0; cent->pe.legs.pitchAngle = angles[0]; cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = angles[1]; - AnglesToAxis( angles, legs ); - //return; + AnglesToAxis(angles, legs); + // return; } } } -static void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t head[3] ) -{ - vec3_t legsAngles, torsoAngles, headAngles; - vec3_t lookAngles, viewAngles; - float headYawClampMin, headYawClampMax; - float headPitchClampMin, headPitchClampMax; - float torsoYawSwingTolMin, torsoYawSwingTolMax; - float torsoYawClampMin, torsoYawClampMax; - float torsoPitchSwingTolMin, torsoPitchSwingTolMax; - float torsoPitchClampMin, torsoPitchClampMax; - float legsYawSwingTolMin, legsYawSwingTolMax; - float maxYawSpeed, yawSpeed, lookingSpeed; - float lookAngleSpeed = LOOK_TALKING_SPEED;//shut up the compiler - float swing, scale; - int i; - qboolean looking = qfalse, talking = qfalse; +static void CG_PlayerAngles(centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t head[3]) { + vec3_t legsAngles, torsoAngles, headAngles; + vec3_t lookAngles, viewAngles; + float headYawClampMin, headYawClampMax; + float headPitchClampMin, headPitchClampMax; + float torsoYawSwingTolMin, torsoYawSwingTolMax; + float torsoYawClampMin, torsoYawClampMax; + float torsoPitchSwingTolMin, torsoPitchSwingTolMax; + float torsoPitchClampMin, torsoPitchClampMax; + float legsYawSwingTolMin, legsYawSwingTolMax; + float maxYawSpeed, yawSpeed, lookingSpeed; + float lookAngleSpeed = LOOK_TALKING_SPEED; // shut up the compiler + float swing, scale; + int i; + qboolean looking = qfalse, talking = qfalse; - if ( cg.renderingThirdPerson && cent->gent && cent->gent->s.number == 0 ) - { + if (cg.renderingThirdPerson && cent->gent && cent->gent->s.number == 0) { // If we are rendering third person, we should just force the player body to always fully face // whatever way they are looking, otherwise, you can end up with gun shots coming off of the // gun at angles that just look really wrong. - //NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso - //should pitch *some* when looking up and down... + // NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso + // should pitch *some* when looking up and down... - //VectorClear( viewAngles ); - VectorCopy( cent->lerpAngles, viewAngles ); + // VectorClear( viewAngles ); + VectorCopy(cent->lerpAngles, viewAngles); viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - AnglesToAxis( viewAngles, head ); + AnglesToAxis(viewAngles, head); viewAngles[PITCH] *= 0.75; cent->pe.torso.pitchAngle = viewAngles[PITCH]; cent->pe.torso.yawAngle = viewAngles[YAW]; - AnglesToAxis( viewAngles, torso ); + AnglesToAxis(viewAngles, torso); - VectorCopy( cent->lerpAngles, lookAngles ); + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[PITCH] = 0; - //FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place - if ( lookAngles[YAW] == cent->pe.legs.yawAngle ) - { + // FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place + if (lookAngles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } - if ( cent->gent->client->ps.velocity[0] || cent->gent->client->ps.velocity[1] ) - { - float moveYaw; - moveYaw = vectoyaw( cent->gent->client->ps.velocity ); - lookAngles[YAW] = cent->lerpAngles[YAW] + AngleDelta( cent->lerpAngles[YAW], moveYaw ); + if (cent->gent->client->ps.velocity[0] || cent->gent->client->ps.velocity[1]) { + float moveYaw; + moveYaw = vectoyaw(cent->gent->client->ps.velocity); + lookAngles[YAW] = cent->lerpAngles[YAW] + AngleDelta(cent->lerpAngles[YAW], moveYaw); } cent->pe.legs.yawAngle = lookAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = lookAngles[YAW]; } - AnglesToAxis( lookAngles, legs ); + AnglesToAxis(lookAngles, legs); return; } - if ( cent->currentState.clientNum != 0 ) - { + if (cent->currentState.clientNum != 0) { headYawClampMin = -cent->gent->client->renderInfo.headYawRangeLeft; headYawClampMax = cent->gent->client->renderInfo.headYawRangeRight; - //These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles + // These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles headPitchClampMin = -cent->gent->client->renderInfo.headPitchRangeUp; headPitchClampMax = cent->gent->client->renderInfo.headPitchRangeDown; torsoYawSwingTolMin = headYawClampMin * 0.3; torsoYawSwingTolMax = headYawClampMax * 0.3; torsoPitchSwingTolMin = headPitchClampMin * 0.5; - torsoPitchSwingTolMax = headPitchClampMax * 0.5; + torsoPitchSwingTolMax = headPitchClampMax * 0.5; torsoYawClampMin = -cent->gent->client->renderInfo.torsoYawRangeLeft; torsoYawClampMax = cent->gent->client->renderInfo.torsoYawRangeRight; torsoPitchClampMin = -cent->gent->client->renderInfo.torsoPitchRangeUp; @@ -3115,26 +2515,17 @@ static void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], v legsYawSwingTolMin = torsoYawClampMin * 0.5; legsYawSwingTolMax = torsoYawClampMax * 0.5; - if ( cent->gent && cent->gent->next_roff_time && cent->gent->next_roff_time >= cg.time ) - {//Following a roff, body must keep up with head, yaw-wise - headYawClampMin = - headYawClampMax = - torsoYawSwingTolMin = - torsoYawSwingTolMax = - torsoYawClampMin = - torsoYawClampMax = - legsYawSwingTolMin = - legsYawSwingTolMax = 0; + if (cent->gent && cent->gent->next_roff_time && cent->gent->next_roff_time >= cg.time) { // Following a roff, body must keep up with head, yaw-wise + headYawClampMin = headYawClampMax = torsoYawSwingTolMin = torsoYawSwingTolMax = torsoYawClampMin = torsoYawClampMax = legsYawSwingTolMin = + legsYawSwingTolMax = 0; } - yawSpeed = maxYawSpeed = cent->gent->NPC->stats.yawSpeed/150;//about 0.33 normally - } - else - { + yawSpeed = maxYawSpeed = cent->gent->NPC->stats.yawSpeed / 150; // about 0.33 normally + } else { headYawClampMin = -70; headYawClampMax = 70; - //These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles + // These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles headPitchClampMin = -90; headPitchClampMax = 90; @@ -3153,70 +2544,56 @@ static void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], v yawSpeed = maxYawSpeed = CG_SWINGSPEED; } - if(yawSpeed <= 0) - {//Just in case - yawSpeed = 0.5f; //was 0.33 + if (yawSpeed <= 0) { // Just in case + yawSpeed = 0.5f; // was 0.33 } lookingSpeed = yawSpeed; - VectorCopy( cent->lerpAngles, headAngles ); - headAngles[YAW] = AngleNormalize360( headAngles[YAW] ); - VectorClear( legsAngles ); - VectorClear( torsoAngles ); + VectorCopy(cent->lerpAngles, headAngles); + headAngles[YAW] = AngleNormalize360(headAngles[YAW]); + VectorClear(legsAngles); + VectorClear(torsoAngles); // --------- yaw ------------- - //Clamp and swing the legs + // Clamp and swing the legs legsAngles[YAW] = headAngles[YAW]; - if(cent->gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) - { + if (cent->gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) { cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = cent->gent->client->renderInfo.lockYaw; cent->pe.legs.yawing = qfalse; legsAngles[YAW] = cent->pe.legs.yawAngle; - } - else - { + } else { qboolean alwaysFace = qfalse; - if ( cent->gent && cent->gent->health > 0 ) - { - if ( cent->gent->enemy ) - { + if (cent->gent && cent->gent->health > 0) { + if (cent->gent->enemy) { alwaysFace = qtrue; } - if ( CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &legsAngles[YAW], headAngles[YAW], torsoYawClampMin, torsoYawClampMax, alwaysFace ) ) - { - if ( legsAngles[YAW] == cent->pe.legs.yawAngle ) - { + if (CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &legsAngles[YAW], headAngles[YAW], torsoYawClampMin, torsoYawClampMax, + alwaysFace)) { + if (legsAngles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = legsAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } - } - else - { - CG_SwingAngles( legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, ¢->pe.legs.yawing ); + } else { + CG_SwingAngles(legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, + ¢->pe.legs.yawAngle, ¢->pe.legs.yawing); legsAngles[YAW] = cent->pe.legs.yawAngle; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } } - } - else - { - CG_SwingAngles( legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, ¢->pe.legs.yawing ); + } else { + CG_SwingAngles(legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, + ¢->pe.legs.yawing); legsAngles[YAW] = cent->pe.legs.yawAngle; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } } @@ -3232,140 +2609,123 @@ static void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], v // torso // If applicable, swing the lower parts to catch up with the head - CG_SwingAngles( headAngles[YAW], torsoYawSwingTolMin, torsoYawSwingTolMax, headYawClampMin, headYawClampMax, yawSpeed, ¢->pe.torso.yawAngle, ¢->pe.torso.yawing); + CG_SwingAngles(headAngles[YAW], torsoYawSwingTolMin, torsoYawSwingTolMax, headYawClampMin, headYawClampMax, yawSpeed, ¢->pe.torso.yawAngle, + ¢->pe.torso.yawing); torsoAngles[YAW] = cent->pe.torso.yawAngle; // ---------- pitch ----------- - //As the body twists to its extents, the back tends to arch backwards - + // As the body twists to its extents, the back tends to arch backwards float dest; // only show a fraction of the pitch angle in the torso - if ( headAngles[PITCH] > 180 ) - { + if (headAngles[PITCH] > 180) { dest = (-360 + headAngles[PITCH]) * 0.75; - } - else - { + } else { dest = headAngles[PITCH] * 0.75; } - CG_SwingAngles( dest, torsoPitchSwingTolMin, torsoPitchSwingTolMax, torsoPitchClampMin, torsoPitchClampMax, 0.1f, ¢->pe.torso.pitchAngle, ¢->pe.torso.pitching ); + CG_SwingAngles(dest, torsoPitchSwingTolMin, torsoPitchSwingTolMax, torsoPitchClampMin, torsoPitchClampMax, 0.1f, ¢->pe.torso.pitchAngle, + ¢->pe.torso.pitching); torsoAngles[PITCH] = cent->pe.torso.pitchAngle; // --------- roll ------------- // pain twitch - FIXME: don't do this if you have no head (like droids?) // Maybe need to have clamp angles for roll as well as pitch and yaw? - //CG_AddPainTwitch( cent, torsoAngles ); + // CG_AddPainTwitch( cent, torsoAngles ); //----------- Special head looking --------------- - //FIXME: to clamp the head angles, figure out tag_head's offset from tag_torso and add + // FIXME: to clamp the head angles, figure out tag_head's offset from tag_torso and add // that to whatever offset we're getting here... so turning the head in an // anim that also turns the head doesn't allow the head to turn out of range. - //Start with straight ahead - VectorCopy( headAngles, viewAngles ); - VectorCopy( headAngles, lookAngles ); + // Start with straight ahead + VectorCopy(headAngles, viewAngles); + VectorCopy(headAngles, lookAngles); - //Remember last headAngles - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, headAngles ); + // Remember last headAngles + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, headAngles); - //See if we're looking at someone/thing - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); + // See if we're looking at someone/thing + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); - //Now add head bob when talking -/* if ( cent->gent->client->clientInfo.extensions ) - { - talking = CG_AddHeadBob( cent, lookAngles ); - } -*/ - //Figure out how fast head should be turning - if ( cent->pe.torso.yawing || cent->pe.torso.pitching ) - {//If torso is turning, we want to turn head just as fast + // Now add head bob when talking + /* if ( cent->gent->client->clientInfo.extensions ) + { + talking = CG_AddHeadBob( cent, lookAngles ); + } + */ + // Figure out how fast head should be turning + if (cent->pe.torso.yawing || cent->pe.torso.pitching) { // If torso is turning, we want to turn head just as fast lookAngleSpeed = yawSpeed; - } - else if ( talking ) - {//Slow for head bobbing + } else if (talking) { // Slow for head bobbing lookAngleSpeed = LOOK_TALKING_SPEED; - } - else if ( looking ) - {//Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary + } else if (looking) { // Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary lookAngleSpeed = lookingSpeed; - } - else if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - {//Not looking, not talking, head is returning from a talking head bob, use talking speed + } else if (cent->gent->client->renderInfo.lookingDebounceTime > + cg.time) { // Not looking, not talking, head is returning from a talking head bob, use talking speed lookAngleSpeed = LOOK_TALKING_SPEED; } - if ( looking || talking ) - {//Keep this type of looking for a second after stopped looking + if (looking || talking) { // Keep this type of looking for a second after stopped looking cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { - //Calc our actual desired head angles - for ( i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize360( cent->gent->client->renderInfo.headBobAngles[i] + lookAngles[i] ); + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { + // Calc our actual desired head angles + for (i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize360(cent->gent->client->renderInfo.headBobAngles[i] + lookAngles[i]); } - if( VectorCompare( headAngles, lookAngles ) == qfalse ) - { - //FIXME: This clamp goes off viewAngles, - //but really should go off the tag_torso's axis[0] angles, no? - CG_UpdateAngleClamp( lookAngles[PITCH], headPitchClampMin/1.25, headPitchClampMax/1.25, lookAngleSpeed, &headAngles[PITCH], viewAngles[PITCH] ); - CG_UpdateAngleClamp( lookAngles[YAW], headYawClampMin/1.25, headYawClampMax/1.25, lookAngleSpeed, &headAngles[YAW], viewAngles[YAW] ); - CG_UpdateAngleClamp( lookAngles[ROLL], -10, 10, lookAngleSpeed, &headAngles[ROLL], viewAngles[ROLL] ); + if (VectorCompare(headAngles, lookAngles) == qfalse) { + // FIXME: This clamp goes off viewAngles, + // but really should go off the tag_torso's axis[0] angles, no? + CG_UpdateAngleClamp(lookAngles[PITCH], headPitchClampMin / 1.25, headPitchClampMax / 1.25, lookAngleSpeed, &headAngles[PITCH], viewAngles[PITCH]); + CG_UpdateAngleClamp(lookAngles[YAW], headYawClampMin / 1.25, headYawClampMax / 1.25, lookAngleSpeed, &headAngles[YAW], viewAngles[YAW]); + CG_UpdateAngleClamp(lookAngles[ROLL], -10, 10, lookAngleSpeed, &headAngles[ROLL], viewAngles[ROLL]); } - if ( !cent->gent->enemy || cent->gent->enemy->s.number != cent->gent->client->renderInfo.lookTarget ) - { - //NOTE: Hacky, yes, I know, but necc. - //We want to turn the body to follow the lookTarget - //ONLY IF WE DON'T HAVE AN ENEMY OR OUR ENEMY IS NOT OUR LOOKTARGET - //This is the piece of code that was making the enemies not face where - //they were actually aiming. + if (!cent->gent->enemy || cent->gent->enemy->s.number != cent->gent->client->renderInfo.lookTarget) { + // NOTE: Hacky, yes, I know, but necc. + // We want to turn the body to follow the lookTarget + // ONLY IF WE DON'T HAVE AN ENEMY OR OUR ENEMY IS NOT OUR LOOKTARGET + // This is the piece of code that was making the enemies not face where + // they were actually aiming. - //Yaw change - swing = AngleSubtract( legsAngles[YAW], headAngles[YAW] ); - scale = fabs( swing ) / ( torsoYawClampMax + 0.01 ); //NOTENOTE: Some ents have a clamp of 0, which is bad for division + // Yaw change + swing = AngleSubtract(legsAngles[YAW], headAngles[YAW]); + scale = fabs(swing) / (torsoYawClampMax + 0.01); // NOTENOTE: Some ents have a clamp of 0, which is bad for division scale *= LOOK_SWING_SCALE; - torsoAngles[YAW] = legsAngles[YAW] - ( swing * scale ); + torsoAngles[YAW] = legsAngles[YAW] - (swing * scale); - //Pitch change - swing = AngleSubtract( legsAngles[PITCH], headAngles[PITCH] ); - scale = fabs( swing ) / ( torsoPitchClampMax + 0.01 ); //NOTENOTE: Some ents have a clamp of 0, which is bad for division + // Pitch change + swing = AngleSubtract(legsAngles[PITCH], headAngles[PITCH]); + scale = fabs(swing) / (torsoPitchClampMax + 0.01); // NOTENOTE: Some ents have a clamp of 0, which is bad for division scale *= LOOK_SWING_SCALE; - torsoAngles[PITCH] = legsAngles[PITCH] - ( swing * scale ); + torsoAngles[PITCH] = legsAngles[PITCH] - (swing * scale); } - } - else - {//Look straight ahead - VectorCopy( viewAngles, headAngles ); + } else { // Look straight ahead + VectorCopy(viewAngles, headAngles); } - //Remember current headAngles next time - VectorCopy( headAngles, cent->gent->client->renderInfo.lastHeadAngles ); + // Remember current headAngles next time + VectorCopy(headAngles, cent->gent->client->renderInfo.lastHeadAngles); //------------------------------------------------------------- // pull the angles back out of the hierarchial chain - AnglesSubtract( headAngles, torsoAngles, headAngles ); - AnglesSubtract( torsoAngles, legsAngles, torsoAngles ); - AnglesToAxis( legsAngles, legs ); - AnglesToAxis( torsoAngles, torso ); - AnglesToAxis( headAngles, head ); + AnglesSubtract(headAngles, torsoAngles, headAngles); + AnglesSubtract(torsoAngles, legsAngles, torsoAngles); + AnglesToAxis(legsAngles, legs); + AnglesToAxis(torsoAngles, torso); + AnglesToAxis(headAngles, head); } - //========================================================================== - /* =============== CG_TrailItem @@ -3398,75 +2758,71 @@ static void CG_TrailItem( centity_t *cent, qhandle_t hModel ) { CG_PlayerPowerups =============== */ -extern void CG_Seeker( centity_t *cent ); -static void CG_PlayerPowerups( centity_t *cent ) -{ - if ( !cent->currentState.powerups ) - { +extern void CG_Seeker(centity_t *cent); +static void CG_PlayerPowerups(centity_t *cent) { + if (!cent->currentState.powerups) { return; } -/* + /* - // quad gives a dlight - if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) { - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); - } + // quad gives a dlight + if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) { + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); + } - // redflag - if ( cent->currentState.powerups & ( 1 << PW_REDFLAG ) ) { - CG_TrailItem( cent, cgs.media.redFlagModel ); - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1, 0.2, 0.2 ); - } + // redflag + if ( cent->currentState.powerups & ( 1 << PW_REDFLAG ) ) { + CG_TrailItem( cent, cgs.media.redFlagModel ); + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1, 0.2, 0.2 ); + } - // blueflag - if ( cent->currentState.powerups & ( 1 << PW_BLUEFLAG ) ) { - CG_TrailItem( cent, cgs.media.blueFlagModel ); - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); - } -*/ + // blueflag + if ( cent->currentState.powerups & ( 1 << PW_BLUEFLAG ) ) { + CG_TrailItem( cent, cgs.media.blueFlagModel ); + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); + } + */ // invul gives a dlight -// if ( cent->currentState.powerups & ( 1 << PW_BATTLESUIT ) ) -// { -// cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.8f, 0.8f, 0.2f ); -// } + // if ( cent->currentState.powerups & ( 1 << PW_BATTLESUIT ) ) + // { + // cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.8f, 0.8f, 0.2f ); + // } // seeker coolness -/* if ( cent->currentState.powerups & ( 1 << PW_SEEKER ) ) - { -// CG_Seeker(cent); - }*/ + /* if ( cent->currentState.powerups & ( 1 << PW_SEEKER ) ) + { + // CG_Seeker(cent); + }*/ } -#define SHADOW_DISTANCE 128 -static qboolean _PlayerShadow( const vec3_t origin, const float orientation, float *const shadowPlane, const float radius, qhandle_t markShader ) { - vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; - trace_t trace; - float alpha; +#define SHADOW_DISTANCE 128 +static qboolean _PlayerShadow(const vec3_t origin, const float orientation, float *const shadowPlane, const float radius, qhandle_t markShader) { + vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; + trace_t trace; + float alpha; // send a trace down from the player to the ground - VectorCopy( origin, end ); + VectorCopy(origin, end); end[2] -= SHADOW_DISTANCE; - cgi_CM_BoxTrace( &trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID ); + cgi_CM_BoxTrace(&trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID); // no shadow if too high - if ( trace.fraction == 1.0 || (trace.startsolid && trace.allsolid) ) { + if (trace.fraction == 1.0 || (trace.startsolid && trace.allsolid)) { return qfalse; } *shadowPlane = trace.endpos[2] + 1; // no mark for stencil or projection shadows - if ( cg_shadows.integer == 1 - || (in_camera && cg_shadows.integer == 2) )//don't want stencil shadows during a cinematic + if (cg_shadows.integer == 1 || (in_camera && cg_shadows.integer == 2)) // don't want stencil shadows during a cinematic { // fade the shadow out with height alpha = 1.0 - trace.fraction; // add the mark as a temporary, so it goes directly to the renderer // without taking a spot in the cg_marks array - CG_ImpactMark( markShader, trace.endpos, trace.plane.normal, - orientation, 1,1,1,alpha, qfalse, radius, qtrue ); + CG_ImpactMark(markShader, trace.endpos, trace.plane.normal, orientation, 1, 1, 1, alpha, qfalse, radius, qtrue); } return qtrue; } @@ -3480,87 +2836,72 @@ Returns the Z component of the surface being shadowed should it return a full plane instead of a Z? =============== */ -static qboolean CG_PlayerShadow( centity_t *const cent, float *const shadowPlane ) { +static qboolean CG_PlayerShadow(centity_t *const cent, float *const shadowPlane) { *shadowPlane = 0; - if ( cg_shadows.integer == 0 ) { + if (cg_shadows.integer == 0) { return qfalse; } // no shadows when cloaked - if ( cent->currentState.powerups & ( 1 << PW_CLOAKED )) - { + if (cent->currentState.powerups & (1 << PW_CLOAKED)) { return qfalse; } - if ( cent->gent->client->NPC_class == CLASS_SAND_CREATURE ) - {//sand creatures have no shadow + if (cent->gent->client->NPC_class == CLASS_SAND_CREATURE) { // sand creatures have no shadow return qfalse; } vec3_t rootOrigin; vec3_t tempAngles; - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; - if (cent->gent->rootBone>=0 && cent->gent->ghoul2.IsValid() && cent->gent->ghoul2[0].animModelIndexOffset)//If it has an animOffset it's a cinematic anim - { //i might be running out of my bounding box, so get my root origin - mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->rootBone, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, rootOrigin ); - } - else - { - VectorCopy(cent->lerpOrigin,rootOrigin); - } - - if ( DistanceSquared( cg.refdef.vieworg, rootOrigin ) > cg_shadowCullDistance.value * cg_shadowCullDistance.value ) - { + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; + if (cent->gent->rootBone >= 0 && cent->gent->ghoul2.IsValid() && + cent->gent->ghoul2[0].animModelIndexOffset) // If it has an animOffset it's a cinematic anim + { // i might be running out of my bounding box, so get my root origin + mdxaBone_t boltMatrix; + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->rootBone, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, rootOrigin); + } else { + VectorCopy(cent->lerpOrigin, rootOrigin); + } + + if (DistanceSquared(cg.refdef.vieworg, rootOrigin) > cg_shadowCullDistance.value * cg_shadowCullDistance.value) { // Shadow is too far away, don't do any traces, don't do any marks...blah return qfalse; } - if (cent->gent->client->NPC_class == CLASS_ATST) - { + if (cent->gent->client->NPC_class == CLASS_ATST) { qboolean bShadowed; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; vec3_t sideOrigin; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 30; //fudge up a bit for coplaner + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 30; // fudge up a bit for coplaner bShadowed = _PlayerShadow(sideOrigin, 0, shadowPlane, 28, cgs.media.shadowMarkShader); - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 30; //fudge up a bit for coplaner + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 30; // fudge up a bit for coplaner bShadowed = (qboolean)(_PlayerShadow(sideOrigin, 0, shadowPlane, 28, cgs.media.shadowMarkShader) || bShadowed); - bShadowed = (qboolean)( _PlayerShadow(rootOrigin, cent->pe.legs.yawAngle, shadowPlane, 64, cgs.media.shadowMarkShader) || bShadowed); + bShadowed = (qboolean)(_PlayerShadow(rootOrigin, cent->pe.legs.yawAngle, shadowPlane, 64, cgs.media.shadowMarkShader) || bShadowed); return bShadowed; - } - else if ( cent->gent->client->NPC_class == CLASS_RANCOR ) - { + } else if (cent->gent->client->NPC_class == CLASS_RANCOR) { return _PlayerShadow(rootOrigin, cent->pe.legs.yawAngle, shadowPlane, 64, cgs.media.shadowMarkShader); - } - else - { + } else { return _PlayerShadow(rootOrigin, cent->pe.legs.yawAngle, shadowPlane, 16, cgs.media.shadowMarkShader); } - } -void CG_LandingEffect( vec3_t origin, vec3_t normal, int material ) -{ - int effectID = -1; - switch ( material ) - { +void CG_LandingEffect(vec3_t origin, vec3_t normal, int material) { + int effectID = -1; + switch (material) { case MATERIAL_MUD: effectID = cgs.effects.landingMud; break; @@ -3578,180 +2919,168 @@ void CG_LandingEffect( vec3_t origin, vec3_t normal, int material ) break; } - if ( effectID != -1 ) - { - theFxScheduler.PlayEffect( effectID, origin, normal ); + if (effectID != -1) { + theFxScheduler.PlayEffect(effectID, origin, normal); } } -#define FOOTSTEP_DISTANCE 32 -static void _PlayerFootStep( const vec3_t origin, - const vec3_t traceDir, - const float orientation, - const float radius, - centity_t *const cent, footstepType_t footStepType ) -{ - vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; - trace_t trace; - footstep_t soundType = FOOTSTEP_TOTAL; - bool bMark = false; - int effectID = -1; - //float alpha; +#define FOOTSTEP_DISTANCE 32 +static void _PlayerFootStep(const vec3_t origin, const vec3_t traceDir, const float orientation, const float radius, centity_t *const cent, + footstepType_t footStepType) { + vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; + trace_t trace; + footstep_t soundType = FOOTSTEP_TOTAL; + bool bMark = false; + int effectID = -1; + // float alpha; // send a trace down from the player to the ground - VectorCopy( origin, end ); - VectorMA( origin, FOOTSTEP_DISTANCE, traceDir, end );//was end[2] -= FOOTSTEP_DISTANCE; + VectorCopy(origin, end); + VectorMA(origin, FOOTSTEP_DISTANCE, traceDir, end); // was end[2] -= FOOTSTEP_DISTANCE; - cgi_CM_BoxTrace( &trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID ); + cgi_CM_BoxTrace(&trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID); // no shadow if too high - if ( trace.fraction >= 1.0f ) - { + if (trace.fraction >= 1.0f) { return; } - //check for foot-steppable surface flag - switch( trace.surfaceFlags & MATERIAL_MASK ) - { - case MATERIAL_MUD: - bMark = true; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_MUDRUN; - } else { - soundType = FOOTSTEP_MUDWALK; - } - effectID = cgs.effects.footstepMud; - break; - case MATERIAL_DIRT: - bMark = true; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_DIRTRUN; - } else { - soundType = FOOTSTEP_DIRTWALK; - } - effectID = cgs.effects.footstepSand; - break; - case MATERIAL_SAND: - bMark = true; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_SANDRUN; - } else { - soundType = FOOTSTEP_SANDWALK; - } - effectID = cgs.effects.footstepSand; - break; - case MATERIAL_SNOW: - bMark = true; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_SNOWRUN; - } else { - soundType = FOOTSTEP_SNOWWALK; - } - effectID = cgs.effects.footstepSnow; - break; - case MATERIAL_SHORTGRASS: - case MATERIAL_LONGGRASS: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_GRASSRUN; - } else { - soundType = FOOTSTEP_GRASSWALK; - } - break; - case MATERIAL_SOLIDMETAL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_METALRUN; - } else { - soundType = FOOTSTEP_METALWALK; - } - break; - case MATERIAL_HOLLOWMETAL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_PIPERUN; - } else { - soundType = FOOTSTEP_PIPEWALK; - } - break; - case MATERIAL_GRAVEL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_GRAVELRUN; - } else { - soundType = FOOTSTEP_GRAVELWALK; - } - effectID = cgs.effects.footstepGravel; - break; - case MATERIAL_CARPET: - case MATERIAL_FABRIC: - case MATERIAL_CANVAS: - case MATERIAL_RUBBER: - case MATERIAL_PLASTIC: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_RUGRUN; - } else { - soundType = FOOTSTEP_RUGWALK; - } - break; - case MATERIAL_SOLIDWOOD: - case MATERIAL_HOLLOWWOOD: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_WOODRUN; - } else { - soundType = FOOTSTEP_WOODWALK; - } - break; + // check for foot-steppable surface flag + switch (trace.surfaceFlags & MATERIAL_MASK) { + case MATERIAL_MUD: + bMark = true; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_MUDRUN; + } else { + soundType = FOOTSTEP_MUDWALK; + } + effectID = cgs.effects.footstepMud; + break; + case MATERIAL_DIRT: + bMark = true; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_DIRTRUN; + } else { + soundType = FOOTSTEP_DIRTWALK; + } + effectID = cgs.effects.footstepSand; + break; + case MATERIAL_SAND: + bMark = true; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_SANDRUN; + } else { + soundType = FOOTSTEP_SANDWALK; + } + effectID = cgs.effects.footstepSand; + break; + case MATERIAL_SNOW: + bMark = true; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_SNOWRUN; + } else { + soundType = FOOTSTEP_SNOWWALK; + } + effectID = cgs.effects.footstepSnow; + break; + case MATERIAL_SHORTGRASS: + case MATERIAL_LONGGRASS: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_GRASSRUN; + } else { + soundType = FOOTSTEP_GRASSWALK; + } + break; + case MATERIAL_SOLIDMETAL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_METALRUN; + } else { + soundType = FOOTSTEP_METALWALK; + } + break; + case MATERIAL_HOLLOWMETAL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_PIPERUN; + } else { + soundType = FOOTSTEP_PIPEWALK; + } + break; + case MATERIAL_GRAVEL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_GRAVELRUN; + } else { + soundType = FOOTSTEP_GRAVELWALK; + } + effectID = cgs.effects.footstepGravel; + break; + case MATERIAL_CARPET: + case MATERIAL_FABRIC: + case MATERIAL_CANVAS: + case MATERIAL_RUBBER: + case MATERIAL_PLASTIC: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_RUGRUN; + } else { + soundType = FOOTSTEP_RUGWALK; + } + break; + case MATERIAL_SOLIDWOOD: + case MATERIAL_HOLLOWWOOD: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_WOODRUN; + } else { + soundType = FOOTSTEP_WOODWALK; + } + break; - default: - //fall through - case MATERIAL_GLASS: - case MATERIAL_WATER: - case MATERIAL_FLESH: - case MATERIAL_BPGLASS: - case MATERIAL_DRYLEAVES: - case MATERIAL_GREENLEAVES: - case MATERIAL_TILES: - case MATERIAL_PLASTER: - case MATERIAL_SHATTERGLASS: - case MATERIAL_ARMOR: - case MATERIAL_COMPUTER: - - case MATERIAL_CONCRETE: - case MATERIAL_ROCK: - case MATERIAL_ICE: - case MATERIAL_MARBLE: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_STONERUN; - } else { - soundType = FOOTSTEP_STONEWALK; - } - break; + default: + // fall through + case MATERIAL_GLASS: + case MATERIAL_WATER: + case MATERIAL_FLESH: + case MATERIAL_BPGLASS: + case MATERIAL_DRYLEAVES: + case MATERIAL_GREENLEAVES: + case MATERIAL_TILES: + case MATERIAL_PLASTER: + case MATERIAL_SHATTERGLASS: + case MATERIAL_ARMOR: + case MATERIAL_COMPUTER: + + case MATERIAL_CONCRETE: + case MATERIAL_ROCK: + case MATERIAL_ICE: + case MATERIAL_MARBLE: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_STONERUN; + } else { + soundType = FOOTSTEP_STONEWALK; + } + break; } - if (soundType < FOOTSTEP_TOTAL) - { - cgi_S_StartSound( NULL, cent->currentState.clientNum, CHAN_BODY, cgs.media.footsteps[soundType][Q_irand( 0, 3)] ); + if (soundType < FOOTSTEP_TOTAL) { + cgi_S_StartSound(NULL, cent->currentState.clientNum, CHAN_BODY, cgs.media.footsteps[soundType][Q_irand(0, 3)]); } - if ( cg_footsteps.integer < 4 ) - {//debugging - 4 always does footstep effect - if ( cg_footsteps.integer < 2 ) //1 for sounds, 2 for effects, 3 for marks + if (cg_footsteps.integer < 4) { // debugging - 4 always does footstep effect + if (cg_footsteps.integer < 2) // 1 for sounds, 2 for effects, 3 for marks { return; } } - if ( effectID != -1 ) - { - theFxScheduler.PlayEffect( effectID, trace.endpos, trace.plane.normal ); + if (effectID != -1) { + theFxScheduler.PlayEffect(effectID, trace.endpos, trace.plane.normal); } - if ( cg_footsteps.integer < 4 ) - {//debugging - 4 always does footprint decal - if (!bMark || cg_footsteps.integer < 3) //1 for sounds, 2 for effects, 3 for marks + if (cg_footsteps.integer < 4) { // debugging - 4 always does footprint decal + if (!bMark || cg_footsteps.integer < 3) // 1 for sounds, 2 for effects, 3 for marks { return; } } qhandle_t footMarkShader; - switch ( footStepType ) - { + switch (footStepType) { case FOOTSTEP_HEAVY_R: footMarkShader = cgs.media.fshrMarkShader; break; @@ -3768,135 +3097,109 @@ static void _PlayerFootStep( const vec3_t origin, } // fade the shadow out with height -// alpha = 1.0 - trace.fraction; + // alpha = 1.0 - trace.fraction; // add the mark as a temporary, so it goes directly to the renderer // without taking a spot in the cg_marks array - vec3_t projNormal; - VectorCopy(trace.plane.normal,projNormal); - if (projNormal[2]>0.5f) - { + vec3_t projNormal; + VectorCopy(trace.plane.normal, projNormal); + if (projNormal[2] > 0.5f) { // footsteps will not have the correct orientation for all surfaces, so punt and set the projection to Z - projNormal[0]=0.0f; - projNormal[1]=0.0f; - projNormal[2]=1.0f; + projNormal[0] = 0.0f; + projNormal[1] = 0.0f; + projNormal[2] = 1.0f; } - CG_ImpactMark( footMarkShader, trace.endpos,projNormal, - orientation, 1,1,1, 1.0f, qfalse, radius, qfalse ); + CG_ImpactMark(footMarkShader, trace.endpos, projNormal, orientation, 1, 1, 1, 1.0f, qfalse, radius, qfalse); } -extern vmCvar_t cg_footsteps; -static void CG_PlayerFootsteps( centity_t *const cent, footstepType_t footStepType ) -{ - if ( cg_footsteps.integer == 0 ) - { +extern vmCvar_t cg_footsteps; +static void CG_PlayerFootsteps(centity_t *const cent, footstepType_t footStepType) { + if (cg_footsteps.integer == 0) { return; } - //FIXME: make this a feature of NPCs in the NPCs.cfg? Specify a footstep shader, if any? - if ( cent->gent->client->NPC_class != CLASS_ATST - && cent->gent->client->NPC_class != CLASS_CLAW - && cent->gent->client->NPC_class != CLASS_FISH - && cent->gent->client->NPC_class != CLASS_FLIER2 - && cent->gent->client->NPC_class != CLASS_GLIDER - && cent->gent->client->NPC_class != CLASS_INTERROGATOR - && cent->gent->client->NPC_class != CLASS_MURJJ - && cent->gent->client->NPC_class != CLASS_PROBE - && cent->gent->client->NPC_class != CLASS_R2D2 - && cent->gent->client->NPC_class != CLASS_R5D2 - && cent->gent->client->NPC_class != CLASS_REMOTE - && cent->gent->client->NPC_class != CLASS_SEEKER - && cent->gent->client->NPC_class != CLASS_SENTRY - && cent->gent->client->NPC_class != CLASS_SWAMP ) - { - mdxaBone_t boltMatrix; + // FIXME: make this a feature of NPCs in the NPCs.cfg? Specify a footstep shader, if any? + if (cent->gent->client->NPC_class != CLASS_ATST && cent->gent->client->NPC_class != CLASS_CLAW && cent->gent->client->NPC_class != CLASS_FISH && + cent->gent->client->NPC_class != CLASS_FLIER2 && cent->gent->client->NPC_class != CLASS_GLIDER && cent->gent->client->NPC_class != CLASS_INTERROGATOR && + cent->gent->client->NPC_class != CLASS_MURJJ && cent->gent->client->NPC_class != CLASS_PROBE && cent->gent->client->NPC_class != CLASS_R2D2 && + cent->gent->client->NPC_class != CLASS_R5D2 && cent->gent->client->NPC_class != CLASS_REMOTE && cent->gent->client->NPC_class != CLASS_SEEKER && + cent->gent->client->NPC_class != CLASS_SENTRY && cent->gent->client->NPC_class != CLASS_SWAMP) { + mdxaBone_t boltMatrix; vec3_t tempAngles, sideOrigin, footDownDir; - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; int footBolt = cent->gent->footLBolt; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_R) - { + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_R) { footBolt = cent->gent->footRBolt; } - //FIXME: get yaw orientation of the foot and use on decal - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, footBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, footDownDir ); - VectorMA( sideOrigin, -8.0f, footDownDir, sideOrigin );//was [2] += 15; //fudge up a bit for coplanar - _PlayerFootStep( sideOrigin, footDownDir, cent->pe.legs.yawAngle, 6, cent, footStepType ); + // FIXME: get yaw orientation of the foot and use on decal + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, footBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, footDownDir); + VectorMA(sideOrigin, -8.0f, footDownDir, sideOrigin); // was [2] += 15; //fudge up a bit for coplanar + _PlayerFootStep(sideOrigin, footDownDir, cent->pe.legs.yawAngle, 6, cent, footStepType); } } -static void _PlayerSplash( const vec3_t origin, const vec3_t velocity, const float radius, const int maxUp ) -{ - static vec3_t WHITE={1,1,1}; - vec3_t start, end; - trace_t trace; - int contents; +static void _PlayerSplash(const vec3_t origin, const vec3_t velocity, const float radius, const int maxUp) { + static vec3_t WHITE = {1, 1, 1}; + vec3_t start, end; + trace_t trace; + int contents; - VectorCopy( origin, end ); + VectorCopy(origin, end); end[2] -= 24; // if the feet aren't in liquid, don't make a mark // this won't handle moving water brushes, but they wouldn't draw right anyway... - contents = cgi_CM_PointContents( end, 0 ); - if ( !( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) ) - { + contents = cgi_CM_PointContents(end, 0); + if (!(contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { return; } - VectorCopy( origin, start ); - if ( maxUp < 32 ) - {//our head may actually be lower than 32 above our origin + VectorCopy(origin, start); + if (maxUp < 32) { // our head may actually be lower than 32 above our origin start[2] += maxUp; - } - else - { + } else { start[2] += 32; } // if the head isn't out of liquid, don't make a mark - contents = cgi_CM_PointContents( start, 0 ); - if ( contents & ( CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) - { + contents = cgi_CM_PointContents(start, 0); + if (contents & (CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { return; } // trace down to find the surface - cgi_CM_BoxTrace( &trace, start, end, NULL, NULL, 0, ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ); + cgi_CM_BoxTrace(&trace, start, end, NULL, NULL, 0, (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)); - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { return; } - VectorCopy( trace.endpos, end ); + VectorCopy(trace.endpos, end); end[0] += Q_flrand(-1.0f, 1.0f) * 3.0f; end[1] += Q_flrand(-1.0f, 1.0f) * 3.0f; - end[2] += 1.0f; //fudge up + end[2] += 1.0f; // fudge up - int t = VectorLengthSquared( velocity ); + int t = VectorLengthSquared(velocity); - if ( t > 8192 ) // oh, magic number + if (t > 8192) // oh, magic number { t = 8192; } - float alpha = ( t / 8192.0f ) * 0.6f + 0.2f; + float alpha = (t / 8192.0f) * 0.6f + 0.2f; - FX_AddOrientedParticle( -1, end, trace.plane.normal, NULL, NULL, - 6.0f, radius + Q_flrand(0.0f, 1.0f) * 48.0f, 0, - alpha, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - Q_flrand(0.0f, 1.0f) * 360, Q_flrand(-1.0f, 1.0f) * 6.0f, NULL, NULL, 0.0f, 0 ,0, 1200, - cgs.media.wakeMarkShader, FX_ALPHA_LINEAR | FX_SIZE_LINEAR ); + FX_AddOrientedParticle(-1, end, trace.plane.normal, NULL, NULL, 6.0f, radius + Q_flrand(0.0f, 1.0f) * 48.0f, 0, alpha, 0.0f, 0.0f, WHITE, WHITE, 0.0f, + Q_flrand(0.0f, 1.0f) * 360, Q_flrand(-1.0f, 1.0f) * 6.0f, NULL, NULL, 0.0f, 0, 0, 1200, cgs.media.wakeMarkShader, + FX_ALPHA_LINEAR | FX_SIZE_LINEAR); } /* @@ -3906,47 +3209,39 @@ CG_PlayerSplash Draw a mark at the water surface =============== */ -static void CG_PlayerSplash( centity_t *cent ) -{ - if ( !cg_shadows.integer ) - { +static void CG_PlayerSplash(centity_t *cent) { + if (!cg_shadows.integer) { return; } - if ( cent->gent && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { gclient_t *cl = cent->gent->client; - if ( cent->gent->disconnectDebounceTime < cg.time ) // can't do these expanding ripples all the time + if (cent->gent->disconnectDebounceTime < cg.time) // can't do these expanding ripples all the time { - if ( cl->NPC_class == CLASS_ATST ) - { - mdxaBone_t boltMatrix; - vec3_t tempAngles, sideOrigin; + if (cl->NPC_class == CLASS_ATST) { + mdxaBone_t boltMatrix; + vec3_t tempAngles, sideOrigin; - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 22; //fudge up a bit for coplaner - _PlayerSplash( sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2] ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 22; // fudge up a bit for coplaner + _PlayerSplash(sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2]); - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 22; //fudge up a bit for coplaner + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 22; // fudge up a bit for coplaner - _PlayerSplash( sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2] ); - } - else - { + _PlayerSplash(sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2]); + } else { // player splash mark - _PlayerSplash( cent->lerpOrigin, cl->ps.velocity, 36, cl->renderInfo.eyePoint[2] - cent->lerpOrigin[2] + 5 ); + _PlayerSplash(cent->lerpOrigin, cl->ps.velocity, 36, cl->renderInfo.eyePoint[2] - cent->lerpOrigin[2] + 5); } cent->gent->disconnectDebounceTime = cg.time + 125 + Q_flrand(0.0f, 1.0f) * 50.0f; @@ -3954,7 +3249,6 @@ static void CG_PlayerSplash( centity_t *cent ) } } - /* =============== CG_LightningBolt @@ -4035,10 +3329,9 @@ extern void FX_DEMP2_AltBeam( vec3_t start, vec3_t end, vec3_t normal, //qboolea #endif //------------------------------------------- -#define REFRACT_EFFECT_DURATION 500 -void CG_ForcePushBlur( const vec3_t org, qboolean darkSide = qfalse ); -static void CG_ForcePushRefraction( vec3_t org, centity_t *cent ) -{ +#define REFRACT_EFFECT_DURATION 500 +void CG_ForcePushBlur(const vec3_t org, qboolean darkSide = qfalse); +static void CG_ForcePushRefraction(vec3_t org, centity_t *cent) { refEntity_t ent; vec3_t ang; float scale; @@ -4046,71 +3339,56 @@ static void CG_ForcePushRefraction( vec3_t org, centity_t *cent ) float alpha; int tDif; - if (!cg_renderToTextureFX.integer) - { + if (!cg_renderToTextureFX.integer) { CG_ForcePushBlur(org); return; } - if (!cent->gent || - !cent->gent->client) - { //can only do this for player/npc's + if (!cent->gent || !cent->gent->client) { // can only do this for player/npc's return; } - if (!cent->gent->client->pushEffectFadeTime) - { //the duration for the expansion and fade + if (!cent->gent->client->pushEffectFadeTime) { // the duration for the expansion and fade cent->gent->client->pushEffectFadeTime = cg.time + REFRACT_EFFECT_DURATION; } - //closer tDif is to 0, the closer we are to - //being "done" + // closer tDif is to 0, the closer we are to + // being "done" tDif = (cent->gent->client->pushEffectFadeTime - cg.time); - if ((REFRACT_EFFECT_DURATION-tDif) < 200) - { //stop following the hand after a little and stay in a fixed spot - //save the initial spot of the effect + if ((REFRACT_EFFECT_DURATION - tDif) < 200) { // stop following the hand after a little and stay in a fixed spot + // save the initial spot of the effect VectorCopy(org, cent->gent->client->pushEffectOrigin); } - //scale from 1.0f to 0.1f then hold at 0.1 for the rest of the duration - if (cent->gent->client->ps.forcePowersActive & ( 1 << FP_PULL ) ) - { - scale = (float)(REFRACT_EFFECT_DURATION-tDif)*0.003f; - } - else - { + // scale from 1.0f to 0.1f then hold at 0.1 for the rest of the duration + if (cent->gent->client->ps.forcePowersActive & (1 << FP_PULL)) { + scale = (float)(REFRACT_EFFECT_DURATION - tDif) * 0.003f; + } else { scale = (float)(tDif)*0.003f; } - if (scale > 1.0f) - { + if (scale > 1.0f) { scale = 1.0f; - } - else if (scale < 0.2f) - { + } else if (scale < 0.2f) { scale = 0.2f; } - //start alpha at 244, fade to 10 - alpha = (float)tDif*0.488f; + // start alpha at 244, fade to 10 + alpha = (float)tDif * 0.488f; - if (alpha > 244.0f) - { + if (alpha > 244.0f) { alpha = 244.0f; - } - else if (alpha < 10.0f) - { + } else if (alpha < 10.0f) { alpha = 10.0f; } - memset( &ent, 0, sizeof( ent ) ); - ent.shaderTime = (cent->gent->client->pushEffectFadeTime-REFRACT_EFFECT_DURATION) / 1000.0f; + memset(&ent, 0, sizeof(ent)); + ent.shaderTime = (cent->gent->client->pushEffectFadeTime - REFRACT_EFFECT_DURATION) / 1000.0f; - VectorCopy( cent->gent->client->pushEffectOrigin, ent.origin ); + VectorCopy(cent->gent->client->pushEffectOrigin, ent.origin); VectorSubtract(ent.origin, cg.refdef.vieworg, ent.axis[0]); vLen = VectorLength(ent.axis[0]); - if (vLen <= 0.1f) - { // Entity is right on vieworg. quit. + if (vLen <= 0.1f) { // Entity is right on vieworg. quit. return; } @@ -4119,21 +3397,14 @@ static void CG_ForcePushRefraction( vec3_t org, centity_t *cent ) AnglesToAxis(ang, ent.axis); - //radius must be a power of 2, and is the actual captured texture size - if (vLen < 128) - { + // radius must be a power of 2, and is the actual captured texture size + if (vLen < 128) { ent.radius = 256; - } - else if (vLen < 256) - { + } else if (vLen < 256) { ent.radius = 128; - } - else if (vLen < 512) - { + } else if (vLen < 512) { ent.radius = 64; - } - else - { + } else { ent.radius = 32; } @@ -4145,20 +3416,18 @@ static void CG_ForcePushRefraction( vec3_t org, centity_t *cent ) ent.customShader = cgs.media.refractShader; ent.nonNormalizedAxes = qtrue; - //make it partially transparent so it blends with the background - ent.renderfx = (RF_DISTORTION|RF_ALPHA_FADE); + // make it partially transparent so it blends with the background + ent.renderfx = (RF_DISTORTION | RF_ALPHA_FADE); ent.shaderRGBA[0] = 255.0f; ent.shaderRGBA[1] = 255.0f; ent.shaderRGBA[2] = 255.0f; ent.shaderRGBA[3] = alpha; - - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } -void CG_ForcePushBlur( const vec3_t org, qboolean darkSide ) -{ - localEntity_t *ex; +void CG_ForcePushBlur(const vec3_t org, qboolean darkSide) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -4166,24 +3435,21 @@ void CG_ForcePushBlur( const vec3_t org, qboolean darkSide ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], 55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], 55, ex->pos.trDelta); - if ( darkSide ) - {//make it red + if (darkSide) { // make it red ex->color[0] = 60; ex->color[1] = 8; ex->color[2] = 8; - } - else - {//blue + } else { // blue ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; } - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/forcePush"); ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -4192,192 +3458,158 @@ void CG_ForcePushBlur( const vec3_t org, qboolean darkSide ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], -55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], -55, ex->pos.trDelta); - if ( darkSide ) - {//make it red + if (darkSide) { // make it red ex->color[0] = 60; ex->color[1] = 8; ex->color[2] = 8; - } - else - {//blue + } else { // blue ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; } - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/forcePush"); } -static void CG_ForcePushBodyBlur( centity_t *cent, const vec3_t origin, vec3_t tempAngles ) -{ +static void CG_ForcePushBodyBlur(centity_t *cent, const vec3_t origin, vec3_t tempAngles) { vec3_t fxOrg; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Head blur - CG_ForcePushBlur( cent->gent->client->renderInfo.eyePoint ); + CG_ForcePushBlur(cent->gent->client->renderInfo.eyePoint); // Do a torso based blur - if (cent->gent->torsoBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->torsoBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->torsoBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->torsoBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->handRBolt>=0) - { + if (cent->gent->handRBolt >= 0) { // Do a right-hand based blur - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->handLBolt>=0) - { + if (cent->gent->handLBolt >= 0) { // Do a left-hand based blur - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } // Do the knees - if (cent->gent->kneeLBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->kneeLBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->kneeRBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->kneeRBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->elbowLBolt>=0) - { + if (cent->gent->elbowLBolt >= 0) { // Do the elbows - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->elbowRBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->elbowRBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } } -static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t tempAngles, qhandle_t shader, qboolean alwaysDo = qfalse ) -{ +static void CG_ForceElectrocution(centity_t *cent, const vec3_t origin, vec3_t tempAngles, qhandle_t shader, qboolean alwaysDo = qfalse) { // Undoing for now, at least this code should compile if I ( or anyone else ) decides to work on this effect - qboolean found = qfalse; - vec3_t fxOrg, fxOrg2, dir; - vec3_t rgb = {1.0f,1.0f,1.0f}; - mdxaBone_t boltMatrix; + qboolean found = qfalse; + vec3_t fxOrg, fxOrg2, dir; + vec3_t rgb = {1.0f, 1.0f, 1.0f}; + mdxaBone_t boltMatrix; - int bolt=-1; - int iter=0; + int bolt = -1; + int iter = 0; // Pick a random start point - while (bolt<0) - { + while (bolt < 0) { int test; - if (iter>5) - { - test=iter-5; - } - else - { - test=Q_irand(0,6); + if (iter > 5) { + test = iter - 5; + } else { + test = Q_irand(0, 6); } - switch(test) - { + switch (test) { case 0: // Right Elbow - bolt=cent->gent->elbowRBolt; + bolt = cent->gent->elbowRBolt; break; case 1: // Left Hand - bolt=cent->gent->handLBolt; + bolt = cent->gent->handLBolt; break; case 2: // Right hand - bolt=cent->gent->handRBolt; + bolt = cent->gent->handRBolt; break; case 3: // Left Foot - bolt=cent->gent->footLBolt; + bolt = cent->gent->footLBolt; break; case 4: // Right foot - bolt=cent->gent->footRBolt; + bolt = cent->gent->footRBolt; break; case 5: // Torso - bolt=cent->gent->torsoBolt; + bolt = cent->gent->torsoBolt; break; case 6: default: // Left Elbow - bolt=cent->gent->elbowLBolt; + bolt = cent->gent->elbowLBolt; break; } - if (++iter==20) + if (++iter == 20) break; } - if (bolt>=0) - { - found = gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); + if (bolt >= 0) { + found = gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); } // Make sure that it's safe to even try and get these values out of the Matrix, otherwise the values could be garbage - if ( found ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, dir ); - } - else - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + if (found) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, dir); + } else { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); } // Add some fudge, makes us not normalized, but that isn't really important dir[0] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[1] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[2] += Q_flrand(-1.0f, 1.0f) * 0.4f; - } - else - { + } else { // Just use the lerp Origin and a random direction - VectorCopy( cent->lerpOrigin, fxOrg ); - VectorSet( dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f) ); // Not normalized, but who cares. - if ( cent->gent && cent->gent->client ) - { - switch ( cent->gent->client->NPC_class ) - { + VectorCopy(cent->lerpOrigin, fxOrg); + VectorSet(dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); // Not normalized, but who cares. + if (cent->gent && cent->gent->client) { + switch (cent->gent->client->NPC_class) { case CLASS_PROBE: fxOrg[2] += 50; break; @@ -4393,33 +3625,24 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t } } - VectorMA( fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2 ); + VectorMA(fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2); - trace_t tr; + trace_t tr; - CG_Trace( &tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID ); + CG_Trace(&tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f || alwaysDo ) - { - FX_AddElectricity( -1, fxOrg, tr.endpos, - 1.5f, 4.0f, 0.0f, - 1.0f, 0.5f, 0.0f, - rgb, rgb, 0.0f, - 5.5f, Q_flrand(0.0f, 1.0f) * 50 + 100, shader, FX_ALPHA_LINEAR | FX_SIZE_LINEAR | FX_BRANCH | FX_GROW | FX_TAPER, -1, -1 ); + if (tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f || alwaysDo) { + FX_AddElectricity(-1, fxOrg, tr.endpos, 1.5f, 4.0f, 0.0f, 1.0f, 0.5f, 0.0f, rgb, rgb, 0.0f, 5.5f, Q_flrand(0.0f, 1.0f) * 50 + 100, shader, + FX_ALPHA_LINEAR | FX_SIZE_LINEAR | FX_BRANCH | FX_GROW | FX_TAPER, -1, -1); } } -static void CG_BoltedEffects( centity_t *cent, const vec3_t origin, vec3_t tempAngles ) -{ - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE ) - { +static void CG_BoltedEffects(centity_t *cent, const vec3_t origin, vec3_t tempAngles) { + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE) { Vehicle_t *pVeh = cent->gent->m_pVehicle; gentity_t *parent = cent->gent; - if (pVeh->m_ulFlags&VEH_ARMORLOW - && (pVeh->m_iLastFXTime<=cg.time) - && Q_irand(0,1)==0 ) - { - pVeh->m_iLastFXTime = cg.time + 50;//Q_irand(50, 100); + if (pVeh->m_ulFlags & VEH_ARMORLOW && (pVeh->m_iLastFXTime <= cg.time) && Q_irand(0, 1) == 0) { + pVeh->m_iLastFXTime = cg.time + 50; // Q_irand(50, 100); CG_PlayEffectIDBolted(pVeh->m_pVehicleInfo->iArmorLowFX, parent->playerModel, parent->crotchBolt, parent->s.number, parent->currentOrigin); } } @@ -4432,61 +3655,54 @@ CG_PlayerCanSeeCent tests force sight level =============== */ -qboolean CG_PlayerCanSeeCent( centity_t *cent ) -{//return true if this cent is in view - //NOTE: this is similar to the func SV_PlayerCanSeeEnt in sv_snapshot - if ( (cent->currentState.eFlags&EF_FORCE_VISIBLE) ) - {//can always be seen +qboolean CG_PlayerCanSeeCent(centity_t *cent) { // return true if this cent is in view + // NOTE: this is similar to the func SV_PlayerCanSeeEnt in sv_snapshot + if ((cent->currentState.eFlags & EF_FORCE_VISIBLE)) { // can always be seen return qtrue; } - if ( g_entities[0].client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 - && cent->currentState.eType != ET_PLAYER ) - {//TEST: level 1 only sees force hints and enemies + if (g_entities[0].client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 && + cent->currentState.eType != ET_PLAYER) { // TEST: level 1 only sees force hints and enemies return qfalse; } - float dot = 0.25f;//1.0f; + float dot = 0.25f; // 1.0f; float range = 512.0f; - switch ( g_entities[0].client->ps.forcePowerLevel[FP_SEE] ) - { + switch (g_entities[0].client->ps.forcePowerLevel[FP_SEE]) { case FORCE_LEVEL_1: - //dot = 0.95f; + // dot = 0.95f; range = 1024.0f; break; case FORCE_LEVEL_2: - //dot = 0.7f; + // dot = 0.7f; range = 2048.0f; break; case FORCE_LEVEL_3: case FORCE_LEVEL_4: case FORCE_LEVEL_5: - //dot = 0.4f; + // dot = 0.4f; range = 4096.0f; break; } - vec3_t centDir, lookDir; - VectorSubtract( cent->lerpOrigin, cg.refdef.vieworg, centDir ); - float centDist = VectorNormalize( centDir ); + vec3_t centDir, lookDir; + VectorSubtract(cent->lerpOrigin, cg.refdef.vieworg, centDir); + float centDist = VectorNormalize(centDir); - if ( centDist < 128.0f ) - {//can always see them if they're really close + if (centDist < 128.0f) { // can always see them if they're really close return qtrue; } - if ( centDist > range ) - {//too far away to see them + if (centDist > range) { // too far away to see them return qfalse; } - dot += (0.99f-dot)*centDist/range;//the farther away they are, the more in front they have to be + dot += (0.99f - dot) * centDist / range; // the farther away they are, the more in front they have to be - AngleVectors( cg.refdefViewAngles, lookDir, NULL, NULL ); + AngleVectors(cg.refdefViewAngles, lookDir, NULL, NULL); - if ( DotProduct( centDir, lookDir ) < dot ) - {//not in force sight cone + if (DotProduct(centDir, lookDir) < dot) { // not in force sight cone return qfalse; } @@ -4500,23 +3716,20 @@ CG_AddForceSightShell Adds the special effect =============== */ -extern void CG_AddHealthBarEnt( int entNum ); -void CG_AddForceSightShell( refEntity_t *ent, centity_t *cent ) -{ +extern void CG_AddHealthBarEnt(int entNum); +void CG_AddForceSightShell(refEntity_t *ent, centity_t *cent) { ent->customShader = cgs.media.forceShell; ent->renderfx &= ~RF_RGB_TINT; // See through walls. - ent->renderfx |= (RF_MORELIGHT|RF_NODEPTH); + ent->renderfx |= (RF_MORELIGHT | RF_NODEPTH); - if ( (cent->currentState.eFlags&EF_FORCE_VISIBLE) - || (cent->currentState.eType == ET_PLAYER && cent->gent && cent->gent->message) ) - { + if ((cent->currentState.eFlags & EF_FORCE_VISIBLE) || (cent->currentState.eType == ET_PLAYER && cent->gent && cent->gent->message)) { ent->shaderRGBA[0] = 0; ent->shaderRGBA[1] = 0; ent->shaderRGBA[2] = 255; ent->shaderRGBA[3] = 254; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); return; } @@ -4524,59 +3737,46 @@ void CG_AddForceSightShell( refEntity_t *ent, centity_t *cent ) ent->shaderRGBA[1] = 255; ent->shaderRGBA[2] = 0; - //if ( g_entities[0].client->ps.forcePowerLevel[FP_SEE] > FORCE_LEVEL_2 ) + // if ( g_entities[0].client->ps.forcePowerLevel[FP_SEE] > FORCE_LEVEL_2 ) //{TEST: level 3 identifies friend or foe with color - team_t team = TEAM_NEUTRAL; - if ( cent->gent && cent->gent->client ) - { - team = cent->gent->client->playerTeam; + team_t team = TEAM_NEUTRAL; + if (cent->gent && cent->gent->client) { + team = cent->gent->client->playerTeam; + } else if (cent->gent && cent->gent->owner) { + if (cent->gent->owner->client) { + team = cent->gent->owner->client->playerTeam; + } else { + team = cent->gent->owner->noDamageTeam; } - else if ( cent->gent && cent->gent->owner ) - { - if ( cent->gent->owner->client ) - { - team = cent->gent->owner->client->playerTeam; - } - else - { - team = cent->gent->owner->noDamageTeam; + } + switch (team) { + case TEAM_ENEMY: + ent->shaderRGBA[0] = 255; + ent->shaderRGBA[1] = 0; + ent->shaderRGBA[2] = 0; + break; + case TEAM_PLAYER: + ent->shaderRGBA[0] = 0; + ent->shaderRGBA[1] = 255; + ent->shaderRGBA[2] = 0; + break; + case TEAM_FREE: + if (cent->gent && cent->gent->client) { + if (cent->gent->client->NPC_class == CLASS_TUSKEN || cent->gent->client->NPC_class == CLASS_RANCOR || + cent->gent->client->NPC_class == CLASS_WAMPA || cent->gent->client->NPC_class == CLASS_SAND_CREATURE) { + ent->shaderRGBA[0] = 255; + ent->shaderRGBA[1] = 0; + ent->shaderRGBA[2] = 0; } } - switch ( team ) - { - case TEAM_ENEMY: - ent->shaderRGBA[0] = 255; - ent->shaderRGBA[1] = 0; - ent->shaderRGBA[2] = 0; - break; - case TEAM_PLAYER: - ent->shaderRGBA[0] = 0; - ent->shaderRGBA[1] = 255; - ent->shaderRGBA[2] = 0; - break; - case TEAM_FREE: - if ( cent->gent && cent->gent->client ) - { - if ( cent->gent->client->NPC_class == CLASS_TUSKEN - || cent->gent->client->NPC_class == CLASS_RANCOR - || cent->gent->client->NPC_class == CLASS_WAMPA - || cent->gent->client->NPC_class == CLASS_SAND_CREATURE ) - { - ent->shaderRGBA[0] = 255; - ent->shaderRGBA[1] = 0; - ent->shaderRGBA[2] = 0; - } - } - break; - default: - break; - } + break; + default: + break; + } - if ( g_entities[0].client->ps.forcePowerLevel[FP_SEE] > FORCE_LEVEL_2 ) - {//TEST: level 3 also displays health - if ( cent->gent && cent->gent->health > 0 && cent->gent->max_health > 0 ) - {//draw a health bar over them - CG_AddHealthBarEnt( cent->currentState.clientNum ); + if (g_entities[0].client->ps.forcePowerLevel[FP_SEE] > FORCE_LEVEL_2) { // TEST: level 3 also displays health + if (cent->gent && cent->gent->health > 0 && cent->gent->max_health > 0) { // draw a health bar over them + CG_AddHealthBarEnt(cent->currentState.clientNum); } } @@ -4587,9 +3787,9 @@ void CG_AddForceSightShell( refEntity_t *ent, centity_t *cent ) } */ - //FIXME: make it darker or more translucent the further away it is? + // FIXME: make it darker or more translucent the further away it is? - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } /* @@ -4599,90 +3799,78 @@ CG_AddRefEntityWithPowerups Adds a piece with modifications or duplications for powerups =============== */ -void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cent ) -{ - if ( !cent ) - { - cgi_R_AddRefEntityToScene( ent ); +void CG_AddRefEntityWithPowerups(refEntity_t *ent, int powerups, centity_t *cent) { + if (!cent) { + cgi_R_AddRefEntityToScene(ent); return; } - gentity_t *gent = cent->gent; - if ( !gent ) - { - cgi_R_AddRefEntityToScene( ent ); + gentity_t *gent = cent->gent; + if (!gent) { + cgi_R_AddRefEntityToScene(ent); return; } - if ( gent->client->ps.powerups[PW_DISRUPTION] < cg.time ) - {//disruptor - if (( powerups & ( 1 << PW_DISRUPTION ))) - { - //stop drawing him after this effect + if (gent->client->ps.powerups[PW_DISRUPTION] < cg.time) { // disruptor + if ((powerups & (1 << PW_DISRUPTION))) { + // stop drawing him after this effect gent->client->ps.eFlags |= EF_NODRAW; return; } } -// if ( gent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 ) -// { -// centity_t *cent = &cg_entities[gent->s.number]; -// cgi_S_AddLoopingSound( 0, cent->lerpOrigin, vec3_origin, cgs.media.overchargeLoopSound ); -// } + // if ( gent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 ) + // { + // centity_t *cent = &cg_entities[gent->s.number]; + // cgi_S_AddLoopingSound( 0, cent->lerpOrigin, vec3_origin, cgs.media.overchargeLoopSound ); + // } - //get the dude's color choice in + // get the dude's color choice in ent->shaderRGBA[0] = gent->client->renderInfo.customRGBA[0]; ent->shaderRGBA[1] = gent->client->renderInfo.customRGBA[1]; ent->shaderRGBA[2] = gent->client->renderInfo.customRGBA[2]; ent->shaderRGBA[3] = gent->client->renderInfo.customRGBA[3]; // If certain states are active, we don't want to add in the regular body - if ( !gent->client->ps.powerups[PW_CLOAKED] && - !gent->client->ps.powerups[PW_UNCLOAKING] && - !gent->client->ps.powerups[PW_DISRUPTION] ) - { - cgi_R_AddRefEntityToScene( ent ); + if (!gent->client->ps.powerups[PW_CLOAKED] && !gent->client->ps.powerups[PW_UNCLOAKING] && !gent->client->ps.powerups[PW_DISRUPTION]) { + cgi_R_AddRefEntityToScene(ent); } // Disruptor Gun Alt-fire - if ( gent->client->ps.powerups[PW_DISRUPTION] ) - { + if (gent->client->ps.powerups[PW_DISRUPTION]) { // I guess when something dies, it looks like pos1 gets set to the impact point on death, we can do fun stuff with this vec3_t tempAng; - VectorSubtract( gent->pos1, ent->origin, ent->oldorigin ); - //er, adjust this to get the proper position in model space... account for yaw - float tempLength = VectorNormalize( ent->oldorigin ); - vectoangles( ent->oldorigin, tempAng ); + VectorSubtract(gent->pos1, ent->origin, ent->oldorigin); + // er, adjust this to get the proper position in model space... account for yaw + float tempLength = VectorNormalize(ent->oldorigin); + vectoangles(ent->oldorigin, tempAng); tempAng[YAW] -= gent->client->ps.viewangles[YAW]; - AngleVectors( tempAng, ent->oldorigin, NULL, NULL ); - VectorScale( ent->oldorigin, tempLength, ent->oldorigin ); + AngleVectors(tempAng, ent->oldorigin, NULL, NULL); + VectorScale(ent->oldorigin, tempLength, ent->oldorigin); ent->endTime = gent->fx_time; ent->renderfx |= (RF_DISINTEGRATE2); - ent->customShader = cgi_R_RegisterShader( "gfx/effects/burn" ); - cgi_R_AddRefEntityToScene( ent ); + ent->customShader = cgi_R_RegisterShader("gfx/effects/burn"); + cgi_R_AddRefEntityToScene(ent); ent->renderfx &= ~(RF_DISINTEGRATE2); ent->renderfx |= (RF_DISINTEGRATE1); ent->customShader = 0; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); - if ( cg.time - ent->endTime < 1000 && (cg_timescale.value * cg_timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f ) - { + if (cg.time - ent->endTime < 1000 && (cg_timescale.value * cg_timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f) { vec3_t fxOrg; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, gent->playerModel, gent->torsoBolt, - &boltMatrix, gent->currentAngles, ent->origin, cg.time, - cgs.model_draw, gent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, gent->playerModel, gent->torsoBolt, &boltMatrix, gent->currentAngles, ent->origin, cg.time, + cgs.model_draw, gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); - VectorMA( fxOrg, -18, cg.refdef.viewaxis[0], fxOrg ); + VectorMA(fxOrg, -18, cg.refdef.viewaxis[0], fxOrg); fxOrg[2] += Q_flrand(-1.0f, 1.0f) * 20; - theFxScheduler.PlayEffect( "disruptor/death_smoke", fxOrg ); + theFxScheduler.PlayEffect("disruptor/death_smoke", fxOrg); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - theFxScheduler.PlayEffect( "disruptor/death_smoke", fxOrg ); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + theFxScheduler.PlayEffect("disruptor/death_smoke", fxOrg); } } } @@ -4690,135 +3878,108 @@ void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cen // Cloaking & Uncloaking Technology //---------------------------------------- - if (( powerups & ( 1 << PW_UNCLOAKING ))) - {//in the middle of cloaking - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && CG_PlayerCanSeeCent( cent )) - {//just draw him - cgi_R_AddRefEntityToScene( ent ); - } - else - { + if ((powerups & (1 << PW_UNCLOAKING))) { // in the middle of cloaking + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + CG_PlayerCanSeeCent(cent)) { // just draw him + cgi_R_AddRefEntityToScene(ent); + } else { float perc = (float)(gent->client->ps.powerups[PW_UNCLOAKING] - cg.time) / 2000.0f; - if (( powerups & ( 1 << PW_CLOAKED ))) - {//actually cloaking, so reverse it + if ((powerups & (1 << PW_CLOAKED))) { // actually cloaking, so reverse it perc = 1.0f - perc; } - if ( perc >= 0.0f && perc <= 1.0f ) - { + if (perc >= 0.0f && perc <= 1.0f) { ent->renderfx &= ~RF_ALPHA_FADE; ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255.0f * perc; ent->shaderRGBA[3] = 0; ent->customShader = cgs.media.cloakedShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255; ent->shaderRGBA[3] = 255 * (1.0f - perc); // let model alpha in - ent->customShader = 0; // use regular skin + ent->customShader = 0; // use regular skin ent->renderfx &= ~RF_RGB_TINT; ent->renderfx |= RF_ALPHA_FADE; - cgi_R_AddRefEntityToScene( ent ); - } - } - } - else if (( powerups & ( 1 << PW_CLOAKED ))) - {//fully cloaked - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && CG_PlayerCanSeeCent( cent )) - {//just draw him - cgi_R_AddRefEntityToScene( ent ); - } - else - { - if (cg_renderToTextureFX.integer && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) - { - cgi_R_SetRefractProp(1.0f, 0.0f, qfalse, qfalse); //don't need to do this every frame.. but.. - ent->customShader = 2; //crazy "refractive" shader - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); + } + } + } else if ((powerups & (1 << PW_CLOAKED))) { // fully cloaked + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + CG_PlayerCanSeeCent(cent)) { // just draw him + cgi_R_AddRefEntityToScene(ent); + } else { + if (cg_renderToTextureFX.integer && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) { + cgi_R_SetRefractProp(1.0f, 0.0f, qfalse, qfalse); // don't need to do this every frame.. but.. + ent->customShader = 2; // crazy "refractive" shader + cgi_R_AddRefEntityToScene(ent); ent->customShader = 0; - } - else - { //stencil buffer's in use, sorry - ent->renderfx = 0;//&= ~(RF_RGB_TINT|RF_ALPHA_FADE); + } else { // stencil buffer's in use, sorry + ent->renderfx = 0; //&= ~(RF_RGB_TINT|RF_ALPHA_FADE); ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = ent->shaderRGBA[3] = 255; ent->customShader = cgs.media.cloakedShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } } } // Electricity //------------------------------------------------ - if ( (powerups & ( 1 << PW_SHOCKED )) ) - { - int dif = gent->client->ps.powerups[PW_SHOCKED] - cg.time; + if ((powerups & (1 << PW_SHOCKED))) { + int dif = gent->client->ps.powerups[PW_SHOCKED] - cg.time; - if ( dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f ) - { + if (dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f) { // fade out over the last 500 ms int brightness = 255; - if ( dif < 500 ) - { - brightness = floor((dif - 500.0f) / 500.0f * 255.0f ); + if (dif < 500) { + brightness = floor((dif - 500.0f) / 500.0f * 255.0f); } ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = brightness; ent->shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { ent->customShader = cgs.media.electricBodyShader; - } - else - { + } else { ent->customShader = cgs.media.electricBody2Shader; } - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); - if ( Q_flrand(0.0f, 1.0f) > 0.9f ) - cgi_S_StartSound ( ent->origin, gent->s.number, CHAN_AUTO, cgi_S_RegisterSound( "sound/effects/energy_crackle.wav" ) ); + if (Q_flrand(0.0f, 1.0f) > 0.9f) + cgi_S_StartSound(ent->origin, gent->s.number, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/energy_crackle.wav")); } } // FORCE speed does blur trails //------------------------------------------------------ - if ( cg_speedTrail.integer - && (gent->client->ps.forcePowersActive & (1 << FP_SPEED) //in force speed - || cent->gent->client->ps.legsAnim == BOTH_FORCELONGLEAP_START//or force long jump - FIXME: only 1st half of that anim? - || cent->gent->client->ps.legsAnim == BOTH_FORCELONGLEAP_ATTACK )//or force long jump attack - && (gent->s.number || cg.renderingThirdPerson) ) // looks dumb doing this with first peron mode on + if (cg_speedTrail.integer && + (gent->client->ps.forcePowersActive & (1 << FP_SPEED) // in force speed + || cent->gent->client->ps.legsAnim == BOTH_FORCELONGLEAP_START // or force long jump - FIXME: only 1st half of that anim? + || cent->gent->client->ps.legsAnim == BOTH_FORCELONGLEAP_ATTACK) // or force long jump attack + && (gent->s.number || cg.renderingThirdPerson)) // looks dumb doing this with first peron mode on { - //FIXME: debounce this - localEntity_t *ex; + // FIXME: debounce this + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_FADE_MODEL; - memcpy( &ex->refEntity, ent, sizeof( refEntity_t )); + memcpy(&ex->refEntity, ent, sizeof(refEntity_t)); - ex->refEntity.renderfx |= (RF_ALPHA_FADE | RF_NOSHADOW | RF_G2MINLOD ) ; - //ex->refEntity.renderfx |= RF_ALPHA_FADE; + ex->refEntity.renderfx |= (RF_ALPHA_FADE | RF_NOSHADOW | RF_G2MINLOD); + // ex->refEntity.renderfx |= RF_ALPHA_FADE; ex->startTime = cg.time; ex->endTime = ex->startTime + 75; - VectorCopy( ex->refEntity.origin, ex->pos.trBase ); - VectorClear( ex->pos.trDelta ); + VectorCopy(ex->refEntity.origin, ex->pos.trBase); + VectorClear(ex->pos.trDelta); - if ( gent->client->renderInfo.customRGBA[0] - || gent->client->renderInfo.customRGBA[1] - || gent->client->renderInfo.customRGBA[2] ) - { + if (gent->client->renderInfo.customRGBA[0] || gent->client->renderInfo.customRGBA[1] || gent->client->renderInfo.customRGBA[2]) { ex->color[0] = gent->client->renderInfo.customRGBA[0]; ex->color[1] = gent->client->renderInfo.customRGBA[1]; ex->color[2] = gent->client->renderInfo.customRGBA[2]; - } - else - { + } else { ex->color[0] = ex->color[1] = ex->color[2] = 255.0f; } ex->color[3] = 50.0f; @@ -4826,63 +3987,58 @@ void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cen // Personal Shields //------------------------ - if ( powerups & ( 1 << PW_BATTLESUIT )) - { + if (powerups & (1 << PW_BATTLESUIT)) { float diff = gent->client->ps.powerups[PW_BATTLESUIT] - cg.time; float t; - if ( diff > 0 ) - { - t = 1.0f - ( diff / (ARMOR_EFFECT_TIME * 2.0f)); + if (diff > 0) { + t = 1.0f - (diff / (ARMOR_EFFECT_TIME * 2.0f)); // Only display when we have damage - if ( t < 0.0f || t > 1.0f ) - { - } - else - { + if (t < 0.0f || t > 1.0f) { + } else { ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255.0f * t; ent->shaderRGBA[3] = 255; ent->renderfx &= ~RF_ALPHA_FADE; ent->renderfx |= RF_RGB_TINT; ent->customShader = cgs.media.personalShieldShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } } } // Galak Mech shield bubble //------------------------------------------------------ - if ( powerups & ( 1 << PW_GALAK_SHIELD )) - { -/* refEntity_t tent; + if (powerups & (1 << PW_GALAK_SHIELD)) { + /* refEntity_t tent; - memset( &tent, 0, sizeof( refEntity_t )); + memset( &tent, 0, sizeof( refEntity_t )); - tent.reType = RT_LATHE; + tent.reType = RT_LATHE; - // Setting up the 2d control points, these get swept around to make a 3D lathed model - VectorSet2( tent.axis[0], 0.5, 0 ); // start point of curve - VectorSet2( tent.axis[1], 50, 85 ); // control point 1 - VectorSet2( tent.axis[2], 135, -100 ); // control point 2 - VectorSet2( tent.oldorigin, 0, -90 ); // end point of curve + // Setting up the 2d control points, these get swept around to make a 3D lathed model + VectorSet2( tent.axis[0], 0.5, 0 ); // start point of curve + VectorSet2( tent.axis[1], 50, 85 ); // control point 1 + VectorSet2( tent.axis[2], 135, -100 ); // control point 2 + VectorSet2( tent.oldorigin, 0, -90 ); // end point of curve - if ( gent->client->poisonTime && gent->client->poisonTime + 1000 > cg.time ) - { - VectorCopy( gent->pos4, tent.lightingOrigin ); - tent.frame = gent->client->poisonTime; - } + if ( gent->client->poisonTime && gent->client->poisonTime + 1000 > cg.time ) + { + VectorCopy( gent->pos4, tent.lightingOrigin ); + tent.frame = gent->client->poisonTime; + } - mdxaBone_t boltMatrix; - vec3_t angles = {0,gent->client->ps.legsYaw,0}; + mdxaBone_t boltMatrix; + vec3_t angles = {0,gent->client->ps.legsYaw,0}; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, gent->playerModel, gent->genericBolt1, &boltMatrix, angles, cent->lerpOrigin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tent.origin );// pass in the emitter origin here + gi.G2API_GetBoltMatrix( cent->gent->ghoul2, gent->playerModel, gent->genericBolt1, &boltMatrix, angles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tent.origin );// pass in the emitter origin + here - tent.endTime = gent->fx_time + 1000; // if you want the shell to build around the guy, pass in a time that is 1000ms after the start of the turn-on-effect - tent.customShader = cgi_R_RegisterShader( "gfx/effects/irid_shield" ); + tent.endTime = gent->fx_time + 1000; // if you want the shell to build around the guy, pass in a time that is 1000ms after the start + of the turn-on-effect tent.customShader = cgi_R_RegisterShader( "gfx/effects/irid_shield" ); - cgi_R_AddRefEntityToScene( &tent );*/ + cgi_R_AddRefEntityToScene( &tent );*/ } // Invincibility -- effect needs work @@ -4896,192 +4052,155 @@ void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cen // Healing -- could use some work....maybe also make it NOT be framerate dependant //------------------------------------------------------ -/* if ( powerups & ( 1 << PW_HEALING )) - { - vec3_t axis[3]; + /* if ( powerups & ( 1 << PW_HEALING )) + { + vec3_t axis[3]; - AngleVectors( cent->gent->client->renderInfo.eyeAngles, axis[0], axis[1], axis[2] ); + AngleVectors( cent->gent->client->renderInfo.eyeAngles, axis[0], axis[1], axis[2] ); - theFxScheduler.PlayEffect( cgs.effects.forceHeal, cent->gent->client->renderInfo.eyePoint, axis ); - } -*/ + theFxScheduler.PlayEffect( cgs.effects.forceHeal, cent->gent->client->renderInfo.eyePoint, axis ); + } + */ // Push Blur - if ( gent->forcePushTime > cg.time && gi.G2API_HaveWeGhoul2Models( cent->gent->ghoul2 ) ) - { - CG_ForcePushBlur( ent->origin ); + if (gent->forcePushTime > cg.time && gi.G2API_HaveWeGhoul2Models(cent->gent->ghoul2)) { + CG_ForcePushBlur(ent->origin); } - //new Jedi Academy force powers - //Rage effect - if ((cent->gent->client->ps.forcePowersActive & (1 << FP_RAGE)) && - (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) - { - //ent->renderfx &= ~RF_FORCE_ENT_ALPHA; - //ent->renderfx &= ~RF_MINLIGHT; + // new Jedi Academy force powers + // Rage effect + if ((cent->gent->client->ps.forcePowersActive & (1 << FP_RAGE)) && (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) { + // ent->renderfx &= ~RF_FORCE_ENT_ALPHA; + // ent->renderfx &= ~RF_MINLIGHT; ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = 255; ent->shaderRGBA[1] = ent->shaderRGBA[2] = 0; ent->shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { ent->customShader = cgs.media.electricBodyShader; - } - else - { + } else { ent->customShader = cgs.media.electricBody2Shader; } - cgi_R_AddRefEntityToScene( ent); + cgi_R_AddRefEntityToScene(ent); } - //FIXME: Tavion possessed effect? White? - //For now, these two are using the old shield shader. This is just so that you - //can tell it apart from the JM/duel shaders, but it's still very obvious. - if ( (cent->gent->client->ps.forcePowersActive & (1 << FP_PROTECT)) - && (cent->gent->client->ps.forcePowersActive & (1 << FP_ABSORB)) ) - {//using both at once, save ourselves some rendering - //protect+absorb is represented by cyan.. + // FIXME: Tavion possessed effect? White? + // For now, these two are using the old shield shader. This is just so that you + // can tell it apart from the JM/duel shaders, but it's still very obvious. + if ((cent->gent->client->ps.forcePowersActive & (1 << FP_PROTECT)) && + (cent->gent->client->ps.forcePowersActive & (1 << FP_ABSORB))) { // using both at once, save ourselves some rendering + // protect+absorb is represented by cyan.. ent->shaderRGBA[0] = 0; ent->shaderRGBA[1] = 255; ent->shaderRGBA[2] = 255; ent->shaderRGBA[3] = 254; ent->renderfx &= ~RF_RGB_TINT; - //ent->renderfx &= ~RF_FORCE_ENT_ALPHA; - if ( cent->gent->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1 - || cent->gent->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1 ) - { + // ent->renderfx &= ~RF_FORCE_ENT_ALPHA; + if (cent->gent->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1 || cent->gent->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1) { ent->customShader = cgs.media.forceShell; - } - else - { + } else { ent->customShader = cgs.media.playerShieldDamage; } - cgi_R_AddRefEntityToScene( ent ); - } - else if ( cent->gent->client->ps.forcePowersActive & (1 << FP_PROTECT) ) - { //protect is represented by green.. + cgi_R_AddRefEntityToScene(ent); + } else if (cent->gent->client->ps.forcePowersActive & (1 << FP_PROTECT)) { // protect is represented by green.. ent->shaderRGBA[0] = 0; ent->shaderRGBA[1] = 255; ent->shaderRGBA[2] = 0; ent->shaderRGBA[3] = 254; ent->renderfx &= ~RF_RGB_TINT; - //ent->renderfx &= ~RF_FORCE_ENT_ALPHA; - if ( cent->gent->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1 ) - { + // ent->renderfx &= ~RF_FORCE_ENT_ALPHA; + if (cent->gent->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1) { ent->customShader = cgs.media.forceShell; - } - else - { + } else { ent->customShader = cgs.media.playerShieldDamage; } - cgi_R_AddRefEntityToScene( ent ); - } - else if ( cent->gent->client->ps.forcePowersActive & (1 << FP_ABSORB)) - { //absorb is represented by blue.. + cgi_R_AddRefEntityToScene(ent); + } else if (cent->gent->client->ps.forcePowersActive & (1 << FP_ABSORB)) { // absorb is represented by blue.. ent->shaderRGBA[0] = 0; ent->shaderRGBA[1] = 0; ent->shaderRGBA[2] = 255; ent->shaderRGBA[3] = 254; ent->renderfx &= ~RF_RGB_TINT; - //ent->renderfx &= ~RF_FORCE_ENT_ALPHA; - if ( cent->gent->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1 ) - { + // ent->renderfx &= ~RF_FORCE_ENT_ALPHA; + if (cent->gent->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1) { ent->customShader = cgs.media.forceShell; - } - else - { + } else { ent->customShader = cgs.media.playerShieldDamage; } - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } - if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number - && (cent->currentState.eFlags&EF_FORCE_VISIBLE - || ((cent->gent->health > 0 || cent->gent->message ) - && cent->currentState.eType == ET_PLAYER//other things handle this in their own render funcs - && CG_PlayerCanSeeCent( cent )) - ) - ) - {//force sight draws auras around living things - CG_AddForceSightShell( ent, cent ); + if ((cg.snap->ps.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && + (cent->currentState.eFlags & EF_FORCE_VISIBLE || + ((cent->gent->health > 0 || cent->gent->message) && cent->currentState.eType == ET_PLAYER // other things handle this in their own render funcs + && CG_PlayerCanSeeCent(cent)))) { // force sight draws auras around living things + CG_AddForceSightShell(ent, cent); } - //temp stuff for drain - if ( ( (cent->gent->client->ps.eFlags&EF_FORCE_DRAINED) || cent->gent->client->ps.forcePowersActive&(1<currentState.number != cg.snap->ps.clientNum)) - {//draining or being drained + // temp stuff for drain + if (((cent->gent->client->ps.eFlags & EF_FORCE_DRAINED) || cent->gent->client->ps.forcePowersActive & (1 << FP_DRAIN)) && + (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) { // draining or being drained ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = 255; ent->shaderRGBA[1] = ent->shaderRGBA[2] = 0; ent->shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { ent->customShader = cgs.media.electricBodyShader; - } - else - { + } else { ent->customShader = cgs.media.electricBody2Shader; } - cgi_R_AddRefEntityToScene( ent); + cgi_R_AddRefEntityToScene(ent); } } - /* ------------------------- CG_G2SetHeadBlink ------------------------- */ -static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) -{ - if ( !cent ) - { +static void CG_G2SetHeadBlink(centity_t *cent, qboolean bStart) { + if (!cent) { return; } gentity_t *gent = cent->gent; - //FIXME: get these boneIndices game-side and pass it down? - //FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 - const int hLeye = gi.G2API_GetBoneIndex( &gent->ghoul2[0], "leye", qtrue ); - if (hLeye == -1) - { + // FIXME: get these boneIndices game-side and pass it down? + // FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 + const int hLeye = gi.G2API_GetBoneIndex(&gent->ghoul2[0], "leye", qtrue); + if (hLeye == -1) { return; } - vec3_t desiredAngles = {0}; + vec3_t desiredAngles = {0}; int blendTime = 80; qboolean bWink = qfalse; - if (bStart) - { + if (bStart) { desiredAngles[YAW] = -38; - if ( !in_camera && Q_flrand(0.0f, 1.0f) > 0.95f ) - { + if (!in_camera && Q_flrand(0.0f, 1.0f) > 0.95f) { bWink = qtrue; - blendTime /=3; + blendTime /= 3; } } - gi.G2API_SetBoneAnglesIndex( &gent->ghoul2[gent->playerModel], hLeye, desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); - const int hReye = gi.G2API_GetBoneIndex( &gent->ghoul2[0], "reye", qtrue ); - if (hReye == -1) - { + gi.G2API_SetBoneAnglesIndex(&gent->ghoul2[gent->playerModel], hLeye, desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + blendTime, cg.time); + const int hReye = gi.G2API_GetBoneIndex(&gent->ghoul2[0], "reye", qtrue); + if (hReye == -1) { return; } if (!bWink) - gi.G2API_SetBoneAnglesIndex( &gent->ghoul2[gent->playerModel], hReye, desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); + gi.G2API_SetBoneAnglesIndex(&gent->ghoul2[gent->playerModel], hReye, desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + blendTime, cg.time); } /* @@ -5089,145 +4208,114 @@ static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) CG_G2SetHeadAnims ------------------------- */ -static void CG_G2SetHeadAnim( centity_t *cent, int anim ) -{ - gentity_t *gent = cent->gent; +static void CG_G2SetHeadAnim(centity_t *cent, int anim) { + gentity_t *gent = cent->gent; const int blendTime = 50; const animation_t *animations = level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations; - int animFlags = BONE_ANIM_OVERRIDE ;//| BONE_ANIM_BLEND; + int animFlags = BONE_ANIM_OVERRIDE; //| BONE_ANIM_BLEND; // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). -// float timeScaleMod = (cg_timescale.value&&gent&&gent->s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); + // int startFrame, endFrame; + // const qboolean animatingHead = gi.G2API_GetAnimRangeIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); -// if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, - firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); - } + // if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again + { gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); } } -static qboolean CG_G2PlayerHeadAnims( centity_t *cent ) -{ - if(!ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) - { +static qboolean CG_G2PlayerHeadAnims(centity_t *cent) { + if (!ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) { return qfalse; } - if (cent->gent->faceBone == BONE_INDEX_INVALID) - { // i don't have a face + if (cent->gent->faceBone == BONE_INDEX_INVALID) { // i don't have a face return qfalse; } int anim = -1; - if ( cent->gent->health <= 0 ) - {//Dead people close their eyes and don't make faces! + if (cent->gent->health <= 0) { // Dead people close their eyes and don't make faces! anim = FACE_DEAD; - } - else - { - if (!cent->gent->client->facial_blink) - { // set the timers + } else { + if (!cent->gent->client->facial_blink) { // set the timers cent->gent->client->facial_blink = cg.time + Q_flrand(4000.0, 8000.0); cent->gent->client->facial_timer = cg.time + Q_flrand(6000.0, 10000.0); } - //are we blinking? - if (cent->gent->client->facial_blink < 0) - { // yes, check if we are we done blinking ? - if (-(cent->gent->client->facial_blink) < cg.time) - { // yes, so reset blink timer + // are we blinking? + if (cent->gent->client->facial_blink < 0) { // yes, check if we are we done blinking ? + if (-(cent->gent->client->facial_blink) < cg.time) { // yes, so reset blink timer cent->gent->client->facial_blink = cg.time + Q_flrand(4000.0, 8000.0); - CG_G2SetHeadBlink( cent, qfalse ); //stop the blink + CG_G2SetHeadBlink(cent, qfalse); // stop the blink } - } - else // no we aren't blinking + } else // no we aren't blinking { - if (cent->gent->client->facial_blink < cg.time)// but should we start ? + if (cent->gent->client->facial_blink < cg.time) // but should we start ? { - CG_G2SetHeadBlink( cent, qtrue ); - if (cent->gent->client->facial_blink == 1) - {//requested to stay shut by SET_FACEEYESCLOSED - cent->gent->client->facial_blink = -(cg.time + 99999999.0f);// set blink timer - } - else - { - cent->gent->client->facial_blink = -(cg.time + 300.0f);// set blink timer + CG_G2SetHeadBlink(cent, qtrue); + if (cent->gent->client->facial_blink == 1) { // requested to stay shut by SET_FACEEYESCLOSED + cent->gent->client->facial_blink = -(cg.time + 99999999.0f); // set blink timer + } else { + cent->gent->client->facial_blink = -(cg.time + 300.0f); // set blink timer } } } - - if (gi.VoiceVolume[cent->gent->s.clientNum] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused + if (gi.VoiceVolume[cent->gent->s.clientNum] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused { - anim = FACE_TALK1 + gi.VoiceVolume[cent->gent->s.clientNum] -1; + anim = FACE_TALK1 + gi.VoiceVolume[cent->gent->s.clientNum] - 1; cent->gent->client->facial_timer = cg.time + Q_flrand(2000.0, 7000.0); - if ( cent->gent->client->breathPuffTime > cg.time + 300 ) - {//when talking, do breath puff + if (cent->gent->client->breathPuffTime > cg.time + 300) { // when talking, do breath puff cent->gent->client->breathPuffTime = cg.time; } - } - else if (gi.VoiceVolume[cent->gent->s.clientNum] == -1 ) - {//talking but silent + } else if (gi.VoiceVolume[cent->gent->s.clientNum] == -1) { // talking but silent anim = FACE_TALK0; cent->gent->client->facial_timer = cg.time + Q_flrand(2000.0, 7000.0); - } - else if (gi.VoiceVolume[cent->gent->s.clientNum] == 0) //don't do aux if in a slient part of speech - {//not talking - if (cent->gent->client->facial_timer < 0) // are we auxing ? - { //yes - if (-(cent->gent->client->facial_timer) < cg.time)// are we done auxing ? - { // yes, reset aux timer + } else if (gi.VoiceVolume[cent->gent->s.clientNum] == 0) // don't do aux if in a slient part of speech + { // not talking + if (cent->gent->client->facial_timer < 0) // are we auxing ? + { // yes + if (-(cent->gent->client->facial_timer) < cg.time) // are we done auxing ? + { // yes, reset aux timer cent->gent->client->facial_timer = cg.time + Q_flrand(7000.0, 10000.0); - } - else - { // not yet, so choose anim + } else { // not yet, so choose anim anim = cent->gent->client->facial_anim; } - } - else // no we aren't auxing - { // but should we start ? - if (cent->gent->client->facial_timer < cg.time) - {//yes - cent->gent->client->facial_anim = FACE_ALERT + Q_irand(0,2); //alert, smile, frown + } else // no we aren't auxing + { // but should we start ? + if (cent->gent->client->facial_timer < cg.time) { // yes + cent->gent->client->facial_anim = FACE_ALERT + Q_irand(0, 2); // alert, smile, frown // set aux timer cent->gent->client->facial_timer = -(cg.time + 2000.0); anim = cent->gent->client->facial_anim; } } - }//talking - }//dead - if (anim != -1) - { - CG_G2SetHeadAnim( cent, anim ); + } // talking + } // dead + if (anim != -1) { + CG_G2SetHeadAnim(cent, anim); return qtrue; } return qfalse; @@ -5371,7 +4459,7 @@ int CG_PlayerHeadExtension( centity_t *cent, refEntity_t *head ) { add_in += 2; // set blink timer - cent->gent->client->facial_frown = -(cg.time + 3000.0); + cent->gent->client->facial_frown = -(cg.time + 3000.0); } } } @@ -5394,23 +4482,19 @@ int CG_PlayerHeadExtension( centity_t *cent, refEntity_t *head ) // // Can pass in NULL for the axis //-------------------------------------------------------------- -void CG_GetTagWorldPosition( refEntity_t *model, char *tag, vec3_t pos, vec3_t axis[3] ) -{ - orientation_t orientation; +void CG_GetTagWorldPosition(refEntity_t *model, char *tag, vec3_t pos, vec3_t axis[3]) { + orientation_t orientation; // Get the requested tag - cgi_R_LerpTag( &orientation, model->hModel, model->oldframe, model->frame, - 1.0f - model->backlerp, tag ); + cgi_R_LerpTag(&orientation, model->hModel, model->oldframe, model->frame, 1.0f - model->backlerp, tag); - VectorCopy( model->origin, pos ); - for ( int i = 0 ; i < 3 ; i++ ) - { - VectorMA( pos, orientation.origin[i], model->axis[i], pos ); + VectorCopy(model->origin, pos); + for (int i = 0; i < 3; i++) { + VectorMA(pos, orientation.origin[i], model->axis[i], pos); } - if ( axis ) - { - MatrixMultiply( orientation.axis, model->axis, axis ); + if (axis) { + MatrixMultiply(orientation.axis, model->axis, axis); } } @@ -5422,29 +4506,26 @@ CG_GetPlayerLightLevel ------------------------- */ -static void CG_GetPlayerLightLevel( centity_t *cent ) -{ - vec3_t ambient={0}, directed, lightDir; +static void CG_GetPlayerLightLevel(centity_t *cent) { + vec3_t ambient = {0}, directed, lightDir; - //Poll the renderer for the light level - if ( cent->currentState.clientNum == cg.snap->ps.clientNum ) - {//hAX0R + // Poll the renderer for the light level + if (cent->currentState.clientNum == cg.snap->ps.clientNum) { // hAX0R ambient[0] = 666; } - cgi_R_GetLighting( cent->lerpOrigin, ambient, directed, lightDir ); + cgi_R_GetLighting(cent->lerpOrigin, ambient, directed, lightDir); - //Get the maximum value for the player + // Get the maximum value for the player cent->gent->lightLevel = directed[0]; - if ( directed[1] > cent->gent->lightLevel ) + if (directed[1] > cent->gent->lightLevel) cent->gent->lightLevel = directed[1]; - if ( directed[2] > cent->gent->lightLevel ) + if (directed[2] > cent->gent->lightLevel) cent->gent->lightLevel = directed[2]; - if ( cent->gent->client->ps.weapon == WP_SABER && cent->gent->client->ps.SaberLength() > 0 ) - { - cent->gent->lightLevel += (cent->gent->client->ps.SaberLength()/cent->gent->client->ps.SaberLengthMax())*200; + if (cent->gent->client->ps.weapon == WP_SABER && cent->gent->client->ps.SaberLength() > 0) { + cent->gent->lightLevel += (cent->gent->client->ps.SaberLength() / cent->gent->client->ps.SaberLengthMax()) * 200; } } @@ -5455,50 +4536,35 @@ CG_StopWeaponSounds Stops any weapon sounds as needed =============== */ -static void CG_StopWeaponSounds( centity_t *cent ) -{ - weaponInfo_t *weapon = &cg_weapons[ cent->currentState.weapon ]; +static void CG_StopWeaponSounds(centity_t *cent) { + weaponInfo_t *weapon = &cg_weapons[cent->currentState.weapon]; - if ( cent->currentState.weapon == WP_SABER ) - { - if ( cent->gent && cent->gent->client ) - { - if ( !cent->gent->client->ps.SaberActive() ) - {//neither saber is on + if (cent->currentState.weapon == WP_SABER) { + if (cent->gent && cent->gent->client) { + if (!cent->gent->client->ps.SaberActive()) { // neither saber is on return; - } - else if ( cent->gent->client->ps.saberInFlight ) //cent->gent->client->ps.saberInFlight ) - {//throwing saber - if ( !cent->gent->client->ps.dualSabers || !cent->gent->client->ps.saber[1].Active() ) - {//don't have a second saber or it's not on + } else if (cent->gent->client->ps.saberInFlight) // cent->gent->client->ps.saberInFlight ) + { // throwing saber + if (!cent->gent->client->ps.dualSabers || !cent->gent->client->ps.saber[1].Active()) { // don't have a second saber or it's not on return; } } } - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - cgs.sound_precache[g_entities[cent->currentState.clientNum].client->ps.saber[0].soundLoop] ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, + cgs.sound_precache[g_entities[cent->currentState.clientNum].client->ps.saber[0].soundLoop]); return; } - if ( cent->currentState.weapon == WP_STUN_BATON || cent->currentState.weapon == WP_CONCUSSION ) - { //idling sounds - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - weapon->firingSound ); + if (cent->currentState.weapon == WP_STUN_BATON || cent->currentState.weapon == WP_CONCUSSION) { // idling sounds + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); return; } - if ( !( cent->currentState.eFlags & EF_FIRING ) ) - { - if ( cent->pe.lightningFiring ) - { - if ( weapon->stopSound ) - { - cgi_S_StartSound( cent->lerpOrigin, cent->currentState.number, CHAN_WEAPON, weapon->stopSound ); + if (!(cent->currentState.eFlags & EF_FIRING)) { + if (cent->pe.lightningFiring) { + if (weapon->stopSound) { + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_WEAPON, weapon->stopSound); } cent->pe.lightningFiring = qfalse; @@ -5506,231 +4572,175 @@ static void CG_StopWeaponSounds( centity_t *cent ) return; } - if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { - if ( weapon->altFiringSound ) - { - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->altFiringSound ); + if (cent->currentState.eFlags & EF_ALT_FIRING) { + if (weapon->altFiringSound) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->altFiringSound); } cent->pe.lightningFiring = qtrue; } } - //--------------- SABER STUFF -------- -extern void CG_Smoke( vec3_t origin, vec3_t dir, float radius, float speed, qhandle_t shader, int flags); -void CG_SaberDoWeaponHitMarks( gclient_t *client, gentity_t *saberEnt, gentity_t *hitEnt, int saberNum, int bladeNum, vec3_t hitPos, vec3_t hitDir, vec3_t uaxis, vec3_t splashBackDir, float sizeTimeScale ) -{ - if ( client - && sizeTimeScale > 0.0f - && hitEnt - && hitEnt->client - && hitEnt->ghoul2.size() ) - {//burn mark with glow - //FIXME: set the correct angle based on direction of swing - //FIXME: keep a count of these on the ent and don't add too many - int lifeTime = (1.01-(float)(hitEnt->health)/hitEnt->max_health) * (float)Q_irand( 5000, 10000 ); +extern void CG_Smoke(vec3_t origin, vec3_t dir, float radius, float speed, qhandle_t shader, int flags); +void CG_SaberDoWeaponHitMarks(gclient_t *client, gentity_t *saberEnt, gentity_t *hitEnt, int saberNum, int bladeNum, vec3_t hitPos, vec3_t hitDir, vec3_t uaxis, + vec3_t splashBackDir, float sizeTimeScale) { + if (client && sizeTimeScale > 0.0f && hitEnt && hitEnt->client && hitEnt->ghoul2.size()) { // burn mark with glow + // FIXME: set the correct angle based on direction of swing + // FIXME: keep a count of these on the ent and don't add too many + int lifeTime = (1.01 - (float)(hitEnt->health) / hitEnt->max_health) * (float)Q_irand(5000, 10000); float size = 0.0f; int weaponMarkShader = 0, markShader = cgs.media.bdecal_saberglowmark; - //First: do mark decal on hitEnt - if ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) ) - { - if ( client->ps.saber[saberNum].g2MarksShader2[0] ) - {//we have a shader to use instead of the standard mark shader - markShader = cgi_R_RegisterShader( client->ps.saber[saberNum].g2MarksShader2 ); - lifeTime = Q_irand( 20000, 30000 );//last longer if overridden + // First: do mark decal on hitEnt + if (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum)) { + if (client->ps.saber[saberNum].g2MarksShader2[0]) { // we have a shader to use instead of the standard mark shader + markShader = cgi_R_RegisterShader(client->ps.saber[saberNum].g2MarksShader2); + lifeTime = Q_irand(20000, 30000); // last longer if overridden } - } - else - { - if ( client->ps.saber[saberNum].g2MarksShader[0] ) - {//we have a shader to use instead of the standard mark shader - markShader = cgi_R_RegisterShader( client->ps.saber[saberNum].g2MarksShader ); - lifeTime = Q_irand( 20000, 30000 );//last longer if overridden + } else { + if (client->ps.saber[saberNum].g2MarksShader[0]) { // we have a shader to use instead of the standard mark shader + markShader = cgi_R_RegisterShader(client->ps.saber[saberNum].g2MarksShader); + lifeTime = Q_irand(20000, 30000); // last longer if overridden } } - if ( markShader ) - { - lifeTime = ceil( (float)lifeTime * sizeTimeScale ); - size = Q_flrand( 2.0f, 3.0f ) * sizeTimeScale; - CG_AddGhoul2Mark( markShader, size, hitPos, hitDir, hitEnt->s.number, - hitEnt->client->ps.origin, hitEnt->client->renderInfo.legsYaw, hitEnt->ghoul2, hitEnt->s.modelScale, - lifeTime, 0, uaxis ); + if (markShader) { + lifeTime = ceil((float)lifeTime * sizeTimeScale); + size = Q_flrand(2.0f, 3.0f) * sizeTimeScale; + CG_AddGhoul2Mark(markShader, size, hitPos, hitDir, hitEnt->s.number, hitEnt->client->ps.origin, hitEnt->client->renderInfo.legsYaw, hitEnt->ghoul2, + hitEnt->s.modelScale, lifeTime, 0, uaxis); } - //now do weaponMarkShader - splashback decal on weapon - if ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) ) - { - if ( client->ps.saber[saberNum].g2WeaponMarkShader2[0] ) - {//we have a shader to use instead of the standard mark shader - weaponMarkShader = cgi_R_RegisterShader( client->ps.saber[saberNum].g2WeaponMarkShader2 ); - lifeTime = Q_irand( 7000, 12000 );//last longer if overridden + // now do weaponMarkShader - splashback decal on weapon + if (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum)) { + if (client->ps.saber[saberNum].g2WeaponMarkShader2[0]) { // we have a shader to use instead of the standard mark shader + weaponMarkShader = cgi_R_RegisterShader(client->ps.saber[saberNum].g2WeaponMarkShader2); + lifeTime = Q_irand(7000, 12000); // last longer if overridden } - } - else - { - if ( client->ps.saber[saberNum].g2WeaponMarkShader[0] ) - {//we have a shader to use instead of the standard mark shader - weaponMarkShader = cgi_R_RegisterShader( client->ps.saber[saberNum].g2WeaponMarkShader ); - lifeTime = Q_irand( 7000, 12000 );//last longer if overridden + } else { + if (client->ps.saber[saberNum].g2WeaponMarkShader[0]) { // we have a shader to use instead of the standard mark shader + weaponMarkShader = cgi_R_RegisterShader(client->ps.saber[saberNum].g2WeaponMarkShader); + lifeTime = Q_irand(7000, 12000); // last longer if overridden } } - if ( weaponMarkShader ) - { - centity_t *splatterOnCent = (saberEnt&&client->ps.saberInFlight?&cg_entities[saberEnt->s.number]:&cg_entities[client->ps.clientNum]); + if (weaponMarkShader) { + centity_t *splatterOnCent = (saberEnt && client->ps.saberInFlight ? &cg_entities[saberEnt->s.number] : &cg_entities[client->ps.clientNum]); float yawAngle = 0; vec3_t backDir; - VectorScale( hitDir, -1, backDir ); - if ( !splatterOnCent->gent->client ) - { + VectorScale(hitDir, -1, backDir); + if (!splatterOnCent->gent->client) { yawAngle = splatterOnCent->lerpAngles[YAW]; - } - else - { + } else { yawAngle = splatterOnCent->gent->client->renderInfo.legsYaw; } - lifeTime = ceil( (float)lifeTime * sizeTimeScale ); - size = Q_flrand( 1.0f, 3.0f ) * sizeTimeScale; - if ( splatterOnCent->gent->ghoul2.size() > saberNum+1 ) - { - CG_AddGhoul2Mark( weaponMarkShader, size, hitPos, backDir, splatterOnCent->currentState.number, - splatterOnCent->lerpOrigin, yawAngle, splatterOnCent->gent->ghoul2, splatterOnCent->currentState.modelScale, - lifeTime, saberNum+1, uaxis/*splashBackDir*/ ); + lifeTime = ceil((float)lifeTime * sizeTimeScale); + size = Q_flrand(1.0f, 3.0f) * sizeTimeScale; + if (splatterOnCent->gent->ghoul2.size() > saberNum + 1) { + CG_AddGhoul2Mark(weaponMarkShader, size, hitPos, backDir, splatterOnCent->currentState.number, splatterOnCent->lerpOrigin, yawAngle, + splatterOnCent->gent->ghoul2, splatterOnCent->currentState.modelScale, lifeTime, saberNum + 1, uaxis /*splashBackDir*/); } } } } -static void CG_RGBForSaberColor( saber_colors_t color, vec3_t rgb ) -{ - switch( color ) - { - case SABER_RED: - VectorSet( rgb, 1.0f, 0.2f, 0.2f ); - break; - case SABER_ORANGE: - VectorSet( rgb, 1.0f, 0.5f, 0.1f ); - break; - case SABER_YELLOW: - VectorSet( rgb, 1.0f, 1.0f, 0.2f ); - break; - case SABER_GREEN: - VectorSet( rgb, 0.2f, 1.0f, 0.2f ); - break; - case SABER_BLUE: - VectorSet( rgb, 0.2f, 0.4f, 1.0f ); - break; - case SABER_PURPLE: - VectorSet( rgb, 0.9f, 0.2f, 1.0f ); - break; +static void CG_RGBForSaberColor(saber_colors_t color, vec3_t rgb) { + switch (color) { + case SABER_RED: + VectorSet(rgb, 1.0f, 0.2f, 0.2f); + break; + case SABER_ORANGE: + VectorSet(rgb, 1.0f, 0.5f, 0.1f); + break; + case SABER_YELLOW: + VectorSet(rgb, 1.0f, 1.0f, 0.2f); + break; + case SABER_GREEN: + VectorSet(rgb, 0.2f, 1.0f, 0.2f); + break; + case SABER_BLUE: + VectorSet(rgb, 0.2f, 0.4f, 1.0f); + break; + case SABER_PURPLE: + VectorSet(rgb, 0.9f, 0.2f, 1.0f); + break; } } -static void CG_DoSaberLight( saberInfo_t *saber ) -{ +static void CG_DoSaberLight(saberInfo_t *saber) { int firstBlade = 0; int lastBlade; - //RGB combine all the colors of the sabers you're using into one averaged color! - if ( !saber ) - { + // RGB combine all the colors of the sabers you're using into one averaged color! + if (!saber) { return; } lastBlade = saber->numBlades - 1; - if ( (saber->saberFlags2&SFL2_NO_DLIGHT) ) - { - if ( saber->bladeStyle2Start > 0 ) - { - if ( (saber->saberFlags2&SFL2_NO_DLIGHT2) ) - { + if ((saber->saberFlags2 & SFL2_NO_DLIGHT)) { + if (saber->bladeStyle2Start > 0) { + if ((saber->saberFlags2 & SFL2_NO_DLIGHT2)) { return; - } - else - { + } else { firstBlade = saber->bladeStyle2Start; } - } - else - { + } else { return; } - } - else if ( saber->bladeStyle2Start > 0 ) - { - if ( (saber->saberFlags2&SFL2_NO_DLIGHT2) ) - { + } else if (saber->bladeStyle2Start > 0) { + if ((saber->saberFlags2 & SFL2_NO_DLIGHT2)) { lastBlade = saber->bladeStyle2Start; } } - vec3_t positions[MAX_BLADES*2], mid={0}, rgbs[MAX_BLADES*2], rgb={0}; - float lengths[MAX_BLADES*2]={0}, totallength = 0, numpositions = 0, dist, diameter = 0; - int i, j; + vec3_t positions[MAX_BLADES * 2], mid = {0}, rgbs[MAX_BLADES * 2], rgb = {0}; + float lengths[MAX_BLADES * 2] = {0}, totallength = 0, numpositions = 0, dist, diameter = 0; + int i, j; - if ( saber ) - { - for ( i = firstBlade; i <= lastBlade; i++ ) - { - if ( saber->blade[i].length >= MIN_SABERBLADE_DRAW_LENGTH ) - { - //FIXME: make RGB sabers - CG_RGBForSaberColor( saber->blade[i].color, rgbs[i] ); + if (saber) { + for (i = firstBlade; i <= lastBlade; i++) { + if (saber->blade[i].length >= MIN_SABERBLADE_DRAW_LENGTH) { + // FIXME: make RGB sabers + CG_RGBForSaberColor(saber->blade[i].color, rgbs[i]); lengths[i] = saber->blade[i].length; - if ( saber->blade[i].length*2.0f > diameter ) - { - diameter = saber->blade[i].length*2.0f; + if (saber->blade[i].length * 2.0f > diameter) { + diameter = saber->blade[i].length * 2.0f; } totallength += saber->blade[i].length; - VectorMA( saber->blade[i].muzzlePoint, saber->blade[i].length, saber->blade[i].muzzleDir, positions[i] ); - if ( !numpositions ) - {//first blade, store middle of that as midpoint - VectorMA( saber->blade[i].muzzlePoint, saber->blade[i].length*0.5, saber->blade[i].muzzleDir, mid ); - VectorCopy( rgbs[i], rgb ); + VectorMA(saber->blade[i].muzzlePoint, saber->blade[i].length, saber->blade[i].muzzleDir, positions[i]); + if (!numpositions) { // first blade, store middle of that as midpoint + VectorMA(saber->blade[i].muzzlePoint, saber->blade[i].length * 0.5, saber->blade[i].muzzleDir, mid); + VectorCopy(rgbs[i], rgb); } numpositions++; } } } - if ( totallength ) - {//actually have something to do - if ( numpositions == 1 ) - {//only 1 blade, midpoint is already set (halfway between the start and end of that blade), rgb is already set, so it diameter - } - else - {//multiple blades, calc averages - VectorClear( mid ); - VectorClear( rgb ); - //now go through all the data and get the average RGB and middle position and the radius - for ( i = 0; i < MAX_BLADES*2; i++ ) - { - if ( lengths[i] ) - { - VectorMA( rgb, lengths[i], rgbs[i], rgb ); - VectorAdd( mid, positions[i], mid ); + if (totallength) { // actually have something to do + if (numpositions == 1) { // only 1 blade, midpoint is already set (halfway between the start and end of that blade), rgb is already set, so it diameter + } else { // multiple blades, calc averages + VectorClear(mid); + VectorClear(rgb); + // now go through all the data and get the average RGB and middle position and the radius + for (i = 0; i < MAX_BLADES * 2; i++) { + if (lengths[i]) { + VectorMA(rgb, lengths[i], rgbs[i], rgb); + VectorAdd(mid, positions[i], mid); } } - //get middle rgb - VectorScale( rgb, 1/totallength, rgb );//get the average, normalized RGB - //get mid position - VectorScale( mid, 1/numpositions, mid ); - //find the farthest distance between the blade tips, this will be our diameter - for ( i = 0; i < MAX_BLADES*2; i++ ) - { - if ( lengths[i] ) - { - for ( j = 0; j < MAX_BLADES*2; j++ ) - { - if ( lengths[j] ) - { - dist = Distance( positions[i], positions[j] ); - if ( dist > diameter ) - { + // get middle rgb + VectorScale(rgb, 1 / totallength, rgb); // get the average, normalized RGB + // get mid position + VectorScale(mid, 1 / numpositions, mid); + // find the farthest distance between the blade tips, this will be our diameter + for (i = 0; i < MAX_BLADES * 2; i++) { + if (lengths[i]) { + for (j = 0; j < MAX_BLADES * 2; j++) { + if (lengths[j]) { + dist = Distance(positions[i], positions[j]); + if (dist > diameter) { diameter = dist; } } @@ -5739,63 +4749,59 @@ static void CG_DoSaberLight( saberInfo_t *saber ) } } - cgi_R_AddLightToScene( mid, diameter + (Q_flrand(0.0f, 1.0f)*8.0f), rgb[0], rgb[1], rgb[2] ); + cgi_R_AddLightToScene(mid, diameter + (Q_flrand(0.0f, 1.0f) * 8.0f), rgb[0], rgb[1], rgb[2]); } } -static void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color, int rfx, qboolean doLight ) -{ - vec3_t mid; - qhandle_t blade = 0, glow = 0; +static void CG_DoSaber(vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color, int rfx, qboolean doLight) { + vec3_t mid; + qhandle_t blade = 0, glow = 0; refEntity_t saber; float radiusmult; - if ( length < MIN_SABERBLADE_DRAW_LENGTH ) - { + if (length < MIN_SABERBLADE_DRAW_LENGTH) { // if the thing is so short, just forget even adding me. return; } // Find the midpoint of the saber for lighting purposes - VectorMA( origin, length * 0.5f, dir, mid ); + VectorMA(origin, length * 0.5f, dir, mid); - switch( color ) - { - case SABER_RED: - glow = cgs.media.redSaberGlowShader; - blade = cgs.media.redSaberCoreShader; - break; - case SABER_ORANGE: - glow = cgs.media.orangeSaberGlowShader; - blade = cgs.media.orangeSaberCoreShader; - break; - case SABER_YELLOW: - glow = cgs.media.yellowSaberGlowShader; - blade = cgs.media.yellowSaberCoreShader; - break; - case SABER_GREEN: - glow = cgs.media.greenSaberGlowShader; - blade = cgs.media.greenSaberCoreShader; - break; - case SABER_BLUE: - glow = cgs.media.blueSaberGlowShader; - blade = cgs.media.blueSaberCoreShader; - break; - case SABER_PURPLE: - glow = cgs.media.purpleSaberGlowShader; - blade = cgs.media.purpleSaberCoreShader; - break; + switch (color) { + case SABER_RED: + glow = cgs.media.redSaberGlowShader; + blade = cgs.media.redSaberCoreShader; + break; + case SABER_ORANGE: + glow = cgs.media.orangeSaberGlowShader; + blade = cgs.media.orangeSaberCoreShader; + break; + case SABER_YELLOW: + glow = cgs.media.yellowSaberGlowShader; + blade = cgs.media.yellowSaberCoreShader; + break; + case SABER_GREEN: + glow = cgs.media.greenSaberGlowShader; + blade = cgs.media.greenSaberCoreShader; + break; + case SABER_BLUE: + glow = cgs.media.blueSaberGlowShader; + blade = cgs.media.blueSaberCoreShader; + break; + case SABER_PURPLE: + glow = cgs.media.purpleSaberGlowShader; + blade = cgs.media.purpleSaberCoreShader; + break; } // always add a light because sabers cast a nice glow before they slice you in half!! or something... - if ( doLight ) - {//FIXME: RGB combine all the colors of the sabers you're using into one averaged color! - vec3_t rgb={1,1,1}; - CG_RGBForSaberColor( color, rgb ); - cgi_R_AddLightToScene( mid, (length*1.4f) + (Q_flrand(0.0f, 1.0f)*3.0f), rgb[0], rgb[1], rgb[2] ); + if (doLight) { // FIXME: RGB combine all the colors of the sabers you're using into one averaged color! + vec3_t rgb = {1, 1, 1}; + CG_RGBForSaberColor(color, rgb); + cgi_R_AddLightToScene(mid, (length * 1.4f) + (Q_flrand(0.0f, 1.0f) * 3.0f), rgb[0], rgb[1], rgb[2]); } - memset( &saber, 0, sizeof( refEntity_t )); + memset(&saber, 0, sizeof(refEntity_t)); // Saber glow is it's own ref type because it uses a ton of sprites, otherwise it would eat up too many // refEnts to do each glow blob individually @@ -5803,106 +4809,95 @@ static void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax // Jeff, I did this because I foolishly wished to have a bright halo as the saber is unleashed. // It's not quite what I'd hoped tho. If you have any ideas, go for it! --Pat - if (length < lengthMax ) - { - radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. - } - else - { + if (length < lengthMax) { + radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. + } else { radiusmult = 1.0; } float radiusRange = radius * 0.075f; - float radiusStart = radius-radiusRange; + float radiusStart = radius - radiusRange; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; - //saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - - VectorCopy( origin, saber.origin ); - VectorCopy( dir, saber.axis[0] ); + VectorCopy(origin, saber.origin); + VectorCopy(dir, saber.axis[0]); saber.reType = RT_SABER_GLOW; saber.customShader = glow; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; saber.renderfx = rfx; - cgi_R_AddRefEntityToScene( &saber ); + cgi_R_AddRefEntityToScene(&saber); // Do the hot core - VectorMA( origin, length, dir, saber.origin ); - VectorMA( origin, -1, dir, saber.oldorigin ); + VectorMA(origin, length, dir, saber.origin); + VectorMA(origin, -1, dir, saber.oldorigin); saber.customShader = blade; saber.reType = RT_LINE; - radiusStart = radius/3.0f; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; -// saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + radiusStart = radius / 3.0f; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - cgi_R_AddRefEntityToScene( &saber ); + cgi_R_AddRefEntityToScene(&saber); } -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 extern markPoly_t *CG_AllocMark(); -static void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) -{ -// byte colors[4]; - int i, j, numFragments; - vec3_t axis[3], originalPoints[4], mid; - vec3_t markPoints[MAX_MARK_POINTS], projection; - polyVert_t *v, verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - - if ( !cg_addMarks.integer ) { +static void CG_CreateSaberMarks(vec3_t start, vec3_t end, vec3_t normal) { + // byte colors[4]; + int i, j, numFragments; + vec3_t axis[3], originalPoints[4], mid; + vec3_t markPoints[MAX_MARK_POINTS], projection; + polyVert_t *v, verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; + + if (!cg_addMarks.integer) { return; } - float radius = 0.65f; + float radius = 0.65f; - VectorSubtract( end, start, axis[1] ); - VectorNormalizeFast( axis[1] ); + VectorSubtract(end, start, axis[1]); + VectorNormalizeFast(axis[1]); // create the texture axis - VectorCopy( normal, axis[0] ); - CrossProduct( axis[1], axis[0], axis[2] ); + VectorCopy(normal, axis[0]); + CrossProduct(axis[1], axis[0], axis[2]); // create the full polygon that we'll project - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { originalPoints[0][i] = start[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = end[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = end[i] + radius * axis[1][i] + radius * axis[2][i]; originalPoints[3][i] = start[i] - radius * axis[1][i] + radius * axis[2][i]; } - VectorScale( normal, -1, projection ); + VectorScale(normal, -1, projection); // get the fragments - numFragments = cgi_CM_MarkFragments( 4, (const float (*)[3])originalPoints, - projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments ); + numFragments = cgi_CM_MarkFragments(4, (const float(*)[3])originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); - - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) - { + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { // we have an upper limit on the complexity of polygons that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) - { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) - { + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { vec3_t delta; // Set up our texture coords, this may need some work - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); - VectorAdd( end, start, mid ); - VectorScale( mid, 0.5f, mid ); - VectorSubtract( v->xyz, mid, delta ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); + VectorAdd(end, start, mid); + VectorScale(mid, 0.5f, mid); + VectorSubtract(v->xyz, mid, delta); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); } // save it persistantly, do burn first @@ -5912,93 +4907,78 @@ static void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) mark->markShader = cgs.media.rivetMarkShader; mark->poly.numVerts = mf->numPoints; mark->color[0] = mark->color[1] = mark->color[2] = mark->color[3] = 255; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); // And now do a glow pass // by moving the start time back, we can hack it to fade out way before the burn does mark = CG_AllocMark(); mark->time = cg.time - 8500; mark->alphaFade = qfalse; - mark->markShader = cgi_R_RegisterShader("gfx/effects/saberDamageGlow" ); + mark->markShader = cgi_R_RegisterShader("gfx/effects/saberDamageGlow"); mark->poly.numVerts = mf->numPoints; mark->color[0] = 215 + Q_flrand(0.0f, 1.0f) * 40.0f; mark->color[1] = 96 + Q_flrand(0.0f, 1.0f) * 32.0f; - mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f)*15.0f; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f) * 15.0f; + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); } } -extern void FX_AddPrimitive( CEffect **effect, int killTime ); +extern void FX_AddPrimitive(CEffect **effect, int killTime); //------------------------------------------------------- -void CG_CheckSaberInWater( centity_t *cent, centity_t *scent, int saberNum, int modelIndex, vec3_t origin, vec3_t angles ) -{ +void CG_CheckSaberInWater(centity_t *cent, centity_t *scent, int saberNum, int modelIndex, vec3_t origin, vec3_t angles) { gclient_t *client = cent->gent->client; - if ( !client ) - { + if (!client) { return; } - if ( !scent || - modelIndex == -1 || - scent->gent->ghoul2.size() <= modelIndex || - scent->gent->ghoul2[modelIndex].mBltlist.size() <= 0 || //using a camera puts away your saber so you have no bolts - scent->gent->ghoul2[modelIndex].mModelindex == -1 ) - { + if (!scent || modelIndex == -1 || scent->gent->ghoul2.size() <= modelIndex || + scent->gent->ghoul2[modelIndex].mBltlist.size() <= 0 || // using a camera puts away your saber so you have no bolts + scent->gent->ghoul2[modelIndex].mModelindex == -1) { return; } - if ( cent && cent->gent && cent->gent->client - && (cent->gent->client->ps.saber[saberNum].saberFlags&SFL_ON_IN_WATER) ) - {//saber can stay on underwater + if (cent && cent->gent && cent->gent->client && (cent->gent->client->ps.saber[saberNum].saberFlags & SFL_ON_IN_WATER)) { // saber can stay on underwater return; } - if (gi.totalMapContents() & (CONTENTS_WATER|CONTENTS_SLIME)) - { - vec3_t saberOrg; - mdxaBone_t boltMatrix; + if (gi.totalMapContents() & (CONTENTS_WATER | CONTENTS_SLIME)) { + vec3_t saberOrg; + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, saberOrg ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, saberOrg); - const int contents = gi.pointcontents( saberOrg, cent->currentState.clientNum ); - if ( contents & (CONTENTS_WATER|CONTENTS_SLIME) ) - {//still in water + const int contents = gi.pointcontents(saberOrg, cent->currentState.clientNum); + if (contents & (CONTENTS_WATER | CONTENTS_SLIME)) { // still in water client->ps.saberEventFlags |= SEF_INWATER; return; } } - //not in water + // not in water client->ps.saberEventFlags &= ~SEF_INWATER; } -static void CG_AddSaberBladeGo( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles, int saberNum, int bladeNum ) -{ - vec3_t org_, end,//org_future, - axis_[3] = {{0,0,0}, {0,0,0}, {0,0,0}};//, axis_future[3]={0,0,0, 0,0,0, 0,0,0}; // shut the compiler up - trace_t trace; - float length; - int bolt; - mdxaBone_t boltMatrix; +static void CG_AddSaberBladeGo(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles, int saberNum, + int bladeNum) { + vec3_t org_, end, // org_future, + axis_[3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; //, axis_future[3]={0,0,0, 0,0,0, 0,0,0}; // shut the compiler up + trace_t trace; + float length; + int bolt; + mdxaBone_t boltMatrix; qboolean tagHack = qfalse; gclient_t *client = cent->gent->client; - if ( !client ) - { + if (!client) { return; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// if (scent->gent->ghoul2.size()) - if(1) - { - if ( !scent || - modelIndex == -1 || - scent->gent->ghoul2.size() <= modelIndex || - scent->gent->ghoul2[modelIndex].mModelindex == -1 ) - { + // if (scent->gent->ghoul2.size()) + if (1) { + if (!scent || modelIndex == -1 || scent->gent->ghoul2.size() <= modelIndex || scent->gent->ghoul2[modelIndex].mModelindex == -1) { return; } @@ -6032,7 +5012,8 @@ Ghoul2 Insert Start } tagHack = qtrue;//use the hacked switch statement below to position and orient the blades // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale ); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, (Eorientations)fwdAxis, axis_[0]); @@ -6044,46 +5025,43 @@ Ghoul2 Insert Start { // figure out where the actual model muzzle is - //old way - only 1 tag ever in a saber: - //gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); + // old way - only 1 tag ever in a saber: + // gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); - //New way, multiple blade tags: - char *tagName = va( "*blade%d", bladeNum+1 ); - bolt = gi.G2API_AddBolt( &scent->gent->ghoul2[modelIndex], tagName ); + // New way, multiple blade tags: + char *tagName = va("*blade%d", bladeNum + 1); + bolt = gi.G2API_AddBolt(&scent->gent->ghoul2[modelIndex], tagName); - if ( bolt == -1 ) - { - tagHack = qtrue;//use the hacked switch statement below to position and orient the blades - //hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models - bolt = gi.G2API_AddBolt( &scent->gent->ghoul2[modelIndex], "*flash" ); - if ( bolt == -1 ) - {//no tag_flash either?!! + if (bolt == -1) { + tagHack = qtrue; // use the hacked switch statement below to position and orient the blades + // hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models + bolt = gi.G2API_AddBolt(&scent->gent->ghoul2[modelIndex], "*flash"); + if (bolt == -1) { // no tag_flash either?!! bolt = 0; } } - //if there is an effect on this blade, play it - if ( !WP_SaberBladeUseSecondBladeStyle( ¢->gent->client->ps.saber[saberNum], bladeNum ) - && cent->gent->client->ps.saber[saberNum].bladeEffect ) - { - CG_PlayEffectIDBolted( cent->gent->client->ps.saber[saberNum].bladeEffect, modelIndex, bolt, scent->currentState.clientNum, scent->lerpOrigin, -1, qfalse ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( ¢->gent->client->ps.saber[saberNum], bladeNum ) - && cent->gent->client->ps.saber[saberNum].bladeEffect2 ) - { - CG_PlayEffectIDBolted( cent->gent->client->ps.saber[saberNum].bladeEffect2, modelIndex, bolt, scent->currentState.clientNum, scent->lerpOrigin, -1, qfalse ); + // if there is an effect on this blade, play it + if (!WP_SaberBladeUseSecondBladeStyle(¢->gent->client->ps.saber[saberNum], bladeNum) && cent->gent->client->ps.saber[saberNum].bladeEffect) { + CG_PlayEffectIDBolted(cent->gent->client->ps.saber[saberNum].bladeEffect, modelIndex, bolt, scent->currentState.clientNum, scent->lerpOrigin, + -1, qfalse); + } else if (WP_SaberBladeUseSecondBladeStyle(¢->gent->client->ps.saber[saberNum], bladeNum) && + cent->gent->client->ps.saber[saberNum].bladeEffect2) { + CG_PlayEffectIDBolted(cent->gent->client->ps.saber[saberNum].bladeEffect2, modelIndex, bolt, scent->currentState.clientNum, scent->lerpOrigin, + -1, qfalse); } - //get the boltMatrix + // get the boltMatrix gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_); - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_[0]);//front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, axis_[1]);//right - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, axis_[2]);//up + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, + axis_[0]); // front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, axis_[1]); // right + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, axis_[2]); // up } - //Now figure out where this info will be next frame + // Now figure out where this info will be next frame /* { vec3_t futureOrigin, futureAngles, orgDiff, angDiff; @@ -6108,122 +5086,108 @@ Ghoul2 Insert Start } // figure out where the actual model muzzle will be after next server frame. - gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, futureAngles, futureOrigin, futuretime, cgs.model_draw, scent->currentState.modelScale); + gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, futureAngles, futureOrigin, futuretime, cgs.model_draw, + scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_future); - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_future[0]);//was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_future[0]);//was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' + awful } */ - } - else - { - CG_GetTagWorldPosition( saber, "*flash", org_, axis_ ); + } else { + CG_GetTagWorldPosition(saber, "*flash", org_, axis_); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ -//====FIXMEFIXMEFIXMEFIXMEFIXME======================================================== -//FIXME: temp hack until we have a tag_flash2 for the second (3rd? 4th?) blade - //FIXME: maybe fall back on this if the saber model has only 1 tag_flash? + //====FIXMEFIXMEFIXMEFIXMEFIXME======================================================== + // FIXME: temp hack until we have a tag_flash2 for the second (3rd? 4th?) blade + // FIXME: maybe fall back on this if the saber model has only 1 tag_flash? // or, better yet, if the saber info doesn't list tagnames for the blades? - if ( tagHack ) - { - switch ( cent->gent->client->ps.saber[saberNum].type ) - { + if (tagHack) { + switch (cent->gent->client->ps.saber[saberNum].type) { case SABER_SINGLE: case SABER_DAGGER: case SABER_LANCE: break; case SABER_STAFF: - if ( bladeNum == 1 ) - { - VectorScale( axis_[0], -1, axis_[0] ); - VectorMA( org_, 16, axis_[0], org_ ); + if (bladeNum == 1) { + VectorScale(axis_[0], -1, axis_[0]); + VectorMA(org_, 16, axis_[0], org_); } break; case SABER_BROAD: - if ( bladeNum == 0 ) - { - VectorMA( org_, -1, axis_[1], org_ ); - } - else if ( bladeNum == 1 ) - { - VectorMA( org_, 1, axis_[1], org_ ); + if (bladeNum == 0) { + VectorMA(org_, -1, axis_[1], org_); + } else if (bladeNum == 1) { + VectorMA(org_, 1, axis_[1], org_); } break; case SABER_PRONG: - if ( bladeNum == 0 ) - { - VectorMA( org_, -3, axis_[1], org_ ); - } - else if ( bladeNum == 1 ) - { - VectorMA( org_, 3, axis_[1], org_ ); + if (bladeNum == 0) { + VectorMA(org_, -3, axis_[1], org_); + } else if (bladeNum == 1) { + VectorMA(org_, 3, axis_[1], org_); } break; case SABER_ARC: - VectorSubtract( axis_[1], axis_[2], axis_[1] ); - VectorNormalizeFast( axis_[1] ); - switch ( bladeNum ) - { + VectorSubtract(axis_[1], axis_[2], axis_[1]); + VectorNormalizeFast(axis_[1]); + switch (bladeNum) { case 0: - VectorMA( org_, 8, axis_[0], org_ ); - VectorScale( axis_[0], 0.75f, axis_[0] ); - VectorScale( axis_[1], 0.25f, axis_[1] ); - VectorAdd( axis_[0], axis_[1], axis_[0] ); - //VectorNormalize( axis_[0] ); + VectorMA(org_, 8, axis_[0], org_); + VectorScale(axis_[0], 0.75f, axis_[0]); + VectorScale(axis_[1], 0.25f, axis_[1]); + VectorAdd(axis_[0], axis_[1], axis_[0]); + // VectorNormalize( axis_[0] ); break; case 1: - //VectorMA( org_, 0, axis_[0], org_ ); - VectorScale( axis_[0], 0.25f, axis_[0] ); - VectorScale( axis_[1], 0.75f, axis_[1] ); - VectorAdd( axis_[0], axis_[1], axis_[0] ); - //VectorNormalize( axis_[0] ); + // VectorMA( org_, 0, axis_[0], org_ ); + VectorScale(axis_[0], 0.25f, axis_[0]); + VectorScale(axis_[1], 0.75f, axis_[1]); + VectorAdd(axis_[0], axis_[1], axis_[0]); + // VectorNormalize( axis_[0] ); break; case 2: - VectorMA( org_, -8, axis_[0], org_ ); - VectorScale( axis_[0], -0.25f, axis_[0] ); - VectorScale( axis_[1], 0.75f, axis_[1] ); - VectorAdd( axis_[0], axis_[1], axis_[0] ); - //VectorNormalize( axis_[0] ); + VectorMA(org_, -8, axis_[0], org_); + VectorScale(axis_[0], -0.25f, axis_[0]); + VectorScale(axis_[1], 0.75f, axis_[1]); + VectorAdd(axis_[0], axis_[1], axis_[0]); + // VectorNormalize( axis_[0] ); break; case 3: - VectorMA( org_, -16, axis_[0], org_ ); - VectorScale( axis_[0], -0.75f, axis_[0] ); - VectorScale( axis_[1], 0.25f, axis_[1] ); - VectorAdd( axis_[0], axis_[1], axis_[0] ); - //VectorNormalize( axis_[0] ); + VectorMA(org_, -16, axis_[0], org_); + VectorScale(axis_[0], -0.75f, axis_[0]); + VectorScale(axis_[1], 0.25f, axis_[1]); + VectorAdd(axis_[0], axis_[1], axis_[0]); + // VectorNormalize( axis_[0] ); break; } break; case SABER_SAI: - if ( bladeNum == 1 ) - { - VectorMA( org_, -3, axis_[1], org_ ); - } - else if ( bladeNum == 2 ) - { - VectorMA( org_, 3, axis_[1], org_ ); + if (bladeNum == 1) { + VectorMA(org_, -3, axis_[1], org_); + } else if (bladeNum == 2) { + VectorMA(org_, 3, axis_[1], org_); } break; case SABER_CLAW: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( org_, 2, axis_[0], org_ ); - VectorMA( org_, 2, axis_[2], org_ ); + VectorMA(org_, 2, axis_[0], org_); + VectorMA(org_, 2, axis_[2], org_); break; case 1: - VectorMA( org_, 2, axis_[0], org_ ); - VectorMA( org_, 2, axis_[2], org_ ); - VectorMA( org_, 2, axis_[1], org_ ); + VectorMA(org_, 2, axis_[0], org_); + VectorMA(org_, 2, axis_[2], org_); + VectorMA(org_, 2, axis_[1], org_); break; case 2: - VectorMA( org_, 2, axis_[0], org_ ); - VectorMA( org_, 2, axis_[2], org_ ); - VectorMA( org_, -2, axis_[1], org_ ); + VectorMA(org_, 2, axis_[0], org_); + VectorMA(org_, 2, axis_[2], org_); + VectorMA(org_, -2, axis_[1], org_); break; } /* @@ -6251,7 +5215,8 @@ Ghoul2 Insert End bolt = cent->gent->handLBolt; } // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, angles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale ); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_); } @@ -6262,255 +5227,219 @@ Ghoul2 Insert End VectorCopy( axis_[1], axis_[2] ); } */ - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( org_, 8, axis_[0], org_ ); + VectorMA(org_, 8, axis_[0], org_); break; case 1: - VectorScale( axis_[0], 0.33f, axis_[0] ); - VectorScale( axis_[2], 0.67f, axis_[2] ); - VectorAdd( axis_[0], axis_[2], axis_[0] ); - //VectorNormalize( axis_[0] ); - VectorMA( org_, 8, axis_[0], org_ ); + VectorScale(axis_[0], 0.33f, axis_[0]); + VectorScale(axis_[2], 0.67f, axis_[2]); + VectorAdd(axis_[0], axis_[2], axis_[0]); + // VectorNormalize( axis_[0] ); + VectorMA(org_, 8, axis_[0], org_); break; case 2: - VectorScale( axis_[0], -0.33f, axis_[0] ); - VectorScale( axis_[2], 0.67f, axis_[2] ); - VectorAdd( axis_[0], axis_[2], axis_[0] ); - //VectorNormalize( axis_[0] ); - VectorMA( org_, 8, axis_[0], org_ ); + VectorScale(axis_[0], -0.33f, axis_[0]); + VectorScale(axis_[2], 0.67f, axis_[2]); + VectorAdd(axis_[0], axis_[2], axis_[0]); + // VectorNormalize( axis_[0] ); + VectorMA(org_, 8, axis_[0], org_); break; case 3: - VectorScale( axis_[0], -1, axis_[0] ); - VectorMA( org_, 8, axis_[0], org_ ); + VectorScale(axis_[0], -1, axis_[0]); + VectorMA(org_, 8, axis_[0], org_); break; case 4: - VectorScale( axis_[0], -0.33f, axis_[0] ); - VectorScale( axis_[2], -0.67f, axis_[2] ); - VectorAdd( axis_[0], axis_[2], axis_[0] ); - //VectorNormalize( axis_[0] ); - VectorMA( org_, 8, axis_[0], org_ ); + VectorScale(axis_[0], -0.33f, axis_[0]); + VectorScale(axis_[2], -0.67f, axis_[2]); + VectorAdd(axis_[0], axis_[2], axis_[0]); + // VectorNormalize( axis_[0] ); + VectorMA(org_, 8, axis_[0], org_); break; case 5: - VectorScale( axis_[0], 0.33f, axis_[0] ); - VectorScale( axis_[2], -0.67f, axis_[2] ); - VectorAdd( axis_[0], axis_[2], axis_[0] ); - //VectorNormalize( axis_[0] ); - VectorMA( org_, 8, axis_[0], org_ ); + VectorScale(axis_[0], 0.33f, axis_[0]); + VectorScale(axis_[2], -0.67f, axis_[2]); + VectorAdd(axis_[0], axis_[2], axis_[0]); + // VectorNormalize( axis_[0] ); + VectorMA(org_, 8, axis_[0], org_); break; } break; case SABER_TRIDENT: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( org_, 24, axis_[0], org_ ); + VectorMA(org_, 24, axis_[0], org_); break; case 1: - VectorMA( org_, -6, axis_[1], org_ ); - VectorMA( org_, 24, axis_[0], org_ ); + VectorMA(org_, -6, axis_[1], org_); + VectorMA(org_, 24, axis_[0], org_); break; case 2: - VectorMA( org_, 6, axis_[1], org_ ); - VectorMA( org_, 24, axis_[0], org_ ); + VectorMA(org_, 6, axis_[1], org_); + VectorMA(org_, 24, axis_[0], org_); break; case 3: - VectorMA( org_, -32, axis_[0], org_ ); - VectorScale( axis_[0], -1, axis_[0] ); + VectorMA(org_, -32, axis_[0], org_); + VectorScale(axis_[0], -1, axis_[0]); break; } break; case SABER_SITH_SWORD: - //no blade + // no blade break; default: break; } } -//====FIXMEFIXMEFIXMEFIXMEFIXME======================================================== + //====FIXMEFIXMEFIXMEFIXMEFIXME======================================================== - //store where saber is this frame - VectorCopy( org_, cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint ); - VectorCopy( axis_[0], cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir ); - if ( saberNum == 0 && bladeNum == 0 ) - { - VectorCopy( org_, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( axis_[0], cent->gent->client->renderInfo.muzzleDir ); + // store where saber is this frame + VectorCopy(org_, cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint); + VectorCopy(axis_[0], cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir); + if (saberNum == 0 && bladeNum == 0) { + VectorCopy(org_, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(axis_[0], cent->gent->client->renderInfo.muzzleDir); cent->gent->client->renderInfo.mPCalcTime = cg.time; } - //length for purposes of rendering and marks trace will be longer than blade so we don't damage past a wall's surface - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax ) - { - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax - 8 ) - { + // length for purposes of rendering and marks trace will be longer than blade so we don't damage past a wall's surface + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax) { + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax - 8) { length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].length + 8; - } - else - { + } else { length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax; } - } - else - { + } else { length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].length; } - VectorMA( org_, length, axis_[0], end ); + VectorMA(org_, length, axis_[0], end); // Now store where the saber will be after next frame. - //VectorCopy(org_future, cent->gent->client->renderInfo.muzzlePointNext); - //VectorCopy(axis_future[0], cent->gent->client->renderInfo.muzzleDirNext); + // VectorCopy(org_future, cent->gent->client->renderInfo.muzzlePointNext); + // VectorCopy(axis_future[0], cent->gent->client->renderInfo.muzzleDirNext); - VectorAdd( end, axis_[0], end ); + VectorAdd(end, axis_[0], end); // If the saber is in flight we shouldn't trace from the player to the muzzle point - if ( cent->gent->client->ps.saberInFlight && saberNum == 0 ) - { + if (cent->gent->client->ps.saberInFlight && saberNum == 0) { trace.fraction = 1.0f; - } - else - { + } else { vec3_t rootOrigin; - if (cent->gent->rootBone>=0 && cent->gent->ghoul2.IsValid() && cent->gent->ghoul2[0].animModelIndexOffset)//If it has an animOffset it's a cinematic anim - { //i might be running out of my bounding box, so get my root origin - mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->rootBone, - &boltMatrix, angles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, rootOrigin ); + if (cent->gent->rootBone >= 0 && cent->gent->ghoul2.IsValid() && + cent->gent->ghoul2[0].animModelIndexOffset) // If it has an animOffset it's a cinematic anim + { // i might be running out of my bounding box, so get my root origin + mdxaBone_t boltMatrix; + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->rootBone, &boltMatrix, angles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, rootOrigin); + } else { + VectorCopy(cent->lerpOrigin, rootOrigin); } - else - { - VectorCopy( cent->lerpOrigin, rootOrigin ); - } - gi.trace( &trace, rootOrigin, NULL, NULL, cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, cent->currentState.number, CONTENTS_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&trace, rootOrigin, NULL, NULL, cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, cent->currentState.number, CONTENTS_SOLID, + (EG2_Collision)0, 0); } - if ( trace.fraction < 1.0f ) - { + if (trace.fraction < 1.0f) { // Saber is on the other side of a wall cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = 0.1f; cent->gent->client->ps.saberEventFlags &= ~SEF_INWATER; - } - else - { + } else { extern vmCvar_t cg_saberEntMarks; int traceMask = MASK_SOLID; qboolean noMarks = qfalse; - if ( (!WP_SaberBladeUseSecondBladeStyle( ¢->gent->client->ps.saber[saberNum], bladeNum ) - && (cent->gent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - || ( WP_SaberBladeUseSecondBladeStyle( ¢->gent->client->ps.saber[saberNum], bladeNum ) - && (cent->gent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT2) ) - ) - {//do no effects when idle - if ( !cent->gent->client->ps.saberInFlight - && !PM_SaberInAttack( cent->gent->client->ps.saberMove ) - && !PM_SaberInTransitionAny( cent->gent->client->ps.saberMove ) - && !PM_SaberInSpecialAttack( cent->gent->client->ps.torsoAnim ) ) - {//idle, do no marks + if ((!WP_SaberBladeUseSecondBladeStyle(¢->gent->client->ps.saber[saberNum], bladeNum) && + (cent->gent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT)) || + (WP_SaberBladeUseSecondBladeStyle(¢->gent->client->ps.saber[saberNum], bladeNum) && + (cent->gent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT2))) { // do no effects when idle + if (!cent->gent->client->ps.saberInFlight && !PM_SaberInAttack(cent->gent->client->ps.saberMove) && + !PM_SaberInTransitionAny(cent->gent->client->ps.saberMove) && !PM_SaberInSpecialAttack(cent->gent->client->ps.torsoAnim)) { // idle, do no marks noMarks = qtrue; } } - if ( cg_saberEntMarks.integer ) - { - if ( cent->gent->client->ps.saberInFlight - || PM_SaberInAttack( cent->gent->client->ps.saberMove ) + if (cg_saberEntMarks.integer) { + if (cent->gent->client->ps.saberInFlight || + PM_SaberInAttack(cent->gent->client->ps.saberMove) //|| PM_SaberInTransitionAny( cent->gent->client->ps.saberMove ) - || PM_SaberInSpecialAttack( cent->gent->client->ps.torsoAnim ) ) - { - traceMask |= (CONTENTS_BODY|CONTENTS_CORPSE); + || PM_SaberInSpecialAttack(cent->gent->client->ps.torsoAnim)) { + traceMask |= (CONTENTS_BODY | CONTENTS_CORPSE); } } - for ( int i = 0; i < 1; i++ )//was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad if we hit a corner, blade is still 8 longer than hit + for (int i = 0; i < 1; i++) // was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad + // if we hit a corner, blade is still 8 longer than hit { - if ( i ) - {//tracing from end to base - gi.trace( &trace, end, NULL, NULL, org_, cent->currentState.clientNum, traceMask, (EG2_Collision)0, 0 ); - } - else - {//tracing from base to end - gi.trace( &trace, org_, NULL, NULL, end, cent->currentState.clientNum, traceMask|CONTENTS_WATER|CONTENTS_SLIME, (EG2_Collision)0, 0 ); + if (i) { // tracing from end to base + gi.trace(&trace, end, NULL, NULL, org_, cent->currentState.clientNum, traceMask, (EG2_Collision)0, 0); + } else { // tracing from base to end + gi.trace(&trace, org_, NULL, NULL, end, cent->currentState.clientNum, traceMask | CONTENTS_WATER | CONTENTS_SLIME, (EG2_Collision)0, 0); } - if ( trace.fraction < 1.0f ) - { - if ( (trace.contents&CONTENTS_WATER) || (trace.contents&CONTENTS_SLIME) ) - { - if ( !noMarks ) - { + if (trace.fraction < 1.0f) { + if ((trace.contents & CONTENTS_WATER) || (trace.contents & CONTENTS_SLIME)) { + if (!noMarks) { /* if ( !(cent->gent->client->ps.saberEventFlags&SEF_INWATER) ) { } */ - if ( !Q_irand( 0, 10 ) ) - {//FIXME: don't do this this way.... :) - vec3_t spot; - VectorCopy( trace.endpos, spot ); + if (!Q_irand(0, 10)) { // FIXME: don't do this this way.... :) + vec3_t spot; + VectorCopy(trace.endpos, spot); spot[2] += 4; - if ( Q_irand( 1, client->ps.saber[saberNum].numBlades ) == 1 ) - { - theFxScheduler.PlayEffect( "saber/boil", spot ); - cgi_S_StartSound ( spot, -1, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/hitwater.wav" ) ); + if (Q_irand(1, client->ps.saber[saberNum].numBlades) == 1) { + theFxScheduler.PlayEffect("saber/boil", spot); + cgi_S_StartSound(spot, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/saber/hitwater.wav")); } } - //cent->gent->client->ps.saberEventFlags |= SEF_INWATER; - //don't do other trace + // cent->gent->client->ps.saberEventFlags |= SEF_INWATER; + // don't do other trace } i = 1; - } - else - { - if ( !noMarks ) - { - if ( ( !WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS) ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS2) ) ) - { - if ( !(trace.surfaceFlags & SURF_NOIMPACT) // never spark on sky - && (trace.entityNum == ENTITYNUM_WORLD || cg_entities[trace.entityNum].currentState.solid == SOLID_BMODEL) - && Q_irand( 1, client->ps.saber[saberNum].numBlades ) == 1 ) - { - //was "sparks/spark" - theFxScheduler.PlayEffect( "sparks/spark_nosnd", trace.endpos, trace.plane.normal ); + } else { + if (!noMarks) { + if ((!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS)) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS2))) { + if (!(trace.surfaceFlags & SURF_NOIMPACT) // never spark on sky + && (trace.entityNum == ENTITYNUM_WORLD || cg_entities[trace.entityNum].currentState.solid == SOLID_BMODEL) && + Q_irand(1, client->ps.saber[saberNum].numBlades) == 1) { + // was "sparks/spark" + theFxScheduler.PlayEffect("sparks/spark_nosnd", trace.endpos, trace.plane.normal); } } // All I need is a bool to mark whether I have a previous point to work with. //....come up with something better.. - if ( client->ps.saber[saberNum].blade[bladeNum].trail.haveOldPos[i] ) - { - if ( trace.entityNum == ENTITYNUM_WORLD || (cg_entities[trace.entityNum].currentState.eFlags & EF_PERMANENT) || cg_entities[trace.entityNum].currentState.eType == ET_TERRAIN ) - {//only put marks on architecture - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS)) - || (WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS2)) ) - { + if (client->ps.saber[saberNum].blade[bladeNum].trail.haveOldPos[i]) { + if (trace.entityNum == ENTITYNUM_WORLD || (cg_entities[trace.entityNum].currentState.eFlags & EF_PERMANENT) || + cg_entities[trace.entityNum].currentState.eType == ET_TERRAIN) { // only put marks on architecture + if ((!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS)) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS2))) { // Let's do some cool burn/glowing mark bits!!! - CG_CreateSaberMarks( client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i], trace.endpos, trace.plane.normal ); + CG_CreateSaberMarks(client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i], trace.endpos, trace.plane.normal); - if ( Q_irand( 1, client->ps.saber[saberNum].numBlades ) == 1 ) - { - //make a sound - if ( cg.time - cent->gent->client->ps.saberHitWallSoundDebounceTime >= 100 ) - {//ugh, need to have a real sound debouncer... or do this game-side + if (Q_irand(1, client->ps.saber[saberNum].numBlades) == 1) { + // make a sound + if (cg.time - cent->gent->client->ps.saberHitWallSoundDebounceTime >= + 100) { // ugh, need to have a real sound debouncer... or do this game-side cent->gent->client->ps.saberHitWallSoundDebounceTime = cg.time; - cgi_S_StartSound ( cent->lerpOrigin, cent->currentState.clientNum, CHAN_ITEM, cgi_S_RegisterSound( va ( "sound/weapons/saber/saberhitwall%d.wav", Q_irand( 1, 3 ) ) ) ); + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.clientNum, CHAN_ITEM, + cgi_S_RegisterSound(va("sound/weapons/saber/saberhitwall%d.wav", Q_irand(1, 3)))); } } } - } - else if ( !i ) - {//can put marks on G2 clients (but only on base to tip trace) + } else if (!i) { // can put marks on G2 clients (but only on base to tip trace) gentity_t *hitEnt = &g_entities[trace.entityNum]; vec3_t uaxis, splashBackDir; VectorSubtract(client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i], trace.endpos, uaxis); - VectorScale( axis_[0], -1, splashBackDir ); - //FIXME: if not hitting the first model on the enemy, don't do this! - CG_SaberDoWeaponHitMarks( client, (scent!=NULL?scent->gent:NULL), hitEnt, saberNum, bladeNum, trace.endpos, axis_[0], uaxis, splashBackDir, 0.25f ); + VectorScale(axis_[0], -1, splashBackDir); + // FIXME: if not hitting the first model on the enemy, don't do this! + CG_SaberDoWeaponHitMarks(client, (scent != NULL ? scent->gent : NULL), hitEnt, saberNum, bladeNum, trace.endpos, axis_[0], + uaxis, splashBackDir, 0.25f); } - } - else - { + } else { // if we impact next frame, we'll mark a slash mark client->ps.saber[saberNum].blade[bladeNum].trail.haveOldPos[i] = qtrue; } @@ -6518,34 +5447,34 @@ Ghoul2 Insert End } // stash point so we can connect-the-dots later - VectorCopy( trace.endpos, client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i] ); - VectorCopy( trace.plane.normal, client->ps.saber[saberNum].blade[bladeNum].trail.oldNormal[i] ); - - if ( !i && trace.contents&(CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_SHOTCLIP) ) - { //Now that we don't let the blade go through walls, we need to shorten the blade when it hits one - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].length * trace.fraction;//this will stop damage from going through walls - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length <= 0.1f ) - {//SIGH... hack so it doesn't play the saber turn-on sound that plays when you first turn the saber on (assumed when saber is active but length is zero) - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = 0.1f;//FIXME: may go through walls still?? + VectorCopy(trace.endpos, client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i]); + VectorCopy(trace.plane.normal, client->ps.saber[saberNum].blade[bladeNum].trail.oldNormal[i]); + + if (!i && + trace.contents & (CONTENTS_SOLID | CONTENTS_TERRAIN | + CONTENTS_SHOTCLIP)) { // Now that we don't let the blade go through walls, we need to shorten the blade when it hits one + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length * trace.fraction; // this will stop damage from going through walls + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length <= + 0.1f) { // SIGH... hack so it doesn't play the saber turn-on sound that plays when you first turn the saber on (assumed when saber is + // active but length is zero) + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = 0.1f; // FIXME: may go through walls still?? } - //FIXME: should probably re-extend instantly, not use the "turning-on" growth rate + // FIXME: should probably re-extend instantly, not use the "turning-on" growth rate } - } - else - { + } else { cent->gent->client->ps.saberEventFlags &= ~SEF_INWATER; - if ( client->ps.saber[saberNum].blade[bladeNum].trail.haveOldPos[i] ) - { - if ( !noMarks ) - { - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS)) - || (WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && !(client->ps.saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS2)) ) - { + if (client->ps.saber[saberNum].blade[bladeNum].trail.haveOldPos[i]) { + if (!noMarks) { + if ((!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS)) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + !(client->ps.saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS2))) { // Hmmm, no impact this frame, but we have an old point // Let's put the mark there, we should use an endcap mark to close the line, but we // can probably just get away with a round mark - //CG_ImpactMark( cgs.media.rivetMarkShader, client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i], client->ps.saber[saberNum].blade[bladeNum].trail.oldNormal[i], - // 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); + // CG_ImpactMark( cgs.media.rivetMarkShader, client->ps.saber[saberNum].blade[bladeNum].trail.oldPos[i], + // client->ps.saber[saberNum].blade[bladeNum].trail.oldNormal[i], 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); } } } @@ -6558,104 +5487,93 @@ Ghoul2 Insert End // Added 10/02/02 by Aurelio Reis. // If the Blade is not active, leave here; we do not Render it! -/* if ( cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD ) - {//draws no blade or trail - //FIXME: draw some sort of energy halo and motion trail! - return; - } -*/ - if ( !client->ps.saber[saberNum].blade[bladeNum].active && client->ps.saber[saberNum].blade[bladeNum].length <= 0 ) - { + /* if ( cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD ) + {//draws no blade or trail + //FIXME: draw some sort of energy halo and motion trail! + return; + } + */ + if (!client->ps.saber[saberNum].blade[bladeNum].active && client->ps.saber[saberNum].blade[bladeNum].length <= 0) { return; } - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && client->ps.saber[saberNum].trailStyle < 2 ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && client->ps.saber[saberNum].trailStyle2 < 2 ) ) - {//okay to draw the trail - saberTrail_t *saberTrail = &client->ps.saber[saberNum].blade[bladeNum].trail; + if ((!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && client->ps.saber[saberNum].trailStyle < 2) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && client->ps.saber[saberNum].trailStyle2 < 2)) { // okay to draw the trail + saberTrail_t *saberTrail = &client->ps.saber[saberNum].blade[bladeNum].trail; -#define SABER_TRAIL_TIME 40.0f +#define SABER_TRAIL_TIME 40.0f // if we happen to be timescaled or running in a high framerate situation, we don't want to flood // the system with very small trail slices...but perhaps doing it by distance would yield better results? - if ( saberTrail->lastTime > cg.time ) - {//after a pause, cg.time jumps ahead in time for one frame - //and lastTime gets set to that and will freak out, so, since - //it's never valid for saberTrail->lastTime to be > cg.time, - //cap it to cg.time here + if (saberTrail->lastTime > cg.time) { // after a pause, cg.time jumps ahead in time for one frame + // and lastTime gets set to that and will freak out, so, since + // it's never valid for saberTrail->lastTime to be > cg.time, + // cap it to cg.time here saberTrail->lastTime = cg.time; } - if ( cg.time > saberTrail->lastTime + 2 && saberTrail->inAction ) // 2ms + if (cg.time > saberTrail->lastTime + 2 && saberTrail->inAction) // 2ms { - if ( saberTrail->inAction && cg.time < saberTrail->lastTime + 300 ) // if we have a stale segment, don't draw until we have a fresh one + if (saberTrail->inAction && cg.time < saberTrail->lastTime + 300) // if we have a stale segment, don't draw until we have a fresh one { - vec3_t rgb1={255,255,255}; + vec3_t rgb1 = {255, 255, 255}; - if ( cent->gent->client->ps.saber[saberNum].type != SABER_SITH_SWORD - && ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) || client->ps.saber[saberNum].trailStyle != 1 ) - && ( !WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) || client->ps.saber[saberNum].trailStyle2 != 1 ) - ) - { - switch( client->ps.saber[saberNum].blade[bladeNum].color ) - { - case SABER_RED: - VectorSet( rgb1, 255.0f, 0.0f, 0.0f ); - break; - case SABER_ORANGE: - VectorSet( rgb1, 255.0f, 64.0f, 0.0f ); - break; - case SABER_YELLOW: - VectorSet( rgb1, 255.0f, 255.0f, 0.0f ); - break; - case SABER_GREEN: - VectorSet( rgb1, 0.0f, 255.0f, 0.0f ); - break; - case SABER_BLUE: - VectorSet( rgb1, 0.0f, 64.0f, 255.0f ); - break; - case SABER_PURPLE: - VectorSet( rgb1, 220.0f, 0.0f, 255.0f ); - break; + if (cent->gent->client->ps.saber[saberNum].type != SABER_SITH_SWORD && + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) || client->ps.saber[saberNum].trailStyle != 1) && + (!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) || client->ps.saber[saberNum].trailStyle2 != 1)) { + switch (client->ps.saber[saberNum].blade[bladeNum].color) { + case SABER_RED: + VectorSet(rgb1, 255.0f, 0.0f, 0.0f); + break; + case SABER_ORANGE: + VectorSet(rgb1, 255.0f, 64.0f, 0.0f); + break; + case SABER_YELLOW: + VectorSet(rgb1, 255.0f, 255.0f, 0.0f); + break; + case SABER_GREEN: + VectorSet(rgb1, 0.0f, 255.0f, 0.0f); + break; + case SABER_BLUE: + VectorSet(rgb1, 0.0f, 64.0f, 255.0f); + break; + case SABER_PURPLE: + VectorSet(rgb1, 220.0f, 0.0f, 255.0f); + break; } } float diff = cg.time - saberTrail->lastTime; // I'm not sure that clipping this is really the best idea - if ( diff <= SABER_TRAIL_TIME * 2 ) - { + if (diff <= SABER_TRAIL_TIME * 2) { // build a quad CTrail *fx = new CTrail; float duration; - if ( cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD - || (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && client->ps.saber[saberNum].trailStyle == 1 ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && client->ps.saber[saberNum].trailStyle2 == 1 ) - ) - { + if (cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD || + (!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && client->ps.saber[saberNum].trailStyle == 1) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && client->ps.saber[saberNum].trailStyle2 == 1)) { fx->mShader = cgs.media.swordTrailShader; - duration = saberTrail->duration/2.0f; // stay around twice as long - VectorSet( rgb1, 32.0f, 32.0f, 32.0f ); // make the sith sword trail pretty faint - } - else - { + duration = saberTrail->duration / 2.0f; // stay around twice as long + VectorSet(rgb1, 32.0f, 32.0f, 32.0f); // make the sith sword trail pretty faint + } else { fx->mShader = cgs.media.saberBlurShader; - duration = saberTrail->duration/5.0f; + duration = saberTrail->duration / 5.0f; } - float oldAlpha = 1.0f - ( diff / duration ); + float oldAlpha = 1.0f - (diff / duration); // Go from new muzzle to new end...then to old end...back down to old muzzle...finally // connect back to the new muzzle...this is our trail quad - VectorCopy( org_, fx->mVerts[0].origin ); - VectorMA( end, 3.0f, axis_[0], fx->mVerts[1].origin ); + VectorCopy(org_, fx->mVerts[0].origin); + VectorMA(end, 3.0f, axis_[0], fx->mVerts[1].origin); - VectorCopy( saberTrail->tip, fx->mVerts[2].origin ); - VectorCopy( saberTrail->base, fx->mVerts[3].origin ); + VectorCopy(saberTrail->tip, fx->mVerts[2].origin); + VectorCopy(saberTrail->base, fx->mVerts[3].origin); // New muzzle - VectorCopy( rgb1, fx->mVerts[0].rgb ); + VectorCopy(rgb1, fx->mVerts[0].rgb); fx->mVerts[0].alpha = 255.0f; fx->mVerts[0].ST[0] = 0.0f; @@ -6664,7 +5582,7 @@ Ghoul2 Insert End fx->mVerts[0].destST[1] = 0.99f; // new tip - VectorCopy( rgb1, fx->mVerts[1].rgb ); + VectorCopy(rgb1, fx->mVerts[1].rgb); fx->mVerts[1].alpha = 255.0f; fx->mVerts[1].ST[0] = 0.0f; @@ -6673,7 +5591,7 @@ Ghoul2 Insert End fx->mVerts[1].destST[1] = 0.0f; // old tip - VectorCopy( rgb1, fx->mVerts[2].rgb ); + VectorCopy(rgb1, fx->mVerts[2].rgb); fx->mVerts[2].alpha = 255.0f; fx->mVerts[2].ST[0] = 0.99f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -6682,7 +5600,7 @@ Ghoul2 Insert End fx->mVerts[2].destST[1] = 0.0f; // old muzzle - VectorCopy( rgb1, fx->mVerts[3].rgb ); + VectorCopy(rgb1, fx->mVerts[3].rgb); fx->mVerts[3].alpha = 255.0f; fx->mVerts[3].ST[0] = 0.99f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -6690,64 +5608,52 @@ Ghoul2 Insert End fx->mVerts[3].destST[0] = 0.99f + fx->mVerts[2].ST[0]; fx->mVerts[3].destST[1] = 0.99f; - // fx->SetFlags( FX_USE_ALPHA ); - FX_AddPrimitive( (CEffect**)&fx, duration );//SABER_TRAIL_TIME ); + // fx->SetFlags( FX_USE_ALPHA ); + FX_AddPrimitive((CEffect **)&fx, duration); // SABER_TRAIL_TIME ); } } // we must always do this, even if we aren't active..otherwise we won't know where to pick up from - VectorCopy( org_, saberTrail->base ); - VectorMA( end, 3.0f, axis_[0], saberTrail->tip ); + VectorCopy(org_, saberTrail->base); + VectorMA(end, 3.0f, axis_[0], saberTrail->tip); saberTrail->lastTime = cg.time; } } - if ( cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD) - { + if (cent->gent->client->ps.saber[saberNum].type == SABER_SITH_SWORD) { // don't need to do nuthin else return; } qboolean noDlight = qfalse; - if ( client->ps.saber[saberNum].numBlades >= 3 - || (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && (client->ps.saber[saberNum].saberFlags2&SFL2_NO_DLIGHT) ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && (client->ps.saber[saberNum].saberFlags2&SFL2_NO_DLIGHT2) ) - ) - { + if (client->ps.saber[saberNum].numBlades >= 3 || + (!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && (client->ps.saber[saberNum].saberFlags2 & SFL2_NO_DLIGHT)) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && (client->ps.saber[saberNum].saberFlags2 & SFL2_NO_DLIGHT2))) { noDlight = qtrue; } - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && (client->ps.saber[saberNum].saberFlags2&SFL2_NO_BLADE) ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->ps.saber[saberNum], bladeNum ) && (client->ps.saber[saberNum].saberFlags2&SFL2_NO_BLADE2) ) ) - {//don't draw a blade - if ( !noDlight ) - {//but still do dlight - CG_DoSaberLight( &client->ps.saber[saberNum] ); + if ((!WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && (client->ps.saber[saberNum].saberFlags2 & SFL2_NO_BLADE)) || + (WP_SaberBladeUseSecondBladeStyle(&client->ps.saber[saberNum], bladeNum) && + (client->ps.saber[saberNum].saberFlags2 & SFL2_NO_BLADE2))) { // don't draw a blade + if (!noDlight) { // but still do dlight + CG_DoSaberLight(&client->ps.saber[saberNum]); } return; } // Pass in the renderfx flags attached to the saber weapon model...this is done so that saber glows // will get rendered properly in a mirror...not sure if this is necessary?? - CG_DoSaber( - org_, axis_[0], length, - client->ps.saber[saberNum].blade[bladeNum].lengthMax, - client->ps.saber[saberNum].blade[bladeNum].radius, - client->ps.saber[saberNum].blade[bladeNum].color, - renderfx, (qboolean)!noDlight ); + CG_DoSaber(org_, axis_[0], length, client->ps.saber[saberNum].blade[bladeNum].lengthMax, client->ps.saber[saberNum].blade[bladeNum].radius, + client->ps.saber[saberNum].blade[bladeNum].color, renderfx, (qboolean)!noDlight); } -void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles ) -{ - //FIXME: if this is a dropped saber, it could be possible that it's the second saber? - if ( cent->gent->client ) - { - for ( int i = 0; i < cent->gent->client->ps.saber[0].numBlades;i++ ) - { - CG_AddSaberBladeGo( cent, scent, saber, renderfx, modelIndex, origin, angles, 0, i ); +void CG_AddSaberBlade(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles) { + // FIXME: if this is a dropped saber, it could be possible that it's the second saber? + if (cent->gent->client) { + for (int i = 0; i < cent->gent->client->ps.saber[0].numBlades; i++) { + CG_AddSaberBladeGo(cent, scent, saber, renderfx, modelIndex, origin, angles, 0, i); } - if ( cent->gent->client->ps.saber[0].numBlades > 2 ) - {// add blended light - CG_DoSaberLight( ¢->gent->client->ps.saber[0] ); + if (cent->gent->client->ps.saber[0].numBlades > 2) { // add blended light + CG_DoSaberLight(¢->gent->client->ps.saber[0]); } } } @@ -6811,360 +5717,314 @@ CG_Player =============== */ -extern qboolean G_GetRootSurfNameWithVariant( gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize ); -extern qboolean G_ControlledByPlayer( gentity_t *self ); +extern qboolean G_GetRootSurfNameWithVariant(gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize); +extern qboolean G_ControlledByPlayer(gentity_t *self); extern qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles); -int cg_saberOnSoundTime[MAX_GENTITIES] = {0}; +int cg_saberOnSoundTime[MAX_GENTITIES] = {0}; -void CG_Player( centity_t *cent ) { - clientInfo_t *ci; - qboolean shadow, staticScale = qfalse; - float shadowPlane; - const weaponData_t *wData = NULL; +void CG_Player(centity_t *cent) { + clientInfo_t *ci; + qboolean shadow, staticScale = qfalse; + float shadowPlane; + const weaponData_t *wData = NULL; - if ( cent->currentState.eFlags & EF_NODRAW ) - { + if (cent->currentState.eFlags & EF_NODRAW) { return; } - //make sure this thing has a gent and client - if(!cent->gent) - { + // make sure this thing has a gent and client + if (!cent->gent) { return; } - if(!cent->gent->client) - { + if (!cent->gent->client) { return; } - if( cent->gent->s.number == 0 && cg.weaponSelect == WP_NONE && cg.zoomMode == 1 ) - { + if (cent->gent->s.number == 0 && cg.weaponSelect == WP_NONE && cg.zoomMode == 1) { // HACK return; } calcedMp = qfalse; - //Get the player's light level for stealth calculations - CG_GetPlayerLightLevel( cent ); + // Get the player's light level for stealth calculations + CG_GetPlayerLightLevel(cent); - if ((in_camera) && cent->currentState.clientNum == 0 ) // If player in camera then no need for shadow + if ((in_camera) && cent->currentState.clientNum == 0) // If player in camera then no need for shadow { return; } - if(cent->currentState.number == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) + if (cent->currentState.number == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) { calcedMp = qtrue; } ci = ¢->gent->client->clientInfo; - if ( !ci->infoValid ) - { + if (!ci->infoValid) { return; } G_RagDoll(cent->gent, cent->lerpAngles); - if ( cent->currentState.weapon ) - { + if (cent->currentState.weapon) { wData = &weaponData[cent->currentState.weapon]; } -/* -Ghoul2 Insert Start -*/ - if (cent->gent->ghoul2.size()) //do we have ghoul models attached? + /* + Ghoul2 Insert Start + */ + if (cent->gent->ghoul2.size()) // do we have ghoul models attached? { - refEntity_t ent; - vec3_t tempAngles; - memset (&ent, 0, sizeof(ent)); + refEntity_t ent; + vec3_t tempAngles; + memset(&ent, 0, sizeof(ent)); - //FIXME: if at all possible, do all our sets before our gets to do only *1* G2 skeleton transform per render frame + // FIXME: if at all possible, do all our sets before our gets to do only *1* G2 skeleton transform per render frame CG_SetGhoul2Info(&ent, cent); // Weapon sounds may need to be stopped, so check now - CG_StopWeaponSounds( cent ); + CG_StopWeaponSounds(cent); // add powerups floating behind the player - CG_PlayerPowerups( cent ); + CG_PlayerPowerups(cent); // add the shadow - //FIXME: funcs that modify our origin below will cause the shadow to be in the wrong spot - shadow = CG_PlayerShadow( cent, &shadowPlane ); + // FIXME: funcs that modify our origin below will cause the shadow to be in the wrong spot + shadow = CG_PlayerShadow(cent, &shadowPlane); // add a water splash if partially in and out of water - CG_PlayerSplash( cent ); + CG_PlayerSplash(cent); // get the player model information ent.renderfx = 0; - if ( !cg.renderingThirdPerson || cg.zoomMode ) - {//in first person or zoomed in - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) - {//no viewentity - if ( cent->currentState.number == cg.snap->ps.clientNum ) - {//I am the player - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + if (!cg.renderingThirdPerson || cg.zoomMode) { // in first person or zoomed in + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // no viewentity + if (cent->currentState.number == cg.snap->ps.clientNum) { // I am the player + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } } - } - else if ( cent->currentState.number == cg.snap->ps.viewEntity ) - {//I am the view entity - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using first person saber test or, if so, not using saber - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + } else if (cent->currentState.number == cg.snap->ps.viewEntity) { // I am the view entity + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using first person saber test or, if so, not using saber + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } } } - if ( cent->gent->client->ps.powerups[PW_DISINT_2] > cg.time ) - {//ghost! - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors - } - else if (cg_shadows.integer == 2 && (ent.renderfx & RF_THIRD_PERSON)) - { //show stencil shadow in first person now because we can -rww + if (cent->gent->client->ps.powerups[PW_DISINT_2] > cg.time) { // ghost! + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + } else if (cg_shadows.integer == 2 && (ent.renderfx & RF_THIRD_PERSON)) { // show stencil shadow in first person now because we can -rww ent.renderfx |= RF_SHADOW_ONLY; } - if ( (cg_shadows.integer == 2 && !in_camera) || (cg_shadows.integer == 3 && shadow) ) - { + if ((cg_shadows.integer == 2 && !in_camera) || (cg_shadows.integer == 3 && shadow)) { ent.renderfx |= RF_SHADOW_PLANE; } ent.shadowPlane = shadowPlane; - ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all - if ( cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT ) - { - ent.renderfx |= RF_MORELIGHT; //bigger than normal min light + ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + if (cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT) { + ent.renderfx |= RF_MORELIGHT; // bigger than normal min light } - CG_RegisterWeapon( cent->currentState.weapon ); + CG_RegisterWeapon(cent->currentState.weapon); -//--------------- + //--------------- Vehicle_t *pVeh; - if ( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON && cent->gent && cent->gent->health > 0 && cent->gent->owner ) - { - centity_t *chair = &cg_entities[cent->gent->owner->s.number]; - if ( chair && chair->gent ) - { - vec3_t temp; - mdxaBone_t boltMatrix; + if (cent->currentState.eFlags & EF_LOCKED_TO_WEAPON && cent->gent && cent->gent->health > 0 && cent->gent->owner) { + centity_t *chair = &cg_entities[cent->gent->owner->s.number]; + if (chair && chair->gent) { + vec3_t temp; + mdxaBone_t boltMatrix; - //NOTE: call this so it updates on the server and client - if ( chair->gent->bounceCount ) - {//EWeb + // NOTE: call this so it updates on the server and client + if (chair->gent->bounceCount) { // EWeb // We'll set the turret angles directly - VectorClear( temp ); - VectorClear( chair->gent->pos1 ); + VectorClear(temp); + VectorClear(chair->gent->pos1); temp[PITCH] = cent->lerpAngles[PITCH]; - chair->gent->pos1[YAW] = AngleSubtract( cent->lerpAngles[YAW], chair->gent->s.angles[YAW] );//remember which dir our turret is facing for later + chair->gent->pos1[YAW] = + AngleSubtract(cent->lerpAngles[YAW], chair->gent->s.angles[YAW]); // remember which dir our turret is facing for later cent->lerpAngles[ROLL] = 0; - BG_G2SetBoneAngles( chair, chair->gent, chair->gent->lowerLumbarBone, chair->gent->pos1, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, cgs.model_draw ); - BG_G2SetBoneAngles( chair, chair->gent, chair->gent->upperLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, cgs.model_draw ); - } - else - { + BG_G2SetBoneAngles(chair, chair->gent, chair->gent->lowerLumbarBone, chair->gent->pos1, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, + NEGATIVE_Y, cgs.model_draw); + BG_G2SetBoneAngles(chair, chair->gent, chair->gent->upperLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, + cgs.model_draw); + } else { // We'll set the turret yaw directly - VectorClear( chair->gent->s.apos.trBase ); - VectorClear( temp ); + VectorClear(chair->gent->s.apos.trBase); + VectorClear(temp); chair->gent->s.apos.trBase[YAW] = cent->lerpAngles[YAW]; temp[PITCH] = -cent->lerpAngles[PITCH]; cent->lerpAngles[ROLL] = 0; - BG_G2SetBoneAngles( chair, chair->gent, chair->gent->lowerLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, cgs.model_draw ); + BG_G2SetBoneAngles(chair, chair->gent, chair->gent->lowerLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, + cgs.model_draw); } - //gi.G2API_SetBoneAngles( &chair->gent->ghoul2[0], "swivel_bone", temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, cgs.model_draw ); - VectorCopy( temp, chair->gent->lastAngles ); + // gi.G2API_SetBoneAngles( &chair->gent->ghoul2[0], "swivel_bone", temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, + // cgs.model_draw ); + VectorCopy(temp, chair->gent->lastAngles); - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); // Getting the seat bolt here - gi.G2API_GetBoltMatrix( chair->gent->ghoul2, chair->gent->playerModel, chair->gent->headBolt, - &boltMatrix, chair->gent->s.apos.trBase, chair->gent->currentOrigin, cg.time, - cgs.model_draw, chair->currentState.modelScale ); - - if ( chair->gent->bounceCount ) - {//put behind it, not in chair - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, chair->gent->pos3 ); + gi.G2API_GetBoltMatrix(chair->gent->ghoul2, chair->gent->playerModel, chair->gent->headBolt, &boltMatrix, chair->gent->s.apos.trBase, + chair->gent->currentOrigin, cg.time, cgs.model_draw, chair->currentState.modelScale); + + if (chair->gent->bounceCount) { // put behind it, not in chair + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, chair->gent->pos3); chair->gent->pos3[2] = 0; - VectorNormalizeFast( chair->gent->pos3 ); - VectorMA( ent.origin, -44.0f, chair->gent->pos3, ent.origin ); + VectorNormalizeFast(chair->gent->pos3); + VectorMA(ent.origin, -44.0f, chair->gent->pos3, ent.origin); ent.origin[2] = cent->lerpOrigin[2]; - cent->lerpAngles[YAW] = vectoyaw( chair->gent->pos3 ); + cent->lerpAngles[YAW] = vectoyaw(chair->gent->pos3); cent->lerpAngles[ROLL] = 0; - CG_G2PlayerAngles( cent, ent.axis, tempAngles); + CG_G2PlayerAngles(cent, ent.axis, tempAngles); calcedMp = qtrue; - } - else - {//sitting in it + } else { // sitting in it // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); - VectorCopy( ent.origin, chair->gent->pos2 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, chair->gent->pos3 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, chair->gent->pos4 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); + VectorCopy(ent.origin, chair->gent->pos2); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, chair->gent->pos3); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, chair->gent->pos4); - AnglesToAxis( cent->lerpAngles, ent.axis ); - VectorCopy( cent->lerpAngles, tempAngles);//tempAngles is needed a lot below + AnglesToAxis(cent->lerpAngles, ent.axis); + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below } - VectorCopy( ent.origin, ent.oldorigin ); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); // FIXME: Mike claims that hacking the eyepoint will make them shoot at me.......so, // we move up from the seat bolt and store off that point. - // VectorMA( ent.origin, -20, chair->gent->pos3, cent->gent->client->renderInfo.eyePoint ); - // VectorMA( cent->gent->client->renderInfo.eyePoint, 40, chair->gent->pos4, cent->gent->client->renderInfo.eyePoint ); + // VectorMA( ent.origin, -20, chair->gent->pos3, cent->gent->client->renderInfo.eyePoint ); + // VectorMA( cent->gent->client->renderInfo.eyePoint, 40, chair->gent->pos4, cent->gent->client->renderInfo.eyePoint ); } - } - else if ( ( pVeh = G_IsRidingVehicle( cent->gent ) ) != NULL ) - {//rider - CG_G2PlayerAngles( cent, ent.axis, tempAngles); - //Deal with facial expressions - CG_G2PlayerHeadAnims( cent ); + } else if ((pVeh = G_IsRidingVehicle(cent->gent)) != NULL) { // rider + CG_G2PlayerAngles(cent, ent.axis, tempAngles); + // Deal with facial expressions + CG_G2PlayerHeadAnims(cent); centity_t *vehEnt = &cg_entities[cent->gent->owner->s.number]; - CG_CalcEntityLerpPositions( vehEnt ); + CG_CalcEntityLerpPositions(vehEnt); // Get the driver tag. - mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( vehEnt->gent->ghoul2, vehEnt->gent->playerModel, vehEnt->gent->crotchBolt, - &boltMatrix, vehEnt->lerpAngles, vehEnt->lerpOrigin, (cg.time?cg.time:level.time), NULL, vehEnt->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); + mdxaBone_t boltMatrix; + gi.G2API_GetBoltMatrix(vehEnt->gent->ghoul2, vehEnt->gent->playerModel, vehEnt->gent->crotchBolt, &boltMatrix, vehEnt->lerpAngles, + vehEnt->lerpOrigin, (cg.time ? cg.time : level.time), NULL, vehEnt->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); float savPitch = cent->lerpAngles[PITCH]; - VectorCopy( vehEnt->lerpAngles, cent->lerpAngles ); - AnglesToAxis( cent->lerpAngles, ent.axis ); + VectorCopy(vehEnt->lerpAngles, cent->lerpAngles); + AnglesToAxis(cent->lerpAngles, ent.axis); - VectorCopy( ent.origin, ent.oldorigin ); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); - VectorCopy( cent->lerpAngles, tempAngles );//tempAngles is needed a lot below - VectorCopy( ent.origin, cent->lerpOrigin ); - VectorCopy( ent.origin, cent->gent->client->ps.origin ); - //bah, keep our pitch! + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below + VectorCopy(ent.origin, cent->lerpOrigin); + VectorCopy(ent.origin, cent->gent->client->ps.origin); + // bah, keep our pitch! cent->lerpAngles[PITCH] = savPitch; - } - else if ( ( (cent->gent->client->ps.eFlags&EF_HELD_BY_RANCOR)||(cent->gent->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - && cent->gent && cent->gent->activator ) - { - centity_t *monster = &cg_entities[cent->gent->activator->s.number]; - if ( monster && monster->gent && monster->gent->inuse && monster->gent->health > 0 ) - { - mdxaBone_t boltMatrix; + } else if (((cent->gent->client->ps.eFlags & EF_HELD_BY_RANCOR) || (cent->gent->client->ps.eFlags & EF_HELD_BY_WAMPA)) && cent->gent && + cent->gent->activator) { + centity_t *monster = &cg_entities[cent->gent->activator->s.number]; + if (monster && monster->gent && monster->gent->inuse && monster->gent->health > 0) { + mdxaBone_t boltMatrix; // Getting the bolt here - //in mouth + // in mouth int boltIndex = monster->gent->gutBolt; - if ( monster->gent->count == 1 ) - {//in hand + if (monster->gent->count == 1) { // in hand boltIndex = monster->gent->handRBolt; } vec3_t rancAngles = {0}; rancAngles[YAW] = monster->lerpAngles[YAW]; - gi.G2API_GetBoltMatrix( monster->gent->ghoul2, monster->gent->playerModel, boltIndex, - &boltMatrix, rancAngles, monster->lerpOrigin, cg.time, - cgs.model_draw, monster->currentState.modelScale ); + gi.G2API_GetBoltMatrix(monster->gent->ghoul2, monster->gent->playerModel, boltIndex, &boltMatrix, rancAngles, monster->lerpOrigin, cg.time, + cgs.model_draw, monster->currentState.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); - if ( (cent->gent->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent.axis[0] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_X, ent.axis[1] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Z, ent.axis[2] ); - } - else if ( monster->gent->count == 1 ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent.axis[0] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_X, ent.axis[1] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Z, ent.axis[2] ); - } - else - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Z, ent.axis[0] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent.axis[1] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, ent.axis[2] ); - } - //FIXME: this is messing up our axis and turning us inside-out - if ( cent->gent->client->isRagging ) - {//hack, ragdoll has you way at bottom of bounding box - VectorMA( ent.origin, 32, ent.axis[2], ent.origin ); - } - VectorCopy( ent.origin, ent.oldorigin ); - VectorCopy( ent.origin, ent.lightingOrigin ); - - vectoangles( ent.axis[0], cent->lerpAngles ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); + if ((cent->gent->client->ps.eFlags & EF_HELD_BY_WAMPA)) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent.axis[0]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_X, ent.axis[1]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, ent.axis[2]); + } else if (monster->gent->count == 1) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent.axis[0]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_X, ent.axis[1]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, ent.axis[2]); + } else { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, ent.axis[0]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent.axis[1]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, ent.axis[2]); + } + // FIXME: this is messing up our axis and turning us inside-out + if (cent->gent->client->isRagging) { // hack, ragdoll has you way at bottom of bounding box + VectorMA(ent.origin, 32, ent.axis[2], ent.origin); + } + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); + + vectoangles(ent.axis[0], cent->lerpAngles); vec3_t temp; - vectoangles( ent.axis[2], temp ); + vectoangles(ent.axis[2], temp); cent->lerpAngles[ROLL] = -temp[PITCH]; - VectorCopy( cent->lerpAngles, tempAngles );//tempAngles is needed a lot below - VectorCopy( ent.origin, cent->lerpOrigin ); - VectorCopy( ent.origin, cent->gent->client->ps.origin ); - // if ( (cent->gent->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - // { - vectoangles( ent.axis[0], cent->lerpAngles ); - VectorCopy( cent->lerpAngles, tempAngles );//tempAngles is needed a lot below - // } - // else - // { - // //cent->gent->client->ps.viewangles[YAW] = cent->lerpAngles[YAW]; - // } - } - else - {//wtf happened to the guy holding me? Better get out + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below + VectorCopy(ent.origin, cent->lerpOrigin); + VectorCopy(ent.origin, cent->gent->client->ps.origin); + // if ( (cent->gent->client->ps.eFlags&EF_HELD_BY_WAMPA) ) + // { + vectoangles(ent.axis[0], cent->lerpAngles); + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below + // } + // else + // { + // //cent->gent->client->ps.viewangles[YAW] = cent->lerpAngles[YAW]; + // } + } else { // wtf happened to the guy holding me? Better get out cent->gent->activator = NULL; - cent->gent->client->ps.eFlags &= ~(EF_HELD_BY_WAMPA|EF_HELD_BY_RANCOR); + cent->gent->client->ps.eFlags &= ~(EF_HELD_BY_WAMPA | EF_HELD_BY_RANCOR); } - } - else if ( (cent->gent->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - && cent->gent - && cent->gent->activator ) - { - centity_t *sand_creature = &cg_entities[cent->gent->activator->s.number]; - if ( sand_creature && sand_creature->gent ) - { - mdxaBone_t boltMatrix; + } else if ((cent->gent->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) && cent->gent && cent->gent->activator) { + centity_t *sand_creature = &cg_entities[cent->gent->activator->s.number]; + if (sand_creature && sand_creature->gent) { + mdxaBone_t boltMatrix; // Getting the bolt here - //in hand + // in hand vec3_t scAngles = {0}; scAngles[YAW] = sand_creature->lerpAngles[YAW]; - gi.G2API_GetBoltMatrix( sand_creature->gent->ghoul2, sand_creature->gent->playerModel, sand_creature->gent->gutBolt, - &boltMatrix, scAngles, sand_creature->lerpOrigin, cg.time, - cgs.model_draw, sand_creature->currentState.modelScale ); + gi.G2API_GetBoltMatrix(sand_creature->gent->ghoul2, sand_creature->gent->playerModel, sand_creature->gent->gutBolt, &boltMatrix, scAngles, + sand_creature->lerpOrigin, cg.time, cgs.model_draw, sand_creature->currentState.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent.axis[0] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, ent.axis[1] ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Z, ent.axis[2] ); - //FIXME: this is messing up our axis and turning us inside-out - if ( cent->gent->client->isRagging ) - {//hack, ragdoll has you way at bottom of bounding box - VectorMA( ent.origin, 32, ent.axis[2], ent.origin ); - } - VectorCopy( ent.origin, ent.oldorigin ); - VectorCopy( ent.origin, ent.lightingOrigin ); - - vectoangles( ent.axis[0], cent->lerpAngles ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent.axis[0]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, ent.axis[1]); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, ent.axis[2]); + // FIXME: this is messing up our axis and turning us inside-out + if (cent->gent->client->isRagging) { // hack, ragdoll has you way at bottom of bounding box + VectorMA(ent.origin, 32, ent.axis[2], ent.origin); + } + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); + + vectoangles(ent.axis[0], cent->lerpAngles); vec3_t temp; - vectoangles( ent.axis[2], temp ); + vectoangles(ent.axis[2], temp); cent->lerpAngles[ROLL] = -temp[PITCH]; - VectorCopy( cent->lerpAngles, tempAngles );//tempAngles is needed a lot below - VectorCopy( ent.origin, cent->lerpOrigin ); - VectorCopy( ent.origin, cent->gent->client->ps.origin ); + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below + VectorCopy(ent.origin, cent->lerpOrigin); + VectorCopy(ent.origin, cent->gent->client->ps.origin); cent->gent->client->ps.viewangles[YAW] = cent->lerpAngles[YAW]; } - } - else - { -//--------------- - CG_G2PlayerAngles( cent, ent.axis, tempAngles); - //Deal with facial expressions - CG_G2PlayerHeadAnims( cent ); + } else { + //--------------- + CG_G2PlayerAngles(cent, ent.axis, tempAngles); + // Deal with facial expressions + CG_G2PlayerHeadAnims(cent); /* if ( cent->gent->client->ps.eFlags & EF_FORCE_DRAINED @@ -7174,25 +6034,21 @@ Ghoul2 Insert Start } else */ - { - VectorCopy( cent->lerpOrigin, ent.origin); - } + { VectorCopy(cent->lerpOrigin, ent.origin); } - if (ent.modelScale[2] && ent.modelScale[2] != 1.0f) - { + if (ent.modelScale[2] && ent.modelScale[2] != 1.0f) { ent.origin[2] += 24 * (ent.modelScale[2] - 1); } - VectorCopy( ent.origin, ent.oldorigin); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); } - if ( cent->gent && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { cent->gent->client->ps.legsYaw = tempAngles[YAW]; } ScaleModelAxis(&ent); -//HACK - add swoop model + // HACK - add swoop model /* if ( cent->currentState.vehicleIndex != VEHICLE_NONE && g_vehicleInfo[cent->currentState.vehicleIndex].type == VH_SPEEDER ) @@ -7210,271 +6066,219 @@ Ghoul2 Insert Start cgi_R_AddRefEntityToScene( &swoopEnt ); } */ -//HACK - add swoop model + // HACK - add swoop model -extern vmCvar_t cg_thirdPersonAlpha; + extern vmCvar_t cg_thirdPersonAlpha; - if ( (cent->gent->s.number == 0 || G_ControlledByPlayer( cent->gent )) ) - { + if ((cent->gent->s.number == 0 || G_ControlledByPlayer(cent->gent))) { float alpha = 1.0f; - if ( (cg.overrides.active&CG_OVERRIDE_3RD_PERSON_APH) ) - { + if ((cg.overrides.active & CG_OVERRIDE_3RD_PERSON_APH)) { alpha = cg.overrides.thirdPersonAlpha; - } - else - { + } else { alpha = cg_thirdPersonAlpha.value; } - if ( alpha < 1.0f ) - { + if (alpha < 1.0f) { ent.renderfx |= RF_ALPHA_FADE; ent.shaderRGBA[3] = (unsigned char)(alpha * 255.0f); } } - if ( cg_debugHealthBars.integer ) - { - if ( cent->gent && cent->gent->health > 0 && cent->gent->max_health > 0 ) - {//draw a health bar over them - CG_AddHealthBarEnt( cent->currentState.clientNum ); - } - } - CG_AddRefEntityWithPowerups( &ent, cent->currentState.powerups, cent ); - VectorCopy( tempAngles, cent->renderAngles ); - - //Initialize all these to *some* valid data - VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.handRPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.handLPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.footRPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.footLPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.torsoPoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.crotchPoint ); - if ( cent->currentState.number != 0 - || cg.renderingThirdPerson - || cg.snap->ps.stats[STAT_HEALTH] <= 0 - || ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//First person saber - ) - {//in some third person mode or NPC - //we don't override thes in pure 1st person because they will be set before this func - VectorCopy( ent.origin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles ); - if ( !cent->gent->client->ps.saberInFlight ) - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( ent.axis[0], cent->gent->client->renderInfo.muzzleDir ); + if (cg_debugHealthBars.integer) { + if (cent->gent && cent->gent->health > 0 && cent->gent->max_health > 0) { // draw a health bar over them + CG_AddHealthBarEnt(cent->currentState.clientNum); } } - //now try to get the right data + CG_AddRefEntityWithPowerups(&ent, cent->currentState.powerups, cent); + VectorCopy(tempAngles, cent->renderAngles); - mdxaBone_t boltMatrix; - vec3_t tempAxis, G2Angles = {0, tempAngles[YAW], 0}; + // Initialize all these to *some* valid data + VectorCopy(ent.origin, cent->gent->client->renderInfo.headPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.handRPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.handLPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.footRPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.footLPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.torsoPoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles); + VectorCopy(ent.origin, cent->gent->client->renderInfo.crotchPoint); + if (cent->currentState.number != 0 || cg.renderingThirdPerson || cg.snap->ps.stats[STAT_HEALTH] <= 0 || + (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // First person saber + ) { // in some third person mode or NPC + // we don't override thes in pure 1st person because they will be set before this func + VectorCopy(ent.origin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles); + if (!cent->gent->client->ps.saberInFlight) { + VectorCopy(ent.origin, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(ent.axis[0], cent->gent->client->renderInfo.muzzleDir); + } + } + // now try to get the right data - if ( cent->gent->handRBolt != -1 ) - { - //Get handRPoint - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.handRPoint ); + mdxaBone_t boltMatrix; + vec3_t tempAxis, G2Angles = {0, tempAngles[YAW], 0}; + + if (cent->gent->handRBolt != -1) { + // Get handRPoint + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.handRPoint); } - if ( cent->gent->handLBolt != -1 ) - { - //always get handLPoint too...? - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.handLPoint ); + if (cent->gent->handLBolt != -1) { + // always get handLPoint too...? + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.handLPoint); } - if ( cent->gent->footLBolt != -1 ) - { - //get the feet - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.footLPoint ); + if (cent->gent->footLBolt != -1) { + // get the feet + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.footLPoint); } - if ( cent->gent->footRBolt != -1 ) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.footRPoint ); - } - - //Handle saber - if ( cent->gent - && cent->gent->client - && ( cent->currentState.weapon == WP_SABER || cent->gent->client->ps.saberInFlight ) - && cent->gent->client->NPC_class != CLASS_ATST ) - {//FIXME: somehow saberactive is getting lost over the network - //loop this and do for both sabers - int numSabers = 1; - if ( cent->gent->client->ps.dualSabers ) - { + if (cent->gent->footRBolt != -1) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.footRPoint); + } + + // Handle saber + if (cent->gent && cent->gent->client && (cent->currentState.weapon == WP_SABER || cent->gent->client->ps.saberInFlight) && + cent->gent->client->NPC_class != CLASS_ATST) { // FIXME: somehow saberactive is getting lost over the network + // loop this and do for both sabers + int numSabers = 1; + if (cent->gent->client->ps.dualSabers) { numSabers = 2; } - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { + for (int saberNum = 0; saberNum < numSabers; saberNum++) { + if (cent->gent->client->ps.saberEventFlags & SEF_INWATER) { cent->gent->client->ps.saber[saberNum].Deactivate(); } - //loop this and do for both blades - for ( int bladeNum = 0; bladeNum < cent->gent->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - if ( !cent->gent->client->ps.saber[saberNum].blade[bladeNum].active || - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax )//hack around network lag for now - {//saber blade is off - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0 ) - { - if ( cent->gent->client->ps.stats[STAT_HEALTH] <= 0 ) - {//dead, didn't actively turn it off - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length -= cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax/10 * cg.frametime/100; - } - else - {//actively turned it off, shrink faster - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length -= cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax/10 * cg.frametime/100; + // loop this and do for both blades + for (int bladeNum = 0; bladeNum < cent->gent->client->ps.saber[saberNum].numBlades; bladeNum++) { + if (!cent->gent->client->ps.saber[saberNum].blade[bladeNum].active || + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax) // hack around network lag for now + { // saber blade is off + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0) { + if (cent->gent->client->ps.stats[STAT_HEALTH] <= 0) { // dead, didn't actively turn it off + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length -= + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax / 10 * cg.frametime / 100; + } else { // actively turned it off, shrink faster + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length -= + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax / 10 * cg.frametime / 100; } } - } - else - {//saber blade is on - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax ) - { - if ( !cent->gent->client->ps.saber[saberNum].blade[bladeNum].length ) - { + } else { // saber blade is on + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax) { + if (!cent->gent->client->ps.saber[saberNum].blade[bladeNum].length) { qhandle_t saberOnSound = cgs.sound_precache[g_entities[cent->currentState.clientNum].client->ps.saber[saberNum].soundOn]; - if ( !cent->gent->client->ps.weaponTime - && !saberNum//first saber only - && !bladeNum )//first blade only - {//make us play the turn on anim + if (!cent->gent->client->ps.weaponTime && !saberNum // first saber only + && !bladeNum) // first blade only + { // make us play the turn on anim cent->gent->client->ps.weaponstate = WEAPON_RAISING; cent->gent->client->ps.weaponTime = 250; } - if ( cent->gent->client->ps.saberInFlight && saberNum == 0 ) - {//play it on the saber - if ( cg_saberOnSoundTime[cent->currentState.number] < cg.time ) - { - cgi_S_UpdateEntityPosition( cent->gent->client->ps.saberEntityNum, g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, saberOnSound ); - cg_saberOnSoundTime[cent->currentState.number] = cg.time;//so we don't play multiple on sounds at one time + if (cent->gent->client->ps.saberInFlight && saberNum == 0) { // play it on the saber + if (cg_saberOnSoundTime[cent->currentState.number] < cg.time) { + cgi_S_UpdateEntityPosition(cent->gent->client->ps.saberEntityNum, + g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin); + cgi_S_StartSound(NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, saberOnSound); + cg_saberOnSoundTime[cent->currentState.number] = cg.time; // so we don't play multiple on sounds at one time } - } - else - { - if ( cg_saberOnSoundTime[cent->currentState.number] < cg.time ) - { - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_AUTO, saberOnSound ); - cg_saberOnSoundTime[cent->currentState.number] = cg.time;//so we don't play multiple on sounds at one time + } else { + if (cg_saberOnSoundTime[cent->currentState.number] < cg.time) { + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, saberOnSound); + cg_saberOnSoundTime[cent->currentState.number] = cg.time; // so we don't play multiple on sounds at one time } } } - if ( cg.frametime > 0 ) - { - if ( PM_SuperBreakWinAnim( cent->gent->client->ps.torsoAnim ) ) - {//just keep it full length! - //NOTE: does this mean it will go through walls now...? - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax; - } - else - { - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length += cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax/10 * cg.frametime/100; + if (cg.frametime > 0) { + if (PM_SuperBreakWinAnim(cent->gent->client->ps.torsoAnim)) { // just keep it full length! + // NOTE: does this mean it will go through walls now...? + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax; + } else { + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length += + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax / 10 * cg.frametime / 100; } } - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax ) - { - cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax; + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax) { + cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = + cent->gent->client->ps.saber[saberNum].blade[bladeNum].lengthMax; } } } - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0 ) - { - if ( !cent->gent->client->ps.saberInFlight || saberNum != 0 )//&& cent->gent->client->ps.saberActive) - {//holding the saber in-hand - // CGhoul2Info *currentModel = ¢->gent->ghoul2[1]; - // CGhoul2Info *nextModel = ¢->gent->ghoul2[1]; - //FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 - //FIXME: use an actual surfaceIndex? - char handName[MAX_QPATH]; - if ( saberNum == 0 ) - { - //this returns qfalse if it doesn't exist or isn't being rendered - if ( G_GetRootSurfNameWithVariant( cent->gent, "r_hand", handName, sizeof(handName) ) ) //!gi.G2API_GetSurfaceRenderStatus( ¢->gent->ghoul2[cent->gent->playerModel], "r_hand" ) )//surf is still on + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0) { + if (!cent->gent->client->ps.saberInFlight || saberNum != 0) //&& cent->gent->client->ps.saberActive) + { // holding the saber in-hand + // CGhoul2Info *currentModel = ¢->gent->ghoul2[1]; + // CGhoul2Info *nextModel = ¢->gent->ghoul2[1]; + // FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 + // FIXME: use an actual surfaceIndex? + char handName[MAX_QPATH]; + if (saberNum == 0) { + // this returns qfalse if it doesn't exist or isn't being rendered + if (G_GetRootSurfNameWithVariant( + cent->gent, "r_hand", handName, + sizeof(handName))) //! gi.G2API_GetSurfaceRenderStatus( ¢->gent->ghoul2[cent->gent->playerModel], "r_hand" ) )//surf + //! is still on { - CG_AddSaberBladeGo( cent, cent, NULL, ent.renderfx, cent->gent->weaponModel[saberNum], ent.origin, tempAngles, saberNum, bladeNum ); - //CG_AddSaberBlades( cent, ent.renderfx, ent.origin, tempAngles, saberNum ); - }//else, the limb will draw the blade itself - } - else if ( saberNum == 1 ) - { - //this returns qfalse if it doesn't exist or isn't being rendered - if ( G_GetRootSurfNameWithVariant( cent->gent, "l_hand", handName, sizeof(handName) ) ) //!gi.G2API_GetSurfaceRenderStatus( ¢->gent->ghoul2[cent->gent->playerModel], "l_hand" ) )//surf is still on + CG_AddSaberBladeGo(cent, cent, NULL, ent.renderfx, cent->gent->weaponModel[saberNum], ent.origin, tempAngles, saberNum, + bladeNum); + // CG_AddSaberBlades( cent, ent.renderfx, ent.origin, tempAngles, saberNum ); + } // else, the limb will draw the blade itself + } else if (saberNum == 1) { + // this returns qfalse if it doesn't exist or isn't being rendered + if (G_GetRootSurfNameWithVariant( + cent->gent, "l_hand", handName, + sizeof(handName))) //! gi.G2API_GetSurfaceRenderStatus( ¢->gent->ghoul2[cent->gent->playerModel], "l_hand" ) )//surf + //! is still on { - CG_AddSaberBladeGo( cent, cent, NULL, ent.renderfx, cent->gent->weaponModel[saberNum], ent.origin, tempAngles, saberNum, bladeNum ); - //CG_AddSaberBlades( cent, ent.renderfx, ent.origin, tempAngles, saberNum ); - }//else, the limb will draw the blade itself + CG_AddSaberBladeGo(cent, cent, NULL, ent.renderfx, cent->gent->weaponModel[saberNum], ent.origin, tempAngles, saberNum, + bladeNum); + // CG_AddSaberBlades( cent, ent.renderfx, ent.origin, tempAngles, saberNum ); + } // else, the limb will draw the blade itself } - }//in-flight saber draws it's own blade - } - else - { - if ( cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < 0 ) - { + } // in-flight saber draws it's own blade + } else { + if (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length < 0) { cent->gent->client->ps.saber[saberNum].blade[bladeNum].length = 0; } - //if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { - CG_CheckSaberInWater( cent, cent, saberNum, cent->gent->weaponModel[saberNum], ent.origin, tempAngles ); - } + // if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) + { CG_CheckSaberInWater(cent, cent, saberNum, cent->gent->weaponModel[saberNum], ent.origin, tempAngles); } } - if ( cent->currentState.weapon == WP_SABER - && (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0 || cent->gent->client->ps.saberInFlight) ) - { + if (cent->currentState.weapon == WP_SABER && + (cent->gent->client->ps.saber[saberNum].blade[bladeNum].length > 0 || cent->gent->client->ps.saberInFlight)) { calcedMp = qtrue; } } } - //add the light - if ( cent->gent->client->ps.dualSabers ) - { - if ( cent->gent->client->ps.saber[0].Length() > 0.0f - && !cent->gent->client->ps.saberInFlight ) - { - if ( cent->gent->client->ps.saber[0].numBlades > 2 ) - {// add blended light - CG_DoSaberLight( ¢->gent->client->ps.saber[0] ); + // add the light + if (cent->gent->client->ps.dualSabers) { + if (cent->gent->client->ps.saber[0].Length() > 0.0f && !cent->gent->client->ps.saberInFlight) { + if (cent->gent->client->ps.saber[0].numBlades > 2) { // add blended light + CG_DoSaberLight(¢->gent->client->ps.saber[0]); } } - if ( cent->gent->client->ps.saber[1].Length() > 0.0f ) - { - if ( cent->gent->client->ps.saber[1].numBlades > 2 ) - {// add blended light - CG_DoSaberLight( ¢->gent->client->ps.saber[1] ); + if (cent->gent->client->ps.saber[1].Length() > 0.0f) { + if (cent->gent->client->ps.saber[1].numBlades > 2) { // add blended light + CG_DoSaberLight(¢->gent->client->ps.saber[1]); } } - } - else if ( cent->gent->client->ps.saber[0].Length() > 0.0f - && !cent->gent->client->ps.saberInFlight ) - { - if ( cent->gent->client->ps.saber[0].numBlades > 2 ) - {// add blended light - CG_DoSaberLight( ¢->gent->client->ps.saber[0] ); + } else if (cent->gent->client->ps.saber[0].Length() > 0.0f && !cent->gent->client->ps.saberInFlight) { + if (cent->gent->client->ps.saber[0].numBlades > 2) { // add blended light + CG_DoSaberLight(¢->gent->client->ps.saber[0]); } } } - if ( cent->currentState.number != 0 - || cg.renderingThirdPerson - || cg.snap->ps.stats[STAT_HEALTH] <= 0 - || ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//First person saber - ) - {//if NPC, third person, or dead, unless using saber - //Get eyePoint & eyeAngles + if (cent->currentState.number != 0 || cg.renderingThirdPerson || cg.snap->ps.stats[STAT_HEALTH] <= 0 || + (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // First person saber + ) { // if NPC, third person, or dead, unless using saber + // Get eyePoint & eyeAngles /* if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD @@ -7485,235 +6289,194 @@ extern vmCvar_t cg_thirdPersonAlpha; VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); } else - */if ( cent->gent->headBolt == -1 ) - {//no headBolt - VectorCopy( ent.origin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( tempAngles, cent->gent->client->renderInfo.eyeAngles ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); - } - else - { - //FIXME: if head is missing, we should let the dismembered head set our eyePoint... - gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + */ + if (cent->gent->headBolt == -1) { // no headBolt + VectorCopy(ent.origin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(tempAngles, cent->gent->client->renderInfo.eyeAngles); + VectorCopy(ent.origin, cent->gent->client->renderInfo.headPoint); + } else { + // FIXME: if head is missing, we should let the dismembered head set our eyePoint... + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.eyePoint); - if ( cent->gent->client->NPC_class == CLASS_RANCOR ) - {//temp hack - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_X, tempAxis); - } - else - { - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tempAxis); + if (cent->gent->client->NPC_class == CLASS_RANCOR) { // temp hack + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_X, tempAxis); + } else { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tempAxis); } - vectoangles( tempAxis, cent->gent->client->renderInfo.eyeAngles ); - //estimate where the neck would be... - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis);//go down to find neck - VectorMA( cent->gent->client->renderInfo.eyePoint, 8, tempAxis, cent->gent->client->renderInfo.headPoint ); + vectoangles(tempAxis, cent->gent->client->renderInfo.eyeAngles); + // estimate where the neck would be... + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis); // go down to find neck + VectorMA(cent->gent->client->renderInfo.eyePoint, 8, tempAxis, cent->gent->client->renderInfo.headPoint); // Play the breath puffs (or not). - CG_BreathPuffs( cent, tempAngles, ent.origin ); - } - //Get torsoPoint & torsoAngles - if (cent->gent->chestBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->chestBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.torsoPoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, tempAxis ); - vectoangles( tempAxis, cent->gent->client->renderInfo.torsoAngles ); - } - else - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.torsoPoint); + CG_BreathPuffs(cent, tempAngles, ent.origin); + } + // Get torsoPoint & torsoAngles + if (cent->gent->chestBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->chestBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.torsoPoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis); + vectoangles(tempAxis, cent->gent->client->renderInfo.torsoAngles); + } else { + VectorCopy(ent.origin, cent->gent->client->renderInfo.torsoPoint); VectorClear(cent->gent->client->renderInfo.torsoAngles); } - //get crotchPoint - if (cent->gent->crotchBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.crotchPoint ); - } - else - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.crotchPoint); + // get crotchPoint + if (cent->gent->crotchBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.crotchPoint); + } else { + VectorCopy(ent.origin, cent->gent->client->renderInfo.crotchPoint); } - //NOTE: these are used for any case where an NPC fires and the next shot needs to come out + // NOTE: these are used for any case where an NPC fires and the next shot needs to come out // of a new barrel/point. That way the muzzleflash will draw on the old barrel/point correctly - //NOTE: I'm only doing this for the saboteur right now - AT-STs might need this... others? - vec3_t oldMP = {0,0,0}; - vec3_t oldMD = {0,0,0}; + // NOTE: I'm only doing this for the saboteur right now - AT-STs might need this... others? + vec3_t oldMP = {0, 0, 0}; + vec3_t oldMD = {0, 0, 0}; - if( !calcedMp ) - { - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) - {//FIXME: different for the three different weapon positions - mdxaBone_t boltMatrix; - int bolt; - entityState_t *es; + if (!calcedMp) { + if (cent->gent && cent->gent->client && + cent->gent->client->NPC_class == CLASS_ATST) { // FIXME: different for the three different weapon positions + mdxaBone_t boltMatrix; + int bolt; + entityState_t *es; es = ¢->currentState; // figure out where the actual model muzzle is - if (es->weapon == WP_ATST_MAIN) - { - if ( !es->number ) - {//player, just use left one, I guess - if ( cent->gent->alt_fire ) - { + if (es->weapon == WP_ATST_MAIN) { + if (!es->number) { // player, just use left one, I guess + if (cent->gent->alt_fire) { bolt = cent->gent->handRBolt; - } - else - { + } else { bolt = cent->gent->handLBolt; } - } - else if (cent->gent->count > 0) - { + } else if (cent->gent->count > 0) { cent->gent->count = 0; bolt = cent->gent->handLBolt; - } - else - { + } else { cent->gent->count = 1; bolt = cent->gent->handRBolt; } - } - else // ATST SIDE weapons + } else // ATST SIDE weapons { - if ( cent->gent->alt_fire) - { + if (cent->gent->alt_fire) { bolt = cent->gent->genericBolt2; - } - else - { + } else { bolt = cent->gent->genericBolt1; } } - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); - } - else if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_GALAKMECH ) - { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); + } else if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_GALAKMECH) { int bolt = -1; - if ( cent->gent->lockCount ) - {//using the big laser beam + if (cent->gent->lockCount) { // using the big laser beam bolt = cent->gent->handLBolt; - } - else//repeater + } else // repeater { - if ( cent->gent->alt_fire ) - {//fire from the lower barrel (not that anyone will ever notice this, but...) + if (cent->gent->alt_fire) { // fire from the lower barrel (not that anyone will ever notice this, but...) bolt = cent->gent->genericBolt3; - } - else - { + } else { bolt = cent->gent->handRBolt; } } - if ( bolt == -1 ) - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.muzzlePoint ); - AngleVectors( tempAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL ); - } - else - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + if (bolt == -1) { + VectorCopy(ent.origin, cent->gent->client->renderInfo.muzzlePoint); + AngleVectors(tempAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL); + } else { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); } } // Set the Vehicle Muzzle Point and Direction. - else if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE ) - { + else if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE) { // Get the Position and Direction of the Tag and use that as our Muzzles Properties. - mdxaBone_t boltMatrix; - vec3_t velocity; + mdxaBone_t boltMatrix; + vec3_t velocity; VectorCopy(cent->gent->client->ps.velocity, velocity); velocity[2] = 0; - for ( int i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( cent->gent->m_pVehicle->m_iMuzzleTag[i] != -1 ) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->m_pVehicle->m_iMuzzleTag[i], &boltMatrix, cent->lerpAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzleDir ); - VectorMA(cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos, 0.075f, velocity, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos); - } - else - { + for (int i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (cent->gent->m_pVehicle->m_iMuzzleTag[i] != -1) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->m_pVehicle->m_iMuzzleTag[i], &boltMatrix, + cent->lerpAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzleDir); + VectorMA(cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos, 0.075f, velocity, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos); + } else { break; } } - } - else if ( cent->gent->client && cent->gent->NPC//client NPC - /* - && cent->gent->client->NPC_class == CLASS_REBORN//cultist - && cent->gent->NPC->rank >= RANK_LT_COMM//commando - */ - && cent->gent->s.weapon == WP_BLASTER_PISTOL//using blaster pistol - && cent->gent->weaponModel[1] )//one in each hand + } else if (cent->gent->client && + cent->gent->NPC // client NPC + /* + && cent->gent->client->NPC_class == CLASS_REBORN//cultist + && cent->gent->NPC->rank >= RANK_LT_COMM//commando + */ + && cent->gent->s.weapon == WP_BLASTER_PISTOL // using blaster pistol + && cent->gent->weaponModel[1]) // one in each hand { qboolean getBoth = qfalse; - int oldOne = 0; - if ( cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - {//we need to get both muzzles since we're toggling and we fired recently + int oldOne = 0; + if (cent->muzzleFlashTime > 0 && wData && + !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { // we need to get both muzzles since we're toggling and we fired recently getBoth = qtrue; - oldOne = (cent->gent->count)?0:1; + oldOne = (cent->gent->count) ? 0 : 1; } - if ( ( cent->gent->weaponModel[cent->gent->count] != -1) - && ( cent->gent->ghoul2.size() > cent->gent->weaponModel[cent->gent->count] ) - && ( cent->gent->ghoul2[cent->gent->weaponModel[cent->gent->count]].mModelindex != -1) ) - {//get whichever one we're using now - mdxaBone_t boltMatrix; + if ((cent->gent->weaponModel[cent->gent->count] != -1) && (cent->gent->ghoul2.size() > cent->gent->weaponModel[cent->gent->count]) && + (cent->gent->ghoul2[cent->gent->weaponModel[cent->gent->count]].mModelindex != -1)) { // get whichever one we're using now + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->weaponModel[cent->gent->count], 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->weaponModel[cent->gent->count], 0, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); } - //get the old one too, if needbe, and store it in muzzle2 - if ( getBoth - && ( cent->gent->weaponModel[oldOne] != -1) //have a second weapon - && ( cent->gent->ghoul2.size() > cent->gent->weaponModel[oldOne] ) //have a valid ghoul model index - && ( cent->gent->ghoul2[cent->gent->weaponModel[oldOne]].mModelindex != -1) )//model exists and was loaded - {//saboteur commando, toggle the muzzle point back and forth between the two pistols each time he fires - mdxaBone_t boltMatrix; + // get the old one too, if needbe, and store it in muzzle2 + if (getBoth && (cent->gent->weaponModel[oldOne] != -1) // have a second weapon + && (cent->gent->ghoul2.size() > cent->gent->weaponModel[oldOne]) // have a valid ghoul model index + && (cent->gent->ghoul2[cent->gent->weaponModel[oldOne]].mModelindex != -1)) // model exists and was loaded + { // saboteur commando, toggle the muzzle point back and forth between the two pistols each time he fires + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->weaponModel[oldOne], 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->weaponModel[oldOne], 0, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, oldMP ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, oldMD ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, oldMP); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, oldMD); } - } - else if (( cent->gent->weaponModel[0] != -1) && - ( cent->gent->ghoul2.size() > cent->gent->weaponModel[0] ) && - ( cent->gent->ghoul2[cent->gent->weaponModel[0]].mModelindex != -1)) - { - mdxaBone_t boltMatrix; + } else if ((cent->gent->weaponModel[0] != -1) && (cent->gent->ghoul2.size() > cent->gent->weaponModel[0]) && + (cent->gent->ghoul2[cent->gent->weaponModel[0]].mModelindex != -1)) { + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->weaponModel[0], 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->weaponModel[0], 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); - } - else - { - VectorCopy( cent->gent->client->renderInfo.eyePoint, cent->gent->client->renderInfo.muzzlePoint ); - AngleVectors( cent->gent->client->renderInfo.eyeAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); + } else { + VectorCopy(cent->gent->client->renderInfo.eyePoint, cent->gent->client->renderInfo.muzzlePoint); + AngleVectors(cent->gent->client->renderInfo.eyeAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL); } cent->gent->client->renderInfo.mPCalcTime = cg.time; } // Draw Vehicle Muzzle Flashs. - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE ) - { - for ( int i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_VEHICLE) { + for (int i = 0; i < MAX_VEHICLE_MUZZLES; i++) { /*if ( cent->gent->m_pVehicle->m_pVehicleInfo->weap1ID == cent->gent->m_pVehicle->m_pVehicleInfo->weapMuzzle[i] ) { iDelay = cent->gent->m_pVehicle->m_pVehicleInfo->weap1Delay; @@ -7725,65 +6488,52 @@ extern vmCvar_t cg_thirdPersonAlpha; if ( cent->gent->m_pVehicle->m_Muzzles[i].m_iMuzzleWait - cg.time > ( iDelay - 500 ) )*/ - if ( cent->gent->m_pVehicle->m_Muzzles[i].m_bFired ) - { - const char *effect = &weaponData[ cent->gent->m_pVehicle->m_pVehicleInfo->weapMuzzle[i] ].mMuzzleEffect[0]; - if ( effect ) - { - theFxScheduler.PlayEffect( effect, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzleDir ); + if (cent->gent->m_pVehicle->m_Muzzles[i].m_bFired) { + const char *effect = &weaponData[cent->gent->m_pVehicle->m_pVehicleInfo->weapMuzzle[i]].mMuzzleEffect[0]; + if (effect) { + theFxScheduler.PlayEffect(effect, cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzlePos, + cent->gent->m_pVehicle->m_Muzzles[i].m_vMuzzleDir); } cent->gent->m_pVehicle->m_Muzzles[i].m_bFired = false; } } } // Pick the right effect for the type of weapon we are, defaults to no effect unless explicitly specified - else if ( cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { + else if (cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { const char *effect = NULL; - cent->muzzleFlashTime = 0; + cent->muzzleFlashTime = 0; // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cent->altFire ) - { + if (cent->altFire) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect ) - { - if ( cent->gent && cent->gent->NPC ) - { - if ( !VectorCompare( oldMP, vec3_origin ) - && !VectorCompare( oldMD, vec3_origin ) ) - {//we have an old muzzlePoint we want to use - theFxScheduler.PlayEffect( effect, oldMP, oldMD ); - } - else - {//use the current one - theFxScheduler.PlayEffect( effect, cent->gent->client->renderInfo.muzzlePoint, - cent->gent->client->renderInfo.muzzleDir ); + if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect) { + if (cent->gent && cent->gent->NPC) { + if (!VectorCompare(oldMP, vec3_origin) && !VectorCompare(oldMD, vec3_origin)) { // we have an old muzzlePoint we want to use + theFxScheduler.PlayEffect(effect, oldMP, oldMD); + } else { // use the current one + theFxScheduler.PlayEffect(effect, cent->gent->client->renderInfo.muzzlePoint, cent->gent->client->renderInfo.muzzleDir); } - } - else - { + } else { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cent->currentState.clientNum ); + theFxScheduler.PlayEffect(effect, cent->currentState.clientNum); } } } - //play special force effects + // play special force effects /* - if ( cent->gent->NPC && ( cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time) ) + if ( cent->gent->NPC && ( cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > + cg.time) ) {// we are currently confused, so play an effect at the headBolt position if ( TIMER_Done( cent->gent, "confusionEffectDebounce" ) ) {//ARGH!!! @@ -7793,615 +6543,537 @@ extern vmCvar_t cg_thirdPersonAlpha; } */ - if ( cent->gent->client && cent->gent->forcePushTime > cg.time ) - {//being pushed - CG_ForcePushBodyBlur( cent, ent.origin, tempAngles ); + if (cent->gent->client && cent->gent->forcePushTime > cg.time) { // being pushed + CG_ForcePushBodyBlur(cent, ent.origin, tempAngles); } - //This is now being done via an effect and the animevents.cfg - //if ( cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time || - if ( (cent->gent->client->ps.forcePowersActive & (1<gent->client->renderInfo.handLPoint, qtrue ); + // This is now being done via an effect and the animevents.cfg + // if ( cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time || + if ((cent->gent->client->ps.forcePowersActive & (1 << FP_GRIP))) { // doing the gripping + // FIXME: effect? + CG_ForcePushBlur(cent->gent->client->renderInfo.handLPoint, qtrue); } - if ( cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED ) - {//being gripped - CG_ForcePushBlur( cent->gent->client->renderInfo.headPoint, qtrue ); + if (cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED) { // being gripped + CG_ForcePushBlur(cent->gent->client->renderInfo.headPoint, qtrue); } - if ( cent->gent->client && cent->gent->client->ps.powerups[PW_SHOCKED] > cg.time ) - {//being electrocuted - CG_ForceElectrocution( cent, ent.origin, tempAngles, cgs.media.boltShader ); + if (cent->gent->client && cent->gent->client->ps.powerups[PW_SHOCKED] > cg.time) { // being electrocuted + CG_ForceElectrocution(cent, ent.origin, tempAngles, cgs.media.boltShader); } - if ( cent->gent->client->ps.eFlags & EF_FORCE_DRAINED - || (cent->currentState.powerups&(1<gent->client->ps.eFlags & EF_FORCE_DRAINED || (cent->currentState.powerups & (1 << PW_DRAINED))) { // being drained + // do red electricity lines off them and red drain shell on them + CG_ForceElectrocution(cent, ent.origin, tempAngles, cgs.media.drainShader, qtrue); } - if ( cent->gent->client->ps.forcePowersActive&(1<gent->client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // doing the electrocuting + // FIXME: if the target is absorbing or blocking lightning w/saber, draw a beam from my hand to his (hand?chest?saber?) vec3_t tAng, fxDir; - VectorCopy( cent->lerpAngles, tAng ); - if ( cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t fxAxis[3]; - AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handLPoint, fxAxis ); - if ( cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING - || cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START - || cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD - || cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE ) - {//jackin' 'em up, Palpatine-style - theFxScheduler.PlayEffect( cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handRPoint, fxAxis ); + VectorCopy(cent->lerpAngles, tAng); + if (cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t fxAxis[3]; + AnglesToAxis(tAng, fxAxis); + theFxScheduler.PlayEffect(cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handLPoint, fxAxis); + if (cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING || + cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START || + cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD || + cent->gent->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE) { // jackin' 'em up, Palpatine-style + theFxScheduler.PlayEffect(cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handRPoint, fxAxis); } - } - else - {//line - AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceLightning, cent->gent->client->renderInfo.handLPoint, fxDir ); + } else { // line + AngleVectors(tAng, fxDir, NULL, NULL); + theFxScheduler.PlayEffect(cgs.effects.forceLightning, cent->gent->client->renderInfo.handLPoint, fxDir); } } - if ( (cent->gent->client->ps.eFlags&EF_POWERING_ROSH) ) - { + if ((cent->gent->client->ps.eFlags & EF_POWERING_ROSH)) { vec3_t tAng, fxDir; - VectorCopy( cent->lerpAngles, tAng ); - AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceDrain, cent->gent->client->renderInfo.handLPoint, fxDir );//theFxScheduler.RegisterEffect( "force/dr1" ) + VectorCopy(cent->lerpAngles, tAng); + AngleVectors(tAng, fxDir, NULL, NULL); + theFxScheduler.PlayEffect(cgs.effects.forceDrain, cent->gent->client->renderInfo.handLPoint, + fxDir); // theFxScheduler.RegisterEffect( "force/dr1" ) } - if ( cent->gent->client->ps.forcePowersActive&(1<gent->client->ps.forceDrainEntityNum >= ENTITYNUM_WORLD ) - {//doing the draining and not on a single person + if (cent->gent->client->ps.forcePowersActive & (1 << FP_DRAIN) && + cent->gent->client->ps.forceDrainEntityNum >= ENTITYNUM_WORLD) { // doing the draining and not on a single person vec3_t tAng, fxDir; - VectorCopy( cent->lerpAngles, tAng ); - if ( cent->gent->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//arc - vec3_t fxAxis[3]; - AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceDrainWide, cent->gent->client->renderInfo.handLPoint, fxAxis ); - } - else - {//line - AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceDrain, cent->gent->client->renderInfo.handLPoint, fxDir ); - } - } - //spotlight? - if ( (cent->currentState.eFlags&EF_SPOTLIGHT) ) - {//FIXME: player's view should glare/flare if look at this... maybe build into the effect? + VectorCopy(cent->lerpAngles, tAng); + if (cent->gent->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // arc + vec3_t fxAxis[3]; + AnglesToAxis(tAng, fxAxis); + theFxScheduler.PlayEffect(cgs.effects.forceDrainWide, cent->gent->client->renderInfo.handLPoint, fxAxis); + } else { // line + AngleVectors(tAng, fxDir, NULL, NULL); + theFxScheduler.PlayEffect(cgs.effects.forceDrain, cent->gent->client->renderInfo.handLPoint, fxDir); + } + } + // spotlight? + if ((cent->currentState.eFlags & EF_SPOTLIGHT)) { // FIXME: player's view should glare/flare if look at this... maybe build into the effect? // hack for the spotlight - vec3_t org, eyeFwd; + vec3_t org, eyeFwd; - AngleVectors( cent->gent->client->renderInfo.eyeAngles, eyeFwd, NULL, NULL ); - theFxScheduler.PlayEffect( "rockettrooper/light_cone", cent->gent->client->renderInfo.eyePoint, eyeFwd ); + AngleVectors(cent->gent->client->renderInfo.eyeAngles, eyeFwd, NULL, NULL); + theFxScheduler.PlayEffect("rockettrooper/light_cone", cent->gent->client->renderInfo.eyePoint, eyeFwd); // stay a bit back from the server-side's trace impact point...this may not be enough? - VectorMA( cent->gent->client->renderInfo.eyePoint, cent->gent->speed - 5, eyeFwd, org ); + VectorMA(cent->gent->client->renderInfo.eyePoint, cent->gent->speed - 5, eyeFwd, org); float radius = cent->gent->speed; - if ( radius < 128.0f ) - { + if (radius < 128.0f) { radius = 128.0f; - } - else if ( radius > 1024.0f ) - { + } else if (radius > 1024.0f) { radius = 1024.0f; } - cgi_R_AddLightToScene( org, radius, 1.0f, 1.0f, 1.0f ); + cgi_R_AddLightToScene(org, radius, 1.0f, 1.0f, 1.0f); } } //"refraction" effect -rww - if ( cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time ) - { + if (cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time) { CG_ForcePushRefraction(cent->gent->client->renderInfo.handLPoint, cent); - } - else if ( cent->gent->client->ps.powerups[PW_FORCE_PUSH_RHAND] > cg.time ) - { + } else if (cent->gent->client->ps.powerups[PW_FORCE_PUSH_RHAND] > cg.time) { CG_ForcePushRefraction(cent->gent->client->renderInfo.handRPoint, cent); - } - else - { - cent->gent->client->ps.forcePowersActive &= ~( 1 << FP_PULL ); - } - - //bolted effects - CG_BoltedEffects( cent, ent.origin, tempAngles ); - //As good a place as any, I suppose, to do this keyframed sound thing - CGG2_AnimEvents( cent ); - //setup old system for gun to look at - //CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); - if ( cent->gent && cent->gent->client && cent->gent->client->ps.weapon == WP_SABER ) - { -extern qboolean PM_KickingAnim( int anim ); - if ( !PM_KickingAnim( cent->gent->client->ps.torsoAnim ) - || cent->gent->client->ps.torsoAnim == BOTH_A7_KICK_S ) - {//not kicking (unless it's the spinning kick) - if ( cg_timescale.value < 1.0f && (cent->gent->client->ps.forcePowersActive&(1<gent->client->ps.saberDamageDebounceTime - cg.time > wait ) - {//when you unpause the game with force speed on, the time gets *really* wiggy... + } else { + cent->gent->client->ps.forcePowersActive &= ~(1 << FP_PULL); + } + + // bolted effects + CG_BoltedEffects(cent, ent.origin, tempAngles); + // As good a place as any, I suppose, to do this keyframed sound thing + CGG2_AnimEvents(cent); + // setup old system for gun to look at + // CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); + if (cent->gent && cent->gent->client && cent->gent->client->ps.weapon == WP_SABER) { + extern qboolean PM_KickingAnim(int anim); + if (!PM_KickingAnim(cent->gent->client->ps.torsoAnim) || + cent->gent->client->ps.torsoAnim == BOTH_A7_KICK_S) { // not kicking (unless it's the spinning kick) + if (cg_timescale.value < 1.0f && (cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED))) { + int wait = floor((float)FRAMETIME / 2.0f); + // sanity check + if (cent->gent->client->ps.saberDamageDebounceTime - cg.time > + wait) { // when you unpause the game with force speed on, the time gets *really* wiggy... cent->gent->client->ps.saberDamageDebounceTime = cg.time + wait; } - if ( cent->gent->client->ps.saberDamageDebounceTime <= cg.time ) - { -extern void WP_SabersDamageTrace( gentity_t *ent, qboolean noEffects ); -extern void WP_SaberUpdateOldBladeData( gentity_t *ent ); - //FIXME: this causes an ASSLOAD of effects - WP_SabersDamageTrace( cent->gent, qtrue ); - WP_SaberUpdateOldBladeData( cent->gent ); - cent->gent->client->ps.saberDamageDebounceTime = cg.time + floor((float)wait*cg_timescale.value); + if (cent->gent->client->ps.saberDamageDebounceTime <= cg.time) { + extern void WP_SabersDamageTrace(gentity_t * ent, qboolean noEffects); + extern void WP_SaberUpdateOldBladeData(gentity_t * ent); + // FIXME: this causes an ASSLOAD of effects + WP_SabersDamageTrace(cent->gent, qtrue); + WP_SaberUpdateOldBladeData(cent->gent); + cent->gent->client->ps.saberDamageDebounceTime = cg.time + floor((float)wait * cg_timescale.value); } } } } - } - else - { - refEntity_t legs; - refEntity_t torso; - refEntity_t head; - refEntity_t gun; - refEntity_t flash; - refEntity_t flashlight; - int renderfx, i; - const weaponInfo_t *weapon; - + } else { + refEntity_t legs; + refEntity_t torso; + refEntity_t head; + refEntity_t gun; + refEntity_t flash; + refEntity_t flashlight; + int renderfx, i; + const weaponInfo_t *weapon; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - memset( &legs, 0, sizeof(legs) ); - memset( &torso, 0, sizeof(torso) ); - memset( &head, 0, sizeof(head) ); - memset( &gun, 0, sizeof(gun) ); - memset( &flash, 0, sizeof(flash) ); - memset( &flashlight, 0, sizeof(flashlight) ); + memset(&legs, 0, sizeof(legs)); + memset(&torso, 0, sizeof(torso)); + memset(&head, 0, sizeof(head)); + memset(&gun, 0, sizeof(gun)); + memset(&flash, 0, sizeof(flash)); + memset(&flashlight, 0, sizeof(flashlight)); - // Weapon sounds may need to be stopped, so check now - CG_StopWeaponSounds( cent ); + // Weapon sounds may need to be stopped, so check now + CG_StopWeaponSounds(cent); - //FIXME: pass in the axis/angles offset between the tag_torso and the tag_head? - // get the rotation information - CG_PlayerAngles( cent, legs.axis, torso.axis, head.axis ); - if ( cent->gent && cent->gent->client ) - { - cent->gent->client->ps.legsYaw = cent->lerpAngles[YAW]; - } + // FIXME: pass in the axis/angles offset between the tag_torso and the tag_head? + // get the rotation information + CG_PlayerAngles(cent, legs.axis, torso.axis, head.axis); + if (cent->gent && cent->gent->client) { + cent->gent->client->ps.legsYaw = cent->lerpAngles[YAW]; + } - // get the animation state (after rotation, to allow feet shuffle) - // NB: Also plays keyframed animSounds (Bob- hope you dont mind, I was here late and at about 5:30 Am i needed to do something to keep me awake and i figured you wouldn't mind- you might want to check it, though, to make sure I wasn't smoking crack and missed something important, it is pretty late and I'm getting pretty close to being up for 24 hours here, so i wouldn't doubt if I might have messed something up, but i tested it and it looked right.... noticed in old code base i was doing it wrong too, whic h explains why I was getting so many damn sounds all the time! I had to lower the probabilities because it seemed like i was getting way too many sounds, and that was the problem! Well, should be fixed now I think...) - CG_PlayerAnimation( cent, &legs.oldframe, &legs.frame, &legs.backlerp, - &torso.oldframe, &torso.frame, &torso.backlerp ); + // get the animation state (after rotation, to allow feet shuffle) + // NB: Also plays keyframed animSounds (Bob- hope you dont mind, I was here late and at about 5:30 Am i needed to do something to keep me awake and i + // figured you wouldn't mind- you might want to check it, though, to make sure I wasn't smoking crack and missed something important, it is pretty late + // and I'm getting pretty close to being up for 24 hours here, so i wouldn't doubt if I might have messed something up, but i tested it and it looked + // right.... noticed in old code base i was doing it wrong too, whic h explains why I was getting so many damn sounds all the time! I had to + // lower the probabilities because it seemed like i was getting way too many sounds, and that was the problem! Well, should be fixed now I think...) + CG_PlayerAnimation(cent, &legs.oldframe, &legs.frame, &legs.backlerp, &torso.oldframe, &torso.frame, &torso.backlerp); - cent->gent->client->renderInfo.legsFrame = cent->pe.legs.frame; - cent->gent->client->renderInfo.torsoFrame = cent->pe.torso.frame; + cent->gent->client->renderInfo.legsFrame = cent->pe.legs.frame; + cent->gent->client->renderInfo.torsoFrame = cent->pe.torso.frame; - // add powerups floating behind the player - CG_PlayerPowerups( cent ); + // add powerups floating behind the player + CG_PlayerPowerups(cent); - // add the shadow - shadow = CG_PlayerShadow( cent, &shadowPlane ); + // add the shadow + shadow = CG_PlayerShadow(cent, &shadowPlane); - // add a water splash if partially in and out of water - CG_PlayerSplash( cent ); + // add a water splash if partially in and out of water + CG_PlayerSplash(cent); - // get the player model information - renderfx = 0; - if ( !cg.renderingThirdPerson || cg.zoomMode ) - { - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) - {//no viewentity - if ( cent->currentState.number == cg.snap->ps.clientNum ) - {//I am the player - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - renderfx = RF_THIRD_PERSON; // only draw in mirrors + // get the player model information + renderfx = 0; + if (!cg.renderingThirdPerson || cg.zoomMode) { + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // no viewentity + if (cent->currentState.number == cg.snap->ps.clientNum) { // I am the player + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + renderfx = RF_THIRD_PERSON; // only draw in mirrors + } + } + } else if (cent->currentState.number == cg.snap->ps.viewEntity) { // I am the view entity + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + renderfx = RF_THIRD_PERSON; // only draw in mirrors } } } - else if ( cent->currentState.number == cg.snap->ps.viewEntity ) - {//I am the view entity - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - renderfx = RF_THIRD_PERSON; // only draw in mirrors - } + + if ((cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow)) { + renderfx |= RF_SHADOW_PLANE; + } + renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + if (cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT) { + renderfx |= RF_MORELIGHT; // bigger than normal min light } - } - if ( (cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow) ) - { - renderfx |= RF_SHADOW_PLANE; - } - renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all - if ( cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT ) - { - renderfx |= RF_MORELIGHT; //bigger than normal min light - } + if (cent->gent && cent->gent->client) { + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.headPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.handRPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.handLPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.footRPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.footLPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.torsoPoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.crotchPoint); + } + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && + cg.snap->ps.viewEntity == cent->currentState.clientNum) { // player is in an entity camera view, ME + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.headPoint); + } + // + // add the legs + // + legs.hModel = ci->legsModel; + legs.customSkin = ci->legsSkin; - if ( cent->gent && cent->gent->client ) - { - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.headPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.handRPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.handLPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.footRPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.footLPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.torsoPoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.crotchPoint ); - } - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && cg.snap->ps.viewEntity == cent->currentState.clientNum ) - {//player is in an entity camera view, ME - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.headPoint ); - } - // - // add the legs - // - legs.hModel = ci->legsModel; - legs.customSkin = ci->legsSkin; - - VectorCopy( cent->lerpOrigin, legs.origin ); - - //Scale applied to a refEnt will apply to any models attached to it... - //This seems to copy the scale to every piece attached, kinda cool, but doesn't - //allow the body to be scaled up without scaling a bolt on or whatnot... - //Only apply scale if it's not 100% scale... - if(cent->currentState.modelScale[0] != 0.0f) - { - VectorScale( legs.axis[0], cent->currentState.modelScale[0], legs.axis[0] ); - legs.nonNormalizedAxes = qtrue; - } + VectorCopy(cent->lerpOrigin, legs.origin); - if(cent->currentState.modelScale[1] != 0.0f) - { - VectorScale( legs.axis[1], cent->currentState.modelScale[1], legs.axis[1] ); - legs.nonNormalizedAxes = qtrue; - } + // Scale applied to a refEnt will apply to any models attached to it... + // This seems to copy the scale to every piece attached, kinda cool, but doesn't + // allow the body to be scaled up without scaling a bolt on or whatnot... + // Only apply scale if it's not 100% scale... + if (cent->currentState.modelScale[0] != 0.0f) { + VectorScale(legs.axis[0], cent->currentState.modelScale[0], legs.axis[0]); + legs.nonNormalizedAxes = qtrue; + } - if(cent->currentState.modelScale[2] != 0.0f) - { - VectorScale( legs.axis[2], cent->currentState.modelScale[2], legs.axis[2] ); - legs.nonNormalizedAxes = qtrue; - if ( !staticScale ) - { - //FIXME:? need to know actual height of leg model bottom to origin, not hardcoded - legs.origin[2] += 24 * (cent->currentState.modelScale[2] - 1); + if (cent->currentState.modelScale[1] != 0.0f) { + VectorScale(legs.axis[1], cent->currentState.modelScale[1], legs.axis[1]); + legs.nonNormalizedAxes = qtrue; } - } - VectorCopy( legs.origin, legs.lightingOrigin ); - legs.shadowPlane = shadowPlane; - legs.renderfx = renderfx; - VectorCopy (legs.origin, legs.oldorigin); // don't positionally lerp at all + if (cent->currentState.modelScale[2] != 0.0f) { + VectorScale(legs.axis[2], cent->currentState.modelScale[2], legs.axis[2]); + legs.nonNormalizedAxes = qtrue; + if (!staticScale) { + // FIXME:? need to know actual height of leg model bottom to origin, not hardcoded + legs.origin[2] += 24 * (cent->currentState.modelScale[2] - 1); + } + } - CG_AddRefEntityWithPowerups( &legs, cent->currentState.powerups, cent ); + VectorCopy(legs.origin, legs.lightingOrigin); + legs.shadowPlane = shadowPlane; + legs.renderfx = renderfx; + VectorCopy(legs.origin, legs.oldorigin); // don't positionally lerp at all - // if the model failed, allow the default nullmodel to be displayed - if (!legs.hModel) - { - return; - } + CG_AddRefEntityWithPowerups(&legs, cent->currentState.powerups, cent); - // - // add the torso - // - torso.hModel = ci->torsoModel; - if (torso.hModel) - { - orientation_t tag_torso; + // if the model failed, allow the default nullmodel to be displayed + if (!legs.hModel) { + return; + } - torso.customSkin = ci->torsoSkin; + // + // add the torso + // + torso.hModel = ci->torsoModel; + if (torso.hModel) { + orientation_t tag_torso; - VectorCopy( cent->lerpOrigin, torso.lightingOrigin ); + torso.customSkin = ci->torsoSkin; - CG_PositionRotatedEntityOnTag( &torso, &legs, legs.hModel, "tag_torso", &tag_torso ); - VectorCopy( torso.origin, cent->gent->client->renderInfo.torsoPoint ); - vectoangles( tag_torso.axis[0], cent->gent->client->renderInfo.torsoAngles ); + VectorCopy(cent->lerpOrigin, torso.lightingOrigin); - torso.shadowPlane = shadowPlane; - torso.renderfx = renderfx; + CG_PositionRotatedEntityOnTag(&torso, &legs, legs.hModel, "tag_torso", &tag_torso); + VectorCopy(torso.origin, cent->gent->client->renderInfo.torsoPoint); + vectoangles(tag_torso.axis[0], cent->gent->client->renderInfo.torsoAngles); - CG_AddRefEntityWithPowerups( &torso, cent->currentState.powerups, cent ); + torso.shadowPlane = shadowPlane; + torso.renderfx = renderfx; - // - // add the head - // - head.hModel = ci->headModel; - if (head.hModel) - { - orientation_t tag_head; + CG_AddRefEntityWithPowerups(&torso, cent->currentState.powerups, cent); + + // + // add the head + // + head.hModel = ci->headModel; + if (head.hModel) { + orientation_t tag_head; - //Deal with facial expressions - //CG_PlayerHeadExtension( cent, &head ); + // Deal with facial expressions + // CG_PlayerHeadExtension( cent, &head ); - VectorCopy( cent->lerpOrigin, head.lightingOrigin ); + VectorCopy(cent->lerpOrigin, head.lightingOrigin); - CG_PositionRotatedEntityOnTag( &head, &torso, torso.hModel, "tag_head", &tag_head ); - VectorCopy( head.origin, cent->gent->client->renderInfo.headPoint ); - vectoangles( tag_head.axis[0], cent->gent->client->renderInfo.headAngles ); + CG_PositionRotatedEntityOnTag(&head, &torso, torso.hModel, "tag_head", &tag_head); + VectorCopy(head.origin, cent->gent->client->renderInfo.headPoint); + vectoangles(tag_head.axis[0], cent->gent->client->renderInfo.headAngles); - head.shadowPlane = shadowPlane; - head.renderfx = renderfx; + head.shadowPlane = shadowPlane; + head.renderfx = renderfx; - CG_AddRefEntityWithPowerups( &head, cent->currentState.powerups, cent ); + CG_AddRefEntityWithPowerups(&head, cent->currentState.powerups, cent); - if ( cent->gent && cent->gent->NPC && ( cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time) ) - { - // we are currently confused, so play an effect - if ( TIMER_Done( cent->gent, "confusionEffectDebounce" ) ) - {//ARGH!!! - theFxScheduler.PlayEffect( cgs.effects.forceConfusion, head.origin ); - TIMER_Set( cent->gent, "confusionEffectDebounce", 1000 ); + if (cent->gent && cent->gent->NPC && + (cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time)) { + // we are currently confused, so play an effect + if (TIMER_Done(cent->gent, "confusionEffectDebounce")) { // ARGH!!! + theFxScheduler.PlayEffect(cgs.effects.forceConfusion, head.origin); + TIMER_Set(cent->gent, "confusionEffectDebounce", 1000); + } } - } - if ( !calcedMp ) - {//First person player's eyePoint and eyeAngles should be copies from cg.refdef... - //Calc this client's eyepoint - VectorCopy( head.origin, cent->gent->client->renderInfo.eyePoint ); - // race is gone, eyepoint should refer to the tag/bolt on the model... if this breaks something let me know - dmv - // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][1]*scaleFactor[2], head.axis[2], cent->gent->client->renderInfo.eyePoint );//up - // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][0]*scaleFactor[0], head.axis[0], cent->gent->client->renderInfo.eyePoint );//forward - //Calc this client's eyeAngles - vectoangles( head.axis[0], cent->gent->client->renderInfo.eyeAngles ); + if (!calcedMp) { // First person player's eyePoint and eyeAngles should be copies from cg.refdef... + // Calc this client's eyepoint + VectorCopy(head.origin, cent->gent->client->renderInfo.eyePoint); + // race is gone, eyepoint should refer to the tag/bolt on the model... if this breaks something let me know - dmv + // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][1]*scaleFactor[2], head.axis[2], + //cent->gent->client->renderInfo.eyePoint );//up VectorMA( cent->gent->client->renderInfo.eyePoint, + //CG_EyePointOfsForRace[cent->gent->client->race][0]*scaleFactor[0], head.axis[0], cent->gent->client->renderInfo.eyePoint );//forward Calc + // this client's eyeAngles + vectoangles(head.axis[0], cent->gent->client->renderInfo.eyeAngles); + } + } else { + VectorCopy(torso.origin, cent->gent->client->renderInfo.eyePoint); + cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; + vectoangles(torso.axis[0], cent->gent->client->renderInfo.eyeAngles); } - } - else - { - VectorCopy( torso.origin, cent->gent->client->renderInfo.eyePoint ); - cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; - vectoangles( torso.axis[0], cent->gent->client->renderInfo.eyeAngles ); - } - // - // add the gun - // - CG_RegisterWeapon( cent->currentState.weapon ); - weapon = &cg_weapons[cent->currentState.weapon]; + // + // add the gun + // + CG_RegisterWeapon(cent->currentState.weapon); + weapon = &cg_weapons[cent->currentState.weapon]; - gun.hModel = weapon->weaponWorldModel; - if (gun.hModel) - { - qboolean drawGun = qtrue; - //FIXME: allow scale, animation and angle offsets - VectorCopy( cent->lerpOrigin, gun.lightingOrigin ); + gun.hModel = weapon->weaponWorldModel; + if (gun.hModel) { + qboolean drawGun = qtrue; + // FIXME: allow scale, animation and angle offsets + VectorCopy(cent->lerpOrigin, gun.lightingOrigin); - //FIXME: allow it to be put anywhere and move this out of if(torso.hModel) - //Will have to call CG_PositionRotatedEntityOnTag + // FIXME: allow it to be put anywhere and move this out of if(torso.hModel) + // Will have to call CG_PositionRotatedEntityOnTag - CG_PositionEntityOnTag( &gun, &torso, torso.hModel, "tag_weapon"); + CG_PositionEntityOnTag(&gun, &torso, torso.hModel, "tag_weapon"); -//--------------------- start saber hacks -/* - if ( cent->gent && cent->gent->client && ( cent->currentState.weapon == WP_SABER || cent->gent->client->ps.saberInFlight ) ) - { - int numSabers = 1; - if ( cent->gent->client->ps.dualSabers ) - { - numSabers = 2; - } - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - if ( !cent->gent->client->ps.saber[saberNum].active )//!cent->gent->client->ps.saberActive ) - {//saber is off - if ( cent->gent->client->ps.saber[saberNum].length > 0 ) - { - if ( cent->gent->client->ps.stats[STAT_HEALTH] <= 0 ) - {//dead, didn't actively turn it off - cent->gent->client->ps.saber[saberNum].length -= cent->gent->client->ps.saber[saberNum].lengthMax/10 * cg.frametime/100; - } - else - {//actively turned it off, shrink faster - cent->gent->client->ps.saber[saberNum].length -= cent->gent->client->ps.saber[saberNum].lengthMax/3 * cg.frametime/100; - } - } - if ( cent->gent->client->ps.saber[saberNum].length < 0 ) - { - cent->gent->client->ps.saber[saberNum].length = 0; - } - } - else if ( cent->gent->client->ps.saber[saberNum].length < cent->gent->client->ps.saber[saberNum].lengthMax ) - {//saber is on - if ( !cent->gent->client->ps.saber[saberNum].length ) - { - if ( cent->gent->client->ps.saberInFlight ) - {//play it on the saber - cgi_S_UpdateEntityPosition( cent->gent->client->ps.saberEntityNum, g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, cgs.sound_precache[cent->gent->client->ps.saber[0].soundOn] ); - } - else + //--------------------- start saber hacks + /* + if ( cent->gent && cent->gent->client && ( cent->currentState.weapon == WP_SABER || cent->gent->client->ps.saberInFlight ) ) { - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_AUTO, cgs.sound_precache[cent->gent->client->ps.saber[0].soundOn] ); -#ifdef _IMMERSION - cgi_FF_Start( cgi_FF_Register( "fffx/weapons/saber/saberon", FF_CHANNEL_WEAPON ), cent->currentState.number ); -#endif // _IMMERSION - } - } - cent->gent->client->ps.saber[saberNum].length += cent->gent->client->ps.saber[saberNum].lengthMax/6 * cg.frametime/100;//= saber[saberNum].lengthMax; - if ( cent->gent->client->ps.saber[saberNum].length > cent->gent->client->ps.saber[saberNum].lengthMax ) - { - cent->gent->client->ps.saber[saberNum].length = cent->gent->client->ps.saber[saberNum].lengthMax; - } - } + int numSabers = 1; + if ( cent->gent->client->ps.dualSabers ) + { + numSabers = 2; + } + for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) + { + if ( !cent->gent->client->ps.saber[saberNum].active )//!cent->gent->client->ps.saberActive ) + {//saber is off + if ( cent->gent->client->ps.saber[saberNum].length > 0 ) + { + if ( cent->gent->client->ps.stats[STAT_HEALTH] <= 0 ) + {//dead, didn't actively turn it off + cent->gent->client->ps.saber[saberNum].length -= cent->gent->client->ps.saber[saberNum].lengthMax/10 * + cg.frametime/100; + } + else + {//actively turned it off, shrink faster + cent->gent->client->ps.saber[saberNum].length -= cent->gent->client->ps.saber[saberNum].lengthMax/3 * + cg.frametime/100; + } + } + if ( cent->gent->client->ps.saber[saberNum].length < 0 ) + { + cent->gent->client->ps.saber[saberNum].length = 0; + } + } + else if ( cent->gent->client->ps.saber[saberNum].length < cent->gent->client->ps.saber[saberNum].lengthMax ) + {//saber is on + if ( !cent->gent->client->ps.saber[saberNum].length ) + { + if ( cent->gent->client->ps.saberInFlight ) + {//play it on the saber + cgi_S_UpdateEntityPosition( cent->gent->client->ps.saberEntityNum, + g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin ); cgi_S_StartSound (NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, + cgs.sound_precache[cent->gent->client->ps.saber[0].soundOn] ); + } + else + { + cgi_S_StartSound (NULL, cent->currentState.number, CHAN_AUTO, + cgs.sound_precache[cent->gent->client->ps.saber[0].soundOn] ); #ifdef _IMMERSION cgi_FF_Start( cgi_FF_Register( "fffx/weapons/saber/saberon", + FF_CHANNEL_WEAPON ), cent->currentState.number ); #endif // _IMMERSION + } + } + cent->gent->client->ps.saber[saberNum].length += cent->gent->client->ps.saber[saberNum].lengthMax/6 * + cg.frametime/100;//= saber[saberNum].lengthMax; if ( cent->gent->client->ps.saber[saberNum].length > + cent->gent->client->ps.saber[saberNum].lengthMax ) + { + cent->gent->client->ps.saber[saberNum].length = cent->gent->client->ps.saber[saberNum].lengthMax; + } + } - if ( cent->gent->client->ps.saberInFlight ) - {//not holding the saber in-hand - drawGun = qfalse; - } - if ( cent->gent->client->ps.saber[saberNum].length > 0 ) - { - if ( !cent->gent->client->ps.saberInFlight ) - {//holding the saber in-hand - CG_AddSaberBlade( cent, cent, &gun, renderfx, 0, NULL, NULL ); - calcedMp = qtrue; - } - } - else - { - //if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { - CG_CheckSaberInWater( cent, cent, 0, 0, NULL, NULL ); - } - } - } - } + if ( cent->gent->client->ps.saberInFlight ) + {//not holding the saber in-hand + drawGun = qfalse; + } + if ( cent->gent->client->ps.saber[saberNum].length > 0 ) + { + if ( !cent->gent->client->ps.saberInFlight ) + {//holding the saber in-hand + CG_AddSaberBlade( cent, cent, &gun, renderfx, 0, NULL, NULL ); + calcedMp = qtrue; + } + } + else + { + //if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) + { + CG_CheckSaberInWater( cent, cent, 0, 0, NULL, NULL ); + } + } + } + } -*/ -//--------------------- end saber hacks + */ + //--------------------- end saber hacks - gun.shadowPlane = shadowPlane; - gun.renderfx = renderfx; + gun.shadowPlane = shadowPlane; + gun.renderfx = renderfx; - if ( drawGun ) - { - CG_AddRefEntityWithPowerups( &gun, - (cent->currentState.powerups & ((1<currentState.powerups & ((1 << PW_CLOAKED) | (1 << PW_BATTLESUIT))), cent); + } - // - // add the flash (even if invisible) - // + // + // add the flash (even if invisible) + // - // impulse flash - if ( cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { - int effect = 0; + // impulse flash + if (cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { + int effect = 0; - cent->muzzleFlashTime = 0; + cent->muzzleFlashTime = 0; - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); - // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffectID ) - { - effect = wData->mMuzzleEffectID; - } + // Try and get a default muzzle so we have one to fall back on + if (wData->mMuzzleEffectID) { + effect = wData->mMuzzleEffectID; + } - if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { - // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffectID ) - { - effect = wData->mAltMuzzleEffectID; + if (cent->currentState.eFlags & EF_ALT_FIRING) { + // We're alt-firing, so see if we need to override with a custom alt-fire effect + if (wData->mAltMuzzleEffectID) { + effect = wData->mAltMuzzleEffectID; + } } - } - if (( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) && effect ) - { - vec3_t up={0,0,1}, ax[3]; + if ((cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING) && effect) { + vec3_t up = {0, 0, 1}, ax[3]; - VectorCopy( flash.axis[0], ax[0] ); + VectorCopy(flash.axis[0], ax[0]); - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); - if (( cent->gent && cent->gent->NPC ) || cg.renderingThirdPerson ) - { - theFxScheduler.PlayEffect( effect, flash.origin, ax ); - } - else - { - // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, flash.origin, ax ); + if ((cent->gent && cent->gent->NPC) || cg.renderingThirdPerson) { + theFxScheduler.PlayEffect(effect, flash.origin, ax); + } else { + // We got an effect and we're firing, so let 'er rip. + theFxScheduler.PlayEffect(effect, flash.origin, ax); + } } } - } - if ( !calcedMp && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - {// Set the muzzle point - orientation_t orientation; + if (!calcedMp && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { // Set the muzzle point + orientation_t orientation; - cgi_R_LerpTag( &orientation, weapon->weaponModel, gun.oldframe, gun.frame, - 1.0f - gun.backlerp, "tag_flash" ); - - // FIXME: allow origin offsets along tag? - VectorCopy( gun.origin, cent->gent->client->renderInfo.muzzlePoint ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorMA( cent->gent->client->renderInfo.muzzlePoint, orientation.origin[i], gun.axis[i], cent->gent->client->renderInfo.muzzlePoint ); - } -// VectorCopy( gun.axis[0], cent->gent->client->renderInfo.muzzleDir ); -// VectorAdd( gun.axis[0], orientation.axis[0], cent->gent->client->renderInfo.muzzleDir ); -// VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); + cgi_R_LerpTag(&orientation, weapon->weaponModel, gun.oldframe, gun.frame, 1.0f - gun.backlerp, "tag_flash"); + // FIXME: allow origin offsets along tag? + VectorCopy(gun.origin, cent->gent->client->renderInfo.muzzlePoint); + for (i = 0; i < 3; i++) { + VectorMA(cent->gent->client->renderInfo.muzzlePoint, orientation.origin[i], gun.axis[i], cent->gent->client->renderInfo.muzzlePoint); + } + // VectorCopy( gun.axis[0], cent->gent->client->renderInfo.muzzleDir ); + // VectorAdd( gun.axis[0], orientation.axis[0], cent->gent->client->renderInfo.muzzleDir ); + // VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); - cent->gent->client->renderInfo.mPCalcTime = cg.time; - // Weapon wasn't firing anymore, so ditch any weapon associated looping sounds. - //cent->gent->s.loopSound = 0; + cent->gent->client->renderInfo.mPCalcTime = cg.time; + // Weapon wasn't firing anymore, so ditch any weapon associated looping sounds. + // cent->gent->s.loopSound = 0; + } } + } else { + VectorCopy(legs.origin, cent->gent->client->renderInfo.eyePoint); + cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; + vectoangles(legs.axis[0], cent->gent->client->renderInfo.eyeAngles); } } - else - { - VectorCopy( legs.origin, cent->gent->client->renderInfo.eyePoint ); - cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; - vectoangles( legs.axis[0], cent->gent->client->renderInfo.eyeAngles ); - } - - } - //FIXME: for debug, allow to draw a cone of the NPC's FOV... - if ( cent->currentState.number == 0 && cg.renderingThirdPerson ) - { + // FIXME: for debug, allow to draw a cone of the NPC's FOV... + if (cent->currentState.number == 0 && cg.renderingThirdPerson) { playerState_t *ps = &cg.predicted_player_state; - if (( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL ) - || ( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BLASTER_PISTOL ) - || ( ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING ) - || ( ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT )) - { - int shader = 0; - float val = 0.0f, scale = 1.0f; - vec3_t WHITE = {1.0f,1.0f,1.0f}; + if ((ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL) || + (ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BLASTER_PISTOL) || (ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING) || + (ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT)) { + int shader = 0; + float val = 0.0f, scale = 1.0f; + vec3_t WHITE = {1.0f, 1.0f, 1.0f}; - if ( ps->weapon == WP_BRYAR_PISTOL - || ps->weapon == WP_BLASTER_PISTOL ) - { + if (ps->weapon == WP_BRYAR_PISTOL || ps->weapon == WP_BLASTER_PISTOL) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/bryarFrontFlash" ); - } - else if ( ps->weapon == WP_BOWCASTER ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/bryarFrontFlash"); + } else if (ps->weapon == WP_BOWCASTER) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/greenFrontFlash" ); - } - else if ( ps->weapon == WP_DEMP2 ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/greenFrontFlash"); + } else if (ps->weapon == WP_DEMP2) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/misc/lightningFlash" ); + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/misc/lightningFlash"); scale = 1.75f; } - if ( val < 0.0f ) - { + if (val < 0.0f) { val = 0.0f; - } - else if ( val > 1.0f ) - { + } else if (val > 1.0f) { val = 1.0f; - CGCam_Shake( 0.1f, 100 ); - } - else - { - CGCam_Shake( val * val * 0.3f, 100 ); + CGCam_Shake(0.1f, 100); + } else { + CGCam_Shake(val * val * 0.3f, 100); } val += Q_flrand(0.0f, 1.0f) * 0.5f; - FX_AddSprite( cent->gent->client->renderInfo.muzzlePoint, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA ); + FX_AddSprite(cent->gent->client->renderInfo.muzzlePoint, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, + 0.0f, 1.0f, shader, FX_USE_ALPHA); } } } @@ -8418,39 +7090,35 @@ FIXME: We do not need to do this, we can remember the last anim and frame they w on and coontinue from there. =============== */ -void CG_ResetPlayerEntity( centity_t *cent ) { -// cent->errorTime = -99999; // guarantee no error decay added -// cent->extrapolated = qfalse; +void CG_ResetPlayerEntity(centity_t *cent) { + // cent->errorTime = -99999; // guarantee no error decay added + // cent->extrapolated = qfalse; - if ( cent->gent && cent->gent->ghoul2.size() ) - { - if ( cent->currentState.clientNum < MAX_CLIENTS ) - { - CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], ¢->pe.legs, cent->currentState.legsAnim ); - CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], ¢->pe.torso, cent->currentState.torsoAnim ); - } - else if ( cent->gent && cent->gent->client ) - { - CG_ClearLerpFrame( ¢->gent->client->clientInfo, ¢->pe.legs, cent->currentState.legsAnim ); - CG_ClearLerpFrame( ¢->gent->client->clientInfo, ¢->pe.torso, cent->currentState.torsoAnim ); + if (cent->gent && cent->gent->ghoul2.size()) { + if (cent->currentState.clientNum < MAX_CLIENTS) { + CG_ClearLerpFrame(&cgs.clientinfo[cent->currentState.clientNum], ¢->pe.legs, cent->currentState.legsAnim); + CG_ClearLerpFrame(&cgs.clientinfo[cent->currentState.clientNum], ¢->pe.torso, cent->currentState.torsoAnim); + } else if (cent->gent && cent->gent->client) { + CG_ClearLerpFrame(¢->gent->client->clientInfo, ¢->pe.legs, cent->currentState.legsAnim); + CG_ClearLerpFrame(¢->gent->client->clientInfo, ¢->pe.torso, cent->currentState.torsoAnim); } } - //else???? + // else???? - EvaluateTrajectory( ¢->currentState.pos, cg.time, cent->lerpOrigin ); - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.pos, cg.time, cent->lerpOrigin); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); -// Removed by BTO (VV) - These values are crap anyway. Also changed below to use lerp instead -// VectorCopy( cent->lerpOrigin, cent->rawOrigin ); -// VectorCopy( cent->lerpAngles, cent->rawAngles ); + // Removed by BTO (VV) - These values are crap anyway. Also changed below to use lerp instead + // VectorCopy( cent->lerpOrigin, cent->rawOrigin ); + // VectorCopy( cent->lerpAngles, cent->rawAngles ); - memset( ¢->pe.legs, 0, sizeof( cent->pe.legs ) ); + memset(¢->pe.legs, 0, sizeof(cent->pe.legs)); cent->pe.legs.yawAngle = cent->lerpAngles[YAW]; cent->pe.legs.yawing = qfalse; cent->pe.legs.pitchAngle = 0; cent->pe.legs.pitching = qfalse; - memset( ¢->pe.torso, 0, sizeof( cent->pe.legs ) ); + memset(¢->pe.torso, 0, sizeof(cent->pe.legs)); cent->pe.torso.yawAngle = cent->lerpAngles[YAW]; cent->pe.torso.yawing = qfalse; cent->pe.torso.pitchAngle = cent->lerpAngles[PITCH]; diff --git a/code/cgame/cg_playerstate.cpp b/code/cgame/cg_playerstate.cpp index 3d75db3e57..01e84bcb66 100644 --- a/code/cgame/cg_playerstate.cpp +++ b/code/cgame/cg_playerstate.cpp @@ -29,7 +29,6 @@ along with this program; if not, see . // this line must stay at top so the whole PCH thing works... #include "cg_headers.h" - #include "cg_media.h" /* @@ -39,12 +38,11 @@ CG_CheckAmmo If the ammo has gone low enough to generate the warning, play a sound ============== */ -void CG_CheckAmmo( void ) -{ -// int i; - int total; - int previous; -// int weapons; +void CG_CheckAmmo(void) { + // int i; + int total; + int previous; + // int weapons; #if 0 @@ -81,8 +79,7 @@ void CG_CheckAmmo( void ) #endif // Don't bother drawing the ammo warning when have no weapon selected - if ( cg.weaponSelect == WP_NONE ) - { + if (cg.weaponSelect == WP_NONE) { return; } @@ -94,21 +91,19 @@ void CG_CheckAmmo( void ) return; } - previous = cg.lowAmmoWarning; - if (!total) // We're completely freak'in out! + if (!total) // We're completely freak'in out! { cg.lowAmmoWarning = 2; - } - else // Got a little left + } else // Got a little left { cg.lowAmmoWarning = 1; } // play a sound on transitions - if ( cg.lowAmmoWarning != previous ) { - cgi_S_StartLocalSound( cgs.media.noAmmoSound, CHAN_LOCAL_SOUND ); //"sound/weapons/noammo.wav" + if (cg.lowAmmoWarning != previous) { + cgi_S_StartLocalSound(cgs.media.noAmmoSound, CHAN_LOCAL_SOUND); //"sound/weapons/noammo.wav" } } @@ -117,22 +112,22 @@ void CG_CheckAmmo( void ) CG_DamageFeedback ============== */ -void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { - float left, front, up; - float kick; - int health; - float scale; - vec3_t dir; - vec3_t angles; - float dist; - float yaw, pitch; - - //FIXME: Based on MOD, do different kinds of damage effects, +void CG_DamageFeedback(int yawByte, int pitchByte, int damage) { + float left, front, up; + float kick; + int health; + float scale; + vec3_t dir; + vec3_t angles; + float dist; + float yaw, pitch; + + // FIXME: Based on MOD, do different kinds of damage effects, // for example, Borg damage could progressively tint screen green and raise FOV? // the lower on health you are, the greater the view kick will be health = cg.snap->ps.stats[STAT_HEALTH]; - if ( health < 40 ) { + if (health < 40) { scale = 1; } else { scale = 40.0 / health; @@ -145,7 +140,7 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { kick = 10; // if yaw and pitch are both 255, make the damage always centered (falling, etc) - if ( yawByte == 255 && pitchByte == 255 ) { + if (yawByte == 255 && pitchByte == 255) { cg.damageX = 0; cg.damageY = 0; cg.v_dmg_roll = 0; @@ -159,18 +154,18 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { angles[YAW] = yaw; angles[ROLL] = 0; - AngleVectors( angles, dir, NULL, NULL ); - VectorSubtract( vec3_origin, dir, dir ); + AngleVectors(angles, dir, NULL, NULL); + VectorSubtract(vec3_origin, dir, dir); - front = DotProduct (dir, cg.refdef.viewaxis[0] ); - left = DotProduct (dir, cg.refdef.viewaxis[1] ); - up = DotProduct (dir, cg.refdef.viewaxis[2] ); + front = DotProduct(dir, cg.refdef.viewaxis[0]); + left = DotProduct(dir, cg.refdef.viewaxis[1]); + up = DotProduct(dir, cg.refdef.viewaxis[2]); dir[0] = front; dir[1] = left; dir[2] = 0; - dist = VectorLength( dir ); - if ( dist < 0.1 ) { + dist = VectorLength(dir); + if (dist < 0.1) { dist = 0.1f; } @@ -178,7 +173,7 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { cg.v_dmg_pitch = -kick * front; - if ( front <= 0.1 ) { + if (front <= 0.1) { front = 0.1f; } cg.damageX = -left / front; @@ -186,22 +181,22 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { } // clamp the position - if ( cg.damageX > 1.0 ) { + if (cg.damageX > 1.0) { cg.damageX = 1.0; } - if ( cg.damageX < - 1.0 ) { + if (cg.damageX < -1.0) { cg.damageX = -1.0; } - if ( cg.damageY > 1.0 ) { + if (cg.damageY > 1.0) { cg.damageY = 1.0; } - if ( cg.damageY < - 1.0 ) { + if (cg.damageY < -1.0) { cg.damageY = -1.0; } // don't let the screen flashes vary as much - if ( kick > 10 ) { + if (kick > 10) { kick = 10; } cg.damageValue = kick; @@ -209,9 +204,6 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { cg.damageTime = cg.snap->serverTime; } - - - /* ================ CG_Respawn @@ -219,12 +211,12 @@ CG_Respawn A respawn happened this snapshot ================ */ -void CG_Respawn( void ) { +void CG_Respawn(void) { // no error decay on player movement cg.thisFrameTeleport = qtrue; // display weapons available -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); // select the weapon the server says we are using @@ -232,17 +224,16 @@ void CG_Respawn( void ) { cg.weaponSelect = cg.snap->ps.weapon; } - /* ============== CG_CheckPlayerstateEvents ============== */ -void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { - int i; - int event; - centity_t *cent; +void CG_CheckPlayerstateEvents(playerState_t *ps, playerState_t *ops) { + int i; + int event; + centity_t *cent; #if 0 if ( ps->externalEvent && ps->externalEvent != ops->externalEvent ) { @@ -253,15 +244,14 @@ void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { } #endif - for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) { - if ( ps->events[i & (MAX_PS_EVENTS-1)] != ops->events[i & (MAX_PS_EVENTS-1)] - || i >= ops->eventSequence ) { - event = ps->events[ i & (MAX_PS_EVENTS-1) ]; + for (i = ps->eventSequence - MAX_PS_EVENTS; i < ps->eventSequence; i++) { + if (ps->events[i & (MAX_PS_EVENTS - 1)] != ops->events[i & (MAX_PS_EVENTS - 1)] || i >= ops->eventSequence) { + event = ps->events[i & (MAX_PS_EVENTS - 1)]; - cent = &cg_entities[ ps->clientNum ]; + cent = &cg_entities[ps->clientNum]; cent->currentState.event = event; - cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ]; - CG_EntityEvent( cent, cent->lerpOrigin ); + cent->currentState.eventParm = ps->eventParms[i & (MAX_PS_EVENTS - 1)]; + CG_EntityEvent(cent, cent->lerpOrigin); } } } @@ -331,28 +321,28 @@ CG_TransitionPlayerState =============== */ -void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) { +void CG_TransitionPlayerState(playerState_t *ps, playerState_t *ops) { // teleporting - if ( ( ps->eFlags ^ ops->eFlags ) & EF_TELEPORT_BIT ) { + if ((ps->eFlags ^ ops->eFlags) & EF_TELEPORT_BIT) { cg.thisFrameTeleport = qtrue; } else { cg.thisFrameTeleport = qfalse; } // check for changing follow mode - if ( ps->clientNum != ops->clientNum ) { + if (ps->clientNum != ops->clientNum) { cg.thisFrameTeleport = qtrue; // make sure we don't get any unwanted transition effects *ops = *ps; } // damage events (player is getting wounded) - if ( ps->damageEvent != ops->damageEvent && ps->damageCount ) { - CG_DamageFeedback( ps->damageYaw, ps->damagePitch, ps->damageCount ); + if (ps->damageEvent != ops->damageEvent && ps->damageCount) { + CG_DamageFeedback(ps->damageYaw, ps->damagePitch, ps->damageCount); } // respawning - if ( ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT] ) { + if (ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT]) { CG_Respawn(); } @@ -360,17 +350,14 @@ void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) { CG_CheckAmmo(); // run events - CG_CheckPlayerstateEvents( ps, ops ); + CG_CheckPlayerstateEvents(ps, ops); // smooth the ducking viewheight change - if ( ps->viewheight != ops->viewheight ) - { - if ( !cg.nextFrameTeleport ) - {//when we crouch/uncrouch in mid-air, our viewhieght doesn't actually change in - //absolute world coordinates, just locally. + if (ps->viewheight != ops->viewheight) { + if (!cg.nextFrameTeleport) { // when we crouch/uncrouch in mid-air, our viewhieght doesn't actually change in + // absolute world coordinates, just locally. cg.duckChange = ps->viewheight - ops->viewheight; cg.duckTime = cg.time; } } } - diff --git a/code/cgame/cg_predict.cpp b/code/cgame/cg_predict.cpp index f0a55359ad..24320d7c6a 100644 --- a/code/cgame/cg_predict.cpp +++ b/code/cgame/cg_predict.cpp @@ -32,10 +32,10 @@ along with this program; if not, see . #include "../game/g_vehicles.h" -static pmove_t cg_pmove; +static pmove_t cg_pmove; -static int cg_numSolidEntities; -static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; +static int cg_numSolidEntities; +static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; /* ==================== @@ -46,53 +46,43 @@ of the entities that are actually solid, to make for more efficient collision detection ==================== */ -void CG_BuildSolidList( void ) -{ - int i; - centity_t *cent; - vec3_t difference; - float dsquared; +void CG_BuildSolidList(void) { + int i; + centity_t *cent; + vec3_t difference; + float dsquared; cg_numSolidEntities = 0; - if(!cg.snap) - { + if (!cg.snap) { return; } - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) - { - if ( cg.snap->entities[ i ].number < ENTITYNUM_WORLD ) - { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + if (cg.snap->entities[i].number < ENTITYNUM_WORLD) { + cent = &cg_entities[cg.snap->entities[i].number]; - if ( cent->gent != NULL && cent->gent->s.solid ) - { + if (cent->gent != NULL && cent->gent->s.solid) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; } } } - dsquared = 5000+500; + dsquared = 5000 + 500; dsquared *= dsquared; - for(i=0;ilerpOrigin, cg.snap->ps.origin, difference); if (cent->currentState.eType == ET_TERRAIN || - ((difference[0]*difference[0]) + (difference[1]*difference[1]) + (difference[2]*difference[2])) <= dsquared) - { + ((difference[0] * difference[0]) + (difference[1] * difference[1]) + (difference[2] * difference[2])) <= dsquared) { cent->currentValid = qtrue; - if ( cent->nextState && cent->nextState->solid ) - { + if (cent->nextState && cent->nextState->solid) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; } - } - else - { + } else { cent->currentValid = qfalse; } } @@ -104,60 +94,57 @@ CG_ClipMoveToEntities ==================== */ -void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask, trace_t *tr ) { - int i, x, zd, zu; - trace_t trace; - entityState_t *ent; - clipHandle_t cmodel; - vec3_t bmins, bmaxs; - vec3_t origin, angles; - centity_t *cent; - - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; +void CG_ClipMoveToEntities(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask, trace_t *tr) { + int i, x, zd, zu; + trace_t trace; + entityState_t *ent; + clipHandle_t cmodel; + vec3_t bmins, bmaxs; + vec3_t origin, angles; + centity_t *cent; + + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == skipNumber ) { + if (ent->number == skipNumber) { continue; } - if ( ent->eType == ET_PUSH_TRIGGER ) { + if (ent->eType == ET_PUSH_TRIGGER) { continue; } - if ( ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_TELEPORT_TRIGGER) { continue; } - if ( ent->solid == SOLID_BMODEL ) { + if (ent->solid == SOLID_BMODEL) { // special value for bmodel - cmodel = cgi_CM_InlineModel( ent->modelindex ); - VectorCopy( cent->lerpAngles, angles ); + cmodel = cgi_CM_InlineModel(ent->modelindex); + VectorCopy(cent->lerpAngles, angles); - //Hmm... this would cause traces against brush movers to snap at 20fps (as with the third person camera)... - //Let's use the lerpOrigin for now and see if it breaks anything... - //EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, origin ); - VectorCopy( cent->lerpOrigin, origin ); + // Hmm... this would cause traces against brush movers to snap at 20fps (as with the third person camera)... + // Let's use the lerpOrigin for now and see if it breaks anything... + // EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, origin ); + VectorCopy(cent->lerpOrigin, origin); } else { // encoded bbox x = (ent->solid & 255); - zd = ((ent->solid>>8) & 255); - zu = ((ent->solid>>16) & 255) - 32; + zd = ((ent->solid >> 8) & 255); + zu = ((ent->solid >> 16) & 255) - 32; bmins[0] = bmins[1] = -x; bmaxs[0] = bmaxs[1] = x; bmins[2] = -zd; bmaxs[2] = zu; - cmodel = cgi_CM_TempBoxModel( bmins, bmaxs );//, cent->gent->contents ); - VectorCopy( vec3_origin, angles ); - VectorCopy( cent->lerpOrigin, origin ); + cmodel = cgi_CM_TempBoxModel(bmins, bmaxs); //, cent->gent->contents ); + VectorCopy(vec3_origin, angles); + VectorCopy(cent->lerpOrigin, origin); } - - cgi_CM_TransformedBoxTrace ( &trace, start, end, - mins, maxs, cmodel, mask, origin, angles); + cgi_CM_TransformedBoxTrace(&trace, start, end, mins, maxs, cmodel, mask, origin, angles); if (trace.allsolid || trace.fraction < tr->fraction) { trace.entityNum = ent->number; @@ -165,7 +152,7 @@ void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t } else if (trace.startsolid) { tr->startsolid = qtrue; } - if ( tr->allsolid ) { + if (tr->allsolid) { return; } } @@ -176,14 +163,14 @@ void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t CG_Trace ================ */ -void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - const int skipNumber, const int mask, const EG2_Collision eG2TraceType/*=G2_NOCOLLIDE*/, const int useLod/*=0*/) { - trace_t t; +void CG_Trace(trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int skipNumber, const int mask, + const EG2_Collision eG2TraceType /*=G2_NOCOLLIDE*/, const int useLod /*=0*/) { + trace_t t; - cgi_CM_BoxTrace ( &t, start, end, mins, maxs, 0, mask); + cgi_CM_BoxTrace(&t, start, end, mins, maxs, 0, mask); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models - CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t); + CG_ClipMoveToEntities(start, mins, maxs, end, skipNumber, mask, &t); *result = t; } @@ -197,25 +184,23 @@ CG_PointContents #define USE_SV_PNT_CONTENTS (1) #if USE_SV_PNT_CONTENTS -int CG_PointContents( const vec3_t point, int passEntityNum ) { - return gi.pointcontents(point,passEntityNum ); -} +int CG_PointContents(const vec3_t point, int passEntityNum) { return gi.pointcontents(point, passEntityNum); } #else -int CG_PointContents( const vec3_t point, int passEntityNum ) { - int i; - entityState_t *ent; - centity_t *cent; +int CG_PointContents(const vec3_t point, int passEntityNum) { + int i; + entityState_t *ent; + centity_t *cent; clipHandle_t cmodel; - int contents; + int contents; - contents = cgi_CM_PointContents (point, 0); + contents = cgi_CM_PointContents(point, 0); - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == passEntityNum ) { + if (ent->number == passEntityNum) { continue; } @@ -223,56 +208,49 @@ int CG_PointContents( const vec3_t point, int passEntityNum ) { continue; } - cmodel = cgi_CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = cgi_CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - contents |= cgi_CM_TransformedPointContents( point, cmodel, ent->origin, ent->angles ); + contents |= cgi_CM_TransformedPointContents(point, cmodel, ent->origin, ent->angles); } return contents; } #endif -void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ) -{ - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD || overrideViewEnt ) - {//don't clamp angles when looking through a viewEntity - for( int i = 0; i < 3; i++ ) - { +void CG_SetClientViewAngles(vec3_t angles, qboolean overrideViewEnt) { + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD || overrideViewEnt) { // don't clamp angles when looking through a viewEntity + for (int i = 0; i < 3; i++) { cg.predicted_player_state.viewangles[i] = angles[i]; cg.predicted_player_state.delta_angles[i] = 0; cg.snap->ps.viewangles[i] = angles[i]; cg.snap->ps.delta_angles[i] = 0; g_entities[0].client->pers.cmd_angles[i] = ANGLE2SHORT(angles[i]); } - cgi_SetUserCmdAngles( angles[PITCH], angles[YAW], angles[ROLL] ); + cgi_SetUserCmdAngles(angles[PITCH], angles[YAW], angles[ROLL]); } } -extern qboolean PM_AdjustAnglesToGripper( gentity_t *gent, usercmd_t *cmd ); -extern qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ); -extern qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ); -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -qboolean CG_CheckModifyUCmd( usercmd_t *cmd, vec3_t viewangles ) -{ +extern qboolean PM_AdjustAnglesToGripper(gentity_t *gent, usercmd_t *cmd); +extern qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly); +extern qboolean G_CheckClampUcmd(gentity_t *ent, usercmd_t *ucmd); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +qboolean CG_CheckModifyUCmd(usercmd_t *cmd, vec3_t viewangles) { qboolean overridAngles = qfalse; - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//controlling something else - memset( cmd, 0, sizeof( usercmd_t ) ); + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // controlling something else + memset(cmd, 0, sizeof(usercmd_t)); /* //to keep pointing in same dir, need to set cmd.angles cmd->angles[PITCH] = ANGLE2SHORT( cg.snap->ps.viewangles[PITCH] ) - cg.snap->ps.delta_angles[PITCH]; cmd->angles[YAW] = ANGLE2SHORT( cg.snap->ps.viewangles[YAW] ) - cg.snap->ps.delta_angles[YAW]; cmd->angles[ROLL] = 0; */ - VectorCopy( g_entities[0].pos4, viewangles ); + VectorCopy(g_entities[0].pos4, viewangles); overridAngles = qtrue; - //CG_SetClientViewAngles( g_entities[cg.snap->ps.viewEntity].client->ps.viewangles, qtrue ); - } - else if ( G_IsRidingVehicle( &g_entities[0] ) ) - { + // CG_SetClientViewAngles( g_entities[cg.snap->ps.viewEntity].client->ps.viewangles, qtrue ); + } else if (G_IsRidingVehicle(&g_entities[0])) { overridAngles = qtrue; /* int vehIndex = g_entities[0].owner->client->ps.vehicleIndex; @@ -291,35 +269,26 @@ qboolean CG_CheckModifyUCmd( usercmd_t *cmd, vec3_t viewangles ) */ } - if ( g_entities[0].inuse && g_entities[0].client ) - { - if ( !PM_AdjustAnglesToGripper( &g_entities[0], cmd ) ) - { - if ( PM_AdjustAnglesForSpinningFlip( &g_entities[0], cmd, qtrue ) ) - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + if (g_entities[0].inuse && g_entities[0].client) { + if (!PM_AdjustAnglesToGripper(&g_entities[0], cmd)) { + if (PM_AdjustAnglesForSpinningFlip(&g_entities[0], cmd, qtrue)) { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } - } - else - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + } else { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } - if ( G_CheckClampUcmd( &g_entities[0], cmd ) ) - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + if (G_CheckClampUcmd(&g_entities[0], cmd)) { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } @@ -327,26 +296,17 @@ qboolean CG_CheckModifyUCmd( usercmd_t *cmd, vec3_t viewangles ) return overridAngles; } -qboolean CG_OnMovingPlat( playerState_t *ps ) -{ - if ( ps->groundEntityNum != ENTITYNUM_NONE ) - { +qboolean CG_OnMovingPlat(playerState_t *ps) { + if (ps->groundEntityNum != ENTITYNUM_NONE) { entityState_t *es = &cg_entities[ps->groundEntityNum].currentState; - if ( es->eType == ET_MOVER ) - {//on a mover - if ( es->pos.trType != TR_STATIONARY ) - { - if ( es->pos.trType != TR_LINEAR_STOP && es->pos.trType != TR_NONLINEAR_STOP ) - {//a constant mover - if ( !VectorCompare( vec3_origin, es->pos.trDelta ) ) - {//is moving + if (es->eType == ET_MOVER) { // on a mover + if (es->pos.trType != TR_STATIONARY) { + if (es->pos.trType != TR_LINEAR_STOP && es->pos.trType != TR_NONLINEAR_STOP) { // a constant mover + if (!VectorCompare(vec3_origin, es->pos.trDelta)) { // is moving return qtrue; } - } - else - {//a linear-stop mover - if ( es->pos.trTime+es->pos.trDuration > cg.time ) - {//still moving + } else { // a linear-stop mover + if (es->pos.trTime + es->pos.trDuration > cg.time) { // still moving return qtrue; } } @@ -363,141 +323,112 @@ Generates cg.predicted_player_state by interpolating between cg.snap->player_state and cg.nextFrame->player_state ======================== */ -void CG_InterpolatePlayerState( qboolean grabAngles ) { - float f; - int i; - playerState_t *out; - snapshot_t *prev, *next; - qboolean skip = qfalse; - vec3_t oldOrg; +void CG_InterpolatePlayerState(qboolean grabAngles) { + float f; + int i; + playerState_t *out; + snapshot_t *prev, *next; + qboolean skip = qfalse; + vec3_t oldOrg; out = &cg.predicted_player_state; prev = cg.snap; next = cg.nextSnap; - VectorCopy(out->origin,oldOrg); + VectorCopy(out->origin, oldOrg); *out = cg.snap->ps; // if we are still allowing local input, short circuit the view angles - if ( grabAngles ) { - usercmd_t cmd; - int cmdNum; + if (grabAngles) { + usercmd_t cmd; + int cmdNum; cmdNum = cgi_GetCurrentCmdNumber(); - cgi_GetUserCmd( cmdNum, &cmd ); + cgi_GetUserCmd(cmdNum, &cmd); - skip = CG_CheckModifyUCmd( &cmd, out->viewangles ); + skip = CG_CheckModifyUCmd(&cmd, out->viewangles); - if ( !skip ) - { - //NULL so that it doesn't execute a block of code that must be run from game - PM_UpdateViewAngles( out, &cmd, NULL ); + if (!skip) { + // NULL so that it doesn't execute a block of code that must be run from game + PM_UpdateViewAngles(out, &cmd, NULL); } } // if the next frame is a teleport, we can't lerp to it - if ( cg.nextFrameTeleport ) - { + if (cg.nextFrameTeleport) { return; } - if (!( !next || next->serverTime <= prev->serverTime ) ) - { + if (!(!next || next->serverTime <= prev->serverTime)) { - f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime ); + f = (float)(cg.time - prev->serverTime) / (next->serverTime - prev->serverTime); i = next->ps.bobCycle; - if ( i < prev->ps.bobCycle ) - { - i += 256; // handle wraparound + if (i < prev->ps.bobCycle) { + i += 256; // handle wraparound } - out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle ); + out->bobCycle = prev->ps.bobCycle + f * (i - prev->ps.bobCycle); - for ( i = 0 ; i < 3 ; i++ ) - { - out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i] ); - if ( !grabAngles ) - { - out->viewangles[i] = LerpAngle( - prev->ps.viewangles[i], next->ps.viewangles[i], f ); + for (i = 0; i < 3; i++) { + out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i]); + if (!grabAngles) { + out->viewangles[i] = LerpAngle(prev->ps.viewangles[i], next->ps.viewangles[i], f); } - out->velocity[i] = prev->ps.velocity[i] + - f * (next->ps.velocity[i] - prev->ps.velocity[i] ); + out->velocity[i] = prev->ps.velocity[i] + f * (next->ps.velocity[i] - prev->ps.velocity[i]); } } - bool onPlat=false; - centity_t *pent=0; - if (out->groundEntityNum>0) - { - pent=&cg_entities[out->groundEntityNum]; - if (pent->currentState.eType == ET_MOVER ) + bool onPlat = false; + centity_t *pent = 0; + if (out->groundEntityNum > 0) { + pent = &cg_entities[out->groundEntityNum]; + if (pent->currentState.eType == ET_MOVER) { - onPlat=true; + onPlat = true; } } - if ( - cg.validPPS && - cg_smoothPlayerPos.value>0.0f && - cg_smoothPlayerPos.value<1.0f && - !onPlat - ) - { + if (cg.validPPS && cg_smoothPlayerPos.value > 0.0f && cg_smoothPlayerPos.value < 1.0f && !onPlat) { // 0 = no smoothing, 1 = no movement - for (i=0;i<3;i++) - { - out->origin[i]=cg_smoothPlayerPos.value*(oldOrg[i]-out->origin[i])+out->origin[i]; + for (i = 0; i < 3; i++) { + out->origin[i] = cg_smoothPlayerPos.value * (oldOrg[i] - out->origin[i]) + out->origin[i]; } - } - else if (onPlat&&cg_smoothPlayerPlat.value>0.0f&&cg_smoothPlayerPlat.value<1.0f) - { -// if (cg.frametime<150) -// { + } else if (onPlat && cg_smoothPlayerPlat.value > 0.0f && cg_smoothPlayerPlat.value < 1.0f) { + // if (cg.frametime<150) + // { assert(pent); - vec3_t p1,p2,vel; + vec3_t p1, p2, vel; float lerpTime; - - EvaluateTrajectory( &pent->currentState.pos,cg.snap->serverTime, p1 ); - if ( cg.nextSnap &&cg.nextSnap->serverTime > cg.snap->serverTime && pent->nextState) - { - EvaluateTrajectory( &pent->nextState->pos,cg.nextSnap->serverTime, p2 ); - lerpTime=float(cg.nextSnap->serverTime - cg.snap->serverTime); - } - else - { - EvaluateTrajectory( &pent->currentState.pos,cg.snap->serverTime+50, p2 ); - lerpTime=50.0f; + EvaluateTrajectory(&pent->currentState.pos, cg.snap->serverTime, p1); + if (cg.nextSnap && cg.nextSnap->serverTime > cg.snap->serverTime && pent->nextState) { + EvaluateTrajectory(&pent->nextState->pos, cg.nextSnap->serverTime, p2); + lerpTime = float(cg.nextSnap->serverTime - cg.snap->serverTime); + } else { + EvaluateTrajectory(&pent->currentState.pos, cg.snap->serverTime + 50, p2); + lerpTime = 50.0f; } - float accel=cg_smoothPlayerPlatAccel.value*cg.frametime/lerpTime; + float accel = cg_smoothPlayerPlatAccel.value * cg.frametime / lerpTime; - if (accel>20.0f) - { - accel=20.0f; + if (accel > 20.0f) { + accel = 20.0f; } - for (i=0;i<3;i++) - { - vel[i]=accel*(p2[i]-p1[i]); + for (i = 0; i < 3; i++) { + vel[i] = accel * (p2[i] - p1[i]); } - VectorAdd(out->origin,vel,out->origin); + VectorAdd(out->origin, vel, out->origin); - if (cg.validPPS && - cg_smoothPlayerPlat.value>0.0f && - cg_smoothPlayerPlat.value<1.0f - ) - { + if (cg.validPPS && cg_smoothPlayerPlat.value > 0.0f && cg_smoothPlayerPlat.value < 1.0f) { // 0 = no smoothing, 1 = no movement - for (i=0;i<3;i++) - { - out->origin[i]=cg_smoothPlayerPlat.value*(oldOrg[i]-out->origin[i])+out->origin[i]; + for (i = 0; i < 3; i++) { + out->origin[i] = cg_smoothPlayerPlat.value * (oldOrg[i] - out->origin[i]) + out->origin[i]; } } -// } + // } } } @@ -506,26 +437,26 @@ void CG_InterpolatePlayerState( qboolean grabAngles ) { CG_TouchItem =================== */ -void CG_TouchItem( centity_t *cent ) { - gitem_t *item; +void CG_TouchItem(centity_t *cent) { + gitem_t *item; // never pick an item up twice in a prediction - if ( cent->miscTime == cg.time ) { + if (cent->miscTime == cg.time) { return; } - if ( !BG_PlayerTouchesItem( &cg.predicted_player_state, ¢->currentState, cg.time ) ) { + if (!BG_PlayerTouchesItem(&cg.predicted_player_state, ¢->currentState, cg.time)) { return; } - if ( !BG_CanItemBeGrabbed( ¢->currentState, &cg.predicted_player_state ) ) { - return; // can't hold it + if (!BG_CanItemBeGrabbed(¢->currentState, &cg.predicted_player_state)) { + return; // can't hold it } - item = &bg_itemlist[ cent->currentState.modelindex ]; + item = &bg_itemlist[cent->currentState.modelindex]; // grab it - AddEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.modelindex , &cg.predicted_player_state); + AddEventToPlayerstate(EV_ITEM_PICKUP, cent->currentState.modelindex, &cg.predicted_player_state); // remove it from the frame so it won't be drawn cent->currentState.eFlags |= EF_NODRAW; @@ -534,16 +465,15 @@ void CG_TouchItem( centity_t *cent ) { cent->miscTime = cg.time; // if its a weapon, give them some predicted ammo so the autoswitch will work - if ( item->giType == IT_WEAPON ) { + if (item->giType == IT_WEAPON) { int ammotype = weaponData[item->giTag].ammoIndex; - cg.predicted_player_state.stats[ STAT_WEAPONS ] |= 1 << item->giTag; - if ( !cg.predicted_player_state.ammo[ ammotype] ) { - cg.predicted_player_state.ammo[ ammotype ] = 1; + cg.predicted_player_state.stats[STAT_WEAPONS] |= 1 << item->giTag; + if (!cg.predicted_player_state.ammo[ammotype]) { + cg.predicted_player_state.ammo[ammotype] = 1; } } } - /* ========================= CG_TouchTriggerPrediction @@ -552,68 +482,66 @@ Predict push triggers and items Only called for the last command ========================= */ -void CG_TouchTriggerPrediction( void ) { - int i; - trace_t trace; - entityState_t *ent; +void CG_TouchTriggerPrediction(void) { + int i; + trace_t trace; + entityState_t *ent; clipHandle_t cmodel; - centity_t *cent; - qboolean spectator; + centity_t *cent; + qboolean spectator; // dead clients don't activate triggers - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 ) { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0) { return; } - spectator = (qboolean)( cg.predicted_player_state.pm_type == PM_SPECTATOR ); + spectator = (qboolean)(cg.predicted_player_state.pm_type == PM_SPECTATOR); - if ( cg.predicted_player_state.pm_type != PM_NORMAL && !spectator ) { + if (cg.predicted_player_state.pm_type != PM_NORMAL && !spectator) { return; } - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; ent = ¢->currentState; - if ( ent->eType == ET_ITEM && !spectator ) { - CG_TouchItem( cent ); + if (ent->eType == ET_ITEM && !spectator) { + CG_TouchItem(cent); continue; } - if ( ent->eType != ET_PUSH_TRIGGER && ent->eType != ET_TELEPORT_TRIGGER ) { + if (ent->eType != ET_PUSH_TRIGGER && ent->eType != ET_TELEPORT_TRIGGER) { continue; } - if ( ent->solid != SOLID_BMODEL ) { + if (ent->solid != SOLID_BMODEL) { continue; } - cmodel = cgi_CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = cgi_CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - cgi_CM_BoxTrace( &trace, cg.predicted_player_state.origin, cg.predicted_player_state.origin, - cg_pmove.mins, cg_pmove.maxs, cmodel, -1 ); + cgi_CM_BoxTrace(&trace, cg.predicted_player_state.origin, cg.predicted_player_state.origin, cg_pmove.mins, cg_pmove.maxs, cmodel, -1); - if ( !trace.startsolid ) { + if (!trace.startsolid) { continue; } - if ( ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_TELEPORT_TRIGGER) { cg.hyperspace = qtrue; } else { // we hit this push trigger - if ( spectator ) { + if (spectator) { continue; } - VectorCopy( ent->origin2, cg.predicted_player_state.velocity ); + VectorCopy(ent->origin2, cg.predicted_player_state.velocity); } } } - /* ================= CG_PredictPlayerState @@ -636,23 +564,22 @@ We detect prediction errors and allow them to be decayed off over several frames to ease the jerk. ================= */ -extern qboolean player_locked; -void CG_PredictPlayerState( void ) { - int cmdNum, current; - playerState_t oldPlayerState; +extern qboolean player_locked; +void CG_PredictPlayerState(void) { + int cmdNum, current; + playerState_t oldPlayerState; - cg.hyperspace = qfalse; // will be set if touching a trigger_teleport + cg.hyperspace = qfalse; // will be set if touching a trigger_teleport // if this is the first frame we must guarantee // predicted_player_state is valid even if there is some // other error condition - if ( !cg.validPPS ) { + if (!cg.validPPS) { cg.validPPS = qtrue; cg.predicted_player_state = cg.snap->ps; } - - if ( 1 )//cg_timescale.value >= 1.0f ) + if (1) // cg_timescale.value >= 1.0f ) { // demo playback just copies the moves /* @@ -663,18 +590,18 @@ void CG_PredictPlayerState( void ) { */ // non-predicting local movement will grab the latest angles - CG_InterpolatePlayerState( qtrue ); + CG_InterpolatePlayerState(qtrue); return; } // prepare for pmove - //FIXME: is this bad??? + // FIXME: is this bad??? cg_pmove.gent = NULL; cg_pmove.ps = &cg.predicted_player_state; cg_pmove.trace = CG_Trace; cg_pmove.pointcontents = CG_PointContents; cg_pmove.tracemask = MASK_PLAYERSOLID; - cg_pmove.noFootsteps = qfalse;//( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; + cg_pmove.noFootsteps = qfalse; //( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; // save the state before the pmove so we can detect transitions oldPlayerState = cg.predicted_player_state; @@ -683,7 +610,7 @@ void CG_PredictPlayerState( void ) { cmdNum = cg.snap->cmdNum; current = cgi_GetCurrentCmdNumber(); - if ( current - cmdNum >= CMD_BACKUP ) { + if (current - cmdNum >= CMD_BACKUP) { return; } @@ -691,7 +618,7 @@ void CG_PredictPlayerState( void ) { cg.predicted_player_state = cg.snap->ps; // we should always be predicting at least one frame - if ( cmdNum >= current ) { + if (cmdNum >= current) { return; } @@ -702,36 +629,35 @@ void CG_PredictPlayerState( void ) { // from the snapshot, but on a wan we will have // to predict several commands to get to the point // we want to compare - if ( cmdNum == current - 1 ) { - vec3_t delta; - float len; + if (cmdNum == current - 1) { + vec3_t delta; + float len; - if ( cg.thisFrameTeleport ) { + if (cg.thisFrameTeleport) { // a teleport will not cause an error decay - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); cg.thisFrameTeleport = qfalse; } else { - vec3_t adjusted; - CG_AdjustPositionForMover( cg.predicted_player_state.origin, - cg.predicted_player_state.groundEntityNum, cg.oldTime, adjusted ); + vec3_t adjusted; + CG_AdjustPositionForMover(cg.predicted_player_state.origin, cg.predicted_player_state.groundEntityNum, cg.oldTime, adjusted); - VectorSubtract( oldPlayerState.origin, adjusted, delta ); - len = VectorLength( delta ); - if ( len > 0.1 ) { - if ( cg_errorDecay.integer ) { - int t; - float f; + VectorSubtract(oldPlayerState.origin, adjusted, delta); + len = VectorLength(delta); + if (len > 0.1) { + if (cg_errorDecay.integer) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f < 0 ) { + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f < 0) { f = 0; } - VectorScale( cg.predictedError, f, cg.predictedError ); + VectorScale(cg.predictedError, f, cg.predictedError); } else { - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); } - VectorAdd( delta, cg.predictedError, cg.predictedError ); + VectorAdd(delta, cg.predictedError, cg.predictedError); cg.predictedErrorTime = cg.oldTime; } } @@ -742,38 +668,32 @@ void CG_PredictPlayerState( void ) { // this should never happen, because we check ranges at // the top of the function cmdNum++; - if ( !cgi_GetUserCmd( cmdNum, &cg_pmove.cmd ) ) { + if (!cgi_GetUserCmd(cmdNum, &cg_pmove.cmd)) { break; } - gentity_t *ent = &g_entities[0];//cheating and dirty, I know, but this is a SP game so prediction can cheat - if ( player_locked || - (ent && !ent->s.number&&ent->aimDebounceTime>level.time) || - (ent && ent->client && ent->client->ps.pm_time && (ent->client->ps.pm_flags&PMF_TIME_KNOCKBACK)) || - (ent && ent->forcePushTime > level.time) ) - {//lock out player control unless dead - //VectorClear( cg_pmove.cmd.angles ); + gentity_t *ent = &g_entities[0]; // cheating and dirty, I know, but this is a SP game so prediction can cheat + if (player_locked || (ent && !ent->s.number && ent->aimDebounceTime > level.time) || + (ent && ent->client && ent->client->ps.pm_time && (ent->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) || + (ent && ent->forcePushTime > level.time)) { // lock out player control unless dead + // VectorClear( cg_pmove.cmd.angles ); cg_pmove.cmd.forwardmove = 0; cg_pmove.cmd.rightmove = 0; cg_pmove.cmd.buttons = 0; cg_pmove.cmd.upmove = 0; } - CG_CheckModifyUCmd( &cg_pmove.cmd, NULL ); - //FIXME: prediction on clients in timescale results in jerky positional translation - Pmove( &cg_pmove ); + CG_CheckModifyUCmd(&cg_pmove.cmd, NULL); + // FIXME: prediction on clients in timescale results in jerky positional translation + Pmove(&cg_pmove); // add push trigger movement effects CG_TouchTriggerPrediction(); - } while ( cmdNum < current ); + } while (cmdNum < current); // adjust for the movement of the groundentity - CG_AdjustPositionForMover( cg.predicted_player_state.origin, - cg.predicted_player_state.groundEntityNum, - cg.time, cg.predicted_player_state.origin ); + CG_AdjustPositionForMover(cg.predicted_player_state.origin, cg.predicted_player_state.groundEntityNum, cg.time, cg.predicted_player_state.origin); // fire events and other transition triggered things - CG_TransitionPlayerState( &cg.predicted_player_state, &oldPlayerState ); + CG_TransitionPlayerState(&cg.predicted_player_state, &oldPlayerState); } - - diff --git a/code/cgame/cg_scoreboard.cpp b/code/cgame/cg_scoreboard.cpp index b4e54e97fd..809f2350ac 100644 --- a/code/cgame/cg_scoreboard.cpp +++ b/code/cgame/cg_scoreboard.cpp @@ -27,8 +27,7 @@ along with this program; if not, see . #include "../game/objectives.h" #include "../game/b_local.h" -#define SCOREBOARD_WIDTH (26*BIGCHAR_WIDTH) - +#define SCOREBOARD_WIDTH (26 * BIGCHAR_WIDTH) /* static void Scoreboard_Draw( void ) @@ -82,93 +81,87 @@ static void Scoreboard_Draw( void ) } */ - - /* ================= CG_MissionFailed ================= */ int statusTextIndex = -1; -void CG_MissionFailed(void) -{ +void CG_MissionFailed(void) { char *text; - if (!cg.missionFailedScreen) - { + if (!cg.missionFailedScreen) { cgi_UI_SetActive_Menu("missionfailed_menu"); cg.missionFailedScreen = qtrue; - switch (statusTextIndex) - { - case -1: //Our HERO DIED!!! - text = "@SP_INGAME_MISSIONFAILED_PLAYER"; - break; - case MISSIONFAILED_JAN: - text = "@SP_INGAME_MISSIONFAILED_JAN"; - break; - case MISSIONFAILED_LUKE: - text = "@SP_INGAME_MISSIONFAILED_LUKE"; - break; - case MISSIONFAILED_LANDO: - text = "@SP_INGAME_MISSIONFAILED_LANDO"; - break; - case MISSIONFAILED_R5D2: - text = "@SP_INGAME_MISSIONFAILED_R5D2"; - break; - case MISSIONFAILED_WARDEN: - text = "@SP_INGAME_MISSIONFAILED_WARDEN"; - break; - case MISSIONFAILED_PRISONERS: - text = "@SP_INGAME_MISSIONFAILED_PRISONERS"; - break; - case MISSIONFAILED_EMPLACEDGUNS: - text = "@SP_INGAME_MISSIONFAILED_EMPLACEDGUNS"; - break; - case MISSIONFAILED_LADYLUCK: - text = "@SP_INGAME_MISSIONFAILED_LADYLUCK"; - break; - case MISSIONFAILED_KYLECAPTURE: - text = "@SP_INGAME_MISSIONFAILED_KYLECAPTURE"; - break; - case MISSIONFAILED_TOOMANYALLIESDIED: - text = "@SP_INGAME_MISSIONFAILED_TOOMANYALLIESDIED"; - break; - - case MISSIONFAILED_CHEWIE: - text = "@SP_INGAME_MISSIONFAILED_CHEWIE"; - break; - - case MISSIONFAILED_KYLE: - text = "@SP_INGAME_MISSIONFAILED_KYLE"; - break; - - case MISSIONFAILED_ROSH: - text = "@SP_INGAME_MISSIONFAILED_ROSH"; - break; - - case MISSIONFAILED_WEDGE: - text = "@SP_INGAME_MISSIONFAILED_WEDGE"; - break; - - case MISSIONFAILED_TURNED: - text = "@SP_INGAME_MISSIONFAILED_TURNED"; - break; - - default: - text = "@SP_INGAME_MISSIONFAILED_UNKNOWN"; - break; + switch (statusTextIndex) { + case -1: // Our HERO DIED!!! + text = "@SP_INGAME_MISSIONFAILED_PLAYER"; + break; + case MISSIONFAILED_JAN: + text = "@SP_INGAME_MISSIONFAILED_JAN"; + break; + case MISSIONFAILED_LUKE: + text = "@SP_INGAME_MISSIONFAILED_LUKE"; + break; + case MISSIONFAILED_LANDO: + text = "@SP_INGAME_MISSIONFAILED_LANDO"; + break; + case MISSIONFAILED_R5D2: + text = "@SP_INGAME_MISSIONFAILED_R5D2"; + break; + case MISSIONFAILED_WARDEN: + text = "@SP_INGAME_MISSIONFAILED_WARDEN"; + break; + case MISSIONFAILED_PRISONERS: + text = "@SP_INGAME_MISSIONFAILED_PRISONERS"; + break; + case MISSIONFAILED_EMPLACEDGUNS: + text = "@SP_INGAME_MISSIONFAILED_EMPLACEDGUNS"; + break; + case MISSIONFAILED_LADYLUCK: + text = "@SP_INGAME_MISSIONFAILED_LADYLUCK"; + break; + case MISSIONFAILED_KYLECAPTURE: + text = "@SP_INGAME_MISSIONFAILED_KYLECAPTURE"; + break; + case MISSIONFAILED_TOOMANYALLIESDIED: + text = "@SP_INGAME_MISSIONFAILED_TOOMANYALLIESDIED"; + break; + + case MISSIONFAILED_CHEWIE: + text = "@SP_INGAME_MISSIONFAILED_CHEWIE"; + break; + + case MISSIONFAILED_KYLE: + text = "@SP_INGAME_MISSIONFAILED_KYLE"; + break; + + case MISSIONFAILED_ROSH: + text = "@SP_INGAME_MISSIONFAILED_ROSH"; + break; + + case MISSIONFAILED_WEDGE: + text = "@SP_INGAME_MISSIONFAILED_WEDGE"; + break; + + case MISSIONFAILED_TURNED: + text = "@SP_INGAME_MISSIONFAILED_TURNED"; + break; + + default: + text = "@SP_INGAME_MISSIONFAILED_UNKNOWN"; + break; } gi.cvar_set("ui_missionfailed_text", text); } -// w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); -// cgi_R_Font_DrawString(320 - w/2, y+30, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); - -// cgi_SP_GetStringTextString( "SP_INGAME_RELOADMISSION", text, sizeof(text) ); -// w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); -// cgi_R_Font_DrawString(320 - w/2, 450, text, colorTable[CT_CYAN], cgs.media.qhFontSmall, -1, 1.0f); + // w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); + // cgi_R_Font_DrawString(320 - w/2, y+30, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); + // cgi_SP_GetStringTextString( "SP_INGAME_RELOADMISSION", text, sizeof(text) ); + // w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + // cgi_R_Font_DrawString(320 - w/2, 450, text, colorTable[CT_CYAN], cgs.media.qhFontSmall, -1, 1.0f); } /* @@ -367,18 +360,14 @@ Draw the normal in-game scoreboard return value is bool to NOT draw centerstring ================= */ -qboolean CG_DrawScoreboard( void ) -{ +qboolean CG_DrawScoreboard(void) { // don't draw anything if the menu is up - if ( cg_paused.integer ) - { + if (cg_paused.integer) { return qfalse; } // Character is either dead, or a script has brought up the screen - if (((cg.predicted_player_state.pm_type == PM_DEAD) && (cg.missionStatusDeadTime < level.time)) - || (cg.missionStatusShow)) - { + if (((cg.predicted_player_state.pm_type == PM_DEAD) && (cg.missionStatusDeadTime < level.time)) || (cg.missionStatusShow)) { CG_MissionFailed(); return qtrue; } @@ -386,9 +375,6 @@ qboolean CG_DrawScoreboard( void ) return qfalse; } -void ScoreBoardReset(void) -{ -} +void ScoreBoardReset(void) {} //================================================================================ - diff --git a/code/cgame/cg_servercmds.cpp b/code/cgame/cg_servercmds.cpp index 390fe61141..295c274fdd 100644 --- a/code/cgame/cg_servercmds.cpp +++ b/code/cgame/cg_servercmds.cpp @@ -28,7 +28,6 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* ================ CG_ParseServerinfo @@ -37,190 +36,168 @@ This is called explicitly when the gamestate is first received, and whenever the server updates any serverinfo flagged cvars ================ */ -void CG_ParseServerinfo( void ) { - const char *info; - const char *mapname; - - info = CG_ConfigString( CS_SERVERINFO ); - cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) ); - cgs.teamflags = atoi( Info_ValueForKey( info, "teamflags" ) ); - cgs.timelimit = atoi( Info_ValueForKey( info, "timelimit" ) ); +void CG_ParseServerinfo(void) { + const char *info; + const char *mapname; + + info = CG_ConfigString(CS_SERVERINFO); + cgs.dmflags = atoi(Info_ValueForKey(info, "dmflags")); + cgs.teamflags = atoi(Info_ValueForKey(info, "teamflags")); + cgs.timelimit = atoi(Info_ValueForKey(info, "timelimit")); cgs.maxclients = 1; - mapname = Info_ValueForKey( info, "mapname" ); - Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname ); - const char *p = strrchr(mapname,'/'); - Q_strncpyz( cgs.stripLevelName[0], p?p+1:mapname, sizeof(cgs.stripLevelName[0]) ); - Q_strupr( cgs.stripLevelName[0] ); - for (int i=1; i= CS_MODELS && num < CS_MODELS+MAX_MODELS ) { - cgs.model_draw[ num-CS_MODELS ] = cgi_R_RegisterModel( str ); -// OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); -// GHOUL2 Insert start - } else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) { - cgs.skins[ num-CS_CHARSKINS ] = cgi_R_RegisterSkin( str ); -// Ghoul2 Insert end - } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) { - if ( str[0] != '*' ) { - cgs.sound_precache[ num-CS_SOUNDS] = cgi_S_RegisterSound( str ); + } else if (num >= CS_MODELS && num < CS_MODELS + MAX_MODELS) { + cgs.model_draw[num - CS_MODELS] = cgi_R_RegisterModel(str); + // OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); + // GHOUL2 Insert start + } else if (num >= CS_CHARSKINS && num < CS_CHARSKINS + MAX_CHARSKINS) { + cgs.skins[num - CS_CHARSKINS] = cgi_R_RegisterSkin(str); + // Ghoul2 Insert end + } else if (num >= CS_SOUNDS && num < CS_SOUNDS + MAX_SOUNDS) { + if (str[0] != '*') { + cgs.sound_precache[num - CS_SOUNDS] = cgi_S_RegisterSound(str); } - } - else if ( num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX ) - { - theFxScheduler.RegisterEffect( str ); - } - else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) { - CG_NewClientinfo( num - CS_PLAYERS ); - CG_RegisterClientModels( num - CS_PLAYERS ); - } - else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES*3)) - { + } else if (num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX) { + theFxScheduler.RegisterEffect(str); + } else if (num >= CS_PLAYERS && num < CS_PLAYERS + MAX_CLIENTS) { + CG_NewClientinfo(num - CS_PLAYERS); + CG_RegisterClientModels(num - CS_PLAYERS); + } else if (num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES * 3)) { CG_SetLightstyle(num - CS_LIGHT_STYLES); - } - else if ( num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX ) - { - cgi_R_WorldEffectCommand( str ); + } else if (num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX) { + cgi_R_WorldEffectCommand(str); } } -static void CG_CenterPrint_f( void ) { - CG_CenterPrint( CG_Argv( 1 ), SCREEN_HEIGHT * 0.25 ); -} +static void CG_CenterPrint_f(void) { CG_CenterPrint(CG_Argv(1), SCREEN_HEIGHT * 0.25); } -static void CG_Print_f( void ) { - CG_Printf( "%s", CG_Argv( 1 ) ); -} +static void CG_Print_f(void) { CG_Printf("%s", CG_Argv(1)); } -static void CG_CaptionText_f( void ) { - sfxHandle_t sound = (sfxHandle_t)atoi( CG_Argv( 2 ) ); +static void CG_CaptionText_f(void) { + sfxHandle_t sound = (sfxHandle_t)atoi(CG_Argv(2)); - CG_CaptionText( CG_Argv( 1 ), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND ); + CG_CaptionText(CG_Argv(1), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND); } -static void CG_ScrollText_f( void ) { - CG_ScrollText( CG_Argv( 1 ), SCREEN_WIDTH - 16 ); -} +static void CG_ScrollText_f(void) { CG_ScrollText(CG_Argv(1), SCREEN_WIDTH - 16); } -static void CG_LCARSText_f( void ) { - CG_Printf( "CG_LCARSText() being called. Tell Ste\n" "String: \"%s\"\n", CG_Argv( 1 ) ); +static void CG_LCARSText_f(void) { + CG_Printf("CG_LCARSText() being called. Tell Ste\n" + "String: \"%s\"\n", + CG_Argv(1)); } -static void CG_ClientLevelShot_f( void ) { +static void CG_ClientLevelShot_f(void) { // clientLevelShot is sent before taking a special screenshot for // the menu system during development cg.levelShot = qtrue; } typedef struct serverCommand_s { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } serverCommand_t; -static int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((serverCommand_t*)b)->cmd ); -} +static int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((serverCommand_t *)b)->cmd); } /* This array MUST be sorted correctly by alphabetical name field */ -static serverCommand_t commands[] = { - { "chat", CG_Print_f }, - { "clientLevelShot", CG_ClientLevelShot_f }, - { "cp", CG_CenterPrint_f }, - { "cs", CG_ConfigStringModified }, - { "ct", CG_CaptionText_f }, - { "cts", CG_CaptionTextStop }, - { "lt", CG_LCARSText_f }, - { "print", CG_Print_f }, - { "st", CG_ScrollText_f }, +static serverCommand_t commands[] = { + {"chat", CG_Print_f}, {"clientLevelShot", CG_ClientLevelShot_f}, + {"cp", CG_CenterPrint_f}, {"cs", CG_ConfigStringModified}, + {"ct", CG_CaptionText_f}, {"cts", CG_CaptionTextStop}, + {"lt", CG_LCARSText_f}, {"print", CG_Print_f}, + {"st", CG_ScrollText_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -230,26 +207,25 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -static void CG_ServerCommand( void ) { - const char *cmd = CG_Argv( 0 ); - serverCommand_t *command = NULL; +static void CG_ServerCommand(void) { + const char *cmd = CG_Argv(0); + serverCommand_t *command = NULL; - if ( !cmd[0] ) { + if (!cmd[0]) { // server claimed the command return; } - command = (serverCommand_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp ); + command = (serverCommand_t *)Q_LinearSearch(cmd, commands, numCommands, sizeof(commands[0]), svcmdcmp); - if ( command ) { + if (command) { command->func(); return; } - CG_Printf( "Unknown client game command: %s\n", cmd ); + CG_Printf("Unknown client game command: %s\n", cmd); } - /* ==================== CG_ExecuteNewServerCommands @@ -258,9 +234,9 @@ Execute all of the server commands that were received along with this this snapshot. ==================== */ -void CG_ExecuteNewServerCommands( int latestSequence ) { - while ( cgs.serverCommandSequence < latestSequence ) { - if ( cgi_GetServerCommand( ++cgs.serverCommandSequence ) ) { +void CG_ExecuteNewServerCommands(int latestSequence) { + while (cgs.serverCommandSequence < latestSequence) { + if (cgi_GetServerCommand(++cgs.serverCommandSequence)) { CG_ServerCommand(); } } diff --git a/code/cgame/cg_snapshot.cpp b/code/cgame/cg_snapshot.cpp index 78f16f6908..fa9d0c9958 100644 --- a/code/cgame/cg_snapshot.cpp +++ b/code/cgame/cg_snapshot.cpp @@ -26,23 +26,22 @@ along with this program; if not, see . #include "cg_headers.h" - /* ================== CG_ResetEntity ================== */ -void CG_ResetEntity( centity_t *cent ) { +void CG_ResetEntity(centity_t *cent) { // if an event is set, assume it is new enough to use // if the event had timed out, it would have been cleared cent->previousEvent = 0; -// cent->trailTime = cg.snap->serverTime; + // cent->trailTime = cg.snap->serverTime; - VectorCopy (cent->currentState.origin, cent->lerpOrigin); - VectorCopy (cent->currentState.angles, cent->lerpAngles); - if ( cent->currentState.eType == ET_PLAYER ) { - CG_ResetPlayerEntity( cent ); + VectorCopy(cent->currentState.origin, cent->lerpOrigin); + VectorCopy(cent->currentState.angles, cent->lerpAngles); + if (cent->currentState.eType == ET_PLAYER) { + CG_ResetPlayerEntity(cent); } } @@ -53,28 +52,26 @@ CG_TransitionEntity cent->nextState is moved to cent->currentState and events are fired =============== */ -void CG_TransitionEntity( centity_t *cent ) { +void CG_TransitionEntity(centity_t *cent) { if (cent->nextState) { cent->currentState = *cent->nextState; } cent->currentValid = qtrue; // reset if the entity wasn't in the last frame or was teleported - if ( !cent->interpolate ) { - CG_ResetEntity( cent ); + if (!cent->interpolate) { + CG_ResetEntity(cent); } // clear the next state. if will be set by the next CG_SetNextSnap cent->interpolate = qfalse; - if ( cent->currentState.number != 0 ) - { + if (cent->currentState.number != 0) { // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } } - /* ================== CG_SetInitialSnapshot @@ -84,38 +81,37 @@ on tourney restarts. All other times will use CG_TransitionSnapshot instead. ================== */ -void CG_SetInitialSnapshot( snapshot_t *snap ) { - int i; - centity_t *cent; - entityState_t *state; +void CG_SetInitialSnapshot(snapshot_t *snap) { + int i; + centity_t *cent; + entityState_t *state; cg.snap = snap; // sort out solid entities - //CG_BuildSolidList(); + // CG_BuildSolidList(); - CG_ExecuteNewServerCommands( snap->serverCommandSequence ); + CG_ExecuteNewServerCommands(snap->serverCommandSequence); // set our local weapon selection pointer to // what the server has indicated the current weapon is CG_Respawn(); - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - state = &cg.snap->entities[ i ]; - cent = &cg_entities[ state->number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + state = &cg.snap->entities[i]; + cent = &cg_entities[state->number]; cent->currentState = *state; cent->interpolate = qfalse; cent->currentValid = qtrue; - CG_ResetEntity( cent ); + CG_ResetEntity(cent); // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } } - /* =================== CG_TransitionSnapshot @@ -123,24 +119,24 @@ CG_TransitionSnapshot The transition point from snap to nextSnap has passed =================== */ -void CG_TransitionSnapshot( void ) { - centity_t *cent; - snapshot_t *oldFrame; - int i; +void CG_TransitionSnapshot(void) { + centity_t *cent; + snapshot_t *oldFrame; + int i; - if ( !cg.snap ) { - CG_Error( "CG_TransitionSnapshot: NULL cg.snap" ); + if (!cg.snap) { + CG_Error("CG_TransitionSnapshot: NULL cg.snap"); } - if ( !cg.nextSnap ) { - CG_Error( "CG_TransitionSnapshot: NULL cg.nextSnap" ); + if (!cg.nextSnap) { + CG_Error("CG_TransitionSnapshot: NULL cg.nextSnap"); } // execute any server string commands before transitioning entities - CG_ExecuteNewServerCommands( cg.nextSnap->serverCommandSequence ); + CG_ExecuteNewServerCommands(cg.nextSnap->serverCommandSequence); // clear the currentValid flag for all entities in the existing snapshot - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; cent->currentValid = qfalse; } @@ -149,32 +145,28 @@ void CG_TransitionSnapshot( void ) { cg.snap = cg.nextSnap; // sort out solid entities - //CG_BuildSolidList(); + // CG_BuildSolidList(); - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) - { - if ( 1 ) //cg.snap->entities[ i ].number != 0 ) // I guess the player adds his/her events elsewhere, so doing this also gives us double events for the player! + for (i = 0; i < cg.snap->numEntities; i++) { + if (1) // cg.snap->entities[ i ].number != 0 ) // I guess the player adds his/her events elsewhere, so doing this also gives us double events for the + // player! { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; - CG_TransitionEntity( cent ); + cent = &cg_entities[cg.snap->entities[i].number]; + CG_TransitionEntity(cent); } } cg.nextSnap = NULL; // check for playerstate transition events - if ( oldFrame ) { + if (oldFrame) { // if we are not doing client side movement prediction for any // reason, then the client events and view changes will be issued now - //if ( cg_timescale.value >= 1.0f ) - { - CG_TransitionPlayerState( &cg.snap->ps, &oldFrame->ps ); - } + // if ( cg_timescale.value >= 1.0f ) + { CG_TransitionPlayerState(&cg.snap->ps, &oldFrame->ps); } } - } - /* =============== CG_SetEntityNextState @@ -183,25 +175,23 @@ Determine if the entity can be interpolated between the states present in cg.snap and cg,nextSnap =============== */ -void CG_SetEntityNextState( centity_t *cent, entityState_t *state ) { +void CG_SetEntityNextState(centity_t *cent, entityState_t *state) { cent->nextState = state; // since we can't interpolate ghoul2 stuff from one frame to another, I'm just going to copy the ghoul2 info directly into the current state now -// CGhoul2Info *currentModel = &state->ghoul2[1]; -// cent->gent->ghoul2 = state->ghoul2; -// CGhoul2Info *newModel = ¢->gent->ghoul2[1]; - + // CGhoul2Info *currentModel = &state->ghoul2[1]; + // cent->gent->ghoul2 = state->ghoul2; + // CGhoul2Info *newModel = ¢->gent->ghoul2[1]; // if this frame is a teleport, or the entity wasn't in the // previous frame, don't interpolate - if ( !cent->currentValid || ( ( cent->currentState.eFlags ^ state->eFlags ) & EF_TELEPORT_BIT ) ) { + if (!cent->currentValid || ((cent->currentState.eFlags ^ state->eFlags) & EF_TELEPORT_BIT)) { cent->interpolate = qfalse; } else { cent->interpolate = qtrue; } } - /* =================== CG_SetNextSnap @@ -209,29 +199,28 @@ CG_SetNextSnap A new snapshot has just been read in from the client system. =================== */ -void CG_SetNextSnap( snapshot_t *snap ) { - int num; - entityState_t *es; - centity_t *cent; +void CG_SetNextSnap(snapshot_t *snap) { + int num; + entityState_t *es; + centity_t *cent; cg.nextSnap = snap; // check for extrapolation errors - for ( num = 0 ; num < snap->numEntities ; num++ ) { + for (num = 0; num < snap->numEntities; num++) { es = &snap->entities[num]; - cent = &cg_entities[ es->number ]; - CG_SetEntityNextState( cent, es ); + cent = &cg_entities[es->number]; + CG_SetEntityNextState(cent, es); } // if the next frame is a teleport for the playerstate, - if ( cg.snap && ( ( snap->ps.eFlags ^ cg.snap->ps.eFlags ) & EF_TELEPORT_BIT ) ) { + if (cg.snap && ((snap->ps.eFlags ^ cg.snap->ps.eFlags) & EF_TELEPORT_BIT)) { cg.nextFrameTeleport = qtrue; } else { cg.nextFrameTeleport = qfalse; } } - /* ======================== CG_ReadNextSnapshot @@ -242,13 +231,13 @@ times if the client system fails to return a valid snapshot. ======================== */ -snapshot_t *CG_ReadNextSnapshot( void ) { - qboolean r; - snapshot_t *dest; +snapshot_t *CG_ReadNextSnapshot(void) { + qboolean r; + snapshot_t *dest; - while ( cg.processedSnapshotNum < cg.latestSnapshotNum ) { + while (cg.processedSnapshotNum < cg.latestSnapshotNum) { // decide which of the two slots to load it into - if ( cg.snap == &cg.activeSnapshots[0] ) { + if (cg.snap == &cg.activeSnapshots[0]) { dest = &cg.activeSnapshots[1]; } else { dest = &cg.activeSnapshots[0]; @@ -256,10 +245,10 @@ snapshot_t *CG_ReadNextSnapshot( void ) { // try to read the snapshot from the client system cg.processedSnapshotNum++; - r = cgi_GetSnapshot( cg.processedSnapshotNum, dest ); + r = cgi_GetSnapshot(cg.processedSnapshotNum, dest); // if it succeeded, return - if ( r ) { + if (r) { return dest; } @@ -269,7 +258,7 @@ snapshot_t *CG_ReadNextSnapshot( void ) { // buffer in the client system. // record as a dropped packet -// CG_AddLagometerSnapshotInfo( NULL ); + // CG_AddLagometerSnapshotInfo( NULL ); // If there are additional snapshots, continue trying to // read them. @@ -288,13 +277,13 @@ require a reload of all the media ================= */ extern void CG_LinkCentsToGents(void); -static void CG_RestartLevel( void ) { - int snapshotNum; - int r; +static void CG_RestartLevel(void) { + int snapshotNum; + int r; snapshotNum = cg.processedSnapshotNum; - memset( cg_entities, 0, sizeof( cg_entities ) ); + memset(cg_entities, 0, sizeof(cg_entities)); CG_Init_CG(); CG_LinkCentsToGents(); @@ -304,16 +293,15 @@ static void CG_RestartLevel( void ) { // regrab the first snapshot of the restart cg.processedSnapshotNum = snapshotNum; - r = cgi_GetSnapshot( cg.processedSnapshotNum, &cg.activeSnapshots[0] ); - if ( !r ) { - CG_Error( "cgi_GetSnapshot failed on restart" ); + r = cgi_GetSnapshot(cg.processedSnapshotNum, &cg.activeSnapshots[0]); + if (!r) { + CG_Error("cgi_GetSnapshot failed on restart"); } - CG_SetInitialSnapshot( &cg.activeSnapshots[0] ); + CG_SetInitialSnapshot(&cg.activeSnapshots[0]); cg.time = cg.snap->serverTime; } - /* ============ CG_ProcessSnapshots @@ -333,16 +321,16 @@ of an interpolating one) ============ */ -void CG_ProcessSnapshots( void ) { - snapshot_t *snap; - int n; +void CG_ProcessSnapshots(void) { + snapshot_t *snap; + int n; // see what the latest snapshot the client system has is - cgi_GetCurrentSnapshotNumber( &n, &cg.latestSnapshotTime ); - if ( n != cg.latestSnapshotNum ) { - if ( n < cg.latestSnapshotNum ) { + cgi_GetCurrentSnapshotNumber(&n, &cg.latestSnapshotTime); + if (n != cg.latestSnapshotNum) { + if (n < cg.latestSnapshotNum) { // this should never happen - CG_Error( "CG_ProcessSnapshots: n < cg.latestSnapshotNum" ); + CG_Error("CG_ProcessSnapshots: n < cg.latestSnapshotNum"); } cg.latestSnapshotNum = n; } @@ -350,16 +338,16 @@ void CG_ProcessSnapshots( void ) { // If we have yet to receive a snapshot, check for it. // Once we have gotten the first snapshot, cg.snap will // always have valid data for the rest of the game - if ( !cg.snap ) { + if (!cg.snap) { snap = CG_ReadNextSnapshot(); - if ( !snap ) { + if (!snap) { // we can't continue until we get a snapshot return; } // set our weapon selection to what // the playerstate is currently using - CG_SetInitialSnapshot( snap ); + CG_SetInitialSnapshot(snap); } // loop until we either have a valid nextSnap with a serverTime @@ -367,58 +355,54 @@ void CG_ProcessSnapshots( void ) { // out of available snapshots do { // if we don't have a nextframe, try to read a new one in - if ( !cg.nextSnap ) { + if (!cg.nextSnap) { snap = CG_ReadNextSnapshot(); // if we still don't have a nextframe, we will just have to // extrapolate - if ( !snap ) { + if (!snap) { break; } - CG_SetNextSnap( snap ); + CG_SetNextSnap(snap); // if time went backwards, we have a level restart - if ( cg.nextSnap->serverTime < cg.snap->serverTime ) { + if (cg.nextSnap->serverTime < cg.snap->serverTime) { // restart the level CG_RestartLevel(); - continue; // we might also get a nextsnap + continue; // we might also get a nextsnap } } // if our time is < nextFrame's, we have a nice interpolating state - if ( cg.time < cg.nextSnap->serverTime ) { + if (cg.time < cg.nextSnap->serverTime) { break; } // we have passed the transition from nextFrame to frame CG_TransitionSnapshot(); - } while ( 1 ); + } while (1); - if ( cg.snap->serverTime > cg.time ) - { - cg.time=cg.snap->serverTime; + if (cg.snap->serverTime > cg.time) { + cg.time = cg.snap->serverTime; #if _DEBUG Com_Printf("CG_ProcessSnapshots: cg.snap->serverTime > cg.time"); #endif - } - if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) - { - cg.time=cg.nextSnap->serverTime-1; + if (cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time) { + cg.time = cg.nextSnap->serverTime - 1; #if _DEBUG Com_Printf("CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time"); #endif } // assert our valid conditions upon exiting - if ( cg.snap == NULL ) { - CG_Error( "CG_ProcessSnapshots: cg.snap == NULL" ); + if (cg.snap == NULL) { + CG_Error("CG_ProcessSnapshots: cg.snap == NULL"); } - if ( cg.snap->serverTime > cg.time ) { - CG_Error( "CG_ProcessSnapshots: cg.snap->serverTime > cg.time" ); + if (cg.snap->serverTime > cg.time) { + CG_Error("CG_ProcessSnapshots: cg.snap->serverTime > cg.time"); } - if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) { - CG_Error( "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time" ); + if (cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time) { + CG_Error("CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time"); } } - diff --git a/code/cgame/cg_syscalls.cpp b/code/cgame/cg_syscalls.cpp index 7c20a9c2df..5c0cc2c300 100644 --- a/code/cgame/cg_syscalls.cpp +++ b/code/cgame/cg_syscalls.cpp @@ -25,569 +25,329 @@ along with this program; if not, see . // this file is only included when building a dll -//prototypes +// prototypes extern void CG_PreInit(); -static intptr_t (QDECL *Q_syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; +static intptr_t(QDECL *Q_syscall)(intptr_t arg, ...) = (intptr_t(QDECL *)(intptr_t, ...)) - 1; -extern "C" Q_EXPORT void QDECL dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg, ... ) ) { +extern "C" Q_EXPORT void QDECL dllEntry(intptr_t(QDECL *syscallptr)(intptr_t arg, ...)) { Q_syscall = syscallptr; CG_PreInit(); } - -inline int PASSFLOAT( float x ) { +inline int PASSFLOAT(float x) { byteAlias_t fi; fi.f = x; return fi.i; } -void cgi_Printf( const char *fmt ) { - Q_syscall( CG_PRINT, fmt ); -} +void cgi_Printf(const char *fmt) { Q_syscall(CG_PRINT, fmt); } -NORETURN void cgi_Error( const char *fmt ) { - Q_syscall( CG_ERROR, fmt ); +NORETURN void cgi_Error(const char *fmt) { + Q_syscall(CG_ERROR, fmt); // shut up GCC warning about returning functions, because we know better exit(1); } -int cgi_Milliseconds( void ) { - return Q_syscall( CG_MILLISECONDS ); -} +int cgi_Milliseconds(void) { return Q_syscall(CG_MILLISECONDS); } -void cgi_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) { - Q_syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags ); +void cgi_Cvar_Register(vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags) { + Q_syscall(CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags); } -void cgi_Cvar_Update( vmCvar_t *vmCvar ) { - Q_syscall( CG_CVAR_UPDATE, vmCvar ); -} +void cgi_Cvar_Update(vmCvar_t *vmCvar) { Q_syscall(CG_CVAR_UPDATE, vmCvar); } -void cgi_Cvar_Set( const char *var_name, const char *value ) { - Q_syscall( CG_CVAR_SET, var_name, value ); -} +void cgi_Cvar_Set(const char *var_name, const char *value) { Q_syscall(CG_CVAR_SET, var_name, value); } -int cgi_Argc( void ) { - return Q_syscall( CG_ARGC ); -} +int cgi_Argc(void) { return Q_syscall(CG_ARGC); } -void cgi_Argv( int n, char *buffer, int bufferLength ) { - Q_syscall( CG_ARGV, n, buffer, bufferLength ); -} +void cgi_Argv(int n, char *buffer, int bufferLength) { Q_syscall(CG_ARGV, n, buffer, bufferLength); } -void cgi_Args( char *buffer, int bufferLength ) { - Q_syscall( CG_ARGS, buffer, bufferLength ); -} +void cgi_Args(char *buffer, int bufferLength) { Q_syscall(CG_ARGS, buffer, bufferLength); } -int cgi_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - return Q_syscall( CG_FS_FOPENFILE, qpath, f, mode ); -} +int cgi_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode) { return Q_syscall(CG_FS_FOPENFILE, qpath, f, mode); } -int cgi_FS_Read( void *buffer, int len, fileHandle_t f ) { - return Q_syscall( CG_FS_READ, buffer, len, f ); -} +int cgi_FS_Read(void *buffer, int len, fileHandle_t f) { return Q_syscall(CG_FS_READ, buffer, len, f); } -int cgi_FS_Write( const void *buffer, int len, fileHandle_t f ) { - return Q_syscall( CG_FS_WRITE, buffer, len, f ); -} +int cgi_FS_Write(const void *buffer, int len, fileHandle_t f) { return Q_syscall(CG_FS_WRITE, buffer, len, f); } -void cgi_FS_FCloseFile( fileHandle_t f ) { - Q_syscall( CG_FS_FCLOSEFILE, f ); -} +void cgi_FS_FCloseFile(fileHandle_t f) { Q_syscall(CG_FS_FCLOSEFILE, f); } -void cgi_SendConsoleCommand( const char *text ) { - Q_syscall( CG_SENDCONSOLECOMMAND, text ); -} +void cgi_SendConsoleCommand(const char *text) { Q_syscall(CG_SENDCONSOLECOMMAND, text); } -void cgi_AddCommand( const char *cmdName ) { - Q_syscall( CG_ADDCOMMAND, cmdName ); -} +void cgi_AddCommand(const char *cmdName) { Q_syscall(CG_ADDCOMMAND, cmdName); } -void cgi_SendClientCommand( const char *s ) { - Q_syscall( CG_SENDCLIENTCOMMAND, s ); -} +void cgi_SendClientCommand(const char *s) { Q_syscall(CG_SENDCLIENTCOMMAND, s); } -void cgi_UpdateScreen( void ) { - Q_syscall( CG_UPDATESCREEN ); -} +void cgi_UpdateScreen(void) { Q_syscall(CG_UPDATESCREEN); } -//RMG BEGIN -void cgi_RMG_Init(int terrainID, const char *terrainInfo) -{ - Q_syscall( CG_RMG_INIT, terrainID, terrainInfo); -} +// RMG BEGIN +void cgi_RMG_Init(int terrainID, const char *terrainInfo) { Q_syscall(CG_RMG_INIT, terrainID, terrainInfo); } -int cgi_CM_RegisterTerrain(const char *terrainInfo) -{ - return Q_syscall( CG_CM_REGISTER_TERRAIN, terrainInfo); -} +int cgi_CM_RegisterTerrain(const char *terrainInfo) { return Q_syscall(CG_CM_REGISTER_TERRAIN, terrainInfo); } -void cgi_RE_InitRendererTerrain( const char *terrainInfo ) -{ - Q_syscall(CG_RE_INIT_RENDERER_TERRAIN, terrainInfo); -} -//RMG END +void cgi_RE_InitRendererTerrain(const char *terrainInfo) { Q_syscall(CG_RE_INIT_RENDERER_TERRAIN, terrainInfo); } +// RMG END -void cgi_CM_LoadMap( const char *mapname, qboolean subBSP ) { - Q_syscall( CG_CM_LOADMAP, mapname, subBSP ); -} +void cgi_CM_LoadMap(const char *mapname, qboolean subBSP) { Q_syscall(CG_CM_LOADMAP, mapname, subBSP); } -int cgi_CM_NumInlineModels( void ) { - return Q_syscall( CG_CM_NUMINLINEMODELS ); -} +int cgi_CM_NumInlineModels(void) { return Q_syscall(CG_CM_NUMINLINEMODELS); } -clipHandle_t cgi_CM_InlineModel( int index ) { - return Q_syscall( CG_CM_INLINEMODEL, index ); -} +clipHandle_t cgi_CM_InlineModel(int index) { return Q_syscall(CG_CM_INLINEMODEL, index); } -clipHandle_t cgi_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) {//, const int contents ) { - return Q_syscall( CG_CM_TEMPBOXMODEL, mins, maxs );//, contents ); +clipHandle_t cgi_CM_TempBoxModel(const vec3_t mins, const vec3_t maxs) { //, const int contents ) { + return Q_syscall(CG_CM_TEMPBOXMODEL, mins, maxs); //, contents ); } -int cgi_CM_PointContents( const vec3_t p, clipHandle_t model ) { - return Q_syscall( CG_CM_POINTCONTENTS, p, model ); -} +int cgi_CM_PointContents(const vec3_t p, clipHandle_t model) { return Q_syscall(CG_CM_POINTCONTENTS, p, model); } -int cgi_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) { - return Q_syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles ); +int cgi_CM_TransformedPointContents(const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { + return Q_syscall(CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles); } -void cgi_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask ) { - Q_syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask ); +void cgi_CM_BoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask) { + Q_syscall(CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask); } -void cgi_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask, - const vec3_t origin, const vec3_t angles ) { - Q_syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles ); +void cgi_CM_TransformedBoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, + const vec3_t origin, const vec3_t angles) { + Q_syscall(CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles); } -int cgi_CM_MarkFragments( int numPoints, const vec3_t *points, - const vec3_t projection, - int maxPoints, vec3_t pointBuffer, - int maxFragments, markFragment_t *fragmentBuffer ) { - return Q_syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer ); +int cgi_CM_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + return Q_syscall(CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer); } -void cgi_CM_SnapPVS(vec3_t origin,byte *buffer) -{ - Q_syscall(CG_CM_SNAPPVS,origin,buffer); -} +void cgi_CM_SnapPVS(vec3_t origin, byte *buffer) { Q_syscall(CG_CM_SNAPPVS, origin, buffer); } -void cgi_S_StopSounds( void ) -{ - Q_syscall( CG_S_STOPSOUNDS); -} +void cgi_S_StopSounds(void) { Q_syscall(CG_S_STOPSOUNDS); } -void cgi_S_StartSound( const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) { - Q_syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx ); -} +void cgi_S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx) { Q_syscall(CG_S_STARTSOUND, origin, entityNum, entchannel, sfx); } -void cgi_AS_ParseSets( void ) { - Q_syscall( CG_AS_PARSESETS ); -} +void cgi_AS_ParseSets(void) { Q_syscall(CG_AS_PARSESETS); } -void cgi_AS_AddPrecacheEntry( const char *name ) { - Q_syscall( CG_AS_ADDENTRY, name ); -} +void cgi_AS_AddPrecacheEntry(const char *name) { Q_syscall(CG_AS_ADDENTRY, name); } -void cgi_S_UpdateAmbientSet( const char *name, vec3_t origin ) { - Q_syscall( CG_S_UPDATEAMBIENTSET, name, origin ); -} +void cgi_S_UpdateAmbientSet(const char *name, vec3_t origin) { Q_syscall(CG_S_UPDATEAMBIENTSET, name, origin); } -int cgi_S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ) { - return Q_syscall( CG_S_ADDLOCALSET, name, listener_origin, origin, entID, time ); +int cgi_S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time) { + return Q_syscall(CG_S_ADDLOCALSET, name, listener_origin, origin, entID, time); } -sfxHandle_t cgi_AS_GetBModelSound( const char *name, int stage ) { - return Q_syscall( CG_AS_GETBMODELSOUND, name, stage ); -} +sfxHandle_t cgi_AS_GetBModelSound(const char *name, int stage) { return Q_syscall(CG_AS_GETBMODELSOUND, name, stage); } -void cgi_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) { - Q_syscall( CG_S_STARTLOCALSOUND, sfx, channelNum ); -} +void cgi_S_StartLocalSound(sfxHandle_t sfx, int channelNum) { Q_syscall(CG_S_STARTLOCALSOUND, sfx, channelNum); } -void cgi_S_ClearLoopingSounds( void ) { - Q_syscall( CG_S_CLEARLOOPINGSOUNDS ); -} +void cgi_S_ClearLoopingSounds(void) { Q_syscall(CG_S_CLEARLOOPINGSOUNDS); } -void cgi_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx, soundChannel_t chan ) { - Q_syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx, chan ); +void cgi_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx, soundChannel_t chan) { + Q_syscall(CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx, chan); } -void cgi_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) { - Q_syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin ); -} +void cgi_S_UpdateEntityPosition(int entityNum, const vec3_t origin) { Q_syscall(CG_S_UPDATEENTITYPOSITION, entityNum, origin); } -void cgi_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], qboolean inwater ) { - Q_syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater ); +void cgi_S_Respatialize(int entityNum, const vec3_t origin, vec3_t axis[3], qboolean inwater) { + Q_syscall(CG_S_RESPATIALIZE, entityNum, origin, axis, inwater); } -sfxHandle_t cgi_S_RegisterSound( const char *sample ) { - return Q_syscall( CG_S_REGISTERSOUND, sample ); -} +sfxHandle_t cgi_S_RegisterSound(const char *sample) { return Q_syscall(CG_S_REGISTERSOUND, sample); } -void cgi_S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bForceStart ) { - Q_syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop, bForceStart ); -} +void cgi_S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bForceStart) { Q_syscall(CG_S_STARTBACKGROUNDTRACK, intro, loop, bForceStart); } -float cgi_S_GetSampleLength( sfxHandle_t sfx ) { - return Q_syscall( CG_S_GETSAMPLELENGTH, sfx); -} +float cgi_S_GetSampleLength(sfxHandle_t sfx) { return Q_syscall(CG_S_GETSAMPLELENGTH, sfx); } -void cgi_R_LoadWorldMap( const char *mapname ) { - Q_syscall( CG_R_LOADWORLDMAP, mapname ); -} +void cgi_R_LoadWorldMap(const char *mapname) { Q_syscall(CG_R_LOADWORLDMAP, mapname); } -qhandle_t cgi_R_RegisterModel( const char *name ) { - return Q_syscall( CG_R_REGISTERMODEL, name ); -} +qhandle_t cgi_R_RegisterModel(const char *name) { return Q_syscall(CG_R_REGISTERMODEL, name); } -qhandle_t cgi_R_RegisterSkin( const char *name ) { - return Q_syscall( CG_R_REGISTERSKIN, name ); -} +qhandle_t cgi_R_RegisterSkin(const char *name) { return Q_syscall(CG_R_REGISTERSKIN, name); } -qhandle_t cgi_R_RegisterShader( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADER, name ); -} +qhandle_t cgi_R_RegisterShader(const char *name) { return Q_syscall(CG_R_REGISTERSHADER, name); } -qhandle_t cgi_R_RegisterShaderNoMip( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADERNOMIP, name ); -} +qhandle_t cgi_R_RegisterShaderNoMip(const char *name) { return Q_syscall(CG_R_REGISTERSHADERNOMIP, name); } -qhandle_t cgi_R_RegisterFont( const char *name ) { - return Q_syscall( CG_R_REGISTERFONT, name ); -} +qhandle_t cgi_R_RegisterFont(const char *name) { return Q_syscall(CG_R_REGISTERFONT, name); } int cgi_R_Font_StrLenPixels(const char *text, const int iFontIndex, const float scale /*= 1.0f*/) { - return Q_syscall( CG_R_FONTSTRLENPIXELS, text, iFontIndex, PASSFLOAT(scale) ) ; + return Q_syscall(CG_R_FONTSTRLENPIXELS, text, iFontIndex, PASSFLOAT(scale)); } -int cgi_R_Font_StrLenChars(const char *text) { - return Q_syscall( CG_R_FONTSTRLENCHARS, text ) ; -} +int cgi_R_Font_StrLenChars(const char *text) { return Q_syscall(CG_R_FONTSTRLENCHARS, text); } -int cgi_R_Font_HeightPixels(const int iFontIndex, const float scale /*= 1.0f*/) { - return Q_syscall( CG_R_FONTHEIGHTPIXELS, iFontIndex, PASSFLOAT(scale) ); -} +int cgi_R_Font_HeightPixels(const int iFontIndex, const float scale /*= 1.0f*/) { return Q_syscall(CG_R_FONTHEIGHTPIXELS, iFontIndex, PASSFLOAT(scale)); } -qboolean cgi_Language_IsAsian( void ) -{ - return (qboolean)(Q_syscall( CG_LANGUAGE_ISASIAN ) != 0); -} +qboolean cgi_Language_IsAsian(void) { return (qboolean)(Q_syscall(CG_LANGUAGE_ISASIAN) != 0); } -qboolean cgi_Language_UsesSpaces(void) -{ - return (qboolean)(Q_syscall( CG_LANGUAGE_USESSPACES ) != 0); -} +qboolean cgi_Language_UsesSpaces(void) { return (qboolean)(Q_syscall(CG_LANGUAGE_USESSPACES) != 0); } -unsigned int cgi_AnyLanguage_ReadCharFromString( const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */ ) -{ - return Q_syscall( CG_ANYLANGUAGE_READFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation ); +unsigned int cgi_AnyLanguage_ReadCharFromString(const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */) { + return Q_syscall(CG_ANYLANGUAGE_READFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation); } void cgi_R_Font_DrawString(int ox, int oy, const char *text, const float *rgba, const int setIndex, int iMaxPixelWidth, const float scale /*= 1.0f*/) { - Q_syscall (CG_R_FONTDRAWSTRING, ox, oy, text, rgba, setIndex, iMaxPixelWidth, PASSFLOAT(scale) ); + Q_syscall(CG_R_FONTDRAWSTRING, ox, oy, text, rgba, setIndex, iMaxPixelWidth, PASSFLOAT(scale)); } -//set some properties for the draw layer for my refractive effect (here primarily for mod authors) -rww -void cgi_R_SetRefractProp(float alpha, float stretch, qboolean prepost, qboolean negate) -{ +// set some properties for the draw layer for my refractive effect (here primarily for mod authors) -rww +void cgi_R_SetRefractProp(float alpha, float stretch, qboolean prepost, qboolean negate) { Q_syscall(CG_R_SETREFRACTIONPROP, PASSFLOAT(alpha), PASSFLOAT(stretch), prepost, negate); } -void cgi_R_ClearScene( void ) { - Q_syscall( CG_R_CLEARSCENE ); -} +void cgi_R_ClearScene(void) { Q_syscall(CG_R_CLEARSCENE); } -void cgi_R_AddRefEntityToScene( const refEntity_t *re ) { - Q_syscall( CG_R_ADDREFENTITYTOSCENE, re ); -} +void cgi_R_AddRefEntityToScene(const refEntity_t *re) { Q_syscall(CG_R_ADDREFENTITYTOSCENE, re); } -qboolean cgi_R_inPVS( vec3_t p1, vec3_t p2 ) -{ - return (qboolean)(Q_syscall( CG_R_INPVS, p1, p2 ) != 0); -} +qboolean cgi_R_inPVS(vec3_t p1, vec3_t p2) { return (qboolean)(Q_syscall(CG_R_INPVS, p1, p2) != 0); } - -void cgi_R_GetLighting( const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t ligthDir ) { - Q_syscall( CG_R_GETLIGHTING, origin, ambientLight, directedLight, ligthDir ); +void cgi_R_GetLighting(const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t ligthDir) { + Q_syscall(CG_R_GETLIGHTING, origin, ambientLight, directedLight, ligthDir); } -void cgi_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) { - Q_syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts ); -} +void cgi_R_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts) { Q_syscall(CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts); } -void cgi_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - Q_syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) ); +void cgi_R_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + Q_syscall(CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b)); } -void cgi_R_RenderScene( const refdef_t *fd ) { - Q_syscall( CG_R_RENDERSCENE, fd ); -} +void cgi_R_RenderScene(const refdef_t *fd) { Q_syscall(CG_R_RENDERSCENE, fd); } -void cgi_R_SetColor( const float *rgba ) { - Q_syscall( CG_R_SETCOLOR, rgba ); -} +void cgi_R_SetColor(const float *rgba) { Q_syscall(CG_R_SETCOLOR, rgba); } -void cgi_R_DrawStretchPic( float x, float y, float w, float h, - float s1, float t1, float s2, float t2, qhandle_t hShader ) { - Q_syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader ); +void cgi_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + Q_syscall(CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader); } -void cgi_R_ModelBounds( qhandle_t model, vec3_t mins, vec3_t maxs ) { - Q_syscall( CG_R_MODELBOUNDS, model, mins, maxs ); -} +void cgi_R_ModelBounds(qhandle_t model, vec3_t mins, vec3_t maxs) { Q_syscall(CG_R_MODELBOUNDS, model, mins, maxs); } -void cgi_R_LerpTag( orientation_t *tag, qhandle_t mod, int startFrame, int endFrame, - float frac, const char *tagName ) { - Q_syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName ); +void cgi_R_LerpTag(orientation_t *tag, qhandle_t mod, int startFrame, int endFrame, float frac, const char *tagName) { + Q_syscall(CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName); } -void cgi_R_DrawRotatePic( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) -{ - Q_syscall( CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); +void cgi_R_DrawRotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } -void cgi_R_DrawRotatePic2( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) -{ - Q_syscall( CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); +void cgi_R_DrawRotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } -//linear fogging, with settable range -rww -void cgi_R_SetRangeFog(float range) -{ - Q_syscall(CG_R_SETRANGEFOG, PASSFLOAT(range)); -} +// linear fogging, with settable range -rww +void cgi_R_SetRangeFog(float range) { Q_syscall(CG_R_SETRANGEFOG, PASSFLOAT(range)); } -void cgi_R_LAGoggles( void ) -{ - Q_syscall( CG_R_LA_GOGGLES ); -} +void cgi_R_LAGoggles(void) { Q_syscall(CG_R_LA_GOGGLES); } -void cgi_R_Scissor( float x, float y, float w, float h) -{ - Q_syscall( CG_R_SCISSOR, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h)); -} +void cgi_R_Scissor(float x, float y, float w, float h) { Q_syscall(CG_R_SCISSOR, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h)); } -void cgi_GetGlconfig( glconfig_t *glconfig ) { - Q_syscall( CG_GETGLCONFIG, glconfig ); -} +void cgi_GetGlconfig(glconfig_t *glconfig) { Q_syscall(CG_GETGLCONFIG, glconfig); } -void cgi_GetGameState( gameState_t *gamestate ) { - Q_syscall( CG_GETGAMESTATE, gamestate ); -} +void cgi_GetGameState(gameState_t *gamestate) { Q_syscall(CG_GETGAMESTATE, gamestate); } -void cgi_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { - Q_syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime ); -} +void cgi_GetCurrentSnapshotNumber(int *snapshotNumber, int *serverTime) { Q_syscall(CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime); } -qboolean cgi_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { - return (qboolean)(Q_syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot ) != 0); -} +qboolean cgi_GetSnapshot(int snapshotNumber, snapshot_t *snapshot) { return (qboolean)(Q_syscall(CG_GETSNAPSHOT, snapshotNumber, snapshot) != 0); } -qboolean cgi_GetDefaultState(int entityIndex, entityState_t *state ) -{ - return (qboolean)(Q_syscall( CG_GETDEFAULTSTATE, entityIndex, state ) != 0); -} +qboolean cgi_GetDefaultState(int entityIndex, entityState_t *state) { return (qboolean)(Q_syscall(CG_GETDEFAULTSTATE, entityIndex, state) != 0); } -qboolean cgi_GetServerCommand( int serverCommandNumber ) { - return (qboolean)(Q_syscall( CG_GETSERVERCOMMAND, serverCommandNumber ) != 0); -} +qboolean cgi_GetServerCommand(int serverCommandNumber) { return (qboolean)(Q_syscall(CG_GETSERVERCOMMAND, serverCommandNumber) != 0); } -int cgi_GetCurrentCmdNumber( void ) { - return Q_syscall( CG_GETCURRENTCMDNUMBER ); -} +int cgi_GetCurrentCmdNumber(void) { return Q_syscall(CG_GETCURRENTCMDNUMBER); } -qboolean cgi_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { - return (qboolean)(Q_syscall( CG_GETUSERCMD, cmdNumber, ucmd ) != 0); -} +qboolean cgi_GetUserCmd(int cmdNumber, usercmd_t *ucmd) { return (qboolean)(Q_syscall(CG_GETUSERCMD, cmdNumber, ucmd) != 0); } -void cgi_SetUserCmdValue( int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride ) { - Q_syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride) ); +void cgi_SetUserCmdValue(int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride) { + Q_syscall(CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride)); } -void cgi_SetUserCmdAngles( float pitchOverride, float yawOverride, float rollOverride ) { - Q_syscall( CG_SETUSERCMDANGLES, PASSFLOAT(pitchOverride), PASSFLOAT(yawOverride), PASSFLOAT(rollOverride) ); +void cgi_SetUserCmdAngles(float pitchOverride, float yawOverride, float rollOverride) { + Q_syscall(CG_SETUSERCMDANGLES, PASSFLOAT(pitchOverride), PASSFLOAT(yawOverride), PASSFLOAT(rollOverride)); } /* Ghoul2 Insert Start */ // CG Specific API calls -void trap_G2_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) -{ - Q_syscall( CG_G2_SETMODELS, &ghoul2, modelList, skinList); +void trap_G2_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + Q_syscall(CG_G2_SETMODELS, &ghoul2, modelList, skinList); } /* Ghoul2 Insert End */ -void trap_Com_SetOrgAngles(vec3_t org,vec3_t angles) -{ - Q_syscall(COM_SETORGANGLES,org,angles); -} +void trap_Com_SetOrgAngles(vec3_t org, vec3_t angles) { Q_syscall(COM_SETORGANGLES, org, angles); } -void trap_R_GetLightStyle(int style, color4ub_t color) -{ - Q_syscall(CG_R_GET_LIGHT_STYLE, style, color); -} +void trap_R_GetLightStyle(int style, color4ub_t color) { Q_syscall(CG_R_GET_LIGHT_STYLE, style, color); } -void trap_R_SetLightStyle(int style, int color) -{ - Q_syscall(CG_R_SET_LIGHT_STYLE, style, color); -} +void trap_R_SetLightStyle(int style, int color) { Q_syscall(CG_R_SET_LIGHT_STYLE, style, color); } -void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal ) -{ - Q_syscall( CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal ); -} +void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { Q_syscall(CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal); } -void cgi_R_WorldEffectCommand( const char *command ) -{ - Q_syscall( CG_R_WORLD_EFFECT_COMMAND, command ); -} +void cgi_R_WorldEffectCommand(const char *command) { Q_syscall(CG_R_WORLD_EFFECT_COMMAND, command); } // this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate) -int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile /* = NULL */) { - return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); +int trap_CIN_PlayCinematic(const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile /* = NULL */) { + return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); } // stops playing the cinematic and ends it. should always return FMV_EOF // cinematics must be stopped in reverse order of when they are started -e_status trap_CIN_StopCinematic(int handle) { - return (e_status) Q_syscall(CG_CIN_STOPCINEMATIC, handle); -} - +e_status trap_CIN_StopCinematic(int handle) { return (e_status)Q_syscall(CG_CIN_STOPCINEMATIC, handle); } // will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached. -e_status trap_CIN_RunCinematic (int handle) { - return (e_status) Q_syscall(CG_CIN_RUNCINEMATIC, handle); -} - +e_status trap_CIN_RunCinematic(int handle) { return (e_status)Q_syscall(CG_CIN_RUNCINEMATIC, handle); } // draws the current frame -void trap_CIN_DrawCinematic (int handle) { - Q_syscall(CG_CIN_DRAWCINEMATIC, handle); -} - +void trap_CIN_DrawCinematic(int handle) { Q_syscall(CG_CIN_DRAWCINEMATIC, handle); } // allows you to resize the animation dynamically -void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) { - Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); -} +void trap_CIN_SetExtents(int handle, int x, int y, int w, int h) { Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); } -void *cgi_Z_Malloc( int size, int tag ) -{ - return (void *)Q_syscall(CG_Z_MALLOC,size,tag); -} +void *cgi_Z_Malloc(int size, int tag) { return (void *)Q_syscall(CG_Z_MALLOC, size, tag); } -void cgi_Z_Free( void *ptr ) -{ - Q_syscall(CG_Z_FREE,ptr); -} +void cgi_Z_Free(void *ptr) { Q_syscall(CG_Z_FREE, ptr); } -void cgi_UI_SetActive_Menu(char *name) -{ - Q_syscall(CG_UI_SETACTIVE_MENU,name); -} +void cgi_UI_SetActive_Menu(char *name) { Q_syscall(CG_UI_SETACTIVE_MENU, name); } -void cgi_UI_Menu_OpenByName(char *buf) -{ - Q_syscall(CG_UI_MENU_OPENBYNAME,buf); -} +void cgi_UI_Menu_OpenByName(char *buf) { Q_syscall(CG_UI_MENU_OPENBYNAME, buf); } -void cgi_UI_Menu_Reset(void) -{ - Q_syscall(CG_UI_MENU_RESET); -} +void cgi_UI_Menu_Reset(void) { Q_syscall(CG_UI_MENU_RESET); } -void cgi_UI_Menu_New(char *buf) -{ - Q_syscall(CG_UI_MENU_NEW,buf); -} +void cgi_UI_Menu_New(char *buf) { Q_syscall(CG_UI_MENU_NEW, buf); } -void cgi_UI_Parse_Int(int *value) -{ - Q_syscall(CG_UI_PARSE_INT,value); -} +void cgi_UI_Parse_Int(int *value) { Q_syscall(CG_UI_PARSE_INT, value); } -void cgi_UI_Parse_String(char *buf) -{ - Q_syscall(CG_UI_PARSE_STRING,buf); -} +void cgi_UI_Parse_String(char *buf) { Q_syscall(CG_UI_PARSE_STRING, buf); } -void cgi_UI_Parse_Float(float *value) -{ - Q_syscall(CG_UI_PARSE_FLOAT,value); -} +void cgi_UI_Parse_Float(float *value) { Q_syscall(CG_UI_PARSE_FLOAT, value); } -int cgi_UI_StartParseSession(char *menuFile,char **buf) -{ - return(int) Q_syscall(CG_UI_STARTPARSESESSION,menuFile,buf); -} +int cgi_UI_StartParseSession(char *menuFile, char **buf) { return (int)Q_syscall(CG_UI_STARTPARSESESSION, menuFile, buf); } -void cgi_UI_EndParseSession(char *buf) -{ - Q_syscall(CG_UI_ENDPARSESESSION,buf); -} +void cgi_UI_EndParseSession(char *buf) { Q_syscall(CG_UI_ENDPARSESESSION, buf); } -void cgi_UI_ParseExt(char **token) -{ - Q_syscall(CG_UI_PARSEEXT,token); -} +void cgi_UI_ParseExt(char **token) { Q_syscall(CG_UI_PARSEEXT, token); } -void cgi_UI_MenuCloseAll(void) -{ - Q_syscall(CG_UI_MENUCLOSE_ALL); -} +void cgi_UI_MenuCloseAll(void) { Q_syscall(CG_UI_MENUCLOSE_ALL); } -void cgi_UI_MenuPaintAll(void) -{ - Q_syscall(CG_UI_MENUPAINT_ALL); -} +void cgi_UI_MenuPaintAll(void) { Q_syscall(CG_UI_MENUPAINT_ALL); } -void cgi_UI_String_Init(void) -{ - Q_syscall(CG_UI_STRING_INIT); -} +void cgi_UI_String_Init(void) { Q_syscall(CG_UI_STRING_INIT); } -int cgi_UI_GetMenuInfo(char *menuFile,int *x,int *y,int *w,int *h) -{ - return(int) Q_syscall(CG_UI_GETMENUINFO,menuFile,x,y,w,h); -} +int cgi_UI_GetMenuInfo(char *menuFile, int *x, int *y, int *w, int *h) { return (int)Q_syscall(CG_UI_GETMENUINFO, menuFile, x, y, w, h); } -int cgi_UI_GetMenuItemInfo(const char *menuFile,const char *itemName, int *x,int *y,int *w,int *h,vec4_t color,qhandle_t *background) -{ - return(int) Q_syscall(CG_UI_GETITEMINFO,menuFile,itemName,x,y,w,h,color,background); +int cgi_UI_GetMenuItemInfo(const char *menuFile, const char *itemName, int *x, int *y, int *w, int *h, vec4_t color, qhandle_t *background) { + return (int)Q_syscall(CG_UI_GETITEMINFO, menuFile, itemName, x, y, w, h, color, background); } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char* text) -{ - return(int) Q_syscall(CG_UI_GETITEMTEXT,menuFile,itemName,text); -} +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text) { return (int)Q_syscall(CG_UI_GETITEMTEXT, menuFile, itemName, text); } -int cgi_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) -{ - return Q_syscall( CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength ); -} +int cgi_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) { return Q_syscall(CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength); } /* OpenJK Add Since the modules are incompatible, might as well break base compat even further amirite? */ -void *cgi_UI_GetMenuByName( const char *menu ) -{ - return (void *)Q_syscall( CG_OPENJK_GETMENU_BYNAME, menu ); -} +void *cgi_UI_GetMenuByName(const char *menu) { return (void *)Q_syscall(CG_OPENJK_GETMENU_BYNAME, menu); } -void cgi_UI_Menu_Paint( void *menu, qboolean force ) -{ - Q_syscall( CG_OPENJK_MENU_PAINT, menu, force ); -} +void cgi_UI_Menu_Paint(void *menu, qboolean force) { Q_syscall(CG_OPENJK_MENU_PAINT, menu, force); } diff --git a/code/cgame/cg_text.cpp b/code/cgame/cg_text.cpp index d535bcec2c..b2f3d85ce5 100644 --- a/code/cgame/cg_text.cpp +++ b/code/cgame/cg_text.cpp @@ -27,20 +27,16 @@ along with this program; if not, see . #include "cg_media.h" +// int precacheWav_i; // Current high index of precacheWav array +// precacheWav_t precacheWav[MAX_PRECACHEWAV]; -//int precacheWav_i; // Current high index of precacheWav array -//precacheWav_t precacheWav[MAX_PRECACHEWAV]; - - -//int precacheText_i; // Current high index of precacheText array -//precacheText_t precacheText[MAX_PRECACHETEXT]; - +// int precacheText_i; // Current high index of precacheText array +// precacheText_t precacheText[MAX_PRECACHETEXT]; extern vec4_t textcolor_caption; extern vec4_t textcolor_center; extern vec4_t textcolor_scroll; - // display text in a supplied box, start at top left and going down by however many pixels I feel like internally, // return value is NULL if all fitted, else char * of next char to continue from that didn't fit. // @@ -48,23 +44,20 @@ extern vec4_t textcolor_scroll; // // ( if you get the same char * returned as what you passed in, then none of it fitted at all (box too small) ) // - // this is execrable, and should NOT have had to've been done now, but... - // - float gfAdvanceHack = 0.0f; // MUST default to this - int giLinesOutput; // hack-city after release, only used by one function +// this is execrable, and should NOT have had to've been done now, but... +// +float gfAdvanceHack = 0.0f; // MUST default to this +int giLinesOutput; // hack-city after release, only used by one function // -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color) -{ +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color) { giLinesOutput = 0; - cgi_R_SetColor( v4Color ); + cgi_R_SetColor(v4Color); // Setup a reasonable vertical spacing (taiwanese & japanese need 1.5 fontheight, so use that for all)... // - const int iFontHeight = cgi_R_Font_HeightPixels(iFontHandle, fScale); - const int iFontHeightAdvance = (int) ( ((gfAdvanceHack == 0.0f) ? 1.5f : gfAdvanceHack) * (float) iFontHeight); - int iYpos = iBoxY; // start print pos + const int iFontHeight = cgi_R_Font_HeightPixels(iFontHandle, fScale); + const int iFontHeightAdvance = (int)(((gfAdvanceHack == 0.0f) ? 1.5f : gfAdvanceHack) * (float)iFontHeight); + int iYpos = iBoxY; // start print pos // this could probably be simplified now, but it was converted from something else I didn't originally write, // and it works anyway so wtf... @@ -72,17 +65,15 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei const char *psCurrentTextReadPos = psText; const char *psReadPosAtLineStart = psCurrentTextReadPos; const char *psBestLineBreakSrcPos = psCurrentTextReadPos; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) - while( *psCurrentTextReadPos && (iYpos + iFontHeight < (iBoxY + iBoxHeight)) ) - { - char sLineForDisplay[2048]; // ott + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + while (*psCurrentTextReadPos && (iYpos + iFontHeight < (iBoxY + iBoxHeight))) { + char sLineForDisplay[2048]; // ott // construct a line... // psCurrentTextReadPos = psReadPosAtLineStart; sLineForDisplay[0] = '\0'; - while ( *psCurrentTextReadPos ) - { + while (*psCurrentTextReadPos) { psLastGood_s = psCurrentTextReadPos; // read letter... @@ -94,45 +85,33 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // concat onto string so far... // - if (uiLetter == 32 && sLineForDisplay[0] == '\0') - { + if (uiLetter == 32 && sLineForDisplay[0] == '\0') { psReadPosAtLineStart++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - sLineForDisplay[ strlen(sLineForDisplay)-1 ] = '\0'; // kill the CR + sLineForDisplay[strlen(sLineForDisplay) - 1] = '\0'; // kill the CR psReadPosAtLineStart = psCurrentTextReadPos; psBestLineBreakSrcPos = psCurrentTextReadPos; - break; // print this line - } - else - if ( cgi_R_Font_StrLenPixels(sLineForDisplay, iFontHandle, fScale) >= iBoxWidth ) - { + break; // print this line + } else if (cgi_R_Font_StrLenPixels(sLineForDisplay, iFontHandle, fScale) >= iBoxWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == psReadPosAtLineStart) - { + } else { + if (psBestLineBreakSrcPos == psReadPosAtLineStart) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -140,19 +119,18 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // normally). On the other hand I suppose it'psCurrentTextReadPos entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - sLineForDisplay[ psBestLineBreakSrcPos - psReadPosAtLineStart ] = '\0'; + sLineForDisplay[psBestLineBreakSrcPos - psReadPosAtLineStart] = '\0'; psReadPosAtLineStart = psCurrentTextReadPos = psBestLineBreakSrcPos; - break; // print this line + break; // print this line } } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) { psBestLineBreakSrcPos = psCurrentTextReadPos; } } @@ -165,16 +143,13 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // and echo to console in dev mode... // - if ( cg_developer.integer ) - { -// Com_Printf( "%psCurrentTextReadPos\n", sLineForDisplay ); + if (cg_developer.integer) { + // Com_Printf( "%psCurrentTextReadPos\n", sLineForDisplay ); } } return psReadPosAtLineStart; } - - /* =============================================================================== @@ -182,33 +157,26 @@ CAPTION TEXT =============================================================================== */ -void CG_CaptionTextStop(void) -{ - cg.captionTextTime = 0; -} +void CG_CaptionTextStop(void) { cg.captionTextTime = 0; } // try and get the correct StripEd text (with retry) for a given reference... // // returns 0 if failed, else strlen... // -static int cg_SP_GetStringTextStringWithRetry( const char *psReference, char *psDest, int iSizeofDest) -{ +static int cg_SP_GetStringTextStringWithRetry(const char *psReference, char *psDest, int iSizeofDest) { int iReturn; - if (psReference[0] == '#') - { + if (psReference[0] == '#') { // then we know the striped package name is already built in, so do NOT try prepending anything else... // - return cgi_SP_GetStringTextString( va("%s",psReference+1), psDest, iSizeofDest ); + return cgi_SP_GetStringTextString(va("%s", psReference + 1), psDest, iSizeofDest); } - for (int i=0; i 255) - { - Q_strcat(cg.captionText[i],sizeof(cg.captionText[i]),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(cg.captionText[i],sizeof(cg.captionText[i]),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(cg.captionText[i], sizeof(cg.captionText[i]), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(cg.captionText[i], sizeof(cg.captionText[i]), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - cg.captionText[i][ strlen(cg.captionText[i])-1 ] = '\0'; // kill the CR + cg.captionText[i][strlen(cg.captionText[i]) - 1] = '\0'; // kill the CR i++; holds = s; psBestLineBreakSrcPos = s; cg.scrollTextLines++; - } - else - if ( cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale) >= SCREEN_WIDTH) - { + } else if (cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale) >= SCREEN_WIDTH) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == holds) - { + } else { + if (psBestLineBreakSrcPos == holds) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -351,10 +302,10 @@ void CG_CaptionText( const char *str, int sound) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - cg.captionText[i][ psBestLineBreakSrcPos - holds ] = '\0'; + cg.captionText[i][psBestLineBreakSrcPos - holds] = '\0'; holds = s = psBestLineBreakSrcPos; i++; cg.scrollTextLines++; @@ -363,102 +314,85 @@ void CG_CaptionText( const char *str, int sound) // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) { psBestLineBreakSrcPos = s; } } - // calc the length of time to hold each 2 lines of text on the screen.... presumably this works? // holdTime = strlen(cg.captionText[0]); - if (cg.scrollTextLines > 1) - { - holdTime += strlen(cg.captionText[1]); // strlen is also good for MBCS in this instance, since it's for timing + if (cg.scrollTextLines > 1) { + holdTime += strlen(cg.captionText[1]); // strlen is also good for MBCS in this instance, since it's for timing } cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime); - cg.scrollTextTime = 0; // No scrolling during captions + cg.scrollTextTime = 0; // No scrolling during captions - //Echo to console in dev mode - if ( cg_developer.integer ) - { - Com_Printf( "%s\n", cg.captionText[0] ); // ste: was [i], but surely sentence 0 is more useful than last? + // Echo to console in dev mode + if (cg_developer.integer) { + Com_Printf("%s\n", cg.captionText[0]); // ste: was [i], but surely sentence 0 is more useful than last? } } +void CG_DrawCaptionText(void) { + int i; + int x, y, w; + int holdTime; -void CG_DrawCaptionText(void) -{ - int i; - int x, y, w; - int holdTime; - - if ( !cg.captionTextTime ) - { + if (!cg.captionTextTime) { return; } const float fFontScale = cgi_Language_IsAsian() ? 0.8f : 1.0f; - if (cg_skippingcin.integer != 0) - { + if (cg_skippingcin.integer != 0) { cg.captionTextTime = 0; return; } - if ( cg.captionNextTextTime < cg.time ) - { + if (cg.captionNextTextTime < cg.time) { cg.captionTextCurrentLine += 2; - if (cg.captionTextCurrentLine >= cg.scrollTextLines) - { + if (cg.captionTextCurrentLine >= cg.scrollTextLines) { cg.captionTextTime = 0; return; - } - else - { + } else { holdTime = strlen(cg.captionText[cg.captionTextCurrentLine]); - if (cg.scrollTextLines >= cg.captionTextCurrentLine) - { + if (cg.scrollTextLines >= cg.captionTextCurrentLine) { // ( strlen is also good for MBCS in this instance, since it's for timing -ste) // holdTime += strlen(cg.captionText[cg.captionTextCurrentLine + 1]); } - cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime);//50); + cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime); // 50); } } // Give a color if one wasn't given - if((textcolor_caption[0] == 0) && (textcolor_caption[1] == 0) && - (textcolor_caption[2] == 0) && (textcolor_caption[3] == 0)) - { - VectorCopy4( colorTable[CT_WHITE], textcolor_caption ); + if ((textcolor_caption[0] == 0) && (textcolor_caption[1] == 0) && (textcolor_caption[2] == 0) && (textcolor_caption[3] == 0)) { + VectorCopy4(colorTable[CT_WHITE], textcolor_caption); } cgi_R_SetColor(textcolor_caption); // Set Y of the first line (varies if only printing one line of text) // (this all works, please don't mess with it) - const int fontHeight = (int) ((cgi_Language_IsAsian() ? 1.4f : 1.0f) * (float) cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, fFontScale)); - const bool bPrinting2Lines = !!(cg.captionText[ cg.captionTextCurrentLine+1 ][0]); - y = cg.captionTextY - ( (float)fontHeight * (bPrinting2Lines ? 1 : 0.5f)); // captionTextY was a centered Y pos, not a top one + const int fontHeight = (int)((cgi_Language_IsAsian() ? 1.4f : 1.0f) * (float)cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, fFontScale)); + const bool bPrinting2Lines = !!(cg.captionText[cg.captionTextCurrentLine + 1][0]); + y = cg.captionTextY - ((float)fontHeight * (bPrinting2Lines ? 1 : 0.5f)); // captionTextY was a centered Y pos, not a top one y -= cgi_Language_IsAsian() ? 0 : 4; - for (i= cg.captionTextCurrentLine;i< cg.captionTextCurrentLine + 2;++i) - { + for (i = cg.captionTextCurrentLine; i < cg.captionTextCurrentLine + 2; ++i) { w = cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale); - if (w) - { - x = (SCREEN_WIDTH-w) / 2; + if (w) { + x = (SCREEN_WIDTH - w) / 2; cgi_R_Font_DrawString(x, y, cg.captionText[i], textcolor_caption, cgs.media.qhFontMedium, -1, fFontScale); y += fontHeight; } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -474,40 +408,37 @@ CG_ScrollText - split text up into seperate lines */ int giScrollTextPixelWidth = SCREEN_WIDTH; -void CG_ScrollText( const char *str, int iPixelWidth ) -{ - const char *s,*holds; - int i;//, len;//, numChars; +void CG_ScrollText(const char *str, int iPixelWidth) { + const char *s, *holds; + int i; //, len;//, numChars; giScrollTextPixelWidth = iPixelWidth; // first, ask the strlen of the final string... // - i = cgi_SP_GetStringTextString( str, NULL, 0 ); + i = cgi_SP_GetStringTextString(str, NULL, 0); - //ensure we found a match - if (!i) - { + // ensure we found a match + if (!i) { #ifndef FINAL_BUILD - Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n",str); + Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n", str); #endif return; } // // malloc space to hold it... // - char *psText = (char *) cgi_Z_Malloc( i+1, TAG_TEMP_WORKSPACE ); + char *psText = (char *)cgi_Z_Malloc(i + 1, TAG_TEMP_WORKSPACE); // // now get the string... // - i = cgi_SP_GetStringTextString( str, psText, i+1 ); - //ensure we found a match - if (!i) - { - assert(0); // should never get here now, but wtf? + i = cgi_SP_GetStringTextString(str, psText, i + 1); + // ensure we found a match + if (!i) { + assert(0); // should never get here now, but wtf? cgi_Z_Free(psText); #ifndef FINAL_BUILD - Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n",str); + Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n", str); #endif return; } @@ -521,9 +452,8 @@ void CG_ScrollText( const char *str, int iPixelWidth ) holds = s; const char *psBestLineBreakSrcPos = s; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) - while( *s ) - { + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + while (*s) { psLastGood_s = s; // read letter... @@ -535,49 +465,38 @@ void CG_ScrollText( const char *str, int iPixelWidth ) // concat onto string so far... // - if (uiLetter == 32 && cg.printText[i][0] == '\0') - { + if (uiLetter == 32 && cg.printText[i][0] == '\0') { holds++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(cg.printText[i],sizeof(cg.printText[i]),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(cg.printText[i],sizeof(cg.printText[i]),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(cg.printText[i], sizeof(cg.printText[i]), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(cg.printText[i], sizeof(cg.printText[i]), va("%c", uiLetter & 0xFF)); } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ') - { + if (bIsTrailingPunctuation || uiLetter == ' ') { psBestLineBreakSrcPos = s; } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - cg.printText[i][ strlen(cg.printText[i])-1 ] = '\0'; // kill the CR + cg.printText[i][strlen(cg.printText[i]) - 1] = '\0'; // kill the CR i++; - assert (i < (int)(sizeof(cg.printText)/sizeof(cg.printText[0])) ); - if (i >= (int)(sizeof(cg.printText)/sizeof(cg.printText[0])) ) - { + assert(i < (int)(sizeof(cg.printText) / sizeof(cg.printText[0]))); + if (i >= (int)(sizeof(cg.printText) / sizeof(cg.printText[0]))) { break; } holds = s; cg.scrollTextLines++; - } - else - if ( cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f) >= iPixelWidth) - { + } else if (cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f) >= iPixelWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (psBestLineBreakSrcPos == holds) - { + if (psBestLineBreakSrcPos == holds) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -585,77 +504,69 @@ void CG_ScrollText( const char *str, int iPixelWidth ) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - cg.printText[i][ psBestLineBreakSrcPos - holds ] = '\0'; + cg.printText[i][psBestLineBreakSrcPos - holds] = '\0'; holds = s = psBestLineBreakSrcPos; i++; - assert (i < (int)(sizeof(cg.printText)/sizeof(cg.printText[0])) ); + assert(i < (int)(sizeof(cg.printText) / sizeof(cg.printText[0]))); cg.scrollTextLines++; } } - cg.captionTextTime = 0; // No captions during scrolling + cg.captionTextTime = 0; // No captions during scrolling cgi_Z_Free(psText); } - // draws using [textcolor_scroll]... // -#define SCROLL_LPM (1/50.0) // 1 line per 50 ms -void CG_DrawScrollText(void) -{ - int i; - int x,y; - const int fontHeight = (int) (1.5f * (float) cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f)); // taiwanese & japanese need 1.5 fontheight spacing - - if ( !cg.scrollTextTime ) - { +#define SCROLL_LPM (1 / 50.0) // 1 line per 50 ms +void CG_DrawScrollText(void) { + int i; + int x, y; + const int fontHeight = (int)(1.5f * (float)cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f)); // taiwanese & japanese need 1.5 fontheight spacing + + if (!cg.scrollTextTime) { return; } - cgi_R_SetColor( textcolor_scroll ); + cgi_R_SetColor(textcolor_scroll); y = cg.printTextY - (cg.time - cg.scrollTextTime) * SCROLL_LPM; -// cgi_R_Font_DrawString(320, 200, va("Scrolltext printing @ %d",y), colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + // cgi_R_Font_DrawString(320, 200, va("Scrolltext printing @ %d",y), colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); // See if text has finished scrolling off screen - if ((y + cg.scrollTextLines * fontHeight) < 1) - { + if ((y + cg.scrollTextLines * fontHeight) < 1) { cg.scrollTextTime = 0; return; } - for (i=0;i SCREEN_HEIGHT) - { + else if (y > SCREEN_HEIGHT) { break; } -// w = cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f); -// if (w) + // w = cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f); + // if (w) { x = (SCREEN_WIDTH - giScrollTextPixelWidth) / 2; - cgi_R_Font_DrawString(x,y, cg.printText[i], textcolor_scroll, cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x, y, cg.printText[i], textcolor_scroll, cgs.media.qhFontMedium, -1, 1.0f); y += fontHeight; } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - /* =============================================================================== @@ -664,7 +575,6 @@ CENTER PRINTING =============================================================================== */ - /* ============== CG_CenterPrint @@ -673,25 +583,21 @@ Called for important messages that should stay in the center of the screen for a few moments ============== */ -void CG_CenterPrint( const char *str, int y) { - char *s; +void CG_CenterPrint(const char *str, int y) { + char *s; // Find text to match the str given - if (*str == '@') - { + if (*str == '@') { int i; - i = cgi_SP_GetStringTextString( str+1, cg.centerPrint, sizeof(cg.centerPrint) ); + i = cgi_SP_GetStringTextString(str + 1, cg.centerPrint, sizeof(cg.centerPrint)); - if (!i) - { - Com_Printf (S_COLOR_RED"CG_CenterPrint: cannot find reference '%s' in StringPackage!\n",str); - Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); + if (!i) { + Com_Printf(S_COLOR_RED "CG_CenterPrint: cannot find reference '%s' in StringPackage!\n", str); + Q_strncpyz(cg.centerPrint, str, sizeof(cg.centerPrint)); } - } - else - { - Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); + } else { + Q_strncpyz(cg.centerPrint, str, sizeof(cg.centerPrint)); } cg.centerPrintTime = cg.time; @@ -700,40 +606,35 @@ void CG_CenterPrint( const char *str, int y) { // count the number of lines for centering cg.centerPrintLines = 1; s = cg.centerPrint; - while( *s ) { + while (*s) { if (*s == '\n') cg.centerPrintLines++; s++; } - } - /* =================== CG_DrawCenterString =================== */ -void CG_DrawCenterString( void ) -{ - char *start; +void CG_DrawCenterString(void) { + char *start; unsigned int l; - int x, y, w; - float *color; + int x, y, w; + float *color; - if ( !cg.centerPrintTime ) { + if (!cg.centerPrintTime) { return; } - color = CG_FadeColor( cg.centerPrintTime, 1000 * 3 ); - if ( !color ) { + color = CG_FadeColor(cg.centerPrintTime, 1000 * 3); + if (!color) { return; } - if((textcolor_center[0] == 0) && (textcolor_center[1] == 0) && - (textcolor_center[2] == 0) && (textcolor_center[3] == 0)) - { - VectorCopy4( colorTable[CT_WHITE], textcolor_center ); + if ((textcolor_center[0] == 0) && (textcolor_center[1] == 0) && (textcolor_center[2] == 0) && (textcolor_center[3] == 0)) { + VectorCopy4(colorTable[CT_WHITE], textcolor_center); } start = cg.centerPrint; @@ -741,27 +642,24 @@ void CG_DrawCenterString( void ) const int fontHeight = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f); y = cg.centerPrintY - (cg.centerPrintLines * fontHeight) / 2; - while ( 1 ) { + while (1) { char linebuffer[1024]; // this is kind of unpleasant when dealing with MBCS, but... // const char *psString = start; int iOutIndex = 0; - for ( l = 0; l < sizeof(linebuffer)-1; l++ ) { + for (l = 0; l < sizeof(linebuffer) - 1; l++) { int iAdvanceCount; unsigned int uiLetter = cgi_AnyLanguage_ReadCharFromString(psString, &iAdvanceCount); psString += iAdvanceCount; - if (!uiLetter || uiLetter == '\n'){ + if (!uiLetter || uiLetter == '\n') { break; } - if (uiLetter > 255) - { + if (uiLetter > 255) { linebuffer[iOutIndex++] = uiLetter >> 8; linebuffer[iOutIndex++] = uiLetter & 0xFF; - } - else - { + } else { linebuffer[iOutIndex++] = uiLetter & 0xFF; } } @@ -769,19 +667,18 @@ void CG_DrawCenterString( void ) w = cgi_R_Font_StrLenPixels(linebuffer, cgs.media.qhFontMedium, 1.0f); - x = ( SCREEN_WIDTH - w ) / 2; + x = (SCREEN_WIDTH - w) / 2; - cgi_R_Font_DrawString(x,y,linebuffer, textcolor_center, cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x, y, linebuffer, textcolor_center, cgs.media.qhFontMedium, -1, 1.0f); y += fontHeight; - while ( *start && ( *start != '\n' ) ) { + while (*start && (*start != '\n')) { start++; } - if ( !*start ) { + if (!*start) { break; } start++; } - } diff --git a/code/cgame/cg_view.cpp b/code/cgame/cg_view.cpp index 01cb293e07..9f09fb23b2 100644 --- a/code/cgame/cg_view.cpp +++ b/code/cgame/cg_view.cpp @@ -33,13 +33,13 @@ along with this program; if not, see . #include "../game/g_vehicles.h" #define MASK_CAMERACLIP (MASK_SOLID) -#define CAMERA_SIZE 4 +#define CAMERA_SIZE 4 float cg_zoomFov; //#define CG_CAM_ABOVE 2 -extern qboolean CG_OnMovingPlat( playerState_t *ps ); -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); +extern qboolean CG_OnMovingPlat(playerState_t *ps); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); extern int g_crosshairSameEntTime; extern int g_crosshairEntNum; @@ -91,83 +91,76 @@ Creates an entity in front of the current position, which can then be moved around ================= */ -void CG_TestG2Model_f (void) { - vec3_t angles; +void CG_TestG2Model_f(void) { + vec3_t angles; CGhoul2Info_v *ghoul2; - memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) ); + memset(&cg.testModelEntity, 0, sizeof(cg.testModelEntity)); ghoul2 = new CGhoul2Info_v; cg.testModelEntity.ghoul2 = ghoul2; - if ( cgi_Argc() < 2 ) { + if (cgi_Argc() < 2) { return; } - Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH ); - cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + Q_strncpyz(cg.testModelName, CG_Argv(1), MAX_QPATH); + cg.testModelEntity.hModel = cgi_R_RegisterModel(cg.testModelName); - cg.testModel = gi.G2API_InitGhoul2Model(*((CGhoul2Info_v *)cg.testModelEntity.ghoul2), cg.testModelName, cg.testModelEntity.hModel, NULL_HANDLE, NULL_HANDLE,0,0); + cg.testModel = + gi.G2API_InitGhoul2Model(*((CGhoul2Info_v *)cg.testModelEntity.ghoul2), cg.testModelName, cg.testModelEntity.hModel, NULL_HANDLE, NULL_HANDLE, 0, 0); cg.testModelEntity.radius = 100.0f; - if ( cgi_Argc() == 3 ) { - cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) ); + if (cgi_Argc() == 3) { + cg.testModelEntity.backlerp = atof(CG_Argv(2)); cg.testModelEntity.frame = 1; cg.testModelEntity.oldframe = 0; } - if (! cg.testModelEntity.hModel ) { - CG_Printf( "Can't register model\n" ); + if (!cg.testModelEntity.hModel) { + CG_Printf("Can't register model\n"); return; } - VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin ); + VectorMA(cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin); angles[PITCH] = 0; angles[YAW] = 180 + cg.refdefViewAngles[1]; angles[ROLL] = 0; - AnglesToAxis( angles, cg.testModelEntity.axis ); + AnglesToAxis(angles, cg.testModelEntity.axis); } -void CG_ListModelSurfaces_f (void) -{ - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); +void CG_ListModelSurfaces_f(void) { + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); - gi.G2API_ListSurfaces(&ghoul2[cg.testModel]); + gi.G2API_ListSurfaces(&ghoul2[cg.testModel]); } - -void CG_ListModelBones_f (void) -{ - // test to see if we got enough args - if ( cgi_Argc() < 2 ) - { +void CG_ListModelBones_f(void) { + // test to see if we got enough args + if (cgi_Argc() < 2) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); gi.G2API_ListBones(&ghoul2[cg.testModel], atoi(CG_Argv(1))); } -void CG_TestModelSurfaceOnOff_f(void) -{ +void CG_TestModelSurfaceOnOff_f(void) { // test to see if we got enough args - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); gi.G2API_SetSurfaceOnOff(&ghoul2[cg.testModel], CG_Argv(1), atoi(CG_Argv(2))); } -void CG_TestModelSetAnglespre_f(void) -{ - vec3_t angles; +void CG_TestModelSetAnglespre_f(void) { + vec3_t angles; - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); angles[0] = atof(CG_Argv(2)); angles[1] = atof(CG_Argv(3)); @@ -175,15 +168,13 @@ void CG_TestModelSetAnglespre_f(void) gi.G2API_SetBoneAngles(&ghoul2[cg.testModel], CG_Argv(1), angles, BONE_ANGLES_PREMULT, POSITIVE_X, POSITIVE_Z, POSITIVE_Y, NULL, 0, 0); } -void CG_TestModelSetAnglespost_f(void) -{ - vec3_t angles; +void CG_TestModelSetAnglespost_f(void) { + vec3_t angles; - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); angles[0] = atof(CG_Argv(2)); angles[1] = atof(CG_Argv(3)); @@ -191,21 +182,18 @@ void CG_TestModelSetAnglespost_f(void) gi.G2API_SetBoneAngles(&ghoul2[cg.testModel], CG_Argv(1), angles, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Z, POSITIVE_Y, NULL, 0, 0); } -void CG_TestModelAnimate_f(void) -{ - char boneName[100]; - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); +void CG_TestModelAnimate_f(void) { + char boneName[100]; + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); strcpy(boneName, CG_Argv(1)); gi.G2API_SetBoneAnim(&ghoul2[cg.testModel], boneName, atoi(CG_Argv(2)), atoi(CG_Argv(3)), BONE_ANIM_OVERRIDE_LOOP, atof(CG_Argv(4)), cg.time, -1, -1); - } /* Ghoul2 Insert End */ - /* ================= CG_TestModel_f @@ -214,79 +202,75 @@ Creates an entity in front of the current position, which can then be moved around ================= */ -void CG_TestModel_f (void) { - vec3_t angles; +void CG_TestModel_f(void) { + vec3_t angles; - memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) ); - if ( cgi_Argc() < 2 ) { + memset(&cg.testModelEntity, 0, sizeof(cg.testModelEntity)); + if (cgi_Argc() < 2) { return; } - Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH ); - cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + Q_strncpyz(cg.testModelName, CG_Argv(1), MAX_QPATH); + cg.testModelEntity.hModel = cgi_R_RegisterModel(cg.testModelName); - if ( cgi_Argc() == 3 ) { - cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) ); + if (cgi_Argc() == 3) { + cg.testModelEntity.backlerp = atof(CG_Argv(2)); cg.testModelEntity.frame = 1; cg.testModelEntity.oldframe = 0; } - if (! cg.testModelEntity.hModel ) { - CG_Printf( "Can't register model\n" ); + if (!cg.testModelEntity.hModel) { + CG_Printf("Can't register model\n"); return; } - VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin ); + VectorMA(cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin); angles[PITCH] = 0; angles[YAW] = 180 + cg.refdefViewAngles[1]; angles[ROLL] = 0; - AnglesToAxis( angles, cg.testModelEntity.axis ); + AnglesToAxis(angles, cg.testModelEntity.axis); } - -void CG_TestModelNextFrame_f (void) { +void CG_TestModelNextFrame_f(void) { cg.testModelEntity.frame++; - CG_Printf( "frame %i\n", cg.testModelEntity.frame ); + CG_Printf("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelPrevFrame_f (void) { +void CG_TestModelPrevFrame_f(void) { cg.testModelEntity.frame--; - if ( cg.testModelEntity.frame < 0 ) { + if (cg.testModelEntity.frame < 0) { cg.testModelEntity.frame = 0; } - CG_Printf( "frame %i\n", cg.testModelEntity.frame ); + CG_Printf("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelNextSkin_f (void) { +void CG_TestModelNextSkin_f(void) { cg.testModelEntity.skinNum++; - CG_Printf( "skin %i\n", cg.testModelEntity.skinNum ); + CG_Printf("skin %i\n", cg.testModelEntity.skinNum); } -void CG_TestModelPrevSkin_f (void) { +void CG_TestModelPrevSkin_f(void) { cg.testModelEntity.skinNum--; - if ( cg.testModelEntity.skinNum < 0 ) { + if (cg.testModelEntity.skinNum < 0) { cg.testModelEntity.skinNum = 0; } - CG_Printf( "skin %i\n", cg.testModelEntity.skinNum ); + CG_Printf("skin %i\n", cg.testModelEntity.skinNum); } -static void CG_AddTestModel (void) { +static void CG_AddTestModel(void) { // re-register the model, because the level may have changed -/* cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); - if (! cg.testModelEntity.hModel ) { - CG_Printf ("Can't register model\n"); - return; - } -*/ - cgi_R_AddRefEntityToScene( &cg.testModelEntity ); + /* cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + if (! cg.testModelEntity.hModel ) { + CG_Printf ("Can't register model\n"); + return; + } + */ + cgi_R_AddRefEntityToScene(&cg.testModelEntity); } - - //============================================================================ - /* ================= CG_CalcVrect @@ -294,8 +278,8 @@ CG_CalcVrect Sets the coordinates of the rendered window ================= */ -void CG_CalcVrect (void) { - const int size = 100; +void CG_CalcVrect(void) { + const int size = 100; cg.refdef.width = cgs.glconfig.vidWidth * size * 0.01; cg.refdef.width &= ~1; @@ -309,22 +293,22 @@ void CG_CalcVrect (void) { //============================================================================== //============================================================================== -#define CAMERA_DAMP_INTERVAL 50 +#define CAMERA_DAMP_INTERVAL 50 -#define CAMERA_CROUCH_NUDGE 6 +#define CAMERA_CROUCH_NUDGE 6 -static vec3_t cameramins = { -CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE }; -static vec3_t cameramaxs = { CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE }; -vec3_t camerafwd, cameraup, camerahorizdir; +static vec3_t cameramins = {-CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE}; +static vec3_t cameramaxs = {CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE}; +vec3_t camerafwd, cameraup, camerahorizdir; -vec3_t cameraFocusAngles, cameraFocusLoc; -vec3_t cameraIdealTarget, cameraIdealLoc; -vec3_t cameraCurTarget={0,0,0}, cameraCurLoc={0,0,0}; -vec3_t cameraOldLoc={0,0,0}, cameraNewLoc={0,0,0}; -int cameraLastFrame=0; +vec3_t cameraFocusAngles, cameraFocusLoc; +vec3_t cameraIdealTarget, cameraIdealLoc; +vec3_t cameraCurTarget = {0, 0, 0}, cameraCurLoc = {0, 0, 0}; +vec3_t cameraOldLoc = {0, 0, 0}, cameraNewLoc = {0, 0, 0}; +int cameraLastFrame = 0; -float cameraLastYaw=0; -float cameraStiffFactor=0.0f; +float cameraLastYaw = 0; +float cameraStiffFactor = 0.0f; /* =============== @@ -346,156 +330,105 @@ CG_CalcIdealThirdPersonViewTarget =============== */ -static void CG_CalcIdealThirdPersonViewTarget(void) -{ +static void CG_CalcIdealThirdPersonViewTarget(void) { // Initialize IdealTarget qboolean usesViewEntity = (qboolean)(cg.snap->ps.viewEntity && cg.snap->ps.viewEntity < ENTITYNUM_WORLD); VectorCopy(cg.refdef.vieworg, cameraFocusLoc); - if ( usesViewEntity ) - { + if (usesViewEntity) { gentity_t *gent = &g_entities[cg.snap->ps.viewEntity]; - if ( gent->client && (gent->client->NPC_class == CLASS_GONK - || gent->client->NPC_class == CLASS_INTERROGATOR - || gent->client->NPC_class == CLASS_SENTRY - || gent->client->NPC_class == CLASS_PROBE - || gent->client->NPC_class == CLASS_MOUSE - || gent->client->NPC_class == CLASS_R2D2 - || gent->client->NPC_class == CLASS_R5D2) ) - { // Droids use a generic offset + if (gent->client && (gent->client->NPC_class == CLASS_GONK || gent->client->NPC_class == CLASS_INTERROGATOR || + gent->client->NPC_class == CLASS_SENTRY || gent->client->NPC_class == CLASS_PROBE || gent->client->NPC_class == CLASS_MOUSE || + gent->client->NPC_class == CLASS_R2D2 || gent->client->NPC_class == CLASS_R5D2)) { // Droids use a generic offset cameraFocusLoc[2] += 4; - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); return; } - if( gent->client->ps.pm_flags & PMF_DUCKED ) - { // sort of a nasty hack in order to get this to work. Don't tell Ensiform, or I'll have to kill him. --eez - cameraFocusLoc[2] -= CAMERA_CROUCH_NUDGE*4; + if (gent->client->ps.pm_flags & PMF_DUCKED) { // sort of a nasty hack in order to get this to work. Don't tell Ensiform, or I'll have to kill him. --eez + cameraFocusLoc[2] -= CAMERA_CROUCH_NUDGE * 4; } } // Add in the new viewheight cameraFocusLoc[2] += cg.predicted_player_state.viewheight; - if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) ) - { - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE)) { + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += 192; - } - else if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_WAMPA) ) - { - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + } else if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_WAMPA)) { + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] -= 48; - } - else if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_VOF ) - { + } else if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_VOF) { // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += cg.overrides.thirdPersonVertOffset; - //VectorMA(cameraFocusLoc, cg.overrides.thirdPersonVertOffset, cameraup, cameraIdealTarget); - } - else - { + // VectorMA(cameraFocusLoc, cg.overrides.thirdPersonVertOffset, cameraup, cameraIdealTarget); + } else { // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += cg_thirdPersonVertOffset.value; - //VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); + // VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); } // Now, if the player is crouching, do a little special tweak. The problem is that the player's head is way out of his bbox. - if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - { // Nudge to focus location up a tad. + if (cg.predicted_player_state.pm_flags & PMF_DUCKED) { // Nudge to focus location up a tad. vec3_t nudgepos; trace_t trace; VectorCopy(cameraFocusLoc, nudgepos); - nudgepos[2]+=CAMERA_CROUCH_NUDGE; - CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, nudgepos, - ( usesViewEntity ) ? cg.snap->ps.viewEntity : cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction < 1.0) - { + nudgepos[2] += CAMERA_CROUCH_NUDGE; + CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, nudgepos, (usesViewEntity) ? cg.snap->ps.viewEntity : cg.predicted_player_state.clientNum, + MASK_CAMERACLIP); + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraFocusLoc); - } - else - { + } else { VectorCopy(nudgepos, cameraFocusLoc); } } } - - /* =============== CG_CalcIdealThirdPersonViewLocation =============== */ -static void CG_CalcIdealThirdPersonViewLocation(void) -{ - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_RNG ) - { +static void CG_CalcIdealThirdPersonViewLocation(void) { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_RNG) { VectorMA(cameraIdealTarget, -(cg.overrides.thirdPersonRange), camerafwd, cameraIdealLoc); - } - else if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_RANCOR) - && cg_entities[cg.snap->ps.clientNum].gent->activator ) - {//stay back - VectorMA(cameraIdealTarget, -180.0f*cg_entities[cg.snap->ps.clientNum].gent->activator->s.modelScale[0], camerafwd, cameraIdealLoc); - } - else if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_WAMPA) - && cg_entities[cg.snap->ps.clientNum].gent->activator - && cg_entities[cg.snap->ps.clientNum].gent->activator->inuse ) - {//stay back - VectorMA(cameraIdealTarget, -120.0f*cg_entities[cg.snap->ps.clientNum].gent->activator->s.modelScale[0], camerafwd, cameraIdealLoc); - } - else if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - && cg_entities[cg.snap->ps.clientNum].gent->activator ) - {//stay back + } else if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_RANCOR) && cg_entities[cg.snap->ps.clientNum].gent->activator) { // stay back + VectorMA(cameraIdealTarget, -180.0f * cg_entities[cg.snap->ps.clientNum].gent->activator->s.modelScale[0], camerafwd, cameraIdealLoc); + } else if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_WAMPA) && cg_entities[cg.snap->ps.clientNum].gent->activator && + cg_entities[cg.snap->ps.clientNum].gent->activator->inuse) { // stay back + VectorMA(cameraIdealTarget, -120.0f * cg_entities[cg.snap->ps.clientNum].gent->activator->s.modelScale[0], camerafwd, cameraIdealLoc); + } else if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE) && cg_entities[cg.snap->ps.clientNum].gent->activator) { // stay back VectorMA(cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number].lerpOrigin, -180.0f, camerafwd, cameraIdealLoc); - } - else - { + } else { VectorMA(cameraIdealTarget, -(cg_thirdPersonRange.value), camerafwd, cameraIdealLoc); } - if ( cg.renderingThirdPerson && (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] ) - { + if (cg.renderingThirdPerson && (cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && player->client->ps.forcePowerDuration[FP_SPEED]) { float timeLeft = player->client->ps.forcePowerDuration[FP_SPEED] - cg.time; - float length = FORCE_SPEED_DURATION*forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; + float length = FORCE_SPEED_DURATION * forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; float amt = forceSpeedRangeMod[player->client->ps.forcePowerLevel[FP_SPEED]]; - if ( timeLeft < 500 ) - {//start going back - VectorMA(cameraIdealLoc, (timeLeft)/500*amt, camerafwd, cameraIdealLoc); - } - else if ( length - timeLeft < 1000 ) - {//start zooming in - VectorMA(cameraIdealLoc, (length - timeLeft)/1000*amt, camerafwd, cameraIdealLoc); - } - else - { + if (timeLeft < 500) { // start going back + VectorMA(cameraIdealLoc, (timeLeft) / 500 * amt, camerafwd, cameraIdealLoc); + } else if (length - timeLeft < 1000) { // start zooming in + VectorMA(cameraIdealLoc, (length - timeLeft) / 1000 * amt, camerafwd, cameraIdealLoc); + } else { VectorMA(cameraIdealLoc, amt, camerafwd, cameraIdealLoc); } } } - - -static void CG_ResetThirdPersonViewDamp(void) -{ +static void CG_ResetThirdPersonViewDamp(void) { trace_t trace; // Cap the pitch within reasonable limits - if (cameraFocusAngles[PITCH] > 89.0) - { + if (cameraFocusAngles[PITCH] > 89.0) { cameraFocusAngles[PITCH] = 89.0; - } - else if (cameraFocusAngles[PITCH] < -89.0) - { + } else if (cameraFocusAngles[PITCH] < -89.0) { cameraFocusAngles[PITCH] = -89.0; } @@ -513,15 +446,13 @@ static void CG_ResetThirdPersonViewDamp(void) // First thing we do is trace from the first person viewpoint out to the new target location. CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } // Now we trace from the new target location to the new view location, to make sure there is nothing in the way. CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurLoc); } @@ -531,40 +462,36 @@ static void CG_ResetThirdPersonViewDamp(void) } // This is called every frame. -static void CG_UpdateThirdPersonTargetDamp(void) -{ +static void CG_UpdateThirdPersonTargetDamp(void) { trace_t trace; - vec3_t targetdiff; - float dampfactor, dtime, ratio; + vec3_t targetdiff; + float dampfactor, dtime, ratio; // Set the cameraIdealTarget // Automatically get the ideal target, to avoid jittering. CG_CalcIdealThirdPersonViewTarget(); - if ( CG_OnMovingPlat( &cg.snap->ps ) ) - {//if moving on a plat, camera is *tight* + if (CG_OnMovingPlat(&cg.snap->ps)) { // if moving on a plat, camera is *tight* VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=1.0)//||cg.thisFrameTeleport) - { // No damping. + } else if (cg_thirdPersonTargetDamp.value >= 1.0) //||cg.thisFrameTeleport) + { // No damping. VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=0.0) - { + } else if (cg_thirdPersonTargetDamp.value >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealTarget, cameraCurTarget, targetdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/cg_timescale.value) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / cg_timescale.value) * + (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. - if ( cg_smoothCamera.integer ) - ratio = powf( dampfactor, dtime ); + if (cg_smoothCamera.integer) + ratio = powf(dampfactor, dtime); else - ratio = Q_powf( dampfactor, dtime ); + ratio = Q_powf(dampfactor, dtime); // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealTarget, -ratio, targetdiff, cameraCurTarget); @@ -574,18 +501,15 @@ static void CG_UpdateThirdPersonTargetDamp(void) // Now we trace to see if the new location is cool or not. // First thing we do is trace from the first person viewpoint out to the new target location. - if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - && cg_entities[cg.snap->ps.clientNum].gent->activator ) - {//if being held by a sand creature, trace from his actual origin, since we could be underground or otherwise in solid once he eats us - CG_Trace(&trace, cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number].lerpOrigin, cameramins, cameramaxs, cameraCurTarget, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - } - else - { + if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE) && + cg_entities[cg.snap->ps.clientNum].gent->activator) { // if being held by a sand creature, trace from his actual origin, since we could be underground + // or otherwise in solid once he eats us + CG_Trace(&trace, cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number].lerpOrigin, cameramins, cameramaxs, cameraCurTarget, + cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + } else { CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); } - if (trace.fraction < 1.0) - { + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } @@ -597,40 +521,32 @@ static void CG_UpdateThirdPersonTargetDamp(void) // This can be called every interval, at the user's discretion. static int camWaterAdjust = 0; -static void CG_UpdateThirdPersonCameraDamp(void) -{ +static void CG_UpdateThirdPersonCameraDamp(void) { trace_t trace; - vec3_t locdiff; + vec3_t locdiff; float dampfactor, dtime, ratio; // Set the cameraIdealLoc CG_CalcIdealThirdPersonViewLocation(); - // First thing we do is calculate the appropriate damping factor for the camera. - dampfactor=0.0f; - if ( CG_OnMovingPlat( &cg.snap->ps ) ) - {//if moving on a plat, camera is *tight* - dampfactor=1.0f; - } - else if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_CDP ) - { - if ( cg.overrides.thirdPersonCameraDamp != 0.0f ) - { + dampfactor = 0.0f; + if (CG_OnMovingPlat(&cg.snap->ps)) { // if moving on a plat, camera is *tight* + dampfactor = 1.0f; + } else if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_CDP) { + if (cg.overrides.thirdPersonCameraDamp != 0.0f) { float pitch; // Note that the camera pitch has already been capped off to 89. pitch = Q_fabs(cameraFocusAngles[PITCH]); // The higher the pitch, the larger the factor, so as you look up, it damps a lot less. - pitch /=115.0f; - dampfactor = (1.0-cg.overrides.thirdPersonCameraDamp)*(pitch*pitch); + pitch /= 115.0f; + dampfactor = (1.0 - cg.overrides.thirdPersonCameraDamp) * (pitch * pitch); dampfactor += cg.overrides.thirdPersonCameraDamp; } - } - else if ( cg_thirdPersonCameraDamp.value != 0.0f ) - { + } else if (cg_thirdPersonCameraDamp.value != 0.0f) { float pitch; // Note that the camera pitch has already been capped off to 89. @@ -638,37 +554,36 @@ static void CG_UpdateThirdPersonCameraDamp(void) // The higher the pitch, the larger the factor, so as you look up, it damps a lot less. pitch /= 115.0f; - dampfactor = (1.0-cg_thirdPersonCameraDamp.value)*(pitch*pitch); + dampfactor = (1.0 - cg_thirdPersonCameraDamp.value) * (pitch * pitch); dampfactor += cg_thirdPersonCameraDamp.value; // Now we also multiply in the stiff factor, so that faster yaw changes are stiffer. - if (cameraStiffFactor > 0.0f) - { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. - dampfactor += (1.0-dampfactor)*cameraStiffFactor; + if (cameraStiffFactor > + 0.0f) { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. + dampfactor += (1.0 - dampfactor) * cameraStiffFactor; } } - if (dampfactor>=1.0)//||cg.thisFrameTeleport) - { // No damping. + if (dampfactor >= 1.0) //||cg.thisFrameTeleport) + { // No damping. VectorCopy(cameraIdealLoc, cameraCurLoc); - } - else if (dampfactor>=0.0) - { + } else if (dampfactor >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealLoc, cameraCurLoc, locdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-dampfactor; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/cg_timescale.value) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - dampfactor; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / cg_timescale.value) * + (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. - if ( cg_smoothCamera.integer ) - ratio = powf( dampfactor, dtime ); + if (cg_smoothCamera.integer) + ratio = powf(dampfactor, dtime); else - ratio = Q_powf( dampfactor, dtime ); + ratio = Q_powf(dampfactor, dtime); // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealLoc, -ratio, locdiff, cameraCurLoc); @@ -676,27 +591,24 @@ static void CG_UpdateThirdPersonCameraDamp(void) } // Now we trace from the first person viewpoint to the new view location, to make sure there is nothing in the way between the user and the camera... -// CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + // CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); // (OLD) Now we trace from the new target location to the new view location, to make sure there is nothing in the way. - if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - && cg_entities[cg.snap->ps.clientNum].gent->activator ) - {//if being held by a sand creature, trace from his actual origin, since we could be underground or otherwise in solid once he eats us - CG_Trace( &trace, cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number].lerpOrigin, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - } - else - { - CG_Trace( &trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE) && + cg_entities[cg.snap->ps.clientNum].gent->activator) { // if being held by a sand creature, trace from his actual origin, since we could be underground + // or otherwise in solid once he eats us + CG_Trace(&trace, cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number].lerpOrigin, cameramins, cameramaxs, cameraCurLoc, + cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + } else { + CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); } - if ( trace.fraction < 1.0f ) - { - VectorCopy( trace.endpos, cameraCurLoc ); + if (trace.fraction < 1.0f) { + VectorCopy(trace.endpos, cameraCurLoc); // We didn't trace all the way back, so push down the target accordingly. -// VectorSubtract(cameraCurTarget, cameraFocusLoc, locdiff); -// VectorMA(cameraFocusLoc, trace.fraction, locdiff, cameraCurTarget); + // VectorSubtract(cameraCurTarget, cameraFocusLoc, locdiff); + // VectorMA(cameraFocusLoc, trace.fraction, locdiff, cameraCurTarget); - //FIXME: when the trace hits movers, it gets very very jaggy... ? + // FIXME: when the trace hits movers, it gets very very jaggy... ? /* //this doesn't actually help any if ( trace.entityNum != ENTITYNUM_WORLD ) @@ -722,18 +634,14 @@ static void CG_UpdateThirdPersonCameraDamp(void) // however two full volume traces each frame is a bit scary to think about. } - - - /* =============== CG_OffsetThirdPersonView =============== */ -extern qboolean MatrixMode; -static void CG_OffsetThirdPersonView( void ) -{ +extern qboolean MatrixMode; +static void CG_OffsetThirdPersonView(void) { vec3_t diff; float deltayaw; @@ -741,122 +649,83 @@ static void CG_OffsetThirdPersonView( void ) cameraStiffFactor = 0.0; // Set camera viewing direction. - VectorCopy( cg.refdefViewAngles, cameraFocusAngles ); - - if ( cg.snap - && (cg.snap->ps.eFlags&EF_HELD_BY_RANCOR) - && cg_entities[cg.snap->ps.clientNum].gent->activator ) - { - centity_t *monster = &cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number]; - VectorSet( cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW]+180), 0 ); - } - else if ( cg.snap && (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) ) - { - centity_t *monster = &cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number]; - VectorSet( cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW]+180), 0 ); - cameraFocusAngles[PITCH] = 0.0f;//flatten it out - } - else if ( G_IsRidingVehicle( &g_entities[0] ) ) - { + VectorCopy(cg.refdefViewAngles, cameraFocusAngles); + + if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_RANCOR) && cg_entities[cg.snap->ps.clientNum].gent->activator) { + centity_t *monster = &cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number]; + VectorSet(cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW] + 180), 0); + } else if (cg.snap && (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE)) { + centity_t *monster = &cg_entities[cg_entities[cg.snap->ps.clientNum].gent->activator->s.number]; + VectorSet(cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW] + 180), 0); + cameraFocusAngles[PITCH] = 0.0f; // flatten it out + } else if (G_IsRidingVehicle(&g_entities[0])) { cameraFocusAngles[YAW] = cg_entities[g_entities[0].owner->s.number].lerpAngles[YAW]; - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG ) - { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG) { cameraFocusAngles[YAW] += cg.overrides.thirdPersonAngle; - } - else - { + } else { cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; } - } - else if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 ) - {// if dead, look at killer - if ( MatrixMode ) - { - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG ) - { + } else if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0) { // if dead, look at killer + if (MatrixMode) { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG) { cameraFocusAngles[YAW] += cg.overrides.thirdPersonAngle; - } - else - { + } else { cameraFocusAngles[YAW] = cg.predicted_player_state.stats[STAT_DEAD_YAW]; cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; } - } - else - { + } else { cameraFocusAngles[YAW] = cg.predicted_player_state.stats[STAT_DEAD_YAW]; } - } - else - { // Add in the third Person Angle. - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG ) - { + } else { // Add in the third Person Angle. + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG) { cameraFocusAngles[YAW] += cg.overrides.thirdPersonAngle; - } - else - { + } else { cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; } - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_POF ) - { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_POF) { cameraFocusAngles[PITCH] += cg.overrides.thirdPersonPitchOffset; - } - else - { + } else { cameraFocusAngles[PITCH] += cg_thirdPersonPitchOffset.value; } } - if ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) ) - {// First person saber + if (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) { // First person saber // FIXME: use something network-friendly - vec3_t org, viewDir; - VectorCopy( cg_entities[0].gent->client->renderInfo.eyePoint, org ); - float blend = 1.0f - fabs(cg.refdefViewAngles[PITCH])/90.0f; - AngleVectors( cg.refdefViewAngles, viewDir, NULL, NULL ); - VectorMA( org, -8, viewDir, org ); - VectorScale( org, 1.0f - blend, org ); - VectorMA( org, blend, cg.refdef.vieworg, cg.refdef.vieworg ); + vec3_t org, viewDir; + VectorCopy(cg_entities[0].gent->client->renderInfo.eyePoint, org); + float blend = 1.0f - fabs(cg.refdefViewAngles[PITCH]) / 90.0f; + AngleVectors(cg.refdefViewAngles, viewDir, NULL, NULL); + VectorMA(org, -8, viewDir, org); + VectorScale(org, 1.0f - blend, org); + VectorMA(org, blend, cg.refdef.vieworg, cg.refdef.vieworg); return; } // The next thing to do is to see if we need to calculate a new camera target location. // If we went back in time for some reason, or if we just started, reset the sample. - if (cameraLastFrame == 0 || cameraLastFrame > cg.time) - { + if (cameraLastFrame == 0 || cameraLastFrame > cg.time) { CG_ResetThirdPersonViewDamp(); - } - else - { + } else { // Cap the pitch within reasonable limits - if (cameraFocusAngles[PITCH] > 89.0) - { + if (cameraFocusAngles[PITCH] > 89.0) { cameraFocusAngles[PITCH] = 89.0; - } - else if (cameraFocusAngles[PITCH] < -89.0) - { + } else if (cameraFocusAngles[PITCH] < -89.0) { cameraFocusAngles[PITCH] = -89.0; } AngleVectors(cameraFocusAngles, camerafwd, NULL, cameraup); deltayaw = fabs(cameraFocusAngles[YAW] - cameraLastYaw); - if (deltayaw > 180.0f) - { // Normalize this angle so that it is between 0 and 180. + if (deltayaw > 180.0f) { // Normalize this angle so that it is between 0 and 180. deltayaw = fabs(deltayaw - 360.0f); } - cameraStiffFactor = deltayaw / (float)(cg.time-cameraLastFrame); - if (cameraStiffFactor < 1.0) - { + cameraStiffFactor = deltayaw / (float)(cg.time - cameraLastFrame); + if (cameraStiffFactor < 1.0) { cameraStiffFactor = 0.0; - } - else if (cameraStiffFactor > 2.5) - { + } else if (cameraStiffFactor > 2.5) { cameraStiffFactor = 0.75; - } - else - { // 1 to 2 scales from 0.0 to 0.5 - cameraStiffFactor = (cameraStiffFactor-1.0f)*0.5f; + } else { // 1 to 2 scales from 0.0 to 0.5 + cameraStiffFactor = (cameraStiffFactor - 1.0f) * 0.5f; } cameraLastYaw = cameraFocusAngles[YAW]; @@ -870,35 +739,30 @@ static void CG_OffsetThirdPersonView( void ) // We must now take the angle taken from the camera target and location. VectorSubtract(cameraCurTarget, cameraCurLoc, diff); - //Com_Printf( "%s\n", vtos(diff) ); + // Com_Printf( "%s\n", vtos(diff) ); float dist = VectorNormalize(diff); - if ( dist < 1.0f ) - {//must be hitting something, need some value to calc angles, so use cam forward - VectorCopy( camerafwd, diff ); + if (dist < 1.0f) { // must be hitting something, need some value to calc angles, so use cam forward + VectorCopy(camerafwd, diff); } vectoangles(diff, cg.refdefViewAngles); // Temp: just move the camera to the side a bit extern vmCvar_t cg_thirdPersonHorzOffset; - if ( cg_thirdPersonHorzOffset.value != 0.0f ) - { - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); - VectorMA( cameraCurLoc, cg_thirdPersonHorzOffset.value, cg.refdef.viewaxis[1], cameraCurLoc ); + if (cg_thirdPersonHorzOffset.value != 0.0f) { + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); + VectorMA(cameraCurLoc, cg_thirdPersonHorzOffset.value, cg.refdef.viewaxis[1], cameraCurLoc); } // ...and of course we should copy the new view location to the proper spot too. VectorCopy(cameraCurLoc, cg.refdef.vieworg); - //if we hit the water, do a last-minute adjustment - if ( camWaterAdjust ) - { + // if we hit the water, do a last-minute adjustment + if (camWaterAdjust) { cg.refdef.vieworg[2] += camWaterAdjust; } - cameraLastFrame=cg.time; + cameraLastFrame = cg.time; } - - /* =============== CG_OffsetThirdPersonView @@ -1038,14 +902,13 @@ static void CG_OffsetThirdPersonOverheadView( void ) { } */ // this causes a compiler bug on mac MrC compiler -static void CG_StepOffset( void ) { - int timeDelta; +static void CG_StepOffset(void) { + int timeDelta; // smooth out stair climbing timeDelta = cg.time - cg.stepTime; - if ( timeDelta < STEP_TIME ) { - cg.refdef.vieworg[2] -= cg.stepChange - * (STEP_TIME - timeDelta) / STEP_TIME; + if (timeDelta < STEP_TIME) { + cg.refdef.vieworg[2] -= cg.stepChange * (STEP_TIME - timeDelta) / STEP_TIME; } } @@ -1055,22 +918,22 @@ CG_OffsetFirstPersonView =============== */ -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern int PM_AnimLength( int index, animNumber_t anim ); -static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { - float *origin; - float *angles; - float bob; - float ratio; - float delta; - float speed; - float f; - vec3_t predictedVelocity; - int timeDelta; - - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern int PM_AnimLength(int index, animNumber_t anim); +static void CG_OffsetFirstPersonView(qboolean firstPersonSaber) { + float *origin; + float *angles; + float bob; + float ratio; + float delta; + float speed; + float f; + vec3_t predictedVelocity; + int timeDelta; + + if (cg.snap->ps.pm_type == PM_INTERMISSION) { return; } @@ -1078,8 +941,7 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { angles = cg.refdefViewAngles; // if dead, fix the angle and don't add any kick - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { angles[ROLL] = 40; angles[PITCH] = -15; angles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW]; @@ -1087,52 +949,43 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { return; } - if ( g_entities[0].client && PM_InKnockDown( &g_entities[0].client->ps ) ) - { - float perc, animLen = (float)PM_AnimLength( g_entities[0].client->clientInfo.animFileIndex, (animNumber_t)g_entities[0].client->ps.legsAnim ); - if ( PM_InGetUp( &g_entities[0].client->ps ) || PM_InForceGetUp( &g_entities[0].client->ps ) ) - {//start righting the view - perc = (float)g_entities[0].client->ps.legsAnimTimer/animLen*2; - } - else - {//tilt the view - perc = (animLen-g_entities[0].client->ps.legsAnimTimer)/animLen*2; + if (g_entities[0].client && PM_InKnockDown(&g_entities[0].client->ps)) { + float perc, animLen = (float)PM_AnimLength(g_entities[0].client->clientInfo.animFileIndex, (animNumber_t)g_entities[0].client->ps.legsAnim); + if (PM_InGetUp(&g_entities[0].client->ps) || PM_InForceGetUp(&g_entities[0].client->ps)) { // start righting the view + perc = (float)g_entities[0].client->ps.legsAnimTimer / animLen * 2; + } else { // tilt the view + perc = (animLen - g_entities[0].client->ps.legsAnimTimer) / animLen * 2; } - if ( perc > 1.0f ) - { + if (perc > 1.0f) { perc = 1.0f; } - angles[ROLL] = perc*40; - angles[PITCH] = perc*-15; + angles[ROLL] = perc * 40; + angles[PITCH] = perc * -15; } // add angles based on weapon kick int kickTime = (cg.time - cg.kick_time); - if ( kickTime < 800 ) - {//kicks are always 1 second long. Deal with it. + if (kickTime < 800) { // kicks are always 1 second long. Deal with it. float kickPerc = 0.0f; - if ( kickTime <= 200 ) - {//winding up - kickPerc = kickTime/200.0f; - } - else - {//returning to normal + if (kickTime <= 200) { // winding up + kickPerc = kickTime / 200.0f; + } else { // returning to normal kickTime = 800 - kickTime; - kickPerc = kickTime/600.0f; + kickPerc = kickTime / 600.0f; } - VectorMA( angles, kickPerc, cg.kick_angles, angles ); + VectorMA(angles, kickPerc, cg.kick_angles, angles); } // add angles based on damage kick - if ( cg.damageTime ) { + if (cg.damageTime) { ratio = cg.time - cg.damageTime; - if ( ratio < DAMAGE_DEFLECT_TIME ) { + if (ratio < DAMAGE_DEFLECT_TIME) { ratio /= DAMAGE_DEFLECT_TIME; angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } else { - ratio = 1.0 - ( ratio - DAMAGE_DEFLECT_TIME ) / DAMAGE_RETURN_TIME; - if ( ratio > 0 ) { + ratio = 1.0 - (ratio - DAMAGE_DEFLECT_TIME) / DAMAGE_RETURN_TIME; + if (ratio > 0) { angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } @@ -1148,12 +1001,12 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { #endif // add angles based on velocity - VectorCopy( cg.predicted_player_state.velocity, predictedVelocity ); + VectorCopy(cg.predicted_player_state.velocity, predictedVelocity); - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[0]); + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[0]); angles[PITCH] += delta * cg_runpitch.value; - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[1]); + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[1]); angles[ROLL] -= delta * cg_runroll.value; // add angles based on bob @@ -1163,42 +1016,35 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { delta = cg.bobfracsin * cg_bobpitch.value * speed; if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - delta *= 3; // crouching + delta *= 3; // crouching angles[PITCH] += delta; delta = cg.bobfracsin * cg_bobroll.value * speed; if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - delta *= 3; // crouching accentuates roll + delta *= 3; // crouching accentuates roll if (cg.bobcycle & 1) delta = -delta; angles[ROLL] += delta; -//=================================== + //=================================== - if ( !firstPersonSaber )//First person saber + if (!firstPersonSaber) // First person saber { // add view height - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if ( g_entities[cg.snap->ps.viewEntity].inuse && - g_entities[cg.snap->ps.viewEntity].client && - g_entities[cg.snap->ps.viewEntity].client->ps.viewheight ) - { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (g_entities[cg.snap->ps.viewEntity].inuse && g_entities[cg.snap->ps.viewEntity].client && + g_entities[cg.snap->ps.viewEntity].client->ps.viewheight) { origin[2] += g_entities[cg.snap->ps.viewEntity].client->ps.viewheight; + } else { + origin[2] += 4; //??? } - else - { - origin[2] += 4;//??? - } - } - else - { + } else { origin[2] += cg.predicted_player_state.viewheight; } } // smooth out duck height changes timeDelta = cg.time - cg.duckTime; - if ( timeDelta < DUCK_TIME) { + if (timeDelta < DUCK_TIME) { cg.refdef.vieworg[2] -= cg.duckChange * (DUCK_TIME - timeDelta) / DUCK_TIME; } @@ -1210,27 +1056,25 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { origin[2] += bob; - // add fall height delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { + if (delta < LAND_DEFLECT_TIME) { f = delta / LAND_DEFLECT_TIME; cg.refdef.vieworg[2] += cg.landChange * f; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { delta -= LAND_DEFLECT_TIME; - f = 1.0 - ( delta / LAND_RETURN_TIME ); + f = 1.0 - (delta / LAND_RETURN_TIME); cg.refdef.vieworg[2] += cg.landChange * f; } // add step offset CG_StepOffset(); - if(cg.snap->ps.leanofs != 0) - { - vec3_t right; - //add leaning offset - //FIXME: when crouching, this bounces up and down?! - cg.refdefViewAngles[2] += (float)cg.snap->ps.leanofs/2; + if (cg.snap->ps.leanofs != 0) { + vec3_t right; + // add leaning offset + // FIXME: when crouching, this bounces up and down?! + cg.refdefViewAngles[2] += (float)cg.snap->ps.leanofs / 2; AngleVectors(cg.refdefViewAngles, NULL, right, NULL); VectorMA(cg.refdef.vieworg, (float)cg.snap->ps.leanofs, right, cg.refdef.vieworg); } @@ -1238,7 +1082,7 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { // pivot the eye based on a neck length #if 0 { -#define NECK_LENGTH 8 +#define NECK_LENGTH 8 vec3_t forward, up; cg.refdef.vieworg[2] -= NECK_LENGTH; @@ -1249,7 +1093,6 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { #endif } - /* ==================== CG_CalcFovFromX @@ -1257,24 +1100,23 @@ CG_CalcFovFromX Calcs Y FOV from given X FOV ==================== */ -qboolean CG_CalcFOVFromX( float fov_x ) -{ - float x; - float fov_y; - qboolean inwater; +qboolean CG_CalcFOVFromX(float fov_x) { + float x; + float fov_y; + qboolean inwater; - if ( cg_fovAspectAdjust.integer ) { + if (cg_fovAspectAdjust.integer) { // Based on LordHavoc's code for Darkplaces // http://www.quakeworld.nu/forum/topic/53/what-does-your-qw-look-like/page/30 const float baseAspect = 0.75f; // 3/4 - const float aspect = (float)cgs.glconfig.vidWidth/(float)cgs.glconfig.vidHeight; + const float aspect = (float)cgs.glconfig.vidWidth / (float)cgs.glconfig.vidHeight; const float desiredFov = fov_x; - fov_x = atan( tan( desiredFov*M_PI / 360.0f ) * baseAspect*aspect )*360.0f / M_PI; + fov_x = atan(tan(desiredFov * M_PI / 360.0f) * baseAspect * aspect) * 360.0f / M_PI; } - x = cg.refdef.width / tan( fov_x / 360 * M_PI ); - fov_y = atan2( cg.refdef.height, x ); + x = cg.refdef.width / tan(fov_x / 360 * M_PI); + fov_y = atan2(cg.refdef.height, x); fov_y = fov_y * 360 / M_PI; // there's a problem with this, it only takes the leafbrushes into account, not the entity brushes, @@ -1282,33 +1124,28 @@ qboolean CG_CalcFOVFromX( float fov_x ) // level up/down this doesn't take into account the door position, so warps the view the whole time // whether the water is up or not. // warp if underwater - float phase; - float v; + float phase; + float v; cg.refdef.viewContents = 0; - if (gi.totalMapContents() & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA )) - { - cg.refdef.viewContents = CG_PointContents( cg.refdef.vieworg, -1 ); + if (gi.totalMapContents() & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { + cg.refdef.viewContents = CG_PointContents(cg.refdef.vieworg, -1); } - if ( cg.refdef.viewContents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) - { + if (cg.refdef.viewContents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - v = WAVE_AMPLITUDE * sin( phase ); + v = WAVE_AMPLITUDE * sin(phase); fov_x += v; fov_y -= v; inwater = qtrue; - } - else - { + } else { inwater = qfalse; } // see if we are drugged by an interrogator. We muck with the FOV here, a bit later, after viewangles are calc'ed, I muck with those too. - if ( cg.wonkyTime > 0 && cg.wonkyTime > cg.time ) - { + if (cg.wonkyTime > 0 && cg.wonkyTime > cg.time) { float perc = (float)(cg.wonkyTime - cg.time) / 10000.0f; // goes for 10 seconds - fov_x += ( 25.0f * perc ); - fov_y -= ( cos( cg.time * 0.0008f ) * 5.0f * perc ); + fov_x += (25.0f * perc); + fov_y -= (cos(cg.time * 0.0008f) * 5.0f * perc); } // set it @@ -1318,23 +1155,17 @@ qboolean CG_CalcFOVFromX( float fov_x ) return (inwater); } -float CG_ForceSpeedFOV( void ) -{ +float CG_ForceSpeedFOV(void) { float fov; float timeLeft = player->client->ps.forcePowerDuration[FP_SPEED] - cg.time; - float length = FORCE_SPEED_DURATION*forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; + float length = FORCE_SPEED_DURATION * forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; float amt = forceSpeedFOVMod[player->client->ps.forcePowerLevel[FP_SPEED]]; - if ( timeLeft < 500 ) - {//start going back - fov = cg_fov.value + (timeLeft)/500*amt; - } - else if ( length - timeLeft < 1000 ) - {//start zooming in - fov = cg_fov.value + (length - timeLeft)/1000*amt; - } - else - {//stay at this FOV - fov = cg_fov.value+amt; + if (timeLeft < 500) { // start going back + fov = cg_fov.value + (timeLeft) / 500 * amt; + } else if (length - timeLeft < 1000) { // start zooming in + fov = cg_fov.value + (length - timeLeft) / 1000 * amt; + } else { // stay at this FOV + fov = cg_fov.value + amt; } return fov; } @@ -1345,110 +1176,81 @@ CG_CalcFov Fixed fov at intermissions, otherwise account for fov variable and zooms. ==================== */ -static qboolean CG_CalcFov( void ) { - float fov_x; - float f; +static qboolean CG_CalcFov(void) { + float fov_x; + float f; - if ( cg.predicted_player_state.pm_type == PM_INTERMISSION ) { + if (cg.predicted_player_state.pm_type == PM_INTERMISSION) { // if in intermission, use a fixed value fov_x = 80; - } - else if ( cg.snap - && cg.snap->ps.viewEntity > 0 - && cg.snap->ps.viewEntity < ENTITYNUM_WORLD - && (!cg.renderingThirdPerson || g_entities[cg.snap->ps.viewEntity].e_DieFunc == dieF_camera_die) ) - { + } else if (cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && + (!cg.renderingThirdPerson || g_entities[cg.snap->ps.viewEntity].e_DieFunc == dieF_camera_die)) { // if in entity camera view, use a special FOV - if ( g_entities[cg.snap->ps.viewEntity].inuse && - g_entities[cg.snap->ps.viewEntity].NPC ) - {//FIXME: looks bad when take over a jedi... but never really do that, do we? + if (g_entities[cg.snap->ps.viewEntity].inuse && + g_entities[cg.snap->ps.viewEntity].NPC) { // FIXME: looks bad when take over a jedi... but never really do that, do we? fov_x = g_entities[cg.snap->ps.viewEntity].NPC->stats.hfov; - //sanity-cap? - if ( fov_x > 120 ) - { + // sanity-cap? + if (fov_x > 120) { fov_x = 120; - } - else if ( fov_x < 10 ) - { + } else if (fov_x < 10) { fov_x = 10; } - } - else - { - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + } else { + if (cg.overrides.active & CG_OVERRIDE_FOV) { fov_x = cg.overrides.fov; - } - else - { - fov_x = 120;//FIXME: read from the NPC's fov stats? + } else { + fov_x = 120; // FIXME: read from the NPC's fov stats? } } - } - else if ( (!cg.zoomMode || cg.zoomMode > 2) && (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] )//cg.renderingThirdPerson && + } else if ((!cg.zoomMode || cg.zoomMode > 2) && (cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && + player->client->ps.forcePowerDuration[FP_SPEED]) // cg.renderingThirdPerson && { fov_x = CG_ForceSpeedFOV(); } else { // user selectable - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + if (cg.overrides.active & CG_OVERRIDE_FOV) { fov_x = cg.overrides.fov; - } - else - { + } else { fov_x = cg_fov.value; } - if ( fov_x < 1 ) { + if (fov_x < 1) { fov_x = 1; - } else if ( fov_x > 160 ) { + } else if (fov_x > 160) { fov_x = 160; } // Disable zooming when in third person - if ( cg.zoomMode && cg.zoomMode < 3 )//&& !cg.renderingThirdPerson ) // light amp goggles do none of the zoom silliness + if (cg.zoomMode && cg.zoomMode < 3) //&& !cg.renderingThirdPerson ) // light amp goggles do none of the zoom silliness { - if ( !cg.zoomLocked ) - { - if ( cg.zoomMode == 1 ) - { + if (!cg.zoomLocked) { + if (cg.zoomMode == 1) { // binoculars zooming either in or out cg_zoomFov += cg.zoomDir * cg.frametime * 0.05f; - } - else - { + } else { // disruptor zooming in faster cg_zoomFov -= cg.frametime * 0.075f; } // Clamp zoomFov - float actualFOV = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - if ( cg_zoomFov < MAX_ZOOM_FOV ) - { + float actualFOV = (cg.overrides.active & CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + if (cg_zoomFov < MAX_ZOOM_FOV) { cg_zoomFov = MAX_ZOOM_FOV; - } - else if ( cg_zoomFov > actualFOV ) - { + } else if (cg_zoomFov > actualFOV) { cg_zoomFov = actualFOV; - } - else - {//still zooming + } else { // still zooming static int zoomSoundTime = 0; - if ( zoomSoundTime < cg.time ) - { + if (zoomSoundTime < cg.time) { sfxHandle_t snd; - if ( cg.zoomMode == 1 ) - { + if (cg.zoomMode == 1) { snd = cgs.media.zoomLoop; - } - else - { + } else { snd = cgs.media.disruptorZoomLoop; } // huh? This could probably just be added as a looping sound?? - cgi_S_StartSound( cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_LOCAL, snd ); + cgi_S_StartSound(cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_LOCAL, snd); zoomSoundTime = cg.time + 150; } } @@ -1456,57 +1258,54 @@ static qboolean CG_CalcFov( void ) { fov_x = cg_zoomFov; } else { - f = ( cg.time - cg.zoomTime ) / ZOOM_OUT_TIME; - if ( f <= 1.0 ) { - fov_x = cg_zoomFov + f * ( fov_x - cg_zoomFov ); + f = (cg.time - cg.zoomTime) / ZOOM_OUT_TIME; + if (f <= 1.0) { + fov_x = cg_zoomFov + f * (fov_x - cg_zoomFov); } } } -// g_fov = fov_x; - return ( CG_CalcFOVFromX( fov_x ) ); + // g_fov = fov_x; + return (CG_CalcFOVFromX(fov_x)); } - - /* =============== CG_DamageBlendBlob =============== */ -static void CG_DamageBlendBlob( void ) -{ - int t; - int maxTime; - refEntity_t ent; +static void CG_DamageBlendBlob(void) { + int t; + int maxTime; + refEntity_t ent; - if ( !cg.damageValue ) { + if (!cg.damageValue) { return; } maxTime = DAMAGE_TIME; t = cg.time - cg.damageTime; - if ( t <= 0 || t >= maxTime ) { + if (t <= 0 || t >= maxTime) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; ent.renderfx = RF_FIRST_PERSON; - VectorMA( cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin ); - VectorMA( ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin ); - VectorMA( ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin ); + VectorMA(cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin); + VectorMA(ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin); + VectorMA(ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin); - ent.radius = cg.damageValue * 3 * ( 1.0 - ((float)t / maxTime) ); + ent.radius = cg.damageValue * 3 * (1.0 - ((float)t / maxTime)); ent.customShader = cgs.media.damageBlendBlobShader; - ent.shaderRGBA[0] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[1] = 50 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[2] = 50 * ( 1.0 - ((float)t / maxTime) ); + ent.shaderRGBA[0] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[1] = 50 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[2] = 50 * (1.0 - ((float)t / maxTime)); ent.shaderRGBA[3] = 255; - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } /* @@ -1517,56 +1316,49 @@ CG_SaberClashFlare extern int g_saberFlashTime; extern vec3_t g_saberFlashPos; extern qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y); -void CG_SaberClashFlare( void ) -{ - int t, maxTime = 150; +void CG_SaberClashFlare(void) { + int t, maxTime = 150; t = cg.time - g_saberFlashTime; - if ( t <= 0 || t >= maxTime ) - { + if (t <= 0 || t >= maxTime) { return; } vec3_t dif; // Don't do clashes for things that are behind us - VectorSubtract( g_saberFlashPos, cg.refdef.vieworg, dif ); + VectorSubtract(g_saberFlashPos, cg.refdef.vieworg, dif); - if ( DotProduct( dif, cg.refdef.viewaxis[0] ) < 0.2 ) - { + if (DotProduct(dif, cg.refdef.viewaxis[0]) < 0.2) { return; } trace_t tr; - CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, g_saberFlashPos, -1, CONTENTS_SOLID ); + CG_Trace(&tr, cg.refdef.vieworg, NULL, NULL, g_saberFlashPos, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f ) - { + if (tr.fraction < 1.0f) { return; } vec3_t color; - int x,y; - float v, len = VectorNormalize( dif ); + int x, y; + float v, len = VectorNormalize(dif); // clamp to a known range - if ( len > 800 ) - { + if (len > 800) { len = 800; } - v = ( 1.0f - ((float)t / maxTime )) * ((1.0f - ( len / 800.0f )) * 2.0f + 0.35f); + v = (1.0f - ((float)t / maxTime)) * ((1.0f - (len / 800.0f)) * 2.0f + 0.35f); - CG_WorldCoordToScreenCoord( g_saberFlashPos, &x, &y ); + CG_WorldCoordToScreenCoord(g_saberFlashPos, &x, &y); - VectorSet( color, 0.8f, 0.8f, 0.8f ); - cgi_R_SetColor( color ); + VectorSet(color, 0.8f, 0.8f, 0.8f); + cgi_R_SetColor(color); - CG_DrawPic( x - ( v * 300 ), y - ( v * 300 ), - v * 600, v * 600, - cgi_R_RegisterShader( "gfx/effects/saberFlare" )); + CG_DrawPic(x - (v * 300), y - (v * 300), v * 600, v * 600, cgi_R_RegisterShader("gfx/effects/saberFlare")); } /* @@ -1576,54 +1368,45 @@ CG_CalcViewValues Sets cg.refdef view values =============== */ -static qboolean CG_CalcViewValues( void ) { - playerState_t *ps; - //qboolean viewEntIsHumanoid = qfalse; - qboolean viewEntIsCam = qfalse; +static qboolean CG_CalcViewValues(void) { + playerState_t *ps; + // qboolean viewEntIsHumanoid = qfalse; + qboolean viewEntIsCam = qfalse; - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); // calculate size of 3D view CG_CalcVrect(); - if( cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && - g_entities[cg.snap->ps.viewEntity].client) - { + if (cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && g_entities[cg.snap->ps.viewEntity].client) { ps = &g_entities[cg.snap->ps.viewEntity].client->ps; - //viewEntIsHumanoid = qtrue; - } - else - { + // viewEntIsHumanoid = qtrue; + } else { ps = &cg.predicted_player_state; } #ifndef FINAL_BUILD - trap_Com_SetOrgAngles(ps->origin,ps->viewangles); + trap_Com_SetOrgAngles(ps->origin, ps->viewangles); #endif // intermission view - if ( ps->pm_type == PM_INTERMISSION ) { - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + if (ps->pm_type == PM_INTERMISSION) { + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); return CG_CalcFov(); } - cg.bobcycle = ( ps->bobCycle & 128 ) >> 7; - cg.bobfracsin = fabs( sin( ( ps->bobCycle & 127 ) / 127.0 * M_PI ) ); - cg.xyspeed = sqrt( ps->velocity[0] * ps->velocity[0] + - ps->velocity[1] * ps->velocity[1] ); + cg.bobcycle = (ps->bobCycle & 128) >> 7; + cg.bobfracsin = fabs(sin((ps->bobCycle & 127) / 127.0 * M_PI)); + cg.xyspeed = sqrt(ps->velocity[0] * ps->velocity[0] + ps->velocity[1] * ps->velocity[1]); - if ( G_IsRidingVehicle( &g_entities[0] ) ) - { - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( cg_entities[g_entities[0].owner->s.number].lerpAngles, cg.refdefViewAngles ); - if ( !(ps->eFlags&EF_NODRAW) ) - {//riding it, not *inside* it - //let us look up & down + if (G_IsRidingVehicle(&g_entities[0])) { + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(cg_entities[g_entities[0].owner->s.number].lerpAngles, cg.refdefViewAngles); + if (!(ps->eFlags & EF_NODRAW)) { // riding it, not *inside* it + // let us look up & down cg.refdefViewAngles[PITCH] = cg_entities[ps->clientNum].lerpAngles[PITCH] * 0.2f; } - } - else if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view + } else if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in an entity camera view /* if ( g_entities[cg.snap->ps.viewEntity].client && cg.renderingThirdPerson ) { @@ -1631,100 +1414,80 @@ static qboolean CG_CalcViewValues( void ) { } else */ - { - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, cg.refdef.vieworg ); - } - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpAngles, cg.refdefViewAngles ); - if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname ) || g_entities[cg.snap->ps.viewEntity].s.weapon == WP_TURRET ) - { + { VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpOrigin, cg.refdef.vieworg); } + VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpAngles, cg.refdefViewAngles); + if (!Q_stricmp("misc_camera", g_entities[cg.snap->ps.viewEntity].classname) || g_entities[cg.snap->ps.viewEntity].s.weapon == WP_TURRET) { viewEntIsCam = qtrue; } - } - else if ( cg.renderingThirdPerson && !cg.zoomMode && (cg.overrides.active&CG_OVERRIDE_3RD_PERSON_ENT) ) - {//different center, same angle - VectorCopy( cg_entities[cg.overrides.thirdPersonEntity].lerpOrigin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); - } - else - {//player's center and angles - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); + } else if (cg.renderingThirdPerson && !cg.zoomMode && (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ENT)) { // different center, same angle + VectorCopy(cg_entities[cg.overrides.thirdPersonEntity].lerpOrigin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); + } else { // player's center and angles + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); } // add error decay - if ( cg_errorDecay.value > 0 ) { - int t; - float f; + if (cg_errorDecay.value > 0) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f > 0 && f < 1 ) { - VectorMA( cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg ); + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f > 0 && f < 1) { + VectorMA(cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg); } else { cg.predictedErrorTime = 0; } } - if ( (cg.renderingThirdPerson||cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) - && !cg.zoomMode - && !viewEntIsCam ) - { + if ((cg.renderingThirdPerson || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) && !cg.zoomMode && !viewEntIsCam) { // back away from character -// if ( cg_thirdPerson.integer == CG_CAM_ABOVE) -// { ` -// CG_OffsetThirdPersonOverheadView(); -// } -// else -// { + // if ( cg_thirdPerson.integer == CG_CAM_ABOVE) + // { ` + // CG_OffsetThirdPersonOverheadView(); + // } + // else + // { // First person saber - if ( !cg.renderingThirdPerson ) - { - if ( cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE ) - { + if (!cg.renderingThirdPerson) { + if (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) { vec3_t dir; - CG_OffsetFirstPersonView( qtrue ); + CG_OffsetFirstPersonView(qtrue); cg.refdef.vieworg[2] += 32; - AngleVectors( cg.refdefViewAngles, dir, NULL, NULL ); - VectorMA( cg.refdef.vieworg, -2, dir, cg.refdef.vieworg ); + AngleVectors(cg.refdefViewAngles, dir, NULL, NULL); + VectorMA(cg.refdef.vieworg, -2, dir, cg.refdef.vieworg); } } CG_OffsetThirdPersonView(); -// } - } - else - { + // } + } else { // offset for local bobbing and kicks - CG_OffsetFirstPersonView( qfalse ); - centity_t *playerCent = &cg_entities[0]; - if ( playerCent && playerCent->gent && playerCent->gent->client ) - { - VectorCopy( cg.refdef.vieworg, playerCent->gent->client->renderInfo.eyePoint ); - VectorCopy( cg.refdefViewAngles, playerCent->gent->client->renderInfo.eyeAngles ); - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view - if ( cg_entities[cg.snap->ps.viewEntity].gent->client ) - {//looking through a client's eyes - VectorCopy( cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyePoint ); - VectorCopy( cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyeAngles ); - } - else - {//looking through a regular ent's eyes - VectorCopy( cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].lerpOrigin ); - VectorCopy( cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].lerpAngles ); + CG_OffsetFirstPersonView(qfalse); + centity_t *playerCent = &cg_entities[0]; + if (playerCent && playerCent->gent && playerCent->gent->client) { + VectorCopy(cg.refdef.vieworg, playerCent->gent->client->renderInfo.eyePoint); + VectorCopy(cg.refdefViewAngles, playerCent->gent->client->renderInfo.eyeAngles); + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in an entity camera view + if (cg_entities[cg.snap->ps.viewEntity].gent->client) { // looking through a client's eyes + VectorCopy(cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyePoint); + VectorCopy(cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyeAngles); + } else { // looking through a regular ent's eyes + VectorCopy(cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].lerpOrigin); + VectorCopy(cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].lerpAngles); } } - VectorCopy( playerCent->gent->client->renderInfo.eyePoint, playerCent->gent->client->renderInfo.headPoint ); - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) - {//not in entity cam + VectorCopy(playerCent->gent->client->renderInfo.eyePoint, playerCent->gent->client->renderInfo.headPoint); + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // not in entity cam playerCent->gent->client->renderInfo.headPoint[2] -= 8; } } } - //VectorCopy( cg.refdef.vieworg, cgRefdefVieworg ); - // shake the camera if necessary - CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); - CGCam_UpdateShake( cg.refdef.vieworg, cg.refdefViewAngles ); + // VectorCopy( cg.refdef.vieworg, cgRefdefVieworg ); + // shake the camera if necessary + CGCam_UpdateSmooth(cg.refdef.vieworg, cg.refdefViewAngles); + CGCam_UpdateShake(cg.refdef.vieworg, cg.refdefViewAngles); /* if ( in_camera ) @@ -1734,18 +1497,16 @@ static qboolean CG_CalcViewValues( void ) { */ // see if we are drugged by an interrogator. We muck with the angles here, just a bit earlier, we mucked with the FOV - if ( cg.wonkyTime > 0 && cg.wonkyTime > cg.time ) - { + if (cg.wonkyTime > 0 && cg.wonkyTime > cg.time) { float perc = (float)(cg.wonkyTime - cg.time) / 10000.0f; // goes for 10 seconds - cg.refdefViewAngles[ROLL] += ( sin( cg.time * 0.0004f ) * 7.0f * perc ); - cg.refdefViewAngles[PITCH] += ( 26.0f * perc + sin( cg.time * 0.0011f ) * 3.0f * perc ); + cg.refdefViewAngles[ROLL] += (sin(cg.time * 0.0004f) * 7.0f * perc); + cg.refdefViewAngles[PITCH] += (26.0f * perc + sin(cg.time * 0.0011f) * 3.0f * perc); } - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); - if ( cg.hyperspace ) - { + if (cg.hyperspace) { cg.refdef.rdflags |= RDF_NOWORLDMODEL | RDF_HYPERSPACE; } @@ -1753,30 +1514,26 @@ static qboolean CG_CalcViewValues( void ) { return CG_CalcFov(); } - /* ===================== CG_PowerupTimerSounds ===================== */ -static void CG_PowerupTimerSounds( void ) -{ - int i, time; +static void CG_PowerupTimerSounds(void) { + int i, time; // powerup timers going away - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) - { + for (i = 0; i < MAX_POWERUPS; i++) { time = cg.snap->ps.powerups[i]; - if ( time > 0 && time < cg.time ) - { + if (time > 0 && time < cg.time) { // add any special powerup expiration sounds here -// switch( i ) -// { -// case PW_WEAPON_OVERCHARGE: -// cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.overchargeEndSound ); -// break; -// } + // switch( i ) + // { + // case PW_WEAPON_OVERCHARGE: + // cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.overchargeEndSound ); + // break; + // } } } } @@ -1786,18 +1543,16 @@ static void CG_PowerupTimerSounds( void ) CG_DrawSkyBoxPortal ============== */ -extern void cgi_CM_SnapPVS(vec3_t origin,byte *buffer); +extern void cgi_CM_SnapPVS(vec3_t origin, byte *buffer); -static void CG_DrawSkyBoxPortal(void) -{ +static void CG_DrawSkyBoxPortal(void) { refdef_t backuprefdef; const char *cstr; char *token; cstr = CG_ConfigString(CS_SKYBOXORG); - if (!cstr || !strlen(cstr)) - { + if (!cstr || !strlen(cstr)) { // no skybox in this map return; } @@ -1807,171 +1562,157 @@ static void CG_DrawSkyBoxPortal(void) // asdf --eez COM_BeginParseSession(); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[0] = atof(token); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[1] = atof(token); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[2] = atof(token); // setup fog the first time, ignore this part of the configstring after that token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog state\n"); - } - else - { - if ( atoi( token ) ) { + if (!token || !token[0]) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog state\n"); + } else { + if (atoi(token)) { // this camera has fog - token = COM_ParseExt( &cstr, qfalse ); - if ( !VALIDSTRING( token ) ) { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[0]\n"); + token = COM_ParseExt(&cstr, qfalse); + if (!VALIDSTRING(token)) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[0]\n"); } token = COM_ParseExt(&cstr, qfalse); - if ( !VALIDSTRING( token ) ) { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[1]\n"); + if (!VALIDSTRING(token)) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[1]\n"); } token = COM_ParseExt(&cstr, qfalse); - if ( !VALIDSTRING( token ) ) { - CG_Error( "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[2]\n"); + if (!VALIDSTRING(token)) { + CG_Error("CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog[2]\n"); } - COM_ParseExt( &cstr, qfalse ); - COM_ParseExt( &cstr, qfalse ); + COM_ParseExt(&cstr, qfalse); + COM_ParseExt(&cstr, qfalse); } } COM_EndParseSession(); -/* - static float lastfov = cg_zoomFov; // for transitions back from zoomed in modes - float fov_x; - float fov_y; - float x; - float f = 0; + /* + static float lastfov = cg_zoomFov; // for transitions back from zoomed in modes + float fov_x; + float fov_y; + float x; + float f = 0; - if ( cg.predicted_player_state.pm_type == PM_INTERMISSION ) - { - // if in intermission, use a fixed value - fov_x = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - } - else - { - if (cg.zoomMode) + if ( cg.predicted_player_state.pm_type == PM_INTERMISSION ) { - fov_x = cg_zoomFov; + // if in intermission, use a fixed value + fov_x = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; } else { - fov_x = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - if ( fov_x < 1 ) + if (cg.zoomMode) { - fov_x = 1; + fov_x = cg_zoomFov; } - else if ( fov_x > 160 ) + else { - fov_x = 160; + fov_x = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + if ( fov_x < 1 ) + { + fov_x = 1; + } + else if ( fov_x > 160 ) + { + fov_x = 160; + } } - } - // do smooth transitions for zooming - if (cg.zoomMode) - { //zoomed/zooming in - f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; - if ( f > 1.0 ) { - fov_x = cg_zoomFov; - } else { - fov_x = fov_x + f * ( cg_zoomFov - fov_x ); + // do smooth transitions for zooming + if (cg.zoomMode) + { //zoomed/zooming in + f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; + if ( f > 1.0 ) { + fov_x = cg_zoomFov; + } else { + fov_x = fov_x + f * ( cg_zoomFov - fov_x ); + } + lastfov = fov_x; } - lastfov = fov_x; - } - else - { //zooming out - f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; - if ( f > 1.0 ) { - fov_x = fov_x; - } else { - fov_x = cg_zoomFov + f * ( fov_x - cg_zoomFov); + else + { //zooming out + f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; + if ( f > 1.0 ) { + fov_x = fov_x; + } else { + fov_x = cg_zoomFov + f * ( fov_x - cg_zoomFov); + } } } - } - x = cg.refdef.width / tan( fov_x / 360 * M_PI ); - fov_y = atan2( cg.refdef.height, x ); - fov_y = fov_y * 360 / M_PI; + x = cg.refdef.width / tan( fov_x / 360 * M_PI ); + fov_y = atan2( cg.refdef.height, x ); + fov_y = fov_y * 360 / M_PI; - cg.refdef.fov_x = fov_x; - cg.refdef.fov_y = fov_y; -*/ - //inherit fov and axis from whatever the player is doing (regular, camera overrides or zoomed, whatever) - if ( !cg.hyperspace ) - { - CG_AddPacketEntities(qtrue); //rww - There was no proper way to put real entities inside the portal view before. - //This will put specially flagged entities in the render. - //Add effects flagged to play only in portals - theFxScheduler.AddScheduledEffects( true ); + cg.refdef.fov_x = fov_x; + cg.refdef.fov_y = fov_y; + */ + // inherit fov and axis from whatever the player is doing (regular, camera overrides or zoomed, whatever) + if (!cg.hyperspace) { + CG_AddPacketEntities(qtrue); // rww - There was no proper way to put real entities inside the portal view before. + // This will put specially flagged entities in the render. + // Add effects flagged to play only in portals + theFxScheduler.AddScheduledEffects(true); } - cg.refdef.rdflags |= RDF_SKYBOXPORTAL; //mark portal scene specialness - cg.refdef.rdflags |= RDF_DRAWSKYBOX; //drawk portal skies + cg.refdef.rdflags |= RDF_SKYBOXPORTAL; // mark portal scene specialness + cg.refdef.rdflags |= RDF_DRAWSKYBOX; // drawk portal skies - cgi_CM_SnapPVS( cg.refdef.vieworg, cg.refdef.areamask ); //fill in my areamask for this view origin + cgi_CM_SnapPVS(cg.refdef.vieworg, cg.refdef.areamask); // fill in my areamask for this view origin // draw the skybox - cgi_R_RenderScene( &cg.refdef ); + cgi_R_RenderScene(&cg.refdef); cg.refdef = backuprefdef; } //---------------------------- -void CG_RunEmplacedWeapon() -{ - gentity_t *player = &g_entities[0], - *gun = player->owner; +void CG_RunEmplacedWeapon() { + gentity_t *player = &g_entities[0], *gun = player->owner; // Override the camera when we are locked onto the gun. - if ( player - && gun - && !gun->bounceCount//not an eweb - && ( player->s.eFlags & EF_LOCKED_TO_WEAPON )) - { -// float dist = -1; // default distance behind gun + if (player && gun && !gun->bounceCount // not an eweb + && (player->s.eFlags & EF_LOCKED_TO_WEAPON)) { + // float dist = -1; // default distance behind gun // don't let the player try and change this cg.renderingThirdPerson = qtrue; -// cg.refdefViewAngles[PITCH] += cg.overrides.thirdPersonPitchOffset? cg.overrides.thirdPersonPitchOffset: cg_thirdPersonPitchOffset.value; -// cg.refdefViewAngles[YAW] += cg.overrides.thirdPersonAngle ? cg.overrides.thirdPersonAngle : cg_thirdPersonAngle.value;; + // cg.refdefViewAngles[PITCH] += cg.overrides.thirdPersonPitchOffset? cg.overrides.thirdPersonPitchOffset: cg_thirdPersonPitchOffset.value; + // cg.refdefViewAngles[YAW] += cg.overrides.thirdPersonAngle ? cg.overrides.thirdPersonAngle : cg_thirdPersonAngle.value;; - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); // Slide in behind the gun. -// if ( gun->delay + 500 > cg.time ) -// { -// dist -= (( gun->delay + 500 ) - cg.time ) * 0.02f; -// } - - VectorCopy( gun->pos2, cg.refdef.vieworg ); - VectorMA( cg.refdef.vieworg, -20.0f, gun->pos3, cg.refdef.vieworg ); - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) - { - VectorMA( cg.refdef.vieworg, 35.0f, gun->pos4, cg.refdef.vieworg ); + // if ( gun->delay + 500 > cg.time ) + // { + // dist -= (( gun->delay + 500 ) - cg.time ) * 0.02f; + // } + + VectorCopy(gun->pos2, cg.refdef.vieworg); + VectorMA(cg.refdef.vieworg, -20.0f, gun->pos3, cg.refdef.vieworg); + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { + VectorMA(cg.refdef.vieworg, 35.0f, gun->pos4, cg.refdef.vieworg); } - } } @@ -1984,12 +1725,12 @@ CG_DrawActiveFrame Generates and draws a game scene and status information at the given time. ================= */ -extern void CG_BuildSolidList( void ); -extern void CG_ClearHealthBarEnts( void ); -extern vec3_t serverViewOrg; -static qboolean cg_rangedFogging = qfalse; //so we know if we should go back to normal fog -void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { - qboolean inwater = qfalse; +extern void CG_BuildSolidList(void); +extern void CG_ClearHealthBarEnts(void); +extern vec3_t serverViewOrg; +static qboolean cg_rangedFogging = qfalse; // so we know if we should go back to normal fog +void CG_DrawActiveFrame(int serverTime, stereoFrame_t stereoView) { + qboolean inwater = qfalse; cg.time = serverTime; @@ -1998,7 +1739,7 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { // if we are only updating the screen as a loading // pacifier, don't even try to read snapshots - if ( cg.infoScreenText[0] != 0 ) { + if (cg.infoScreenText[0] != 0) { CG_DrawInformation(); return; } @@ -2020,61 +1761,55 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { CG_ProcessSnapshots(); // if we haven't received any snapshots yet, all // we can draw is the information screen - if ( !cg.snap ) { - //CG_DrawInformation(); + if (!cg.snap) { + // CG_DrawInformation(); return; } // make sure the lagometerSample and frame timing isn't done twice when in stereo - if ( stereoView != STEREO_RIGHT ) { + if (stereoView != STEREO_RIGHT) { cg.frametime = cg.time - cg.oldTime; cg.oldTime = cg.time; } // Make sure the helper has the updated time - theFxHelper.AdjustTime( cg.frametime ); + theFxHelper.AdjustTime(cg.frametime); // let the client system know what our weapon and zoom settings are - //FIXME: should really send forcePowersActive over network onto cg.snap->ps... + // FIXME: should really send forcePowersActive over network onto cg.snap->ps... const int fpActive = cg_entities[0].gent->client->ps.forcePowersActive; const bool matrixMode = !!(fpActive & ((1 << FP_SPEED) | (1 << FP_RAGE))); float speed = cg.refdef.fov_y / 75.0 * (matrixMode ? 1.0f : cg_timescale.value); -//FIXME: junk code, BUG:168 + // FIXME: junk code, BUG:168 - static bool wasForceSpeed=false; - bool isForceSpeed=cg_entities[0].gent->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_SPEED) ? true : false; + if (isForceSpeed && !wasForceSpeed) { + CGCam_Smooth(0.75f, 5000); } - wasForceSpeed=isForceSpeed; + wasForceSpeed = isForceSpeed; -// + // float mPitchOverride = 0.0f; float mYawOverride = 0.0f; - if ( cg.snap->ps.clientNum == 0 && cg_scaleVehicleSensitivity.integer ) - {//pointless check, but.. - if ( cg_entities[0].gent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.clientNum == 0 && cg_scaleVehicleSensitivity.integer) { // pointless check, but.. + if (cg_entities[0].gent->s.eFlags & EF_LOCKED_TO_WEAPON) { speed *= 0.25f; } Vehicle_t *pVeh = NULL; // Mouse turns slower. - if ( ( pVeh = G_IsRidingVehicle( &g_entities[0] ) ) != NULL ) - { - if ( pVeh->m_pVehicleInfo->mousePitch ) - { + if ((pVeh = G_IsRidingVehicle(&g_entities[0])) != NULL) { + if (pVeh->m_pVehicleInfo->mousePitch) { mPitchOverride = pVeh->m_pVehicleInfo->mousePitch; } - if ( pVeh->m_pVehicleInfo->mouseYaw ) - { + if (pVeh->m_pVehicleInfo->mouseYaw) { mYawOverride = pVeh->m_pVehicleInfo->mouseYaw; } } } - cgi_SetUserCmdValue( cg.weaponSelect, speed, mPitchOverride, mYawOverride ); + cgi_SetUserCmdValue(cg.weaponSelect, speed, mPitchOverride, mYawOverride); // this counter will be bumped for every valid scene we generate cg.clientFrame++; @@ -2082,45 +1817,34 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { // update cg.predicted_player_state CG_PredictPlayerState(); - if (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - { + if (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE) { cg.zoomMode = 0; } // decide on third person view - cg.renderingThirdPerson = (qboolean)( - cg_thirdPerson.integer - || (cg.snap->ps.stats[STAT_HEALTH] <= 0) - || (cg.snap->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - || ((g_entities[0].client&&g_entities[0].client->NPC_class==CLASS_ATST) - || (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) )); - - if ( cg.zoomMode ) - { + cg.renderingThirdPerson = (qboolean)(cg_thirdPerson.integer || (cg.snap->ps.stats[STAT_HEALTH] <= 0) || (cg.snap->ps.eFlags & EF_HELD_BY_SAND_CREATURE) || + ((g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) || + (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE))); + + if (cg.zoomMode) { // zoomed characters should never do third person stuff?? cg.renderingThirdPerson = qfalse; } - if ( in_camera ) - { + if (in_camera) { // The camera takes over the view CGCam_RenderScene(); - } - else - { - //Finish any fading that was happening + } else { + // Finish any fading that was happening CGCam_UpdateFade(); // build cg.refdef inwater = CG_CalcViewValues(); } - if (cg.zoomMode) - { //zooming with binoculars or sniper, set the fog range based on the zoom level -rww + if (cg.zoomMode) { // zooming with binoculars or sniper, set the fog range based on the zoom level -rww cg_rangedFogging = qtrue; - //smaller the fov the less fog we have between the view and cull dist - cgi_R_SetRangeFog(cg.refdef.fov_x*64.0f); - } - else if (cg_rangedFogging) - { //disable it + // smaller the fov the less fog we have between the view and cull dist + cgi_R_SetRangeFog(cg.refdef.fov_x * 64.0f); + } else if (cg_rangedFogging) { // disable it cg_rangedFogging = qfalse; cgi_R_SetRangeFog(0.0f); } @@ -2133,41 +1857,35 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { CG_RunEmplacedWeapon(); // first person blend blobs, done after AnglesToAxis - if ( !cg.renderingThirdPerson ) { + if (!cg.renderingThirdPerson) { CG_DamageBlendBlob(); } // build the render lists - if ( !cg.hyperspace ) { - CG_AddPacketEntities(qfalse); // adter calcViewValues, so predicted player state is correct + if (!cg.hyperspace) { + CG_AddPacketEntities(qfalse); // adter calcViewValues, so predicted player state is correct CG_AddMarks(); CG_AddLocalEntities(); CG_DrawMiscEnts(); } - //check for opaque water - // this game does not have opaque water - if ( 0 ) - { - vec3_t camTest; - VectorCopy( cg.refdef.vieworg, camTest ); + // check for opaque water + // this game does not have opaque water + if (0) { + vec3_t camTest; + VectorCopy(cg.refdef.vieworg, camTest); camTest[2] += 6; - if ( !(CG_PointContents( camTest, 0 )&CONTENTS_SOLID) && !gi.inPVS( cg.refdef.vieworg, camTest ) ) - {//crossed visible line into another room + if (!(CG_PointContents(camTest, 0) & CONTENTS_SOLID) && !gi.inPVS(cg.refdef.vieworg, camTest)) { // crossed visible line into another room cg.refdef.vieworg[2] -= 6; - //cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); - } - else - { - VectorCopy( cg.refdef.vieworg, camTest ); + // cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); + } else { + VectorCopy(cg.refdef.vieworg, camTest); camTest[2] -= 6; - if ( !(CG_PointContents( camTest, 0 )&CONTENTS_SOLID) && !gi.inPVS( cg.refdef.vieworg, camTest ) ) - { + if (!(CG_PointContents(camTest, 0) & CONTENTS_SOLID) && !gi.inPVS(cg.refdef.vieworg, camTest)) { cg.refdef.vieworg[2] += 6; - //cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); - } - else //if ( inwater ) - {//extra-special hack... sometimes when crouched in water with first person lightsaber, your PVS is wrong??? + // cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); + } else // if ( inwater ) + { // extra-special hack... sometimes when crouched in water with first person lightsaber, your PVS is wrong??? /* if ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) ) {//pseudo first-person for saber and fists @@ -2177,46 +1895,38 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { } } } - //FIXME: first person crouch-uncrouch STILL FUCKS UP THE AREAMASK!!! - //if ( !VectorCompare2( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) && !gi.inPVS( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) ) - {//actual view org and server's view org don't match and aren't same PVS, rebuild the areamask - //Com_Printf( S_COLOR_RED"%s != %s\n", vtos(cg.refdef.vieworg), vtos(cg.snap->ps.serverViewOrg) ); - cgi_CM_SnapPVS( cg.refdef.vieworg, cg.snap->areamask ); + // FIXME: first person crouch-uncrouch STILL FUCKS UP THE AREAMASK!!! + // if ( !VectorCompare2( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) && !gi.inPVS( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) ) + { // actual view org and server's view org don't match and aren't same PVS, rebuild the areamask + // Com_Printf( S_COLOR_RED"%s != %s\n", vtos(cg.refdef.vieworg), vtos(cg.snap->ps.serverViewOrg) ); + cgi_CM_SnapPVS(cg.refdef.vieworg, cg.snap->areamask); } // Don't draw the in-view weapon when in camera mode - if ( !in_camera - && !cg_pano.integer - && cg.snap->ps.weapon != WP_SABER - && ( cg.snap->ps.viewEntity == 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) ) - { - CG_AddViewWeapon( &cg.predicted_player_state ); - } - else if( cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if( g_entities[cg.snap->ps.viewEntity].client && g_entities[cg.snap->ps.viewEntity].NPC ) - { - CG_AddViewWeapon( &g_entities[cg.snap->ps.viewEntity ].client->ps ); // HAX - because I wanted to --eez + if (!in_camera && !cg_pano.integer && cg.snap->ps.weapon != WP_SABER && (cg.snap->ps.viewEntity == 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD)) { + CG_AddViewWeapon(&cg.predicted_player_state); + } else if (cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (g_entities[cg.snap->ps.viewEntity].client && g_entities[cg.snap->ps.viewEntity].NPC) { + CG_AddViewWeapon(&g_entities[cg.snap->ps.viewEntity].client->ps); // HAX - because I wanted to --eez } } - if ( !cg.hyperspace && fx_freeze.integer<2 ) - { - //Add all effects - theFxScheduler.AddScheduledEffects( false ); + if (!cg.hyperspace && fx_freeze.integer < 2) { + // Add all effects + theFxScheduler.AddScheduledEffects(false); } // finish up the rest of the refdef - if ( cg.testModelEntity.hModel ) { + if (cg.testModelEntity.hModel) { CG_AddTestModel(); } - memcpy( cg.refdef.areamask, cg.snap->areamask, sizeof( cg.refdef.areamask ) ); + memcpy(cg.refdef.areamask, cg.snap->areamask, sizeof(cg.refdef.areamask)); // update audio positions - //This is done from the vieworg to get origin for non-attenuated sounds - cgi_S_UpdateAmbientSet( CG_ConfigString( CS_AMBIENT_SET ), cg.refdef.vieworg ); - //NOTE: if we want to make you be able to hear far away sounds with electrobinoculars, add the hacked-in positional offset here (base on fov) + // This is done from the vieworg to get origin for non-attenuated sounds + cgi_S_UpdateAmbientSet(CG_ConfigString(CS_AMBIENT_SET), cg.refdef.vieworg); + // NOTE: if we want to make you be able to hear far away sounds with electrobinoculars, add the hacked-in positional offset here (base on fov) /* vec3_t listener_origin; VectorCopy( cg.refdef.vieworg, listener_origin ); @@ -2237,21 +1947,21 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { } cgi_S_Respatialize( cg.snap->ps.clientNum, listener_origin, cg.refdef.viewaxis, inwater ); */ - cgi_S_Respatialize( cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater ); + cgi_S_Respatialize(cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater); // warning sounds when powerup is wearing off CG_PowerupTimerSounds(); - if ( cg_pano.integer ) { // let's grab a panorama! - cg.levelShot = qtrue; //hide the 2d + if (cg_pano.integer) { // let's grab a panorama! + cg.levelShot = qtrue; // hide the 2d VectorClear(cg.refdefViewAngles); - cg.refdefViewAngles[YAW] = -360 * cg_pano.integer/cg_panoNumShots.integer; //choose angle - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); - CG_DrawActive( stereoView ); + cg.refdefViewAngles[YAW] = -360 * cg_pano.integer / cg_panoNumShots.integer; // choose angle + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); + CG_DrawActive(stereoView); cg.levelShot = qfalse; - } else { + } else { // actually issue the rendering calls - CG_DrawActive( stereoView ); + CG_DrawActive(stereoView); } /* if ( in_camera && !cg_skippingcin.integer ) @@ -2260,4 +1970,3 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { } */ } - diff --git a/code/cgame/cg_weapons.cpp b/code/cgame/cg_weapons.cpp index dc90ee497e..f854097780 100644 --- a/code/cgame/cg_weapons.cpp +++ b/code/cgame/cg_weapons.cpp @@ -30,13 +30,11 @@ along with this program; if not, see . #include "../game/anims.h" -extern void CG_LightningBolt( centity_t *cent, vec3_t origin ); +extern void CG_LightningBolt(centity_t *cent, vec3_t origin); -#define PHASER_HOLDFRAME 2 -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color); +#define PHASER_HOLDFRAME 2 +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color); /* ================= @@ -45,227 +43,212 @@ CG_RegisterWeapon The server says this item is used on this level ================= */ -void CG_RegisterWeapon( int weaponNum ) { - weaponInfo_t *weaponInfo; - gitem_t *item, *ammo; - char path[MAX_QPATH]; - vec3_t mins, maxs; - int i; +void CG_RegisterWeapon(int weaponNum) { + weaponInfo_t *weaponInfo; + gitem_t *item, *ammo; + char path[MAX_QPATH]; + vec3_t mins, maxs; + int i; weaponInfo = &cg_weapons[weaponNum]; // error checking - if ( weaponNum == 0 ) { + if (weaponNum == 0) { return; } - if ( weaponInfo->registered ) { + if (weaponInfo->registered) { return; } // clear out the memory we use - memset( weaponInfo, 0, sizeof( *weaponInfo ) ); + memset(weaponInfo, 0, sizeof(*weaponInfo)); weaponInfo->registered = qtrue; // find the weapon in the item list - for ( item = bg_itemlist + 1 ; item->classname ; item++ ) { - if ( item->giType == IT_WEAPON && item->giTag == weaponNum ) { + for (item = bg_itemlist + 1; item->classname; item++) { + if (item->giType == IT_WEAPON && item->giTag == weaponNum) { weaponInfo->item = item; break; } } // if we couldn't find which weapon this is, give us an error - if ( !item->classname ) { - CG_Error( "Couldn't find item for weapon %s\nNeed to update Items.dat!", weaponData[weaponNum].classname); + if (!item->classname) { + CG_Error("Couldn't find item for weapon %s\nNeed to update Items.dat!", weaponData[weaponNum].classname); } - CG_RegisterItemVisuals( item - bg_itemlist ); + CG_RegisterItemVisuals(item - bg_itemlist); // set up in view weapon model - weaponInfo->weaponModel = cgi_R_RegisterModel( weaponData[weaponNum].weaponMdl ); - {//in case the weaponmodel isn't _w, precache the _w.glm + weaponInfo->weaponModel = cgi_R_RegisterModel(weaponData[weaponNum].weaponMdl); + { // in case the weaponmodel isn't _w, precache the _w.glm char weaponModel[64]; - Q_strncpyz (weaponModel, weaponData[weaponNum].weaponMdl, sizeof(weaponModel)); - if (char *spot = strstr(weaponModel, ".md3") ) - { + Q_strncpyz(weaponModel, weaponData[weaponNum].weaponMdl, sizeof(weaponModel)); + if (char *spot = strstr(weaponModel, ".md3")) { *spot = 0; - spot = strstr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on - if (!spot) - { - Q_strcat (weaponModel, sizeof(weaponModel), "_w"); + spot = strstr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on + if (!spot) { + Q_strcat(weaponModel, sizeof(weaponModel), "_w"); } - Q_strcat (weaponModel, sizeof(weaponModel), ".glm"); //and change to ghoul2 + Q_strcat(weaponModel, sizeof(weaponModel), ".glm"); // and change to ghoul2 } - gi.G2API_PrecacheGhoul2Model( weaponModel ); // correct way is item->world_model + gi.G2API_PrecacheGhoul2Model(weaponModel); // correct way is item->world_model } - if ( weaponInfo->weaponModel == 0 ) - { - CG_Error( "Couldn't find weapon model %s for weapon %s\n", weaponData[weaponNum].weaponMdl, weaponData[weaponNum].classname); + if (weaponInfo->weaponModel == 0) { + CG_Error("Couldn't find weapon model %s for weapon %s\n", weaponData[weaponNum].weaponMdl, weaponData[weaponNum].classname); return; } // calc midpoint for rotation - cgi_R_ModelBounds( weaponInfo->weaponModel, mins, maxs ); - for ( i = 0 ; i < 3 ; i++ ) { - weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * ( maxs[i] - mins[i] ); + cgi_R_ModelBounds(weaponInfo->weaponModel, mins, maxs); + for (i = 0; i < 3; i++) { + weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * (maxs[i] - mins[i]); } // setup the shader we will use for the icon - if (weaponData[weaponNum].weaponIcon[0]) - { - weaponInfo->weaponIcon = cgi_R_RegisterShaderNoMip( weaponData[weaponNum].weaponIcon); - weaponInfo->weaponIconNoAmmo = cgi_R_RegisterShaderNoMip( va("%s_na",weaponData[weaponNum].weaponIcon)); + if (weaponData[weaponNum].weaponIcon[0]) { + weaponInfo->weaponIcon = cgi_R_RegisterShaderNoMip(weaponData[weaponNum].weaponIcon); + weaponInfo->weaponIconNoAmmo = cgi_R_RegisterShaderNoMip(va("%s_na", weaponData[weaponNum].weaponIcon)); } - for ( ammo = bg_itemlist + 1 ; ammo->classname ; ammo++ ) { - if ( ammo->giType == IT_AMMO && ammo->giTag == weaponData[weaponNum].ammoIndex) { + for (ammo = bg_itemlist + 1; ammo->classname; ammo++) { + if (ammo->giType == IT_AMMO && ammo->giTag == weaponData[weaponNum].ammoIndex) { break; } } - if ( ammo->classname && ammo->world_model ) { - weaponInfo->ammoModel = cgi_R_RegisterModel( ammo->world_model ); + if (ammo->classname && ammo->world_model) { + weaponInfo->ammoModel = cgi_R_RegisterModel(ammo->world_model); } - for (i=0; i< weaponData[weaponNum].numBarrels; i++) { - Q_strncpyz( path, weaponData[weaponNum].weaponMdl, sizeof(path) ); - COM_StripExtension( path, path, sizeof(path) ); - if (i) - { - //char crap[50]; - //Com_sprintf(crap, sizeof(crap), "_barrel%d.md3", i+1 ); - //strcat ( path, crap ); - Q_strcat( path, sizeof(path), va("_barrel%d.md3", i+1) ); - } - else - Q_strcat( path, sizeof(path), "_barrel.md3" ); - weaponInfo->barrelModel[i] = cgi_R_RegisterModel( path ); + for (i = 0; i < weaponData[weaponNum].numBarrels; i++) { + Q_strncpyz(path, weaponData[weaponNum].weaponMdl, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + if (i) { + // char crap[50]; + // Com_sprintf(crap, sizeof(crap), "_barrel%d.md3", i+1 ); + // strcat ( path, crap ); + Q_strcat(path, sizeof(path), va("_barrel%d.md3", i + 1)); + } else + Q_strcat(path, sizeof(path), "_barrel.md3"); + weaponInfo->barrelModel[i] = cgi_R_RegisterModel(path); } - // set up the world model for the weapon - weaponInfo->weaponWorldModel = cgi_R_RegisterModel( item->world_model ); - if ( !weaponInfo->weaponWorldModel) { + weaponInfo->weaponWorldModel = cgi_R_RegisterModel(item->world_model); + if (!weaponInfo->weaponWorldModel) { weaponInfo->weaponWorldModel = weaponInfo->weaponModel; } // set up the hand that holds the in view weapon - assuming we have one - Q_strncpyz( path, weaponData[weaponNum].weaponMdl, sizeof(path) ); - COM_StripExtension( path, path, sizeof(path) ); - Q_strcat( path, sizeof(path), "_hand.md3" ); - weaponInfo->handsModel = cgi_R_RegisterModel( path ); + Q_strncpyz(path, weaponData[weaponNum].weaponMdl, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + Q_strcat(path, sizeof(path), "_hand.md3"); + weaponInfo->handsModel = cgi_R_RegisterModel(path); - if ( !weaponInfo->handsModel ) { - weaponInfo->handsModel = cgi_R_RegisterModel( "models/weapons2/briar_pistol/briar_pistol_hand.md3" ); + if (!weaponInfo->handsModel) { + weaponInfo->handsModel = cgi_R_RegisterModel("models/weapons2/briar_pistol/briar_pistol_hand.md3"); } // register the sounds for the weapon if (weaponData[weaponNum].firingSnd[0]) { - weaponInfo->firingSound = cgi_S_RegisterSound( weaponData[weaponNum].firingSnd ); + weaponInfo->firingSound = cgi_S_RegisterSound(weaponData[weaponNum].firingSnd); } if (weaponData[weaponNum].altFiringSnd[0]) { - weaponInfo->altFiringSound = cgi_S_RegisterSound( weaponData[weaponNum].altFiringSnd ); + weaponInfo->altFiringSound = cgi_S_RegisterSound(weaponData[weaponNum].altFiringSnd); } if (weaponData[weaponNum].stopSnd[0]) { - weaponInfo->stopSound = cgi_S_RegisterSound( weaponData[weaponNum].stopSnd ); + weaponInfo->stopSound = cgi_S_RegisterSound(weaponData[weaponNum].stopSnd); } if (weaponData[weaponNum].chargeSnd[0]) { - weaponInfo->chargeSound = cgi_S_RegisterSound( weaponData[weaponNum].chargeSnd ); + weaponInfo->chargeSound = cgi_S_RegisterSound(weaponData[weaponNum].chargeSnd); } if (weaponData[weaponNum].altChargeSnd[0]) { - weaponInfo->altChargeSound = cgi_S_RegisterSound( weaponData[weaponNum].altChargeSnd ); + weaponInfo->altChargeSound = cgi_S_RegisterSound(weaponData[weaponNum].altChargeSnd); } if (weaponData[weaponNum].selectSnd[0]) { - weaponInfo->selectSound = cgi_S_RegisterSound( weaponData[weaponNum].selectSnd ); + weaponInfo->selectSound = cgi_S_RegisterSound(weaponData[weaponNum].selectSnd); } // give us missile models if we should - if (weaponData[weaponNum].missileMdl[0]) { - weaponInfo->missileModel = cgi_R_RegisterModel(weaponData[weaponNum].missileMdl ); + if (weaponData[weaponNum].missileMdl[0]) { + weaponInfo->missileModel = cgi_R_RegisterModel(weaponData[weaponNum].missileMdl); } - if (weaponData[weaponNum].alt_missileMdl[0]) { - weaponInfo->alt_missileModel = cgi_R_RegisterModel(weaponData[weaponNum].alt_missileMdl ); + if (weaponData[weaponNum].alt_missileMdl[0]) { + weaponInfo->alt_missileModel = cgi_R_RegisterModel(weaponData[weaponNum].alt_missileMdl); } if (weaponData[weaponNum].missileSound[0]) { - weaponInfo->missileSound = cgi_S_RegisterSound( weaponData[weaponNum].missileSound ); + weaponInfo->missileSound = cgi_S_RegisterSound(weaponData[weaponNum].missileSound); } if (weaponData[weaponNum].alt_missileSound[0]) { - weaponInfo->alt_missileSound = cgi_S_RegisterSound( weaponData[weaponNum].alt_missileSound ); + weaponInfo->alt_missileSound = cgi_S_RegisterSound(weaponData[weaponNum].alt_missileSound); } if (weaponData[weaponNum].missileHitSound[0]) { - weaponInfo->missileHitSound = cgi_S_RegisterSound( weaponData[weaponNum].missileHitSound ); + weaponInfo->missileHitSound = cgi_S_RegisterSound(weaponData[weaponNum].missileHitSound); } if (weaponData[weaponNum].altmissileHitSound[0]) { - weaponInfo->altmissileHitSound = cgi_S_RegisterSound( weaponData[weaponNum].altmissileHitSound ); + weaponInfo->altmissileHitSound = cgi_S_RegisterSound(weaponData[weaponNum].altmissileHitSound); } - if ( weaponData[weaponNum].mMuzzleEffect[0] ) - { - weaponData[weaponNum].mMuzzleEffectID = theFxScheduler.RegisterEffect( weaponData[weaponNum].mMuzzleEffect ); + if (weaponData[weaponNum].mMuzzleEffect[0]) { + weaponData[weaponNum].mMuzzleEffectID = theFxScheduler.RegisterEffect(weaponData[weaponNum].mMuzzleEffect); } - if ( weaponData[weaponNum].mAltMuzzleEffect[0] ) - { - weaponData[weaponNum].mAltMuzzleEffectID = theFxScheduler.RegisterEffect( weaponData[weaponNum].mAltMuzzleEffect ); + if (weaponData[weaponNum].mAltMuzzleEffect[0]) { + weaponData[weaponNum].mAltMuzzleEffectID = theFxScheduler.RegisterEffect(weaponData[weaponNum].mAltMuzzleEffect); } - //fixme: don't really need to copy these, should just use directly - // give ourselves the functions if we can - if (weaponData[weaponNum].func) - { - weaponInfo->missileTrailFunc = (void (*)(struct centity_s *,const struct weaponInfo_s *))weaponData[weaponNum].func; + // fixme: don't really need to copy these, should just use directly + // give ourselves the functions if we can + if (weaponData[weaponNum].func) { + weaponInfo->missileTrailFunc = (void (*)(struct centity_s *, const struct weaponInfo_s *))weaponData[weaponNum].func; } - if (weaponData[weaponNum].altfunc) - { - weaponInfo->alt_missileTrailFunc = (void (*)(struct centity_s *,const struct weaponInfo_s *))weaponData[weaponNum].altfunc; + if (weaponData[weaponNum].altfunc) { + weaponInfo->alt_missileTrailFunc = (void (*)(struct centity_s *, const struct weaponInfo_s *))weaponData[weaponNum].altfunc; } - switch ( weaponNum ) //extra client only stuff + switch (weaponNum) // extra client only stuff { case WP_SABER: - //saber/force FX - theFxScheduler.RegisterEffect( "sparks/spark_nosnd" );//was "sparks/spark" - theFxScheduler.RegisterEffect( "sparks/blood_sparks2" ); - theFxScheduler.RegisterEffect( "force/force_touch" ); - theFxScheduler.RegisterEffect( "saber/saber_block" ); - theFxScheduler.RegisterEffect( "saber/saber_cut" ); - //theFxScheduler.RegisterEffect( "saber/limb_bolton" ); - theFxScheduler.RegisterEffect( "saber/fizz" ); - theFxScheduler.RegisterEffect( "saber/boil" ); - //theFxScheduler.RegisterEffect( "saber/fire" );//was "sparks/spark" - - cgs.effects.forceHeal = theFxScheduler.RegisterEffect( "force/heal" ); - //cgs.effects.forceInvincibility = theFxScheduler.RegisterEffect( "force/invin" ); - cgs.effects.forceConfusion = theFxScheduler.RegisterEffect( "force/confusion" ); - cgs.effects.forceLightning = theFxScheduler.RegisterEffect( "force/lightning" ); - cgs.effects.forceLightningWide = theFxScheduler.RegisterEffect( "force/lightningwide" ); - //new Jedi Academy force power effects - cgs.effects.forceDrain = theFxScheduler.RegisterEffect( "mp/drain" ); - cgs.effects.forceDrainWide = theFxScheduler.RegisterEffect( "mp/drainwide" ); - //cgs.effects.forceDrained = theFxScheduler.RegisterEffect( "mp/drainhit"); - - //saber sounds - //cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ); - //cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_on.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberonquick.wav" ); - //cgi_S_RegisterSound( "sound/weapons/saber/saberoff.wav" ); - //cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_off.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberbounce%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhit%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhitwall%d.wav", i ) ); - } - for ( i = 1; i < 10; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberblock%d.wav", i ) ); + // saber/force FX + theFxScheduler.RegisterEffect("sparks/spark_nosnd"); // was "sparks/spark" + theFxScheduler.RegisterEffect("sparks/blood_sparks2"); + theFxScheduler.RegisterEffect("force/force_touch"); + theFxScheduler.RegisterEffect("saber/saber_block"); + theFxScheduler.RegisterEffect("saber/saber_cut"); + // theFxScheduler.RegisterEffect( "saber/limb_bolton" ); + theFxScheduler.RegisterEffect("saber/fizz"); + theFxScheduler.RegisterEffect("saber/boil"); + // theFxScheduler.RegisterEffect( "saber/fire" );//was "sparks/spark" + + cgs.effects.forceHeal = theFxScheduler.RegisterEffect("force/heal"); + // cgs.effects.forceInvincibility = theFxScheduler.RegisterEffect( "force/invin" ); + cgs.effects.forceConfusion = theFxScheduler.RegisterEffect("force/confusion"); + cgs.effects.forceLightning = theFxScheduler.RegisterEffect("force/lightning"); + cgs.effects.forceLightningWide = theFxScheduler.RegisterEffect("force/lightningwide"); + // new Jedi Academy force power effects + cgs.effects.forceDrain = theFxScheduler.RegisterEffect("mp/drain"); + cgs.effects.forceDrainWide = theFxScheduler.RegisterEffect("mp/drainwide"); + // cgs.effects.forceDrained = theFxScheduler.RegisterEffect( "mp/drainhit"); + + // saber sounds + // cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ); + // cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_on.wav" ); + cgi_S_RegisterSound("sound/weapons/saber/saberonquick.wav"); + // cgi_S_RegisterSound( "sound/weapons/saber/saberoff.wav" ); + // cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_off.wav" ); + cgi_S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); + cgi_S_RegisterSound("sound/weapons/saber/saberoffquick.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberbounce%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhit%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhitwall%d.wav", i)); + } + for (i = 1; i < 10; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberblock%d.wav", i)); } /* for ( i = 1; i < 6; i++ ) @@ -273,332 +256,326 @@ void CG_RegisterWeapon( int weaponNum ) { cgi_S_RegisterSound( va( "sound/weapons/saber/saberhum%d.wav", i ) ); } */ - for ( i = 1; i < 10; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhup%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberspin%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/saber/saber_catch.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/bounce%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/saber/hitwater.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/boiling.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/rainfizz%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/movers/objects/saber_slam" ); - - //force sounds - cgi_S_RegisterSound( "sound/weapons/force/heal.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/speed.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/speedloop.mp3" ); - for ( i = 1; i < 5; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d_m.mp3", i ) ); - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d_f.mp3", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/force/lightning.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/lightning2.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/lightninghit%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/force/push.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/pull.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/jump.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/jumpbuild.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/grip.mp3" ); - //new Jedi Academy force sounds - cgi_S_RegisterSound( "sound/weapons/force/absorb.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/absorbhit.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/absorbloop.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/protect.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/protecthit.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/protectloop.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/rage.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/ragehit.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/rageloop.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/see.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/seeloop.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/drain.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/drained.mp3" ); - //force graphics + for (i = 1; i < 10; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhup%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberspin%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/saber/saber_catch.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/bounce%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/saber/hitwater.wav"); + cgi_S_RegisterSound("sound/weapons/saber/boiling.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/rainfizz%d.wav", i)); + } + cgi_S_RegisterSound("sound/movers/objects/saber_slam"); + + // force sounds + cgi_S_RegisterSound("sound/weapons/force/heal.mp3"); + cgi_S_RegisterSound("sound/weapons/force/speed.mp3"); + cgi_S_RegisterSound("sound/weapons/force/speedloop.mp3"); + for (i = 1; i < 5; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/heal%d_m.mp3", i)); + cgi_S_RegisterSound(va("sound/weapons/force/heal%d_f.mp3", i)); + } + cgi_S_RegisterSound("sound/weapons/force/lightning.wav"); + cgi_S_RegisterSound("sound/weapons/force/lightning2.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/lightninghit%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/force/push.wav"); + cgi_S_RegisterSound("sound/weapons/force/pull.wav"); + cgi_S_RegisterSound("sound/weapons/force/jump.wav"); + cgi_S_RegisterSound("sound/weapons/force/jumpbuild.wav"); + cgi_S_RegisterSound("sound/weapons/force/grip.mp3"); + // new Jedi Academy force sounds + cgi_S_RegisterSound("sound/weapons/force/absorb.mp3"); + cgi_S_RegisterSound("sound/weapons/force/absorbhit.mp3"); + cgi_S_RegisterSound("sound/weapons/force/absorbloop.mp3"); + cgi_S_RegisterSound("sound/weapons/force/protect.mp3"); + cgi_S_RegisterSound("sound/weapons/force/protecthit.mp3"); + cgi_S_RegisterSound("sound/weapons/force/protectloop.mp3"); + cgi_S_RegisterSound("sound/weapons/force/rage.mp3"); + cgi_S_RegisterSound("sound/weapons/force/ragehit.mp3"); + cgi_S_RegisterSound("sound/weapons/force/rageloop.mp3"); + cgi_S_RegisterSound("sound/weapons/force/see.mp3"); + cgi_S_RegisterSound("sound/weapons/force/seeloop.mp3"); + cgi_S_RegisterSound("sound/weapons/force/drain.mp3"); + cgi_S_RegisterSound("sound/weapons/force/drained.mp3"); + // force graphics cgs.media.playerShieldDamage = cgi_R_RegisterShader("gfx/misc/personalshield"); - //cgs.media.forceSightBubble = cgi_R_RegisterShader("gfx/misc/sightbubble"); - //cgs.media.forceShell = cgi_R_RegisterShader("powerups/forceshell"); + // cgs.media.forceSightBubble = cgi_R_RegisterShader("gfx/misc/sightbubble"); + // cgs.media.forceShell = cgi_R_RegisterShader("powerups/forceshell"); cgs.media.forceShell = cgi_R_RegisterShader("gfx/misc/forceprotect"); cgs.media.sightShell = cgi_R_RegisterShader("powerups/sightshell"); - cgi_R_RegisterShader( "gfx/2d/jsense" ); - //force effects - FIXME: only if someone has these powers? - theFxScheduler.RegisterEffect( "force/rage2" ); - //theFxScheduler.RegisterEffect( "force/heal_joint" ); - theFxScheduler.RegisterEffect( "force/heal2" ); - theFxScheduler.RegisterEffect( "force/drain_hand" ); - - //saber graphics - cgs.media.saberBlurShader = cgi_R_RegisterShader("gfx/effects/sabers/saberBlur"); - cgs.media.swordTrailShader = cgi_R_RegisterShader("gfx/effects/sabers/swordTrail"); - cgs.media.yellowDroppedSaberShader = cgi_R_RegisterShader("gfx/effects/yellow_glow"); - cgi_R_RegisterShader( "gfx/effects/saberDamageGlow" ); - cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); - cgi_R_RegisterShader( "gfx/effects/forcePush" ); - cgi_R_RegisterShader( "gfx/effects/saberFlare" ); - cgs.media.redSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/red_glow" ); - cgs.media.redSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/red_line" ); - cgs.media.orangeSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/orange_glow" ); - cgs.media.orangeSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/orange_line" ); - cgs.media.yellowSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/yellow_glow" ); - cgs.media.yellowSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/yellow_line" ); - cgs.media.greenSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/green_glow" ); - cgs.media.greenSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/green_line" ); - cgs.media.blueSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/blue_glow" ); - cgs.media.blueSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/blue_line" ); - cgs.media.purpleSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/purple_glow" ); - cgs.media.purpleSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/purple_line" ); - - cgs.media.forceCoronaShader = cgi_R_RegisterShaderNoMip( "gfx/hud/force_swirl" ); - - //new Jedi Academy force graphics - cgs.media.drainShader = cgi_R_RegisterShader( "gfx/misc/redLine" ); - - //for grip slamming into walls - theFxScheduler.RegisterEffect( "env/impact_dustonly" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); - - //For kicks with saber staff... - theFxScheduler.RegisterEffect( "melee/kick_impact" ); - - //Kothos beam - cgi_R_RegisterShader( "gfx/misc/dr1" ); + cgi_R_RegisterShader("gfx/2d/jsense"); + // force effects - FIXME: only if someone has these powers? + theFxScheduler.RegisterEffect("force/rage2"); + // theFxScheduler.RegisterEffect( "force/heal_joint" ); + theFxScheduler.RegisterEffect("force/heal2"); + theFxScheduler.RegisterEffect("force/drain_hand"); + + // saber graphics + cgs.media.saberBlurShader = cgi_R_RegisterShader("gfx/effects/sabers/saberBlur"); + cgs.media.swordTrailShader = cgi_R_RegisterShader("gfx/effects/sabers/swordTrail"); + cgs.media.yellowDroppedSaberShader = cgi_R_RegisterShader("gfx/effects/yellow_glow"); + cgi_R_RegisterShader("gfx/effects/saberDamageGlow"); + cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); + cgi_R_RegisterShader("gfx/effects/forcePush"); + cgi_R_RegisterShader("gfx/effects/saberFlare"); + cgs.media.redSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/red_glow"); + cgs.media.redSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/red_line"); + cgs.media.orangeSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/orange_glow"); + cgs.media.orangeSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/orange_line"); + cgs.media.yellowSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/yellow_glow"); + cgs.media.yellowSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/yellow_line"); + cgs.media.greenSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/green_glow"); + cgs.media.greenSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/green_line"); + cgs.media.blueSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/blue_glow"); + cgs.media.blueSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/blue_line"); + cgs.media.purpleSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/purple_glow"); + cgs.media.purpleSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/purple_line"); + + cgs.media.forceCoronaShader = cgi_R_RegisterShaderNoMip("gfx/hud/force_swirl"); + + // new Jedi Academy force graphics + cgs.media.drainShader = cgi_R_RegisterShader("gfx/misc/redLine"); + + // for grip slamming into walls + theFxScheduler.RegisterEffect("env/impact_dustonly"); + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); + + // For kicks with saber staff... + theFxScheduler.RegisterEffect("melee/kick_impact"); + + // Kothos beam + cgi_R_RegisterShader("gfx/misc/dr1"); break; case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: // enemy version case WP_JAWA: - cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect( "bryar/shot" ); - theFxScheduler.RegisterEffect( "bryar/NPCshot" ); - cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect( "bryar/crackleShot" ); - cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect( "bryar/wall_impact" ); - cgs.effects.bryarWallImpactEffect2 = theFxScheduler.RegisterEffect( "bryar/wall_impact2" ); - cgs.effects.bryarWallImpactEffect3 = theFxScheduler.RegisterEffect( "bryar/wall_impact3" ); - cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect( "bryar/flesh_impact" ); + cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect("bryar/shot"); + theFxScheduler.RegisterEffect("bryar/NPCshot"); + cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect("bryar/crackleShot"); + cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect("bryar/wall_impact"); + cgs.effects.bryarWallImpactEffect2 = theFxScheduler.RegisterEffect("bryar/wall_impact2"); + cgs.effects.bryarWallImpactEffect3 = theFxScheduler.RegisterEffect("bryar/wall_impact3"); + cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect("bryar/flesh_impact"); // Note....these are temp shared effects - theFxScheduler.RegisterEffect( "blaster/deflect" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); // note: this will be called game side + theFxScheduler.RegisterEffect("blaster/deflect"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); // note: this will be called game side break; case WP_BLASTER: - cgs.effects.blasterShotEffect = theFxScheduler.RegisterEffect( "blaster/shot" ); - theFxScheduler.RegisterEffect( "blaster/NPCshot" ); -// cgs.effects.blasterOverchargeEffect = theFxScheduler.RegisterEffect( "blaster/overcharge" ); - cgs.effects.blasterWallImpactEffect = theFxScheduler.RegisterEffect( "blaster/wall_impact" ); - cgs.effects.blasterFleshImpactEffect = theFxScheduler.RegisterEffect( "blaster/flesh_impact" ); - theFxScheduler.RegisterEffect( "blaster/deflect" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); // note: this will be called game side + cgs.effects.blasterShotEffect = theFxScheduler.RegisterEffect("blaster/shot"); + theFxScheduler.RegisterEffect("blaster/NPCshot"); + // cgs.effects.blasterOverchargeEffect = theFxScheduler.RegisterEffect( "blaster/overcharge" ); + cgs.effects.blasterWallImpactEffect = theFxScheduler.RegisterEffect("blaster/wall_impact"); + cgs.effects.blasterFleshImpactEffect = theFxScheduler.RegisterEffect("blaster/flesh_impact"); + theFxScheduler.RegisterEffect("blaster/deflect"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); // note: this will be called game side break; case WP_DISRUPTOR: - theFxScheduler.RegisterEffect( "disruptor/wall_impact" ); - theFxScheduler.RegisterEffect( "disruptor/flesh_impact" ); - theFxScheduler.RegisterEffect( "disruptor/alt_miss" ); - theFxScheduler.RegisterEffect( "disruptor/alt_hit" ); - theFxScheduler.RegisterEffect( "disruptor/line_cap" ); - theFxScheduler.RegisterEffect( "disruptor/death_smoke" ); + theFxScheduler.RegisterEffect("disruptor/wall_impact"); + theFxScheduler.RegisterEffect("disruptor/flesh_impact"); + theFxScheduler.RegisterEffect("disruptor/alt_miss"); + theFxScheduler.RegisterEffect("disruptor/alt_hit"); + theFxScheduler.RegisterEffect("disruptor/line_cap"); + theFxScheduler.RegisterEffect("disruptor/death_smoke"); - cgi_R_RegisterShader( "gfx/effects/redLine" ); - cgi_R_RegisterShader( "gfx/misc/whiteline2" ); - cgi_R_RegisterShader( "gfx/effects/smokeTrail" ); - cgi_R_RegisterShader( "gfx/effects/burn" ); + cgi_R_RegisterShader("gfx/effects/redLine"); + cgi_R_RegisterShader("gfx/misc/whiteline2"); + cgi_R_RegisterShader("gfx/effects/smokeTrail"); + cgi_R_RegisterShader("gfx/effects/burn"); - cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" ); + cgi_R_RegisterShaderNoMip("gfx/2d/crop_charge"); // zoom sounds - cgi_S_RegisterSound( "sound/weapons/disruptor/zoomstart.wav" ); - cgi_S_RegisterSound( "sound/weapons/disruptor/zoomend.wav" ); - cgs.media.disruptorZoomLoop = cgi_S_RegisterSound( "sound/weapons/disruptor/zoomloop.wav" ); + cgi_S_RegisterSound("sound/weapons/disruptor/zoomstart.wav"); + cgi_S_RegisterSound("sound/weapons/disruptor/zoomend.wav"); + cgs.media.disruptorZoomLoop = cgi_S_RegisterSound("sound/weapons/disruptor/zoomloop.wav"); // Disruptor gun zoom interface - cgs.media.disruptorMask = cgi_R_RegisterShader( "gfx/2d/cropCircle2"); - cgs.media.disruptorInsert = cgi_R_RegisterShader( "gfx/2d/cropCircle"); - cgs.media.disruptorLight = cgi_R_RegisterShader( "gfx/2d/cropCircleGlow" ); - cgs.media.disruptorInsertTick = cgi_R_RegisterShader( "gfx/2d/insertTick" ); + cgs.media.disruptorMask = cgi_R_RegisterShader("gfx/2d/cropCircle2"); + cgs.media.disruptorInsert = cgi_R_RegisterShader("gfx/2d/cropCircle"); + cgs.media.disruptorLight = cgi_R_RegisterShader("gfx/2d/cropCircleGlow"); + cgs.media.disruptorInsertTick = cgi_R_RegisterShader("gfx/2d/insertTick"); break; case WP_BOWCASTER: - cgs.effects.bowcasterShotEffect = theFxScheduler.RegisterEffect( "bowcaster/shot" ); - cgs.effects.bowcasterBounceEffect = theFxScheduler.RegisterEffect( "bowcaster/bounce_wall" ); - cgs.effects.bowcasterImpactEffect = theFxScheduler.RegisterEffect( "bowcaster/explosion" ); - theFxScheduler.RegisterEffect( "bowcaster/deflect" ); + cgs.effects.bowcasterShotEffect = theFxScheduler.RegisterEffect("bowcaster/shot"); + cgs.effects.bowcasterBounceEffect = theFxScheduler.RegisterEffect("bowcaster/bounce_wall"); + cgs.effects.bowcasterImpactEffect = theFxScheduler.RegisterEffect("bowcaster/explosion"); + theFxScheduler.RegisterEffect("bowcaster/deflect"); break; case WP_REPEATER: - theFxScheduler.RegisterEffect( "repeater/muzzle_smoke" ); - theFxScheduler.RegisterEffect( "repeater/projectile" ); - theFxScheduler.RegisterEffect( "repeater/alt_projectile" ); - theFxScheduler.RegisterEffect( "repeater/wall_impact" ); -// theFxScheduler.RegisterEffect( "repeater/alt_wall_impact2" ); -// theFxScheduler.RegisterEffect( "repeater/flesh_impact" ); - theFxScheduler.RegisterEffect( "repeater/concussion" ); + theFxScheduler.RegisterEffect("repeater/muzzle_smoke"); + theFxScheduler.RegisterEffect("repeater/projectile"); + theFxScheduler.RegisterEffect("repeater/alt_projectile"); + theFxScheduler.RegisterEffect("repeater/wall_impact"); + // theFxScheduler.RegisterEffect( "repeater/alt_wall_impact2" ); + // theFxScheduler.RegisterEffect( "repeater/flesh_impact" ); + theFxScheduler.RegisterEffect("repeater/concussion"); break; case WP_DEMP2: - theFxScheduler.RegisterEffect( "demp2/projectile" ); - theFxScheduler.RegisterEffect( "demp2/wall_impact" ); - theFxScheduler.RegisterEffect( "demp2/flesh_impact" ); - theFxScheduler.RegisterEffect( "demp2/altDetonate" ); - cgi_R_RegisterModel( "models/items/sphere.md3" ); - cgi_R_RegisterShader( "gfx/effects/demp2shell" ); + theFxScheduler.RegisterEffect("demp2/projectile"); + theFxScheduler.RegisterEffect("demp2/wall_impact"); + theFxScheduler.RegisterEffect("demp2/flesh_impact"); + theFxScheduler.RegisterEffect("demp2/altDetonate"); + cgi_R_RegisterModel("models/items/sphere.md3"); + cgi_R_RegisterShader("gfx/effects/demp2shell"); break; case WP_ATST_MAIN: - theFxScheduler.RegisterEffect( "atst/shot" ); - theFxScheduler.RegisterEffect( "atst/wall_impact" ); - theFxScheduler.RegisterEffect( "atst/flesh_impact" ); - theFxScheduler.RegisterEffect( "atst/droid_impact" ); + theFxScheduler.RegisterEffect("atst/shot"); + theFxScheduler.RegisterEffect("atst/wall_impact"); + theFxScheduler.RegisterEffect("atst/flesh_impact"); + theFxScheduler.RegisterEffect("atst/droid_impact"); break; case WP_ATST_SIDE: // For the ALT fire - theFxScheduler.RegisterEffect( "atst/side_alt_shot" ); - theFxScheduler.RegisterEffect( "atst/side_alt_explosion" ); + theFxScheduler.RegisterEffect("atst/side_alt_shot"); + theFxScheduler.RegisterEffect("atst/side_alt_explosion"); // For the regular fire - theFxScheduler.RegisterEffect( "atst/side_main_shot" ); - theFxScheduler.RegisterEffect( "atst/side_main_impact" ); + theFxScheduler.RegisterEffect("atst/side_main_shot"); + theFxScheduler.RegisterEffect("atst/side_main_impact"); break; case WP_FLECHETTE: - cgs.effects.flechetteShotEffect = theFxScheduler.RegisterEffect( "flechette/shot" ); - cgs.effects.flechetteAltShotEffect = theFxScheduler.RegisterEffect( "flechette/alt_shot" ); - cgs.effects.flechetteShotDeathEffect = theFxScheduler.RegisterEffect( "flechette/wall_impact" ); // shot death - cgs.effects.flechetteFleshImpactEffect = theFxScheduler.RegisterEffect( "flechette/flesh_impact" ); - cgs.effects.flechetteRicochetEffect = theFxScheduler.RegisterEffect( "flechette/ricochet" ); + cgs.effects.flechetteShotEffect = theFxScheduler.RegisterEffect("flechette/shot"); + cgs.effects.flechetteAltShotEffect = theFxScheduler.RegisterEffect("flechette/alt_shot"); + cgs.effects.flechetteShotDeathEffect = theFxScheduler.RegisterEffect("flechette/wall_impact"); // shot death + cgs.effects.flechetteFleshImpactEffect = theFxScheduler.RegisterEffect("flechette/flesh_impact"); + cgs.effects.flechetteRicochetEffect = theFxScheduler.RegisterEffect("flechette/ricochet"); -// theFxScheduler.RegisterEffect( "flechette/explosion" ); - theFxScheduler.RegisterEffect( "flechette/alt_blow" ); + // theFxScheduler.RegisterEffect( "flechette/explosion" ); + theFxScheduler.RegisterEffect("flechette/alt_blow"); break; case WP_ROCKET_LAUNCHER: - theFxScheduler.RegisterEffect( "rocket/shot" ); - theFxScheduler.RegisterEffect( "rocket/explosion" ); + theFxScheduler.RegisterEffect("rocket/shot"); + theFxScheduler.RegisterEffect("rocket/explosion"); - cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" ); - cgi_R_RegisterShaderNoMip( "gfx/2d/lock" ); + cgi_R_RegisterShaderNoMip("gfx/2d/wedge"); + cgi_R_RegisterShaderNoMip("gfx/2d/lock"); - cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" ); - cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" ); + cgi_S_RegisterSound("sound/weapons/rocket/lock.wav"); + cgi_S_RegisterSound("sound/weapons/rocket/tick.wav"); break; case WP_CONCUSSION: - //Primary - theFxScheduler.RegisterEffect( "concussion/shot" ); - theFxScheduler.RegisterEffect( "concussion/explosion" ); - //Alt - theFxScheduler.RegisterEffect( "concussion/alt_miss" ); - theFxScheduler.RegisterEffect( "concussion/alt_hit" ); - theFxScheduler.RegisterEffect( "concussion/alt_ring" ); - //not used (eventually)? - cgi_R_RegisterShader( "gfx/effects/blueLine" ); - cgi_R_RegisterShader( "gfx/misc/whiteline2" ); + // Primary + theFxScheduler.RegisterEffect("concussion/shot"); + theFxScheduler.RegisterEffect("concussion/explosion"); + // Alt + theFxScheduler.RegisterEffect("concussion/alt_miss"); + theFxScheduler.RegisterEffect("concussion/alt_hit"); + theFxScheduler.RegisterEffect("concussion/alt_ring"); + // not used (eventually)? + cgi_R_RegisterShader("gfx/effects/blueLine"); + cgi_R_RegisterShader("gfx/misc/whiteline2"); break; case WP_THERMAL: - cgs.media.grenadeBounce1 = cgi_S_RegisterSound( "sound/weapons/thermal/bounce1.wav" ); - cgs.media.grenadeBounce2 = cgi_S_RegisterSound( "sound/weapons/thermal/bounce2.wav" ); + cgs.media.grenadeBounce1 = cgi_S_RegisterSound("sound/weapons/thermal/bounce1.wav"); + cgs.media.grenadeBounce2 = cgi_S_RegisterSound("sound/weapons/thermal/bounce2.wav"); - cgi_S_RegisterSound( "sound/weapons/thermal/thermloop.wav" ); - cgi_S_RegisterSound( "sound/weapons/thermal/warning.wav" ); - theFxScheduler.RegisterEffect( "thermal/explosion" ); - theFxScheduler.RegisterEffect( "thermal/shockwave" ); + cgi_S_RegisterSound("sound/weapons/thermal/thermloop.wav"); + cgi_S_RegisterSound("sound/weapons/thermal/warning.wav"); + theFxScheduler.RegisterEffect("thermal/explosion"); + theFxScheduler.RegisterEffect("thermal/shockwave"); break; case WP_TRIP_MINE: - theFxScheduler.RegisterEffect( "tripMine/explosion" ); - theFxScheduler.RegisterEffect( "tripMine/laser" ); - theFxScheduler.RegisterEffect( "tripMine/laserImpactGlow" ); - theFxScheduler.RegisterEffect( "tripMine/glowBit" ); + theFxScheduler.RegisterEffect("tripMine/explosion"); + theFxScheduler.RegisterEffect("tripMine/laser"); + theFxScheduler.RegisterEffect("tripMine/laserImpactGlow"); + theFxScheduler.RegisterEffect("tripMine/glowBit"); - cgs.media.tripMineStickSound = cgi_S_RegisterSound( "sound/weapons/laser_trap/stick.wav" ); - cgi_S_RegisterSound( "sound/weapons/laser_trap/warning.wav" ); - cgi_S_RegisterSound( "sound/weapons/laser_trap/hum_loop.wav" ); + cgs.media.tripMineStickSound = cgi_S_RegisterSound("sound/weapons/laser_trap/stick.wav"); + cgi_S_RegisterSound("sound/weapons/laser_trap/warning.wav"); + cgi_S_RegisterSound("sound/weapons/laser_trap/hum_loop.wav"); break; case WP_DET_PACK: - theFxScheduler.RegisterEffect( "detpack/explosion.efx" ); + theFxScheduler.RegisterEffect("detpack/explosion.efx"); - cgs.media.detPackStickSound = cgi_S_RegisterSound( "sound/weapons/detpack/stick.wav" ); - cgi_R_RegisterModel( "models/weapons2/detpack/detpack.md3" ); - cgi_S_RegisterSound( "sound/weapons/detpack/warning.wav" ); - cgi_S_RegisterSound( "sound/weapons/explosions/explode5.wav" ); + cgs.media.detPackStickSound = cgi_S_RegisterSound("sound/weapons/detpack/stick.wav"); + cgi_R_RegisterModel("models/weapons2/detpack/detpack.md3"); + cgi_S_RegisterSound("sound/weapons/detpack/warning.wav"); + cgi_S_RegisterSound("sound/weapons/explosions/explode5.wav"); break; case WP_EMPLACED_GUN: - theFxScheduler.RegisterEffect( "emplaced/shot" ); - theFxScheduler.RegisterEffect( "emplaced/shotNPC" ); - theFxScheduler.RegisterEffect( "emplaced/wall_impact" ); - //E-Web, too, can't tell here which one you wanted, so... - theFxScheduler.RegisterEffect( "eweb/shot" ); - theFxScheduler.RegisterEffect( "eweb/shotNPC" ); - theFxScheduler.RegisterEffect( "eweb/wall_impact" ); - theFxScheduler.RegisterEffect( "eweb/flesh_impact" ); + theFxScheduler.RegisterEffect("emplaced/shot"); + theFxScheduler.RegisterEffect("emplaced/shotNPC"); + theFxScheduler.RegisterEffect("emplaced/wall_impact"); + // E-Web, too, can't tell here which one you wanted, so... + theFxScheduler.RegisterEffect("eweb/shot"); + theFxScheduler.RegisterEffect("eweb/shotNPC"); + theFxScheduler.RegisterEffect("eweb/wall_impact"); + theFxScheduler.RegisterEffect("eweb/flesh_impact"); - cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg" ); - cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_on" ); + cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg"); + cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_on"); - cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip( "gfx/hud/health_frame" ); - cgs.media.turretComputerOverlayShader = cgi_R_RegisterShaderNoMip( "gfx/hud/generic_target" ); - cgs.media.turretCrossHairShader = cgi_R_RegisterShaderNoMip( "gfx/2d/panel_crosshair" ); + cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip("gfx/hud/health_frame"); + cgs.media.turretComputerOverlayShader = cgi_R_RegisterShaderNoMip("gfx/hud/generic_target"); + cgs.media.turretCrossHairShader = cgi_R_RegisterShaderNoMip("gfx/2d/panel_crosshair"); break; case WP_MELEE: case WP_TUSKEN_STAFF: - //TEMP - theFxScheduler.RegisterEffect( "melee/punch_impact" ); - theFxScheduler.RegisterEffect( "melee/kick_impact" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); + // TEMP + theFxScheduler.RegisterEffect("melee/punch_impact"); + theFxScheduler.RegisterEffect("melee/kick_impact"); + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); break; case WP_STUN_BATON: - cgi_R_RegisterShader( "gfx/effects/stunPass" ); - theFxScheduler.RegisterEffect( "stunBaton/flesh_impact" ); - //TEMP - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); - cgi_S_RegisterSound( "sound/weapons/baton/fire" ); + cgi_R_RegisterShader("gfx/effects/stunPass"); + theFxScheduler.RegisterEffect("stunBaton/flesh_impact"); + // TEMP + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); + cgi_S_RegisterSound("sound/weapons/baton/fire"); break; case WP_TURRET: - theFxScheduler.RegisterEffect( "turret/shot" ); - theFxScheduler.RegisterEffect( "turret/wall_impact" ); - theFxScheduler.RegisterEffect( "turret/flesh_impact" ); + theFxScheduler.RegisterEffect("turret/shot"); + theFxScheduler.RegisterEffect("turret/wall_impact"); + theFxScheduler.RegisterEffect("turret/flesh_impact"); break; case WP_TUSKEN_RIFLE: - //melee - theFxScheduler.RegisterEffect( "melee/punch_impact" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); - //fire - theFxScheduler.RegisterEffect( "tusken/shot" ); - theFxScheduler.RegisterEffect( "tusken/hit" ); - theFxScheduler.RegisterEffect( "tusken/hitwall" ); + // melee + theFxScheduler.RegisterEffect("melee/punch_impact"); + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); + // fire + theFxScheduler.RegisterEffect("tusken/shot"); + theFxScheduler.RegisterEffect("tusken/hit"); + theFxScheduler.RegisterEffect("tusken/hitwall"); break; @@ -607,16 +584,16 @@ void CG_RegisterWeapon( int weaponNum ) { break; case WP_NOGHRI_STICK: - //fire - theFxScheduler.RegisterEffect( "noghri_stick/shot" ); - theFxScheduler.RegisterEffect( "noghri_stick/flesh_impact" ); - //explosion - theFxScheduler.RegisterEffect( "noghri_stick/gas_cloud" ); - //cgi_S_RegisterSound("sound/weapons/noghri/smoke.wav"); + // fire + theFxScheduler.RegisterEffect("noghri_stick/shot"); + theFxScheduler.RegisterEffect("noghri_stick/flesh_impact"); + // explosion + theFxScheduler.RegisterEffect("noghri_stick/gas_cloud"); + // cgi_S_RegisterSound("sound/weapons/noghri/smoke.wav"); break; case WP_TIE_FIGHTER: - theFxScheduler.RegisterEffect( "ships/imp_blastershot" ); + theFxScheduler.RegisterEffect("ships/imp_blastershot"); break; } } @@ -628,103 +605,92 @@ CG_RegisterItemVisuals The server says this item is used on this level ================= */ -void CG_RegisterItemVisuals( int itemNum ) { - itemInfo_t *itemInfo; - gitem_t *item; +void CG_RegisterItemVisuals(int itemNum) { + itemInfo_t *itemInfo; + gitem_t *item; - itemInfo = &cg_items[ itemNum ]; - if ( itemInfo->registered ) { + itemInfo = &cg_items[itemNum]; + if (itemInfo->registered) { return; } - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - memset( itemInfo, 0, sizeof( *itemInfo ) ); + memset(itemInfo, 0, sizeof(*itemInfo)); itemInfo->registered = qtrue; - itemInfo->models = cgi_R_RegisterModel( item->world_model ); + itemInfo->models = cgi_R_RegisterModel(item->world_model); - if ( item->icon && item->icon[0] ) - { - itemInfo->icon = cgi_R_RegisterShaderNoMip( item->icon ); - } - else - { + if (item->icon && item->icon[0]) { + itemInfo->icon = cgi_R_RegisterShaderNoMip(item->icon); + } else { itemInfo->icon = -1; } - if ( item->giType == IT_WEAPON ) - { - CG_RegisterWeapon( item->giTag ); + if (item->giType == IT_WEAPON) { + CG_RegisterWeapon(item->giTag); } // some ammo types are actually the weapon, like in the case of explosives - if ( item->giType == IT_AMMO ) - { - switch( item->giTag ) - { + if (item->giType == IT_AMMO) { + switch (item->giTag) { case AMMO_THERMAL: - CG_RegisterWeapon( WP_THERMAL ); + CG_RegisterWeapon(WP_THERMAL); break; case AMMO_TRIPMINE: - CG_RegisterWeapon( WP_TRIP_MINE ); + CG_RegisterWeapon(WP_TRIP_MINE); break; case AMMO_DETPACK: - CG_RegisterWeapon( WP_DET_PACK ); + CG_RegisterWeapon(WP_DET_PACK); break; } } - - if ( item->giType == IT_HOLDABLE ) - { + if (item->giType == IT_HOLDABLE) { // This should be set up to actually work. - switch( item->giTag ) - { + switch (item->giTag) { case INV_SEEKER: cgi_S_RegisterSound("sound/chars/seeker/misc/fire.wav"); - cgi_S_RegisterSound( "sound/chars/seeker/misc/hiss.wav"); - theFxScheduler.RegisterEffect( "env/small_explode"); + cgi_S_RegisterSound("sound/chars/seeker/misc/hiss.wav"); + theFxScheduler.RegisterEffect("env/small_explode"); - CG_RegisterWeapon( WP_BLASTER ); + CG_RegisterWeapon(WP_BLASTER); break; case INV_SENTRY: - CG_RegisterWeapon( WP_TURRET ); - cgi_S_RegisterSound( "sound/player/use_sentry" ); + CG_RegisterWeapon(WP_TURRET); + cgi_S_RegisterSound("sound/player/use_sentry"); break; case INV_ELECTROBINOCULARS: // Binocular interface - cgs.media.binocularCircle = cgi_R_RegisterShader( "gfx/2d/binCircle" ); - cgs.media.binocularMask = cgi_R_RegisterShader( "gfx/2d/binMask" ); - cgs.media.binocularArrow = cgi_R_RegisterShader( "gfx/2d/binSideArrow" ); - cgs.media.binocularTri = cgi_R_RegisterShader( "gfx/2d/binTopTri" ); - cgs.media.binocularStatic = cgi_R_RegisterShader( "gfx/2d/binocularWindow" ); - cgs.media.binocularOverlay = cgi_R_RegisterShader( "gfx/2d/binocularNumOverlay" ); + cgs.media.binocularCircle = cgi_R_RegisterShader("gfx/2d/binCircle"); + cgs.media.binocularMask = cgi_R_RegisterShader("gfx/2d/binMask"); + cgs.media.binocularArrow = cgi_R_RegisterShader("gfx/2d/binSideArrow"); + cgs.media.binocularTri = cgi_R_RegisterShader("gfx/2d/binTopTri"); + cgs.media.binocularStatic = cgi_R_RegisterShader("gfx/2d/binocularWindow"); + cgs.media.binocularOverlay = cgi_R_RegisterShader("gfx/2d/binocularNumOverlay"); break; case INV_LIGHTAMP_GOGGLES: // LA Goggles Shaders - cgs.media.laGogglesStatic = cgi_R_RegisterShader( "gfx/2d/lagogglesWindow" ); - cgs.media.laGogglesMask = cgi_R_RegisterShader( "gfx/2d/amp_mask" ); - cgs.media.laGogglesSideBit = cgi_R_RegisterShader( "gfx/2d/side_bit" ); - cgs.media.laGogglesBracket = cgi_R_RegisterShader( "gfx/2d/bracket" ); - cgs.media.laGogglesArrow = cgi_R_RegisterShader( "gfx/2d/bracket2" ); + cgs.media.laGogglesStatic = cgi_R_RegisterShader("gfx/2d/lagogglesWindow"); + cgs.media.laGogglesMask = cgi_R_RegisterShader("gfx/2d/amp_mask"); + cgs.media.laGogglesSideBit = cgi_R_RegisterShader("gfx/2d/side_bit"); + cgs.media.laGogglesBracket = cgi_R_RegisterShader("gfx/2d/bracket"); + cgs.media.laGogglesArrow = cgi_R_RegisterShader("gfx/2d/bracket2"); break; case INV_BACTA_CANISTER: - for ( int i = 1; i < 5; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d_m.mp3", i ) ); - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d_f.mp3", i ) ); + for (int i = 1; i < 5; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/heal%d_m.mp3", i)); + cgi_S_RegisterSound(va("sound/weapons/force/heal%d_f.mp3", i)); } break; } } } - /* ======================================================================================== @@ -746,19 +712,16 @@ the weapon hand animation has 3 anims, if the torso anim does not match these lengths, it will not animate correctly! ================= */ -extern qboolean ValidAnimFileIndex ( int index ); -int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, int weaponNum, int firing ) -{ +extern qboolean ValidAnimFileIndex(int index); +int CG_MapTorsoToWeaponFrame(const clientInfo_t *ci, int frame, int animNum, int weaponNum, int firing) { // we should use the animNum to map a weapon frame instead of relying on the torso frame - if ( !ValidAnimFileIndex( ci->animFileIndex ) ) - { + if (!ValidAnimFileIndex(ci->animFileIndex)) { return 0; } animation_t *animations = level.knownAnimFileSets[ci->animFileIndex].animations; - int ret=0; + int ret = 0; - switch( animNum ) - { + switch (animNum) { case TORSO_WEAPONREADY1: case TORSO_WEAPONREADY2: case TORSO_WEAPONREADY3: @@ -768,24 +731,18 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in break; case TORSO_DROPWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5) { ret = frame - animations[animNum].firstFrame + 6; - } - else - { -// assert(0); + } else { + // assert(0); } break; case TORSO_RAISEWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4) { ret = frame - animations[animNum].firstFrame + 6 + 5; - } - else - { -// assert(0); + } else { + // assert(0); } break; @@ -793,13 +750,10 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in case BOTH_ATTACK2: case BOTH_ATTACK3: case BOTH_ATTACK4: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6 ) - { - ret = 1 + ( frame - animations[animNum].firstFrame ); - } - else - { -// assert(0); + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6) { + ret = 1 + (frame - animations[animNum].firstFrame); + } else { + // assert(0); } break; default: @@ -814,17 +768,16 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in CG_CalculateWeaponPosition ============== */ -void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) -{ - float scale; - int delta; - float fracsin; +void CG_CalculateWeaponPosition(vec3_t origin, vec3_t angles) { + float scale; + int delta; + float fracsin; - VectorCopy( cg.refdef.vieworg, origin ); - VectorCopy( cg.refdefViewAngles, angles ); + VectorCopy(cg.refdef.vieworg, origin); + VectorCopy(cg.refdefViewAngles, angles); // on odd legs, invert some angles - if ( cg.bobcycle & 1 ) { + if (cg.bobcycle & 1) { scale = -cg.xyspeed; } else { scale = cg.xyspeed; @@ -837,11 +790,10 @@ void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) // drop the weapon when landing delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { - origin[2] += cg.landChange*0.25 * delta / LAND_DEFLECT_TIME; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { - origin[2] += cg.landChange*0.25 * - (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; + if (delta < LAND_DEFLECT_TIME) { + origin[2] += cg.landChange * 0.25 * delta / LAND_DEFLECT_TIME; + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { + origin[2] += cg.landChange * 0.25 * (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; } #if 0 @@ -855,11 +807,11 @@ void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) #endif // idle drift - scale = /*cg.xyspeed + */40; - fracsin = sin( cg.time * 0.001 ); + scale = /*cg.xyspeed + */ 40; + fracsin = sin(cg.time * 0.001); angles[ROLL] += scale * fracsin * 0.01; angles[YAW] += scale * fracsin * 0.01; - angles[PITCH] += (scale * 0.5f ) * fracsin * 0.01; + angles[PITCH] += (scale * 0.5f) * fracsin * 0.01; } /* @@ -900,57 +852,44 @@ static float CG_MachinegunSpinAngle( centity_t *cent ) { Ghoul2 Insert Start */ // set up the appropriate ghoul2 info to a refent -void CG_SetGhoul2InfoRef( refEntity_t *ent, refEntity_t *s1) -{ +void CG_SetGhoul2InfoRef(refEntity_t *ent, refEntity_t *s1) { ent->ghoul2 = s1->ghoul2; - VectorCopy( s1->modelScale, ent->modelScale); + VectorCopy(s1->modelScale, ent->modelScale); ent->radius = s1->radius; - VectorCopy( s1->angles, ent->angles); + VectorCopy(s1->angles, ent->angles); } - //-------------------------------------------------------------------------- -static void CG_DoMuzzleFlash( centity_t *cent, vec3_t org, vec3_t dir, weaponData_t *wData ) -{ +static void CG_DoMuzzleFlash(centity_t *cent, vec3_t org, vec3_t dir, weaponData_t *wData) { // Handle muzzle flashes, really this could just be a qboolean instead of a time....... - if ( cent->muzzleFlashTime > 0 ) - { - cent->muzzleFlashTime = 0; + if (cent->muzzleFlashTime > 0) { + cent->muzzleFlashTime = 0; const char *effect = NULL; -// CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + // CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cent->altFire ) - { + if (cent->altFire) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect ) - { - if (( cent->gent && cent->gent->NPC ) || cg.renderingThirdPerson ) - { - theFxScheduler.PlayEffect( effect, org, dir ); - } - else - { + if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect) { + if ((cent->gent && cent->gent->NPC) || cg.renderingThirdPerson) { + theFxScheduler.PlayEffect(effect, org, dir); + } else { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cent->currentState.clientNum ); + theFxScheduler.PlayEffect(effect, cent->currentState.clientNum); } } - } - else - { -// CG_PositionRotatedEntityOnTag( &flash, &gun, weapon->weaponModel, "tag_flash", NULL); + } else { + // CG_PositionRotatedEntityOnTag( &flash, &gun, weapon->weaponModel, "tag_flash", NULL); } } @@ -965,95 +904,84 @@ CG_AddViewWeapon Add the weapon, and flash for the player's view ============== */ -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -extern float CG_ForceSpeedFOV( void ); - -void CG_AddViewWeapon( playerState_t *ps ) -{ - refEntity_t hand; - refEntity_t flash; - vec3_t angles; - const weaponInfo_t *weapon; - weaponData_t *wData; - centity_t *cent; - float fovOffset, leanOffset; +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +extern float CG_ForceSpeedFOV(void); + +void CG_AddViewWeapon(playerState_t *ps) { + refEntity_t hand; + refEntity_t flash; + vec3_t angles; + const weaponInfo_t *weapon; + weaponData_t *wData; + centity_t *cent; + float fovOffset, leanOffset; // no gun if in third person view - if ( cg.renderingThirdPerson ) + if (cg.renderingThirdPerson) return; - if ( ps->pm_type == PM_INTERMISSION ) + if (ps->pm_type == PM_INTERMISSION) return; cent = &cg_entities[ps->clientNum]; - if ( ps->eFlags & EF_LOCKED_TO_WEAPON ) - { + if (ps->eFlags & EF_LOCKED_TO_WEAPON) { return; } - if ( cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive&(1<pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); + if (cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // doing the electrocuting + vec3_t temp; // tAng, fxDir, + // VectorSet( tAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); - VectorCopy( cent->gent->client->renderInfo.handLPoint, temp ); - VectorMA( temp, -5, cg.refdef.viewaxis[0], temp ); - if ( cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - //vec3_t fxAxis[3]; - //AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceLightningWide, temp, cg.refdef.viewaxis ); - } - else - {//line - //AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceLightning, temp, cg.refdef.viewaxis[0] ); + VectorCopy(cent->gent->client->renderInfo.handLPoint, temp); + VectorMA(temp, -5, cg.refdef.viewaxis[0], temp); + if (cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + // vec3_t fxAxis[3]; + // AnglesToAxis( tAng, fxAxis ); + theFxScheduler.PlayEffect(cgs.effects.forceLightningWide, temp, cg.refdef.viewaxis); + } else { // line + // AngleVectors( tAng, fxDir, NULL, NULL ); + theFxScheduler.PlayEffect(cgs.effects.forceLightning, temp, cg.refdef.viewaxis[0]); } } - if ( cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive&(1<pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); + if (cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_DRAIN)) { // doing the draining + vec3_t temp; // tAng, fxDir, + // VectorSet( tAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); - VectorCopy( cent->gent->client->renderInfo.handLPoint, temp ); - VectorMA( temp, -5, cg.refdef.viewaxis[0], temp ); - if ( cent->gent->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//arc - //vec3_t fxAxis[3]; - //AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceDrainWide, temp, cg.refdef.viewaxis ); - } - else - {//line - //AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceDrain, temp, cg.refdef.viewaxis[0] ); + VectorCopy(cent->gent->client->renderInfo.handLPoint, temp); + VectorMA(temp, -5, cg.refdef.viewaxis[0], temp); + if (cent->gent->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // arc + // vec3_t fxAxis[3]; + // AnglesToAxis( tAng, fxAxis ); + theFxScheduler.PlayEffect(cgs.effects.forceDrainWide, temp, cg.refdef.viewaxis); + } else { // line + // AngleVectors( tAng, fxDir, NULL, NULL ); + theFxScheduler.PlayEffect(cgs.effects.forceDrain, temp, cg.refdef.viewaxis[0]); } } // allow the gun to be completely removed - if ( !cg_drawGun.integer || cg.zoomMode ) - { - vec3_t origin; + if (!cg_drawGun.integer || cg.zoomMode) { + vec3_t origin; // special hack for lightning guns... - VectorCopy( cg.refdef.vieworg, origin ); - VectorMA( origin, -10, cg.refdef.viewaxis[2], origin ); - VectorMA( origin, 16, cg.refdef.viewaxis[0], origin ); -// Doesn't look like we'll have lightning style guns. Clean this crap up when we are sure about this. -// CG_LightningBolt( cent, origin ); + VectorCopy(cg.refdef.vieworg, origin); + VectorMA(origin, -10, cg.refdef.viewaxis[2], origin); + VectorMA(origin, 16, cg.refdef.viewaxis[0], origin); + // Doesn't look like we'll have lightning style guns. Clean this crap up when we are sure about this. + // CG_LightningBolt( cent, origin ); // We should still do muzzle flashes though... - CG_RegisterWeapon( ps->weapon ); + CG_RegisterWeapon(ps->weapon); weapon = &cg_weapons[ps->weapon]; - wData = &weaponData[ps->weapon]; + wData = &weaponData[ps->weapon]; - CG_DoMuzzleFlash( cent, origin, cg.refdef.viewaxis[0], wData ); + CG_DoMuzzleFlash(cent, origin, cg.refdef.viewaxis[0], wData); // If we don't update this, the muzzle flash point won't even be updated properly - VectorCopy( origin, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( cg.refdef.viewaxis[0], cent->gent->client->renderInfo.muzzleDir ); + VectorCopy(origin, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(cg.refdef.viewaxis[0], cent->gent->client->renderInfo.muzzleDir); cent->gent->client->renderInfo.mPCalcTime = cg.time; return; @@ -1061,305 +989,258 @@ void CG_AddViewWeapon( playerState_t *ps ) // drop gun lower at higher fov float actualFOV; - if ( (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] )//cg.renderingThirdPerson && + if ((cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && player->client->ps.forcePowerDuration[FP_SPEED]) // cg.renderingThirdPerson && { actualFOV = CG_ForceSpeedFOV(); - } - else - { - if ( cg.overrides.active & CG_OVERRIDE_FOV ) + } else { + if (cg.overrides.active & CG_OVERRIDE_FOV) actualFOV = cg.overrides.fov; else { actualFOV = cg_fovViewmodel.integer ? cg_fovViewmodel.value : cg_fov.value; } } - if ( cg_fovViewmodelAdjust.integer && actualFOV > 90 ) - fovOffset = -0.1 * ( actualFOV - 80 ); + if (cg_fovViewmodelAdjust.integer && actualFOV > 90) + fovOffset = -0.1 * (actualFOV - 80); else fovOffset = 0; - if ( ps->leanofs != 0 ) - { //add leaning offset + if (ps->leanofs != 0) { // add leaning offset leanOffset = ps->leanofs * 0.25f; fovOffset += abs(ps->leanofs) * -0.1f; - } - else - { + } else { leanOffset = 0; } - CG_RegisterWeapon( ps->weapon ); + CG_RegisterWeapon(ps->weapon); weapon = &cg_weapons[ps->weapon]; - wData = &weaponData[ps->weapon]; + wData = &weaponData[ps->weapon]; - memset (&hand, 0, sizeof(hand)); + memset(&hand, 0, sizeof(hand)); - if ( ps->weapon == WP_STUN_BATON || ps->weapon == WP_CONCUSSION ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - weapon->firingSound ); + if (ps->weapon == WP_STUN_BATON || ps->weapon == WP_CONCUSSION) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); } // set up gun position - CG_CalculateWeaponPosition( hand.origin, angles ); + CG_CalculateWeaponPosition(hand.origin, angles); vec3_t extraOffset; extraOffset[0] = extraOffset[1] = extraOffset[2] = 0.0f; - if( ps->weapon == WP_TUSKEN_RIFLE || ps->weapon == WP_NOGHRI_STICK || ps->weapon == WP_TUSKEN_STAFF ) - { + if (ps->weapon == WP_TUSKEN_RIFLE || ps->weapon == WP_NOGHRI_STICK || ps->weapon == WP_TUSKEN_STAFF) { extraOffset[0] = 2; extraOffset[1] = -3; extraOffset[2] = -6; } - VectorMA( hand.origin, cg_gun_x.value+extraOffset[0], cg.refdef.viewaxis[0], hand.origin ); - VectorMA( hand.origin, (cg_gun_y.value+leanOffset+extraOffset[1]), cg.refdef.viewaxis[1], hand.origin ); - VectorMA( hand.origin, (cg_gun_z.value+fovOffset+extraOffset[2]), cg.refdef.viewaxis[2], hand.origin ); - //VectorMA( hand.origin, 0, cg.refdef.viewaxis[0], hand.origin ); - //VectorMA( hand.origin, (0+leanOffset), cg.refdef.viewaxis[1], hand.origin ); - //VectorMA( hand.origin, (0+fovOffset), cg.refdef.viewaxis[2], hand.origin ); - - AnglesToAxis( angles, hand.axis ); + VectorMA(hand.origin, cg_gun_x.value + extraOffset[0], cg.refdef.viewaxis[0], hand.origin); + VectorMA(hand.origin, (cg_gun_y.value + leanOffset + extraOffset[1]), cg.refdef.viewaxis[1], hand.origin); + VectorMA(hand.origin, (cg_gun_z.value + fovOffset + extraOffset[2]), cg.refdef.viewaxis[2], hand.origin); + // VectorMA( hand.origin, 0, cg.refdef.viewaxis[0], hand.origin ); + // VectorMA( hand.origin, (0+leanOffset), cg.refdef.viewaxis[1], hand.origin ); + // VectorMA( hand.origin, (0+fovOffset), cg.refdef.viewaxis[2], hand.origin ); + AnglesToAxis(angles, hand.axis); - if ( cg_fovViewmodel.integer ) { - float fracDistFOV = tanf( cg.refdef.fov_x * ( M_PI/180 ) * 0.5f ); - float fracWeapFOV = (1.0f / fracDistFOV) * tanf( actualFOV * (M_PI / 180) * 0.5f ); - VectorScale( hand.axis[0], fracWeapFOV, hand.axis[0] ); + if (cg_fovViewmodel.integer) { + float fracDistFOV = tanf(cg.refdef.fov_x * (M_PI / 180) * 0.5f); + float fracWeapFOV = (1.0f / fracDistFOV) * tanf(actualFOV * (M_PI / 180) * 0.5f); + VectorScale(hand.axis[0], fracWeapFOV, hand.axis[0]); } // map torso animations to weapon animations #ifndef FINAL_BUILD - if ( cg_gun_frame.integer ) - { + if (cg_gun_frame.integer) { // development tool hand.frame = hand.oldframe = cg_gun_frame.integer; hand.backlerp = 0; - } - else + } else #endif { // get clientinfo for animation map - const clientInfo_t *ci = ¢->gent->client->clientInfo; - int torsoAnim = cent->gent->client->ps.torsoAnim;//pe.torso.animationNumber; + const clientInfo_t *ci = ¢->gent->client->clientInfo; + int torsoAnim = cent->gent->client->ps.torsoAnim; // pe.torso.animationNumber; float currentFrame; - int startFrame,endFrame,flags; + int startFrame, endFrame, flags; float animSpeed; - if (cent->gent->lowerLumbarBone>=0&& gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed,0) ) - { - hand.oldframe = CG_MapTorsoToWeaponFrame( ci,floor(currentFrame), torsoAnim, cent->currentState.weapon, ( cent->currentState.eFlags & EF_FIRING ) ); - hand.frame = CG_MapTorsoToWeaponFrame( ci,ceil(currentFrame), torsoAnim, cent->currentState.weapon, ( cent->currentState.eFlags & EF_FIRING ) ); - hand.backlerp=1.0f-(currentFrame-floor(currentFrame)); - if ( cg_debugAnim.integer == 1 && cent->currentState.clientNum == 0 ) - { - Com_Printf( "Torso frame %d to %d makes Weapon frame %d to %d\n", cent->pe.torso.oldFrame, cent->pe.torso.frame, hand.oldframe, hand.frame ); + if (cent->gent->lowerLumbarBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, + ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, 0)) { + hand.oldframe = CG_MapTorsoToWeaponFrame(ci, floor(currentFrame), torsoAnim, cent->currentState.weapon, (cent->currentState.eFlags & EF_FIRING)); + hand.frame = CG_MapTorsoToWeaponFrame(ci, ceil(currentFrame), torsoAnim, cent->currentState.weapon, (cent->currentState.eFlags & EF_FIRING)); + hand.backlerp = 1.0f - (currentFrame - floor(currentFrame)); + if (cg_debugAnim.integer == 1 && cent->currentState.clientNum == 0) { + Com_Printf("Torso frame %d to %d makes Weapon frame %d to %d\n", cent->pe.torso.oldFrame, cent->pe.torso.frame, hand.oldframe, hand.frame); } - } - else - { -// assert(0); // no idea what to do here - hand.oldframe=0; - hand.frame=0; - hand.backlerp=0.0f; + } else { + // assert(0); // no idea what to do here + hand.oldframe = 0; + hand.frame = 0; + hand.backlerp = 0.0f; } } // add the weapon(s) - FIXME: allow for 2 weapons generically, not just 2 sabers? - int numSabers = 1; - if ( cent->gent->client->ps.dualSabers ) - { + int numSabers = 1; + if (cent->gent->client->ps.dualSabers) { numSabers = 2; } - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - refEntity_t gun; - memset (&gun, 0, sizeof(gun)); + for (int saberNum = 0; saberNum < numSabers; saberNum++) { + refEntity_t gun; + memset(&gun, 0, sizeof(gun)); gun.hModel = weapon->weaponModel; - if (!gun.hModel) - { + if (!gun.hModel) { return; } - AnglesToAxis( angles, gun.axis ); - CG_PositionEntityOnTag( &gun, &hand, weapon->handsModel, "tag_weapon"); + AnglesToAxis(angles, gun.axis); + CG_PositionEntityOnTag(&gun, &hand, weapon->handsModel, "tag_weapon"); gun.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON; - //--------- + //--------- // OK, we are making an assumption here that if we have the phaser that it is always on.... - //FIXME: if saberInFlight, need to draw empty hand guiding it - if ( cent->gent && cent->gent->client && cent->currentState.weapon == WP_SABER ) - { + // FIXME: if saberInFlight, need to draw empty hand guiding it + if (cent->gent && cent->gent->client && cent->currentState.weapon == WP_SABER) { vec3_t org_, axis_[3]; - for ( int bladeNum = 0; bladeNum < cent->gent->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - //FIXME: need to get from tag_flash2 for saberstaff's second blade? - CG_GetTagWorldPosition( &gun, "tag_flash", org_, axis_ ); - //loop this and do for both blades - if ( cent->gent->client->ps.saber[0].blade[0].active && cent->gent->client->ps.saber[0].blade[0].length < cent->gent->client->ps.saber[0].blade[0].lengthMax ) - { - cent->gent->client->ps.saber[0].blade[0].length += cg.frametime*0.03; - if ( cent->gent->client->ps.saber[0].blade[0].length > cent->gent->client->ps.saber[0].blade[0].lengthMax ) - { + for (int bladeNum = 0; bladeNum < cent->gent->client->ps.saber[saberNum].numBlades; bladeNum++) { + // FIXME: need to get from tag_flash2 for saberstaff's second blade? + CG_GetTagWorldPosition(&gun, "tag_flash", org_, axis_); + // loop this and do for both blades + if (cent->gent->client->ps.saber[0].blade[0].active && + cent->gent->client->ps.saber[0].blade[0].length < cent->gent->client->ps.saber[0].blade[0].lengthMax) { + cent->gent->client->ps.saber[0].blade[0].length += cg.frametime * 0.03; + if (cent->gent->client->ps.saber[0].blade[0].length > cent->gent->client->ps.saber[0].blade[0].lengthMax) { cent->gent->client->ps.saber[0].blade[0].length = cent->gent->client->ps.saber[0].blade[0].lengthMax; } } - // FX_Saber( org_, axis_[0], cent->gent->client->ps.saberLength, 2.0 + Q_flrand(-1.0f, 1.0f) * 0.2f, cent->gent->client->ps.saberColor ); - if ( saberNum == 0 && bladeNum == 0 ) - { - VectorCopy( axis_[0], cent->gent->client->renderInfo.muzzleDir ); - } - else - {//need these points stored here when in 1st person saber + // FX_Saber( org_, axis_[0], cent->gent->client->ps.saberLength, 2.0 + Q_flrand(-1.0f, 1.0f) * 0.2f, cent->gent->client->ps.saberColor ); + if (saberNum == 0 && bladeNum == 0) { + VectorCopy(axis_[0], cent->gent->client->renderInfo.muzzleDir); + } else { // need these points stored here when in 1st person saber VectorCopy(org_, cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint); } - VectorCopy( axis_[0], cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir ); + VectorCopy(axis_[0], cent->gent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir); } } //--------- // CG_AddRefEntityWithPowerups( &gun, cent->currentState.powerups, cent->gent ); - cgi_R_AddRefEntityToScene( &gun ); + cgi_R_AddRefEntityToScene(&gun); - /* if ( ps->weapon == WP_STUN_BATON ) - { - gun.shaderRGBA[0] = gun.shaderRGBA[1] = gun.shaderRGBA[2] = 25; + /* if ( ps->weapon == WP_STUN_BATON ) + { + gun.shaderRGBA[0] = gun.shaderRGBA[1] = gun.shaderRGBA[2] = 25; - gun.customShader = cgi_R_RegisterShader( "gfx/effects/stunPass" ); - gun.renderfx = RF_RGB_TINT | RF_FIRST_PERSON | RF_DEPTHHACK; - cgi_R_AddRefEntityToScene( &gun ); - } - */ + gun.customShader = cgi_R_RegisterShader( "gfx/effects/stunPass" ); + gun.renderfx = RF_RGB_TINT | RF_FIRST_PERSON | RF_DEPTHHACK; + cgi_R_AddRefEntityToScene( &gun ); + } + */ // add the spinning barrel[s] - for (int i = 0; (i < wData->numBarrels); i++) - { - refEntity_t barrel; - memset( &barrel, 0, sizeof( barrel ) ); + for (int i = 0; (i < wData->numBarrels); i++) { + refEntity_t barrel; + memset(&barrel, 0, sizeof(barrel)); barrel.hModel = weapon->barrelModel[i]; - //VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); - //barrel.shadowPlane = parent->shadowPlane; + // VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); + // barrel.shadowPlane = parent->shadowPlane; barrel.renderfx = gun.renderfx; angles[YAW] = 0; angles[PITCH] = 0; - // if ( ps->weapon == WP_TETRION_DISRUPTOR) { - // angles[ROLL] = CG_MachinegunSpinAngle( cent ); - // } else { - angles[ROLL] = 0;//CG_MachinegunSpinAngle( cent ); - // } - - AnglesToAxis( angles, barrel.axis ); - if (!i) - { - CG_PositionRotatedEntityOnTag( &barrel, &hand, weapon->handsModel, "tag_barrel", NULL ); - } else - { - CG_PositionRotatedEntityOnTag( &barrel, &hand, weapon->handsModel, va("tag_barrel%d",i+1), NULL ); + // if ( ps->weapon == WP_TETRION_DISRUPTOR) { + // angles[ROLL] = CG_MachinegunSpinAngle( cent ); + // } else { + angles[ROLL] = 0; // CG_MachinegunSpinAngle( cent ); + // } + + AnglesToAxis(angles, barrel.axis); + if (!i) { + CG_PositionRotatedEntityOnTag(&barrel, &hand, weapon->handsModel, "tag_barrel", NULL); + } else { + CG_PositionRotatedEntityOnTag(&barrel, &hand, weapon->handsModel, va("tag_barrel%d", i + 1), NULL); } - cgi_R_AddRefEntityToScene( &barrel ); + cgi_R_AddRefEntityToScene(&barrel); } - memset (&flash, 0, sizeof(flash)); + memset(&flash, 0, sizeof(flash)); // Seems like we should always do this in case we have an animating muzzle flash....that way we can always store the correct muzzle dir, etc. - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); - CG_DoMuzzleFlash( cent, flash.origin, flash.axis[0], wData ); + CG_DoMuzzleFlash(cent, flash.origin, flash.axis[0], wData); - if ( cent->gent && cent->gent->client ) - { - if ( saberNum == 0 ) - { + if (cent->gent && cent->gent->client) { + if (saberNum == 0) { VectorCopy(flash.origin, cent->gent->client->renderInfo.muzzlePoint); VectorCopy(flash.axis[0], cent->gent->client->renderInfo.muzzleDir); } - // VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); + // VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); cent->gent->client->renderInfo.mPCalcTime = cg.time; - //CG_LightningBolt( cent, flash.origin ); + // CG_LightningBolt( cent, flash.origin ); } } // Do special charge bits //----------------------- - if (( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL ) - || ( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BLASTER_PISTOL ) - || ( ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING ) - || ( ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT )) - { - int shader = 0; - float val = 0.0f, scale = 1.0f; - vec3_t WHITE = {1.0f,1.0f,1.0f}; - - if ( ps->weapon == WP_BRYAR_PISTOL - || ps->weapon == WP_BLASTER_PISTOL ) - { + if ((ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL) || + (ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BLASTER_PISTOL) || (ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING) || + (ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT)) { + int shader = 0; + float val = 0.0f, scale = 1.0f; + vec3_t WHITE = {1.0f, 1.0f, 1.0f}; + + if (ps->weapon == WP_BRYAR_PISTOL || ps->weapon == WP_BLASTER_PISTOL) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/bryarFrontFlash" ); - } - else if ( ps->weapon == WP_BOWCASTER ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/bryarFrontFlash"); + } else if (ps->weapon == WP_BOWCASTER) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/greenFrontFlash" ); - } - else if ( ps->weapon == WP_DEMP2 ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/greenFrontFlash"); + } else if (ps->weapon == WP_DEMP2) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/misc/lightningFlash" ); + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/misc/lightningFlash"); scale = 1.75f; } - if ( val < 0.0f ) - { + if (val < 0.0f) { val = 0.0f; - } - else if ( val > 1.0f ) - { + } else if (val > 1.0f) { val = 1.0f; - CGCam_Shake( 0.1f, 100 ); - } - else - { - CGCam_Shake( val * val * 0.3f, 100 ); + CGCam_Shake(0.1f, 100); + } else { + CGCam_Shake(val * val * 0.3f, 100); } val += Q_flrand(0.0f, 1.0f) * 0.5f; - FX_AddSprite( flash.origin, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA | FX_DEPTH_HACK ); + FX_AddSprite(flash.origin, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, + FX_USE_ALPHA | FX_DEPTH_HACK); } // Check if the heavy repeater is finishing up a sustained burst //------------------------------- - if ( ps->weapon == WP_REPEATER && ps->weaponstate == WEAPON_FIRING ) - { - if ( cent->gent && cent->gent->client && cent->gent->client->ps.weaponstate != WEAPON_FIRING ) - { - int ct = 0; + if (ps->weapon == WP_REPEATER && ps->weaponstate == WEAPON_FIRING) { + if (cent->gent && cent->gent->client && cent->gent->client->ps.weaponstate != WEAPON_FIRING) { + int ct = 0; // the more continuous shots we've got, the more smoke we spawn - if ( cent->gent->client->ps.weaponShotCount > 60 ) { + if (cent->gent->client->ps.weaponShotCount > 60) { ct = 5; - } - else if ( cent->gent->client->ps.weaponShotCount > 35 ) { + } else if (cent->gent->client->ps.weaponShotCount > 35) { ct = 3; - } - else if ( cent->gent->client->ps.weaponShotCount > 15 ) { + } else if (cent->gent->client->ps.weaponShotCount > 15) { ct = 1; } - for ( int i = 0; i < ct; i++ ) - { - theFxScheduler.PlayEffect( "repeater/muzzle_smoke", cent->currentState.clientNum ); + for (int i = 0; i < ct; i++) { + theFxScheduler.PlayEffect("repeater/muzzle_smoke", cent->currentState.clientNum); } cent->gent->client->ps.weaponShotCount = 0; @@ -1380,55 +1261,35 @@ WEAPON SELECTION CG_WeaponCheck =================== */ -int CG_WeaponCheck( int weaponIndex ) -{ - int value; +int CG_WeaponCheck(int weaponIndex) { + int value; - if ( weaponIndex == WP_SABER) - { + if (weaponIndex == WP_SABER) { return qtrue; } + value = weaponData[weaponIndex].energyPerShot < weaponData[weaponIndex].altEnergyPerShot ? weaponData[weaponIndex].energyPerShot + : weaponData[weaponIndex].altEnergyPerShot; - value = weaponData[weaponIndex].energyPerShot < weaponData[weaponIndex].altEnergyPerShot - ? weaponData[weaponIndex].energyPerShot - : weaponData[weaponIndex].altEnergyPerShot; - - if( !cg.snap ) - { + if (!cg.snap) { return qfalse; } // check how much energy(ammo) it takes to fire this weapon against how much ammo we have - if ( value > cg.snap->ps.ammo[weaponData[weaponIndex].ammoIndex] ) - { + if (value > cg.snap->ps.ammo[weaponData[weaponIndex].ammoIndex]) { value = qfalse; - } - else - { + } else { value = qtrue; } return value; } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char *text); +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text); -const char *weaponDesc[13] = -{ -"SABER_DESC", -"NEW_BLASTER_PISTOL_DESC", -"BLASTER_RIFLE_DESC", -"DISRUPTOR_RIFLE_DESC", -"BOWCASTER_DESC", -"HEAVYREPEATER_DESC", -"DEMP2_DESC", -"FLECHETTE_DESC", -"MERR_SONN_DESC", -"THERMAL_DETONATOR_DESC", -"TRIP_MINE_DESC", -"DET_PACK_DESC", -"CONCUSSION_DESC", +const char *weaponDesc[13] = { + "SABER_DESC", "NEW_BLASTER_PISTOL_DESC", "BLASTER_RIFLE_DESC", "DISRUPTOR_RIFLE_DESC", "BOWCASTER_DESC", "HEAVYREPEATER_DESC", "DEMP2_DESC", + "FLECHETTE_DESC", "MERR_SONN_DESC", "THERMAL_DETONATOR_DESC", "TRIP_MINE_DESC", "DET_PACK_DESC", "CONCUSSION_DESC", }; /* @@ -1438,77 +1299,65 @@ CG_DrawDataPadWeaponSelect Allows user to cycle through the various weapons currently owned and view the description =================== */ -void CG_DrawDataPadWeaponSelect( void ) -{ - int i; - int weaponBitFlag,weaponCount,weaponSelectI; - int holdX; - int sideLeftIconCnt,sideRightIconCnt; - int holdCount,iconCnt; - char text[1024]={0}; +void CG_DrawDataPadWeaponSelect(void) { + int i; + int weaponBitFlag, weaponCount, weaponSelectI; + int holdX; + int sideLeftIconCnt, sideRightIconCnt; + int holdCount, iconCnt; + char text[1024] = {0}; qboolean drewConc = qfalse; // showing weapon select clears pickup item display, but not the blend blob cg.itemPickupTime = 0; - weaponBitFlag = cg.snap->ps.stats[ STAT_WEAPONS ]; + weaponBitFlag = cg.snap->ps.stats[STAT_WEAPONS]; // count the number of weapons owned weaponCount = 0; - for ( i = 1 ; i < 16 ; i++ ) - { - if ( weaponBitFlag & ( 1 << i ) ) - { + for (i = 1; i < 16; i++) { + if (weaponBitFlag & (1 << i)) { weaponCount++; } } - if (weaponCount == 0) // If no weapons, don't display + if (weaponCount == 0) // If no weapons, don't display { return; } - const short sideMax = 3; // Max number of icons on the side + const short sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = weaponCount - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = weaponCount - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (weaponCount > (2*sideMax)) // Go to the max on each side + } else if (weaponCount > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } // This seems to be a problem if datapad comes up too early - if (cg.DataPadWeaponSelect13) - { + } else if (cg.DataPadWeaponSelect > 13) { cg.DataPadWeaponSelect = 13; } // What weapon does the player currently have selected - if ( cg.DataPadWeaponSelect == WP_CONCUSSION ) - { + if (cg.DataPadWeaponSelect == WP_CONCUSSION) { weaponSelectI = WP_FLECHETTE; - } - else - { + } else { weaponSelectI = cg.DataPadWeaponSelect - 1; } - if (weaponSelectI<1) - { + if (weaponSelectI < 1) { weaponSelectI = 13; } @@ -1520,60 +1369,48 @@ void CG_DrawDataPadWeaponSelect( void ) const int centerXPos = 320; const int graphicYPos = 340; - // Left side ICONS // Work backwards from current icon - holdX = centerXPos - ((bigIconSize/2) + bigPad + smallIconSize); + holdX = centerXPos - ((bigIconSize / 2) + bigPad + smallIconSize); - cgi_R_SetColor( colorTable[CT_WHITE] ); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);weaponSelectI--) - { - if ( weaponSelectI == WP_CONCUSSION ) - { + cgi_R_SetColor(colorTable[CT_WHITE]); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); weaponSelectI--) { + if (weaponSelectI == WP_CONCUSSION) { weaponSelectI--; - } - else if ( weaponSelectI == WP_FLECHETTE && !drewConc && cg.DataPadWeaponSelect != WP_CONCUSSION ) - { + } else if (weaponSelectI == WP_FLECHETTE && !drewConc && cg.DataPadWeaponSelect != WP_CONCUSSION) { weaponSelectI = WP_CONCUSSION; } - if (weaponSelectI<1) - { + if (weaponSelectI < 1) { weaponSelectI = 13; } - if ( !(weaponBitFlag & ( 1 << weaponSelectI ))) // Does he have this weapon? + if (!(weaponBitFlag & (1 << weaponSelectI))) // Does he have this weapon? { - if ( weaponSelectI == WP_CONCUSSION ) - { + if (weaponSelectI == WP_CONCUSSION) { drewConc = qtrue; weaponSelectI = WP_ROCKET_LAUNCHER; } continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[weaponSelectI].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( weaponSelectI ); + if (weaponData[weaponSelectI].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(weaponSelectI); weaponInfo = &cg_weapons[weaponSelectI]; - if (!CG_WeaponCheck(weaponSelectI)) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(weaponSelectI)) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } - if ( weaponSelectI == WP_CONCUSSION ) - { + if (weaponSelectI == WP_CONCUSSION) { drewConc = qtrue; weaponSelectI = WP_ROCKET_LAUNCHER; } @@ -1582,116 +1419,90 @@ void CG_DrawDataPadWeaponSelect( void ) // Current Center Icon cgi_R_SetColor(colorTable[CT_WHITE]); - if (weaponData[cg.DataPadWeaponSelect].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( cg.DataPadWeaponSelect ); + if (weaponData[cg.DataPadWeaponSelect].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(cg.DataPadWeaponSelect); weaponInfo = &cg_weapons[cg.DataPadWeaponSelect]; - // Draw graphic to show weapon has ammo or no ammo - if (!CG_WeaponCheck(cg.DataPadWeaponSelect)) - { - CG_DrawPic( centerXPos-(bigIconSize/2), (graphicYPos-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( centerXPos-(bigIconSize/2), (graphicYPos-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIcon ); + // Draw graphic to show weapon has ammo or no ammo + if (!CG_WeaponCheck(cg.DataPadWeaponSelect)) { + CG_DrawPic(centerXPos - (bigIconSize / 2), (graphicYPos - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, + weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(centerXPos - (bigIconSize / 2), (graphicYPos - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, + weaponInfo->weaponIcon); } } - if ( cg.DataPadWeaponSelect == WP_CONCUSSION ) - { + if (cg.DataPadWeaponSelect == WP_CONCUSSION) { weaponSelectI = WP_ROCKET_LAUNCHER; - } - else - { + } else { weaponSelectI = cg.DataPadWeaponSelect + 1; } - if (weaponSelectI> 13) - { + if (weaponSelectI > 13) { weaponSelectI = 1; } // Right side ICONS // Work forwards from current icon cgi_R_SetColor(colorTable[CT_WHITE]); - holdX = centerXPos + (bigIconSize/2) + bigPad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);weaponSelectI++) - { - if ( weaponSelectI == WP_CONCUSSION ) - { + holdX = centerXPos + (bigIconSize / 2) + bigPad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); weaponSelectI++) { + if (weaponSelectI == WP_CONCUSSION) { weaponSelectI++; - } - else if ( weaponSelectI == WP_ROCKET_LAUNCHER && !drewConc && cg.DataPadWeaponSelect != WP_CONCUSSION ) - { + } else if (weaponSelectI == WP_ROCKET_LAUNCHER && !drewConc && cg.DataPadWeaponSelect != WP_CONCUSSION) { weaponSelectI = WP_CONCUSSION; } - if (weaponSelectI>13) - { + if (weaponSelectI > 13) { weaponSelectI = 1; } - if ( !(weaponBitFlag & ( 1 << weaponSelectI ))) // Does he have this weapon? + if (!(weaponBitFlag & (1 << weaponSelectI))) // Does he have this weapon? { - if ( weaponSelectI == WP_CONCUSSION ) - { + if (weaponSelectI == WP_CONCUSSION) { drewConc = qtrue; weaponSelectI = WP_FLECHETTE; } continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[weaponSelectI].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( weaponSelectI ); + if (weaponData[weaponSelectI].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(weaponSelectI); weaponInfo = &cg_weapons[weaponSelectI]; // Draw graphic to show weapon has ammo or no ammo - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, graphicYPos, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } - if ( weaponSelectI == WP_CONCUSSION ) - { + if (weaponSelectI == WP_CONCUSSION) { drewConc = qtrue; weaponSelectI = WP_FLECHETTE; } } // Print the weapon description - cgi_SP_GetStringTextString( va("SP_INGAME_%s",weaponDesc[cg.DataPadWeaponSelect-1]), text, sizeof(text) ); + cgi_SP_GetStringTextString(va("SP_INGAME_%s", weaponDesc[cg.DataPadWeaponSelect - 1]), text, sizeof(text)); - if (text[0]) - { + if (text[0]) { const short textboxXPos = 40; const short textboxYPos = 60; - const int textboxWidth = 560; - const int textboxHeight = 300; - const float textScale = 1.0f; + const int textboxWidth = 560; + const int textboxHeight = 300; + const float textScale = 1.0f; - CG_DisplayBoxedText( - textboxXPos, textboxYPos, - textboxWidth, textboxHeight, - text, - 4, - textScale, - colorTable[CT_WHITE] - ); + CG_DisplayBoxedText(textboxXPos, textboxYPos, textboxWidth, textboxHeight, text, 4, textScale, colorTable[CT_WHITE]); } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -1701,43 +1512,42 @@ CG_DrawDataPadIconBackground Draw the proper background graphic for the icons being displayed on the datapad =================== */ -void CG_DrawDataPadIconBackground(const int backgroundType) -{ -// const int graphicXPos = 40; -// const int graphicYPos = 340; -// const short graphicHeight = 60; -// const short graphicWidth = 560; -// qhandle_t background; +void CG_DrawDataPadIconBackground(const int backgroundType) { + // const int graphicXPos = 40; + // const int graphicYPos = 340; + // const short graphicHeight = 60; + // const short graphicWidth = 560; + // qhandle_t background; -/* - if (backgroundType == ICON_INVENTORY) // Display inventory background? - { - background = cgs.media.inventoryIconBackground; - } - else if (backgroundType == ICON_WEAPONS) // Display weapon background? - { - background = cgs.media.weaponIconBackground; - } - else // Display force background? - { - background = cgs.media.forceIconBackground; - } + /* + if (backgroundType == ICON_INVENTORY) // Display inventory background? + { + background = cgs.media.inventoryIconBackground; + } + else if (backgroundType == ICON_WEAPONS) // Display weapon background? + { + background = cgs.media.weaponIconBackground; + } + else // Display force background? + { + background = cgs.media.forceIconBackground; + } - cgi_R_SetColor( colorTable[CT_WHITE] ); // Let the graphic set the color + cgi_R_SetColor( colorTable[CT_WHITE] ); // Let the graphic set the color - CG_DrawPic( graphicXPos, - graphicYPos+(graphicHeight/2), - graphicWidth, - -graphicHeight, - background); // Top half + CG_DrawPic( graphicXPos, + graphicYPos+(graphicHeight/2), + graphicWidth, + -graphicHeight, + background); // Top half - CG_DrawPic( graphicXPos, - graphicYPos+(graphicHeight/2), - graphicWidth, - graphicHeight, - background); // Bottom half + CG_DrawPic( graphicXPos, + graphicYPos+(graphicHeight/2), + graphicWidth, + graphicHeight, + background); // Bottom half -*/ + */ } /* @@ -1745,18 +1555,15 @@ void CG_DrawDataPadIconBackground(const int backgroundType) SetWeaponSelectTime =============== */ -void SetWeaponSelectTime(void) -{ +void SetWeaponSelectTime(void) { - if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Inventory HUD was currently active to just swap it out with Force HUD - ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD + if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Inventory HUD was currently active to just swap it out with Force HUD + ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD { cg.inventorySelectTime = 0; cg.forcepowerSelectTime = 0; cg.weaponSelectTime = cg.time + 130.0f; - } - else - { + } else { cg.weaponSelectTime = cg.time; } } @@ -1766,90 +1573,79 @@ void SetWeaponSelectTime(void) CG_DrawWeaponSelect =================== */ -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern bool G_IsRidingTurboVehicle( gentity_t *ent ); - -void CG_DrawWeaponSelect( void ) -{ - int i; - int bits; - int count; - int smallIconSize,bigIconSize; - int holdX,x,y,x2,y2,w2,h2,pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; - //int height; - vec4_t calcColor; - vec4_t textColor = { .875f, .718f, .121f, 1.0f }; - int yOffset = 0; - bool isOnVeh = false; +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern bool G_IsRidingTurboVehicle(gentity_t *ent); + +void CG_DrawWeaponSelect(void) { + int i; + int bits; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, x2, y2, w2, h2, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + // int height; + vec4_t calcColor; + vec4_t textColor = {.875f, .718f, .121f, 1.0f}; + int yOffset = 0; + bool isOnVeh = false; qboolean drewConc = qfalse; - if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)ps.stats[ STAT_WEAPONS ]; + bits = cg.snap->ps.stats[STAT_WEAPONS]; // count the number of weapons owned count = 0; - isOnVeh = (G_IsRidingVehicle(cg_entities[0].gent)!=0); - for ( i = 1 ; i < MAX_PLAYER_WEAPONS ; i++ ) - { - if ((bits & ( 1 << i )) && - (!isOnVeh || i==WP_NONE || i==WP_SABER || i==WP_BLASTER)) - { + isOnVeh = (G_IsRidingVehicle(cg_entities[0].gent) != 0); + for (i = 1; i < MAX_PLAYER_WEAPONS; i++) { + if ((bits & (1 << i)) && (!isOnVeh || i == WP_NONE || i == WP_SABER || i == WP_BLASTER)) { count++; } } - if (count == 0) // If no weapons, don't display + if (count == 0) // If no weapons, don't display { return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } - if ( cg.weaponSelect == WP_CONCUSSION ) - { + if (cg.weaponSelect == WP_CONCUSSION) { i = WP_FLECHETTE; - } - else - { + } else { i = cg.weaponSelect - 1; } - if (i<1) - { + if (i < 1) { i = MAX_PLAYER_WEAPONS; } @@ -1857,8 +1653,7 @@ void CG_DrawWeaponSelect( void ) bigIconSize = 80; pad = 12; - if (!cgi_UI_GetMenuInfo("weaponselecthud",&x2,&y2,&w2,&h2)) - { + if (!cgi_UI_GetMenuInfo("weaponselecthud", &x2, &y2, &w2, &h2)) { return; } x = 320; @@ -1867,244 +1662,194 @@ void CG_DrawWeaponSelect( void ) // Background memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); calcColor[3] = .60f; - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Left side ICONS - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; drewConc = qfalse; - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if ( i == WP_CONCUSSION ) - { + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i == WP_CONCUSSION) { i--; - } - else if ( i == WP_FLECHETTE && !drewConc && cg.weaponSelect != WP_CONCUSSION ) - { + } else if (i == WP_FLECHETTE && !drewConc && cg.weaponSelect != WP_CONCUSSION) { i = WP_CONCUSSION; } - if (i<1) - { + if (i < 1) { i = MAX_PLAYER_WEAPONS; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } continue; } - if (isOnVeh) - { - if ( i != WP_NONE && i!=WP_SABER && i!=WP_BLASTER ) - { - if ( i == WP_CONCUSSION ) - { + if (isOnVeh) { + if (i != WP_NONE && i != WP_SABER && i != WP_BLASTER) { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } - continue; // Don't draw anything else if on a vehicle + continue; // Don't draw anything else if on a vehicle } } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; + // height = bigIconSize * cg.iconHUDPercent; cgi_R_SetColor(NULL); - if (weaponData[cg.weaponSelect].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( cg.weaponSelect ); + if (weaponData[cg.weaponSelect].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(cg.weaponSelect); weaponInfo = &cg_weapons[cg.weaponSelect]; - if (!CG_WeaponCheck(cg.weaponSelect)) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10+yOffset, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10+yOffset, bigIconSize, bigIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(cg.weaponSelect)) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize, bigIconSize, weaponInfo->weaponIcon); } } - if ( cg.weaponSelect == WP_CONCUSSION ) - { + if (cg.weaponSelect == WP_CONCUSSION) { i = WP_ROCKET_LAUNCHER; - } - else - { + } else { i = cg.weaponSelect + 1; } - if (i> MAX_PLAYER_WEAPONS) - { + if (i > MAX_PLAYER_WEAPONS) { i = 1; } // Right side ICONS // Work forwards from current icon - cgi_R_SetColor( calcColor); - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; + cgi_R_SetColor(calcColor); + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; drewConc = qfalse; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if ( i == WP_CONCUSSION ) - { + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i == WP_CONCUSSION) { i++; - } - else if ( i == WP_ROCKET_LAUNCHER && !drewConc && cg.weaponSelect != WP_CONCUSSION ) - { + } else if (i == WP_ROCKET_LAUNCHER && !drewConc && cg.weaponSelect != WP_CONCUSSION) { i = WP_CONCUSSION; } - if (i>MAX_PLAYER_WEAPONS) - { + if (i > MAX_PLAYER_WEAPONS) { i = 1; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_FLECHETTE; } continue; } - if (isOnVeh) - { - if ( i != WP_NONE && i!=WP_SABER && i!=WP_BLASTER ) - { - if ( i == WP_CONCUSSION ) - { + if (isOnVeh) { + if (i != WP_NONE && i != WP_SABER && i != WP_BLASTER) { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_FLECHETTE; } - continue; // Don't draw anything else if on a vehicle + continue; // Don't draw anything else if on a vehicle } } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; // No ammo for this weapon? - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_FLECHETTE; } } - gitem_t *item = cg_weapons[ cg.weaponSelect ].item; + gitem_t *item = cg_weapons[cg.weaponSelect].item; // draw the selected name - if ( item && item->classname && item->classname[0] ) - { + if (item && item->classname && item->classname[0]) { char text[1024]; - if ( cgi_SP_GetStringTextString( va("SP_INGAME_%s",item->classname), text, sizeof( text ))) - { + if (cgi_SP_GetStringTextString(va("SP_INGAME_%s", item->classname), text, sizeof(text))) { int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - int x = ( SCREEN_WIDTH - w ) / 2; - cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24)+yOffset, text, textColor, cgs.media.qhFontSmall, -1, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; + cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24) + yOffset, text, textColor, cgs.media.qhFontSmall, -1, 1.0f); } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - /* =============== CG_WeaponSelectable =============== */ -qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) -{ - int usage_for_weap; +qboolean CG_WeaponSelectable(int i, int original, qboolean dpMode) { + int usage_for_weap; - if (i > MAX_PLAYER_WEAPONS) - { + if (i > MAX_PLAYER_WEAPONS) { #ifndef FINAL_BUILD - Com_Printf("CG_WeaponSelectable() passed illegal index of %d!\n",i); + Com_Printf("CG_WeaponSelectable() passed illegal index of %d!\n", i); #endif return qfalse; } - if ( cg.weaponSelectTime + 200 > cg.time ) - {//TEMP standard weapon cycle debounce for E3 because G2 can't keep up with fast weapon changes + if (cg.weaponSelectTime + 200 > cg.time) { // TEMP standard weapon cycle debounce for E3 because G2 can't keep up with fast weapon changes return qfalse; } - //FIXME: this doesn't work below, can still cycle too fast! - if ( original == WP_SABER && cg.weaponSelectTime + 500 > cg.time ) - {//when switch to lightsaber, have to stay there for at least half a second! + // FIXME: this doesn't work below, can still cycle too fast! + if (original == WP_SABER && cg.weaponSelectTime + 500 > cg.time) { // when switch to lightsaber, have to stay there for at least half a second! return qfalse; } - if ( G_IsRidingVehicle(cg_entities[0].gent) ) - { - if (G_IsRidingTurboVehicle(cg_entities[0].gent) || (i!=WP_NONE && i!=WP_SABER && i!=WP_BLASTER) ) - { + if (G_IsRidingVehicle(cg_entities[0].gent)) { + if (G_IsRidingTurboVehicle(cg_entities[0].gent) || (i != WP_NONE && i != WP_SABER && i != WP_BLASTER)) { return qfalse; } } - if (( weaponData[i].ammoIndex != AMMO_NONE ) && !dpMode ) - {//weapon uses ammo, see if we have any - usage_for_weap = weaponData[i].energyPerShot < weaponData[i].altEnergyPerShot - ? weaponData[i].energyPerShot - : weaponData[i].altEnergyPerShot; + if ((weaponData[i].ammoIndex != AMMO_NONE) && !dpMode) { // weapon uses ammo, see if we have any + usage_for_weap = weaponData[i].energyPerShot < weaponData[i].altEnergyPerShot ? weaponData[i].energyPerShot : weaponData[i].altEnergyPerShot; - if ( cg.snap->ps.ammo[weaponData[i].ammoIndex] - usage_for_weap < 0 ) - { - if ( i != WP_DET_PACK ) // detpack can be switched to...should possibly check if there are any stuck to a wall somewhere? + if (cg.snap->ps.ammo[weaponData[i].ammoIndex] - usage_for_weap < 0) { + if (i != WP_DET_PACK) // detpack can be switched to...should possibly check if there are any stuck to a wall somewhere? { // This weapon doesn't have enough ammo to shoot either the main or the alt-fire return qfalse; @@ -2112,8 +1857,7 @@ qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) } } - if (!(cg.snap->ps.stats[ STAT_WEAPONS ] & ( 1 << i ))) - { + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << i))) { // Don't have this weapon to start with. return qfalse; } @@ -2121,44 +1865,30 @@ qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) return qtrue; } -void CG_ToggleATSTWeapon( void ) -{ - if ( cg.weaponSelect == WP_ATST_MAIN ) - { +void CG_ToggleATSTWeapon(void) { + if (cg.weaponSelect == WP_ATST_MAIN) { cg.weaponSelect = WP_ATST_SIDE; - } - else - { + } else { cg.weaponSelect = WP_ATST_MAIN; } -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); } -void CG_PlayerLockedWeaponSpeech( int jumping ) -{ -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); +void CG_PlayerLockedWeaponSpeech(int jumping) { + extern qboolean Q3_TaskIDPending(gentity_t * ent, taskID_t taskType); static int speechDebounceTime = 0; - if ( !in_camera ) - {//not in a cinematic - if ( speechDebounceTime < cg.time ) - {//spoke more than 3 seconds ago - if ( !Q3_TaskIDPending( &g_entities[0], TID_CHAN_VOICE ) ) - {//not waiting on a scripted sound to finish - if( !jumping ) - { - if( Q_flrand(0.0f, 1.0f) > 0.5 ) - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/09kyk015.wav" )); - } - else - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/09kyk016.wav" )); + if (!in_camera) { // not in a cinematic + if (speechDebounceTime < cg.time) { // spoke more than 3 seconds ago + if (!Q3_TaskIDPending(&g_entities[0], TID_CHAN_VOICE)) { // not waiting on a scripted sound to finish + if (!jumping) { + if (Q_flrand(0.0f, 1.0f) > 0.5) { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/09kyk015.wav")); + } else { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/09kyk016.wav")); } - } - else - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/16kyk007.wav" )); + } else { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/16kyk007.wav")); } speechDebounceTime = cg.time + 3000; } @@ -2170,11 +1900,11 @@ extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); CG_NextWeapon_f =============== */ -void CG_NextWeapon_f( void ) { - int i; - int original; +void CG_NextWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2183,31 +1913,26 @@ void CG_NextWeapon_f( void ) { } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } @@ -2215,39 +1940,29 @@ void CG_NextWeapon_f( void ) { original = cg.weaponSelect; int firstWeapon = FIRST_WEAPON; - if (G_IsRidingVehicle(&g_entities[cg.snap->ps.viewEntity])) - { - firstWeapon = 0; // include WP_NONE here + if (G_IsRidingVehicle(&g_entities[cg.snap->ps.viewEntity])) { + firstWeapon = 0; // include WP_NONE here } - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.weaponSelect == WP_FLECHETTE ) - { + if (cg.weaponSelect == WP_FLECHETTE) { cg.weaponSelect = WP_CONCUSSION; - } - else if ( cg.weaponSelect == WP_CONCUSSION ) - { + } else if (cg.weaponSelect == WP_CONCUSSION) { cg.weaponSelect = WP_ROCKET_LAUNCHER; - } - else if ( cg.weaponSelect == WP_DET_PACK ) - { + } else if (cg.weaponSelect == WP_DET_PACK) { cg.weaponSelect = firstWeapon; - } - else - { + } else { cg.weaponSelect++; } - if ( cg.weaponSelect < firstWeapon || cg.weaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.weaponSelect < firstWeapon || cg.weaponSelect > MAX_PLAYER_WEAPONS) { cg.weaponSelect = firstWeapon; } - if ( CG_WeaponSelectable( cg.weaponSelect, original, qfalse ) ) - { -// cg.weaponSelectTime = cg.time; + if (CG_WeaponSelectable(cg.weaponSelect, original, qfalse)) { + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); return; } @@ -2261,11 +1976,11 @@ void CG_NextWeapon_f( void ) { CG_DPNextWeapon_f =============== */ -void CG_DPNextWeapon_f( void ) { - int i; - int original; +void CG_DPNextWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2276,33 +1991,24 @@ void CG_DPNextWeapon_f( void ) { original = cg.DataPadWeaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.DataPadWeaponSelect == WP_FLECHETTE ) - { + if (cg.DataPadWeaponSelect == WP_FLECHETTE) { cg.DataPadWeaponSelect = WP_CONCUSSION; - } - else if ( cg.DataPadWeaponSelect == WP_CONCUSSION ) - { + } else if (cg.DataPadWeaponSelect == WP_CONCUSSION) { cg.DataPadWeaponSelect = WP_ROCKET_LAUNCHER; - } - else if ( cg.DataPadWeaponSelect == WP_DET_PACK ) - { + } else if (cg.DataPadWeaponSelect == WP_DET_PACK) { cg.DataPadWeaponSelect = FIRST_WEAPON; - } - else - { + } else { cg.DataPadWeaponSelect++; } - if ( cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { cg.DataPadWeaponSelect = FIRST_WEAPON; } - if ( CG_WeaponSelectable( cg.DataPadWeaponSelect, original, qtrue ) ) - { + if (CG_WeaponSelectable(cg.DataPadWeaponSelect, original, qtrue)) { return; } } @@ -2315,13 +2021,11 @@ void CG_DPNextWeapon_f( void ) { CG_DPPrevWeapon_f =============== */ -void CG_DPPrevWeapon_f( void ) -{ - int i; - int original; +void CG_DPPrevWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } @@ -2334,34 +2038,24 @@ void CG_DPPrevWeapon_f( void ) original = cg.DataPadWeaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.DataPadWeaponSelect == WP_ROCKET_LAUNCHER ) - { + if (cg.DataPadWeaponSelect == WP_ROCKET_LAUNCHER) { cg.DataPadWeaponSelect = WP_CONCUSSION; - } - else if ( cg.DataPadWeaponSelect == WP_CONCUSSION ) - { + } else if (cg.DataPadWeaponSelect == WP_CONCUSSION) { cg.DataPadWeaponSelect = WP_FLECHETTE; - } - else if ( cg.DataPadWeaponSelect == WP_MELEE ) - { + } else if (cg.DataPadWeaponSelect == WP_MELEE) { cg.DataPadWeaponSelect = WP_DET_PACK; - } - else - { + } else { cg.DataPadWeaponSelect--; } - if ( cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) - { + if (cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { cg.DataPadWeaponSelect = MAX_PLAYER_WEAPONS; } - if ( CG_WeaponSelectable( cg.DataPadWeaponSelect, original, qtrue ) ) - { + if (CG_WeaponSelectable(cg.DataPadWeaponSelect, original, qtrue)) { return; } } @@ -2374,11 +2068,11 @@ void CG_DPPrevWeapon_f( void ) CG_PrevWeapon_f =============== */ -void CG_PrevWeapon_f( void ) { - int i; - int original; +void CG_PrevWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2387,31 +2081,26 @@ void CG_PrevWeapon_f( void ) { } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } @@ -2419,40 +2108,30 @@ void CG_PrevWeapon_f( void ) { original = cg.weaponSelect; int firstWeapon = FIRST_WEAPON; - if (G_IsRidingVehicle(&g_entities[cg.snap->ps.viewEntity])) - { - firstWeapon = 0; // include WP_NONE here + if (G_IsRidingVehicle(&g_entities[cg.snap->ps.viewEntity])) { + firstWeapon = 0; // include WP_NONE here } - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.weaponSelect == WP_ROCKET_LAUNCHER ) - { + if (cg.weaponSelect == WP_ROCKET_LAUNCHER) { cg.weaponSelect = WP_CONCUSSION; - } - else if ( cg.weaponSelect == WP_CONCUSSION ) - { + } else if (cg.weaponSelect == WP_CONCUSSION) { cg.weaponSelect = WP_FLECHETTE; - } - else if ( cg.weaponSelect == WP_MELEE ) - { + } else if (cg.weaponSelect == WP_MELEE) { cg.weaponSelect = WP_DET_PACK; - } - else - { + } else { cg.weaponSelect--; } - - if ( cg.weaponSelect < firstWeapon || cg.weaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.weaponSelect < firstWeapon || cg.weaponSelect > MAX_PLAYER_WEAPONS) { cg.weaponSelect = MAX_PLAYER_WEAPONS; } - if ( CG_WeaponSelectable( cg.weaponSelect, original, qfalse ) ) - { + if (CG_WeaponSelectable(cg.weaponSelect, original, qfalse)) { SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; return; } } @@ -2465,46 +2144,38 @@ void CG_ChangeWeapon( int num ) Meant to be called from the normal game, so checks the game-side weapon inventory data */ -void CG_ChangeWeapon( int num ) -{ - gentity_t *player = &g_entities[0]; +void CG_ChangeWeapon(int num) { + gentity_t *player = &g_entities[0]; - if ( num < WP_NONE || num >= WP_NUM_WEAPONS ) - { + if (num < WP_NONE || num >= WP_NUM_WEAPONS) { return; } - if( player->flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (player->flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if ( player->client != NULL && !(player->client->ps.stats[STAT_WEAPONS] & ( 1 << num )) ) - { - return; // don't have the weapon + if (player->client != NULL && !(player->client->ps.stats[STAT_WEAPONS] & (1 << num))) { + return; // don't have the weapon } // because we don't have an empty hand model for the thermal, don't allow selecting that weapon if it has no ammo - if ( num == WP_THERMAL ) - { - if ( cg.snap && cg.snap->ps.ammo[AMMO_THERMAL] <= 0 ) - { + if (num == WP_THERMAL) { + if (cg.snap && cg.snap->ps.ammo[AMMO_THERMAL] <= 0) { return; } } // because we don't have an empty hand model for the thermal, don't allow selecting that weapon if it has no ammo - if ( num == WP_TRIP_MINE ) - { - if ( cg.snap && cg.snap->ps.ammo[AMMO_TRIPMINE] <= 0 ) - { + if (num == WP_TRIP_MINE) { + if (cg.snap && cg.snap->ps.ammo[AMMO_TRIPMINE] <= 0) { return; } } SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; cg.weaponSelect = num; } @@ -2513,16 +2184,14 @@ void CG_ChangeWeapon( int num ) CG_Weapon_f =============== */ -void CG_Weapon_f( void ) -{ - int num; +void CG_Weapon_f(void) { + int num; - if ( cg.weaponSelectTime + 200 > cg.time ) - { + if (cg.weaponSelectTime + 200 > cg.time) { return; } - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2531,114 +2200,90 @@ void CG_Weapon_f( void ) } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } - num = atoi( CG_Argv( 1 ) ); + num = atoi(CG_Argv(1)); - if ( num < WP_NONE || num >= WP_NUM_WEAPONS ) { + if (num < WP_NONE || num >= WP_NUM_WEAPONS) { return; } - if ( num == WP_SABER ) - {//lightsaber - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - {//don't have saber, try stun baton - if ( ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << WP_STUN_BATON ) ) ) - { + if (num == WP_SABER) { // lightsaber + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { // don't have saber, try stun baton + if ((cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_STUN_BATON))) { num = WP_STUN_BATON; - } - else - {//don't have stun baton, use fists + } else { // don't have stun baton, use fists num = WP_MELEE; } - } - else if ( num == cg.snap->ps.weapon ) - {//already have it up, let's try to toggle it - if ( !in_camera ) - {//player can't activate/deactivate saber when in a cinematic - //can't toggle it if not holding it and not controlling it or dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] > 0 && (!cg_entities[0].gent->client->ps.saberInFlight || (&g_entities[cg_entities[0].gent->client->ps.saberEntityNum] != NULL && g_entities[cg_entities[0].gent->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR) ) ) - {//it's either in-hand or it's under telekinetic control - if ( cg_entities[0].gent->client->ps.SaberActive() ) - {//a saber is on - if ( cg_entities[0].gent->client->ps.dualSabers - && cg_entities[0].gent->client->ps.saber[1].Active() ) - {//2nd saber is on, turn it off, too + } else if (num == cg.snap->ps.weapon) { // already have it up, let's try to toggle it + if (!in_camera) { // player can't activate/deactivate saber when in a cinematic + // can't toggle it if not holding it and not controlling it or dead + if (cg.predicted_player_state.stats[STAT_HEALTH] > 0 && + (!cg_entities[0].gent->client->ps.saberInFlight || (&g_entities[cg_entities[0].gent->client->ps.saberEntityNum] != NULL && + g_entities[cg_entities[0].gent->client->ps.saberEntityNum].s.pos.trType == + TR_LINEAR))) { // it's either in-hand or it's under telekinetic control + if (cg_entities[0].gent->client->ps.SaberActive()) { // a saber is on + if (cg_entities[0].gent->client->ps.dualSabers && + cg_entities[0].gent->client->ps.saber[1].Active()) { // 2nd saber is on, turn it off, too cg_entities[0].gent->client->ps.saber[1].Deactivate(); } cg_entities[0].gent->client->ps.saber[0].Deactivate(); - if ( cg_entities[0].gent->client->ps.saberInFlight ) - {//play it on the saber - cgi_S_UpdateEntityPosition( cg_entities[0].gent->client->ps.saberEntityNum, g_entities[cg_entities[0].gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cg_entities[0].gent->client->ps.saberEntityNum, CHAN_AUTO, cgs.sound_precache[cg_entities[0].gent->client->ps.saber[0].soundOff] ); - } - else - { - cgi_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[cg_entities[0].gent->client->ps.saber[0].soundOff] ); + if (cg_entities[0].gent->client->ps.saberInFlight) { // play it on the saber + cgi_S_UpdateEntityPosition(cg_entities[0].gent->client->ps.saberEntityNum, + g_entities[cg_entities[0].gent->client->ps.saberEntityNum].currentOrigin); + cgi_S_StartSound(NULL, cg_entities[0].gent->client->ps.saberEntityNum, CHAN_AUTO, + cgs.sound_precache[cg_entities[0].gent->client->ps.saber[0].soundOff]); + } else { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[cg_entities[0].gent->client->ps.saber[0].soundOff]); } - } - else - {//turn them both on + } else { // turn them both on cg_entities[0].gent->client->ps.SaberActivate(); } } } } - } - else if ( num >= WP_THERMAL && num <= WP_DET_PACK ) // these weapons cycle + } else if (num >= WP_THERMAL && num <= WP_DET_PACK) // these weapons cycle { int weap, i = 0; - if ( cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK ) - { + if (cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK) { // already in cycle range so start with next cycle item weap = cg.snap->ps.weapon + 1; - } - else - { + } else { // not in cycle range, so start with thermal detonator weap = WP_THERMAL; } // prevent an endless loop - while ( i <= 4 ) - { - if ( weap > WP_DET_PACK ) - { + while (i <= 4) { + if (weap > WP_DET_PACK) { weap = WP_THERMAL; } - if ( cg.snap->ps.ammo[weaponData[weap].ammoIndex] > 0 || weap == WP_DET_PACK ) - { - if ( CG_WeaponSelectable( weap, cg.snap->ps.weapon, qfalse ) ) - { + if (cg.snap->ps.ammo[weaponData[weap].ammoIndex] > 0 || weap == WP_DET_PACK) { + if (CG_WeaponSelectable(weap, cg.snap->ps.weapon, qfalse)) { num = weap; break; } @@ -2649,13 +2294,12 @@ void CG_Weapon_f( void ) } } - if (!CG_WeaponSelectable(num, cg.snap->ps.weapon, qfalse)) - { + if (!CG_WeaponSelectable(num, cg.snap->ps.weapon, qfalse)) { return; } SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; cg.weaponSelect = num; } @@ -2666,46 +2310,37 @@ CG_OutOfAmmoChange The current weapon has just run out of ammo =================== */ -void CG_OutOfAmmoChange( void ) { - int i; - int original; +void CG_OutOfAmmoChange(void) { + int i; + int original; - if ( cg.weaponSelectTime + 200 > cg.time ) + if (cg.weaponSelectTime + 200 > cg.time) return; - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } original = cg.weaponSelect; - for ( i = WP_ROCKET_LAUNCHER; i > 0 ; i-- ) - { + for (i = WP_ROCKET_LAUNCHER; i > 0; i--) { // We don't want the emplaced, melee, or explosive devices here - if ( original != i && CG_WeaponSelectable( i, original, qfalse ) ) - { + if (original != i && CG_WeaponSelectable(i, original, qfalse)) { SetWeaponSelectTime(); cg.weaponSelect = i; break; } } - if ( cg_autoswitch.integer != 1 ) - { + if (cg_autoswitch.integer != 1) { // didn't have that, so try these. Start with thermal... - for ( i = WP_THERMAL; i <= WP_DET_PACK; i++ ) - { + for (i = WP_THERMAL; i <= WP_DET_PACK; i++) { // We don't want the emplaced, or melee here - if ( original != i && CG_WeaponSelectable( i, original, qfalse ) ) - { - if ( i == WP_DET_PACK && cg.snap->ps.ammo[weaponData[i].ammoIndex] <= 0 ) - { + if (original != i && CG_WeaponSelectable(i, original, qfalse)) { + if (i == WP_DET_PACK && cg.snap->ps.ammo[weaponData[i].ammoIndex] <= 0) { // crap, no point in switching to this - } - else - { + } else { SetWeaponSelectTime(); cg.weaponSelect = i; break; @@ -2715,15 +2350,12 @@ void CG_OutOfAmmoChange( void ) { } // try stun baton as a last ditch effort - if ( CG_WeaponSelectable( WP_STUN_BATON, original, qfalse )) - { + if (CG_WeaponSelectable(WP_STUN_BATON, original, qfalse)) { SetWeaponSelectTime(); cg.weaponSelect = WP_STUN_BATON; } } - - /* =================================================================================================== @@ -2739,31 +2371,26 @@ CG_FireWeapon Caused by an EV_FIRE_WEAPON event ================ */ -void CG_FireWeapon( centity_t *cent, qboolean alt_fire ) -{ +void CG_FireWeapon(centity_t *cent, qboolean alt_fire) { entityState_t *ent; - //weaponInfo_t *weap; + // weaponInfo_t *weap; ent = ¢->currentState; - if ( ent->weapon == WP_NONE ) { + if (ent->weapon == WP_NONE) { return; } - if ( ent->weapon >= WP_NUM_WEAPONS ) { - CG_Error( "CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS" ); + if (ent->weapon >= WP_NUM_WEAPONS) { + CG_Error("CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS"); return; } - if ( ent->weapon == WP_TUSKEN_RIFLE && cent->gent->client) - { - if (cent->gent->client->ps.torsoAnim==BOTH_TUSKENATTACK1 || - cent->gent->client->ps.torsoAnim==BOTH_TUSKENATTACK2 || - cent->gent->client->ps.torsoAnim==BOTH_TUSKENATTACK3 || - cent->gent->client->ps.torsoAnim==BOTH_TUSKENLUNGE1) - { + if (ent->weapon == WP_TUSKEN_RIFLE && cent->gent->client) { + if (cent->gent->client->ps.torsoAnim == BOTH_TUSKENATTACK1 || cent->gent->client->ps.torsoAnim == BOTH_TUSKENATTACK2 || + cent->gent->client->ps.torsoAnim == BOTH_TUSKENATTACK3 || cent->gent->client->ps.torsoAnim == BOTH_TUSKENLUNGE1) { return; } } - //weap = &cg_weapons[ ent->weapon ]; + // weap = &cg_weapons[ ent->weapon ]; // mark the entity as muzzle flashing, so when it is added it will // append the flash to the weapon model @@ -2771,64 +2398,62 @@ void CG_FireWeapon( centity_t *cent, qboolean alt_fire ) cent->altFire = alt_fire; // lightning type guns only does this this on initial press - if ( ent->weapon == WP_SABER ) - { - if ( cent->pe.lightningFiring ) - { -/* if ( ent->weapon == WP_DREADNOUGHT ) - { - cgi_FF_EnsureFX( fffx_Laser3 ); - } -*/ + if (ent->weapon == WP_SABER) { + if (cent->pe.lightningFiring) { + /* if ( ent->weapon == WP_DREADNOUGHT ) + { + cgi_FF_EnsureFX( fffx_Laser3 ); + } + */ return; } } // Do overcharge sound that get's added to the top -/* if (( ent->powerups & ( 1<powerups & ( 1<weapon ) + if ( alt_fire ) { - case WP_THERMAL: - case WP_DET_PACK: - case WP_TRIP_MINE: - case WP_ROCKET_LAUNCHER: - case WP_FLECHETTE: - // these weapon fires don't overcharge - break; - - case WP_BLASTER: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); - break; - - default: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); - break; + switch( ent->weapon ) + { + case WP_THERMAL: + case WP_DET_PACK: + case WP_TRIP_MINE: + case WP_ROCKET_LAUNCHER: + case WP_FLECHETTE: + // these weapon fires don't overcharge + break; + + case WP_BLASTER: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); + break; + + default: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); + break; + } } - } - else - { - switch( ent->weapon ) + else { - case WP_THERMAL: - case WP_DET_PACK: - case WP_TRIP_MINE: - case WP_ROCKET_LAUNCHER: - // these weapon fires don't overcharge - break; - - case WP_REPEATER: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); - break; - - default: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); - break; + switch( ent->weapon ) + { + case WP_THERMAL: + case WP_DET_PACK: + case WP_TRIP_MINE: + case WP_ROCKET_LAUNCHER: + // these weapon fires don't overcharge + break; + + case WP_REPEATER: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); + break; + + default: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); + break; + } } - } - }*/ + }*/ } /* @@ -2838,44 +2463,41 @@ CG_BounceEffect Caused by an EV_BOUNCE | EV_BOUNCE_HALF event ================= */ -void CG_BounceEffect( centity_t *cent, int weapon, vec3_t origin, vec3_t normal ) -{ - switch( weapon ) - { +void CG_BounceEffect(centity_t *cent, int weapon, vec3_t origin, vec3_t normal) { + switch (weapon) { case WP_THERMAL: - if ( rand() & 1 ) { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1 ); + if (rand() & 1) { + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1); } else { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2 ); + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2); } break; case WP_BOWCASTER: - theFxScheduler.PlayEffect( cgs.effects.bowcasterBounceEffect, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bowcasterBounceEffect, origin, normal); break; case WP_FLECHETTE: - theFxScheduler.PlayEffect( "flechette/ricochet", origin, normal ); + theFxScheduler.PlayEffect("flechette/ricochet", origin, normal); break; default: - if ( rand() & 1 ) { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1 ); + if (rand() & 1) { + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1); } else { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2 ); + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2); } break; } } //---------------------------------------------------------------------- -void CG_MissileStick( centity_t *cent, int weapon, vec3_t position ) +void CG_MissileStick(centity_t *cent, int weapon, vec3_t position) //---------------------------------------------------------------------- { sfxHandle_t snd = 0; - switch( weapon ) - { + switch (weapon) { case WP_FLECHETTE: snd = cgs.media.flechetteStickSound; break; @@ -2889,17 +2511,14 @@ void CG_MissileStick( centity_t *cent, int weapon, vec3_t position ) break; } - if ( snd ) - { - cgi_S_StartSound( NULL, cent->currentState.number, CHAN_AUTO, snd ); + if (snd) { + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, snd); } } -qboolean CG_VehicleWeaponImpact( centity_t *cent ) -{//see if this is a missile entity that's owned by a vehicle and should do a special, overridden impact effect - if (cent->currentState.otherEntityNum2 - && g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX) - {//missile is from a special vehWeapon +qboolean CG_VehicleWeaponImpact(centity_t *cent) { // see if this is a missile entity that's owned by a vehicle and should do a special, overridden impact + // effect + if (cent->currentState.otherEntityNum2 && g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX) { // missile is from a special vehWeapon CG_PlayEffectID(g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX, cent->lerpOrigin, cent->gent->pos1); return qtrue; } @@ -2913,122 +2532,104 @@ CG_MissileHitWall Caused by an EV_MISSILE_MISS event, or directly by local bullet tracing ================= */ -void CG_MissileHitWall( centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire ) -{ +void CG_MissileHitWall(centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire) { int parm; - switch( weapon ) - { + switch (weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: case WP_JAWA: - if ( altFire ) - { + if (altFire) { parm = 0; - if ( cent->gent ) - { + if (cent->gent) { parm += cent->gent->count; } - FX_BryarAltHitWall( origin, dir, parm ); - } - else - { - FX_BryarHitWall( origin, dir ); + FX_BryarAltHitWall(origin, dir, parm); + } else { + FX_BryarHitWall(origin, dir); } break; case WP_BLASTER: - FX_BlasterWeaponHitWall( origin, dir ); + FX_BlasterWeaponHitWall(origin, dir); break; case WP_BOWCASTER: - FX_BowcasterHitWall( origin, dir ); + FX_BowcasterHitWall(origin, dir); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitWall( origin, dir ); - } - else - { - FX_RepeaterHitWall( origin, dir ); + if (altFire) { + FX_RepeaterAltHitWall(origin, dir); + } else { + FX_RepeaterHitWall(origin, dir); } break; case WP_DEMP2: - if ( altFire ) - { - } - else - { - FX_DEMP2_HitWall( origin, dir ); + if (altFire) { + } else { + FX_DEMP2_HitWall(origin, dir); } break; case WP_FLECHETTE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "flechette/alt_blow", origin, dir ); - } - else - { - FX_FlechetteWeaponHitWall( origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("flechette/alt_blow", origin, dir); + } else { + FX_FlechetteWeaponHitWall(origin, dir); } break; case WP_ROCKET_LAUNCHER: - FX_RocketHitWall( origin, dir ); + FX_RocketHitWall(origin, dir); break; case WP_CONCUSSION: - FX_ConcHitWall( origin, dir ); + FX_ConcHitWall(origin, dir); break; case WP_THERMAL: - theFxScheduler.PlayEffect( "thermal/explosion", origin, dir ); - theFxScheduler.PlayEffect( "thermal/shockwave", origin ); + theFxScheduler.PlayEffect("thermal/explosion", origin, dir); + theFxScheduler.PlayEffect("thermal/shockwave", origin); break; case WP_EMPLACED_GUN: - FX_EmplacedHitWall( origin, dir, (qboolean)(cent->gent&¢->gent->alt_fire) ); + FX_EmplacedHitWall(origin, dir, (qboolean)(cent->gent && cent->gent->alt_fire)); break; case WP_ATST_MAIN: - FX_ATSTMainHitWall( origin, dir ); + FX_ATSTMainHitWall(origin, dir); break; case WP_ATST_SIDE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "atst/side_alt_explosion", origin, dir ); - } - else - { - theFxScheduler.PlayEffect( "atst/side_main_impact", origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("atst/side_alt_explosion", origin, dir); + } else { + theFxScheduler.PlayEffect("atst/side_main_impact", origin, dir); } break; case WP_TRIP_MINE: - theFxScheduler.PlayEffect( "tripmine/explosion", origin, dir ); + theFxScheduler.PlayEffect("tripmine/explosion", origin, dir); break; case WP_DET_PACK: - theFxScheduler.PlayEffect( "detpack/explosion", origin, dir ); + theFxScheduler.PlayEffect("detpack/explosion", origin, dir); break; case WP_TURRET: - theFxScheduler.PlayEffect( "turret/wall_impact", origin, dir ); + theFxScheduler.PlayEffect("turret/wall_impact", origin, dir); break; case WP_TUSKEN_RIFLE: - FX_TuskenShotWeaponHitWall( origin, dir ); + FX_TuskenShotWeaponHitWall(origin, dir); break; case WP_NOGHRI_STICK: - FX_NoghriShotWeaponHitWall( origin, dir ); + FX_NoghriShotWeaponHitWall(origin, dir); break; } } @@ -3039,136 +2640,116 @@ CG_MissileHitPlayer ------------------------- */ -void CG_MissileHitPlayer( centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire ) -{ +void CG_MissileHitPlayer(centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire) { gentity_t *other = NULL; - qboolean humanoid = qtrue; + qboolean humanoid = qtrue; - if ( cent->gent ) - { + if (cent->gent) { other = &g_entities[cent->gent->s.otherEntityNum]; - if( other->client ) - { - class_t npc_class = other->client->NPC_class; + if (other->client) { + class_t npc_class = other->client->NPC_class; // check for all droids, maybe check for certain monsters if they're considered non-humanoid..? - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { humanoid = qfalse; } } } - switch( weapon ) - { + switch (weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: case WP_JAWA: - if ( altFire ) - { - FX_BryarAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_BryarHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_BryarAltHitPlayer(origin, dir, humanoid); + } else { + FX_BryarHitPlayer(origin, dir, humanoid); } break; case WP_BLASTER: - FX_BlasterWeaponHitPlayer( other, origin, dir, humanoid ); + FX_BlasterWeaponHitPlayer(other, origin, dir, humanoid); break; case WP_BOWCASTER: - FX_BowcasterHitPlayer( origin, dir, humanoid ); + FX_BowcasterHitPlayer(origin, dir, humanoid); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_RepeaterHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_RepeaterAltHitPlayer(origin, dir, humanoid); + } else { + FX_RepeaterHitPlayer(origin, dir, humanoid); } break; case WP_DEMP2: - if ( !altFire ) - { - FX_DEMP2_HitPlayer( origin, dir, humanoid ); + if (!altFire) { + FX_DEMP2_HitPlayer(origin, dir, humanoid); } // Do a full body effect here for some more feedback - if ( other && other->client ) - { - other->s.powerups |= ( 1 << PW_SHOCKED ); + if (other && other->client) { + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = cg.time + 1000; } break; case WP_FLECHETTE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "flechette/alt_blow", origin, dir ); - } - else - { - FX_FlechetteWeaponHitPlayer( origin, dir, humanoid ); + if (altFire) { + theFxScheduler.PlayEffect("flechette/alt_blow", origin, dir); + } else { + FX_FlechetteWeaponHitPlayer(origin, dir, humanoid); } break; case WP_ROCKET_LAUNCHER: - FX_RocketHitPlayer( origin, dir, humanoid ); + FX_RocketHitPlayer(origin, dir, humanoid); break; case WP_CONCUSSION: - FX_ConcHitPlayer( origin, dir, humanoid ); + FX_ConcHitPlayer(origin, dir, humanoid); break; case WP_THERMAL: - theFxScheduler.PlayEffect( "thermal/explosion", origin, dir ); - theFxScheduler.PlayEffect( "thermal/shockwave", origin ); + theFxScheduler.PlayEffect("thermal/explosion", origin, dir); + theFxScheduler.PlayEffect("thermal/shockwave", origin); break; case WP_EMPLACED_GUN: - FX_EmplacedHitPlayer( origin, dir, (qboolean)(cent->gent&¢->gent->alt_fire) ); + FX_EmplacedHitPlayer(origin, dir, (qboolean)(cent->gent && cent->gent->alt_fire)); break; case WP_TRIP_MINE: - theFxScheduler.PlayEffect( "tripmine/explosion", origin, dir ); + theFxScheduler.PlayEffect("tripmine/explosion", origin, dir); break; case WP_DET_PACK: - theFxScheduler.PlayEffect( "detpack/explosion", origin, dir ); + theFxScheduler.PlayEffect("detpack/explosion", origin, dir); break; case WP_TURRET: - theFxScheduler.PlayEffect( "turret/flesh_impact", origin, dir ); + theFxScheduler.PlayEffect("turret/flesh_impact", origin, dir); break; case WP_ATST_MAIN: - FX_EmplacedHitWall( origin, dir, qfalse ); + FX_EmplacedHitWall(origin, dir, qfalse); break; case WP_ATST_SIDE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "atst/side_alt_explosion", origin, dir ); - } - else - { - theFxScheduler.PlayEffect( "atst/side_main_impact", origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("atst/side_alt_explosion", origin, dir); + } else { + theFxScheduler.PlayEffect("atst/side_main_impact", origin, dir); } break; case WP_TUSKEN_RIFLE: - FX_TuskenShotWeaponHitPlayer( other, origin, dir, humanoid ); + FX_TuskenShotWeaponHitPlayer(other, origin, dir, humanoid); break; case WP_NOGHRI_STICK: - FX_NoghriShotWeaponHitPlayer( other, origin, dir, humanoid ); + FX_NoghriShotWeaponHitPlayer(other, origin, dir, humanoid); break; } } diff --git a/code/client/cl_cgame.cpp b/code/client/cl_cgame.cpp index b9d7b6fc11..26e4d04851 100644 --- a/code/client/cl_cgame.cpp +++ b/code/client/cl_cgame.cpp @@ -33,56 +33,54 @@ along with this program; if not, see . #include "qcommon/stringed_ingame.h" #include "sys/sys_loadlib.h" -vm_t cgvm; +vm_t cgvm; /* Ghoul2 Insert Start */ #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif /* Ghoul2 Insert End */ -//FIXME: Temp -extern void S_UpdateAmbientSet ( const char *name, vec3_t origin ); -extern int S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ); -extern void AS_ParseSets( void ); -extern sfxHandle_t AS_GetBModelSound( const char *name, int stage ); -extern void AS_AddPrecacheEntry( const char *name ); +// FIXME: Temp +extern void S_UpdateAmbientSet(const char *name, vec3_t origin); +extern int S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time); +extern void AS_ParseSets(void); +extern sfxHandle_t AS_GetBModelSound(const char *name, int stage); +extern void AS_AddPrecacheEntry(const char *name); extern menuDef_t *Menus_FindByName(const char *p); -extern qboolean R_inPVS( vec3_t p1, vec3_t p2 ); +extern qboolean R_inPVS(vec3_t p1, vec3_t p2); -void UI_SetActiveMenu( const char* menuname,const char *menuID ); +void UI_SetActiveMenu(const char *menuname, const char *menuID); -qboolean CL_InitCGameVM( void *gameLibrary ) -{ - typedef intptr_t SyscallProc( intptr_t, ... ); - typedef void DllEntryProc( SyscallProc * ); +qboolean CL_InitCGameVM(void *gameLibrary) { + typedef intptr_t SyscallProc(intptr_t, ...); + typedef void DllEntryProc(SyscallProc *); - DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction( gameLibrary, "dllEntry" ); + DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction(gameLibrary, "dllEntry"); // NOTE: arm64 mac has a different calling convention for fixed parameters vs. variadic parameters. // As the cgame entryPoints (vmMain) in jk2 and jka use fixed arg0 to arg7 we can't use "..." around here or we end up with undefined behavior. // See: https://developer.apple.com/documentation/apple-silicon/addressing-architectural-differences-in-your-macos-code - cgvm.entryPoint = (intptr_t (*)(int,intptr_t,intptr_t,intptr_t,intptr_t,intptr_t,intptr_t,intptr_t,intptr_t))Sys_LoadFunction( gameLibrary, "vmMain" ); + cgvm.entryPoint = (intptr_t(*)(int, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))Sys_LoadFunction(gameLibrary, "vmMain"); - if ( !cgvm.entryPoint || !dllEntry ) { + if (!cgvm.entryPoint || !dllEntry) { #ifdef JK2_MODE const char *gamename = "jospgame"; #else const char *gamename = "jagame"; #endif - Com_Printf( "CL_InitCGameVM: client game entry point not found in %s" ARCH_STRING DLL_EXT ": %s\n", - gamename, Sys_LibraryError() ); + Com_Printf("CL_InitCGameVM: client game entry point not found in %s" ARCH_STRING DLL_EXT ": %s\n", gamename, Sys_LibraryError()); return qfalse; } - dllEntry( VM_DllSyscall ); + dllEntry(VM_DllSyscall); return qtrue; } @@ -92,48 +90,40 @@ qboolean CL_InitCGameVM( void *gameLibrary ) CL_GetGameState ==================== */ -void CL_GetGameState( gameState_t *gs ) { - *gs = cl.gameState; -} +void CL_GetGameState(gameState_t *gs) { *gs = cl.gameState; } /* ==================== CL_GetGlconfig ==================== */ -void CL_GetGlconfig( glconfig_t *glconfig ) { - *glconfig = cls.glconfig; -} - +void CL_GetGlconfig(glconfig_t *glconfig) { *glconfig = cls.glconfig; } /* ==================== CL_GetUserCmd ==================== */ -qboolean CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { +qboolean CL_GetUserCmd(int cmdNumber, usercmd_t *ucmd) { // cmds[cmdNumber] is the last properly generated command // can't return anything that we haven't created yet - if ( cmdNumber > cl.cmdNumber ) { - Com_Error( ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber ); + if (cmdNumber > cl.cmdNumber) { + Com_Error(ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber); } // the usercmd has been overwritten in the wrapping // buffer because it is too far out of date - if ( cmdNumber <= cl.cmdNumber - CMD_BACKUP ) { + if (cmdNumber <= cl.cmdNumber - CMD_BACKUP) { return qfalse; } - *ucmd = cl.cmds[ cmdNumber & CMD_MASK ]; + *ucmd = cl.cmds[cmdNumber & CMD_MASK]; return qtrue; } -int CL_GetCurrentCmdNumber( void ) { - return cl.cmdNumber; -} - +int CL_GetCurrentCmdNumber(void) { return cl.cmdNumber; } /* ==================== @@ -163,7 +153,7 @@ qboolean CL_GetParseEntityState( int parseEntityNumber, entityState_t *state ) { CL_GetCurrentSnapshotNumber ==================== */ -void CL_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { +void CL_GetCurrentSnapshotNumber(int *snapshotNumber, int *serverTime) { *snapshotNumber = cl.frame.messageNum; *serverTime = cl.frame.serverTime; } @@ -173,28 +163,28 @@ void CL_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { CL_GetSnapshot ==================== */ -qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { - clSnapshot_t *clSnap; - int i, count; +qboolean CL_GetSnapshot(int snapshotNumber, snapshot_t *snapshot) { + clSnapshot_t *clSnap; + int i, count; - if ( snapshotNumber > cl.frame.messageNum ) { - Com_Error( ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.frame.messageNum" ); + if (snapshotNumber > cl.frame.messageNum) { + Com_Error(ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.frame.messageNum"); } // if the frame has fallen out of the circular buffer, we can't return it - if ( cl.frame.messageNum - snapshotNumber >= PACKET_BACKUP ) { + if (cl.frame.messageNum - snapshotNumber >= PACKET_BACKUP) { return qfalse; } // if the frame is not valid, we can't return it clSnap = &cl.frames[snapshotNumber & PACKET_MASK]; - if ( !clSnap->valid ) { + if (!clSnap->valid) { return qfalse; } // if the entities in the frame have fallen out of their // circular buffer, we can't return it - if ( cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES ) { + if (cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES) { return qfalse; } @@ -202,60 +192,56 @@ qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { snapshot->snapFlags = clSnap->snapFlags; snapshot->serverCommandSequence = clSnap->serverCommandNum; snapshot->serverTime = clSnap->serverTime; - memcpy( snapshot->areamask, clSnap->areamask, sizeof( snapshot->areamask ) ); + memcpy(snapshot->areamask, clSnap->areamask, sizeof(snapshot->areamask)); snapshot->cmdNum = clSnap->cmdNum; snapshot->ps = clSnap->ps; count = clSnap->numEntities; - if ( count > MAX_ENTITIES_IN_SNAPSHOT ) { - Com_DPrintf( "CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT ); + if (count > MAX_ENTITIES_IN_SNAPSHOT) { + Com_DPrintf("CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT); count = MAX_ENTITIES_IN_SNAPSHOT; } snapshot->numEntities = count; -/* -Ghoul2 Insert Start -*/ - for ( i = 0 ; i < count ; i++ ) - { + /* + Ghoul2 Insert Start + */ + for (i = 0; i < count; i++) { - int entNum = ( clSnap->parseEntitiesNum + i ) & (MAX_PARSE_ENTITIES-1) ; - snapshot->entities[i] = cl.parseEntities[ entNum ]; + int entNum = (clSnap->parseEntitiesNum + i) & (MAX_PARSE_ENTITIES - 1); + snapshot->entities[i] = cl.parseEntities[entNum]; } -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert End + */ // FIXME: configstring changes and server commands!!! return qtrue; } -//bg_public.h won't cooperate in here -#define EF_PERMANENT 0x00080000 +// bg_public.h won't cooperate in here +#define EF_PERMANENT 0x00080000 -qboolean CL_GetDefaultState(int index, entityState_t *state) -{ - if (index < 0 || index >= MAX_GENTITIES) - { +qboolean CL_GetDefaultState(int index, entityState_t *state) { + if (index < 0 || index >= MAX_GENTITIES) { return qfalse; } // Is this safe? I think so. But it's still ugly as sin. if (!(sv.svEntities[index].baseline.eFlags & EF_PERMANENT)) -// if (!(cl.entityBaselines[index].eFlags & EF_PERMANENT)) + // if (!(cl.entityBaselines[index].eFlags & EF_PERMANENT)) { return qfalse; } *state = sv.svEntities[index].baseline; -// *state = cl.entityBaselines[index]; + // *state = cl.entityBaselines[index]; return qtrue; } extern float cl_mPitchOverride; extern float cl_mYawOverride; -void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale, float mPitchOverride, float mYawOverride ) { +void CL_SetUserCmdValue(int userCmdValue, float sensitivityScale, float mPitchOverride, float mYawOverride) { cl.cgameUserCmdValue = userCmdValue; cl.cgameSensitivity = sensitivityScale; cl_mPitchOverride = mPitchOverride; @@ -264,79 +250,75 @@ void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale, float mPitchO extern vec3_t cl_overriddenAngles; extern qboolean cl_overrideAngles; -void CL_SetUserCmdAngles( float pitchOverride, float yawOverride, float rollOverride ) { +void CL_SetUserCmdAngles(float pitchOverride, float yawOverride, float rollOverride) { cl_overriddenAngles[PITCH] = pitchOverride; cl_overriddenAngles[YAW] = yawOverride; cl_overriddenAngles[ROLL] = rollOverride; cl_overrideAngles = qtrue; } -void CL_AddCgameCommand( const char *cmdName ) { - Cmd_AddCommand( cmdName, NULL ); -} +void CL_AddCgameCommand(const char *cmdName) { Cmd_AddCommand(cmdName, NULL); } /* ===================== CL_ConfigstringModified ===================== */ -void CL_ConfigstringModified( void ) { +void CL_ConfigstringModified(void) { const char *s; - char *old; - int i, index; - const char *dup; - gameState_t oldGs; - int len; - - index = atoi( Cmd_Argv(1) ); - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error( ERR_DROP, "configstring > MAX_CONFIGSTRINGS" ); + char *old; + int i, index; + const char *dup; + gameState_t oldGs; + int len; + + index = atoi(Cmd_Argv(1)); + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "configstring > MAX_CONFIGSTRINGS"); } s = Cmd_Argv(2); - old = cl.gameState.stringData + cl.gameState.stringOffsets[ index ]; - if ( !strcmp( old, s ) ) { - return; // unchanged + old = cl.gameState.stringData + cl.gameState.stringOffsets[index]; + if (!strcmp(old, s)) { + return; // unchanged } // build the new gameState_t oldGs = cl.gameState; - memset( &cl.gameState, 0, sizeof( cl.gameState ) ); + memset(&cl.gameState, 0, sizeof(cl.gameState)); // leave the first 0 for uninitialized strings cl.gameState.dataCount = 1; - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( i == index ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (i == index) { dup = s; } else { - dup = oldGs.stringData + oldGs.stringOffsets[ i ]; + dup = oldGs.stringData + oldGs.stringOffsets[i]; } - if ( !dup[0] ) { - continue; // leave with the default empty string + if (!dup[0]) { + continue; // leave with the default empty string } - len = strlen( dup ); + len = strlen(dup); - if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) { - Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" ); + if (len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS) { + Com_Error(ERR_DROP, "MAX_GAMESTATE_CHARS exceeded"); } // append it to the gameState string buffer - cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount; - memcpy( cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1 ); + cl.gameState.stringOffsets[i] = cl.gameState.dataCount; + memcpy(cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1); cl.gameState.dataCount += len + 1; } - if ( index == CS_SYSTEMINFO ) { + if (index == CS_SYSTEMINFO) { // parse serverId and other cvars CL_SystemInfoChanged(); } - } - /* =================== CL_GetServerCommand @@ -344,36 +326,36 @@ CL_GetServerCommand Set up argc/argv for the given command =================== */ -qboolean CL_GetServerCommand( int serverCommandNumber ) { - char *s; - const char *cmd; +qboolean CL_GetServerCommand(int serverCommandNumber) { + char *s; + const char *cmd; // if we have irretrievably lost a reliable command, drop the connection - if ( serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS ) { - Com_Error( ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out" ); + if (serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS) { + Com_Error(ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out"); return qfalse; } - if ( serverCommandNumber > clc.serverCommandSequence ) { - Com_Error( ERR_DROP, "CL_GetServerCommand: requested a command not received" ); + if (serverCommandNumber > clc.serverCommandSequence) { + Com_Error(ERR_DROP, "CL_GetServerCommand: requested a command not received"); return qfalse; } - s = clc.serverCommands[ serverCommandNumber & ( MAX_RELIABLE_COMMANDS - 1 ) ]; + s = clc.serverCommands[serverCommandNumber & (MAX_RELIABLE_COMMANDS - 1)]; - Com_DPrintf( "serverCommand: %i : %s\n", serverCommandNumber, s ); + Com_DPrintf("serverCommand: %i : %s\n", serverCommandNumber, s); - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); cmd = Cmd_Argv(0); - if ( !strcmp( cmd, "disconnect" ) ) { - Com_Error (ERR_DISCONNECT,"Server disconnected\n"); + if (!strcmp(cmd, "disconnect")) { + Com_Error(ERR_DISCONNECT, "Server disconnected\n"); } - if ( !strcmp( cmd, "cs" ) ) { + if (!strcmp(cmd, "cs")) { CL_ConfigstringModified(); // reparse the string, because CL_ConfigstringModified may have done another Cmd_TokenizeString() - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); return qtrue; } @@ -382,17 +364,17 @@ qboolean CL_GetServerCommand( int serverCommandNumber ) { // point of levels for the menu system to use // we pass it along to the cgame to make apropriate adjustments, // but we also clear the console and notify lines here - if ( !strcmp( cmd, "clientLevelShot" ) ) { + if (!strcmp(cmd, "clientLevelShot")) { // don't do it if we aren't running the server locally, // otherwise malicious remote servers could overwrite // the existing thumbnails - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return qfalse; } // close the console Con_Close(); // take a special screenshot next frame - Cbuf_AddText( "wait ; wait ; wait ; wait ; screenshot levelshot\n" ); + Cbuf_AddText("wait ; wait ; wait ; wait ; screenshot levelshot\n"); return qtrue; } @@ -402,7 +384,6 @@ qboolean CL_GetServerCommand( int serverCommandNumber ) { return qtrue; } - /* ==================== CL_CM_LoadMap @@ -410,10 +391,10 @@ CL_CM_LoadMap Just adds default parameters that cgame doesn't need to know about ==================== */ -void CL_CM_LoadMap( const char *mapname, qboolean subBSP ) { - int checksum; +void CL_CM_LoadMap(const char *mapname, qboolean subBSP) { + int checksum; - CM_LoadMap( mapname, qtrue, &checksum, subBSP ); + CM_LoadMap(mapname, qtrue, &checksum, subBSP); } /* @@ -422,16 +403,16 @@ CL_ShutdonwCGame ==================== */ -void CL_ShutdownCGame( void ) { +void CL_ShutdownCGame(void) { cls.cgameStarted = qfalse; - if ( !cgvm.entryPoint) { + if (!cgvm.entryPoint) { return; } - VM_Call( CG_SHUTDOWN ); + VM_Call(CG_SHUTDOWN); -// VM_Free( cgvm ); -// cgvm = NULL; + // VM_Free( cgvm ); + // cgvm = NULL; } #ifdef JK2_MODE @@ -443,356 +424,354 @@ Converts a JK2 syscall to a JKA syscall ==================== */ -cgameImport_t CL_ConvertJK2SysCall( cgameJK2Import_t import ) -{ +cgameImport_t CL_ConvertJK2SysCall(cgameJK2Import_t import) { // FIXME: This was a 5-minute slap-hack job in order to test if this really works. CLEAN ME UP! --eez - switch(import) - { - case CG_PRINT_JK2: - return CG_PRINT; - break; - case CG_ERROR_JK2: - return CG_ERROR; - break; - case CG_MILLISECONDS_JK2: - return CG_MILLISECONDS; - break; - case CG_CVAR_REGISTER_JK2: - return CG_CVAR_REGISTER; - break; - case CG_CVAR_UPDATE_JK2: - return CG_CVAR_UPDATE; - break; - case CG_CVAR_SET_JK2: - return CG_CVAR_SET; - break; - case CG_ARGC_JK2: - return CG_ARGC; - break; - case CG_ARGV_JK2: - return CG_ARGV; - break; - case CG_ARGS_JK2: - return CG_ARGS; - break; - case CG_FS_FOPENFILE_JK2: - return CG_FS_FOPENFILE; - break; - case CG_FS_READ_JK2: - return CG_FS_READ; - break; - case CG_FS_WRITE_JK2: - return CG_FS_WRITE; - break; - case CG_FS_FCLOSEFILE_JK2: - return CG_FS_FCLOSEFILE; - break; - case CG_SENDCONSOLECOMMAND_JK2: - return CG_SENDCONSOLECOMMAND; - break; - case CG_ADDCOMMAND_JK2: - return CG_ADDCOMMAND; - break; - case CG_SENDCLIENTCOMMAND_JK2: - return CG_SENDCLIENTCOMMAND; - break; - case CG_UPDATESCREEN_JK2: - return CG_UPDATESCREEN; - break; - case CG_CM_LOADMAP_JK2: - return CG_CM_LOADMAP; - break; - case CG_CM_NUMINLINEMODELS_JK2: - return CG_CM_NUMINLINEMODELS; - break; - case CG_CM_INLINEMODEL_JK2: - return CG_CM_INLINEMODEL; - break; - case CG_CM_TEMPBOXMODEL_JK2: - return CG_CM_TEMPBOXMODEL; - break; - case CG_CM_POINTCONTENTS_JK2: - return CG_CM_POINTCONTENTS; - break; - case CG_CM_TRANSFORMEDPOINTCONTENTS_JK2: - return CG_CM_TRANSFORMEDPOINTCONTENTS; - break; - case CG_CM_BOXTRACE_JK2: - return CG_CM_BOXTRACE; - break; - case CG_CM_TRANSFORMEDBOXTRACE_JK2: - return CG_CM_TRANSFORMEDBOXTRACE; - break; - case CG_CM_MARKFRAGMENTS_JK2: - return CG_CM_MARKFRAGMENTS; - break; - case CG_CM_SNAPPVS_JK2: - return CG_CM_SNAPPVS; - break; - case CG_S_STARTSOUND_JK2: - return CG_S_STARTSOUND; - break; - case CG_S_STARTLOCALSOUND_JK2: - return CG_S_STARTLOCALSOUND; - break; - case CG_S_CLEARLOOPINGSOUNDS_JK2: - return CG_S_CLEARLOOPINGSOUNDS; - break; - case CG_S_ADDLOOPINGSOUND_JK2: - return CG_S_ADDLOOPINGSOUND; - break; - case CG_S_UPDATEENTITYPOSITION_JK2: - return CG_S_UPDATEENTITYPOSITION; - break; - case CG_S_RESPATIALIZE_JK2: - return CG_S_RESPATIALIZE; - break; - case CG_S_REGISTERSOUND_JK2: - return CG_S_REGISTERSOUND; - break; - case CG_S_STARTBACKGROUNDTRACK_JK2: - return CG_S_STARTBACKGROUNDTRACK; - break; - case CG_R_LOADWORLDMAP_JK2: - return CG_R_LOADWORLDMAP; - break; - case CG_R_REGISTERMODEL_JK2: - return CG_R_REGISTERMODEL; - break; - case CG_R_REGISTERSKIN_JK2: - return CG_R_REGISTERSKIN; - break; - case CG_R_REGISTERSHADER_JK2: - return CG_R_REGISTERSHADER; - break; - case CG_R_REGISTERSHADERNOMIP_JK2: - return CG_R_REGISTERSHADERNOMIP; - break; - case CG_R_REGISTERFONT_JK2: - return CG_R_REGISTERFONT; - break; - case CG_R_FONTSTRLENPIXELS_JK2: - return CG_R_FONTSTRLENPIXELS; - break; - case CG_R_FONTSTRLENCHARS_JK2: - return CG_R_FONTSTRLENCHARS; - break; - case CG_R_FONTHEIGHTPIXELS_JK2: - return CG_R_FONTHEIGHTPIXELS; - break; - case CG_R_FONTDRAWSTRING_JK2: - return CG_R_FONTDRAWSTRING; - break; - case CG_LANGUAGE_ISASIAN_JK2: - return CG_LANGUAGE_ISASIAN; - break; - case CG_LANGUAGE_USESSPACES_JK2: - return CG_LANGUAGE_USESSPACES; - break; - case CG_ANYLANGUAGE_READFROMSTRING_JK2: - return CG_ANYLANGUAGE_READFROMSTRING; - break; - case CG_R_CLEARSCENE_JK2: - return CG_R_CLEARSCENE; - break; - case CG_R_ADDREFENTITYTOSCENE_JK2: - return CG_R_ADDREFENTITYTOSCENE; - break; - case CG_R_GETLIGHTING_JK2: - return CG_R_GETLIGHTING; - break; - case CG_R_ADDPOLYTOSCENE_JK2: - return CG_R_ADDPOLYTOSCENE; - break; - case CG_R_ADDLIGHTTOSCENE_JK2: - return CG_R_ADDLIGHTTOSCENE; - break; - case CG_R_RENDERSCENE_JK2: - return CG_R_RENDERSCENE; - break; - case CG_R_SETCOLOR_JK2: - return CG_R_SETCOLOR; - break; - case CG_R_DRAWSTRETCHPIC_JK2: - return CG_R_DRAWSTRETCHPIC; - break; - case CG_R_DRAWSCREENSHOT_JK2: - return CG_R_DRAWSCREENSHOT; - break; - case CG_R_MODELBOUNDS_JK2: - return CG_R_MODELBOUNDS; - break; - case CG_R_LERPTAG_JK2: - return CG_R_LERPTAG; - break; - case CG_R_DRAWROTATEPIC_JK2: - return CG_R_DRAWROTATEPIC; - break; - case CG_R_DRAWROTATEPIC2_JK2: - return CG_R_DRAWROTATEPIC2; - break; - case CG_R_LA_GOGGLES_JK2: - return CG_R_LA_GOGGLES; - break; - case CG_R_SCISSOR_JK2: - return CG_R_SCISSOR; - break; - case CG_GETGLCONFIG_JK2: - return CG_GETGLCONFIG; - break; - case CG_GETGAMESTATE_JK2: - return CG_GETGAMESTATE; - break; - case CG_GETCURRENTSNAPSHOTNUMBER_JK2: - return CG_GETCURRENTSNAPSHOTNUMBER; - break; - case CG_GETSNAPSHOT_JK2: - return CG_GETSNAPSHOT; - break; - case CG_GETSERVERCOMMAND_JK2: - return CG_GETSERVERCOMMAND; - break; - case CG_GETCURRENTCMDNUMBER_JK2: - return CG_GETCURRENTCMDNUMBER; - break; - case CG_GETUSERCMD_JK2: - return CG_GETUSERCMD; - break; - case CG_SETUSERCMDVALUE_JK2: - return CG_SETUSERCMDVALUE; - break; - case CG_SETUSERCMDANGLES_JK2: - return CG_SETUSERCMDANGLES; - break; - case CG_S_UPDATEAMBIENTSET_JK2: - return CG_S_UPDATEAMBIENTSET; - break; - case CG_S_ADDLOCALSET_JK2: - return CG_S_ADDLOCALSET; - break; - case CG_AS_PARSESETS_JK2: - return CG_AS_PARSESETS; - break; - case CG_AS_ADDENTRY_JK2: - return CG_AS_ADDENTRY; - break; - case CG_AS_GETBMODELSOUND_JK2: - return CG_AS_GETBMODELSOUND; - break; - case CG_S_GETSAMPLELENGTH_JK2: - return CG_S_GETSAMPLELENGTH; - break; - case COM_SETORGANGLES_JK2: - return COM_SETORGANGLES; - break; -/* -Ghoul2 Insert Start -*/ - case CG_G2_LISTBONES_JK2: - return CG_G2_LISTBONES; - break; - case CG_G2_LISTSURFACES_JK2: - return CG_G2_LISTSURFACES; - break; - case CG_G2_HAVEWEGHOULMODELS_JK2: - return CG_G2_HAVEWEGHOULMODELS; - break; - case CG_G2_SETMODELS_JK2: - return CG_G2_SETMODELS; - break; -/* -Ghoul2 Insert End -*/ + switch (import) { + case CG_PRINT_JK2: + return CG_PRINT; + break; + case CG_ERROR_JK2: + return CG_ERROR; + break; + case CG_MILLISECONDS_JK2: + return CG_MILLISECONDS; + break; + case CG_CVAR_REGISTER_JK2: + return CG_CVAR_REGISTER; + break; + case CG_CVAR_UPDATE_JK2: + return CG_CVAR_UPDATE; + break; + case CG_CVAR_SET_JK2: + return CG_CVAR_SET; + break; + case CG_ARGC_JK2: + return CG_ARGC; + break; + case CG_ARGV_JK2: + return CG_ARGV; + break; + case CG_ARGS_JK2: + return CG_ARGS; + break; + case CG_FS_FOPENFILE_JK2: + return CG_FS_FOPENFILE; + break; + case CG_FS_READ_JK2: + return CG_FS_READ; + break; + case CG_FS_WRITE_JK2: + return CG_FS_WRITE; + break; + case CG_FS_FCLOSEFILE_JK2: + return CG_FS_FCLOSEFILE; + break; + case CG_SENDCONSOLECOMMAND_JK2: + return CG_SENDCONSOLECOMMAND; + break; + case CG_ADDCOMMAND_JK2: + return CG_ADDCOMMAND; + break; + case CG_SENDCLIENTCOMMAND_JK2: + return CG_SENDCLIENTCOMMAND; + break; + case CG_UPDATESCREEN_JK2: + return CG_UPDATESCREEN; + break; + case CG_CM_LOADMAP_JK2: + return CG_CM_LOADMAP; + break; + case CG_CM_NUMINLINEMODELS_JK2: + return CG_CM_NUMINLINEMODELS; + break; + case CG_CM_INLINEMODEL_JK2: + return CG_CM_INLINEMODEL; + break; + case CG_CM_TEMPBOXMODEL_JK2: + return CG_CM_TEMPBOXMODEL; + break; + case CG_CM_POINTCONTENTS_JK2: + return CG_CM_POINTCONTENTS; + break; + case CG_CM_TRANSFORMEDPOINTCONTENTS_JK2: + return CG_CM_TRANSFORMEDPOINTCONTENTS; + break; + case CG_CM_BOXTRACE_JK2: + return CG_CM_BOXTRACE; + break; + case CG_CM_TRANSFORMEDBOXTRACE_JK2: + return CG_CM_TRANSFORMEDBOXTRACE; + break; + case CG_CM_MARKFRAGMENTS_JK2: + return CG_CM_MARKFRAGMENTS; + break; + case CG_CM_SNAPPVS_JK2: + return CG_CM_SNAPPVS; + break; + case CG_S_STARTSOUND_JK2: + return CG_S_STARTSOUND; + break; + case CG_S_STARTLOCALSOUND_JK2: + return CG_S_STARTLOCALSOUND; + break; + case CG_S_CLEARLOOPINGSOUNDS_JK2: + return CG_S_CLEARLOOPINGSOUNDS; + break; + case CG_S_ADDLOOPINGSOUND_JK2: + return CG_S_ADDLOOPINGSOUND; + break; + case CG_S_UPDATEENTITYPOSITION_JK2: + return CG_S_UPDATEENTITYPOSITION; + break; + case CG_S_RESPATIALIZE_JK2: + return CG_S_RESPATIALIZE; + break; + case CG_S_REGISTERSOUND_JK2: + return CG_S_REGISTERSOUND; + break; + case CG_S_STARTBACKGROUNDTRACK_JK2: + return CG_S_STARTBACKGROUNDTRACK; + break; + case CG_R_LOADWORLDMAP_JK2: + return CG_R_LOADWORLDMAP; + break; + case CG_R_REGISTERMODEL_JK2: + return CG_R_REGISTERMODEL; + break; + case CG_R_REGISTERSKIN_JK2: + return CG_R_REGISTERSKIN; + break; + case CG_R_REGISTERSHADER_JK2: + return CG_R_REGISTERSHADER; + break; + case CG_R_REGISTERSHADERNOMIP_JK2: + return CG_R_REGISTERSHADERNOMIP; + break; + case CG_R_REGISTERFONT_JK2: + return CG_R_REGISTERFONT; + break; + case CG_R_FONTSTRLENPIXELS_JK2: + return CG_R_FONTSTRLENPIXELS; + break; + case CG_R_FONTSTRLENCHARS_JK2: + return CG_R_FONTSTRLENCHARS; + break; + case CG_R_FONTHEIGHTPIXELS_JK2: + return CG_R_FONTHEIGHTPIXELS; + break; + case CG_R_FONTDRAWSTRING_JK2: + return CG_R_FONTDRAWSTRING; + break; + case CG_LANGUAGE_ISASIAN_JK2: + return CG_LANGUAGE_ISASIAN; + break; + case CG_LANGUAGE_USESSPACES_JK2: + return CG_LANGUAGE_USESSPACES; + break; + case CG_ANYLANGUAGE_READFROMSTRING_JK2: + return CG_ANYLANGUAGE_READFROMSTRING; + break; + case CG_R_CLEARSCENE_JK2: + return CG_R_CLEARSCENE; + break; + case CG_R_ADDREFENTITYTOSCENE_JK2: + return CG_R_ADDREFENTITYTOSCENE; + break; + case CG_R_GETLIGHTING_JK2: + return CG_R_GETLIGHTING; + break; + case CG_R_ADDPOLYTOSCENE_JK2: + return CG_R_ADDPOLYTOSCENE; + break; + case CG_R_ADDLIGHTTOSCENE_JK2: + return CG_R_ADDLIGHTTOSCENE; + break; + case CG_R_RENDERSCENE_JK2: + return CG_R_RENDERSCENE; + break; + case CG_R_SETCOLOR_JK2: + return CG_R_SETCOLOR; + break; + case CG_R_DRAWSTRETCHPIC_JK2: + return CG_R_DRAWSTRETCHPIC; + break; + case CG_R_DRAWSCREENSHOT_JK2: + return CG_R_DRAWSCREENSHOT; + break; + case CG_R_MODELBOUNDS_JK2: + return CG_R_MODELBOUNDS; + break; + case CG_R_LERPTAG_JK2: + return CG_R_LERPTAG; + break; + case CG_R_DRAWROTATEPIC_JK2: + return CG_R_DRAWROTATEPIC; + break; + case CG_R_DRAWROTATEPIC2_JK2: + return CG_R_DRAWROTATEPIC2; + break; + case CG_R_LA_GOGGLES_JK2: + return CG_R_LA_GOGGLES; + break; + case CG_R_SCISSOR_JK2: + return CG_R_SCISSOR; + break; + case CG_GETGLCONFIG_JK2: + return CG_GETGLCONFIG; + break; + case CG_GETGAMESTATE_JK2: + return CG_GETGAMESTATE; + break; + case CG_GETCURRENTSNAPSHOTNUMBER_JK2: + return CG_GETCURRENTSNAPSHOTNUMBER; + break; + case CG_GETSNAPSHOT_JK2: + return CG_GETSNAPSHOT; + break; + case CG_GETSERVERCOMMAND_JK2: + return CG_GETSERVERCOMMAND; + break; + case CG_GETCURRENTCMDNUMBER_JK2: + return CG_GETCURRENTCMDNUMBER; + break; + case CG_GETUSERCMD_JK2: + return CG_GETUSERCMD; + break; + case CG_SETUSERCMDVALUE_JK2: + return CG_SETUSERCMDVALUE; + break; + case CG_SETUSERCMDANGLES_JK2: + return CG_SETUSERCMDANGLES; + break; + case CG_S_UPDATEAMBIENTSET_JK2: + return CG_S_UPDATEAMBIENTSET; + break; + case CG_S_ADDLOCALSET_JK2: + return CG_S_ADDLOCALSET; + break; + case CG_AS_PARSESETS_JK2: + return CG_AS_PARSESETS; + break; + case CG_AS_ADDENTRY_JK2: + return CG_AS_ADDENTRY; + break; + case CG_AS_GETBMODELSOUND_JK2: + return CG_AS_GETBMODELSOUND; + break; + case CG_S_GETSAMPLELENGTH_JK2: + return CG_S_GETSAMPLELENGTH; + break; + case COM_SETORGANGLES_JK2: + return COM_SETORGANGLES; + break; + /* + Ghoul2 Insert Start + */ + case CG_G2_LISTBONES_JK2: + return CG_G2_LISTBONES; + break; + case CG_G2_LISTSURFACES_JK2: + return CG_G2_LISTSURFACES; + break; + case CG_G2_HAVEWEGHOULMODELS_JK2: + return CG_G2_HAVEWEGHOULMODELS; + break; + case CG_G2_SETMODELS_JK2: + return CG_G2_SETMODELS; + break; + /* + Ghoul2 Insert End + */ - case CG_R_GET_LIGHT_STYLE_JK2: - return CG_R_GET_LIGHT_STYLE; - break; - case CG_R_SET_LIGHT_STYLE_JK2: - return CG_R_SET_LIGHT_STYLE; - break; - case CG_R_GET_BMODEL_VERTS_JK2: - return CG_R_GET_BMODEL_VERTS; - break; - case CG_R_WORLD_EFFECT_COMMAND_JK2: - return CG_R_WORLD_EFFECT_COMMAND; - break; - - case CG_CIN_PLAYCINEMATIC_JK2: - return CG_CIN_PLAYCINEMATIC; - break; - case CG_CIN_STOPCINEMATIC_JK2: - return CG_CIN_STOPCINEMATIC; - break; - case CG_CIN_RUNCINEMATIC_JK2: - return CG_CIN_RUNCINEMATIC; - break; - case CG_CIN_DRAWCINEMATIC_JK2: - return CG_CIN_DRAWCINEMATIC; - break; - case CG_CIN_SETEXTENTS_JK2: - return CG_CIN_SETEXTENTS; - break; - case CG_Z_MALLOC_JK2: - return CG_Z_MALLOC; - break; - case CG_Z_FREE_JK2: - return CG_Z_FREE; - break; - case CG_UI_MENU_RESET_JK2: - return CG_UI_MENU_RESET; - break; - case CG_UI_MENU_NEW_JK2: - return CG_UI_MENU_NEW; - break; - case CG_UI_PARSE_INT_JK2: - return CG_UI_PARSE_INT; - break; - case CG_UI_PARSE_STRING_JK2: - return CG_UI_PARSE_STRING; - break; - case CG_UI_PARSE_FLOAT_JK2: - return CG_UI_PARSE_FLOAT; - break; - case CG_UI_STARTPARSESESSION_JK2: - return CG_UI_STARTPARSESESSION; - break; - case CG_UI_ENDPARSESESSION_JK2: - return CG_UI_ENDPARSESESSION; - break; - case CG_UI_PARSEEXT_JK2: - return CG_UI_PARSEEXT; - break; - case CG_UI_MENUPAINT_ALL_JK2: - return CG_UI_MENUPAINT_ALL; - break; - case CG_UI_STRING_INIT_JK2: - return CG_UI_STRING_INIT; - break; - case CG_UI_GETMENUINFO_JK2: - return CG_UI_GETMENUINFO; - break; - case CG_SP_REGISTER_JK2: - return CG_SP_REGISTER; - break; - case CG_SP_GETSTRINGTEXT_JK2: - return CG_SP_GETSTRINGTEXT; - break; - case CG_SP_GETSTRINGTEXTSTRING_JK2: - // Both of these do the same thing --eez - return CG_SP_GETSTRINGTEXTSTRING; - break; - case CG_UI_GETITEMTEXT_JK2: - return CG_UI_GETITEMTEXT; - break; - case CG_ANYLANGUAGE_READFROMSTRING2_JK2: - return CG_ANYLANGUAGE_READFROMSTRING2; - break; - case CG_OPENJK_MENU_PAINT_JK2: - return CG_OPENJK_MENU_PAINT; - break; - case CG_OPENJK_GETMENU_BYNAME_JK2: - return CG_OPENJK_GETMENU_BYNAME; - break; + case CG_R_GET_LIGHT_STYLE_JK2: + return CG_R_GET_LIGHT_STYLE; + break; + case CG_R_SET_LIGHT_STYLE_JK2: + return CG_R_SET_LIGHT_STYLE; + break; + case CG_R_GET_BMODEL_VERTS_JK2: + return CG_R_GET_BMODEL_VERTS; + break; + case CG_R_WORLD_EFFECT_COMMAND_JK2: + return CG_R_WORLD_EFFECT_COMMAND; + break; + + case CG_CIN_PLAYCINEMATIC_JK2: + return CG_CIN_PLAYCINEMATIC; + break; + case CG_CIN_STOPCINEMATIC_JK2: + return CG_CIN_STOPCINEMATIC; + break; + case CG_CIN_RUNCINEMATIC_JK2: + return CG_CIN_RUNCINEMATIC; + break; + case CG_CIN_DRAWCINEMATIC_JK2: + return CG_CIN_DRAWCINEMATIC; + break; + case CG_CIN_SETEXTENTS_JK2: + return CG_CIN_SETEXTENTS; + break; + case CG_Z_MALLOC_JK2: + return CG_Z_MALLOC; + break; + case CG_Z_FREE_JK2: + return CG_Z_FREE; + break; + case CG_UI_MENU_RESET_JK2: + return CG_UI_MENU_RESET; + break; + case CG_UI_MENU_NEW_JK2: + return CG_UI_MENU_NEW; + break; + case CG_UI_PARSE_INT_JK2: + return CG_UI_PARSE_INT; + break; + case CG_UI_PARSE_STRING_JK2: + return CG_UI_PARSE_STRING; + break; + case CG_UI_PARSE_FLOAT_JK2: + return CG_UI_PARSE_FLOAT; + break; + case CG_UI_STARTPARSESESSION_JK2: + return CG_UI_STARTPARSESESSION; + break; + case CG_UI_ENDPARSESESSION_JK2: + return CG_UI_ENDPARSESESSION; + break; + case CG_UI_PARSEEXT_JK2: + return CG_UI_PARSEEXT; + break; + case CG_UI_MENUPAINT_ALL_JK2: + return CG_UI_MENUPAINT_ALL; + break; + case CG_UI_STRING_INIT_JK2: + return CG_UI_STRING_INIT; + break; + case CG_UI_GETMENUINFO_JK2: + return CG_UI_GETMENUINFO; + break; + case CG_SP_REGISTER_JK2: + return CG_SP_REGISTER; + break; + case CG_SP_GETSTRINGTEXT_JK2: + return CG_SP_GETSTRINGTEXT; + break; + case CG_SP_GETSTRINGTEXTSTRING_JK2: + // Both of these do the same thing --eez + return CG_SP_GETSTRINGTEXTSTRING; + break; + case CG_UI_GETITEMTEXT_JK2: + return CG_UI_GETITEMTEXT; + break; + case CG_ANYLANGUAGE_READFROMSTRING2_JK2: + return CG_ANYLANGUAGE_READFROMSTRING2; + break; + case CG_OPENJK_MENU_PAINT_JK2: + return CG_OPENJK_MENU_PAINT; + break; + case CG_OPENJK_GETMENU_BYNAME_JK2: + return CG_OPENJK_GETMENU_BYNAME; + break; } return (cgameImport_t)-1; } @@ -805,62 +784,62 @@ CL_CgameSystemCalls The cgame module is making a system call ==================== */ -void CM_SnapPVS(vec3_t origin,byte *buffer); -extern void Menu_Paint(menuDef_t *menu, qboolean forcePaint); +void CM_SnapPVS(vec3_t origin, byte *buffer); +extern void Menu_Paint(menuDef_t *menu, qboolean forcePaint); extern menuDef_t *Menus_FindByName(const char *p); -intptr_t CL_CgameSystemCalls( intptr_t *args ) { +intptr_t CL_CgameSystemCalls(intptr_t *args) { #ifdef JK2_MODE args[0] = (intptr_t)CL_ConvertJK2SysCall((cgameJK2Import_t)args[0]); #endif - switch( args[0] ) { + switch (args[0]) { case CG_PRINT: - Com_Printf( "%s", VMA(1) ); + Com_Printf("%s", VMA(1)); return 0; case CG_ERROR: - Com_Error( ERR_DROP, S_COLOR_RED"%s", VMA(1) ); + Com_Error(ERR_DROP, S_COLOR_RED "%s", VMA(1)); return 0; case CG_MILLISECONDS: return Sys_Milliseconds(); case CG_CVAR_REGISTER: - Cvar_Register( (vmCvar_t *) VMA(1), (const char *) VMA(2), (const char *) VMA(3), args[4] ); + Cvar_Register((vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4]); return 0; case CG_CVAR_UPDATE: - Cvar_Update( (vmCvar_t *) VMA(1) ); + Cvar_Update((vmCvar_t *)VMA(1)); return 0; case CG_CVAR_SET: - Cvar_Set( (const char *) VMA(1), (const char *) VMA(2) ); + Cvar_Set((const char *)VMA(1), (const char *)VMA(2)); return 0; case CG_ARGC: return Cmd_Argc(); case CG_ARGV: - Cmd_ArgvBuffer( args[1], (char *) VMA(2), args[3] ); + Cmd_ArgvBuffer(args[1], (char *)VMA(2), args[3]); return 0; case CG_ARGS: - Cmd_ArgsBuffer( (char *) VMA(1), args[2] ); + Cmd_ArgsBuffer((char *)VMA(1), args[2]); return 0; case CG_FS_FOPENFILE: - return FS_FOpenFileByMode( (const char *) VMA(1), (int *) VMA(2), (fsMode_t) args[3] ); + return FS_FOpenFileByMode((const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3]); case CG_FS_READ: - FS_Read( VMA(1), args[2], args[3] ); + FS_Read(VMA(1), args[2], args[3]); return 0; case CG_FS_WRITE: - FS_Write( VMA(1), args[2], args[3] ); + FS_Write(VMA(1), args[2], args[3]); return 0; case CG_FS_FCLOSEFILE: - FS_FCloseFile( args[1] ); + FS_FCloseFile(args[1]); return 0; case CG_SENDCONSOLECOMMAND: - Cbuf_AddText( (const char *) VMA(1) ); + Cbuf_AddText((const char *)VMA(1)); return 0; case CG_ADDCOMMAND: - CL_AddCgameCommand( (const char *) VMA(1) ); + CL_AddCgameCommand((const char *)VMA(1)); return 0; case CG_SENDCLIENTCOMMAND: - CL_AddReliableCommand( (const char *) VMA(1) ); + CL_AddReliableCommand((const char *)VMA(1)); return 0; case CG_UPDATESCREEN: // this is used during lengthy level loading, so pump message loop - Com_EventLoop(); // FIXME: if a server restarts here, BAD THINGS HAPPEN! + Com_EventLoop(); // FIXME: if a server restarts here, BAD THINGS HAPPEN! SCR_UpdateScreen(); return 0; case CG_RMG_INIT: @@ -872,31 +851,32 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_CM_LOADMAP: - CL_CM_LoadMap( (const char *) VMA(1), (qboolean)(args[2] != 0) ); + CL_CM_LoadMap((const char *)VMA(1), (qboolean)(args[2] != 0)); return 0; case CG_CM_NUMINLINEMODELS: return CM_NumInlineModels(); case CG_CM_INLINEMODEL: - return CM_InlineModel( args[1] ); + return CM_InlineModel(args[1]); case CG_CM_TEMPBOXMODEL: - return CM_TempBoxModel( (const float *) VMA(1), (const float *) VMA(2) );//, (int) VMA(3) ); + return CM_TempBoxModel((const float *)VMA(1), (const float *)VMA(2)); //, (int) VMA(3) ); case CG_CM_POINTCONTENTS: - return CM_PointContents( (float *)VMA(1), args[2] ); + return CM_PointContents((float *)VMA(1), args[2]); case CG_CM_TRANSFORMEDPOINTCONTENTS: - return CM_TransformedPointContents( (const float *) VMA(1), args[2], (const float *) VMA(3), (const float *) VMA(4) ); + return CM_TransformedPointContents((const float *)VMA(1), args[2], (const float *)VMA(3), (const float *)VMA(4)); case CG_CM_BOXTRACE: - CM_BoxTrace( (trace_t *) VMA(1), (const float *) VMA(2), (const float *) VMA(3), (const float *) VMA(4), (const float *) VMA(5), args[6], args[7] ); + CM_BoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7]); return 0; case CG_CM_TRANSFORMEDBOXTRACE: - CM_TransformedBoxTrace( (trace_t *) VMA(1), (const float *) VMA(2), (const float *) VMA(3), (const float *) VMA(4), (const float *) VMA(5), args[6], args[7], (const float *) VMA(8), (const float *) VMA(9) ); + CM_TransformedBoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + (const float *)VMA(8), (const float *)VMA(9)); return 0; case CG_CM_MARKFRAGMENTS: - return re.MarkFragments( args[1], (float(*)[3]) VMA(2), (const float *) VMA(3), args[4], (float *) VMA(5), args[6], (markFragment_t *) VMA(7) ); + return re.MarkFragments(args[1], (float(*)[3])VMA(2), (const float *)VMA(3), args[4], (float *)VMA(5), args[6], (markFragment_t *)VMA(7)); case CG_CM_SNAPPVS: - CM_SnapPVS((float(*))VMA(1),(byte *) VMA(2)); + CM_SnapPVS((float(*))VMA(1), (byte *)VMA(2)); return 0; case CG_S_STOPSOUNDS: - S_StopSounds( ); + S_StopSounds(); return 0; case CG_S_STARTSOUND: @@ -905,7 +885,7 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { if (!cls.cgameStarted) { return 0; } - S_StartSound( (float *) VMA(1), args[2], (soundChannel_t)args[3], args[4] ); + S_StartSound((float *)VMA(1), args[2], (soundChannel_t)args[3], args[4]); return 0; case CG_S_UPDATEAMBIENTSET: // stops an ERR_DROP internally if called illegally from game side, but note that it also gets here @@ -913,25 +893,25 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { if (!cls.cgameStarted) { return 0; } - S_UpdateAmbientSet( (const char *) VMA(1), (float *) VMA(2) ); + S_UpdateAmbientSet((const char *)VMA(1), (float *)VMA(2)); return 0; case CG_S_ADDLOCALSET: - return S_AddLocalSet( (const char *) VMA(1), (float *) VMA(2), (float *) VMA(3), args[4], args[5] ); + return S_AddLocalSet((const char *)VMA(1), (float *)VMA(2), (float *)VMA(3), args[4], args[5]); case CG_AS_PARSESETS: AS_ParseSets(); return 0; case CG_AS_ADDENTRY: - AS_AddPrecacheEntry( (const char *) VMA(1) ); + AS_AddPrecacheEntry((const char *)VMA(1)); return 0; case CG_AS_GETBMODELSOUND: - return AS_GetBModelSound( (const char *) VMA(1), args[2] ); + return AS_GetBModelSound((const char *)VMA(1), args[2]); case CG_S_STARTLOCALSOUND: // stops an ERR_DROP internally if called illegally from game side, but note that it also gets here // legally during level start where normally the internal s_soundStarted check would return. So ok to hit this. if (!cls.cgameStarted) { return 0; } - S_StartLocalSound( args[1], args[2] ); + S_StartLocalSound(args[1], args[2]); return 0; case CG_S_CLEARLOOPINGSOUNDS: S_ClearLoopingSounds(); @@ -942,51 +922,51 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { if (!cls.cgameStarted) { return 0; } - S_AddLoopingSound( args[1], (const float *) VMA(2), (const float *) VMA(3), args[4], (soundChannel_t)args[5] ); + S_AddLoopingSound(args[1], (const float *)VMA(2), (const float *)VMA(3), args[4], (soundChannel_t)args[5]); return 0; case CG_S_UPDATEENTITYPOSITION: - S_UpdateEntityPosition( args[1], (const float *) VMA(2) ); + S_UpdateEntityPosition(args[1], (const float *)VMA(2)); return 0; case CG_S_RESPATIALIZE: - S_Respatialize( args[1], (const float *) VMA(2), (float(*)[3]) VMA(3), (qboolean)(args[4] != 0) ); + S_Respatialize(args[1], (const float *)VMA(2), (float(*)[3])VMA(3), (qboolean)(args[4] != 0)); return 0; case CG_S_REGISTERSOUND: - return S_RegisterSound( (const char *) VMA(1) ); + return S_RegisterSound((const char *)VMA(1)); case CG_S_STARTBACKGROUNDTRACK: - S_StartBackgroundTrack( (const char *) VMA(1), (const char *) VMA(2), (qboolean)(args[3] != 0) ); + S_StartBackgroundTrack((const char *)VMA(1), (const char *)VMA(2), (qboolean)(args[3] != 0)); return 0; case CG_S_GETSAMPLELENGTH: - return S_GetSampleLengthInMilliSeconds( args[1]); + return S_GetSampleLengthInMilliSeconds(args[1]); case CG_R_LOADWORLDMAP: - re.LoadWorld( (const char *) VMA(1) ); + re.LoadWorld((const char *)VMA(1)); return 0; case CG_R_REGISTERMODEL: - return re.RegisterModel( (const char *) VMA(1) ); + return re.RegisterModel((const char *)VMA(1)); case CG_R_REGISTERSKIN: - return re.RegisterSkin( (const char *) VMA(1) ); + return re.RegisterSkin((const char *)VMA(1)); case CG_R_REGISTERSHADER: - return re.RegisterShader( (const char *) VMA(1) ); + return re.RegisterShader((const char *)VMA(1)); case CG_R_REGISTERSHADERNOMIP: - return re.RegisterShaderNoMip( (const char *) VMA(1) ); + return re.RegisterShaderNoMip((const char *)VMA(1)); case CG_R_REGISTERFONT: - return re.RegisterFont( (const char *) VMA(1) ); + return re.RegisterFont((const char *)VMA(1)); case CG_R_FONTSTRLENPIXELS: - return re.Font_StrLenPixels( (const char *) VMA(1), args[2], VMF(3) ); + return re.Font_StrLenPixels((const char *)VMA(1), args[2], VMF(3)); case CG_R_FONTSTRLENCHARS: - return re.Font_StrLenChars( (const char *) VMA(1) ); + return re.Font_StrLenChars((const char *)VMA(1)); case CG_R_FONTHEIGHTPIXELS: - return re.Font_HeightPixels( args[1], VMF(2) ); + return re.Font_HeightPixels(args[1], VMF(2)); case CG_R_FONTDRAWSTRING: - re.Font_DrawString(args[1],args[2], (const char *) VMA(3), (float*)args[4], args[5], args[6], VMF(7)); + re.Font_DrawString(args[1], args[2], (const char *)VMA(3), (float *)args[4], args[5], args[6], VMF(7)); return 0; case CG_LANGUAGE_ISASIAN: return re.Language_IsAsian(); case CG_LANGUAGE_USESSPACES: return re.Language_UsesSpaces(); case CG_ANYLANGUAGE_READFROMSTRING: - return re.AnyLanguage_ReadCharFromString( (char *) VMA(1), (int *) VMA(2), (qboolean *) VMA(3) ); + return re.AnyLanguage_ReadCharFromString((char *)VMA(1), (int *)VMA(2), (qboolean *)VMA(3)); case CG_ANYLANGUAGE_READFROMSTRING2: - return re.AnyLanguage_ReadCharFromString2( (char **) VMA(1), (qboolean *) VMA(3) ); + return re.AnyLanguage_ReadCharFromString2((char **)VMA(1), (qboolean *)VMA(3)); case CG_R_SETREFRACTIONPROP: *(re.tr_distortionAlpha()) = VMF(1); *(re.tr_distortionStretch()) = VMF(2); @@ -997,152 +977,152 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { re.ClearScene(); return 0; case CG_R_ADDREFENTITYTOSCENE: - re.AddRefEntityToScene( (const refEntity_t *) VMA(1) ); + re.AddRefEntityToScene((const refEntity_t *)VMA(1)); return 0; case CG_R_INPVS: - return re.R_inPVS((float *) VMA(1), (float *) VMA(2)); + return re.R_inPVS((float *)VMA(1), (float *)VMA(2)); case CG_R_GETLIGHTING: - return re.GetLighting( (const float * ) VMA(1), (float *) VMA(2), (float *) VMA(3), (float *) VMA(4) ); + return re.GetLighting((const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4)); case CG_R_ADDPOLYTOSCENE: - re.AddPolyToScene( args[1], args[2], (const polyVert_t *) VMA(3) ); + re.AddPolyToScene(args[1], args[2], (const polyVert_t *)VMA(3)); return 0; case CG_R_ADDLIGHTTOSCENE: - re.AddLightToScene( (const float *) VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) ); + re.AddLightToScene((const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5)); return 0; case CG_R_RENDERSCENE: - re.RenderScene( (const refdef_t *) VMA(1) ); + re.RenderScene((const refdef_t *)VMA(1)); return 0; case CG_R_SETCOLOR: - re.SetColor( (const float *) VMA(1) ); + re.SetColor((const float *)VMA(1)); return 0; case CG_R_DRAWSTRETCHPIC: - re.DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] ); + re.DrawStretchPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9]); return 0; // The below was commented out for whatever reason... /me shrugs --eez case CG_R_DRAWSCREENSHOT: - re.DrawStretchRaw( VMF(1), VMF(2), VMF(3), VMF(4), SG_SCR_WIDTH, SG_SCR_HEIGHT, SCR_GetScreenshot(0), 0, qtrue); + re.DrawStretchRaw(VMF(1), VMF(2), VMF(3), VMF(4), SG_SCR_WIDTH, SG_SCR_HEIGHT, SCR_GetScreenshot(0), 0, qtrue); return 0; case CG_R_MODELBOUNDS: - re.ModelBounds( args[1], (float *) VMA(2), (float *) VMA(3) ); + re.ModelBounds(args[1], (float *)VMA(2), (float *)VMA(3)); return 0; case CG_R_LERPTAG: - re.LerpTag( (orientation_t *) VMA(1), args[2], args[3], args[4], VMF(5), (const char *) VMA(6) ); + re.LerpTag((orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6)); return 0; case CG_R_DRAWROTATEPIC: - re.DrawRotatePic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10] ); + re.DrawRotatePic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10]); return 0; case CG_R_DRAWROTATEPIC2: - re.DrawRotatePic2( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10] ); + re.DrawRotatePic2(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10]); return 0; case CG_R_SETRANGEFOG: - re.SetRangedFog( VMF( 1 ) ); + re.SetRangedFog(VMF(1)); return 0; case CG_R_LA_GOGGLES: re.LAGoggles(); return 0; case CG_R_SCISSOR: - re.Scissor( VMF(1), VMF(2), VMF(3), VMF(4)); + re.Scissor(VMF(1), VMF(2), VMF(3), VMF(4)); return 0; case CG_GETGLCONFIG: - CL_GetGlconfig( (glconfig_t *) VMA(1) ); + CL_GetGlconfig((glconfig_t *)VMA(1)); return 0; case CG_GETGAMESTATE: - CL_GetGameState( (gameState_t *) VMA(1) ); + CL_GetGameState((gameState_t *)VMA(1)); return 0; case CG_GETCURRENTSNAPSHOTNUMBER: - CL_GetCurrentSnapshotNumber( (int *) VMA(1), (int *) VMA(2) ); + CL_GetCurrentSnapshotNumber((int *)VMA(1), (int *)VMA(2)); return 0; case CG_GETSNAPSHOT: - return CL_GetSnapshot( args[1], (snapshot_t *) VMA(2) ); + return CL_GetSnapshot(args[1], (snapshot_t *)VMA(2)); case CG_GETDEFAULTSTATE: return CL_GetDefaultState(args[1], (entityState_t *)VMA(2)); case CG_GETSERVERCOMMAND: - return CL_GetServerCommand( args[1] ); + return CL_GetServerCommand(args[1]); case CG_GETCURRENTCMDNUMBER: return CL_GetCurrentCmdNumber(); case CG_GETUSERCMD: - return CL_GetUserCmd( args[1], (usercmd_s *) VMA(2) ); + return CL_GetUserCmd(args[1], (usercmd_s *)VMA(2)); case CG_SETUSERCMDVALUE: - CL_SetUserCmdValue( args[1], VMF(2), VMF(3), VMF(4) ); + CL_SetUserCmdValue(args[1], VMF(2), VMF(3), VMF(4)); return 0; case CG_SETUSERCMDANGLES: - CL_SetUserCmdAngles( VMF(1), VMF(2), VMF(3) ); + CL_SetUserCmdAngles(VMF(1), VMF(2), VMF(3)); return 0; case COM_SETORGANGLES: - Com_SetOrgAngles((float *)VMA(1),(float *)VMA(2)); + Com_SetOrgAngles((float *)VMA(1), (float *)VMA(2)); return 0; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ case CG_G2_LISTSURFACES: - re.G2API_ListSurfaces( (CGhoul2Info *) VMA(1) ); + re.G2API_ListSurfaces((CGhoul2Info *)VMA(1)); return 0; case CG_G2_LISTBONES: - re.G2API_ListBones( (CGhoul2Info *) VMA(1), args[2]); + re.G2API_ListBones((CGhoul2Info *)VMA(1), args[2]); return 0; case CG_G2_HAVEWEGHOULMODELS: - return re.G2API_HaveWeGhoul2Models( *((CGhoul2Info_v *)VMA(1)) ); + return re.G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)VMA(1))); case CG_G2_SETMODELS: - re.G2API_SetGhoul2ModelIndexes( *((CGhoul2Info_v *)VMA(1)),(qhandle_t *)VMA(2),(qhandle_t *)VMA(3)); + re.G2API_SetGhoul2ModelIndexes(*((CGhoul2Info_v *)VMA(1)), (qhandle_t *)VMA(2), (qhandle_t *)VMA(3)); return 0; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ case CG_R_GET_LIGHT_STYLE: - re.GetLightStyle(args[1], (byte*) VMA(2) ); + re.GetLightStyle(args[1], (byte *)VMA(2)); return 0; case CG_R_SET_LIGHT_STYLE: - re.SetLightStyle(args[1], args[2] ); + re.SetLightStyle(args[1], args[2]); return 0; case CG_R_GET_BMODEL_VERTS: - re.GetBModelVerts( args[1], (float (*)[3])VMA(2), (float *)VMA(3) ); + re.GetBModelVerts(args[1], (float(*)[3])VMA(2), (float *)VMA(3)); return 0; case CG_R_WORLD_EFFECT_COMMAND: - re.WorldEffectCommand( (const char *) VMA(1) ); + re.WorldEffectCommand((const char *)VMA(1)); return 0; case CG_CIN_PLAYCINEMATIC: - return CIN_PlayCinematic( (const char *) VMA(1), args[2], args[3], args[4], args[5], args[6], (const char *) VMA(7)); + return CIN_PlayCinematic((const char *)VMA(1), args[2], args[3], args[4], args[5], args[6], (const char *)VMA(7)); case CG_CIN_STOPCINEMATIC: - return CIN_StopCinematic(args[1]); + return CIN_StopCinematic(args[1]); case CG_CIN_RUNCINEMATIC: - return CIN_RunCinematic(args[1]); + return CIN_RunCinematic(args[1]); case CG_CIN_DRAWCINEMATIC: - CIN_DrawCinematic(args[1]); - return 0; + CIN_DrawCinematic(args[1]); + return 0; case CG_CIN_SETEXTENTS: - CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]); - return 0; + CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]); + return 0; case CG_Z_MALLOC: - return (intptr_t)Z_Malloc(args[1], (memtag_t) args[2], qfalse); + return (intptr_t)Z_Malloc(args[1], (memtag_t)args[2], qfalse); case CG_Z_FREE: - Z_Free((void *) VMA(1)); + Z_Free((void *)VMA(1)); return 0; case CG_UI_SETACTIVE_MENU: - UI_SetActiveMenu((const char *) VMA(1),NULL); + UI_SetActiveMenu((const char *)VMA(1), NULL); return 0; case CG_UI_MENU_OPENBYNAME: - Menus_OpenByName((const char *) VMA(1)); + Menus_OpenByName((const char *)VMA(1)); return 0; case CG_UI_MENU_RESET: @@ -1150,35 +1130,34 @@ Ghoul2 Insert End return 0; case CG_UI_MENU_NEW: - Menu_New((char *) VMA(1)); + Menu_New((char *)VMA(1)); return 0; case CG_UI_PARSE_INT: - PC_ParseInt((int *) VMA(1)); + PC_ParseInt((int *)VMA(1)); return 0; case CG_UI_PARSE_STRING: - PC_ParseString((const char **) VMA(1)); + PC_ParseString((const char **)VMA(1)); return 0; case CG_UI_PARSE_FLOAT: - PC_ParseFloat((float *) VMA(1)); + PC_ParseFloat((float *)VMA(1)); return 0; case CG_UI_STARTPARSESESSION: - return(PC_StartParseSession((char *) VMA(1),(char **) VMA(2))); + return (PC_StartParseSession((char *)VMA(1), (char **)VMA(2))); case CG_UI_ENDPARSESESSION: - PC_EndParseSession((char *) VMA(1)); + PC_EndParseSession((char *)VMA(1)); return 0; case CG_UI_PARSEEXT: char **holdPtr; - holdPtr = (char **) VMA(1); + holdPtr = (char **)VMA(1); - if(!holdPtr) - { + if (!holdPtr) { Com_Error(ERR_FATAL, "CG_UI_PARSEEXT: NULL holdPtr"); } @@ -1194,11 +1173,11 @@ Ghoul2 Insert End return 0; case CG_OPENJK_MENU_PAINT: - Menu_Paint( (menuDef_t *)VMA(1), (qboolean)(args[2] != 0) ); + Menu_Paint((menuDef_t *)VMA(1), (qboolean)(args[2] != 0)); return 0; case CG_OPENJK_GETMENU_BYNAME: - return (intptr_t)Menus_FindByName( (const char *)VMA(1) ); + return (intptr_t)Menus_FindByName((const char *)VMA(1)); case CG_UI_STRING_INIT: String_Init(); @@ -1206,39 +1185,33 @@ Ghoul2 Insert End case CG_UI_GETMENUINFO: menuDef_t *menu; - int *xPos,*yPos,*w,*h,result; + int *xPos, *yPos, *w, *h, result; #ifndef JK2_MODE - menu = Menus_FindByName((char *) VMA(1)); // Get menu - if (menu) - { - xPos = (int *) VMA(2); - *xPos = (int) menu->window.rect.x; - yPos = (int *) VMA(3); - *yPos = (int) menu->window.rect.y; - w = (int *) VMA(4); - *w = (int) menu->window.rect.w; - h = (int *) VMA(5); - *h = (int) menu->window.rect.h; + menu = Menus_FindByName((char *)VMA(1)); // Get menu + if (menu) { + xPos = (int *)VMA(2); + *xPos = (int)menu->window.rect.x; + yPos = (int *)VMA(3); + *yPos = (int)menu->window.rect.y; + w = (int *)VMA(4); + *w = (int)menu->window.rect.w; + h = (int *)VMA(5); + *h = (int)menu->window.rect.h; result = qtrue; - } - else - { + } else { result = qfalse; } return result; #else - menu = Menus_FindByName((char *) VMA(1)); // Get menu - if (menu) - { - xPos = (int *) VMA(2); - *xPos = (int) menu->window.rect.x; - yPos = (int *) VMA(3); - *yPos = (int) menu->window.rect.y; + menu = Menus_FindByName((char *)VMA(1)); // Get menu + if (menu) { + xPos = (int *)VMA(2); + *xPos = (int)menu->window.rect.x; + yPos = (int *)VMA(3); + *yPos = (int)menu->window.rect.y; result = qtrue; - } - else - { + } else { result = qfalse; } @@ -1248,75 +1221,61 @@ Ghoul2 Insert End case CG_UI_GETITEMTEXT: itemDef_t *item; - menu = Menus_FindByName((char *) VMA(1)); // Get menu + menu = Menus_FindByName((char *)VMA(1)); // Get menu - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, (char *) VMA(2)); - if (item) - { - Q_strncpyz( (char *) VMA(3), item->text, 256 ); + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, (char *)VMA(2)); + if (item) { + Q_strncpyz((char *)VMA(3), item->text, 256); result = qtrue; - } - else - { + } else { result = qfalse; } - } - else - { + } else { result = qfalse; } return result; case CG_UI_GETITEMINFO: - menu = Menus_FindByName((char *) VMA(1)); // Get menu + menu = Menus_FindByName((char *)VMA(1)); // Get menu - if (menu) - { + if (menu) { qhandle_t *background; - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, (char *) VMA(2)); - if (item) - { - xPos = (int *) VMA(3); - *xPos = (int) item->window.rect.x; - yPos = (int *) VMA(4); - *yPos = (int) item->window.rect.y; - w = (int *) VMA(5); - *w = (int) item->window.rect.w; - h = (int *) VMA(6); - *h = (int) item->window.rect.h; + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, (char *)VMA(2)); + if (item) { + xPos = (int *)VMA(3); + *xPos = (int)item->window.rect.x; + yPos = (int *)VMA(4); + *yPos = (int)item->window.rect.y; + w = (int *)VMA(5); + *w = (int)item->window.rect.w; + h = (int *)VMA(6); + *h = (int)item->window.rect.h; vec4_t *color; - color = (vec4_t *) VMA(7); - if (!color) - { + color = (vec4_t *)VMA(7); + if (!color) { return qfalse; } - (*color)[0] = (float) item->window.foreColor[0]; - (*color)[1] = (float) item->window.foreColor[1]; - (*color)[2] = (float) item->window.foreColor[2]; - (*color)[3] = (float) item->window.foreColor[3]; - background = (qhandle_t *) VMA(8); - if (!background) - { + (*color)[0] = (float)item->window.foreColor[0]; + (*color)[1] = (float)item->window.foreColor[1]; + (*color)[2] = (float)item->window.foreColor[2]; + (*color)[3] = (float)item->window.foreColor[3]; + background = (qhandle_t *)VMA(8); + if (!background) { return qfalse; } *background = item->window.background; result = qtrue; - } - else - { + } else { result = qfalse; } - } - else - { + } else { result = qfalse; } @@ -1325,29 +1284,23 @@ Ghoul2 Insert End #ifdef JK2_MODE case CG_SP_GETSTRINGTEXTSTRING: case CG_SP_GETSTRINGTEXT: - const char* text; + const char *text; assert(VMA(1)); -// assert(VMA(2)); // can now pass in NULL to just query the size + // assert(VMA(2)); // can now pass in NULL to just query the size - if (args[0] == CG_SP_GETSTRINGTEXT) - { - text = JK2SP_GetStringText( args[1] ); - } - else - { - text = JK2SP_GetStringTextString( (const char *) VMA(1) ); + if (args[0] == CG_SP_GETSTRINGTEXT) { + text = JK2SP_GetStringText(args[1]); + } else { + text = JK2SP_GetStringTextString((const char *)VMA(1)); } - if (VMA(2)) // only if dest buffer supplied... + if (VMA(2)) // only if dest buffer supplied... { - if ( text[0] ) - { - Q_strncpyz( (char *) VMA(2), text, args[3] ); - } - else - { - Q_strncpyz( (char *) VMA(2), "??", args[3] ); + if (text[0]) { + Q_strncpyz((char *)VMA(2), text, args[3]); + } else { + Q_strncpyz((char *)VMA(2), "??", args[3]); } } return strlen(text); @@ -1356,32 +1309,28 @@ Ghoul2 Insert End return JK2SP_Register((const char *)VMA(1), args[2] ? (SP_REGISTER_MENU | SP_REGISTER_REQUIRED) : SP_REGISTER_CLIENT); #else case CG_SP_GETSTRINGTEXTSTRING: - const char* text; + const char *text; assert(VMA(1)); - text = SE_GetString( (const char *) VMA(1) ); + text = SE_GetString((const char *)VMA(1)); - if (VMA(2)) // only if dest buffer supplied... + if (VMA(2)) // only if dest buffer supplied... { - if ( text[0] ) - { - Q_strncpyz( (char *) VMA(2), text, args[3] ); - } - else - { - Com_sprintf( (char *) VMA(2), args[3], "??%s", VMA(1) ); + if (text[0]) { + Q_strncpyz((char *)VMA(2), text, args[3]); + } else { + Com_sprintf((char *)VMA(2), args[3], "??%s", VMA(1)); } } return strlen(text); #endif default: - Com_Error( ERR_DROP, "Bad cgame system trap: %ld", (long int) args[0] ); + Com_Error(ERR_DROP, "Bad cgame system trap: %ld", (long int)args[0]); } return 0; } - /* ==================== CL_InitCGame @@ -1390,52 +1339,49 @@ Should only be called by CL_StartHunkUsers ==================== */ extern qboolean Sys_LowPhysicalMemory(); -void CL_InitCGame( void ) { - const char *info; - const char *mapname; - //int t1, t2; +void CL_InitCGame(void) { + const char *info; + const char *mapname; + // int t1, t2; - //t1 = Sys_Milliseconds(); + // t1 = Sys_Milliseconds(); // put away the console Con_Close(); // find the current mapname - info = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ]; - mapname = Info_ValueForKey( info, "mapname" ); - Com_sprintf( cl.mapname, sizeof( cl.mapname ), "maps/%s.bsp", mapname ); + info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SERVERINFO]; + mapname = Info_ValueForKey(info, "mapname"); + Com_sprintf(cl.mapname, sizeof(cl.mapname), "maps/%s.bsp", mapname); cls.state = CA_LOADING; // init for this gamestate - VM_Call( CG_INIT, clc.serverCommandSequence ); + VM_Call(CG_INIT, clc.serverCommandSequence); // reset any CVAR_CHEAT cvars registered by cgame - if ( !cl_connectedToCheatServer ) + if (!cl_connectedToCheatServer) Cvar_SetCheatState(); // we will send a usercmd this frame, which // will cause the server to send us the first snapshot cls.state = CA_PRIMED; - //t2 = Sys_Milliseconds(); + // t2 = Sys_Milliseconds(); - //Com_Printf( "CL_InitCGame: %5.2f seconds\n", (t2-t1)/1000.0 ); - // have the renderer touch all its images, so they are present - // on the card even if the driver does deferred loading + // Com_Printf( "CL_InitCGame: %5.2f seconds\n", (t2-t1)/1000.0 ); + // have the renderer touch all its images, so they are present + // on the card even if the driver does deferred loading re.EndRegistration(); // make sure everything is paged in -// if (!Sys_LowPhysicalMemory()) - { - Com_TouchMemory(); - } + // if (!Sys_LowPhysicalMemory()) + { Com_TouchMemory(); } // clear anything that got printed - Con_ClearNotify (); + Con_ClearNotify(); } - /* ==================== CL_GameCommand @@ -1443,22 +1389,20 @@ CL_GameCommand See if the current console command is claimed by the cgame ==================== */ -qboolean CL_GameCommand( void ) { - if ( cls.state != CA_ACTIVE ) { +qboolean CL_GameCommand(void) { + if (cls.state != CA_ACTIVE) { return qfalse; } - return (qboolean)(VM_Call( CG_CONSOLE_COMMAND ) != 0); + return (qboolean)(VM_Call(CG_CONSOLE_COMMAND) != 0); } - - /* ===================== CL_CGameRendering ===================== */ -void CL_CGameRendering( stereoFrame_t stereo ) { +void CL_CGameRendering(stereoFrame_t stereo) { #if 0 if ( cls.state == CA_ACTIVE ) { static int counter; @@ -1468,17 +1412,15 @@ void CL_CGameRendering( stereoFrame_t stereo ) { } } #endif - int timei=cl.serverTime; - if (timei>60) - { - timei-=0; + int timei = cl.serverTime; + if (timei > 60) { + timei -= 0; } - re.G2API_SetTime(cl.serverTime,G2T_CG_TIME); - VM_Call( CG_DRAW_ACTIVE_FRAME,timei, stereo, qfalse ); -// VM_Debug( 0 ); + re.G2API_SetTime(cl.serverTime, G2T_CG_TIME); + VM_Call(CG_DRAW_ACTIVE_FRAME, timei, stereo, qfalse); + // VM_Debug( 0 ); } - /* ================= CL_AdjustTimeDelta @@ -1498,64 +1440,64 @@ during times of significant packet loss. ================= */ -#define RESET_TIME 300 - -void CL_AdjustTimeDelta( void ) { -/* - cl.newSnapshots = qfalse; - // if the current time is WAY off, just correct to the current value - if ( cls.realtime + cl.serverTimeDelta < cl.frame.serverTime - RESET_TIME - || cls.realtime + cl.serverTimeDelta > cl.frame.serverTime + RESET_TIME ) { - cl.serverTimeDelta = cl.frame.serverTime - cls.realtime; - cl.oldServerTime = cl.frame.serverTime; - if ( cl_showTimeDelta->integer ) { - Com_Printf( " " ); +#define RESET_TIME 300 + +void CL_AdjustTimeDelta(void) { + /* + cl.newSnapshots = qfalse; + // if the current time is WAY off, just correct to the current value + if ( cls.realtime + cl.serverTimeDelta < cl.frame.serverTime - RESET_TIME + || cls.realtime + cl.serverTimeDelta > cl.frame.serverTime + RESET_TIME ) { + cl.serverTimeDelta = cl.frame.serverTime - cls.realtime; + cl.oldServerTime = cl.frame.serverTime; + if ( cl_showTimeDelta->integer ) { + Com_Printf( " " ); + } } - } - // if any of the frames between this and the previous snapshot - // had to be extrapolated, nudge our sense of time back a little - if ( cl.extrapolatedSnapshot ) { - cl.extrapolatedSnapshot = qfalse; - cl.serverTimeDelta -= 2; - } else { - // otherwise, move our sense of time forward to minimize total latency - cl.serverTimeDelta++; - } + // if any of the frames between this and the previous snapshot + // had to be extrapolated, nudge our sense of time back a little + if ( cl.extrapolatedSnapshot ) { + cl.extrapolatedSnapshot = qfalse; + cl.serverTimeDelta -= 2; + } else { + // otherwise, move our sense of time forward to minimize total latency + cl.serverTimeDelta++; + } - if ( cl_showTimeDelta->integer ) { - Com_Printf( "%i ", cl.serverTimeDelta ); - } -*/ - int newDelta; - int deltaDelta; + if ( cl_showTimeDelta->integer ) { + Com_Printf( "%i ", cl.serverTimeDelta ); + } + */ + int newDelta; + int deltaDelta; cl.newSnapshots = qfalse; newDelta = cl.frame.serverTime - cls.realtime; - deltaDelta = abs( newDelta - cl.serverTimeDelta ); + deltaDelta = abs(newDelta - cl.serverTimeDelta); - if ( deltaDelta > RESET_TIME ) { + if (deltaDelta > RESET_TIME) { cl.serverTimeDelta = newDelta; - cl.oldServerTime = cl.frame.serverTime; // FIXME: is this a problem for cgame? + cl.oldServerTime = cl.frame.serverTime; // FIXME: is this a problem for cgame? cl.serverTime = cl.frame.serverTime; - if ( cl_showTimeDelta->integer ) { - Com_Printf( " " ); + if (cl_showTimeDelta->integer) { + Com_Printf(" "); } - } else if ( deltaDelta > 100 ) { + } else if (deltaDelta > 100) { // fast adjust, cut the difference in half - if ( cl_showTimeDelta->integer ) { - Com_Printf( " " ); + if (cl_showTimeDelta->integer) { + Com_Printf(" "); } - cl.serverTimeDelta = ( cl.serverTimeDelta + newDelta ) >> 1; + cl.serverTimeDelta = (cl.serverTimeDelta + newDelta) >> 1; } else { // slow drift adjust, only move 1 or 2 msec // if any of the frames between this and the previous snapshot // had to be extrapolated, nudge our sense of time back a little // the granularity of +1 / -2 is too high for timescale modified frametimes - if ( com_timescale->value == 0 || com_timescale->value == 1 ) { - if ( cl.extrapolatedSnapshot ) { + if (com_timescale->value == 0 || com_timescale->value == 1) { + if (cl.extrapolatedSnapshot) { cl.extrapolatedSnapshot = qfalse; cl.serverTimeDelta -= 2; } else { @@ -1565,18 +1507,17 @@ void CL_AdjustTimeDelta( void ) { } } - if ( cl_showTimeDelta->integer ) { - Com_Printf( "%i ", cl.serverTimeDelta ); + if (cl_showTimeDelta->integer) { + Com_Printf("%i ", cl.serverTimeDelta); } } - /* ================== CL_FirstSnapshot ================== */ -void CL_FirstSnapshot( void ) { +void CL_FirstSnapshot(void) { re.RegisterMedia_LevelLoadEnd(); @@ -1590,9 +1531,9 @@ void CL_FirstSnapshot( void ) { // execute the contents of activeAction now // this is to allow scripting a timedemo to start right // after loading - if ( cl_activeAction->string[0] ) { - Cbuf_AddText( cl_activeAction->string ); - Cvar_Set( "activeAction", "" ); + if (cl_activeAction->string[0]) { + Cbuf_AddText(cl_activeAction->string); + Cvar_Set("activeAction", ""); } } @@ -1601,40 +1542,39 @@ void CL_FirstSnapshot( void ) { CL_SetCGameTime ================== */ -void CL_SetCGameTime( void ) { +void CL_SetCGameTime(void) { // getting a valid frame message ends the connection process - if ( cls.state != CA_ACTIVE ) { - if ( cls.state != CA_PRIMED ) { + if (cls.state != CA_ACTIVE) { + if (cls.state != CA_PRIMED) { return; } - if ( cl.newSnapshots ) { + if (cl.newSnapshots) { cl.newSnapshots = qfalse; CL_FirstSnapshot(); } - if ( cls.state != CA_ACTIVE ) { + if (cls.state != CA_ACTIVE) { return; } } // if we have gotten to this point, cl.frame is guaranteed to be valid - if ( !cl.frame.valid ) { - Com_Error( ERR_DROP, "CL_SetCGameTime: !cl.snap.valid" ); + if (!cl.frame.valid) { + Com_Error(ERR_DROP, "CL_SetCGameTime: !cl.snap.valid"); } // allow pause in single player - if ( sv_paused->integer && CL_CheckPaused() && com_sv_running->integer ) { + if (sv_paused->integer && CL_CheckPaused() && com_sv_running->integer) { // paused return; } - if ( cl.frame.serverTime < cl.oldFrameServerTime ) { - Com_Error( ERR_DROP, "cl.frame.serverTime < cl.oldFrameServerTime" ); + if (cl.frame.serverTime < cl.oldFrameServerTime) { + Com_Error(ERR_DROP, "cl.frame.serverTime < cl.oldFrameServerTime"); } cl.oldFrameServerTime = cl.frame.serverTime; - // get our current view of time // cl_timeNudge is a user adjustable cvar that allows more @@ -1644,22 +1584,21 @@ void CL_SetCGameTime( void ) { // guarantee that time will never flow backwards, even if // serverTimeDelta made an adjustment or cl_timeNudge was changed - if ( cl.serverTime < cl.oldServerTime ) { + if (cl.serverTime < cl.oldServerTime) { cl.serverTime = cl.oldServerTime; } cl.oldServerTime = cl.serverTime; // note if we are almost past the latest frame (without timeNudge), // so we will try and adjust back a bit when the next snapshot arrives - if ( cls.realtime + cl.serverTimeDelta >= cl.frame.serverTime - 5 ) { + if (cls.realtime + cl.serverTimeDelta >= cl.frame.serverTime - 5) { cl.extrapolatedSnapshot = qtrue; } // if we have gotten new snapshots, drift serverTimeDelta // don't do this every frame, or a period of packet loss would // make a huge adjustment - if ( cl.newSnapshots ) { + if (cl.newSnapshots) { CL_AdjustTimeDelta(); } } - diff --git a/code/client/cl_cin.cpp b/code/client/cl_cin.cpp index 7cf2db8c2f..812983d31b 100644 --- a/code/client/cl_cin.cpp +++ b/code/client/cl_cin.cpp @@ -40,140 +40,135 @@ along with this program; if not, see . *****************************************************************************/ #include "client.h" -#include "client_ui.h" // CHC +#include "client_ui.h" // CHC #include "snd_local.h" #include "qcommon/stringed_ingame.h" -#define MAXSIZE 8 -#define MINSIZE 4 +#define MAXSIZE 8 +#define MINSIZE 4 -#define DEFAULT_CIN_WIDTH 512 -#define DEFAULT_CIN_HEIGHT 512 +#define DEFAULT_CIN_WIDTH 512 +#define DEFAULT_CIN_HEIGHT 512 -#define ROQ_QUAD 0x1000 -#define ROQ_QUAD_INFO 0x1001 -#define ROQ_CODEBOOK 0x1002 -#define ROQ_QUAD_VQ 0x1011 -#define ROQ_QUAD_JPEG 0x1012 -#define ROQ_QUAD_HANG 0x1013 -#define ROQ_PACKET 0x1030 -#define ZA_SOUND_MONO 0x1020 -#define ZA_SOUND_STEREO 0x1021 +#define ROQ_QUAD 0x1000 +#define ROQ_QUAD_INFO 0x1001 +#define ROQ_CODEBOOK 0x1002 +#define ROQ_QUAD_VQ 0x1011 +#define ROQ_QUAD_JPEG 0x1012 +#define ROQ_QUAD_HANG 0x1013 +#define ROQ_PACKET 0x1030 +#define ZA_SOUND_MONO 0x1020 +#define ZA_SOUND_STEREO 0x1021 -#define MAX_VIDEO_HANDLES 16 +#define MAX_VIDEO_HANDLES 16 extern void S_CIN_StopSound(sfxHandle_t sfxHandle); -static void RoQ_init( void ); +static void RoQ_init(void); /****************************************************************************** -* -* Class: trFMV -* -* Description: RoQ/RnR manipulation routines -* not entirely complete for first run -* -******************************************************************************/ - -static long ROQ_YY_tab[256]; -static long ROQ_UB_tab[256]; -static long ROQ_UG_tab[256]; -static long ROQ_VG_tab[256]; -static long ROQ_VR_tab[256]; -static unsigned short vq2[256*16*4]; -static unsigned short vq4[256*64*4]; -static unsigned short vq8[256*256*4]; + * + * Class: trFMV + * + * Description: RoQ/RnR manipulation routines + * not entirely complete for first run + * + ******************************************************************************/ + +static long ROQ_YY_tab[256]; +static long ROQ_UB_tab[256]; +static long ROQ_UG_tab[256]; +static long ROQ_VG_tab[256]; +static long ROQ_VR_tab[256]; +static unsigned short vq2[256 * 16 * 4]; +static unsigned short vq4[256 * 64 * 4]; +static unsigned short vq8[256 * 256 * 4]; typedef struct { - byte linbuf[DEFAULT_CIN_WIDTH*DEFAULT_CIN_HEIGHT*4*2]; - byte file[65536]; - short sqrTable[256]; + byte linbuf[DEFAULT_CIN_WIDTH * DEFAULT_CIN_HEIGHT * 4 * 2]; + byte file[65536]; + short sqrTable[256]; - int mcomp[256]; - byte *qStatus[2][32768]; + int mcomp[256]; + byte *qStatus[2][32768]; - long oldXOff, oldYOff, oldysize, oldxsize; + long oldXOff, oldYOff, oldysize, oldxsize; - int currentHandle; + int currentHandle; } cinematics_t; typedef struct { - char fileName[MAX_OSPATH]; - int CIN_WIDTH, CIN_HEIGHT; - int xpos, ypos, width, height; - qboolean looping, holdAtEnd, dirty, alterGameState, silent, shader; - fileHandle_t iFile; // 0 = none - e_status status; - unsigned int startTime; - unsigned int lastTime; - long tfps; - long RoQPlayed; - long ROQSize; - unsigned int RoQFrameSize; - long onQuad; - long numQuads; - long samplesPerLine; - unsigned int roq_id; - long screenDelta; - - void ( *VQ0)(byte *status, void *qdata ); - void ( *VQ1)(byte *status, void *qdata ); - void ( *VQNormal)(byte *status, void *qdata ); - void ( *VQBuffer)(byte *status, void *qdata ); - - long samplesPerPixel; // defaults to 2 - byte* gray; - unsigned int xsize, ysize, maxsize, minsize; - - qboolean half, smootheddouble, inMemory; - long normalBuffer0; - long roq_flags; - long roqF0; - long roqF1; - long t[2]; - long roqFPS; - int playonwalls; - byte* buf; - long drawX, drawY; - sfxHandle_t hSFX; // 0 = none - qhandle_t hCRAWLTEXT; // 0 = none + char fileName[MAX_OSPATH]; + int CIN_WIDTH, CIN_HEIGHT; + int xpos, ypos, width, height; + qboolean looping, holdAtEnd, dirty, alterGameState, silent, shader; + fileHandle_t iFile; // 0 = none + e_status status; + unsigned int startTime; + unsigned int lastTime; + long tfps; + long RoQPlayed; + long ROQSize; + unsigned int RoQFrameSize; + long onQuad; + long numQuads; + long samplesPerLine; + unsigned int roq_id; + long screenDelta; + + void (*VQ0)(byte *status, void *qdata); + void (*VQ1)(byte *status, void *qdata); + void (*VQNormal)(byte *status, void *qdata); + void (*VQBuffer)(byte *status, void *qdata); + + long samplesPerPixel; // defaults to 2 + byte *gray; + unsigned int xsize, ysize, maxsize, minsize; + + qboolean half, smootheddouble, inMemory; + long normalBuffer0; + long roq_flags; + long roqF0; + long roqF1; + long t[2]; + long roqFPS; + int playonwalls; + byte *buf; + long drawX, drawY; + sfxHandle_t hSFX; // 0 = none + qhandle_t hCRAWLTEXT; // 0 = none } cin_cache; -static cinematics_t cin; -static cin_cache cinTable[MAX_VIDEO_HANDLES]; -static int currentHandle = -1; -static int CL_handle = -1; -static int CL_iPlaybackStartTime; // so I can stop users quitting playback <1 second after it starts - -extern int s_soundtime; // sample PAIRS -extern int s_paintedtime; // sample PAIRS +static cinematics_t cin; +static cin_cache cinTable[MAX_VIDEO_HANDLES]; +static int currentHandle = -1; +static int CL_handle = -1; +static int CL_iPlaybackStartTime; // so I can stop users quitting playback <1 second after it starts +extern int s_soundtime; // sample PAIRS +extern int s_paintedtime; // sample PAIRS void CIN_CloseAllVideos(void) { - int i; + int i; - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if (cinTable[i].fileName[0] != 0 ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (cinTable[i].fileName[0] != 0) { CIN_StopCinematic(i); } } } - static int CIN_HandleForVideo(void) { - int i; + int i; - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if ( cinTable[i].fileName[0] == 0 ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (cinTable[i].fileName[0] == 0) { return i; } } - Com_Error( ERR_DROP, "CIN_HandleForVideo: none free" ); + Com_Error(ERR_DROP, "CIN_HandleForVideo: none free"); return -1; } - - - //----------------------------------------------------------------------------- // RllSetupTable // @@ -183,18 +178,15 @@ static int CIN_HandleForVideo(void) { // // Returns: Nothing //----------------------------------------------------------------------------- -static void RllSetupTable( void ) -{ +static void RllSetupTable(void) { int z; - for (z=0;z<128;z++) { - cin.sqrTable[z] = (short)(z*z); - cin.sqrTable[z+128] = (short)(-cin.sqrTable[z]); + for (z = 0; z < 128; z++) { + cin.sqrTable[z] = (short)(z * z); + cin.sqrTable[z + 128] = (short)(-cin.sqrTable[z]); } } - - //----------------------------------------------------------------------------- // RllDecodeMonoToMono // @@ -240,25 +232,23 @@ static long RllDecodeMonoToMono(unsigned char *from,short *to,unsigned int size, // // Returns: Number of samples placed in output buffer //----------------------------------------------------------------------------- -static long RllDecodeMonoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput,unsigned short flag) -{ +static long RllDecodeMonoToStereo(unsigned char *from, short *to, unsigned int size, char signedOutput, unsigned short flag) { unsigned int z; int prev; if (signedOutput) - prev = flag - 0x8000; + prev = flag - 0x8000; else prev = flag; for (z = 0; z < size; z++) { prev = (short)(prev + cin.sqrTable[from[z]]); - to[z*2+0] = to[z*2+1] = (short)(prev); + to[z * 2 + 0] = to[z * 2 + 1] = (short)(prev); } - return size; // * 2 * sizeof(short)); + return size; // * 2 * sizeof(short)); } - //----------------------------------------------------------------------------- // RllDecodeStereoToStereo // @@ -272,11 +262,10 @@ static long RllDecodeMonoToStereo(unsigned char *from,short *to,unsigned int siz // // Returns: Number of samples placed in output buffer //----------------------------------------------------------------------------- -static long RllDecodeStereoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput, unsigned short flag) -{ +static long RllDecodeStereoToStereo(unsigned char *from, short *to, unsigned int size, char signedOutput, unsigned short flag) { unsigned int z; unsigned char *zz = from; - int prevL, prevR; + int prevL, prevR; if (signedOutput) { prevL = (flag & 0xff00) - 0x8000; @@ -286,17 +275,16 @@ static long RllDecodeStereoToStereo(unsigned char *from,short *to,unsigned int s prevR = (flag & 0x00ff) << 8; } - for (z=0;z>1); //*sizeof(short)); + return (size >> 1); //*sizeof(short)); } - //----------------------------------------------------------------------------- // RllDecodeStereoToMono // @@ -334,19 +322,17 @@ static long RllDecodeStereoToMono(unsigned char *from,short *to,unsigned int siz } */ /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void move8_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void move8_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 8; ++i) - { + for (i = 0; i < 8; ++i) { memcpy(dst, src, 32); src += spl; dst += spl; @@ -354,19 +340,17 @@ static void move8_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void move4_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void move4_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 4; ++i) - { + for (i = 0; i < 4; ++i) { memcpy(dst, src, 16); src += spl; dst += spl; @@ -374,19 +358,17 @@ static void move4_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blit8_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blit8_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 8; ++i) - { + for (i = 0; i < 8; ++i) { memcpy(dst, src, 32); src += 32; dst += spl; @@ -394,18 +376,16 @@ static void blit8_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ -static void blit4_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ +static void blit4_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 4; ++i) - { + for (i = 0; i < 4; ++i) { memmove(dst, src, 16); src += 16; dst += spl; @@ -413,190 +393,193 @@ static void blit4_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blit2_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blit2_32(byte *src, byte *dst, int spl) { memcpy(dst, src, 8); - memcpy(dst+spl, src+8, 8); + memcpy(dst + spl, src + 8, 8); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blitVQQuad32fs( byte **status, unsigned char *data ) -{ -unsigned short newd, celdata, code; -unsigned int index, i; -int spl; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blitVQQuad32fs(byte **status, unsigned char *data) { + unsigned short newd, celdata, code; + unsigned int index, i; + int spl; - newd = 0; + newd = 0; celdata = 0; - index = 0; + index = 0; - spl = cinTable[currentHandle].samplesPerLine; + spl = cinTable[currentHandle].samplesPerLine; do { if (!newd) { newd = 7; - celdata = data[0] + data[1]*256; + celdata = data[0] + data[1] * 256; data += 2; } else { newd--; } - code = (unsigned short)(celdata&0xc000); + code = (unsigned short)(celdata & 0xc000); celdata <<= 2; switch (code) { - case 0x8000: // vq code - blit8_32( (byte *)&vq8[(*data)*128], status[index], spl ); - data++; - index += 5; - break; - case 0xc000: // drop - index++; // skip 8x8 - for(i=0;i<4;i++) { - if (!newd) { - newd = 7; - celdata = data[0] + data[1]*256; - data += 2; - } else { - newd--; - } + case 0x8000: // vq code + blit8_32((byte *)&vq8[(*data) * 128], status[index], spl); + data++; + index += 5; + break; + case 0xc000: // drop + index++; // skip 8x8 + for (i = 0; i < 4; i++) { + if (!newd) { + newd = 7; + celdata = data[0] + data[1] * 256; + data += 2; + } else { + newd--; + } - code = (unsigned short)(celdata&0xc000); celdata <<= 2; - - switch (code) { // code in top two bits of code - case 0x8000: // 4x4 vq code - blit4_32( (byte *)&vq4[(*data)*32], status[index], spl ); - data++; - break; - case 0xc000: // 2x2 vq code - blit2_32( (byte *)&vq2[(*data)*8], status[index], spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+8, spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2, spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2+8, spl ); - data++; - break; - case 0x4000: // motion compensation - move4_32( status[index] + cin.mcomp[(*data)], status[index], spl ); - data++; - break; - } - index++; + code = (unsigned short)(celdata & 0xc000); + celdata <<= 2; + + switch (code) { // code in top two bits of code + case 0x8000: // 4x4 vq code + blit4_32((byte *)&vq4[(*data) * 32], status[index], spl); + data++; + break; + case 0xc000: // 2x2 vq code + blit2_32((byte *)&vq2[(*data) * 8], status[index], spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + 8, spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + spl * 2, spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + spl * 2 + 8, spl); + data++; + break; + case 0x4000: // motion compensation + move4_32(status[index] + cin.mcomp[(*data)], status[index], spl); + data++; + break; } - break; - case 0x4000: // motion compensation - move8_32( status[index] + cin.mcomp[(*data)], status[index], spl ); - data++; - index += 5; - break; - case 0x0000: - index += 5; - break; + index++; + } + break; + case 0x4000: // motion compensation + move8_32(status[index] + cin.mcomp[(*data)], status[index], spl); + data++; + index += 5; + break; + case 0x0000: + index += 5; + break; } - } while ( status[index] != NULL ); + } while (status[index] != NULL); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void ROQ_GenYUVTables( void ) -{ - float t_ub,t_vr,t_ug,t_vg; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void ROQ_GenYUVTables(void) { + float t_ub, t_vr, t_ug, t_vg; long i; - t_ub = (1.77200f/2.0f) * (float)(1<<6) + 0.5f; - t_vr = (1.40200f/2.0f) * (float)(1<<6) + 0.5f; - t_ug = (0.34414f/2.0f) * (float)(1<<6) + 0.5f; - t_vg = (0.71414f/2.0f) * (float)(1<<6) + 0.5f; - for(i=0;i<256;i++) { + t_ub = (1.77200f / 2.0f) * (float)(1 << 6) + 0.5f; + t_vr = (1.40200f / 2.0f) * (float)(1 << 6) + 0.5f; + t_ug = (0.34414f / 2.0f) * (float)(1 << 6) + 0.5f; + t_vg = (0.71414f / 2.0f) * (float)(1 << 6) + 0.5f; + for (i = 0; i < 256; i++) { float x = (float)(2 * i - 255); - ROQ_UB_tab[i] = (long)( ( t_ub * x) + (1<<5)); - ROQ_VR_tab[i] = (long)( ( t_vr * x) + (1<<5)); - ROQ_UG_tab[i] = (long)( (-t_ug * x) ); - ROQ_VG_tab[i] = (long)( (-t_vg * x) + (1<<5)); - ROQ_YY_tab[i] = (long)( (i << 6) | (i >> 2) ); + ROQ_UB_tab[i] = (long)((t_ub * x) + (1 << 5)); + ROQ_VR_tab[i] = (long)((t_vr * x) + (1 << 5)); + ROQ_UG_tab[i] = (long)((-t_ug * x)); + ROQ_VG_tab[i] = (long)((-t_vg * x) + (1 << 5)); + ROQ_YY_tab[i] = (long)((i << 6) | (i >> 2)); } } -#define VQ2TO4(a,b,c,d) { \ - *c++ = a[0]; \ - *d++ = a[0]; \ - *d++ = a[0]; \ - *c++ = a[1]; \ - *d++ = a[1]; \ - *d++ = a[1]; \ - *c++ = b[0]; \ - *d++ = b[0]; \ - *d++ = b[0]; \ - *c++ = b[1]; \ - *d++ = b[1]; \ - *d++ = b[1]; \ - *d++ = a[0]; \ - *d++ = a[0]; \ - *d++ = a[1]; \ - *d++ = a[1]; \ - *d++ = b[0]; \ - *d++ = b[0]; \ - *d++ = b[1]; \ - *d++ = b[1]; \ - a += 2; b += 2; } - -#define VQ2TO2(a,b,c,d) { \ - *c++ = *a; \ - *d++ = *a; \ - *d++ = *a; \ - *c++ = *b; \ - *d++ = *b; \ - *d++ = *b; \ - *d++ = *a; \ - *d++ = *a; \ - *d++ = *b; \ - *d++ = *b; \ - a++; b++; } +#define VQ2TO4(a, b, c, d) \ + { \ + *c++ = a[0]; \ + *d++ = a[0]; \ + *d++ = a[0]; \ + *c++ = a[1]; \ + *d++ = a[1]; \ + *d++ = a[1]; \ + *c++ = b[0]; \ + *d++ = b[0]; \ + *d++ = b[0]; \ + *c++ = b[1]; \ + *d++ = b[1]; \ + *d++ = b[1]; \ + *d++ = a[0]; \ + *d++ = a[0]; \ + *d++ = a[1]; \ + *d++ = a[1]; \ + *d++ = b[0]; \ + *d++ = b[0]; \ + *d++ = b[1]; \ + *d++ = b[1]; \ + a += 2; \ + b += 2; \ + } + +#define VQ2TO2(a, b, c, d) \ + { \ + *c++ = *a; \ + *d++ = *a; \ + *d++ = *a; \ + *c++ = *b; \ + *d++ = *b; \ + *d++ = *b; \ + *d++ = *a; \ + *d++ = *a; \ + *d++ = *b; \ + *d++ = *b; \ + a++; \ + b++; \ + } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static unsigned short yuv_to_rgb( long y, long u, long v ) -{ - long r,g,b,YY = (long)(ROQ_YY_tab[(y)]); + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static unsigned short yuv_to_rgb(long y, long u, long v) { + long r, g, b, YY = (long)(ROQ_YY_tab[(y)]); r = (YY + ROQ_VR_tab[v]) >> 9; g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 8; b = (YY + ROQ_UB_tab[u]) >> 9; - if (r<0) + if (r < 0) r = 0; - if (g<0) + if (g < 0) g = 0; - if (b<0) + if (b < 0) b = 0; if (r > 31) r = 31; @@ -605,30 +588,29 @@ static unsigned short yuv_to_rgb( long y, long u, long v ) if (b > 31) b = 31; - return (unsigned short)((r<<11)+(g<<5)+(b)); + return (unsigned short)((r << 11) + (g << 5) + (b)); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static unsigned int yuv_to_rgb24( long y, long u, long v ) -{ - long r,g,b,YY = (long)(ROQ_YY_tab[(y)]); + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static unsigned int yuv_to_rgb24(long y, long u, long v) { + long r, g, b, YY = (long)(ROQ_YY_tab[(y)]); r = (YY + ROQ_VR_tab[v]) >> 6; g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 6; b = (YY + ROQ_UB_tab[u]) >> 6; - if (r<0) + if (r < 0) r = 0; - if (g<0) + if (g < 0) g = 0; - if (b<0) + if (b < 0) b = 0; if (r > 255) r = 255; @@ -637,23 +619,22 @@ static unsigned int yuv_to_rgb24( long y, long u, long v ) if (b > 255) b = 255; - return LittleLong ((r)|(g<<8)|(b<<16)|(255<<24)); + return LittleLong((r) | (g << 8) | (b << 16) | (255 << 24)); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void decodeCodeBook( byte *input, unsigned short roq_flags ) -{ - long i, j, two, four; - unsigned short *aptr, *bptr, *cptr, *dptr; - long y0,y1,y2,y3,cr,cb; - byte *bbptr, *baptr, *bcptr, *bdptr; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void decodeCodeBook(byte *input, unsigned short roq_flags) { + long i, j, two, four; + unsigned short *aptr, *bptr, *cptr, *dptr; + long y0, y1, y2, y3, cr, cb; + byte *bbptr, *baptr, *bcptr, *bdptr; union { unsigned int *i; unsigned short *s; @@ -662,9 +643,10 @@ static void decodeCodeBook( byte *input, unsigned short roq_flags ) if (!roq_flags) { two = four = 256; } else { - two = roq_flags>>8; - if (!two) two = 256; - four = roq_flags&0xff; + two = roq_flags >> 8; + if (!two) + two = 256; + four = roq_flags & 0xff; } four *= 2; @@ -673,155 +655,157 @@ static void decodeCodeBook( byte *input, unsigned short roq_flags ) if (!cinTable[currentHandle].half) { if (!cinTable[currentHandle].smootheddouble) { -// -// normal height -// - if (cinTable[currentHandle].samplesPerPixel==2) { - for(i=0;i cinTable[currentHandle].CIN_WIDTH) bigx = cinTable[currentHandle].CIN_WIDTH; - if (bigy > cinTable[currentHandle].CIN_HEIGHT) bigy = cinTable[currentHandle].CIN_HEIGHT; + if (bigx > cinTable[currentHandle].CIN_WIDTH) + bigx = cinTable[currentHandle].CIN_WIDTH; + if (bigy > cinTable[currentHandle].CIN_HEIGHT) + bigy = cinTable[currentHandle].CIN_HEIGHT; - if ( (startX >= lowx) && (startX+quadSize) <= (bigx) && (startY+quadSize) <= (bigy) && (startY >= lowy) && quadSize <= MAXSIZE) { + if ((startX >= lowx) && (startX + quadSize) <= (bigx) && (startY + quadSize) <= (bigy) && (startY >= lowy) && quadSize <= MAXSIZE) { useY = startY; - scroff = cin.linbuf + (useY+((cinTable[currentHandle].CIN_HEIGHT-bigy)>>1)+yOff)*(cinTable[currentHandle].samplesPerLine) + (((startX+xOff))*cinTable[currentHandle].samplesPerPixel); + scroff = cin.linbuf + (useY + ((cinTable[currentHandle].CIN_HEIGHT - bigy) >> 1) + yOff) * (cinTable[currentHandle].samplesPerLine) + + (((startX + xOff)) * cinTable[currentHandle].samplesPerPixel); - cin.qStatus[0][cinTable[currentHandle].onQuad ] = scroff; - cin.qStatus[1][cinTable[currentHandle].onQuad++] = scroff+offset; + cin.qStatus[0][cinTable[currentHandle].onQuad] = scroff; + cin.qStatus[1][cinTable[currentHandle].onQuad++] = scroff + offset; } - if ( quadSize != MINSIZE ) { + if (quadSize != MINSIZE) { quadSize >>= 1; - recurseQuad( startX, startY , quadSize, xOff, yOff ); - recurseQuad( startX+quadSize, startY , quadSize, xOff, yOff ); - recurseQuad( startX, startY+quadSize , quadSize, xOff, yOff ); - recurseQuad( startX+quadSize, startY+quadSize , quadSize, xOff, yOff ); + recurseQuad(startX, startY, quadSize, xOff, yOff); + recurseQuad(startX + quadSize, startY, quadSize, xOff, yOff); + recurseQuad(startX, startY + quadSize, quadSize, xOff, yOff); + recurseQuad(startX + quadSize, startY + quadSize, quadSize, xOff, yOff); } } - /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void setupQuad( long xOff, long yOff ) -{ - long numQuadCels, i,x,y; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void setupQuad(long xOff, long yOff) { + long numQuadCels, i, x, y; byte *temp; - if (xOff == cin.oldXOff && yOff == cin.oldYOff && cinTable[currentHandle].ysize == (unsigned)cin.oldysize && cinTable[currentHandle].xsize == (unsigned)cin.oldxsize) { + if (xOff == cin.oldXOff && yOff == cin.oldYOff && cinTable[currentHandle].ysize == (unsigned)cin.oldysize && + cinTable[currentHandle].xsize == (unsigned)cin.oldxsize) { return; } @@ -970,53 +961,52 @@ static void setupQuad( long xOff, long yOff ) cin.oldYOff = yOff; cin.oldysize = cinTable[currentHandle].ysize; cin.oldxsize = cinTable[currentHandle].xsize; -/* Enisform: Not in q3 source - numQuadCels = (cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].CIN_HEIGHT) / (16); - numQuadCels += numQuadCels/4 + numQuadCels/16; - numQuadCels += 64; // for overflow -*/ + /* Enisform: Not in q3 source + numQuadCels = (cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].CIN_HEIGHT) / (16); + numQuadCels += numQuadCels/4 + numQuadCels/16; + numQuadCels += 64; // for overflow + */ - numQuadCels = (cinTable[currentHandle].xsize*cinTable[currentHandle].ysize) / (16); - numQuadCels += numQuadCels/4; - numQuadCels += 64; // for overflow + numQuadCels = (cinTable[currentHandle].xsize * cinTable[currentHandle].ysize) / (16); + numQuadCels += numQuadCels / 4; + numQuadCels += 64; // for overflow cinTable[currentHandle].onQuad = 0; - for(y=0;y<(long)cinTable[currentHandle].ysize;y+=16) - for(x=0;x<(long)cinTable[currentHandle].xsize;x+=16) - recurseQuad( x, y, 16, xOff, yOff ); + for (y = 0; y < (long)cinTable[currentHandle].ysize; y += 16) + for (x = 0; x < (long)cinTable[currentHandle].xsize; x += 16) + recurseQuad(x, y, 16, xOff, yOff); temp = NULL; - for(i=(numQuadCels-64);i256) { - cinTable[currentHandle].drawX = 256; - } - if (cinTable[currentHandle].drawY>256) { - cinTable[currentHandle].drawY = 256; - } + if (cls.glconfig.maxTextureSize <= 256) { + if (cinTable[currentHandle].drawX > 256) { + cinTable[currentHandle].drawX = 256; + } + if (cinTable[currentHandle].drawY > 256) { + cinTable[currentHandle].drawY = 256; + } if (cinTable[currentHandle].CIN_WIDTH != 256 || cinTable[currentHandle].CIN_HEIGHT != 256) { Com_Printf("HACK: approxmimating cinematic for Rage Pro or Voodoo\n"); } @@ -1044,40 +1034,43 @@ static void readQuadInfo( byte *qData ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQPrepMcomp( long xoff, long yoff ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQPrepMcomp(long xoff, long yoff) { long i, j, x, y, temp, temp2; - i=cinTable[currentHandle].samplesPerLine; j=cinTable[currentHandle].samplesPerPixel; - if ( cinTable[currentHandle].xsize == (cinTable[currentHandle].ysize*4) && !cinTable[currentHandle].half ) { j = j+j; i = i+i; } + i = cinTable[currentHandle].samplesPerLine; + j = cinTable[currentHandle].samplesPerPixel; + if (cinTable[currentHandle].xsize == (cinTable[currentHandle].ysize * 4) && !cinTable[currentHandle].half) { + j = j + j; + i = i + i; + } - for(y=0;y<16;y++) { - temp2 = (y+yoff-8)*i; - for(x=0;x<16;x++) { - temp = (x+xoff-8)*j; - cin.mcomp[(x*16)+y] = cinTable[currentHandle].normalBuffer0-(temp2+temp); + for (y = 0; y < 16; y++) { + temp2 = (y + yoff - 8) * i; + for (x = 0; x < 16; x++) { + temp = (x + xoff - 8) * j; + cin.mcomp[(x * 16) + y] = cinTable[currentHandle].normalBuffer0 - (temp2 + temp); } } } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void initRoQ( void ) -{ - if (currentHandle < 0) return; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void initRoQ(void) { + if (currentHandle < 0) + return; cinTable[currentHandle].VQNormal = (void (*)(byte *, void *))blitVQQuad32fs; cinTable[currentHandle].VQBuffer = (void (*)(byte *, void *))blitVQQuad32fs; @@ -1087,12 +1080,12 @@ static void initRoQ( void ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ + * + * Function: + * + * Description: + * + ******************************************************************************/ /* static byte* RoQFetchInterlaced( byte *source ) { int x, *src, *dst; @@ -1109,37 +1102,38 @@ static byte* RoQFetchInterlaced( byte *source ) { return cinTable[currentHandle].buf2; } */ -static void RoQReset( void ) { +static void RoQReset(void) { - if (currentHandle < 0) return; + if (currentHandle < 0) + return; - FS_FCloseFile( cinTable[currentHandle].iFile ); - FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); + FS_FCloseFile(cinTable[currentHandle].iFile); + FS_FOpenFileRead(cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); // let the background thread start reading ahead - FS_Read (cin.file, 16, cinTable[currentHandle].iFile); + FS_Read(cin.file, 16, cinTable[currentHandle].iFile); RoQ_init(); cinTable[currentHandle].status = FMV_LOOPED; } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQInterrupt(void) -{ - byte *framedata; - short sbuf[32768]; - int ssize; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQInterrupt(void) { + byte *framedata; + short sbuf[32768]; + int ssize; - if (currentHandle < 0) return; + if (currentHandle < 0) + return; - FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); - if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) { - if (cinTable[currentHandle].holdAtEnd==qfalse) { + FS_Read(cin.file, cinTable[currentHandle].RoQFrameSize + 8, cinTable[currentHandle].iFile); + if (cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize) { + if (cinTable[currentHandle].holdAtEnd == qfalse) { if (cinTable[currentHandle].looping) { RoQReset(); } else { @@ -1156,71 +1150,71 @@ static void RoQInterrupt(void) // new frame is ready // redump: - switch(cinTable[currentHandle].roq_id) - { - case ROQ_QUAD_VQ: - if ((cinTable[currentHandle].numQuads&1)) { - cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[1]; - RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 ); - cinTable[currentHandle].VQ1( (byte *)cin.qStatus[1], framedata); - cinTable[currentHandle].buf = cin.linbuf + cinTable[currentHandle].screenDelta; - } else { - cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[0]; - RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 ); - cinTable[currentHandle].VQ0( (byte *)cin.qStatus[0], framedata ); - cinTable[currentHandle].buf = cin.linbuf; - } - if (cinTable[currentHandle].numQuads == 0) { // first frame - Com_Memcpy(cin.linbuf+cinTable[currentHandle].screenDelta, cin.linbuf, cinTable[currentHandle].samplesPerLine*cinTable[currentHandle].ysize); - } - cinTable[currentHandle].numQuads++; - cinTable[currentHandle].dirty = qtrue; - break; - case ROQ_CODEBOOK: - decodeCodeBook( framedata, (unsigned short)cinTable[currentHandle].roq_flags ); - break; - case ZA_SOUND_MONO: - if (!cinTable[currentHandle].silent) { - ssize = RllDecodeMonoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); - S_RawSamples( ssize, 22050, 2, 1, (byte *)sbuf, s_volume->value, qtrue ); - } - break; - case ZA_SOUND_STEREO: - if (!cinTable[currentHandle].silent) { - if (cinTable[currentHandle].numQuads == -1) { - S_Update(); - s_rawend = s_soundtime; - } - ssize = RllDecodeStereoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); - S_RawSamples( ssize, 22050, 2, 2, (byte *)sbuf, s_volume->value, qtrue ); - } - break; - case ROQ_QUAD_INFO: + switch (cinTable[currentHandle].roq_id) { + case ROQ_QUAD_VQ: + if ((cinTable[currentHandle].numQuads & 1)) { + cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[1]; + RoQPrepMcomp(cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1); + cinTable[currentHandle].VQ1((byte *)cin.qStatus[1], framedata); + cinTable[currentHandle].buf = cin.linbuf + cinTable[currentHandle].screenDelta; + } else { + cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[0]; + RoQPrepMcomp(cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1); + cinTable[currentHandle].VQ0((byte *)cin.qStatus[0], framedata); + cinTable[currentHandle].buf = cin.linbuf; + } + if (cinTable[currentHandle].numQuads == 0) { // first frame + Com_Memcpy(cin.linbuf + cinTable[currentHandle].screenDelta, cin.linbuf, cinTable[currentHandle].samplesPerLine * cinTable[currentHandle].ysize); + } + cinTable[currentHandle].numQuads++; + cinTable[currentHandle].dirty = qtrue; + break; + case ROQ_CODEBOOK: + decodeCodeBook(framedata, (unsigned short)cinTable[currentHandle].roq_flags); + break; + case ZA_SOUND_MONO: + if (!cinTable[currentHandle].silent) { + ssize = RllDecodeMonoToStereo(framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); + S_RawSamples(ssize, 22050, 2, 1, (byte *)sbuf, s_volume->value, qtrue); + } + break; + case ZA_SOUND_STEREO: + if (!cinTable[currentHandle].silent) { if (cinTable[currentHandle].numQuads == -1) { - readQuadInfo( framedata ); - setupQuad( 0, 0 ); - cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds()*com_timescale->value; + S_Update(); + s_rawend = s_soundtime; } - if (cinTable[currentHandle].numQuads != 1) cinTable[currentHandle].numQuads = 0; - break; - case ROQ_PACKET: - cinTable[currentHandle].inMemory = (qboolean)cinTable[currentHandle].roq_flags; - cinTable[currentHandle].RoQFrameSize = 0; // for header - break; - case ROQ_QUAD_HANG: - cinTable[currentHandle].RoQFrameSize = 0; - break; - case ROQ_QUAD_JPEG: - break; - default: - cinTable[currentHandle].status = FMV_EOF; - break; + ssize = RllDecodeStereoToStereo(framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); + S_RawSamples(ssize, 22050, 2, 2, (byte *)sbuf, s_volume->value, qtrue); + } + break; + case ROQ_QUAD_INFO: + if (cinTable[currentHandle].numQuads == -1) { + readQuadInfo(framedata); + setupQuad(0, 0); + cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds() * com_timescale->value; + } + if (cinTable[currentHandle].numQuads != 1) + cinTable[currentHandle].numQuads = 0; + break; + case ROQ_PACKET: + cinTable[currentHandle].inMemory = (qboolean)cinTable[currentHandle].roq_flags; + cinTable[currentHandle].RoQFrameSize = 0; // for header + break; + case ROQ_QUAD_HANG: + cinTable[currentHandle].RoQFrameSize = 0; + break; + case ROQ_QUAD_JPEG: + break; + default: + cinTable[currentHandle].status = FMV_EOF; + break; } -// -// read in next frame data -// - if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) { - if (cinTable[currentHandle].holdAtEnd==qfalse) { + // + // read in next frame data + // + if (cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize) { + if (cinTable[currentHandle].holdAtEnd == qfalse) { if (cinTable[currentHandle].looping) { RoQReset(); } else { @@ -1232,14 +1226,14 @@ static void RoQInterrupt(void) return; } - framedata += cinTable[currentHandle].RoQFrameSize; - cinTable[currentHandle].roq_id = framedata[0] + framedata[1]*256; - cinTable[currentHandle].RoQFrameSize = framedata[2] + framedata[3]*256 + framedata[4]*65536; - cinTable[currentHandle].roq_flags = framedata[6] + framedata[7]*256; - cinTable[currentHandle].roqF0 = (signed char)framedata[7]; - cinTable[currentHandle].roqF1 = (signed char)framedata[6]; + framedata += cinTable[currentHandle].RoQFrameSize; + cinTable[currentHandle].roq_id = framedata[0] + framedata[1] * 256; + cinTable[currentHandle].RoQFrameSize = framedata[2] + framedata[3] * 256 + framedata[4] * 65536; + cinTable[currentHandle].roq_flags = framedata[6] + framedata[7] * 256; + cinTable[currentHandle].roqF0 = (signed char)framedata[7]; + cinTable[currentHandle].roqF1 = (signed char)framedata[6]; - if (cinTable[currentHandle].RoQFrameSize>65536||cinTable[currentHandle].roq_id==0x1084) { + if (cinTable[currentHandle].RoQFrameSize > 65536 || cinTable[currentHandle].roq_id == 0x1084) { Com_DPrintf("roq_size>65536||roq_id==0x1084\n"); cinTable[currentHandle].status = FMV_EOF; if (cinTable[currentHandle].looping) { @@ -1247,75 +1241,72 @@ static void RoQInterrupt(void) } return; } - if (cinTable[currentHandle].inMemory && (cinTable[currentHandle].status != FMV_EOF)) - { - cinTable[currentHandle].inMemory = (qboolean)(((int)cinTable[currentHandle].inMemory)-1); + if (cinTable[currentHandle].inMemory && (cinTable[currentHandle].status != FMV_EOF)) { + cinTable[currentHandle].inMemory = (qboolean)(((int)cinTable[currentHandle].inMemory) - 1); framedata += 8; goto redump; } -// -// one more frame hits the dust -// -// assert(cinTable[currentHandle].RoQFrameSize <= 65536); -// r = FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); - cinTable[currentHandle].RoQPlayed += cinTable[currentHandle].RoQFrameSize+8; + // + // one more frame hits the dust + // + // assert(cinTable[currentHandle].RoQFrameSize <= 65536); + // r = FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); + cinTable[currentHandle].RoQPlayed += cinTable[currentHandle].RoQFrameSize + 8; } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQ_init( void ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ - cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds()*com_timescale->value; +static void RoQ_init(void) { - cinTable[currentHandle].RoQPlayed = 24; + cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds() * com_timescale->value; -/* get frame rate */ - cinTable[currentHandle].roqFPS = cin.file[ 6] + cin.file[ 7]*256; + cinTable[currentHandle].RoQPlayed = 24; - if (!cinTable[currentHandle].roqFPS) cinTable[currentHandle].roqFPS = 30; + /* get frame rate */ + cinTable[currentHandle].roqFPS = cin.file[6] + cin.file[7] * 256; + if (!cinTable[currentHandle].roqFPS) + cinTable[currentHandle].roqFPS = 30; cinTable[currentHandle].numQuads = -1; - cinTable[currentHandle].roq_id = cin.file[ 8] + cin.file[ 9]*256; - cinTable[currentHandle].RoQFrameSize = cin.file[10] + cin.file[11]*256 + cin.file[12]*65536; - cinTable[currentHandle].roq_flags = cin.file[14] + cin.file[15]*256; + cinTable[currentHandle].roq_id = cin.file[8] + cin.file[9] * 256; + cinTable[currentHandle].RoQFrameSize = cin.file[10] + cin.file[11] * 256 + cin.file[12] * 65536; + cinTable[currentHandle].roq_flags = cin.file[14] + cin.file[15] * 256; if (cinTable[currentHandle].RoQFrameSize > 65536 || !cinTable[currentHandle].RoQFrameSize) { return; } - if (cinTable[currentHandle].hSFX) - { + if (cinTable[currentHandle].hSFX) { S_StartLocalSound(cinTable[currentHandle].hSFX, CHAN_AUTO); } } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQShutdown( void ) { + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQShutdown(void) { const char *s; if (!cinTable[currentHandle].buf) { if (cinTable[currentHandle].iFile) { -// assert( 0 && "ROQ handle leak-prevention WAS needed!"); - FS_FCloseFile( cinTable[currentHandle].iFile ); + // assert( 0 && "ROQ handle leak-prevention WAS needed!"); + FS_FCloseFile(cinTable[currentHandle].iFile); cinTable[currentHandle].iFile = 0; if (cinTable[currentHandle].hSFX) { - S_CIN_StopSound( cinTable[currentHandle].hSFX ); + S_CIN_StopSound(cinTable[currentHandle].hSFX); } } return; @@ -1329,10 +1320,10 @@ static void RoQShutdown( void ) { cinTable[currentHandle].status = FMV_IDLE; if (cinTable[currentHandle].iFile) { - FS_FCloseFile( cinTable[currentHandle].iFile ); + FS_FCloseFile(cinTable[currentHandle].iFile); cinTable[currentHandle].iFile = 0; if (cinTable[currentHandle].hSFX) { - S_CIN_StopSound( cinTable[currentHandle].hSFX ); + S_CIN_StopSound(cinTable[currentHandle].hSFX); } } @@ -1342,10 +1333,10 @@ static void RoQShutdown( void ) { // if we are aborting the intro cinematic with // a devmap command, nextmap would be valid by // the time it was referenced - s = Cvar_VariableString( "nextmap" ); - if ( s[0] ) { - Cbuf_ExecuteText( EXEC_APPEND, va("%s\n", s) ); - Cvar_Set( "nextmap", "" ); + s = Cvar_VariableString("nextmap"); + if (s[0]) { + Cbuf_ExecuteText(EXEC_APPEND, va("%s\n", s)); + Cvar_Set("nextmap", ""); } CL_handle = -1; } @@ -1361,26 +1352,27 @@ CIN_StopCinematic e_status CIN_StopCinematic(int handle) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return FMV_EOF; currentHandle = handle; Com_DPrintf("trFMV::stop(), closing %s\n", cinTable[currentHandle].fileName); if (!cinTable[currentHandle].buf) { if (cinTable[currentHandle].iFile) { -// assert( 0 && "ROQ handle leak-prevention WAS needed!"); - FS_FCloseFile( cinTable[currentHandle].iFile ); + // assert( 0 && "ROQ handle leak-prevention WAS needed!"); + FS_FCloseFile(cinTable[currentHandle].iFile); cinTable[currentHandle].iFile = 0; cinTable[currentHandle].fileName[0] = 0; if (cinTable[currentHandle].hSFX) { - S_CIN_StopSound( cinTable[currentHandle].hSFX ); + S_CIN_StopSound(cinTable[currentHandle].hSFX); } } return FMV_EOF; } if (cinTable[currentHandle].alterGameState) { - if ( cls.state != CA_CINEMATIC ) { + if (cls.state != CA_CINEMATIC) { return cinTable[currentHandle].status; } } @@ -1398,13 +1390,12 @@ Fetch and decompress the pending frame ================== */ +e_status CIN_RunCinematic(int handle) { + int start = 0; + int thisTime = 0; -e_status CIN_RunCinematic (int handle) -{ - int start = 0; - int thisTime = 0; - - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return FMV_EOF; if (cin.currentHandle != handle) { currentHandle = handle; @@ -1413,15 +1404,14 @@ e_status CIN_RunCinematic (int handle) RoQReset(); } - if (cinTable[handle].playonwalls < -1) - { + if (cinTable[handle].playonwalls < -1) { return cinTable[handle].status; } currentHandle = handle; if (cinTable[currentHandle].alterGameState) { - if ( cls.state != CA_CINEMATIC ) { + if (cls.state != CA_CINEMATIC) { return cinTable[currentHandle].status; } } @@ -1430,20 +1420,19 @@ e_status CIN_RunCinematic (int handle) return cinTable[currentHandle].status; } - thisTime = Sys_Milliseconds()*com_timescale->value; - if (cinTable[currentHandle].shader && (abs(thisTime - (double)cinTable[currentHandle].lastTime))>100) { + thisTime = Sys_Milliseconds() * com_timescale->value; + if (cinTable[currentHandle].shader && (abs(thisTime - (double)cinTable[currentHandle].lastTime)) > 100) { cinTable[currentHandle].startTime += thisTime - cinTable[currentHandle].lastTime; } - cinTable[currentHandle].tfps = ((((Sys_Milliseconds()*com_timescale->value) - cinTable[currentHandle].startTime)*cinTable[currentHandle].roqFPS)/1000); + cinTable[currentHandle].tfps = + ((((Sys_Milliseconds() * com_timescale->value) - cinTable[currentHandle].startTime) * cinTable[currentHandle].roqFPS) / 1000); start = cinTable[currentHandle].startTime; - while( (cinTable[currentHandle].tfps != cinTable[currentHandle].numQuads) - && (cinTable[currentHandle].status == FMV_PLAY) ) - { + while ((cinTable[currentHandle].tfps != cinTable[currentHandle].numQuads) && (cinTable[currentHandle].status == FMV_PLAY)) { RoQInterrupt(); if ((unsigned)start != cinTable[currentHandle].startTime) { - cinTable[currentHandle].tfps = ((((Sys_Milliseconds()*com_timescale->value) - - cinTable[currentHandle].startTime)*cinTable[currentHandle].roqFPS)/1000); + cinTable[currentHandle].tfps = + ((((Sys_Milliseconds() * com_timescale->value) - cinTable[currentHandle].startTime) * cinTable[currentHandle].roqFPS) / 1000); start = cinTable[currentHandle].startTime; } } @@ -1455,18 +1444,18 @@ e_status CIN_RunCinematic (int handle) } if (cinTable[currentHandle].status == FMV_EOF) { - if (cinTable[currentHandle].looping) { - RoQReset(); - } else { - RoQShutdown(); - } + if (cinTable[currentHandle].looping) { + RoQReset(); + } else { + RoQShutdown(); + } } return cinTable[currentHandle].status; } -void Menus_CloseAll(void); -void UI_Cursor_Show(qboolean flag); +void Menus_CloseAll(void); +void UI_Cursor_Show(qboolean flag); /* ================== @@ -1474,22 +1463,21 @@ CL_PlayCinematic ================== */ -int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBits, const char *psAudioFile /* = NULL */ ) -{ +int CIN_PlayCinematic(const char *arg, int x, int y, int w, int h, int systemBits, const char *psAudioFile /* = NULL */) { unsigned short RoQID; - char name[MAX_OSPATH]; - int i; + char name[MAX_OSPATH]; + int i; if (strstr(arg, "/") == NULL && strstr(arg, "\\") == NULL) { - Com_sprintf (name, sizeof(name), "video/%s", arg); + Com_sprintf(name, sizeof(name), "video/%s", arg); } else { - Com_sprintf (name, sizeof(name), "%s", arg); + Com_sprintf(name, sizeof(name), "%s", arg); } - COM_DefaultExtension(name,sizeof(name),".roq"); + COM_DefaultExtension(name, sizeof(name), ".roq"); if (!(systemBits & CIN_system)) { - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if (!strcmp(cinTable[i].fileName, name) ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (!strcmp(cinTable[i].fileName, name)) { return i; } } @@ -1497,7 +1485,7 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi Com_DPrintf("CIN_PlayCinematic( %s )\n", arg); - memset(&cin, 0, sizeof(cinematics_t) ); + memset(&cin, 0, sizeof(cinematics_t)); currentHandle = CIN_HandleForVideo(); cin.currentHandle = currentHandle; @@ -1505,10 +1493,10 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi Q_strncpyz(cinTable[currentHandle].fileName, name, MAX_OSPATH); cinTable[currentHandle].ROQSize = 0; - cinTable[currentHandle].ROQSize = FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); + cinTable[currentHandle].ROQSize = FS_FOpenFileRead(cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); - if (cinTable[currentHandle].ROQSize<=0) { - Com_Printf(S_COLOR_RED"ERROR: playCinematic: %s not found!\n", arg); + if (cinTable[currentHandle].ROQSize <= 0) { + Com_Printf(S_COLOR_RED "ERROR: playCinematic: %s not found!\n", arg); cinTable[currentHandle].fileName[0] = 0; return -1; } @@ -1517,46 +1505,38 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi CIN_SetLooping(currentHandle, (qboolean)((systemBits & CIN_loop) != 0)); cinTable[currentHandle].CIN_HEIGHT = DEFAULT_CIN_HEIGHT; - cinTable[currentHandle].CIN_WIDTH = DEFAULT_CIN_WIDTH; + cinTable[currentHandle].CIN_WIDTH = DEFAULT_CIN_WIDTH; cinTable[currentHandle].holdAtEnd = (qboolean)((systemBits & CIN_hold) != 0); cinTable[currentHandle].alterGameState = (qboolean)((systemBits & CIN_system) != 0); cinTable[currentHandle].playonwalls = 1; cinTable[currentHandle].silent = (qboolean)((systemBits & CIN_silent) != 0); cinTable[currentHandle].shader = (qboolean)((systemBits & CIN_shader) != 0); - if (psAudioFile) - { + if (psAudioFile) { cinTable[currentHandle].hSFX = S_RegisterSound(psAudioFile); - } - else - { + } else { cinTable[currentHandle].hSFX = 0; } cinTable[currentHandle].hCRAWLTEXT = 0; - if (cinTable[currentHandle].alterGameState) - { + if (cinTable[currentHandle].alterGameState) { // close the menu Con_Close(); - if (cls.uiStarted) - { + if (cls.uiStarted) { UI_Cursor_Show(qfalse); Menus_CloseAll(); } - } - else - { + } else { cinTable[currentHandle].playonwalls = cl_inGameVideo->integer; } initRoQ(); - FS_Read (cin.file, 16, cinTable[currentHandle].iFile); + FS_Read(cin.file, 16, cinTable[currentHandle].iFile); - RoQID = (unsigned short)(cin.file[0]) + (unsigned short)(cin.file[1])*256; - if (RoQID == 0x1084) - { + RoQID = (unsigned short)(cin.file[0]) + (unsigned short)(cin.file[1]) * 256; + if (RoQID == 0x1084) { RoQ_init(); -// FS_Read (cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile); + // FS_Read (cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile); cinTable[currentHandle].status = FMV_PLAY; Com_DPrintf("trFMV::play(), playing %s\n", arg); @@ -1567,7 +1547,7 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi Con_Close(); - if ( !cinTable[currentHandle].silent ) + if (!cinTable[currentHandle].silent) s_rawend = s_soundtime; return currentHandle; @@ -1578,8 +1558,9 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi return -1; } -void CIN_SetExtents (int handle, int x, int y, int w, int h) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; +void CIN_SetExtents(int handle, int x, int y, int w, int h) { + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; cinTable[handle].xpos = x; cinTable[handle].ypos = y; cinTable[handle].width = w; @@ -1588,29 +1569,29 @@ void CIN_SetExtents (int handle, int x, int y, int w, int h) { } void CIN_SetLooping(int handle, qboolean loop) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; cinTable[handle].looping = loop; } // Text crawl defines -#define TC_PLANE_WIDTH 250 -#define TC_PLANE_NEAR 90 -#define TC_PLANE_FAR 715 -#define TC_PLANE_TOP 0 -#define TC_PLANE_BOTTOM 1100 +#define TC_PLANE_WIDTH 250 +#define TC_PLANE_NEAR 90 +#define TC_PLANE_FAR 715 +#define TC_PLANE_TOP 0 +#define TC_PLANE_BOTTOM 1100 #define TC_DELAY 9000 #define TC_STOPTIME 81000 -static void CIN_AddTextCrawl() -{ - refdef_t refdef; - polyVert_t verts[4]; +static void CIN_AddTextCrawl() { + refdef_t refdef; + polyVert_t verts[4]; // Set up refdef - memset( &refdef, 0, sizeof( refdef )); + memset(&refdef, 0, sizeof(refdef)); refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); + AxisClear(refdef.viewaxis); refdef.fov_x = 130; refdef.fov_y = 130; @@ -1625,58 +1606,53 @@ static void CIN_AddTextCrawl() // Set up the poly verts float fadeDown = 1.0; - if (cls.realtime-CL_iPlaybackStartTime >= (TC_STOPTIME-2500)) - { - fadeDown = (TC_STOPTIME - (cls.realtime-CL_iPlaybackStartTime))/ 2480.0f; - if (fadeDown < 0) - { + if (cls.realtime - CL_iPlaybackStartTime >= (TC_STOPTIME - 2500)) { + fadeDown = (TC_STOPTIME - (cls.realtime - CL_iPlaybackStartTime)) / 2480.0f; + if (fadeDown < 0) { fadeDown = 0; } - if (fadeDown > 1) - { + if (fadeDown > 1) { fadeDown = 1; } } - for ( int i = 0; i < 4; i++ ) - { - verts[i].modulate[0] = 255*fadeDown; // gold color? - verts[i].modulate[1] = 235*fadeDown; - verts[i].modulate[2] = 127*fadeDown; - verts[i].modulate[3] = 255*fadeDown; + for (int i = 0; i < 4; i++) { + verts[i].modulate[0] = 255 * fadeDown; // gold color? + verts[i].modulate[1] = 235 * fadeDown; + verts[i].modulate[2] = 127 * fadeDown; + verts[i].modulate[3] = 255 * fadeDown; } - VectorScaleM( verts[2].modulate, 0.1f, verts[2].modulate ); // darken at the top?? - VectorScaleM( verts[3].modulate, 0.1f, verts[3].modulate ); + VectorScaleM(verts[2].modulate, 0.1f, verts[2].modulate); // darken at the top?? + VectorScaleM(verts[3].modulate, 0.1f, verts[3].modulate); -#define TIMEOFFSET +(cls.realtime-CL_iPlaybackStartTime-TC_DELAY)*0.000015f -1 - VectorSet( verts[0].xyz, TC_PLANE_NEAR, -TC_PLANE_WIDTH, TC_PLANE_TOP ); +#define TIMEOFFSET +(cls.realtime - CL_iPlaybackStartTime - TC_DELAY) * 0.000015f - 1 + VectorSet(verts[0].xyz, TC_PLANE_NEAR, -TC_PLANE_WIDTH, TC_PLANE_TOP); verts[0].st[0] = 1; verts[0].st[1] = 1 TIMEOFFSET; - VectorSet( verts[1].xyz, TC_PLANE_NEAR, TC_PLANE_WIDTH, TC_PLANE_TOP ); + VectorSet(verts[1].xyz, TC_PLANE_NEAR, TC_PLANE_WIDTH, TC_PLANE_TOP); verts[1].st[0] = 0; verts[1].st[1] = 1 TIMEOFFSET; - VectorSet( verts[2].xyz, TC_PLANE_FAR, TC_PLANE_WIDTH, TC_PLANE_BOTTOM ); + VectorSet(verts[2].xyz, TC_PLANE_FAR, TC_PLANE_WIDTH, TC_PLANE_BOTTOM); verts[2].st[0] = 0; verts[2].st[1] = 0 TIMEOFFSET; - VectorSet( verts[3].xyz, TC_PLANE_FAR, -TC_PLANE_WIDTH, TC_PLANE_BOTTOM ); + VectorSet(verts[3].xyz, TC_PLANE_FAR, -TC_PLANE_WIDTH, TC_PLANE_BOTTOM); verts[3].st[0] = 1; verts[3].st[1] = 0 TIMEOFFSET; // render it out re.ClearScene(); - re.AddPolyToScene( cinTable[CL_handle].hCRAWLTEXT, 4, verts ); - re.RenderScene( &refdef ); + re.AddPolyToScene(cinTable[CL_handle].hCRAWLTEXT, 4, verts); + re.RenderScene(&refdef); - //time's up - if (cls.realtime-CL_iPlaybackStartTime >= TC_STOPTIME) - { -// cinTable[currentHandle].holdAtEnd = qfalse; + // time's up + if (cls.realtime - CL_iPlaybackStartTime >= TC_STOPTIME) { + // cinTable[currentHandle].holdAtEnd = qfalse; cinTable[CL_handle].status = FMV_EOF; RoQShutdown(); - SCR_StopCinematic(); // change ROQ from FMV_IDLE to FMV_EOF, and clear some other vars + SCR_StopCinematic(); // change ROQ from FMV_IDLE to FMV_EOF, and clear some other vars } } @@ -1689,52 +1665,52 @@ Resample cinematic to 256x256 and store in buf2 */ void CIN_ResampleCinematic(int handle, int *buf2) { int ix, iy, *buf3, xm, ym, ll; - byte *buf; + byte *buf; buf = cinTable[handle].buf; - xm = cinTable[handle].CIN_WIDTH/256; - ym = cinTable[handle].CIN_HEIGHT/256; + xm = cinTable[handle].CIN_WIDTH / 256; + ym = cinTable[handle].CIN_HEIGHT / 256; ll = 8; - if (cinTable[handle].CIN_WIDTH==512) { + if (cinTable[handle].CIN_WIDTH == 512) { ll = 9; } - buf3 = (int*)buf; - if (xm==2 && ym==2) { + buf3 = (int *)buf; + if (xm == 2 && ym == 2) { byte *bc2, *bc3; - int ic, iiy; + int ic, iiy; bc2 = (byte *)buf2; bc3 = (byte *)buf3; - for (iy = 0; iy<256; iy++) { - iiy = iy<<12; - for (ix = 0; ix<2048; ix+=8) { - for(ic = ix;ic<(ix+4);ic++) { - *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic]+bc3[iiy+2048+ic]+bc3[iiy+2048+4+ic])>>2; + for (iy = 0; iy < 256; iy++) { + iiy = iy << 12; + for (ix = 0; ix < 2048; ix += 8) { + for (ic = ix; ic < (ix + 4); ic++) { + *bc2 = (bc3[iiy + ic] + bc3[iiy + 4 + ic] + bc3[iiy + 2048 + ic] + bc3[iiy + 2048 + 4 + ic]) >> 2; bc2++; } } } - } else if (xm==2 && ym==1) { + } else if (xm == 2 && ym == 1) { byte *bc2, *bc3; - int ic, iiy; + int ic, iiy; bc2 = (byte *)buf2; bc3 = (byte *)buf3; - for (iy = 0; iy<256; iy++) { - iiy = iy<<11; - for (ix = 0; ix<2048; ix+=8) { - for(ic = ix;ic<(ix+4);ic++) { - *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic])>>1; + for (iy = 0; iy < 256; iy++) { + iiy = iy << 11; + for (ix = 0; ix < 2048; ix += 8) { + for (ic = ix; ic < (ix + 4); ic++) { + *bc2 = (bc3[iiy + ic] + bc3[iiy + 4 + ic]) >> 1; bc2++; } } } } else { - for (iy = 0; iy<256; iy++) { - for (ix = 0; ix<256; ix++) { - buf2[(iy<<8)+ix] = buf3[((iy*ym)<= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; if (!cinTable[handle].buf) { return; @@ -1765,211 +1742,172 @@ void CIN_DrawCinematic (int handle) { if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { int *buf2; - //buf2 = (int *)Hunk_AllocateTempMemory( 256*256*4 ); - buf2 = (int*)Z_Malloc( 256*256*4, TAG_TEMP_WORKSPACE, qfalse ); + // buf2 = (int *)Hunk_AllocateTempMemory( 256*256*4 ); + buf2 = (int *)Z_Malloc(256 * 256 * 4, TAG_TEMP_WORKSPACE, qfalse); CIN_ResampleCinematic(handle, buf2); - re.DrawStretchRaw( x, y, w, h, 256, 256, (byte *)buf2, handle, qtrue); + re.DrawStretchRaw(x, y, w, h, 256, 256, (byte *)buf2, handle, qtrue); cinTable[handle].dirty = qfalse; - Z_Free(buf2); //Hunk_FreeTempMemory(buf2); + Z_Free(buf2); // Hunk_FreeTempMemory(buf2); return; } - re.DrawStretchRaw( x, y, w, h, cinTable[handle].drawX, cinTable[handle].drawY, buf, handle, cinTable[handle].dirty); + re.DrawStretchRaw(x, y, w, h, cinTable[handle].drawX, cinTable[handle].drawY, buf, handle, cinTable[handle].dirty); cinTable[handle].dirty = qfalse; } // external vars so I can check if the game is setup enough that I can play the intro video... // -extern qboolean com_fullyInitialized; +extern qboolean com_fullyInitialized; extern qboolean s_soundStarted, s_soundMuted; // // ... and if the app isn't ready yet (which should only apply for the intro video), then I use these... // -static char sPendingCinematic_Arg [256]={0}; -static char sPendingCinematic_s [256]={0}; +static char sPendingCinematic_Arg[256] = {0}; +static char sPendingCinematic_s[256] = {0}; static qboolean gbPendingCinematic = qfalse; // // This stuff is for EF1-type ingame cinematics... // static qboolean qbPlayingInGameCinematic = qfalse; static qboolean qbInGameCinematicOnStandBy = qfalse; -static char sInGameCinematicStandingBy[MAX_QPATH]; -static char sTextCrawlFixedCinematic[MAX_QPATH]; +static char sInGameCinematicStandingBy[MAX_QPATH]; +static char sTextCrawlFixedCinematic[MAX_QPATH]; static qboolean qbTextCrawlFixed = qfalse; -static int stopCinematicCallCount = 0; - +static int stopCinematicCallCount = 0; - -static qboolean CIN_HardwareReadyToPlayVideos(void) -{ - if (com_fullyInitialized && cls.rendererStarted && - cls.soundStarted && - cls.soundRegistered - ) - { +static qboolean CIN_HardwareReadyToPlayVideos(void) { + if (com_fullyInitialized && cls.rendererStarted && cls.soundStarted && cls.soundRegistered) { return qtrue; } return qfalse; } - -static void PlayCinematic(const char *arg, const char *s, qboolean qbInGame) -{ +static void PlayCinematic(const char *arg, const char *s, qboolean qbInGame) { qboolean bFailed = qfalse; - Cvar_Set( "timescale", "1" ); // jic we were skipping a scripted cinematic, return to normal after playing video - Cvar_Set( "skippingCinematic", "0" ); // "" + Cvar_Set("timescale", "1"); // jic we were skipping a scripted cinematic, return to normal after playing video + Cvar_Set("skippingCinematic", "0"); // "" - if(qbInGameCinematicOnStandBy == qfalse) - { + if (qbInGameCinematicOnStandBy == qfalse) { qbTextCrawlFixed = qfalse; - } - else - { + } else { qbInGameCinematicOnStandBy = qfalse; } - int bits = qbInGame?0:CIN_system; + int bits = qbInGame ? 0 : CIN_system; Com_DPrintf("CL_PlayCinematic_f\n"); char sTemp[1024]; if (strstr(arg, "/") == NULL && strstr(arg, "\\") == NULL) { - Com_sprintf (sTemp, sizeof(sTemp), "video/%s", arg); + Com_sprintf(sTemp, sizeof(sTemp), "video/%s", arg); } else { - Com_sprintf (sTemp, sizeof(sTemp), "%s", arg); + Com_sprintf(sTemp, sizeof(sTemp), "%s", arg); } - COM_DefaultExtension(sTemp,sizeof(sTemp),".roq"); + COM_DefaultExtension(sTemp, sizeof(sTemp), ".roq"); arg = &sTemp[0]; - extern qboolean S_FileExists( const char *psFilename ); - if (S_FileExists( arg )) - { + extern qboolean S_FileExists(const char *psFilename); + if (S_FileExists(arg)) { SCR_StopCinematic(); // command-line hack to avoid problems when playing intro video before app is fully setup... // - if (!CIN_HardwareReadyToPlayVideos()) - { - Q_strncpyz(sPendingCinematic_Arg,arg, 256); - Q_strncpyz(sPendingCinematic_s , (s&&s[0])?s:"", 256); + if (!CIN_HardwareReadyToPlayVideos()) { + Q_strncpyz(sPendingCinematic_Arg, arg, 256); + Q_strncpyz(sPendingCinematic_s, (s && s[0]) ? s : "", 256); gbPendingCinematic = qtrue; return; } qbPlayingInGameCinematic = qbInGame; - if ((s && s[0] == '1') || Q_stricmp(arg,"video/end.roq")==0) { + if ((s && s[0] == '1') || Q_stricmp(arg, "video/end.roq") == 0) { bits |= CIN_hold; } if (s && s[0] == '2') { bits |= CIN_loop; } - S_StopAllSounds (); - + S_StopAllSounds(); //////////////////////////////////////////////////////////////////// // // work out associated audio-overlay file, if any... // extern cvar_t *s_language; - qboolean bIsForeign = (qboolean)(s_language && Q_stricmp(s_language->string,"english") && Q_stricmp(s_language->string,"")); - const char *psAudioFile = NULL; - qhandle_t hCrawl = 0; - if (!Q_stricmp(arg,"video/jk0101_sw.roq")) - { + qboolean bIsForeign = (qboolean)(s_language && Q_stricmp(s_language->string, "english") && Q_stricmp(s_language->string, "")); + const char *psAudioFile = NULL; + qhandle_t hCrawl = 0; + if (!Q_stricmp(arg, "video/jk0101_sw.roq")) { psAudioFile = "music/cinematic_1"; #ifdef JK2_MODE - hCrawl = re.RegisterShaderNoMip( va("menu/video/tc_%d", sp_language->integer) ); - if(!hCrawl) - { + hCrawl = re.RegisterShaderNoMip(va("menu/video/tc_%d", sp_language->integer)); + if (!hCrawl) { // failed, so go back to english - hCrawl = re.RegisterShaderNoMip( "menu/video/tc_0" ); + hCrawl = re.RegisterShaderNoMip("menu/video/tc_0"); } #else - hCrawl = re.RegisterShaderNoMip( va("menu/video/tc_%s",se_language->string) ); - if (!hCrawl) - { - hCrawl = re.RegisterShaderNoMip( "menu/video/tc_english" );//failed, so go back to english + hCrawl = re.RegisterShaderNoMip(va("menu/video/tc_%s", se_language->string)); + if (!hCrawl) { + hCrawl = re.RegisterShaderNoMip("menu/video/tc_english"); // failed, so go back to english } #endif bits |= CIN_hold; - } - else - if (bIsForeign) - { - if (!Q_stricmp(arg,"video/jk05.roq")) - { + } else if (bIsForeign) { + if (!Q_stricmp(arg, "video/jk05.roq")) { psAudioFile = "sound/chars/video/cinematic_5"; - bits |= CIN_silent; // knock out existing english track - } - else - if (!Q_stricmp(arg,"video/jk06.roq")) - { + bits |= CIN_silent; // knock out existing english track + } else if (!Q_stricmp(arg, "video/jk06.roq")) { psAudioFile = "sound/chars/video/cinematic_6"; - bits |= CIN_silent; // knock out existing english track + bits |= CIN_silent; // knock out existing english track } } // //////////////////////////////////////////////////////////////////// - CL_handle = CIN_PlayCinematic( arg, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, bits, psAudioFile ); - if (CL_handle >= 0) - { + CL_handle = CIN_PlayCinematic(arg, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, bits, psAudioFile); + if (CL_handle >= 0) { cinTable[CL_handle].hCRAWLTEXT = hCrawl; - do - { + do { SCR_RunCinematic(); - } - while (cinTable[currentHandle].buf == NULL && cinTable[currentHandle].status == FMV_PLAY); // wait for first frame (load codebook and sound) + } while (cinTable[currentHandle].buf == NULL && cinTable[currentHandle].status == FMV_PLAY); // wait for first frame (load codebook and sound) - if (qbInGame) - { - Cvar_SetValue( "cl_paused", 1); // remove-menu call will have unpaused us, so we sometimes need to re-pause + if (qbInGame) { + Cvar_SetValue("cl_paused", 1); // remove-menu call will have unpaused us, so we sometimes need to re-pause } - CL_iPlaybackStartTime = cls.realtime; // special use to avoid accidentally skipping ingame videos via fast-firing - } - else - { + CL_iPlaybackStartTime = cls.realtime; // special use to avoid accidentally skipping ingame videos via fast-firing + } else { // failed to open video... // bFailed = qtrue; } - } - else - { + } else { // failed to open video... // bFailed = qtrue; } - if (bFailed) - { - Com_Printf(S_COLOR_RED "PlayCinematic(): Failed to open \"%s\"\n",arg); - //S_RestartMusic(); //restart the level music - SCR_StopCinematic(); // I know this seems pointless, but it clears a bunch of vars as well - } - else - { + if (bFailed) { + Com_Printf(S_COLOR_RED "PlayCinematic(): Failed to open \"%s\"\n", arg); + // S_RestartMusic(); //restart the level music + SCR_StopCinematic(); // I know this seems pointless, but it clears a bunch of vars as well + } else { // this doesn't work for now... // -// if (cls.state == CA_ACTIVE){ -// re.InitDissolve(qfalse); // so we get a dissolve between previous screen image and cinematic -// } + // if (cls.state == CA_ACTIVE){ + // re.InitDissolve(qfalse); // so we get a dissolve between previous screen image and cinematic + // } } } - -qboolean CL_CheckPendingCinematic(void) -{ - if ( gbPendingCinematic && CIN_HardwareReadyToPlayVideos() ) - { - gbPendingCinematic = qfalse; // BEFORE next line, or we get recursion - PlayCinematic(sPendingCinematic_Arg,sPendingCinematic_s[0]?sPendingCinematic_s:NULL,qfalse); +qboolean CL_CheckPendingCinematic(void) { + if (gbPendingCinematic && CIN_HardwareReadyToPlayVideos()) { + gbPendingCinematic = qfalse; // BEFORE next line, or we get recursion + PlayCinematic(sPendingCinematic_Arg, sPendingCinematic_s[0] ? sPendingCinematic_s : NULL, qfalse); return qtrue; } return qfalse; @@ -1980,144 +1918,113 @@ qboolean CL_CheckPendingCinematic(void) CL_CompleteCinematic ================== */ -void CL_CompleteCinematic( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "video", "roq", qtrue, qfalse ); +void CL_CompleteCinematic(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("video", "roq", qtrue, qfalse); } -void CL_PlayCinematic_f(void) -{ - const char *arg, *s; +void CL_PlayCinematic_f(void) { + const char *arg, *s; - arg = Cmd_Argv( 1 ); + arg = Cmd_Argv(1); s = Cmd_Argv(2); - PlayCinematic(arg,s,qfalse); + PlayCinematic(arg, s, qfalse); } -void CL_PlayInGameCinematic_f(void) -{ - const char *arg = Cmd_Argv( 1 ); - if (cls.state == CA_ACTIVE) - { - PlayCinematic(arg,NULL,qtrue); - } - else if( !qbInGameCinematicOnStandBy ) - { +void CL_PlayInGameCinematic_f(void) { + const char *arg = Cmd_Argv(1); + if (cls.state == CA_ACTIVE) { + PlayCinematic(arg, NULL, qtrue); + } else if (!qbInGameCinematicOnStandBy) { Q_strncpyz(sInGameCinematicStandingBy, arg, MAX_QPATH); qbInGameCinematicOnStandBy = qtrue; - } - else - { + } else { // hack in order to fix text crawl --eez Q_strncpyz(sTextCrawlFixedCinematic, arg, MAX_QPATH); qbTextCrawlFixed = qtrue; } } - // Externally-called only, and only if cls.state == CA_CINEMATIC (or CL_IsRunningInGameCinematic() == true now) // -void SCR_DrawCinematic (void) -{ - if (CL_InGameCinematicOnStandBy()) - { - PlayCinematic(sInGameCinematicStandingBy,NULL,qtrue); - } - else if( qbTextCrawlFixed && stopCinematicCallCount > 1) - { +void SCR_DrawCinematic(void) { + if (CL_InGameCinematicOnStandBy()) { + PlayCinematic(sInGameCinematicStandingBy, NULL, qtrue); + } else if (qbTextCrawlFixed && stopCinematicCallCount > 1) { PlayCinematic(sTextCrawlFixedCinematic, NULL, qtrue); } if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) { CIN_DrawCinematic(CL_handle); - if (cinTable[CL_handle].hCRAWLTEXT && (cls.realtime - CL_iPlaybackStartTime >= TC_DELAY)) - { + if (cinTable[CL_handle].hCRAWLTEXT && (cls.realtime - CL_iPlaybackStartTime >= TC_DELAY)) { CIN_AddTextCrawl(); } } } -void SCR_RunCinematic (void) -{ +void SCR_RunCinematic(void) { CL_CheckPendingCinematic(); if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) { e_status Status = CIN_RunCinematic(CL_handle); - if (CL_IsRunningInGameCinematic() && Status == FMV_IDLE && !cinTable[CL_handle].holdAtEnd) - { - SCR_StopCinematic(); // change ROQ from FMV_IDLE to FMV_EOF, and clear some other vars + if (CL_IsRunningInGameCinematic() && Status == FMV_IDLE && !cinTable[CL_handle].holdAtEnd) { + SCR_StopCinematic(); // change ROQ from FMV_IDLE to FMV_EOF, and clear some other vars } } } -void SCR_StopCinematic( qboolean bAllowRefusal /* = qfalse */ ) -{ - if (bAllowRefusal) - { - if ( (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) - && - cls.realtime < CL_iPlaybackStartTime + 1200 // 1.2 seconds have to have elapsed - ) - { +void SCR_StopCinematic(qboolean bAllowRefusal /* = qfalse */) { + if (bAllowRefusal) { + if ((CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) && cls.realtime < CL_iPlaybackStartTime + 1200 // 1.2 seconds have to have elapsed + ) { return; } } - if ( CL_IsRunningInGameCinematic()) - { + if (CL_IsRunningInGameCinematic()) { Com_DPrintf("In-game Cinematic Stopped\n"); } - if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES && - stopCinematicCallCount != 1) { // hello no, don't want this plz + if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES && stopCinematicCallCount != 1) { // hello no, don't want this plz CIN_StopCinematic(CL_handle); - S_StopAllSounds (); + S_StopAllSounds(); CL_handle = -1; - if (CL_IsRunningInGameCinematic()){ - re.InitDissolve(qfalse); // dissolve from cinematic to underlying ingame + if (CL_IsRunningInGameCinematic()) { + re.InitDissolve(qfalse); // dissolve from cinematic to underlying ingame } } - if (cls.state == CA_CINEMATIC) - { + if (cls.state == CA_CINEMATIC) { Com_DPrintf("Cinematic Stopped\n"); - cls.state = CA_DISCONNECTED; + cls.state = CA_DISCONNECTED; } - if(sInGameCinematicStandingBy[0] && - qbTextCrawlFixed) - { + if (sInGameCinematicStandingBy[0] && qbTextCrawlFixed) { // Hacky fix to help deal with broken text crawl.. // If we are skipping past the one on standby, DO NOT SKIP THE OTHER ONES! stopCinematicCallCount++; - } - else if(stopCinematicCallCount == 1) - { + } else if (stopCinematicCallCount == 1) { stopCinematicCallCount++; - } - else - { + } else { // Skipping the last one in the list, go ahead and kill it. qbTextCrawlFixed = qfalse; sTextCrawlFixedCinematic[0] = 0; stopCinematicCallCount = 0; } - if(stopCinematicCallCount != 2) - { + if (stopCinematicCallCount != 2) { qbPlayingInGameCinematic = qfalse; qbInGameCinematicOnStandBy = qfalse; - sInGameCinematicStandingBy[0]=0; - Cvar_SetValue( "cl_paused", 0 ); + sInGameCinematicStandingBy[0] = 0; + Cvar_SetValue("cl_paused", 0); } - if (cls.state != CA_DISCONNECTED) // cut down on needless calls to music code + if (cls.state != CA_DISCONNECTED) // cut down on needless calls to music code { - S_RestartMusic(); //restart the level music + S_RestartMusic(); // restart the level music } } - void CIN_UploadCinematic(int handle) { if (handle >= 0 && handle < MAX_VIDEO_HANDLES) { if (!cinTable[handle].buf) { @@ -2136,41 +2043,30 @@ void CIN_UploadCinematic(int handle) { } // Resample the video if needed - if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { + if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { int *buf2; - buf2 = (int *)Z_Malloc(256*256*4, TAG_TEMP_WORKSPACE, qfalse); + buf2 = (int *)Z_Malloc(256 * 256 * 4, TAG_TEMP_WORKSPACE, qfalse); CIN_ResampleCinematic(handle, buf2); - re.UploadCinematic( 256, 256, (byte *)buf2, handle, qtrue); + re.UploadCinematic(256, 256, (byte *)buf2, handle, qtrue); cinTable[handle].dirty = qfalse; Z_Free(buf2); } else { // Upload video at normal resolution - re.UploadCinematic( cinTable[handle].drawX, cinTable[handle].drawY, - cinTable[handle].buf, handle, cinTable[handle].dirty); + re.UploadCinematic(cinTable[handle].drawX, cinTable[handle].drawY, cinTable[handle].buf, handle, cinTable[handle].dirty); cinTable[handle].dirty = qfalse; } if (cl_inGameVideo->integer == 0 && cinTable[handle].playonwalls == 1) { cinTable[handle].playonwalls--; - } - else if (cl_inGameVideo->integer != 0 && cinTable[handle].playonwalls != 1) { + } else if (cl_inGameVideo->integer != 0 && cinTable[handle].playonwalls != 1) { cinTable[handle].playonwalls = 1; } } } +qboolean CL_IsRunningInGameCinematic(void) { return qbPlayingInGameCinematic; } -qboolean CL_IsRunningInGameCinematic(void) -{ - return qbPlayingInGameCinematic; -} - -qboolean CL_InGameCinematicOnStandBy(void) -{ - return qbInGameCinematicOnStandBy; -} - - +qboolean CL_InGameCinematicOnStandBy(void) { return qbInGameCinematicOnStandBy; } diff --git a/code/client/cl_console.cpp b/code/client/cl_console.cpp index f175cbcaf5..b80c6a3867 100644 --- a/code/client/cl_console.cpp +++ b/code/client/cl_console.cpp @@ -32,48 +32,47 @@ along with this program; if not, see . int g_console_field_width = 78; -console_t con; +console_t con; -cvar_t *con_conspeed; -cvar_t *con_notifytime; -cvar_t *con_opacity; // background alpha multiplier -cvar_t *con_autoclear; -cvar_t *con_height; -cvar_t *con_scale; -cvar_t *con_timestamps; +cvar_t *con_conspeed; +cvar_t *con_notifytime; +cvar_t *con_opacity; // background alpha multiplier +cvar_t *con_autoclear; +cvar_t *con_height; +cvar_t *con_scale; +cvar_t *con_timestamps; -#define DEFAULT_CONSOLE_WIDTH 78 +#define DEFAULT_CONSOLE_WIDTH 78 -#define CON_BLANK_CHAR ' ' -#define CON_SCROLL_L_CHAR '$' -#define CON_SCROLL_R_CHAR '$' -#define CON_TIMESTAMP_LEN 11 // "[13:37:00] " -#define CON_MIN_WIDTH 20 +#define CON_BLANK_CHAR ' ' +#define CON_SCROLL_L_CHAR '$' +#define CON_SCROLL_R_CHAR '$' +#define CON_TIMESTAMP_LEN 11 // "[13:37:00] " +#define CON_MIN_WIDTH 20 +static const conChar_t CON_WRAP = {{ColorIndex(COLOR_GREY), '\\'}}; +static const conChar_t CON_BLANK = {{ColorIndex(COLOR_WHITE), CON_BLANK_CHAR}}; -static const conChar_t CON_WRAP = { { ColorIndex(COLOR_GREY), '\\' } }; -static const conChar_t CON_BLANK = { { ColorIndex(COLOR_WHITE), CON_BLANK_CHAR } }; - -vec4_t console_color = {0.509f, 0.609f, 0.847f, 1.0f}; +vec4_t console_color = {0.509f, 0.609f, 0.847f, 1.0f}; /* ================ Con_ToggleConsole_f ================ */ -void Con_ToggleConsole_f (void) { +void Con_ToggleConsole_f(void) { // closing a full screen console restarts the demo loop - if ( cls.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) { -// CL_StartDemoLoop(); + if (cls.state == CA_DISCONNECTED && Key_GetCatcher() == KEYCATCH_CONSOLE) { + // CL_StartDemoLoop(); return; } - if( con_autoclear->integer ) - Field_Clear( &g_consoleField ); + if (con_autoclear->integer) + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - Con_ClearNotify (); - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE ); + Con_ClearNotify(); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_CONSOLE); } /* @@ -81,9 +80,9 @@ void Con_ToggleConsole_f (void) { Con_ToggleMenu_f =================== */ -void Con_ToggleMenu_f( void ) { - CL_KeyEvent( A_ESCAPE, qtrue, Sys_Milliseconds() ); - CL_KeyEvent( A_ESCAPE, qfalse, Sys_Milliseconds() ); +void Con_ToggleMenu_f(void) { + CL_KeyEvent(A_ESCAPE, qtrue, Sys_Milliseconds()); + CL_KeyEvent(A_ESCAPE, qfalse, Sys_Milliseconds()); } /* @@ -91,14 +90,14 @@ void Con_ToggleMenu_f( void ) { Con_Clear_f ================ */ -void Con_Clear_f (void) { - int i; +void Con_Clear_f(void) { + int i; - for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) { + for (i = 0; i < CON_TEXTSIZE; i++) { con.text[i] = CON_BLANK; } - Con_Bottom(); // go to end + Con_Bottom(); // go to end } /* @@ -108,56 +107,50 @@ Con_Dump_f Save the console contents out to a file ================ */ -void Con_Dump_f (void) -{ - char filename[MAX_QPATH]; - qboolean empty; - int l, i, j; - int line; - int lineLen; - fileHandle_t f; +void Con_Dump_f(void) { + char filename[MAX_QPATH]; + qboolean empty; + int l, i, j; + int line; + int lineLen; + fileHandle_t f; #ifdef WIN32 - char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 2]; + char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 2]; #else - char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 1]; + char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 1]; #endif - if (Cmd_Argc() != 2) - { - Com_Printf ("%s\n", SE_GetString("CON_TEXT_DUMP_USAGE")); + if (Cmd_Argc() != 2) { + Com_Printf("%s\n", SE_GetString("CON_TEXT_DUMP_USAGE")); return; } - Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".txt"); - if(!COM_CompareExtension(filename, ".txt")) - { - Com_Printf( "Con_Dump_f: Only the \".txt\" extension is supported by this command!\n" ); + if (!COM_CompareExtension(filename, ".txt")) { + Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } - f = FS_FOpenFileWrite( filename ); - if (!f) - { - Com_Printf ("ERROR: couldn't open %s.\n", filename); + f = FS_FOpenFileWrite(filename); + if (!f) { + Com_Printf("ERROR: couldn't open %s.\n", filename); return; } - Com_Printf ("Dumped console text to %s.\n", filename ); + Com_Printf("Dumped console text to %s.\n", filename); // skip empty lines - for (l = 1, empty = qtrue ; l < con.totallines && empty ; l++) - { + for (l = 1, empty = qtrue; l < con.totallines && empty; l++) { line = ((con.current + l) % con.totallines) * con.rowwidth; - for (j = CON_TIMESTAMP_LEN ; j < con.rowwidth - 1 ; j++) + for (j = CON_TIMESTAMP_LEN; j < con.rowwidth - 1; j++) if (con.text[line + j].f.character != CON_BLANK_CHAR) empty = qfalse; } - for ( ; l < con.totallines ; l++) - { + for (; l < con.totallines; l++) { lineLen = 0; i = 0; @@ -172,8 +165,7 @@ void Con_Dump_f (void) } // Concatenate wrapped lines - for ( ; l < con.totallines ; l++) - { + for (; l < con.totallines; l++) { line = ((con.current + l) % con.totallines) * con.rowwidth; for (j = CON_TIMESTAMP_LEN; j < con.rowwidth - 1 && i < (int)sizeof(buffer) - 1; j++, i++) { @@ -192,7 +184,7 @@ void Con_Dump_f (void) #ifdef WIN32 // I really don't like this inconsistency, but OpenJK has been doing this since April 2013 buffer[lineLen] = '\r'; - buffer[lineLen+1] = '\n'; + buffer[lineLen + 1] = '\n'; FS_Write(buffer, lineLen + 2, f); #else buffer[lineLen] = '\n'; @@ -200,19 +192,18 @@ void Con_Dump_f (void) #endif } - FS_FCloseFile( f ); + FS_FCloseFile(f); } - /* ================ Con_ClearNotify ================ */ -void Con_ClearNotify( void ) { - int i; +void Con_ClearNotify(void) { + int i; - for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) { + for (i = 0; i < NUM_CON_TIMES; i++) { con.times[i] = 0; } } @@ -224,9 +215,8 @@ Con_Initialize Initialize console for the first time. ================ */ -void Con_Initialize(void) -{ - int i; +void Con_Initialize(void) { + int i; VectorCopy4(colorWhite, con.color); con.charWidth = SMALLCHAR_WIDTH; @@ -238,16 +228,13 @@ void Con_Initialize(void) con.display = con.current; con.xadjust = 1.0f; con.yadjust = 1.0f; - for(i=0; i= SMALLCHAR_WIDTH); @@ -387,21 +370,19 @@ void Con_CheckResize (void) con.yadjust = ((float)SCREEN_HEIGHT) / cls.glconfig.vidHeight; g_consoleField.widthInChars = width - 1; // Command prompt - if (con.rowwidth != rowwidth) - { + if (con.rowwidth != rowwidth) { Con_Resize(rowwidth); } } - /* ================== Cmd_CompleteTxtName ================== */ -void Cmd_CompleteTxtName( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "", "txt", qfalse, qtrue ); +void Cmd_CompleteTxtName(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("", "txt", qfalse, qtrue); } /* @@ -409,60 +390,57 @@ void Cmd_CompleteTxtName( char *args, int argNum ) { Con_Init ================ */ -void Con_Init (void) { - int i; +void Con_Init(void) { + int i; - con_notifytime = Cvar_Get ("con_notifytime", "3", 0); - con_conspeed = Cvar_Get ("scr_conspeed", "3", 0); - Cvar_CheckRange (con_conspeed, 1.0f, 100.0f, qfalse); + con_notifytime = Cvar_Get("con_notifytime", "3", 0); + con_conspeed = Cvar_Get("scr_conspeed", "3", 0); + Cvar_CheckRange(con_conspeed, 1.0f, 100.0f, qfalse); - con_opacity = Cvar_Get ("con_opacity", "0.8", CVAR_ARCHIVE_ND); - con_autoclear = Cvar_Get ("con_autoclear", "1", CVAR_ARCHIVE_ND); - con_height = Cvar_Get ("con_height", "0.5", CVAR_ARCHIVE_ND); + con_opacity = Cvar_Get("con_opacity", "0.8", CVAR_ARCHIVE_ND); + con_autoclear = Cvar_Get("con_autoclear", "1", CVAR_ARCHIVE_ND); + con_height = Cvar_Get("con_height", "0.5", CVAR_ARCHIVE_ND); - con_scale = Cvar_Get ("con_scale", "1", CVAR_ARCHIVE_ND); - con_timestamps = Cvar_Get ("con_timestamps", "0", CVAR_ARCHIVE_ND); + con_scale = Cvar_Get("con_scale", "1", CVAR_ARCHIVE_ND); + con_timestamps = Cvar_Get("con_timestamps", "0", CVAR_ARCHIVE_ND); - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) { - Field_Clear( &historyEditLines[i] ); + for (i = 0; i < COMMAND_HISTORY; i++) { + Field_Clear(&historyEditLines[i]); historyEditLines[i].widthInChars = g_console_field_width; } - Cmd_AddCommand ("toggleconsole", Con_ToggleConsole_f); - Cmd_AddCommand ("togglemenu", Con_ToggleMenu_f); - Cmd_AddCommand ("clear", Con_Clear_f); - Cmd_AddCommand ("condump", Con_Dump_f); - Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName ); + Cmd_AddCommand("toggleconsole", Con_ToggleConsole_f); + Cmd_AddCommand("togglemenu", Con_ToggleMenu_f); + Cmd_AddCommand("clear", Con_Clear_f); + Cmd_AddCommand("condump", Con_Dump_f); + Cmd_SetCommandCompletionFunc("condump", Cmd_CompleteTxtName); - //Initialize values on first print + // Initialize values on first print con.initialized = qfalse; } - /* =============== Con_Linefeed =============== */ -void Con_Linefeed (void) -{ - int i; - int line = (con.current % con.totallines) * con.rowwidth; +void Con_Linefeed(void) { + int i; + int line = (con.current % con.totallines) * con.rowwidth; // print timestamp on the PREVIOUS line { - time_t t = time( NULL ); - struct tm *tms = localtime( &t ); + time_t t = time(NULL); + struct tm *tms = localtime(&t); char timestamp[CON_TIMESTAMP_LEN + 1]; const unsigned char color = ColorIndex(COLOR_GREY); - Com_sprintf(timestamp, sizeof(timestamp), "[%02d:%02d:%02d] ", - tms->tm_hour, tms->tm_min, tms->tm_sec); + Com_sprintf(timestamp, sizeof(timestamp), "[%02d:%02d:%02d] ", tms->tm_hour, tms->tm_min, tms->tm_sec); - for ( i = 0; i < CON_TIMESTAMP_LEN; i++ ) { - con.text[line + i].f = { color, timestamp[i] }; + for (i = 0; i < CON_TIMESTAMP_LEN; i++) { + con.text[line + i].f = {color, timestamp[i]}; } } @@ -478,7 +456,7 @@ void Con_Linefeed (void) line = (con.current % con.totallines) * con.rowwidth; - for ( i = 0; i < con.rowwidth; i++ ) + for (i = 0; i < con.rowwidth; i++) con.text[line + i] = CON_BLANK; } @@ -491,13 +469,13 @@ All console printing must go through this in order to be logged to disk If no console is visible, the text will appear at the top of the game window ================ */ -void CL_ConsolePrint( const char *txt) { - int y; - char c; - unsigned char color; +void CL_ConsolePrint(const char *txt) { + int y; + char c; + unsigned char color; // for some demos we don't want to ever show anything on the console - if ( cl_noprint && cl_noprint->integer ) { + if (cl_noprint && cl_noprint->integer) { return; } @@ -507,24 +485,23 @@ void CL_ConsolePrint( const char *txt) { color = ColorIndex(COLOR_WHITE); - while ( (c = (unsigned char) *txt) != 0 ) { - if ( Q_IsColorString( (unsigned char*) txt ) ) { - color = ColorIndex( *(txt+1) ); + while ((c = (unsigned char)*txt) != 0) { + if (Q_IsColorString((unsigned char *)txt)) { + color = ColorIndex(*(txt + 1)); txt += 2; continue; } txt++; - switch (c) - { + switch (c) { case '\n': - Con_Linefeed (); + Con_Linefeed(); break; case '\r': con.x = 0; break; - default: // display character and advance + default: // display character and advance y = con.current % con.totallines; if (con.x == con.rowwidth - CON_TIMESTAMP_LEN - 1) { @@ -533,20 +510,18 @@ void CL_ConsolePrint( const char *txt) { y = con.current % con.totallines; } - con.text[y * con.rowwidth + CON_TIMESTAMP_LEN + con.x].f = { color, c }; + con.text[y * con.rowwidth + CON_TIMESTAMP_LEN + con.x].f = {color, c}; con.x++; break; } } - // mark time for transparent overlay if (con.current >= 0) con.times[con.current % NUM_CON_TIMES] = cls.realtime; } - /* ============================================================================== @@ -555,7 +530,6 @@ DRAWING ============================================================================== */ - /* ================ Con_DrawInput @@ -563,33 +537,32 @@ Con_DrawInput Draw the editline after a ] prompt ================ */ -void Con_DrawInput (void) { - int y; +void Con_DrawInput(void) { + int y; - if ( cls.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) { + if (cls.state != CA_DISCONNECTED && !(Key_GetCatcher() & KEYCATCH_CONSOLE)) { return; } - y = con.vislines - ( con.charHeight * (re.Language_IsAsian() ? 1.5 : 2) ); + y = con.vislines - (con.charHeight * (re.Language_IsAsian() ? 1.5 : 2)); - re.SetColor( con.color ); + re.SetColor(con.color); - Field_Draw( &g_consoleField, 2 * con.charWidth, y, qtrue, qtrue ); + Field_Draw(&g_consoleField, 2 * con.charWidth, y, qtrue, qtrue); - SCR_DrawSmallChar( con.charWidth, y, CONSOLE_PROMPT_CHAR ); + SCR_DrawSmallChar(con.charWidth, y, CONSOLE_PROMPT_CHAR); - re.SetColor( g_color_table[ColorIndex(COLOR_GREY)] ); + re.SetColor(g_color_table[ColorIndex(COLOR_GREY)]); - if ( g_consoleField.scroll > 0 ) - SCR_DrawSmallChar( 0, y, CON_SCROLL_L_CHAR ); + if (g_consoleField.scroll > 0) + SCR_DrawSmallChar(0, y, CON_SCROLL_L_CHAR); - int len = Q_PrintStrlen( g_consoleField.buffer ); - int pos = Q_PrintStrLenTo( g_consoleField.buffer, g_consoleField.scroll, NULL ); - if ( pos + g_consoleField.widthInChars < len ) - SCR_DrawSmallChar( cls.glconfig.vidWidth - con.charWidth, y, CON_SCROLL_R_CHAR ); + int len = Q_PrintStrlen(g_consoleField.buffer); + int pos = Q_PrintStrLenTo(g_consoleField.buffer, g_consoleField.scroll, NULL); + if (pos + g_consoleField.widthInChars < len) + SCR_DrawSmallChar(cls.glconfig.vidWidth - con.charWidth, y, CON_SCROLL_R_CHAR); } - /* ================ Con_DrawNotify @@ -597,40 +570,36 @@ Con_DrawNotify Draws the last few lines of output transparently over the game top ================ */ -void Con_DrawNotify (void) -{ - int x, v; - conChar_t *text; - int i; - int time; - int currentColor; +void Con_DrawNotify(void) { + int x, v; + conChar_t *text; + int i; + int time; + int currentColor; currentColor = 7; - re.SetColor( g_color_table[currentColor] ); + re.SetColor(g_color_table[currentColor]); int iFontIndex = cls.consoleFont; float fFontScale = 1.0f; int iPixelHeightToAdvance = 0; - if (re.Language_IsAsian()) - { - fFontScale = con.charWidth * 10.0f / - re.Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); + if (re.Language_IsAsian()) { + fFontScale = con.charWidth * 10.0f / re.Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); fFontScale *= con.yadjust; - iPixelHeightToAdvance = 2+(1.3/con.yadjust) * re.Font_HeightPixels(iFontIndex, fFontScale); + iPixelHeightToAdvance = 2 + (1.3 / con.yadjust) * re.Font_HeightPixels(iFontIndex, fFontScale); } v = 0; - for (i= con.current-NUM_CON_TIMES+1 ; i<=con.current ; i++) - { + for (i = con.current - NUM_CON_TIMES + 1; i <= con.current; i++) { if (i < 0) continue; time = con.times[i % NUM_CON_TIMES]; if (time == 0) continue; time = cls.realtime - time; - if (time > con_notifytime->value*1000) + if (time > con_notifytime->value * 1000) continue; - text = con.text + (i % con.totallines)*con.rowwidth; + text = con.text + (i % con.totallines) * con.rowwidth; if (!con_timestamps->integer) text += CON_TIMESTAMP_LEN; @@ -638,46 +607,41 @@ void Con_DrawNotify (void) // // (ignore colours since we're going to print the whole thing as one string) // - if (re.Language_IsAsian()) - { + if (re.Language_IsAsian()) { // concat the text to be printed... // - char sTemp[4096]; // ott + char sTemp[4096]; // ott sTemp[0] = '\0'; - for (x = 0 ; x < con.linewidth ; x++) - { - if ( text[x].f.color != currentColor ) { + for (x = 0; x < con.linewidth; x++) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - strcat(sTemp,va("^%i", currentColor )); + strcat(sTemp, va("^%i", currentColor)); } - strcat(sTemp,va("%c",text[x].f.character)); + strcat(sTemp, va("%c", text[x].f.character)); } // // and print... // - re.Font_DrawString(con.xadjust * (con.xadjust + con.charWidth), con.yadjust * v, sTemp, - g_color_table[currentColor], iFontIndex, -1, fFontScale); + re.Font_DrawString(con.xadjust * (con.xadjust + con.charWidth), con.yadjust * v, sTemp, g_color_table[currentColor], iFontIndex, -1, fFontScale); - v += iPixelHeightToAdvance; - } - else - { - for (x = 0 ; x < con.linewidth ; x++) { - if ( text[x].f.character == ' ' ) { + v += iPixelHeightToAdvance; + } else { + for (x = 0; x < con.linewidth; x++) { + if (text[x].f.character == ' ') { continue; } - if ( text[x].f.color != currentColor ) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - re.SetColor( g_color_table[currentColor] ); + re.SetColor(g_color_table[currentColor]); } - SCR_DrawSmallChar( (x+1)*con.charWidth, v, text[x].f.character ); + SCR_DrawSmallChar((x + 1) * con.charWidth, v, text[x].f.character); } v += con.charHeight; } } - re.SetColor( NULL ); + re.SetColor(NULL); } /* @@ -687,97 +651,87 @@ Con_DrawSolidConsole Draws the console with the solid background ================ */ -void Con_DrawSolidConsole( float frac ) -{ - int i, x, y; - int rows; - conChar_t *text; - int row; - int lines; -// qhandle_t conShader; - int currentColor; +void Con_DrawSolidConsole(float frac) { + int i, x, y; + int rows; + conChar_t *text; + int row; + int lines; + // qhandle_t conShader; + int currentColor; lines = cls.glconfig.vidHeight * frac; if (lines <= 0) return; - if (lines > cls.glconfig.vidHeight ) + if (lines > cls.glconfig.vidHeight) lines = cls.glconfig.vidHeight; // draw the background y = frac * SCREEN_HEIGHT - 2; - if ( y < 1 ) { + if (y < 1) { y = 0; - } - else { + } else { // draw the background at full opacity only if fullscreen - if (frac < 1.0f) - { + if (frac < 1.0f) { vec4_t con_color; MAKERGBA(con_color, 1.0f, 1.0f, 1.0f, Com_Clamp(0.0f, 1.0f, con_opacity->value)); re.SetColor(con_color); - } - else - { + } else { re.SetColor(NULL); } - SCR_DrawPic( 0, 0, SCREEN_WIDTH, y, cls.consoleShader ); + SCR_DrawPic(0, 0, SCREEN_WIDTH, y, cls.consoleShader); } // draw the bottom bar and version number - re.SetColor( console_color ); - re.DrawStretchPic( 0, y, SCREEN_WIDTH, 2, 0, 0, 0, 0, cls.whiteShader ); + re.SetColor(console_color); + re.DrawStretchPic(0, y, SCREEN_WIDTH, 2, 0, 0, 0, 0, cls.whiteShader); - i = strlen( Q3_VERSION ); + i = strlen(Q3_VERSION); - for (x=0 ; x= con.totallines) { @@ -785,7 +739,7 @@ void Con_DrawSolidConsole( float frac ) continue; } - text = con.text + (row % con.totallines)*con.rowwidth; + text = con.text + (row % con.totallines) * con.rowwidth; if (!con_timestamps->integer) text += CON_TIMESTAMP_LEN; @@ -793,70 +747,63 @@ void Con_DrawSolidConsole( float frac ) // // (ignore colours since we're going to print the whole thing as one string) // - if (re.Language_IsAsian()) - { + if (re.Language_IsAsian()) { // concat the text to be printed... // - char sTemp[4096]; // ott + char sTemp[4096]; // ott sTemp[0] = '\0'; - for (x = 0 ; x < con.linewidth + 1 ; x++) - { - if ( text[x].f.color != currentColor ) { + for (x = 0; x < con.linewidth + 1; x++) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - strcat(sTemp,va("^%i", currentColor )); + strcat(sTemp, va("^%i", currentColor)); } - strcat(sTemp,va("%c",text[x].f.character)); + strcat(sTemp, va("%c", text[x].f.character)); } // // and print... // - re.Font_DrawString(con.xadjust*(con.xadjust + con.charWidth), con.yadjust * y, sTemp, g_color_table[currentColor], - iFontIndex, -1, fFontScale); - } - else - { - for (x = 0; x < con.linewidth + 1 ; x++) { - if ( text[x].f.character == ' ' ) { + re.Font_DrawString(con.xadjust * (con.xadjust + con.charWidth), con.yadjust * y, sTemp, g_color_table[currentColor], iFontIndex, -1, fFontScale); + } else { + for (x = 0; x < con.linewidth + 1; x++) { + if (text[x].f.character == ' ') { continue; } - if ( text[x].f.color != currentColor ) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - re.SetColor( g_color_table[currentColor] ); + re.SetColor(g_color_table[currentColor]); } - SCR_DrawSmallChar( (x+1)*con.charWidth, y, text[x].f.character ); + SCR_DrawSmallChar((x + 1) * con.charWidth, y, text[x].f.character); } } } - re.SetColor( NULL ); + re.SetColor(NULL); } - - /* ================== Con_DrawConsole ================== */ -void Con_DrawConsole( void ) { +void Con_DrawConsole(void) { // check for console width changes from a vid mode change - Con_CheckResize (); + Con_CheckResize(); // if disconnected, render console full screen - if ( cls.state == CA_DISCONNECTED ) { - if ( !( Key_GetCatcher( ) & KEYCATCH_UI) ) { - Con_DrawSolidConsole( 1.0 ); + if (cls.state == CA_DISCONNECTED) { + if (!(Key_GetCatcher() & KEYCATCH_UI)) { + Con_DrawSolidConsole(1.0); return; } } - if ( con.displayFrac ) { - Con_DrawSolidConsole( con.displayFrac ); + if (con.displayFrac) { + Con_DrawSolidConsole(con.displayFrac); } else { // draw notify lines - if ( cls.state == CA_ACTIVE ) { - Con_DrawNotify (); + if (cls.state == CA_ACTIVE) { + Con_DrawNotify(); } } } @@ -870,61 +817,53 @@ Con_RunConsole Scroll it up or down ================== */ -void Con_RunConsole (void) { +void Con_RunConsole(void) { // decide on the destination height of the console - if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) + if (Key_GetCatcher() & KEYCATCH_CONSOLE) con.finalFrac = con_height->value; else - con.finalFrac = 0; // none visible + con.finalFrac = 0; // none visible // scroll towards the destination height - if (con.finalFrac < con.displayFrac) - { - con.displayFrac -= con_conspeed->value*cls.realFrametime*0.001; + if (con.finalFrac < con.displayFrac) { + con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001; if (con.finalFrac > con.displayFrac) con.displayFrac = con.finalFrac; - } - else if (con.finalFrac > con.displayFrac) - { - con.displayFrac += con_conspeed->value*cls.realFrametime*0.001; + } else if (con.finalFrac > con.displayFrac) { + con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001; if (con.finalFrac < con.displayFrac) con.displayFrac = con.finalFrac; } - } - -void Con_PageUp( void ) { +void Con_PageUp(void) { con.display -= 2; - if ( con.current - con.display >= con.totallines ) { + if (con.current - con.display >= con.totallines) { con.display = con.current - con.totallines + 1; } } -void Con_PageDown( void ) { +void Con_PageDown(void) { con.display += 2; if (con.display > con.current) { con.display = con.current; } } -void Con_Top( void ) { +void Con_Top(void) { con.display = con.totallines; - if ( con.current - con.display >= con.totallines ) { + if (con.current - con.display >= con.totallines) { con.display = con.current - con.totallines + 1; } } -void Con_Bottom( void ) { - con.display = con.current; -} - +void Con_Bottom(void) { con.display = con.current; } -void Con_Close( void ) { - Field_Clear( &g_consoleField ); - Con_ClearNotify (); - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE ); - con.finalFrac = 0; // none visible +void Con_Close(void) { + Field_Clear(&g_consoleField); + Con_ClearNotify(); + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_CONSOLE); + con.finalFrac = 0; // none visible con.displayFrac = 0; } diff --git a/code/client/cl_input.cpp b/code/client/cl_input.cpp index 940517600b..412b022dc0 100644 --- a/code/client/cl_input.cpp +++ b/code/client/cl_input.cpp @@ -32,8 +32,8 @@ along with this program; if not, see . #include #endif -unsigned frame_msec; -int old_com_frameTime; +unsigned frame_msec; +int old_com_frameTime; float cl_mPitchOverride = 0.0f; float cl_mYawOverride = 0.0f; @@ -57,32 +57,29 @@ at the same time. =============================================================================== */ +kbutton_t in_left, in_right, in_forward, in_back; +kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; +kbutton_t in_strafe, in_speed; +kbutton_t in_up, in_down; -kbutton_t in_left, in_right, in_forward, in_back; -kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; -kbutton_t in_strafe, in_speed; -kbutton_t in_up, in_down; +kbutton_t in_buttons[32]; -kbutton_t in_buttons[32]; +qboolean in_mlooking; +extern cvar_t *in_joystick; -qboolean in_mlooking; - -extern cvar_t *in_joystick; - -static void IN_UseGivenForce(void) -{ +static void IN_UseGivenForce(void) { const char *c = Cmd_Argv(1); - int forceNum=-1; + int forceNum = -1; int genCmdNum = 0; - if(c) { + if (c) { forceNum = atoi(c); } else { return; } - switch(forceNum) { + switch (forceNum) { #ifndef JK2_MODE case FP_DRAIN: genCmdNum = GENCMD_FORCE_DRAIN; @@ -131,51 +128,48 @@ static void IN_UseGivenForce(void) break; } - if(genCmdNum) { + if (genCmdNum) { cl.gcmdSendValue = qtrue; cl.gcmdValue = genCmdNum; } } +void IN_MLookDown(void) { in_mlooking = qtrue; } -void IN_MLookDown( void ) { - in_mlooking = qtrue; -} - -void IN_CenterView( void ); -void IN_MLookUp( void ) { +void IN_CenterView(void); +void IN_MLookUp(void) { in_mlooking = qfalse; - if ( !cl_freelook->integer ) { - IN_CenterView (); + if (!cl_freelook->integer) { + IN_CenterView(); } } -void IN_KeyDown( kbutton_t *b ) { - int k; - const char *c; +void IN_KeyDown(kbutton_t *b) { + int k; + const char *c; c = Cmd_Argv(1); - if ( c[0] ) { + if (c[0]) { k = atoi(c); } else { - k = -1; // typed manually at the console for continuous down + k = -1; // typed manually at the console for continuous down } - if ( k == b->down[0] || k == b->down[1] ) { - return; // repeating key + if (k == b->down[0] || k == b->down[1]) { + return; // repeating key } - if ( !b->down[0] ) { + if (!b->down[0]) { b->down[0] = k; - } else if ( !b->down[1] ) { + } else if (!b->down[1]) { b->down[1] = k; } else { - Com_Printf ("Three keys down for a button!\n"); + Com_Printf("Three keys down for a button!\n"); return; } - if ( b->active ) { - return; // still down + if (b->active) { + return; // still down } // save timestamp for partial frame summing @@ -186,13 +180,13 @@ void IN_KeyDown( kbutton_t *b ) { b->wasPressed = qtrue; } -void IN_KeyUp( kbutton_t *b ) { - int k; - const char *c; - unsigned uptime; +void IN_KeyUp(kbutton_t *b) { + int k; + const char *c; + unsigned uptime; c = Cmd_Argv(1); - if ( c[0] ) { + if (c[0]) { k = atoi(c); } else { // typed manually at the console, assume for unsticking, so clear all @@ -201,15 +195,15 @@ void IN_KeyUp( kbutton_t *b ) { return; } - if ( b->down[0] == k ) { + if (b->down[0] == k) { b->down[0] = 0; - } else if ( b->down[1] == k ) { + } else if (b->down[1] == k) { b->down[1] = 0; } else { - return; // key up without coresponding down (menu pass through) + return; // key up without coresponding down (menu pass through) } - if ( b->down[0] || b->down[1] ) { - return; // some other key is still holding it down + if (b->down[0] || b->down[1]) { + return; // some other key is still holding it down } b->active = qfalse; @@ -217,7 +211,7 @@ void IN_KeyUp( kbutton_t *b ) { // save timestamp for partial frame summing c = Cmd_Argv(2); uptime = atoi(c); - if ( uptime ) { + if (uptime) { b->msec += uptime - b->downtime; } else { b->msec += frame_msec / 2; @@ -226,8 +220,6 @@ void IN_KeyUp( kbutton_t *b ) { b->active = qfalse; } - - /* =============== CL_KeyState @@ -235,16 +227,16 @@ CL_KeyState Returns the fraction of the frame that the key was down =============== */ -float CL_KeyState( kbutton_t *key ) { - float val; - int msec; +float CL_KeyState(kbutton_t *key) { + float val; + int msec; msec = key->msec; key->msec = 0; - if ( key->active ) { + if (key->active) { // still down - if ( !key->downtime ) { + if (!key->downtime) { msec = com_frameTime; } else { msec += com_frameTime - key->downtime; @@ -259,96 +251,89 @@ float CL_KeyState( kbutton_t *key ) { #endif val = (float)msec / frame_msec; - if ( val < 0 ) { + if (val < 0) { val = 0; } - if ( val > 1 ) { + if (val > 1) { val = 1; } return val; } - - -void IN_UpDown(void) {IN_KeyDown(&in_up);} -void IN_UpUp(void) {IN_KeyUp(&in_up);} -void IN_DownDown(void) {IN_KeyDown(&in_down);} -void IN_DownUp(void) {IN_KeyUp(&in_down);} -void IN_LeftDown(void) {IN_KeyDown(&in_left);} -void IN_LeftUp(void) {IN_KeyUp(&in_left);} -void IN_RightDown(void) {IN_KeyDown(&in_right);} -void IN_RightUp(void) {IN_KeyUp(&in_right);} -void IN_ForwardDown(void) {IN_KeyDown(&in_forward);} -void IN_ForwardUp(void) {IN_KeyUp(&in_forward);} -void IN_BackDown(void) {IN_KeyDown(&in_back);} -void IN_BackUp(void) {IN_KeyUp(&in_back);} -void IN_LookupDown(void) {IN_KeyDown(&in_lookup);} -void IN_LookupUp(void) {IN_KeyUp(&in_lookup);} -void IN_LookdownDown(void) {IN_KeyDown(&in_lookdown);} -void IN_LookdownUp(void) {IN_KeyUp(&in_lookdown);} -void IN_MoveleftDown(void) {IN_KeyDown(&in_moveleft);} -void IN_MoveleftUp(void) {IN_KeyUp(&in_moveleft);} -void IN_MoverightDown(void) {IN_KeyDown(&in_moveright);} -void IN_MoverightUp(void) {IN_KeyUp(&in_moveright);} - -void IN_SpeedDown(void) {IN_KeyDown(&in_speed);} -void IN_SpeedUp(void) {IN_KeyUp(&in_speed);} -void IN_StrafeDown(void) {IN_KeyDown(&in_strafe);} -void IN_StrafeUp(void) {IN_KeyUp(&in_strafe);} - -void IN_Button0Down(void) {IN_KeyDown(&in_buttons[0]);} -void IN_Button0Up(void) {IN_KeyUp(&in_buttons[0]);} -void IN_Button1Down(void) {IN_KeyDown(&in_buttons[1]);} -void IN_Button1Up(void) {IN_KeyUp(&in_buttons[1]);} -void IN_Button2Down(void) {IN_KeyDown(&in_buttons[2]);} -void IN_Button2Up(void) {IN_KeyUp(&in_buttons[2]);} -void IN_Button3Down(void) {IN_KeyDown(&in_buttons[3]);} -void IN_Button3Up(void) {IN_KeyUp(&in_buttons[3]);} -void IN_Button4Down(void) {IN_KeyDown(&in_buttons[4]);} -void IN_Button4Up(void) {IN_KeyUp(&in_buttons[4]);} -void IN_Button5Down(void) {IN_KeyDown(&in_buttons[5]);} -void IN_Button5Up(void) {IN_KeyUp(&in_buttons[5]);} -void IN_Button6Down(void) {IN_KeyDown(&in_buttons[6]);} -void IN_Button6Up(void) {IN_KeyUp(&in_buttons[6]);} -void IN_Button7Down(void) {IN_KeyDown(&in_buttons[7]);} -void IN_Button7Up(void) {IN_KeyUp(&in_buttons[7]);} -void IN_Button8Down(void) {IN_KeyDown(&in_buttons[8]);} -void IN_Button8Up(void) {IN_KeyUp(&in_buttons[8]);} -void IN_Button9Down(void) {IN_KeyDown(&in_buttons[9]);} -void IN_Button9Up(void) {IN_KeyUp(&in_buttons[9]);} -void IN_Button10Down(void) {IN_KeyDown(&in_buttons[10]);} -void IN_Button10Up(void) {IN_KeyUp(&in_buttons[10]);} -void IN_Button11Down(void) {IN_KeyDown(&in_buttons[11]);} -void IN_Button11Up(void) {IN_KeyUp(&in_buttons[11]);} -void IN_Button12Down(void) {IN_KeyDown(&in_buttons[12]);} -void IN_Button12Up(void) {IN_KeyUp(&in_buttons[12]);} -void IN_Button13Down(void) {IN_KeyDown(&in_buttons[13]);} -void IN_Button13Up(void) {IN_KeyUp(&in_buttons[13]);} -void IN_Button14Down(void) {IN_KeyDown(&in_buttons[14]);} -void IN_Button14Up(void) {IN_KeyUp(&in_buttons[14]);} -void IN_Button15Down(void) {IN_KeyDown(&in_buttons[15]);} -void IN_Button15Up(void) {IN_KeyUp(&in_buttons[15]);} - - -void IN_CenterView (void) { - cl.viewangles[PITCH] = -SHORT2ANGLE(cl.frame.ps.delta_angles[PITCH]); -} - +void IN_UpDown(void) { IN_KeyDown(&in_up); } +void IN_UpUp(void) { IN_KeyUp(&in_up); } +void IN_DownDown(void) { IN_KeyDown(&in_down); } +void IN_DownUp(void) { IN_KeyUp(&in_down); } +void IN_LeftDown(void) { IN_KeyDown(&in_left); } +void IN_LeftUp(void) { IN_KeyUp(&in_left); } +void IN_RightDown(void) { IN_KeyDown(&in_right); } +void IN_RightUp(void) { IN_KeyUp(&in_right); } +void IN_ForwardDown(void) { IN_KeyDown(&in_forward); } +void IN_ForwardUp(void) { IN_KeyUp(&in_forward); } +void IN_BackDown(void) { IN_KeyDown(&in_back); } +void IN_BackUp(void) { IN_KeyUp(&in_back); } +void IN_LookupDown(void) { IN_KeyDown(&in_lookup); } +void IN_LookupUp(void) { IN_KeyUp(&in_lookup); } +void IN_LookdownDown(void) { IN_KeyDown(&in_lookdown); } +void IN_LookdownUp(void) { IN_KeyUp(&in_lookdown); } +void IN_MoveleftDown(void) { IN_KeyDown(&in_moveleft); } +void IN_MoveleftUp(void) { IN_KeyUp(&in_moveleft); } +void IN_MoverightDown(void) { IN_KeyDown(&in_moveright); } +void IN_MoverightUp(void) { IN_KeyUp(&in_moveright); } + +void IN_SpeedDown(void) { IN_KeyDown(&in_speed); } +void IN_SpeedUp(void) { IN_KeyUp(&in_speed); } +void IN_StrafeDown(void) { IN_KeyDown(&in_strafe); } +void IN_StrafeUp(void) { IN_KeyUp(&in_strafe); } + +void IN_Button0Down(void) { IN_KeyDown(&in_buttons[0]); } +void IN_Button0Up(void) { IN_KeyUp(&in_buttons[0]); } +void IN_Button1Down(void) { IN_KeyDown(&in_buttons[1]); } +void IN_Button1Up(void) { IN_KeyUp(&in_buttons[1]); } +void IN_Button2Down(void) { IN_KeyDown(&in_buttons[2]); } +void IN_Button2Up(void) { IN_KeyUp(&in_buttons[2]); } +void IN_Button3Down(void) { IN_KeyDown(&in_buttons[3]); } +void IN_Button3Up(void) { IN_KeyUp(&in_buttons[3]); } +void IN_Button4Down(void) { IN_KeyDown(&in_buttons[4]); } +void IN_Button4Up(void) { IN_KeyUp(&in_buttons[4]); } +void IN_Button5Down(void) { IN_KeyDown(&in_buttons[5]); } +void IN_Button5Up(void) { IN_KeyUp(&in_buttons[5]); } +void IN_Button6Down(void) { IN_KeyDown(&in_buttons[6]); } +void IN_Button6Up(void) { IN_KeyUp(&in_buttons[6]); } +void IN_Button7Down(void) { IN_KeyDown(&in_buttons[7]); } +void IN_Button7Up(void) { IN_KeyUp(&in_buttons[7]); } +void IN_Button8Down(void) { IN_KeyDown(&in_buttons[8]); } +void IN_Button8Up(void) { IN_KeyUp(&in_buttons[8]); } +void IN_Button9Down(void) { IN_KeyDown(&in_buttons[9]); } +void IN_Button9Up(void) { IN_KeyUp(&in_buttons[9]); } +void IN_Button10Down(void) { IN_KeyDown(&in_buttons[10]); } +void IN_Button10Up(void) { IN_KeyUp(&in_buttons[10]); } +void IN_Button11Down(void) { IN_KeyDown(&in_buttons[11]); } +void IN_Button11Up(void) { IN_KeyUp(&in_buttons[11]); } +void IN_Button12Down(void) { IN_KeyDown(&in_buttons[12]); } +void IN_Button12Up(void) { IN_KeyUp(&in_buttons[12]); } +void IN_Button13Down(void) { IN_KeyDown(&in_buttons[13]); } +void IN_Button13Up(void) { IN_KeyUp(&in_buttons[13]); } +void IN_Button14Down(void) { IN_KeyDown(&in_buttons[14]); } +void IN_Button14Up(void) { IN_KeyUp(&in_buttons[14]); } +void IN_Button15Down(void) { IN_KeyDown(&in_buttons[15]); } +void IN_Button15Up(void) { IN_KeyUp(&in_buttons[15]); } + +void IN_CenterView(void) { cl.viewangles[PITCH] = -SHORT2ANGLE(cl.frame.ps.delta_angles[PITCH]); } //========================================================================== -cvar_t *cl_upspeed; -cvar_t *cl_forwardspeed; -cvar_t *cl_sidespeed; - -cvar_t *cl_yawspeed; -cvar_t *cl_pitchspeed; +cvar_t *cl_upspeed; +cvar_t *cl_forwardspeed; +cvar_t *cl_sidespeed; -cvar_t *cl_run; +cvar_t *cl_yawspeed; +cvar_t *cl_pitchspeed; -cvar_t *cl_anglespeedkey; +cvar_t *cl_run; +cvar_t *cl_anglespeedkey; /* ================ @@ -357,37 +342,31 @@ CL_AdjustAngles Moves the local angle positions ================ */ -void CL_AdjustAngles( void ) { - float speed; +void CL_AdjustAngles(void) { + float speed; - if ( in_speed.active ) { + if (in_speed.active) { speed = 0.001 * cls.frametime * cl_anglespeedkey->value; } else { speed = 0.001 * cls.frametime; } - if ( !in_strafe.active ) { - if ( cl_mYawOverride ) - { - cl.viewangles[YAW] -= cl_mYawOverride*5.0f*speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += cl_mYawOverride*5.0f*speed*cl_yawspeed->value*CL_KeyState (&in_left); - } - else - { - cl.viewangles[YAW] -= speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += speed*cl_yawspeed->value*CL_KeyState (&in_left); + if (!in_strafe.active) { + if (cl_mYawOverride) { + cl.viewangles[YAW] -= cl_mYawOverride * 5.0f * speed * cl_yawspeed->value * CL_KeyState(&in_right); + cl.viewangles[YAW] += cl_mYawOverride * 5.0f * speed * cl_yawspeed->value * CL_KeyState(&in_left); + } else { + cl.viewangles[YAW] -= speed * cl_yawspeed->value * CL_KeyState(&in_right); + cl.viewangles[YAW] += speed * cl_yawspeed->value * CL_KeyState(&in_left); } } - if ( cl_mPitchOverride ) - { - cl.viewangles[PITCH] -= cl_mPitchOverride*5.0f*speed*cl_pitchspeed->value * CL_KeyState (&in_lookup); - cl.viewangles[PITCH] += cl_mPitchOverride*5.0f*speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown); - } - else - { - cl.viewangles[PITCH] -= speed*cl_pitchspeed->value * CL_KeyState (&in_lookup); - cl.viewangles[PITCH] += speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown); + if (cl_mPitchOverride) { + cl.viewangles[PITCH] -= cl_mPitchOverride * 5.0f * speed * cl_pitchspeed->value * CL_KeyState(&in_lookup); + cl.viewangles[PITCH] += cl_mPitchOverride * 5.0f * speed * cl_pitchspeed->value * CL_KeyState(&in_lookdown); + } else { + cl.viewangles[PITCH] -= speed * cl_pitchspeed->value * CL_KeyState(&in_lookup); + cl.viewangles[PITCH] += speed * cl_pitchspeed->value * CL_KeyState(&in_lookdown); } } @@ -398,16 +377,16 @@ CL_KeyMove Sets the usercmd_t based on key states ================ */ -void CL_KeyMove( usercmd_t *cmd ) { - int movespeed; - int forward, side, up; +void CL_KeyMove(usercmd_t *cmd) { + int movespeed; + int forward, side, up; // // adjust for speed key / running // the walking flag is to keep animations consistant // even during acceleration and develeration // - if ( in_speed.active ^ cl_run->integer ) { + if (in_speed.active ^ cl_run->integer) { movespeed = 127; cmd->buttons &= ~BUTTON_WALKING; } else { @@ -418,38 +397,36 @@ void CL_KeyMove( usercmd_t *cmd ) { forward = 0; side = 0; up = 0; - if ( in_strafe.active ) { - side += movespeed * CL_KeyState (&in_right); - side -= movespeed * CL_KeyState (&in_left); + if (in_strafe.active) { + side += movespeed * CL_KeyState(&in_right); + side -= movespeed * CL_KeyState(&in_left); } - side += movespeed * CL_KeyState (&in_moveright); - side -= movespeed * CL_KeyState (&in_moveleft); - + side += movespeed * CL_KeyState(&in_moveright); + side -= movespeed * CL_KeyState(&in_moveleft); - up += movespeed * CL_KeyState (&in_up); - up -= movespeed * CL_KeyState (&in_down); + up += movespeed * CL_KeyState(&in_up); + up -= movespeed * CL_KeyState(&in_down); - forward += movespeed * CL_KeyState (&in_forward); - forward -= movespeed * CL_KeyState (&in_back); + forward += movespeed * CL_KeyState(&in_forward); + forward -= movespeed * CL_KeyState(&in_back); - cmd->forwardmove = ClampChar( forward ); - cmd->rightmove = ClampChar( side ); - cmd->upmove = ClampChar( up ); + cmd->forwardmove = ClampChar(forward); + cmd->rightmove = ClampChar(side); + cmd->upmove = ClampChar(up); } -void _UI_MouseEvent( int dx, int dy ); +void _UI_MouseEvent(int dx, int dy); /* ================= CL_MouseEvent ================= */ -void CL_MouseEvent( int dx, int dy, int time ) { - if ( Key_GetCatcher( ) & KEYCATCH_UI ) { - _UI_MouseEvent( dx, dy ); - } - else { +void CL_MouseEvent(int dx, int dy, int time) { + if (Key_GetCatcher() & KEYCATCH_UI) { + _UI_MouseEvent(dx, dy); + } else { cl.mouseDx[cl.mouseIndex] += dx; cl.mouseDy[cl.mouseIndex] += dy; } @@ -462,9 +439,9 @@ CL_JoystickEvent Joystick values stay set until changed ================= */ -void CL_JoystickEvent( int axis, int value, int time ) { - if ( axis < 0 || axis >= MAX_JOYSTICK_AXIS ) { - Com_Error( ERR_DROP, "CL_JoystickEvent: bad axis %i", axis ); +void CL_JoystickEvent(int axis, int value, int time) { + if (axis < 0 || axis >= MAX_JOYSTICK_AXIS) { + Com_Error(ERR_DROP, "CL_JoystickEvent: bad axis %i", axis); } cl.joystickAxis[axis] = value; } @@ -474,53 +451,44 @@ void CL_JoystickEvent( int axis, int value, int time ) { CL_JoystickMove ================= */ -void CL_JoystickMove( usercmd_t *cmd ) { - float anglespeed; +void CL_JoystickMove(usercmd_t *cmd) { + float anglespeed; - if ( !in_joystick->integer ) - { + if (!in_joystick->integer) { return; } - if ( !(in_speed.active ^ cl_run->integer) ) { + if (!(in_speed.active ^ cl_run->integer)) { cmd->buttons |= BUTTON_WALKING; } - if ( in_speed.active ) { + if (in_speed.active) { anglespeed = 0.001 * cls.frametime * cl_anglespeedkey->value; } else { anglespeed = 0.001 * cls.frametime; } - if ( !in_strafe.active ) { - if ( cl_mYawOverride ) - { + if (!in_strafe.active) { + if (cl_mYawOverride) { cl.viewangles[YAW] += 5.0f * cl_mYawOverride * cl.joystickAxis[AXIS_SIDE]; - } - else - { + } else { cl.viewangles[YAW] += anglespeed * (cl_yawspeed->value / 100.0f) * cl.joystickAxis[AXIS_SIDE]; } - } - else - { - cmd->rightmove = ClampChar( cmd->rightmove + cl.joystickAxis[AXIS_SIDE] ); + } else { + cmd->rightmove = ClampChar(cmd->rightmove + cl.joystickAxis[AXIS_SIDE]); } - if ( in_mlooking ) { - if ( cl_mPitchOverride ) - { + if (in_mlooking) { + if (cl_mPitchOverride) { cl.viewangles[PITCH] += 5.0f * cl_mPitchOverride * cl.joystickAxis[AXIS_FORWARD]; - } - else - { + } else { cl.viewangles[PITCH] += anglespeed * (cl_pitchspeed->value / 100.0f) * cl.joystickAxis[AXIS_FORWARD]; } } else { - cmd->forwardmove = ClampChar( cmd->forwardmove + cl.joystickAxis[AXIS_FORWARD] ); + cmd->forwardmove = ClampChar(cmd->forwardmove + cl.joystickAxis[AXIS_FORWARD]); } - cmd->upmove = ClampChar( cmd->upmove + cl.joystickAxis[AXIS_UP] ); + cmd->upmove = ClampChar(cmd->upmove + cl.joystickAxis[AXIS_UP]); } /* @@ -528,17 +496,17 @@ void CL_JoystickMove( usercmd_t *cmd ) { CL_MouseMove ================= */ -void CL_MouseMove( usercmd_t *cmd ) { - float mx, my; - float accelSensitivity; - float rate; - const float speed = static_cast(frame_msec); +void CL_MouseMove(usercmd_t *cmd) { + float mx, my; + float accelSensitivity; + float rate; + const float speed = static_cast(frame_msec); const float pitch = m_pitch->value; // allow mouse smoothing - if ( m_filter->integer ) { - mx = ( cl.mouseDx[0] + cl.mouseDx[1] ) * 0.5; - my = ( cl.mouseDy[0] + cl.mouseDy[1] ) * 0.5; + if (m_filter->integer) { + mx = (cl.mouseDx[0] + cl.mouseDx[1]) * 0.5; + my = (cl.mouseDy[0] + cl.mouseDy[1]) * 0.5; } else { mx = cl.mouseDx[cl.mouseIndex]; my = cl.mouseDy[cl.mouseIndex]; @@ -548,14 +516,14 @@ void CL_MouseMove( usercmd_t *cmd ) { cl.mouseDx[cl.mouseIndex] = 0; cl.mouseDy[cl.mouseIndex] = 0; - rate = SQRTFAST( mx * mx + my * my ) / speed; + rate = SQRTFAST(mx * mx + my * my) / speed; accelSensitivity = cl_sensitivity->value + rate * cl_mouseAccel->value; // scale by FOV accelSensitivity *= cl.cgameSensitivity; - if ( rate && cl_showMouseRate->integer ) { - Com_Printf( "%f : %f\n", rate, accelSensitivity ); + if (rate && cl_showMouseRate->integer) { + Com_Printf("%f : %f\n", rate, accelSensitivity); } mx *= accelSensitivity; @@ -566,65 +534,55 @@ void CL_MouseMove( usercmd_t *cmd ) { } // add mouse X/Y movement to cmd - if ( in_strafe.active ) { - cmd->rightmove = ClampChar( cmd->rightmove + m_side->value * mx ); + if (in_strafe.active) { + cmd->rightmove = ClampChar(cmd->rightmove + m_side->value * mx); } else { - if ( cl_mYawOverride ) - { + if (cl_mYawOverride) { cl.viewangles[YAW] -= cl_mYawOverride * mx; - } - else - { + } else { cl.viewangles[YAW] -= m_yaw->value * mx; } } - if ( (in_mlooking || cl_freelook->integer) && !in_strafe.active ) { + if ((in_mlooking || cl_freelook->integer) && !in_strafe.active) { // VVFIXME - This is supposed to be a CVAR const float cl_pitchSensitivity = 1.0f; - if ( cl_mPitchOverride ) - { - if ( pitch > 0 ) - { + if (cl_mPitchOverride) { + if (pitch > 0) { cl.viewangles[PITCH] += cl_mPitchOverride * my * cl_pitchSensitivity; - } - else - { + } else { cl.viewangles[PITCH] -= cl_mPitchOverride * my * cl_pitchSensitivity; } - } - else - { + } else { cl.viewangles[PITCH] += pitch * my * cl_pitchSensitivity; } } else { - cmd->forwardmove = ClampChar( cmd->forwardmove - m_forward->value * my ); + cmd->forwardmove = ClampChar(cmd->forwardmove - m_forward->value * my); } } - /* ============== CL_CmdButtons ============== */ -void CL_CmdButtons( usercmd_t *cmd ) { - int i; +void CL_CmdButtons(usercmd_t *cmd) { + int i; // // figure button bits // send a button bit even if the key was pressed and released in // less than a frame // - for (i = 0 ; i < 32 ; i++) { - if ( in_buttons[i].active || in_buttons[i].wasPressed ) { + for (i = 0; i < 32; i++) { + if (in_buttons[i].active || in_buttons[i].wasPressed) { cmd->buttons |= 1 << i; } in_buttons[i].wasPressed = qfalse; } - if ( Key_GetCatcher( ) ) { - //cmd->buttons |= BUTTON_TALK; + if (Key_GetCatcher()) { + // cmd->buttons |= BUTTON_TALK; } // allow the game to know if any key at all is @@ -636,25 +594,21 @@ void CL_CmdButtons( usercmd_t *cmd ) { */ } - /* ============== CL_FinishMove ============== */ -void CL_FinishMove( usercmd_t *cmd ) { - int i; +void CL_FinishMove(usercmd_t *cmd) { + int i; // copy the state that the cgame is currently sending cmd->weapon = cl.cgameUserCmdValue; - if (cl.gcmdSendValue) - { + if (cl.gcmdSendValue) { cmd->generic_cmd = cl.gcmdValue; cl.gcmdSendValue = qfalse; - } - else - { + } else { cmd->generic_cmd = 0; } @@ -662,7 +616,7 @@ void CL_FinishMove( usercmd_t *cmd ) { // can be determined without allowing cheating cmd->serverTime = cl.serverTime; - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { cmd->angles[i] = ANGLE2SHORT(cl.viewangles[i]); } } @@ -672,59 +626,57 @@ void CL_FinishMove( usercmd_t *cmd ) { CL_CreateCmd ================= */ -vec3_t cl_overriddenAngles = {0,0,0}; +vec3_t cl_overriddenAngles = {0, 0, 0}; qboolean cl_overrideAngles = qfalse; -usercmd_t CL_CreateCmd( void ) { - usercmd_t cmd; - vec3_t oldAngles; +usercmd_t CL_CreateCmd(void) { + usercmd_t cmd; + vec3_t oldAngles; - VectorCopy( cl.viewangles, oldAngles ); + VectorCopy(cl.viewangles, oldAngles); // keyboard angle adjustment - CL_AdjustAngles (); + CL_AdjustAngles(); - memset( &cmd, 0, sizeof( cmd ) ); + memset(&cmd, 0, sizeof(cmd)); - CL_CmdButtons( &cmd ); + CL_CmdButtons(&cmd); // get basic movement from keyboard - CL_KeyMove (&cmd); + CL_KeyMove(&cmd); // get basic movement from mouse - CL_MouseMove( &cmd ); + CL_MouseMove(&cmd); // get basic movement from joystick - CL_JoystickMove( &cmd ); + CL_JoystickMove(&cmd); // check to make sure the angles haven't wrapped - if ( cl.viewangles[PITCH] - oldAngles[PITCH] > 90 ) { + if (cl.viewangles[PITCH] - oldAngles[PITCH] > 90) { cl.viewangles[PITCH] = oldAngles[PITCH] + 90; - } else if ( oldAngles[PITCH] - cl.viewangles[PITCH] > 90 ) { + } else if (oldAngles[PITCH] - cl.viewangles[PITCH] > 90) { cl.viewangles[PITCH] = oldAngles[PITCH] - 90; } - if ( cl_overrideAngles ) - { - VectorCopy( cl_overriddenAngles, cl.viewangles ); + if (cl_overrideAngles) { + VectorCopy(cl_overriddenAngles, cl.viewangles); cl_overrideAngles = qfalse; } // store out the final values - CL_FinishMove( &cmd ); + CL_FinishMove(&cmd); // draw debug graphs of turning for mouse testing - if ( cl_debugMove->integer ) { - if ( cl_debugMove->integer == 1 ) { - SCR_DebugGraph( abs(cl.viewangles[YAW] - oldAngles[YAW]), 0 ); + if (cl_debugMove->integer) { + if (cl_debugMove->integer == 1) { + SCR_DebugGraph(abs(cl.viewangles[YAW] - oldAngles[YAW]), 0); } - if ( cl_debugMove->integer == 2 ) { - SCR_DebugGraph( abs(cl.viewangles[PITCH] - oldAngles[PITCH]), 0 ); + if (cl_debugMove->integer == 2) { + SCR_DebugGraph(abs(cl.viewangles[PITCH] - oldAngles[PITCH]), 0); } } return cmd; } - /* ================= CL_CreateNewCommands @@ -732,23 +684,23 @@ CL_CreateNewCommands Create a new usercmd_t structure for this frame ================= */ -void CL_CreateNewCommands( void ) { - int cmdNum; +void CL_CreateNewCommands(void) { + int cmdNum; // no need to create usercmds until we have a gamestate -// if ( cls.state < CA_PRIMED ) -// return; + // if ( cls.state < CA_PRIMED ) + // return; frame_msec = com_frameTime - old_com_frameTime; // if running over 1000fps, act as if each frame is 1ms // prevents divisions by zero - if ( frame_msec < 1 ) + if (frame_msec < 1) frame_msec = 1; // if running less than 5fps, truncate the extra time to prevent // unexpected moves after a hitch - if ( frame_msec > 200 ) + if (frame_msec > 200) frame_msec = 200; old_com_frameTime = com_frameTime; @@ -770,18 +722,16 @@ delivered in the next packet, but saving a header and getting more delta compression will reduce total bandwidth. ================= */ -qboolean CL_ReadyToSendPacket( void ) { +qboolean CL_ReadyToSendPacket(void) { // don't send anything if playing back a demo -// if ( cls.state == CA_CINEMATIC ) - if ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) - { + // if ( cls.state == CA_CINEMATIC ) + if (cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) { return qfalse; } // if we don't have a valid gamestate yet, only send // one packet a second - if ( cls.state != CA_ACTIVE && cls.state != CA_PRIMED - && cls.realtime - clc.lastPacketSentTime < 1000 ) { + if (cls.state != CA_ACTIVE && cls.state != CA_PRIMED && cls.realtime - clc.lastPacketSentTime < 1000) { return qfalse; } @@ -810,84 +760,83 @@ During normal gameplay, a client packet will contain something like: =================== */ -void CL_WritePacket( void ) { - msg_t buf; - byte data[MAX_MSGLEN]; - int i, j; - usercmd_t *cmd, *oldcmd; - usercmd_t nullcmd; - int packetNum; - int oldPacketNum; - int count; +void CL_WritePacket(void) { + msg_t buf; + byte data[MAX_MSGLEN]; + int i, j; + usercmd_t *cmd, *oldcmd; + usercmd_t nullcmd; + int packetNum; + int oldPacketNum; + int count; // don't send anything if playing back a demo -// if ( cls.state == CA_CINEMATIC ) - if ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) - { + // if ( cls.state == CA_CINEMATIC ) + if (cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) { return; } - MSG_Init( &buf, data, sizeof(data) ); + MSG_Init(&buf, data, sizeof(data)); // write any unacknowledged clientCommands - for ( i = clc.reliableAcknowledge + 1 ; i <= clc.reliableSequence ; i++ ) { - MSG_WriteByte( &buf, clc_clientCommand ); - MSG_WriteLong( &buf, i ); - MSG_WriteString( &buf, clc.reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] ); + for (i = clc.reliableAcknowledge + 1; i <= clc.reliableSequence; i++) { + MSG_WriteByte(&buf, clc_clientCommand); + MSG_WriteLong(&buf, i); + MSG_WriteString(&buf, clc.reliableCommands[i & (MAX_RELIABLE_COMMANDS - 1)]); } // we want to send all the usercmds that were generated in the last // few packet, so even if a couple packets are dropped in a row, // all the cmds will make it to the server - if ( cl_packetdup->integer < 0 ) { - Cvar_Set( "cl_packetdup", "0" ); - } else if ( cl_packetdup->integer > 5 ) { - Cvar_Set( "cl_packetdup", "5" ); + if (cl_packetdup->integer < 0) { + Cvar_Set("cl_packetdup", "0"); + } else if (cl_packetdup->integer > 5) { + Cvar_Set("cl_packetdup", "5"); } oldPacketNum = (clc.netchan.outgoingSequence - 1 - cl_packetdup->integer) & PACKET_MASK; - count = cl.cmdNumber - cl.packetCmdNumber[ oldPacketNum ]; - if ( count > MAX_PACKET_USERCMDS ) { + count = cl.cmdNumber - cl.packetCmdNumber[oldPacketNum]; + if (count > MAX_PACKET_USERCMDS) { count = MAX_PACKET_USERCMDS; Com_Printf("MAX_PACKET_USERCMDS\n"); } - if ( count >= 1 ) { + if (count >= 1) { // begin a client move command - MSG_WriteByte (&buf, clc_move); + MSG_WriteByte(&buf, clc_move); // write the last reliable message we received - MSG_WriteLong( &buf, clc.serverCommandSequence ); + MSG_WriteLong(&buf, clc.serverCommandSequence); // write the current serverId so the server // can tell if this is from the current gameState - MSG_WriteLong (&buf, cl.serverId); + MSG_WriteLong(&buf, cl.serverId); // write the current time - MSG_WriteLong (&buf, cls.realtime); + MSG_WriteLong(&buf, cls.realtime); // let the server know what the last messagenum we // got was, so the next message can be delta compressed // FIXME: this could just be a bit flag, with the message implicit // from the unreliable ack of the netchan if (cl_nodelta->integer || !cl.frame.valid) { - MSG_WriteLong (&buf, -1); // no compression + MSG_WriteLong(&buf, -1); // no compression } else { - MSG_WriteLong (&buf, cl.frame.messageNum); + MSG_WriteLong(&buf, cl.frame.messageNum); } // write the cmdNumber so the server can determine which ones it // has already received - MSG_WriteLong( &buf, cl.cmdNumber ); + MSG_WriteLong(&buf, cl.cmdNumber); // write the command count - MSG_WriteByte( &buf, count ); + MSG_WriteByte(&buf, count); // write all the commands, including the predicted command - memset( &nullcmd, 0, sizeof(nullcmd) ); + memset(&nullcmd, 0, sizeof(nullcmd)); oldcmd = &nullcmd; - for ( i = 0 ; i < count ; i++ ) { + for (i = 0; i < count; i++) { j = (cl.cmdNumber - count + i + 1) & CMD_MASK; cmd = &cl.cmds[j]; - MSG_WriteDeltaUsercmd (&buf, oldcmd, cmd); + MSG_WriteDeltaUsercmd(&buf, oldcmd, cmd); oldcmd = cmd; } } @@ -896,10 +845,10 @@ void CL_WritePacket( void ) { // deliver the message // packetNum = clc.netchan.outgoingSequence & PACKET_MASK; - cl.packetTime[ packetNum ] = cls.realtime; - cl.packetCmdNumber[ packetNum ] = cl.cmdNumber; + cl.packetTime[packetNum] = cls.realtime; + cl.packetCmdNumber[packetNum] = cl.cmdNumber; clc.lastPacketSentTime = cls.realtime; - Netchan_Transmit (&clc.netchan, buf.cursize, buf.data); + Netchan_Transmit(&clc.netchan, buf.cursize, buf.data); } /* @@ -909,14 +858,14 @@ CL_SendCmd Called every frame to builds and sends a command packet to the server. ================= */ -void CL_SendCmd( void ) { +void CL_SendCmd(void) { // don't send any message if not connected - if ( cls.state < CA_CONNECTED ) { + if (cls.state < CA_CONNECTED) { return; } // don't send commands if paused - if ( com_sv_running->integer && sv_paused->integer && cl_paused->integer ) { + if (com_sv_running->integer && sv_paused->integer && cl_paused->integer) { return; } @@ -924,116 +873,114 @@ void CL_SendCmd( void ) { CL_CreateNewCommands(); // don't send a packet if the last packet was sent too recently - if ( !CL_ReadyToSendPacket() ) { + if (!CL_ReadyToSendPacket()) { return; } CL_WritePacket(); } - /* ============ CL_InitInput ============ */ -void CL_InitInput( void ) { - Cmd_AddCommand ("centerview",IN_CenterView); - - Cmd_AddCommand ("+moveup",IN_UpDown); - Cmd_AddCommand ("-moveup",IN_UpUp); - Cmd_AddCommand ("+movedown",IN_DownDown); - Cmd_AddCommand ("-movedown",IN_DownUp); - Cmd_AddCommand ("+left",IN_LeftDown); - Cmd_AddCommand ("-left",IN_LeftUp); - Cmd_AddCommand ("+right",IN_RightDown); - Cmd_AddCommand ("-right",IN_RightUp); - Cmd_AddCommand ("+forward",IN_ForwardDown); - Cmd_AddCommand ("-forward",IN_ForwardUp); - Cmd_AddCommand ("+back",IN_BackDown); - Cmd_AddCommand ("-back",IN_BackUp); - Cmd_AddCommand ("+lookup", IN_LookupDown); - Cmd_AddCommand ("-lookup", IN_LookupUp); - Cmd_AddCommand ("+lookdown", IN_LookdownDown); - Cmd_AddCommand ("-lookdown", IN_LookdownUp); - Cmd_AddCommand ("+strafe", IN_StrafeDown); - Cmd_AddCommand ("-strafe", IN_StrafeUp); - Cmd_AddCommand ("+moveleft", IN_MoveleftDown); - Cmd_AddCommand ("-moveleft", IN_MoveleftUp); - Cmd_AddCommand ("+moveright", IN_MoverightDown); - Cmd_AddCommand ("-moveright", IN_MoverightUp); - Cmd_AddCommand ("+speed", IN_SpeedDown); - Cmd_AddCommand ("-speed", IN_SpeedUp); - Cmd_AddCommand ("useGivenForce", IN_UseGivenForce); - //buttons - Cmd_AddCommand ("+attack", IN_Button0Down);//attack - Cmd_AddCommand ("-attack", IN_Button0Up); - Cmd_AddCommand ("+force_lightning", IN_Button1Down);//force lightning - Cmd_AddCommand ("-force_lightning", IN_Button1Up); - Cmd_AddCommand ("+useforce", IN_Button2Down); //use current force power - Cmd_AddCommand ("-useforce", IN_Button2Up); +void CL_InitInput(void) { + Cmd_AddCommand("centerview", IN_CenterView); + + Cmd_AddCommand("+moveup", IN_UpDown); + Cmd_AddCommand("-moveup", IN_UpUp); + Cmd_AddCommand("+movedown", IN_DownDown); + Cmd_AddCommand("-movedown", IN_DownUp); + Cmd_AddCommand("+left", IN_LeftDown); + Cmd_AddCommand("-left", IN_LeftUp); + Cmd_AddCommand("+right", IN_RightDown); + Cmd_AddCommand("-right", IN_RightUp); + Cmd_AddCommand("+forward", IN_ForwardDown); + Cmd_AddCommand("-forward", IN_ForwardUp); + Cmd_AddCommand("+back", IN_BackDown); + Cmd_AddCommand("-back", IN_BackUp); + Cmd_AddCommand("+lookup", IN_LookupDown); + Cmd_AddCommand("-lookup", IN_LookupUp); + Cmd_AddCommand("+lookdown", IN_LookdownDown); + Cmd_AddCommand("-lookdown", IN_LookdownUp); + Cmd_AddCommand("+strafe", IN_StrafeDown); + Cmd_AddCommand("-strafe", IN_StrafeUp); + Cmd_AddCommand("+moveleft", IN_MoveleftDown); + Cmd_AddCommand("-moveleft", IN_MoveleftUp); + Cmd_AddCommand("+moveright", IN_MoverightDown); + Cmd_AddCommand("-moveright", IN_MoverightUp); + Cmd_AddCommand("+speed", IN_SpeedDown); + Cmd_AddCommand("-speed", IN_SpeedUp); + Cmd_AddCommand("useGivenForce", IN_UseGivenForce); + // buttons + Cmd_AddCommand("+attack", IN_Button0Down); // attack + Cmd_AddCommand("-attack", IN_Button0Up); + Cmd_AddCommand("+force_lightning", IN_Button1Down); // force lightning + Cmd_AddCommand("-force_lightning", IN_Button1Up); + Cmd_AddCommand("+useforce", IN_Button2Down); // use current force power + Cmd_AddCommand("-useforce", IN_Button2Up); #ifdef JK2_MODE - Cmd_AddCommand ("+block", IN_Button3Down);//manual blocking - Cmd_AddCommand ("-block", IN_Button3Up); + Cmd_AddCommand("+block", IN_Button3Down); // manual blocking + Cmd_AddCommand("-block", IN_Button3Up); #else - Cmd_AddCommand ("+force_drain", IN_Button3Down);//force drain - Cmd_AddCommand ("-force_drain", IN_Button3Up); + Cmd_AddCommand("+force_drain", IN_Button3Down); // force drain + Cmd_AddCommand("-force_drain", IN_Button3Up); #endif - Cmd_AddCommand ("+walk", IN_Button4Down);//walking - Cmd_AddCommand ("-walk", IN_Button4Up); - Cmd_AddCommand ("+use", IN_Button5Down);//use object - Cmd_AddCommand ("-use", IN_Button5Up); - Cmd_AddCommand ("+force_grip", IN_Button6Down);//force jump - Cmd_AddCommand ("-force_grip", IN_Button6Up); - Cmd_AddCommand ("+altattack", IN_Button7Down);//altattack - Cmd_AddCommand ("-altattack", IN_Button7Up); + Cmd_AddCommand("+walk", IN_Button4Down); // walking + Cmd_AddCommand("-walk", IN_Button4Up); + Cmd_AddCommand("+use", IN_Button5Down); // use object + Cmd_AddCommand("-use", IN_Button5Up); + Cmd_AddCommand("+force_grip", IN_Button6Down); // force jump + Cmd_AddCommand("-force_grip", IN_Button6Up); + Cmd_AddCommand("+altattack", IN_Button7Down); // altattack + Cmd_AddCommand("-altattack", IN_Button7Up); #ifndef JK2_MODE - Cmd_AddCommand ("+forcefocus", IN_Button8Down);//special saber attacks - Cmd_AddCommand ("-forcefocus", IN_Button8Up); - Cmd_AddCommand ("+block", IN_Button8Down);//manual blocking - Cmd_AddCommand ("-block", IN_Button8Up); + Cmd_AddCommand("+forcefocus", IN_Button8Down); // special saber attacks + Cmd_AddCommand("-forcefocus", IN_Button8Up); + Cmd_AddCommand("+block", IN_Button8Down); // manual blocking + Cmd_AddCommand("-block", IN_Button8Up); #endif - Cmd_AddCommand ("+button0", IN_Button0Down); - Cmd_AddCommand ("-button0", IN_Button0Up); - Cmd_AddCommand ("+button1", IN_Button1Down); - Cmd_AddCommand ("-button1", IN_Button1Up); - Cmd_AddCommand ("+button2", IN_Button2Down); - Cmd_AddCommand ("-button2", IN_Button2Up); - Cmd_AddCommand ("+button3", IN_Button3Down); - Cmd_AddCommand ("-button3", IN_Button3Up); - Cmd_AddCommand ("+button4", IN_Button4Down); - Cmd_AddCommand ("-button4", IN_Button4Up); - Cmd_AddCommand ("+button5", IN_Button5Down); - Cmd_AddCommand ("-button5", IN_Button5Up); - Cmd_AddCommand ("+button6", IN_Button6Down); - Cmd_AddCommand ("-button6", IN_Button6Up); - Cmd_AddCommand ("+button7", IN_Button7Down); - Cmd_AddCommand ("-button7", IN_Button7Up); - Cmd_AddCommand ("+button8", IN_Button8Down); - Cmd_AddCommand ("-button8", IN_Button8Up); - Cmd_AddCommand ("+button9", IN_Button9Down); - Cmd_AddCommand ("-button9", IN_Button9Up); - Cmd_AddCommand ("+button10", IN_Button10Down); - Cmd_AddCommand ("-button10", IN_Button10Up); - Cmd_AddCommand ("+button11", IN_Button11Down); - Cmd_AddCommand ("-button11", IN_Button11Up); - Cmd_AddCommand ("+button12", IN_Button12Down); - Cmd_AddCommand ("-button12", IN_Button12Up); - Cmd_AddCommand ("+button13", IN_Button13Down); - Cmd_AddCommand ("-button13", IN_Button13Up); - Cmd_AddCommand ("+button14", IN_Button14Down); - Cmd_AddCommand ("-button14", IN_Button14Up); - Cmd_AddCommand ("+button15", IN_Button15Down); - Cmd_AddCommand ("-button15", IN_Button15Up); + Cmd_AddCommand("+button0", IN_Button0Down); + Cmd_AddCommand("-button0", IN_Button0Up); + Cmd_AddCommand("+button1", IN_Button1Down); + Cmd_AddCommand("-button1", IN_Button1Up); + Cmd_AddCommand("+button2", IN_Button2Down); + Cmd_AddCommand("-button2", IN_Button2Up); + Cmd_AddCommand("+button3", IN_Button3Down); + Cmd_AddCommand("-button3", IN_Button3Up); + Cmd_AddCommand("+button4", IN_Button4Down); + Cmd_AddCommand("-button4", IN_Button4Up); + Cmd_AddCommand("+button5", IN_Button5Down); + Cmd_AddCommand("-button5", IN_Button5Up); + Cmd_AddCommand("+button6", IN_Button6Down); + Cmd_AddCommand("-button6", IN_Button6Up); + Cmd_AddCommand("+button7", IN_Button7Down); + Cmd_AddCommand("-button7", IN_Button7Up); + Cmd_AddCommand("+button8", IN_Button8Down); + Cmd_AddCommand("-button8", IN_Button8Up); + Cmd_AddCommand("+button9", IN_Button9Down); + Cmd_AddCommand("-button9", IN_Button9Up); + Cmd_AddCommand("+button10", IN_Button10Down); + Cmd_AddCommand("-button10", IN_Button10Up); + Cmd_AddCommand("+button11", IN_Button11Down); + Cmd_AddCommand("-button11", IN_Button11Up); + Cmd_AddCommand("+button12", IN_Button12Down); + Cmd_AddCommand("-button12", IN_Button12Up); + Cmd_AddCommand("+button13", IN_Button13Down); + Cmd_AddCommand("-button13", IN_Button13Up); + Cmd_AddCommand("+button14", IN_Button14Down); + Cmd_AddCommand("-button14", IN_Button14Up); + Cmd_AddCommand("+button15", IN_Button15Down); + Cmd_AddCommand("-button15", IN_Button15Up); // can add up to button31 this just brings the number of available binds up to par with MP - //end buttons - Cmd_AddCommand ("+mlook", IN_MLookDown); - Cmd_AddCommand ("-mlook", IN_MLookUp); + // end buttons + Cmd_AddCommand("+mlook", IN_MLookDown); + Cmd_AddCommand("-mlook", IN_MLookUp); - cl_nodelta = Cvar_Get ("cl_nodelta", "0", 0); - cl_debugMove = Cvar_Get ("cl_debugMove", "0", 0); + cl_nodelta = Cvar_Get("cl_nodelta", "0", 0); + cl_debugMove = Cvar_Get("cl_debugMove", "0", 0); } - diff --git a/code/client/cl_keys.cpp b/code/client/cl_keys.cpp index 768c135937..83c80fbfc9 100644 --- a/code/client/cl_keys.cpp +++ b/code/client/cl_keys.cpp @@ -24,7 +24,6 @@ along with this program; if not, see . #include "../server/exe_headers.h" - #include "client.h" #include "client_ui.h" @@ -35,351 +34,346 @@ key up events are sent even if in console mode */ // console -field_t g_consoleField; -int nextHistoryLine; // the last line in the history buffer, not masked -int historyLine; // the line being displayed from history buffer will be <= nextHistoryLine -field_t historyEditLines[COMMAND_HISTORY]; +field_t g_consoleField; +int nextHistoryLine; // the last line in the history buffer, not masked +int historyLine; // the line being displayed from history buffer will be <= nextHistoryLine +field_t historyEditLines[COMMAND_HISTORY]; -keyGlobals_t kg; +keyGlobals_t kg; // do NOT blithely change any of the key names (3rd field) here, since they have to match the key binds // in the CFG files, they're also prepended with "KEYNAME_" when looking up StripEd references // -keyname_t keynames[MAX_KEYS] = -{ - { 0x00, 0x00, NULL, A_NULL, false }, - { 0x01, 0x01, "SHIFT", A_SHIFT, false }, - { 0x02, 0x02, "CTRL", A_CTRL, false }, - { 0x03, 0x03, "ALT", A_ALT, false }, - { 0x04, 0x04, "CAPSLOCK", A_CAPSLOCK, false }, - { 0x05, 0x05, "KP_NUMLOCK", A_NUMLOCK, false }, - { 0x06, 0x06, "SCROLLLOCK", A_SCROLLLOCK, false }, - { 0x07, 0x07, "PAUSE", A_PAUSE, false }, - { 0x08, 0x08, "BACKSPACE", A_BACKSPACE, false }, - { 0x09, 0x09, "TAB", A_TAB, false }, - { 0x0a, 0x0a, "ENTER", A_ENTER, false }, - { 0x0b, 0x0b, "KP_PLUS", A_KP_PLUS, false }, - { 0x0c, 0x0c, "KP_MINUS", A_KP_MINUS, false }, - { 0x0d, 0x0d, "KP_ENTER", A_KP_ENTER, false }, - { 0x0e, 0x0e, "KP_DEL", A_KP_PERIOD, false }, - { 0x0f, 0x0f, NULL, A_PRINTSCREEN, false }, - { 0x10, 0x10, "KP_INS", A_KP_0, false }, - { 0x11, 0x11, "KP_END", A_KP_1, false }, - { 0x12, 0x12, "KP_DOWNARROW", A_KP_2, false }, - { 0x13, 0x13, "KP_PGDN", A_KP_3, false }, - { 0x14, 0x14, "KP_LEFTARROW", A_KP_4, false }, - { 0x15, 0x15, "KP_5", A_KP_5, false }, - { 0x16, 0x16, "KP_RIGHTARROW", A_KP_6, false }, - { 0x17, 0x17, "KP_HOME", A_KP_7, false }, - { 0x18, 0x18, "KP_UPARROW", A_KP_8, false }, - { 0x19, 0x19, "KP_PGUP", A_KP_9, false }, - { 0x1a, 0x1a, "CONSOLE", A_CONSOLE, false }, - { 0x1b, 0x1b, "ESCAPE", A_ESCAPE, false }, - { 0x1c, 0x1c, "F1", A_F1, true }, - { 0x1d, 0x1d, "F2", A_F2, true }, - { 0x1e, 0x1e, "F3", A_F3, true }, - { 0x1f, 0x1f, "F4", A_F4, true }, - - { 0x20, 0x20, "SPACE", A_SPACE, false }, - { (word)'!', (word)'!', NULL, A_PLING, false }, - { (word)'"', (word)'"', NULL, A_DOUBLE_QUOTE, false }, - { (word)'#', (word)'#', NULL, A_HASH, false }, - { (word)'$', (word)'$', NULL, A_STRING, false }, - { (word)'%', (word)'%', NULL, A_PERCENT, false }, - { (word)'&', (word)'&', NULL, A_AND, false }, - { 0x27, 0x27, NULL, A_SINGLE_QUOTE, false }, - { (word)'(', (word)'(', NULL, A_OPEN_BRACKET, false }, - { (word)')', (word)')', NULL, A_CLOSE_BRACKET, false }, - { (word)'*', (word)'*', NULL, A_STAR, false }, - { (word)'+', (word)'+', NULL, A_PLUS, false }, - { (word)',', (word)',', NULL, A_COMMA, false }, - { (word)'-', (word)'-', NULL, A_MINUS, false }, - { (word)'.', (word)'.', NULL, A_PERIOD, false }, - { (word)'/', (word)'/', NULL, A_FORWARD_SLASH, false }, - { (word)'0', (word)'0', NULL, A_0, false }, - { (word)'1', (word)'1', NULL, A_1, false }, - { (word)'2', (word)'2', NULL, A_2, false }, - { (word)'3', (word)'3', NULL, A_3, false }, - { (word)'4', (word)'4', NULL, A_4, false }, - { (word)'5', (word)'5', NULL, A_5, false }, - { (word)'6', (word)'6', NULL, A_6, false }, - { (word)'7', (word)'7', NULL, A_7, false }, - { (word)'8', (word)'8', NULL, A_8, false }, - { (word)'9', (word)'9', NULL, A_9, false }, - { (word)':', (word)':', NULL, A_COLON, false }, - { (word)';', (word)';', "SEMICOLON", A_SEMICOLON, false }, - { (word)'<', (word)'<', NULL, A_LESSTHAN, false }, - { (word)'=', (word)'=', NULL, A_EQUALS, false }, - { (word)'>', (word)'>', NULL, A_GREATERTHAN, false }, - { (word)'?', (word)'?', NULL, A_QUESTION, false }, - - { (word)'@', (word)'@', NULL, A_AT, false }, - { (word)'A', (word)'a', NULL, A_CAP_A, false }, - { (word)'B', (word)'b', NULL, A_CAP_B, false }, - { (word)'C', (word)'c', NULL, A_CAP_C, false }, - { (word)'D', (word)'d', NULL, A_CAP_D, false }, - { (word)'E', (word)'e', NULL, A_CAP_E, false }, - { (word)'F', (word)'f', NULL, A_CAP_F, false }, - { (word)'G', (word)'g', NULL, A_CAP_G, false }, - { (word)'H', (word)'h', NULL, A_CAP_H, false }, - { (word)'I', (word)'i', NULL, A_CAP_I, false }, - { (word)'J', (word)'j', NULL, A_CAP_J, false }, - { (word)'K', (word)'k', NULL, A_CAP_K, false }, - { (word)'L', (word)'l', NULL, A_CAP_L, false }, - { (word)'M', (word)'m', NULL, A_CAP_M, false }, - { (word)'N', (word)'n', NULL, A_CAP_N, false }, - { (word)'O', (word)'o', NULL, A_CAP_O, false }, - { (word)'P', (word)'p', NULL, A_CAP_P, false }, - { (word)'Q', (word)'q', NULL, A_CAP_Q, false }, - { (word)'R', (word)'r', NULL, A_CAP_R, false }, - { (word)'S', (word)'s', NULL, A_CAP_S, false }, - { (word)'T', (word)'t', NULL, A_CAP_T, false }, - { (word)'U', (word)'u', NULL, A_CAP_U, false }, - { (word)'V', (word)'v', NULL, A_CAP_V, false }, - { (word)'W', (word)'w', NULL, A_CAP_W, false }, - { (word)'X', (word)'x', NULL, A_CAP_X, false }, - { (word)'Y', (word)'y', NULL, A_CAP_Y, false }, - { (word)'Z', (word)'z', NULL, A_CAP_Z, false }, - { (word)'[', (word)'[', NULL, A_OPEN_SQUARE, false }, - { 0x5c, 0x5c, NULL, A_BACKSLASH, false }, - { (word)']', (word)']', NULL, A_CLOSE_SQUARE, false }, - { (word)'^', (word)'^', NULL, A_CARET, false }, - { (word)'_', (word)'_', NULL, A_UNDERSCORE, false }, - - { 0x60, 0x60, NULL, A_LEFT_SINGLE_QUOTE, false }, - { (word)'A', (word)'a', NULL, A_LOW_A, false }, - { (word)'B', (word)'b', NULL, A_LOW_B, false }, - { (word)'C', (word)'c', NULL, A_LOW_C, false }, - { (word)'D', (word)'d', NULL, A_LOW_D, false }, - { (word)'E', (word)'e', NULL, A_LOW_E, false }, - { (word)'F', (word)'f', NULL, A_LOW_F, false }, - { (word)'G', (word)'g', NULL, A_LOW_G, false }, - { (word)'H', (word)'h', NULL, A_LOW_H, false }, - { (word)'I', (word)'i', NULL, A_LOW_I, false }, - { (word)'J', (word)'j', NULL, A_LOW_J, false }, - { (word)'K', (word)'k', NULL, A_LOW_K, false }, - { (word)'L', (word)'l', NULL, A_LOW_L, false }, - { (word)'M', (word)'m', NULL, A_LOW_M, false }, - { (word)'N', (word)'n', NULL, A_LOW_N, false }, - { (word)'O', (word)'o', NULL, A_LOW_O, false }, - { (word)'P', (word)'p', NULL, A_LOW_P, false }, - { (word)'Q', (word)'q', NULL, A_LOW_Q, false }, - { (word)'R', (word)'r', NULL, A_LOW_R, false }, - { (word)'S', (word)'s', NULL, A_LOW_S, false }, - { (word)'T', (word)'t', NULL, A_LOW_T, false }, - { (word)'U', (word)'u', NULL, A_LOW_U, false }, - { (word)'V', (word)'v', NULL, A_LOW_V, false }, - { (word)'W', (word)'w', NULL, A_LOW_W, false }, - { (word)'X', (word)'x', NULL, A_LOW_X, false }, - { (word)'Y', (word)'y', NULL, A_LOW_Y, false }, - { (word)'Z', (word)'z', NULL, A_LOW_Z, false }, - { (word)'{', (word)'{', NULL, A_OPEN_BRACE, false }, - { (word)'|', (word)'|', NULL, A_BAR, false }, - { (word)'}', (word)'}', NULL, A_CLOSE_BRACE, false }, - { (word)'~', (word)'~', NULL, A_TILDE, false }, - { 0x7f, 0x7f, "DEL", A_DELETE, false }, - - { 0x80, 0x80, "EURO", A_EURO, false }, - { 0x81, 0x81, "SHIFT", A_SHIFT2, false }, - { 0x82, 0x82, "CTRL", A_CTRL2, false }, - { 0x83, 0x83, "ALT", A_ALT2, false }, - { 0x84, 0x84, "F5", A_F5, true }, - { 0x85, 0x85, "F6", A_F6, true }, - { 0x86, 0x86, "F7", A_F7, true }, - { 0x87, 0x87, "F8", A_F8, true }, - { 0x88, 0x88, "CIRCUMFLEX", A_CIRCUMFLEX, false }, - { 0x89, 0x89, "MWHEELUP", A_MWHEELUP, false }, - { 0x8a, 0x9a, NULL, A_CAP_SCARON, false }, // ****** - { 0x8b, 0x8b, "MWHEELDOWN", A_MWHEELDOWN, false }, - { 0x8c, 0x9c, NULL, A_CAP_OE, false }, // ****** - { 0x8d, 0x8d, "MOUSE1", A_MOUSE1, false }, - { 0x8e, 0x8e, "MOUSE2", A_MOUSE2, false }, - { 0x8f, 0x8f, "INS", A_INSERT, false }, - { 0x90, 0x90, "HOME", A_HOME, false }, - { 0x91, 0x91, "PGUP", A_PAGE_UP, false }, - { 0x92, 0x92, NULL, A_RIGHT_SINGLE_QUOTE, false }, - { 0x93, 0x93, NULL, A_LEFT_DOUBLE_QUOTE, false }, - { 0x94, 0x94, NULL, A_RIGHT_DOUBLE_QUOTE, false }, - { 0x95, 0x95, "F9", A_F9, true }, - { 0x96, 0x96, "F10", A_F10, true }, - { 0x97, 0x97, "F11", A_F11, true }, - { 0x98, 0x98, "F12", A_F12, true }, - { 0x99, 0x99, NULL, A_TRADEMARK, false }, - { 0x8a, 0x9a, NULL, A_LOW_SCARON, false }, // ****** - { 0x9b, 0x9b, "SHIFT_ENTER", A_ENTER, false }, - { 0x8c, 0x9c, NULL, A_LOW_OE, false }, // ****** - { 0x9d, 0x9d, "END", A_END, false }, - { 0x9e, 0x9e, "PGDN", A_PAGE_DOWN, false }, - { 0x9f, 0xff, NULL, A_CAP_YDIERESIS, false }, // ****** - - { 0xa0, 0, "SHIFT_SPACE", A_SPACE, false }, - { 0xa1, 0xa1, NULL, A_EXCLAMDOWN, false }, // upside down '!' - undisplayable - { L'\u00A2', L'\u00A2', NULL, A_CENT, false }, // cent sign - { L'\u00A3', L'\u00A3', NULL, A_POUND, false }, // pound (as in currency) symbol - { 0xa4, 0, "SHIFT_KP_ENTER", A_KP_ENTER, false }, - { L'\u00A5', L'\u00A5', NULL, A_YEN, false }, // yen symbol - { 0xa6, 0xa6, "MOUSE3", A_MOUSE3, false }, - { 0xa7, 0xa7, "MOUSE4", A_MOUSE4, false }, - { 0xa8, 0xa8, "MOUSE5", A_MOUSE5, false }, - { L'\u00A9', L'\u00A9', NULL, A_COPYRIGHT, false }, // copyright symbol - { 0xaa, 0xaa, "UPARROW", A_CURSOR_UP, false }, - { 0xab, 0xab, "DOWNARROW", A_CURSOR_DOWN, false }, - { 0xac, 0xac, "LEFTARROW", A_CURSOR_LEFT, false }, - { 0xad, 0xad, "RIGHTARROW", A_CURSOR_RIGHT, false }, - { L'\u00AE', L'\u00AE', NULL, A_REGISTERED, false }, // registered trademark symbol - { 0xaf, 0, NULL, A_UNDEFINED_7, false }, - { 0xb0, 0, NULL, A_UNDEFINED_8, false }, - { 0xb1, 0, NULL, A_UNDEFINED_9, false }, - { 0xb2, 0, NULL, A_UNDEFINED_10, false }, - { 0xb3, 0, NULL, A_UNDEFINED_11, false }, - { 0xb4, 0, NULL, A_UNDEFINED_12, false }, - { 0xb5, 0, NULL, A_UNDEFINED_13, false }, - { 0xb6, 0, NULL, A_UNDEFINED_14, false }, - { 0xb7, 0, NULL, A_UNDEFINED_15, false }, - { 0xb8, 0, NULL, A_UNDEFINED_16, false }, - { 0xb9, 0, NULL, A_UNDEFINED_17, false }, - { 0xba, 0, NULL, A_UNDEFINED_18, false }, - { 0xbb, 0, NULL, A_UNDEFINED_19, false }, - { 0xbc, 0, NULL, A_UNDEFINED_20, false }, - { 0xbd, 0, NULL, A_UNDEFINED_21, false }, - { 0xbe, 0, NULL, A_UNDEFINED_22, false }, - { L'\u00BF', L'\u00BF', NULL, A_QUESTION_DOWN, false }, // upside-down question mark - - { L'\u00C0', L'\u00E0', NULL, A_CAP_AGRAVE, false }, - { L'\u00C1', L'\u00E1', NULL, A_CAP_AACUTE, false }, - { L'\u00C2', L'\u00E2', NULL, A_CAP_ACIRCUMFLEX, false }, - { L'\u00C3', L'\u00E3', NULL, A_CAP_ATILDE, false }, - { L'\u00C4', L'\u00E4', NULL, A_CAP_ADIERESIS, false }, - { L'\u00C5', L'\u00E5', NULL, A_CAP_ARING, false }, - { L'\u00C6', L'\u00E6', NULL, A_CAP_AE, false }, - { L'\u00C7', L'\u00E7', NULL, A_CAP_CCEDILLA, false }, - { L'\u00C8', L'\u00E8', NULL, A_CAP_EGRAVE, false }, - { L'\u00C9', L'\u00E9', NULL, A_CAP_EACUTE, false }, - { L'\u00CA', L'\u00EA', NULL, A_CAP_ECIRCUMFLEX, false }, - { L'\u00CB', L'\u00EB', NULL, A_CAP_EDIERESIS, false }, - { L'\u00CC', L'\u00EC', NULL, A_CAP_IGRAVE, false }, - { L'\u00CD', L'\u00ED', NULL, A_CAP_IACUTE, false }, - { L'\u00CE', L'\u00EE', NULL, A_CAP_ICIRCUMFLEX, false }, - { L'\u00CF', L'\u00EF', NULL, A_CAP_IDIERESIS, false }, - { L'\u00D0', L'\u00F0', NULL, A_CAP_ETH, false }, - { L'\u00D1', L'\u00F1', NULL, A_CAP_NTILDE, false }, - { L'\u00D2', L'\u00F2', NULL, A_CAP_OGRAVE, false }, - { L'\u00D3', L'\u00F3', NULL, A_CAP_OACUTE, false }, - { L'\u00D4', L'\u00F4', NULL, A_CAP_OCIRCUMFLEX, false }, - { L'\u00D5', L'\u00F5', NULL, A_CAP_OTILDE, false }, - { L'\u00D6', L'\u00F6', NULL, A_CAP_ODIERESIS, false }, - { L'\u00D7', L'\u00D7', "KP_STAR", A_MULTIPLY, false }, - { L'\u00D8', L'\u00F8', NULL, A_CAP_OSLASH, false }, - { L'\u00D9', L'\u00F9', NULL, A_CAP_UGRAVE, false }, - { L'\u00DA', L'\u00FA', NULL, A_CAP_UACUTE, false }, - { L'\u00DB', L'\u00FB', NULL, A_CAP_UCIRCUMFLEX, false }, - { L'\u00DC', L'\u00FC', NULL, A_CAP_UDIERESIS, false }, - { L'\u00DD', L'\u00FD', NULL, A_CAP_YACUTE, false }, - { L'\u00DE', L'\u00FE', NULL, A_CAP_THORN, false }, - { L'\u00DF', L'\u00DF', NULL, A_GERMANDBLS, false }, - - { L'\u00C0', L'\u00E0', NULL, A_LOW_AGRAVE, false }, - { L'\u00C1', L'\u00E1', NULL, A_LOW_AACUTE, false }, - { L'\u00C2', L'\u00E2', NULL, A_LOW_ACIRCUMFLEX, false }, - { L'\u00C3', L'\u00E3', NULL, A_LOW_ATILDE, false }, - { L'\u00C4', L'\u00E4', NULL, A_LOW_ADIERESIS, false }, - { L'\u00C5', L'\u00E5', NULL, A_LOW_ARING, false }, - { L'\u00C6', L'\u00E6', NULL, A_LOW_AE, false }, - { L'\u00C7', L'\u00E7', NULL, A_LOW_CCEDILLA, false }, - { L'\u00C8', L'\u00E8', NULL, A_LOW_EGRAVE, false }, - { L'\u00C9', L'\u00E9', NULL, A_LOW_EACUTE, false }, - { L'\u00CA', L'\u00EA', NULL, A_LOW_ECIRCUMFLEX, false }, - { L'\u00CB', L'\u00EB', NULL, A_LOW_EDIERESIS, false }, - { L'\u00CC', L'\u00EC', NULL, A_LOW_IGRAVE, false }, - { L'\u00CD', L'\u00ED', NULL, A_LOW_IACUTE, false }, - { L'\u00CE', L'\u00EE', NULL, A_LOW_ICIRCUMFLEX, false }, - { L'\u00CF', L'\u00EF', NULL, A_LOW_IDIERESIS, false }, - { L'\u00D0', L'\u00F0', NULL, A_LOW_ETH, false }, - { L'\u00D1', L'\u00F1', NULL, A_LOW_NTILDE, false }, - { L'\u00D2', L'\u00F2', NULL, A_LOW_OGRAVE, false }, - { L'\u00D3', L'\u00F3', NULL, A_LOW_OACUTE, false }, - { L'\u00D4', L'\u00F4', NULL, A_LOW_OCIRCUMFLEX, false }, - { L'\u00D5', L'\u00F5', NULL, A_LOW_OTILDE, false }, - { L'\u00D6', L'\u00F6', NULL, A_LOW_ODIERESIS, false }, - { L'\u00F7', L'\u00F7', "KP_SLASH", A_DIVIDE, false }, - { L'\u00D8', L'\u00F8', NULL, A_LOW_OSLASH, false }, - { L'\u00D9', L'\u00F9', NULL, A_LOW_UGRAVE, false }, - { L'\u00DA', L'\u00FA', NULL, A_LOW_UACUTE, false }, - { L'\u00DB', L'\u00FB', NULL, A_LOW_UCIRCUMFLEX, false }, - { L'\u00DC', L'\u00FC', NULL, A_LOW_UDIERESIS, false }, - { L'\u00DD', L'\u00FD', NULL, A_LOW_YACUTE, false }, - { L'\u00DE', L'\u00FE', NULL, A_LOW_THORN, false }, - { 0x9f, 0xff, NULL, A_LOW_YDIERESIS, false }, // ******* - - { 0x100, 0x100, "JOY0", A_JOY0, false }, - { 0x101, 0x101, "JOY1", A_JOY1, false }, - { 0x102, 0x102, "JOY2", A_JOY2, false }, - { 0x103, 0x103, "JOY3", A_JOY3, false }, - { 0x104, 0x104, "JOY4", A_JOY4, false }, - { 0x105, 0x105, "JOY5", A_JOY5, false }, - { 0x106, 0x106, "JOY6", A_JOY6, false }, - { 0x107, 0x107, "JOY7", A_JOY7, false }, - { 0x108, 0x108, "JOY8", A_JOY8, false }, - { 0x109, 0x109, "JOY9", A_JOY9, false }, - { 0x10a, 0x10a, "JOY10", A_JOY10, false }, - { 0x10b, 0x10b, "JOY11", A_JOY11, false }, - { 0x10c, 0x10c, "JOY12", A_JOY12, false }, - { 0x10d, 0x10d, "JOY13", A_JOY13, false }, - { 0x10e, 0x10e, "JOY14", A_JOY14, false }, - { 0x10f, 0x10f, "JOY15", A_JOY15, false }, - { 0x110, 0x110, "JOY16", A_JOY16, false }, - { 0x111, 0x111, "JOY17", A_JOY17, false }, - { 0x112, 0x112, "JOY18", A_JOY18, false }, - { 0x113, 0x113, "JOY19", A_JOY19, false }, - { 0x114, 0x114, "JOY20", A_JOY20, false }, - { 0x115, 0x115, "JOY21", A_JOY21, false }, - { 0x116, 0x116, "JOY22", A_JOY22, false }, - { 0x117, 0x117, "JOY23", A_JOY23, false }, - { 0x118, 0x118, "JOY24", A_JOY24, false }, - { 0x119, 0x119, "JOY25", A_JOY25, false }, - { 0x11a, 0x11a, "JOY26", A_JOY26, false }, - { 0x11b, 0x11b, "JOY27", A_JOY27, false }, - { 0x11c, 0x11c, "JOY28", A_JOY28, false }, - { 0x11d, 0x11d, "JOY29", A_JOY29, false }, - { 0x11e, 0x11e, "JOY30", A_JOY30, false }, - { 0x11f, 0x11f, "JOY31", A_JOY31, false }, - - { 0x120, 0x120, "AUX0", A_AUX0, false }, - { 0x121, 0x121, "AUX1", A_AUX1, false }, - { 0x122, 0x122, "AUX2", A_AUX2, false }, - { 0x123, 0x123, "AUX3", A_AUX3, false }, - { 0x124, 0x124, "AUX4", A_AUX4, false }, - { 0x125, 0x125, "AUX5", A_AUX5, false }, - { 0x126, 0x126, "AUX6", A_AUX6, false }, - { 0x127, 0x127, "AUX7", A_AUX7, false }, - { 0x128, 0x128, "AUX8", A_AUX8, false }, - { 0x129, 0x129, "AUX9", A_AUX9, false }, - { 0x12a, 0x12a, "AUX10", A_AUX10, false }, - { 0x12b, 0x12b, "AUX11", A_AUX11, false }, - { 0x12c, 0x12c, "AUX12", A_AUX12, false }, - { 0x12d, 0x12d, "AUX13", A_AUX13, false }, - { 0x12e, 0x12e, "AUX14", A_AUX14, false }, - { 0x12f, 0x12f, "AUX15", A_AUX15, false }, - { 0x130, 0x130, "AUX16", A_AUX16, false }, - { 0x131, 0x131, "AUX17", A_AUX17, false }, - { 0x132, 0x132, "AUX18", A_AUX18, false }, - { 0x133, 0x133, "AUX19", A_AUX19, false }, - { 0x134, 0x134, "AUX20", A_AUX20, false }, - { 0x135, 0x135, "AUX21", A_AUX21, false }, - { 0x136, 0x136, "AUX22", A_AUX22, false }, - { 0x137, 0x137, "AUX23", A_AUX23, false }, - { 0x138, 0x138, "AUX24", A_AUX24, false }, - { 0x139, 0x139, "AUX25", A_AUX25, false }, - { 0x13a, 0x13a, "AUX26", A_AUX26, false }, - { 0x13b, 0x13b, "AUX27", A_AUX27, false }, - { 0x13c, 0x13c, "AUX28", A_AUX28, false }, - { 0x13d, 0x13d, "AUX29", A_AUX29, false }, - { 0x13e, 0x13e, "AUX30", A_AUX30, false }, - { 0x13f, 0x13f, "AUX31", A_AUX31, false } -}; -static const size_t numKeynames = ARRAY_LEN( keynames ); - - +keyname_t keynames[MAX_KEYS] = {{0x00, 0x00, NULL, A_NULL, false}, + {0x01, 0x01, "SHIFT", A_SHIFT, false}, + {0x02, 0x02, "CTRL", A_CTRL, false}, + {0x03, 0x03, "ALT", A_ALT, false}, + {0x04, 0x04, "CAPSLOCK", A_CAPSLOCK, false}, + {0x05, 0x05, "KP_NUMLOCK", A_NUMLOCK, false}, + {0x06, 0x06, "SCROLLLOCK", A_SCROLLLOCK, false}, + {0x07, 0x07, "PAUSE", A_PAUSE, false}, + {0x08, 0x08, "BACKSPACE", A_BACKSPACE, false}, + {0x09, 0x09, "TAB", A_TAB, false}, + {0x0a, 0x0a, "ENTER", A_ENTER, false}, + {0x0b, 0x0b, "KP_PLUS", A_KP_PLUS, false}, + {0x0c, 0x0c, "KP_MINUS", A_KP_MINUS, false}, + {0x0d, 0x0d, "KP_ENTER", A_KP_ENTER, false}, + {0x0e, 0x0e, "KP_DEL", A_KP_PERIOD, false}, + {0x0f, 0x0f, NULL, A_PRINTSCREEN, false}, + {0x10, 0x10, "KP_INS", A_KP_0, false}, + {0x11, 0x11, "KP_END", A_KP_1, false}, + {0x12, 0x12, "KP_DOWNARROW", A_KP_2, false}, + {0x13, 0x13, "KP_PGDN", A_KP_3, false}, + {0x14, 0x14, "KP_LEFTARROW", A_KP_4, false}, + {0x15, 0x15, "KP_5", A_KP_5, false}, + {0x16, 0x16, "KP_RIGHTARROW", A_KP_6, false}, + {0x17, 0x17, "KP_HOME", A_KP_7, false}, + {0x18, 0x18, "KP_UPARROW", A_KP_8, false}, + {0x19, 0x19, "KP_PGUP", A_KP_9, false}, + {0x1a, 0x1a, "CONSOLE", A_CONSOLE, false}, + {0x1b, 0x1b, "ESCAPE", A_ESCAPE, false}, + {0x1c, 0x1c, "F1", A_F1, true}, + {0x1d, 0x1d, "F2", A_F2, true}, + {0x1e, 0x1e, "F3", A_F3, true}, + {0x1f, 0x1f, "F4", A_F4, true}, + + {0x20, 0x20, "SPACE", A_SPACE, false}, + {(word)'!', (word)'!', NULL, A_PLING, false}, + {(word)'"', (word)'"', NULL, A_DOUBLE_QUOTE, false}, + {(word)'#', (word)'#', NULL, A_HASH, false}, + {(word)'$', (word)'$', NULL, A_STRING, false}, + {(word)'%', (word)'%', NULL, A_PERCENT, false}, + {(word)'&', (word)'&', NULL, A_AND, false}, + {0x27, 0x27, NULL, A_SINGLE_QUOTE, false}, + {(word)'(', (word)'(', NULL, A_OPEN_BRACKET, false}, + {(word)')', (word)')', NULL, A_CLOSE_BRACKET, false}, + {(word)'*', (word)'*', NULL, A_STAR, false}, + {(word)'+', (word)'+', NULL, A_PLUS, false}, + {(word)',', (word)',', NULL, A_COMMA, false}, + {(word)'-', (word)'-', NULL, A_MINUS, false}, + {(word)'.', (word)'.', NULL, A_PERIOD, false}, + {(word)'/', (word)'/', NULL, A_FORWARD_SLASH, false}, + {(word)'0', (word)'0', NULL, A_0, false}, + {(word)'1', (word)'1', NULL, A_1, false}, + {(word)'2', (word)'2', NULL, A_2, false}, + {(word)'3', (word)'3', NULL, A_3, false}, + {(word)'4', (word)'4', NULL, A_4, false}, + {(word)'5', (word)'5', NULL, A_5, false}, + {(word)'6', (word)'6', NULL, A_6, false}, + {(word)'7', (word)'7', NULL, A_7, false}, + {(word)'8', (word)'8', NULL, A_8, false}, + {(word)'9', (word)'9', NULL, A_9, false}, + {(word)':', (word)':', NULL, A_COLON, false}, + {(word)';', (word)';', "SEMICOLON", A_SEMICOLON, false}, + {(word)'<', (word)'<', NULL, A_LESSTHAN, false}, + {(word)'=', (word)'=', NULL, A_EQUALS, false}, + {(word)'>', (word)'>', NULL, A_GREATERTHAN, false}, + {(word)'?', (word)'?', NULL, A_QUESTION, false}, + + {(word)'@', (word)'@', NULL, A_AT, false}, + {(word)'A', (word)'a', NULL, A_CAP_A, false}, + {(word)'B', (word)'b', NULL, A_CAP_B, false}, + {(word)'C', (word)'c', NULL, A_CAP_C, false}, + {(word)'D', (word)'d', NULL, A_CAP_D, false}, + {(word)'E', (word)'e', NULL, A_CAP_E, false}, + {(word)'F', (word)'f', NULL, A_CAP_F, false}, + {(word)'G', (word)'g', NULL, A_CAP_G, false}, + {(word)'H', (word)'h', NULL, A_CAP_H, false}, + {(word)'I', (word)'i', NULL, A_CAP_I, false}, + {(word)'J', (word)'j', NULL, A_CAP_J, false}, + {(word)'K', (word)'k', NULL, A_CAP_K, false}, + {(word)'L', (word)'l', NULL, A_CAP_L, false}, + {(word)'M', (word)'m', NULL, A_CAP_M, false}, + {(word)'N', (word)'n', NULL, A_CAP_N, false}, + {(word)'O', (word)'o', NULL, A_CAP_O, false}, + {(word)'P', (word)'p', NULL, A_CAP_P, false}, + {(word)'Q', (word)'q', NULL, A_CAP_Q, false}, + {(word)'R', (word)'r', NULL, A_CAP_R, false}, + {(word)'S', (word)'s', NULL, A_CAP_S, false}, + {(word)'T', (word)'t', NULL, A_CAP_T, false}, + {(word)'U', (word)'u', NULL, A_CAP_U, false}, + {(word)'V', (word)'v', NULL, A_CAP_V, false}, + {(word)'W', (word)'w', NULL, A_CAP_W, false}, + {(word)'X', (word)'x', NULL, A_CAP_X, false}, + {(word)'Y', (word)'y', NULL, A_CAP_Y, false}, + {(word)'Z', (word)'z', NULL, A_CAP_Z, false}, + {(word)'[', (word)'[', NULL, A_OPEN_SQUARE, false}, + {0x5c, 0x5c, NULL, A_BACKSLASH, false}, + {(word)']', (word)']', NULL, A_CLOSE_SQUARE, false}, + {(word)'^', (word)'^', NULL, A_CARET, false}, + {(word)'_', (word)'_', NULL, A_UNDERSCORE, false}, + + {0x60, 0x60, NULL, A_LEFT_SINGLE_QUOTE, false}, + {(word)'A', (word)'a', NULL, A_LOW_A, false}, + {(word)'B', (word)'b', NULL, A_LOW_B, false}, + {(word)'C', (word)'c', NULL, A_LOW_C, false}, + {(word)'D', (word)'d', NULL, A_LOW_D, false}, + {(word)'E', (word)'e', NULL, A_LOW_E, false}, + {(word)'F', (word)'f', NULL, A_LOW_F, false}, + {(word)'G', (word)'g', NULL, A_LOW_G, false}, + {(word)'H', (word)'h', NULL, A_LOW_H, false}, + {(word)'I', (word)'i', NULL, A_LOW_I, false}, + {(word)'J', (word)'j', NULL, A_LOW_J, false}, + {(word)'K', (word)'k', NULL, A_LOW_K, false}, + {(word)'L', (word)'l', NULL, A_LOW_L, false}, + {(word)'M', (word)'m', NULL, A_LOW_M, false}, + {(word)'N', (word)'n', NULL, A_LOW_N, false}, + {(word)'O', (word)'o', NULL, A_LOW_O, false}, + {(word)'P', (word)'p', NULL, A_LOW_P, false}, + {(word)'Q', (word)'q', NULL, A_LOW_Q, false}, + {(word)'R', (word)'r', NULL, A_LOW_R, false}, + {(word)'S', (word)'s', NULL, A_LOW_S, false}, + {(word)'T', (word)'t', NULL, A_LOW_T, false}, + {(word)'U', (word)'u', NULL, A_LOW_U, false}, + {(word)'V', (word)'v', NULL, A_LOW_V, false}, + {(word)'W', (word)'w', NULL, A_LOW_W, false}, + {(word)'X', (word)'x', NULL, A_LOW_X, false}, + {(word)'Y', (word)'y', NULL, A_LOW_Y, false}, + {(word)'Z', (word)'z', NULL, A_LOW_Z, false}, + {(word)'{', (word)'{', NULL, A_OPEN_BRACE, false}, + {(word)'|', (word)'|', NULL, A_BAR, false}, + {(word)'}', (word)'}', NULL, A_CLOSE_BRACE, false}, + {(word)'~', (word)'~', NULL, A_TILDE, false}, + {0x7f, 0x7f, "DEL", A_DELETE, false}, + + {0x80, 0x80, "EURO", A_EURO, false}, + {0x81, 0x81, "SHIFT", A_SHIFT2, false}, + {0x82, 0x82, "CTRL", A_CTRL2, false}, + {0x83, 0x83, "ALT", A_ALT2, false}, + {0x84, 0x84, "F5", A_F5, true}, + {0x85, 0x85, "F6", A_F6, true}, + {0x86, 0x86, "F7", A_F7, true}, + {0x87, 0x87, "F8", A_F8, true}, + {0x88, 0x88, "CIRCUMFLEX", A_CIRCUMFLEX, false}, + {0x89, 0x89, "MWHEELUP", A_MWHEELUP, false}, + {0x8a, 0x9a, NULL, A_CAP_SCARON, false}, // ****** + {0x8b, 0x8b, "MWHEELDOWN", A_MWHEELDOWN, false}, + {0x8c, 0x9c, NULL, A_CAP_OE, false}, // ****** + {0x8d, 0x8d, "MOUSE1", A_MOUSE1, false}, + {0x8e, 0x8e, "MOUSE2", A_MOUSE2, false}, + {0x8f, 0x8f, "INS", A_INSERT, false}, + {0x90, 0x90, "HOME", A_HOME, false}, + {0x91, 0x91, "PGUP", A_PAGE_UP, false}, + {0x92, 0x92, NULL, A_RIGHT_SINGLE_QUOTE, false}, + {0x93, 0x93, NULL, A_LEFT_DOUBLE_QUOTE, false}, + {0x94, 0x94, NULL, A_RIGHT_DOUBLE_QUOTE, false}, + {0x95, 0x95, "F9", A_F9, true}, + {0x96, 0x96, "F10", A_F10, true}, + {0x97, 0x97, "F11", A_F11, true}, + {0x98, 0x98, "F12", A_F12, true}, + {0x99, 0x99, NULL, A_TRADEMARK, false}, + {0x8a, 0x9a, NULL, A_LOW_SCARON, false}, // ****** + {0x9b, 0x9b, "SHIFT_ENTER", A_ENTER, false}, + {0x8c, 0x9c, NULL, A_LOW_OE, false}, // ****** + {0x9d, 0x9d, "END", A_END, false}, + {0x9e, 0x9e, "PGDN", A_PAGE_DOWN, false}, + {0x9f, 0xff, NULL, A_CAP_YDIERESIS, false}, // ****** + + {0xa0, 0, "SHIFT_SPACE", A_SPACE, false}, + {0xa1, 0xa1, NULL, A_EXCLAMDOWN, false}, // upside down '!' - undisplayable + {L'\u00A2', L'\u00A2', NULL, A_CENT, false}, // cent sign + {L'\u00A3', L'\u00A3', NULL, A_POUND, false}, // pound (as in currency) symbol + {0xa4, 0, "SHIFT_KP_ENTER", A_KP_ENTER, false}, + {L'\u00A5', L'\u00A5', NULL, A_YEN, false}, // yen symbol + {0xa6, 0xa6, "MOUSE3", A_MOUSE3, false}, + {0xa7, 0xa7, "MOUSE4", A_MOUSE4, false}, + {0xa8, 0xa8, "MOUSE5", A_MOUSE5, false}, + {L'\u00A9', L'\u00A9', NULL, A_COPYRIGHT, false}, // copyright symbol + {0xaa, 0xaa, "UPARROW", A_CURSOR_UP, false}, + {0xab, 0xab, "DOWNARROW", A_CURSOR_DOWN, false}, + {0xac, 0xac, "LEFTARROW", A_CURSOR_LEFT, false}, + {0xad, 0xad, "RIGHTARROW", A_CURSOR_RIGHT, false}, + {L'\u00AE', L'\u00AE', NULL, A_REGISTERED, false}, // registered trademark symbol + {0xaf, 0, NULL, A_UNDEFINED_7, false}, + {0xb0, 0, NULL, A_UNDEFINED_8, false}, + {0xb1, 0, NULL, A_UNDEFINED_9, false}, + {0xb2, 0, NULL, A_UNDEFINED_10, false}, + {0xb3, 0, NULL, A_UNDEFINED_11, false}, + {0xb4, 0, NULL, A_UNDEFINED_12, false}, + {0xb5, 0, NULL, A_UNDEFINED_13, false}, + {0xb6, 0, NULL, A_UNDEFINED_14, false}, + {0xb7, 0, NULL, A_UNDEFINED_15, false}, + {0xb8, 0, NULL, A_UNDEFINED_16, false}, + {0xb9, 0, NULL, A_UNDEFINED_17, false}, + {0xba, 0, NULL, A_UNDEFINED_18, false}, + {0xbb, 0, NULL, A_UNDEFINED_19, false}, + {0xbc, 0, NULL, A_UNDEFINED_20, false}, + {0xbd, 0, NULL, A_UNDEFINED_21, false}, + {0xbe, 0, NULL, A_UNDEFINED_22, false}, + {L'\u00BF', L'\u00BF', NULL, A_QUESTION_DOWN, false}, // upside-down question mark + + {L'\u00C0', L'\u00E0', NULL, A_CAP_AGRAVE, false}, + {L'\u00C1', L'\u00E1', NULL, A_CAP_AACUTE, false}, + {L'\u00C2', L'\u00E2', NULL, A_CAP_ACIRCUMFLEX, false}, + {L'\u00C3', L'\u00E3', NULL, A_CAP_ATILDE, false}, + {L'\u00C4', L'\u00E4', NULL, A_CAP_ADIERESIS, false}, + {L'\u00C5', L'\u00E5', NULL, A_CAP_ARING, false}, + {L'\u00C6', L'\u00E6', NULL, A_CAP_AE, false}, + {L'\u00C7', L'\u00E7', NULL, A_CAP_CCEDILLA, false}, + {L'\u00C8', L'\u00E8', NULL, A_CAP_EGRAVE, false}, + {L'\u00C9', L'\u00E9', NULL, A_CAP_EACUTE, false}, + {L'\u00CA', L'\u00EA', NULL, A_CAP_ECIRCUMFLEX, false}, + {L'\u00CB', L'\u00EB', NULL, A_CAP_EDIERESIS, false}, + {L'\u00CC', L'\u00EC', NULL, A_CAP_IGRAVE, false}, + {L'\u00CD', L'\u00ED', NULL, A_CAP_IACUTE, false}, + {L'\u00CE', L'\u00EE', NULL, A_CAP_ICIRCUMFLEX, false}, + {L'\u00CF', L'\u00EF', NULL, A_CAP_IDIERESIS, false}, + {L'\u00D0', L'\u00F0', NULL, A_CAP_ETH, false}, + {L'\u00D1', L'\u00F1', NULL, A_CAP_NTILDE, false}, + {L'\u00D2', L'\u00F2', NULL, A_CAP_OGRAVE, false}, + {L'\u00D3', L'\u00F3', NULL, A_CAP_OACUTE, false}, + {L'\u00D4', L'\u00F4', NULL, A_CAP_OCIRCUMFLEX, false}, + {L'\u00D5', L'\u00F5', NULL, A_CAP_OTILDE, false}, + {L'\u00D6', L'\u00F6', NULL, A_CAP_ODIERESIS, false}, + {L'\u00D7', L'\u00D7', "KP_STAR", A_MULTIPLY, false}, + {L'\u00D8', L'\u00F8', NULL, A_CAP_OSLASH, false}, + {L'\u00D9', L'\u00F9', NULL, A_CAP_UGRAVE, false}, + {L'\u00DA', L'\u00FA', NULL, A_CAP_UACUTE, false}, + {L'\u00DB', L'\u00FB', NULL, A_CAP_UCIRCUMFLEX, false}, + {L'\u00DC', L'\u00FC', NULL, A_CAP_UDIERESIS, false}, + {L'\u00DD', L'\u00FD', NULL, A_CAP_YACUTE, false}, + {L'\u00DE', L'\u00FE', NULL, A_CAP_THORN, false}, + {L'\u00DF', L'\u00DF', NULL, A_GERMANDBLS, false}, + + {L'\u00C0', L'\u00E0', NULL, A_LOW_AGRAVE, false}, + {L'\u00C1', L'\u00E1', NULL, A_LOW_AACUTE, false}, + {L'\u00C2', L'\u00E2', NULL, A_LOW_ACIRCUMFLEX, false}, + {L'\u00C3', L'\u00E3', NULL, A_LOW_ATILDE, false}, + {L'\u00C4', L'\u00E4', NULL, A_LOW_ADIERESIS, false}, + {L'\u00C5', L'\u00E5', NULL, A_LOW_ARING, false}, + {L'\u00C6', L'\u00E6', NULL, A_LOW_AE, false}, + {L'\u00C7', L'\u00E7', NULL, A_LOW_CCEDILLA, false}, + {L'\u00C8', L'\u00E8', NULL, A_LOW_EGRAVE, false}, + {L'\u00C9', L'\u00E9', NULL, A_LOW_EACUTE, false}, + {L'\u00CA', L'\u00EA', NULL, A_LOW_ECIRCUMFLEX, false}, + {L'\u00CB', L'\u00EB', NULL, A_LOW_EDIERESIS, false}, + {L'\u00CC', L'\u00EC', NULL, A_LOW_IGRAVE, false}, + {L'\u00CD', L'\u00ED', NULL, A_LOW_IACUTE, false}, + {L'\u00CE', L'\u00EE', NULL, A_LOW_ICIRCUMFLEX, false}, + {L'\u00CF', L'\u00EF', NULL, A_LOW_IDIERESIS, false}, + {L'\u00D0', L'\u00F0', NULL, A_LOW_ETH, false}, + {L'\u00D1', L'\u00F1', NULL, A_LOW_NTILDE, false}, + {L'\u00D2', L'\u00F2', NULL, A_LOW_OGRAVE, false}, + {L'\u00D3', L'\u00F3', NULL, A_LOW_OACUTE, false}, + {L'\u00D4', L'\u00F4', NULL, A_LOW_OCIRCUMFLEX, false}, + {L'\u00D5', L'\u00F5', NULL, A_LOW_OTILDE, false}, + {L'\u00D6', L'\u00F6', NULL, A_LOW_ODIERESIS, false}, + {L'\u00F7', L'\u00F7', "KP_SLASH", A_DIVIDE, false}, + {L'\u00D8', L'\u00F8', NULL, A_LOW_OSLASH, false}, + {L'\u00D9', L'\u00F9', NULL, A_LOW_UGRAVE, false}, + {L'\u00DA', L'\u00FA', NULL, A_LOW_UACUTE, false}, + {L'\u00DB', L'\u00FB', NULL, A_LOW_UCIRCUMFLEX, false}, + {L'\u00DC', L'\u00FC', NULL, A_LOW_UDIERESIS, false}, + {L'\u00DD', L'\u00FD', NULL, A_LOW_YACUTE, false}, + {L'\u00DE', L'\u00FE', NULL, A_LOW_THORN, false}, + {0x9f, 0xff, NULL, A_LOW_YDIERESIS, false}, // ******* + + {0x100, 0x100, "JOY0", A_JOY0, false}, + {0x101, 0x101, "JOY1", A_JOY1, false}, + {0x102, 0x102, "JOY2", A_JOY2, false}, + {0x103, 0x103, "JOY3", A_JOY3, false}, + {0x104, 0x104, "JOY4", A_JOY4, false}, + {0x105, 0x105, "JOY5", A_JOY5, false}, + {0x106, 0x106, "JOY6", A_JOY6, false}, + {0x107, 0x107, "JOY7", A_JOY7, false}, + {0x108, 0x108, "JOY8", A_JOY8, false}, + {0x109, 0x109, "JOY9", A_JOY9, false}, + {0x10a, 0x10a, "JOY10", A_JOY10, false}, + {0x10b, 0x10b, "JOY11", A_JOY11, false}, + {0x10c, 0x10c, "JOY12", A_JOY12, false}, + {0x10d, 0x10d, "JOY13", A_JOY13, false}, + {0x10e, 0x10e, "JOY14", A_JOY14, false}, + {0x10f, 0x10f, "JOY15", A_JOY15, false}, + {0x110, 0x110, "JOY16", A_JOY16, false}, + {0x111, 0x111, "JOY17", A_JOY17, false}, + {0x112, 0x112, "JOY18", A_JOY18, false}, + {0x113, 0x113, "JOY19", A_JOY19, false}, + {0x114, 0x114, "JOY20", A_JOY20, false}, + {0x115, 0x115, "JOY21", A_JOY21, false}, + {0x116, 0x116, "JOY22", A_JOY22, false}, + {0x117, 0x117, "JOY23", A_JOY23, false}, + {0x118, 0x118, "JOY24", A_JOY24, false}, + {0x119, 0x119, "JOY25", A_JOY25, false}, + {0x11a, 0x11a, "JOY26", A_JOY26, false}, + {0x11b, 0x11b, "JOY27", A_JOY27, false}, + {0x11c, 0x11c, "JOY28", A_JOY28, false}, + {0x11d, 0x11d, "JOY29", A_JOY29, false}, + {0x11e, 0x11e, "JOY30", A_JOY30, false}, + {0x11f, 0x11f, "JOY31", A_JOY31, false}, + + {0x120, 0x120, "AUX0", A_AUX0, false}, + {0x121, 0x121, "AUX1", A_AUX1, false}, + {0x122, 0x122, "AUX2", A_AUX2, false}, + {0x123, 0x123, "AUX3", A_AUX3, false}, + {0x124, 0x124, "AUX4", A_AUX4, false}, + {0x125, 0x125, "AUX5", A_AUX5, false}, + {0x126, 0x126, "AUX6", A_AUX6, false}, + {0x127, 0x127, "AUX7", A_AUX7, false}, + {0x128, 0x128, "AUX8", A_AUX8, false}, + {0x129, 0x129, "AUX9", A_AUX9, false}, + {0x12a, 0x12a, "AUX10", A_AUX10, false}, + {0x12b, 0x12b, "AUX11", A_AUX11, false}, + {0x12c, 0x12c, "AUX12", A_AUX12, false}, + {0x12d, 0x12d, "AUX13", A_AUX13, false}, + {0x12e, 0x12e, "AUX14", A_AUX14, false}, + {0x12f, 0x12f, "AUX15", A_AUX15, false}, + {0x130, 0x130, "AUX16", A_AUX16, false}, + {0x131, 0x131, "AUX17", A_AUX17, false}, + {0x132, 0x132, "AUX18", A_AUX18, false}, + {0x133, 0x133, "AUX19", A_AUX19, false}, + {0x134, 0x134, "AUX20", A_AUX20, false}, + {0x135, 0x135, "AUX21", A_AUX21, false}, + {0x136, 0x136, "AUX22", A_AUX22, false}, + {0x137, 0x137, "AUX23", A_AUX23, false}, + {0x138, 0x138, "AUX24", A_AUX24, false}, + {0x139, 0x139, "AUX25", A_AUX25, false}, + {0x13a, 0x13a, "AUX26", A_AUX26, false}, + {0x13b, 0x13b, "AUX27", A_AUX27, false}, + {0x13c, 0x13c, "AUX28", A_AUX28, false}, + {0x13d, 0x13d, "AUX29", A_AUX29, false}, + {0x13e, 0x13e, "AUX30", A_AUX30, false}, + {0x13f, 0x13f, "AUX31", A_AUX31, false}}; +static const size_t numKeynames = ARRAY_LEN(keynames); /* ============================================================================= @@ -389,7 +383,6 @@ EDIT FIELDS ============================================================================= */ - /* =================== Field_Draw @@ -399,84 +392,82 @@ x, y, amd width are in pixels =================== */ extern console_t con; -void Field_VariableSizeDraw( field_t *edit, int x, int y, int size, qboolean showCursor, qboolean noColorEscape ) { - int len; - int drawLen; - int prestep; - int cursorChar; - char str[MAX_STRING_CHARS]; - int i; +void Field_VariableSizeDraw(field_t *edit, int x, int y, int size, qboolean showCursor, qboolean noColorEscape) { + int len; + int drawLen; + int prestep; + int cursorChar; + char str[MAX_STRING_CHARS]; + int i; drawLen = edit->widthInChars - 1; // - 1 so there is always a space for the cursor - len = strlen( edit->buffer ); + len = strlen(edit->buffer); // guarantee that cursor will be visible - if ( len <= drawLen ) { + if (len <= drawLen) { prestep = 0; } else { - if ( edit->scroll + drawLen > len ) { + if (edit->scroll + drawLen > len) { edit->scroll = len - drawLen; - if ( edit->scroll < 0 ) { + if (edit->scroll < 0) { edit->scroll = 0; } } prestep = edit->scroll; } - if ( prestep + drawLen > len ) { + if (prestep + drawLen > len) { drawLen = len - prestep; } // extract characters from the field at - if ( drawLen >= MAX_STRING_CHARS ) { - Com_Error( ERR_DROP, "drawLen >= MAX_STRING_CHARS" ); + if (drawLen >= MAX_STRING_CHARS) { + Com_Error(ERR_DROP, "drawLen >= MAX_STRING_CHARS"); } - memcpy( str, edit->buffer + prestep, drawLen ); - str[ drawLen ] = 0; + memcpy(str, edit->buffer + prestep, drawLen); + str[drawLen] = 0; // draw it - if ( size == con.charWidth ) { - float color[4]; + if (size == con.charWidth) { + float color[4]; color[0] = color[1] = color[2] = color[3] = 1.0; - SCR_DrawSmallStringExt( x, y, str, color, qfalse, noColorEscape ); + SCR_DrawSmallStringExt(x, y, str, color, qfalse, noColorEscape); } else { // draw big string with drop shadow - SCR_DrawBigString( x, y, str, 1.0, noColorEscape ); + SCR_DrawBigString(x, y, str, 1.0, noColorEscape); } // draw the cursor - if ( showCursor ) { - if ( (int)( cls.realtime >> 8 ) & 1 ) { - return; // off blink + if (showCursor) { + if ((int)(cls.realtime >> 8) & 1) { + return; // off blink } - if ( kg.key_overstrikeMode ) { + if (kg.key_overstrikeMode) { cursorChar = 11; } else { cursorChar = 10; } - i = drawLen - strlen( str ); + i = drawLen - strlen(str); - if ( size == con.charWidth ) { - SCR_DrawSmallChar( x + ( edit->cursor - prestep - i ) * size, y, cursorChar ); + if (size == con.charWidth) { + SCR_DrawSmallChar(x + (edit->cursor - prestep - i) * size, y, cursorChar); } else { str[0] = cursorChar; str[1] = 0; - SCR_DrawBigString( x + ( edit->cursor - prestep - i ) * size, y, str, 1.0, qfalse ); + SCR_DrawBigString(x + (edit->cursor - prestep - i) * size, y, str, 1.0, qfalse); } } } -void Field_Draw( field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape ) -{ - Field_VariableSizeDraw( edit, x, y, con.charWidth, showCursor, noColorEscape ); +void Field_Draw(field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape) { + Field_VariableSizeDraw(edit, x, y, con.charWidth, showCursor, noColorEscape); } -void Field_BigDraw( field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape ) -{ - Field_VariableSizeDraw( edit, x, y, BIGCHAR_WIDTH, showCursor, noColorEscape ); +void Field_BigDraw(field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape) { + Field_VariableSizeDraw(edit, x, y, BIGCHAR_WIDTH, showCursor, noColorEscape); } /* @@ -484,24 +475,23 @@ void Field_BigDraw( field_t *edit, int x, int y, qboolean showCursor, qboolean n Field_Paste ================ */ -void Field_CharEvent( field_t *edit, int ch ); -void Field_Paste( field_t *edit ) { - char *cbd, *c; +void Field_CharEvent(field_t *edit, int ch); +void Field_Paste(field_t *edit) { + char *cbd, *c; c = cbd = Sys_GetClipboardData(); - if ( !cbd ) { + if (!cbd) { return; } // send as if typed, so insert / overstrike works properly - while( *c ) - { - uint32_t utf32 = ConvertUTF8ToUTF32( c, &c ); - Field_CharEvent( edit, ConvertUTF32ToExpectedCharset( utf32 ) ); + while (*c) { + uint32_t utf32 = ConvertUTF8ToUTF32(c, &c); + Field_CharEvent(edit, ConvertUTF32ToExpectedCharset(utf32)); } - Z_Free( cbd ); + Z_Free(cbd); } /* @@ -514,64 +504,55 @@ in-game talk, and menu fields Key events are used for non-printable characters, others are gotten from char events. ================= */ -void Field_KeyDownEvent( field_t *edit, int key ) { - int len; +void Field_KeyDownEvent(field_t *edit, int key) { + int len; // shift-insert is paste - if ( ( key == A_INSERT ) && kg.keys[A_SHIFT].down ) - { - Field_Paste( edit ); + if ((key == A_INSERT) && kg.keys[A_SHIFT].down) { + Field_Paste(edit); return; } - len = strlen( edit->buffer ); + len = strlen(edit->buffer); - if ( key == A_DELETE ) { - if ( edit->cursor < len ) { - memmove( edit->buffer + edit->cursor, - edit->buffer + edit->cursor + 1, len - edit->cursor ); + if (key == A_DELETE) { + if (edit->cursor < len) { + memmove(edit->buffer + edit->cursor, edit->buffer + edit->cursor + 1, len - edit->cursor); } return; } - if ( key == A_CURSOR_RIGHT ) - { - if ( edit->cursor < len ) { + if (key == A_CURSOR_RIGHT) { + if (edit->cursor < len) { edit->cursor++; } - if ( edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len ) - { + if (edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len) { edit->scroll++; } return; } - if ( key == A_CURSOR_LEFT ) - { - if ( edit->cursor > 0 ) { + if (key == A_CURSOR_LEFT) { + if (edit->cursor > 0) { edit->cursor--; } - if ( edit->cursor < edit->scroll ) - { + if (edit->cursor < edit->scroll) { edit->scroll--; } return; } - if ( key == A_HOME || ( keynames[key].lower == 'a' && kg.keys[A_CTRL].down ) ) - { + if (key == A_HOME || (keynames[key].lower == 'a' && kg.keys[A_CTRL].down)) { edit->cursor = 0; return; } - if ( key == A_END || ( keynames[key].lower == 'e' && kg.keys[A_CTRL].down ) ) - { + if (key == A_END || (keynames[key].lower == 'e' && kg.keys[A_CTRL].down)) { edit->cursor = len; return; } - if ( key == A_INSERT ) - { + if (key == A_INSERT) { kg.key_overstrikeMode = (qboolean)!kg.key_overstrikeMode; return; } @@ -582,41 +563,39 @@ void Field_KeyDownEvent( field_t *edit, int key ) { Field_CharEvent ================== */ -void Field_CharEvent( field_t *edit, int ch ) { - int len; +void Field_CharEvent(field_t *edit, int ch) { + int len; - if ( ch == 'v' - 'a' + 1 ) { // ctrl-v is paste - Field_Paste( edit ); + if (ch == 'v' - 'a' + 1) { // ctrl-v is paste + Field_Paste(edit); return; } - if ( ch == 'c' - 'a' + 1 ) { // ctrl-c clears the field - Field_Clear( edit ); + if (ch == 'c' - 'a' + 1) { // ctrl-c clears the field + Field_Clear(edit); return; } - len = strlen( edit->buffer ); + len = strlen(edit->buffer); - if ( ch == 'h' - 'a' + 1 ) { // ctrl-h is backspace - if ( edit->cursor > 0 ) { - memmove( edit->buffer + edit->cursor - 1, - edit->buffer + edit->cursor, len + 1 - edit->cursor ); + if (ch == 'h' - 'a' + 1) { // ctrl-h is backspace + if (edit->cursor > 0) { + memmove(edit->buffer + edit->cursor - 1, edit->buffer + edit->cursor, len + 1 - edit->cursor); edit->cursor--; - if ( edit->cursor < edit->scroll ) - { + if (edit->cursor < edit->scroll) { edit->scroll--; } } return; } - if ( ch == 'a' - 'a' + 1 ) { // ctrl-a is home + if (ch == 'a' - 'a' + 1) { // ctrl-a is home edit->cursor = 0; edit->scroll = 0; return; } - if ( ch == 'e' - 'a' + 1 ) { // ctrl-e is end + if (ch == 'e' - 'a' + 1) { // ctrl-e is end edit->cursor = len; edit->scroll = edit->cursor - edit->widthInChars; return; @@ -625,33 +604,31 @@ void Field_CharEvent( field_t *edit, int ch ) { // // ignore any other non printable chars // - if ( ch < 32 ) { + if (ch < 32) { return; } - if ( kg.key_overstrikeMode ) { + if (kg.key_overstrikeMode) { // - 2 to leave room for the leading slash and trailing \0 - if ( edit->cursor == MAX_EDIT_LINE - 2 ) + if (edit->cursor == MAX_EDIT_LINE - 2) return; edit->buffer[edit->cursor] = ch; edit->cursor++; - } else { // insert mode + } else { // insert mode // - 2 to leave room for the leading slash and trailing \0 - if ( len == MAX_EDIT_LINE - 2 ) { + if (len == MAX_EDIT_LINE - 2) { return; // all full } - memmove( edit->buffer + edit->cursor + 1, - edit->buffer + edit->cursor, len + 1 - edit->cursor ); + memmove(edit->buffer + edit->cursor + 1, edit->buffer + edit->cursor, len + 1 - edit->cursor); edit->buffer[edit->cursor] = ch; edit->cursor++; } - if ( edit->cursor >= edit->widthInChars ) - { + if (edit->cursor >= edit->widthInChars) { edit->scroll++; } - if ( edit->cursor == len + 1) { + if (edit->cursor == len + 1) { edit->buffer[edit->cursor] = 0; } } @@ -663,33 +640,31 @@ Console_Key Handles history and console scrollback ==================== */ -void Console_Key (int key) { +void Console_Key(int key) { // ctrl-L clears screen - if ( keynames[ key ].lower == 'l' && kg.keys[A_CTRL].down ) { - Cbuf_AddText ("clear\n"); + if (keynames[key].lower == 'l' && kg.keys[A_CTRL].down) { + Cbuf_AddText("clear\n"); return; } // enter finishes the line - if ( key == A_ENTER || key == A_KP_ENTER ) { + if (key == A_ENTER || key == A_KP_ENTER) { // legacy hack: strip any prepended slashes. they're not necessary anymore - if ( g_consoleField.buffer[0] && - (g_consoleField.buffer[0] == '\\' || g_consoleField.buffer[0] == '/') ) { - char temp[MAX_EDIT_LINE-1]; + if (g_consoleField.buffer[0] && (g_consoleField.buffer[0] == '\\' || g_consoleField.buffer[0] == '/')) { + char temp[MAX_EDIT_LINE - 1]; - Q_strncpyz( temp, g_consoleField.buffer+1, sizeof( temp ) ); - Com_sprintf( g_consoleField.buffer, sizeof( g_consoleField.buffer ), "%s", temp ); + Q_strncpyz(temp, g_consoleField.buffer + 1, sizeof(temp)); + Com_sprintf(g_consoleField.buffer, sizeof(g_consoleField.buffer), "%s", temp); g_consoleField.cursor--; } // print executed command - Com_Printf( "%c%s\n", CONSOLE_PROMPT_CHAR, g_consoleField.buffer ); + Com_Printf("%c%s\n", CONSOLE_PROMPT_CHAR, g_consoleField.buffer); - Cbuf_AddText( g_consoleField.buffer ); // valid command - Cbuf_AddText ("\n"); + Cbuf_AddText(g_consoleField.buffer); // valid command + Cbuf_AddText("\n"); - if (!g_consoleField.buffer[0]) - { + if (!g_consoleField.buffer[0]) { return; // empty lines just scroll the console without adding to history } @@ -698,14 +673,14 @@ void Console_Key (int key) { nextHistoryLine++; historyLine = nextHistoryLine; - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - //CL_SaveConsoleHistory(); + // CL_SaveConsoleHistory(); - if ( cls.state == CA_DISCONNECTED ) - SCR_UpdateScreen (); // force an update, because the command may take some time + if (cls.state == CA_DISCONNECTED) + SCR_UpdateScreen(); // force an update, because the command may take some time return; } @@ -713,30 +688,26 @@ void Console_Key (int key) { // command completion if (key == A_TAB) { - Field_AutoComplete( &g_consoleField ); + Field_AutoComplete(&g_consoleField); return; } // history scrolling - if ( key == A_CURSOR_UP || key == A_KP_8 - || (kg.keys[A_SHIFT].down && key == A_MWHEELUP) - || (kg.keys[A_CTRL].down && keynames[key].lower == 'p') ) - {// scroll up: arrow-up, numpad-up, shift + mwheelup, ctrl + p - if ( nextHistoryLine - historyLine < COMMAND_HISTORY && historyLine > 0 ) + if (key == A_CURSOR_UP || key == A_KP_8 || (kg.keys[A_SHIFT].down && key == A_MWHEELUP) || + (kg.keys[A_CTRL].down && keynames[key].lower == 'p')) { // scroll up: arrow-up, numpad-up, shift + mwheelup, ctrl + p + if (nextHistoryLine - historyLine < COMMAND_HISTORY && historyLine > 0) historyLine--; g_consoleField = historyEditLines[historyLine % COMMAND_HISTORY]; return; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 - || (kg.keys[A_SHIFT].down && key == A_MWHEELDOWN) - || (kg.keys[A_CTRL].down && keynames[key].lower == 'n') ) - {// scroll down: arrow-down, numpad-down, shift + mwheeldown, ctrl + n + if (key == A_CURSOR_DOWN || key == A_KP_2 || (kg.keys[A_SHIFT].down && key == A_MWHEELDOWN) || + (kg.keys[A_CTRL].down && keynames[key].lower == 'n')) { // scroll down: arrow-down, numpad-down, shift + mwheeldown, ctrl + n historyLine++; if (historyLine >= nextHistoryLine) { historyLine = nextHistoryLine; - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; return; } @@ -745,53 +716,49 @@ void Console_Key (int key) { } // console scrolling (ctrl to scroll fast) - if ( key == A_PAGE_UP || key == A_MWHEELUP ) { + if (key == A_PAGE_UP || key == A_MWHEELUP) { int count = kg.keys[A_CTRL].down ? 5 : 1; - for ( int i=0; i= MAX_KEYS ) +qboolean Key_IsDown(int keynum) { + if (keynum < 0 || keynum >= MAX_KEYS) return qfalse; return kg.keys[keynames[keynum].upper].down; @@ -809,25 +776,25 @@ the K_* names are matched up. to be configured even if they don't have defined names. =================== */ -int Key_StringToKeynum( char *str ) { - if ( !VALIDSTRING( str ) ) +int Key_StringToKeynum(char *str) { + if (!VALIDSTRING(str)) return -1; // If single char bind, presume ascii char bind - if ( !str[1] ) + if (!str[1]) return keynames[(unsigned char)str[0]].upper; // scan for a text match - for ( int i=0; i= 0 ) + if (n >= 0) return n; } @@ -835,33 +802,34 @@ int Key_StringToKeynum( char *str ) { } static char tinyString[16]; -static const char *Key_KeynumValid( int keynum ) { - if ( keynum == -1 ) +static const char *Key_KeynumValid(int keynum) { + if (keynum == -1) return ""; - if ( keynum < 0 || keynum >= MAX_KEYS ) + if (keynum < 0 || keynum >= MAX_KEYS) return ""; return NULL; } -static const char *Key_KeyToName( int keynum ) -{ - return keynames[keynum].name; -} +static const char *Key_KeyToName(int keynum) { return keynames[keynum].name; } -static const char *Key_KeyToAscii( int keynum ) { - if ( !keynames[keynum].lower ) +static const char *Key_KeyToAscii(int keynum) { + if (!keynames[keynum].lower) return NULL; - if ( keynum == A_SPACE ) tinyString[0] = (char)A_SHIFT_SPACE; - else if ( keynum == A_ENTER ) tinyString[0] = (char)A_SHIFT_ENTER; - else if ( keynum == A_KP_ENTER ) tinyString[0] = (char)A_SHIFT_KP_ENTER; - else tinyString[0] = keynames[keynum].upper; + if (keynum == A_SPACE) + tinyString[0] = (char)A_SHIFT_SPACE; + else if (keynum == A_ENTER) + tinyString[0] = (char)A_SHIFT_ENTER; + else if (keynum == A_KP_ENTER) + tinyString[0] = (char)A_SHIFT_KP_ENTER; + else + tinyString[0] = keynames[keynum].upper; tinyString[1] = '\0'; return tinyString; } -static const char *Key_KeyToHex( int keynum ) { +static const char *Key_KeyToHex(int keynum) { int i = keynum >> 4; int j = keynum & 15; @@ -875,20 +843,20 @@ static const char *Key_KeyToHex( int keynum ) { } // Returns the ascii code of the keynum -const char *Key_KeynumToAscii( int keynum ) { +const char *Key_KeynumToAscii(int keynum) { const char *name = Key_KeynumValid(keynum); // check for printable ascii - if ( !name && keynum > 0 && keynum < 256 ) - name = Key_KeyToAscii( keynum ); + if (!name && keynum > 0 && keynum < 256) + name = Key_KeyToAscii(keynum); // Check for name (for JOYx and AUXx buttons) - if ( !name ) - name = Key_KeyToName( keynum ); + if (!name) + name = Key_KeyToName(keynum); // Fallback to hex number - if ( !name ) - name = Key_KeyToHex( keynum ); + if (!name) + name = Key_KeyToHex(keynum); return name; } @@ -902,22 +870,22 @@ given keynum. =================== */ // Returns a console/config file friendly name for the key -const char *Key_KeynumToString( int keynum ) { +const char *Key_KeynumToString(int keynum) { const char *name; - name = Key_KeynumValid( keynum ); + name = Key_KeynumValid(keynum); // Check for friendly name - if ( !name ) - name = Key_KeyToName( keynum ); + if (!name) + name = Key_KeyToName(keynum); // check for printable ascii - if ( !name && keynum > 0 && keynum < 256) - name = Key_KeyToAscii( keynum ); + if (!name && keynum > 0 && keynum < 256) + name = Key_KeyToAscii(keynum); // Fallback to hex number - if ( !name ) - name = Key_KeyToHex( keynum ); + if (!name) + name = Key_KeyToHex(keynum); return name; } @@ -927,19 +895,19 @@ const char *Key_KeynumToString( int keynum ) { Key_SetBinding =================== */ -void Key_SetBinding( int keynum, const char *binding ) { - if ( keynum < 0 || keynum >= MAX_KEYS ) +void Key_SetBinding(int keynum, const char *binding) { + if (keynum < 0 || keynum >= MAX_KEYS) return; // free old bindings - if ( kg.keys[keynames[keynum].upper].binding ) { - Z_Free( kg.keys[keynames[keynum].upper].binding ); + if (kg.keys[keynames[keynum].upper].binding) { + Z_Free(kg.keys[keynames[keynum].upper].binding); kg.keys[keynames[keynum].upper].binding = NULL; } // allocate memory for new binding - if ( binding ) - kg.keys[keynames[keynum].upper].binding = CopyString( binding ); + if (binding) + kg.keys[keynames[keynum].upper].binding = CopyString(binding); // consider this like modifying an archived cvar, so the // file write will be triggered at the next oportunity @@ -951,8 +919,8 @@ void Key_SetBinding( int keynum, const char *binding ) { Key_GetBinding =================== */ -const char *Key_GetBinding( int keynum ) { - if ( keynum < 0 || keynum >= MAX_KEYS ) +const char *Key_GetBinding(int keynum) { + if (keynum < 0 || keynum >= MAX_KEYS) return ""; return kg.keys[keynum].binding; @@ -963,10 +931,10 @@ const char *Key_GetBinding( int keynum ) { Key_GetKey =================== */ -int Key_GetKey( const char *binding ) { - if ( binding ) { - for ( int i=0; i : remove commands from a key\n" ); +void Key_Unbind_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf("unbind : remove commands from a key\n"); return; } - int b = Key_StringToKeynum( Cmd_Argv( 1 ) ); - if ( b == -1 ) { - Com_Printf( "\"%s\" isn't a valid key\n", Cmd_Argv( 1 ) ); + int b = Key_StringToKeynum(Cmd_Argv(1)); + if (b == -1) { + Com_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - Key_SetBinding( b, "" ); + Key_SetBinding(b, ""); } /* @@ -999,10 +967,10 @@ void Key_Unbind_f( void ) { Key_Unbindall_f =================== */ -void Key_Unbindall_f( void ) { - for ( int i=0; i [command] : attach a command to a key\n" ); + if (c < 2) { + Com_Printf("bind [command] : attach a command to a key\n"); return; } - int b = Key_StringToKeynum( Cmd_Argv( 1 ) ); - if ( b == -1 ) { - Com_Printf( "\"%s\" isn't a valid key\n", Cmd_Argv( 1 ) ); + int b = Key_StringToKeynum(Cmd_Argv(1)); + if (b == -1) { + Com_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - if ( c == 2 ) { - if ( kg.keys[b].binding && kg.keys[b].binding[0] ) - Com_Printf( S_COLOR_GREY "Bind " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", Key_KeynumToString( b ), kg.keys[b].binding ); + if (c == 2) { + if (kg.keys[b].binding && kg.keys[b].binding[0]) + Com_Printf(S_COLOR_GREY "Bind " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", + Key_KeynumToString(b), kg.keys[b].binding); else - Com_Printf( "\"%s\" is not bound\n", Key_KeynumToString( b ) ); + Com_Printf("\"%s\" is not bound\n", Key_KeynumToString(b)); return; } - Key_SetBinding( b, Cmd_ArgsFrom( 2 ) ); + Key_SetBinding(b, Cmd_ArgsFrom(2)); } /* @@ -1043,17 +1012,17 @@ Key_WriteBindings Writes lines containing "bind key value" ============ */ -void Key_WriteBindings( fileHandle_t f ) { - FS_Printf( f, "unbindall\n" ); - for ( size_t i=0; i args ) + char *p = Com_SkipTokens(args, 1, " "); + if (p > args) Field_CompleteKeyname(); } } @@ -1102,22 +1072,21 @@ static void Key_CompleteUnbind( char *args, int argNum ) { Key_CompleteBind ==================== */ -static void Key_CompleteBind( char *args, int argNum ) { +static void Key_CompleteBind(char *args, int argNum) { char *p; - if ( argNum == 2 ) { + if (argNum == 2) { // Skip "bind " - p = Com_SkipTokens( args, 1, " " ); + p = Com_SkipTokens(args, 1, " "); - if ( p > args ) + if (p > args) Field_CompleteKeyname(); - } - else if ( argNum >= 3 ) { + } else if (argNum >= 3) { // Skip "bind " - p = Com_SkipTokens( args, 2, " " ); + p = Com_SkipTokens(args, 2, " "); - if ( p > args ) - Field_CompleteCommand( p, qtrue, qtrue ); + if (p > args) + Field_CompleteCommand(p, qtrue, qtrue); } } @@ -1126,14 +1095,14 @@ static void Key_CompleteBind( char *args, int argNum ) { CL_InitKeyCommands =================== */ -void CL_InitKeyCommands( void ) { +void CL_InitKeyCommands(void) { // register our functions - Cmd_AddCommand( "bind", Key_Bind_f ); - Cmd_SetCommandCompletionFunc( "bind", Key_CompleteBind ); - Cmd_AddCommand( "unbind", Key_Unbind_f ); - Cmd_SetCommandCompletionFunc( "unbind", Key_CompleteUnbind ); - Cmd_AddCommand( "unbindall", Key_Unbindall_f ); - Cmd_AddCommand( "bindlist", Key_Bindlist_f ); + Cmd_AddCommand("bind", Key_Bind_f); + Cmd_SetCommandCompletionFunc("bind", Key_CompleteBind); + Cmd_AddCommand("unbind", Key_Unbind_f); + Cmd_SetCommandCompletionFunc("unbind", Key_CompleteUnbind); + Cmd_AddCommand("unbindall", Key_Unbindall_f); + Cmd_AddCommand("bindlist", Key_Bindlist_f); } /* @@ -1143,13 +1112,13 @@ CL_BindUICommand Returns qtrue if bind command should be executed while user interface is shown =================== */ -static qboolean CL_BindUICommand( const char *cmd ) { - if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) +static qboolean CL_BindUICommand(const char *cmd) { + if (Key_GetCatcher() & KEYCATCH_CONSOLE) return qfalse; - if ( !Q_stricmp( cmd, "toggleconsole" ) ) + if (!Q_stricmp(cmd, "toggleconsole")) return qtrue; - if ( !Q_stricmp( cmd, "togglemenu" ) ) + if (!Q_stricmp(cmd, "togglemenu")) return qtrue; return qfalse; @@ -1162,51 +1131,45 @@ CL_ParseBinding Execute the commands in the bind string =================== */ -void CL_ParseBinding( int key, qboolean down, unsigned time ) -{ - char buf[ MAX_STRING_CHARS ], *p = buf, *end; +void CL_ParseBinding(int key, qboolean down, unsigned time) { + char buf[MAX_STRING_CHARS], *p = buf, *end; qboolean allCommands, allowUpCmds; - if( cls.state == CA_DISCONNECTED && Key_GetCatcher( ) == 0 ) + if (cls.state == CA_DISCONNECTED && Key_GetCatcher() == 0) return; - if( !kg.keys[keynames[key].upper].binding || !kg.keys[keynames[key].upper].binding[0] ) + if (!kg.keys[keynames[key].upper].binding || !kg.keys[keynames[key].upper].binding[0]) return; - Q_strncpyz( buf, kg.keys[keynames[key].upper].binding, sizeof( buf ) ); + Q_strncpyz(buf, kg.keys[keynames[key].upper].binding, sizeof(buf)); // run all bind commands if console, ui, etc aren't reading keys - allCommands = (qboolean)( Key_GetCatcher( ) == 0 ); + allCommands = (qboolean)(Key_GetCatcher() == 0); // allow button up commands if in game even if key catcher is set - allowUpCmds = (qboolean)( cls.state != CA_DISCONNECTED ); + allowUpCmds = (qboolean)(cls.state != CA_DISCONNECTED); - while( 1 ) - { - while( isspace( *p ) ) + while (1) { + while (isspace(*p)) p++; - end = strchr( p, ';' ); - if( end ) + end = strchr(p, ';'); + if (end) *end = '\0'; - if( *p == '+' ) - { + if (*p == '+') { // button commands add keynum and time as parameters // so that multiple sources can be discriminated and // subframe corrected - if ( allCommands || ( allowUpCmds && !down ) ) { + if (allCommands || (allowUpCmds && !down)) { char cmd[1024]; - Com_sprintf( cmd, sizeof( cmd ), "%c%s %d %d\n", - ( down ) ? '+' : '-', p + 1, key, time ); - Cbuf_AddText( cmd ); + Com_sprintf(cmd, sizeof(cmd), "%c%s %d %d\n", (down) ? '+' : '-', p + 1, key, time); + Cbuf_AddText(cmd); } - } - else if( down ) - { + } else if (down) { // normal commands only execute on key press - if ( allCommands || CL_BindUICommand( p ) ) { - Cbuf_AddText( p ); - Cbuf_AddText( "\n" ); + if (allCommands || CL_BindUICommand(p)) { + Cbuf_AddText(p); + Cbuf_AddText("\n"); } } - if( !end ) + if (!end) break; p = end + 1; } @@ -1219,68 +1182,65 @@ CL_KeyDownEvent Called by CL_KeyEvent to handle a keypress =================== */ -void CL_KeyDownEvent( int key, unsigned time ) -{ +void CL_KeyDownEvent(int key, unsigned time) { kg.keys[keynames[key].upper].down = qtrue; kg.keys[keynames[key].upper].repeats++; - if( kg.keys[keynames[key].upper].repeats == 1 ) { + if (kg.keys[keynames[key].upper].repeats == 1) { kg.keyDownCount++; kg.anykeydown = qtrue; } - if ( cl_allowAltEnter->integer && kg.keys[A_ALT].down && key == A_ENTER ) - { - Cvar_SetValue( "r_fullscreen", !Cvar_VariableIntegerValue( "r_fullscreen" ) ); + if (cl_allowAltEnter->integer && kg.keys[A_ALT].down && key == A_ENTER) { + Cvar_SetValue("r_fullscreen", !Cvar_VariableIntegerValue("r_fullscreen")); return; } // console key is hardcoded, so the user can never unbind it - if ( key == A_CONSOLE || (kg.keys[A_SHIFT].down && key == A_ESCAPE) ) { + if (key == A_CONSOLE || (kg.keys[A_SHIFT].down && key == A_ESCAPE)) { Con_ToggleConsole_f(); - Key_ClearStates (); + Key_ClearStates(); return; } // keys can still be used for bound actions - if ( ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) && !Key_GetCatcher() ) - { + if ((cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) && !Key_GetCatcher()) { SCR_StopCinematic(qtrue); return; -// key = A_ESCAPE; + // key = A_ESCAPE; } // escape is always handled special - if ( key == A_ESCAPE ) { - if ( !kg.keys[A_SHIFT].down && ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) { - Con_ToggleConsole_f (); - Key_ClearStates (); + if (key == A_ESCAPE) { + if (!kg.keys[A_SHIFT].down && (Key_GetCatcher() & KEYCATCH_CONSOLE)) { + Con_ToggleConsole_f(); + Key_ClearStates(); return; } - if ( !( Key_GetCatcher( ) & KEYCATCH_UI ) ) { - if ( cls.state == CA_ACTIVE ) - UI_SetActiveMenu( "ingame", NULL ); + if (!(Key_GetCatcher() & KEYCATCH_UI)) { + if (cls.state == CA_ACTIVE) + UI_SetActiveMenu("ingame", NULL); else { CL_Disconnect_f(); - UI_SetActiveMenu( "mainMenu", NULL ); + UI_SetActiveMenu("mainMenu", NULL); } return; } - _UI_KeyEvent( key, qtrue ); + _UI_KeyEvent(key, qtrue); return; } // send the bound action - CL_ParseBinding( key, qtrue, time ); + CL_ParseBinding(key, qtrue, time); // distribute the key down event to the apropriate handler - if ( Key_GetCatcher() & KEYCATCH_CONSOLE ) { - Console_Key( key ); - } else if ( Key_GetCatcher() & KEYCATCH_UI ) { - _UI_KeyEvent( key, qtrue ); - } else if ( cls.state == CA_DISCONNECTED ) { - Console_Key( key ); + if (Key_GetCatcher() & KEYCATCH_CONSOLE) { + Console_Key(key); + } else if (Key_GetCatcher() & KEYCATCH_UI) { + _UI_KeyEvent(key, qtrue); + } else if (cls.state == CA_DISCONNECTED) { + Console_Key(key); } } @@ -1291,8 +1251,7 @@ CL_KeyUpEvent Called by CL_KeyEvent to handle a keyrelease =================== */ -void CL_KeyUpEvent( int key, unsigned time ) -{ +void CL_KeyUpEvent(int key, unsigned time) { kg.keys[keynames[key].upper].repeats = 0; kg.keys[keynames[key].upper].down = qfalse; kg.keyDownCount--; @@ -1303,7 +1262,7 @@ void CL_KeyUpEvent( int key, unsigned time ) } // don't process key-up events for the console key - if ( key == A_CONSOLE || ( key == A_ESCAPE && kg.keys[A_SHIFT].down ) ) + if (key == A_CONSOLE || (key == A_ESCAPE && kg.keys[A_SHIFT].down)) return; // @@ -1312,10 +1271,10 @@ void CL_KeyUpEvent( int key, unsigned time ) // console mode and menu mode, to keep the character from continuing // an action started before a mode switch. // - CL_ParseBinding( key, qfalse, time ); + CL_ParseBinding(key, qfalse, time); - if ( Key_GetCatcher( ) & KEYCATCH_UI ) - _UI_KeyEvent( key, qfalse ); + if (Key_GetCatcher() & KEYCATCH_UI) + _UI_KeyEvent(key, qfalse); } /* @@ -1325,11 +1284,11 @@ CL_KeyEvent Called by the system for both key up and key down events =================== */ -void CL_KeyEvent (int key, qboolean down, unsigned time) { - if( down ) - CL_KeyDownEvent( key, time ); +void CL_KeyEvent(int key, qboolean down, unsigned time) { + if (down) + CL_KeyDownEvent(key, time); else - CL_KeyUpEvent( key, time ); + CL_KeyUpEvent(key, time); } /* @@ -1339,15 +1298,18 @@ CL_CharEvent Normal keyboard characters, already shifted / capslocked / etc =================== */ -void CL_CharEvent( int key ) { +void CL_CharEvent(int key) { // delete is not a printable character and is otherwise handled by Field_KeyDownEvent - if ( key == 127 ) + if (key == 127) return; // distribute the key down event to the apropriate handler - if ( Key_GetCatcher() & KEYCATCH_CONSOLE ) Field_CharEvent( &g_consoleField, key ); - else if ( Key_GetCatcher() & KEYCATCH_UI ) _UI_KeyEvent( key|K_CHAR_FLAG, qtrue ); - else if ( cls.state == CA_DISCONNECTED ) Field_CharEvent( &g_consoleField, key ); + if (Key_GetCatcher() & KEYCATCH_CONSOLE) + Field_CharEvent(&g_consoleField, key); + else if (Key_GetCatcher() & KEYCATCH_UI) + _UI_KeyEvent(key | K_CHAR_FLAG, qtrue); + else if (cls.state == CA_DISCONNECTED) + Field_CharEvent(&g_consoleField, key); } /* @@ -1355,13 +1317,13 @@ void CL_CharEvent( int key ) { Key_ClearStates =================== */ -void Key_ClearStates( void ) { +void Key_ClearStates(void) { kg.anykeydown = qfalse; kg.keyDownCount = 0; - for ( int i=0; i. #include "sys/sys_loadlib.h" #include "qcommon/ojk_saved_game.h" -#define RETRANSMIT_TIMEOUT 3000 // time between connection packet retransmits +#define RETRANSMIT_TIMEOUT 3000 // time between connection packet retransmits -cvar_t *cl_renderer; +cvar_t *cl_renderer; -cvar_t *cl_nodelta; -cvar_t *cl_debugMove; +cvar_t *cl_nodelta; +cvar_t *cl_debugMove; -cvar_t *cl_noprint; +cvar_t *cl_noprint; -cvar_t *cl_timeout; -cvar_t *cl_packetdup; -cvar_t *cl_timeNudge; -cvar_t *cl_showTimeDelta; -cvar_t *cl_newClock=0; +cvar_t *cl_timeout; +cvar_t *cl_packetdup; +cvar_t *cl_timeNudge; +cvar_t *cl_showTimeDelta; +cvar_t *cl_newClock = 0; -cvar_t *cl_shownet; -cvar_t *cl_avidemo; +cvar_t *cl_shownet; +cvar_t *cl_avidemo; -cvar_t *cl_pano; -cvar_t *cl_panoNumShots; -cvar_t *cl_skippingcin; -cvar_t *cl_endcredits; +cvar_t *cl_pano; +cvar_t *cl_panoNumShots; +cvar_t *cl_skippingcin; +cvar_t *cl_endcredits; -cvar_t *cl_freelook; -cvar_t *cl_sensitivity; +cvar_t *cl_freelook; +cvar_t *cl_sensitivity; -cvar_t *cl_mouseAccel; -cvar_t *cl_showMouseRate; -cvar_t *cl_framerate; +cvar_t *cl_mouseAccel; +cvar_t *cl_showMouseRate; +cvar_t *cl_framerate; -cvar_t *m_pitch; -cvar_t *m_yaw; -cvar_t *m_forward; -cvar_t *m_side; -cvar_t *m_filter; +cvar_t *m_pitch; +cvar_t *m_yaw; +cvar_t *m_forward; +cvar_t *m_side; +cvar_t *m_filter; -cvar_t *cl_activeAction; +cvar_t *cl_activeAction; -cvar_t *cl_allowAltEnter; +cvar_t *cl_allowAltEnter; -cvar_t *cl_inGameVideo; +cvar_t *cl_inGameVideo; -cvar_t *cl_consoleKeys; -cvar_t *cl_consoleUseScanCode; -cvar_t *cl_consoleShiftRequirement; +cvar_t *cl_consoleKeys; +cvar_t *cl_consoleUseScanCode; +cvar_t *cl_consoleShiftRequirement; -clientActive_t cl; -clientConnection_t clc; -clientStatic_t cls; +clientActive_t cl; +clientConnection_t clc; +clientStatic_t cls; // Structure containing functions exported from refresh DLL -refexport_t re; +refexport_t re; static void *rendererLib = NULL; -//RAZFIXME: BAD BAD, maybe? had to move it out of ghoul2_shared.h -> CGhoul2Info_v at the least.. -IGhoul2InfoArray &_TheGhoul2InfoArray( void ) { - return re.TheGhoul2InfoArray(); -} +// RAZFIXME: BAD BAD, maybe? had to move it out of ghoul2_shared.h -> CGhoul2Info_v at the least.. +IGhoul2InfoArray &_TheGhoul2InfoArray(void) { return re.TheGhoul2InfoArray(); } -static void CL_ShutdownRef( qboolean restarting ); -void CL_InitRef( void ); -void CL_CheckForResend( void ); +static void CL_ShutdownRef(qboolean restarting); +void CL_InitRef(void); +void CL_CheckForResend(void); /* ======================================================================= @@ -113,20 +111,20 @@ The given command will be transmitted to the server, and is gauranteed to not have future usercmd_t executed before it is executed ====================== */ -void CL_AddReliableCommand( const char *cmd ) { - int index; +void CL_AddReliableCommand(const char *cmd) { + int index; // if we would be losing an old command that hasn't been acknowledged, // we must drop the connection - if ( clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS ) { - Com_Error( ERR_DROP, "Client command overflow" ); + if (clc.reliableSequence - clc.reliableAcknowledge > MAX_RELIABLE_COMMANDS) { + Com_Error(ERR_DROP, "Client command overflow"); } clc.reliableSequence++; - index = clc.reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 ); - if ( clc.reliableCommands[ index ] ) { - Z_Free( clc.reliableCommands[ index ] ); + index = clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1); + if (clc.reliableCommands[index]) { + Z_Free(clc.reliableCommands[index]); } - clc.reliableCommands[ index ] = CopyString( cmd ); + clc.reliableCommands[index] = CopyString(cmd); } //====================================================================== @@ -140,7 +138,7 @@ ways a client gets into a game Also called by Com_Error ================= */ -void CL_FlushMemory( void ) { +void CL_FlushMemory(void) { // clear sounds (moved higher up within this func to avoid the odd sound stutter) S_DisableSounds(); @@ -150,11 +148,11 @@ void CL_FlushMemory( void ) { CL_ShutdownUI(); - if ( re.Shutdown ) { - re.Shutdown( qfalse, qfalse ); // don't destroy window or context + if (re.Shutdown) { + re.Shutdown(qfalse, qfalse); // don't destroy window or context } - //rwwFIXMEFIXME: The game server appears to continue running, so clearing common bsp data causes crashing and other bad things + // rwwFIXMEFIXME: The game server appears to continue running, so clearing common bsp data causes crashing and other bad things /* CM_ClearMap(); */ @@ -172,32 +170,32 @@ screen to let the user know about it, then dump all client memory on the hunk from cgame, ui, and renderer ===================== */ -void CL_MapLoading( void ) { - if ( !com_cl_running->integer ) { +void CL_MapLoading(void) { + if (!com_cl_running->integer) { return; } Con_Close(); - Key_SetCatcher( 0 ); + Key_SetCatcher(0); // if we are already connected to the local host, stay connected - if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) { - cls.state = CA_CONNECTED; // so the connect screen is drawn - memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) ); -// memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) ); - memset( &cl.gameState, 0, sizeof( cl.gameState ) ); + if (cls.state >= CA_CONNECTED && !Q_stricmp(cls.servername, "localhost")) { + cls.state = CA_CONNECTED; // so the connect screen is drawn + memset(cls.updateInfoString, 0, sizeof(cls.updateInfoString)); + // memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) ); + memset(&cl.gameState, 0, sizeof(cl.gameState)); clc.lastPacketSentTime = -9999; SCR_UpdateScreen(); } else { // clear nextmap so the cinematic shutdown doesn't execute it - Cvar_Set( "nextmap", "" ); + Cvar_Set("nextmap", ""); CL_Disconnect(); - Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) ); - cls.state = CA_CHALLENGING; // so the connect screen is drawn - Key_SetCatcher( 0 ); + Q_strncpyz(cls.servername, "localhost", sizeof(cls.servername)); + cls.state = CA_CHALLENGING; // so the connect screen is drawn + Key_SetCatcher(0); SCR_UpdateScreen(); clc.connectTime = -RETRANSMIT_TIMEOUT; - NET_StringToAdr( cls.servername, &clc.serverAddress); + NET_StringToAdr(cls.servername, &clc.serverAddress); // we don't need a challenge on the localhost CL_CheckForResend(); @@ -213,12 +211,12 @@ CL_ClearState Called before parsing a gamestate ===================== */ -void CL_ClearState (void) { +void CL_ClearState(void) { CL_ShutdownCGame(); S_StopAllSounds(); - memset( &cl, 0, sizeof( cl ) ); + memset(&cl, 0, sizeof(cl)); } /* @@ -228,18 +226,16 @@ CL_FreeReliableCommands Wipes all reliableCommands strings from clc ===================== */ -void CL_FreeReliableCommands( void ) -{ +void CL_FreeReliableCommands(void) { // wipe the client connection - for ( int i = 0 ; i < MAX_RELIABLE_COMMANDS ; i++ ) { - if ( clc.reliableCommands[i] ) { - Z_Free( clc.reliableCommands[i] ); - clc.reliableCommands[i] = NULL; + for (int i = 0; i < MAX_RELIABLE_COMMANDS; i++) { + if (clc.reliableCommands[i]) { + Z_Free(clc.reliableCommands[i]); + clc.reliableCommands[i] = NULL; } } } - /* ===================== CL_Disconnect @@ -250,43 +246,42 @@ Sends a disconnect message to the server This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors ===================== */ -void CL_Disconnect( void ) { - if ( !com_cl_running || !com_cl_running->integer ) { +void CL_Disconnect(void) { + if (!com_cl_running || !com_cl_running->integer) { return; } if (cls.uiStarted) - UI_SetActiveMenu( NULL,NULL ); + UI_SetActiveMenu(NULL, NULL); - SCR_StopCinematic (); + SCR_StopCinematic(); S_ClearSoundBuffer(); // send a disconnect message to the server // send it a few times in case one is dropped - if ( cls.state >= CA_CONNECTED ) { - CL_AddReliableCommand( "disconnect" ); + if (cls.state >= CA_CONNECTED) { + CL_AddReliableCommand("disconnect"); CL_WritePacket(); CL_WritePacket(); CL_WritePacket(); } - CL_ClearState (); + CL_ClearState(); CL_FreeReliableCommands(); extern void CL_FreeServerCommands(void); CL_FreeServerCommands(); - memset( &clc, 0, sizeof( clc ) ); + memset(&clc, 0, sizeof(clc)); cls.state = CA_DISCONNECTED; // allow cheats locally - Cvar_Set( "timescale", "1" );//jic we were skipping - Cvar_Set( "skippingCinematic", "0" );//jic we were skipping + Cvar_Set("timescale", "1"); // jic we were skipping + Cvar_Set("skippingCinematic", "0"); // jic we were skipping } - /* =================== CL_ForwardCommandToServer @@ -296,32 +291,31 @@ things like godmode, noclip, etc, are commands directed to the server, so when they are typed in at the console, they will need to be forwarded. =================== */ -void CL_ForwardCommandToServer( void ) { - const char *cmd; - char string[MAX_STRING_CHARS]; +void CL_ForwardCommandToServer(void) { + const char *cmd; + char string[MAX_STRING_CHARS]; cmd = Cmd_Argv(0); // ignore key up commands - if ( cmd[0] == '-' ) { + if (cmd[0] == '-') { return; } - if ( cls.state != CA_ACTIVE || cmd[0] == '+' ) { - Com_Printf ("Unknown command \"%s\"\n", cmd); + if (cls.state != CA_ACTIVE || cmd[0] == '+') { + Com_Printf("Unknown command \"%s\"\n", cmd); return; } - if ( Cmd_Argc() > 1 ) { - Com_sprintf( string, sizeof(string), "%s %s", cmd, Cmd_Args() ); + if (Cmd_Argc() > 1) { + Com_sprintf(string, sizeof(string), "%s %s", cmd, Cmd_Args()); } else { - Q_strncpyz( string, cmd, sizeof(string) ); + Q_strncpyz(string, cmd, sizeof(string)); } - CL_AddReliableCommand( string ); + CL_AddReliableCommand(string); } - /* ====================================================================== @@ -335,15 +329,15 @@ CONSOLE COMMANDS CL_ForwardToServer_f ================== */ -void CL_ForwardToServer_f( void ) { - if ( cls.state != CA_ACTIVE ) { - Com_Printf ("Not connected to a server.\n"); +void CL_ForwardToServer_f(void) { + if (cls.state != CA_ACTIVE) { + Com_Printf("Not connected to a server.\n"); return; } // don't forward the first argument - if ( Cmd_Argc() > 1 ) { - CL_AddReliableCommand( Cmd_Args() ); + if (Cmd_Argc() > 1) { + CL_AddReliableCommand(Cmd_Args()); } } @@ -352,20 +346,19 @@ void CL_ForwardToServer_f( void ) { CL_Disconnect_f ================== */ -void CL_Disconnect_f( void ) { +void CL_Disconnect_f(void) { SCR_StopCinematic(); - //FIXME: - // TA codebase added additional CA_CINEMATIC check below, presumably so they could play cinematics + // FIXME: + // TA codebase added additional CA_CINEMATIC check below, presumably so they could play cinematics // in the menus when disconnected, although having the SCR_StopCinematic() call above is weird. - // Either there's a bug, or the new version of that function conditionally-doesn't stop cinematics... + // Either there's a bug, or the new version of that function conditionally-doesn't stop cinematics... // - if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) { - Com_Error (ERR_DISCONNECT, "Disconnected from server"); + if (cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC) { + Com_Error(ERR_DISCONNECT, "Disconnected from server"); } } - /* ================= CL_Vid_Restart_f @@ -373,15 +366,15 @@ CL_Vid_Restart_f Restart the video subsystem ================= */ -void CL_Vid_Restart_f( void ) { - S_StopAllSounds(); // don't let them loop during the restart - S_BeginRegistration(); // all sound handles are now invalid +void CL_Vid_Restart_f(void) { + S_StopAllSounds(); // don't let them loop during the restart + S_BeginRegistration(); // all sound handles are now invalid CL_ShutdownRef(qtrue); CL_ShutdownUI(); CL_ShutdownCGame(); - //rww - sof2mp does this here, but it seems to cause problems in this codebase. -// CM_ClearMap(); + // rww - sof2mp does this here, but it seems to cause problems in this codebase. + // CM_ClearMap(); cls.rendererStarted = qfalse; cls.uiStarted = qfalse; @@ -393,7 +386,7 @@ void CL_Vid_Restart_f( void ) { CL_StartHunkUsers(); // unpause so the cgame definately gets a snapshot and renders a frame - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } /* @@ -405,15 +398,15 @@ The cgame and game must also be forced to restart because handles will be invalid ================= */ -void CL_Snd_Restart_f( void ) { +void CL_Snd_Restart_f(void) { S_Shutdown(); S_Init(); -// CL_Vid_Restart_f(); + // CL_Vid_Restart_f(); - extern qboolean s_soundMuted; - s_soundMuted = qfalse; // we can play again + extern qboolean s_soundMuted; + s_soundMuted = qfalse; // we can play again S_RestartMusic(); @@ -428,21 +421,21 @@ void CL_Snd_Restart_f( void ) { CL_Configstrings_f ================== */ -void CL_Configstrings_f( void ) { - int i; - int ofs; +void CL_Configstrings_f(void) { + int i; + int ofs; - if ( cls.state != CA_ACTIVE ) { - Com_Printf( "Not connected to a server.\n"); + if (cls.state != CA_ACTIVE) { + Com_Printf("Not connected to a server.\n"); return; } - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - ofs = cl.gameState.stringOffsets[ i ]; - if ( !ofs ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + ofs = cl.gameState.stringOffsets[i]; + if (!ofs) { continue; } - Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs ); + Com_Printf("%4i: %s\n", i, cl.gameState.stringData + ofs); } } @@ -451,19 +444,18 @@ void CL_Configstrings_f( void ) { CL_Clientinfo_f ============== */ -void CL_Clientinfo_f( void ) { - Com_Printf( "--------- Client Information ---------\n" ); - Com_Printf( "state: %i\n", cls.state ); - Com_Printf( "Server: %s\n", cls.servername ); - Com_Printf ("User info settings:\n"); - Info_Print( Cvar_InfoString( CVAR_USERINFO ) ); - Com_Printf( "--------------------------------------\n" ); +void CL_Clientinfo_f(void) { + Com_Printf("--------- Client Information ---------\n"); + Com_Printf("state: %i\n", cls.state); + Com_Printf("Server: %s\n", cls.servername); + Com_Printf("User info settings:\n"); + Info_Print(Cvar_InfoString(CVAR_USERINFO)); + Com_Printf("--------------------------------------\n"); } - //==================================================================== -void UI_UpdateConnectionString( const char *string ); +void UI_UpdateConnectionString(const char *string); /* ================= @@ -472,58 +464,56 @@ CL_CheckForResend Resend a connect message if the last one has timed out ================= */ -void CL_CheckForResend( void ) { - int port; - char info[MAX_INFO_STRING]; +void CL_CheckForResend(void) { + int port; + char info[MAX_INFO_STRING]; -// if ( cls.state == CA_CINEMATIC ) - if ( cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) - { + // if ( cls.state == CA_CINEMATIC ) + if (cls.state == CA_CINEMATIC || CL_IsRunningInGameCinematic()) { return; } // resend if we haven't gotten a reply yet - if ( cls.state < CA_CONNECTING || cls.state > CA_CHALLENGING ) { + if (cls.state < CA_CONNECTING || cls.state > CA_CHALLENGING) { return; } - if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) { + if (cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT) { return; } - clc.connectTime = cls.realtime; // for retransmit requests + clc.connectTime = cls.realtime; // for retransmit requests clc.connectPacketCount++; // requesting a challenge - switch ( cls.state ) { + switch (cls.state) { case CA_CONNECTING: - UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) ); + UI_UpdateConnectionString(va("(%i)", clc.connectPacketCount)); NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "getchallenge"); break; case CA_CHALLENGING: - // sending back the challenge + // sending back the challenge port = Cvar_VariableIntegerValue("net_qport"); - UI_UpdateConnectionString( va("(%i)", clc.connectPacketCount ) ); + UI_UpdateConnectionString(va("(%i)", clc.connectPacketCount)); - Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) ); - Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) ); - Info_SetValueForKey( info, "qport", va("%i", port ) ); - Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) ); - NET_OutOfBandPrint( NS_CLIENT, clc.serverAddress, "connect \"%s\"", info ); + Q_strncpyz(info, Cvar_InfoString(CVAR_USERINFO), sizeof(info)); + Info_SetValueForKey(info, "protocol", va("%i", PROTOCOL_VERSION)); + Info_SetValueForKey(info, "qport", va("%i", port)); + Info_SetValueForKey(info, "challenge", va("%i", clc.challenge)); + NET_OutOfBandPrint(NS_CLIENT, clc.serverAddress, "connect \"%s\"", info); // the most current userinfo has been sent, so watch for any // newer changes to userinfo variables cvar_modifiedFlags &= ~CVAR_USERINFO; break; default: - Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" ); + Com_Error(ERR_FATAL, "CL_CheckForResend: bad cls.state"); } } - /* =================== CL_DisconnectPacket @@ -534,28 +524,27 @@ to the server, the server will send out of band disconnect packets to the client so it doesn't have to wait for the full timeout period. =================== */ -void CL_DisconnectPacket( netadr_t from ) { - if ( cls.state != CA_ACTIVE ) { +void CL_DisconnectPacket(netadr_t from) { + if (cls.state != CA_ACTIVE) { return; } // if not from our server, ignore it - if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { + if (!NET_CompareAdr(from, clc.netchan.remoteAddress)) { return; } // if we have received packets within three seconds, ignore it // (it might be a malicious spoof) - if ( cls.realtime - clc.lastPacketTime < 3000 ) { + if (cls.realtime - clc.lastPacketTime < 3000) { return; } // drop the connection (FIXME: connection dropped dialog) - Com_Printf( "Server disconnected for unknown reason\n" ); + Com_Printf("Server disconnected for unknown reason\n"); CL_Disconnect(); } - /* ================= CL_ConnectionlessPacket @@ -563,25 +552,25 @@ CL_ConnectionlessPacket Responses to broadcasts, etc ================= */ -void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { - char *s; - const char *c; +void CL_ConnectionlessPacket(netadr_t from, msg_t *msg) { + char *s; + const char *c; - MSG_BeginReading( msg ); - MSG_ReadLong( msg ); // skip the -1 + MSG_BeginReading(msg); + MSG_ReadLong(msg); // skip the -1 - s = MSG_ReadStringLine( msg ); + s = MSG_ReadStringLine(msg); - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); c = Cmd_Argv(0); - Com_DPrintf ("CL packet %s: %s\n", NET_AdrToString(from), c); + Com_DPrintf("CL packet %s: %s\n", NET_AdrToString(from), c); // challenge from the server we are connecting to - if ( !strcmp(c, "challengeResponse") ) { - if ( cls.state != CA_CONNECTING ) { - Com_Printf( "Unwanted challenge response received. Ignored.\n" ); + if (!strcmp(c, "challengeResponse")) { + if (cls.state != CA_CONNECTING) { + Com_Printf("Unwanted challenge response received. Ignored.\n"); } else { // start sending challenge repsonse instead of challenge request packets clc.challenge = atoi(Cmd_Argv(1)); @@ -597,53 +586,50 @@ void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { } // server connection - if ( !strcmp(c, "connectResponse") ) { - if ( cls.state >= CA_CONNECTED ) { - Com_Printf ("Dup connect received. Ignored.\n"); + if (!strcmp(c, "connectResponse")) { + if (cls.state >= CA_CONNECTED) { + Com_Printf("Dup connect received. Ignored.\n"); return; } - if ( cls.state != CA_CHALLENGING ) { - Com_Printf ("connectResponse packet while not connecting. Ignored.\n"); + if (cls.state != CA_CHALLENGING) { + Com_Printf("connectResponse packet while not connecting. Ignored.\n"); return; } - if ( !NET_CompareBaseAdr( from, clc.serverAddress ) ) { - Com_Printf( "connectResponse from a different address. Ignored.\n" ); - Com_Printf( "%s should have been %s\n", NET_AdrToString( from ), - NET_AdrToString( clc.serverAddress ) ); + if (!NET_CompareBaseAdr(from, clc.serverAddress)) { + Com_Printf("connectResponse from a different address. Ignored.\n"); + Com_Printf("%s should have been %s\n", NET_AdrToString(from), NET_AdrToString(clc.serverAddress)); return; } - Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableIntegerValue( "net_qport" ) ); + Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableIntegerValue("net_qport")); cls.state = CA_CONNECTED; - clc.lastPacketSentTime = -9999; // send first packet immediately + clc.lastPacketSentTime = -9999; // send first packet immediately return; } // a disconnect message from the server, which will happen if the server // dropped the connection but it is still getting packets from us if (!strcmp(c, "disconnect")) { - CL_DisconnectPacket( from ); + CL_DisconnectPacket(from); return; } // echo request from server - if ( !strcmp(c, "echo") ) { - NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) ); + if (!strcmp(c, "echo")) { + NET_OutOfBandPrint(NS_CLIENT, from, "%s", Cmd_Argv(1)); return; } // print request from server - if ( !strcmp(c, "print") ) { - s = MSG_ReadString( msg ); - UI_UpdateConnectionMessageString( s ); - Com_Printf( "%s", s ); + if (!strcmp(c, "print")) { + s = MSG_ReadString(msg); + UI_UpdateConnectionMessageString(s); + Com_Printf("%s", s); return; } - - Com_DPrintf ("Unknown connectionless packet command.\n"); + Com_DPrintf("Unknown connectionless packet command.\n"); } - /* ================= CL_PacketEvent @@ -651,39 +637,38 @@ CL_PacketEvent A packet has arrived from the main event loop ================= */ -void CL_PacketEvent( netadr_t from, msg_t *msg ) { +void CL_PacketEvent(netadr_t from, msg_t *msg) { clc.lastPacketTime = cls.realtime; - if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) { - CL_ConnectionlessPacket( from, msg ); + if (msg->cursize >= 4 && *(int *)msg->data == -1) { + CL_ConnectionlessPacket(from, msg); return; } - if ( cls.state < CA_CONNECTED ) { - return; // can't be a valid sequenced packet + if (cls.state < CA_CONNECTED) { + return; // can't be a valid sequenced packet } - if ( msg->cursize < 8 ) { - Com_Printf ("%s: Runt packet\n",NET_AdrToString( from )); + if (msg->cursize < 8) { + Com_Printf("%s: Runt packet\n", NET_AdrToString(from)); return; } // // packet from server // - if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { - Com_DPrintf ("%s:sequenced packet without connection\n" - ,NET_AdrToString( from ) ); + if (!NET_CompareAdr(from, clc.netchan.remoteAddress)) { + Com_DPrintf("%s:sequenced packet without connection\n", NET_AdrToString(from)); // FIXME: send a client disconnect? return; } - if (!Netchan_Process( &clc.netchan, msg) ) { - return; // out of order, duplicated, etc + if (!Netchan_Process(&clc.netchan, msg)) { + return; // out of order, duplicated, etc } clc.lastPacketTime = cls.realtime; - CL_ParseServerMessage( msg ); + CL_ParseServerMessage(msg); } /* @@ -692,17 +677,17 @@ CL_CheckTimeout ================== */ -void CL_CheckTimeout( void ) { +void CL_CheckTimeout(void) { // // check timeout // - if ( ( !CL_CheckPaused() || !sv_paused->integer ) -// && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC - && cls.state >= CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic()) - && cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) { - if (++cl.timeoutcount > 5) { // timeoutcount saves debugger - Com_Printf ("\nServer connection timed out.\n"); - CL_Disconnect (); + if ((!CL_CheckPaused() || !sv_paused->integer) + // && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC + && cls.state >= CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic()) && + cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000) { + if (++cl.timeoutcount > 5) { // timeoutcount saves debugger + Com_Printf("\nServer connection timed out.\n"); + CL_Disconnect(); return; } } else { @@ -716,12 +701,11 @@ CL_CheckPaused Check whether client has been paused. ================== */ -qboolean CL_CheckPaused(void) -{ +qboolean CL_CheckPaused(void) { // if cl_paused->modified is set, the cvar has only been changed in // this frame. Keep paused in this frame to ensure the server doesn't // lag behind. - if(cl_paused->integer || cl_paused->modified) + if (cl_paused->integer || cl_paused->modified) return qtrue; return qfalse; @@ -735,59 +719,55 @@ CL_CheckUserinfo ================== */ -void CL_CheckUserinfo( void ) { - if ( cls.state < CA_CHALLENGING ) { +void CL_CheckUserinfo(void) { + if (cls.state < CA_CHALLENGING) { return; } // don't overflow the reliable command buffer when paused - if ( CL_CheckPaused() ) { + if (CL_CheckPaused()) { return; } // send a reliable userinfo update if needed - if ( cvar_modifiedFlags & CVAR_USERINFO ) { + if (cvar_modifiedFlags & CVAR_USERINFO) { cvar_modifiedFlags &= ~CVAR_USERINFO; - CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ) ); + CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString(CVAR_USERINFO))); } - } - /* ================== CL_Frame ================== */ -extern cvar_t *cl_newClock; +extern cvar_t *cl_newClock; static unsigned int frameCount; -float avgFrametime=0.0; -void CL_Frame ( int msec,float fractionMsec ) { +float avgFrametime = 0.0; +void CL_Frame(int msec, float fractionMsec) { - if ( !com_cl_running->integer ) { + if (!com_cl_running->integer) { return; } // load the ref / cgame if needed CL_StartHunkUsers(); - if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI ) - && !com_sv_running->integer ) { + if (cls.state == CA_DISCONNECTED && !(Key_GetCatcher() & KEYCATCH_UI) && !com_sv_running->integer) { // if disconnected, bring up the menu - if (!CL_CheckPendingCinematic()) // this avoid having the menu flash for one frame before pending cinematics + if (!CL_CheckPendingCinematic()) // this avoid having the menu flash for one frame before pending cinematics { - UI_SetActiveMenu( "mainMenu",NULL ); + UI_SetActiveMenu("mainMenu", NULL); } } - // if recording an avi, lock to a fixed fps - if ( cl_avidemo->integer ) { + if (cl_avidemo->integer) { // save the current screen - if ( cls.state == CA_ACTIVE ) { + if (cls.state == CA_ACTIVE) { if (cl_avidemo->integer > 0) { - Cbuf_ExecuteText( EXEC_NOW, "screenshot silent\n" ); + Cbuf_ExecuteText(EXEC_NOW, "screenshot silent\n"); } else { - Cbuf_ExecuteText( EXEC_NOW, "screenshot_tga silent\n" ); + Cbuf_ExecuteText(EXEC_NOW, "screenshot_tga silent\n"); } } // fixed time for next frame @@ -803,32 +783,28 @@ void CL_Frame ( int msec,float fractionMsec ) { // decide the simulation time cls.frametime = msec; - if(cl_framerate->integer) - { - avgFrametime+=msec; + if (cl_framerate->integer) { + avgFrametime += msec; char mess[256]; - if(!(frameCount&0x1f)) - { - sprintf(mess,"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f))); - // OutputDebugString(mess); + if (!(frameCount & 0x1f)) { + sprintf(mess, "Frame rate=%f\n\n", 1000.0f * (1.0 / (avgFrametime / 32.0f))); + // OutputDebugString(mess); Com_Printf(mess); - avgFrametime=0.0f; + avgFrametime = 0.0f; } frameCount++; } - cls.frametimeFraction=fractionMsec; + cls.frametimeFraction = fractionMsec; cls.realtime += msec; - cls.realtimeFraction+=fractionMsec; - if (cls.realtimeFraction>=1.0f) - { - if (cl_newClock&&cl_newClock->integer) - { + cls.realtimeFraction += fractionMsec; + if (cls.realtimeFraction >= 1.0f) { + if (cl_newClock && cl_newClock->integer) { cls.realtime++; } - cls.realtimeFraction-=1.0f; + cls.realtimeFraction -= 1.0f; } - if ( cl_timegraph->integer ) { - SCR_DebugGraph ( cls.realFrametime * 0.25, 0 ); + if (cl_timegraph->integer) { + SCR_DebugGraph(cls.realFrametime * 0.25, 0); } // see if we need to update any userinfo @@ -847,26 +823,26 @@ void CL_Frame ( int msec,float fractionMsec ) { // decide on the serverTime to render CL_SetCGameTime(); - if (cl_pano->integer && cls.state == CA_ACTIVE) { //grab some panoramic shots + if (cl_pano->integer && cls.state == CA_ACTIVE) { // grab some panoramic shots int i = 1; int pref = cl_pano->integer; int oldnoprint = cl_noprint->integer; Con_Close(); - cl_noprint->integer = 1; //hide the screen shot msgs + cl_noprint->integer = 1; // hide the screen shot msgs for (; i <= cl_panoNumShots->integer; i++) { - Cvar_SetValue( "pano", i ); - SCR_UpdateScreen();// update the screen - Cbuf_ExecuteText( EXEC_NOW, va("screenshot %dpano%02d\n", pref, i) ); //grab this screen + Cvar_SetValue("pano", i); + SCR_UpdateScreen(); // update the screen + Cbuf_ExecuteText(EXEC_NOW, va("screenshot %dpano%02d\n", pref, i)); // grab this screen } - Cvar_SetValue( "pano", 0 ); //done + Cvar_SetValue("pano", 0); // done cl_noprint->integer = oldnoprint; } - if (cl_skippingcin->integer && !cl_endcredits->integer && !com_developer->integer ) { - if (cl_skippingcin->modified){ - S_StopSounds(); //kill em all but music - cl_skippingcin->modified=qfalse; - Com_Printf (S_COLOR_YELLOW "%s", SE_GetString("CON_TEXT_SKIPPING")); + if (cl_skippingcin->integer && !cl_endcredits->integer && !com_developer->integer) { + if (cl_skippingcin->modified) { + S_StopSounds(); // kill em all but music + cl_skippingcin->modified = qfalse; + Com_Printf(S_COLOR_YELLOW "%s", SE_GetString("CON_TEXT_SKIPPING")); SCR_UpdateScreen(); } } else { @@ -891,15 +867,15 @@ void CL_Frame ( int msec,float fractionMsec ) { CL_ShutdownRef ============ */ -static void CL_ShutdownRef( qboolean restarting ) { - if ( re.Shutdown ) { - re.Shutdown( qtrue, restarting ); +static void CL_ShutdownRef(qboolean restarting) { + if (re.Shutdown) { + re.Shutdown(qtrue, restarting); } - memset( &re, 0, sizeof( re ) ); + memset(&re, 0, sizeof(re)); - if ( rendererLib != NULL ) { - Sys_UnloadDll (rendererLib); + if (rendererLib != NULL) { + Sys_UnloadDll(rendererLib); rendererLib = NULL; } } @@ -912,13 +888,13 @@ Convenience function for the sound system to be started REALLY early on Xbox, helps with memory fragmentation. ============================ */ -void CL_StartSound( void ) { - if ( !cls.soundStarted ) { +void CL_StartSound(void) { + if (!cls.soundStarted) { cls.soundStarted = qtrue; S_Init(); } - if ( !cls.soundRegistered ) { + if (!cls.soundRegistered) { cls.soundRegistered = qtrue; S_BeginRegistration(); } @@ -929,15 +905,15 @@ void CL_StartSound( void ) { CL_InitRenderer ============ */ -void CL_InitRenderer( void ) { +void CL_InitRenderer(void) { // this sets up the renderer and calls R_Init - re.BeginRegistration( &cls.glconfig ); + re.BeginRegistration(&cls.glconfig); // load character sets cls.charSetShader = re.RegisterShaderNoMip("gfx/2d/charsgrid_med"); - cls.consoleFont = re.RegisterFont( "ocr_a" ); - cls.whiteShader = re.RegisterShader( "white" ); - cls.consoleShader = re.RegisterShader( "console" ); + cls.consoleFont = re.RegisterFont("ocr_a"); + cls.whiteShader = re.RegisterShader("white"); + cls.consoleShader = re.RegisterShader("console"); g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2; g_consoleField.widthInChars = g_console_field_width; } @@ -950,35 +926,34 @@ After the server has cleared the hunk, these will need to be restarted This is the only place that any of these functions are called from ============================ */ -void CL_StartHunkUsers( void ) { - if ( !com_cl_running->integer ) { +void CL_StartHunkUsers(void) { + if (!com_cl_running->integer) { return; } - if ( !cls.rendererStarted ) { + if (!cls.rendererStarted) { cls.rendererStarted = qtrue; CL_InitRenderer(); } - if ( !cls.soundStarted ) { + if (!cls.soundStarted) { cls.soundStarted = qtrue; S_Init(); } - if ( !cls.soundRegistered ) { + if (!cls.soundRegistered) { cls.soundRegistered = qtrue; S_BeginRegistration(); } - //we require the ui to be loaded here or else it crashes trying to access the ui on command line map loads - if ( !cls.uiStarted ) { + // we require the ui to be loaded here or else it crashes trying to access the ui on command line map loads + if (!cls.uiStarted) { cls.uiStarted = qtrue; CL_InitUI(); } -// if ( !cls.cgameStarted && cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) { - if ( !cls.cgameStarted && cls.state > CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic()) ) - { + // if ( !cls.cgameStarted && cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) { + if (!cls.cgameStarted && cls.state > CA_CONNECTED && (cls.state != CA_CINEMATIC && !CL_IsRunningInGameCinematic())) { cls.cgameStarted = qtrue; CL_InitCGame(); } @@ -991,20 +966,20 @@ CL_RefPrintf DLL glue ================ */ -void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL CL_RefPrintf(int print_level, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf(msg, sizeof(msg), fmt, argptr); - va_end (argptr); - - if ( print_level == PRINT_ALL ) { - Com_Printf ("%s", msg); - } else if ( print_level == PRINT_WARNING ) { - Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow - } else if ( print_level == PRINT_DEVELOPER ) { - Com_DPrintf (S_COLOR_RED "%s", msg); // red + va_end(argptr); + + if (print_level == PRINT_ALL) { + Com_Printf("%s", msg); + } else if (print_level == PRINT_WARNING) { + Com_Printf(S_COLOR_YELLOW "%s", msg); // yellow + } else if (print_level == PRINT_DEVELOPER) { + Com_DPrintf(S_COLOR_RED "%s", msg); // red } } @@ -1016,8 +991,7 @@ DLL glue, but highly reusuable DLL glue at that ============ */ -const char *String_GetStringValue( const char *reference ) -{ +const char *String_GetStringValue(const char *reference) { #ifndef JK2_MODE return SE_GetString(reference); #else @@ -1027,91 +1001,70 @@ const char *String_GetStringValue( const char *reference ) extern qboolean gbAlreadyDoingLoad; extern void *gpvCachedMapDiskImage; -extern char gsCachedMapDiskImage[MAX_QPATH]; +extern char gsCachedMapDiskImage[MAX_QPATH]; extern qboolean gbUsingCachedMapDataRightNow; -char *get_gsCachedMapDiskImage( void ) -{ - return gsCachedMapDiskImage; -} +char *get_gsCachedMapDiskImage(void) { return gsCachedMapDiskImage; } -void *get_gpvCachedMapDiskImage( void ) -{ - return gpvCachedMapDiskImage; -} +void *get_gpvCachedMapDiskImage(void) { return gpvCachedMapDiskImage; } -qboolean *get_gbUsingCachedMapDataRightNow( void ) -{ - return &gbUsingCachedMapDataRightNow; -} +qboolean *get_gbUsingCachedMapDataRightNow(void) { return &gbUsingCachedMapDataRightNow; } -qboolean *get_gbAlreadyDoingLoad( void ) -{ - return &gbAlreadyDoingLoad; -} +qboolean *get_gbAlreadyDoingLoad(void) { return &gbAlreadyDoingLoad; } -int get_com_frameTime( void ) -{ - return com_frameTime; -} +int get_com_frameTime(void) { return com_frameTime; } -void *CL_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign) -{ - return Z_Malloc(iSize, eTag, bZeroit); -} +void *CL_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign) { return Z_Malloc(iSize, eTag, bZeroit); } /* ============ CL_InitRef ============ */ -extern qboolean S_FileExists( const char *psFilename ); -extern bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds); +extern qboolean S_FileExists(const char *psFilename); +extern bool CM_CullWorldBox(const cplane_t *frustum, const vec3pair_t bounds); extern qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */); -extern cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force); +extern cvar_t *Cvar_Set2(const char *var_name, const char *value, qboolean force); extern CMiniHeap *G2VertSpaceServer; -static CMiniHeap *GetG2VertSpaceServer( void ) { - return G2VertSpaceServer; -} +static CMiniHeap *GetG2VertSpaceServer(void) { return G2VertSpaceServer; } // NOTENOTE: If you change the output name of rd-vanilla, change this define too! #ifdef JK2_MODE -#define DEFAULT_RENDER_LIBRARY "rdjosp-vanilla" +#define DEFAULT_RENDER_LIBRARY "rdjosp-vanilla" #else -#define DEFAULT_RENDER_LIBRARY "rdsp-vanilla" +#define DEFAULT_RENDER_LIBRARY "rdsp-vanilla" #endif -void CL_InitRef( void ) { - refexport_t *ret; +void CL_InitRef(void) { + refexport_t *ret; static refimport_t rit; - char dllName[MAX_OSPATH]; - GetRefAPI_t GetRefAPI; + char dllName[MAX_OSPATH]; + GetRefAPI_t GetRefAPI; - Com_Printf( "----- Initializing Renderer ----\n" ); - cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH ); + Com_Printf("----- Initializing Renderer ----\n"); + cl_renderer = Cvar_Get("cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE | CVAR_LATCH); - Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string ); + Com_sprintf(dllName, sizeof(dllName), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string); - if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) ) - { - Com_Printf( "failed: trying to load fallback renderer\n" ); - Cvar_ForceReset( "cl_renderer" ); + if (!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { + Com_Printf("failed: trying to load fallback renderer\n"); + Cvar_ForceReset("cl_renderer"); - Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT ); - rendererLib = Sys_LoadDll( dllName, qfalse ); + Com_sprintf(dllName, sizeof(dllName), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT); + rendererLib = Sys_LoadDll(dllName, qfalse); } - if ( !rendererLib ) { - Com_Error( ERR_FATAL, "Failed to load renderer\n" ); + if (!rendererLib) { + Com_Error(ERR_FATAL, "Failed to load renderer\n"); } - memset( &rit, 0, sizeof( rit ) ); + memset(&rit, 0, sizeof(rit)); - GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" ); - if ( !GetRefAPI ) - Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() ); + GetRefAPI = (GetRefAPI_t)Sys_LoadFunction(rendererLib, "GetRefAPI"); + if (!GetRefAPI) + Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); -#define RIT(y) rit.y = y +#define RIT(y) rit.y = y RIT(CIN_PlayCinematic); RIT(CIN_RunCinematic); RIT(CIN_UploadCinematic); @@ -1149,20 +1102,20 @@ void CL_InitRef( void ) { RIT(FS_WriteFile); RIT(Hunk_ClearToMark); RIT(SND_RegisterAudio_LevelLoadEnd); - //RIT(SV_PointContents); + // RIT(SV_PointContents); RIT(SV_Trace); RIT(S_RestartMusic); RIT(Z_Free); - rit.Malloc=CL_Malloc; + rit.Malloc = CL_Malloc; RIT(Z_MemSize); RIT(Z_MorphMallocTag); RIT(Hunk_ClearToMark); - rit.WIN_Init = WIN_Init; + rit.WIN_Init = WIN_Init; rit.WIN_SetGamma = WIN_SetGamma; - rit.WIN_Shutdown = WIN_Shutdown; - rit.WIN_Present = WIN_Present; + rit.WIN_Shutdown = WIN_Shutdown; + rit.WIN_Present = WIN_Present; rit.GL_GetProcAddress = WIN_GL_GetProcAddress; rit.GL_ExtensionSupported = WIN_GL_ExtensionSupported; @@ -1189,165 +1142,164 @@ void CL_InitRef( void ) { rit.saved_game = &ojk::SavedGame::get_instance(); - ret = GetRefAPI( REF_API_VERSION, &rit ); + ret = GetRefAPI(REF_API_VERSION, &rit); - if ( !ret ) { - Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); + if (!ret) { + Com_Error(ERR_FATAL, "Couldn't initialize refresh"); } re = *ret; - Com_Printf( "-------------------------------\n"); + Com_Printf("-------------------------------\n"); // unpause so the cgame definately gets a snapshot and renders a frame - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } - //=========================================================================================== -void CL_CompleteCinematic( char *args, int argNum ); +void CL_CompleteCinematic(char *args, int argNum); /* ==================== CL_Init ==================== */ -void CL_Init( void ) { - Com_Printf( "----- Client Initialization -----\n" ); +void CL_Init(void) { + Com_Printf("----- Client Initialization -----\n"); #ifdef JK2_MODE - JK2SP_Register("con_text", SP_REGISTER_REQUIRED); //reference is CON_TEXT - JK2SP_Register("keynames", SP_REGISTER_REQUIRED); // reference is KEYNAMES + JK2SP_Register("con_text", SP_REGISTER_REQUIRED); // reference is CON_TEXT + JK2SP_Register("keynames", SP_REGISTER_REQUIRED); // reference is KEYNAMES #endif - Con_Init (); + Con_Init(); - CL_ClearState (); + CL_ClearState(); - cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED - //cls.keyCatchers = KEYCATCH_CONSOLE; + cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED + // cls.keyCatchers = KEYCATCH_CONSOLE; cls.realtime = 0; - cls.realtimeFraction=0.0f; // fraction of a msec accumulated + cls.realtimeFraction = 0.0f; // fraction of a msec accumulated - CL_InitInput (); + CL_InitInput(); // // register our variables // - cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); + cl_noprint = Cvar_Get("cl_noprint", "0", 0); - cl_timeout = Cvar_Get ("cl_timeout", "125", 0); + cl_timeout = Cvar_Get("cl_timeout", "125", 0); - cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); - cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); - cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); - cl_newClock = Cvar_Get ("cl_newClock", "1", 0); - cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); + cl_timeNudge = Cvar_Get("cl_timeNudge", "0", CVAR_TEMP); + cl_shownet = Cvar_Get("cl_shownet", "0", CVAR_TEMP); + cl_showTimeDelta = Cvar_Get("cl_showTimeDelta", "0", CVAR_TEMP); + cl_newClock = Cvar_Get("cl_newClock", "1", 0); + cl_activeAction = Cvar_Get("activeAction", "", CVAR_TEMP); - cl_avidemo = Cvar_Get ("cl_avidemo", "0", 0); - cl_pano = Cvar_Get ("pano", "0", 0); - cl_panoNumShots= Cvar_Get ("panoNumShots", "10", CVAR_ARCHIVE_ND); - cl_skippingcin = Cvar_Get ("skippingCinematic", "0", CVAR_ROM); - cl_endcredits = Cvar_Get ("cg_endcredits", "0", 0); + cl_avidemo = Cvar_Get("cl_avidemo", "0", 0); + cl_pano = Cvar_Get("pano", "0", 0); + cl_panoNumShots = Cvar_Get("panoNumShots", "10", CVAR_ARCHIVE_ND); + cl_skippingcin = Cvar_Get("skippingCinematic", "0", CVAR_ROM); + cl_endcredits = Cvar_Get("cg_endcredits", "0", 0); - cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE_ND); - cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE_ND); - cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE_ND); + cl_yawspeed = Cvar_Get("cl_yawspeed", "140", CVAR_ARCHIVE_ND); + cl_pitchspeed = Cvar_Get("cl_pitchspeed", "140", CVAR_ARCHIVE_ND); + cl_anglespeedkey = Cvar_Get("cl_anglespeedkey", "1.5", CVAR_ARCHIVE_ND); - cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE_ND ); + cl_packetdup = Cvar_Get("cl_packetdup", "1", CVAR_ARCHIVE_ND); - cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE_ND); - cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); - cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE_ND); - cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE_ND ); + cl_run = Cvar_Get("cl_run", "1", CVAR_ARCHIVE_ND); + cl_sensitivity = Cvar_Get("sensitivity", "5", CVAR_ARCHIVE); + cl_mouseAccel = Cvar_Get("cl_mouseAccel", "0", CVAR_ARCHIVE_ND); + cl_freelook = Cvar_Get("cl_freelook", "1", CVAR_ARCHIVE_ND); - cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); + cl_showMouseRate = Cvar_Get("cl_showmouserate", "0", 0); - cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE_ND); - cl_inGameVideo = Cvar_Get ("cl_inGameVideo", "1", CVAR_ARCHIVE_ND); - cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP); + cl_allowAltEnter = Cvar_Get("cl_allowAltEnter", "1", CVAR_ARCHIVE_ND); + cl_inGameVideo = Cvar_Get("cl_inGameVideo", "1", CVAR_ARCHIVE_ND); + cl_framerate = Cvar_Get("cl_framerate", "0", CVAR_TEMP); // init autoswitch so the ui will have it correctly even // if the cgame hasn't been started - Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); + Cvar_Get("cg_autoswitch", "1", CVAR_ARCHIVE); - m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE_ND); - m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE_ND); - m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE_ND); - m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE_ND); - m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE_ND); + m_pitch = Cvar_Get("m_pitch", "0.022", CVAR_ARCHIVE_ND); + m_yaw = Cvar_Get("m_yaw", "0.022", CVAR_ARCHIVE_ND); + m_forward = Cvar_Get("m_forward", "0.25", CVAR_ARCHIVE_ND); + m_side = Cvar_Get("m_side", "0.25", CVAR_ARCHIVE_ND); + m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE_ND); // ~ and `, as keys and characters - cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE); - cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE ); - cl_consoleShiftRequirement = Cvar_Get( "cl_consoleShiftRequirement", "0", CVAR_ARCHIVE ); + cl_consoleKeys = Cvar_Get("cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE); + cl_consoleUseScanCode = Cvar_Get("cl_consoleUseScanCode", "1", CVAR_ARCHIVE); + cl_consoleShiftRequirement = Cvar_Get("cl_consoleShiftRequirement", "0", CVAR_ARCHIVE); // userinfo #ifdef JK2_MODE - Cvar_Get ("name", "Kyle", CVAR_USERINFO | CVAR_ARCHIVE_ND ); + Cvar_Get("name", "Kyle", CVAR_USERINFO | CVAR_ARCHIVE_ND); #else - Cvar_Get ("name", "Jaden", CVAR_USERINFO | CVAR_ARCHIVE_ND ); + Cvar_Get("name", "Jaden", CVAR_USERINFO | CVAR_ARCHIVE_ND); #endif #ifdef JK2_MODE // this is required for savegame compatibility - not ever actually used - Cvar_Get ("snaps", "20", CVAR_USERINFO ); - Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); - Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME ); + Cvar_Get("snaps", "20", CVAR_USERINFO); + Cvar_Get("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE); + Cvar_Get("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME); #else - Cvar_Get ("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART ); - Cvar_Get ("snd", "jaden_fmle", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART );//UI_SetSexandSoundForModel changes to match sounds.cfg for model - Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME | CVAR_NORESTART); + Cvar_Get("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + Cvar_Get("snd", "jaden_fmle", + CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); // UI_SetSexandSoundForModel changes to match sounds.cfg for model + Cvar_Get("handicap", "100", CVAR_USERINFO | CVAR_SAVEGAME | CVAR_NORESTART); #endif // // register our commands // - Cmd_AddCommand ("cmd", CL_ForwardToServer_f); - Cmd_AddCommand ("configstrings", CL_Configstrings_f); - Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); - Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); - Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); - Cmd_AddCommand ("disconnect", CL_Disconnect_f); - Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); - Cmd_SetCommandCompletionFunc( "cinematic", CL_CompleteCinematic ); - Cmd_AddCommand ("ingamecinematic", CL_PlayInGameCinematic_f); - Cmd_AddCommand ("uimenu", CL_GenericMenu_f); - Cmd_AddCommand ("datapad", CL_DataPad_f); - Cmd_AddCommand ("endscreendissolve", CL_EndScreenDissolve_f); + Cmd_AddCommand("cmd", CL_ForwardToServer_f); + Cmd_AddCommand("configstrings", CL_Configstrings_f); + Cmd_AddCommand("clientinfo", CL_Clientinfo_f); + Cmd_AddCommand("snd_restart", CL_Snd_Restart_f); + Cmd_AddCommand("vid_restart", CL_Vid_Restart_f); + Cmd_AddCommand("disconnect", CL_Disconnect_f); + Cmd_AddCommand("cinematic", CL_PlayCinematic_f); + Cmd_SetCommandCompletionFunc("cinematic", CL_CompleteCinematic); + Cmd_AddCommand("ingamecinematic", CL_PlayInGameCinematic_f); + Cmd_AddCommand("uimenu", CL_GenericMenu_f); + Cmd_AddCommand("datapad", CL_DataPad_f); + Cmd_AddCommand("endscreendissolve", CL_EndScreenDissolve_f); CL_InitRef(); CL_StartHunkUsers(); - SCR_Init (); + SCR_Init(); - Cbuf_Execute (); + Cbuf_Execute(); - Cvar_Set( "cl_running", "1" ); + Cvar_Set("cl_running", "1"); - Com_Printf( "----- Client Initialization Complete -----\n" ); + Com_Printf("----- Client Initialization Complete -----\n"); } - /* =============== CL_Shutdown =============== */ -void CL_Shutdown( void ) { +void CL_Shutdown(void) { static qboolean recursive = qfalse; - if ( !com_cl_running || !com_cl_running->integer ) { + if (!com_cl_running || !com_cl_running->integer) { return; } - Com_Printf( "----- CL_Shutdown -----\n" ); + Com_Printf("----- CL_Shutdown -----\n"); - if ( recursive ) { - Com_Printf( "WARNING: Recursive CL_Shutdown called!\n" ); + if (recursive) { + Com_Printf("WARNING: Recursive CL_Shutdown called!\n"); return; } recursive = qtrue; @@ -1358,24 +1310,23 @@ void CL_Shutdown( void ) { S_Shutdown(); CL_ShutdownRef(qfalse); - Cmd_RemoveCommand ("cmd"); - Cmd_RemoveCommand ("configstrings"); - Cmd_RemoveCommand ("clientinfo"); - Cmd_RemoveCommand ("snd_restart"); - Cmd_RemoveCommand ("vid_restart"); - Cmd_RemoveCommand ("disconnect"); - Cmd_RemoveCommand ("cinematic"); - Cmd_RemoveCommand ("ingamecinematic"); - Cmd_RemoveCommand ("uimenu"); - Cmd_RemoveCommand ("datapad"); - Cmd_RemoveCommand ("endscreendissolve"); + Cmd_RemoveCommand("cmd"); + Cmd_RemoveCommand("configstrings"); + Cmd_RemoveCommand("clientinfo"); + Cmd_RemoveCommand("snd_restart"); + Cmd_RemoveCommand("vid_restart"); + Cmd_RemoveCommand("disconnect"); + Cmd_RemoveCommand("cinematic"); + Cmd_RemoveCommand("ingamecinematic"); + Cmd_RemoveCommand("uimenu"); + Cmd_RemoveCommand("datapad"); + Cmd_RemoveCommand("endscreendissolve"); - Cvar_Set( "cl_running", "0" ); + Cvar_Set("cl_running", "0"); recursive = qfalse; - memset( &cls, 0, sizeof( cls ) ); + memset(&cls, 0, sizeof(cls)); - Com_Printf( "-----------------------\n" ); + Com_Printf("-----------------------\n"); } - diff --git a/code/client/cl_mp3.cpp b/code/client/cl_mp3.cpp index c397a494f4..b8ae13cbd8 100644 --- a/code/client/cl_mp3.cpp +++ b/code/client/cl_mp3.cpp @@ -26,46 +26,42 @@ along with this program; if not, see . #include "../server/exe_headers.h" #include "client.h" -#include "cl_mp3.h" // only included directly by a few snd_xxxx.cpp files plus this one -#include "../mp3code/mp3struct.h" // keep this rather awful file secret from the rest of the program +#include "cl_mp3.h" // only included directly by a few snd_xxxx.cpp files plus this one +#include "../mp3code/mp3struct.h" // keep this rather awful file secret from the rest of the program // expects data already loaded, filename arg is for error printing only // // returns success/fail // -qboolean MP3_IsValid( const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) -{ +qboolean MP3_IsValid(const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) { char *psError = C_MP3_IsValid(pvData, iDataLen, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s(%s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s(%s)\n", psError, psLocalFilename)); } return (qboolean)(!psError); } - - // expects data already loaded, filename arg is for error printing only // // returns unpacked length, or 0 for errors (which will be printed internally) // -int MP3_GetUnpackedSize( const char *psLocalFilename, void *pvData, int iDataLen, qboolean qbIgnoreID3Tag /* = qfalse */ - , qboolean bStereoDesired /* = qfalse */ - ) -{ - int iUnpackedSize = 0; - - // always do this now that we have fast-unpack code for measuring output size... (much safer than relying on tags that may have been edited, or if MP3 has been re-saved with same tag) +int MP3_GetUnpackedSize(const char *psLocalFilename, void *pvData, int iDataLen, qboolean qbIgnoreID3Tag /* = qfalse */ + , + qboolean bStereoDesired /* = qfalse */ +) { + int iUnpackedSize = 0; + + // always do this now that we have fast-unpack code for measuring output size... (much safer than relying on tags that may have been edited, or if MP3 has + // been re-saved with same tag) // - if (1)//qbIgnoreID3Tag || !MP3_ReadSpecialTagInfo((byte *)pvData, iDataLen, NULL, &iUnpackedSize)) + if (1) // qbIgnoreID3Tag || !MP3_ReadSpecialTagInfo((byte *)pvData, iDataLen, NULL, &iUnpackedSize)) { - char *psError = C_MP3_GetUnpackedSize( pvData, iDataLen, &iUnpackedSize, bStereoDesired); + char *psError = C_MP3_GetUnpackedSize(pvData, iDataLen, &iUnpackedSize, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); return 0; } } @@ -73,50 +69,41 @@ int MP3_GetUnpackedSize( const char *psLocalFilename, void *pvData, int iDataLen return iUnpackedSize; } - - // expects data already loaded, filename arg is for error printing only // // returns byte count of unpacked data (effectively a success/fail bool) // -int MP3_UnpackRawPCM( const char *psLocalFilename, void *pvData, int iDataLen, byte *pbUnpackBuffer, qboolean bStereoDesired /* = qfalse */) -{ +int MP3_UnpackRawPCM(const char *psLocalFilename, void *pvData, int iDataLen, byte *pbUnpackBuffer, qboolean bStereoDesired /* = qfalse */) { int iUnpackedSize; - char *psError = C_MP3_UnpackRawPCM( pvData, iDataLen, &iUnpackedSize, pbUnpackBuffer, bStereoDesired); + char *psError = C_MP3_UnpackRawPCM(pvData, iDataLen, &iUnpackedSize, pbUnpackBuffer, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); return 0; } return iUnpackedSize; } - // psLocalFilename is just for error reporting (if any)... // -qboolean MP3Stream_InitPlayingTimeFields( LP_MP3STREAM lpMP3Stream, const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) -{ +qboolean MP3Stream_InitPlayingTimeFields(LP_MP3STREAM lpMP3Stream, const char *psLocalFilename, void *pvData, int iDataLen, + qboolean bStereoDesired /* = qfalse */) { qboolean bRetval = qfalse; int iRate, iWidth, iChannels; - char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &iRate, &iWidth, &iChannels, bStereoDesired ); - if (psError) - { - Com_Printf(va(S_COLOR_RED"MP3Stream_InitPlayingTimeFields(): %s\n(File: %s)\n",psError, psLocalFilename)); - } - else - { - int iUnpackLength = MP3_GetUnpackedSize( psLocalFilename, pvData, iDataLen, qfalse, // qboolean qbIgnoreID3Tag - bStereoDesired); - if (iUnpackLength) - { - lpMP3Stream->iTimeQuery_UnpackedLength = iUnpackLength; - lpMP3Stream->iTimeQuery_SampleRate = iRate; - lpMP3Stream->iTimeQuery_Channels = iChannels; - lpMP3Stream->iTimeQuery_Width = iWidth; + char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &iRate, &iWidth, &iChannels, bStereoDesired); + if (psError) { + Com_Printf(va(S_COLOR_RED "MP3Stream_InitPlayingTimeFields(): %s\n(File: %s)\n", psError, psLocalFilename)); + } else { + int iUnpackLength = MP3_GetUnpackedSize(psLocalFilename, pvData, iDataLen, qfalse, // qboolean qbIgnoreID3Tag + bStereoDesired); + if (iUnpackLength) { + lpMP3Stream->iTimeQuery_UnpackedLength = iUnpackLength; + lpMP3Stream->iTimeQuery_SampleRate = iRate; + lpMP3Stream->iTimeQuery_Channels = iChannels; + lpMP3Stream->iTimeQuery_Width = iWidth; bRetval = qtrue; } @@ -125,84 +112,72 @@ qboolean MP3Stream_InitPlayingTimeFields( LP_MP3STREAM lpMP3Stream, const char * return bRetval; } -float MP3Stream_GetPlayingTimeInSeconds( LP_MP3STREAM lpMP3Stream ) -{ - if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? - return (float)((((double)lpMP3Stream->iTimeQuery_UnpackedLength / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / (double)lpMP3Stream->iTimeQuery_Width); +float MP3Stream_GetPlayingTimeInSeconds(LP_MP3STREAM lpMP3Stream) { + if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? + return ( + float)((((double)lpMP3Stream->iTimeQuery_UnpackedLength / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / + (double)lpMP3Stream->iTimeQuery_Width); return 0.0f; } -float MP3Stream_GetRemainingTimeInSeconds( LP_MP3STREAM lpMP3Stream ) -{ - if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? - return (float)(((((double)(lpMP3Stream->iTimeQuery_UnpackedLength - (lpMP3Stream->iBytesDecodedTotal * (lpMP3Stream->iTimeQuery_SampleRate / dma.speed)))) / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / (double)lpMP3Stream->iTimeQuery_Width); +float MP3Stream_GetRemainingTimeInSeconds(LP_MP3STREAM lpMP3Stream) { + if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? + return ( + float)(((((double)(lpMP3Stream->iTimeQuery_UnpackedLength - (lpMP3Stream->iBytesDecodedTotal * (lpMP3Stream->iTimeQuery_SampleRate / dma.speed)))) / + (double)lpMP3Stream->iTimeQuery_SampleRate) / + (double)lpMP3Stream->iTimeQuery_Channels) / + (double)lpMP3Stream->iTimeQuery_Width); return 0.0f; } - - - // expects data already loaded, filename arg is for error printing only // -qboolean MP3_FakeUpWAVInfo( const char *psLocalFilename, void *pvData, int iDataLen, int iUnpackedDataLength, - int &format, int &rate, int &width, int &channels, int &samples, int &dataofs, - qboolean bStereoDesired /* = qfalse */ - ) -{ +qboolean MP3_FakeUpWAVInfo(const char *psLocalFilename, void *pvData, int iDataLen, int iUnpackedDataLength, int &format, int &rate, int &width, int &channels, + int &samples, int &dataofs, qboolean bStereoDesired /* = qfalse */ +) { // some things can be done instantly... // - format = 1; // 1 for MS format - dataofs= 0; // will be 0 for me (since there's no header in the unpacked data) + format = 1; // 1 for MS format + dataofs = 0; // will be 0 for me (since there's no header in the unpacked data) // some things need to be read... (though the whole stereo flag thing is crap) // - char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &rate, &width, &channels, bStereoDesired ); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &rate, &width, &channels, bStereoDesired); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); } // and some stuff needs calculating... // - samples = iUnpackedDataLength / width; + samples = iUnpackedDataLength / width; return (qboolean)(!psError); } - - -const char sKEY_MAXVOL[]="#MAXVOL"; // formerly #defines -const char sKEY_UNCOMP[]="#UNCOMP"; // " " +const char sKEY_MAXVOL[] = "#MAXVOL"; // formerly #defines +const char sKEY_UNCOMP[] = "#UNCOMP"; // " " // returns qtrue for success... // -qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, - id3v1_1** ppTAG /* = NULL */, - int *piUncompressedSize /* = NULL */, +qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, id3v1_1 **ppTAG /* = NULL */, int *piUncompressedSize /* = NULL */, float *pfMaxVol /* = NULL */ - ) -{ +) { qboolean qbError = qfalse; - id3v1_1* pTAG = (id3v1_1*) ((pbLoadedFile+iLoadedFileLen)-sizeof(id3v1_1)); // sizeof = 128 + id3v1_1 *pTAG = (id3v1_1 *)((pbLoadedFile + iLoadedFileLen) - sizeof(id3v1_1)); // sizeof = 128 - if (!strncmp(pTAG->id, "TAG", 3)) - { + if (!strncmp(pTAG->id, "TAG", 3)) { // TAG found... // // read MAXVOL key... // - if (strncmp(pTAG->comment, sKEY_MAXVOL, strlen(sKEY_MAXVOL))) - { + if (strncmp(pTAG->comment, sKEY_MAXVOL, strlen(sKEY_MAXVOL))) { qbError = qtrue; - } - else - { - if ( pfMaxVol) - { + } else { + if (pfMaxVol) { *pfMaxVol = atof(pTAG->comment + strlen(sKEY_MAXVOL)); } } @@ -210,42 +185,30 @@ qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, // // read UNCOMP key... // - if (strncmp(pTAG->album, sKEY_UNCOMP, strlen(sKEY_UNCOMP))) - { + if (strncmp(pTAG->album, sKEY_UNCOMP, strlen(sKEY_UNCOMP))) { qbError = qtrue; - } - else - { - if ( piUncompressedSize) - { + } else { + if (piUncompressedSize) { *piUncompressedSize = atoi(pTAG->album + strlen(sKEY_UNCOMP)); } } - } - else - { + } else { pTAG = NULL; } - if (ppTAG) - { + if (ppTAG) { *ppTAG = pTAG; } return (qboolean)(pTAG && !qbError); } +#define FUZZY_AMOUNT \ + (5 * 1024) // so it has to be significantly over, not just break even, because of + // the xtra CPU time versus memory saving - -#define FUZZY_AMOUNT (5*1024) // so it has to be significantly over, not just break even, because of - // the xtra CPU time versus memory saving - -cvar_t* cv_MP3overhead = NULL; -void MP3_InitCvars(void) -{ - cv_MP3overhead = Cvar_Get("s_mp3overhead", va("%d", sizeof(MP3STREAM) + FUZZY_AMOUNT), CVAR_ARCHIVE ); -} - +cvar_t *cv_MP3overhead = NULL; +void MP3_InitCvars(void) { cv_MP3overhead = Cvar_Get("s_mp3overhead", va("%d", sizeof(MP3STREAM) + FUZZY_AMOUNT), CVAR_ARCHIVE); } // a file has been loaded in memory, see if we want to keep it as MP3, else as normal WAV... // @@ -253,55 +216,47 @@ void MP3_InitCvars(void) // // (note: the reason I pass in the unpacked size rather than working it out here is simply because I already have it) // -qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, const char *psSrcDataFilename, - int iMP3UnPackedSize, qboolean bStereoDesired /* = qfalse */ - ) -{ +qboolean MP3Stream_InitFromFile(sfx_t *sfx, byte *pbSrcData, int iSrcDatalen, const char *psSrcDataFilename, int iMP3UnPackedSize, + qboolean bStereoDesired /* = qfalse */ +) { // first, make a decision based on size here as to whether or not it's worth it because of MP3 buffer space // making small files much bigger (and therefore best left as WAV)... // - if (cv_MP3overhead && - ( - //iSrcDatalen + sizeof(MP3STREAM) + FUZZY_AMOUNT < iMP3UnPackedSize - iSrcDatalen + cv_MP3overhead->integer < iMP3UnPackedSize - ) - ) - { + if (cv_MP3overhead && ( + // iSrcDatalen + sizeof(MP3STREAM) + FUZZY_AMOUNT < iMP3UnPackedSize + iSrcDatalen + cv_MP3overhead->integer < iMP3UnPackedSize)) { // ok, let's keep it as MP3 then... // - float fMaxVol = 128; // seems to be a reasonable typical default for maxvol (for lip synch). Naturally there's no #define I can use instead... + float fMaxVol = 128; // seems to be a reasonable typical default for maxvol (for lip synch). Naturally there's no #define I can use instead... - MP3_ReadSpecialTagInfo(pbSrcData, iSrcDatalen, NULL, NULL, &fMaxVol ); // try and read a read maxvol from MP3 header + MP3_ReadSpecialTagInfo(pbSrcData, iSrcDatalen, NULL, NULL, &fMaxVol); // try and read a read maxvol from MP3 header // fill in some sfx_t fields... // -// Q_strncpyz( sfx->name, psSrcDataFilename, sizeof(sfx->name) ); + // Q_strncpyz( sfx->name, psSrcDataFilename, sizeof(sfx->name) ); sfx->eSoundCompressionMethod = ct_MP3; sfx->fVolRange = fMaxVol; - //sfx->width = 2; - sfx->iSoundLengthInSamples = ((iMP3UnPackedSize / 2/*sfx->width*/) / (44100 / dma.speed)) / (bStereoDesired?2:1); + // sfx->width = 2; + sfx->iSoundLengthInSamples = ((iMP3UnPackedSize / 2 /*sfx->width*/) / (44100 / dma.speed)) / (bStereoDesired ? 2 : 1); // // alloc mem for data and store it (raw MP3 in this case)... // - sfx->pSoundData = (short *) SND_malloc( iSrcDatalen, sfx ); - memcpy( sfx->pSoundData, pbSrcData, iSrcDatalen ); + sfx->pSoundData = (short *)SND_malloc(iSrcDatalen, sfx); + memcpy(sfx->pSoundData, pbSrcData, iSrcDatalen); // now init the low-level MP3 stuff... // - MP3STREAM SFX_MP3Stream = {}; // important to init to all zeroes! - char *psError = C_MP3Stream_DecodeInit( &SFX_MP3Stream, /*sfx->data*/ /*sfx->soundData*/ pbSrcData, iSrcDatalen, - dma.speed,//(s_khz->value == 44)?44100:(s_khz->value == 22)?22050:11025, - 2/*sfx->width*/ * 8, - bStereoDesired - ); - SFX_MP3Stream.pbSourceData = (byte *) sfx->pSoundData; - if (psError) - { + MP3STREAM SFX_MP3Stream = {}; // important to init to all zeroes! + char *psError = C_MP3Stream_DecodeInit(&SFX_MP3Stream, /*sfx->data*/ /*sfx->soundData*/ pbSrcData, iSrcDatalen, + dma.speed, //(s_khz->value == 44)?44100:(s_khz->value == 22)?22050:11025, + 2 /*sfx->width*/ * 8, bStereoDesired); + SFX_MP3Stream.pbSourceData = (byte *)sfx->pSoundData; + if (psError) { // This should never happen, since any errors or problems with the MP3 file would have stopped us getting // to this whole function, but just in case... // - Com_Printf(va(S_COLOR_YELLOW"File \"%s\": %s\n",psSrcDataFilename,psError)); + Com_Printf(va(S_COLOR_YELLOW "File \"%s\": %s\n", psSrcDataFilename, psError)); // This will leave iSrcDatalen bytes on the hunk stack (since you can't dealloc that), but MP3 files are // usually small, and like I say, it should never happen. @@ -317,8 +272,8 @@ qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, c // // make a copy of the filled-in stream struct and attach to the sfx_t struct... // - sfx->pMP3StreamHeader = (MP3STREAM *) Z_Malloc( sizeof(MP3STREAM), TAG_SND_MP3STREAMHDR, qfalse ); - memcpy( sfx->pMP3StreamHeader, &SFX_MP3Stream, sizeof(MP3STREAM) ); + sfx->pMP3StreamHeader = (MP3STREAM *)Z_Malloc(sizeof(MP3STREAM), TAG_SND_MP3STREAMHDR, qfalse); + memcpy(sfx->pMP3StreamHeader, &SFX_MP3Stream, sizeof(MP3STREAM)); // return qtrue; } @@ -326,17 +281,14 @@ qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, c return qfalse; } - - // decode one packet of MP3 data only (typical output size is 2304, or 2304*2 for stereo, so input size is less // // return is decoded byte count, else 0 for finished // -int MP3Stream_Decode( LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic ) -{ +int MP3Stream_Decode(LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic) { lpMP3Stream->iCopyOffset = 0; - if (0)//!bDoingMusic) + if (0) //! bDoingMusic) { /* // SOF2: need to make a local buffer up so we can decode the piece we want from a contiguous bitstream rather than @@ -408,164 +360,140 @@ int MP3Stream_Decode( LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic ) } } */ - } - else - { + } else { // SOF2 music, or EF1 anything... // - return C_MP3Stream_Decode( lpMP3Stream, qfalse ); // bFastForwarding + return C_MP3Stream_Decode(lpMP3Stream, qfalse); // bFastForwarding } } +qboolean MP3Stream_SeekTo(channel_t *ch, float fTimeToSeekTo) { + const float fEpsilon = 0.05f; // accurate to 1/50 of a second, but plus or minus this gives 1/10 of second -qboolean MP3Stream_SeekTo( channel_t *ch, float fTimeToSeekTo ) -{ - const float fEpsilon = 0.05f; // accurate to 1/50 of a second, but plus or minus this gives 1/10 of second - - MP3Stream_Rewind( ch ); + MP3Stream_Rewind(ch); // // sanity... :-) // - const float fTrackLengthInSeconds = MP3Stream_GetPlayingTimeInSeconds( &ch->MP3StreamHeader ); - if (fTimeToSeekTo > fTrackLengthInSeconds) - { + const float fTrackLengthInSeconds = MP3Stream_GetPlayingTimeInSeconds(&ch->MP3StreamHeader); + if (fTimeToSeekTo > fTrackLengthInSeconds) { fTimeToSeekTo = fTrackLengthInSeconds; } // now do the seek... // - while (1) - { - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( &ch->MP3StreamHeader ) - MP3Stream_GetRemainingTimeInSeconds( &ch->MP3StreamHeader ); + while (1) { + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(&ch->MP3StreamHeader) - MP3Stream_GetRemainingTimeInSeconds(&ch->MP3StreamHeader); float fAbsTimeDiff = fabs(fTimeToSeekTo - fPlayingTimeElapsed); - if ( fAbsTimeDiff <= fEpsilon) + if (fAbsTimeDiff <= fEpsilon) return qtrue; // when decoding, use fast-forward until within 3 seconds, then slow-decode (which should init stuff properly?)... // - int iBytesDecodedThisPacket = C_MP3Stream_Decode( &ch->MP3StreamHeader, (fAbsTimeDiff > 3.0f) ); // bFastForwarding + int iBytesDecodedThisPacket = C_MP3Stream_Decode(&ch->MP3StreamHeader, (fAbsTimeDiff > 3.0f)); // bFastForwarding if (iBytesDecodedThisPacket == 0) - break; // EOS + break; // EOS } return qfalse; } - // returns qtrue for all ok // -qboolean MP3Stream_Rewind( channel_t *ch ) -{ +qboolean MP3Stream_Rewind(channel_t *ch) { ch->iMP3SlidingDecodeWritePos = 0; - ch->iMP3SlidingDecodeWindowPos= 0; + ch->iMP3SlidingDecodeWindowPos = 0; -/* - char *psError = C_MP3Stream_Rewind( &ch->MP3StreamHeader ); + /* + char *psError = C_MP3Stream_Rewind( &ch->MP3StreamHeader ); - if (psError) - { - Com_Printf(S_COLOR_YELLOW"%s\n",psError); - return qfalse; - } + if (psError) + { + Com_Printf(S_COLOR_YELLOW"%s\n",psError); + return qfalse; + } - return qtrue; -*/ + return qtrue; + */ // speed opt, since I know I already have the right data setup here... // memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); return qtrue; - } - // returns qtrue while still playing normally, else qfalse for either finished or request-offset-error // -qboolean MP3Stream_GetSamples( channel_t *ch, int startingSampleNum, int count, short *buf, qboolean bStereo ) -{ +qboolean MP3Stream_GetSamples(channel_t *ch, int startingSampleNum, int count, short *buf, qboolean bStereo) { qboolean qbStreamStillGoing = qtrue; - const int iQuarterOfSlidingBuffer = sizeof(ch->MP3SlidingDecodeBuffer)/4; - const int iThreeQuartersOfSlidingBuffer = (sizeof(ch->MP3SlidingDecodeBuffer)*3)/4; + const int iQuarterOfSlidingBuffer = sizeof(ch->MP3SlidingDecodeBuffer) / 4; + const int iThreeQuartersOfSlidingBuffer = (sizeof(ch->MP3SlidingDecodeBuffer) * 3) / 4; -// Com_Printf("startingSampleNum %d\n",startingSampleNum); + // Com_Printf("startingSampleNum %d\n",startingSampleNum); - count *= 2/* <- = SOF2; ch->sfx->width*/; // count arg was for words, so double it for bytes; + count *= 2 /* <- = SOF2; ch->sfx->width*/; // count arg was for words, so double it for bytes; // convert sample number into a byte offset... (make new variable for clarity?) // - startingSampleNum *= 2 /* <- = SOF2; ch->sfx->width*/ * (bStereo?2:1); + startingSampleNum *= 2 /* <- = SOF2; ch->sfx->width*/ * (bStereo ? 2 : 1); - if ( startingSampleNum < ch->iMP3SlidingDecodeWindowPos) - { + if (startingSampleNum < ch->iMP3SlidingDecodeWindowPos) { // what?!?!?! smegging time travel needed or something?, forget it - memset(buf,0,count); + memset(buf, 0, count); return qfalse; } -// OutputDebugString(va("\nRequest: startingSampleNum %d, count %d\n",startingSampleNum,count)); -// OutputDebugString(va("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos)); + // OutputDebugString(va("\nRequest: startingSampleNum %d, count %d\n",startingSampleNum,count)); + // OutputDebugString(va("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos)); -// qboolean _bDecoded = qfalse; + // qboolean _bDecoded = qfalse; - while (! - ( - (startingSampleNum >= ch->iMP3SlidingDecodeWindowPos) - && - (startingSampleNum + count < ch->iMP3SlidingDecodeWindowPos + ch->iMP3SlidingDecodeWritePos) - ) - ) - { -// if (!_bDecoded) -// { -// Com_Printf(S_COLOR_YELLOW"Decode needed!\n"); -// } -// _bDecoded = qtrue; -// OutputDebugString("Scrolling..."); - - int _iBytesDecoded = MP3Stream_Decode( (LP_MP3STREAM) &ch->MP3StreamHeader, bStereo ); // stereo only for music, so this is safe -// OutputDebugString(va("%d bytes decoded\n",_iBytesDecoded)); - if (_iBytesDecoded == 0) - { + while (!((startingSampleNum >= ch->iMP3SlidingDecodeWindowPos) && + (startingSampleNum + count < ch->iMP3SlidingDecodeWindowPos + ch->iMP3SlidingDecodeWritePos))) { + // if (!_bDecoded) + // { + // Com_Printf(S_COLOR_YELLOW"Decode needed!\n"); + // } + // _bDecoded = qtrue; + // OutputDebugString("Scrolling..."); + + int _iBytesDecoded = MP3Stream_Decode((LP_MP3STREAM)&ch->MP3StreamHeader, bStereo); // stereo only for music, so this is safe + // OutputDebugString(va("%d bytes decoded\n",_iBytesDecoded)); + if (_iBytesDecoded == 0) { // no more source data left so clear the remainder of the buffer... // - memset(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, 0, sizeof(ch->MP3SlidingDecodeBuffer)-ch->iMP3SlidingDecodeWritePos); -// OutputDebugString("Finished\n"); + memset(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, 0, sizeof(ch->MP3SlidingDecodeBuffer) - ch->iMP3SlidingDecodeWritePos); + // OutputDebugString("Finished\n"); qbStreamStillGoing = qfalse; break; - } - else - { - memcpy(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos,ch->MP3StreamHeader.bDecodeBuffer,_iBytesDecoded); + } else { + memcpy(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, ch->MP3StreamHeader.bDecodeBuffer, _iBytesDecoded); ch->iMP3SlidingDecodeWritePos += _iBytesDecoded; // if reached 3/4 of buffer pos, backscroll the decode window by one quarter... // - if (ch->iMP3SlidingDecodeWritePos > iThreeQuartersOfSlidingBuffer) - { + if (ch->iMP3SlidingDecodeWritePos > iThreeQuartersOfSlidingBuffer) { memmove(ch->MP3SlidingDecodeBuffer, ((byte *)ch->MP3SlidingDecodeBuffer + iQuarterOfSlidingBuffer), iThreeQuartersOfSlidingBuffer); ch->iMP3SlidingDecodeWritePos -= iQuarterOfSlidingBuffer; - ch->iMP3SlidingDecodeWindowPos+= iQuarterOfSlidingBuffer; + ch->iMP3SlidingDecodeWindowPos += iQuarterOfSlidingBuffer; } } -// OutputDebugString(va("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos)); + // OutputDebugString(va("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos)); } -// if (!_bDecoded) -// { -// Com_Printf(S_COLOR_YELLOW"No decode needed\n"); -// } + // if (!_bDecoded) + // { + // Com_Printf(S_COLOR_YELLOW"No decode needed\n"); + // } assert(startingSampleNum >= ch->iMP3SlidingDecodeWindowPos); - memcpy( buf, ch->MP3SlidingDecodeBuffer + (startingSampleNum-ch->iMP3SlidingDecodeWindowPos), count); + memcpy(buf, ch->MP3SlidingDecodeBuffer + (startingSampleNum - ch->iMP3SlidingDecodeWindowPos), count); -// OutputDebugString("OK\n\n"); + // OutputDebugString("OK\n\n"); return qbStreamStillGoing; } - ///////////// eof ///////////// - diff --git a/code/client/cl_parse.cpp b/code/client/cl_parse.cpp index 81c702dc8e..2b1ae476cd 100644 --- a/code/client/cl_parse.cpp +++ b/code/client/cl_parse.cpp @@ -28,25 +28,16 @@ along with this program; if not, see . #include "client.h" #include "client_ui.h" -const char *svc_strings[256] = { - "svc_bad", - - "svc_nop", - "svc_gamestate", - "svc_configstring", - "svc_baseline", - "svc_serverCommand", - "svc_download", - "svc_snapshot" -}; - -void SHOWNET( msg_t *msg, const char *s) { - if ( cl_shownet->integer >= 2) { - Com_Printf ("%3i:%s\n", msg->readcount-1, s); +const char *svc_strings[256] = {"svc_bad", + + "svc_nop", "svc_gamestate", "svc_configstring", "svc_baseline", "svc_serverCommand", "svc_download", "svc_snapshot"}; + +void SHOWNET(msg_t *msg, const char *s) { + if (cl_shownet->integer >= 2) { + Com_Printf("%3i:%s\n", msg->readcount - 1, s); } } - /* ========================================================================= @@ -63,18 +54,17 @@ Parses deltas from the given base and adds the resulting entity to the current frame ================== */ -void CL_DeltaEntity (msg_t *msg, clSnapshot_t *frame) -{ - entityState_t *state; +void CL_DeltaEntity(msg_t *msg, clSnapshot_t *frame) { + entityState_t *state; // save the parsed entity state into the big circular buffer so // it can be used as the source for a later delta - state = &cl.parseEntities[cl.parseEntitiesNum & (MAX_PARSE_ENTITIES-1)]; + state = &cl.parseEntities[cl.parseEntitiesNum & (MAX_PARSE_ENTITIES - 1)]; - MSG_ReadEntity( msg, state); + MSG_ReadEntity(msg, state); - if ( state->number == (MAX_GENTITIES-1) ) { - return; // entity was delta removed + if (state->number == (MAX_GENTITIES - 1)) { + return; // entity was delta removed } cl.parseEntitiesNum++; frame->numEntities++; @@ -86,10 +76,10 @@ CL_ParsePacketEntities ================== */ -void CL_ParsePacketEntities( msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *newframe) { - int newnum; - entityState_t *oldstate; - int oldindex, oldnum; +void CL_ParsePacketEntities(msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *newframe) { + int newnum; + entityState_t *oldstate; + int oldindex, oldnum; newframe->parseEntitiesNum = cl.parseEntitiesNum; newframe->numEntities = 0; @@ -100,95 +90,89 @@ void CL_ParsePacketEntities( msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *n if (!oldframe) { oldnum = 99999; } else { - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } - while ( 1 ) { + while (1) { // read the entity index number - newnum = MSG_ReadBits( msg, GENTITYNUM_BITS ); + newnum = MSG_ReadBits(msg, GENTITYNUM_BITS); - if ( newnum == (MAX_GENTITIES-1) ) { + if (newnum == (MAX_GENTITIES - 1)) { break; } - if ( msg->readcount > msg->cursize ) { - Com_Error (ERR_DROP,"CL_ParsePacketEntities: end of message"); + if (msg->readcount > msg->cursize) { + Com_Error(ERR_DROP, "CL_ParsePacketEntities: end of message"); } - while ( oldnum < newnum ) { + while (oldnum < newnum) { // one or more entities from the old packet are unchanged - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: unchanged: %i\n", msg->readcount, oldnum); } - CL_DeltaEntity( msg, newframe ); + CL_DeltaEntity(msg, newframe); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } if (oldnum == newnum) { // delta from previous state - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: delta: %i\n", msg->readcount, newnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: delta: %i\n", msg->readcount, newnum); } - CL_DeltaEntity( msg, newframe ); + CL_DeltaEntity(msg, newframe); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } continue; } - if ( oldnum > newnum ) { + if (oldnum > newnum) { // delta from baseline - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: baseline: %i\n", msg->readcount, newnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: baseline: %i\n", msg->readcount, newnum); } - CL_DeltaEntity( msg, newframe ); + CL_DeltaEntity(msg, newframe); continue; } - } // any remaining entities in the old frame are copied over - while ( oldnum != 99999 ) { + while (oldnum != 99999) { // one or more entities from the old packet are unchanged - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: unchanged: %i\n", msg->readcount, oldnum); } - CL_DeltaEntity( msg, newframe ); + CL_DeltaEntity(msg, newframe); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } } - /* ================ CL_ParseSnapshot @@ -198,81 +182,81 @@ cl.frame and saved in cl.frames[]. If the snapshot is invalid for any reason, no changes to the state will be made at all. ================ */ -void CL_ParseSnapshot( msg_t *msg ) { - int len; - clSnapshot_t *old; - clSnapshot_t newSnap; - int deltaNum; - int oldMessageNum; - int i, packetNum; +void CL_ParseSnapshot(msg_t *msg) { + int len; + clSnapshot_t *old; + clSnapshot_t newSnap; + int deltaNum; + int oldMessageNum; + int i, packetNum; // get the reliable sequence acknowledge number - clc.reliableAcknowledge = MSG_ReadLong( msg ); + clc.reliableAcknowledge = MSG_ReadLong(msg); // read in the new snapshot to a temporary buffer // we will only copy to cl.frame if it is valid - memset (&newSnap, 0, sizeof(newSnap)); + memset(&newSnap, 0, sizeof(newSnap)); newSnap.serverCommandNum = clc.serverCommandSequence; - newSnap.serverTime = MSG_ReadLong( msg ); + newSnap.serverTime = MSG_ReadLong(msg); // if we were just unpaused, we can only *now* really let the // change come into effect or the client hangs. cl_paused->modified = qfalse; - newSnap.messageNum = MSG_ReadLong( msg ); - deltaNum = MSG_ReadByte( msg ); - if ( !deltaNum ) { + newSnap.messageNum = MSG_ReadLong(msg); + deltaNum = MSG_ReadByte(msg); + if (!deltaNum) { newSnap.deltaNum = -1; } else { newSnap.deltaNum = newSnap.messageNum - deltaNum; } - newSnap.cmdNum = MSG_ReadLong( msg ); - newSnap.snapFlags = MSG_ReadByte( msg ); + newSnap.cmdNum = MSG_ReadLong(msg); + newSnap.snapFlags = MSG_ReadByte(msg); // If the frame is delta compressed from data that we // no longer have available, we must suck up the rest of // the frame, but not use it, then ask for a non-compressed // message - if ( newSnap.deltaNum <= 0 ) { - newSnap.valid = qtrue; // uncompressed frame + if (newSnap.deltaNum <= 0) { + newSnap.valid = qtrue; // uncompressed frame old = NULL; } else { old = &cl.frames[newSnap.deltaNum & PACKET_MASK]; - if ( !old->valid ) { + if (!old->valid) { // should never happen - Com_Printf ("Delta from invalid frame (not supposed to happen!).\n"); - } else if ( old->messageNum != newSnap.deltaNum ) { + Com_Printf("Delta from invalid frame (not supposed to happen!).\n"); + } else if (old->messageNum != newSnap.deltaNum) { // The frame that the server did the delta from // is too old, so we can't reconstruct it properly. - Com_Printf ("Delta frame too old.\n"); - } else if ( cl.parseEntitiesNum - old->parseEntitiesNum > MAX_PARSE_ENTITIES ) { - Com_Printf ("Delta parseEntitiesNum too old.\n"); + Com_Printf("Delta frame too old.\n"); + } else if (cl.parseEntitiesNum - old->parseEntitiesNum > MAX_PARSE_ENTITIES) { + Com_Printf("Delta parseEntitiesNum too old.\n"); } else { - newSnap.valid = qtrue; // valid delta parse + newSnap.valid = qtrue; // valid delta parse } } // read areamask - len = MSG_ReadByte( msg ); - MSG_ReadData( msg, &newSnap.areamask, len); + len = MSG_ReadByte(msg); + MSG_ReadData(msg, &newSnap.areamask, len); // read playerinfo - SHOWNET( msg, "playerstate" ); - if ( old ) { - MSG_ReadDeltaPlayerstate( msg, &old->ps, &newSnap.ps ); + SHOWNET(msg, "playerstate"); + if (old) { + MSG_ReadDeltaPlayerstate(msg, &old->ps, &newSnap.ps); } else { - MSG_ReadDeltaPlayerstate( msg, NULL, &newSnap.ps ); + MSG_ReadDeltaPlayerstate(msg, NULL, &newSnap.ps); } // read packet entities - SHOWNET( msg, "packet entities" ); - CL_ParsePacketEntities( msg, old, &newSnap ); + SHOWNET(msg, "packet entities"); + CL_ParsePacketEntities(msg, old, &newSnap); // if not valid, dump the entire thing now that it has // been properly read - if ( !newSnap.valid ) { + if (!newSnap.valid) { return; } @@ -280,10 +264,10 @@ void CL_ParseSnapshot( msg_t *msg ) { // received and this one oldMessageNum = cl.frame.messageNum + 1; - if ( cl.frame.messageNum - oldMessageNum >= PACKET_BACKUP ) { - oldMessageNum = cl.frame.messageNum - ( PACKET_BACKUP - 1 ); + if (cl.frame.messageNum - oldMessageNum >= PACKET_BACKUP) { + oldMessageNum = cl.frame.messageNum - (PACKET_BACKUP - 1); } - for ( ; oldMessageNum < newSnap.messageNum ; oldMessageNum++ ) { + for (; oldMessageNum < newSnap.messageNum; oldMessageNum++) { cl.frames[oldMessageNum & PACKET_MASK].valid = qfalse; } @@ -291,10 +275,10 @@ void CL_ParseSnapshot( msg_t *msg ) { cl.frame = newSnap; // calculate ping time - for ( i = 0 ; i < PACKET_BACKUP ; i++ ) { - packetNum = ( clc.netchan.outgoingSequence - 1 - i ) & PACKET_MASK; - if ( cl.frame.cmdNum == cl.packetCmdNumber[ packetNum ] ) { - cl.frame.ping = cls.realtime - cl.packetTime[ packetNum ]; + for (i = 0; i < PACKET_BACKUP; i++) { + packetNum = (clc.netchan.outgoingSequence - 1 - i) & PACKET_MASK; + if (cl.frame.cmdNum == cl.packetCmdNumber[packetNum]) { + cl.frame.ping = cls.realtime - cl.packetTime[packetNum]; break; } } @@ -302,15 +286,13 @@ void CL_ParseSnapshot( msg_t *msg ) { cl.frames[cl.frame.messageNum & PACKET_MASK] = cl.frame; if (cl_shownet->integer == 3) { - Com_Printf (" frame:%i delta:%i\n", cl.frame.messageNum, - cl.frame.deltaNum); + Com_Printf(" frame:%i delta:%i\n", cl.frame.messageNum, cl.frame.deltaNum); } // actions for valid frames cl.newSnapshots = qtrue; } - //===================================================================== int cl_connectedToCheatServer; @@ -324,94 +306,93 @@ new information out of it. This will happen at every gamestate, and possibly during gameplay. ================== */ -void CL_SystemInfoChanged( void ) { - char *systemInfo; - const char *s; - char key[MAX_INFO_KEY]; - char value[MAX_INFO_VALUE]; - - systemInfo = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SYSTEMINFO ]; - cl.serverId = atoi( Info_ValueForKey( systemInfo, "sv_serverid" ) ); - - s = Info_ValueForKey( systemInfo, "helpUsObi" ); - cl_connectedToCheatServer = atoi( s ); - if ( !cl_connectedToCheatServer ) - { +void CL_SystemInfoChanged(void) { + char *systemInfo; + const char *s; + char key[MAX_INFO_KEY]; + char value[MAX_INFO_VALUE]; + + systemInfo = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SYSTEMINFO]; + cl.serverId = atoi(Info_ValueForKey(systemInfo, "sv_serverid")); + + s = Info_ValueForKey(systemInfo, "helpUsObi"); + cl_connectedToCheatServer = atoi(s); + if (!cl_connectedToCheatServer) { Cvar_SetCheatState(); } // scan through all the variables in the systeminfo and locally set cvars to match s = systemInfo; - while ( s ) { - Info_NextPair( &s, key, value ); - if ( !key[0] ) { + while (s) { + Info_NextPair(&s, key, value); + if (!key[0]) { break; } - Cvar_Set( key, value ); + Cvar_Set(key, value); } - //if ( Cvar_VariableIntegerValue("ui_iscensored") == 1 ) + // if ( Cvar_VariableIntegerValue("ui_iscensored") == 1 ) //{ // Cvar_Set( "g_dismemberment", "0"); - //} + // } } -void UI_UpdateConnectionString( const char *string ); +void UI_UpdateConnectionString(const char *string); /* ================== CL_ParseGamestate ================== */ -void CL_ParseGamestate( msg_t *msg ) { - int i; - int cmd; - char *s; +void CL_ParseGamestate(msg_t *msg) { + int i; + int cmd; + char *s; Con_Close(); - UI_UpdateConnectionString( "" ); + UI_UpdateConnectionString(""); // wipe local client state CL_ClearState(); // a gamestate always marks a server command sequence - clc.serverCommandSequence = MSG_ReadLong( msg ); + clc.serverCommandSequence = MSG_ReadLong(msg); // parse all the configstrings and baselines - cl.gameState.dataCount = 1; // leave a 0 at the beginning for uninitialized configstrings - while ( 1 ) { - cmd = MSG_ReadByte( msg ); + cl.gameState.dataCount = 1; // leave a 0 at the beginning for uninitialized configstrings + while (1) { + cmd = MSG_ReadByte(msg); - if ( cmd <= 0 ) { + if (cmd <= 0) { break; } - if ( cmd == svc_configstring ) { - int len; + if (cmd == svc_configstring) { + int len; - i = MSG_ReadShort( msg ); - if ( i < 0 || i >= MAX_CONFIGSTRINGS ) { - Com_Error( ERR_DROP, "configstring > MAX_CONFIGSTRINGS" ); + i = MSG_ReadShort(msg); + if (i < 0 || i >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "configstring > MAX_CONFIGSTRINGS"); } - s = MSG_ReadString( msg ); - len = strlen( s ); + s = MSG_ReadString(msg); + len = strlen(s); - if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) { - Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" ); + if (len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS) { + Com_Error(ERR_DROP, "MAX_GAMESTATE_CHARS exceeded"); } // append it to the gameState string buffer - cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount; - memcpy( cl.gameState.stringData + cl.gameState.dataCount, s, len + 1 ); + cl.gameState.stringOffsets[i] = cl.gameState.dataCount; + memcpy(cl.gameState.stringData + cl.gameState.dataCount, s, len + 1); cl.gameState.dataCount += len + 1; - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: CS# %d %s (%d)\n",msg->readcount, i,s,len); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: CS# %d %s (%d)\n", msg->readcount, i, s, len); } - } else if ( cmd == svc_baseline ) { + } else if (cmd == svc_baseline) { assert(0); } else { - Com_Error( ERR_DROP, "CL_ParseGamestate: bad command byte" ); + Com_Error(ERR_DROP, "CL_ParseGamestate: bad command byte"); } } @@ -430,25 +411,22 @@ void CL_ParseGamestate( msg_t *msg ) { CL_StartHunkUsers(); // make sure the game starts - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } - //===================================================================== -void CL_FreeServerCommands(void) -{ +void CL_FreeServerCommands(void) { int i; - for(i=0; i= seq ) { + if (clc.serverCommandSequence >= seq) { return; } clc.serverCommandSequence = seq; - index = seq & (MAX_RELIABLE_COMMANDS-1); - if ( clc.serverCommands[ index ] ) { - Z_Free( clc.serverCommands[ index ] ); + index = seq & (MAX_RELIABLE_COMMANDS - 1); + if (clc.serverCommands[index]) { + Z_Free(clc.serverCommands[index]); } - clc.serverCommands[ index ] = CopyString( s ); + clc.serverCommands[index] = CopyString(s); } - /* ===================== CL_ParseServerMessage ===================== */ -void CL_ParseServerMessage( msg_t *msg ) { - int cmd; +void CL_ParseServerMessage(msg_t *msg) { + int cmd; - if ( cl_shownet->integer == 1 ) { - Com_Printf ("%i ",msg->cursize); - } else if ( cl_shownet->integer >= 2 ) { - Com_Printf ("------------------\n"); + if (cl_shownet->integer == 1) { + Com_Printf("%i ", msg->cursize); + } else if (cl_shownet->integer >= 2) { + Com_Printf("------------------\n"); } // // parse the message // - while ( 1 ) { - if ( msg->readcount > msg->cursize ) { - Com_Error (ERR_DROP,"CL_ParseServerMessage: read past end of server message"); + while (1) { + if (msg->readcount > msg->cursize) { + Com_Error(ERR_DROP, "CL_ParseServerMessage: read past end of server message"); break; } - cmd = MSG_ReadByte( msg ); + cmd = MSG_ReadByte(msg); - if ( cmd == -1 ) { - SHOWNET( msg, "END OF MESSAGE" ); + if (cmd == -1) { + SHOWNET(msg, "END OF MESSAGE"); break; } - if ( cl_shownet->integer >= 2 ) { - if ( !svc_strings[cmd] ) { - Com_Printf( "%3i:BAD CMD %i\n", msg->readcount-1, cmd ); + if (cl_shownet->integer >= 2) { + if (!svc_strings[cmd]) { + Com_Printf("%3i:BAD CMD %i\n", msg->readcount - 1, cmd); } else { - SHOWNET( msg, svc_strings[cmd] ); + SHOWNET(msg, svc_strings[cmd]); } } - // other commands - switch ( cmd ) { + // other commands + switch (cmd) { default: - Com_Error (ERR_DROP,"CL_ParseServerMessage: Illegible server message\n"); + Com_Error(ERR_DROP, "CL_ParseServerMessage: Illegible server message\n"); break; case svc_nop: break; case svc_serverCommand: - CL_ParseCommandString( msg ); + CL_ParseCommandString(msg); break; case svc_gamestate: - CL_ParseGamestate( msg ); + CL_ParseGamestate(msg); break; case svc_snapshot: - CL_ParseSnapshot( msg ); + CL_ParseSnapshot(msg); break; } } } - - diff --git a/code/client/cl_scrn.cpp b/code/client/cl_scrn.cpp index 730ee7d466..38d044e5a9 100644 --- a/code/client/cl_scrn.cpp +++ b/code/client/cl_scrn.cpp @@ -31,13 +31,13 @@ along with this program; if not, see . extern console_t con; -qboolean scr_initialized; // ready to draw +qboolean scr_initialized; // ready to draw -cvar_t *cl_timegraph; -cvar_t *cl_debuggraph; -cvar_t *cl_graphheight; -cvar_t *cl_graphscale; -cvar_t *cl_graphshift; +cvar_t *cl_timegraph; +cvar_t *cl_debuggraph; +cvar_t *cl_graphheight; +cvar_t *cl_graphscale; +cvar_t *cl_graphshift; /* ================ @@ -46,16 +46,15 @@ SCR_DrawNamedPic Coordinates are 640*480 virtual values ================= */ -void SCR_DrawNamedPic( float x, float y, float width, float height, const char *picname ) { - qhandle_t hShader; +void SCR_DrawNamedPic(float x, float y, float width, float height, const char *picname) { + qhandle_t hShader; - assert( width != 0 ); + assert(width != 0); - hShader = re.RegisterShader( picname ); - re.DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); + hShader = re.RegisterShader(picname); + re.DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } - /* ================ SCR_FillRect @@ -63,15 +62,14 @@ SCR_FillRect Coordinates are 640*480 virtual values ================= */ -void SCR_FillRect( float x, float y, float width, float height, const float *color ) { - re.SetColor( color ); +void SCR_FillRect(float x, float y, float width, float height, const float *color) { + re.SetColor(color); - re.DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cls.whiteShader ); + re.DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cls.whiteShader); - re.SetColor( NULL ); + re.SetColor(NULL); } - /* ================ SCR_DrawPic @@ -80,28 +78,25 @@ Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ -void SCR_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { - re.DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); -} - +void SCR_DrawPic(float x, float y, float width, float height, qhandle_t hShader) { re.DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } /* ** SCR_DrawBigChar ** big chars are drawn at 640*480 virtual screen size */ -void SCR_DrawBigChar( int x, int y, int ch ) { +void SCR_DrawBigChar(int x, int y, int ch) { int row, col; float frow, fcol; float size; - float ax, ay, aw, ah; + float ax, ay, aw, ah; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } - if ( y < -BIGCHAR_HEIGHT ) { + if (y < -BIGCHAR_HEIGHT) { return; } @@ -110,81 +105,71 @@ void SCR_DrawBigChar( int x, int y, int ch ) { aw = BIGCHAR_WIDTH; ah = BIGCHAR_HEIGHT; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.0625; -/* - re.DrawStretchPic( ax, ay, aw, ah, - fcol, frow, - fcol + size, frow + size, - cls.charSetShader ); -*/ + /* + re.DrawStretchPic( ax, ay, aw, ah, + fcol, frow, + fcol + size, frow + size, + cls.charSetShader ); + */ float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - re.DrawStretchPic( ax, ay, aw, ah, - fcol, frow, - fcol + size, frow + size2, - cls.charSetShader ); - + re.DrawStretchPic(ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cls.charSetShader); } /* ** SCR_DrawSmallChar ** small chars are drawn at native screen resolution */ -void SCR_DrawSmallChar( int x, int y, int ch ) { +void SCR_DrawSmallChar(int x, int y, int ch) { int row, col; float frow, fcol; float size; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } - if ( y < -con.charHeight ) { + if (y < -con.charHeight) { return; } - row = ch>>4; - col = ch&15; -/* - frow = row*0.0625; - fcol = col*0.0625; - size = 0.0625; + row = ch >> 4; + col = ch & 15; + /* + frow = row*0.0625; + fcol = col*0.0625; + size = 0.0625; - re.DrawStretchPic( x, y, con.charWidth, con.charHeight, - fcol, frow, - fcol + size, frow + size, - cls.charSetShader ); -*/ + re.DrawStretchPic( x, y, con.charWidth, con.charHeight, + fcol, frow, + fcol + size, frow + size, + cls.charSetShader ); + */ float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - re.DrawStretchPic( x * con.xadjust, y * con.yadjust, - con.charWidth * con.xadjust, con.charHeight * con.yadjust, - fcol, frow, - fcol + size, frow + size2, - cls.charSetShader ); - + re.DrawStretchPic(x * con.xadjust, y * con.yadjust, con.charWidth * con.xadjust, con.charHeight * con.yadjust, fcol, frow, fcol + size, frow + size2, + cls.charSetShader); } - - /* ================== SCR_DrawBigString[Color] @@ -195,63 +180,59 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -void SCR_DrawBigStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape ) { - vec4_t color; - const char *s; - int xx; +void SCR_DrawBigStringExt(int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape) { + vec4_t color; + const char *s; + int xx; // draw the drop shadow color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; - re.SetColor( color ); + re.SetColor(color); s = string; xx = x; - while ( *s ) { - if ( !noColorEscape && Q_IsColorString( s ) ) { + while (*s) { + if (!noColorEscape && Q_IsColorString(s)) { s += 2; continue; } - SCR_DrawBigChar( xx+2, y+2, *s ); + SCR_DrawBigChar(xx + 2, y + 2, *s); xx += BIGCHAR_WIDTH; s++; } - // draw the colored text s = string; xx = x; - re.SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + re.SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - re.SetColor( color ); + re.SetColor(color); } - if ( !noColorEscape ) { + if (!noColorEscape) { s += 2; continue; } } - SCR_DrawBigChar( xx, y, *s ); + SCR_DrawBigChar(xx, y, *s); xx += BIGCHAR_WIDTH; s++; } - re.SetColor( NULL ); + re.SetColor(NULL); } - -void SCR_DrawBigString( int x, int y, const char *s, float alpha, qboolean noColorEscape ) { - float color[4]; +void SCR_DrawBigString(int x, int y, const char *s, float alpha, qboolean noColorEscape) { + float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; - SCR_DrawBigStringExt( x, y, s, color, qfalse, noColorEscape ); + SCR_DrawBigStringExt(x, y, s, color, qfalse, noColorEscape); } -void SCR_DrawBigStringColor( int x, int y, const char *s, vec4_t color, qboolean noColorEscape ) { - SCR_DrawBigStringExt( x, y, s, color, qtrue, noColorEscape ); -} +void SCR_DrawBigStringColor(int x, int y, const char *s, vec4_t color, qboolean noColorEscape) { SCR_DrawBigStringExt(x, y, s, color, qtrue, noColorEscape); } /* ================== @@ -261,44 +242,43 @@ Draws a multi-colored string with a drop shadow, optionally forcing to a fixed color. ================== */ -void SCR_DrawSmallStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor, - qboolean noColorEscape ) { - vec4_t color; - const char *s; - int xx; +void SCR_DrawSmallStringExt(int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape) { + vec4_t color; + const char *s; + int xx; // draw the colored text s = string; xx = x; - re.SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + re.SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - re.SetColor( color ); + re.SetColor(color); } - if ( !noColorEscape ) { + if (!noColorEscape) { s += 2; continue; } } - SCR_DrawSmallChar( xx, y, *s ); + SCR_DrawSmallChar(xx, y, *s); xx += con.charWidth; s++; } - re.SetColor( NULL ); + re.SetColor(NULL); } /* ** SCR_Strlen -- skips color escape codes */ -static int SCR_Strlen( const char *str ) { +static int SCR_Strlen(const char *str) { const char *s = str; int count = 0; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; } else { count++; @@ -312,13 +292,10 @@ static int SCR_Strlen( const char *str ) { /* ** SCR_GetBigStringWidth */ -int SCR_GetBigStringWidth( const char *str ) { - return SCR_Strlen( str ) * BIGCHAR_WIDTH; -} +int SCR_GetBigStringWidth(const char *str) { return SCR_Strlen(str) * BIGCHAR_WIDTH; } //=============================================================================== - /* =============================================================================== @@ -326,24 +303,22 @@ DEBUG GRAPH =============================================================================== */ -typedef struct -{ - float value; - int color; +typedef struct { + float value; + int color; } graphsamp_t; -static int current; -static graphsamp_t values[1024]; +static int current; +static graphsamp_t values[1024]; /* ============== SCR_DebugGraph ============== */ -void SCR_DebugGraph (float value, int color) -{ - values[current&1023].value = value; - values[current&1023].color = color; +void SCR_DebugGraph(float value, int color) { + values[current & 1023].value = value; + values[current & 1023].color = color; current++; } @@ -352,10 +327,9 @@ void SCR_DebugGraph (float value, int color) SCR_DrawDebugGraph ============== */ -void SCR_DrawDebugGraph (void) -{ - int a, x, y, w, i, h; - float v; +void SCR_DrawDebugGraph(void) { + int a, x, y, w, i, h; + float v; // // draw the graph @@ -363,21 +337,19 @@ void SCR_DrawDebugGraph (void) w = cls.glconfig.vidWidth; x = 0; y = cls.glconfig.vidHeight; - re.SetColor( g_color_table[0] ); - re.DrawStretchPic(x, y - cl_graphheight->integer, - w, cl_graphheight->integer, 0, 0, 0, 0, 0 ); - re.SetColor( NULL ); - - for (a=0 ; ainteger, w, cl_graphheight->integer, 0, 0, 0, 0, 0); + re.SetColor(NULL); + + for (a = 0; a < w; a++) { + i = (current - 1 - a + 1024) & 1023; v = values[i].value; v = v * cl_graphscale->integer + cl_graphshift->integer; if (v < 0) - v += cl_graphheight->integer * (1+(int)(-v / cl_graphheight->integer)); + v += cl_graphheight->integer * (1 + (int)(-v / cl_graphheight->integer)); h = (int)v % cl_graphheight->integer; - re.DrawStretchPic( x+w-1-a, y - h, 1, h, 0, 0, 0, 0, 0 ); + re.DrawStretchPic(x + w - 1 - a, y - h, 1, h, 0, 0, 0, 0, 0); } } //============================================================================= @@ -387,22 +359,21 @@ void SCR_DrawDebugGraph (void) SCR_Init ================== */ -void SCR_Init( void ) { - cl_timegraph = Cvar_Get ("timegraph", "0", CVAR_CHEAT); - cl_debuggraph = Cvar_Get ("debuggraph", "0", CVAR_CHEAT); - cl_graphheight = Cvar_Get ("graphheight", "32", CVAR_CHEAT); - cl_graphscale = Cvar_Get ("graphscale", "1", CVAR_CHEAT); - cl_graphshift = Cvar_Get ("graphshift", "0", CVAR_CHEAT); +void SCR_Init(void) { + cl_timegraph = Cvar_Get("timegraph", "0", CVAR_CHEAT); + cl_debuggraph = Cvar_Get("debuggraph", "0", CVAR_CHEAT); + cl_graphheight = Cvar_Get("graphheight", "32", CVAR_CHEAT); + cl_graphscale = Cvar_Get("graphscale", "1", CVAR_CHEAT); + cl_graphshift = Cvar_Get("graphshift", "0", CVAR_CHEAT); scr_initialized = qtrue; } - //======================================================= -void UI_SetActiveMenu( const char* menuname,const char *menuID ); -void _UI_Refresh( int realtime ); -void UI_DrawConnect( const char *servername, const char * updateInfoString ); +void UI_SetActiveMenu(const char *menuname, const char *menuID); +void _UI_Refresh(int realtime); +void UI_DrawConnect(const char *servername, const char *updateInfoString); /* ================== @@ -411,45 +382,42 @@ SCR_DrawScreenField This will be called twice if rendering in stereo mode ================== */ -void SCR_DrawScreenField( stereoFrame_t stereoFrame ) { +void SCR_DrawScreenField(stereoFrame_t stereoFrame) { - re.BeginFrame( stereoFrame ); + re.BeginFrame(stereoFrame); qboolean uiFullscreen = _UI_IsFullscreen(); // if the menu is going to cover the entire screen, we // don't need to render anything under it - if ( !uiFullscreen ) { - switch( cls.state ) { + if (!uiFullscreen) { + switch (cls.state) { default: - Com_Error( ERR_FATAL, "SCR_DrawScreenField: bad cls.state" ); + Com_Error(ERR_FATAL, "SCR_DrawScreenField: bad cls.state"); break; case CA_CINEMATIC: SCR_DrawCinematic(); break; case CA_DISCONNECTED: // force menu up - UI_SetActiveMenu( "mainMenu", NULL ); + UI_SetActiveMenu("mainMenu", NULL); break; case CA_CONNECTING: case CA_CHALLENGING: case CA_CONNECTED: // connecting clients will only show the connection dialog - UI_DrawConnect( clc.servername, cls.updateInfoString ); + UI_DrawConnect(clc.servername, cls.updateInfoString); break; case CA_LOADING: case CA_PRIMED: // draw the game information screen and loading progress - CL_CGameRendering( stereoFrame ); + CL_CGameRendering(stereoFrame); break; case CA_ACTIVE: - if (CL_IsRunningInGameCinematic() || CL_InGameCinematicOnStandBy()) - { + if (CL_IsRunningInGameCinematic() || CL_InGameCinematicOnStandBy()) { SCR_DrawCinematic(); - } - else - { - CL_CGameRendering( stereoFrame ); + } else { + CL_CGameRendering(stereoFrame); } break; } @@ -460,14 +428,14 @@ void SCR_DrawScreenField( stereoFrame_t stereoFrame ) { // draw downloading progress bar // the menu draws next - _UI_Refresh( cls.realtime ); + _UI_Refresh(cls.realtime); // console draws next - Con_DrawConsole (); + Con_DrawConsole(); // debug graph can be drawn on top of anything - if ( cl_debuggraph->integer || cl_timegraph->integer ) { - SCR_DrawDebugGraph (); + if (cl_debuggraph->integer || cl_timegraph->integer) { + SCR_DrawDebugGraph(); } } @@ -479,37 +447,36 @@ This is called every frame, and can also be called explicitly to flush text to the screen. ================== */ -void SCR_UpdateScreen( void ) { - static int recursive; +void SCR_UpdateScreen(void) { + static int recursive; - if ( !scr_initialized ) { - return; // not initialized yet + if (!scr_initialized) { + return; // not initialized yet } // load the ref / ui / cgame if needed CL_StartHunkUsers(); - if ( ++recursive > 2 ) { - Com_Error( ERR_FATAL, "SCR_UpdateScreen: recursively called" ); + if (++recursive > 2) { + Com_Error(ERR_FATAL, "SCR_UpdateScreen: recursively called"); } recursive = qtrue; // If there is no VM, there are also no rendering commands issued. Stop the renderer in // that case. - if ( cls.uiStarted ) - { + if (cls.uiStarted) { // if running in stereo, we need to draw the frame twice - if ( cls.glconfig.stereoEnabled ) { - SCR_DrawScreenField( STEREO_LEFT ); - SCR_DrawScreenField( STEREO_RIGHT ); + if (cls.glconfig.stereoEnabled) { + SCR_DrawScreenField(STEREO_LEFT); + SCR_DrawScreenField(STEREO_RIGHT); } else { - SCR_DrawScreenField( STEREO_CENTER ); + SCR_DrawScreenField(STEREO_CENTER); } - if ( com_speeds->integer ) { - re.EndFrame( &time_frontend, &time_backend ); + if (com_speeds->integer) { + re.EndFrame(&time_frontend, &time_backend); } else { - re.EndFrame( NULL, NULL ); + re.EndFrame(NULL, NULL); } } @@ -519,43 +486,33 @@ void SCR_UpdateScreen( void ) { // this stuff is only used by the savegame (SG) code for screenshots... // - -static byte bScreenData[SG_SCR_WIDTH * SG_SCR_HEIGHT * 4]; +static byte bScreenData[SG_SCR_WIDTH * SG_SCR_HEIGHT * 4]; static qboolean screenDataValid = qfalse; -void SCR_UnprecacheScreenshot() -{ - screenDataValid = qfalse; -} +void SCR_UnprecacheScreenshot() { screenDataValid = qfalse; } - -void SCR_PrecacheScreenshot() -{ +void SCR_PrecacheScreenshot() { // No screenshots unless connected to single player local server... // -// char *psInfo = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ]; -// int iMaxClients = atoi(Info_ValueForKey( psInfo, "sv_maxclients" )); + // char *psInfo = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ]; + // int iMaxClients = atoi(Info_ValueForKey( psInfo, "sv_maxclients" )); // (no need to check single-player status in voyager, this code base is all singleplayer) - if ( cls.state != CA_ACTIVE ) - { + if (cls.state != CA_ACTIVE) { return; } - if (!Key_GetCatcher( )) - { + if (!Key_GetCatcher()) { // in-game... // -// SCR_UnprecacheScreenshot(); -// pbScreenData = (byte *)Z_Malloc(SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); - S_ClearSoundBuffer(); // clear DMA etc because the following glReadPixels() call can take ages - re.GetScreenShot( (byte *) &bScreenData, SG_SCR_WIDTH, SG_SCR_HEIGHT); + // SCR_UnprecacheScreenshot(); + // pbScreenData = (byte *)Z_Malloc(SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); + S_ClearSoundBuffer(); // clear DMA etc because the following glReadPixels() call can take ages + re.GetScreenShot((byte *)&bScreenData, SG_SCR_WIDTH, SG_SCR_HEIGHT); screenDataValid = qtrue; } - } -byte *SCR_GetScreenshot(qboolean *qValid) -{ +byte *SCR_GetScreenshot(qboolean *qValid) { if (!screenDataValid) { SCR_PrecacheScreenshot(); } @@ -567,36 +524,25 @@ byte *SCR_GetScreenshot(qboolean *qValid) // called from save-game code to set the lo-res loading screen to be the one from the save file... // -void SCR_SetScreenshot(const byte *pbData, int w, int h) -{ - if (w == SG_SCR_WIDTH && h == SG_SCR_HEIGHT) - { +void SCR_SetScreenshot(const byte *pbData, int w, int h) { + if (w == SG_SCR_WIDTH && h == SG_SCR_HEIGHT) { screenDataValid = qtrue; - memcpy(&bScreenData, pbData, SG_SCR_WIDTH*SG_SCR_HEIGHT*4); - } - else - { + memcpy(&bScreenData, pbData, SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); + } else { screenDataValid = qfalse; - memset(&bScreenData, 0, SG_SCR_WIDTH*SG_SCR_HEIGHT*4); + memset(&bScreenData, 0, SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); } } - #ifdef JK2_MODE // This is just a client-side wrapper for the function RE_TempRawImage_ReadFromFile() in the renderer code... // -byte* SCR_TempRawImage_ReadFromFile(const char *psLocalFilename, int *piWidth, int *piHeight, byte *pbReSampleBuffer, qboolean qbVertFlip) -{ +byte *SCR_TempRawImage_ReadFromFile(const char *psLocalFilename, int *piWidth, int *piHeight, byte *pbReSampleBuffer, qboolean qbVertFlip) { return re.TempRawImage_ReadFromFile(psLocalFilename, piWidth, piHeight, pbReSampleBuffer, qbVertFlip); } // // ditto (sort of)... // -void SCR_TempRawImage_CleanUp() -{ - re.TempRawImage_CleanUp(); -} +void SCR_TempRawImage_CleanUp() { re.TempRawImage_CleanUp(); } #endif - - diff --git a/code/client/cl_ui.cpp b/code/client/cl_ui.cpp index 80d002f1f3..ac1703c7e0 100644 --- a/code/client/cl_ui.cpp +++ b/code/client/cl_ui.cpp @@ -29,17 +29,16 @@ along with this program; if not, see . #include "vmachine.h" -intptr_t CL_UISystemCalls( intptr_t *args ); +intptr_t CL_UISystemCalls(intptr_t *args); -//prototypes +// prototypes #ifdef JK2_MODE -extern qboolean SG_GetSaveImage( const char *psPathlessBaseName, void *pvAddress ); +extern qboolean SG_GetSaveImage(const char *psPathlessBaseName, void *pvAddress); #endif extern int SG_GetSaveGameComment(const char *psPathlessBaseName, char *sComment, char *sMapName); extern qboolean SG_GameAllowedToSaveHere(qboolean inCamera); extern void SG_StoreSaveGameComment(const char *sComment); -extern byte *SCR_GetScreenshot(qboolean *qValid); // uncommented --eez - +extern byte *SCR_GetScreenshot(qboolean *qValid); // uncommented --eez /* ==================== @@ -52,40 +51,35 @@ Helper functions for User Interface GetClientState ==================== */ -static connstate_t GetClientState( void ) { - return cls.state; -} +static connstate_t GetClientState(void) { return cls.state; } /* ==================== CL_GetGlConfig ==================== */ -static void UI_GetGlconfig( glconfig_t *config ) { - *config = cls.glconfig; -} +static void UI_GetGlconfig(glconfig_t *config) { *config = cls.glconfig; } /* ==================== GetClipboardData ==================== */ -static void GetClipboardData( char *buf, int buflen ) { - char *cbd, *c; +static void GetClipboardData(char *buf, int buflen) { + char *cbd, *c; c = cbd = Sys_GetClipboardData(); - if ( !cbd ) { + if (!cbd) { *buf = 0; return; } - for ( int i = 0, end = buflen - 1; *c && i < end; i++ ) - { - uint32_t utf32 = ConvertUTF8ToUTF32( c, &c ); - buf[i] = ConvertUTF32ToExpectedCharset( utf32 ); + for (int i = 0, end = buflen - 1; *c && i < end; i++) { + uint32_t utf32 = ConvertUTF8ToUTF32(c, &c); + buf[i] = ConvertUTF32ToExpectedCharset(utf32); } - Z_Free( cbd ); + Z_Free(cbd); } /* @@ -96,15 +90,14 @@ Key_KeynumToStringBuf // only ever called by binding-display code, therefore returns non-technical "friendly" names // in any language that don't necessarily match those in the config file... // -void Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) -{ - const char *psKeyName = Key_KeynumToString( keynum/*, qtrue */); +void Key_KeynumToStringBuf(int keynum, char *buf, int buflen) { + const char *psKeyName = Key_KeynumToString(keynum /*, qtrue */); // see if there's a more friendly (or localised) name... // - const char *psKeyNameFriendly = SE_GetString( va("KEYNAMES_KEYNAME_%s",psKeyName) ); + const char *psKeyNameFriendly = SE_GetString(va("KEYNAMES_KEYNAME_%s", psKeyName)); - Q_strncpyz( buf, (psKeyNameFriendly && psKeyNameFriendly[0]) ? psKeyNameFriendly : psKeyName, buflen ); + Q_strncpyz(buf, (psKeyNameFriendly && psKeyNameFriendly[0]) ? psKeyNameFriendly : psKeyName, buflen); } /* @@ -112,14 +105,13 @@ void Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) Key_GetBindingBuf ==================== */ -void Key_GetBindingBuf( int keynum, char *buf, int buflen ) { - const char *value; +void Key_GetBindingBuf(int keynum, char *buf, int buflen) { + const char *value; - value = Key_GetBinding( keynum ); - if ( value ) { - Q_strncpyz( buf, value, buflen ); - } - else { + value = Key_GetBinding(keynum); + if (value) { + Q_strncpyz(buf, value, buflen); + } else { *buf = 0; } } @@ -129,20 +121,16 @@ void Key_GetBindingBuf( int keynum, char *buf, int buflen ) { FloatAsInt ==================== */ -static int FloatAsInt( float f ) -{ +static int FloatAsInt(float f) { byteAlias_t fi; fi.f = f; return fi.i; } -static void UI_Cvar_Create( const char *var_name, const char *var_value, int flags ) { - Cvar_Register( NULL, var_name, var_value, flags ); -} +static void UI_Cvar_Create(const char *var_name, const char *var_value, int flags) { Cvar_Register(NULL, var_name, var_value, flags); } -static int GetConfigString(int index, char *buf, int size) -{ - int offset; +static int GetConfigString(int index, char *buf, int size) { + int offset; if (index < 0 || index >= MAX_CONFIGSTRINGS) return qfalse; @@ -151,7 +139,7 @@ static int GetConfigString(int index, char *buf, int size) if (!offset) return qfalse; - Q_strncpyz( buf, cl.gameState.stringData+offset, size); + Q_strncpyz(buf, cl.gameState.stringData + offset, size); return qtrue; } @@ -161,189 +149,177 @@ static int GetConfigString(int index, char *buf, int size) CL_ShutdownUI ==================== */ -void UI_Shutdown( void ); -void CL_ShutdownUI( void ) { +void UI_Shutdown(void); +void CL_ShutdownUI(void) { UI_Shutdown(); - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_UI ); + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_UI); cls.uiStarted = qfalse; } -void CL_DrawDatapad(int HUDType) -{ - switch(HUDType) - { +void CL_DrawDatapad(int HUDType) { + switch (HUDType) { case DP_HUD: - VM_Call( CG_DRAW_DATAPAD_HUD ); + VM_Call(CG_DRAW_DATAPAD_HUD); break; case DP_OBJECTIVES: - VM_Call( CG_DRAW_DATAPAD_OBJECTIVES ); + VM_Call(CG_DRAW_DATAPAD_OBJECTIVES); break; case DP_WEAPONS: - VM_Call( CG_DRAW_DATAPAD_WEAPONS ); + VM_Call(CG_DRAW_DATAPAD_WEAPONS); break; case DP_INVENTORY: - VM_Call( CG_DRAW_DATAPAD_INVENTORY ); + VM_Call(CG_DRAW_DATAPAD_INVENTORY); break; case DP_FORCEPOWERS: - VM_Call( CG_DRAW_DATAPAD_FORCEPOWERS ); + VM_Call(CG_DRAW_DATAPAD_FORCEPOWERS); break; default: break; } - - } -void UI_Init( int apiVersion, uiimport_t *uiimport, qboolean inGameLoad ); +void UI_Init(int apiVersion, uiimport_t *uiimport, qboolean inGameLoad); /* ==================== CL_InitUI ==================== */ -void CL_InitUI( void ) { +void CL_InitUI(void) { #ifdef JK2_MODE - JK2SP_Register("keynames", 0 /*SP_REGISTER_REQUIRED*/); // reference is KEYNAMES + JK2SP_Register("keynames", 0 /*SP_REGISTER_REQUIRED*/); // reference is KEYNAMES #endif - uiimport_t uii; + uiimport_t uii; - memset( &uii, 0, sizeof( uii ) ); + memset(&uii, 0, sizeof(uii)); uii.Printf = Com_Printf; uii.Error = Com_Error; - uii.Cvar_Set = Cvar_Set; - uii.Cvar_VariableValue = Cvar_VariableValue; + uii.Cvar_Set = Cvar_Set; + uii.Cvar_VariableValue = Cvar_VariableValue; uii.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; - uii.Cvar_SetValue = Cvar_SetValue; - uii.Cvar_Reset = Cvar_Reset; - uii.Cvar_Create = UI_Cvar_Create; - uii.Cvar_InfoStringBuffer = Cvar_InfoStringBuffer; - - uii.Draw_DataPad = CL_DrawDatapad; - - uii.Argc = Cmd_Argc; - uii.Argv = Cmd_ArgvBuffer; - uii.Cmd_TokenizeString = Cmd_TokenizeString; - - uii.Cmd_ExecuteText = Cbuf_ExecuteText; - - uii.FS_FOpenFile = FS_FOpenFileByMode; - uii.FS_Read = FS_Read; - uii.FS_Write = FS_Write; - uii.FS_FCloseFile = FS_FCloseFile; - uii.FS_GetFileList = FS_GetFileList; - uii.FS_ReadFile = FS_ReadFile; - uii.FS_FreeFile = FS_FreeFile; - - uii.R_RegisterModel = re.RegisterModel; - uii.R_RegisterSkin = re.RegisterSkin; - uii.R_RegisterShader = re.RegisterShader; - uii.R_RegisterShaderNoMip = re.RegisterShaderNoMip; - uii.R_RegisterFont = re.RegisterFont; - uii.R_Font_StrLenPixels = re.Font_StrLenPixels; - uii.R_Font_HeightPixels = re.Font_HeightPixels; - uii.R_Font_DrawString = re.Font_DrawString; - uii.R_Font_StrLenChars = re.Font_StrLenChars; - uii.Language_IsAsian = re.Language_IsAsian; - uii.Language_UsesSpaces = re.Language_UsesSpaces; + uii.Cvar_SetValue = Cvar_SetValue; + uii.Cvar_Reset = Cvar_Reset; + uii.Cvar_Create = UI_Cvar_Create; + uii.Cvar_InfoStringBuffer = Cvar_InfoStringBuffer; + + uii.Draw_DataPad = CL_DrawDatapad; + + uii.Argc = Cmd_Argc; + uii.Argv = Cmd_ArgvBuffer; + uii.Cmd_TokenizeString = Cmd_TokenizeString; + + uii.Cmd_ExecuteText = Cbuf_ExecuteText; + + uii.FS_FOpenFile = FS_FOpenFileByMode; + uii.FS_Read = FS_Read; + uii.FS_Write = FS_Write; + uii.FS_FCloseFile = FS_FCloseFile; + uii.FS_GetFileList = FS_GetFileList; + uii.FS_ReadFile = FS_ReadFile; + uii.FS_FreeFile = FS_FreeFile; + + uii.R_RegisterModel = re.RegisterModel; + uii.R_RegisterSkin = re.RegisterSkin; + uii.R_RegisterShader = re.RegisterShader; + uii.R_RegisterShaderNoMip = re.RegisterShaderNoMip; + uii.R_RegisterFont = re.RegisterFont; + uii.R_Font_StrLenPixels = re.Font_StrLenPixels; + uii.R_Font_HeightPixels = re.Font_HeightPixels; + uii.R_Font_DrawString = re.Font_DrawString; + uii.R_Font_StrLenChars = re.Font_StrLenChars; + uii.Language_IsAsian = re.Language_IsAsian; + uii.Language_UsesSpaces = re.Language_UsesSpaces; uii.AnyLanguage_ReadCharFromString = re.AnyLanguage_ReadCharFromString; #ifdef JK2_MODE - uii.SG_GetSaveImage = SG_GetSaveImage; + uii.SG_GetSaveImage = SG_GetSaveImage; #endif - uii.SG_GetSaveGameComment = SG_GetSaveGameComment; + uii.SG_GetSaveGameComment = SG_GetSaveGameComment; uii.SG_StoreSaveGameComment = SG_StoreSaveGameComment; - uii.SG_GameAllowedToSaveHere= SG_GameAllowedToSaveHere; + uii.SG_GameAllowedToSaveHere = SG_GameAllowedToSaveHere; - //uii.SCR_GetScreenshot = SCR_GetScreenshot; + // uii.SCR_GetScreenshot = SCR_GetScreenshot; #ifdef JK2_MODE - uii.DrawStretchRaw = re.DrawStretchRaw; + uii.DrawStretchRaw = re.DrawStretchRaw; #endif - uii.R_ClearScene = re.ClearScene; - uii.R_AddRefEntityToScene = re.AddRefEntityToScene; - uii.R_AddPolyToScene = re.AddPolyToScene; - uii.R_AddLightToScene = re.AddLightToScene; - uii.R_RenderScene = re.RenderScene; + uii.R_ClearScene = re.ClearScene; + uii.R_AddRefEntityToScene = re.AddRefEntityToScene; + uii.R_AddPolyToScene = re.AddPolyToScene; + uii.R_AddLightToScene = re.AddLightToScene; + uii.R_RenderScene = re.RenderScene; - uii.R_ModelBounds = re.ModelBounds; + uii.R_ModelBounds = re.ModelBounds; - uii.R_SetColor = re.SetColor; - uii.R_DrawStretchPic = re.DrawStretchPic; - uii.UpdateScreen = SCR_UpdateScreen; + uii.R_SetColor = re.SetColor; + uii.R_DrawStretchPic = re.DrawStretchPic; + uii.UpdateScreen = SCR_UpdateScreen; #ifdef JK2_MODE - uii.PrecacheScreenshot = SCR_PrecacheScreenshot; + uii.PrecacheScreenshot = SCR_PrecacheScreenshot; #endif - uii.R_LerpTag = re.LerpTag; - - uii.S_StartLocalLoopingSound= S_StartLocalLoopingSound; - uii.S_StartLocalSound = S_StartLocalSound; - uii.S_RegisterSound = S_RegisterSound; - - uii.Key_KeynumToStringBuf = Key_KeynumToStringBuf; - uii.Key_GetBindingBuf = Key_GetBindingBuf; - uii.Key_SetBinding = Key_SetBinding; - uii.Key_IsDown = Key_IsDown; - uii.Key_GetOverstrikeMode = Key_GetOverstrikeMode; - uii.Key_SetOverstrikeMode = Key_SetOverstrikeMode; - uii.Key_ClearStates = Key_ClearStates; - uii.Key_GetCatcher = Key_GetCatcher; - uii.Key_SetCatcher = Key_SetCatcher; + uii.R_LerpTag = re.LerpTag; + + uii.S_StartLocalLoopingSound = S_StartLocalLoopingSound; + uii.S_StartLocalSound = S_StartLocalSound; + uii.S_RegisterSound = S_RegisterSound; + + uii.Key_KeynumToStringBuf = Key_KeynumToStringBuf; + uii.Key_GetBindingBuf = Key_GetBindingBuf; + uii.Key_SetBinding = Key_SetBinding; + uii.Key_IsDown = Key_IsDown; + uii.Key_GetOverstrikeMode = Key_GetOverstrikeMode; + uii.Key_SetOverstrikeMode = Key_SetOverstrikeMode; + uii.Key_ClearStates = Key_ClearStates; + uii.Key_GetCatcher = Key_GetCatcher; + uii.Key_SetCatcher = Key_SetCatcher; #ifdef JK2_MODE - uii.SP_Register = JK2SP_Register; - uii.SP_GetStringText = JK2SP_GetStringText; - uii.SP_GetStringTextString = JK2SP_GetStringTextString; + uii.SP_Register = JK2SP_Register; + uii.SP_GetStringText = JK2SP_GetStringText; + uii.SP_GetStringTextString = JK2SP_GetStringTextString; #endif - uii.GetClipboardData = GetClipboardData; + uii.GetClipboardData = GetClipboardData; - uii.GetClientState = GetClientState; + uii.GetClientState = GetClientState; - uii.GetGlconfig = UI_GetGlconfig; + uii.GetGlconfig = UI_GetGlconfig; - uii.GetConfigString = (void (*)(int, char *, int))GetConfigString; + uii.GetConfigString = (void (*)(int, char *, int))GetConfigString; - uii.Milliseconds = Sys_Milliseconds2; + uii.Milliseconds = Sys_Milliseconds2; UI_Init(UI_API_VERSION, &uii, (qboolean)(cls.state > CA_DISCONNECTED && cls.state <= CA_ACTIVE)); -// uie->UI_Init( UI_API_VERSION, &uii ); - + // uie->UI_Init( UI_API_VERSION, &uii ); } - -qboolean UI_GameCommand( void ) { - if (!cls.uiStarted) - { +qboolean UI_GameCommand(void) { + if (!cls.uiStarted) { return qfalse; } return UI_ConsoleCommand(); } - -void CL_GenericMenu_f(void) -{ - const char *arg = Cmd_Argv( 1 ); +void CL_GenericMenu_f(void) { + const char *arg = Cmd_Argv(1); if (cls.uiStarted) { - UI_SetActiveMenu("ingame",arg); + UI_SetActiveMenu("ingame", arg); } } - -void CL_EndScreenDissolve_f(void) -{ - re.InitDissolve(qtrue); // dissolve from cinematic to underlying ingame +void CL_EndScreenDissolve_f(void) { + re.InitDissolve(qtrue); // dissolve from cinematic to underlying ingame } -void CL_DataPad_f(void) -{ - if (cls.uiStarted && cls.cgameStarted && (cls.state == CA_ACTIVE) ) { - UI_SetActiveMenu("datapad",NULL); +void CL_DataPad_f(void) { + if (cls.uiStarted && cls.cgameStarted && (cls.state == CA_ACTIVE)) { + UI_SetActiveMenu("datapad", NULL); } } @@ -352,10 +328,7 @@ void CL_DataPad_f(void) CL_GetGlConfig ==================== */ -static void CL_GetGlconfig( glconfig_t *config ) -{ - *config = cls.glconfig; -} +static void CL_GetGlconfig(glconfig_t *config) { *config = cls.glconfig; } /* int PC_ReadTokenHandle(int handle, pc_token_t *pc_token); int PC_SourceFileAndLine(int handle, char *filename, int *line); @@ -367,53 +340,51 @@ CL_UISystemCalls The ui module is making a system call ==================== */ -intptr_t CL_UISystemCalls( intptr_t *args ) -{ +intptr_t CL_UISystemCalls(intptr_t *args) { - switch( args[0] ) - { + switch (args[0]) { case UI_ERROR: - Com_Error( ERR_DROP, "%s", VMA(1) ); + Com_Error(ERR_DROP, "%s", VMA(1)); return 0; case UI_CVAR_REGISTER: - Cvar_Register( (vmCvar_t *)VMA(1),(const char *) VMA(2),(const char *) VMA(3), args[4] ); + Cvar_Register((vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4]); return 0; case UI_CVAR_SET: - Cvar_Set( (const char *) VMA(1), (const char *) VMA(2) ); + Cvar_Set((const char *)VMA(1), (const char *)VMA(2)); return 0; case UI_CVAR_SETVALUE: - Cvar_SetValue( (const char *) VMA(1), VMF(2) ); + Cvar_SetValue((const char *)VMA(1), VMF(2)); return 0; case UI_CVAR_UPDATE: - Cvar_Update( (vmCvar_t *) VMA(1) ); + Cvar_Update((vmCvar_t *)VMA(1)); return 0; case UI_R_REGISTERMODEL: - return re.RegisterModel((const char *) VMA(1) ); + return re.RegisterModel((const char *)VMA(1)); case UI_R_REGISTERSHADERNOMIP: - return re.RegisterShaderNoMip((const char *) VMA(1) ); + return re.RegisterShaderNoMip((const char *)VMA(1)); case UI_GETGLCONFIG: - CL_GetGlconfig( ( glconfig_t *) VMA(1) ); + CL_GetGlconfig((glconfig_t *)VMA(1)); return 0; case UI_CMD_EXECUTETEXT: - Cbuf_ExecuteText( args[1], (const char *) VMA(2) ); + Cbuf_ExecuteText(args[1], (const char *)VMA(2)); return 0; case UI_CVAR_VARIABLEVALUE: - return FloatAsInt( Cvar_VariableValue( (const char *) VMA(1) ) ); + return FloatAsInt(Cvar_VariableValue((const char *)VMA(1))); case UI_FS_GETFILELIST: - return FS_GetFileList( (const char *) VMA(1), (const char *) VMA(2), (char *) VMA(3), args[4] ); + return FS_GetFileList((const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4]); case UI_KEY_SETCATCHER: - Key_SetCatcher( args[1] ); + Key_SetCatcher(args[1]); return 0; case UI_KEY_CLEARSTATES: @@ -421,34 +392,34 @@ intptr_t CL_UISystemCalls( intptr_t *args ) return 0; case UI_R_SETCOLOR: - re.SetColor( (const float *) VMA(1) ); + re.SetColor((const float *)VMA(1)); return 0; case UI_R_DRAWSTRETCHPIC: - re.DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] ); + re.DrawStretchPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9]); return 0; case UI_CVAR_VARIABLESTRINGBUFFER: - Cvar_VariableStringBuffer( (const char *) VMA(1), (char *) VMA(2), args[3] ); + Cvar_VariableStringBuffer((const char *)VMA(1), (char *)VMA(2), args[3]); return 0; - case UI_R_MODELBOUNDS: - re.ModelBounds( args[1], (float *) VMA(2),(float *) VMA(3) ); + case UI_R_MODELBOUNDS: + re.ModelBounds(args[1], (float *)VMA(2), (float *)VMA(3)); return 0; case UI_R_CLEARSCENE: re.ClearScene(); return 0; -// case UI_KEY_GETOVERSTRIKEMODE: -// return Key_GetOverstrikeMode(); -// return 0; + // case UI_KEY_GETOVERSTRIKEMODE: + // return Key_GetOverstrikeMode(); + // return 0; -// case UI_PC_READ_TOKEN: -// return PC_ReadTokenHandle( args[1], VMA(2) ); + // case UI_PC_READ_TOKEN: + // return PC_ReadTokenHandle( args[1], VMA(2) ); -// case UI_PC_SOURCE_FILE_AND_LINE: -// return PC_SourceFileAndLine( args[1], VMA(2), VMA(3) ); + // case UI_PC_SOURCE_FILE_AND_LINE: + // return PC_SourceFileAndLine( args[1], VMA(2), VMA(3) ); case UI_KEY_GETCATCHER: return Key_GetCatcher(); @@ -457,52 +428,49 @@ intptr_t CL_UISystemCalls( intptr_t *args ) return Sys_Milliseconds(); case UI_S_REGISTERSOUND: - return S_RegisterSound((const char *) VMA(1)); + return S_RegisterSound((const char *)VMA(1)); case UI_S_STARTLOCALSOUND: - S_StartLocalSound( args[1], args[2] ); + S_StartLocalSound(args[1], args[2]); return 0; -// case UI_R_REGISTERFONT: -// re.RegisterFont( VMA(1), args[2], VMA(3)); -// return 0; + // case UI_R_REGISTERFONT: + // re.RegisterFont( VMA(1), args[2], VMA(3)); + // return 0; case UI_CIN_PLAYCINEMATIC: - Com_DPrintf("UI_CIN_PlayCinematic\n"); - return CIN_PlayCinematic((const char *)VMA(1), args[2], args[3], args[4], args[5], args[6], (const char *)VMA(7)); + Com_DPrintf("UI_CIN_PlayCinematic\n"); + return CIN_PlayCinematic((const char *)VMA(1), args[2], args[3], args[4], args[5], args[6], (const char *)VMA(7)); case UI_CIN_STOPCINEMATIC: - return CIN_StopCinematic(args[1]); + return CIN_StopCinematic(args[1]); case UI_CIN_RUNCINEMATIC: - return CIN_RunCinematic(args[1]); + return CIN_RunCinematic(args[1]); case UI_CIN_DRAWCINEMATIC: - CIN_DrawCinematic(args[1]); - return 0; + CIN_DrawCinematic(args[1]); + return 0; case UI_KEY_SETBINDING: - Key_SetBinding( args[1], (const char *) VMA(2) ); + Key_SetBinding(args[1], (const char *)VMA(2)); return 0; case UI_KEY_KEYNUMTOSTRINGBUF: - Key_KeynumToStringBuf( args[1],(char *) VMA(2), args[3] ); + Key_KeynumToStringBuf(args[1], (char *)VMA(2), args[3]); return 0; case UI_CIN_SETEXTENTS: - CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]); - return 0; + CIN_SetExtents(args[1], args[2], args[3], args[4], args[5]); + return 0; case UI_KEY_GETBINDINGBUF: - Key_GetBindingBuf( args[1], (char *) VMA(2), args[3] ); + Key_GetBindingBuf(args[1], (char *)VMA(2), args[3]); return 0; - default: - Com_Error( ERR_DROP, "Bad UI system trap: %i", args[0] ); - + Com_Error(ERR_DROP, "Bad UI system trap: %i", args[0]); } return 0; } - diff --git a/code/client/snd_ambient.cpp b/code/client/snd_ambient.cpp index 6e2c612d3d..763d7d46a2 100644 --- a/code/client/snd_ambient.cpp +++ b/code/client/snd_ambient.cpp @@ -27,77 +27,62 @@ along with this program; if not, see . #include "snd_ambient.h" #include "snd_local.h" -static const int MAX_SET_VOLUME = 255; +static const int MAX_SET_VOLUME = 255; -static void AS_GetGeneralSet( ambientSet_t & ); -static void AS_GetLocalSet( ambientSet_t & ); -static void AS_GetBModelSet( ambientSet_t & ); +static void AS_GetGeneralSet(ambientSet_t &); +static void AS_GetLocalSet(ambientSet_t &); +static void AS_GetBModelSet(ambientSet_t &); -//Current set and old set for crossfading -static int currentSet = -1; -static int oldSet = -1; -static int crossDelay = 1000; //1 second +// Current set and old set for crossfading +static int currentSet = -1; +static int oldSet = -1; +static int crossDelay = 1000; // 1 second static int currentSetTime = 0; static int oldSetTime = 0; // Globals for debug purposes -static int numSets = 0; +static int numSets = 0; // Main ambient sound group -static CSetGroup* aSets = NULL; +static CSetGroup *aSets = NULL; // Globals for speed, blech -static char *parseBuffer = NULL; -static int parseSize = 0; -static int parsePos = 0; -static char tempBuffer[1024]; +static char *parseBuffer = NULL; +static int parseSize = 0; +static int parsePos = 0; +static char tempBuffer[1024]; -//NOTENOTE: Be sure to change the mirrored code in g_spawn.cpp, and cg_main.cpp -typedef std::map namePrecache_m; -static namePrecache_m *pMap; +// NOTENOTE: Be sure to change the mirrored code in g_spawn.cpp, and cg_main.cpp +typedef std::map namePrecache_m; +static namePrecache_m *pMap; // Used for enum / string matching -static const char *setNames[NUM_AS_SETS] = - { - "generalSet", - "localSet", - "bmodelSet", - }; +static const char *setNames[NUM_AS_SETS] = { + "generalSet", + "localSet", + "bmodelSet", +}; // Used for enum / function matching -static const parseFunc_t parseFuncs[NUM_AS_SETS] = - { - AS_GetGeneralSet, - AS_GetLocalSet, - AS_GetBModelSet, - }; +static const parseFunc_t parseFuncs[NUM_AS_SETS] = { + AS_GetGeneralSet, + AS_GetLocalSet, + AS_GetBModelSet, +}; // Used for keyword / enum matching -static const char *keywordNames[NUM_AS_KEYWORDS]= - { - "timeBetweenWaves", - "subWaves", - "loopedWave", - "volRange", - "radius", - "type", - "amsdir", - "outdir", - "basedir", - }; - - -CSetGroup::CSetGroup(void) -{ - m_ambientSets = new std::vector; - m_setMap = new std::map; +static const char *keywordNames[NUM_AS_KEYWORDS] = { + "timeBetweenWaves", "subWaves", "loopedWave", "volRange", "radius", "type", "amsdir", "outdir", "basedir", +}; + +CSetGroup::CSetGroup(void) { + m_ambientSets = new std::vector; + m_setMap = new std::map; m_numSets = 0; } - -CSetGroup::~CSetGroup(void) -{ +CSetGroup::~CSetGroup(void) { delete m_ambientSets; delete m_setMap; } @@ -108,20 +93,18 @@ Free ------------------------- */ -void CSetGroup::Free( void ) -{ - std::vector::iterator ai; +void CSetGroup::Free(void) { + std::vector::iterator ai; - for ( ai = m_ambientSets->begin(); ai != m_ambientSets->end(); ++ai ) - { - Z_Free ( (*ai) ); + for (ai = m_ambientSets->begin(); ai != m_ambientSets->end(); ++ai) { + Z_Free((*ai)); } - //Do this in place of clear() so it *really* frees the memory. + // Do this in place of clear() so it *really* frees the memory. delete m_ambientSets; delete m_setMap; - m_ambientSets = new std::vector; - m_setMap = new std::map; + m_ambientSets = new std::vector; + m_setMap = new std::map; m_numSets = 0; } @@ -132,29 +115,28 @@ AddSet ------------------------- */ -ambientSet_t *CSetGroup::AddSet( const char *name ) -{ - ambientSet_t *set; +ambientSet_t *CSetGroup::AddSet(const char *name) { + ambientSet_t *set; - //Allocate the memory - set = (ambientSet_t *) Z_Malloc( sizeof( ambientSet_t ), TAG_AMBIENTSET, qtrue); + // Allocate the memory + set = (ambientSet_t *)Z_Malloc(sizeof(ambientSet_t), TAG_AMBIENTSET, qtrue); - //Set up some defaults - Q_strncpyz(set->name,name,sizeof(set->name)); + // Set up some defaults + Q_strncpyz(set->name, name, sizeof(set->name)); set->loopedVolume = MAX_SET_VOLUME; set->masterVolume = MAX_SET_VOLUME; set->radius = 250; set->time_start = 10; - set->time_end = 25; + set->time_end = 25; set->volRange_start = MAX_SET_VOLUME; - set->volRange_end = MAX_SET_VOLUME; + set->volRange_end = MAX_SET_VOLUME; - m_ambientSets->insert( m_ambientSets->end(), set ); + m_ambientSets->insert(m_ambientSets->end(), set); set->id = m_numSets++; - //Map the name to the pointer for reference later + // Map the name to the pointer for reference later (*m_setMap)[name] = set; return set; @@ -166,36 +148,33 @@ GetSet ------------------------- */ -ambientSet_t *CSetGroup::GetSet( const char *name ) -{ - std::map::iterator mi; +ambientSet_t *CSetGroup::GetSet(const char *name) { + std::map::iterator mi; - if ( name == NULL ) + if (name == NULL) return NULL; - mi = m_setMap->find( name ); + mi = m_setMap->find(name); - if ( mi == m_setMap->end() ) + if (mi == m_setMap->end()) return NULL; return (*mi).second; } -ambientSet_t *CSetGroup::GetSet( int ID ) -{ - if ( m_ambientSets->empty() ) +ambientSet_t *CSetGroup::GetSet(int ID) { + if (m_ambientSets->empty()) return NULL; - if ( ID < 0 ) + if (ID < 0) return NULL; - if ( ID >= m_numSets ) + if (ID >= m_numSets) return NULL; return (*m_ambientSets)[ID]; } - /* =============================================== @@ -210,15 +189,13 @@ AS_GetSetNameIDForString ------------------------- */ -static int AS_GetSetNameIDForString( const char *name ) -{ - //Make sure it's valid - if ( name == NULL || name[0] == '\0' ) +static int AS_GetSetNameIDForString(const char *name) { + // Make sure it's valid + if (name == NULL || name[0] == '\0') return -1; - for ( int i = 0; i < NUM_AS_SETS; i++ ) - { - if ( Q_stricmp( name, setNames[i] ) == 0 ) + for (int i = 0; i < NUM_AS_SETS; i++) { + if (Q_stricmp(name, setNames[i]) == 0) return i; } @@ -231,15 +208,13 @@ AS_GetKeywordIDForString ------------------------- */ -static int AS_GetKeywordIDForString( const char *name ) -{ - //Make sure it's valid - if ( name == NULL || name[0] == '\0' ) +static int AS_GetKeywordIDForString(const char *name) { + // Make sure it's valid + if (name == NULL || name[0] == '\0') return -1; - for ( int i = 0; i < NUM_AS_KEYWORDS; i++ ) - { - if ( Q_stricmp( name, keywordNames[i] ) == 0 ) + for (int i = 0; i < NUM_AS_KEYWORDS; i++) { + if (Q_stricmp(name, keywordNames[i]) == 0) return i; } @@ -254,16 +229,14 @@ Skips a line in the character buffer ------------------------- */ -static void AS_SkipLine( void ) -{ - if ( parsePos > parseSize ) // needed to avoid a crash because of some OOR access that shouldn't be done +static void AS_SkipLine(void) { + if (parsePos > parseSize) // needed to avoid a crash because of some OOR access that shouldn't be done return; - while ( (parseBuffer[parsePos] != '\n') && (parseBuffer[parsePos] != '\r') ) - { + while ((parseBuffer[parsePos] != '\n') && (parseBuffer[parsePos] != '\r')) { parsePos++; - if ( parsePos > parseSize ) + if (parsePos > parseSize) return; } @@ -278,28 +251,26 @@ getTimeBetweenWaves ------------------------- */ -static void AS_GetTimeBetweenWaves( ambientSet_t &set ) -{ - int startTime, endTime; +static void AS_GetTimeBetweenWaves(ambientSet_t &set) { + int startTime, endTime; - //Get the data - sscanf( parseBuffer+parsePos, "%s %d %d", tempBuffer, &startTime, &endTime ); + // Get the data + sscanf(parseBuffer + parsePos, "%s %d %d", tempBuffer, &startTime, &endTime); - //Check for swapped start / end - if ( startTime > endTime ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Corrected swapped start / end times in a \"timeBetweenWaves\" keyword\n"); - #endif + // Check for swapped start / end + if (startTime > endTime) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Corrected swapped start / end times in a \"timeBetweenWaves\" keyword\n"); +#endif int swap = startTime; startTime = endTime; endTime = swap; } - //Store it - set.time_start = startTime; - set.time_end = endTime; + // Store it + set.time_start = startTime; + set.time_end = endTime; AS_SkipLine(); } @@ -312,48 +283,42 @@ subWaves ... ------------------------- */ -static void AS_GetSubWaves( ambientSet_t &set ) -{ - char dirBuffer[512], waveBuffer[256], waveName[1024]; +static void AS_GetSubWaves(ambientSet_t &set) { + char dirBuffer[512], waveBuffer[256], waveName[1024]; - //Get the directory for these sets - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, dirBuffer ); + // Get the directory for these sets + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, dirBuffer); - //Move the pointer past these two strings - parsePos += ((strlen(keywordNames[SET_KEYWORD_SUBWAVES])+1) + (strlen(dirBuffer)+1)); + // Move the pointer past these two strings + parsePos += ((strlen(keywordNames[SET_KEYWORD_SUBWAVES]) + 1) + (strlen(dirBuffer) + 1)); - //Get all the subwaves - while ( parsePos <= parseSize ) - { - //Get the data - sscanf( parseBuffer+parsePos, "%s", waveBuffer ); + // Get all the subwaves + while (parsePos <= parseSize) { + // Get the data + sscanf(parseBuffer + parsePos, "%s", waveBuffer); - if ( set.numSubWaves >= MAX_WAVES_PER_GROUP ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Too many subwaves on set \"%s\"\n", set.name ); - #endif - } - else - { - //Construct the wave name (pretty, huh?) - Com_sprintf( waveName, sizeof(waveName), "sound/%s/%s.wav", dirBuffer, waveBuffer ); - - //Place this onto the sound directory name - - //Precache the file at this point and store off the ID instead of the name - if ( ( set.subWaves[set.numSubWaves++] = S_RegisterSound( waveName ) ) <= 0 ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_RED"ERROR: Unable to load ambient sound \"%s\"\n", waveName); - #endif + if (set.numSubWaves >= MAX_WAVES_PER_GROUP) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Too many subwaves on set \"%s\"\n", set.name); +#endif + } else { + // Construct the wave name (pretty, huh?) + Com_sprintf(waveName, sizeof(waveName), "sound/%s/%s.wav", dirBuffer, waveBuffer); + + // Place this onto the sound directory name + + // Precache the file at this point and store off the ID instead of the name + if ((set.subWaves[set.numSubWaves++] = S_RegisterSound(waveName)) <= 0) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_RED "ERROR: Unable to load ambient sound \"%s\"\n", waveName); +#endif } } - //Move the pointer past this string - parsePos += strlen(waveBuffer)+1; + // Move the pointer past this string + parsePos += strlen(waveBuffer) + 1; - if ( ( (parseBuffer+parsePos)[0] == '\n') || ( (parseBuffer+parsePos)[0] == '\r') ) + if (((parseBuffer + parsePos)[0] == '\n') || ((parseBuffer + parsePos)[0] == '\r')) break; } @@ -368,22 +333,20 @@ loopedWave ------------------------- */ -static void AS_GetLoopedWave( ambientSet_t &set ) -{ - char waveBuffer[256], waveName[1024]; +static void AS_GetLoopedWave(ambientSet_t &set) { + char waveBuffer[256], waveName[1024]; - //Get the looped wave name - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, waveBuffer ); + // Get the looped wave name + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, waveBuffer); - //Construct the wave name - Com_sprintf( waveName, sizeof(waveName), "sound/%s.wav", waveBuffer ); + // Construct the wave name + Com_sprintf(waveName, sizeof(waveName), "sound/%s.wav", waveBuffer); - //Precache the file at this point and store off the ID instead of the name - if ( ( set.loopedWave = S_RegisterSound( waveName ) ) <= 0 ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_RED"ERROR: Unable to load ambient sound \"%s\"\n", waveName); - #endif + // Precache the file at this point and store off the ID instead of the name + if ((set.loopedWave = S_RegisterSound(waveName)) <= 0) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_RED "ERROR: Unable to load ambient sound \"%s\"\n", waveName); +#endif } AS_SkipLine(); @@ -395,28 +358,26 @@ AS_GetVolumeRange ------------------------- */ -static void AS_GetVolumeRange( ambientSet_t &set ) -{ - int min, max; +static void AS_GetVolumeRange(ambientSet_t &set) { + int min, max; - //Get the data - sscanf( parseBuffer+parsePos, "%s %d %d", tempBuffer, &min, &max ); + // Get the data + sscanf(parseBuffer + parsePos, "%s %d %d", tempBuffer, &min, &max); - //Check for swapped min / max - if ( min > max ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Corrected swapped min / max range in a \"volRange\" keyword\n"); - #endif + // Check for swapped min / max + if (min > max) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Corrected swapped min / max range in a \"volRange\" keyword\n"); +#endif - int swap = min; - min = max; - max = swap; + int swap = min; + min = max; + max = swap; } - //Store the data - set.volRange_start = min; - set.volRange_end = max; + // Store the data + set.volRange_start = min; + set.volRange_end = max; AS_SkipLine(); } @@ -427,10 +388,9 @@ AS_GetRadius ------------------------- */ -static void AS_GetRadius( ambientSet_t &set ) -{ - //Get the data - sscanf( parseBuffer+parsePos, "%s %d", tempBuffer, &set.radius ); +static void AS_GetRadius(ambientSet_t &set) { + // Get the data + sscanf(parseBuffer + parsePos, "%s %d", tempBuffer, &set.radius); AS_SkipLine(); } @@ -441,51 +401,47 @@ AS_GetGeneralSet ------------------------- */ -static void AS_GetGeneralSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetGeneralSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_TIMEBETWEENWAVES: - AS_GetTimeBetweenWaves( set ); + AS_GetTimeBetweenWaves(set); break; case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; case SET_KEYWORD_LOOPEDWAVE: - AS_GetLoopedWave( set ); + AS_GetLoopedWave(set); break; case SET_KEYWORD_VOLRANGE: - AS_GetVolumeRange( set ); + AS_GetVolumeRange(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -500,55 +456,51 @@ AS_GetLocalSet ------------------------- */ -static void AS_GetLocalSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetLocalSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_TIMEBETWEENWAVES: - AS_GetTimeBetweenWaves( set ); + AS_GetTimeBetweenWaves(set); break; case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; case SET_KEYWORD_LOOPEDWAVE: - AS_GetLoopedWave( set ); + AS_GetLoopedWave(set); break; case SET_KEYWORD_VOLRANGE: - AS_GetVolumeRange( set ); + AS_GetVolumeRange(set); break; case SET_KEYWORD_RADIUS: - AS_GetRadius( set ); + AS_GetRadius(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -563,39 +515,35 @@ AS_GetBModelSet ------------------------- */ -static void AS_GetBModelSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetBModelSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -612,53 +560,49 @@ Parses an individual set group out of a set file buffer ------------------------- */ -static qboolean AS_ParseSet( int setID, CSetGroup *sg ) -{ - ambientSet_t *set; - const char *name; +static qboolean AS_ParseSet(int setID, CSetGroup *sg) { + ambientSet_t *set; + const char *name; - //Make sure we're not overstepping the name array - if ( setID >= NUM_AS_SETS ) + // Make sure we're not overstepping the name array + if (setID >= NUM_AS_SETS) return qfalse; - //Reset the pointers for this run through + // Reset the pointers for this run through parsePos = 0; name = setNames[setID]; - //Iterate through the whole file and find every occurance of a set - while ( parsePos <= parseSize ) - { - //Check for a valid set group - if ( Q_strncmp( parseBuffer+parsePos, name, strlen(name) ) == 0 ) - { - //Update the debug info + // Iterate through the whole file and find every occurance of a set + while (parsePos <= parseSize) { + // Check for a valid set group + if (Q_strncmp(parseBuffer + parsePos, name, strlen(name)) == 0) { + // Update the debug info numSets++; - //Push past the set specifier and on to the name - parsePos+=strlen(name)+1; //Also take the following space out + // Push past the set specifier and on to the name + parsePos += strlen(name) + 1; // Also take the following space out - //Get the set name (this MUST be first) - sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // Get the set name (this MUST be first) + sscanf(parseBuffer + parsePos, "%s", tempBuffer); AS_SkipLine(); - //Test the string against the precaches - if ( tempBuffer[0] ) - { - //Not in our precache listings, so skip it - if ( ( pMap->find( (const char *) &tempBuffer ) == pMap->end() ) ) + // Test the string against the precaches + if (tempBuffer[0]) { + // Not in our precache listings, so skip it + if ((pMap->find((const char *)&tempBuffer) == pMap->end())) continue; } - //Create a new set - set = sg->AddSet( (const char *) &tempBuffer ); + // Create a new set + set = sg->AddSet((const char *)&tempBuffer); - //Run the function to parse the data out - parseFuncs[setID]( *set ); + // Run the function to parse the data out + parseFuncs[setID](*set); continue; } - //If not found on this line, go down another and check again + // If not found on this line, go down another and check again AS_SkipLine(); } @@ -673,40 +617,36 @@ Parses the directory information out of the beginning of the file ------------------------- */ -static void AS_ParseHeader( void ) -{ - char typeBuffer[128]; - int keywordID; +static void AS_ParseHeader(void) { + char typeBuffer[128]; + int keywordID; - while ( parsePos <= parseSize ) - { - sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + while (parsePos <= parseSize) { + sscanf(parseBuffer + parsePos, "%s", tempBuffer); - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - switch ( keywordID ) - { + switch (keywordID) { case SET_KEYWORD_TYPE: - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, typeBuffer ); + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, typeBuffer); - if ( !Q_stricmp( (const char *) typeBuffer, "ambientSet" ) ) - { + if (!Q_stricmp((const char *)typeBuffer, "ambientSet")) { return; } - Com_Error( ERR_DROP, "AS_ParseHeader: Set type \"%s\" is not a valid set type!\n", typeBuffer ); + Com_Error(ERR_DROP, "AS_ParseHeader: Set type \"%s\" is not a valid set type!\n", typeBuffer); break; case SET_KEYWORD_AMSDIR: - //TODO: Implement + // TODO: Implement break; case SET_KEYWORD_OUTDIR: - //TODO: Implement + // TODO: Implement break; case SET_KEYWORD_BASEDIR: - //TODO: Implement + // TODO: Implement break; } @@ -722,23 +662,22 @@ Opens and parses a sound set file ------------------------- */ -static qboolean AS_ParseFile( const char *filename, CSetGroup *sg ) -{ - //Open the file and read the information from it - parseSize = FS_ReadFile( filename, (void **) &parseBuffer ); +static qboolean AS_ParseFile(const char *filename, CSetGroup *sg) { + // Open the file and read the information from it + parseSize = FS_ReadFile(filename, (void **)&parseBuffer); - if ( parseSize <= 0 ) + if (parseSize <= 0) return qfalse; - //Parse the directory information out of the file + // Parse the directory information out of the file AS_ParseHeader(); - //Parse all the relevent sets out of it - for ( int i = 0; i < NUM_AS_SETS; i++ ) - AS_ParseSet( i, sg ); + // Parse all the relevent sets out of it + for (int i = 0; i < NUM_AS_SETS; i++) + AS_ParseSet(i, sg); - //Free the memory and close the file - FS_FreeFile( parseBuffer ); + // Free the memory and close the file + FS_FreeFile(parseBuffer); return qtrue; } @@ -759,8 +698,7 @@ Loads the ambient sound sets and prepares to play them when needed ------------------------- */ -static namePrecache_m *TheNamePrecache() -{ +static namePrecache_m *TheNamePrecache() { // we use these singletons so we can find memory leaks // if you let things like this leak, you never can tell // what is really leaking and what is merely not ever freed @@ -768,15 +706,13 @@ static namePrecache_m *TheNamePrecache() return &singleton; } -void AS_Init( void ) -{ - if (!aSets) - { +void AS_Init(void) { + if (!aSets) { numSets = 0; pMap = TheNamePrecache(); - //Setup the structure + // Setup the structure aSets = new CSetGroup(); aSets->Init(); } @@ -788,19 +724,16 @@ AS_AddPrecacheEntry ------------------------- */ -void AS_AddPrecacheEntry( const char *name ) { - if ( !pMap ) { // s_initsound 0 probably +void AS_AddPrecacheEntry(const char *name) { + if (!pMap) { // s_initsound 0 probably return; } - if (!Q_stricmp(name,"#clear")) - { + if (!Q_stricmp(name, "#clear")) { pMap->clear(); - currentSet = -1; - oldSet = -1; - } - else - { - (*pMap)[ name ] = 1; + currentSet = -1; + oldSet = -1; + } else { + (*pMap)[name] = 1; } } @@ -812,42 +745,37 @@ Called on the client side to load and precache all the ambient sound sets ------------------------- */ -void AS_ParseSets( void ) -{ - if ( !s_initsound->integer ) { +void AS_ParseSets(void) { + if (!s_initsound->integer) { return; } AS_Init(); - //Parse all the sets - if ( AS_ParseFile( AMBIENT_SET_FILENAME, aSets ) == qfalse ) - { - Com_Error ( ERR_FATAL, S_COLOR_RED"ERROR: Couldn't load ambient sound sets from %s", AMBIENT_SET_FILENAME ); + // Parse all the sets + if (AS_ParseFile(AMBIENT_SET_FILENAME, aSets) == qfalse) { + Com_Error(ERR_FATAL, S_COLOR_RED "ERROR: Couldn't load ambient sound sets from %s", AMBIENT_SET_FILENAME); } - //Com_Printf( "AS_ParseFile: Loaded %d of %d ambient set(s)\n", pMap.size(), numSets ); + // Com_Printf( "AS_ParseFile: Loaded %d of %d ambient set(s)\n", pMap.size(), numSets ); int iErrorsOccured = 0; - for (namePrecache_m::iterator it = pMap->begin(); it != pMap->end(); ++it) - { - const char* str = (*it).first.c_str(); - ambientSet_t *aSet = aSets->GetSet( str ); - if (!aSet) - { + for (namePrecache_m::iterator it = pMap->begin(); it != pMap->end(); ++it) { + const char *str = (*it).first.c_str(); + ambientSet_t *aSet = aSets->GetSet(str); + if (!aSet) { // I print these red instead of yellow because they're going to cause an ERR_DROP if they occur - Com_Printf( S_COLOR_RED"ERROR: AS_ParseSets: Unable to find ambient soundset \"%s\"!\n",str); + Com_Printf(S_COLOR_RED "ERROR: AS_ParseSets: Unable to find ambient soundset \"%s\"!\n", str); iErrorsOccured++; } } - if (iErrorsOccured) - { - Com_Error( ERR_DROP, "....%d missing sound sets! (see above)\n", iErrorsOccured); + if (iErrorsOccured) { + Com_Error(ERR_DROP, "....%d missing sound sets! (see above)\n", iErrorsOccured); } -// //Done with the precache info, it will be rebuilt on a restart -// pMap->clear(); // do NOT do this here now + // //Done with the precache info, it will be rebuilt on a restart + // pMap->clear(); // do NOT do this here now } /* @@ -858,37 +786,32 @@ Frees up the ambient sound system ------------------------- */ -void AS_Free( void ) -{ - if (aSets) - { +void AS_Free(void) { + if (aSets) { aSets->Free(); delete aSets; aSets = NULL; - currentSet = -1; - oldSet = -1; + currentSet = -1; + oldSet = -1; currentSetTime = 0; oldSetTime = 0; - numSets = 0; + numSets = 0; } } - -void AS_FreePartial(void) -{ - if (aSets) - { +void AS_FreePartial(void) { + if (aSets) { aSets->Free(); - currentSet = -1; - oldSet = -1; + currentSet = -1; + oldSet = -1; currentSetTime = 0; oldSetTime = 0; - numSets = 0; + numSets = 0; pMap = TheNamePrecache(); pMap->clear(); @@ -911,47 +834,47 @@ Fades volumes up or down depending on the action being taken on them. ------------------------- */ -static void AS_UpdateSetVolumes( void ) { - if ( !aSets ) { +static void AS_UpdateSetVolumes(void) { + if (!aSets) { return; } - //Get the sets and validate them - ambientSet_t *current = aSets->GetSet( currentSet ); - if ( !current ) { + // Get the sets and validate them + ambientSet_t *current = aSets->GetSet(currentSet); + if (!current) { return; } float scale; int deltaTime; - if ( current->masterVolume < MAX_SET_VOLUME ) { + if (current->masterVolume < MAX_SET_VOLUME) { deltaTime = cls.realtime - current->fadeTime; - scale = ((float)(deltaTime)/(float)(crossDelay)); + scale = ((float)(deltaTime) / (float)(crossDelay)); current->masterVolume = (int)((scale) * (float)MAX_SET_VOLUME); } - if ( current->masterVolume > MAX_SET_VOLUME ) { + if (current->masterVolume > MAX_SET_VOLUME) { current->masterVolume = MAX_SET_VOLUME; } - //Only update the old set if it's still valid - if ( oldSet == -1 ) { + // Only update the old set if it's still valid + if (oldSet == -1) { return; } - ambientSet_t *old = aSets->GetSet( oldSet ); - if ( !old ) { + ambientSet_t *old = aSets->GetSet(oldSet); + if (!old) { return; } - //Update the volumes - if ( old->masterVolume > 0 ) { + // Update the volumes + if (old->masterVolume > 0) { deltaTime = cls.realtime - old->fadeTime; - scale = ((float)(deltaTime)/(float)(crossDelay)); + scale = ((float)(deltaTime) / (float)(crossDelay)); old->masterVolume = MAX_SET_VOLUME - (int)((scale) * (float)MAX_SET_VOLUME); } - if ( old->masterVolume <= 0 ) { + if (old->masterVolume <= 0) { old->masterVolume = 0; oldSet = -1; } @@ -965,36 +888,36 @@ Does internal maintenance to keep track of changing sets. ------------------------- */ -static void AS_UpdateCurrentSet( int id ) { - if ( !aSets ) { +static void AS_UpdateCurrentSet(int id) { + if (!aSets) { return; } - //Check for a change - if ( id != currentSet ) { - //This is new, so start the fading + // Check for a change + if (id != currentSet) { + // This is new, so start the fading oldSet = currentSet; currentSet = id; - ambientSet_t *current = aSets->GetSet( currentSet ); + ambientSet_t *current = aSets->GetSet(currentSet); // Ste, I just put this null check in for now, not sure if there's a more graceful way to exit this function - dmv - if ( !current ) { + if (!current) { return; } - ambientSet_t *old = aSets->GetSet( oldSet ); - if ( old ) { + ambientSet_t *old = aSets->GetSet(oldSet); + if (old) { old->masterVolume = MAX_SET_VOLUME; old->fadeTime = cls.realtime; } current->masterVolume = 0; - //Set the fading starts + // Set the fading starts current->fadeTime = cls.realtime; } - //Update their volumes if fading + // Update their volumes if fading AS_UpdateSetVolumes(); } @@ -1007,41 +930,41 @@ Alters lastTime to reflect the time updates. ------------------------- */ -static void AS_PlayLocalSet( vec3_t listener_origin, vec3_t origin, const ambientSet_t *set, int entID, int *lastTime ) { - //Make sure it's valid - if ( !set ) { +static void AS_PlayLocalSet(vec3_t listener_origin, vec3_t origin, const ambientSet_t *set, int entID, int *lastTime) { + // Make sure it's valid + if (!set) { return; } vec3_t dir; - VectorSubtract( origin, listener_origin, dir ); - float dist = VectorLength( dir ); + VectorSubtract(origin, listener_origin, dir); + float dist = VectorLength(dir); - //Determine the volume based on distance (NOTE: This sits on top of what SpatializeOrigin does) - float distScale = ( dist < ( set->radius * 0.5f ) ) ? 1 : ( set->radius - dist ) / ( set->radius * 0.5f ); - unsigned char volume = ( distScale > 1.0f || distScale < 0.0f ) ? 0 : (unsigned char) ( set->masterVolume * distScale ); + // Determine the volume based on distance (NOTE: This sits on top of what SpatializeOrigin does) + float distScale = (dist < (set->radius * 0.5f)) ? 1 : (set->radius - dist) / (set->radius * 0.5f); + unsigned char volume = (distScale > 1.0f || distScale < 0.0f) ? 0 : (unsigned char)(set->masterVolume * distScale); - //Add the looping sound - if ( set->loopedWave ) { - S_AddAmbientLoopingSound( origin, volume, set->loopedWave ); + // Add the looping sound + if (set->loopedWave) { + S_AddAmbientLoopingSound(origin, volume, set->loopedWave); } - //Check the time to start another one-shot subwave + // Check the time to start another one-shot subwave int time = cl.serverTime; - if ( ( time - *lastTime ) < ( ( Q_irand( set->time_start, set->time_end ) ) * 1000 ) ) { + if ((time - *lastTime) < ((Q_irand(set->time_start, set->time_end)) * 1000)) { return; } - //Update the time + // Update the time *lastTime = time; - //Scale the volume ranges for the subwaves based on the overall master volume - float volScale = (float) volume / (float) MAX_SET_VOLUME; - volume = (unsigned char) Q_irand( (int)(volScale*set->volRange_start), (int)(volScale*set->volRange_end) ); + // Scale the volume ranges for the subwaves based on the overall master volume + float volScale = (float)volume / (float)MAX_SET_VOLUME; + volume = (unsigned char)Q_irand((int)(volScale * set->volRange_start), (int)(volScale * set->volRange_end)); - //Add the random subwave - if ( set->numSubWaves ) { - S_StartAmbientSound( origin, entID, volume, set->subWaves[Q_irand( 0, set->numSubWaves-1)] ); + // Add the random subwave + if (set->numSubWaves) { + S_StartAmbientSound(origin, entID, volume, set->subWaves[Q_irand(0, set->numSubWaves - 1)]); } } @@ -1054,38 +977,38 @@ Alters lastTime to reflect the time updates. ------------------------- */ -static void AS_PlayAmbientSet( vec3_t origin, const ambientSet_t *set, int *lastTime ) { - //Make sure it's valid - if ( !set ) { +static void AS_PlayAmbientSet(vec3_t origin, const ambientSet_t *set, int *lastTime) { + // Make sure it's valid + if (!set) { return; } - //Add the looping sound - if ( set->loopedWave ) { - S_AddAmbientLoopingSound( origin, (unsigned char) set->masterVolume, set->loopedWave ); + // Add the looping sound + if (set->loopedWave) { + S_AddAmbientLoopingSound(origin, (unsigned char)set->masterVolume, set->loopedWave); } - //Check the time to start another one-shot subwave + // Check the time to start another one-shot subwave int time = cls.realtime; - if ( ( time - *lastTime ) < ( ( Q_irand( set->time_start, set->time_end ) ) * 1000 ) ) { + if ((time - *lastTime) < ((Q_irand(set->time_start, set->time_end)) * 1000)) { return; } - //Update the time + // Update the time *lastTime = time; - //Scale the volume ranges for the subwaves based on the overall master volume - float volScale = (float) set->masterVolume / (float) MAX_SET_VOLUME; - unsigned char volume = Q_irand( (int)(volScale*set->volRange_start), (int)(volScale*set->volRange_end) ); + // Scale the volume ranges for the subwaves based on the overall master volume + float volScale = (float)set->masterVolume / (float)MAX_SET_VOLUME; + unsigned char volume = Q_irand((int)(volScale * set->volRange_start), (int)(volScale * set->volRange_end)); - //Allow for softer noises than the masterVolume, but not louder - if ( volume > set->masterVolume ) { + // Allow for softer noises than the masterVolume, but not louder + if (volume > set->masterVolume) { volume = set->masterVolume; } - //Add the random subwave - if ( set->numSubWaves ) { - S_StartAmbientSound( origin, 0, volume, set->subWaves[Q_irand( 0, set->numSubWaves-1)] ); + // Add the random subwave + if (set->numSubWaves) { + S_StartAmbientSound(origin, 0, volume, set->subWaves[Q_irand(0, set->numSubWaves - 1)]); } } @@ -1097,27 +1020,27 @@ Does maintenance and plays the ambient sets (two if crossfading) ------------------------- */ -void S_UpdateAmbientSet( const char *name, vec3_t origin ) { - if ( !aSets ) { +void S_UpdateAmbientSet(const char *name, vec3_t origin) { + if (!aSets) { return; } - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set ) { + const ambientSet_t *set = aSets->GetSet(name); + if (!set) { return; } - //Update the current and old set for crossfading - AS_UpdateCurrentSet( set->id ); + // Update the current and old set for crossfading + AS_UpdateCurrentSet(set->id); - const ambientSet_t *current = aSets->GetSet( currentSet ); - if ( current ) { - AS_PlayAmbientSet( origin, set, ¤tSetTime ); + const ambientSet_t *current = aSets->GetSet(currentSet); + if (current) { + AS_PlayAmbientSet(origin, set, ¤tSetTime); } - const ambientSet_t *old = aSets->GetSet( oldSet ); - if ( old ) { - AS_PlayAmbientSet( origin, old, &oldSetTime ); + const ambientSet_t *old = aSets->GetSet(oldSet); + if (old) { + AS_PlayAmbientSet(origin, old, &oldSetTime); } } @@ -1127,18 +1050,18 @@ S_AddLocalSet ------------------------- */ -int S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ) { - if ( !aSets ) { +int S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time) { + if (!aSets) { return cl.serverTime; } - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set ) { + const ambientSet_t *set = aSets->GetSet(name); + if (!set) { return cl.serverTime; } int currentTime = time; - AS_PlayLocalSet( listener_origin, origin, set, entID, ¤tTime ); + AS_PlayLocalSet(listener_origin, origin, set, entID, ¤tTime); return currentTime; } @@ -1148,14 +1071,14 @@ AS_GetBModelSound ------------------------- */ -sfxHandle_t AS_GetBModelSound( const char *name, int stage ) { - if ( !aSets ) { +sfxHandle_t AS_GetBModelSound(const char *name, int stage) { + if (!aSets) { return -1; } - //Stage must be within a valid range - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set || stage < 0 || stage > (set->numSubWaves - 1) ) { + // Stage must be within a valid range + const ambientSet_t *set = aSets->GetSet(name); + if (!set || stage < 0 || stage > (set->numSubWaves - 1)) { return -1; } diff --git a/code/client/snd_dma.cpp b/code/client/snd_dma.cpp index bb539e4cd6..0d1aece01c 100644 --- a/code/client/snd_dma.cpp +++ b/code/client/snd_dma.cpp @@ -48,8 +48,8 @@ static void S_SetDynamicMusic_f(void); void S_Update_(); void S_StopAllSounds(void); -static void S_UpdateBackgroundTrack( void ); -sfx_t *S_FindName( const char *name ); +static void S_UpdateBackgroundTrack(void); +sfx_t *S_FindName(const char *name); static int SND_FreeSFXMem(sfx_t *sfx); extern qboolean Sys_LowPhysicalMemory(); @@ -58,127 +58,123 @@ extern qboolean Sys_LowPhysicalMemory(); // // vars for bgrnd music track... // -const int iMP3MusicStream_DiskBytesToRead = 10000;//4096; -const int iMP3MusicStream_DiskBufferSize = iMP3MusicStream_DiskBytesToRead*2; //*10; +const int iMP3MusicStream_DiskBytesToRead = 10000; // 4096; +const int iMP3MusicStream_DiskBufferSize = iMP3MusicStream_DiskBytesToRead * 2; //*10; -typedef struct -{ - qboolean bIsMP3; +typedef struct { + qboolean bIsMP3; // // MP3 specific... // - sfx_t sfxMP3_Bgrnd; - MP3STREAM streamMP3_Bgrnd; // this one is pointed at by the sfx_t's ptr, and is NOT the one the decoder uses every cycle - channel_t chMP3_Bgrnd; // ... but the one in this struct IS. + sfx_t sfxMP3_Bgrnd; + MP3STREAM streamMP3_Bgrnd; // this one is pointed at by the sfx_t's ptr, and is NOT the one the decoder uses every cycle + channel_t chMP3_Bgrnd; // ... but the one in this struct IS. // // MP3 disk streamer stuff... (if music is non-dynamic) // - byte byMP3MusicStream_DiskBuffer[iMP3MusicStream_DiskBufferSize]; - int iMP3MusicStream_DiskReadPos; - int iMP3MusicStream_DiskWindowPos; + byte byMP3MusicStream_DiskBuffer[iMP3MusicStream_DiskBufferSize]; + int iMP3MusicStream_DiskReadPos; + int iMP3MusicStream_DiskWindowPos; // // MP3 disk-load stuff (for use during dynamic music, which is mem-resident) // - byte *pLoadedData; // Z_Malloc, Z_Free // these two MUST be kept as valid/invalid together - char sLoadedDataName[MAX_QPATH]; // " " " " " - int iLoadedDataLen; + byte *pLoadedData; // Z_Malloc, Z_Free // these two MUST be kept as valid/invalid together + char sLoadedDataName[MAX_QPATH]; // " " " " " + int iLoadedDataLen; // // remaining dynamic fields... // - int iXFadeVolumeSeekTime; - int iXFadeVolumeSeekTo; // when changing this, set the above timer to Sys_Milliseconds(). - // Note that this should be thought of more as an up/down bool rather than as a - // number now, in other words set it only to 0 or 255. I'll probably change this - // to actually be a bool later. - int iXFadeVolume; // 0 = silent, 255 = max mixer vol, though still modulated via overall music_volume - float fSmoothedOutVolume; - qboolean bActive; // whether playing or not - qboolean bExists; // whether was even loaded for this level (ie don't try and start playing it) + int iXFadeVolumeSeekTime; + int iXFadeVolumeSeekTo; // when changing this, set the above timer to Sys_Milliseconds(). + // Note that this should be thought of more as an up/down bool rather than as a + // number now, in other words set it only to 0 or 255. I'll probably change this + // to actually be a bool later. + int iXFadeVolume; // 0 = silent, 255 = max mixer vol, though still modulated via overall music_volume + float fSmoothedOutVolume; + qboolean bActive; // whether playing or not + qboolean bExists; // whether was even loaded for this level (ie don't try and start playing it) // // new dynamic fields... // - qboolean bTrackSwitchPending; + qboolean bTrackSwitchPending; MusicState_e eTS_NewState; - float fTS_NewTime; + float fTS_NewTime; // // Generic... // - fileHandle_t s_backgroundFile; // valid handle, else -1 if an MP3 (so that NZ compares still work) - wavinfo_t s_backgroundInfo; - int s_backgroundSamples; + fileHandle_t s_backgroundFile; // valid handle, else -1 if an MP3 (so that NZ compares still work) + wavinfo_t s_backgroundInfo; + int s_backgroundSamples; - void Rewind() - { - MP3Stream_Rewind( &chMP3_Bgrnd ); + void Rewind() { + MP3Stream_Rewind(&chMP3_Bgrnd); s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples; } - void SeekTo(float fTime) - { + void SeekTo(float fTime) { chMP3_Bgrnd.iMP3SlidingDecodeWindowPos = 0; chMP3_Bgrnd.iMP3SlidingDecodeWritePos = 0; - MP3Stream_SeekTo( &chMP3_Bgrnd, fTime ); + MP3Stream_SeekTo(&chMP3_Bgrnd, fTime); s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples; } } MusicInfo_t; -static void S_SetDynamicMusicState( MusicState_e musicState ); +static void S_SetDynamicMusicState(MusicState_e musicState); #define fDYNAMIC_XFADE_SECONDS (1.0f) -static MusicInfo_t tMusic_Info[eBGRNDTRACK_NUMBEROF] = {}; -static qboolean bMusic_IsDynamic = qfalse; -static MusicState_e eMusic_StateActual = eBGRNDTRACK_EXPLORE; // actual state, can be any enum -static MusicState_e eMusic_StateRequest = eBGRNDTRACK_EXPLORE; // requested state, can only be explore, action, boss, or silence -static char sMusic_BackgroundLoop[MAX_QPATH] = {0}; // only valid for non-dynamic music -static char sInfoOnly_CurrentDynamicMusicSet[64]; // any old reasonable size, only has to fit stuff like "kejim_post" +static MusicInfo_t tMusic_Info[eBGRNDTRACK_NUMBEROF] = {}; +static qboolean bMusic_IsDynamic = qfalse; +static MusicState_e eMusic_StateActual = eBGRNDTRACK_EXPLORE; // actual state, can be any enum +static MusicState_e eMusic_StateRequest = eBGRNDTRACK_EXPLORE; // requested state, can only be explore, action, boss, or silence +static char sMusic_BackgroundLoop[MAX_QPATH] = {0}; // only valid for non-dynamic music +static char sInfoOnly_CurrentDynamicMusicSet[64]; // any old reasonable size, only has to fit stuff like "kejim_post" // ////////////////////////// - // ======================================================================= // Internal sound data & structures // ======================================================================= // only begin attenuating sound volumes when outside the FULLVOLUME range -#define SOUND_FULLVOLUME 256 +#define SOUND_FULLVOLUME 256 -#define SOUND_ATTENUATE 0.0008f -#define VOICE_ATTENUATE 0.004f +#define SOUND_ATTENUATE 0.0008f +#define VOICE_ATTENUATE 0.004f -const float SOUND_FMAXVOL=0.75;//1.0; -const int SOUND_MAXVOL=255; +const float SOUND_FMAXVOL = 0.75; // 1.0; +const int SOUND_MAXVOL = 255; -channel_t s_channels[MAX_CHANNELS]; +channel_t s_channels[MAX_CHANNELS]; -int s_soundStarted; -qboolean s_soundMuted; +int s_soundStarted; +qboolean s_soundMuted; -dma_t dma; +dma_t dma; -int listener_number; -vec3_t listener_origin; -vec3_t listener_axis[3]; +int listener_number; +vec3_t listener_origin; +vec3_t listener_axis[3]; -int s_soundtime; // sample PAIRS -int s_paintedtime; // sample PAIRS +int s_soundtime; // sample PAIRS +int s_paintedtime; // sample PAIRS // MAX_SFX may be larger than MAX_SOUNDS because // of custom player sounds -#define MAX_SFX 10000 //512 * 2 -sfx_t s_knownSfx[MAX_SFX]; -int s_numSfx; +#define MAX_SFX 10000 // 512 * 2 +sfx_t s_knownSfx[MAX_SFX]; +int s_numSfx; -#define LOOP_HASH 128 -static sfx_t *sfxHash[LOOP_HASH]; +#define LOOP_HASH 128 +static sfx_t *sfxHash[LOOP_HASH]; cvar_t *s_allowDynamicMusic; cvar_t *s_debugdynamic; cvar_t *s_dynamix; cvar_t *s_initsound; cvar_t *s_khz; -cvar_t *s_language; // note that this is distinct from "g_language" +cvar_t *s_language; // note that this is distinct from "g_language" cvar_t *s_lip_threshold_1; cvar_t *s_lip_threshold_2; cvar_t *s_lip_threshold_3; @@ -192,32 +188,31 @@ cvar_t *s_testsound; cvar_t *s_volume; cvar_t *s_volumeVoice; -typedef struct -{ - unsigned char volume; - vec3_t origin; -// vec3_t velocity; -/* const*/ sfx_t *sfx; - int mergeFrame; - int entnum; - soundChannel_t entchan; +typedef struct { + unsigned char volume; + vec3_t origin; + // vec3_t velocity; + /* const*/ sfx_t *sfx; + int mergeFrame; + int entnum; + soundChannel_t entchan; // For Open AL - qboolean bProcessed; - qboolean bRelative; + qboolean bProcessed; + qboolean bRelative; } loopSound_t; -#define MAX_LOOP_SOUNDS 64 -int numLoopSounds; -loopSound_t loopSounds[MAX_LOOP_SOUNDS]; +#define MAX_LOOP_SOUNDS 64 +int numLoopSounds; +loopSound_t loopSounds[MAX_LOOP_SOUNDS]; -int s_rawend; -portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; -vec3_t s_entityPosition[MAX_GENTITIES]; -int s_entityWavVol[MAX_GENTITIES]; -int s_entityWavVol_back[MAX_GENTITIES]; +int s_rawend; +portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; +vec3_t s_entityPosition[MAX_GENTITIES]; +int s_entityWavVol[MAX_GENTITIES]; +int s_entityWavVol_back[MAX_GENTITIES]; -int s_numChannels; // Number of AL Sources == Num of Channels +int s_numChannels; // Number of AL Sources == Num of Channels #ifdef USE_OPENAL @@ -227,23 +222,23 @@ int s_numChannels; // Number of AL Sources == Num of Channels * \**************************************************************************************************/ -#define sqr(a) ((a)*(a)) -#define ENV_UPDATE_RATE 100 // Environmental audio update rate (in ms) +#define sqr(a) ((a) * (a)) +#define ENV_UPDATE_RATE 100 // Environmental audio update rate (in ms) //#define DISPLAY_CLOSEST_ENVS // Displays the closest env. zones (including the one the listener is in) -#define DEFAULT_REF_DISTANCE 300.0f // Default reference distance -#define DEFAULT_VOICE_REF_DISTANCE 1500.0f // Default voice reference distance +#define DEFAULT_REF_DISTANCE 300.0f // Default reference distance +#define DEFAULT_VOICE_REF_DISTANCE 1500.0f // Default voice reference distance -int s_UseOpenAL = 0; // Determines if using Open AL or the default software mixer +int s_UseOpenAL = 0; // Determines if using Open AL or the default software mixer -ALfloat listener_pos[3]; // Listener Position -ALfloat listener_ori[6]; // Listener Orientation +ALfloat listener_pos[3]; // Listener Position +ALfloat listener_ori[6]; // Listener Orientation -short s_rawdata[MAX_RAW_SAMPLES*2]; // Used for Raw Samples (Music etc...) +short s_rawdata[MAX_RAW_SAMPLES * 2]; // Used for Raw Samples (Music etc...) channel_t *S_OpenALPickChannel(int entnum, int entchannel); -int S_MP3PreProcessLipSync(channel_t *ch, short *data); +int S_MP3PreProcessLipSync(channel_t *ch, short *data); void UpdateSingleShotSounds(); void UpdateLoopingSounds(); void AL_UpdateRawSamples(); @@ -251,46 +246,42 @@ void S_SetLipSyncs(); // EAX Related -typedef struct -{ - ALuint ulNumApertures; - ALint lFXSlotID; - ALboolean bUsed; - struct - { +typedef struct { + ALuint ulNumApertures; + ALint lFXSlotID; + ALboolean bUsed; + struct { ALfloat vPos1[3]; ALfloat vPos2[3]; ALfloat vCenter[3]; } Aperture[64]; } ENVTABLE, *LPENVTABLE; -typedef struct -{ +typedef struct { long lEnvID; long lApertureNum; float flDist; } REVERBDATA, *LPREVERBDATA; -typedef struct -{ - GUID FXSlotGuid; - ALint lEnvID; +typedef struct { + GUID FXSlotGuid; + ALint lEnvID; } FXSLOTINFO, *LPFXSLOTINFO; -ALboolean s_bEAX; // Is EAX 4.0 support available -bool s_bEALFileLoaded; // Has an .eal file been loaded for the current level -bool s_bInWater; // Underwater effect currently active -int s_EnvironmentID; // EAGLE ID of current environment -LPEAXMANAGER s_lpEAXManager; // Pointer to EAXManager object -HINSTANCE s_hEAXManInst; // Handle of EAXManager DLL -EAXSet s_eaxSet; // EAXSet() function -EAXGet s_eaxGet; // EAXGet() function -EAXREVERBPROPERTIES s_eaxLPCur; // Current EAX Parameters -LPENVTABLE s_lpEnvTable=NULL; // Stores information about each environment zone -long s_lLastEnvUpdate; // Time of last EAX update -long s_lNumEnvironments; // Number of environment zones -long s_NumFXSlots; // Number of EAX 4.0 FX Slots -FXSLOTINFO s_FXSlotInfo[EAX_MAX_FXSLOTS]; // Stores information about the EAX 4.0 FX Slots +ALboolean s_bEAX; // Is EAX 4.0 support available +bool s_bEALFileLoaded; // Has an .eal file been loaded for the current level +bool s_bInWater; // Underwater effect currently active +int s_EnvironmentID; // EAGLE ID of current environment +LPEAXMANAGER s_lpEAXManager; // Pointer to EAXManager object +HINSTANCE s_hEAXManInst; // Handle of EAXManager DLL +EAXSet s_eaxSet; // EAXSet() function +EAXGet s_eaxGet; // EAXGet() function +EAXREVERBPROPERTIES s_eaxLPCur; // Current EAX Parameters +LPENVTABLE s_lpEnvTable = NULL; // Stores information about each environment zone +long s_lLastEnvUpdate; // Time of last EAX update +long s_lNumEnvironments; // Number of environment zones +long s_NumFXSlots; // Number of EAX 4.0 FX Slots +FXSLOTINFO s_FXSlotInfo[EAX_MAX_FXSLOTS]; // Stores information about the EAX 4.0 FX Slots static void InitEAXManager(); static void ReleaseEAXManager(); @@ -301,8 +292,7 @@ static void UpdateEAXBuffer(channel_t *ch); static void EALFileInit(const char *level); float CalcDistance(EMPOINT A, EMPOINT B); -void Normalize(EAXVECTOR *v) -{ +void Normalize(EAXVECTOR *v) { float flMagnitude; flMagnitude = (float)sqrt(sqr(v->x) + sqr(v->y) + sqr(v->z)); @@ -314,23 +304,23 @@ void Normalize(EAXVECTOR *v) // EAX 4.0 GUIDS ... confidential information ... -const GUID EAXPROPERTYID_EAX40_FXSlot0 = { 0xc4d79f1e, 0xf1ac, 0x436b, { 0xa8, 0x1d, 0xa7, 0x38, 0xe7, 0x4, 0x54, 0x69} }; +const GUID EAXPROPERTYID_EAX40_FXSlot0 = {0xc4d79f1e, 0xf1ac, 0x436b, {0xa8, 0x1d, 0xa7, 0x38, 0xe7, 0x4, 0x54, 0x69}}; -const GUID EAXPROPERTYID_EAX40_FXSlot1 = { 0x8c00e96, 0x74be, 0x4491, { 0x93, 0xaa, 0xe8, 0xad, 0x35, 0xa4, 0x91, 0x17} }; +const GUID EAXPROPERTYID_EAX40_FXSlot1 = {0x8c00e96, 0x74be, 0x4491, {0x93, 0xaa, 0xe8, 0xad, 0x35, 0xa4, 0x91, 0x17}}; -const GUID EAXPROPERTYID_EAX40_FXSlot2 = { 0x1d433b88, 0xf0f6, 0x4637, { 0x91, 0x9f, 0x60, 0xe7, 0xe0, 0x6b, 0x5e, 0xdd} }; +const GUID EAXPROPERTYID_EAX40_FXSlot2 = {0x1d433b88, 0xf0f6, 0x4637, {0x91, 0x9f, 0x60, 0xe7, 0xe0, 0x6b, 0x5e, 0xdd}}; -const GUID EAXPROPERTYID_EAX40_FXSlot3 = { 0xefff08ea, 0xc7d8, 0x44ab, { 0x93, 0xad, 0x6d, 0xbd, 0x5f, 0x91, 0x0, 0x64} }; +const GUID EAXPROPERTYID_EAX40_FXSlot3 = {0xefff08ea, 0xc7d8, 0x44ab, {0x93, 0xad, 0x6d, 0xbd, 0x5f, 0x91, 0x0, 0x64}}; -const GUID EAXPROPERTYID_EAX40_Context = { 0x1d4870ad, 0xdef, 0x43c0, { 0xa4, 0xc, 0x52, 0x36, 0x32, 0x29, 0x63, 0x42} }; +const GUID EAXPROPERTYID_EAX40_Context = {0x1d4870ad, 0xdef, 0x43c0, {0xa4, 0xc, 0x52, 0x36, 0x32, 0x29, 0x63, 0x42}}; -const GUID EAXPROPERTYID_EAX40_Source = { 0x1b86b823, 0x22df, 0x4eae, { 0x8b, 0x3c, 0x12, 0x78, 0xce, 0x54, 0x42, 0x27} }; +const GUID EAXPROPERTYID_EAX40_Source = {0x1b86b823, 0x22df, 0x4eae, {0x8b, 0x3c, 0x12, 0x78, 0xce, 0x54, 0x42, 0x27}}; -const GUID EAX_NULL_GUID = { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; +const GUID EAX_NULL_GUID = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; -const GUID EAX_PrimaryFXSlotID = { 0xf317866d, 0x924c, 0x450c, { 0x86, 0x1b, 0xe6, 0xda, 0xa2, 0x5e, 0x7c, 0x20} }; +const GUID EAX_PrimaryFXSlotID = {0xf317866d, 0x924c, 0x450c, {0x86, 0x1b, 0xe6, 0xda, 0xa2, 0x5e, 0x7c, 0x20}}; -const GUID EAX_REVERB_EFFECT = { 0xcf95c8f, 0xa3cc, 0x4849, { 0xb0, 0xb6, 0x83, 0x2e, 0xcc, 0x18, 0x22, 0xdf} }; +const GUID EAX_REVERB_EFFECT = {0xcf95c8f, 0xa3cc, 0x4849, {0xb0, 0xb6, 0x83, 0x2e, 0xcc, 0x18, 0x22, 0xdf}}; /**************************************************************************************************\ * @@ -345,132 +335,114 @@ const GUID EAX_REVERB_EFFECT = { 0xcf95c8f, 0xa3cc, 0x4849, { 0xb0, 0xb6, 0x83, #ifndef offsetof #include #endif -static inline void Channel_Clear(channel_t *ch) -{ +static inline void Channel_Clear(channel_t *ch) { // memset (ch, 0, sizeof(*ch)); - memset(ch,0,offsetof(channel_t,MP3SlidingDecodeBuffer)); + memset(ch, 0, offsetof(channel_t, MP3SlidingDecodeBuffer)); - byte *const p = (byte *)ch + offsetof(channel_t,MP3SlidingDecodeBuffer) + sizeof(ch->MP3SlidingDecodeBuffer); + byte *const p = (byte *)ch + offsetof(channel_t, MP3SlidingDecodeBuffer) + sizeof(ch->MP3SlidingDecodeBuffer); - memset(p,0,(sizeof(*ch) - offsetof(channel_t,MP3SlidingDecodeBuffer)) - sizeof(ch->MP3SlidingDecodeBuffer)); + memset(p, 0, (sizeof(*ch) - offsetof(channel_t, MP3SlidingDecodeBuffer)) - sizeof(ch->MP3SlidingDecodeBuffer)); } // ==================================================================== // User-setable variables // ==================================================================== -static void DynamicMusicInfoPrint(void) -{ - if (bMusic_IsDynamic) - { +static void DynamicMusicInfoPrint(void) { + if (bMusic_IsDynamic) { // horribly lazy... ;-) // - const char *psRequestMusicState = Music_BaseStateToString( eMusic_StateRequest ); - const char *psActualMusicState = Music_BaseStateToString( eMusic_StateActual, qtrue ); - if (psRequestMusicState == NULL) - { + const char *psRequestMusicState = Music_BaseStateToString(eMusic_StateRequest); + const char *psActualMusicState = Music_BaseStateToString(eMusic_StateActual, qtrue); + if (psRequestMusicState == NULL) { psRequestMusicState = ""; } - if (psActualMusicState == NULL) - { - psActualMusicState = ""; + if (psActualMusicState == NULL) { + psActualMusicState = ""; } - Com_Printf("( Dynamic music ON, request state: '%s'(%d), actual: '%s' (%d) )\n", psRequestMusicState, eMusic_StateRequest, psActualMusicState, eMusic_StateActual); - } - else - { + Com_Printf("( Dynamic music ON, request state: '%s'(%d), actual: '%s' (%d) )\n", psRequestMusicState, eMusic_StateRequest, psActualMusicState, + eMusic_StateActual); + } else { Com_Printf("( Dynamic music OFF )\n"); } } void S_SoundInfo_f(void) { - Com_Printf("----- Sound Info -----\n" ); + Com_Printf("----- Sound Info -----\n"); if (!s_soundStarted) { - Com_Printf ("sound system not started\n"); + Com_Printf("sound system not started\n"); } else { #ifdef USE_OPENAL - if (s_UseOpenAL) - { - Com_Printf("EAX 4.0 %s supported\n",s_bEAX?"is":"not"); - Com_Printf("Eal file %s loaded\n",s_bEALFileLoaded?"is":"not"); - Com_Printf("s_EnvironmentID = %d\n",s_EnvironmentID); - Com_Printf("s_bInWater = %s\n",s_bInWater?"true":"false"); - } - else - { + if (s_UseOpenAL) { + Com_Printf("EAX 4.0 %s supported\n", s_bEAX ? "is" : "not"); + Com_Printf("Eal file %s loaded\n", s_bEALFileLoaded ? "is" : "not"); + Com_Printf("s_EnvironmentID = %d\n", s_EnvironmentID); + Com_Printf("s_bInWater = %s\n", s_bInWater ? "true" : "false"); + } else { #endif Com_Printf("%5d stereo\n", dma.channels - 1); Com_Printf("%5d samples\n", dma.samples); Com_Printf("%5d samplebits\n", dma.samplebits); Com_Printf("%5d submission_chunk\n", dma.submission_chunk); Com_Printf("%5d speed\n", dma.speed); - Com_Printf( "0x%" PRIxPTR " dma buffer\n", dma.buffer ); + Com_Printf("0x%" PRIxPTR " dma buffer\n", dma.buffer); #ifdef USE_OPENAL } #endif - if (bMusic_IsDynamic) - { + if (bMusic_IsDynamic) { DynamicMusicInfoPrint(); - Com_Printf("( Dynamic music set name: \"%s\" )\n",sInfoOnly_CurrentDynamicMusicSet); - } - else - { - if (!s_allowDynamicMusic->integer) - { - Com_Printf("( Dynamic music inhibited (s_allowDynamicMusic == 0) )\n", sMusic_BackgroundLoop ); - } - if ( tMusic_Info[eBGRNDTRACK_NONDYNAMIC].s_backgroundFile ) - { - Com_Printf("Background file: %s\n", sMusic_BackgroundLoop ); + Com_Printf("( Dynamic music set name: \"%s\" )\n", sInfoOnly_CurrentDynamicMusicSet); + } else { + if (!s_allowDynamicMusic->integer) { + Com_Printf("( Dynamic music inhibited (s_allowDynamicMusic == 0) )\n", sMusic_BackgroundLoop); } - else - { - Com_Printf("No background file.\n" ); + if (tMusic_Info[eBGRNDTRACK_NONDYNAMIC].s_backgroundFile) { + Com_Printf("Background file: %s\n", sMusic_BackgroundLoop); + } else { + Com_Printf("No background file.\n"); } } } S_DisplayFreeMemory(); - Com_Printf("----------------------\n" ); + Com_Printf("----------------------\n"); } - - /* ================ S_Init ================ */ -void S_Init( void ) { - qboolean r; +void S_Init(void) { + qboolean r; Com_Printf("\n------- sound initialization -------\n"); - s_allowDynamicMusic = Cvar_Get( "s_allowDynamicMusic", "1", CVAR_ARCHIVE_ND ); - s_debugdynamic = Cvar_Get( "s_debugdynamic", "0", 0 ); - s_initsound = Cvar_Get( "s_initsound", "1", CVAR_ARCHIVE | CVAR_LATCH ); - s_khz = Cvar_Get( "s_khz", "44", CVAR_ARCHIVE | CVAR_LATCH ); - s_language = Cvar_Get( "s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART ); - s_lip_threshold_1 = Cvar_Get( "s_threshold1", "0.3", 0 ); - s_lip_threshold_2 = Cvar_Get( "s_threshold2", "4", 0 ); - s_lip_threshold_3 = Cvar_Get( "s_threshold3", "6", 0 ); - s_lip_threshold_4 = Cvar_Get( "s_threshold4", "8", 0 ); - s_mixahead = Cvar_Get( "s_mixahead", "0.2", CVAR_ARCHIVE ); - s_mixPreStep = Cvar_Get( "s_mixPreStep", "0.05", CVAR_ARCHIVE ); - s_musicVolume = Cvar_Get( "s_musicvolume", "0.25", CVAR_ARCHIVE ); - s_separation = Cvar_Get( "s_separation", "0.5", CVAR_ARCHIVE ); - s_show = Cvar_Get( "s_show", "0", CVAR_CHEAT ); - s_testsound = Cvar_Get( "s_testsound", "0", CVAR_CHEAT ); - s_volume = Cvar_Get( "s_volume", "0.5", CVAR_ARCHIVE ); - s_volumeVoice = Cvar_Get( "s_volumeVoice", "1.0", CVAR_ARCHIVE ); + s_allowDynamicMusic = Cvar_Get("s_allowDynamicMusic", "1", CVAR_ARCHIVE_ND); + s_debugdynamic = Cvar_Get("s_debugdynamic", "0", 0); + s_initsound = Cvar_Get("s_initsound", "1", CVAR_ARCHIVE | CVAR_LATCH); + s_khz = Cvar_Get("s_khz", "44", CVAR_ARCHIVE | CVAR_LATCH); + s_language = Cvar_Get("s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); + s_lip_threshold_1 = Cvar_Get("s_threshold1", "0.3", 0); + s_lip_threshold_2 = Cvar_Get("s_threshold2", "4", 0); + s_lip_threshold_3 = Cvar_Get("s_threshold3", "6", 0); + s_lip_threshold_4 = Cvar_Get("s_threshold4", "8", 0); + s_mixahead = Cvar_Get("s_mixahead", "0.2", CVAR_ARCHIVE); + s_mixPreStep = Cvar_Get("s_mixPreStep", "0.05", CVAR_ARCHIVE); + s_musicVolume = Cvar_Get("s_musicvolume", "0.25", CVAR_ARCHIVE); + s_separation = Cvar_Get("s_separation", "0.5", CVAR_ARCHIVE); + s_show = Cvar_Get("s_show", "0", CVAR_CHEAT); + s_testsound = Cvar_Get("s_testsound", "0", CVAR_CHEAT); + s_volume = Cvar_Get("s_volume", "0.5", CVAR_ARCHIVE); + s_volumeVoice = Cvar_Get("s_volumeVoice", "1.0", CVAR_ARCHIVE); MP3_InitCvars(); - if ( !s_initsound->integer ) { - s_soundStarted = 0; // needed in case you set s_initsound to 0 midgame then snd_restart (div0 err otherwise later) - Com_Printf ("not initializing.\n"); + if (!s_initsound->integer) { + s_soundStarted = 0; // needed in case you set s_initsound to 0 midgame then snd_restart (div0 err otherwise later) + Com_Printf("not initializing.\n"); Com_Printf("------------------------------------\n"); return; } @@ -485,23 +457,22 @@ void S_Init( void ) { Cmd_AddCommand("s_dynamic", S_SetDynamicMusic_f); #ifdef USE_OPENAL - cvar_t *cv = Cvar_Get("s_UseOpenAL" , "0",CVAR_ARCHIVE|CVAR_LATCH); + cvar_t *cv = Cvar_Get("s_UseOpenAL", "0", CVAR_ARCHIVE | CVAR_LATCH); s_UseOpenAL = !!(cv->integer); - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i, j; - ALCdevice *ALCDevice = alcOpenDevice((ALubyte*)"DirectSound3D"); + ALCdevice *ALCDevice = alcOpenDevice((ALubyte *)"DirectSound3D"); if (!ALCDevice) return; - //Create context(s) + // Create context(s) ALCcontext *ALCContext = alcCreateContext(ALCDevice, NULL); if (!ALCContext) return; - //Set active context + // Set active context alcMakeContextCurrent(ALCContext); if (alcGetError(ALCDevice) != ALC_NO_ERROR) return; @@ -514,15 +485,15 @@ void S_Init( void ) { S_StopAllSounds(); - //S_SoundInfo_f(); + // S_SoundInfo_f(); // Set Listener attributes - ALfloat listenerPos[]={0.0,0.0,0.0}; - ALfloat listenerVel[]={0.0,0.0,0.0}; - ALfloat listenerOri[]={0.0,0.0,-1.0, 0.0,1.0,0.0}; - alListenerfv(AL_POSITION,listenerPos); - alListenerfv(AL_VELOCITY,listenerVel); - alListenerfv(AL_ORIENTATION,listenerOri); + ALfloat listenerPos[] = {0.0, 0.0, 0.0}; + ALfloat listenerVel[] = {0.0, 0.0, 0.0}; + ALfloat listenerOri[] = {0.0, 0.0, -1.0, 0.0, 1.0, 0.0}; + alListenerfv(AL_POSITION, listenerPos); + alListenerfv(AL_VELOCITY, listenerVel); + alListenerfv(AL_ORIENTATION, listenerOri); InitEAXManager(); @@ -531,25 +502,21 @@ void S_Init( void ) { s_numChannels = 0; // Create as many AL Sources (up to Max) as possible - for (i = 0; i < MAX_CHANNELS; i++) - { + for (i = 0; i < MAX_CHANNELS; i++) { alGenSources(1, &s_channels[i].alSource); // &g_Sources[i]); - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { // Reached limit of sources break; } alSourcef(s_channels[i].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { break; } // Sources / Channels are not sending to any Slots (other than the Listener / Primary FX Slot) s_channels[i].lSlotID = -1; - if (s_bEAX) - { + if (s_bEAX) { // Remove the RoomAuto flag from each Source (to remove Reverb Engine Statistical // model that is assuming units are in metres) // Without this call reverb sends from the sources will attenuate too quickly @@ -557,9 +524,7 @@ void S_Init( void ) { unsigned long ulFlags = 0; - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_FLAGS, - s_channels[i].alSource, &ulFlags, sizeof(ulFlags))!=AL_NO_ERROR) - { + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_FLAGS, s_channels[i].alSource, &ulFlags, sizeof(ulFlags)) != AL_NO_ERROR) { #ifdef _WIN32 OutputDebugString("Failed to to remove Source flags\n"); #endif @@ -571,10 +536,8 @@ void S_Init( void ) { // Generate AL Buffers for streaming audio playback (used for MP3s) channel_t *ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { alGenBuffers(1, &(ch->buffers[j].BufferID)); ch->buffers[j].Status = UNQUEUED; ch->buffers[j].Data = (char *)Z_Malloc(STREAMING_BUFFER_SIZE, TAG_SND_RAWDATA, qfalse); @@ -611,51 +574,47 @@ void S_Init( void ) { // s_init could be called in game, if so there may be an .eal file // for this level - const char *mapname = Cvar_VariableString( "mapname" ); + const char *mapname = Cvar_VariableString("mapname"); EALFileInit(mapname); - } - else - { + } else { #endif r = SNDDMA_Init(s_khz->integer); - if ( r ) { + if (r) { s_soundStarted = 1; s_soundMuted = qtrue; - // s_numSfx = 0; // do NOT do this here now!!! + // s_numSfx = 0; // do NOT do this here now!!! s_soundtime = 0; s_paintedtime = 0; - S_StopAllSounds (); + S_StopAllSounds(); - //S_SoundInfo_f(); + // S_SoundInfo_f(); } #ifdef USE_OPENAL } #endif -// Com_Printf("------------------------------------\n"); + // Com_Printf("------------------------------------\n"); -// Com_Printf("\n--- ambient sound initialization ---\n"); + // Com_Printf("\n--- ambient sound initialization ---\n"); AS_Init(); } // only called from snd_restart. QA request... // -void S_ReloadAllUsedSounds(void) -{ - if (s_soundStarted && !s_soundMuted ) - { +void S_ReloadAllUsedSounds(void) { + if (s_soundStarted && !s_soundMuted) { // new bit, reload all soundsthat are used on the current level... // - for (int i=1 ; i < s_numSfx ; i++) // start @ 1 to skip freeing default sound + for (int i = 1; i < s_numSfx; i++) // start @ 1 to skip freeing default sound { sfx_t *sfx = &s_knownSfx[i]; - if (!sfx->bInMemory && !sfx->bDefaultSound && sfx->iLastLevelUsedOn == re.RegisterMedia_GetLevel()){ + if (!sfx->bInMemory && !sfx->bDefaultSound && sfx->iLastLevelUsedOn == re.RegisterMedia_GetLevel()) { S_memoryLoad(sfx); } } @@ -666,9 +625,8 @@ void S_ReloadAllUsedSounds(void) // Shutdown sound engine // ======================================================================= -void S_Shutdown( void ) -{ - if ( !s_soundStarted ) { +void S_Shutdown(void) { + if (!s_soundStarted) { return; } @@ -676,26 +634,21 @@ void S_Shutdown( void ) S_UnCacheDynamicMusic(); #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i, j; // Release all the AL Sources (including Music channel (Source 0)) - for (i = 0; i < s_numChannels; i++) - { + for (i = 0; i < s_numChannels; i++) { alDeleteSources(1, &(s_channels[i].alSource)); } // Release Streaming AL Buffers channel_t *ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { alDeleteBuffers(1, &(ch->buffers[j].BufferID)); ch->buffers[j].BufferID = 0; ch->buffers[j].Status = UNQUEUED; - if (ch->buffers[j].Data) - { + if (ch->buffers[j].Data) { Z_Free(ch->buffers[j].Data); ch->buffers[j].Data = NULL; } @@ -715,9 +668,7 @@ void S_Shutdown( void ) s_numChannels = 0; - } - else - { + } else { #endif SNDDMA_Shutdown(); #ifdef USE_OPENAL @@ -742,22 +693,18 @@ void S_Shutdown( void ) Mutes / Unmutes all OpenAL sound */ #ifdef USE_OPENAL -void S_AL_MuteAllSounds(qboolean bMute) -{ - if (!s_soundStarted) - return; - - if (!s_UseOpenAL) - return; - - if (bMute) - { - alListenerf(AL_GAIN, 0.0f); - } - else - { - alListenerf(AL_GAIN, 1.0f); - } +void S_AL_MuteAllSounds(qboolean bMute) { + if (!s_soundStarted) + return; + + if (!s_UseOpenAL) + return; + + if (bMute) { + alListenerf(AL_GAIN, 0.0f); + } else { + alListenerf(AL_GAIN, 1.0f); + } } #endif @@ -770,20 +717,22 @@ return a hash value for the sfx name ================ */ static long S_HashSFXName(const char *name) { - int i; - long hash; - char letter; + int i; + long hash; + char letter; hash = 0; i = 0; while (name[i] != '\0') { letter = tolower(name[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (LOOP_HASH-1); + hash &= (LOOP_HASH - 1); return hash; } @@ -794,59 +743,57 @@ S_FindName Will allocate a new sfx if it isn't found ================== */ -sfx_t *S_FindName( const char *name ) { - int i; - int hash; +sfx_t *S_FindName(const char *name) { + int i; + int hash; - sfx_t *sfx; + sfx_t *sfx; if (!name) { - Com_Error (ERR_FATAL, "S_FindName: NULL"); + Com_Error(ERR_FATAL, "S_FindName: NULL"); } if (!name[0]) { - Com_Error (ERR_FATAL, "S_FindName: empty name"); + Com_Error(ERR_FATAL, "S_FindName: empty name"); } if (strlen(name) >= MAX_QPATH) { - Com_Error (ERR_FATAL, "Sound name too long: %s", name); + Com_Error(ERR_FATAL, "Sound name too long: %s", name); } char sSoundNameNoExt[MAX_QPATH]; - COM_StripExtension(name,sSoundNameNoExt, sizeof(sSoundNameNoExt)); + COM_StripExtension(name, sSoundNameNoExt, sizeof(sSoundNameNoExt)); hash = S_HashSFXName(sSoundNameNoExt); sfx = sfxHash[hash]; // see if already loaded while (sfx) { - if (!Q_stricmp(sfx->sSoundName, sSoundNameNoExt) ) { + if (!Q_stricmp(sfx->sSoundName, sSoundNameNoExt)) { return sfx; } sfx = sfx->next; } -/* - // find a free sfx - for (i=0 ; i < s_numSfx ; i++) { - if (!s_knownSfx[i].soundName[0]) { - break; + /* + // find a free sfx + for (i=0 ; i < s_numSfx ; i++) { + if (!s_knownSfx[i].soundName[0]) { + break; + } } - } -*/ - i = s_numSfx; //we don't clear the soundName after failed loads any more, so it'll always be the last entry + */ + i = s_numSfx; // we don't clear the soundName after failed loads any more, so it'll always be the last entry - if (s_numSfx == MAX_SFX) - { + if (s_numSfx == MAX_SFX) { // ok, no sfx's free, but are there any with defaultSound set? (which the registering ent will never // see because he gets zero returned if it's default...) // - for (i=0 ; i < s_numSfx ; i++) { + for (i = 0; i < s_numSfx; i++) { if (s_knownSfx[i].bDefaultSound) { break; } } - if (i==s_numSfx) - { + if (i == s_numSfx) { // genuinely out of handles... // if we ever reach this, let me know and I'll either boost the array or put in a map-used-on @@ -855,18 +802,16 @@ sfx_t *S_FindName( const char *name ) { // events, so current MAX_SFX limit should do, or only need a small boost... -ste // - Com_Error (ERR_FATAL, "S_FindName: out of sfx_t"); + Com_Error(ERR_FATAL, "S_FindName: out of sfx_t"); } - } - else - { + } else { s_numSfx++; } sfx = &s_knownSfx[i]; - memset (sfx, 0, sizeof(*sfx)); + memset(sfx, 0, sizeof(*sfx)); Q_strncpyz(sfx->sSoundName, sSoundNameNoExt, sizeof(sfx->sSoundName)); - Q_strlwr(sfx->sSoundName);//force it down low + Q_strlwr(sfx->sSoundName); // force it down low sfx->next = sfxHash[hash]; sfxHash[hash] = sfx; @@ -880,16 +825,15 @@ S_DefaultSound ================= */ #ifdef _DEBUG -static void S_DefaultSound( sfx_t *sfx ) { +static void S_DefaultSound(sfx_t *sfx) { - int i; + int i; - sfx->iSoundLengthInSamples = 512; // #samples, ie shorts - sfx->pSoundData = (short *) SND_malloc(512*2, sfx); // ... so *2 for alloc bytes - sfx->bInMemory = true; + sfx->iSoundLengthInSamples = 512; // #samples, ie shorts + sfx->pSoundData = (short *)SND_malloc(512 * 2, sfx); // ... so *2 for alloc bytes + sfx->bInMemory = true; - for ( i=0 ; i < sfx->iSoundLengthInSamples ; i++ ) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i++) { sfx->pSoundData[i] = i; } } @@ -904,7 +848,7 @@ This is called when the hunk is cleared and the sounds are no longer valid. =================== */ -void S_DisableSounds( void ) { +void S_DisableSounds(void) { S_StopAllSounds(); s_soundMuted = qtrue; } @@ -915,19 +859,16 @@ S_BeginRegistration ===================== */ -void S_BeginRegistration( void ) -{ - s_soundMuted = qfalse; // we can play again +void S_BeginRegistration(void) { + s_soundMuted = qfalse; // we can play again #ifdef USE_OPENAL // Find name of level so we can load in the appropriate EAL file - if (s_UseOpenAL) - { - const char *mapname = Cvar_VariableString( "mapname" ); + if (s_UseOpenAL) { + const char *mapname = Cvar_VariableString("mapname"); EALFileInit(mapname); // clear carry crap from previous map - for (int i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (int i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].lEnvID = -1; } } @@ -937,12 +878,12 @@ void S_BeginRegistration( void ) SND_setup(); s_numSfx = 0; - memset( s_knownSfx, 0, sizeof( s_knownSfx ) ); - memset(sfxHash, 0, sizeof(sfx_t *)*LOOP_HASH); + memset(s_knownSfx, 0, sizeof(s_knownSfx)); + memset(sfxHash, 0, sizeof(sfx_t *) * LOOP_HASH); #ifdef _DEBUG - sfx_t *sfx = S_FindName( "***DEFAULT***" ); - S_DefaultSound( sfx ); + sfx_t *sfx = S_FindName("***DEFAULT***"); + S_DefaultSound(sfx); #else S_RegisterSound("sound/null.wav"); #endif @@ -950,11 +891,9 @@ void S_BeginRegistration( void ) } #ifdef USE_OPENAL -static void EALFileInit(const char *level) -{ +static void EALFileInit(const char *level) { // If an EAL File is already unloaded, remove it - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { UnloadEALFile(); } @@ -962,34 +901,27 @@ static void EALFileInit(const char *level) s_bInWater = false; // Try and load an EAL file for the new level - char name[MAX_QPATH]; + char name[MAX_QPATH]; COM_StripExtension(level, name, sizeof(name)); - char szEALFilename[MAX_QPATH]; + char szEALFilename[MAX_QPATH]; Com_sprintf(szEALFilename, MAX_QPATH, "eagle/%s.eal", name); s_bEALFileLoaded = LoadEALFile(szEALFilename); - if (!s_bEALFileLoaded) - { + if (!s_bEALFileLoaded) { Com_sprintf(szEALFilename, MAX_QPATH, "base/eagle/%s.eal", name); s_bEALFileLoaded = LoadEALFile(szEALFilename); } - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { s_lLastEnvUpdate = timeGetTime(); - } - else - { + } else { // Mute reverbs if no EAL file is found - if ((s_bEAX)&&(s_eaxSet)) - { + if ((s_bEAX) && (s_eaxSet)) { long lRoom = -10000; - for (int i = 0; i < s_NumFXSlots; i++) - { - s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_ROOM, NULL, - &lRoom, sizeof(long)); + for (int i = 0; i < s_NumFXSlots; i++) { + s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_ROOM, NULL, &lRoom, sizeof(long)); } } } @@ -1003,37 +935,33 @@ S_RegisterSound Creates a default buzz sound if the file can't be loaded ================== */ -sfxHandle_t S_RegisterSound( const char *name) -{ - sfx_t *sfx; +sfxHandle_t S_RegisterSound(const char *name) { + sfx_t *sfx; if (!s_soundStarted) { return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( S_COLOR_RED"Sound name exceeds MAX_QPATH - %s\n", name ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf(S_COLOR_RED "Sound name exceeds MAX_QPATH - %s\n", name); return 0; } - sfx = S_FindName( name ); + sfx = S_FindName(name); SND_TouchSFX(sfx); - if ( sfx->bDefaultSound ) + if (sfx->bDefaultSound) return 0; #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if ((sfx->pSoundData) || (sfx->Buffer)) return sfx - s_knownSfx; - } - else + } else #endif { - if ( sfx->pSoundData ) - { + if (sfx->pSoundData) { return sfx - s_knownSfx; } } @@ -1042,9 +970,9 @@ sfxHandle_t S_RegisterSound( const char *name) S_memoryLoad(sfx); - if ( sfx->bDefaultSound ) { + if (sfx->bDefaultSound) { #ifndef FINAL_BUILD - Com_DPrintf( S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->sSoundName ); + Com_DPrintf(S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->sSoundName); #endif return 0; } @@ -1052,33 +980,29 @@ sfxHandle_t S_RegisterSound( const char *name) return sfx - s_knownSfx; } -void S_memoryLoad(sfx_t *sfx) -{ +void S_memoryLoad(sfx_t *sfx) { // load the sound file... // - if ( !S_LoadSound( sfx ) ) - { -// Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->sSoundName ); + if (!S_LoadSound(sfx)) { + // Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->sSoundName ); sfx->bDefaultSound = true; } sfx->bInMemory = true; } //============================================================================= -static qboolean S_CheckChannelStomp( int chan1, int chan2 ) -{ +static qboolean S_CheckChannelStomp(int chan1, int chan2) { #ifdef USE_OPENAL if (!s_UseOpenAL) #endif { - if ( chan1 == chan2 ) - { + if (chan1 == chan2) { return qtrue; } } - if ( ( chan1 == CHAN_VOICE || chan1 == CHAN_VOICE_ATTEN || chan1 == CHAN_VOICE_GLOBAL ) && ( chan2 == CHAN_VOICE || chan2 == CHAN_VOICE_ATTEN || chan2 == CHAN_VOICE_GLOBAL ) ) - { + if ((chan1 == CHAN_VOICE || chan1 == CHAN_VOICE_ATTEN || chan1 == CHAN_VOICE_GLOBAL) && + (chan2 == CHAN_VOICE || chan2 == CHAN_VOICE_ATTEN || chan2 == CHAN_VOICE_GLOBAL)) { return qtrue; } @@ -1090,44 +1014,37 @@ static qboolean S_CheckChannelStomp( int chan1, int chan2 ) S_PickChannel ================= */ -channel_t *S_PickChannel(int entnum, int entchannel) -{ - int ch_idx; - channel_t *ch, *firstToDie; - qboolean foundChan = qfalse; +channel_t *S_PickChannel(int entnum, int entchannel) { + int ch_idx; + channel_t *ch, *firstToDie; + qboolean foundChan = qfalse; #ifdef USE_OPENAL if (s_UseOpenAL) return S_OpenALPickChannel(entnum, entchannel); #endif - if ( entchannel<0 ) { - Com_Error (ERR_DROP, "S_PickChannel: entchannel<0"); + if (entchannel < 0) { + Com_Error(ERR_DROP, "S_PickChannel: entchannel<0"); } // Check for replacement sound, or find the best one to replace - firstToDie = &s_channels[0]; + firstToDie = &s_channels[0]; - for ( int pass = 0; (pass < ((entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN)?1:2)) && !foundChan; pass++ ) - { - for (ch_idx = 0, ch = &s_channels[0]; ch_idx < MAX_CHANNELS ; ch_idx++, ch++ ) - { - if ( entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN || pass > 0 ) - {//if we're on the second pass, just find the first open chan - if ( !ch->thesfx ) - {//grab the first open channel + for (int pass = 0; (pass < ((entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN) ? 1 : 2)) && !foundChan; pass++) { + for (ch_idx = 0, ch = &s_channels[0]; ch_idx < MAX_CHANNELS; ch_idx++, ch++) { + if (entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN || pass > 0) { // if we're on the second pass, just find the first open chan + if (!ch->thesfx) { // grab the first open channel firstToDie = ch; break; } - } - else if ( ch->entnum == entnum && S_CheckChannelStomp( ch->entchannel, entchannel ) ) - { + } else if (ch->entnum == entnum && S_CheckChannelStomp(ch->entchannel, entchannel)) { // always override sound from same entity - if ( s_show->integer == 1 && ch->thesfx ) { - Com_Printf( S_COLOR_YELLOW"...overrides %s\n", ch->thesfx->sSoundName ); - ch->thesfx = 0; //just to clear the next error msg + if (s_show->integer == 1 && ch->thesfx) { + Com_Printf(S_COLOR_YELLOW "...overrides %s\n", ch->thesfx->sSoundName); + ch->thesfx = 0; // just to clear the next error msg } firstToDie = ch; foundChan = qtrue; @@ -1135,26 +1052,26 @@ channel_t *S_PickChannel(int entnum, int entchannel) } // don't let anything else override local player sounds - if ( ch->entnum == listener_number && entnum != listener_number && ch->thesfx) { + if (ch->entnum == listener_number && entnum != listener_number && ch->thesfx) { continue; } // don't override loop sounds - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } - if ( ch->startSample < firstToDie->startSample ) { + if (ch->startSample < firstToDie->startSample) { firstToDie = ch; } } } - if ( s_show->integer == 1 && firstToDie->thesfx ) { - Com_Printf( S_COLOR_RED"***kicking %s\n", firstToDie->thesfx->sSoundName ); + if (s_show->integer == 1 && firstToDie->thesfx) { + Com_Printf(S_COLOR_RED "***kicking %s\n", firstToDie->thesfx->sSoundName); } - Channel_Clear(firstToDie); // memset(firstToDie, 0, sizeof(*firstToDie)); + Channel_Clear(firstToDie); // memset(firstToDie, 0, sizeof(*firstToDie)); return firstToDie; } @@ -1166,30 +1083,26 @@ channel_t *S_PickChannel(int entnum, int entchannel) on hardware this way esp. rapid fire modes of weapons! */ #ifdef USE_OPENAL -channel_t *S_OpenALPickChannel(int entnum, int entchannel) -{ - int ch_idx; - channel_t *ch, *ch_firstToDie; - bool foundChan = false; - float source_pos[3]; - - if ( entchannel < 0 ) - { - Com_Error (ERR_DROP, "S_PickChannel: entchannel<0"); +channel_t *S_OpenALPickChannel(int entnum, int entchannel) { + int ch_idx; + channel_t *ch, *ch_firstToDie; + bool foundChan = false; + float source_pos[3]; + + if (entchannel < 0) { + Com_Error(ERR_DROP, "S_PickChannel: entchannel<0"); } // Check for replacement sound, or find the best one to replace - ch_firstToDie = s_channels + 1; // channel 0 is reserved for Music + ch_firstToDie = s_channels + 1; // channel 0 is reserved for Music - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if ( ch->entnum == entnum && S_CheckChannelStomp( ch->entchannel, entchannel ) ) - { + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if (ch->entnum == entnum && S_CheckChannelStomp(ch->entchannel, entchannel)) { // always override sound from same entity - if ( s_show->integer == 1 && ch->thesfx ) { - Com_Printf( S_COLOR_YELLOW"...overrides %s\n", ch->thesfx->sSoundName ); - ch->thesfx = 0; //just to clear the next error msg + if (s_show->integer == 1 && ch->thesfx) { + Com_Printf(S_COLOR_YELLOW "...overrides %s\n", ch->thesfx->sSoundName); + ch->thesfx = 0; // just to clear the next error msg } ch_firstToDie = ch; foundChan = true; @@ -1198,24 +1111,18 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } if (!foundChan) - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - // See if the channel is free - if (!ch->thesfx) - { - ch_firstToDie = ch; - foundChan = true; - break; + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + // See if the channel is free + if (!ch->thesfx) { + ch_firstToDie = ch; + foundChan = true; + break; + } } - } - if (!foundChan) - { - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if ( (ch->entnum == entnum) && (ch->entchannel == entchannel) && (ch->entchannel != CHAN_AMBIENT) - && (ch->entnum != listener_number) ) - { + if (!foundChan) { + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if ((ch->entnum == entnum) && (ch->entchannel == entchannel) && (ch->entchannel != CHAN_AMBIENT) && (ch->entnum != listener_number)) { // Same entity and same type of sound effect (entchannel) ch_firstToDie = ch; foundChan = true; @@ -1227,13 +1134,11 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) int longestDist; int dist; - if (!foundChan) - { + if (!foundChan) { // Find sound effect furthest from listener ch = s_channels + 1; - if (ch->fixed_origin) - { + if (ch->fixed_origin) { // Convert to Open AL co-ordinates source_pos[0] = ch->origin[0]; source_pos[1] = ch->origin[2]; @@ -1242,22 +1147,16 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) longestDist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); - } - else - { + } else { if (ch->entnum == listener_number) longestDist = 0; - else - { - if (ch->bLooping) - { + else { + if (ch->bLooping) { // Convert to Open AL co-ordinates source_pos[0] = loopSounds[ch->entnum].origin[0]; source_pos[1] = loopSounds[ch->entnum].origin[2]; source_pos[2] = -loopSounds[ch->entnum].origin[1]; - } - else - { + } else { // Convert to Open AL co-ordinates source_pos[0] = s_entityPosition[ch->entnum][0]; source_pos[1] = s_entityPosition[ch->entnum][2]; @@ -1270,10 +1169,8 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } } - for (ch_idx = 2, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if (ch->fixed_origin) - { + for (ch_idx = 2, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if (ch->fixed_origin) { // Convert to Open AL co-ordinates source_pos[0] = ch->origin[0]; source_pos[1] = ch->origin[2]; @@ -1282,22 +1179,16 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) dist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); - } - else - { + } else { if (ch->entnum == listener_number) dist = 0; - else - { - if (ch->bLooping) - { + else { + if (ch->bLooping) { // Convert to Open AL co-ordinates source_pos[0] = loopSounds[ch->entnum].origin[0]; source_pos[1] = loopSounds[ch->entnum].origin[2]; source_pos[2] = -loopSounds[ch->entnum].origin[1]; - } - else - { + } else { // Convert to Open AL co-ordinates source_pos[0] = s_entityPosition[ch->entnum][0]; source_pos[1] = s_entityPosition[ch->entnum][2]; @@ -1305,24 +1196,21 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } dist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + - ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); } } - if (dist > longestDist) - { + if (dist > longestDist) { longestDist = dist; ch_firstToDie = ch; } } } - if (ch_firstToDie->bPlaying) - { - if (s_show->integer == 1 && ch_firstToDie->thesfx ) - { - Com_Printf(S_COLOR_RED"***kicking %s\n", ch_firstToDie->thesfx->sSoundName ); + if (ch_firstToDie->bPlaying) { + if (s_show->integer == 1 && ch_firstToDie->thesfx) { + Com_Printf(S_COLOR_RED "***kicking %s\n", ch_firstToDie->thesfx->sSoundName); } // Stop sound @@ -1336,7 +1224,7 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) ch_firstToDie->bProcessed = false; ch_firstToDie->bStreaming = false; - return ch_firstToDie; + return ch_firstToDie; } #endif @@ -1347,82 +1235,67 @@ S_SpatializeOrigin Used for spatializing s_channels ================= */ -static void S_SpatializeOrigin (const vec3_t origin, float master_vol, int *left_vol, int *right_vol, soundChannel_t channel) -{ - vec_t dot; - vec_t dist; - vec_t lscale, rscale, scale; - vec3_t source_vec; - float dist_mult = SOUND_ATTENUATE; +static void S_SpatializeOrigin(const vec3_t origin, float master_vol, int *left_vol, int *right_vol, soundChannel_t channel) { + vec_t dot; + vec_t dist; + vec_t lscale, rscale, scale; + vec3_t source_vec; + float dist_mult = SOUND_ATTENUATE; // calculate stereo seperation and distance attenuation VectorSubtract(origin, listener_origin, source_vec); dist = VectorNormalize(source_vec); - if ( channel == CHAN_VOICE ) - { + if (channel == CHAN_VOICE) { dist -= SOUND_FULLVOLUME * 3.0f; -// dist_mult = VOICE_ATTENUATE; // tweak added (this fixes an NPC dialogue "in your ears" bug, but we're not sure if it'll make a bunch of others fade too early. Too close to shipping...) - } - else if ( channel == CHAN_LESS_ATTEN ) - { + // dist_mult = VOICE_ATTENUATE; // tweak added (this fixes an NPC dialogue "in your ears" bug, but we're not sure if it'll make a bunch of others + //fade too early. Too close to shipping...) + } else if (channel == CHAN_LESS_ATTEN) { dist -= SOUND_FULLVOLUME * 5.0f; // maybe is too large - } - else if ( channel == CHAN_VOICE_ATTEN ) - { + } else if (channel == CHAN_VOICE_ATTEN) { dist -= SOUND_FULLVOLUME * 1.35f; // used to be 0.15f, dropped off too sharply - dmv dist_mult = VOICE_ATTENUATE; - } - else if ( channel == CHAN_VOICE_GLOBAL ) - { + } else if (channel == CHAN_VOICE_GLOBAL) { dist = -1; - } - else // use normal attenuation. + } else // use normal attenuation. { dist -= SOUND_FULLVOLUME; } - if (dist < 0) - { - dist = 0; // close enough to be at full volume + if (dist < 0) { + dist = 0; // close enough to be at full volume } - dist *= dist_mult; // different attenuation levels + dist *= dist_mult; // different attenuation levels dot = -DotProduct(listener_axis[1], source_vec); - if (dma.channels == 1) // || !dist_mult) - { // no attenuation = no spatialization + if (dma.channels == 1) // || !dist_mult) + { // no attenuation = no spatialization rscale = SOUND_FMAXVOL; lscale = SOUND_FMAXVOL; - } - else - { - //rscale = 0.5 * (1.0 + dot); - //lscale = 0.5 * (1.0 - dot); - rscale = s_separation->value + ( 1.0f - s_separation->value ) * dot; - lscale = s_separation->value - ( 1.0f - s_separation->value ) * dot; - if ( rscale < 0 ) - { + } else { + // rscale = 0.5 * (1.0 + dot); + // lscale = 0.5 * (1.0 - dot); + rscale = s_separation->value + (1.0f - s_separation->value) * dot; + lscale = s_separation->value - (1.0f - s_separation->value) * dot; + if (rscale < 0) { rscale = 0; } - if ( lscale < 0 ) - { + if (lscale < 0) { lscale = 0; } } // add in distance effect scale = (1.0f - dist) * rscale; - *right_vol = (int) (master_vol * scale); - if (*right_vol < 0) - { + *right_vol = (int)(master_vol * scale); + if (*right_vol < 0) { *right_vol = 0; } scale = (1.0f - dist) * lscale; - *left_vol = (int) (master_vol * scale); - if (*left_vol < 0) - { + *left_vol = (int)(master_vol * scale); + if (*left_vol < 0) { *left_vol = 0; } } @@ -1439,51 +1312,46 @@ Starts an ambient, 'one-shot" sound. ==================== */ -void S_StartAmbientSound( const vec3_t origin, int entityNum, unsigned char volume, sfxHandle_t sfxHandle ) -{ - channel_t *ch; +void S_StartAmbientSound(const vec3_t origin, int entityNum, unsigned char volume, sfxHandle_t sfxHandle) { + channel_t *ch; /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( !origin && ( entityNum < 0 || entityNum >= MAX_GENTITIES ) ) - Com_Error( ERR_DROP, "S_StartAmbientSound: bad entitynum %i", entityNum ); + if (!origin && (entityNum < 0 || entityNum >= MAX_GENTITIES)) + Com_Error(ERR_DROP, "S_StartAmbientSound: bad entitynum %i", entityNum); - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) - Com_Error( ERR_DROP, "S_StartAmbientSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) + Com_Error(ERR_DROP, "S_StartAmbientSound: handle %i out of range", sfxHandle); - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if (volume==0) + if (s_UseOpenAL) { + if (volume == 0) return; } #endif - if ( s_show->integer == 1 ) { - Com_Printf( "%i : %s on (%d) Ambient\n", s_paintedtime, sfx->sSoundName, entityNum ); + if (s_show->integer == 1) { + Com_Printf("%i : %s on (%d) Ambient\n", s_paintedtime, sfx->sSoundName, entityNum); } // pick a channel to play on - ch = S_PickChannel( entityNum, CHAN_AMBIENT ); + ch = S_PickChannel(entityNum, CHAN_AMBIENT); if (!ch) { return; } - if (origin) - { - VectorCopy (origin, ch->origin); + if (origin) { + VectorCopy(origin, ch->origin); ch->fixed_origin = qtrue; - } - else - { + } else { ch->fixed_origin = qfalse; } @@ -1493,18 +1361,15 @@ void S_StartAmbientSound( const vec3_t origin, int entityNum, unsigned char volu ch->thesfx = sfx; ch->startSample = START_SAMPLE_IMMEDIATE; - ch->leftvol = ch->master_vol; // these will get calced at next spatialize - ch->rightvol = ch->master_vol; // unless the game isn't running + ch->leftvol = ch->master_vol; // these will get calced at next spatialize + ch->rightvol = ch->master_vol; // unless the game isn't running - if (sfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader,sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); - //ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... - //ch->iMP3SlidingDecodeWindowPos= 0; // - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (sfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + // ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... + // ch->iMP3SlidingDecodeWindowPos= 0; // + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } @@ -1517,53 +1382,46 @@ if pos is NULL, the sound will be dynamically sourced from the entity Entchannel 0 will never override a playing sound ==================== */ -void S_StartSound(const vec3_t origin, int entityNum, soundChannel_t entchannel, sfxHandle_t sfxHandle ) -{ - channel_t *ch; +void S_StartSound(const vec3_t origin, int entityNum, soundChannel_t entchannel, sfxHandle_t sfxHandle) { + channel_t *ch; /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( !origin && ( entityNum < 0 || entityNum >= MAX_GENTITIES ) ) { - Com_Error( ERR_DROP, "S_StartSound: bad entitynum %i", entityNum ); + if (!origin && (entityNum < 0 || entityNum >= MAX_GENTITIES)) { + Com_Error(ERR_DROP, "S_StartSound: bad entitynum %i", entityNum); } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( s_show->integer == 1 ) { - Com_Printf( "%i : %s for ent %d, chan=%d\n", s_paintedtime, sfx->sSoundName, entityNum, entchannel ); + if (s_show->integer == 1) { + Com_Printf("%i : %s for ent %d, chan=%d\n", s_paintedtime, sfx->sSoundName, entityNum, entchannel); } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i; - if (entchannel == CHAN_VOICE) - { + if (entchannel == CHAN_VOICE) { // Make howlers and sand_creature VOICE effects use the normal fall-off (they will still be affected // by the Voice Volume) - if ((strstr(sfx->sSoundName, "sand_creature")!=NULL) || (strstr(sfx->sSoundName, "howler")!=NULL)) - { + if ((strstr(sfx->sSoundName, "sand_creature") != NULL) || (strstr(sfx->sSoundName, "howler") != NULL)) { entchannel = CHAN_VOICE_ATTEN; } } - if (entchannel == CHAN_WEAPON) - { + if (entchannel == CHAN_WEAPON) { // Check if we are playing a 'charging' sound, if so, stop it now .. ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->entnum == entityNum) && (ch->entchannel == CHAN_WEAPON) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "altcharge") != NULL)) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->entnum == entityNum) && (ch->entchannel == CHAN_WEAPON) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "altcharge") != NULL)) { // Stop this sound alSourceStop(ch->alSource); alSourcei(ch->alSource, AL_BUFFER, NULL); @@ -1572,14 +1430,10 @@ void S_StartSound(const vec3_t origin, int entityNum, soundChannel_t entchannel, break; } } - } - else - { + } else { ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->entnum == entityNum) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "falling") != NULL)) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->entnum == entityNum) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "falling") != NULL)) { // Stop this sound alSourceStop(ch->alSource); alSourcei(ch->alSource, AL_BUFFER, NULL); @@ -1594,44 +1448,40 @@ void S_StartSound(const vec3_t origin, int entityNum, soundChannel_t entchannel, // pick a channel to play on - ch = S_PickChannel( entityNum, entchannel ); + ch = S_PickChannel(entityNum, entchannel); if (!ch) { return; } if (origin) { - VectorCopy (origin, ch->origin); + VectorCopy(origin, ch->origin); ch->fixed_origin = qtrue; } else { ch->fixed_origin = qfalse; } - ch->master_vol = SOUND_MAXVOL; //FIXME: Um.. control? + ch->master_vol = SOUND_MAXVOL; // FIXME: Um.. control? ch->entnum = entityNum; ch->entchannel = entchannel; ch->thesfx = sfx; ch->startSample = START_SAMPLE_IMMEDIATE; - ch->leftvol = ch->master_vol; // these will get calced at next spatialize - ch->rightvol = ch->master_vol; // unless the game isn't running + ch->leftvol = ch->master_vol; // these will get calced at next spatialize + ch->rightvol = ch->master_vol; // unless the game isn't running - if (entchannel < CHAN_AMBIENT && entityNum == listener_number) { //only do it for body sounds not local sounds - ch->master_vol = SOUND_MAXVOL * SOUND_FMAXVOL; //this won't be attenuated so let it scale down + if (entchannel < CHAN_AMBIENT && entityNum == listener_number) { // only do it for body sounds not local sounds + ch->master_vol = SOUND_MAXVOL * SOUND_FMAXVOL; // this won't be attenuated so let it scale down } - if ( entchannel == CHAN_VOICE || entchannel == CHAN_VOICE_ATTEN || entchannel == CHAN_VOICE_GLOBAL ) - { - s_entityWavVol[ ch->entnum ] = -1; //we've started the sound but it's silent for now + if (entchannel == CHAN_VOICE || entchannel == CHAN_VOICE_ATTEN || entchannel == CHAN_VOICE_GLOBAL) { + s_entityWavVol[ch->entnum] = -1; // we've started the sound but it's silent for now } - if (sfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader,sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); - //ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... - //ch->iMP3SlidingDecodeWindowPos= 0; // - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (sfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + // ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... + // ch->iMP3SlidingDecodeWindowPos= 0; // + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } @@ -1640,16 +1490,16 @@ void S_StartSound(const vec3_t origin, int entityNum, soundChannel_t entchannel, S_StartLocalSound ================== */ -void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) { - if ( !s_soundStarted || s_soundMuted ) { +void S_StartLocalSound(sfxHandle_t sfxHandle, int channelNum) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartLocalSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartLocalSound: handle %i out of range", sfxHandle); } - S_StartSound (NULL, listener_number, (soundChannel_t)channelNum, sfxHandle ); + S_StartSound(NULL, listener_number, (soundChannel_t)channelNum, sfxHandle); } /* @@ -1657,36 +1507,33 @@ void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) { S_StartLocalLoopingSound ================== */ -void S_StartLocalLoopingSound( sfxHandle_t sfxHandle) { - vec3_t nullVec = {0,0,0}; +void S_StartLocalLoopingSound(sfxHandle_t sfxHandle) { + vec3_t nullVec = {0, 0, 0}; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartLocalLoopingSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartLocalLoopingSound: handle %i out of range", sfxHandle); } - S_AddLoopingSound( listener_number, nullVec, nullVec, sfxHandle ); - + S_AddLoopingSound(listener_number, nullVec, nullVec, sfxHandle); } // returns length in milliseconds of supplied sound effect... (else 0 for bad handle now) // -float S_GetSampleLengthInMilliSeconds( sfxHandle_t sfxHandle) -{ +float S_GetSampleLengthInMilliSeconds(sfxHandle_t sfxHandle) { sfx_t *sfx; - if (!s_soundStarted) - { //we have no sound, so let's just make a reasonable guess + if (!s_soundStarted) { // we have no sound, so let's just make a reasonable guess return 512 * 1000; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) + if (sfxHandle < 0 || sfxHandle >= s_numSfx) return 0.0f; - sfx = &s_knownSfx[ sfxHandle ]; + sfx = &s_knownSfx[sfxHandle]; float f = (float)sfx->iSoundLengthInSamples / (float)dma.speed; @@ -1701,13 +1548,13 @@ If we are about to perform file access, clear the buffer so sound doesn't stutter. ================== */ -void S_ClearSoundBuffer( void ) { - int clear; +void S_ClearSoundBuffer(void) { + int clear; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } -#if 0 //this causes scripts to freak when the sounds get cut... +#if 0 // this causes scripts to freak when the sounds get cut... // clear all the sounds so they don't // start back up after the load finishes memset( s_channels, 0, sizeof( s_channels ) ); @@ -1725,14 +1572,13 @@ void S_ClearSoundBuffer( void ) { else clear = 0; - SNDDMA_BeginPainting (); + SNDDMA_BeginPainting(); if (dma.buffer) - memset(dma.buffer, clear, dma.samples * dma.samplebits/8); - SNDDMA_Submit (); + memset(dma.buffer, clear, dma.samples * dma.samplebits / 8); + SNDDMA_Submit(); } #ifdef USE_OPENAL - else - { + else { s_paintedtime = 0; s_soundtime = 0; } @@ -1741,30 +1587,26 @@ void S_ClearSoundBuffer( void ) { // kinda kludgy way to stop a special-use sfx_t playing... // -void S_CIN_StopSound(sfxHandle_t sfxHandle) -{ - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_CIN_StopSound: handle %i out of range", sfxHandle ); +void S_CIN_StopSound(sfxHandle_t sfxHandle) { + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_CIN_StopSound: handle %i out of range", sfxHandle); } - sfx_t *sfx = &s_knownSfx[ sfxHandle ]; + sfx_t *sfx = &s_knownSfx[sfxHandle]; channel_t *ch = s_channels; int i; - for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) - { - if ( !ch->thesfx || (ch->leftvol<0.25 && ch->rightvol<0.25 )) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx || (ch->leftvol < 0.25 && ch->rightvol < 0.25)) { continue; } - if (ch->thesfx == sfx) - { + if (ch->thesfx == sfx) { #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { alSourceStop(s_channels[i].alSource); } #endif - SND_FreeSFXMem(ch->thesfx); // heh, may as well... + SND_FreeSFXMem(ch->thesfx); // heh, may as well... ch->thesfx = NULL; memset(&ch->MP3StreamHeader, 0, sizeof(MP3STREAM)); ch->bLooping = false; @@ -1781,9 +1623,8 @@ void S_CIN_StopSound(sfxHandle_t sfxHandle) S_StopAllSounds ================== */ -void S_StopSounds(void) -{ - if ( !s_soundStarted ) { +void S_StopSounds(void) { + if (!s_soundStarted) { return; } @@ -1792,12 +1633,10 @@ void S_StopSounds(void) #ifdef USE_OPENAL // clear all the s_channels - if (s_UseOpenAL) - { + if (s_UseOpenAL) { channel_t *ch = s_channels; int i; - for (i = 0; i < s_numChannels; i++, ch++) - { + for (i = 0; i < s_numChannels; i++, ch++) { alSourceStop(s_channels[i].alSource); alSourcei(s_channels[i].alSource, AL_BUFFER, NULL); ch->thesfx = NULL; @@ -1807,9 +1646,7 @@ void S_StopSounds(void) ch->bPlaying = false; ch->bStreaming = false; } - } - else - { + } else { #endif memset(s_channels, 0, sizeof(s_channels)); #ifdef USE_OPENAL @@ -1817,9 +1654,9 @@ void S_StopSounds(void) #endif // clear out the lip synching override array - memset(s_entityWavVol, 0,sizeof(s_entityWavVol)); + memset(s_entityWavVol, 0, sizeof(s_entityWavVol)); - S_ClearSoundBuffer (); + S_ClearSoundBuffer(); } /* @@ -1829,7 +1666,7 @@ S_StopAllSounds ================== */ void S_StopAllSounds(void) { - if ( !s_soundStarted ) { + if (!s_soundStarted) { return; } // stop the background music @@ -1852,11 +1689,9 @@ S_ClearLoopingSounds ================== */ -void S_ClearLoopingSounds( void ) -{ +void S_ClearLoopingSounds(void) { #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { for (int i = 0; i < MAX_LOOP_SOUNDS; i++) loopSounds[i].bProcessed = qfalse; } @@ -1872,36 +1707,36 @@ Called during entity generation for a frame Include velocity in case I get around to doing doppler... ================== */ -void S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle, soundChannel_t chan ) { +void S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle, soundChannel_t chan) { /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( numLoopSounds >= MAX_LOOP_SOUNDS ) { - //assert(numLoopSounds= MAX_LOOP_SOUNDS) { + // assert(numLoopSounds= s_numSfx ) { - Com_Error( ERR_DROP, "S_AddLoopingSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_AddLoopingSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; - if (!sfx->bInMemory){ + sfx = &s_knownSfx[sfxHandle]; + if (!sfx->bInMemory) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( !sfx->iSoundLengthInSamples ) { - Com_Error( ERR_DROP, "%s has length 0", sfx->sSoundName ); + if (!sfx->iSoundLengthInSamples) { + Com_Error(ERR_DROP, "%s has length 0", sfx->sSoundName); } assert(!sfx->pMP3StreamHeader); - VectorCopy( origin, loopSounds[numLoopSounds].origin ); -// VectorCopy( velocity, loopSounds[numLoopSounds].velocity ); + VectorCopy(origin, loopSounds[numLoopSounds].origin); + // VectorCopy( velocity, loopSounds[numLoopSounds].velocity ); loopSounds[numLoopSounds].sfx = sfx; loopSounds[numLoopSounds].volume = SOUND_MAXVOL; loopSounds[numLoopSounds].entnum = entityNum; @@ -1914,43 +1749,41 @@ void S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocit S_AddAmbientLoopingSound ================== */ -void S_AddAmbientLoopingSound( const vec3_t origin, unsigned char volume, sfxHandle_t sfxHandle ) -{ +void S_AddAmbientLoopingSound(const vec3_t origin, unsigned char volume, sfxHandle_t sfxHandle) { /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( numLoopSounds >= MAX_LOOP_SOUNDS ) { + if (numLoopSounds >= MAX_LOOP_SOUNDS) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if (volume == 0) return; } #endif - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( !sfx->iSoundLengthInSamples ) { - Com_Error( ERR_DROP, "%s has length 0", sfx->sSoundName ); + if (!sfx->iSoundLengthInSamples) { + Com_Error(ERR_DROP, "%s has length 0", sfx->sSoundName); } - VectorCopy( origin, loopSounds[numLoopSounds].origin ); + VectorCopy(origin, loopSounds[numLoopSounds].origin); loopSounds[numLoopSounds].sfx = sfx; assert(!sfx->pMP3StreamHeader); - //TODO: Calculate the distance falloff + // TODO: Calculate the distance falloff loopSounds[numLoopSounds].volume = volume; numLoopSounds++; } @@ -1964,39 +1797,38 @@ All sounds are on the same cycle, so any duplicates can just sum up the channel multipliers. ================== */ -void S_AddLoopSounds (void) -{ - int i, j; - int left, right, left_total, right_total; - channel_t *ch; - loopSound_t *loop, *loop2; - static int loopFrame; +void S_AddLoopSounds(void) { + int i, j; + int left, right, left_total, right_total; + channel_t *ch; + loopSound_t *loop, *loop2; + static int loopFrame; loopFrame++; - for ( i = 0 ; i < numLoopSounds ; i++) { + for (i = 0; i < numLoopSounds; i++) { loop = &loopSounds[i]; - if ( loop->mergeFrame == loopFrame ) { - continue; // already merged into an earlier sound + if (loop->mergeFrame == loopFrame) { + continue; // already merged into an earlier sound } // find the total contribution of all sounds of this type left_total = right_total = 0; - for ( j = i ; j < numLoopSounds ; j++) { + for (j = i; j < numLoopSounds; j++) { loop2 = &loopSounds[j]; - if ( loop2->sfx != loop->sfx ) { + if (loop2->sfx != loop->sfx) { continue; } - loop2->mergeFrame = loopFrame; // don't check this again later + loop2->mergeFrame = loopFrame; // don't check this again later - S_SpatializeOrigin( loop2->origin, loop2->volume, &left, &right, loop2->entchan); + S_SpatializeOrigin(loop2->origin, loop2->volume, &left, &right, loop2->entchan); left_total += left; right_total += right; } if (left_total == 0 && right_total == 0) - continue; // not audible + continue; // not audible // allocate a channel ch = S_PickChannel(0, 0); @@ -2009,18 +1841,15 @@ void S_AddLoopSounds (void) right_total = SOUND_MAXVOL; ch->leftvol = left_total; ch->rightvol = right_total; - ch->loopSound = qtrue; // remove next frame + ch->loopSound = qtrue; // remove next frame ch->thesfx = loop->sfx; // you cannot use MP3 files here because they offer only streaming access, not random // - if (loop->sfx->pMP3StreamHeader) - { - Com_Error( ERR_DROP, "S_AddLoopSounds(): Cannot use streamed MP3 files here for random access (%s)\n",loop->sfx->sSoundName ); - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (loop->sfx->pMP3StreamHeader) { + Com_Error(ERR_DROP, "S_AddLoopSounds(): Cannot use streamed MP3 files here for random access (%s)\n", loop->sfx->sSoundName); + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } } @@ -2035,27 +1864,25 @@ If raw data has been loaded in little endien binary form, this must be done. If raw data was calculated, as with ADPCM, this should not be called. ================= */ -static void S_ByteSwapRawSamples( int samples, int width, int s_channels, const byte *data ) { - int i; +static void S_ByteSwapRawSamples(int samples, int width, int s_channels, const byte *data) { + int i; - if ( width != 2 ) { + if (width != 2) { return; } - if ( LittleShort( 256 ) == 256 ) { + if (LittleShort(256) == 256) { return; } - if ( s_channels == 2 ) { + if (s_channels == 2) { samples <<= 1; } - for ( i = 0 ; i < samples ; i++ ) { - ((short *)data)[i] = LittleShort( ((short *)data)[i] ); + for (i = 0; i < samples; i++) { + ((short *)data)[i] = LittleShort(((short *)data)[i]); } } -portable_samplepair_t *S_GetRawSamplePointer() { - return s_rawsamples; -} +portable_samplepair_t *S_GetRawSamplePointer() { return s_rawsamples; } /* ============ @@ -2064,22 +1891,21 @@ S_RawSamples Music streaming ============ */ -void S_RawSamples( int samples, int rate, int width, int channels, const byte *data, float volume, qboolean bFirstOrOnlyUpdateThisFrame ) -{ - int i; - int src, dst; - float scale; - int intVolume; - int rawEndStart; - - if ( !s_soundStarted || s_soundMuted ) { +void S_RawSamples(int samples, int rate, int width, int channels, const byte *data, float volume, qboolean bFirstOrOnlyUpdateThisFrame) { + int i; + int src, dst; + float scale; + int intVolume; + int rawEndStart; + + if (!s_soundStarted || s_soundMuted) { return; } intVolume = 256 * volume; - if ( s_rawend < s_soundtime ) { - Com_DPrintf( "S_RawSamples: resetting minimum: %i < %i\n", s_rawend, s_soundtime ); + if (s_rawend < s_soundtime) { + Com_DPrintf("S_RawSamples: resetting minimum: %i < %i\n", s_rawend, s_soundtime); s_rawend = s_soundtime; } @@ -2087,180 +1913,145 @@ void S_RawSamples( int samples, int rate, int width, int channels, const byte *d scale = (float)rate / dma.speed; -//Com_Printf ("%i < %i < %i\n", s_soundtime, s_paintedtime, s_rawend); - if (channels == 2 && width == 2) - { - if (scale == 1.0) - { // optimized case - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; i= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left = ((short *)data)[src*2] * intVolume; - s_rawsamples[dst].right = ((short *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left = ((short *)data)[src * 2] * intVolume; + s_rawsamples[dst].right = ((short *)data)[src * 2 + 1] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left += ((short *)data)[src*2] * intVolume; - s_rawsamples[dst].right += ((short *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left += ((short *)data)[src * 2] * intVolume; + s_rawsamples[dst].right += ((short *)data)[src * 2 + 1] * intVolume; } } } - } - else if (channels == 1 && width == 2) - { - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + } else if (channels == 1 && width == 2) { + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; s_rawsamples[dst].left = ((short *)data)[src] * intVolume; s_rawsamples[dst].right = ((short *)data)[src] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left += ((short *)data)[src] * intVolume; + s_rawsamples[dst].left += ((short *)data)[src] * intVolume; s_rawsamples[dst].right += ((short *)data)[src] * intVolume; } } - } - else if (channels == 2 && width == 1) - { + } else if (channels == 2 && width == 1) { intVolume *= 256; - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left = ((char *)data)[src*2] * intVolume; - s_rawsamples[dst].right = ((char *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left = ((char *)data)[src * 2] * intVolume; + s_rawsamples[dst].right = ((char *)data)[src * 2 + 1] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left += ((char *)data)[src*2] * intVolume; - s_rawsamples[dst].right += ((char *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left += ((char *)data)[src * 2] * intVolume; + s_rawsamples[dst].right += ((char *)data)[src * 2 + 1] * intVolume; } } - } - else if (channels == 1 && width == 1) - { + } else if (channels == 1 && width == 1) { intVolume *= 256; - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left = (((byte *)data)[src]-128) * intVolume; - s_rawsamples[dst].right = (((byte *)data)[src]-128) * intVolume; + s_rawsamples[dst].left = (((byte *)data)[src] - 128) * intVolume; + s_rawsamples[dst].right = (((byte *)data)[src] - 128) * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - //Don't overflow if resampling. + // Don't overflow if resampling. if (s_rawend > rawEndStart + MAX_RAW_SAMPLES) break; - s_rawsamples[dst].left += (((byte *)data)[src]-128) * intVolume; - s_rawsamples[dst].right += (((byte *)data)[src]-128) * intVolume; + s_rawsamples[dst].left += (((byte *)data)[src] - 128) * intVolume; + s_rawsamples[dst].right += (((byte *)data)[src] - 128) * intVolume; } } } - if ( s_rawend > s_soundtime + MAX_RAW_SAMPLES ) { - Com_DPrintf( "S_RawSamples: overflowed %i > %i\n", s_rawend, s_soundtime ); + if (s_rawend > s_soundtime + MAX_RAW_SAMPLES) { + Com_DPrintf("S_RawSamples: overflowed %i > %i\n", s_rawend, s_soundtime); } } @@ -2273,26 +2064,21 @@ S_UpdateEntityPosition let the sound system know where an entity currently is ====================== */ -void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) -{ - if ( entityNum < 0 || entityNum >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum ); +void S_UpdateEntityPosition(int entityNum, const vec3_t origin) { + if (entityNum < 0 || entityNum >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum); } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if (entityNum == 0) return; channel_t *ch = s_channels + 1; - for (int i = 1; i < s_numChannels; i++, ch++) - { - if ((s_channels[i].bPlaying) && (s_channels[i].entnum == entityNum) && (!s_channels[i].bLooping)) - { + for (int i = 1; i < s_numChannels; i++, ch++) { + if ((s_channels[i].bPlaying) && (s_channels[i].entnum == entityNum) && (!s_channels[i].bLooping)) { // Ignore position updates for CHAN_VOICE_GLOBAL - if (ch->entchannel != CHAN_VOICE_GLOBAL && ch->entchannel != CHAN_ANNOUNCER) - { + if (ch->entchannel != CHAN_VOICE_GLOBAL && ch->entchannel != CHAN_ANNOUNCER) { ALfloat pos[3]; pos[0] = origin[0]; pos[1] = origin[2]; @@ -2302,22 +2088,23 @@ void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) UpdateEAXBuffer(ch); } -/* pos[0] = origin[0]; - pos[1] = origin[2]; - pos[2] = -origin[1]; - alSourcefv(s_channels[i].alSource, AL_POSITION, pos); + /* pos[0] = origin[0]; + pos[1] = origin[2]; + pos[2] = -origin[1]; + alSourcefv(s_channels[i].alSource, AL_POSITION, pos); - if ((s_bEALFileLoaded) && !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) ) - { - UpdateEAXBuffer(ch); - } -*/ + if ((s_bEALFileLoaded) && !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == + CHAN_VOICE_GLOBAL ) ) + { + UpdateEAXBuffer(ch); + } + */ } } } #endif - VectorCopy( origin, s_entityPosition[entityNum] ); + VectorCopy(origin, s_entityPosition[entityNum]); } // Given a current wav we are playing, and our position within it, lets figure out its volume... @@ -2325,76 +2112,66 @@ void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) // (this is mostly Jake's code from EF1, which explains a lot...:-) // static int next_amplitude = 0; -static int S_CheckAmplitude(channel_t *ch, const int s_oldpaintedtime ) -{ +static int S_CheckAmplitude(channel_t *ch, const int s_oldpaintedtime) { // now, is this a cycle - or have we just started a new sample - where we should update the backup table, and write this value // into the new table? or should we just take the value FROM the back up table and feed it out. - assert( ch->startSample != START_SAMPLE_IMMEDIATE ); - if ( ch->startSample == s_oldpaintedtime || (next_amplitude < s_soundtime) )//(ch->startSample == START_SAMPLE_IMMEDIATE)//!s_entityWavVol_back[ch->entnum] + assert(ch->startSample != START_SAMPLE_IMMEDIATE); + if (ch->startSample == s_oldpaintedtime || (next_amplitude < s_soundtime)) //(ch->startSample == START_SAMPLE_IMMEDIATE)//!s_entityWavVol_back[ch->entnum] { - int sample; - int sample_total = 0; - int count = 0; + int sample; + int sample_total = 0; + int count = 0; short *current_pos_s; -// char *current_pos_c; - int offset = 0; + // char *current_pos_c; + int offset = 0; // if we haven't started the sample yet, we must be at the beginning - current_pos_s = ((short*)ch->thesfx->pSoundData); -// current_pos_c = ((char*)ch->thesfx->data); + current_pos_s = ((short *)ch->thesfx->pSoundData); + // current_pos_c = ((char*)ch->thesfx->data); - //if (ch->startSample != START_SAMPLE_IMMEDIATE) + // if (ch->startSample != START_SAMPLE_IMMEDIATE) //{ - // figure out where we are in the sample right now. - offset = s_oldpaintedtime - ch->startSample;//s_paintedtime - current_pos_s += offset; -// current_pos_c += offset; + // figure out where we are in the sample right now. + offset = s_oldpaintedtime - ch->startSample; // s_paintedtime + current_pos_s += offset; + // current_pos_c += offset; //} // scan through 10 samples 100( at 11hz or 200 at 22hz) samples apart. // - for (int i=0; i<10; i++) - { + for (int i = 0; i < 10; i++) { // // have we run off the end? - if ((offset + (i*100)) > ch->thesfx->iSoundLengthInSamples) - { + if ((offset + (i * 100)) > ch->thesfx->iSoundLengthInSamples) { break; } -// if (ch->thesfx->width == 1) -// { -// sample = current_pos_c[i*100]; -// } -// else + // if (ch->thesfx->width == 1) + // { + // sample = current_pos_c[i*100]; + // } + // else { - switch (ch->thesfx->eSoundCompressionMethod) - { - case ct_16: - { - sample = current_pos_s[i*100]; - } - break; - - case ct_MP3: - { - const int iIndex = (i*100) + ((offset * /*ch->thesfx->width*/2) - ch->iMP3SlidingDecodeWindowPos); - const short* pwSamples = (short*) (ch->MP3SlidingDecodeBuffer + iIndex); - - sample = *pwSamples; - } - break; - - default: - { - assert(0); - sample = 0; - } - break; + switch (ch->thesfx->eSoundCompressionMethod) { + case ct_16: { + sample = current_pos_s[i * 100]; + } break; + + case ct_MP3: { + const int iIndex = (i * 100) + ((offset * /*ch->thesfx->width*/ 2) - ch->iMP3SlidingDecodeWindowPos); + const short *pwSamples = (short *)(ch->MP3SlidingDecodeBuffer + iIndex); + + sample = *pwSamples; + } break; + + default: { + assert(0); + sample = 0; + } break; } -// if (sample < 0) -// sample = -sample; - sample = sample>>8; + // if (sample < 0) + // sample = -sample; + sample = sample >> 8; } // square it for better accuracy sample_total += (sample * sample); @@ -2402,35 +2179,22 @@ static int S_CheckAmplitude(channel_t *ch, const int s_oldpaintedtime ) } // if we are already done with this sample, then its silence - if (!count) - { - return(0); + if (!count) { + return (0); } sample_total /= count; // I hate doing this, but its the simplest way - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_1->value) - { - // tell the scripts that are relying on this that we are still going, but actually silent right now. + if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_1->value) { + // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_2->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_2->value) { sample = 1; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_3->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_3->value) { sample = 2; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_4->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_4->value) { sample = 3; - } - else - { + } else { sample = 4; } @@ -2439,12 +2203,12 @@ static int S_CheckAmplitude(channel_t *ch, const int s_oldpaintedtime ) #endif // store away the value we got into the back up table - s_entityWavVol_back[ ch->entnum ] = sample; + s_entityWavVol_back[ch->entnum] = sample; return (sample); } // no, just get last value calculated from backup table - assert( s_entityWavVol_back[ch->entnum] ); - return (s_entityWavVol_back[ ch->entnum]); + assert(s_entityWavVol_back[ch->entnum]); + return (s_entityWavVol_back[ch->entnum]); } /* @@ -2454,22 +2218,20 @@ S_Respatialize Change the volumes of all the playing sounds for changes in their positions ============ */ -void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], qboolean inwater ) -{ +void S_Respatialize(int entityNum, const vec3_t head, vec3_t axis[3], qboolean inwater) { #ifdef USE_OPENAL EAXOCCLUSIONPROPERTIES eaxOCProp; EAXACTIVEFXSLOTS eaxActiveSlots; #endif - int i; - channel_t *ch; + int i; + channel_t *ch; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { listener_pos[0] = head[0]; listener_pos[1] = head[2]; listener_pos[2] = -head[1]; @@ -2484,28 +2246,22 @@ void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], qboolean alListenerfv(AL_ORIENTATION, listener_ori); // Update EAX effects here - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { // Check if the Listener is underwater - if (inwater) - { + if (inwater) { // Check if we have already applied Underwater effect - if (!s_bInWater) - { + if (!s_bInWater) { // New underwater fix - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].lEnvID = -1; } // Load underwater reverb effect into FX Slot 0, and set this as the Primary FX Slot unsigned int ulEnvironment = EAX_ENVIRONMENT_UNDERWATER; - s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ENVIRONMENT, - NULL, &ulEnvironment, sizeof(unsigned int)); + s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ENVIRONMENT, NULL, &ulEnvironment, sizeof(unsigned int)); s_EnvironmentID = 999; - s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, (ALvoid*)&EAXPROPERTYID_EAX40_FXSlot0, - sizeof(GUID)); + s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, (ALvoid *)&EAXPROPERTYID_EAX40_FXSlot0, sizeof(GUID)); // Occlude all sounds into this environment, and mute all their sends to other reverbs eaxOCProp.lOcclusion = -3000; @@ -2517,46 +2273,35 @@ void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], qboolean eaxActiveSlots.guidActiveFXSlots[1] = EAX_PrimaryFXSlotID; ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { // New underwater fix s_channels[i].lSlotID = -1; - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, - &eaxActiveSlots, 2*sizeof(GUID)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &eaxActiveSlots, 2 * sizeof(GUID)); } s_bInWater = true; } - } - else - { + } else { // Not underwater ... check if the underwater effect is still present - if (s_bInWater) - { + if (s_bInWater) { s_bInWater = false; // Remove underwater Reverb effect, and reset Occlusion / Obstruction amount on all Sources UpdateEAXListener(); ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { UpdateEAXBuffer(ch); } - } - else - { + } else { UpdateEAXListener(); } } } - } - else - { + } else { #endif listener_number = entityNum; VectorCopy(head, listener_origin); @@ -2566,12 +2311,12 @@ void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], qboolean // update spatialization for dynamic sounds ch = s_channels; - for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) { - if ( !ch->thesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { // loopSounds are regenerated fresh each frame - Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); + if (ch->loopSound) { // loopSounds are regenerated fresh each frame + Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); continue; } @@ -2580,26 +2325,26 @@ void S_Respatialize( int entityNum, const vec3_t head, vec3_t axis[3], qboolean ch->leftvol = ch->master_vol; ch->rightvol = ch->master_vol; } else { - const vec3_t *origin; + const vec3_t *origin; if (ch->fixed_origin) { origin = &ch->origin; } else { - origin = &s_entityPosition[ ch->entnum ]; + origin = &s_entityPosition[ch->entnum]; } - S_SpatializeOrigin (*origin, (float)ch->master_vol, &ch->leftvol, &ch->rightvol, ch->entchannel); + S_SpatializeOrigin(*origin, (float)ch->master_vol, &ch->leftvol, &ch->rightvol, ch->entchannel); } - //NOTE: Made it so that voice sounds keep playing, even out of range + // NOTE: Made it so that voice sounds keep playing, even out of range // so that tasks waiting for sound completion keep proper timing - if ( !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) && !ch->leftvol && !ch->rightvol ) { - Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); + if (!(ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) && !ch->leftvol && !ch->rightvol) { + Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); continue; } } // add loopsounds - S_AddLoopSounds (); + S_AddLoopSounds(); #ifdef USE_OPENAL } #endif @@ -2614,32 +2359,32 @@ S_ScanChannelStarts Returns qtrue if any new sounds were started since the last mix ======================== */ -qboolean S_ScanChannelStarts( void ) { - channel_t *ch; - int i; - qboolean newSamples; +qboolean S_ScanChannelStarts(void) { + channel_t *ch; + int i; + qboolean newSamples; newSamples = qfalse; ch = s_channels; - for (i=0; ithesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } // if this channel was just started this frame, // set the sample count to it begins mixing // into the very first sample - if ( ch->startSample == START_SAMPLE_IMMEDIATE ) { + if (ch->startSample == START_SAMPLE_IMMEDIATE) { ch->startSample = s_paintedtime; newSamples = qtrue; continue; } // if it is completely finished by now, clear it - if ( ch->startSample + ch->thesfx->iSoundLengthInSamples <= s_paintedtime ) { + if (ch->startSample + ch->thesfx->iSoundLengthInSamples <= s_paintedtime) { ch->thesfx = NULL; continue; } @@ -2651,36 +2396,34 @@ qboolean S_ScanChannelStarts( void ) { // this is now called AFTER the DMA painting, since it's only the painter calls that cause the MP3s to be unpacked, // and therefore to have data readable by the lip-sync volume calc code. // -void S_DoLipSynchs( const int s_oldpaintedtime ) -{ - channel_t *ch; - int i; +void S_DoLipSynchs(const int s_oldpaintedtime) { + channel_t *ch; + int i; // clear out the lip synching override array for this frame - memset(s_entityWavVol, 0,(MAX_GENTITIES * 4)); + memset(s_entityWavVol, 0, (MAX_GENTITIES * 4)); ch = s_channels; - for (i=0; ithesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } // if we are playing a sample that should override the lip texture on its owning model, lets figure out // what the amplitude is, stick it in a table, then return it - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { // go away and work out amplitude for this sound we are playing right now. - s_entityWavVol[ ch->entnum ] = S_CheckAmplitude( ch, s_oldpaintedtime ); - if ( s_show->integer == 3 ) { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + s_entityWavVol[ch->entnum] = S_CheckAmplitude(ch, s_oldpaintedtime); + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } } - if (next_amplitude < s_soundtime) { + if (next_amplitude < s_soundtime) { next_amplitude = s_soundtime + 800; } } @@ -2692,34 +2435,34 @@ S_Update Called once each time through the main loop ============ */ -void S_Update( void ) { - int i; - channel_t *ch; +void S_Update(void) { + int i; + channel_t *ch; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } // // debugging output // - if ( s_show->integer == 2 ) { - //int total = 0; - //int totalMeg =0; + if (s_show->integer == 2) { + // int total = 0; + // int totalMeg =0; ch = s_channels; - for (i=0 ; ithesfx && (ch->leftvol || ch->rightvol) ) { - Com_Printf ("(%i) %3i %3i %s\n", ch->entnum, ch->leftvol, ch->rightvol, ch->thesfx->sSoundName); - //total++; - //totalMeg += Z_Size(ch->thesfx->pSoundData); - //if (ch->thesfx->pMP3StreamHeader) + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (ch->thesfx && (ch->leftvol || ch->rightvol)) { + Com_Printf("(%i) %3i %3i %s\n", ch->entnum, ch->leftvol, ch->rightvol, ch->thesfx->sSoundName); + // total++; + // totalMeg += Z_Size(ch->thesfx->pSoundData); + // if (ch->thesfx->pMP3StreamHeader) //{ // totalMeg += sizeof(*ch->thesfx->pMP3StreamHeader); - //} + // } } } - //if (total) + // if (total) // Com_Printf ("----(%i)---- painted: %i, SND %.2fMB\n", total, s_paintedtime, totalMeg/1024.0f/1024.0f); } @@ -2736,32 +2479,29 @@ void S_Update( void ) { S_Update_(); } -void S_GetSoundtime(void) -{ - int samplepos; - static int buffers; - static int oldsamplepos; - int fullsamples; +void S_GetSoundtime(void) { + int samplepos; + static int buffers; + static int oldsamplepos; + int fullsamples; fullsamples = dma.samples / dma.channels; // it is possible to miscount buffers if it has wrapped twice between // calls to S_Update. Oh well. samplepos = SNDDMA_GetDMAPos(); - if (samplepos < oldsamplepos) - { - buffers++; // buffer wrapped + if (samplepos < oldsamplepos) { + buffers++; // buffer wrapped - if (s_paintedtime > 0x40000000) - { // time to chop things off to avoid 32 bit limits + if (s_paintedtime > 0x40000000) { // time to chop things off to avoid 32 bit limits buffers = 0; s_paintedtime = fullsamples; - S_StopAllSounds (); + S_StopAllSounds(); } } oldsamplepos = samplepos; - s_soundtime = buffers*fullsamples + samplepos/dma.channels; + s_soundtime = buffers * fullsamples + samplepos / dma.channels; #if 0 // check to make sure that we haven't overshot @@ -2772,41 +2512,37 @@ void S_GetSoundtime(void) } #endif - if ( dma.submission_chunk < 256 ) { + if (dma.submission_chunk < 256) { s_paintedtime = (int)(s_soundtime + s_mixPreStep->value * dma.speed); } else { s_paintedtime = s_soundtime + dma.submission_chunk; } } - void S_Update_(void) { - unsigned endtime; - int samps; + unsigned endtime; + int samps; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { - int i,j; - int source; + if (s_UseOpenAL) { + int i, j; + int source; UpdateSingleShotSounds(); channel_t *ch = s_channels + 1; - for ( i = 1; i < MAX_CHANNELS ; i++, ch++ ) - { - float pos[3]; + for (i = 1; i < MAX_CHANNELS; i++, ch++) { + float pos[3]; - if ( !ch->thesfx || (ch->bPlaying)) + if (!ch->thesfx || (ch->bPlaying)) continue; source = ch - s_channels; - if (ch->entchannel == CHAN_VOICE_GLOBAL || ch->entchannel == CHAN_ANNOUNCER) - { + if (ch->entchannel == CHAN_VOICE_GLOBAL || ch->entchannel == CHAN_ANNOUNCER) { // Always play these sounds at 0,0,-1 (in front of listener) pos[0] = 0.0f; pos[1] = 0.0f; @@ -2815,45 +2551,31 @@ void S_Update_(void) { alSourcefv(s_channels[source].alSource, AL_POSITION, pos); alSourcei(s_channels[source].alSource, AL_LOOPING, AL_FALSE); alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_TRUE); - if (ch->entchannel == CHAN_ANNOUNCER) - { + if (ch->entchannel == CHAN_ANNOUNCER) { alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.0f); - } - else - { + } else { alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); } - } - else - { + } else { // Get position of source - if (ch->fixed_origin) - { + if (ch->fixed_origin) { pos[0] = ch->origin[0]; pos[1] = ch->origin[2]; pos[2] = -ch->origin[1]; alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_FALSE); - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { pos[0] = 0.0f; pos[1] = 0.0f; pos[2] = 0.0f; alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_TRUE); - } - else - { + } else { // Get position of Entity - if (ch->bLooping) - { - pos[0] = loopSounds[ ch->entnum ].origin[0]; - pos[1] = loopSounds[ ch->entnum ].origin[2]; - pos[2] = -loopSounds[ ch->entnum ].origin[1]; - } - else - { + if (ch->bLooping) { + pos[0] = loopSounds[ch->entnum].origin[0]; + pos[1] = loopSounds[ch->entnum].origin[2]; + pos[2] = -loopSounds[ch->entnum].origin[1]; + } else { pos[0] = s_entityPosition[ch->entnum][0]; pos[1] = s_entityPosition[ch->entnum][2]; pos[2] = -s_entityPosition[ch->entnum][1]; @@ -2865,26 +2587,19 @@ void S_Update_(void) { alSourcefv(s_channels[source].alSource, AL_POSITION, pos); alSourcei(s_channels[source].alSource, AL_LOOPING, AL_FALSE); - if (ch->entchannel == CHAN_VOICE) - { + if (ch->entchannel == CHAN_VOICE) { // Reduced fall-off (Large Reference Distance), affected by Voice Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_VOICE_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); - } - else if (ch->entchannel == CHAN_VOICE_ATTEN) - { + } else if (ch->entchannel == CHAN_VOICE_ATTEN) { // Normal fall-off, affected by Voice Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); - } - else if (ch->entchannel == CHAN_LESS_ATTEN) - { + } else if (ch->entchannel == CHAN_LESS_ATTEN) { // Reduced fall-off, affected by Sound Effect Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_VOICE_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); - } - else - { + } else { // Normal fall-off, affect by Sound Effect Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); @@ -2898,33 +2613,27 @@ void S_Update_(void) { int nTotalBytesDecoded = 0; int nBuffersToAdd = 0; - if (ch->thesfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + if (ch->thesfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); ch->iMP3SlidingDecodeWritePos = 0; - ch->iMP3SlidingDecodeWindowPos= 0; + ch->iMP3SlidingDecodeWindowPos = 0; // Reset streaming buffers status's for (i = 0; i < NUM_STREAMING_BUFFERS; i++) ch->buffers[i].Status = UNQUEUED; // Decode (STREAMING_BUFFER_SIZE / 1152) MP3 frames for each of the NUM_STREAMING_BUFFERS AL Buffers - for (i = 0; i < NUM_STREAMING_BUFFERS; i++) - { + for (i = 0; i < NUM_STREAMING_BUFFERS; i++) { nTotalBytesDecoded = 0; - for (j = 0; j < (STREAMING_BUFFER_SIZE / 1152); j++) - { - nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 ? + for (j = 0; j < (STREAMING_BUFFER_SIZE / 1152); j++) { + nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 ? memcpy(ch->buffers[i].Data + nTotalBytesDecoded, ch->MP3StreamHeader.bDecodeBuffer, nBytesDecoded); - if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { - ch->thesfx->lipSyncData[(i*NUM_STREAMING_BUFFERS)+j] = S_MP3PreProcessLipSync(ch, (short *)(ch->MP3StreamHeader.bDecodeBuffer)); - } - else - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { + ch->thesfx->lipSyncData[(i * NUM_STREAMING_BUFFERS) + j] = + S_MP3PreProcessLipSync(ch, (short *)(ch->MP3StreamHeader.bDecodeBuffer)); + } else { #ifdef _DEBUG #ifdef _MSC_VER char szString[256]; @@ -2937,8 +2646,7 @@ void S_Update_(void) { nTotalBytesDecoded += nBytesDecoded; } - if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) - { + if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) { memset(ch->buffers[i].Data + nTotalBytesDecoded, 0, (STREAMING_BUFFER_SIZE - nTotalBytesDecoded)); break; } @@ -2952,15 +2660,13 @@ void S_Update_(void) { // Make sure queue is empty first alSourcei(s_channels[source].alSource, AL_BUFFER, NULL); - for (i = 0; i < nBuffersToAdd; i++) - { + for (i = 0; i < nBuffersToAdd; i++) { // Copy decoded data to AL Buffer alBufferData(ch->buffers[i].BufferID, AL_FORMAT_MONO16, ch->buffers[i].Data, STREAMING_BUFFER_SIZE, 22050); // Queue AL Buffer on Source alSourceQueueBuffers(s_channels[source].alSource, 1, &(ch->buffers[i].BufferID)); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { ch->buffers[i].Status = QUEUED; } } @@ -2973,18 +2679,14 @@ void S_Update_(void) { ch->bStreaming = true; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { // Record start time for Lip-syncing s_channels[source].iStartTime = timeGetTime(); // Prepare lipsync value(s) - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[0]; - } - else - { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[0]; + } else { #ifdef _DEBUG #ifdef _MSC_VER char szString[256]; @@ -2996,9 +2698,7 @@ void S_Update_(void) { } return; - } - else - { + } else { // Attach buffer to source alSourcei(s_channels[source].alSource, AL_BUFFER, ch->thesfx->Buffer); @@ -3010,18 +2710,14 @@ void S_Update_(void) { if (alGetError() == AL_NO_ERROR) s_channels[source].bPlaying = true; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { // Record start time for Lip-syncing s_channels[source].iStartTime = timeGetTime(); // Prepare lipsync value(s) - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[0]; - } - else - { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[0]; + } else { #ifdef _DEBUG char szString[256]; sprintf(szString, "Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); @@ -3037,9 +2733,7 @@ void S_Update_(void) { UpdateLoopingSounds(); AL_UpdateRawSamples(); - } - else - { + } else { #endif // Updates s_soundtime S_GetSoundtime(); @@ -3054,30 +2748,27 @@ void S_Update_(void) { endtime = (int)(s_soundtime + s_mixahead->value * dma.speed); // mix to an even submission block size - endtime = (endtime + dma.submission_chunk-1) - & ~(dma.submission_chunk-1); + endtime = (endtime + dma.submission_chunk - 1) & ~(dma.submission_chunk - 1); // never mix more than the complete buffer - samps = dma.samples >> (dma.channels-1); + samps = dma.samples >> (dma.channels - 1); if (endtime - s_soundtime > (unsigned)samps) endtime = s_soundtime + samps; + SNDDMA_BeginPainting(); - SNDDMA_BeginPainting (); + S_PaintChannels(endtime); - S_PaintChannels (endtime); + SNDDMA_Submit(); - SNDDMA_Submit (); - - S_DoLipSynchs( s_oldpaintedtime ); + S_DoLipSynchs(s_oldpaintedtime); #ifdef USE_OPENAL } #endif } #ifdef USE_OPENAL -void UpdateSingleShotSounds() -{ +void UpdateSingleShotSounds() { int i, j, k; ALint state; ALint processed; @@ -3089,23 +2780,17 @@ void UpdateSingleShotSounds() // Firstly, check if any single-shot sounds have completed, or if they need more data (for streaming Sources), // and/or if any of the currently playing (non-Ambient) looping sounds need to be stopped ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { ch->bProcessed = false; - if ((s_channels[i].bPlaying) && (!ch->bLooping)) - { + if ((s_channels[i].bPlaying) && (!ch->bLooping)) { // Single-shot - if (s_channels[i].bStreaming == false) - { + if (s_channels[i].bStreaming == false) { alGetSourcei(s_channels[i].alSource, AL_SOURCE_STATE, &state); - if (state == AL_STOPPED) - { + if (state == AL_STOPPED) { s_channels[i].thesfx = NULL; s_channels[i].bPlaying = false; } - } - else - { + } else { // Process streaming sample // Procedure :- @@ -3121,14 +2806,11 @@ void UpdateSingleShotSounds() int nBytesDecoded; - if (ch->thesfx->pMP3StreamHeader) - { - if (ch->MP3StreamHeader.iSourceBytesRemaining == 0) - { + if (ch->thesfx->pMP3StreamHeader) { + if (ch->MP3StreamHeader.iSourceBytesRemaining == 0) { // Finished decoding data - if the source has finished playing then we're done alGetSourcei(ch->alSource, AL_SOURCE_STATE, &state); - if (state == AL_STOPPED) - { + if (state == AL_STOPPED) { // Attach NULL buffer to Source to remove any buffers left in the queue alSourcei(ch->alSource, AL_BUFFER, NULL); ch->thesfx = NULL; @@ -3142,13 +2824,10 @@ void UpdateSingleShotSounds() alGetSourcei(ch->alSource, AL_BUFFERS_PROCESSED, &processed); ALuint buffer; - while (processed) - { + while (processed) { alSourceUnqueueBuffers(ch->alSource, 1, &buffer); - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { - if (ch->buffers[j].BufferID == buffer) - { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { + if (ch->buffers[j].BufferID == buffer) { ch->buffers[j].Status = UNQUEUED; break; } @@ -3158,28 +2837,20 @@ void UpdateSingleShotSounds() int nTotalBytesDecoded = 0; - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { - if ((ch->buffers[j].Status == UNQUEUED) && (ch->MP3StreamHeader.iSourceBytesRemaining > 0)) - { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { + if ((ch->buffers[j].Status == UNQUEUED) && (ch->MP3StreamHeader.iSourceBytesRemaining > 0)) { nTotalBytesDecoded = 0; - for (k = 0; k < (STREAMING_BUFFER_SIZE / 1152); k++) - { + for (k = 0; k < (STREAMING_BUFFER_SIZE / 1152); k++) { nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 - if (nBytesDecoded > 0) - { + if (nBytesDecoded > 0) { memcpy(ch->buffers[j].Data + nTotalBytesDecoded, ch->MP3StreamHeader.bDecodeBuffer, nBytesDecoded); - if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { - ch->thesfx->lipSyncData[(j*4)+k] = S_MP3PreProcessLipSync(ch, (short *)(ch->buffers[j].Data)); - } - else - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { + ch->thesfx->lipSyncData[(j * 4) + k] = S_MP3PreProcessLipSync(ch, (short *)(ch->buffers[j].Data)); + } else { #ifdef _DEBUG sprintf(szString, "Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); OutputDebugString(szString); @@ -3187,20 +2858,16 @@ void UpdateSingleShotSounds() } } nTotalBytesDecoded += nBytesDecoded; - } - else - { + } else { // Make sure that iSourceBytesRemaining is 0 - if (ch->MP3StreamHeader.iSourceBytesRemaining != 0) - { + if (ch->MP3StreamHeader.iSourceBytesRemaining != 0) { ch->MP3StreamHeader.iSourceBytesRemaining = 0; break; } } } - if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) - { + if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) { memset(ch->buffers[j].Data + nTotalBytesDecoded, 0, (STREAMING_BUFFER_SIZE - nTotalBytesDecoded)); // Move data to buffer @@ -3213,9 +2880,7 @@ void UpdateSingleShotSounds() ch->buffers[j].Status = QUEUED; break; - } - else - { + } else { // Move data to buffer alBufferData(ch->buffers[j].BufferID, AL_FORMAT_MONO16, ch->buffers[j].Data, STREAMING_BUFFER_SIZE, 22050); @@ -3230,12 +2895,12 @@ void UpdateSingleShotSounds() // Get state of Buffer alGetSourcei(ch->alSource, AL_SOURCE_STATE, &state); - if (state != AL_PLAYING) - { + if (state != AL_PLAYING) { alSourcePlay(ch->alSource); #ifdef _DEBUG char szString[256]; - sprintf(szString,"[%d] Restarting playback of single-shot streaming MP3 sample - still have %d bytes to decode\n", i, ch->MP3StreamHeader.iSourceBytesRemaining); + sprintf(szString, "[%d] Restarting playback of single-shot streaming MP3 sample - still have %d bytes to decode\n", i, + ch->MP3StreamHeader.iSourceBytesRemaining); OutputDebugString(szString); #endif } @@ -3245,34 +2910,26 @@ void UpdateSingleShotSounds() } } -void UpdateLoopingSounds() -{ - int i,j; +void UpdateLoopingSounds() { + int i, j; ALuint source; channel_t *ch; - loopSound_t *loop; + loopSound_t *loop; float pos[3]; // First check to see if any of the looping sounds are already playing at the correct positions ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if (ch->bLooping && s_channels[i].bPlaying) - { - for (j = 0; j < numLoopSounds; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if (ch->bLooping && s_channels[i].bPlaying) { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; // If this channel is playing the right sound effect at the right position then mark this channel and looping sound // as processed - if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) ) - { - if ( (loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) - && (loop->origin[2] == listener_pos[1]) ) - { + if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) { + if ((loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) && (loop->origin[2] == listener_pos[1])) { // Assume that this sound is head relative - if (!loop->bRelative) - { + if (!loop->bRelative) { // Set position to 0,0,0 and turn on Head Relative Mode float pos[3]; pos[0] = 0.f; @@ -3285,24 +2942,20 @@ void UpdateLoopingSounds() } // Make sure Gain is set correctly - if (ch->master_vol != loop->volume) - { + if (ch->master_vol != loop->volume) { ch->master_vol = loop->volume; alSourcef(s_channels[i].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); } ch->bProcessed = true; loop->bProcessed = qtrue; - } - else if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) && (!memcmp(ch->origin, loop->origin, sizeof(ch->origin)))) - { + } else if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) && (!memcmp(ch->origin, loop->origin, sizeof(ch->origin)))) { // Match ! ch->bProcessed = true; loop->bProcessed = qtrue; // Make sure Gain is set correctly - if (ch->master_vol != loop->volume) - { + if (ch->master_vol != loop->volume) { ch->master_vol = loop->volume; alSourcef(s_channels[i].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); } @@ -3316,16 +2969,12 @@ void UpdateLoopingSounds() // Next check if the correct looping sound is playing, but at the wrong position ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->bLooping) && (ch->bProcessed == false) && s_channels[i].bPlaying) - { - for (j = 0; j < numLoopSounds; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->bLooping) && (ch->bProcessed == false) && s_channels[i].bPlaying) { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; - if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) - { + if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) { // Same sound - wrong position ch->origin[0] = loop->origin[0]; ch->origin[1] = loop->origin[1]; @@ -3353,10 +3002,8 @@ void UpdateLoopingSounds() // If any non-procesed looping sounds are still playing on a channel, they can be removed as they are no longer // required ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if (s_channels[i].bPlaying && ch->bLooping && !ch->bProcessed) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if (s_channels[i].bPlaying && ch->bLooping && !ch->bProcessed) { // Sound no longer needed alSourceStop(s_channels[i].alSource); ch->thesfx = NULL; @@ -3368,13 +3015,11 @@ void UpdateLoopingSounds() alGetError(); #endif // Finally if there are any non-processed sounds left, we need to try and play them - for (j = 0; j < numLoopSounds; j++) - { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; - if (!loop->bProcessed) - { - ch = S_PickChannel(0,0); + if (!loop->bProcessed) { + ch = S_PickChannel(0, 0); ch->master_vol = loop->volume; ch->entnum = loop->entnum; @@ -3383,17 +3028,13 @@ void UpdateLoopingSounds() ch->bLooping = true; // Check if the Source is positioned at exactly the same location as the listener - if ( (loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) - && (loop->origin[2] == listener_pos[1]) ) - { + if ((loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) && (loop->origin[2] == listener_pos[1])) { // Assume that this sound is head relative loop->bRelative = qtrue; ch->origin[0] = 0.f; ch->origin[1] = 0.f; ch->origin[2] = 0.f; - } - else - { + } else { ch->origin[0] = loop->origin[0]; ch->origin[1] = loop->origin[1]; ch->origin[2] = loop->origin[2]; @@ -3411,12 +3052,9 @@ void UpdateLoopingSounds() alSourcei(s_channels[source].alSource, AL_LOOPING, AL_TRUE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.0f); alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, ch->fixed_origin ? AL_TRUE : AL_FALSE); - if (ch->entchannel == CHAN_LESS_ATTEN) - { // Reduced fall-off + if (ch->entchannel == CHAN_LESS_ATTEN) { // Reduced fall-off alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_VOICE_REF_DISTANCE); - } - else - { + } else { alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); } if (s_bEALFileLoaded) @@ -3430,13 +3068,12 @@ void UpdateLoopingSounds() } } -void AL_UpdateRawSamples() -{ +void AL_UpdateRawSamples() { ALuint buffer; ALint size; ALint processed; ALint state; - int i,j,src; + int i, j, src; #ifdef _DEBUG // Clear Open AL Error @@ -3448,8 +3085,7 @@ void AL_UpdateRawSamples() // Find out how many buffers have been processed (played) by the Source alGetSourcei(s_channels[0].alSource, AL_BUFFERS_PROCESSED, &processed); - while (processed) - { + while (processed) { // Unqueue each buffer, determine the length of the buffer, and then delete it alSourceUnqueueBuffers(s_channels[0].alSource, 1, &buffer); alGetBufferi(buffer, AL_SIZE, &size); @@ -3462,22 +3098,19 @@ void AL_UpdateRawSamples() } // Add new data to a new Buffer and queue it on the Source - if (s_rawend > s_paintedtime) - { - size = (s_rawend - s_paintedtime)<<2; - if (size > (MAX_RAW_SAMPLES<<2)) - { + if (s_rawend > s_paintedtime) { + size = (s_rawend - s_paintedtime) << 2; + if (size > (MAX_RAW_SAMPLES << 2)) { OutputDebugString("UpdateRawSamples :- Raw Sample buffer has overflowed !!!\n"); - size = MAX_RAW_SAMPLES<<2; + size = MAX_RAW_SAMPLES << 2; s_paintedtime = s_rawend - MAX_RAW_SAMPLES; } // Copy samples from RawSamples to audio buffer (sg.rawdata) - for (i = s_paintedtime, j = 0; i < s_rawend; i++, j+=2) - { + for (i = s_paintedtime, j = 0; i < s_rawend; i++, j += 2) { src = i & (MAX_RAW_SAMPLES - 1); - s_rawdata[j] = (short)(s_rawsamples[src].left>>8); - s_rawdata[j+1] = (short)(s_rawsamples[src].right>>8); + s_rawdata[j] = (short)(s_rawsamples[src].left >> 8); + s_rawdata[j + 1] = (short)(s_rawsamples[src].right >> 8); } // Need to generate more than 1 buffer for music playback @@ -3495,19 +3128,15 @@ void AL_UpdateRawSamples() // iterations++; int iterations = 0; - int largestBufferSize = MAX_RAW_SAMPLES; // in bytes (== quarter of Raw Samples data) - while (size) - { + int largestBufferSize = MAX_RAW_SAMPLES; // in bytes (== quarter of Raw Samples data) + while (size) { alGenBuffers(1, &buffer); - if (size > largestBufferSize) - { - alBufferData(buffer, AL_FORMAT_STEREO16, (char*)(s_rawdata + ((iterations * largestBufferSize)>>1)), largestBufferSize, 22050); + if (size > largestBufferSize) { + alBufferData(buffer, AL_FORMAT_STEREO16, (char *)(s_rawdata + ((iterations * largestBufferSize) >> 1)), largestBufferSize, 22050); size -= largestBufferSize; - } - else - { - alBufferData(buffer, AL_FORMAT_STEREO16, (char*)(s_rawdata + ((iterations * largestBufferSize)>>1)), size, 22050); + } else { + alBufferData(buffer, AL_FORMAT_STEREO16, (char *)(s_rawdata + ((iterations * largestBufferSize) >> 1)), size, 22050); size = 0; } @@ -3520,13 +3149,11 @@ void AL_UpdateRawSamples() // Check that the Source is actually playing alGetSourcei(s_channels[0].alSource, AL_SOURCE_STATE, &state); - if (state != AL_PLAYING) - { + if (state != AL_PLAYING) { // Stopped playing ... due to buffer underrun // Unqueue any buffers still on the Source (they will be PROCESSED), and restart playback alGetSourcei(s_channels[0].alSource, AL_BUFFERS_PROCESSED, &processed); - while (processed) - { + while (processed) { alSourceUnqueueBuffers(s_channels[0].alSource, 1, &buffer); processed--; alGetBufferi(buffer, AL_SIZE, &size); @@ -3550,14 +3177,12 @@ void AL_UpdateRawSamples() } #endif -int S_MP3PreProcessLipSync(channel_t *ch, short *data) -{ +int S_MP3PreProcessLipSync(channel_t *ch, short *data) { int i; int sample; int sampleTotal = 0; - for (i = 0; i < 576; i += 100) - { + for (i = 0; i < 576; i += 100) { sample = LittleShort(data[i]); sample = sample >> 8; sampleTotal += sample * sample; @@ -3579,9 +3204,7 @@ int S_MP3PreProcessLipSync(channel_t *ch, short *data) return sample; } - -void S_SetLipSyncs() -{ +void S_SetLipSyncs() { int i; unsigned int samples; int currentTime, timePlayed; @@ -3595,31 +3218,27 @@ void S_SetLipSyncs() #ifdef _WIN32 currentTime = timeGetTime(); #else - // FIXME: alternative to timeGetTime ? - currentTime = 0; + // FIXME: alternative to timeGetTime ? + currentTime = 0; #endif memset(s_entityWavVol, 0, sizeof(s_entityWavVol)); ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((!ch->thesfx)||(!ch->bPlaying)) + for (i = 1; i < s_numChannels; i++, ch++) { + if ((!ch->thesfx) || (!ch->bPlaying)) continue; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { // Calculate how much time has passed since the sample was started timePlayed = currentTime - ch->iStartTime; - if (ch->thesfx->eSoundCompressionMethod==ct_16) - { + if (ch->thesfx->eSoundCompressionMethod == ct_16) { // There is a new computed lip-sync value every 1000 samples - so find out how many samples // have been played and lookup the value in the lip-sync table samples = (timePlayed * 22050) / 1000; - if (ch->thesfx->lipSyncData == NULL) - { + if (ch->thesfx->lipSyncData == NULL) { #ifdef _DEBUG #ifdef _MSC_VER sprintf(szString, "Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); @@ -3628,27 +3247,23 @@ void S_SetLipSyncs() #endif } - if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) - { - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[samples / 1000]; + if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[samples / 1000]; -// Com_Printf("%s, total samples = %d, current sample = %d, lip type = %d \n", ch->thesfx->sSoundName, ch->thesfx->iSoundLengthInSamples, samples, s_entityWavVol[ ch->entnum ] ); - if ( s_show->integer == 3 ) - { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + // Com_Printf("%s, total samples = %d, current sample = %d, lip type = %d \n", ch->thesfx->sSoundName, + //ch->thesfx->iSoundLengthInSamples, samples, s_entityWavVol[ ch->entnum ] ); + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } - } - else - { + } else { // MP3 // There is a new computed lip-sync value every 576 samples - so find out how many samples // have been played and lookup the value in the lip-sync table samples = (timePlayed * 22050) / 1000; - if (ch->thesfx->lipSyncData == NULL) - { + if (ch->thesfx->lipSyncData == NULL) { #ifdef _DEBUG #ifdef _MSC_VER sprintf(szString, "Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); @@ -3657,13 +3272,11 @@ void S_SetLipSyncs() #endif } - if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) - { - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[(samples / 576) % 16]; + if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[(samples / 576) % 16]; - if ( s_show->integer == 3 ) - { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } } @@ -3671,7 +3284,6 @@ void S_SetLipSyncs() } } - /* =============================================================================== @@ -3680,105 +3292,79 @@ console functions =============================================================================== */ -static void S_Play_f( void ) { - int i; - sfxHandle_t h; +static void S_Play_f(void) { + int i; + sfxHandle_t h; char name[256]; i = 1; - while ( i [loopfile]\n"); + Com_Printf("music [loopfile]\n"); return; } } -static void S_StopMusic_f( void ) { - S_StopBackgroundTrack(); -} +static void S_StopMusic_f(void) { S_StopBackgroundTrack(); } // a debug function, but no harm to leave in... // -static void S_SetDynamicMusic_f(void) -{ +static void S_SetDynamicMusic_f(void) { int c = Cmd_Argc(); - if ( c == 2 ) - { - if (bMusic_IsDynamic) - { + if (c == 2) { + if (bMusic_IsDynamic) { // don't need to check existance of 'explore' or 'action' music, since music wouldn't // be counted as dynamic if either were missing, but other types are optional... // - if (!Q_stricmp(Cmd_Argv(1),"explore")) - { - S_SetDynamicMusicState( eBGRNDTRACK_EXPLORE ); + if (!Q_stricmp(Cmd_Argv(1), "explore")) { + S_SetDynamicMusicState(eBGRNDTRACK_EXPLORE); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"action")) - { - S_SetDynamicMusicState( eBGRNDTRACK_ACTION ); + } else if (!Q_stricmp(Cmd_Argv(1), "action")) { + S_SetDynamicMusicState(eBGRNDTRACK_ACTION); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"silence")) - { - S_SetDynamicMusicState( eBGRNDTRACK_SILENCE ); + } else if (!Q_stricmp(Cmd_Argv(1), "silence")) { + S_SetDynamicMusicState(eBGRNDTRACK_SILENCE); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"boss")) - { - if (tMusic_Info[ eBGRNDTRACK_BOSS ].bExists) - { - S_SetDynamicMusicState( eBGRNDTRACK_BOSS ); - } - else - { + } else if (!Q_stricmp(Cmd_Argv(1), "boss")) { + if (tMusic_Info[eBGRNDTRACK_BOSS].bExists) { + S_SetDynamicMusicState(eBGRNDTRACK_BOSS); + } else { Com_Printf("No 'boss' music defined in current dynamic set\n"); } return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"death")) - { - if (tMusic_Info[ eBGRNDTRACK_DEATH ].bExists) - { - S_SetDynamicMusicState( eBGRNDTRACK_DEATH ); - } - else - { + } else if (!Q_stricmp(Cmd_Argv(1), "death")) { + if (tMusic_Info[eBGRNDTRACK_DEATH].bExists) { + S_SetDynamicMusicState(eBGRNDTRACK_DEATH); + } else { Com_Printf("No 'death' music defined in current dynamic set\n"); } return; } - } - else - { - DynamicMusicInfoPrint(); // print "inactive" string + } else { + DynamicMusicInfoPrint(); // print "inactive" string return; } } @@ -3789,60 +3375,40 @@ static void S_SetDynamicMusic_f(void) DynamicMusicInfoPrint(); } - // this table needs to be in-sync with the typedef'd enum "SoundCompressionMethod_t"... -ste // -static const char *sSoundCompressionMethodStrings[ct_NUMBEROF] = -{ - "16b", // ct_16 - "mp3" // ct_MP3 +static const char *sSoundCompressionMethodStrings[ct_NUMBEROF] = { + "16b", // ct_16 + "mp3" // ct_MP3 }; -void S_SoundList_f( void ) { - int i; - sfx_t *sfx; - int size, total; - int iVariantCap = -1; // for %d-inquiry stuff - int iTotalBytes = 0; +void S_SoundList_f(void) { + int i; + sfx_t *sfx; + int size, total; + int iVariantCap = -1; // for %d-inquiry stuff + int iTotalBytes = 0; qboolean bWavOnly = qfalse; qboolean bShouldBeMP3 = qfalse; - if ( Cmd_Argc() == 2 ) - { - if (!Q_stricmp(Cmd_Argv(1), "shouldbeMP3")) - { + if (Cmd_Argc() == 2) { + if (!Q_stricmp(Cmd_Argv(1), "shouldbeMP3")) { bShouldBeMP3 = qtrue; - } - else - if (!Q_stricmp(Cmd_Argv(1), "wavonly")) - { + } else if (!Q_stricmp(Cmd_Argv(1), "wavonly")) { bWavOnly = qtrue; - } - else - { - if (!Q_stricmp(Cmd_Argv(1), "1")) - { + } else { + if (!Q_stricmp(Cmd_Argv(1), "1")) { iVariantCap = 1; - } - else - if (!Q_stricmp(Cmd_Argv(1), "2")) - { + } else if (!Q_stricmp(Cmd_Argv(1), "2")) { iVariantCap = 2; - } - else - if (!Q_stricmp(Cmd_Argv(1), "3")) - { + } else if (!Q_stricmp(Cmd_Argv(1), "3")) { iVariantCap = 3; } } - } - else - { - Com_Printf("( additional (mutually exclusive) options available:\n'wavonly', 'ShouldBeMP3', '1'/'2'/'3' for %%d-variant capping )\n" ); + } else { + Com_Printf("( additional (mutually exclusive) options available:\n'wavonly', 'ShouldBeMP3', '1'/'2'/'3' for %%d-variant capping )\n"); } - - total = 0; Com_Printf("\n"); @@ -3852,44 +3418,33 @@ void S_SoundList_f( void ) { Com_Printf(" | |\n"); Com_Printf(" | |\n"); Com_Printf(" Slot Smpls Type | | Name\n"); -// Com_Printf(" Slot Smpls Type InMem? Name\n"); + // Com_Printf(" Slot Smpls Type InMem? Name\n"); - for (sfx=s_knownSfx, i=0 ; ibDefaultSound && - !sfx->pMP3StreamHeader && - sfx->pSoundData && - (Z_Size(sfx->pSoundData) > cv_MP3overhead->integer)); - - if (bMP3DumpOverride || (!bShouldBeMP3 && (!bWavOnly || sfx->eSoundCompressionMethod == ct_16))) - { + qboolean bMP3DumpOverride = (qboolean)(bShouldBeMP3 && cv_MP3overhead && !sfx->bDefaultSound && !sfx->pMP3StreamHeader && sfx->pSoundData && + (Z_Size(sfx->pSoundData) > cv_MP3overhead->integer)); + + if (bMP3DumpOverride || (!bShouldBeMP3 && (!bWavOnly || sfx->eSoundCompressionMethod == ct_16))) { qboolean bDumpThisOne = qtrue; - if (iVariantCap >= 1 && iVariantCap <= 3) - { + if (iVariantCap >= 1 && iVariantCap <= 3) { int iStrLen = strlen(sfx->sSoundName); - if (iStrLen > 2) // crash-safety, jic. + if (iStrLen > 2) // crash-safety, jic. { - char c = sfx->sSoundName[iStrLen-1]; - char c2 = sfx->sSoundName[iStrLen-2]; + char c = sfx->sSoundName[iStrLen - 1]; + char c2 = sfx->sSoundName[iStrLen - 2]; if (!isdigit(c2) // quick-avoid of stuff like "pain75" - && isdigit(c) && atoi(va("%c",c)) > iVariantCap) - { + && isdigit(c) && atoi(va("%c", c)) > iVariantCap) { // need to see if this %d-variant should be omitted, in other words if there's a %1 version then skip this... // char sFindName[MAX_QPATH]; - Q_strncpyz(sFindName,sfx->sSoundName,sizeof(sFindName)); - sFindName[iStrLen-1] = '1'; + Q_strncpyz(sFindName, sfx->sSoundName, sizeof(sFindName)); + sFindName[iStrLen - 1] = '1'; int i2; sfx_t *sfx2; - for (sfx2 = s_knownSfx, i2=0 ; i2sSoundName)) - { - bDumpThisOne = qfalse; // found a %1-variant of this, so use variant capping and ignore this sfx_t + for (sfx2 = s_knownSfx, i2 = 0; i2 < s_numSfx; i2++, sfx2++) { + if (!Q_stricmp(sFindName, sfx2->sSoundName)) { + bDumpThisOne = qfalse; // found a %1-variant of this, so use variant capping and ignore this sfx_t break; } } @@ -3898,24 +3453,20 @@ void S_SoundList_f( void ) { } size = sfx->iSoundLengthInSamples; - if (sfx->bDefaultSound) - { - Com_Printf("%5d Missing file: \"%s\"\n", i, sfx->sSoundName ); - } - else - { - if (bDumpThisOne) - { + if (sfx->bDefaultSound) { + Com_Printf("%5d Missing file: \"%s\"\n", i, sfx->sSoundName); + } else { + if (bDumpThisOne) { iTotalBytes += (sfx->bInMemory && sfx->pSoundData) ? Z_Size(sfx->pSoundData) : 0; iTotalBytes += (sfx->bInMemory && sfx->pMP3StreamHeader) ? sizeof(*sfx->pMP3StreamHeader) : 0; - total += sfx->bInMemory ? size : 0; + total += sfx->bInMemory ? size : 0; } - Com_Printf("%5d %7i [%s] %s %2d %s", i, size, sSoundCompressionMethodStrings[sfx->eSoundCompressionMethod], sfx->bInMemory?"y":"n", sfx->iLastLevelUsedOn, sfx->sSoundName ); + Com_Printf("%5d %7i [%s] %s %2d %s", i, size, sSoundCompressionMethodStrings[sfx->eSoundCompressionMethod], sfx->bInMemory ? "y" : "n", + sfx->iLastLevelUsedOn, sfx->sSoundName); - if (!bDumpThisOne) - { + if (!bDumpThisOne) { Com_Printf(" ( Skipping, variant capped )"); - //OutputDebugString(va("Variant capped: %s\n",sfx->sSoundName)); + // OutputDebugString(va("Variant capped: %s\n",sfx->sSoundName)); } Com_Printf("\n"); } @@ -3923,14 +3474,12 @@ void S_SoundList_f( void ) { } Com_Printf(" Slot Smpls Type In? Lev Name\n"); - - Com_Printf ("Total resident samples: %i %s ( not mem usage, see 'meminfo' ).\n", total, bWavOnly?"(WAV only)":""); - Com_Printf ("%d out of %d sfx_t slots used\n", s_numSfx, MAX_SFX); - Com_Printf ("%.2fMB bytes used when counting sfx_t->pSoundData + MP3 headers (if any)\n", (float)iTotalBytes / 1024.0f / 1024.0f); + Com_Printf("Total resident samples: %i %s ( not mem usage, see 'meminfo' ).\n", total, bWavOnly ? "(WAV only)" : ""); + Com_Printf("%d out of %d sfx_t slots used\n", s_numSfx, MAX_SFX); + Com_Printf("%.2fMB bytes used when counting sfx_t->pSoundData + MP3 headers (if any)\n", (float)iTotalBytes / 1024.0f / 1024.0f); S_DisplayFreeMemory(); } - /* =============================================================================== @@ -3939,43 +3488,43 @@ background music functions =============================================================================== */ -int FGetLittleLong( fileHandle_t f ) { - int v; +int FGetLittleLong(fileHandle_t f) { + int v; - FS_Read( &v, sizeof(v), f ); + FS_Read(&v, sizeof(v), f); - return LittleLong( v); + return LittleLong(v); } -int FGetLittleShort( fileHandle_t f ) { - short v; +int FGetLittleShort(fileHandle_t f) { + short v; - FS_Read( &v, sizeof(v), f ); + FS_Read(&v, sizeof(v), f); - return LittleShort( v); + return LittleShort(v); } // returns the length of the data in the chunk, or 0 if not found -int S_FindWavChunk( fileHandle_t f, const char *chunk ) { - char name[5]; - int len; - int r; +int S_FindWavChunk(fileHandle_t f, const char *chunk) { + char name[5]; + int len; + int r; name[4] = 0; len = 0; - r = FS_Read( name, 4, f ); - if ( r != 4 ) { + r = FS_Read(name, 4, f); + if (r != 4) { return 0; } - len = FGetLittleLong( f ); - if ( len < 0 || len > 0xfffffff ) { + len = FGetLittleLong(f); + if (len < 0 || len > 0xfffffff) { len = 0; return 0; } - len = (len + 1 ) & ~1; // pad to word boundary -// s_nextWavChunk += len + 8; + len = (len + 1) & ~1; // pad to word boundary + // s_nextWavChunk += len + 8; - if ( strcmp( name, chunk ) ) { + if (strcmp(name, chunk)) { return 0; } return len; @@ -3986,11 +3535,10 @@ int S_FindWavChunk( fileHandle_t f, const char *chunk ) { // // DO NOT replace this with a call to FS_FileExists, that's for checking about writing out, and doesn't work for this. // -qboolean S_FileExists( const char *psFilename ) -{ +qboolean S_FileExists(const char *psFilename) { fileHandle_t fhTemp; - FS_FOpenFileRead (psFilename, &fhTemp, qtrue); // qtrue so I can fclose the handle without closing a PAK + FS_FOpenFileRead(psFilename, &fhTemp, qtrue); // qtrue so I can fclose the handle without closing a PAK if (!fhTemp) return qfalse; @@ -4000,145 +3548,125 @@ qboolean S_FileExists( const char *psFilename ) // some stuff for streaming MP3 files from disk (not pleasant, but nothing about MP3 is, other than compression ratios...) // -static void MP3MusicStream_Reset(MusicInfo_t *pMusicInfo) -{ - pMusicInfo->iMP3MusicStream_DiskReadPos = 0; - pMusicInfo->iMP3MusicStream_DiskWindowPos = 0; +static void MP3MusicStream_Reset(MusicInfo_t *pMusicInfo) { + pMusicInfo->iMP3MusicStream_DiskReadPos = 0; + pMusicInfo->iMP3MusicStream_DiskWindowPos = 0; } // // return is where the decoder should read from... // -static byte *MP3MusicStream_ReadFromDisk(MusicInfo_t *pMusicInfo, int iReadOffset, int iReadBytesNeeded) -{ - if (iReadOffset < pMusicInfo->iMP3MusicStream_DiskWindowPos) - { - assert(0); // should never happen - return pMusicInfo->byMP3MusicStream_DiskBuffer; // ...but return something safe anyway +static byte *MP3MusicStream_ReadFromDisk(MusicInfo_t *pMusicInfo, int iReadOffset, int iReadBytesNeeded) { + if (iReadOffset < pMusicInfo->iMP3MusicStream_DiskWindowPos) { + assert(0); // should never happen + return pMusicInfo->byMP3MusicStream_DiskBuffer; // ...but return something safe anyway } - while (iReadOffset + iReadBytesNeeded > pMusicInfo->iMP3MusicStream_DiskReadPos) - { - int iBytesRead = FS_Read( pMusicInfo->byMP3MusicStream_DiskBuffer + (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos), iMP3MusicStream_DiskBytesToRead, pMusicInfo->s_backgroundFile ); + while (iReadOffset + iReadBytesNeeded > pMusicInfo->iMP3MusicStream_DiskReadPos) { + int iBytesRead = + FS_Read(pMusicInfo->byMP3MusicStream_DiskBuffer + (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos), + iMP3MusicStream_DiskBytesToRead, pMusicInfo->s_backgroundFile); pMusicInfo->iMP3MusicStream_DiskReadPos += iBytesRead; - if (iBytesRead != iMP3MusicStream_DiskBytesToRead) // quietly ignore any requests to read past file end + if (iBytesRead != iMP3MusicStream_DiskBytesToRead) // quietly ignore any requests to read past file end { - break; // we need to do this because the disk read code can't know how much source data we need to - // read for a given number of requested output bytes, so we'll always be asking for too many + break; // we need to do this because the disk read code can't know how much source data we need to + // read for a given number of requested output bytes, so we'll always be asking for too many } } // if reached halfway point in buffer (approx 20k), backscroll it... // - if (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos > iMP3MusicStream_DiskBufferSize/2) - { + if (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos > iMP3MusicStream_DiskBufferSize / 2) { int iMoveSrcOffset = iReadOffset - pMusicInfo->iMP3MusicStream_DiskWindowPos; - int iMoveCount = (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos ) - iMoveSrcOffset; - memmove( &pMusicInfo->byMP3MusicStream_DiskBuffer, &pMusicInfo->byMP3MusicStream_DiskBuffer[iMoveSrcOffset], iMoveCount); + int iMoveCount = (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos) - iMoveSrcOffset; + memmove(&pMusicInfo->byMP3MusicStream_DiskBuffer, &pMusicInfo->byMP3MusicStream_DiskBuffer[iMoveSrcOffset], iMoveCount); pMusicInfo->iMP3MusicStream_DiskWindowPos += iMoveSrcOffset; } return pMusicInfo->byMP3MusicStream_DiskBuffer + (iReadOffset - pMusicInfo->iMP3MusicStream_DiskWindowPos); } - // does NOT set s_rawend!... // -static void S_StopBackgroundTrack_Actual( MusicInfo_t *pMusicInfo ) -{ - if ( pMusicInfo->s_backgroundFile ) - { - if ( pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); +static void S_StopBackgroundTrack_Actual(MusicInfo_t *pMusicInfo) { + if (pMusicInfo->s_backgroundFile) { + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } } -static void FreeMusic( MusicInfo_t *pMusicInfo ) -{ - if (pMusicInfo->pLoadedData) - { +static void FreeMusic(MusicInfo_t *pMusicInfo) { + if (pMusicInfo->pLoadedData) { Z_Free(pMusicInfo->pLoadedData); - pMusicInfo->pLoadedData = NULL; // these two MUST be kept as valid/invalid together - pMusicInfo->sLoadedDataName[0]= '\0'; // - pMusicInfo->iLoadedDataLen = 0; + pMusicInfo->pLoadedData = NULL; // these two MUST be kept as valid/invalid together + pMusicInfo->sLoadedDataName[0] = '\0'; // + pMusicInfo->iLoadedDataLen = 0; } } // called only by snd_shutdown (from snd_restart or app exit) // -void S_UnCacheDynamicMusic( void ) -{ - for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) - { - FreeMusic( &tMusic_Info[i]); +void S_UnCacheDynamicMusic(void) { + for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) { + FreeMusic(&tMusic_Info[i]); } } -static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean qbDynamic, const char *intro, const char *loop ) -{ - int len; - char dump[16]; - char name[MAX_QPATH]; +static qboolean S_StartBackgroundTrack_Actual(MusicInfo_t *pMusicInfo, qboolean qbDynamic, const char *intro, const char *loop) { + int len; + char dump[16]; + char name[MAX_QPATH]; - Q_strncpyz( sMusic_BackgroundLoop, loop, sizeof( sMusic_BackgroundLoop )); + Q_strncpyz(sMusic_BackgroundLoop, loop, sizeof(sMusic_BackgroundLoop)); - Q_strncpyz( name, intro, sizeof( name ) - 4 ); // this seems to be so that if the filename hasn't got an extension - // but doesn't have the room to append on either then you'll just - // get the "soft" fopen() error, rather than the ERR_DROP you'd get - // if COM_DefaultExtension didn't have room to add it on. - COM_DefaultExtension( name, sizeof( name ), ".mp3" ); + Q_strncpyz(name, intro, sizeof(name) - 4); // this seems to be so that if the filename hasn't got an extension + // but doesn't have the room to append on either then you'll just + // get the "soft" fopen() error, rather than the ERR_DROP you'd get + // if COM_DefaultExtension didn't have room to add it on. + COM_DefaultExtension(name, sizeof(name), ".mp3"); // close the background track, but DON'T reset s_rawend (or remaining music bits that haven't been output yet will be cut off) // - S_StopBackgroundTrack_Actual( pMusicInfo ); + S_StopBackgroundTrack_Actual(pMusicInfo); pMusicInfo->bIsMP3 = qfalse; - if ( !intro[0] ) { + if (!intro[0]) { return qfalse; } // new bit, if file requested is not same any loaded one (if prev was in-mem), ditch it... // - if (Q_stricmp(name, pMusicInfo->sLoadedDataName)) - { - FreeMusic( pMusicInfo ); + if (Q_stricmp(name, pMusicInfo->sLoadedDataName)) { + FreeMusic(pMusicInfo); } - if (!Q_stricmpn(name+(strlen(name)-4),".mp3",4)) - { - if (pMusicInfo->pLoadedData) - { + if (!Q_stricmpn(name + (strlen(name) - 4), ".mp3", 4)) { + if (pMusicInfo->pLoadedData) { pMusicInfo->s_backgroundFile = -1; - } - else - { - pMusicInfo->iLoadedDataLen = FS_FOpenFileRead( name, &pMusicInfo->s_backgroundFile, qtrue ); + } else { + pMusicInfo->iLoadedDataLen = FS_FOpenFileRead(name, &pMusicInfo->s_backgroundFile, qtrue); } - if (!pMusicInfo->s_backgroundFile) - { - Com_Printf( S_COLOR_RED"Couldn't open music file %s\n", name ); + if (!pMusicInfo->s_backgroundFile) { + Com_Printf(S_COLOR_RED "Couldn't open music file %s\n", name); return qfalse; } - MP3MusicStream_Reset( pMusicInfo ); + MP3MusicStream_Reset(pMusicInfo); - byte *pbMP3DataSegment = NULL; - int iInitialMP3ReadSize = 8192; // fairly arbitrary, whatever size this is then the decoder is allowed to - // scan up to halfway of it to find floating headers, so don't make it - // too small. 8k works fine. + byte *pbMP3DataSegment = NULL; + int iInitialMP3ReadSize = 8192; // fairly arbitrary, whatever size this is then the decoder is allowed to + // scan up to halfway of it to find floating headers, so don't make it + // too small. 8k works fine. qboolean bMusicSucceeded = qfalse; - if (qbDynamic) - { - if (!pMusicInfo->pLoadedData) - { - pMusicInfo->pLoadedData = (byte *) Z_Malloc(pMusicInfo->iLoadedDataLen, TAG_SND_DYNAMICMUSIC, qfalse); + if (qbDynamic) { + if (!pMusicInfo->pLoadedData) { + pMusicInfo->pLoadedData = (byte *)Z_Malloc(pMusicInfo->iLoadedDataLen, TAG_SND_DYNAMICMUSIC, qfalse); S_ClearSoundBuffer(); FS_Read(pMusicInfo->pLoadedData, pMusicInfo->iLoadedDataLen, pMusicInfo->s_backgroundFile); @@ -4147,95 +3675,79 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean // enable the rest of the code to work as before... // - pbMP3DataSegment = pMusicInfo->pLoadedData; + pbMP3DataSegment = pMusicInfo->pLoadedData; iInitialMP3ReadSize = pMusicInfo->iLoadedDataLen; - } - else - { + } else { pbMP3DataSegment = MP3MusicStream_ReadFromDisk(pMusicInfo, 0, iInitialMP3ReadSize); } - if (MP3_IsValid(name, pbMP3DataSegment, iInitialMP3ReadSize, qtrue /*bStereoDesired*/)) - { + if (MP3_IsValid(name, pbMP3DataSegment, iInitialMP3ReadSize, qtrue /*bStereoDesired*/)) { // init stream struct... // - memset(&pMusicInfo->streamMP3_Bgrnd,0,sizeof(pMusicInfo->streamMP3_Bgrnd)); - char *psError = C_MP3Stream_DecodeInit( &pMusicInfo->streamMP3_Bgrnd, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, - dma.speed, - 16, // sfx->width * 8, - qtrue // bStereoDesired - ); + memset(&pMusicInfo->streamMP3_Bgrnd, 0, sizeof(pMusicInfo->streamMP3_Bgrnd)); + char *psError = C_MP3Stream_DecodeInit(&pMusicInfo->streamMP3_Bgrnd, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, dma.speed, + 16, // sfx->width * 8, + qtrue // bStereoDesired + ); - - if (psError == NULL) - { + if (psError == NULL) { // init sfx struct & setup the few fields I actually need... // - memset( &pMusicInfo->sfxMP3_Bgrnd,0,sizeof(pMusicInfo->sfxMP3_Bgrnd)); + memset(&pMusicInfo->sfxMP3_Bgrnd, 0, sizeof(pMusicInfo->sfxMP3_Bgrnd)); // pMusicInfo->sfxMP3_Bgrnd.width = 2; // read by MP3_GetSamples() - pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples = 0x7FFFFFFF; // max possible +ve int, since music finishes when decoder stops - pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader = &pMusicInfo->streamMP3_Bgrnd; - Q_strncpyz( pMusicInfo->sfxMP3_Bgrnd.sSoundName, name, sizeof(pMusicInfo->sfxMP3_Bgrnd.sSoundName) ); + pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples = 0x7FFFFFFF; // max possible +ve int, since music finishes when decoder stops + pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader = &pMusicInfo->streamMP3_Bgrnd; + Q_strncpyz(pMusicInfo->sfxMP3_Bgrnd.sSoundName, name, sizeof(pMusicInfo->sfxMP3_Bgrnd.sSoundName)); - if (qbDynamic) - { - MP3Stream_InitPlayingTimeFields ( &pMusicInfo->streamMP3_Bgrnd, name, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, qtrue); + if (qbDynamic) { + MP3Stream_InitPlayingTimeFields(&pMusicInfo->streamMP3_Bgrnd, name, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, qtrue); } - pMusicInfo->s_backgroundInfo.format = WAV_FORMAT_MP3; // not actually used this way, but just ensures we don't match one of the legit formats - pMusicInfo->s_backgroundInfo.channels = 2; // always, for our MP3s when used for music (else 1 for FX) - pMusicInfo->s_backgroundInfo.rate = dma.speed; - pMusicInfo->s_backgroundInfo.width = 2; // always, for our MP3s - pMusicInfo->s_backgroundInfo.samples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; - pMusicInfo->s_backgroundSamples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; + pMusicInfo->s_backgroundInfo.format = WAV_FORMAT_MP3; // not actually used this way, but just ensures we don't match one of the legit formats + pMusicInfo->s_backgroundInfo.channels = 2; // always, for our MP3s when used for music (else 1 for FX) + pMusicInfo->s_backgroundInfo.rate = dma.speed; + pMusicInfo->s_backgroundInfo.width = 2; // always, for our MP3s + pMusicInfo->s_backgroundInfo.samples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; + pMusicInfo->s_backgroundSamples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; - memset(&pMusicInfo->chMP3_Bgrnd,0,sizeof(pMusicInfo->chMP3_Bgrnd)); - pMusicInfo->chMP3_Bgrnd.thesfx = &pMusicInfo->sfxMP3_Bgrnd; + memset(&pMusicInfo->chMP3_Bgrnd, 0, sizeof(pMusicInfo->chMP3_Bgrnd)); + pMusicInfo->chMP3_Bgrnd.thesfx = &pMusicInfo->sfxMP3_Bgrnd; memcpy(&pMusicInfo->chMP3_Bgrnd.MP3StreamHeader, pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader, sizeof(*pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader)); - if (qbDynamic) - { - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundFile = -1; // special mp3 value for "valid, but not a real file" + if (qbDynamic) { + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundFile = -1; // special mp3 value for "valid, but not a real file" } } pMusicInfo->bIsMP3 = qtrue; bMusicSucceeded = qtrue; - } - else - { - Com_Printf(S_COLOR_RED"Error streaming file %s: %s\n", name, psError); - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + } else { + Com_Printf(S_COLOR_RED "Error streaming file %s: %s\n", name, psError); + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } - } - else - { + } else { // MP3_IsValid() will already have printed any errors via Com_Printf at this point... // - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } return bMusicSucceeded; - } - else // not an mp3 file + } else // not an mp3 file { // // open up a wav file and get all the info // - FS_FOpenFileRead( name, &pMusicInfo->s_backgroundFile, qtrue ); - if ( !pMusicInfo->s_backgroundFile ) { - Com_Printf( S_COLOR_YELLOW "WARNING: couldn't open music file %s\n", name ); + FS_FOpenFileRead(name, &pMusicInfo->s_backgroundFile, qtrue); + if (!pMusicInfo->s_backgroundFile) { + Com_Printf(S_COLOR_YELLOW "WARNING: couldn't open music file %s\n", name); return qfalse; } @@ -4243,34 +3755,34 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean FS_Read(dump, 12, pMusicInfo->s_backgroundFile); - if ( !S_FindWavChunk( pMusicInfo->s_backgroundFile, "fmt " ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: No fmt chunk in %s\n", name ); - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if (!S_FindWavChunk(pMusicInfo->s_backgroundFile, "fmt ")) { + Com_Printf(S_COLOR_YELLOW "WARNING: No fmt chunk in %s\n", name); + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; return qfalse; } // save name for soundinfo - pMusicInfo->s_backgroundInfo.format = FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.channels = FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.rate = FGetLittleLong( pMusicInfo->s_backgroundFile ); - FGetLittleLong( pMusicInfo->s_backgroundFile ); - FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.width = FGetLittleShort( pMusicInfo->s_backgroundFile ) / 8; - - if ( pMusicInfo->s_backgroundInfo.format != WAV_FORMAT_PCM ) { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + pMusicInfo->s_backgroundInfo.format = FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.channels = FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.rate = FGetLittleLong(pMusicInfo->s_backgroundFile); + FGetLittleLong(pMusicInfo->s_backgroundFile); + FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.width = FGetLittleShort(pMusicInfo->s_backgroundFile) / 8; + + if (pMusicInfo->s_backgroundInfo.format != WAV_FORMAT_PCM) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; Com_Printf(S_COLOR_YELLOW "WARNING: Not a microsoft PCM format wav: %s\n", name); return qfalse; } - if ( pMusicInfo->s_backgroundInfo.channels != 2 || pMusicInfo->s_backgroundInfo.rate != 22050 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: music file %s is not 22k stereo\n", name ); + if (pMusicInfo->s_backgroundInfo.channels != 2 || pMusicInfo->s_backgroundInfo.rate != 22050) { + Com_Printf(S_COLOR_YELLOW "WARNING: music file %s is not 22k stereo\n", name); } - if ( ( len = S_FindWavChunk( pMusicInfo->s_backgroundFile, "data" ) ) == 0 ) { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if ((len = S_FindWavChunk(pMusicInfo->s_backgroundFile, "data")) == 0) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; Com_Printf(S_COLOR_YELLOW "WARNING: No data chunk in %s\n", name); return qfalse; @@ -4284,37 +3796,33 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean return qtrue; } - -static void S_SwitchDynamicTracks( MusicState_e eOldState, MusicState_e eNewState, qboolean bNewTrackStartsFullVolume ) -{ +static void S_SwitchDynamicTracks(MusicState_e eOldState, MusicState_e eNewState, qboolean bNewTrackStartsFullVolume) { // copy old track into fader... // - tMusic_Info[ eBGRNDTRACK_FADE ] = tMusic_Info[ eOldState ]; -// tMusic_Info[ eBGRNDTRACK_FADE ].bActive = qtrue; // inherent -// tMusic_Info[ eBGRNDTRACK_FADE ].bExists = qtrue; // inherent - tMusic_Info[ eBGRNDTRACK_FADE ].iXFadeVolumeSeekTime= Sys_Milliseconds(); - tMusic_Info[ eBGRNDTRACK_FADE ].iXFadeVolumeSeekTo = 0; + tMusic_Info[eBGRNDTRACK_FADE] = tMusic_Info[eOldState]; + // tMusic_Info[ eBGRNDTRACK_FADE ].bActive = qtrue; // inherent + // tMusic_Info[ eBGRNDTRACK_FADE ].bExists = qtrue; // inherent + tMusic_Info[eBGRNDTRACK_FADE].iXFadeVolumeSeekTime = Sys_Milliseconds(); + tMusic_Info[eBGRNDTRACK_FADE].iXFadeVolumeSeekTo = 0; // // ... and deactivate... // - tMusic_Info[ eOldState ].bActive = qfalse; + tMusic_Info[eOldState].bActive = qfalse; // // set new track to either full volume or fade up... // - tMusic_Info[eNewState].bActive = qtrue; - tMusic_Info[eNewState].iXFadeVolumeSeekTime = Sys_Milliseconds(); - tMusic_Info[eNewState].iXFadeVolumeSeekTo = 255; - tMusic_Info[eNewState].iXFadeVolume = bNewTrackStartsFullVolume ? 255 : 0; + tMusic_Info[eNewState].bActive = qtrue; + tMusic_Info[eNewState].iXFadeVolumeSeekTime = Sys_Milliseconds(); + tMusic_Info[eNewState].iXFadeVolumeSeekTo = 255; + tMusic_Info[eNewState].iXFadeVolume = bNewTrackStartsFullVolume ? 255 : 0; eMusic_StateActual = eNewState; + if (s_debugdynamic->integer) { + const char *psNewStateString = Music_BaseStateToString(eNewState, qtrue); + psNewStateString = psNewStateString ? psNewStateString : ""; - if (s_debugdynamic->integer) - { - const char *psNewStateString = Music_BaseStateToString( eNewState, qtrue ); - psNewStateString = psNewStateString?psNewStateString:""; - - Com_Printf( S_COLOR_MAGENTA "S_SwitchDynamicTracks( \"%s\" )\n", psNewStateString ); + Com_Printf(S_COLOR_MAGENTA "S_SwitchDynamicTracks( \"%s\" )\n", psNewStateString); } } @@ -4323,188 +3831,159 @@ static void S_SwitchDynamicTracks( MusicState_e eOldState, MusicState_e eNewStat // This either changes the music right now (copying track structures etc), or leaves the new state as pending // so it gets picked up by the general music player if in a transition that can't be overridden... // -static void S_SetDynamicMusicState( MusicState_e eNewState ) -{ - if (eMusic_StateRequest != eNewState) - { - eMusic_StateRequest = eNewState; +static void S_SetDynamicMusicState(MusicState_e eNewState) { + if (eMusic_StateRequest != eNewState) { + eMusic_StateRequest = eNewState; - if (s_debugdynamic->integer) - { - const char *psNewStateString = Music_BaseStateToString( eNewState, qtrue ); - psNewStateString = psNewStateString?psNewStateString:""; + if (s_debugdynamic->integer) { + const char *psNewStateString = Music_BaseStateToString(eNewState, qtrue); + psNewStateString = psNewStateString ? psNewStateString : ""; - Com_Printf( S_COLOR_MAGENTA "S_SetDynamicMusicState( Request: \"%s\" )\n", psNewStateString ); + Com_Printf(S_COLOR_MAGENTA "S_SetDynamicMusicState( Request: \"%s\" )\n", psNewStateString); } } } - -static void S_HandleDynamicMusicStateChange( void ) -{ - if (eMusic_StateRequest != eMusic_StateActual) - { +static void S_HandleDynamicMusicStateChange(void) { + if (eMusic_StateRequest != eMusic_StateActual) { // check whether or not the new request can be honoured, given what's currently playing... // - if (Music_StateCanBeInterrupted( eMusic_StateActual, eMusic_StateRequest )) - { - LP_MP3STREAM pMP3StreamActual = &tMusic_Info[ eMusic_StateActual ].chMP3_Bgrnd.MP3StreamHeader; + if (Music_StateCanBeInterrupted(eMusic_StateActual, eMusic_StateRequest)) { + LP_MP3STREAM pMP3StreamActual = &tMusic_Info[eMusic_StateActual].chMP3_Bgrnd.MP3StreamHeader; - switch (eMusic_StateRequest) + switch (eMusic_StateRequest) { + case eBGRNDTRACK_EXPLORE: // ... from action or silence { - case eBGRNDTRACK_EXPLORE: // ... from action or silence + switch (eMusic_StateActual) { + case eBGRNDTRACK_ACTION: // action->explore { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_ACTION: // action->explore - { - // find the transition track to play, and the entry point for explore when we get there, - // and also see if we're at a permitted exit point to switch at all... - // - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( pMP3StreamActual ) - MP3Stream_GetRemainingTimeInSeconds( pMP3StreamActual ); - - // supply: - // - // playing point in float seconds - // enum of track being queried - // - // get: - // - // enum of transition track to switch to - // float time of entry point of new track *after* transition - - MusicState_e eTransition; - float fNewTrackEntryTime = 0.0f; - if (Music_AllowedToTransition( fPlayingTimeElapsed, eBGRNDTRACK_ACTION, &eTransition, &fNewTrackEntryTime)) - { - S_SwitchDynamicTracks( eMusic_StateActual, eTransition, qfalse ); // qboolean bNewTrackStartsFullVolume + // find the transition track to play, and the entry point for explore when we get there, + // and also see if we're at a permitted exit point to switch at all... + // + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(pMP3StreamActual) - MP3Stream_GetRemainingTimeInSeconds(pMP3StreamActual); - tMusic_Info[eTransition].Rewind(); - tMusic_Info[eTransition].bTrackSwitchPending = qtrue; - tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; - tMusic_Info[eTransition].fTS_NewTime = fNewTrackEntryTime; - } - } - break; + // supply: + // + // playing point in float seconds + // enum of track being queried + // + // get: + // + // enum of transition track to switch to + // float time of entry point of new track *after* transition + + MusicState_e eTransition; + float fNewTrackEntryTime = 0.0f; + if (Music_AllowedToTransition(fPlayingTimeElapsed, eBGRNDTRACK_ACTION, &eTransition, &fNewTrackEntryTime)) { + S_SwitchDynamicTracks(eMusic_StateActual, eTransition, qfalse); // qboolean bNewTrackStartsFullVolume + + tMusic_Info[eTransition].Rewind(); + tMusic_Info[eTransition].bTrackSwitchPending = qtrue; + tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; + tMusic_Info[eTransition].fTS_NewTime = fNewTrackEntryTime; + } + } break; - case eBGRNDTRACK_SILENCE: // silence->explore - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume + case eBGRNDTRACK_SILENCE: // silence->explore + { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume -// float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); -// tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); - tMusic_Info[ eMusic_StateRequest ].Rewind(); - } - break; + // float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); + // tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); + tMusic_Info[eMusic_StateRequest].Rewind(); + } break; - default: // trying to transition from some state I wasn't aware you could transition from (shouldn't happen), so ignore - { - assert(0); - S_SwitchDynamicTracks( eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse ); // qboolean bNewTrackStartsFullVolume - } - break; - } + default: // trying to transition from some state I wasn't aware you could transition from (shouldn't happen), so ignore + { + assert(0); + S_SwitchDynamicTracks(eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse); // qboolean bNewTrackStartsFullVolume + } break; } - break; + } break; - case eBGRNDTRACK_SILENCE: // from explore or action + case eBGRNDTRACK_SILENCE: // from explore or action + { + switch (eMusic_StateActual) { + case eBGRNDTRACK_ACTION: // action->silence + case eBGRNDTRACK_EXPLORE: // explore->silence { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_ACTION: // action->silence - case eBGRNDTRACK_EXPLORE: // explore->silence - { - // find the transition track to play, and the entry point for explore when we get there, - // and also see if we're at a permitted exit point to switch at all... - // - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( pMP3StreamActual ) - MP3Stream_GetRemainingTimeInSeconds( pMP3StreamActual ); - - MusicState_e eTransition; - float fNewTrackEntryTime = 0.0f; - if (Music_AllowedToTransition( fPlayingTimeElapsed, eMusic_StateActual, &eTransition, &fNewTrackEntryTime)) - { - S_SwitchDynamicTracks( eMusic_StateActual, eTransition, qfalse ); // qboolean bNewTrackStartsFullVolume - - tMusic_Info[eTransition].Rewind(); - tMusic_Info[eTransition].bTrackSwitchPending = qtrue; - tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; - tMusic_Info[eTransition].fTS_NewTime = 0.0f; //fNewTrackEntryTime; irrelevant when switching to silence - } - } - break; + // find the transition track to play, and the entry point for explore when we get there, + // and also see if we're at a permitted exit point to switch at all... + // + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(pMP3StreamActual) - MP3Stream_GetRemainingTimeInSeconds(pMP3StreamActual); - default: // some unhandled type switching to silence - assert(0); // fall through since boss case just does silence->switch anyway + MusicState_e eTransition; + float fNewTrackEntryTime = 0.0f; + if (Music_AllowedToTransition(fPlayingTimeElapsed, eMusic_StateActual, &eTransition, &fNewTrackEntryTime)) { + S_SwitchDynamicTracks(eMusic_StateActual, eTransition, qfalse); // qboolean bNewTrackStartsFullVolume - case eBGRNDTRACK_BOSS: // boss->silence - { - S_SwitchDynamicTracks( eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse ); // qboolean bNewTrackStartsFullVolume - } - break; + tMusic_Info[eTransition].Rewind(); + tMusic_Info[eTransition].bTrackSwitchPending = qtrue; + tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; + tMusic_Info[eTransition].fTS_NewTime = 0.0f; // fNewTrackEntryTime; irrelevant when switching to silence } - } - break; + } break; - case eBGRNDTRACK_ACTION: // anything->action - { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_SILENCE: // silence->action - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume - tMusic_Info[ eMusic_StateRequest ].Rewind(); - } - break; + default: // some unhandled type switching to silence + assert(0); // fall through since boss case just does silence->switch anyway - default: // !silence->action - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qtrue ); // qboolean bNewTrackStartsFullVolume - float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); - tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); - } - break; - } + case eBGRNDTRACK_BOSS: // boss->silence + { + S_SwitchDynamicTracks(eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse); // qboolean bNewTrackStartsFullVolume + } break; } - break; + } break; - case eBGRNDTRACK_BOSS: + case eBGRNDTRACK_ACTION: // anything->action + { + switch (eMusic_StateActual) { + case eBGRNDTRACK_SILENCE: // silence->action { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume - // - // ( no need to fast forward or rewind, boss track is only entered into once, at start, and can't exit ) - // - } - break; + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume + tMusic_Info[eMusic_StateRequest].Rewind(); + } break; - case eBGRNDTRACK_DEATH: + default: // !silence->action { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qtrue ); // qboolean bNewTrackStartsFullVolume - // - // ( no need to fast forward or rewind, death track is only entered into once, at start, and can't exit or loop) - // + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qtrue); // qboolean bNewTrackStartsFullVolume + float fEntryTime = Music_GetRandomEntryTime(eMusic_StateRequest); + tMusic_Info[eMusic_StateRequest].SeekTo(fEntryTime); + } break; } - break; + } break; + + case eBGRNDTRACK_BOSS: { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume + // + // ( no need to fast forward or rewind, boss track is only entered into once, at start, and can't exit ) + // + } break; + + case eBGRNDTRACK_DEATH: { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qtrue); // qboolean bNewTrackStartsFullVolume + // + // ( no need to fast forward or rewind, death track is only entered into once, at start, and can't exit or loop) + // + } break; - default: assert(0); break; // unknown new mode request, so just ignore it + default: + assert(0); + break; // unknown new mode request, so just ignore it } } } } +static char gsIntroMusic[MAX_QPATH] = {0}; +static char gsLoopMusic[MAX_QPATH] = {0}; - -static char gsIntroMusic[MAX_QPATH]={0}; -static char gsLoopMusic [MAX_QPATH]={0}; - -void S_RestartMusic( void ) -{ - if (s_soundStarted && !s_soundMuted ) - { - //if (gsIntroMusic[0] || gsLoopMusic[0]) // dont test this anymore (but still *use* them), they're blank for JK2 dynamic-music levels anyway +void S_RestartMusic(void) { + if (s_soundStarted && !s_soundMuted) { + // if (gsIntroMusic[0] || gsLoopMusic[0]) // dont test this anymore (but still *use* them), they're blank for JK2 dynamic-music levels anyway { - MusicState_e ePrevState = eMusic_StateRequest; - S_StartBackgroundTrack( gsIntroMusic, gsLoopMusic, qfalse ); // ( default music start will set the state to EXPLORE ) - S_SetDynamicMusicState( ePrevState ); // restore to prev state + MusicState_e ePrevState = eMusic_StateRequest; + S_StartBackgroundTrack(gsIntroMusic, gsLoopMusic, qfalse); // ( default music start will set the state to EXPLORE ) + S_SetDynamicMusicState(ePrevState); // restore to prev state } } } @@ -4516,94 +3995,83 @@ void S_RestartMusic( void ) // to be honest, although the code still plays WAVs some of the file-check logic only works for MP3s, so if you ever want // to use WAV music you'll have to do some tweaking below (but I've got other things to do so it'll have to wait - Ste) // -void S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bCalledByCGameStart ) -{ +void S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bCalledByCGameStart) { bMusic_IsDynamic = qfalse; - if (!s_soundStarted) - { //we have no sound, so don't even bother trying + if (!s_soundStarted) { // we have no sound, so don't even bother trying return; } - if ( !intro ) { + if (!intro) { intro = ""; } - if ( !loop || !loop[0] ) { + if (!loop || !loop[0]) { loop = intro; } - if ( intro != gsIntroMusic ) { - Q_strncpyz( gsIntroMusic, intro, sizeof(gsIntroMusic) ); + if (intro != gsIntroMusic) { + Q_strncpyz(gsIntroMusic, intro, sizeof(gsIntroMusic)); } - if ( loop != gsLoopMusic ) { - Q_strncpyz( gsLoopMusic, loop, sizeof(gsLoopMusic) ); + if (loop != gsLoopMusic) { + Q_strncpyz(gsLoopMusic, loop, sizeof(gsLoopMusic)); } char sNameIntro[MAX_QPATH]; - char sNameLoop [MAX_QPATH]; - Q_strncpyz(sNameIntro, intro, sizeof(sNameIntro)); - Q_strncpyz(sNameLoop, loop, sizeof(sNameLoop)); + char sNameLoop[MAX_QPATH]; + Q_strncpyz(sNameIntro, intro, sizeof(sNameIntro)); + Q_strncpyz(sNameLoop, loop, sizeof(sNameLoop)); - COM_DefaultExtension( sNameIntro, sizeof( sNameIntro ), ".mp3" ); - COM_DefaultExtension( sNameLoop, sizeof( sNameLoop), ".mp3" ); + COM_DefaultExtension(sNameIntro, sizeof(sNameIntro), ".mp3"); + COM_DefaultExtension(sNameLoop, sizeof(sNameLoop), ".mp3"); // if dynamic music not allowed, then just stream the explore music instead of playing dynamic... // - if (!s_allowDynamicMusic->integer && Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) + if (!s_allowDynamicMusic->integer && Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) { - const char *psMusicName = Music_GetFileNameForState( eBGRNDTRACK_DATABEGIN ); - if (psMusicName && S_FileExists( psMusicName )) - { - Q_strncpyz(sNameIntro,psMusicName,sizeof(sNameIntro)); - Q_strncpyz(sNameLoop, psMusicName,sizeof(sNameLoop )); + const char *psMusicName = Music_GetFileNameForState(eBGRNDTRACK_DATABEGIN); + if (psMusicName && S_FileExists(psMusicName)) { + Q_strncpyz(sNameIntro, psMusicName, sizeof(sNameIntro)); + Q_strncpyz(sNameLoop, psMusicName, sizeof(sNameLoop)); } } // conceptually we always play the 'intro'[/sName] track, intro-to-loop transition is handled in UpdateBackGroundTrack(). // - if ( (strstr(sNameIntro,"/") && S_FileExists( sNameIntro )) ) // strstr() check avoids extra file-exists check at runtime if reverting from streamed music to dynamic since literal files all need at least one slash in their name (eg "music/blah") + if ((strstr(sNameIntro, "/") && S_FileExists(sNameIntro))) // strstr() check avoids extra file-exists check at runtime if reverting from streamed music to + // dynamic since literal files all need at least one slash in their name (eg "music/blah") { - const char *psLoopName = S_FileExists( sNameLoop ) ? sNameLoop : sNameIntro; + const char *psLoopName = S_FileExists(sNameLoop) ? sNameLoop : sNameIntro; Com_DPrintf("S_StartBackgroundTrack: Found/using non-dynamic music track '%s' (loop: '%s')\n", sNameIntro, psLoopName); - S_StartBackgroundTrack_Actual( &tMusic_Info[eBGRNDTRACK_NONDYNAMIC], bMusic_IsDynamic, sNameIntro, psLoopName ); - } - else - { - if (Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) + S_StartBackgroundTrack_Actual(&tMusic_Info[eBGRNDTRACK_NONDYNAMIC], bMusic_IsDynamic, sNameIntro, psLoopName); + } else { + if (Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) { extern const char *Music_GetLevelSetName(void); Q_strncpyz(sInfoOnly_CurrentDynamicMusicSet, Music_GetLevelSetName(), sizeof(sInfoOnly_CurrentDynamicMusicSet)); - for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) - { + for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) { qboolean bOk = qfalse; - const char *psMusicName = Music_GetFileNameForState( (MusicState_e) i); - if (psMusicName && (!Q_stricmp(tMusic_Info[i].sLoadedDataName, psMusicName) || S_FileExists( psMusicName )) ) - { - bOk = S_StartBackgroundTrack_Actual( &tMusic_Info[i], qtrue, psMusicName, loop ); + const char *psMusicName = Music_GetFileNameForState((MusicState_e)i); + if (psMusicName && (!Q_stricmp(tMusic_Info[i].sLoadedDataName, psMusicName) || S_FileExists(psMusicName))) { + bOk = S_StartBackgroundTrack_Actual(&tMusic_Info[i], qtrue, psMusicName, loop); } tMusic_Info[i].bExists = bOk; - if (!tMusic_Info[i].bExists) - { - FreeMusic( &tMusic_Info[i] ); + if (!tMusic_Info[i].bExists) { + FreeMusic(&tMusic_Info[i]); } } // // default all tracks to OFF first (and set any other vars) // - for (int i = 0; ibActive = qtrue; - pMusicInfo->iXFadeVolumeSeekTime= Sys_Milliseconds(); - pMusicInfo->iXFadeVolumeSeekTo = 255; - pMusicInfo->iXFadeVolume = 0; + pMusicInfo->bActive = qtrue; + pMusicInfo->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfo->iXFadeVolumeSeekTo = 255; + pMusicInfo->iXFadeVolume = 0; - //#ifdef _DEBUG - // float fRemaining = MP3Stream_GetPlayingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader); - //#endif - } - else - { - Com_Printf( S_COLOR_RED "Dynamic music did not have both 'action' and 'explore' versions, inhibiting...\n"); + //#ifdef _DEBUG + // float fRemaining = MP3Stream_GetPlayingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader); + //#endif + } else { + Com_Printf(S_COLOR_RED "Dynamic music did not have both 'action' and 'explore' versions, inhibiting...\n"); S_StopBackgroundTrack(); } - } - else - { - if (sNameIntro[0]!='.') // blank name with ".mp3" or whatever attached - no error print out + } else { + if (sNameIntro[0] != '.') // blank name with ".mp3" or whatever attached - no error print out { - Com_Printf( S_COLOR_RED "Unable to find music \"%s\" as explicit track or dynamic music entry!\n",sNameIntro); + Com_Printf(S_COLOR_RED "Unable to find music \"%s\" as explicit track or dynamic music entry!\n", sNameIntro); S_StopBackgroundTrack(); } } } - if (bCalledByCGameStart) - { + if (bCalledByCGameStart) { S_StopBackgroundTrack(); } } -void S_StopBackgroundTrack( void ) -{ - for (int i=0; ivalue; - if (bMusic_IsDynamic) - { + if (bMusic_IsDynamic) { // step xfade volume... // - if ( pMusicInfo->iXFadeVolume != pMusicInfo->iXFadeVolumeSeekTo ) - { + if (pMusicInfo->iXFadeVolume != pMusicInfo->iXFadeVolumeSeekTo) { int iFadeMillisecondsElapsed = Sys_Milliseconds() - pMusicInfo->iXFadeVolumeSeekTime; - if (iFadeMillisecondsElapsed > (fDYNAMIC_XFADE_SECONDS * 1000)) - { + if (iFadeMillisecondsElapsed > (fDYNAMIC_XFADE_SECONDS * 1000)) { pMusicInfo->iXFadeVolume = pMusicInfo->iXFadeVolumeSeekTo; - } - else - { - pMusicInfo->iXFadeVolume = (int) (255.0f * ((float)iFadeMillisecondsElapsed/(fDYNAMIC_XFADE_SECONDS * 1000.0f))); - if (pMusicInfo->iXFadeVolumeSeekTo == 0) // bleurgh + } else { + pMusicInfo->iXFadeVolume = (int)(255.0f * ((float)iFadeMillisecondsElapsed / (fDYNAMIC_XFADE_SECONDS * 1000.0f))); + if (pMusicInfo->iXFadeVolumeSeekTo == 0) // bleurgh pMusicInfo->iXFadeVolume = 255 - pMusicInfo->iXFadeVolume; } } @@ -4697,27 +4150,26 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea // normal sfx buffer painting, and allowing sufficient sliding room, even though the music file never goes back in time. // #define SIZEOF_RAW_BUFFER_FOR_MP3 4096 -#define RAWSIZE (pMusicInfo->bIsMP3?SIZEOF_RAW_BUFFER_FOR_MP3:sizeof(raw)) +#define RAWSIZE (pMusicInfo->bIsMP3 ? SIZEOF_RAW_BUFFER_FOR_MP3 : sizeof(raw)) - if ( !pMusicInfo->s_backgroundFile ) { + if (!pMusicInfo->s_backgroundFile) { return qfalse; } - pMusicInfo->fSmoothedOutVolume = (pMusicInfo->fSmoothedOutVolume + fMasterVol)/2.0f; -// OutputDebugString(va("%f\n",pMusicInfo->fSmoothedOutVolume)); + pMusicInfo->fSmoothedOutVolume = (pMusicInfo->fSmoothedOutVolume + fMasterVol) / 2.0f; + // OutputDebugString(va("%f\n",pMusicInfo->fSmoothedOutVolume)); // don't bother playing anything if musicvolume is 0 - if ( pMusicInfo->fSmoothedOutVolume <= 0 ) { + if (pMusicInfo->fSmoothedOutVolume <= 0) { return qfalse; } // see how many samples should be copied into the raw buffer - if ( s_rawend < s_soundtime ) { + if (s_rawend < s_soundtime) { s_rawend = s_soundtime; } - while ( s_rawend < s_soundtime + MAX_RAW_SAMPLES ) - { + while (s_rawend < s_soundtime + MAX_RAW_SAMPLES) { bufferSamples = MAX_RAW_SAMPLES - (s_rawend - s_soundtime); // decide how much data needs to be read from the file @@ -4729,34 +4181,30 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea } // don't try and read past the end of the file - if ( fileSamples > pMusicInfo->s_backgroundSamples ) { + if (fileSamples > pMusicInfo->s_backgroundSamples) { fileSamples = pMusicInfo->s_backgroundSamples; } // our max buffer size fileBytes = fileSamples * (pMusicInfo->s_backgroundInfo.width * pMusicInfo->s_backgroundInfo.channels); - if ((unsigned)fileBytes > RAWSIZE ) { + if ((unsigned)fileBytes > RAWSIZE) { fileBytes = RAWSIZE; fileSamples = fileBytes / (pMusicInfo->s_backgroundInfo.width * pMusicInfo->s_backgroundInfo.channels); } qboolean qbForceFinish = qfalse; - if (pMusicInfo->bIsMP3) - { - int iStartingSampleNum = pMusicInfo->chMP3_Bgrnd.thesfx->iSoundLengthInSamples - pMusicInfo->s_backgroundSamples; // but this IS relevant + if (pMusicInfo->bIsMP3) { + int iStartingSampleNum = pMusicInfo->chMP3_Bgrnd.thesfx->iSoundLengthInSamples - pMusicInfo->s_backgroundSamples; // but this IS relevant // Com_Printf(S_COLOR_YELLOW "Requesting MP3 samples: sample %d\n",iStartingSampleNum); - - if (pMusicInfo->s_backgroundFile == -1) - { + if (pMusicInfo->s_backgroundFile == -1) { // in-mem... // - qbForceFinish = (MP3Stream_GetSamples( &pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes/2, (short*) raw, qtrue ))?qfalse:qtrue; + qbForceFinish = (MP3Stream_GetSamples(&pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes / 2, (short *)raw, qtrue)) ? qfalse : qtrue; - //Com_Printf(S_COLOR_YELLOW "Music time remaining: %f seconds\n", MP3Stream_GetRemainingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader )); - } - else - { + // Com_Printf(S_COLOR_YELLOW "Music time remaining: %f seconds\n", MP3Stream_GetRemainingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader + // )); + } else { // streaming an MP3 file instead... (note that the 'fileBytes' request size isn't that relevant for MP3s, // since code here can't know how much the MP3 needs to decompress) // @@ -4764,67 +4212,56 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea pMusicInfo->chMP3_Bgrnd.MP3StreamHeader.pbSourceData = pbScrolledStreamData - pMusicInfo->chMP3_Bgrnd.MP3StreamHeader.iSourceReadIndex; - qbForceFinish = (MP3Stream_GetSamples( &pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes/2, (short*) raw, qtrue ))?qfalse:qtrue; + qbForceFinish = (MP3Stream_GetSamples(&pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes / 2, (short *)raw, qtrue)) ? qfalse : qtrue; } - } - else - { + } else { // streaming a WAV off disk... // - r = FS_Read( raw, fileBytes, pMusicInfo->s_backgroundFile ); - if ( r != fileBytes ) { - Com_Printf(S_COLOR_RED"StreamedRead failure on music track\n"); + r = FS_Read(raw, fileBytes, pMusicInfo->s_backgroundFile); + if (r != fileBytes) { + Com_Printf(S_COLOR_RED "StreamedRead failure on music track\n"); S_StopBackgroundTrack(); return qfalse; } // byte swap if needed (do NOT do for MP3 decoder, that has an internal big/little endian handler) // - S_ByteSwapRawSamples( fileSamples, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw ); + S_ByteSwapRawSamples(fileSamples, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw); } // add to raw buffer - S_RawSamples( fileSamples, pMusicInfo->s_backgroundInfo.rate, - pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw, pMusicInfo->fSmoothedOutVolume, - bFirstOrOnlyMusicTrack - ); + S_RawSamples(fileSamples, pMusicInfo->s_backgroundInfo.rate, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw, + pMusicInfo->fSmoothedOutVolume, bFirstOrOnlyMusicTrack); pMusicInfo->s_backgroundSamples -= fileSamples; - if ( !pMusicInfo->s_backgroundSamples || qbForceFinish ) - { + if (!pMusicInfo->s_backgroundSamples || qbForceFinish) { // loop the music, or play the next piece if we were on the intro... // (but not for dynamic, that can only be used for loop music) // - if (bMusic_IsDynamic) // needs special logic for this, different call + if (bMusic_IsDynamic) // needs special logic for this, different call { pMusicInfo->Rewind(); - } - else - { + } else { // for non-dynamic music we need to check if "sMusic_BackgroundLoop" is an actual filename, // or if it's a dynamic music specifier (which can't literally exist), in which case it should set // a return flag then exit... // - char sTestName[MAX_QPATH*2];// *2 so COM_DefaultExtension doesn't do an ERR_DROP if there was no space - // for an extension, since this is a "soft" test - Q_strncpyz( sTestName, sMusic_BackgroundLoop, sizeof(sTestName)); + char sTestName[MAX_QPATH * 2]; // *2 so COM_DefaultExtension doesn't do an ERR_DROP if there was no space + // for an extension, since this is a "soft" test + Q_strncpyz(sTestName, sMusic_BackgroundLoop, sizeof(sTestName)); COM_DefaultExtension(sTestName, sizeof(sTestName), ".mp3"); - if (S_FileExists( sTestName )) - { - S_StartBackgroundTrack_Actual( pMusicInfo, qfalse, sMusic_BackgroundLoop, sMusic_BackgroundLoop ); - } - else - { + if (S_FileExists(sTestName)) { + S_StartBackgroundTrack_Actual(pMusicInfo, qfalse, sMusic_BackgroundLoop, sMusic_BackgroundLoop); + } else { // proposed file doesn't exist, but this may be a dynamic track we're wanting to loop, // so exit with a special flag... // return qtrue; } } - if ( !pMusicInfo->s_backgroundFile ) - { - return qfalse; // loop failed to restart + if (!pMusicInfo->s_backgroundFile) { + return qfalse; // loop failed to restart } } } @@ -4835,15 +4272,12 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea return qfalse; } - // used to be just for dynamic, but now even non-dynamic music has to know whether it should be silent or not... // -static const char *S_Music_GetRequestedState(void) -{ +static const char *S_Music_GetRequestedState(void) { int iStringOffset = cl.gameState.stringOffsets[CS_DYNAMIC_MUSIC_STATE]; - if (iStringOffset) - { - const char *psCommand = cl.gameState.stringData+iStringOffset; + if (iStringOffset) { + const char *psCommand = cl.gameState.stringData + iStringOffset; return psCommand; } @@ -4851,235 +4285,189 @@ static const char *S_Music_GetRequestedState(void) return NULL; } - // scan the configstring to see if there's been a state-change requested... // (note that even if the state doesn't change it still gets here, so do a same-state check for applying) // // then go on to do transition handling etc... // -static void S_CheckDynamicMusicState(void) -{ +static void S_CheckDynamicMusicState(void) { const char *psCommand = S_Music_GetRequestedState(); - if (psCommand) - { + if (psCommand) { MusicState_e eNewState; - if ( !Q_stricmpn( psCommand, "silence", 7) ) - { + if (!Q_stricmpn(psCommand, "silence", 7)) { eNewState = eBGRNDTRACK_SILENCE; - } - else if ( !Q_stricmpn( psCommand, "action", 6) ) - { + } else if (!Q_stricmpn(psCommand, "action", 6)) { eNewState = eBGRNDTRACK_ACTION; - } - else if ( !Q_stricmpn( psCommand, "boss", 4) ) - { + } else if (!Q_stricmpn(psCommand, "boss", 4)) { // special case, boss music is optional and may not be defined... // - if (tMusic_Info[ eBGRNDTRACK_BOSS ].bExists) - { + if (tMusic_Info[eBGRNDTRACK_BOSS].bExists) { eNewState = eBGRNDTRACK_BOSS; - } - else - { + } else { // ( leave it playing current track ) // eNewState = eMusic_StateActual; } - } - else if ( !Q_stricmpn( psCommand, "death", 5) ) - { + } else if (!Q_stricmpn(psCommand, "death", 5)) { // special case, death music is optional and may not be defined... // - if (tMusic_Info[ eBGRNDTRACK_DEATH ].bExists) - { + if (tMusic_Info[eBGRNDTRACK_DEATH].bExists) { eNewState = eBGRNDTRACK_DEATH; - } - else - { + } else { // ( leave it playing current track, typically either boss or action ) // eNewState = eMusic_StateActual; } - } - else - { + } else { // seems a reasonable default... // eNewState = eBGRNDTRACK_EXPLORE; } - S_SetDynamicMusicState( eNewState ); + S_SetDynamicMusicState(eNewState); } S_HandleDynamicMusicStateChange(); } -static void S_UpdateBackgroundTrack( void ) -{ - if (bMusic_IsDynamic) - { - if (s_debugdynamic->integer == 2) - { +static void S_UpdateBackgroundTrack(void) { + if (bMusic_IsDynamic) { + if (s_debugdynamic->integer == 2) { DynamicMusicInfoPrint(); } S_CheckDynamicMusicState(); - if (eMusic_StateActual != eBGRNDTRACK_SILENCE) - { - MusicInfo_t *pMusicInfoCurrent = &tMusic_Info[ (eMusic_StateActual == eBGRNDTRACK_FADE)?eBGRNDTRACK_EXPLORE:eMusic_StateActual ]; - MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[ eBGRNDTRACK_FADE ]; + if (eMusic_StateActual != eBGRNDTRACK_SILENCE) { + MusicInfo_t *pMusicInfoCurrent = &tMusic_Info[(eMusic_StateActual == eBGRNDTRACK_FADE) ? eBGRNDTRACK_EXPLORE : eMusic_StateActual]; + MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[eBGRNDTRACK_FADE]; - if ( pMusicInfoCurrent->s_backgroundFile == -1) - { + if (pMusicInfoCurrent->s_backgroundFile == -1) { int iRawEnd = s_rawend; - S_UpdateBackgroundTrack_Actual( pMusicInfoCurrent, qtrue, s_musicVolume->value ); + S_UpdateBackgroundTrack_Actual(pMusicInfoCurrent, qtrue, s_musicVolume->value); - /* static int iPrevFrontVol = 0; - if (iPrevFrontVol != pMusicInfoCurrent->iXFadeVolume) - { - iPrevFrontVol = pMusicInfoCurrent->iXFadeVolume; - Com_Printf("front vol = %d\n",pMusicInfoCurrent->iXFadeVolume); - } - */ - if (pMusicInfoFadeOut->bActive) - { + /* static int iPrevFrontVol = 0; + if (iPrevFrontVol != pMusicInfoCurrent->iXFadeVolume) + { + iPrevFrontVol = pMusicInfoCurrent->iXFadeVolume; + Com_Printf("front vol = %d\n",pMusicInfoCurrent->iXFadeVolume); + } + */ + if (pMusicInfoFadeOut->bActive) { s_rawend = iRawEnd; - S_UpdateBackgroundTrack_Actual( pMusicInfoFadeOut, qfalse, s_musicVolume->value ); // inactive-checked internally - /* - static int iPrevFadeVol = 0; - if (iPrevFadeVol != pMusicInfoFadeOut->iXFadeVolume) - { - iPrevFadeVol = pMusicInfoFadeOut->iXFadeVolume; - Com_Printf("fade vol = %d\n",pMusicInfoFadeOut->iXFadeVolume); - } - */ + S_UpdateBackgroundTrack_Actual(pMusicInfoFadeOut, qfalse, s_musicVolume->value); // inactive-checked internally + /* + static int iPrevFadeVol = 0; + if (iPrevFadeVol != pMusicInfoFadeOut->iXFadeVolume) + { + iPrevFadeVol = pMusicInfoFadeOut->iXFadeVolume; + Com_Printf("fade vol = %d\n",pMusicInfoFadeOut->iXFadeVolume); + } + */ // // only do this for the fader!... // - if (pMusicInfoFadeOut->iXFadeVolume == 0) - { + if (pMusicInfoFadeOut->iXFadeVolume == 0) { pMusicInfoFadeOut->bActive = qfalse; } } - float fRemainingTimeInSeconds = MP3Stream_GetRemainingTimeInSeconds( &pMusicInfoCurrent->chMP3_Bgrnd.MP3StreamHeader ); + float fRemainingTimeInSeconds = MP3Stream_GetRemainingTimeInSeconds(&pMusicInfoCurrent->chMP3_Bgrnd.MP3StreamHeader); // Com_Printf("Remaining: %3.3f\n",fRemainingTimeInSeconds); - if ( fRemainingTimeInSeconds < fDYNAMIC_XFADE_SECONDS*2 ) - { + if (fRemainingTimeInSeconds < fDYNAMIC_XFADE_SECONDS * 2) { // now either loop current track, switch if finishing a transition, or stop if finished a death... // - if (pMusicInfoCurrent->bTrackSwitchPending) - { - pMusicInfoCurrent->bTrackSwitchPending = qfalse; // ack - S_SwitchDynamicTracks( eMusic_StateActual, pMusicInfoCurrent->eTS_NewState, qfalse); // qboolean bNewTrackStartsFullVolume - if (tMusic_Info[ pMusicInfoCurrent->eTS_NewState ].bExists) // don't do this if switching to silence + if (pMusicInfoCurrent->bTrackSwitchPending) { + pMusicInfoCurrent->bTrackSwitchPending = qfalse; // ack + S_SwitchDynamicTracks(eMusic_StateActual, pMusicInfoCurrent->eTS_NewState, qfalse); // qboolean bNewTrackStartsFullVolume + if (tMusic_Info[pMusicInfoCurrent->eTS_NewState].bExists) // don't do this if switching to silence { - tMusic_Info[ pMusicInfoCurrent->eTS_NewState ].SeekTo(pMusicInfoCurrent->fTS_NewTime); + tMusic_Info[pMusicInfoCurrent->eTS_NewState].SeekTo(pMusicInfoCurrent->fTS_NewTime); } - } - else - { + } else { // normal looping, so set rewind current track, set volume to 0 and fade up to full (unless death track playing, then stays quiet) // (while fader copy of end-section fades down) // // copy current track to fader... // - *pMusicInfoFadeOut = *pMusicInfoCurrent; // struct copy - pMusicInfoFadeOut->iXFadeVolumeSeekTime = Sys_Milliseconds(); - pMusicInfoFadeOut->iXFadeVolumeSeekTo = 0; + *pMusicInfoFadeOut = *pMusicInfoCurrent; // struct copy + pMusicInfoFadeOut->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfoFadeOut->iXFadeVolumeSeekTo = 0; // pMusicInfoCurrent->Rewind(); - pMusicInfoCurrent->iXFadeVolumeSeekTime = Sys_Milliseconds(); - pMusicInfoCurrent->iXFadeVolumeSeekTo = (eMusic_StateActual == eBGRNDTRACK_DEATH) ? 0: 255; - pMusicInfoCurrent->iXFadeVolume = 0; + pMusicInfoCurrent->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfoCurrent->iXFadeVolumeSeekTo = (eMusic_StateActual == eBGRNDTRACK_DEATH) ? 0 : 255; + pMusicInfoCurrent->iXFadeVolume = 0; } } } - } - else - { + } else { // special case, when foreground music is shut off but fader still running to fade off previous track... // - MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[ eBGRNDTRACK_FADE ]; - if (pMusicInfoFadeOut->bActive) - { - S_UpdateBackgroundTrack_Actual( pMusicInfoFadeOut, qtrue, s_musicVolume->value ); - if (pMusicInfoFadeOut->iXFadeVolume == 0) - { + MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[eBGRNDTRACK_FADE]; + if (pMusicInfoFadeOut->bActive) { + S_UpdateBackgroundTrack_Actual(pMusicInfoFadeOut, qtrue, s_musicVolume->value); + if (pMusicInfoFadeOut->iXFadeVolume == 0) { pMusicInfoFadeOut->bActive = qfalse; } } } - } - else - { + } else { // standard / non-dynamic one-track music... // - const char *psCommand = S_Music_GetRequestedState(); // special check just for "silence" case... - qboolean bShouldBeSilent = (qboolean)(psCommand && !Q_stricmp(psCommand,"silence")); + const char *psCommand = S_Music_GetRequestedState(); // special check just for "silence" case... + qboolean bShouldBeSilent = (qboolean)(psCommand && !Q_stricmp(psCommand, "silence")); float fDesiredVolume = bShouldBeSilent ? 0.0f : s_musicVolume->value; // // internal to this code is a volume-smoother... // qboolean bNewTrackDesired = S_UpdateBackgroundTrack_Actual(&tMusic_Info[eBGRNDTRACK_NONDYNAMIC], qtrue, fDesiredVolume); - if (bNewTrackDesired) - { - S_StartBackgroundTrack( sMusic_BackgroundLoop, sMusic_BackgroundLoop, qfalse ); + if (bNewTrackDesired) { + S_StartBackgroundTrack(sMusic_BackgroundLoop, sMusic_BackgroundLoop, qfalse); } } } - cvar_t *s_soundpoolmegs = NULL; - // currently passing in sfx as a param in case I want to do something with it later. // -byte *SND_malloc(int iSize, sfx_t *sfx) -{ - byte *pData = (byte *) Z_Malloc(iSize, TAG_SND_RAWDATA, qfalse); // don't bother asking for zeroed mem +byte *SND_malloc(int iSize, sfx_t *sfx) { + byte *pData = (byte *)Z_Malloc(iSize, TAG_SND_RAWDATA, qfalse); // don't bother asking for zeroed mem // if "s_soundpoolmegs" is < 0, then the -ve of the value is the maximum amount of sounds we're allowed to have loaded... // - if (s_soundpoolmegs && s_soundpoolmegs->integer < 0) - { - while ( (Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR)) > ((-s_soundpoolmegs->integer) * 1024 * 1024)) - { + if (s_soundpoolmegs && s_soundpoolmegs->integer < 0) { + while ((Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR)) > ((-s_soundpoolmegs->integer) * 1024 * 1024)) { int iBytesFreed = SND_FreeOldestSound(sfx); if (iBytesFreed == 0) - break; // sanity + break; // sanity } } return pData; } - // called once-only in EXE lifetime... // -void SND_setup() -{ +void SND_setup() { s_soundpoolmegs = Cvar_Get("s_soundpoolmegs", "25", CVAR_ARCHIVE); - if (Sys_LowPhysicalMemory() ) - { + if (Sys_LowPhysicalMemory()) { Cvar_Set("s_soundpoolmegs", "0"); } -// Com_Printf("Sound memory manager started\n"); + // Com_Printf("Sound memory manager started\n"); } - // ask how much mem an sfx has allocated... // -static int SND_MemUsed(sfx_t *sfx) -{ +static int SND_MemUsed(sfx_t *sfx) { int iSize = 0; - if (sfx->pSoundData){ + if (sfx->pSoundData) { iSize += Z_Size(sfx->pSoundData); } @@ -5094,22 +4482,18 @@ static int SND_MemUsed(sfx_t *sfx) // // now returns # bytes freed to help with z_malloc()-fail recovery // -static int SND_FreeSFXMem(sfx_t *sfx) -{ +static int SND_FreeSFXMem(sfx_t *sfx) { int iBytesFreed = 0; #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { alGetError(); - if (sfx->Buffer) - { + if (sfx->Buffer) { alDeleteBuffers(1, &(sfx->Buffer)); #ifdef _DEBUG #ifdef _MSC_VER char szString[256]; - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { sprintf(szString, "Failed to delete AL Buffer (%s) ... !\n", sfx->sSoundName); OutputDebugString(szString); } @@ -5118,70 +4502,60 @@ static int SND_FreeSFXMem(sfx_t *sfx) sfx->Buffer = 0; } - if (sfx->lipSyncData) - { - iBytesFreed += Z_Free( sfx->lipSyncData); - sfx->lipSyncData = NULL; + if (sfx->lipSyncData) { + iBytesFreed += Z_Free(sfx->lipSyncData); + sfx->lipSyncData = NULL; } } #endif - if ( sfx->pSoundData) { - iBytesFreed += Z_Free( sfx->pSoundData ); - sfx->pSoundData = NULL; + if (sfx->pSoundData) { + iBytesFreed += Z_Free(sfx->pSoundData); + sfx->pSoundData = NULL; } sfx->bInMemory = false; - if ( sfx->pMP3StreamHeader) { - iBytesFreed += Z_Free( sfx->pMP3StreamHeader ); - sfx->pMP3StreamHeader = NULL; + if (sfx->pMP3StreamHeader) { + iBytesFreed += Z_Free(sfx->pMP3StreamHeader); + sfx->pMP3StreamHeader = NULL; } return iBytesFreed; } -void S_DisplayFreeMemory() -{ - int iSoundDataSize = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); - int iMusicDataSize = Z_MemSize ( TAG_SND_DYNAMICMUSIC ); +void S_DisplayFreeMemory() { + int iSoundDataSize = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); + int iMusicDataSize = Z_MemSize(TAG_SND_DYNAMICMUSIC); - if (iSoundDataSize || iMusicDataSize) - { - Com_Printf("\n%.2fMB audio data: ( %.2fMB WAV/MP3 ) + ( %.2fMB Music )\n", - ((float)(iSoundDataSize+iMusicDataSize))/1024.0f/1024.0f, - ((float)(iSoundDataSize))/1024.0f/1024.0f, - ((float)(iMusicDataSize))/1024.0f/1024.0f - ); + if (iSoundDataSize || iMusicDataSize) { + Com_Printf("\n%.2fMB audio data: ( %.2fMB WAV/MP3 ) + ( %.2fMB Music )\n", ((float)(iSoundDataSize + iMusicDataSize)) / 1024.0f / 1024.0f, + ((float)(iSoundDataSize)) / 1024.0f / 1024.0f, ((float)(iMusicDataSize)) / 1024.0f / 1024.0f); // now count up amount used on this level... // iSoundDataSize = 0; - for (int i=1; iiLastLevelUsedOn == re.RegisterMedia_GetLevel()){ + if (sfx->iLastLevelUsedOn == re.RegisterMedia_GetLevel()) { iSoundDataSize += SND_MemUsed(sfx); } } - Com_Printf("%.2fMB in sfx_t alloc data (WAV/MP3) loaded this level\n",(float)iSoundDataSize/1024.0f/1024.0f); + Com_Printf("%.2fMB in sfx_t alloc data (WAV/MP3) loaded this level\n", (float)iSoundDataSize / 1024.0f / 1024.0f); } } -void SND_TouchSFX(sfx_t *sfx) -{ - sfx->iLastTimeUsed = Com_Milliseconds()+1; - sfx->iLastLevelUsedOn = re.RegisterMedia_GetLevel(); +void SND_TouchSFX(sfx_t *sfx) { + sfx->iLastTimeUsed = Com_Milliseconds() + 1; + sfx->iLastLevelUsedOn = re.RegisterMedia_GetLevel(); } - // currently this is only called during snd_shutdown or snd_restart // -void S_FreeAllSFXMem(void) -{ - for (int i=1 ; i < s_numSfx ; i++) // start @ 1 to skip freeing default sound +void S_FreeAllSFXMem(void) { + for (int i = 1; i < s_numSfx; i++) // start @ 1 to skip freeing default sound { SND_FreeSFXMem(&s_knownSfx[i]); } @@ -5191,36 +4565,30 @@ void S_FreeAllSFXMem(void) // // new param is so we can be usre of not freeing ourselves (without having to rely on possible uninitialised timers etc) // -int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) -{ +int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) { int iBytesFreed = 0; sfx_t *sfx; - int iOldest = Com_Milliseconds(); - int iUsed = 0; + int iOldest = Com_Milliseconds(); + int iUsed = 0; // start on 1 so we never dump the default sound... // - for (int i=1 ; i < s_numSfx ; i++) - { + for (int i = 1; i < s_numSfx; i++) { sfx = &s_knownSfx[i]; - if (sfx != pButNotThisOne) - { - if (!sfx->bDefaultSound && sfx->bInMemory && sfx->iLastTimeUsed < iOldest) - { + if (sfx != pButNotThisOne) { + if (!sfx->bDefaultSound && sfx->bInMemory && sfx->iLastTimeUsed < iOldest) { // new bit, we can't throw away any sfx_t struct in use by a channel, else the paint code will crash... // int iChannel = 0; - for (iChannel=0; iChannelthesfx == sfx) - break; // damn, being used + break; // damn, being used } - if (iChannel == MAX_CHANNELS) - { + if (iChannel == MAX_CHANNELS) { // this sfx_t struct wasn't used by any channels, so we can lose it... // iUsed = i; @@ -5230,9 +4598,8 @@ int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) } } - if (iUsed) - { - sfx = &s_knownSfx[ iUsed ]; + if (iUsed) { + sfx = &s_knownSfx[iUsed]; Com_DPrintf("SND_FreeOldestSound: freeing sound %s\n", sfx->sSoundName); @@ -5241,71 +4608,59 @@ int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) return iBytesFreed; } -int SND_FreeOldestSound(void) -{ - return SND_FreeOldestSound(NULL); // I had to add a void-arg version of this because of link issues, sigh +int SND_FreeOldestSound(void) { + return SND_FreeOldestSound(NULL); // I had to add a void-arg version of this because of link issues, sigh } - // just before we drop into a level, ensure the audio pool is under whatever the maximum // pool size is (but not by dropping out sounds used by the current level)... // // returns qtrue if at least one sound was dropped out, so z_malloc-fail recovery code knows if anything changed // extern qboolean gbInsideLoadSound; -qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */) -{ +qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */) { qboolean bAtLeastOneSoundDropped = qfalse; - Com_DPrintf( "SND_RegisterAudio_LevelLoadEnd():\n"); + Com_DPrintf("SND_RegisterAudio_LevelLoadEnd():\n"); - if (gbInsideLoadSound) - { - Com_DPrintf( "(Inside S_LoadSound (z_malloc recovery?), exiting...\n"); - } - else - { - int iLoadedAudioBytes = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); + if (gbInsideLoadSound) { + Com_DPrintf("(Inside S_LoadSound (z_malloc recovery?), exiting...\n"); + } else { + int iLoadedAudioBytes = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); const int iMaxAudioBytes = s_soundpoolmegs->integer * 1024 * 1024; - for (int i=1; i iMaxAudioBytes || bDeleteEverythingNotUsedThisLevel) ; i++) // i=1 so we never page out default sound + for (int i = 1; i < s_numSfx && (iLoadedAudioBytes > iMaxAudioBytes || bDeleteEverythingNotUsedThisLevel); + i++) // i=1 so we never page out default sound { sfx_t *sfx = &s_knownSfx[i]; - if (sfx->bInMemory) - { + if (sfx->bInMemory) { qboolean bDeleteThis = qfalse; - if (bDeleteEverythingNotUsedThisLevel) - { + if (bDeleteEverythingNotUsedThisLevel) { bDeleteThis = (qboolean)(sfx->iLastLevelUsedOn != re.RegisterMedia_GetLevel()); - } - else - { + } else { bDeleteThis = (qboolean)(sfx->iLastLevelUsedOn < re.RegisterMedia_GetLevel()); } - if (bDeleteThis) - { - Com_DPrintf( "Dumping sfx_t \"%s\"\n",sfx->sSoundName); + if (bDeleteThis) { + Com_DPrintf("Dumping sfx_t \"%s\"\n", sfx->sSoundName); - if (SND_FreeSFXMem(sfx)) - { + if (SND_FreeSFXMem(sfx)) { bAtLeastOneSoundDropped = qtrue; } - iLoadedAudioBytes = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); + iLoadedAudioBytes = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); } } } } - Com_DPrintf( "SND_RegisterAudio_LevelLoadEnd(): Ok\n"); + Com_DPrintf("SND_RegisterAudio_LevelLoadEnd(): Ok\n"); return bAtLeastOneSoundDropped; } - /****************************************************************************************************\ * * EAX Related @@ -5315,60 +4670,49 @@ qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLev /* Initialize the EAX Manager */ -void InitEAXManager() -{ +void InitEAXManager() { #ifdef USE_OPENAL LPEAXMANAGERCREATE lpEAXManagerCreateFn; EAXFXSLOTPROPERTIES FXSlotProp; - GUID Effect; - GUID FXSlotGuids[4]; + GUID Effect; + GUID FXSlotGuids[4]; int i; s_bEALFileLoaded = false; // Check for EAX 4.0 support - s_bEAX = alIsExtensionPresent((ALubyte*)"EAX4.0"); + s_bEAX = alIsExtensionPresent((ALubyte *)"EAX4.0"); - if (s_bEAX) - { + if (s_bEAX) { Com_Printf("Found EAX 4.0 native support\n"); - } - else - { + } else { // Support for EAXUnified (automatic translation of EAX 4.0 calls into EAX 3.0) - if ((alIsExtensionPresent((ALubyte*)"EAX3.0")) && (alIsExtensionPresent((ALubyte*)"EAX4.0Emulated"))) - { + if ((alIsExtensionPresent((ALubyte *)"EAX3.0")) && (alIsExtensionPresent((ALubyte *)"EAX4.0Emulated"))) { s_bEAX = AL_TRUE; Com_Printf("Found EAX 4.0 EMULATION support\n"); } } - if (s_bEAX) - { - s_eaxSet = (EAXSet)alGetProcAddress((ALubyte*)"EAXSet"); + if (s_bEAX) { + s_eaxSet = (EAXSet)alGetProcAddress((ALubyte *)"EAXSet"); if (s_eaxSet == NULL) s_bEAX = false; - s_eaxGet = (EAXGet)alGetProcAddress((ALubyte*)"EAXGet"); + s_eaxGet = (EAXGet)alGetProcAddress((ALubyte *)"EAXGet"); if (s_eaxGet == NULL) s_bEAX = false; } // If we have detected EAX support, then try and load the EAX Manager DLL - if (s_bEAX) - { + if (s_bEAX) { s_hEAXManInst = LoadLibrary("EAXMan.dll"); - if (s_hEAXManInst) - { + if (s_hEAXManInst) { lpEAXManagerCreateFn = (LPEAXMANAGERCREATE)GetProcAddress(s_hEAXManInst, "EaxManagerCreate"); - if (lpEAXManagerCreateFn) - { - if (lpEAXManagerCreateFn(&s_lpEAXManager)==EM_OK) - { + if (lpEAXManagerCreateFn) { + if (lpEAXManagerCreateFn(&s_lpEAXManager) == EM_OK) { // Configure our EAX 4.0 Effect Slots s_NumFXSlots = 0; - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].FXSlotGuid = EAX_NULL_GUID; s_FXSlotInfo[i].lEnvID = -1; } @@ -5384,22 +4728,16 @@ void InitEAXManager() FXSlotProp.lLock = EAXFXSLOT_LOCKED; FXSlotProp.ulFlags = EAXFXSLOTFLAGS_ENVIRONMENT; - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { - if (s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_ALLPARAMETERS, NULL, &FXSlotProp, sizeof(EAXFXSLOTPROPERTIES))==AL_NO_ERROR) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { + if (s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_ALLPARAMETERS, NULL, &FXSlotProp, sizeof(EAXFXSLOTPROPERTIES)) == AL_NO_ERROR) { // We can use this slot s_FXSlotInfo[s_NumFXSlots].FXSlotGuid = FXSlotGuids[i]; s_NumFXSlots++; - } - else - { + } else { // If this slot already contains a reverb, then we will use it anyway (Slot 0 will // be in this category). (It probably means that Slot 0 is locked) - if (s_eaxGet(&FXSlotGuids[i], EAXFXSLOT_LOADEFFECT, NULL, &Effect, sizeof(GUID))==AL_NO_ERROR) - { - if (Effect == EAX_REVERB_EFFECT) - { + if (s_eaxGet(&FXSlotGuids[i], EAXFXSLOT_LOADEFFECT, NULL, &Effect, sizeof(GUID)) == AL_NO_ERROR) { + if (Effect == EAX_REVERB_EFFECT) { // We can use this slot // Make sure the environment flag is on s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_FLAGS, NULL, &FXSlotProp.ulFlags, sizeof(unsigned long)); @@ -5417,8 +4755,7 @@ void InitEAXManager() } // If the EAXManager library was loaded (and there was a problem), then unload it - if (s_hEAXManInst) - { + if (s_hEAXManInst) { FreeLibrary(s_hEAXManInst); s_hEAXManInst = NULL; } @@ -5433,44 +4770,39 @@ void InitEAXManager() /* Release the EAX Manager */ -void ReleaseEAXManager() -{ +void ReleaseEAXManager() { #ifdef USE_OPENAL s_bEAX = false; UnloadEALFile(); - if (s_lpEAXManager) - { + if (s_lpEAXManager) { s_lpEAXManager->Release(); s_lpEAXManager = NULL; } - if (s_hEAXManInst) - { + if (s_hEAXManInst) { FreeLibrary(s_hEAXManInst); s_hEAXManInst = NULL; } #endif } - #ifdef USE_OPENAL /* Try to load the given .eal file */ -static bool LoadEALFile(char *szEALFilename) -{ - char *ealData = NULL; - HRESULT hr; - long i, j, lID, lEnvID; - EMPOINT EMPoint; - char szAperture[128]; - char szFullEALFilename[MAX_QPATH]; - long lNumInst, lNumInstA, lNumInstB; - bool bLoaded = false; - bool bValid = true; - int result; - char szString[256]; +static bool LoadEALFile(char *szEALFilename) { + char *ealData = NULL; + HRESULT hr; + long i, j, lID, lEnvID; + EMPOINT EMPoint; + char szAperture[128]; + char szFullEALFilename[MAX_QPATH]; + long lNumInst, lNumInstA, lNumInstB; + bool bLoaded = false; + bool bValid = true; + int result; + char szString[256]; if ((!s_lpEAXManager) || (!s_bEAX)) return false; @@ -5486,198 +4818,148 @@ static bool LoadEALFile(char *szEALFilename) // Load EAL file from PAK file result = FS_ReadFile(szEALFilename, (void **)&ealData); - if ((ealData) && (result != -1)) - { + if ((ealData) && (result != -1)) { hr = s_lpEAXManager->LoadDataSet(ealData, EMFLAG_LOADFROMMEMORY); // Unload EAL file - FS_FreeFile (ealData); + FS_FreeFile(ealData); - if (hr == EM_OK) - { + if (hr == EM_OK) { Com_DPrintf("Loaded %s by Quake loader\n", szEALFilename); bLoaded = true; } - } - else - { + } else { // Failed to load via Quake loader, try manually Com_sprintf(szFullEALFilename, MAX_QPATH, "base/%s", szEALFilename); - if (SUCCEEDED(s_lpEAXManager->LoadDataSet(szFullEALFilename, 0))) - { + if (SUCCEEDED(s_lpEAXManager->LoadDataSet(szFullEALFilename, 0))) { Com_DPrintf("Loaded %s by EAXManager\n", szEALFilename); bLoaded = true; } } - if (bLoaded) - { + if (bLoaded) { // For a valid eal file ... need to find 'Center' tag, record num of instances, and then find // the right number of instances of 'Aperture0a' and 'Aperture0b'. - if (s_lpEAXManager->GetSourceID("Center", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &s_lNumEnvironments)==EM_OK) - { - if (s_lpEAXManager->GetSourceID("Aperture0a", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - if (lNumInst == s_lNumEnvironments) - { - if (s_lpEAXManager->GetSourceID("Aperture0b", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - if (lNumInst == s_lNumEnvironments) - { + if (s_lpEAXManager->GetSourceID("Center", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &s_lNumEnvironments) == EM_OK) { + if (s_lpEAXManager->GetSourceID("Aperture0a", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + if (lNumInst == s_lNumEnvironments) { + if (s_lpEAXManager->GetSourceID("Aperture0b", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + if (lNumInst == s_lNumEnvironments) { // Check equal numbers of ApertureXa and ApertureXb i = 1; - while (true) - { + while (true) { lNumInstA = lNumInstB = 0; - sprintf(szAperture,"Aperture%da",i); - if ((s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) && (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstA)==EM_OK)) - { - sprintf(szAperture,"Aperture%db",i); + sprintf(szAperture, "Aperture%da", i); + if ((s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) && + (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstA) == EM_OK)) { + sprintf(szAperture, "Aperture%db", i); s_lpEAXManager->GetSourceID(szAperture, &lID); s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstB); - if (lNumInstA!=lNumInstB) - { - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL file - %d Aperture%da tags, and %d Aperture%db tags\n", lNumInstA, i, lNumInstB, i); + if (lNumInstA != lNumInstB) { + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL file - %d Aperture%da tags, and %d Aperture%db tags\n", lNumInstA, + i, lNumInstB, i); bValid = false; } - } - else - { + } else { break; } i++; } - if (bValid) - { + if (bValid) { s_lpEnvTable = (LPENVTABLE)Z_Malloc(s_lNumEnvironments * sizeof(ENVTABLE), TAG_NEWDEL, qtrue); } - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - expected %d instances of Aperture0b, found %d\n", s_lNumEnvironments, lNumInst); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0b' source-tag\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - found %d instances of the 'Center' tag, but only %d instances of 'Aperture0a'\n", s_lNumEnvironments, lNumInst); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0a' source-tag\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Center' source-tag\n"); - - - if (s_lpEnvTable) - { + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - expected %d instances of Aperture0b, found %d\n", s_lNumEnvironments, + lNumInst); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0b' source-tag\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - found %d instances of the 'Center' tag, but only %d instances of 'Aperture0a'\n", + s_lNumEnvironments, lNumInst); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0a' source-tag\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Center' source-tag\n"); + + if (s_lpEnvTable) { i = 0; - while (true) - { + while (true) { sprintf(szAperture, "Aperture%da", i); - if (s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - for (j = 0; j < s_lNumEnvironments; j++) - { + if (s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + for (j = 0; j < s_lNumEnvironments; j++) { s_lpEnvTable[j].bUsed = false; } - for (j = 0; j < lNumInst; j++) - { - if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint)==EM_OK) - { - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0)==EM_OK) - { - if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) - { + for (j = 0; j < lNumInst; j++) { + if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint) == EM_OK) { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0) == EM_OK) { + if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) { assert(s_lpEnvTable[lEnvID].ulNumApertures < 64); - if (!s_lpEnvTable[lEnvID].bUsed) - { + if (!s_lpEnvTable[lEnvID].bUsed) { s_lpEnvTable[lEnvID].bUsed = true; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0] = EMPoint.fX; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1] = EMPoint.fY; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2] = EMPoint.fZ; - } - else - { + } else { s_lpEAXManager->GetEnvironmentName(lEnvID, szString, 256); - Com_DPrintf( S_COLOR_YELLOW "Found more than one occurance of Aperture%da in %s sub-space\n", i, szString); - Com_DPrintf( S_COLOR_YELLOW "One tag at %.3f,%.3f,%.3f, other at %.3f,%.3f,%.3f\n", EMPoint.fX, EMPoint.fY, EMPoint.fZ, - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0], s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1], - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2]); + Com_DPrintf(S_COLOR_YELLOW "Found more than one occurance of Aperture%da in %s sub-space\n", i, szString); + Com_DPrintf(S_COLOR_YELLOW "One tag at %.3f,%.3f,%.3f, other at %.3f,%.3f,%.3f\n", EMPoint.fX, EMPoint.fY, + EMPoint.fZ, s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0], + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1], + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2]); bValid = false; } - } - else - { - if (lEnvID==-1) - Com_DPrintf( S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, EMPoint.fY, EMPoint.fZ); + } else { + if (lEnvID == -1) + Com_DPrintf(S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, + EMPoint.fY, EMPoint.fZ); else - Com_DPrintf( S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); + Com_DPrintf(S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); bValid = false; } } } } } - } - else - { + } else { break; } - if (bValid) - { + if (bValid) { sprintf(szAperture, "Aperture%db", i); - if (s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - for (j = 0; j < s_lNumEnvironments; j++) - { + if (s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + for (j = 0; j < s_lNumEnvironments; j++) { s_lpEnvTable[j].bUsed = false; } - for (j = 0; j < lNumInst; j++) - { - if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint)==EM_OK) - { - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0)==EM_OK) - { - if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) - { - if (!s_lpEnvTable[lEnvID].bUsed) - { + for (j = 0; j < lNumInst; j++) { + if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint) == EM_OK) { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0) == EM_OK) { + if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) { + if (!s_lpEnvTable[lEnvID].bUsed) { s_lpEnvTable[lEnvID].bUsed = true; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0] = EMPoint.fX; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1] = EMPoint.fY; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2] = EMPoint.fZ; - } - else - { + } else { s_lpEAXManager->GetEnvironmentName(lEnvID, szString, 256); - Com_DPrintf( S_COLOR_YELLOW "Found more than one occurance of Aperture%db in %s sub-space\n", i, szString); + Com_DPrintf(S_COLOR_YELLOW "Found more than one occurance of Aperture%db in %s sub-space\n", i, szString); bValid = false; } @@ -5685,25 +4967,27 @@ static bool LoadEALFile(char *szEALFilename) s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[0] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0]) / + 2; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[1] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1]) / + 2; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[2] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2]) / + 2; s_lpEnvTable[lEnvID].ulNumApertures++; assert(s_lpEnvTable[lEnvID].ulNumApertures < 64); - } - else - { - if (lEnvID==-1) - Com_DPrintf( S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, EMPoint.fY, EMPoint.fZ); + } else { + if (lEnvID == -1) + Com_DPrintf(S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, + EMPoint.fX, EMPoint.fY, EMPoint.fZ); else - Com_DPrintf( S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); + Com_DPrintf(S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); bValid = false; } } @@ -5713,10 +4997,9 @@ static bool LoadEALFile(char *szEALFilename) } } - if (!bValid) - { + if (!bValid) { // Found a problem - Com_DPrintf( S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); + Com_DPrintf(S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); Z_Free(s_lpEnvTable); s_lpEnvTable = NULL; @@ -5725,16 +5008,14 @@ static bool LoadEALFile(char *szEALFilename) i++; } - } - else - { - Com_DPrintf( S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); + } else { + Com_DPrintf(S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); } return true; } - Com_DPrintf( S_COLOR_YELLOW "Failed to load %s\n", szEALFilename); + Com_DPrintf(S_COLOR_YELLOW "Failed to load %s\n", szEALFilename); return false; } #endif @@ -5743,8 +5024,7 @@ static bool LoadEALFile(char *szEALFilename) /* Unload current .eal file */ -static void UnloadEALFile() -{ +static void UnloadEALFile() { HRESULT hr; if ((!s_lpEAXManager) || (!s_bEAX)) @@ -5753,8 +5033,7 @@ static void UnloadEALFile() hr = s_lpEAXManager->FreeDataSet(0); s_bEALFileLoaded = false; - if (s_lpEnvTable) - { + if (s_lpEnvTable) { Z_Free(s_lpEnvTable); s_lpEnvTable = NULL; } @@ -5767,8 +5046,7 @@ static void UnloadEALFile() /* Updates the current EAX Reverb setting, based on the location of the listener */ -static void UpdateEAXListener() -{ +static void UpdateEAXListener() { EMPOINT ListPos, ListOri; EMPOINT EMAperture; EMPOINT EMSourcePoint; @@ -5779,8 +5057,8 @@ static void UpdateEAXListener() bool bFound; long lVolume; long lCurTime; - channel_t *ch; - EAXVECTOR LR, LP1, LP2, Pan; + channel_t *ch; + EAXVECTOR LR, LP1, LP2, Pan; REVERBDATA ReverbData[3]; // Hardcoded to three (maximum no of reverbs) #ifdef DISPLAY_CLOSEST_ENVS char szEnvName[256]; @@ -5791,37 +5069,31 @@ static void UpdateEAXListener() lCurTime = timeGetTime(); - if ((s_lLastEnvUpdate + ENV_UPDATE_RATE) < lCurTime) - { + if ((s_lLastEnvUpdate + ENV_UPDATE_RATE) < lCurTime) { // Update closest reverbs s_lLastEnvUpdate = lCurTime; // No panning information in .eal file, or we only have 1 FX Slot to use, revert to legacy // behaviour (i.e only one reverb) - if ((!s_lpEnvTable) || (s_NumFXSlots==1)) - { + if ((!s_lpEnvTable) || (s_NumFXSlots == 1)) { // Convert Listener co-ordinate to left-handed system ListPos.fX = listener_pos[0]; ListPos.fY = listener_pos[1]; ListPos.fZ = -listener_pos[2]; - if (SUCCEEDED(s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION))) - { - if (lID != s_EnvironmentID) - { + if (SUCCEEDED(s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION))) { + if (lID != s_EnvironmentID) { #ifdef DISPLAY_CLOSEST_ENVS if (SUCCEEDED(s_lpEAXManager->GetEnvironmentName(lID, szEnvName, 256))) Com_Printf("Changing to '%s' zone !\n", szEnvName); #endif // Get EAX Preset info. - if (SUCCEEDED(s_lpEAXManager->GetEnvironmentAttributes(lID, &s_eaxLPCur))) - { + if (SUCCEEDED(s_lpEAXManager->GetEnvironmentAttributes(lID, &s_eaxLPCur))) { // Override s_eaxLPCur.flAirAbsorptionHF = 0.0f; // Set Environment - s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ALLPARAMETERS, - NULL, &s_eaxLPCur, sizeof(EAXREVERBPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ALLPARAMETERS, NULL, &s_eaxLPCur, sizeof(EAXREVERBPROPERTIES)); s_EnvironmentID = lID; } @@ -5842,12 +5114,10 @@ static void UpdateEAXListener() // Need to find closest s_NumFXSlots (including the Listener's slot) - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION)==EM_OK) - { - if (lID == -1) - { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION) == EM_OK) { + if (lID == -1) { // Found default environment -// Com_Printf( S_COLOR_YELLOW "Listener in default environment - ignoring zone !\n"); + // Com_Printf( S_COLOR_YELLOW "Listener in default environment - ignoring zone !\n"); return; } @@ -5863,24 +5133,20 @@ static void UpdateEAXListener() ReverbData[2].lApertureNum = -1; ReverbData[2].flDist = 0.0f; - for (i = 0; i < s_lNumEnvironments; i++) - { + for (i = 0; i < s_lNumEnvironments; i++) { // Ignore Environment id lID as this one will always be used - if (i != lID) - { + if (i != lID) { flNearest = FLT_MAX; - lApertureNum = 0; //shut up compile warning + lApertureNum = 0; // shut up compile warning - for (j = 0; j < s_lpEnvTable[i].ulNumApertures; j++) - { + for (j = 0; j < s_lpEnvTable[i].ulNumApertures; j++) { EMAperture.fX = s_lpEnvTable[i].Aperture[j].vCenter[0]; EMAperture.fY = s_lpEnvTable[i].Aperture[j].vCenter[1]; EMAperture.fZ = s_lpEnvTable[i].Aperture[j].vCenter[2]; flDistance = CalcDistance(EMAperture, ListPos); - if (flDistance < flNearest) - { + if (flDistance < flNearest) { flNearest = flDistance; lApertureNum = j; } @@ -5888,17 +5154,13 @@ static void UpdateEAXListener() // Now have closest point for this Environment - see if this is closer than any others - if (flNearest < ReverbData[1].flDist) - { - if (flNearest < ReverbData[0].flDist) - { + if (flNearest < ReverbData[1].flDist) { + if (flNearest < ReverbData[0].flDist) { ReverbData[1] = ReverbData[0]; ReverbData[0].flDist = flNearest; ReverbData[0].lApertureNum = lApertureNum; ReverbData[0].lEnvID = i; - } - else - { + } else { ReverbData[1].flDist = flNearest; ReverbData[1].lApertureNum = lApertureNum; ReverbData[1].lEnvID = i; @@ -5906,7 +5168,6 @@ static void UpdateEAXListener() } } } - } #ifdef DISPLAY_CLOSEST_ENVS @@ -5918,31 +5179,26 @@ static void UpdateEAXListener() s_lpEAXManager->GetEnvironmentName(ReverbData[1].lEnvID, szEnvName2, 256); s_lpEAXManager->GetEnvironmentName(ReverbData[2].lEnvID, szEnvName3, 256); - Com_Printf("Closest zones are %s, %s (Listener in %s)\n", szEnvName1, - szEnvName2, szEnvName3); + Com_Printf("Closest zones are %s, %s (Listener in %s)\n", szEnvName1, szEnvName2, szEnvName3); #endif // Mute any reverbs no longer required ... - for (i = 0; i < s_NumFXSlots; i++) - { - if ((s_FXSlotInfo[i].lEnvID != -1) && (s_FXSlotInfo[i].lEnvID != ReverbData[0].lEnvID) && (s_FXSlotInfo[i].lEnvID != ReverbData[1].lEnvID) - && (s_FXSlotInfo[i].lEnvID != ReverbData[2].lEnvID)) - { + for (i = 0; i < s_NumFXSlots; i++) { + if ((s_FXSlotInfo[i].lEnvID != -1) && (s_FXSlotInfo[i].lEnvID != ReverbData[0].lEnvID) && (s_FXSlotInfo[i].lEnvID != ReverbData[1].lEnvID) && + (s_FXSlotInfo[i].lEnvID != ReverbData[2].lEnvID)) { // This environment is no longer needed // Mute it lVolume = -10000; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long)) != AL_NO_ERROR) OutputDebugString("Failed to Mute FX Slot\n"); // If any source is sending to this Slot ID then we need to stop them sending to the slot - for (j = 1; j < s_numChannels; j++) - { - if (s_channels[j].lSlotID == i) - { - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, s_channels[j].alSource, (void*)&EAX_NULL_GUID, sizeof(GUID))!=AL_NO_ERROR) - { + for (j = 1; j < s_numChannels; j++) { + if (s_channels[j].lSlotID == i) { + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, s_channels[j].alSource, (void *)&EAX_NULL_GUID, sizeof(GUID)) != + AL_NO_ERROR) { OutputDebugString("Failed to set Source ActiveFXSlotID to NULL\n"); } @@ -5951,44 +5207,35 @@ static void UpdateEAXListener() } assert(s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0); - if (s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0) - { + if (s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0) { s_lpEnvTable[s_FXSlotInfo[i].lEnvID].lFXSlotID = -1; } s_FXSlotInfo[i].lEnvID = -1; } } - // Make sure all the reverbs we want are being rendered, if not, find an empty slot // and apply appropriate reverb settings - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { bFound = false; - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == ReverbData[j].lEnvID) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == ReverbData[j].lEnvID) { bFound = true; break; } } - if (!bFound) - { + if (!bFound) { // Find the first available slot and use that one - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == -1) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == -1) { // Found slot // load reverb here // Retrieve reverb properties from EAX Manager - if (s_lpEAXManager->GetEnvironmentAttributes(ReverbData[j].lEnvID, &Reverb)==EM_OK) - { + if (s_lpEAXManager->GetEnvironmentAttributes(ReverbData[j].lEnvID, &Reverb) == EM_OK) { // Override Air Absorption HF Reverb.flAirAbsorptionHF = 0.0f; @@ -5996,44 +5243,36 @@ static void UpdateEAXListener() // See if any Sources are in this environment, if they are, enable their sends ch = s_channels + 1; - for (k = 1; k < s_numChannels; k++, ch++) - { - if (ch->fixed_origin) - { + for (k = 1; k < s_numChannels; k++, ch++) { + if (ch->fixed_origin) { // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z EMSourcePoint.fX = ch->origin[0]; EMSourcePoint.fY = ch->origin[2]; EMSourcePoint.fZ = ch->origin[1]; - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { // Source at same position as listener // Probably won't be any Occlusion / Obstruction effect -- unless the listener is underwater // Converting from Open AL -> DS3D (for EAGLE) ... invert Z EMSourcePoint.fX = listener_pos[0]; EMSourcePoint.fY = listener_pos[1]; EMSourcePoint.fZ = -listener_pos[2]; - } - else - { + } else { // Get position of Entity // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z - EMSourcePoint.fX = loopSounds[ ch->entnum ].origin[0]; - EMSourcePoint.fY = loopSounds[ ch->entnum ].origin[2]; - EMSourcePoint.fZ = loopSounds[ ch->entnum ].origin[1]; + EMSourcePoint.fX = loopSounds[ch->entnum].origin[0]; + EMSourcePoint.fY = loopSounds[ch->entnum].origin[2]; + EMSourcePoint.fZ = loopSounds[ch->entnum].origin[1]; } } // Get Source Environment point - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0)!=EM_OK) + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0) != EM_OK) OutputDebugString("Failed to get environment zone for Source\n"); - if (lSourceID == i) - { - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, (void*)&(s_FXSlotInfo[i].FXSlotGuid), sizeof(GUID))!=AL_NO_ERROR) - { + if (lSourceID == i) { + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, (void *)&(s_FXSlotInfo[i].FXSlotGuid), + sizeof(GUID)) != AL_NO_ERROR) { OutputDebugString("Failed to set Source ActiveFXSlotID to new environment\n"); } @@ -6042,8 +5281,7 @@ static void UpdateEAXListener() } assert(ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0); - if (ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0) - { + if (ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0) { s_FXSlotInfo[i].lEnvID = ReverbData[j].lEnvID; s_lpEnvTable[ReverbData[j].lEnvID].lFXSlotID = i; } @@ -6056,15 +5294,14 @@ static void UpdateEAXListener() } // Make sure Primary FX Slot ID is set correctly - if (s_EnvironmentID != ReverbData[2].lEnvID) - { - s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, &(s_FXSlotInfo[s_lpEnvTable[ReverbData[2].lEnvID].lFXSlotID].FXSlotGuid), sizeof(GUID)); + if (s_EnvironmentID != ReverbData[2].lEnvID) { + s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, &(s_FXSlotInfo[s_lpEnvTable[ReverbData[2].lEnvID].lFXSlotID].FXSlotGuid), + sizeof(GUID)); s_EnvironmentID = ReverbData[2].lEnvID; } // Have right reverbs loaded ... now to pan them and adjust volume - // We need to rotate the vector from the Listener to the reverb Aperture by minus the listener // orientation @@ -6082,27 +5319,23 @@ static void UpdateEAXListener() float flSin = (float)sin(-flTheta); float flCos = (float)cos(-flTheta); - for (i = 0; i < Q_min(s_NumFXSlots,s_lNumEnvironments); i++) - { - if (s_FXSlotInfo[i].lEnvID == s_EnvironmentID) - { + for (i = 0; i < Q_min(s_NumFXSlots, s_lNumEnvironments); i++) { + if (s_FXSlotInfo[i].lEnvID == s_EnvironmentID) { // Listener's environment // Find the closest Aperture in *this* environment flNearest = FLT_MAX; - lApertureNum = 0; //shut up compile warning + lApertureNum = 0; // shut up compile warning - for (j = 0; j < s_lpEnvTable[s_EnvironmentID].ulNumApertures; j++) - { + for (j = 0; j < s_lpEnvTable[s_EnvironmentID].ulNumApertures; j++) { EMAperture.fX = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[0]; EMAperture.fY = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[1]; EMAperture.fZ = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[2]; flDistance = CalcDistance(EMAperture, ListPos); - if (flDistance < flNearest) - { + if (flDistance < flNearest) { flNearest = flDistance; lApertureNum = j; } @@ -6120,14 +5353,12 @@ static void UpdateEAXListener() Normalize(&Pan); - // Adjust magnitude ... // Magnitude is based on the angle subtended by the aperture, so compute the angle between // the vector from the Listener to Pos1 of the aperture, and the vector from the // Listener to Pos2 of the aperture. - LP1.x = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[0] - ListPos.fX; LP1.y = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[1] - ListPos.fY; LP1.z = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[2] - ListPos.fZ; @@ -6142,21 +5373,19 @@ static void UpdateEAXListener() float flGamma = acos((LP1.x * LP2.x) + (LP1.y * LP2.y) + (LP1.z * LP2.z)); // We want opposite magnitude (because we are 'in' this environment) - float flMagnitude = 1.0f - ((2.0f * (float)sin(flGamma/2.0f)) / flGamma); + float flMagnitude = 1.0f - ((2.0f * (float)sin(flGamma / 2.0f)) / flGamma); // Negative (because pan should be 180 degrees) Pan.x *= -flMagnitude; Pan.y *= -flMagnitude; Pan.z *= -flMagnitude; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) OutputDebugString("Failed to set Listener Reverb Pan\n"); - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) OutputDebugString("Failed to set Listener Reflections Pan\n"); - } - else - { + } else { // Find out which Reverb this is if (ReverbData[0].lEnvID == s_FXSlotInfo[i].lEnvID) k = 0; @@ -6181,7 +5410,6 @@ static void UpdateEAXListener() // the vector from the Listener to Pos1 of the aperture, and the vector from the // Listener to Pos2 of the aperture. - LP1.x = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[0] - ListPos.fX; LP1.y = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[1] - ListPos.fY; LP1.z = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[2] - ListPos.fZ; @@ -6194,24 +5422,23 @@ static void UpdateEAXListener() Normalize(&LP2); float flGamma = acos((LP1.x * LP2.x) + (LP1.y * LP2.y) + (LP1.z * LP2.z)); - float flMagnitude = (2.0f * (float)sin(flGamma/2.0f)) / flGamma; + float flMagnitude = (2.0f * (float)sin(flGamma / 2.0f)) / flGamma; Pan.x *= flMagnitude; Pan.y *= flMagnitude; Pan.z *= flMagnitude; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) OutputDebugString("Failed to set Reverb Pan\n"); - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) OutputDebugString("Failed to set Reflections Pan\n"); } } lVolume = 0; - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long))!=AL_NO_ERROR) + for (i = 0; i < s_NumFXSlots; i++) { + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long)) != AL_NO_ERROR) OutputDebugString("Failed to set FX Slot Volume to 0\n"); } } @@ -6222,8 +5449,7 @@ static void UpdateEAXListener() /* Updates the EAX Buffer related effects on the given Source */ -static void UpdateEAXBuffer(channel_t *ch) -{ +static void UpdateEAXBuffer(channel_t *ch) { HRESULT hr; EMPOINT EMSourcePoint; EMPOINT EMVirtualSourcePoint; @@ -6242,36 +5468,27 @@ static void UpdateEAXBuffer(channel_t *ch) eaxOCProp.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO; // Convert Source co-ordinate to left-handed system - if (ch->fixed_origin) - { + if (ch->fixed_origin) { // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z EMSourcePoint.fX = ch->origin[0]; EMSourcePoint.fY = ch->origin[2]; EMSourcePoint.fZ = ch->origin[1]; - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { // Source at same position as listener // Probably won't be any Occlusion / Obstruction effect -- unless the listener is underwater // Converting from Open AL -> DS3D (for EAGLE) ... invert Z EMSourcePoint.fX = listener_pos[0]; EMSourcePoint.fY = listener_pos[1]; EMSourcePoint.fZ = -listener_pos[2]; - } - else - { + } else { // Get position of Entity // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z - if (ch->bLooping) - { - EMSourcePoint.fX = loopSounds[ ch->entnum ].origin[0]; - EMSourcePoint.fY = loopSounds[ ch->entnum ].origin[2]; - EMSourcePoint.fZ = loopSounds[ ch->entnum ].origin[1]; - } - else - { + if (ch->bLooping) { + EMSourcePoint.fX = loopSounds[ch->entnum].origin[0]; + EMSourcePoint.fY = loopSounds[ch->entnum].origin[2]; + EMSourcePoint.fZ = loopSounds[ch->entnum].origin[1]; + } else { EMSourcePoint.fX = s_entityPosition[ch->entnum][0]; EMSourcePoint.fY = s_entityPosition[ch->entnum][2]; EMSourcePoint.fZ = s_entityPosition[ch->entnum][1]; @@ -6282,18 +5499,14 @@ static void UpdateEAXBuffer(channel_t *ch) long lExclusion; // Just determine what environment the source is in - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0)==EM_OK) - { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0) == EM_OK) { // See if a Slot is rendering this environment - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == lSourceID) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == lSourceID) { // If the Source is not sending to this slot, then enable the send now - if (ch->lSlotID != i) - { + if (ch->lSlotID != i) { // Set this - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &s_FXSlotInfo[i].FXSlotGuid, sizeof(GUID))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &s_FXSlotInfo[i].FXSlotGuid, sizeof(GUID)) != AL_NO_ERROR) OutputDebugString("UpdateEAXBuffer = failed to set ActiveFXSlotID\n"); ch->lSlotID = i; @@ -6302,28 +5515,22 @@ static void UpdateEAXBuffer(channel_t *ch) break; } } - } - else - { + } else { OutputDebugString("UpdateEAXBuffer::Failed to get Source environment zone\n"); } // Add some Exclusion to sounds that are not located in the Listener's environment - if (s_FXSlotInfo[ch->lSlotID].lEnvID == s_EnvironmentID) - { + if (s_FXSlotInfo[ch->lSlotID].lEnvID == s_EnvironmentID) { lExclusion = 0; - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long)) != AL_NO_ERROR) OutputDebugString("UpdateEAXBuffer : Failed to set exclusion to 0\n"); - } - else - { + } else { lExclusion = -1000; - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long)) != AL_NO_ERROR) OutputDebugString("UpdateEAXBuffer : Failed to set exclusion to -1000\n"); } - if ((ch->entchannel == CHAN_VOICE) || (ch->entchannel == CHAN_VOICE_ATTEN) || (ch->entchannel == CHAN_VOICE_GLOBAL)) - { + if ((ch->entchannel == CHAN_VOICE) || (ch->entchannel == CHAN_VOICE_ATTEN) || (ch->entchannel == CHAN_VOICE_GLOBAL)) { // Remove any Occlusion + Obstruction eaxOBProp.lObstruction = EAXSOURCE_DEFAULTOBSTRUCTION; eaxOBProp.flObstructionLFRatio = EAXSOURCE_DEFAULTOBSTRUCTIONLFRATIO; @@ -6333,33 +5540,23 @@ static void UpdateEAXBuffer(channel_t *ch) eaxOCProp.flOcclusionRoomRatio = EAXSOURCE_DEFAULTOCCLUSIONROOMRATIO; eaxOCProp.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO; - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, - ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); - } - else - { + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + } else { // Check for Occlusion + Obstruction - hr = s_lpEAXManager->GetSourceDynamicAttributes(0, &EMSourcePoint, &eaxOBProp.lObstruction, &eaxOBProp.flObstructionLFRatio, - &eaxOCProp.lOcclusion, &eaxOCProp.flOcclusionLFRatio, &eaxOCProp.flOcclusionRoomRatio, &EMVirtualSourcePoint, 0); - if (hr == EM_OK) - { + hr = s_lpEAXManager->GetSourceDynamicAttributes(0, &EMSourcePoint, &eaxOBProp.lObstruction, &eaxOBProp.flObstructionLFRatio, &eaxOCProp.lOcclusion, + &eaxOCProp.flOcclusionLFRatio, &eaxOCProp.flOcclusionRoomRatio, &EMVirtualSourcePoint, 0); + if (hr == EM_OK) { // Set EAX effect ! - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, - ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); } } return; } -float CalcDistance(EMPOINT A, EMPOINT B) -{ - return (float)sqrt(sqr(A.fX - B.fX)+sqr(A.fY - B.fY) + sqr(A.fZ - B.fZ)); -} +float CalcDistance(EMPOINT A, EMPOINT B) { return (float)sqrt(sqr(A.fX - B.fX) + sqr(A.fY - B.fY) + sqr(A.fZ - B.fZ)); } #endif diff --git a/code/client/snd_mem.cpp b/code/client/snd_mem.cpp index 97b4f4b4d1..37e6b5413a 100644 --- a/code/client/snd_mem.cpp +++ b/code/client/snd_mem.cpp @@ -42,84 +42,74 @@ WAV loading =============================================================================== */ -byte *data_p; -byte *iff_end; -byte *last_chunk; -byte *iff_data; -int iff_chunk_len; -extern sfx_t s_knownSfx[]; -extern int s_numSfx; - -extern cvar_t *s_lip_threshold_1; -extern cvar_t *s_lip_threshold_2; -extern cvar_t *s_lip_threshold_3; -extern cvar_t *s_lip_threshold_4; - -short GetLittleShort(void) -{ +byte *data_p; +byte *iff_end; +byte *last_chunk; +byte *iff_data; +int iff_chunk_len; +extern sfx_t s_knownSfx[]; +extern int s_numSfx; + +extern cvar_t *s_lip_threshold_1; +extern cvar_t *s_lip_threshold_2; +extern cvar_t *s_lip_threshold_3; +extern cvar_t *s_lip_threshold_4; + +short GetLittleShort(void) { short val = 0; val = *data_p; - val = (short)(val + (*(data_p+1)<<8)); + val = (short)(val + (*(data_p + 1) << 8)); data_p += 2; return val; } -int GetLittleLong(void) -{ +int GetLittleLong(void) { int val = 0; val = *data_p; - val = val + (*(data_p+1)<<8); - val = val + (*(data_p+2)<<16); - val = val + (*(data_p+3)<<24); + val = val + (*(data_p + 1) << 8); + val = val + (*(data_p + 2) << 16); + val = val + (*(data_p + 3) << 24); data_p += 4; return val; } -void FindNextChunk(const char *name) -{ - while (1) - { - data_p=last_chunk; +void FindNextChunk(const char *name) { + while (1) { + data_p = last_chunk; - if (data_p >= iff_end) - { // didn't find the chunk + if (data_p >= iff_end) { // didn't find the chunk data_p = NULL; return; } data_p += 4; iff_chunk_len = GetLittleLong(); - if (iff_chunk_len < 0) - { + if (iff_chunk_len < 0) { data_p = NULL; return; } data_p -= 8; - last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 ); + last_chunk = data_p + 8 + ((iff_chunk_len + 1) & ~1); if (!strncmp((char *)data_p, name, 4)) return; } } -void FindChunk(const char *name) -{ +void FindChunk(const char *name) { last_chunk = iff_data; - FindNextChunk (name); + FindNextChunk(name); } - -void DumpChunks(void) -{ - char str[5]; +void DumpChunks(void) { + char str[5]; str[4] = 0; - data_p=iff_data; - do - { - memcpy (str, data_p, 4); + data_p = iff_data; + do { + memcpy(str, data_p, 4); data_p += 4; iff_chunk_len = GetLittleLong(); - Com_Printf ("0x%x : %s (%d)\n", (intptr_t)(data_p - 4), str, iff_chunk_len); + Com_Printf("0x%x : %s (%d)\n", (intptr_t)(data_p - 4), str, iff_chunk_len); data_p += (iff_chunk_len + 1) & ~1; } while (data_p < iff_end); } @@ -129,12 +119,11 @@ void DumpChunks(void) GetWavinfo ============ */ -wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) -{ - wavinfo_t info; - int samples; +wavinfo_t GetWavinfo(const char *name, byte *wav, int wavlength) { + wavinfo_t info; + int samples; - memset (&info, 0, sizeof(info)); + memset(&info, 0, sizeof(info)); if (!wav) return info; @@ -142,21 +131,19 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) iff_data = wav; iff_end = wav + wavlength; -// find "RIFF" chunk + // find "RIFF" chunk FindChunk("RIFF"); - if (!(data_p && !strncmp((char *)data_p+8, "WAVE", 4))) - { + if (!(data_p && !strncmp((char *)data_p + 8, "WAVE", 4))) { Com_Printf("Missing RIFF/WAVE chunks\n"); return info; } -// get "fmt " chunk + // get "fmt " chunk iff_data = data_p + 12; -// DumpChunks (); + // DumpChunks (); FindChunk("fmt "); - if (!data_p) - { + if (!data_p) { Com_Printf("Missing fmt chunk\n"); return info; } @@ -164,42 +151,35 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) info.format = GetLittleShort(); info.channels = GetLittleShort(); info.rate = GetLittleLong(); - data_p += 4+2; + data_p += 4 + 2; info.width = GetLittleShort() / 8; - if (info.format != 1) - { + if (info.format != 1) { Com_Printf("Microsoft PCM format only\n"); return info; } - -// find data chunk + // find data chunk FindChunk("data"); - if (!data_p) - { + if (!data_p) { Com_Printf("Missing data chunk\n"); return info; } data_p += 4; - samples = GetLittleLong () / info.width; + samples = GetLittleLong() / info.width; - if (info.samples) - { + if (info.samples) { if (samples < info.samples) - Com_Error (ERR_DROP, "Sound %s has a bad loop length", name); - } - else + Com_Error(ERR_DROP, "Sound %s has a bad loop length", name); + } else info.samples = samples; info.dataofs = data_p - wav; - return info; } - /* ================ ResampleSfx @@ -207,36 +187,34 @@ ResampleSfx resample / decimate to the current source rate ================ */ -void ResampleSfx (sfx_t *sfx, int iInRate, int iInWidth, byte *pData) -{ - int iOutCount; - int iSrcSample; - float fStepScale; - int i; - int iSample; - unsigned int uiSampleFrac, uiFracStep; // uiSampleFrac MUST be unsigned, or large samples (eg music tracks) crash +void ResampleSfx(sfx_t *sfx, int iInRate, int iInWidth, byte *pData) { + int iOutCount; + int iSrcSample; + float fStepScale; + int i; + int iSample; + unsigned int uiSampleFrac, uiFracStep; // uiSampleFrac MUST be unsigned, or large samples (eg music tracks) crash - fStepScale = (float)iInRate / dma.speed; // this is usually 0.5, 1, or 2 + fStepScale = (float)iInRate / dma.speed; // this is usually 0.5, 1, or 2 // When stepscale is > 1 (we're downsampling), we really ought to run a low pass filter on the samples iOutCount = (int)(sfx->iSoundLengthInSamples / fStepScale); sfx->iSoundLengthInSamples = iOutCount; - sfx->pSoundData = (short *) SND_malloc( sfx->iSoundLengthInSamples*2 ,sfx ); + sfx->pSoundData = (short *)SND_malloc(sfx->iSoundLengthInSamples * 2, sfx); - sfx->fVolRange = 0; - uiSampleFrac = 0; - uiFracStep = (int)(fStepScale*256); + sfx->fVolRange = 0; + uiSampleFrac = 0; + uiFracStep = (int)(fStepScale * 256); - for (i=0 ; iiSoundLengthInSamples ; i++) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i++) { iSrcSample = uiSampleFrac >> 8; uiSampleFrac += uiFracStep; if (iInWidth == 2) { - iSample = LittleShort ( ((short *)pData)[iSrcSample] ); + iSample = LittleShort(((short *)pData)[iSrcSample]); } else { - iSample = (unsigned int)( (unsigned char)(pData[iSrcSample]) - 128) << 8; + iSample = (unsigned int)((unsigned char)(pData[iSrcSample]) - 128) << 8; } sfx->pSoundData[i] = (short)iSample; @@ -245,71 +223,57 @@ void ResampleSfx (sfx_t *sfx, int iInRate, int iInWidth, byte *pData) // if (iSample < 0) iSample = -iSample; - if (sfx->fVolRange < (iSample >> 8) ) - { - sfx->fVolRange = iSample >> 8; + if (sfx->fVolRange < (iSample >> 8)) { + sfx->fVolRange = iSample >> 8; } } } - //============================================================================= +void S_LoadSound_Finalize(wavinfo_t *info, sfx_t *sfx, byte *data) { + // float stepscale = (float)info->rate / dma.speed; + // int len = (int)(info->samples / stepscale); -void S_LoadSound_Finalize(wavinfo_t *info, sfx_t *sfx, byte *data) -{ - //float stepscale = (float)info->rate / dma.speed; - //int len = (int)(info->samples / stepscale); - - //len *= info->width; + // len *= info->width; sfx->eSoundCompressionMethod = ct_16; - sfx->iSoundLengthInSamples = info->samples; - ResampleSfx( sfx, info->rate, info->width, data + info->dataofs ); + sfx->iSoundLengthInSamples = info->samples; + ResampleSfx(sfx, info->rate, info->width, data + info->dataofs); } - - - - // maybe I'm re-inventing the wheel, here, but I can't see any functions that already do this, so... // -char *Filename_WithoutPath(const char *psFilename) -{ - static char sString[MAX_QPATH]; // !! - const char *p = strrchr(psFilename,'\\'); +char *Filename_WithoutPath(const char *psFilename) { + static char sString[MAX_QPATH]; // !! + const char *p = strrchr(psFilename, '\\'); - if (!p++) - p=psFilename; + if (!p++) + p = psFilename; - strcpy(sString,p); + strcpy(sString, p); return sString; - } // returns (eg) "\dir\name" for "\dir\name.bmp" // -char *Filename_WithoutExt(const char *psFilename) -{ - static char sString[MAX_QPATH]; // ! +char *Filename_WithoutExt(const char *psFilename) { + static char sString[MAX_QPATH]; // ! - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p = strrchr(sString,'.'); - char *p2= strrchr(sString,'\\'); + char *p = strrchr(sString, '.'); + char *p2 = strrchr(sString, '\\'); // special check, make sure the first suffix we found from the end wasn't just a directory suffix (eg on a path'd filename with no extension anyway) // - if (p && (p2==0 || (p2 && p>p2))) - *p=0; + if (p && (p2 == 0 || (p2 && p > p2))) + *p = 0; return sString; - } - - int iFilesFound; int iFilesUpdated; int iErrors; @@ -317,50 +281,44 @@ qboolean qbForceRescan; qboolean qbForceStereo; std::string strErrors; -void R_CheckMP3s( const char *psDir ) -{ -// Com_Printf(va("Scanning Dir: %s\n",psDir)); - Com_Printf("."); // stops useful info scrolling off screen +void R_CheckMP3s(const char *psDir) { + // Com_Printf(va("Scanning Dir: %s\n",psDir)); + Com_Printf("."); // stops useful info scrolling off screen - char **sysFiles, **dirFiles; - int numSysFiles, i, numdirs; + char **sysFiles, **dirFiles; + int numSysFiles, i, numdirs; - dirFiles = FS_ListFiles( psDir, "/", &numdirs); - if (numdirs > 2) - { - for (i=2;i 2) { + for (i = 2; i < numdirs; i++) { + char sDirName[MAX_QPATH]; sprintf(sDirName, "%s\\%s", psDir, dirFiles[i]); R_CheckMP3s(sDirName); } } - sysFiles = FS_ListFiles( psDir, ".mp3", &numSysFiles ); - for(i=0; ifVolRange; // free sfx->data... // { - #ifndef INT_MIN - #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ - #endif +#ifndef INT_MIN +#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ +#endif // - pSFX->iLastTimeUsed = INT_MIN; // force this to be oldest sound file, therefore disposable... + pSFX->iLastTimeUsed = INT_MIN; // force this to be oldest sound file, therefore disposable... pSFX->bInMemory = true; - SND_FreeOldestSound(); // ... and do the disposal + SND_FreeOldestSound(); // ... and do the disposal // now set our temp SFX struct back to default name so nothing else accidentally uses it... // @@ -429,7 +385,7 @@ void R_CheckMP3s( const char *psDir ) pSFX->bDefaultSound = false; } -// OutputDebugString(va("File: \"%s\" MaxVol %f\n",sFilename,pSFX->fVolRange)); + // OutputDebugString(va("File: \"%s\" MaxVol %f\n",sFilename,pSFX->fVolRange)); // other stuff... // @@ -438,90 +394,74 @@ void R_CheckMP3s( const char *psDir ) // well, time to update the file now... // - fileHandle_t f = FS_FOpenFileWrite( sFilename ); - if (f) - { + fileHandle_t f = FS_FOpenFileWrite(sFilename); + if (f) { // write the file back out, but omitting the tag if there was one... // - int iWritten = FS_Write(pbData, iSize-(pTAG?sizeof(*pTAG):0), f); + int iWritten = FS_Write(pbData, iSize - (pTAG ? sizeof(*pTAG) : 0), f); - if (iWritten) - { + if (iWritten) { // make up a new tag if we didn't find one in the original file... // id3v1_1 TAG; - if (!pTAG) - { + if (!pTAG) { pTAG = &TAG; - memset(&TAG,0,sizeof(TAG)); - strncpy(pTAG->id,"TAG",3); + memset(&TAG, 0, sizeof(TAG)); + strncpy(pTAG->id, "TAG", 3); } - strncpy(pTAG->title, Filename_WithoutPath(Filename_WithoutExt(sFilename)), sizeof(pTAG->title)); - strncpy(pTAG->artist, "Raven Software", sizeof(pTAG->artist) ); - strncpy(pTAG->year, "2002", sizeof(pTAG->year) ); - strncpy(pTAG->comment, va("%s %g",sKEY_MAXVOL,fMaxVol), sizeof(pTAG->comment) ); - strncpy(pTAG->album, va("%s %d",sKEY_UNCOMP,iActualUnpackedSize),sizeof(pTAG->album) ); + strncpy(pTAG->title, Filename_WithoutPath(Filename_WithoutExt(sFilename)), sizeof(pTAG->title)); + strncpy(pTAG->artist, "Raven Software", sizeof(pTAG->artist)); + strncpy(pTAG->year, "2002", sizeof(pTAG->year)); + strncpy(pTAG->comment, va("%s %g", sKEY_MAXVOL, fMaxVol), sizeof(pTAG->comment)); + strncpy(pTAG->album, va("%s %d", sKEY_UNCOMP, iActualUnpackedSize), sizeof(pTAG->album)); - if (FS_Write( pTAG, sizeof(*pTAG), f )) // NZ = success + if (FS_Write(pTAG, sizeof(*pTAG), f)) // NZ = success { iFilesUpdated++; - } - else - { - Com_Printf("*********** Failed write to file \"%s\"!\n",sFilename); + } else { + Com_Printf("*********** Failed write to file \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to write: \"%s\"\n",sFilename); + strErrors += va("Failed to write: \"%s\"\n", sFilename); } - } - else - { - Com_Printf("*********** Failed write to file \"%s\"!\n",sFilename); + } else { + Com_Printf("*********** Failed write to file \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to write: \"%s\"\n",sFilename); + strErrors += va("Failed to write: \"%s\"\n", sFilename); } - FS_FCloseFile( f ); - } - else - { - Com_Printf("*********** Failed to re-open for write \"%s\"!\n",sFilename); + FS_FCloseFile(f); + } else { + Com_Printf("*********** Failed to re-open for write \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to re-open for write: \"%s\"\n",sFilename); + strErrors += va("Failed to re-open for write: \"%s\"\n", sFilename); } + } else { + Com_Error(ERR_DROP, "******* This MP3 should be deleted: \"%s\"\n", sFilename); } - else - { - Com_Error(ERR_DROP, "******* This MP3 should be deleted: \"%s\"\n",sFilename); - } - } - else - { - Com_Printf("*********** File was not a valid MP3!: \"%s\"\n",sFilename); + } else { + Com_Printf("*********** File was not a valid MP3!: \"%s\"\n", sFilename); iErrors++; - strErrors += va("Not game-legal MP3 format: \"%s\"\n",sFilename); + strErrors += va("Not game-legal MP3 format: \"%s\"\n", sFilename); } - } - else - { + } else { Com_Printf(" ( OK )\n"); } - FS_FreeFile( pbData ); + FS_FreeFile(pbData); } } - FS_FreeFileList( sysFiles ); - FS_FreeFileList( dirFiles ); + FS_FreeFileList(sysFiles); + FS_FreeFileList(dirFiles); } // this console-function is for development purposes, and makes sure that sound/*.mp3 /s have tags in them // specifying stuff like their max volume (and uncompressed size) etc... // -void S_MP3_CalcVols_f( void ) -{ +void S_MP3_CalcVols_f(void) { char sStartDir[MAX_QPATH] = {"sound"}; const char sUsage[] = "Usage: mp3_calcvols [-rescan] \ne.g. mp3_calcvols sound/chars"; - if (Cmd_Argc() == 1 || Cmd_Argc()>4) // 3 optional arguments + if (Cmd_Argc() == 1 || Cmd_Argc() > 4) // 3 optional arguments { Com_Printf(sUsage); return; @@ -529,29 +469,20 @@ void S_MP3_CalcVols_f( void ) S_StopAllSounds(); - qbForceRescan = qfalse; qbForceStereo = qfalse; - iFilesFound = 0; - iFilesUpdated = 0; - iErrors = 0; - strErrors = ""; - - for (int i=1; iinteger) - { + if (com_buildScript->integer) { fileHandle_t hFile; - //German - strncpy(psVoice,"chr_d",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + // German + strncpy(psVoice, "chr_d", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav - - //French - strncpy(psVoice,"chr_f",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav + + // French + strncpy(psVoice, "chr_f", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav - - //Spanish - strncpy(psVoice,"chr_e",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav + + // Spanish + strncpy(psVoice, "chr_e", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav - strncpy(psVoice,"chars",5); //put it back to chars + strncpy(psVoice, "chars", 5); // put it back to chars } // account for foreign voices... // - extern cvar_t* s_language; - if (s_language && Q_stricmp("DEUTSCH",s_language->string)==0) - { - strncpy(psVoice,"chr_d",5); // same number of letters as "chars" - } - else if (s_language && Q_stricmp("FRANCAIS",s_language->string)==0) - { - strncpy(psVoice,"chr_f",5); // same number of letters as "chars" - } - else if (s_language && Q_stricmp("ESPANOL",s_language->string)==0) - { - strncpy(psVoice,"chr_e",5); // same number of letters as "chars" - } - else - { - psVoice = NULL; // use this ptr as a flag as to whether or not we substituted with a foreign version + extern cvar_t *s_language; + if (s_language && Q_stricmp("DEUTSCH", s_language->string) == 0) { + strncpy(psVoice, "chr_d", 5); // same number of letters as "chars" + } else if (s_language && Q_stricmp("FRANCAIS", s_language->string) == 0) { + strncpy(psVoice, "chr_f", 5); // same number of letters as "chars" + } else if (s_language && Q_stricmp("ESPANOL", s_language->string) == 0) { + strncpy(psVoice, "chr_e", 5); // same number of letters as "chars" + } else { + psVoice = NULL; // use this ptr as a flag as to whether or not we substituted with a foreign version } } - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try WAV - if ( !*pData ) { - psFilename[iNameStrlen-3] = 'm'; - psFilename[iNameStrlen-2] = 'p'; - psFilename[iNameStrlen-1] = '3'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try MP3 + *piSize = FS_ReadFile(psFilename, (void **)pData); // try WAV + if (!*pData) { + psFilename[iNameStrlen - 3] = 'm'; + psFilename[iNameStrlen - 2] = 'p'; + psFilename[iNameStrlen - 1] = '3'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try MP3 - if ( !*pData ) - { - //hmmm, not found, ok, maybe we were trying a foreign noise ("arghhhhh.mp3" that doesn't matter?) but it - // was missing? Can't tell really, since both types are now in sound/chars. Oh well, fall back to English for now... + if (!*pData) { + // hmmm, not found, ok, maybe we were trying a foreign noise ("arghhhhh.mp3" that doesn't matter?) but it + // was missing? Can't tell really, since both types are now in sound/chars. Oh well, fall back to English for now... - if (psVoice) // were we trying to load foreign? + if (psVoice) // were we trying to load foreign? { // yep, so fallback to re-try the english... // #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW "Foreign file missing: \"%s\"! (using English...)\n",psFilename); + Com_Printf(S_COLOR_YELLOW "Foreign file missing: \"%s\"! (using English...)\n", psFilename); #endif - strncpy(psVoice,"chars",5); - - psFilename[iNameStrlen-3] = 'w'; - psFilename[iNameStrlen-2] = 'a'; - psFilename[iNameStrlen-1] = 'v'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try English WAV - if ( !*pData ) - { - psFilename[iNameStrlen-3] = 'm'; - psFilename[iNameStrlen-2] = 'p'; - psFilename[iNameStrlen-1] = '3'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try English MP3 + strncpy(psVoice, "chars", 5); + + psFilename[iNameStrlen - 3] = 'w'; + psFilename[iNameStrlen - 2] = 'a'; + psFilename[iNameStrlen - 1] = 'v'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try English WAV + if (!*pData) { + psFilename[iNameStrlen - 3] = 'm'; + psFilename[iNameStrlen - 2] = 'p'; + psFilename[iNameStrlen - 1] = '3'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try English MP3 } } - if (!*pData) - { - return qfalse; // sod it, give up... + if (!*pData) { + return qfalse; // sod it, give up... } } } @@ -714,10 +621,9 @@ static qboolean S_LoadSound_FileLoadAndNameAdjuster(char *psFilename, byte **pDa // #define SOUND_CHARS_DIR "sound/chars/" #define SOUND_CHARS_DIR_LENGTH 12 // strlen( SOUND_CHARS_DIR ) -static qboolean S_LoadSound_DirIsAllowedToKeepMP3s( const char *psFilename ) -{ - if ( Q_stricmpn( psFilename, SOUND_CHARS_DIR, SOUND_CHARS_DIR_LENGTH ) == 0 ) - return qtrue; // found a dir that's allowed to keep MP3s +static qboolean S_LoadSound_DirIsAllowedToKeepMP3s(const char *psFilename) { + if (Q_stricmpn(psFilename, SOUND_CHARS_DIR, SOUND_CHARS_DIR_LENGTH) == 0) + return qtrue; // found a dir that's allowed to keep MP3s return qfalse; } @@ -731,119 +637,103 @@ of a forced fallback of a player specific sound (or of a wav/mp3 substitution no ============== */ qboolean gbInsideLoadSound = qfalse; -static qboolean S_LoadSound_Actual( sfx_t *sfx ) -{ - byte *data; - short *samples; - wavinfo_t info; - int size; - char *psExt; - char sLoadName[MAX_QPATH]; - - int len = strlen(sfx->sSoundName); - if (len<5) - { +static qboolean S_LoadSound_Actual(sfx_t *sfx) { + byte *data; + short *samples; + wavinfo_t info; + int size; + char *psExt; + char sLoadName[MAX_QPATH]; + + int len = strlen(sfx->sSoundName); + if (len < 5) { return qfalse; } // player specific sounds are never directly loaded... // - if ( sfx->sSoundName[0] == '*') { + if (sfx->sSoundName[0] == '*') { return qfalse; } // make up a local filename to try wav/mp3 substitutes... // Q_strncpyz(sLoadName, sfx->sSoundName, sizeof(sLoadName)); - Q_strlwr( sLoadName ); + Q_strlwr(sLoadName); // // Ensure name has an extension (which it must have, but you never know), and get ptr to it... // - psExt = &sLoadName[strlen(sLoadName)-4]; - if (*psExt != '.') - { - //Com_Printf( "WARNING: soundname '%s' does not have 3-letter extension\n",sLoadName); - COM_DefaultExtension(sLoadName,sizeof(sLoadName),".wav"); // so psExt below is always valid - psExt = &sLoadName[strlen(sLoadName)-4]; + psExt = &sLoadName[strlen(sLoadName) - 4]; + if (*psExt != '.') { + // Com_Printf( "WARNING: soundname '%s' does not have 3-letter extension\n",sLoadName); + COM_DefaultExtension(sLoadName, sizeof(sLoadName), ".wav"); // so psExt below is always valid + psExt = &sLoadName[strlen(sLoadName) - 4]; len = strlen(sLoadName); } - if (!S_LoadSound_FileLoadAndNameAdjuster(sLoadName, &data, &size, len)) - { + if (!S_LoadSound_FileLoadAndNameAdjuster(sLoadName, &data, &size, len)) { return qfalse; } SND_TouchSFX(sfx); -//========= - if (Q_stricmpn(psExt,".mp3",4)==0) - { + //========= + if (Q_stricmpn(psExt, ".mp3", 4) == 0) { // load MP3 file instead... // - if (MP3_IsValid(sLoadName,data, size, qfalse)) - { - int iRawPCMDataSize = MP3_GetUnpackedSize(sLoadName,data,size,qfalse,qfalse); - - if (S_LoadSound_DirIsAllowedToKeepMP3s(sfx->sSoundName) // NOT sLoadName, this uses original un-languaged name - && - MP3Stream_InitFromFile(sfx, data, size, sLoadName, iRawPCMDataSize + 2304 /* + 1 MP3 frame size, jic */,qfalse) - ) - { -// Com_DPrintf("(Keeping file \"%s\" as MP3)\n",sLoadName); + if (MP3_IsValid(sLoadName, data, size, qfalse)) { + int iRawPCMDataSize = MP3_GetUnpackedSize(sLoadName, data, size, qfalse, qfalse); + + if (S_LoadSound_DirIsAllowedToKeepMP3s(sfx->sSoundName) // NOT sLoadName, this uses original un-languaged name + && MP3Stream_InitFromFile(sfx, data, size, sLoadName, iRawPCMDataSize + 2304 /* + 1 MP3 frame size, jic */, qfalse)) { + // Com_DPrintf("(Keeping file \"%s\" as MP3)\n",sLoadName); #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { // Create space for lipsync data (4 lip sync values per streaming AL buffer) - if (strstr(sfx->sSoundName, "chars") ) + if (strstr(sfx->sSoundName, "chars")) sfx->lipSyncData = (char *)Z_Malloc(16, TAG_SND_RAWDATA, qfalse); else sfx->lipSyncData = NULL; } #endif - } - else - { + } else { // small file, not worth keeping as MP3 since it would increase in size (with MP3 header etc)... // - Com_DPrintf("S_LoadSound: Unpacking MP3 file \"%s\" to wav.\n",sLoadName); + Com_DPrintf("S_LoadSound: Unpacking MP3 file \"%s\" to wav.\n", sLoadName); // // unpack and convert into WAV... // { - byte *pbUnpackBuffer = (byte *) Z_Malloc( iRawPCMDataSize+10 +2304 /* */, TAG_TEMP_WORKSPACE, qfalse ); // won't return if fails + byte *pbUnpackBuffer = (byte *)Z_Malloc(iRawPCMDataSize + 10 + 2304 /* */, TAG_TEMP_WORKSPACE, qfalse); // won't return if fails { - int iResultBytes = MP3_UnpackRawPCM( sLoadName, data, size, pbUnpackBuffer, qfalse ); + int iResultBytes = MP3_UnpackRawPCM(sLoadName, data, size, pbUnpackBuffer, qfalse); - if (iResultBytes!= iRawPCMDataSize){ - Com_Printf(S_COLOR_YELLOW"**** MP3 %s final unpack size %d different to previous value %d\n",sLoadName,iResultBytes,iRawPCMDataSize); - //assert (iResultBytes == iRawPCMDataSize); + if (iResultBytes != iRawPCMDataSize) { + Com_Printf(S_COLOR_YELLOW "**** MP3 %s final unpack size %d different to previous value %d\n", sLoadName, iResultBytes, + iRawPCMDataSize); + // assert (iResultBytes == iRawPCMDataSize); } - // fake up a WAV structure so I can use the other post-load sound code such as volume calc for lip-synching // // (this is a bit crap really, but it lets me drop through into existing code)... // - MP3_FakeUpWAVInfo( sLoadName, data, size, iResultBytes, - // these params are all references... - info.format, info.rate, info.width, info.channels, info.samples, info.dataofs, - qfalse - ); + MP3_FakeUpWAVInfo(sLoadName, data, size, iResultBytes, + // these params are all references... + info.format, info.rate, info.width, info.channels, info.samples, info.dataofs, qfalse); - S_LoadSound_Finalize(&info,sfx,pbUnpackBuffer); + S_LoadSound_Finalize(&info, sfx, pbUnpackBuffer); #ifdef Q3_BIG_ENDIAN // the MP3 decoder returns the samples in the correct endianness, but ResampleSfx byteswaps them, // so we have to swap them again... - sfx->fVolRange = 0; + sfx->fVolRange = 0; - for (int i = 0; i < sfx->iSoundLengthInSamples; i++) - { + for (int i = 0; i < sfx->iSoundLengthInSamples; i++) { sfx->pSoundData[i] = LittleShort(sfx->pSoundData[i]); // C++11 defines double abs(short) which is not what we want here, // because double >> int is not defined. Force interpretation as int - if (sfx->fVolRange < (abs(static_cast(sfx->pSoundData[i])) >> 8)) - { + if (sfx->fVolRange < (abs(static_cast(sfx->pSoundData[i])) >> 8)) { sfx->fVolRange = abs(static_cast(sfx->pSoundData[i])) >> 8; } } @@ -851,14 +741,11 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) // Open AL #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if (strstr(sfx->sSoundName, "chars")) - { + if (s_UseOpenAL) { + if (strstr(sfx->sSoundName, "chars")) { sfx->lipSyncData = (char *)Z_Malloc((sfx->iSoundLengthInSamples / 1000) + 1, TAG_SND_RAWDATA, qfalse); S_PreProcessLipSync(sfx); - } - else + } else sfx->lipSyncData = NULL; // Clear Open AL Error state @@ -867,12 +754,10 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) // Generate AL Buffer ALuint Buffer; alGenBuffers(1, &Buffer); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { // Copy audio data to AL Buffer - alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples*2, 22050); - if (alGetError() == AL_NO_ERROR) - { + alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples * 2, 22050); + if (alGetError() == AL_NO_ERROR) { sfx->Buffer = Buffer; Z_Free(sfx->pSoundData); sfx->pSoundData = NULL; @@ -885,53 +770,46 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) } } } - } - else - { + } else { // MP3_IsValid() will already have printed any errors via Com_Printf at this point... // - FS_FreeFile (data); + FS_FreeFile(data); return qfalse; } - } - else - { + } else { // loading a WAV, presumably... -//========= + //========= - info = GetWavinfo( sLoadName, data, size ); - if ( info.channels != 1 ) { - Com_Printf ("%s is a stereo wav file\n", sLoadName); - FS_FreeFile (data); + info = GetWavinfo(sLoadName, data, size); + if (info.channels != 1) { + Com_Printf("%s is a stereo wav file\n", sLoadName); + FS_FreeFile(data); return qfalse; } -/* if ( info.width == 1 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: %s is a 8 bit wav file\n", sLoadName); - } + /* if ( info.width == 1 ) { + Com_Printf(S_COLOR_YELLOW "WARNING: %s is a 8 bit wav file\n", sLoadName); + } - if ( info.rate != 22050 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: %s is not a 22kHz wav file\n", sLoadName); - } -*/ + if ( info.rate != 22050 ) { + Com_Printf(S_COLOR_YELLOW "WARNING: %s is not a 22kHz wav file\n", sLoadName); + } + */ samples = (short *)Z_Malloc(info.samples * sizeof(short) * 2, TAG_TEMP_WORKSPACE, qfalse); sfx->eSoundCompressionMethod = ct_16; - sfx->iSoundLengthInSamples = info.samples; + sfx->iSoundLengthInSamples = info.samples; sfx->pSoundData = NULL; - ResampleSfx( sfx, info.rate, info.width, data + info.dataofs ); + ResampleSfx(sfx, info.rate, info.width, data + info.dataofs); // Open AL #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) - { + if (s_UseOpenAL) { + if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) { sfx->lipSyncData = (char *)Z_Malloc((sfx->iSoundLengthInSamples / 1000) + 1, TAG_SND_RAWDATA, qfalse); S_PreProcessLipSync(sfx); - } - else + } else sfx->lipSyncData = NULL; // Clear Open AL Error State @@ -940,12 +818,10 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) // Generate AL Buffer ALuint Buffer; alGenBuffers(1, &Buffer); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { // Copy audio data to AL Buffer - alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples*2, 22050); - if (alGetError() == AL_NO_ERROR) - { + alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples * 2, 22050); + if (alGetError() == AL_NO_ERROR) { // Store AL Buffer in sfx struct, and release sample data sfx->Buffer = Buffer; Z_Free(sfx->pSoundData); @@ -958,22 +834,20 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) Z_Free(samples); } - FS_FreeFile( data ); + FS_FreeFile(data); return qtrue; } - // wrapper function for above so I can guarantee that we don't attempt any audio-dumping during this call because // of a z_malloc() fail recovery... // -qboolean S_LoadSound( sfx_t *sfx ) -{ - gbInsideLoadSound = qtrue; // !!!!!!!!!!!!! +qboolean S_LoadSound(sfx_t *sfx) { + gbInsideLoadSound = qtrue; // !!!!!!!!!!!!! - qboolean bReturn = S_LoadSound_Actual( sfx ); + qboolean bReturn = S_LoadSound_Actual(sfx); - gbInsideLoadSound = qfalse; // !!!!!!!!!!!!! + gbInsideLoadSound = qfalse; // !!!!!!!!!!!!! return bReturn; } @@ -982,29 +856,24 @@ qboolean S_LoadSound( sfx_t *sfx ) /* Precalculate the lipsync values for the whole sample */ -void S_PreProcessLipSync(sfx_t *sfx) -{ +void S_PreProcessLipSync(sfx_t *sfx) { int i, j; int sample; int sampleTotal = 0; j = 0; - for (i = 0; i < sfx->iSoundLengthInSamples; i += 100) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i += 100) { sample = LittleShort(sfx->pSoundData[i]); sample = sample >> 8; sampleTotal += sample * sample; - if (((i + 100) % 1000) == 0) - { + if (((i + 100) % 1000) == 0) { sampleTotal /= 10; - if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) - { + if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) { // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) + } else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) sample = 1; else if (sampleTotal < sfx->fVolRange * s_lip_threshold_3->value) sample = 2; @@ -1032,12 +901,10 @@ void S_PreProcessLipSync(sfx_t *sfx) else sampleTotal = 0; - if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) - { + if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) { // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) + } else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) sample = 1; else if (sampleTotal < sfx->fVolRange * s_lip_threshold_3->value) sample = 2; diff --git a/code/client/snd_mix.cpp b/code/client/snd_mix.cpp index d245590db1..8e8863504c 100644 --- a/code/client/snd_mix.cpp +++ b/code/client/snd_mix.cpp @@ -28,17 +28,15 @@ along with this program; if not, see . #include "snd_local.h" portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE]; -int *snd_p, snd_linear_count, snd_vol; -short *snd_out; +int *snd_p, snd_linear_count, snd_vol; +short *snd_out; -void S_WriteLinearBlastStereo16 (void) -{ - int i; - int val; +void S_WriteLinearBlastStereo16(void) { + int i; + int val; - for (i=0 ; i>8; + for (i = 0; i < snd_linear_count; i += 2) { + val = snd_p[i] >> 8; if (val > 0x7fff) snd_out[i] = 0x7fff; else if (val < (short)0x8000) @@ -46,42 +44,40 @@ void S_WriteLinearBlastStereo16 (void) else snd_out[i] = val; - val = snd_p[i+1]>>8; + val = snd_p[i + 1] >> 8; if (val > 0x7fff) - snd_out[i+1] = 0x7fff; + snd_out[i + 1] = 0x7fff; else if (val < (short)0x8000) - snd_out[i+1] = (short)0x8000; + snd_out[i + 1] = (short)0x8000; else - snd_out[i+1] = val; + snd_out[i + 1] = val; } } -void S_TransferStereo16 (unsigned long *pbuf, int endtime) -{ - int lpos; - int ls_paintedtime; +void S_TransferStereo16(unsigned long *pbuf, int endtime) { + int lpos; + int ls_paintedtime; - snd_p = (int *) paintbuffer; + snd_p = (int *)paintbuffer; ls_paintedtime = s_paintedtime; - while (ls_paintedtime < endtime) - { - // handle recirculating buffer issues - lpos = ls_paintedtime & ((dma.samples>>1)-1); + while (ls_paintedtime < endtime) { + // handle recirculating buffer issues + lpos = ls_paintedtime & ((dma.samples >> 1) - 1); - snd_out = (short *) pbuf + (lpos<<1); + snd_out = (short *)pbuf + (lpos << 1); - snd_linear_count = (dma.samples>>1) - lpos; + snd_linear_count = (dma.samples >> 1) - lpos; if (ls_paintedtime + snd_linear_count > endtime) snd_linear_count = endtime - ls_paintedtime; snd_linear_count <<= 1; - // write a linear blast of samples - S_WriteLinearBlastStereo16 (); + // write a linear blast of samples + S_WriteLinearBlastStereo16(); snd_p += snd_linear_count; - ls_paintedtime += (snd_linear_count>>1); + ls_paintedtime += (snd_linear_count >> 1); } } @@ -91,49 +87,41 @@ S_TransferPaintBuffer =================== */ -void S_TransferPaintBuffer(int endtime) -{ - int out_idx; - int count; - int out_mask; - int *p; - int step; - int val; +void S_TransferPaintBuffer(int endtime) { + int out_idx; + int count; + int out_mask; + int *p; + int step; + int val; unsigned long *pbuf; pbuf = (unsigned long *)dma.buffer; - - if ( s_testsound->integer ) { - int i; - int count; + if (s_testsound->integer) { + int i; + int count; // write a fixed sine wave count = (endtime - s_paintedtime); - for (i=0 ; i> 8; - p+= step; + p += step; if (val > 0x7fff) val = 0x7fff; else if (val < (short)0x8000) @@ -141,26 +129,22 @@ void S_TransferPaintBuffer(int endtime) out[out_idx] = (short)val; out_idx = (out_idx + 1) & out_mask; } - } - else if (dma.samplebits == 8) - { - unsigned char *out = (unsigned char *) pbuf; - while (count--) - { + } else if (dma.samplebits == 8) { + unsigned char *out = (unsigned char *)pbuf; + while (count--) { val = *p >> 8; - p+= step; + p += step; if (val > 0x7fff) val = 0x7fff; else if (val < (short)0x8000) val = (short)0x8000; - out[out_idx] = (short)((val>>8) + 128); + out[out_idx] = (short)((val >> 8) + 128); out_idx = (out_idx + 1) & out_mask; } } } } - /* =============================================================================== @@ -168,156 +152,144 @@ CHANNEL MIXING =============================================================================== */ -static void S_PaintChannelFrom16( channel_t *ch, const sfx_t *sfx, int count, int sampleOffset, int bufferOffset ) -{ - portable_samplepair_t *pSamplesDest; +static void S_PaintChannelFrom16(channel_t *ch, const sfx_t *sfx, int count, int sampleOffset, int bufferOffset) { + portable_samplepair_t *pSamplesDest; int iData; + int iLeftVol = ch->leftvol * snd_vol; + int iRightVol = ch->rightvol * snd_vol; - int iLeftVol = ch->leftvol * snd_vol; - int iRightVol = ch->rightvol * snd_vol; - - pSamplesDest = &paintbuffer[ bufferOffset ]; + pSamplesDest = &paintbuffer[bufferOffset]; - for ( int i=0 ; ipSoundData[ sampleOffset++ ]; + for (int i = 0; i < count; i++) { + iData = sfx->pSoundData[sampleOffset++]; - pSamplesDest[i].left += (iData * iLeftVol )>>8; - pSamplesDest[i].right += (iData * iRightVol)>>8; + pSamplesDest[i].left += (iData * iLeftVol) >> 8; + pSamplesDest[i].right += (iData * iRightVol) >> 8; } } - -void S_PaintChannelFromMP3( channel_t *ch, const sfx_t *sc, int count, int sampleOffset, int bufferOffset ) -{ +void S_PaintChannelFromMP3(channel_t *ch, const sfx_t *sc, int count, int sampleOffset, int bufferOffset) { int data; int leftvol, rightvol; signed short *sfx; - int i; - portable_samplepair_t *samp; + int i; + portable_samplepair_t *samp; static short tempMP3Buffer[PAINTBUFFER_SIZE]; - MP3Stream_GetSamples( ch, sampleOffset, count, tempMP3Buffer, qfalse ); // qfalse = not stereo + MP3Stream_GetSamples(ch, sampleOffset, count, tempMP3Buffer, qfalse); // qfalse = not stereo - leftvol = ch->leftvol*snd_vol; - rightvol = ch->rightvol*snd_vol; + leftvol = ch->leftvol * snd_vol; + rightvol = ch->rightvol * snd_vol; sfx = tempMP3Buffer; - samp = &paintbuffer[ bufferOffset ]; - + samp = &paintbuffer[bufferOffset]; - while ( count & 3 ) { + while (count & 3) { data = *sfx; - samp->left += (data * leftvol)>>8; - samp->right += (data * rightvol)>>8; + samp->left += (data * leftvol) >> 8; + samp->right += (data * rightvol) >> 8; sfx++; samp++; count--; } - for ( i=0 ; i>8; - samp[i].right += (data * rightvol)>>8; + samp[i].left += (data * leftvol) >> 8; + samp[i].right += (data * rightvol) >> 8; - data = sfx[i+1]; - samp[i+1].left += (data * leftvol)>>8; - samp[i+1].right += (data * rightvol)>>8; + data = sfx[i + 1]; + samp[i + 1].left += (data * leftvol) >> 8; + samp[i + 1].right += (data * rightvol) >> 8; - data = sfx[i+2]; - samp[i+2].left += (data * leftvol)>>8; - samp[i+2].right += (data * rightvol)>>8; + data = sfx[i + 2]; + samp[i + 2].left += (data * leftvol) >> 8; + samp[i + 2].right += (data * rightvol) >> 8; - data = sfx[i+3]; - samp[i+3].left += (data * leftvol)>>8; - samp[i+3].right += (data * rightvol)>>8; + data = sfx[i + 3]; + samp[i + 3].left += (data * leftvol) >> 8; + samp[i + 3].right += (data * rightvol) >> 8; } } - // subroutinised to save code dup (called twice) -ste // -void ChannelPaint(channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset) -{ - switch (sc->eSoundCompressionMethod) - { - case ct_16: +void ChannelPaint(channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset) { + switch (sc->eSoundCompressionMethod) { + case ct_16: - S_PaintChannelFrom16 (ch, sc, count, sampleOffset, bufferOffset); - break; + S_PaintChannelFrom16(ch, sc, count, sampleOffset, bufferOffset); + break; - case ct_MP3: + case ct_MP3: - S_PaintChannelFromMP3 (ch, sc, count, sampleOffset, bufferOffset); - break; + S_PaintChannelFromMP3(ch, sc, count, sampleOffset, bufferOffset); + break; - default: + default: - assert(0); // debug aid, ignored in release. FIXME: Should we ERR_DROP here for badness-catch? - break; + assert(0); // debug aid, ignored in release. FIXME: Should we ERR_DROP here for badness-catch? + break; } } - - -void S_PaintChannels( int endtime ) { - int i; - int end; +void S_PaintChannels(int endtime) { + int i; + int end; channel_t *ch; - sfx_t *sc; - int ltime, count; - int sampleOffset; - int normal_vol,voice_vol; + sfx_t *sc; + int ltime, count; + int sampleOffset; + int normal_vol, voice_vol; - snd_vol = normal_vol = s_volume->value*256.0f; - voice_vol = (s_volumeVoice->value*256.0f); + snd_vol = normal_vol = s_volume->value * 256.0f; + voice_vol = (s_volumeVoice->value * 256.0f); -//Com_Printf ("%i to %i\n", s_paintedtime, endtime); - while ( s_paintedtime < endtime ) { + // Com_Printf ("%i to %i\n", s_paintedtime, endtime); + while (s_paintedtime < endtime) { // if paintbuffer is smaller than DMA buffer // we may need to fill it multiple times end = endtime; - if ( endtime - s_paintedtime > PAINTBUFFER_SIZE ) { + if (endtime - s_paintedtime > PAINTBUFFER_SIZE) { end = s_paintedtime + PAINTBUFFER_SIZE; } // clear the paint buffer to either music or zeros - if ( s_rawend < s_paintedtime ) { - if ( s_rawend ) { - //Com_DPrintf ("background sound underrun\n"); + if (s_rawend < s_paintedtime) { + if (s_rawend) { + // Com_DPrintf ("background sound underrun\n"); } memset(paintbuffer, 0, (end - s_paintedtime) * sizeof(portable_samplepair_t)); } else { // copy from the streaming sound source - int s; - int stop; + int s; + int stop; stop = (end < s_rawend) ? end : s_rawend; - for ( i = s_paintedtime ; i < stop ; i++ ) { - s = i&(MAX_RAW_SAMPLES-1); - paintbuffer[i-s_paintedtime] = s_rawsamples[s]; + for (i = s_paintedtime; i < stop; i++) { + s = i & (MAX_RAW_SAMPLES - 1); + paintbuffer[i - s_paintedtime] = s_rawsamples[s]; } -// if (i != end) -// Com_Printf ("partial stream\n"); -// else -// Com_Printf ("full stream\n"); - for ( ; i < end ; i++ ) { - paintbuffer[i-s_paintedtime].left = - paintbuffer[i-s_paintedtime].right = 0; + // if (i != end) + // Com_Printf ("partial stream\n"); + // else + // Com_Printf ("full stream\n"); + for (; i < end; i++) { + paintbuffer[i - s_paintedtime].left = paintbuffer[i - s_paintedtime].right = 0; } } // paint in the channels. ch = s_channels; - for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) { - if ( !ch->thesfx || (ch->leftvol<0.25 && ch->rightvol<0.25 )) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx || (ch->leftvol < 0.25 && ch->rightvol < 0.25)) { continue; } - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) snd_vol = voice_vol; else snd_vol = normal_vol; @@ -329,8 +301,7 @@ void S_PaintChannels( int endtime ) { // a looping sound effect and the end of // the sameple is hit... // - do - { + do { if (ch->loopSound) { sampleOffset = ltime % sc->iSoundLengthInSamples; } else { @@ -338,55 +309,55 @@ void S_PaintChannels( int endtime ) { } count = end - ltime; - if ( sampleOffset + count > sc->iSoundLengthInSamples ) { + if (sampleOffset + count > sc->iSoundLengthInSamples) { count = sc->iSoundLengthInSamples - sampleOffset; } - if ( count > 0 ) { + if (count > 0) { ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); ltime += count; } - } while ( ltime < end && ch->loopSound ); + } while (ltime < end && ch->loopSound); } -/* temprem - // paint in the looped channels. - ch = loop_channels; - for ( i = 0; i < numLoopChannels ; i++, ch++ ) { - if ( !ch->thesfx || (!ch->leftvol && !ch->rightvol )) { - continue; - } - - { - - ltime = s_paintedtime; - sc = ch->thesfx; - - if (sc->soundData==NULL || sc->soundLength==0) { - continue; - } - // we might have to make two passes if it - // is a looping sound effect and the end of - // the sample is hit - do { - sampleOffset = (ltime % sc->soundLength); - - count = end - ltime; - if ( sampleOffset + count > sc->soundLength ) { - count = sc->soundLength - sampleOffset; + /* temprem + // paint in the looped channels. + ch = loop_channels; + for ( i = 0; i < numLoopChannels ; i++, ch++ ) { + if ( !ch->thesfx || (!ch->leftvol && !ch->rightvol )) { + continue; } - if ( count > 0 ) { - ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); - ltime += count; - } - } while ( ltime < end); - } - } -*/ + ltime = s_paintedtime; + sc = ch->thesfx; + + if (sc->soundData==NULL || sc->soundLength==0) { + continue; + } + // we might have to make two passes if it + // is a looping sound effect and the end of + // the sample is hit + do { + sampleOffset = (ltime % sc->soundLength); + + count = end - ltime; + if ( sampleOffset + count > sc->soundLength ) { + count = sc->soundLength - sampleOffset; + } + + if ( count > 0 ) + { + ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); + ltime += count; + } + + } while ( ltime < end); + } + } + */ // transfer out according to DMA format - S_TransferPaintBuffer( end ); + S_TransferPaintBuffer(end); s_paintedtime = end; } } diff --git a/code/client/snd_music.cpp b/code/client/snd_music.cpp index 5bebe9cdee..0855bcedab 100644 --- a/code/client/snd_music.cpp +++ b/code/client/snd_music.cpp @@ -24,7 +24,7 @@ along with this program; if not, see . // // Stuff to parse in special x-fade music format and handle blending etc -//Anything above this #include will be ignored by the compiler +// Anything above this #include will be ignored by the compiler #include "../server/exe_headers.h" #include "../qcommon/sstring.h" @@ -40,119 +40,102 @@ along with this program; if not, see . #include "../game/genericparser2.h" -extern qboolean S_FileExists( const char *psFilename ); +extern qboolean S_FileExists(const char *psFilename); -#define sKEY_MUSICFILES CSTRING_VIEW( "musicfiles" ) -#define sKEY_ENTRY CSTRING_VIEW( "entry" ) -#define sKEY_EXIT CSTRING_VIEW( "exit" ) -#define sKEY_MARKER CSTRING_VIEW( "marker" ) -#define sKEY_TIME CSTRING_VIEW( "time" ) -#define sKEY_NEXTFILE CSTRING_VIEW( "nextfile" ) -#define sKEY_NEXTMARK CSTRING_VIEW( "nextmark" ) -#define sKEY_LEVELMUSIC CSTRING_VIEW( "levelmusic" ) -#define sKEY_EXPLORE CSTRING_VIEW( "explore" ) -#define sKEY_ACTION CSTRING_VIEW( "action" ) -#define sKEY_BOSS CSTRING_VIEW( "boss" ) -#define sKEY_DEATH CSTRING_VIEW( "death" ) -#define sKEY_USES CSTRING_VIEW( "uses" ) -#define sKEY_USEBOSS CSTRING_VIEW( "useboss" ) +#define sKEY_MUSICFILES CSTRING_VIEW("musicfiles") +#define sKEY_ENTRY CSTRING_VIEW("entry") +#define sKEY_EXIT CSTRING_VIEW("exit") +#define sKEY_MARKER CSTRING_VIEW("marker") +#define sKEY_TIME CSTRING_VIEW("time") +#define sKEY_NEXTFILE CSTRING_VIEW("nextfile") +#define sKEY_NEXTMARK CSTRING_VIEW("nextmark") +#define sKEY_LEVELMUSIC CSTRING_VIEW("levelmusic") +#define sKEY_EXPLORE CSTRING_VIEW("explore") +#define sKEY_ACTION CSTRING_VIEW("action") +#define sKEY_BOSS CSTRING_VIEW("boss") +#define sKEY_DEATH CSTRING_VIEW("death") +#define sKEY_USES CSTRING_VIEW("uses") +#define sKEY_USEBOSS CSTRING_VIEW("useboss") -#define sKEY_PLACEHOLDER "placeholder" // ignore these +#define sKEY_PLACEHOLDER "placeholder" // ignore these -#define sFILENAME_DMS "ext_data/dms.dat" +#define sFILENAME_DMS "ext_data/dms.dat" -typedef struct -{ - sstring_t sNextFile; - sstring_t sNextMark; // blank if used for an explore piece, name of marker point to enter new file at +typedef struct { + sstring_t sNextFile; + sstring_t sNextMark; // blank if used for an explore piece, name of marker point to enter new file at } MusicExitPoint_t; -struct MusicExitTime_t // need to declare this way for operator < below +struct MusicExitTime_t // need to declare this way for operator < below { - float fTime; - int iExitPoint; + float fTime; + int iExitPoint; // I'm defining this '<' operator so STL's sort algorithm will work // - bool operator < (const MusicExitTime_t& X) const {return (fTime < X.fTime);} + bool operator<(const MusicExitTime_t &X) const { return (fTime < X.fTime); } }; // it's possible for all 3 of these to be empty if it's boss or death music // -typedef std::vector MusicExitPoints_t; -typedef std::vector MusicExitTimes_t; -typedef std::map MusicEntryTimes_t; // key eg "marker1" +typedef std::vector MusicExitPoints_t; +typedef std::vector MusicExitTimes_t; +typedef std::map MusicEntryTimes_t; // key eg "marker1" -typedef struct -{ - sstring_t sFileNameBase; - MusicEntryTimes_t MusicEntryTimes; - MusicExitPoints_t MusicExitPoints; - MusicExitTimes_t MusicExitTimes; +typedef struct { + sstring_t sFileNameBase; + MusicEntryTimes_t MusicEntryTimes; + MusicExitPoints_t MusicExitPoints; + MusicExitTimes_t MusicExitTimes; } MusicFile_t; -typedef std::map MusicData_t; // string is "explore", "action", "boss" etc - MusicData_t* MusicData = NULL; +typedef std::map MusicData_t; // string is "explore", "action", "boss" etc +MusicData_t *MusicData = NULL; // there are now 2 of these, because of the new "uses" keyword... // -sstring_t gsLevelNameForLoad; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths -sstring_t gsLevelNameForCompare; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths -sstring_t gsLevelNameForBossLoad; // eg "kejim_base', special case for enabling boss music to come from a different dir - sigh.... +sstring_t gsLevelNameForLoad; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths +sstring_t gsLevelNameForCompare; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths +sstring_t gsLevelNameForBossLoad; // eg "kejim_base', special case for enabling boss music to come from a different dir - sigh.... -void Music_Free(void) -{ - if (MusicData) - { +void Music_Free(void) { + if (MusicData) { MusicData->clear(); } MusicData = NULL; } -namespace detail -{ - static void build_string( std::ostream& stream ) - { - } +namespace detail { +static void build_string(std::ostream &stream) {} - template< typename T, typename... Tail > - static void build_string( std::ostream& stream, const T& head, Tail... tail ) - { - stream << head; - build_string( stream, tail... ); - } +template static void build_string(std::ostream &stream, const T &head, Tail... tail) { + stream << head; + build_string(stream, tail...); } +} // namespace detail -template< typename... Tail > -static std::string build_string( Tail... tail ) -{ +template static std::string build_string(Tail... tail) { std::ostringstream os; - detail::build_string( os, tail... ); + detail::build_string(os, tail...); return os.str(); } // some sort of error in the music data... // only use during parse, not run-time use, and bear in mid that data is zapped after error message, so exit any loops immediately // -static void Music_Parse_Error( gsl::czstring filename, const std::string& error ) -{ - std::string message = build_string( - S_COLOR_RED "Error parsing music data (in \"", filename, "\"):\n", - error , "\n" - ); - Com_Printf( "%s", message.c_str() ); +static void Music_Parse_Error(gsl::czstring filename, const std::string &error) { + std::string message = build_string(S_COLOR_RED "Error parsing music data (in \"", filename, "\"):\n", error, "\n"); + Com_Printf("%s", message.c_str()); MusicData->clear(); } // something to just mention if interested... // -static void Music_Parse_Warning( const std::string& error ) -{ +static void Music_Parse_Warning(const std::string &error) { extern cvar_t *s_debugdynamic; - if( s_debugdynamic && s_debugdynamic->integer ) - { - Com_Printf( S_COLOR_YELLOW "%s", error.c_str() ); + if (s_debugdynamic && s_debugdynamic->integer) { + Com_Printf(S_COLOR_YELLOW "%s", error.c_str()); } } @@ -160,58 +143,77 @@ static void Music_Parse_Warning( const std::string& error ) // Unfortunately two of the places that calls this doesn't have much other access to the state other than // a string, not an enum, so for those cases they only pass in BOSS or EXPLORE, so don't rely on it totally. // -static const char *Music_BuildFileName(const char *psFileNameBase, MusicState_e eMusicState ) -{ +static const char *Music_BuildFileName(const char *psFileNameBase, MusicState_e eMusicState) { static sstring_t sFileName; - //HACK! - if (eMusicState == eBGRNDTRACK_DEATH) - { + // HACK! + if (eMusicState == eBGRNDTRACK_DEATH) { return "music/death_music.mp3"; } const char *psDirName = (eMusicState == eBGRNDTRACK_BOSS) ? gsLevelNameForBossLoad.c_str() : gsLevelNameForLoad.c_str(); - sFileName = va("music/%s/%s.mp3",psDirName,psFileNameBase); + sFileName = va("music/%s/%s.mp3", psDirName, psFileNameBase); return sFileName.c_str(); } // this MUST return NULL for non-base states unless doing debug-query -const char *Music_BaseStateToString( MusicState_e eMusicState, qboolean bDebugPrintQuery /* = qfalse */ ) -{ - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: return "explore"; - case eBGRNDTRACK_ACTION: return "action"; - case eBGRNDTRACK_BOSS: return "boss"; - case eBGRNDTRACK_SILENCE: return "silence"; // not used in this module, but snd_dma uses it now it's de-static'd - case eBGRNDTRACK_DEATH: return "death"; - - // info only, not map<> lookup keys (unlike above)... - // - case eBGRNDTRACK_ACTIONTRANS0: if (bDebugPrintQuery) return "action_tr0"; - case eBGRNDTRACK_ACTIONTRANS1: if (bDebugPrintQuery) return "action_tr1"; - case eBGRNDTRACK_ACTIONTRANS2: if (bDebugPrintQuery) return "action_tr2"; - case eBGRNDTRACK_ACTIONTRANS3: if (bDebugPrintQuery) return "action_tr3"; - case eBGRNDTRACK_EXPLORETRANS0: if (bDebugPrintQuery) return "explore_tr0"; - case eBGRNDTRACK_EXPLORETRANS1: if (bDebugPrintQuery) return "explore_tr1"; - case eBGRNDTRACK_EXPLORETRANS2: if (bDebugPrintQuery) return "explore_tr2"; - case eBGRNDTRACK_EXPLORETRANS3: if (bDebugPrintQuery) return "explore_tr3"; - case eBGRNDTRACK_FADE: if (bDebugPrintQuery) return "fade"; - default: break; +const char *Music_BaseStateToString(MusicState_e eMusicState, qboolean bDebugPrintQuery /* = qfalse */) { + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: + return "explore"; + case eBGRNDTRACK_ACTION: + return "action"; + case eBGRNDTRACK_BOSS: + return "boss"; + case eBGRNDTRACK_SILENCE: + return "silence"; // not used in this module, but snd_dma uses it now it's de-static'd + case eBGRNDTRACK_DEATH: + return "death"; + + // info only, not map<> lookup keys (unlike above)... + // + case eBGRNDTRACK_ACTIONTRANS0: + if (bDebugPrintQuery) + return "action_tr0"; + case eBGRNDTRACK_ACTIONTRANS1: + if (bDebugPrintQuery) + return "action_tr1"; + case eBGRNDTRACK_ACTIONTRANS2: + if (bDebugPrintQuery) + return "action_tr2"; + case eBGRNDTRACK_ACTIONTRANS3: + if (bDebugPrintQuery) + return "action_tr3"; + case eBGRNDTRACK_EXPLORETRANS0: + if (bDebugPrintQuery) + return "explore_tr0"; + case eBGRNDTRACK_EXPLORETRANS1: + if (bDebugPrintQuery) + return "explore_tr1"; + case eBGRNDTRACK_EXPLORETRANS2: + if (bDebugPrintQuery) + return "explore_tr2"; + case eBGRNDTRACK_EXPLORETRANS3: + if (bDebugPrintQuery) + return "explore_tr3"; + case eBGRNDTRACK_FADE: + if (bDebugPrintQuery) + return "fade"; + default: + break; } return NULL; } -static qboolean Music_ParseMusic( gsl::czstring filename, const CGenericParser2& Parser, MusicData_t* MusicData, const CGPGroup& pgMusicFiles, const gsl::cstring_span& psMusicName, const gsl::cstring_span& psMusicNameKey, MusicState_e eMusicState ) -{ +static qboolean Music_ParseMusic(gsl::czstring filename, const CGenericParser2 &Parser, MusicData_t *MusicData, const CGPGroup &pgMusicFiles, + const gsl::cstring_span &psMusicName, const gsl::cstring_span &psMusicNameKey, MusicState_e eMusicState) { bool bReturn = false; MusicFile_t MusicFile; - const CGPGroup* const pgMusicFile = pgMusicFiles.FindSubGroup( psMusicName ); - if( pgMusicFile ) - { + const CGPGroup *const pgMusicFile = pgMusicFiles.FindSubGroup(psMusicName); + if (pgMusicFile) { // read subgroups... // bool bEntryFound = false; @@ -219,96 +221,80 @@ static qboolean Music_ParseMusic( gsl::czstring filename, const CGenericParser2& // // (read entry points first, so I can check exit points aren't too close in time) // - const CGPGroup* pEntryGroup = pgMusicFile->FindSubGroup( sKEY_ENTRY ); - if( pEntryGroup ) - { + const CGPGroup *pEntryGroup = pgMusicFile->FindSubGroup(sKEY_ENTRY); + if (pEntryGroup) { // read entry points... // - for( auto& prop : pEntryGroup->GetProperties() ) - { - //if( Q::substr( prop.GetName(), 0, sKEY_MARKER.size() ) == sKEY_MARKER ) // for now, assume anything is a marker + for (auto &prop : pEntryGroup->GetProperties()) { + // if( Q::substr( prop.GetName(), 0, sKEY_MARKER.size() ) == sKEY_MARKER ) // for now, assume anything is a marker { - MusicFile.MusicEntryTimes[ prop.GetName() ] = Q::svtoi( prop.GetTopValue() ); + MusicFile.MusicEntryTimes[prop.GetName()] = Q::svtoi(prop.GetTopValue()); bEntryFound = true; } } } - for( auto& group : pgMusicFile->GetSubGroups() ) - { - auto& groupName = group.GetName(); + for (auto &group : pgMusicFile->GetSubGroups()) { + auto &groupName = group.GetName(); - if( groupName == sKEY_ENTRY ) - { + if (groupName == sKEY_ENTRY) { // skip entry points, I've already read them in above // - } - else if( groupName == sKEY_EXIT ) - { - int iThisExitPointIndex = MusicFile.MusicExitPoints.size(); // must eval this first, so unaffected by push_back etc + } else if (groupName == sKEY_EXIT) { + int iThisExitPointIndex = MusicFile.MusicExitPoints.size(); // must eval this first, so unaffected by push_back etc // // read this set of exit points... // MusicExitPoint_t MusicExitPoint; - for( auto& prop : group.GetProperties() ) - { - auto& key = prop.GetName(); - auto& value = prop.GetTopValue(); + for (auto &prop : group.GetProperties()) { + auto &key = prop.GetName(); + auto &value = prop.GetTopValue(); - if( key == sKEY_NEXTFILE ) - { + if (key == sKEY_NEXTFILE) { MusicExitPoint.sNextFile = value; - bExitFound = true; // harmless to keep setting - } - else if( key == sKEY_NEXTMARK ) - { + bExitFound = true; // harmless to keep setting + } else if (key == sKEY_NEXTMARK) { MusicExitPoint.sNextMark = value; - } - else if( Q::substr( key, 0, sKEY_TIME.size() ) == sKEY_TIME ) - { + } else if (Q::substr(key, 0, sKEY_TIME.size()) == sKEY_TIME) { MusicExitTime_t MusicExitTime; - MusicExitTime.fTime = Q::svtof( value ); + MusicExitTime.fTime = Q::svtof(value); MusicExitTime.iExitPoint = iThisExitPointIndex; // new check, don't keep this this exit point if it's within 1.5 seconds either way of an entry point... // bool bTooCloseToEntryPoint = false; - for( auto& item : MusicFile.MusicEntryTimes ) - { + for (auto &item : MusicFile.MusicEntryTimes) { float fThisEntryTime = item.second; - if( Q_fabs( fThisEntryTime - MusicExitTime.fTime ) < 1.5f ) - { + if (Q_fabs(fThisEntryTime - MusicExitTime.fTime) < 1.5f) { // bTooCloseToEntryPoint = true; // not sure about this, ignore for now break; } } - if( !bTooCloseToEntryPoint ) - { - MusicFile.MusicExitTimes.push_back( MusicExitTime ); + if (!bTooCloseToEntryPoint) { + MusicFile.MusicExitTimes.push_back(MusicExitTime); } } } - MusicFile.MusicExitPoints.push_back( MusicExitPoint ); + MusicFile.MusicExitPoints.push_back(MusicExitPoint); int iNumExitPoints = MusicFile.MusicExitPoints.size(); // error checking... // - switch( eMusicState ) - { + switch (eMusicState) { case eBGRNDTRACK_EXPLORE: - if( iNumExitPoints > iMAX_EXPLORE_TRANSITIONS ) - { - Music_Parse_Error( filename, build_string( "\"", psMusicName, "\" has > ", iMAX_EXPLORE_TRANSITIONS, " ", psMusicNameKey, " transitions defined!\n" ) ); + if (iNumExitPoints > iMAX_EXPLORE_TRANSITIONS) { + Music_Parse_Error( + filename, build_string("\"", psMusicName, "\" has > ", iMAX_EXPLORE_TRANSITIONS, " ", psMusicNameKey, " transitions defined!\n")); return qfalse; } break; case eBGRNDTRACK_ACTION: - if( iNumExitPoints > iMAX_ACTION_TRANSITIONS ) - { - Music_Parse_Error( filename, build_string( "\"", psMusicName, "\" has > ", iMAX_ACTION_TRANSITIONS, " ", psMusicNameKey, " transitions defined!\n" ) ); + if (iNumExitPoints > iMAX_ACTION_TRANSITIONS) { + Music_Parse_Error( + filename, build_string("\"", psMusicName, "\" has > ", iMAX_ACTION_TRANSITIONS, " ", psMusicNameKey, " transitions defined!\n")); return qfalse; } break; @@ -316,7 +302,7 @@ static qboolean Music_ParseMusic( gsl::czstring filename, const CGenericParser2& case eBGRNDTRACK_BOSS: case eBGRNDTRACK_DEATH: - Music_Parse_Error( filename, build_string( "\"", psMusicName, "\" has ", psMusicNameKey, " transitions defined, this is not allowed!\n" ) ); + Music_Parse_Error(filename, build_string("\"", psMusicName, "\" has ", psMusicNameKey, " transitions defined, this is not allowed!\n")); return qfalse; default: break; @@ -329,29 +315,23 @@ static qboolean Music_ParseMusic( gsl::czstring filename, const CGenericParser2& bReturn = true; // boss & death pieces can omit entry/exit stuff - if( eMusicState != eBGRNDTRACK_BOSS && eMusicState != eBGRNDTRACK_DEATH ) - { - if( !bEntryFound ) - { - Music_Parse_Error( filename, build_string( "Unable to find subgroup \"", sKEY_ENTRY, "\" in group \"", psMusicName, "\"\n" ) ); + if (eMusicState != eBGRNDTRACK_BOSS && eMusicState != eBGRNDTRACK_DEATH) { + if (!bEntryFound) { + Music_Parse_Error(filename, build_string("Unable to find subgroup \"", sKEY_ENTRY, "\" in group \"", psMusicName, "\"\n")); bReturn = false; } - if( !bExitFound ) - { - Music_Parse_Error( filename, build_string( "Unable to find subgroup \"", sKEY_EXIT, "\" in group \"", psMusicName, "\"\n" ) ); + if (!bExitFound) { + Music_Parse_Error(filename, build_string("Unable to find subgroup \"", sKEY_EXIT, "\" in group \"", psMusicName, "\"\n")); bReturn = false; } } - } - else - { - Music_Parse_Error( filename, build_string( "Unable to find musicfiles entry \"", psMusicName, "\"\n" ) ); + } else { + Music_Parse_Error(filename, build_string("Unable to find musicfiles entry \"", psMusicName, "\"\n")); } - if( bReturn ) - { + if (bReturn) { MusicFile.sFileNameBase = psMusicName; - ( *MusicData )[ psMusicNameKey ] = MusicFile; + (*MusicData)[psMusicNameKey] = MusicFile; } return (qboolean)bReturn; @@ -362,17 +342,12 @@ static qboolean Music_ParseMusic( gsl::czstring filename, const CGenericParser2& // This just initialises the Lucas music structs so the background music player can interrogate them... // sstring_t gsLevelNameFromServer; -void Music_SetLevelName(const char *psLevelName) -{ - gsLevelNameFromServer = psLevelName; -} +void Music_SetLevelName(const char *psLevelName) { gsLevelNameFromServer = psLevelName; } -static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) -{ +static qboolean Music_ParseLeveldata(gsl::czstring psLevelName) { qboolean bReturn = qfalse; - if (MusicData == NULL) - { + if (MusicData == NULL) { // sorry vv, false leaks make it hard to find true leaks static MusicData_t singleton; MusicData = &singleton; @@ -380,8 +355,7 @@ static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) // already got this data? // - if (MusicData->size() && !Q_stricmp(psLevelName,gsLevelNameForCompare.c_str())) - { + if (MusicData->size() && !Q_stricmp(psLevelName, gsLevelNameForCompare.c_str())) { return qtrue; } @@ -389,70 +363,54 @@ static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) // shorten level name to MAX_QPATH so sstring's assignment assertion is satisfied. char sLevelName[MAX_QPATH]; - Q_strncpyz(sLevelName,psLevelName,sizeof(sLevelName)); + Q_strncpyz(sLevelName, psLevelName, sizeof(sLevelName)); - gsLevelNameForLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file - gsLevelNameForCompare = sLevelName; // harmless to init here even if we fail to parse dms.dat file - gsLevelNameForBossLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForCompare = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForBossLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file gsl::czstring filename = sFILENAME_DMS; CGenericParser2 Parser; - if( !Parser.Parse( filename ) ) - { - Music_Parse_Error( filename, "Error using GP to parse file\n" ); - } - else - { - const CGPGroup& pFileGroup = Parser.GetBaseParseGroup(); - const CGPGroup* pgMusicFiles = pFileGroup.FindSubGroup( sKEY_MUSICFILES ); - if( !pgMusicFiles ) - { - Music_Parse_Error(filename, build_string( "Unable to find subgroup \"", sKEY_MUSICFILES ,"\"\n" ) ); - } - else - { - const CGPGroup* pgLevelMusic = pFileGroup.FindSubGroup( sKEY_LEVELMUSIC ); - - if( !pgLevelMusic ) - { - Music_Parse_Error( filename, build_string( "Unable to find subgroup \"", sKEY_MUSICFILES, "\"\n" ) ); - } - else - { + if (!Parser.Parse(filename)) { + Music_Parse_Error(filename, "Error using GP to parse file\n"); + } else { + const CGPGroup &pFileGroup = Parser.GetBaseParseGroup(); + const CGPGroup *pgMusicFiles = pFileGroup.FindSubGroup(sKEY_MUSICFILES); + if (!pgMusicFiles) { + Music_Parse_Error(filename, build_string("Unable to find subgroup \"", sKEY_MUSICFILES, "\"\n")); + } else { + const CGPGroup *pgLevelMusic = pFileGroup.FindSubGroup(sKEY_LEVELMUSIC); + + if (!pgLevelMusic) { + Music_Parse_Error(filename, build_string("Unable to find subgroup \"", sKEY_MUSICFILES, "\"\n")); + } else { const CGPGroup *pgThisLevelMusic = nullptr; // // check for new USE keyword... // int steps = 0; - gsl::cstring_span searchName{ &sLevelName[ 0 ], &sLevelName[ strlen( &sLevelName[ 0 ] ) ] }; + gsl::cstring_span searchName{&sLevelName[0], &sLevelName[strlen(&sLevelName[0])]}; const int sanityLimit = 10; - while( !searchName.empty() && steps < sanityLimit ) - { + while (!searchName.empty() && steps < sanityLimit) { gsLevelNameForLoad = searchName; gsLevelNameForBossLoad = gsLevelNameForLoad; - pgThisLevelMusic = pgLevelMusic->FindSubGroup( searchName ); + pgThisLevelMusic = pgLevelMusic->FindSubGroup(searchName); - if( pgThisLevelMusic ) - { - const CGPProperty* pValue = pgThisLevelMusic->FindProperty( sKEY_USES ); - if( pValue ) - { + if (pgThisLevelMusic) { + const CGPProperty *pValue = pgThisLevelMusic->FindProperty(sKEY_USES); + if (pValue) { // re-search using the USE param... // searchName = pValue->GetTopValue(); steps++; // Com_DPrintf("Using \"%s\"\n",sSearchName.c_str()); - } - else - { + } else { // no new USE keyword found... // searchName = {}; } - } - else - { + } else { // level entry not found... // break; @@ -461,12 +419,9 @@ static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) // now go ahead and use the final music set we've decided on... // - if( !pgThisLevelMusic || steps >= sanityLimit ) - { - Music_Parse_Warning( build_string( "Unable to find entry for \"", sLevelName, "\" in \"", filename, "\"\n" ) ); - } - else - { + if (!pgThisLevelMusic || steps >= sanityLimit) { + Music_Parse_Warning(build_string("Unable to find entry for \"", sLevelName, "\" in \"", filename, "\"\n")); + } else { // these are optional fields, so see which ones we find... // gsl::cstring_span psName_Explore; @@ -474,153 +429,128 @@ static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) gsl::cstring_span psName_Boss; gsl::cstring_span psName_UseBoss; - for( auto& prop : pgThisLevelMusic->GetProperties() ) - { - auto& key = prop.GetName(); - auto& value = prop.GetTopValue(); + for (auto &prop : pgThisLevelMusic->GetProperties()) { + auto &key = prop.GetName(); + auto &value = prop.GetTopValue(); - if( Q::stricmp( value, sKEY_PLACEHOLDER ) == Q::Ordering::EQ ) - { + if (Q::stricmp(value, sKEY_PLACEHOLDER) == Q::Ordering::EQ) { // ignore "placeholder" items continue; } - if( Q::stricmp( key, sKEY_EXPLORE ) == Q::Ordering::EQ ) - { + if (Q::stricmp(key, sKEY_EXPLORE) == Q::Ordering::EQ) { psName_Explore = value; - } - else if( Q::stricmp( key, sKEY_ACTION ) == Q::Ordering::EQ ) - { + } else if (Q::stricmp(key, sKEY_ACTION) == Q::Ordering::EQ) { psName_Action = value; - } - else if( Q::stricmp( key, sKEY_USEBOSS ) == Q::Ordering::EQ ) - { + } else if (Q::stricmp(key, sKEY_USEBOSS) == Q::Ordering::EQ) { psName_UseBoss = value; - } - else if( Q::stricmp( key, sKEY_BOSS ) == Q::Ordering::EQ ) - { + } else if (Q::stricmp(key, sKEY_BOSS) == Q::Ordering::EQ) { psName_Boss = value; } } - bReturn = qtrue; // defualt to ON now, so I can turn it off if "useboss" fails + bReturn = qtrue; // defualt to ON now, so I can turn it off if "useboss" fails - if( !psName_UseBoss.empty() ) - { - const CGPGroup *pgLevelMusicOfBoss = pgLevelMusic->FindSubGroup( psName_UseBoss ); - if( !pgLevelMusicOfBoss ) - { - Music_Parse_Error( filename, build_string( "Unable to find 'useboss' entry \"", psName_UseBoss, "\"\n", psName_UseBoss ) ); + if (!psName_UseBoss.empty()) { + const CGPGroup *pgLevelMusicOfBoss = pgLevelMusic->FindSubGroup(psName_UseBoss); + if (!pgLevelMusicOfBoss) { + Music_Parse_Error(filename, build_string("Unable to find 'useboss' entry \"", psName_UseBoss, "\"\n", psName_UseBoss)); bReturn = qfalse; - } - else - { - const CGPProperty *pValueBoss = pgLevelMusicOfBoss->FindProperty( sKEY_BOSS ); - if( !pValueBoss ) - { - Music_Parse_Error( filename, build_string( "'useboss' \"", psName_UseBoss, "\" has no \"boss\" entry!\n" ) ); + } else { + const CGPProperty *pValueBoss = pgLevelMusicOfBoss->FindProperty(sKEY_BOSS); + if (!pValueBoss) { + Music_Parse_Error(filename, build_string("'useboss' \"", psName_UseBoss, "\" has no \"boss\" entry!\n")); bReturn = qfalse; - } - else - { + } else { psName_Boss = pValueBoss->GetTopValue(); gsLevelNameForBossLoad = psName_UseBoss; } } } - // done this way in case I want to conditionally pass any bools depending on music type... // - if( bReturn && psName_Explore.length() ) - { - bReturn = Music_ParseMusic( filename, Parser, MusicData, *pgMusicFiles, psName_Explore, sKEY_EXPLORE, eBGRNDTRACK_EXPLORE ); + if (bReturn && psName_Explore.length()) { + bReturn = Music_ParseMusic(filename, Parser, MusicData, *pgMusicFiles, psName_Explore, sKEY_EXPLORE, eBGRNDTRACK_EXPLORE); } - if( bReturn && psName_Action.length() ) - { - bReturn = Music_ParseMusic( filename, Parser, MusicData, *pgMusicFiles, psName_Action, sKEY_ACTION, eBGRNDTRACK_ACTION ); + if (bReturn && psName_Action.length()) { + bReturn = Music_ParseMusic(filename, Parser, MusicData, *pgMusicFiles, psName_Action, sKEY_ACTION, eBGRNDTRACK_ACTION); } - if( bReturn && psName_Boss.length() ) - { - bReturn = Music_ParseMusic( filename, Parser, MusicData, *pgMusicFiles, psName_Boss, sKEY_BOSS, eBGRNDTRACK_BOSS ); + if (bReturn && psName_Boss.length()) { + bReturn = Music_ParseMusic(filename, Parser, MusicData, *pgMusicFiles, psName_Boss, sKEY_BOSS, eBGRNDTRACK_BOSS); } - if( bReturn /*&& psName_Death*/ ) // LAST MINUTE HACK!!, always force in some death music!!!! + if (bReturn /*&& psName_Death*/) // LAST MINUTE HACK!!, always force in some death music!!!! { - //bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Death, sKEY_DEATH, eBGRNDTRACK_DEATH); + // bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Death, sKEY_DEATH, eBGRNDTRACK_DEATH); MusicFile_t m; m.sFileNameBase = "death_music"; - ( *MusicData )[ sKEY_DEATH ] = m; + (*MusicData)[sKEY_DEATH] = m; } } } } } - if (bReturn) - { + if (bReturn) { // sort exit points, and do some error checking... // - for (MusicData_t::iterator itMusicData = MusicData->begin(); itMusicData != MusicData->end(); ++itMusicData) - { - const char *psMusicStateType = (*itMusicData).first.c_str(); - MusicFile_t &MusicFile = (*itMusicData).second; + for (MusicData_t::iterator itMusicData = MusicData->begin(); itMusicData != MusicData->end(); ++itMusicData) { + const char *psMusicStateType = (*itMusicData).first.c_str(); + MusicFile_t &MusicFile = (*itMusicData).second; // kludge up an enum, only interested in boss or not at the moment, so... // - MusicState_e eMusicState = !Q_stricmp(psMusicStateType,"boss") ? eBGRNDTRACK_BOSS : !Q_stricmp(psMusicStateType,"death") ? eBGRNDTRACK_DEATH : eBGRNDTRACK_EXPLORE; + MusicState_e eMusicState = !Q_stricmp(psMusicStateType, "boss") ? eBGRNDTRACK_BOSS + : !Q_stricmp(psMusicStateType, "death") ? eBGRNDTRACK_DEATH + : eBGRNDTRACK_EXPLORE; - if (!MusicFile.MusicExitTimes.empty()) - { - sort(MusicFile.MusicExitTimes.begin(),MusicFile.MusicExitTimes.end()); + if (!MusicFile.MusicExitTimes.empty()) { + sort(MusicFile.MusicExitTimes.begin(), MusicFile.MusicExitTimes.end()); } // check music exists... // - const char *psMusicFileName = Music_BuildFileName( MusicFile.sFileNameBase.c_str(), eMusicState ); - if (!S_FileExists( psMusicFileName )) - { - Music_Parse_Error( filename, build_string( "Music file \"", psMusicFileName, "\" not found!\n" ) ); - return qfalse; // have to return, because music data destroyed now + const char *psMusicFileName = Music_BuildFileName(MusicFile.sFileNameBase.c_str(), eMusicState); + if (!S_FileExists(psMusicFileName)) { + Music_Parse_Error(filename, build_string("Music file \"", psMusicFileName, "\" not found!\n")); + return qfalse; // have to return, because music data destroyed now } // check all transition music pieces exist, and that entry points into new pieces after transitions also exist... // - for (size_t iExitPoint=0; iExitPoint < MusicFile.MusicExitPoints.size(); iExitPoint++) - { - MusicExitPoint_t &MusicExitPoint = MusicFile.MusicExitPoints[ iExitPoint ]; - - const char *psTransitionFileName = Music_BuildFileName( MusicExitPoint.sNextFile.c_str(), eMusicState ); - if (!S_FileExists( psTransitionFileName )) - { - Music_Parse_Error( filename, build_string( "Transition file \"", psTransitionFileName, "\" (entry \"", MusicExitPoint.sNextFile.c_str(), "\" ) not found!\n" ) ); - return qfalse; // have to return, because music data destroyed now + for (size_t iExitPoint = 0; iExitPoint < MusicFile.MusicExitPoints.size(); iExitPoint++) { + MusicExitPoint_t &MusicExitPoint = MusicFile.MusicExitPoints[iExitPoint]; + + const char *psTransitionFileName = Music_BuildFileName(MusicExitPoint.sNextFile.c_str(), eMusicState); + if (!S_FileExists(psTransitionFileName)) { + Music_Parse_Error(filename, build_string("Transition file \"", psTransitionFileName, "\" (entry \"", MusicExitPoint.sNextFile.c_str(), + "\" ) not found!\n")); + return qfalse; // have to return, because music data destroyed now } const char *psNextMark = MusicExitPoint.sNextMark.c_str(); - if (strlen(psNextMark)) // always NZ ptr + if (strlen(psNextMark)) // always NZ ptr { // then this must be "action" music under current rules... // - assert( !strcmp(psMusicStateType, Music_BaseStateToString(eBGRNDTRACK_ACTION) ? Music_BaseStateToString(eBGRNDTRACK_ACTION):"") ); + assert(!strcmp(psMusicStateType, Music_BaseStateToString(eBGRNDTRACK_ACTION) ? Music_BaseStateToString(eBGRNDTRACK_ACTION) : "")); // // does this marker exist in the explore piece? // - MusicData_t::iterator itExploreMusicData = MusicData->find( Music_BaseStateToString(eBGRNDTRACK_EXPLORE) ); - if (itExploreMusicData != MusicData->end()) - { + MusicData_t::iterator itExploreMusicData = MusicData->find(Music_BaseStateToString(eBGRNDTRACK_EXPLORE)); + if (itExploreMusicData != MusicData->end()) { MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; - if (!MusicFile_Explore.MusicEntryTimes.count(psNextMark)) - { - Music_Parse_Error( filename, build_string( "Unable to find entry point \"", psNextMark, "\" in description for \"", MusicFile_Explore.sFileNameBase.c_str(), "\"\n" ) ); - return qfalse; // have to return, because music data destroyed now + if (!MusicFile_Explore.MusicEntryTimes.count(psNextMark)) { + Music_Parse_Error(filename, build_string("Unable to find entry point \"", psNextMark, "\" in description for \"", + MusicFile_Explore.sFileNameBase.c_str(), "\"\n")); + return qfalse; // have to return, because music data destroyed now } - } - else - { - Music_Parse_Error( filename, build_string( "Unable to find ", Music_BaseStateToString( eBGRNDTRACK_EXPLORE ), " piece to match \"", MusicFile.sFileNameBase.c_str(), "\"\n" ) ); - return qfalse; // have to return, because music data destroyed now + } else { + Music_Parse_Error(filename, build_string("Unable to find ", Music_BaseStateToString(eBGRNDTRACK_EXPLORE), " piece to match \"", + MusicFile.sFileNameBase.c_str(), "\"\n")); + return qfalse; // have to return, because music data destroyed now } } } @@ -630,14 +560,12 @@ static qboolean Music_ParseLeveldata( gsl::czstring psLevelName ) return bReturn; } - // returns ptr to music file, or NULL for error/missing... // -static MusicFile_t *Music_GetBaseMusicFile( const char *psMusicState ) // where psMusicState is (eg) "explore", "action" or "boss" +static MusicFile_t *Music_GetBaseMusicFile(const char *psMusicState) // where psMusicState is (eg) "explore", "action" or "boss" { - MusicData_t::iterator it = MusicData->find( psMusicState ); - if (it != MusicData->end()) - { + MusicData_t::iterator it = MusicData->find(psMusicState); + if (it != MusicData->end()) { MusicFile_t *pMusicFile = &(*it).second; return pMusicFile; } @@ -645,109 +573,92 @@ static MusicFile_t *Music_GetBaseMusicFile( const char *psMusicState ) // where return NULL; } -static MusicFile_t *Music_GetBaseMusicFile( MusicState_e eMusicState ) -{ - const char *psMusicStateString = Music_BaseStateToString( eMusicState ); - if ( psMusicStateString ) - { - return Music_GetBaseMusicFile( psMusicStateString ); +static MusicFile_t *Music_GetBaseMusicFile(MusicState_e eMusicState) { + const char *psMusicStateString = Music_BaseStateToString(eMusicState); + if (psMusicStateString) { + return Music_GetBaseMusicFile(psMusicStateString); } return NULL; } - // where label is (eg) "kejim_base"... // -qboolean Music_DynamicDataAvailable(const char *psDynamicMusicLabel) -{ +qboolean Music_DynamicDataAvailable(const char *psDynamicMusicLabel) { char sLevelName[MAX_QPATH]; - Q_strncpyz(sLevelName,COM_SkipPath( const_cast( (psDynamicMusicLabel&&psDynamicMusicLabel[0])?psDynamicMusicLabel:gsLevelNameFromServer.c_str() ) ),sizeof(sLevelName)); + Q_strncpyz(sLevelName, + COM_SkipPath(const_cast((psDynamicMusicLabel && psDynamicMusicLabel[0]) ? psDynamicMusicLabel : gsLevelNameFromServer.c_str())), + sizeof(sLevelName)); Q_strlwr(sLevelName); - if (strlen(sLevelName)) // avoid error messages when there's no music waiting to be played and we try and restart it... + if (strlen(sLevelName)) // avoid error messages when there's no music waiting to be played and we try and restart it... { - if (Music_ParseLeveldata(sLevelName)) - { - return (qboolean)(Music_GetBaseMusicFile(eBGRNDTRACK_EXPLORE) && - Music_GetBaseMusicFile(eBGRNDTRACK_ACTION)); + if (Music_ParseLeveldata(sLevelName)) { + return (qboolean)(Music_GetBaseMusicFile(eBGRNDTRACK_EXPLORE) && Music_GetBaseMusicFile(eBGRNDTRACK_ACTION)); } } return qfalse; } -const char *Music_GetFileNameForState( MusicState_e eMusicState) -{ +const char *Music_GetFileNameForState(MusicState_e eMusicState) { MusicFile_t *pMusicFile = NULL; - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: - case eBGRNDTRACK_ACTION: - case eBGRNDTRACK_BOSS: - case eBGRNDTRACK_DEATH: - - pMusicFile = Music_GetBaseMusicFile( eMusicState ); - if (pMusicFile) - { - return Music_BuildFileName( pMusicFile->sFileNameBase.c_str(), eMusicState ); - } - break; - - case eBGRNDTRACK_ACTIONTRANS0: - case eBGRNDTRACK_ACTIONTRANS1: - case eBGRNDTRACK_ACTIONTRANS2: - case eBGRNDTRACK_ACTIONTRANS3: - - pMusicFile = Music_GetBaseMusicFile( eBGRNDTRACK_ACTION ); - if (pMusicFile) - { - size_t iTransNum = eMusicState - eBGRNDTRACK_ACTIONTRANS0; - if (iTransNum < pMusicFile->MusicExitPoints.size()) - { - return Music_BuildFileName( pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState ); - } + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: + case eBGRNDTRACK_ACTION: + case eBGRNDTRACK_BOSS: + case eBGRNDTRACK_DEATH: + + pMusicFile = Music_GetBaseMusicFile(eMusicState); + if (pMusicFile) { + return Music_BuildFileName(pMusicFile->sFileNameBase.c_str(), eMusicState); + } + break; + + case eBGRNDTRACK_ACTIONTRANS0: + case eBGRNDTRACK_ACTIONTRANS1: + case eBGRNDTRACK_ACTIONTRANS2: + case eBGRNDTRACK_ACTIONTRANS3: + + pMusicFile = Music_GetBaseMusicFile(eBGRNDTRACK_ACTION); + if (pMusicFile) { + size_t iTransNum = eMusicState - eBGRNDTRACK_ACTIONTRANS0; + if (iTransNum < pMusicFile->MusicExitPoints.size()) { + return Music_BuildFileName(pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState); } - break; - - case eBGRNDTRACK_EXPLORETRANS0: - case eBGRNDTRACK_EXPLORETRANS1: - case eBGRNDTRACK_EXPLORETRANS2: - case eBGRNDTRACK_EXPLORETRANS3: - - pMusicFile = Music_GetBaseMusicFile( eBGRNDTRACK_EXPLORE ); - if (pMusicFile) - { - size_t iTransNum = eMusicState - eBGRNDTRACK_EXPLORETRANS0; - if (iTransNum < pMusicFile->MusicExitPoints.size()) - { - return Music_BuildFileName( pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState ); - } + } + break; + + case eBGRNDTRACK_EXPLORETRANS0: + case eBGRNDTRACK_EXPLORETRANS1: + case eBGRNDTRACK_EXPLORETRANS2: + case eBGRNDTRACK_EXPLORETRANS3: + + pMusicFile = Music_GetBaseMusicFile(eBGRNDTRACK_EXPLORE); + if (pMusicFile) { + size_t iTransNum = eMusicState - eBGRNDTRACK_EXPLORETRANS0; + if (iTransNum < pMusicFile->MusicExitPoints.size()) { + return Music_BuildFileName(pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState); } - break; - - default: - #ifndef FINAL_BUILD - assert(0); // duh....what state are they asking for? - Com_Printf( S_COLOR_RED "Music_GetFileNameForState( %d ) unhandled case!\n",eMusicState ); - #endif - break; + } + break; + + default: +#ifndef FINAL_BUILD + assert(0); // duh....what state are they asking for? + Com_Printf(S_COLOR_RED "Music_GetFileNameForState( %d ) unhandled case!\n", eMusicState); +#endif + break; } return NULL; } - - -qboolean Music_StateIsTransition( MusicState_e eMusicState ) -{ - return (qboolean)(eMusicState >= eBGRNDTRACK_FIRSTTRANSITION && - eMusicState <= eBGRNDTRACK_LASTTRANSITION); +qboolean Music_StateIsTransition(MusicState_e eMusicState) { + return (qboolean)(eMusicState >= eBGRNDTRACK_FIRSTTRANSITION && eMusicState <= eBGRNDTRACK_LASTTRANSITION); } - -qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e eProposedMusicState ) -{ +qboolean Music_StateCanBeInterrupted(MusicState_e eMusicState, MusicState_e eProposedMusicState) { // death music can interrupt anything... // if (eProposedMusicState == eBGRNDTRACK_DEATH) @@ -755,8 +666,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // // ... and can't be interrupted once started...(though it will internally-switch to silence at the end, rather than loop) // - if (eMusicState == eBGRNDTRACK_DEATH) - { + if (eMusicState == eBGRNDTRACK_DEATH) { return qfalse; } @@ -767,8 +677,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // // ... and can't be interrupted once started... // - if (eMusicState == eBGRNDTRACK_BOSS) - { + if (eMusicState == eBGRNDTRACK_BOSS) { // ...except by silence (or death, but again, that's already handled above) // if (eProposedMusicState == eBGRNDTRACK_SILENCE) @@ -784,7 +693,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // nothing can interrupt a transition (after above filters)... // - if (Music_StateIsTransition( eMusicState )) + if (Music_StateIsTransition(eMusicState)) return qfalse; // current state is therefore interruptable... @@ -792,8 +701,6 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr return qtrue; } - - // returns qtrue if music is allowed to transition out of current state, based on current play position... // (doesn't bother returning final state after transition (eg action->transition->explore) becuase it's fairly obvious) // @@ -807,143 +714,119 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // enum of transition track to switch to // float time of entry point of new track *after* transition // -qboolean Music_AllowedToTransition( float fPlayingTimeElapsed, - MusicState_e eMusicState, - // - MusicState_e *peTransition /* = NULL */, - float *pfNewTrackEntryTime /* = NULL */ - ) -{ - const float fTimeEpsilon = 0.3f; // arb., how close we have to be to an exit point to take it. - // if set too high then music change is sloppy - // if set too low[/precise] then we might miss an exit if client fps is poor - - - MusicFile_t *pMusicFile = Music_GetBaseMusicFile( eMusicState ); - if (pMusicFile && !pMusicFile->MusicExitTimes.empty()) - { - MusicExitTime_t T; - T.fTime = fPlayingTimeElapsed; +qboolean Music_AllowedToTransition(float fPlayingTimeElapsed, MusicState_e eMusicState, + // + MusicState_e *peTransition /* = NULL */, float *pfNewTrackEntryTime /* = NULL */ +) { + const float fTimeEpsilon = 0.3f; // arb., how close we have to be to an exit point to take it. + // if set too high then music change is sloppy + // if set too low[/precise] then we might miss an exit if client fps is poor + + MusicFile_t *pMusicFile = Music_GetBaseMusicFile(eMusicState); + if (pMusicFile && !pMusicFile->MusicExitTimes.empty()) { + MusicExitTime_t T; + T.fTime = fPlayingTimeElapsed; // since a MusicExitTimes_t item is a sorted array, we can use the equal_range algorithm... // - std::pair itp = equal_range( pMusicFile->MusicExitTimes.begin(), pMusicFile->MusicExitTimes.end(), T); + std::pair itp = + equal_range(pMusicFile->MusicExitTimes.begin(), pMusicFile->MusicExitTimes.end(), T); if (itp.first != pMusicFile->MusicExitTimes.begin()) - itp.first--; // encompass the one before, in case we've just missed an exit point by < fTimeEpsilon - if (itp.second!= pMusicFile->MusicExitTimes.end()) - itp.second++; // increase range to one beyond, so we can do normal STL being/end looping below - for (MusicExitTimes_t::iterator it = itp.first; it != itp.second; ++it) - { + itp.first--; // encompass the one before, in case we've just missed an exit point by < fTimeEpsilon + if (itp.second != pMusicFile->MusicExitTimes.end()) + itp.second++; // increase range to one beyond, so we can do normal STL being/end looping below + for (MusicExitTimes_t::iterator it = itp.first; it != itp.second; ++it) { MusicExitTimes_t::iterator pExitTime = it; - if ( Q_fabs(pExitTime->fTime - fPlayingTimeElapsed) <= fTimeEpsilon ) - { + if (Q_fabs(pExitTime->fTime - fPlayingTimeElapsed) <= fTimeEpsilon) { // got an exit point!, work out feedback params... // size_t iExitPoint = pExitTime->iExitPoint; // // the two params to give back... // - MusicState_e eFeedBackTransition = eBGRNDTRACK_EXPLORETRANS0; // any old default - float fFeedBackNewTrackEntryTime = 0.0f; + MusicState_e eFeedBackTransition = eBGRNDTRACK_EXPLORETRANS0; // any old default + float fFeedBackNewTrackEntryTime = 0.0f; // // check legality in case of crap data... // - if (iExitPoint < pMusicFile->MusicExitPoints.size()) - { - MusicExitPoint_t &ExitPoint = pMusicFile->MusicExitPoints[ iExitPoint ]; + if (iExitPoint < pMusicFile->MusicExitPoints.size()) { + MusicExitPoint_t &ExitPoint = pMusicFile->MusicExitPoints[iExitPoint]; - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: - { - assert(iExitPoint < iMAX_EXPLORE_TRANSITIONS); // already been checked, but sanity - assert(!ExitPoint.sNextMark.c_str()[0]); // simple error checking, but harmless if tripped. explore transitions go to silence, hence no entry time for [silence] state after transition + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: { + assert(iExitPoint < iMAX_EXPLORE_TRANSITIONS); // already been checked, but sanity + assert(!ExitPoint.sNextMark.c_str()[0]); // simple error checking, but harmless if tripped. explore transitions go to silence, hence no + // entry time for [silence] state after transition - eFeedBackTransition = (MusicState_e) (eBGRNDTRACK_EXPLORETRANS0 + iExitPoint); - } - break; + eFeedBackTransition = (MusicState_e)(eBGRNDTRACK_EXPLORETRANS0 + iExitPoint); + } break; - case eBGRNDTRACK_ACTION: - { - assert(iExitPoint < iMAX_ACTION_TRANSITIONS); // already been checked, but sanity + case eBGRNDTRACK_ACTION: { + assert(iExitPoint < iMAX_ACTION_TRANSITIONS); // already been checked, but sanity - // if there's an entry marker point defined... + // if there's an entry marker point defined... + // + if (ExitPoint.sNextMark.c_str()[0]) { + MusicData_t::iterator itExploreMusicData = MusicData->find(Music_BaseStateToString(eBGRNDTRACK_EXPLORE)); + // + // find "explore" music... // - if (ExitPoint.sNextMark.c_str()[0]) - { - MusicData_t::iterator itExploreMusicData = MusicData->find( Music_BaseStateToString(eBGRNDTRACK_EXPLORE) ); + if (itExploreMusicData != MusicData->end()) { + MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; // - // find "explore" music... + // find the entry marker within the music and read the time there... // - if (itExploreMusicData != MusicData->end()) - { - MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; - // - // find the entry marker within the music and read the time there... - // - MusicEntryTimes_t::iterator itEntryTime = MusicFile_Explore.MusicEntryTimes.find( ExitPoint.sNextMark.c_str() ); - if (itEntryTime != MusicFile_Explore.MusicEntryTimes.end()) - { - fFeedBackNewTrackEntryTime = (*itEntryTime).second; - eFeedBackTransition = (MusicState_e) (eBGRNDTRACK_ACTIONTRANS0 + iExitPoint); - } - else - { - #ifndef FINAL_BUILD - assert(0); // sanity, should have been caught elsewhere, but harmless to do this - Com_Printf( S_COLOR_RED "Music_AllowedToTransition() unable to find entry marker \"%s\" in \"%s\"",ExitPoint.sNextMark.c_str(), MusicFile_Explore.sFileNameBase.c_str()); - #endif - return qfalse; - } - } - else - { - #ifndef FINAL_BUILD - assert(0); // sanity, should have been caught elsewhere, but harmless to do this - Com_Printf( S_COLOR_RED "Music_AllowedToTransition() unable to find %s version of \"%s\"\n",Music_BaseStateToString(eBGRNDTRACK_EXPLORE), pMusicFile->sFileNameBase.c_str()); - #endif + MusicEntryTimes_t::iterator itEntryTime = MusicFile_Explore.MusicEntryTimes.find(ExitPoint.sNextMark.c_str()); + if (itEntryTime != MusicFile_Explore.MusicEntryTimes.end()) { + fFeedBackNewTrackEntryTime = (*itEntryTime).second; + eFeedBackTransition = (MusicState_e)(eBGRNDTRACK_ACTIONTRANS0 + iExitPoint); + } else { +#ifndef FINAL_BUILD + assert(0); // sanity, should have been caught elsewhere, but harmless to do this + Com_Printf(S_COLOR_RED "Music_AllowedToTransition() unable to find entry marker \"%s\" in \"%s\"", + ExitPoint.sNextMark.c_str(), MusicFile_Explore.sFileNameBase.c_str()); +#endif return qfalse; } + } else { +#ifndef FINAL_BUILD + assert(0); // sanity, should have been caught elsewhere, but harmless to do this + Com_Printf(S_COLOR_RED "Music_AllowedToTransition() unable to find %s version of \"%s\"\n", + Music_BaseStateToString(eBGRNDTRACK_EXPLORE), pMusicFile->sFileNameBase.c_str()); +#endif + return qfalse; } - else - { - eFeedBackTransition = eBGRNDTRACK_ACTIONTRANS0; - fFeedBackNewTrackEntryTime = 0.0f; // already set to this, but FYI - } + } else { + eFeedBackTransition = eBGRNDTRACK_ACTIONTRANS0; + fFeedBackNewTrackEntryTime = 0.0f; // already set to this, but FYI } - break; + } break; - default: - { - #ifndef FINAL_BUILD - assert(0); - Com_Printf( S_COLOR_RED "Music_AllowedToTransition(): No code to transition from music type %d\n",eMusicState); - #endif - return qfalse; - } - break; + default: { +#ifndef FINAL_BUILD + assert(0); + Com_Printf(S_COLOR_RED "Music_AllowedToTransition(): No code to transition from music type %d\n", eMusicState); +#endif + return qfalse; + } break; } - } - else - { - #ifndef FINAL_BUILD + } else { +#ifndef FINAL_BUILD assert(0); - Com_Printf( S_COLOR_RED "Music_AllowedToTransition(): Illegal exit point %d, max = %d (music: \"%s\")\n",iExitPoint, pMusicFile->MusicExitPoints.size()-1, pMusicFile->sFileNameBase.c_str() ); - #endif + Com_Printf(S_COLOR_RED "Music_AllowedToTransition(): Illegal exit point %d, max = %d (music: \"%s\")\n", iExitPoint, + pMusicFile->MusicExitPoints.size() - 1, pMusicFile->sFileNameBase.c_str()); +#endif return qfalse; } - // feed back answers... // - if ( peTransition) - { + if (peTransition) { *peTransition = eFeedBackTransition; } - if ( pfNewTrackEntryTime ) - { + if (pfNewTrackEntryTime) { *pfNewTrackEntryTime = fFeedBackNewTrackEntryTime; } @@ -955,18 +838,15 @@ qboolean Music_AllowedToTransition( float fPlayingTimeElapsed, return qfalse; } - // typically used to get a (predefined) random entry point for the action music, but will work on any defined type with entry points, // defaults safely to 0.0f if no info available... // -float Music_GetRandomEntryTime( MusicState_e eMusicState ) -{ - MusicData_t::iterator itMusicData = MusicData->find( Music_BaseStateToString( eMusicState ) ); - if (itMusicData != MusicData->end()) - { +float Music_GetRandomEntryTime(MusicState_e eMusicState) { + MusicData_t::iterator itMusicData = MusicData->find(Music_BaseStateToString(eMusicState)); + if (itMusicData != MusicData->end()) { MusicFile_t &MusicFile = (*itMusicData).second; - if (MusicFile.MusicEntryTimes.size()) // make sure at least one defined, else default to start + if (MusicFile.MusicEntryTimes.size()) // make sure at least one defined, else default to start { // Quake's random number generator isn't very good, so instead of this: // @@ -974,23 +854,20 @@ float Music_GetRandomEntryTime( MusicState_e eMusicState ) // // ... I'll do this (ensuring we don't get the same result on two consecutive calls, but without while-loop)... // - static int iPrevRandomNumber = -1; - static int iCallCount = 0; - iCallCount++; - int iRandomEntryNum = (rand()+iCallCount) % (MusicFile.MusicEntryTimes.size()); // legal range - if (iRandomEntryNum == iPrevRandomNumber && MusicFile.MusicEntryTimes.size()>1) - { + static int iPrevRandomNumber = -1; + static int iCallCount = 0; + iCallCount++; + int iRandomEntryNum = (rand() + iCallCount) % (MusicFile.MusicEntryTimes.size()); // legal range + if (iRandomEntryNum == iPrevRandomNumber && MusicFile.MusicEntryTimes.size() > 1) { iRandomEntryNum += 1; iRandomEntryNum %= (MusicFile.MusicEntryTimes.size()); } iPrevRandomNumber = iRandomEntryNum; -// OutputDebugString(va("Music_GetRandomEntryTime(): Entry %d\n",iRandomEntryNum)); + // OutputDebugString(va("Music_GetRandomEntryTime(): Entry %d\n",iRandomEntryNum)); - for (MusicEntryTimes_t::iterator itEntryTime = MusicFile.MusicEntryTimes.begin(); itEntryTime != MusicFile.MusicEntryTimes.end(); ++itEntryTime) - { - if (!iRandomEntryNum--) - { + for (MusicEntryTimes_t::iterator itEntryTime = MusicFile.MusicEntryTimes.begin(); itEntryTime != MusicFile.MusicEntryTimes.end(); ++itEntryTime) { + if (!iRandomEntryNum--) { return (*itEntryTime).second; } } @@ -1002,17 +879,14 @@ float Music_GetRandomEntryTime( MusicState_e eMusicState ) // info only, used in "soundinfo" command... // -const char *Music_GetLevelSetName(void) -{ - if (Q_stricmp(gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str())) - { +const char *Music_GetLevelSetName(void) { + if (Q_stricmp(gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str())) { // music remap via USES command... // - return va("%s -> %s",gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str()); + return va("%s -> %s", gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str()); } return gsLevelNameForLoad.c_str(); } ///////////////// eof ///////////////////// - diff --git a/code/client/vmachine.cpp b/code/client/vmachine.cpp index 0ee1464468..3df78c536f 100644 --- a/code/client/vmachine.cpp +++ b/code/client/vmachine.cpp @@ -32,18 +32,17 @@ VIRTUAL MACHINE ============================================================== */ -intptr_t VM_Call( int callnum, ... ) -{ - intptr_t args[8] = { 0 }; +intptr_t VM_Call(int callnum, ...) { + intptr_t args[8] = {0}; va_list ap; - if ( cgvm.entryPoint ) { - va_start( ap, callnum ); - for ( size_t i = 0; i < ARRAY_LEN( args ); i++ ) - args[i] = va_arg( ap, intptr_t ); + if (cgvm.entryPoint) { + va_start(ap, callnum); + for (size_t i = 0; i < ARRAY_LEN(args); i++) + args[i] = va_arg(ap, intptr_t); va_end(ap); - return cgvm.entryPoint( callnum, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] ); + return cgvm.entryPoint(callnum, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); } return -1; } @@ -63,9 +62,9 @@ intptr_t VM_Call( int callnum, ... ) // works on. Rather than add the performance hit for those platforms, the original code is still in use there. // For speed, we just grab 9 arguments, and don't worry about exactly how many the syscall actually needs; the extra is // thrown away. -extern intptr_t CL_CgameSystemCalls( intptr_t *args ); +extern intptr_t CL_CgameSystemCalls(intptr_t *args); -intptr_t VM_DllSyscall( intptr_t arg, ... ) { +intptr_t VM_DllSyscall(intptr_t arg, ...) { #if !id386 || defined __clang__ || defined MACOS_X // rcg010206 - see commentary above intptr_t args[16]; @@ -73,13 +72,13 @@ intptr_t VM_DllSyscall( intptr_t arg, ... ) { args[0] = arg; - va_start( ap, arg ); - for (size_t i = 1; i < ARRAY_LEN (args); i++) - args[i] = va_arg( ap, intptr_t ); - va_end( ap ); + va_start(ap, arg); + for (size_t i = 1; i < ARRAY_LEN(args); i++) + args[i] = va_arg(ap, intptr_t); + va_end(ap); - return CL_CgameSystemCalls( args ); + return CL_CgameSystemCalls(args); #else // original id code - return CL_CgameSystemCalls( &arg ); + return CL_CgameSystemCalls(&arg); #endif } diff --git a/code/game/AI_Animal.cpp b/code/game/AI_Animal.cpp index 4626ff4d1f..1039888040 100644 --- a/code/game/AI_Animal.cpp +++ b/code/game/AI_Animal.cpp @@ -28,44 +28,38 @@ along with this program; if not, see . #endif #include "../Ratl/vector_vs.h" -#define MAX_PACKS 10 +#define MAX_PACKS 10 -#define LEAVE_PACK_DISTANCE 1000 -#define JOIN_PACK_DISTANCE 800 -#define WANDER_RANGE 1000 -#define FRIGHTEN_DISTANCE 300 +#define LEAVE_PACK_DISTANCE 1000 +#define JOIN_PACK_DISTANCE 800 +#define WANDER_RANGE 1000 +#define FRIGHTEN_DISTANCE 300 -extern qboolean G_PlayerSpawned( void ); - -ratl::vector_vs mPacks; +extern qboolean G_PlayerSpawned(void); +ratl::vector_vs mPacks; //////////////////////////////////////////////////////////////////////////////////////// // Update The Packs, Delete Dead Leaders, Join / Split Packs, Find MY Leader //////////////////////////////////////////////////////////////////////////////////////// -gentity_t* NPC_AnimalUpdateLeader(void) -{ +gentity_t *NPC_AnimalUpdateLeader(void) { // Find The Closest Pack Leader, Not Counting Myself //--------------------------------------------------- - gentity_t* closestLeader = 0; - float closestDist = 0; - int myLeaderNum = 0; + gentity_t *closestLeader = 0; + float closestDist = 0; + int myLeaderNum = 0; - for (int i=0; ihealth<=0) - { - if (mPacks[i]==NPC->client->leader) - { + if (mPacks[i] == 0 || mPacks[i]->health <= 0) { + if (mPacks[i] == NPC->client->leader) { NPC->client->leader = 0; } mPacks.erase_swap(i); - if (i>=mPacks.size()) - { + if (i >= mPacks.size()) { closestLeader = 0; break; } @@ -73,15 +67,13 @@ gentity_t* NPC_AnimalUpdateLeader(void) // Don't Count Self //------------------ - if (mPacks[i]==NPC) - { + if (mPacks[i] == NPC) { myLeaderNum = i; continue; } - float Dist = Distance(mPacks[i]->currentOrigin, NPC->currentOrigin); - if (!closestLeader || DistcurrentOrigin, NPC->currentOrigin); + if (!closestLeader || Dist < closestDist) { closestDist = Dist; closestLeader = mPacks[i]; } @@ -89,13 +81,11 @@ gentity_t* NPC_AnimalUpdateLeader(void) // In Joining Distance? //---------------------- - if (closestLeader && closestDistclient->leader==NPC) - { - mPacks.erase_swap(myLeaderNum); // Erase Myself From The Leader List + if (NPC->client->leader == NPC) { + mPacks.erase_swap(myLeaderNum); // Erase Myself From The Leader List } // Join The Pack! @@ -103,34 +93,28 @@ gentity_t* NPC_AnimalUpdateLeader(void) NPC->client->leader = closestLeader; } - // Do I Have A Leader? //--------------------- - if (NPC->client->leader) - { + if (NPC->client->leader) { // AM I A Leader? //---------------- - if (NPC->client->leader!=NPC) - { + if (NPC->client->leader != NPC) { // If Our Leader Is Dead, Clear Him Out - if ( NPC->client->leader->health<=0 || NPC->client->leader->inuse == 0) - { + if (NPC->client->leader->health <= 0 || NPC->client->leader->inuse == 0) { NPC->client->leader = 0; } // If My Leader Isn't His Own Leader, Then, Use His Leader //--------------------------------------------------------- - else if (NPC->client->leader->client->leader!=NPC->client->leader) - { + else if (NPC->client->leader->client->leader != NPC->client->leader) { // Eh. Can this get more confusing? NPC->client->leader = NPC->client->leader->client->leader; } // If Our Leader Is Too Far Away, Clear Him Out //------------------------------------------------------ - else if ( Distance(NPC->client->leader->currentOrigin, NPC->currentOrigin)>LEAVE_PACK_DISTANCE) - { + else if (Distance(NPC->client->leader->currentOrigin, NPC->currentOrigin) > LEAVE_PACK_DISTANCE) { NPC->client->leader = 0; } } @@ -139,164 +123,133 @@ gentity_t* NPC_AnimalUpdateLeader(void) // If We Couldn't Find A Leader, Then Become One //----------------------------------------------- - else if (!mPacks.full()) - { + else if (!mPacks.full()) { NPC->client->leader = NPC; mPacks.push_back(NPC); } return NPC->client->leader; } - - - /* ------------------------- NPC_BSAnimal_Default ------------------------- */ -void NPC_BSAnimal_Default( void ) -{ - if (!NPC || !NPC->client) - { +void NPC_BSAnimal_Default(void) { + if (!NPC || !NPC->client) { return; } // Update Some Positions //----------------------- - CVec3 CurrentLocation(NPC->currentOrigin); - + CVec3 CurrentLocation(NPC->currentOrigin); // Update The Leader //------------------- - gentity_t* leader = NPC_AnimalUpdateLeader(); - + gentity_t *leader = NPC_AnimalUpdateLeader(); // Select Closest Threat Location //-------------------------------- - CVec3 ThreatLocation(0,0,0); + CVec3 ThreatLocation(0, 0, 0); qboolean PlayerSpawned = G_PlayerSpawned(); - if ( PlayerSpawned ) - {//player is actually in the level now + if (PlayerSpawned) { // player is actually in the level now ThreatLocation = player->currentOrigin; } - int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_MINOR, qfalse); - if ( alertEvent >= 0 ) - { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_MINOR, qfalse); + if (alertEvent >= 0) { alertEvent_t *event = &level.alertEvents[alertEvent]; - if (event->owner!=NPC && Distance(event->position, CurrentLocation.v)radius) - { + if (event->owner != NPC && Distance(event->position, CurrentLocation.v) < event->radius) { ThreatLocation = event->position; } } + // float DistToThreat = CurrentLocation.Dist(ThreatLocation); + // float DistFromHome = CurrentLocation.Dist(mHome); - -// float DistToThreat = CurrentLocation.Dist(ThreatLocation); -// float DistFromHome = CurrentLocation.Dist(mHome); - - - - bool EvadeThreat = (level.timeinvestigateSoundDebounceTime); - bool CharmedDocile = (level.timeconfusionTime); - bool CharmedApproach = (level.timecharmedTime); - - + bool EvadeThreat = (level.time < NPCInfo->investigateSoundDebounceTime); + bool CharmedDocile = (level.time < NPCInfo->confusionTime); + bool CharmedApproach = (level.time < NPCInfo->charmedTime); // If Not Already Evading, Test To See If We Should "Know" About The Threat //-------------------------------------------------------------------------- -/* if (false && !EvadeThreat && PlayerSpawned && (DistToThreatcurrentAngles); - LookAim.AngToVec(); - CVec3 MyPos(CurrentLocation); - MyPos -= ThreatLocation; - MyPos.SafeNorm(); - - float DirectionSimilarity = MyPos.Dot(LookAim); - - if (fabsf(DirectionSimilarity)<0.8f) + /* if (false && !EvadeThreat && PlayerSpawned && (DistToThreatinvestigateSoundDebounceTime = level.time + Q_irand(0, 1000); - VectorCopy(ThreatLocation.v, NPCInfo->investigateGoal); - } - }*/ - - + CVec3 LookAim(NPC->currentAngles); + LookAim.AngToVec(); + CVec3 MyPos(CurrentLocation); + MyPos -= ThreatLocation; + MyPos.SafeNorm(); + float DirectionSimilarity = MyPos.Dot(LookAim); + if (fabsf(DirectionSimilarity)<0.8f) + { + EvadeThreat = true; + NPCInfo->investigateSoundDebounceTime = level.time + Q_irand(0, 1000); + VectorCopy(ThreatLocation.v, NPCInfo->investigateGoal); + } + }*/ STEER::Activate(NPC); { // Charmed Approach - Walk TOWARD The Threat Location //---------------------------------------------------- - if (CharmedApproach) - { + if (CharmedApproach) { NAV::GoTo(NPC, NPCInfo->investigateGoal); } // Charmed Docile - Stay Put //--------------------------- - else if (CharmedDocile) - { + else if (CharmedDocile) { NAV::ClearPath(NPC); STEER::Stop(NPC); } // Run Away From This Threat //--------------------------- - else if (EvadeThreat) - { + else if (EvadeThreat) { NAV::ClearPath(NPC); STEER::Flee(NPC, NPCInfo->investigateGoal); } // Normal Behavior //----------------- - else - { + else { // Follow Our Pack Leader! //------------------------- - if (leader && leader!=NPC) - { - float followDist = 100.0f; - float curDist = Distance(NPC->currentOrigin, leader->followPos); - + if (leader && leader != NPC) { + float followDist = 100.0f; + float curDist = Distance(NPC->currentOrigin, leader->followPos); // Update The Leader's Follow Position //------------------------------------- STEER::FollowLeader(NPC, leader, followDist); - bool inSeekRange = (curDistfollowPosWaypoint)); - bool leaderStop = ((level.time - leader->lastMoveTime)>500); + bool inSeekRange = (curDist < followDist * 10.0f); + bool onNbrPoints = (NAV::OnNeighboringPoints(NAV::GetNearestNode(NPC), leader->followPosWaypoint)); + bool leaderStop = ((level.time - leader->lastMoveTime) > 500); // If Close Enough, Dump Any Existing Path //----------------------------------------- - if (inSeekRange || onNbrPoints) - { + if (inSeekRange || onNbrPoints) { NAV::ClearPath(NPC); // If The Leader Isn't Moving, Stop //---------------------------------- - if (leaderStop) - { + if (leaderStop) { STEER::Stop(NPC); } // Otherwise, Try To Get To The Follow Position //---------------------------------------------- - else - { - STEER::Seek(NPC, leader->followPos, fabsf(followDist)/2.0f/*slowing distance*/, 1.0f/*wight*/, leader->resultspeed); + else { + STEER::Seek(NPC, leader->followPos, fabsf(followDist) / 2.0f /*slowing distance*/, 1.0f /*wight*/, leader->resultspeed); } } // Otherwise, Get A Path To The Follow Position //---------------------------------------------- - else - { + else { NAV::GoTo(NPC, leader->followPosWaypoint); } STEER::Separation(NPC, 4.0f); @@ -305,66 +258,54 @@ void NPC_BSAnimal_Default( void ) // Leader AI - Basically Wander //------------------------------ - else - { + else { // Are We Doing A Path? //---------------------- - bool HasPath = NAV::HasPath(NPC); - if (HasPath) - { + bool HasPath = NAV::HasPath(NPC); + if (HasPath) { HasPath = NAV::UpdatePath(NPC); - if (HasPath) - { - STEER::Path(NPC); // Follow The Path + if (HasPath) { + STEER::Path(NPC); // Follow The Path STEER::AvoidCollisions(NPC); } } - if (!HasPath) - { + if (!HasPath) { // If Debounce Time Has Expired, Choose A New Sub State //------------------------------------------------------ - if (NPCInfo->investigateDebounceTimeinvestigateDebounceTime < level.time) { // Clear Out Flags From The Previous Substate //-------------------------------------------- - NPCInfo->aiFlags &= ~NPCAI_OFF_PATH; - NPCInfo->aiFlags &= ~NPCAI_WALKING; - + NPCInfo->aiFlags &= ~NPCAI_OFF_PATH; + NPCInfo->aiFlags &= ~NPCAI_WALKING; // Pick Another Spot //------------------- - int NEXTSUBSTATE = Q_irand(0, 10); - - bool RandomPathNode = (NEXTSUBSTATE<8); //(NEXTSUBSTATE<9); - bool PathlessWander = (NEXTSUBSTATE<9); //false; - + int NEXTSUBSTATE = Q_irand(0, 10); + bool RandomPathNode = (NEXTSUBSTATE < 8); //(NEXTSUBSTATE<9); + bool PathlessWander = (NEXTSUBSTATE < 9); // false; // Random Path Node //------------------ - if (RandomPathNode) - { + if (RandomPathNode) { // Sometimes, Walk //----------------- - if (Q_irand(0, 1)==0) - { - NPCInfo->aiFlags |= NPCAI_WALKING; + if (Q_irand(0, 1) == 0) { + NPCInfo->aiFlags |= NPCAI_WALKING; } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); - NAV::FindPath(NPC, NAV::ChooseRandomNeighbor(NAV::GetNearestNode(NPC)));//, mHome.v, WANDER_RANGE)); + NAV::FindPath(NPC, NAV::ChooseRandomNeighbor(NAV::GetNearestNode(NPC))); //, mHome.v, WANDER_RANGE)); } // Pathless Wandering //-------------------- - else if (PathlessWander) - { + else if (PathlessWander) { // Sometimes, Walk //----------------- - if (Q_irand(0, 1)==0) - { - NPCInfo->aiFlags |= NPCAI_WALKING; + if (Q_irand(0, 1) == 0) { + NPCInfo->aiFlags |= NPCAI_WALKING; } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); @@ -373,30 +314,25 @@ void NPC_BSAnimal_Default( void ) // Just Stand Here //----------------- - else - { + else { NPCInfo->investigateDebounceTime = level.time + Q_irand(2000, 6000); - //NPC_SetAnim(NPC, SETANIM_BOTH, ((Q_irand(0, 1)==0)?(BOTH_GUARD_LOOKAROUND1):(BOTH_GUARD_IDLE1)), SETANIM_FLAG_NORMAL); + // NPC_SetAnim(NPC, SETANIM_BOTH, ((Q_irand(0, 1)==0)?(BOTH_GUARD_LOOKAROUND1):(BOTH_GUARD_IDLE1)), SETANIM_FLAG_NORMAL); } } // Ok, So We Don't Have A Path, And Debounce Time Is Still Active, So We Are Either Wandering Or Looking Around //-------------------------------------------------------------------------------------------------------------- - else - { - // if (DistFromHome>(WANDER_RANGE)) - // { - // STEER::Seek(NPC, mHome); - // } - // else + else { + // if (DistFromHome>(WANDER_RANGE)) + // { + // STEER::Seek(NPC, mHome); + // } + // else { - if (NPCInfo->aiFlags & NPCAI_OFF_PATH) - { + if (NPCInfo->aiFlags & NPCAI_OFF_PATH) { STEER::Wander(NPC); STEER::AvoidCollisions(NPC); - } - else - { + } else { STEER::Stop(NPC); } } @@ -407,6 +343,5 @@ void NPC_BSAnimal_Default( void ) } STEER::DeActivate(NPC, &ucmd); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - diff --git a/code/game/AI_AssassinDroid.cpp b/code/game/AI_AssassinDroid.cpp index 26368d9463..7d36d090b7 100644 --- a/code/game/AI_AssassinDroid.cpp +++ b/code/game/AI_AssassinDroid.cpp @@ -23,68 +23,56 @@ along with this program; if not, see . #include "bg_public.h" #include "b_local.h" -//custom anims: - //both_attack1 - running attack - //both_attack2 - crouched attack - //both_attack3 - standing attack - //both_stand1idle1 - idle - //both_crouch2stand1 - uncrouch - //both_death4 - running death - -#define ASSASSIN_SHIELD_SIZE 75 -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 - - +// custom anims: +// both_attack1 - running attack +// both_attack2 - crouched attack +// both_attack3 - standing attack +// both_stand1idle1 - idle +// both_crouch2stand1 - uncrouch +// both_death4 - running death + +#define ASSASSIN_SHIELD_SIZE 75 +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool BubbleShield_IsOn() -{ - return (NPC->flags&FL_SHIELDED); -} +bool BubbleShield_IsOn() { return (NPC->flags & FL_SHIELDED); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void BubbleShield_TurnOn() -{ - if (!BubbleShield_IsOn()) - { +void BubbleShield_TurnOn() { + if (!BubbleShield_IsOn()) { NPC->flags |= FL_SHIELDED; NPC->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE; - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "force_shield", TURN_ON ); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "force_shield", TURN_ON); } } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void BubbleShield_TurnOff() -{ - if ( BubbleShield_IsOn()) - { +void BubbleShield_TurnOff() { + if (BubbleShield_IsOn()) { NPC->flags &= ~FL_SHIELDED; NPC->client->ps.powerups[PW_GALAK_SHIELD] = 0; - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "force_shield", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "force_shield", TURN_OFF); } } - //////////////////////////////////////////////////////////////////////////////////////// // Push A Particular Ent //////////////////////////////////////////////////////////////////////////////////////// -void BubbleShield_PushEnt(gentity_t* pushed, vec3_t smackDir) -{ - G_Damage(pushed, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer+1)*Q_irand( 5, 10), DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE); +void BubbleShield_PushEnt(gentity_t *pushed, vec3_t smackDir) { + G_Damage(pushed, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer + 1) * Q_irand(5, 10), DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE); G_Throw(pushed, smackDir, 10); // Make Em Electric //------------------ - pushed->s.powerups |= (1 << PW_SHOCKED); - if (pushed->client) - { + pushed->s.powerups |= (1 << PW_SHOCKED); + if (pushed->client) { pushed->client->ps.powerups[PW_SHOCKED] = level.time + 1000; } } @@ -92,42 +80,36 @@ void BubbleShield_PushEnt(gentity_t* pushed, vec3_t smackDir) //////////////////////////////////////////////////////////////////////////////////////// // Go Through All The Ents Within The Radius Of The Shield And Push Them //////////////////////////////////////////////////////////////////////////////////////// -void BubbleShield_PushRadiusEnts() -{ - int numEnts; - gentity_t* radiusEnts[128]; - const float radius = ASSASSIN_SHIELD_SIZE; - vec3_t mins, maxs; - vec3_t smackDir; - float smackDist; - - for (int i = 0; i < 3; i++ ) - { +void BubbleShield_PushRadiusEnts() { + int numEnts; + gentity_t *radiusEnts[128]; + const float radius = ASSASSIN_SHIELD_SIZE; + vec3_t mins, maxs; + vec3_t smackDir; + float smackDist; + + for (int i = 0; i < 3; i++) { mins[i] = NPC->currentOrigin[i] - radius; maxs[i] = NPC->currentOrigin[i] + radius; } numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - for (int entIndex=0; entIndexclient) - { + if (!radiusEnts[entIndex] || !radiusEnts[entIndex]->client) { continue; } // Don't Push Away Other Assassin Droids //--------------------------------------- - if (radiusEnts[entIndex]->client->NPC_class==NPC->client->NPC_class) - { + if (radiusEnts[entIndex]->client->NPC_class == NPC->client->NPC_class) { continue; } // Should Have Already Pushed The Enemy If He Touched Us //------------------------------------------------------- - if (NPC->enemy && NPCInfo->touchedByPlayer==NPC->enemy && radiusEnts[entIndex]==NPC->enemy) - { + if (NPC->enemy && NPCInfo->touchedByPlayer == NPC->enemy && radiusEnts[entIndex] == NPC->enemy) { continue; } @@ -135,8 +117,7 @@ void BubbleShield_PushRadiusEnts() //----------------------------- VectorSubtract(radiusEnts[entIndex]->currentOrigin, NPC->currentOrigin, smackDir); smackDist = VectorNormalize(smackDir); - if (smackDisthealth<=0) - { - if (BubbleShield_IsOn()) - { + if (NPC->health <= 0) { + if (BubbleShield_IsOn()) { BubbleShield_TurnOff(); } return; } - // Recharge Shields //------------------ - NPC->client->ps.stats[STAT_ARMOR] += 1; - if (NPC->client->ps.stats[STAT_ARMOR]>250) - { + NPC->client->ps.stats[STAT_ARMOR] += 1; + if (NPC->client->ps.stats[STAT_ARMOR] > 250) { NPC->client->ps.stats[STAT_ARMOR] = 250; } - - - // If We Have Enough Armor And Are Not Shooting Right Now, Kick The Shield On //---------------------------------------------------------------------------- - if (NPC->client->ps.stats[STAT_ARMOR]>100 && TIMER_Done(NPC, "ShieldsDown")) - { + if (NPC->client->ps.stats[STAT_ARMOR] > 100 && TIMER_Done(NPC, "ShieldsDown")) { // Check On Timers To Raise And Lower Shields //-------------------------------------------- - if ((level.time - NPCInfo->enemyLastSeenTime)<1000 && TIMER_Done(NPC, "ShieldsUp")) - { - TIMER_Set(NPC, "ShieldsDown", 2000); // Drop Shields - TIMER_Set(NPC, "ShieldsUp", Q_irand(4000, 5000)); // Then Bring Them Back Up For At Least 3 sec + if ((level.time - NPCInfo->enemyLastSeenTime) < 1000 && TIMER_Done(NPC, "ShieldsUp")) { + TIMER_Set(NPC, "ShieldsDown", 2000); // Drop Shields + TIMER_Set(NPC, "ShieldsUp", Q_irand(4000, 5000)); // Then Bring Them Back Up For At Least 3 sec } BubbleShield_TurnOn(); - if (BubbleShield_IsOn()) - { + if (BubbleShield_IsOn()) { // Update Our Shader Value //------------------------- - NPC->client->renderInfo.customRGBA[0] = - NPC->client->renderInfo.customRGBA[1] = - NPC->client->renderInfo.customRGBA[2] = - NPC->client->renderInfo.customRGBA[3] = (NPC->client->ps.stats[STAT_ARMOR] - 100); - + NPC->client->renderInfo.customRGBA[0] = NPC->client->renderInfo.customRGBA[1] = NPC->client->renderInfo.customRGBA[2] = + NPC->client->renderInfo.customRGBA[3] = (NPC->client->ps.stats[STAT_ARMOR] - 100); // If Touched By An Enemy, ALWAYS Shove Them //------------------------------------------- - if (NPC->enemy && NPCInfo->touchedByPlayer==NPC->enemy) - { + if (NPC->enemy && NPCInfo->touchedByPlayer == NPC->enemy) { vec3_t dir; VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, dir); VectorNormalize(dir); @@ -209,11 +175,9 @@ void BubbleShield_Update() } } - // Shields Gone //-------------- - else - { + else { BubbleShield_TurnOff(); } } \ No newline at end of file diff --git a/code/game/AI_Atst.cpp b/code/game/AI_Atst.cpp index 26ce45cdfd..8c9d80126d 100644 --- a/code/game/AI_Atst.cpp +++ b/code/game/AI_Atst.cpp @@ -24,14 +24,13 @@ along with this program; if not, see . #include "g_functions.h" #include "../cgame/cg_local.h" +#define MIN_MELEE_RANGE 640 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_MELEE_RANGE 640 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) - -#define TURN_OFF 0x00000100//G2SURFACEFLAG_NODESCENDANTS +#define TURN_OFF 0x00000100 // G2SURFACEFLAG_NODESCENDANTS #define LEFT_ARM_HEALTH 40 #define RIGHT_ARM_HEALTH 40 @@ -41,38 +40,33 @@ along with this program; if not, see . NPC_ATST_Precache ------------------------- */ -void NPC_ATST_Precache(void) -{ - G_SoundIndex( "sound/chars/atst/atst_damaged1" ); - G_SoundIndex( "sound/chars/atst/atst_damaged2" ); - - RegisterItem( FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon - - G_EffectIndex( "env/med_explode2" ); -// G_EffectIndex( "smaller_chunks" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "explosions/droidexplosion1" ); +void NPC_ATST_Precache(void) { + G_SoundIndex("sound/chars/atst/atst_damaged1"); + G_SoundIndex("sound/chars/atst/atst_damaged2"); + + RegisterItem(FindItemForWeapon(WP_ATST_MAIN)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_BOWCASTER)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_ROCKET_LAUNCHER)); // precache the weapon + + G_EffectIndex("env/med_explode2"); + // G_EffectIndex( "smaller_chunks" ); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("explosions/droidexplosion1"); } //----------------------------------------------------------------- -static void ATST_PlayEffect( gentity_t *self, const int boltID, const char *fx ) -{ - if ( boltID >=0 && fx && fx[0] ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +static void ATST_PlayEffect(gentity_t *self, const int boltID, const char *fx) { + if (boltID >= 0 && fx && fx[0]) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - boltID, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, boltID, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( fx, org, dir ); + G_PlayEffect(fx, org, dir); } } @@ -84,47 +78,38 @@ Called by NPC's and player in an ATST ------------------------- */ -void G_ATSTCheckPain( gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ +void G_ATSTCheckPain(gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { int newBolt; - if ( rand() & 1 ) - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1" ); - } - else - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2" ); + if (rand() & 1) { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1"); + } else { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2"); } - if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) - { - if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? + if ((hitLoc == HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { + if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash3" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt1, self->s.number); - ATST_PlayEffect( self, self->genericBolt1, "env/med_explode2" ); - G_PlayEffect( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, newBolt, self->s.number, point); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash3"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt1, self->s.number); + ATST_PlayEffect(self, self->genericBolt1, "env/med_explode2"); + G_PlayEffect(G_EffectIndex("blaster/smoke_bolton"), self->playerModel, newBolt, self->s.number, point); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_light_blaster_cann", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_light_blaster_cann", TURN_OFF); } - } - else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? + } else if ((hitLoc == HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash4" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); - ATST_PlayEffect( self, self->genericBolt2, "env/med_explode2" ); - G_PlayEffect( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, newBolt, self->s.number, point); + if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash4"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); + ATST_PlayEffect(self, self->genericBolt2, "env/med_explode2"); + G_PlayEffect(G_EffectIndex("blaster/smoke_bolton"), self->playerModel, newBolt, self->s.number, point); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_concussion_charger", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_concussion_charger", TURN_OFF); } } } @@ -133,10 +118,9 @@ void G_ATSTCheckPain( gentity_t *self, gentity_t *other, const vec3_t point, int NPC_ATST_Pain ------------------------- */ -void NPC_ATST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - G_ATSTCheckPain( self, other, point, damage, mod, hitLoc ); - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_ATST_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + G_ATSTCheckPain(self, other, point, damage, mod, hitLoc); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -144,18 +128,15 @@ void NPC_ATST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, con ATST_Hunt -------------------------` */ -void ATST_Hunt( qboolean visible, qboolean advance ) -{ +void ATST_Hunt(qboolean visible, qboolean advance) { - if ( NPCInfo->goalEntity == NULL ) - {//hunt + if (NPCInfo->goalEntity == NULL) { // hunt NPCInfo->goalEntity = NPC->enemy; } NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); - + NPC_MoveToGoal(qtrue); } /* @@ -163,26 +144,21 @@ void ATST_Hunt( qboolean visible, qboolean advance ) ATST_Ranged ------------------------- */ -void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) -{ +void ATST_Ranged(qboolean visible, qboolean advance, qboolean altAttack) { - if ( TIMER_Done( NPC, "atkDelay" ) && visible ) // Attack? + if (TIMER_Done(NPC, "atkDelay") && visible) // Attack? { - TIMER_Set( NPC, "atkDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPC, "atkDelay", Q_irand(500, 3000)); - if (altAttack) - { - ucmd.buttons |= BUTTON_ATTACK|BUTTON_ALT_ATTACK; - } - else - { + if (altAttack) { + ucmd.buttons |= BUTTON_ATTACK | BUTTON_ALT_ATTACK; + } else { ucmd.buttons |= BUTTON_ATTACK; } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); } } @@ -191,83 +167,72 @@ void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) ATST_Attack ------------------------- */ -void ATST_Attack( void ) -{ - qboolean altAttack=qfalse; - int blasterTest,chargerTest,weapon; +void ATST_Attack(void) { + qboolean altAttack = qfalse; + int blasterTest, chargerTest, weapon; - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; return; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + distance_e distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); return; } } // Decide what type of attack to do - switch ( distRate ) - { + switch (distRate) { case DIST_MELEE: - NPC_ChangeWeapon( WP_ATST_MAIN ); + NPC_ChangeWeapon(WP_ATST_MAIN); break; case DIST_LONG: - NPC_ChangeWeapon( WP_ATST_SIDE ); + NPC_ChangeWeapon(WP_ATST_SIDE); // See if the side weapons are there - blasterTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head_light_blaster_cann" ); - chargerTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head_concussion_charger" ); + blasterTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head_light_blaster_cann"); + chargerTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head_concussion_charger"); // It has both side weapons - if (!(blasterTest & TURN_OFF) && !(chargerTest & TURN_OFF)) - { - weapon = Q_irand( 0, 1); // 0 is blaster, 1 is charger (ALT SIDE) + if (!(blasterTest & TURN_OFF) && !(chargerTest & TURN_OFF)) { + weapon = Q_irand(0, 1); // 0 is blaster, 1 is charger (ALT SIDE) - if (weapon) // Fire charger + if (weapon) // Fire charger { altAttack = qtrue; - } - else - { + } else { altAttack = qfalse; } - } - else if (!(blasterTest & TURN_OFF)) // Blaster is on + } else if (!(blasterTest & TURN_OFF)) // Blaster is on { altAttack = qfalse; - } - else if (!(chargerTest & TURN_OFF)) // Blaster is on + } else if (!(chargerTest & TURN_OFF)) // Blaster is on { altAttack = qtrue; - } - else - { - NPC_ChangeWeapon( WP_NONE ); + } else { + NPC_ChangeWeapon(WP_NONE); } break; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - ATST_Ranged( visible, advance,altAttack ); + ATST_Ranged(visible, advance, altAttack); } /* @@ -275,25 +240,20 @@ void ATST_Attack( void ) ATST_Patrol ------------------------- */ -void ATST_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void ATST_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } } - } /* @@ -301,12 +261,11 @@ void ATST_Patrol( void ) ATST_Idle ------------------------- */ -void ATST_Idle( void ) -{ +void ATST_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); } /* @@ -314,22 +273,15 @@ void ATST_Idle( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSATST_Default( void ) -{ - if ( NPC->enemy ) - { - if( (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) ) - { +void NPC_BSATST_Default(void) { + if (NPC->enemy) { + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { NPCInfo->goalEntity = NPC->enemy; } ATST_Attack(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ATST_Patrol(); - } - else - { + } else { ATST_Idle(); } } diff --git a/code/game/AI_BobaFett.cpp b/code/game/AI_BobaFett.cpp index 8c5925e254..08535389a7 100644 --- a/code/game/AI_BobaFett.cpp +++ b/code/game/AI_BobaFett.cpp @@ -35,245 +35,213 @@ along with this program; if not, see . #include "b_local.h" #include "../Ravl/CVec.h" - //////////////////////////////////////////////////////////////////////////////////////// // Forward References Of Functions //////////////////////////////////////////////////////////////////////////////////////// -void Boba_Precache( void ); -void Boba_DustFallNear(const vec3_t origin, int dustcount); -void Boba_ChangeWeapon(int wp); -qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown = qfalse); +void Boba_Precache(void); +void Boba_DustFallNear(const vec3_t origin, int dustcount); +void Boba_ChangeWeapon(int wp); +qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown = qfalse); // Flight Related Functions (also used by Rocket Trooper) //-------------------------------------------------------- -qboolean Boba_Flying( gentity_t *self ); -void Boba_FlyStart( gentity_t *self ); -void Boba_FlyStop( gentity_t *self ); +qboolean Boba_Flying(gentity_t *self); +void Boba_FlyStart(gentity_t *self); +void Boba_FlyStop(gentity_t *self); // Called From NPC_Pain() //----------------------------- -void Boba_Pain( gentity_t *self, gentity_t *inflictor, int damage, int mod); - +void Boba_Pain(gentity_t *self, gentity_t *inflictor, int damage, int mod); // Local: Flame Thrower Weapon //----------------------------- -void Boba_FireFlameThrower( gentity_t *self ); -void Boba_StopFlameThrower( gentity_t *self ); -void Boba_StartFlameThrower( gentity_t *self ); -void Boba_DoFlameThrower( gentity_t *self ); +void Boba_FireFlameThrower(gentity_t *self); +void Boba_StopFlameThrower(gentity_t *self); +void Boba_StartFlameThrower(gentity_t *self); +void Boba_DoFlameThrower(gentity_t *self); // Local: Other Tactics //---------------------- -void Boba_DoAmbushWait( gentity_t *self); -void Boba_DoSniper( gentity_t *self); +void Boba_DoAmbushWait(gentity_t *self); +void Boba_DoSniper(gentity_t *self); // Local: Respawning //------------------- -bool Boba_Respawn(); +bool Boba_Respawn(); // Called From Within AI_Jedi && AI_Seeker //----------------------------------------- -void Boba_Fire(); -void Boba_FireDecide(); +void Boba_Fire(); +void Boba_FireDecide(); // Local: Called From Tactics() //---------------------------- -void Boba_TacticsSelect(); -bool Boba_CanSeeEnemy( gentity_t *self ); - +void Boba_TacticsSelect(); +bool Boba_CanSeeEnemy(gentity_t *self); // Called From NPC_RunBehavior() //------------------------------- -void Boba_Update(); // Always Called First, Before Any Other Thinking -bool Boba_Tactics(); // If returns true, Jedi and Seeker AI not used -bool Boba_Flee(); // If returns true, Jedi and Seeker AI not used - - +void Boba_Update(); // Always Called First, Before Any Other Thinking +bool Boba_Tactics(); // If returns true, Jedi and Seeker AI not used +bool Boba_Flee(); // If returns true, Jedi and Seeker AI not used //////////////////////////////////////////////////////////////////////////////////////// // External Functions //////////////////////////////////////////////////////////////////////////////////////// -extern void G_SoundAtSpot( vec3_t org, int soundIndex, qboolean broadcast ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void WP_ResistForcePush( gentity_t *self, gentity_t *pusher, qboolean noPenalty ); -extern void ForceJump( gentity_t *self, usercmd_t *ucmd ); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); +extern void G_SoundAtSpot(vec3_t org, int soundIndex, qboolean broadcast); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void WP_ResistForcePush(gentity_t *self, gentity_t *pusher, qboolean noPenalty); +extern void ForceJump(gentity_t *self, usercmd_t *ucmd); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); -extern void CG_DrawEdge( vec3_t start, vec3_t end, int type ); +extern void CG_DrawEdge(vec3_t start, vec3_t end, int type); //////////////////////////////////////////////////////////////////////////////////////// // External Data //////////////////////////////////////////////////////////////////////////////////////// -extern cvar_t* g_bobaDebug; - - +extern cvar_t *g_bobaDebug; //////////////////////////////////////////////////////////////////////////////////////// // Boba Debug Output //////////////////////////////////////////////////////////////////////////////////////// #ifndef FINAL_BUILD #if !defined(CTYPE_H_INC) - #include - #define CTYPE_H_INC +#include +#define CTYPE_H_INC #endif #if !defined(STDARG_H_INC) - #include - #define STDARG_H_INC +#include +#define STDARG_H_INC #endif #if !defined(STDIO_H_INC) - #include - #define STDIO_H_INC +#include +#define STDIO_H_INC #endif -void Boba_Printf(const char * format, ...) -{ - if (g_bobaDebug->integer==0) - { +void Boba_Printf(const char *format, ...) { + if (g_bobaDebug->integer == 0) { return; } - static char string[2][1024]; // in case this is called by nested functions - static int index = 0; - static char nFormat[300]; - char* buf; + static char string[2][1024]; // in case this is called by nested functions + static int index = 0; + static char nFormat[300]; + char *buf; // Tack On The Standard Format Around The Given Format //----------------------------------------------------- Com_sprintf(nFormat, sizeof(nFormat), "[BOBA %8d] %s\n", level.time, format); - // Resolve Remaining Elipsis Parameters Into Newly Formated String //----------------------------------------------------------------- buf = string[index & 1]; index++; - va_list argptr; - va_start (argptr, format); - Q_vsnprintf (buf, sizeof(*string), nFormat, argptr); - va_end (argptr); + va_list argptr; + va_start(argptr, format); + Q_vsnprintf(buf, sizeof(*string), nFormat, argptr); + va_end(argptr); // Print It To Debug Output Console //---------------------------------- gi.Printf(buf); } #else -void Boba_Printf(const char * format, ...) -{ -} +void Boba_Printf(const char *format, ...) {} #endif - //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define BOBA_FLAMEDURATION 3000 -#define BOBA_FLAMETHROWRANGE 128 -#define BOBA_FLAMETHROWSIZE 40 -#define BOBA_FLAMETHROWDAMAGEMIN 1//10 -#define BOBA_FLAMETHROWDAMAGEMAX 5//40 -#define BOBA_ROCKETRANGEMIN 300 -#define BOBA_ROCKETRANGEMAX 2000 - +#define BOBA_FLAMEDURATION 3000 +#define BOBA_FLAMETHROWRANGE 128 +#define BOBA_FLAMETHROWSIZE 40 +#define BOBA_FLAMETHROWDAMAGEMIN 1 // 10 +#define BOBA_FLAMETHROWDAMAGEMAX 5 // 40 +#define BOBA_ROCKETRANGEMIN 300 +#define BOBA_ROCKETRANGEMAX 2000 //////////////////////////////////////////////////////////////////////////////////////// // Global Data //////////////////////////////////////////////////////////////////////////////////////// -bool BobaHadDeathScript = false; -bool BobaActive = false; -vec3_t BobaFootStepLoc; -int BobaFootStepCount = 0; - -vec3_t AverageEnemyDirection; -int AverageEnemyDirectionSamples; +bool BobaHadDeathScript = false; +bool BobaActive = false; +vec3_t BobaFootStepLoc; +int BobaFootStepCount = 0; +vec3_t AverageEnemyDirection; +int AverageEnemyDirectionSamples; //////////////////////////////////////////////////////////////////////////////////////// // Enums //////////////////////////////////////////////////////////////////////////////////////// -enum EBobaTacticsState -{ +enum EBobaTacticsState { BTS_NONE, // Attack //-------- - BTS_RIFLE, // Uses Jedi / Seeker Movement - BTS_MISSILE, // Uses Jedi / Seeker Movement - BTS_SNIPER, // Uses Special Movement Internal To This File - BTS_FLAMETHROW, // Locked In Place + BTS_RIFLE, // Uses Jedi / Seeker Movement + BTS_MISSILE, // Uses Jedi / Seeker Movement + BTS_SNIPER, // Uses Special Movement Internal To This File + BTS_FLAMETHROW, // Locked In Place // Waiting //--------- - BTS_AMBUSHWAIT, // Goto CP & Wait + BTS_AMBUSHWAIT, // Goto CP & Wait BTS_MAX }; - - - - - - - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_Precache( void ) -{ - G_SoundIndex( "sound/chars/boba/bf_blast-off.wav" ); - G_SoundIndex( "sound/chars/boba/bf_jetpack_lp.wav" ); - G_SoundIndex( "sound/chars/boba/bf_land.wav" ); - G_SoundIndex( "sound/weapons/boba/bf_flame.mp3" ); - G_SoundIndex( "sound/player/footsteps/boot1" ); - G_SoundIndex( "sound/player/footsteps/boot2" ); - G_SoundIndex( "sound/player/footsteps/boot3" ); - G_SoundIndex( "sound/player/footsteps/boot4" ); - G_EffectIndex( "boba/jetSP" ); - G_EffectIndex( "boba/fthrw" ); - G_EffectIndex( "volumetric/black_smoke" ); - G_EffectIndex( "chunks/dustFall" ); +void Boba_Precache(void) { + G_SoundIndex("sound/chars/boba/bf_blast-off.wav"); + G_SoundIndex("sound/chars/boba/bf_jetpack_lp.wav"); + G_SoundIndex("sound/chars/boba/bf_land.wav"); + G_SoundIndex("sound/weapons/boba/bf_flame.mp3"); + G_SoundIndex("sound/player/footsteps/boot1"); + G_SoundIndex("sound/player/footsteps/boot2"); + G_SoundIndex("sound/player/footsteps/boot3"); + G_SoundIndex("sound/player/footsteps/boot4"); + G_EffectIndex("boba/jetSP"); + G_EffectIndex("boba/fthrw"); + G_EffectIndex("volumetric/black_smoke"); + G_EffectIndex("chunks/dustFall"); AverageEnemyDirectionSamples = 0; VectorClear(AverageEnemyDirection); - BobaHadDeathScript = false; - BobaActive = true; - BobaFootStepCount = 0; + BobaHadDeathScript = false; + BobaActive = true; + BobaFootStepCount = 0; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_DustFallNear(const vec3_t origin, int dustcount) -{ - if (!BobaActive) - { +void Boba_DustFallNear(const vec3_t origin, int dustcount) { + if (!BobaActive) { return; } - trace_t testTrace; - vec3_t testDirection; - vec3_t testStartPos; - vec3_t testEndPos; + trace_t testTrace; + vec3_t testDirection; + vec3_t testStartPos; + vec3_t testEndPos; VectorCopy(origin, testStartPos); - for (int i=0; iinuse)?(0):(ENTITYNUM_NONE), MASK_SHOT, (EG2_Collision)0, 0 ); - - if (!testTrace.startsolid && - !testTrace.allsolid && - testTrace.fraction>0.1f && - testTrace.fraction<0.9f) - { - G_PlayEffect( "chunks/dustFall", testTrace.endpos, testTrace.plane.normal ); + gi.trace(&testTrace, origin, NULL, NULL, testEndPos, (player && player->inuse) ? (0) : (ENTITYNUM_NONE), MASK_SHOT, (EG2_Collision)0, 0); + + if (!testTrace.startsolid && !testTrace.allsolid && testTrace.fraction > 0.1f && testTrace.fraction < 0.9f) { + G_PlayEffect("chunks/dustFall", testTrace.endpos, testTrace.plane.normal); } } } @@ -281,83 +249,63 @@ void Boba_DustFallNear(const vec3_t origin, int dustcount) //////////////////////////////////////////////////////////////////////////////////////// // This is just a super silly wrapper around NPC_Change Weapon //////////////////////////////////////////////////////////////////////////////////////// -void Boba_ChangeWeapon( int wp ) -{ - if ( NPC->s.weapon == wp ) - { +void Boba_ChangeWeapon(int wp) { + if (NPC->s.weapon == wp) { return; } - NPC_ChangeWeapon( wp ); - G_AddEvent( NPC, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + NPC_ChangeWeapon(wp); + G_AddEvent(NPC, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); } //////////////////////////////////////////////////////////////////////////////////////// // Choose an "anti-knockdown" response //////////////////////////////////////////////////////////////////////////////////////// -qboolean Boba_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown ) -{ - if ( self->client->NPC_class != CLASS_BOBAFETT ) - { +qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown) { + if (self->client->NPC_class != CLASS_BOBAFETT) { return qfalse; } - if ( self->client->moveType == MT_FLYSWIM ) - {//can't knock me down when I'm flying + if (self->client->moveType == MT_FLYSWIM) { // can't knock me down when I'm flying return qtrue; } - vec3_t pDir, fwd, right, ang = {0, self->currentAngles[YAW], 0}; - float fDot, rDot; - int strafeTime = Q_irand( 1000, 2000 ); + vec3_t pDir, fwd, right, ang = {0, self->currentAngles[YAW], 0}; + float fDot, rDot; + int strafeTime = Q_irand(1000, 2000); - AngleVectors( ang, fwd, right, NULL ); - VectorNormalize2( pushDir, pDir ); - fDot = DotProduct( pDir, fwd ); - rDot = DotProduct( pDir, right ); + AngleVectors(ang, fwd, right, NULL); + VectorNormalize2(pushDir, pDir); + fDot = DotProduct(pDir, fwd); + rDot = DotProduct(pDir, right); - if ( Q_irand( 0, 2 ) ) - {//flip or roll with it - usercmd_t tempCmd; - if ( fDot >= 0.4f ) - { + if (Q_irand(0, 2)) { // flip or roll with it + usercmd_t tempCmd; + if (fDot >= 0.4f) { tempCmd.forwardmove = 127; - TIMER_Set( self, "moveforward", strafeTime ); - } - else if ( fDot <= -0.4f ) - { + TIMER_Set(self, "moveforward", strafeTime); + } else if (fDot <= -0.4f) { tempCmd.forwardmove = -127; - TIMER_Set( self, "moveback", strafeTime ); - } - else if ( rDot > 0 ) - { + TIMER_Set(self, "moveback", strafeTime); + } else if (rDot > 0) { tempCmd.rightmove = 127; - TIMER_Set( self, "strafeRight", strafeTime ); - TIMER_Set( self, "strafeLeft", -1 ); - } - else - { + TIMER_Set(self, "strafeRight", strafeTime); + TIMER_Set(self, "strafeLeft", -1); + } else { tempCmd.rightmove = -127; - TIMER_Set( self, "strafeLeft", strafeTime ); - TIMER_Set( self, "strafeRight", -1 ); + TIMER_Set(self, "strafeLeft", strafeTime); + TIMER_Set(self, "strafeRight", -1); } - G_AddEvent( self, EV_JUMP, 0 ); - if ( !Q_irand( 0, 1 ) ) - {//flip - self->client->ps.forceJumpCharge = 280;//FIXME: calc this intelligently? - ForceJump( self, &tempCmd ); + G_AddEvent(self, EV_JUMP, 0); + if (!Q_irand(0, 1)) { // flip + self->client->ps.forceJumpCharge = 280; // FIXME: calc this intelligently? + ForceJump(self, &tempCmd); + } else { // roll + TIMER_Set(self, "duck", strafeTime); } - else - {//roll - TIMER_Set( self, "duck", strafeTime ); - } - self->painDebounceTime = 0;//so we do something - } - else if ( !Q_irand( 0, 1 ) && forceKnockdown ) - {//resist - WP_ResistForcePush( self, pusher, qtrue ); - } - else - {//fall down + self->painDebounceTime = 0; // so we do something + } else if (!Q_irand(0, 1) && forceKnockdown) { // resist + WP_ResistForcePush(self, pusher, qtrue); + } else { // fall down return qfalse; } @@ -367,65 +315,54 @@ qboolean Boba_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pu //////////////////////////////////////////////////////////////////////////////////////// // Is this entity flying //////////////////////////////////////////////////////////////////////////////////////// -qboolean Boba_Flying( gentity_t *self ) -{ - assert(self && self->client && self->client->NPC_class==CLASS_BOBAFETT);//self->NPC && - return ((qboolean)(self->client->moveType==MT_FLYSWIM)); +qboolean Boba_Flying(gentity_t *self) { + assert(self && self->client && self->client->NPC_class == CLASS_BOBAFETT); // self->NPC && + return ((qboolean)(self->client->moveType == MT_FLYSWIM)); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Boba_CanSeeEnemy( gentity_t *self ) -{ - assert(self && self->NPC && self->client && self->client->NPC_class==CLASS_BOBAFETT); - return ((level.time - self->NPC->enemyLastSeenTime)<1000); +bool Boba_CanSeeEnemy(gentity_t *self) { + assert(self && self->NPC && self->client && self->client->NPC_class == CLASS_BOBAFETT); + return ((level.time - self->NPC->enemyLastSeenTime) < 1000); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_Pain( gentity_t *self, gentity_t *inflictor, int damage, int mod) -{ - if (mod==MOD_SABER && !(NPCInfo->aiFlags&NPCAI_FLAMETHROW)) - { - TIMER_Set( self, "Boba_TacticsSelect", 0); // Hurt By The Saber, Time To Try Something New +void Boba_Pain(gentity_t *self, gentity_t *inflictor, int damage, int mod) { + if (mod == MOD_SABER && !(NPCInfo->aiFlags & NPCAI_FLAMETHROW)) { + TIMER_Set(self, "Boba_TacticsSelect", 0); // Hurt By The Saber, Time To Try Something New } - if (self->NPC->aiFlags&NPCAI_FLAMETHROW) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.torsoAnimTimer = level.time - TIMER_Get(self, "falmeTime"); + if (self->NPC->aiFlags & NPCAI_FLAMETHROW) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.torsoAnimTimer = level.time - TIMER_Get(self, "falmeTime"); } } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_FlyStart( gentity_t *self ) -{//switch to seeker AI for a while - if ( TIMER_Done( self, "jetRecharge" ) - && !Boba_Flying( self ) ) - { +void Boba_FlyStart(gentity_t *self) { // switch to seeker AI for a while + if (TIMER_Done(self, "jetRecharge") && !Boba_Flying(self)) { self->client->ps.gravity = 0; self->svFlags |= SVF_CUSTOM_GRAVITY; self->client->moveType = MT_FLYSWIM; - //start jet effect - self->client->jetPackTime = level.time + Q_irand( 3000, 10000 ); - if ( self->genericBolt1 != -1 ) - { - G_PlayEffect( G_EffectIndex( "boba/jetSP" ), self->playerModel, self->genericBolt1, self->s.number, self->currentOrigin, qtrue, qtrue ); + // start jet effect + self->client->jetPackTime = level.time + Q_irand(3000, 10000); + if (self->genericBolt1 != -1) { + G_PlayEffect(G_EffectIndex("boba/jetSP"), self->playerModel, self->genericBolt1, self->s.number, self->currentOrigin, qtrue, qtrue); } - if ( self->genericBolt2 != -1 ) - { - G_PlayEffect( G_EffectIndex( "boba/jetSP" ), self->playerModel, self->genericBolt2, self->s.number, self->currentOrigin, qtrue, qtrue ); + if (self->genericBolt2 != -1) { + G_PlayEffect(G_EffectIndex("boba/jetSP"), self->playerModel, self->genericBolt2, self->s.number, self->currentOrigin, qtrue, qtrue); } - //take-off sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav" ); - //jet loop sound - self->s.loopSound = G_SoundIndex( "sound/chars/boba/bf_jetpack_lp.wav" ); - if ( self->NPC ) - { + // take-off sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav"); + // jet loop sound + self->s.loopSound = G_SoundIndex("sound/chars/boba/bf_jetpack_lp.wav"); + if (self->NPC) { self->count = Q3_INFINITE; // SEEKER shot ammo count } } @@ -434,68 +371,61 @@ void Boba_FlyStart( gentity_t *self ) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_FlyStop( gentity_t *self ) -{ +void Boba_FlyStop(gentity_t *self) { self->client->ps.gravity = g_gravity->value; self->svFlags &= ~SVF_CUSTOM_GRAVITY; self->client->moveType = MT_RUNJUMP; - //Stop effect + // Stop effect self->client->jetPackTime = 0; - if ( self->genericBolt1 != -1 ) - { - G_StopEffect( "boba/jetSP", self->playerModel, self->genericBolt1, self->s.number ); + if (self->genericBolt1 != -1) { + G_StopEffect("boba/jetSP", self->playerModel, self->genericBolt1, self->s.number); } - if ( self->genericBolt2 != -1 ) - { - G_StopEffect( "boba/jetSP", self->playerModel, self->genericBolt2, self->s.number ); + if (self->genericBolt2 != -1) { + G_StopEffect("boba/jetSP", self->playerModel, self->genericBolt2, self->s.number); } - //stop jet loop sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/boba/bf_land.wav" ); + // stop jet loop sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/boba/bf_land.wav"); self->s.loopSound = 0; - if ( self->NPC ) - { + if (self->NPC) { self->count = 0; // SEEKER shot ammo count - TIMER_Set( self, "jetRecharge", Q_irand( 1000, 5000 ) ); - TIMER_Set( self, "jumpChaseDebounce", Q_irand( 500, 2000 ) ); + TIMER_Set(self, "jetRecharge", Q_irand(1000, 5000)); + TIMER_Set(self, "jumpChaseDebounce", Q_irand(500, 2000)); } } //////////////////////////////////////////////////////////////////////////////////////// // This func actually does the damage inflicting traces //////////////////////////////////////////////////////////////////////////////////////// -void Boba_FireFlameThrower( gentity_t *self ) -{ - trace_t tr; - vec3_t start, end, dir; - CVec3 traceMins(self->mins); - CVec3 traceMaxs(self->maxs); - gentity_t* traceEnt = NULL; - int damage = Q_irand( BOBA_FLAMETHROWDAMAGEMIN, BOBA_FLAMETHROWDAMAGEMAX ); - - AngleVectors(self->currentAngles, dir, 0, 0); +void Boba_FireFlameThrower(gentity_t *self) { + trace_t tr; + vec3_t start, end, dir; + CVec3 traceMins(self->mins); + CVec3 traceMaxs(self->maxs); + gentity_t *traceEnt = NULL; + int damage = Q_irand(BOBA_FLAMETHROWDAMAGEMIN, BOBA_FLAMETHROWDAMAGEMAX); + + AngleVectors(self->currentAngles, dir, 0, 0); dir[2] = 0.0f; VectorCopy(self->currentOrigin, start); traceMins *= 0.5f; traceMaxs *= 0.5f; start[2] += 40.0f; - VectorMA( start, 150.0f, dir, end ); + VectorMA(start, 150.0f, dir, end); - if (g_bobaDebug->integer) - { + if (g_bobaDebug->integer) { CG_DrawEdge(start, end, EDGE_IMPACT_POSSIBLE); } - gi.trace( &tr, start, self->mins, self->maxs, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + gi.trace(&tr, start, self->mins, self->maxs, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); traceEnt = &g_entities[tr.entityNum]; - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { - G_Damage( traceEnt, self, self, dir, tr.endpos, damage, DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC|DAMAGE_IGNORE_TEAM, MOD_LAVA, HL_NONE ); - if (traceEnt->health>0) - { -// G_Knockdown( traceEnt, self, dir, Q_irand(200, 330), qfalse); + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { + G_Damage(traceEnt, self, self, dir, tr.endpos, damage, DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC | DAMAGE_IGNORE_TEAM, MOD_LAVA, + HL_NONE); + if (traceEnt->health > 0) { + // G_Knockdown( traceEnt, self, dir, Q_irand(200, 330), qfalse); G_Throw(traceEnt, dir, 30); } } @@ -504,25 +434,22 @@ void Boba_FireFlameThrower( gentity_t *self ) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_StopFlameThrower( gentity_t *self ) -{ - if ( self->s.number < MAX_CLIENTS ) - { - self->client->ps.torsoAnimTimer = 0; - G_StopEffect( G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number); +void Boba_StopFlameThrower(gentity_t *self) { + if (self->s.number < MAX_CLIENTS) { + self->client->ps.torsoAnimTimer = 0; + G_StopEffect(G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number); return; } - if ((NPCInfo->aiFlags&NPCAI_FLAMETHROW)) - { - self->NPC->aiFlags &= ~NPCAI_FLAMETHROW; - self->client->ps.torsoAnimTimer = 0; + if ((NPCInfo->aiFlags & NPCAI_FLAMETHROW)) { + self->NPC->aiFlags &= ~NPCAI_FLAMETHROW; + self->client->ps.torsoAnimTimer = 0; - TIMER_Set( self, "flameTime", 0); - TIMER_Set( self, "nextAttackDelay", 0); - TIMER_Set( self, "Boba_TacticsSelect", 0); + TIMER_Set(self, "flameTime", 0); + TIMER_Set(self, "nextAttackDelay", 0); + TIMER_Set(self, "Boba_TacticsSelect", 0); - // G_SoundOnEnt( self, CHAN_WEAPON, "sound/effects/flameoff.mp3" ); - G_StopEffect( G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number); + // G_SoundOnEnt( self, CHAN_WEAPON, "sound/effects/flameoff.mp3" ); + G_StopEffect(G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number); Boba_Printf("FlameThrower OFF"); } @@ -531,22 +458,20 @@ void Boba_StopFlameThrower( gentity_t *self ) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_StartFlameThrower( gentity_t *self ) -{ - if (!(NPCInfo->aiFlags&NPCAI_FLAMETHROW)) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); +void Boba_StartFlameThrower(gentity_t *self) { + if (!(NPCInfo->aiFlags & NPCAI_FLAMETHROW)) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - self->NPC->aiFlags |= NPCAI_FLAMETHROW; - self->client->ps.torsoAnimTimer = BOBA_FLAMEDURATION; + self->NPC->aiFlags |= NPCAI_FLAMETHROW; + self->client->ps.torsoAnimTimer = BOBA_FLAMEDURATION; - TIMER_Set( self, "flameTime", BOBA_FLAMEDURATION); - TIMER_Set( self, "nextAttackDelay", BOBA_FLAMEDURATION); - TIMER_Set( self, "nextFlameDelay", BOBA_FLAMEDURATION*2); - TIMER_Set( self, "Boba_TacticsSelect", BOBA_FLAMEDURATION); + TIMER_Set(self, "flameTime", BOBA_FLAMEDURATION); + TIMER_Set(self, "nextAttackDelay", BOBA_FLAMEDURATION); + TIMER_Set(self, "nextFlameDelay", BOBA_FLAMEDURATION * 2); + TIMER_Set(self, "Boba_TacticsSelect", BOBA_FLAMEDURATION); - G_SoundOnEnt( self, CHAN_WEAPON, "sound/weapons/boba/bf_flame.mp3" ); - G_PlayEffect( G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number, self->s.origin, 1 ); + G_SoundOnEnt(self, CHAN_WEAPON, "sound/weapons/boba/bf_flame.mp3"); + G_PlayEffect(G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number, self->s.origin, 1); Boba_Printf("FlameThrower ON"); } @@ -555,111 +480,88 @@ void Boba_StartFlameThrower( gentity_t *self ) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_DoFlameThrower( gentity_t *self ) -{ - if ( self->s.number < MAX_CLIENTS ) - { - if ( self->client ) - { - if ( !self->client->ps.forcePowerDuration[FP_LIGHTNING] ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.torsoAnimTimer = BOBA_FLAMEDURATION; - G_SoundOnEnt( self, CHAN_WEAPON, "sound/weapons/boba/bf_flame.mp3" ); - G_PlayEffect( G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number, self->s.origin, 1 ); +void Boba_DoFlameThrower(gentity_t *self) { + if (self->s.number < MAX_CLIENTS) { + if (self->client) { + if (!self->client->ps.forcePowerDuration[FP_LIGHTNING]) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.torsoAnimTimer = BOBA_FLAMEDURATION; + G_SoundOnEnt(self, CHAN_WEAPON, "sound/weapons/boba/bf_flame.mp3"); + G_PlayEffect(G_EffectIndex("boba/fthrw"), self->playerModel, self->genericBolt3, self->s.number, self->s.origin, 1); self->client->ps.forcePowerDuration[FP_LIGHTNING] = 1; } - Boba_FireFlameThrower( self ); + Boba_FireFlameThrower(self); } return; } - if (!(NPCInfo->aiFlags&NPCAI_FLAMETHROW) && TIMER_Done(self, "nextAttackDelay")) - { - Boba_StartFlameThrower( self ); + if (!(NPCInfo->aiFlags & NPCAI_FLAMETHROW) && TIMER_Done(self, "nextAttackDelay")) { + Boba_StartFlameThrower(self); } - if ( (NPCInfo->aiFlags&NPCAI_FLAMETHROW)) - { - Boba_FireFlameThrower( self ); + if ((NPCInfo->aiFlags & NPCAI_FLAMETHROW)) { + Boba_FireFlameThrower(self); } } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_DoAmbushWait( gentity_t *self) -{ -} +void Boba_DoAmbushWait(gentity_t *self) {} //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_DoSniper( gentity_t *self) -{ - if (TIMER_Done(NPC, "PickNewSniperPoint")) - { +void Boba_DoSniper(gentity_t *self) { + if (TIMER_Done(NPC, "PickNewSniperPoint")) { TIMER_Set(NPC, "PickNewSniperPoint", Q_irand(15000, 25000)); - int SniperPoint = NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_SNIPE|CP_CLEAR|CP_HAS_ROUTE|CP_TRYFAR|CP_HORZ_DIST_COLL, 0, -1); - if (SniperPoint!=-1) - { + int SniperPoint = + NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_SNIPE | CP_CLEAR | CP_HAS_ROUTE | CP_TRYFAR | CP_HORZ_DIST_COLL, 0, -1); + if (SniperPoint != -1) { NPC_SetCombatPoint(SniperPoint); - NPC_SetMoveGoal( NPC, level.combatPoints[SniperPoint].origin, 20, qtrue, SniperPoint ); + NPC_SetMoveGoal(NPC, level.combatPoints[SniperPoint].origin, 20, qtrue, SniperPoint); } } - if (Distance(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin)<50.0f) - { + if (Distance(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin) < 50.0f) { Boba_FireDecide(); } - - bool IsOnAPath = !!NPC_MoveToGoal(qtrue); + bool IsOnAPath = !!NPC_MoveToGoal(qtrue); // Resolve Blocked Problems //-------------------------- - if (NPCInfo->aiFlags&NPCAI_BLOCKED && - NPC->client->moveType!=MT_FLYSWIM && - ((level.time - NPCInfo->blockedDebounceTime)>3000) - ) - { + if (NPCInfo->aiFlags & NPCAI_BLOCKED && NPC->client->moveType != MT_FLYSWIM && ((level.time - NPCInfo->blockedDebounceTime) > 3000)) { Boba_Printf("BLOCKED: Attempting Jump"); - if (IsOnAPath) - { - if (!NPC_TryJump(NPCInfo->blockedTargetPosition)) - { + if (IsOnAPath) { + if (!NPC_TryJump(NPCInfo->blockedTargetPosition)) { Boba_Printf(" Failed"); } } } NPC_FaceEnemy(qtrue); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - //////////////////////////////////////////////////////////////////////////////////////// // Call This function to make Boba actually shoot his current weapon //////////////////////////////////////////////////////////////////////////////////////// -void Boba_Fire() -{ +void Boba_Fire() { WeaponThink(qtrue); // If Actually Fired, Decide To Apply Alt Fire And Calc Next Attack Delay //------------------------------------------------------------------------ - if (ucmd.buttons&BUTTON_ATTACK) - { - switch (NPC->s.weapon) - { + if (ucmd.buttons & BUTTON_ATTACK) { + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: - TIMER_Set( NPC, "nextAttackDelay", Q_irand(1000, 2000)); + TIMER_Set(NPC, "nextAttackDelay", Q_irand(1000, 2000)); // Occasionally Shoot A Homing Missile //------------------------------------- - if (!Q_irand(0,3)) - { + if (!Q_irand(0, 3)) { ucmd.buttons &= ~BUTTON_ATTACK; - ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1000, 3000 ); + ucmd.buttons |= BUTTON_ALT_ATTACK; + NPC->client->fireDelay = Q_irand(1000, 3000); } break; @@ -668,79 +570,66 @@ void Boba_Fire() // Occasionally Alt-Fire //----------------------- - if (!Q_irand(0,3)) - { + if (!Q_irand(0, 3)) { ucmd.buttons &= ~BUTTON_ATTACK; - ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1000, 3000 ); + ucmd.buttons |= BUTTON_ALT_ATTACK; + NPC->client->fireDelay = Q_irand(1000, 3000); } break; case WP_BLASTER: - if (TIMER_Done(NPC, "nextBlasterAltFireDecide")) - { - if (Q_irand(0, (NPC->count*2)+3)>2) - { - TIMER_Set(NPC, "nextBlasterAltFireDecide", Q_irand(3000, 8000)); - if (!(NPCInfo->scriptFlags&SCF_ALT_FIRE)) - { + if (TIMER_Done(NPC, "nextBlasterAltFireDecide")) { + if (Q_irand(0, (NPC->count * 2) + 3) > 2) { + TIMER_Set(NPC, "nextBlasterAltFireDecide", Q_irand(3000, 8000)); + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { Boba_Printf("ALT FIRE On"); NPCInfo->scriptFlags |= SCF_ALT_FIRE; - NPC_ChangeWeapon(WP_BLASTER); // Update Delay Timers + NPC_ChangeWeapon(WP_BLASTER); // Update Delay Timers } - } - else - { + } else { TIMER_Set(NPC, "nextBlasterAltFireDecide", Q_irand(2000, 5000)); - if ( (NPCInfo->scriptFlags&SCF_ALT_FIRE)) - { + if ((NPCInfo->scriptFlags & SCF_ALT_FIRE)) { Boba_Printf("ALT FIRE Off"); - NPCInfo->scriptFlags &=~SCF_ALT_FIRE; - NPC_ChangeWeapon(WP_BLASTER); // Update Delay Timers + NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; + NPC_ChangeWeapon(WP_BLASTER); // Update Delay Timers } } } // Occasionally Alt Fire //----------------------- - if (NPCInfo->scriptFlags&SCF_ALT_FIRE) - { + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { ucmd.buttons &= ~BUTTON_ATTACK; - ucmd.buttons |= BUTTON_ALT_ATTACK; + ucmd.buttons |= BUTTON_ALT_ATTACK; } break; } } } - //////////////////////////////////////////////////////////////////////////////////////// // Call this function to see if Fett should fire his current weapon //////////////////////////////////////////////////////////////////////////////////////// -void Boba_FireDecide( void ) -{ +void Boba_FireDecide(void) { // Any Reason Not To Shoot? //-------------------------- - if (!NPC || // Only NPCs - !NPC->client || // Only Clients - NPC->client->NPC_class!=CLASS_BOBAFETT || // Only Boba - !NPC->enemy || // Only If There Is An Enemy - NPC->s.weapon==WP_NONE || // Only If Using A Valid Weapon - !TIMER_Done(NPC, "nextAttackDelay") || // Only If Ready To Shoot Again - !Boba_CanSeeEnemy(NPC) // Only If Enemy Recently Seen - ) - { + if (!NPC || // Only NPCs + !NPC->client || // Only Clients + NPC->client->NPC_class != CLASS_BOBAFETT || // Only Boba + !NPC->enemy || // Only If There Is An Enemy + NPC->s.weapon == WP_NONE || // Only If Using A Valid Weapon + !TIMER_Done(NPC, "nextAttackDelay") || // Only If Ready To Shoot Again + !Boba_CanSeeEnemy(NPC) // Only If Enemy Recently Seen + ) { return; } // Now Check Weapon Specific Parameters To See If We Should Shoot Or Not //----------------------------------------------------------------------- - switch (NPC->s.weapon) - { + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: - if (Distance(NPC->currentOrigin, NPC->enemy->currentOrigin)>400.0f) - { + if (Distance(NPC->currentOrigin, NPC->enemy->currentOrigin) > 400.0f) { Boba_Fire(); } break; @@ -757,8 +646,6 @@ void Boba_FireDecide( void ) } } - - //////////////////////////////////////////////////////////////////////////////////////// // Tactics avaliable to Boba Fett: // -------------------------------- @@ -777,102 +664,81 @@ void Boba_FireDecide( void ) // WP_DISRUPTOR // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_TacticsSelect() -{ +void Boba_TacticsSelect() { // Don't Change Tactics For A Little While //------------------------------------------ TIMER_Set(NPC, "Boba_TacticsSelect", Q_irand(8000, 15000)); - int nextState = NPCInfo->localState; - + int nextState = NPCInfo->localState; // Get Some Data That Will Help With The Selection Of The Next Tactic //-------------------------------------------------------------------- - bool enemyAlive = (NPC->enemy->health>0); - float enemyDistance = Distance(NPC->currentOrigin, NPC->enemy->currentOrigin); - bool enemyInFlameRange = (enemyDistanceBOBA_ROCKETRANGEMIN && enemyDistanceenemy->health > 0); + float enemyDistance = Distance(NPC->currentOrigin, NPC->enemy->currentOrigin); + bool enemyInFlameRange = (enemyDistance < BOBA_FLAMETHROWRANGE); + bool enemyInRocketRange = (enemyDistance > BOBA_ROCKETRANGEMIN && enemyDistance < BOBA_ROCKETRANGEMAX); + bool enemyRecentlySeen = Boba_CanSeeEnemy(NPC); // Enemy Is Really Close //----------------------- - if (!enemyAlive) - { + if (!enemyAlive) { nextState = BTS_RIFLE; - } - else if (enemyInFlameRange) - { + } else if (enemyInFlameRange) { // If It's Been Long Enough Since Our Last Flame Blast, Try To Torch The Enemy //----------------------------------------------------------------------------- - if (TIMER_Done(NPC, "nextFlameDelay")) - { + if (TIMER_Done(NPC, "nextFlameDelay")) { nextState = BTS_FLAMETHROW; } // Otherwise, He's Probably Too Close, So Try To Get Clear Of Him //---------------------------------------------------------------- - else - { + else { nextState = BTS_RIFLE; } } // Recently Saw The Enemy, Time For Some Good Ole Fighten! //--------------------------------------------------------- - else if (enemyRecentlySeen) - { + else if (enemyRecentlySeen) { // At First, Boba will prefer to use his blaster against the player, but // the more times he is driven away (NPC->count), he will be less likely to // choose the blaster, and more likely to go for the missile launcher - nextState = (!enemyInRocketRange || Q_irand(0, NPC->count)<1)?(BTS_RIFLE):(BTS_MISSILE); + nextState = (!enemyInRocketRange || Q_irand(0, NPC->count) < 1) ? (BTS_RIFLE) : (BTS_MISSILE); } // Hmmm... Havn't Seen The Player In A While, We Might Want To Try Something Sneaky //----------------------------------------------------------------------------------- - else - { - bool SnipePointsNear = false; // TODO - bool AmbushPointNear = false; // TODO - - if (Q_irand(0, NPC->count)>0) - { - int SniperPoint = NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_SNIPE|CP_CLEAR|CP_HAS_ROUTE|CP_TRYFAR|CP_HORZ_DIST_COLL, 0, -1); - if (SniperPoint!=-1) - { + else { + bool SnipePointsNear = false; // TODO + bool AmbushPointNear = false; // TODO + + if (Q_irand(0, NPC->count) > 0) { + int SniperPoint = + NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_SNIPE | CP_CLEAR | CP_HAS_ROUTE | CP_TRYFAR | CP_HORZ_DIST_COLL, 0, -1); + if (SniperPoint != -1) { NPC_SetCombatPoint(SniperPoint); - NPC_SetMoveGoal( NPC, level.combatPoints[SniperPoint].origin, 20, qtrue, SniperPoint ); + NPC_SetMoveGoal(NPC, level.combatPoints[SniperPoint].origin, 20, qtrue, SniperPoint); TIMER_Set(NPC, "PickNewSniperPoint", Q_irand(15000, 25000)); SnipePointsNear = true; } } - - if (SnipePointsNear && TIMER_Done(NPC, "Boba_NoSniperTime")) - { - TIMER_Set(NPC, "Boba_NoSniperTime", 120000); // Don't snipe again for a while - TIMER_Set(NPC, "Boba_TacticsSelect", Q_irand(35000, 45000));// More patience here + if (SnipePointsNear && TIMER_Done(NPC, "Boba_NoSniperTime")) { + TIMER_Set(NPC, "Boba_NoSniperTime", 120000); // Don't snipe again for a while + TIMER_Set(NPC, "Boba_TacticsSelect", Q_irand(35000, 45000)); // More patience here nextState = BTS_SNIPER; - } - else if (AmbushPointNear) - { - TIMER_Set(NPC, "Boba_TacticsSelect", Q_irand(15000, 25000));// More patience here + } else if (AmbushPointNear) { + TIMER_Set(NPC, "Boba_TacticsSelect", Q_irand(15000, 25000)); // More patience here nextState = BTS_AMBUSHWAIT; - } - else - { - nextState = (!enemyInRocketRange || Q_irand(0, NPC->count)<1)?(BTS_RIFLE):(BTS_MISSILE); + } else { + nextState = (!enemyInRocketRange || Q_irand(0, NPC->count) < 1) ? (BTS_RIFLE) : (BTS_MISSILE); } } - - // The Next State Has Been Selected, Now Change Weapon If Necessary //------------------------------------------------------------------ - if (nextState!=NPCInfo->localState) - { + if (nextState != NPCInfo->localState) { NPCInfo->localState = nextState; - switch (NPCInfo->localState) - { + switch (NPCInfo->localState) { case BTS_FLAMETHROW: Boba_Printf("NEW TACTIC: Flame Thrower"); Boba_ChangeWeapon(WP_NONE); @@ -902,7 +768,6 @@ void Boba_TacticsSelect() } } - //////////////////////////////////////////////////////////////////////////////////////// // Tactics // @@ -910,92 +775,77 @@ void Boba_TacticsSelect() // If returns true, Jedi and Seeker AI not used for movement // //////////////////////////////////////////////////////////////////////////////////////// -bool Boba_Tactics() -{ - if (!NPC->enemy) - { +bool Boba_Tactics() { + if (!NPC->enemy) { return false; } // Think About Changing Tactics //------------------------------ - if (TIMER_Done(NPC, "Boba_TacticsSelect")) - { + if (TIMER_Done(NPC, "Boba_TacticsSelect")) { Boba_TacticsSelect(); } // These Tactics Require Seeker & Jedi Movement //---------------------------------------------- - if (!NPCInfo->localState || - NPCInfo->localState==BTS_RIFLE || - NPCInfo->localState==BTS_MISSILE) - { + if (!NPCInfo->localState || NPCInfo->localState == BTS_RIFLE || NPCInfo->localState == BTS_MISSILE) { return false; } // Flame Thrower - Locked In Place //--------------------------------- - if (NPCInfo->localState==BTS_FLAMETHROW) - { - Boba_DoFlameThrower( NPC ); + if (NPCInfo->localState == BTS_FLAMETHROW) { + Boba_DoFlameThrower(NPC); } // Sniper - Move Around, And Take Shots //-------------------------------------- - else if (NPCInfo->localState==BTS_SNIPER) - { - Boba_DoSniper( NPC ); + else if (NPCInfo->localState == BTS_SNIPER) { + Boba_DoSniper(NPC); } // Ambush Wait //------------ - else if (NPCInfo->localState==BTS_AMBUSHWAIT) - { - Boba_DoAmbushWait( NPC ); + else if (NPCInfo->localState == BTS_AMBUSHWAIT) { + Boba_DoAmbushWait(NPC); } - - NPC_FacePosition( NPC->enemy->currentOrigin, qtrue); + NPC_FacePosition(NPC->enemy->currentOrigin, qtrue); NPC_UpdateAngles(qtrue, qtrue); - return true; // Do Not Use Normal Jedi Or Seeker Movement + return true; // Do Not Use Normal Jedi Or Seeker Movement } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Boba_Respawn() -{ +bool Boba_Respawn() { int cp = -1; // Try To Predict Where The Enemy Is Going //----------------------------------------- - if (AverageEnemyDirectionSamples && NPC->behaviorSet[BSET_DEATH]==0) - { - vec3_t endPos; - VectorMA(NPC->enemy->currentOrigin, 1000.0f / (float)AverageEnemyDirectionSamples, AverageEnemyDirection, endPos); - cp = NPC_FindCombatPoint(endPos, 0, endPos, CP_FLEE|CP_TRYFAR|CP_HORZ_DIST_COLL, 0, -1); + if (AverageEnemyDirectionSamples && NPC->behaviorSet[BSET_DEATH] == 0) { + vec3_t endPos; + VectorMA(NPC->enemy->currentOrigin, 1000.0f / (float)AverageEnemyDirectionSamples, AverageEnemyDirection, endPos); + cp = NPC_FindCombatPoint(endPos, 0, endPos, CP_FLEE | CP_TRYFAR | CP_HORZ_DIST_COLL, 0, -1); Boba_Printf("Attempting Predictive Spawn Point"); } // If That Failed, Try To Go Directly To The Enemy //------------------------------------------------- - if (cp==-1) - { - cp = NPC_FindCombatPoint(NPC->enemy->currentOrigin, 0, NPC->enemy->currentOrigin, CP_FLEE|CP_TRYFAR|CP_HORZ_DIST_COLL, 0, -1); + if (cp == -1) { + cp = NPC_FindCombatPoint(NPC->enemy->currentOrigin, 0, NPC->enemy->currentOrigin, CP_FLEE | CP_TRYFAR | CP_HORZ_DIST_COLL, 0, -1); Boba_Printf("Attempting Closest Current Spawn Point"); } // If We've Found One, Go There //------------------------------ - if (cp!=-1) - { - NPC_SetCombatPoint( cp ); + if (cp != -1) { + NPC_SetCombatPoint(cp); NPCInfo->surrenderTime = 0; NPC->health = NPC->max_health; - NPC->svFlags &=~SVF_NOCLIENT; - NPC->count ++; // This is the number of times spawned + NPC->svFlags &= ~SVF_NOCLIENT; + NPC->count++; // This is the number of times spawned G_SetOrigin(NPC, level.combatPoints[cp].origin); AverageEnemyDirectionSamples = 0; @@ -1005,286 +855,214 @@ bool Boba_Respawn() return true; } - assert(0); // Yea, that's bad... + assert(0); // Yea, that's bad... Boba_Printf("FAILED TO FIND SPAWN POINT"); return false; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Boba_Update() -{ +void Boba_Update() { // Never Forget The Player... Never. //----------------------------------- - if (player && player->inuse && !NPC->enemy) - { + if (player && player->inuse && !NPC->enemy) { G_SetEnemy(NPC, player); - NPC->svFlags |= SVF_LOCKEDENEMY; // Don't forget about the enemy once you've found him + NPC->svFlags |= SVF_LOCKEDENEMY; // Don't forget about the enemy once you've found him } // Hey, This Is Boba, He Tests The Trace All The Time //---------------------------------------------------- - if (NPC->enemy) - { - if (!(NPC->svFlags&SVF_NOCLIENT)) - { - trace_t testTrace; - vec3_t eyes; - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); - gi.trace (&testTrace, eyes, NULL, NULL, NPC->enemy->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); - - bool wasSeen = Boba_CanSeeEnemy(NPC); - - if (!testTrace.startsolid && - !testTrace.allsolid && - testTrace.entityNum == NPC->enemy->s.number) - { - NPCInfo->enemyLastSeenTime = level.time; - NPCInfo->enemyLastHeardTime = level.time; + if (NPC->enemy) { + if (!(NPC->svFlags & SVF_NOCLIENT)) { + trace_t testTrace; + vec3_t eyes; + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); + gi.trace(&testTrace, eyes, NULL, NULL, NPC->enemy->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + + bool wasSeen = Boba_CanSeeEnemy(NPC); + + if (!testTrace.startsolid && !testTrace.allsolid && testTrace.entityNum == NPC->enemy->s.number) { + NPCInfo->enemyLastSeenTime = level.time; + NPCInfo->enemyLastHeardTime = level.time; VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastHeardLocation); - } - else if (gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin)) - { - NPCInfo->enemyLastHeardTime = level.time; + } else if (gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { + NPCInfo->enemyLastHeardTime = level.time; VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastHeardLocation); } - if (g_bobaDebug->integer) - { - bool nowSeen = Boba_CanSeeEnemy(NPC); - if (!wasSeen && nowSeen) - { + if (g_bobaDebug->integer) { + bool nowSeen = Boba_CanSeeEnemy(NPC); + if (!wasSeen && nowSeen) { Boba_Printf("Enemy Seen"); } - if (wasSeen && !nowSeen) - { + if (wasSeen && !nowSeen) { Boba_Printf("Enemy Lost"); } - CG_DrawEdge(NPC->currentOrigin, NPC->enemy->currentOrigin, (nowSeen)?(EDGE_IMPACT_SAFE):(EDGE_IMPACT_POSSIBLE)); + CG_DrawEdge(NPC->currentOrigin, NPC->enemy->currentOrigin, (nowSeen) ? (EDGE_IMPACT_SAFE) : (EDGE_IMPACT_POSSIBLE)); } } - if (!NPCInfo->surrenderTime) - { - if ((level.time - NPCInfo->enemyLastSeenTime)>20000 && TIMER_Done(NPC, "TooLongGoneRespawn")) - { - TIMER_Set(NPC, "TooLongGoneRespawn", 30000); // Give him some time to get to you before trying again + if (!NPCInfo->surrenderTime) { + if ((level.time - NPCInfo->enemyLastSeenTime) > 20000 && TIMER_Done(NPC, "TooLongGoneRespawn")) { + TIMER_Set(NPC, "TooLongGoneRespawn", 30000); // Give him some time to get to you before trying again Boba_Printf("Gone Too Long, Attempting Respawn Even Though Not Hiding"); Boba_Respawn(); } } } - // Make Sure He Always Appears In The Last Area With Full Health When His Death Script Is Turned On //-------------------------------------------------------------------------------------------------- - if (!BobaHadDeathScript && NPC->behaviorSet[BSET_DEATH]!=0) - { - if (!gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) - { + if (!BobaHadDeathScript && NPC->behaviorSet[BSET_DEATH] != 0) { + if (!gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { Boba_Printf("Attempting Final Battle Spawn..."); - if (Boba_Respawn()) - { + if (Boba_Respawn()) { BobaHadDeathScript = true; - } - else - { + } else { Boba_Printf("Failed"); } } } - - // Don't Forget To Turn Off That Flame Thrower, Mr. Fett - You're Waisting Precious Natural Gases //------------------------------------------------------------------------------------------------ - if ((NPCInfo->aiFlags&NPCAI_FLAMETHROW) && (TIMER_Done(NPC, "flameTime"))) - { + if ((NPCInfo->aiFlags & NPCAI_FLAMETHROW) && (TIMER_Done(NPC, "flameTime"))) { Boba_StopFlameThrower(NPC); } - // Occasionally A Jump Turns Into A Rocket Fly //--------------------------------------------- - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE - && NPC->client->ps.forceJumpZStart - && !Q_irand( 0, 10 ) ) - {//take off - Boba_FlyStart( NPC ); + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE && NPC->client->ps.forceJumpZStart && !Q_irand(0, 10)) { // take off + Boba_FlyStart(NPC); } - // If Hurting, Try To Run Away //----------------------------- - if (!NPCInfo->surrenderTime && (NPC->healthmax_health/10)) - { + if (!NPCInfo->surrenderTime && (NPC->health < NPC->max_health / 10)) { Boba_Printf("Time To Surrender, Searching For Flee Point"); - // Find The Closest Flee Point That I Can Get To //----------------------------------------------- - int cp = NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_FLEE|CP_HAS_ROUTE|CP_TRYFAR|CP_HORZ_DIST_COLL, 0, -1); - if (cp!=-1) - { - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); - if (NPC->count<6) - { - NPCInfo->surrenderTime = level.time + Q_irand(5000, 10000) + 1000*(6-NPC->count); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, 0, NPC->currentOrigin, CP_FLEE | CP_HAS_ROUTE | CP_TRYFAR | CP_HORZ_DIST_COLL, 0, -1); + if (cp != -1) { + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + if (NPC->count < 6) { + NPCInfo->surrenderTime = level.time + Q_irand(5000, 10000) + 1000 * (6 - NPC->count); + } else { + NPCInfo->surrenderTime = level.time + Q_irand(5000, 10000); } - else - { - NPCInfo->surrenderTime = level.time + Q_irand(5000, 10000); - } - } - else - { + } else { Boba_Printf(" Failure"); } } } - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Boba_Flee() -{ - bool EnemyRecentlySeen = ((level.time - NPCInfo->enemyLastSeenTime)<10000); - bool ReachedEscapePoint = (Distance(level.combatPoints[NPCInfo->combatPoint].origin, NPC->currentOrigin)<50.0f); - bool HasBeenGoneEnough = (level.time>NPCInfo->surrenderTime || (level.time - NPCInfo->enemyLastSeenTime)>400000); - +bool Boba_Flee() { + bool EnemyRecentlySeen = ((level.time - NPCInfo->enemyLastSeenTime) < 10000); + bool ReachedEscapePoint = (Distance(level.combatPoints[NPCInfo->combatPoint].origin, NPC->currentOrigin) < 50.0f); + bool HasBeenGoneEnough = (level.time > NPCInfo->surrenderTime || (level.time - NPCInfo->enemyLastSeenTime) > 400000); // Is It Time To Come Back For Some More? //---------------------------------------- - if (!EnemyRecentlySeen || ReachedEscapePoint) - { + if (!EnemyRecentlySeen || ReachedEscapePoint) { NPC->svFlags |= SVF_NOCLIENT; - if (HasBeenGoneEnough) - { - if ((level.time - NPCInfo->enemyLastSeenTime)>400000) - { + if (HasBeenGoneEnough) { + if ((level.time - NPCInfo->enemyLastSeenTime) > 400000) { Boba_Printf(" Gone Too Long, Attempting Respawn"); } - if (Boba_Respawn()) - { + if (Boba_Respawn()) { return true; } - } - else if (ReachedEscapePoint && (NPCInfo->surrenderTime - level.time)>3000) - { - if (TIMER_Done(NPC, "SpookPlayerTimer")) - { - vec3_t testDirection; + } else if (ReachedEscapePoint && (NPCInfo->surrenderTime - level.time) > 3000) { + if (TIMER_Done(NPC, "SpookPlayerTimer")) { + vec3_t testDirection; TIMER_Set(NPC, "SpookPlayerTimer", Q_irand(2000, 10000)); - switch(Q_irand(0, 1)) - { + switch (Q_irand(0, 1)) { case 0: Boba_Printf("SPOOK: Dust"); - Boba_DustFallNear(NPC->enemy->currentOrigin, Q_irand(1,2)); + Boba_DustFallNear(NPC->enemy->currentOrigin, Q_irand(1, 2)); break; case 1: Boba_Printf("SPOOK: Footsteps"); - testDirection[0] = (Q_flrand(0.0f, 1.0f) * 0.5f) - 1.0f; - testDirection[0] += (testDirection[0]>0.0f)?(0.5f):(-0.5f); + testDirection[0] = (Q_flrand(0.0f, 1.0f) * 0.5f) - 1.0f; + testDirection[0] += (testDirection[0] > 0.0f) ? (0.5f) : (-0.5f); testDirection[1] = (Q_flrand(0.0f, 1.0f) * 0.5f) - 1.0f; - testDirection[1] += (testDirection[1]>0.0f)?(0.5f):(-0.5f); + testDirection[1] += (testDirection[1] > 0.0f) ? (0.5f) : (-0.5f); testDirection[2] = 1.0f; - VectorMA(NPC->enemy->currentOrigin, 400.0f, testDirection, BobaFootStepLoc); + VectorMA(NPC->enemy->currentOrigin, 400.0f, testDirection, BobaFootStepLoc); - BobaFootStepCount = Q_irand(3,8); + BobaFootStepCount = Q_irand(3, 8); break; } } - if (BobaFootStepCount && TIMER_Done(NPC, "BobaFootStepFakeTimer")) - { + if (BobaFootStepCount && TIMER_Done(NPC, "BobaFootStepFakeTimer")) { TIMER_Set(NPC, "BobaFootStepFakeTimer", Q_irand(300, 800)); - BobaFootStepCount --; - G_SoundAtSpot(BobaFootStepLoc, G_SoundIndex(va("sound/player/footsteps/boot%d", Q_irand(1,4))), qtrue); + BobaFootStepCount--; + G_SoundAtSpot(BobaFootStepLoc, G_SoundIndex(va("sound/player/footsteps/boot%d", Q_irand(1, 4))), qtrue); } - if (TIMER_Done(NPC, "ResampleEnemyDirection") && NPC->enemy->resultspeed>10.0f) - { + if (TIMER_Done(NPC, "ResampleEnemyDirection") && NPC->enemy->resultspeed > 10.0f) { TIMER_Set(NPC, "ResampleEnemyDirection", Q_irand(500, 1000)); - AverageEnemyDirectionSamples ++; + AverageEnemyDirectionSamples++; - vec3_t moveDir; + vec3_t moveDir; VectorCopy(NPC->enemy->client->ps.velocity, moveDir); VectorNormalize(moveDir); VectorAdd(AverageEnemyDirection, moveDir, AverageEnemyDirection); } - if (g_bobaDebug->integer && AverageEnemyDirectionSamples) - { - vec3_t endPos; + if (g_bobaDebug->integer && AverageEnemyDirectionSamples) { + vec3_t endPos; VectorMA(NPC->enemy->currentOrigin, 500.0f / (float)AverageEnemyDirectionSamples, AverageEnemyDirection, endPos); CG_DrawEdge(NPC->enemy->currentOrigin, endPos, EDGE_IMPACT_POSSIBLE); } } - } - else - { + } else { NPCInfo->surrenderTime += 100; } // Finish The Flame Thrower First... //----------------------------------- - if (NPCInfo->aiFlags&NPCAI_FLAMETHROW) - { - Boba_DoFlameThrower( NPC ); - NPC_FacePosition( NPC->enemy->currentOrigin, qtrue); + if (NPCInfo->aiFlags & NPCAI_FLAMETHROW) { + Boba_DoFlameThrower(NPC); + NPC_FacePosition(NPC->enemy->currentOrigin, qtrue); NPC_UpdateAngles(qtrue, qtrue); return true; } - bool IsOnAPath = !!NPC_MoveToGoal(qtrue); - if (!ReachedEscapePoint && - NPCInfo->aiFlags&NPCAI_BLOCKED && - NPC->client->moveType!=MT_FLYSWIM && - ((level.time - NPCInfo->blockedDebounceTime)>1000) - ) - { - if (!Boba_CanSeeEnemy(NPC) && Distance(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin)<200) - { + bool IsOnAPath = !!NPC_MoveToGoal(qtrue); + if (!ReachedEscapePoint && NPCInfo->aiFlags & NPCAI_BLOCKED && NPC->client->moveType != MT_FLYSWIM && + ((level.time - NPCInfo->blockedDebounceTime) > 1000)) { + if (!Boba_CanSeeEnemy(NPC) && Distance(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin) < 200) { Boba_Printf("BLOCKED: Just Teleporting There"); G_SetOrigin(NPC, level.combatPoints[NPCInfo->combatPoint].origin); - } - else - { + } else { Boba_Printf("BLOCKED: Attempting Jump"); - if (IsOnAPath) - { - if (NPC_TryJump(NPCInfo->blockedTargetPosition)) - { - } - else - { + if (IsOnAPath) { + if (NPC_TryJump(NPCInfo->blockedTargetPosition)) { + } else { Boba_Printf(" Failed"); } - } - else if (EnemyRecentlySeen) - { - if (NPC_TryJump(NPCInfo->enemyLastSeenLocation)) - { - } - else - { + } else if (EnemyRecentlySeen) { + if (NPC_TryJump(NPCInfo->enemyLastSeenLocation)) { + } else { Boba_Printf(" Failed"); } } } } - - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return true; } \ No newline at end of file diff --git a/code/game/AI_Civilian.cpp b/code/game/AI_Civilian.cpp index b2ba49fc6e..58122f2136 100644 --- a/code/game/AI_Civilian.cpp +++ b/code/game/AI_Civilian.cpp @@ -24,41 +24,27 @@ along with this program; if not, see . #include "b_local.h" #include "Q3_Interface.h" -extern qboolean NPC_CheckSurrender( void ); -extern void NPC_BehaviorSet_Default( int bState ); +extern qboolean NPC_CheckSurrender(void); +extern void NPC_BehaviorSet_Default(int bState); -void NPC_BSCivilian_Default( int bState ) -{ - if ( NPC->enemy - && NPC->s.weapon == WP_NONE - && NPC_CheckSurrender() ) - {//surrendering, do nothing - } - else if ( NPC->enemy - && NPC->s.weapon == WP_NONE - && bState != BS_HUNT_AND_KILL - && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there - if ( !NPCInfo->goalEntity - || bState != BS_FLEE //not fleeing - || ( NPC_BSFlee()//have reached our flee goal - && NPC->enemy//still have enemy (NPC_BSFlee checks enemy and can clear it) - && DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ) < 16384 )//enemy within 128 - ) - {//run away! - NPC_StartFlee( NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); +void NPC_BSCivilian_Default(int bState) { + if (NPC->enemy && NPC->s.weapon == WP_NONE && NPC_CheckSurrender()) { // surrendering, do nothing + } else if (NPC->enemy && NPC->s.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && + !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there + if (!NPCInfo->goalEntity || bState != BS_FLEE // not fleeing + || (NPC_BSFlee() // have reached our flee goal + && NPC->enemy // still have enemy (NPC_BSFlee checks enemy and can clear it) + && DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin) < 16384) // enemy within 128 + ) { // run away! + NPC_StartFlee(NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000); } - } - else - {//not surrendering - //FIXME: if unarmed and a jawa/ugnuaght, constantly look for enemies/players to run away from? - //FIXME: if we have a weapon and an enemy, set out playerTeam to the opposite of our enemy..??? + } else { // not surrendering + // FIXME: if unarmed and a jawa/ugnuaght, constantly look for enemies/players to run away from? + // FIXME: if we have a weapon and an enemy, set out playerTeam to the opposite of our enemy..??? NPC_BehaviorSet_Default(bState); } - if ( !VectorCompare( NPC->client->ps.moveDir, vec3_origin ) ) - {//moving - if ( NPC->client->ps.legsAnim == BOTH_COWER1 ) - {//stop cowering anim on legs + if (!VectorCompare(NPC->client->ps.moveDir, vec3_origin)) { // moving + if (NPC->client->ps.legsAnim == BOTH_COWER1) { // stop cowering anim on legs NPC->client->ps.legsAnimTimer = 0; } } diff --git a/code/game/AI_Default.cpp b/code/game/AI_Default.cpp index 368cf10832..b343c4425a 100644 --- a/code/game/AI_Default.cpp +++ b/code/game/AI_Default.cpp @@ -33,23 +33,20 @@ void NPC_LostEnemyDecideChase(void) We lost our enemy and want to drop him but see if we should chase him if we are in the proper bState */ -void NPC_LostEnemyDecideChase(void) -{ - switch( NPCInfo->behaviorState ) - { +void NPC_LostEnemyDecideChase(void) { + switch (NPCInfo->behaviorState) { case BS_HUNT_AND_KILL: - //We were chasing him and lost him, so try to find him - if ( NPC->enemy == NPCInfo->goalEntity && NPC->enemy->lastWaypoint != WAYPOINT_NONE ) - {//Remember his last valid Wp, then check it out - //FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? - NPC_BSSearchStart( NPC->enemy->lastWaypoint, BS_SEARCH ); + // We were chasing him and lost him, so try to find him + if (NPC->enemy == NPCInfo->goalEntity && NPC->enemy->lastWaypoint != WAYPOINT_NONE) { // Remember his last valid Wp, then check it out + // FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? + NPC_BSSearchStart(NPC->enemy->lastWaypoint, BS_SEARCH); } - //If he's not our goalEntity, we're running somewhere else, so lose him + // If he's not our goalEntity, we're running somewhere else, so lose him break; default: break; } - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); } /* ------------------------- @@ -57,99 +54,86 @@ NPC_StandIdle ------------------------- */ -void NPC_StandIdle( void ) -{ -/* - //Must be done with any other animations - if ( NPC->client->ps.legsAnimTimer != 0 ) - return; +void NPC_StandIdle(void) { + /* + //Must be done with any other animations + if ( NPC->client->ps.legsAnimTimer != 0 ) + return; - //Not ready to do another one - if ( TIMER_Done( NPC, "idleAnim" ) == false ) - return; + //Not ready to do another one + if ( TIMER_Done( NPC, "idleAnim" ) == false ) + return; - int anim = NPC->client->ps.legsAnim; + int anim = NPC->client->ps.legsAnim; - if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) - return; + if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) + return; - //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly - int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; + //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly + int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; - //Must have at least one random idle animation - //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay - if ( PM_HasAnimation( NPC, baseSeq ) == false ) - return; + //Must have at least one random idle animation + //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay + if ( PM_HasAnimation( NPC, baseSeq ) == false ) + return; - int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); + int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); - //FIXME: Technically this could never complete.. but that's not really too likely - while( 1 ) - { - if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) - break; + //FIXME: Technically this could never complete.. but that's not really too likely + while( 1 ) + { + if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) + break; - newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); - } + newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); + } - //Start that animation going - NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + //Start that animation going + NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); + int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); - //Don't do this again for a random amount of time - TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); -*/ + //Don't do this again for a random amount of time + TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); + */ } -qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) -{ - qboolean attack_ok = qfalse; - qboolean duck_ok = qfalse; - qboolean faced = qfalse; - float attack_scale = 1.0; - - //First see if we're hurt bad- if so, duck - //FIXME: if even when ducked, we can shoot someone, we should. - //Maybe is can be shot even when ducked, we should run away to the nearest cover? - if ( canDuck ) - { - if ( NPC->health < 20 ) - { - // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) - if( Q_flrand(0.0f, 1.0f) ) - { +qboolean NPC_StandTrackAndShoot(gentity_t *NPC, qboolean canDuck) { + qboolean attack_ok = qfalse; + qboolean duck_ok = qfalse; + qboolean faced = qfalse; + float attack_scale = 1.0; + + // First see if we're hurt bad- if so, duck + // FIXME: if even when ducked, we can shoot someone, we should. + // Maybe is can be shot even when ducked, we should run away to the nearest cover? + if (canDuck) { + if (NPC->health < 20) { + // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) + if (Q_flrand(0.0f, 1.0f)) { duck_ok = qtrue; } - } - else if ( NPC->health < 40 ) - { -// if ( NPC->svFlags&SVF_HEALING ) -// {//Medic is on the way, get down! -// duck_ok = qtrue; -// } + } else if (NPC->health < 40) { + // if ( NPC->svFlags&SVF_HEALING ) + // {//Medic is on the way, get down! + // duck_ok = qtrue; + // } } } - //NPC_CheckEnemy( qtrue, qfalse ); + // NPC_CheckEnemy( qtrue, qfalse ); - if ( !duck_ok ) - {//made this whole part a function call - attack_ok = NPC_CheckCanAttack( attack_scale, qtrue ); + if (!duck_ok) { // made this whole part a function call + attack_ok = NPC_CheckCanAttack(attack_scale, qtrue); faced = qtrue; } - if ( canDuck && (duck_ok || (!attack_ok && client->fireDelay == 0)) && ucmd.upmove != -127 ) - {//if we didn't attack check to duck if we're not already - if( !duck_ok ) - { - if ( NPC->enemy->client ) - { - if ( NPC->enemy->enemy == NPC ) - { - if ( NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? + if (canDuck && (duck_ok || (!attack_ok && client->fireDelay == 0)) && ucmd.upmove != -127) { // if we didn't attack check to duck if we're not already + if (!duck_ok) { + if (NPC->enemy->client) { + if (NPC->enemy->enemy == NPC) { + if (NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? { duck_ok = qtrue; } @@ -158,86 +142,68 @@ qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) } } - if ( duck_ok ) - {//duck and don't shoot + if (duck_ok) { // duck and don't shoot attack_ok = qfalse; ucmd.upmove = -127; - NPCInfo->duckDebounceTime = level.time + 1000;//duck for a full second + NPCInfo->duckDebounceTime = level.time + 1000; // duck for a full second } } return faced; } - -void NPC_BSIdle( void ) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSIdle(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - if ( ( ucmd.forwardmove == 0 ) && ( ucmd.rightmove == 0 ) && ( ucmd.upmove == 0 ) ) - { -// NPC_StandIdle(); + if ((ucmd.forwardmove == 0) && (ucmd.rightmove == 0) && (ucmd.upmove == 0)) { + // NPC_StandIdle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); ucmd.buttons |= BUTTON_WALKING; } -void NPC_BSRun (void) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSRun(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSStandGuard (void) -{ - //FIXME: Use Snapshot info - if ( NPC->enemy == NULL ) - {//Possible to pick one up by being shot - if( Q_flrand(0.0f, 1.0f) < 0.5 ) - { - if(NPC->client->enemyTeam) - { - gentity_t *newenemy = NPC_PickEnemy( - NPC, NPC->client->enemyTeam, - (qboolean)(NPC->cantHitEnemyCounter < 10), - (qboolean)(NPC->client->enemyTeam == TEAM_PLAYER), - qtrue); - - //only checks for vis if couldn't hit last enemy - if(newenemy) - { - G_SetEnemy( NPC, newenemy ); +void NPC_BSStandGuard(void) { + // FIXME: Use Snapshot info + if (NPC->enemy == NULL) { // Possible to pick one up by being shot + if (Q_flrand(0.0f, 1.0f) < 0.5) { + if (NPC->client->enemyTeam) { + gentity_t *newenemy = NPC_PickEnemy(NPC, NPC->client->enemyTeam, (qboolean)(NPC->cantHitEnemyCounter < 10), + (qboolean)(NPC->client->enemyTeam == TEAM_PLAYER), qtrue); + + // only checks for vis if couldn't hit last enemy + if (newenemy) { + G_SetEnemy(NPC, newenemy); } } } } - if ( NPC->enemy != NULL ) - { - if( NPCInfo->tempBehavior == BS_STAND_GUARD ) - { + if (NPC->enemy != NULL) { + if (NPCInfo->tempBehavior == BS_STAND_GUARD) { NPCInfo->tempBehavior = BS_DEFAULT; } - if( NPCInfo->behaviorState == BS_STAND_GUARD ) - { + if (NPCInfo->behaviorState == BS_STAND_GUARD) { NPCInfo->behaviorState = BS_STAND_AND_SHOOT; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -246,92 +212,77 @@ NPC_BSHuntAndKill ------------------------- */ -void NPC_BSHuntAndKill( void ) -{ - qboolean turned = qfalse; - vec3_t vec; - float enemyDist; - visibility_t oEVis; - int curAnim; - - NPC_CheckEnemy( (qboolean)(NPCInfo->tempBehavior != BS_HUNT_AND_KILL), qfalse );//don't find new enemy if this is tempbehav - - if ( NPC->enemy ) - { - oEVis = enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|//CHECK_PVS| - if(enemyVisibility > VIS_PVS) - { - if ( !NPC_EnemyTooFar( NPC->enemy, 0, qtrue ) ) - {//Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for info on whether ot not to turn later - NPC_CheckCanAttack( 1.0, qfalse ); +void NPC_BSHuntAndKill(void) { + qboolean turned = qfalse; + vec3_t vec; + float enemyDist; + visibility_t oEVis; + int curAnim; + + NPC_CheckEnemy((qboolean)(NPCInfo->tempBehavior != BS_HUNT_AND_KILL), qfalse); // don't find new enemy if this is tempbehav + + if (NPC->enemy) { + oEVis = enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|//CHECK_PVS| + if (enemyVisibility > VIS_PVS) { + if (!NPC_EnemyTooFar(NPC->enemy, 0, qtrue)) { // Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for + // info on whether ot not to turn later + NPC_CheckCanAttack(1.0, qfalse); turned = qtrue; } } curAnim = NPC->client->ps.legsAnim; - if(curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 ) - {//Don't move toward enemy if we're in a full-body attack anim - //FIXME, use IdealDistance to determin if we need to close distance + if (curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && + curAnim != BOTH_MELEE2) { // Don't move toward enemy if we're in a full-body attack anim + // FIXME, use IdealDistance to determin if we need to close distance VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); enemyDist = VectorLength(vec); - if( enemyDist > 48 && ((enemyDist*1.5)*(enemyDist*1.5) >= NPC_MaxDistSquaredForWeapon() || - oEVis != VIS_SHOOT || - //!(ucmd.buttons & BUTTON_ATTACK) || - enemyDist > IdealDistance(NPC)*3 ) ) - {//We should close in? + if (enemyDist > 48 && ((enemyDist * 1.5) * (enemyDist * 1.5) >= NPC_MaxDistSquaredForWeapon() || oEVis != VIS_SHOOT || + //!(ucmd.buttons & BUTTON_ATTACK) || + enemyDist > IdealDistance(NPC) * 3)) { // We should close in? NPCInfo->goalEntity = NPC->enemy; - NPC_MoveToGoal( qtrue ); - } - else if(enemyDist < IdealDistance(NPC)) - {//We should back off? - //if(ucmd.buttons & BUTTON_ATTACK) + NPC_MoveToGoal(qtrue); + } else if (enemyDist < IdealDistance(NPC)) { // We should back off? + // if(ucmd.buttons & BUTTON_ATTACK) { NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); ucmd.forwardmove *= -1; ucmd.rightmove *= -1; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); ucmd.buttons |= BUTTON_WALKING; } - }//otherwise, stay where we are + } // otherwise, stay where we are } - } - else - {//ok, stand guard until we find an enemy - if( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { + } else { // ok, stand guard until we find an enemy + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } return; } - if(!turned) - { + if (!turned) { NPC_UpdateAngles(qtrue, qtrue); } } -void NPC_BSStandAndShoot (void) -{ - //FIXME: - //When our numbers outnumber enemies 3 to 1, or only one of them, - //go into hunt and kill mode +void NPC_BSStandAndShoot(void) { + // FIXME: + // When our numbers outnumber enemies 3 to 1, or only one of them, + // go into hunt and kill mode - //FIXME: - //When they're all dead, go to some script or wander off to sickbay? + // FIXME: + // When they're all dead, go to some script or wander off to sickbay? - if(NPC->client->playerTeam && NPC->client->enemyTeam) - { - //FIXME: don't realize this right away- or else enemies show up and we're standing around + if (NPC->client->playerTeam && NPC->client->enemyTeam) { + // FIXME: don't realize this right away- or else enemies show up and we're standing around /* if( teamNumbers[NPC->enemyTeam] == 0 ) {//ok, stand guard until we find another enemy @@ -380,36 +331,29 @@ void NPC_BSStandAndShoot (void) NPC_CheckEnemy(qtrue, qfalse); - if(NPCInfo->duckDebounceTime > level.time && NPC->client->ps.weapon != WP_SABER ) - { + if (NPCInfo->duckDebounceTime > level.time && NPC->client->ps.weapon != WP_SABER) { ucmd.upmove = -127; - if(NPC->enemy) - { + if (NPC->enemy) { NPC_CheckCanAttack(1.0, qtrue); } return; } - if(NPC->enemy) - { - if(!NPC_StandTrackAndShoot( NPC, qtrue )) - {//That func didn't update our angles + if (NPC->enemy) { + if (!NPC_StandTrackAndShoot(NPC, qtrue)) { // That func didn't update our angles NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); } - } - else - { + } else { NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); -// NPC_BSIdle();//only moves if we have a goal + // NPC_BSIdle();//only moves if we have a goal } } -void NPC_BSRunAndShoot (void) -{ +void NPC_BSRunAndShoot(void) { /*if(NPC->playerTeam && NPC->enemyTeam) { //FIXME: don't realize this right away- or else enemies show up and we're standing around @@ -423,130 +367,112 @@ void NPC_BSRunAndShoot (void) } }*/ - //NOTE: are we sure we want ALL run and shoot people to move this way? - //Shouldn't it check to see if we have an enemy and our enemy is our goal?! - //Moved that check into NPC_MoveToGoal - //NPCInfo->combatMove = qtrue; + // NOTE: are we sure we want ALL run and shoot people to move this way? + // Shouldn't it check to see if we have an enemy and our enemy is our goal?! + // Moved that check into NPC_MoveToGoal + // NPCInfo->combatMove = qtrue; - NPC_CheckEnemy( qtrue, qfalse ); + NPC_CheckEnemy(qtrue, qfalse); - if ( NPCInfo->duckDebounceTime > level.time ) // && NPCInfo->hidingGoal ) + if (NPCInfo->duckDebounceTime > level.time) // && NPCInfo->hidingGoal ) { ucmd.upmove = -127; - if ( NPC->enemy ) - { - NPC_CheckCanAttack( 1.0, qfalse ); + if (NPC->enemy) { + NPC_CheckCanAttack(1.0, qfalse); } return; } - if ( NPC->enemy ) - { + if (NPC->enemy) { int monitor = NPC->cantHitEnemyCounter; - NPC_StandTrackAndShoot( NPC, qfalse );//(NPCInfo->hidingGoal != NULL) ); + NPC_StandTrackAndShoot(NPC, qfalse); //(NPCInfo->hidingGoal != NULL) ); - if ( !(ucmd.buttons & BUTTON_ATTACK) && ucmd.upmove >= 0 && NPC->cantHitEnemyCounter > monitor ) - {//not crouching and not firing - vec3_t vec; + if (!(ucmd.buttons & BUTTON_ATTACK) && ucmd.upmove >= 0 && NPC->cantHitEnemyCounter > monitor) { // not crouching and not firing + vec3_t vec; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, vec ); + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); vec[2] = 0; - if ( VectorLength( vec ) > 128 || NPC->cantHitEnemyCounter >= 10 ) - {//run at enemy if too far away - //The cantHitEnemyCounter getting high has other repercussions - //100 (10 seconds) will make you try to pick a new enemy... - //But we're chasing, so we clamp it at 50 here - if ( NPC->cantHitEnemyCounter > 60 ) - { + if (VectorLength(vec) > 128 || NPC->cantHitEnemyCounter >= 10) { // run at enemy if too far away + // The cantHitEnemyCounter getting high has other repercussions + // 100 (10 seconds) will make you try to pick a new enemy... + // But we're chasing, so we clamp it at 50 here + if (NPC->cantHitEnemyCounter > 60) { NPC->cantHitEnemyCounter = 60; } - if ( NPC->cantHitEnemyCounter >= (NPCInfo->stats.aggression+1) * 10 ) - { + if (NPC->cantHitEnemyCounter >= (NPCInfo->stats.aggression + 1) * 10) { NPC_LostEnemyDecideChase(); } - //chase and face + // chase and face ucmd.angles[YAW] = 0; ucmd.angles[PITCH] = 0; NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); NPC_UpdateAngles(qtrue, qtrue); + } else { + // FIXME: this could happen if they're just on the other side + // of a thin wall or something else blocking out shot. That + // would make us just stand there and not go around it... + // but maybe it's okay- might look like we're waiting for + // him to come out...? + // Current solution: runs around if cantHitEnemyCounter gets + // to 10 (1 second). } - else - { - //FIXME: this could happen if they're just on the other side - //of a thin wall or something else blocking out shot. That - //would make us just stand there and not go around it... - //but maybe it's okay- might look like we're waiting for - //him to come out...? - //Current solution: runs around if cantHitEnemyCounter gets - //to 10 (1 second). - } - } - else - {//Clear the can't hit enemy counter here + } else { // Clear the can't hit enemy counter here NPC->cantHitEnemyCounter = 0; } - } - else - { - if ( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + } else { + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCInfo->tempBehavior = BS_DEFAULT; return; } -// NPC_BSRun();//only moves if we have a goal + // NPC_BSRun();//only moves if we have a goal } } -//Simply turn until facing desired angles -void NPC_BSFace (void) -{ - //FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? - //Once this is over, it snaps back to what it was facing before- WHY??? - if( NPC_UpdateAngles ( qtrue, qtrue ) ) - { - Q3_TaskIDComplete( NPC, TID_BSTATE ); +// Simply turn until facing desired angles +void NPC_BSFace(void) { + // FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? + // Once this is over, it snaps back to what it was facing before- WHY??? + if (NPC_UpdateAngles(qtrue, qtrue)) { + Q3_TaskIDComplete(NPC, TID_BSTATE); NPCInfo->desiredYaw = client->ps.viewangles[YAW]; NPCInfo->desiredPitch = client->ps.viewangles[PITCH]; - NPCInfo->aimTime = 0;//ok to turn normally now + NPCInfo->aimTime = 0; // ok to turn normally now } } -void NPC_BSPointShoot (qboolean shoot) -{//FIXME: doesn't check for clear shot... - vec3_t muzzle, dir, angles, org; +void NPC_BSPointShoot(qboolean shoot) { // FIXME: doesn't check for clear shot... + vec3_t muzzle, dir, angles, org; - if ( !NPC->enemy || !NPC->enemy->inuse || (NPC->enemy->NPC && NPC->enemy->health <= 0) ) - {//FIXME: should still keep shooting for a second or two after they actually die... - Q3_TaskIDComplete( NPC, TID_BSTATE ); + if (!NPC->enemy || !NPC->enemy->inuse || + (NPC->enemy->NPC && NPC->enemy->health <= 0)) { // FIXME: should still keep shooting for a second or two after they actually die... + Q3_TaskIDComplete(NPC, TID_BSTATE); goto finished; return; } CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - CalcEntitySpot(NPC->enemy, SPOT_HEAD, org);//Was spot_org - //Head is a little high, so let's aim for the chest: - if ( NPC->enemy->client ) - { - org[2] -= 12;//NOTE: is this enough? + CalcEntitySpot(NPC->enemy, SPOT_HEAD, org); // Was spot_org + // Head is a little high, so let's aim for the chest: + if (NPC->enemy->client) { + org[2] -= 12; // NOTE: is this enough? } VectorSubtract(org, muzzle, dir); vectoangles(dir, angles); - switch( NPC->client->ps.weapon ) - { + switch (NPC->client->ps.weapon) { case WP_NONE: case WP_MELEE: case WP_TUSKEN_STAFF: case WP_SABER: - //don't do any pitch change if not holding a firing weapon + // don't do any pitch change if not holding a firing weapon break; default: NPCInfo->desiredPitch = NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); @@ -555,23 +481,18 @@ void NPC_BSPointShoot (qboolean shoot) NPCInfo->desiredYaw = NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); - if ( NPC_UpdateAngles ( qtrue, qtrue ) ) - {//FIXME: if angles clamped, this may never work! - //NPCInfo->shotTime = NPC->attackDebounceTime = 0; + if (NPC_UpdateAngles(qtrue, qtrue)) { // FIXME: if angles clamped, this may never work! + // NPCInfo->shotTime = NPC->attackDebounceTime = 0; - if ( shoot ) - {//FIXME: needs to hold this down if using a weapon that requires it, like phaser... + if (shoot) { // FIXME: needs to hold this down if using a weapon that requires it, like phaser... ucmd.buttons |= BUTTON_ATTACK; } - if ( !shoot || !(NPC->svFlags & SVF_LOCKEDENEMY) ) - {//If locked_enemy is on, dont complete until it is destroyed... - Q3_TaskIDComplete( NPC, TID_BSTATE ); + if (!shoot || !(NPC->svFlags & SVF_LOCKEDENEMY)) { // If locked_enemy is on, dont complete until it is destroyed... + Q3_TaskIDComplete(NPC, TID_BSTATE); goto finished; } - } - else if ( shoot && (NPC->svFlags & SVF_LOCKEDENEMY) ) - {//shooting them till their dead, not aiming right at them yet... + } else if (shoot && (NPC->svFlags & SVF_LOCKEDENEMY)) { // shooting them till their dead, not aiming right at them yet... /* qboolean movingTarget = qfalse; @@ -590,25 +511,22 @@ void NPC_BSPointShoot (qboolean shoot) if (movingTarget ) */ { - float dist = VectorLength( dir ); - float yawMiss, yawMissAllow = NPC->enemy->maxs[0]; - float pitchMiss, pitchMissAllow = (NPC->enemy->maxs[2] - NPC->enemy->mins[2])/2; + float dist = VectorLength(dir); + float yawMiss, yawMissAllow = NPC->enemy->maxs[0]; + float pitchMiss, pitchMissAllow = (NPC->enemy->maxs[2] - NPC->enemy->mins[2]) / 2; - if ( yawMissAllow < 8.0f ) - { + if (yawMissAllow < 8.0f) { yawMissAllow = 8.0f; } - if ( pitchMissAllow < 8.0f ) - { + if (pitchMissAllow < 8.0f) { pitchMissAllow = 8.0f; } - yawMiss = tan(DEG2RAD(AngleDelta ( NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw ))) * dist; - pitchMiss = tan(DEG2RAD(AngleDelta ( NPC->client->ps.viewangles[PITCH], NPCInfo->desiredPitch))) * dist; + yawMiss = tan(DEG2RAD(AngleDelta(NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw))) * dist; + pitchMiss = tan(DEG2RAD(AngleDelta(NPC->client->ps.viewangles[PITCH], NPCInfo->desiredPitch))) * dist; - if ( yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss ) - { + if (yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss) { ucmd.buttons |= BUTTON_ATTACK; } } @@ -620,31 +538,26 @@ void NPC_BSPointShoot (qboolean shoot) NPCInfo->desiredYaw = client->ps.viewangles[YAW]; NPCInfo->desiredPitch = client->ps.viewangles[PITCH]; - NPCInfo->aimTime = 0;//ok to turn normally now + NPCInfo->aimTime = 0; // ok to turn normally now } /* void NPC_BSMove(void) Move in a direction, face another */ -void NPC_BSMove(void) -{ - gentity_t *goal = NULL; +void NPC_BSMove(void) { + gentity_t *goal = NULL; NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - { + if (NPC->enemy) { NPC_CheckCanAttack(1.0, qfalse); - } - else - { + } else { NPC_UpdateAngles(qtrue, qtrue); } goal = UpdateGoal(); - if(goal) - { -// NPCInfo->moveToGoalMod = 1.0; + if (goal) { + // NPCInfo->moveToGoalMod = 1.0; NPC_SlideMoveToGoal(); } @@ -655,14 +568,12 @@ void NPC_BSShoot(void) Move in a direction, face another */ -void NPC_BSShoot(void) -{ -// NPC_BSMove(); +void NPC_BSShoot(void) { + // NPC_BSMove(); enemyVisibility = VIS_SHOOT; - if ( client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING ) - { + if (client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING) { client->ps.weaponstate = WEAPON_READY; } @@ -675,23 +586,20 @@ void NPC_BSPatrol( void ) Same as idle, but you look for enemies every "vigilance" using your angles, HFOV, VFOV and visrange, and listen for sounds within earshot... */ -void NPC_BSPatrol( void ) -{ - //int alertEventNum; +void NPC_BSPatrol(void) { + // int alertEventNum; - if(level.time > NPCInfo->enemyCheckDebounceTime) - { + if (level.time > NPCInfo->enemyCheckDebounceTime) { NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - {//FIXME: do anger script + if (NPC->enemy) { // FIXME: do anger script NPCInfo->behaviorState = BS_HUNT_AND_KILL; - //NPC_AngerSound(); + // NPC_AngerSound(); return; } } - //FIXME: Implement generic sound alerts + // FIXME: Implement generic sound alerts /* alertEventNum = NPC_CheckAlertEvents( qtrue, qtrue ); if( alertEventNum != -1 ) @@ -704,14 +612,13 @@ void NPC_BSPatrol( void ) */ NPCInfo->investigateSoundDebounceTime = 0; - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); ucmd.buttons |= BUTTON_WALKING; } @@ -720,255 +627,216 @@ void NPC_BSPatrol( void ) void NPC_BSDefault(void) uses various scriptflags to determine how an npc should behave */ -extern void NPC_CheckGetNewWeapon( void ); -extern void NPC_BSST_Attack( void ); - -void NPC_BSDefault( void ) -{ -// vec3_t enemyDir; -// float enemyDist; -// float shootDist; -// qboolean enemyFOV = qfalse; -// qboolean enemyShotFOV = qfalse; -// qboolean enemyPVS = qfalse; -// vec3_t enemyHead; -// vec3_t muzzle; -// qboolean enemyLOS = qfalse; -// qboolean enemyCS = qfalse; - qboolean move = qtrue; -// qboolean shoot = qfalse; - - - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); - } - - if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - if( NPC->client->ps.torsoAnim != TORSO_SURRENDER_START ) - { - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD ); - } - } - //look for a new enemy if don't have one and are allowed to look, validate current enemy if have one - NPC_CheckEnemy( (qboolean)((NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) != 0), qfalse ); - if ( !NPC->enemy ) - {//still don't have an enemy - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//check for alert events - //FIXME: Check Alert events, see if we should investigate or just look at it - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); - - //There is an event to look at - if ( alertEvent >= 0 )//&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - {//heard/saw something - if ( level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - {//was a big event - if ( level.alertEvents[alertEvent].owner - && level.alertEvents[alertEvent].owner != NPC - && level.alertEvents[alertEvent].owner->client - && level.alertEvents[alertEvent].owner->health >= 0 - && level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); +extern void NPC_CheckGetNewWeapon(void); +extern void NPC_BSST_Attack(void); + +void NPC_BSDefault(void) { + // vec3_t enemyDir; + // float enemyDist; + // float shootDist; + // qboolean enemyFOV = qfalse; + // qboolean enemyShotFOV = qfalse; + // qboolean enemyPVS = qfalse; + // vec3_t enemyHead; + // vec3_t muzzle; + // qboolean enemyLOS = qfalse; + // qboolean enemyCS = qfalse; + qboolean move = qtrue; + // qboolean shoot = qfalse; + + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); + } + + if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + if (NPC->client->ps.torsoAnim != TORSO_SURRENDER_START) { + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD); + } + } + // look for a new enemy if don't have one and are allowed to look, validate current enemy if have one + NPC_CheckEnemy((qboolean)((NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) != 0), qfalse); + if (!NPC->enemy) { // still don't have an enemy + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // check for alert events + // FIXME: Check Alert events, see if we should investigate or just look at it + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); + + // There is an event to look at + if (alertEvent >= 0) //&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + { // heard/saw something + if (level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { // was a big event + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner != NPC && level.alertEvents[alertEvent].owner->client && + level.alertEvents[alertEvent].owner->health >= 0 && + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); } - } - else - {//FIXME: investigate lesser events + } else { // FIXME: investigate lesser events } } - //FIXME: also check our allies' condition? + // FIXME: also check our allies' condition? } } - if ( NPC->enemy && !(NPCInfo->scriptFlags&SCF_FORCED_MARCH) ) - { + if (NPC->enemy && !(NPCInfo->scriptFlags & SCF_FORCED_MARCH)) { // just use the stormtrooper attack AI... NPC_CheckGetNewWeapon(); - if ( NPC->client->leader - && NPCInfo->goalEntity == NPC->client->leader - && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - { + if (NPC->client->leader && NPCInfo->goalEntity == NPC->client->leader && !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { NPC_ClearGoal(); } NPC_BSST_Attack(); return; -/* - //have an enemy - //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); - enemyDist = VectorNormalize( enemyDir ); - enemyDist *= enemyDist; - shootDist = NPC_MaxDistSquaredForWeapon(); - - enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); - enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); - enemyPVS = gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ); - - if ( enemyPVS ) - {//in the pvs - trace_t tr; - - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); - enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); - - gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); - enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); - } - else - {//skip thr 2 traces since they would have to fail - enemyLOS = qfalse; - enemyCS = qfalse; - } + /* + //have an enemy + //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? + VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); + enemyDist = VectorNormalize( enemyDir ); + enemyDist *= enemyDist; + shootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyCS && enemyShotFOV ) - {//can hit enemy if we want - NPC->cantHitEnemyCounter = 0; - } - else - {//can't hit - NPC->cantHitEnemyCounter++; - } + enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); + enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); + enemyPVS = gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ); - if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) - {//can shoot - shoot = qtrue; - if ( NPCInfo->goalEntity == NPC->enemy ) - {//my goal is my enemy and I have a clear shot, no need to chase right now - move = qfalse; - } - } - else - {//don't shoot yet, keep chasing - shoot = qfalse; - move = qtrue; - } + if ( enemyPVS ) + {//in the pvs + trace_t tr; - //shoot decision - if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//try to shoot - if ( NPC->enemy ) - { - if ( shoot ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); + enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); + CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); + + gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); + enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); + } + else + {//skip thr 2 traces since they would have to fail + enemyLOS = qfalse; + enemyCS = qfalse; + } + + if ( enemyCS && enemyShotFOV ) + {//can hit enemy if we want + NPC->cantHitEnemyCounter = 0; + } + else + {//can't hit + NPC->cantHitEnemyCounter++; + } + + if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) + {//can shoot + shoot = qtrue; + if ( NPCInfo->goalEntity == NPC->enemy ) + {//my goal is my enemy and I have a clear shot, no need to chase right now + move = qfalse; + } + } + else + {//don't shoot yet, keep chasing + shoot = qfalse; + move = qtrue; + } + + //shoot decision + if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) + {//try to shoot + if ( NPC->enemy ) { - WeaponThink( qtrue ); + if ( shoot ) + { + if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + { + WeaponThink( qtrue ); + } + } } } - } - } - //chase decision - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//go after him - NPCInfo->goalEntity = NPC->enemy; - //FIXME: don't need to chase when have a clear shot and in range? - if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) - {//haven't been able to shoot enemy for about 6 seconds, need to do something - //FIXME: combat points? Just chase? - if ( enemyPVS ) - {//in my PVS, just pick a combat point - //FIXME: implement + //chase decision + if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + {//go after him + NPCInfo->goalEntity = NPC->enemy; + //FIXME: don't need to chase when have a clear shot and in range? + if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) + {//haven't been able to shoot enemy for about 6 seconds, need to do something + //FIXME: combat points? Just chase? + if ( enemyPVS ) + {//in my PVS, just pick a combat point + //FIXME: implement + } + else + {//just chase him + } + } + //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? } - else - {//just chase him + else if ( NPC->cantHitEnemyCounter > 60 ) + {//pick a new one + NPC_CheckEnemy( qtrue, qfalse ); } - } - //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? - } - else if ( NPC->cantHitEnemyCounter > 60 ) - {//pick a new one - NPC_CheckEnemy( qtrue, qfalse ); - } - if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) - {//have a clear LOS to him//, but not looking at him - //Find the desired angles - vec3_t angles; + if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) + {//have a clear LOS to him//, but not looking at him + //Find the desired angles + vec3_t angles; - GetAnglesForDirection( muzzle, enemyHead, angles ); + GetAnglesForDirection( muzzle, enemyHead, angles ); - NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); - } - */ + NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); + NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); + } + */ } - if ( UpdateGoal() ) - {//have a goal - if ( !NPC->enemy - && NPC->client->leader - && NPCInfo->goalEntity == NPC->client->leader - && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - { + if (UpdateGoal()) { // have a goal + if (!NPC->enemy && NPC->client->leader && NPCInfo->goalEntity == NPC->client->leader && !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { NPC_BSFollowLeader(); - } - else - { - //set angles - if ( (NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || NPCInfo->goalEntity != NPC->enemy ) - {//face direction of movement, NOTE: default behavior when not chasing enemy + } else { + // set angles + if ((NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || + NPCInfo->goalEntity != NPC->enemy) { // face direction of movement, NOTE: default behavior when not chasing enemy NPCInfo->combatMove = qfalse; - } - else - {//face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? - vec3_t dir, angles; + } else { // face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? + vec3_t dir, angles; NPCInfo->combatMove = qfalse; - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); + vectoangles(dir, angles); NPCInfo->desiredYaw = angles[YAW]; - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { NPCInfo->desiredPitch = angles[PITCH]; } } - //set movement - //override default walk/run behavior - //NOTE: redundant, done in NPC_ApplyScriptFlags - if ( NPCInfo->scriptFlags & SCF_RUNNING ) - { + // set movement + // override default walk/run behavior + // NOTE: redundant, done in NPC_ApplyScriptFlags + if (NPCInfo->scriptFlags & SCF_RUNNING) { ucmd.buttons &= ~BUTTON_WALKING; - } - else if ( NPCInfo->scriptFlags & SCF_WALKING ) - { + } else if (NPCInfo->scriptFlags & SCF_WALKING) { ucmd.buttons |= BUTTON_WALKING; - } - else if ( NPCInfo->goalEntity == NPC->enemy ) - { + } else if (NPCInfo->goalEntity == NPC->enemy) { ucmd.buttons &= ~BUTTON_WALKING; - } - else - { + } else { ucmd.buttons |= BUTTON_WALKING; } - if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - if ( g_crosshairEntNum != NPC->s.number ) - {//don't walk if player isn't aiming at me + if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + if (g_crosshairEntNum != NPC->s.number) { // don't walk if player isn't aiming at me move = qfalse; } } - if ( move ) - { - //move toward goal - NPC_MoveToGoal( qtrue ); + if (move) { + // move toward goal + NPC_MoveToGoal(qtrue); } } - } - else if ( !NPC->enemy && NPC->client->leader ) - { + } else if (!NPC->enemy && NPC->client->leader) { NPC_BSFollowLeader(); } - //update angles - NPC_UpdateAngles( qtrue, qtrue ); + // update angles + NPC_UpdateAngles(qtrue, qtrue); } \ No newline at end of file diff --git a/code/game/AI_Droid.cpp b/code/game/AI_Droid.cpp index 8fab6ecac9..3c0283fd0b 100644 --- a/code/game/AI_Droid.cpp +++ b/code/game/AI_Droid.cpp @@ -23,42 +23,33 @@ along with this program; if not, see . #include "b_local.h" #include "g_functions.h" -//static void R5D2_LookAround( void ); -float NPC_GetPainChance( gentity_t *self, int damage ); +// static void R5D2_LookAround( void ); +float NPC_GetPainChance(gentity_t *self, int damage); -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; /* ------------------------- R2D2_PartsMove ------------------------- */ -void R2D2_PartsMove(void) -{ +void R2D2_PartsMove(void) { // Front 'eye' lense - if ( TIMER_Done(NPC,"eyeDelay") ) - { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); + if (TIMER_Done(NPC, "eyeDelay")) { + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); - NPC->pos1[0]+=Q_irand( -20, 20 ); // Roll - NPC->pos1[1]=Q_irand( -20, 20 ); - NPC->pos1[2]=Q_irand( -20, 20 ); + NPC->pos1[0] += Q_irand(-20, 20); // Roll + NPC->pos1[1] = Q_irand(-20, 20); + NPC->pos1[2] = Q_irand(-20, 20); - if (NPC->genericBone1) - { - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0); + if (NPC->genericBone1) { + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - TIMER_Set( NPC, "eyeDelay", Q_irand( 100, 1000 ) ); + TIMER_Set(NPC, "eyeDelay", Q_irand(100, 1000)); } } @@ -67,11 +58,10 @@ void R2D2_PartsMove(void) NPC_BSDroid_Idle ------------------------- */ -void Droid_Idle( void ) -{ -// VectorCopy( NPCInfo->investigateGoal, lookPos ); +void Droid_Idle(void) { + // VectorCopy( NPCInfo->investigateGoal, lookPos ); -// NPC_FacePosition( lookPos ); + // NPC_FacePosition( lookPos ); } /* @@ -79,36 +69,26 @@ void Droid_Idle( void ) R2D2_TurnAnims ------------------------- */ -void R2D2_TurnAnims ( void ) -{ +void R2D2_TurnAnims(void) { float turndelta; - int anim; + int anim; turndelta = AngleDelta(NPC->currentAngles[YAW], NPCInfo->desiredYaw); - if ((fabs(turndelta) > 20) && ((NPC->client->NPC_class == CLASS_R2D2) || (NPC->client->NPC_class == CLASS_R5D2))) - { + if ((fabs(turndelta) > 20) && ((NPC->client->NPC_class == CLASS_R2D2) || (NPC->client->NPC_class == CLASS_R5D2))) { anim = NPC->client->ps.legsAnim; - if (turndelta<0) - { - if (anim != BOTH_TURN_LEFT1) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (turndelta < 0) { + if (anim != BOTH_TURN_LEFT1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - if (anim != BOTH_TURN_RIGHT1) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + if (anim != BOTH_TURN_RIGHT1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } /* @@ -116,69 +96,55 @@ void R2D2_TurnAnims ( void ) Droid_Patrol ------------------------- */ -void Droid_Patrol( void ) -{ +void Droid_Patrol(void) { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); - if ( NPC->client && NPC->client->NPC_class != CLASS_GONK ) - { - R2D2_PartsMove(); // Get his eye moving. + if (NPC->client && NPC->client->NPC_class != CLASS_GONK) { + R2D2_PartsMove(); // Get his eye moving. R2D2_TurnAnims(); } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); - if( NPC->client && NPC->client->NPC_class == CLASS_MOUSE ) - { - NPCInfo->desiredYaw += sin(level.time*.5) * 25; // Weaves side to side a little + if (NPC->client && NPC->client->NPC_class == CLASS_MOUSE) { + NPCInfo->desiredYaw += sin(level.time * .5) * 25; // Weaves side to side a little - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)) ); + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPC->client && NPC->client->NPC_class == CLASS_R2D2 ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)) ); + } else if (NPC->client && NPC->client->NPC_class == CLASS_R2D2) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPC->client && NPC->client->NPC_class == CLASS_R5D2 ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)) ); + } else if (NPC->client && NPC->client->NPC_class == CLASS_R5D2) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } - if( NPC->client && NPC->client->NPC_class == CLASS_GONK ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)) ); + if (NPC->client && NPC->client->NPC_class == CLASS_GONK) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } -// else -// { -// R5D2_LookAround(); -// } + // else + // { + // R5D2_LookAround(); + // } } - NPC_UpdateAngles( qtrue, qtrue ); - + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -186,31 +152,25 @@ void Droid_Patrol( void ) Droid_Run ------------------------- */ -void Droid_Run( void ) -{ +void Droid_Run(void) { R2D2_PartsMove(); - if ( NPCInfo->localState == LSTATE_BACKINGUP ) - { + if (NPCInfo->localState == LSTATE_BACKINGUP) { ucmd.forwardmove = -127; NPCInfo->desiredYaw += 5; - NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. - } - else - { + NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. + } else { ucmd.forwardmove = 64; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { - if (NPC_MoveToGoal( qfalse )) - { - NPCInfo->desiredYaw += sin(level.time*.5) * 5; // Weaves side to side a little + // If we have somewhere to go, then do that + if (UpdateGoal()) { + if (NPC_MoveToGoal(qfalse)) { + NPCInfo->desiredYaw += sin(level.time * .5) * 5; // Weaves side to side a little } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -218,64 +178,47 @@ void Droid_Run( void ) void Droid_Spin( void ) ------------------------- */ -void Droid_Spin( void ) -{ - vec3_t dir = {0,0,1}; +void Droid_Spin(void) { + vec3_t dir = {0, 0, 1}; R2D2_TurnAnims(); - // Head is gone, spin and spark - if ( NPC->client->NPC_class == CLASS_R5D2 ) - { + if (NPC->client->NPC_class == CLASS_R5D2) { // No head? - if (gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head" )) - { - if (TIMER_Done(NPC,"smoke") && !TIMER_Done(NPC,"droidsmoketotal")) - { - TIMER_Set( NPC, "smoke", 100); - G_PlayEffect( "volumetric/droid_smoke" , NPC->currentOrigin,dir); + if (gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head")) { + if (TIMER_Done(NPC, "smoke") && !TIMER_Done(NPC, "droidsmoketotal")) { + TIMER_Set(NPC, "smoke", 100); + G_PlayEffect("volumetric/droid_smoke", NPC->currentOrigin, dir); } - if (TIMER_Done(NPC,"droidspark")) - { - TIMER_Set( NPC, "droidspark", Q_irand(100,500)); - G_PlayEffect( "sparks/spark", NPC->currentOrigin,dir); + if (TIMER_Done(NPC, "droidspark")) { + TIMER_Set(NPC, "droidspark", Q_irand(100, 500)); + G_PlayEffect("sparks/spark", NPC->currentOrigin, dir); } - ucmd.forwardmove = Q_irand( -64, 64); + ucmd.forwardmove = Q_irand(-64, 64); - if (TIMER_Done(NPC,"roam")) - { - TIMER_Set( NPC, "roam", Q_irand( 250, 1000 ) ); - NPCInfo->desiredYaw = Q_irand( 0, 360 ); // Go in random directions + if (TIMER_Done(NPC, "roam")) { + TIMER_Set(NPC, "roam", Q_irand(250, 1000)); + NPCInfo->desiredYaw = Q_irand(0, 360); // Go in random directions } - } - else - { - if (TIMER_Done(NPC,"roam")) - { + } else { + if (TIMER_Done(NPC, "roam")) { NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 40); // Spin around } } - } - else - { - if (TIMER_Done(NPC,"roam")) - { + } else { + if (TIMER_Done(NPC, "roam")) { NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 40); // Spin around } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -283,131 +226,111 @@ void Droid_Spin( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Droid_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - int anim; - float pain_chance; +void NPC_Droid_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + int anim; + float pain_chance; - if ( self->NPC && self->NPC->ignorePain ) - { + if (self->NPC && self->NPC->ignorePain) { return; } - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->client->NPC_class == CLASS_R5D2 ) - { - pain_chance = NPC_GetPainChance( self, damage ); + if (self->client->NPC_class == CLASS_R5D2) { + pain_chance = NPC_GetPainChance(self, damage); // Put it in pain - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { // Health is between 0-30 or was hit by a DEMP2 so pop his head - if ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { - if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE + if (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { + if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE { - if ((self->NPC->localState != LSTATE_SPINNING) && - (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head" ))) - { - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head", TURN_OFF ); + if ((self->NPC->localState != LSTATE_SPINNING) && (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head"))) { + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head", TURN_OFF); -// G_PlayEffect( "small_chunks" , self->currentOrigin ); - G_PlayEffect( "chunks/r5d2head", self->currentOrigin ); + // G_PlayEffect( "small_chunks" , self->currentOrigin ); + G_PlayEffect("chunks/r5d2head", self->currentOrigin); - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; - TIMER_Set( self, "droidsmoketotal", 5000); - TIMER_Set( self, "droidspark", 100); + TIMER_Set(self, "droidsmoketotal", 5000); + TIMER_Set(self, "droidspark", 100); self->NPC->localState = LSTATE_SPINNING; } } } // Just give him normal pain for a little while - else - { + else { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); + TIMER_Set(self, "roam", Q_irand(1000, 2000)); } } - } - else if (self->client->NPC_class == CLASS_MOUSE) - { - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + } else if (self->client->NPC_class == CLASS_MOUSE) { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->localState = LSTATE_SPINNING; - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; - } - else - { + } else { self->NPC->localState = LSTATE_BACKINGUP; } self->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; - } - else if (self->client->NPC_class == CLASS_R2D2) - { + } else if (self->client->NPC_class == CLASS_R2D2) { - pain_chance = NPC_GetPainChance( self, damage ); + pain_chance = NPC_GetPainChance(self, damage); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); + TIMER_Set(self, "roam", Q_irand(1000, 2000)); } - } - else if ( self->client->NPC_class == CLASS_INTERROGATOR && ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) && other ) - { + } else if (self->client->NPC_class == CLASS_INTERROGATOR && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - VectorSubtract( self->currentOrigin, other->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->currentOrigin, other->currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - NPC_Pain( self, inflictor, other, point, damage, mod); + NPC_Pain(self, inflictor, other, point, damage, mod); } - /* ------------------------- Droid_Pain ------------------------- */ -void Droid_Pain(void) -{ - if (TIMER_Done(NPC,"droidpain")) //He's done jumping around +void Droid_Pain(void) { + if (TIMER_Done(NPC, "droidpain")) // He's done jumping around { NPCInfo->localState = LSTATE_NONE; } @@ -418,18 +341,16 @@ void Droid_Pain(void) NPC_Mouse_Precache ------------------------- */ -void NPC_Mouse_Precache( void ) -{ - int i; +void NPC_Mouse_Precache(void) { + int i; - for (i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/mouse/misc/mousego%d.wav", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", i)); } - G_EffectIndex( "env/small_explode" ); - G_SoundIndex( "sound/chars/mouse/misc/death1" ); - G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + G_EffectIndex("env/small_explode"); + G_SoundIndex("sound/chars/mouse/misc/death1"); + G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); } /* @@ -437,17 +358,15 @@ void NPC_Mouse_Precache( void ) NPC_R5D2_Precache ------------------------- */ -void NPC_R5D2_Precache(void) -{ - for ( int i = 1; i < 5; i++) - { - G_SoundIndex( va( "sound/chars/r5d2/misc/r5talk%d.wav", i ) ); +void NPC_R5D2_Precache(void) { + for (int i = 1; i < 5; i++) { + G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", i)); } - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); - G_EffectIndex( "env/med_explode"); - G_EffectIndex( "volumetric/droid_smoke" ); - G_EffectIndex( "chunks/r5d2head"); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); + G_EffectIndex("env/med_explode"); + G_EffectIndex("volumetric/droid_smoke"); + G_EffectIndex("chunks/r5d2head"); } /* @@ -455,15 +374,13 @@ void NPC_R5D2_Precache(void) NPC_R2D2_Precache ------------------------- */ -void NPC_R2D2_Precache(void) -{ - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/r2d2/misc/r2d2talk0%d.wav", i ) ); +void NPC_R2D2_Precache(void) { + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", i)); } - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); - G_EffectIndex( "env/med_explode"); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); + G_EffectIndex("env/med_explode"); } /* @@ -471,8 +388,7 @@ void NPC_R2D2_Precache(void) NPC_Gonk_Precache ------------------------- */ -void NPC_Gonk_Precache( void ) -{ +void NPC_Gonk_Precache(void) { G_SoundIndex("sound/chars/gonk/misc/gonktalk1.wav"); G_SoundIndex("sound/chars/gonk/misc/gonktalk2.wav"); @@ -480,7 +396,7 @@ void NPC_Gonk_Precache( void ) G_SoundIndex("sound/chars/gonk/misc/death2.wav"); G_SoundIndex("sound/chars/gonk/misc/death3.wav"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("env/med_explode"); } /* @@ -488,10 +404,9 @@ void NPC_Gonk_Precache( void ) NPC_Protocol_Precache ------------------------- */ -void NPC_Protocol_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); - G_EffectIndex( "env/med_explode"); +void NPC_Protocol_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); + G_EffectIndex("env/med_explode"); } /* @@ -548,28 +463,18 @@ static void R5D2_LookAround( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSDroid_Default( void ) -{ +void NPC_BSDroid_Default(void) { - if ( NPCInfo->localState == LSTATE_SPINNING ) - { + if (NPCInfo->localState == LSTATE_SPINNING) { Droid_Spin(); - } - else if ( NPCInfo->localState == LSTATE_PAIN ) - { + } else if (NPCInfo->localState == LSTATE_PAIN) { Droid_Pain(); - } - else if ( NPCInfo->localState == LSTATE_DROP ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else if (NPCInfo->localState == LSTATE_DROP) { + NPC_UpdateAngles(qtrue, qtrue); ucmd.upmove = Q_flrand(-1.0f, 1.0f) * 64; - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Droid_Patrol(); - } - else - { + } else { Droid_Run(); } } diff --git a/code/game/AI_GalakMech.cpp b/code/game/AI_GalakMech.cpp index a8b4d1bf8c..fe36341448 100644 --- a/code/game/AI_GalakMech.cpp +++ b/code/game/AI_GalakMech.cpp @@ -28,7 +28,6 @@ along with this program; if not, see . // //////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////////////// @@ -38,47 +37,39 @@ along with this program; if not, see . #include "g_vehicles.h" #include "g_functions.h" #if !defined(RATL_VECTOR_VS_INC) - #include "../Ratl/vector_vs.h" +#include "../Ratl/vector_vs.h" #endif - //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define MAX_VEHICLES_REGISTERED 100 - -#define ATTACK_FWD 0.95f -#define ATTACK_SIDE 0.20f -#define AIM_SIDE 0.60f -#define FUTURE_PRED_DIST 20.0f -#define FUTURE_SIDE_DIST 60.0f -#define ATTACK_FLANK_SLOWING 1000.0f -#define RAM_DIST 150.0f -#define MIN_STAY_VIEWABLE_TIME 20000 - +#define MAX_VEHICLES_REGISTERED 100 +#define ATTACK_FWD 0.95f +#define ATTACK_SIDE 0.20f +#define AIM_SIDE 0.60f +#define FUTURE_PRED_DIST 20.0f +#define FUTURE_SIDE_DIST 60.0f +#define ATTACK_FLANK_SLOWING 1000.0f +#define RAM_DIST 150.0f +#define MIN_STAY_VIEWABLE_TIME 20000 //////////////////////////////////////////////////////////////////////////////////////// // Externs //////////////////////////////////////////////////////////////////////////////////////// -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern void G_SoundAtSpot( vec3_t org, int soundIndex, qboolean broadcast ); -extern void CG_DrawEdge( vec3_t start, vec3_t end, int type ); - - - -trace_t mPilotViewTrace; -int mPilotViewTraceCount; -int mActivePilotCount; -ratl::vector_vs mRegistered; - +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern void G_SoundAtSpot(vec3_t org, int soundIndex, qboolean broadcast); +extern void CG_DrawEdge(vec3_t start, vec3_t end, int type); +trace_t mPilotViewTrace; +int mPilotViewTraceCount; +int mActivePilotCount; +ratl::vector_vs mRegistered; //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Pilot_Reset(void) -{ +void Pilot_Reset(void) { mPilotViewTraceCount = 0; mActivePilotCount = 0; mRegistered.clear(); @@ -87,60 +78,37 @@ void Pilot_Reset(void) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -int Pilot_ActivePilotCount() -{ - return mActivePilotCount; -} +int Pilot_ActivePilotCount() { return mActivePilotCount; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Pilot_Update(void) -{ +void Pilot_Update(void) { mActivePilotCount = 0; mRegistered.clear(); - for (int i=0; igreetEnt && - g_entities[i].NPC->greetEnt->owner==(&g_entities[i]) - ) - { + for (int i = 0; i < ENTITYNUM_WORLD; i++) { + if (g_entities[i].inuse && g_entities[i].client && g_entities[i].NPC && g_entities[i].NPC->greetEnt && + g_entities[i].NPC->greetEnt->owner == (&g_entities[i])) { mActivePilotCount++; } - if ( g_entities[i].inuse && - g_entities[i].client && - g_entities[i].m_pVehicle && - !g_entities[i].owner && - g_entities[i].health>0 && - g_entities[i].m_pVehicle->m_pVehicleInfo->type==VH_SPEEDER && - !mRegistered.full()) - { + if (g_entities[i].inuse && g_entities[i].client && g_entities[i].m_pVehicle && !g_entities[i].owner && g_entities[i].health > 0 && + g_entities[i].m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && !mRegistered.full()) { mRegistered.push_back(&g_entities[i]); } - } + if (player && player->inuse && TIMER_Done(player, "FlybySoundArchitectureDebounce")) { + TIMER_Set(player, "FlybySoundArchitectureDebounce", 300); - if (player && - player->inuse && - TIMER_Done(player, "FlybySoundArchitectureDebounce")) - { - TIMER_Set(player, "FlybySoundArchitectureDebounce", 300); - - Vehicle_t* pVeh = G_IsRidingVehicle(player); + Vehicle_t *pVeh = G_IsRidingVehicle(player); - if (pVeh && - (pVeh->m_pVehicleInfo->soundFlyBy || pVeh->m_pVehicleInfo->soundFlyBy2) && - //fabsf(pVeh->m_pParentEntity->currentAngles[2])<15.0f && - VectorLength(pVeh->m_pParentEntity->client->ps.velocity)>500.0f) - { - vec3_t projectedPosition; - vec3_t projectedDirection; - vec3_t projectedRight; - vec3_t anglesNoRoll; + if (pVeh && (pVeh->m_pVehicleInfo->soundFlyBy || pVeh->m_pVehicleInfo->soundFlyBy2) && + // fabsf(pVeh->m_pParentEntity->currentAngles[2])<15.0f && + VectorLength(pVeh->m_pParentEntity->client->ps.velocity) > 500.0f) { + vec3_t projectedPosition; + vec3_t projectedDirection; + vec3_t projectedRight; + vec3_t anglesNoRoll; VectorCopy(pVeh->m_pParentEntity->currentAngles, anglesNoRoll); anglesNoRoll[2] = 0; @@ -149,34 +117,20 @@ void Pilot_Update(void) VectorMA(player->currentOrigin, 1.2f, pVeh->m_pParentEntity->client->ps.velocity, projectedPosition); VectorMA(projectedPosition, Q_flrand(-200.0f, 200.0f), projectedRight, projectedPosition); - gi.trace(&mPilotViewTrace, - player->currentOrigin, - 0, - 0, - projectedPosition, - player->s.number, - MASK_SHOT, (EG2_Collision)0, 0); - - if ((mPilotViewTrace.allsolid==qfalse) && - (mPilotViewTrace.startsolid==qfalse) && - (mPilotViewTrace.fraction<0.99f) && - (mPilotViewTrace.plane.normal[2]<0.5f) && - (DotProduct(projectedDirection, mPilotViewTrace.plane.normal)<-0.5f) - ) - { - // CG_DrawEdge(player->currentOrigin, mPilotViewTrace.endpos, EDGE_IMPACT_POSSIBLE); - TIMER_Set(player, "FlybySoundArchitectureDebounce", Q_irand(1000, 2000)); + gi.trace(&mPilotViewTrace, player->currentOrigin, 0, 0, projectedPosition, player->s.number, MASK_SHOT, (EG2_Collision)0, 0); + + if ((mPilotViewTrace.allsolid == qfalse) && (mPilotViewTrace.startsolid == qfalse) && (mPilotViewTrace.fraction < 0.99f) && + (mPilotViewTrace.plane.normal[2] < 0.5f) && (DotProduct(projectedDirection, mPilotViewTrace.plane.normal) < -0.5f)) { + // CG_DrawEdge(player->currentOrigin, mPilotViewTrace.endpos, EDGE_IMPACT_POSSIBLE); + TIMER_Set(player, "FlybySoundArchitectureDebounce", Q_irand(1000, 2000)); int soundFlyBy = pVeh->m_pVehicleInfo->soundFlyBy; - if (pVeh->m_pVehicleInfo->soundFlyBy2 && (!soundFlyBy || !Q_irand(0,1))) - { + if (pVeh->m_pVehicleInfo->soundFlyBy2 && (!soundFlyBy || !Q_irand(0, 1))) { soundFlyBy = pVeh->m_pVehicleInfo->soundFlyBy2; } G_SoundAtSpot(mPilotViewTrace.endpos, soundFlyBy, qtrue); - } - else - { - // CG_DrawEdge(player->currentOrigin, mPilotViewTrace.endpos, EDGE_IMPACT_SAFE); + } else { + // CG_DrawEdge(player->currentOrigin, mPilotViewTrace.endpos, EDGE_IMPACT_SAFE); } } } @@ -185,14 +139,7 @@ void Pilot_Update(void) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Pilot_AnyVehiclesRegistered() -{ - return (!mRegistered.empty()); -} - - - - +bool Pilot_AnyVehiclesRegistered() { return (!mRegistered.empty()); } //////////////////////////////////////////////////////////////////////////////////////// // Vehicle Registration @@ -200,17 +147,12 @@ bool Pilot_AnyVehiclesRegistered() // Any vehicles that can be ridden by NPCs should be registered here // //////////////////////////////////////////////////////////////////////////////////////// -void Vehicle_Register(gentity_t *ent) -{ -} - +void Vehicle_Register(gentity_t *ent) {} //////////////////////////////////////////////////////////////////////////////////////// // Vehicle Remove From The List Of Valid //////////////////////////////////////////////////////////////////////////////////////// -void Vehicle_Remove(gentity_t *ent) -{ -} +void Vehicle_Remove(gentity_t *ent) {} //////////////////////////////////////////////////////////////////////////////////////// // Vehicle_Find @@ -219,22 +161,16 @@ void Vehicle_Remove(gentity_t *ent) // entity can get to. // //////////////////////////////////////////////////////////////////////////////////////// -gentity_t* Vehicle_Find(gentity_t *ent) -{ - gentity_t* closest = 0; - float closestDist = 0; - float curDist = 0; - +gentity_t *Vehicle_Find(gentity_t *ent) { + gentity_t *closest = 0; + float closestDist = 0; + float curDist = 0; - for (int i=0; iowner) - { + for (int i = 0; i < mRegistered.size(); i++) { + if (!mRegistered[i]->owner) { curDist = Distance(mRegistered[i]->currentOrigin, ent->currentOrigin); - if (curDist<1000 && (!closest || curDistenemy) - { +bool Pilot_MasterUpdate() { + if (!NPC->enemy) { // If Still On A Vehicle, Jump Off //--------------------------------- - if (NPCInfo->greetEnt) - { + if (NPCInfo->greetEnt) { ucmd.upmove = 127; - if (NPCInfo->greetEnt && NPCInfo->greetEnt->m_pVehicle && level.timeconfusionTime) - { - Vehicle_t* pVeh = NPCInfo->greetEnt->m_pVehicle; - if (!(pVeh->m_ulFlags&VEH_OUTOFCONTROL)) - { - gentity_t* parent = pVeh->m_pParentEntity; - float CurSpeed = VectorLength(parent->client->ps.velocity); + if (NPCInfo->greetEnt && NPCInfo->greetEnt->m_pVehicle && level.time < NPCInfo->confusionTime) { + Vehicle_t *pVeh = NPCInfo->greetEnt->m_pVehicle; + if (!(pVeh->m_ulFlags & VEH_OUTOFCONTROL)) { + gentity_t *parent = pVeh->m_pParentEntity; + float CurSpeed = VectorLength(parent->client->ps.velocity); pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 10000); pVeh->m_ulFlags |= (VEH_OUTOFCONTROL); VectorScale(parent->client->ps.velocity, 1.25f, parent->pos3); - if (CurSpeedm_pVehicleInfo->speedMax) - { + if (CurSpeed < pVeh->m_pVehicleInfo->speedMax) { VectorNormalize(parent->pos3); - if (fabsf(parent->pos3[2])<0.25f) - { + if (fabsf(parent->pos3[2]) < 0.25f) { VectorScale(parent->pos3, (pVeh->m_pVehicleInfo->speedMax * 1.25f), parent->pos3); - } - else - { + } else { VectorScale(parent->client->ps.velocity, 1.25f, parent->pos3); } } } } - if (NPCInfo->greetEnt->owner==NPC) - { + if (NPCInfo->greetEnt->owner == NPC) { return true; } NPCInfo->greetEnt = 0; @@ -309,21 +228,13 @@ bool Pilot_MasterUpdate() return false; } - // If We Already Have A Target Vehicle, Make Sure It Is Still Valid //------------------------------------------------------------------ - if (NPCInfo->greetEnt) - { - if (!NPCInfo->greetEnt->inuse || - !NPCInfo->greetEnt->m_pVehicle || - !NPCInfo->greetEnt->m_pVehicle->m_pVehicleInfo) - { + if (NPCInfo->greetEnt) { + if (!NPCInfo->greetEnt->inuse || !NPCInfo->greetEnt->m_pVehicle || !NPCInfo->greetEnt->m_pVehicle->m_pVehicleInfo) { NPCInfo->greetEnt = Vehicle_Find(NPC); - } - else - { - if (NPCInfo->greetEnt->owner && NPCInfo->greetEnt->owner!=NPC) - { + } else { + if (NPCInfo->greetEnt->owner && NPCInfo->greetEnt->owner != NPC) { NPCInfo->greetEnt = Vehicle_Find(NPC); } } @@ -331,26 +242,19 @@ bool Pilot_MasterUpdate() // If We Have An Enemy, Try To Find A Vehicle Nearby //--------------------------------------------------- - else - { + else { NPCInfo->greetEnt = Vehicle_Find(NPC); } // If No Vehicle Available, Continue As Usual //-------------------------------------------- - if (!NPCInfo->greetEnt) - { + if (!NPCInfo->greetEnt) { return false; } - - - if (NPCInfo->greetEnt->owner==NPC) - { + if (NPCInfo->greetEnt->owner == NPC) { Pilot_Steer_Vehicle(); - } - else - { + } else { Pilot_Goto_Vehicle(); } @@ -358,81 +262,51 @@ bool Pilot_MasterUpdate() return true; } - - - - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Pilot_Update_Enemy() -{ - if (!TIMER_Exists(NPC, "PilotRemoveTime")) - { +void Pilot_Update_Enemy() { + if (!TIMER_Exists(NPC, "PilotRemoveTime")) { TIMER_Set(NPC, "PilotRemoveTime", MIN_STAY_VIEWABLE_TIME); } - if (TIMER_Done(NPC, "NextPilotCheckEnemyTime")) - { - TIMER_Set(NPC, "NextPilotCheckEnemyTime", Q_irand(1000,2000)); - if (NPC->enemy && Distance(NPC->currentOrigin, NPC->enemy->currentOrigin)>1000.0f) - { - mPilotViewTraceCount ++; - gi.trace(&mPilotViewTrace, - NPC->currentOrigin, - 0, - 0, - NPC->enemy->currentOrigin, - NPC->s.number, - MASK_SHOT, - (EG2_Collision)0, 0); - - if ((mPilotViewTrace.allsolid==qfalse) && - (mPilotViewTrace.startsolid==qfalse ) && - ((mPilotViewTrace.entityNum==NPC->enemy->s.number)||(mPilotViewTrace.entityNum==NPC->enemy->s.m_iVehicleNum))) - { + if (TIMER_Done(NPC, "NextPilotCheckEnemyTime")) { + TIMER_Set(NPC, "NextPilotCheckEnemyTime", Q_irand(1000, 2000)); + if (NPC->enemy && Distance(NPC->currentOrigin, NPC->enemy->currentOrigin) > 1000.0f) { + mPilotViewTraceCount++; + gi.trace(&mPilotViewTrace, NPC->currentOrigin, 0, 0, NPC->enemy->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + + if ((mPilotViewTrace.allsolid == qfalse) && (mPilotViewTrace.startsolid == qfalse) && + ((mPilotViewTrace.entityNum == NPC->enemy->s.number) || (mPilotViewTrace.entityNum == NPC->enemy->s.m_iVehicleNum))) { TIMER_Set(NPC, "PilotRemoveTime", MIN_STAY_VIEWABLE_TIME); } - } - else - { + } else { TIMER_Set(NPC, "PilotRemoveTime", MIN_STAY_VIEWABLE_TIME); } } - if (TIMER_Done(NPC, "PilotRemoveTime")) - { - if (NPCInfo->greetEnt->owner==NPC) - { - NPCInfo->greetEnt->e_ThinkFunc = thinkF_G_FreeEntity; - NPCInfo->greetEnt->nextthink = level.time; + if (TIMER_Done(NPC, "PilotRemoveTime")) { + if (NPCInfo->greetEnt->owner == NPC) { + NPCInfo->greetEnt->e_ThinkFunc = thinkF_G_FreeEntity; + NPCInfo->greetEnt->nextthink = level.time; } - NPC->e_ThinkFunc = thinkF_G_FreeEntity; - NPC->nextthink = level.time; + NPC->e_ThinkFunc = thinkF_G_FreeEntity; + NPC->nextthink = level.time; } } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Pilot_Goto_Vehicle() -{ +void Pilot_Goto_Vehicle() { STEER::Activate(NPC); { - if (STEER::Reached(NPC, NPCInfo->greetEnt, 80.0f)) - { + if (STEER::Reached(NPC, NPCInfo->greetEnt, 80.0f)) { NPC_Use(NPCInfo->greetEnt, NPC, NPC); - } - else if (NAV::OnNeighboringPoints(NPC, NPCInfo->greetEnt)) - { + } else if (NAV::OnNeighboringPoints(NPC, NPCInfo->greetEnt)) { STEER::Persue(NPC, NPCInfo->greetEnt, 50.0f, 0.0f, 30.0f, 0.0f, true); - } - else - { - if (!NAV::GoTo(NPC, NPCInfo->greetEnt)) - { + } else { + if (!NAV::GoTo(NPC, NPCInfo->greetEnt)) { STEER::Stop(NPC); } } @@ -442,325 +316,253 @@ void Pilot_Goto_Vehicle() NPC_UpdateAngles(qtrue, qtrue); } -extern bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right); +extern bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right); //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Pilot_Steer_Vehicle() -{ - if (!NPC->enemy || !NPC->enemy->client) - { +void Pilot_Steer_Vehicle() { + if (!NPC->enemy || !NPC->enemy->client) { return; } - - - - - -// SETUP -//======= + // SETUP + //======= // Setup Actor Data //------------------ - CVec3 ActorPos(NPC->currentOrigin); - CVec3 ActorAngles(NPC->currentAngles); - ActorAngles[2] = 0; - Vehicle_t* ActorVeh = NPCInfo->greetEnt->m_pVehicle; - bool ActorInTurbo = (ActorVeh->m_iTurboTime>level.time); - float ActorSpeed = (ActorVeh)?(VectorLength(ActorVeh->m_pParentEntity->client->ps.velocity)):(NPC->client->ps.speed); - + CVec3 ActorPos(NPC->currentOrigin); + CVec3 ActorAngles(NPC->currentAngles); + ActorAngles[2] = 0; + Vehicle_t *ActorVeh = NPCInfo->greetEnt->m_pVehicle; + bool ActorInTurbo = (ActorVeh->m_iTurboTime > level.time); + float ActorSpeed = (ActorVeh) ? (VectorLength(ActorVeh->m_pParentEntity->client->ps.velocity)) : (NPC->client->ps.speed); // If my vehicle is spinning out of control, just hold on, we're going to die!!!!! //--------------------------------------------------------------------------------- - if (ActorVeh && (ActorVeh->m_ulFlags & VEH_OUTOFCONTROL)) - { - if (NPC->client->ps.weapon!=WP_NONE) - { + if (ActorVeh && (ActorVeh->m_ulFlags & VEH_OUTOFCONTROL)) { + if (NPC->client->ps.weapon != WP_NONE) { NPC_ChangeWeapon(WP_NONE); } - ucmd.buttons &=~BUTTON_ATTACK; - ucmd.buttons &=~BUTTON_ALT_ATTACK; + ucmd.buttons &= ~BUTTON_ATTACK; + ucmd.buttons &= ~BUTTON_ALT_ATTACK; return; } - CVec3 ActorDirection; - AngleVectors(ActorAngles.v, ActorDirection.v, 0, 0); + CVec3 ActorDirection; + AngleVectors(ActorAngles.v, ActorDirection.v, 0, 0); - CVec3 ActorFuturePos(ActorPos); - ActorFuturePos.ScaleAdd(ActorDirection, FUTURE_PRED_DIST); - - bool ActorDoTurbo = false; - bool ActorAccelerate = false; - bool ActorAimAtTarget= true; - float ActorYawOffset = 0.0f; + CVec3 ActorFuturePos(ActorPos); + ActorFuturePos.ScaleAdd(ActorDirection, FUTURE_PRED_DIST); + bool ActorDoTurbo = false; + bool ActorAccelerate = false; + bool ActorAimAtTarget = true; + float ActorYawOffset = 0.0f; // Setup Enemy Data //------------------ - CVec3 EnemyPos(NPC->enemy->currentOrigin); - CVec3 EnemyAngles(NPC->enemy->currentAngles); - EnemyAngles[2] = 0; - Vehicle_t* EnemyVeh = (NPC->enemy->s.m_iVehicleNum)?(g_entities[NPC->enemy->s.m_iVehicleNum].m_pVehicle):(0); - bool EnemyInTurbo = (EnemyVeh && EnemyVeh->m_iTurboTime>level.time); - float EnemySpeed = (EnemyVeh)?(EnemyVeh->m_pParentEntity->client->ps.speed):(NPC->enemy->resultspeed); - bool EnemySlideBreak = (EnemyVeh && (EnemyVeh->m_ulFlags&VEH_SLIDEBREAKING || EnemyVeh->m_ulFlags&VEH_STRAFERAM)); - bool EnemyDead = (NPC->enemy->health<=0); + CVec3 EnemyPos(NPC->enemy->currentOrigin); + CVec3 EnemyAngles(NPC->enemy->currentAngles); + EnemyAngles[2] = 0; + Vehicle_t *EnemyVeh = (NPC->enemy->s.m_iVehicleNum) ? (g_entities[NPC->enemy->s.m_iVehicleNum].m_pVehicle) : (0); + bool EnemyInTurbo = (EnemyVeh && EnemyVeh->m_iTurboTime > level.time); + float EnemySpeed = (EnemyVeh) ? (EnemyVeh->m_pParentEntity->client->ps.speed) : (NPC->enemy->resultspeed); + bool EnemySlideBreak = (EnemyVeh && (EnemyVeh->m_ulFlags & VEH_SLIDEBREAKING || EnemyVeh->m_ulFlags & VEH_STRAFERAM)); + bool EnemyDead = (NPC->enemy->health <= 0); - bool ActorFlank = (NPCInfo->lastAvoidSteerSideDebouncer>level.time && EnemyVeh && EnemySpeed>10.0f); + bool ActorFlank = (NPCInfo->lastAvoidSteerSideDebouncer > level.time && EnemyVeh && EnemySpeed > 10.0f); - CVec3 EnemyDirection; - CVec3 EnemyRight; - AngleVectors(EnemyAngles.v, EnemyDirection.v, EnemyRight.v, 0); + CVec3 EnemyDirection; + CVec3 EnemyRight; + AngleVectors(EnemyAngles.v, EnemyDirection.v, EnemyRight.v, 0); - CVec3 EnemyFuturePos(EnemyPos); - EnemyFuturePos.ScaleAdd(EnemyDirection, FUTURE_PRED_DIST); + CVec3 EnemyFuturePos(EnemyPos); + EnemyFuturePos.ScaleAdd(EnemyDirection, FUTURE_PRED_DIST); - ESide EnemySide = ActorPos.LRTest(EnemyPos, EnemyFuturePos); - CVec3 EnemyFlankPos(EnemyFuturePos); - EnemyFlankPos.ScaleAdd(EnemyRight, (EnemySide==Side_Right)?(FUTURE_SIDE_DIST):(-FUTURE_SIDE_DIST)); + ESide EnemySide = ActorPos.LRTest(EnemyPos, EnemyFuturePos); + CVec3 EnemyFlankPos(EnemyFuturePos); + EnemyFlankPos.ScaleAdd(EnemyRight, (EnemySide == Side_Right) ? (FUTURE_SIDE_DIST) : (-FUTURE_SIDE_DIST)); // Debug Draw Enemy Data //----------------------- - if (false) - { - CG_DrawEdge(EnemyPos.v, EnemyFuturePos.v, EDGE_IMPACT_SAFE); - CG_DrawEdge(EnemyFuturePos.v, EnemyFlankPos.v, EDGE_IMPACT_SAFE); + if (false) { + CG_DrawEdge(EnemyPos.v, EnemyFuturePos.v, EDGE_IMPACT_SAFE); + CG_DrawEdge(EnemyFuturePos.v, EnemyFlankPos.v, EDGE_IMPACT_SAFE); } - // Setup Move And Aim Directions //------------------------------- - CVec3 MoveDirection((ActorFlank)?(EnemyFlankPos):(EnemyFuturePos)); - MoveDirection -= ActorPos; - float MoveDistance = MoveDirection.SafeNorm(); - float MoveAccuracy = MoveDirection.Dot(ActorDirection); - - CVec3 AimDirection(EnemyPos); - AimDirection -= ActorPos; - float AimDistance = AimDirection.SafeNorm(); - float AimAccuracy = AimDirection.Dot(ActorDirection); + CVec3 MoveDirection((ActorFlank) ? (EnemyFlankPos) : (EnemyFuturePos)); + MoveDirection -= ActorPos; + float MoveDistance = MoveDirection.SafeNorm(); + float MoveAccuracy = MoveDirection.Dot(ActorDirection); + CVec3 AimDirection(EnemyPos); + AimDirection -= ActorPos; + float AimDistance = AimDirection.SafeNorm(); + float AimAccuracy = AimDirection.Dot(ActorDirection); - - if (!ActorFlank && TIMER_Done(NPC, "FlankAttackCheck")) - { + if (!ActorFlank && TIMER_Done(NPC, "FlankAttackCheck")) { TIMER_Set(NPC, "FlankAttackCheck", Q_irand(1000, 3000)); - if (MoveDistance<4000 && Q_irand(0, 1)==0) - { - NPCInfo->lastAvoidSteerSideDebouncer = level.time + Q_irand(8000, 14000); + if (MoveDistance < 4000 && Q_irand(0, 1) == 0) { + NPCInfo->lastAvoidSteerSideDebouncer = level.time + Q_irand(8000, 14000); } } - - // Fly By Sounds //--------------- - if ((ActorVeh->m_pVehicleInfo->soundFlyBy || ActorVeh->m_pVehicleInfo->soundFlyBy2) && - EnemyVeh && - MoveDistance<800 && - ActorSpeed>500.0f && - TIMER_Done(NPC, "FlybySoundDebouncer") - ) - { - if (EnemySpeed<100.0f || (ActorDirection.Dot(EnemyDirection)*(MoveDistance/800.0f))<-0.5f) - { + if ((ActorVeh->m_pVehicleInfo->soundFlyBy || ActorVeh->m_pVehicleInfo->soundFlyBy2) && EnemyVeh && MoveDistance < 800 && ActorSpeed > 500.0f && + TIMER_Done(NPC, "FlybySoundDebouncer")) { + if (EnemySpeed < 100.0f || (ActorDirection.Dot(EnemyDirection) * (MoveDistance / 800.0f)) < -0.5f) { TIMER_Set(NPC, "FlybySoundDebouncer", 2000); int soundFlyBy = ActorVeh->m_pVehicleInfo->soundFlyBy; - if (ActorVeh->m_pVehicleInfo->soundFlyBy2 && (!soundFlyBy || !Q_irand(0,1))) - { + if (ActorVeh->m_pVehicleInfo->soundFlyBy2 && (!soundFlyBy || !Q_irand(0, 1))) { soundFlyBy = ActorVeh->m_pVehicleInfo->soundFlyBy2; } G_Sound(ActorVeh->m_pParentEntity, soundFlyBy); } } - - -// FLY PAST BEHAVIOR -//=================== - if (EnemySlideBreak || !TIMER_Done(NPC, "MinHoldDirectionTime")) - { - if (TIMER_Done(NPC, "MinHoldDirectionTime")) - { - TIMER_Set(NPC, "MinHoldDirectionTime", 500); // Hold For At Least 500 ms + // FLY PAST BEHAVIOR + //=================== + if (EnemySlideBreak || !TIMER_Done(NPC, "MinHoldDirectionTime")) { + if (TIMER_Done(NPC, "MinHoldDirectionTime")) { + TIMER_Set(NPC, "MinHoldDirectionTime", 500); // Hold For At Least 500 ms } - ActorAccelerate = true; // Go - ActorAimAtTarget = false; // Don't Alter Our Aim Direction - ucmd.buttons &=~BUTTON_VEH_SPEED; // Let Normal Vehicle Controls Go + ActorAccelerate = true; // Go + ActorAimAtTarget = false; // Don't Alter Our Aim Direction + ucmd.buttons &= ~BUTTON_VEH_SPEED; // Let Normal Vehicle Controls Go } - -// FLANKING BEHAVIOR -//=================== - else if (ActorFlank) - { - ActorAccelerate = true; - ActorDoTurbo = (MoveDistance>2500 || EnemyInTurbo); - ucmd.buttons |= BUTTON_VEH_SPEED; // Tells PMove to use the ps.speed we calculate here, not the one from g_vehicles.c - + // FLANKING BEHAVIOR + //=================== + else if (ActorFlank) { + ActorAccelerate = true; + ActorDoTurbo = (MoveDistance > 2500 || EnemyInTurbo); + ucmd.buttons |= BUTTON_VEH_SPEED; // Tells PMove to use the ps.speed we calculate here, not the one from g_vehicles.c // For Flanking, We Calculate The Speed By Hand, Rather Than Using Pure Accelerate / No Accelerate Functionality //--------------------------------------------------------------------------------------------------------------- - NPC->client->ps.speed = ActorVeh->m_pVehicleInfo->speedMax * ((ActorInTurbo)?(1.35f):(1.15f)); - + NPC->client->ps.speed = ActorVeh->m_pVehicleInfo->speedMax * ((ActorInTurbo) ? (1.35f) : (1.15f)); // If In Slowing Distance, Scale Down The Speed As We Approach Our Move Target //----------------------------------------------------------------------------- - if (MoveDistanceclient->ps.speed *= (MoveDistance/ATTACK_FLANK_SLOWING); + if (MoveDistance < ATTACK_FLANK_SLOWING) { + NPC->client->ps.speed *= (MoveDistance / ATTACK_FLANK_SLOWING); NPC->client->ps.speed += EnemySpeed; // Match Enemy Speed //------------------- - if (NPC->client->ps.speed<5.0f && EnemySpeed<5.0f) - { + if (NPC->client->ps.speed < 5.0f && EnemySpeed < 5.0f) { NPC->client->ps.speed = EnemySpeed; } // Extra Slow Down When Out In Front //----------------------------------- - if (MoveAccuracy<0.0f) - { + if (MoveAccuracy < 0.0f) { NPC->client->ps.speed *= (MoveAccuracy + 1.0f); } + MoveDirection *= (MoveDistance / ATTACK_FLANK_SLOWING); + EnemyDirection *= 1.0f - (MoveDistance / ATTACK_FLANK_SLOWING); + MoveDirection += EnemyDirection; - MoveDirection *= (MoveDistance/ATTACK_FLANK_SLOWING); - EnemyDirection *= 1.0f - (MoveDistance/ATTACK_FLANK_SLOWING); - MoveDirection += EnemyDirection; - - if (TIMER_Done(NPC, "RamCheck")) - { + if (TIMER_Done(NPC, "RamCheck")) { TIMER_Set(NPC, "RamCheck", Q_irand(1000, 3000)); - if (MoveDistance0.99f && MoveDistance<500 && !EnemyDead) - { + // NORMAL CHASE BEHAVIOR + //======================= + else { + if (!EnemyVeh && AimAccuracy > 0.99f && MoveDistance < 500 && !EnemyDead) { ActorAccelerate = true; - ActorDoTurbo = false; - } - else - { - ActorAccelerate = ((MoveDistance>500 && EnemySpeed>20.0f) || MoveDistance>1000); - ActorDoTurbo = (MoveDistance>3000 && EnemySpeed>20.0f); + ActorDoTurbo = false; + } else { + ActorAccelerate = ((MoveDistance > 500 && EnemySpeed > 20.0f) || MoveDistance > 1000); + ActorDoTurbo = (MoveDistance > 3000 && EnemySpeed > 20.0f); } - ucmd.buttons &=~BUTTON_VEH_SPEED; + ucmd.buttons &= ~BUTTON_VEH_SPEED; } - - - -// APPLY RESULTS -//======================= + // APPLY RESULTS + //======================= // Decide Turbo //-------------- - if (ActorDoTurbo || ActorInTurbo) - { + if (ActorDoTurbo || ActorInTurbo) { ucmd.buttons |= BUTTON_ALT_ATTACK; - } - else - { - ucmd.buttons &=~BUTTON_ALT_ATTACK; + } else { + ucmd.buttons &= ~BUTTON_ALT_ATTACK; } // Decide Acceleration //--------------------- - ucmd.forwardmove = (ActorAccelerate)?(127):(0); - - + ucmd.forwardmove = (ActorAccelerate) ? (127) : (0); // Decide To Shoot //----------------- - ucmd.buttons &=~BUTTON_ATTACK; - ucmd.rightmove = 0; - if (AimDistance<2000 && !EnemyDead) - { + ucmd.buttons &= ~BUTTON_ATTACK; + ucmd.rightmove = 0; + if (AimDistance < 2000 && !EnemyDead) { // If Doing A Ram Attack //----------------------- - if (ActorYawOffset!=0) - { - if (NPC->client->ps.weapon!=WP_NONE) - { + if (ActorYawOffset != 0) { + if (NPC->client->ps.weapon != WP_NONE) { NPC_ChangeWeapon(WP_NONE); } - ucmd.buttons &=~BUTTON_ATTACK; - } - else if (AimAccuracy>ATTACK_FWD) - { - if (NPC->client->ps.weapon!=WP_NONE) - { + ucmd.buttons &= ~BUTTON_ATTACK; + } else if (AimAccuracy > ATTACK_FWD) { + if (NPC->client->ps.weapon != WP_NONE) { NPC_ChangeWeapon(WP_NONE); } - ucmd.buttons |= BUTTON_ATTACK; - } - else if (AimAccuracy-AIM_SIDE) - { - if (NPC->client->ps.weapon!=WP_BLASTER) - { + ucmd.buttons |= BUTTON_ATTACK; + } else if (AimAccuracy < AIM_SIDE && AimAccuracy > -AIM_SIDE) { + if (NPC->client->ps.weapon != WP_BLASTER) { NPC_ChangeWeapon(WP_BLASTER); } - if (AimAccuracy-ATTACK_SIDE) - { - //if (!TIMER_Done(NPC, "RiderAltAttack")) + if (AimAccuracy < ATTACK_SIDE && AimAccuracy > -ATTACK_SIDE) { + // if (!TIMER_Done(NPC, "RiderAltAttack")) //{ // ucmd.buttons |= BUTTON_ALT_ATTACK; - //} - //else + // } + // else //{ - ucmd.buttons |= BUTTON_ATTACK; + ucmd.buttons |= BUTTON_ATTACK; - /* if (TIMER_Done(NPC, "RiderAltAttackCheck")) - { - TIMER_Set(NPC, "RiderAltAttackCheck", Q_irand(1000, 3000)); - if (Q_irand(0, 2)==0) + /* if (TIMER_Done(NPC, "RiderAltAttackCheck")) { - TIMER_Set(NPC, "RiderAltAttack", 300); - } - }*/ + TIMER_Set(NPC, "RiderAltAttackCheck", Q_irand(1000, 3000)); + if (Q_irand(0, 2)==0) + { + TIMER_Set(NPC, "RiderAltAttack", 300); + } + }*/ //} WeaponThink(qtrue); } - ucmd.rightmove = (EnemySide==Side_Left)?( 127):(-127); - } - else - { - if (NPC->client->ps.weapon!=WP_NONE) - { + ucmd.rightmove = (EnemySide == Side_Left) ? (127) : (-127); + } else { + if (NPC->client->ps.weapon != WP_NONE) { NPC_ChangeWeapon(WP_NONE); } } - } - else - { - if (NPC->client->ps.weapon!=WP_NONE) - { + } else { + if (NPC->client->ps.weapon != WP_NONE) { NPC_ChangeWeapon(WP_NONE); } } - // Aim At Target //--------------- - if (ActorAimAtTarget) - { + if (ActorAimAtTarget) { MoveDirection.VecToAng(); - NPCInfo->desiredPitch = AngleNormalize360(MoveDirection[PITCH]); - NPCInfo->desiredYaw = AngleNormalize360(MoveDirection[YAW] + ActorYawOffset); + NPCInfo->desiredPitch = AngleNormalize360(MoveDirection[PITCH]); + NPCInfo->desiredYaw = AngleNormalize360(MoveDirection[YAW] + ActorYawOffset); } NPC_UpdateAngles(qtrue, qtrue); } - diff --git a/code/game/AI_Grenadier.cpp b/code/game/AI_Grenadier.cpp index 6932d0913d..2c88b6f339 100644 --- a/code/game/AI_Grenadier.cpp +++ b/code/game/AI_Grenadier.cpp @@ -26,98 +26,90 @@ along with this program; if not, see . #include "g_navigator.h" #include "g_functions.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) - -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; static qboolean faceEnemy; static qboolean doMove; static qboolean shoot; -static float enemyDist; +static float enemyDist; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Grenadier_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); +void Grenadier_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); } -void NPC_Grenadier_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Grenadier_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Grenadier_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod ) -{ +void NPC_Grenadier_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -127,9 +119,8 @@ ST_HoldPosition ------------------------- */ -static void Grenadier_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); +static void Grenadier_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); NPCInfo->goalEntity = NULL; /*if ( TIMER_Done( NPC, "stand" ) ) @@ -145,52 +136,47 @@ ST_Move ------------------------- */ -static qboolean Grenadier_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always doMove straight toward our goal - - qboolean moved = NPC_MoveToGoal( qtrue ); -// navInfo_t info; - - //Get the doMove info -// NAV_GetLastMove( info ); - - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! -// if ( info.flags & NIF_COLLISION ) -// { -// if ( info.blocker == NPC->enemy ) -// { -// Grenadier_HoldPosition(); -// } -// } - - //If our doMove failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPC->client->ps.weapon == WP_THERMAL && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); +static qboolean Grenadier_Move(void) { + NPCInfo->combatMove = qtrue; // always doMove straight toward our goal + + qboolean moved = NPC_MoveToGoal(qtrue); + // navInfo_t info; + + // Get the doMove info + // NAV_GetLastMove( info ); + + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + // if ( info.flags & NIF_COLLISION ) + // { + // if ( info.blocker == NPC->enemy ) + // { + // Grenadier_HoldPosition(); + // } + // } + + // If our doMove failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPC->client->ps.weapon == WP_THERMAL && NPCInfo->goalEntity && + NPCInfo->goalEntity == NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); return moved; } } - //just hang here + // just hang here Grenadier_HoldPosition(); } @@ -203,77 +189,62 @@ NPC_BSGrenadier_Patrol ------------------------- */ -void NPC_BSGrenadier_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 )//&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0) //&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) { - //NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + // NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -282,14 +253,13 @@ void NPC_BSGrenadier_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -320,26 +290,20 @@ ST_CheckMoveState ------------------------- */ -static void Grenadier_CheckMoveState( void ) -{ - //See if we're a scout - if ( !(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//behaviorState == BS_STAND_AND_SHOOT ) +static void Grenadier_CheckMoveState(void) { + // See if we're a scout + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { doMove = qfalse; return; } } - //See if we're running away - else if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPC, "flee" ) ) - { + // See if we're running away + else if (NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPC, "flee")) { NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy = qfalse; } } @@ -355,54 +319,47 @@ static void Grenadier_CheckMoveState( void ) } */ - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || - ( NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - { - //int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - //newSquadState = SQUAD_COVER; + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || (NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet + TIMER_Set(NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(4000, 8000)); } - if ( !NPCInfo->goalEntity ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { + if (!NPCInfo->goalEntity) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = (NPC->maxs[0]*1.5f); + NPCInfo->goalRadius = (NPC->maxs[0] * 1.5f); } } } @@ -413,24 +370,21 @@ ST_CheckFireState ------------------------- */ -static void Grenadier_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void Grenadier_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //continue to fire on their last position + // continue to fire on their last position /* if ( !Q_irand( 0, 1 ) && NPCInfo->enemyLastSeenTime && level.time - NPCInfo->enemyLastSeenTime < 4000 ) { @@ -455,15 +409,13 @@ static void Grenadier_CheckFireState( void ) */ } -qboolean Grenadier_EvaluateShot( int hit ) -{ - if ( !NPC->enemy ) - { +qboolean Grenadier_EvaluateShot(int hit) { + if (!NPC->enemy) { return qfalse; } - if ( hit == NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -475,32 +427,28 @@ NPC_BSGrenadier_Attack ------------------------- */ -void NPC_BSGrenadier_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } @@ -508,75 +456,61 @@ void NPC_BSGrenadier_Attack( void ) doMove = qtrue; faceEnemy = qfalse; shoot = qfalse; - enemyDist = DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ); - - //See if we should switch to melee attack - if ( enemyDist < 16384 && (!NPC->enemy->client||NPC->enemy->client->ps.weapon != WP_SABER||(!NPC->enemy->client->ps.SaberActive())) )//128 - {//enemy is close and not using saber - if ( NPC->client->ps.weapon == WP_THERMAL ) - {//grenadier - trace_t trace; - gi.trace ( &trace, NPC->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->enemy->currentOrigin, NPC->s.number, NPC->enemy->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->enemy->s.number ) ) - {//I can get right to him - //reset fire-timing variables - NPC_ChangeWeapon( WP_MELEE ); - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) - {//FIXME: should we be overriding scriptFlags? - NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES;//NPCInfo->behaviorState = BS_HUNT_AND_KILL; + enemyDist = DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin); + + // See if we should switch to melee attack + if (enemyDist < 16384 && (!NPC->enemy->client || NPC->enemy->client->ps.weapon != WP_SABER || (!NPC->enemy->client->ps.SaberActive()))) // 128 + { // enemy is close and not using saber + if (NPC->client->ps.weapon == WP_THERMAL) { // grenadier + trace_t trace; + gi.trace(&trace, NPC->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->enemy->currentOrigin, NPC->s.number, NPC->enemy->clipmask, + (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->enemy->s.number)) { // I can get right to him + // reset fire-timing variables + NPC_ChangeWeapon(WP_MELEE); + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) + { // FIXME: should we be overriding scriptFlags? + NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES; // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } } } - } - else if ( enemyDist > 65536 || (NPC->enemy->client && NPC->enemy->client->ps.weapon == WP_SABER && NPC->enemy->client->ps.SaberActive()) )//256 - {//enemy is far or using saber - if ( NPC->client->ps.weapon == WP_MELEE && (NPC->client->ps.stats[STAT_WEAPONS]&(1< 65536 || (NPC->enemy->client && NPC->enemy->client->ps.weapon == WP_SABER && NPC->enemy->client->ps.SaberActive())) // 256 + { // enemy is far or using saber + if (NPC->client->ps.weapon == WP_MELEE && (NPC->client->ps.stats[STAT_WEAPONS] & (1 << WP_THERMAL))) { // fisticuffs, make switch to thermal if have it + // reset fire-timing variables + NPC_ChangeWeapon(WP_THERMAL); } } - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_MELEE ) - { - if ( enemyDist <= 4096 && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45 ) )//within 64 & infront + if (NPC->client->ps.weapon == WP_MELEE) { + if (enemyDist <= 4096 && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45)) // within 64 & infront { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); enemyCS = qtrue; } - } - else if ( InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 45, 90 ) ) - {//in front of me - //can we shoot our target? - //FIXME: how accurate/necessary is this check? - int hit = NPC_ShotEntity( NPC->enemy ); + } else if (InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 45, 90)) { // in front of me + // can we shoot our target? + // FIXME: how accurate/necessary is this check? + int hit = NPC_ShotEntity(NPC->enemy); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) ) - { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - float enemyHorzDist = DistanceHorizontalSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ); - if ( enemyHorzDist < 1048576 ) - {//within 1024 + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam)) { + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + float enemyHorzDist = DistanceHorizontalSquared(NPC->enemy->currentOrigin, NPC->currentOrigin); + if (enemyHorzDist < 1048576) { // within 1024 enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - } - else - { - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + } else { + NPC_AimAdjust(1); // adjust aim better longer we can see enemy } } } - } - else - { - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } else { + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } /* else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) @@ -586,103 +520,81 @@ void NPC_BSGrenadier_Attack( void ) } */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; - if ( NPC->client->ps.weapon == WP_THERMAL ) - {//don't chase and throw + if (NPC->client->ps.weapon == WP_THERMAL) { // don't chase and throw doMove = qfalse; - } - else if ( NPC->client->ps.weapon == WP_MELEE && enemyDist < (NPC->maxs[0]+NPC->enemy->maxs[0]+16)*(NPC->maxs[0]+NPC->enemy->maxs[0]+16) ) - {//close enough + } else if (NPC->client->ps.weapon == WP_MELEE && + enemyDist < (NPC->maxs[0] + NPC->enemy->maxs[0] + 16) * (NPC->maxs[0] + NPC->enemy->maxs[0] + 16)) { // close enough doMove = qfalse; } - }//this should make him chase enemy when out of range...? + } // this should make him chase enemy when out of range...? - //Check for movement to take care of + // Check for movement to take care of Grenadier_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Grenadier_CheckFireState(); - if ( doMove ) - {//doMove toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (doMove) { // doMove toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { doMove = Grenadier_Move(); - } - else - { + } else { doMove = qfalse; } } - if ( !doMove ) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!doMove) { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); } - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( doMove ) - {//don't run away and shoot + if (!faceEnemy) { // we want to face in the dir we're running + if (doMove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy ) + { // face the enemy NPC_FaceEnemy(); } - if ( NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); - TIMER_Set( NPC, "attackDelay", NPCInfo->shotTime-level.time ); + WeaponThink(qtrue); + TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime - level.time); } - } } } -void NPC_BSGrenadier_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSGrenadier_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSGrenadier_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSGrenadier_Attack(); } } diff --git a/code/game/AI_HazardTrooper.cpp b/code/game/AI_HazardTrooper.cpp index bb18c85fec..76835598f6 100644 --- a/code/game/AI_HazardTrooper.cpp +++ b/code/game/AI_HazardTrooper.cpp @@ -39,36 +39,33 @@ along with this program; if not, see . #include "b_local.h" #include "g_navigator.h" #if !defined(RAVL_VEC_INC) - #include "../Ravl/CVec.h" +#include "../Ravl/CVec.h" #endif #if !defined(RATL_ARRAY_VS_INC) - #include "../Ratl/array_vs.h" +#include "../Ratl/array_vs.h" #endif #if !defined(RATL_VECTOR_VS_INC) - #include "../Ratl/vector_vs.h" +#include "../Ratl/vector_vs.h" #endif #if !defined(RATL_HANDLE_POOL_VS_INC) - #include "../Ratl/handle_pool_vs.h" +#include "../Ratl/handle_pool_vs.h" #endif #if !defined(RUFL_HSTRING_INC) - #include "../Rufl/hstring.h" +#include "../Rufl/hstring.h" #endif - //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define MAX_TROOPS 100 -#define MAX_ENTS_PER_TROOP 7 -#define MAX_TROOP_JOIN_DIST2 1000000 //1000 units -#define MAX_TROOP_MERGE_DIST2 250000 //500 units -#define TARGET_POS_VISITED 10000 //100 units - +#define MAX_TROOPS 100 +#define MAX_ENTS_PER_TROOP 7 +#define MAX_TROOP_JOIN_DIST2 1000000 // 1000 units +#define MAX_TROOP_MERGE_DIST2 250000 // 500 units +#define TARGET_POS_VISITED 10000 // 100 units -bool NPC_IsTrooper(gentity_t* actor); +bool NPC_IsTrooper(gentity_t *actor); -enum -{ +enum { SPEECH_CHASE, SPEECH_CONFUSED, SPEECH_COVER, @@ -84,21 +81,16 @@ enum SPEECH_YELL, SPEECH_PUSHED }; -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void CG_DrawEdge( vec3_t start, vec3_t end, int type ); -static void HT_Speech( gentity_t *self, int speechType, float failChance ) -{ - if ( Q_flrand(0.0f, 1.0f) < failChance ) - { +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void CG_DrawEdge(vec3_t start, vec3_t end, int type); +static void HT_Speech(gentity_t *self, int speechType, float failChance) { + if (Q_flrand(0.0f, 1.0f) < failChance) { return; } - if ( failChance >= 0 ) - {//a negative failChance makes it always talk - if ( self->NPC->group ) - {//group AI speech debounce timer - if ( self->NPC->group->speechDebounceTime > level.time ) - { + if (failChance >= 0) { // a negative failChance makes it always talk + if (self->NPC->group) { // group AI speech debounce timer + if (self->NPC->group->speechDebounceTime > level.time) { return; } /* @@ -110,63 +102,59 @@ static void HT_Speech( gentity_t *self, int speechType, float failChance ) } } */ - } - else if ( !TIMER_Done( self, "chatter" ) ) - {//personal timer + } else if (!TIMER_Done(self, "chatter")) { // personal timer return; } } - TIMER_Set( self, "chatter", Q_irand( 2000, 4000 ) ); + TIMER_Set(self, "chatter", Q_irand(2000, 4000)); - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - switch( speechType ) - { + switch (speechType) { case SPEECH_CHASE: - G_AddVoiceEvent( self, Q_irand(EV_CHASE1, EV_CHASE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CHASE1, EV_CHASE3), 2000); break; case SPEECH_CONFUSED: - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); break; case SPEECH_COVER: - G_AddVoiceEvent( self, Q_irand(EV_COVER1, EV_COVER5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_COVER1, EV_COVER5), 2000); break; case SPEECH_DETECTED: - G_AddVoiceEvent( self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000); break; case SPEECH_GIVEUP: - G_AddVoiceEvent( self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000); break; case SPEECH_LOOK: - G_AddVoiceEvent( self, Q_irand(EV_LOOK1, EV_LOOK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_LOOK1, EV_LOOK2), 2000); break; case SPEECH_LOST: - G_AddVoiceEvent( self, EV_LOST1, 2000 ); + G_AddVoiceEvent(self, EV_LOST1, 2000); break; case SPEECH_OUTFLANK: - G_AddVoiceEvent( self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000); break; case SPEECH_ESCAPING: - G_AddVoiceEvent( self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000); break; case SPEECH_SIGHT: - G_AddVoiceEvent( self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000); break; case SPEECH_SOUND: - G_AddVoiceEvent( self, Q_irand(EV_SOUND1, EV_SOUND3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SOUND1, EV_SOUND3), 2000); break; case SPEECH_SUSPICIOUS: - G_AddVoiceEvent( self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000); break; case SPEECH_YELL: - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 2000); break; case SPEECH_PUSHED: - G_AddVoiceEvent( self, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); break; default: break; @@ -175,9 +163,6 @@ static void HT_Speech( gentity_t *self, int speechType, float failChance ) self->NPC->blockedSpeechDebounceTime = level.time + 2000; } - - - //////////////////////////////////////////////////////////////////////////////////////// // The Troop // @@ -186,107 +171,85 @@ static void HT_Speech( gentity_t *self, int speechType, float failChance ) // the movement of the rest of the group. // //////////////////////////////////////////////////////////////////////////////////////// -class CTroop -{ +class CTroop { //////////////////////////////////////////////////////////////////////////////////// // Various Troop Wide Data //////////////////////////////////////////////////////////////////////////////////// - int mTroopHandle; - int mTroopTeam; - bool mTroopReform; + int mTroopHandle; + int mTroopTeam; + bool mTroopReform; - float mFormSpacingFwd; - float mFormSpacingRight; + float mFormSpacingFwd; + float mFormSpacingRight; -public: - bool Empty() {return mActors.empty();} - int Team() {return mTroopTeam;} - int Handle() {return mTroopHandle;} + public: + bool Empty() { return mActors.empty(); } + int Team() { return mTroopTeam; } + int Handle() { return mTroopHandle; } //////////////////////////////////////////////////////////////////////////////////// // Initialize - Clear out all data, all actors, reset all variables //////////////////////////////////////////////////////////////////////////////////// - void Initialize(int TroopHandle=0) - { + void Initialize(int TroopHandle = 0) { mActors.clear(); - mTarget = 0; - mState = TS_NONE; - mTroopHandle = TroopHandle; - mTroopTeam = 0; - mTroopReform = false; + mTarget = 0; + mState = TS_NONE; + mTroopHandle = TroopHandle; + mTroopTeam = 0; + mTroopReform = false; } //////////////////////////////////////////////////////////////////////////////////// // DistanceSq - Quick Operation to see how far an ent is from the rest of the troop //////////////////////////////////////////////////////////////////////////////////// - float DistanceSq(gentity_t* ent) - { - if (mActors.size()) - { + float DistanceSq(gentity_t *ent) { + if (mActors.size()) { return DistanceSquared(ent->currentOrigin, mActors[0]->currentOrigin); } return 0.0f; } - - - - - - - - - -private: + private: //////////////////////////////////////////////////////////////////////////////////// // The Actors // // Actors are all the troopers who belong to the group, their positions in this // vector affect their positions in the troop, whith the first actor as the leader //////////////////////////////////////////////////////////////////////////////////// - ratl::vector_vs mActors; + ratl::vector_vs mActors; //////////////////////////////////////////////////////////////////////////////////// // MakeActorLeader - Move A Given Index To A Leader Position //////////////////////////////////////////////////////////////////////////////////// - void MakeActorLeader(int index) - { - if (index!=0) - { + void MakeActorLeader(int index) { + if (index != 0) { mActors[0]->client->leader = 0; mActors.swap(index, 0); } mActors[0]->client->leader = mActors[0]; - if (mActors[0]) - { - if (mActors[0]->client->NPC_class==CLASS_HAZARD_TROOPER) - { - mFormSpacingFwd = 75.0f; - mFormSpacingRight = 50.0f; - } - else - { - mFormSpacingFwd = 75.0f; - mFormSpacingRight = 20.0f; + if (mActors[0]) { + if (mActors[0]->client->NPC_class == CLASS_HAZARD_TROOPER) { + mFormSpacingFwd = 75.0f; + mFormSpacingRight = 50.0f; + } else { + mFormSpacingFwd = 75.0f; + mFormSpacingRight = 20.0f; } } } -public: + public: //////////////////////////////////////////////////////////////////////////////////// // AddActor - Adds a new actor to the troop & automatically promote to leader //////////////////////////////////////////////////////////////////////////////////// - void AddActor(gentity_t* actor) - { - assert(actor->NPC->troop==0 && !mActors.full()); + void AddActor(gentity_t *actor) { + assert(actor->NPC->troop == 0 && !mActors.full()); actor->NPC->troop = mTroopHandle; mActors.push_back(actor); mTroopReform = true; - if ((mActors.size()==1) || (actor->NPC->rank > mActors[0]->NPC->rank)) - { - MakeActorLeader(mActors.size()-1); + if ((mActors.size() == 1) || (actor->NPC->rank > mActors[0]->NPC->rank)) { + MakeActorLeader(mActors.size() - 1); } - if (!mTroopTeam) - { + if (!mTroopTeam) { mTroopTeam = actor->client->playerTeam; } } @@ -294,115 +257,98 @@ class CTroop //////////////////////////////////////////////////////////////////////////////////// // RemoveActor - Removes an actor from the troop & automatically promote leader //////////////////////////////////////////////////////////////////////////////////// - void RemoveActor(gentity_t* actor) - { - assert(actor->NPC->troop==mTroopHandle); - int bestNewLeader=-1; - int numEnts = mActors.size(); - //bool found = false; + void RemoveActor(gentity_t *actor) { + assert(actor->NPC->troop == mTroopHandle); + int bestNewLeader = -1; + int numEnts = mActors.size(); + // bool found = false; mTroopReform = true; // Find The Actor //---------------- - for (int i=0; i=0 && (mActors[i]->NPC->rank > mActors[bestNewLeader]->NPC->rank)) - { + if (bestNewLeader >= 0 && (mActors[i]->NPC->rank > mActors[bestNewLeader]->NPC->rank)) { bestNewLeader = i; } } - if (!mActors.empty() && bestNewLeader>=0) - { + if (!mActors.empty() && bestNewLeader >= 0) { MakeActorLeader(bestNewLeader); } - //assert(found); + // assert(found); actor->NPC->troop = 0; } -private: + private: //////////////////////////////////////////////////////////////////////////////////// // Enemy // // The troop has a collective enemy that it knows about, which is updated by all // the members of the group; //////////////////////////////////////////////////////////////////////////////////// - gentity_t* mTarget; - bool mTargetVisable; - int mTargetVisableStartTime; - int mTargetVisableStopTime; - CVec3 mTargetVisablePosition; - int mTargetIndex; - int mTargetLastKnownTime; - CVec3 mTargetLastKnownPosition; - bool mTargetLastKnownPositionVisited; + gentity_t *mTarget; + bool mTargetVisable; + int mTargetVisableStartTime; + int mTargetVisableStopTime; + CVec3 mTargetVisablePosition; + int mTargetIndex; + int mTargetLastKnownTime; + CVec3 mTargetLastKnownPosition; + bool mTargetLastKnownPositionVisited; //////////////////////////////////////////////////////////////////////////////////// // RegisterTarget - Records That the target is seen, when and where //////////////////////////////////////////////////////////////////////////////////// - void RegisterTarget(gentity_t* target, int index, bool visable) - { - if (!mTarget) - { + void RegisterTarget(gentity_t *target, int index, bool visable) { + if (!mTarget) { HT_Speech(mActors[0], SPEECH_DETECTED, 0); - } - else if ((level.time - mTargetLastKnownTime)>8000) - { + } else if ((level.time - mTargetLastKnownTime) > 8000) { HT_Speech(mActors[0], SPEECH_SIGHT, 0); } - if (visable) - { + if (visable) { mTargetVisableStopTime = level.time; - if (!mTargetVisable) - { + if (!mTargetVisable) { mTargetVisableStartTime = level.time; } - CalcEntitySpot(target, SPOT_HEAD, mTargetVisablePosition.v); + CalcEntitySpot(target, SPOT_HEAD, mTargetVisablePosition.v); mTargetVisablePosition[2] -= 10.0f; } - mTarget = target; - mTargetVisable = visable; - mTargetIndex = index; - mTargetLastKnownTime = level.time; - mTargetLastKnownPosition = target->currentOrigin; + mTarget = target; + mTargetVisable = visable; + mTargetIndex = index; + mTargetLastKnownTime = level.time; + mTargetLastKnownPosition = target->currentOrigin; mTargetLastKnownPositionVisited = false; } //////////////////////////////////////////////////////////////////////////////////// // RegisterTarget - Records That the target is seen, when and where //////////////////////////////////////////////////////////////////////////////////// - bool TargetLastKnownPositionVisited() - { - if (!mTargetLastKnownPositionVisited) - { + bool TargetLastKnownPositionVisited() { + if (!mTargetLastKnownPositionVisited) { float dist = DistanceSquared(mTargetLastKnownPosition.v, mActors[0]->currentOrigin); - mTargetLastKnownPositionVisited = (dist1.0f) - { + float ClampScale(float val) { + if (val > 1.0f) { val = 1.0f; } - if (val<0.0f) - { + if (val < 0.0f) { val = 0.0f; } return val; @@ -413,11 +359,9 @@ class CTroop // // Compute all factors that can add visibility to a target //////////////////////////////////////////////////////////////////////////////////// - float TargetVisibility(gentity_t* target) - { - float Scale = 0.8f; - if (target->client && target->client->ps.weapon==WP_SABER && target->client->ps.SaberActive()) - { + float TargetVisibility(gentity_t *target) { + float Scale = 0.8f; + if (target->client && target->client->ps.weapon == WP_SABER && target->client->ps.SaberActive()) { Scale += 0.1f; } return ClampScale(Scale); @@ -426,12 +370,10 @@ class CTroop //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - float TargetNoiseLevel(gentity_t* target) - { - float Scale = 0.1f; - Scale += target->resultspeed / (float)g_speed->integer; - if (target->client && target->client->ps.weapon==WP_SABER && target->client->ps.SaberActive()) - { + float TargetNoiseLevel(gentity_t *target) { + float Scale = 0.1f; + Scale += target->resultspeed / (float)g_speed->integer; + if (target->client && target->client->ps.weapon == WP_SABER && target->client->ps.SaberActive()) { Scale += 0.2f; } return ClampScale(Scale); @@ -440,66 +382,57 @@ class CTroop //////////////////////////////////////////////////////////////////////////////////// // Scan For Enemies //////////////////////////////////////////////////////////////////////////////////// - void ScanForTarget(int scannerIndex) - { - gentity_t* target; - int targetIndex=0; - int targetStop=ENTITYNUM_WORLD; - CVec3 targetPos; - CVec3 targetDirection; - float targetDistance; - float targetVisibility; - float targetNoiseLevel; - - gentity_t* scanner = mActors[scannerIndex]; - gNPCstats_t* scannerStats = &(scanner->NPC->stats); - float scannerMaxViewDist = scannerStats->visrange; - float scannerMinVisability = 0.1f;//1.0f - scannerStats->vigilance; - float scannerMaxHearDist = scannerStats->earshot; - float scannerMinNoiseLevel = 0.3f;//1.0f - scannerStats->vigilance; - CVec3 scannerPos(scanner->currentOrigin); - CVec3 scannerFwd(scanner->currentAngles); + void ScanForTarget(int scannerIndex) { + gentity_t *target; + int targetIndex = 0; + int targetStop = ENTITYNUM_WORLD; + CVec3 targetPos; + CVec3 targetDirection; + float targetDistance; + float targetVisibility; + float targetNoiseLevel; + + gentity_t *scanner = mActors[scannerIndex]; + gNPCstats_t *scannerStats = &(scanner->NPC->stats); + float scannerMaxViewDist = scannerStats->visrange; + float scannerMinVisability = 0.1f; // 1.0f - scannerStats->vigilance; + float scannerMaxHearDist = scannerStats->earshot; + float scannerMinNoiseLevel = 0.3f; // 1.0f - scannerStats->vigilance; + CVec3 scannerPos(scanner->currentOrigin); + CVec3 scannerFwd(scanner->currentAngles); scannerFwd.AngToVec(); // If Existing Target, Only Check It //----------------------------------- - if (mTarget) - { - targetIndex = mTargetIndex; - targetStop = mTargetIndex+1; + if (mTarget) { + targetIndex = mTargetIndex; + targetStop = mTargetIndex + 1; } SaveNPCGlobals(); SetNPCGlobals(scanner); - - for (; targetIndexcurrentOrigin; - if (target->client && target->client->ps.leanofs) - { - targetPos = target->client->renderInfo.eyePoint; + targetPos = target->currentOrigin; + if (target->client && target->client->ps.leanofs) { + targetPos = target->client->renderInfo.eyePoint; } - targetDirection = (targetPos - scannerPos); - targetDistance = targetDirection.SafeNorm(); + targetDirection = (targetPos - scannerPos); + targetDistance = targetDirection.SafeNorm(); // Can The Scanner SEE The Target? //--------------------------------- - if (targetDistancescannerMinVisability) - { - if (NPC_ClearLOS(targetPos.v)) - { + if (targetDistance < scannerMaxViewDist) { + targetVisibility = TargetVisibility(target); + targetVisibility *= targetDirection.Dot(scannerFwd); + if (targetVisibility > scannerMinVisability) { + if (NPC_ClearLOS(targetPos.v)) { RegisterTarget(target, targetIndex, true); RestoreNPCGlobals(); return; @@ -509,12 +442,10 @@ class CTroop // Can The Scanner HEAR The Target? //---------------------------------- - if (targetDistancescannerMinNoiseLevel) - { + targetNoiseLevel *= (1.0f - (targetDistance / scannerMaxHearDist)); // scale by distance + if (targetNoiseLevel > scannerMinNoiseLevel) { RegisterTarget(target, targetIndex, false); RestoreNPCGlobals(); return; @@ -524,55 +455,43 @@ class CTroop RestoreNPCGlobals(); } - - - - - - - -private: + private: //////////////////////////////////////////////////////////////////////////////////// // Troop State // // The troop as a whole can be acting under a number of different "behavior states" //////////////////////////////////////////////////////////////////////////////////// - enum ETroopState - { - TS_NONE = 0, // No troop wide activity active - - TS_ADVANCE, // CHOOSE A NEW ADVANCE TACTIC - TS_ADVANCE_REGROUP, // All ents move into squad position - TS_ADVANCE_SEARCH, // Slow advance, looking left to right, in formation - TS_ADVANCE_COVER, // One at a time moves forward, goes off path, provides cover - TS_ADVANCE_FORMATION, // In formation jog to goal location - - TS_ATTACK, // CHOOSE A NEW ATTACK TACTIC - TS_ATTACK_LINE, // Form 2 lines, front kneel, back stand - TS_ATTACK_FLANK, // Same As Line, except scouting group attemts to get around other side of target - TS_ATTACK_SURROUND, // Get on all sides of target - TS_ATTACK_COVER, // + enum ETroopState { + TS_NONE = 0, // No troop wide activity active + + TS_ADVANCE, // CHOOSE A NEW ADVANCE TACTIC + TS_ADVANCE_REGROUP, // All ents move into squad position + TS_ADVANCE_SEARCH, // Slow advance, looking left to right, in formation + TS_ADVANCE_COVER, // One at a time moves forward, goes off path, provides cover + TS_ADVANCE_FORMATION, // In formation jog to goal location + + TS_ATTACK, // CHOOSE A NEW ATTACK TACTIC + TS_ATTACK_LINE, // Form 2 lines, front kneel, back stand + TS_ATTACK_FLANK, // Same As Line, except scouting group attemts to get around other side of target + TS_ATTACK_SURROUND, // Get on all sides of target + TS_ATTACK_COVER, // TS_MAX }; - ETroopState mState; - - CVec3 mFormHead; - CVec3 mFormFwd; - CVec3 mFormRight; + ETroopState mState; + CVec3 mFormHead; + CVec3 mFormFwd; + CVec3 mFormRight; //////////////////////////////////////////////////////////////////////////////////// // TroopInFormation - A quick check to see if the troop is currently in formation //////////////////////////////////////////////////////////////////////////////////// - bool TroopInFormation() - { - float maxActorRangeSq = ((mActors.size()/2) + 2) * mFormSpacingFwd; + bool TroopInFormation() { + float maxActorRangeSq = ((mActors.size() / 2) + 2) * mFormSpacingFwd; maxActorRangeSq *= maxActorRangeSq; - for (int actorIndex=1; actorIndexmaxActorRangeSq) - { + for (int actorIndex = 1; actorIndex < mActors.size(); actorIndex++) { + if (DistanceSq(mActors[actorIndex]) > maxActorRangeSq) { return false; } } @@ -582,45 +501,37 @@ class CTroop //////////////////////////////////////////////////////////////////////////////////// // SActorOrder //////////////////////////////////////////////////////////////////////////////////// - struct SActorOrder - { - CVec3 mPosition; - int mCombatPoint; - bool mKneelAndShoot; + struct SActorOrder { + CVec3 mPosition; + int mCombatPoint; + bool mKneelAndShoot; }; - ratl::array_vs mOrders; - + ratl::array_vs mOrders; //////////////////////////////////////////////////////////////////////////////////// // LeaderIssueAndUpdateOrders - Tell Everyone Where To Go //////////////////////////////////////////////////////////////////////////////////// - void LeaderIssueAndUpdateOrders(ETroopState NextState) - { - int actorIndex; - int actorCount = mActors.size(); + void LeaderIssueAndUpdateOrders(ETroopState NextState) { + int actorIndex; + int actorCount = mActors.size(); // Always Put Guys Closest To The Order Locations In Those Locations //------------------------------------------------------------------- - for (int orderIndex=1; orderIndexcurrentOrigin); - float currentDistance = closestActorDistance; - for (actorIndex=orderIndex+1; actorIndexcurrentOrigin); + float currentDistance = closestActorDistance; + for (actorIndex = orderIndex + 1; actorIndex < actorCount; actorIndex++) { currentDistance = DistanceSquared(mOrders[orderIndex].mPosition.v, mActors[actorIndex]->currentOrigin); - if (currentDistancepos1); } -// PHASE I - VOICE COMMANDS & ANIMATIONS -//======================================= - gentity_t* leader = mActors[0]; - - if (NextState!=mState) - { - if (mActors.size()>0) - { - switch (NextState) - { - case (TS_ADVANCE_REGROUP) : - { - break; - } - case (TS_ADVANCE_SEARCH) : - { - HT_Speech(leader, SPEECH_LOOK, 0); - break; - } - case (TS_ADVANCE_COVER) : - { - HT_Speech(leader, SPEECH_COVER, 0); - NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLDLESS); - break; - } - case (TS_ADVANCE_FORMATION) : - { - HT_Speech(leader, SPEECH_ESCAPING, 0); - break; - } + // PHASE I - VOICE COMMANDS & ANIMATIONS + //======================================= + gentity_t *leader = mActors[0]; + if (NextState != mState) { + if (mActors.size() > 0) { + switch (NextState) { + case (TS_ADVANCE_REGROUP): { + break; + } + case (TS_ADVANCE_SEARCH): { + HT_Speech(leader, SPEECH_LOOK, 0); + break; + } + case (TS_ADVANCE_COVER): { + HT_Speech(leader, SPEECH_COVER, 0); + NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS); + break; + } + case (TS_ADVANCE_FORMATION): { + HT_Speech(leader, SPEECH_ESCAPING, 0); + break; + } - case (TS_ATTACK_LINE) : - { - HT_Speech(leader, SPEECH_CHASE, 0); - NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLDLESS); - break; - } - case (TS_ATTACK_FLANK) : - { - HT_Speech(leader, SPEECH_OUTFLANK, 0); - NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLDLESS); - break; - } - case (TS_ATTACK_SURROUND) : - { - HT_Speech(leader, SPEECH_GIVEUP, 0); - NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLDLESS); - break; - } - case (TS_ATTACK_COVER) : - { - HT_Speech(leader, SPEECH_COVER, 0); - break; - } - default: - { - } + case (TS_ATTACK_LINE): { + HT_Speech(leader, SPEECH_CHASE, 0); + NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS); + break; + } + case (TS_ATTACK_FLANK): { + HT_Speech(leader, SPEECH_OUTFLANK, 0); + NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS); + break; + } + case (TS_ATTACK_SURROUND): { + HT_Speech(leader, SPEECH_GIVEUP, 0); + NPC_SetAnim(leader, SETANIM_TORSO, TORSO_HANDSIGNAL2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS); + break; + } + case (TS_ATTACK_COVER): { + HT_Speech(leader, SPEECH_COVER, 0); + break; + } + default: { + } } } } // If Attacking, And Not Forced To Reform, Don't Recalculate Orders //------------------------------------------------------------------ - else if (NextState>TS_ATTACK && !mTroopReform) - { + else if (NextState > TS_ATTACK && !mTroopReform) { return; } - -// PHASE II - COMPUTE THE NEW FORMATION HEAD, FORWARD, AND RIGHT VECTORS -//======================================================================= - mFormHead = leader->currentOrigin; - mFormFwd = (NAV::HasPath(leader))?(NAV::NextPosition(leader)):(mTargetLastKnownPosition); - mFormFwd -= mFormHead; + // PHASE II - COMPUTE THE NEW FORMATION HEAD, FORWARD, AND RIGHT VECTORS + //======================================================================= + mFormHead = leader->currentOrigin; + mFormFwd = (NAV::HasPath(leader)) ? (NAV::NextPosition(leader)) : (mTargetLastKnownPosition); + mFormFwd -= mFormHead; mFormFwd[2] = 0; - mFormFwd *= -1.0f; // Form Forward Goes Behind The Leader + mFormFwd *= -1.0f; // Form Forward Goes Behind The Leader mFormFwd.Norm(); - mFormRight = mFormFwd; + mFormRight = mFormFwd; mFormRight.Cross(CVec3::mZ); - // Scale Vectors By Spacing Distances //------------------------------------ - mFormFwd *= mFormSpacingFwd; - mFormRight *= mFormSpacingRight; + mFormFwd *= mFormSpacingFwd; + mFormRight *= mFormSpacingRight; // If Attacking, Move Head Forward Some To Center On Target //---------------------------------------------------------- - if (NextState>TS_ATTACK) - { - if (!mTroopReform) - { - int FwdNum = ((actorCount/2)+1); - for (int i=0; i TS_ATTACK) { + if (!mTroopReform) { + int FwdNum = ((actorCount / 2) + 1); + for (int i = 0; i < FwdNum; i++) { mFormHead -= mFormFwd; } } - trace_t trace; + trace_t trace; mOrders[0].mPosition = mFormHead; - gi.trace(&trace, - mActors[0]->currentOrigin, - mActors[0]->mins, - mActors[0]->maxs, - mOrders[0].mPosition.v, - mActors[0]->s.number, - mActors[0]->clipmask, - (EG2_Collision)0, - 0 - ); - - if (trace.fraction<1.0f) - { + gi.trace(&trace, mActors[0]->currentOrigin, mActors[0]->mins, mActors[0]->maxs, mOrders[0].mPosition.v, mActors[0]->s.number, mActors[0]->clipmask, + (EG2_Collision)0, 0); + + if (trace.fraction < 1.0f) { mOrders[0].mPosition = trace.endpos; } - } - else - { + } else { mOrders[0].mPosition = mTargetLastKnownPosition; } VectorCopy(mOrders[0].mPosition.v, mActors[0]->pos1); - CVec3 FormTgtToHead(mFormHead); - FormTgtToHead -= mTargetLastKnownPosition; - /*float FormTgtToHeadDist = */FormTgtToHead.SafeNorm(); + CVec3 FormTgtToHead(mFormHead); + FormTgtToHead -= mTargetLastKnownPosition; + /*float FormTgtToHeadDist = */ FormTgtToHead.SafeNorm(); - CVec3 BaseAngleToHead(FormTgtToHead); - BaseAngleToHead.VecToAng(); + CVec3 BaseAngleToHead(FormTgtToHead); + BaseAngleToHead.VecToAng(); -// int NumPerSide = mActors.size()/2; -// float WidestAngle = FORMATION_SURROUND_FAN * (NumPerSide+1); + // int NumPerSide = mActors.size()/2; + // float WidestAngle = FORMATION_SURROUND_FAN * (NumPerSide+1); - - -// PHASE III - USE FORMATION VECTORS TO COMPUTE ORDERS FOR ALL ACTORS -//==================================================================== - for (actorIndex=1; actorIndexNPC->combatPoint!=-1) - { + if (mActors[actorIndex]->NPC->combatPoint != -1) { NPC_FreeCombatPoint(mActors[actorIndex]->NPC->combatPoint, qfalse); mActors[actorIndex]->NPC->combatPoint = -1; } - - Order.mPosition = mFormHead; - Order.mCombatPoint = -1; - Order.mKneelAndShoot= false; - + Order.mPosition = mFormHead; + Order.mCombatPoint = -1; + Order.mKneelAndShoot = false; // Advance Orders //---------------- - if (NextState=4) - { - int cpFlags = (CP_HAS_ROUTE|CP_AVOID_ENEMY|CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); - float avoidDist = 128.0f; - - Order.mCombatPoint = NPC_FindCombatPointRetry( - mActors[actorIndex]->currentOrigin, - mActors[actorIndex]->currentOrigin, - mActors[actorIndex]->currentOrigin, - &cpFlags, - avoidDist, - 0); - - if (Order.mCombatPoint!=-1 && (cpFlags&CP_CLEAR)) - { + else { + if (NextState == TS_ATTACK_LINE || (NextState == TS_ATTACK_FLANK && actorIndex < 4)) { + Order.mPosition.ScaleAdd(mFormFwd, FwdScale); + Order.mPosition.ScaleAdd(mFormRight, SideScale); + } else if (NextState == TS_ATTACK_FLANK && actorIndex >= 4) { + int cpFlags = (CP_HAS_ROUTE | CP_AVOID_ENEMY | CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); + float avoidDist = 128.0f; + + Order.mCombatPoint = NPC_FindCombatPointRetry(mActors[actorIndex]->currentOrigin, mActors[actorIndex]->currentOrigin, + mActors[actorIndex]->currentOrigin, &cpFlags, avoidDist, 0); + + if (Order.mCombatPoint != -1 && (cpFlags & CP_CLEAR)) { Order.mPosition = level.combatPoints[Order.mCombatPoint].origin; NPC_SetCombatPoint(Order.mCombatPoint); + } else { + Order.mPosition.ScaleAdd(mFormFwd, FwdScale); + Order.mPosition.ScaleAdd(mFormRight, SideScale); } - else - { - Order.mPosition.ScaleAdd(mFormFwd, FwdScale); - Order.mPosition.ScaleAdd(mFormRight, SideScale); - } - } - else if (NextState==TS_ATTACK_SURROUND) - { - Order.mPosition.ScaleAdd(mFormFwd, FwdScale); - Order.mPosition.ScaleAdd(mFormRight, SideScale); - -/* CVec3 FanAngles = BaseAngleToHead; - FanAngles[YAW] += (SideScale * (WidestAngle-(FwdScale*FORMATION_SURROUND_FAN))); - FanAngles.AngToVec(); - - Order.mPosition = mTargetLastKnownPosition; - Order.mPosition.ScaleAdd(FanAngles, FormTgtToHeadDist); -*/ - } - else if (NextState==TS_ATTACK_COVER) - { - Order.mPosition.ScaleAdd(mFormFwd, FwdScale); - Order.mPosition.ScaleAdd(mFormRight, SideScale); + } else if (NextState == TS_ATTACK_SURROUND) { + Order.mPosition.ScaleAdd(mFormFwd, FwdScale); + Order.mPosition.ScaleAdd(mFormRight, SideScale); + + /* CVec3 FanAngles = BaseAngleToHead; + FanAngles[YAW] += (SideScale * (WidestAngle-(FwdScale*FORMATION_SURROUND_FAN))); + FanAngles.AngToVec(); + + Order.mPosition = mTargetLastKnownPosition; + Order.mPosition.ScaleAdd(FanAngles, FormTgtToHeadDist); + */ + } else if (NextState == TS_ATTACK_COVER) { + Order.mPosition.ScaleAdd(mFormFwd, FwdScale); + Order.mPosition.ScaleAdd(mFormRight, SideScale); } } - if (NextState>=TS_ATTACK) - { - trace_t trace; - CVec3 OrderUp(Order.mPosition); + if (NextState >= TS_ATTACK) { + trace_t trace; + CVec3 OrderUp(Order.mPosition); OrderUp[2] += 10.0f; - gi.trace(&trace, - Order.mPosition.v, - mActors[actorIndex]->mins, - mActors[actorIndex]->maxs, - OrderUp.v, - mActors[actorIndex]->s.number, - CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, - (EG2_Collision)0, - 0); - - if (trace.startsolid || trace.allsolid) - { - int cpFlags = (CP_HAS_ROUTE|CP_AVOID_ENEMY|CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); - float avoidDist = 128.0f; - - Order.mCombatPoint = NPC_FindCombatPointRetry( - mActors[actorIndex]->currentOrigin, - mActors[actorIndex]->currentOrigin, - mActors[actorIndex]->currentOrigin, - &cpFlags, - avoidDist, - 0); - - if (Order.mCombatPoint!=-1) - { + gi.trace(&trace, Order.mPosition.v, mActors[actorIndex]->mins, mActors[actorIndex]->maxs, OrderUp.v, mActors[actorIndex]->s.number, + CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, (EG2_Collision)0, 0); + + if (trace.startsolid || trace.allsolid) { + int cpFlags = (CP_HAS_ROUTE | CP_AVOID_ENEMY | CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); + float avoidDist = 128.0f; + + Order.mCombatPoint = NPC_FindCombatPointRetry(mActors[actorIndex]->currentOrigin, mActors[actorIndex]->currentOrigin, + mActors[actorIndex]->currentOrigin, &cpFlags, avoidDist, 0); + + if (Order.mCombatPoint != -1) { Order.mPosition = level.combatPoints[Order.mCombatPoint].origin; NPC_SetCombatPoint(Order.mCombatPoint); - } - else - { + } else { Order.mPosition = mOrders[0].mPosition; } } @@ -910,106 +747,78 @@ class CTroop mTroopReform = false; mState = NextState; - } + } //////////////////////////////////////////////////////////////////////////////////// // SufficientCoverNearby - Look at nearby combat points, see if there is enough //////////////////////////////////////////////////////////////////////////////////// - bool SufficientCoverNearby() - { + bool SufficientCoverNearby() { // TODO: Evaluate Available Combat Points return false; } - - - - - - - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Update - This is the primary "think" function from the troop //////////////////////////////////////////////////////////////////////////////////// - void Update() - { - if (mActors.empty()) - { + void Update() { + if (mActors.empty()) { return; } ScanForTarget(0 /*Q_irand(0, (mActors.size()-1))*/); - if (mTarget) - { - ETroopState NextState = mState; - int TimeSinceLastSeen = (level.time - mTargetVisableStopTime); - // int TimeVisable = (mTargetVisableStopTime - mTargetVisableStartTime); - bool Attack = (TimeSinceLastSeen<2000); + if (mTarget) { + ETroopState NextState = mState; + int TimeSinceLastSeen = (level.time - mTargetVisableStopTime); + // int TimeVisable = (mTargetVisableStopTime - mTargetVisableStartTime); + bool Attack = (TimeSinceLastSeen < 2000); - if (Attack) - { + if (Attack) { // If Not Currently Attacking, Or We Want To Pick A New Attack Tactic //-------------------------------------------------------------------- - if (mState4)?(TS_ATTACK_FLANK):(TS_ATTACK_LINE); - } - else - { - NextState = (SufficientCoverNearby())?(TS_ATTACK_COVER):(TS_ATTACK_SURROUND); + if (mState < TS_ATTACK /*|| TODO: Timer To Pick New Tactic */) { + if (TroopInFormation()) { + NextState = (mActors.size() > 4) ? (TS_ATTACK_FLANK) : (TS_ATTACK_LINE); + } else { + NextState = (SufficientCoverNearby()) ? (TS_ATTACK_COVER) : (TS_ATTACK_SURROUND); } } - } - else - { - if (!TroopInFormation()) - { + } else { + if (!TroopInFormation()) { NextState = TS_ADVANCE_REGROUP; - } - else - { - if (TargetLastKnownPositionVisited()) - { + } else { + if (TargetLastKnownPositionVisited()) { NextState = TS_ADVANCE_SEARCH; - } - else - { - NextState = (TimeSinceLastSeen<10000)?(TS_ADVANCE_COVER):(TS_ADVANCE_FORMATION); + } else { + NextState = (TimeSinceLastSeen < 10000) ? (TS_ADVANCE_COVER) : (TS_ADVANCE_FORMATION); } } } LeaderIssueAndUpdateOrders(NextState); - } } //////////////////////////////////////////////////////////////////////////////////// // MergeInto - Merges all actors into anther troop //////////////////////////////////////////////////////////////////////////////////// - void MergeInto(CTroop& Other) - { - int numEnts = mActors.size(); - for (int i=0; iclient->leader = 0; mActors[i]->NPC->troop = 0; Other.AddActor(mActors[i]); } mActors.clear(); - if (!Other.mTarget && mTarget) - { - Other.mTarget = mTarget; - Other.mTargetIndex = mTargetIndex; - Other.mTargetLastKnownPosition = mTargetLastKnownPosition; - Other.mTargetLastKnownPositionVisited = mTargetLastKnownPositionVisited; - Other.mTargetLastKnownTime = mTargetLastKnownTime; - Other.mTargetVisableStartTime = mTargetVisableStartTime; - Other.mTargetVisableStopTime = mTargetVisableStopTime; - Other.mTargetVisable = mTargetVisable; - Other.mTargetVisablePosition = mTargetVisablePosition; + if (!Other.mTarget && mTarget) { + Other.mTarget = mTarget; + Other.mTargetIndex = mTargetIndex; + Other.mTargetLastKnownPosition = mTargetLastKnownPosition; + Other.mTargetLastKnownPositionVisited = mTargetLastKnownPositionVisited; + Other.mTargetLastKnownTime = mTargetLastKnownTime; + Other.mTargetVisableStartTime = mTargetVisableStartTime; + Other.mTargetVisableStopTime = mTargetVisableStopTime; + Other.mTargetVisable = mTargetVisable; + Other.mTargetVisablePosition = mTargetVisablePosition; Other.LeaderIssueAndUpdateOrders(mState); } } @@ -1017,153 +826,101 @@ class CTroop //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - gentity_t* TrackingTarget() - { - return mTarget; - } + gentity_t *TrackingTarget() { return mTarget; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - gentity_t* TroopLeader() - { - return mActors[0]; - } + gentity_t *TroopLeader() { return mActors[0]; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - int TimeSinceSeenTarget() - { - return (level.time - mTargetVisableStopTime); - } + int TimeSinceSeenTarget() { return (level.time - mTargetVisableStopTime); } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - CVec3& TargetVisablePosition() - { - return mTargetVisablePosition; - } - + CVec3 &TargetVisablePosition() { return mTargetVisablePosition; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - float FormSpacingFwd() - { - return mFormSpacingFwd; - } + float FormSpacingFwd() { return mFormSpacingFwd; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - gentity_t* TooCloseToTroopMember(gentity_t* actor) - { - for (int i=0; iresultspeed<10.0f) - // { - // continue; - // } + // if (mActors[i]->resultspeed<10.0f) + // { + // continue; + // } - if (i==0) - { - if (Distance(actor->currentOrigin, mActors[i]->currentOrigin)<(mFormSpacingFwd*0.5f)) - { + if (i == 0) { + if (Distance(actor->currentOrigin, mActors[i]->currentOrigin) < (mFormSpacingFwd * 0.5f)) { return mActors[i]; } - } - else - { - if (Distance(actor->currentOrigin, mActors[i]->currentOrigin)<(mFormSpacingFwd*0.5f)) - { + } else { + if (Distance(actor->currentOrigin, mActors[i]->currentOrigin) < (mFormSpacingFwd * 0.5f)) { return mActors[i]; } } } - assert("Somehow this actor is not actually in the troop..."==0); + assert("Somehow this actor is not actually in the troop..." == 0); return 0; } }; -typedef ratl::handle_pool_vs TTroopPool; -TTroopPool mTroops; - - - - - +typedef ratl::handle_pool_vs TTroopPool; +TTroopPool mTroops; //////////////////////////////////////////////////////////////////////////////////////// // Erase All Data, Set To Default Vals Before Entities Spawn //////////////////////////////////////////////////////////////////////////////////////// -void Troop_Reset() -{ - mTroops.clear(); -} +void Troop_Reset() { mTroops.clear(); } //////////////////////////////////////////////////////////////////////////////////////// // Entities Have Just Spawned, Initialize //////////////////////////////////////////////////////////////////////////////////////// -void Troop_Initialize() -{ -} +void Troop_Initialize() {} //////////////////////////////////////////////////////////////////////////////////////// // Global Update Of All Troops //////////////////////////////////////////////////////////////////////////////////////// -void Troop_Update() -{ - for (TTroopPool::iterator i=mTroops.begin(); i!=mTroops.end(); ++i) - { +void Troop_Update() { + for (TTroopPool::iterator i = mTroops.begin(); i != mTroops.end(); ++i) { i->Update(); } } - //////////////////////////////////////////////////////////////////////////////////////// // Erase All Data, Set To Default Vals Before Entities Spawn //////////////////////////////////////////////////////////////////////////////////////// -void Trooper_UpdateTroop(gentity_t* actor) -{ +void Trooper_UpdateTroop(gentity_t *actor) { // Try To Join A Troop //--------------------- - if (!actor->NPC->troop) - { - float curDist = 0; - float closestDist = 0; - TTroopPool::iterator closestTroop = mTroops.end(); - trace_t trace; - - for (TTroopPool::iterator iTroop=mTroops.begin(); iTroop!=mTroops.end(); ++iTroop) - { - if (iTroop->Team()==actor->client->playerTeam) - { + if (!actor->NPC->troop) { + float curDist = 0; + float closestDist = 0; + TTroopPool::iterator closestTroop = mTroops.end(); + trace_t trace; + + for (TTroopPool::iterator iTroop = mTroops.begin(); iTroop != mTroops.end(); ++iTroop) { + if (iTroop->Team() == actor->client->playerTeam) { curDist = iTroop->DistanceSq(actor); - if (curDistcurrentOrigin, - actor->mins, - actor->maxs, - iTroop->TroopLeader()->currentOrigin, - actor->s.number, - CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, - (EG2_Collision)0, - 0); - - if (!trace.allsolid && - !trace.startsolid && - (trace.fraction>=1.0f || trace.entityNum==iTroop->TroopLeader()->s.number)) - { + gi.trace(&trace, actor->currentOrigin, actor->mins, actor->maxs, iTroop->TroopLeader()->currentOrigin, actor->s.number, + CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, (EG2_Collision)0, 0); + + if (!trace.allsolid && !trace.startsolid && (trace.fraction >= 1.0f || trace.entityNum == iTroop->TroopLeader()->s.number)) { closestDist = curDist; closestTroop = iTroop; } @@ -1173,16 +930,14 @@ void Trooper_UpdateTroop(gentity_t* actor) // If Found, Add The Actor To It //-------------------------------- - if (closestTroop!=mTroops.end()) - { + if (closestTroop != mTroops.end()) { closestTroop->AddActor(actor); } // If We Couldn't Find One, Create A New Troop //--------------------------------------------- - else if (!mTroops.full()) - { - int nTroopHandle = mTroops.alloc(); + else if (!mTroops.full()) { + int nTroopHandle = mTroops.alloc(); mTroops[nTroopHandle].Initialize(nTroopHandle); mTroops[nTroopHandle].AddActor(actor); } @@ -1190,27 +945,22 @@ void Trooper_UpdateTroop(gentity_t* actor) // If This Is A Leader, Then He Is Responsible For Merging Troops //---------------------------------------------------------------- - else if (actor->client->leader==actor) - { - float curDist = 0; - float closestDist = 0; - TTroopPool::iterator closestTroop = mTroops.end(); + else if (actor->client->leader == actor) { + float curDist = 0; + float closestDist = 0; + TTroopPool::iterator closestTroop = mTroops.end(); - for (TTroopPool::iterator iTroop=mTroops.begin(); iTroop!=mTroops.end(); ++iTroop) - { + for (TTroopPool::iterator iTroop = mTroops.begin(); iTroop != mTroops.end(); ++iTroop) { curDist = iTroop->DistanceSq(actor); - if ((curDistNPC->troop)) - { + if ((curDist < MAX_TROOP_MERGE_DIST2) && (!closestDist || curDist < closestDist) && + (mTroops.index_to_handle(iTroop.index()) != actor->NPC->troop)) { closestDist = curDist; closestTroop = iTroop; } } - if (closestTroop!=mTroops.end()) - { - int oldTroopNum = actor->NPC->troop; + if (closestTroop != mTroops.end()) { + int oldTroopNum = actor->NPC->troop; mTroops[oldTroopNum].MergeInto(*closestTroop); mTroops.free(oldTroopNum); } @@ -1220,19 +970,15 @@ void Trooper_UpdateTroop(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Trooper_UpdateSmackAway(gentity_t* actor, gentity_t* target) -{ - if (actor->client->ps.legsAnim==BOTH_MELEE1) - { - if (TIMER_Done(actor, "Trooper_SmackAway")) - { - CVec3 ActorPos(actor->currentOrigin); - CVec3 ActorToTgt(target->currentOrigin); - ActorToTgt -= ActorPos; - float ActorToTgtDist = ActorToTgt.SafeNorm(); - - if (ActorToTgtDist<100.0f) - { +bool Trooper_UpdateSmackAway(gentity_t *actor, gentity_t *target) { + if (actor->client->ps.legsAnim == BOTH_MELEE1) { + if (TIMER_Done(actor, "Trooper_SmackAway")) { + CVec3 ActorPos(actor->currentOrigin); + CVec3 ActorToTgt(target->currentOrigin); + ActorToTgt -= ActorPos; + float ActorToTgtDist = ActorToTgt.SafeNorm(); + + if (ActorToTgtDist < 100.0f) { G_Throw(target, ActorToTgt.v, 200.0f); } } @@ -1241,39 +987,30 @@ bool Trooper_UpdateSmackAway(gentity_t* actor, gentity_t* target) return false; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Trooper_SmackAway(gentity_t* actor, gentity_t* target) -{ +void Trooper_SmackAway(gentity_t *actor, gentity_t *target) { assert(actor && actor->NPC); - if (actor->client->ps.legsAnim!=BOTH_MELEE1) - { - NPC_SetAnim(actor, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - TIMER_Set(actor, "Trooper_SmackAway", actor->client->ps.torsoAnimTimer/4.0f); + if (actor->client->ps.legsAnim != BOTH_MELEE1) { + NPC_SetAnim(actor, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(actor, "Trooper_SmackAway", actor->client->ps.torsoAnimTimer / 4.0f); } } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool Trooper_Kneeling(gentity_t* actor) -{ - return (actor->NPC->aiFlags&NPCAI_KNEEL || actor->client->ps.legsAnim==BOTH_STAND_TO_KNEEL); -} +bool Trooper_Kneeling(gentity_t *actor) { return (actor->NPC->aiFlags & NPCAI_KNEEL || actor->client->ps.legsAnim == BOTH_STAND_TO_KNEEL); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Trooper_KneelDown(gentity_t* actor) -{ +void Trooper_KneelDown(gentity_t *actor) { assert(actor && actor->NPC); - if (!Trooper_Kneeling(actor) && level.time>actor->NPC->kneelTime) - { - NPC_SetAnim(actor, SETANIM_BOTH, BOTH_STAND_TO_KNEEL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - actor->NPC->aiFlags |= NPCAI_KNEEL; + if (!Trooper_Kneeling(actor) && level.time > actor->NPC->kneelTime) { + NPC_SetAnim(actor, SETANIM_BOTH, BOTH_STAND_TO_KNEEL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + actor->NPC->aiFlags |= NPCAI_KNEEL; actor->NPC->kneelTime = level.time + Q_irand(3000, 6000); } } @@ -1281,13 +1018,11 @@ void Trooper_KneelDown(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Trooper_StandUp(gentity_t* actor, bool always=false) -{ +void Trooper_StandUp(gentity_t *actor, bool always = false) { assert(actor && actor->NPC); - if (Trooper_Kneeling(actor) && (always || level.time>actor->NPC->kneelTime)) - { + if (Trooper_Kneeling(actor) && (always || level.time > actor->NPC->kneelTime)) { actor->NPC->aiFlags &= ~NPCAI_KNEEL; - NPC_SetAnim(actor, SETANIM_BOTH, BOTH_KNEEL_TO_STAND, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(actor, SETANIM_BOTH, BOTH_KNEEL_TO_STAND, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); actor->NPC->kneelTime = level.time + Q_irand(3000, 6000); } } @@ -1295,33 +1030,28 @@ void Trooper_StandUp(gentity_t* actor, bool always=false) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -int Trooper_CanHitTarget(gentity_t* actor, gentity_t* target, CTroop& troop, float& MuzzleToTargetDistance, CVec3& MuzzleToTarget) -{ - trace_t tr; - CVec3 MuzzlePoint(actor->currentOrigin); - CalcEntitySpot(actor, SPOT_WEAPON, MuzzlePoint.v); +int Trooper_CanHitTarget(gentity_t *actor, gentity_t *target, CTroop &troop, float &MuzzleToTargetDistance, CVec3 &MuzzleToTarget) { + trace_t tr; + CVec3 MuzzlePoint(actor->currentOrigin); + CalcEntitySpot(actor, SPOT_WEAPON, MuzzlePoint.v); - MuzzleToTarget = troop.TargetVisablePosition(); - MuzzleToTarget -= MuzzlePoint; - MuzzleToTargetDistance = MuzzleToTarget.SafeNorm(); + MuzzleToTarget = troop.TargetVisablePosition(); + MuzzleToTarget -= MuzzlePoint; + MuzzleToTargetDistance = MuzzleToTarget.SafeNorm(); - - CVec3 MuzzleDirection(actor->currentAngles); - MuzzleDirection.AngToVec(); + CVec3 MuzzleDirection(actor->currentAngles); + MuzzleDirection.AngToVec(); // Aiming In The Right Direction? //-------------------------------- - if (MuzzleDirection.Dot(MuzzleToTarget)>0.95) - { + if (MuzzleDirection.Dot(MuzzleToTarget) > 0.95) { // Clear Line Of Sight To Target? //-------------------------------- gi.trace(&tr, MuzzlePoint.v, NULL, NULL, troop.TargetVisablePosition().v, actor->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if (tr.startsolid || tr.allsolid) - { + if (tr.startsolid || tr.allsolid) { return ENTITYNUM_NONE; } - if (tr.entityNum==target->s.number || tr.fraction>0.9f) - { + if (tr.entityNum == target->s.number || tr.fraction > 0.9f) { return target->s.number; } return tr.entityNum; @@ -1329,49 +1059,40 @@ int Trooper_CanHitTarget(gentity_t* actor, gentity_t* target, CTroop& troop, f return ENTITYNUM_NONE; } - //////////////////////////////////////////////////////////////////////////////////////// // Run The Per Trooper Update //////////////////////////////////////////////////////////////////////////////////////// -void Trooper_Think(gentity_t* actor) -{ - gentity_t* target = (actor->NPC->troop)?(mTroops[actor->NPC->troop].TrackingTarget()):(0); - if (target) - { +void Trooper_Think(gentity_t *actor) { + gentity_t *target = (actor->NPC->troop) ? (mTroops[actor->NPC->troop].TrackingTarget()) : (0); + if (target) { G_SetEnemy(actor, target); - CTroop& troop = mTroops[actor->NPC->troop]; - bool AtPos = STEER::Reached(actor, actor->pos1, 10.0f); - int traceTgt = ENTITYNUM_NONE; - bool traced = false; - bool inSmackAway = false; + CTroop &troop = mTroops[actor->NPC->troop]; + bool AtPos = STEER::Reached(actor, actor->pos1, 10.0f); + int traceTgt = ENTITYNUM_NONE; + bool traced = false; + bool inSmackAway = false; - float MuzzleToTargetDistance = 0.0f; - CVec3 MuzzleToTarget; + float MuzzleToTargetDistance = 0.0f; + CVec3 MuzzleToTarget; - if (actor->NPC->combatPoint!=-1) - { - traceTgt = Trooper_CanHitTarget(actor, target, troop, MuzzleToTargetDistance, MuzzleToTarget); - traced = true; - if (traceTgt==target->s.number) - { + if (actor->NPC->combatPoint != -1) { + traceTgt = Trooper_CanHitTarget(actor, target, troop, MuzzleToTargetDistance, MuzzleToTarget); + traced = true; + if (traceTgt == target->s.number) { AtPos = true; } } - // Smack! //------- - if (Trooper_UpdateSmackAway(actor, target)) - { - traced = true; - AtPos = true; + if (Trooper_UpdateSmackAway(actor, target)) { + traced = true; + AtPos = true; inSmackAway = true; } - - if (false) - { + if (false) { CG_DrawEdge(actor->currentOrigin, actor->pos1, EDGE_IMPACT_SAFE); } @@ -1379,144 +1100,111 @@ void Trooper_Think(gentity_t* actor) //----------------------- STEER::Activate(actor); { - gentity_t* fleeFrom = troop.TooCloseToTroopMember(actor); + gentity_t *fleeFrom = troop.TooCloseToTroopMember(actor); // If Too Close To The Leader, Get Out Of His Way //------------------------------------------------ - if (fleeFrom) - { + if (fleeFrom) { STEER::Flee(actor, fleeFrom->currentOrigin, 1.0f); AtPos = false; } - // If In Position, Stop Moving //----------------------------- - if (AtPos) - { - NAV::ClearPath(actor); + if (AtPos) { + NAV::ClearPath(actor); STEER::Stop(actor); } // Otherwise, Try To Get To Position //----------------------------------- - else - { + else { Trooper_StandUp(actor, true); // If Close Enough, Persue Our Target Directly //--------------------------------------------- - bool moveSuccess = STEER::GoTo(NPC, actor->pos1, 10.0f, false); + bool moveSuccess = STEER::GoTo(NPC, actor->pos1, 10.0f, false); // Otherwise //----------- - if (!moveSuccess) - { + if (!moveSuccess) { moveSuccess = NAV::GoTo(NPC, actor->pos1); } // If No Way To Get To Position, Stay Here //----------------------------------------- - if (!moveSuccess || (level.time - actor->lastMoveTime)>4000) - { + if (!moveSuccess || (level.time - actor->lastMoveTime) > 4000) { AtPos = true; } } } STEER::DeActivate(actor, &ucmd); - - - // If There And Target Was Recently Visable //------------------------------------------ - if (AtPos && (troop.TimeSinceSeenTarget()<1500)) - { - if (!traced) - { + if (AtPos && (troop.TimeSinceSeenTarget() < 1500)) { + if (!traced) { traceTgt = Trooper_CanHitTarget(actor, target, troop, MuzzleToTargetDistance, MuzzleToTarget); } // Shoot! //-------- - if (traceTgt==target->s.number) - { + if (traceTgt == target->s.number) { WeaponThink(qtrue); - } - else if (!inSmackAway) - { + } else if (!inSmackAway) { // Otherwise, If Kneeling, Get Up! //--------------------------------- - if (Trooper_Kneeling(actor)) - { + if (Trooper_Kneeling(actor)) { Trooper_StandUp(actor); } // If The Enemy Is Close Enough, Smack Him Away //---------------------------------------------- - else if (MuzzleToTargetDistance<40.0f) - { + else if (MuzzleToTargetDistance < 40.0f) { Trooper_SmackAway(actor, target); } // If We Would Have It A Friend, Ask Him To Kneel //------------------------------------------------ - else if (traceTgt!=ENTITYNUM_NONE && - traceTgt!=ENTITYNUM_WORLD && - g_entities[traceTgt].client && - g_entities[traceTgt].NPC && - g_entities[traceTgt].client->playerTeam==actor->client->playerTeam && - NPC_IsTrooper(&g_entities[traceTgt]) && - g_entities[traceTgt].resultspeed<1.0f && - !(g_entities[traceTgt].NPC->aiFlags & NPCAI_KNEEL)) - { + else if (traceTgt != ENTITYNUM_NONE && traceTgt != ENTITYNUM_WORLD && g_entities[traceTgt].client && g_entities[traceTgt].NPC && + g_entities[traceTgt].client->playerTeam == actor->client->playerTeam && NPC_IsTrooper(&g_entities[traceTgt]) && + g_entities[traceTgt].resultspeed < 1.0f && !(g_entities[traceTgt].NPC->aiFlags & NPCAI_KNEEL)) { Trooper_KneelDown(&g_entities[traceTgt]); } } - // Convert To Angles And Set That As Our Desired Look Direction //-------------------------------------------------------------- - if (MuzzleToTargetDistance>100) - { - MuzzleToTarget.VecToAng(); - - NPCInfo->desiredYaw = MuzzleToTarget[YAW]; - NPCInfo->desiredPitch = MuzzleToTarget[PITCH]; - } - else - { - MuzzleToTarget = troop.TargetVisablePosition(); - MuzzleToTarget.v[2] -= 20.0f; // Aim Lower - MuzzleToTarget -= actor->currentOrigin; + if (MuzzleToTargetDistance > 100) { + MuzzleToTarget.VecToAng(); + + NPCInfo->desiredYaw = MuzzleToTarget[YAW]; + NPCInfo->desiredPitch = MuzzleToTarget[PITCH]; + } else { + MuzzleToTarget = troop.TargetVisablePosition(); + MuzzleToTarget.v[2] -= 20.0f; // Aim Lower + MuzzleToTarget -= actor->currentOrigin; MuzzleToTarget.SafeNorm(); - MuzzleToTarget.VecToAng(); + MuzzleToTarget.VecToAng(); - NPCInfo->desiredYaw = MuzzleToTarget[YAW]; - NPCInfo->desiredPitch = MuzzleToTarget[PITCH]; + NPCInfo->desiredYaw = MuzzleToTarget[YAW]; + NPCInfo->desiredPitch = MuzzleToTarget[PITCH]; } } - NPC_UpdateFiringAngles( qtrue, qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateFiringAngles(qtrue, qtrue); + NPC_UpdateAngles(qtrue, qtrue); - if (Trooper_Kneeling(actor)) - { - ucmd.upmove = -127; // Set Crouch Height + if (Trooper_Kneeling(actor)) { + ucmd.upmove = -127; // Set Crouch Height } } - - - - else - { + else { NPC_BSST_Default(); } } - - //////////////////////////////////////////////////////////////////////////////////////// /* ------------------------- @@ -1524,11 +1212,9 @@ NPC_BehaviorSet_Trooper ------------------------- */ //////////////////////////////////////////////////////////////////////////////////////// -void NPC_BehaviorSet_Trooper( int bState ) -{ +void NPC_BehaviorSet_Trooper(int bState) { Trooper_UpdateTroop(NPC); - switch( bState ) - { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1554,26 +1240,17 @@ void NPC_BehaviorSet_Trooper( int bState ) //////////////////////////////////////////////////////////////////////////////////////// // IsTrooper - return true if you want a given actor to use trooper AI //////////////////////////////////////////////////////////////////////////////////////// -bool NPC_IsTrooper(gentity_t* actor) -{ - return ( - actor && - actor->NPC && - actor->s.weapon && - !!(actor->NPC->scriptFlags&SCF_NO_GROUPS)// && -// !(actor->NPC->scriptFlags&SCF_CHASE_ENEMIES) - ); +bool NPC_IsTrooper(gentity_t *actor) { + return (actor && actor->NPC && actor->s.weapon && !!(actor->NPC->scriptFlags & SCF_NO_GROUPS) // && + // !(actor->NPC->scriptFlags&SCF_CHASE_ENEMIES) + ); } -void NPC_LeaveTroop(gentity_t* actor) -{ +void NPC_LeaveTroop(gentity_t *actor) { assert(actor->NPC->troop); int wasInTroop = actor->NPC->troop; mTroops[actor->NPC->troop].RemoveActor(actor); - if (mTroops[wasInTroop].Empty()) - { + if (mTroops[wasInTroop].Empty()) { mTroops.free(wasInTroop); } } - - diff --git a/code/game/AI_Howler.cpp b/code/game/AI_Howler.cpp index e3a6d664be..79dd8e0974 100644 --- a/code/game/AI_Howler.cpp +++ b/code/game/AI_Howler.cpp @@ -24,126 +24,103 @@ along with this program; if not, see . #include "../cgame/cg_camera.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) - -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) - -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 -#define LSTATE_FLEE 2 -#define LSTATE_BERZERK 3 - -#define HOWLER_RETREAT_DIST 300.0f -#define HOWLER_PANIC_HEALTH 10 - -extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ); -extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean NAV_DirSafe( gentity_t *self, vec3_t dir, float dist ); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ); -extern int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); - -static void Howler_Attack( float enemyDist, qboolean howl = qfalse ); +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) + +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) + +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 +#define LSTATE_FLEE 2 +#define LSTATE_BERZERK 3 + +#define HOWLER_RETREAT_DIST 300.0f +#define HOWLER_PANIC_HEALTH 10 + +extern void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir); +extern void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean NAV_DirSafe(gentity_t *self, vec3_t dir, float dist); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern float NPC_EntRangeFromBolt(gentity_t *targEnt, int boltIndex); +extern int NPC_GetEntsNearBolt(gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); + +static void Howler_Attack(float enemyDist, qboolean howl = qfalse); /* ------------------------- NPC_Howler_Precache ------------------------- */ -void NPC_Howler_Precache( void ) -{ +void NPC_Howler_Precache(void) { int i; - //G_SoundIndex( "sound/chars/howler/howl.mp3" ); - G_EffectIndex( "howler/sonic" ); - G_SoundIndex( "sound/chars/howler/howl.mp3" ); - for ( i = 1; i < 3; i++ ) - { - G_SoundIndex( va( "sound/chars/howler/idle_hiss%d.mp3", i ) ); + // G_SoundIndex( "sound/chars/howler/howl.mp3" ); + G_EffectIndex("howler/sonic"); + G_SoundIndex("sound/chars/howler/howl.mp3"); + for (i = 1; i < 3; i++) { + G_SoundIndex(va("sound/chars/howler/idle_hiss%d.mp3", i)); } - for ( i = 1; i < 6; i++ ) - { - G_SoundIndex( va( "sound/chars/howler/howl_talk%d.mp3", i ) ); - G_SoundIndex( va( "sound/chars/howler/howl_yell%d.mp3", i ) ); + for (i = 1; i < 6; i++) { + G_SoundIndex(va("sound/chars/howler/howl_talk%d.mp3", i)); + G_SoundIndex(va("sound/chars/howler/howl_yell%d.mp3", i)); } } -void Howler_ClearTimers( gentity_t *self ) -{ - //clear all my timers - TIMER_Set( self, "flee", -level.time ); - TIMER_Set( self, "retreating", -level.time ); - TIMER_Set( self, "standing", -level.time ); - TIMER_Set( self, "walking", -level.time ); - TIMER_Set( self, "running", -level.time ); - TIMER_Set( self, "aggressionDecay", -level.time ); - TIMER_Set( self, "speaking", -level.time ); +void Howler_ClearTimers(gentity_t *self) { + // clear all my timers + TIMER_Set(self, "flee", -level.time); + TIMER_Set(self, "retreating", -level.time); + TIMER_Set(self, "standing", -level.time); + TIMER_Set(self, "walking", -level.time); + TIMER_Set(self, "running", -level.time); + TIMER_Set(self, "aggressionDecay", -level.time); + TIMER_Set(self, "speaking", -level.time); } -static qboolean NPC_Howler_Move( int randomJumpChance = 0 ) -{ - if ( !TIMER_Done( NPC, "standing" ) ) - {//standing around +static qboolean NPC_Howler_Move(int randomJumpChance = 0) { + if (!TIMER_Done(NPC, "standing")) { // standing around return qfalse; } - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//in air, don't do anything + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // in air, don't do anything return qfalse; } - if ( (!NPC->enemy&&TIMER_Done( NPC, "running" )) || !TIMER_Done( NPC, "walking" ) ) - { + if ((!NPC->enemy && TIMER_Done(NPC, "running")) || !TIMER_Done(NPC, "walking")) { ucmd.buttons |= BUTTON_WALKING; } - if ( (!randomJumpChance||Q_irand( 0, randomJumpChance )) - && NPC_MoveToGoal( qtrue ) ) - { - if ( VectorCompare( NPC->client->ps.moveDir, vec3_origin ) - || !NPC->client->ps.speed ) - {//uh.... wtf? Got there? - if ( NPCInfo->goalEntity ) - { - NPC_FaceEntity( NPCInfo->goalEntity, qfalse ); - } - else - { - NPC_UpdateAngles( qfalse, qtrue ); + if ((!randomJumpChance || Q_irand(0, randomJumpChance)) && NPC_MoveToGoal(qtrue)) { + if (VectorCompare(NPC->client->ps.moveDir, vec3_origin) || !NPC->client->ps.speed) { // uh.... wtf? Got there? + if (NPCInfo->goalEntity) { + NPC_FaceEntity(NPCInfo->goalEntity, qfalse); + } else { + NPC_UpdateAngles(qfalse, qtrue); } return qtrue; } - //TEMP: don't want to strafe - VectorClear( NPC->client->ps.moveDir ); + // TEMP: don't want to strafe + VectorClear(NPC->client->ps.moveDir); ucmd.rightmove = 0.0f; -// Com_Printf( "Howler moving %d\n",ucmd.forwardmove ); - //if backing up, go slow... - if ( ucmd.forwardmove < 0.0f ) - { + // Com_Printf( "Howler moving %d\n",ucmd.forwardmove ); + // if backing up, go slow... + if (ucmd.forwardmove < 0.0f) { ucmd.buttons |= BUTTON_WALKING; - //if ( NPC->client->ps.speed > NPCInfo->stats.walkSpeed ) - {//don't walk faster than I'm allowed to + // if ( NPC->client->ps.speed > NPCInfo->stats.walkSpeed ) + { // don't walk faster than I'm allowed to NPC->client->ps.speed = NPCInfo->stats.walkSpeed; } - } - else - { - if ( (ucmd.buttons&BUTTON_WALKING) ) - { + } else { + if ((ucmd.buttons & BUTTON_WALKING)) { NPC->client->ps.speed = NPCInfo->stats.walkSpeed; - } - else - { + } else { NPC->client->ps.speed = NPCInfo->stats.runSpeed; } } NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; - NPC_UpdateAngles( qfalse, qtrue ); - } - else if ( NPCInfo->goalEntity ) - {//couldn't get where we wanted to go, try to jump there - NPC_FaceEntity( NPCInfo->goalEntity, qfalse ); - NPC_TryJump( NPCInfo->goalEntity, 400.0f, -256.0f ); + NPC_UpdateAngles(qfalse, qtrue); + } else if (NPCInfo->goalEntity) { // couldn't get where we wanted to go, try to jump there + NPC_FaceEntity(NPCInfo->goalEntity, qfalse); + NPC_TryJump(NPCInfo->goalEntity, 400.0f, -256.0f); } return qtrue; } @@ -152,41 +129,34 @@ static qboolean NPC_Howler_Move( int randomJumpChance = 0 ) Howler_Idle ------------------------- */ -static void Howler_Idle( void ) -{ -} - +static void Howler_Idle(void) {} /* ------------------------- Howler_Patrol ------------------------- */ -static void Howler_Patrol( void ) -{ +static void Howler_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { - NPC_Howler_Move( 100 ); + // If we have somewhere to go, then do that + if (UpdateGoal()) { + NPC_Howler_Move(100); } vec3_t dif; - VectorSubtract( g_entities[0].currentOrigin, NPC->currentOrigin, dif ); + VectorSubtract(g_entities[0].currentOrigin, NPC->currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Howler_Idle(); return; } - Howler_Attack( 0.0f, qtrue ); + Howler_Attack(0.0f, qtrue); } /* @@ -194,138 +164,107 @@ static void Howler_Patrol( void ) Howler_Move ------------------------- */ -static qboolean Howler_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +static qboolean Howler_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - return NPC_Howler_Move( 30 ); + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + return NPC_Howler_Move(30); } return qfalse; } //--------------------------------------------------------- -static void Howler_TryDamage( int damage, qboolean tongue, qboolean knockdown ) -{ - vec3_t start, end, dir; - trace_t tr; - - if ( tongue ) - { - G_GetBoltPosition( NPC, NPC->genericBolt1, start ); - G_GetBoltPosition( NPC, NPC->genericBolt2, end ); - VectorSubtract( end, start, dir ); - float dist = VectorNormalize( dir ); - VectorMA( start, dist+16, dir, end ); - } - else - { - VectorCopy( NPC->currentOrigin, start ); - AngleVectors( NPC->currentAngles, dir, NULL, NULL ); - VectorMA( start, MIN_DISTANCE*2, dir, end ); +static void Howler_TryDamage(int damage, qboolean tongue, qboolean knockdown) { + vec3_t start, end, dir; + trace_t tr; + + if (tongue) { + G_GetBoltPosition(NPC, NPC->genericBolt1, start); + G_GetBoltPosition(NPC, NPC->genericBolt2, end); + VectorSubtract(end, start, dir); + float dist = VectorNormalize(dir); + VectorMA(start, dist + 16, dir, end); + } else { + VectorCopy(NPC->currentOrigin, start); + AngleVectors(NPC->currentAngles, dir, NULL, NULL); + VectorMA(start, MIN_DISTANCE * 2, dir, end); } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { + if (d_saberCombat->integer > 1) { G_DebugLine(start, end, 1000, 0x000000ff, qtrue); } #endif // Should probably trace from the mouth, but, ah well. - gi.trace( &tr, start, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, start, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( tr.entityNum < ENTITYNUM_WORLD ) - {//hit *something* + if (tr.entityNum < ENTITYNUM_WORLD) { // hit *something* gentity_t *victim = &g_entities[tr.entityNum]; - if ( !victim->client - || victim->client->NPC_class != CLASS_HOWLER ) - {//not another howler - - if ( knockdown && victim->client ) - {//only do damage if victim isn't knocked down. If he isn't, knock him down - if ( PM_InKnockDown( &victim->client->ps ) ) - { + if (!victim->client || victim->client->NPC_class != CLASS_HOWLER) { // not another howler + + if (knockdown && victim->client) { // only do damage if victim isn't knocked down. If he isn't, knock him down + if (PM_InKnockDown(&victim->client->ps)) { return; } } - //FIXME: some sort of damage effect (claws and tongue are cutting you... blood?) - G_Damage( victim, NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - if ( knockdown && victim->health > 0 ) - {//victim still alive - G_Knockdown( victim, NPC, NPC->client->ps.velocity, 500, qfalse ); + // FIXME: some sort of damage effect (claws and tongue are cutting you... blood?) + G_Damage(victim, NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + if (knockdown && victim->health > 0) { // victim still alive + G_Knockdown(victim, NPC, NPC->client->ps.velocity, 500, qfalse); } } } } -static void Howler_Howl( void ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = (NPC->spawnflags&1)?256:128; - const float halfRadSquared = ((radius/2)*(radius/2)); - const float radiusSquared = (radius*radius); - float distSq; - int i; - vec3_t boltOrg; +static void Howler_Howl(void) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = (NPC->spawnflags & 1) ? 256 : 128; + const float halfRadSquared = ((radius / 2) * (radius / 2)); + const float radiusSquared = (radius * radius); + float distSq; + int i; + vec3_t boltOrg; - AddSoundEvent( NPC, NPC->currentOrigin, 512, AEL_DANGER, qfalse, qtrue ); + AddSoundEvent(NPC, NPC->currentOrigin, 512, AEL_DANGER, qfalse, qtrue); - numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, NPC->handLBolt, boltOrg ); + numEnts = NPC_GetEntsNearBolt(radiusEnts, radius, NPC->handLBolt, boltOrg); - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the rancor ent + if (radiusEnts[i] == NPC) { // Skip the rancor ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client + if (radiusEnts[i]->client == NULL) { // must be a client continue; } - if ( radiusEnts[i]->client->NPC_class == CLASS_HOWLER ) - {//other howlers immune + if (radiusEnts[i]->client->NPC_class == CLASS_HOWLER) { // other howlers immune continue; } - distSq = DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ); - if ( distSq <= radiusSquared ) - { - if ( distSq < halfRadSquared ) - {//close enough to do damage, too - if ( Q_irand( 0, g_spskill->integer ) ) - {//does no damage on easy, does 1 point every other frame on medium, more often on hard - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, NPC->currentOrigin, 1, DAMAGE_NO_KNOCKBACK, MOD_IMPACT ); + distSq = DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg); + if (distSq <= radiusSquared) { + if (distSq < halfRadSquared) { // close enough to do damage, too + if (Q_irand(0, g_spskill->integer)) { // does no damage on easy, does 1 point every other frame on medium, more often on hard + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, NPC->currentOrigin, 1, DAMAGE_NO_KNOCKBACK, MOD_IMPACT); } } - if ( radiusEnts[i]->health > 0 - && radiusEnts[i]->client - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST - && !PM_InKnockDown( &radiusEnts[i]->client->ps ) ) - { - if ( PM_HasAnimation( radiusEnts[i], BOTH_SONICPAIN_START ) ) - { - if ( radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_START - && radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_HOLD ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_START, SETANIM_FLAG_NORMAL ); - NPC_SetAnim( radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (radiusEnts[i]->health > 0 && radiusEnts[i]->client && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && + radiusEnts[i]->client->NPC_class != CLASS_ATST && !PM_InKnockDown(&radiusEnts[i]->client->ps)) { + if (PM_HasAnimation(radiusEnts[i], BOTH_SONICPAIN_START)) { + if (radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_START && radiusEnts[i]->client->ps.torsoAnim != BOTH_SONICPAIN_HOLD) { + NPC_SetAnim(radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_START, SETANIM_FLAG_NORMAL); + NPC_SetAnim(radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); radiusEnts[i]->client->ps.torsoAnimTimer += 100; radiusEnts[i]->client->ps.weaponTime = radiusEnts[i]->client->ps.torsoAnimTimer; - } - else if ( radiusEnts[i]->client->ps.torsoAnimTimer <= 100 ) - {//at the end of the sonic pain start or hold anim - NPC_SetAnim( radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_NORMAL ); - NPC_SetAnim( radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (radiusEnts[i]->client->ps.torsoAnimTimer <= 100) { // at the end of the sonic pain start or hold anim + NPC_SetAnim(radiusEnts[i], SETANIM_LEGS, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_NORMAL); + NPC_SetAnim(radiusEnts[i], SETANIM_TORSO, BOTH_SONICPAIN_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); radiusEnts[i]->client->ps.torsoAnimTimer += 100; radiusEnts[i]->client->ps.weaponTime = radiusEnts[i]->client->ps.torsoAnimTimer; } @@ -342,181 +281,146 @@ static void Howler_Howl( void ) } } - float playerDist = NPC_EntRangeFromBolt( player, NPC->genericBolt1 ); - if ( playerDist < 256.0f ) - { - CGCam_Shake( 1.0f*playerDist/128.0f, 200 ); + float playerDist = NPC_EntRangeFromBolt(player, NPC->genericBolt1); + if (playerDist < 256.0f) { + CGCam_Shake(1.0f * playerDist / 128.0f, 200); } } //------------------------------ -static void Howler_Attack( float enemyDist, qboolean howl ) -{ - int dmg = (NPCInfo->localState==LSTATE_BERZERK)?5:2; +static void Howler_Attack(float enemyDist, qboolean howl) { + int dmg = (NPCInfo->localState == LSTATE_BERZERK) ? 5 : 2; - if ( !TIMER_Exists( NPC, "attacking" )) - { + if (!TIMER_Exists(NPC, "attacking")) { int attackAnim = BOTH_GESTURE1; // Going to do an attack - if ( NPC->enemy && NPC->enemy->client && PM_InKnockDown( &NPC->enemy->client->ps ) - && enemyDist <= MIN_DISTANCE ) - { + if (NPC->enemy && NPC->enemy->client && PM_InKnockDown(&NPC->enemy->client->ps) && enemyDist <= MIN_DISTANCE) { attackAnim = BOTH_ATTACK2; - } - else if ( !Q_irand( 0, 4 ) || howl ) - {//howl attack - //G_SoundOnEnt( NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3" ); - } - else if ( enemyDist > MIN_DISTANCE && Q_irand( 0, 1 ) ) - {//lunge attack - //jump foward - vec3_t fwd, yawAng = {0, NPC->client->ps.viewangles[YAW], 0}; - AngleVectors( yawAng, fwd, NULL, NULL ); - VectorScale( fwd, (enemyDist*3.0f), NPC->client->ps.velocity ); + } else if (!Q_irand(0, 4) || howl) { // howl attack + // G_SoundOnEnt( NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3" ); + } else if (enemyDist > MIN_DISTANCE && Q_irand(0, 1)) { // lunge attack + // jump foward + vec3_t fwd, yawAng = {0, NPC->client->ps.viewangles[YAW], 0}; + AngleVectors(yawAng, fwd, NULL, NULL); + VectorScale(fwd, (enemyDist * 3.0f), NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 200; NPC->client->ps.groundEntityNum = ENTITYNUM_NONE; attackAnim = BOTH_ATTACK1; - } - else - {//tongue attack + } else { // tongue attack attackAnim = BOTH_ATTACK2; } - NPC_SetAnim( NPC, SETANIM_BOTH, attackAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART ); - if ( NPCInfo->localState == LSTATE_BERZERK ) - {//attack again right away - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer ); - } - else - { - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand( 0, 1500 ) );//FIXME: base on skill - TIMER_Set( NPC, "standing", -level.time ); - TIMER_Set( NPC, "walking", -level.time ); - TIMER_Set( NPC, "running", NPC->client->ps.legsAnimTimer + 5000 ); + NPC_SetAnim(NPC, SETANIM_BOTH, attackAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + if (NPCInfo->localState == LSTATE_BERZERK) { // attack again right away + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer); + } else { + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(0, 1500)); // FIXME: base on skill + TIMER_Set(NPC, "standing", -level.time); + TIMER_Set(NPC, "walking", -level.time); + TIMER_Set(NPC, "running", NPC->client->ps.legsAnimTimer + 5000); } - TIMER_Set( NPC, "attack_dmg", 200 ); // level two damage + TIMER_Set(NPC, "attack_dmg", 200); // level two damage } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - switch ( NPC->client->ps.legsAnim ) - { + switch (NPC->client->ps.legsAnim) { case BOTH_ATTACK1: case BOTH_MELEE1: - if ( NPC->client->ps.legsAnimTimer > 650//more than 13 frames left - && PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 800 )//at least 16 frames into anim + if (NPC->client->ps.legsAnimTimer > 650 // more than 13 frames left + && PM_AnimLength(NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim) - NPC->client->ps.legsAnimTimer >= + 800) // at least 16 frames into anim { - Howler_TryDamage( dmg, qfalse, qfalse ); + Howler_TryDamage(dmg, qfalse, qfalse); } break; case BOTH_ATTACK2: case BOTH_MELEE2: - if ( NPC->client->ps.legsAnimTimer > 350//more than 7 frames left - && PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 550 )//at least 11 frames into anim + if (NPC->client->ps.legsAnimTimer > 350 // more than 7 frames left + && PM_AnimLength(NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim) - NPC->client->ps.legsAnimTimer >= + 550) // at least 11 frames into anim { - Howler_TryDamage( dmg, qtrue, qfalse ); + Howler_TryDamage(dmg, qtrue, qfalse); } break; - case BOTH_GESTURE1: + case BOTH_GESTURE1: { + if (NPC->client->ps.legsAnimTimer > 1800 // more than 36 frames left + && PM_AnimLength(NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim) - NPC->client->ps.legsAnimTimer >= + 950) // at least 19 frames into anim { - if ( NPC->client->ps.legsAnimTimer > 1800//more than 36 frames left - && PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim ) - NPC->client->ps.legsAnimTimer >= 950 )//at least 19 frames into anim - { - Howler_Howl(); - if ( !NPC->count ) - { - G_PlayEffect( G_EffectIndex( "howler/sonic" ), NPC->playerModel, NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 4750, qtrue ); - G_SoundOnEnt( NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3" ); - NPC->count = 1; - } + Howler_Howl(); + if (!NPC->count) { + G_PlayEffect(G_EffectIndex("howler/sonic"), NPC->playerModel, NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 4750, qtrue); + G_SoundOnEnt(NPC, CHAN_VOICE, "sound/chars/howler/howl.mp3"); + NPC->count = 1; } } - break; + } break; default: - //anims seem to get reset after a load, so just stop attacking and it will restart as needed. - TIMER_Remove( NPC, "attacking" ); + // anims seem to get reset after a load, so just stop attacking and it will restart as needed. + TIMER_Remove(NPC, "attacking"); break; } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); } //---------------------------------- -static void Howler_Combat( void ) -{ - qboolean faced = qfalse; - float distance; - qboolean advance = qfalse; - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//not on the ground - if ( NPC->client->ps.legsAnim == BOTH_JUMP1 - || NPC->client->ps.legsAnim == BOTH_INAIR1 ) - {//flying through the air with the greatest of ease, etc - Howler_TryDamage( 10, qfalse, qfalse ); - } - } - else - {//not in air, see if we should attack or advance +static void Howler_Combat(void) { + qboolean faced = qfalse; + float distance; + qboolean advance = qfalse; + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // not on the ground + if (NPC->client->ps.legsAnim == BOTH_JUMP1 || NPC->client->ps.legsAnim == BOTH_INAIR1) { // flying through the air with the greatest of ease, etc + Howler_TryDamage(10, qfalse, qfalse); + } + } else { // not in air, see if we should attack or advance // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) )//|| UpdateGoal( )) + if (!NPC_ClearLOS(NPC->enemy)) //|| UpdateGoal( )) { NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - if ( NPCInfo->localState == LSTATE_BERZERK ) - { - NPC_Howler_Move( 3 ); + if (NPCInfo->localState == LSTATE_BERZERK) { + NPC_Howler_Move(3); + } else { + NPC_Howler_Move(10); } - else - { - NPC_Howler_Move( 10 ); - } - NPC_UpdateAngles( qfalse, qtrue ); + NPC_UpdateAngles(qfalse, qtrue); return; } - distance = DistanceHorizontal( NPC->currentOrigin, NPC->enemy->currentOrigin ); + distance = DistanceHorizontal(NPC->currentOrigin, NPC->enemy->currentOrigin); - if ( NPC->enemy && NPC->enemy->client && PM_InKnockDown( &NPC->enemy->client->ps ) ) - {//get really close to knocked down enemies - advance = (qboolean)( distance > MIN_DISTANCE ? qtrue : qfalse ); - } - else - { - advance = (qboolean)( distance > MAX_DISTANCE ? qtrue : qfalse );//MIN_DISTANCE + if (NPC->enemy && NPC->enemy->client && PM_InKnockDown(&NPC->enemy->client->ps)) { // get really close to knocked down enemies + advance = (qboolean)(distance > MIN_DISTANCE ? qtrue : qfalse); + } else { + advance = (qboolean)(distance > MAX_DISTANCE ? qtrue : qfalse); // MIN_DISTANCE } - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else if (TIMER_Done(NPC, "standing")) { + faced = Howler_Move(qtrue); } - else if ( TIMER_Done( NPC, "standing" ) ) - { - faced = Howler_Move( qtrue ); - } - } - else - { - Howler_Attack( distance ); + } else { + Howler_Attack(distance); } } - if ( !faced ) - { - if ( //TIMER_Done( NPC, "standing" ) //not just standing there - //!advance //not moving - TIMER_Done( NPC, "attacking" ) )// not attacking - {//not standing around + if (!faced) { + if ( // TIMER_Done( NPC, "standing" ) //not just standing there + //! advance //not moving + TIMER_Done(NPC, "attacking")) // not attacking + { // not standing around // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); - } - else - { - NPC_UpdateAngles( qfalse, qtrue ); + NPC_FaceEnemy(qtrue); + } else { + NPC_UpdateAngles(qfalse, qtrue); } } } @@ -526,346 +430,236 @@ static void Howler_Combat( void ) NPC_Howler_Pain ------------------------- */ -void NPC_Howler_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( !self || !self->NPC ) - { +void NPC_Howler_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + if (!self || !self->NPC) { return; } - if ( self->NPC->localState != LSTATE_BERZERK )//damage >= 10 ) + if (self->NPC->localState != LSTATE_BERZERK) // damage >= 10 ) { self->NPC->stats.aggression += damage; self->NPC->localState = LSTATE_WAITING; - TIMER_Remove( self, "attacking" ); + TIMER_Remove(self, "attacking"); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - //if ( self->client->ps.legsAnim == BOTH_GESTURE1 ) - { - G_StopEffect( G_EffectIndex( "howler/sonic" ), self->playerModel, self->genericBolt1, self->s.number ); - } + // if ( self->client->ps.legsAnim == BOTH_GESTURE1 ) + { G_StopEffect(G_EffectIndex("howler/sonic"), self->playerModel, self->genericBolt1, self->s.number); } - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( self, "takingPain", self->client->ps.legsAnimTimer );//2900 ); - - if ( self->health > HOWLER_PANIC_HEALTH ) - {//still have some health left - if ( Q_irand( 0, self->max_health ) > self->health )//FIXME: or check damage? - {//back off! - TIMER_Set( self, "standing", -level.time ); - TIMER_Set( self, "running", -level.time ); - TIMER_Set( self, "walking", -level.time ); - TIMER_Set( self, "retreating", Q_irand( 1000, 5000 ) ); - } - else - {//go after him! - TIMER_Set( self, "standing", -level.time ); - TIMER_Set( self, "running", self->client->ps.legsAnimTimer+Q_irand(3000,6000) ); - TIMER_Set( self, "walking", -level.time ); - TIMER_Set( self, "retreating", -level.time ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(self, "takingPain", self->client->ps.legsAnimTimer); // 2900 ); + + if (self->health > HOWLER_PANIC_HEALTH) { // still have some health left + if (Q_irand(0, self->max_health) > self->health) // FIXME: or check damage? + { // back off! + TIMER_Set(self, "standing", -level.time); + TIMER_Set(self, "running", -level.time); + TIMER_Set(self, "walking", -level.time); + TIMER_Set(self, "retreating", Q_irand(1000, 5000)); + } else { // go after him! + TIMER_Set(self, "standing", -level.time); + TIMER_Set(self, "running", self->client->ps.legsAnimTimer + Q_irand(3000, 6000)); + TIMER_Set(self, "walking", -level.time); + TIMER_Set(self, "retreating", -level.time); } - } - else if ( self->NPC ) - {//panic! - if ( Q_irand( 0, 1 ) ) - {//berzerk + } else if (self->NPC) { // panic! + if (Q_irand(0, 1)) { // berzerk self->NPC->localState = LSTATE_BERZERK; - } - else - {//flee + } else { // flee self->NPC->localState = LSTATE_FLEE; - TIMER_Set( self, "flee", Q_irand( 10000, 30000 ) ); + TIMER_Set(self, "flee", Q_irand(10000, 30000)); } } } } - /* ------------------------- NPC_BSHowler_Default ------------------------- */ -void NPC_BSHowler_Default( void ) -{ - if ( NPC->client->ps.legsAnim != BOTH_GESTURE1 ) - { +void NPC_BSHowler_Default(void) { + if (NPC->client->ps.legsAnim != BOTH_GESTURE1) { NPC->count = 0; } - //FIXME: if in jump, do damage in front and maybe knock them down? - if ( !TIMER_Done( NPC, "attacking" ) ) - { - if ( NPC->enemy ) - { - //NPC_FaceEnemy( qfalse ); - Howler_Attack( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) ); - } - else - { - //NPC_UpdateAngles( qfalse, qtrue ); - Howler_Attack( 0.0f ); - } - NPC_UpdateAngles( qfalse, qtrue ); + // FIXME: if in jump, do damage in front and maybe knock them down? + if (!TIMER_Done(NPC, "attacking")) { + if (NPC->enemy) { + // NPC_FaceEnemy( qfalse ); + Howler_Attack(Distance(NPC->enemy->currentOrigin, NPC->currentOrigin)); + } else { + // NPC_UpdateAngles( qfalse, qtrue ); + Howler_Attack(0.0f); + } + NPC_UpdateAngles(qfalse, qtrue); return; } - if ( NPC->enemy ) - { - if ( NPCInfo->stats.aggression > 0 ) - { - if ( TIMER_Done( NPC, "aggressionDecay" ) ) - { + if (NPC->enemy) { + if (NPCInfo->stats.aggression > 0) { + if (TIMER_Done(NPC, "aggressionDecay")) { NPCInfo->stats.aggression--; - TIMER_Set( NPC, "aggressionDecay", 500 ); + TIMER_Set(NPC, "aggressionDecay", 500); } } - if ( !TIMER_Done( NPC, "flee" ) - && NPC_BSFlee() ) //this can clear ENEMY - {//successfully trying to run away + if (!TIMER_Done(NPC, "flee") && NPC_BSFlee()) // this can clear ENEMY + { // successfully trying to run away return; } - if ( NPC->enemy == NULL) - { - NPC_UpdateAngles( qfalse, qtrue ); + if (NPC->enemy == NULL) { + NPC_UpdateAngles(qfalse, qtrue); return; } - if ( NPCInfo->localState == LSTATE_FLEE ) - {//we were fleeing, now done (either timer ran out or we cannot flee anymore - if ( NPC_ClearLOS( NPC->enemy ) ) - {//if enemy is still around, go berzerk + if (NPCInfo->localState == LSTATE_FLEE) { // we were fleeing, now done (either timer ran out or we cannot flee anymore + if (NPC_ClearLOS(NPC->enemy)) { // if enemy is still around, go berzerk NPCInfo->localState = LSTATE_BERZERK; - } - else - {//otherwise, lick our wounds? + } else { // otherwise, lick our wounds? NPCInfo->localState = LSTATE_CLEAR; - TIMER_Set( NPC, "standing", Q_irand( 3000, 10000 ) ); + TIMER_Set(NPC, "standing", Q_irand(3000, 10000)); } - } - else if ( NPCInfo->localState == LSTATE_BERZERK ) - {//go nuts! - } - else if ( NPCInfo->stats.aggression >= Q_irand( 75, 125 ) ) - {//that's it, go nuts! + } else if (NPCInfo->localState == LSTATE_BERZERK) { // go nuts! + } else if (NPCInfo->stats.aggression >= Q_irand(75, 125)) { // that's it, go nuts! NPCInfo->localState = LSTATE_BERZERK; - } - else if ( !TIMER_Done( NPC, "retreating" ) ) - {//trying to back off - NPC_FaceEnemy( qtrue ); - if ( NPC->client->ps.speed > NPCInfo->stats.walkSpeed ) - { + } else if (!TIMER_Done(NPC, "retreating")) { // trying to back off + NPC_FaceEnemy(qtrue); + if (NPC->client->ps.speed > NPCInfo->stats.walkSpeed) { NPC->client->ps.speed = NPCInfo->stats.walkSpeed; } ucmd.buttons |= BUTTON_WALKING; - if ( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) < HOWLER_RETREAT_DIST ) - {//enemy is close + if (Distance(NPC->enemy->currentOrigin, NPC->currentOrigin) < HOWLER_RETREAT_DIST) { // enemy is close vec3_t moveDir; - AngleVectors( NPC->currentAngles, moveDir, NULL, NULL ); - VectorScale( moveDir, -1, moveDir ); - if ( !NAV_DirSafe( NPC, moveDir, 8 ) ) - {//enemy is backing me up against a wall or ledge! Start to get really mad! + AngleVectors(NPC->currentAngles, moveDir, NULL, NULL); + VectorScale(moveDir, -1, moveDir); + if (!NAV_DirSafe(NPC, moveDir, 8)) { // enemy is backing me up against a wall or ledge! Start to get really mad! NPCInfo->stats.aggression += 2; - } - else - {//back off + } else { // back off ucmd.forwardmove = -127; } - //enemy won't leave me alone, get mad... + // enemy won't leave me alone, get mad... NPCInfo->stats.aggression++; } return; - } - else if ( TIMER_Done( NPC, "standing" ) ) - {//not standing around - if ( !(NPCInfo->last_ucmd.forwardmove) - && !(NPCInfo->last_ucmd.rightmove) ) - {//stood last frame - if ( TIMER_Done( NPC, "walking" ) - && TIMER_Done( NPC, "running" ) ) - {//not walking or running - if ( Q_irand( 0, 2 ) ) - {//run for a while - TIMER_Set( NPC, "walking", Q_irand( 4000, 8000 ) ); - } - else - {//walk for a bit - TIMER_Set( NPC, "running", Q_irand( 2500, 5000 ) ); + } else if (TIMER_Done(NPC, "standing")) { // not standing around + if (!(NPCInfo->last_ucmd.forwardmove) && !(NPCInfo->last_ucmd.rightmove)) { // stood last frame + if (TIMER_Done(NPC, "walking") && TIMER_Done(NPC, "running")) { // not walking or running + if (Q_irand(0, 2)) { // run for a while + TIMER_Set(NPC, "walking", Q_irand(4000, 8000)); + } else { // walk for a bit + TIMER_Set(NPC, "running", Q_irand(2500, 5000)); } } - } - else if ( (NPCInfo->last_ucmd.buttons&BUTTON_WALKING) ) - {//walked last frame - if ( TIMER_Done( NPC, "walking" ) ) - {//just finished walking - if ( Q_irand( 0, 5 ) || DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) < MAX_DISTANCE_SQR ) - {//run for a while - TIMER_Set( NPC, "running", Q_irand( 4000, 20000 ) ); - } - else - {//stand for a bit - TIMER_Set( NPC, "standing", Q_irand( 2000, 6000 ) ); + } else if ((NPCInfo->last_ucmd.buttons & BUTTON_WALKING)) { // walked last frame + if (TIMER_Done(NPC, "walking")) { // just finished walking + if (Q_irand(0, 5) || DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin) < MAX_DISTANCE_SQR) { // run for a while + TIMER_Set(NPC, "running", Q_irand(4000, 20000)); + } else { // stand for a bit + TIMER_Set(NPC, "standing", Q_irand(2000, 6000)); } } - } - else - {//ran last frame - if ( TIMER_Done( NPC, "running" ) ) - {//just finished running - if ( Q_irand( 0, 8 ) || DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) < MAX_DISTANCE_SQR ) - {//walk for a while - TIMER_Set( NPC, "walking", Q_irand( 3000, 10000 ) ); - } - else - {//stand for a bit - TIMER_Set( NPC, "standing", Q_irand( 2000, 6000 ) ); + } else { // ran last frame + if (TIMER_Done(NPC, "running")) { // just finished running + if (Q_irand(0, 8) || DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin) < MAX_DISTANCE_SQR) { // walk for a while + TIMER_Set(NPC, "walking", Q_irand(3000, 10000)); + } else { // stand for a bit + TIMER_Set(NPC, "standing", Q_irand(2000, 6000)); } } } } - if ( NPC_ValidEnemy( NPC->enemy ) == qfalse ) - { - TIMER_Remove( NPC, "lookForNewEnemy" );//make them look again right now - if ( !NPC->enemy->inuse || level.time - NPC->enemy->s.time > Q_irand( 10000, 15000 ) ) - {//it's been a while since the enemy died, or enemy is completely gone, get bored with him + if (NPC_ValidEnemy(NPC->enemy) == qfalse) { + TIMER_Remove(NPC, "lookForNewEnemy"); // make them look again right now + if (!NPC->enemy->inuse || level.time - NPC->enemy->s.time > + Q_irand(10000, 15000)) { // it's been a while since the enemy died, or enemy is completely gone, get bored with him NPC->enemy = NULL; Howler_Patrol(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( TIMER_Done( NPC, "lookForNewEnemy" ) ) - { - gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy? + if (TIMER_Done(NPC, "lookForNewEnemy")) { + gentity_t *sav_enemy = NPC->enemy; // FIXME: what about NPC->lastEnemy? NPC->enemy = NULL; - gentity_t *newEnemy = NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse ); + gentity_t *newEnemy = NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse); NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, newEnemy ); - if ( NPC->enemy != NPC->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(NPC, newEnemy); + if (NPC->enemy != NPC->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up NPC->useDebounceTime = 0; } - //hold this one for at least 5-15 seconds - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - } - else - {//look again in 2-5 secs - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + // hold this one for at least 5-15 seconds + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(5000, 15000)); + } else { // look again in 2-5 secs + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(2000, 5000)); } } Howler_Combat(); - if ( TIMER_Done( NPC, "speaking" ) ) - { - if ( !TIMER_Done( NPC, "standing" ) - || !TIMER_Done( NPC, "retreating" )) - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/idle_hiss%d.mp3", Q_irand( 1, 2 ) ) ); - } - else if ( !TIMER_Done( NPC, "walking" ) - || NPCInfo->localState == LSTATE_FLEE ) - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_talk%d.mp3", Q_irand( 1, 5 ) ) ); + if (TIMER_Done(NPC, "speaking")) { + if (!TIMER_Done(NPC, "standing") || !TIMER_Done(NPC, "retreating")) { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/howler/idle_hiss%d.mp3", Q_irand(1, 2))); + } else if (!TIMER_Done(NPC, "walking") || NPCInfo->localState == LSTATE_FLEE) { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/howler/howl_talk%d.mp3", Q_irand(1, 5))); + } else { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/howler/howl_yell%d.mp3", Q_irand(1, 5))); } - else - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_yell%d.mp3", Q_irand( 1, 5 ) ) ); - } - if ( NPCInfo->localState == LSTATE_BERZERK - || NPCInfo->localState == LSTATE_FLEE ) - { - TIMER_Set( NPC, "speaking", Q_irand( 1000, 4000 ) ); - } - else - { - TIMER_Set( NPC, "speaking", Q_irand( 3000, 8000 ) ); + if (NPCInfo->localState == LSTATE_BERZERK || NPCInfo->localState == LSTATE_FLEE) { + TIMER_Set(NPC, "speaking", Q_irand(1000, 4000)); + } else { + TIMER_Set(NPC, "speaking", Q_irand(3000, 8000)); } } return; - } - else - { - if ( TIMER_Done( NPC, "speaking" ) ) - { - if ( !Q_irand( 0, 3 ) ) - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/idle_hiss%d.mp3", Q_irand( 1, 2 ) ) ); - } - else - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/howler/howl_talk%d.mp3", Q_irand( 1, 5 ) ) ); + } else { + if (TIMER_Done(NPC, "speaking")) { + if (!Q_irand(0, 3)) { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/howler/idle_hiss%d.mp3", Q_irand(1, 2))); + } else { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/howler/howl_talk%d.mp3", Q_irand(1, 5))); } - TIMER_Set( NPC, "speaking", Q_irand( 4000, 12000 ) ); + TIMER_Set(NPC, "speaking", Q_irand(4000, 12000)); } - if ( NPCInfo->stats.aggression > 0 ) - { - if ( TIMER_Done( NPC, "aggressionDecay" ) ) - { + if (NPCInfo->stats.aggression > 0) { + if (TIMER_Done(NPC, "aggressionDecay")) { NPCInfo->stats.aggression--; - TIMER_Set( NPC, "aggressionDecay", 200 ); + TIMER_Set(NPC, "aggressionDecay", 200); } } - if ( TIMER_Done( NPC, "standing" ) ) - {//not standing around - if ( !(NPCInfo->last_ucmd.forwardmove) - && !(NPCInfo->last_ucmd.rightmove) ) - {//stood last frame - if ( TIMER_Done( NPC, "walking" ) - && TIMER_Done( NPC, "running" ) ) - {//not walking or running - if ( NPCInfo->goalEntity ) - {//have somewhere to go - if ( Q_irand( 0, 2 ) ) - {//walk for a while - TIMER_Set( NPC, "walking", Q_irand( 3000, 10000 ) ); - } - else - {//run for a bit - TIMER_Set( NPC, "running", Q_irand( 2500, 5000 ) ); + if (TIMER_Done(NPC, "standing")) { // not standing around + if (!(NPCInfo->last_ucmd.forwardmove) && !(NPCInfo->last_ucmd.rightmove)) { // stood last frame + if (TIMER_Done(NPC, "walking") && TIMER_Done(NPC, "running")) { // not walking or running + if (NPCInfo->goalEntity) { // have somewhere to go + if (Q_irand(0, 2)) { // walk for a while + TIMER_Set(NPC, "walking", Q_irand(3000, 10000)); + } else { // run for a bit + TIMER_Set(NPC, "running", Q_irand(2500, 5000)); } } } - } - else if ( (NPCInfo->last_ucmd.buttons&BUTTON_WALKING) ) - {//walked last frame - if ( TIMER_Done( NPC, "walking" ) ) - {//just finished walking - if ( Q_irand( 0, 3 ) ) - {//run for a while - TIMER_Set( NPC, "running", Q_irand( 3000, 6000 ) ); - } - else - {//stand for a bit - TIMER_Set( NPC, "standing", Q_irand( 2500, 5000 ) ); + } else if ((NPCInfo->last_ucmd.buttons & BUTTON_WALKING)) { // walked last frame + if (TIMER_Done(NPC, "walking")) { // just finished walking + if (Q_irand(0, 3)) { // run for a while + TIMER_Set(NPC, "running", Q_irand(3000, 6000)); + } else { // stand for a bit + TIMER_Set(NPC, "standing", Q_irand(2500, 5000)); } } - } - else - {//ran last frame - if ( TIMER_Done( NPC, "running" ) ) - {//just finished running - if ( Q_irand( 0, 2 ) ) - {//walk for a while - TIMER_Set( NPC, "walking", Q_irand( 6000, 15000 ) ); - } - else - {//stand for a bit - TIMER_Set( NPC, "standing", Q_irand( 4000, 6000 ) ); + } else { // ran last frame + if (TIMER_Done(NPC, "running")) { // just finished running + if (Q_irand(0, 2)) { // walk for a while + TIMER_Set(NPC, "walking", Q_irand(6000, 15000)); + } else { // stand for a bit + TIMER_Set(NPC, "standing", Q_irand(4000, 6000)); } } } } - if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Howler_Patrol(); - } - else - { + } else { Howler_Idle(); } } - NPC_UpdateAngles( qfalse, qtrue ); + NPC_UpdateAngles(qfalse, qtrue); } diff --git a/code/game/AI_ImperialProbe.cpp b/code/game/AI_ImperialProbe.cpp index 25620b374b..8e5bcfb070 100644 --- a/code/game/AI_ImperialProbe.cpp +++ b/code/game/AI_ImperialProbe.cpp @@ -25,38 +25,29 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); - -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; - -void ImperialProbe_Idle( void ); - -void NPC_Probe_Precache(void) -{ - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/probe/misc/probetalk%d", i ) ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +extern gitem_t *FindItemForAmmo(ammo_t ammo); + +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; + +void ImperialProbe_Idle(void); + +void NPC_Probe_Precache(void) { + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/probe/misc/probetalk%d", i)); } - G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + G_SoundIndex("sound/chars/probe/misc/probedroidloop"); G_SoundIndex("sound/chars/probe/misc/anger1"); G_SoundIndex("sound/chars/probe/misc/fire"); - G_EffectIndex( "chunks/probehead" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "explosions/probeexplosion1"); - G_EffectIndex( "bryar/muzzle_flash" ); + G_EffectIndex("chunks/probehead"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("explosions/probeexplosion1"); + G_EffectIndex("bryar/muzzle_flash"); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL ) ); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); } /* ------------------------- @@ -64,126 +55,106 @@ Hunter_MaintainHeight ------------------------- */ -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f -void ImperialProbe_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void ImperialProbe_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference dif = NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > 16 ) - { - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 8) { + if (fabs(dif) > 16) { + dif = (dif < 0 ? -16 : 16); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } // Stay at a given height until we take on an enemy -/* VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 512 ); - gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); + /* VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 512 ); + gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); - if ( trace.fraction != 1.0f ) - { - float length = ( trace.fraction * 512 ); - - if ( length < 80 ) - { - ucmd.upmove = 32; - } - else if ( length > 120 ) - { - ucmd.upmove = -32; - } - else - { - if ( NPC->client->ps.velocity[2] ) + if ( trace.fraction != 1.0f ) { - NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + float length = ( trace.fraction * 512 ); - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + if ( length < 80 ) { - NPC->client->ps.velocity[2] = 0; + ucmd.upmove = 32; } - } - } - } */ + else if ( length > 120 ) + { + ucmd.upmove = -32; + } + else + { + if ( NPC->client->ps.velocity[2] ) + { + NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + + if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + { + NPC->client->ps.velocity[2] = 0; + } + } + } + } */ } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } @@ -195,29 +166,27 @@ ImperialProbe_Strafe ------------------------- */ -#define HUNTER_STRAFE_VEL 256 -#define HUNTER_STRAFE_DIS 200 -#define HUNTER_UPWARD_PUSH 32 +#define HUNTER_STRAFE_VEL 256 +#define HUNTER_STRAFE_DIS 200 +#define HUNTER_UPWARD_PUSH 32 -void ImperialProbe_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void ImperialProbe_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push NPC->client->ps.velocity[2] += HUNTER_UPWARD_PUSH; @@ -234,49 +203,43 @@ ImperialProbe_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 5 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 5 -void ImperialProbe_Hunt( qboolean visible, qboolean advance ) -{ - float speed; - vec3_t forward; +void ImperialProbe_Hunt(qboolean visible, qboolean advance) { + float speed; + vec3_t forward; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { ImperialProbe_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; NPC_MoveToGoal(qtrue); return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } /* @@ -284,58 +247,47 @@ void ImperialProbe_Hunt( qboolean visible, qboolean advance ) ImperialProbe_FireBlaster ------------------------- */ -void ImperialProbe_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - - //FIXME: use {0, NPC->client->ps.legsYaw, 0} - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt1, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - - G_PlayEffect( "bryar/muzzle_flash", muzzle1 ); - - G_Sound( NPC, G_SoundIndex( "sound/chars/probe/misc/fire" )); - - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_CHEST, enemy_org1 ); - enemy_org1[0]+= Q_irand(0,10); - enemy_org1[1]+= Q_irand(0,10); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); +void ImperialProbe_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + + // FIXME: use {0, NPC->client->ps.legsYaw, 0} + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt1, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); + + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + + G_PlayEffect("bryar/muzzle_flash", muzzle1); + + G_Sound(NPC, G_SoundIndex("sound/chars/probe/misc/fire")); + + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_CHEST, enemy_org1); + enemy_org1[0] += Q_irand(0, 10); + enemy_org1[1] += Q_irand(0, 10); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; - if ( g_spskill->integer <= 1 ) - { + if (g_spskill->integer <= 1) { missile->damage = 5; - } - else - { + } else { missile->damage = 10; } - missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -343,37 +295,30 @@ void ImperialProbe_FireBlaster(void) ImperialProbe_Ranged ------------------------- */ -void ImperialProbe_Ranged( qboolean visible, qboolean advance ) -{ - int delay_min,delay_max; +void ImperialProbe_Ranged(qboolean visible, qboolean advance) { + int delay_min, delay_max; - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { delay_min = 500; delay_max = 3000; - } - else if ( g_spskill->integer > 1 ) - { + } else if (g_spskill->integer > 1) { delay_min = 500; delay_max = 2000; - } - else - { + } else { delay_min = 300; delay_max = 1500; } - TIMER_Set( NPC, "attackDelay", Q_irand( delay_min, delay_max ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(delay_min, delay_max)); ImperialProbe_FireBlaster(); -// ucmd.buttons |= BUTTON_ATTACK; + // ucmd.buttons |= BUTTON_ATTACK; } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); } } @@ -383,58 +328,52 @@ ImperialProbe_AttackDecision ------------------------- */ -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -void ImperialProbe_AttackDecision( void ) -{ +void ImperialProbe_AttackDecision(void) { // Always keep a good height off the ground ImperialProbe_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { ImperialProbe_Idle(); return; } - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); -// distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + // distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); return; } } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Decide what type of attack to do - ImperialProbe_Ranged( visible, advance ); + ImperialProbe_Ranged(visible, advance); } /* @@ -442,66 +381,61 @@ void ImperialProbe_AttackDecision( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Probe_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - float pain_chance; +void NPC_Probe_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + float pain_chance; - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) // demp2 always messes them up real good + if (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) // demp2 always messes them up real good { vec3_t endPos; - trace_t trace; + trace_t trace; - VectorSet( endPos, self->currentOrigin[0], self->currentOrigin[1], self->currentOrigin[2] - 128 ); - gi.trace( &trace, self->currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + VectorSet(endPos, self->currentOrigin[0], self->currentOrigin[1], self->currentOrigin[2] - 128); + gi.trace(&trace, self->currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, (EG2_Collision)0, 0); - if ( trace.fraction == 1.0f || mod == MOD_DEMP2 ) // demp2 always does this + if (trace.fraction == 1.0f || mod == MOD_DEMP2) // demp2 always does this { - if (self->client->clientInfo.headModel != 0) - { + if (self->client->clientInfo.headModel != 0) { vec3_t origin; - VectorCopy(self->currentOrigin,origin); - origin[2] +=50; -// G_PlayEffect( "small_chunks", origin ); - G_PlayEffect( "chunks/probehead", origin ); - G_PlayEffect( "env/med_explode2", origin ); + VectorCopy(self->currentOrigin, origin); + origin[2] += 50; + // G_PlayEffect( "small_chunks", origin ); + G_PlayEffect("chunks/probehead", origin); + G_PlayEffect("env/med_explode2", origin); self->client->clientInfo.headModel = 0; self->client->moveType = MT_RUNJUMP; - self->client->ps.gravity = g_gravity->value*.1; + self->client->ps.gravity = g_gravity->value * .1; } - if ( (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other ) - { + if ((mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - VectorSubtract( self->currentOrigin, other->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->currentOrigin, other->currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->NPC->localState = LSTATE_DROP; } - } - else - { - pain_chance = NPC_GetPainChance( self, damage ); + } else { + pain_chance = NPC_GetPainChance(self, damage); - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? + if (Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); } } - NPC_Pain( self, inflictor, other, point, damage, mod); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -510,8 +444,7 @@ ImperialProbe_Idle ------------------------- */ -void ImperialProbe_Idle( void ) -{ +void ImperialProbe_Idle(void) { ImperialProbe_MaintainHeight(); NPC_BSIdle(); @@ -522,44 +455,38 @@ void ImperialProbe_Idle( void ) NPC_BSImperialProbe_Patrol ------------------------- */ -void ImperialProbe_Patrol( void ) -{ +void ImperialProbe_Patrol(void) { ImperialProbe_MaintainHeight(); - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL ); + // If we have somewhere to go, then do that + if (!NPC->enemy) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); - if ( UpdateGoal() ) - { - //start loop sound once we move - NPC->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + if (UpdateGoal()) { + // start loop sound once we move + NPC->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else // He's got an enemy. Make him angry. + } else // He's got an enemy. Make him angry. { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1" ); - TIMER_Set( NPC, "angerNoise", Q_irand( 2000, 4000 ) ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL; + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1"); + TIMER_Set(NPC, "angerNoise", Q_irand(2000, 4000)); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -567,25 +494,22 @@ void ImperialProbe_Patrol( void ) ImperialProbe_Wait ------------------------- */ -void ImperialProbe_Wait(void) -{ - if ( NPCInfo->localState == LSTATE_DROP ) - { +void ImperialProbe_Wait(void) { + if (NPCInfo->localState == LSTATE_DROP) { vec3_t endPos; - trace_t trace; + trace_t trace; - NPCInfo->desiredYaw = AngleNormalize360( NPCInfo->desiredYaw + 25 ); + NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 25); - VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 32 ); - gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + VectorSet(endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 32); + gi.trace(&trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); - if ( trace.fraction != 1.0f ) - { - G_Damage(NPC, NPC->enemy, NPC->enemy, NULL, NULL, 2000, 0,MOD_UNKNOWN); + if (trace.fraction != 1.0f) { + G_Damage(NPC, NPC->enemy, NPC->enemy, NULL, NULL, 2000, 0, MOD_UNKNOWN); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -593,24 +517,16 @@ void ImperialProbe_Wait(void) NPC_BSImperialProbe_Default ------------------------- */ -void NPC_BSImperialProbe_Default( void ) -{ +void NPC_BSImperialProbe_Default(void) { - if ( NPC->enemy ) - { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; ImperialProbe_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ImperialProbe_Patrol(); - } - else if ( NPCInfo->localState == LSTATE_DROP ) - { + } else if (NPCInfo->localState == LSTATE_DROP) { ImperialProbe_Wait(); - } - else - { + } else { ImperialProbe_Idle(); } } diff --git a/code/game/AI_Interrogator.cpp b/code/game/AI_Interrogator.cpp index f3bd826dd3..056581cc6b 100644 --- a/code/game/AI_Interrogator.cpp +++ b/code/game/AI_Interrogator.cpp @@ -23,14 +23,13 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -void Interrogator_Idle( void ); -void DeathFX( gentity_t *ent ); - -enum -{ -LSTATE_BLADESTOP=0, -LSTATE_BLADEUP, -LSTATE_BLADEDOWN, +void Interrogator_Idle(void); +void DeathFX(gentity_t *ent); + +enum { + LSTATE_BLADESTOP = 0, + LSTATE_BLADEUP, + LSTATE_BLADEDOWN, }; /* @@ -38,22 +37,20 @@ LSTATE_BLADEDOWN, NPC_Interrogator_Precache ------------------------- */ -void NPC_Interrogator_Precache(gentity_t *self) -{ - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); +void NPC_Interrogator_Precache(gentity_t *self) { + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); G_SoundIndex("sound/chars/mark1/misc/anger.wav"); - G_SoundIndex( "sound/chars/probe/misc/talk"); - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject" ); - G_SoundIndex( "sound/chars/interrogator/misc/int_droid_explo" ); - G_EffectIndex( "explosions/droidexplosion1" ); + G_SoundIndex("sound/chars/probe/misc/talk"); + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject"); + G_SoundIndex("sound/chars/interrogator/misc/int_droid_explo"); + G_EffectIndex("explosions/droidexplosion1"); } /* ------------------------- Interrogator_die ------------------------- */ -void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Interrogator_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { self->client->ps.velocity[2] = -100; /* self->locationDamage[HL_NONE] += damage; @@ -67,13 +64,13 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke */ { self->client->moveType = MT_WALK; - self->client->ps.velocity[0] = Q_irand( -20, -10 ); - self->client->ps.velocity[1] = Q_irand( -20, -10 ); + self->client->ps.velocity[0] = Q_irand(-20, -10); + self->client->ps.velocity[1] = Q_irand(-20, -10); self->client->ps.velocity[2] = -100; } - //self->takedamage = qfalse; - //self->client->ps.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->takedamage = qfalse; + // self->client->ps.eFlags |= EF_NODRAW; + // self->contents = 0; return; } @@ -82,209 +79,175 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke Interrogator_PartsMove ------------------------- */ -void Interrogator_PartsMove(void) -{ +void Interrogator_PartsMove(void) { // Syringe - if ( TIMER_Done(NPC,"syringeDelay") ) - { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); - - if ((NPC->pos1[1] < 60) || (NPC->pos1[1] > 300)) - { - NPC->pos1[1]+=Q_irand( -20, 20 ); // Pitch - } - else if (NPC->pos1[1] > 180) - { - NPC->pos1[1]=Q_irand( 300, 360 ); // Pitch - } - else - { - NPC->pos1[1]=Q_irand( 0, 60 ); // Pitch + if (TIMER_Done(NPC, "syringeDelay")) { + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); + + if ((NPC->pos1[1] < 60) || (NPC->pos1[1] > 300)) { + NPC->pos1[1] += Q_irand(-20, 20); // Pitch + } else if (NPC->pos1[1] > 180) { + NPC->pos1[1] = Q_irand(300, 360); // Pitch + } else { + NPC->pos1[1] = Q_irand(0, 60); // Pitch } - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - TIMER_Set( NPC, "syringeDelay", Q_irand( 100, 1000 ) ); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + TIMER_Set(NPC, "syringeDelay", Q_irand(100, 1000)); } // Scalpel - if ( TIMER_Done(NPC,"scalpelDelay") ) - { + if (TIMER_Done(NPC, "scalpelDelay")) { // Change pitch - if ( NPCInfo->localState == LSTATE_BLADEDOWN ) // Blade is moving down + if (NPCInfo->localState == LSTATE_BLADEDOWN) // Blade is moving down { - NPC->pos2[0]-= 30; - if (NPC->pos2[0] < 180) - { + NPC->pos2[0] -= 30; + if (NPC->pos2[0] < 180) { NPC->pos2[0] = 180; - NPCInfo->localState = LSTATE_BLADEUP; // Make it move up + NPCInfo->localState = LSTATE_BLADEUP; // Make it move up } - } - else // Blade is coming back up + } else // Blade is coming back up { - NPC->pos2[0]+= 30; - if (NPC->pos2[0] >= 360) - { + NPC->pos2[0] += 30; + if (NPC->pos2[0] >= 360) { NPC->pos2[0] = 360; - NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down - TIMER_Set( NPC, "scalpelDelay", Q_irand( 100, 1000 ) ); + NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down + TIMER_Set(NPC, "scalpelDelay", Q_irand(100, 1000)); } } - NPC->pos2[0] = AngleNormalize360( NPC->pos2[0]); - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + NPC->pos2[0] = AngleNormalize360(NPC->pos2[0]); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } // Claw - NPC->pos3[1] += Q_irand( 10, 30 ); - NPC->pos3[1] = AngleNormalize360( NPC->pos3[1]); - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - + NPC->pos3[1] += Q_irand(10, 30); + NPC->pos3[1] = AngleNormalize360(NPC->pos3[1]); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, + 0); } -#define VELOCITY_DECAY 0.85f -#define HUNTER_UPWARD_PUSH 2 +#define VELOCITY_DECAY 0.85f +#define HUNTER_UPWARD_PUSH 2 /* ------------------------- Interrogator_MaintainHeight ------------------------- */ -void Interrogator_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void Interrogator_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; - NPC->s.loopSound = G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference dif = (NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 16 ) - { - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 16) { + dif = (dif < 0 ? -16 : 16); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } -#define HUNTER_STRAFE_VEL 32 -#define HUNTER_STRAFE_DIS 200 +#define HUNTER_STRAFE_VEL 32 +#define HUNTER_STRAFE_DIS 200 /* ------------------------- Interrogator_Strafe ------------------------- */ -void Interrogator_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; - float dif; +void Interrogator_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; + float dif; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference dif = (NPC->enemy->currentOrigin[2] + 32) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - dif = ( dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH ); + if (fabs(dif) > 8) { + dif = (dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH); } NPC->client->ps.velocity[2] += dif; - } // Set the strafe start time @@ -299,11 +262,10 @@ Interrogator_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 2 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 2 -void Interrogator_Hunt( qboolean visible, qboolean advance ) -{ +void Interrogator_Hunt(qboolean visible, qboolean advance) { float speed; vec3_t forward; @@ -311,27 +273,23 @@ void Interrogator_Hunt( qboolean visible, qboolean advance ) NPC_FaceEnemy(qfalse); - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Interrogator_Strafe(); - if ( NPCInfo->standTime > level.time ) - {//successfully strafed + if (NPCInfo->standTime > level.time) { // successfully strafed return; } } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; @@ -339,48 +297,44 @@ void Interrogator_Hunt( qboolean visible, qboolean advance ) NPC_MoveToGoal(qtrue); return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } -#define MIN_DISTANCE 64 +#define MIN_DISTANCE 64 /* ------------------------- Interrogator_Melee ------------------------- */ -void Interrogator_Melee( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Interrogator_Melee(qboolean visible, qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { // Make sure that we are within the height range before we allow any damage to happen - if ( NPC->currentOrigin[2] >= NPC->enemy->currentOrigin[2]+NPC->enemy->mins[2] && NPC->currentOrigin[2]+NPC->mins[2]+8 < NPC->enemy->currentOrigin[2]+NPC->enemy->maxs[2] ) - { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 3000 ) ); - G_Damage( NPC->enemy, NPC, NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (NPC->currentOrigin[2] >= NPC->enemy->currentOrigin[2] + NPC->enemy->mins[2] && + NPC->currentOrigin[2] + NPC->mins[2] + 8 < NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) { + TIMER_Set(NPC, "attackDelay", Q_irand(500, 3000)); + G_Damage(NPC->enemy, NPC, NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE); NPC->enemy->client->poisonDamage = 18; NPC->enemy->client->poisonTime = level.time + 1000; // Drug our enemy up and do the wonky vision thing - gentity_t *tent = G_TempEntity( NPC->enemy->currentOrigin, EV_DRUGGED ); + gentity_t *tent = G_TempEntity(NPC->enemy->currentOrigin, EV_DRUGGED); tent->owner = NPC->enemy; - G_Sound( NPC, G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject.mp3" )); + G_Sound(NPC, G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject.mp3")); } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } } @@ -389,48 +343,41 @@ void Interrogator_Melee( qboolean visible, qboolean advance ) Interrogator_Attack ------------------------- */ -void Interrogator_Attack( void ) -{ +void Interrogator_Attack(void) { // Always keep a good height off the ground Interrogator_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Interrogator_Idle(); return; } // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE*MIN_DISTANCE ); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE * MIN_DISTANCE); - if ( !visible ) - { + if (!visible) { advance = qtrue; } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (!advance) - { - Interrogator_Melee( visible, advance ); + if (!advance) { + Interrogator_Melee(visible, advance); } } @@ -439,12 +386,10 @@ void Interrogator_Attack( void ) Interrogator_Idle ------------------------- */ -void Interrogator_Idle( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav" ); - NPC_UpdateAngles( qtrue, qtrue ); +void Interrogator_Idle(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav"); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -458,17 +403,12 @@ void Interrogator_Idle( void ) NPC_BSInterrogator_Default ------------------------- */ -void NPC_BSInterrogator_Default( void ) -{ - //NPC->e_DieFunc = dieF_Interrogator_die; +void NPC_BSInterrogator_Default(void) { + // NPC->e_DieFunc = dieF_Interrogator_die; - if ( NPC->enemy ) - { + if (NPC->enemy) { Interrogator_Attack(); - } - else - { + } else { Interrogator_Idle(); } - } diff --git a/code/game/AI_Jedi.cpp b/code/game/AI_Jedi.cpp index 1c508c5784..52004aa335 100644 --- a/code/game/AI_Jedi.cpp +++ b/code/game/AI_Jedi.cpp @@ -29,363 +29,297 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -//Externs -extern qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ); -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); -extern void ForceJump( gentity_t *self, usercmd_t *ucmd ); -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean NPC_CheckEnemyStealth( void ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); -extern void ForceLightning( gentity_t *self ); -extern void ForceHeal( gentity_t *self ); -extern void ForceRage( gentity_t *self ); -extern void ForceProtect( gentity_t *self ); -extern void ForceAbsorb( gentity_t *self ); -extern qboolean ForceDrain2( gentity_t *self ); -extern int WP_MissileBlockForBlock( int saberBlock ); -extern qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); -extern void WP_KnockdownTurret( gentity_t *self, gentity_t *pas ); -extern void WP_DeactivateSaber( gentity_t *self, qboolean clearLength = qfalse ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SaberInDeflect( int move ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_SuperBreakWinAnim( int anim ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern qboolean PM_DodgeAnim( int anim ); -extern qboolean PM_DodgeHoldAnim( int anim ); -extern qboolean PM_InAirKickingAnim( int anim ); -extern qboolean PM_KickingAnim( int anim ); -extern qboolean PM_StabDownAnim( int anim ); -extern qboolean PM_SuperBreakLoseAnim( int anim ); -extern qboolean PM_SaberInKata( saberMoveName_t saberMove ); -extern qboolean PM_InRollIgnoreTimer( playerState_t *ps ); -extern qboolean PM_PainAnim( int anim ); -extern qboolean G_CanKickEntity( gentity_t *self, gentity_t *target ); -extern saberMoveName_t G_PickAutoKick( gentity_t *self, gentity_t *enemy, qboolean storeMove ); -extern saberMoveName_t G_PickAutoMultiKick( gentity_t *self, qboolean allowSingles, qboolean storeMove ); -extern qboolean NAV_DirSafe( gentity_t *self, vec3_t dir, float dist ); -extern qboolean NAV_MoveDirSafe( gentity_t *self, usercmd_t *cmd, float distScale = 1.0f ); -extern float NPC_EnemyRangeFromBolt( int boltIndex ); -extern qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ); -extern qboolean PM_LockedAnim( int anim ); +// Externs +extern qboolean G_ValidEnemy(gentity_t *self, gentity_t *enemy); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); +extern void ForceJump(gentity_t *self, usercmd_t *ucmd); +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean NPC_CheckEnemyStealth(void); +extern gitem_t *FindItemForAmmo(ammo_t ammo); +extern void ForceLightning(gentity_t *self); +extern void ForceHeal(gentity_t *self); +extern void ForceRage(gentity_t *self); +extern void ForceProtect(gentity_t *self); +extern void ForceAbsorb(gentity_t *self); +extern qboolean ForceDrain2(gentity_t *self); +extern int WP_MissileBlockForBlock(int saberBlock); +extern qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); +extern void WP_KnockdownTurret(gentity_t *self, gentity_t *pas); +extern void WP_DeactivateSaber(gentity_t *self, qboolean clearLength = qfalse); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SaberInDeflect(int move); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_SuperBreakWinAnim(int anim); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern qboolean PM_DodgeAnim(int anim); +extern qboolean PM_DodgeHoldAnim(int anim); +extern qboolean PM_InAirKickingAnim(int anim); +extern qboolean PM_KickingAnim(int anim); +extern qboolean PM_StabDownAnim(int anim); +extern qboolean PM_SuperBreakLoseAnim(int anim); +extern qboolean PM_SaberInKata(saberMoveName_t saberMove); +extern qboolean PM_InRollIgnoreTimer(playerState_t *ps); +extern qboolean PM_PainAnim(int anim); +extern qboolean G_CanKickEntity(gentity_t *self, gentity_t *target); +extern saberMoveName_t G_PickAutoKick(gentity_t *self, gentity_t *enemy, qboolean storeMove); +extern saberMoveName_t G_PickAutoMultiKick(gentity_t *self, qboolean allowSingles, qboolean storeMove); +extern qboolean NAV_DirSafe(gentity_t *self, vec3_t dir, float dist); +extern qboolean NAV_MoveDirSafe(gentity_t *self, usercmd_t *cmd, float distScale = 1.0f); +extern float NPC_EnemyRangeFromBolt(int boltIndex); +extern qboolean WP_SabersCheckLock2(gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker); +extern qboolean PM_LockedAnim(int anim); extern qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask); -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *d_slowmodeath; -extern cvar_t *g_saberNewControlScheme; +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *d_slowmodeath; +extern cvar_t *g_saberNewControlScheme; extern int parryDebounce[]; -//Locals -static void Jedi_Aggression( gentity_t *self, int change ); -qboolean Jedi_WaitingAmbush( gentity_t *self ); -void Tavion_SithSwordRecharge( void ); -qboolean Rosh_BeingHealed( gentity_t *self ); +// Locals +static void Jedi_Aggression(gentity_t *self, int change); +qboolean Jedi_WaitingAmbush(gentity_t *self); +void Tavion_SithSwordRecharge(void); +qboolean Rosh_BeingHealed(gentity_t *self); static qboolean enemy_in_striking_range = qfalse; -static int jediSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several jedi from speaking all at once +static int jediSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several jedi from speaking all at once -void NPC_CultistDestroyer_Precache( void ) -{ - G_SoundIndex( "sound/movers/objects/green_beam_lp2.wav" ); - G_EffectIndex( "force/destruction_exp" ); +void NPC_CultistDestroyer_Precache(void) { + G_SoundIndex("sound/movers/objects/green_beam_lp2.wav"); + G_EffectIndex("force/destruction_exp"); } -void NPC_ShadowTrooper_Precache( void ) -{ - RegisterItem( FindItemForAmmo( AMMO_FORCE ) ); - G_SoundIndex( "sound/chars/shadowtrooper/cloak.wav" ); - G_SoundIndex( "sound/chars/shadowtrooper/decloak.wav" ); +void NPC_ShadowTrooper_Precache(void) { + RegisterItem(FindItemForAmmo(AMMO_FORCE)); + G_SoundIndex("sound/chars/shadowtrooper/cloak.wav"); + G_SoundIndex("sound/chars/shadowtrooper/decloak.wav"); } -void NPC_Rosh_Dark_Precache( void ) -{ - G_EffectIndex( "force/kothos_recharge.efx" ); - G_EffectIndex( "force/kothos_beam.efx" ); +void NPC_Rosh_Dark_Precache(void) { + G_EffectIndex("force/kothos_recharge.efx"); + G_EffectIndex("force/kothos_beam.efx"); } -void Jedi_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "strafeLeft", 0 ); - TIMER_Set( ent, "strafeRight", 0 ); - TIMER_Set( ent, "noStrafe", 0 ); - TIMER_Set( ent, "walking", 0 ); - TIMER_Set( ent, "taunting", 0 ); - TIMER_Set( ent, "parryTime", 0 ); - TIMER_Set( ent, "parryReCalcTime", 0 ); - TIMER_Set( ent, "forceJumpChasing", 0 ); - TIMER_Set( ent, "jumpChaseDebounce", 0 ); - TIMER_Set( ent, "moveforward", 0 ); - TIMER_Set( ent, "moveback", 0 ); - TIMER_Set( ent, "movenone", 0 ); - TIMER_Set( ent, "moveright", 0 ); - TIMER_Set( ent, "moveleft", 0 ); - TIMER_Set( ent, "movecenter", 0 ); - TIMER_Set( ent, "saberLevelDebounce", 0 ); - TIMER_Set( ent, "noRetreat", 0 ); - TIMER_Set( ent, "holdLightning", 0 ); - TIMER_Set( ent, "gripping", 0 ); - TIMER_Set( ent, "draining", 0 ); - TIMER_Set( ent, "noturn", 0 ); - TIMER_Set( ent, "specialEvasion", 0 ); +void Jedi_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "strafeLeft", 0); + TIMER_Set(ent, "strafeRight", 0); + TIMER_Set(ent, "noStrafe", 0); + TIMER_Set(ent, "walking", 0); + TIMER_Set(ent, "taunting", 0); + TIMER_Set(ent, "parryTime", 0); + TIMER_Set(ent, "parryReCalcTime", 0); + TIMER_Set(ent, "forceJumpChasing", 0); + TIMER_Set(ent, "jumpChaseDebounce", 0); + TIMER_Set(ent, "moveforward", 0); + TIMER_Set(ent, "moveback", 0); + TIMER_Set(ent, "movenone", 0); + TIMER_Set(ent, "moveright", 0); + TIMER_Set(ent, "moveleft", 0); + TIMER_Set(ent, "movecenter", 0); + TIMER_Set(ent, "saberLevelDebounce", 0); + TIMER_Set(ent, "noRetreat", 0); + TIMER_Set(ent, "holdLightning", 0); + TIMER_Set(ent, "gripping", 0); + TIMER_Set(ent, "draining", 0); + TIMER_Set(ent, "noturn", 0); + TIMER_Set(ent, "specialEvasion", 0); } -qboolean Jedi_CultistDestroyer( gentity_t *self ) -{ - if ( !self || !self->client ) - { +qboolean Jedi_CultistDestroyer(gentity_t *self) { + if (!self || !self->client) { return qfalse; } - //FIXME: just make a flag, dude! - if ( self->client->NPC_class == CLASS_REBORN - && self->s.weapon == WP_MELEE - && Q_stricmp( "cultist_destroyer", self->NPC_type ) == 0 ) - { + // FIXME: just make a flag, dude! + if (self->client->NPC_class == CLASS_REBORN && self->s.weapon == WP_MELEE && Q_stricmp("cultist_destroyer", self->NPC_type) == 0) { return qtrue; } return qfalse; } -void Jedi_PlayBlockedPushSound( gentity_t *self ) -{ - if ( !self->s.number ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); +void Jedi_PlayBlockedPushSound(gentity_t *self) { + if (!self->s.number) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void Jedi_PlayDeflectSound( gentity_t *self ) -{ - if ( !self->s.number ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); +void Jedi_PlayDeflectSound(gentity_t *self) { + if (!self->s.number) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void NPC_Jedi_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->client - && ( self->client->NPC_class == CLASS_ALORA - || self->client->NPC_class == CLASS_TAVION - || self->client->NPC_class == CLASS_DESANN ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE1, EV_CONFUSE3 ), 2000 ); - } - else if ( Q_irand( 0, 1 ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 2000 ); - } - else - { - G_AddVoiceEvent( self, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 2000 ); +void NPC_Jedi_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->client && (self->client->NPC_class == CLASS_ALORA || self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_DESANN)) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); + } else if (Q_irand(0, 1)) { + G_AddVoiceEvent(self, Q_irand(EV_TAUNT1, EV_TAUNT3), 2000); + } else { + G_AddVoiceEvent(self, Q_irand(EV_GLOAT1, EV_GLOAT3), 2000); } } } -qboolean Jedi_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir ) -{ - if ( self->s.number < MAX_CLIENTS || !self->NPC ) - {//only NPCs +qboolean Jedi_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir) { + if (self->s.number < MAX_CLIENTS || !self->NPC) { // only NPCs return qfalse; } - if ( self->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1 ) - {//only force-users + if (self->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1) { // only force-users return qfalse; } - if ( self->client->moveType == MT_FLYSWIM ) - {//can't knock me down when I'm flying + if (self->client->moveType == MT_FLYSWIM) { // can't knock me down when I'm flying return qtrue; } - if ( self->NPC && (self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) - {//bosses always get out of a knockdown - } - else if ( Q_irand( 0, RANK_CAPTAIN+5 ) > self->NPC->rank ) - {//lower their rank, the more likely they are fall down + if (self->NPC && (self->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) { // bosses always get out of a knockdown + } else if (Q_irand(0, RANK_CAPTAIN + 5) > self->NPC->rank) { // lower their rank, the more likely they are fall down return qfalse; } - vec3_t pDir, fwd, right, ang = {0, self->currentAngles[YAW], 0}; - float fDot, rDot; - int strafeTime = Q_irand( 1000, 2000 ); + vec3_t pDir, fwd, right, ang = {0, self->currentAngles[YAW], 0}; + float fDot, rDot; + int strafeTime = Q_irand(1000, 2000); - AngleVectors( ang, fwd, right, NULL ); - VectorNormalize2( pushDir, pDir ); - fDot = DotProduct( pDir, fwd ); - rDot = DotProduct( pDir, right ); + AngleVectors(ang, fwd, right, NULL); + VectorNormalize2(pushDir, pDir); + fDot = DotProduct(pDir, fwd); + rDot = DotProduct(pDir, right); - //flip or roll with it - usercmd_t tempCmd; - if ( fDot >= 0.4f ) - { + // flip or roll with it + usercmd_t tempCmd; + if (fDot >= 0.4f) { tempCmd.forwardmove = 127; - TIMER_Set( self, "moveforward", strafeTime ); - } - else if ( fDot <= -0.4f ) - { + TIMER_Set(self, "moveforward", strafeTime); + } else if (fDot <= -0.4f) { tempCmd.forwardmove = -127; - TIMER_Set( self, "moveback", strafeTime ); - } - else if ( rDot > 0 ) - { + TIMER_Set(self, "moveback", strafeTime); + } else if (rDot > 0) { tempCmd.rightmove = 127; - TIMER_Set( self, "strafeRight", strafeTime ); - TIMER_Set( self, "strafeLeft", -1 ); - } - else - { + TIMER_Set(self, "strafeRight", strafeTime); + TIMER_Set(self, "strafeLeft", -1); + } else { tempCmd.rightmove = -127; - TIMER_Set( self, "strafeLeft", strafeTime ); - TIMER_Set( self, "strafeRight", -1 ); - } - G_AddEvent( self, EV_JUMP, 0 ); - if ( !Q_irand( 0, 1 ) ) - {//flip - self->client->ps.forceJumpCharge = 280;//FIXME: calc this intelligently? - ForceJump( self, &tempCmd ); + TIMER_Set(self, "strafeLeft", strafeTime); + TIMER_Set(self, "strafeRight", -1); } - else - {//roll - TIMER_Set( self, "duck", strafeTime ); + G_AddEvent(self, EV_JUMP, 0); + if (!Q_irand(0, 1)) { // flip + self->client->ps.forceJumpCharge = 280; // FIXME: calc this intelligently? + ForceJump(self, &tempCmd); + } else { // roll + TIMER_Set(self, "duck", strafeTime); } - self->painDebounceTime = 0;//so we do something + self->painDebounceTime = 0; // so we do something return qtrue; } -extern void Boba_FireDecide( void ); -extern void RT_FireDecide( void ); -extern void Boba_FlyStart( gentity_t *self ); - - - - +extern void Boba_FireDecide(void); +extern void RT_FireDecide(void); +extern void Boba_FlyStart(gentity_t *self); //=============================================================================================== -//TAVION BOSS +// TAVION BOSS //=============================================================================================== -void NPC_TavionScepter_Precache( void ) -{ - G_EffectIndex( "scepter/beam_warmup.efx" ); - G_EffectIndex( "scepter/beam.efx" ); - G_EffectIndex( "scepter/slam_warmup.efx" ); - G_EffectIndex( "scepter/slam.efx" ); - G_EffectIndex( "scepter/impact.efx" ); - G_SoundIndex( "sound/weapons/scepter/loop.wav" ); - G_SoundIndex( "sound/weapons/scepter/slam_warmup.wav" ); - G_SoundIndex( "sound/weapons/scepter/beam_warmup.wav" ); +void NPC_TavionScepter_Precache(void) { + G_EffectIndex("scepter/beam_warmup.efx"); + G_EffectIndex("scepter/beam.efx"); + G_EffectIndex("scepter/slam_warmup.efx"); + G_EffectIndex("scepter/slam.efx"); + G_EffectIndex("scepter/impact.efx"); + G_SoundIndex("sound/weapons/scepter/loop.wav"); + G_SoundIndex("sound/weapons/scepter/slam_warmup.wav"); + G_SoundIndex("sound/weapons/scepter/beam_warmup.wav"); } -void NPC_TavionSithSword_Precache( void ) -{ - G_EffectIndex( "scepter/recharge.efx" ); - G_EffectIndex( "scepter/invincibility.efx" ); - G_EffectIndex( "scepter/sword.efx" ); - G_SoundIndex( "sound/weapons/scepter/recharge.wav" ); +void NPC_TavionSithSword_Precache(void) { + G_EffectIndex("scepter/recharge.efx"); + G_EffectIndex("scepter/invincibility.efx"); + G_EffectIndex("scepter/sword.efx"); + G_SoundIndex("sound/weapons/scepter/recharge.wav"); } -void Tavion_ScepterDamage( void ) -{ - if ( !NPC->ghoul2.size() - || NPC->weaponModel[1] <= 0 ) - { +void Tavion_ScepterDamage(void) { + if (!NPC->ghoul2.size() || NPC->weaponModel[1] <= 0) { return; } - if ( NPC->genericBolt1 != -1 ) - { - int curTime = (cg.time?cg.time:level.time); + if (NPC->genericBolt1 != -1) { + int curTime = (cg.time ? cg.time : level.time); qboolean hit = qfalse; - int lastHit = ENTITYNUM_NONE; - for ( int time = curTime-25; time <= curTime+25&&!hit; time += 25 ) - { - mdxaBone_t boltMatrix; - vec3_t tip, dir, base, angles={0,NPC->currentAngles[YAW],0}; - trace_t trace; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->weaponModel[1], - NPC->genericBolt1, - &boltMatrix, angles, NPC->currentOrigin, time, - NULL, NPC->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, base ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, dir ); - VectorMA( base, 512, dir, tip ); - #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { + int lastHit = ENTITYNUM_NONE; + for (int time = curTime - 25; time <= curTime + 25 && !hit; time += 25) { + mdxaBone_t boltMatrix; + vec3_t tip, dir, base, angles = {0, NPC->currentAngles[YAW], 0}; + trace_t trace; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->weaponModel[1], NPC->genericBolt1, &boltMatrix, angles, NPC->currentOrigin, time, NULL, NPC->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, base); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, dir); + VectorMA(base, 512, dir, tip); +#ifndef FINAL_BUILD + if (d_saberCombat->integer > 1) { G_DebugLine(base, tip, 1000, 0x000000ff, qtrue); } - #endif - gi.trace( &trace, base, vec3_origin, vec3_origin, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( trace.fraction < 1.0f ) - {//hit something +#endif + gi.trace(&trace, base, vec3_origin, vec3_origin, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10); + if (trace.fraction < 1.0f) { // hit something gentity_t *traceEnt = &g_entities[trace.entityNum]; - //FIXME: too expensive! - //if ( time == curTime ) - {//UGH - G_PlayEffect( G_EffectIndex( "scepter/impact.efx" ), trace.endpos, trace.plane.normal ); - } - - if ( traceEnt->takedamage - && trace.entityNum != lastHit - && (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class) ) - {//smack - int dmg = Q_irand( 10, 20 )*(g_spskill->integer+1);//NOTE: was 6-12 - //FIXME: debounce? - //FIXME: do dismemberment - G_Damage( traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_SABER );//MOD_MELEE ); - if ( traceEnt->client ) - { - if ( !Q_irand( 0, 2 ) ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_CONFUSE1, EV_CONFUSE2 ), 10000 ); - } - else - { - G_AddVoiceEvent( NPC, EV_JDETECTED3, 10000 ); + // FIXME: too expensive! + // if ( time == curTime ) + { // UGH + G_PlayEffect(G_EffectIndex("scepter/impact.efx"), trace.endpos, trace.plane.normal); + } + + if (traceEnt->takedamage && trace.entityNum != lastHit && + (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class)) { // smack + int dmg = Q_irand(10, 20) * (g_spskill->integer + 1); // NOTE: was 6-12 + // FIXME: debounce? + // FIXME: do dismemberment + G_Damage(traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_SABER); // MOD_MELEE ); + if (traceEnt->client) { + if (!Q_irand(0, 2)) { + G_AddVoiceEvent(NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE2), 10000); + } else { + G_AddVoiceEvent(NPC, EV_JDETECTED3, 10000); } - G_Throw( traceEnt, dir, Q_flrand( 50, 80 ) ); - if ( traceEnt->health > 0 && !Q_irand( 0, 2 ) )//FIXME: base on skill! - {//do pain on enemy - G_Knockdown( traceEnt, NPC, dir, 300, qtrue ); + G_Throw(traceEnt, dir, Q_flrand(50, 80)); + if (traceEnt->health > 0 && !Q_irand(0, 2)) // FIXME: base on skill! + { // do pain on enemy + G_Knockdown(traceEnt, NPC, dir, 300, qtrue); } } hit = qtrue; @@ -396,119 +330,92 @@ void Tavion_ScepterDamage( void ) } } -void Tavion_ScepterSlam( void ) -{ - if ( !NPC->ghoul2.size() - || NPC->weaponModel[1] <= 0 ) - { +void Tavion_ScepterSlam(void) { + if (!NPC->ghoul2.size() || NPC->weaponModel[1] <= 0) { return; } - int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[1]], "*weapon"); - if ( boltIndex != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t handle, bottom, angles={0,NPC->currentAngles[YAW],0}; - trace_t trace; - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = 300.0f; - const float halfRad = (radius/2); - float dist; - int i; - vec3_t mins, maxs, entDir; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->weaponModel[1], - boltIndex, - &boltMatrix, angles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, handle ); - VectorCopy( handle, bottom ); + int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[1]], "*weapon"); + if (boltIndex != -1) { + mdxaBone_t boltMatrix; + vec3_t handle, bottom, angles = {0, NPC->currentAngles[YAW], 0}; + trace_t trace; + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = 300.0f; + const float halfRad = (radius / 2); + float dist; + int i; + vec3_t mins, maxs, entDir; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->weaponModel[1], boltIndex, &boltMatrix, angles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, handle); + VectorCopy(handle, bottom); bottom[2] -= 128.0f; - gi.trace( &trace, handle, vec3_origin, vec3_origin, bottom, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); - G_PlayEffect( G_EffectIndex( "scepter/slam.efx" ), trace.endpos, trace.plane.normal ); + gi.trace(&trace, handle, vec3_origin, vec3_origin, bottom, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10); + G_PlayEffect(G_EffectIndex("scepter/slam.efx"), trace.endpos, trace.plane.normal); - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = trace.endpos[i] - radius; maxs[i] = trace.endpos[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( (radiusEnts[i]->flags&FL_NO_KNOCKBACK) ) - {//don't throw them back + if ((radiusEnts[i]->flags & FL_NO_KNOCKBACK)) { // don't throw them back continue; } - if ( radiusEnts[i] == NPC ) - {//Skip myself + if (radiusEnts[i] == NPC) { // Skip myself continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client - if ( G_EntIsBreakable( radiusEnts[i]->s.number, NPC ) ) - {//damage breakables within range, but not as much - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, 100, 0, MOD_EXPLOSIVE_SPLASH ); + if (radiusEnts[i]->client == NULL) { // must be a client + if (G_EntIsBreakable(radiusEnts[i]->s.number, NPC)) { // damage breakables within range, but not as much + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, 100, 0, MOD_EXPLOSIVE_SPLASH); } continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR) || (radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // can't be one being held continue; } - VectorSubtract( radiusEnts[i]->currentOrigin, trace.endpos, entDir ); - dist = VectorNormalize( entDir ); - if ( dist <= radius ) - { - if ( dist < halfRad ) - {//close enough to do damage, too - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand( 20, 30 ), DAMAGE_NO_KNOCKBACK, MOD_EXPLOSIVE_SPLASH ); + VectorSubtract(radiusEnts[i]->currentOrigin, trace.endpos, entDir); + dist = VectorNormalize(entDir); + if (dist <= radius) { + if (dist < halfRad) { // close enough to do damage, too + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand(20, 30), DAMAGE_NO_KNOCKBACK, MOD_EXPLOSIVE_SPLASH); } - if ( radiusEnts[i]->client - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST ) - { + if (radiusEnts[i]->client && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && radiusEnts[i]->client->NPC_class != CLASS_ATST) { float throwStr = 0.0f; - if ( g_spskill->integer > 1 ) - { - throwStr = 10.0f+((radius-dist)/2.0f); - if ( throwStr > 150.0f ) - { + if (g_spskill->integer > 1) { + throwStr = 10.0f + ((radius - dist) / 2.0f); + if (throwStr > 150.0f) { throwStr = 150.0f; } - } - else - { - throwStr = 10.0f+((radius-dist)/4.0f); - if ( throwStr > 85.0f ) - { + } else { + throwStr = 10.0f + ((radius - dist) / 4.0f); + if (throwStr > 85.0f) { throwStr = 85.0f; } } entDir[2] += 0.1f; - VectorNormalize( entDir ); - G_Throw( radiusEnts[i], entDir, throwStr ); - if ( radiusEnts[i]->health > 0 ) - { - if ( dist < halfRad - || radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//within range of my fist or within ground-shaking range and not in the air - G_Knockdown( radiusEnts[i], NPC, vec3_origin, 500, qtrue ); + VectorNormalize(entDir); + G_Throw(radiusEnts[i], entDir, throwStr); + if (radiusEnts[i]->health > 0) { + if (dist < halfRad || radiusEnts[i]->client->ps.groundEntityNum != + ENTITYNUM_NONE) { // within range of my fist or within ground-shaking range and not in the air + G_Knockdown(radiusEnts[i], NPC, vec3_origin, 500, qtrue); } } } @@ -517,116 +424,92 @@ void Tavion_ScepterSlam( void ) } } -void Tavion_StartScepterBeam( void ) -{ - G_PlayEffect( G_EffectIndex( "scepter/beam_warmup.efx" ), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 0, qtrue ); - G_SoundOnEnt( NPC, CHAN_ITEM, "sound/weapons/scepter/beam_warmup.wav" ); +void Tavion_StartScepterBeam(void) { + G_PlayEffect(G_EffectIndex("scepter/beam_warmup.efx"), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 0, qtrue); + G_SoundOnEnt(NPC, CHAN_ITEM, "sound/weapons/scepter/beam_warmup.wav"); NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SCEPTER_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SCEPTER_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer += 200; NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_time = NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); } -void Tavion_StartScepterSlam( void ) -{ - G_PlayEffect( G_EffectIndex( "scepter/slam_warmup.efx" ), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 0, qtrue ); - G_SoundOnEnt( NPC, CHAN_ITEM, "sound/weapons/scepter/slam_warmup.wav" ); +void Tavion_StartScepterSlam(void) { + G_PlayEffect(G_EffectIndex("scepter/slam_warmup.efx"), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 0, qtrue); + G_SoundOnEnt(NPC, CHAN_ITEM, "sound/weapons/scepter/slam_warmup.wav"); NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TAVION_SCEPTERGROUND, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TAVION_SCEPTERGROUND, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_time = NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); NPC->count = 0; } -void Tavion_SithSwordRecharge( void ) -{ - if ( NPC->client->ps.torsoAnim != BOTH_TAVION_SWORDPOWER - && NPC->count - && TIMER_Done( NPC, "rechargeDebounce" ) - && NPC->weaponModel[0] != -1 ) - { - NPC->s.loopSound = G_SoundIndex( "sound/weapons/scepter/recharge.wav" ); - int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); +void Tavion_SithSwordRecharge(void) { + if (NPC->client->ps.torsoAnim != BOTH_TAVION_SWORDPOWER && NPC->count && TIMER_Done(NPC, "rechargeDebounce") && NPC->weaponModel[0] != -1) { + NPC->s.loopSound = G_SoundIndex("sound/weapons/scepter/recharge.wav"); + int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TAVION_SWORDPOWER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_PlayEffect( G_EffectIndex( "scepter/recharge.efx" ), NPC->weaponModel[0], boltIndex, NPC->s.number, NPC->currentOrigin, NPC->client->ps.torsoAnimTimer, qtrue ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TAVION_SWORDPOWER, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_PlayEffect(G_EffectIndex("scepter/recharge.efx"), NPC->weaponModel[0], boltIndex, NPC->s.number, NPC->currentOrigin, NPC->client->ps.torsoAnimTimer, + qtrue); NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_time = NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.powerups[PW_INVINCIBLE] = level.time + NPC->client->ps.torsoAnimTimer + 10000; - G_PlayEffect( G_EffectIndex( "scepter/invincibility.efx" ), NPC->playerModel, 0, NPC->s.number, NPC->currentOrigin, NPC->client->ps.torsoAnimTimer + 10000, qfalse ); - TIMER_Set( NPC, "rechargeDebounce", NPC->client->ps.torsoAnimTimer + 10000 + Q_irand(10000,20000) ); + G_PlayEffect(G_EffectIndex("scepter/invincibility.efx"), NPC->playerModel, 0, NPC->s.number, NPC->currentOrigin, NPC->client->ps.torsoAnimTimer + 10000, + qfalse); + TIMER_Set(NPC, "rechargeDebounce", NPC->client->ps.torsoAnimTimer + 10000 + Q_irand(10000, 20000)); NPC->count--; - //now you have a chance of killing her + // now you have a chance of killing her NPC->flags &= ~FL_UNDYING; } } //====================================================================================== -//END TAVION BOSS +// END TAVION BOSS //====================================================================================== -void Jedi_Cloak( gentity_t *self ) -{ - if ( self && self->client ) - { - if ( !self->client->ps.powerups[PW_CLOAKED] ) - {//cloak +void Jedi_Cloak(gentity_t *self) { + if (self && self->client) { + if (!self->client->ps.powerups[PW_CLOAKED]) { // cloak self->client->ps.powerups[PW_CLOAKED] = Q3_INFINITE; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: debounce attacks? - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav" ); + // FIXME: debounce attacks? + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav"); } } } -void Jedi_Decloak( gentity_t *self ) -{ - if ( self && self->client ) - { - if ( self->client->ps.powerups[PW_CLOAKED] ) - {//Uncloak +void Jedi_Decloak(gentity_t *self) { + if (self && self->client) { + if (self->client->ps.powerups[PW_CLOAKED]) { // Uncloak self->client->ps.powerups[PW_CLOAKED] = 0; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav" ); + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav"); } } } -void Jedi_CheckCloak( void ) -{ - if ( NPC - && NPC->client - && NPC->client->NPC_class == CLASS_SHADOWTROOPER - && Q_stricmpn("shadowtrooper", NPC->NPC_type, 13 ) == 0 ) - { - if ( NPC->client->ps.SaberActive() || - NPC->health <= 0 || - NPC->client->ps.saberInFlight || - (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) || - (NPC->client->ps.eFlags&EF_FORCE_DRAINED) || - NPC->painDebounceTime > level.time ) - {//can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped - Jedi_Decloak( NPC ); - } - else if ( NPC->health > 0 - && !NPC->client->ps.saberInFlight - && !(NPC->client->ps.eFlags&EF_FORCE_GRIPPED) - && !(NPC->client->ps.eFlags&EF_FORCE_DRAINED) - && NPC->painDebounceTime < level.time ) - {//still alive, have saber in hand, not taking pain and not being gripped - Jedi_Cloak( NPC ); +void Jedi_CheckCloak(void) { + if (NPC && NPC->client && NPC->client->NPC_class == CLASS_SHADOWTROOPER && Q_stricmpn("shadowtrooper", NPC->NPC_type, 13) == 0) { + if (NPC->client->ps.SaberActive() || NPC->health <= 0 || NPC->client->ps.saberInFlight || (NPC->client->ps.eFlags & EF_FORCE_GRIPPED) || + (NPC->client->ps.eFlags & EF_FORCE_DRAINED) || + NPC->painDebounceTime > level.time) { // can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped + Jedi_Decloak(NPC); + } else if (NPC->health > 0 && !NPC->client->ps.saberInFlight && !(NPC->client->ps.eFlags & EF_FORCE_GRIPPED) && + !(NPC->client->ps.eFlags & EF_FORCE_DRAINED) && + NPC->painDebounceTime < level.time) { // still alive, have saber in hand, not taking pain and not being gripped + Jedi_Cloak(NPC); } } } @@ -635,114 +518,94 @@ void Jedi_CheckCloak( void ) AGGRESSION ========================================================================================== */ -static void Jedi_Aggression( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +static void Jedi_Aggression(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == TEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == TEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive - if ( self->client->NPC_class == CLASS_DESANN ) - { + } else { // bad guys are more aggressive + if (self->client->NPC_class == CLASS_DESANN) { upper_threshold = 20; lower_threshold = 5; - } - else - { + } else { upper_threshold = 10; lower_threshold = 3; } } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } - //Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); + // Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); } -static void Jedi_AggressionErosion( int amt ) -{ - if ( TIMER_Done( NPC, "roamTime" ) ) - {//the longer we're not alerted and have no enemy, the more our aggression goes down - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - Jedi_Aggression( NPC, amt ); +static void Jedi_AggressionErosion(int amt) { + if (TIMER_Done(NPC, "roamTime")) { // the longer we're not alerted and have no enemy, the more our aggression goes down + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + Jedi_Aggression(NPC, amt); } - if ( NPCInfo->stats.aggression < 4 || (NPCInfo->stats.aggression < 6&&NPC->client->NPC_class == CLASS_DESANN)) - {//turn off the saber - WP_DeactivateSaber( NPC ); + if (NPCInfo->stats.aggression < 4 || (NPCInfo->stats.aggression < 6 && NPC->client->NPC_class == CLASS_DESANN)) { // turn off the saber + WP_DeactivateSaber(NPC); } } -void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ) -{ +void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy) { float healthAggression; float weaponAggression; - switch( enemy->s.weapon ) - { + switch (enemy->s.weapon) { case WP_SABER: - healthAggression = (float)self->health/200.0f*6.0f; - weaponAggression = 7;//go after him + healthAggression = (float)self->health / 200.0f * 6.0f; + weaponAggression = 7; // go after him break; case WP_BLASTER: - if ( DistanceSquared( self->currentOrigin, enemy->currentOrigin ) < 65536 )//256 squared - { - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 8;//go after him - } - else + if (DistanceSquared(self->currentOrigin, enemy->currentOrigin) < 65536) // 256 squared { - healthAggression = 8.0f - ((float)self->health/200.0f*8.0f); - weaponAggression = 2;//hang back for a second + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 8; // go after him + } else { + healthAggression = 8.0f - ((float)self->health / 200.0f * 8.0f); + weaponAggression = 2; // hang back for a second } break; default: - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 6;//approach + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 6; // approach break; } - //Average these with current aggression - int newAggression = ceil( (healthAggression + weaponAggression + (float)self->NPC->stats.aggression )/3.0f); - //Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); - Jedi_Aggression( self, newAggression - self->NPC->stats.aggression ); + // Average these with current aggression + int newAggression = ceil((healthAggression + weaponAggression + (float)self->NPC->stats.aggression) / 3.0f); + // Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); + Jedi_Aggression(self, newAggression - self->NPC->stats.aggression); - //don't taunt right away - TIMER_Set( self, "chatter", Q_irand( 4000, 7000 ) ); + // don't taunt right away + TIMER_Set(self, "chatter", Q_irand(4000, 7000)); } -static void Jedi_Rage( void ) -{ - Jedi_Aggression( NPC, 10 - NPCInfo->stats.aggression + Q_irand( -2, 2 ) ); - TIMER_Set( NPC, "roamTime", 0 ); - TIMER_Set( NPC, "chatter", 0 ); - TIMER_Set( NPC, "walking", 0 ); - TIMER_Set( NPC, "taunting", 0 ); - TIMER_Set( NPC, "jumpChaseDebounce", 0 ); - TIMER_Set( NPC, "movenone", 0 ); - TIMER_Set( NPC, "movecenter", 0 ); - TIMER_Set( NPC, "noturn", 0 ); - ForceRage( NPC ); +static void Jedi_Rage(void) { + Jedi_Aggression(NPC, 10 - NPCInfo->stats.aggression + Q_irand(-2, 2)); + TIMER_Set(NPC, "roamTime", 0); + TIMER_Set(NPC, "chatter", 0); + TIMER_Set(NPC, "walking", 0); + TIMER_Set(NPC, "taunting", 0); + TIMER_Set(NPC, "jumpChaseDebounce", 0); + TIMER_Set(NPC, "movenone", 0); + TIMER_Set(NPC, "movecenter", 0); + TIMER_Set(NPC, "noturn", 0); + ForceRage(NPC); } -void Jedi_RageStop( gentity_t *self ) -{ - if ( self->NPC ) - {//calm down and back off - TIMER_Set( self, "roamTime", 0 ); - Jedi_Aggression( self, Q_irand( -5, 0 ) ); +void Jedi_RageStop(gentity_t *self) { + if (self->NPC) { // calm down and back off + TIMER_Set(self, "roamTime", 0); + Jedi_Aggression(self, Q_irand(-5, 0)); } } /* @@ -751,51 +614,34 @@ SPEAKING ========================================================================================== */ -static qboolean Jedi_BattleTaunt( void ) -{ - if ( TIMER_Done( NPC, "chatter" ) - && !Q_irand( 0, 3 ) - && NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) - { +static qboolean Jedi_BattleTaunt(void) { + if (TIMER_Done(NPC, "chatter") && !Q_irand(0, 3) && NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPC->client->playerTeam] < level.time) { int event = -1; - if ( NPC->enemy - && NPC->enemy->client - && (NPC->enemy->client->NPC_class == CLASS_RANCOR - || NPC->enemy->client->NPC_class == CLASS_WAMPA - || NPC->enemy->client->NPC_class == CLASS_SAND_CREATURE) ) - {//never taunt these mindless creatures - //NOTE: howlers? tusken? etc? Only reborn? - } - else - { - if ( NPC->client->playerTeam == TEAM_PLAYER - && NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//a jedi fighting a jedi - training - if ( NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) - {//only trainer taunts + if (NPC->enemy && NPC->enemy->client && + (NPC->enemy->client->NPC_class == CLASS_RANCOR || NPC->enemy->client->NPC_class == CLASS_WAMPA || + NPC->enemy->client->NPC_class == CLASS_SAND_CREATURE)) { // never taunt these mindless creatures + // NOTE: howlers? tusken? etc? Only reborn? + } else { + if (NPC->client->playerTeam == TEAM_PLAYER && NPC->enemy && NPC->enemy->client && + NPC->enemy->client->NPC_class == CLASS_JEDI) { // a jedi fighting a jedi - training + if (NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER) { // only trainer taunts event = EV_TAUNT1; } + } else { // reborn or a jedi fighting an enemy + event = Q_irand(EV_TAUNT1, EV_TAUNT3); } - else - {//reborn or a jedi fighting an enemy - event = Q_irand( EV_TAUNT1, EV_TAUNT3 ); - } - if ( event != -1 ) - { - G_AddVoiceEvent( NPC, event, 3000 ); + if (event != -1) { + G_AddVoiceEvent(NPC, event, 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 6000; - if ( (NPCInfo->aiFlags&NPCAI_ROSH) ) - { - TIMER_Set( NPC, "chatter", Q_irand( 8000, 20000 ) ); - } - else - { - TIMER_Set( NPC, "chatter", Q_irand( 5000, 10000 ) ); + if ((NPCInfo->aiFlags & NPCAI_ROSH)) { + TIMER_Set(NPC, "chatter", Q_irand(8000, 20000)); + } else { + TIMER_Set(NPC, "chatter", Q_irand(5000, 10000)); } - if ( NPC->enemy && NPC->enemy->NPC && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//Have the enemy jedi say something in response when I'm done? + if (NPC->enemy && NPC->enemy->NPC && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && + NPC->enemy->client->NPC_class == CLASS_JEDI) { // Have the enemy jedi say something in response when I'm done? } return qtrue; } @@ -809,86 +655,72 @@ static qboolean Jedi_BattleTaunt( void ) MOVEMENT ========================================================================================== */ -static qboolean Jedi_ClearPathToSpot( vec3_t dest, int impactEntNum ) -{ - trace_t trace; - vec3_t mins, start, end, dir; - float dist, drop; +static qboolean Jedi_ClearPathToSpot(vec3_t dest, int impactEntNum) { + trace_t trace; + vec3_t mins, start, end, dir; + float dist, drop; - //Offset the step height - VectorSet( mins, NPC->mins[0], NPC->mins[1], NPC->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, NPC->mins[0], NPC->mins[1], NPC->mins[2] + STEPSIZE); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, dest, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->currentOrigin, mins, NPC->maxs, dest, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); - //Do a simple check - if ( trace.allsolid || trace.startsolid ) - {//inside solid + // Do a simple check + if (trace.allsolid || trace.startsolid) { // inside solid return qfalse; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum ) - {//hit what we're going after + if (trace.fraction < 1.0f) { // hit something + if (impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum) { // hit what we're going after return qtrue; - } - else - { + } else { return qfalse; } } - //otherwise, clear path in a straight line. - //Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. - VectorSubtract( dest, NPC->currentOrigin, dir ); - dist = VectorNormalize( dir ); - if ( dest[2] > NPC->currentOrigin[2] ) - {//going up, check for steps + // otherwise, clear path in a straight line. + // Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. + VectorSubtract(dest, NPC->currentOrigin, dir); + dist = VectorNormalize(dir); + if (dest[2] > NPC->currentOrigin[2]) { // going up, check for steps drop = STEPSIZE; - } - else - {//going down or level, check for moderate drops + } else { // going down or level, check for moderate drops drop = 64; } - for ( float i = NPC->maxs[0]*2; i < dist; i += NPC->maxs[0]*2 ) - {//FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? - VectorMA( NPC->currentOrigin, i, dir, start ); - VectorCopy( start, end ); + for (float i = NPC->maxs[0] * 2; i < dist; + i += NPC->maxs[0] * 2) { // FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? + VectorMA(NPC->currentOrigin, i, dir, start); + VectorCopy(start, end); end[2] -= drop; - gi.trace( &trace, start, mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 );//NPC->mins? - if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) - {//good to go + gi.trace(&trace, start, mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); // NPC->mins? + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) { // good to go continue; } - //no floor here! (or a long drop?) + // no floor here! (or a long drop?) return qfalse; } - //we made it! + // we made it! return qtrue; } -qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) -{ - vec3_t forward, right, testPos, angles, mins; - trace_t trace; - float fwdDist, rtDist; - float bottom_max = -STEPSIZE*4 - 1; - - if ( !forwardmove && !rightmove ) - {//not even moving - //gi.Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); +qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset) { + vec3_t forward, right, testPos, angles, mins; + trace_t trace; + float fwdDist, rtDist; + float bottom_max = -STEPSIZE * 4 - 1; + + if (!forwardmove && !rightmove) { // not even moving + // gi.Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); return qtrue; } - if ( ucmd.upmove > 0 || NPC->client->ps.forceJumpCharge ) - {//Going to jump - //gi.Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); + if (ucmd.upmove > 0 || NPC->client->ps.forceJumpCharge) { // Going to jump + // gi.Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); return qtrue; } - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//in the air - //gi.Printf( "%d skipping walk-cliff check (in air)\n", level.time ); + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // in the air + // gi.Printf( "%d skipping walk-cliff check (in air)\n", level.time ); return qtrue; } /* @@ -904,81 +736,71 @@ qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) } */ - //FIXME: to really do this right, we'd have to actually do a pmove to predict where we're - //going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows - //NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? - VectorCopy( NPC->mins, mins ); + // FIXME: to really do this right, we'd have to actually do a pmove to predict where we're + // going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows + // NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? + VectorCopy(NPC->mins, mins); mins[2] += STEPSIZE; angles[PITCH] = angles[ROLL] = 0; - angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); - fwdDist = ((float)forwardmove)/2.0f; - rtDist = ((float)rightmove)/2.0f; - VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); - VectorMA( testPos, rtDist, right, testPos ); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//hmm, trace started inside this brush... how do we decide if we should continue? - //FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? - if ( reset ) - { + angles[YAW] = NPC->client->ps.viewangles[YAW]; // Add ucmd.angles[YAW]? + AngleVectors(angles, forward, right, NULL); + fwdDist = ((float)forwardmove) / 2.0f; + rtDist = ((float)rightmove) / 2.0f; + VectorMA(NPC->currentOrigin, fwdDist, forward, testPos); + VectorMA(testPos, rtDist, right, testPos); + gi.trace(&trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid) { // hmm, trace started inside this brush... how do we decide if we should continue? + // FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? + if (reset) { trace.fraction = 1.0f; } - VectorCopy( testPos, trace.endpos ); - //return qtrue; + VectorCopy(testPos, trace.endpos); + // return qtrue; } - if ( trace.fraction < 0.6 ) - {//Going to bump into something very close, don't move, just turn - if ( (NPC->enemy && trace.entityNum == NPC->enemy->s.number) || (NPCInfo->goalEntity && trace.entityNum == NPCInfo->goalEntity->s.number) ) - {//okay to bump into enemy or goal - //gi.Printf( "%d bump into enemy/goal okay\n", level.time ); + if (trace.fraction < 0.6) { // Going to bump into something very close, don't move, just turn + if ((NPC->enemy && trace.entityNum == NPC->enemy->s.number) || + (NPCInfo->goalEntity && trace.entityNum == NPCInfo->goalEntity->s.number)) { // okay to bump into enemy or goal + // gi.Printf( "%d bump into enemy/goal okay\n", level.time ); return qtrue; - } - else if ( reset ) - {//actually want to screw with the ucmd - //gi.Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); + } else if (reset) { // actually want to screw with the ucmd + // gi.Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); ucmd.forwardmove = 0; ucmd.rightmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } return qfalse; } - if ( NPCInfo->goalEntity ) - { - if ( NPCInfo->goalEntity->currentOrigin[2] < NPC->currentOrigin[2] ) - {//goal is below me, okay to step off at least that far plus stepheight + if (NPCInfo->goalEntity) { + if (NPCInfo->goalEntity->currentOrigin[2] < NPC->currentOrigin[2]) { // goal is below me, okay to step off at least that far plus stepheight bottom_max += NPCInfo->goalEntity->currentOrigin[2] - NPC->currentOrigin[2]; } } - VectorCopy( trace.endpos, testPos ); + VectorCopy(trace.endpos, testPos); testPos[2] += bottom_max; - gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); - //FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? - //OR: just put NPC clip brushes on these edges (still fall through when die) + // FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? + // OR: just put NPC clip brushes on these edges (still fall through when die) - if ( trace.allsolid || trace.startsolid ) - {//Not going off a cliff - //gi.Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); + if (trace.allsolid || trace.startsolid) { // Not going off a cliff + // gi.Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); return qtrue; } - if ( trace.fraction < 1.0 ) - {//Not going off a cliff - //FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... - //gi.Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); + if (trace.fraction < 1.0) { // Not going off a cliff + // FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... + // gi.Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); return qtrue; } - //going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? - if ( reset ) - {//actually want to screw with the ucmd - //gi.Printf( "%d avoiding walk off cliff\n", level.time ); - ucmd.forwardmove *= -1.0;//= 0; - ucmd.rightmove *= -1.0;//= 0; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + // going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? + if (reset) { // actually want to screw with the ucmd + // gi.Printf( "%d avoiding walk off cliff\n", level.time ); + ucmd.forwardmove *= -1.0; //= 0; + ucmd.rightmove *= -1.0; //= 0; + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); } return qfalse; } @@ -988,9 +810,8 @@ Jedi_HoldPosition ------------------------- */ -static void Jedi_HoldPosition( void ) -{ - //NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; +static void Jedi_HoldPosition(void) { + // NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; NPCInfo->goalEntity = NULL; /* @@ -1007,60 +828,51 @@ Jedi_Move ------------------------- */ -static qboolean Jedi_Move( gentity_t *goal, qboolean retreat ) -{ +static qboolean Jedi_Move(gentity_t *goal, qboolean retreat) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = goal; - qboolean moved = NPC_MoveToGoal( qtrue ); - if (!moved) - { + qboolean moved = NPC_MoveToGoal(qtrue); + if (!moved) { Jedi_HoldPosition(); } // NAV_TODO: Put Retreate Behavior Here - //FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy - if ( retreat ) - {//FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? + // FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy + if (retreat) { // FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? ucmd.forwardmove *= -1; ucmd.rightmove *= -1; - //we clear moveDir here so the Jedi's ucmd-driven movement does do not enter checks - VectorClear( NPC->client->ps.moveDir ); - //VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + // we clear moveDir here so the Jedi's ucmd-driven movement does do not enter checks + VectorClear(NPC->client->ps.moveDir); + // VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); } return moved; } -static qboolean Jedi_Hunt( void ) -{ - //gi.Printf( "Hunting\n" ); - //if we're at all interested in fighting, go after him - if ( NPCInfo->stats.aggression > 1 ) - {//approach enemy +static qboolean Jedi_Hunt(void) { + // gi.Printf( "Hunting\n" ); + // if we're at all interested in fighting, go after him + if (NPCInfo->stats.aggression > 1) { // approach enemy NPCInfo->combatMove = qtrue; - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else - { - /* if ( NPCInfo->goalEntity == NULL ) - {//hunt - NPCInfo->goalEntity = NPC->enemy; - } - if (NPC->client && NPC->client->NPC_class==CLASS_BOBAFETT) - { - NPCInfo->goalEntity = NPC->enemy; - }*/ -// NPC_SetMoveGoal(NPC, NPC->enemy->currentOrigin, 40.0f, false, 0, NPC->enemy); + } else { + /* if ( NPCInfo->goalEntity == NULL ) + {//hunt + NPCInfo->goalEntity = NPC->enemy; + } + if (NPC->client && NPC->client->NPC_class==CLASS_BOBAFETT) + { + NPCInfo->goalEntity = NPC->enemy; + }*/ + // NPC_SetMoveGoal(NPC, NPC->enemy->currentOrigin, 40.0f, false, 0, NPC->enemy); NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 40.0f; - //Jedi_Move( NPC->enemy, qfalse ); - if ( NPC_MoveToGoal( qfalse ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // Jedi_Move( NPC->enemy, qfalse ); + if (NPC_MoveToGoal(qfalse)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -1086,103 +898,76 @@ static qboolean Jedi_Track( void ) } */ -static void Jedi_StartBackOff( void ) -{ - TIMER_Set( NPC, "roamTime", -level.time ); - TIMER_Set( NPC, "strafeLeft", -level.time ); - TIMER_Set( NPC, "strafeRight", -level.time ); - TIMER_Set( NPC, "walking", -level.time ); - TIMER_Set( NPC, "moveforward", -level.time ); - TIMER_Set( NPC, "movenone", -level.time ); - TIMER_Set( NPC, "moveright", -level.time ); - TIMER_Set( NPC, "moveleft", -level.time ); - TIMER_Set( NPC, "movecenter", -level.time ); - TIMER_Set( NPC, "moveback", 1000 ); +static void Jedi_StartBackOff(void) { + TIMER_Set(NPC, "roamTime", -level.time); + TIMER_Set(NPC, "strafeLeft", -level.time); + TIMER_Set(NPC, "strafeRight", -level.time); + TIMER_Set(NPC, "walking", -level.time); + TIMER_Set(NPC, "moveforward", -level.time); + TIMER_Set(NPC, "movenone", -level.time); + TIMER_Set(NPC, "moveright", -level.time); + TIMER_Set(NPC, "moveleft", -level.time); + TIMER_Set(NPC, "movecenter", -level.time); + TIMER_Set(NPC, "moveback", 1000); ucmd.forwardmove = -127; ucmd.rightmove = 0; ucmd.upmove = 0; - if ( d_JediAI->integer ) - { - Com_Printf( "%s backing off from spin attack!\n", NPC->NPC_type ); + if (d_JediAI->integer) { + Com_Printf("%s backing off from spin attack!\n", NPC->NPC_type); } - TIMER_Set( NPC, "specialEvasion", 1000 ); - TIMER_Set( NPC, "noRetreat", -level.time ); - if ( PM_PainAnim(NPC->client->ps.legsAnim) ) - { + TIMER_Set(NPC, "specialEvasion", 1000); + TIMER_Set(NPC, "noRetreat", -level.time); + if (PM_PainAnim(NPC->client->ps.legsAnim)) { NPC->client->ps.legsAnimTimer = 0; } - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } -static qboolean Jedi_Retreat( void ) -{ - if ( !TIMER_Done( NPC, "noRetreat" ) ) - {//don't actually move +static qboolean Jedi_Retreat(void) { + if (!TIMER_Done(NPC, "noRetreat")) { // don't actually move return qfalse; } - //FIXME: when retreating, we should probably see if we can retreat - //in the direction we want. If not...? Evade? - //gi.Printf( "Retreating\n" ); - return Jedi_Move( NPC->enemy, qtrue ); + // FIXME: when retreating, we should probably see if we can retreat + // in the direction we want. If not...? Evade? + // gi.Printf( "Retreating\n" ); + return Jedi_Move(NPC->enemy, qtrue); } -static qboolean Jedi_Advance( void ) -{ - if ( (NPCInfo->aiFlags&NPCAI_HEAL_ROSH) ) - { +static qboolean Jedi_Advance(void) { + if ((NPCInfo->aiFlags & NPCAI_HEAL_ROSH)) { return qfalse; } - if ( !NPC->client->ps.saberInFlight ) - { + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.SaberActivate(); } - //gi.Printf( "Advancing\n" ); - return Jedi_Move( NPC->enemy, qfalse ); + // gi.Printf( "Advancing\n" ); + return Jedi_Move(NPC->enemy, qfalse); - //TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( NPC, "duck", 0 ); + // TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); + // TIMER_Set( NPC, "duck", 0 ); } -static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) -{ - if ( !self || !self->client ) - { +static void Jedi_AdjustSaberAnimLevel(gentity_t *self, int newLevel) { + if (!self || !self->client) { return; } - //FIXME: each NPC shold have a unique pattern of behavior for the order in which they - if ( self->client->playerTeam == TEAM_ENEMY ) - { - //FIXME: CLASS_CULTIST + self->NPC->rank instead of these Q_stricmps? - if ( !Q_stricmp( "cultist_saber_all", self->NPC_type ) - || !Q_stricmp( "cultist_saber_all_throw", self->NPC_type ) ) - {//use any, regardless of rank, etc. - } - else if ( !Q_stricmp( "cultist_saber", self->NPC_type ) - || !Q_stricmp( "cultist_saber_throw", self->NPC_type ) ) - {//fast only + // FIXME: each NPC shold have a unique pattern of behavior for the order in which they + if (self->client->playerTeam == TEAM_ENEMY) { + // FIXME: CLASS_CULTIST + self->NPC->rank instead of these Q_stricmps? + if (!Q_stricmp("cultist_saber_all", self->NPC_type) || !Q_stricmp("cultist_saber_all_throw", self->NPC_type)) { // use any, regardless of rank, etc. + } else if (!Q_stricmp("cultist_saber", self->NPC_type) || !Q_stricmp("cultist_saber_throw", self->NPC_type)) { // fast only self->client->ps.saberAnimLevel = SS_FAST; - } - else if ( !Q_stricmp( "cultist_saber_med", self->NPC_type ) - || !Q_stricmp( "cultist_saber_med_throw", self->NPC_type ) ) - {//med only + } else if (!Q_stricmp("cultist_saber_med", self->NPC_type) || !Q_stricmp("cultist_saber_med_throw", self->NPC_type)) { // med only self->client->ps.saberAnimLevel = SS_MEDIUM; - } - else if ( !Q_stricmp( "cultist_saber_strong", self->NPC_type ) - || !Q_stricmp( "cultist_saber_strong_throw", self->NPC_type ) ) - {//strong only + } else if (!Q_stricmp("cultist_saber_strong", self->NPC_type) || !Q_stricmp("cultist_saber_strong_throw", self->NPC_type)) { // strong only self->client->ps.saberAnimLevel = SS_STRONG; - } - else - {//regular reborn - if ( self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG ) - {//grunt and fencer always uses quick attacks + } else { // regular reborn + if (self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG) { // grunt and fencer always uses quick attacks self->client->ps.saberAnimLevel = SS_FAST; return; } - if ( self->NPC->rank == RANK_CREWMAN - || self->NPC->rank == RANK_ENSIGN ) - {//acrobat & force-users always use medium attacks + if (self->NPC->rank == RANK_CREWMAN || self->NPC->rank == RANK_ENSIGN) { // acrobat & force-users always use medium attacks self->client->ps.saberAnimLevel = SS_MEDIUM; return; } @@ -1195,147 +980,109 @@ static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) */ } } - if ( newLevel < SS_FAST ) - { + if (newLevel < SS_FAST) { newLevel = SS_FAST; - } - else if ( newLevel > SS_STAFF ) - { + } else if (newLevel > SS_STAFF) { newLevel = SS_STAFF; } - //use the different attacks, how often they switch and under what circumstances - if ( !(self->client->ps.saberStylesKnown&(1<client->ps.saberStylesKnown & (1 << newLevel))) { // don't know that style, sorry return; - } - else - {//go ahead and set it + } else { // go ahead and set it self->client->ps.saberAnimLevel = newLevel; } - if ( d_JediAI->integer ) - { - switch ( self->client->ps.saberAnimLevel ) - { + if (d_JediAI->integer) { + switch (self->client->ps.saberAnimLevel) { case SS_FAST: - gi.Printf( S_COLOR_GREEN"%s Saber Attack Set: fast\n", self->NPC_type ); + gi.Printf(S_COLOR_GREEN "%s Saber Attack Set: fast\n", self->NPC_type); break; case SS_MEDIUM: - gi.Printf( S_COLOR_YELLOW"%s Saber Attack Set: medium\n", self->NPC_type ); + gi.Printf(S_COLOR_YELLOW "%s Saber Attack Set: medium\n", self->NPC_type); break; case SS_STRONG: - gi.Printf( S_COLOR_RED"%s Saber Attack Set: strong\n", self->NPC_type ); + gi.Printf(S_COLOR_RED "%s Saber Attack Set: strong\n", self->NPC_type); break; } } } -static void Jedi_CheckDecreaseSaberAnimLevel( void ) -{ - if ( !NPC->client->ps.weaponTime && !(ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS)) ) - {//not attacking - if ( TIMER_Done( NPC, "saberLevelDebounce" ) && !Q_irand( 0, 10 ) ) - { - //Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//drop - Jedi_AdjustSaberAnimLevel( NPC, Q_irand( SS_FAST, SS_STRONG ));//random - TIMER_Set( NPC, "saberLevelDebounce", Q_irand( 3000, 10000 ) ); +static void Jedi_CheckDecreaseSaberAnimLevel(void) { + if (!NPC->client->ps.weaponTime && !(ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS))) { // not attacking + if (TIMER_Done(NPC, "saberLevelDebounce") && !Q_irand(0, 10)) { + // Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//drop + Jedi_AdjustSaberAnimLevel(NPC, Q_irand(SS_FAST, SS_STRONG)); // random + TIMER_Set(NPC, "saberLevelDebounce", Q_irand(3000, 10000)); } - } - else - { - TIMER_Set( NPC, "saberLevelDebounce", Q_irand( 1000, 5000 ) ); + } else { + TIMER_Set(NPC, "saberLevelDebounce", Q_irand(1000, 5000)); } } -static qboolean Jedi_DecideKick( void ) -{ - if ( PM_InKnockDown( &NPC->client->ps ) ) - { +static qboolean Jedi_DecideKick(void) { + if (PM_InKnockDown(&NPC->client->ps)) { return qfalse; } - if ( PM_InRoll( &NPC->client->ps ) ) - { + if (PM_InRoll(&NPC->client->ps)) { return qfalse; } - if ( PM_InGetUp( &NPC->client->ps ) ) - { + if (PM_InGetUp(&NPC->client->ps)) { return qfalse; } - if ( !NPC->enemy || (NPC->enemy->s.number < MAX_CLIENTS&&NPC->enemy->health<=0) ) - {//have no enemy or enemy is a dead player + if (!NPC->enemy || (NPC->enemy->s.number < MAX_CLIENTS && NPC->enemy->health <= 0)) { // have no enemy or enemy is a dead player return qfalse; } - //FIXME: check FP_SABER_OFFENSE? - //FIXME: check for saber staff style only? - //FIXME: g_spskill? - if ( Q_irand( 0, RANK_CAPTAIN+5 ) > NPCInfo->rank ) - {//low chance, based on rank + // FIXME: check FP_SABER_OFFENSE? + // FIXME: check for saber staff style only? + // FIXME: g_spskill? + if (Q_irand(0, RANK_CAPTAIN + 5) > NPCInfo->rank) { // low chance, based on rank return qfalse; } - if ( Q_irand( 0, 10 ) > NPCInfo->stats.aggression ) - {//the madder the better + if (Q_irand(0, 10) > NPCInfo->stats.aggression) { // the madder the better return qfalse; } - if ( !TIMER_Done( NPC, "kickDebounce" ) ) - {//just did one + if (!TIMER_Done(NPC, "kickDebounce")) { // just did one return qfalse; } - if ( NPC->client->ps.weapon == WP_SABER ) - { - if ( (NPC->client->ps.saber[0].saberFlags&SFL_NO_KICKS) ) - { + if (NPC->client->ps.weapon == WP_SABER) { + if ((NPC->client->ps.saber[0].saberFlags & SFL_NO_KICKS)) { return qfalse; - } - else if ( NPC->client->ps.dualSabers - && (NPC->client->ps.saber[1].saberFlags&SFL_NO_KICKS) ) - { + } else if (NPC->client->ps.dualSabers && (NPC->client->ps.saber[1].saberFlags & SFL_NO_KICKS)) { return qfalse; } } - //go for it! + // go for it! return qtrue; } -void Kyle_GrabEnemy( void ) -{ - WP_SabersCheckLock2( NPC, NPC->enemy, (sabersLockMode_t)Q_irand(LOCK_KYLE_GRAB1,LOCK_KYLE_GRAB2) );//LOCK_KYLE_GRAB3 - TIMER_Set( NPC, "grabEnemyDebounce", NPC->client->ps.torsoAnimTimer + Q_irand( 4000, 20000 ) ); +void Kyle_GrabEnemy(void) { + WP_SabersCheckLock2(NPC, NPC->enemy, (sabersLockMode_t)Q_irand(LOCK_KYLE_GRAB1, LOCK_KYLE_GRAB2)); // LOCK_KYLE_GRAB3 + TIMER_Set(NPC, "grabEnemyDebounce", NPC->client->ps.torsoAnimTimer + Q_irand(4000, 20000)); } -void Kyle_TryGrab( void ) -{ - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); +void Kyle_TryGrab(void) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer += 200; NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; NPC->client->ps.saberMove = NPC->client->ps.saberMoveNext = LS_READY; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); ucmd.rightmove = ucmd.forwardmove = ucmd.upmove = 0; NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; - //WTF? + // WTF? NPC->client->ps.SaberDeactivate(); } -qboolean Kyle_CanDoGrab( void ) -{ - if ( NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags&1) ) - {//Boss Kyle - if ( NPC->enemy && NPC->enemy->client ) - {//have a valid enemy - if ( TIMER_Done( NPC, "grabEnemyDebounce" ) ) - {//okay to grab again - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE - && NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//me and enemy are on ground - if ( !PM_InOnGroundAnim( &NPC->enemy->client->ps ) ) - { - if ( (NPC->client->ps.weaponTime <= 200||NPC->client->ps.torsoAnim==BOTH_KYLE_GRAB) - && !NPC->client->ps.saberInFlight ) - { - if ( fabs(NPC->enemy->currentOrigin[2]-NPC->currentOrigin[2])<=8.0f ) - {//close to same level of ground - if ( DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) <= 10000.0f ) - { +qboolean Kyle_CanDoGrab(void) { + if (NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1)) { // Boss Kyle + if (NPC->enemy && NPC->enemy->client) { // have a valid enemy + if (TIMER_Done(NPC, "grabEnemyDebounce")) { // okay to grab again + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE && + NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // me and enemy are on ground + if (!PM_InOnGroundAnim(&NPC->enemy->client->ps)) { + if ((NPC->client->ps.weaponTime <= 200 || NPC->client->ps.torsoAnim == BOTH_KYLE_GRAB) && !NPC->client->ps.saberInFlight) { + if (fabs(NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2]) <= 8.0f) { // close to same level of ground + if (DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin) <= 10000.0f) { return qtrue; } } @@ -1348,365 +1095,231 @@ qboolean Kyle_CanDoGrab( void ) return qfalse; } -static void Jedi_CombatDistance( int enemy_dist ) -{//FIXME: for many of these checks, what we really want is horizontal distance to enemy - if ( Jedi_CultistDestroyer( NPC ) ) - {//destroyer +static void Jedi_CombatDistance(int enemy_dist) { // FIXME: for many of these checks, what we really want is horizontal distance to enemy + if (Jedi_CultistDestroyer(NPC)) { // destroyer Jedi_Advance(); - //always run, regardless of what navigation tells us to do! + // always run, regardless of what navigation tells us to do! NPC->client->ps.speed = NPCInfo->stats.runSpeed; ucmd.buttons &= ~BUTTON_WALKING; return; } - if ( enemy_dist < 128 - && NPC->enemy - && NPC->enemy->client - && (NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 - || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7 ) ) - {//whoa, back off!!! - if ( Q_irand( -3, NPCInfo->rank ) > RANK_CREWMAN ) - { + if (enemy_dist < 128 && NPC->enemy && NPC->enemy->client && + (NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7)) { // whoa, back off!!! + if (Q_irand(-3, NPCInfo->rank) > RANK_CREWMAN) { Jedi_StartBackOff(); return; } } - if ( NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//when gripping, don't move + if (NPC->client->ps.forcePowersActive & (1 << FP_GRIP) && NPC->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // when gripping, don't move return; - } - else if ( !TIMER_Done( NPC, "gripping" ) ) - {//stopped gripping, clear timers just in case - TIMER_Set( NPC, "gripping", -level.time ); - TIMER_Set( NPC, "attackDelay", Q_irand( 0, 1000 ) ); + } else if (!TIMER_Done(NPC, "gripping")) { // stopped gripping, clear timers just in case + TIMER_Set(NPC, "gripping", -level.time); + TIMER_Set(NPC, "attackDelay", Q_irand(0, 1000)); } - if ( NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 ) - {//when draining, don't move + if (NPC->client->ps.forcePowersActive & (1 << FP_DRAIN) && NPC->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1) { // when draining, don't move return; - } - else if ( !TIMER_Done( NPC, "draining" ) ) - {//stopped draining, clear timers just in case - TIMER_Set( NPC, "draining", -level.time ); - TIMER_Set( NPC, "attackDelay", Q_irand( 0, 1000 ) ); + } else if (!TIMER_Done(NPC, "draining")) { // stopped draining, clear timers just in case + TIMER_Set(NPC, "draining", -level.time); + TIMER_Set(NPC, "attackDelay", Q_irand(0, 1000)); } - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( !TIMER_Done( NPC, "flameTime" ) ) - { - if ( enemy_dist > 50 ) - { + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + if (!TIMER_Done(NPC, "flameTime")) { + if (enemy_dist > 50) { Jedi_Advance(); - } - else if ( enemy_dist <= 0 ) - { + } else if (enemy_dist <= 0) { Jedi_Retreat(); } - } - else if ( enemy_dist < 200 ) - { + } else if (enemy_dist < 200) { Jedi_Retreat(); - } - else if ( enemy_dist > 1024 ) - { + } else if (enemy_dist > 1024) { Jedi_Advance(); } - } - else if ( NPC->client->ps.legsAnim == BOTH_ALORA_SPIN_THROW ) - {//don't move at all - //FIXME: sabers need trails - } - else if ( NPC->client->ps.torsoAnim == BOTH_KYLE_GRAB ) - {//see if we grabbed enemy - if ( NPC->client->ps.torsoAnimTimer <= 200 ) - { - if ( Kyle_CanDoGrab() - && NPC_EnemyRangeFromBolt( NPC->handRBolt ) <= 72.0f ) - {//grab him! + } else if (NPC->client->ps.legsAnim == BOTH_ALORA_SPIN_THROW) { // don't move at all + // FIXME: sabers need trails + } else if (NPC->client->ps.torsoAnim == BOTH_KYLE_GRAB) { // see if we grabbed enemy + if (NPC->client->ps.torsoAnimTimer <= 200) { + if (Kyle_CanDoGrab() && NPC_EnemyRangeFromBolt(NPC->handRBolt) <= 72.0f) { // grab him! Kyle_GrabEnemy(); return; - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; return; } } - //else just sit here? + // else just sit here? return; - } - else if ( NPC->client->ps.saberInFlight && - !PM_SaberInBrokenParry( NPC->client->ps.saberMove ) - && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//maintain distance - if ( enemy_dist < NPC->client->ps.saberEntityDist ) - { + } else if (NPC->client->ps.saberInFlight && !PM_SaberInBrokenParry(NPC->client->ps.saberMove) && + NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // maintain distance + if (enemy_dist < NPC->client->ps.saberEntityDist) { Jedi_Retreat(); - } - else if ( enemy_dist > NPC->client->ps.saberEntityDist && enemy_dist > 100 ) - { + } else if (enemy_dist > NPC->client->ps.saberEntityDist && enemy_dist > 100) { Jedi_Advance(); } - if ( NPC->client->ps.weapon == WP_SABER //using saber - && NPC->client->ps.saberEntityState == SES_LEAVING //not returning yet - && NPC->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 //2nd or 3rd level lightsaber - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//hold it out there + if (NPC->client->ps.weapon == WP_SABER // using saber + && NPC->client->ps.saberEntityState == SES_LEAVING // not returning yet + && NPC->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 // 2nd or 3rd level lightsaber + && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // hold it out there ucmd.buttons |= BUTTON_ALT_ATTACK; - //FIXME: time limit? + // FIXME: time limit? } - } - else if ( !TIMER_Done( NPC, "taunting" ) ) - { - if ( enemy_dist <= 64 ) - {//he's getting too close + } else if (!TIMER_Done(NPC, "taunting")) { + if (enemy_dist <= 64) { // he's getting too close ucmd.buttons |= BUTTON_ATTACK; - if ( !NPC->client->ps.saberInFlight ) - { + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.SaberActivate(); } - TIMER_Set( NPC, "taunting", -level.time ); - } - else if ( NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoAnimTimer < 2000 ) - {//we're almost done with our special taunt - //FIXME: this doesn't always work, for some reason - if ( !NPC->client->ps.saberInFlight ) - { + TIMER_Set(NPC, "taunting", -level.time); + } else if (NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoAnimTimer < 2000) { // we're almost done with our special taunt + // FIXME: this doesn't always work, for some reason + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.SaberActivate(); } } - } - else if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage - if ( enemy_dist > 0 ) - {//get closer so we can hit! + } else if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage + if (enemy_dist > 0) { // get closer so we can hit! Jedi_Advance(); } - if ( enemy_dist > 128 ) - {//lost 'em + if (enemy_dist > 128) { // lost 'em NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - if ( NPC->enemy->painDebounceTime + 2000 < level.time ) - {//the window of opportunity is gone + if (NPC->enemy->painDebounceTime + 2000 < level.time) { // the window of opportunity is gone NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - //don't strafe? - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - } - else if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time - && NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not - if ( enemy_dist < 64 ) - {//FIXME: maybe just pick another enemy? + // don't strafe? + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + } else if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client->ps.saberLockTime > level.time && + NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not + if (enemy_dist < 64) { // FIXME: maybe just pick another enemy? Jedi_Retreat(); } - } - else if ( NPC->enemy->s.weapon == WP_TURRET - && !Q_stricmp( "PAS", NPC->enemy->classname ) - && NPC->enemy->s.apos.trType == TR_STATIONARY ) - { - if ( enemy_dist > forcePushPullRadius[FORCE_LEVEL_1] - 16 ) - { + } else if (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname) && NPC->enemy->s.apos.trType == TR_STATIONARY) { + if (enemy_dist > forcePushPullRadius[FORCE_LEVEL_1] - 16) { Jedi_Advance(); } - int testlevel; - if ( NPC->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1 ) - {// + int testlevel; + if (NPC->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) { // testlevel = FORCE_LEVEL_1; - } - else - { + } else { testlevel = NPC->client->ps.forcePowerLevel[FP_PUSH]; } - if ( enemy_dist < forcePushPullRadius[testlevel] - 16 ) - {//close enough to push - if ( InFront( NPC->enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 0.6f ) ) - {//knock it down - WP_KnockdownTurret( NPC, NPC->enemy ); - //do the forcethrow call just for effect - ForceThrow( NPC, qfalse ); - } - } - } - else if ( enemy_dist <= 64 - && ((NPCInfo->scriptFlags&SCF_DONT_FIRE)||(!Q_stricmp("Yoda",NPC->NPC_type)&&!Q_irand(0,10))) ) - {//can't use saber and they're in striking range - if ( !Q_irand( 0, 5 ) && InFront( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f ) ) - { - if ( ((NPCInfo->scriptFlags&SCF_DONT_FIRE)||NPC->max_health - NPC->health > NPC->max_health*0.25f)//lost over 1/4 of our health or not firing - && WP_ForcePowerUsable( NPC, FP_DRAIN, 20 )//know how to drain and have enough power - && !Q_irand( 0, 2 ) ) - {//drain - TIMER_Set( NPC, "draining", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); + if (enemy_dist < forcePushPullRadius[testlevel] - 16) { // close enough to push + if (InFront(NPC->enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 0.6f)) { // knock it down + WP_KnockdownTurret(NPC, NPC->enemy); + // do the forcethrow call just for effect + ForceThrow(NPC, qfalse); + } + } + } else if (enemy_dist <= 64 && ((NPCInfo->scriptFlags & SCF_DONT_FIRE) || + (!Q_stricmp("Yoda", NPC->NPC_type) && !Q_irand(0, 10)))) { // can't use saber and they're in striking range + if (!Q_irand(0, 5) && InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f)) { + if (((NPCInfo->scriptFlags & SCF_DONT_FIRE) || NPC->max_health - NPC->health > NPC->max_health * 0.25f) // lost over 1/4 of our health or not firing + && WP_ForcePowerUsable(NPC, FP_DRAIN, 20) // know how to drain and have enough power + && !Q_irand(0, 2)) { // drain + TIMER_Set(NPC, "draining", 3000); + TIMER_Set(NPC, "attackDelay", 3000); Jedi_Advance(); return; - } - else - { - if ( Jedi_DecideKick() ) - {//let's try a kick - if ( G_PickAutoMultiKick( NPC, qfalse, qtrue ) != LS_NONE - || (G_CanKickEntity(NPC, NPC->enemy ) && G_PickAutoKick( NPC, NPC->enemy, qtrue ) != LS_NONE ) ) - {//kicked! - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); + } else { + if (Jedi_DecideKick()) { // let's try a kick + if (G_PickAutoMultiKick(NPC, qfalse, qtrue) != LS_NONE || + (G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE)) { // kicked! + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); return; } } - ForceThrow( NPC, qfalse ); + ForceThrow(NPC, qfalse); } } Jedi_Retreat(); - } - else if ( enemy_dist <= 64 - && NPC->max_health - NPC->health > NPC->max_health*0.25f//lost over 1/4 of our health - && NPC->client->ps.forcePowersKnown&(1<enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f ) ) - { - TIMER_Set( NPC, "draining", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); + } else if (enemy_dist <= 64 && NPC->max_health - NPC->health > NPC->max_health * 0.25f // lost over 1/4 of our health + && NPC->client->ps.forcePowersKnown & (1 << FP_DRAIN) // know how to drain + && WP_ForcePowerAvailable(NPC, FP_DRAIN, 20) // have enough power + && !Q_irand(0, 10) && InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f)) { + TIMER_Set(NPC, "draining", 3000); + TIMER_Set(NPC, "attackDelay", 3000); Jedi_Advance(); return; - } - else if ( enemy_dist <= -16 ) - {//we're too damn close! - if ( !Q_irand( 0, 30 ) - && Kyle_CanDoGrab() ) - { + } else if (enemy_dist <= -16) { // we're too damn close! + if (!Q_irand(0, 30) && Kyle_CanDoGrab()) { Kyle_TryGrab(); return; - } - else if ( NPC->client->ps.stats[STAT_WEAPONS]&(1<client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER) && !Q_irand(0, 20)) { Tavion_StartScepterSlam(); return; } - if ( Jedi_DecideKick() ) - {//let's try a kick - if ( G_PickAutoMultiKick( NPC, qfalse, qtrue ) != LS_NONE - || (G_CanKickEntity(NPC, NPC->enemy ) && G_PickAutoKick( NPC, NPC->enemy, qtrue ) != LS_NONE ) ) - {//kicked! - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); + if (Jedi_DecideKick()) { // let's try a kick + if (G_PickAutoMultiKick(NPC, qfalse, qtrue) != LS_NONE || + (G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE)) { // kicked! + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); return; } } Jedi_Retreat(); - } - else if ( enemy_dist <= 0 ) - {//we're within striking range - //if we are attacking, see if we should stop - if ( NPCInfo->stats.aggression < 4 ) - {//back off and defend - if ( !Q_irand( 0, 30 ) - && Kyle_CanDoGrab() ) - { + } else if (enemy_dist <= 0) { // we're within striking range + // if we are attacking, see if we should stop + if (NPCInfo->stats.aggression < 4) { // back off and defend + if (!Q_irand(0, 30) && Kyle_CanDoGrab()) { Kyle_TryGrab(); return; - } - else if ( NPC->client->ps.stats[STAT_WEAPONS]&(1<client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER) && !Q_irand(0, 20)) { Tavion_StartScepterSlam(); return; } - if ( Jedi_DecideKick() ) - {//let's try a kick - if ( G_PickAutoMultiKick( NPC, qfalse, qtrue ) != LS_NONE - || (G_CanKickEntity(NPC, NPC->enemy ) && G_PickAutoKick( NPC, NPC->enemy, qtrue ) != LS_NONE ) ) - {//kicked! - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); + if (Jedi_DecideKick()) { // let's try a kick + if (G_PickAutoMultiKick(NPC, qfalse, qtrue) != LS_NONE || + (G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE)) { // kicked! + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); return; } } Jedi_Retreat(); } - } - else if ( enemy_dist > 256 ) - {//we're way out of range + } else if (enemy_dist > 256) { // we're way out of range qboolean usedForce = qfalse; - if ( NPCInfo->stats.aggression < Q_irand( 0, 20 ) - && NPC->health < NPC->max_health*0.75f - && !Q_irand( 0, 2 ) ) - { - if ( NPC->enemy - && NPC->enemy->s.number < MAX_CLIENTS - && NPC->client->NPC_class!=CLASS_KYLE - && ((NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) - || NPC->client->NPC_class==CLASS_SHADOWTROOPER) - && Q_irand(0, 3-g_spskill->integer) ) - {//hmm, bosses should do this less against the player - } - else if ( NPC->client->ps.saber[0].type == SABER_SITH_SWORD - && NPC->weaponModel[0] != -1 ) - { + if (NPCInfo->stats.aggression < Q_irand(0, 20) && NPC->health < NPC->max_health * 0.75f && !Q_irand(0, 2)) { + if (NPC->enemy && NPC->enemy->s.number < MAX_CLIENTS && NPC->client->NPC_class != CLASS_KYLE && + ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER) || NPC->client->NPC_class == CLASS_SHADOWTROOPER) && + Q_irand(0, 3 - g_spskill->integer)) { // hmm, bosses should do this less against the player + } else if (NPC->client->ps.saber[0].type == SABER_SITH_SWORD && NPC->weaponModel[0] != -1) { Tavion_SithSwordRecharge(); usedForce = qtrue; - } - else if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersKnown & (1 << FP_HEAL)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_HEAL)) == 0 && Q_irand(0, 1)) { + ForceHeal(NPC); usedForce = qtrue; - //FIXME: check level of heal and know not to move or attack when healing - } - else if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersKnown & (1 << FP_PROTECT)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_PROTECT)) == 0 && + Q_irand(0, 1)) { + ForceProtect(NPC); usedForce = qtrue; - } - else if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersKnown & (1 << FP_ABSORB)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_ABSORB)) == 0 && + Q_irand(0, 1)) { + ForceAbsorb(NPC); usedForce = qtrue; - } - else if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersKnown & (1 << FP_RAGE)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_RAGE)) == 0 && Q_irand(0, 1)) { Jedi_Rage(); usedForce = qtrue; } - //FIXME: what about things like mind tricks and force sight? + // FIXME: what about things like mind tricks and force sight? } - if ( enemy_dist > 384 ) - {//FIXME: check for enemy facing away and/or moving away - if ( !Q_irand( 0, 10 ) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) - { - if ( NPC_ClearLOS( NPC->enemy ) ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JCHASE1, EV_JCHASE3 ), 3000 ); + if (enemy_dist > 384) { // FIXME: check for enemy facing away and/or moving away + if (!Q_irand(0, 10) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time) { + if (NPC_ClearLOS(NPC->enemy)) { + G_AddVoiceEvent(NPC, Q_irand(EV_JCHASE1, EV_JCHASE3), 3000); } jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - //Unless we're totally hiding, go after him - if ( NPCInfo->stats.aggression > 0 ) - {//approach enemy - if ( !usedForce ) - { - if ( NPC->enemy - && NPC->enemy->client - && (NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 - || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7 ) ) - {//stay put! - } - else - { + // Unless we're totally hiding, go after him + if (NPCInfo->stats.aggression > 0) { // approach enemy + if (!usedForce) { + if (NPC->enemy && NPC->enemy->client && + (NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7)) { // stay put! + } else { Jedi_Advance(); } } @@ -1718,335 +1331,241 @@ static void Jedi_CombatDistance( int enemy_dist ) Jedi_Retreat(); } */ - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - else if ( enemy_dist > 50 )//FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax - {//we're out of striking range and we are allowed to attack - //first, check some tactical force power decisions - if ( NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//They're being gripped, rush them! - if ( NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + else if (enemy_dist > 50) // FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax + { // we're out of striking range and we are allowed to attack + // first, check some tactical force power decisions + if (NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.eFlags & EF_FORCE_GRIPPED)) { // They're being gripped, rush them! + if (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - if ( (NPCInfo->rank >= RANK_LT_JG||WP_ForcePowerUsable( NPC, FP_SABERTHROW, 0 )) - && !Q_irand( 0, 5 ) - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + if ((NPCInfo->rank >= RANK_LT_JG || WP_ForcePowerUsable(NPC, FP_SABERTHROW, 0)) && !Q_irand(0, 5) && + !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } - } - else if ( NPC->enemy && NPC->enemy->client && //valid enemy - NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saber[0].Active() && //enemy throwing saber - !NPC->client->ps.weaponTime && //I'm not busy - WP_ForcePowerAvailable( NPC, FP_GRIP, 0 ) && //I can use the power - !Q_irand( 0, 10 ) && //don't do it all the time, averages to 1 check a second - Q_irand( 0, 6 ) < g_spskill->integer && //more likely on harder diff - Q_irand( RANK_CIVILIAN, RANK_CAPTAIN ) < NPCInfo->rank //more likely against harder enemies - && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30 ) ) - {//They're throwing their saber, grip them! - //taunt - if ( TIMER_Done( NPC, "chatter" ) && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); + } else if (NPC->enemy && NPC->enemy->client && // valid enemy + NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saber[0].Active() && // enemy throwing saber + !NPC->client->ps.weaponTime && // I'm not busy + WP_ForcePowerAvailable(NPC, FP_GRIP, 0) && // I can use the power + !Q_irand(0, 10) && // don't do it all the time, averages to 1 check a second + Q_irand(0, 6) < g_spskill->integer && // more likely on harder diff + Q_irand(RANK_CIVILIAN, RANK_CAPTAIN) < NPCInfo->rank // more likely against harder enemies + && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30)) { // They're throwing their saber, grip them! + // taunt + if (TIMER_Done(NPC, "chatter") && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - if ( (NPCInfo->aiFlags&NPCAI_ROSH) ) - { - TIMER_Set( NPC, "chatter", 6000 ); - } - else - { - TIMER_Set( NPC, "chatter", 3000 ); - } - } - - //grip - TIMER_Set( NPC, "gripping", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); - } - else - { - if ( NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + if ((NPCInfo->aiFlags & NPCAI_ROSH)) { + TIMER_Set(NPC, "chatter", 6000); + } else { + TIMER_Set(NPC, "chatter", 3000); + } + } + + // grip + TIMER_Set(NPC, "gripping", 3000); + TIMER_Set(NPC, "attackDelay", 3000); + } else { + if (NPC->enemy && NPC->enemy->client && + (NPC->enemy->client->ps.forcePowersActive & + (1 << FP_GRIP))) { // They're choking someone, probably an ally, run at them and do some sort of attack + if (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } } - if ( NPC->client->NPC_class == CLASS_KYLE - && (NPC->spawnflags&1) - && (NPC->enemy&&NPC->enemy->client&&!NPC->enemy->client->ps.saberInFlight) - && TIMER_Done( NPC, "kyleTakesSaber" ) - && !Q_irand( 0, 20 ) ) - { - ForceThrow( NPC, qtrue ); - } - else if ( NPC->client->ps.stats[STAT_WEAPONS]&(1<client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1) && (NPC->enemy && NPC->enemy->client && !NPC->enemy->client->ps.saberInFlight) && + TIMER_Done(NPC, "kyleTakesSaber") && !Q_irand(0, 20)) { + ForceThrow(NPC, qtrue); + } else if (NPC->client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER) && !Q_irand(0, 20)) { Tavion_StartScepterBeam(); return; - } - else - { + } else { int chanceScale = 0; - if ( NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags&1) ) - { + if (NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1)) { chanceScale = 4; - } - else if ( NPC->enemy - && NPC->enemy->s.number < MAX_CLIENTS - && ((NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) - || NPC->client->NPC_class==CLASS_SHADOWTROOPER) ) - {//hmm, bosses do this less against player - chanceScale = 8 - g_spskill->integer*2; - } - else if ( NPC->client->NPC_class == CLASS_DESANN - || !Q_stricmp("Yoda",NPC->NPC_type) ) - //|| (NPC->client->NPC_class == CLASS_CULTIST && NPC->client->ps.weapon == WP_NONE) )//force-only cultists use force a lot + } else if (NPC->enemy && NPC->enemy->s.number < MAX_CLIENTS && + ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER) || + NPC->client->NPC_class == CLASS_SHADOWTROOPER)) { // hmm, bosses do this less against player + chanceScale = 8 - g_spskill->integer * 2; + } else if (NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", NPC->NPC_type)) + //|| (NPC->client->NPC_class == CLASS_CULTIST && NPC->client->ps.weapon == WP_NONE) )//force-only cultists use force a lot { chanceScale = 1; - } - else if ( NPCInfo->rank == RANK_ENSIGN ) - { + } else if (NPCInfo->rank == RANK_ENSIGN) { chanceScale = 2; - } - else if ( NPCInfo->rank >= RANK_LT_JG ) - { + } else if (NPCInfo->rank >= RANK_LT_JG) { chanceScale = 5; } - if ( chanceScale - && (enemy_dist > Q_irand( 100, 200 ) || (NPCInfo->scriptFlags&SCF_DONT_FIRE) || (!Q_stricmp("Yoda",NPC->NPC_type)&&!Q_irand(0,3)) ) - && enemy_dist < 500 - && (Q_irand( 0, chanceScale*10 )<5 || (NPC->enemy->client && NPC->enemy->client->ps.weapon != WP_SABER && !Q_irand( 0, chanceScale ) ) ) ) - {//else, randomly try some kind of attack every now and then - //FIXME: Cultist fencers don't have any of these fancy powers + if (chanceScale && + (enemy_dist > Q_irand(100, 200) || (NPCInfo->scriptFlags & SCF_DONT_FIRE) || (!Q_stricmp("Yoda", NPC->NPC_type) && !Q_irand(0, 3))) && + enemy_dist < 500 && + (Q_irand(0, chanceScale * 10) < 5 || (NPC->enemy->client && NPC->enemy->client->ps.weapon != WP_SABER && + !Q_irand(0, chanceScale)))) { // else, randomly try some kind of attack every now and then + // FIXME: Cultist fencers don't have any of these fancy powers // the only thing they might be able to do is throw their saber - if ( (NPCInfo->rank == RANK_ENSIGN //old reborn crap - || NPCInfo->rank > RANK_LT_JG //old reborn crap - /* - || WP_ForcePowerUsable( NPC, FP_PULL, 0 ) - || WP_ForcePowerUsable( NPC, FP_LIGHTNING, 0 ) - || WP_ForcePowerUsable( NPC, FP_DRAIN, 0 ) - || WP_ForcePowerUsable( NPC, FP_GRIP, 0 ) - || WP_ForcePowerUsable( NPC, FP_SABERTHROW, 0 ) - */ - ) - && (!Q_irand( 0, 1 ) || NPC->s.weapon != WP_SABER) ) - { - if ( WP_ForcePowerUsable( NPC, FP_PULL, 0 ) && !Q_irand( 0, 2 ) ) - { - //force pull the guy to me! - //FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qtrue ); - //maybe strafe too? - TIMER_Set( NPC, "duck", enemy_dist*3 ); - if ( Q_irand( 0, 1 ) ) - { + if ((NPCInfo->rank == RANK_ENSIGN // old reborn crap + || NPCInfo->rank > RANK_LT_JG // old reborn crap + /* + || WP_ForcePowerUsable( NPC, FP_PULL, 0 ) + || WP_ForcePowerUsable( NPC, FP_LIGHTNING, 0 ) + || WP_ForcePowerUsable( NPC, FP_DRAIN, 0 ) + || WP_ForcePowerUsable( NPC, FP_GRIP, 0 ) + || WP_ForcePowerUsable( NPC, FP_SABERTHROW, 0 ) + */ + ) && + (!Q_irand(0, 1) || NPC->s.weapon != WP_SABER)) { + if (WP_ForcePowerUsable(NPC, FP_PULL, 0) && !Q_irand(0, 2)) { + // force pull the guy to me! + // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qtrue); + // maybe strafe too? + TIMER_Set(NPC, "duck", enemy_dist * 3); + if (Q_irand(0, 1)) { ucmd.buttons |= BUTTON_ATTACK; } - } - else if ( WP_ForcePowerUsable( NPC, FP_LIGHTNING, 0 ) - && (((NPCInfo->scriptFlags&SCF_DONT_FIRE)&&Q_stricmp("cultist_lightning",NPC->NPC_type)) || Q_irand( 0, 1 )) ) - { - ForceLightning( NPC ); - if ( NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - { - NPC->client->ps.weaponTime = Q_irand( 1000, 3000+(g_spskill->integer*500) ); - TIMER_Set( NPC, "holdLightning", NPC->client->ps.weaponTime ); + } else if (WP_ForcePowerUsable(NPC, FP_LIGHTNING, 0) && + (((NPCInfo->scriptFlags & SCF_DONT_FIRE) && Q_stricmp("cultist_lightning", NPC->NPC_type)) || Q_irand(0, 1))) { + ForceLightning(NPC); + if (NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { + NPC->client->ps.weaponTime = Q_irand(1000, 3000 + (g_spskill->integer * 500)); + TIMER_Set(NPC, "holdLightning", NPC->client->ps.weaponTime); } - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); - } - else if ( NPC->health < NPC->max_health * 0.75f - && Q_irand( FORCE_LEVEL_0, NPC->client->ps.forcePowerLevel[FP_DRAIN] ) > FORCE_LEVEL_1 - && WP_ForcePowerUsable( NPC, FP_DRAIN, 0 ) - && (((NPCInfo->scriptFlags&SCF_DONT_FIRE)&&Q_stricmp("cultist_drain",NPC->NPC_type)) || Q_irand( 0, 1 )) ) - { - ForceDrain2( NPC ); - NPC->client->ps.weaponTime = Q_irand( 1000, 3000+(g_spskill->integer*500) ); - TIMER_Set( NPC, "draining", NPC->client->ps.weaponTime ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); - } - else if ( WP_ForcePowerUsable( NPC, FP_GRIP, 0 ) - && NPC->enemy && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30 ) ) - { - //taunt - if ( TIMER_Done( NPC, "chatter" ) && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); + } else if (NPC->health < NPC->max_health * 0.75f && Q_irand(FORCE_LEVEL_0, NPC->client->ps.forcePowerLevel[FP_DRAIN]) > FORCE_LEVEL_1 && + WP_ForcePowerUsable(NPC, FP_DRAIN, 0) && + (((NPCInfo->scriptFlags & SCF_DONT_FIRE) && Q_stricmp("cultist_drain", NPC->NPC_type)) || Q_irand(0, 1))) { + ForceDrain2(NPC); + NPC->client->ps.weaponTime = Q_irand(1000, 3000 + (g_spskill->integer * 500)); + TIMER_Set(NPC, "draining", NPC->client->ps.weaponTime); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); + } else if (WP_ForcePowerUsable(NPC, FP_GRIP, 0) && NPC->enemy && + InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30)) { + // taunt + if (TIMER_Done(NPC, "chatter") && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && + NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - if ( (NPCInfo->aiFlags&NPCAI_ROSH) ) - { - TIMER_Set( NPC, "chatter", 6000 ); - } - else - { - TIMER_Set( NPC, "chatter", 3000 ); + if ((NPCInfo->aiFlags & NPCAI_ROSH)) { + TIMER_Set(NPC, "chatter", 6000); + } else { + TIMER_Set(NPC, "chatter", 3000); } } - //grip - TIMER_Set( NPC, "gripping", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); - } - else - { - if ( WP_ForcePowerUsable( NPC, FP_SABERTHROW, 0 ) - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + // grip + TIMER_Set(NPC, "gripping", 3000); + TIMER_Set(NPC, "attackDelay", 3000); + } else { + if (WP_ForcePowerUsable(NPC, FP_SABERTHROW, 0) && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } } - } - else - { - if ( (NPCInfo->rank >= RANK_LT_JG||WP_ForcePowerUsable( NPC, FP_SABERTHROW, 0 )) - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + } else { + if ((NPCInfo->rank >= RANK_LT_JG || WP_ForcePowerUsable(NPC, FP_SABERTHROW, 0)) && + !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } } } - //see if we should advance now - else if ( NPCInfo->stats.aggression > 5 ) - {//approach enemy - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + // see if we should advance now + else if (NPCInfo->stats.aggression > 5) { // approach enemy + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (!NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - } - else - {//maintain this distance? - //walk? + } else { // maintain this distance? + // walk? } } } - } - else - {//we're not close enough to attack, but not far enough away to be safe - if ( !Q_irand( 0, 30 ) - && Kyle_CanDoGrab() ) - { + } else { // we're not close enough to attack, but not far enough away to be safe + if (!Q_irand(0, 30) && Kyle_CanDoGrab()) { Kyle_TryGrab(); return; } - if ( NPCInfo->stats.aggression < 4 ) - {//back off and defend - if ( Jedi_DecideKick() ) - {//let's try a kick - if ( G_PickAutoMultiKick( NPC, qfalse, qtrue ) != LS_NONE - || (G_CanKickEntity(NPC, NPC->enemy ) && G_PickAutoKick( NPC, NPC->enemy, qtrue ) != LS_NONE ) ) - {//kicked! - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); + if (NPCInfo->stats.aggression < 4) { // back off and defend + if (Jedi_DecideKick()) { // let's try a kick + if (G_PickAutoMultiKick(NPC, qfalse, qtrue) != LS_NONE || + (G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE)) { // kicked! + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); return; } } Jedi_Retreat(); - } - else if ( NPCInfo->stats.aggression > 5 ) - {//try to get closer - if ( enemy_dist > 0 && !(NPCInfo->scriptFlags&SCF_DONT_FIRE)) - {//we're allowed to use our lightsaber, get closer - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance + } else if (NPCInfo->stats.aggression > 5) { // try to get closer + if (enemy_dist > 0 && !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // we're allowed to use our lightsaber, get closer + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (!NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance Jedi_Advance(); } } } - } - else - {//agression is 4 or 5... somewhere in the middle - //what do we do here? Nothing? - //Move forward and back? + } else { // agression is 4 or 5... somewhere in the middle + // what do we do here? Nothing? + // Move forward and back? } } - //if really really mad, rage! - if ( NPCInfo->stats.aggression > Q_irand( 5, 15 ) - && NPC->health < NPC->max_health*0.75f - && !Q_irand( 0, 2 ) ) - { - if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<stats.aggression > Q_irand(5, 15) && NPC->health < NPC->max_health * 0.75f && !Q_irand(0, 2)) { + if ((NPC->client->ps.forcePowersKnown & (1 << FP_RAGE)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_RAGE)) == 0) { Jedi_Rage(); } } } -static qboolean Jedi_Strafe( int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking ) -{ - if ( Jedi_CultistDestroyer( NPC ) ) - {//never strafe +static qboolean Jedi_Strafe(int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking) { + if (Jedi_CultistDestroyer(NPC)) { // never strafe return qfalse; } - if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON && NPC->enemy && NPC->enemy->painDebounceTime > level.time ) - {//don't strafe if pressing the advantage of winning a saberLock + if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON && NPC->enemy && + NPC->enemy->painDebounceTime > level.time) { // don't strafe if pressing the advantage of winning a saberLock return qfalse; } - if ( TIMER_Done( NPC, "strafeLeft" ) && TIMER_Done( NPC, "strafeRight" ) ) - { + if (TIMER_Done(NPC, "strafeLeft") && TIMER_Done(NPC, "strafeRight")) { qboolean strafed = qfalse; - //TODO: make left/right choice a tactical decision rather than random: + // TODO: make left/right choice a tactical decision rather than random: // try to keep own back away from walls and ledges, // try to keep enemy's back to a ledge or wall // Maybe try to strafe toward designer-placed "safe spots" or "goals"? - int strafeTime = Q_irand( strafeTimeMin, strafeTimeMax ); + int strafeTime = Q_irand(strafeTimeMin, strafeTimeMax); - if ( Q_irand( 0, 1 ) ) - { - if ( NPC_MoveDirClear( ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPC, "strafeLeft", strafeTime ); + if (Q_irand(0, 1)) { + if (NPC_MoveDirClear(ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPC, "strafeLeft", strafeTime); strafed = qtrue; - } - else if ( NPC_MoveDirClear( ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPC, "strafeRight", strafeTime ); + } else if (NPC_MoveDirClear(ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPC, "strafeRight", strafeTime); strafed = qtrue; } - } - else - { - if ( NPC_MoveDirClear( ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPC, "strafeRight", strafeTime ); + } else { + if (NPC_MoveDirClear(ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPC, "strafeRight", strafeTime); strafed = qtrue; - } - else if ( NPC_MoveDirClear( ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPC, "strafeLeft", strafeTime ); + } else if (NPC_MoveDirClear(ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPC, "strafeLeft", strafeTime); strafed = qtrue; } } - if ( strafed ) - { - TIMER_Set( NPC, "noStrafe", strafeTime + Q_irand( nextStrafeTimeMin, nextStrafeTimeMax ) ); - if ( walking ) - {//should be a slow strafe - TIMER_Set( NPC, "walking", strafeTime ); + if (strafed) { + TIMER_Set(NPC, "noStrafe", strafeTime + Q_irand(nextStrafeTimeMin, nextStrafeTimeMax)); + if (walking) { // should be a slow strafe + TIMER_Set(NPC, "walking", strafeTime); } return qtrue; } @@ -2089,30 +1608,24 @@ Right now used to dodge instant-hit weapons. FIXME: possibly call this for saber melee evasion and/or missile evasion? FIXME: possibly let player do this too? */ -qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ) -{ - int dodgeAnim = -1; +qboolean Jedi_DodgeEvasion(gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc) { + int dodgeAnim = -1; - if ( !self || !self->client || self->health <= 0 ) - { + if (!self || !self->client || self->health <= 0) { return qfalse; } - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//can't dodge in mid-air + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // can't dodge in mid-air return qfalse; } - if ( self->client->ps.pm_time && (self->client->ps.pm_flags&PMF_TIME_KNOCKBACK) ) - {//in some effect that stops me from moving on my own + if (self->client->ps.pm_time && (self->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) { // in some effect that stops me from moving on my own return qfalse; } - if ( self->enemy == shooter ) - {//FIXME: make it so that we are better able to dodge shots from my current enemy + if (self->enemy == shooter) { // FIXME: make it so that we are better able to dodge shots from my current enemy } - if ( self->s.number ) - {//if an NPC, check game skill setting + if (self->s.number) { // if an NPC, check game skill setting /* if ( self->NPC && (self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) {//those NPCs are "bosses" and always succeed @@ -2128,44 +1641,37 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in } } */ - } - else - {//the player - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_SPEED))) { // not already in speed + if (!WP_ForcePowerUsable(self, FP_SPEED, 0)) { // make sure we have it and have enough force power return qfalse; } } - //check force speed power level to determine if I should be able to dodge it - if ( Q_irand( 1, 10 ) > self->client->ps.forcePowerLevel[FP_SPEED] ) - {//more likely to fail on lower force speed level + // check force speed power level to determine if I should be able to dodge it + if (Q_irand(1, 10) > self->client->ps.forcePowerLevel[FP_SPEED]) { // more likely to fail on lower force speed level return qfalse; } } - if ( hitLoc == HL_NONE ) - { - if ( tr ) - { - for ( int z = 0; z < MAX_G2_COLLISIONS; z++ ) - { - if ( tr->G2CollisionMap[z].mEntityNum == -1 ) - {//actually, completely break out of this for loop since nothing after this in the aray should ever be valid either - continue;//break;// + if (hitLoc == HL_NONE) { + if (tr) { + for (int z = 0; z < MAX_G2_COLLISIONS; z++) { + if (tr->G2CollisionMap[z].mEntityNum == + -1) { // actually, completely break out of this for loop since nothing after this in the aray should ever be valid either + continue; // break;// } - CCollisionRecord &coll = tr->G2CollisionMap[z]; - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &hitLoc, coll.mCollisionPosition, NULL, NULL, MOD_UNKNOWN ); - //only want the first + CCollisionRecord &coll = tr->G2CollisionMap[z]; + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &hitLoc, + coll.mCollisionPosition, NULL, NULL, MOD_UNKNOWN); + // only want the first break; } } } - switch( hitLoc ) - { + switch (hitLoc) { case HL_NONE: return qfalse; break; @@ -2175,42 +1681,29 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in case HL_LEG_RT: case HL_LEG_LT: case HL_WAIST: - if ( !self->s.number ) - {//don't force the player to jump + if (!self->s.number) { // don't force the player to jump return qfalse; - } - else - { - if ( !self->enemy && G_ValidEnemy(self,shooter)) - { - G_SetEnemy( self, shooter ); + } else { + if (!self->enemy && G_ValidEnemy(self, shooter)) { + G_SetEnemy(self, shooter); } - if ( self->NPC - && ((self->NPC->scriptFlags&SCF_NO_ACROBATICS) || PM_InKnockDown( &self->client->ps ) ) ) - { + if (self->NPC && ((self->NPC->scriptFlags & SCF_NO_ACROBATICS) || PM_InKnockDown(&self->client->ps))) { return qfalse; } - if ( self->client - && (self->client->ps.forceRageRecoveryTime > level.time || (self->client->ps.forcePowersActive&(1<client && (self->client->ps.forceRageRecoveryTime > level.time || + (self->client->ps.forcePowersActive & (1 << FP_RAGE)))) { // no fancy dodges when raging or recovering return qfalse; } - if ( self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0,1)) - { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 1)) { return qfalse; // half the time he dodges } - - if ( self->client->NPC_class == CLASS_BOBAFETT - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) - || self->client->NPC_class == CLASS_ROCKETTROOPER ) - { - self->client->ps.forceJumpCharge = 280;//FIXME: calc this intelligently? - } - else - { - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently? - WP_ForcePowerStop( self, FP_GRIP ); + if (self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) || + self->client->NPC_class == CLASS_ROCKETTROOPER) { + self->client->ps.forceJumpCharge = 280; // FIXME: calc this intelligently? + } else { + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently? + WP_ForcePowerStop(self, FP_GRIP); } return qtrue; } @@ -2230,7 +1723,7 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in break; case HL_BACK: case HL_CHEST: - dodgeAnim = Q_irand( BOTH_DODGE_FL, BOTH_DODGE_R ); + dodgeAnim = Q_irand(BOTH_DODGE_FL, BOTH_DODGE_R); break; case HL_ARM_RT: case HL_HAND_RT: @@ -2241,13 +1734,12 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in dodgeAnim = BOTH_DODGE_R; break; case HL_HEAD: - dodgeAnim = Q_irand( BOTH_DODGE_FL, BOTH_DODGE_BR ); + dodgeAnim = Q_irand(BOTH_DODGE_FL, BOTH_DODGE_BR); break; } - if ( dodgeAnim != -1 ) - { - int extraHoldTime = 0;//Q_irand( 5, 40 ) * 50; + if (dodgeAnim != -1) { + int extraHoldTime = 0; // Q_irand( 5, 40 ) * 50; /* int type = SETANIM_TORSO; if ( VectorCompare( self->client->ps.velocity, vec3_origin ) ) @@ -2255,54 +1747,42 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in type = SETANIM_BOTH; } */ - if ( self->s.number < MAX_CLIENTS ) - {//player - if ( (self->client->ps.forcePowersActive&(1<client->ps.torsoAnim ) - && !PM_DodgeHoldAnim( self->client->ps.torsoAnim ) ) - {//already in a dodge - //use the hold pose, don't start it all over again - dodgeAnim = BOTH_DODGE_HOLD_FL+(dodgeAnim-BOTH_DODGE_FL); + if (self->s.number < MAX_CLIENTS) { // player + if ((self->client->ps.forcePowersActive & (1 << FP_SPEED))) { // in speed + if (PM_DodgeAnim(self->client->ps.torsoAnim) && !PM_DodgeHoldAnim(self->client->ps.torsoAnim)) { // already in a dodge + // use the hold pose, don't start it all over again + dodgeAnim = BOTH_DODGE_HOLD_FL + (dodgeAnim - BOTH_DODGE_FL); extraHoldTime = 200; } } } - //set the dodge anim we chose - NPC_SetAnim( self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//type - if ( extraHoldTime && self->client->ps.torsoAnimTimer < extraHoldTime ) - { + // set the dodge anim we chose + NPC_SetAnim(self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // type + if (extraHoldTime && self->client->ps.torsoAnimTimer < extraHoldTime) { self->client->ps.torsoAnimTimer += extraHoldTime; } - //if ( type == SETANIM_BOTH ) - { - self->client->ps.legsAnimTimer = self->client->ps.torsoAnimTimer; - } + // if ( type == SETANIM_BOTH ) + { self->client->ps.legsAnimTimer = self->client->ps.torsoAnimTimer; } - if ( self->s.number ) - {//NPC - //maybe force them to stop moving in this case? - self->client->ps.pm_time = self->client->ps.torsoAnimTimer + Q_irand( 100, 1000 ); + if (self->s.number) { // NPC + // maybe force them to stop moving in this case? + self->client->ps.pm_time = self->client->ps.torsoAnimTimer + Q_irand(100, 1000); self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //do force speed effect + // do force speed effect self->client->ps.forcePowersActive |= (1 << FP_SPEED); self->client->ps.forcePowerDuration[FP_SPEED] = level.time + self->client->ps.torsoAnimTimer; - //sound - G_Sound( self, G_SoundIndex( "sound/weapons/force/speed.wav" ) ); - } - else - {//player - ForceSpeed( self, 500 ); + // sound + G_Sound(self, G_SoundIndex("sound/weapons/force/speed.wav")); + } else { // player + ForceSpeed(self, 500); } - WP_ForcePowerStop( self, FP_GRIP ); - if ( !self->enemy && G_ValidEnemy( self, shooter) ) - { - G_SetEnemy( self, shooter ); - if ( self->s.number ) - { - Jedi_Aggression( self, 10 ); + WP_ForcePowerStop(self, FP_GRIP); + if (!self->enemy && G_ValidEnemy(self, shooter)) { + G_SetEnemy(self, shooter); + if (self->s.number) { + Jedi_Aggression(self, 10); } } return qtrue; @@ -2310,350 +1790,261 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in return qfalse; } -evasionType_t Jedi_CheckFlipEvasions( gentity_t *self, float rightdot, float zdiff ) -{ - if ( self->NPC && (self->NPC->scriptFlags&SCF_NO_ACROBATICS) ) - { +evasionType_t Jedi_CheckFlipEvasions(gentity_t *self, float rightdot, float zdiff) { + if (self->NPC && (self->NPC->scriptFlags & SCF_NO_ACROBATICS)) { return EVASION_NONE; } - if ( self->client ) - { - if ( self->client->NPC_class == CLASS_BOBAFETT ) - {//boba can't flip + if (self->client) { + if (self->client->NPC_class == CLASS_BOBAFETT) { // boba can't flip return EVASION_NONE; } - if ( self->client->ps.forceRageRecoveryTime > level.time - || (self->client->ps.forcePowersActive&(1<client->ps.forceRageRecoveryTime > level.time || (self->client->ps.forcePowersActive & (1 << FP_RAGE))) { // no fancy dodges when raging return EVASION_NONE; } } - //Check for: - //ARIALS/CARTWHEELS - //WALL-RUNS - //WALL-FLIPS - //FIXME: if facing a wall, do forward wall-walk-backflip - //FIXME: add new JKA ones + // Check for: + // ARIALS/CARTWHEELS + // WALL-RUNS + // WALL-FLIPS + // FIXME: if facing a wall, do forward wall-walk-backflip + // FIXME: add new JKA ones -//FIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXME -// -//Make these check for do not enter and ledges!!! -// -//FIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXME + // FIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXME + // + // Make these check for do not enter and ledges!!! + // + // FIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXMEFIXME - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - {//already running on a wall + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { // already running on a wall vec3_t right, fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; - int anim = -1; + int anim = -1; - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); - float animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ); - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0 ) - {//I'm running on a wall to my left and the attack is on the left - if ( animLength - self->client->ps.legsAnimTimer > 400 - && self->client->ps.legsAnimTimer > 400 ) - {//not at the beginning or end of the anim + float animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim); + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0) { // I'm running on a wall to my left and the attack is on the left + if (animLength - self->client->ps.legsAnimTimer > 400 && self->client->ps.legsAnimTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_LEFT_FLIP; } - } - else if ( self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0 ) - {//I'm running on a wall to my right and the attack is on the right - if ( animLength - self->client->ps.legsAnimTimer > 400 - && self->client->ps.legsAnimTimer > 400 ) - {//not at the beginning or end of the anim + } else if (self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0) { // I'm running on a wall to my right and the attack is on the right + if (animLength - self->client->ps.legsAnimTimer > 400 && self->client->ps.legsAnimTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_RIGHT_FLIP; } } - if ( anim != -1 ) - {//flip off the wall! - //FIXME: check the direction we will flip towards for do-not-enter/walls/drops? - //NOTE: we presume there is still a wall there! - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + if (anim != -1) { // flip off the wall! + // FIXME: check the direction we will flip towards for do-not-enter/walls/drops? + // NOTE: we presume there is still a wall there! + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - G_AddEvent( self, EV_JUMP, 0 ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + G_AddEvent(self, EV_JUMP, 0); return EVASION_OTHER; } - } - else if ( self->client->NPC_class != CLASS_DESANN //desann doesn't do these kind of frilly acrobatics - && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) - && Q_irand( 0, 1 ) - && !PM_InRoll( &self->client->ps ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - { - vec3_t fwd, right, traceto, mins = {self->mins[0],self->mins[1],self->mins[2]+STEPSIZE}, maxs = {self->maxs[0],self->maxs[1],24}, fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; - trace_t trace; + } else if (self->client->NPC_class != CLASS_DESANN // desann doesn't do these kind of frilly acrobatics + && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) && Q_irand(0, 1) && !PM_InRoll(&self->client->ps) && + !PM_InKnockDown(&self->client->ps) && !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) { + vec3_t fwd, right, traceto, mins = {self->mins[0], self->mins[1], self->mins[2] + STEPSIZE}, maxs = {self->maxs[0], self->maxs[1], 24}, + fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; + trace_t trace; - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); int parts = SETANIM_BOTH, anim; - float speed, checkDist; + float speed, checkDist; qboolean allowCartWheels = qtrue; - if ( self->client->ps.weapon == WP_SABER ) - { - if ( (self->client->ps.saber[0].saberFlags&SFL_NO_CARTWHEELS) ) - { + if (self->client->ps.weapon == WP_SABER) { + if ((self->client->ps.saber[0].saberFlags & SFL_NO_CARTWHEELS)) { allowCartWheels = qfalse; - } - else if ( self->client->ps.dualSabers - && (self->client->ps.saber[1].saberFlags&SFL_NO_CARTWHEELS) ) - { + } else if (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_CARTWHEELS)) { allowCartWheels = qfalse; } } - if ( PM_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInStart( self->client->ps.saberMove ) ) - { + if (PM_SaberInAttack(self->client->ps.saberMove) || PM_SaberInStart(self->client->ps.saberMove)) { parts = SETANIM_LEGS; } - if ( rightdot >= 0 ) - { - if ( Q_irand( 0, 1 ) ) - { + if (rightdot >= 0) { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_LEFT; - } - else - { + } else { anim = BOTH_CARTWHEEL_LEFT; } checkDist = -128; speed = -200; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_RIGHT; - } - else - { + } else { anim = BOTH_CARTWHEEL_RIGHT; } checkDist = 128; speed = 200; } - //trace in the dir that we want to go - VectorMA( self->currentOrigin, checkDist, right, traceto ); - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); - if ( trace.fraction >= 1.0f && allowCartWheels ) - {//it's clear, let's do it - //FIXME: check for drops? - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.weaponTime = self->client->ps.legsAnimTimer;//don't attack again until this anim is done + // trace in the dir that we want to go + VectorMA(self->currentOrigin, checkDist, right, traceto); + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, (EG2_Collision)0, + 0); + if (trace.fraction >= 1.0f && allowCartWheels) { // it's clear, let's do it + // FIXME: check for drops? + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.weaponTime = self->client->ps.legsAnimTimer; // don't attack again until this anim is done vec3_t fwdAngles, jumpRt; - VectorCopy( self->client->ps.viewangles, fwdAngles ); + VectorCopy(self->client->ps.viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the flip - AngleVectors( fwdAngles, NULL, jumpRt, NULL ); - VectorScale( jumpRt, speed, self->client->ps.velocity ); - self->client->ps.forceJumpCharge = 0;//so we don't play the force flip anim + // do the flip + AngleVectors(fwdAngles, NULL, jumpRt, NULL); + VectorScale(jumpRt, speed, self->client->ps.velocity); + self->client->ps.forceJumpCharge = 0; // so we don't play the force flip anim self->client->ps.velocity[2] = 200; - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height self->client->ps.pm_flags |= PMF_JUMPING; - if ( self->client->NPC_class == CLASS_BOBAFETT - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + if (self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } - //ucmd.upmove = 0; + // ucmd.upmove = 0; return EVASION_CARTWHEEL; - } - else if ( !(trace.contents&CONTENTS_BOTCLIP) ) - {//hit a wall, not a do-not-enter brush - //FIXME: before we check any of these jump-type evasions, we should check for headroom, right? - //Okay, see if we can flip *off* the wall and go the other way - vec3_t idealNormal; - VectorSubtract( self->currentOrigin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + } else if (!(trace.contents & CONTENTS_BOTCLIP)) { // hit a wall, not a do-not-enter brush + // FIXME: before we check any of these jump-type evasions, we should check for headroom, right? + // Okay, see if we can flip *off* the wall and go the other way + vec3_t idealNormal; + VectorSubtract(self->currentOrigin, traceto, idealNormal); + VectorNormalize(idealNormal); gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( (trace.entityNums.solid!=SOLID_BMODEL) || DotProduct( trace.plane.normal, idealNormal ) > 0.7f ) - {//it's a ent of some sort or it's a wall roughly facing us + if ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7f) { // it's a ent of some sort or it's a wall roughly facing us float bestCheckDist = 0; - //hmm, see if we're moving forward - if ( DotProduct( self->client->ps.velocity, fwd ) < 200 ) - {//not running forward very fast - //check to see if it's okay to move the other way - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on that side is close enough to wall-flip off of or wall-run on + // hmm, see if we're moving forward + if (DotProduct(self->client->ps.velocity, fwd) < 200) { // not running forward very fast + // check to see if it's okay to move the other way + if ((trace.fraction * checkDist) <= 32) { // wall on that side is close enough to wall-flip off of or wall-run on bestCheckDist = checkDist; checkDist *= -1.0f; - VectorMA( self->currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); - if ( trace.fraction >= 1.0f ) - {//it's clear, let's do it + VectorMA(self->currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, + (EG2_Collision)0, 0); + if (trace.fraction >= 1.0f) { // it's clear, let's do it qboolean allowWallFlips = qtrue; - if ( self->client->ps.weapon == WP_SABER ) - { - if ( (self->client->ps.saber[0].saberFlags&SFL_NO_WALL_FLIPS) ) - { + if (self->client->ps.weapon == WP_SABER) { + if ((self->client->ps.saber[0].saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; - } - else if ( self->client->ps.dualSabers - && (self->client->ps.saber[1].saberFlags&SFL_NO_WALL_FLIPS) ) - { + } else if (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; } } - if ( allowWallFlips ) - {//okay to do wall-flips with this saber - //FIXME: check for drops? - //turn the cartwheel into a wallflip in the other dir - if ( rightdot > 0 ) - { + if (allowWallFlips) { // okay to do wall-flips with this saber + // FIXME: check for drops? + // turn the cartwheel into a wallflip in the other dir + if (rightdot > 0) { anim = BOTH_WALL_FLIP_LEFT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else { anim = BOTH_WALL_FLIP_RIGHT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - if ( self->client->NPC_class == CLASS_BOBAFETT - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + if (self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } return EVASION_OTHER; } - } - else - {//boxed in on both sides - if ( DotProduct( self->client->ps.velocity, fwd ) < 0 ) - {//moving backwards + } else { // boxed in on both sides + if (DotProduct(self->client->ps.velocity, fwd) < 0) { // moving backwards return EVASION_NONE; } - if ( (trace.fraction*checkDist) <= 32 && (trace.fraction*checkDist) < bestCheckDist ) - { + if ((trace.fraction * checkDist) <= 32 && (trace.fraction * checkDist) < bestCheckDist) { bestCheckDist = checkDist; } } - } - else - {//too far from that wall to flip or run off it, check other side + } else { // too far from that wall to flip or run off it, check other side checkDist *= -1.0f; - VectorMA( self->currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on this side is close enough + VectorMA(self->currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, + (EG2_Collision)0, 0); + if ((trace.fraction * checkDist) <= 32) { // wall on this side is close enough bestCheckDist = checkDist; - } - else - {//neither side has a wall within 32 + } else { // neither side has a wall within 32 return EVASION_NONE; } } } - //Try wall run? - if ( bestCheckDist ) - {//one of the walls was close enough to wall-run on + // Try wall run? + if (bestCheckDist) { // one of the walls was close enough to wall-run on qboolean allowWallRuns = qtrue; - if ( self->client->ps.weapon == WP_SABER ) - { - if ( (self->client->ps.saber[0].saberFlags&SFL_NO_WALL_RUNS) ) - { + if (self->client->ps.weapon == WP_SABER) { + if ((self->client->ps.saber[0].saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; - } - else if ( self->client->ps.dualSabers - && (self->client->ps.saber[1].saberFlags&SFL_NO_WALL_RUNS) ) - { + } else if (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; } } - if ( allowWallRuns ) - {//okay to do wallruns with this saber - //FIXME: check for long enough wall and a drop at the end? - if ( bestCheckDist > 0 ) - {//it was to the right + if (allowWallRuns) { // okay to do wallruns with this saber + // FIXME: check for long enough wall and a drop at the end? + if (bestCheckDist > 0) { // it was to the right anim = BOTH_WALL_RUN_RIGHT; - } - else - {//it was to the left + } else { // it was to the left anim = BOTH_WALL_RUN_LEFT; } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - if ( self->client->NPC_class == CLASS_BOBAFETT - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + if (self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } return EVASION_OTHER; } } - //else check for wall in front, do backflip off wall + // else check for wall in front, do backflip off wall } } } return EVASION_NONE; } -int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) -{ - if ( !self->client ) - { +int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType) { + if (!self->client) { return 0; } - if ( !self->s.number ) - {//player + if (!self->s.number) { // player return parryDebounce[self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]]; - } - else if ( self->NPC ) - { + } else if (self->NPC) { /* if ( !g_saberRealisticCombat->integer && ( g_spskill->integer == 2 || (g_spskill->integer == 1 && (self->client->NPC_class == CLASS_TAVION||self->client->NPC_class == CLASS_ALORA) ) ) ) @@ -2670,21 +2061,14 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) else */ { - int baseTime; - if ( evasionType == EVASION_DODGE ) - { + int baseTime; + if (evasionType == EVASION_DODGE) { baseTime = self->client->ps.torsoAnimTimer; - } - else if ( evasionType == EVASION_CARTWHEEL ) - { + } else if (evasionType == EVASION_CARTWHEEL) { baseTime = self->client->ps.torsoAnimTimer; - } - else if ( self->client->ps.saberInFlight ) - { - baseTime = Q_irand( 1, 3 ) * 50; - } - else - { + } else if (self->client->ps.saberInFlight) { + baseTime = Q_irand(1, 3) * 50; + } else { /* baseTime = 1000; @@ -2702,92 +2086,65 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) break; } */ - if ( 1 )//g_saberRealisticCombat->integer ) + if (1) // g_saberRealisticCombat->integer ) { baseTime = 500; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: - baseTime = 400;//was 500 + baseTime = 400; // was 500 break; case 1: - baseTime = 200;//was 300 + baseTime = 200; // was 300 break; case 2: default: baseTime = 100; break; } - } - else - { - baseTime = 150;//500; + } else { + baseTime = 150; // 500; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: - baseTime = 200;//500; + baseTime = 200; // 500; break; case 1: - baseTime = 100;//300; + baseTime = 100; // 300; break; case 2: default: - baseTime = 50;//100; + baseTime = 50; // 100; break; } } - if ( self->client->NPC_class == CLASS_ALORA - || self->client->NPC_class == CLASS_SHADOWTROOPER - || self->client->NPC_class == CLASS_TAVION ) - {//Tavion & Alora are faster - baseTime = ceil(baseTime/2.0f); - } - else if ( self->NPC->rank >= RANK_LT_JG ) - {//fencers, bosses, shadowtroopers, luke, desann, et al use the norm - if ( !Q_irand( 0, 2 ) ) - {//with the occasional fast parry - baseTime = ceil(baseTime/2.0f); - } - } - else if ( self->NPC->rank == RANK_CIVILIAN ) - {//grunts are slowest - baseTime = baseTime*Q_irand(1,3); - } - else if ( self->NPC->rank == RANK_CREWMAN ) - {//acrobats aren't so bad - if ( evasionType == EVASION_PARRY - || evasionType == EVASION_DUCK_PARRY - || evasionType == EVASION_JUMP_PARRY ) - {//slower with parries - baseTime = baseTime*Q_irand(1,2); + if (self->client->NPC_class == CLASS_ALORA || self->client->NPC_class == CLASS_SHADOWTROOPER || + self->client->NPC_class == CLASS_TAVION) { // Tavion & Alora are faster + baseTime = ceil(baseTime / 2.0f); + } else if (self->NPC->rank >= RANK_LT_JG) { // fencers, bosses, shadowtroopers, luke, desann, et al use the norm + if (!Q_irand(0, 2)) { // with the occasional fast parry + baseTime = ceil(baseTime / 2.0f); } - else - {//faster with acrobatics - //baseTime = baseTime; + } else if (self->NPC->rank == RANK_CIVILIAN) { // grunts are slowest + baseTime = baseTime * Q_irand(1, 3); + } else if (self->NPC->rank == RANK_CREWMAN) { // acrobats aren't so bad + if (evasionType == EVASION_PARRY || evasionType == EVASION_DUCK_PARRY || evasionType == EVASION_JUMP_PARRY) { // slower with parries + baseTime = baseTime * Q_irand(1, 2); + } else { // faster with acrobatics + // baseTime = baseTime; } + } else { // force users are kinda slow + baseTime = baseTime * Q_irand(1, 2); } - else - {//force users are kinda slow - baseTime = baseTime*Q_irand(1,2); - } - if ( evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY ) - { - baseTime += 250;//300;//100; - } - else if ( evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY ) - { - baseTime += 400;//500;//50; - } - else if ( evasionType == EVASION_OTHER ) - { - baseTime += 50;//100; - } - else if ( evasionType == EVASION_FJUMP ) - { - baseTime += 300;//400;//100; + if (evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY) { + baseTime += 250; // 300;//100; + } else if (evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY) { + baseTime += 400; // 500;//50; + } else if (evasionType == EVASION_OTHER) { + baseTime += 50; // 100; + } else if (evasionType == EVASION_FJUMP) { + baseTime += 300; // 400;//100; } } @@ -2797,60 +2154,45 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) return 0; } -qboolean Jedi_QuickReactions( gentity_t *self ) -{ - if ( ( self->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) || - self->client->NPC_class == CLASS_SHADOWTROOPER || self->client->NPC_class == CLASS_ALORA || self->client->NPC_class == CLASS_TAVION || - (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_1&&g_spskill->integer>1) || - (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_2&&g_spskill->integer>0) ) - { +qboolean Jedi_QuickReactions(gentity_t *self) { + if ((self->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER) || self->client->NPC_class == CLASS_SHADOWTROOPER || + self->client->NPC_class == CLASS_ALORA || self->client->NPC_class == CLASS_TAVION || + (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && g_spskill->integer > 1) || + (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 && g_spskill->integer > 0)) { return qtrue; } return qfalse; } -qboolean Jedi_SaberBusy( gentity_t *self ) -{ - if ( self->client->ps.torsoAnimTimer > 300 - && ( (PM_SaberInAttack( self->client->ps.saberMove )&&self->client->ps.saberAnimLevel==SS_STRONG) - || PM_SpinningSaberAnim( self->client->ps.torsoAnim ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - //|| PM_SaberInBounce( self->client->ps.saberMove ) - || PM_SaberInBrokenParry( self->client->ps.saberMove ) - //|| PM_SaberInDeflect( self->client->ps.saberMove ) - || PM_FlippingAnim( self->client->ps.torsoAnim ) - || PM_RollingAnim( self->client->ps.torsoAnim ) ) ) - {//my saber is not in a parrying position +qboolean Jedi_SaberBusy(gentity_t *self) { + if (self->client->ps.torsoAnimTimer > 300 && + ((PM_SaberInAttack(self->client->ps.saberMove) && self->client->ps.saberAnimLevel == SS_STRONG) || PM_SpinningSaberAnim(self->client->ps.torsoAnim) || + PM_SaberInSpecialAttack(self->client->ps.torsoAnim) + //|| PM_SaberInBounce( self->client->ps.saberMove ) + || PM_SaberInBrokenParry(self->client->ps.saberMove) + //|| PM_SaberInDeflect( self->client->ps.saberMove ) + || PM_FlippingAnim(self->client->ps.torsoAnim) || PM_RollingAnim(self->client->ps.torsoAnim))) { // my saber is not in a parrying position return qtrue; } return qfalse; } -qboolean Jedi_InNoAIAnim( gentity_t *self ) -{ - if ( !self || !self->client ) - {//wtf??? +qboolean Jedi_InNoAIAnim(gentity_t *self) { + if (!self || !self->client) { // wtf??? return qtrue; } - if ( NPCInfo->rank >= RANK_COMMANDER ) - {//boss-level guys can multitask, the rest need to chill out during special moves + if (NPCInfo->rank >= RANK_COMMANDER) { // boss-level guys can multitask, the rest need to chill out during special moves return qfalse; } - if ( PM_KickingAnim( NPC->client->ps.legsAnim ) - ||PM_StabDownAnim( NPC->client->ps.legsAnim ) - ||PM_InAirKickingAnim( NPC->client->ps.legsAnim ) - ||PM_InRollIgnoreTimer( &NPC->client->ps ) - ||PM_SaberInKata((saberMoveName_t)NPC->client->ps.saberMove) - ||PM_SuperBreakWinAnim( NPC->client->ps.torsoAnim ) - ||PM_SuperBreakLoseAnim( NPC->client->ps.torsoAnim ) ) - { + if (PM_KickingAnim(NPC->client->ps.legsAnim) || PM_StabDownAnim(NPC->client->ps.legsAnim) || PM_InAirKickingAnim(NPC->client->ps.legsAnim) || + PM_InRollIgnoreTimer(&NPC->client->ps) || PM_SaberInKata((saberMoveName_t)NPC->client->ps.saberMove) || + PM_SuperBreakWinAnim(NPC->client->ps.torsoAnim) || PM_SuperBreakLoseAnim(NPC->client->ps.torsoAnim)) { return qtrue; } - switch ( self->client->ps.legsAnim ) - { + switch (self->client->ps.legsAnim) { case BOTH_BUTTERFLY_LEFT: case BOTH_BUTTERFLY_RIGHT: case BOTH_BUTTERFLY_FL1: @@ -2891,43 +2233,31 @@ qboolean Jedi_InNoAIAnim( gentity_t *self ) return qfalse; } -void Jedi_CheckJumpEvasionSafety( gentity_t *self, usercmd_t *cmd, evasionType_t evasionType ) -{ - if ( evasionType != EVASION_OTHER//not a FlipEvasion, which does it's own safety checks - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on terra firma right now - if ( NPC->client->ps.velocity[2] > 0 - || NPC->client->ps.forceJumpCharge - || cmd->upmove > 0 ) - {//going to jump - if ( !NAV_MoveDirSafe( NPC, cmd, NPC->client->ps.speed*10.0f ) ) - {//we can't jump in the dir we're pushing in - //cancel the evasion +void Jedi_CheckJumpEvasionSafety(gentity_t *self, usercmd_t *cmd, evasionType_t evasionType) { + if (evasionType != EVASION_OTHER // not a FlipEvasion, which does it's own safety checks + && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on terra firma right now + if (NPC->client->ps.velocity[2] > 0 || NPC->client->ps.forceJumpCharge || cmd->upmove > 0) { // going to jump + if (!NAV_MoveDirSafe(NPC, cmd, NPC->client->ps.speed * 10.0f)) { // we can't jump in the dir we're pushing in + // cancel the evasion NPC->client->ps.velocity[2] = NPC->client->ps.forceJumpCharge = 0; cmd->upmove = 0; - if ( d_JediAI->integer ) - { - Com_Printf( S_COLOR_RED"jump not safe, cancelling!" ); + if (d_JediAI->integer) { + Com_Printf(S_COLOR_RED "jump not safe, cancelling!"); } - } - else if ( NPC->client->ps.velocity[0] || NPC->client->ps.velocity[1] ) - {//sliding + } else if (NPC->client->ps.velocity[0] || NPC->client->ps.velocity[1]) { // sliding vec3_t jumpDir; - float jumpDist = VectorNormalize2( NPC->client->ps.velocity, jumpDir ); - if ( !NAV_DirSafe( NPC, jumpDir, jumpDist ) ) - {//this jump combined with our momentum would send us into a do not enter brush, so cancel it - //cancel the evasion + float jumpDist = VectorNormalize2(NPC->client->ps.velocity, jumpDir); + if (!NAV_DirSafe(NPC, jumpDir, jumpDist)) { // this jump combined with our momentum would send us into a do not enter brush, so cancel it + // cancel the evasion NPC->client->ps.velocity[2] = NPC->client->ps.forceJumpCharge = 0; cmd->upmove = 0; - if ( d_JediAI->integer ) - { - Com_Printf( S_COLOR_RED"jump not safe, cancelling!\n" ); + if (d_JediAI->integer) { + Com_Printf(S_COLOR_RED "jump not safe, cancelling!\n"); } } } - if ( d_JediAI->integer ) - { - Com_Printf( S_COLOR_GREEN"jump checked, is safe\n" ); + if (d_JediAI->integer) { + Com_Printf(S_COLOR_GREEN "jump checked, is safe\n"); } } } @@ -2944,48 +2274,38 @@ NOTE: always blocking projectiles in this func! ------------------------- */ -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f ) -{ - vec3_t hitloc, hitdir, diff, fwdangles={0,0,0}, right; +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f) { + vec3_t hitloc, hitdir, diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - int duckChance = 0; - int dodgeAnim = -1; - qboolean saberBusy = qfalse; - evasionType_t evasionType = EVASION_NONE; + int duckChance = 0; + int dodgeAnim = -1; + qboolean saberBusy = qfalse; + evasionType_t evasionType = EVASION_NONE; - if ( !self || !self->client ) - { + if (!self || !self->client) { return EVASION_NONE; } - if ( PM_LockedAnim( self->client->ps.torsoAnim ) - && self->client->ps.torsoAnimTimer ) - {//Never interrupt these... + if (PM_LockedAnim(self->client->ps.torsoAnim) && self->client->ps.torsoAnimTimer) { // Never interrupt these... return EVASION_NONE; } - if ( PM_InSpecialJump( self->client->ps.legsAnim ) - && PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - { + if (PM_InSpecialJump(self->client->ps.legsAnim) && PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) { return EVASION_NONE; } - if ( Jedi_InNoAIAnim( self ) ) - { + if (Jedi_InNoAIAnim(self)) { return EVASION_NONE; } - - //FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! - //FIXME: reborn don't block enough anymore - if ( !incoming ) - { - VectorCopy( pHitloc, hitloc ); - VectorCopy( phitDir, hitdir ); - //FIXME: maybe base this on rank some? And/or g_spskill? - if ( self->client->ps.saberInFlight ) - {//DOH! do non-saber evasion! + // FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! + // FIXME: reborn don't block enough anymore + if (!incoming) { + VectorCopy(pHitloc, hitloc); + VectorCopy(phitDir, hitdir); + // FIXME: maybe base this on rank some? And/or g_spskill? + if (self->client->ps.saberInFlight) { // DOH! do non-saber evasion! saberBusy = qtrue; } /* @@ -2994,69 +2314,55 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc //Also, on medium, all level 3 people can parry any time and on hard, all level 2 or 3 people can parry any time } */ - else - { - saberBusy = Jedi_SaberBusy( self ); + else { + saberBusy = Jedi_SaberBusy(self); } - } - else - { - if ( incoming->s.weapon == WP_SABER ) - {//flying lightsaber, face it! - //FIXME: for this to actually work, we'd need to call update angles too? - //Jedi_FaceEntity( self, incoming, qtrue ); + } else { + if (incoming->s.weapon == WP_SABER) { // flying lightsaber, face it! + // FIXME: for this to actually work, we'd need to call update angles too? + // Jedi_FaceEntity( self, incoming, qtrue ); } - VectorCopy( incoming->currentOrigin, hitloc ); - VectorNormalize2( incoming->s.pos.trDelta, hitdir ); + VectorCopy(incoming->currentOrigin, hitloc); + VectorNormalize2(incoming->s.pos.trDelta, hitdir); } - VectorSubtract( hitloc, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(hitloc, self->client->renderInfo.eyePoint, diff); diff[2] = 0; - //VectorNormalize( diff ); + // VectorNormalize( diff ); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); - rightdot = DotProduct(right, diff);// + Q_flrand(-0.10f,0.10f); - //totalHeight = self->client->renderInfo.eyePoint[2] - self->absmin[2]; - zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2];// + Q_irand(-6,6); + rightdot = DotProduct(right, diff); // + Q_flrand(-0.10f,0.10f); + // totalHeight = self->client->renderInfo.eyePoint[2] - self->absmin[2]; + zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2]; // + Q_irand(-6,6); qboolean doDodge = qfalse; qboolean alwaysDodgeOrRoll = qfalse; - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { + if (self->client->NPC_class == CLASS_BOBAFETT) { saberBusy = qtrue; doDodge = qtrue; alwaysDodgeOrRoll = qtrue; - } - else - { - if ( self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER ) - { + } else { + if (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) { saberBusy = qtrue; alwaysDodgeOrRoll = qtrue; } - //see if we can dodge if need-be - if ( (dist>16&&(Q_irand( 0, 2 )||saberBusy)) - || self->client->ps.saberInFlight - || !self->client->ps.SaberActive() - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) ) - {//either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG) ) - {//acrobat or fencer or above - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE &&//on the ground - !(self->client->ps.pm_flags&PMF_DUCKED)&&cmd->upmove>=0&&TIMER_Done( self, "duck" )//not ducking - && !PM_InRoll( &self->client->ps )//not rolling - && !PM_InKnockDown( &self->client->ps )//not knocked down - && ( self->client->ps.saberInFlight || - (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) || - (!PM_SaberInAttack( self->client->ps.saberMove )//not attacking - && !PM_SaberInStart( self->client->ps.saberMove )//not starting an attack - && !PM_SpinningSaberAnim( self->client->ps.torsoAnim )//not in a saber spin - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ))//not in a special attack - ) - ) - {//need to check all these because it overrides both torso and legs with the dodge + // see if we can dodge if need-be + if ((dist > 16 && (Q_irand(0, 2) || saberBusy)) || self->client->ps.saberInFlight || !self->client->ps.SaberActive() || + (self->client->NPC_class == CLASS_REBORN && + self->s.weapon != WP_SABER)) { // either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG)) { // acrobat or fencer or above + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && // on the ground + !(self->client->ps.pm_flags & PMF_DUCKED) && cmd->upmove >= 0 && TIMER_Done(self, "duck") // not ducking + && !PM_InRoll(&self->client->ps) // not rolling + && !PM_InKnockDown(&self->client->ps) // not knocked down + && (self->client->ps.saberInFlight || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) || + (!PM_SaberInAttack(self->client->ps.saberMove) // not attacking + && !PM_SaberInStart(self->client->ps.saberMove) // not starting an attack + && !PM_SpinningSaberAnim(self->client->ps.torsoAnim) // not in a saber spin + && !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) // not in a special attack + )) { // need to check all these because it overrides both torso and legs with the dodge doDodge = qtrue; } } @@ -3064,387 +2370,260 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } qboolean doRoll = qfalse; - if ( ( self->client->NPC_class == CLASS_BOBAFETT //boba fett - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) //non-saber reborn (cultist) - ) - && !Q_irand( 0, 2 ) - ) - { + if ((self->client->NPC_class == CLASS_BOBAFETT // boba fett + || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) // non-saber reborn (cultist) + ) && + !Q_irand(0, 2)) { doRoll = qtrue; } // Figure out what quadrant the block was in. - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2]-self->absmin[2],zdiff,rightdot); - } - - //UL = > -1//-6 - //UR = > -6//-9 - //TOP = > +6//+4 - //FIXME: take FP_SABER_DEFENSE into account here somehow? - if ( zdiff >= -5 )//was 0 - { - if ( incoming || !saberBusy || alwaysDodgeOrRoll ) - { - if ( rightdot > 12 - || (rightdot > 3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, 0.3 - {//coming from right - if ( doDodge ) - { - if ( doRoll ) - {//roll! - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); + if (d_JediAI->integer) { + gi.Printf("(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2] - self->absmin[2], zdiff, rightdot); + } + + // UL = > -1//-6 + // UR = > -6//-9 + // TOP = > +6//+4 + // FIXME: take FP_SABER_DEFENSE into account here somehow? + if (zdiff >= -5) // was 0 + { + if (incoming || !saberBusy || alwaysDodgeOrRoll) { + if (rightdot > 12 || (rightdot > 3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, 0.3 + { // coming from right + if (doDodge) { + if (doRoll) { // roll! + TIMER_Start(self, "duck", Q_irand(500, 1500)); + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); evasionType = EVASION_DUCK; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FL; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BL; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI->integer ) - { - gi.Printf( "UR block\n" ); + if (d_JediAI->integer) { + gi.Printf("UR block\n"); } - } - else if ( rightdot < -12 - || (rightdot < -3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, -0.3 - {//coming from left - if ( doDodge ) - { - if ( doRoll ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - TIMER_Start( self, "strafeRight", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeLeft", 0 ); + } else if (rightdot < -12 || (rightdot < -3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, -0.3 + { // coming from left + if (doDodge) { + if (doRoll) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); + TIMER_Start(self, "strafeRight", Q_irand(500, 1500)); + TIMER_Set(self, "strafeLeft", 0); evasionType = EVASION_DUCK; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FR; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BR; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI->integer ) - { - gi.Printf( "UL block\n" ); + if (d_JediAI->integer) { + gi.Printf("UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { duckChance = 4; } - if ( d_JediAI->integer ) - { - gi.Printf( "TOP block\n" ); - } - } - } - else - { - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - evasionType = EVASION_DUCK; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + if (d_JediAI->integer) { + gi.Printf("TOP block\n"); + } + } + } else { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); + evasionType = EVASION_DUCK; + if (d_JediAI->integer) { + gi.Printf("duck "); } } } } - //LL = -22//= -18 to -39 - //LR = -23//= -20 to -41 - else if ( zdiff > -22 )//was-15 ) + // LL = -22//= -18 to -39 + // LR = -23//= -20 to -41 + else if (zdiff > -22) // was-15 ) { - if ( 1 )//zdiff < -10 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (1) // zdiff < -10 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - {//in air! Ducking does no good + } else { // in air! Ducking does no good } } - if ( incoming || !saberBusy || alwaysDodgeOrRoll ) - { - if ( rightdot > 8 || (rightdot > 3 && zdiff < -11) )//was normalized, 0.2 + if (incoming || !saberBusy || alwaysDodgeOrRoll) { + if (rightdot > 8 || (rightdot > 3 && zdiff < -11)) // was normalized, 0.2 { - if ( doDodge ) - { - if ( doRoll ) - {//roll! - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - } - else - { + if (doDodge) { + if (doRoll) { // roll! + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + } else { dodgeAnim = BOTH_DODGE_L; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-UR block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-UR block\n"); } - } - else if ( rightdot < -8 || (rightdot < -3 && zdiff < -11) )//was normalized, -0.2 + } else if (rightdot < -8 || (rightdot < -3 && zdiff < -11)) // was normalized, -0.2 { - if ( doDodge ) - { - if ( doRoll ) - {//roll! - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - } - else - { + if (doDodge) { + if (doRoll) { // roll! + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + } else { dodgeAnim = BOTH_DODGE_R; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-UL block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-TOP block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-TOP block\n"); } } } - } - else - { - if ( saberBusy || (zdiff < -36 && ( zdiff < -44 || !Q_irand( 0, 2 ) ) ) )//was -30 and -40//2nd one was -46 - {//jump! - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//already in air, duck to pull up legs - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + } else { + if (saberBusy || (zdiff < -36 && (zdiff < -44 || !Q_irand(0, 2)))) // was -30 and -40//2nd one was -46 + { // jump! + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // already in air, duck to pull up legs + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - if ( d_JediAI->integer ) - { - gi.Printf( "legs up\n" ); + if (d_JediAI->integer) { + gi.Printf("legs up\n"); } - if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } } - } - else - {//gotta jump! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.forceRageRecoveryTime < level.time - && !(self->client->ps.forcePowersActive&(1<client->ps ) ) - { - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently + } else { // gotta jump! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.forceRageRecoveryTime < level.time && + !(self->client->ps.forcePowersActive & (1 << FP_RAGE)) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - if ( d_JediAI->integer ) - { - gi.Printf( "force jump + " ); + if (d_JediAI->integer) { + gi.Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.forceRageRecoveryTime < level.time - && !(self->client->ps.forcePowersActive&(1<client->NPC_class == CLASS_BOBAFETT - || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) - ) - && !Q_irand( 0, 1 ) ) - {//flip! - if ( rightdot > 0 ) - { - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - TIMER_Set( self, "walking", 0 ); + } else { // normal jump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.forceRageRecoveryTime < level.time && + !(self->client->ps.forcePowersActive & (1 << FP_RAGE))) { + if ((self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER)) && + !Q_irand(0, 1)) { // flip! + if (rightdot > 0) { + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + TIMER_Set(self, "walking", 0); + } else { + TIMER_Start(self, "strafeRight", Q_irand(500, 1500)); + TIMER_Set(self, "strafeLeft", 0); + TIMER_Set(self, "walking", 0); } - else - { - TIMER_Start( self, "strafeRight", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeLeft", 0 ); - TIMER_Set( self, "walking", 0 ); - } - } - else - { - if ( self == NPC ) - { + } else { + if (self == NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } } evasionType = EVASION_JUMP; - if ( d_JediAI->integer ) - { - gi.Printf( "jump + " ); + if (d_JediAI->integer) { + gi.Printf("jump + "); } } - if ( self->client->NPC_class == CLASS_ALORA - || self->client->NPC_class == CLASS_SHADOWTROOPER - || self->client->NPC_class == CLASS_TAVION ) - { - if ( !incoming - && self->client->ps.groundEntityNum < ENTITYNUM_NONE - && !Q_irand( 0, 2 ) ) - { - if ( !PM_SaberInAttack( self->client->ps.saberMove ) - && !PM_SaberInStart( self->client->ps.saberMove ) - && !PM_InRoll( &self->client->ps ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - {//do the butterfly! + if (self->client->NPC_class == CLASS_ALORA || self->client->NPC_class == CLASS_SHADOWTROOPER || self->client->NPC_class == CLASS_TAVION) { + if (!incoming && self->client->ps.groundEntityNum < ENTITYNUM_NONE && !Q_irand(0, 2)) { + if (!PM_SaberInAttack(self->client->ps.saberMove) && !PM_SaberInStart(self->client->ps.saberMove) && + !PM_InRoll(&self->client->ps) && !PM_InKnockDown(&self->client->ps) && + !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) { // do the butterfly! int butterflyAnim; - if ( self->client->NPC_class == CLASS_ALORA - && !Q_irand( 0, 2 ) ) - { + if (self->client->NPC_class == CLASS_ALORA && !Q_irand(0, 2)) { butterflyAnim = BOTH_ALORA_SPIN; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { butterflyAnim = BOTH_BUTTERFLY_LEFT; - } - else - { + } else { butterflyAnim = BOTH_BUTTERFLY_RIGHT; } evasionType = EVASION_CARTWHEEL; - NPC_SetAnim( self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.velocity[2] = 225; - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - self->client->ps.SaberActivateTrail( 300 );//FIXME: reset this when done! + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + self->client->ps.SaberActivateTrail(300); // FIXME: reset this when done! /* if ( self->client->NPC_class == CLASS_BOBAFETT || (self->client->NPC_class == CLASS_REBORN && self->s.weapon != WP_SABER) ) @@ -3453,123 +2632,82 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } else */ - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } + { G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } cmd->upmove = 0; saberBusy = qtrue; } } } } - if ( ((evasionType = Jedi_CheckFlipEvasions( self, rightdot, zdiff ))!=EVASION_NONE) ) - { - if ( d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number ) - { - G_StartMatrixEffect( self ); + if (((evasionType = Jedi_CheckFlipEvasions(self, rightdot, zdiff)) != EVASION_NONE)) { + if (d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number) { + G_StartMatrixEffect(self); } saberBusy = qtrue; - } - else if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + } else if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } } } - } - else - { - if ( incoming || !saberBusy ) - { - if ( rightdot >= 0 ) - { + } else { + if (incoming || !saberBusy) { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } - if ( incoming && incoming->s.weapon == WP_SABER ) - {//thrown saber! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.forceRageRecoveryTime < level.time - && !(self->client->ps.forcePowersActive&(1<client->ps ) ) - { - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently + if (incoming && incoming->s.weapon == WP_SABER) { // thrown saber! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.forceRageRecoveryTime < level.time && + !(self->client->ps.forcePowersActive & (1 << FP_RAGE)) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - if ( d_JediAI->integer ) - { - gi.Printf( "force jump + " ); + if (d_JediAI->integer) { + gi.Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.forceRageRecoveryTime < level.time - && !(self->client->ps.forcePowersActive&(1<NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.forceRageRecoveryTime < level.time && + !(self->client->ps.forcePowersActive & (1 << FP_RAGE))) { + if (self == NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } evasionType = EVASION_JUMP_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "jump + " ); + if (d_JediAI->integer) { + gi.Printf("jump + "); } } } @@ -3577,51 +2715,41 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } } - if ( evasionType == EVASION_NONE ) - { + if (evasionType == EVASION_NONE) { return EVASION_NONE; } -//======================================================================================= - //see if it's okay to jump - Jedi_CheckJumpEvasionSafety( self, cmd, evasionType ); -//======================================================================================= - //stop taunting - TIMER_Set( self, "taunting", 0 ); - //stop gripping - TIMER_Set( self, "gripping", -level.time ); - WP_ForcePowerStop( self, FP_GRIP ); - //stop draining - TIMER_Set( self, "draining", -level.time ); - WP_ForcePowerStop( self, FP_DRAIN ); - - if ( dodgeAnim != -1 ) - {//dodged + //======================================================================================= + // see if it's okay to jump + Jedi_CheckJumpEvasionSafety(self, cmd, evasionType); + //======================================================================================= + // stop taunting + TIMER_Set(self, "taunting", 0); + // stop gripping + TIMER_Set(self, "gripping", -level.time); + WP_ForcePowerStop(self, FP_GRIP); + // stop draining + TIMER_Set(self, "draining", -level.time); + WP_ForcePowerStop(self, FP_DRAIN); + + if (dodgeAnim != -1) { // dodged evasionType = EVASION_DODGE; - NPC_SetAnim( self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - //force them to stop moving in this case + // force them to stop moving in this case self->client->ps.pm_time = self->client->ps.torsoAnimTimer; - //FIXME: maybe make a sound? Like a grunt? EV_JUMP? + // FIXME: maybe make a sound? Like a grunt? EV_JUMP? self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //dodged, not block - if ( d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number ) - { - G_StartMatrixEffect( self ); - } - } - else - { - if ( duckChance ) - { - if ( !Q_irand( 0, duckChance ) ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - if ( evasionType == EVASION_PARRY ) - { + // dodged, not block + if (d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number) { + G_StartMatrixEffect(self); + } + } else { + if (duckChance) { + if (!Q_irand(0, duckChance)) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); + if (evasionType == EVASION_PARRY) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_DUCK; } /* @@ -3633,198 +2761,146 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } - if ( incoming ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (incoming) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } - } - //if ( self->client->ps.saberBlocked != BLOCKED_NONE ) + // if ( self->client->ps.saberBlocked != BLOCKED_NONE ) { - int parryReCalcTime = Jedi_ReCalcParryTime( self, evasionType ); - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + int parryReCalcTime = Jedi_ReCalcParryTime(self, evasionType); + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } } return evasionType; } -static evasionType_t Jedi_CheckEvadeSpecialAttacks( void ) -{ - if ( !NPC - || !NPC->client ) - { +static evasionType_t Jedi_CheckEvadeSpecialAttacks(void) { + if (!NPC || !NPC->client) { return EVASION_NONE; } - if ( !NPC->enemy - || NPC->enemy->health <= 0 - || !NPC->enemy->client ) - {//don't keep blocking him once he's dead (or if not a client) + if (!NPC->enemy || NPC->enemy->health <= 0 || !NPC->enemy->client) { // don't keep blocking him once he's dead (or if not a client) return EVASION_NONE; } - if ( NPC->enemy->s.number >= MAX_CLIENTS ) - {//only do these against player + if (NPC->enemy->s.number >= MAX_CLIENTS) { // only do these against player return EVASION_NONE; } - if ( !TIMER_Done( NPC, "specialEvasion" ) ) - {//still evading from last time + if (!TIMER_Done(NPC, "specialEvasion")) { // still evading from last time return EVASION_NONE; } - if ( NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 - || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7 ) - {//back away from these - if ( (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA - || Q_irand( 0, NPCInfo->rank ) > RANK_LT_JG ) - {//see if we should back off - if ( InFront( NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles ) ) - {//facing me - float minSafeDistSq = (NPC->maxs[0]*1.5f+NPC->enemy->maxs[0]*1.5f+NPC->enemy->client->ps.SaberLength()+24.0f); + if (NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK6 || NPC->enemy->client->ps.torsoAnim == BOTH_SPINATTACK7) { // back away from these + if ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER) || NPC->client->NPC_class == CLASS_SHADOWTROOPER || NPC->client->NPC_class == CLASS_ALORA || + Q_irand(0, NPCInfo->rank) > RANK_LT_JG) { // see if we should back off + if (InFront(NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles)) { // facing me + float minSafeDistSq = (NPC->maxs[0] * 1.5f + NPC->enemy->maxs[0] * 1.5f + NPC->enemy->client->ps.SaberLength() + 24.0f); minSafeDistSq *= minSafeDistSq; - if ( DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ) < minSafeDistSq ) - {//back off! + if (DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin) < minSafeDistSq) { // back off! Jedi_StartBackOff(); return EVASION_OTHER; } } } - } - else - {//check some other attacks? - //check roll-stab - if ( NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_STAB - || (NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_F && ((NPC->enemy->client->pers.lastCommand.buttons&BUTTON_ATTACK)||(NPC->enemy->client->ps.pm_flags&PMF_ATTACK_HELD)) ) ) - {//either already in a roll-stab or may go into one - if ( (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA - || Q_irand( -3, NPCInfo->rank ) > RANK_LT_JG ) - {//see if we should evade - vec3_t yawOnlyAngles = {0, NPC->enemy->currentAngles[YAW], 0 }; - if ( InFront( NPC->currentOrigin, NPC->enemy->currentOrigin, yawOnlyAngles, 0.25f ) ) - {//facing me - float minSafeDistSq = (NPC->maxs[0]*1.5f+NPC->enemy->maxs[0]*1.5f+NPC->enemy->client->ps.SaberLength()+24.0f); + } else { // check some other attacks? + // check roll-stab + if (NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_STAB || + (NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_F && + ((NPC->enemy->client->pers.lastCommand.buttons & BUTTON_ATTACK) || + (NPC->enemy->client->ps.pm_flags & PMF_ATTACK_HELD)))) { // either already in a roll-stab or may go into one + if ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER) || NPC->client->NPC_class == CLASS_SHADOWTROOPER || NPC->client->NPC_class == CLASS_ALORA || + Q_irand(-3, NPCInfo->rank) > RANK_LT_JG) { // see if we should evade + vec3_t yawOnlyAngles = {0, NPC->enemy->currentAngles[YAW], 0}; + if (InFront(NPC->currentOrigin, NPC->enemy->currentOrigin, yawOnlyAngles, 0.25f)) { // facing me + float minSafeDistSq = (NPC->maxs[0] * 1.5f + NPC->enemy->maxs[0] * 1.5f + NPC->enemy->client->ps.SaberLength() + 24.0f); minSafeDistSq *= minSafeDistSq; - float distSq = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - if ( distSq < minSafeDistSq ) - {//evade! - qboolean doJump = (qboolean)( NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_STAB || distSq < 3000.0f );//not much time left, just jump! - if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - || !doJump ) - {//roll? + float distSq = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + if (distSq < minSafeDistSq) { // evade! + qboolean doJump = (qboolean)(NPC->enemy->client->ps.torsoAnim == BOTH_ROLL_STAB || distSq < 3000.0f); // not much time left, just jump! + if ((NPCInfo->scriptFlags & SCF_NO_ACROBATICS) || !doJump) { // roll? vec3_t enemyRight, dir2Me; - AngleVectors( yawOnlyAngles, NULL, enemyRight, NULL ); - VectorSubtract( NPC->currentOrigin, NPC->enemy->currentOrigin, dir2Me ); - VectorNormalize( dir2Me ); - float dot = DotProduct( enemyRight, dir2Me ); + AngleVectors(yawOnlyAngles, NULL, enemyRight, NULL); + VectorSubtract(NPC->currentOrigin, NPC->enemy->currentOrigin, dir2Me); + VectorNormalize(dir2Me); + float dot = DotProduct(enemyRight, dir2Me); ucmd.forwardmove = 0; - TIMER_Start( NPC, "duck", Q_irand( 500, 1500 ) ); + TIMER_Start(NPC, "duck", Q_irand(500, 1500)); ucmd.upmove = -127; - //NOTE: this *assumes* I'm facing him! - if ( dot > 0 ) - {//I'm to his right - if ( !NPC_MoveDirClear( 0, -127, qfalse ) ) - {//fuck, jump instead + // NOTE: this *assumes* I'm facing him! + if (dot > 0) { // I'm to his right + if (!NPC_MoveDirClear(0, -127, qfalse)) { // fuck, jump instead doJump = qtrue; - } - else - { - TIMER_Start( NPC, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( NPC, "strafeRight", 0 ); + } else { + TIMER_Start(NPC, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(NPC, "strafeRight", 0); ucmd.rightmove = -127; - if ( d_JediAI->integer ) - { - Com_Printf( "%s rolling left from roll-stab!\n", NPC->NPC_type ); + if (d_JediAI->integer) { + Com_Printf("%s rolling left from roll-stab!\n", NPC->NPC_type); } - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//fuck it, just force it - NPC_SetAnim(NPC,SETANIM_BOTH,BOTH_ROLL_L,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - G_AddEvent( NPC, EV_ROLL, 0 ); + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // fuck it, just force it + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ROLL_L, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(NPC, EV_ROLL, 0); NPC->client->ps.saberMove = LS_NONE; } } - } - else - {//I'm to his left - if ( !NPC_MoveDirClear( 0, 127, qfalse ) ) - {//fuck, jump instead + } else { // I'm to his left + if (!NPC_MoveDirClear(0, 127, qfalse)) { // fuck, jump instead doJump = qtrue; - } - else - { - TIMER_Start( NPC, "strafeRight", Q_irand( 500, 1500 ) ); - TIMER_Set( NPC, "strafeLeft", 0 ); + } else { + TIMER_Start(NPC, "strafeRight", Q_irand(500, 1500)); + TIMER_Set(NPC, "strafeLeft", 0); ucmd.rightmove = 127; - if ( d_JediAI->integer ) - { - Com_Printf( "%s rolling right from roll-stab!\n", NPC->NPC_type ); + if (d_JediAI->integer) { + Com_Printf("%s rolling right from roll-stab!\n", NPC->NPC_type); } - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//fuck it, just force it - NPC_SetAnim(NPC,SETANIM_BOTH,BOTH_ROLL_R,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - G_AddEvent( NPC, EV_ROLL, 0 ); + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // fuck it, just force it + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ROLL_R, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(NPC, EV_ROLL, 0); NPC->client->ps.saberMove = LS_NONE; } } } - if ( !doJump ) - { - TIMER_Set( NPC, "specialEvasion", 3000 ); + if (!doJump) { + TIMER_Set(NPC, "specialEvasion", 3000); return EVASION_DUCK; } } - //didn't roll, do jump - if ( NPC->s.weapon != WP_SABER - || (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA - || Q_irand( -3, NPCInfo->rank ) > RANK_CREWMAN ) - {//superjump - NPC->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently - if ( Q_irand( 0, 2 ) ) - {//make it a backflip + // didn't roll, do jump + if (NPC->s.weapon != WP_SABER || (NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER) || NPC->client->NPC_class == CLASS_SHADOWTROOPER || + NPC->client->NPC_class == CLASS_ALORA || Q_irand(-3, NPCInfo->rank) > RANK_CREWMAN) { // superjump + NPC->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently + if (Q_irand(0, 2)) { // make it a backflip ucmd.forwardmove = -127; - TIMER_Set( NPC, "roamTime", -level.time ); - TIMER_Set( NPC, "strafeLeft", -level.time ); - TIMER_Set( NPC, "strafeRight", -level.time ); - TIMER_Set( NPC, "walking", -level.time ); - TIMER_Set( NPC, "moveforward", -level.time ); - TIMER_Set( NPC, "movenone", -level.time ); - TIMER_Set( NPC, "moveright", -level.time ); - TIMER_Set( NPC, "moveleft", -level.time ); - TIMER_Set( NPC, "movecenter", -level.time ); - TIMER_Set( NPC, "moveback", Q_irand( 500, 1000 ) ); - if ( d_JediAI->integer ) - { - Com_Printf( "%s backflipping from roll-stab!\n", NPC->NPC_type ); + TIMER_Set(NPC, "roamTime", -level.time); + TIMER_Set(NPC, "strafeLeft", -level.time); + TIMER_Set(NPC, "strafeRight", -level.time); + TIMER_Set(NPC, "walking", -level.time); + TIMER_Set(NPC, "moveforward", -level.time); + TIMER_Set(NPC, "movenone", -level.time); + TIMER_Set(NPC, "moveright", -level.time); + TIMER_Set(NPC, "moveleft", -level.time); + TIMER_Set(NPC, "movecenter", -level.time); + TIMER_Set(NPC, "moveback", Q_irand(500, 1000)); + if (d_JediAI->integer) { + Com_Printf("%s backflipping from roll-stab!\n", NPC->NPC_type); } - } - else - { - if ( d_JediAI->integer ) - { - Com_Printf( "%s force-jumping over roll-stab!\n", NPC->NPC_type ); + } else { + if (d_JediAI->integer) { + Com_Printf("%s force-jumping over roll-stab!\n", NPC->NPC_type); } } - TIMER_Set( NPC, "specialEvasion", 3000 ); + TIMER_Set(NPC, "specialEvasion", 3000); return EVASION_FJUMP; - } - else - {//normal jump + } else { // normal jump ucmd.upmove = 127; - if ( d_JediAI->integer ) - { - Com_Printf( "%s jumping over roll-stab!\n", NPC->NPC_type ); + if (d_JediAI->integer) { + Com_Printf("%s jumping over roll-stab!\n", NPC->NPC_type); } - TIMER_Set( NPC, "specialEvasion", 2000 ); + TIMER_Set(NPC, "specialEvasion", 2000); return EVASION_JUMP; } } @@ -3835,17 +2911,16 @@ static evasionType_t Jedi_CheckEvadeSpecialAttacks( void ) return EVASION_NONE; } -extern int WPDEBUG_SaberColor( saber_colors_t saberColor ); -static qboolean Jedi_SaberBlock( void ) -{ - vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir;//saberBase, - vec3_t pointDir, baseDir, tipDir, saberHitPoint, saberMins={-4,-4,-4}, saberMaxs={4,4,4}; - float pointDist, baseDirPerc; - float dist, bestDist = Q3_INFINITE; - int saberNum = 0, bladeNum = 0; - int closestSaberNum = 0, closestBladeNum = 0; - - //FIXME: reborn don't block enough anymore +extern int WPDEBUG_SaberColor(saber_colors_t saberColor); +static qboolean Jedi_SaberBlock(void) { + vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir; // saberBase, + vec3_t pointDir, baseDir, tipDir, saberHitPoint, saberMins = {-4, -4, -4}, saberMaxs = {4, 4, 4}; + float pointDist, baseDirPerc; + float dist, bestDist = Q3_INFINITE; + int saberNum = 0, bladeNum = 0; + int closestSaberNum = 0, closestBladeNum = 0; + + // FIXME: reborn don't block enough anymore /* //maybe do this on easy only... or only on grunt-level reborn if ( NPC->client->ps.weaponTime ) @@ -3854,13 +2929,11 @@ static qboolean Jedi_SaberBlock( void ) } */ - if ( !TIMER_Done( NPC, "parryReCalcTime" ) ) - {//can't do our own re-think of which parry to use yet + if (!TIMER_Done(NPC, "parryReCalcTime")) { // can't do our own re-think of which parry to use yet return qfalse; } - if ( NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't move the saber to another position yet + if (NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time) { // can't move the saber to another position yet return qfalse; } @@ -3872,14 +2945,13 @@ static qboolean Jedi_SaberBlock( void ) } */ - if ( NPC->enemy->health <= 0 || !NPC->enemy->client ) - {//don't keep blocking him once he's dead (or if not a client) + if (NPC->enemy->health <= 0 || !NPC->enemy->client) { // don't keep blocking him once he's dead (or if not a client) return qfalse; } /* //VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); - //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext ); - VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); + //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext + ); VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); VectorSubtract( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->renderInfo.muzzlePointOld, dir );//get the dir @@ -3919,26 +2991,25 @@ static qboolean Jedi_SaberBlock( void ) } */ - //FIXME: need to check against both sabers/blades now!...? + // FIXME: need to check against both sabers/blades now!...? - for ( saberNum = 0; saberNum < MAX_SABERS; saberNum++ ) - { - for ( bladeNum = 0; bladeNum < NPC->enemy->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - if ( NPC->enemy->client->ps.saber[saberNum].type != SABER_NONE - && NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length > 0 ) - {//valid saber and this blade is on - VectorMA( NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, saberTipOld ); - VectorMA( NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, saberTip ); + for (saberNum = 0; saberNum < MAX_SABERS; saberNum++) { + for (bladeNum = 0; bladeNum < NPC->enemy->client->ps.saber[saberNum].numBlades; bladeNum++) { + if (NPC->enemy->client->ps.saber[saberNum].type != SABER_NONE && + NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length > 0) { // valid saber and this blade is on + VectorMA(NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length, + NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, saberTipOld); + VectorMA(NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].length, + NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, saberTip); - VectorCopy( NPC->currentOrigin, top ); + VectorCopy(NPC->currentOrigin, top); top[2] = NPC->absmax[2]; - VectorCopy( NPC->currentOrigin, bottom ); + VectorCopy(NPC->currentOrigin, bottom); bottom[2] = NPC->absmin[2]; - dist = ShortestLineSegBewteen2LineSegs( NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint ); - if ( dist < bestDist ) - { + dist = ShortestLineSegBewteen2LineSegs(NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, saberTip, bottom, top, saberPoint, + axisPoint); + if (dist < bestDist) { bestDist = dist; closestSaberNum = saberNum; closestBladeNum = bladeNum; @@ -3947,11 +3018,10 @@ static qboolean Jedi_SaberBlock( void ) } } - if ( bestDist > NPC->maxs[0]*5 )//was *3 - {//FIXME: sometimes he reacts when you're too far away to actually hit him - if ( d_JediAI->integer ) - { - Com_Printf( S_COLOR_RED"enemy saber dist: %4.2f\n", bestDist ); + if (bestDist > NPC->maxs[0] * 5) // was *3 + { // FIXME: sometimes he reacts when you're too far away to actually hit him + if (d_JediAI->integer) { + Com_Printf(S_COLOR_RED "enemy saber dist: %4.2f\n", bestDist); } /* if ( bestDist < 300 //close @@ -3962,56 +3032,54 @@ static qboolean Jedi_SaberBlock( void ) } else */ - { - TIMER_Set( NPC, "parryTime", -1 ); - } + { TIMER_Set(NPC, "parryTime", -1); } return qfalse; } dist = bestDist; - if ( d_JediAI->integer ) - { - Com_Printf( S_COLOR_GREEN"enemy saber dist: %4.2f\n", dist ); + if (d_JediAI->integer) { + Com_Printf(S_COLOR_GREEN "enemy saber dist: %4.2f\n", dist); } - //now use the closest blade for my evasion check - VectorMA( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePointOld, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzleDirOld, saberTipOld ); - VectorMA( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzleDir, saberTip ); + // now use the closest blade for my evasion check + VectorMA(NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePointOld, + NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length, + NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzleDirOld, saberTipOld); + VectorMA(NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, + NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length, + NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzleDir, saberTip); - VectorCopy( NPC->currentOrigin, top ); + VectorCopy(NPC->currentOrigin, top); top[2] = NPC->absmax[2]; - VectorCopy( NPC->currentOrigin, bottom ); + VectorCopy(NPC->currentOrigin, bottom); bottom[2] = NPC->absmin[2]; - dist = ShortestLineSegBewteen2LineSegs( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint ); - VectorSubtract( saberPoint, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, pointDir ); - pointDist = VectorLength( pointDir ); + dist = ShortestLineSegBewteen2LineSegs(NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, saberTip, bottom, top, saberPoint, + axisPoint); + VectorSubtract(saberPoint, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, pointDir); + pointDist = VectorLength(pointDir); - if ( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length <= 0 ) - { + if (NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length <= 0) { baseDirPerc = 0.5f; - } - else - { - baseDirPerc = pointDist/NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length; - } - VectorSubtract( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePointOld, baseDir ); - VectorSubtract( saberTip, saberTipOld, tipDir ); - VectorScale( baseDir, baseDirPerc, baseDir ); - VectorMA( baseDir, 1.0f-baseDirPerc, tipDir, dir ); - VectorMA( saberPoint, 200, dir, hitloc ); - - //get the actual point of impact - trace_t tr; - gi.trace( &tr, saberPoint, saberMins, saberMaxs, hitloc, NPC->enemy->s.number, CONTENTS_BODY, (EG2_Collision)0, 0 );//, G2_RETURNONHIT, 10 ); - if ( tr.allsolid || tr.startsolid || tr.fraction >= 1.0f ) - {//estimate - vec3_t dir2Me; - VectorSubtract( axisPoint, saberPoint, dir2Me ); - dist = VectorNormalize( dir2Me ); - if ( DotProduct( dir, dir2Me ) < 0.2f ) - {//saber is not swinging in my direction + } else { + baseDirPerc = pointDist / NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].length; + } + VectorSubtract(NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePoint, + NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].muzzlePointOld, baseDir); + VectorSubtract(saberTip, saberTipOld, tipDir); + VectorScale(baseDir, baseDirPerc, baseDir); + VectorMA(baseDir, 1.0f - baseDirPerc, tipDir, dir); + VectorMA(saberPoint, 200, dir, hitloc); + + // get the actual point of impact + trace_t tr; + gi.trace(&tr, saberPoint, saberMins, saberMaxs, hitloc, NPC->enemy->s.number, CONTENTS_BODY, (EG2_Collision)0, 0); //, G2_RETURNONHIT, 10 ); + if (tr.allsolid || tr.startsolid || tr.fraction >= 1.0f) { // estimate + vec3_t dir2Me; + VectorSubtract(axisPoint, saberPoint, dir2Me); + dist = VectorNormalize(dir2Me); + if (DotProduct(dir, dir2Me) < 0.2f) { // saber is not swinging in my direction /* if ( dist < 300 //close && !Jedi_QuickReactions( NPC )//quick reaction people can interrupt themselves @@ -4021,88 +3089,63 @@ static qboolean Jedi_SaberBlock( void ) } else */ - { - TIMER_Set( NPC, "parryTime", -1 ); - } + { TIMER_Set(NPC, "parryTime", -1); } return qfalse; } - ShortestLineSegBewteen2LineSegs( saberPoint, hitloc, bottom, top, saberHitPoint, hitloc ); + ShortestLineSegBewteen2LineSegs(saberPoint, hitloc, bottom, top, saberHitPoint, hitloc); /* VectorSubtract( saberPoint, axisPoint, dir ); VectorNormalize( dir ); VectorMA( axisPoint, NPC->maxs[0]*1.22, dir, hitloc ); */ - } - else - { - VectorCopy( tr.endpos, hitloc ); + } else { + VectorCopy(tr.endpos, hitloc); } - if ( d_JediAI->integer ) - { - G_DebugLine( saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor( NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].color ), qtrue ); + if (d_JediAI->integer) { + G_DebugLine(saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor(NPC->enemy->client->ps.saber[closestSaberNum].blade[closestBladeNum].color), qtrue); } - //FIXME: if saber is off and/or we have force speed and want to be really cocky, + // FIXME: if saber is off and/or we have force speed and want to be really cocky, // and the swing misses by some amount, we can use the dodges here... :) - evasionType_t evasionType; - if ( (evasionType=Jedi_SaberBlockGo( NPC, &ucmd, hitloc, dir, NULL, dist )) != EVASION_NONE ) - {//did some sort of evasion - if ( evasionType != EVASION_DODGE ) - {//(not dodge) - if ( !NPC->client->ps.saberInFlight ) - {//make sure saber is on + evasionType_t evasionType; + if ((evasionType = Jedi_SaberBlockGo(NPC, &ucmd, hitloc, dir, NULL, dist)) != EVASION_NONE) { // did some sort of evasion + if (evasionType != EVASION_DODGE) { //(not dodge) + if (!NPC->client->ps.saberInFlight) { // make sure saber is on NPC->client->ps.SaberActivate(); } - //debounce our parry recalc time - int parryReCalcTime = Jedi_ReCalcParryTime( NPC, evasionType ); - TIMER_Set( NPC, "parryReCalcTime", Q_irand( 0, parryReCalcTime ) ); - if ( d_JediAI->integer ) - { - gi.Printf( "Keep parry choice until: %d\n", level.time + parryReCalcTime ); + // debounce our parry recalc time + int parryReCalcTime = Jedi_ReCalcParryTime(NPC, evasionType); + TIMER_Set(NPC, "parryReCalcTime", Q_irand(0, parryReCalcTime)); + if (d_JediAI->integer) { + gi.Printf("Keep parry choice until: %d\n", level.time + parryReCalcTime); } - //determine how long to hold this anim - if ( TIMER_Done( NPC, "parryTime" ) ) - { - if ( NPC->client->NPC_class == CLASS_TAVION - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA ) - { - TIMER_Set( NPC, "parryTime", Q_irand( parryReCalcTime/2, parryReCalcTime*1.5 ) ); - } - else if ( NPCInfo->rank >= RANK_LT_JG ) - {//fencers and higher hold a parry less - TIMER_Set( NPC, "parryTime", parryReCalcTime ); - } - else - {//others hold it longer - TIMER_Set( NPC, "parryTime", Q_irand( 1, 2 )*parryReCalcTime ); + // determine how long to hold this anim + if (TIMER_Done(NPC, "parryTime")) { + if (NPC->client->NPC_class == CLASS_TAVION || NPC->client->NPC_class == CLASS_SHADOWTROOPER || NPC->client->NPC_class == CLASS_ALORA) { + TIMER_Set(NPC, "parryTime", Q_irand(parryReCalcTime / 2, parryReCalcTime * 1.5)); + } else if (NPCInfo->rank >= RANK_LT_JG) { // fencers and higher hold a parry less + TIMER_Set(NPC, "parryTime", parryReCalcTime); + } else { // others hold it longer + TIMER_Set(NPC, "parryTime", Q_irand(1, 2) * parryReCalcTime); } } - } - else - {//dodged + } else { // dodged int dodgeTime = NPC->client->ps.torsoAnimTimer; - if ( NPCInfo->rank > RANK_LT_COMM && NPC->client->NPC_class != CLASS_DESANN ) - {//higher-level guys can dodge faster + if (NPCInfo->rank > RANK_LT_COMM && NPC->client->NPC_class != CLASS_DESANN) { // higher-level guys can dodge faster dodgeTime -= 200; } - TIMER_Set( NPC, "parryReCalcTime", dodgeTime ); - TIMER_Set( NPC, "parryTime", dodgeTime ); + TIMER_Set(NPC, "parryReCalcTime", dodgeTime); + TIMER_Set(NPC, "parryTime", dodgeTime); } } - if ( evasionType != EVASION_DUCK_PARRY - && evasionType != EVASION_JUMP_PARRY - && evasionType != EVASION_JUMP - && evasionType != EVASION_DUCK - && evasionType != EVASION_FJUMP ) - { - if ( Jedi_CheckEvadeSpecialAttacks() != EVASION_NONE ) - {//got a new evasion! - //see if it's okay to jump - Jedi_CheckJumpEvasionSafety( NPC, &ucmd, evasionType ); + if (evasionType != EVASION_DUCK_PARRY && evasionType != EVASION_JUMP_PARRY && evasionType != EVASION_JUMP && evasionType != EVASION_DUCK && + evasionType != EVASION_FJUMP) { + if (Jedi_CheckEvadeSpecialAttacks() != EVASION_NONE) { // got a new evasion! + // see if it's okay to jump + Jedi_CheckJumpEvasionSafety(NPC, &ucmd, evasionType); } } return qtrue; @@ -4114,103 +3157,77 @@ Jedi_EvasionSaber defend if other is using saber and attacking me! ------------------------- */ -static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir ) -{ - vec3_t dirEnemy2Me; - int evasionChance = 30;//only step aside 30% if he's moving at me but not attacking - qboolean enemy_attacking = qfalse; - qboolean throwing_saber = qfalse; - qboolean shooting_lightning = qfalse; - - if ( !NPC->enemy->client ) - { +static void Jedi_EvasionSaber(vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir) { + vec3_t dirEnemy2Me; + int evasionChance = 30; // only step aside 30% if he's moving at me but not attacking + qboolean enemy_attacking = qfalse; + qboolean throwing_saber = qfalse; + qboolean shooting_lightning = qfalse; + + if (!NPC->enemy->client) { return; - } - else if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time ) - {//don't try to block/evade an enemy who is in a saberLock + } else if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->client->ps.saberLockTime > level.time) { // don't try to block/evade an enemy who is in a saberLock return; - } - else if ( (NPC->client->ps.saberEventFlags&SEF_LOCK_WON) - && NPC->enemy->painDebounceTime > level.time ) - {//pressing the advantage of winning a saber lock + } else if ((NPC->client->ps.saberEventFlags & SEF_LOCK_WON) && NPC->enemy->painDebounceTime > level.time) { // pressing the advantage of winning a saber + // lock return; } - if ( NPC->enemy->client->ps.saberInFlight && !TIMER_Done( NPC, "taunting" ) ) - {//if he's throwing his saber, stop taunting - TIMER_Set( NPC, "taunting", -level.time ); - if ( !NPC->client->ps.saberInFlight ) - { + if (NPC->enemy->client->ps.saberInFlight && !TIMER_Done(NPC, "taunting")) { // if he's throwing his saber, stop taunting + TIMER_Set(NPC, "taunting", -level.time); + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.SaberActivate(); } } - if ( TIMER_Done( NPC, "parryTime" ) ) - { - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + if (TIMER_Done(NPC, "parryTime")) { + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - { - if ( (!NPC->client->ps.saberInFlight || (NPC->client->ps.dualSabers&&NPC->client->ps.saber[1].Active()) ) - && Jedi_SaberBlock() ) - { + if (NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { + if ((!NPC->client->ps.saberInFlight || (NPC->client->ps.dualSabers && NPC->client->ps.saber[1].Active())) && Jedi_SaberBlock()) { return; } - } - else if ( Jedi_CheckEvadeSpecialAttacks() != EVASION_NONE ) - { + } else if (Jedi_CheckEvadeSpecialAttacks() != EVASION_NONE) { return; } + VectorSubtract(NPC->currentOrigin, NPC->enemy->currentOrigin, dirEnemy2Me); + VectorNormalize(dirEnemy2Me); - VectorSubtract( NPC->currentOrigin, NPC->enemy->currentOrigin, dirEnemy2Me ); - VectorNormalize( dirEnemy2Me ); - - if ( NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - {//enemy is attacking + if (NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { // enemy is attacking enemy_attacking = qtrue; evasionChance = 90; } - if ( (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client->ps.forcePowersActive & (1 << FP_LIGHTNING))) { // enemy is shooting lightning enemy_attacking = qtrue; shooting_lightning = qtrue; evasionChance = 50; } - if ( NPC->enemy->client->ps.saberInFlight - && NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE - && NPC->enemy->client->ps.saberEntityState != SES_RETURNING ) - {//enemy is shooting lightning + if (NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE && + NPC->enemy->client->ps.saberEntityState != SES_RETURNING) { // enemy is shooting lightning enemy_attacking = qtrue; throwing_saber = qtrue; } - //FIXME: this needs to take skill and rank(reborn type) into account much more - if ( Q_irand( 0, 100 ) < evasionChance ) - {//check to see if he's coming at me + // FIXME: this needs to take skill and rank(reborn type) into account much more + if (Q_irand(0, 100) < evasionChance) { // check to see if he's coming at me float facingAmt; - if ( VectorCompare( enemy_movedir, vec3_origin ) || shooting_lightning || throwing_saber ) - {//he's not moving (or he's using a ranged attack), see if he's facing me - vec3_t enemy_fwd; - AngleVectors( NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL ); - facingAmt = DotProduct( enemy_fwd, dirEnemy2Me ); - } - else - {//he's moving - facingAmt = DotProduct( enemy_movedir, dirEnemy2Me ); + if (VectorCompare(enemy_movedir, vec3_origin) || shooting_lightning || + throwing_saber) { // he's not moving (or he's using a ranged attack), see if he's facing me + vec3_t enemy_fwd; + AngleVectors(NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL); + facingAmt = DotProduct(enemy_fwd, dirEnemy2Me); + } else { // he's moving + facingAmt = DotProduct(enemy_movedir, dirEnemy2Me); } - if ( Q_flrand( 0.25, 1 ) < facingAmt ) - {//coming at/facing me! + if (Q_flrand(0.25, 1) < facingAmt) { // coming at/facing me! int whichDefense = 0; /*if ( NPC->client->NPC_class == CLASS_SABOTEUR ) { @@ -4232,114 +3249,82 @@ static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t en return; } } - else */if ( NPC->client->ps.weaponTime - || NPC->client->ps.saberInFlight - || NPC->client->NPC_class == CLASS_BOBAFETT - || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) - || NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - {//I'm attacking or recovering from a parry, can only try to strafe/jump right now - if ( Q_irand( 0, 10 ) < NPCInfo->stats.aggression ) - { + else */ + if (NPC->client->ps.weaponTime || NPC->client->ps.saberInFlight || NPC->client->NPC_class == CLASS_BOBAFETT || + (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) || + NPC->client->NPC_class == CLASS_ROCKETTROOPER) { // I'm attacking or recovering from a parry, can only try to strafe/jump right now + if (Q_irand(0, 10) < NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - { - if ( shooting_lightning ) - {//check for lightning attack - //only valid defense is strafe and/or jump + } else { + if (shooting_lightning) { // check for lightning attack + // only valid defense is strafe and/or jump whichDefense = 100; - } - else if ( throwing_saber ) - {//he's thrown his saber! See if it's coming at me - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (throwing_saber) { // he's thrown his saber! See if it's coming at me + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[NPC->enemy->client->ps.saberEntityNum]; - VectorSubtract( NPC->currentOrigin, saber->currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( !Q_irand( 0, 3 ) ) - { - //Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); - Jedi_Aggression( NPC, 1 ); + VectorSubtract(NPC->currentOrigin, saber->currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (!Q_irand(0, 3)) { + // Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); + Jedi_Aggression(NPC, 1); } - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 100 ) - {//it's close - whichDefense = Q_irand( 3, 6 ); - } - else if ( saberDist < 200 ) - {//got some time, yet, try pushing - whichDefense = Q_irand( 0, 8 ); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 100) { // it's close + whichDefense = Q_irand(3, 6); + } else if (saberDist < 200) { // got some time, yet, try pushing + whichDefense = Q_irand(0, 8); } } } - if ( whichDefense ) - {//already chose one - } - else if ( enemy_dist > 80 || !enemy_attacking ) - {//he's pretty far, or not swinging, just strafe - if ( VectorCompare( enemy_movedir, vec3_origin ) ) - {//if he's not moving, not swinging and far enough away, no evasion necc. + if (whichDefense) { // already chose one + } else if (enemy_dist > 80 || !enemy_attacking) { // he's pretty far, or not swinging, just strafe + if (VectorCompare(enemy_movedir, vec3_origin)) { // if he's not moving, not swinging and far enough away, no evasion necc. return; } - if ( Q_irand( 0, 10 ) < NPCInfo->stats.aggression ) - { + if (Q_irand(0, 10) < NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - {//he's getting close and swinging at me - vec3_t fwd; - //see if I'm facing him - AngleVectors( NPC->client->ps.viewangles, fwd, NULL, NULL ); - if ( DotProduct( enemy_dir, fwd ) < 0.5 ) - {//I'm not really facing him, best option is to strafe - whichDefense = Q_irand( 5, 16 ); - } - else if ( enemy_dist < 56 ) - {//he's very close, maybe we should be more inclined to block or throw - whichDefense = Q_irand( NPCInfo->stats.aggression, 12 ); - } - else - { - whichDefense = Q_irand( 2, 16 ); + } else { // he's getting close and swinging at me + vec3_t fwd; + // see if I'm facing him + AngleVectors(NPC->client->ps.viewangles, fwd, NULL, NULL); + if (DotProduct(enemy_dir, fwd) < 0.5) { // I'm not really facing him, best option is to strafe + whichDefense = Q_irand(5, 16); + } else if (enemy_dist < 56) { // he's very close, maybe we should be more inclined to block or throw + whichDefense = Q_irand(NPCInfo->stats.aggression, 12); + } else { + whichDefense = Q_irand(2, 16); } } } - if ( whichDefense >= 4 && whichDefense <= 12 ) - {//would try to block - if ( NPC->client->ps.saberInFlight ) - {//can't, saber in not in hand, so fall back to strafe/jump + if (whichDefense >= 4 && whichDefense <= 12) { // would try to block + if (NPC->client->ps.saberInFlight) { // can't, saber in not in hand, so fall back to strafe/jump whichDefense = 100; } } - switch( whichDefense ) - { + switch (whichDefense) { case 0: case 1: case 2: case 3: - //use jedi force push? or kick? - //FIXME: try to do this if health low or enemy back to a cliff? - if ( Jedi_DecideKick()//let's try a kick - && ( G_PickAutoMultiKick( NPC, qfalse, qtrue ) != LS_NONE - || (G_CanKickEntity(NPC, NPC->enemy )&&G_PickAutoKick( NPC, NPC->enemy, qtrue )!=LS_NONE) - ) - ) - {//kicked - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); - } - else if ( (NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && TIMER_Done( NPC, "parryTime" ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qfalse ); + // use jedi force push? or kick? + // FIXME: try to do this if health low or enemy back to a cliff? + if (Jedi_DecideKick() // let's try a kick + && (G_PickAutoMultiKick(NPC, qfalse, qtrue) != LS_NONE || + (G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE))) { // kicked + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); + } else if ((NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && + TIMER_Done(NPC, "parryTime")) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qfalse); } break; case 4: @@ -4351,100 +3336,73 @@ static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t en case 10: case 11: case 12: - //try to parry the blow - //gi.Printf( "blocking\n" ); + // try to parry the blow + // gi.Printf( "blocking\n" ); Jedi_SaberBlock(); break; default: - //Evade! - //start a strafe left/right if not already - if ( !Q_irand( 0, 5 ) || !Jedi_Strafe( 300, 1000, 0, 1000, qfalse ) ) - {//certain chance they will pick an alternative evasion - //if couldn't strafe, try a different kind of evasion... - if ( Jedi_DecideKick() && G_CanKickEntity(NPC, NPC->enemy ) && G_PickAutoKick( NPC, NPC->enemy, qtrue ) != LS_NONE ) - {//kicked! - TIMER_Set( NPC, "kickDebounce", Q_irand( 3000, 10000 ) ); - } - else if ( shooting_lightning || throwing_saber || enemy_dist < 80 ) - { - //FIXME: force-jump+forward - jump over the guy! - if ( shooting_lightning || (!Q_irand( 0, 2 ) && NPCInfo->stats.aggression < 4 && TIMER_Done( NPC, "parryTime" ) ) ) - { - if ( (NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && Q_irand( 0, 2 ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qfalse ); - } - else if ( (NPCInfo->rank==RANK_CREWMAN||NPCInfo->rank>RANK_LT_JG) - && !(NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && NPC->client->ps.forceRageRecoveryTime < level.time - && !(NPC->client->ps.forcePowersActive&(1<client->ps ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? + // Evade! + // start a strafe left/right if not already + if (!Q_irand(0, 5) || !Jedi_Strafe(300, 1000, 0, 1000, qfalse)) { // certain chance they will pick an alternative evasion + // if couldn't strafe, try a different kind of evasion... + if (Jedi_DecideKick() && G_CanKickEntity(NPC, NPC->enemy) && G_PickAutoKick(NPC, NPC->enemy, qtrue) != LS_NONE) { // kicked! + TIMER_Set(NPC, "kickDebounce", Q_irand(3000, 10000)); + } else if (shooting_lightning || throwing_saber || enemy_dist < 80) { + // FIXME: force-jump+forward - jump over the guy! + if (shooting_lightning || (!Q_irand(0, 2) && NPCInfo->stats.aggression < 4 && TIMER_Done(NPC, "parryTime"))) { + if ((NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && + Q_irand(0, 2)) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qfalse); + } else if ((NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG) && !(NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && + NPC->client->ps.forceRageRecoveryTime < level.time && !(NPC->client->ps.forcePowersActive & (1 << FP_RAGE)) && + !PM_InKnockDown(&NPC->client->ps)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? NPC->client->ps.forceJumpCharge = 480; - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); - if ( Q_irand( 0, 2 ) ) - { + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); + if (Q_irand(0, 2)) { ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else - { + VectorClear(NPC->client->ps.moveDir); + } else { ucmd.forwardmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //FIXME: if this jump is cleared, we can't block... so pick a random lower block? - if ( Q_irand( 0, 1 ) )//FIXME: make intelligent + // FIXME: if this jump is cleared, we can't block... so pick a random lower block? + if (Q_irand(0, 1)) // FIXME: make intelligent { NPC->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { NPC->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - } - else if ( enemy_attacking ) - { + } else if (enemy_attacking) { Jedi_SaberBlock(); } } - } - else - {//strafed - if ( d_JediAI->integer ) - { - gi.Printf( "def strafe\n" ); + } else { // strafed + if (d_JediAI->integer) { + gi.Printf("def strafe\n"); } - if ( !(NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && NPC->client->ps.forceRageRecoveryTime < level.time - && !(NPC->client->ps.forcePowersActive&(1<rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) - && !PM_InKnockDown( &NPC->client->ps ) - && !Q_irand( 0, 5 ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? - if ( NPC->client->NPC_class == CLASS_BOBAFETT - || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) - || NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - { - NPC->client->ps.forceJumpCharge = 280;//FIXME: calc this intelligently? - } - else - { + if (!(NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && NPC->client->ps.forceRageRecoveryTime < level.time && + !(NPC->client->ps.forcePowersActive & (1 << FP_RAGE)) && (NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG) && + !PM_InKnockDown(&NPC->client->ps) && !Q_irand(0, 5)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? + if (NPC->client->NPC_class == CLASS_BOBAFETT || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) || + NPC->client->NPC_class == CLASS_ROCKETTROOPER) { + NPC->client->ps.forceJumpCharge = 280; // FIXME: calc this intelligently? + } else { NPC->client->ps.forceJumpCharge = 320; } - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); } } break; } - //turn off slow walking no matter what - TIMER_Set( NPC, "walking", -level.time ); - TIMER_Set( NPC, "taunting", -level.time ); + // turn off slow walking no matter what + TIMER_Set(NPC, "walking", -level.time); + TIMER_Set(NPC, "taunting", -level.time); } } } @@ -4461,82 +3419,68 @@ static qboolean Jedi_Flee( void ) } */ - /* ========================================================================================== INTERNAL AI ROUTINES ========================================================================================== */ -gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float minDot ) -{ +gentity_t *Jedi_FindEnemyInCone(gentity_t *self, gentity_t *fallback, float minDot) { vec3_t forward, mins, maxs, dir; - float dist, bestDist = Q3_INFINITE; - gentity_t *enemy = fallback; - gentity_t *check = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int e, numListedEntities; - trace_t tr; - - if ( !self->client ) - { + float dist, bestDist = Q3_INFINITE; + gentity_t *enemy = fallback; + gentity_t *check = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int e, numListedEntities; + trace_t tr; + + if (!self->client) { return enemy; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); - for ( e = 0 ; e < 3 ; e++ ) - { + for (e = 0; e < 3; e++) { mins[e] = self->currentOrigin[e] - 1024; maxs[e] = self->currentOrigin[e] + 1024; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { check = entityList[e]; - if ( check == self ) - {//me + if (check == self) { // me continue; } - if ( !(check->inuse) ) - {//freed + if (!(check->inuse)) { // freed continue; } - if ( !check->client ) - {//not a client - FIXME: what about turrets? + if (!check->client) { // not a client - FIXME: what about turrets? continue; } - if ( check->client->playerTeam != self->client->enemyTeam ) - {//not an enemy - FIXME: what about turrets? + if (check->client->playerTeam != self->client->enemyTeam) { // not an enemy - FIXME: what about turrets? continue; } - if ( check->health <= 0 ) - {//dead + if (check->health <= 0) { // dead continue; } - if ( !gi.inPVS( check->currentOrigin, self->currentOrigin ) ) - {//can't potentially see them + if (!gi.inPVS(check->currentOrigin, self->currentOrigin)) { // can't potentially see them continue; } - VectorSubtract( check->currentOrigin, self->currentOrigin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(check->currentOrigin, self->currentOrigin, dir); + dist = VectorNormalize(dir); - if ( DotProduct( dir, forward ) < minDot ) - {//not in front + if (DotProduct(dir, forward) < minDot) { // not in front continue; } - //really should have a clear LOS to this thing... - gi.trace( &tr, self->currentOrigin, vec3_origin, vec3_origin, check->currentOrigin, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != check->s.number ) - {//must have clear shot + // really should have a clear LOS to this thing... + gi.trace(&tr, self->currentOrigin, vec3_origin, vec3_origin, check->currentOrigin, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.fraction < 1.0f && tr.entityNum != check->s.number) { // must have clear shot continue; } - if ( dist < bestDist ) - {//closer than our last best one + if (dist < bestDist) { // closer than our last best one dist = bestDist; enemy = check; } @@ -4544,169 +3488,124 @@ gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float min return enemy; } -static void Jedi_SetEnemyInfo( vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction ) -{ - if ( !NPC || !NPC->enemy ) - {//no valid enemy +static void Jedi_SetEnemyInfo(vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction) { + if (!NPC || !NPC->enemy) { // no valid enemy return; } - if ( !NPC->enemy->client ) - { - VectorClear( enemy_movedir ); + if (!NPC->enemy->client) { + VectorClear(enemy_movedir); *enemy_movespeed = 0; - VectorCopy( NPC->enemy->currentOrigin, enemy_dest ); - enemy_dest[2] += NPC->enemy->mins[2] + 24;//get it's origin to a height I can work with - VectorSubtract( enemy_dest, NPC->currentOrigin, enemy_dir ); - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - *enemy_dist = VectorNormalize( enemy_dir );// - (NPC->client->ps.saberLengthMax + NPC->maxs[0]*1.5 + 16); - } - else - {//see where enemy is headed - VectorCopy( NPC->enemy->client->ps.velocity, enemy_movedir ); - *enemy_movespeed = VectorNormalize( enemy_movedir ); - //figure out where he'll be, say, 3 frames from now - VectorMA( NPC->enemy->currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest ); - //figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is - VectorSubtract( enemy_dest, NPC->currentOrigin, enemy_dir );//NPC->client->renderInfo.muzzlePoint - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - *enemy_dist = VectorNormalize( enemy_dir ) - (NPC->client->ps.SaberLengthMax() + NPC->maxs[0]*1.5 + 16); - //FIXME: keep a group of enemies around me and use that info to make decisions... + VectorCopy(NPC->enemy->currentOrigin, enemy_dest); + enemy_dest[2] += NPC->enemy->mins[2] + 24; // get it's origin to a height I can work with + VectorSubtract(enemy_dest, NPC->currentOrigin, enemy_dir); + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + *enemy_dist = VectorNormalize(enemy_dir); // - (NPC->client->ps.saberLengthMax + NPC->maxs[0]*1.5 + 16); + } else { // see where enemy is headed + VectorCopy(NPC->enemy->client->ps.velocity, enemy_movedir); + *enemy_movespeed = VectorNormalize(enemy_movedir); + // figure out where he'll be, say, 3 frames from now + VectorMA(NPC->enemy->currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest); + // figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is + VectorSubtract(enemy_dest, NPC->currentOrigin, enemy_dir); // NPC->client->renderInfo.muzzlePoint + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + *enemy_dist = VectorNormalize(enemy_dir) - (NPC->client->ps.SaberLengthMax() + NPC->maxs[0] * 1.5 + 16); + // FIXME: keep a group of enemies around me and use that info to make decisions... // For instance, if there are multiple enemies, evade more, push them away // and use medium attacks. If enemies are using blasters, switch to fast. // If one jedi enemy, use strong attacks. Use grip when fighting one or // two enemies, use lightning spread when fighting multiple enemies, etc. // Also, when kill one, check rest of group instead of walking up to victim. } - //init this to false + // init this to false enemy_in_striking_range = qfalse; - if ( *enemy_dist <= 0.0f ) - { + if (*enemy_dist <= 0.0f) { enemy_in_striking_range = qtrue; - } - else - {//if he's too far away, see if he's at least facing us or coming towards us - if ( *enemy_dist <= 32.0f ) - {//has to be facing us - vec3_t eAngles = {0,NPC->currentAngles[YAW],0}; - if ( InFOV( NPC->currentOrigin, NPC->enemy->currentOrigin, eAngles, 30, 90 ) ) - {//in striking range + } else { // if he's too far away, see if he's at least facing us or coming towards us + if (*enemy_dist <= 32.0f) { // has to be facing us + vec3_t eAngles = {0, NPC->currentAngles[YAW], 0}; + if (InFOV(NPC->currentOrigin, NPC->enemy->currentOrigin, eAngles, 30, 90)) { // in striking range enemy_in_striking_range = qtrue; } } - if ( *enemy_dist >= 64.0f ) - {//we have to be approaching each other + if (*enemy_dist >= 64.0f) { // we have to be approaching each other float vDot = 1.0f; - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//I am moving, see if I'm moving toward the enemy - vec3_t eDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, eDir ); - VectorNormalize( eDir ); - vDot = DotProduct( eDir, NPC->client->ps.velocity ); - } - else if ( NPC->enemy->client && !VectorCompare( NPC->enemy->client->ps.velocity, vec3_origin ) ) - {//I'm not moving, but the enemy is, see if he's moving towards me - vec3_t meDir; - VectorSubtract( NPC->currentOrigin, NPC->enemy->currentOrigin, meDir ); - VectorNormalize( meDir ); - vDot = DotProduct( meDir, NPC->enemy->client->ps.velocity ); - } - else - {//neither of us is moving, below check will fail, so just return + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // I am moving, see if I'm moving toward the enemy + vec3_t eDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, eDir); + VectorNormalize(eDir); + vDot = DotProduct(eDir, NPC->client->ps.velocity); + } else if (NPC->enemy->client && + !VectorCompare(NPC->enemy->client->ps.velocity, vec3_origin)) { // I'm not moving, but the enemy is, see if he's moving towards me + vec3_t meDir; + VectorSubtract(NPC->currentOrigin, NPC->enemy->currentOrigin, meDir); + VectorNormalize(meDir); + vDot = DotProduct(meDir, NPC->enemy->client->ps.velocity); + } else { // neither of us is moving, below check will fail, so just return return; } - if ( vDot >= *enemy_dist ) - {//moving towards each other + if (vDot >= *enemy_dist) { // moving towards each other enemy_in_striking_range = qtrue; } } } } -void NPC_EvasionSaber( void ) -{ - if ( ucmd.upmove <= 0//not jumping - && (!ucmd.upmove || !ucmd.rightmove) )//either just ducking or just strafing (i.e.: not rolling - {//see if we need to avoid their saber - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - //set enemy - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); +void NPC_EvasionSaber(void) { + if (ucmd.upmove <= 0 // not jumping + && (!ucmd.upmove || !ucmd.rightmove)) // either just ducking or just strafing (i.e.: not rolling + { // see if we need to avoid their saber + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + // set enemy + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); } } -extern float WP_SpeedOfMissileForWeapon( int wp, qboolean alt_fire ); -static void Jedi_FaceEnemy( qboolean doPitch ) -{ - vec3_t enemy_eyes, eyes, angles; +extern float WP_SpeedOfMissileForWeapon(int wp, qboolean alt_fire); +static void Jedi_FaceEnemy(qboolean doPitch) { + vec3_t enemy_eyes, eyes, angles; - if ( NPC == NULL ) + if (NPC == NULL) return; - if ( NPC->enemy == NULL ) + if (NPC->enemy == NULL) return; - if ( NPC->client->ps.forcePowersActive & (1<client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//don't update? + if (NPC->client->ps.forcePowersActive & (1 << FP_GRIP) && NPC->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // don't update? NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; return; } - CalcEntitySpot( NPC, SPOT_HEAD, eyes ); - - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_eyes ); - - if ( NPC->client->NPC_class == CLASS_BOBAFETT - && TIMER_Done( NPC, "flameTime" ) - && NPC->s.weapon != WP_NONE - && NPC->s.weapon != WP_DISRUPTOR - && (NPC->s.weapon != WP_ROCKET_LAUNCHER||!(NPCInfo->scriptFlags&SCF_ALT_FIRE)) - && NPC->s.weapon != WP_THERMAL - && NPC->s.weapon != WP_TRIP_MINE - && NPC->s.weapon != WP_DET_PACK - && NPC->s.weapon != WP_STUN_BATON - && NPC->s.weapon != WP_MELEE ) - {//boba leads his enemy - if ( NPC->health < NPC->max_health*0.5f ) - {//lead - float missileSpeed = WP_SpeedOfMissileForWeapon( NPC->s.weapon, ((qboolean)(NPCInfo->scriptFlags&SCF_ALT_FIRE)) ); - if ( missileSpeed ) - { - float eDist = Distance( eyes, enemy_eyes ); - eDist /= missileSpeed;//How many seconds it will take to get to the enemy - VectorMA( enemy_eyes, eDist*Q_flrand(0.95f,1.25f), NPC->enemy->client->ps.velocity, enemy_eyes ); + CalcEntitySpot(NPC, SPOT_HEAD, eyes); + + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_eyes); + + if (NPC->client->NPC_class == CLASS_BOBAFETT && TIMER_Done(NPC, "flameTime") && NPC->s.weapon != WP_NONE && NPC->s.weapon != WP_DISRUPTOR && + (NPC->s.weapon != WP_ROCKET_LAUNCHER || !(NPCInfo->scriptFlags & SCF_ALT_FIRE)) && NPC->s.weapon != WP_THERMAL && NPC->s.weapon != WP_TRIP_MINE && + NPC->s.weapon != WP_DET_PACK && NPC->s.weapon != WP_STUN_BATON && NPC->s.weapon != WP_MELEE) { // boba leads his enemy + if (NPC->health < NPC->max_health * 0.5f) { // lead + float missileSpeed = WP_SpeedOfMissileForWeapon(NPC->s.weapon, ((qboolean)(NPCInfo->scriptFlags & SCF_ALT_FIRE))); + if (missileSpeed) { + float eDist = Distance(eyes, enemy_eyes); + eDist /= missileSpeed; // How many seconds it will take to get to the enemy + VectorMA(enemy_eyes, eDist * Q_flrand(0.95f, 1.25f), NPC->enemy->client->ps.velocity, enemy_eyes); } } } - - //Find the desired angles - if ( !NPC->client->ps.saberInFlight - && (NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 - || NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 - || NPC->client->ps.legsAnim == BOTH_ATTACK_BACK - || NPC->client->ps.legsAnim == BOTH_A7_KICK_B ) - ) - {//point *away* - GetAnglesForDirection( enemy_eyes, eyes, angles ); - } - else if ( NPC->client->ps.legsAnim == BOTH_A7_KICK_R ) - {//keep enemy to right - } - else if ( NPC->client->ps.legsAnim == BOTH_A7_KICK_L ) - {//keep enemy to left - } - else if ( NPC->client->ps.legsAnim == BOTH_A7_KICK_RL - || NPC->client->ps.legsAnim == BOTH_A7_KICK_BF - || NPC->client->ps.legsAnim == BOTH_A7_KICK_S ) - {//??? - } - else - {//point towards him - GetAnglesForDirection( eyes, enemy_eyes, angles ); + + // Find the desired angles + if (!NPC->client->ps.saberInFlight && (NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 || NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 || + NPC->client->ps.legsAnim == BOTH_ATTACK_BACK || NPC->client->ps.legsAnim == BOTH_A7_KICK_B)) { // point *away* + GetAnglesForDirection(enemy_eyes, eyes, angles); + } else if (NPC->client->ps.legsAnim == BOTH_A7_KICK_R) { // keep enemy to right + } else if (NPC->client->ps.legsAnim == BOTH_A7_KICK_L) { // keep enemy to left + } else if (NPC->client->ps.legsAnim == BOTH_A7_KICK_RL || NPC->client->ps.legsAnim == BOTH_A7_KICK_BF || NPC->client->ps.legsAnim == BOTH_A7_KICK_S) { //??? + } else { // point towards him + GetAnglesForDirection(eyes, enemy_eyes, angles); } - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); /* if ( NPC->client->ps.saberBlocked == BLOCKED_UPPER_LEFT ) {//temp hack- to make up for poor coverage on left side @@ -4714,284 +3613,207 @@ static void Jedi_FaceEnemy( qboolean doPitch ) } */ - if ( doPitch ) - { - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); - if ( NPC->client->ps.saberInFlight ) - {//tilt down a little + if (doPitch) { + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); + if (NPC->client->ps.saberInFlight) { // tilt down a little NPCInfo->desiredPitch += 10; } } - //FIXME: else desiredPitch = 0? Or keep previous? + // FIXME: else desiredPitch = 0? Or keep previous? } -static void Jedi_DebounceDirectionChanges( void ) -{ - //FIXME: check these before making fwd/back & right/left decisions? - //Time-debounce changes in forward/back dir - if ( ucmd.forwardmove > 0 ) - { - if ( !TIMER_Done( NPC, "moveback" ) || !TIMER_Done( NPC, "movenone" ) ) - { +static void Jedi_DebounceDirectionChanges(void) { + // FIXME: check these before making fwd/back & right/left decisions? + // Time-debounce changes in forward/back dir + if (ucmd.forwardmove > 0) { + if (!TIMER_Done(NPC, "moveback") || !TIMER_Done(NPC, "movenone")) { ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.rightmove > 0) { ucmd.rightmove = 127; - } - else if ( ucmd.rightmove < 0 ) - { + } else if (ucmd.rightmove < 0) { ucmd.rightmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveback", -level.time ); - if ( TIMER_Done( NPC, "movenone" ) ) - { - TIMER_Set( NPC, "movenone", Q_irand( 1000, 2000 ) ); - } - } - else if ( TIMER_Done( NPC, "moveforward" ) ) - {//FIXME: should be if it's zero? - if ( TIMER_Done( NPC, "lastmoveforward" ) ) - { - int holdDirTime = Q_irand( 500, 2000 ); - TIMER_Set( NPC, "moveforward", holdDirTime ); - //so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last "moveback" timer's ending... - TIMER_Set( NPC, "lastmoveforward", holdDirTime + Q_irand(1000,2000) ); - } - } - else - {//NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? - //if being forced to move forward, do a full-speed moveforward + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveback", -level.time); + if (TIMER_Done(NPC, "movenone")) { + TIMER_Set(NPC, "movenone", Q_irand(1000, 2000)); + } + } else if (TIMER_Done(NPC, "moveforward")) { // FIXME: should be if it's zero? + if (TIMER_Done(NPC, "lastmoveforward")) { + int holdDirTime = Q_irand(500, 2000); + TIMER_Set(NPC, "moveforward", holdDirTime); + // so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last + // "moveback" timer's ending... + TIMER_Set(NPC, "lastmoveforward", holdDirTime + Q_irand(1000, 2000)); + } + } else { // NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? + // if being forced to move forward, do a full-speed moveforward ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - } - else if ( ucmd.forwardmove < 0 ) - { - if ( !TIMER_Done( NPC, "moveforward" ) || !TIMER_Done( NPC, "movenone" ) ) - { + } else if (ucmd.forwardmove < 0) { + if (!TIMER_Done(NPC, "moveforward") || !TIMER_Done(NPC, "movenone")) { ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.rightmove > 0) { ucmd.rightmove = 127; - } - else if ( ucmd.rightmove < 0 ) - { + } else if (ucmd.rightmove < 0) { ucmd.rightmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveforward", -level.time ); - if ( TIMER_Done( NPC, "movenone" ) ) - { - TIMER_Set( NPC, "movenone", Q_irand( 1000, 2000 ) ); - } - } - else if ( TIMER_Done( NPC, "moveback" ) ) - {//FIXME: should be if it's zero? - if ( TIMER_Done( NPC, "lastmoveback" ) ) - { - int holdDirTime = Q_irand( 500, 2000 ); - TIMER_Set( NPC, "moveback", holdDirTime ); - //so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last "moveback" timer's ending... - TIMER_Set( NPC, "lastmoveback", holdDirTime + Q_irand(1000,2000) ); - } - } - else - {//NOTE: edge checking should stop me if this is bad... - //if being forced to move back, do a full-speed moveback + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveforward", -level.time); + if (TIMER_Done(NPC, "movenone")) { + TIMER_Set(NPC, "movenone", Q_irand(1000, 2000)); + } + } else if (TIMER_Done(NPC, "moveback")) { // FIXME: should be if it's zero? + if (TIMER_Done(NPC, "lastmoveback")) { + int holdDirTime = Q_irand(500, 2000); + TIMER_Set(NPC, "moveback", holdDirTime); + // so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last + // "moveback" timer's ending... + TIMER_Set(NPC, "lastmoveback", holdDirTime + Q_irand(1000, 2000)); + } + } else { // NOTE: edge checking should stop me if this is bad... + // if being forced to move back, do a full-speed moveback ucmd.forwardmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - } - else if ( !TIMER_Done( NPC, "moveforward" ) ) - {//NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? + } else if (!TIMER_Done(NPC, "moveforward")) { // NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPC, "moveback" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPC, "moveback")) { // NOTE: edge checking should stop me if this is bad... ucmd.forwardmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //Time-debounce changes in right/left dir - if ( ucmd.rightmove > 0 ) - { - if ( !TIMER_Done( NPC, "moveleft" ) || !TIMER_Done( NPC, "movecenter" ) ) - { + // Time-debounce changes in right/left dir + if (ucmd.rightmove > 0) { + if (!TIMER_Done(NPC, "moveleft") || !TIMER_Done(NPC, "movecenter")) { ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.forwardmove > 0) { ucmd.forwardmove = 127; - } - else if ( ucmd.forwardmove < 0 ) - { + } else if (ucmd.forwardmove < 0) { ucmd.forwardmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveleft", -level.time ); - if ( TIMER_Done( NPC, "movecenter" ) ) - { - TIMER_Set( NPC, "movecenter", Q_irand( 1000, 2000 ) ); - } - } - else if ( TIMER_Done( NPC, "moveright" ) ) - {//FIXME: should be if it's zero? - if ( TIMER_Done( NPC, "lastmoveright" ) ) - { - int holdDirTime = Q_irand( 250, 1500 ); - TIMER_Set( NPC, "moveright", holdDirTime ); - //so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last "moveback" timer's ending... - TIMER_Set( NPC, "lastmoveright", holdDirTime + Q_irand(1000,2000) ); - } - } - else - {//NOTE: edge checking should stop me if this is bad... - //if being forced to move back, do a full-speed moveright + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveleft", -level.time); + if (TIMER_Done(NPC, "movecenter")) { + TIMER_Set(NPC, "movecenter", Q_irand(1000, 2000)); + } + } else if (TIMER_Done(NPC, "moveright")) { // FIXME: should be if it's zero? + if (TIMER_Done(NPC, "lastmoveright")) { + int holdDirTime = Q_irand(250, 1500); + TIMER_Set(NPC, "moveright", holdDirTime); + // so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last + // "moveback" timer's ending... + TIMER_Set(NPC, "lastmoveright", holdDirTime + Q_irand(1000, 2000)); + } + } else { // NOTE: edge checking should stop me if this is bad... + // if being forced to move back, do a full-speed moveright ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - } - else if ( ucmd.rightmove < 0 ) - { - if ( !TIMER_Done( NPC, "moveright" ) || !TIMER_Done( NPC, "movecenter" ) ) - { + } else if (ucmd.rightmove < 0) { + if (!TIMER_Done(NPC, "moveright") || !TIMER_Done(NPC, "movecenter")) { ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.forwardmove > 0) { ucmd.forwardmove = 127; - } - else if ( ucmd.forwardmove < 0 ) - { + } else if (ucmd.forwardmove < 0) { ucmd.forwardmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveright", -level.time ); - if ( TIMER_Done( NPC, "movecenter" ) ) - { - TIMER_Set( NPC, "movecenter", Q_irand( 1000, 2000 ) ); - } - } - else if ( TIMER_Done( NPC, "moveleft" ) ) - {//FIXME: should be if it's zero? - if ( TIMER_Done( NPC, "lastmoveleft" ) ) - { - int holdDirTime = Q_irand( 250, 1500 ); - TIMER_Set( NPC, "moveleft", holdDirTime ); - //so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last "moveback" timer's ending... - TIMER_Set( NPC, "lastmoveleft", holdDirTime + Q_irand(1000,2000) ); - } - } - else - {//NOTE: edge checking should stop me if this is bad... - //if being forced to move back, do a full-speed moveleft + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveright", -level.time); + if (TIMER_Done(NPC, "movecenter")) { + TIMER_Set(NPC, "movecenter", Q_irand(1000, 2000)); + } + } else if (TIMER_Done(NPC, "moveleft")) { // FIXME: should be if it's zero? + if (TIMER_Done(NPC, "lastmoveleft")) { + int holdDirTime = Q_irand(250, 1500); + TIMER_Set(NPC, "moveleft", holdDirTime); + // so we don't keep doing this over and over again - new nav stuff makes them coast to a stop, so they could be just slowing down from the last + // "moveback" timer's ending... + TIMER_Set(NPC, "lastmoveleft", holdDirTime + Q_irand(1000, 2000)); + } + } else { // NOTE: edge checking should stop me if this is bad... + // if being forced to move back, do a full-speed moveleft ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - } - else if ( !TIMER_Done( NPC, "moveright" ) ) - {//NOTE: edge checking should stop me if this is bad... + } else if (!TIMER_Done(NPC, "moveright")) { // NOTE: edge checking should stop me if this is bad... ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPC, "moveleft" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPC, "moveleft")) { // NOTE: edge checking should stop me if this is bad... ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } -static void Jedi_TimersApply( void ) -{ - //use careful anim/slower movement if not already moving - if ( !ucmd.forwardmove && !TIMER_Done( NPC, "walking" ) ) - { +static void Jedi_TimersApply(void) { + // use careful anim/slower movement if not already moving + if (!ucmd.forwardmove && !TIMER_Done(NPC, "walking")) { ucmd.buttons |= (BUTTON_WALKING); } - if ( !TIMER_Done( NPC, "taunting" ) ) - { + if (!TIMER_Done(NPC, "taunting")) { ucmd.buttons |= (BUTTON_WALKING); } - if ( !ucmd.rightmove ) - {//only if not already strafing - //FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too - if ( !TIMER_Done( NPC, "strafeLeft" ) ) - { - if ( NPCInfo->desiredYaw > NPC->client->ps.viewangles[YAW] + 60 ) - {//we want to turn left, don't apply the strafing - } - else - {//go ahead and strafe left + if (!ucmd.rightmove) { // only if not already strafing + // FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too + if (!TIMER_Done(NPC, "strafeLeft")) { + if (NPCInfo->desiredYaw > NPC->client->ps.viewangles[YAW] + 60) { // we want to turn left, don't apply the strafing + } else { // go ahead and strafe left ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); - } - } - else if ( !TIMER_Done( NPC, "strafeRight" ) ) - { - if ( NPCInfo->desiredYaw < NPC->client->ps.viewangles[YAW] - 60 ) - {//we want to turn right, don't apply the strafing + VectorClear(NPC->client->ps.moveDir); } - else - {//go ahead and strafe left + } else if (!TIMER_Done(NPC, "strafeRight")) { + if (NPCInfo->desiredYaw < NPC->client->ps.viewangles[YAW] - 60) { // we want to turn right, don't apply the strafing + } else { // go ahead and strafe left ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } } Jedi_DebounceDirectionChanges(); - if ( !TIMER_Done( NPC, "gripping" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (!TIMER_Done(NPC, "gripping")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around ucmd.buttons |= BUTTON_FORCEGRIP; } - if ( !TIMER_Done( NPC, "draining" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (!TIMER_Done(NPC, "draining")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around ucmd.buttons |= BUTTON_FORCE_DRAIN; } - if ( !TIMER_Done( NPC, "holdLightning" ) ) - {//hold down the lightning key + if (!TIMER_Done(NPC, "holdLightning")) { // hold down the lightning key ucmd.buttons |= BUTTON_FORCE_LIGHTNING; } } -static void Jedi_CombatTimersUpdate( int enemy_dist ) -{ - if ( Jedi_CultistDestroyer( NPC ) ) - { - Jedi_Aggression( NPC, 5 ); +static void Jedi_CombatTimersUpdate(int enemy_dist) { + if (Jedi_CultistDestroyer(NPC)) { + Jedi_Aggression(NPC, 5); return; } -//===START MISSING CODE================================================================= - if ( TIMER_Done( NPC, "roamTime" ) ) - { - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - //okay, now mess with agression - if ( NPC->enemy && NPC->enemy->client ) - { - switch( NPC->enemy->client->ps.weapon ) - { - //FIXME: add new weapons + //===START MISSING CODE================================================================= + if (TIMER_Done(NPC, "roamTime")) { + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + // okay, now mess with agression + if (NPC->enemy && NPC->enemy->client) { + switch (NPC->enemy->client->ps.weapon) { + // FIXME: add new weapons case WP_SABER: - //If enemy has a lightsaber, always close in - if ( !NPC->enemy->client->ps.SaberActive() ) - {//fool! Standing around unarmed, charge! - //Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); - Jedi_Aggression( NPC, 2 ); - } - else - { - //Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // If enemy has a lightsaber, always close in + if (!NPC->enemy->client->ps.SaberActive()) { // fool! Standing around unarmed, charge! + // Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); + Jedi_Aggression(NPC, 2); + } else { + // Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); + Jedi_Aggression(NPC, 1); } break; case WP_BLASTER: @@ -5004,18 +3826,16 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) case WP_FLECHETTE: case WP_ROCKET_LAUNCHER: case WP_CONCUSSION: - //if he has a blaster, move in when: - //They're not shooting at me - if ( NPC->enemy->attackDebounceTime < level.time ) - {//does this apply to players? - //Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // if he has a blaster, move in when: + // They're not shooting at me + if (NPC->enemy->attackDebounceTime < level.time) { // does this apply to players? + // Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); + Jedi_Aggression(NPC, 1); } - //He's closer than a dist that gives us time to deflect - if ( enemy_dist < 256 ) - { - //Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // He's closer than a dist that gives us time to deflect + if (enemy_dist < 256) { + // Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); + Jedi_Aggression(NPC, 1); } break; default: @@ -5024,31 +3844,23 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } - if ( TIMER_Done( NPC, "noStrafe" ) && TIMER_Done( NPC, "strafeLeft" ) && TIMER_Done( NPC, "strafeRight" ) ) - { - //FIXME: Maybe more likely to do this if aggression higher? Or some other stat? - if ( !Q_irand( 0, 4 ) ) - {//start a strafe - if ( Jedi_Strafe( 1000, 3000, 0, 4000, qtrue ) ) - { - if ( d_JediAI->integer ) - { - gi.Printf( "off strafe\n" ); + if (TIMER_Done(NPC, "noStrafe") && TIMER_Done(NPC, "strafeLeft") && TIMER_Done(NPC, "strafeRight")) { + // FIXME: Maybe more likely to do this if aggression higher? Or some other stat? + if (!Q_irand(0, 4)) { // start a strafe + if (Jedi_Strafe(1000, 3000, 0, 4000, qtrue)) { + if (d_JediAI->integer) { + gi.Printf("off strafe\n"); } } - } - else - {//postpone any strafing for a while - TIMER_Set( NPC, "noStrafe", Q_irand( 1000, 3000 ) ); + } else { // postpone any strafing for a while + TIMER_Set(NPC, "noStrafe", Q_irand(1000, 3000)); } } -//===END MISSING CODE================================================================= - if ( NPC->client->ps.saberEventFlags ) - {//some kind of saber combat event is still pending + //===END MISSING CODE================================================================= + if (NPC->client->ps.saberEventFlags) { // some kind of saber combat event is still pending int newFlags = NPC->client->ps.saberEventFlags; - if ( NPC->client->ps.saberEventFlags&SEF_PARRIED ) - {//parried - TIMER_Set( NPC, "parryTime", -1 ); + if (NPC->client->ps.saberEventFlags & SEF_PARRIED) { // parried + TIMER_Set(NPC, "parryTime", -1); /* if ( NPCInfo->rank >= RANK_LT_JG ) { @@ -5059,113 +3871,87 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } */ - if ( NPC->enemy && (!NPC->enemy->client||PM_SaberInKnockaway( NPC->enemy->client->ps.saberMove )) ) - {//advance! - Jedi_Aggression( NPC, 1 );//get closer - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//use a faster attack - } - else - { - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (NPC->enemy && (!NPC->enemy->client || PM_SaberInKnockaway(NPC->enemy->client->ps.saberMove))) { // advance! + Jedi_Aggression(NPC, 1); // get closer + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); // use a faster attack + } else { + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we parried\n", level.time ); - Jedi_Aggression( NPC, -1 ); + // Com_Printf( "(%d) drop agg - we parried\n", level.time ); + Jedi_Aggression(NPC, -1); } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } } - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCInfo->stats.aggression, level.time + 100 ); + if (d_JediAI->integer) { + gi.Printf("(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCInfo->stats.aggression, level.time + 100); } newFlags &= ~SEF_PARRIED; } - if ( !NPC->client->ps.weaponTime && (NPC->client->ps.saberEventFlags&SEF_HITENEMY) )//hit enemy - {//we hit our enemy last time we swung, drop our aggression - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (!NPC->client->ps.weaponTime && (NPC->client->ps.saberEventFlags & SEF_HITENEMY)) // hit enemy + { // we hit our enemy last time we swung, drop our aggression + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); - Jedi_Aggression( NPC, -1 ); - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) HIT: agg %d\n", level.time, NPCInfo->stats.aggression ); - } - if ( !Q_irand( 0, 3 ) - && NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time - && NPC->painDebounceTime < level.time - 1000 ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 3000 ); + // Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); + Jedi_Aggression(NPC, -1); + if (d_JediAI->integer) { + gi.Printf("(%d) HIT: agg %d\n", level.time, NPCInfo->stats.aggression); + } + if (!Q_irand(0, 3) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && + NPC->painDebounceTime < level.time - 1000) { + G_AddVoiceEvent(NPC, Q_irand(EV_GLOAT1, EV_GLOAT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - if ( !Q_irand( 0, 2 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) ); + if (!Q_irand(0, 2)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); } newFlags &= ~SEF_HITENEMY; } - if ( (NPC->client->ps.saberEventFlags&SEF_BLOCKED) ) - {//was blocked whilst attacking - if ( PM_SaberInBrokenParry( NPC->client->ps.saberMove ) - || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { - //Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); - if ( NPC->client->ps.saberInFlight ) - {//lost our saber, too!!! - Jedi_Aggression( NPC, -5 );//really really really should back off!!! - } - else - { - Jedi_Aggression( NPC, -2 );//really should back off! + if ((NPC->client->ps.saberEventFlags & SEF_BLOCKED)) { // was blocked whilst attacking + if (PM_SaberInBrokenParry(NPC->client->ps.saberMove) || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { + // Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); + if (NPC->client->ps.saberInFlight) { // lost our saber, too!!! + Jedi_Aggression(NPC, -5); // really really really should back off!!! + } else { + Jedi_Aggression(NPC, -2); // really should back off! } - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) );//use a stronger attack - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression ); + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); // use a stronger attack + if (d_JediAI->integer) { + gi.Printf("(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression); } - } - else - { - if ( !Q_irand( 0, 2 ) )//FIXME: dependant on rank/diff? + } else { + if (!Q_irand(0, 2)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); - Jedi_Aggression( NPC, -1 ); - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression ); + // Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); + Jedi_Aggression(NPC, -1); + if (d_JediAI->integer) { + gi.Printf("(%d) BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression); } } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); } } newFlags &= ~SEF_BLOCKED; - //FIXME: based on the type of parry the enemy is doing and my skill, + // FIXME: based on the type of parry the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. } - if ( NPC->client->ps.saberEventFlags&SEF_DEFLECTED ) - {//deflected a shot + if (NPC->client->ps.saberEventFlags & SEF_DEFLECTED) { // deflected a shot newFlags &= ~SEF_DEFLECTED; - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } } - if ( NPC->client->ps.saberEventFlags&SEF_HITWALL ) - {//hit a wall + if (NPC->client->ps.saberEventFlags & SEF_HITWALL) { // hit a wall newFlags &= ~SEF_HITWALL; } - if ( NPC->client->ps.saberEventFlags&SEF_HITOBJECT ) - {//hit some other damagable object - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (NPC->client->ps.saberEventFlags & SEF_HITOBJECT) { // hit some other damagable object + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } newFlags &= ~SEF_HITOBJECT; } @@ -5173,205 +3959,154 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } -static void Jedi_CombatIdle( int enemy_dist ) -{ - if ( !TIMER_Done( NPC, "parryTime" ) ) - { +static void Jedi_CombatIdle(int enemy_dist) { + if (!TIMER_Done(NPC, "parryTime")) { return; } - if ( NPC->client->ps.saberInFlight ) - {//don't do this idle stuff if throwing saber + if (NPC->client->ps.saberInFlight) { // don't do this idle stuff if throwing saber return; } - if ( NPC->client->ps.forcePowersActive&(1<client->ps.forceRageRecoveryTime > level.time ) - {//never taunt while raging or recovering from rage + if (NPC->client->ps.forcePowersActive & (1 << FP_RAGE) || + NPC->client->ps.forceRageRecoveryTime > level.time) { // never taunt while raging or recovering from rage return; } - if ( NPC->client->ps.stats[STAT_WEAPONS]&(1<client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER)) { // never taunt when holding scepter return; } - if ( NPC->client->ps.saber[0].type == SABER_SITH_SWORD ) - {//never taunt when holding sith sword + if (NPC->client->ps.saber[0].type == SABER_SITH_SWORD) { // never taunt when holding sith sword return; } - //FIXME: make these distance numbers defines? - if ( enemy_dist >= 64 ) - {//FIXME: only do this if standing still? - //based on aggression, flaunt/taunt + // FIXME: make these distance numbers defines? + if (enemy_dist >= 64) { // FIXME: only do this if standing still? + // based on aggression, flaunt/taunt int chance = 20; - if ( NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - { + if (NPC->client->NPC_class == CLASS_SHADOWTROOPER) { chance = 10; } - //FIXME: possibly throw local objects at enemy? - if ( Q_irand( 2, chance ) < NPCInfo->stats.aggression ) - { - if ( TIMER_Done( NPC, "chatter" ) ) - {//FIXME: add more taunt behaviors - //FIXME: sometimes he turns it off, then turns it right back on again??? - if ( enemy_dist > 200 - && NPC->client->NPC_class != CLASS_BOBAFETT - && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) - && NPC->client->NPC_class != CLASS_ROCKETTROOPER - && NPC->client->ps.SaberActive() - && !Q_irand( 0, 5 ) ) - {//taunt even more, turn off the saber - //FIXME: don't do this if health low? - if ( NPC->client->ps.saberAnimLevel != SS_STAFF - && NPC->client->ps.saberAnimLevel != SS_DUAL ) - {//those taunts leave saber on - WP_DeactivateSaber( NPC ); + // FIXME: possibly throw local objects at enemy? + if (Q_irand(2, chance) < NPCInfo->stats.aggression) { + if (TIMER_Done(NPC, "chatter")) { // FIXME: add more taunt behaviors + // FIXME: sometimes he turns it off, then turns it right back on again??? + if (enemy_dist > 200 && NPC->client->NPC_class != CLASS_BOBAFETT && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) && + NPC->client->NPC_class != CLASS_ROCKETTROOPER && NPC->client->ps.SaberActive() && !Q_irand(0, 5)) { // taunt even more, turn off the saber + // FIXME: don't do this if health low? + if (NPC->client->ps.saberAnimLevel != SS_STAFF && NPC->client->ps.saberAnimLevel != SS_DUAL) { // those taunts leave saber on + WP_DeactivateSaber(NPC); } - //Don't attack for a bit + // Don't attack for a bit NPCInfo->stats.aggression = 3; - //FIXME: maybe start strafing? - //debounce this - if ( NPC->client->playerTeam != TEAM_PLAYER && !Q_irand( 0, 1 )) - { + // FIXME: maybe start strafing? + // debounce this + if (NPC->client->playerTeam != TEAM_PLAYER && !Q_irand(0, 1)) { NPC->client->ps.taunting = level.time + 100; - TIMER_Set( NPC, "chatter", Q_irand( 5000, 10000 ) ); - TIMER_Set( NPC, "taunting", 5500 ); - } - else - { + TIMER_Set(NPC, "chatter", Q_irand(5000, 10000)); + TIMER_Set(NPC, "taunting", 5500); + } else { Jedi_BattleTaunt(); - TIMER_Set( NPC, "taunting", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPC, "taunting", Q_irand(5000, 10000)); } - } - else if ( Jedi_BattleTaunt() ) - {//FIXME: pick some anims + } else if (Jedi_BattleTaunt()) { // FIXME: pick some anims } } } } } -extern qboolean PM_SaberInParry( int move ); -static qboolean Jedi_AttackDecide( int enemy_dist ) -{ - if ( !TIMER_Done( NPC, "allyJediDelay" ) ) - { +extern qboolean PM_SaberInParry(int move); +static qboolean Jedi_AttackDecide(int enemy_dist) { + if (!TIMER_Done(NPC, "allyJediDelay")) { return qfalse; } - if ( Jedi_CultistDestroyer( NPC ) ) - {//destroyer - if ( enemy_dist <= 32 ) - {//go boom! - //float? - //VectorClear( NPC->client->ps.velocity ); - //NPC->client->ps.gravity = 0; - //NPC->svFlags |= SVF_CUSTOM_GRAVITY; - //NPC->client->moveType = MT_FLYSWIM; - //NPC->flags |= FL_NO_KNOCKBACK; + if (Jedi_CultistDestroyer(NPC)) { // destroyer + if (enemy_dist <= 32) { // go boom! + // float? + // VectorClear( NPC->client->ps.velocity ); + // NPC->client->ps.gravity = 0; + // NPC->svFlags |= SVF_CUSTOM_GRAVITY; + // NPC->client->moveType = MT_FLYSWIM; + // NPC->flags |= FL_NO_KNOCKBACK; NPC->flags |= FL_GODMODE; NPC->takedamage = qfalse; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPC->client->ps.forcePowersActive |= ( 1 << FP_RAGE ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPC->client->ps.forcePowersActive |= (1 << FP_RAGE); NPC->painDebounceTime = NPC->useDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; return qtrue; } return qfalse; } - if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time - && NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not + if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client->ps.saberLockTime > level.time && + NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not return qfalse; } - if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage with an attack! - int chance = 0; - if ( (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) ) - {//desann and luke + if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage with an attack! + int chance = 0; + if ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER)) { // desann and luke chance = 20; - } - else if ( NPC->client->NPC_class == CLASS_TAVION - || NPC->client->NPC_class == CLASS_ALORA ) - {//tavion + } else if (NPC->client->NPC_class == CLASS_TAVION || NPC->client->NPC_class == CLASS_ALORA) { // tavion chance = 10; - } - else if ( NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - {//shadowtrooper + } else if (NPC->client->NPC_class == CLASS_SHADOWTROOPER) { // shadowtrooper chance = 5; - } - else if ( NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG ) - {//fencer + } else if (NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG) { // fencer chance = 5; - } - else - { + } else { chance = NPCInfo->rank; } - if ( Q_irand( 0, 30 ) < chance ) - {//based on skill with some randomness - NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON;//clear this now that we are using the opportunity - TIMER_Set( NPC, "noRetreat", Q_irand( 500, 2000 ) ); - //FIXME: check enemy_dist? + if (Q_irand(0, 30) < chance) { // based on skill with some randomness + NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; // clear this now that we are using the opportunity + TIMER_Set(NPC, "noRetreat", Q_irand(500, 2000)); + // FIXME: check enemy_dist? NPC->client->ps.weaponTime = NPCInfo->shotTime = NPC->attackDebounceTime = 0; - //NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPC->client->ps.saberBlocked = BLOCKED_NONE; - WeaponThink( qtrue ); + WeaponThink(qtrue); return qtrue; } } - if ( NPC->client->NPC_class == CLASS_TAVION || - NPC->client->NPC_class == CLASS_ALORA || - NPC->client->NPC_class == CLASS_SHADOWTROOPER || - ( NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG ) || - ( NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) ) - {//tavion, fencers, jedi trainer are all good at following up a parry with an attack - if ( ( PM_SaberInParry( NPC->client->ps.saberMove ) || PM_SaberInKnockaway( NPC->client->ps.saberMove ) ) - && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//try to attack straight from a parry + if (NPC->client->NPC_class == CLASS_TAVION || NPC->client->NPC_class == CLASS_ALORA || NPC->client->NPC_class == CLASS_SHADOWTROOPER || + (NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG) || + (NPC->client->NPC_class == CLASS_JEDI && + NPCInfo->rank == RANK_COMMANDER)) { // tavion, fencers, jedi trainer are all good at following up a parry with an attack + if ((PM_SaberInParry(NPC->client->ps.saberMove) || PM_SaberInKnockaway(NPC->client->ps.saberMove)) && + NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // try to attack straight from a parry NPC->client->ps.weaponTime = NPCInfo->shotTime = NPC->attackDebounceTime = 0; - //NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPC->client->ps.saberBlocked = BLOCKED_NONE; - Jedi_AdjustSaberAnimLevel( NPC, SS_FAST );//try to follow-up with a quick attack - WeaponThink( qtrue ); + Jedi_AdjustSaberAnimLevel(NPC, SS_FAST); // try to follow-up with a quick attack + WeaponThink(qtrue); return qtrue; } } - //try to hit them if we can - if ( !enemy_in_striking_range ) - { + // try to hit them if we can + if (!enemy_in_striking_range) { return qfalse; } - if ( !TIMER_Done( NPC, "parryTime" ) ) - { + if (!TIMER_Done(NPC, "parryTime")) { return qfalse; } - if ( (NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//not allowed to attack + if ((NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // not allowed to attack return qfalse; } - if ( !(ucmd.buttons&BUTTON_ATTACK) - && !(ucmd.buttons&BUTTON_ALT_ATTACK) - && !(ucmd.buttons&BUTTON_FORCE_FOCUS) ) - {//not already attacking - //Try to attack - WeaponThink( qtrue ); + if (!(ucmd.buttons & BUTTON_ATTACK) && !(ucmd.buttons & BUTTON_ALT_ATTACK) && !(ucmd.buttons & BUTTON_FORCE_FOCUS)) { // not already attacking + // Try to attack + WeaponThink(qtrue); } - //FIXME: Maybe try to push enemy off a ledge? + // FIXME: Maybe try to push enemy off a ledge? - //close enough to step forward + // close enough to step forward - //FIXME: an attack debounce timer other than the phaser debounce time? + // FIXME: an attack debounce timer other than the phaser debounce time? // or base it on aggression? - if ( ucmd.buttons&BUTTON_ATTACK && !NPC_Jumping()) - {//attacking + if (ucmd.buttons & BUTTON_ATTACK && !NPC_Jumping()) { // attacking /* if ( enemy_dist > 32 && NPCInfo->stats.aggression >= 4 ) {//move forward if we're too far away and we're chasing him @@ -5382,28 +4117,23 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) ucmd.forwardmove = -127; } */ - //FIXME: based on the type of parry/attack the enemy is doing and my skill, + // FIXME: based on the type of parry/attack the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. - //FIXME: have this interact with/override above strafing code? - if ( !ucmd.rightmove ) - {//not already strafing - if ( !Q_irand( 0, 3 ) ) - {//25% chance of doing this - vec3_t right, dir2enemy; - - AngleVectors( NPC->currentAngles, NULL, right, NULL ); - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentAngles, dir2enemy ); - if ( DotProduct( right, dir2enemy ) > 0 ) - {//he's to my right, strafe left + // FIXME: have this interact with/override above strafing code? + if (!ucmd.rightmove) { // not already strafing + if (!Q_irand(0, 3)) { // 25% chance of doing this + vec3_t right, dir2enemy; + + AngleVectors(NPC->currentAngles, NULL, right, NULL); + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentAngles, dir2enemy); + if (DotProduct(right, dir2enemy) > 0) { // he's to my right, strafe left ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); - } - else - {//he's to my left, strafe right + VectorClear(NPC->client->ps.moveDir); + } else { // he's to my left, strafe right ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } } @@ -5413,78 +4143,52 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) return qfalse; } - -extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ); -extern qboolean PM_KickingAnim( int anim ); -static void Jedi_CheckEnemyMovement( float enemy_dist ) -{ - if ( !NPC->enemy || !NPC->enemy->client ) - { +extern void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir); +extern qboolean PM_KickingAnim(int anim); +static void Jedi_CheckEnemyMovement(float enemy_dist) { + if (!NPC->enemy || !NPC->enemy->client) { return; } - if ( !(NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) ) - { - if ( PM_KickingAnim( NPC->enemy->client->ps.legsAnim ) - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE - //FIXME: I'm relatively close to him - && (NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_RL - || NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_BF - || NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_S - || (NPC->enemy->enemy && NPC->enemy->enemy == NPC)) - ) - {//run into the kick! + if (!(NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER)) { + if (PM_KickingAnim(NPC->enemy->client->ps.legsAnim) && + NPC->client->ps.groundEntityNum != ENTITYNUM_NONE + // FIXME: I'm relatively close to him + && (NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_RL || NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_BF || + NPC->enemy->client->ps.legsAnim == BOTH_A7_KICK_S || (NPC->enemy->enemy && NPC->enemy->enemy == NPC))) { // run into the kick! ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); Jedi_Advance(); - } - else if ( NPC->enemy->client->ps.torsoAnim == BOTH_A7_HILT - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//run into the hilt bash - //FIXME : only if in front! + } else if (NPC->enemy->client->ps.torsoAnim == BOTH_A7_HILT && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // run into the hilt bash + // FIXME : only if in front! ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); Jedi_Advance(); - } - else if ( (NPC->enemy->client->ps.torsoAnim == BOTH_A6_FB - || NPC->enemy->client->ps.torsoAnim == BOTH_A6_LR) - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//run into the attack - //FIXME : only if on R/L or F/B? + } else if ((NPC->enemy->client->ps.torsoAnim == BOTH_A6_FB || NPC->enemy->client->ps.torsoAnim == BOTH_A6_LR) && + NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // run into the attack + // FIXME : only if on R/L or F/B? ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); Jedi_Advance(); - } - else if ( NPC->enemy->enemy && NPC->enemy->enemy == NPC ) - {//enemy is mad at *me* - if ( NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 - || NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN - || NPC->enemy->client->ps.legsAnim == BOTH_FLIP_ATTACK7 ) - {//enemy is flipping over me - if ( Q_irand( 0, NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + } else if (NPC->enemy->enemy && NPC->enemy->enemy == NPC) { // enemy is mad at *me* + if (NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 || NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN || + NPC->enemy->client->ps.legsAnim == BOTH_FLIP_ATTACK7) { // enemy is flipping over me + if (Q_irand(0, NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); - } - } - else if ( NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP ) - {//he's flipping off a wall - if ( NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//still in air - if ( enemy_dist < 256 ) - {//close - if ( Q_irand( 0, NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); + } + } else if (NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT || + NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP || + NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP) { // he's flipping off a wall + if (NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE) { // still in air + if (enemy_dist < 256) { // close + if (Q_irand(0, NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... /* ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; VectorClear( NPC->client->ps.moveDir ); @@ -5496,63 +4200,52 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); TIMER_Set( NPC, "noturn", Q_irand( 200, 500 ) ); */ - //stop current movement + // stop current movement ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "noturn", Q_irand( 250, 500 )*(3-g_spskill->integer) ); + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPC, "noturn", Q_irand(250, 500) * (3 - g_spskill->integer)); vec3_t enemyFwd, dest, dir; - VectorCopy( NPC->enemy->client->ps.velocity, enemyFwd ); - VectorNormalize( enemyFwd ); - VectorMA( NPC->enemy->currentOrigin, -64, enemyFwd, dest ); - VectorSubtract( dest, NPC->currentOrigin, dir ); - if ( VectorNormalize( dir ) > 32 ) - { - G_UcmdMoveForDir( NPC, &ucmd, dir ); - } - else - { - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); + VectorCopy(NPC->enemy->client->ps.velocity, enemyFwd); + VectorNormalize(enemyFwd); + VectorMA(NPC->enemy->currentOrigin, -64, enemyFwd, dest); + VectorSubtract(dest, NPC->currentOrigin, dir); + if (VectorNormalize(dir) > 32) { + G_UcmdMoveForDir(NPC, &ucmd, dir); + } else { + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); } } } } - } - else if ( NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1 ) - {//he's stabbing backwards - if ( enemy_dist < 256 && enemy_dist > 64 ) - {//close - if ( !InFront( NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles, 0.0f ) ) - {//behind him - if ( !Q_irand( 0, NPCInfo->rank ) ) - {//be nice and stand still for him... - //stop current movement + } else if (NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1) { // he's stabbing backwards + if (enemy_dist < 256 && enemy_dist > 64) { // close + if (!InFront(NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles, 0.0f)) { // behind him + if (!Q_irand(0, NPCInfo->rank)) { // be nice and stand still for him... + // stop current movement ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); vec3_t enemyFwd, dest, dir; - AngleVectors( NPC->enemy->currentAngles, enemyFwd, NULL, NULL ); - VectorMA( NPC->enemy->currentOrigin, -32, enemyFwd, dest ); - VectorSubtract( dest, NPC->currentOrigin, dir ); - if ( VectorNormalize( dir ) > 64 ) - { - G_UcmdMoveForDir( NPC, &ucmd, dir ); - } - else - { - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); + AngleVectors(NPC->enemy->currentAngles, enemyFwd, NULL, NULL); + VectorMA(NPC->enemy->currentOrigin, -32, enemyFwd, dest); + VectorSubtract(dest, NPC->currentOrigin, dir); + if (VectorNormalize(dir) > 64) { + G_UcmdMoveForDir(NPC, &ucmd, dir); + } else { + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); } } } @@ -5560,233 +4253,179 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) } } } - //FIXME: also: + // FIXME: also: // If enemy doing wall flip, keep running forward // If enemy doing back-attack and we're behind him keep running forward toward his back, don't strafe } -static void Jedi_CheckJumps( void ) -{ - if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { +static void Jedi_CheckJumps(void) { + if ((NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { NPC->client->ps.forceJumpCharge = 0; ucmd.upmove = 0; return; } - //FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb - //FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? - vec3_t jumpVel = {0,0,0}; + // FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb + // FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? + vec3_t jumpVel = {0, 0, 0}; - if ( NPC->client->ps.forceJumpCharge ) - { - //gi.Printf( "(%d) force jump\n", level.time ); - WP_GetVelocityForForceJump( NPC, jumpVel, &ucmd ); - } - else if ( ucmd.upmove > 0 ) - { - //gi.Printf( "(%d) regular jump\n", level.time ); - VectorCopy( NPC->client->ps.velocity, jumpVel ); + if (NPC->client->ps.forceJumpCharge) { + // gi.Printf( "(%d) force jump\n", level.time ); + WP_GetVelocityForForceJump(NPC, jumpVel, &ucmd); + } else if (ucmd.upmove > 0) { + // gi.Printf( "(%d) regular jump\n", level.time ); + VectorCopy(NPC->client->ps.velocity, jumpVel); jumpVel[2] = JUMP_VELOCITY; - } - else - { + } else { return; } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( !jumpVel[0] && !jumpVel[1] )//FIXME: && !ucmd.forwardmove && !ucmd.rightmove? - {//we assume a jump straight up is safe - //gi.Printf( "(%d) jump straight up is safe\n", level.time ); + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (!jumpVel[0] && !jumpVel[1]) // FIXME: && !ucmd.forwardmove && !ucmd.rightmove? + { // we assume a jump straight up is safe + // gi.Printf( "(%d) jump straight up is safe\n", level.time ); return; } - //Now predict where this is going - //in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there - trace_t trace; - trajectory_t tr; - vec3_t lastPos, testPos, bottom; - int elapsedTime; + // Now predict where this is going + // in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there + trace_t trace; + trajectory_t tr; + vec3_t lastPos, testPos, bottom; + int elapsedTime; - VectorCopy( NPC->currentOrigin, tr.trBase ); - VectorCopy( jumpVel, tr.trDelta ); + VectorCopy(NPC->currentOrigin, tr.trBase); + VectorCopy(jumpVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; - VectorCopy( NPC->currentOrigin, lastPos ); - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500 ) - { - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - //FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... - if ( testPos[2] < lastPos[2] ) - {//going down, don't check for BOTCLIP - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 );//FIXME: include CONTENTS_BOTCLIP? - } - else - {//going up, check for BOTCLIP - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); - } - if ( trace.allsolid || trace.startsolid ) - {//WTF? - //FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? + VectorCopy(NPC->currentOrigin, lastPos); + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to + // apex and down? + for (elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500) { + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + // FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... + if (testPos[2] < lastPos[2]) { // going down, don't check for BOTCLIP + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); // FIXME: include CONTENTS_BOTCLIP? + } else { // going up, check for BOTCLIP + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, (EG2_Collision)0, 0); + } + if (trace.allsolid || trace.startsolid) { // WTF? + // FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? goto jump_unsafe; return; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + if (trace.fraction < 1.0f) { // hit something + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush goto jump_unsafe; return; } - //FIXME: trace through func_glass? + // FIXME: trace through func_glass? break; } - VectorCopy( testPos, lastPos ); + VectorCopy(testPos, lastPos); } - //okay, reached end of jump, now trace down from here for a floor - VectorCopy( trace.endpos, bottom ); - if ( bottom[2] > NPC->currentOrigin[2] ) - {//only care about dist down from current height or lower + // okay, reached end of jump, now trace down from here for a floor + VectorCopy(trace.endpos, bottom); + if (bottom[2] > NPC->currentOrigin[2]) { // only care about dist down from current height or lower bottom[2] = NPC->currentOrigin[2]; - } - else if ( NPC->currentOrigin[2] - bottom[2] > 400 ) - {//whoa, long drop, don't do it! - //probably no floor at end of jump, so don't jump + } else if (NPC->currentOrigin[2] - bottom[2] > 400) { // whoa, long drop, don't do it! + // probably no floor at end of jump, so don't jump goto jump_unsafe; return; } bottom[2] -= 128; - gi.trace( &trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0f ) - {//hit ground! - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//landed on an ent + gi.trace(&trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid || trace.fraction < 1.0f) { // hit ground! + if (trace.entityNum < ENTITYNUM_WORLD) { // landed on an ent gentity_t *groundEnt = &g_entities[trace.entityNum]; - if ( groundEnt->svFlags&SVF_GLASS_BRUSH ) - {//don't land on breakable glass! + if (groundEnt->svFlags & SVF_GLASS_BRUSH) { // don't land on breakable glass! goto jump_unsafe; return; } } - //gi.Printf( "(%d) jump is safe\n", level.time ); + // gi.Printf( "(%d) jump is safe\n", level.time ); return; } jump_unsafe: - //probably no floor at end of jump, so don't jump - //gi.Printf( "(%d) unsafe jump cleared\n", level.time ); + // probably no floor at end of jump, so don't jump + // gi.Printf( "(%d) unsafe jump cleared\n", level.time ); NPC->client->ps.forceJumpCharge = 0; ucmd.upmove = 0; } -extern void RT_JetPackEffect( int duration ); -void RT_CheckJump( void ) -{ +extern void RT_JetPackEffect(int duration); +void RT_CheckJump(void) { int jumpEntNum = ENTITYNUM_NONE; - vec3_t jumpPos = {0,0,0}; - - if ( !NPCInfo->goalEntity ) - { - if ( NPC->enemy ) - { - //FIXME: debounce this? - if ( TIMER_Done( NPC, "roamTime" ) - && Q_irand( 0, 9 ) ) - {//okay to try to find another spot to be - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE);//must have a clear shot at enemy - float enemyDistSq = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - //FIXME: base these ranges on weapon - if ( enemyDistSq > (2048*2048) ) - {//hmm, close in? + vec3_t jumpPos = {0, 0, 0}; + + if (!NPCInfo->goalEntity) { + if (NPC->enemy) { + // FIXME: debounce this? + if (TIMER_Done(NPC, "roamTime") && Q_irand(0, 9)) { // okay to try to find another spot to be + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); // must have a clear shot at enemy + float enemyDistSq = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + // FIXME: base these ranges on weapon + if (enemyDistSq > (2048 * 2048)) { // hmm, close in? cpFlags |= CP_APPROACH_ENEMY; - } - else if ( enemyDistSq < (256*256) ) - {//back off! + } else if (enemyDistSq < (256 * 256)) { // back off! cpFlags |= CP_RETREAT; } int sendFlags = cpFlags; - int cp = NPC_FindCombatPointRetry( NPC->currentOrigin, - NPC->currentOrigin, - NPC->currentOrigin, - &sendFlags, - 256, - NPCInfo->lastFailedCombatPoint ); - if ( cp == -1 ) - {//try again, no route needed since we can rocket-jump to it! + int cp = NPC_FindCombatPointRetry(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, &sendFlags, 256, NPCInfo->lastFailedCombatPoint); + if (cp == -1) { // try again, no route needed since we can rocket-jump to it! cpFlags &= ~CP_HAS_ROUTE; - cp = NPC_FindCombatPointRetry( NPC->currentOrigin, - NPC->currentOrigin, - NPC->currentOrigin, - &cpFlags, - 256, - NPCInfo->lastFailedCombatPoint ); - } - if ( cp != -1 ) - { - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + cp = NPC_FindCombatPointRetry(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, &cpFlags, 256, NPCInfo->lastFailedCombatPoint); } - else - {//FIXME: okay to do this if have good close-range weapon... - //FIXME: should we really try to go right for him?! - //NPCInfo->goalEntity = NPC->enemy; + if (cp != -1) { + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + } else { // FIXME: okay to do this if have good close-range weapon... + // FIXME: should we really try to go right for him?! + // NPCInfo->goalEntity = NPC->enemy; jumpEntNum = NPC->enemy->s.number; - VectorCopy( NPC->enemy->currentOrigin, jumpPos ); - //return; + VectorCopy(NPC->enemy->currentOrigin, jumpPos); + // return; } - TIMER_Set( NPC, "roamTime", Q_irand( 3000, 12000 ) ); - } - else - {//FIXME: okay to do this if have good close-range weapon... - //FIXME: should we really try to go right for him?! - //NPCInfo->goalEntity = NPC->enemy; + TIMER_Set(NPC, "roamTime", Q_irand(3000, 12000)); + } else { // FIXME: okay to do this if have good close-range weapon... + // FIXME: should we really try to go right for him?! + // NPCInfo->goalEntity = NPC->enemy; jumpEntNum = NPC->enemy->s.number; - VectorCopy( NPC->enemy->currentOrigin, jumpPos ); - //return; + VectorCopy(NPC->enemy->currentOrigin, jumpPos); + // return; } - } - else - { + } else { return; } - } - else - { + } else { jumpEntNum = NPCInfo->goalEntity->s.number; - VectorCopy( NPCInfo->goalEntity->currentOrigin, jumpPos ); + VectorCopy(NPCInfo->goalEntity->currentOrigin, jumpPos); } vec3_t vec2Goal; - VectorSubtract( jumpPos, NPC->currentOrigin, vec2Goal ); - if ( fabs( vec2Goal[2] ) < 32 ) - {//not a big height diff, see how far it is + VectorSubtract(jumpPos, NPC->currentOrigin, vec2Goal); + if (fabs(vec2Goal[2]) < 32) { // not a big height diff, see how far it is vec2Goal[2] = 0; - if ( VectorLengthSquared( vec2Goal ) < (256*256) ) - {//too close! Don't rocket-jump to it... + if (VectorLengthSquared(vec2Goal) < (256 * 256)) { // too close! Don't rocket-jump to it... return; } } - //If we can't get straight at him - if ( !Jedi_ClearPathToSpot( jumpPos, jumpEntNum ) ) - {//hunt him down - if ( (NPC_ClearLOS( NPC->enemy )||NPCInfo->enemyLastSeenTime>level.time-500) - && InFOV( jumpPos, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 60 ) ) - { - if ( NPC_TryJump( jumpPos ) ) // Rocket Trooper - {//just do the jetpack effect for a litte bit - RT_JetPackEffect( Q_irand( 800, 1500) ); + // If we can't get straight at him + if (!Jedi_ClearPathToSpot(jumpPos, jumpEntNum)) { // hunt him down + if ((NPC_ClearLOS(NPC->enemy) || NPCInfo->enemyLastSeenTime > level.time - 500) && + InFOV(jumpPos, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 60)) { + if (NPC_TryJump(jumpPos)) // Rocket Trooper + { // just do the jetpack effect for a litte bit + RT_JetPackEffect(Q_irand(800, 1500)); return; } } - if ( Jedi_Hunt() && !(NPCInfo->aiFlags&NPCAI_BLOCKED) )//FIXME: have to do this because they can ping-pong forever - {//can macro-navigate to him + if (Jedi_Hunt() && !(NPCInfo->aiFlags & NPCAI_BLOCKED)) // FIXME: have to do this because they can ping-pong forever + { // can macro-navigate to him return; - } - else - {//FIXME: try to find a waypoint that can see enemy, jump from there - if ( STEER::HasBeenBlockedFor(NPC, 2000) ) - {//try to jump to the blockedTargetPosition - if ( NPC_TryJump(NPCInfo->blockedTargetPosition) ) // Rocket Trooper - {//just do the jetpack effect for a litte bit - RT_JetPackEffect( Q_irand( 800, 1500) ); + } else { // FIXME: try to find a waypoint that can see enemy, jump from there + if (STEER::HasBeenBlockedFor(NPC, 2000)) { // try to jump to the blockedTargetPosition + if (NPC_TryJump(NPCInfo->blockedTargetPosition)) // Rocket Trooper + { // just do the jetpack effect for a litte bit + RT_JetPackEffect(Q_irand(800, 1500)); } } } @@ -5795,32 +4434,28 @@ void RT_CheckJump( void ) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -static void Jedi_Combat( void ) -{ - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - trace_t trace; +static void Jedi_Combat(void) { + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + trace_t trace; - //See where enemy will be 300 ms from now - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); + // See where enemy will be 300 ms from now + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); - if ( NPC_Jumping( ) ) - {//I'm in the middle of a jump, so just see if I should attack - Jedi_AttackDecide( enemy_dist ); + if (NPC_Jumping()) { // I'm in the middle of a jump, so just see if I should attack + Jedi_AttackDecide(enemy_dist); return; } - if ( TIMER_Done( NPC, "allyJediDelay" ) ) - { - if ( !(NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//not gripping - //If we can't get straight at him - if ( !Jedi_ClearPathToSpot( enemy_dest, NPC->enemy->s.number ) ) - {//hunt him down - //gi.Printf( "No Clear Path\n" ); - if ( (NPC_ClearLOS( NPC->enemy )||NPCInfo->enemyLastSeenTime>level.time-500) && NPC_FaceEnemy( qtrue ) )//( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && + if (TIMER_Done(NPC, "allyJediDelay")) { + if (!(NPC->client->ps.forcePowersActive & (1 << FP_GRIP)) || NPC->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // not gripping + // If we can't get straight at him + if (!Jedi_ClearPathToSpot(enemy_dest, NPC->enemy->s.number)) { // hunt him down + // gi.Printf( "No Clear Path\n" ); + if ((NPC_ClearLOS(NPC->enemy) || NPCInfo->enemyLastSeenTime > level.time - 500) && + NPC_FaceEnemy(qtrue)) //( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && { - //try to jump to him? + // try to jump to him? /* vec3_t end; VectorCopy( NPC->currentOrigin, end ); @@ -5845,154 +4480,130 @@ static void Jedi_Combat( void ) } } */ - //FIXME: about every 1 second calc a velocity, - //run a loop of traces with evaluate trajectory - //for gravity with my size, see if it makes it... - //this will also catch misacalculations that send you off ledges! - //gi.Printf( "Considering Jump\n" ); - if (NPC->client && NPC->client->NPC_class==CLASS_BOBAFETT) - { + // FIXME: about every 1 second calc a velocity, + // run a loop of traces with evaluate trajectory + // for gravity with my size, see if it makes it... + // this will also catch misacalculations that send you off ledges! + // gi.Printf( "Considering Jump\n" ); + if (NPC->client && NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); } - /* else if ( NPC_TryJump( NPC->enemy ) ) // Jedi, can see enemy, but can't get to him - {//FIXME: what about jumping to his enemyLastSeenLocation? - return; - }*/ + /* else if ( NPC_TryJump( NPC->enemy ) ) // Jedi, can see enemy, but can't get to him + {//FIXME: what about jumping to his enemyLastSeenLocation? + return; + }*/ } - //Check for evasion - if ( TIMER_Done( NPC, "parryTime" ) ) - {//finished parrying - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPC, "parryTime")) { // finished parrying + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( Jedi_Hunt() && !(NPCInfo->aiFlags&NPCAI_BLOCKED) )//FIXME: have to do this because they can ping-pong forever - {//can macro-navigate to him - if ( enemy_dist < 384 && !Q_irand( 0, 10 ) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && !NPC_ClearLOS( NPC->enemy ) ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JLOST1, EV_JLOST3 ), 3000 ); + if (Jedi_Hunt() && !(NPCInfo->aiFlags & NPCAI_BLOCKED)) // FIXME: have to do this because they can ping-pong forever + { // can macro-navigate to him + if (enemy_dist < 384 && !Q_irand(0, 10) && NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && !NPC_ClearLOS(NPC->enemy)) { + G_AddVoiceEvent(NPC, Q_irand(EV_JLOST1, EV_JLOST3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } - if (NPC->client && NPC->client->NPC_class==CLASS_BOBAFETT) - { + if (NPC->client && NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); } return; } - //well, try to head for his last seen location - /* - else if ( Jedi_Track() ) - { - return; - } - */ else - {//FIXME: try to find a waypoint that can see enemy, jump from there - /* if ( STEER::HasBeenBlockedFor(NPC, 3000) ) - {//try to jump to the blockedDest - if (NPCInfo->blockedTargetEntity) - { - NPC_TryJump(NPCInfo->blockedTargetEntity); // commented Out - } - else + // well, try to head for his last seen location + /* + else if ( Jedi_Track() ) { - NPC_TryJump(NPCInfo->blockedTargetPosition);// commented Out + return; } - }*/ - + */ + else { // FIXME: try to find a waypoint that can see enemy, jump from there + /* if ( STEER::HasBeenBlockedFor(NPC, 3000) ) + {//try to jump to the blockedDest + if (NPCInfo->blockedTargetEntity) + { + NPC_TryJump(NPCInfo->blockedTargetEntity); // commented Out + } + else + { + NPC_TryJump(NPCInfo->blockedTargetPosition);// commented Out + } + }*/ } } } - //else, we can see him or we can't track him at all + // else, we can see him or we can't track him at all - //every few seconds, decide if we should we advance or retreat? - Jedi_CombatTimersUpdate( enemy_dist ); + // every few seconds, decide if we should we advance or retreat? + Jedi_CombatTimersUpdate(enemy_dist); - //We call this even if lost enemy to keep him moving and to update the taunting behavior - //maintain a distance from enemy appropriate for our aggression level - Jedi_CombatDistance( enemy_dist ); + // We call this even if lost enemy to keep him moving and to update the taunting behavior + // maintain a distance from enemy appropriate for our aggression level + Jedi_CombatDistance(enemy_dist); } - //if ( !enemy_lost ) - if (NPC->client->NPC_class != CLASS_BOBAFETT) - { - //Update our seen enemy position - if ( !NPC->enemy->client || ( NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) ) - { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + // if ( !enemy_lost ) + if (NPC->client->NPC_class != CLASS_BOBAFETT) { + // Update our seen enemy position + if (!NPC->enemy->client || (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE)) { + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); } NPCInfo->enemyLastSeenTime = level.time; } - //Turn to face the enemy - if ( TIMER_Done( NPC, "noturn" ) && !NPC_Jumping() ) - { - Jedi_FaceEnemy( qtrue ); + // Turn to face the enemy + if (TIMER_Done(NPC, "noturn") && !NPC_Jumping()) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - //Check for evasion - if ( TIMER_Done( NPC, "parryTime" ) ) - {//finished parrying - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPC, "parryTime")) { // finished parrying + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPC->enemy->s.weapon == WP_SABER ) - { - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); - } - else - {//do we need to do any evasion for other kinds of enemies? + if (NPC->enemy->s.weapon == WP_SABER) { + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); + } else { // do we need to do any evasion for other kinds of enemies? } - //apply strafing/walking timers, etc. + // apply strafing/walking timers, etc. Jedi_TimersApply(); - if ( TIMER_Done( NPC, "allyJediDelay" ) ) - { - if ( ( !NPC->client->ps.saberInFlight || (NPC->client->ps.saberAnimLevel == SS_DUAL && NPC->client->ps.saber[1].Active()) ) - && (!(NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) ) - {//not throwing saber or using force grip - //see if we can attack - if ( !Jedi_AttackDecide( enemy_dist ) ) - {//we're not attacking, decide what else to do - Jedi_CombatIdle( enemy_dist ); - //FIXME: lower aggression when actually strike offensively? Or just when do damage? - } - else - {//we are attacking - //stop taunting - TIMER_Set( NPC, "taunting", -level.time ); - } - } - else - { - } - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (TIMER_Done(NPC, "allyJediDelay")) { + if ((!NPC->client->ps.saberInFlight || (NPC->client->ps.saberAnimLevel == SS_DUAL && NPC->client->ps.saber[1].Active())) && + (!(NPC->client->ps.forcePowersActive & (1 << FP_GRIP)) || + NPC->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2)) { // not throwing saber or using force grip + // see if we can attack + if (!Jedi_AttackDecide(enemy_dist)) { // we're not attacking, decide what else to do + Jedi_CombatIdle(enemy_dist); + // FIXME: lower aggression when actually strike offensively? Or just when do damage? + } else { // we are attacking + // stop taunting + TIMER_Set(NPC, "taunting", -level.time); + } + } else { + } + if (NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); - } - else if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - { + } else if (NPC->client->NPC_class == CLASS_ROCKETTROOPER) { RT_FireDecide(); } } - //Check for certain enemy special moves - Jedi_CheckEnemyMovement( enemy_dist ); - //Make sure that we don't jump off ledges over long drops + // Check for certain enemy special moves + Jedi_CheckEnemyMovement(enemy_dist); + // Make sure that we don't jump off ledges over long drops Jedi_CheckJumps(); - //Just make sure we don't strafe into walls or off cliffs + // Just make sure we don't strafe into walls or off cliffs - if ( VectorCompare( NPC->client->ps.moveDir, vec3_origin )//stomped the NAV system's moveDir - && !NPC_MoveDirClear( ucmd.forwardmove, ucmd.rightmove, qtrue ) )//check ucmd-driven movement - {//uh-oh, we are going to fall or hit something + if (VectorCompare(NPC->client->ps.moveDir, vec3_origin) // stomped the NAV system's moveDir + && !NPC_MoveDirClear(ucmd.forwardmove, ucmd.rightmove, qtrue)) // check ucmd-driven movement + { // uh-oh, we are going to fall or hit something /* navInfo_t info; //Get the move info @@ -6002,13 +4613,12 @@ static void Jedi_Combat( void ) NPC_MoveToGoal( qfalse ); } */ - //reset the timers. - TIMER_Set( NPC, "strafeLeft", 0 ); - TIMER_Set( NPC, "strafeRight", 0 ); + // reset the timers. + TIMER_Set(NPC, "strafeLeft", 0); + TIMER_Set(NPC, "strafeRight", 0); } } - /* ========================================================================================== EXTERNALLY CALLED BEHAVIOR STATES @@ -6021,133 +4631,99 @@ NPC_Jedi_Pain ------------------------- */ -void NPC_Jedi_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - //FIXME: base the actual aggression add/subtract on health? - //FIXME: don't do this more than once per frame? - //FIXME: when take pain, stop force gripping....? - if ( other->s.weapon == WP_SABER ) - {//back off - TIMER_Set( self, "parryTime", -1 ); - if ( self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",self->NPC_type) ) - {//less for Desann - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*50; - } - else if ( self->NPC->rank >= RANK_LT_JG ) - { - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*100;//300 - } - else - { - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*200;//500 - } - if ( !Q_irand( 0, 3 ) ) - {//ouch... maybe switch up which saber power level we're using - Jedi_AdjustSaberAnimLevel( self, Q_irand( SS_FAST, SS_STRONG ) ); - } - if ( !Q_irand( 0, 1 ) )//damage > 20 || self->health < 40 || +void NPC_Jedi_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + // FIXME: base the actual aggression add/subtract on health? + // FIXME: don't do this more than once per frame? + // FIXME: when take pain, stop force gripping....? + if (other->s.weapon == WP_SABER) { // back off + TIMER_Set(self, "parryTime", -1); + if (self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", self->NPC_type)) { // less for Desann + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 50; + } else if (self->NPC->rank >= RANK_LT_JG) { + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 100; // 300 + } else { + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 200; // 500 + } + if (!Q_irand(0, 3)) { // ouch... maybe switch up which saber power level we're using + Jedi_AdjustSaberAnimLevel(self, Q_irand(SS_FAST, SS_STRONG)); + } + if (!Q_irand(0, 1)) // damage > 20 || self->health < 40 || { - //Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); - Jedi_Aggression( self, -1 ); + // Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); + Jedi_Aggression(self, -1); } - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time+500 ); + if (d_JediAI->integer) { + gi.Printf("(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time + 500); } - //for testing only - // Figure out what quadrant the hit was in. - if ( d_JediAI->integer ) - { - vec3_t diff, fwdangles, right; + // for testing only + // Figure out what quadrant the hit was in. + if (d_JediAI->integer) { + vec3_t diff, fwdangles, right; - VectorSubtract( point, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(point, self->client->renderInfo.eyePoint, diff); diff[2] = 0; fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); float rightdot = DotProduct(right, diff); float zdiff = point[2] - self->client->renderInfo.eyePoint[2]; - gi.Printf( "(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2]-self->absmin[2],zdiff,rightdot); + gi.Printf("(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2] - self->absmin[2], zdiff, rightdot); } - } - else - {//attack - //Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); - Jedi_Aggression( self, 1 ); + } else { // attack + // Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); + Jedi_Aggression(self, 1); } self->NPC->enemyCheckDebounceTime = 0; - WP_ForcePowerStop( self, FP_GRIP ); + WP_ForcePowerStop(self, FP_GRIP); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } - //drop me from the ceiling if I'm on it - if ( Jedi_WaitingAmbush( self ) ) - { + // drop me from the ceiling if I'm on it + if (Jedi_WaitingAmbush(self)) { self->client->noclip = false; } - if ( self->client->ps.legsAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.legsAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - - //check special defenses - if ( other - && other->client - && !OnSameTeam( self, other )) - {//hit by a client - //FIXME: delay this until *after* the pain anim? - if ( mod == MOD_FORCE_GRIP - || mod == MOD_FORCE_LIGHTNING - || mod == MOD_FORCE_DRAIN ) - {//see if we should turn on absorb - if ( (self->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<s.number >= MAX_CLIENTS //enemy is an NPC - || Q_irand( 0, g_spskill->integer+1 ) )//enemy is player + if (self->client->ps.torsoAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + + // check special defenses + if (other && other->client && !OnSameTeam(self, other)) { // hit by a client + // FIXME: delay this until *after* the pain anim? + if (mod == MOD_FORCE_GRIP || mod == MOD_FORCE_LIGHTNING || mod == MOD_FORCE_DRAIN) { // see if we should turn on absorb + if ((self->client->ps.forcePowersKnown & (1 << FP_ABSORB)) != 0 && + (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) == 0) { // know absorb and not already using it + if (other->s.number >= MAX_CLIENTS // enemy is an NPC + || Q_irand(0, g_spskill->integer + 1)) // enemy is player { - if ( Q_irand( 0, self->NPC->rank ) > RANK_ENSIGN ) - { - if ( !Q_irand( 0, 5 ) ) - { - ForceAbsorb( self ); + if (Q_irand(0, self->NPC->rank) > RANK_ENSIGN) { + if (!Q_irand(0, 5)) { + ForceAbsorb(self); } } } } - } - else if ( damage > Q_irand( 5, 20 ) ) - {//respectable amount of normal damage - if ( (self->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<s.number >= MAX_CLIENTS //enemy is an NPC - || Q_irand( 0, g_spskill->integer+1 ) )//enemy is player + } else if (damage > Q_irand(5, 20)) { // respectable amount of normal damage + if ((self->client->ps.forcePowersKnown & (1 << FP_PROTECT)) != 0 && + (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) == 0) { // know protect and not already using it + if (other->s.number >= MAX_CLIENTS // enemy is an NPC + || Q_irand(0, g_spskill->integer + 1)) // enemy is player { - if ( Q_irand( 0, self->NPC->rank ) > RANK_ENSIGN ) - { - if ( !Q_irand( 0, 1 ) ) - { - if ( other->s.number < MAX_CLIENTS - && ((self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) - || self->client->NPC_class==CLASS_SHADOWTROOPER) - && Q_irand(0, 6-g_spskill->integer) ) - { - } - else - { - ForceProtect( self ); + if (Q_irand(0, self->NPC->rank) > RANK_ENSIGN) { + if (!Q_irand(0, 1)) { + if (other->s.number < MAX_CLIENTS && + ((self->NPC->aiFlags & NPCAI_BOSS_CHARACTER) || self->client->NPC_class == CLASS_SHADOWTROOPER) && + Q_irand(0, 6 - g_spskill->integer)) { + } else { + ForceProtect(self); } } } @@ -6157,112 +4733,87 @@ void NPC_Jedi_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, con } } -qboolean Jedi_CheckDanger( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue ); - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner - || !level.alertEvents[alertEvent].owner->client - || (level.alertEvents[alertEvent].owner!=NPC&&level.alertEvents[alertEvent].owner->client->playerTeam!=NPC->client->playerTeam) ) - {//no owner +qboolean Jedi_CheckDanger(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue); + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != NPC && level.alertEvents[alertEvent].owner->client->playerTeam != NPC->client->playerTeam)) { // no owner return qfalse; } - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } return qfalse; } -extern int g_crosshairEntNum; -qboolean Jedi_CheckAmbushPlayer( void ) -{ - if ( !player || !player->client ) - { +extern int g_crosshairEntNum; +qboolean Jedi_CheckAmbushPlayer(void) { + if (!player || !player->client) { return qfalse; } - if ( !NPC_ValidEnemy( player ) ) - { + if (!NPC_ValidEnemy(player)) { return qfalse; } - if ( NPC->client->ps.powerups[PW_CLOAKED] || g_crosshairEntNum != NPC->s.number ) - {//if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... - if ( !gi.inPVS( player->currentOrigin, NPC->currentOrigin ) ) - {//must be in same room + if (NPC->client->ps.powerups[PW_CLOAKED] || + g_crosshairEntNum != NPC->s.number) { // if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... + if (!gi.inPVS(player->currentOrigin, NPC->currentOrigin)) { // must be in same room return qfalse; - } - else - { - if ( !NPC->client->ps.powerups[PW_CLOAKED] ) - { - NPC_SetLookTarget( NPC, 0, 0 ); + } else { + if (!NPC->client->ps.powerups[PW_CLOAKED]) { + NPC_SetLookTarget(NPC, 0, 0); } } - float target_dist, zDiff = NPC->currentOrigin[2]-player->currentOrigin[2]; - if ( zDiff <= 0 || zDiff > 512 ) - {//never ambush if they're above me or way way below me + float target_dist, zDiff = NPC->currentOrigin[2] - player->currentOrigin[2]; + if (zDiff <= 0 || zDiff > 512) { // never ambush if they're above me or way way below me return qfalse; } - //If the target is this close, then wake up regardless - if ( (target_dist = DistanceHorizontalSquared( player->currentOrigin, NPC->currentOrigin )) > 4096 ) - {//closer than 64 - always ambush - if ( target_dist > 147456 ) - {//> 384, not close enough to ambush + // If the target is this close, then wake up regardless + if ((target_dist = DistanceHorizontalSquared(player->currentOrigin, NPC->currentOrigin)) > 4096) { // closer than 64 - always ambush + if (target_dist > 147456) { //> 384, not close enough to ambush return qfalse; } - //Check FOV first - if ( NPC->client->ps.powerups[PW_CLOAKED] ) - { - if ( InFOV( player, NPC, 30, 90 ) == qfalse ) - { + // Check FOV first + if (NPC->client->ps.powerups[PW_CLOAKED]) { + if (InFOV(player, NPC, 30, 90) == qfalse) { return qfalse; } - } - else - { - if ( InFOV( player, NPC, 45, 90 ) == qfalse ) - { + } else { + if (InFOV(player, NPC, 45, 90) == qfalse) { return qfalse; } } } - if ( !NPC_ClearLOS( player ) ) - { + if (!NPC_ClearLOS(player)) { return qfalse; } } - G_SetEnemy( NPC, player ); + G_SetEnemy(NPC, player); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } -void Jedi_Ambush( gentity_t *self ) -{ +void Jedi_Ambush(gentity_t *self) { self->client->noclip = false; - self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + self->client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; - if ( self->client->NPC_class != CLASS_BOBAFETT - && self->client->NPC_class != CLASS_ROCKETTROOPER ) - { + if (self->client->NPC_class != CLASS_BOBAFETT && self->client->NPC_class != CLASS_ROCKETTROOPER) { self->client->ps.SaberActivate(); } - Jedi_Decloak( self ); - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 1000 ); + Jedi_Decloak(self); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 1000); } -qboolean Jedi_WaitingAmbush( gentity_t *self ) -{ - if ( (self->spawnflags&JSF_AMBUSH) && self->client->noclip ) - { +qboolean Jedi_WaitingAmbush(gentity_t *self) { + if ((self->spawnflags & JSF_AMBUSH) && self->client->noclip) { return qtrue; } return qfalse; @@ -6273,64 +4824,51 @@ Jedi_Patrol ------------------------- */ -static void Jedi_Patrol( void ) -{ +static void Jedi_Patrol(void) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( Jedi_WaitingAmbush( NPC ) ) - {//hiding on the ceiling - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - {//look for enemies - if ( Jedi_CheckAmbushPlayer() || Jedi_CheckDanger() ) - {//found him! - Jedi_Ambush( NPC ); - NPC_UpdateAngles( qtrue, qtrue ); + if (Jedi_WaitingAmbush(NPC)) { // hiding on the ceiling + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { // look for enemies + if (Jedi_CheckAmbushPlayer() || Jedi_CheckDanger()) { // found him! + Jedi_Ambush(NPC); + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES )//NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//look for enemies + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) // NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + { // look for enemies gentity_t *best_enemy = NULL; - float best_enemy_dist = Q3_INFINITE; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { + float best_enemy_dist = Q3_INFINITE; + for (int i = 0; i < ENTITYNUM_WORLD; i++) { gentity_t *enemy = &g_entities[i]; - float enemy_dist; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy )) - { - if ( gi.inPVS( NPC->currentOrigin, enemy->currentOrigin ) ) - {//we could potentially see him - enemy_dist = DistanceSquared( NPC->currentOrigin, enemy->currentOrigin ); - if ( enemy->s.number == 0 || enemy_dist < best_enemy_dist ) - { - //if the enemy is close enough, or threw his saber, take him as the enemy - //FIXME: what if he throws a thermal detonator? - //FIXME: use jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) check for anger sound - if ( enemy_dist < (220*220) || ( NPCInfo->investigateCount>= 3 && NPC->client->ps.SaberActive() ) ) - { - G_SetEnemy( NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + float enemy_dist; + if (enemy && enemy->client && NPC_ValidEnemy(enemy)) { + if (gi.inPVS(NPC->currentOrigin, enemy->currentOrigin)) { // we could potentially see him + enemy_dist = DistanceSquared(NPC->currentOrigin, enemy->currentOrigin); + if (enemy->s.number == 0 || enemy_dist < best_enemy_dist) { + // if the enemy is close enough, or threw his saber, take him as the enemy + // FIXME: what if he throws a thermal detonator? + // FIXME: use jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) check for anger sound + if (enemy_dist < (220 * 220) || (NPCInfo->investigateCount >= 3 && NPC->client->ps.SaberActive())) { + G_SetEnemy(NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCInfo->stats.aggression = 3; break; - } - else if ( enemy->client->ps.saberInFlight && enemy->client->ps.SaberActive() ) - {//threw his saber, see if it's heading toward me and close enough to consider a threat - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (enemy->client->ps.saberInFlight && + enemy->client->ps.SaberActive()) { // threw his saber, see if it's heading toward me and close enough to consider a threat + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[enemy->client->ps.saberEntityNum]; - VectorSubtract( NPC->currentOrigin, saber->currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 200 ) - {//incoming! - G_SetEnemy( NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + VectorSubtract(NPC->currentOrigin, saber->currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 200) { // incoming! + G_SetEnemy(NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCInfo->stats.aggression = 3; break; } @@ -6342,115 +4880,83 @@ static void Jedi_Patrol( void ) } } } - if ( !NPC->enemy ) - {//still not mad - if ( !best_enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); + if (!NPC->enemy) { // still not mad + if (!best_enemy) { + // Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); Jedi_AggressionErosion(-1); - //FIXME: what about alerts? But not if ignore alerts - } - else - {//have one to consider - if ( NPC_ClearLOS( best_enemy ) ) - {//we have a clear (of architecture) LOS to him - if ( (NPCInfo->aiFlags&NPCAI_NO_JEDI_DELAY) ) - {//just get mad right away - if ( DistanceHorizontalSquared( NPC->currentOrigin, best_enemy->currentOrigin ) < (1024*1024) ) - { - G_SetEnemy( NPC, best_enemy ); + // FIXME: what about alerts? But not if ignore alerts + } else { // have one to consider + if (NPC_ClearLOS(best_enemy)) { // we have a clear (of architecture) LOS to him + if ((NPCInfo->aiFlags & NPCAI_NO_JEDI_DELAY)) { // just get mad right away + if (DistanceHorizontalSquared(NPC->currentOrigin, best_enemy->currentOrigin) < (1024 * 1024)) { + G_SetEnemy(NPC, best_enemy); NPCInfo->stats.aggression = 20; } - } - else if ( best_enemy->s.number ) - {//just attack - G_SetEnemy( NPC, best_enemy ); + } else if (best_enemy->s.number) { // just attack + G_SetEnemy(NPC, best_enemy); NPCInfo->stats.aggression = 3; - } - else if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - {//the player, toy with him - //get progressively more interested over time - if ( TIMER_Done( NPC, "watchTime" ) ) - {//we want to pick him up in stages - if ( TIMER_Get( NPC, "watchTime" ) == -1 ) - {//this is the first time, we'll ignore him for a couple seconds - TIMER_Set( NPC, "watchTime", Q_irand( 3000, 5000 ) ); + } else if (NPC->client->NPC_class != CLASS_BOBAFETT) { // the player, toy with him + // get progressively more interested over time + if (TIMER_Done(NPC, "watchTime")) { // we want to pick him up in stages + if (TIMER_Get(NPC, "watchTime") == -1) { // this is the first time, we'll ignore him for a couple seconds + TIMER_Set(NPC, "watchTime", Q_irand(3000, 5000)); goto finish; - } - else - {//okay, we've ignored him, now start to notice him - if ( !NPCInfo->investigateCount ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JDETECTED1, EV_JDETECTED3 ), 3000 ); + } else { // okay, we've ignored him, now start to notice him + if (!NPCInfo->investigateCount) { + G_AddVoiceEvent(NPC, Q_irand(EV_JDETECTED1, EV_JDETECTED3), 3000); } NPCInfo->investigateCount++; - TIMER_Set( NPC, "watchTime", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "watchTime", Q_irand(4000, 10000)); } } - //while we're waiting, do what we need to do - if ( best_enemy_dist < (440*440) || NPCInfo->investigateCount >= 2 ) - {//stage three: keep facing him - NPC_FaceEntity( best_enemy, qtrue ); - if ( best_enemy_dist < (330*330) ) - {//stage four: turn on the saber - if ( !NPC->client->ps.saberInFlight ) - { + // while we're waiting, do what we need to do + if (best_enemy_dist < (440 * 440) || NPCInfo->investigateCount >= 2) { // stage three: keep facing him + NPC_FaceEntity(best_enemy, qtrue); + if (best_enemy_dist < (330 * 330)) { // stage four: turn on the saber + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.SaberActivate(); } } - } - else if ( best_enemy_dist < (550*550) || NPCInfo->investigateCount == 1 ) - {//stage two: stop and face him every now and then - if ( TIMER_Done( NPC, "watchTime" ) ) - { - NPC_FaceEntity( best_enemy, qtrue ); + } else if (best_enemy_dist < (550 * 550) || NPCInfo->investigateCount == 1) { // stage two: stop and face him every now and then + if (TIMER_Done(NPC, "watchTime")) { + NPC_FaceEntity(best_enemy, qtrue); } - } - else - {//stage one: look at him. - NPC_SetLookTarget( NPC, best_enemy->s.number, 0 ); + } else { // stage one: look at him. + NPC_SetLookTarget(NPC, best_enemy->s.number, 0); } } - } - else if ( TIMER_Done( NPC, "watchTime" ) ) - {//haven't seen him in a bit, clear the lookTarget - NPC_ClearLookTarget( NPC ); + } else if (TIMER_Done(NPC, "watchTime")) { // haven't seen him in a bit, clear the lookTarget + NPC_ClearLookTarget(NPC); } } } } finish: - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - //Jedi_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); + // Jedi_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPC->enemy ) - {//just picked one up - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (NPC->enemy) { // just picked one up + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); } } -qboolean Jedi_CanPullBackSaber( gentity_t *self ) -{ - if ( self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done( self, "parryTime" ) ) - { +qboolean Jedi_CanPullBackSaber(gentity_t *self) { + if (self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done(self, "parryTime")) { return qfalse; } - if ( self->client->NPC_class == CLASS_SHADOWTROOPER - || self->client->NPC_class == CLASS_ALORA - || ( self->NPC && (self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) ) - { + if (self->client->NPC_class == CLASS_SHADOWTROOPER || self->client->NPC_class == CLASS_ALORA || + (self->NPC && (self->NPC->aiFlags & NPCAI_BOSS_CHARACTER))) { return qtrue; } - if ( self->painDebounceTime > level.time )//|| self->client->ps.weaponTime > 0 ) + if (self->painDebounceTime > level.time) //|| self->client->ps.weaponTime > 0 ) { return qfalse; } @@ -6462,41 +4968,35 @@ qboolean Jedi_CanPullBackSaber( gentity_t *self ) NPC_BSJedi_FollowLeader ------------------------- */ -extern qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ); +extern qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask); -void NPC_BSJedi_FollowLeader( void ) -{ +void NPC_BSJedi_FollowLeader(void) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( !NPC->enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); + if (!NPC->enemy) { + // Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); Jedi_AggressionErosion(-1); } - //did we drop our saber? If so, go after it! - if ( NPC->client->ps.saberInFlight ) - {//saber is not in hand - if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground, try to pick it up... - if ( Jedi_CanPullBackSaber( NPC ) ) - { - //FIXME: if it's on the ground and we just pulled it back to us, should we + // did we drop our saber? If so, go after it! + if (NPC->client->ps.saberInFlight) { // saber is not in hand + if (NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0) // player is 0 + { // + if (g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground, try to pick it up... + if (Jedi_CanPullBackSaber(NPC)) { + // FIXME: if it's on the ground and we just pulled it back to us, should we // stand still for a bit to make sure it gets to us...? // otherwise we could end up running away from it while it's on its // way back to us and we could lose it again. NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCInfo->goalEntity = &g_entities[NPC->client->ps.saberEntityNum]; ucmd.buttons |= BUTTON_ATTACK; - if ( NPC->enemy && NPC->enemy->health > 0 ) - {//get our saber back NOW! - if ( !NPC_MoveToGoal( qtrue ) )//Jedi_Move( NPCInfo->goalEntity, qfalse ); - {//can't nav to it, try jumping to it - NPC_FaceEntity( NPCInfo->goalEntity, qtrue ); - NPC_TryJump( NPCInfo->goalEntity ); + if (NPC->enemy && NPC->enemy->health > 0) { // get our saber back NOW! + if (!NPC_MoveToGoal(qtrue)) // Jedi_Move( NPCInfo->goalEntity, qfalse ); + { // can't nav to it, try jumping to it + NPC_FaceEntity(NPCInfo->goalEntity, qtrue); + NPC_TryJump(NPCInfo->goalEntity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } @@ -6504,44 +5004,27 @@ void NPC_BSJedi_FollowLeader( void ) } } - //try normal movement + // try normal movement NPC_BSFollowLeader(); - - if (!NPC->enemy && - NPC->health < NPC->max_health && - (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<enemy && NPC->health < NPC->max_health && (NPC->client->ps.forcePowersKnown & (1 << FP_HEAL)) != 0 && + (NPC->client->ps.forcePowersActive & (1 << FP_HEAL)) == 0 && TIMER_Done(NPC, "FollowHealDebouncer")) { + if (Q_irand(0, 3) == 0) { TIMER_Set(NPC, "FollowHealDebouncer", Q_irand(12000, 18000)); - ForceHeal( NPC ); - } - else - { + ForceHeal(NPC); + } else { TIMER_Set(NPC, "FollowHealDebouncer", Q_irand(1000, 2000)); } } - } -qboolean Jedi_CheckKataAttack( void ) -{ - if ( NPCInfo->rank >= RANK_LT_COMM ) - {//only top-level guys and bosses do this - if ( (ucmd.buttons&BUTTON_ATTACK) ) - {//attacking - if ( (g_saberNewControlScheme->integer - && !(ucmd.buttons&BUTTON_FORCE_FOCUS) ) - ||(!g_saberNewControlScheme->integer - && !(ucmd.buttons&BUTTON_ALT_ATTACK) ) ) - {//not already going to do a kata move somehow - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - if ( ucmd.upmove <= 0 && NPC->client->ps.forceJumpCharge <= 0 ) - {//not going to try to jump +qboolean Jedi_CheckKataAttack(void) { + if (NPCInfo->rank >= RANK_LT_COMM) { // only top-level guys and bosses do this + if ((ucmd.buttons & BUTTON_ATTACK)) { // attacking + if ((g_saberNewControlScheme->integer && !(ucmd.buttons & BUTTON_FORCE_FOCUS)) || + (!g_saberNewControlScheme->integer && !(ucmd.buttons & BUTTON_ALT_ATTACK))) { // not already going to do a kata move somehow + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on the ground + if (ucmd.upmove <= 0 && NPC->client->ps.forceJumpCharge <= 0) { // not going to try to jump /* if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) {//uh-oh, no jumping moves! @@ -6552,17 +5035,14 @@ qboolean Jedi_CheckKataAttack( void ) } */ - if ( Q_irand( 0, g_spskill->integer+1 ) //50% chance on easy, 66% on medium, 75% on hard - && !Q_irand( 0, 9 ) )//10% chance overall - {//base on skill level + if (Q_irand(0, g_spskill->integer + 1) // 50% chance on easy, 66% on medium, 75% on hard + && !Q_irand(0, 9)) // 10% chance overall + { // base on skill level ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); - if ( g_saberNewControlScheme->integer ) - { + VectorClear(NPC->client->ps.moveDir); + if (g_saberNewControlScheme->integer) { ucmd.buttons |= BUTTON_FORCE_FOCUS; - } - else - { + } else { ucmd.buttons |= BUTTON_ALT_ATTACK; } return qtrue; @@ -6575,132 +5055,94 @@ qboolean Jedi_CheckKataAttack( void ) return qfalse; } - /* ------------------------- Jedi_Attack ------------------------- */ -static void Jedi_Attack( void ) -{ - //Don't do anything if we're in a pain anim - if ( NPC->painDebounceTime > level.time ) - { - if ( Q_irand( 0, 1 ) ) - { - Jedi_FaceEnemy( qtrue ); +static void Jedi_Attack(void) { + // Don't do anything if we're in a pain anim + if (NPC->painDebounceTime > level.time) { + if (Q_irand(0, 1)) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); - if ( NPC->client->ps.torsoAnim == BOTH_KYLE_GRAB ) - {//see if we grabbed enemy - if ( NPC->client->ps.torsoAnimTimer <= 200 ) - { - if ( Kyle_CanDoGrab() - && NPC_EnemyRangeFromBolt( NPC->handRBolt ) < 88.0f ) - {//grab him! + NPC_UpdateAngles(qtrue, qtrue); + if (NPC->client->ps.torsoAnim == BOTH_KYLE_GRAB) { // see if we grabbed enemy + if (NPC->client->ps.torsoAnimTimer <= 200) { + if (Kyle_CanDoGrab() && NPC_EnemyRangeFromBolt(NPC->handRBolt) < 88.0f) { // grab him! Kyle_GrabEnemy(); return; - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; return; } } - //else just sit here? + // else just sit here? } return; } - if ( NPC->client->ps.saberLockTime > level.time ) - { - //FIXME: maybe kick out of saberlock? - //maybe if I'm losing I should try to force-push out of it? Very rarely, though... - if ( NPC->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 - && NPC->client->ps.saberLockTime < level.time + 5000 - && !Q_irand( 0, 10 )) - { - ForceThrow( NPC, qfalse ); + if (NPC->client->ps.saberLockTime > level.time) { + // FIXME: maybe kick out of saberlock? + // maybe if I'm losing I should try to force-push out of it? Very rarely, though... + if (NPC->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && NPC->client->ps.saberLockTime < level.time + 5000 && !Q_irand(0, 10)) { + ForceThrow(NPC, qfalse); } - //based on my skill, hit attack button every other to every several frames in order to push enemy back - else - { + // based on my skill, hit attack button every other to every several frames in order to push enemy back + else { float chance; - if ( NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",NPC->NPC_type) ) - { - if ( g_spskill->integer ) - { - chance = 4.0f;//he pushes *hard* - } - else - { - chance = 3.0f;//he pushes *hard* - } - } - else if ( NPC->client->NPC_class == CLASS_TAVION - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA - || (NPC->client->NPC_class == CLASS_KYLE&&(NPC->spawnflags&1)) ) - { - chance = 2.0f+g_spskill->value;//from 2 to 4 - } - else - {//the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard - float maxChance = (float)(RANK_LT)/2.0f+3.0f;//5? - if ( !g_spskill->value ) - { - chance = (float)(NPCInfo->rank)/2.0f; - } - else - { - chance = (float)(NPCInfo->rank)/2.0f+1.0f; - } - if ( chance > maxChance ) - { + if (NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", NPC->NPC_type)) { + if (g_spskill->integer) { + chance = 4.0f; // he pushes *hard* + } else { + chance = 3.0f; // he pushes *hard* + } + } else if (NPC->client->NPC_class == CLASS_TAVION || NPC->client->NPC_class == CLASS_SHADOWTROOPER || NPC->client->NPC_class == CLASS_ALORA || + (NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1))) { + chance = 2.0f + g_spskill->value; // from 2 to 4 + } else { // the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard + float maxChance = (float)(RANK_LT) / 2.0f + 3.0f; // 5? + if (!g_spskill->value) { + chance = (float)(NPCInfo->rank) / 2.0f; + } else { + chance = (float)(NPCInfo->rank) / 2.0f + 1.0f; + } + if (chance > maxChance) { chance = maxChance; } } - if ( (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) ) - { - chance += Q_irand(0,2); - } - else if ( (NPCInfo->aiFlags&NPCAI_SUBBOSS_CHARACTER) ) - { - chance += Q_irand(-1,1); + if ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER)) { + chance += Q_irand(0, 2); + } else if ((NPCInfo->aiFlags & NPCAI_SUBBOSS_CHARACTER)) { + chance += Q_irand(-1, 1); } - if ( Q_flrand( -4.0f, chance ) >= 0.0f && !(NPC->client->ps.pm_flags&PMF_ATTACK_HELD) ) - { + if (Q_flrand(-4.0f, chance) >= 0.0f && !(NPC->client->ps.pm_flags & PMF_ATTACK_HELD)) { ucmd.buttons |= BUTTON_ATTACK; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - //did we drop our saber? If so, go after it! - if ( NPC->client->ps.saberInFlight ) - {//saber is not in hand - if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground, try to pick it up - if ( Jedi_CanPullBackSaber( NPC ) ) - { + // did we drop our saber? If so, go after it! + if (NPC->client->ps.saberInFlight) { // saber is not in hand + if (NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0) // player is 0 + { // + if (g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground, try to pick it up + if (Jedi_CanPullBackSaber(NPC)) { NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCInfo->goalEntity = &g_entities[NPC->client->ps.saberEntityNum]; ucmd.buttons |= BUTTON_ATTACK; - if ( NPC->enemy && NPC->enemy->health > 0 ) - {//get our saber back NOW! - Jedi_Move( NPCInfo->goalEntity, qfalse ); - NPC_UpdateAngles( qtrue, qtrue ); - if ( NPC->enemy->s.weapon == WP_SABER ) - {//be sure to continue evasion - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); + if (NPC->enemy && NPC->enemy->health > 0) { // get our saber back NOW! + Jedi_Move(NPCInfo->goalEntity, qfalse); + NPC_UpdateAngles(qtrue, qtrue); + if (NPC->enemy->s.weapon == WP_SABER) { // be sure to continue evasion + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); } return; } @@ -6708,257 +5150,195 @@ static void Jedi_Attack( void ) } } } - //see if our enemy was killed by us, gloat and turn off saber after cool down. - //FIXME: don't do this if we have other enemies to fight...? - if ( NPC->enemy ) - { - if ( NPC->enemy->health <= 0 - && NPC->enemy->enemy == NPC - && (NPC->client->playerTeam != TEAM_PLAYER||(NPC->client->NPC_class==CLASS_KYLE&&(NPC->spawnflags&1)&&NPC->enemy==player)) )//good guys don't gloat (unless it's Kyle having just killed his student - {//my enemy is dead and I killed him - NPCInfo->enemyCheckDebounceTime = 0;//keep looking for others - - if ( NPC->client->NPC_class == CLASS_BOBAFETT - || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) - || NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - { - if ( NPCInfo->walkDebounceTime < level.time && NPCInfo->walkDebounceTime >= 0 ) - { - TIMER_Set( NPC, "gloatTime", 10000 ); + // see if our enemy was killed by us, gloat and turn off saber after cool down. + // FIXME: don't do this if we have other enemies to fight...? + if (NPC->enemy) { + if (NPC->enemy->health <= 0 && NPC->enemy->enemy == NPC && + (NPC->client->playerTeam != TEAM_PLAYER || (NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1) && + NPC->enemy == player))) // good guys don't gloat (unless it's Kyle having just killed his student + { // my enemy is dead and I killed him + NPCInfo->enemyCheckDebounceTime = 0; // keep looking for others + + if (NPC->client->NPC_class == CLASS_BOBAFETT || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) || + NPC->client->NPC_class == CLASS_ROCKETTROOPER) { + if (NPCInfo->walkDebounceTime < level.time && NPCInfo->walkDebounceTime >= 0) { + TIMER_Set(NPC, "gloatTime", 10000); NPCInfo->walkDebounceTime = -1; } - if ( !TIMER_Done( NPC, "gloatTime" ) ) - { - if ( DistanceHorizontalSquared( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin ) > 4096 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + if (!TIMER_Done(NPC, "gloatTime")) { + if (DistanceHorizontalSquared(NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin) > 4096 && + (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCInfo->goalEntity = NPC->enemy; - Jedi_Move( NPC->enemy, qfalse ); + Jedi_Move(NPC->enemy, qfalse); ucmd.buttons |= BUTTON_WALKING; + } else { + TIMER_Set(NPC, "gloatTime", 0); } - else - { - TIMER_Set( NPC, "gloatTime", 0 ); - } - } - else if ( NPCInfo->walkDebounceTime == -1 ) - { + } else if (NPCInfo->walkDebounceTime == -1) { NPCInfo->walkDebounceTime = -2; - G_AddVoiceEvent( NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = level.time + 3000; NPCInfo->desiredPitch = 0; NPCInfo->goalEntity = NULL; } - Jedi_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + Jedi_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - { - if ( !TIMER_Done( NPC, "parryTime" ) ) - { - TIMER_Set( NPC, "parryTime", -1 ); + } else { + if (!TIMER_Done(NPC, "parryTime")) { + TIMER_Set(NPC, "parryTime", -1); NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( NPC->client->ps.SaberActive() || NPC->client->ps.saberInFlight ) - {//saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy - //FIXME: need to stop this from happening over and over again when they're blocking their victim's saber - //FIXME: turn off saber sooner so we get cool walk anim? - //Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); + if (NPC->client->ps.SaberActive() || + NPC->client->ps.saberInFlight) { // saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy + // FIXME: need to stop this from happening over and over again when they're blocking their victim's saber + // FIXME: turn off saber sooner so we get cool walk anim? + // Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); Jedi_AggressionErosion(-3); - if ( !NPC->client->ps.SaberActive() && !NPC->client->ps.saberInFlight ) - {//turned off saber (in hand), gloat - G_AddVoiceEvent( NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); + if (!NPC->client->ps.SaberActive() && !NPC->client->ps.saberInFlight) { // turned off saber (in hand), gloat + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = level.time + 3000; NPCInfo->desiredPitch = 0; NPCInfo->goalEntity = NULL; } - TIMER_Set( NPC, "gloatTime", 10000 ); + TIMER_Set(NPC, "gloatTime", 10000); } - if ( NPC->client->ps.SaberActive() || NPC->client->ps.saberInFlight || !TIMER_Done( NPC, "gloatTime" ) ) - {//keep walking - if ( DistanceHorizontalSquared( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin ) > 4096 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + if (NPC->client->ps.SaberActive() || NPC->client->ps.saberInFlight || !TIMER_Done(NPC, "gloatTime")) { // keep walking + if (DistanceHorizontalSquared(NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin) > 4096 && + (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCInfo->goalEntity = NPC->enemy; - Jedi_Move( NPC->enemy, qfalse ); + Jedi_Move(NPC->enemy, qfalse); ucmd.buttons |= BUTTON_WALKING; - } - else - {//got there - if ( NPC->health < NPC->max_health ) - { - if ( NPC->client->ps.saber[0].type == SABER_SITH_SWORD - && NPC->weaponModel[0] != -1 ) - { + } else { // got there + if (NPC->health < NPC->max_health) { + if (NPC->client->ps.saber[0].type == SABER_SITH_SWORD && NPC->weaponModel[0] != -1) { Tavion_SithSwordRecharge(); - } - else if ( (NPC->client->ps.forcePowersKnown&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersKnown & (1 << FP_HEAL)) != 0 && (NPC->client->ps.forcePowersActive & (1 << FP_HEAL)) == 0) { + ForceHeal(NPC); } } } - Jedi_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + Jedi_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; } } } } - //If we don't have an enemy, just idle - if ( NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPC->enemy->classname ) ) - { - if ( NPC->enemy->count <= 0 ) - {//it's out of ammo - if ( NPC->enemy->activator && NPC_ValidEnemy( NPC->enemy->activator ) ) - { + // If we don't have an enemy, just idle + if (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname)) { + if (NPC->enemy->count <= 0) { // it's out of ammo + if (NPC->enemy->activator && NPC_ValidEnemy(NPC->enemy->activator)) { gentity_t *turretOwner = NPC->enemy->activator; - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, turretOwner ); - } - else - { - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); + G_SetEnemy(NPC, turretOwner); + } else { + G_ClearEnemy(NPC); } } - } - else if ( NPC->enemy && - NPC->enemy->NPC - && NPC->enemy->NPC->charmedTime > level.time ) - {//my enemy was charmed - if ( OnSameTeam( NPC, NPC->enemy ) ) - {//has been charmed to be on my team - G_ClearEnemy( NPC ); + } else if (NPC->enemy && NPC->enemy->NPC && NPC->enemy->NPC->charmedTime > level.time) { // my enemy was charmed + if (OnSameTeam(NPC, NPC->enemy)) { // has been charmed to be on my team + G_ClearEnemy(NPC); } } - if ( NPC->client->playerTeam == TEAM_ENEMY - && NPC->client->enemyTeam == TEAM_PLAYER - && NPC->enemy - && NPC->enemy->client - && NPC->enemy->client->playerTeam != NPC->client->enemyTeam - && OnSameTeam( NPC, NPC->enemy ) - && !(NPC->svFlags&SVF_LOCKEDENEMY) ) - {//an evil jedi somehow got another evil NPC as an enemy, they were probably charmed and it's run out now - if ( !NPC_ValidEnemy( NPC->enemy ) ) - { - G_ClearEnemy( NPC ); + if (NPC->client->playerTeam == TEAM_ENEMY && NPC->client->enemyTeam == TEAM_PLAYER && NPC->enemy && NPC->enemy->client && + NPC->enemy->client->playerTeam != NPC->client->enemyTeam && OnSameTeam(NPC, NPC->enemy) && + !(NPC->svFlags & SVF_LOCKEDENEMY)) { // an evil jedi somehow got another evil NPC as an enemy, they were probably charmed and it's run out now + if (!NPC_ValidEnemy(NPC->enemy)) { + G_ClearEnemy(NPC); } } - NPC_CheckEnemy( qtrue, qtrue ); + NPC_CheckEnemy(qtrue, qtrue); - if ( !NPC->enemy ) - { + if (!NPC->enemy) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - Jedi_Patrol();//was calling Idle... why? + Jedi_Patrol(); // was calling Idle... why? return; } - //always face enemy if have one + // always face enemy if have one NPCInfo->combatMove = qtrue; - //Track the player and kill them if possible + // Track the player and kill them if possible Jedi_Combat(); - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) - || ((NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_HEAL]scriptFlags & SCF_CHASE_ENEMIES) || ((NPC->client->ps.forcePowersActive & (1 << FP_HEAL)) && + NPC->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2)) { // this is really stupid, but okay... ucmd.forwardmove = 0; ucmd.rightmove = 0; - if ( ucmd.upmove > 0 ) - { + if (ucmd.upmove > 0) { ucmd.upmove = 0; } NPC->client->ps.forceJumpCharge = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//don't push while in air, throws off jumps! - //FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // don't push while in air, throws off jumps! + // FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? ucmd.forwardmove = 0; ucmd.rightmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } - if ( NPC->client->NPC_class != CLASS_BOBAFETT - && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) - && NPC->client->NPC_class != CLASS_ROCKETTROOPER ) - { - if ( PM_SaberInBrokenParry( NPC->client->ps.saberMove ) || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - {//just make sure they don't pull their saber to them if they're being blocked + if (NPC->client->NPC_class != CLASS_BOBAFETT && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) && + NPC->client->NPC_class != CLASS_ROCKETTROOPER) { + if (PM_SaberInBrokenParry(NPC->client->ps.saberMove) || + NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { // just make sure they don't pull their saber to them if they're being blocked ucmd.buttons &= ~BUTTON_ATTACK; } } - if( (NPCInfo->scriptFlags&SCF_DONT_FIRE) //not allowed to attack - || ((NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_HEAL]client->ps.saberEventFlags&SEF_INWATER)&&!NPC->client->ps.saberInFlight) )//saber in water + if ((NPCInfo->scriptFlags & SCF_DONT_FIRE) // not allowed to attack + || ((NPC->client->ps.forcePowersActive & (1 << FP_HEAL)) && NPC->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3) || + ((NPC->client->ps.saberEventFlags & SEF_INWATER) && !NPC->client->ps.saberInFlight)) // saber in water { - ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS); + ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS); } - if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { + if ((NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { ucmd.upmove = 0; NPC->client->ps.forceJumpCharge = 0; } - if ( NPC->client->NPC_class != CLASS_BOBAFETT - && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) - && NPC->client->NPC_class != CLASS_ROCKETTROOPER ) - { + if (NPC->client->NPC_class != CLASS_BOBAFETT && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) && + NPC->client->NPC_class != CLASS_ROCKETTROOPER) { Jedi_CheckDecreaseSaberAnimLevel(); } - if ( ucmd.buttons & BUTTON_ATTACK && NPC->client->playerTeam == TEAM_ENEMY ) - { - if ( Q_irand( 0, NPC->client->ps.saberAnimLevel ) > 0 - && Q_irand( 0, NPC->max_health+10 ) > NPC->health - && !Q_irand( 0, 3 )) - {//the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing - G_AddVoiceEvent( NPC, Q_irand( EV_COMBAT1, EV_COMBAT3 ), 1000 ); + if (ucmd.buttons & BUTTON_ATTACK && NPC->client->playerTeam == TEAM_ENEMY) { + if (Q_irand(0, NPC->client->ps.saberAnimLevel) > 0 && Q_irand(0, NPC->max_health + 10) > NPC->health && + !Q_irand(0, 3)) { // the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing + G_AddVoiceEvent(NPC, Q_irand(EV_COMBAT1, EV_COMBAT3), 1000); } } - //Check for trying a kata move - //FIXME: what about force-pull attacks? - if ( Jedi_CheckKataAttack() ) - {//doing a kata attack - } - else - {//check other special combat behavior - if ( NPC->client->NPC_class != CLASS_BOBAFETT - && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) - && NPC->client->NPC_class != CLASS_ROCKETTROOPER ) - { - if ( NPC->client->NPC_class == CLASS_TAVION - || NPC->client->NPC_class == CLASS_SHADOWTROOPER - || NPC->client->NPC_class == CLASS_ALORA - || (g_spskill->integer && ( NPC->client->NPC_class == CLASS_DESANN || NPCInfo->rank >= Q_irand( RANK_CREWMAN, RANK_CAPTAIN )))) - {//Tavion will kick in force speed if the player does... - if ( NPC->enemy - && !NPC->enemy->s.number - && NPC->enemy->client - && (NPC->enemy->client->ps.forcePowersActive & (1<client->ps.forcePowersActive & (1<client->NPC_class != CLASS_BOBAFETT && (NPC->client->NPC_class != CLASS_REBORN || NPC->s.weapon == WP_SABER) && + NPC->client->NPC_class != CLASS_ROCKETTROOPER) { + if (NPC->client->NPC_class == CLASS_TAVION || NPC->client->NPC_class == CLASS_SHADOWTROOPER || NPC->client->NPC_class == CLASS_ALORA || + (g_spskill->integer && (NPC->client->NPC_class == CLASS_DESANN || + NPCInfo->rank >= Q_irand(RANK_CREWMAN, RANK_CAPTAIN)))) { // Tavion will kick in force speed if the player does... + if (NPC->enemy && !NPC->enemy->s.number && NPC->enemy->client && (NPC->enemy->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED))) { int chance = 0; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: chance = 9; break; @@ -6969,198 +5349,144 @@ static void Jedi_Attack( void ) chance = 1; break; } - if ( !Q_irand( 0, chance ) ) - { - ForceSpeed( NPC ); + if (!Q_irand(0, chance)) { + ForceSpeed(NPC); } } } } - //Sometimes Alora flips towards you instead of runs - if ( NPC->client->NPC_class == CLASS_ALORA ) - { - if ( (ucmd.buttons&BUTTON_ALT_ATTACK) ) - {//chance of doing a special dual saber throw - if ( NPC->client->ps.saberAnimLevel == SS_DUAL - && !NPC->client->ps.saberInFlight ) - { - if ( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) >= 120 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ALORA_SPIN_THROW, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + // Sometimes Alora flips towards you instead of runs + if (NPC->client->NPC_class == CLASS_ALORA) { + if ((ucmd.buttons & BUTTON_ALT_ATTACK)) { // chance of doing a special dual saber throw + if (NPC->client->ps.saberAnimLevel == SS_DUAL && !NPC->client->ps.saberInFlight) { + if (Distance(NPC->enemy->currentOrigin, NPC->currentOrigin) >= 120) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ALORA_SPIN_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; - //FIXME: don't move - //FIXME: sabers need trails and sounds + // FIXME: don't move + // FIXME: sabers need trails and sounds } } - } - else if ( NPC->enemy - && ucmd.forwardmove > 0 - && fabs((float)ucmd.rightmove) < 32 - && !(ucmd.buttons&BUTTON_WALKING) - && !(ucmd.buttons&BUTTON_ATTACK) - && NPC->client->ps.saberMove == LS_READY - && NPC->client->ps.legsAnim == BOTH_RUN_DUAL ) - {//running at us, not attacking - if ( Distance( NPC->enemy->currentOrigin, NPC->currentOrigin ) > 80 ) - { - if ( NPC->client->ps.legsAnim == BOTH_FLIP_F - || NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_1 - || NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_2 - || NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_3 ) - { - if ( NPC->client->ps.legsAnimTimer <= 200 && Q_irand( 0, 2 ) ) - {//go ahead and start anotther - NPC_SetAnim( NPC, SETANIM_BOTH, Q_irand(BOTH_ALORA_FLIP_1,BOTH_ALORA_FLIP_3), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + } else if (NPC->enemy && ucmd.forwardmove > 0 && fabs((float)ucmd.rightmove) < 32 && !(ucmd.buttons & BUTTON_WALKING) && + !(ucmd.buttons & BUTTON_ATTACK) && NPC->client->ps.saberMove == LS_READY && + NPC->client->ps.legsAnim == BOTH_RUN_DUAL) { // running at us, not attacking + if (Distance(NPC->enemy->currentOrigin, NPC->currentOrigin) > 80) { + if (NPC->client->ps.legsAnim == BOTH_FLIP_F || NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_1 || + NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_2 || NPC->client->ps.legsAnim == BOTH_ALORA_FLIP_3) { + if (NPC->client->ps.legsAnimTimer <= 200 && Q_irand(0, 2)) { // go ahead and start anotther + NPC_SetAnim(NPC, SETANIM_BOTH, Q_irand(BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } - } - else if ( !Q_irand( 0, 6 ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, Q_irand(BOTH_ALORA_FLIP_1,BOTH_ALORA_FLIP_3), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + } else if (!Q_irand(0, 6)) { + NPC_SetAnim(NPC, SETANIM_BOTH, Q_irand(BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } } } } } - if ( VectorCompare( NPC->client->ps.moveDir, vec3_origin ) - && (ucmd.forwardmove||ucmd.rightmove) ) - {//using ucmds to move this turn, not NAV - if ( (ucmd.buttons&BUTTON_WALKING) ) - {//FIXME: NAV system screws with speed directly, so now I have to re-set it myself! + if (VectorCompare(NPC->client->ps.moveDir, vec3_origin) && (ucmd.forwardmove || ucmd.rightmove)) { // using ucmds to move this turn, not NAV + if ((ucmd.buttons & BUTTON_WALKING)) { // FIXME: NAV system screws with speed directly, so now I have to re-set it myself! NPC->client->ps.speed = NPCInfo->stats.walkSpeed; - } - else - { + } else { NPC->client->ps.speed = NPCInfo->stats.runSpeed; } } } -qboolean Rosh_BeingHealed( gentity_t *self ) -{ - if ( self - && self->NPC - && self->client - && (self->NPC->aiFlags&NPCAI_ROSH) - && (self->flags&FL_UNDYING) - && ( self->health == 1 //need healing - || self->client->ps.powerups[PW_INVINCIBLE] > level.time ) )//being healed +qboolean Rosh_BeingHealed(gentity_t *self) { + if (self && self->NPC && self->client && (self->NPC->aiFlags & NPCAI_ROSH) && (self->flags & FL_UNDYING) && + (self->health == 1 // need healing + || self->client->ps.powerups[PW_INVINCIBLE] > level.time)) // being healed { return qtrue; } return qfalse; } -qboolean Rosh_TwinPresent( gentity_t *self ) -{ - gentity_t *foundTwin = G_Find( NULL, FOFS(NPC_type), "DKothos" ); - if ( !foundTwin - || foundTwin->health < 0 ) - { - foundTwin = G_Find( NULL, FOFS(NPC_type), "VKothos" ); +qboolean Rosh_TwinPresent(gentity_t *self) { + gentity_t *foundTwin = G_Find(NULL, FOFS(NPC_type), "DKothos"); + if (!foundTwin || foundTwin->health < 0) { + foundTwin = G_Find(NULL, FOFS(NPC_type), "VKothos"); } - if ( !foundTwin - || foundTwin->health < 0 ) - {//oh well, both twins are dead... + if (!foundTwin || foundTwin->health < 0) { // oh well, both twins are dead... return qfalse; } return qtrue; } -qboolean Rosh_TwinNearBy( gentity_t *self ) -{ - gentity_t *foundTwin = G_Find( NULL, FOFS(NPC_type), "DKothos" ); - if ( !foundTwin - || foundTwin->health < 0 ) - { - foundTwin = G_Find( NULL, FOFS(NPC_type), "VKothos" ); +qboolean Rosh_TwinNearBy(gentity_t *self) { + gentity_t *foundTwin = G_Find(NULL, FOFS(NPC_type), "DKothos"); + if (!foundTwin || foundTwin->health < 0) { + foundTwin = G_Find(NULL, FOFS(NPC_type), "VKothos"); } - if ( !foundTwin - || foundTwin->health < 0 ) - {//oh well, both twins are dead... + if (!foundTwin || foundTwin->health < 0) { // oh well, both twins are dead... return qfalse; } - if ( self->client - && foundTwin->client ) - { - if ( Distance( self->currentOrigin, foundTwin->currentOrigin ) <= 512.0f - && G_ClearLineOfSight( self->client->renderInfo.eyePoint, foundTwin->client->renderInfo.eyePoint, foundTwin->s.number, MASK_OPAQUE ) ) - { - //make them look charge me for a bit while I do this - TIMER_Set( self, "chargeMeUp", Q_irand( 2000, 4000 ) ); + if (self->client && foundTwin->client) { + if (Distance(self->currentOrigin, foundTwin->currentOrigin) <= 512.0f && + G_ClearLineOfSight(self->client->renderInfo.eyePoint, foundTwin->client->renderInfo.eyePoint, foundTwin->s.number, MASK_OPAQUE)) { + // make them look charge me for a bit while I do this + TIMER_Set(self, "chargeMeUp", Q_irand(2000, 4000)); return qtrue; } } return qfalse; } -qboolean Kothos_HealRosh( void ) -{ - if ( NPC->client - && NPC->client->leader - && NPC->client->leader->client ) - { - if ( DistanceSquared( NPC->client->leader->currentOrigin, NPC->currentOrigin ) <= (256*256) - && G_ClearLineOfSight( NPC->client->leader->client->renderInfo.eyePoint, NPC->client->renderInfo.eyePoint, NPC->s.number, MASK_OPAQUE ) ) - { - //NPC_FaceEntity( NPC->client->leader, qtrue ); - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_FORCE_2HANDEDLIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); +qboolean Kothos_HealRosh(void) { + if (NPC->client && NPC->client->leader && NPC->client->leader->client) { + if (DistanceSquared(NPC->client->leader->currentOrigin, NPC->currentOrigin) <= (256 * 256) && + G_ClearLineOfSight(NPC->client->leader->client->renderInfo.eyePoint, NPC->client->renderInfo.eyePoint, NPC->s.number, MASK_OPAQUE)) { + // NPC_FaceEntity( NPC->client->leader, qtrue ); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_FORCE_2HANDEDLIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = 1000; - //FIXME: unique effect and sound - //NPC->client->ps.eFlags |= EF_POWERING_ROSH; - if ( NPC->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t fxOrg, fxDir, angles={0,NPC->currentAngles[YAW],0}; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - (Q_irand(0,1)?NPC->handLBolt:NPC->handRBolt), - &boltMatrix, angles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - VectorSubtract( NPC->client->leader->currentOrigin, fxOrg, fxDir ); - VectorNormalize( fxDir ); - G_PlayEffect( G_EffectIndex( "force/kothos_beam.efx" ), fxOrg, fxDir ); - } - //BEG HACK LINE - gentity_t *tent = G_TempEntity( NPC->currentOrigin, EV_KOTHOS_BEAM ); + // FIXME: unique effect and sound + // NPC->client->ps.eFlags |= EF_POWERING_ROSH; + if (NPC->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t fxOrg, fxDir, angles = {0, NPC->currentAngles[YAW], 0}; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, (Q_irand(0, 1) ? NPC->handLBolt : NPC->handRBolt), &boltMatrix, angles, + NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + VectorSubtract(NPC->client->leader->currentOrigin, fxOrg, fxDir); + VectorNormalize(fxDir); + G_PlayEffect(G_EffectIndex("force/kothos_beam.efx"), fxOrg, fxDir); + } + // BEG HACK LINE + gentity_t *tent = G_TempEntity(NPC->currentOrigin, EV_KOTHOS_BEAM); tent->svFlags |= SVF_BROADCAST; tent->s.otherEntityNum = NPC->s.number; tent->s.otherEntityNum2 = NPC->client->leader->s.number; - //END HACK LINE - - NPC->client->leader->health += Q_irand( 1+g_spskill->integer*2, 4+g_spskill->integer*3 );//from 1-5 to 4-10 - if ( NPC->client->leader->client ) - { - if ( NPC->client->leader->client->ps.legsAnim == BOTH_FORCEHEAL_START - && NPC->client->leader->health >= NPC->client->leader->max_health ) - {//let him get up now - NPC_SetAnim( NPC->client->leader, SETANIM_BOTH, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //FIXME: temp effect - G_PlayEffect( G_EffectIndex( "force/kothos_recharge.efx" ), NPC->client->leader->playerModel, 0, NPC->client->leader->s.number, NPC->client->leader->currentOrigin, NPC->client->leader->client->ps.torsoAnimTimer, qfalse ); - //make him invincible while we recharge him + // END HACK LINE + + NPC->client->leader->health += Q_irand(1 + g_spskill->integer * 2, 4 + g_spskill->integer * 3); // from 1-5 to 4-10 + if (NPC->client->leader->client) { + if (NPC->client->leader->client->ps.legsAnim == BOTH_FORCEHEAL_START && + NPC->client->leader->health >= NPC->client->leader->max_health) { // let him get up now + NPC_SetAnim(NPC->client->leader, SETANIM_BOTH, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // FIXME: temp effect + G_PlayEffect(G_EffectIndex("force/kothos_recharge.efx"), NPC->client->leader->playerModel, 0, NPC->client->leader->s.number, + NPC->client->leader->currentOrigin, NPC->client->leader->client->ps.torsoAnimTimer, qfalse); + // make him invincible while we recharge him NPC->client->leader->client->ps.powerups[PW_INVINCIBLE] = level.time + NPC->client->leader->client->ps.torsoAnimTimer; NPC->client->leader->NPC->ignorePain = qfalse; NPC->client->leader->health = NPC->client->leader->max_health; - } - else - { - G_PlayEffect( G_EffectIndex( "force/kothos_recharge.efx" ), NPC->client->leader->playerModel, 0, NPC->client->leader->s.number, NPC->client->leader->currentOrigin, 500, qfalse ); + } else { + G_PlayEffect(G_EffectIndex("force/kothos_recharge.efx"), NPC->client->leader->playerModel, 0, NPC->client->leader->s.number, + NPC->client->leader->currentOrigin, 500, qfalse); NPC->client->leader->client->ps.powerups[PW_INVINCIBLE] = level.time + 500; } } - //decrement + // decrement NPC->count--; - if ( !NPC->count ) - { - TIMER_Set( NPC, "healRoshDebounce", Q_irand( 5000, 10000 ) ); + if (!NPC->count) { + TIMER_Set(NPC, "healRoshDebounce", Q_irand(5000, 10000)); NPC->count = 100; } - //now protect me, too - if ( g_spskill->integer ) - {//not on easy - G_PlayEffect( G_EffectIndex( "force/kothos_recharge.efx" ), NPC->playerModel, 0, NPC->s.number, NPC->currentOrigin, 500, qfalse ); + // now protect me, too + if (g_spskill->integer) { // not on easy + G_PlayEffect(G_EffectIndex("force/kothos_recharge.efx"), NPC->playerModel, 0, NPC->s.number, NPC->currentOrigin, 500, qfalse); NPC->client->ps.powerups[PW_INVINCIBLE] = level.time + 500; } return qtrue; @@ -7169,51 +5495,41 @@ qboolean Kothos_HealRosh( void ) return qfalse; } -void Kothos_PowerRosh( void ) -{ - if ( NPC->client - && NPC->client->leader ) - { - if ( Distance( NPC->client->leader->currentOrigin, NPC->currentOrigin ) <= 512.0f - && G_ClearLineOfSight( NPC->client->leader->client->renderInfo.eyePoint, NPC->client->renderInfo.eyePoint, NPC->s.number, MASK_OPAQUE ) ) - { - NPC_FaceEntity( NPC->client->leader, qtrue ); - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); +void Kothos_PowerRosh(void) { + if (NPC->client && NPC->client->leader) { + if (Distance(NPC->client->leader->currentOrigin, NPC->currentOrigin) <= 512.0f && + G_ClearLineOfSight(NPC->client->leader->client->renderInfo.eyePoint, NPC->client->renderInfo.eyePoint, NPC->s.number, MASK_OPAQUE)) { + NPC_FaceEntity(NPC->client->leader, qtrue); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = 500; - //FIXME: unique effect and sound - //NPC->client->ps.eFlags |= EF_POWERING_ROSH; - G_PlayEffect( G_EffectIndex( "force/kothos_beam.efx" ), NPC->playerModel, NPC->handLBolt, NPC->s.number, NPC->currentOrigin, 500, qfalse ); - if ( NPC->client->leader->client ) - {//hmm, give him some force? + // FIXME: unique effect and sound + // NPC->client->ps.eFlags |= EF_POWERING_ROSH; + G_PlayEffect(G_EffectIndex("force/kothos_beam.efx"), NPC->playerModel, NPC->handLBolt, NPC->s.number, NPC->currentOrigin, 500, qfalse); + if (NPC->client->leader->client) { // hmm, give him some force? NPC->client->leader->client->ps.forcePower++; } } } } -qboolean Kothos_Retreat( void ) -{ - STEER::Activate( NPC ); - STEER::Evade( NPC, NPC->enemy ); - STEER::AvoidCollisions( NPC, NPC->client->leader ); - STEER::DeActivate( NPC, &ucmd ); - if ( (NPCInfo->aiFlags&NPCAI_BLOCKED) ) - { - if ( level.time - NPCInfo->blockedDebounceTime > 1000 ) - { +qboolean Kothos_Retreat(void) { + STEER::Activate(NPC); + STEER::Evade(NPC, NPC->enemy); + STEER::AvoidCollisions(NPC, NPC->client->leader); + STEER::DeActivate(NPC, &ucmd); + if ((NPCInfo->aiFlags & NPCAI_BLOCKED)) { + if (level.time - NPCInfo->blockedDebounceTime > 1000) { return qfalse; } } return qtrue; } -#define TWINS_DANGER_DIST_EASY (128.0f*128.0f) -#define TWINS_DANGER_DIST_MEDIUM (192.0f*192.0f) -#define TWINS_DANGER_DIST_HARD (256.0f*256.0f) -float Twins_DangerDist( void ) -{ - switch ( g_spskill->integer ) - { +#define TWINS_DANGER_DIST_EASY (128.0f * 128.0f) +#define TWINS_DANGER_DIST_MEDIUM (192.0f * 192.0f) +#define TWINS_DANGER_DIST_HARD (256.0f * 256.0f) +float Twins_DangerDist(void) { + switch (g_spskill->integer) { case 0: return TWINS_DANGER_DIST_EASY; break; @@ -7227,30 +5543,19 @@ float Twins_DangerDist( void ) } } -qboolean Jedi_InSpecialMove( void ) -{ - if ( NPC->client->ps.torsoAnim == BOTH_KYLE_PA_1 - || NPC->client->ps.torsoAnim == BOTH_KYLE_PA_2 - || NPC->client->ps.torsoAnim == BOTH_KYLE_PA_3 - || NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_1 - || NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_2 - || NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_3 - || NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END - || NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRABBED ) - { - NPC_UpdateAngles( qtrue, qtrue ); +qboolean Jedi_InSpecialMove(void) { + if (NPC->client->ps.torsoAnim == BOTH_KYLE_PA_1 || NPC->client->ps.torsoAnim == BOTH_KYLE_PA_2 || NPC->client->ps.torsoAnim == BOTH_KYLE_PA_3 || + NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_1 || NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_2 || NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_3 || + NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END || NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRABBED) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } - if ( Jedi_InNoAIAnim( NPC ) ) - {//in special anims, don't do force powers or attacks, just face the enemy - if ( NPC->enemy ) - { - NPC_FaceEnemy( qtrue ); - } - else - { - NPC_UpdateAngles( qtrue, qtrue ); + if (Jedi_InNoAIAnim(NPC)) { // in special anims, don't do force powers or attacks, just face the enemy + if (NPC->enemy) { + NPC_FaceEnemy(qtrue); + } else { + NPC_UpdateAngles(qtrue, qtrue); } return qtrue; } @@ -7264,154 +5569,113 @@ qboolean Jedi_InSpecialMove( void ) } */ - if ( NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START - || NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) - { - if ( !TIMER_Done( NPC, "draining" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD) { + if (!TIMER_Done(NPC, "draining")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around ucmd.buttons |= BUTTON_FORCE_DRAIN; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } - if ( NPC->client->ps.torsoAnim == BOTH_TAVION_SWORDPOWER ) - { - NPC->health += Q_irand( 1, 2 ); - if ( NPC->health > NPC->max_health ) - { + if (NPC->client->ps.torsoAnim == BOTH_TAVION_SWORDPOWER) { + NPC->health += Q_irand(1, 2); + if (NPC->health > NPC->max_health) { NPC->health = NPC->max_health; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } - if ( NPC->client->ps.torsoAnim == BOTH_SCEPTER_START ) - { - if ( NPC->client->ps.torsoAnimTimer <= 100 ) - {//go into the hold - NPC->s.loopSound = G_SoundIndex( "sound/weapons/scepter/loop.wav" ); - G_PlayEffect( G_EffectIndex( "scepter/beam.efx" ), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 10000, qtrue ); + if (NPC->client->ps.torsoAnim == BOTH_SCEPTER_START) { + if (NPC->client->ps.torsoAnimTimer <= 100) { // go into the hold + NPC->s.loopSound = G_SoundIndex("sound/weapons/scepter/loop.wav"); + G_PlayEffect(G_EffectIndex("scepter/beam.efx"), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, 10000, qtrue); NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SCEPTER_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SCEPTER_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer += 200; NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_time = NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); } - if ( NPC->enemy ) - { - NPC_FaceEnemy( qtrue ); - } - else - { - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC->enemy) { + NPC_FaceEnemy(qtrue); + } else { + NPC_UpdateAngles(qtrue, qtrue); } return qtrue; - } - else if ( NPC->client->ps.torsoAnim == BOTH_SCEPTER_HOLD ) - { - if ( NPC->client->ps.torsoAnimTimer <= 100 ) - { + } else if (NPC->client->ps.torsoAnim == BOTH_SCEPTER_HOLD) { + if (NPC->client->ps.torsoAnimTimer <= 100) { NPC->s.loopSound = 0; - G_StopEffect( G_EffectIndex( "scepter/beam.efx" ), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number ); + G_StopEffect(G_EffectIndex("scepter/beam.efx"), NPC->weaponModel[1], NPC->genericBolt1, NPC->s.number); NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SCEPTER_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SCEPTER_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->painDebounceTime = level.time + NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_time = NPC->client->ps.torsoAnimTimer; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); - } - else - { + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); + } else { Tavion_ScepterDamage(); } - if ( NPC->enemy ) - { - NPC_FaceEnemy( qtrue ); - } - else - { - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC->enemy) { + NPC_FaceEnemy(qtrue); + } else { + NPC_UpdateAngles(qtrue, qtrue); } return qtrue; - } - else if ( NPC->client->ps.torsoAnim == BOTH_SCEPTER_STOP ) - { - if ( NPC->enemy ) - { - NPC_FaceEnemy( qtrue ); - } - else - { - NPC_UpdateAngles( qtrue, qtrue ); + } else if (NPC->client->ps.torsoAnim == BOTH_SCEPTER_STOP) { + if (NPC->enemy) { + NPC_FaceEnemy(qtrue); + } else { + NPC_UpdateAngles(qtrue, qtrue); } return qtrue; - } - else if ( NPC->client->ps.torsoAnim == BOTH_TAVION_SCEPTERGROUND ) - { - if ( NPC->client->ps.torsoAnimTimer <= 1200 - && !NPC->count ) - { + } else if (NPC->client->ps.torsoAnim == BOTH_TAVION_SCEPTERGROUND) { + if (NPC->client->ps.torsoAnimTimer <= 1200 && !NPC->count) { Tavion_ScepterSlam(); NPC->count = 1; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } - if ( Jedi_CultistDestroyer( NPC ) ) - { - if ( !NPC->takedamage ) - {//ready to explode - if ( NPC->useDebounceTime <= level.time ) - { - //this should damage everyone - FIXME: except other destroyers? - NPC->client->playerTeam = TEAM_FREE;//FIXME: will this destroy wampas, tusken & rancors? - WP_Explode( NPC ); + if (Jedi_CultistDestroyer(NPC)) { + if (!NPC->takedamage) { // ready to explode + if (NPC->useDebounceTime <= level.time) { + // this should damage everyone - FIXME: except other destroyers? + NPC->client->playerTeam = TEAM_FREE; // FIXME: will this destroy wampas, tusken & rancors? + WP_Explode(NPC); return qtrue; } - if ( NPC->enemy ) - { - NPC_FaceEnemy( qfalse ); + if (NPC->enemy) { + NPC_FaceEnemy(qfalse); } return qtrue; } } - if ( NPC->client->NPC_class == CLASS_REBORN ) - { - if ( (NPCInfo->aiFlags&NPCAI_HEAL_ROSH) ) - { - if ( !NPC->client->leader ) - {//find Rosh - NPC->client->leader = G_Find( NULL, FOFS(NPC_type), "rosh_dark" ); + if (NPC->client->NPC_class == CLASS_REBORN) { + if ((NPCInfo->aiFlags & NPCAI_HEAL_ROSH)) { + if (!NPC->client->leader) { // find Rosh + NPC->client->leader = G_Find(NULL, FOFS(NPC_type), "rosh_dark"); } - //NPC->client->ps.eFlags &= ~EF_POWERING_ROSH; - if ( NPC->client->leader ) - { + // NPC->client->ps.eFlags &= ~EF_POWERING_ROSH; + if (NPC->client->leader) { qboolean helpingRosh = qfalse; NPC->flags |= FL_LOCK_PLAYER_WEAPONS; NPC->client->leader->flags |= FL_UNDYING; - if ( NPC->client->leader->client ) - { + if (NPC->client->leader->client) { NPC->client->leader->client->ps.forcePowersKnown |= FORCE_POWERS_ROSH_FROM_TWINS; } - if ( NPC->client->leader->client->ps.legsAnim == BOTH_FORCEHEAL_START - && TIMER_Done( NPC, "healRoshDebounce" ) ) - { - if ( Kothos_HealRosh() ) - { + if (NPC->client->leader->client->ps.legsAnim == BOTH_FORCEHEAL_START && TIMER_Done(NPC, "healRoshDebounce")) { + if (Kothos_HealRosh()) { helpingRosh = qtrue; - } - else - {//can't get to him! + } else { // can't get to him! NPC_BSJedi_FollowLeader(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -7426,142 +5690,109 @@ qboolean Jedi_InSpecialMove( void ) } */ - if ( helpingRosh ) - { - WP_ForcePowerStop( NPC, FP_LIGHTNING ); - WP_ForcePowerStop( NPC, FP_DRAIN ); - WP_ForcePowerStop( NPC, FP_GRIP ); - NPC_FaceEntity( NPC->client->leader, qtrue ); + if (helpingRosh) { + WP_ForcePowerStop(NPC, FP_LIGHTNING); + WP_ForcePowerStop(NPC, FP_DRAIN); + WP_ForcePowerStop(NPC, FP_GRIP); + NPC_FaceEntity(NPC->client->leader, qtrue); return qtrue; - } - else if ( NPC->enemy && DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ) < Twins_DangerDist() ) - { - if ( NPC->enemy && Kothos_Retreat() ) - { - NPC_FaceEnemy( qtrue ); - //NPC_UpdateAngles( qtrue, qtrue ); - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if ( NPC->painDebounceTime > level.time - || (NPC->health < 100 && Q_irand(-20, (g_spskill->integer+1)*10) > 0 ) - || !Q_irand( 0, 80-(g_spskill->integer*20) ) ) - { + } else if (NPC->enemy && DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin) < Twins_DangerDist()) { + if (NPC->enemy && Kothos_Retreat()) { + NPC_FaceEnemy(qtrue); + // NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPC, "attackDelay")) { + if (NPC->painDebounceTime > level.time || (NPC->health < 100 && Q_irand(-20, (g_spskill->integer + 1) * 10) > 0) || + !Q_irand(0, 80 - (g_spskill->integer * 20))) { NPC->flags &= ~FL_LOCK_PLAYER_WEAPONS; - switch ( Q_irand( 0, 7+g_spskill->integer ) )//on easy: no lightning + switch (Q_irand(0, 7 + g_spskill->integer)) // on easy: no lightning { case 0: case 1: case 2: case 3: - ForceThrow( NPC, qfalse, qfalse ); - NPC->client->ps.weaponTime = Q_irand( 1000, 3000 )+(2-g_spskill->integer)*1000; - if ( NPC->painDebounceTime <= level.time - && NPC->health >= 100 ) - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); + ForceThrow(NPC, qfalse, qfalse); + NPC->client->ps.weaponTime = Q_irand(1000, 3000) + (2 - g_spskill->integer) * 1000; + if (NPC->painDebounceTime <= level.time && NPC->health >= 100) { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); } break; case 4: case 5: - ForceDrain2( NPC ); - NPC->client->ps.weaponTime = Q_irand( 3000, 6000 )+(2-g_spskill->integer)*2000; - TIMER_Set( NPC, "draining", NPC->client->ps.weaponTime ); - if ( NPC->painDebounceTime <= level.time - && NPC->health >= 100 ) - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); + ForceDrain2(NPC); + NPC->client->ps.weaponTime = Q_irand(3000, 6000) + (2 - g_spskill->integer) * 2000; + TIMER_Set(NPC, "draining", NPC->client->ps.weaponTime); + if (NPC->painDebounceTime <= level.time && NPC->health >= 100) { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); } break; case 6: case 7: - if ( NPC->enemy && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30 ) ) - { - NPC->client->ps.weaponTime = Q_irand( 3000, 6000 )+(2-g_spskill->integer)*2000; - TIMER_Set( NPC, "gripping", 3000 ); - if ( NPC->painDebounceTime <= level.time - && NPC->health >= 100 ) - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); + if (NPC->enemy && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 20, 30)) { + NPC->client->ps.weaponTime = Q_irand(3000, 6000) + (2 - g_spskill->integer) * 2000; + TIMER_Set(NPC, "gripping", 3000); + if (NPC->painDebounceTime <= level.time && NPC->health >= 100) { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); } } break; case 8: case 9: default: - ForceLightning( NPC ); - if ( NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - { - NPC->client->ps.weaponTime = Q_irand( 3000, 6000 )+(2-g_spskill->integer)*2000; - TIMER_Set( NPC, "holdLightning", NPC->client->ps.weaponTime ); + ForceLightning(NPC); + if (NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { + NPC->client->ps.weaponTime = Q_irand(3000, 6000) + (2 - g_spskill->integer) * 2000; + TIMER_Set(NPC, "holdLightning", NPC->client->ps.weaponTime); } - if ( NPC->painDebounceTime <= level.time - && NPC->health >= 100 ) - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); + if (NPC->painDebounceTime <= level.time && NPC->health >= 100) { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); } break; } } - } - else - { + } else { NPC->flags &= ~FL_LOCK_PLAYER_WEAPONS; } Jedi_TimersApply(); return qtrue; - } - else - { + } else { NPC->flags &= ~FL_LOCK_PLAYER_WEAPONS; } - } - else if ( !G_ClearLOS( NPC, NPC->client->leader ) - || DistanceSquared( NPC->currentOrigin, NPC->client->leader->currentOrigin ) > (512*512) ) - {//can't see Rosh or too far away, catch up with him - if ( !TIMER_Done( NPC, "attackDelay" ) ) - { + } else if (!G_ClearLOS(NPC, NPC->client->leader) || DistanceSquared(NPC->currentOrigin, NPC->client->leader->currentOrigin) > + (512 * 512)) { // can't see Rosh or too far away, catch up with him + if (!TIMER_Done(NPC, "attackDelay")) { NPC->flags &= ~FL_LOCK_PLAYER_WEAPONS; } NPC_BSJedi_FollowLeader(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else - { - if ( !TIMER_Done( NPC, "attackDelay" ) ) - { + } else { + if (!TIMER_Done(NPC, "attackDelay")) { NPC->flags &= ~FL_LOCK_PLAYER_WEAPONS; } - STEER::Activate( NPC ); - STEER::Stop( NPC ); - STEER::DeActivate( NPC, &ucmd ); - NPC_FaceEnemy( qtrue ); - //NPC_UpdateAngles( qtrue, qtrue ); + STEER::Activate(NPC); + STEER::Stop(NPC); + STEER::DeActivate(NPC, &ucmd); + NPC_FaceEnemy(qtrue); + // NPC_UpdateAngles( qtrue, qtrue ); return qtrue; - //NPC_BSJedi_FollowLeader(); - } - } - NPC_UpdateAngles( qtrue, qtrue ); - //NPC->client->ps.eFlags &= ~EF_POWERING_ROSH; - //G_StopEffect( G_EffectIndex( "force/kothos_beam.efx" ), NPC->playerModel, NPC->handLBolt, NPC->s.number ); - } - else if ( (NPCInfo->aiFlags&NPCAI_ROSH) ) - { - if ( (NPC->flags&FL_UNDYING) ) - {//Vil and/or Dasariah still around to heal me - if ( NPC->health == 1 //need healing - || NPC->client->ps.powerups[PW_INVINCIBLE] > level.time )//being healed - {//FIXME: custom anims - if ( Rosh_TwinPresent( NPC ) ) - { - if ( !NPC->client->ps.weaponTime ) - {//not attacking - if ( NPC->client->ps.legsAnim != BOTH_FORCEHEAL_START - && NPC->client->ps.legsAnim != BOTH_FORCEHEAL_STOP ) - {//get down and wait for Vil or Dasariah to help us - //FIXME: sound? + // NPC_BSJedi_FollowLeader(); + } + } + NPC_UpdateAngles(qtrue, qtrue); + // NPC->client->ps.eFlags &= ~EF_POWERING_ROSH; + // G_StopEffect( G_EffectIndex( "force/kothos_beam.efx" ), NPC->playerModel, NPC->handLBolt, NPC->s.number ); + } else if ((NPCInfo->aiFlags & NPCAI_ROSH)) { + if ((NPC->flags & FL_UNDYING)) { // Vil and/or Dasariah still around to heal me + if (NPC->health == 1 // need healing + || NPC->client->ps.powerups[PW_INVINCIBLE] > level.time) // being healed + { // FIXME: custom anims + if (Rosh_TwinPresent(NPC)) { + if (!NPC->client->ps.weaponTime) { // not attacking + if (NPC->client->ps.legsAnim != BOTH_FORCEHEAL_START && + NPC->client->ps.legsAnim != BOTH_FORCEHEAL_STOP) { // get down and wait for Vil or Dasariah to help us + // FIXME: sound? NPC->client->ps.legsAnimTimer = NPC->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = NPC->client->ps.legsAnimTimer = -1; NPC->client->ps.SaberDeactivate(); NPCInfo->ignorePain = qtrue; @@ -7572,8 +5803,8 @@ qboolean Jedi_InSpecialMove( void ) NPC->painDebounceTime = level.time + 500; NPC->client->ps.pm_time = 500; NPC->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - VectorClear( NPC->client->ps.velocity ); - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.velocity); + VectorClear(NPC->client->ps.moveDir); return qtrue; } } @@ -7581,14 +5812,12 @@ qboolean Jedi_InSpecialMove( void ) } } - if ( PM_SuperBreakWinAnim( NPC->client->ps.torsoAnim ) ) - { - NPC_FaceEnemy( qtrue ); - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - VectorClear( NPC->client->ps.velocity ); + if (PM_SuperBreakWinAnim(NPC->client->ps.torsoAnim)) { + NPC_FaceEnemy(qtrue); + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { + VectorClear(NPC->client->ps.velocity); } - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); ucmd.rightmove = ucmd.forwardmove = ucmd.upmove = 0; return qtrue; } @@ -7596,73 +5825,61 @@ qboolean Jedi_InSpecialMove( void ) return qfalse; } -extern void NPC_BSST_Patrol( void ); -extern void NPC_BSSniper_Default( void ); -extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ); -void NPC_BSJedi_Default( void ) -{ - if ( Jedi_InSpecialMove() ) - { +extern void NPC_BSST_Patrol(void); +extern void NPC_BSSniper_Default(void); +extern void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir); +void NPC_BSJedi_Default(void) { + if (Jedi_InSpecialMove()) { return; } Jedi_CheckCloak(); - if( !NPC->enemy ) - {//don't have an enemy, look for one - if ( NPC->client->NPC_class == CLASS_BOBAFETT - || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) - || NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - { + if (!NPC->enemy) { // don't have an enemy, look for one + if (NPC->client->NPC_class == CLASS_BOBAFETT || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) || + NPC->client->NPC_class == CLASS_ROCKETTROOPER) { NPC_BSST_Patrol(); - } - else - { + } else { Jedi_Patrol(); } - } - else//if ( NPC->enemy ) - {//have an enemy - if ( Jedi_WaitingAmbush( NPC ) ) - {//we were still waiting to drop down - must have had enemy set on me outside my AI - Jedi_Ambush( NPC ); + } else // if ( NPC->enemy ) + { // have an enemy + if (Jedi_WaitingAmbush(NPC)) { // we were still waiting to drop down - must have had enemy set on me outside my AI + Jedi_Ambush(NPC); } - if ( Jedi_CultistDestroyer( NPC ) - && !NPCInfo->charmedTime ) - {//destroyer - //permanent effect + if (Jedi_CultistDestroyer(NPC) && !NPCInfo->charmedTime) { // destroyer + // permanent effect NPCInfo->charmedTime = Q3_INFINITE; - NPC->client->ps.forcePowersActive |= ( 1 << FP_RAGE ); + NPC->client->ps.forcePowersActive |= (1 << FP_RAGE); NPC->client->ps.forcePowerDuration[FP_RAGE] = Q3_INFINITE; - //NPC->client->ps.eFlags |= EF_FORCE_DRAINED; - //FIXME: precache me! - NPC->s.loopSound = G_SoundIndex( "sound/movers/objects/green_beam_lp2.wav" );//test/charm.wav" ); + // NPC->client->ps.eFlags |= EF_FORCE_DRAINED; + // FIXME: precache me! + NPC->s.loopSound = G_SoundIndex("sound/movers/objects/green_beam_lp2.wav"); // test/charm.wav" ); } Jedi_Attack(); - //if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch if needbe... - if ( ((!ucmd.buttons&&!NPC->client->ps.forcePowersActive)||(NPC->enemy&&NPC->enemy->health<=0)) && NPCInfo->enemyCheckDebounceTime < level.time ) - {//not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), not using force powers and it's time to look again - //FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain their own list and we just access it? - gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy? + // if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch + // if needbe... + if (((!ucmd.buttons && !NPC->client->ps.forcePowersActive) || (NPC->enemy && NPC->enemy->health <= 0)) && + NPCInfo->enemyCheckDebounceTime < level.time) { // not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), not + // using force powers and it's time to look again + // FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when + // to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain + // their own list and we just access it? + gentity_t *sav_enemy = NPC->enemy; // FIXME: what about NPC->lastEnemy? NPC->enemy = NULL; - gentity_t *newEnemy = NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse ); + gentity_t *newEnemy = NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse); NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, newEnemy ); + G_SetEnemy(NPC, newEnemy); } - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 3000 ); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 3000); } } - if ( NPC->client->ps.saber[0].type == SABER_SITH_SWORD - && NPC->weaponModel[0] != -1 ) - { - if ( NPC->health < 100 - && !Q_irand( 0, 20 ) ) - { + if (NPC->client->ps.saber[0].type == SABER_SITH_SWORD && NPC->weaponModel[0] != -1) { + if (NPC->health < 100 && !Q_irand(0, 20)) { Tavion_SithSwordRecharge(); } } diff --git a/code/game/AI_Mark1.cpp b/code/game/AI_Mark1.cpp index 9e31f6cfd8..4976460886 100644 --- a/code/game/AI_Mark1.cpp +++ b/code/game/AI_Mark1.cpp @@ -25,29 +25,28 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -#define LEFT_ARM_HEALTH 40 -#define RIGHT_ARM_HEALTH 40 -#define AMMO_POD_HEALTH 40 +#define LEFT_ARM_HEALTH 40 +#define RIGHT_ARM_HEALTH 40 +#define AMMO_POD_HEALTH 40 -#define BOWCASTER_VELOCITY 1300 -#define BOWCASTER_NPC_DAMAGE_EASY 12 -#define BOWCASTER_NPC_DAMAGE_NORMAL 24 -#define BOWCASTER_NPC_DAMAGE_HARD 36 -#define BOWCASTER_SIZE 2 -#define BOWCASTER_SPLASH_DAMAGE 0 -#define BOWCASTER_SPLASH_RADIUS 0 +#define BOWCASTER_VELOCITY 1300 +#define BOWCASTER_NPC_DAMAGE_EASY 12 +#define BOWCASTER_NPC_DAMAGE_NORMAL 24 +#define BOWCASTER_NPC_DAMAGE_HARD 36 +#define BOWCASTER_SIZE 2 +#define BOWCASTER_SPLASH_DAMAGE 0 +#define BOWCASTER_SPLASH_RADIUS 0 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -58,41 +57,40 @@ enum LSTATE_FIRED4, }; -qboolean NPC_CheckPlayerTeamStealth( void ); -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +qboolean NPC_CheckPlayerTeamStealth(void); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); void Mark1_BlasterAttack(qboolean advance); -void DeathFX( gentity_t *ent ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +void DeathFX(gentity_t *ent); +extern gitem_t *FindItemForAmmo(ammo_t ammo); /* ------------------------- NPC_Mark1_Precache ------------------------- */ -void NPC_Mark1_Precache(void) -{ - G_SoundIndex( "sound/chars/mark1/misc/mark1_wakeup"); - G_SoundIndex( "sound/chars/mark1/misc/shutdown"); - G_SoundIndex( "sound/chars/mark1/misc/walk"); - G_SoundIndex( "sound/chars/mark1/misc/run"); - G_SoundIndex( "sound/chars/mark1/misc/death1"); - G_SoundIndex( "sound/chars/mark1/misc/death2"); - G_SoundIndex( "sound/chars/mark1/misc/anger"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_fire"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_pain"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_explo"); - -// G_EffectIndex( "small_chunks"); - G_EffectIndex( "env/med_explode2"); - G_EffectIndex( "explosions/probeexplosion1"); - G_EffectIndex( "blaster/smoke_bolton"); - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "explosions/droidexplosion1" ); - - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( FindItemForWeapon( WP_BOWCASTER )); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); +void NPC_Mark1_Precache(void) { + G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup"); + G_SoundIndex("sound/chars/mark1/misc/shutdown"); + G_SoundIndex("sound/chars/mark1/misc/walk"); + G_SoundIndex("sound/chars/mark1/misc/run"); + G_SoundIndex("sound/chars/mark1/misc/death1"); + G_SoundIndex("sound/chars/mark1/misc/death2"); + G_SoundIndex("sound/chars/mark1/misc/anger"); + G_SoundIndex("sound/chars/mark1/misc/mark1_fire"); + G_SoundIndex("sound/chars/mark1/misc/mark1_pain"); + G_SoundIndex("sound/chars/mark1/misc/mark1_explo"); + + // G_EffectIndex( "small_chunks"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("explosions/probeexplosion1"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("explosions/droidexplosion1"); + + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(FindItemForWeapon(WP_BOWCASTER)); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); } /* @@ -100,23 +98,19 @@ void NPC_Mark1_Precache(void) NPC_Mark1_Part_Explode ------------------------- */ -void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark1_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - bolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( "env/med_explode2", org, dir ); - G_PlayEffect( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number, org ); + G_PlayEffect("env/med_explode2", org, dir); + G_PlayEffect(G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number, org); } } @@ -125,12 +119,11 @@ void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) Mark1_Idle ------------------------- */ -void Mark1_Idle( void ) -{ +void Mark1_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL); } /* @@ -139,32 +132,29 @@ Mark1Dead_FireRocket - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireRocket (void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,muzzle_dir; +void Mark1Dead_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, muzzle_dir; - int damage = 50; + int damage = 50; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt5, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, muzzle_dir); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - gentity_t *missile = CreateMissile( muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC ); + gentity_t *missile = CreateMissile(muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -175,7 +165,6 @@ void Mark1Dead_FireRocket (void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -184,28 +173,25 @@ Mark1Dead_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireBlaster (void) -{ - vec3_t muzzle1,muzzle_dir; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1Dead_FireBlaster(void) { + vec3_t muzzle1, muzzle_dir; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; bolt = NPC->genericBolt1; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, muzzle_dir); - missile = CreateMissile( muzzle1, muzzle_dir, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, muzzle_dir, 1600, 10000, NPC); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -214,7 +200,6 @@ void Mark1Dead_FireBlaster (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -222,8 +207,7 @@ void Mark1Dead_FireBlaster (void) Mark1_die ------------------------- */ -void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Mark1_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { /* int anim; @@ -245,16 +229,13 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } */ - G_Sound( self, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav",Q_irand( 1, 2)))); + G_Sound(self, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav", Q_irand(1, 2)))); // Choose a death anim - if (Q_irand( 1, 10) > 5) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (Q_irand(1, 10) > 5) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } @@ -263,68 +244,58 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int Mark1_dying ------------------------- */ -void Mark1_dying( gentity_t *self ) -{ - int num,newBolt; +void Mark1_dying(gentity_t *self) { + int num, newBolt; - if (self->client->ps.torsoAnimTimer>0) - { - if (TIMER_Done(self,"dyingExplosion")) - { - num = Q_irand( 1, 3); + if (self->client->ps.torsoAnimTimer > 0) { + if (TIMER_Done(self, "dyingExplosion")) { + num = Q_irand(1, 3); // Find place to generate explosion - if (num == 1) - { - num = Q_irand( 8, 10); - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*flash%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - } - else - { - num = Q_irand( 1, 6); - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",num), TURN_OFF ); + if (num == 1) { + num = Q_irand(8, 10); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*flash%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + } else { + num = Q_irand(1, 6); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*torso_tube%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_tube%d", num), TURN_OFF); } - TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1000 ) ); + TIMER_Set(self, "dyingExplosion", Q_irand(300, 1000)); } - -// int dir; -// vec3_t right; + // int dir; + // vec3_t right; // Shove to the side -// AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); -// VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); + // AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); + // VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); // See which weapons are there // Randomly fire blaster - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) // Is the blaster still on the model? + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm")) // Is the blaster still on the model? { - if (Q_irand( 1, 5) == 1) - { + if (Q_irand(1, 5) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireBlaster(); RestoreNPCGlobals(); } } // Randomly fire rocket - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" )) // Is the rocket still on the model? + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_arm")) // Is the rocket still on the model? { - if (Q_irand( 1, 10) == 1) - { + if (Q_irand(1, 10) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireRocket(); RestoreNPCGlobals(); } } } - } /* @@ -333,69 +304,58 @@ NPC_Mark1_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark1_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - int newBolt,i,chance; +void NPC_Mark1_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + int newBolt, i, chance; - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - G_Sound( self, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); + G_Sound(self, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); // Hit in the CHEST??? - if (hitLoc==HL_CHEST) - { - chance = Q_irand( 1, 4); + if (hitLoc == HL_CHEST) { + chance = Q_irand(1, 4); - if ((chance == 1) && (damage > 5)) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((chance == 1) && (damage > 5)) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } // Hit in the left arm? - else if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) - { - if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? + else if ((hitLoc == HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { + if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash3" ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash3"); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm", TURN_OFF); } } // Hit in the right arm? - else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? + else if ((hitLoc == HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash4" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); - NPC_Mark1_Part_Explode( self, newBolt ); + if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash4"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "r_arm", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "r_arm", TURN_OFF); } } // Check ammo pods - else - { - for (i=0;i<6;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + else { + for (i = 0; i < 6; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*torso_tube%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",(i+1)), TURN_OFF ); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_tube%d", (i + 1)), TURN_OFF); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); break; } } @@ -403,12 +363,10 @@ void NPC_Mark1_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, co } // Are both guns shot off? - if ((gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) && - (gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" ))) - { - G_Damage(self,NULL,NULL,NULL,NULL,self->health,0,MOD_UNKNOWN); + if ((gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm")) && + (gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_arm"))) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, 0, MOD_UNKNOWN); } - } /* @@ -417,18 +375,16 @@ Mark1_Hunt - look for enemy. -------------------------` */ -void Mark1_Hunt(void) -{ +void Mark1_Hunt(void) { - if ( NPCInfo->goalEntity == NULL ) - { + if (NPCInfo->goalEntity == NULL) { NPCInfo->goalEntity = NPC->enemy; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -437,60 +393,47 @@ Mark1_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; // Which muzzle to fire from? - if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) - { + if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) { NPCInfo->localState = LSTATE_FIRED1; bolt = NPC->genericBolt1; - } - else if (NPCInfo->localState == LSTATE_FIRED1) - { + } else if (NPCInfo->localState == LSTATE_FIRED1) { NPCInfo->localState = LSTATE_FIRED2; bolt = NPC->genericBolt2; - } - else if (NPCInfo->localState == LSTATE_FIRED2) - { + } else if (NPCInfo->localState == LSTATE_FIRED2) { NPCInfo->localState = LSTATE_FIRED3; bolt = NPC->genericBolt3; - } - else - { + } else { NPCInfo->localState = LSTATE_FIRED4; bolt = NPC->genericBolt4; } - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, forward); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -499,7 +442,6 @@ void Mark1_FireBlaster(void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -507,57 +449,47 @@ void Mark1_FireBlaster(void) Mark1_BlasterAttack ------------------------- */ -void Mark1_BlasterAttack(qboolean advance ) -{ +void Mark1_BlasterAttack(qboolean advance) { int chance; - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - chance = Q_irand( 1, 5); + chance = Q_irand(1, 5); NPCInfo->burstCount++; - if (NPCInfo->burstCount<3) // Too few shots this burst? + if (NPCInfo->burstCount < 3) // Too few shots this burst? { - chance = 2; // Force it to keep firing. - } - else if (NPCInfo->burstCount>12) // Too many shots fired this burst? + chance = 2; // Force it to keep firing. + } else if (NPCInfo->burstCount > 12) // Too many shots fired this burst? { NPCInfo->burstCount = 0; - chance = 1; // Force it to stop firing. + chance = 1; // Force it to stop firing. } // Stop firing. - if (chance == 1) - { + if (chance == 1) { NPCInfo->burstCount = 0; - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. - } - else - { - if (TIMER_Done( NPC, "attackDelay2" )) // Can't be shooting every frame. + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. + } else { + if (TIMER_Done(NPC, "attackDelay2")) // Can't be shooting every frame. { - TIMER_Set( NPC, "attackDelay2", Q_irand( 50, 50) ); + TIMER_Set(NPC, "attackDelay2", Q_irand(50, 50)); Mark1_FireBlaster(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } return; } - } - else if (advance) - { - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. + } else if (advance) { + if (NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. } Mark1_Hunt(); - } - else // Make sure he's not firing. + } else // Make sure he's not firing. { - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. + if (NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. } } } @@ -567,37 +499,34 @@ void Mark1_BlasterAttack(qboolean advance ) Mark1_FireRocket ------------------------- */ -void Mark1_FireRocket(void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; +void Mark1_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; - int damage = 50; + int damage = 50; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt5, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); -// G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); + // G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire" )); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - gentity_t *missile = CreateMissile( muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC ); + gentity_t *missile = CreateMissile(muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -608,7 +537,6 @@ void Mark1_FireRocket(void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -616,16 +544,13 @@ void Mark1_FireRocket(void) Mark1_RocketAttack ------------------------- */ -void Mark1_RocketAttack( qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Mark1_RocketAttack(qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); Mark1_FireRocket(); - } - else if (advance) - { + } else if (advance) { Mark1_Hunt(); } } @@ -635,58 +560,47 @@ void Mark1_RocketAttack( qboolean advance ) Mark1_AttackDecision ------------------------- */ -void Mark1_AttackDecision( void ) -{ - int blasterTest,rocketTest; - - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); +void Mark1_AttackDecision(void) { + int blasterTest, rocketTest; + + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // Enemy is dead or he has no enemy. - if ((NPC->enemy->health<1) || ( NPC_CheckEnemyExt() == qfalse )) - { + if ((NPC->enemy->health < 1) || (NPC_CheckEnemyExt() == qfalse)) { NPC->enemy = NULL; return; } // Rate our distance to the target and visibility - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + distance_e distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { Mark1_Hunt(); return; } // See if the side weapons are there - blasterTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "l_arm" ); - rocketTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "r_arm" ); + blasterTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "l_arm"); + rocketTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "r_arm"); // It has both side weapons - if (!blasterTest && !rocketTest) - { - ; // So do nothing. - } - else if (blasterTest) - { + if (!blasterTest && !rocketTest) { + ; // So do nothing. + } else if (blasterTest) { distRate = DIST_LONG; - } - else if (rocketTest) - { + } else if (rocketTest) { distRate = DIST_MELEE; - } - else // It should never get here, but just in case + } else // It should never get here, but just in case { NPC->health = 0; NPC->client->ps.stats[STAT_HEALTH] = 0; @@ -694,14 +608,11 @@ void Mark1_AttackDecision( void ) } // We can see enemy so shoot him if timers let you. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (distRate == DIST_MELEE) - { + if (distRate == DIST_MELEE) { Mark1_BlasterAttack(advance); - } - else if (distRate == DIST_LONG) - { + } else if (distRate == DIST_LONG) { Mark1_RocketAttack(advance); } } @@ -711,57 +622,45 @@ void Mark1_AttackDecision( void ) Mark1_Patrol ------------------------- */ -void Mark1_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark1_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk -// if (TIMER_Done(NPC,"patrolNoise")) -// { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); -// -// TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); -// } + // randomly talk + // if (TIMER_Done(NPC,"patrolNoise")) + // { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // + // TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + // } } - } - /* ------------------------- NPC_BSMark1_Default ------------------------- */ -void NPC_BSMark1_Default( void ) -{ - //NPC->e_DieFunc = dieF_Mark1_die; +void NPC_BSMark1_Default(void) { + // NPC->e_DieFunc = dieF_Mark1_die; - if ( NPC->enemy ) - { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; Mark1_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark1_Patrol(); - } - else - { + } else { Mark1_Idle(); } } diff --git a/code/game/AI_Mark2.cpp b/code/game/AI_Mark2.cpp index 7c66513386..7b71a98127 100644 --- a/code/game/AI_Mark2.cpp +++ b/code/game/AI_Mark2.cpp @@ -23,48 +23,45 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" - #include "b_local.h" #include "g_nav.h" -#define AMMO_POD_HEALTH 1 -#define TURN_OFF 0x00000100 +#define AMMO_POD_HEALTH 1 +#define TURN_OFF 0x00000100 -#define VELOCITY_DECAY 0.25 -#define MAX_DISTANCE 256 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) -#define MIN_DISTANCE 24 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define VELOCITY_DECAY 0.25 +#define MAX_DISTANCE 256 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) +#define MIN_DISTANCE 24 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +extern gitem_t *FindItemForAmmo(ammo_t ammo); -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_DROPPINGDOWN, LSTATE_DOWN, LSTATE_RISINGUP, }; -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void NPC_Mark2_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" );// blows up on death - G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_fire" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); +void NPC_Mark2_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // blows up on death + G_SoundIndex("sound/chars/mark2/misc/mark2_pain"); + G_SoundIndex("sound/chars/mark2/misc/mark2_fire"); + G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); - G_EffectIndex( "explosions/droidexplosion1" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "bryar/muzzle_flash" ); + G_EffectIndex("explosions/droidexplosion1"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( FindItemForAmmo( AMMO_POWERCELL )); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(FindItemForAmmo(AMMO_POWERCELL)); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } /* @@ -72,26 +69,22 @@ void NPC_Mark2_Precache( void ) NPC_Mark2_Part_Explode ------------------------- */ -void NPC_Mark2_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark2_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - bolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( "env/med_explode2", org, dir ); - G_PlayEffect( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number, org); + G_PlayEffect("env/med_explode2", org, dir); + G_PlayEffect(G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number, org); } - self->count++; // Count of pods blown off + self->count++; // Count of pods blown off } /* @@ -100,35 +93,30 @@ NPC_Mark2_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark2_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - int newBolt,i; +void NPC_Mark2_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + int newBolt, i; - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - for (i=0;i<3;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + for (i = 0; i < 3; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark2_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("torso_canister%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark2_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)), TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_canister%d", (i + 1)), TURN_OFF); break; } } } - G_Sound( self, G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" )); + G_Sound(self, G_SoundIndex("sound/chars/mark2/misc/mark2_pain")); // If any pods were blown off, kill him - if (self->count > 0) - { - G_Damage( self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN ); + if (self->count > 0) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } } @@ -137,18 +125,16 @@ void NPC_Mark2_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, co Mark2_Hunt ------------------------- */ -void Mark2_Hunt(void) -{ - if ( NPCInfo->goalEntity == NULL ) - { +void Mark2_Hunt(void) { + if (NPCInfo->goalEntity == NULL) { NPCInfo->goalEntity = NPC->enemy; } // Turn toward him before moving towards him. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -156,37 +142,31 @@ void Mark2_Hunt(void) Mark2_FireBlaster ------------------------- */ -void Mark2_FireBlaster(qboolean advance) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt1, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); +void Mark2_FireBlaster(qboolean advance) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt1, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); + + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, forward); - G_Sound( NPC, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -195,7 +175,6 @@ void Mark2_FireBlaster(qboolean advance) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -203,23 +182,18 @@ void Mark2_FireBlaster(qboolean advance) Mark2_BlasterAttack ------------------------- */ -void Mark2_BlasterAttack(qboolean advance) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Mark2_BlasterAttack(qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - if (NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. + if (NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2000) ); - } - else - { - TIMER_Set( NPC, "attackDelay", Q_irand( 100, 500) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2000)); + } else { + TIMER_Set(NPC, "attackDelay", Q_irand(100, 500)); } Mark2_FireBlaster(advance); return; - } - else if (advance) - { + } else if (advance) { Mark2_Hunt(); } } @@ -229,118 +203,97 @@ void Mark2_BlasterAttack(qboolean advance) Mark2_AttackDecision ------------------------- */ -void Mark2_AttackDecision( void ) -{ - NPC_FaceEnemy( qtrue ); +void Mark2_AttackDecision(void) { + NPC_FaceEnemy(qtrue); - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // He's been ordered to get up - if (NPCInfo->localState == LSTATE_RISINGUP) - { + if (NPCInfo->localState == LSTATE_RISINGUP) { NPC->flags &= ~FL_SHIELDED; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - if ((NPC->client->ps.legsAnimTimer==0) && - NPC->client->ps.torsoAnim == BOTH_RUN1START ) - { - NPCInfo->localState = LSTATE_NONE; // He's up again. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + if ((NPC->client->ps.legsAnimTimer == 0) && NPC->client->ps.torsoAnim == BOTH_RUN1START) { + NPCInfo->localState = LSTATE_NONE; // He's up again. } return; } // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { // If he's going down or is down, make him get up - if ((NPCInfo->localState == LSTATE_DOWN) || (NPCInfo->localState == LSTATE_DROPPINGDOWN)) - { - if ( TIMER_Done( NPC, "downTime" ) ) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) + if ((NPCInfo->localState == LSTATE_DOWN) || (NPCInfo->localState == LSTATE_DROPPINGDOWN)) { + if (TIMER_Done(NPC, "downTime")) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) { NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - } - else - { + } else { Mark2_Hunt(); } return; } // He's down but he could advance if he wants to. - if ((advance) && (TIMER_Done( NPC, "downTime" )) && (NPCInfo->localState == LSTATE_DOWN)) - { + if ((advance) && (TIMER_Done(NPC, "downTime")) && (NPCInfo->localState == LSTATE_DOWN)) { NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Dropping down to shoot - if (NPCInfo->localState == LSTATE_DROPPINGDOWN) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "downTime", Q_irand( 3000, 9000) ); + if (NPCInfo->localState == LSTATE_DROPPINGDOWN) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "downTime", Q_irand(3000, 9000)); - if ((NPC->client->ps.legsAnimTimer==0) && NPC->client->ps.torsoAnim == BOTH_RUN1STOP ) - { + if ((NPC->client->ps.legsAnimTimer == 0) && NPC->client->ps.torsoAnim == BOTH_RUN1STOP) { NPC->flags |= FL_SHIELDED; NPCInfo->localState = LSTATE_DOWN; } } // He's down and shooting - else if (NPCInfo->localState == LSTATE_DOWN) - { -// NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles + else if (NPCInfo->localState == LSTATE_DOWN) { + // NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles Mark2_BlasterAttack(qfalse); - } - else if (TIMER_Done( NPC, "runTime" )) // Lowering down to attack. But only if he's done running at you. + } else if (TIMER_Done(NPC, "runTime")) // Lowering down to attack. But only if he's done running at you. { NPCInfo->localState = LSTATE_DROPPINGDOWN; - } - else if (advance) - { + } else if (advance) { // We can see enemy so shoot him if timer lets you. Mark2_BlasterAttack(advance); } } - /* ------------------------- Mark2_Patrol ------------------------- */ -void Mark2_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { -// G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark2_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + // G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } } @@ -350,29 +303,20 @@ void Mark2_Patrol( void ) Mark2_Idle ------------------------- */ -void Mark2_Idle( void ) -{ - NPC_BSIdle(); -} +void Mark2_Idle(void) { NPC_BSIdle(); } /* ------------------------- NPC_BSMark2_Default ------------------------- */ -void NPC_BSMark2_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSMark2_Default(void) { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; Mark2_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark2_Patrol(); - } - else - { + } else { Mark2_Idle(); } } diff --git a/code/game/AI_MineMonster.cpp b/code/game/AI_MineMonster.cpp index 02ad97ce8f..f499861514 100644 --- a/code/game/AI_MineMonster.cpp +++ b/code/game/AI_MineMonster.cpp @@ -25,71 +25,61 @@ along with this program; if not, see . #include "g_functions.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 /* ------------------------- NPC_MineMonster_Precache ------------------------- */ -void NPC_MineMonster_Precache( void ) -{ - for ( int i = 0; i < 4; i++ ) - { - G_SoundIndex( va("sound/chars/mine/misc/bite%i.wav", i+1 )); - G_SoundIndex( va("sound/chars/mine/misc/miss%i.wav", i+1 )); +void NPC_MineMonster_Precache(void) { + for (int i = 0; i < 4; i++) { + G_SoundIndex(va("sound/chars/mine/misc/bite%i.wav", i + 1)); + G_SoundIndex(va("sound/chars/mine/misc/miss%i.wav", i + 1)); } } - /* ------------------------- MineMonster_Idle ------------------------- */ -void MineMonster_Idle( void ) -{ - if ( UpdateGoal() ) - { +void MineMonster_Idle(void) { + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - /* ------------------------- MineMonster_Patrol ------------------------- */ -void MineMonster_Patrol( void ) -{ +void MineMonster_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } vec3_t dif; - VectorSubtract( g_entities[0].currentOrigin, NPC->currentOrigin, dif ); + VectorSubtract(g_entities[0].currentOrigin, NPC->currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { MineMonster_Idle(); return; } @@ -100,138 +90,108 @@ void MineMonster_Patrol( void ) MineMonster_Move ------------------------- */ -void MineMonster_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +void MineMonster_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - NPC_MoveToGoal( qtrue ); - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -void MineMonster_TryDamage( gentity_t *enemy, int damage ) -{ - vec3_t end, dir; - trace_t tr; +void MineMonster_TryDamage(gentity_t *enemy, int damage) { + vec3_t end, dir; + trace_t tr; - if ( !enemy ) - { + if (!enemy) { return; } - AngleVectors( NPC->client->ps.viewangles, dir, NULL, NULL ); - VectorMA( NPC->currentOrigin, MIN_DISTANCE, dir, end ); + AngleVectors(NPC->client->ps.viewangles, dir, NULL, NULL); + VectorMA(NPC->currentOrigin, MIN_DISTANCE, dir, end); // Should probably trace from the mouth, but, ah well. - gi.trace( &tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE ) - { - G_Damage( &g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - G_SoundOnEnt( NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/bite%i.wav", Q_irand(1,4))); - } - else - { - G_SoundOnEnt( NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/miss%i.wav", Q_irand(1,4))); + if (tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE) { + G_Damage(&g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + G_SoundOnEnt(NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/bite%i.wav", Q_irand(1, 4))); + } else { + G_SoundOnEnt(NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/miss%i.wav", Q_irand(1, 4))); } } //------------------------------ -void MineMonster_Attack( void ) -{ - if ( !TIMER_Exists( NPC, "attacking" )) - { +void MineMonster_Attack(void) { + if (!TIMER_Exists(NPC, "attacking")) { // usually try and play a jump attack if the player somehow got above them....or just really rarely - if ( NPC->enemy && ((NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f ) - || Q_flrand(0.0f, 1.0f) > 0.8f )) - { + if (NPC->enemy && ((NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f) || Q_flrand(0.0f, 1.0f) > 0.8f)) { // Going to do ATTACK4 - TIMER_Set( NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack2_dmg", 950 ); // level two damage - } - else if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - if ( Q_flrand(0.0f, 1.0f) > 0.8f ) - { + TIMER_Set(NPC, "attack2_dmg", 950); // level two damage + } else if (Q_flrand(0.0f, 1.0f) > 0.5f) { + if (Q_flrand(0.0f, 1.0f) > 0.8f) { // Going to do ATTACK3, (rare) - TIMER_Set( NPC, "attacking", 850 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 850); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack2_dmg", 400 ); // level two damage - } - else - { + TIMER_Set(NPC, "attack2_dmg", 400); // level two damage + } else { // Going to do ATTACK1 - TIMER_Set( NPC, "attacking", 850 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 850); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack1_dmg", 450 ); // level one damage + TIMER_Set(NPC, "attack1_dmg", 450); // level one damage } - } - else - { + } else { // Going to do ATTACK2 - TIMER_Set( NPC, "attacking", 1250 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 1250); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack1_dmg", 700 ); // level one damage + TIMER_Set(NPC, "attack1_dmg", 700); // level one damage } - } - else - { + } else { // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPC, "attack1_dmg", qtrue )) - { - MineMonster_TryDamage( NPC->enemy, 5 ); - } - else if ( TIMER_Done2( NPC, "attack2_dmg", qtrue )) - { - MineMonster_TryDamage( NPC->enemy, 10 ); + if (TIMER_Done2(NPC, "attack1_dmg", qtrue)) { + MineMonster_TryDamage(NPC->enemy, 5); + } else if (TIMER_Done2(NPC, "attack2_dmg", qtrue)) { + MineMonster_TryDamage(NPC->enemy, 10); } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); } //---------------------------------- -void MineMonster_Combat( void ) -{ +void MineMonster_Combat(void) { // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS(NPC->enemy) || UpdateGoal()) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - qboolean advance = (qboolean)( distance > MIN_DISTANCE_SQR ? qtrue : qfalse ); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR ? qtrue : qfalse); - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else { + MineMonster_Move(qtrue); } - else - { - MineMonster_Move( qtrue ); - } - } - else - { + } else { MineMonster_Attack(); } } @@ -241,48 +201,38 @@ void MineMonster_Combat( void ) NPC_MineMonster_Pain ------------------------- */ -void NPC_MineMonster_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); +void NPC_MineMonster_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->max_health * 100.0f)); - if ( damage >= 10 ) - { - TIMER_Remove( self, "attacking" ); - TIMER_Remove( self, "attacking1_dmg" ); - TIMER_Remove( self, "attacking2_dmg" ); - TIMER_Set( self, "takingPain", 1350 ); + if (damage >= 10) { + TIMER_Remove(self, "attacking"); + TIMER_Remove(self, "attacking1_dmg"); + TIMER_Remove(self, "attacking2_dmg"); + TIMER_Set(self, "takingPain", 1350); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } - /* ------------------------- NPC_BSMineMonster_Default ------------------------- */ -void NPC_BSMineMonster_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSMineMonster_Default(void) { + if (NPC->enemy) { MineMonster_Combat(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { MineMonster_Patrol(); - } - else - { + } else { MineMonster_Idle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/code/game/AI_Rancor.cpp b/code/game/AI_Rancor.cpp index 803636dfe3..b62f5edaa9 100644 --- a/code/game/AI_Rancor.cpp +++ b/code/game/AI_Rancor.cpp @@ -27,83 +27,75 @@ along with this program; if not, see . #include "g_nav.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 1024 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 1024 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 -#define SPF_RANCOR_MUTANT 1 -#define SPF_RANCOR_FASTKILL 2 +#define SPF_RANCOR_MUTANT 1 +#define SPF_RANCOR_FASTKILL 2 -extern qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ); -extern cvar_t *g_dismemberment; -extern cvar_t *g_bobaDebug; +extern qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker); +extern cvar_t *g_dismemberment; +extern cvar_t *g_bobaDebug; -void Rancor_Attack( float distance, qboolean doCharge, qboolean aimAtBlockedEntity ); +void Rancor_Attack(float distance, qboolean doCharge, qboolean aimAtBlockedEntity); /* ------------------------- NPC_Rancor_Precache ------------------------- */ -void NPC_Rancor_Precache( void ) -{ +void NPC_Rancor_Precache(void) { int i; - for ( i = 1; i < 5; i ++ ) - { - G_SoundIndex( va("sound/chars/rancor/snort_%d.wav", i) ); + for (i = 1; i < 5; i++) { + G_SoundIndex(va("sound/chars/rancor/snort_%d.wav", i)); } - G_SoundIndex( "sound/chars/rancor/swipehit.wav" ); - G_SoundIndex( "sound/chars/rancor/chomp.wav" ); + G_SoundIndex("sound/chars/rancor/swipehit.wav"); + G_SoundIndex("sound/chars/rancor/chomp.wav"); } -void NPC_MutantRancor_Precache( void ) -{ - G_SoundIndex( "sound/chars/rancor/breath_start.wav" ); - G_SoundIndex( "sound/chars/rancor/breath_loop.wav" ); - G_EffectIndex( "mrancor/breath" ); +void NPC_MutantRancor_Precache(void) { + G_SoundIndex("sound/chars/rancor/breath_start.wav"); + G_SoundIndex("sound/chars/rancor/breath_loop.wav"); + G_EffectIndex("mrancor/breath"); } -//FIXME: initialize all my timers - -qboolean Rancor_CheckAhead( vec3_t end ) -{ - trace_t trace; - int clipmask = NPC->clipmask|CONTENTS_BOTCLIP; - - //make sure our goal isn't underground (else the trace will fail) - vec3_t bottom = {end[0],end[1],end[2]+NPC->mins[2]}; - gi.trace( &trace, end, vec3_origin, vec3_origin, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//in the ground, raise it up - end[2] -= NPC->mins[2]*(1.0f-trace.fraction)-0.125f; +// FIXME: initialize all my timers + +qboolean Rancor_CheckAhead(vec3_t end) { + trace_t trace; + int clipmask = NPC->clipmask | CONTENTS_BOTCLIP; + + // make sure our goal isn't underground (else the trace will fail) + vec3_t bottom = {end[0], end[1], end[2] + NPC->mins[2]}; + gi.trace(&trace, end, vec3_origin, vec3_origin, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // in the ground, raise it up + end[2] -= NPC->mins[2] * (1.0f - trace.fraction) - 0.125f; } - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) return qtrue; - if ( trace.entityNum < ENTITYNUM_WORLD - && G_EntIsBreakable( trace.entityNum, NPC ) ) - {//breakable brush in our way, break it - // NPCInfo->blockedEntity = &g_entities[trace.entityNum]; + if (trace.entityNum < ENTITYNUM_WORLD && G_EntIsBreakable(trace.entityNum, NPC)) { // breakable brush in our way, break it + // NPCInfo->blockedEntity = &g_entities[trace.entityNum]; return qtrue; } - //Aw screw it, always try to go straight at him if we can at all - if ( trace.fraction >= 0.25f ) + // Aw screw it, always try to go straight at him if we can at all + if (trace.fraction >= 0.25f) return qtrue; - //FIXME: if something in the way that's not the world, set blocked ent + // FIXME: if something in the way that's not the world, set blocked ent return qfalse; } @@ -112,26 +104,21 @@ qboolean Rancor_CheckAhead( vec3_t end ) Rancor_Idle ------------------------- */ -void Rancor_Idle( void ) -{ +void Rancor_Idle(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - -qboolean Rancor_CheckRoar( gentity_t *self ) -{ - if ( !self->wait ) - {//haven't ever gotten mad yet - self->wait = 1;//do this only once - NPC_SetAnim( self, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( self, "rageTime", self->client->ps.legsAnimTimer ); +qboolean Rancor_CheckRoar(gentity_t *self) { + if (!self->wait) { // haven't ever gotten mad yet + self->wait = 1; // do this only once + NPC_SetAnim(self, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(self, "rageTime", self->client->ps.legsAnimTimer); return qtrue; } return qfalse; @@ -141,24 +128,21 @@ qboolean Rancor_CheckRoar( gentity_t *self ) Rancor_Patrol ------------------------- */ -void Rancor_Patrol( void ) -{ +void Rancor_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Rancor_Idle(); return; } - Rancor_CheckRoar( NPC ); - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); + Rancor_CheckRoar(NPC); + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(5000, 15000)); } /* @@ -166,25 +150,20 @@ void Rancor_Patrol( void ) Rancor_Move ------------------------- */ -void Rancor_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +void Rancor_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = NPC->maxs[0]+(MIN_DISTANCE*NPC->s.modelScale[0]); // just get us within combat range - //FIXME: for some reason, if NPC_MoveToGoal fails, it sets my angles to my lastPathAngles, which I don't want + NPCInfo->goalRadius = NPC->maxs[0] + (MIN_DISTANCE * NPC->s.modelScale[0]); // just get us within combat range + // FIXME: for some reason, if NPC_MoveToGoal fails, it sets my angles to my lastPathAngles, which I don't want float savYaw = NPCInfo->desiredYaw; - bool savWalking = !!(ucmd.buttons&BUTTON_WALKING); - if ( !NPC_MoveToGoal( qtrue ) ) - {//can't macro-nav, just head right for him - //FIXME: if something in the way that's not the world, set blocked ent + bool savWalking = !!(ucmd.buttons & BUTTON_WALKING); + if (!NPC_MoveToGoal(qtrue)) { // can't macro-nav, just head right for him + // FIXME: if something in the way that's not the world, set blocked ent vec3_t dest; - VectorCopy( NPCInfo->goalEntity->currentOrigin, dest ); - if ( Rancor_CheckAhead( dest ) ) - {//use our temp move straight to goal check - if (!savWalking) - { - ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() + VectorCopy(NPCInfo->goalEntity->currentOrigin, dest); + if (Rancor_CheckAhead(dest)) { // use our temp move straight to goal check + if (!savWalking) { + ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() } STEER::Activate(NPC); STEER::Seek(NPC, dest); @@ -214,29 +193,36 @@ void Rancor_Move( qboolean visible ) } } */ - } - else - {//all else fails, look at him - // gi.Printf("Fail\n"); + } else { // all else fails, look at him + // gi.Printf("Fail\n"); NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw = savYaw; - /* if ( !NPCInfo->blockedEntity ) - {//not already trying to break a breakable somewhere - if ( NPC->enemy && NPC->enemy->client && NPC->enemy->client->ps.groundEntityNum < ENTITYNUM_WORLD ) - {//hmm, maybe he's on a breakable brush? - if ( G_EntIsBreakable( NPC->enemy->client->ps.groundEntityNum, NPC ) ) - {//break it! - gentity_t *breakable = &g_entities[NPC->enemy->client->ps.groundEntityNum]; - int sanityCheck = 0; - //FiXME: and if he's on a stack of 3 breakables? - //FIXME: See if the breakable has a targetname, if so see if the thing targeting it is a breakable, if so, etc... - while ( sanityCheck < 20 && breakable && breakable->targetname ) - { - gentity_t *breakableNext = NULL; - while ( sanityCheck < 20 && (breakableNext = G_Find( breakableNext, FOFS(target), breakable->targetname )) != NULL ) + /* if ( !NPCInfo->blockedEntity ) + {//not already trying to break a breakable somewhere + if ( NPC->enemy && NPC->enemy->client && NPC->enemy->client->ps.groundEntityNum < ENTITYNUM_WORLD ) + {//hmm, maybe he's on a breakable brush? + if ( G_EntIsBreakable( NPC->enemy->client->ps.groundEntityNum, NPC ) ) + {//break it! + gentity_t *breakable = &g_entities[NPC->enemy->client->ps.groundEntityNum]; + int sanityCheck = 0; + //FiXME: and if he's on a stack of 3 breakables? + //FIXME: See if the breakable has a targetname, if so see if the thing targeting it is a breakable, if so, etc... + while ( sanityCheck < 20 && breakable && breakable->targetname ) { - if ( breakableNext && G_EntIsBreakable( breakableNext->s.number, NPC ) ) + gentity_t *breakableNext = NULL; + while ( sanityCheck < 20 && (breakableNext = G_Find( breakableNext, FOFS(target), breakable->targetname )) != NULL ) { - breakable = breakableNext; + if ( breakableNext && G_EntIsBreakable( breakableNext->s.number, NPC ) ) + { + breakable = breakableNext; + break; + } + else + { + sanityCheck++; + } + } + if ( !breakableNext ) + {//not targetted by another breakable that we can break break; } else @@ -244,62 +230,40 @@ void Rancor_Move( qboolean visible ) sanityCheck++; } } - if ( !breakableNext ) - {//not targetted by another breakable that we can break - break; - } - else - { - sanityCheck++; - } + NPCInfo->blockedEntity = breakable; } - NPCInfo->blockedEntity = breakable; } - } - }*/ - if ( !NPCInfo->blockedEntity && NPC->enemy && gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) - {//nothing to destroy? just go straight at goal dest + }*/ + if (!NPCInfo->blockedEntity && NPC->enemy && + gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) { // nothing to destroy? just go straight at goal dest qboolean horzClose = qfalse; - if (!savWalking) - { - ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() + if (!savWalking) { + ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() } - if ( DistanceHorizontal( NPC->enemy->currentOrigin, NPC->currentOrigin ) < (NPC->maxs[0]+(MIN_DISTANCE*NPC->s.modelScale[0])) ) - {//close, just look at him + if (DistanceHorizontal(NPC->enemy->currentOrigin, NPC->currentOrigin) < + (NPC->maxs[0] + (MIN_DISTANCE * NPC->s.modelScale[0]))) { // close, just look at him horzClose = qtrue; - NPC_FaceEnemy( qtrue ); - } - else - {//try to move towards him + NPC_FaceEnemy(qtrue); + } else { // try to move towards him STEER::Activate(NPC); STEER::Seek(NPC, dest); STEER::AvoidCollisions(NPC); STEER::DeActivate(NPC, &ucmd); } - //let him know he should attack at random out of frustration? - if ( NPCInfo->goalEntity == NPC->enemy ) - { - if ( TIMER_Done( NPC, "attacking" ) - && TIMER_Done( NPC, "frustrationAttack" ) ) - { - float enemyDist = Distance( dest, NPC->currentOrigin ); - if ( (!horzClose||!Q_irand(0,5)) - && Q_irand( 0, 1 ) ) - { - Rancor_Attack( enemyDist, qtrue, qfalse ); - } - else - { - Rancor_Attack( enemyDist, qfalse, qfalse ); + // let him know he should attack at random out of frustration? + if (NPCInfo->goalEntity == NPC->enemy) { + if (TIMER_Done(NPC, "attacking") && TIMER_Done(NPC, "frustrationAttack")) { + float enemyDist = Distance(dest, NPC->currentOrigin); + if ((!horzClose || !Q_irand(0, 5)) && Q_irand(0, 1)) { + Rancor_Attack(enemyDist, qtrue, qfalse); + } else { + Rancor_Attack(enemyDist, qfalse, qfalse); } - if ( horzClose ) - { - TIMER_Set( NPC, "frustrationAttack", Q_irand( 2000, 5000 ) ); - } - else - { - TIMER_Set( NPC, "frustrationAttack", Q_irand( 5000, 15000 ) ); + if (horzClose) { + TIMER_Set(NPC, "frustrationAttack", Q_irand(2000, 5000)); + } else { + TIMER_Set(NPC, "frustrationAttack", Q_irand(5000, 15000)); } } } @@ -310,147 +274,117 @@ void Rancor_Move( qboolean visible ) } //--------------------------------------------------------- -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ); -extern float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ); -extern int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); - -void Rancor_DropVictim( gentity_t *self ) -{ - //FIXME: if Rancor dies, it should drop its victim. - //FIXME: if Rancor is removed, it must remove its victim. - //FIXME: if in BOTH_HOLD_DROP, throw them a little, too? - if ( self->activator ) - { - if ( self->activator->client ) - { +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse); +extern float NPC_EntRangeFromBolt(gentity_t *targEnt, int boltIndex); +extern int NPC_GetEntsNearBolt(gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg); + +void Rancor_DropVictim(gentity_t *self) { + // FIXME: if Rancor dies, it should drop its victim. + // FIXME: if Rancor is removed, it must remove its victim. + // FIXME: if in BOTH_HOLD_DROP, throw them a little, too? + if (self->activator) { + if (self->activator->client) { self->activator->client->ps.eFlags &= ~EF_HELD_BY_RANCOR; } self->activator->activator = NULL; - if ( self->activator->health <= 0 ) - { - if ( self->activator->s.number ) - {//never free player - if ( self->count == 1 ) - {//in my hand, just drop them - if ( self->activator->client ) - { + if (self->activator->health <= 0) { + if (self->activator->s.number) { // never free player + if (self->count == 1) { // in my hand, just drop them + if (self->activator->client) { self->activator->client->ps.legsAnimTimer = self->activator->client->ps.torsoAnimTimer = 0; - //FIXME: ragdoll? + // FIXME: ragdoll? } + } else { + G_FreeEntity(self->activator); } - else - { - G_FreeEntity( self->activator ); - } - } - else - { + } else { self->activator->s.eFlags |= EF_NODRAW; - if ( self->activator->client ) - { + if (self->activator->client) { self->activator->client->ps.eFlags |= EF_NODRAW; } self->activator->clipmask &= ~CONTENTS_BODY; } - } - else - { - if ( self->activator->NPC ) - {//start thinking again + } else { + if (self->activator->NPC) { // start thinking again self->activator->NPC->nextBStateThink = level.time; } - //clear their anim and let them fall + // clear their anim and let them fall self->activator->client->ps.legsAnimTimer = self->activator->client->ps.torsoAnimTimer = 0; } - if ( self->enemy == self->activator ) - { + if (self->enemy == self->activator) { self->enemy = NULL; } - if ( self->activator->s.number == 0 ) - {//don't attack the player again for a bit - TIMER_Set( self, "attackDebounce", Q_irand( 2000, 4000+((2-g_spskill->integer)*2000) ) ); + if (self->activator->s.number == 0) { // don't attack the player again for a bit + TIMER_Set(self, "attackDebounce", Q_irand(2000, 4000 + ((2 - g_spskill->integer) * 2000))); } self->activator = NULL; } - self->count = 0;//drop him + self->count = 0; // drop him } -void Rancor_Swing( int boltIndex, qboolean tryGrab ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = (NPC->spawnflags&SPF_RANCOR_MUTANT)?200:88; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; - vec3_t originUp; +void Rancor_Swing(int boltIndex, qboolean tryGrab) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = (NPC->spawnflags & SPF_RANCOR_MUTANT) ? 200 : 88; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; + vec3_t originUp; VectorCopy(NPC->currentOrigin, originUp); - originUp[2] += (NPC->maxs[2]*0.75f); + originUp[2] += (NPC->maxs[2] * 0.75f); - numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, boltIndex, boltOrg ); + numEnts = NPC_GetEntsNearBolt(radiusEnts, radius, boltIndex, boltOrg); - //if ( NPCInfo->blockedEntity && G_EntIsBreakable( NPCInfo->blockedEntity->s.number, NPC ) ) - {//attacking a breakable brush - //HMM... maybe always do this? - //if boltOrg inside a breakable brush, damage it + // if ( NPCInfo->blockedEntity && G_EntIsBreakable( NPCInfo->blockedEntity->s.number, NPC ) ) + { // attacking a breakable brush + // HMM... maybe always do this? + // if boltOrg inside a breakable brush, damage it trace_t trace; - gi.trace( &trace, NPC->pos3, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->pos3, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); #ifndef FINAL_BUILD - if ( g_bobaDebug->integer > 0 ) - { + if (g_bobaDebug->integer > 0) { G_DebugLine(NPC->pos3, boltOrg, 1000, 0x000000ff, qtrue); } #endif - //remember pos3 for the trace from last hand pos to current hand pos next time - VectorCopy( boltOrg, NPC->pos3 ); - //FIXME: also do a trace TO the bolt from where we are...? - if ( G_EntIsBreakable( trace.entityNum, NPC ) ) - { - G_Damage( &g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 100, 0, MOD_MELEE ); - } - else - {//fuck, do an actual line trace, I guess... - gi.trace( &trace, originUp, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); + // remember pos3 for the trace from last hand pos to current hand pos next time + VectorCopy(boltOrg, NPC->pos3); + // FIXME: also do a trace TO the bolt from where we are...? + if (G_EntIsBreakable(trace.entityNum, NPC)) { + G_Damage(&g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 100, 0, MOD_MELEE); + } else { // fuck, do an actual line trace, I guess... + gi.trace(&trace, originUp, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); #ifndef FINAL_BUILD - if ( g_bobaDebug->integer > 0 ) - { + if (g_bobaDebug->integer > 0) { G_DebugLine(originUp, boltOrg, 1000, 0x000000ff, qtrue); } #endif - if ( G_EntIsBreakable( trace.entityNum, NPC ) ) - { - G_Damage( &g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE ); + if (G_EntIsBreakable(trace.entityNum, NPC)) { + G_Damage(&g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE); } } } - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the rancor ent + if (radiusEnts[i] == NPC) { // Skip the rancor ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client + if (radiusEnts[i]->client == NULL) { // must be a client continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) - ||(radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//can't be one already being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR) || (radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // can't be one already being + // held continue; } - if ( (radiusEnts[i]->s.eFlags&EF_NODRAW) ) - {//not if invisible + if ((radiusEnts[i]->s.eFlags & EF_NODRAW)) { // not if invisible continue; } /* @@ -460,10 +394,8 @@ void Rancor_Swing( int boltIndex, qboolean tryGrab ) } */ - if ( DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ) <= radiusSquared ) - { - if ( !gi.inPVS( radiusEnts[i]->currentOrigin, NPC->currentOrigin ) ) - {//don't grab anything that's in another PVS + if (DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg) <= radiusSquared) { + if (!gi.inPVS(radiusEnts[i]->currentOrigin, NPC->currentOrigin)) { // don't grab anything that's in another PVS continue; } /* @@ -476,51 +408,37 @@ void Rancor_Swing( int boltIndex, qboolean tryGrab ) skipGrab = qtrue; } */ - if ( tryGrab + if (tryGrab //&& !skipGrab - && NPC->count != 1 //don't have one in hand or in mouth already - FIXME: allow one in hand and any number in mouth! - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_GALAKMECH - && radiusEnts[i]->client->NPC_class != CLASS_ATST - && radiusEnts[i]->client->NPC_class != CLASS_GONK - && radiusEnts[i]->client->NPC_class != CLASS_R2D2 - && radiusEnts[i]->client->NPC_class != CLASS_R5D2 - && radiusEnts[i]->client->NPC_class != CLASS_MARK1 - && radiusEnts[i]->client->NPC_class != CLASS_MARK2 - && radiusEnts[i]->client->NPC_class != CLASS_MOUSE - && radiusEnts[i]->client->NPC_class != CLASS_PROBE - && radiusEnts[i]->client->NPC_class != CLASS_SEEKER - && radiusEnts[i]->client->NPC_class != CLASS_REMOTE - && radiusEnts[i]->client->NPC_class != CLASS_SENTRY - && radiusEnts[i]->client->NPC_class != CLASS_INTERROGATOR - && radiusEnts[i]->client->NPC_class != CLASS_VEHICLE ) - {//grab - if ( NPC->count == 2 ) - {//have one in my mouth, remove him - TIMER_Remove( NPC, "clearGrabbed" ); - Rancor_DropVictim( NPC ); + && NPC->count != 1 // don't have one in hand or in mouth already - FIXME: allow one in hand and any number in mouth! + && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && radiusEnts[i]->client->NPC_class != CLASS_GALAKMECH && + radiusEnts[i]->client->NPC_class != CLASS_ATST && radiusEnts[i]->client->NPC_class != CLASS_GONK && + radiusEnts[i]->client->NPC_class != CLASS_R2D2 && radiusEnts[i]->client->NPC_class != CLASS_R5D2 && + radiusEnts[i]->client->NPC_class != CLASS_MARK1 && radiusEnts[i]->client->NPC_class != CLASS_MARK2 && + radiusEnts[i]->client->NPC_class != CLASS_MOUSE && radiusEnts[i]->client->NPC_class != CLASS_PROBE && + radiusEnts[i]->client->NPC_class != CLASS_SEEKER && radiusEnts[i]->client->NPC_class != CLASS_REMOTE && + radiusEnts[i]->client->NPC_class != CLASS_SENTRY && radiusEnts[i]->client->NPC_class != CLASS_INTERROGATOR && + radiusEnts[i]->client->NPC_class != CLASS_VEHICLE) { // grab + if (NPC->count == 2) { // have one in my mouth, remove him + TIMER_Remove(NPC, "clearGrabbed"); + Rancor_DropVictim(NPC); } - NPC->enemy = radiusEnts[i];//make him my new best friend + NPC->enemy = radiusEnts[i]; // make him my new best friend radiusEnts[i]->client->ps.eFlags |= EF_HELD_BY_RANCOR; - //FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something + // FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something radiusEnts[i]->activator = NPC; // kind of dumb, but when we are locked to the Rancor, we are owned by it. - NPC->activator = radiusEnts[i];//remember him - NPC->count = 1;//in my hand - //wait to attack - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(500, 2500) ); - if ( radiusEnts[i]->health > 0 ) - {//do pain on enemy - GEntity_PainFunc( radiusEnts[i], NPC, NPC, radiusEnts[i]->currentOrigin, 0, MOD_CRUSH ); - } - else if ( radiusEnts[i]->client ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC->activator = radiusEnts[i]; // remember him + NPC->count = 1; // in my hand + // wait to attack + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(500, 2500)); + if (radiusEnts[i]->health > 0) { // do pain on enemy + GEntity_PainFunc(radiusEnts[i], NPC, NPC, radiusEnts[i]->currentOrigin, 0, MOD_CRUSH); + } else if (radiusEnts[i]->client) { + NPC_SetAnim(radiusEnts[i], SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - {//smack - G_Sound( radiusEnts[i], G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - //actually push the enemy + } else { // smack + G_Sound(radiusEnts[i], G_SoundIndex("sound/chars/rancor/swipehit.wav")); + // actually push the enemy vec3_t pushDir; /* //VectorSubtract( radiusEnts[i]->currentOrigin, boltOrg, pushDir ); @@ -528,24 +446,20 @@ void Rancor_Swing( int boltIndex, qboolean tryGrab ) pushDir[2] = Q_flrand( 100, 200 ); VectorNormalize( pushDir ); */ - if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && radiusEnts[i]->s.number >= MAX_CLIENTS ) - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, boltOrg, radiusEnts[i]->health+1000, (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_PROTECTION), MOD_MELEE ); + if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && radiusEnts[i]->s.number >= MAX_CLIENTS) { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, boltOrg, radiusEnts[i]->health + 1000, (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_PROTECTION), + MOD_MELEE); } vec3_t angs; - VectorCopy( NPC->client->ps.viewangles, angs ); - angs[YAW] += Q_flrand( 25, 50 ); - angs[PITCH] = Q_flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - if ( radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST - && !(radiusEnts[i]->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( radiusEnts[i], pushDir, 250 ); - if ( radiusEnts[i]->health > 0 ) - {//do pain on enemy - G_Knockdown( radiusEnts[i], NPC, pushDir, 100, qtrue ); + VectorCopy(NPC->client->ps.viewangles, angs); + angs[YAW] += Q_flrand(25, 50); + angs[PITCH] = Q_flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + if (radiusEnts[i]->client->NPC_class != CLASS_RANCOR && radiusEnts[i]->client->NPC_class != CLASS_ATST && + !(radiusEnts[i]->flags & FL_NO_KNOCKBACK)) { + G_Throw(radiusEnts[i], pushDir, 250); + if (radiusEnts[i]->health > 0) { // do pain on enemy + G_Knockdown(radiusEnts[i], NPC, pushDir, 100, qtrue); } } } @@ -553,125 +467,97 @@ void Rancor_Swing( int boltIndex, qboolean tryGrab ) } } -void Rancor_Smash( void ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = (NPC->spawnflags&SPF_RANCOR_MUTANT)?256:128; - const float halfRadSquared = ((radius/2)*(radius/2)); - const float radiusSquared = (radius*radius); - float distSq; - int i; - vec3_t boltOrg; - - AddSoundEvent( NPC, NPC->currentOrigin, 512, AEL_DANGER, qfalse, qtrue ); - - numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, NPC->handLBolt, boltOrg ); - - //if ( NPCInfo->blockedEntity && G_EntIsBreakable( NPCInfo->blockedEntity->s.number, NPC ) ) - {//attacking a breakable brush - //HMM... maybe always do this? - //if boltOrg inside a breakable brush, damage it +void Rancor_Smash(void) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = (NPC->spawnflags & SPF_RANCOR_MUTANT) ? 256 : 128; + const float halfRadSquared = ((radius / 2) * (radius / 2)); + const float radiusSquared = (radius * radius); + float distSq; + int i; + vec3_t boltOrg; + + AddSoundEvent(NPC, NPC->currentOrigin, 512, AEL_DANGER, qfalse, qtrue); + + numEnts = NPC_GetEntsNearBolt(radiusEnts, radius, NPC->handLBolt, boltOrg); + + // if ( NPCInfo->blockedEntity && G_EntIsBreakable( NPCInfo->blockedEntity->s.number, NPC ) ) + { // attacking a breakable brush + // HMM... maybe always do this? + // if boltOrg inside a breakable brush, damage it trace_t trace; - gi.trace( &trace, boltOrg, vec3_origin, vec3_origin, NPC->pos3, NPC->s.number, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); + gi.trace(&trace, boltOrg, vec3_origin, vec3_origin, NPC->pos3, NPC->s.number, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); #ifndef FINAL_BUILD - if ( g_bobaDebug->integer > 0 ) - { + if (g_bobaDebug->integer > 0) { G_DebugLine(NPC->pos3, boltOrg, 1000, 0x000000ff, qtrue); } #endif - //remember pos3 for the trace from last hand pos to current hand pos next time - VectorCopy( boltOrg, NPC->pos3 ); - //FIXME: also do a trace TO the bolt from where we are...? - if ( G_EntIsBreakable( trace.entityNum, NPC ) ) - { - G_Damage( &g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE ); - } - else - {//fuck, do an actual line trace, I guess... - gi.trace( &trace, NPC->currentOrigin, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); + // remember pos3 for the trace from last hand pos to current hand pos next time + VectorCopy(boltOrg, NPC->pos3); + // FIXME: also do a trace TO the bolt from where we are...? + if (G_EntIsBreakable(trace.entityNum, NPC)) { + G_Damage(&g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE); + } else { // fuck, do an actual line trace, I guess... + gi.trace(&trace, NPC->currentOrigin, vec3_origin, vec3_origin, boltOrg, NPC->s.number, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); #ifndef FINAL_BUILD - if ( g_bobaDebug->integer > 0 ) - { + if (g_bobaDebug->integer > 0) { G_DebugLine(NPC->currentOrigin, boltOrg, 1000, 0x000000ff, qtrue); } #endif - if ( G_EntIsBreakable( trace.entityNum, NPC ) ) - { - G_Damage( &g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE ); + if (G_EntIsBreakable(trace.entityNum, NPC)) { + G_Damage(&g_entities[trace.entityNum], NPC, NPC, vec3_origin, boltOrg, 200, 0, MOD_MELEE); } } } - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the rancor ent + if (radiusEnts[i] == NPC) { // Skip the rancor ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client - if ( G_EntIsBreakable( radiusEnts[i]->s.number, NPC ) ) - {//damage breakables within range, but not as much - if ( !Q_irand( 0, 1 ) ) - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, 100, 0, MOD_MELEE ); + if (radiusEnts[i]->client == NULL) { // must be a client + if (G_EntIsBreakable(radiusEnts[i]->s.number, NPC)) { // damage breakables within range, but not as much + if (!Q_irand(0, 1)) { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, 100, 0, MOD_MELEE); } } continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR)) { // can't be one being held continue; } - if ( (radiusEnts[i]->s.eFlags&EF_NODRAW) ) - {//not if invisible + if ((radiusEnts[i]->s.eFlags & EF_NODRAW)) { // not if invisible continue; } - distSq = DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ); - if ( distSq <= radiusSquared ) - { - if ( distSq < halfRadSquared ) - {//close enough to do damage, too - G_Sound( radiusEnts[i], G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && radiusEnts[i]->s.number >= MAX_CLIENTS ) - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, boltOrg, radiusEnts[i]->health+1000, (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_PROTECTION), MOD_MELEE ); - } - else if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) )//FIXME: a flag or something would be better - {//more damage - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand( 40, 55 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand( 10, 25 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + distSq = DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg); + if (distSq <= radiusSquared) { + if (distSq < halfRadSquared) { // close enough to do damage, too + G_Sound(radiusEnts[i], G_SoundIndex("sound/chars/rancor/swipehit.wav")); + if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && radiusEnts[i]->s.number >= MAX_CLIENTS) { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, boltOrg, radiusEnts[i]->health + 1000, (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_PROTECTION), + MOD_MELEE); + } else if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) // FIXME: a flag or something would be better + { // more damage + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand(40, 55), DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand(10, 25), DAMAGE_NO_KNOCKBACK, MOD_MELEE); } } - if ( radiusEnts[i]->health > 0 - && radiusEnts[i]->client - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST ) - { - if ( distSq < halfRadSquared - || radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//within range of my fist or withing ground-shaking range and not in the air - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) ) - { - G_Knockdown( radiusEnts[i], NPC, vec3_origin, 500, qtrue ); - } - else - { - G_Knockdown( radiusEnts[i], NPC, vec3_origin, Q_irand( 200, 350), qtrue ); + if (radiusEnts[i]->health > 0 && radiusEnts[i]->client && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && + radiusEnts[i]->client->NPC_class != CLASS_ATST) { + if (distSq < halfRadSquared || + radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_NONE) { // within range of my fist or withing ground-shaking range and not in the air + if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) { + G_Knockdown(radiusEnts[i], NPC, vec3_origin, 500, qtrue); + } else { + G_Knockdown(radiusEnts[i], NPC, vec3_origin, Q_irand(200, 350), qtrue); } } } @@ -679,352 +565,263 @@ void Rancor_Smash( void ) } } -void Rancor_Bite( void ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = 100; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; +void Rancor_Bite(void) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = 100; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; - numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, NPC->gutBolt, boltOrg ); + numEnts = NPC_GetEntsNearBolt(radiusEnts, radius, NPC->gutBolt, boltOrg); - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the rancor ent + if (radiusEnts[i] == NPC) { // Skip the rancor ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client + if (radiusEnts[i]->client == NULL) { // must be a client continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) ) - {//can't be one already being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR)) { // can't be one already being held continue; } - if ( (radiusEnts[i]->s.eFlags&EF_NODRAW) ) - {//not if invisible + if ((radiusEnts[i]->s.eFlags & EF_NODRAW)) { // not if invisible continue; } - if ( DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ) <= radiusSquared ) - { - if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && radiusEnts[i]->s.number >= MAX_CLIENTS ) - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, radiusEnts[i]->health+1000, (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_PROTECTION), MOD_MELEE ); - } - else if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) ) - {//more damage - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand( 35, 50 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else - { - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand( 15, 30 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg) <= radiusSquared) { + if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && radiusEnts[i]->s.number >= MAX_CLIENTS) { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, radiusEnts[i]->health + 1000, + (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_PROTECTION), MOD_MELEE); + } else if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) { // more damage + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand(35, 50), DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else { + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, Q_irand(15, 30), DAMAGE_NO_KNOCKBACK, MOD_MELEE); } - if ( radiusEnts[i]->health <= 0 && radiusEnts[i]->client ) - {//killed them, chance of dismembering - if ( !Q_irand( 0, 1 ) ) - {//bite something off + if (radiusEnts[i]->health <= 0 && radiusEnts[i]->client) { // killed them, chance of dismembering + if (!Q_irand(0, 1)) { // bite something off int hitLoc = HL_WAIST; - if ( g_dismemberment->integer < 3 ) - { - hitLoc = Q_irand( HL_BACK_RT, HL_HAND_LT ); - } - else - { - hitLoc = Q_irand( HL_WAIST, HL_HEAD ); + if (g_dismemberment->integer < 3) { + hitLoc = Q_irand(HL_BACK_RT, HL_HAND_LT); + } else { + hitLoc = Q_irand(HL_WAIST, HL_HEAD); } - if ( hitLoc == HL_HEAD ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else if ( hitLoc == HL_WAIST ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (hitLoc == HL_HEAD) { + NPC_SetAnim(radiusEnts[i], SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (hitLoc == HL_WAIST) { + NPC_SetAnim(radiusEnts[i], SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } radiusEnts[i]->client->dismembered = false; - //FIXME: the limb should just disappear, cuz I ate it - G_DoDismemberment( radiusEnts[i], radiusEnts[i]->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue ); + // FIXME: the limb should just disappear, cuz I ate it + G_DoDismemberment(radiusEnts[i], radiusEnts[i]->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue); } } - G_Sound( radiusEnts[i], G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); + G_Sound(radiusEnts[i], G_SoundIndex("sound/chars/rancor/chomp.wav")); } } } //------------------------------ -extern gentity_t *TossClientItems( gentity_t *self ); -void Rancor_Attack( float distance, qboolean doCharge, qboolean aimAtBlockedEntity ) -{ - if ( !TIMER_Exists( NPC, "attacking" ) - && TIMER_Done( NPC, "attackDebounce" ) ) - { - if ( NPC->count == 2 && NPC->activator ) - { - } - else if ( NPC->count == 1 && NPC->activator ) - {//holding enemy - if ( (!(NPC->spawnflags&SPF_RANCOR_FASTKILL) ||NPC->activator->s.numberactivator->health > 0 - && Q_irand( 0, 1 ) ) - {//quick bite - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 450 ); - } - else - {//full eat - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 900 ); - //Make victim scream in fright - if ( NPC->activator->health > 0 && NPC->activator->client ) - { - G_AddEvent( NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0 ); - NPC_SetAnim( NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - if ( NPC->activator->NPC ) - {//no more thinking for you - TossClientItems( NPC ); +extern gentity_t *TossClientItems(gentity_t *self); +void Rancor_Attack(float distance, qboolean doCharge, qboolean aimAtBlockedEntity) { + if (!TIMER_Exists(NPC, "attacking") && TIMER_Done(NPC, "attackDebounce")) { + if (NPC->count == 2 && NPC->activator) { + } else if (NPC->count == 1 && NPC->activator) { // holding enemy + if ((!(NPC->spawnflags & SPF_RANCOR_FASTKILL) || NPC->activator->s.number < MAX_CLIENTS) && NPC->activator->health > 0 && + Q_irand(0, 1)) { // quick bite + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 450); + } else { // full eat + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 900); + // Make victim scream in fright + if (NPC->activator->health > 0 && NPC->activator->client) { + G_AddEvent(NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0); + NPC_SetAnim(NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (NPC->activator->NPC) { // no more thinking for you + TossClientItems(NPC); NPC->activator->NPC->nextBStateThink = Q3_INFINITE; } } } - } - else if ( NPC->enemy->health > 0 && doCharge ) - {//charge - if ( !Q_irand( 0, 3 ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK5, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 1250 ); - if ( NPC->enemy && NPC->enemy->s.number == 0 ) - {//don't attack the player again for a bit - TIMER_Set( NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand( 2000, 4000+((2-g_spskill->integer)*2000) ) ); + } else if (NPC->enemy->health > 0 && doCharge) { // charge + if (!Q_irand(0, 3)) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK5, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 1250); + if (NPC->enemy && NPC->enemy->s.number == 0) { // don't attack the player again for a bit + TIMER_Set(NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand(2000, 4000 + ((2 - g_spskill->integer) * 2000))); } - } - else if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) ) - {//breath attack + } else if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) { // breath attack int breathAnim = BOTH_ATTACK4; gentity_t *checkEnt = NULL; - vec3_t center; - if ( NPC->enemy && NPC->enemy->inuse ) - { + vec3_t center; + if (NPC->enemy && NPC->enemy->inuse) { checkEnt = NPC->enemy; - VectorCopy( NPC->enemy->currentOrigin, center ); - } - else if ( NPCInfo->blockedEntity && NPCInfo->blockedEntity->inuse ) - { + VectorCopy(NPC->enemy->currentOrigin, center); + } else if (NPCInfo->blockedEntity && NPCInfo->blockedEntity->inuse) { checkEnt = NPCInfo->blockedEntity; - //if it has an origin brush, use it... - if ( VectorCompare( NPCInfo->blockedEntity->s.origin, vec3_origin ) ) - {//no origin brush, calc center - VectorAdd( NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center ); - VectorScale( center, 0.5f, center ); - } - else - {//use origin brush as center - VectorCopy( NPCInfo->blockedEntity->s.origin, center ); + // if it has an origin brush, use it... + if (VectorCompare(NPCInfo->blockedEntity->s.origin, vec3_origin)) { // no origin brush, calc center + VectorAdd(NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center); + VectorScale(center, 0.5f, center); + } else { // use origin brush as center + VectorCopy(NPCInfo->blockedEntity->s.origin, center); } } - if ( checkEnt ) - { - float zHeightRelative = center[2]-NPC->currentOrigin[2]; - if ( zHeightRelative >= (128.0f*NPC->s.modelScale[2]) ) - { + if (checkEnt) { + float zHeightRelative = center[2] - NPC->currentOrigin[2]; + if (zHeightRelative >= (128.0f * NPC->s.modelScale[2])) { breathAnim = BOTH_ATTACK7; - } - else if ( zHeightRelative >= (64.0f*NPC->s.modelScale[2]) ) - { + } else if (zHeightRelative >= (64.0f * NPC->s.modelScale[2])) { breathAnim = BOTH_ATTACK6; } } - NPC_SetAnim( NPC, SETANIM_BOTH, breathAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - //start effect here - G_PlayEffect( G_EffectIndex( "mrancor/breath" ), NPC->playerModel, NPC->gutBolt, NPC->s.number, NPC->currentOrigin, (NPC->client->ps.legsAnimTimer-500), qfalse ); - TIMER_Set( NPC, "breathAttack", NPC->client->ps.legsAnimTimer-500 ); - G_SoundOnEnt( NPC, CHAN_WEAPON, "sound/chars/rancor/breath_start.wav" ); - NPC->s.loopSound = G_SoundIndex( "sound/chars/rancor/breath_loop.wav" ); - if ( NPC->enemy && NPC->enemy->s.number == 0 ) - {//don't attack the player again for a bit - TIMER_Set( NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand( 2000, 4000+((2-g_spskill->integer)*2000) ) ); + NPC_SetAnim(NPC, SETANIM_BOTH, breathAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // start effect here + G_PlayEffect(G_EffectIndex("mrancor/breath"), NPC->playerModel, NPC->gutBolt, NPC->s.number, NPC->currentOrigin, + (NPC->client->ps.legsAnimTimer - 500), qfalse); + TIMER_Set(NPC, "breathAttack", NPC->client->ps.legsAnimTimer - 500); + G_SoundOnEnt(NPC, CHAN_WEAPON, "sound/chars/rancor/breath_start.wav"); + NPC->s.loopSound = G_SoundIndex("sound/chars/rancor/breath_loop.wav"); + if (NPC->enemy && NPC->enemy->s.number == 0) { // don't attack the player again for a bit + TIMER_Set(NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand(2000, 4000 + ((2 - g_spskill->integer) * 2000))); } - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 1250 ); - vec3_t fwd, yawAng ={0, NPC->client->ps.viewangles[YAW], 0}; - AngleVectors( yawAng, fwd, NULL, NULL ); - VectorScale( fwd, distance*1.5f, NPC->client->ps.velocity ); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 1250); + vec3_t fwd, yawAng = {0, NPC->client->ps.viewangles[YAW], 0}; + AngleVectors(yawAng, fwd, NULL, NULL); + VectorScale(fwd, distance * 1.5f, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 150; NPC->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( NPC->enemy && NPC->enemy->s.number == 0 ) - {//don't attack the player again for a bit - TIMER_Set( NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand( 2000, 4000+((2-g_spskill->integer)*2000) ) ); + if (NPC->enemy && NPC->enemy->s.number == 0) { // don't attack the player again for a bit + TIMER_Set(NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand(2000, 4000 + ((2 - g_spskill->integer) * 2000))); } } - } - else if ( !Q_irand(0, 1) - /*&& (NPC->spawnflags&SPF_RANCOR_MUTANT)*/ ) - {//mutant rancor can smash - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 900 ); - //init pos3 for the trace from last hand pos to current hand pos - VectorCopy( NPC->currentOrigin, NPC->pos3 ); - } - else if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) - || distance >= NPC->maxs[0]+(MIN_DISTANCE*NPC->s.modelScale[0])-64.0f ) - {//try to grab + } else if (!Q_irand(0, 1) + /*&& (NPC->spawnflags&SPF_RANCOR_MUTANT)*/) { // mutant rancor can smash + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 900); + // init pos3 for the trace from last hand pos to current hand pos + VectorCopy(NPC->currentOrigin, NPC->pos3); + } else if ((NPC->spawnflags & SPF_RANCOR_MUTANT) || distance >= NPC->maxs[0] + (MIN_DISTANCE * NPC->s.modelScale[0]) - 64.0f) { // try to grab int grabAnim = BOTH_ATTACK2; gentity_t *checkEnt = NULL; - vec3_t center; - if ( (!aimAtBlockedEntity||!NPCInfo->blockedEntity) && NPC->enemy && NPC->enemy->inuse ) - { + vec3_t center; + if ((!aimAtBlockedEntity || !NPCInfo->blockedEntity) && NPC->enemy && NPC->enemy->inuse) { checkEnt = NPC->enemy; - VectorCopy( NPC->enemy->currentOrigin, center ); - } - else if ( NPCInfo->blockedEntity && NPCInfo->blockedEntity->inuse ) - { + VectorCopy(NPC->enemy->currentOrigin, center); + } else if (NPCInfo->blockedEntity && NPCInfo->blockedEntity->inuse) { checkEnt = NPCInfo->blockedEntity; - //if it has an origin brush, use it... - if ( VectorCompare( NPCInfo->blockedEntity->s.origin, vec3_origin ) ) - {//no origin brush, calc center - VectorAdd( NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center ); - VectorScale( center, 0.5f, center ); - } - else - {//use origin brush as center - VectorCopy( NPCInfo->blockedEntity->s.origin, center ); + // if it has an origin brush, use it... + if (VectorCompare(NPCInfo->blockedEntity->s.origin, vec3_origin)) { // no origin brush, calc center + VectorAdd(NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center); + VectorScale(center, 0.5f, center); + } else { // use origin brush as center + VectorCopy(NPCInfo->blockedEntity->s.origin, center); } } - if ( checkEnt ) - { - float zHeightRelative = center[2]-NPC->currentOrigin[2]; - if ( zHeightRelative >= (128.0f*NPC->s.modelScale[2]) ) - { + if (checkEnt) { + float zHeightRelative = center[2] - NPC->currentOrigin[2]; + if (zHeightRelative >= (128.0f * NPC->s.modelScale[2])) { grabAnim = BOTH_ATTACK11; - } - else if ( zHeightRelative >= (64.0f*NPC->s.modelScale[2]) ) - { + } else if (zHeightRelative >= (64.0f * NPC->s.modelScale[2])) { grabAnim = BOTH_ATTACK10; } } - NPC_SetAnim( NPC, SETANIM_BOTH, grabAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 800 ); - if ( NPC->enemy && NPC->enemy->s.number == 0 ) - {//don't attack the player again for a bit - TIMER_Set( NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand( 2000, 4000+((2-g_spskill->integer)*2000) ) ); + NPC_SetAnim(NPC, SETANIM_BOTH, grabAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 800); + if (NPC->enemy && NPC->enemy->s.number == 0) { // don't attack the player again for a bit + TIMER_Set(NPC, "attackDebounce", NPC->client->ps.legsAnimTimer + Q_irand(2000, 4000 + ((2 - g_spskill->integer) * 2000))); } - //init pos3 for the trace from last hand pos to current hand pos - VectorCopy( NPC->currentOrigin, NPC->pos3 ); - } - else - { - //FIXME: back up? + // init pos3 for the trace from last hand pos to current hand pos + VectorCopy(NPC->currentOrigin, NPC->pos3); + } else { + // FIXME: back up? ucmd.forwardmove = -64; - //FIXME: check for walls/ledges? + // FIXME: check for walls/ledges? return; } - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_flrand(0.0f, 1.0f) * 200 ); + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_flrand(0.0f, 1.0f) * 200); } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks float playerDist; - if ( TIMER_Done2( NPC, "attack_dmg", qtrue ) ) - { - switch ( NPC->client->ps.legsAnim ) - { + if (TIMER_Done2(NPC, "attack_dmg", qtrue)) { + switch (NPC->client->ps.legsAnim) { case BOTH_MELEE1: Rancor_Smash(); - playerDist = NPC_EntRangeFromBolt( player, NPC->handLBolt ); - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) ) - { - if ( playerDist < 512 ) - { - CGCam_Shake( 1.0f*playerDist/256, 1000 ); + playerDist = NPC_EntRangeFromBolt(player, NPC->handLBolt); + if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) { + if (playerDist < 512) { + CGCam_Shake(1.0f * playerDist / 256, 1000); } - } - else - { - if ( playerDist < 256 ) - { - CGCam_Shake( 1.0f*playerDist/128.0f, 1000 ); + } else { + if (playerDist < 256) { + CGCam_Shake(1.0f * playerDist / 128.0f, 1000); } } break; case BOTH_MELEE2: Rancor_Bite(); - TIMER_Set( NPC, "attack_dmg2", 450 ); + TIMER_Set(NPC, "attack_dmg2", 450); break; case BOTH_ATTACK1: - if ( NPC->count == 1 && NPC->activator ) - { - if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && NPC->activator->s.number >= MAX_CLIENTS ) - { - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->activator->health+1000, (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_PROTECTION), MOD_MELEE ); - } - else if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) )//FIXME: a flag or something would be better - {//more damage - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand( 55, 70 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else - { - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand( 25, 40 ), DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (NPC->count == 1 && NPC->activator) { + if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && NPC->activator->s.number >= MAX_CLIENTS) { + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->activator->health + 1000, + (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_PROTECTION), MOD_MELEE); + } else if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) // FIXME: a flag or something would be better + { // more damage + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand(55, 70), DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else { + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand(25, 40), DAMAGE_NO_KNOCKBACK, MOD_MELEE); } - if ( NPC->activator->health <= 0 ) - {//killed him - if ( g_dismemberment->integer >= 3 ) - {//make it look like we bit his head off + if (NPC->activator->health <= 0) { // killed him + if (g_dismemberment->integer >= 3) { // make it look like we bit his head off NPC->activator->client->dismembered = false; - G_DoDismemberment( NPC->activator, NPC->activator->currentOrigin, MOD_SABER, 1000, HL_HEAD, qtrue ); + G_DoDismemberment(NPC->activator, NPC->activator->currentOrigin, MOD_SABER, 1000, HL_HEAD, qtrue); } - NPC_SetAnim( NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - G_Sound( NPC->activator, G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); + G_Sound(NPC->activator, G_SoundIndex("sound/chars/rancor/chomp.wav")); } break; case BOTH_ATTACK2: case BOTH_ATTACK10: case BOTH_ATTACK11: - //try to grab - Rancor_Swing( NPC->handRBolt, qtrue ); + // try to grab + Rancor_Swing(NPC->handRBolt, qtrue); break; case BOTH_ATTACK3: - if ( NPC->count == 1 && NPC->activator ) - { - //cut in half - if ( NPC->activator->client ) - { + if (NPC->count == 1 && NPC->activator) { + // cut in half + if (NPC->activator->client) { NPC->activator->client->dismembered = false; - G_DoDismemberment( NPC->activator, NPC->enemy->currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); + G_DoDismemberment(NPC->activator, NPC->enemy->currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue); } - //KILL - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->enemy->health+1000, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_MELEE, HL_NONE ); - if ( NPC->activator->client ) - { - NPC_SetAnim( NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + // KILL + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->enemy->health + 1000, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_MELEE, HL_NONE); + if (NPC->activator->client) { + NPC_SetAnim(NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( NPC, "attack_dmg2", 1350 ); - G_Sound( NPC->activator, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - G_AddEvent( NPC->activator, EV_JUMP, NPC->activator->health ); + TIMER_Set(NPC, "attack_dmg2", 1350); + G_Sound(NPC->activator, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + G_AddEvent(NPC->activator, EV_JUMP, NPC->activator->health); } break; } - } - else if ( TIMER_Done2( NPC, "attack_dmg2", qtrue ) ) - { - switch ( NPC->client->ps.legsAnim ) - { + } else if (TIMER_Done2(NPC, "attack_dmg2", qtrue)) { + switch (NPC->client->ps.legsAnim) { case BOTH_MELEE1: break; case BOTH_MELEE2: @@ -1035,120 +832,89 @@ void Rancor_Attack( float distance, qboolean doCharge, qboolean aimAtBlockedEnti case BOTH_ATTACK2: break; case BOTH_ATTACK3: - if ( NPC->count == 1 && NPC->activator ) - {//swallow victim - G_Sound( NPC->activator, G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); - //FIXME: sometimes end up with a live one in our mouths? - //just make sure they're dead - if ( NPC->activator->health > 0 ) - { - //cut in half + if (NPC->count == 1 && NPC->activator) { // swallow victim + G_Sound(NPC->activator, G_SoundIndex("sound/chars/rancor/chomp.wav")); + // FIXME: sometimes end up with a live one in our mouths? + // just make sure they're dead + if (NPC->activator->health > 0) { + // cut in half NPC->activator->client->dismembered = false; - G_DoDismemberment( NPC->activator, NPC->enemy->currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); - //KILL - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->enemy->health+1000, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_MELEE, HL_NONE ); - NPC_SetAnim( NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - G_AddEvent( NPC->activator, EV_JUMP, NPC->activator->health ); + G_DoDismemberment(NPC->activator, NPC->enemy->currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue); + // KILL + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, NPC->enemy->health + 1000, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_MELEE, HL_NONE); + NPC_SetAnim(NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(NPC->activator, EV_JUMP, NPC->activator->health); } NPC->count = 2; - TIMER_Set( NPC, "clearGrabbed", 2600 ); + TIMER_Set(NPC, "clearGrabbed", 2600); } break; } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); } //---------------------------------- -void Rancor_Combat( void ) -{ - if ( NPC->count ) - {//holding my enemy +void Rancor_Combat(void) { + if (NPC->count) { // holding my enemy NPCInfo->enemyLastSeenTime = level.time; - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; - } - else if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && NPC->activator - && NPC->activator->s.number >= MAX_CLIENTS ) - { - Rancor_Attack( 0, qfalse, qfalse ); - } - else if ( NPC->useDebounceTime >= level.time - && NPC->activator ) - {//just sniffing the guy - if ( NPC->useDebounceTime <= level.time + 100 - && NPC->client->ps.legsAnim != BOTH_HOLD_DROP) - {//just about done, drop him - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer+(Q_irand(500,1000)*(3-g_spskill->integer)) ); + } else if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && NPC->activator && NPC->activator->s.number >= MAX_CLIENTS) { + Rancor_Attack(0, qfalse, qfalse); + } else if (NPC->useDebounceTime >= level.time && NPC->activator) { // just sniffing the guy + if (NPC->useDebounceTime <= level.time + 100 && NPC->client->ps.legsAnim != BOTH_HOLD_DROP) { // just about done, drop him + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + (Q_irand(500, 1000) * (3 - g_spskill->integer))); } - } - else - { - if ( !NPC->useDebounceTime - && NPC->activator - && NPC->activator->s.number < MAX_CLIENTS ) - {//first time I pick the player, just sniff them - if ( TIMER_Done(NPC,"attacking") ) - {//ready to attack - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_SNIFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC->useDebounceTime = level.time + NPC->client->ps.legsAnimTimer + Q_irand( 500, 2000 ); + } else { + if (!NPC->useDebounceTime && NPC->activator && NPC->activator->s.number < MAX_CLIENTS) { // first time I pick the player, just sniff them + if (TIMER_Done(NPC, "attacking")) { // ready to attack + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_SNIFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC->useDebounceTime = level.time + NPC->client->ps.legsAnimTimer + Q_irand(500, 2000); } - } - else - { - Rancor_Attack( 0, qfalse, qfalse ); + } else { + Rancor_Attack(0, qfalse, qfalse); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - NPCInfo->goalRadius = NPC->maxs[0]+(MAX_DISTANCE*NPC->s.modelScale[0]); // just get us within combat range + NPCInfo->goalRadius = NPC->maxs[0] + (MAX_DISTANCE * NPC->s.modelScale[0]); // just get us within combat range // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS(NPC->enemy) || UpdateGoal()) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = NPC->enemy; - Rancor_Move( qfalse ); + Rancor_Move(qfalse); return; } NPCInfo->enemyLastSeenTime = level.time; // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - float distance = Distance( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = Distance(NPC->currentOrigin, NPC->enemy->currentOrigin); - qboolean advance = (qboolean)( distance > (NPC->maxs[0]+(MIN_DISTANCE*NPC->s.modelScale[0])) ? qtrue : qfalse ); - qboolean doCharge = qfalse; + qboolean advance = (qboolean)(distance > (NPC->maxs[0] + (MIN_DISTANCE * NPC->s.modelScale[0])) ? qtrue : qfalse); + qboolean doCharge = qfalse; - if ( advance ) - {//have to get closer - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) - && (!NPC->enemy||!NPC->enemy->client) ) - {//don't do breath attack vs. bbrushes - } - else - { - vec3_t yawOnlyAngles = {0, NPC->currentAngles[YAW], 0}; - if ( NPC->enemy->health > 0 - && fabs(distance-(250.0f*NPC->s.modelScale[0])) <= (80.0f*NPC->s.modelScale[0]) - && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, yawOnlyAngles, 30, 30 ) ) - { + if (advance) { // have to get closer + if ((NPC->spawnflags & SPF_RANCOR_MUTANT) && (!NPC->enemy || !NPC->enemy->client)) { // don't do breath attack vs. bbrushes + } else { + vec3_t yawOnlyAngles = {0, NPC->currentAngles[YAW], 0}; + if (NPC->enemy->health > 0 && fabs(distance - (250.0f * NPC->s.modelScale[0])) <= (80.0f * NPC->s.modelScale[0]) && + InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, yawOnlyAngles, 30, 30)) { int chance = 9; - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) ) - {//higher chance of doing breath attack - chance = 5-g_spskill->integer; + if ((NPC->spawnflags & SPF_RANCOR_MUTANT)) { // higher chance of doing breath attack + chance = 5 - g_spskill->integer; } - if ( !Q_irand( 0, chance ) ) - {//go for the charge + if (!Q_irand(0, chance)) { // go for the charge doCharge = qtrue; advance = qfalse; } @@ -1156,20 +922,15 @@ void Rancor_Combat( void ) } } - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else { + Rancor_Move(qtrue); } - else - { - Rancor_Move( qtrue ); - } - } - else - { - Rancor_Attack( distance, doCharge, qfalse ); + } else { + Rancor_Attack(distance, doCharge, qfalse); } } @@ -1178,97 +939,75 @@ void Rancor_Combat( void ) NPC_Rancor_Pain ------------------------- */ -void NPC_Rancor_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_Rancor_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { qboolean hitByRancor = qfalse; - if ( self->NPC && self->NPC->ignorePain ) - { + if (self->NPC && self->NPC->ignorePain) { return; } - if ( !TIMER_Done( self, "breathAttack" ) ) - {//nothing interrupts breath attack + if (!TIMER_Done(self, "breathAttack")) { // nothing interrupts breath attack return; } - TIMER_Remove( self, "confusionTime" ); + TIMER_Remove(self, "confusionTime"); - if ( other&&other->client&&other->client->NPC_class==CLASS_RANCOR ) - { + if (other && other->client && other->client->NPC_class == CLASS_RANCOR) { hitByRancor = qtrue; } - if ( other - && other->inuse - && other != self->enemy - && !(other->flags&FL_NOTARGET) ) - { - if ( !self->count ) - { - if ( (!other->s.number&&!Q_irand(0,3)) - || !self->enemy - || self->enemy->health == 0 - || (self->enemy->client&&self->enemy->client->NPC_class == CLASS_RANCOR) - || (!Q_irand(0, 4 ) && DistanceSquared( other->currentOrigin, self->currentOrigin ) < DistanceSquared( self->enemy->currentOrigin, self->currentOrigin )) ) - {//if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker - //FIXME: if can't nav to my enemy, take this guy if I can nav to him + if (other && other->inuse && other != self->enemy && !(other->flags & FL_NOTARGET)) { + if (!self->count) { + if ((!other->s.number && !Q_irand(0, 3)) || !self->enemy || self->enemy->health == 0 || + (self->enemy->client && self->enemy->client->NPC_class == CLASS_RANCOR) || + (!Q_irand(0, 4) && + DistanceSquared(other->currentOrigin, self->currentOrigin) < + DistanceSquared( + self->enemy->currentOrigin, + self->currentOrigin))) { // if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker + // FIXME: if can't nav to my enemy, take this guy if I can nav to him self->lastEnemy = self->enemy; - G_SetEnemy( self, other ); - if ( self->enemy != self->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(self, other); + if (self->enemy != self->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up self->useDebounceTime = 0; } - TIMER_Set( self, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - if ( hitByRancor ) - {//stay mad at this Rancor for 2-5 secs before looking for other enemies - TIMER_Set( self, "rancorInfight", Q_irand( 2000, 5000 ) ); + TIMER_Set(self, "lookForNewEnemy", Q_irand(5000, 15000)); + if (hitByRancor) { // stay mad at this Rancor for 2-5 secs before looking for other enemies + TIMER_Set(self, "rancorInfight", Q_irand(2000, 5000)); } - } } } - if ( (hitByRancor|| (self->count==1&&self->activator&&!Q_irand(0,4)) || Q_irand( 0, 200 ) < damage )//hit by rancor, hit while holding live victim, or took a lot of damage - && self->client->ps.legsAnim != BOTH_STAND1TO2 - && TIMER_Done( self, "takingPain" ) ) - { - if ( !Rancor_CheckRoar( self ) ) - { - if ( self->client->ps.legsAnim != BOTH_MELEE1 - && self->client->ps.legsAnim != BOTH_MELEE2 - && self->client->ps.legsAnim != BOTH_ATTACK2 - && self->client->ps.legsAnim != BOTH_ATTACK10 - && self->client->ps.legsAnim != BOTH_ATTACK11 ) - {//cant interrupt one of the big attack anims + if ((hitByRancor || (self->count == 1 && self->activator && !Q_irand(0, 4)) || + Q_irand(0, 200) < damage) // hit by rancor, hit while holding live victim, or took a lot of damage + && self->client->ps.legsAnim != BOTH_STAND1TO2 && TIMER_Done(self, "takingPain")) { + if (!Rancor_CheckRoar(self)) { + if (self->client->ps.legsAnim != BOTH_MELEE1 && self->client->ps.legsAnim != BOTH_MELEE2 && self->client->ps.legsAnim != BOTH_ATTACK2 && + self->client->ps.legsAnim != BOTH_ATTACK10 && self->client->ps.legsAnim != BOTH_ATTACK11) { // cant interrupt one of the big attack anims /* if ( self->count != 1 || other == self->activator || (self->client->ps.legsAnim != BOTH_ATTACK1&&self->client->ps.legsAnim != BOTH_ATTACK3) ) */ - {//if going to bite our victim, only victim can interrupt that anim - if ( self->health > 100 || hitByRancor ) - { - TIMER_Remove( self, "attacking" ); + { // if going to bite our victim, only victim can interrupt that anim + if (self->health > 100 || hitByRancor) { + TIMER_Remove(self, "attacking"); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->count == 1 ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (self->count == 1) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( self, "takingPain", self->client->ps.legsAnimTimer+Q_irand(0, 500*(2-g_spskill->integer)) ); + TIMER_Set(self, "takingPain", self->client->ps.legsAnimTimer + Q_irand(0, 500 * (2 - g_spskill->integer))); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } } } - //let go + // let go /* if ( !Q_irand( 0, 3 ) && self->count == 1 ) { @@ -1278,70 +1017,59 @@ void NPC_Rancor_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, c } } -void Rancor_CheckDropVictim( void ) -{ - if ( (NPC->spawnflags&SPF_RANCOR_FASTKILL) - && NPC->activator->s.number >= MAX_CLIENTS ) - { +void Rancor_CheckDropVictim(void) { + if ((NPC->spawnflags & SPF_RANCOR_FASTKILL) && NPC->activator->s.number >= MAX_CLIENTS) { return; } - vec3_t mins={NPC->activator->mins[0]-1,NPC->activator->mins[1]-1,0}; - vec3_t maxs={NPC->activator->maxs[0]+1,NPC->activator->maxs[1]+1,1}; - vec3_t start={NPC->activator->currentOrigin[0],NPC->activator->currentOrigin[1],NPC->activator->absmin[2]}; - vec3_t end={NPC->activator->currentOrigin[0],NPC->activator->currentOrigin[1],NPC->activator->absmax[2]-1}; - trace_t trace; - gi.trace( &trace, start, mins, maxs, end, NPC->activator->s.number, NPC->activator->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f ) - { - Rancor_DropVictim( NPC ); + vec3_t mins = {NPC->activator->mins[0] - 1, NPC->activator->mins[1] - 1, 0}; + vec3_t maxs = {NPC->activator->maxs[0] + 1, NPC->activator->maxs[1] + 1, 1}; + vec3_t start = {NPC->activator->currentOrigin[0], NPC->activator->currentOrigin[1], NPC->activator->absmin[2]}; + vec3_t end = {NPC->activator->currentOrigin[0], NPC->activator->currentOrigin[1], NPC->activator->absmax[2] - 1}; + trace_t trace; + gi.trace(&trace, start, mins, maxs, end, NPC->activator->s.number, NPC->activator->clipmask, (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f) { + Rancor_DropVictim(NPC); } } -qboolean Rancor_AttackBBrush( void ) -{ - trace_t trace; +qboolean Rancor_AttackBBrush(void) { + trace_t trace; vec3_t center; vec3_t dir2Brush, end; - float checkDist = 64.0f;//32.0f; + float checkDist = 64.0f; // 32.0f; - if ( VectorCompare( NPCInfo->blockedEntity->s.origin, vec3_origin ) ) - {//no origin brush, calc center - VectorAdd( NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center ); - VectorScale( center, 0.5f, center ); - } - else - { - VectorCopy( NPCInfo->blockedEntity->s.origin, center ); + if (VectorCompare(NPCInfo->blockedEntity->s.origin, vec3_origin)) { // no origin brush, calc center + VectorAdd(NPCInfo->blockedEntity->mins, NPCInfo->blockedEntity->maxs, center); + VectorScale(center, 0.5f, center); + } else { + VectorCopy(NPCInfo->blockedEntity->s.origin, center); } - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( NPC->currentOrigin, center, EDGE_IMPACT_POSSIBLE ); + if (NAVDEBUG_showCollision) { + CG_DrawEdge(NPC->currentOrigin, center, EDGE_IMPACT_POSSIBLE); } - center[2] = NPC->currentOrigin[2];//we can't fly, so let's ignore z diff - NPC_FacePosition( center, qfalse ); - //see if we're close to it - VectorSubtract( center, NPC->currentOrigin, dir2Brush ); - float brushSize = ((NPCInfo->blockedEntity->maxs[0] - NPCInfo->blockedEntity->mins[0])*0.5f+(NPCInfo->blockedEntity->maxs[1] - NPCInfo->blockedEntity->mins[1])*0.5f) * 0.5f; - float dist2Brush = VectorNormalize( dir2Brush )-(NPC->maxs[0])-brushSize; - if ( dist2Brush < (MIN_DISTANCE*NPC->s.modelScale[0]) ) - {//close enough to just hit it + center[2] = NPC->currentOrigin[2]; // we can't fly, so let's ignore z diff + NPC_FacePosition(center, qfalse); + // see if we're close to it + VectorSubtract(center, NPC->currentOrigin, dir2Brush); + float brushSize = ((NPCInfo->blockedEntity->maxs[0] - NPCInfo->blockedEntity->mins[0]) * 0.5f + + (NPCInfo->blockedEntity->maxs[1] - NPCInfo->blockedEntity->mins[1]) * 0.5f) * + 0.5f; + float dist2Brush = VectorNormalize(dir2Brush) - (NPC->maxs[0]) - brushSize; + if (dist2Brush < (MIN_DISTANCE * NPC->s.modelScale[0])) { // close enough to just hit it trace.fraction = 0.0f; trace.entityNum = NPCInfo->blockedEntity->s.number; - } - else - { - VectorMA( NPC->currentOrigin, checkDist, dir2Brush, end ); - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//wtf? + } else { + VectorMA(NPC->currentOrigin, checkDist, dir2Brush, end); + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid) { // wtf? NPCInfo->blockedEntity = NULL; return qfalse; } } - if ( trace.fraction >= 1.0f //too far away - || trace.entityNum != NPCInfo->blockedEntity->s.number )//OR blocked by something else - {//keep moving towards it - ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() + if (trace.fraction >= 1.0f // too far away + || trace.entityNum != NPCInfo->blockedEntity->s.number) // OR blocked by something else + { // keep moving towards it + ucmd.buttons &= ~BUTTON_WALKING; // Unset from MoveToGoal() STEER::Activate(NPC); STEER::Seek(NPC, center); STEER::AvoidCollisions(NPC); @@ -1354,30 +1082,24 @@ qboolean Rancor_AttackBBrush( void ) ucmd.buttons |= BUTTON_WALKING; } */ - //NPCInfo->enemyLastSeenTime = level.time; - //let the function that called us know that we called NAV ourselves - } - else if ( trace.entityNum == NPCInfo->blockedEntity->s.number ) - {//close enough, smash it! - Rancor_Attack( (trace.fraction*checkDist), qfalse, qtrue );//FIXME: maybe charge at it, smash through? - TIMER_Remove( NPC, "attackDebounce" );//don't wait on these + // NPCInfo->enemyLastSeenTime = level.time; + // let the function that called us know that we called NAV ourselves + } else if (trace.entityNum == NPCInfo->blockedEntity->s.number) { // close enough, smash it! + Rancor_Attack((trace.fraction * checkDist), qfalse, qtrue); // FIXME: maybe charge at it, smash through? + TIMER_Remove(NPC, "attackDebounce"); // don't wait on these NPCInfo->enemyLastSeenTime = level.time; - } - else - { - //Com_Printf( S_COLOR_RED"RANCOR cannot reach intended breakable %s, blocked by %s\n", NPC->blockedEntity->targetname, g_entities[trace.entityNum].classname ); - if ( G_EntIsBreakable( trace.entityNum, NPC ) ) - {//oh, well, smash that, then - //G_SetEnemy( NPC, &g_entities[trace.entityNum] ); - gentity_t* prevblockedEnt = NPCInfo->blockedEntity; + } else { + // Com_Printf( S_COLOR_RED"RANCOR cannot reach intended breakable %s, blocked by %s\n", NPC->blockedEntity->targetname, + // g_entities[trace.entityNum].classname ); + if (G_EntIsBreakable(trace.entityNum, NPC)) { // oh, well, smash that, then + // G_SetEnemy( NPC, &g_entities[trace.entityNum] ); + gentity_t *prevblockedEnt = NPCInfo->blockedEntity; NPCInfo->blockedEntity = &g_entities[trace.entityNum]; - Rancor_Attack( (trace.fraction*checkDist), qfalse, qtrue );//FIXME: maybe charge at it, smash through? - TIMER_Remove( NPC, "attackDebounce" );//don't wait on these + Rancor_Attack((trace.fraction * checkDist), qfalse, qtrue); // FIXME: maybe charge at it, smash through? + TIMER_Remove(NPC, "attackDebounce"); // don't wait on these NPCInfo->enemyLastSeenTime = level.time; NPCInfo->blockedEntity = prevblockedEnt; - } - else - { + } else { NPCInfo->blockedEntity = NULL; return qfalse; } @@ -1385,69 +1107,49 @@ qboolean Rancor_AttackBBrush( void ) return qtrue; } -void Rancor_FireBreathAttack( void ) -{ - int damage = Q_irand( 10, 15 ); - trace_t tr; - gentity_t *traceEnt = NULL; - mdxaBone_t boltMatrix; - vec3_t start, end, dir, traceMins = {-4, -4, -4}, traceMaxs = {4, 4, 4}; - vec3_t rancAngles = {0,NPC->client->ps.viewangles[YAW],0}; +void Rancor_FireBreathAttack(void) { + int damage = Q_irand(10, 15); + trace_t tr; + gentity_t *traceEnt = NULL; + mdxaBone_t boltMatrix; + vec3_t start, end, dir, traceMins = {-4, -4, -4}, traceMaxs = {4, 4, 4}; + vec3_t rancAngles = {0, NPC->client->ps.viewangles[YAW], 0}; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, NPC->gutBolt, - &boltMatrix, rancAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->gutBolt, &boltMatrix, rancAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, start ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, dir ); - VectorMA( start, 512, dir, end ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, start); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, dir); + VectorMA(start, 512, dir, end); - gi.trace( &tr, start, traceMins, traceMaxs, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, start, traceMins, traceMaxs, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); traceEnt = &g_entities[tr.entityNum]; - if ( tr.entityNum < ENTITYNUM_WORLD - && traceEnt->takedamage - && traceEnt->client ) - {//breath attack only does damage to living things - G_Damage( traceEnt, NPC, NPC, dir, tr.endpos, damage*2, DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC|DAMAGE_IGNORE_TEAM, MOD_LAVA, HL_NONE ); + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage && traceEnt->client) { // breath attack only does damage to living things + G_Damage(traceEnt, NPC, NPC, dir, tr.endpos, damage * 2, DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC | DAMAGE_IGNORE_TEAM, MOD_LAVA, + HL_NONE); } - if ( tr.fraction < 1.0f ) - {//hit something, do radius damage - G_RadiusDamage( tr.endpos, NPC, damage, 250, NPC, MOD_LAVA ); + if (tr.fraction < 1.0f) { // hit something, do radius damage + G_RadiusDamage(tr.endpos, NPC, damage, 250, NPC, MOD_LAVA); } } -void Rancor_CheckAnimDamage( void ) -{ - if ( NPC->client->ps.legsAnim == BOTH_ATTACK2 - || NPC->client->ps.legsAnim == BOTH_ATTACK10 - || NPC->client->ps.legsAnim == BOTH_ATTACK11 ) - { - if ( NPC->client->ps.legsAnimTimer >= 1200 && NPC->client->ps.legsAnimTimer <= 1350 ) - { - if ( Q_irand( 0, 2 ) ) - { - Rancor_Swing( NPC->handRBolt, qfalse ); - } - else - { - Rancor_Swing( NPC->handRBolt, qtrue ); +void Rancor_CheckAnimDamage(void) { + if (NPC->client->ps.legsAnim == BOTH_ATTACK2 || NPC->client->ps.legsAnim == BOTH_ATTACK10 || NPC->client->ps.legsAnim == BOTH_ATTACK11) { + if (NPC->client->ps.legsAnimTimer >= 1200 && NPC->client->ps.legsAnimTimer <= 1350) { + if (Q_irand(0, 2)) { + Rancor_Swing(NPC->handRBolt, qfalse); + } else { + Rancor_Swing(NPC->handRBolt, qtrue); } + } else if (NPC->client->ps.legsAnimTimer >= 1100 && NPC->client->ps.legsAnimTimer <= 1550) { + Rancor_Swing(NPC->handRBolt, qtrue); } - else if ( NPC->client->ps.legsAnimTimer >= 1100 && NPC->client->ps.legsAnimTimer <= 1550 ) - { - Rancor_Swing( NPC->handRBolt, qtrue ); - } - } - else if ( NPC->client->ps.legsAnim == BOTH_ATTACK5 ) - { - if ( NPC->client->ps.legsAnimTimer >= 750 && NPC->client->ps.legsAnimTimer <= 1300 ) - { - Rancor_Swing( NPC->handLBolt, qfalse ); - } - else if ( NPC->client->ps.legsAnimTimer >= 1700 && NPC->client->ps.legsAnimTimer <= 2300 ) - { - Rancor_Swing( NPC->handRBolt, qfalse ); + } else if (NPC->client->ps.legsAnim == BOTH_ATTACK5) { + if (NPC->client->ps.legsAnimTimer >= 750 && NPC->client->ps.legsAnimTimer <= 1300) { + Rancor_Swing(NPC->handLBolt, qfalse); + } else if (NPC->client->ps.legsAnimTimer >= 1700 && NPC->client->ps.legsAnimTimer <= 2300) { + Rancor_Swing(NPC->handRBolt, qfalse); } } } @@ -1456,251 +1158,178 @@ void Rancor_CheckAnimDamage( void ) NPC_BSRancor_Default ------------------------- */ -void NPC_BSRancor_Default( void ) -{ - AddSightEvent( NPC, NPC->currentOrigin, 1024, AEL_DANGER_GREAT, 50 ); +void NPC_BSRancor_Default(void) { + AddSightEvent(NPC, NPC->currentOrigin, 1024, AEL_DANGER_GREAT, 50); - if (NPCInfo->blockedEntity && TIMER_Done(NPC, "blockedEntityIgnore")) - { - if (!TIMER_Exists(NPC, "blockedEntityTimeOut")) - { + if (NPCInfo->blockedEntity && TIMER_Done(NPC, "blockedEntityIgnore")) { + if (!TIMER_Exists(NPC, "blockedEntityTimeOut")) { TIMER_Set(NPC, "blockedEntityTimeOut", 5000); - } - else if (TIMER_Done(NPC, "blockedEntityTimeOut")) - { + } else if (TIMER_Done(NPC, "blockedEntityTimeOut")) { TIMER_Remove(NPC, "blockedEntityTimeOut"); TIMER_Set(NPC, "blockedEntityIgnore", 25000); NPCInfo->blockedEntity = NULL; } - } - else - { + } else { TIMER_Remove(NPC, "blockedEntityTimeOut"); TIMER_Remove(NPC, "blockedEntityIgnore"); } Rancor_CheckAnimDamage(); - if ( !TIMER_Done( NPC, "breathAttack" ) ) - {//doing breath attack, just do damage + if (!TIMER_Done(NPC, "breathAttack")) { // doing breath attack, just do damage Rancor_FireBreathAttack(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; - } - else if ( NPC->client->ps.legsAnim == BOTH_ATTACK4 - || NPC->client->ps.legsAnim == BOTH_ATTACK6 - || NPC->client->ps.legsAnim == BOTH_ATTACK7 ) - { - G_StopEffect( G_EffectIndex( "mrancor/breath" ), NPC->playerModel, NPC->gutBolt, NPC->s.number ); + } else if (NPC->client->ps.legsAnim == BOTH_ATTACK4 || NPC->client->ps.legsAnim == BOTH_ATTACK6 || NPC->client->ps.legsAnim == BOTH_ATTACK7) { + G_StopEffect(G_EffectIndex("mrancor/breath"), NPC->playerModel, NPC->gutBolt, NPC->s.number); NPC->s.loopSound = 0; } - if ( TIMER_Done2( NPC, "clearGrabbed", qtrue ) ) - { - Rancor_DropVictim( NPC ); - } - else if ( (NPC->client->ps.legsAnim == BOTH_PAIN2 || NPC->client->ps.legsAnim == BOTH_HOLD_DROP ) - && NPC->count == 1 - && NPC->activator ) - { + if (TIMER_Done2(NPC, "clearGrabbed", qtrue)) { + Rancor_DropVictim(NPC); + } else if ((NPC->client->ps.legsAnim == BOTH_PAIN2 || NPC->client->ps.legsAnim == BOTH_HOLD_DROP) && NPC->count == 1 && NPC->activator) { Rancor_CheckDropVictim(); } - if ( !TIMER_Done( NPC, "rageTime" ) ) - {//do nothing but roar first time we see an enemy - AddSoundEvent( NPC, NPC->currentOrigin, 1024, AEL_DANGER_GREAT, qfalse, qfalse ); - NPC_FaceEnemy( qtrue ); + if (!TIMER_Done(NPC, "rageTime")) { // do nothing but roar first time we see an enemy + AddSoundEvent(NPC, NPC->currentOrigin, 1024, AEL_DANGER_GREAT, qfalse, qfalse); + NPC_FaceEnemy(qtrue); return; } - if ( NPCInfo->localState == LSTATE_WAITING - && TIMER_Done2( NPC, "takingPain", qtrue ) ) - {//was not doing anything because we were taking pain, but pain is done now, so clear it... + if (NPCInfo->localState == LSTATE_WAITING && + TIMER_Done2(NPC, "takingPain", qtrue)) { // was not doing anything because we were taking pain, but pain is done now, so clear it... NPCInfo->localState = LSTATE_CLEAR; } - if ( !TIMER_Done( NPC, "confusionTime" ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!TIMER_Done(NPC, "confusionTime")) { + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( NPC->enemy ) - { - if ( NPC->enemy->client //enemy is a client - && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA )//enemy is a lowly jawa or ugnaught - && NPC->enemy->enemy != NPC//enemy's enemy is not me - && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || NPC->enemy->enemy->client->NPC_class!=CLASS_RANCOR) )//enemy's enemy is not a client or is not a rancor (which is as scary as me anyway) - {//they should be scared of ME and no-one else - G_SetEnemy( NPC->enemy, NPC ); + if (NPC->enemy) { + if (NPC->enemy->client // enemy is a client + && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA) // enemy is a lowly jawa or ugnaught + && NPC->enemy->enemy != NPC // enemy's enemy is not me + && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || + NPC->enemy->enemy->client->NPC_class != CLASS_RANCOR)) // enemy's enemy is not a client or is not a rancor (which is as scary as me anyway) + { // they should be scared of ME and no-one else + G_SetEnemy(NPC->enemy, NPC); } - if ( TIMER_Done(NPC,"angrynoise") ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/rancor/anger%d.wav", Q_irand(1, 3)) ); + if (TIMER_Done(NPC, "angrynoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/rancor/anger%d.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "angrynoise", Q_irand( 5000, 10000 ) ); - } - else - { - AddSoundEvent( NPC, NPC->currentOrigin, 512, AEL_DANGER_GREAT, qfalse, qfalse ); + TIMER_Set(NPC, "angrynoise", Q_irand(5000, 10000)); + } else { + AddSoundEvent(NPC, NPC->currentOrigin, 512, AEL_DANGER_GREAT, qfalse, qfalse); } - if ( NPC->count == 2 && NPC->client->ps.legsAnim == BOTH_ATTACK3 ) - {//we're still chewing our enemy up - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC->count == 2 && NPC->client->ps.legsAnim == BOTH_ATTACK3) { // we're still chewing our enemy up + NPC_UpdateAngles(qtrue, qtrue); return; } - //else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while - if( NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_RANCOR ) - {//got mad at another Rancor, look for a valid enemy - if ( TIMER_Done( NPC, "rancorInfight" ) ) - { - NPC_CheckEnemyExt( qtrue ); + // else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while + if (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_RANCOR) { // got mad at another Rancor, look for a valid enemy + if (TIMER_Done(NPC, "rancorInfight")) { + NPC_CheckEnemyExt(qtrue); } - } - else if ( !NPC->count ) - { - if ( NPCInfo->blockedEntity ) - {//something in our way - if ( !NPCInfo->blockedEntity->inuse ) - {//was destroyed + } else if (!NPC->count) { + if (NPCInfo->blockedEntity) { // something in our way + if (!NPCInfo->blockedEntity->inuse) { // was destroyed NPCInfo->blockedEntity = NULL; - } - else - { - //a breakable? - if ( G_EntIsBreakable( NPCInfo->blockedEntity->s.number, NPC ) ) - {//breakable brush - if ( !Rancor_AttackBBrush() ) - {//didn't move inside that func, so call move here...? - Rancor_Move( qtrue ); + } else { + // a breakable? + if (G_EntIsBreakable(NPCInfo->blockedEntity->s.number, NPC)) { // breakable brush + if (!Rancor_AttackBBrush()) { // didn't move inside that func, so call move here...? + Rancor_Move(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//if it's a client and in our way, get mad at it! - if ( NPCInfo->blockedEntity != NPC->enemy - && NPCInfo->blockedEntity->client - && NPC_ValidEnemy( NPCInfo->blockedEntity ) - && !Q_irand( 0, 9 ) ) - { - G_SetEnemy( NPC, NPCInfo->blockedEntity ); - //look again in 2-5 secs - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + } else { // if it's a client and in our way, get mad at it! + if (NPCInfo->blockedEntity != NPC->enemy && NPCInfo->blockedEntity->client && NPC_ValidEnemy(NPCInfo->blockedEntity) && + !Q_irand(0, 9)) { + G_SetEnemy(NPC, NPCInfo->blockedEntity); + // look again in 2-5 secs + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(2000, 5000)); NPCInfo->blockedEntity = NULL; } } } } - if ( NPC_ValidEnemy( NPC->enemy ) == qfalse ) - { - TIMER_Remove( NPC, "lookForNewEnemy" );//make them look again right now - if ( !NPC->enemy->inuse - || level.time - NPC->enemy->s.time > Q_irand( 10000, 15000 ) - || (NPC->spawnflags&SPF_RANCOR_FASTKILL) )//don't linger on dead bodies - {//it's been a while since the enemy died, or enemy is completely gone, get bored with him - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) - && player && player->health >= 0 ) - {//all else failing, always go after the player + if (NPC_ValidEnemy(NPC->enemy) == qfalse) { + TIMER_Remove(NPC, "lookForNewEnemy"); // make them look again right now + if (!NPC->enemy->inuse || level.time - NPC->enemy->s.time > Q_irand(10000, 15000) || + (NPC->spawnflags & SPF_RANCOR_FASTKILL)) // don't linger on dead bodies + { // it's been a while since the enemy died, or enemy is completely gone, get bored with him + if ((NPC->spawnflags & SPF_RANCOR_MUTANT) && player && player->health >= 0) { // all else failing, always go after the player NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, player ); - if ( NPC->enemy != NPC->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(NPC, player); + if (NPC->enemy != NPC->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up NPC->useDebounceTime = 0; } - } - else - { + } else { NPC->enemy = NULL; Rancor_Patrol(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( TIMER_Done( NPC, "lookForNewEnemy" ) ) - { - gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy? + if (TIMER_Done(NPC, "lookForNewEnemy")) { + gentity_t *sav_enemy = NPC->enemy; // FIXME: what about NPC->lastEnemy? NPC->enemy = NULL; - gentity_t *newEnemy = NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse ); + gentity_t *newEnemy = NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse); NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, newEnemy ); - if ( NPC->enemy != NPC->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(NPC, newEnemy); + if (NPC->enemy != NPC->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up NPC->useDebounceTime = 0; } - //hold this one for at least 5-15 seconds - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - } - else - {//look again in 2-5 secs - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + // hold this one for at least 5-15 seconds + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(5000, 15000)); + } else { // look again in 2-5 secs + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(2000, 5000)); } } } Rancor_Combat(); - if ( TIMER_Done( NPC, "attacking" ) - && TIMER_Done( NPC, "takingpain" ) - && TIMER_Done( NPC, "confusionDebounce" ) - && NPCInfo->localState == LSTATE_CLEAR - && !NPC->count ) - {//not busy - if ( !ucmd.forwardmove - && !ucmd.rightmove - && VectorCompare( NPC->client->ps.moveDir, vec3_origin ) ) - {//not moving - if ( level.time - NPCInfo->enemyLastSeenTime > 5000 ) - {//haven't seen an enemy in a while - if ( !Q_irand( 0, 20 ) ) - { - if ( Q_irand( 0, 1 ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (TIMER_Done(NPC, "attacking") && TIMER_Done(NPC, "takingpain") && TIMER_Done(NPC, "confusionDebounce") && NPCInfo->localState == LSTATE_CLEAR && + !NPC->count) { // not busy + if (!ucmd.forwardmove && !ucmd.rightmove && VectorCompare(NPC->client->ps.moveDir, vec3_origin)) { // not moving + if (level.time - NPCInfo->enemyLastSeenTime > 5000) { // haven't seen an enemy in a while + if (!Q_irand(0, 20)) { + if (Q_irand(0, 1)) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( NPC, "confusionTime", NPC->client->ps.legsAnimTimer ); - TIMER_Set( NPC, "confusionDebounce", NPC->client->ps.legsAnimTimer+Q_irand( 4000, 8000 ) ); + TIMER_Set(NPC, "confusionTime", NPC->client->ps.legsAnimTimer); + TIMER_Set(NPC, "confusionDebounce", NPC->client->ps.legsAnimTimer + Q_irand(4000, 8000)); } } } } - } - else - { - if ( TIMER_Done(NPC,"idlenoise") ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/rancor/snort_%d.wav", Q_irand(1, 4)) ); + } else { + if (TIMER_Done(NPC, "idlenoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/rancor/snort_%d.wav", Q_irand(1, 4))); - TIMER_Set( NPC, "idlenoise", Q_irand( 2000, 4000 ) ); - AddSoundEvent( NPC, NPC->currentOrigin, 384, AEL_DANGER, qfalse, qfalse ); + TIMER_Set(NPC, "idlenoise", Q_irand(2000, 4000)); + AddSoundEvent(NPC, NPC->currentOrigin, 384, AEL_DANGER, qfalse, qfalse); } - if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Rancor_Patrol(); - if ( !NPC->enemy && NPC->wait ) - {//we've been mad before and can't find an enemy - if ( (NPC->spawnflags&SPF_RANCOR_MUTANT) - && player && player->health >= 0 ) - {//all else failing, always go after the player + if (!NPC->enemy && NPC->wait) { // we've been mad before and can't find an enemy + if ((NPC->spawnflags & SPF_RANCOR_MUTANT) && player && player->health >= 0) { // all else failing, always go after the player NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, player ); - if ( NPC->enemy != NPC->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(NPC, player); + if (NPC->enemy != NPC->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up NPC->useDebounceTime = 0; } } } - } - else - { + } else { Rancor_Idle(); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/code/game/AI_Remote.cpp b/code/game/AI_Remote.cpp index da712d0143..a47725ac5c 100644 --- a/code/game/AI_Remote.cpp +++ b/code/game/AI_Remote.cpp @@ -25,25 +25,22 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -void Remote_Strafe( void ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +void Remote_Strafe(void); -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f - -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, }; -void Remote_Idle( void ); +void Remote_Idle(void); -void NPC_Remote_Precache(void) -{ +void NPC_Remote_Precache(void) { G_SoundIndex("sound/chars/remote/misc/fire.wav"); - G_SoundIndex( "sound/chars/remote/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/remote/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } /* @@ -51,14 +48,13 @@ void NPC_Remote_Precache(void) NPC_Remote_Pain ------------------------- */ -void NPC_Remote_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_Remote_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Remote_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -66,122 +62,103 @@ void NPC_Remote_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, c Remote_MaintainHeight ------------------------- */ -void Remote_MaintainHeight( void ) -{ - float dif; +void Remote_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPC->client->ps.velocity[2] ) - { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPC->enemy ) - { - if (TIMER_Done( NPC, "heightChange")) - { - TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPC->enemy) { + if (TIMER_Done(NPC, "heightChange")) { + TIMER_Set(NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + Q_irand( 0, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + Q_irand(0, NPC->enemy->maxs[2] + 8)) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); } dif *= 10; - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; NPC->fx_time = level.time; - G_Sound( NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + G_Sound(NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } -#define REMOTE_STRAFE_VEL 256 -#define REMOTE_STRAFE_DIS 200 -#define REMOTE_UPWARD_PUSH 32 +#define REMOTE_STRAFE_VEL 256 +#define REMOTE_STRAFE_DIS 200 +#define REMOTE_UPWARD_PUSH 32 /* ------------------------- Remote_Strafe ------------------------- */ -void Remote_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Remote_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, REMOTE_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, REMOTE_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPC->client->ps.velocity); - G_Sound( NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + G_Sound(NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); // Add a slight upward push NPC->client->ps.velocity[2] += REMOTE_UPWARD_PUSH; @@ -192,37 +169,33 @@ void Remote_Strafe( void ) } } -#define REMOTE_FORWARD_BASE_SPEED 10 -#define REMOTE_FORWARD_MULTIPLIER 5 +#define REMOTE_FORWARD_BASE_SPEED 10 +#define REMOTE_FORWARD_MULTIPLIER 5 /* ------------------------- Remote_Hunt ------------------------- */ -void Remote_Hunt( qboolean visible, qboolean advance, qboolean retreat ) -{ - float speed; - vec3_t forward; +void Remote_Hunt(qboolean visible, qboolean advance, qboolean retreat) { + float speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Remote_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse && visible == qtrue ) + // If we don't want to advance, stop here + if (advance == qfalse && visible == qtrue) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; @@ -230,45 +203,40 @@ void Remote_Hunt( qboolean visible, qboolean advance, qboolean retreat ) NPC_MoveToGoal(qtrue); return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = REMOTE_FORWARD_BASE_SPEED + REMOTE_FORWARD_MULTIPLIER * g_spskill->integer; - if ( retreat == qtrue ) - { + if (retreat == qtrue) { speed *= -1; } - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } - /* ------------------------- Remote_Fire ------------------------- */ -void Remote_Fire (void) -{ - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; +void Remote_Fire(void) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorCopy( NPC->currentOrigin, muzzle1 ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorCopy(NPC->currentOrigin, muzzle1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - missile = CreateMissile( NPC->currentOrigin, forward, 1000, 10000, NPC ); + missile = CreateMissile(NPC->currentOrigin, forward, 1000, 10000, NPC); - G_PlayEffect( "bryar/muzzle_flash", NPC->currentOrigin, forward ); + G_PlayEffect("bryar/muzzle_flash", NPC->currentOrigin, forward); missile->classname = "briar"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -277,7 +245,6 @@ void Remote_Fire (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -285,69 +252,61 @@ void Remote_Fire (void) Remote_Ranged ------------------------- */ -void Remote_Ranged( qboolean visible, qboolean advance, qboolean retreat ) -{ +void Remote_Ranged(qboolean visible, qboolean advance, qboolean retreat) { - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 3000)); Remote_Fire(); } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); } } -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) /* ------------------------- Remote_Attack ------------------------- */ -void Remote_Attack( void ) -{ - if ( TIMER_Done(NPC,"spin") ) - { - TIMER_Set( NPC, "spin", Q_irand( 250, 1500 ) ); - NPCInfo->desiredYaw += Q_irand( -200, 200 ); +void Remote_Attack(void) { + if (TIMER_Done(NPC, "spin")) { + TIMER_Set(NPC, "spin", Q_irand(250, 1500)); + NPCInfo->desiredYaw += Q_irand(-200, 200); } // Always keep a good height off the ground Remote_MaintainHeight(); // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Remote_Idle(); return; } // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); -// distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - float idealDist = MIN_DISTANCE_SQR+(MIN_DISTANCE_SQR*Q_flrand( 0, 1 )); - qboolean advance = (qboolean)(distance > idealDist*1.25); - qboolean retreat = (qboolean)(distance < idealDist*0.75); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + // distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + float idealDist = MIN_DISTANCE_SQR + (MIN_DISTANCE_SQR * Q_flrand(0, 1)); + qboolean advance = (qboolean)(distance > idealDist * 1.25); + qboolean retreat = (qboolean)(distance < idealDist * 0.75); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); return; } } - Remote_Ranged( visible, advance, retreat ); - + Remote_Ranged(visible, advance, retreat); } /* @@ -355,8 +314,7 @@ void Remote_Attack( void ) Remote_Idle ------------------------- */ -void Remote_Idle( void ) -{ +void Remote_Idle(void) { Remote_MaintainHeight(); NPC_BSIdle(); @@ -367,42 +325,32 @@ void Remote_Idle( void ) Remote_Patrol ------------------------- */ -void Remote_Patrol( void ) -{ +void Remote_Patrol(void) { Remote_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { - //start loop sound once we move + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { + // start loop sound once we move ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - /* ------------------------- NPC_BSRemote_Default ------------------------- */ -void NPC_BSRemote_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSRemote_Default(void) { + if (NPC->enemy) { Remote_Attack(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Remote_Patrol(); - } - else - { + } else { Remote_Idle(); } } diff --git a/code/game/AI_RocketTrooper.cpp b/code/game/AI_RocketTrooper.cpp index 69ac2f99bb..8a1d6c01b0 100644 --- a/code/game/AI_RocketTrooper.cpp +++ b/code/game/AI_RocketTrooper.cpp @@ -21,273 +21,228 @@ along with this program; if not, see . */ #include "b_local.h" -extern qboolean PM_FlippingAnim( int anim ); -extern void NPC_BSST_Patrol( void ); +extern qboolean PM_FlippingAnim(int anim); +extern void NPC_BSST_Patrol(void); -extern void RT_FlyStart( gentity_t *self ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); +extern void RT_FlyStart(gentity_t *self); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); -#define VELOCITY_DECAY 0.7f +#define VELOCITY_DECAY 0.7f -#define RT_FLYING_STRAFE_VEL 60 -#define RT_FLYING_STRAFE_DIS 200 -#define RT_FLYING_UPWARD_PUSH 150 +#define RT_FLYING_STRAFE_VEL 60 +#define RT_FLYING_STRAFE_DIS 200 +#define RT_FLYING_UPWARD_PUSH 150 -#define RT_FLYING_FORWARD_BASE_SPEED 50 -#define RT_FLYING_FORWARD_MULTIPLIER 10 +#define RT_FLYING_FORWARD_BASE_SPEED 50 +#define RT_FLYING_FORWARD_MULTIPLIER 10 -void RT_Precache( void ) -{ - G_SoundIndex( "sound/chars/boba/bf_blast-off.wav" ); - G_SoundIndex( "sound/chars/boba/bf_jetpack_lp.wav" ); - G_SoundIndex( "sound/chars/boba/bf_land.wav" ); - G_EffectIndex( "rockettrooper/flameNEW" ); - G_EffectIndex( "rockettrooper/light_cone" );//extern this? At least use a different one +void RT_Precache(void) { + G_SoundIndex("sound/chars/boba/bf_blast-off.wav"); + G_SoundIndex("sound/chars/boba/bf_jetpack_lp.wav"); + G_SoundIndex("sound/chars/boba/bf_land.wav"); + G_EffectIndex("rockettrooper/flameNEW"); + G_EffectIndex("rockettrooper/light_cone"); // extern this? At least use a different one } -extern void NPC_BehaviorSet_Stormtrooper( int bState ); -void RT_RunStormtrooperAI( void ) -{ +extern void NPC_BehaviorSet_Stormtrooper(int bState); +void RT_RunStormtrooperAI(void) { int bState; - //Execute our bState - if(NPCInfo->tempBehavior) - {//Overrides normal behavior until cleared + // Execute our bState + if (NPCInfo->tempBehavior) { // Overrides normal behavior until cleared bState = NPCInfo->tempBehavior; - } - else - { - if(!NPCInfo->behaviorState) + } else { + if (!NPCInfo->behaviorState) NPCInfo->behaviorState = NPCInfo->defaultBehavior; bState = NPCInfo->behaviorState; } - NPC_BehaviorSet_Stormtrooper( bState ); + NPC_BehaviorSet_Stormtrooper(bState); } -void RT_FireDecide( void ) -{ +void RT_FireDecide(void) { qboolean enemyLOS = qfalse; qboolean enemyCS = qfalse; qboolean enemyInFOV = qfalse; - //qboolean move = qtrue; + // qboolean move = qtrue; qboolean shoot = qfalse; qboolean hitAlly = qfalse; - vec3_t impactPos; - float enemyDist; - - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE - && NPC->client->ps.forceJumpZStart - && !PM_FlippingAnim( NPC->client->ps.legsAnim ) - && !Q_irand( 0, 10 ) ) - {//take off - RT_FlyStart( NPC ); + vec3_t impactPos; + float enemyDist; + + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE && NPC->client->ps.forceJumpZStart && !PM_FlippingAnim(NPC->client->ps.legsAnim) && + !Q_irand(0, 10)) { // take off + RT_FlyStart(NPC); } - if ( !NPC->enemy ) - { + if (!NPC->enemy) { return; } - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + VectorClear(impactPos); + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - vec3_t enemyDir, shootDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); - VectorNormalize( enemyDir ); - AngleVectors( NPC->client->ps.viewangles, shootDir, NULL, NULL ); - float dot = DotProduct( enemyDir, shootDir ); - if ( dot > 0.5f ||( enemyDist * (1.0f-dot)) < 10000 ) - {//enemy is in front of me or they're very close and not behind me + vec3_t enemyDir, shootDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir); + VectorNormalize(enemyDir); + AngleVectors(NPC->client->ps.viewangles, shootDir, NULL, NULL); + float dot = DotProduct(enemyDir, shootDir); + if (dot > 0.5f || (enemyDist * (1.0f - dot)) < 10000) { // enemy is in front of me or they're very close and not behind me enemyInFOV = qtrue; } - if ( enemyDist < MIN_ROCKET_DIST_SQUARED )//128 - {//enemy within 128 - if ( (NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && - (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + if (enemyDist < MIN_ROCKET_DIST_SQUARED) // 128 + { // enemy within 128 + if ((NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && + (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... + // FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... } } - //can we see our target? - if ( TIMER_Done( NPC, "nextAttackDelay" ) && TIMER_Done( NPC, "flameTime" ) ) - { - if ( NPC_ClearLOS( NPC->enemy ) ) - { + // can we see our target? + if (TIMER_Done(NPC, "nextAttackDelay") && TIMER_Done(NPC, "flameTime")) { + if (NPC_ClearLOS(NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - } - else - {//can we shoot our target? - if ( (NPC->client->ps.weapon == WP_ROCKET_LAUNCHER - || (NPC->client->ps.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags&SCF_ALT_FIRE)) - || (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist < MIN_ROCKET_DIST_SQUARED )//128*128 + if (NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + } else { // can we shoot our target? + if ((NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPC->client->ps.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags & SCF_ALT_FIRE)) || + (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags & SCF_ALT_FIRE))) && + enemyDist < MIN_ROCKET_DIST_SQUARED) // 128*128 { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else if ( enemyInFOV ) - {//if enemy is FOV, go ahead and check for shooting - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else if (enemyInFOV) { // if enemy is FOV, go ahead and check for shooting + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPC->s.weapon == WP_EMPLACED_GUN) ) ) - {//can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && + ((hitEnt->svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || + NPC->s.weapon == WP_EMPLACED_GUN))) { // can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), + // so shoot anyway enemyCS = qtrue; - //NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - //NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + // NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + // NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } - } - else - { - enemyCS = qfalse;//not true, but should stop us from firing + } else { + enemyCS = qfalse; // not true, but should stop us from firing } } - } - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { + } else if (gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { NPCInfo->enemyLastSeenTime = level.time; - //NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + // NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy } - if ( NPC->client->ps.weapon == WP_NONE ) - { + if (NPC->client->ps.weapon == WP_NONE) { shoot = qfalse; - } - else - { - if ( enemyCS ) - { + } else { + if (enemyCS) { shoot = qtrue; } } - if ( !enemyCS ) - {//if have a clear shot, always try - //See if we should continue to fire on their last position - //!TIMER_Done( NPC, "stick" ) || - if ( !hitAlly //we're not going to hit an ally - && enemyInFOV //enemy is in our FOV //FIXME: or we don't have a clear LOS? - && NPCInfo->enemyLastSeenTime > 0 )//we've seen the enemy + if (!enemyCS) { // if have a clear shot, always try + // See if we should continue to fire on their last position + //! TIMER_Done( NPC, "stick" ) || + if (!hitAlly // we're not going to hit an ally + && enemyInFOV // enemy is in our FOV //FIXME: or we don't have a clear LOS? + && NPCInfo->enemyLastSeenTime > 0) // we've seen the enemy { - if ( level.time - NPCInfo->enemyLastSeenTime < 10000 )//we have seem the enemy in the last 10 seconds + if (level.time - NPCInfo->enemyLastSeenTime < 10000) // we have seem the enemy in the last 10 seconds { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - gi.trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - float distThreshold = 16384/*128*128*/;//default - switch ( NPC->s.weapon ) - { + // see if impact would be too close to me + float distThreshold = 16384 /*128*128*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; case WP_CONCUSSION: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - distThreshold = 65536/*256*256*/; + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - float dist = DistanceSquared( impactPos, muzzle ); + float dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 5000 || - (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000 )) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - switch ( NPC->s.weapon ) - { + } else if (level.time - NPCInfo->enemyLastSeenTime > 5000 || + (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000)) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 262144/*512*512*/; + distThreshold = 262144 /*512*512*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } break; case WP_CONCUSSION: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - distThreshold = 262144/*512*512*/; + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + distThreshold = 262144 /*512*512*/; } break; default: break; } - dist = DistanceSquared( impactPos, NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; } @@ -296,54 +251,36 @@ void RT_FireDecide( void ) } } - //FIXME: don't shoot right away! - if ( NPC->client->fireDelay ) - { - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER - || (NPC->s.weapon == WP_CONCUSSION&&!(NPCInfo->scriptFlags&SCF_ALT_FIRE)) ) - { - if ( !enemyLOS || !enemyCS ) - {//cancel it + // FIXME: don't shoot right away! + if (NPC->client->fireDelay) { + if (NPC->s.weapon == WP_ROCKET_LAUNCHER || (NPC->s.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags & SCF_ALT_FIRE))) { + if (!enemyLOS || !enemyCS) { // cancel it NPC->client->fireDelay = 0; - } - else - {//delay our next attempt - TIMER_Set( NPC, "nextAttackDelay", Q_irand( 1000, 3000 ) );//FIXME: base on g_spskill + } else { // delay our next attempt + TIMER_Set(NPC, "nextAttackDelay", Q_irand(1000, 3000)); // FIXME: base on g_spskill } } - } - else if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "nextAttackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + } else if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "nextAttackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } - //NASTY - int altChance = 6;//FIXME: base on g_spskill - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { - if ( (ucmd.buttons&BUTTON_ATTACK) - && !Q_irand( 0, altChance ) ) - {//every now and then, shoot a homing rocket + // NASTY + int altChance = 6; // FIXME: base on g_spskill + if (NPC->s.weapon == WP_ROCKET_LAUNCHER) { + if ((ucmd.buttons & BUTTON_ATTACK) && !Q_irand(0, altChance)) { // every now and then, shoot a homing rocket ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1000, 3000 );//FIXME: base on g_spskill + NPC->client->fireDelay = Q_irand(1000, 3000); // FIXME: base on g_spskill } - } - else if ( NPC->s.weapon == WP_CONCUSSION ) - { - if ( (ucmd.buttons&BUTTON_ATTACK) - && Q_irand( 0, altChance*5 ) ) - {//fire the beam shot + } else if (NPC->s.weapon == WP_CONCUSSION) { + if ((ucmd.buttons & BUTTON_ATTACK) && Q_irand(0, altChance * 5)) { // fire the beam shot ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons |= BUTTON_ALT_ATTACK; - TIMER_Set( NPC, "nextAttackDelay", Q_irand( 1500, 2500 ) );//FIXME: base on g_spskill - } - else - {//fire the rocket-like shot - TIMER_Set( NPC, "nextAttackDelay", Q_irand( 3000, 5000 ) );//FIXME: base on g_spskill + TIMER_Set(NPC, "nextAttackDelay", Q_irand(1500, 2500)); // FIXME: base on g_spskill + } else { // fire the rocket-like shot + TIMER_Set(NPC, "nextAttackDelay", Q_irand(3000, 5000)); // FIXME: base on g_spskill } } } @@ -352,132 +289,107 @@ void RT_FireDecide( void ) } //===================================================================================== -//FLYING behavior +// FLYING behavior //===================================================================================== -qboolean RT_Flying( gentity_t *self ) -{ - return ((qboolean)(self->client->moveType==MT_FLYSWIM)); -} +qboolean RT_Flying(gentity_t *self) { return ((qboolean)(self->client->moveType == MT_FLYSWIM)); } -void RT_FlyStart( gentity_t *self ) -{//switch to seeker AI for a while - if ( TIMER_Done( self, "jetRecharge" ) - && !RT_Flying( self ) ) - { +void RT_FlyStart(gentity_t *self) { // switch to seeker AI for a while + if (TIMER_Done(self, "jetRecharge") && !RT_Flying(self)) { self->client->ps.gravity = 0; self->svFlags |= SVF_CUSTOM_GRAVITY; self->client->moveType = MT_FLYSWIM; - //Inform NPC_HandleAIFlags we want to fly + // Inform NPC_HandleAIFlags we want to fly - if (self->NPC){ + if (self->NPC) { self->NPC->aiFlags |= NPCAI_FLY; self->lastInAirTime = level.time; } - //start jet effect + // start jet effect self->client->jetPackTime = Q3_INFINITE; - if ( self->genericBolt1 != -1 ) - { - G_PlayEffect( G_EffectIndex( "rockettrooper/flameNEW" ), self->playerModel, self->genericBolt1, self->s.number, self->currentOrigin, qtrue, qtrue ); + if (self->genericBolt1 != -1) { + G_PlayEffect(G_EffectIndex("rockettrooper/flameNEW"), self->playerModel, self->genericBolt1, self->s.number, self->currentOrigin, qtrue, qtrue); } - if ( self->genericBolt2 != -1 ) - { - G_PlayEffect( G_EffectIndex( "rockettrooper/flameNEW" ), self->playerModel, self->genericBolt2, self->s.number, self->currentOrigin, qtrue, qtrue ); + if (self->genericBolt2 != -1) { + G_PlayEffect(G_EffectIndex("rockettrooper/flameNEW"), self->playerModel, self->genericBolt2, self->s.number, self->currentOrigin, qtrue, qtrue); } - //take-off sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav" ); - //jet loop sound - self->s.loopSound = G_SoundIndex( "sound/chars/boba/bf_jetpack_lp.wav" ); - if ( self->NPC ) - { + // take-off sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav"); + // jet loop sound + self->s.loopSound = G_SoundIndex("sound/chars/boba/bf_jetpack_lp.wav"); + if (self->NPC) { self->count = Q3_INFINITE; // SEEKER shot ammo count } } } -void RT_FlyStop( gentity_t *self ) -{ +void RT_FlyStop(gentity_t *self) { self->client->ps.gravity = g_gravity->value; self->svFlags &= ~SVF_CUSTOM_GRAVITY; self->client->moveType = MT_RUNJUMP; - //Stop the effect + // Stop the effect self->client->jetPackTime = 0; - if ( self->genericBolt1 != -1 ) - { - G_StopEffect("rockettrooper/flameNEW", self->playerModel, self->genericBolt1, self->s.number ); + if (self->genericBolt1 != -1) { + G_StopEffect("rockettrooper/flameNEW", self->playerModel, self->genericBolt1, self->s.number); } - if ( self->genericBolt2 != -1 ) - { - G_StopEffect("rockettrooper/flameNEW", self->playerModel, self->genericBolt2, self->s.number ); + if (self->genericBolt2 != -1) { + G_StopEffect("rockettrooper/flameNEW", self->playerModel, self->genericBolt2, self->s.number); } - //stop jet loop sound + // stop jet loop sound self->s.loopSound = 0; - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/boba/bf_land.wav" ); + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/boba/bf_land.wav"); - if ( self->NPC ) - { + if (self->NPC) { self->count = 0; // SEEKER shot ammo count - TIMER_Set( self, "jetRecharge", Q_irand( 1000, 5000 ) ); - TIMER_Set( self, "jumpChaseDebounce", Q_irand( 500, 2000 ) ); + TIMER_Set(self, "jetRecharge", Q_irand(1000, 5000)); + TIMER_Set(self, "jumpChaseDebounce", Q_irand(500, 2000)); } } -void RT_JetPackEffect( int duration ) -{ - if ( NPC->genericBolt1 != -1 ) - { - G_PlayEffect( G_EffectIndex( "rockettrooper/flameNEW" ), NPC->playerModel, NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, duration, qtrue ); +void RT_JetPackEffect(int duration) { + if (NPC->genericBolt1 != -1) { + G_PlayEffect(G_EffectIndex("rockettrooper/flameNEW"), NPC->playerModel, NPC->genericBolt1, NPC->s.number, NPC->currentOrigin, duration, qtrue); } - if ( NPC->genericBolt2 != -1 ) - { - G_PlayEffect( G_EffectIndex( "rockettrooper/flameNEW" ), NPC->playerModel, NPC->genericBolt2, NPC->s.number, NPC->currentOrigin, duration, qtrue ); + if (NPC->genericBolt2 != -1) { + G_PlayEffect(G_EffectIndex("rockettrooper/flameNEW"), NPC->playerModel, NPC->genericBolt2, NPC->s.number, NPC->currentOrigin, duration, qtrue); } - //take-off sound - G_SoundOnEnt( NPC, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav" ); + // take-off sound + G_SoundOnEnt(NPC, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav"); } -void RT_Flying_ApplyFriction( float frictionScale ) -{ - if ( NPC->client->ps.velocity[0] ) - { - NPC->client->ps.velocity[0] *= VELOCITY_DECAY;///frictionScale; +void RT_Flying_ApplyFriction(float frictionScale) { + if (NPC->client->ps.velocity[0]) { + NPC->client->ps.velocity[0] *= VELOCITY_DECAY; /// frictionScale; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { - NPC->client->ps.velocity[1] *= VELOCITY_DECAY;///frictionScale; + if (NPC->client->ps.velocity[1]) { + NPC->client->ps.velocity[1] *= VELOCITY_DECAY; /// frictionScale; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } -void RT_Flying_MaintainHeight( void ) -{ - float dif = 0; +void RT_Flying_MaintainHeight(void) { + float dif = 0; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPC->forcePushTime > level.time ) - {//if being pushed, we don't have control over our movement + if (NPC->forcePushTime > level.time) { // if being pushed, we don't have control over our movement return; } - if ( (NPC->client->ps.pm_flags&PMF_TIME_KNOCKBACK) ) - {//don't slow down for a bit - if ( NPC->client->ps.pm_time > 0 ) - { - VectorScale( NPC->client->ps.velocity, 0.9f, NPC->client->ps.velocity ); + if ((NPC->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) { // don't slow down for a bit + if (NPC->client->ps.pm_time > 0) { + VectorScale(NPC->client->ps.velocity, 0.9f, NPC->client->ps.velocity); return; } } @@ -490,127 +402,93 @@ void RT_Flying_MaintainHeight( void ) } */ // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPC->enemy - && (!Q3_TaskIDPending( NPC, TID_MOVE_NAV ) || !NPCInfo->goalEntity ) ) - { - if (TIMER_Done( NPC, "heightChange" )) - { - TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPC->enemy && (!Q3_TaskIDPending(NPC, TID_MOVE_NAV) || !NPCInfo->goalEntity)) { + if (TIMER_Done(NPC, "heightChange")) { + TIMER_Set(NPC, "heightChange", Q_irand(1000, 3000)); float enemyZHeight = NPC->enemy->currentOrigin[2]; - if ( NPC->enemy->client - && NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE - && (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client && NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE && + (NPC->enemy->client->ps.forcePowersActive & (1 << FP_LEVITATION))) { // so we don't go up when they force jump up at us enemyZHeight = NPC->enemy->client->ps.forceJumpZStart; } // Find the height difference - dif = (enemyZHeight + Q_flrand( NPC->enemy->maxs[2]/2, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2]; + dif = (enemyZHeight + Q_flrand(NPC->enemy->maxs[2] / 2, NPC->enemy->maxs[2] + 8)) - NPC->currentOrigin[2]; - float difFactor = 10.0f; + float difFactor = 10.0f; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2*difFactor ) - { - if ( fabs( dif ) > 20*difFactor ) - { - dif = ( dif < 0 ? -20*difFactor : 20*difFactor ); + if (fabs(dif) > 2 * difFactor) { + if (fabs(dif) > 20 * difFactor) { + dif = (dif < 0 ? -20 * difFactor : 20 * difFactor); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - NPC->client->ps.velocity[2] *= Q_flrand( 0.85f, 1.25f ); - } - else - {//don't get too far away from height of enemy... + NPC->client->ps.velocity[2] *= Q_flrand(0.85f, 1.25f); + } else { // don't get too far away from height of enemy... float enemyZHeight = NPC->enemy->currentOrigin[2]; - if ( NPC->enemy->client - && NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE - && (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client && NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE && + (NPC->enemy->client->ps.forcePowersActive & (1 << FP_LEVITATION))) { // so we don't go up when they force jump up at us enemyZHeight = NPC->enemy->client->ps.forceJumpZStart; } - dif = NPC->currentOrigin[2] - (enemyZHeight+64); + dif = NPC->currentOrigin[2] - (enemyZHeight + 64); float maxHeight = 200; - float hDist = DistanceHorizontal( NPC->enemy->currentOrigin, NPC->currentOrigin ); - if ( hDist < 512 ) - { - maxHeight *= hDist/512; + float hDist = DistanceHorizontal(NPC->enemy->currentOrigin, NPC->currentOrigin); + if (hDist < 512) { + maxHeight *= hDist / 512; } - if ( dif > maxHeight ) - { - if ( NPC->client->ps.velocity[2] > 0 )//FIXME: or: we can't see him anymore - {//slow down - if ( NPC->client->ps.velocity[2] ) - { + if (dif > maxHeight) { + if (NPC->client->ps.velocity[2] > 0) // FIXME: or: we can't see him anymore + { // slow down + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } - } - else - {//start coming back down + } else { // start coming back down NPC->client->ps.velocity[2] -= 4; } - } - else if ( dif < -200 && NPC->client->ps.velocity[2] < 0 )//we're way below him + } else if (dif < -200 && NPC->client->ps.velocity[2] < 0) // we're way below him { - if ( NPC->client->ps.velocity[2] < 0 )//FIXME: or: we can't see him anymore - {//slow down - if ( NPC->client->ps.velocity[2] ) - { + if (NPC->client->ps.velocity[2] < 0) // FIXME: or: we can't see him anymore + { // slow down + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) > -2 ) - { + if (fabs(NPC->client->ps.velocity[2]) > -2) { NPC->client->ps.velocity[2] = 0; } } - } - else - {//start going back up + } else { // start going back up NPC->client->ps.velocity[2] += 4; } } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - } - else if ( VectorCompare( NPC->pos1, vec3_origin ) ) - {//have a starting position as a reference point + } else if (VectorCompare(NPC->pos1, vec3_origin)) { // have a starting position as a reference point dif = NPC->pos1[2] - NPC->currentOrigin[2]; } - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } @@ -618,46 +496,36 @@ void RT_Flying_MaintainHeight( void ) } // Apply friction - RT_Flying_ApplyFriction( 1.0f ); + RT_Flying_ApplyFriction(1.0f); } -void RT_Flying_Strafe( void ) -{ - int side; - vec3_t end, right, dir; - trace_t tr; +void RT_Flying_Strafe(void) { + int side; + vec3_t end, right, dir; + trace_t tr; - if ( Q_flrand(0.0f, 1.0f) > 0.7f - || !NPC->enemy - || !NPC->enemy->client ) - { + if (Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client) { // Do a regular style strafe - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonably valid - side = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, RT_FLYING_STRAFE_DIS * side, right, end ); + side = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, RT_FLYING_STRAFE_DIS * side, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - float vel = RT_FLYING_STRAFE_VEL+Q_flrand(-20,20); - VectorMA( NPC->client->ps.velocity, vel*side, right, NPC->client->ps.velocity ); - if ( !Q_irand( 0, 3 ) ) - { + if (tr.fraction > 0.9f) { + float vel = RT_FLYING_STRAFE_VEL + Q_flrand(-20, 20); + VectorMA(NPC->client->ps.velocity, vel * side, right, NPC->client->ps.velocity); + if (!Q_irand(0, 3)) { // Add a slight upward push float upPush = RT_FLYING_UPWARD_PUSH; - if ( NPC->client->ps.velocity[2] < 300 ) - { - if ( NPC->client->ps.velocity[2] < 300+upPush ) - { + if (NPC->client->ps.velocity[2] < 300) { + if (NPC->client->ps.velocity[2] < 300 + upPush) { NPC->client->ps.velocity[2] += upPush; - } - else - { + } else { NPC->client->ps.velocity[2] = 300; } } @@ -665,53 +533,42 @@ void RT_Flying_Strafe( void ) NPCInfo->standTime = level.time + 1000 + Q_flrand(0.0f, 1.0f) * 500; } - } - else - { + } else { // Do a strafe to try and keep on the side of their enemy - AngleVectors( NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL ); + AngleVectors(NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL); // Pick a random side - side = ( rand() & 1 ) ? -1 : 1; - float stDis = RT_FLYING_STRAFE_DIS*2.0f; - VectorMA( NPC->enemy->currentOrigin, stDis * side, right, end ); + side = (rand() & 1) ? -1 : 1; + float stDis = RT_FLYING_STRAFE_DIS * 2.0f; + VectorMA(NPC->enemy->currentOrigin, stDis * side, right, end); // then add a very small bit of random in front of/behind the player action - VectorMA( end, Q_flrand(-1.0f, 1.0f) * 25, dir, end ); + VectorMA(end, Q_flrand(-1.0f, 1.0f) * 25, dir, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - float vel = (RT_FLYING_STRAFE_VEL*4)+Q_flrand(-20,20); - VectorSubtract( tr.endpos, NPC->currentOrigin, dir ); + if (tr.fraction > 0.9f) { + float vel = (RT_FLYING_STRAFE_VEL * 4) + Q_flrand(-20, 20); + VectorSubtract(tr.endpos, NPC->currentOrigin, dir); dir[2] *= 0.25; // do less upward change - float dis = VectorNormalize( dir ); - if ( dis > vel ) - { + float dis = VectorNormalize(dir); + if (dis > vel) { dis = vel; } // Try to move the desired enemy side - VectorMA( NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity); - if ( !Q_irand( 0, 3 ) ) - { + if (!Q_irand(0, 3)) { float upPush = RT_FLYING_UPWARD_PUSH; // Add a slight upward push - if ( NPC->client->ps.velocity[2] < 300 ) - { - if ( NPC->client->ps.velocity[2] < 300+upPush ) - { + if (NPC->client->ps.velocity[2] < 300) { + if (NPC->client->ps.velocity[2] < 300 + upPush) { NPC->client->ps.velocity[2] += upPush; - } - else - { + } else { NPC->client->ps.velocity[2] = 300; } - } - else if ( NPC->client->ps.velocity[2] > 300 ) - { + } else if (NPC->client->ps.velocity[2] > 300) { NPC->client->ps.velocity[2] = 300; } } @@ -721,25 +578,22 @@ void RT_Flying_Strafe( void ) } } -void RT_Flying_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void RT_Flying_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - if ( NPC->forcePushTime >= level.time ) - //|| (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//if being pushed, we don't have control over our movement + if (NPC->forcePushTime >= level.time) + //|| (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) ) + { // if being pushed, we don't have control over our movement NPC->delay = 0; return; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { NPC->delay = 0; RT_Flying_Strafe(); return; @@ -747,11 +601,9 @@ void RT_Flying_Hunt( qboolean visible, qboolean advance ) } // If we don't want to advance, stop here - if ( advance ) - { + if (advance) { // Only try and navigate if the player is visible - if ( visible == qfalse ) - { + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 24; @@ -759,163 +611,124 @@ void RT_Flying_Hunt( qboolean visible, qboolean advance ) NPC->delay = 0; NPC_MoveToGoal(qtrue); return; - } } - //else move straight at/away from him - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); + // else move straight at/away from him + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); forward[2] *= 0.1f; - distance = VectorNormalize( forward ); + distance = VectorNormalize(forward); speed = RT_FLYING_FORWARD_BASE_SPEED + RT_FLYING_FORWARD_MULTIPLIER * g_spskill->integer; - if ( advance && distance < Q_flrand( 256, 3096 ) ) - { + if (advance && distance < Q_flrand(256, 3096)) { NPC->delay = 0; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); - } - else if ( distance < Q_flrand( 0, 128 ) ) - { - if ( NPC->health <= 50 ) - {//always back off + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); + } else if (distance < Q_flrand(0, 128)) { + if (NPC->health <= 50) { // always back off NPC->delay = 0; - } - else if ( !TIMER_Done( NPC, "backoffTime" ) ) - {//still backing off from end of last delay + } else if (!TIMER_Done(NPC, "backoffTime")) { // still backing off from end of last delay NPC->delay = 0; - } - else if ( !NPC->delay ) - {//start a new delay - NPC->delay = Q_irand( 0, 10+(20*(2-g_spskill->integer)) ); - } - else - {//continue the current delay + } else if (!NPC->delay) { // start a new delay + NPC->delay = Q_irand(0, 10 + (20 * (2 - g_spskill->integer))); + } else { // continue the current delay NPC->delay--; } - if ( !NPC->delay ) - {//delay done, now back off for a few seconds! - TIMER_Set( NPC, "backoffTime", Q_irand( 2000, 5000 ) ); - VectorMA( NPC->client->ps.velocity, speed*-2, forward, NPC->client->ps.velocity ); + if (!NPC->delay) { // delay done, now back off for a few seconds! + TIMER_Set(NPC, "backoffTime", Q_irand(2000, 5000)); + VectorMA(NPC->client->ps.velocity, speed * -2, forward, NPC->client->ps.velocity); } - } - else - { + } else { NPC->delay = 0; } } -void RT_Flying_Ranged( qboolean visible, qboolean advance ) -{ - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - RT_Flying_Hunt( visible, advance ); +void RT_Flying_Ranged(qboolean visible, qboolean advance) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + RT_Flying_Hunt(visible, advance); } } -void RT_Flying_Attack( void ) -{ +void RT_Flying_Attack(void) { // Always keep a good height off the ground RT_Flying_MaintainHeight(); // Rate our distance to the target, and our visibilty - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance>(256.0f*256.0f)); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > (256.0f * 256.0f)); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - RT_Flying_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + RT_Flying_Hunt(visible, advance); return; } } - RT_Flying_Ranged( visible, advance ); + RT_Flying_Ranged(visible, advance); } -void RT_Flying_Think( void ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) - && UpdateGoal() ) - {//being scripted to go to a certain spot, don't maintain height - if ( NPC_MoveToGoal( qtrue ) ) - {//we could macro-nav to our goal - if ( NPC->enemy && NPC->enemy->health && NPC->enemy->inuse ) - { - NPC_FaceEnemy( qtrue ); +void RT_Flying_Think(void) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV) && UpdateGoal()) { // being scripted to go to a certain spot, don't maintain height + if (NPC_MoveToGoal(qtrue)) { // we could macro-nav to our goal + if (NPC->enemy && NPC->enemy->health && NPC->enemy->inuse) { + NPC_FaceEnemy(qtrue); RT_FireDecide(); } - } - else - {//frick, no where to nav to, keep us in the air! + } else { // frick, no where to nav to, keep us in the air! RT_Flying_MaintainHeight(); } return; } - if ( NPC->random == 0.0f ) - { + if (NPC->random == 0.0f) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi } - if ( NPC->enemy && NPC->enemy->health && NPC->enemy->inuse ) - { + if (NPC->enemy && NPC->enemy->health && NPC->enemy->inuse) { RT_Flying_Attack(); RT_FireDecide(); return; - } - else - { + } else { RT_Flying_MaintainHeight(); RT_RunStormtrooperAI(); return; } } - //===================================================================================== -//ON GROUND WITH ENEMY behavior +// ON GROUND WITH ENEMY behavior //===================================================================================== - //===================================================================================== -//DEFAULT behavior +// DEFAULT behavior //===================================================================================== -extern void RT_CheckJump( void ); -void NPC_BSRT_Default( void ) -{ - //FIXME: custom pain and death funcs: - //pain3 is in air - //die in air is both_falldeath1 - //attack1 is on ground, attack2 is in air - - //FIXME: this doesn't belong here - if ( NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( NPCInfo->rank >= RANK_LT )//&& !Q_irand( 0, 50 ) ) - {//officers always stay in the air - NPC->client->ps.velocity[2] = Q_irand( 50, 125 ); - NPC->NPC->aiFlags |= NPCAI_FLY; //fixme also, Inform NPC_HandleAIFlags we want to fly +extern void RT_CheckJump(void); +void NPC_BSRT_Default(void) { + // FIXME: custom pain and death funcs: + // pain3 is in air + // die in air is both_falldeath1 + // attack1 is on ground, attack2 is in air + + // FIXME: this doesn't belong here + if (NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (NPCInfo->rank >= RANK_LT) //&& !Q_irand( 0, 50 ) ) + { // officers always stay in the air + NPC->client->ps.velocity[2] = Q_irand(50, 125); + NPC->NPC->aiFlags |= NPCAI_FLY; // fixme also, Inform NPC_HandleAIFlags we want to fly } } - if ( RT_Flying( NPC ) ) - {//FIXME: only officers need do this, right? + if (RT_Flying(NPC)) { // FIXME: only officers need do this, right? RT_Flying_Think(); - } - else if ( NPC->enemy != NULL ) - {//rocketrooper on ground with enemy + } else if (NPC->enemy != NULL) { // rocketrooper on ground with enemy UpdateGoal(); RT_RunStormtrooperAI(); RT_CheckJump(); - //NPC_BSST_Default();//FIXME: add missile avoidance - //RT_Hunt();//NPC_BehaviorSet_Jedi( bState ); - } - else - {//shouldn't have gotten in here + // NPC_BSST_Default();//FIXME: add missile avoidance + // RT_Hunt();//NPC_BehaviorSet_Jedi( bState ); + } else { // shouldn't have gotten in here RT_RunStormtrooperAI(); - //NPC_BSST_Patrol(); + // NPC_BSST_Patrol(); } } \ No newline at end of file diff --git a/code/game/AI_SaberDroid.cpp b/code/game/AI_SaberDroid.cpp index 7a6996c099..9df896a56c 100644 --- a/code/game/AI_SaberDroid.cpp +++ b/code/game/AI_SaberDroid.cpp @@ -26,17 +26,17 @@ along with this program; if not, see . #include "g_navigator.h" #include "wp_saber.h" -extern void WP_DeactivateSaber( gentity_t *self, qboolean clearLength = qfalse ); -extern int PM_AnimLength( int index, animNumber_t anim ); +extern void WP_DeactivateSaber(gentity_t *self, qboolean clearLength = qfalse); +extern int PM_AnimLength(int index, animNumber_t anim); -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; static qboolean faceEnemy; static qboolean doMove; static qboolean shoot; -static float enemyDist; +static float enemyDist; /* void NPC_SaberDroid_PlayConfusionSound( gentity_t *self ) @@ -64,33 +64,31 @@ ST_Move ------------------------- */ -static qboolean SaberDroid_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always doMove straight toward our goal +static qboolean SaberDroid_Move(void) { + NPCInfo->combatMove = qtrue; // always doMove straight toward our goal UpdateGoal(); - if ( !NPCInfo->goalEntity ) - { + if (!NPCInfo->goalEntity) { NPCInfo->goalEntity = NPC->enemy; } NPCInfo->goalRadius = 30.0f; - qboolean moved = NPC_MoveToGoal( qtrue ); -// navInfo_t info; + qboolean moved = NPC_MoveToGoal(qtrue); + // navInfo_t info; - //Get the doMove info -// NAV_GetLastMove( info ); + // Get the doMove info + // NAV_GetLastMove( info ); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! -// if ( info.flags & NIF_COLLISION ) -// { -// if ( info.blocker == NPC->enemy ) -// { -// SaberDroid_HoldPosition(); -// } -// } + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + // if ( info.flags & NIF_COLLISION ) + // { + // if ( info.blocker == NPC->enemy ) + // { + // SaberDroid_HoldPosition(); + // } + // } - //If our doMove failed, then reset + // If our doMove failed, then reset /* if ( moved == qfalse ) {//couldn't get to enemy @@ -108,69 +106,57 @@ NPC_BSSaberDroid_Patrol ------------------------- */ -void NPC_BSSaberDroid_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSSaberDroid_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - //There is an event to look at - if ( alertEvent >= 0 )//&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + // There is an event to look at + if (alertEvent >= 0) //&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) { - //NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level >= AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + // NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; + if (level.alertEvents[alertEvent].level >= AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -179,70 +165,54 @@ void NPC_BSSaberDroid_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else if ( !NPC->client->ps.weaponTime - && TIMER_Done( NPC, "attackDelay" ) - && TIMER_Done( NPC, "inactiveDelay" ) ) - { - if ( NPC->client->ps.SaberActive() ) - { - WP_DeactivateSaber( NPC, qfalse ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURNOFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_MoveToGoal(qtrue); + } else if (!NPC->client->ps.weaponTime && TIMER_Done(NPC, "attackDelay") && TIMER_Done(NPC, "inactiveDelay")) { + if (NPC->client->ps.SaberActive()) { + WP_DeactivateSaber(NPC, qfalse); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURNOFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -int SaberDroid_PowerLevelForSaberAnim( gentity_t *self ) -{ - switch ( self->client->ps.legsAnim ) - { +int SaberDroid_PowerLevelForSaberAnim(gentity_t *self) { + switch (self->client->ps.legsAnim) { case BOTH_A2_TR_BL: - if ( self->client->ps.torsoAnimTimer <= 200 ) - {//end of anim + if (self->client->ps.torsoAnimTimer <= 200) { // end of anim return FORCE_LEVEL_0; - } - else if ( PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ) - self->client->ps.torsoAnimTimer < 200 ) - {//beginning of anim + } else if (PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim) - self->client->ps.torsoAnimTimer < + 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_2; break; case BOTH_A1_BL_TR: - if ( self->client->ps.torsoAnimTimer <= 300 ) - {//end of anim + if (self->client->ps.torsoAnimTimer <= 300) { // end of anim return FORCE_LEVEL_0; - } - else if ( PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ) - self->client->ps.torsoAnimTimer < 200 ) - {//beginning of anim + } else if (PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim) - self->client->ps.torsoAnimTimer < + 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_1; break; case BOTH_A1__L__R: - if ( self->client->ps.torsoAnimTimer <= 250 ) - {//end of anim + if (self->client->ps.torsoAnimTimer <= 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ) - self->client->ps.torsoAnimTimer < 150 ) - {//beginning of anim + } else if (PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim) - self->client->ps.torsoAnimTimer < + 150) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_1; break; case BOTH_A3__L__R: - if ( self->client->ps.torsoAnimTimer <= 200 ) - {//end of anim + if (self->client->ps.torsoAnimTimer <= 200) { // end of anim return FORCE_LEVEL_0; - } - else if ( PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ) - self->client->ps.torsoAnimTimer < 300 ) - {//beginning of anim + } else if (PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim) - self->client->ps.torsoAnimTimer < + 300) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -257,11 +227,9 @@ NPC_BSSaberDroid_Attack ------------------------- */ -void NPC_SaberDroid_PickAttack( void ) -{ - int attackAnim = Q_irand( 0, 3 ); - switch ( attackAnim ) - { +void NPC_SaberDroid_PickAttack(void) { + int attackAnim = Q_irand(0, 3); + switch (attackAnim) { case 0: default: attackAnim = BOTH_A2_TR_BL; @@ -285,42 +253,37 @@ void NPC_SaberDroid_PickAttack( void ) break; } NPC->client->ps.saberBlocking = saberMoveData[NPC->client->ps.saberMove].blocking; - if ( saberMoveData[NPC->client->ps.saberMove].trailLength > 0 ) - { - NPC->client->ps.SaberActivateTrail( saberMoveData[NPC->client->ps.saberMove].trailLength ); // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter - } - else - { - NPC->client->ps.SaberDeactivateTrail( 0 ); + if (saberMoveData[NPC->client->ps.saberMove].trailLength > 0) { + NPC->client->ps.SaberActivateTrail( + saberMoveData[NPC->client->ps.saberMove].trailLength); // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter + } else { + NPC->client->ps.SaberDeactivateTrail(0); } - NPC_SetAnim( NPC, SETANIM_BOTH, attackAnim, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPC->client->ps.torsoAnim = NPC->client->ps.legsAnim;//need to do this because we have no anim split but saber code checks torsoAnim + NPC_SetAnim(NPC, SETANIM_BOTH, attackAnim, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPC->client->ps.torsoAnim = NPC->client->ps.legsAnim; // need to do this because we have no anim split but saber code checks torsoAnim NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer = NPC->client->ps.legsAnimTimer; NPC->client->ps.weaponstate = WEAPON_FIRING; } -void NPC_BSSaberDroid_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSSaberDroid_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; - NPC_BSSaberDroid_Patrol();//FIXME: or patrol? + NPC_BSSaberDroid_Patrol(); // FIXME: or patrol? return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSSaberDroid_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSSaberDroid_Patrol(); // FIXME: or patrol? return; } @@ -328,17 +291,16 @@ void NPC_BSSaberDroid_Attack( void ) doMove = qtrue; faceEnemy = qfalse; shoot = qfalse; - enemyDist = DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ); + enemyDist = DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin); - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( enemyDist <= 4096 && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45 ) )//within 64 & infront + if (enemyDist <= 4096 && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45)) // within 64 & infront { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); enemyCS = qtrue; } } @@ -350,107 +312,83 @@ void NPC_BSSaberDroid_Attack( void ) } */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( !TIMER_Done( NPC, "taunting" ) ) - { + if (!TIMER_Done(NPC, "taunting")) { doMove = qfalse; - } - else if ( enemyCS ) - { + } else if (enemyCS) { shoot = qtrue; - if ( enemyDist < (NPC->maxs[0]+NPC->enemy->maxs[0]+32)*(NPC->maxs[0]+NPC->enemy->maxs[0]+32) ) - {//close enough + if (enemyDist < (NPC->maxs[0] + NPC->enemy->maxs[0] + 32) * (NPC->maxs[0] + NPC->enemy->maxs[0] + 32)) { // close enough doMove = qfalse; } - }//this should make him chase enemy when out of range...? + } // this should make him chase enemy when out of range...? - if ( NPC->client->ps.legsAnimTimer - && NPC->client->ps.legsAnim != BOTH_A3__L__R )//this one is a running attack - {//in the middle of a held, stationary anim, can't doMove + if (NPC->client->ps.legsAnimTimer && NPC->client->ps.legsAnim != BOTH_A3__L__R) // this one is a running attack + { // in the middle of a held, stationary anim, can't doMove doMove = qfalse; } - if ( doMove ) - {//doMove toward goal + if (doMove) { // doMove toward goal doMove = SaberDroid_Move(); - if ( doMove ) - {//if we had to chase him, be sure to attack as soon as possible - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); + if (doMove) { // if we had to chase him, be sure to attack as soon as possible + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); } } - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( doMove ) - {//don't run away and shoot + if (!faceEnemy) { // we want to face in the dir we're running + if (doMove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy ) + { // face the enemy NPC_FaceEnemy(); } - if ( NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - //FIXME: need predicted blocking? - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: need predicted blocking? + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { NPC_SaberDroid_PickAttack(); - if ( NPCInfo->rank > RANK_CREWMAN ) - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime+Q_irand(0, 1000) ); - } - else - { - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime+Q_irand( 0, 1000 )+(Q_irand( 0, (3-g_spskill->integer)*2 )*500) ); + if (NPCInfo->rank > RANK_CREWMAN) { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime + Q_irand(0, 1000)); + } else { + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime + Q_irand(0, 1000) + (Q_irand(0, (3 - g_spskill->integer) * 2) * 500)); } } } } } -void NPC_BSSD_Default( void ) -{ - if( !NPC->enemy ) - {//don't have an enemy, look for one +void NPC_BSSD_Default(void) { + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSSaberDroid_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy - if ( !NPC->client->ps.SaberActive() ) - { + } else // if ( NPC->enemy ) + { // have an enemy + if (!NPC->client->ps.SaberActive()) { NPC->client->ps.SaberActivate(); - if ( NPC->client->ps.legsAnim == BOTH_TURNOFF - || NPC->client->ps.legsAnim == BOTH_STAND1 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURNON, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (NPC->client->ps.legsAnim == BOTH_TURNOFF || NPC->client->ps.legsAnim == BOTH_STAND1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURNON, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } NPC_BSSaberDroid_Attack(); - TIMER_Set( NPC, "inactiveDelay", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "inactiveDelay", Q_irand(2000, 4000)); } - if ( !NPC->client->ps.weaponTime ) - { + if (!NPC->client->ps.weaponTime) { NPC->client->ps.saberMove = LS_READY; NPC->client->ps.saberBlocking = saberMoveData[LS_READY].blocking; - NPC->client->ps.SaberDeactivateTrail( 0 ); + NPC->client->ps.SaberDeactivateTrail(0); NPC->client->ps.saberAnimLevel = SS_MEDIUM; NPC->client->ps.weaponstate = WEAPON_READY; } diff --git a/code/game/AI_SandCreature.cpp b/code/game/AI_SandCreature.cpp index 49e7b8f53a..256f39af82 100644 --- a/code/game/AI_SandCreature.cpp +++ b/code/game/AI_SandCreature.cpp @@ -25,299 +25,244 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); -#define MIN_ATTACK_DIST_SQ 128 -#define MIN_MISS_DIST 100 -#define MIN_MISS_DIST_SQ (MIN_MISS_DIST*MIN_MISS_DIST) -#define MAX_MISS_DIST 500 -#define MAX_MISS_DIST_SQ (MAX_MISS_DIST*MAX_MISS_DIST) -#define MIN_SCORE -37500 //speed of (50*50) - dist of (200*200) +#define MIN_ATTACK_DIST_SQ 128 +#define MIN_MISS_DIST 100 +#define MIN_MISS_DIST_SQ (MIN_MISS_DIST * MIN_MISS_DIST) +#define MAX_MISS_DIST 500 +#define MAX_MISS_DIST_SQ (MAX_MISS_DIST * MAX_MISS_DIST) +#define MIN_SCORE -37500 // speed of (50*50) - dist of (200*200) -void SandCreature_Precache( void ) -{ +void SandCreature_Precache(void) { int i; - G_EffectIndex( "env/sand_dive" ); - G_EffectIndex( "env/sand_spray" ); - G_EffectIndex( "env/sand_move" ); - G_EffectIndex( "env/sand_move_breach" ); - //G_EffectIndex( "env/sand_attack_breach" ); - for ( i = 1; i < 4; i++ ) - { - G_SoundIndex( va( "sound/chars/sand_creature/voice%d.mp3", i ) ); - } - G_SoundIndex( "sound/chars/sand_creature/slither.wav" ); + G_EffectIndex("env/sand_dive"); + G_EffectIndex("env/sand_spray"); + G_EffectIndex("env/sand_move"); + G_EffectIndex("env/sand_move_breach"); + // G_EffectIndex( "env/sand_attack_breach" ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/sand_creature/voice%d.mp3", i)); + } + G_SoundIndex("sound/chars/sand_creature/slither.wav"); } -void SandCreature_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( NPC, "speaking", -level.time ); - TIMER_Set( NPC, "breaching", -level.time ); - TIMER_Set( NPC, "breachDebounce", -level.time ); - TIMER_Set( NPC, "pain", -level.time ); - TIMER_Set( NPC, "attacking", -level.time ); - TIMER_Set( NPC, "missDebounce", -level.time ); +void SandCreature_ClearTimers(gentity_t *ent) { + TIMER_Set(NPC, "speaking", -level.time); + TIMER_Set(NPC, "breaching", -level.time); + TIMER_Set(NPC, "breachDebounce", -level.time); + TIMER_Set(NPC, "pain", -level.time); + TIMER_Set(NPC, "attacking", -level.time); + TIMER_Set(NPC, "missDebounce", -level.time); } -void NPC_SandCreature_Die( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - //FIXME: somehow make him solid when he dies? +void NPC_SandCreature_Die(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + // FIXME: somehow make him solid when he dies? } -void NPC_SandCreature_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( TIMER_Done( self, "pain" ) ) - { - //FIXME: effect and sound - //FIXME: shootable during this anim? - NPC_SetAnim( self, SETANIM_LEGS, Q_irand(BOTH_ATTACK1,BOTH_ATTACK2), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - G_AddEvent( self, EV_PAIN, Q_irand( 0, 100 ) ); - TIMER_Set( self, "pain", self->client->ps.legsAnimTimer + Q_irand( 500, 2000 ) ); - float playerDist = Distance( player->currentOrigin, self->currentOrigin ); - if ( playerDist < 256 ) - { - CGCam_Shake( 1.0f*playerDist/128.0f, self->client->ps.legsAnimTimer ); +void NPC_SandCreature_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + if (TIMER_Done(self, "pain")) { + // FIXME: effect and sound + // FIXME: shootable during this anim? + NPC_SetAnim(self, SETANIM_LEGS, Q_irand(BOTH_ATTACK1, BOTH_ATTACK2), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + G_AddEvent(self, EV_PAIN, Q_irand(0, 100)); + TIMER_Set(self, "pain", self->client->ps.legsAnimTimer + Q_irand(500, 2000)); + float playerDist = Distance(player->currentOrigin, self->currentOrigin); + if (playerDist < 256) { + CGCam_Shake(1.0f * playerDist / 128.0f, self->client->ps.legsAnimTimer); } } self->enemy = self->NPC->goalEntity = NULL; } -void SandCreature_MoveEffect( void ) -{ - vec3_t up = {0,0,1}; - vec3_t org = {NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->absmin[2]+2}; +void SandCreature_MoveEffect(void) { + vec3_t up = {0, 0, 1}; + vec3_t org = {NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->absmin[2] + 2}; - float playerDist = Distance( player->currentOrigin, NPC->currentOrigin ); - if ( playerDist < 256 ) - { - CGCam_Shake( 0.75f*playerDist/256.0f, 250 ); - } - - if ( level.time-NPC->client->ps.lastStationary > 2000 ) - {//first time moving for at least 2 seconds - //clear speakingtime - TIMER_Set( NPC, "speaking", -level.time ); - } - - if ( TIMER_Done( NPC, "breaching" ) - && TIMER_Done( NPC, "breachDebounce" ) - && TIMER_Done( NPC, "pain" ) - && TIMER_Done( NPC, "attacking" ) - && !Q_irand( 0, 10 ) ) - {//Breach! - //FIXME: only do this while moving forward? - trace_t trace; - //make him solid here so he can be hit/gets blocked on stuff. Check clear first. - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid ) - { - NPC->clipmask = MASK_NPCSOLID;//turn solid for a little bit + float playerDist = Distance(player->currentOrigin, NPC->currentOrigin); + if (playerDist < 256) { + CGCam_Shake(0.75f * playerDist / 256.0f, 250); + } + + if (level.time - NPC->client->ps.lastStationary > 2000) { // first time moving for at least 2 seconds + // clear speakingtime + TIMER_Set(NPC, "speaking", -level.time); + } + + if (TIMER_Done(NPC, "breaching") && TIMER_Done(NPC, "breachDebounce") && TIMER_Done(NPC, "pain") && TIMER_Done(NPC, "attacking") && + !Q_irand(0, 10)) { // Breach! + // FIXME: only do this while moving forward? + trace_t trace; + // make him solid here so he can be hit/gets blocked on stuff. Check clear first. + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid) { + NPC->clipmask = MASK_NPCSOLID; // turn solid for a little bit NPC->contents = CONTENTS_BODY; - //NPC->takedamage = qtrue;//can be shot? + // NPC->takedamage = qtrue;//can be shot? - //FIXME: Breach sound? - //FIXME: Breach effect? - NPC_SetAnim( NPC, SETANIM_LEGS, BOTH_WALK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - TIMER_Set( NPC, "breaching", NPC->client->ps.legsAnimTimer ); - TIMER_Set( NPC, "breachDebounce", NPC->client->ps.legsAnimTimer+Q_irand( 0, 10000 ) ); + // FIXME: Breach sound? + // FIXME: Breach effect? + NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_WALK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + TIMER_Set(NPC, "breaching", NPC->client->ps.legsAnimTimer); + TIMER_Set(NPC, "breachDebounce", NPC->client->ps.legsAnimTimer + Q_irand(0, 10000)); } } - if ( !TIMER_Done( NPC, "breaching" ) ) - {//different effect when breaching - //FIXME: make effect - G_PlayEffect( G_EffectIndex( "env/sand_move_breach" ), org, up ); - } - else - { - G_PlayEffect( G_EffectIndex( "env/sand_move" ), org, up ); + if (!TIMER_Done(NPC, "breaching")) { // different effect when breaching + // FIXME: make effect + G_PlayEffect(G_EffectIndex("env/sand_move_breach"), org, up); + } else { + G_PlayEffect(G_EffectIndex("env/sand_move"), org, up); } - NPC->s.loopSound = G_SoundIndex( "sound/chars/sand_creature/slither.wav" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/sand_creature/slither.wav"); } -qboolean SandCreature_CheckAhead( vec3_t end ) -{ - trace_t trace; - int clipmask = NPC->clipmask|CONTENTS_BOTCLIP; +qboolean SandCreature_CheckAhead(vec3_t end) { + trace_t trace; + int clipmask = NPC->clipmask | CONTENTS_BOTCLIP; - //make sure our goal isn't underground (else the trace will fail) - vec3_t bottom = {end[0],end[1],end[2]+NPC->mins[2]}; - gi.trace( &trace, end, vec3_origin, vec3_origin, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//in the ground, raise it up - end[2] -= NPC->mins[2]*(1.0f-trace.fraction)-0.125f; + // make sure our goal isn't underground (else the trace will fail) + vec3_t bottom = {end[0], end[1], end[2] + NPC->mins[2]}; + gi.trace(&trace, end, vec3_origin, vec3_origin, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // in the ground, raise it up + end[2] -= NPC->mins[2] * (1.0f - trace.fraction) - 0.125f; } - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, end, NPC->s.number, clipmask, (EG2_Collision)0, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) return qtrue; - if ( trace.plane.normal[2] >= MIN_WALK_NORMAL ) - { + if (trace.plane.normal[2] >= MIN_WALK_NORMAL) { return qtrue; } - //This is a work around - float radius = ( NPC->maxs[0] > NPC->maxs[1] ) ? NPC->maxs[0] : NPC->maxs[1]; - float dist = Distance( NPC->currentOrigin, end ); - float tFrac = 1.0f - ( radius / dist ); + // This is a work around + float radius = (NPC->maxs[0] > NPC->maxs[1]) ? NPC->maxs[0] : NPC->maxs[1]; + float dist = Distance(NPC->currentOrigin, end); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; return qfalse; } -qboolean SandCreature_Move( void ) -{ +qboolean SandCreature_Move(void) { qboolean moved = qfalse; - //FIXME should ignore doors..? + // FIXME should ignore doors..? vec3_t dest; - VectorCopy( NPCInfo->goalEntity->currentOrigin, dest ); - //Sand Creatures look silly using waypoints when they can go straight to the goal - if ( SandCreature_CheckAhead( dest ) ) - {//use our temp move straight to goal check - VectorSubtract( dest, NPC->currentOrigin, NPC->client->ps.moveDir ); - NPC->client->ps.speed = VectorNormalize( NPC->client->ps.moveDir ); - if ( (ucmd.buttons&BUTTON_WALKING) && NPC->client->ps.speed > NPCInfo->stats.walkSpeed ) - { + VectorCopy(NPCInfo->goalEntity->currentOrigin, dest); + // Sand Creatures look silly using waypoints when they can go straight to the goal + if (SandCreature_CheckAhead(dest)) { // use our temp move straight to goal check + VectorSubtract(dest, NPC->currentOrigin, NPC->client->ps.moveDir); + NPC->client->ps.speed = VectorNormalize(NPC->client->ps.moveDir); + if ((ucmd.buttons & BUTTON_WALKING) && NPC->client->ps.speed > NPCInfo->stats.walkSpeed) { NPC->client->ps.speed = NPCInfo->stats.walkSpeed; - } - else - { - if ( NPC->client->ps.speed < NPCInfo->stats.walkSpeed ) - { + } else { + if (NPC->client->ps.speed < NPCInfo->stats.walkSpeed) { NPC->client->ps.speed = NPCInfo->stats.walkSpeed; } - if ( !(ucmd.buttons&BUTTON_WALKING) && NPC->client->ps.speed < NPCInfo->stats.runSpeed ) - { + if (!(ucmd.buttons & BUTTON_WALKING) && NPC->client->ps.speed < NPCInfo->stats.runSpeed) { NPC->client->ps.speed = NPCInfo->stats.runSpeed; - } - else if ( NPC->client->ps.speed > NPCInfo->stats.runSpeed ) - { + } else if (NPC->client->ps.speed > NPCInfo->stats.runSpeed) { NPC->client->ps.speed = NPCInfo->stats.runSpeed; } } moved = qtrue; + } else { + moved = NPC_MoveToGoal(qtrue); } - else - { - moved = NPC_MoveToGoal( qtrue ); - } - if ( moved && NPC->radius ) - { - vec3_t newPos; + if (moved && NPC->radius) { + vec3_t newPos; float curTurfRange, newTurfRange; - curTurfRange = DistanceHorizontal( NPC->currentOrigin, NPC->s.origin ); - VectorMA( NPC->currentOrigin, NPC->client->ps.speed/100.0f, NPC->client->ps.moveDir, newPos ); - newTurfRange = DistanceHorizontal( newPos, NPC->s.origin ); - if ( newTurfRange > NPC->radius && newTurfRange > curTurfRange ) - {//would leave our range - //stop + curTurfRange = DistanceHorizontal(NPC->currentOrigin, NPC->s.origin); + VectorMA(NPC->currentOrigin, NPC->client->ps.speed / 100.0f, NPC->client->ps.moveDir, newPos); + newTurfRange = DistanceHorizontal(newPos, NPC->s.origin); + if (newTurfRange > NPC->radius && newTurfRange > curTurfRange) { // would leave our range + // stop NPC->client->ps.speed = 0.0f; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); ucmd.forwardmove = ucmd.rightmove = 0; moved = qfalse; } } return (moved); - //often erroneously returns false ??? something wrong with NAV...? + // often erroneously returns false ??? something wrong with NAV...? } -void SandCreature_Attack( qboolean miss ) -{ - //FIXME: make it able to grab a thermal detonator, take it down, +void SandCreature_Attack(qboolean miss) { + // FIXME: make it able to grab a thermal detonator, take it down, // then have it explode inside them, killing them // (or, do damage, making them stick half out of the ground and // screech for a bit, giving you a chance to run for it!) - //FIXME: effect and sound - //FIXME: shootable during this anim? - if ( !NPC->enemy->client ) - { - NPC_SetAnim( NPC, SETANIM_LEGS, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + // FIXME: effect and sound + // FIXME: shootable during this anim? + if (!NPC->enemy->client) { + NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { + NPC_SetAnim(NPC, SETANIM_LEGS, Q_irand(BOTH_ATTACK1, BOTH_ATTACK2), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } - else - { - NPC_SetAnim( NPC, SETANIM_LEGS, Q_irand( BOTH_ATTACK1, BOTH_ATTACK2 ), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - } - //don't do anything else while in this anim - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer ); - float playerDist = Distance( player->currentOrigin, NPC->currentOrigin ); - if ( playerDist < 256 ) - { - //FIXME: tone this down - CGCam_Shake( 0.75f*playerDist/128.0f, NPC->client->ps.legsAnimTimer ); + // don't do anything else while in this anim + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer); + float playerDist = Distance(player->currentOrigin, NPC->currentOrigin); + if (playerDist < 256) { + // FIXME: tone this down + CGCam_Shake(0.75f * playerDist / 128.0f, NPC->client->ps.legsAnimTimer); } - if ( miss ) - {//purposely missed him, chance of knocking him down - //FIXME: if, during the attack anim, I do end up catching him close to my mouth, then snatch him anyway... - if ( NPC->enemy && NPC->enemy->client ) - { + if (miss) { // purposely missed him, chance of knocking him down + // FIXME: if, during the attack anim, I do end up catching him close to my mouth, then snatch him anyway... + if (NPC->enemy && NPC->enemy->client) { vec3_t dir2Enemy; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, dir2Enemy ); - if ( dir2Enemy[2] < 30 ) - { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, dir2Enemy); + if (dir2Enemy[2] < 30) { dir2Enemy[2] = 30; } - if ( g_spskill->integer > 0 ) - { - float enemyDist = VectorNormalize( dir2Enemy ); - //FIXME: tone this down, smaller radius - if ( enemyDist < 200 && NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - float throwStr = ((200-enemyDist)*0.4f)+20; - if ( throwStr > 45 ) - { + if (g_spskill->integer > 0) { + float enemyDist = VectorNormalize(dir2Enemy); + // FIXME: tone this down, smaller radius + if (enemyDist < 200 && NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { + float throwStr = ((200 - enemyDist) * 0.4f) + 20; + if (throwStr > 45) { throwStr = 45; } - G_Throw( NPC->enemy, dir2Enemy, throwStr ); - if ( g_spskill->integer > 1 ) - {//knock them down, too - if ( NPC->enemy->health > 0 - && Q_flrand( 50, 150 ) > enemyDist ) - {//knock them down - G_Knockdown( NPC->enemy, NPC, dir2Enemy, 300, qtrue ); - if ( NPC->enemy->s.number < MAX_CLIENTS ) - {//make the player look up at me + G_Throw(NPC->enemy, dir2Enemy, throwStr); + if (g_spskill->integer > 1) { // knock them down, too + if (NPC->enemy->health > 0 && Q_flrand(50, 150) > enemyDist) { // knock them down + G_Knockdown(NPC->enemy, NPC, dir2Enemy, 300, qtrue); + if (NPC->enemy->s.number < MAX_CLIENTS) { // make the player look up at me vec3_t vAng; - vectoangles( dir2Enemy, vAng ); - VectorSet( vAng, AngleNormalize180(vAng[PITCH])*-1, NPC->enemy->client->ps.viewangles[YAW], 0 ); - SetClientViewAngle( NPC->enemy, vAng ); + vectoangles(dir2Enemy, vAng); + VectorSet(vAng, AngleNormalize180(vAng[PITCH]) * -1, NPC->enemy->client->ps.viewangles[YAW], 0); + SetClientViewAngle(NPC->enemy, vAng); } } } } } } - } - else - { + } else { NPC->enemy->activator = NPC; // kind of dumb, but when we are locked to the Rancor, we are owned by it. - NPC->activator = NPC->enemy;//remember him - //this guy isn't going anywhere anymore + NPC->activator = NPC->enemy; // remember him + // this guy isn't going anywhere anymore NPC->enemy->contents = 0; NPC->enemy->clipmask = 0; - if ( NPC->activator->client ) - { + if (NPC->activator->client) { NPC->activator->client->ps.SaberDeactivate(); NPC->activator->client->ps.eFlags |= EF_HELD_BY_SAND_CREATURE; - if ( NPC->activator->health > 0 && NPC->activator->client ) - { - G_AddEvent( NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0 ); - NPC_SetAnim( NPC->activator, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - NPC_SetAnim( NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TossClientItems( NPC ); - if ( NPC->activator->NPC ) - {//no more thinking for you + if (NPC->activator->health > 0 && NPC->activator->client) { + G_AddEvent(NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0); + NPC_SetAnim(NPC->activator, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC_SetAnim(NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TossClientItems(NPC); + if (NPC->activator->NPC) { // no more thinking for you NPC->activator->NPC->nextBStateThink = Q3_INFINITE; } } @@ -329,115 +274,90 @@ void SandCreature_Attack( qboolean miss ) cg.overrides.thirdPersonRange = 120; } */ - } - else - { + } else { NPC->activator->s.eFlags |= EF_HELD_BY_SAND_CREATURE; } } } -float SandCreature_EntScore( gentity_t *ent ) -{ +float SandCreature_EntScore(gentity_t *ent) { float moveSpeed, dist; - if ( ent->client ) - { - moveSpeed = VectorLengthSquared( ent->client->ps.velocity ); - } - else - { - moveSpeed = VectorLengthSquared( ent->s.pos.trDelta ); + if (ent->client) { + moveSpeed = VectorLengthSquared(ent->client->ps.velocity); + } else { + moveSpeed = VectorLengthSquared(ent->s.pos.trDelta); } - dist = DistanceSquared( NPC->currentOrigin, ent->currentOrigin ); - return (moveSpeed-dist); + dist = DistanceSquared(NPC->currentOrigin, ent->currentOrigin); + return (moveSpeed - dist); } -void SandCreature_SeekEnt( gentity_t *bestEnt, float score ) -{ +void SandCreature_SeekEnt(gentity_t *bestEnt, float score) { NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( bestEnt->currentOrigin, NPCInfo->enemyLastSeenLocation ); - NPC_SetMoveGoal( NPC, NPCInfo->enemyLastSeenLocation, 0, qfalse ); - if ( score > MIN_SCORE ) - { + VectorCopy(bestEnt->currentOrigin, NPCInfo->enemyLastSeenLocation); + NPC_SetMoveGoal(NPC, NPCInfo->enemyLastSeenLocation, 0, qfalse); + if (score > MIN_SCORE) { NPC->enemy = bestEnt; } } -void SandCreature_CheckMovingEnts( void ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = NPCInfo->stats.earshot; - int i; - vec3_t mins, maxs; +void SandCreature_CheckMovingEnts(void) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = NPCInfo->stats.earshot; + int i; + vec3_t mins, maxs; - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = NPC->currentOrigin[i] - radius; maxs[i] = NPC->currentOrigin[i] + radius; } - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); int bestEnt = -1; float bestScore = 0; float checkScore; - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the rancor ent + if (radiusEnts[i] == NPC) { // Skip the rancor ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client - if ( radiusEnts[i]->s.eType != ET_MISSILE - || radiusEnts[i]->s.weapon != WP_THERMAL ) - {//not a thermal detonator + if (radiusEnts[i]->client == NULL) { // must be a client + if (radiusEnts[i]->s.eType != ET_MISSILE || radiusEnts[i]->s.weapon != WP_THERMAL) { // not a thermal detonator continue; } - } - else - { - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) ) - {//can't be one being held + } else { + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR)) { // can't be one being held continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // can't be one being held continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE)) { // can't be one being held continue; } - if ( (radiusEnts[i]->s.eFlags&EF_NODRAW) ) - {//not if invisible + if ((radiusEnts[i]->s.eFlags & EF_NODRAW)) { // not if invisible continue; } - if ( radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_WORLD ) - {//not on the ground + if (radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_WORLD) { // not on the ground continue; } - if ( radiusEnts[i]->client->NPC_class == CLASS_SAND_CREATURE ) - { + if (radiusEnts[i]->client->NPC_class == CLASS_SAND_CREATURE) { continue; } } - if ( (radiusEnts[i]->flags&FL_NOTARGET) ) - { + if ((radiusEnts[i]->flags & FL_NOTARGET)) { continue; } /* @@ -446,235 +366,173 @@ void SandCreature_CheckMovingEnts( void ) continue; } */ - checkScore = SandCreature_EntScore( radiusEnts[i] ); - //FIXME: take mass into account too? What else? - if ( checkScore > bestScore ) - { + checkScore = SandCreature_EntScore(radiusEnts[i]); + // FIXME: take mass into account too? What else? + if (checkScore > bestScore) { bestScore = checkScore; bestEnt = i; } } - if ( bestEnt != -1 ) - { - SandCreature_SeekEnt( radiusEnts[bestEnt], bestScore ); + if (bestEnt != -1) { + SandCreature_SeekEnt(radiusEnts[bestEnt], bestScore); } } -void SandCreature_SeekAlert( int alertEvent ) -{ +void SandCreature_SeekAlert(int alertEvent) { alertEvent_t *alert = &level.alertEvents[alertEvent]; - //FIXME: check for higher alert status or closer than last location? + // FIXME: check for higher alert status or closer than last location? NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( alert->position, NPCInfo->enemyLastSeenLocation ); - NPC_SetMoveGoal( NPC, NPCInfo->enemyLastSeenLocation, 0, qfalse ); + VectorCopy(alert->position, NPCInfo->enemyLastSeenLocation); + NPC_SetMoveGoal(NPC, NPCInfo->enemyLastSeenLocation, 0, qfalse); } -void SandCreature_CheckAlerts( void ) -{ - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qfalse, qtrue, NPCInfo->lastAlertID, qfalse, AEL_MINOR, qtrue ); +void SandCreature_CheckAlerts(void) { + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qfalse, qtrue, NPCInfo->lastAlertID, qfalse, AEL_MINOR, qtrue); - //There is an event to look at - if ( alertEvent >= 0 ) - { - //if ( level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - { - SandCreature_SeekAlert( alertEvent ); - } + // There is an event to look at + if (alertEvent >= 0) { + // if ( level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + { SandCreature_SeekAlert(alertEvent); } } } } -float SandCreature_DistSqToGoal( qboolean goalIsEnemy ) -{ +float SandCreature_DistSqToGoal(qboolean goalIsEnemy) { float goalDistSq; - if ( !NPCInfo->goalEntity || goalIsEnemy ) - { - if ( !NPC->enemy ) - { + if (!NPCInfo->goalEntity || goalIsEnemy) { + if (!NPC->enemy) { return Q3_INFINITE; } NPCInfo->goalEntity = NPC->enemy; } - if ( NPCInfo->goalEntity->client ) - { - goalDistSq = DistanceSquared( NPC->currentOrigin, NPCInfo->goalEntity->currentOrigin ); - } - else - { + if (NPCInfo->goalEntity->client) { + goalDistSq = DistanceSquared(NPC->currentOrigin, NPCInfo->goalEntity->currentOrigin); + } else { vec3_t gOrg; - VectorCopy( NPCInfo->goalEntity->currentOrigin, gOrg ); - gOrg[2] -= (NPC->mins[2]-NPCInfo->goalEntity->mins[2]);//moves the gOrg up/down to make it's origin seem at the proper height as if it had my mins - goalDistSq = DistanceSquared( NPC->currentOrigin, gOrg ); + VectorCopy(NPCInfo->goalEntity->currentOrigin, gOrg); + gOrg[2] -= (NPC->mins[2] - NPCInfo->goalEntity->mins[2]); // moves the gOrg up/down to make it's origin seem at the proper height as if it had my mins + goalDistSq = DistanceSquared(NPC->currentOrigin, gOrg); } return goalDistSq; } -void SandCreature_Chase( void ) -{ - if ( !NPC->enemy->inuse ) - {//freed +void SandCreature_Chase(void) { + if (!NPC->enemy->inuse) { // freed NPC->enemy = NULL; return; } - if ( (NPC->svFlags&SVF_LOCKEDENEMY) ) - {//always know where he is + if ((NPC->svFlags & SVF_LOCKEDENEMY)) { // always know where he is NPCInfo->enemyLastSeenTime = level.time; } - if ( !(NPC->svFlags&SVF_LOCKEDENEMY) ) - { - if ( level.time-NPCInfo->enemyLastSeenTime > 10000 ) - { + if (!(NPC->svFlags & SVF_LOCKEDENEMY)) { + if (level.time - NPCInfo->enemyLastSeenTime > 10000) { NPC->enemy = NULL; return; } } - if ( NPC->enemy->client ) - { - if ( (NPC->enemy->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - || (NPC->enemy->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (NPC->enemy->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//was picked up by another monster, forget about him + if (NPC->enemy->client) { + if ((NPC->enemy->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) || (NPC->enemy->client->ps.eFlags & EF_HELD_BY_RANCOR) || + (NPC->enemy->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // was picked up by another monster, forget about him NPC->enemy = NULL; NPC->svFlags &= ~SVF_LOCKEDENEMY; return; } } - //chase the enemy - if ( NPC->enemy->client - && NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_WORLD - && !(NPC->svFlags&SVF_LOCKEDENEMY) ) - {//off the ground! - //FIXME: keep moving in the dir we were moving for a little bit... - } - else - { - float enemyScore = SandCreature_EntScore( NPC->enemy ); - if ( enemyScore < MIN_SCORE - && !(NPC->svFlags&SVF_LOCKEDENEMY) ) - {//too slow or too far away - } - else - { + // chase the enemy + if (NPC->enemy->client && NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_WORLD && + !(NPC->svFlags & SVF_LOCKEDENEMY)) { // off the ground! + // FIXME: keep moving in the dir we were moving for a little bit... + } else { + float enemyScore = SandCreature_EntScore(NPC->enemy); + if (enemyScore < MIN_SCORE && !(NPC->svFlags & SVF_LOCKEDENEMY)) { // too slow or too far away + } else { float moveSpeed; - if ( NPC->enemy->client ) - { - moveSpeed = VectorLengthSquared( NPC->enemy->client->ps.velocity ); + if (NPC->enemy->client) { + moveSpeed = VectorLengthSquared(NPC->enemy->client->ps.velocity); + } else { + moveSpeed = VectorLengthSquared(NPC->enemy->s.pos.trDelta); } - else - { - moveSpeed = VectorLengthSquared( NPC->enemy->s.pos.trDelta ); - } - if ( moveSpeed ) - {//he's still moving, update my goalEntity's origin - SandCreature_SeekEnt( NPC->enemy, 0 ); + if (moveSpeed) { // he's still moving, update my goalEntity's origin + SandCreature_SeekEnt(NPC->enemy, 0); NPCInfo->enemyLastSeenTime = level.time; } } } - if ( (level.time-NPCInfo->enemyLastSeenTime) > 5000 - && !(NPC->svFlags&SVF_LOCKEDENEMY) ) - {//enemy hasn't moved in about 5 seconds, see if there's anything else of interest + if ((level.time - NPCInfo->enemyLastSeenTime) > 5000 && + !(NPC->svFlags & SVF_LOCKEDENEMY)) { // enemy hasn't moved in about 5 seconds, see if there's anything else of interest SandCreature_CheckAlerts(); SandCreature_CheckMovingEnts(); } - float enemyDistSq = SandCreature_DistSqToGoal( qtrue ); + float enemyDistSq = SandCreature_DistSqToGoal(qtrue); - //FIXME: keeps chasing goalEntity even when it's already reached it...? - if ( enemyDistSq >= MIN_ATTACK_DIST_SQ//NPCInfo->goalEntity && - && (level.time-NPCInfo->enemyLastSeenTime) <= 3000 ) - {//sensed enemy (or something) less than 3 seconds ago + // FIXME: keeps chasing goalEntity even when it's already reached it...? + if (enemyDistSq >= MIN_ATTACK_DIST_SQ // NPCInfo->goalEntity && + && (level.time - NPCInfo->enemyLastSeenTime) <= 3000) { // sensed enemy (or something) less than 3 seconds ago ucmd.buttons &= ~BUTTON_WALKING; - if ( SandCreature_Move() ) - { + if (SandCreature_Move()) { SandCreature_MoveEffect(); } - } - else if ( (level.time-NPCInfo->enemyLastSeenTime) <= 5000 - && !(NPC->svFlags&SVF_LOCKEDENEMY) ) - {//NOTE: this leaves a 2-second dead zone in which they'll just sit there unless their enemy moves - //If there is an event we might be interested in if we weren't still interested in our enemy - if ( NPC_CheckAlertEvents( qfalse, qtrue, NPCInfo->lastAlertID, qfalse, AEL_MINOR, qtrue ) >= 0 ) - {//just stir + } else if ((level.time - NPCInfo->enemyLastSeenTime) <= 5000 && + !(NPC->svFlags & SVF_LOCKEDENEMY)) { // NOTE: this leaves a 2-second dead zone in which they'll just sit there unless their enemy moves + // If there is an event we might be interested in if we weren't still interested in our enemy + if (NPC_CheckAlertEvents(qfalse, qtrue, NPCInfo->lastAlertID, qfalse, AEL_MINOR, qtrue) >= 0) { // just stir SandCreature_MoveEffect(); } } - if ( enemyDistSq < MIN_ATTACK_DIST_SQ ) - { - if ( NPC->enemy->client ) - { + if (enemyDistSq < MIN_ATTACK_DIST_SQ) { + if (NPC->enemy->client) { NPC->client->ps.viewangles[YAW] = NPC->enemy->client->ps.viewangles[YAW]; } - if ( TIMER_Done( NPC, "breaching" ) ) - { - //okay to attack - SandCreature_Attack( qfalse ); + if (TIMER_Done(NPC, "breaching")) { + // okay to attack + SandCreature_Attack(qfalse); } - } - else if ( enemyDistSq < MAX_MISS_DIST_SQ - && enemyDistSq > MIN_MISS_DIST_SQ - && NPC->enemy->client - && TIMER_Done( NPC, "breaching" ) - && TIMER_Done( NPC, "missDebounce" ) - && !VectorCompare( NPC->pos1, NPC->currentOrigin ) //so we don't come up again in the same spot - && !Q_irand( 0, 10 ) ) - { - if ( !(NPC->svFlags&SVF_LOCKEDENEMY) ) - { - //miss them - SandCreature_Attack( qtrue ); - VectorCopy( NPC->currentOrigin, NPC->pos1 ); - TIMER_Set( NPC, "missDebounce", Q_irand( 3000, 10000 ) ); + } else if (enemyDistSq < MAX_MISS_DIST_SQ && enemyDistSq > MIN_MISS_DIST_SQ && NPC->enemy->client && TIMER_Done(NPC, "breaching") && + TIMER_Done(NPC, "missDebounce") && !VectorCompare(NPC->pos1, NPC->currentOrigin) // so we don't come up again in the same spot + && !Q_irand(0, 10)) { + if (!(NPC->svFlags & SVF_LOCKEDENEMY)) { + // miss them + SandCreature_Attack(qtrue); + VectorCopy(NPC->currentOrigin, NPC->pos1); + TIMER_Set(NPC, "missDebounce", Q_irand(3000, 10000)); } } } -void SandCreature_Hunt( void ) -{ +void SandCreature_Hunt(void) { SandCreature_CheckAlerts(); SandCreature_CheckMovingEnts(); - //If we have somewhere to go, then do that - //FIXME: keeps chasing goalEntity even when it's already reached it...? - if ( NPCInfo->goalEntity - && SandCreature_DistSqToGoal( qfalse ) >= MIN_ATTACK_DIST_SQ ) - { + // If we have somewhere to go, then do that + // FIXME: keeps chasing goalEntity even when it's already reached it...? + if (NPCInfo->goalEntity && SandCreature_DistSqToGoal(qfalse) >= MIN_ATTACK_DIST_SQ) { ucmd.buttons |= BUTTON_WALKING; - if ( SandCreature_Move() ) - { + if (SandCreature_Move()) { SandCreature_MoveEffect(); } - } - else - { + } else { NPC_ReachedGoal(); } } -void SandCreature_Sleep( void ) -{ +void SandCreature_Sleep(void) { SandCreature_CheckAlerts(); SandCreature_CheckMovingEnts(); - //FIXME: keeps chasing goalEntity even when it's already reached it! - if ( NPCInfo->goalEntity - && SandCreature_DistSqToGoal( qfalse ) >= MIN_ATTACK_DIST_SQ ) - { + // FIXME: keeps chasing goalEntity even when it's already reached it! + if (NPCInfo->goalEntity && SandCreature_DistSqToGoal(qfalse) >= MIN_ATTACK_DIST_SQ) { ucmd.buttons |= BUTTON_WALKING; - if ( SandCreature_Move() ) - { + if (SandCreature_Move()) { SandCreature_MoveEffect(); } - } - else - { + } else { NPC_ReachedGoal(); } /* @@ -690,28 +548,24 @@ void SandCreature_Sleep( void ) */ } -void SandCreature_PushEnts() -{ - int numEnts; - gentity_t* radiusEnts[128]; - const float radius = 70; - vec3_t mins, maxs; - vec3_t smackDir; - float smackDist; +void SandCreature_PushEnts() { + int numEnts; + gentity_t *radiusEnts[128]; + const float radius = 70; + vec3_t mins, maxs; + vec3_t smackDir; + float smackDist; - for (int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { mins[i] = NPC->currentOrigin[i] - radius; maxs[i] = NPC->currentOrigin[i] + radius; } numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - for (int entIndex=0; entIndexclient || radiusEnts[entIndex]==NPC) - { + if (!radiusEnts[entIndex] || !radiusEnts[entIndex]->client || radiusEnts[entIndex] == NPC) { continue; } @@ -719,116 +573,87 @@ void SandCreature_PushEnts() //----------------------------- VectorSubtract(radiusEnts[entIndex]->currentOrigin, NPC->currentOrigin, smackDir); smackDist = VectorNormalize(smackDir); - if (smackDists.loopSound = 0; - if ( NPC->health > 0 && TIMER_Done( NPC, "breaching" ) ) - {//go back to non-solid mode - if ( NPC->contents ) - { + if (NPC->health > 0 && TIMER_Done(NPC, "breaching")) { // go back to non-solid mode + if (NPC->contents) { NPC->contents = 0; } - if ( NPC->clipmask == MASK_NPCSOLID ) - { - NPC->clipmask = CONTENTS_SOLID|CONTENTS_MONSTERCLIP; + if (NPC->clipmask == MASK_NPCSOLID) { + NPC->clipmask = CONTENTS_SOLID | CONTENTS_MONSTERCLIP; } - if ( TIMER_Done( NPC, "speaking" ) ) - { - G_SoundOnEnt( NPC, CHAN_VOICE, va( "sound/chars/sand_creature/voice%d.mp3", Q_irand( 1, 3 ) ) ); - TIMER_Set( NPC, "speaking", Q_irand( 3000, 10000 ) ); + if (TIMER_Done(NPC, "speaking")) { + G_SoundOnEnt(NPC, CHAN_VOICE, va("sound/chars/sand_creature/voice%d.mp3", Q_irand(1, 3))); + TIMER_Set(NPC, "speaking", Q_irand(3000, 10000)); } - } - else - {//still in breaching anim + } else { // still in breaching anim visible = qtrue; - //FIXME: maybe push things up/away and maybe knock people down when doing this? - //FIXME: don't turn while breaching? - //FIXME: move faster while breaching? - //NOTE: shaking now done whenever he moves + // FIXME: maybe push things up/away and maybe knock people down when doing this? + // FIXME: don't turn while breaching? + // FIXME: move faster while breaching? + // NOTE: shaking now done whenever he moves } - //FIXME: when in start and end of attack/pain anims, need ground disturbance effect around him - // NOTENOTE: someone stubbed this code in, so I figured I'd use it. The timers are all weird, ie, magic numbers that sort of work, + // FIXME: when in start and end of attack/pain anims, need ground disturbance effect around him + // NOTENOTE: someone stubbed this code in, so I figured I'd use it. The timers are all weird, ie, magic numbers that sort of work, // but maybe I'll try and figure out real values later if I have time. - if ( NPC->client->ps.legsAnim == BOTH_ATTACK1 - || NPC->client->ps.legsAnim == BOTH_ATTACK2 ) - {//FIXME: get start and end frame numbers for this effect for each of these anims - vec3_t up={0,0,1}; + if (NPC->client->ps.legsAnim == BOTH_ATTACK1 || + NPC->client->ps.legsAnim == BOTH_ATTACK2) { // FIXME: get start and end frame numbers for this effect for each of these anims + vec3_t up = {0, 0, 1}; vec3_t org; - VectorCopy( NPC->currentOrigin, org ); + VectorCopy(NPC->currentOrigin, org); org[2] -= 40; - if ( NPC->client->ps.legsAnimTimer > 3700 ) - { -// G_PlayEffect( G_EffectIndex( "env/sand_dive" ), NPC->currentOrigin, up ); - G_PlayEffect( G_EffectIndex( "env/sand_spray" ), org, up ); - } - else if ( NPC->client->ps.legsAnimTimer > 1600 && NPC->client->ps.legsAnimTimer < 1900 ) - { - G_PlayEffect( G_EffectIndex( "env/sand_spray" ), org, up ); + if (NPC->client->ps.legsAnimTimer > 3700) { + // G_PlayEffect( G_EffectIndex( "env/sand_dive" ), NPC->currentOrigin, up ); + G_PlayEffect(G_EffectIndex("env/sand_spray"), org, up); + } else if (NPC->client->ps.legsAnimTimer > 1600 && NPC->client->ps.legsAnimTimer < 1900) { + G_PlayEffect(G_EffectIndex("env/sand_spray"), org, up); } - //G_PlayEffect( G_EffectIndex( "env/sand_attack_breach" ), org, up ); + // G_PlayEffect( G_EffectIndex( "env/sand_attack_breach" ), org, up ); } - - if ( !TIMER_Done( NPC, "pain" ) ) - { + if (!TIMER_Done(NPC, "pain")) { visible = qtrue; - } - else if ( !TIMER_Done( NPC, "attacking" ) ) - { + } else if (!TIMER_Done(NPC, "attacking")) { visible = qtrue; - } - else - { - if ( NPC->activator ) - {//kill and remove the guy we ate - //FIXME: want to play ...? What was I going to say? + } else { + if (NPC->activator) { // kill and remove the guy we ate + // FIXME: want to play ...? What was I going to say? NPC->activator->health = 0; - GEntity_DieFunc( NPC->activator, NPC, NPC, 1000, MOD_MELEE, 0, HL_NONE ); - if ( NPC->activator->s.number ) - { - G_FreeEntity( NPC->activator ); - } - else - {//can't remove the player, just make him invisible + GEntity_DieFunc(NPC->activator, NPC, NPC, 1000, MOD_MELEE, 0, HL_NONE); + if (NPC->activator->s.number) { + G_FreeEntity(NPC->activator); + } else { // can't remove the player, just make him invisible NPC->client->ps.eFlags |= EF_NODRAW; } NPC->activator = NPC->enemy = NPCInfo->goalEntity = NULL; } - if ( NPC->enemy ) - { + if (NPC->enemy) { SandCreature_Chase(); - } - else if ( (level.time - NPCInfo->enemyLastSeenTime) < 5000 )//FIXME: should make this able to be variable - {//we were alerted recently, move towards there and look for footsteps, etc. + } else if ((level.time - NPCInfo->enemyLastSeenTime) < 5000) // FIXME: should make this able to be variable + { // we were alerted recently, move towards there and look for footsteps, etc. SandCreature_Hunt(); - } - else - {//no alerts, sleep and wake up only by alerts - //FIXME: keeps chasing goalEntity even when it's already reached it! + } else { // no alerts, sleep and wake up only by alerts + // FIXME: keeps chasing goalEntity even when it's already reached it! SandCreature_Sleep(); } } - NPC_UpdateAngles( qtrue, qtrue ); - if ( !visible ) - { + NPC_UpdateAngles(qtrue, qtrue); + if (!visible) { NPC->client->ps.eFlags |= EF_NODRAW; NPC->s.eFlags |= EF_NODRAW; - } - else - { + } else { NPC->client->ps.eFlags &= ~EF_NODRAW; NPC->s.eFlags &= ~EF_NODRAW; @@ -836,5 +661,5 @@ void NPC_BSSandCreature_Default( void ) } } -//FIXME: need pain behavior of sticking up through ground, writhing and screaming -//FIXME: need death anim like pain, but flopping aside and staying above ground... \ No newline at end of file +// FIXME: need pain behavior of sticking up through ground, writhing and screaming +// FIXME: need death anim like pain, but flopping aside and staying above ground... \ No newline at end of file diff --git a/code/game/AI_Seeker.cpp b/code/game/AI_Seeker.cpp index c96327eddf..ae36e61847 100644 --- a/code/game/AI_Seeker.cpp +++ b/code/game/AI_Seeker.cpp @@ -25,123 +25,102 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -extern void NPC_BSST_Patrol( void ); -extern void Boba_FireDecide( void ); -extern gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +extern void NPC_BSST_Patrol(void); +extern void Boba_FireDecide(void); +extern gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void Seeker_Strafe( void ); +void Seeker_Strafe(void); -#define VELOCITY_DECAY 0.7f +#define VELOCITY_DECAY 0.7f -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SEEKER_STRAFE_VEL 100 -#define SEEKER_STRAFE_DIS 200 -#define SEEKER_UPWARD_PUSH 32 +#define SEEKER_STRAFE_VEL 100 +#define SEEKER_STRAFE_DIS 200 +#define SEEKER_UPWARD_PUSH 32 -#define SEEKER_FORWARD_BASE_SPEED 10 -#define SEEKER_FORWARD_MULTIPLIER 2 +#define SEEKER_FORWARD_BASE_SPEED 10 +#define SEEKER_FORWARD_MULTIPLIER 2 -#define SEEKER_SEEK_RADIUS 1024 +#define SEEKER_SEEK_RADIUS 1024 //------------------------------------ -void NPC_Seeker_Precache(void) -{ +void NPC_Seeker_Precache(void) { G_SoundIndex("sound/chars/seeker/misc/fire.wav"); - G_SoundIndex( "sound/chars/seeker/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/seeker/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } //------------------------------------ -void NPC_Seeker_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( !(self->svFlags & SVF_CUSTOM_GRAVITY )) - { - G_Damage( self, NULL, NULL, vec3_origin, (float*)vec3_origin, 999, 0, MOD_FALLING ); +void NPC_Seeker_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + if (!(self->svFlags & SVF_CUSTOM_GRAVITY)) { + G_Damage(self, NULL, NULL, vec3_origin, (float *)vec3_origin, 999, 0, MOD_FALLING); } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Seeker_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); } //------------------------------------ -void Seeker_MaintainHeight( void ) -{ - float dif; +void Seeker_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPC->enemy ) - { - if (TIMER_Done( NPC, "heightChange" )) - { - TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPC->enemy) { + if (TIMER_Done(NPC, "heightChange")) { + TIMER_Set(NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + Q_flrand( NPC->enemy->maxs[2]/2, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + Q_flrand(NPC->enemy->maxs[2] / 2, NPC->enemy->maxs[2] + 8)) - NPC->currentOrigin[2]; - float difFactor = 1.0f; - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPC, "flameTime" ) ) - { + float difFactor = 1.0f; + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + if (TIMER_Done(NPC, "flameTime")) { difFactor = 10.0f; } } // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2*difFactor ) - { - if ( fabs( dif ) > 24*difFactor ) - { - dif = ( dif < 0 ? -24*difFactor : 24*difFactor ); + if (fabs(dif) > 2 * difFactor) { + if (fabs(dif) > 24 * difFactor) { + dif = (dif < 0 ? -24 * difFactor : 24 * difFactor); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - NPC->client->ps.velocity[2] *= Q_flrand( 0.85f, 3.0f ); + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + NPC->client->ps.velocity[2] *= Q_flrand(0.85f, 3.0f); } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } @@ -150,103 +129,86 @@ void Seeker_MaintainHeight( void ) } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } //------------------------------------ -void Seeker_Strafe( void ) -{ - int side; - vec3_t end, right, dir; - trace_t tr; - - if ( Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client ) - { +void Seeker_Strafe(void) { + int side; + vec3_t end, right, dir; + trace_t tr; + + if (Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client) { // Do a regular style strafe - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonably valid - side = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, SEEKER_STRAFE_DIS * side, right, end ); + side = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, SEEKER_STRAFE_DIS * side, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { + if (tr.fraction > 0.9f) { float vel = SEEKER_STRAFE_VEL; float upPush = SEEKER_UPWARD_PUSH; - if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - { - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); - } - else - { + if (NPC->client->NPC_class != CLASS_BOBAFETT) { + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); + } else { vel *= 3.0f; upPush *= 4.0f; } - VectorMA( NPC->client->ps.velocity, vel*side, right, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, vel * side, right, NPC->client->ps.velocity); // Add a slight upward push NPC->client->ps.velocity[2] += upPush; NPCInfo->standTime = level.time + 1000 + Q_flrand(0.0f, 1.0f) * 500; } - } - else - { + } else { // Do a strafe to try and keep on the side of their enemy - AngleVectors( NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL ); + AngleVectors(NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL); // Pick a random side - side = ( rand() & 1 ) ? -1 : 1; - float stDis = SEEKER_STRAFE_DIS; - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { + side = (rand() & 1) ? -1 : 1; + float stDis = SEEKER_STRAFE_DIS; + if (NPC->client->NPC_class == CLASS_BOBAFETT) { stDis *= 2.0f; } - VectorMA( NPC->enemy->currentOrigin, stDis * side, right, end ); + VectorMA(NPC->enemy->currentOrigin, stDis * side, right, end); // then add a very small bit of random in front of/behind the player action - VectorMA( end, Q_flrand(-1.0f, 1.0f) * 25, dir, end ); + VectorMA(end, Q_flrand(-1.0f, 1.0f) * 25, dir, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorSubtract( tr.endpos, NPC->currentOrigin, dir ); + if (tr.fraction > 0.9f) { + VectorSubtract(tr.endpos, NPC->currentOrigin, dir); dir[2] *= 0.25; // do less upward change - float dis = VectorNormalize( dir ); + float dis = VectorNormalize(dir); // Try to move the desired enemy side - VectorMA( NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity); float upPush = SEEKER_UPWARD_PUSH; - if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - { - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); - } - else - { + if (NPC->client->NPC_class != CLASS_BOBAFETT) { + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); + } else { upPush *= 4.0f; } @@ -259,33 +221,28 @@ void Seeker_Strafe( void ) } //------------------------------------ -void Seeker_Hunt( qboolean visible, qboolean advance ) -{ - float speed; - vec3_t forward; +void Seeker_Hunt(qboolean visible, qboolean advance) { + float speed; + vec3_t forward; - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Seeker_Strafe(); return; } } // If we don't want to advance, stop here - if ( advance == qfalse ) - { + if (advance == qfalse) { return; } // Only try and navigate if the player is visible - if ( visible == qfalse ) - { + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 24; @@ -293,33 +250,30 @@ void Seeker_Hunt( qboolean visible, qboolean advance ) NPC_MoveToGoal(qtrue); return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SEEKER_FORWARD_BASE_SPEED + SEEKER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } //------------------------------------ -void Seeker_Fire( void ) -{ - vec3_t dir, enemy_org, muzzle; - gentity_t *missile; +void Seeker_Fire(void) { + vec3_t dir, enemy_org, muzzle; + gentity_t *missile; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - VectorSubtract( enemy_org, NPC->currentOrigin, dir ); - VectorNormalize( dir ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + VectorSubtract(enemy_org, NPC->currentOrigin, dir); + VectorNormalize(dir); // move a bit forward in the direction we shall shoot in so that the bolt doesn't poke out the other side of the seeker - VectorMA( NPC->currentOrigin, 15, dir, muzzle ); + VectorMA(NPC->currentOrigin, 15, dir, muzzle); - missile = CreateMissile( muzzle, dir, 1000, 10000, NPC ); + missile = CreateMissile(muzzle, dir, 1000, 10000, NPC); - G_PlayEffect( "blaster/muzzle_flash", NPC->currentOrigin, dir ); + G_PlayEffect("blaster/muzzle_flash", NPC->currentOrigin, dir); missile->classname = "blaster"; missile->s.weapon = WP_BLASTER; @@ -331,108 +285,92 @@ void Seeker_Fire( void ) } //------------------------------------ -void Seeker_Ranged( qboolean visible, qboolean advance ) -{ - if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( NPC->count > 0 ) - { - if ( TIMER_Done( NPC, "attackDelay" )) // Attack? +void Seeker_Ranged(qboolean visible, qboolean advance) { + if (NPC->client->NPC_class != CLASS_BOBAFETT) { + if (NPC->count > 0) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 2500 )); + TIMER_Set(NPC, "attackDelay", Q_irand(250, 2500)); Seeker_Fire(); NPC->count--; } - } - else - { + } else { // out of ammo, so let it die...give it a push up so it can fall more and blow up on impact - // NPC->client->ps.gravity = 900; - // NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; - // NPC->client->ps.velocity[2] += 16; - G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN ); + // NPC->client->ps.gravity = 900; + // NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; + // NPC->client->ps.velocity[2] += 16; + G_Damage(NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN); } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); } } //------------------------------------ -void Seeker_Attack( void ) -{ +void Seeker_Attack(void) { // Always keep a good height off the ground Seeker_MaintainHeight(); // Rate our distance to the target, and our visibilty - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - advance = (qboolean)(distance>(200.0f*200.0f)); + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + advance = (qboolean)(distance > (200.0f * 200.0f)); } // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); return; } } - Seeker_Ranged( visible, advance ); + Seeker_Ranged(visible, advance); } //------------------------------------ -void Seeker_FindEnemy( void ) -{ - int numFound; - float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; - vec3_t mins, maxs; - gentity_t *entityList[MAX_GENTITIES], *ent, *best = NULL; +void Seeker_FindEnemy(void) { + int numFound; + float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; + vec3_t mins, maxs; + gentity_t *entityList[MAX_GENTITIES], *ent, *best = NULL; - VectorSet( maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS); + VectorScale(maxs, -1, mins); - numFound = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numFound = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( int i = 0 ; i < numFound ; i++ ) - { + for (int i = 0; i < numFound; i++) { ent = entityList[i]; - if ( ent->s.number == NPC->s.number || !ent->client || !ent->NPC || ent->health <= 0 || !ent->inuse ) - { + if (ent->s.number == NPC->s.number || !ent->client || !ent->NPC || ent->health <= 0 || !ent->inuse) { continue; } - if ( ent->client->playerTeam == NPC->client->playerTeam || ent->client->playerTeam == TEAM_NEUTRAL ) // don't attack same team or bots + if (ent->client->playerTeam == NPC->client->playerTeam || ent->client->playerTeam == TEAM_NEUTRAL) // don't attack same team or bots { continue; } // try to find the closest visible one - if ( !NPC_ClearLOS( ent )) - { + if (!NPC_ClearLOS(ent)) { continue; } - dis = DistanceHorizontalSquared( NPC->currentOrigin, ent->currentOrigin ); + dis = DistanceHorizontalSquared(NPC->currentOrigin, ent->currentOrigin); - if ( dis <= bestDis ) - { + if (dis <= bestDis) { bestDis = dis; best = ent; } } - if ( best ) - { + if (best) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi @@ -441,115 +379,88 @@ void Seeker_FindEnemy( void ) } //------------------------------------ -void Seeker_FollowPlayer( void ) -{ +void Seeker_FollowPlayer(void) { Seeker_MaintainHeight(); - float dis = DistanceHorizontalSquared( NPC->currentOrigin, g_entities[0].currentOrigin ); - vec3_t pt, dir; + float dis = DistanceHorizontalSquared(NPC->currentOrigin, g_entities[0].currentOrigin); + vec3_t pt, dir; - float minDistSqr = MIN_DISTANCE_SQR; + float minDistSqr = MIN_DISTANCE_SQR; - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPC, "flameTime" ) ) - { - minDistSqr = 200*200; + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + if (TIMER_Done(NPC, "flameTime")) { + minDistSqr = 200 * 200; } } - if ( dis < minDistSqr ) - { + if (dis < minDistSqr) { // generally circle the player closely till we take an enemy..this is our target point - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { - pt[0] = g_entities[0].currentOrigin[0] + cos( level.time * 0.001f + NPC->random ) * 250; - pt[1] = g_entities[0].currentOrigin[1] + sin( level.time * 0.001f + NPC->random ) * 250; - if ( NPC->client->jetPackTime < level.time ) - { + if (NPC->client->NPC_class == CLASS_BOBAFETT) { + pt[0] = g_entities[0].currentOrigin[0] + cos(level.time * 0.001f + NPC->random) * 250; + pt[1] = g_entities[0].currentOrigin[1] + sin(level.time * 0.001f + NPC->random) * 250; + if (NPC->client->jetPackTime < level.time) { pt[2] = NPC->currentOrigin[2] - 64; - } - else - { + } else { pt[2] = g_entities[0].currentOrigin[2] + 200; } - } - else - { - pt[0] = g_entities[0].currentOrigin[0] + cos( level.time * 0.001f + NPC->random ) * 56; - pt[1] = g_entities[0].currentOrigin[1] + sin( level.time * 0.001f + NPC->random ) * 56; + } else { + pt[0] = g_entities[0].currentOrigin[0] + cos(level.time * 0.001f + NPC->random) * 56; + pt[1] = g_entities[0].currentOrigin[1] + sin(level.time * 0.001f + NPC->random) * 56; pt[2] = g_entities[0].currentOrigin[2] + 40; } - VectorSubtract( pt, NPC->currentOrigin, dir ); - VectorMA( NPC->client->ps.velocity, 0.8f, dir, NPC->client->ps.velocity ); - } - else - { - if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPC, "seekerhiss" )) - { - TIMER_Set( NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000 ); - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + VectorSubtract(pt, NPC->currentOrigin, dir); + VectorMA(NPC->client->ps.velocity, 0.8f, dir, NPC->client->ps.velocity); + } else { + if (NPC->client->NPC_class != CLASS_BOBAFETT) { + if (TIMER_Done(NPC, "seekerhiss")) { + TIMER_Set(NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000); + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); } } // Hey come back! NPCInfo->goalEntity = &g_entities[0]; NPCInfo->goalRadius = 32; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); NPC->owner = &g_entities[0]; } - if ( NPCInfo->enemyCheckDebounceTime < level.time ) - { + if (NPCInfo->enemyCheckDebounceTime < level.time) { // check twice a second to find a new enemy Seeker_FindEnemy(); NPCInfo->enemyCheckDebounceTime = level.time + 500; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } //------------------------------------ -void NPC_BSSeeker_Default( void ) -{ - if ( in_camera ) - { - if ( NPC->client->NPC_class != CLASS_BOBAFETT ) - { +void NPC_BSSeeker_Default(void) { + if (in_camera) { + if (NPC->client->NPC_class != CLASS_BOBAFETT) { // cameras make me commit suicide.... - G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN ); + G_Damage(NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN); } } - if ( NPC->random == 0.0f ) - { + if (NPC->random == 0.0f) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi } - if ( NPC->enemy && NPC->enemy->health && NPC->enemy->inuse ) - { - if ( NPC->client->NPC_class != CLASS_BOBAFETT - && ( NPC->enemy->s.number == 0 || ( NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_SEEKER )) ) - { - //hacked to never take the player as an enemy, even if the player shoots at it + if (NPC->enemy && NPC->enemy->health && NPC->enemy->inuse) { + if (NPC->client->NPC_class != CLASS_BOBAFETT && (NPC->enemy->s.number == 0 || (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_SEEKER))) { + // hacked to never take the player as an enemy, even if the player shoots at it NPC->enemy = NULL; - } - else - { + } else { Seeker_Attack(); - if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); } return; } - } - else if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { + } else if (NPC->client->NPC_class == CLASS_BOBAFETT) { NPC_BSST_Patrol(); return; } diff --git a/code/game/AI_Sentry.cpp b/code/game/AI_Sentry.cpp index d24c1f9acd..a7506aa49e 100644 --- a/code/game/AI_Sentry.cpp +++ b/code/game/AI_Sentry.cpp @@ -25,24 +25,23 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +extern gitem_t *FindItemForAmmo(ammo_t ammo); -#define MIN_DISTANCE 256 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 256 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SENTRY_FORWARD_BASE_SPEED 10 -#define SENTRY_FORWARD_MULTIPLIER 5 +#define SENTRY_FORWARD_BASE_SPEED 10 +#define SENTRY_FORWARD_MULTIPLIER 5 -#define SENTRY_VELOCITY_DECAY 0.85f -#define SENTRY_STRAFE_VEL 256 -#define SENTRY_STRAFE_DIS 200 -#define SENTRY_UPWARD_PUSH 32 -#define SENTRY_HOVER_HEIGHT 24 +#define SENTRY_VELOCITY_DECAY 0.85f +#define SENTRY_STRAFE_VEL 256 +#define SENTRY_STRAFE_DIS 200 +#define SENTRY_UPWARD_PUSH 32 +#define SENTRY_HOVER_HEIGHT 24 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -56,24 +55,22 @@ enum NPC_Sentry_Precache ------------------------- */ -void NPC_Sentry_Precache(void) -{ - G_SoundIndex( "sound/chars/sentry/misc/sentry_explo" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_pain" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_open" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_close" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); - - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/sentry/misc/talk%d", i ) ); +void NPC_Sentry_Precache(void) { + G_SoundIndex("sound/chars/sentry/misc/sentry_explo"); + G_SoundIndex("sound/chars/sentry/misc/sentry_pain"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_open"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_close"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); + + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/sentry/misc/talk%d", i)); } - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("env/med_explode"); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } /* @@ -81,13 +78,12 @@ void NPC_Sentry_Precache(void) sentry_use ================ */ -void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void sentry_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); self->flags &= ~FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // self->NPC->localState = LSTATE_WAKEUP; self->NPC->localState = LSTATE_ACTIVE; } @@ -96,30 +92,28 @@ void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) NPC_Sentry_Pain ------------------------- */ -void NPC_Sentry_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_Sentry_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->burstCount = 0; - TIMER_Set( self, "attackDelay", Q_irand( 9000, 12000) ); + TIMER_Set(self, "attackDelay", Q_irand(9000, 12000)); self->flags |= FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_SoundOnEnt( self, CHAN_AUTO, "sound/chars/sentry/misc/sentry_pain" ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_SoundOnEnt(self, CHAN_AUTO, "sound/chars/sentry/misc/sentry_pain"); self->NPC->localState = LSTATE_ACTIVE; } // You got hit, go after the enemy -// if (self->NPC->localState == LSTATE_ASLEEP) -// { -// G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); -// -// self->flags &= ~FL_SHIELDED; -// NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; -// } + // if (self->NPC->localState == LSTATE_ASLEEP) + // { + // G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); + // + // self->flags &= ~FL_SHIELDED; + // NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // self->NPC->localState = LSTATE_WAKEUP; + // } } /* @@ -127,40 +121,31 @@ void NPC_Sentry_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, c Sentry_Fire ------------------------- */ -void Sentry_Fire (void) -{ - vec3_t muzzle; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Sentry_Fire(void) { + vec3_t muzzle; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; NPC->flags &= ~FL_SHIELDED; - if ( NPCInfo->localState == LSTATE_POWERING_UP ) - { - if ( TIMER_Done( NPC, "powerup" )) - { + if (NPCInfo->localState == LSTATE_POWERING_UP) { + if (TIMER_Done(NPC, "powerup")) { NPCInfo->localState = LSTATE_ATTACKING; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // can't do anything right now return; } - } - else if ( NPCInfo->localState == LSTATE_ACTIVE ) - { + } else if (NPCInfo->localState == LSTATE_ACTIVE) { NPCInfo->localState = LSTATE_POWERING_UP; - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_open" ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "powerup", 250 ); + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_open"); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "powerup", 250); return; - } - else if ( NPCInfo->localState != LSTATE_ATTACKING ) - { + } else if (NPCInfo->localState != LSTATE_ATTACKING) { // bad because we are uninitialized NPCInfo->localState = LSTATE_ACTIVE; return; @@ -168,8 +153,7 @@ void Sentry_Fire (void) // Which muzzle to fire from? int which = NPCInfo->burstCount % 3; - switch( which ) - { + switch (which) { case 0: bolt = NPC->genericBolt1; break; @@ -181,19 +165,17 @@ void Sentry_Fire (void) bolt = NPC->genericBolt3; } - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle); - AngleVectors( NPC->currentAngles, forward, vright, up ); -// G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); + AngleVectors(NPC->currentAngles, forward, vright, up); + // G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); - G_PlayEffect( "bryar/muzzle_flash", muzzle, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle, forward); - missile = CreateMissile( muzzle, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -207,13 +189,10 @@ void Sentry_Fire (void) missile->damage = 5; // now scale for difficulty - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { NPC->attackDebounceTime += 200; missile->damage = 1; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { NPC->attackDebounceTime += 100; missile->damage = 3; } @@ -224,100 +203,80 @@ void Sentry_Fire (void) Sentry_MaintainHeight ------------------------- */ -void Sentry_MaintainHeight( void ) -{ - float dif; +void Sentry_MaintainHeight(void) { + float dif; - NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference - dif = (NPC->enemy->currentOrigin[2]+NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 8) { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + dif = (dif < 0 ? -24 : 24); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if (goal) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction to Z - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); } /* @@ -325,22 +284,17 @@ void Sentry_MaintainHeight( void ) Sentry_Idle ------------------------- */ -void Sentry_Idle( void ) -{ +void Sentry_Idle(void) { Sentry_MaintainHeight(); // Is he waking up? - if (NPCInfo->localState == LSTATE_WAKEUP) - { - if (NPC->client->ps.torsoAnimTimer<=0) - { + if (NPCInfo->localState == LSTATE_WAKEUP) { + if (NPC->client->ps.torsoAnimTimer <= 0) { NPCInfo->scriptFlags |= SCF_LOOK_FOR_ENEMIES; NPCInfo->burstCount = 0; } - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->flags |= FL_SHIELDED; NPC_BSIdle(); @@ -352,25 +306,23 @@ void Sentry_Idle( void ) Sentry_Strafe ------------------------- */ -void Sentry_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Sentry_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, SENTRY_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, SENTRY_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, (EG2_Collision)0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push NPC->client->ps.velocity[2] += SENTRY_UPWARD_PUSH; @@ -386,44 +338,38 @@ void Sentry_Strafe( void ) Sentry_Hunt ------------------------- */ -void Sentry_Hunt( qboolean visible, qboolean advance ) -{ - float speed; - vec3_t forward; +void Sentry_Hunt(qboolean visible, qboolean advance) { + float speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Sentry_Strafe(); return; } } - //If we don't want to advance, stop here - if ( !advance && visible ) + // If we don't want to advance, stop here + if (!advance && visible) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; NPC_MoveToGoal(qtrue); return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SENTRY_FORWARD_BASE_SPEED + SENTRY_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } /* @@ -431,35 +377,27 @@ void Sentry_Hunt( qboolean visible, qboolean advance ) Sentry_RangedAttack ------------------------- */ -void Sentry_RangedAttack( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) && NPC->attackDebounceTime < level.time && visible ) // Attack? +void Sentry_RangedAttack(qboolean visible, qboolean advance) { + if (TIMER_Done(NPC, "attackDelay") && NPC->attackDebounceTime < level.time && visible) // Attack? { - if ( NPCInfo->burstCount > 6 ) - { - if ( !NPC->fly_sound_debounce_time ) - {//delay closing down to give the player an opening - NPC->fly_sound_debounce_time = level.time + Q_irand( 500, 2000 ); - } - else if ( NPC->fly_sound_debounce_time < level.time ) - { + if (NPCInfo->burstCount > 6) { + if (!NPC->fly_sound_debounce_time) { // delay closing down to give the player an opening + NPC->fly_sound_debounce_time = level.time + Q_irand(500, 2000); + } else if (NPC->fly_sound_debounce_time < level.time) { NPCInfo->localState = LSTATE_ACTIVE; NPC->fly_sound_debounce_time = NPCInfo->burstCount = 0; - TIMER_Set( NPC, "attackDelay", Q_irand( 2000, 3500) ); + TIMER_Set(NPC, "attackDelay", Q_irand(2000, 3500)); NPC->flags |= FL_SHIELDED; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close" ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close"); } - } - else - { + } else { Sentry_Fire(); } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); } } @@ -468,97 +406,85 @@ void Sentry_RangedAttack( qboolean visible, qboolean advance ) Sentry_AttackDecision ------------------------- */ -void Sentry_AttackDecision( void ) -{ +void Sentry_AttackDecision(void) { // Always keep a good height off the ground Sentry_MaintainHeight(); - NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // He's dead. - if (NPC->enemy->health<1) - { + if (NPC->enemy->health < 1) { NPC->enemy = NULL; Sentry_Idle(); return; } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Sentry_Idle(); return; } // Rate our distance to the target and visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); return; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - Sentry_RangedAttack( visible, advance ); + Sentry_RangedAttack(visible, advance); } -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); /* ------------------------- NPC_Sentry_Patrol ------------------------- */ -void NPC_Sentry_Patrol( void ) -{ +void NPC_Sentry_Patrol(void) { Sentry_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (NPC_CheckPlayerTeamStealth()) { + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( UpdateGoal() ) - { - //start loop sound once we move + if (UpdateGoal()) { + // start loop sound once we move ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -566,24 +492,17 @@ void NPC_Sentry_Patrol( void ) NPC_BSSentry_Default ------------------------- */ -void NPC_BSSentry_Default( void ) -{ - if ( NPC->targetname ) - { +void NPC_BSSentry_Default(void) { + if (NPC->targetname) { NPC->e_UseFunc = useF_sentry_use; } - if (( NPC->enemy ) && (NPCInfo->localState != LSTATE_WAKEUP)) - { + if ((NPC->enemy) && (NPCInfo->localState != LSTATE_WAKEUP)) { // Don't attack if waking up or if no enemy Sentry_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { NPC_Sentry_Patrol(); - } - else - { + } else { Sentry_Idle(); } } diff --git a/code/game/AI_Sniper.cpp b/code/game/AI_Sniper.cpp index 6dae655077..93c4fe014e 100644 --- a/code/game/AI_Sniper.cpp +++ b/code/game/AI_Sniper.cpp @@ -26,105 +26,97 @@ along with this program; if not, see . #include "g_navigator.h" #include "g_functions.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern void Saboteur_Cloak( gentity_t *self ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean FlyingCreature(gentity_t *ent); +extern void Saboteur_Cloak(gentity_t *self); -#define SPF_NO_HIDE 2 +#define SPF_NO_HIDE 2 -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -extern void NPC_Tusken_Taunt( void ); -qboolean NPC_CheckPlayerTeamStealth( void ); +extern void NPC_Tusken_Taunt(void); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; static qboolean faceEnemy; static qboolean doMove; static qboolean shoot; -static float enemyDist; +static float enemyDist; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Sniper_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "taunting", 0 ); +void Sniper_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "taunting", 0); } -void NPC_Sniper_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Sniper_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Sniper_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod ) -{ +void NPC_Sniper_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod) { self->NPC->localState = LSTATE_UNDERFIRE; - if ( self->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Decloak( self ); + if (self->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Decloak(self); } - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -134,9 +126,8 @@ ST_HoldPosition ------------------------- */ -static void Sniper_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); +static void Sniper_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); NPCInfo->goalEntity = NULL; /*if ( TIMER_Done( NPC, "stand" ) ) @@ -152,52 +143,46 @@ ST_Move ------------------------- */ -static qboolean Sniper_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always doMove straight toward our goal - - qboolean moved = NPC_MoveToGoal( qtrue ); -// navInfo_t info; - - //Get the doMove info -// NAV_GetLastMove( info ); - - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! -// if ( info.flags & NIF_COLLISION ) -// { -// if ( info.blocker == NPC->enemy ) -// { -// Sniper_HoldPosition(); -// } -// } - - //If our doMove failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); +static qboolean Sniper_Move(void) { + NPCInfo->combatMove = qtrue; // always doMove straight toward our goal + + qboolean moved = NPC_MoveToGoal(qtrue); + // navInfo_t info; + + // Get the doMove info + // NAV_GetLastMove( info ); + + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + // if ( info.flags & NIF_COLLISION ) + // { + // if ( info.blocker == NPC->enemy ) + // { + // Sniper_HoldPosition(); + // } + // } + + // If our doMove failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); return moved; } } - //just hang here + // just hang here Sniper_HoldPosition(); } @@ -210,80 +195,65 @@ NPC_BSSniper_Patrol ------------------------- */ -void NPC_BSSniper_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? +void NPC_BSSniper_Patrol(void) { // FIXME: pick up on bodies of dead buddies? NPC->count = 0; - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 )//&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0) //&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) { - //NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + // NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( (6-NPCInfo->stats.aim)*100, (6-NPCInfo->stats.aim)*500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand((6 - NPCInfo->stats.aim) * 100, (6 - NPCInfo->stats.aim) * 500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - //FIXME: sound? - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + // FIXME: sound? + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies flag - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies flag + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -292,14 +262,13 @@ void NPC_BSSniper_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -333,123 +302,100 @@ ST_CheckMoveState ------------------------- */ -static void Sniper_CheckMoveState( void ) -{ - //See if we're a scout - if ( !(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) +static void Sniper_CheckMoveState(void) { + // See if we're a scout + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { doMove = qfalse; return; } } - //See if we're running away - else if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPC, "flee" ) ) - { + // See if we're running away + else if (NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPC, "flee")) { NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy = qfalse; } - } - else if ( NPCInfo->squadState == SQUAD_IDLE ) - { - if ( !NPCInfo->goalEntity ) - { + } else if (NPCInfo->squadState == SQUAD_IDLE) { + if (!NPCInfo->goalEntity) { doMove = qfalse; return; } } - if ( !TIMER_Done( NPC, "taunting" ) ) - {//no doMove while taunting + if (!TIMER_Done(NPC, "taunting")) { // no doMove while taunting doMove = qfalse; return; } - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || - ( NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - { - //int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Cloak( NPC ); + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || (NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Cloak(NPC); } - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - //newSquadState = SQUAD_COVER; + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( (6-NPCInfo->stats.aim)*50, (6-NPCInfo->stats.aim)*100 ) ); //FIXME: Slant for difficulty levels, too? - //don't do something else just yet - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand((6 - NPCInfo->stats.aim) * 50, (6 - NPCInfo->stats.aim) * 100)); // FIXME: Slant for difficulty levels, too? + // don't do something else just yet + TIMER_Set(NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(4000, 8000)); } } -static void Sniper_ResolveBlockedShot( void ) -{ - if ( TIMER_Done( NPC, "duck" ) ) - {//we're not ducking - if ( TIMER_Done( NPC, "roamTime" ) ) - {//not roaming - //FIXME: try to find another spot from which to hit the enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && (!NPCInfo->goalEntity || NPCInfo->goalEntity == NPC->enemy) ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); +static void Sniper_ResolveBlockedShot(void) { + if (TIMER_Done(NPC, "duck")) { // we're not ducking + if (TIMER_Done(NPC, "roamTime")) { // not roaming + // FIXME: try to find another spot from which to hit the enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && (!NPCInfo->goalEntity || NPCInfo->goalEntity == NPC->enemy)) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = + NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); - TIMER_Set( NPC, "duck", -1 ); - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Decloak( NPC ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + TIMER_Set(NPC, "duck", -1); + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Decloak(NPC); } - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); return; } } @@ -479,188 +425,148 @@ ST_CheckFireState ------------------------- */ -static void Sniper_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void Sniper_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - if ( !TIMER_Done( NPC, "taunting" ) ) - {//no shoot while taunting + if (!TIMER_Done(NPC, "taunting")) { // no shoot while taunting return; } - //continue to fire on their last position - if ( !Q_irand( 0, 1 ) - && NPCInfo->enemyLastSeenTime - && level.time - NPCInfo->enemyLastSeenTime < ((5-NPCInfo->stats.aim)*1000) )//FIXME: incorporate skill too? + // continue to fire on their last position + if (!Q_irand(0, 1) && NPCInfo->enemyLastSeenTime && + level.time - NPCInfo->enemyLastSeenTime < ((5 - NPCInfo->stats.aim) * 1000)) // FIXME: incorporate skill too? { - if ( !VectorCompare( vec3_origin, NPCInfo->enemyLastSeenLocation ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!VectorCompare(vec3_origin, NPCInfo->enemyLastSeenLocation)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); - VectorNormalize( dir ); + VectorNormalize(dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; - //faceEnemy = qfalse; + // faceEnemy = qfalse; } return; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 10000 ) - {//next time we see him, we'll miss few times first + } else if (level.time - NPCInfo->enemyLastSeenTime > 10000) { // next time we see him, we'll miss few times first NPC->count = 0; } } -qboolean Sniper_EvaluateShot( int hit ) -{ - if ( !NPC->enemy ) - { +qboolean Sniper_EvaluateShot(int hit) { + if (!NPC->enemy) { return qfalse; } gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPC->s.weapon == WP_EMPLACED_GUN) ) - || ( hitEnt && (hitEnt->svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && ((hitEnt->svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || NPC->s.weapon == WP_EMPLACED_GUN)) || + (hitEnt && (hitEnt->svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; } -void Sniper_FaceEnemy( void ) -{ - //FIXME: the ones behind kill holes are facing some arbitrary direction and not firing - //FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? - //FIXME: need to give designers option to make them not miss first few shots - if ( NPC->enemy ) - { - vec3_t muzzle, target, angles, forward, right, up; - //Get the positions - AngleVectors( NPC->client->ps.viewangles, forward, right, up ); - CalcMuzzlePoint( NPC, forward, right, up, muzzle, 0 ); - //CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - CalcEntitySpot( NPC->enemy, SPOT_ORIGIN, target ); - - if ( enemyDist > 65536 && NPCInfo->stats.aim < 5 )//is 256 squared, was 16384 (128*128) +void Sniper_FaceEnemy(void) { + // FIXME: the ones behind kill holes are facing some arbitrary direction and not firing + // FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? + // FIXME: need to give designers option to make them not miss first few shots + if (NPC->enemy) { + vec3_t muzzle, target, angles, forward, right, up; + // Get the positions + AngleVectors(NPC->client->ps.viewangles, forward, right, up); + CalcMuzzlePoint(NPC, forward, right, up, muzzle, 0); + // CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC->enemy, SPOT_ORIGIN, target); + + if (enemyDist > 65536 && NPCInfo->stats.aim < 5) // is 256 squared, was 16384 (128*128) { - if ( NPC->count < (5-NPCInfo->stats.aim) ) - {//miss a few times first - if ( shoot && TIMER_Done( NPC, "attackDelay" ) && level.time >= NPCInfo->shotTime ) - {//ready to fire again - qboolean aimError = qfalse; - qboolean hit = qtrue; - int tryMissCount = 0; - trace_t trace; - - GetAnglesForDirection( muzzle, target, angles ); - AngleVectors( angles, forward, right, up ); - - while ( hit && tryMissCount < 10 ) - { + if (NPC->count < (5 - NPCInfo->stats.aim)) { // miss a few times first + if (shoot && TIMER_Done(NPC, "attackDelay") && level.time >= NPCInfo->shotTime) { // ready to fire again + qboolean aimError = qfalse; + qboolean hit = qtrue; + int tryMissCount = 0; + trace_t trace; + + GetAnglesForDirection(muzzle, target, angles); + AngleVectors(angles, forward, right, up); + + while (hit && tryMissCount < 10) { tryMissCount++; - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { aimError = qtrue; - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPC->enemy->maxs[2]*Q_flrand(1.5, 4), right, target ); - } - else - { - VectorMA( target, NPC->enemy->mins[2]*Q_flrand(1.5, 4), right, target ); + if (!Q_irand(0, 1)) { + VectorMA(target, NPC->enemy->maxs[2] * Q_flrand(1.5, 4), right, target); + } else { + VectorMA(target, NPC->enemy->mins[2] * Q_flrand(1.5, 4), right, target); } } - if ( !aimError || !Q_irand( 0, 1 ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPC->enemy->maxs[2]*Q_flrand(1.5, 4), up, target ); - } - else - { - VectorMA( target, NPC->enemy->mins[2]*Q_flrand(1.5, 4), up, target ); + if (!aimError || !Q_irand(0, 1)) { + if (!Q_irand(0, 1)) { + VectorMA(target, NPC->enemy->maxs[2] * Q_flrand(1.5, 4), up, target); + } else { + VectorMA(target, NPC->enemy->mins[2] * Q_flrand(1.5, 4), up, target); } } - gi.trace( &trace, muzzle, vec3_origin, vec3_origin, target, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - hit = Sniper_EvaluateShot( trace.entityNum ); + gi.trace(&trace, muzzle, vec3_origin, vec3_origin, target, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + hit = Sniper_EvaluateShot(trace.entityNum); } NPC->count++; - } - else - { - if ( !enemyLOS ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else { + if (!enemyLOS) { + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else - {//based on distance, aim value, difficulty and enemy movement, miss - //FIXME: incorporate distance as a factor? - int missFactor = 8-(NPCInfo->stats.aim+g_spskill->integer) * 3; - if ( missFactor > ENEMY_POS_LAG_STEPS ) - { + } else { // based on distance, aim value, difficulty and enemy movement, miss + // FIXME: incorporate distance as a factor? + int missFactor = 8 - (NPCInfo->stats.aim + g_spskill->integer) * 3; + if (missFactor > ENEMY_POS_LAG_STEPS) { missFactor = ENEMY_POS_LAG_STEPS; + } else if (missFactor < 0) { //??? + missFactor = 0; } - else if ( missFactor < 0 ) - {//??? - missFactor = 0 ; - } - VectorCopy( NPCInfo->enemyLaggedPos[missFactor], target ); + VectorCopy(NPCInfo->enemyLaggedPos[missFactor], target); } - GetAnglesForDirection( muzzle, target, angles ); - } - else - { - target[2] += Q_flrand( 0, NPC->enemy->maxs[2] ); - //CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); - GetAnglesForDirection( muzzle, target, angles ); + GetAnglesForDirection(muzzle, target, angles); + } else { + target[2] += Q_flrand(0, NPC->enemy->maxs[2]); + // CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); + GetAnglesForDirection(muzzle, target, angles); } - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void Sniper_UpdateEnemyPos( void ) -{ +void Sniper_UpdateEnemyPos(void) { int index; - for ( int i = MAX_ENEMY_POS_LAG-ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL ) - { - index = i/ENEMY_POS_LAG_INTERVAL; - if ( !index ) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, NPCInfo->enemyLaggedPos[index] ); - NPCInfo->enemyLaggedPos[index][2] -= Q_flrand( 2, 16 ); - } - else - { - VectorCopy( NPCInfo->enemyLaggedPos[index-1], NPCInfo->enemyLaggedPos[index] ); + for (int i = MAX_ENEMY_POS_LAG - ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL) { + index = i / ENEMY_POS_LAG_INTERVAL; + if (!index) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD_LEAN, NPCInfo->enemyLaggedPos[index]); + NPCInfo->enemyLaggedPos[index][2] -= Q_flrand(2, 16); + } else { + VectorCopy(NPCInfo->enemyLaggedPos[index - 1], NPCInfo->enemyLaggedPos[index]); } } } @@ -671,45 +577,39 @@ NPC_BSSniper_Attack ------------------------- */ -void Sniper_StartHide( void ) -{ - int duckTime = Q_irand( 2000, 5000 ); +void Sniper_StartHide(void) { + int duckTime = Q_irand(2000, 5000); - TIMER_Set( NPC, "duck", duckTime ); - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Cloak( NPC ); + TIMER_Set(NPC, "duck", duckTime); + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Cloak(NPC); } - TIMER_Set( NPC, "watch", 500 ); - TIMER_Set( NPC, "attackDelay", duckTime + Q_irand( 500, 2000 ) ); + TIMER_Set(NPC, "watch", 500); + TIMER_Set(NPC, "attackDelay", duckTime + Q_irand(500, 2000)); } -void NPC_BSSniper_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSSniper_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { - NPC_BSSniper_Patrol();//FIXME: or patrol? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSSniper_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } @@ -717,65 +617,56 @@ void NPC_BSSniper_Attack( void ) doMove = qtrue; faceEnemy = qfalse; shoot = qfalse; - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - if ( enemyDist < 16384 )//128 squared - {//too close, so switch to primary fire - if ( NPC->client->ps.weapon == WP_DISRUPTOR - || NPC->client->ps.weapon == WP_TUSKEN_RIFLE ) - {//sniping... should be assumed - if ( NPCInfo->scriptFlags & SCF_ALT_FIRE ) - {//use primary fire - trace_t trace; - gi.trace ( &trace, NPC->enemy->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->currentOrigin, NPC->enemy->s.number, NPC->enemy->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->s.number ) ) - {//he can get right to me + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + if (enemyDist < 16384) // 128 squared + { // too close, so switch to primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR || NPC->client->ps.weapon == WP_TUSKEN_RIFLE) { // sniping... should be assumed + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { // use primary fire + trace_t trace; + gi.trace(&trace, NPC->enemy->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->currentOrigin, NPC->enemy->s.number, NPC->enemy->clipmask, + (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->s.number)) { // he can get right to me NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( NPC->client->ps.weapon ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(NPC->client->ps.weapon); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //FIXME: switch back if he gets far away again? + // FIXME: switch back if he gets far away again? } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPC->client->ps.weapon == WP_DISRUPTOR - || NPC->client->ps.weapon == WP_TUSKEN_RIFLE ) - {//sniping... should be assumed - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR || NPC->client->ps.weapon == WP_TUSKEN_RIFLE) { // sniping... should be assumed + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( NPC->client->ps.weapon ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(NPC->client->ps.weapon); + NPC_UpdateAngles(qtrue, qtrue); return; } } } Sniper_UpdateEnemyPos(); - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) )//|| (NPCInfo->stats.aim >= 5 && gi.inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) //|| (NPCInfo->stats.aim >= 5 && gi.inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) { NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); enemyLOS = qtrue; float maxShootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyDist < maxShootDist ) - { + if (enemyDist < maxShootDist) { vec3_t fwd, right, up, muzzle, end; - trace_t tr; - AngleVectors( NPC->client->ps.viewangles, fwd, right, up ); - CalcMuzzlePoint( NPC, fwd, right, up, muzzle, 0 ); - VectorMA( muzzle, 8192, fwd, end ); - gi.trace ( &tr, muzzle, NULL, NULL, end, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); + trace_t tr; + AngleVectors(NPC->client->ps.viewangles, fwd, right, up); + CalcMuzzlePoint(NPC, fwd, right, up, muzzle, 0); + VectorMA(muzzle, 8192, fwd, end); + gi.trace(&tr, muzzle, NULL, NULL, end, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 0); int hit = tr.entityNum; - //can we shoot our target? - if ( Sniper_EvaluateShot( hit ) ) - { + // can we shoot our target? + if (Sniper_EvaluateShot(hit)) { enemyCS = qtrue; } } @@ -788,141 +679,105 @@ void NPC_BSSniper_Attack( void ) } */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( !TIMER_Done( NPC, "taunting" ) ) - { + if (!TIMER_Done(NPC, "taunting")) { doMove = qfalse; shoot = qfalse; - } - else if ( enemyCS ) - { + } else if (enemyCS) { shoot = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 3000 ) - {//Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds up when ducked seems to make them want to run when they uncrouch + } else if (level.time - NPCInfo->enemyLastSeenTime > 3000) { // Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds up + // when ducked seems to make them want to run when they uncrouch Sniper_ResolveBlockedShot(); - } - else if ( NPC->client->ps.weapon == WP_TUSKEN_RIFLE && !Q_irand( 0, 100 ) ) - {//start a taunt + } else if (NPC->client->ps.weapon == WP_TUSKEN_RIFLE && !Q_irand(0, 100)) { // start a taunt NPC_Tusken_Taunt(); - TIMER_Set( NPC, "duck", -1 ); + TIMER_Set(NPC, "duck", -1); doMove = qfalse; } - //Check for movement to take care of + // Check for movement to take care of Sniper_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Sniper_CheckFireState(); - if ( doMove ) - {//doMove toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (doMove) { // doMove toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { doMove = Sniper_Move(); - } - else - { + } else { doMove = qfalse; } } - if ( !doMove ) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { - if ( TIMER_Done( NPC, "watch" ) ) - {//not while watching + if (!doMove) { + if (!TIMER_Done(NPC, "duck")) { + if (TIMER_Done(NPC, "watch")) { // not while watching ucmd.upmove = -127; - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Cloak( NPC ); + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Cloak(NPC); } } } - //FIXME: what about leaning? - //FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Decloak( NPC ); + // FIXME: what about leaning? + // FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Decloak(NPC); } } - if ( TIMER_Done( NPC, "duck" ) - && TIMER_Done( NPC, "watch" ) - && (TIMER_Get( NPC, "attackDelay" )-level.time) > 1000 - && NPC->attackDebounceTime < level.time ) - { - if ( enemyLOS && (NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - if ( NPC->fly_sound_debounce_time < level.time ) - { + if (TIMER_Done(NPC, "duck") && TIMER_Done(NPC, "watch") && (TIMER_Get(NPC, "attackDelay") - level.time) > 1000 && NPC->attackDebounceTime < level.time) { + if (enemyLOS && (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + if (NPC->fly_sound_debounce_time < level.time) { NPC->fly_sound_debounce_time = level.time + 2000; } } } - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( doMove ) - {//don't run away and shoot + if (!faceEnemy) { // we want to face in the dir we're running + if (doMove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy ) + { // face the enemy Sniper_FaceEnemy(); } - if ( NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - WeaponThink( qtrue ); - if ( ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK) ) - { - G_SoundOnEnt( NPC, CHAN_WEAPON, "sound/null.wav" ); + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + WeaponThink(qtrue); + if (ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) { + G_SoundOnEnt(NPC, CHAN_WEAPON, "sound/null.wav"); } - //took a shot, now hide - if ( !(NPC->spawnflags&SPF_NO_HIDE) && !Q_irand( 0, 1 ) ) - { - //FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover + // took a shot, now hide + if (!(NPC->spawnflags & SPF_NO_HIDE) && !Q_irand(0, 1)) { + // FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover Sniper_StartHide(); - } - else - { - TIMER_Set( NPC, "attackDelay", NPCInfo->shotTime-level.time ); + } else { + TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime - level.time); } } } } -void NPC_BSSniper_Default( void ) -{ - if( !NPC->enemy ) - {//don't have an enemy, look for one +void NPC_BSSniper_Default(void) { + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSSniper_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSSniper_Attack(); } } diff --git a/code/game/AI_Stormtrooper.cpp b/code/game/AI_Stormtrooper.cpp index bf278a5deb..f7bed08a46 100644 --- a/code/game/AI_Stormtrooper.cpp +++ b/code/game/AI_Stormtrooper.cpp @@ -27,47 +27,47 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ); -extern qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ); -extern void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ); -extern void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void NPC_CheckGetNewWeapon( void ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern int GetTime ( int lastTime ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern void NPC_EvasionSaber( void ); -extern qboolean RT_Flying( gentity_t *self ); - -extern cvar_t *d_asynchronousGroupAI; - -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 -#define ST_MIN_LIGHT_THRESHOLD 30 -#define ST_MAX_LIGHT_THRESHOLD 180 -#define DISTANCE_THRESHOLD 0.075f -#define MIN_TURN_AROUND_DIST_SQ (10000) //(100 squared) don't stop running backwards if your goal is less than 100 away -#define SABER_AVOID_DIST 128.0f//256.0f -#define SABER_AVOID_DIST_SQ (SABER_AVOID_DIST*SABER_AVOID_DIST) - -#define DISTANCE_SCALE 0.35f //These first three get your base detection rating, ideally add up to 1 -#define FOV_SCALE 0.40f // -#define LIGHT_SCALE 0.25f // - -#define SPEED_SCALE 0.25f //These next two are bonuses -#define TURNING_SCALE 0.25f // - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) - -qboolean NPC_CheckPlayerTeamStealth( void ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState); +extern qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum); +extern void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot); +extern void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void NPC_CheckGetNewWeapon(void); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern int GetTime(int lastTime); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); +extern void NPC_EvasionSaber(void); +extern qboolean RT_Flying(gentity_t *self); + +extern cvar_t *d_asynchronousGroupAI; + +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 +#define ST_MIN_LIGHT_THRESHOLD 30 +#define ST_MAX_LIGHT_THRESHOLD 180 +#define DISTANCE_THRESHOLD 0.075f +#define MIN_TURN_AROUND_DIST_SQ (10000) //(100 squared) don't stop running backwards if your goal is less than 100 away +#define SABER_AVOID_DIST 128.0f // 256.0f +#define SABER_AVOID_DIST_SQ (SABER_AVOID_DIST * SABER_AVOID_DIST) + +#define DISTANCE_SCALE 0.35f // These first three get your base detection rating, ideally add up to 1 +#define FOV_SCALE 0.40f // +#define LIGHT_SCALE 0.25f // + +#define SPEED_SCALE 0.25f // These next two are bonuses +#define TURNING_SCALE 0.25f // + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) + +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; @@ -76,117 +76,95 @@ static qboolean hitAlly; static qboolean faceEnemy; static qboolean doMove; static qboolean shoot; -static float enemyDist; -static vec3_t impactPos; +static float enemyDist; +static vec3_t impactPos; -int groupSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several group AI from speaking all at once +int groupSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several group AI from speaking all at once -void NPC_Saboteur_Precache( void ) -{ - G_SoundIndex( "sound/chars/shadowtrooper/cloak.wav" ); - G_SoundIndex( "sound/chars/shadowtrooper/decloak.wav" ); +void NPC_Saboteur_Precache(void) { + G_SoundIndex("sound/chars/shadowtrooper/cloak.wav"); + G_SoundIndex("sound/chars/shadowtrooper/decloak.wav"); } -void Saboteur_Decloak( gentity_t *self, int uncloakTime ) -{ - if ( self && self->client ) - { - if ( self->client->ps.powerups[PW_CLOAKED] && TIMER_Done(self, "decloakwait")) - {//Uncloak +void Saboteur_Decloak(gentity_t *self, int uncloakTime) { + if (self && self->client) { + if (self->client->ps.powerups[PW_CLOAKED] && TIMER_Done(self, "decloakwait")) { // Uncloak self->client->ps.powerups[PW_CLOAKED] = 0; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav" ); - TIMER_Set( self, "nocloak", uncloakTime ); + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav"); + TIMER_Set(self, "nocloak", uncloakTime); // Can't Recloak - //self->NPC->aiFlags &= ~NPCAI_SHIELDS; + // self->NPC->aiFlags &= ~NPCAI_SHIELDS; } } } -void Saboteur_Cloak( gentity_t *self ) -{ - if ( self && self->client && self->NPC ) - {//FIXME: need to have this timer set once first? - if ( TIMER_Done( self, "nocloak" ) ) - {//not sitting around waiting to cloak again - if ( !(self->NPC->aiFlags&NPCAI_SHIELDS) ) - {//not allowed to cloak, actually - Saboteur_Decloak( self ); - } - else if ( !self->client->ps.powerups[PW_CLOAKED] ) - {//cloak +void Saboteur_Cloak(gentity_t *self) { + if (self && self->client && self->NPC) { // FIXME: need to have this timer set once first? + if (TIMER_Done(self, "nocloak")) { // not sitting around waiting to cloak again + if (!(self->NPC->aiFlags & NPCAI_SHIELDS)) { // not allowed to cloak, actually + Saboteur_Decloak(self); + } else if (!self->client->ps.powerups[PW_CLOAKED]) { // cloak self->client->ps.powerups[PW_CLOAKED] = Q3_INFINITE; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: debounce attacks? - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav" ); + // FIXME: debounce attacks? + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav"); } } } } - - -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void ST_AggressionAdjust( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +void ST_AggressionAdjust(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == TEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == TEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive + } else { // bad guys are more aggressive upper_threshold = 10; lower_threshold = 3; } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } } -void ST_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "interrogating", 0 ); - TIMER_Set( ent, "verifyCP", 0 ); - TIMER_Set( ent, "strafeRight", 0 ); - TIMER_Set( ent, "strafeLeft", 0 ); +void ST_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "interrogating", 0); + TIMER_Set(ent, "verifyCP", 0); + TIMER_Set(ent, "strafeRight", 0); + TIMER_Set(ent, "strafeLeft", 0); } -enum -{ +enum { SPEECH_CHASE, SPEECH_CONFUSED, SPEECH_COVER, @@ -203,19 +181,14 @@ enum SPEECH_PUSHED }; -static void ST_Speech( gentity_t *self, int speechType, float failChance ) -{ - if ( Q_flrand(0.0f, 1.0f) < failChance ) - { +static void ST_Speech(gentity_t *self, int speechType, float failChance) { + if (Q_flrand(0.0f, 1.0f) < failChance) { return; } - if ( failChance >= 0 ) - {//a negative failChance makes it always talk - if ( self->NPC->group ) - {//group AI speech debounce timer - if ( self->NPC->group->speechDebounceTime > level.time ) - { + if (failChance >= 0) { // a negative failChance makes it always talk + if (self->NPC->group) { // group AI speech debounce timer + if (self->NPC->group->speechDebounceTime > level.time) { return; } /* @@ -227,77 +200,68 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) } } */ - } - else if ( !TIMER_Done( self, "chatter" ) ) - {//personal timer + } else if (!TIMER_Done(self, "chatter")) { // personal timer return; - } - else if ( groupSpeechDebounceTime[self->client->playerTeam] > level.time ) - {//for those not in group AI - //FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? + } else if (groupSpeechDebounceTime[self->client->playerTeam] > level.time) { // for those not in group AI + // FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? return; } } - if ( self->NPC->group ) - {//So they don't all speak at once... - //FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! - self->NPC->group->speechDebounceTime = level.time + Q_irand( 2000, 4000 ); + if (self->NPC->group) { // So they don't all speak at once... + // FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! + self->NPC->group->speechDebounceTime = level.time + Q_irand(2000, 4000); + } else { + TIMER_Set(self, "chatter", Q_irand(2000, 4000)); } - else - { - TIMER_Set( self, "chatter", Q_irand( 2000, 4000 ) ); - } - groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand( 2000, 4000 ); + groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand(2000, 4000); - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - switch( speechType ) - { + switch (speechType) { case SPEECH_CHASE: - G_AddVoiceEvent( self, Q_irand(EV_CHASE1, EV_CHASE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CHASE1, EV_CHASE3), 2000); break; case SPEECH_CONFUSED: - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); break; case SPEECH_COVER: - G_AddVoiceEvent( self, Q_irand(EV_COVER1, EV_COVER5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_COVER1, EV_COVER5), 2000); break; case SPEECH_DETECTED: - G_AddVoiceEvent( self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000); break; case SPEECH_GIVEUP: - G_AddVoiceEvent( self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000); break; case SPEECH_LOOK: - G_AddVoiceEvent( self, Q_irand(EV_LOOK1, EV_LOOK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_LOOK1, EV_LOOK2), 2000); break; case SPEECH_LOST: - G_AddVoiceEvent( self, EV_LOST1, 2000 ); + G_AddVoiceEvent(self, EV_LOST1, 2000); break; case SPEECH_OUTFLANK: - G_AddVoiceEvent( self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000); break; case SPEECH_ESCAPING: - G_AddVoiceEvent( self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000); break; case SPEECH_SIGHT: - G_AddVoiceEvent( self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000); break; case SPEECH_SOUND: - G_AddVoiceEvent( self, Q_irand(EV_SOUND1, EV_SOUND3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SOUND1, EV_SOUND3), 2000); break; case SPEECH_SUSPICIOUS: - G_AddVoiceEvent( self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000); break; case SPEECH_YELL: - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 2000); break; case SPEECH_PUSHED: - G_AddVoiceEvent( self, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); break; default: break; @@ -306,31 +270,25 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) self->NPC->blockedSpeechDebounceTime = level.time + 2000; } -void ST_MarkToCover( gentity_t *self ) -{ - if ( !self || !self->NPC ) - { +void ST_MarkToCover(gentity_t *self) { + if (!self || !self->NPC) { return; } self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "attackDelay", Q_irand( 500, 2500 ) ); - ST_AggressionAdjust( self, -3 ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + TIMER_Set(self, "attackDelay", Q_irand(500, 2500)); + ST_AggressionAdjust(self, -3); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } -void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ) -{ - if ( !self || !self->NPC ) - { +void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime) { + if (!self || !self->NPC) { return; } - G_StartFlee( self, enemy, dangerPoint, dangerLevel, minTime, maxTime ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + G_StartFlee(self, enemy, dangerPoint, dangerLevel, minTime, maxTime); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } /* @@ -339,19 +297,17 @@ NPC_ST_Pain ------------------------- */ -void NPC_ST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_ST_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "hideTime", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "hideTime", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod, hitLoc ); + NPC_Pain(self, inflictor, other, point, damage, mod, hitLoc); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -361,48 +317,35 @@ ST_HoldPosition ------------------------- */ -static void ST_HoldPosition( void ) -{ - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); - } - TIMER_Set( NPC, "verifyCP", Q_irand( 1000, 3000 ) );//don't look for another one for a few seconds - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); - //NPCInfo->combatPoint = -1;//??? - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//don't have a script waiting for me to get to my point, okay to stop trying and stand - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); +static void ST_HoldPosition(void) { + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); + } + TIMER_Set(NPC, "verifyCP", Q_irand(1000, 3000)); // don't look for another one for a few seconds + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); + // NPCInfo->combatPoint = -1;//??? + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // don't have a script waiting for me to get to my point, okay to stop trying and stand + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT); NPCInfo->goalEntity = NULL; } - } -void NPC_ST_SayMovementSpeech( void ) -{ - if ( !NPCInfo->movementSpeech ) - { +void NPC_ST_SayMovementSpeech(void) { + if (!NPCInfo->movementSpeech) { return; } - if ( NPCInfo->group && - NPCInfo->group->commander && - NPCInfo->group->commander->client && - NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - {//imperial (commander) gives the order - ST_Speech( NPCInfo->group->commander, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance ); - } - else - {//really don't want to say this unless we can actually get there... - ST_Speech( NPC, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance ); + if (NPCInfo->group && NPCInfo->group->commander && NPCInfo->group->commander->client && NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && + !Q_irand(0, 3)) { // imperial (commander) gives the order + ST_Speech(NPCInfo->group->commander, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance); + } else { // really don't want to say this unless we can actually get there... + ST_Speech(NPC, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance); } NPCInfo->movementSpeech = 0; NPCInfo->movementSpeechChance = 0.0f; } -void NPC_ST_StoreMovementSpeech( int speech, float chance ) -{ +void NPC_ST_StoreMovementSpeech(int speech, float chance) { NPCInfo->movementSpeech = speech; NPCInfo->movementSpeechChance = chance; } @@ -411,14 +354,12 @@ void NPC_ST_StoreMovementSpeech( int speech, float chance ) ST_Move ------------------------- */ -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ); -static qboolean ST_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always doMove straight toward our goal +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other); +static qboolean ST_Move(void) { + NPCInfo->combatMove = qtrue; // always doMove straight toward our goal - qboolean moved = NPC_MoveToGoal( qtrue ); - if (moved==qfalse) - { + qboolean moved = NPC_MoveToGoal(qtrue); + if (moved == qfalse) { ST_HoldPosition(); } @@ -427,28 +368,24 @@ static qboolean ST_Move( void ) return moved; } - /* ------------------------- NPC_ST_SleepShuffle ------------------------- */ -static void NPC_ST_SleepShuffle( void ) -{ - //Play an awake script if we have one - if ( G_ActivateBehavior( NPC, BSET_AWAKE) ) - { +static void NPC_ST_SleepShuffle(void) { + // Play an awake script if we have one + if (G_ActivateBehavior(NPC, BSET_AWAKE)) { return; } - //Automate some movement and noise - if ( TIMER_Done( NPC, "shuffleTime" ) ) - { + // Automate some movement and noise + if (TIMER_Done(NPC, "shuffleTime")) { - //TODO: Play sleeping shuffle animation + // TODO: Play sleeping shuffle animation - //int soundIndex = Q_irand( 0, 1 ); + // int soundIndex = Q_irand( 0, 1 ); /* switch ( soundIndex ) @@ -463,16 +400,15 @@ static void NPC_ST_SleepShuffle( void ) } */ - TIMER_Set( NPC, "shuffleTime", 4000 ); - TIMER_Set( NPC, "sleepTime", 2000 ); + TIMER_Set(NPC, "shuffleTime", 4000); + TIMER_Set(NPC, "sleepTime", 2000); return; } - //They made another noise while we were stirring, see if we can see them - if ( TIMER_Done( NPC, "sleepTime" ) ) - { + // They made another noise while we were stirring, see if we can see them + if (TIMER_Done(NPC, "sleepTime")) { NPC_CheckPlayerTeamStealth(); - TIMER_Set( NPC, "sleepTime", 2000 ); + TIMER_Set(NPC, "sleepTime", 2000); } } @@ -482,24 +418,20 @@ NPC_ST_Sleep ------------------------- */ -void NPC_BSST_Sleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qfalse, qtrue );//only check sounds since we're alseep! +void NPC_BSST_Sleep(void) { + int alertEvent = NPC_CheckAlertEvents(qfalse, qtrue); // only check sounds since we're alseep! - //There is an event we heard - if ( alertEvent >= 0 ) - { - //See if it was enough to wake us up - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - if ( &g_entities[0] && g_entities[0].health > 0 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + // There is an event we heard + if (alertEvent >= 0) { + // See if it was enough to wake us up + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + if (&g_entities[0] && g_entities[0].health > 0) { + G_SetEnemy(NPC, &g_entities[0]); return; } } - //Otherwise just stir a bit + // Otherwise just stir a bit NPC_ST_SleepShuffle(); return; } @@ -511,155 +443,136 @@ NPC_CheckEnemyStealth ------------------------- */ -qboolean NPC_CheckEnemyStealth( gentity_t *target ) -{ - float target_dist, minDist = 40;//any closer than 40 and we definitely notice +qboolean NPC_CheckEnemyStealth(gentity_t *target) { + float target_dist, minDist = 40; // any closer than 40 and we definitely notice - //In case we aquired one some other way - if ( NPC->enemy != NULL ) + // In case we aquired one some other way + if (NPC->enemy != NULL) return qtrue; - //Ignore notarget - if ( target->flags & FL_NOTARGET ) + // Ignore notarget + if (target->flags & FL_NOTARGET) return qfalse; - if ( target->health <= 0 ) - { + if (target->health <= 0) { return qfalse; } - if ( target->client->ps.weapon == WP_SABER && target->client->ps.SaberActive() && !target->client->ps.saberInFlight ) - {//if target has saber in hand and activated, we wake up even sooner even if not facing him + if (target->client->ps.weapon == WP_SABER && target->client->ps.SaberActive() && + !target->client->ps.saberInFlight) { // if target has saber in hand and activated, we wake up even sooner even if not facing him minDist = 100; } - target_dist = DistanceSquared( target->currentOrigin, NPC->currentOrigin ); - //If the target is this close, then wake up regardless - if ( !(target->client->ps.pm_flags&PMF_DUCKED)//not ducking - && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES)//looking for enemies - && target_dist < (minDist*minDist) )//closer than minDist + target_dist = DistanceSquared(target->currentOrigin, NPC->currentOrigin); + // If the target is this close, then wake up regardless + if (!(target->client->ps.pm_flags & PMF_DUCKED) // not ducking + && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) // looking for enemies + && target_dist < (minDist * minDist)) // closer than minDist { - G_SetEnemy( NPC, target ); + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - float maxViewDist = MAX_VIEW_DIST; + float maxViewDist = MAX_VIEW_DIST; -// if ( NPCInfo->stats.visrange > maxViewDist ) - {//FIXME: should we always just set maxViewDist to this? + // if ( NPCInfo->stats.visrange > maxViewDist ) + { // FIXME: should we always just set maxViewDist to this? maxViewDist = NPCInfo->stats.visrange; } - if ( target_dist > (maxViewDist*maxViewDist) ) - {//out of possible visRange + if (target_dist > (maxViewDist * maxViewDist)) { // out of possible visRange return qfalse; } - //Check FOV first - if ( InFOV( target, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Check FOV first + if (InFOV(target, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - qboolean clearLOS = ( target->client->ps.leanofs ) ? NPC_ClearLOS( target->client->renderInfo.eyePoint ) : NPC_ClearLOS( target ); + qboolean clearLOS = (target->client->ps.leanofs) ? NPC_ClearLOS(target->client->renderInfo.eyePoint) : NPC_ClearLOS(target); - //Now check for clear line of vision - if ( clearLOS ) - { - if ( target->client->NPC_class == CLASS_ATST ) - {//can't miss 'em! - G_SetEnemy( NPC, target ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // Now check for clear line of vision + if (clearLOS) { + if (target->client->NPC_class == CLASS_ATST) { // can't miss 'em! + G_SetEnemy(NPC, target); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - vec3_t targ_org = {target->currentOrigin[0],target->currentOrigin[1],target->currentOrigin[2]+target->maxs[2]-4}; - float hAngle_perc = NPC_GetHFOVPercentage( targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov ); - float vAngle_perc = NPC_GetVFOVPercentage( targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.vfov ); + vec3_t targ_org = {target->currentOrigin[0], target->currentOrigin[1], target->currentOrigin[2] + target->maxs[2] - 4}; + float hAngle_perc = NPC_GetHFOVPercentage(targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov); + float vAngle_perc = NPC_GetVFOVPercentage(targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.vfov); - //Scale them vertically some, and horizontally pretty harshly - vAngle_perc *= vAngle_perc;//( vAngle_perc * vAngle_perc ); - hAngle_perc *= ( hAngle_perc * hAngle_perc ); + // Scale them vertically some, and horizontally pretty harshly + vAngle_perc *= vAngle_perc; //( vAngle_perc * vAngle_perc ); + hAngle_perc *= (hAngle_perc * hAngle_perc); - //Cap our vertical vision severely - //if ( vAngle_perc <= 0.3f ) // was 0.5f + // Cap our vertical vision severely + // if ( vAngle_perc <= 0.3f ) // was 0.5f // return qfalse; - //Assess the player's current status - target_dist = Distance( target->currentOrigin, NPC->currentOrigin ); - - float target_speed = VectorLength( target->client->ps.velocity ); - int target_crouching = ( target->client->usercmd.upmove < 0 ); - float dist_rating = ( target_dist / maxViewDist ); - float speed_rating = ( target_speed / MAX_VIEW_SPEED ); - float turning_rating = AngleDelta( target->client->ps.viewangles[PITCH], target->lastAngles[PITCH] )/180.0f + AngleDelta( target->client->ps.viewangles[YAW], target->lastAngles[YAW] )/180.0f; - float light_level = ( target->lightLevel / MAX_LIGHT_INTENSITY ); - float FOV_perc = 1.0f - ( hAngle_perc + vAngle_perc ) * 0.5f; //FIXME: Dunno about the average... - float vis_rating = 0.0f; - - //Too dark - if ( light_level < MIN_LIGHT_THRESHOLD ) + // Assess the player's current status + target_dist = Distance(target->currentOrigin, NPC->currentOrigin); + + float target_speed = VectorLength(target->client->ps.velocity); + int target_crouching = (target->client->usercmd.upmove < 0); + float dist_rating = (target_dist / maxViewDist); + float speed_rating = (target_speed / MAX_VIEW_SPEED); + float turning_rating = AngleDelta(target->client->ps.viewangles[PITCH], target->lastAngles[PITCH]) / 180.0f + + AngleDelta(target->client->ps.viewangles[YAW], target->lastAngles[YAW]) / 180.0f; + float light_level = (target->lightLevel / MAX_LIGHT_INTENSITY); + float FOV_perc = 1.0f - (hAngle_perc + vAngle_perc) * 0.5f; // FIXME: Dunno about the average... + float vis_rating = 0.0f; + + // Too dark + if (light_level < MIN_LIGHT_THRESHOLD) return qfalse; - //Too close? - if ( dist_rating < DISTANCE_THRESHOLD ) - { - G_SetEnemy( NPC, target ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // Too close? + if (dist_rating < DISTANCE_THRESHOLD) { + G_SetEnemy(NPC, target); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //Out of range - if ( dist_rating > 1.0f ) + // Out of range + if (dist_rating > 1.0f) return qfalse; - //Cap our speed checks - if ( speed_rating > 1.0f ) + // Cap our speed checks + if (speed_rating > 1.0f) speed_rating = 1.0f; - - //Calculate the distance, fov and light influences + // Calculate the distance, fov and light influences //...Visibilty linearly wanes over distance - float dist_influence = DISTANCE_SCALE * ( ( 1.0f - dist_rating ) ); + float dist_influence = DISTANCE_SCALE * ((1.0f - dist_rating)); //...As the percentage out of the FOV increases, straight perception suffers on an exponential scale - float fov_influence = FOV_SCALE * ( 1.0f - FOV_perc ); + float fov_influence = FOV_SCALE * (1.0f - FOV_perc); //...Lack of light hides, abundance of light exposes - float light_influence = ( light_level - 0.5f ) * LIGHT_SCALE; - - //Calculate our base rating - float target_rating = dist_influence + fov_influence + light_influence; - - //Now award any final bonuses to this number - int contents = gi.pointcontents( targ_org, target->s.number ); - if ( contents&CONTENTS_WATER ) - { - int myContents = gi.pointcontents( NPC->client->renderInfo.eyePoint, NPC->s.number ); - if ( !(myContents&CONTENTS_WATER) ) - {//I'm not in water - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//these guys can see in in/through water pretty well - vis_rating = 0.10f;//10% bonus + float light_influence = (light_level - 0.5f) * LIGHT_SCALE; + + // Calculate our base rating + float target_rating = dist_influence + fov_influence + light_influence; + + // Now award any final bonuses to this number + int contents = gi.pointcontents(targ_org, target->s.number); + if (contents & CONTENTS_WATER) { + int myContents = gi.pointcontents(NPC->client->renderInfo.eyePoint, NPC->s.number); + if (!(myContents & CONTENTS_WATER)) { // I'm not in water + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // these guys can see in in/through water pretty well + vis_rating = 0.10f; // 10% bonus + } else { + vis_rating = 0.35f; // 35% bonus } - else - { - vis_rating = 0.35f;//35% bonus + } else { // else, if we're both in water + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // I can see him just fine + } else { + vis_rating = 0.15f; // 15% bonus } } - else - {//else, if we're both in water - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//I can see him just fine - } - else - { - vis_rating = 0.15f;//15% bonus - } - } - } - else - {//not in water - if ( contents&CONTENTS_FOG ) - { - vis_rating = 0.15f;//15% bonus + } else { // not in water + if (contents & CONTENTS_FOG) { + vis_rating = 0.15f; // 15% bonus } } @@ -668,68 +581,57 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) //...Motion draws the eye quickly target_rating += speed_rating * SPEED_SCALE; target_rating += turning_rating * TURNING_SCALE; - //FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? + // FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? //...Smaller targets are harder to indentify - if ( target_crouching ) - { - target_rating *= 0.9f; //10% bonus + if (target_crouching) { + target_rating *= 0.9f; // 10% bonus } - //If he's violated the threshold, then realize him - //float difficulty_scale = 1.0f + (2.0f-g_spskill->value);//if playing on easy, 20% harder to be seen...? + // If he's violated the threshold, then realize him + // float difficulty_scale = 1.0f + (2.0f-g_spskill->value);//if playing on easy, 20% harder to be seen...? float realize, cautious; - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//swamptroopers can see much better - realize = (float)CAUTIOUS_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; - } - else - { - realize = (float)REALIZE_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // swamptroopers can see much better + realize = (float)CAUTIOUS_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; + } else { + realize = (float)REALIZE_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; } - if ( target_rating > realize && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - G_SetEnemy( NPC, target ); + if (target_rating > realize && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //If he's above the caution threshold, then realize him in a few seconds unless he moves to cover - if ( target_rating > cautious && !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//FIXME: ambushing guys should never talk - if ( TIMER_Done( NPC, "enemyLastVisible" ) ) - {//If we haven't already, start the counter - int lookTime = Q_irand( 4500, 8500 ); - //NPCInfo->timeEnemyLastVisible = level.time + 2000; - TIMER_Set( NPC, "enemyLastVisible", lookTime ); - //TODO: Play a sound along the lines of, "Huh? What was that?" - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - NPC_TempLookTarget( NPC, target->s.number, lookTime, lookTime ); - //FIXME: set desired yaw and pitch towards this guy? - } - else if ( TIMER_Get( NPC, "enemyLastVisible" ) <= level.time + 500 && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) //FIXME: Is this reliable? + // If he's above the caution threshold, then realize him in a few seconds unless he moves to cover + if (target_rating > cautious && !(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // FIXME: ambushing guys should never talk + if (TIMER_Done(NPC, "enemyLastVisible")) { // If we haven't already, start the counter + int lookTime = Q_irand(4500, 8500); + // NPCInfo->timeEnemyLastVisible = level.time + 2000; + TIMER_Set(NPC, "enemyLastVisible", lookTime); + // TODO: Play a sound along the lines of, "Huh? What was that?" + ST_Speech(NPC, SPEECH_SIGHT, 0); + NPC_TempLookTarget(NPC, target->s.number, lookTime, lookTime); + // FIXME: set desired yaw and pitch towards this guy? + } else if (TIMER_Get(NPC, "enemyLastVisible") <= level.time + 500 && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) // FIXME: Is this reliable? { - if ( NPCInfo->rank < RANK_LT && !Q_irand( 0, 2 ) ) - { - int interrogateTime = Q_irand( 2000, 4000 ); - ST_Speech( NPC, SPEECH_SUSPICIOUS, 0 ); - TIMER_Set( NPC, "interrogating", interrogateTime ); - G_SetEnemy( NPC, target ); + if (NPCInfo->rank < RANK_LT && !Q_irand(0, 2)) { + int interrogateTime = Q_irand(2000, 4000); + ST_Speech(NPC, SPEECH_SUSPICIOUS, 0); + TIMER_Set(NPC, "interrogating", interrogateTime); + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", interrogateTime ); - TIMER_Set( NPC, "stand", interrogateTime ); - } - else - { - G_SetEnemy( NPC, target ); + TIMER_Set(NPC, "attackDelay", interrogateTime); + TIMER_Set(NPC, "stand", interrogateTime); + } else { + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - //FIXME: ambush guys (like those popping out of water) shouldn't delay... - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - TIMER_Set( NPC, "stand", Q_irand( 500, 2500 ) ); + // FIXME: ambush guys (like those popping out of water) shouldn't delay... + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + TIMER_Set(NPC, "stand", Q_irand(500, 2500)); } return qtrue; } @@ -741,8 +643,7 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) return qfalse; } -qboolean NPC_CheckPlayerTeamStealth( void ) -{ +qboolean NPC_CheckPlayerTeamStealth(void) { /* //NOTENOTE: For now, all stealh checks go against the player, since // he is the main focus. Squad members and rivals do not @@ -751,16 +652,12 @@ qboolean NPC_CheckPlayerTeamStealth( void ) NPC_CheckEnemyStealth( &g_entities[0] ); //Change this pointer to assess other entities */ gentity_t *enemy; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { - if(!PInUse(i)) + for (int i = 0; i < ENTITYNUM_WORLD; i++) { + if (!PInUse(i)) continue; enemy = &g_entities[i]; - if ( enemy - && enemy->client - && NPC_ValidEnemy( enemy ) ) - { - if ( NPC_CheckEnemyStealth( enemy ) ) //Change this pointer to assess other entities + if (enemy && enemy->client && NPC_ValidEnemy(enemy)) { + if (NPC_CheckEnemyStealth(enemy)) // Change this pointer to assess other entities { return qtrue; } @@ -769,96 +666,87 @@ qboolean NPC_CheckPlayerTeamStealth( void ) return qfalse; } -qboolean NPC_CheckEnemiesInSpotlight( void ) -{ - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *enemy, *suspect = NULL; - int i, numListedEntities; - vec3_t mins, maxs; +qboolean NPC_CheckEnemiesInSpotlight(void) { + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *enemy, *suspect = NULL; + int i, numListedEntities; + vec3_t mins, maxs; - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = NPC->client->renderInfo.eyePoint[i] - NPC->speed; maxs[i] = NPC->client->renderInfo.eyePoint[i] + NPC->speed; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( i = 0; i < numListedEntities; i++ ) - { - if(!PInUse(i)) + for (i = 0; i < numListedEntities; i++) { + if (!PInUse(i)) continue; enemy = entityList[i]; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPC->client->enemyTeam ) - {//valid ent & client, valid enemy, on the target team - //check to see if they're in my FOV - if ( InFOV( enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) ) - {//in my cone - //check to see that they're close enough - if ( DistanceSquared( NPC->client->renderInfo.eyePoint, enemy->currentOrigin )-256/*fudge factor: 16 squared*/ <= NPC->speed*NPC->speed ) - {//within range - //check to see if we have a clear trace to them - if ( G_ClearLOS( NPC, enemy ) ) - {//clear LOS - //make sure their light level is at least my beam's brightness - //FIXME: HOW? - //enemy->lightLevel / MAX_LIGHT_INTENSITY - - //good enough, take him! - //FIXME: pick closest one? - //FIXME: have the graduated noticing like other NPCs? (based on distance, FOV dot, etc...) - G_SetEnemy( NPC, enemy ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && + enemy->client->playerTeam == NPC->client->enemyTeam) { // valid ent & client, valid enemy, on the target team + // check to see if they're in my FOV + if (InFOV(enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov, + NPCInfo->stats.vfov)) { // in my cone + // check to see that they're close enough + if (DistanceSquared(NPC->client->renderInfo.eyePoint, enemy->currentOrigin) - 256 /*fudge factor: 16 squared*/ <= + NPC->speed * NPC->speed) { // within range + // check to see if we have a clear trace to them + if (G_ClearLOS(NPC, enemy)) { // clear LOS + // make sure their light level is at least my beam's brightness + // FIXME: HOW? + // enemy->lightLevel / MAX_LIGHT_INTENSITY + + // good enough, take him! + // FIXME: pick closest one? + // FIXME: have the graduated noticing like other NPCs? (based on distance, FOV dot, etc...) + G_SetEnemy(NPC, enemy); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } } } - if ( InFOV( enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 90, NPCInfo->stats.vfov*3 ) ) - {//one to look at if we don't get an enemy - if ( G_ClearLOS( NPC, enemy ) ) - {//clear LOS - if ( suspect == NULL || DistanceSquared( NPC->client->renderInfo.eyePoint, enemy->currentOrigin ) < DistanceSquared( NPC->client->renderInfo.eyePoint, suspect->currentOrigin ) ) - {//remember him + if (InFOV(enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 90, + NPCInfo->stats.vfov * 3)) { // one to look at if we don't get an enemy + if (G_ClearLOS(NPC, enemy)) { // clear LOS + if (suspect == NULL || DistanceSquared(NPC->client->renderInfo.eyePoint, enemy->currentOrigin) < + DistanceSquared(NPC->client->renderInfo.eyePoint, suspect->currentOrigin)) { // remember him suspect = enemy; } } } } } - if ( suspect && Q_flrand( 0, NPCInfo->stats.visrange*NPCInfo->stats.visrange ) > DistanceSquared( NPC->client->renderInfo.eyePoint, suspect->currentOrigin ) ) - {//hey! who's that? - if ( TIMER_Done( NPC, "enemyLastVisible" ) ) - {//If we haven't already, start the counter - int lookTime = Q_irand( 4500, 8500 ); - //NPCInfo->timeEnemyLastVisible = level.time + 2000; - TIMER_Set( NPC, "enemyLastVisible", lookTime ); - //TODO: Play a sound along the lines of, "Huh? What was that?" - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - //set desired yaw and pitch towards this guy? - //FIXME: this is permanent, they will never look away... *sigh* - NPC_FacePosition( suspect->currentOrigin, qtrue ); - //FIXME: they still need some sort of eye/head tag/bone that can turn? - //NPC_TempLookTarget( NPC, suspect->s.number, lookTime, lookTime ); - } - else if ( TIMER_Get( NPC, "enemyLastVisible" ) <= level.time + 500 - && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) //FIXME: Is this reliable? + if (suspect && Q_flrand(0, NPCInfo->stats.visrange * NPCInfo->stats.visrange) > + DistanceSquared(NPC->client->renderInfo.eyePoint, suspect->currentOrigin)) { // hey! who's that? + if (TIMER_Done(NPC, "enemyLastVisible")) { // If we haven't already, start the counter + int lookTime = Q_irand(4500, 8500); + // NPCInfo->timeEnemyLastVisible = level.time + 2000; + TIMER_Set(NPC, "enemyLastVisible", lookTime); + // TODO: Play a sound along the lines of, "Huh? What was that?" + ST_Speech(NPC, SPEECH_SIGHT, 0); + // set desired yaw and pitch towards this guy? + // FIXME: this is permanent, they will never look away... *sigh* + NPC_FacePosition(suspect->currentOrigin, qtrue); + // FIXME: they still need some sort of eye/head tag/bone that can turn? + // NPC_TempLookTarget( NPC, suspect->s.number, lookTime, lookTime ); + } else if (TIMER_Get(NPC, "enemyLastVisible") <= level.time + 500 && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) // FIXME: Is this reliable? { - if ( !Q_irand( 0, 2 ) ) - { - int interrogateTime = Q_irand( 2000, 4000 ); - ST_Speech( NPC, SPEECH_SUSPICIOUS, 0 ); - TIMER_Set( NPC, "interrogating", interrogateTime ); - //G_SetEnemy( NPC, target ); - //NPCInfo->enemyLastSeenTime = level.time; - //TIMER_Set( NPC, "attackDelay", interrogateTime ); - //TIMER_Set( NPC, "stand", interrogateTime ); - //set desired yaw and pitch towards this guy? - //FIXME: this is permanent, they will never look away... *sigh* - NPC_FacePosition( suspect->currentOrigin, qtrue ); - //FIXME: they still need some sort of eye/head tag/bone that can turn? - //NPC_TempLookTarget( NPC, suspect->s.number, interrogateTime, interrogateTime ); + if (!Q_irand(0, 2)) { + int interrogateTime = Q_irand(2000, 4000); + ST_Speech(NPC, SPEECH_SUSPICIOUS, 0); + TIMER_Set(NPC, "interrogating", interrogateTime); + // G_SetEnemy( NPC, target ); + // NPCInfo->enemyLastSeenTime = level.time; + // TIMER_Set( NPC, "attackDelay", interrogateTime ); + // TIMER_Set( NPC, "stand", interrogateTime ); + // set desired yaw and pitch towards this guy? + // FIXME: this is permanent, they will never look away... *sigh* + NPC_FacePosition(suspect->currentOrigin, qtrue); + // FIXME: they still need some sort of eye/head tag/bone that can turn? + // NPC_TempLookTarget( NPC, suspect->s.number, interrogateTime, interrogateTime ); } } } @@ -870,37 +758,30 @@ NPC_ST_InvestigateEvent ------------------------- */ -#define MAX_CHECK_THRESHOLD 1 +#define MAX_CHECK_THRESHOLD 1 -static qboolean NPC_ST_InvestigateEvent( int eventID, bool extraSuspicious ) -{ - //If they've given themselves away, just take them as an enemy - if ( NPCInfo->confusionTime < level.time ) - { - if ( level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - //NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam ) - {//not an enemy +static qboolean NPC_ST_InvestigateEvent(int eventID, bool extraSuspicious) { + // If they've given themselves away, just take them as an enemy + if (NPCInfo->confusionTime < level.time) { + if (level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + // NPCInfo->lastAlertID = level.alertEvents[eventID].ID; + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam) { // not an enemy return qfalse; } - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - //ST_Speech( NPC, SPEECH_CHARGE, 0 ); - G_SetEnemy( NPC, level.alertEvents[eventID].owner ); + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just + // let combat AI handle this... (act as if you lost him) ST_Speech( NPC, SPEECH_CHARGE, 0 ); + G_SetEnemy(NPC, level.alertEvents[eventID].owner); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - if ( level.alertEvents[eventID].type == AET_SOUND ) - {//heard him, didn't see him, stick for a bit - TIMER_Set( NPC, "roamTime", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + if (level.alertEvents[eventID].type == AET_SOUND) { // heard him, didn't see him, stick for a bit + TIMER_Set(NPC, "roamTime", Q_irand(500, 2500)); } return qtrue; } } - //don't look at the same alert twice + // don't look at the same alert twice /* if ( level.alertEvents[eventID].ID == NPCInfo->lastAlertID ) { @@ -909,7 +790,7 @@ static qboolean NPC_ST_InvestigateEvent( int eventID, bool extraSuspicious ) NPCInfo->lastAlertID = level.alertEvents[eventID].ID; */ - //Must be ready to take another sound event + // Must be ready to take another sound event /* if ( NPCInfo->investigateSoundDebounceTime > level.time ) { @@ -917,122 +798,95 @@ static qboolean NPC_ST_InvestigateEvent( int eventID, bool extraSuspicious ) } */ - if ( level.alertEvents[eventID].type == AET_SIGHT ) - {//sight alert, check the light level - if ( level.alertEvents[eventID].light < Q_irand( ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD ) ) - {//below my threshhold of potentially seeing + if (level.alertEvents[eventID].type == AET_SIGHT) { // sight alert, check the light level + if (level.alertEvents[eventID].light < Q_irand(ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD)) { // below my threshhold of potentially seeing return qfalse; } } - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[eventID].position, NPCInfo->investigateGoal ); + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[eventID].position, NPCInfo->investigateGoal); - //First awareness of it - NPCInfo->investigateCount += ( extraSuspicious ) ? 2 : 1; + // First awareness of it + NPCInfo->investigateCount += (extraSuspicious) ? 2 : 1; - //Clamp the value - if ( NPCInfo->investigateCount > 4 ) + // Clamp the value + if (NPCInfo->investigateCount > 4) NPCInfo->investigateCount = 4; - //See if we should walk over and investigate - if ( level.alertEvents[eventID].level > AEL_MINOR && NPCInfo->investigateCount > 1 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - //make it so they can walk right to this point and look at it rather than having to use combatPoints - if ( G_ExpandPointToBBox( NPCInfo->investigateGoal, NPC->mins, NPC->maxs, NPC->s.number, ((NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP) ) ) - {//we were able to doMove the investigateGoal to a point in which our bbox would fit - //drop the goal to the ground so we can get at it - vec3_t end; - trace_t trace; - VectorCopy( NPCInfo->investigateGoal, end ); - end[2] -= 512;//FIXME: not always right? What if it's even higher, somehow? - gi.trace( &trace, NPCInfo->investigateGoal, NPC->mins, NPC->maxs, end, ENTITYNUM_NONE, ((NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP), (EG2_Collision)0, 0 ); - if ( trace.fraction >= 1.0f ) - {//too high to even bother - //FIXME: look at them??? - } - else - { - VectorCopy( trace.endpos, NPCInfo->investigateGoal ); - NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); + // See if we should walk over and investigate + if (level.alertEvents[eventID].level > AEL_MINOR && NPCInfo->investigateCount > 1 && (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + // make it so they can walk right to this point and look at it rather than having to use combatPoints + if (G_ExpandPointToBBox( + NPCInfo->investigateGoal, NPC->mins, NPC->maxs, NPC->s.number, + ((NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP))) { // we were able to doMove the investigateGoal to a point in which our bbox would fit + // drop the goal to the ground so we can get at it + vec3_t end; + trace_t trace; + VectorCopy(NPCInfo->investigateGoal, end); + end[2] -= 512; // FIXME: not always right? What if it's even higher, somehow? + gi.trace(&trace, NPCInfo->investigateGoal, NPC->mins, NPC->maxs, end, ENTITYNUM_NONE, ((NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP), + (EG2_Collision)0, 0); + if (trace.fraction >= 1.0f) { // too high to even bother + // FIXME: look at them??? + } else { + VectorCopy(trace.endpos, NPCInfo->investigateGoal); + NPC_SetMoveGoal(NPC, NPCInfo->investigateGoal, 16, qtrue); NPCInfo->localState = LSTATE_INVESTIGATE; } - } - else - { - int id = NPC_FindCombatPoint( NPCInfo->investigateGoal, NPCInfo->investigateGoal, NPCInfo->investigateGoal, CP_INVESTIGATE|CP_HAS_ROUTE, 0 ); + } else { + int id = NPC_FindCombatPoint(NPCInfo->investigateGoal, NPCInfo->investigateGoal, NPCInfo->investigateGoal, CP_INVESTIGATE | CP_HAS_ROUTE, 0); - if ( id != -1 ) - { - NPC_SetMoveGoal( NPC, level.combatPoints[id].origin, 16, qtrue, id ); + if (id != -1) { + NPC_SetMoveGoal(NPC, level.combatPoints[id].origin, 16, qtrue, id); NPCInfo->localState = LSTATE_INVESTIGATE; } } - //Say something - //FIXME: only if have others in group... these should be responses? - if ( NPCInfo->investigateDebounceTime+NPCInfo->pauseTime > level.time ) - {//was already investigating - if ( NPCInfo->group && - NPCInfo->group->commander && - NPCInfo->group->commander->client && - NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - { - ST_Speech( NPCInfo->group->commander, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds + // Say something + // FIXME: only if have others in group... these should be responses? + if (NPCInfo->investigateDebounceTime + NPCInfo->pauseTime > level.time) { // was already investigating + if (NPCInfo->group && NPCInfo->group->commander && NPCInfo->group->commander->client && + NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && !Q_irand(0, 3)) { + ST_Speech(NPCInfo->group->commander, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds + } else { + ST_Speech(NPC, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds } - else - { - ST_Speech( NPC, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds + } else { + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPC, SPEECH_SOUND, 0); } } - else - { - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPC, SPEECH_SOUND, 0 ); - } + // Setup the debounce info + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; + NPCInfo->investigateSoundDebounceTime = level.time + 2000; + NPCInfo->pauseTime = level.time; + } else { // just look? + // Say something + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPC, SPEECH_SOUND, 0); } - //Setup the debounce info - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; - NPCInfo->investigateSoundDebounceTime = level.time + 2000; - NPCInfo->pauseTime = level.time; - } - else - {//just look? - //Say something - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPC, SPEECH_SOUND, 0 ); - } - //Setup the debounce info - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 1000; - NPCInfo->investigateSoundDebounceTime = level.time + 1000; - NPCInfo->pauseTime = level.time; - VectorCopy( level.alertEvents[eventID].position, NPCInfo->investigateGoal ); - if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER - && !RT_Flying( NPC ) ) - { - //if ( !Q_irand( 0, 2 ) ) - {//look around - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // Setup the debounce info + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 1000; + NPCInfo->investigateSoundDebounceTime = level.time + 1000; + NPCInfo->pauseTime = level.time; + VectorCopy(level.alertEvents[eventID].position, NPCInfo->investigateGoal); + if (NPC->client->NPC_class == CLASS_ROCKETTROOPER && !RT_Flying(NPC)) { + // if ( !Q_irand( 0, 2 ) ) + { // look around + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } - if ( level.alertEvents[eventID].level >= AEL_DANGER ) - { - NPCInfo->investigateDebounceTime = Q_irand( 500, 2500 ); + if (level.alertEvents[eventID].level >= AEL_DANGER) { + NPCInfo->investigateDebounceTime = Q_irand(500, 2500); } - //Start investigating + // Start investigating NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; } @@ -1043,16 +897,15 @@ ST_OffsetLook ------------------------- */ -static void ST_OffsetLook( float offset, vec3_t out ) -{ - vec3_t angles, forward, temp; +static void ST_OffsetLook(float offset, vec3_t out) { + vec3_t angles, forward, temp; - GetAnglesForDirection( NPC->currentOrigin, NPCInfo->investigateGoal, angles ); + GetAnglesForDirection(NPC->currentOrigin, NPCInfo->investigateGoal, angles); angles[YAW] += offset; - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( NPC->currentOrigin, 64, forward, out ); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(NPC->currentOrigin, 64, forward, out); - CalcEntitySpot( NPC, SPOT_HEAD, temp ); + CalcEntitySpot(NPC, SPOT_HEAD, temp); out[2] = temp[2]; } @@ -1062,30 +915,25 @@ ST_LookAround ------------------------- */ -static void ST_LookAround( void ) -{ - vec3_t lookPos; - float perc = (float) ( level.time - NPCInfo->pauseTime ) / (float) NPCInfo->investigateDebounceTime; +static void ST_LookAround(void) { + vec3_t lookPos; + float perc = (float)(level.time - NPCInfo->pauseTime) / (float)NPCInfo->investigateDebounceTime; - //Keep looking at the spot - if ( perc < 0.25 ) + // Keep looking at the spot + if (perc < 0.25) { + VectorCopy(NPCInfo->investigateGoal, lookPos); + } else if (perc < 0.5f) // Look up but straight ahead { - VectorCopy( NPCInfo->investigateGoal, lookPos ); - } - else if ( perc < 0.5f ) //Look up but straight ahead - { - ST_OffsetLook( 0.0f, lookPos ); - } - else if ( perc < 0.75f ) //Look right + ST_OffsetLook(0.0f, lookPos); + } else if (perc < 0.75f) // Look right { - ST_OffsetLook( 45.0f, lookPos ); - } - else //Look left + ST_OffsetLook(45.0f, lookPos); + } else // Look left { - ST_OffsetLook( -45.0f, lookPos ); + ST_OffsetLook(-45.0f, lookPos); } - NPC_FacePosition( lookPos ); + NPC_FacePosition(lookPos); } /* @@ -1094,96 +942,81 @@ NPC_BSST_Investigate ------------------------- */ -void NPC_BSST_Investigate( void ) -{ - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPC ); +void NPC_BSST_Investigate(void) { + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPC); - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( NPCInfo->confusionTime < level.time ) - { - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - //Look for an enemy - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - ST_Speech( NPC, SPEECH_DETECTED, 0 ); - NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + // Look for an enemy + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + ST_Speech(NPC, SPEECH_DETECTED, 0); + NPCInfo->tempBehavior = BS_DEFAULT; + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, NPCInfo->lastAlertID ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, NPCInfo->lastAlertID); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPCInfo->confusionTime < level.time ) - { - if ( NPC_CheckForDanger( alertEvent ) ) - {//running like hell - ST_Speech( NPC, SPEECH_COVER, 0 );//FIXME: flee sound? + // There is an event to look at + if (alertEvent >= 0) { + if (NPCInfo->confusionTime < level.time) { + if (NPC_CheckForDanger(alertEvent)) { // running like hell + ST_Speech(NPC, SPEECH_COVER, 0); // FIXME: flee sound? return; } } - //if ( level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - { - NPC_ST_InvestigateEvent( alertEvent, qtrue ); - } + // if ( level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + { NPC_ST_InvestigateEvent(alertEvent, qtrue); } } } - //If we're done looking, then just return to what we were doing - if ( ( NPCInfo->investigateDebounceTime + NPCInfo->pauseTime ) < level.time ) - { + // If we're done looking, then just return to what we were doing + if ((NPCInfo->investigateDebounceTime + NPCInfo->pauseTime) < level.time) { NPCInfo->tempBehavior = BS_DEFAULT; NPCInfo->goalEntity = UpdateGoal(); - NPC_UpdateAngles( qtrue, qtrue ); - //Say something - ST_Speech( NPC, SPEECH_GIVEUP, 0 ); + NPC_UpdateAngles(qtrue, qtrue); + // Say something + ST_Speech(NPC, SPEECH_GIVEUP, 0); return; } - //FIXME: else, look for new alerts + // FIXME: else, look for new alerts - //See if we're searching for the noise's origin - if ( NPCInfo->localState == LSTATE_INVESTIGATE && (NPCInfo->goalEntity!=NULL) ) - { - //See if we're there - if ( !STEER::Reached(NPC, NPCInfo->goalEntity, 32, FlyingCreature(NPC) != qfalse) ) - { + // See if we're searching for the noise's origin + if (NPCInfo->localState == LSTATE_INVESTIGATE && (NPCInfo->goalEntity != NULL)) { + // See if we're there + if (!STEER::Reached(NPC, NPCInfo->goalEntity, 32, FlyingCreature(NPC) != qfalse)) { ucmd.buttons |= BUTTON_WALKING; - //Try and doMove there - if ( NPC_MoveToGoal( qtrue ) ) - { - //Bump our times - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; - NPCInfo->pauseTime = level.time; + // Try and doMove there + if (NPC_MoveToGoal(qtrue)) { + // Bump our times + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; + NPCInfo->pauseTime = level.time; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //Otherwise we're done or have given up - //Say something - //ST_Speech( NPC, SPEECH_LOOK, 0.33f ); + // Otherwise we're done or have given up + // Say something + // ST_Speech( NPC, SPEECH_LOOK, 0.33f ); NPCInfo->localState = LSTATE_NONE; } - //Look around + // Look around ST_LookAround(); } @@ -1193,167 +1026,130 @@ NPC_BSST_Patrol ------------------------- */ -void NPC_BSST_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - - //Not a scriptflag, but... - if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER && (NPC->client->ps.eFlags&EF_SPOTLIGHT) ) - {//using spotlight search mode - vec3_t eyeFwd, end, mins={-2,-2,-2}, maxs={2,2,2}; - trace_t trace; - AngleVectors( NPC->client->renderInfo.eyeAngles, eyeFwd, NULL, NULL ); - VectorMA( NPC->client->renderInfo.eyePoint, NPCInfo->stats.visrange, eyeFwd, end ); - //get server-side trace impact point - gi.trace( &trace, NPC->client->renderInfo.eyePoint, mins, maxs, end, NPC->s.number, MASK_OPAQUE|CONTENTS_BODY|CONTENTS_CORPSE, (EG2_Collision)0, 0 ); - NPC->speed = (trace.fraction*NPCInfo->stats.visrange); - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - //FIXME: do a FOV cone check, then a trace - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit something - //try cheap check first +void NPC_BSST_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + + // Not a scriptflag, but... + if (NPC->client->NPC_class == CLASS_ROCKETTROOPER && (NPC->client->ps.eFlags & EF_SPOTLIGHT)) { // using spotlight search mode + vec3_t eyeFwd, end, mins = {-2, -2, -2}, maxs = {2, 2, 2}; + trace_t trace; + AngleVectors(NPC->client->renderInfo.eyeAngles, eyeFwd, NULL, NULL); + VectorMA(NPC->client->renderInfo.eyePoint, NPCInfo->stats.visrange, eyeFwd, end); + // get server-side trace impact point + gi.trace(&trace, NPC->client->renderInfo.eyePoint, mins, maxs, end, NPC->s.number, MASK_OPAQUE | CONTENTS_BODY | CONTENTS_CORPSE, (EG2_Collision)0, 0); + NPC->speed = (trace.fraction * NPCInfo->stats.visrange); + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + // FIXME: do a FOV cone check, then a trace + if (trace.entityNum < ENTITYNUM_WORLD) { // hit something + // try cheap check first gentity_t *enemy = &g_entities[trace.entityNum]; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPC->client->enemyTeam ) - { - G_SetEnemy( NPC, enemy ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && enemy->client->playerTeam == NPC->client->enemyTeam) { + G_SetEnemy(NPC, enemy); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //FIXME: maybe do a quick check of ents within the spotlight's radius? - //hmmm, look around - if ( NPC_CheckEnemiesInSpotlight() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + // FIXME: maybe do a quick check of ents within the spotlight's radius? + // hmmm, look around + if (NPC_CheckEnemiesInSpotlight()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else - { - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPC ); + } else { + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPC); - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPC_CheckForDanger( alertEvent ) ) - {//going to run? - ST_Speech( NPC, SPEECH_COVER, 0 ); + // There is an event to look at + if (alertEvent >= 0) { + if (NPC_CheckForDanger(alertEvent)) { // going to run? + ST_Speech(NPC, SPEECH_COVER, 0); return; - } - else if (NPC->client->NPC_class==CLASS_BOBAFETT) - { - //NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[alertEvent].owner || - !level.alertEvents[alertEvent].owner->client || - level.alertEvents[alertEvent].owner->health <= 0 || - level.alertEvents[alertEvent].owner->client->playerTeam != NPC->client->enemyTeam ) - {//not an enemy + } else if (NPC->client->NPC_class == CLASS_BOBAFETT) { + // NPCInfo->lastAlertID = level.alertEvents[eventID].ID; + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || level.alertEvents[alertEvent].owner->health <= 0 || + level.alertEvents[alertEvent].owner->client->playerTeam != NPC->client->enemyTeam) { // not an enemy return; } - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - //ST_Speech( NPC, SPEECH_CHARGE, 0 ); - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or + // just let combat AI handle this... (act as if you lost him) ST_Speech( NPC, SPEECH_CHARGE, 0 ); + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return; - } - else if ( NPC_ST_InvestigateEvent( alertEvent, qfalse ) ) - {//actually going to investigate it - NPC_UpdateAngles( qtrue, qtrue ); + } else if (NPC_ST_InvestigateEvent(alertEvent, qfalse)) { // actually going to investigate it + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - //ST_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); - } - else// if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - if ( NPC->client->NPC_class != CLASS_IMPERIAL && NPC->client->NPC_class != CLASS_IMPWORKER ) - {//imperials do not look around - if ( TIMER_Done( NPC, "enemyLastVisible" ) ) - {//nothing suspicious, look around - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand( -90, 90 ); + // ST_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); + } else // if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) + { + if (NPC->client->NPC_class != CLASS_IMPERIAL && NPC->client->NPC_class != CLASS_IMPWORKER) { // imperials do not look around + if (TIMER_Done(NPC, "enemyLastVisible")) { // nothing suspicious, look around + if (!Q_irand(0, 30)) { + NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCInfo->desiredPitch = Q_irand(-20, 20); } } } } - NPC_UpdateAngles( qtrue, qtrue ); - //TEMP hack for Imperial stand anim - if ( NPC->client->NPC_class == CLASS_IMPERIAL - || NPC->client->NPC_class == CLASS_IMPWORKER ) - {//hack - if ( NPC->client->ps.weapon != WP_CONCUSSION ) - {//not Rax - if ( ucmd.forwardmove || ucmd.rightmove || ucmd.upmove ) - {//moving - - if( (!NPC->client->ps.torsoAnimTimer) || (NPC->client->ps.torsoAnim == BOTH_STAND4) ) - { - if ( (ucmd.buttons&BUTTON_WALKING) && !(NPCInfo->scriptFlags&SCF_RUNNING) ) - {//not running, only set upper anim + NPC_UpdateAngles(qtrue, qtrue); + // TEMP hack for Imperial stand anim + if (NPC->client->NPC_class == CLASS_IMPERIAL || NPC->client->NPC_class == CLASS_IMPWORKER) { // hack + if (NPC->client->ps.weapon != WP_CONCUSSION) { // not Rax + if (ucmd.forwardmove || ucmd.rightmove || ucmd.upmove) { // moving + + if ((!NPC->client->ps.torsoAnimTimer) || (NPC->client->ps.torsoAnim == BOTH_STAND4)) { + if ((ucmd.buttons & BUTTON_WALKING) && !(NPCInfo->scriptFlags & SCF_RUNNING)) { // not running, only set upper anim // No longer overrides scripted anims - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = 200; } } - } - else - {//standing still, set both torso and legs anim + } else { // standing still, set both torso and legs anim // No longer overrides scripted anims - if( ( !NPC->client->ps.torsoAnimTimer || (NPC->client->ps.torsoAnim == BOTH_STAND4) ) && - ( !NPC->client->ps.legsAnimTimer || (NPC->client->ps.legsAnim == BOTH_STAND4) ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((!NPC->client->ps.torsoAnimTimer || (NPC->client->ps.torsoAnim == BOTH_STAND4)) && + (!NPC->client->ps.legsAnimTimer || (NPC->client->ps.legsAnim == BOTH_STAND4))) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = NPC->client->ps.legsAnimTimer = 200; } } - //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way - if ( NPC->client->ps.weapon != WP_NONE ) - { - ChangeWeapon( NPC, WP_NONE ); + // FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way + if (NPC->client->ps.weapon != WP_NONE) { + ChangeWeapon(NPC, WP_NONE); NPC->client->ps.weapon = WP_NONE; NPC->client->ps.weaponstate = WEAPON_READY; - G_RemoveWeaponModels( NPC ); + G_RemoveWeaponModels(NPC); } } } @@ -1388,113 +1184,92 @@ ST_CheckMoveState ------------------------- */ -static void ST_CheckMoveState( void ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//moving toward a goal that a script is waiting on, so don't stop for anything! +static void ST_CheckMoveState(void) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // moving toward a goal that a script is waiting on, so don't stop for anything! doMove = qtrue; - } - else if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER - && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//no squad stuff + } else if (NPC->client->NPC_class == CLASS_ROCKETTROOPER && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // no squad stuff return; } -// else if ( NPC->NPC->scriptFlags&SCF_NO_GROUPS ) - { - doMove = qtrue; - } - //See if we're a scout - - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || - (enemyLOS && (NPCInfo->aiFlags&NPCAI_STOP_AT_LOS) && !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) - ) - {//either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and found our enemy - int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - //done fleeing, obviously - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - TIMER_Set( NPC, "flee", -level.time ); + // else if ( NPC->NPC->scriptFlags&SCF_NO_GROUPS ) + { doMove = qtrue; } + // See if we're a scout + + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (STEER::Reached(NPC, NPCInfo->goalEntity, 16, !!FlyingCreature(NPC)) || + (enemyLOS && (NPCInfo->aiFlags & NPCAI_STOP_AT_LOS) && + !Q3_TaskIDPending(NPC, TID_MOVE_NAV))) { // either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're + // scouting and found our enemy + int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + // done fleeing, obviously + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + TIMER_Set(NPC, "flee", -level.time); newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, newSquadState ); + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, newSquadState); NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet // THIS IS THE ONE TRUE PLACE WHERE ROAM TIME IS SET - TIMER_Set( NPC, "roamTime", Q_irand( 8000, 15000 ) );//Q_irand( 1000, 4000 ) ); - if (Q_irand(0, 3)==0) - { - TIMER_Set( NPC, "duck", Q_irand(5000, 10000) ); // just reached our goal, chance of ducking now + TIMER_Set(NPC, "roamTime", Q_irand(8000, 15000)); // Q_irand( 1000, 4000 ) ); + if (Q_irand(0, 3) == 0) { + TIMER_Set(NPC, "duck", Q_irand(5000, 10000)); // just reached our goal, chance of ducking now } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 8000, 9000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(8000, 9000)); } } -void ST_ResolveBlockedShot( int hit ) -{ - int stuckTime; - //figure out how long we intend to stand here, max - if ( TIMER_Get( NPC, "roamTime" ) > TIMER_Get( NPC, "stick" ) ) - { - stuckTime = TIMER_Get( NPC, "roamTime" )-level.time; - } - else - { - stuckTime = TIMER_Get( NPC, "stick" )-level.time; +void ST_ResolveBlockedShot(int hit) { + int stuckTime; + // figure out how long we intend to stand here, max + if (TIMER_Get(NPC, "roamTime") > TIMER_Get(NPC, "stick")) { + stuckTime = TIMER_Get(NPC, "roamTime") - level.time; + } else { + stuckTime = TIMER_Get(NPC, "stick") - level.time; } - if ( TIMER_Done( NPC, "duck" ) ) - {//we're not ducking - if ( AI_GroupContainsEntNum( NPCInfo->group, hit ) ) - { + if (TIMER_Done(NPC, "duck")) { // we're not ducking + if (AI_GroupContainsEntNum(NPCInfo->group, hit)) { gentity_t *member = &g_entities[hit]; - if ( TIMER_Done( member, "duck" ) ) - {//they aren't ducking - if ( TIMER_Done( member, "stand" ) ) - {//they're not being forced to stand - //tell them to duck at least as long as I'm not moving - TIMER_Set( member, "duck", stuckTime ); // tell my friend to duck so I can shoot over his head + if (TIMER_Done(member, "duck")) { // they aren't ducking + if (TIMER_Done(member, "stand")) { // they're not being forced to stand + // tell them to duck at least as long as I'm not moving + TIMER_Set(member, "duck", stuckTime); // tell my friend to duck so I can shoot over his head return; } } } - } - else - {//maybe we should stand - if ( TIMER_Done( NPC, "stand" ) ) - {//stand for as long as we'll be here - TIMER_Set( NPC, "stand", stuckTime ); + } else { // maybe we should stand + if (TIMER_Done(NPC, "stand")) { // stand for as long as we'll be here + TIMER_Set(NPC, "stand", stuckTime); return; } } - //Hmm, can't resolve this by telling them to duck or telling me to stand - //We need to doMove! - TIMER_Set( NPC, "roamTime", -1 ); - TIMER_Set( NPC, "stick", -1 ); - TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( NPC, "attakDelay", Q_irand( 1000, 3000 ) ); + // Hmm, can't resolve this by telling them to duck or telling me to stand + // We need to doMove! + TIMER_Set(NPC, "roamTime", -1); + TIMER_Set(NPC, "stick", -1); + TIMER_Set(NPC, "duck", -1); + TIMER_Set(NPC, "attakDelay", Q_irand(1000, 3000)); } /* @@ -1503,134 +1278,120 @@ ST_CheckFireState ------------------------- */ -static void ST_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void ST_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //See if we should continue to fire on their last position - //!TIMER_Done( NPC, "stick" ) || - if ( !hitAlly //we're not going to hit an ally - && enemyInFOV //enemy is in our FOV //FIXME: or we don't have a clear LOS? - && NPCInfo->enemyLastSeenTime > 0 //we've seen the enemy - && NPCInfo->group //have a group - && (NPCInfo->group->numState[SQUAD_RETREAT]>0||NPCInfo->group->numState[SQUAD_TRANSITION]>0||NPCInfo->group->numState[SQUAD_SCOUT]>0) )//laying down covering fire + // See if we should continue to fire on their last position + //! TIMER_Done( NPC, "stick" ) || + if (!hitAlly // we're not going to hit an ally + && enemyInFOV // enemy is in our FOV //FIXME: or we don't have a clear LOS? + && NPCInfo->enemyLastSeenTime > 0 // we've seen the enemy + && NPCInfo->group // have a group + && (NPCInfo->group->numState[SQUAD_RETREAT] > 0 || NPCInfo->group->numState[SQUAD_TRANSITION] > 0 || + NPCInfo->group->numState[SQUAD_SCOUT] > 0)) // laying down covering fire { - if ( level.time - NPCInfo->enemyLastSeenTime < 10000 &&//we have seem the enemy in the last 10 seconds - (!NPCInfo->group || level.time - NPCInfo->group->lastSeenEnemyTime < 10000 ))//we are not in a group or the group has seen the enemy in the last 10 seconds + if (level.time - NPCInfo->enemyLastSeenTime < 10000 && // we have seem the enemy in the last 10 seconds + (!NPCInfo->group || + level.time - NPCInfo->group->lastSeenEnemyTime < 10000)) // we are not in a group or the group has seen the enemy in the last 10 seconds { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - gi.trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - float distThreshold = 16384/*128*128*/;//default - switch ( NPC->s.weapon ) - { + // see if impact would be too close to me + float distThreshold = 16384 /*128*128*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; case WP_CONCUSSION: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - distThreshold = 65536/*256*256*/; + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - float dist = DistanceSquared( impactPos, muzzle ); + float dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 5000 || - (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000 )) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - switch ( NPC->s.weapon ) - { + } else if (level.time - NPCInfo->enemyLastSeenTime > 5000 || + (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000)) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 262144/*512*512*/; + distThreshold = 262144 /*512*512*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } break; case WP_CONCUSSION: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - distThreshold = 262144/*512*512*/; + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + distThreshold = 262144 /*512*512*/; } break; default: break; } - dist = DistanceSquared( impactPos, NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; faceEnemy = qfalse; - //AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); + // AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); return; } } @@ -1638,125 +1399,102 @@ static void ST_CheckFireState( void ) } } -void ST_TrackEnemy( gentity_t *self, vec3_t enemyPos ) -{ - //clear timers - TIMER_Set( self, "attackDelay", Q_irand( 1000, 2000 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint ); - //go after his last seen pos - NPC_SetMoveGoal( self, enemyPos, 100.0f, qfalse ); - if (Q_irand(0,3)==0) - { +void ST_TrackEnemy(gentity_t *self, vec3_t enemyPos) { + // clear timers + TIMER_Set(self, "attackDelay", Q_irand(1000, 2000)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(500, 1500)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint); + // go after his last seen pos + NPC_SetMoveGoal(self, enemyPos, 100.0f, qfalse); + if (Q_irand(0, 3) == 0) { NPCInfo->aiFlags |= NPCAI_STOP_AT_LOS; } } -int ST_ApproachEnemy( gentity_t *self ) -{ - TIMER_Set( self, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 1000, 2000 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint ); - //return the relevant combat point flags - return (CP_CLEAR|CP_CLOSEST); +int ST_ApproachEnemy(gentity_t *self) { + TIMER_Set(self, "attackDelay", Q_irand(250, 500)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(1000, 2000)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint); + // return the relevant combat point flags + return (CP_CLEAR | CP_CLOSEST); } -void ST_HuntEnemy( gentity_t *self ) -{ - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack - //TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( NPC, "stick", Q_irand( 250, 1000 ) ); - TIMER_Set( NPC, "stand", -1 ); - TIMER_Set( NPC, "scoutTime", TIMER_Get( NPC, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( NPCInfo->combatPoint ); - //go directly after the enemy - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { +void ST_HuntEnemy(gentity_t *self) { + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack + // TIMER_Set( NPC, "duck", -1 ); + TIMER_Set(NPC, "stick", Q_irand(250, 1000)); + TIMER_Set(NPC, "stand", -1); + TIMER_Set(NPC, "scoutTime", TIMER_Get(NPC, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(NPCInfo->combatPoint); + // go directly after the enemy + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { self->NPC->goalEntity = NPC->enemy; } } -void ST_TransferTimers( gentity_t *self, gentity_t *other ) -{ - TIMER_Set( other, "attackDelay", TIMER_Get( self, "attackDelay" )-level.time ); - TIMER_Set( other, "duck", TIMER_Get( self, "duck" )-level.time ); - TIMER_Set( other, "stick", TIMER_Get( self, "stick" )-level.time ); - TIMER_Set( other, "scoutTime", TIMER_Get( self, "scoutTime" )-level.time ); - TIMER_Set( other, "roamTime", TIMER_Get( self, "roamTime" )-level.time ); - TIMER_Set( other, "stand", TIMER_Get( self, "stand" )-level.time ); - TIMER_Set( self, "attackDelay", -1 ); - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", -1 ); - TIMER_Set( self, "scoutTime", -1 ); - TIMER_Set( self, "roamTime", -1 ); - TIMER_Set( self, "stand", -1 ); +void ST_TransferTimers(gentity_t *self, gentity_t *other) { + TIMER_Set(other, "attackDelay", TIMER_Get(self, "attackDelay") - level.time); + TIMER_Set(other, "duck", TIMER_Get(self, "duck") - level.time); + TIMER_Set(other, "stick", TIMER_Get(self, "stick") - level.time); + TIMER_Set(other, "scoutTime", TIMER_Get(self, "scoutTime") - level.time); + TIMER_Set(other, "roamTime", TIMER_Get(self, "roamTime") - level.time); + TIMER_Set(other, "stand", TIMER_Get(self, "stand") - level.time); + TIMER_Set(self, "attackDelay", -1); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stick", -1); + TIMER_Set(self, "scoutTime", -1); + TIMER_Set(self, "roamTime", -1); + TIMER_Set(self, "stand", -1); } -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ) -{ - if ( Q3_TaskIDPending( self, TID_MOVE_NAV ) ) - {//can't transfer movegoal when a script we're running is waiting to complete +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other) { + if (Q3_TaskIDPending(self, TID_MOVE_NAV)) { // can't transfer movegoal when a script we're running is waiting to complete return; } - if ( self->NPC->combatPoint != -1 ) - {//I've got a combatPoint I'm going to, give it to him + if (self->NPC->combatPoint != -1) { // I've got a combatPoint I'm going to, give it to him self->NPC->lastFailedCombatPoint = other->NPC->combatPoint = self->NPC->combatPoint; self->NPC->combatPoint = -1; - } - else - {//I must be going for a goal, give that to him instead - if ( self->NPC->goalEntity == self->NPC->tempGoal ) - { - NPC_SetMoveGoal( other, self->NPC->tempGoal->currentOrigin, self->NPC->goalRadius, (qboolean)((self->NPC->tempGoal->svFlags & SVF_NAVGOAL) != 0) ); - } - else - { + } else { // I must be going for a goal, give that to him instead + if (self->NPC->goalEntity == self->NPC->tempGoal) { + NPC_SetMoveGoal(other, self->NPC->tempGoal->currentOrigin, self->NPC->goalRadius, (qboolean)((self->NPC->tempGoal->svFlags & SVF_NAVGOAL) != 0)); + } else { other->NPC->goalEntity = self->NPC->goalEntity; } } - //give him my squadstate - AI_GroupUpdateSquadstates( self->NPC->group, other, NPCInfo->squadState ); + // give him my squadstate + AI_GroupUpdateSquadstates(self->NPC->group, other, NPCInfo->squadState); - //give him my timers and clear mine - ST_TransferTimers( self, other ); + // give him my timers and clear mine + ST_TransferTimers(self, other); - //now make me stand around for a second or two at least - AI_GroupUpdateSquadstates( self->NPC->group, self, SQUAD_STAND_AND_SHOOT ); - TIMER_Set( self, "stand", Q_irand( 1000, 3000 ) ); + // now make me stand around for a second or two at least + AI_GroupUpdateSquadstates(self->NPC->group, self, SQUAD_STAND_AND_SHOOT); + TIMER_Set(self, "stand", Q_irand(1000, 3000)); } -int ST_GetCPFlags( void ) -{ +int ST_GetCPFlags(void) { int cpFlags = 0; - if ( NPC && NPCInfo->group ) - { - if ( NPC == NPCInfo->group->commander && NPC->client->NPC_class == CLASS_IMPERIAL ) - {//imperials hang back and give orders - if ( NPCInfo->group->numGroup > 1 && Q_irand( -3, NPCInfo->group->numGroup ) > 1 ) - {//FIXME: make sure he;s giving orders with these lines - if ( Q_irand( 0, 1 ) ) - { - ST_Speech( NPC, SPEECH_CHASE, 0.5 ); - } - else - { - ST_Speech( NPC, SPEECH_YELL, 0.5 ); + if (NPC && NPCInfo->group) { + if (NPC == NPCInfo->group->commander && NPC->client->NPC_class == CLASS_IMPERIAL) { // imperials hang back and give orders + if (NPCInfo->group->numGroup > 1 && Q_irand(-3, NPCInfo->group->numGroup) > 1) { // FIXME: make sure he;s giving orders with these lines + if (Q_irand(0, 1)) { + ST_Speech(NPC, SPEECH_CHASE, 0.5); + } else { + ST_Speech(NPC, SPEECH_YELL, 0.5); } } - cpFlags = (CP_CLEAR|CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); - } - else if ( NPCInfo->group->morale < 0 ) - {//hide - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); + cpFlags = (CP_CLEAR | CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); + } else if (NPCInfo->group->morale < 0) { // hide + cpFlags = (CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); /* if ( NPC->client->NPC_class == CLASS_SABOTEUR && !Q_irand( 0, 3 ) ) { @@ -1764,43 +1502,37 @@ int ST_GetCPFlags( void ) } */ } -/* else if ( NPCInfo->group->morale < NPCInfo->group->numGroup ) - {//morale is low for our size - int moraleDrop = NPCInfo->group->numGroup - NPCInfo->group->morale; - if ( moraleDrop < -6 ) - {//flee (no clear shot needed) - cpFlags = (CP_FLEE|CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < -3 ) - {//retreat (no clear shot needed) - cpFlags = (CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < 0 ) - {//cover (no clear shot needed) - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE); - } - }*/ - else - { + /* else if ( NPCInfo->group->morale < NPCInfo->group->numGroup ) + {//morale is low for our size + int moraleDrop = NPCInfo->group->numGroup - NPCInfo->group->morale; + if ( moraleDrop < -6 ) + {//flee (no clear shot needed) + cpFlags = (CP_FLEE|CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); + } + else if ( moraleDrop < -3 ) + {//retreat (no clear shot needed) + cpFlags = (CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); + } + else if ( moraleDrop < 0 ) + {//cover (no clear shot needed) + cpFlags = (CP_COVER|CP_AVOID|CP_SAFE); + } + }*/ + else { int moraleBoost = NPCInfo->group->morale - NPCInfo->group->numGroup; - if ( moraleBoost > 20 ) - {//charge to any one and outflank (no cover needed) - cpFlags = (CP_CLEAR|CP_FLANK|CP_APPROACH_ENEMY); - //Saboteur_Decloak( NPC ); - } - else if ( moraleBoost > 15 ) - {//charge to closest one (no cover needed) - cpFlags = (CP_CLEAR|CP_CLOSEST|CP_APPROACH_ENEMY); + if (moraleBoost > 20) { // charge to any one and outflank (no cover needed) + cpFlags = (CP_CLEAR | CP_FLANK | CP_APPROACH_ENEMY); + // Saboteur_Decloak( NPC ); + } else if (moraleBoost > 15) { // charge to closest one (no cover needed) + cpFlags = (CP_CLEAR | CP_CLOSEST | CP_APPROACH_ENEMY); /* if ( NPC->client->NPC_class == CLASS_SABOTEUR && !Q_irand( 0, 3 ) ) { Saboteur_Decloak( NPC ); } */ - } - else if ( moraleBoost > 10 ) - {//charge closer (no cover needed) - cpFlags = (CP_CLEAR|CP_APPROACH_ENEMY); + } else if (moraleBoost > 10) { // charge closer (no cover needed) + cpFlags = (CP_CLEAR | CP_APPROACH_ENEMY); /* if ( NPC->client->NPC_class == CLASS_SABOTEUR && !Q_irand( 0, 6 ) ) { @@ -1810,28 +1542,25 @@ int ST_GetCPFlags( void ) } } } - if ( !cpFlags ) - { - //at some medium level of morale - switch( Q_irand( 0, 3 ) ) - { - case 0://just take the nearest one - cpFlags = (CP_CLEAR|CP_COVER|CP_NEAREST); + if (!cpFlags) { + // at some medium level of morale + switch (Q_irand(0, 3)) { + case 0: // just take the nearest one + cpFlags = (CP_CLEAR | CP_COVER | CP_NEAREST); break; - case 1://take one closer to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_APPROACH_ENEMY); + case 1: // take one closer to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_APPROACH_ENEMY); break; - case 2://take the one closest to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_CLOSEST|CP_APPROACH_ENEMY); + case 2: // take the one closest to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_CLOSEST | CP_APPROACH_ENEMY); break; - case 3://take the one on the other side of the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); + case 3: // take the one on the other side of the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); break; } } - if ( NPC && (NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPC && (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } return cpFlags; @@ -1850,60 +1579,49 @@ FIXME: work in pairs? ------------------------- */ -void ST_Commander( void ) -{ - int i;//, j; - int cp, cpFlags; - AIGroupInfo_t *group = NPCInfo->group; - gentity_t *member;//, *buddy; - qboolean enemyLost = qfalse; - float avoidDist; +void ST_Commander(void) { + int i; //, j; + int cp, cpFlags; + AIGroupInfo_t *group = NPCInfo->group; + gentity_t *member; //, *buddy; + qboolean enemyLost = qfalse; + float avoidDist; group->processed = qtrue; - if ( group->enemy == NULL || group->enemy->client == NULL ) - {//hmm, no enemy...?! + if (group->enemy == NULL || group->enemy->client == NULL) { // hmm, no enemy...?! return; } - //FIXME: have this group commander check the enemy group (if any) and see if they have + // FIXME: have this group commander check the enemy group (if any) and see if they have // superior numbers. If they do, fall back rather than advance. If you have // superior numbers, advance on them. - //FIXME: find the group commander and have him occasionally give orders when there is speech - //FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left + // FIXME: find the group commander and have him occasionally give orders when there is speech + // FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left SaveNPCGlobals(); - if ( group->lastSeenEnemyTime < level.time - 180000 ) - {//dissolve the group - ST_Speech( NPC, SPEECH_LOST, 0.0f ); + if (group->lastSeenEnemyTime < level.time - 180000) { // dissolve the group + ST_Speech(NPC, SPEECH_LOST, 0.0f); group->enemy->waypoint = NAV::GetNearestNode(group->enemy); - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - SetNPCGlobals( member ); - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't break from that + SetNPCGlobals(member); + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't break from that continue; } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to doMove on my own + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to doMove on my own continue; } - //Lost enemy for three minutes? go into search mode? - G_ClearEnemy( NPC ); + // Lost enemy for three minutes? go into search mode? + G_ClearEnemy(NPC); NPC->waypoint = NAV::GetNearestNode(group->enemy); - if ( NPC->waypoint == WAYPOINT_NONE ) - { - NPCInfo->behaviorState = BS_DEFAULT;//BS_PATROL; - } - else if ( group->enemy->waypoint == WAYPOINT_NONE || (NAV::EstimateCostToGoal( NPC->waypoint, group->enemy->waypoint ) >= Q3_INFINITE) ) - { - NPC_BSSearchStart( NPC->waypoint, BS_SEARCH ); - } - else - { - NPC_BSSearchStart( group->enemy->waypoint, BS_SEARCH ); + if (NPC->waypoint == WAYPOINT_NONE) { + NPCInfo->behaviorState = BS_DEFAULT; // BS_PATROL; + } else if (group->enemy->waypoint == WAYPOINT_NONE || (NAV::EstimateCostToGoal(NPC->waypoint, group->enemy->waypoint) >= Q3_INFINITE)) { + NPC_BSSearchStart(NPC->waypoint, BS_SEARCH); + } else { + NPC_BSSearchStart(group->enemy->waypoint, BS_SEARCH); } } group->enemy = NULL; @@ -1911,276 +1629,220 @@ void ST_Commander( void ) return; } - if ( /*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && group->lastSeenEnemyTime < level.time - 30000 ) - {//no-one has seen the enemy for 30 seconds// and no-one is running after him - if ( group->commander && !Q_irand( 0, 1 ) ) - { - ST_Speech( group->commander, SPEECH_ESCAPING, 0.0f ); + if (/*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && + group->lastSeenEnemyTime < level.time - 30000) { // no-one has seen the enemy for 30 seconds// and no-one is running after him + if (group->commander && !Q_irand(0, 1)) { + ST_Speech(group->commander, SPEECH_ESCAPING, 0.0f); + } else { + ST_Speech(NPC, SPEECH_ESCAPING, 0.0f); } - else - { - ST_Speech( NPC, SPEECH_ESCAPING, 0.0f ); - } - //don't say this again + // don't say this again NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } - if ( group->lastSeenEnemyTime < level.time - 7000 ) - {//no-one has seen the enemy for at least 10 seconds! Should send a scout + if (group->lastSeenEnemyTime < level.time - 7000) { // no-one has seen the enemy for at least 10 seconds! Should send a scout enemyLost = qtrue; } - //Go through the list: + // Go through the list: - //Everyone should try to get to a combat point if possible - int curMemberNum, lastMemberNum; - if ( d_asynchronousGroupAI->integer ) - {//do one member a turn + // Everyone should try to get to a combat point if possible + int curMemberNum, lastMemberNum; + if (d_asynchronousGroupAI->integer) { // do one member a turn group->activeMemberNum++; - if ( group->activeMemberNum >= group->numGroup ) - { + if (group->activeMemberNum >= group->numGroup) { group->activeMemberNum = 0; } curMemberNum = group->activeMemberNum; lastMemberNum = curMemberNum + 1; - } - else - { + } else { curMemberNum = 0; lastMemberNum = group->numGroup; } - for ( i = curMemberNum; i < lastMemberNum; i++ ) - { - //reset combat point flags + for (i = curMemberNum; i < lastMemberNum; i++) { + // reset combat point flags cp = -1; cpFlags = 0; avoidDist = 0; - //get the next guy + // get the next guy member = &g_entities[group->member[i].number]; - if ( !member->enemy ) - {//don't include guys that aren't angry + if (!member->enemy) { // don't include guys that aren't angry continue; } - SetNPCGlobals( member ); + SetNPCGlobals(member); - if ( !TIMER_Done( NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPC, "flee")) { // running away continue; } - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go continue; } - if ( NPC->s.weapon == WP_NONE - && NPCInfo->goalEntity - && NPCInfo->goalEntity == NPCInfo->tempGoal - && NPCInfo->goalEntity->s.eType == ET_ITEM ) - {//running to pick up a gun, don't do other logic + if (NPC->s.weapon == WP_NONE && NPCInfo->goalEntity && NPCInfo->goalEntity == NPCInfo->tempGoal && + NPCInfo->goalEntity->s.eType == ET_ITEM) { // running to pick up a gun, don't do other logic continue; } - - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to do combat-movement + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to do combat-movement continue; } - - if ( NPC->client->ps.weapon == WP_NONE ) - {//weaponless, should be hiding - if ( NPCInfo->goalEntity == NULL || NPCInfo->goalEntity->enemy == NULL || NPCInfo->goalEntity->enemy->s.eType != ET_ITEM ) - {//not running after a pickup - if ( TIMER_Done( NPC, "hideTime" ) || (DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < 65536 && NPC_ClearLOS( NPC->enemy )) ) - {//done hiding or enemy near and can see us - //er, start another flee I guess? - NPC_StartFlee( NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - }//else, just hang here + if (NPC->client->ps.weapon == WP_NONE) { // weaponless, should be hiding + if (NPCInfo->goalEntity == NULL || NPCInfo->goalEntity->enemy == NULL || + NPCInfo->goalEntity->enemy->s.eType != ET_ITEM) { // not running after a pickup + if (TIMER_Done(NPC, "hideTime") || (DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < 65536 && + NPC_ClearLOS(NPC->enemy))) { // done hiding or enemy near and can see us + // er, start another flee I guess? + NPC_StartFlee(NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } // else, just hang here } continue; } - if (enemyLost && NAV::InSameRegion(NPC, NPC->enemy->currentOrigin)) - { - ST_TrackEnemy( NPC, NPC->enemy->currentOrigin ); + if (enemyLost && NAV::InSameRegion(NPC, NPC->enemy->currentOrigin)) { + ST_TrackEnemy(NPC, NPC->enemy->currentOrigin); continue; } - if (!NPC->enemy) - { + if (!NPC->enemy) { continue; } - // Check To See We Have A Clear Shot To The Enemy Every Couple Seconds //--------------------------------------------------------------------- - if (TIMER_Done( NPC, "checkGrenadeTooCloseDebouncer" )) - { - TIMER_Set (NPC, "checkGrenadeTooCloseDebouncer", Q_irand(300, 600)); + if (TIMER_Done(NPC, "checkGrenadeTooCloseDebouncer")) { + TIMER_Set(NPC, "checkGrenadeTooCloseDebouncer", Q_irand(300, 600)); - vec3_t mins; - vec3_t maxs; - bool fled = false; - gentity_t* ent; + vec3_t mins; + vec3_t maxs; + bool fled = false; + gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; + gentity_t *entityList[MAX_GENTITIES]; - for (int i = 0 ; i < 3 ; i++ ) - { + for (int i = 0; i < 3; i++) { mins[i] = NPC->currentOrigin[i] - 200; maxs[i] = NPC->currentOrigin[i] + 200; } - int numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + int numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for (int e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (int e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == NPC) continue; if (ent->owner == NPC) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType == ET_MISSILE ) - { - if ( ent->s.weapon == WP_THERMAL ) - {//a thermal - if ( ent->has_bounced && (!ent->owner || !OnSameTeam(ent->owner, NPC))) - {//bounced and an enemy thermal - ST_Speech( NPC, SPEECH_COVER, 0 );//FIXME: flee sound? + if (ent->s.eType == ET_MISSILE) { + if (ent->s.weapon == WP_THERMAL) { // a thermal + if (ent->has_bounced && (!ent->owner || !OnSameTeam(ent->owner, NPC))) { // bounced and an enemy thermal + ST_Speech(NPC, SPEECH_COVER, 0); // FIXME: flee sound? NPC_StartFlee(NPC->enemy, ent->currentOrigin, AEL_DANGER_GREAT, 1000, 2000); fled = true; -// cpFlags |= (CP_CLEAR|CP_COVER); // NOPE, Can't See The Enemy, So Find A New Combat Point - TIMER_Set (NPC, "checkGrenadeTooCloseDebouncer", Q_irand(2000, 4000)); + // cpFlags |= (CP_CLEAR|CP_COVER); // NOPE, Can't See The Enemy, So Find A New Combat Point + TIMER_Set(NPC, "checkGrenadeTooCloseDebouncer", Q_irand(2000, 4000)); break; } } } } - if (fled) - { + if (fled) { continue; } } - // Check To See We Have A Clear Shot To The Enemy Every Couple Seconds //--------------------------------------------------------------------- - if (TIMER_Done( NPC, "checkEnemyVisDebouncer" )) - { - TIMER_Set (NPC, "checkEnemyVisDebouncer", Q_irand(3000, 7000)); - if (!NPC_ClearLOS(NPC->enemy)) - { - cpFlags |= (CP_CLEAR|CP_COVER); // NOPE, Can't See The Enemy, So Find A New Combat Point + if (TIMER_Done(NPC, "checkEnemyVisDebouncer")) { + TIMER_Set(NPC, "checkEnemyVisDebouncer", Q_irand(3000, 7000)); + if (!NPC_ClearLOS(NPC->enemy)) { + cpFlags |= (CP_CLEAR | CP_COVER); // NOPE, Can't See The Enemy, So Find A New Combat Point } } // Check To See If The Enemy Is Too Close For Comfort //---------------------------------------------------- - if (NPC->client->NPC_class!=CLASS_ASSASSIN_DROID) - { - if (TIMER_Done(NPC, "checkEnemyTooCloseDebouncer")) - { - TIMER_Set (NPC, "checkEnemyTooCloseDebouncer", Q_irand(1000, 6000)); + if (NPC->client->NPC_class != CLASS_ASSASSIN_DROID) { + if (TIMER_Done(NPC, "checkEnemyTooCloseDebouncer")) { + TIMER_Set(NPC, "checkEnemyTooCloseDebouncer", Q_irand(1000, 6000)); - float distThreshold = 16384/*128*128*/;//default - switch ( NPC->s.weapon ) - { + float distThreshold = 16384 /*128*128*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; case WP_CONCUSSION: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - distThreshold = 65536/*256*256*/; + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - if ( DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < distThreshold ) - { - cpFlags |= (CP_CLEAR|CP_COVER); + if (DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < distThreshold) { + cpFlags |= (CP_CLEAR | CP_COVER); } } } - - //clear the local state + // clear the local state NPCInfo->localState = LSTATE_NONE; cpFlags &= ~CP_NEAREST; - //Assign combat points - if ( cpFlags ) - {//we want to run to a combat point - //always avoid enemy when picking combat points, and we always want to be able to get there - cpFlags |= CP_AVOID_ENEMY|CP_HAS_ROUTE|CP_TRYFAR; - avoidDist = 200; - - //now get a combat point - if ( cp == -1 ) - {//may have had sone set above - cp = NPC_FindCombatPointRetry( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, &cpFlags, avoidDist, NPCInfo->lastFailedCombatPoint ); - } + // Assign combat points + if (cpFlags) { // we want to run to a combat point + // always avoid enemy when picking combat points, and we always want to be able to get there + cpFlags |= CP_AVOID_ENEMY | CP_HAS_ROUTE | CP_TRYFAR; + avoidDist = 200; - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - //let others know that someone is now running - //don't change course again until we get to where we're going - TIMER_Set( NPC, "roamTime", Q3_INFINITE ); + // now get a combat point + if (cp == -1) { // may have had sone set above + cp = NPC_FindCombatPointRetry(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, &cpFlags, avoidDist, NPCInfo->lastFailedCombatPoint); + } + // see if we got a valid one + if (cp != -1) { // found a combat point + // let others know that someone is now running + // don't change course again until we get to where we're going + TIMER_Set(NPC, "roamTime", Q3_INFINITE); - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); // If Successfully - if ((cpFlags&CP_FLANK) || ((cpFlags&CP_COVER) && (cpFlags&CP_CLEAR))) - { - } - else if (Q_irand(0,3)==0) - { + if ((cpFlags & CP_FLANK) || ((cpFlags & CP_COVER) && (cpFlags & CP_CLEAR))) { + } else if (Q_irand(0, 3) == 0) { NPCInfo->aiFlags |= NPCAI_STOP_AT_LOS; } - //okay, try a doMove right now to see if we can even get there - if ( (cpFlags&CP_FLANK) ) - { - if ( group->numGroup > 1 ) - { - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); + // okay, try a doMove right now to see if we can even get there + if ((cpFlags & CP_FLANK)) { + if (group->numGroup > 1) { + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); } - } - else if ( (cpFlags&CP_COVER) && !(cpFlags&CP_CLEAR) ) - {//going into hiding - NPC_ST_StoreMovementSpeech( SPEECH_COVER, -1 ); - } - else - { - if ( !Q_irand( 0, 20 ) ) - {//hell, we're loading the sounds, use them every now and then! - if ( Q_irand( 0, 1 ) ) - { - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); - } - else - { - NPC_ST_StoreMovementSpeech( SPEECH_ESCAPING, -1 ); + } else if ((cpFlags & CP_COVER) && !(cpFlags & CP_CLEAR)) { // going into hiding + NPC_ST_StoreMovementSpeech(SPEECH_COVER, -1); + } else { + if (!Q_irand(0, 20)) { // hell, we're loading the sounds, use them every now and then! + if (Q_irand(0, 1)) { + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); + } else { + NPC_ST_StoreMovementSpeech(SPEECH_ESCAPING, -1); } } } @@ -2192,55 +1854,42 @@ void ST_Commander( void ) return; } -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -void Noghri_StickTrace( void ) -{ - if ( !NPC->ghoul2.size() - || NPC->weaponModel[0] <= 0 ) - { +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +void Noghri_StickTrace(void) { + if (!NPC->ghoul2.size() || NPC->weaponModel[0] <= 0) { return; } - int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); - if ( boltIndex != -1 ) - { - int curTime = (cg.time?cg.time:level.time); + int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); + if (boltIndex != -1) { + int curTime = (cg.time ? cg.time : level.time); qboolean hit = qfalse; - int lastHit = ENTITYNUM_NONE; - for ( int time = curTime-25; time <= curTime+25&&!hit; time += 25 ) - { - mdxaBone_t boltMatrix; - vec3_t tip, dir, base, angles={0,NPC->currentAngles[YAW],0}; - vec3_t mins={-2,-2,-2},maxs={2,2,2}; - trace_t trace; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->weaponModel[0], - boltIndex, - &boltMatrix, angles, NPC->currentOrigin, time, - NULL, NPC->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, base ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, dir ); - VectorMA( base, 48, dir, tip ); - #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { + int lastHit = ENTITYNUM_NONE; + for (int time = curTime - 25; time <= curTime + 25 && !hit; time += 25) { + mdxaBone_t boltMatrix; + vec3_t tip, dir, base, angles = {0, NPC->currentAngles[YAW], 0}; + vec3_t mins = {-2, -2, -2}, maxs = {2, 2, 2}; + trace_t trace; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->weaponModel[0], boltIndex, &boltMatrix, angles, NPC->currentOrigin, time, NULL, NPC->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, base); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, dir); + VectorMA(base, 48, dir, tip); +#ifndef FINAL_BUILD + if (d_saberCombat->integer > 1) { G_DebugLine(base, tip, FRAMETIME, 0x000000ff, qtrue); } - #endif - gi.trace( &trace, base, mins, maxs, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( trace.fraction < 1.0f && trace.entityNum != lastHit ) - {//hit something +#endif + gi.trace(&trace, base, mins, maxs, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10); + if (trace.fraction < 1.0f && trace.entityNum != lastHit) { // hit something gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt->takedamage - && (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class) ) - {//smack - int dmg = Q_irand( 12, 20 );//FIXME: base on skill! - //FIXME: debounce? - G_Sound( traceEnt, G_SoundIndex( va( "sound/weapons/tusken_staff/stickhit%d.wav", Q_irand( 1, 4 ) ) ) ); - G_Damage( traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - if ( traceEnt->health > 0 && dmg > 17 ) - {//do pain on enemy - G_Knockdown( traceEnt, NPC, dir, 300, qtrue ); + if (traceEnt->takedamage && (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class)) { // smack + int dmg = Q_irand(12, 20); // FIXME: base on skill! + // FIXME: debounce? + G_Sound(traceEnt, G_SoundIndex(va("sound/weapons/tusken_staff/stickhit%d.wav", Q_irand(1, 4)))); + G_Damage(traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + if (traceEnt->health > 0 && dmg > 17) { // do pain on enemy + G_Knockdown(traceEnt, NPC, dir, 300, qtrue); } lastHit = trace.entityNum; hit = qtrue; @@ -2255,467 +1904,363 @@ NPC_BSST_Attack ------------------------- */ -void NPC_BSST_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSST_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { - if( NPC->client->playerTeam == TEAM_PLAYER ) - { + if (NPC->client->playerTeam == TEAM_PLAYER) { NPC_BSPatrol(); - } - else - { - NPC_BSST_Patrol();//FIXME: or patrol? + } else { + NPC_BSST_Patrol(); // FIXME: or patrol? } return; } - //FIXME: put some sort of delay into the guys depending on how they saw you...? + // FIXME: put some sort of delay into the guys depending on how they saw you...? - //Get our group info - if ( TIMER_Done( NPC, "interrogating" ) ) - { - AI_GetGroup( NPC );//, 45, 512, NPC->enemy ); - } - else - { - //FIXME: when done interrogating, I should send out a team alert! + // Get our group info + if (TIMER_Done(NPC, "interrogating")) { + AI_GetGroup(NPC); //, 45, 512, NPC->enemy ); + } else { + // FIXME: when done interrogating, I should send out a team alert! } - if ( NPCInfo->group ) - {//I belong to a squad of guys - we should *always* have a group - if ( !NPCInfo->group->processed ) - {//I'm the first ent in my group, I'll make the command decisions -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS + if (NPCInfo->group) { // I belong to a squad of guys - we should *always* have a group + if (!NPCInfo->group->processed) { // I'm the first ent in my group, I'll make the command decisions +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS ST_Commander(); -#if AI_TIMERS - int commTime = GetTime ( startTime ); - if ( commTime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: Commander time: %d\n", commTime ); - } - else if ( commTime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: Commander time: %d\n", commTime ); - } - else if ( commTime > 2 ) - { - gi.Printf( S_COLOR_GREEN"Commander time: %d\n", commTime ); - } -#endif// AI_TIMERS - } - } - else if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//not already fleeing, and going to run - ST_Speech( NPC, SPEECH_COVER, 0 ); - NPC_UpdateAngles( qtrue, qtrue ); +#if AI_TIMERS + int commTime = GetTime(startTime); + if (commTime > 20) { + gi.Printf(S_COLOR_RED "ERROR: Commander time: %d\n", commTime); + } else if (commTime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: Commander time: %d\n", commTime); + } else if (commTime > 2) { + gi.Printf(S_COLOR_GREEN "Commander time: %d\n", commTime); + } +#endif // AI_TIMERS + } + } else if (TIMER_Done(NPC, "flee") && + NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // not already fleeing, and going to run + ST_Speech(NPC, SPEECH_COVER, 0); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSST_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSST_Patrol(); // FIXME: or patrol? return; } - if (NPCInfo->goalEntity && NPCInfo->goalEntity!=NPC->enemy) - { - NPCInfo->goalEntity = UpdateGoal(); + if (NPCInfo->goalEntity && NPCInfo->goalEntity != NPC->enemy) { + NPCInfo->goalEntity = UpdateGoal(); } - enemyLOS = enemyCS = enemyInFOV = qfalse; doMove = qtrue; faceEnemy = qfalse; shoot = qfalse; hitAlly = qfalse; - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - - vec3_t enemyDir, shootDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); - VectorNormalize( enemyDir ); - AngleVectors( NPC->client->ps.viewangles, shootDir, NULL, NULL ); - float dot = DotProduct( enemyDir, shootDir ); - if ( dot > 0.5f ||( enemyDist * (1.0f-dot)) < 10000 ) - {//enemy is in front of me or they're very close and not behind me + VectorClear(impactPos); + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + + vec3_t enemyDir, shootDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir); + VectorNormalize(enemyDir); + AngleVectors(NPC->client->ps.viewangles, shootDir, NULL, NULL); + float dot = DotProduct(enemyDir, shootDir); + if (dot > 0.5f || (enemyDist * (1.0f - dot)) < 10000) { // enemy is in front of me or they're very close and not behind me enemyInFOV = qtrue; } - if ( enemyDist < MIN_ROCKET_DIST_SQUARED )//128 - {//enemy within 128 - if ( (NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && - (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + if (enemyDist < MIN_ROCKET_DIST_SQUARED) // 128 + { // enemy within 128 + if ((NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && + (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... + // FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( NPC->client->ps.weapon ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(NPC->client->ps.weapon); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { - AI_GroupUpdateEnemyLastSeen( NPCInfo->group, NPC->enemy->currentOrigin ); + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { + AI_GroupUpdateEnemyLastSeen(NPCInfo->group, NPC->enemy->currentOrigin); NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - NPC_AimAdjust( -1 );//adjust aim worse longer we have no weapon - } - else - {//can we shoot our target? - if ((enemyDist < MIN_ROCKET_DIST_SQUARED) && - ((level.time - NPC->lastMoveTime)<5000) && - ( - (NPC->client->ps.weapon == WP_ROCKET_LAUNCHER - || (NPC->client->ps.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags&SCF_ALT_FIRE)) - || (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags&SCF_ALT_FIRE))))) - { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else if ( enemyInFOV ) - {//if enemy is FOV, go ahead and check for shooting - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + if (NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + NPC_AimAdjust(-1); // adjust aim worse longer we have no weapon + } else { // can we shoot our target? + if ((enemyDist < MIN_ROCKET_DIST_SQUARED) && ((level.time - NPC->lastMoveTime) < 5000) && + ((NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPC->client->ps.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags & SCF_ALT_FIRE)) || + (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags & SCF_ALT_FIRE))))) { + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else if (enemyInFOV) { // if enemy is FOV, go ahead and check for shooting + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPC->s.weapon == WP_EMPLACED_GUN) ) ) - {//can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway - AI_GroupUpdateClearShotTime( NPCInfo->group ); + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && + ((hitEnt->svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || + NPC->s.weapon == + WP_EMPLACED_GUN))) { // can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + AI_GroupUpdateClearShotTime(NPCInfo->group); enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - ST_ResolveBlockedShot( hit ); - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + NPC_AimAdjust(1); // adjust aim better longer we can see enemy + ST_ResolveBlockedShot(hit); + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } - } - else - { - enemyCS = qfalse;//not true, but should stop us from firing + } else { + enemyCS = qfalse; // not true, but should stop us from firing } } - } - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { + } else if (gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { NPCInfo->enemyLastSeenTime = level.time; faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } - if ( NPC->client->ps.weapon == WP_NONE ) - { + if (NPC->client->ps.weapon == WP_NONE) { faceEnemy = qfalse; shoot = qfalse; - } - else - { - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + } else { + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } } - //Check for movement to take care of + // Check for movement to take care of ST_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations ST_CheckFireState(); - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not supposed to chase my enemies - if ( NPCInfo->goalEntity == NPC->enemy ) - {//goal is my entity, so don't doMove + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not supposed to chase my enemies + if (NPCInfo->goalEntity == NPC->enemy) { // goal is my entity, so don't doMove doMove = qfalse; } - } - else if (NPC->NPC->scriptFlags&SCF_NO_GROUPS) - { - // NPCInfo->goalEntity = UpdateGoal(); + } else if (NPC->NPC->scriptFlags & SCF_NO_GROUPS) { + // NPCInfo->goalEntity = UpdateGoal(); - NPCInfo->goalEntity = (enemyLOS)?(0):(NPC->enemy); + NPCInfo->goalEntity = (enemyLOS) ? (0) : (NPC->enemy); } - if ( NPC->client->fireDelay && NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { + if (NPC->client->fireDelay && NPC->s.weapon == WP_ROCKET_LAUNCHER) { doMove = qfalse; } - if ( !ucmd.rightmove ) - {//only if not already strafing for some strange reason...? - //NOTE: these are never set here, but can be set in AI_Jedi.cpp for those NPCs who are sort of Stormtrooper/Jedi hybrids - //NOTE: this stomps navigation movement entirely! - //FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too - if ( !TIMER_Done( NPC, "strafeLeft" ) ) - { + if (!ucmd.rightmove) { // only if not already strafing for some strange reason...? + // NOTE: these are never set here, but can be set in AI_Jedi.cpp for those NPCs who are sort of Stormtrooper/Jedi hybrids + // NOTE: this stomps navigation movement entirely! + // FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too + if (!TIMER_Done(NPC, "strafeLeft")) { /* if ( NPCInfo->desiredYaw > NPC->client->ps.viewangles[YAW] + 60 ) {//we want to turn left, don't apply the strafing } else */ - {//go ahead and strafe left + { // go ahead and strafe left ucmd.rightmove = -127; - //re-check the duck as we might want to be rolling - VectorClear( NPC->client->ps.moveDir ); + // re-check the duck as we might want to be rolling + VectorClear(NPC->client->ps.moveDir); doMove = qfalse; } - } - else if ( !TIMER_Done( NPC, "strafeRight" ) ) - { + } else if (!TIMER_Done(NPC, "strafeRight")) { /*if ( NPCInfo->desiredYaw < NPC->client->ps.viewangles[YAW] - 60 ) {//we want to turn right, don't apply the strafing } else */ - {//go ahead and strafe left + { // go ahead and strafe left ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); doMove = qfalse; } } } - if ( NPC->client->ps.legsAnim == BOTH_GUARD_LOOKAROUND1 ) - {//don't doMove when doing silly look around thing + if (NPC->client->ps.legsAnim == BOTH_GUARD_LOOKAROUND1) { // don't doMove when doing silly look around thing doMove = qfalse; } - if ( doMove ) - {//doMove toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (doMove) { // doMove toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { doMove = ST_Move(); - if ( (NPC->client->NPC_class != CLASS_ROCKETTROOPER||NPC->s.weapon!=WP_ROCKET_LAUNCHER||enemyDistgoalEntity - && DistanceSquared( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin ) > MIN_TURN_AROUND_DIST_SQ ) - {//don't stop running backwards if your goal is less than 100 away - if ( TIMER_Done( NPC, "runBackwardsDebounce" ) ) - {//not already waiting for next run backwards - if ( !TIMER_Exists( NPC, "runningBackwards" ) ) - {//start running backwards - TIMER_Set( NPC, "runningBackwards", Q_irand( 500, 1000 ) );//Q_irand( 2000, 3500 ) ); - } - else if ( TIMER_Done2( NPC, "runningBackwards", qtrue ) ) - {//done running backwards - TIMER_Set( NPC, "runBackwardsDebounce", Q_irand( 3000, 5000 ) ); + if ((NPC->client->NPC_class != CLASS_ROCKETTROOPER || NPC->s.weapon != WP_ROCKET_LAUNCHER || + enemyDist < MIN_ROCKET_DIST_SQUARED) // rockettroopers who use rocket launchers turn around and run if you get too close (closer than 128) + && ucmd.forwardmove <= -32) { // moving backwards at least 45 degrees + if (NPCInfo->goalEntity && DistanceSquared(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin) > + MIN_TURN_AROUND_DIST_SQ) { // don't stop running backwards if your goal is less than 100 away + if (TIMER_Done(NPC, "runBackwardsDebounce")) { // not already waiting for next run backwards + if (!TIMER_Exists(NPC, "runningBackwards")) { // start running backwards + TIMER_Set(NPC, "runningBackwards", Q_irand(500, 1000)); // Q_irand( 2000, 3500 ) ); + } else if (TIMER_Done2(NPC, "runningBackwards", qtrue)) { // done running backwards + TIMER_Set(NPC, "runBackwardsDebounce", Q_irand(3000, 5000)); } } } + } else { // not running backwards + // TIMER_Remove( NPC, "runningBackwards" ); } - else - {//not running backwards - //TIMER_Remove( NPC, "runningBackwards" ); - } - } - else - { + } else { doMove = qfalse; } } - if ( !doMove ) - { - if (NPC->client->NPC_class != CLASS_ASSASSIN_DROID) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!doMove) { + if (NPC->client->NPC_class != CLASS_ASSASSIN_DROID) { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); } - if ( NPC->client->NPC_class == CLASS_REBORN//cultist using a gun - && NPCInfo->rank >= RANK_LT_COMM //commando or better - && NPC->enemy->s.weapon == WP_SABER )//fighting a saber-user - {//commando saboteur vs. jedi/reborn - //see if we need to avoid their saber + if (NPC->client->NPC_class == CLASS_REBORN // cultist using a gun + && NPCInfo->rank >= RANK_LT_COMM // commando or better + && NPC->enemy->s.weapon == WP_SABER) // fighting a saber-user + { // commando saboteur vs. jedi/reborn + // see if we need to avoid their saber NPC_EvasionSaber(); } - if ( //!TIMER_Done( NPC, "flee" ) || - (doMove&&!TIMER_Done( NPC, "runBackwardsDebounce" )) ) - {//running away + if ( //! TIMER_Done( NPC, "flee" ) || + (doMove && !TIMER_Done(NPC, "runBackwardsDebounce"))) { // running away faceEnemy = qfalse; } - //FIXME: check scf_face_move_dir here? + // FIXME: check scf_face_move_dir here? - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( !doMove ) - {//if we haven't moved, we should look in the direction we last looked? - VectorCopy( NPC->client->ps.viewangles, NPCInfo->lastPathAngles ); + if (!faceEnemy) { // we want to face in the dir we're running + if (!doMove) { // if we haven't moved, we should look in the direction we last looked? + VectorCopy(NPC->client->ps.viewangles, NPCInfo->lastPathAngles); } NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; - NPC_UpdateAngles( qtrue, qtrue ); - if ( doMove ) - {//don't run away and shoot + NPC_UpdateAngles(qtrue, qtrue); + if (doMove) { // don't run away and shoot shoot = qfalse; } } - if ( NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPC->enemy && NPC->enemy->enemy ) - { - if ( NPC->enemy->s.weapon == WP_SABER && NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPC->enemy && NPC->enemy->enemy) { + if (NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue + // blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - //FIXME: don't shoot right away! - if ( NPC->client->fireDelay ) - { - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Decloak( NPC ); + // FIXME: don't shoot right away! + if (NPC->client->fireDelay) { + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Decloak(NPC); } - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER - || (NPC->s.weapon==WP_CONCUSSION&&!(NPCInfo->scriptFlags&SCF_ALT_FIRE)) ) - { - if ( !enemyLOS || !enemyCS ) - {//cancel it + if (NPC->s.weapon == WP_ROCKET_LAUNCHER || (NPC->s.weapon == WP_CONCUSSION && !(NPCInfo->scriptFlags & SCF_ALT_FIRE))) { + if (!enemyLOS || !enemyCS) { // cancel it NPC->client->fireDelay = 0; - } - else - {//delay our next attempt - TIMER_Set( NPC, "attackDelay", Q_irand( 3000, 5000 ) ); + } else { // delay our next attempt + TIMER_Set(NPC, "attackDelay", Q_irand(3000, 5000)); } } - } - else if ( shoot ) - {//try to shoot if it's time - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Decloak( NPC ); + } else if (shoot) { // try to shoot if it's time + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Decloak(NPC); } - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } - //NASTY - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { - if ( (ucmd.buttons&BUTTON_ATTACK) - && !doMove - && g_spskill->integer > 1 - && !Q_irand( 0, 3 ) ) - {//every now and then, shoot a homing rocket + // NASTY + if (NPC->s.weapon == WP_ROCKET_LAUNCHER) { + if ((ucmd.buttons & BUTTON_ATTACK) && !doMove && g_spskill->integer > 1 && !Q_irand(0, 3)) { // every now and then, shoot a homing rocket ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1000, 2500 ); + NPC->client->fireDelay = Q_irand(1000, 2500); } - } - else if ( NPC->s.weapon == WP_NOGHRI_STICK - && enemyDist < (48*48) )//? + } else if (NPC->s.weapon == WP_NOGHRI_STICK && enemyDist < (48 * 48)) //? { ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1500, 2000 ); + NPC->client->fireDelay = Q_irand(1500, 2000); } } - } - else - { - if ( NPC->attackDebounceTime < level.time ) - { - if ( NPC->client->NPC_class == CLASS_SABOTEUR ) - { - Saboteur_Cloak( NPC ); + } else { + if (NPC->attackDebounceTime < level.time) { + if (NPC->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Cloak(NPC); } } } } -extern qboolean G_TuskenAttackAnimDamage( gentity_t *self ); -void NPC_BSST_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +extern qboolean G_TuskenAttackAnimDamage(gentity_t *self); +void NPC_BSST_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( NPC->s.weapon == WP_NOGHRI_STICK ) - { - if ( G_TuskenAttackAnimDamage( NPC ) ) - { + if (NPC->s.weapon == WP_NOGHRI_STICK) { + if (G_TuskenAttackAnimDamage(NPC)) { Noghri_StickTrace(); } } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSST_Patrol(); - } - else //if ( NPC->enemy ) - {//have an enemy - if ( NPC->enemy->client //enemy is a client - && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA )//enemy is a lowly jawa or ugnaught - && NPC->enemy->enemy != NPC//enemy's enemy is not me - && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || (NPC->enemy->enemy->client->NPC_class!=CLASS_RANCOR&&NPC->enemy->enemy->client->NPC_class!=CLASS_WAMPA)) )//enemy's enemy is not a client or is not a wampa or rancor (which is scarier than me) - {//they should be scared of ME and no-one else - G_SetEnemy( NPC->enemy, NPC ); + } else // if ( NPC->enemy ) + { // have an enemy + if (NPC->enemy->client // enemy is a client + && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA) // enemy is a lowly jawa or ugnaught + && NPC->enemy->enemy != NPC // enemy's enemy is not me + && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || + (NPC->enemy->enemy->client->NPC_class != CLASS_RANCOR && + NPC->enemy->enemy->client->NPC_class != CLASS_WAMPA))) // enemy's enemy is not a client or is not a wampa or rancor (which is scarier than me) + { // they should be scared of ME and no-one else + G_SetEnemy(NPC->enemy, NPC); } NPC_CheckGetNewWeapon(); NPC_BSST_Attack(); diff --git a/code/game/AI_Tusken.cpp b/code/game/AI_Tusken.cpp index bf6df7334a..6bc8b2b5e5 100644 --- a/code/game/AI_Tusken.cpp +++ b/code/game/AI_Tusken.cpp @@ -27,36 +27,34 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern int PM_AnimLength( int index, animNumber_t anim ); - - -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 - -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) - -qboolean NPC_CheckPlayerTeamStealth( void ); - -static float enemyDist; - -//Local state enums -enum -{ +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); +extern int PM_AnimLength(int index, animNumber_t anim); + +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 + +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) + +qboolean NPC_CheckPlayerTeamStealth(void); + +static float enemyDist; + +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, @@ -67,69 +65,61 @@ enum NPC_Tusken_Precache ------------------------- */ -void NPC_Tusken_Precache( void ) -{ +void NPC_Tusken_Precache(void) { int i; - for ( i = 1; i < 5; i ++ ) - { - G_SoundIndex( va( "sound/weapons/tusken_staff/stickhit%d.wav", i ) ); + for (i = 1; i < 5; i++) { + G_SoundIndex(va("sound/weapons/tusken_staff/stickhit%d.wav", i)); } } -void Tusken_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "taunting", 0 ); +void Tusken_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "taunting", 0); } -void NPC_Tusken_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Tusken_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Tusken_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod ) -{ +void NPC_Tusken_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -139,9 +129,8 @@ ST_HoldPosition ------------------------- */ -static void Tusken_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); +static void Tusken_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); NPCInfo->goalEntity = NULL; } @@ -151,16 +140,14 @@ ST_Move ------------------------- */ -static qboolean Tusken_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always move straight toward our goal +static qboolean Tusken_Move(void) { + NPCInfo->combatMove = qtrue; // always move straight toward our goal - qboolean moved = NPC_MoveToGoal( qtrue ); + qboolean moved = NPC_MoveToGoal(qtrue); - //If our move failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - //just hang here + // If our move failed, then reset + if (moved == qfalse) { // couldn't get to enemy + // just hang here Tusken_HoldPosition(); } @@ -173,76 +160,61 @@ NPC_BSTusken_Patrol ------------------------- */ -void NPC_BSTusken_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSTusken_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 )//&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0) //&& level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) { - //NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + // NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -251,22 +223,19 @@ void NPC_BSTusken_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - -void NPC_Tusken_Taunt( void ) -{ - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TUSKENTAUNT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "taunting", NPC->client->ps.torsoAnimTimer ); - TIMER_Set( NPC, "duck", -1 ); +void NPC_Tusken_Taunt(void) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TUSKENTAUNT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "taunting", NPC->client->ps.torsoAnimTimer); + TIMER_Set(NPC, "duck", -1); } /* @@ -275,191 +244,154 @@ NPC_BSTusken_Attack ------------------------- */ -void NPC_BSTusken_Attack( void ) -{ -// IN PAIN -//--------- - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSTusken_Attack(void) { + // IN PAIN + //--------- + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } -// IN FLEE -//--------- - if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // IN FLEE + //--------- + if (TIMER_Done(NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { + NPC_UpdateAngles(qtrue, qtrue); return; } - - -// UPDATE OUR ENEMY -//------------------ - if (NPC_CheckEnemyExt()==qfalse || !NPC->enemy) - { + // UPDATE OUR ENEMY + //------------------ + if (NPC_CheckEnemyExt() == qfalse || !NPC->enemy) { NPC_BSTusken_Patrol(); return; } - enemyDist = Distance(NPC->enemy->currentOrigin, NPC->currentOrigin); + enemyDist = Distance(NPC->enemy->currentOrigin, NPC->currentOrigin); // Is The Current Enemy A Jawa? //------------------------------ - if (NPC->enemy->client && NPC->enemy->client->NPC_class==CLASS_JAWA) - { + if (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_JAWA) { // Make Sure His Enemy Is Me //--------------------------- - if (NPC->enemy->enemy!=NPC) - { + if (NPC->enemy->enemy != NPC) { G_SetEnemy(NPC->enemy, NPC); } // Should We Forget About Our Current Enemy And Go After The Player? //------------------------------------------------------------------- - if ((player) && // If There Is A Player Pointer - (player!=NPC->enemy) && // The Player Is Not Currently My Enemy - (Distance(player->currentOrigin, NPC->currentOrigin)<130.0f) && // The Player Is Close Enough - (NAV::InSameRegion(NPC, player)) // And In The Same Region - ) - { + if ((player) && // If There Is A Player Pointer + (player != NPC->enemy) && // The Player Is Not Currently My Enemy + (Distance(player->currentOrigin, NPC->currentOrigin) < 130.0f) && // The Player Is Close Enough + (NAV::InSameRegion(NPC, player)) // And In The Same Region + ) { G_SetEnemy(NPC, player); } } // Update Our Last Seen Time //--------------------------- - if (NPC_ClearLOS(NPC->enemy)) - { + if (NPC_ClearLOS(NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; } - - // Check To See If We Are In Attack Range //---------------------------------------- - float boundsMin = (NPC->maxs[0]+NPC->enemy->maxs[0]); - float lungeRange = (boundsMin + 65.0f); - float strikeRange = (boundsMin + 40.0f); - bool meleeRange = (enemyDistclient->ps.weapon!=WP_TUSKEN_RIFLE); - bool canSeeEnemy = ((level.time - NPCInfo->enemyLastSeenTime)<3000); + float boundsMin = (NPC->maxs[0] + NPC->enemy->maxs[0]); + float lungeRange = (boundsMin + 65.0f); + float strikeRange = (boundsMin + 40.0f); + bool meleeRange = (enemyDist < lungeRange); + bool meleeWeapon = (NPC->client->ps.weapon != WP_TUSKEN_RIFLE); + bool canSeeEnemy = ((level.time - NPCInfo->enemyLastSeenTime) < 3000); // Check To Start Taunting //------------------------- - if (canSeeEnemy && !meleeRange && TIMER_Done(NPC, "tuskenTauntCheck")) - { + if (canSeeEnemy && !meleeRange && TIMER_Done(NPC, "tuskenTauntCheck")) { TIMER_Set(NPC, "tuskenTauntCheck", Q_irand(2000, 6000)); - if (!Q_irand(0,3)) - { + if (!Q_irand(0, 3)) { NPC_Tusken_Taunt(); } } - - if (TIMER_Done(NPC, "taunting")) - { + if (TIMER_Done(NPC, "taunting")) { // Should I Attack? //------------------ - if (meleeRange || (!meleeWeapon && canSeeEnemy)) - { - if (!(NPCInfo->scriptFlags&SCF_FIRE_WEAPON) && // If This Flag Is On, It Calls Attack From Elsewhere - !(NPCInfo->scriptFlags&SCF_DONT_FIRE) && // If This Flag Is On, Don't Fire At All - (TIMER_Done(NPC, "attackDelay")) - ) - { + if (meleeRange || (!meleeWeapon && canSeeEnemy)) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) && // If This Flag Is On, It Calls Attack From Elsewhere + !(NPCInfo->scriptFlags & SCF_DONT_FIRE) && // If This Flag Is On, Don't Fire At All + (TIMER_Done(NPC, "attackDelay"))) { ucmd.buttons &= ~BUTTON_ALT_ATTACK; // If Not In Strike Range, Do Lunge, Or If We Don't Have The Staff, Just Shoot Normally //-------------------------------------------------------------------------------------- - if (enemyDist > strikeRange) - { + if (enemyDist > strikeRange) { ucmd.buttons |= BUTTON_ALT_ATTACK; } - WeaponThink( qtrue ); - TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime-level.time); + WeaponThink(qtrue); + TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime - level.time); } - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } } // Or Should I Move? //------------------- - else if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) - { + else if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = lungeRange; Tusken_Move(); } } - -// UPDATE ANGLES -//--------------- - if (canSeeEnemy) - { + // UPDATE ANGLES + //--------------- + if (canSeeEnemy) { NPC_FaceEnemy(qtrue); } NPC_UpdateAngles(qtrue, qtrue); } -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -void Tusken_StaffTrace( void ) -{ - if ( !NPC->ghoul2.size() - || NPC->weaponModel[0] <= 0 ) - { +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +void Tusken_StaffTrace(void) { + if (!NPC->ghoul2.size() || NPC->weaponModel[0] <= 0) { return; } - int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); - if ( boltIndex != -1 ) - { - int curTime = (cg.time?cg.time:level.time); + int boltIndex = gi.G2API_AddBolt(&NPC->ghoul2[NPC->weaponModel[0]], "*weapon"); + if (boltIndex != -1) { + int curTime = (cg.time ? cg.time : level.time); qboolean hit = qfalse; - int lastHit = ENTITYNUM_NONE; - for ( int time = curTime-25; time <= curTime+25&&!hit; time += 25 ) - { - mdxaBone_t boltMatrix; - vec3_t tip, dir, base, angles={0,NPC->currentAngles[YAW],0}; - vec3_t mins={-2,-2,-2},maxs={2,2,2}; - trace_t trace; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->weaponModel[0], - boltIndex, - &boltMatrix, angles, NPC->currentOrigin, time, - NULL, NPC->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, base ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); - VectorMA( base, -20, dir, base ); - VectorMA( base, 78, dir, tip ); - #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { + int lastHit = ENTITYNUM_NONE; + for (int time = curTime - 25; time <= curTime + 25 && !hit; time += 25) { + mdxaBone_t boltMatrix; + vec3_t tip, dir, base, angles = {0, NPC->currentAngles[YAW], 0}; + vec3_t mins = {-2, -2, -2}, maxs = {2, 2, 2}; + trace_t trace; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->weaponModel[0], boltIndex, &boltMatrix, angles, NPC->currentOrigin, time, NULL, NPC->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, base); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); + VectorMA(base, -20, dir, base); + VectorMA(base, 78, dir, tip); +#ifndef FINAL_BUILD + if (d_saberCombat->integer > 1) { G_DebugLine(base, tip, 1000, 0x000000ff, qtrue); } - #endif - gi.trace( &trace, base, mins, maxs, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( trace.fraction < 1.0f && trace.entityNum != lastHit ) - {//hit something +#endif + gi.trace(&trace, base, mins, maxs, tip, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 10); + if (trace.fraction < 1.0f && trace.entityNum != lastHit) { // hit something gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt->takedamage - && (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class) ) - {//smack - int dmg = Q_irand( 5, 10 ) * (g_spskill->integer+1); - - //FIXME: debounce? - G_Sound( traceEnt, G_SoundIndex( va( "sound/weapons/tusken_staff/stickhit%d.wav", Q_irand( 1, 4 ) ) ) ); - G_Damage( traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - if ( traceEnt->health > 0 - && ( (traceEnt->client&&traceEnt->client->NPC_class==CLASS_JAWA&&!Q_irand(0,1)) - || dmg > 19 ) )//FIXME: base on skill! - {//do pain on enemy - G_Knockdown( traceEnt, NPC, dir, 300, qtrue ); + if (traceEnt->takedamage && (!traceEnt->client || traceEnt == NPC->enemy || traceEnt->client->NPC_class != NPC->client->NPC_class)) { // smack + int dmg = Q_irand(5, 10) * (g_spskill->integer + 1); + + // FIXME: debounce? + G_Sound(traceEnt, G_SoundIndex(va("sound/weapons/tusken_staff/stickhit%d.wav", Q_irand(1, 4)))); + G_Damage(traceEnt, NPC, NPC, vec3_origin, trace.endpos, dmg, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + if (traceEnt->health > 0 && + ((traceEnt->client && traceEnt->client->NPC_class == CLASS_JAWA && !Q_irand(0, 1)) || dmg > 19)) // FIXME: base on skill! + { // do pain on enemy + G_Knockdown(traceEnt, NPC, dir, 300, qtrue); } lastHit = trace.entityNum; hit = qtrue; @@ -469,59 +401,43 @@ void Tusken_StaffTrace( void ) } } -qboolean G_TuskenAttackAnimDamage( gentity_t *self ) -{ - if (self->client->ps.torsoAnim==BOTH_TUSKENATTACK1 || - self->client->ps.torsoAnim==BOTH_TUSKENATTACK2 || - self->client->ps.torsoAnim==BOTH_TUSKENATTACK3 || - self->client->ps.torsoAnim==BOTH_TUSKENLUNGE1) - { - float current = 0.0f; - int end = 0; - int start = 0; - if (!!gi.G2API_GetBoneAnimIndex(& - self->ghoul2[self->playerModel], - self->lowerLumbarBone, - level.time, - ¤t, - &start, - &end, - NULL, - NULL, - NULL)) - { - float percentComplete = (current-start)/(end-start); - //gi.Printf("%f\n", percentComplete); - switch (self->client->ps.torsoAnim) - { - case BOTH_TUSKENATTACK1: return (qboolean)(percentComplete>0.3 && percentComplete<0.7); - case BOTH_TUSKENATTACK2: return (qboolean)(percentComplete>0.3 && percentComplete<0.7); - case BOTH_TUSKENATTACK3: return (qboolean)(percentComplete>0.1 && percentComplete<0.5); - case BOTH_TUSKENLUNGE1: return (qboolean)(percentComplete>0.3 && percentComplete<0.5); +qboolean G_TuskenAttackAnimDamage(gentity_t *self) { + if (self->client->ps.torsoAnim == BOTH_TUSKENATTACK1 || self->client->ps.torsoAnim == BOTH_TUSKENATTACK2 || + self->client->ps.torsoAnim == BOTH_TUSKENATTACK3 || self->client->ps.torsoAnim == BOTH_TUSKENLUNGE1) { + float current = 0.0f; + int end = 0; + int start = 0; + if (!!gi.G2API_GetBoneAnimIndex(&self->ghoul2[self->playerModel], self->lowerLumbarBone, level.time, ¤t, &start, &end, NULL, NULL, NULL)) { + float percentComplete = (current - start) / (end - start); + // gi.Printf("%f\n", percentComplete); + switch (self->client->ps.torsoAnim) { + case BOTH_TUSKENATTACK1: + return (qboolean)(percentComplete > 0.3 && percentComplete < 0.7); + case BOTH_TUSKENATTACK2: + return (qboolean)(percentComplete > 0.3 && percentComplete < 0.7); + case BOTH_TUSKENATTACK3: + return (qboolean)(percentComplete > 0.1 && percentComplete < 0.5); + case BOTH_TUSKENLUNGE1: + return (qboolean)(percentComplete > 0.3 && percentComplete < 0.5); } } } return qfalse; } -void NPC_BSTusken_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSTusken_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( G_TuskenAttackAnimDamage( NPC ) ) - { + if (G_TuskenAttackAnimDamage(NPC)) { Tusken_StaffTrace(); } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSTusken_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSTusken_Attack(); } } diff --git a/code/game/AI_Utils.cpp b/code/game/AI_Utils.cpp index bbb1b8313d..5fb23b999f 100644 --- a/code/game/AI_Utils.cpp +++ b/code/game/AI_Utils.cpp @@ -29,11 +29,11 @@ along with this program; if not, see . #include "g_nav.h" #include "g_navigator.h" -#define MAX_RADIUS_ENTS 128 -#define DEFAULT_RADIUS 45 +#define MAX_RADIUS_ENTS 128 +#define DEFAULT_RADIUS 45 -extern cvar_t *d_noGroupAI; -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ); +extern cvar_t *d_noGroupAI; +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member); /* ------------------------- @@ -41,39 +41,36 @@ AI_GetGroupSize ------------------------- */ -int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid ) -{ - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; - vec3_t mins, maxs; - int numEnts, realCount = 0; +int AI_GetGroupSize(vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid) { + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; + vec3_t mins, maxs; + int numEnts, realCount = 0; - //Setup the bbox to search in - for ( int i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (int i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( int j = 0; j < numEnts; j++ ) - { - //Validate clients - if ( radiusEnts[ j ]->client == NULL ) + // Cull this list + for (int j = 0; j < numEnts; j++) { + // Validate clients + if (radiusEnts[j]->client == NULL) continue; - //Skip the requested avoid ent if present - if ( ( avoid != NULL ) && ( radiusEnts[ j ] == avoid ) ) + // Skip the requested avoid ent if present + if ((avoid != NULL) && (radiusEnts[j] == avoid)) continue; - //Must be on the same team - if ( radiusEnts[ j ]->client->playerTeam != playerTeam ) + // Must be on the same team + if (radiusEnts[j]->client->playerTeam != playerTeam) continue; - //Must be alive - if ( radiusEnts[ j ]->health <= 0 ) + // Must be alive + if (radiusEnts[j]->health <= 0) continue; realCount++; @@ -82,31 +79,26 @@ int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *av return realCount; } -//Overload +// Overload -int AI_GetGroupSize( gentity_t *ent, int radius ) -{ - if ( ( ent == NULL ) || ( ent->client == NULL ) ) +int AI_GetGroupSize(gentity_t *ent, int radius) { + if ((ent == NULL) || (ent->client == NULL)) return -1; - return AI_GetGroupSize( ent->currentOrigin, radius, ent->client->playerTeam, ent ); + return AI_GetGroupSize(ent->currentOrigin, radius, ent->client->playerTeam, ent); } -void AI_SetClosestBuddy( AIGroupInfo_t *group ) -{ - int i, j; - int dist, bestDist; +void AI_SetClosestBuddy(AIGroupInfo_t *group) { + int i, j; + int dist, bestDist; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { group->member[i].closestBuddy = ENTITYNUM_NONE; bestDist = Q3_INFINITE; - for ( j = 0; j < group->numGroup; j++ ) - { - dist = DistanceSquared( g_entities[group->member[i].number].currentOrigin, g_entities[group->member[j].number].currentOrigin ); - if ( dist < bestDist ) - { + for (j = 0; j < group->numGroup; j++) { + dist = DistanceSquared(g_entities[group->member[i].number].currentOrigin, g_entities[group->member[j].number].currentOrigin); + if (dist < bestDist) { bestDist = dist; group->member[i].closestBuddy = group->member[j].number; } @@ -114,95 +106,71 @@ void AI_SetClosestBuddy( AIGroupInfo_t *group ) } } -void AI_SortGroupByPathCostToEnemy( AIGroupInfo_t *group ) -{ +void AI_SortGroupByPathCostToEnemy(AIGroupInfo_t *group) { AIGroupMember_t bestMembers[MAX_GROUP_MEMBERS]; - int i, j, k; - qboolean sort = qfalse; + int i, j, k; + qboolean sort = qfalse; - if ( group->enemy != NULL ) - {//FIXME: just use enemy->waypoint? + if (group->enemy != NULL) { // FIXME: just use enemy->waypoint? group->enemyWP = NAV::GetNearestNode(group->enemy); - } - else - { + } else { group->enemyWP = WAYPOINT_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->enemyWP == WAYPOINT_NONE ) - {//FIXME: just use member->waypoint? + for (i = 0; i < group->numGroup; i++) { + if (group->enemyWP == WAYPOINT_NONE) { // FIXME: just use member->waypoint? group->member[i].waypoint = WAYPOINT_NONE; group->member[i].pathCostToEnemy = Q3_INFINITE; - } - else - {//FIXME: just use member->waypoint? + } else { // FIXME: just use member->waypoint? group->member[i].waypoint = NAV::GetNearestNode(group->enemy); - if ( group->member[i].waypoint != WAYPOINT_NONE ) - { - group->member[i].pathCostToEnemy = NAV::EstimateCostToGoal( group->member[i].waypoint, group->enemyWP ); - //at least one of us has a path, so do sorting + if (group->member[i].waypoint != WAYPOINT_NONE) { + group->member[i].pathCostToEnemy = NAV::EstimateCostToGoal(group->member[i].waypoint, group->enemyWP); + // at least one of us has a path, so do sorting sort = qtrue; - } - else - { + } else { group->member[i].pathCostToEnemy = Q3_INFINITE; } } } - //Now sort - if ( sort ) - { - //initialize bestMembers data - for ( j = 0; j < group->numGroup; j++ ) - { + // Now sort + if (sort) { + // initialize bestMembers data + for (j = 0; j < group->numGroup; j++) { bestMembers[j].number = ENTITYNUM_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - for ( j = 0; j < group->numGroup; j++ ) - { - if ( bestMembers[j].number != ENTITYNUM_NONE ) - {//slot occupied - if ( group->member[i].pathCostToEnemy < bestMembers[j].pathCostToEnemy ) - {//this guy has a shorter path than the one currenly in this spot, bump him and put myself in here - for ( k = group->numGroup; k > j; k++ ) - { - memcpy( &bestMembers[k], &bestMembers[k-1], sizeof( bestMembers[k] ) ); + for (i = 0; i < group->numGroup; i++) { + for (j = 0; j < group->numGroup; j++) { + if (bestMembers[j].number != ENTITYNUM_NONE) { // slot occupied + if (group->member[i].pathCostToEnemy < + bestMembers[j].pathCostToEnemy) { // this guy has a shorter path than the one currenly in this spot, bump him and put myself in here + for (k = group->numGroup; k > j; k++) { + memcpy(&bestMembers[k], &bestMembers[k - 1], sizeof(bestMembers[k])); } - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } - } - else - {//slot unoccupied, reached end of list, throw self in here - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + } else { // slot unoccupied, reached end of list, throw self in here + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } } } - //Okay, now bestMembers is a sorted list, just copy it into group->members - for ( i = 0; i < group->numGroup; i++ ) - { - memcpy( &group->member[i], &bestMembers[i], sizeof( group->member[i] ) ); + // Okay, now bestMembers is a sorted list, just copy it into group->members + for (i = 0; i < group->numGroup; i++) { + memcpy(&group->member[i], &bestMembers[i], sizeof(group->member[i])); } } } -qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those contain me already - int i, j; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup )//&& level.groups[i].enemy != NULL ) - {//check this one - for ( j = 0; j < level.groups[i].numGroup; j++ ) - { - if ( level.groups[i].member[j].number == self->s.number ) - { +qboolean AI_FindSelfInPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those contain me already + int i, j; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup) //&& level.groups[i].enemy != NULL ) + { // check this one + for (j = 0; j < level.groups[i].numGroup; j++) { + if (level.groups[i].member[j].number == self->s.number) { self->NPC->group = &level.groups[i]; return qtrue; } @@ -212,45 +180,35 @@ qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) return qfalse; } -void AI_InsertGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ +void AI_InsertGroupMember(AIGroupInfo_t *group, gentity_t *member) { int i; - //okay, you know what? Check this damn group and make sure we're not already in here! - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - {//already in here + // okay, you know what? Check this damn group and make sure we're not already in here! + for (i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { // already in here break; } } - if ( i < group->numGroup ) - {//found him in group already - } - else - {//add him in + if (i < group->numGroup) { // found him in group already + } else { // add him in group->member[group->numGroup++].number = member->s.number; group->numState[member->NPC->squadState]++; } - if ( !group->commander || (member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || (member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } member->NPC->group = group; } -qboolean AI_TryJoinPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! - int i; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup - && level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) +qboolean +AI_TryJoinPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! + int i; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup && + level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) //&& level.groups[i].enemy != NULL - && level.groups[i].enemy == self->enemy ) - {//has members, not full and has my enemy - if ( AI_ValidateGroupMember( &level.groups[i], self ) ) - {//I am a valid member for this group - AI_InsertGroupMember( &level.groups[i], self ); + && level.groups[i].enemy == self->enemy) { // has members, not full and has my enemy + if (AI_ValidateGroupMember(&level.groups[i], self)) { // I am a valid member for this group + AI_InsertGroupMember(&level.groups[i], self); return qtrue; } } @@ -258,167 +216,133 @@ qboolean AI_TryJoinPreviousGroup( gentity_t *self ) return qfalse; } -qboolean AI_GetNextEmptyGroup( gentity_t *self ) -{ - if ( AI_FindSelfInPreviousGroup( self ) ) - {//already in one, no need to make a new one +qboolean AI_GetNextEmptyGroup(gentity_t *self) { + if (AI_FindSelfInPreviousGroup(self)) { // already in one, no need to make a new one return qfalse; } - if ( AI_TryJoinPreviousGroup( self ) ) - {//try to just put us in one that already exists + if (AI_TryJoinPreviousGroup(self)) { // try to just put us in one that already exists return qfalse; } - //okay, make a whole new one, then - for ( int i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup ) - {//make a new one + // okay, make a whole new one, then + for (int i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup) { // make a new one self->NPC->group = &level.groups[i]; return qtrue; } } - //if ( i >= MAX_FRAME_GROUPS ) - {//WTF? Out of groups! + // if ( i >= MAX_FRAME_GROUPS ) + { // WTF? Out of groups! self->NPC->group = NULL; return qfalse; } } -qboolean AI_ValidateNoEnemyGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - if ( !group ) - { +qboolean AI_ValidateNoEnemyGroupMember(AIGroupInfo_t *group, gentity_t *member) { + if (!group) { return qfalse; } vec3_t center; - if ( group->commander ) - { - VectorCopy( group->commander->currentOrigin, center ); - } - else - {//hmm, just pick the first member - if ( group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD ) - { + if (group->commander) { + VectorCopy(group->commander->currentOrigin, center); + } else { // hmm, just pick the first member + if (group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD) { return qfalse; } - VectorCopy( g_entities[group->member[0].number].currentOrigin, center ); + VectorCopy(g_entities[group->member[0].number].currentOrigin, center); } - //FIXME: maybe it should be based on the center of the mass of the group, not the commander? - if ( DistanceSquared( center, member->currentOrigin ) > 147456/*384*384*/ ) - { + // FIXME: maybe it should be based on the center of the mass of the group, not the commander? + if (DistanceSquared(center, member->currentOrigin) > 147456 /*384*384*/) { return qfalse; } - if ( !gi.inPVS( member->currentOrigin, center ) ) - {//not within PVS of the group enemy + if (!gi.inPVS(member->currentOrigin, center)) { // not within PVS of the group enemy return qfalse; } return qtrue; } -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - //Validate ents - if ( member == NULL ) +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member) { + // Validate ents + if (member == NULL) return qfalse; - //Validate clients - if ( member->client == NULL ) + // Validate clients + if (member->client == NULL) return qfalse; - //Validate NPCs - if ( member->NPC == NULL ) + // Validate NPCs + if (member->NPC == NULL) return qfalse; - //must be aware - if ( member->NPC->confusionTime > level.time ) + // must be aware + if (member->NPC->confusionTime > level.time) return qfalse; - //must be allowed to join groups - if ( member->NPC->scriptFlags&SCF_NO_GROUPS ) + // must be allowed to join groups + if (member->NPC->scriptFlags & SCF_NO_GROUPS) return qfalse; - //Must not be in another group - if ( member->NPC->group != NULL && member->NPC->group != group ) - {//FIXME: if that group's enemy is mine, why not absorb that group into mine? + // Must not be in another group + if (member->NPC->group != NULL && member->NPC->group != group) { // FIXME: if that group's enemy is mine, why not absorb that group into mine? return qfalse; } - //Must be alive - if ( member->health <= 0 ) + // Must be alive + if (member->health <= 0) return qfalse; - //can't be in an emplaced gun - if( member->s.eFlags & EF_LOCKED_TO_WEAPON ) + // can't be in an emplaced gun + if (member->s.eFlags & EF_LOCKED_TO_WEAPON) return qfalse; - if( member->s.eFlags & EF_HELD_BY_RANCOR ) + if (member->s.eFlags & EF_HELD_BY_RANCOR) return qfalse; - if( member->s.eFlags & EF_HELD_BY_SAND_CREATURE ) + if (member->s.eFlags & EF_HELD_BY_SAND_CREATURE) return qfalse; - if( member->s.eFlags & EF_HELD_BY_WAMPA ) + if (member->s.eFlags & EF_HELD_BY_WAMPA) return qfalse; - //Must be on the same team - if ( member->client->playerTeam != group->team ) + // Must be on the same team + if (member->client->playerTeam != group->team) return qfalse; - if ( member->client->ps.weapon == WP_SABER ||//!= self->s.weapon ) - member->client->ps.weapon == WP_THERMAL || - member->client->ps.weapon == WP_DISRUPTOR || - member->client->ps.weapon == WP_EMPLACED_GUN || - member->client->ps.weapon == WP_BOT_LASER || // Probe droid - Laser blast - member->client->ps.weapon == WP_MELEE || - member->client->ps.weapon == WP_TURRET || // turret guns - member->client->ps.weapon == WP_ATST_MAIN || - member->client->ps.weapon == WP_ATST_SIDE || - member->client->ps.weapon == WP_TIE_FIGHTER ) - {//not really a squad-type guy + if (member->client->ps.weapon == WP_SABER || //!= self->s.weapon ) + member->client->ps.weapon == WP_THERMAL || member->client->ps.weapon == WP_DISRUPTOR || member->client->ps.weapon == WP_EMPLACED_GUN || + member->client->ps.weapon == WP_BOT_LASER || // Probe droid - Laser blast + member->client->ps.weapon == WP_MELEE || member->client->ps.weapon == WP_TURRET || // turret guns + member->client->ps.weapon == WP_ATST_MAIN || member->client->ps.weapon == WP_ATST_SIDE || + member->client->ps.weapon == WP_TIE_FIGHTER) { // not really a squad-type guy return qfalse; } - if ( member->client->NPC_class == CLASS_ATST || - member->client->NPC_class == CLASS_PROBE || - member->client->NPC_class == CLASS_SEEKER || - member->client->NPC_class == CLASS_REMOTE || - member->client->NPC_class == CLASS_SENTRY || - member->client->NPC_class == CLASS_INTERROGATOR || - member->client->NPC_class == CLASS_MINEMONSTER || - member->client->NPC_class == CLASS_HOWLER || - member->client->NPC_class == CLASS_RANCOR || - member->client->NPC_class == CLASS_MARK1 || - member->client->NPC_class == CLASS_MARK2 ) - {//these kinds of enemies don't actually use this group AI + if (member->client->NPC_class == CLASS_ATST || member->client->NPC_class == CLASS_PROBE || member->client->NPC_class == CLASS_SEEKER || + member->client->NPC_class == CLASS_REMOTE || member->client->NPC_class == CLASS_SENTRY || member->client->NPC_class == CLASS_INTERROGATOR || + member->client->NPC_class == CLASS_MINEMONSTER || member->client->NPC_class == CLASS_HOWLER || member->client->NPC_class == CLASS_RANCOR || + member->client->NPC_class == CLASS_MARK1 || member->client->NPC_class == CLASS_MARK2) { // these kinds of enemies don't actually use this group AI return qfalse; } - //should have same enemy - if ( member->enemy != group->enemy ) - { - if ( member->enemy != NULL ) - {//he's fighting someone else, leave him out + // should have same enemy + if (member->enemy != group->enemy) { + if (member->enemy != NULL) { // he's fighting someone else, leave him out return qfalse; } - if ( !gi.inPVS( member->currentOrigin, group->enemy->currentOrigin ) ) - {//not within PVS of the group enemy + if (!gi.inPVS(member->currentOrigin, group->enemy->currentOrigin)) { // not within PVS of the group enemy return qfalse; } - } - else if ( group->enemy == NULL ) - {//if the group is a patrol group, only take those within the room and radius - if ( !AI_ValidateNoEnemyGroupMember( group, member ) ) - { + } else if (group->enemy == NULL) { // if the group is a patrol group, only take those within the room and radius + if (!AI_ValidateNoEnemyGroupMember(group, member)) { return qfalse; } } - //must be actually in combat mode - if ( !TIMER_Done( member, "interrogating" ) ) + // must be actually in combat mode + if (!TIMER_Done(member, "interrogating")) return qfalse; - //FIXME: need to have a route to enemy and/or clear shot? + // FIXME: need to have a route to enemy and/or clear shot? return qtrue; } @@ -427,48 +351,41 @@ qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) AI_GetGroup ------------------------- */ -void AI_GetGroup( gentity_t *self ) -{ - int i; - gentity_t *member;//, *waiter; - //int waiters[MAX_WAITERS]; +void AI_GetGroup(gentity_t *self) { + int i; + gentity_t *member; //, *waiter; + // int waiters[MAX_WAITERS]; - if ( !self || !self->NPC ) - { + if (!self || !self->NPC) { return; } - if ( d_noGroupAI->integer ) - { + if (d_noGroupAI->integer) { self->NPC->group = NULL; return; } - if ( !self->client ) - { + if (!self->client) { self->NPC->group = NULL; return; } - if ( self->NPC->scriptFlags&SCF_NO_GROUPS ) - { + if (self->NPC->scriptFlags & SCF_NO_GROUPS) { self->NPC->group = NULL; return; } - if ( self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000 ))) - { + if (self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000))) { self->NPC->group = NULL; return; } - if ( !AI_GetNextEmptyGroup( self ) ) - {//either no more groups left or we're already in a group built earlier + if (!AI_GetNextEmptyGroup(self)) { // either no more groups left or we're already in a group built earlier return; } - //create a new one - memset( self->NPC->group, 0, sizeof( AIGroupInfo_t ) ); + // create a new one + memset(self->NPC->group, 0, sizeof(AIGroupInfo_t)); self->NPC->group->enemy = self->enemy; self->NPC->group->team = self->client->playerTeam; @@ -477,30 +394,27 @@ void AI_GetGroup( gentity_t *self ) self->NPC->group->memberValidateTime = level.time + 2000; self->NPC->group->activeMemberNum = 0; - if ( self->NPC->group->enemy ) - { + if (self->NPC->group->enemy) { self->NPC->group->lastSeenEnemyTime = level.time; self->NPC->group->lastClearShotTime = level.time; - VectorCopy( self->NPC->group->enemy->currentOrigin, self->NPC->group->enemyLastSeenPos ); + VectorCopy(self->NPC->group->enemy->currentOrigin, self->NPC->group->enemyLastSeenPos); } -// for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) - for ( i = 0; i < globals.num_entities ; i++) - { - if(!PInUse(i)) + // for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) + for (i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; member = &g_entities[i]; - if ( !AI_ValidateGroupMember( self->NPC->group, member ) ) - {//FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group + if (!AI_ValidateGroupMember( + self->NPC->group, member)) { // FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group continue; } - //store it - AI_InsertGroupMember( self->NPC->group, member ); + // store it + AI_InsertGroupMember(self->NPC->group, member); - if ( self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1) ) - {//full + if (self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1)) { // full break; } } @@ -524,120 +438,80 @@ void AI_GetGroup( gentity_t *self ) } */ - if ( self->NPC->group->numGroup <= 0 ) - {//none in group + if (self->NPC->group->numGroup <= 0) { // none in group self->NPC->group = NULL; return; } - AI_SortGroupByPathCostToEnemy( self->NPC->group ); - AI_SetClosestBuddy( self->NPC->group ); + AI_SortGroupByPathCostToEnemy(self->NPC->group); + AI_SetClosestBuddy(self->NPC->group); } -void AI_SetNewGroupCommander( AIGroupInfo_t *group ) -{ +void AI_SetNewGroupCommander(AIGroupInfo_t *group) { gentity_t *member = NULL; group->commander = NULL; - for ( int i = 0; i < group->numGroup; i++ ) - { + for (int i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( !group->commander || (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || + (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } } } -void AI_DeleteGroupMember( AIGroupInfo_t *group, int memberNum ) -{ - if ( group->commander && group->commander->s.number == group->member[memberNum].number ) - { +void AI_DeleteGroupMember(AIGroupInfo_t *group, int memberNum) { + if (group->commander && group->commander->s.number == group->member[memberNum].number) { group->commander = NULL; } - if ( g_entities[group->member[memberNum].number].NPC ) - { + if (g_entities[group->member[memberNum].number].NPC) { g_entities[group->member[memberNum].number].NPC->group = NULL; } - for ( int i = memberNum; i < (group->numGroup-1); i++ ) - { - memcpy( &group->member[i], &group->member[i+1], sizeof( group->member[i] ) ); + for (int i = memberNum; i < (group->numGroup - 1); i++) { + memcpy(&group->member[i], &group->member[i + 1], sizeof(group->member[i])); } - if ( memberNum < group->activeMemberNum ) - { + if (memberNum < group->activeMemberNum) { group->activeMemberNum--; - if ( group->activeMemberNum < 0 ) - { + if (group->activeMemberNum < 0) { group->activeMemberNum = 0; } } group->numGroup--; - if ( group->numGroup < 0 ) - { + if (group->numGroup < 0) { group->numGroup = 0; } - AI_SetNewGroupCommander( group ); + AI_SetNewGroupCommander(group); } -void AI_DeleteSelfFromGroup( gentity_t *self ) -{ - //FIXME: if killed, keep track of how many in group killed? To affect morale? - for ( int i = 0; i < self->NPC->group->numGroup; i++ ) - { - if ( self->NPC->group->member[i].number == self->s.number ) - { - AI_DeleteGroupMember( self->NPC->group, i ); +void AI_DeleteSelfFromGroup(gentity_t *self) { + // FIXME: if killed, keep track of how many in group killed? To affect morale? + for (int i = 0; i < self->NPC->group->numGroup; i++) { + if (self->NPC->group->member[i].number == self->s.number) { + AI_DeleteGroupMember(self->NPC->group, i); return; } } } -extern void ST_AggressionAdjust( gentity_t *self, int change ); -extern void ST_MarkToCover( gentity_t *self ); -extern void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ); -void AI_GroupMemberKilled( gentity_t *self ) -{ -/* AIGroupInfo_t *group = self->NPC->group; - gentity_t *member; - qboolean noflee = qfalse; +extern void ST_AggressionAdjust(gentity_t *self, int change); +extern void ST_MarkToCover(gentity_t *self); +extern void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime); +void AI_GroupMemberKilled(gentity_t *self) { + /* AIGroupInfo_t *group = self->NPC->group; + gentity_t *member; + qboolean noflee = qfalse; - if ( !group ) - {//what group? - return; - } - if ( !self || !self->NPC || self->NPC->rank < RANK_ENSIGN ) - {//I'm not an officer, let's not really care for now - return; - } - //temporarily drop group morale for a few seconds - group->moraleAdjust -= self->NPC->rank; - //go through and drop aggression on my teammates (more cover, worse aim) - for ( int i = 0; i < group->numGroup; i++ ) - { - member = &g_entities[group->member[i].number]; - if ( member == self ) - { - continue; - } - if ( member->NPC->rank > RANK_ENSIGN ) - {//officers do not panic - noflee = qtrue; + if ( !group ) + {//what group? + return; } - else - { - ST_AggressionAdjust( member, -1 ); - member->NPC->currentAim -= Q_irand( 0, 10 );//Q_irand( 0, 2);//drop their aim accuracy + if ( !self || !self->NPC || self->NPC->rank < RANK_ENSIGN ) + {//I'm not an officer, let's not really care for now + return; } - } - //okay, if I'm the group commander, make everyone else flee - if ( group->commander != self ) - {//I'm not the commander... hmm, should maybe a couple flee... maybe those near me? - return; - } - //now see if there is another of sufficient rank to keep them from fleeing - if ( !noflee ) - { - self->NPC->group->speechDebounceTime = 0; + //temporarily drop group morale for a few seconds + group->moraleAdjust -= self->NPC->rank; + //go through and drop aggression on my teammates (more cover, worse aim) for ( int i = 0; i < group->numGroup; i++ ) { member = &g_entities[group->member[i].number]; @@ -645,65 +519,83 @@ void AI_GroupMemberKilled( gentity_t *self ) { continue; } - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunt - if ( group->enemy && DistanceSquared( member->currentOrigin, group->enemy->currentOrigin ) < 65536 )//256*256 - {//those close to enemy run away! - ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else if ( DistanceSquared( member->currentOrigin, self->currentOrigin ) < 65536 ) - {//those close to me run away! - ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); + if ( member->NPC->rank > RANK_ENSIGN ) + {//officers do not panic + noflee = qtrue; + } + else + { + ST_AggressionAdjust( member, -1 ); + member->NPC->currentAim -= Q_irand( 0, 10 );//Q_irand( 0, 2);//drop their aim accuracy + } + } + //okay, if I'm the group commander, make everyone else flee + if ( group->commander != self ) + {//I'm not the commander... hmm, should maybe a couple flee... maybe those near me? + return; + } + //now see if there is another of sufficient rank to keep them from fleeing + if ( !noflee ) + { + self->NPC->group->speechDebounceTime = 0; + for ( int i = 0; i < group->numGroup; i++ ) + { + member = &g_entities[group->member[i].number]; + if ( member == self ) + { + continue; } - else - {//else, maybe just a random chance - if ( Q_irand( 0, self->NPC->rank ) > member->NPC->rank ) - {//lower rank they are, higher rank I am, more likely they are to flee + if ( member->NPC->rank < RANK_ENSIGN ) + {//grunt + if ( group->enemy && DistanceSquared( member->currentOrigin, group->enemy->currentOrigin ) < 65536 )//256*256 + {//those close to enemy run away! + ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); + } + else if ( DistanceSquared( member->currentOrigin, self->currentOrigin ) < 65536 ) + {//those close to me run away! ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); } else - { - ST_MarkToCover( member ); + {//else, maybe just a random chance + if ( Q_irand( 0, self->NPC->rank ) > member->NPC->rank ) + {//lower rank they are, higher rank I am, more likely they are to flee + ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); + } + else + { + ST_MarkToCover( member ); + } } + member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more } member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more } - member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more - } - }*/ + }*/ } -void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ) -{ - if ( !group ) - { +void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot) { + if (!group) { return; } group->lastSeenEnemyTime = level.time; - VectorCopy( spot, group->enemyLastSeenPos ); + VectorCopy(spot, group->enemyLastSeenPos); } -void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ) -{ - if ( !group ) - { +void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group) { + if (!group) { return; } group->lastClearShotTime = level.time; } -void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ) -{ - if ( !group ) - { +void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState) { + if (!group) { member->NPC->squadState = newSquadState; return; } - for ( int i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - { + for (int i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { group->numState[member->NPC->squadState]--; member->NPC->squadState = newSquadState; group->numState[member->NPC->squadState]++; @@ -712,63 +604,50 @@ void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int new } } -qboolean AI_RefreshGroup( AIGroupInfo_t *group ) -{ - gentity_t *member; - int i;//, j; +qboolean AI_RefreshGroup(AIGroupInfo_t *group) { + gentity_t *member; + int i; //, j; - //see if we should merge with another group - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( &level.groups[i] == group ) - { + // see if we should merge with another group + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (&level.groups[i] == group) { break; - } - else - { - if ( level.groups[i].enemy == group->enemy ) - {//2 groups with same enemy - if ( level.groups[i].numGroup+group->numGroup < (MAX_GROUP_MEMBERS - 1) ) - {//combining the members would fit in one group + } else { + if (level.groups[i].enemy == group->enemy) { // 2 groups with same enemy + if (level.groups[i].numGroup + group->numGroup < (MAX_GROUP_MEMBERS - 1)) { // combining the members would fit in one group qboolean deleteWhenDone = qtrue; - //combine the members of mine into theirs - for ( int j = 0; j < group->numGroup; j++ ) - { + // combine the members of mine into theirs + for (int j = 0; j < group->numGroup; j++) { member = &g_entities[group->member[j].number]; - if ( level.groups[i].enemy == NULL ) - {//special case for groups without enemies, must be in range - if ( !AI_ValidateNoEnemyGroupMember( &level.groups[i], member ) ) - { + if (level.groups[i].enemy == NULL) { // special case for groups without enemies, must be in range + if (!AI_ValidateNoEnemyGroupMember(&level.groups[i], member)) { deleteWhenDone = qfalse; continue; } } - //remove this member from this group - AI_DeleteGroupMember( group, j ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // remove this member from this group + AI_DeleteGroupMember(group, j); + // keep marker at same place since we deleted this guy and shifted everyone up one j--; - //add them to the earlier group - AI_InsertGroupMember( &level.groups[i], member ); + // add them to the earlier group + AI_InsertGroupMember(&level.groups[i], member); } - //return and delete this group - if ( deleteWhenDone ) - { + // return and delete this group + if (deleteWhenDone) { return qfalse; } } } } } - //clear numStates - for ( i = 0; i < NUM_SQUAD_STATES; i++ ) - { + // clear numStates + for (i = 0; i < NUM_SQUAD_STATES; i++) { group->numState[i] = 0; } - //go through group and validate each membership + // go through group and validate each membership group->commander = NULL; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { /* //this checks for duplicate copies of one member in a group for ( j = 0; j < group->numGroup; j++ ) @@ -783,43 +662,34 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } if ( j < group->numGroup ) {//found a dupe! - gi.Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, group->member[i].number ); - AI_DeleteGroupMember( group, i ); - i--; - continue; + gi.Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, group->member[i].number + ); AI_DeleteGroupMember( group, i ); i--; continue; } */ member = &g_entities[group->member[i].number]; - //Must be alive - if ( member->health <= 0 ) - { - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // Must be alive + if (member->health <= 0) { + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else if ( group->memberValidateTime < level.time && !AI_ValidateGroupMember( group, member ) ) - { - //remove this one from the group - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + } else if (group->memberValidateTime < level.time && !AI_ValidateGroupMember(group, member)) { + // remove this one from the group + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else - {//membership is valid - //keep track of squadStates + } else { // membership is valid + // keep track of squadStates group->numState[member->NPC->squadState]++; - if ( !group->commander || member->NPC->rank > group->commander->NPC->rank ) - {//keep track of highest rank + if (!group->commander || member->NPC->rank > group->commander->NPC->rank) { // keep track of highest rank group->commander = member; } } } - if ( group->memberValidateTime < level.time ) - { - group->memberValidateTime = level.time + Q_irand( 500, 2500 ); + if (group->memberValidateTime < level.time) { + group->memberValidateTime = level.time + Q_irand(500, 2500); } - //Now add any new guys as long as we're not full + // Now add any new guys as long as we're not full /* for ( i = 0, member = &g_entities[0]; i < globals.num_entities && group->numGroup < (MAX_GROUP_MEMBERS - 1); i++, member++) { @@ -837,40 +707,28 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } */ - //calc the morale of this group + // calc the morale of this group group->morale = group->moraleAdjust; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunts + if (member->NPC->rank < RANK_ENSIGN) { // grunts group->morale++; - } - else - { + } else { group->morale += member->NPC->rank; } - if ( group->commander && debugNPCAI->integer ) - { - G_DebugLine( group->commander->currentOrigin, member->currentOrigin, FRAMETIME, 0x00ff00ff, qtrue ); + if (group->commander && debugNPCAI->integer) { + G_DebugLine(group->commander->currentOrigin, member->currentOrigin, FRAMETIME, 0x00ff00ff, qtrue); } } - if ( group->enemy ) - {//modify morale based on enemy health and weapon - if ( group->enemy->health < 10 ) - { + if (group->enemy) { // modify morale based on enemy health and weapon + if (group->enemy->health < 10) { group->morale += 10; - } - else if ( group->enemy->health < 25 ) - { + } else if (group->enemy->health < 25) { group->morale += 5; - } - else if ( group->enemy->health < 50 ) - { + } else if (group->enemy->health < 50) { group->morale += 2; } - switch( group->enemy->s.weapon ) - { + switch (group->enemy->s.weapon) { case WP_SABER: group->morale -= 5; break; @@ -902,7 +760,7 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) case WP_DET_PACK: group->morale -= 10; break; - case WP_MELEE: // Any ol' melee attack + case WP_MELEE: // Any ol' melee attack group->morale += 20; break; case WP_STUN_BATON: @@ -919,56 +777,45 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) break; } } - if ( group->moraleDebounce < level.time ) - {//slowly degrade whatever moraleAdjusters we may have - if ( group->moraleAdjust > 0 ) - { + if (group->moraleDebounce < level.time) { // slowly degrade whatever moraleAdjusters we may have + if (group->moraleAdjust > 0) { group->moraleAdjust--; - } - else if ( group->moraleAdjust < 0 ) - { + } else if (group->moraleAdjust < 0) { group->moraleAdjust++; } - group->moraleDebounce = level.time + 1000;//FIXME: define? + group->moraleDebounce = level.time + 1000; // FIXME: define? } - //mark this group as not having been run this frame + // mark this group as not having been run this frame group->processed = qfalse; - return (qboolean)(group->numGroup>0); + return (qboolean)(group->numGroup > 0); } -void AI_UpdateGroups( void ) -{ - if ( d_noGroupAI->integer ) - { +void AI_UpdateGroups(void) { + if (d_noGroupAI->integer) { return; } - //Clear all Groups - for ( int i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup || AI_RefreshGroup( &level.groups[i] ) == qfalse )//level.groups[i].enemy == NULL || + // Clear all Groups + for (int i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup || AI_RefreshGroup(&level.groups[i]) == qfalse) // level.groups[i].enemy == NULL || { - memset( &level.groups[i], 0, sizeof( level.groups[i] ) ); + memset(&level.groups[i], 0, sizeof(level.groups[i])); } } } -qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ) -{ - if ( !group ) - { +qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum) { + if (!group) { return qfalse; } - for ( int i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == entNum ) - { + for (int i = 0; i < group->numGroup; i++) { + if (group->member[i].number == entNum) { return qtrue; } } return qfalse; } -//Overload +// Overload /* void AI_GetGroup( AIGroupInfo_t &group, gentity_t *ent, int radius ) @@ -1000,68 +847,63 @@ AI_DistributeAttack ------------------------- */ -#define MAX_RADIUS_ENTS 128 +#define MAX_RADIUS_ENTS 128 -gentity_t *AI_DistributeAttack( gentity_t *attacker, gentity_t *enemy, team_t team, int threshold ) -{ - //Don't take new targets - if ( NPC->svFlags & SVF_LOCKEDENEMY ) +gentity_t *AI_DistributeAttack(gentity_t *attacker, gentity_t *enemy, team_t team, int threshold) { + // Don't take new targets + if (NPC->svFlags & SVF_LOCKEDENEMY) return enemy; - int numSurrounding = AI_GetGroupSize( enemy->currentOrigin, 48, team, attacker ); + int numSurrounding = AI_GetGroupSize(enemy->currentOrigin, 48, team, attacker); - //First, see if we should look for the player - if ( enemy != &g_entities[0] ) - { - int aroundPlayer = AI_GetGroupSize( g_entities[0].currentOrigin, 48, team, attacker ); + // First, see if we should look for the player + if (enemy != &g_entities[0]) { + int aroundPlayer = AI_GetGroupSize(g_entities[0].currentOrigin, 48, team, attacker); - //See if we're above our threshold - if ( aroundPlayer < threshold ) - { + // See if we're above our threshold + if (aroundPlayer < threshold) { return &g_entities[0]; } } - //See if our current enemy is still ok - if ( numSurrounding < threshold ) + // See if our current enemy is still ok + if (numSurrounding < threshold) return enemy; - //Otherwise we need to take a new enemy if possible - vec3_t mins, maxs; + // Otherwise we need to take a new enemy if possible + vec3_t mins, maxs; - //Setup the bbox to search in - for ( int i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (int i = 0; i < 3; i++) { mins[i] = enemy->currentOrigin[i] - 512; maxs[i] = enemy->currentOrigin[i] + 512; } - //Get the number of entities in a given space - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; + // Get the number of entities in a given space + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; - int numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + int numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( int j = 0; j < numEnts; j++ ) - { - //Validate clients - if ( radiusEnts[ j ]->client == NULL ) + // Cull this list + for (int j = 0; j < numEnts; j++) { + // Validate clients + if (radiusEnts[j]->client == NULL) continue; - //Skip the requested avoid ent if present - if ( radiusEnts[ j ] == enemy ) + // Skip the requested avoid ent if present + if (radiusEnts[j] == enemy) continue; - //Must be on the same team - if ( radiusEnts[ j ]->client->playerTeam != enemy->client->playerTeam ) + // Must be on the same team + if (radiusEnts[j]->client->playerTeam != enemy->client->playerTeam) continue; - //Must be alive - if ( radiusEnts[ j ]->health <= 0 ) + // Must be alive + if (radiusEnts[j]->health <= 0) continue; - //Must not be overwhelmed - if ( AI_GetGroupSize( radiusEnts[j]->currentOrigin, 48, team, attacker ) > threshold ) + // Must not be overwhelmed + if (AI_GetGroupSize(radiusEnts[j]->currentOrigin, 48, team, attacker) > threshold) continue; return radiusEnts[j]; diff --git a/code/game/AI_Wampa.cpp b/code/game/AI_Wampa.cpp index 57195d3015..a5e7dae969 100644 --- a/code/game/AI_Wampa.cpp +++ b/code/game/AI_Wampa.cpp @@ -24,26 +24,25 @@ along with this program; if not, see . #include "g_navigator.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 48 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 48 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 1024 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 1024 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 float enemyDist = 0; -extern qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern cvar_t *g_dismemberment; +extern qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask); +extern int PM_AnimLength(int index, animNumber_t anim); +extern cvar_t *g_dismemberment; /* ------------------------- NPC_Wampa_Precache ------------------------- */ -void NPC_Wampa_Precache( void ) -{ +void NPC_Wampa_Precache(void) { /* int i; for ( i = 1; i < 4; i ++ ) @@ -55,35 +54,30 @@ void NPC_Wampa_Precache( void ) G_SoundIndex( va("sound/chars/wampa/snort%d.wav", i) ); } */ - G_SoundIndex( "sound/chars/rancor/swipehit.wav" ); - //G_SoundIndex( "sound/chars/wampa/chomp.wav" ); + G_SoundIndex("sound/chars/rancor/swipehit.wav"); + // G_SoundIndex( "sound/chars/wampa/chomp.wav" ); } - /* ------------------------- Wampa_Idle ------------------------- */ -void Wampa_Idle( void ) -{ +void Wampa_Idle(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } -qboolean Wampa_CheckRoar( gentity_t *self ) -{ - if ( self->wait < level.time ) - { - self->wait = level.time + Q_irand( 5000, 20000 ); - NPC_SetAnim( self, SETANIM_BOTH, Q_irand(BOTH_GESTURE1,BOTH_GESTURE2), (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD) ); - TIMER_Set( self, "rageTime", self->client->ps.legsAnimTimer ); +qboolean Wampa_CheckRoar(gentity_t *self) { + if (self->wait < level.time) { + self->wait = level.time + Q_irand(5000, 20000); + NPC_SetAnim(self, SETANIM_BOTH, Q_irand(BOTH_GESTURE1, BOTH_GESTURE2), (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD)); + TIMER_Set(self, "rageTime", self->client->ps.legsAnimTimer); return qtrue; } return qfalse; @@ -93,24 +87,21 @@ qboolean Wampa_CheckRoar( gentity_t *self ) Wampa_Patrol ------------------------- */ -void Wampa_Patrol( void ) -{ +void Wampa_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Wampa_Idle(); return; } - Wampa_CheckRoar( NPC ); - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); + Wampa_CheckRoar(NPC); + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(5000, 15000)); } /* @@ -118,267 +109,211 @@ void Wampa_Patrol( void ) Wampa_Move ------------------------- */ -void Wampa_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +void Wampa_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - trace_t trace; - if ( !NAV_CheckAhead( NPC, NPCInfo->goalEntity->currentOrigin, trace, (NPC->clipmask|CONTENTS_BOTCLIP) ) ) - { - if ( !NPC_MoveToGoal( qfalse ) ) - { + trace_t trace; + if (!NAV_CheckAhead(NPC, NPCInfo->goalEntity->currentOrigin, trace, (NPC->clipmask | CONTENTS_BOTCLIP))) { + if (!NPC_MoveToGoal(qfalse)) { STEER::Activate(NPC); STEER::Seek(NPC, NPCInfo->goalEntity->currentOrigin); STEER::AvoidCollisions(NPC); STEER::DeActivate(NPC, &ucmd); } } - NPCInfo->goalRadius = MIN_DISTANCE;//MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MIN_DISTANCE; // MAX_DISTANCE; // just get us within combat range - if ( NPC->enemy ) - {//pick correct movement speed and anim - //run by default + if (NPC->enemy) { // pick correct movement speed and anim + // run by default ucmd.buttons &= ~BUTTON_WALKING; - if ( !TIMER_Done( NPC, "runfar" ) - || !TIMER_Done( NPC, "runclose" ) ) - {//keep running with this anim & speed for a bit - } - else if ( !TIMER_Done( NPC, "walk" ) ) - {//keep walking for a bit + if (!TIMER_Done(NPC, "runfar") || !TIMER_Done(NPC, "runclose")) { // keep running with this anim & speed for a bit + } else if (!TIMER_Done(NPC, "walk")) { // keep walking for a bit ucmd.buttons |= BUTTON_WALKING; - } - else if ( visible && enemyDist > 350 && NPCInfo->stats.runSpeed == 200 )//180 ) - {//fast run, all fours - //BOTH_RUN1 + } else if (visible && enemyDist > 350 && NPCInfo->stats.runSpeed == 200) // 180 ) + { // fast run, all fours + // BOTH_RUN1 NPCInfo->stats.runSpeed = 300; - TIMER_Set( NPC, "runfar", Q_irand( 4000, 8000 ) ); - if ( NPC->client->ps.legsAnim == BOTH_RUN2 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN2TORUN1, SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "runfar", Q_irand(4000, 8000)); + if (NPC->client->ps.legsAnim == BOTH_RUN2) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN2TORUN1, SETANIM_FLAG_HOLD); } - } - else if ( enemyDist > 200 && NPCInfo->stats.runSpeed == 300 ) - {//slow run, upright - //BOTH_RUN2 - NPCInfo->stats.runSpeed = 200;//180; - TIMER_Set( NPC, "runclose", Q_irand( 5000, 10000 ) ); - if ( NPC->client->ps.legsAnim == BOTH_RUN1 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1TORUN2, SETANIM_FLAG_HOLD ); + } else if (enemyDist > 200 && NPCInfo->stats.runSpeed == 300) { // slow run, upright + // BOTH_RUN2 + NPCInfo->stats.runSpeed = 200; // 180; + TIMER_Set(NPC, "runclose", Q_irand(5000, 10000)); + if (NPC->client->ps.legsAnim == BOTH_RUN1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1TORUN2, SETANIM_FLAG_HOLD); } - } - else if ( enemyDist < 100 ) - {//walk - NPCInfo->stats.runSpeed = 200;//180; + } else if (enemyDist < 100) { // walk + NPCInfo->stats.runSpeed = 200; // 180; ucmd.buttons |= BUTTON_WALKING; - TIMER_Set( NPC, "walk", Q_irand( 6000, 12000 ) ); + TIMER_Set(NPC, "walk", Q_irand(6000, 12000)); } } } } //--------------------------------------------------------- -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ); -extern int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); - -void Wampa_Slash( int boltIndex, qboolean backhand ) -{ - gentity_t *radiusEnts[ 128 ]; - int numEnts; - const float radius = 88; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; - int damage = (backhand)?Q_irand(10,15):Q_irand(20,30); - - numEnts = NPC_GetEntsNearBolt( radiusEnts, radius, boltIndex, boltOrg ); - - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse); +extern int NPC_GetEntsNearBolt(gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg); + +void Wampa_Slash(int boltIndex, qboolean backhand) { + gentity_t *radiusEnts[128]; + int numEnts; + const float radius = 88; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; + int damage = (backhand) ? Q_irand(10, 15) : Q_irand(20, 30); + + numEnts = NPC_GetEntsNearBolt(radiusEnts, radius, boltIndex, boltOrg); + + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == NPC ) - {//Skip the wampa ent + if (radiusEnts[i] == NPC) { // Skip the wampa ent continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client + if (radiusEnts[i]->client == NULL) { // must be a client continue; } - if ( DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ) <= radiusSquared ) - { - //smack - G_Damage( radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, damage, ((backhand)?0:DAMAGE_NO_KNOCKBACK), MOD_MELEE ); - if ( backhand ) - { - //actually push the enemy + if (DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg) <= radiusSquared) { + // smack + G_Damage(radiusEnts[i], NPC, NPC, vec3_origin, radiusEnts[i]->currentOrigin, damage, ((backhand) ? 0 : DAMAGE_NO_KNOCKBACK), MOD_MELEE); + if (backhand) { + // actually push the enemy vec3_t pushDir; vec3_t angs; - VectorCopy( NPC->client->ps.viewangles, angs ); - angs[YAW] += Q_flrand( 25, 50 ); - angs[PITCH] = Q_flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - if ( radiusEnts[i]->client->NPC_class != CLASS_WAMPA - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST - && !(radiusEnts[i]->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( radiusEnts[i], pushDir, 65 ); - if ( radiusEnts[i]->health > 0 && Q_irand( 0, 1 ) ) - {//do pain on enemy - G_Knockdown( radiusEnts[i], NPC, pushDir, 300, qtrue ); + VectorCopy(NPC->client->ps.viewangles, angs); + angs[YAW] += Q_flrand(25, 50); + angs[PITCH] = Q_flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + if (radiusEnts[i]->client->NPC_class != CLASS_WAMPA && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && + radiusEnts[i]->client->NPC_class != CLASS_ATST && !(radiusEnts[i]->flags & FL_NO_KNOCKBACK)) { + G_Throw(radiusEnts[i], pushDir, 65); + if (radiusEnts[i]->health > 0 && Q_irand(0, 1)) { // do pain on enemy + G_Knockdown(radiusEnts[i], NPC, pushDir, 300, qtrue); } } - } - else if ( radiusEnts[i]->health <= 0 && radiusEnts[i]->client ) - {//killed them, chance of dismembering - if ( !Q_irand( 0, 1 ) ) - {//bite something off + } else if (radiusEnts[i]->health <= 0 && radiusEnts[i]->client) { // killed them, chance of dismembering + if (!Q_irand(0, 1)) { // bite something off int hitLoc = HL_WAIST; - if ( g_dismemberment->integer < 4 ) - { - hitLoc = Q_irand( HL_BACK_RT, HL_HAND_LT ); - } - else - { - hitLoc = Q_irand( HL_WAIST, HL_HEAD ); - } - if ( hitLoc == HL_HEAD ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (g_dismemberment->integer < 4) { + hitLoc = Q_irand(HL_BACK_RT, HL_HAND_LT); + } else { + hitLoc = Q_irand(HL_WAIST, HL_HEAD); } - else if ( hitLoc == HL_WAIST ) - { - NPC_SetAnim( radiusEnts[i], SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (hitLoc == HL_HEAD) { + NPC_SetAnim(radiusEnts[i], SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (hitLoc == HL_WAIST) { + NPC_SetAnim(radiusEnts[i], SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } radiusEnts[i]->client->dismembered = false; - //FIXME: the limb should just disappear, cuz I ate it - G_DoDismemberment( radiusEnts[i], radiusEnts[i]->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue ); + // FIXME: the limb should just disappear, cuz I ate it + G_DoDismemberment(radiusEnts[i], radiusEnts[i]->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue); } - } - else if ( !Q_irand( 0, 3 ) && radiusEnts[i]->health > 0 ) - {//one out of every 4 normal hits does a knockdown, too + } else if (!Q_irand(0, 3) && radiusEnts[i]->health > 0) { // one out of every 4 normal hits does a knockdown, too vec3_t pushDir; vec3_t angs; - VectorCopy( NPC->client->ps.viewangles, angs ); - angs[YAW] += Q_flrand( 25, 50 ); - angs[PITCH] = Q_flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - G_Knockdown( radiusEnts[i], NPC, pushDir, 35, qtrue ); + VectorCopy(NPC->client->ps.viewangles, angs); + angs[YAW] += Q_flrand(25, 50); + angs[PITCH] = Q_flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + G_Knockdown(radiusEnts[i], NPC, pushDir, 35, qtrue); } - G_Sound( radiusEnts[i], G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); + G_Sound(radiusEnts[i], G_SoundIndex("sound/chars/rancor/swipehit.wav")); } } } //------------------------------ -void Wampa_Attack( float distance, qboolean doCharge ) -{ - if ( !TIMER_Exists( NPC, "attacking" ) ) - { - if ( !Q_irand(0, 3) && !doCharge ) - {//double slash - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 750 ); - } - else if ( doCharge || (distance > 270 && distance < 430 && !Q_irand(0, 1)) ) - {//leap - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 500 ); - vec3_t fwd, yawAng ={0, NPC->client->ps.viewangles[YAW], 0}; - AngleVectors( yawAng, fwd, NULL, NULL ); - VectorScale( fwd, distance*1.5f, NPC->client->ps.velocity ); +void Wampa_Attack(float distance, qboolean doCharge) { + if (!TIMER_Exists(NPC, "attacking")) { + if (!Q_irand(0, 3) && !doCharge) { // double slash + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 750); + } else if (doCharge || (distance > 270 && distance < 430 && !Q_irand(0, 1))) { // leap + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 500); + vec3_t fwd, yawAng = {0, NPC->client->ps.viewangles[YAW], 0}; + AngleVectors(yawAng, fwd, NULL, NULL); + VectorScale(fwd, distance * 1.5f, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 150; NPC->client->ps.groundEntityNum = ENTITYNUM_NONE; - } - else if ( distance < 100 )//&& !Q_irand( 0, 4 ) ) - {//grab - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + } else if (distance < 100) //&& !Q_irand( 0, 4 ) ) + { // grab + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer += 200; - TIMER_Set( NPC, "attack_dmg", 250 ); - } - else - {//backhand - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attack_dmg", 250 ); + TIMER_Set(NPC, "attack_dmg", 250); + } else { // backhand + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attack_dmg", 250); } - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_flrand(0.0f, 1.0f) * 200 ); - //allow us to re-evaluate our running speed/anim - TIMER_Set( NPC, "runfar", -1 ); - TIMER_Set( NPC, "runclose", -1 ); - TIMER_Set( NPC, "walk", -1 ); + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_flrand(0.0f, 1.0f) * 200); + // allow us to re-evaluate our running speed/anim + TIMER_Set(NPC, "runfar", -1); + TIMER_Set(NPC, "runclose", -1); + TIMER_Set(NPC, "walk", -1); } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPC, "attack_dmg", qtrue ) ) - { - switch ( NPC->client->ps.legsAnim ) - { + if (TIMER_Done2(NPC, "attack_dmg", qtrue)) { + switch (NPC->client->ps.legsAnim) { case BOTH_ATTACK1: - Wampa_Slash( NPC->handRBolt, qfalse ); - //do second hit - TIMER_Set( NPC, "attack_dmg2", 100 ); + Wampa_Slash(NPC->handRBolt, qfalse); + // do second hit + TIMER_Set(NPC, "attack_dmg2", 100); break; case BOTH_ATTACK2: - Wampa_Slash( NPC->handRBolt, qfalse ); - TIMER_Set( NPC, "attack_dmg2", 100 ); + Wampa_Slash(NPC->handRBolt, qfalse); + TIMER_Set(NPC, "attack_dmg2", 100); break; case BOTH_ATTACK3: - Wampa_Slash( NPC->handLBolt, qtrue ); + Wampa_Slash(NPC->handLBolt, qtrue); break; } - } - else if ( TIMER_Done2( NPC, "attack_dmg2", qtrue ) ) - { - switch ( NPC->client->ps.legsAnim ) - { + } else if (TIMER_Done2(NPC, "attack_dmg2", qtrue)) { + switch (NPC->client->ps.legsAnim) { case BOTH_ATTACK1: - Wampa_Slash( NPC->handLBolt, qfalse ); + Wampa_Slash(NPC->handLBolt, qfalse); break; case BOTH_ATTACK2: - Wampa_Slash( NPC->handLBolt, qfalse ); + Wampa_Slash(NPC->handLBolt, qfalse); break; } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); - if ( NPC->client->ps.legsAnim == BOTH_ATTACK1 && distance > (NPC->maxs[0]+MIN_DISTANCE) ) - {//okay to keep moving + if (NPC->client->ps.legsAnim == BOTH_ATTACK1 && distance > (NPC->maxs[0] + MIN_DISTANCE)) { // okay to keep moving ucmd.buttons |= BUTTON_WALKING; - Wampa_Move( qtrue ); + Wampa_Move(qtrue); } } //---------------------------------- -void Wampa_Combat( void ) -{ +void Wampa_Combat(void) { // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) ) - { - if ( !Q_irand( 0, 10 ) ) - { - if ( Wampa_CheckRoar( NPC ) ) - { + if (!NPC_ClearLOS(NPC->enemy)) { + if (!Q_irand(0, 10)) { + if (Wampa_CheckRoar(NPC)) { return; } } NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MIN_DISTANCE;//MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MIN_DISTANCE; // MAX_DISTANCE; // just get us within combat range - Wampa_Move( qfalse ); + Wampa_Move(qfalse); return; } /* @@ -393,50 +328,41 @@ void Wampa_Combat( void ) }*/ // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - //FIXME: always seems to face off to the left or right?!!!! - NPC_FaceEnemy( qtrue ); - - float distance = enemyDist = Distance( NPC->currentOrigin, NPC->enemy->currentOrigin ); - - qboolean advance = (qboolean)( distance > (NPC->maxs[0]+MIN_DISTANCE) ? qtrue : qfalse ); - qboolean doCharge = qfalse; - - if ( advance ) - {//have to get closer - vec3_t yawOnlyAngles = {0, NPC->currentAngles[YAW], 0}; - if ( NPC->enemy->health > 0//enemy still alive - && fabs(distance-350) <= 80 //enemy anywhere from 270 to 430 away - && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, yawOnlyAngles, 20, 20 ) )//enemy generally in front - {//10% chance of doing charge anim - if ( !Q_irand( 0, 6 ) ) - {//go for the charge + // FIXME: always seems to face off to the left or right?!!!! + NPC_FaceEnemy(qtrue); + + float distance = enemyDist = Distance(NPC->currentOrigin, NPC->enemy->currentOrigin); + + qboolean advance = (qboolean)(distance > (NPC->maxs[0] + MIN_DISTANCE) ? qtrue : qfalse); + qboolean doCharge = qfalse; + + if (advance) { // have to get closer + vec3_t yawOnlyAngles = {0, NPC->currentAngles[YAW], 0}; + if (NPC->enemy->health > 0 // enemy still alive + && fabs(distance - 350) <= 80 // enemy anywhere from 270 to 430 away + && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, yawOnlyAngles, 20, 20)) // enemy generally in front + { // 10% chance of doing charge anim + if (!Q_irand(0, 6)) { // go for the charge doCharge = qtrue; advance = qfalse; } } } - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else { + Wampa_Move(qtrue); } - else - { - Wampa_Move( qtrue ); - } - } - else - { - if ( !Q_irand( 0, 15 ) ) - {//FIXME: only do this if we just damaged them or vice-versa? - if ( Wampa_CheckRoar( NPC ) ) - { + } else { + if (!Q_irand(0, 15)) { // FIXME: only do this if we just damaged them or vice-versa? + if (Wampa_CheckRoar(NPC)) { return; } } - Wampa_Attack( distance, doCharge ); + Wampa_Attack(distance, doCharge); } } @@ -445,79 +371,60 @@ void Wampa_Combat( void ) NPC_Wampa_Pain ------------------------- */ -void NPC_Wampa_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_Wampa_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { qboolean hitByWampa = qfalse; - if ( self->count ) - {//FIXME: need pain anim - NPC_SetAnim( self, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( self, "takingPain", self->client->ps.legsAnimTimer ); - TIMER_Set(self,"attacking",-level.time); + if (self->count) { // FIXME: need pain anim + NPC_SetAnim(self, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(self, "takingPain", self->client->ps.legsAnimTimer); + TIMER_Set(self, "attacking", -level.time); return; } - if ( other&&other->client&&other->client->NPC_class==CLASS_WAMPA ) - { + if (other && other->client && other->client->NPC_class == CLASS_WAMPA) { hitByWampa = qtrue; } - if ( other - && other->inuse - && other != self->enemy - && !(other->flags&FL_NOTARGET) ) - { - if ( (!other->s.number&&!Q_irand(0,3)) - || !self->enemy - || self->enemy->health == 0 - || (self->enemy->client&&self->enemy->client->NPC_class == CLASS_WAMPA) - || (!Q_irand(0, 4 ) && DistanceSquared( other->currentOrigin, self->currentOrigin ) < DistanceSquared( self->enemy->currentOrigin, self->currentOrigin )) ) - {//if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker - //FIXME: if can't nav to my enemy, take this guy if I can nav to him + if (other && other->inuse && other != self->enemy && !(other->flags & FL_NOTARGET)) { + if ((!other->s.number && !Q_irand(0, 3)) || !self->enemy || self->enemy->health == 0 || + (self->enemy->client && self->enemy->client->NPC_class == CLASS_WAMPA) || + (!Q_irand(0, 4) && + DistanceSquared(other->currentOrigin, self->currentOrigin) < + DistanceSquared( + self->enemy->currentOrigin, + self->currentOrigin))) { // if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker + // FIXME: if can't nav to my enemy, take this guy if I can nav to him self->lastEnemy = other; - G_SetEnemy( self, other ); - if ( self->enemy != self->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(self, other); + if (self->enemy != self->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up self->useDebounceTime = 0; } - TIMER_Set( self, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - if ( hitByWampa ) - {//stay mad at this Wampa for 2-5 secs before looking for other enemies - TIMER_Set( self, "wampaInfight", Q_irand( 2000, 5000 ) ); + TIMER_Set(self, "lookForNewEnemy", Q_irand(5000, 15000)); + if (hitByWampa) { // stay mad at this Wampa for 2-5 secs before looking for other enemies + TIMER_Set(self, "wampaInfight", Q_irand(2000, 5000)); } } } - if ( (hitByWampa|| Q_irand( 0, 100 ) < damage )//hit by wampa, hit while holding live victim, or took a lot of damage - && self->client->ps.legsAnim != BOTH_GESTURE1 - && self->client->ps.legsAnim != BOTH_GESTURE2 - && TIMER_Done( self, "takingPain" ) ) - { - if ( !Wampa_CheckRoar( self ) ) - { - if ( self->client->ps.legsAnim != BOTH_ATTACK1 - && self->client->ps.legsAnim != BOTH_ATTACK2 - && self->client->ps.legsAnim != BOTH_ATTACK3 ) - {//cant interrupt one of the big attack anims - if ( self->health > 100 || hitByWampa ) - { - TIMER_Remove( self, "attacking" ); - - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); - - if ( !Q_irand( 0, 1 ) ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if ((hitByWampa || Q_irand(0, 100) < damage) // hit by wampa, hit while holding live victim, or took a lot of damage + && self->client->ps.legsAnim != BOTH_GESTURE1 && self->client->ps.legsAnim != BOTH_GESTURE2 && TIMER_Done(self, "takingPain")) { + if (!Wampa_CheckRoar(self)) { + if (self->client->ps.legsAnim != BOTH_ATTACK1 && self->client->ps.legsAnim != BOTH_ATTACK2 && + self->client->ps.legsAnim != BOTH_ATTACK3) { // cant interrupt one of the big attack anims + if (self->health > 100 || hitByWampa) { + TIMER_Remove(self, "attacking"); + + VectorCopy(self->NPC->lastPathAngles, self->s.angles); + + if (!Q_irand(0, 1)) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( self, "takingPain", self->client->ps.legsAnimTimer+Q_irand(0, 500*(2-g_spskill->integer)) ); - TIMER_Set(self,"attacking",-level.time); - //allow us to re-evaluate our running speed/anim - TIMER_Set( self, "runfar", -1 ); - TIMER_Set( self, "runclose", -1 ); - TIMER_Set( self, "walk", -1 ); - - if ( self->NPC ) - { + TIMER_Set(self, "takingPain", self->client->ps.legsAnimTimer + Q_irand(0, 500 * (2 - g_spskill->integer))); + TIMER_Set(self, "attacking", -level.time); + // allow us to re-evaluate our running speed/anim + TIMER_Set(self, "runfar", -1); + TIMER_Set(self, "runclose", -1); + TIMER_Set(self, "walk", -1); + + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } @@ -526,150 +433,111 @@ void NPC_Wampa_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, co } } -void Wampa_DropVictim( gentity_t *self ) -{ - //FIXME: if Wampa dies, it should drop its victim. - //FIXME: if Wampa is removed, it must remove its victim. - //FIXME: if in BOTH_HOLD_DROP, throw them a little, too? - if ( self->health > 0 ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); +void Wampa_DropVictim(gentity_t *self) { + // FIXME: if Wampa dies, it should drop its victim. + // FIXME: if Wampa is removed, it must remove its victim. + // FIXME: if in BOTH_HOLD_DROP, throw them a little, too? + if (self->health > 0) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set(self,"attacking",-level.time); - if ( self->activator ) - { - if ( self->activator->client ) - { + TIMER_Set(self, "attacking", -level.time); + if (self->activator) { + if (self->activator->client) { self->activator->client->ps.eFlags &= ~EF_HELD_BY_WAMPA; } self->activator->activator = NULL; - NPC_SetAnim( self->activator, SETANIM_BOTH, BOTH_RELEASED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self->activator, SETANIM_BOTH, BOTH_RELEASED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->activator->client->ps.legsAnimTimer += 500; self->activator->client->ps.weaponTime = self->activator->client->ps.torsoAnimTimer = self->activator->client->ps.legsAnimTimer; - if ( self->activator->health > 0 ) - { - if ( self->activator->NPC ) - {//start thinking again + if (self->activator->health > 0) { + if (self->activator->NPC) { // start thinking again self->activator->NPC->nextBStateThink = level.time; } - if ( self->activator->client && self->activator->s.number < MAX_CLIENTS ) - { - vec3_t vicAngles = {30,AngleNormalize180(self->client->ps.viewangles[YAW]+180),0}; - SetClientViewAngle( self->activator, vicAngles ); + if (self->activator->client && self->activator->s.number < MAX_CLIENTS) { + vec3_t vicAngles = {30, AngleNormalize180(self->client->ps.viewangles[YAW] + 180), 0}; + SetClientViewAngle(self->activator, vicAngles); } - } - else - { - if ( self->enemy == self->activator ) - { + } else { + if (self->enemy == self->activator) { self->enemy = NULL; } self->activator->clipmask &= ~CONTENTS_BODY; } self->activator = NULL; } - self->count = 0;//drop him + self->count = 0; // drop him } -qboolean Wampa_CheckDropVictim( gentity_t *self, qboolean excludeMe ) -{ - if ( !self - || !self->activator ) - { +qboolean Wampa_CheckDropVictim(gentity_t *self, qboolean excludeMe) { + if (!self || !self->activator) { return qtrue; } - vec3_t mins={self->activator->mins[0]-1,self->activator->mins[1]-1,0}; - vec3_t maxs={self->activator->maxs[0]+1,self->activator->maxs[1]+1,1}; - vec3_t start={self->activator->currentOrigin[0],self->activator->currentOrigin[1],self->activator->absmin[2]}; - vec3_t end={self->activator->currentOrigin[0],self->activator->currentOrigin[1],self->activator->absmax[2]-1}; - trace_t trace; - if ( excludeMe ) - { - gi.unlinkentity( self ); + vec3_t mins = {self->activator->mins[0] - 1, self->activator->mins[1] - 1, 0}; + vec3_t maxs = {self->activator->maxs[0] + 1, self->activator->maxs[1] + 1, 1}; + vec3_t start = {self->activator->currentOrigin[0], self->activator->currentOrigin[1], self->activator->absmin[2]}; + vec3_t end = {self->activator->currentOrigin[0], self->activator->currentOrigin[1], self->activator->absmax[2] - 1}; + trace_t trace; + if (excludeMe) { + gi.unlinkentity(self); } - gi.trace( &trace, start, mins, maxs, end, self->activator->s.number, self->activator->clipmask, (EG2_Collision)0, 0 ); - if ( excludeMe ) - { - gi.linkentity( self ); + gi.trace(&trace, start, mins, maxs, end, self->activator->s.number, self->activator->clipmask, (EG2_Collision)0, 0); + if (excludeMe) { + gi.linkentity(self); } - if ( !trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f ) - { - Wampa_DropVictim( self ); + if (!trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f) { + Wampa_DropVictim(self); return qtrue; } - if ( excludeMe ) - {//victim stuck in wall - if ( self->NPC ) - {//turn - self->NPC->desiredYaw += Q_irand( -30, 30 ); + if (excludeMe) { // victim stuck in wall + if (self->NPC) { // turn + self->NPC->desiredYaw += Q_irand(-30, 30); self->NPC->lockedDesiredYaw = self->NPC->desiredYaw; } } return qfalse; } -extern float NPC_EnemyRangeFromBolt( int boltIndex ); -qboolean Wampa_TryGrab( void ) -{ - const float radius = 64.0f; +extern float NPC_EnemyRangeFromBolt(int boltIndex); +qboolean Wampa_TryGrab(void) { + const float radius = 64.0f; - if ( !NPC->enemy - || !NPC->enemy->client - || NPC->enemy->health <= 0 ) - { + if (!NPC->enemy || !NPC->enemy->client || NPC->enemy->health <= 0) { return qfalse; } - float enemyDist = NPC_EnemyRangeFromBolt( NPC->handRBolt ); - if ( enemyDist <= radius - && !NPC->count //don't have one in hand already - && NPC->enemy->client->NPC_class != CLASS_RANCOR - && NPC->enemy->client->NPC_class != CLASS_GALAKMECH - && NPC->enemy->client->NPC_class != CLASS_ATST - && NPC->enemy->client->NPC_class != CLASS_GONK - && NPC->enemy->client->NPC_class != CLASS_R2D2 - && NPC->enemy->client->NPC_class != CLASS_R5D2 - && NPC->enemy->client->NPC_class != CLASS_MARK1 - && NPC->enemy->client->NPC_class != CLASS_MARK2 - && NPC->enemy->client->NPC_class != CLASS_MOUSE - && NPC->enemy->client->NPC_class != CLASS_PROBE - && NPC->enemy->client->NPC_class != CLASS_SEEKER - && NPC->enemy->client->NPC_class != CLASS_REMOTE - && NPC->enemy->client->NPC_class != CLASS_SENTRY - && NPC->enemy->client->NPC_class != CLASS_INTERROGATOR - && NPC->enemy->client->NPC_class != CLASS_VEHICLE ) - {//grab - NPC->enemy = NPC->enemy;//make him my new best friend + float enemyDist = NPC_EnemyRangeFromBolt(NPC->handRBolt); + if (enemyDist <= radius && !NPC->count // don't have one in hand already + && NPC->enemy->client->NPC_class != CLASS_RANCOR && NPC->enemy->client->NPC_class != CLASS_GALAKMECH && NPC->enemy->client->NPC_class != CLASS_ATST && + NPC->enemy->client->NPC_class != CLASS_GONK && NPC->enemy->client->NPC_class != CLASS_R2D2 && NPC->enemy->client->NPC_class != CLASS_R5D2 && + NPC->enemy->client->NPC_class != CLASS_MARK1 && NPC->enemy->client->NPC_class != CLASS_MARK2 && NPC->enemy->client->NPC_class != CLASS_MOUSE && + NPC->enemy->client->NPC_class != CLASS_PROBE && NPC->enemy->client->NPC_class != CLASS_SEEKER && NPC->enemy->client->NPC_class != CLASS_REMOTE && + NPC->enemy->client->NPC_class != CLASS_SENTRY && NPC->enemy->client->NPC_class != CLASS_INTERROGATOR && + NPC->enemy->client->NPC_class != CLASS_VEHICLE) { // grab + NPC->enemy = NPC->enemy; // make him my new best friend NPC->enemy->client->ps.eFlags |= EF_HELD_BY_WAMPA; - //FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something + // FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something NPC->enemy->activator = NPC; // kind of dumb, but when we are locked to the Rancor, we are owned by it. - NPC->activator = NPC->enemy;//remember him - NPC->count = 1;//in my hand - //wait to attack - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(500, 2500) ); - NPC_SetAnim( NPC->enemy, SETANIM_BOTH, BOTH_GRABBED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "takingPain", -level.time ); + NPC->activator = NPC->enemy; // remember him + NPC->count = 1; // in my hand + // wait to attack + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(500, 2500)); + NPC_SetAnim(NPC->enemy, SETANIM_BOTH, BOTH_GRABBED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "takingPain", -level.time); return qtrue; - } - else if ( enemyDist < radius*2.0f ) - {//smack - G_Sound( NPC->enemy, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - //actually push the enemy + } else if (enemyDist < radius * 2.0f) { // smack + G_Sound(NPC->enemy, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + // actually push the enemy vec3_t pushDir; vec3_t angs; - VectorCopy( NPC->client->ps.viewangles, angs ); - angs[YAW] += Q_flrand( 25, 50 ); - angs[PITCH] = Q_flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - if ( NPC->enemy->client->NPC_class != CLASS_RANCOR - && NPC->enemy->client->NPC_class != CLASS_ATST - && !(NPC->enemy->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( NPC->enemy, pushDir, Q_irand( 30, 70 ) ); - if ( NPC->enemy->health > 0 ) - {//do pain on enemy - G_Knockdown( NPC->enemy, NPC, pushDir, 300, qtrue ); + VectorCopy(NPC->client->ps.viewangles, angs); + angs[YAW] += Q_flrand(25, 50); + angs[PITCH] = Q_flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + if (NPC->enemy->client->NPC_class != CLASS_RANCOR && NPC->enemy->client->NPC_class != CLASS_ATST && !(NPC->enemy->flags & FL_NO_KNOCKBACK)) { + G_Throw(NPC->enemy, pushDir, Q_irand(30, 70)); + if (NPC->enemy->health > 0) { // do pain on enemy + G_Knockdown(NPC->enemy, NPC, pushDir, 300, qtrue); } } } @@ -681,243 +549,180 @@ qboolean Wampa_TryGrab( void ) NPC_BSWampa_Default ------------------------- */ -void NPC_BSWampa_Default( void ) -{ - //NORMAL ANIMS +void NPC_BSWampa_Default(void) { + // NORMAL ANIMS // stand1 = normal stand // walk1 = normal, non-angry walk // walk2 = injured // run1 = far away run // run2 = close run - //VICTIM ANIMS + // VICTIM ANIMS // grabswipe = melee1 - sweep out and grab // stand2 attack = attack4 - while holding victim, swipe at him // walk3_drag = walk5 - walk with drag // stand2 = hold victim // stand2to1 = drop victim - if ( NPC->client->ps.legsAnim == BOTH_HOLD_START ) - { - NPC_FaceEnemy( qtrue ); - if ( NPC->client->ps.legsAnimTimer < 200 ) - {//see if he's there to grab - if ( !Wampa_TryGrab() ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (NPC->client->ps.legsAnim == BOTH_HOLD_START) { + NPC_FaceEnemy(qtrue); + if (NPC->client->ps.legsAnimTimer < 200) { // see if he's there to grab + if (!Wampa_TryGrab()) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } return; } - - if ( NPC->count ) - { - if ( !NPC->activator - || !NPC->activator->client ) - {//wtf? + if (NPC->count) { + if (!NPC->activator || !NPC->activator->client) { // wtf? NPC->count = 0; NPC->activator = NULL; - } - else - { - if ( NPC->client->ps.legsAnim == BOTH_HOLD_DROP ) - { - if ( NPC->client->ps.legsAnimTimer < PM_AnimLength(NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim)-500 ) - {//at least half a second into the anim - if ( Wampa_CheckDropVictim( NPC, qfalse ) ) - { - TIMER_Set( NPC, "attacking", 1000+(Q_irand(500,1000)*(3-g_spskill->integer)) ); + } else { + if (NPC->client->ps.legsAnim == BOTH_HOLD_DROP) { + if (NPC->client->ps.legsAnimTimer < PM_AnimLength(NPC->client->clientInfo.animFileIndex, (animNumber_t)NPC->client->ps.legsAnim) - + 500) { // at least half a second into the anim + if (Wampa_CheckDropVictim(NPC, qfalse)) { + TIMER_Set(NPC, "attacking", 1000 + (Q_irand(500, 1000) * (3 - g_spskill->integer))); } } - } - else if ( !TIMER_Done( NPC, "takingPain" ) ) - { - Wampa_CheckDropVictim( NPC, qfalse ); - } - else if ( NPC->activator->health <= 0 ) - { - if ( TIMER_Done(NPC,"sniffCorpse") ) - { - Wampa_CheckDropVictim( NPC, qfalse ); + } else if (!TIMER_Done(NPC, "takingPain")) { + Wampa_CheckDropVictim(NPC, qfalse); + } else if (NPC->activator->health <= 0) { + if (TIMER_Done(NPC, "sniffCorpse")) { + Wampa_CheckDropVictim(NPC, qfalse); } - } - else if ( NPC->useDebounceTime >= level.time - && NPC->activator ) - {//just sniffing the guy - if ( NPC->useDebounceTime <= level.time + 100 - && NPC->client->ps.legsAnim != BOTH_HOLD_DROP) - {//just about done, drop him - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attacking", NPC->client->ps.legsAnimTimer+500 ); + } else if (NPC->useDebounceTime >= level.time && NPC->activator) { // just sniffing the guy + if (NPC->useDebounceTime <= level.time + 100 && NPC->client->ps.legsAnim != BOTH_HOLD_DROP) { // just about done, drop him + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + 500); } - } - else - { - if ( !NPC->useDebounceTime - && NPC->activator - && NPC->activator->s.number < MAX_CLIENTS ) - {//first time I pick the player, just sniff them - if ( TIMER_Done(NPC,"attacking") ) - {//ready to attack - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_SNIFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC->useDebounceTime = level.time + NPC->client->ps.legsAnimTimer + Q_irand( 500, 2000 ); + } else { + if (!NPC->useDebounceTime && NPC->activator && NPC->activator->s.number < MAX_CLIENTS) { // first time I pick the player, just sniff them + if (TIMER_Done(NPC, "attacking")) { // ready to attack + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_SNIFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC->useDebounceTime = level.time + NPC->client->ps.legsAnimTimer + Q_irand(500, 2000); } - } - else - { - if ( TIMER_Done(NPC,"attacking") ) - {//ready to attack - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_ATTACK/*BOTH_ATTACK4*/, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set(NPC,"grabAttackDamage",1400); - TIMER_Set(NPC,"attacking",NPC->client->ps.legsAnimTimer+Q_irand(3000,10000)); + } else { + if (TIMER_Done(NPC, "attacking")) { // ready to attack + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_ATTACK /*BOTH_ATTACK4*/, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "grabAttackDamage", 1400); + TIMER_Set(NPC, "attacking", NPC->client->ps.legsAnimTimer + Q_irand(3000, 10000)); } - if ( NPC->client->ps.legsAnim == BOTH_HOLD_ATTACK ) - { - if ( NPC->client->ps.legsAnimTimer ) - { - if ( TIMER_Done2(NPC,"grabAttackDamage",qtrue) ) - { - G_Sound( NPC->activator, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - G_Damage( NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand( 25, 40 ), (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR), MOD_MELEE ); - if ( NPC->activator->health <= 0 ) - {//killed them, chance of dismembering + if (NPC->client->ps.legsAnim == BOTH_HOLD_ATTACK) { + if (NPC->client->ps.legsAnimTimer) { + if (TIMER_Done2(NPC, "grabAttackDamage", qtrue)) { + G_Sound(NPC->activator, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + G_Damage(NPC->activator, NPC, NPC, vec3_origin, NPC->activator->currentOrigin, Q_irand(25, 40), + (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_ARMOR), MOD_MELEE); + if (NPC->activator->health <= 0) { // killed them, chance of dismembering int hitLoc = HL_WAIST; - if ( g_dismemberment->integer < 4 ) - { - hitLoc = Q_irand( HL_BACK_RT, HL_HAND_LT ); - } - else - { - hitLoc = Q_irand( HL_WAIST, HL_HEAD ); + if (g_dismemberment->integer < 4) { + hitLoc = Q_irand(HL_BACK_RT, HL_HAND_LT); + } else { + hitLoc = Q_irand(HL_WAIST, HL_HEAD); } NPC->activator->client->dismembered = false; - //FIXME: the limb should just disappear, cuz I ate it - G_DoDismemberment( NPC->activator, NPC->activator->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue ); - TIMER_Set( NPC, "sniffCorpse", Q_irand( 2000, 5000 ) ); + // FIXME: the limb should just disappear, cuz I ate it + G_DoDismemberment(NPC->activator, NPC->activator->currentOrigin, MOD_SABER, 1000, hitLoc, qtrue); + TIMER_Set(NPC, "sniffCorpse", Q_irand(2000, 5000)); } - NPC_SetAnim( NPC->activator, SETANIM_BOTH, BOTH_HANG_PAIN, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC->activator, SETANIM_BOTH, BOTH_HANG_PAIN, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_IDLE /*BOTH_ATTACK4*/, SETANIM_FLAG_NORMAL); } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_IDLE/*BOTH_ATTACK4*/, SETANIM_FLAG_NORMAL ); - } - } - else if ( NPC->client->ps.legsAnim == BOTH_STAND2TO1 - && !NPC->client->ps.legsAnimTimer ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_HOLD_IDLE, SETANIM_FLAG_NORMAL ); + } else if (NPC->client->ps.legsAnim == BOTH_STAND2TO1 && !NPC->client->ps.legsAnimTimer) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_HOLD_IDLE, SETANIM_FLAG_NORMAL); } } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( NPCInfo->localState == LSTATE_WAITING - && TIMER_Done2( NPC, "takingPain", qtrue ) ) - {//was not doing anything because we were taking pain, but pain is done now, so clear it... + if (NPCInfo->localState == LSTATE_WAITING && + TIMER_Done2(NPC, "takingPain", qtrue)) { // was not doing anything because we were taking pain, but pain is done now, so clear it... NPCInfo->localState = LSTATE_CLEAR; } - if ( !TIMER_Done( NPC, "rageTime" ) ) - {//do nothing but roar first time we see an enemy - NPC_FaceEnemy( qtrue ); + if (!TIMER_Done(NPC, "rageTime")) { // do nothing but roar first time we see an enemy + NPC_FaceEnemy(qtrue); return; } - if ( NPC->enemy ) - { - if ( NPC->enemy->client //enemy is a client - && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA )//enemy is a lowly jawa or ugnaught - && NPC->enemy->enemy != NPC//enemy's enemy is not me - && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || NPC->enemy->enemy->client->NPC_class!=CLASS_RANCOR) )//enemy's enemy is not a client or is not a rancor (which is scarier than me) - {//they should be scared of ME and no-one else - G_SetEnemy( NPC->enemy, NPC ); - } - if ( !TIMER_Done(NPC,"attacking") ) - {//in middle of attack - //face enemy - NPC_FaceEnemy( qtrue ); - //continue attack logic - enemyDist = Distance( NPC->currentOrigin, NPC->enemy->currentOrigin ); - Wampa_Attack( enemyDist, qfalse ); + if (NPC->enemy) { + if (NPC->enemy->client // enemy is a client + && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA) // enemy is a lowly jawa or ugnaught + && NPC->enemy->enemy != NPC // enemy's enemy is not me + && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || + NPC->enemy->enemy->client->NPC_class != CLASS_RANCOR)) // enemy's enemy is not a client or is not a rancor (which is scarier than me) + { // they should be scared of ME and no-one else + G_SetEnemy(NPC->enemy, NPC); + } + if (!TIMER_Done(NPC, "attacking")) { // in middle of attack + // face enemy + NPC_FaceEnemy(qtrue); + // continue attack logic + enemyDist = Distance(NPC->currentOrigin, NPC->enemy->currentOrigin); + Wampa_Attack(enemyDist, qfalse); return; - } - else - { - if ( TIMER_Done(NPC,"angrynoise") ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/wampa/misc/anger%d.wav", Q_irand(1, 2)) ); + } else { + if (TIMER_Done(NPC, "angrynoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/wampa/misc/anger%d.wav", Q_irand(1, 2))); - TIMER_Set( NPC, "angrynoise", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPC, "angrynoise", Q_irand(5000, 10000)); } - //else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while - if( NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_WAMPA ) - {//got mad at another Wampa, look for a valid enemy - if ( TIMER_Done( NPC, "wampaInfight" ) ) - { - NPC_CheckEnemyExt( qtrue ); + // else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while + if (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_WAMPA) { // got mad at another Wampa, look for a valid enemy + if (TIMER_Done(NPC, "wampaInfight")) { + NPC_CheckEnemyExt(qtrue); } - } - else - { - if ( NPC_ValidEnemy( NPC->enemy ) == qfalse ) - { - TIMER_Remove( NPC, "lookForNewEnemy" );//make them look again right now - if ( !NPC->enemy->inuse || level.time - NPC->enemy->s.time > Q_irand( 10000, 15000 ) ) - {//it's been a while since the enemy died, or enemy is completely gone, get bored with him + } else { + if (NPC_ValidEnemy(NPC->enemy) == qfalse) { + TIMER_Remove(NPC, "lookForNewEnemy"); // make them look again right now + if (!NPC->enemy->inuse || + level.time - NPC->enemy->s.time > + Q_irand(10000, 15000)) { // it's been a while since the enemy died, or enemy is completely gone, get bored with him NPC->enemy = NULL; Wampa_Patrol(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( TIMER_Done( NPC, "lookForNewEnemy" ) ) - { - gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy? + if (TIMER_Done(NPC, "lookForNewEnemy")) { + gentity_t *sav_enemy = NPC->enemy; // FIXME: what about NPC->lastEnemy? NPC->enemy = NULL; - gentity_t *newEnemy = NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse ); + gentity_t *newEnemy = NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse); NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, newEnemy ); - if ( NPC->enemy != NPC->lastEnemy ) - {//clear this so that we only sniff the player the first time we pick them up + G_SetEnemy(NPC, newEnemy); + if (NPC->enemy != NPC->lastEnemy) { // clear this so that we only sniff the player the first time we pick them up NPC->useDebounceTime = 0; } - //hold this one for at least 5-15 seconds - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - } - else - {//look again in 2-5 secs - TIMER_Set( NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + // hold this one for at least 5-15 seconds + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(5000, 15000)); + } else { // look again in 2-5 secs + TIMER_Set(NPC, "lookForNewEnemy", Q_irand(2000, 5000)); } } } Wampa_Combat(); return; } - } - else - { - if ( TIMER_Done(NPC,"idlenoise") ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/wampa/misc/anger3.wav" ); + } else { + if (TIMER_Done(NPC, "idlenoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/wampa/misc/anger3.wav"); - TIMER_Set( NPC, "idlenoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "idlenoise", Q_irand(2000, 4000)); } - if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Wampa_Patrol(); - } - else - { + } else { Wampa_Idle(); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/code/game/AnimalNPC.cpp b/code/game/AnimalNPC.cpp index 6b6aa54931..340c134fe7 100644 --- a/code/game/AnimalNPC.cpp +++ b/code/game/AnimalNPC.cpp @@ -20,11 +20,11 @@ along with this program; if not, see . =========================================================================== */ -//seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles -//or something, so the headers spew errors on these defs from the previous compile. -//this fixes that. -rww +// seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles +// or something, so the headers spew errors on these defs from the previous compile. +// this fixes that. -rww #ifdef _JK2MP -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins @@ -41,19 +41,19 @@ along with this program; if not, see . #undef MOD_EXPLOSIVE #endif -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif #endif -#ifndef _JK2MP //if single player -#ifndef QAGAME //I don't think we have a QAGAME define -#define QAGAME //but define it cause in sp we're always in the game +#ifndef _JK2MP // if single player +#ifndef QAGAME // I don't think we have a QAGAME define +#define QAGAME // but define it cause in sp we're always in the game #endif #endif -#ifdef QAGAME //including game headers on cgame is FORBIDDEN ^_^ +#ifdef QAGAME // including game headers on cgame is FORBIDDEN ^_^ #include "g_local.h" #elif defined _JK2MP #include "bg_public.h" @@ -68,8 +68,8 @@ along with this program; if not, see . #endif #ifdef _JK2MP -//this is really horrible, but it works! just be sure not to use any locals or anything -//with these names (exluding bool, false, true). -rww +// this is really horrible, but it works! just be sure not to use any locals or anything +// with these names (exluding bool, false, true). -rww #define currentAngles r.currentAngles #define currentOrigin r.currentOrigin #define mins r.mins @@ -90,113 +90,105 @@ along with this program; if not, see . #include "../cgame/cg_local.h" -#ifdef QAGAME //we only want a few of these functions for BG +#ifdef QAGAME // we only want a few of these functions for BG -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -extern vmCvar_t cg_thirdPersonAlpha; +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +extern vmCvar_t cg_thirdPersonAlpha; extern vec3_t playerMins; extern vec3_t playerMaxs; -extern cvar_t *g_speederControlScheme; +extern cvar_t *g_speederControlScheme; #ifdef _JK2MP #include "../namespace_begin.h" #endif -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); #ifdef _JK2MP #include "../namespace_end.h" #endif -#ifndef _JK2MP -extern void CG_ChangeWeapon( int num ); +#ifndef _JK2MP +extern void CG_ChangeWeapon(int num); #endif -extern void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); +extern void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); // Update death sequence. -static void DeathUpdate( Vehicle_t *pVeh ) -{ - if ( level.time >= pVeh->m_iDieTime ) - { +static void DeathUpdate(Vehicle_t *pVeh) { + if (level.time >= pVeh->m_iDieTime) { // If the vehicle is not empty. - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); - } - else - { + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); + } else { // Waste this sucker. } // Die now... -/* else - { - vec3_t mins, maxs, bottom; - trace_t trace; - - if ( pVeh->m_pVehicleInfo->explodeFX ) - { - G_PlayEffect( pVeh->m_pVehicleInfo->explodeFX, parent->currentOrigin ); - //trace down and place mark - VectorCopy( parent->currentOrigin, bottom ); - bottom[2] -= 80; - gi.trace( &trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); - if ( trace.fraction < 1.0f ) + /* else { - VectorCopy( trace.endpos, bottom ); - bottom[2] += 2; - G_PlayEffect( "ships/ship_explosion_mark", trace.endpos ); - } - } + vec3_t mins, maxs, bottom; + trace_t trace; - parent->takedamage = qfalse;//so we don't recursively damage ourselves - if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) - { - VectorCopy( parent->mins, mins ); - mins[2] = -4;//to keep it off the ground a *little* - VectorCopy( parent->maxs, maxs ); - VectorCopy( parent->currentOrigin, bottom ); - bottom[2] += parent->mins[2] - 32; - gi.trace( &trace, parent->currentOrigin, mins, maxs, bottom, parent->s.number, CONTENTS_SOLID ); - G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, MOD_EXPLOSIVE );//FIXME: extern damage and radius or base on fuel - } + if ( pVeh->m_pVehicleInfo->explodeFX ) + { + G_PlayEffect( pVeh->m_pVehicleInfo->explodeFX, parent->currentOrigin ); + //trace down and place mark + VectorCopy( parent->currentOrigin, bottom ); + bottom[2] -= 80; + gi.trace( &trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); + if ( trace.fraction < 1.0f ) + { + VectorCopy( trace.endpos, bottom ); + bottom[2] += 2; + G_PlayEffect( "ships/ship_explosion_mark", trace.endpos ); + } + } - parent->e_ThinkFunc = thinkF_G_FreeEntity; - parent->nextthink = level.time + FRAMETIME; - }*/ + parent->takedamage = qfalse;//so we don't recursively damage ourselves + if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) + { + VectorCopy( parent->mins, mins ); + mins[2] = -4;//to keep it off the ground a *little* + VectorCopy( parent->maxs, maxs ); + VectorCopy( parent->currentOrigin, bottom ); + bottom[2] += parent->mins[2] - 32; + gi.trace( &trace, parent->currentOrigin, mins, maxs, bottom, parent->s.number, CONTENTS_SOLID ); + G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, MOD_EXPLOSIVE + );//FIXME: extern damage and radius or base on fuel + } + + parent->e_ThinkFunc = thinkF_G_FreeEntity; + parent->nextthink = level.time + FRAMETIME; + }*/ } } // Like a think or move command, this updates various vehicle properties. -static bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ - return g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ); -} -#endif //QAGAME +static bool Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { return g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd); } +#endif // QAGAME #ifdef _JK2MP #include "../namespace_begin.h" #endif -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations - float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */speedMin, speedMax; + // Client sets ucmds and such for speed alterations + float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */ speedMin, speedMax; float fWalkSpeedMax; - int curTime; + int curTime; bgEntity_t *parent = pVeh->m_pParentEntity; #ifdef _JK2MP playerState_t *parentPS = parent->playerState; @@ -204,23 +196,21 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) playerState_t *parentPS = &parent->client->ps; #endif -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP curTime = level.time; -#elif defined QAGAME//MP GAME +#elif defined QAGAME // MP GAME curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif - -#ifndef _JK2MP //bad for prediction - fixme +#ifndef _JK2MP // bad for prediction - fixme // Bucking so we can't do anything. - if ( pVeh->m_ulFlags & VEH_BUCKING || pVeh->m_ulFlags & VEH_FLYING || pVeh->m_ulFlags & VEH_CRASHING ) - { -//#ifdef QAGAME //this was in Update above -// ((gentity_t *)parent)->client->ps.speed = 0; -//#endif + if (pVeh->m_ulFlags & VEH_BUCKING || pVeh->m_ulFlags & VEH_FLYING || pVeh->m_ulFlags & VEH_CRASHING) { + //#ifdef QAGAME //this was in Update above + // ((gentity_t *)parent)->client->ps.speed = 0; + //#endif parentPS->speed = 0; return; } @@ -229,100 +219,73 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedMax = pVeh->m_pVehicleInfo->speedMax; speedIdle = pVeh->m_pVehicleInfo->speedIdle; - //speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; + // speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; - - - if ( pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && - (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && pVeh->m_pVehicleInfo->turboSpeed ) - { - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if (pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && + pVeh->m_pVehicleInfo->turboSpeed) { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); -#ifndef _JK2MP //kill me now - if (pVeh->m_pVehicleInfo->soundTurbo) - { +#ifndef _JK2MP // kill me now + if (pVeh->m_pVehicleInfo->soundTurbo) { G_SoundIndexOnEnt(pVeh->m_pParentEntity, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo); } #endif - parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed + parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed } } - if ( curTime < pVeh->m_iTurboTime ) - { + if (curTime < pVeh->m_iTurboTime) { speedMax = pVeh->m_pVehicleInfo->turboSpeed; - } - else - { + } else { speedMax = pVeh->m_pVehicleInfo->speedMax; } #ifdef _JK2MP - if ( !parentPS->m_iVehicleNum ) + if (!parentPS->m_iVehicleNum) #else - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh)) #endif - {//drifts to a stop + { // drifts to a stop speedInc = speedIdle * pVeh->m_fTimeModifier; - VectorClear( parentPS->moveDir ); - //m_ucmd.forwardmove = 127; + VectorClear(parentPS->moveDir); + // m_ucmd.forwardmove = 127; parentPS->speed = 0; - } - else - { + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } - //pVeh->m_ucmd.rightmove = 0; + // pVeh->m_ucmd.rightmove = 0; /*if ( !pVeh->m_pVehicleInfo->strafePerc || (!g_speederControlScheme->value && !parent->s.number) ) @@ -332,16 +295,11 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) } fWalkSpeedMax = speedMax * 0.275f; - if ( curTime>pVeh->m_iTurboTime && (pVeh->m_ucmd.buttons & BUTTON_WALKING) && parentPS->speed > fWalkSpeedMax ) - { + if (curTime > pVeh->m_iTurboTime && (pVeh->m_ucmd.buttons & BUTTON_WALKING) && parentPS->speed > fWalkSpeedMax) { parentPS->speed = fWalkSpeedMax; - } - else if ( parentPS->speed > speedMax ) - { + } else if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } @@ -350,25 +308,23 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ bgEntity_t *parent = pVeh->m_pParentEntity; - playerState_t /**parentPS, */*riderPS; + playerState_t /**parentPS, */ *riderPS; #ifdef _JK2MP bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } #else @@ -376,123 +332,110 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #endif // Bucking so we can't do anything. -#ifndef _JK2MP //bad for prediction - fixme - if ( pVeh->m_ulFlags & VEH_BUCKING || pVeh->m_ulFlags & VEH_FLYING || pVeh->m_ulFlags & VEH_CRASHING ) - { +#ifndef _JK2MP // bad for prediction - fixme + if (pVeh->m_ulFlags & VEH_BUCKING || pVeh->m_ulFlags & VEH_FLYING || pVeh->m_ulFlags & VEH_CRASHING) { return; } #endif #ifdef _JK2MP - if ( !rider ) + if (!rider) #else - if ( !rider || !rider->client ) + if (!rider || !rider->client) #endif { rider = parent; } - - #ifdef _JK2MP parentPS = parent->playerState; riderPS = rider->playerState; #else - //parentPS = &parent->client->ps; + // parentPS = &parent->client->ps; riderPS = &rider->client->ps; #endif - if (rider) - { + if (rider) { #ifdef _JK2MP - float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { - float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*4.0f; //magic number hackery - if (s < 0.0f) - { - s = -s; - } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { - angDif = maxDif; - } - else if (angDif < -maxDif) - { - angDif = -maxDif; + float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); + if (parentPS && parentPS->speed) { + float s = parentPS->speed; + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 4.0f; // magic number hackery + if (s < 0.0f) { + s = -s; + } + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { + angDif = maxDif; + } else if (angDif < -maxDif) { + angDif = -maxDif; + } + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); - } #else pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; #endif } + /* speed = VectorLength( parentPS->velocity ); -/* speed = VectorLength( parentPS->velocity ); - - // If the player is the rider... - if ( rider->s.number < MAX_CLIENTS ) - {//FIXME: use the vehicle's turning stat in this calc - pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; - } - else - { - float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; - if ( !pVeh->m_pVehicleInfo->turnWhenStopped - && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? - {//can't turn when not moving - //FIXME: or ramp up to max turnSpeed? - turnSpeed = 0.0f; + // If the player is the rider... + if ( rider->s.number < MAX_CLIENTS ) + {//FIXME: use the vehicle's turning stat in this calc + pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; } -#ifdef _JK2MP - if (rider->s.eType == ET_NPC) -#else - if ( !rider || rider->NPC ) -#endif - {//help NPCs out some - turnSpeed *= 2.0f; -#ifdef _JK2MP - if (parentPS->speed > 200.0f) -#else - if ( parent->client->ps.speed > 200.0f ) -#endif - { - turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + else + { + float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; + if ( !pVeh->m_pVehicleInfo->turnWhenStopped + && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? + {//can't turn when not moving + //FIXME: or ramp up to max turnSpeed? + turnSpeed = 0.0f; } - } - turnSpeed *= pVeh->m_fTimeModifier; + #ifdef _JK2MP + if (rider->s.eType == ET_NPC) + #else + if ( !rider || rider->NPC ) + #endif + {//help NPCs out some + turnSpeed *= 2.0f; + #ifdef _JK2MP + if (parentPS->speed > 200.0f) + #else + if ( parent->client->ps.speed > 200.0f ) + #endif + { + turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + } + } + turnSpeed *= pVeh->m_fTimeModifier; - //default control scheme: strafing turns, mouselook aims - if ( pVeh->m_ucmd.rightmove < 0 ) - { - pVeh->m_vOrientation[YAW] += turnSpeed; - } - else if ( pVeh->m_ucmd.rightmove > 0 ) - { - pVeh->m_vOrientation[YAW] -= turnSpeed; - } + //default control scheme: strafing turns, mouselook aims + if ( pVeh->m_ucmd.rightmove < 0 ) + { + pVeh->m_vOrientation[YAW] += turnSpeed; + } + else if ( pVeh->m_ucmd.rightmove > 0 ) + { + pVeh->m_vOrientation[YAW] -= turnSpeed; + } - if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) - {//damaged badly - } - }*/ + if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) + {//damaged badly + } + }*/ /********************************************************************************/ /* END Here is where make sure the vehicle is properly oriented. END */ /********************************************************************************/ } -#ifdef _JK2MP //temp hack til mp speeder controls are sorted -rww -void AnimalProcessOri(Vehicle_t *pVeh) -{ - ProcessOrientCommands(pVeh); -} +#ifdef _JK2MP // temp hack til mp speeder controls are sorted -rww +void AnimalProcessOri(Vehicle_t *pVeh) { ProcessOrientCommands(pVeh); } #endif -#ifdef QAGAME //back to our game-only functions +#ifdef QAGAME // back to our game-only functions // This function makes sure that the vehicle is properly animated. /* static void AnimalTailSwipe(Vehicle_t* pVeh, gentity_t *parent, gentity_t *pilot) @@ -599,88 +542,73 @@ static void AnimalTailSwipe(Vehicle_t* pVeh, gentity_t *parent, gentity_t *pilot }// Trace Hit Anything? } */ -static void AnimateVehicle( Vehicle_t *pVeh ) -{ - animNumber_t Anim = BOTH_VT_IDLE; - int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; - gentity_t * pilot = (gentity_t *)pVeh->m_pPilot; - gentity_t * parent = (gentity_t *)pVeh->m_pParentEntity; - //playerState_t * pilotPS; - //playerState_t * parentPS; - float fSpeedPercToMax; +static void AnimateVehicle(Vehicle_t *pVeh) { + animNumber_t Anim = BOTH_VT_IDLE; + int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; + gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; + gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; + // playerState_t * pilotPS; + // playerState_t * parentPS; + float fSpeedPercToMax; #ifdef _JK2MP - pilotPS = (pilot)?(pilot->playerState):(0); + pilotPS = (pilot) ? (pilot->playerState) : (0); parentPS = parent->playerState; #else - //pilotPS = (pilot)?(&pilot->client->ps):(0); - //parentPS = &parent->client->ps; + // pilotPS = (pilot)?(&pilot->client->ps):(0); + // parentPS = &parent->client->ps; #endif // We're dead (boarding is reused here so I don't have to make another variable :-). - if ( parent->health <= 0 ) - { - if ( pVeh->m_iBoarding != -999 ) // Animate the death just once! + if (parent->health <= 0) { + if (pVeh->m_iBoarding != -999) // Animate the death just once! { pVeh->m_iBoarding = -999; iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; // FIXME! Why do you keep repeating over and over!!?!?!? Bastard! - //Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_DEATH1, iFlags, iBlend ); + // Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_DEATH1, iFlags, iBlend ); } return; } // If they're bucking, play the animation and leave... - if ( parent->client->ps.legsAnim == BOTH_VT_BUCK ) - { + if (parent->client->ps.legsAnim == BOTH_VT_BUCK) { // Done with animation? Erase the flag. - if ( parent->client->ps.legsAnimTimer <= 0 ) - { + if (parent->client->ps.legsAnimTimer <= 0) { pVeh->m_ulFlags &= ~VEH_BUCKING; - } - else - { + } else { return; } - } - else if ( pVeh->m_ulFlags & VEH_BUCKING ) - { + } else if (pVeh->m_ulFlags & VEH_BUCKING) { iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; Anim = BOTH_VT_BUCK; iBlend = 500; - Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_BUCK, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, BOTH_VT_BUCK, iFlags, iBlend); return; } // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { // We've just started boarding, set the amount of time it will take to finish boarding. - if ( pVeh->m_iBoarding < 0 ) - { + if (pVeh->m_iBoarding < 0) { int iAnimLen; // Boarding from left... - if ( pVeh->m_iBoarding == -1 ) - { + if (pVeh->m_iBoarding == -1) { Anim = BOTH_VT_MOUNT_L; - } - else if ( pVeh->m_iBoarding == -2 ) - { + } else if (pVeh->m_iBoarding == -2) { Anim = BOTH_VT_MOUNT_R; - } - else if ( pVeh->m_iBoarding == -3 ) - { + } else if (pVeh->m_iBoarding == -3) { Anim = BOTH_VT_MOUNT_B; } // Set the delay time (which happens to be the time it takes for the animation to complete). // NOTE: Here I made it so the delay is actually 70% (0.7f) of the animation time. #ifdef _JK2MP - iAnimLen = BG_AnimLength( parent->localAnimIndex, Anim ) * 0.7f; + iAnimLen = BG_AnimLength(parent->localAnimIndex, Anim) * 0.7f; #else - iAnimLen = PM_AnimLength( parent->client->clientInfo.animFileIndex, Anim ) * 0.7f; + iAnimLen = PM_AnimLength(parent->client->clientInfo.animFileIndex, Anim) * 0.7f; #endif pVeh->m_iBoarding = level.time + iAnimLen; @@ -688,136 +616,119 @@ static void AnimateVehicle( Vehicle_t *pVeh ) // TODO: But what if he's killed? Should the animation remain persistant??? iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); - if (pilot) - { - Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); + if (pilot) { + Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend); } return; } // Otherwise we're done. - else if ( pVeh->m_iBoarding <= level.time ) - { + else if (pVeh->m_iBoarding <= level.time) { pVeh->m_iBoarding = 0; } } // Percentage of maximum speed relative to current speed. - //float fSpeed = VectorLength( client->ps.velocity ); + // float fSpeed = VectorLength( client->ps.velocity ); fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; - // Going in reverse... - if ( fSpeedPercToMax < -0.01f ) - { + if (fSpeedPercToMax < -0.01f) { Anim = BOTH_VT_WALK_REV; iBlend = 600; - } - else - { - bool Turbo = (fSpeedPercToMax>0.0f && level.timem_iTurboTime); - bool Walking = (fSpeedPercToMax>0.0f && ((pVeh->m_ucmd.buttons&BUTTON_WALKING) || fSpeedPercToMax<=0.275f)); - bool Running = (fSpeedPercToMax>0.275f); - + } else { + bool Turbo = (fSpeedPercToMax > 0.0f && level.time < pVeh->m_iTurboTime); + bool Walking = (fSpeedPercToMax > 0.0f && ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax <= 0.275f)); + bool Running = (fSpeedPercToMax > 0.275f); // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - if (Turbo) - {// Kicked In Turbo - iBlend = 50; - iFlags = SETANIM_FLAG_OVERRIDE; - Anim = BOTH_VT_TURBO; - } - else - {// No Special Moves - iBlend = 300; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - Anim = (Walking)?(BOTH_VT_WALK_FWD ):((Running)?(BOTH_VT_RUN_FWD ):(BOTH_VT_IDLE1)); + if (Turbo) { // Kicked In Turbo + iBlend = 50; + iFlags = SETANIM_FLAG_OVERRIDE; + Anim = BOTH_VT_TURBO; + } else { // No Special Moves + iBlend = 300; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + Anim = (Walking) ? (BOTH_VT_WALK_FWD) : ((Running) ? (BOTH_VT_RUN_FWD) : (BOTH_VT_IDLE1)); } } - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); } -//rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful -//and lagged -// This function makes sure that the rider's in this vehicle are properly animated. -static void AnimateRiders( Vehicle_t *pVeh ) -{ +// rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful +// and lagged +// This function makes sure that the rider's in this vehicle are properly animated. +static void AnimateRiders(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_VT_IDLE; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 500; gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; playerState_t *pilotPS; - //playerState_t *parentPS; + // playerState_t *parentPS; float fSpeedPercToMax; #ifdef _JK2MP pilotPS = pVeh->m_pPilot->playerState; - //parentPS = pVeh->m_pPilot->playerState; + // parentPS = pVeh->m_pPilot->playerState; #else pilotPS = &pVeh->m_pPilot->client->ps; - //parentPS = &pVeh->m_pParentEntity->client->ps; + // parentPS = &pVeh->m_pParentEntity->client->ps; #endif // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { return; } // Percentage of maximum speed relative to current speed. fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; -/* // Going in reverse... -#ifdef _JK2MP //handled in pmove in mp - if (0) -#else - if ( fSpeedPercToMax < -0.01f ) -#endif - { - Anim = BOTH_VT_WALK_REV; - iBlend = 600; - bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - if (HasWeapon) + /* // Going in reverse... + #ifdef _JK2MP //handled in pmove in mp + if (0) + #else + if ( fSpeedPercToMax < -0.01f ) + #endif { - if (pVeh->m_pPilot->s.numberweapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + if (HasWeapon) { - CG_ChangeWeapon(WP_NONE); - } + if (pVeh->m_pPilot->s.numberm_pPilot->client->ps.weapon = WP_NONE; - G_RemoveWeaponModels(pVeh->m_pPilot); + pVeh->m_pPilot->client->ps.weapon = WP_NONE; + G_RemoveWeaponModels(pVeh->m_pPilot); + } } - } - else -*/ + else + */ { - bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - bool Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons&BUTTON_ATTACK)); - bool Right = (pVeh->m_ucmd.rightmove>0); - bool Left = (pVeh->m_ucmd.rightmove<0); - bool Turbo = (fSpeedPercToMax>0.0f && level.timem_iTurboTime); - bool Walking = (fSpeedPercToMax>0.0f && ((pVeh->m_ucmd.buttons&BUTTON_WALKING) || fSpeedPercToMax<=0.275f)); - bool Running = (fSpeedPercToMax>0.275f); - EWeaponPose WeaponPose = WPOSE_NONE; - + bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + bool Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons & BUTTON_ATTACK)); + bool Right = (pVeh->m_ucmd.rightmove > 0); + bool Left = (pVeh->m_ucmd.rightmove < 0); + bool Turbo = (fSpeedPercToMax > 0.0f && level.time < pVeh->m_iTurboTime); + bool Walking = (fSpeedPercToMax > 0.0f && ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax <= 0.275f)); + bool Running = (fSpeedPercToMax > 0.275f); + EWeaponPose WeaponPose = WPOSE_NONE; // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - // Put Away Saber When It Is Not Active //-------------------------------------- #ifndef _JK2MP - if (HasWeapon && - (pVeh->m_pPilot->s.number>=MAX_CLIENTS || (cg.weaponSelectTime+500)weapon==WP_SABER && (Turbo || !pilotPS->SaberActive()))) - { - if (pVeh->m_pPilot->s.numberm_pPilot->s.number >= MAX_CLIENTS || (cg.weaponSelectTime + 500) < cg.time) && + (pilotPS->weapon == WP_SABER && (Turbo || !pilotPS->SaberActive()))) { + if (pVeh->m_pPilot->s.number < MAX_CLIENTS) { CG_ChangeWeapon(WP_NONE); } @@ -829,19 +740,16 @@ static void AnimateRiders( Vehicle_t *pVeh ) // Don't Interrupt Attack Anims //------------------------------ #ifdef _JK2MP - if (pilotPS->weaponTime>0) - { + if (pilotPS->weaponTime > 0) { return; } #else - if (pilotPS->torsoAnim>=BOTH_VT_ATL_S && pilotPS->torsoAnim<=BOTH_VT_ATF_G) - { - float bodyCurrent = 0.0f; - int bodyEnd = 0; - if (!!gi.G2API_GetBoneAnimIndex(&pVeh->m_pPilot->ghoul2[pVeh->m_pPilot->playerModel], pVeh->m_pPilot->rootBone, level.time, &bodyCurrent, NULL, &bodyEnd, NULL, NULL, NULL)) - { - if (bodyCurrent<=((float)(bodyEnd)-1.5f)) - { + if (pilotPS->torsoAnim >= BOTH_VT_ATL_S && pilotPS->torsoAnim <= BOTH_VT_ATF_G) { + float bodyCurrent = 0.0f; + int bodyEnd = 0; + if (!!gi.G2API_GetBoneAnimIndex(&pVeh->m_pPilot->ghoul2[pVeh->m_pPilot->playerModel], pVeh->m_pPilot->rootBone, level.time, &bodyCurrent, NULL, + &bodyEnd, NULL, NULL, NULL)) { + if (bodyCurrent <= ((float)(bodyEnd)-1.5f)) { return; } } @@ -850,180 +758,167 @@ static void AnimateRiders( Vehicle_t *pVeh ) // Compute The Weapon Pose //-------------------------- - if (pilotPS->weapon==WP_BLASTER) - { + if (pilotPS->weapon == WP_BLASTER) { WeaponPose = WPOSE_BLASTER; - } - else if (pilotPS->weapon==WP_SABER) - { - if ( (pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VT_ATL_TO_R_S) - { - pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; + } else if (pilotPS->weapon == WP_SABER) { + if ((pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VT_ATL_TO_R_S) { + pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; } - if (!(pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VT_ATR_TO_L_S) - { - pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; + if (!(pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VT_ATR_TO_L_S) { + pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; } - WeaponPose = (pVeh->m_ulFlags&VEH_SABERINLEFTHAND)?(WPOSE_SABERLEFT):(WPOSE_SABERRIGHT); + WeaponPose = (pVeh->m_ulFlags & VEH_SABERINLEFTHAND) ? (WPOSE_SABERLEFT) : (WPOSE_SABERRIGHT); } + if (Attacking && WeaponPose) { // Attack! + iBlend = 100; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART; - if (Attacking && WeaponPose) - {// Attack! - iBlend = 100; - iFlags = SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART; - - if (Turbo) - { + if (Turbo) { Right = true; Left = false; } // Auto Aiming //=============================================== - if (!Left && !Right) // Allow player strafe keys to override + if (!Left && !Right) // Allow player strafe keys to override { #ifndef _JK2MP - if (pVeh->m_pPilot->enemy) - { - vec3_t toEnemy; - //float toEnemyDistance; - vec3_t actorRight; - float actorRightDot; + if (pVeh->m_pPilot->enemy) { + vec3_t toEnemy; + // float toEnemyDistance; + vec3_t actorRight; + float actorRightDot; VectorSubtract(pVeh->m_pPilot->currentOrigin, pVeh->m_pPilot->enemy->currentOrigin, toEnemy); - /*toEnemyDistance = */VectorNormalize(toEnemy); + /*toEnemyDistance = */ VectorNormalize(toEnemy); AngleVectors(pVeh->m_pParentEntity->currentAngles, 0, actorRight, 0); actorRightDot = DotProduct(toEnemy, actorRight); - if (fabsf(actorRightDot)>0.5f || pilotPS->weapon==WP_SABER) - { - Left = (actorRightDot>0.0f); - Right = !Left; - } - else - { + if (fabsf(actorRightDot) > 0.5f || pilotPS->weapon == WP_SABER) { + Left = (actorRightDot > 0.0f); + Right = !Left; + } else { Right = Left = false; } - } - else + } else #endif - if (pilotPS->weapon==WP_SABER && !Left && !Right) - { - Left = (WeaponPose==WPOSE_SABERLEFT); - Right = !Left; + if (pilotPS->weapon == WP_SABER && !Left && !Right) { + Left = (WeaponPose == WPOSE_SABERLEFT); + Right = !Left; } } - - if (Left) - {// Attack Left - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_ATL_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_ATR_TO_L_S; break; - default: assert(0); + if (Left) { // Attack Left + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_ATL_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_ATR_TO_L_S; + break; + default: + assert(0); } - } - else if (Right) - {// Attack Right - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_ATL_TO_R_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_ATR_S; break; - default: assert(0); + } else if (Right) { // Attack Right + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_ATL_TO_R_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_ATR_S; + break; + default: + assert(0); } - } - else - {// Attack Ahead - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATF_G; break; - default: assert(0); + } else { // Attack Ahead + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATF_G; + break; + default: + assert(0); } } - } - else if (Turbo) - {// Kicked In Turbo - iBlend = 50; - iFlags = SETANIM_FLAG_OVERRIDE; - Anim = BOTH_VT_TURBO; - } - else - {// No Special Moves - iBlend = 300; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - if (WeaponPose==WPOSE_NONE) - { - if (Walking) - { + } else if (Turbo) { // Kicked In Turbo + iBlend = 50; + iFlags = SETANIM_FLAG_OVERRIDE; + Anim = BOTH_VT_TURBO; + } else { // No Special Moves + iBlend = 300; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + if (WeaponPose == WPOSE_NONE) { + if (Walking) { Anim = BOTH_VT_WALK_FWD; - } - else if (Running) - { + } else if (Running) { Anim = BOTH_VT_RUN_FWD; + } else { + Anim = BOTH_VT_IDLE1; //(Q_irand(0,1)==0)?(BOTH_VT_IDLE):(BOTH_VT_IDLE1); } - else - { - Anim = BOTH_VT_IDLE1;//(Q_irand(0,1)==0)?(BOTH_VT_IDLE):(BOTH_VT_IDLE1); + } else { + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_IDLE_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_IDLE_SR; + break; + default: + assert(0); } } - else - { - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_IDLE_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_IDLE_SR; break; - default: assert(0); - } - } - }// No Special Moves + } // No Special Moves } - Vehicle_SetAnim( pilot, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend); } -#endif //QAGAME +#endif // QAGAME #ifndef QAGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -//on the client this function will only set up the process command funcs -void G_SetAnimalVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +// on the client this function will only set up the process command funcs +void G_SetAnimalVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef QAGAME - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; -// pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; - pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + // pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; -#endif //QAGAME - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; +#endif // QAGAME + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef QAGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef QAGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -1040,27 +935,25 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -//this is a BG function too in MP so don't un-bg-compatibilify it -rww -void G_CreateAnimalNPC( Vehicle_t **pVeh, const char *strAnimalType ) -{ +// this is a BG function too in MP so don't un-bg-compatibilify it -rww +void G_CreateAnimalNPC(Vehicle_t **pVeh, const char *strAnimalType) { // Allocate the Vehicle. #ifdef _JK2MP #ifdef QAGAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; #else - (*pVeh) = (Vehicle_t *) gi.Malloc( sizeof(Vehicle_t), TAG_G_ALLOC, qtrue ); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh) = (Vehicle_t *)gi.Malloc(sizeof(Vehicle_t), TAG_G_ALLOC, qtrue); + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; #endif } @@ -1068,7 +961,7 @@ void G_CreateAnimalNPC( Vehicle_t **pVeh, const char *strAnimalType ) #include "../namespace_end.h" -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins diff --git a/code/game/FighterNPC.cpp b/code/game/FighterNPC.cpp index dfab7bd2af..1ffa30c706 100644 --- a/code/game/FighterNPC.cpp +++ b/code/game/FighterNPC.cpp @@ -20,11 +20,11 @@ along with this program; if not, see . =========================================================================== */ -//seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles -//or something, so the headers spew errors on these defs from the previous compile. -//this fixes that. -rww +// seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles +// or something, so the headers spew errors on these defs from the previous compile. +// this fixes that. -rww #ifdef _JK2MP -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins @@ -41,19 +41,19 @@ along with this program; if not, see . #undef MOD_EXPLOSIVE #endif -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif #endif -#ifndef _JK2MP //if single player -#ifndef QAGAME //I don't think we have a QAGAME define -#define QAGAME //but define it cause in sp we're always in the game +#ifndef _JK2MP // if single player +#ifndef QAGAME // I don't think we have a QAGAME define +#define QAGAME // but define it cause in sp we're always in the game #endif #endif -#ifdef QAGAME //including game headers on cgame is FORBIDDEN ^_^ +#ifdef QAGAME // including game headers on cgame is FORBIDDEN ^_^ #include "g_local.h" #elif defined _JK2MP #include "bg_public.h" @@ -67,8 +67,8 @@ along with this program; if not, see . #endif #ifdef _JK2MP -//this is really horrible, but it works! just be sure not to use any locals or anything -//with these names (exluding bool, false, true). -rww +// this is really horrible, but it works! just be sure not to use any locals or anything +// with these names (exluding bool, false, true). -rww #define currentAngles r.currentAngles #define currentOrigin r.currentOrigin #define mins r.mins @@ -87,84 +87,76 @@ along with this program; if not, see . #define bgEntity_t gentity_t #endif -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -#ifdef QAGAME //SP or gameside MP -extern vmCvar_t cg_thirdPersonAlpha; +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +#ifdef QAGAME // SP or gameside MP +extern vmCvar_t cg_thirdPersonAlpha; extern vec3_t playerMins; extern vec3_t playerMaxs; -extern cvar_t *g_speederControlScheme; -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); +extern cvar_t *g_speederControlScheme; +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); #endif -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); #ifdef _JK2MP #include "../namespace_begin.h" -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags, int blendTime); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags, int blendTime); extern int BG_GetTime(void); #endif #include "b_local.h" -extern void BG_ExternThisSoICanRecompileInDebug( Vehicle_t *pVeh, playerState_t *riderPS ); +extern void BG_ExternThisSoICanRecompileInDebug(Vehicle_t *pVeh, playerState_t *riderPS); -//this stuff has got to be predicted, so.. +// this stuff has got to be predicted, so.. bool BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins, vec3_t trMaxs, float gravity, - void (*traceFunc)( trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, int passEntityNum, int contentMask )) -{ - vec3_t bottom; + void (*traceFunc)(trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, int passEntityNum, + int contentMask)) { + vec3_t bottom; playerState_t *parentPS; - //qboolean isDead = qfalse; -#ifdef QAGAME //don't do this on client + // qboolean isDead = qfalse; +#ifdef QAGAME // don't do this on client // Make sure the riders are not visible or collidable. - pVeh->m_pVehicleInfo->Ghost( pVeh, pVeh->m_pPilot ); + pVeh->m_pVehicleInfo->Ghost(pVeh, pVeh->m_pPilot); #endif - #ifdef _JK2MP parentPS = pVeh->m_pParentEntity->playerState; #else parentPS = &pVeh->m_pParentEntity->client->ps; #endif - if (!parentPS) - { + if (!parentPS) { Com_Error(ERR_DROP, "NULL PS in BG_FighterUpdate (%s)", pVeh->m_pVehicleInfo->name); return false; } // If we have a pilot, take out gravity (it's a flying craft...). - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { parentPS->gravity = 0; -#ifndef _JK2MP //don't need this flag in mp, I.. guess +#ifndef _JK2MP // don't need this flag in mp, I.. guess pVeh->m_pParentEntity->svFlags |= SVF_CUSTOM_GRAVITY; #endif - } - else - { -#ifndef _JK2MP //don't need this flag in mp, I.. guess + } else { +#ifndef _JK2MP // don't need this flag in mp, I.. guess pVeh->m_pParentEntity->svFlags &= ~SVF_CUSTOM_GRAVITY; -#else //in MP set grav back to normal gravity - if (pVeh->m_pVehicleInfo->gravity) - { +#else // in MP set grav back to normal gravity + if (pVeh->m_pVehicleInfo->gravity) { parentPS->gravity = pVeh->m_pVehicleInfo->gravity; - } - else - { //it doesn't have gravity specified apparently + } else { // it doesn't have gravity specified apparently parentPS->gravity = gravity; } #endif } #ifdef _JK2MP - //isDead = (qboolean)((parentPS->eFlags&EF_DEAD)!=0); + // isDead = (qboolean)((parentPS->eFlags&EF_DEAD)!=0); #else - //isDead = (parentPS->stats[STAT_HEALTH] <= 0 ); + // isDead = (parentPS->stats[STAT_HEALTH] <= 0 ); #endif /* @@ -181,38 +173,34 @@ bool BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins, ve else { */ - //argh, no, I need to have a way to see when they impact the ground while damaged. -rww + // argh, no, I need to have a way to see when they impact the ground while damaged. -rww - // Check to see if the fighter has taken off yet (if it's a certain height above ground). - VectorCopy( parentPS->origin, bottom ); - bottom[2] -= pVeh->m_pVehicleInfo->landingHeight; + // Check to see if the fighter has taken off yet (if it's a certain height above ground). + VectorCopy(parentPS->origin, bottom); + bottom[2] -= pVeh->m_pVehicleInfo->landingHeight; - traceFunc( &pVeh->m_LandTrace, parentPS->origin, trMins, trMaxs, bottom, pVeh->m_pParentEntity->s.number, (MASK_NPCSOLID&~CONTENTS_BODY) ); + traceFunc(&pVeh->m_LandTrace, parentPS->origin, trMins, trMaxs, bottom, pVeh->m_pParentEntity->s.number, (MASK_NPCSOLID & ~CONTENTS_BODY)); //} return true; } -#ifdef QAGAME //ONLY in SP or on server, not cgame +#ifdef QAGAME // ONLY in SP or on server, not cgame // Like a think or move command, this updates various vehicle properties. -static bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ +static bool Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { assert(pVeh->m_pParentEntity); - if (!BG_FighterUpdate(pVeh, pUcmd, ((gentity_t *)pVeh->m_pParentEntity)->mins, - ((gentity_t *)pVeh->m_pParentEntity)->maxs, + if (!BG_FighterUpdate(pVeh, pUcmd, ((gentity_t *)pVeh->m_pParentEntity)->mins, ((gentity_t *)pVeh->m_pParentEntity)->maxs, #ifdef _JK2MP - g_gravity.value, + g_gravity.value, #else - g_gravity->value, + g_gravity->value, #endif - G_VehicleTrace)) - { + G_VehicleTrace)) { return false; } - if ( !g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ) ) - { + if (!g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd)) { return false; } @@ -220,9 +208,8 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) } // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -static bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Board( pVeh, pEnt ) ) +static bool Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { + if (!g_vehicleInfo[VEHICLE_BASE].Board(pVeh, pEnt)) return false; // Set the board wait time (they won't be able to do anything, including getting off, for this amount of time). @@ -232,50 +219,40 @@ static bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) } // Eject an entity from the vehicle. -static bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) -{ - if ( g_vehicleInfo[VEHICLE_BASE].Eject( pVeh, pEnt, forceEject ) ) - { +static bool Eject(Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject) { + if (g_vehicleInfo[VEHICLE_BASE].Eject(pVeh, pEnt, forceEject)) { return true; } return false; } -#endif //end game-side only +#endif // end game-side only -//method of decrementing the given angle based on the given taking variable frame times into account -static float PredictedAngularDecrement(float scale, float timeMod, float originalAngle) -{ - float fixedBaseDec = originalAngle*0.05f; +// method of decrementing the given angle based on the given taking variable frame times into account +static float PredictedAngularDecrement(float scale, float timeMod, float originalAngle) { + float fixedBaseDec = originalAngle * 0.05f; float r = 0.0f; - if (fixedBaseDec < 0.0f) - { + if (fixedBaseDec < 0.0f) { fixedBaseDec = -fixedBaseDec; } - fixedBaseDec *= (1.0f+(1.0f-scale)); + fixedBaseDec *= (1.0f + (1.0f - scale)); - if (fixedBaseDec < 0.1f) - { //don't increment in incredibly small fractions, it would eat up unnecessary bandwidth. + if (fixedBaseDec < 0.1f) { // don't increment in incredibly small fractions, it would eat up unnecessary bandwidth. fixedBaseDec = 0.1f; } - fixedBaseDec *= (timeMod*0.1f); - if (originalAngle > 0.0f) - { //subtract - r = (originalAngle-fixedBaseDec); - if (r < 0.0f) - { + fixedBaseDec *= (timeMod * 0.1f); + if (originalAngle > 0.0f) { // subtract + r = (originalAngle - fixedBaseDec); + if (r < 0.0f) { r = 0.0f; } - } - else if (originalAngle < 0.0f) - { //add - r = (originalAngle+fixedBaseDec); - if (r > 0.0f) - { + } else if (originalAngle < 0.0f) { // add + r = (originalAngle + fixedBaseDec); + if (r > 0.0f) { r = 0.0f; } } @@ -283,79 +260,67 @@ static float PredictedAngularDecrement(float scale, float timeMod, float origina return r; } -#ifdef QAGAME//only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver -qboolean FighterIsInSpace( gentity_t *gParent ) -{ - if ( gParent - && gParent->client - && gParent->client->inSpaceIndex - && gParent->client->inSpaceIndex < ENTITYNUM_WORLD ) - { +#ifdef QAGAME // only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver +qboolean FighterIsInSpace(gentity_t *gParent) { + if (gParent && gParent->client && gParent->client->inSpaceIndex && gParent->client->inSpaceIndex < ENTITYNUM_WORLD) { return qtrue; } return qfalse; } #endif -qboolean FighterOverValidLandingSurface( Vehicle_t *pVeh ) -{ - if ( pVeh->m_LandTrace.fraction < 1.0f //ground present - && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE )//flat enough - //FIXME: also check for a certain surface flag ... "landing zones"? +qboolean FighterOverValidLandingSurface(Vehicle_t *pVeh) { + if (pVeh->m_LandTrace.fraction < 1.0f // ground present + && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE) // flat enough + // FIXME: also check for a certain surface flag ... "landing zones"? { return qtrue; } return qfalse; } -qboolean FighterIsLanded( Vehicle_t *pVeh, playerState_t *parentPS ) -{ - if ( FighterOverValidLandingSurface( pVeh ) - && !parentPS->speed )//stopped +qboolean FighterIsLanded(Vehicle_t *pVeh, playerState_t *parentPS) { + if (FighterOverValidLandingSurface(pVeh) && !parentPS->speed) // stopped { return qtrue; } return qfalse; } -qboolean FighterIsLanding( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +qboolean FighterIsLanding(Vehicle_t *pVeh, playerState_t *parentPS) { - if ( FighterOverValidLandingSurface( pVeh ) -#ifdef QAGAME//only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing + if (FighterOverValidLandingSurface(pVeh) +#ifdef QAGAME // only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing #endif - && (pVeh->m_ucmd.forwardmove < 0||pVeh->m_ucmd.upmove<0) //decelerating or holding crouch button - && parentPS->speed <= MIN_LANDING_SPEED )//going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast + && (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0) // decelerating or holding crouch button + && parentPS->speed <= MIN_LANDING_SPEED) // going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast { return qtrue; } return qfalse; } -qboolean FighterIsLaunching( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +qboolean FighterIsLaunching(Vehicle_t *pVeh, playerState_t *parentPS) { - if ( FighterOverValidLandingSurface( pVeh ) -#ifdef QAGAME//only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing + if (FighterOverValidLandingSurface(pVeh) +#ifdef QAGAME // only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing #endif - && pVeh->m_ucmd.upmove > 0 //trying to take off - && parentPS->speed <= 200.0f )//going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast + && pVeh->m_ucmd.upmove > 0 // trying to take off + && parentPS->speed <= 200.0f) // going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast { return qtrue; } return qfalse; } -qboolean FighterSuspended( Vehicle_t *pVeh, playerState_t *parentPS ) -{ -#ifdef QAGAME//only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver - if (!pVeh->m_pPilot//empty - && !parentPS->speed//not moving - && pVeh->m_ucmd.forwardmove <= 0//not trying to go forward for whatever reason - && pVeh->m_pParentEntity != NULL - && (((gentity_t *)pVeh->m_pParentEntity)->spawnflags&2) )//SUSPENDED spawnflag is on +qboolean FighterSuspended(Vehicle_t *pVeh, playerState_t *parentPS) { +#ifdef QAGAME // only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver + if (!pVeh->m_pPilot // empty + && !parentPS->speed // not moving + && pVeh->m_ucmd.forwardmove <= 0 // not trying to go forward for whatever reason + && pVeh->m_pParentEntity != NULL && (((gentity_t *)pVeh->m_pParentEntity)->spawnflags & 2)) // SUSPENDED spawnflag is on { return qtrue; } @@ -366,34 +331,33 @@ qboolean FighterSuspended( Vehicle_t *pVeh, playerState_t *parentPS ) } #ifdef CGAME -extern void trap_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); //cg_syscalls.c -extern sfxHandle_t trap_S_RegisterSound( const char *sample); //cg_syscalls.c +extern void trap_S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); // cg_syscalls.c +extern sfxHandle_t trap_S_RegisterSound(const char *sample); // cg_syscalls.c #endif -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. #define FIGHTER_MIN_TAKEOFF_FRACTION 0.7f -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations + // Client sets ucmds and such for speed alterations float speedInc, speedIdleDec, speedIdle, speedIdleAccel, speedMin, speedMax; bgEntity_t *parent = pVeh->m_pParentEntity; qboolean isLandingOrLaunching = qfalse; -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP int curTime = level.time; -#elif defined QAGAME//MP GAME +#elif defined QAGAME // MP GAME int curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... int curTime = pm->cmd.serverTime; #endif @@ -404,151 +368,127 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) #endif #ifdef _JK2MP - if ( parentPS->hyperSpaceTime - && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME ) - {//Going to Hyperspace - //totally override movement - float timeFrac = ((float)(curTime-parentPS->hyperSpaceTime))/HYPERSPACE_TIME; - if ( timeFrac < HYPERSPACE_TELEPORT_FRAC ) - {//for first half, instantly jump to top speed! - if ( !(parentPS->eFlags2&EF2_HYPERSPACE) ) - {//waiting to face the right direction, do nothing + if (parentPS->hyperSpaceTime && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME) { // Going to Hyperspace + // totally override movement + float timeFrac = ((float)(curTime - parentPS->hyperSpaceTime)) / HYPERSPACE_TIME; + if (timeFrac < HYPERSPACE_TELEPORT_FRAC) { // for first half, instantly jump to top speed! + if (!(parentPS->eFlags2 & EF2_HYPERSPACE)) { // waiting to face the right direction, do nothing parentPS->speed = 0.0f; - } - else - { - if ( parentPS->speed < HYPERSPACE_SPEED ) - {//just started hyperspace -//MIKE: This is going to play the sound twice for the predicting client, I suggest using -//a predicted event or only doing it game-side. -rich -#ifdef QAGAME//MP GAME-side - //G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); -#elif defined CGAME//MP CGAME-side - trap_S_StartSound( NULL, pm->ps->clientNum, CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); + } else { + if (parentPS->speed < HYPERSPACE_SPEED) { // just started hyperspace +// MIKE: This is going to play the sound twice for the predicting client, I suggest using +// a predicted event or only doing it game-side. -rich +#ifdef QAGAME // MP GAME-side + // G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); +#elif defined CGAME // MP CGAME-side + trap_S_StartSound(NULL, pm->ps->clientNum, CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper); #endif } parentPS->speed = HYPERSPACE_SPEED; } - } - else - {//slow from top speed to 200... - parentPS->speed = 200.0f + ((1.0f-timeFrac)*(1.0f/HYPERSPACE_TELEPORT_FRAC)*(HYPERSPACE_SPEED-200.0f)); - //don't mess with acceleration, just pop to the high velocity - if ( VectorLength( parentPS->velocity ) < parentPS->speed ) - { - VectorScale( parentPS->moveDir, parentPS->speed, parentPS->velocity ); + } else { // slow from top speed to 200... + parentPS->speed = 200.0f + ((1.0f - timeFrac) * (1.0f / HYPERSPACE_TELEPORT_FRAC) * (HYPERSPACE_SPEED - 200.0f)); + // don't mess with acceleration, just pop to the high velocity + if (VectorLength(parentPS->velocity) < parentPS->speed) { + VectorScale(parentPS->moveDir, parentPS->speed, parentPS->velocity); } } return; } #endif - if ( pVeh->m_iDropTime >= curTime ) - {//no speed, just drop + if (pVeh->m_iDropTime >= curTime) { // no speed, just drop parentPS->speed = 0.0f; parentPS->gravity = 800; return; } - isLandingOrLaunching = (qboolean)(FighterIsLanding( pVeh, parentPS )||FighterIsLaunching( pVeh, parentPS )); + isLandingOrLaunching = (qboolean)(FighterIsLanding(pVeh, parentPS) || FighterIsLaunching(pVeh, parentPS)); // If we are hitting the ground, just allow the fighter to go up and down. - if ( isLandingOrLaunching//going slow enough to start landing - && (pVeh->m_ucmd.forwardmove<=0||pVeh->m_LandTrace.fraction<=FIGHTER_MIN_TAKEOFF_FRACTION) )//not trying to accelerate away already (or: you are trying to, but not high enough off the ground yet) - {//FIXME: if start to move forward and fly over something low while still going relatively slow, you may try to land even though you don't mean to... - //float fInvFrac = 1.0f - pVeh->m_LandTrace.fraction; - - if ( pVeh->m_ucmd.upmove > 0 ) - { + if (isLandingOrLaunching // going slow enough to start landing + && (pVeh->m_ucmd.forwardmove <= 0 || + pVeh->m_LandTrace.fraction <= + FIGHTER_MIN_TAKEOFF_FRACTION)) // not trying to accelerate away already (or: you are trying to, but not high enough off the ground yet) + { // FIXME: if start to move forward and fly over something low while still going relatively slow, you may try to land even though you don't mean to... + // float fInvFrac = 1.0f - pVeh->m_LandTrace.fraction; + + if (pVeh->m_ucmd.upmove > 0) { #ifdef _JK2MP - if ( parentPS->velocity[2] <= 0 - && pVeh->m_pVehicleInfo->soundTakeOff ) - {//taking off for the first time -#ifdef QAGAME//MP GAME-side - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTakeOff ); + if (parentPS->velocity[2] <= 0 && pVeh->m_pVehicleInfo->soundTakeOff) { // taking off for the first time +#ifdef QAGAME // MP GAME-side + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTakeOff); #endif } #endif - parentPS->velocity[2] += pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier;// * ( /*fInvFrac **/ 1.5f ); - } - else if ( pVeh->m_ucmd.upmove < 0 ) - { - parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier;// * ( /*fInvFrac **/ 1.8f ); - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( pVeh->m_LandTrace.fraction != 0.0f ) - { + parentPS->velocity[2] += pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; // * ( /*fInvFrac **/ 1.5f ); + } else if (pVeh->m_ucmd.upmove < 0) { + parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; // * ( /*fInvFrac **/ 1.8f ); + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (pVeh->m_LandTrace.fraction != 0.0f) { parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( pVeh->m_LandTrace.fraction <= FIGHTER_MIN_TAKEOFF_FRACTION ) - { - //pVeh->m_pParentEntity->client->ps.velocity[0] *= pVeh->m_LandTrace.fraction; - //pVeh->m_pParentEntity->client->ps.velocity[1] *= pVeh->m_LandTrace.fraction; + if (pVeh->m_LandTrace.fraction <= FIGHTER_MIN_TAKEOFF_FRACTION) { + // pVeh->m_pParentEntity->client->ps.velocity[0] *= pVeh->m_LandTrace.fraction; + // pVeh->m_pParentEntity->client->ps.velocity[1] *= pVeh->m_LandTrace.fraction; - //remember to always base this stuff on the time modifier! otherwise, you create - //framerate-dependancy issues and break prediction in MP -rww - //parentPS->velocity[2] *= pVeh->m_LandTrace.fraction; - //it's not an angle, but hey - parentPS->velocity[2] = PredictedAngularDecrement(pVeh->m_LandTrace.fraction, pVeh->m_fTimeModifier*5.0f, parentPS->velocity[2]); + // remember to always base this stuff on the time modifier! otherwise, you create + // framerate-dependancy issues and break prediction in MP -rww + // parentPS->velocity[2] *= pVeh->m_LandTrace.fraction; + // it's not an angle, but hey + parentPS->velocity[2] = PredictedAngularDecrement(pVeh->m_LandTrace.fraction, pVeh->m_fTimeModifier * 5.0f, parentPS->velocity[2]); parentPS->speed = 0; } } // Make sure they don't pitch as they near the ground. - //pVeh->m_vOrientation[PITCH] *= 0.7f; - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.7f, pVeh->m_fTimeModifier*10.0f, pVeh->m_vOrientation[PITCH]); + // pVeh->m_vOrientation[PITCH] *= 0.7f; + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.7f, pVeh->m_fTimeModifier * 10.0f, pVeh->m_vOrientation[PITCH]); return; } - if ( (pVeh->m_ucmd.upmove > 0) && pVeh->m_pVehicleInfo->turboSpeed ) - { - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if ((pVeh->m_ucmd.upmove > 0) && pVeh->m_pVehicleInfo->turboSpeed) { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); - if (pVeh->m_pVehicleInfo->iTurboStartFX) - { + if (pVeh->m_pVehicleInfo->iTurboStartFX) { int i; - for (i=0; im_iExhaustTag[i]==-1) - { + for (i = 0; i < MAX_VEHICLE_EXHAUSTS; i++) { + if (pVeh->m_iExhaustTag[i] == -1) { break; } - #ifndef _JK2MP//SP - G_PlayEffect(pVeh->m_pVehicleInfo->iTurboStartFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin ); - #else - //TODO: MP Play Effect? - #endif +#ifndef _JK2MP // SP + G_PlayEffect(pVeh->m_pVehicleInfo->iTurboStartFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], + pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin); +#else + // TODO: MP Play Effect? +#endif } } - //NOTE: turbo sound can't be part of effect if effect is played on every muzzle! - if ( pVeh->m_pVehicleInfo->soundTurbo ) - { -#ifndef _JK2MP//SP - G_SoundIndexOnEnt( pVeh->m_pParentEntity, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo ); -#elif defined QAGAME//MP GAME-side - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo ); -#elif defined CGAME//MP CGAME-side - //trap_S_StartSound( NULL, pVeh->m_pParentEntity->s.number, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo ); + // NOTE: turbo sound can't be part of effect if effect is played on every muzzle! + if (pVeh->m_pVehicleInfo->soundTurbo) { +#ifndef _JK2MP // SP + G_SoundIndexOnEnt(pVeh->m_pParentEntity, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo); +#elif defined QAGAME // MP GAME-side + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo); +#elif defined CGAME // MP CGAME-side + // trap_S_StartSound( NULL, pVeh->m_pParentEntity->s.number, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo ); #endif } } } speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; - if ( curTime < pVeh->m_iTurboTime ) - {//going turbo speed + if (curTime < pVeh->m_iTurboTime) { // going turbo speed speedMax = pVeh->m_pVehicleInfo->turboSpeed; - //double our acceleration + // double our acceleration speedInc *= 2.0f; - //force us to move forward + // force us to move forward pVeh->m_ucmd.forwardmove = 127; -#ifdef _JK2MP//SP can cheat and just check m_iTurboTime directly... :) - //add flag to let cgame know to draw the iTurboFX effect +#ifdef _JK2MP // SP can cheat and just check m_iTurboTime directly... :) + // add flag to let cgame know to draw the iTurboFX effect parentPS->eFlags |= EF_JETPACK_ACTIVE; #endif } @@ -559,12 +499,10 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedMax = pVeh->m_pVehicleInfo->speedMax*0.75; } */ - else - {//normal max speed + else { // normal max speed speedMax = pVeh->m_pVehicleInfo->speedMax; -#ifdef _JK2MP//SP can cheat and just check m_iTurboTime directly... :) - if ( (parentPS->eFlags&EF_JETPACK_ACTIVE) ) - {//stop cgame from playing the turbo exhaust effect +#ifdef _JK2MP // SP can cheat and just check m_iTurboTime directly... :) + if ((parentPS->eFlags & EF_JETPACK_ACTIVE)) { // stop cgame from playing the turbo exhaust effect parentPS->eFlags &= ~EF_JETPACK_ACTIVE; } #endif @@ -574,331 +512,235 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; - if ( (parentPS->brokenLimbs&(1<brokenLimbs&(1<brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_HEAVY))) { // engine has taken heavy damage + speedMax *= 0.8f; // at 80% speed + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_LIGHT))) { // engine has taken light damage + speedMax *= 0.6f; // at 60% speed } - if (pVeh->m_iRemovedSurfaces - || parentPS->electrifyTime>=curTime) - { //go out of control + if (pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) { // go out of control parentPS->speed += speedInc; - //Why set forwardmove? PMove code doesn't use it... does it? + // Why set forwardmove? PMove code doesn't use it... does it? pVeh->m_ucmd.forwardmove = 127; } -#ifdef QAGAME //well, the thing is always going to be inhabited if it's being predicted! - else if ( FighterSuspended( pVeh, parentPS ) ) - { +#ifdef QAGAME // well, the thing is always going to be inhabited if it's being predicted! + else if (FighterSuspended(pVeh, parentPS)) { parentPS->speed = 0; pVeh->m_ucmd.forwardmove = 0; - } - else if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) - && parentPS->speed > 0 ) - {//pilot jumped out while we were moving forward (not landing or landed) so just keep the throttle locked - //Why set forwardmove? PMove code doesn't use it... does it? + } else if (!pVeh->m_pVehicleInfo->Inhabited(pVeh) && + parentPS->speed > 0) { // pilot jumped out while we were moving forward (not landing or landed) so just keep the throttle locked + // Why set forwardmove? PMove code doesn't use it... does it? pVeh->m_ucmd.forwardmove = 127; } #endif - else if ( ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) && pVeh->m_LandTrace.fraction >= 0.05f ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + else if ((parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) && + pVeh->m_LandTrace.fraction >= 0.05f) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; pVeh->m_ucmd.forwardmove = 127; - } - else if ( pVeh->m_ucmd.forwardmove < 0 - || pVeh->m_ucmd.upmove < 0 ) - {//decelerating or braking - if ( pVeh->m_ucmd.upmove < 0 ) - {//braking (trying to land?), slow down faster - if ( pVeh->m_ucmd.forwardmove ) - {//decelerator + brakes + } else if (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0) { // decelerating or braking + if (pVeh->m_ucmd.upmove < 0) { // braking (trying to land?), slow down faster + if (pVeh->m_ucmd.forwardmove) { // decelerator + brakes speedInc += pVeh->m_pVehicleInfo->braking; speedIdleDec += pVeh->m_pVehicleInfo->braking; - } - else - {//just brakes + } else { // just brakes speedInc = speedIdleDec = pVeh->m_pVehicleInfo->braking; } } - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { - if ( FighterOverValidLandingSurface( pVeh ) ) - {//there's ground below us and we're trying to slow down, slow down faster + } else if (parentPS->speed > speedMin) { + if (FighterOverValidLandingSurface(pVeh)) { // there's ground below us and we're trying to slow down, slow down faster parentPS->speed -= speedInc; - } - else - { + } else { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < MIN_LANDING_SPEED ) - {//unless you can land, don't drop below the landing speed!!! This way you can't come to a dead stop in mid-air + if (parentPS->speed < + MIN_LANDING_SPEED) { // unless you can land, don't drop below the landing speed!!! This way you can't come to a dead stop in mid-air parentPS->speed = MIN_LANDING_SPEED; } } } - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { pVeh->m_ucmd.forwardmove = 127; - } - else if ( speedMin >= 0 ) - { + } else if (speedMin >= 0) { pVeh->m_ucmd.forwardmove = 0; } } - //else not accel, decel or braking - else if ( pVeh->m_pVehicleInfo->throttleSticks ) - {//we're using a throttle that sticks at current speed - if ( parentPS->speed <= MIN_LANDING_SPEED ) - {//going less than landing speed - if ( FighterOverValidLandingSurface( pVeh ) ) - {//close to ground and not going very fast - //slow to a stop if within landing height and not accel/decel/braking - if ( parentPS->speed > 0 ) - {//slow down + // else not accel, decel or braking + else if (pVeh->m_pVehicleInfo->throttleSticks) { // we're using a throttle that sticks at current speed + if (parentPS->speed <= MIN_LANDING_SPEED) { // going less than landing speed + if (FighterOverValidLandingSurface(pVeh)) { // close to ground and not going very fast + // slow to a stop if within landing height and not accel/decel/braking + if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - } - else if ( parentPS->speed < 0 ) - {//going backwards, slow down + } else if (parentPS->speed < 0) { // going backwards, slow down parentPS->speed += speedIdleDec; } - } - else - {//not over a valid landing surf, but going too slow - //speed up to idle speed if not over a valid landing surf and not accel/decel/braking - if ( parentPS->speed < speedIdle ) - { + } else { // not over a valid landing surf, but going too slow + // speed up to idle speed if not over a valid landing surf and not accel/decel/braking + if (parentPS->speed < speedIdle) { parentPS->speed += speedIdleAccel; - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed = speedIdle; } } } } - } - else - {//then speed up or slow down to idle speed - //accelerate to cruising speed only, otherwise, just coast - // If they've launched, apply some constant motion. - if ( (pVeh->m_LandTrace.fraction >= 1.0f //no ground - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE )//or can't land on ground below us - && speedIdle > 0 ) - {//not above ground and have an idle speed - //float fSpeed = pVeh->m_pParentEntity->client->ps.speed; - if ( parentPS->speed < speedIdle ) - { + } else { // then speed up or slow down to idle speed + // accelerate to cruising speed only, otherwise, just coast + // If they've launched, apply some constant motion. + if ((pVeh->m_LandTrace.fraction >= 1.0f // no ground + || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) // or can't land on ground below us + && speedIdle > 0) { // not above ground and have an idle speed + // float fSpeed = pVeh->m_pParentEntity->client->ps.speed; + if (parentPS->speed < speedIdle) { parentPS->speed += speedIdleAccel; - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed = speedIdle; } - } - else if ( parentPS->speed > 0 ) - {//slow down + } else if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - if ( parentPS->speed < speedIdle ) - { + if (parentPS->speed < speedIdle) { parentPS->speed = speedIdle; } } - } - else//either close to ground or no idle speed - {//slow to a stop if no idle speed or within landing height and not accel/decel/braking - if ( parentPS->speed > 0 ) - {//slow down + } else // either close to ground or no idle speed + { // slow to a stop if no idle speed or within landing height and not accel/decel/braking + if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - } - else if ( parentPS->speed < 0 ) - {//going backwards, slow down + } else if (parentPS->speed < 0) { // going backwards, slow down parentPS->speed += speedIdleDec; } } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } #ifndef _JK2MP - if ( !pVeh->m_pVehicleInfo->strafePerc || (!g_speederControlScheme->value && !pVeh->m_pParentEntity->s.number) ) - {//if in a strafe-capable vehicle, clear strafing unless using alternate control scheme + if (!pVeh->m_pVehicleInfo->strafePerc || + (!g_speederControlScheme->value && + !pVeh->m_pParentEntity->s.number)) { // if in a strafe-capable vehicle, clear strafing unless using alternate control scheme pVeh->m_ucmd.rightmove = 0; } #endif } -#if 1//This is working now, but there are some transitional jitters... Rich? -//STRAFING============================================================================== - if ( pVeh->m_pVehicleInfo->strafePerc -#ifdef QAGAME//only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing -#endif - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_LandTrace.fraction >= 1.0f//no grounf - ||pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE//can't land here - ||parentPS->speed>MIN_LANDING_SPEED)//going too fast to land - && pVeh->m_ucmd.rightmove ) - {//strafe +#if 1 // This is working now, but there are some transitional jitters... Rich? + // STRAFING============================================================================== + if (pVeh->m_pVehicleInfo->strafePerc +#ifdef QAGAME // only do this check on GAME side, because if it's CGAME, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing +#endif + && !pVeh->m_iRemovedSurfaces && parentPS->electrifyTime < curTime && + (pVeh->m_LandTrace.fraction >= 1.0f // no grounf + || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE // can't land here + || parentPS->speed > MIN_LANDING_SPEED) // going too fast to land + && pVeh->m_ucmd.rightmove) { // strafe vec3_t vAngles, vRight; - float strafeSpeed = (pVeh->m_pVehicleInfo->strafePerc*speedMax)*5.0f; - VectorCopy( pVeh->m_vOrientation, vAngles ); + float strafeSpeed = (pVeh->m_pVehicleInfo->strafePerc * speedMax) * 5.0f; + VectorCopy(pVeh->m_vOrientation, vAngles); vAngles[PITCH] = vAngles[ROLL] = 0; - AngleVectors( vAngles, NULL, vRight, NULL ); + AngleVectors(vAngles, NULL, vRight, NULL); - if ( pVeh->m_ucmd.rightmove > 0 ) - {//strafe right - //FIXME: this will probably make it possible to cheat and + if (pVeh->m_ucmd.rightmove > 0) { // strafe right + // FIXME: this will probably make it possible to cheat and // go faster than max speed if you keep turning and strafing... - if ( pVeh->m_fStrafeTime > -MAX_STRAFE_TIME ) - {//can strafe right for 2 seconds - float curStrafeSpeed = DotProduct( parentPS->velocity, vRight ); - if ( curStrafeSpeed > 0.0f ) - {//if > 0, already strafing right - strafeSpeed -= curStrafeSpeed;//so it doesn't add up + if (pVeh->m_fStrafeTime > -MAX_STRAFE_TIME) { // can strafe right for 2 seconds + float curStrafeSpeed = DotProduct(parentPS->velocity, vRight); + if (curStrafeSpeed > 0.0f) { // if > 0, already strafing right + strafeSpeed -= curStrafeSpeed; // so it doesn't add up } - if ( strafeSpeed > 0 ) - { - VectorMA( parentPS->velocity, strafeSpeed*pVeh->m_fTimeModifier, vRight, parentPS->velocity ); + if (strafeSpeed > 0) { + VectorMA(parentPS->velocity, strafeSpeed * pVeh->m_fTimeModifier, vRight, parentPS->velocity); } - pVeh->m_fStrafeTime -= 50*pVeh->m_fTimeModifier; + pVeh->m_fStrafeTime -= 50 * pVeh->m_fTimeModifier; } - } - else - {//strafe left - if ( pVeh->m_fStrafeTime < MAX_STRAFE_TIME ) - {//can strafe left for 2 seconds - float curStrafeSpeed = DotProduct( parentPS->velocity, vRight ); - if ( curStrafeSpeed < 0.0f ) - {//if < 0, already strafing left - strafeSpeed += curStrafeSpeed;//so it doesn't add up + } else { // strafe left + if (pVeh->m_fStrafeTime < MAX_STRAFE_TIME) { // can strafe left for 2 seconds + float curStrafeSpeed = DotProduct(parentPS->velocity, vRight); + if (curStrafeSpeed < 0.0f) { // if < 0, already strafing left + strafeSpeed += curStrafeSpeed; // so it doesn't add up } - if ( strafeSpeed > 0 ) - { - VectorMA( parentPS->velocity, -strafeSpeed*pVeh->m_fTimeModifier, vRight, parentPS->velocity ); + if (strafeSpeed > 0) { + VectorMA(parentPS->velocity, -strafeSpeed * pVeh->m_fTimeModifier, vRight, parentPS->velocity); } - pVeh->m_fStrafeTime += 50*pVeh->m_fTimeModifier; + pVeh->m_fStrafeTime += 50 * pVeh->m_fTimeModifier; } } - //strafing takes away from forward speed? If so, strafePerc above should use speedMax - //parentPS->speed *= (1.0f-pVeh->m_pVehicleInfo->strafePerc); - } - else//if ( pVeh->m_fStrafeTime ) + // strafing takes away from forward speed? If so, strafePerc above should use speedMax + // parentPS->speed *= (1.0f-pVeh->m_pVehicleInfo->strafePerc); + } else // if ( pVeh->m_fStrafeTime ) { - if ( pVeh->m_fStrafeTime > 0 ) - { - pVeh->m_fStrafeTime -= 50*pVeh->m_fTimeModifier; - if ( pVeh->m_fStrafeTime < 0 ) - { + if (pVeh->m_fStrafeTime > 0) { + pVeh->m_fStrafeTime -= 50 * pVeh->m_fTimeModifier; + if (pVeh->m_fStrafeTime < 0) { pVeh->m_fStrafeTime = 0.0f; } - } - else if ( pVeh->m_fStrafeTime < 0 ) - { - pVeh->m_fStrafeTime += 50*pVeh->m_fTimeModifier; - if ( pVeh->m_fStrafeTime > 0 ) - { + } else if (pVeh->m_fStrafeTime < 0) { + pVeh->m_fStrafeTime += 50 * pVeh->m_fTimeModifier; + if (pVeh->m_fStrafeTime > 0) { pVeh->m_fStrafeTime = 0.0f; } } } -//STRAFING============================================================================== +// STRAFING============================================================================== #endif - if ( parentPS->speed > speedMax ) - { + if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } -#ifdef QAGAME//FIXME: get working in GAME and CGAME - if ((pVeh->m_vOrientation[PITCH]*0.1f) > 10.0f) - { //pitched downward, increase speed more and more based on our tilt - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//in space, do nothing with speed base on pitch... - } - else - { - //really should only do this when on a planet - float mult = pVeh->m_vOrientation[PITCH]*0.1f; - if (mult < 1.0f) - { +#ifdef QAGAME // FIXME: get working in GAME and CGAME + if ((pVeh->m_vOrientation[PITCH] * 0.1f) > 10.0f) { // pitched downward, increase speed more and more based on our tilt + if (FighterIsInSpace((gentity_t *)parent)) { // in space, do nothing with speed base on pitch... + } else { + // really should only do this when on a planet + float mult = pVeh->m_vOrientation[PITCH] * 0.1f; + if (mult < 1.0f) { mult = 1.0f; } - parentPS->speed = PredictedAngularDecrement(mult, pVeh->m_fTimeModifier*10.0f, parentPS->speed); + parentPS->speed = PredictedAngularDecrement(mult, pVeh->m_fTimeModifier * 10.0f, parentPS->speed); } } - if (pVeh->m_iRemovedSurfaces - || parentPS->electrifyTime>=curTime) - { //going down - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//we're in a valid trigger_space brush - //simulate randomness - if ( !(parent->s.number&3) ) - {//even multiple of 3, don't do anything + if (pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) { // going down + if (FighterIsInSpace((gentity_t *)parent)) { // we're in a valid trigger_space brush + // simulate randomness + if (!(parent->s.number & 3)) { // even multiple of 3, don't do anything parentPS->gravity = 0; - } - else if ( !(parent->s.number&2) ) - {//even multiple of 2, go up + } else if (!(parent->s.number & 2)) { // even multiple of 2, go up parentPS->gravity = -500.0f; parentPS->velocity[2] = 80.0f; - } - else - {//odd number, go down + } else { // odd number, go down parentPS->gravity = 500.0f; parentPS->velocity[2] = -80.0f; } - } - else - {//over a planet + } else { // over a planet parentPS->gravity = 500.0f; parentPS->velocity[2] = -80.0f; } - } - else if ( FighterSuspended( pVeh, parentPS ) ) - { + } else if (FighterSuspended(pVeh, parentPS)) { parentPS->gravity = 0; - } - else if ( (!parentPS->speed||parentPS->speed < speedIdle) && pVeh->m_ucmd.upmove <= 0 ) - {//slowing down or stopped and not trying to take off - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//we're in space, stopping doesn't make us drift downward - if ( FighterOverValidLandingSurface( pVeh ) ) - {//well, there's something below us to land on, so go ahead and lower us down to it - parentPS->gravity = (speedIdle - parentPS->speed)/4; + } else if ((!parentPS->speed || parentPS->speed < speedIdle) && pVeh->m_ucmd.upmove <= 0) { // slowing down or stopped and not trying to take off + if (FighterIsInSpace((gentity_t *)parent)) { // we're in space, stopping doesn't make us drift downward + if (FighterOverValidLandingSurface(pVeh)) { // well, there's something below us to land on, so go ahead and lower us down to it + parentPS->gravity = (speedIdle - parentPS->speed) / 4; } + } else { // over a planet + parentPS->gravity = (speedIdle - parentPS->speed) / 4; } - else - {//over a planet - parentPS->gravity = (speedIdle - parentPS->speed)/4; - } - } - else - { + } else { parentPS->gravity = 0; } -#else//FIXME: get above checks working in GAME and CGAME +#else // FIXME: get above checks working in GAME and CGAME parentPS->gravity = 0; #endif @@ -907,151 +749,113 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -extern void BG_VehicleTurnRateForSpeed( Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride ); -static void FighterWingMalfunctionCheck( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +extern void BG_VehicleTurnRateForSpeed(Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride); +static void FighterWingMalfunctionCheck(Vehicle_t *pVeh, playerState_t *parentPS) { float mPitchOverride = 1.0f; float mYawOverride = 1.0f; - BG_VehicleTurnRateForSpeed( pVeh, parentPS->speed, &mPitchOverride, &mYawOverride ); - //check right wing damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] += (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*50.0f; - } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] += (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*12.5f; + BG_VehicleTurnRateForSpeed(pVeh, parentPS->speed, &mPitchOverride, &mYawOverride); + // check right wing damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_RIGHT_HEAVY))) { // right wing has taken heavy damage + pVeh->m_vOrientation[ROLL] += (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_RIGHT_LIGHT))) { // right wing has taken light damage + pVeh->m_vOrientation[ROLL] += (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 12.5f; } - //check left wing damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] -= (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*50.0f; - } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] -= (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*12.5f; + // check left wing damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_LEFT_HEAVY))) { // left wing has taken heavy damage + pVeh->m_vOrientation[ROLL] -= (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_LEFT_LIGHT))) { // left wing has taken light damage + pVeh->m_vOrientation[ROLL] -= (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 12.5f; } - } -static void FighterNoseMalfunctionCheck( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +static void FighterNoseMalfunctionCheck(Vehicle_t *pVeh, playerState_t *parentPS) { float mPitchOverride = 1.0f; float mYawOverride = 1.0f; - BG_VehicleTurnRateForSpeed( pVeh, parentPS->speed, &mPitchOverride, &mYawOverride ); - //check nose damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[PITCH] += sin( pVeh->m_ucmd.serverTime*0.001 )*pVeh->m_fTimeModifier*mPitchOverride*50.0f; - } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[PITCH] += sin( pVeh->m_ucmd.serverTime*0.001 )*pVeh->m_fTimeModifier*mPitchOverride*20.0f; + BG_VehicleTurnRateForSpeed(pVeh, parentPS->speed, &mPitchOverride, &mYawOverride); + // check nose damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_FRONT_HEAVY))) { // nose has taken heavy damage + // pitch up and down over time + pVeh->m_vOrientation[PITCH] += sin(pVeh->m_ucmd.serverTime * 0.001) * pVeh->m_fTimeModifier * mPitchOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_FRONT_LIGHT))) { // nose has taken heavy damage + // pitch up and down over time + pVeh->m_vOrientation[PITCH] += sin(pVeh->m_ucmd.serverTime * 0.001) * pVeh->m_fTimeModifier * mPitchOverride * 20.0f; } } -static void FighterDamageRoutine( Vehicle_t *pVeh, bgEntity_t *parent, playerState_t *parentPS, playerState_t *riderPS, qboolean isDead ) -{ - if ( !pVeh->m_iRemovedSurfaces ) - {//still in one piece - if ( pVeh->m_pParentEntity && isDead ) - {//death spiral +static void FighterDamageRoutine(Vehicle_t *pVeh, bgEntity_t *parent, playerState_t *parentPS, playerState_t *riderPS, qboolean isDead) { + if (!pVeh->m_iRemovedSurfaces) { // still in one piece + if (pVeh->m_pParentEntity && isDead) { // death spiral pVeh->m_ucmd.upmove = 0; - //FIXME: don't bias toward pitching down when not in space + // FIXME: don't bias toward pitching down when not in space /* if ( FighterIsInSpace( pVeh->m_pParentEntity ) ) { } else */ - if ( !(pVeh->m_pParentEntity->s.number%3) ) - {//NOT everyone should do this + if (!(pVeh->m_pParentEntity->s.number % 3)) { // NOT everyone should do this pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } - } - else if ( !(pVeh->m_pParentEntity->s.number%2) ) - { + } else if (!(pVeh->m_pParentEntity->s.number % 2)) { pVeh->m_vOrientation[PITCH] -= pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > -60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > -60.0f) { pVeh->m_vOrientation[PITCH] = -60.0f; } } } - if ( (pVeh->m_pParentEntity->s.number%2) ) - { + if ((pVeh->m_pParentEntity->s.number % 2)) { pVeh->m_vOrientation[YAW] += pVeh->m_fTimeModifier; - pVeh->m_vOrientation[ROLL] += pVeh->m_fTimeModifier*4.0f; - } - else - { + pVeh->m_vOrientation[ROLL] += pVeh->m_fTimeModifier * 4.0f; + } else { pVeh->m_vOrientation[YAW] -= pVeh->m_fTimeModifier; - pVeh->m_vOrientation[ROLL] -= pVeh->m_fTimeModifier*4.0f; + pVeh->m_vOrientation[ROLL] -= pVeh->m_fTimeModifier * 4.0f; } } return; } - //if we get into here we have at least one broken piece + // if we get into here we have at least one broken piece pVeh->m_ucmd.upmove = 0; - //if you're off the ground and not suspended, pitch down - //FIXME: not in space! - if ( pVeh->m_LandTrace.fraction >= 0.1f ) - { - if ( !FighterSuspended( pVeh, parentPS ) ) - { - //pVeh->m_ucmd.forwardmove = 0; - //FIXME: don't bias towards pitching down when in space... - if ( !(pVeh->m_pParentEntity->s.number%2) ) - {//NOT everyone should do this + // if you're off the ground and not suspended, pitch down + // FIXME: not in space! + if (pVeh->m_LandTrace.fraction >= 0.1f) { + if (!FighterSuspended(pVeh, parentPS)) { + // pVeh->m_ucmd.forwardmove = 0; + // FIXME: don't bias towards pitching down when in space... + if (!(pVeh->m_pParentEntity->s.number % 2)) { // NOT everyone should do this pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } - } - else if ( !(pVeh->m_pParentEntity->s.number%3) ) - { + } else if (!(pVeh->m_pParentEntity->s.number % 3)) { pVeh->m_vOrientation[PITCH] -= pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > -60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > -60.0f) { pVeh->m_vOrientation[PITCH] = -60.0f; } } } - //else: just keep going forward + // else: just keep going forward } } #ifdef QAGAME - if ( pVeh->m_LandTrace.fraction < 1.0f ) - { //if you land at all when pieces of your ship are missing, then die + if (pVeh->m_LandTrace.fraction < 1.0f) { // if you land at all when pieces of your ship are missing, then die gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *killer = parent; -#ifdef _JK2MP//only have this info in MP... - if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && - parent->client->ps.otherKillerTime > level.time) - { +#ifdef _JK2MP // only have this info in MP... + if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && parent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[parent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } @@ -1060,126 +864,94 @@ static void FighterDamageRoutine( Vehicle_t *pVeh, bgEntity_t *parent, playerSta } #endif - if ( ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) && - ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) ) - { //wings on both side broken + if (((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) && + ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F))) { // wings on both side broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //all wings broken + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // all wings broken factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] += (pVeh->m_fTimeModifier*factor); //do some spiralling - } - else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //left wing broken + pVeh->m_vOrientation[ROLL] += (pVeh->m_fTimeModifier * factor); // do some spiralling + } else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // left wing broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //if both are broken.. + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // if both are broken.. factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] += factor*pVeh->m_fTimeModifier; - } - else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { //right wing broken + pVeh->m_vOrientation[ROLL] += factor * pVeh->m_fTimeModifier; + } else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { // right wing broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { //if both are broken.. + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { // if both are broken.. factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] -= factor*pVeh->m_fTimeModifier; + pVeh->m_vOrientation[ROLL] -= factor * pVeh->m_fTimeModifier; } } #ifdef _JK2MP -void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ +void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*0.8f; //magic number hackery + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 0.8f; // magic number hackery - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } -void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ +void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { float angDif = AngleSubtract(pVeh->m_vOrientation[PITCH], riderPS->viewangles[PITCH]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*0.8f; //magic number hackery + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 0.8f; // magic number hackery - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[PITCH] = AngleNormalize360(pVeh->m_vOrientation[PITCH] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[PITCH] = AngleNormalize360(pVeh->m_vOrientation[PITCH] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } #endif -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -1190,22 +962,21 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #ifdef QAGAME const float groundFraction = 0.1f; #endif - float curRoll = 0.0f; + float curRoll = 0.0f; qboolean isDead = qfalse; qboolean isLandingOrLanded = qfalse; -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP int curTime = level.time; -#elif defined QAGAME//MP GAME +#elif defined QAGAME // MP GAME int curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... int curTime = pm->cmd.serverTime; #endif #ifdef _JK2MP bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } #else @@ -1213,9 +984,9 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #endif #ifdef _JK2MP - if ( !rider ) + if (!rider) #else - if ( !rider || !rider->client ) + if (!rider || !rider->client) #endif { rider = parent; @@ -1224,149 +995,119 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #ifdef _JK2MP parentPS = parent->playerState; riderPS = rider->playerState; - isDead = (qboolean)((parentPS->eFlags&EF_DEAD)!=0); + isDead = (qboolean)((parentPS->eFlags & EF_DEAD) != 0); #else parentPS = &parent->client->ps; riderPS = &rider->client->ps; - isDead = (qboolean)(parentPS->stats[STAT_HEALTH] <= 0 ); + isDead = (qboolean)(parentPS->stats[STAT_HEALTH] <= 0); #endif #ifdef _JK2MP - if ( parentPS->hyperSpaceTime - && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME ) - {//Going to Hyperspace - VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - VectorCopy( riderPS->viewangles, parentPS->viewangles ); + if (parentPS->hyperSpaceTime && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME) { // Going to Hyperspace + VectorCopy(riderPS->viewangles, pVeh->m_vOrientation); + VectorCopy(riderPS->viewangles, parentPS->viewangles); return; } #endif - if ( pVeh->m_iDropTime >= curTime ) - {//you can only YAW during this + if (pVeh->m_iDropTime >= curTime) { // you can only YAW during this parentPS->viewangles[YAW] = pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; return; } angleTimeMod = pVeh->m_fTimeModifier; - if ( isDead || parentPS->electrifyTime>=curTime || - (pVeh->m_pVehicleInfo->surfDestruction && - pVeh->m_iRemovedSurfaces && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) ) - { //do some special stuff for when all the wings are torn off + if (isDead || parentPS->electrifyTime >= curTime || + (pVeh->m_pVehicleInfo->surfDestruction && pVeh->m_iRemovedSurfaces && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F))) { // do some special stuff for when all the wings are torn off FighterDamageRoutine(pVeh, parent, parentPS, riderPS, isDead); - pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); + pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL]); return; } - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - pVeh->m_vOrientation[ROLL] = PredictedAngularDecrement(0.95f, angleTimeMod*2.0f, pVeh->m_vOrientation[ROLL]); + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + pVeh->m_vOrientation[ROLL] = PredictedAngularDecrement(0.95f, angleTimeMod * 2.0f, pVeh->m_vOrientation[ROLL]); } - isLandingOrLanded = (qboolean)(FighterIsLanding( pVeh, parentPS )||FighterIsLanded( pVeh, parentPS )); + isLandingOrLanded = (qboolean)(FighterIsLanding(pVeh, parentPS) || FighterIsLanded(pVeh, parentPS)); - if (!isLandingOrLanded) - { //don't do this stuff while landed.. I guess. I don't want ships spinning in place, looks silly. + if (!isLandingOrLanded) { // don't do this stuff while landed.. I guess. I don't want ships spinning in place, looks silly. int m = 0; float aVelDif; float dForVel; - FighterWingMalfunctionCheck( pVeh, parentPS ); + FighterWingMalfunctionCheck(pVeh, parentPS); - while (m < 3) - { + while (m < 3) { aVelDif = pVeh->m_vFullAngleVelocity[m]; - if (aVelDif != 0.0f) - { - dForVel = (aVelDif*0.1f)*pVeh->m_fTimeModifier; - if (dForVel > 1.0f || dForVel < -1.0f) - { + if (aVelDif != 0.0f) { + dForVel = (aVelDif * 0.1f) * pVeh->m_fTimeModifier; + if (dForVel > 1.0f || dForVel < -1.0f) { pVeh->m_vOrientation[m] += dForVel; pVeh->m_vOrientation[m] = AngleNormalize180(pVeh->m_vOrientation[m]); - if (m == PITCH) - { //don't pitch downward into ground even more. - if (pVeh->m_vOrientation[m] > 90.0f && (pVeh->m_vOrientation[m]-dForVel) < 90.0f) - { + if (m == PITCH) { // don't pitch downward into ground even more. + if (pVeh->m_vOrientation[m] > 90.0f && (pVeh->m_vOrientation[m] - dForVel) < 90.0f) { pVeh->m_vOrientation[m] = 90.0f; pVeh->m_vFullAngleVelocity[m] = -pVeh->m_vFullAngleVelocity[m]; } } - if (riderPS) - { + if (riderPS) { riderPS->viewangles[m] = pVeh->m_vOrientation[m]; } pVeh->m_vFullAngleVelocity[m] -= dForVel; - } - else - { + } else { pVeh->m_vFullAngleVelocity[m] = 0.0f; } } m++; } - } - else - { //clear decr/incr angles once landed. + } else { // clear decr/incr angles once landed. VectorClear(pVeh->m_vFullAngleVelocity); } curRoll = pVeh->m_vOrientation[ROLL]; // If we're landed, we shouldn't be able to do anything but take off. - if ( isLandingOrLanded //going slow enough to start landing - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_iRemovedSurfaces && parentPS->electrifyTime < curTime) // not spiraling out of control { - if ( parentPS->speed > 0.0f ) - {//Uh... what? Why? - if ( pVeh->m_LandTrace.fraction < 0.3f ) - { + if (parentPS->speed > 0.0f) { // Uh... what? Why? + if (pVeh->m_LandTrace.fraction < 0.3f) { pVeh->m_vOrientation[PITCH] = 0.0f; - } - else - { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.83f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + } else { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.83f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); } } - if ( pVeh->m_LandTrace.fraction > 0.1f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - {//off the ground, at least (or not on a valid landing surf) - // Dampen the turn rate based on the current height. + if (pVeh->m_LandTrace.fraction > 0.1f || + pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { // off the ground, at least (or not on a valid landing surf) + // Dampen the turn rate based on the current height. #ifdef _JK2MP FighterYawAdjust(pVeh, riderPS, parentPS); #else - pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW];//*pVeh->m_LandTrace.fraction; + pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; //*pVeh->m_LandTrace.fraction; #endif } - } - else if ( (pVeh->m_iRemovedSurfaces||parentPS->electrifyTime>=curTime)//spiralling out of control - && (!(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5)) ) - {//no yaw control - } - else if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS && parentPS->speed > 0.0f )//&& !( pVeh->m_ucmd.forwardmove > 0 && pVeh->m_LandTrace.fraction != 1.0f ) ) + } else if ((pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) // spiralling out of control + && (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5))) { // no yaw control + } else if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS && + parentPS->speed > 0.0f) //&& !( pVeh->m_ucmd.forwardmove > 0 && pVeh->m_LandTrace.fraction != 1.0f ) ) { - if ( BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - VectorCopy( riderPS->viewangles, parentPS->viewangles ); + if (BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + VectorCopy(riderPS->viewangles, pVeh->m_vOrientation); + VectorCopy(riderPS->viewangles, parentPS->viewangles); #ifdef _JK2MP - //BG_ExternThisSoICanRecompileInDebug( pVeh, riderPS ); + // BG_ExternThisSoICanRecompileInDebug( pVeh, riderPS ); #endif curRoll = pVeh->m_vOrientation[ROLL]; - FighterNoseMalfunctionCheck( pVeh, parentPS ); + FighterNoseMalfunctionCheck(pVeh, parentPS); - //VectorCopy( pVeh->m_vOrientation, parentPS->viewangles ); - } - else - { + // VectorCopy( pVeh->m_vOrientation, parentPS->viewangles ); + } else { /* float fTurnAmt[3]; //PITCH @@ -1384,7 +1125,7 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) fTurnAmt[2] = 0.0f; */ - //Actal YAW + // Actal YAW #ifdef _JK2MP FighterYawAdjust(pVeh, riderPS, parentPS); #else @@ -1392,9 +1133,8 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #endif // If we are not hitting the ground, allow the fighter to pitch up and down. - if ( !FighterOverValidLandingSurface( pVeh ) - || parentPS->speed > MIN_LANDING_SPEED ) - //if ( ( pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_ucmd.forwardmove != 0 ) && pVeh->m_LandTrace.fraction >= 0.0f ) + if (!FighterOverValidLandingSurface(pVeh) || parentPS->speed > MIN_LANDING_SPEED) + // if ( ( pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_ucmd.forwardmove != 0 ) && pVeh->m_LandTrace.fraction >= 0.0f ) { float fYawDelta; @@ -1404,31 +1144,25 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) pVeh->m_vOrientation[PITCH] = riderPS->viewangles[PITCH]; #endif - FighterNoseMalfunctionCheck( pVeh, parentPS ); + FighterNoseMalfunctionCheck(pVeh, parentPS); // Adjust the roll based on the turn amount and dampen it a little. - fYawDelta = AngleSubtract(pVeh->m_vOrientation[YAW], pVeh->m_vPrevOrientation[YAW]); //pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; - if ( fYawDelta > 8.0f ) - { + fYawDelta = + AngleSubtract(pVeh->m_vOrientation[YAW], pVeh->m_vPrevOrientation[YAW]); // pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; + if (fYawDelta > 8.0f) { fYawDelta = 8.0f; - } - else if ( fYawDelta < -8.0f ) - { + } else if (fYawDelta < -8.0f) { fYawDelta = -8.0f; } curRoll -= fYawDelta; - curRoll = PredictedAngularDecrement(0.93f, angleTimeMod*2.0f, curRoll); - //cap it reasonably - //NOTE: was hardcoded to 40.0f, now using extern data - if ( pVeh->m_pVehicleInfo->rollLimit != -1 ) - { - if (curRoll > pVeh->m_pVehicleInfo->rollLimit ) - { + curRoll = PredictedAngularDecrement(0.93f, angleTimeMod * 2.0f, curRoll); + // cap it reasonably + // NOTE: was hardcoded to 40.0f, now using extern data + if (pVeh->m_pVehicleInfo->rollLimit != -1) { + if (curRoll > pVeh->m_pVehicleInfo->rollLimit) { curRoll = pVeh->m_pVehicleInfo->rollLimit; - } - else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) - { + } else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) { curRoll = -pVeh->m_pVehicleInfo->rollLimit; } } @@ -1437,138 +1171,109 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) } // If you are directly impacting the ground, even out your pitch. - if ( isLandingOrLanded ) - {//only if capable of landing - if ( !isDead - && parentPS->electrifyTimem_pVehicleInfo->surfDestruction || !pVeh->m_iRemovedSurfaces ) ) - {//not crashing or spiralling out of control... - if ( pVeh->m_vOrientation[PITCH] > 0 ) + if (isLandingOrLanded) { // only if capable of landing + if (!isDead && parentPS->electrifyTime < curTime && + (!pVeh->m_pVehicleInfo->surfDestruction || !pVeh->m_iRemovedSurfaces)) { // not crashing or spiralling out of control... + if (pVeh->m_vOrientation[PITCH] > 0) { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.2f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); + } else { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.75f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); + } + } + } + + /* + //NOTE: all this is redundant now since we have the FighterDamageRoutine func... + #ifdef _JK2MP //...yeah. Need to send armor across net for prediction to work. + if ( isDead ) + #else + if ( pVeh->m_iArmor <= 0 ) + #endif + {//going to explode + //FIXME: maybe make it erratically jerk or spin or start and stop? + #ifndef _JK2MP + if ( g_speederControlScheme->value > 0 || !rider || rider->s.number ) + #else + if (1) + #endif { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.2f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + pVeh->m_ucmd.rightmove = Q_irand( -64, 64 ); } else { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.75f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + pVeh->m_ucmd.rightmove = 0; + } + pVeh->m_ucmd.forwardmove = Q_irand( -32, 127 ); + pVeh->m_ucmd.upmove = Q_irand( -127, 127 ); + pVeh->m_vOrientation[YAW] += Q_flrand( -10, 10 ); + pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; + if ( pVeh->m_vOrientation[PITCH] > 60.0f ) + { + pVeh->m_vOrientation[PITCH] = 60.0f; + } + if ( pVeh->m_LandTrace.fraction != 0.0f ) + { + parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } } - } - - -/* -//NOTE: all this is redundant now since we have the FighterDamageRoutine func... -#ifdef _JK2MP //...yeah. Need to send armor across net for prediction to work. - if ( isDead ) -#else - if ( pVeh->m_iArmor <= 0 ) -#endif - {//going to explode - //FIXME: maybe make it erratically jerk or spin or start and stop? -#ifndef _JK2MP - if ( g_speederControlScheme->value > 0 || !rider || rider->s.number ) -#else - if (1) -#endif - { - pVeh->m_ucmd.rightmove = Q_irand( -64, 64 ); - } - else - { - pVeh->m_ucmd.rightmove = 0; - } - pVeh->m_ucmd.forwardmove = Q_irand( -32, 127 ); - pVeh->m_ucmd.upmove = Q_irand( -127, 127 ); - pVeh->m_vOrientation[YAW] += Q_flrand( -10, 10 ); - pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { - pVeh->m_vOrientation[PITCH] = 60.0f; - } - if ( pVeh->m_LandTrace.fraction != 0.0f ) - { - parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; - } - } -*/ + */ // If no one is in this vehicle and it's up in the sky, pitch it forward as it comes tumbling down. -#ifdef QAGAME //never gonna happen on client anyway, we can't be getting predicted unless the predicting client is boarded - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) - && pVeh->m_LandTrace.fraction >= groundFraction - && !FighterIsInSpace( (gentity_t *)parent ) - && !FighterSuspended( pVeh, parentPS ) ) - { +#ifdef QAGAME // never gonna happen on client anyway, we can't be getting predicted unless the predicting client is boarded + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh) && pVeh->m_LandTrace.fraction >= groundFraction && !FighterIsInSpace((gentity_t *)parent) && + !FighterSuspended(pVeh, parentPS)) { pVeh->m_ucmd.upmove = 0; - //pVeh->m_ucmd.forwardmove = 0; + // pVeh->m_ucmd.forwardmove = 0; pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } } #endif - if ( !pVeh->m_fStrafeTime ) - {//use that roll + if (!pVeh->m_fStrafeTime) { // use that roll pVeh->m_vOrientation[ROLL] = curRoll; - //NOTE: this seems really backwards... - if ( pVeh->m_vOrientation[ROLL] ) - { //continually adjust the yaw based on the roll.. - if ( (pVeh->m_iRemovedSurfaces||parentPS->electrifyTime>=curTime)//spiralling out of control - && (!(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5)) ) - {//leave YAW alone - } - else - { - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - pVeh->m_vOrientation[YAW] -= ((pVeh->m_vOrientation[ROLL])*0.05f)*pVeh->m_fTimeModifier; + // NOTE: this seems really backwards... + if (pVeh->m_vOrientation[ROLL]) { // continually adjust the yaw based on the roll.. + if ((pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) // spiralling out of control + && (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5))) { // leave YAW alone + } else { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + pVeh->m_vOrientation[YAW] -= ((pVeh->m_vOrientation[ROLL]) * 0.05f) * pVeh->m_fTimeModifier; } } } - } - else - {//add in strafing roll - float strafeRoll = (pVeh->m_fStrafeTime/MAX_STRAFE_TIME)*pVeh->m_pVehicleInfo->rollLimit;//pVeh->m_pVehicleInfo->bankingSpeed* + } else { // add in strafing roll + float strafeRoll = (pVeh->m_fStrafeTime / MAX_STRAFE_TIME) * pVeh->m_pVehicleInfo->rollLimit; // pVeh->m_pVehicleInfo->bankingSpeed* float strafeDif = AngleSubtract(strafeRoll, pVeh->m_vOrientation[ROLL]); - pVeh->m_vOrientation[ROLL] += (strafeDif*0.1f)*pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - {//cap it reasonably - if ( pVeh->m_pVehicleInfo->rollLimit != -1 - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_vOrientation[ROLL] > pVeh->m_pVehicleInfo->rollLimit ) - { + pVeh->m_vOrientation[ROLL] += (strafeDif * 0.1f) * pVeh->m_fTimeModifier; + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { // cap it reasonably + if (pVeh->m_pVehicleInfo->rollLimit != -1 && !pVeh->m_iRemovedSurfaces && parentPS->electrifyTime < curTime) { + if (pVeh->m_vOrientation[ROLL] > pVeh->m_pVehicleInfo->rollLimit) { pVeh->m_vOrientation[ROLL] = pVeh->m_pVehicleInfo->rollLimit; - } - else if (pVeh->m_vOrientation[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) - { + } else if (pVeh->m_vOrientation[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) { pVeh->m_vOrientation[ROLL] = -pVeh->m_pVehicleInfo->rollLimit; } } } } - if (pVeh->m_pVehicleInfo->surfDestruction) - { + if (pVeh->m_pVehicleInfo->surfDestruction) { FighterDamageRoutine(pVeh, parent, parentPS, riderPS, isDead); } - pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); + pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL]); /********************************************************************************/ /* END Here is where make sure the vehicle is properly oriented. END */ /********************************************************************************/ } -#ifdef QAGAME //ONLY in SP or on server, not cgame +#ifdef QAGAME // ONLY in SP or on server, not cgame -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); // This function makes sure that the vehicle is properly animated. -static void AnimateVehicle( Vehicle_t *pVeh ) -{ +static void AnimateVehicle(Vehicle_t *pVeh) { int Anim = -1; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; qboolean isLanding = qfalse, isLanded = qfalse; @@ -1577,80 +1282,64 @@ static void AnimateVehicle( Vehicle_t *pVeh ) #else playerState_t *parentPS = &pVeh->m_pParentEntity->client->ps; #endif -#ifndef _JK2MP//SP - //nothing -#elif defined QAGAME//MP GAME +#ifndef _JK2MP // SP + // nothing +#elif defined QAGAME // MP GAME int curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... int curTime = pm->cmd.serverTime; #endif #ifdef _JK2MP - if ( parentPS->hyperSpaceTime - && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME ) - {//Going to Hyperspace - //close the wings (FIXME: makes sense on X-Wing, not Shuttle?) - if ( pVeh->m_ulFlags & VEH_WINGSOPEN ) - { + if (parentPS->hyperSpaceTime && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME) { // Going to Hyperspace + // close the wings (FIXME: makes sense on X-Wing, not Shuttle?) + if (pVeh->m_ulFlags & VEH_WINGSOPEN) { pVeh->m_ulFlags &= ~VEH_WINGSOPEN; Anim = BOTH_WINGS_CLOSE; } - } - else + } else #endif { - isLanding = FighterIsLanding( pVeh, parentPS ); - isLanded = FighterIsLanded( pVeh, parentPS ); + isLanding = FighterIsLanding(pVeh, parentPS); + isLanded = FighterIsLanded(pVeh, parentPS); // if we're above launch height (way up in the air)... - if ( !isLanding && !isLanded ) - { - if ( !( pVeh->m_ulFlags & VEH_WINGSOPEN ) ) - { + if (!isLanding && !isLanded) { + if (!(pVeh->m_ulFlags & VEH_WINGSOPEN)) { pVeh->m_ulFlags |= VEH_WINGSOPEN; pVeh->m_ulFlags &= ~VEH_GEARSOPEN; Anim = BOTH_WINGS_OPEN; } } // otherwise we're below launch height and still taking off. - else - { - if ( (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0||isLanded) - && pVeh->m_LandTrace.fraction <= 0.4f - && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE ) - {//already landed or trying to land and close to ground + else { + if ((pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0 || isLanded) && pVeh->m_LandTrace.fraction <= 0.4f && + pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE) { // already landed or trying to land and close to ground // Open gears. - if ( !( pVeh->m_ulFlags & VEH_GEARSOPEN ) ) - { + if (!(pVeh->m_ulFlags & VEH_GEARSOPEN)) { #ifdef _JK2MP - if ( pVeh->m_pVehicleInfo->soundLand ) - {//just landed? -#ifdef QAGAME//MP GAME-side - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand ); -#elif defined CGAME//MP CGAME-side - //trap_S_StartSound( NULL, pVeh->m_pParentEntity->s.number, CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand ); + if (pVeh->m_pVehicleInfo->soundLand) { // just landed? +#ifdef QAGAME // MP GAME-side + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand); +#elif defined CGAME // MP CGAME-side + // trap_S_StartSound( NULL, pVeh->m_pParentEntity->s.number, CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand ); #endif } #endif pVeh->m_ulFlags |= VEH_GEARSOPEN; Anim = BOTH_GEARS_OPEN; } - } - else - {//trying to take off and almost halfway off the ground + } else { // trying to take off and almost halfway off the ground // Close gears (if they're open). - if ( pVeh->m_ulFlags & VEH_GEARSOPEN ) - { + if (pVeh->m_ulFlags & VEH_GEARSOPEN) { pVeh->m_ulFlags &= ~VEH_GEARSOPEN; Anim = BOTH_GEARS_CLOSE; - //iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + // iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; } // If gears are closed, and we are below launch height, close the wings. - else - { - if ( pVeh->m_ulFlags & VEH_WINGSOPEN ) - { + else { + if (pVeh->m_ulFlags & VEH_WINGSOPEN) { pVeh->m_ulFlags &= ~VEH_WINGSOPEN; Anim = BOTH_WINGS_CLOSE; } @@ -1659,58 +1348,53 @@ static void AnimateVehicle( Vehicle_t *pVeh ) } } - if ( Anim != -1 ) - { - #ifdef _JK2MP - BG_SetAnim(pVeh->m_pParentEntity->playerState, bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, - SETANIM_BOTH, Anim, iFlags, iBlend); - #else - NPC_SetAnim( pVeh->m_pParentEntity, SETANIM_BOTH, Anim, iFlags, iBlend ); - #endif + if (Anim != -1) { +#ifdef _JK2MP + BG_SetAnim(pVeh->m_pParentEntity->playerState, bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags, iBlend); +#else + NPC_SetAnim(pVeh->m_pParentEntity, SETANIM_BOTH, Anim, iFlags, iBlend); +#endif } } // This function makes sure that the rider's in this vehicle are properly animated. -static void AnimateRiders( Vehicle_t *pVeh ) -{ -} +static void AnimateRiders(Vehicle_t *pVeh) {} -#endif //game-only +#endif // game-only #ifndef QAGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); -#endif - -void G_SetFighterVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ -#ifdef QAGAME //ONLY in SP or on server, not cgame - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; - pVehInfo->Board = Board; - pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; +void AttachRidersGeneric(Vehicle_t *pVeh); +#endif + +void G_SetFighterVehicleFunctions(vehicleInfo_t *pVehInfo) { +#ifdef QAGAME // ONLY in SP or on server, not cgame + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; -#endif //game-only - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; +#endif // game-only + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef QAGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef QAGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -1727,33 +1411,31 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -void G_CreateFighterNPC( Vehicle_t **pVeh, const char *strType ) -{ +void G_CreateFighterNPC(Vehicle_t **pVeh, const char *strType) { // Allocate the Vehicle. #ifdef _JK2MP #ifdef QAGAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); #else - (*pVeh) = (Vehicle_t *) gi.Malloc( sizeof(Vehicle_t), TAG_G_ALLOC, qtrue ); + (*pVeh) = (Vehicle_t *)gi.Malloc(sizeof(Vehicle_t), TAG_G_ALLOC, qtrue); #endif - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strType)]; } #ifdef _JK2MP #include "../namespace_end.h" -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins diff --git a/code/game/G_Timer.cpp b/code/game/G_Timer.cpp index 028613a4bd..32da0617ff 100644 --- a/code/game/G_Timer.cpp +++ b/code/game/G_Timer.cpp @@ -25,27 +25,23 @@ along with this program; if not, see . #include "../Rufl/hstring.h" #include "qcommon/ojk_saved_game_helper.h" -#define MAX_GTIMERS 16384 +#define MAX_GTIMERS 16384 -typedef struct gtimer_s -{ - hstring id; // Use handle strings, so that things work after loading +typedef struct gtimer_s { + hstring id; // Use handle strings, so that things work after loading int time; - struct gtimer_s *next; // In either free list or current list + struct gtimer_s *next; // In either free list or current list } gtimer_t; -gtimer_t g_timerPool[ MAX_GTIMERS ]; -gtimer_t *g_timers[ MAX_GENTITIES ]; +gtimer_t g_timerPool[MAX_GTIMERS]; +gtimer_t *g_timers[MAX_GENTITIES]; gtimer_t *g_timerFreeList; - -static int TIMER_GetCount(int num) -{ +static int TIMER_GetCount(int num) { gtimer_t *p = g_timers[num]; int count = 0; - while (p) - { + while (p) { count++; p = p->next; } @@ -53,7 +49,6 @@ static int TIMER_GetCount(int num) return count; } - /* ------------------------- TIMER_RemoveHelper @@ -64,13 +59,11 @@ timer from the list and put it on the free list Doesn't do much error checking, only called below ------------------------- */ -static void TIMER_RemoveHelper( int num, gtimer_t *timer ) -{ +static void TIMER_RemoveHelper(int num, gtimer_t *timer) { gtimer_t *p = g_timers[num]; // Special case: first timer in list - if (p == timer) - { + if (p == timer) { g_timers[num] = g_timers[num]->next; p->next = g_timerFreeList; g_timerFreeList = p; @@ -78,8 +71,7 @@ static void TIMER_RemoveHelper( int num, gtimer_t *timer ) } // Find the predecessor - while (p->next != timer) - { + while (p->next != timer) { p = p->next; } @@ -90,28 +82,22 @@ static void TIMER_RemoveHelper( int num, gtimer_t *timer ) return; } - - - /* ------------------------- TIMER_Clear ------------------------- */ -void TIMER_Clear( void ) -{ +void TIMER_Clear(void) { int i; - for (i = 0; i < MAX_GENTITIES; i++) - { + for (i = 0; i < MAX_GENTITIES; i++) { g_timers[i] = NULL; } - for (i = 0; i < MAX_GTIMERS - 1; i++) - { - g_timerPool[i].next = &g_timerPool[i+1]; + for (i = 0; i < MAX_GTIMERS - 1; i++) { + g_timerPool[i].next = &g_timerPool[i + 1]; } - g_timerPool[MAX_GTIMERS-1].next = NULL; + g_timerPool[MAX_GTIMERS - 1].next = NULL; g_timerFreeList = &g_timerPool[0]; } @@ -121,22 +107,18 @@ TIMER_Clear ------------------------- */ -void TIMER_Clear( int idx ) -{ +void TIMER_Clear(int idx) { // rudimentary safety checks, might be other things to check? - if ( idx >= 0 && idx < MAX_GENTITIES ) - { + if (idx >= 0 && idx < MAX_GENTITIES) { gtimer_t *p = g_timers[idx]; // No timers at all -> do nothing - if (!p) - { + if (!p) { return; } // Find the end of this ents timer list - while (p->next) - { + while (p->next) { p = p->next; } @@ -148,59 +130,46 @@ void TIMER_Clear( int idx ) } } - /* ------------------------- TIMER_Save ------------------------- */ -void TIMER_Save( void ) -{ - int j; - gentity_t *ent; +void TIMER_Save(void) { + int j; + gentity_t *ent; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) - { + for (j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++) { unsigned char numTimers = TIMER_GetCount(j); - if ( !ent->inuse && numTimers) - { -// Com_Printf( "WARNING: ent with timers not inuse\n" ); + if (!ent->inuse && numTimers) { + // Com_Printf( "WARNING: ent with timers not inuse\n" ); assert(numTimers); - TIMER_Clear( j ); + TIMER_Clear(j); numTimers = 0; } - //Write out the timer information - saved_game.write_chunk( - INT_ID('T', 'I', 'M', 'E'), - numTimers); + // Write out the timer information + saved_game.write_chunk(INT_ID('T', 'I', 'M', 'E'), numTimers); gtimer_t *p = g_timers[j]; - assert ((numTimers && p) || (!numTimers && !p)); + assert((numTimers && p) || (!numTimers && !p)); - while(p) - { - const char *timerID = p->id.c_str(); - const int length = strlen(timerID) + 1; - const int time = p->time - level.time; //convert this back to delta so we can use SET after loading + while (p) { + const char *timerID = p->id.c_str(); + const int length = strlen(timerID) + 1; + const int time = p->time - level.time; // convert this back to delta so we can use SET after loading - assert( length < 1024 );//This will cause problems when loading the timer if longer + assert(length < 1024); // This will cause problems when loading the timer if longer - //Write out the id string - saved_game.write_chunk( - INT_ID('T', 'M', 'I', 'D'), - timerID, - length); + // Write out the id string + saved_game.write_chunk(INT_ID('T', 'M', 'I', 'D'), timerID, length); - //Write out the timer data - saved_game.write_chunk( - INT_ID('T', 'D', 'T', 'A'), - time); + // Write out the timer data + saved_game.write_chunk(INT_ID('T', 'D', 'T', 'A'), time); p = p->next; } @@ -213,75 +182,56 @@ TIMER_Load ------------------------- */ -void TIMER_Load( void ) -{ +void TIMER_Load(void) { int j; - gentity_t *ent; + gentity_t *ent; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) - { + for (j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++) { unsigned char numTimers = 0; - saved_game.read_chunk( - INT_ID('T', 'I', 'M', 'E'), - numTimers); + saved_game.read_chunk(INT_ID('T', 'I', 'M', 'E'), numTimers); - //Read back all entries - for ( int i = 0; i < numTimers; i++ ) - { - int time = 0; - char tempBuffer[1024]; // Still ugly. Setting ourselves up for 007 AUF all over again. =) + // Read back all entries + for (int i = 0; i < numTimers; i++) { + int time = 0; + char tempBuffer[1024]; // Still ugly. Setting ourselves up for 007 AUF all over again. =) - assert (sizeof(g_timers[0]->time) == sizeof(time) );//make sure we're reading the same size as we wrote + assert(sizeof(g_timers[0]->time) == sizeof(time)); // make sure we're reading the same size as we wrote - //Read the id string and time - saved_game.read_chunk( - INT_ID('T', 'M', 'I', 'D')); + // Read the id string and time + saved_game.read_chunk(INT_ID('T', 'M', 'I', 'D')); - const char* sg_buffer_data = static_cast( - saved_game.get_buffer_data()); + const char *sg_buffer_data = static_cast(saved_game.get_buffer_data()); int sg_buffer_size = saved_game.get_buffer_size(); - if (sg_buffer_size < 0 || static_cast(sg_buffer_size) >= sizeof(tempBuffer)) - { + if (sg_buffer_size < 0 || static_cast(sg_buffer_size) >= sizeof(tempBuffer)) { ::G_Error("invalid length for TMID string in saved game: %d\n", sg_buffer_size); } - std::uninitialized_copy_n( - sg_buffer_data, - sg_buffer_size, - tempBuffer); + std::uninitialized_copy_n(sg_buffer_data, sg_buffer_size, tempBuffer); tempBuffer[sg_buffer_size] = '\0'; - saved_game.read_chunk( - INT_ID('T', 'D', 'T', 'A'), - time); + saved_game.read_chunk(INT_ID('T', 'D', 'T', 'A'), time); - //this is odd, we saved all the timers in the autosave, but not all the ents are spawned yet from an auto load, so skip it - if (ent->inuse) - { //Restore it + // this is odd, we saved all the timers in the autosave, but not all the ents are spawned yet from an auto load, so skip it + if (ent->inuse) { // Restore it TIMER_Set(ent, tempBuffer, time); } } } } - -static gtimer_t *TIMER_GetNew(int num, const char *identifier) -{ - assert(num < ENTITYNUM_MAX_NORMAL);//don't want timers on NONE or the WORLD +static gtimer_t *TIMER_GetNew(int num, const char *identifier) { + assert(num < ENTITYNUM_MAX_NORMAL); // don't want timers on NONE or the WORLD gtimer_t *p = g_timers[num]; // Search for an existing timer with this name - while (p) - { - if (p->id == identifier) - { // Found it + while (p) { + if (p->id == identifier) { // Found it return p; } @@ -289,8 +239,7 @@ static gtimer_t *TIMER_GetNew(int num, const char *identifier) } // No existing timer with this name was found, so grab one from the free list - if (!g_timerFreeList) - {//oh no, none free! + if (!g_timerFreeList) { // oh no, none free! assert(g_timerFreeList); return NULL; } @@ -302,15 +251,11 @@ static gtimer_t *TIMER_GetNew(int num, const char *identifier) return p; } - -gtimer_t *TIMER_GetExisting(int num, const char *identifier) -{ +gtimer_t *TIMER_GetExisting(int num, const char *identifier) { gtimer_t *p = g_timers[num]; - while (p) - { - if (p->id == identifier) - { // Found it + while (p) { + if (p->id == identifier) { // Found it return p; } @@ -320,22 +265,18 @@ gtimer_t *TIMER_GetExisting(int num, const char *identifier) return NULL; } - - /* ------------------------- TIMER_Set ------------------------- */ -void TIMER_Set( gentity_t *ent, const char *identifier, int duration ) -{ +void TIMER_Set(gentity_t *ent, const char *identifier, int duration) { assert(ent->inuse); gtimer_t *timer = TIMER_GetNew(ent->s.number, identifier); - if (timer) - { - timer->id = identifier; + if (timer) { + timer->id = identifier; timer->time = level.time + duration; } } @@ -346,12 +287,10 @@ TIMER_Get ------------------------- */ -int TIMER_Get( gentity_t *ent, const char *identifier ) -{ +int TIMER_Get(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return -1; } @@ -364,12 +303,10 @@ TIMER_Done ------------------------- */ -qboolean TIMER_Done( gentity_t *ent, const char *identifier ) -{ +qboolean TIMER_Done(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return qtrue; } @@ -386,20 +323,17 @@ timer was never started ------------------------- */ -qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) -{ +qboolean TIMER_Done2(gentity_t *ent, const char *identifier, qboolean remove) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); qboolean res; - if (!timer) - { + if (!timer) { return qfalse; } res = (qboolean)(timer->time < level.time); - if (res && remove) - { + if (res && remove) { // Put it back on the free list TIMER_RemoveHelper(ent->s.number, timer); } @@ -412,12 +346,7 @@ qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) TIMER_Exists ------------------------- */ -qboolean TIMER_Exists( gentity_t *ent, const char *identifier ) -{ - return (qboolean)(TIMER_GetExisting(ent->s.number, identifier) != NULL); -} - - +qboolean TIMER_Exists(gentity_t *ent, const char *identifier) { return (qboolean)(TIMER_GetExisting(ent->s.number, identifier) != NULL); } /* ------------------------- @@ -425,12 +354,10 @@ TIMER_Remove Utility to get rid of any timer ------------------------- */ -void TIMER_Remove( gentity_t *ent, const char *identifier ) -{ +void TIMER_Remove(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return; } @@ -444,11 +371,9 @@ TIMER_Start ------------------------- */ -qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ) -{ - if ( TIMER_Done( self, identifier ) ) - { - TIMER_Set( self, identifier, duration ); +qboolean TIMER_Start(gentity_t *self, const char *identifier, int duration) { + if (TIMER_Done(self, identifier)) { + TIMER_Set(self, identifier, duration); return qtrue; } return qfalse; diff --git a/code/game/NPC.cpp b/code/game/NPC.cpp index d1c794e0e0..3bcd14b4c7 100644 --- a/code/game/NPC.cpp +++ b/code/game/NPC.cpp @@ -33,102 +33,93 @@ along with this program; if not, see . extern vec3_t playerMins; extern vec3_t playerMaxs; -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void NPC_BSNoClip ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_ApplyRoff (void); -extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern void NPC_CheckPlayerAim ( void ); -extern void NPC_CheckAllClear ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void Mark1_dying( gentity_t *self ); -extern void NPC_BSCinematic( void ); -extern int GetTime ( int lastTime ); -extern void G_CheckCharmed( gentity_t *self ); -extern qboolean Boba_Flying( gentity_t *self ); -extern qboolean RT_Flying( gentity_t *self ); -extern qboolean Jedi_CultistDestroyer( gentity_t *self ); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void NPC_BSNoClip(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_ApplyRoff(void); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern void NPC_CheckPlayerAim(void); +extern void NPC_CheckAllClear(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void Mark1_dying(gentity_t *self); +extern void NPC_BSCinematic(void); +extern int GetTime(int lastTime); +extern void G_CheckCharmed(gentity_t *self); +extern qboolean Boba_Flying(gentity_t *self); +extern qboolean RT_Flying(gentity_t *self); +extern qboolean Jedi_CultistDestroyer(gentity_t *self); extern void Boba_Update(); extern bool Boba_Flee(); extern bool Boba_Tactics(); extern void BubbleShield_Update(); -extern qboolean PM_LockedAnim( int anim ); - -extern cvar_t *g_dismemberment; -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *g_corpseRemovalTime; -extern cvar_t *debug_subdivision; - -//Local Variables -// ai debug cvars -cvar_t *debugNPCAI; // used to print out debug info about the bot AI -cvar_t *debugNPCFreeze; // set to disable bot ai and temporarily freeze them in place -cvar_t *debugNPCName; -cvar_t *d_saberCombat; -cvar_t *d_JediAI; -cvar_t *d_noGroupAI; -cvar_t *d_asynchronousGroupAI; -cvar_t *d_slowmodeath; - -extern qboolean stop_icarus; - -gentity_t *NPC; -gNPC_t *NPCInfo; -gclient_t *client; -usercmd_t ucmd; -visibility_t enemyVisibility; - -void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -static bState_t G_CurrentBState( gNPC_t *gNPC ); +extern qboolean PM_LockedAnim(int anim); + +extern cvar_t *g_dismemberment; +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *g_corpseRemovalTime; +extern cvar_t *debug_subdivision; + +// Local Variables +// ai debug cvars +cvar_t *debugNPCAI; // used to print out debug info about the bot AI +cvar_t *debugNPCFreeze; // set to disable bot ai and temporarily freeze them in place +cvar_t *debugNPCName; +cvar_t *d_saberCombat; +cvar_t *d_JediAI; +cvar_t *d_noGroupAI; +cvar_t *d_asynchronousGroupAI; +cvar_t *d_slowmodeath; + +extern qboolean stop_icarus; + +gentity_t *NPC; +gNPC_t *NPCInfo; +gclient_t *client; +usercmd_t ucmd; +visibility_t enemyVisibility; + +void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +static bState_t G_CurrentBState(gNPC_t *gNPC); extern int eventClearTime; -void CorpsePhysics( gentity_t *self ) -{ +void CorpsePhysics(gentity_t *self) { // run the bot through the server like it was a real client - memset( &ucmd, 0, sizeof( ucmd ) ); - ClientThink( self->s.number, &ucmd ); - VectorCopy( self->s.origin, self->s.origin2 ); + memset(&ucmd, 0, sizeof(ucmd)); + ClientThink(self->s.number, &ucmd); + VectorCopy(self->s.origin, self->s.origin2); - //FIXME: match my pitch and roll for the slope of my groundPlane - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->flags&FL_DISINTEGRATED) ) - {//on the ground - //FIXME: check 4 corners - pitch_roll_for_slope( self ); + // FIXME: match my pitch and roll for the slope of my groundPlane + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->flags & FL_DISINTEGRATED)) { // on the ground + // FIXME: check 4 corners + pitch_roll_for_slope(self); } - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - if ( !(self->client->ps.eFlags&EF_NODRAW) ) - { - AddSightEvent( self->enemy, self->currentOrigin, 384, AEL_DISCOVERED ); + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + if (!(self->client->ps.eFlags & EF_NODRAW)) { + AddSightEvent(self->enemy, self->currentOrigin, 384, AEL_DISCOVERED); } } - if ( level.time - self->s.time > 3000 ) - {//been dead for 3 seconds - if ( !debug_subdivision->integer && !g_saberRealisticCombat->integer ) - {//can't be dismembered once dead - if ( self->client->NPC_class != CLASS_PROTOCOL ) - { + if (level.time - self->s.time > 3000) { // been dead for 3 seconds + if (!debug_subdivision->integer && !g_saberRealisticCombat->integer) { // can't be dismembered once dead + if (self->client->NPC_class != CLASS_PROTOCOL) { self->client->dismembered = true; } } } - if ( level.time - self->s.time > 500 ) - {//don't turn "nonsolid" until about 1 second after actual death + if (level.time - self->s.time > 500) { // don't turn "nonsolid" until about 1 second after actual death - if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. + if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. { self->contents = CONTENTS_CORPSE; } - if ( self->message ) - { + if (self->message) { self->contents |= CONTENTS_TRIGGER; } } @@ -141,165 +132,130 @@ NPC_RemoveBody Determines when it's ok to ditch the corpse ---------------------------------------- */ -#define REMOVE_DISTANCE 128 +#define REMOVE_DISTANCE 128 #define REMOVE_DISTANCE_SQR (REMOVE_DISTANCE * REMOVE_DISTANCE) -extern qboolean InFOVFromPlayerView ( gentity_t *ent, int hFOV, int vFOV ); -qboolean G_OkayToRemoveCorpse( gentity_t *self ) -{ - //if we're still on a vehicle, we won't remove ourselves until we get ejected - if ( self->client && self->client->NPC_class != CLASS_VEHICLE && self->s.m_iVehicleNum != 0 ) - { +extern qboolean InFOVFromPlayerView(gentity_t *ent, int hFOV, int vFOV); +qboolean G_OkayToRemoveCorpse(gentity_t *self) { + // if we're still on a vehicle, we won't remove ourselves until we get ejected + if (self->client && self->client->NPC_class != CLASS_VEHICLE && self->s.m_iVehicleNum != 0) { Vehicle_t *pVeh = g_entities[self->s.m_iVehicleNum].m_pVehicle; - if ( pVeh ) - { - if ( !pVeh->m_pVehicleInfo->Eject( pVeh, self, qtrue ) ) - {//dammit, still can't get off the vehicle... + if (pVeh) { + if (!pVeh->m_pVehicleInfo->Eject(pVeh, self, qtrue)) { // dammit, still can't get off the vehicle... return qfalse; } - } - else - { + } else { assert(0); #ifndef FINAL_BUILD - Com_Printf(S_COLOR_RED"ERROR: Dead pilot's vehicle removed while corpse was riding it (pilot: %s)???\n",self->targetname); + Com_Printf(S_COLOR_RED "ERROR: Dead pilot's vehicle removed while corpse was riding it (pilot: %s)???\n", self->targetname); #endif } } - if ( self->message ) - {//I still have a key + if (self->message) { // I still have a key return qfalse; } - if ( IIcarusInterface::GetIcarus()->IsRunning( self->m_iIcarusID ) ) - {//still running a script + if (IIcarusInterface::GetIcarus()->IsRunning(self->m_iIcarusID)) { // still running a script return qfalse; } - if ( self->activator - && self->activator->client - && ((self->activator->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (self->activator->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - || (self->activator->client->ps.eFlags&EF_HELD_BY_WAMPA)) ) - {//still holding a victim? + if (self->activator && self->activator->client && + ((self->activator->client->ps.eFlags & EF_HELD_BY_RANCOR) || (self->activator->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) || + (self->activator->client->ps.eFlags & EF_HELD_BY_WAMPA))) { // still holding a victim? return qfalse; } - if ( self->client - && ((self->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (self->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - || (self->client->ps.eFlags&EF_HELD_BY_WAMPA) ) ) - {//being held by a creature + if (self->client && ((self->client->ps.eFlags & EF_HELD_BY_RANCOR) || (self->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) || + (self->client->ps.eFlags & EF_HELD_BY_WAMPA))) { // being held by a creature return qfalse; } - if ( self->client->ps.heldByClient < ENTITYNUM_WORLD ) - {//being dragged + if (self->client->ps.heldByClient < ENTITYNUM_WORLD) { // being dragged return qfalse; } - //okay, well okay to remove us...? + // okay, well okay to remove us...? return qtrue; } -void NPC_RemoveBody( gentity_t *self ) -{ - self->nextthink = level.time + FRAMETIME/2; +void NPC_RemoveBody(gentity_t *self) { + self->nextthink = level.time + FRAMETIME / 2; - //run physics at 20fps - CorpsePhysics( self ); + // run physics at 20fps + CorpsePhysics(self); - if ( self->NPC->nextBStateThink <= level.time ) - {//run logic at 10 fps - if( self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( self->m_iIcarusID ); + if (self->NPC->nextBStateThink <= level.time) { // run logic at 10 fps + if (self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(self->m_iIcarusID); } self->NPC->nextBStateThink = level.time + FRAMETIME; - if ( !G_OkayToRemoveCorpse( self ) ) - { + if (!G_OkayToRemoveCorpse(self)) { return; } // I don't consider this a hack, it's creative coding . . . // I agree, very creative... need something like this for ATST and GALAKMECH too! - if (self->client->NPC_class == CLASS_MARK1) - { - Mark1_dying( self ); + if (self->client->NPC_class == CLASS_MARK1) { + Mark1_dying(self); } // Since these blow up, remove the bounding box. - if ( self->client->NPC_class == CLASS_REMOTE - || self->client->NPC_class == CLASS_SENTRY - || self->client->NPC_class == CLASS_PROBE - || self->client->NPC_class == CLASS_INTERROGATOR - || self->client->NPC_class == CLASS_PROBE - || self->client->NPC_class == CLASS_MARK2 ) - { - G_FreeEntity( self ); + if (self->client->NPC_class == CLASS_REMOTE || self->client->NPC_class == CLASS_SENTRY || self->client->NPC_class == CLASS_PROBE || + self->client->NPC_class == CLASS_INTERROGATOR || self->client->NPC_class == CLASS_PROBE || self->client->NPC_class == CLASS_MARK2) { + G_FreeEntity(self); return; } - //FIXME: don't ever inflate back up? + // FIXME: don't ever inflate back up? self->maxs[2] = self->client->renderInfo.eyePoint[2] - self->currentOrigin[2] + 4; - if ( self->maxs[2] < -8 ) - { + if (self->maxs[2] < -8) { self->maxs[2] = -8; } - if ( (self->NPC->aiFlags&NPCAI_HEAL_ROSH) ) - {//kothos twins' bodies are never removed + if ((self->NPC->aiFlags & NPCAI_HEAL_ROSH)) { // kothos twins' bodies are never removed return; } - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//never disappears + if (self->client->NPC_class == CLASS_GALAKMECH) { // never disappears return; } - if ( self->NPC && self->NPC->timeOfDeath <= level.time ) - { + if (self->NPC && self->NPC->timeOfDeath <= level.time) { self->NPC->timeOfDeath = level.time + 1000; // Only do all of this nonsense for Scav boys ( and girls ) - /// if ( self->client->playerTeam == TEAM_SCAVENGERS || self->client->playerTeam == TEAM_KLINGON - // || self->client->playerTeam == TEAM_HIROGEN || self->client->playerTeam == TEAM_MALON ) + /// if ( self->client->playerTeam == TEAM_SCAVENGERS || self->client->playerTeam == TEAM_KLINGON + // || self->client->playerTeam == TEAM_HIROGEN || self->client->playerTeam == TEAM_MALON ) // should I check NPC_class here instead of TEAM ? - dmv - if( self->client->playerTeam == TEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL ) - { + if (self->client->playerTeam == TEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL) { self->nextthink = level.time + FRAMETIME; // try back in a second - if ( DistanceSquared( g_entities[0].currentOrigin, self->currentOrigin ) <= REMOVE_DISTANCE_SQR ) - { + if (DistanceSquared(g_entities[0].currentOrigin, self->currentOrigin) <= REMOVE_DISTANCE_SQR) { return; } - if ( (InFOVFromPlayerView( self, 110, 90 )) ) // generous FOV check + if ((InFOVFromPlayerView(self, 110, 90))) // generous FOV check { - if ( (NPC_ClearLOS( &g_entities[0], self->currentOrigin )) ) - { + if ((NPC_ClearLOS(&g_entities[0], self->currentOrigin))) { return; } } } - //FIXME: there are some conditions - such as heavy combat - in which we want + // FIXME: there are some conditions - such as heavy combat - in which we want // to remove the bodies... but in other cases it's just weird, like // when they're right behind you in a closed room and when they've been // placed as dead NPCs by a designer... // For now we just assume that a corpse with no enemy was // placed in the map as a corpse - if ( self->enemy ) - { - if ( self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD ) - { + if (self->enemy) { + if (self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD) { gentity_t *saberent = &g_entities[self->client->ps.saberEntityNum]; - if ( saberent ) - { - G_FreeEntity( saberent ); + if (saberent) { + G_FreeEntity(saberent); } } - G_FreeEntity( self ); + G_FreeEntity(self); } } } @@ -313,21 +269,19 @@ Determines when it's ok to ditch the corpse ---------------------------------------- */ -int BodyRemovalPadTime( gentity_t *ent ) -{ - int time; +int BodyRemovalPadTime(gentity_t *ent) { + int time; - if ( !ent || !ent->client ) + if (!ent || !ent->client) return 0; // team no longer indicates species/race, so in this case we'd use NPC_class, but - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_MOUSE: case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_PROBE: @@ -339,23 +293,17 @@ int BodyRemovalPadTime( gentity_t *ent ) break; default: // never go away - if ( g_corpseRemovalTime->integer <= 0 ) - { + if (g_corpseRemovalTime->integer <= 0) { time = Q3_INFINITE; - } - else - { - time = g_corpseRemovalTime->integer*1000; + } else { + time = g_corpseRemovalTime->integer * 1000; } break; - } - return time; } - /* ---------------------------------------- NPC_RemoveBodyEffect @@ -364,19 +312,17 @@ Effect to be applied when ditching the corpse ---------------------------------------- */ -static void NPC_RemoveBodyEffect(void) -{ -// vec3_t org; -// gentity_t *tent; +static void NPC_RemoveBodyEffect(void) { + // vec3_t org; + // gentity_t *tent; - if ( !NPC || !NPC->client || (NPC->s.eFlags & EF_NODRAW) ) + if (!NPC || !NPC->client || (NPC->s.eFlags & EF_NODRAW)) return; // team no longer indicates species/race, so in this case we'd use NPC_class, but // stub code - switch(NPC->client->NPC_class) - { + switch (NPC->client->NPC_class) { case CLASS_PROBE: case CLASS_SEEKER: case CLASS_REMOTE: @@ -384,24 +330,21 @@ static void NPC_RemoveBodyEffect(void) case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_INTERROGATOR: case CLASS_ATST: // yeah, this is a little weird, but for now I'm listing all droids - // VectorCopy( NPC->currentOrigin, org ); - // org[2] -= 16; - // tent = G_TempEntity( org, EV_BOT_EXPLODE ); - // tent->owner = NPC; + // VectorCopy( NPC->currentOrigin, org ); + // org[2] -= 16; + // tent = G_TempEntity( org, EV_BOT_EXPLODE ); + // tent->owner = NPC; break; default: break; } - - } - /* ==================================================================== void pitch_roll_for_slope (edict_t *forwhom, vec3_t *slope, vec3_t storeAngles ) @@ -416,97 +359,83 @@ and returns. ==================================================================== */ -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope, vec3_t storeAngles, qboolean keepPitch ) -{ - vec3_t slope; - vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = { 0, 0, 0 }; - float pitch, mod, dot; +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope, vec3_t storeAngles, qboolean keepPitch) { + vec3_t slope; + vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = {0, 0, 0}; + float pitch, mod, dot; - //if we don't have a slope, get one - if( !pass_slope || VectorCompare( vec3_origin, pass_slope ) ) - { + // if we don't have a slope, get one + if (!pass_slope || VectorCompare(vec3_origin, pass_slope)) { trace_t trace; - VectorCopy( forwhom->currentOrigin, startspot ); + VectorCopy(forwhom->currentOrigin, startspot); startspot[2] += forwhom->mins[2] + 4; - VectorCopy( startspot, endspot ); + VectorCopy(startspot, endspot); endspot[2] -= 300; - gi.trace( &trace, forwhom->currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); -// if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) -// forwhom.flags(-)FL_ONGROUND; + gi.trace(&trace, forwhom->currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, (EG2_Collision)0, 0); + // if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) + // forwhom.flags(-)FL_ONGROUND; - if ( trace.fraction >= 1.0 ) + if (trace.fraction >= 1.0) return; - if ( VectorCompare( vec3_origin, trace.plane.normal ) ) + if (VectorCompare(vec3_origin, trace.plane.normal)) return; - VectorCopy( trace.plane.normal, slope ); - } - else - { - VectorCopy( pass_slope, slope ); + VectorCopy(trace.plane.normal, slope); + } else { + VectorCopy(pass_slope, slope); } float oldPitch = 0; - if ( forwhom->client && forwhom->client->NPC_class == CLASS_VEHICLE ) - {//special code for vehicles + if (forwhom->client && forwhom->client->NPC_class == CLASS_VEHICLE) { // special code for vehicles Vehicle_t *pVeh = forwhom->m_pVehicle; vec3_t tempAngles; tempAngles[PITCH] = tempAngles[ROLL] = 0; tempAngles[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( tempAngles, ovf, ovr, NULL ); - } - else - { + AngleVectors(tempAngles, ovf, ovr, NULL); + } else { oldPitch = forwhom->currentAngles[PITCH]; - AngleVectors( forwhom->currentAngles, ovf, ovr, NULL ); + AngleVectors(forwhom->currentAngles, ovf, ovr, NULL); } - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; - if ( keepPitch ) - { + if (keepPitch) { pitch += oldPitch; } new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod<0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); - if ( storeAngles ) - { + if (storeAngles) { storeAngles[PITCH] = dot * pitch; - storeAngles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); - } - else if ( forwhom->client ) - { + storeAngles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); + } else if (forwhom->client) { forwhom->client->ps.viewangles[PITCH] = dot * pitch; - forwhom->client->ps.viewangles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->client->ps.viewangles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); float oldmins2 = forwhom->mins[2]; - forwhom->mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH])/180.0f; - //FIXME: if it gets bigger, move up - if ( oldmins2 > forwhom->mins[2] ) - {//our mins is now lower, need to move up - //FIXME: trace? + forwhom->mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH]) / 180.0f; + // FIXME: if it gets bigger, move up + if (oldmins2 > forwhom->mins[2]) { // our mins is now lower, need to move up + // FIXME: trace? forwhom->client->ps.origin[2] += (oldmins2 - forwhom->mins[2]); forwhom->currentOrigin[2] = forwhom->client->ps.origin[2]; - gi.linkentity( forwhom ); + gi.linkentity(forwhom); } - } - else - { + } else { forwhom->currentAngles[PITCH] = dot * pitch; - forwhom->currentAngles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->currentAngles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } } @@ -751,24 +680,20 @@ void NPC_PostDeathThink( void ) DeadThink ---------------------------------------- */ -static void DeadThink ( void ) -{ - trace_t trace; - //HACKHACKHACKHACKHACK - //We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only - //FIXME: don't ever inflate back up? - //GAH! With Ragdoll, they get stuck in the ceiling +static void DeadThink(void) { + trace_t trace; + // HACKHACKHACKHACKHACK + // We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only + // FIXME: don't ever inflate back up? + // GAH! With Ragdoll, they get stuck in the ceiling float oldMaxs2 = NPC->maxs[2]; NPC->maxs[2] = NPC->client->renderInfo.eyePoint[2] - NPC->currentOrigin[2] + 4; - if ( NPC->maxs[2] < -8 ) - { + if (NPC->maxs[2] < -8) { NPC->maxs[2] = -8; } - if ( NPC->maxs[2] > oldMaxs2 ) - {//inflating maxs, make sure we're not inflating into solid - gi.trace (&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.allsolid ) - {//must be inflating + if (NPC->maxs[2] > oldMaxs2) { // inflating maxs, make sure we're not inflating into solid + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.allsolid) { // must be inflating NPC->maxs[2] = oldMaxs2; } } @@ -817,9 +742,8 @@ static void DeadThink ( void ) //HACKHACKHACKHACKHACK */ - - //FIXME: tilt and fall off of ledges? - //NPC_PostDeathThink(); + // FIXME: tilt and fall off of ledges? + // NPC_PostDeathThink(); /* if ( !NPCInfo->timeOfDeath && NPC->client != NULL && NPCInfo != NULL ) @@ -840,39 +764,32 @@ static void DeadThink ( void ) else */ { - //death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove - if ( level.time >= NPCInfo->timeOfDeath + BodyRemovalPadTime( NPC ) ) - { - if ( NPC->client->ps.eFlags & EF_NODRAW ) - { - if ( !IIcarusInterface::GetIcarus()->IsRunning( NPC->m_iIcarusID ) ) - { + // death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove + if (level.time >= NPCInfo->timeOfDeath + BodyRemovalPadTime(NPC)) { + if (NPC->client->ps.eFlags & EF_NODRAW) { + if (!IIcarusInterface::GetIcarus()->IsRunning(NPC->m_iIcarusID)) { NPC->e_ThinkFunc = thinkF_G_FreeEntity; NPC->nextthink = level.time + FRAMETIME; } - } - else - { + } else { // Start the body effect first, then delay 400ms before ditching the corpse NPC_RemoveBodyEffect(); - //FIXME: keep it running through physics somehow? + // FIXME: keep it running through physics somehow? NPC->e_ThinkFunc = thinkF_NPC_RemoveBody; - NPC->nextthink = level.time + FRAMETIME/2; - // if ( NPC->client->playerTeam == TEAM_FORGE ) - // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - // else if ( NPC->client->playerTeam == TEAM_BOTS ) - class_t npc_class = NPC->client->NPC_class; + NPC->nextthink = level.time + FRAMETIME / 2; + // if ( NPC->client->playerTeam == TEAM_FORGE ) + // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; + // else if ( NPC->client->playerTeam == TEAM_BOTS ) + class_t npc_class = NPC->client->NPC_class; // check for droids - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_MARK2 || npc_class == CLASS_SENTRY )//npc_class == CLASS_PROTOCOL || + if (npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_MARK2 || + npc_class == CLASS_SENTRY) // npc_class == CLASS_PROTOCOL || { NPC->client->ps.eFlags |= EF_NODRAW; NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - } - else - { + } else { NPCInfo->timeOfDeath = level.time + FRAMETIME * 4; } } @@ -881,18 +798,16 @@ static void DeadThink ( void ) } // If the player is on the ground and the resting position contents haven't been set yet...(BounceCount tracks the contents) - if ( NPC->bounceCount < 0 && NPC->s.groundEntityNum >= 0 ) - { + if (NPC->bounceCount < 0 && NPC->s.groundEntityNum >= 0) { // if client is in a nodrop area, make him/her nodraw - int contents = NPC->bounceCount = gi.pointcontents( NPC->currentOrigin, -1 ); + int contents = NPC->bounceCount = gi.pointcontents(NPC->currentOrigin, -1); - if ( ( contents & CONTENTS_NODROP ) ) - { + if ((contents & CONTENTS_NODROP)) { NPC->client->ps.eFlags |= EF_NODRAW; } } - CorpsePhysics( NPC ); + CorpsePhysics(NPC); } /* @@ -902,136 +817,112 @@ SetNPCGlobals local function to set globals used throughout the AI code =============== */ -void SetNPCGlobals( gentity_t *ent ) -{ +void SetNPCGlobals(gentity_t *ent) { NPC = ent; NPCInfo = ent->NPC; client = ent->client; - memset( &ucmd, 0, sizeof( usercmd_t ) ); + memset(&ucmd, 0, sizeof(usercmd_t)); } -gentity_t *_saved_NPC; -gNPC_t *_saved_NPCInfo; -gclient_t *_saved_client; -usercmd_t _saved_ucmd; +gentity_t *_saved_NPC; +gNPC_t *_saved_NPCInfo; +gclient_t *_saved_client; +usercmd_t _saved_ucmd; -void SaveNPCGlobals() -{ +void SaveNPCGlobals() { _saved_NPC = NPC; _saved_NPCInfo = NPCInfo; _saved_client = client; - memcpy( &_saved_ucmd, &ucmd, sizeof( usercmd_t ) ); + memcpy(&_saved_ucmd, &ucmd, sizeof(usercmd_t)); } -void RestoreNPCGlobals() -{ +void RestoreNPCGlobals() { NPC = _saved_NPC; NPCInfo = _saved_NPCInfo; client = _saved_client; - memcpy( &ucmd, &_saved_ucmd, sizeof( usercmd_t ) ); + memcpy(&ucmd, &_saved_ucmd, sizeof(usercmd_t)); } -//We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC -void ClearNPCGlobals( void ) -{ +// We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC +void ClearNPCGlobals(void) { NPC = NULL; NPCInfo = NULL; client = NULL; } //=============== -extern qboolean showBBoxes; +extern qboolean showBBoxes; vec3_t NPCDEBUG_RED = {1.0, 0.0, 0.0}; vec3_t NPCDEBUG_GREEN = {0.0, 1.0, 0.0}; vec3_t NPCDEBUG_BLUE = {0.0, 0.0, 1.0}; vec3_t NPCDEBUG_LIGHT_BLUE = {0.3f, 0.7f, 1.0}; -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); - -void NPC_ShowDebugInfo (void) -{ - if ( showBBoxes ) - { - gentity_t *found = NULL; - vec3_t mins, maxs; - - //do player, too - VectorAdd( player->currentOrigin, player->mins, mins ); - VectorAdd( player->currentOrigin, player->maxs, maxs ); - CG_Cube( mins, maxs, NPCDEBUG_RED, 0.25 ); - //do NPCs - while( (found = G_Find( found, FOFS(classname), "NPC" ) ) != NULL ) - { - if ( gi.inPVS( found->currentOrigin, g_entities[0].currentOrigin ) ) - { - VectorAdd( found->currentOrigin, found->mins, mins ); - VectorAdd( found->currentOrigin, found->maxs, maxs ); - CG_Cube( mins, maxs, NPCDEBUG_RED, 0.25 ); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); + +void NPC_ShowDebugInfo(void) { + if (showBBoxes) { + gentity_t *found = NULL; + vec3_t mins, maxs; + + // do player, too + VectorAdd(player->currentOrigin, player->mins, mins); + VectorAdd(player->currentOrigin, player->maxs, maxs); + CG_Cube(mins, maxs, NPCDEBUG_RED, 0.25); + // do NPCs + while ((found = G_Find(found, FOFS(classname), "NPC")) != NULL) { + if (gi.inPVS(found->currentOrigin, g_entities[0].currentOrigin)) { + VectorAdd(found->currentOrigin, found->mins, mins); + VectorAdd(found->currentOrigin, found->maxs, maxs); + CG_Cube(mins, maxs, NPCDEBUG_RED, 0.25); } } } } -void NPC_ApplyScriptFlags (void) -{ - if ( NPCInfo->scriptFlags & SCF_CROUCHED ) - { - if ( NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the crouched command - } - else - { +void NPC_ApplyScriptFlags(void) { + if (NPCInfo->scriptFlags & SCF_CROUCHED) { + if (NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove)) { // ugh, if charmed and moving, ignore the crouched command + } else { ucmd.upmove = -127; } } - if(NPCInfo->scriptFlags & SCF_RUNNING) - { + if (NPCInfo->scriptFlags & SCF_RUNNING) { ucmd.buttons &= ~BUTTON_WALKING; - } - else if(NPCInfo->scriptFlags & SCF_WALKING) - { - if ( NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the walking command - } - else - { + } else if (NPCInfo->scriptFlags & SCF_WALKING) { + if (NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove)) { // ugh, if charmed and moving, ignore the walking command + } else { ucmd.buttons |= BUTTON_WALKING; } } -/* - if(NPCInfo->scriptFlags & SCF_CAREFUL) - { - ucmd.buttons |= BUTTON_CAREFUL; - } -*/ - if(NPCInfo->scriptFlags & SCF_LEAN_RIGHT) - { + /* + if(NPCInfo->scriptFlags & SCF_CAREFUL) + { + ucmd.buttons |= BUTTON_CAREFUL; + } + */ + if (NPCInfo->scriptFlags & SCF_LEAN_RIGHT) { ucmd.buttons |= BUTTON_USE; ucmd.rightmove = 127; ucmd.forwardmove = 0; ucmd.upmove = 0; - } - else if(NPCInfo->scriptFlags & SCF_LEAN_LEFT) - { + } else if (NPCInfo->scriptFlags & SCF_LEAN_LEFT) { ucmd.buttons |= BUTTON_USE; ucmd.rightmove = -127; ucmd.forwardmove = 0; ucmd.upmove = 0; } - if ( (NPCInfo->scriptFlags & SCF_ALT_FIRE) && (ucmd.buttons & BUTTON_ATTACK) ) - {//Use altfire instead + if ((NPCInfo->scriptFlags & SCF_ALT_FIRE) && (ucmd.buttons & BUTTON_ATTACK)) { // Use altfire instead ucmd.buttons |= BUTTON_ALT_ATTACK; } // only removes NPC when it's safe too (Player is out of PVS) - if( NPCInfo->scriptFlags & SCF_SAFE_REMOVE ) - { + if (NPCInfo->scriptFlags & SCF_SAFE_REMOVE) { // take from BSRemove - if( !gi.inPVS( NPC->currentOrigin, g_entities[0].currentOrigin ) )//FIXME: use cg.vieworg? + if (!gi.inPVS(NPC->currentOrigin, g_entities[0].currentOrigin)) // FIXME: use cg.vieworg? { - G_UseTargets2( NPC, NPC, NPC->target3 ); + G_UseTargets2(NPC, NPC, NPC->target3); NPC->s.eFlags |= EF_NODRAW; NPC->svFlags &= ~SVF_NPC; NPC->s.eType = ET_INVISIBLE; @@ -1039,219 +930,191 @@ void NPC_ApplyScriptFlags (void) NPC->health = 0; NPC->targetname = NULL; - //Disappear in half a second + // Disappear in half a second NPC->e_ThinkFunc = thinkF_G_FreeEntity; NPC->nextthink = level.time + FRAMETIME; - }//FIXME: else allow for out of FOV??? - + } // FIXME: else allow for out of FOV??? } } +extern qboolean JET_Flying(gentity_t *self); +extern void JET_FlyStart(gentity_t *self); +extern void JET_FlyStop(gentity_t *self); -extern qboolean JET_Flying( gentity_t *self ); -extern void JET_FlyStart( gentity_t *self ); -extern void JET_FlyStop( gentity_t *self ); - -void NPC_HandleAIFlags (void) -{ +void NPC_HandleAIFlags(void) { // Update Guys With Jet Packs //---------------------------- - if (NPCInfo->scriptFlags & SCF_FLY_WITH_JET) - { - bool ShouldFly = !!(NPCInfo->aiFlags & NPCAI_FLY); - bool IsFlying = !!(JET_Flying(NPC)); - bool IsInTheAir = (NPC->client->ps.groundEntityNum==ENTITYNUM_NONE); + if (NPCInfo->scriptFlags & SCF_FLY_WITH_JET) { + bool ShouldFly = !!(NPCInfo->aiFlags & NPCAI_FLY); + bool IsFlying = !!(JET_Flying(NPC)); + bool IsInTheAir = (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE); - if (IsFlying) - { + if (IsFlying) { // Don't Stop Flying Until Near The Ground //----------------------------------------- - if (IsInTheAir) - { - vec3_t ground; - trace_t trace; + if (IsInTheAir) { + vec3_t ground; + trace_t trace; VectorCopy(NPC->currentOrigin, ground); ground[2] -= 60.0f; - gi.trace(&trace, NPC->currentOrigin, 0, 0, ground, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + gi.trace(&trace, NPC->currentOrigin, 0, 0, ground, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); - IsInTheAir = (!trace.allsolid && !trace.startsolid && trace.fraction>0.9f); + IsInTheAir = (!trace.allsolid && !trace.startsolid && trace.fraction > 0.9f); } // If Flying, Remember The Last Time //----------------------------------- - if (IsInTheAir) - { + if (IsInTheAir) { NPC->lastInAirTime = level.time; ShouldFly = true; } - // Auto Turn Off Jet Pack After 1 Second On The Ground //----------------------------------------------------- - else if (!ShouldFly && (level.time - NPC->lastInAirTime)>3000) - { + else if (!ShouldFly && (level.time - NPC->lastInAirTime) > 3000) { NPCInfo->aiFlags &= ~NPCAI_FLY; } } - // If We Should Be Flying And Are Not, Start Er Up //------------------------------------------------- - if (ShouldFly && !IsFlying) - { - JET_FlyStart(NPC); // EVENTUALLY, Remove All Other Calls + if (ShouldFly && !IsFlying) { + JET_FlyStart(NPC); // EVENTUALLY, Remove All Other Calls } // Otherwise, If Needed, Shut It Off //----------------------------------- - else if (!ShouldFly && IsFlying) - { - JET_FlyStop(NPC); // EVENTUALLY, Remove All Other Calls + else if (!ShouldFly && IsFlying) { + JET_FlyStop(NPC); // EVENTUALLY, Remove All Other Calls } } - //FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers - if ( NPCInfo->aiFlags & NPCAI_LOST ) - {//Print that you need help! - //FIXME: shouldn't remove this just yet if cg_draw needs it + // FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers + if (NPCInfo->aiFlags & NPCAI_LOST) { // Print that you need help! + // FIXME: shouldn't remove this just yet if cg_draw needs it NPCInfo->aiFlags &= ~NPCAI_LOST; /* if ( showWaypoints ) { - Quake3Game()->DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, NPC->waypoint, NPCInfo->goalEntity->waypoint ); + Quake3Game()->DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, + NPC->waypoint, NPCInfo->goalEntity->waypoint ); } */ - if ( NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//We can't nav to our enemy - //Drop enemy and see if we should search for him + if (NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy) { // We can't nav to our enemy + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); } } - //been told to play a victory sound after a delay - if ( NPCInfo->greetingDebounceTime && NPCInfo->greetingDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand( 2000, 4000 ) ); + // been told to play a victory sound after a delay + if (NPCInfo->greetingDebounceTime && NPCInfo->greetingDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand(2000, 4000)); NPCInfo->greetingDebounceTime = 0; } - if ( NPCInfo->ffireCount > 0 ) - { - if ( NPCInfo->ffireFadeDebounce < level.time ) - { + if (NPCInfo->ffireCount > 0) { + if (NPCInfo->ffireFadeDebounce < level.time) { NPCInfo->ffireCount--; - //Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_spskill->integer)*2) ); + // Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_spskill->integer)*2) ); NPCInfo->ffireFadeDebounce = level.time + 3000; } } } -void NPC_AvoidWallsAndCliffs (void) -{ -/* - vec3_t forward, right, testPos, angles, mins; - trace_t trace; - float fwdDist, rtDist; - //FIXME: set things like this forward dir once at the beginning - //of a frame instead of over and over again - if ( NPCInfo->aiFlags & NPCAI_NO_COLL_AVOID ) - { - return; - } +void NPC_AvoidWallsAndCliffs(void) { + /* + vec3_t forward, right, testPos, angles, mins; + trace_t trace; + float fwdDist, rtDist; + //FIXME: set things like this forward dir once at the beginning + //of a frame instead of over and over again + if ( NPCInfo->aiFlags & NPCAI_NO_COLL_AVOID ) + { + return; + } - if ( ucmd.upmove > 0 || NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//Going to jump or in the air - return; - } + if ( ucmd.upmove > 0 || NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) + {//Going to jump or in the air + return; + } - if ( !ucmd.forwardmove && !ucmd.rightmove ) - { - return; - } + if ( !ucmd.forwardmove && !ucmd.rightmove ) + { + return; + } - if ( fabs( AngleDelta( NPC->currentAngles[YAW], NPCInfo->desiredYaw ) ) < 5.0 )//!ucmd.angles[YAW] ) - {//Not turning much, don't do this - //NOTE: Should this not happen only if you're not turning AT ALL? - // You could be turning slowly but moving fast, so that would - // still let you walk right off a cliff... - //NOTE: Or maybe it is a good idea to ALWAYS do this, regardless - // of whether ot not we're turning? But why would we be walking - // straight into a wall or off a cliff unless we really wanted to? - return; - } + if ( fabs( AngleDelta( NPC->currentAngles[YAW], NPCInfo->desiredYaw ) ) < 5.0 )//!ucmd.angles[YAW] ) + {//Not turning much, don't do this + //NOTE: Should this not happen only if you're not turning AT ALL? + // You could be turning slowly but moving fast, so that would + // still let you walk right off a cliff... + //NOTE: Or maybe it is a good idea to ALWAYS do this, regardless + // of whether ot not we're turning? But why would we be walking + // straight into a wall or off a cliff unless we really wanted to? + return; + } - VectorCopy( NPC->mins, mins ); - mins[2] += STEPSIZE; - angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); - fwdDist = ((float)ucmd.forwardmove)/16.0f; - rtDist = ((float)ucmd.rightmove)/16.0f; - VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); - VectorMA( testPos, rtDist, right, testPos ); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) - {//Going to bump into something, don't move, just turn - ucmd.forwardmove = 0; - ucmd.rightmove = 0; - return; - } + VectorCopy( NPC->mins, mins ); + mins[2] += STEPSIZE; + angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? + AngleVectors( angles, forward, right, NULL ); + fwdDist = ((float)ucmd.forwardmove)/16.0f; + rtDist = ((float)ucmd.rightmove)/16.0f; + VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); + VectorMA( testPos, rtDist, right, testPos ); + gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); + if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) + {//Going to bump into something, don't move, just turn + ucmd.forwardmove = 0; + ucmd.rightmove = 0; + return; + } - VectorCopy(trace.endpos, testPos); - testPos[2] -= 128; + VectorCopy(trace.endpos, testPos); + testPos[2] -= 128; - gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) - {//Not going off a cliff - return; - } + gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); + if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) + {//Not going off a cliff + return; + } - //going to fall at least 128, don't move, just turn... is this bad, though? What if we want them to drop off? - ucmd.forwardmove = 0; - ucmd.rightmove = 0; - return; -*/ + //going to fall at least 128, don't move, just turn... is this bad, though? What if we want them to drop off? + ucmd.forwardmove = 0; + ucmd.rightmove = 0; + return; + */ } -void NPC_CheckAttackScript(void) -{ - if(!(ucmd.buttons & BUTTON_ATTACK)) - { +void NPC_CheckAttackScript(void) { + if (!(ucmd.buttons & BUTTON_ATTACK)) { return; } G_ActivateBehavior(NPC, BSET_ATTACK); } -float NPC_MaxDistSquaredForWeapon (void); -void NPC_CheckAttackHold(void) -{ - vec3_t vec; +float NPC_MaxDistSquaredForWeapon(void); +void NPC_CheckAttackHold(void) { + vec3_t vec; // If they don't have an enemy they shouldn't hold their attack anim. - if ( !NPC->enemy ) - { + if (!NPC->enemy) { NPCInfo->attackHoldTime = 0; return; } - //FIXME: need to tie this into AI somehow? + // FIXME: need to tie this into AI somehow? VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); - if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) - { + if (VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon()) { NPCInfo->attackHoldTime = 0; - } - else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) - { + } else if (NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time) { ucmd.buttons |= BUTTON_ATTACK; - } - else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) - { + } else if ((NPCInfo->attackHold) && (ucmd.buttons & BUTTON_ATTACK)) { NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; - } - else - { + } else { NPCInfo->attackHoldTime = 0; } } @@ -1261,16 +1124,13 @@ void NPC_KeepCurrentFacing(void) Fills in a default ucmd to keep current angles facing */ -void NPC_KeepCurrentFacing(void) -{ - if(!ucmd.angles[YAW]) - { - ucmd.angles[YAW] = ANGLE2SHORT( client->ps.viewangles[YAW] ) - client->ps.delta_angles[YAW]; +void NPC_KeepCurrentFacing(void) { + if (!ucmd.angles[YAW]) { + ucmd.angles[YAW] = ANGLE2SHORT(client->ps.viewangles[YAW]) - client->ps.delta_angles[YAW]; } - if(!ucmd.angles[PITCH]) - { - ucmd.angles[PITCH] = ANGLE2SHORT( client->ps.viewangles[PITCH] ) - client->ps.delta_angles[PITCH]; + if (!ucmd.angles[PITCH]) { + ucmd.angles[PITCH] = ANGLE2SHORT(client->ps.viewangles[PITCH]) - client->ps.delta_angles[PITCH]; } } @@ -1280,27 +1140,25 @@ NPC_BehaviorSet_Charmed ------------------------- */ -void NPC_BehaviorSet_Charmed( int bState ) -{ - switch( bState ) - { - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across +void NPC_BehaviorSet_Charmed(int bState) { + switch (bState) { + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: NPC_BSFlee(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -1311,32 +1169,30 @@ NPC_BehaviorSet_Default ------------------------- */ -void NPC_BehaviorSet_Default( int bState ) -{ - switch( bState ) - { - case BS_ADVANCE_FIGHT://head toward captureGoal, shoot anything that gets in the way - NPC_BSAdvanceFight (); +void NPC_BehaviorSet_Default(int bState) { + switch (bState) { + case BS_ADVANCE_FIGHT: // head toward captureGoal, shoot anything that gets in the way + NPC_BSAdvanceFight(); break; - case BS_SLEEP://Follow a path, looking for enemies - NPC_BSSleep (); + case BS_SLEEP: // Follow a path, looking for enemies + NPC_BSSleep(); break; - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; - case BS_JUMP: //41: Face navgoal and jump to it. + case BS_JUMP: // 41: Face navgoal and jump to it. NPC_BSJump(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; case BS_NOCLIP: NPC_BSNoClip(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: @@ -1349,7 +1205,7 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BSCinematic(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -1360,10 +1216,8 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BehaviorSet_Interrogator ------------------------- */ -void NPC_BehaviorSet_Interrogator( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Interrogator(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1372,13 +1226,13 @@ void NPC_BehaviorSet_Interrogator( int bState ) NPC_BSInterrogator_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSImperialProbe_Attack( void ); -void NPC_BSImperialProbe_Patrol( void ); +void NPC_BSImperialProbe_Attack(void); +void NPC_BSImperialProbe_Patrol(void); void NPC_BSImperialProbe_Wait(void); /* @@ -1386,10 +1240,8 @@ void NPC_BSImperialProbe_Wait(void); NPC_BehaviorSet_ImperialProbe ------------------------- */ -void NPC_BehaviorSet_ImperialProbe( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ImperialProbe(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1398,23 +1250,20 @@ void NPC_BehaviorSet_ImperialProbe( int bState ) NPC_BSImperialProbe_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } - -void NPC_BSSeeker_Default( void ); +void NPC_BSSeeker_Default(void); /* ------------------------- NPC_BehaviorSet_Seeker ------------------------- */ -void NPC_BehaviorSet_Seeker( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Seeker(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1426,17 +1275,15 @@ void NPC_BehaviorSet_Seeker( int bState ) } } -void NPC_BSRemote_Default( void ); +void NPC_BSRemote_Default(void); /* ------------------------- NPC_BehaviorSet_Remote ------------------------- */ -void NPC_BehaviorSet_Remote( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Remote(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1445,22 +1292,20 @@ void NPC_BehaviorSet_Remote( int bState ) NPC_BSRemote_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSSentry_Default( void ); +void NPC_BSSentry_Default(void); /* ------------------------- NPC_BehaviorSet_Sentry ------------------------- */ -void NPC_BehaviorSet_Sentry( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sentry(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1469,7 +1314,7 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BSSentry_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1479,10 +1324,8 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BehaviorSet_Grenadier ------------------------- */ -void NPC_BehaviorSet_Grenadier( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Grenadier(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1492,7 +1335,7 @@ void NPC_BehaviorSet_Grenadier( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1502,10 +1345,8 @@ void NPC_BehaviorSet_Grenadier( int bState ) NPC_BehaviorSet_Tusken ------------------------- */ -void NPC_BehaviorSet_Tusken( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Tusken(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1515,7 +1356,7 @@ void NPC_BehaviorSet_Tusken( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1525,10 +1366,8 @@ void NPC_BehaviorSet_Tusken( int bState ) NPC_BehaviorSet_Sniper ------------------------- */ -void NPC_BehaviorSet_Sniper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sniper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1538,7 +1377,7 @@ void NPC_BehaviorSet_Sniper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1548,10 +1387,8 @@ NPC_BehaviorSet_Stormtrooper ------------------------- */ -void NPC_BehaviorSet_Stormtrooper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Stormtrooper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1569,7 +1406,7 @@ void NPC_BehaviorSet_Stormtrooper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1580,15 +1417,13 @@ NPC_BehaviorSet_Jedi ------------------------- */ -void NPC_BehaviorSet_Jedi( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Jedi(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: case BS_HUNT_AND_KILL: - case BS_INVESTIGATE://WTF???!! + case BS_INVESTIGATE: // WTF???!! case BS_DEFAULT: NPC_BSJedi_Default(); break; @@ -1598,17 +1433,15 @@ void NPC_BehaviorSet_Jedi( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -qboolean G_JediInNormalAI( gentity_t *ent ) -{//NOTE: should match above func's switch! - //check our bState - bState_t bState = G_CurrentBState( ent->NPC ); - switch ( bState ) - { +qboolean G_JediInNormalAI(gentity_t *ent) { // NOTE: should match above func's switch! + // check our bState + bState_t bState = G_CurrentBState(ent->NPC); + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1629,17 +1462,15 @@ qboolean G_JediInNormalAI( gentity_t *ent ) NPC_BehaviorSet_Droid ------------------------- */ -void NPC_BehaviorSet_Droid( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Droid(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSDroid_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1649,17 +1480,15 @@ void NPC_BehaviorSet_Droid( int bState ) NPC_BehaviorSet_Mark1 ------------------------- */ -void NPC_BehaviorSet_Mark1( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark1(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSMark1_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1669,10 +1498,8 @@ void NPC_BehaviorSet_Mark1( int bState ) NPC_BehaviorSet_Mark2 ------------------------- */ -void NPC_BehaviorSet_Mark2( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark2(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1680,7 +1507,7 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BSMark2_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1690,10 +1517,8 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BehaviorSet_ATST ------------------------- */ -void NPC_BehaviorSet_ATST( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ATST(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1701,7 +1526,7 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BSATST_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1711,10 +1536,8 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BehaviorSet_MineMonster ------------------------- */ -void NPC_BehaviorSet_MineMonster( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_MineMonster(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1723,7 +1546,7 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BSMineMonster_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1733,10 +1556,8 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BehaviorSet_Howler ------------------------- */ -void NPC_BehaviorSet_Howler( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Howler(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1745,7 +1566,7 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_BSHowler_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1755,10 +1576,8 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_BehaviorSet_Rancor ------------------------- */ -void NPC_BehaviorSet_Rancor( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Rancor(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1767,7 +1586,7 @@ void NPC_BehaviorSet_Rancor( int bState ) NPC_BSRancor_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1777,10 +1596,8 @@ void NPC_BehaviorSet_Rancor( int bState ) NPC_BehaviorSet_Wampa ------------------------- */ -void NPC_BehaviorSet_Wampa( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Wampa(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1789,7 +1606,7 @@ void NPC_BehaviorSet_Wampa( int bState ) NPC_BSWampa_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1799,10 +1616,8 @@ void NPC_BehaviorSet_Wampa( int bState ) NPC_BehaviorSet_SandCreature ------------------------- */ -void NPC_BehaviorSet_SandCreature( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_SandCreature(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1811,7 +1626,7 @@ void NPC_BehaviorSet_SandCreature( int bState ) NPC_BSSandCreature_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1822,19 +1637,17 @@ NPC_BehaviorSet_Droid ------------------------- */ // Added 01/21/03 by AReis. -void NPC_BehaviorSet_Animal( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Animal(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSAnimal_Default(); - //NPC_BSDroid_Default(); + // NPC_BSDroid_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1844,305 +1657,222 @@ void NPC_BehaviorSet_Animal( int bState ) NPC_RunBehavior ------------------------- */ -extern void NPC_BSEmplaced( void ); -extern qboolean NPC_CheckSurrender( void ); -extern void NPC_BSRT_Default( void ); -extern void NPC_BSCivilian_Default( int bState ); -extern void NPC_BSSD_Default( void ); -extern void NPC_BehaviorSet_Trooper( int bState ); -extern bool NPC_IsTrooper( gentity_t *ent ); +extern void NPC_BSEmplaced(void); +extern qboolean NPC_CheckSurrender(void); +extern void NPC_BSRT_Default(void); +extern void NPC_BSCivilian_Default(int bState); +extern void NPC_BSSD_Default(void); +extern void NPC_BehaviorSet_Trooper(int bState); +extern bool NPC_IsTrooper(gentity_t *ent); extern bool Pilot_MasterUpdate(); -void NPC_RunBehavior( int team, int bState ) -{ +void NPC_RunBehavior(int team, int bState) { // - if ( bState == BS_CINEMATIC ) - { + if (bState == BS_CINEMATIC) { NPC_BSCinematic(); - } - else if ( (NPCInfo->scriptFlags&SCF_PILOT) && Pilot_MasterUpdate()) - { + } else if ((NPCInfo->scriptFlags & SCF_PILOT) && Pilot_MasterUpdate()) { return; - } - else if ( NPC_JumpBackingUp() ) - { + } else if (NPC_JumpBackingUp()) { return; - } - else if ( !TIMER_Done(NPC, "DEMP2_StunTime")) - { + } else if (!TIMER_Done(NPC, "DEMP2_StunTime")) { NPC_UpdateAngles(qtrue, qtrue); return; - } - else if ( NPC->client->ps.weapon == WP_EMPLACED_GUN ) - { + } else if (NPC->client->ps.weapon == WP_EMPLACED_GUN) { NPC_BSEmplaced(); - G_CheckCharmed( NPC ); + G_CheckCharmed(NPC); return; - } - else if ( NPC->client->NPC_class == CLASS_HOWLER ) - { - NPC_BehaviorSet_Howler( bState ); + } else if (NPC->client->NPC_class == CLASS_HOWLER) { + NPC_BehaviorSet_Howler(bState); return; - } - else if ( Jedi_CultistDestroyer( NPC ) ) - { + } else if (Jedi_CultistDestroyer(NPC)) { NPC_BSJedi_Default(); - } - else if ( NPC->client->NPC_class == CLASS_SABER_DROID ) - {//saber droid + } else if (NPC->client->NPC_class == CLASS_SABER_DROID) { // saber droid NPC_BSSD_Default(); - } - else if ( NPC->client->ps.weapon == WP_SABER ) - {//jedi - NPC_BehaviorSet_Jedi( bState ); - } - else if ( NPC->client->NPC_class == CLASS_REBORN && NPC->client->ps.weapon == WP_MELEE ) - {//force-only reborn - NPC_BehaviorSet_Jedi( bState ); - } - else if ( NPC->client->NPC_class == CLASS_BOBAFETT ) - { + } else if (NPC->client->ps.weapon == WP_SABER) { // jedi + NPC_BehaviorSet_Jedi(bState); + } else if (NPC->client->NPC_class == CLASS_REBORN && NPC->client->ps.weapon == WP_MELEE) { // force-only reborn + NPC_BehaviorSet_Jedi(bState); + } else if (NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_Update(); - if (NPCInfo->surrenderTime) - { + if (NPCInfo->surrenderTime) { Boba_Flee(); - } - else - { - if (!Boba_Tactics()) - { - if ( Boba_Flying( NPC ) ) - { + } else { + if (!Boba_Tactics()) { + if (Boba_Flying(NPC)) { NPC_BehaviorSet_Seeker(bState); - } - else - { - NPC_BehaviorSet_Jedi( bState ); + } else { + NPC_BehaviorSet_Jedi(bState); } } } - } - else if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - {//bounty hunter - if ( RT_Flying( NPC ) || NPC->enemy != NULL ) - { + } else if (NPC->client->NPC_class == CLASS_ROCKETTROOPER) { // bounty hunter + if (RT_Flying(NPC) || NPC->enemy != NULL) { NPC_BSRT_Default(); - } - else - { - NPC_BehaviorSet_Stormtrooper( bState ); - } - G_CheckCharmed( NPC ); - } - else if ( NPC->client->NPC_class == CLASS_RANCOR ) - { - NPC_BehaviorSet_Rancor( bState ); - } - else if ( NPC->client->NPC_class == CLASS_SAND_CREATURE ) - { - NPC_BehaviorSet_SandCreature( bState ); - } - else if ( NPC->client->NPC_class == CLASS_WAMPA ) - { - NPC_BehaviorSet_Wampa( bState ); - G_CheckCharmed( NPC ); - } - else if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to march + } else { + NPC_BehaviorSet_Stormtrooper(bState); + } + G_CheckCharmed(NPC); + } else if (NPC->client->NPC_class == CLASS_RANCOR) { + NPC_BehaviorSet_Rancor(bState); + } else if (NPC->client->NPC_class == CLASS_SAND_CREATURE) { + NPC_BehaviorSet_SandCreature(bState); + } else if (NPC->client->NPC_class == CLASS_WAMPA) { + NPC_BehaviorSet_Wampa(bState); + G_CheckCharmed(NPC); + } else if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to march NPC_BSDefault(); - } - else if ( NPC->client->ps.weapon == WP_TUSKEN_RIFLE ) - { - if ( (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - { - NPC_BehaviorSet_Sniper( bState ); - G_CheckCharmed( NPC ); + } else if (NPC->client->ps.weapon == WP_TUSKEN_RIFLE) { + if ((NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + NPC_BehaviorSet_Sniper(bState); + G_CheckCharmed(NPC); return; - } - else - { - NPC_BehaviorSet_Tusken( bState ); - G_CheckCharmed( NPC ); + } else { + NPC_BehaviorSet_Tusken(bState); + G_CheckCharmed(NPC); return; } - } - else if ( NPC->client->ps.weapon == WP_TUSKEN_STAFF ) - { - NPC_BehaviorSet_Tusken( bState ); - G_CheckCharmed( NPC ); + } else if (NPC->client->ps.weapon == WP_TUSKEN_STAFF) { + NPC_BehaviorSet_Tusken(bState); + G_CheckCharmed(NPC); return; - } - else if ( NPC->client->ps.weapon == WP_NOGHRI_STICK ) - { - NPC_BehaviorSet_Stormtrooper( bState ); - G_CheckCharmed( NPC ); - } - else - { - switch( team ) - { - - // case TEAM_SCAVENGERS: - // case TEAM_IMPERIAL: - // case TEAM_KLINGON: - // case TEAM_HIROGEN: - // case TEAM_MALON: - // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv + } else if (NPC->client->ps.weapon == WP_NOGHRI_STICK) { + NPC_BehaviorSet_Stormtrooper(bState); + G_CheckCharmed(NPC); + } else { + switch (team) { + + // case TEAM_SCAVENGERS: + // case TEAM_IMPERIAL: + // case TEAM_KLINGON: + // case TEAM_HIROGEN: + // case TEAM_MALON: + // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv case TEAM_ENEMY: // special cases for enemy droids - switch( NPC->client->NPC_class) - { + switch (NPC->client->NPC_class) { case CLASS_ATST: - NPC_BehaviorSet_ATST( bState ); + NPC_BehaviorSet_ATST(bState); return; case CLASS_PROBE: NPC_BehaviorSet_ImperialProbe(bState); return; case CLASS_REMOTE: - NPC_BehaviorSet_Remote( bState ); + NPC_BehaviorSet_Remote(bState); return; case CLASS_SENTRY: NPC_BehaviorSet_Sentry(bState); return; case CLASS_INTERROGATOR: - NPC_BehaviorSet_Interrogator( bState ); + NPC_BehaviorSet_Interrogator(bState); return; case CLASS_MINEMONSTER: - NPC_BehaviorSet_MineMonster( bState ); + NPC_BehaviorSet_MineMonster(bState); return; case CLASS_HOWLER: - NPC_BehaviorSet_Howler( bState ); + NPC_BehaviorSet_Howler(bState); return; case CLASS_RANCOR: - NPC_BehaviorSet_Rancor( bState ); + NPC_BehaviorSet_Rancor(bState); return; case CLASS_SAND_CREATURE: - NPC_BehaviorSet_SandCreature( bState ); + NPC_BehaviorSet_SandCreature(bState); return; case CLASS_MARK1: - NPC_BehaviorSet_Mark1( bState ); + NPC_BehaviorSet_Mark1(bState); return; case CLASS_MARK2: - NPC_BehaviorSet_Mark2( bState ); + NPC_BehaviorSet_Mark2(bState); return; default: break; } - - if (NPC->client->NPC_class==CLASS_ASSASSIN_DROID) - { + if (NPC->client->NPC_class == CLASS_ASSASSIN_DROID) { BubbleShield_Update(); } - if (NPC_IsTrooper(NPC)) - { - NPC_BehaviorSet_Trooper( bState); + if (NPC_IsTrooper(NPC)) { + NPC_BehaviorSet_Trooper(bState); return; } - if ( NPC->enemy && NPC->client->ps.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there - if ( bState != BS_FLEE ) - { - NPC_StartFlee( NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - } - else - { + if (NPC->enemy && NPC->client->ps.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && + !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there + if (bState != BS_FLEE) { + NPC_StartFlee(NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } else { NPC_BSFlee(); } return; } - if ( NPC->client->ps.weapon == WP_SABER ) - {//special melee exception - NPC_BehaviorSet_Default( bState ); + if (NPC->client->ps.weapon == WP_SABER) { // special melee exception + NPC_BehaviorSet_Default(bState); return; } - if ( NPC->client->ps.weapon == WP_DISRUPTOR && (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//a sniper - NPC_BehaviorSet_Sniper( bState ); + if (NPC->client->ps.weapon == WP_DISRUPTOR && (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // a sniper + NPC_BehaviorSet_Sniper(bState); return; } - if ( NPC->client->ps.weapon == WP_THERMAL - || NPC->client->ps.weapon == WP_MELEE )//FIXME: separate AI for melee fighters - {//a grenadier - NPC_BehaviorSet_Grenadier( bState ); + if (NPC->client->ps.weapon == WP_THERMAL || NPC->client->ps.weapon == WP_MELEE) // FIXME: separate AI for melee fighters + { // a grenadier + NPC_BehaviorSet_Grenadier(bState); return; } - if ( NPC_CheckSurrender() ) - { + if (NPC_CheckSurrender()) { return; } - NPC_BehaviorSet_Stormtrooper( bState ); + NPC_BehaviorSet_Stormtrooper(bState); break; case TEAM_NEUTRAL: // special cases for enemy droids - if ( NPC->client->NPC_class == CLASS_PROTOCOL ) - { + if (NPC->client->NPC_class == CLASS_PROTOCOL) { NPC_BehaviorSet_Default(bState); - } - else if ( NPC->client->NPC_class == CLASS_UGNAUGHT - || NPC->client->NPC_class == CLASS_JAWA ) - {//others, too? - NPC_BSCivilian_Default( bState ); + } else if (NPC->client->NPC_class == CLASS_UGNAUGHT || NPC->client->NPC_class == CLASS_JAWA) { // others, too? + NPC_BSCivilian_Default(bState); return; } // Add special vehicle behavior here. - else if ( NPC->client->NPC_class == CLASS_VEHICLE ) - { + else if (NPC->client->NPC_class == CLASS_VEHICLE) { Vehicle_t *pVehicle = NPC->m_pVehicle; - if ( !pVehicle->m_pPilot && pVehicle->m_iBoarding==0 ) - { - if (pVehicle->m_pVehicleInfo->type == VH_ANIMAL) - { - NPC_BehaviorSet_Animal( bState ); + if (!pVehicle->m_pPilot && pVehicle->m_iBoarding == 0) { + if (pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { + NPC_BehaviorSet_Animal(bState); } // TODO: The only other case were we want a vehicle to do something specifically is // perhaps in multiplayer where we want the shuttle to be able to lift off when not // occupied and in a landing zone. } - } - else - { + } else { // Just one of the average droids - NPC_BehaviorSet_Droid( bState ); + NPC_BehaviorSet_Droid(bState); } break; default: - if ( NPC->client->NPC_class == CLASS_SEEKER ) - { + if (NPC->client->NPC_class == CLASS_SEEKER) { NPC_BehaviorSet_Seeker(bState); - } - else - { - if ( NPCInfo->charmedTime > level.time ) - { - NPC_BehaviorSet_Charmed( bState ); + } else { + if (NPCInfo->charmedTime > level.time) { + NPC_BehaviorSet_Charmed(bState); + } else { + NPC_BehaviorSet_Default(bState); } - else - { - NPC_BehaviorSet_Default( bState ); - } - G_CheckCharmed( NPC ); + G_CheckCharmed(NPC); } break; } } } -static bState_t G_CurrentBState( gNPC_t *gNPC ) -{ - if ( gNPC->tempBehavior != BS_DEFAULT ) - {//Overrides normal behavior until cleared +static bState_t G_CurrentBState(gNPC_t *gNPC) { + if (gNPC->tempBehavior != BS_DEFAULT) { // Overrides normal behavior until cleared return (gNPC->tempBehavior); } - if( gNPC->behaviorState == BS_DEFAULT ) - { + if (gNPC->behaviorState == BS_DEFAULT) { gNPC->behaviorState = gNPC->defaultBehavior; } @@ -2158,106 +1888,88 @@ NPC Behavior state thinking =============== */ -void NPC_ExecuteBState ( gentity_t *self)//, int msec ) +void NPC_ExecuteBState(gentity_t *self) //, int msec ) { - bState_t bState; + bState_t bState; NPC_HandleAIFlags(); - //FIXME: these next three bits could be a function call, some sort of setup/cleanup func - //Lookmode must be reset every think cycle - if(NPC->delayScriptTime && NPC->delayScriptTime <= level.time) - { - G_ActivateBehavior( NPC, BSET_DELAYED); + // FIXME: these next three bits could be a function call, some sort of setup/cleanup func + // Lookmode must be reset every think cycle + if (NPC->delayScriptTime && NPC->delayScriptTime <= level.time) { + G_ActivateBehavior(NPC, BSET_DELAYED); NPC->delayScriptTime = 0; } - //Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func + // Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func NPCInfo->combatMove = qfalse; - //Execute our bState - bState = G_CurrentBState( NPCInfo ); - - //Pick the proper bstate for us and run it - NPC_RunBehavior( self->client->playerTeam, bState ); + // Execute our bState + bState = G_CurrentBState(NPCInfo); + // Pick the proper bstate for us and run it + NPC_RunBehavior(self->client->playerTeam, bState); -// if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) -// { - //level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; - //NPCInfo->combatPoint = -1; -// } + // if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) + // { + // level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; + // NPCInfo->combatPoint = -1; + // } - //Here we need to see what the scripted stuff told us to do -//Only process snapshot if independant and in combat mode- this would pick enemies and go after needed items -// ProcessSnapshot(); + // Here we need to see what the scripted stuff told us to do + // Only process snapshot if independant and in combat mode- this would pick enemies and go after needed items + // ProcessSnapshot(); -//Ignore my needs if I'm under script control- this would set needs for items -// CheckSelf(); + // Ignore my needs if I'm under script control- this would set needs for items + // CheckSelf(); - //Back to normal? All decisions made? + // Back to normal? All decisions made? - //FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface - //NPCPredict(); + // FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface + // NPCPredict(); - if ( NPC->enemy ) - { - if ( !NPC->enemy->inuse ) - {//just in case bState doesn't catch this - G_ClearEnemy( NPC ); + if (NPC->enemy) { + if (!NPC->enemy->inuse) { // just in case bState doesn't catch this + G_ClearEnemy(NPC); } } - if ( NPC->client->ps.saberLockTime && NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE ) - { - NPC_SetLookTarget( NPC, NPC->client->ps.saberLockEnemy, level.time+1000 ); - } - else if ( !NPC_CheckLookTarget( NPC ) ) - { - if ( NPC->enemy ) - { - NPC_SetLookTarget( NPC, NPC->enemy->s.number, 0 ); + if (NPC->client->ps.saberLockTime && NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE) { + NPC_SetLookTarget(NPC, NPC->client->ps.saberLockEnemy, level.time + 1000); + } else if (!NPC_CheckLookTarget(NPC)) { + if (NPC->enemy) { + NPC_SetLookTarget(NPC, NPC->enemy->s.number, 0); } } - if ( NPC->enemy ) - { - if(NPC->enemy->flags & FL_DONT_SHOOT) - { + if (NPC->enemy) { + if (NPC->enemy->flags & FL_DONT_SHOOT) { ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons &= ~BUTTON_ALT_ATTACK; - } - else if ( NPC->client->playerTeam != TEAM_ENEMY //not an enemy - && (NPC->client->playerTeam != TEAM_FREE || (NPC->client->NPC_class == CLASS_TUSKEN && Q_irand( 0, 4 )))//not a rampaging creature or I'm a tusken and I feel generous (temporarily) - && NPC->enemy->NPC - && (NPC->enemy->NPC->surrenderTime > level.time || (NPC->enemy->NPC->scriptFlags&SCF_FORCED_MARCH)) ) - {//don't shoot someone who's surrendering if you're a good guy + } else if (NPC->client->playerTeam != TEAM_ENEMY // not an enemy + && (NPC->client->playerTeam != TEAM_FREE || + (NPC->client->NPC_class == CLASS_TUSKEN && Q_irand(0, 4))) // not a rampaging creature or I'm a tusken and I feel generous (temporarily) + && NPC->enemy->NPC && + (NPC->enemy->NPC->surrenderTime > level.time || + (NPC->enemy->NPC->scriptFlags & SCF_FORCED_MARCH))) { // don't shoot someone who's surrendering if you're a good guy ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons &= ~BUTTON_ALT_ATTACK; } - if(client->ps.weaponstate == WEAPON_IDLE) - { + if (client->ps.weaponstate == WEAPON_IDLE) { client->ps.weaponstate = WEAPON_READY; } - } - else - { - if(client->ps.weaponstate == WEAPON_READY) - { + } else { + if (client->ps.weaponstate == WEAPON_READY) { client->ps.weaponstate = WEAPON_IDLE; } } - if(!(ucmd.buttons & BUTTON_ATTACK) && NPC->attackDebounceTime > level.time) - {//We just shot but aren't still shooting, so hold the gun up for a while - if(client->ps.weapon == WP_SABER ) - {//One-handed - NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY1,SETANIM_FLAG_NORMAL); - } - else if(client->ps.weapon == WP_BRYAR_PISTOL) - {//Sniper pose - NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + if (!(ucmd.buttons & BUTTON_ATTACK) && NPC->attackDebounceTime > level.time) { // We just shot but aren't still shooting, so hold the gun up for a while + if (client->ps.weapon == WP_SABER) { // One-handed + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_WEAPONREADY1, SETANIM_FLAG_NORMAL); + } else if (client->ps.weapon == WP_BRYAR_PISTOL) { // Sniper pose + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } /*//FIXME: What's the proper solution here? else @@ -2270,27 +1982,23 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) NPC_CheckAttackHold(); NPC_ApplyScriptFlags(); - //cliff and wall avoidance + // cliff and wall avoidance NPC_AvoidWallsAndCliffs(); // run the bot through the server like it was a real client -//=== Save the ucmd for the second no-think Pmove ============================ + //=== Save the ucmd for the second no-think Pmove ============================ ucmd.serverTime = level.time - 50; - memcpy( &NPCInfo->last_ucmd, &ucmd, sizeof( usercmd_t ) ); - if ( !NPCInfo->attackHoldTime ) - { - NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS);//so we don't fire twice in one think + memcpy(&NPCInfo->last_ucmd, &ucmd, sizeof(usercmd_t)); + if (!NPCInfo->attackHoldTime) { + NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS); // so we don't fire twice in one think } -//============================================================================ + //============================================================================ NPC_CheckAttackScript(); NPC_KeepCurrentFacing(); - if ( !NPC->next_roff_time || NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - ClientThink( NPC->s.number, &ucmd ); - } - else - { + if (!NPC->next_roff_time || NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + ClientThink(NPC->s.number, &ucmd); + } else { NPC_ApplyRoff(); } @@ -2324,28 +2032,24 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) if(la != -1 && ta != -1) {//FIXME: should never play same frame twice or restart an anim before finishing it - gi.Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, NPC->client->renderInfo.torsoFrame); + gi.Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, + NPC->client->renderInfo.torsoFrame); } }*/ } -void NPC_CheckInSolid(void) -{ - trace_t trace; - vec3_t point; +void NPC_CheckInSolid(void) { + trace_t trace; + vec3_t point; VectorCopy(NPC->currentOrigin, point); point[2] -= 0.25; gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, point, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); - if(!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy(NPC->currentOrigin, NPCInfo->lastClearOrigin); - } - else - { - if(VectorLengthSquared(NPCInfo->lastClearOrigin)) - { -// gi.Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->currentOrigin)); + } else { + if (VectorLengthSquared(NPCInfo->lastClearOrigin)) { + // gi.Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->currentOrigin)); G_SetOrigin(NPC, NPCInfo->lastClearOrigin); gi.linkentity(NPC); } @@ -2359,45 +2063,40 @@ NPC_Think Main NPC AI - called once per frame =============== */ -#if AI_TIMERS +#if AI_TIMERS extern int AITime; -#endif// AI_TIMERS -void NPC_Think ( gentity_t *self)//, int msec ) +#endif // AI_TIMERS +void NPC_Think(gentity_t *self) //, int msec ) { - vec3_t oldMoveDir; + vec3_t oldMoveDir; - self->nextthink = level.time + FRAMETIME/2; + self->nextthink = level.time + FRAMETIME / 2; - SetNPCGlobals( self ); + SetNPCGlobals(self); - memset( &ucmd, 0, sizeof( ucmd ) ); + memset(&ucmd, 0, sizeof(ucmd)); - VectorCopy( self->client->ps.moveDir, oldMoveDir ); - VectorClear( self->client->ps.moveDir ); + VectorCopy(self->client->ps.moveDir, oldMoveDir); + VectorClear(self->client->ps.moveDir); // see if NPC ai is frozen - if ( debugNPCFreeze->integer || (NPC->svFlags&SVF_ICARUS_FREEZE) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (debugNPCFreeze->integer || (NPC->svFlags & SVF_ICARUS_FREEZE)) { + NPC_UpdateAngles(qtrue, qtrue); ClientThink(self->s.number, &ucmd); - VectorCopy(self->s.origin, self->s.origin2 ); + VectorCopy(self->s.origin, self->s.origin2); return; } - if(!self || !self->NPC || !self->client) - { + if (!self || !self->NPC || !self->client) { return; } // dead NPCs have a special think, don't run scripts (for now) - //FIXME: this breaks deathscripts - if ( self->health <= 0 ) - { + // FIXME: this breaks deathscripts + if (self->health <= 0) { DeadThink(); - if ( NPCInfo->nextBStateThink <= level.time ) - { - if( self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( self->m_iIcarusID ); + if (NPCInfo->nextBStateThink <= level.time) { + if (self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(self->m_iIcarusID); } } return; @@ -2405,152 +2104,126 @@ void NPC_Think ( gentity_t *self)//, int msec ) // TODO! Tauntaun's (and other creature vehicles?) think, we'll need to make an exception here to allow that. - if ( self->client - && self->client->NPC_class == CLASS_VEHICLE - && self->NPC_type - && ( !self->m_pVehicle->m_pVehicleInfo->Inhabited( self->m_pVehicle ) ) ) - {//empty swoop logic - if ( self->owner ) - {//still have attached owner, check and see if can forget him (so he can use me later) + if (self->client && self->client->NPC_class == CLASS_VEHICLE && self->NPC_type && + (!self->m_pVehicle->m_pVehicleInfo->Inhabited(self->m_pVehicle))) { // empty swoop logic + if (self->owner) { // still have attached owner, check and see if can forget him (so he can use me later) vec3_t dir2owner; - VectorSubtract( self->owner->currentOrigin, self->currentOrigin, dir2owner ); + VectorSubtract(self->owner->currentOrigin, self->currentOrigin, dir2owner); gentity_t *oldOwner = self->owner; - self->owner = NULL;//clear here for that SpotWouldTelefrag check...? + self->owner = NULL; // clear here for that SpotWouldTelefrag check...? - if ( VectorLengthSquared( dir2owner ) > 128*128 - || !(self->clipmask&oldOwner->clipmask) - || (DotProduct( self->client->ps.velocity, oldOwner->client->ps.velocity ) < -200.0f &&!G_BoundsOverlap( self->absmin, self->absmin, oldOwner->absmin, oldOwner->absmax )) ) - {//all clear, become solid to our owner now - gi.linkentity( self ); - } - else - {//blocked, retain owner + if (VectorLengthSquared(dir2owner) > 128 * 128 || !(self->clipmask & oldOwner->clipmask) || + (DotProduct(self->client->ps.velocity, oldOwner->client->ps.velocity) < -200.0f && + !G_BoundsOverlap(self->absmin, self->absmin, oldOwner->absmin, oldOwner->absmax))) { // all clear, become solid to our owner now + gi.linkentity(self); + } else { // blocked, retain owner self->owner = oldOwner; } } } - if ( player->client->ps.viewEntity == self->s.number ) - {//being controlled by player - if ( self->client ) - {//make the noises - if ( TIMER_Done( self, "patrolNoise" ) && !Q_irand( 0, 20 ) ) - { - switch( self->client->NPC_class ) - { - case CLASS_R2D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)) ); + if (player->client->ps.viewEntity == self->s.number) { // being controlled by player + if (self->client) { // make the noises + if (TIMER_Done(self, "patrolNoise") && !Q_irand(0, 20)) { + switch (self->client->NPC_class) { + case CLASS_R2D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); break; - case CLASS_R5D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)) ); + case CLASS_R5D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); break; - case CLASS_PROBE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav",Q_irand(1, 3)) ); + case CLASS_PROBE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav", Q_irand(1, 3))); break; - case CLASS_MOUSE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)) ); + case CLASS_MOUSE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); break; - case CLASS_GONK: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)) ); + case CLASS_GONK: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); break; default: break; } - TIMER_Set( self, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(self, "patrolNoise", Q_irand(2000, 4000)); } } - //FIXME: might want to at least make sounds or something? - //NPC_UpdateAngles(qtrue, qtrue); - //Which ucmd should we send? Does it matter, since it gets overridden anyway? + // FIXME: might want to at least make sounds or something? + // NPC_UpdateAngles(qtrue, qtrue); + // Which ucmd should we send? Does it matter, since it gets overridden anyway? NPCInfo->last_ucmd.serverTime = level.time - 50; - ClientThink( NPC->s.number, &ucmd ); - VectorCopy(self->s.origin, self->s.origin2 ); + ClientThink(NPC->s.number, &ucmd); + VectorCopy(self->s.origin, self->s.origin2); return; } - if ( NPCInfo->nextBStateThink <= level.time ) - { -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS - if ( NPC->s.eType != ET_PLAYER ) - {//Something drastic happened in our script + if (NPCInfo->nextBStateThink <= level.time) { +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS + if (NPC->s.eType != ET_PLAYER) { // Something drastic happened in our script return; } - if ( NPC->s.weapon == WP_SABER && g_spskill->integer >= 2 && NPCInfo->rank > RANK_LT_JG ) - {//Jedi think faster on hard difficulty, except low-rank (reborn) - NPCInfo->nextBStateThink = level.time + FRAMETIME/2; - } - else - {//Maybe even 200 ms? + if (NPC->s.weapon == WP_SABER && g_spskill->integer >= 2 && + NPCInfo->rank > RANK_LT_JG) { // Jedi think faster on hard difficulty, except low-rank (reborn) + NPCInfo->nextBStateThink = level.time + FRAMETIME / 2; + } else { // Maybe even 200 ms? NPCInfo->nextBStateThink = level.time + FRAMETIME; } - //nextthink is set before this so something in here can override it - NPC_ExecuteBState( self ); + // nextthink is set before this so something in here can override it + NPC_ExecuteBState(self); -#if AI_TIMERS - int addTime = GetTime( startTime ); - if ( addTime > 50 ) - { - gi.Printf( S_COLOR_RED"ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, vtos(NPC->currentOrigin), NPC->s.weapon, addTime ); +#if AI_TIMERS + int addTime = GetTime(startTime); + if (addTime > 50) { + gi.Printf(S_COLOR_RED "ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, + vtos(NPC->currentOrigin), NPC->s.weapon, addTime); } AITime += addTime; -#endif// AI_TIMERS - } - else - { - if ( NPC->client - && NPC->client->NPC_class == CLASS_ROCKETTROOPER - && (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) - && NPC->client->moveType == MT_FLYSWIM - && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//reduce velocity - VectorScale( NPC->client->ps.velocity, 0.75f, NPC->client->ps.velocity ); - } - VectorCopy( oldMoveDir, self->client->ps.moveDir ); - //or use client->pers.lastCommand? +#endif // AI_TIMERS + } else { + if (NPC->client && NPC->client->NPC_class == CLASS_ROCKETTROOPER && (NPC->client->ps.eFlags & EF_FORCE_GRIPPED) && + NPC->client->moveType == MT_FLYSWIM && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // reduce velocity + VectorScale(NPC->client->ps.velocity, 0.75f, NPC->client->ps.velocity); + } + VectorCopy(oldMoveDir, self->client->ps.moveDir); + // or use client->pers.lastCommand? NPCInfo->last_ucmd.serverTime = level.time - 50; - if ( !NPC->next_roff_time || NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - //FIXME: firing angles (no aim offset) or regular angles? + if (!NPC->next_roff_time || NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + // FIXME: firing angles (no aim offset) or regular angles? NPC_UpdateAngles(qtrue, qtrue); - memcpy( &ucmd, &NPCInfo->last_ucmd, sizeof( usercmd_t ) ); + memcpy(&ucmd, &NPCInfo->last_ucmd, sizeof(usercmd_t)); ClientThink(NPC->s.number, &ucmd); - } - else - { + } else { NPC_ApplyRoff(); } - VectorCopy(self->s.origin, self->s.origin2 ); + VectorCopy(self->s.origin, self->s.origin2); } - //must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands - if( self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( self->m_iIcarusID ); + // must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands + if (self->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(self->m_iIcarusID); } } -void NPC_InitAI ( void ) -{ - debugNPCAI = gi.cvar ( "d_npcai", "0", CVAR_CHEAT ); - debugNPCFreeze = gi.cvar ( "d_npcfreeze", "0", CVAR_CHEAT); - d_JediAI = gi.cvar ( "d_JediAI", "0", CVAR_CHEAT ); - d_noGroupAI = gi.cvar ( "d_noGroupAI", "0", CVAR_CHEAT ); - d_asynchronousGroupAI = gi.cvar ( "d_asynchronousGroupAI", "1", CVAR_CHEAT ); - - //0 = never (BORING) - //1 = kyle only - //2 = kyle and last enemy jedi - //3 = kyle and any enemy jedi - //4 = kyle and last enemy in a group, special kicks - //5 = kyle and any enemy - //6 = also when kyle takes pain or enemy jedi dodges player saber swing or does an acrobatic evasion - // NOTE : I also create this in UI_Init() - d_slowmodeath = gi.cvar ( "d_slowmodeath", "3", CVAR_ARCHIVE );//save this setting - - d_saberCombat = gi.cvar ( "d_saberCombat", "0", CVAR_CHEAT ); +void NPC_InitAI(void) { + debugNPCAI = gi.cvar("d_npcai", "0", CVAR_CHEAT); + debugNPCFreeze = gi.cvar("d_npcfreeze", "0", CVAR_CHEAT); + d_JediAI = gi.cvar("d_JediAI", "0", CVAR_CHEAT); + d_noGroupAI = gi.cvar("d_noGroupAI", "0", CVAR_CHEAT); + d_asynchronousGroupAI = gi.cvar("d_asynchronousGroupAI", "1", CVAR_CHEAT); + + // 0 = never (BORING) + // 1 = kyle only + // 2 = kyle and last enemy jedi + // 3 = kyle and any enemy jedi + // 4 = kyle and last enemy in a group, special kicks + // 5 = kyle and any enemy + // 6 = also when kyle takes pain or enemy jedi dodges player saber swing or does an acrobatic evasion + // NOTE : I also create this in UI_Init() + d_slowmodeath = gi.cvar("d_slowmodeath", "3", CVAR_ARCHIVE); // save this setting + + d_saberCombat = gi.cvar("d_saberCombat", "0", CVAR_CHEAT); } /* @@ -2565,29 +2238,25 @@ void NPC_InitAnimTable( void ) (frameLerp of 0 * numFrames of 0 = 0) ================================== */ -void NPC_InitAnimTable( void ) -{ - for ( int i = 0; i < MAX_ANIM_FILES; i++ ) - { - for ( int j = 0; j < MAX_ANIMATIONS; j++ ) - { +void NPC_InitAnimTable(void) { + for (int i = 0; i < MAX_ANIM_FILES; i++) { + for (int j = 0; j < MAX_ANIMATIONS; j++) { level.knownAnimFileSets[i].animations[j].firstFrame = 0; level.knownAnimFileSets[i].animations[j].frameLerp = 100; -// level.knownAnimFileSets[i].animations[j].initialLerp = 100; + // level.knownAnimFileSets[i].animations[j].initialLerp = 100; level.knownAnimFileSets[i].animations[j].numFrames = 0; } } } -extern int G_ParseAnimFileSet( const char *skeletonName, const char *modelName=0); -void NPC_InitGame( void ) -{ -// globals.NPCs = (gNPC_t *) gi.TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); - debugNPCName = gi.cvar ( "d_npc", "", 0 ); +extern int G_ParseAnimFileSet(const char *skeletonName, const char *modelName = 0); +void NPC_InitGame(void) { + // globals.NPCs = (gNPC_t *) gi.TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); + debugNPCName = gi.cvar("d_npc", "", 0); NPC_LoadParms(); NPC_InitAI(); NPC_InitAnimTable(); - G_ParseAnimFileSet("_humanoid"); //GET THIS CACHED NOW BEFORE CGAME STARTS + G_ParseAnimFileSet("_humanoid"); // GET THIS CACHED NOW BEFORE CGAME STARTS /* ResetTeamCounters(); for ( int team = TEAM_FREE; team < TEAM_NUM_TEAMS; team++ ) @@ -2597,81 +2266,58 @@ void NPC_InitGame( void ) */ } -void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend) -{ // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players +void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, + int iBlend) { // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players // rename PM_SETAnimFinal to PM_SetAnim and have both NCP and Players call PM_SetAnim - if ( !ent ) - { + if (!ent) { return; } - if ( ent->health > 0 ) - {//don't lock anims if the guy is dead - if ( ent->client->ps.torsoAnimTimer - && PM_LockedAnim( ent->client->ps.torsoAnim ) - && !PM_LockedAnim( anim ) ) - {//nothing can override these special anims + if (ent->health > 0) { // don't lock anims if the guy is dead + if (ent->client->ps.torsoAnimTimer && PM_LockedAnim(ent->client->ps.torsoAnim) && !PM_LockedAnim(anim)) { // nothing can override these special anims setAnimParts &= ~SETANIM_TORSO; } - if ( ent->client->ps.legsAnimTimer - && PM_LockedAnim( ent->client->ps.legsAnim ) - && !PM_LockedAnim( anim ) ) - {//nothing can override these special anims + if (ent->client->ps.legsAnimTimer && PM_LockedAnim(ent->client->ps.legsAnim) && !PM_LockedAnim(anim)) { // nothing can override these special anims setAnimParts &= ~SETANIM_LEGS; } } - if ( !setAnimParts ) - { + if (!setAnimParts) { return; } - if(ent->client) - {//Players, NPCs - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, 0 ); + if (ent->client) { // Players, NPCs + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim) { + PM_SetTorsoAnimTimer(ent, &ent->client->ps.torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim ) - { - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim) { + PM_SetLegsAnimTimer(ent, &ent->client->ps.legsAnimTimer, 0); } } } - PM_SetAnimFinal(&ent->client->ps.torsoAnim,&ent->client->ps.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->client->ps.torsoAnimTimer,&ent->client->ps.legsAnimTimer,ent, iBlend ); - } - else - {//bodies, etc. - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( ent, &ent->s.torsoAnimTimer, 0 ); + PM_SetAnimFinal(&ent->client->ps.torsoAnim, &ent->client->ps.legsAnim, setAnimParts, anim, setAnimFlags, &ent->client->ps.torsoAnimTimer, + &ent->client->ps.legsAnimTimer, ent, iBlend); + } else { // bodies, etc. + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim) { + PM_SetTorsoAnimTimer(ent, &ent->s.torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim ) - { - PM_SetLegsAnimTimer( ent, &ent->s.legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim) { + PM_SetLegsAnimTimer(ent, &ent->s.legsAnimTimer, 0); } } } - PM_SetAnimFinal(&ent->s.torsoAnim,&ent->s.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->s.torsoAnimTimer,&ent->s.legsAnimTimer,ent); + PM_SetAnimFinal(&ent->s.torsoAnim, &ent->s.legsAnim, setAnimParts, anim, setAnimFlags, &ent->s.torsoAnimTimer, &ent->s.legsAnimTimer, ent); } } diff --git a/code/game/NPC_behavior.cpp b/code/game/NPC_behavior.cpp index 249bc3c17d..4461d71dd9 100644 --- a/code/game/NPC_behavior.cpp +++ b/code/game/NPC_behavior.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_behavior.cpp +// NPC_behavior.cpp /* FIXME - MCG: These all need to make use of the snapshots. Write something that can look for only specific @@ -36,107 +36,93 @@ we need it... #include "g_functions.h" #include "g_nav.h" -extern cvar_t *g_AIsurrender; -extern qboolean showBBoxes; +extern cvar_t *g_AIsurrender; +extern qboolean showBBoxes; static vec3_t NPCDEBUG_BLUE = {0.0, 0.0, 1.0}; -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void NPC_CheckGetNewWeapon( void ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern void NPC_AimAdjust( int change ); -extern qboolean G_StandardHumanoid( gentity_t *self ); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void NPC_CheckGetNewWeapon(void); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern void NPC_AimAdjust(int change); +extern qboolean G_StandardHumanoid(gentity_t *self); /* void NPC_BSAdvanceFight (void) Advance towards your captureGoal and shoot anyone you can along the way. */ -void NPC_BSAdvanceFight (void) -{//FIXME: IMPLEMENT -//Head to Goal if I can +void NPC_BSAdvanceFight(void) { // FIXME: IMPLEMENT + // Head to Goal if I can - //Make sure we're still headed where we want to capture - if ( NPCInfo->captureGoal ) - {//FIXME: if no captureGoal, what do we do? - //VectorCopy( NPCInfo->captureGoal->currentOrigin, NPCInfo->tempGoal->currentOrigin ); - //NPCInfo->goalEntity = NPCInfo->tempGoal; + // Make sure we're still headed where we want to capture + if (NPCInfo->captureGoal) { // FIXME: if no captureGoal, what do we do? + // VectorCopy( NPCInfo->captureGoal->currentOrigin, NPCInfo->tempGoal->currentOrigin ); + // NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_SetMoveGoal( NPC, NPCInfo->captureGoal->currentOrigin, 16, qtrue ); + NPC_SetMoveGoal(NPC, NPCInfo->captureGoal->currentOrigin, 16, qtrue); NPCInfo->goalTime = level.time + 100000; } -// NPC_BSRun(); + // NPC_BSRun(); NPC_CheckEnemy(qtrue, qfalse); - //FIXME: Need melee code - if( NPC->enemy ) - {//See if we can shoot him - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; - qboolean dead_on = qfalse; - float attack_scale = 1.0; - float aim_off; - float max_aim_off = 64; - - //Yaw to enemy + // FIXME: Need melee code + if (NPC->enemy) { // See if we can shoot him + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + qboolean dead_on = qfalse; + float attack_scale = 1.0; + float aim_off; + float max_aim_off = 64; + + // Yaw to enemy VectorMA(NPC->enemy->absmin, 0.5, NPC->enemy->maxs, enemy_org); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); - if(!NPC_EnemyTooFar(NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue)) - { + if (!NPC_EnemyTooFar(NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { attack_ok = qtrue; } - if(attack_ok) - { + if (attack_ok) { NPC_UpdateShootAngles(angleToEnemy, qfalse, qtrue); NPCInfo->enemyLastVisibility = enemyVisibility; - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV);//CHECK_360|//CHECK_PVS| + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV); // CHECK_360|//CHECK_PVS| - if(enemyVisibility == VIS_FOV) - {//He's in our FOV + if (enemyVisibility == VIS_FOV) { // He's in our FOV attack_ok = qtrue; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_head); - if(attack_ok) - { - trace_t tr; - gentity_t *traceEnt; - //are we gonna hit him if we shoot at his center? - gi.trace ( &tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + if (attack_ok) { + trace_t tr; + gentity_t *traceEnt; + // are we gonna hit him if we shoot at his center? + gi.trace(&tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); traceEnt = &g_entities[tr.entityNum]; - if( traceEnt != NPC->enemy && - (!traceEnt || !traceEnt->client || !NPC->client->enemyTeam || NPC->client->enemyTeam != traceEnt->client->playerTeam) ) - {//no, so shoot for the head + if (traceEnt != NPC->enemy && (!traceEnt || !traceEnt->client || !NPC->client->enemyTeam || + NPC->client->enemyTeam != traceEnt->client->playerTeam)) { // no, so shoot for the head attack_scale *= 0.75; - gi.trace ( &tr, muzzle, NULL, NULL, enemy_head, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, muzzle, NULL, NULL, enemy_head, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); traceEnt = &g_entities[tr.entityNum]; } - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -144,354 +130,319 @@ void NPC_BSAdvanceFight (void) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateShootAngles(angleToEnemy, qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - AngleVectors (NPCInfo->shootAngles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + AngleVectors(NPCInfo->shootAngles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_head, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); - } - else + } else attack_ok = qfalse; } -//Don't do this- only for when stationary and trying to shoot an enemy -// else -// NPC->cantHitEnemyCounter++; - } - else - {//FIXME: + // Don't do this- only for when stationary and trying to shoot an enemy + // else + // NPC->cantHitEnemyCounter++; + } else { // FIXME: NPC_UpdateShootAngles(NPC->client->ps.viewangles, qtrue, qtrue); } - if(!ucmd.forwardmove && !ucmd.rightmove) - {//We reached our captureGoal - if( NPC->m_iIcarusID != IIcarusInterface::ICARUS_INVALID /*NPC->taskManager*/ ) - { - Q3_TaskIDComplete( NPC, TID_BSTATE ); + if (!ucmd.forwardmove && !ucmd.rightmove) { // We reached our captureGoal + if (NPC->m_iIcarusID != IIcarusInterface::ICARUS_INVALID /*NPC->taskManager*/) { + Q3_TaskIDComplete(NPC, TID_BSTATE); } } } -void Disappear(gentity_t *self) -{ -// ClientDisconnect(self); +void Disappear(gentity_t *self) { + // ClientDisconnect(self); self->s.eFlags |= EF_NODRAW; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; } -void MakeOwnerInvis (gentity_t *self); -void BeamOut (gentity_t *self) -{ -// gentity_t *tent = G_Spawn(); +void MakeOwnerInvis(gentity_t *self); +void BeamOut(gentity_t *self) { + // gentity_t *tent = G_Spawn(); -/* - tent->owner = self; - tent->think = MakeOwnerInvis; - tent->nextthink = level.time + 1800; - //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); - tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); -*/ - //fixme: doesn't actually go away! + /* + tent->owner = self; + tent->think = MakeOwnerInvis; + tent->nextthink = level.time + 1800; + //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); + tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); + */ + // fixme: doesn't actually go away! self->nextthink = level.time + 1500; self->e_ThinkFunc = thinkF_Disappear; self->client->playerTeam = TEAM_FREE; self->svFlags |= SVF_BEAMING; } -void NPC_BSCinematic( void ) -{ +void NPC_BSCinematic(void) { - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if (NPCInfo->scriptFlags&SCF_FIRE_WEAPON_NO_ANIM) - { - if (TIMER_Done(NPC, "NoAnimFireDelay")) - { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON_NO_ANIM) { + if (TIMER_Done(NPC, "NoAnimFireDelay")) { TIMER_Set(NPC, "NoAnimFireDelay", NPC_AttackDebounceForWeapon()); - FireWeapon(NPC, (qboolean)((NPCInfo->scriptFlags&SCF_ALT_FIRE) != 0)); + FireWeapon(NPC, (qboolean)((NPCInfo->scriptFlags & SCF_ALT_FIRE) != 0)); } } - if ( UpdateGoal() ) - {//have a goalEntity - //move toward goal, should also face that goal - NPC_MoveToGoal( qtrue ); + if (UpdateGoal()) { // have a goalEntity + // move toward goal, should also face that goal + NPC_MoveToGoal(qtrue); } - if ( NPCInfo->watchTarget ) - {//have an entity which we want to keep facing - //NOTE: this will override any angles set by NPC_MoveToGoal + if (NPCInfo->watchTarget) { // have an entity which we want to keep facing + // NOTE: this will override any angles set by NPC_MoveToGoal vec3_t eyes, viewSpot, viewvec, viewangles; - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); - CalcEntitySpot( NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot ); + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); + CalcEntitySpot(NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot); - VectorSubtract( viewSpot, eyes, viewvec ); + VectorSubtract(viewSpot, eyes, viewvec); - vectoangles( viewvec, viewangles ); + vectoangles(viewvec, viewangles); NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw = viewangles[YAW]; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch = viewangles[PITCH]; } - NPC_UpdateAngles( qtrue, qtrue ); -} - -void NPC_BSWait( void ) -{ - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } +void NPC_BSWait(void) { NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSInvestigate (void) -{ -/* - //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the - //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) - vec3_t invDir, invAngles, spot; - gentity_t *saveGoal; - //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, - //look for enemies, then turn away after your investigate counter was down- - //investigate counter goes up every time you set it... - - if(level.time > NPCInfo->enemyCheckDebounceTime) - { - NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); - NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - {//FIXME: do anger script - NPCInfo->goalEntity = NPC->enemy; - NPCInfo->behaviorState = BS_RUN_AND_SHOOT; - NPCInfo->tempBehavior = BS_DEFAULT; - NPC_AngerSound(); - return; +void NPC_BSInvestigate(void) { + /* + //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the + //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) + vec3_t invDir, invAngles, spot; + gentity_t *saveGoal; + //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, + //look for enemies, then turn away after your investigate counter was down- + //investigate counter goes up every time you set it... + + if(level.time > NPCInfo->enemyCheckDebounceTime) + { + NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); + NPC_CheckEnemy(qtrue, qfalse); + if(NPC->enemy) + {//FIXME: do anger script + NPCInfo->goalEntity = NPC->enemy; + NPCInfo->behaviorState = BS_RUN_AND_SHOOT; + NPCInfo->tempBehavior = BS_DEFAULT; + NPC_AngerSound(); + return; + } } - } - - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) - { - VectorCopy(NPCInfo->eventOwner->currentOrigin, NPCInfo->investigateGoal); - } + NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - saveGoal = NPCInfo->goalEntity; - if( level.time > NPCInfo->walkDebounceTime ) - { - vec3_t vec; + if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) + { + VectorCopy(NPCInfo->eventOwner->currentOrigin, NPCInfo->investigateGoal); + } - VectorSubtract(NPCInfo->investigateGoal, NPC->currentOrigin, vec); - vec[2] = 0; - if(VectorLength(vec) > 64) + saveGoal = NPCInfo->goalEntity; + if( level.time > NPCInfo->walkDebounceTime ) { - if(Q_irand(0, 100) < NPCInfo->investigateCount) - {//take a full step - //NPCInfo->walkDebounceTime = level.time + 1400; - //actually finds length of my BOTH_WALK anim - NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + vec3_t vec; + + VectorSubtract(NPCInfo->investigateGoal, NPC->currentOrigin, vec); + vec[2] = 0; + if(VectorLength(vec) > 64) + { + if(Q_irand(0, 100) < NPCInfo->investigateCount) + {//take a full step + //NPCInfo->walkDebounceTime = level.time + 1400; + //actually finds length of my BOTH_WALK anim + NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + } } } - } - if( level.time < NPCInfo->walkDebounceTime ) - {//walk toward investigateGoal + if( level.time < NPCInfo->walkDebounceTime ) + {//walk toward investigateGoal - / * - NPCInfo->goalEntity = NPCInfo->tempGoal; - VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->currentOrigin); - */ + / * + NPCInfo->goalEntity = NPCInfo->tempGoal; + VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->currentOrigin); + */ -/* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); + /* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal( qtrue ); - //FIXME: walk2? - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); + //FIXME: walk2? + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); - ucmd.buttons |= BUTTON_WALKING; - } - else - { + ucmd.buttons |= BUTTON_WALKING; + } + else + { - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - if(NPCInfo->hlookCount > 30) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->hlookCount > 30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount < -30) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->hlookCount < -30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount == 0) - { - NPCInfo->hlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 7) - { - if(NPCInfo->hlookCount > 0) + else if(NPCInfo->hlookCount == 0) { - NPCInfo->hlookCount++; + NPCInfo->hlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 7) { - NPCInfo->hlookCount--; + if(NPCInfo->hlookCount > 0) + { + NPCInfo->hlookCount++; + } + else//lookCount < 0 + { + NPCInfo->hlookCount--; + } } - } - if(NPCInfo->vlookCount >= 15) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->vlookCount >= 15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount <= -15) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->vlookCount <= -15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount == 0) - { - NPCInfo->vlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 8) - { - if(NPCInfo->vlookCount > 0) + else if(NPCInfo->vlookCount == 0) { - NPCInfo->vlookCount++; + NPCInfo->vlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 8) { - NPCInfo->vlookCount--; + if(NPCInfo->vlookCount > 0) + { + NPCInfo->vlookCount++; + } + else//lookCount < 0 + { + NPCInfo->vlookCount--; + } } + + //turn toward investigateGoal + CalcEntitySpot( NPC, SPOT_HEAD, spot ); + VectorSubtract(NPCInfo->investigateGoal, spot, invDir); + VectorNormalize(invDir); + vectoangles(invDir, invAngles); + NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); + NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); } - //turn toward investigateGoal - CalcEntitySpot( NPC, SPOT_HEAD, spot ); - VectorSubtract(NPCInfo->investigateGoal, spot, invDir); - VectorNormalize(invDir); - vectoangles(invDir, invAngles); - NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); - NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); - } + NPC_UpdateAngles(qtrue, qtrue); - NPC_UpdateAngles(qtrue, qtrue); + NPCInfo->goalEntity = saveGoal; - NPCInfo->goalEntity = saveGoal; - - if(level.time > NPCInfo->investigateDebounceTime) - { - NPCInfo->tempBehavior = BS_DEFAULT; - } + if(level.time > NPCInfo->investigateDebounceTime) + { + NPCInfo->tempBehavior = BS_DEFAULT; + } - NPC_CheckSoundEvents(); - */ + NPC_CheckSoundEvents(); + */ } -qboolean NPC_CheckInvestigate( int alertEventNum ) -{ - gentity_t *owner = level.alertEvents[alertEventNum].owner; - int invAdd = level.alertEvents[alertEventNum].level; - vec3_t soundPos; - float soundRad = level.alertEvents[alertEventNum].radius; - float earshot = NPCInfo->stats.earshot; +qboolean NPC_CheckInvestigate(int alertEventNum) { + gentity_t *owner = level.alertEvents[alertEventNum].owner; + int invAdd = level.alertEvents[alertEventNum].level; + vec3_t soundPos; + float soundRad = level.alertEvents[alertEventNum].radius; + float earshot = NPCInfo->stats.earshot; - VectorCopy( level.alertEvents[alertEventNum].position, soundPos ); + VectorCopy(level.alertEvents[alertEventNum].position, soundPos); - //NOTE: Trying to preserve previous investigation behavior - if ( !owner ) - { + // NOTE: Trying to preserve previous investigation behavior + if (!owner) { return qfalse; } - if ( owner->s.eType != ET_PLAYER && owner == NPCInfo->goalEntity ) - { + if (owner->s.eType != ET_PLAYER && owner == NPCInfo->goalEntity) { return qfalse; } - if ( owner->s.eFlags & EF_NODRAW ) - { + if (owner->s.eFlags & EF_NODRAW) { return qfalse; } - if ( owner->flags & FL_NOTARGET ) - { + if (owner->flags & FL_NOTARGET) { return qfalse; } - if ( soundRad < earshot ) - { + if (soundRad < earshot) { return qfalse; } - //if(!gi.inPVSIgnorePortals(ent->currentOrigin, NPC->currentOrigin))//should we be able to hear through areaportals? - if ( !gi.inPVS( soundPos, NPC->currentOrigin ) ) - {//can hear through doors? + // if(!gi.inPVSIgnorePortals(ent->currentOrigin, NPC->currentOrigin))//should we be able to hear through areaportals? + if (!gi.inPVS(soundPos, NPC->currentOrigin)) { // can hear through doors? return qfalse; } - if ( owner->client && owner->client->playerTeam && NPC->client->playerTeam && owner->client->playerTeam != NPC->client->playerTeam ) - { - if( (float)NPCInfo->investigateCount >= (NPCInfo->stats.vigilance*200) && owner ) - {//If investigateCount == 10, just take it as enemy and go - if ( NPC_ValidEnemy( owner ) ) - {//FIXME: run angerscript - G_SetEnemy( NPC, owner ); + if (owner->client && owner->client->playerTeam && NPC->client->playerTeam && owner->client->playerTeam != NPC->client->playerTeam) { + if ((float)NPCInfo->investigateCount >= (NPCInfo->stats.vigilance * 200) && owner) { // If investigateCount == 10, just take it as enemy and go + if (NPC_ValidEnemy(owner)) { // FIXME: run angerscript + G_SetEnemy(NPC, owner); NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; NPCInfo->behaviorState = BS_HUNT_AND_KILL; return qtrue; } - } - else - { + } else { NPCInfo->investigateCount += invAdd; } - //run awakescript + // run awakescript G_ActivateBehavior(NPC, BSET_AWAKE); /* @@ -501,16 +452,13 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) } */ - //NPCInfo->hlookCount = NPCInfo->vlookCount = 0; + // NPCInfo->hlookCount = NPCInfo->vlookCount = 0; NPCInfo->eventOwner = owner; - VectorCopy( soundPos, NPCInfo->investigateGoal ); - if ( NPCInfo->investigateCount > 20 ) - { + VectorCopy(soundPos, NPCInfo->investigateGoal); + if (NPCInfo->investigateCount > 20) { NPCInfo->investigateDebounceTime = level.time + 10000; - } - else - { - NPCInfo->investigateDebounceTime = level.time + (NPCInfo->investigateCount*500); + } else { + NPCInfo->investigateDebounceTime = level.time + (NPCInfo->investigateCount * 500); } NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; @@ -519,17 +467,14 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) return qfalse; } - /* void NPC_BSSleep( void ) */ -void NPC_BSSleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qfalse ); +void NPC_BSSleep(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qfalse); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { G_ActivateBehavior(NPC, BSET_AWAKE); return; } @@ -546,41 +491,32 @@ void NPC_BSSleep( void ) */ } +extern qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset); -extern qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ); - -bool NPC_BSFollowLeader_UpdateLeader(void) -{ - if ( NPC->client->leader//have a leader - && NPC->client->leader->s.number < MAX_CLIENTS //player - && NPC->client->leader->client//player is a client - && !NPC->client->leader->client->pers.enterTime )//player has not finished spawning in yet - {//don't do anything just yet, but don't clear the leader either +bool NPC_BSFollowLeader_UpdateLeader(void) { + if (NPC->client->leader // have a leader + && NPC->client->leader->s.number < MAX_CLIENTS // player + && NPC->client->leader->client // player is a client + && !NPC->client->leader->client->pers.enterTime) // player has not finished spawning in yet + { // don't do anything just yet, but don't clear the leader either return false; } - if (NPC->client->leader && NPC->client->leader->health<=0) - { + if (NPC->client->leader && NPC->client->leader->health <= 0) { NPC->client->leader = NULL; } - if ( !NPC->client->leader ) - {//ok, stand guard until we find an enemy - if( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { + if (!NPC->client->leader) { // ok, stand guard until we find an enemy + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } - if ( NPCInfo->behaviorState == BS_FOLLOW_LEADER ) - { + if (NPCInfo->behaviorState == BS_FOLLOW_LEADER) { NPCInfo->behaviorState = BS_DEFAULT; } - if ( NPCInfo->defaultBehavior == BS_FOLLOW_LEADER ) - { + if (NPCInfo->defaultBehavior == BS_FOLLOW_LEADER) { NPCInfo->defaultBehavior = BS_DEFAULT; } return false; @@ -588,156 +524,115 @@ bool NPC_BSFollowLeader_UpdateLeader(void) return true; } - -void NPC_BSFollowLeader_UpdateEnemy(void) -{ - if ( !NPC->enemy ) - {//no enemy, find one - NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTimeenemy ) - {//just found one - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); - } - else - { - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int eventID = NPC_CheckAlertEvents( qtrue, qtrue ); - if ( eventID > -1 && level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - //NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam ) - {//not an enemy - } - else - { - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - G_SetEnemy( NPC, level.alertEvents[eventID].owner ); - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); +void NPC_BSFollowLeader_UpdateEnemy(void) { + if (!NPC->enemy) { // no enemy, find one + NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse); // don't find new enemy if this is tempbehav + if (NPC->enemy) { // just found one + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); + } else { + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int eventID = NPC_CheckAlertEvents(qtrue, qtrue); + if (eventID > -1 && level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + // NPCInfo->lastAlertID = level.alertEvents[eventID].ID; + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam) { // not an enemy + } else { + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for + // him? Or just let combat AI handle this... (act as if you lost him) + G_SetEnemy(NPC, level.alertEvents[eventID].owner); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 1000 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 1000)); } } - } } - if ( !NPC->enemy ) - { - if ( NPC->client->leader - && NPC->client->leader->enemy - && NPC->client->leader->enemy != NPC - && ( (NPC->client->leader->enemy->client&&NPC->client->leader->enemy->client->playerTeam==NPC->client->enemyTeam) - ||(NPC->client->leader->enemy->svFlags&SVF_NONNPC_ENEMY&&NPC->client->leader->enemy->noDamageTeam==NPC->client->enemyTeam) ) - && NPC->client->leader->enemy->health > 0 ) - { - G_SetEnemy( NPC, NPC->client->leader->enemy ); - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (!NPC->enemy) { + if (NPC->client->leader && NPC->client->leader->enemy && NPC->client->leader->enemy != NPC && + ((NPC->client->leader->enemy->client && NPC->client->leader->enemy->client->playerTeam == NPC->client->enemyTeam) || + (NPC->client->leader->enemy->svFlags & SVF_NONNPC_ENEMY && NPC->client->leader->enemy->noDamageTeam == NPC->client->enemyTeam)) && + NPC->client->leader->enemy->health > 0) { + G_SetEnemy(NPC, NPC->client->leader->enemy); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCInfo->enemyLastSeenTime = level.time; } } - } - else - { - if ( NPC->enemy->health <= 0 || (NPC->enemy->flags&FL_NOTARGET) ) - { - G_ClearEnemy( NPC ); - if ( NPCInfo->enemyCheckDebounceTime > level.time + 1000 ) - { - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 2000 ); + } else { + if (NPC->enemy->health <= 0 || (NPC->enemy->flags & FL_NOTARGET)) { + G_ClearEnemy(NPC); + if (NPCInfo->enemyCheckDebounceTime > level.time + 1000) { + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 2000); } - } - else if ( NPC->client->ps.weapon && NPCInfo->enemyCheckDebounceTime < level.time ) - { - NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTimetempBehavior!=BS_FOLLOW_LEADER), qfalse );//don't find new enemy if this is tempbehav + } else if (NPC->client->ps.weapon && NPCInfo->enemyCheckDebounceTime < level.time) { + NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time || NPCInfo->tempBehavior != BS_FOLLOW_LEADER), + qfalse); // don't find new enemy if this is tempbehav } } } - -bool NPC_BSFollowLeader_AttackEnemy(void) -{ - if ( NPC->client->ps.weapon == WP_SABER )//|| NPCInfo->confusionTime>level.time ) - {//lightsaber user or charmed enemy - if ( NPCInfo->tempBehavior != BS_FOLLOW_LEADER ) - {//not already in a temp bState - //go after the guy +bool NPC_BSFollowLeader_AttackEnemy(void) { + if (NPC->client->ps.weapon == WP_SABER) //|| NPCInfo->confusionTime>level.time ) + { // lightsaber user or charmed enemy + if (NPCInfo->tempBehavior != BS_FOLLOW_LEADER) { // not already in a temp bState + // go after the guy NPCInfo->tempBehavior = BS_HUNT_AND_KILL; NPC_UpdateAngles(qtrue, qtrue); return true; } } - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|CHECK_PVS| - if ( enemyVisibility > VIS_PVS ) - {//face - vec3_t enemy_org, muzzle, delta, angleToEnemy; + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|CHECK_PVS| + if (enemyVisibility > VIS_PVS) { // face + vec3_t enemy_org, muzzle, delta, angleToEnemy; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - VectorSubtract( enemy_org, muzzle, delta); - vectoangles( delta, angleToEnemy ); - VectorNormalize( delta ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); + VectorNormalize(delta); NPCInfo->desiredYaw = angleToEnemy[YAW]; NPCInfo->desiredPitch = angleToEnemy[PITCH]; - NPC_UpdateFiringAngles( qtrue, qtrue ); - - if ( enemyVisibility >= VIS_SHOOT ) - {//shoot - NPC_AimAdjust( 2 ); - if ( NPC_GetHFOVPercentage( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.hfov ) > 0.6f - && NPC_GetHFOVPercentage( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.vfov ) > 0.5f ) - {//actually withing our front cone - WeaponThink( qtrue ); + NPC_UpdateFiringAngles(qtrue, qtrue); + + if (enemyVisibility >= VIS_SHOOT) { // shoot + NPC_AimAdjust(2); + if (NPC_GetHFOVPercentage(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.hfov) > 0.6f && + NPC_GetHFOVPercentage(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.vfov) > + 0.5f) { // actually withing our front cone + WeaponThink(qtrue); } - } - else - { - NPC_AimAdjust( 1 ); + } else { + NPC_AimAdjust(1); } - //NPC_CheckCanAttack(1.0, qfalse); - } - else - { - NPC_AimAdjust( -1 ); + // NPC_CheckCanAttack(1.0, qfalse); + } else { + NPC_AimAdjust(-1); } return false; } -bool NPC_BSFollowLeader_CanAttack(void) -{ - return (NPC->enemy - && NPC->client->ps.weapon - && !(NPCInfo->aiFlags&NPCAI_HEAL_ROSH) //Kothos twins never go after their enemy - ); +bool NPC_BSFollowLeader_CanAttack(void) { + return (NPC->enemy && NPC->client->ps.weapon && !(NPCInfo->aiFlags & NPCAI_HEAL_ROSH) // Kothos twins never go after their enemy + ); } -bool NPC_BSFollowLeader_InFullBodyAttack(void) -{ - return ( - NPC->client->ps.legsAnim==BOTH_ATTACK1 || - NPC->client->ps.legsAnim==BOTH_ATTACK2 || - NPC->client->ps.legsAnim==BOTH_ATTACK3 || - NPC->client->ps.legsAnim==BOTH_MELEE1 || - NPC->client->ps.legsAnim==BOTH_MELEE2 - ); +bool NPC_BSFollowLeader_InFullBodyAttack(void) { + return (NPC->client->ps.legsAnim == BOTH_ATTACK1 || NPC->client->ps.legsAnim == BOTH_ATTACK2 || NPC->client->ps.legsAnim == BOTH_ATTACK3 || + NPC->client->ps.legsAnim == BOTH_MELEE1 || NPC->client->ps.legsAnim == BOTH_MELEE2); } -void NPC_BSFollowLeader_LookAtLeader(void) -{ - vec3_t head, leaderHead, delta, angleToLeader; +void NPC_BSFollowLeader_LookAtLeader(void) { + vec3_t head, leaderHead, delta, angleToLeader; - CalcEntitySpot( NPC->client->leader, SPOT_HEAD, leaderHead ); - CalcEntitySpot( NPC, SPOT_HEAD, head ); - VectorSubtract (leaderHead, head, delta); - vectoangles ( delta, angleToLeader ); + CalcEntitySpot(NPC->client->leader, SPOT_HEAD, leaderHead); + CalcEntitySpot(NPC, SPOT_HEAD, head); + VectorSubtract(leaderHead, head, delta); + vectoangles(delta, angleToLeader); VectorNormalize(delta); NPC->NPC->desiredYaw = angleToLeader[YAW]; NPC->NPC->desiredPitch = angleToLeader[PITCH]; @@ -745,26 +640,22 @@ void NPC_BSFollowLeader_LookAtLeader(void) NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSFollowLeader (void) -{ +void NPC_BSFollowLeader(void) { // If In A Jump, Return //---------------------- - if (NPC_Jumping()) - { + if (NPC_Jumping()) { return; } // If There Is No Leader, Return //------------------------------- - if (!NPC_BSFollowLeader_UpdateLeader()) - { + if (!NPC_BSFollowLeader_UpdateLeader()) { return; } // Don't Do Anything Else If In A Full Body Attack //------------------------------------------------- - if (NPC_BSFollowLeader_InFullBodyAttack()) - { + if (NPC_BSFollowLeader_InFullBodyAttack()) { return; } @@ -772,135 +663,104 @@ void NPC_BSFollowLeader (void) //------------------ NPC_BSFollowLeader_UpdateEnemy(); - // Do Any Attacking //------------------ - if (NPC_BSFollowLeader_CanAttack()) - { - if (NPC_BSFollowLeader_AttackEnemy()) - { + if (NPC_BSFollowLeader_CanAttack()) { + if (NPC_BSFollowLeader_AttackEnemy()) { return; } - } - else - { + } else { NPC_BSFollowLeader_LookAtLeader(); } + float followDist = (NPCInfo->followDist) ? (NPCInfo->followDist) : (110.0f); + bool moveSuccess; - - - - - float followDist = (NPCInfo->followDist)?(NPCInfo->followDist):(110.0f); - bool moveSuccess; - - STEER::Activate(NPC); + STEER::Activate(NPC); { - if (NPC->client->leader->client && NPC->client->leader->client->ps.groundEntityNum!=ENTITYNUM_NONE) - { + if (NPC->client->leader->client && NPC->client->leader->client->ps.groundEntityNum != ENTITYNUM_NONE) { // If Too Close, Back Away Some //------------------------------ - if (STEER::Reached(NPC, NPC->client->leader, 65.0f)) - { + if (STEER::Reached(NPC, NPC->client->leader, 65.0f)) { STEER::Evade(NPC, NPC->client->leader); - } - else - { + } else { // Attempt To Steer Directly To Our Goal //--------------------------------------- - moveSuccess = STEER::GoTo(NPC, NPC->client->leader, followDist); + moveSuccess = STEER::GoTo(NPC, NPC->client->leader, followDist); // Perhaps Not Close Enough? Try To Use The Navigation Grid //----------------------------------------------------------- - if (!moveSuccess) - { + if (!moveSuccess) { moveSuccess = NAV::GoTo(NPC, NPC->client->leader); - if (!moveSuccess) - { + if (!moveSuccess) { STEER::Stop(NPC); } } } - } - else - { + } else { STEER::Stop(NPC); } } STEER::DeActivate(NPC, &ucmd); } +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f +void NPC_BSJump(void) { + vec3_t dir, angles, p1, p2, apex; + float time, height, forward, z, xy, dist, yawError, apexHeight; - -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f -void NPC_BSJump (void) -{ - vec3_t dir, angles, p1, p2, apex; - float time, height, forward, z, xy, dist, yawError, apexHeight; - - if( !NPCInfo->goalEntity ) - {//Should have task completed the navgoal + if (!NPCInfo->goalEntity) { // Should have task completed the navgoal return; } - if ( NPCInfo->jumpState != JS_JUMPING && NPCInfo->jumpState != JS_LANDING ) - { - //Face navgoal + if (NPCInfo->jumpState != JS_JUMPING && NPCInfo->jumpState != JS_LANDING) { + // Face navgoal VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); vectoangles(dir, angles); NPCInfo->desiredPitch = NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); NPCInfo->desiredYaw = NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); } - NPC_UpdateAngles ( qtrue, qtrue ); - yawError = AngleDelta ( NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw ); - //We don't really care about pitch here + NPC_UpdateAngles(qtrue, qtrue); + yawError = AngleDelta(NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw); + // We don't really care about pitch here - switch ( NPCInfo->jumpState ) - { + switch (NPCInfo->jumpState) { case JS_FACING: - if ( yawError < MIN_ANGLE_ERROR ) - {//Facing it, Start crouching - NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (yawError < MIN_ANGLE_ERROR) { // Facing it, Start crouching + NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCInfo->jumpState = JS_CROUCHING; } break; case JS_CROUCHING: - if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing crouching anim + if (NPC->client->ps.legsAnimTimer > 0) { // Still playing crouching anim return; } - //Create a parabola + // Create a parabola - if ( NPC->currentOrigin[2] > NPCInfo->goalEntity->currentOrigin[2] ) - { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( NPCInfo->goalEntity->currentOrigin, p2 ); - } - else if ( NPC->currentOrigin[2] < NPCInfo->goalEntity->currentOrigin[2] ) - { - VectorCopy( NPCInfo->goalEntity->currentOrigin, p1 ); - VectorCopy( NPC->currentOrigin, p2 ); - } - else - { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( NPCInfo->goalEntity->currentOrigin, p2 ); + if (NPC->currentOrigin[2] > NPCInfo->goalEntity->currentOrigin[2]) { + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(NPCInfo->goalEntity->currentOrigin, p2); + } else if (NPC->currentOrigin[2] < NPCInfo->goalEntity->currentOrigin[2]) { + VectorCopy(NPCInfo->goalEntity->currentOrigin, p1); + VectorCopy(NPC->currentOrigin, p2); + } else { + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(NPCInfo->goalEntity->currentOrigin, p2); } - //z = xy*xy - VectorSubtract( p2, p1, dir ); + // z = xy*xy + VectorSubtract(p2, p1, dir); dir[2] = 0; - //Get xy and z diffs - xy = VectorNormalize( dir ); + // Get xy and z diffs + xy = VectorNormalize(dir); z = p1[2] - p2[2]; - apexHeight = APEX_HEIGHT/2; + apexHeight = APEX_HEIGHT / 2; /* //Determine most desirable apex height apexHeight = (APEX_HEIGHT * PARA_WIDTH/xy) + (APEX_HEIGHT * z/128); @@ -914,100 +774,88 @@ void NPC_BSJump (void) } */ - //FIXME: length of xy will change curve of parabola, need to account for this - //somewhere... PARA_WIDTH + // FIXME: length of xy will change curve of parabola, need to account for this + // somewhere... PARA_WIDTH z = (sqrt(apexHeight + z) - sqrt(apexHeight)); assert(z >= 0); -// gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); + // gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); // Don't need to set apex xy if NPC is jumping directly up. - if ( xy > 0.0f ) - { + if (xy > 0.0f) { xy -= z; xy *= 0.5; assert(xy > 0); } - VectorMA( p1, xy, dir, apex ); + VectorMA(p1, xy, dir, apex); apex[2] += apexHeight; VectorCopy(apex, NPC->pos1); - //Now we have the apex, aim for it + // Now we have the apex, aim for it height = apex[2] - NPC->currentOrigin[2]; - time = sqrt( height / ( .5 * NPC->client->ps.gravity ) ); - if ( !time ) - { -// gi.Printf("ERROR no time in jump\n"); + time = sqrt(height / (.5 * NPC->client->ps.gravity)); + if (!time) { + // gi.Printf("ERROR no time in jump\n"); return; } // set s.origin2 to the push velocity - VectorSubtract ( apex, NPC->currentOrigin, NPC->client->ps.velocity ); + VectorSubtract(apex, NPC->currentOrigin, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 0; - dist = VectorNormalize( NPC->client->ps.velocity ); + dist = VectorNormalize(NPC->client->ps.velocity); forward = dist / time; - VectorScale( NPC->client->ps.velocity, forward, NPC->client->ps.velocity ); + VectorScale(NPC->client->ps.velocity, forward, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = time * NPC->client->ps.gravity; -// gi.Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); + // gi.Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); NPCInfo->jumpState = JS_JUMPING; - //FIXME: jumpsound? + // FIXME: jumpsound? break; case JS_JUMPING: - if ( showBBoxes ) - { + if (showBBoxes) { VectorAdd(NPC->mins, NPC->pos1, p1); VectorAdd(NPC->maxs, NPC->pos1, p2); - CG_Cube( p1, p2, NPCDEBUG_BLUE, 0.5 ); + CG_Cube(p1, p2, NPCDEBUG_BLUE, 0.5); } - if ( NPC->s.groundEntityNum != ENTITYNUM_NONE) - {//Landed, start landing anim - //FIXME: if the + if (NPC->s.groundEntityNum != ENTITYNUM_NONE) { // Landed, start landing anim + // FIXME: if the VectorClear(NPC->client->ps.velocity); - NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCInfo->jumpState = JS_LANDING; - //FIXME: landsound? - } - else if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing jumping anim - //FIXME: apply jump velocity here, a couple frames after start, not right away + // FIXME: landsound? + } else if (NPC->client->ps.legsAnimTimer > 0) { // Still playing jumping anim + // FIXME: apply jump velocity here, a couple frames after start, not right away return; - } - else - {//still in air, but done with jump anim, play inair anim + } else { // still in air, but done with jump anim, play inair anim NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_OVERRIDE); } break; case JS_LANDING: - if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing landing anim + if (NPC->client->ps.legsAnimTimer > 0) { // Still playing landing anim return; - } - else - { + } else { NPCInfo->jumpState = JS_WAITING; NPCInfo->goalEntity = UpdateGoal(); // If he made it to his goal or his task is no longer pending. - if ( !NPCInfo->goalEntity || !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - { + if (!NPCInfo->goalEntity || !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { NPC_ClearGoal(); NPCInfo->goalTime = level.time; NPCInfo->aiFlags &= ~NPCAI_MOVING; ucmd.forwardmove = 0; NPC->flags &= ~FL_NO_KNOCKBACK; - //Return that the goal was reached - Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); + // Return that the goal was reached + Q3_TaskIDComplete(NPC, TID_MOVE_NAV); } } break; @@ -1018,12 +866,11 @@ void NPC_BSJump (void) } } -void NPC_BSRemove (void) -{ - NPC_UpdateAngles ( qtrue, qtrue ); - if( !gi.inPVS( NPC->currentOrigin, g_entities[0].currentOrigin ) )//FIXME: use cg.vieworg? +void NPC_BSRemove(void) { + NPC_UpdateAngles(qtrue, qtrue); + if (!gi.inPVS(NPC->currentOrigin, g_entities[0].currentOrigin)) // FIXME: use cg.vieworg? { - G_UseTargets2( NPC, NPC, NPC->target3 ); + G_UseTargets2(NPC, NPC, NPC->target3); NPC->s.eFlags |= EF_NODRAW; NPC->svFlags &= ~SVF_NPC; NPC->s.eType = ET_INVISIBLE; @@ -1031,58 +878,48 @@ void NPC_BSRemove (void) NPC->health = 0; NPC->targetname = NULL; - //Disappear in half a second + // Disappear in half a second NPC->e_ThinkFunc = thinkF_G_FreeEntity; NPC->nextthink = level.time + FRAMETIME; - }//FIXME: else allow for out of FOV??? + } // FIXME: else allow for out of FOV??? } -void NPC_BSSearch (void) -{ +void NPC_BSSearch(void) { NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER, qfalse); - //FIXME: do something with these alerts...? - //FIXME: do the Stormtrooper alert reaction? (investigation) - if ( (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) - && NPC->client->enemyTeam != TEAM_NEUTRAL ) - {//look for enemies + // FIXME: do something with these alerts...? + // FIXME: do the Stormtrooper alert reaction? (investigation) + if ((NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) && NPC->client->enemyTeam != TEAM_NEUTRAL) { // look for enemies NPC_CheckEnemy(qtrue, qfalse); - if ( NPC->enemy ) - {//found one - if( NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + if (NPC->enemy) { // found one + if (NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to run and shoot - NPCInfo->behaviorState = BS_DEFAULT;//BS_HUNT_AND_KILL; - //NPC_BSRunAndShoot(); + } else { // if bState, change to run and shoot + NPCInfo->behaviorState = BS_DEFAULT; // BS_HUNT_AND_KILL; + // NPC_BSRunAndShoot(); } return; } } - //FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must - //want us to do something else? If tempBehavior, just default, else set - //to run and shoot...? + // FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must + // want us to do something else? If tempBehavior, just default, else set + // to run and shoot...? - //FIXME: Reimplement + // FIXME: Reimplement - if ( !NPCInfo->investigateDebounceTime ) - {//On our way to a tempGoal - float minGoalReachedDistSquared = 32*32; - vec3_t vec; + if (!NPCInfo->investigateDebounceTime) { // On our way to a tempGoal + float minGoalReachedDistSquared = 32 * 32; + vec3_t vec; - //Keep moving toward our tempGoal + // Keep moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); - if ( vec[2] < 24 ) - { + VectorSubtract(NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); + if (vec[2] < 24) { vec[2] = 0; } - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { /* //FIXME: can't get the radius... float wpRadSq = waypoints[NPCInfo->tempGoal->waypoint].radius * waypoints[NPCInfo->tempGoal->waypoint].radius; @@ -1092,106 +929,83 @@ void NPC_BSSearch (void) } */ - minGoalReachedDistSquared = 32*32;//12*12; + minGoalReachedDistSquared = 32 * 32; // 12*12; } - if ( VectorLengthSquared( vec ) < minGoalReachedDistSquared ) - { - //Close enough, just got there + if (VectorLengthSquared(vec) < minGoalReachedDistSquared) { + // Close enough, just got there NPC->waypoint = NAV::GetNearestNode(NPC); - if ( ( NPCInfo->homeWp == WAYPOINT_NONE ) || ( NPC->waypoint == WAYPOINT_NONE ) ) - { - //Heading for or at an invalid waypoint, get out of this bState - if( NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + if ((NPCInfo->homeWp == WAYPOINT_NONE) || (NPC->waypoint == WAYPOINT_NONE)) { + // Heading for or at an invalid waypoint, get out of this bState + if (NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to stand guard + } else { // if bState, change to stand guard NPCInfo->behaviorState = BS_STAND_GUARD; NPC_BSRunAndShoot(); } return; } - if ( NPC->waypoint == NPCInfo->homeWp ) - { - //Just Reached our homeWp, if this is the first time, run your lostenemyscript - if ( NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP ) - { + if (NPC->waypoint == NPCInfo->homeWp) { + // Just Reached our homeWp, if this is the first time, run your lostenemyscript + if (NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP) { NPCInfo->aiFlags &= ~NPCAI_ENROUTE_TO_HOMEWP; - G_ActivateBehavior( NPC, BSET_LOSTENEMY ); + G_ActivateBehavior(NPC, BSET_LOSTENEMY); } - } - //gi.Printf("Got there.\n"); - //gi.Printf("Looking..."); - if( !Q_irand(0, 1) ) - { + // gi.Printf("Got there.\n"); + // gi.Printf("Looking..."); + if (!Q_irand(0, 1)) { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); - } - else - { + } else { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); - } - else - { - NPC_MoveToGoal( qtrue ); - } - } - else - { - //We're there - if ( NPCInfo->investigateDebounceTime > level.time ) - { - //Still waiting around for a bit - //Turn angles every now and then to look around - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { - if ( !Q_irand( 0, 30 ) ) - { + } else { + NPC_MoveToGoal(qtrue); + } + } else { + // We're there + if (NPCInfo->investigateDebounceTime > level.time) { + // Still waiting around for a bit + // Turn angles every now and then to look around + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { + if (!Q_irand(0, 30)) { // NAV_TODO: What if there are no neighbors? - vec3_t branchPos, lookDir; + vec3_t branchPos, lookDir; NAV::GetNodePosition(NAV::ChooseRandomNeighbor(NPCInfo->tempGoal->waypoint), branchPos); - VectorSubtract( branchPos, NPCInfo->tempGoal->currentOrigin, lookDir ); - NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); + VectorSubtract(branchPos, NPCInfo->tempGoal->currentOrigin, lookDir); + NPCInfo->desiredYaw = AngleNormalize360(vectoyaw(lookDir) + Q_flrand(-45, 45)); } } - //gi.Printf("."); - } - else - {//Just finished waiting + // gi.Printf("."); + } else { // Just finished waiting NPC->waypoint = NAV::GetNearestNode(NPC); - if ( NPC->waypoint == NPCInfo->homeWp ) - { + if (NPC->waypoint == NPCInfo->homeWp) { // NAV_TODO: What if there are no neighbors? int nextWp = NAV::ChooseRandomNeighbor(NPCInfo->tempGoal->waypoint); NAV::GetNodePosition(nextWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = nextWp; - } - else - {//At a branch, so return home + } else { // At a branch, so return home NAV::GetNodePosition(NPCInfo->homeWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = NPCInfo->homeWp; } NPCInfo->investigateDebounceTime = 0; - //Start moving toward our tempGoal + // Start moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -1200,16 +1014,15 @@ NPC_BSSearchStart ------------------------- */ -void NPC_BSSearchStart( int homeWp, bState_t bState ) -{ - //FIXME: Reimplement +void NPC_BSSearchStart(int homeWp, bState_t bState) { + // FIXME: Reimplement NPCInfo->homeWp = homeWp; NPCInfo->tempBehavior = bState; NPCInfo->aiFlags |= NPCAI_ENROUTE_TO_HOMEWP; NPCInfo->investigateDebounceTime = 0; NAV::GetNodePosition(homeWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = homeWp; - //gi.Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); + // gi.Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); } /* @@ -1220,21 +1033,19 @@ NPC_BSNoClip ------------------------- */ -void NPC_BSNoClip ( void ) -{ - if ( UpdateGoal() ) - { - vec3_t dir, forward, right, angles, up = {0, 0, 1}; - float fDot, rDot, uDot; +void NPC_BSNoClip(void) { + if (UpdateGoal()) { + vec3_t dir, forward, right, angles, up = {0, 0, 1}; + float fDot, rDot, uDot; - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); NPCInfo->desiredYaw = angles[YAW]; - AngleVectors( NPC->currentAngles, forward, right, NULL ); + AngleVectors(NPC->currentAngles, forward, right, NULL); - VectorNormalize( dir ); + VectorNormalize(dir); fDot = DotProduct(forward, dir) * 127; rDot = DotProduct(right, dir) * 127; @@ -1243,36 +1054,27 @@ void NPC_BSNoClip ( void ) ucmd.forwardmove = floor(fDot); ucmd.rightmove = floor(rDot); ucmd.upmove = floor(uDot); - } - else - { - //Cut velocity? - VectorClear( NPC->client->ps.velocity ); + } else { + // Cut velocity? + VectorClear(NPC->client->ps.velocity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSWander (void) -{//FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? +void NPC_BSWander(void) { // FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER, qfalse); - //FIXME: do something with these alerts...? - //FIXME: do the Stormtrooper alert reaction? (investigation) - if ( (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) - && NPC->client->enemyTeam != TEAM_NEUTRAL ) - {//look for enemies + // FIXME: do something with these alerts...? + // FIXME: do the Stormtrooper alert reaction? (investigation) + if ((NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) && NPC->client->enemyTeam != TEAM_NEUTRAL) { // look for enemies NPC_CheckEnemy(qtrue, qfalse); - if ( NPC->enemy ) - {//found one - if( NPCInfo->tempBehavior == BS_WANDER ) - {//if tempbehavior, set tempbehavior to default + if (NPC->enemy) { // found one + if (NPCInfo->tempBehavior == BS_WANDER) { // if tempbehavior, set tempbehavior to default NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to run and shoot - NPCInfo->behaviorState = BS_DEFAULT;//BS_HUNT_AND_KILL; - //NPC_BSRunAndShoot(); + } else { // if bState, change to run and shoot + NPCInfo->behaviorState = BS_DEFAULT; // BS_HUNT_AND_KILL; + // NPC_BSRunAndShoot(); } return; } @@ -1280,56 +1082,44 @@ void NPC_BSWander (void) STEER::Activate(NPC); - // Are We Doing A Path? //---------------------- - bool HasPath = NAV::HasPath(NPC); - if (HasPath) - { + bool HasPath = NAV::HasPath(NPC); + if (HasPath) { HasPath = NAV::UpdatePath(NPC); - if (HasPath) - { - STEER::Path(NPC); // Follow The Path + if (HasPath) { + STEER::Path(NPC); // Follow The Path STEER::AvoidCollisions(NPC); - if ((NPCInfo->aiFlags&NPCAI_BLOCKED) && (level.time-NPCInfo->blockedDebounceTime)>1000) - { - HasPath = false;// find a new one + if ((NPCInfo->aiFlags & NPCAI_BLOCKED) && (level.time - NPCInfo->blockedDebounceTime) > 1000) { + HasPath = false; // find a new one } } } - if (!HasPath) - { + if (!HasPath) { // If Debounce Time Has Expired, Choose A New Sub State //------------------------------------------------------ - if (NPCInfo->investigateDebounceTimeaiFlags&NPCAI_BLOCKED) && (level.time-NPCInfo->blockedDebounceTime)>1000)) - { + if (NPCInfo->investigateDebounceTime < level.time || ((NPCInfo->aiFlags & NPCAI_BLOCKED) && (level.time - NPCInfo->blockedDebounceTime) > 1000)) { // Clear Out Flags From The Previous Substate //-------------------------------------------- - NPCInfo->aiFlags &= ~NPCAI_OFF_PATH; - NPCInfo->aiFlags &= ~NPCAI_WALKING; - + NPCInfo->aiFlags &= ~NPCAI_OFF_PATH; + NPCInfo->aiFlags &= ~NPCAI_WALKING; // Pick Another Spot //------------------- - int NEXTSUBSTATE = Q_irand(0, 10); - - bool RandomPathNode = (NEXTSUBSTATE<9); //(NEXTSUBSTATE<4); - bool PathlessWander = false; //(NEXTSUBSTATE<9) - + int NEXTSUBSTATE = Q_irand(0, 10); + bool RandomPathNode = (NEXTSUBSTATE < 9); //(NEXTSUBSTATE<4); + bool PathlessWander = false; //(NEXTSUBSTATE<9) // Random Path Node //------------------ - if (RandomPathNode) - { + if (RandomPathNode) { // Sometimes, Walk //----------------- - if (Q_irand(0, 1)==0) - { - NPCInfo->aiFlags |= NPCAI_WALKING; + if (Q_irand(0, 1) == 0) { + NPCInfo->aiFlags |= NPCAI_WALKING; } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); @@ -1338,13 +1128,11 @@ void NPC_BSWander (void) // Pathless Wandering //-------------------- - else if (PathlessWander) - { + else if (PathlessWander) { // Sometimes, Walk //----------------- - if (Q_irand(0, 1)==0) - { - NPCInfo->aiFlags |= NPCAI_WALKING; + if (Q_irand(0, 1) == 0) { + NPCInfo->aiFlags |= NPCAI_WALKING; } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); @@ -1353,31 +1141,26 @@ void NPC_BSWander (void) // Just Stand Here //----------------- - else - { + else { NPCInfo->investigateDebounceTime = level.time + Q_irand(2000, 10000); - NPC_SetAnim(NPC, SETANIM_BOTH, ((Q_irand(0, 1)==0)?(BOTH_GUARD_LOOKAROUND1):(BOTH_GUARD_IDLE1)), SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC, SETANIM_BOTH, ((Q_irand(0, 1) == 0) ? (BOTH_GUARD_LOOKAROUND1) : (BOTH_GUARD_IDLE1)), SETANIM_FLAG_NORMAL); } } // Ok, So We Don't Have A Path, And Debounce Time Is Still Active, So We Are Either Wandering Or Looking Around //-------------------------------------------------------------------------------------------------------------- - else - { - if (NPCInfo->aiFlags & NPCAI_OFF_PATH) - { + else { + if (NPCInfo->aiFlags & NPCAI_OFF_PATH) { STEER::Wander(NPC); STEER::AvoidCollisions(NPC); - } - else - { + } else { STEER::Stop(NPC); } } } STEER::DeActivate(NPC, &ucmd); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -1407,16 +1190,13 @@ void NPC_BSFaceLeader (void) NPC_BSFlee ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void WP_DropWeapon( gentity_t *dropper, vec3_t velocity ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void WP_DropWeapon(gentity_t *dropper, vec3_t velocity); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); extern int g_crosshairEntNum; -qboolean NPC_CanSurrender( void ) -{ - if ( NPC->client ) - { - switch ( NPC->client->NPC_class ) - { +qboolean NPC_CanSurrender(void) { + if (NPC->client) { + switch (NPC->client->NPC_class) { case CLASS_ATST: case CLASS_CLAW: case CLASS_DESANN: @@ -1424,34 +1204,34 @@ qboolean NPC_CanSurrender( void ) case CLASS_FLIER2: case CLASS_GALAK: case CLASS_GLIDER: - case CLASS_GONK: // droid + case CLASS_GONK: // droid case CLASS_HOWLER: case CLASS_RANCOR: case CLASS_SAND_CREATURE: case CLASS_WAMPA: - case CLASS_INTERROGATOR: // droid + case CLASS_INTERROGATOR: // droid case CLASS_JAN: case CLASS_JEDI: case CLASS_KYLE: case CLASS_LANDO: case CLASS_LIZARD: case CLASS_LUKE: - case CLASS_MARK1: // droid - case CLASS_MARK2: // droid - case CLASS_GALAKMECH: // droid + case CLASS_MARK1: // droid + case CLASS_MARK2: // droid + case CLASS_GALAKMECH: // droid case CLASS_MINEMONSTER: case CLASS_MONMOTHA: case CLASS_MORGANKATARN: - case CLASS_MOUSE: // droid + case CLASS_MOUSE: // droid case CLASS_MURJJ: - case CLASS_PROBE: // droid - case CLASS_PROTOCOL: // droid - case CLASS_R2D2: // droid - case CLASS_R5D2: // droid + case CLASS_PROBE: // droid + case CLASS_PROTOCOL: // droid + case CLASS_R2D2: // droid + case CLASS_R5D2: // droid case CLASS_REBORN: case CLASS_REELO: case CLASS_REMOTE: - case CLASS_SEEKER: // droid + case CLASS_SEEKER: // droid case CLASS_SENTRY: case CLASS_SHADOWTROOPER: case CLASS_SWAMP: @@ -1470,201 +1250,152 @@ qboolean NPC_CanSurrender( void ) default: break; } - if ( !G_StandardHumanoid( NPC ) ) - { + if (!G_StandardHumanoid(NPC)) { return qfalse; } - if ( NPC->client->ps.weapon == WP_SABER ) - { + if (NPC->client->ps.weapon == WP_SABER) { return qfalse; } } - if ( NPCInfo ) - { - if ( (NPCInfo->aiFlags&NPCAI_BOSS_CHARACTER) ) - { + if (NPCInfo) { + if ((NPCInfo->aiFlags & NPCAI_BOSS_CHARACTER)) { return qfalse; } - if ( (NPCInfo->aiFlags&NPCAI_SUBBOSS_CHARACTER) ) - { + if ((NPCInfo->aiFlags & NPCAI_SUBBOSS_CHARACTER)) { return qfalse; } - if ( (NPCInfo->aiFlags&NPCAI_ROSH) ) - { + if ((NPCInfo->aiFlags & NPCAI_ROSH)) { return qfalse; } - if ( (NPCInfo->aiFlags&NPCAI_HEAL_ROSH) ) - { + if ((NPCInfo->aiFlags & NPCAI_HEAL_ROSH)) { return qfalse; } } return qtrue; } -void NPC_Surrender( void ) -{//FIXME: say "don't shoot!" if we weren't already surrendering - if ( NPC->client->ps.weaponTime || PM_InKnockDown( &NPC->client->ps ) ) - { +void NPC_Surrender(void) { // FIXME: say "don't shoot!" if we weren't already surrendering + if (NPC->client->ps.weaponTime || PM_InKnockDown(&NPC->client->ps)) { return; } - if ( !NPC_CanSurrender() ) - { + if (!NPC_CanSurrender()) { return; } - if ( NPC->s.weapon != WP_NONE && - NPC->s.weapon != WP_MELEE && - NPC->s.weapon != WP_SABER ) - { - WP_DropWeapon( NPC, NULL ); + if (NPC->s.weapon != WP_NONE && NPC->s.weapon != WP_MELEE && NPC->s.weapon != WP_SABER) { + WP_DropWeapon(NPC, NULL); } - if ( NPCInfo->surrenderTime < level.time - 5000 ) - {//haven't surrendered for at least 6 seconds, tell them what you're doing - //FIXME: need real dialogue EV_SURRENDER - NPCInfo->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( NPC, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 3000 ); + if (NPCInfo->surrenderTime < level.time - 5000) { // haven't surrendered for at least 6 seconds, tell them what you're doing + // FIXME: need real dialogue EV_SURRENDER + NPCInfo->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(NPC, Q_irand(EV_PUSHED1, EV_PUSHED3), 3000); } // Already Surrendering? If So, Just Update Animations //------------------------------------------------------ - if (NPCInfo->surrenderTime>level.time) - { - if (NPC->client->ps.torsoAnim==BOTH_COWER1_START && NPC->client->ps.torsoAnimTimer<=100) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_COWER1, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer; + if (NPCInfo->surrenderTime > level.time) { + if (NPC->client->ps.torsoAnim == BOTH_COWER1_START && NPC->client->ps.torsoAnimTimer <= 100) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_COWER1, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer; } - if (NPC->client->ps.torsoAnim==BOTH_COWER1 && NPC->client->ps.torsoAnimTimer<=100) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_COWER1_STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer; + if (NPC->client->ps.torsoAnim == BOTH_COWER1 && NPC->client->ps.torsoAnimTimer <= 100) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_COWER1_STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer; } } // New To The Surrender, So Start The Animation //---------------------------------------------- - else - { - if ( NPC->client->NPC_class == CLASS_JAWA && NPC->client->ps.weapon == WP_NONE ) - {//an unarmed Jawa is very scared - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_COWER1, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - //FIXME: stop doing this if decide to take off and run - } - else - { + else { + if (NPC->client->NPC_class == CLASS_JAWA && NPC->client->ps.weapon == WP_NONE) { // an unarmed Jawa is very scared + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_COWER1, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + // FIXME: stop doing this if decide to take off and run + } else { // A Big Monster? OR: Being Tracked By A Homing Rocket? So Do The Cower Sequence //------------------------------------------ - if ( (NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class==CLASS_RANCOR) || !TIMER_Done( NPC, "rocketChasing" ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_COWER1_START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); + if ((NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_RANCOR) || !TIMER_Done(NPC, "rocketChasing")) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_COWER1_START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); } // Otherwise, Use The Old Surrender "Arms In Air" Animation //---------------------------------------------------------- - else - { - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPC->client->ps.torsoAnimTimer = Q_irand(3000, 8000); // Pretend the anim lasts longer + else { + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPC->client->ps.torsoAnimTimer = Q_irand(3000, 8000); // Pretend the anim lasts longer } } - NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer + 1000; + NPCInfo->surrenderTime = level.time + NPC->client->ps.torsoAnimTimer + 1000; } } -qboolean NPC_CheckSurrender( void ) -{ - if ( !g_AIsurrender->integer - && NPC->client->NPC_class != CLASS_UGNAUGHT - && NPC->client->NPC_class != CLASS_JAWA ) - {//not enabled +qboolean NPC_CheckSurrender(void) { + if (!g_AIsurrender->integer && NPC->client->NPC_class != CLASS_UGNAUGHT && NPC->client->NPC_class != CLASS_JAWA) { // not enabled return qfalse; } - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) //not scripted to go somewhere - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE //not in the air - && !NPC->client->ps.weaponTime && !PM_InKnockDown( &NPC->client->ps )//not firing and not on the ground - && NPC->enemy && NPC->enemy->client && NPC->enemy->enemy == NPC && NPC->enemy->s.weapon != WP_NONE && (NPC->enemy->s.weapon != WP_MELEE || (NPC->enemy->client->NPC_class == CLASS_RANCOR||NPC->enemy->client->NPC_class == CLASS_WAMPA) )//enemy is using a weapon or is a Rancor or Wampa - && NPC->enemy->health > 20 && NPC->enemy->painDebounceTime < level.time - 3000 && NPC->enemy->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time - 1000 ) - {//don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the enemy is not mad at me or is hurt or not a threat or busy being attacked - //FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? - if ( NPC->s.weapon != WP_ROCKET_LAUNCHER - && NPC->s.weapon != WP_CONCUSSION - && NPC->s.weapon != WP_REPEATER - && NPC->s.weapon != WP_FLECHETTE - && NPC->s.weapon != WP_SABER ) - {//jedi and heavy weapons guys never surrender - //FIXME: rework all this logic into some orderly fashion!!! - if ( NPC->s.weapon != WP_NONE ) - {//they have a weapon so they'd have to drop it to surrender - //don't give up unless low on health - if ( NPC->health > 25 || NPC->health >= NPC->max_health ) - { + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV) // not scripted to go somewhere + && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE // not in the air + && !NPC->client->ps.weaponTime && !PM_InKnockDown(&NPC->client->ps) // not firing and not on the ground + && NPC->enemy && NPC->enemy->client && NPC->enemy->enemy == NPC && NPC->enemy->s.weapon != WP_NONE && + (NPC->enemy->s.weapon != WP_MELEE || + (NPC->enemy->client->NPC_class == CLASS_RANCOR || NPC->enemy->client->NPC_class == CLASS_WAMPA)) // enemy is using a weapon or is a Rancor or Wampa + && NPC->enemy->health > 20 && NPC->enemy->painDebounceTime < level.time - 3000 && + NPC->enemy->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < + level.time - 1000) { // don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the + // enemy is not mad at me or is hurt or not a threat or busy being attacked + // FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? + if (NPC->s.weapon != WP_ROCKET_LAUNCHER && NPC->s.weapon != WP_CONCUSSION && NPC->s.weapon != WP_REPEATER && NPC->s.weapon != WP_FLECHETTE && + NPC->s.weapon != WP_SABER) { // jedi and heavy weapons guys never surrender + // FIXME: rework all this logic into some orderly fashion!!! + if (NPC->s.weapon != WP_NONE) { // they have a weapon so they'd have to drop it to surrender + // don't give up unless low on health + if (NPC->health > 25 || NPC->health >= NPC->max_health) { return qfalse; } - if ( g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time ) - {//if he just shot me, always give up - //fall through - } - else - {//don't give up unless facing enemy and he's very close - if ( !InFOV( player, NPC, 60, 30 ) ) - {//I'm not looking at them + if (g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time) { // if he just shot me, always give up + // fall through + } else { // don't give up unless facing enemy and he's very close + if (!InFOV(player, NPC, 60, 30)) { // I'm not looking at them return qfalse; - } - else if ( DistanceSquared( NPC->currentOrigin, player->currentOrigin ) < 65536/*256*256*/ ) - {//they're not close + } else if (DistanceSquared(NPC->currentOrigin, player->currentOrigin) < 65536 /*256*256*/) { // they're not close return qfalse; - } - else if ( !gi.inPVS( NPC->currentOrigin, player->currentOrigin ) ) - {//they're not in the same room + } else if (!gi.inPVS(NPC->currentOrigin, player->currentOrigin)) { // they're not in the same room return qfalse; } } } - if ( !NPCInfo->group || (NPCInfo->group && NPCInfo->group->numGroup <= 1) ) - {//I'm alone but I was in a group//FIXME: surrender anyway if just melee or no weap? - if ( NPC->s.weapon == WP_NONE - //NPC has a weapon - || NPC->enemy == player - || (NPC->enemy->s.weapon == WP_SABER&&NPC->enemy->client&&NPC->enemy->client->ps.SaberActive()) - || (NPC->enemy->NPC && NPC->enemy->NPC->group && NPC->enemy->NPC->group->numGroup > 2) ) - {//surrender only if have no weapon or fighting a player or jedi or if we are outnumbered at least 3 to 1 - if ( NPC->enemy == player ) - {//player is the guy I'm running from - if ( g_crosshairEntNum == NPC->s.number ) - {//give up if player is aiming at me + if (!NPCInfo->group || + (NPCInfo->group && NPCInfo->group->numGroup <= 1)) { // I'm alone but I was in a group//FIXME: surrender anyway if just melee or no weap? + if (NPC->s.weapon == WP_NONE + // NPC has a weapon + || NPC->enemy == player || (NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && NPC->enemy->client->ps.SaberActive()) || + (NPC->enemy->NPC && NPC->enemy->NPC->group && + NPC->enemy->NPC->group->numGroup > + 2)) { // surrender only if have no weapon or fighting a player or jedi or if we are outnumbered at least 3 to 1 + if (NPC->enemy == player) { // player is the guy I'm running from + if (g_crosshairEntNum == NPC->s.number) { // give up if player is aiming at me NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else if ( player->s.weapon == WP_SABER ) - {//player is using saber - if ( InFOV( NPC, player, 60, 30 ) ) - {//they're looking at me - if ( DistanceSquared( NPC->currentOrigin, player->currentOrigin ) < 16384/*128*128*/ ) - {//they're close - if ( gi.inPVS( NPC->currentOrigin, player->currentOrigin ) ) - {//they're in the same room + } else if (player->s.weapon == WP_SABER) { // player is using saber + if (InFOV(NPC, player, 60, 30)) { // they're looking at me + if (DistanceSquared(NPC->currentOrigin, player->currentOrigin) < 16384 /*128*128*/) { // they're close + if (gi.inPVS(NPC->currentOrigin, player->currentOrigin)) { // they're in the same room NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } } } - } - else if ( NPC->enemy ) - {//??? - //should NPC's surrender to others? - if ( InFOV( NPC, NPC->enemy, 30, 30 ) ) - {//they're looking at me - float maxDist = (64+(NPC->maxs[0]*1.5)+(NPC->enemy->maxs[0]*1.5)); + } else if (NPC->enemy) { //??? + // should NPC's surrender to others? + if (InFOV(NPC, NPC->enemy, 30, 30)) { // they're looking at me + float maxDist = (64 + (NPC->maxs[0] * 1.5) + (NPC->enemy->maxs[0] * 1.5)); maxDist *= maxDist; - if ( DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ) < maxDist ) - {//they're close - if ( gi.inPVS( NPC->currentOrigin, NPC->enemy->currentOrigin ) ) - {//they're in the same room - //FIXME: should player-team NPCs not fire on surrendered NPCs? + if (DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin) < maxDist) { // they're close + if (gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) { // they're in the same room + // FIXME: should player-team NPCs not fire on surrendered NPCs? NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -1677,158 +1408,121 @@ qboolean NPC_CheckSurrender( void ) return qfalse; } -void NPC_JawaFleeSound( void ) -{ - if ( NPC - && NPC->client - && NPC->client->NPC_class == CLASS_JAWA - && !Q_irand( 0, 3 ) - && NPCInfo->blockedSpeechDebounceTime < level.time - && !Q3_TaskIDPending(NPC, TID_CHAN_VOICE ) ) - {//ooteenee!!!! - //Com_Printf( "ooteenee!!!!\n" ); - G_SoundOnEnt(NPC, CHAN_VOICE, "sound/chars/jawa/misc/ooh-tee-nee.wav" ); +void NPC_JawaFleeSound(void) { + if (NPC && NPC->client && NPC->client->NPC_class == CLASS_JAWA && !Q_irand(0, 3) && NPCInfo->blockedSpeechDebounceTime < level.time && + !Q3_TaskIDPending(NPC, TID_CHAN_VOICE)) { // ooteenee!!!! + // Com_Printf( "ooteenee!!!!\n" ); + G_SoundOnEnt(NPC, CHAN_VOICE, "sound/chars/jawa/misc/ooh-tee-nee.wav"); NPCInfo->blockedSpeechDebounceTime = level.time + 2000; } } -extern gentity_t *NPC_SearchForWeapons( void ); -extern qboolean G_CanPickUpWeapons( gentity_t *other ); -qboolean NPC_BSFlee( void ) -{ - bool enemyRecentlySeen = false; - float enemyTooCloseDist = 50.0f; - bool reachedEscapePoint = false; - bool hasEscapePoint = false; - bool moveSuccess = false; - bool inSurrender = (level.timesurrenderTime); - - +extern gentity_t *NPC_SearchForWeapons(void); +extern qboolean G_CanPickUpWeapons(gentity_t *other); +qboolean NPC_BSFlee(void) { + bool enemyRecentlySeen = false; + float enemyTooCloseDist = 50.0f; + bool reachedEscapePoint = false; + bool hasEscapePoint = false; + bool moveSuccess = false; + bool inSurrender = (level.time < NPCInfo->surrenderTime); // Check For Enemies And Alert Events //------------------------------------ NPC_CheckEnemy(qtrue, qfalse); NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER, qfalse); - if (NPC->enemy && G_ClearLOS(NPC, NPC->enemy)) - { + if (NPC->enemy && G_ClearLOS(NPC, NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; } - enemyRecentlySeen = (NPC->enemy && (level.time - NPCInfo->enemyLastSeenTime)<3000); - if (enemyRecentlySeen) - { - if (NPC->enemy->client && NPC->enemy->client->NPC_class==CLASS_RANCOR) - { + enemyRecentlySeen = (NPC->enemy && (level.time - NPCInfo->enemyLastSeenTime) < 3000); + if (enemyRecentlySeen) { + if (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_RANCOR) { enemyTooCloseDist = 400.0f; } enemyTooCloseDist += NPC->maxs[0] + NPC->enemy->maxs[0]; } - // Look For Weapons To Pick Up //----------------------------- - if (enemyRecentlySeen && // Is There An Enemy Near? - NPC->client->NPC_class!=CLASS_PRISONER && // Prisoners can't pickup weapons - NPCInfo->rank>RANK_CIVILIAN && // Neither can civilians - TIMER_Done(NPC, "panic") && // Panic causes him to run for a bit, don't pickup weapons - TIMER_Done(NPC, "CheckForWeaponToPickup") && - G_CanPickUpWeapons( NPC ) //Allowed To Pick Up Dropped Weapons - ) - { + if (enemyRecentlySeen && // Is There An Enemy Near? + NPC->client->NPC_class != CLASS_PRISONER && // Prisoners can't pickup weapons + NPCInfo->rank > RANK_CIVILIAN && // Neither can civilians + TIMER_Done(NPC, "panic") && // Panic causes him to run for a bit, don't pickup weapons + TIMER_Done(NPC, "CheckForWeaponToPickup") && G_CanPickUpWeapons(NPC) // Allowed To Pick Up Dropped Weapons + ) { gentity_t *foundWeap = NPC_SearchForWeapons(); // Ok, There Is A Weapon! Try Going To It! //------------------------------------------ - if (foundWeap && NAV::SafePathExists(NPC->currentOrigin, foundWeap->currentOrigin, NPC->enemy->currentOrigin, 150.0f)) - { - NAV::ClearPath(NPC); // Remove Any Old Path + if (foundWeap && NAV::SafePathExists(NPC->currentOrigin, foundWeap->currentOrigin, NPC->enemy->currentOrigin, 150.0f)) { + NAV::ClearPath(NPC); // Remove Any Old Path - NPCInfo->goalEntity = foundWeap; // Change Our Target Goal - NPCInfo->goalRadius = 30.0f; // 30 good enough? + NPCInfo->goalEntity = foundWeap; // Change Our Target Goal + NPCInfo->goalRadius = 30.0f; // 30 good enough? TIMER_Set(NPC, "CheckForWeaponToPickup", Q_irand(10000, 50000)); } // Look Again Soon //----------------- - else - { + else { TIMER_Set(NPC, "CheckForWeaponToPickup", Q_irand(1000, 5000)); } } // If Attempting To Get To An Entity That Is Gone, Clear The Pointer //------------------------------------------------------------------- - if ( NPCInfo->goalEntity - && !Q3_TaskIDPending(NPC, TID_MOVE_NAV) - && NPC->enemy - && Distance( NPCInfo->goalEntity->currentOrigin, NPC->enemy->currentOrigin ) < enemyTooCloseDist ) - { - //our goal is too close to our enemy, dump it... + if (NPCInfo->goalEntity && !Q3_TaskIDPending(NPC, TID_MOVE_NAV) && NPC->enemy && + Distance(NPCInfo->goalEntity->currentOrigin, NPC->enemy->currentOrigin) < enemyTooCloseDist) { + // our goal is too close to our enemy, dump it... NPCInfo->goalEntity = NULL; } - if (NPCInfo->goalEntity && !NPCInfo->goalEntity->inuse) - { + if (NPCInfo->goalEntity && !NPCInfo->goalEntity->inuse) { NPCInfo->goalEntity = 0; } - hasEscapePoint = (NPCInfo->goalEntity && NPCInfo->goalRadius!=0.0f); - - - + hasEscapePoint = (NPCInfo->goalEntity && NPCInfo->goalRadius != 0.0f); STEER::Activate(NPC); { // Have We Reached The Escape Point? //----------------------------------- - if (hasEscapePoint && STEER::Reached(NPC, NPCInfo->goalEntity, NPCInfo->goalRadius, false)) - { - if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) - { + if (hasEscapePoint && STEER::Reached(NPC, NPCInfo->goalEntity, NPCInfo->goalRadius, false)) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { Q3_TaskIDComplete(NPC, TID_MOVE_NAV); } reachedEscapePoint = true; } - // If Super Close To The Enemy, Run In The Other Direction //--------------------------------------------------------- - if (enemyRecentlySeen && - Distance(NPC->enemy->currentOrigin, NPC->currentOrigin)enemy->currentOrigin, NPC->currentOrigin) < enemyTooCloseDist) { STEER::Evade(NPC, NPC->enemy); STEER::AvoidCollisions(NPC); } // If Already At The Escape Point, Or Surrendering, Don't Move //------------------------------------------------------------- - else if (reachedEscapePoint || inSurrender) - { + else if (reachedEscapePoint || inSurrender) { STEER::Stop(NPC); - } - else - { + } else { // Try To Get To The Escape Point //-------------------------------- - if (hasEscapePoint) - { + if (hasEscapePoint) { moveSuccess = STEER::GoTo(NPC, NPCInfo->goalEntity, true); - if (!moveSuccess) - { + if (!moveSuccess) { moveSuccess = NAV::GoTo(NPC, NPCInfo->goalEntity, 0.3f); } } // Cant Get To The Escape Point, So If There Is An Enemy //------------------------------------------------------- - if (!moveSuccess && enemyRecentlySeen) - { + if (!moveSuccess && enemyRecentlySeen) { // Try To Get To The Farthest Combat Point From Him //-------------------------------------------------- NAV::TNodeHandle Nbr = NAV::ChooseFarthestNeighbor(NPC, NPC->enemy->currentOrigin, 0.25f); - if (Nbr>0) - { + if (Nbr > 0) { moveSuccess = STEER::GoTo(NPC, NAV::GetNodePosition(Nbr), true); - if (!moveSuccess) - { + if (!moveSuccess) { moveSuccess = NAV::GoTo(NPC, Nbr, 0.3f); } } @@ -1836,46 +1530,35 @@ qboolean NPC_BSFlee( void ) // If We Still Can't (Or Don't Need To) Move, Just Stop //------------------------------------------------------ - if (!moveSuccess) - { + if (!moveSuccess) { STEER::Stop(NPC); } } } STEER::DeActivate(NPC, &ucmd); - // Is There An Enemy Around? //--------------------------- - if (enemyRecentlySeen) - { + if (enemyRecentlySeen) { // Time To Surrender? //-------------------- - if ( TIMER_Done( NPC, "panic" ) ) - { - //done panicking, time to realize we're dogmeat, if we haven't been able to flee for a few seconds - if ((level.time-NPC->lastMoveTime)>3000 - && (level.time-NPCInfo->surrenderTime) > 3000 )//and haven't just finished surrendering + if (TIMER_Done(NPC, "panic")) { + // done panicking, time to realize we're dogmeat, if we haven't been able to flee for a few seconds + if ((level.time - NPC->lastMoveTime) > 3000 && (level.time - NPCInfo->surrenderTime) > 3000) // and haven't just finished surrendering { NPC_FaceEnemy(); NPC_Surrender(); - } + } } // Time To Choose A New Escape Point? //------------------------------------ - if ((!hasEscapePoint || reachedEscapePoint) && TIMER_Done(NPC, "FindNewEscapePointDebounce")) - { + if ((!hasEscapePoint || reachedEscapePoint) && TIMER_Done(NPC, "FindNewEscapePointDebounce")) { TIMER_Set(NPC, "FindNewEscapePointDebounce", 2500); - int escapePoint = NPC_FindCombatPoint( - NPC->currentOrigin, - NPC->enemy->currentOrigin, - NPC->currentOrigin, - CP_COVER|CP_AVOID_ENEMY|CP_HAS_ROUTE, - 128 ); - if (escapePoint!=-1) - { + int escapePoint = + NPC_FindCombatPoint(NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->currentOrigin, CP_COVER | CP_AVOID_ENEMY | CP_HAS_ROUTE, 128); + if (escapePoint != -1) { NPC_JawaFleeSound(); NPC_SetCombatPoint(escapePoint); NPC_SetMoveGoal(NPC, level.combatPoints[escapePoint].origin, 8, qtrue, escapePoint); @@ -1883,148 +1566,120 @@ qboolean NPC_BSFlee( void ) } } - // If Only Temporarly In Flee, Think About Perhaps Returning To Combat //--------------------------------------------------------------------- - if (NPCInfo->tempBehavior==BS_FLEE && - TIMER_Done(NPC, "flee") && - NPC->s.weapon != WP_NONE && - NPC->s.weapon != WP_MELEE - ) - { - NPCInfo->tempBehavior = BS_DEFAULT; + if (NPCInfo->tempBehavior == BS_FLEE && TIMER_Done(NPC, "flee") && NPC->s.weapon != WP_NONE && NPC->s.weapon != WP_MELEE) { + NPCInfo->tempBehavior = BS_DEFAULT; } // Always Update Angles //---------------------- - NPC_UpdateAngles( qtrue, qtrue ); - if (reachedEscapePoint) - { + NPC_UpdateAngles(qtrue, qtrue); + if (reachedEscapePoint) { return qtrue; } return qfalse; } -void NPC_StartFlee( gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't interrupt that! +void NPC_StartFlee(gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't interrupt that! return; } - if (NPCInfo->scriptFlags & SCF_DONT_FLEE ) // no flee for you + if (NPCInfo->scriptFlags & SCF_DONT_FLEE) // no flee for you { return; } - - //if have a fleescript, run that instead - if ( G_ActivateBehavior( NPC, BSET_FLEE ) ) - { + // if have a fleescript, run that instead + if (G_ActivateBehavior(NPC, BSET_FLEE)) { return; } - //FIXME: play a flee sound? Appropriate to situation? - if ( enemy ) - { + // FIXME: play a flee sound? Appropriate to situation? + if (enemy) { NPC_JawaFleeSound(); - G_SetEnemy( NPC, enemy ); + G_SetEnemy(NPC, enemy); } - - //FIXME: if don't have a weapon, find nearest one we have a route to and run for it? + // FIXME: if don't have a weapon, find nearest one we have a route to and run for it? int cp = -1; - if ( dangerLevel > AEL_DANGER || NPC->s.weapon == WP_NONE || ((!NPCInfo->group || NPCInfo->group->numGroup <= 1) && NPC->health <= 10 ) ) - {//IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS - cp = NPC_FindCombatPoint( NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER|CP_AVOID|CP_HAS_ROUTE|CP_NO_PVS, 128 ); - } - //FIXME: still happens too often... - if ( cp == -1 ) - {//okay give up on the no PVS thing - cp = NPC_FindCombatPoint( NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER|CP_AVOID|CP_HAS_ROUTE, 128 ); - if ( cp == -1 ) - {//okay give up on the avoid - cp = NPC_FindCombatPoint( NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER|CP_HAS_ROUTE, 128 ); - if ( cp == -1 ) - {//okay give up on the cover - cp = NPC_FindCombatPoint( NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_HAS_ROUTE, 128 ); + if (dangerLevel > AEL_DANGER || NPC->s.weapon == WP_NONE || + ((!NPCInfo->group || NPCInfo->group->numGroup <= 1) && + NPC->health <= 10)) { // IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS + cp = NPC_FindCombatPoint(NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER | CP_AVOID | CP_HAS_ROUTE | CP_NO_PVS, 128); + } + // FIXME: still happens too often... + if (cp == -1) { // okay give up on the no PVS thing + cp = NPC_FindCombatPoint(NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER | CP_AVOID | CP_HAS_ROUTE, 128); + if (cp == -1) { // okay give up on the avoid + cp = NPC_FindCombatPoint(NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_COVER | CP_HAS_ROUTE, 128); + if (cp == -1) { // okay give up on the cover + cp = NPC_FindCombatPoint(NPC->currentOrigin, dangerPoint, NPC->currentOrigin, CP_HAS_ROUTE, 128); } } } - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); - } - else - {//couldn't find a place to hide - //FIXME: re-implement the old BS_FLEE behavior of following any the waypoint edge + // see if we got a valid one + if (cp != -1) { // found a combat point + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + } else { // couldn't find a place to hide + // FIXME: re-implement the old BS_FLEE behavior of following any the waypoint edge // that leads away from the danger point. - NPC_SetMoveGoal( NPC, NPC->currentOrigin, 0/*goalRadius*/, qtrue, cp ); + NPC_SetMoveGoal(NPC, NPC->currentOrigin, 0 /*goalRadius*/, qtrue, cp); } - if ( dangerLevel > AEL_DANGER//geat danger always makes people turn and run - || NPC->s.weapon == WP_NONE //melee/unarmed guys turn and run, others keep facing you and shooting - || NPC->s.weapon == WP_MELEE - || NPC->s.weapon == WP_TUSKEN_STAFF ) - { - NPCInfo->tempBehavior = BS_FLEE;//we don't want to do this forever! - //FIXME: only make it temp if you have a weapon? Otherwise, permanent? - // NPCInfo->behaviorState = BS_FLEE; - // NPCInfo->tempBehavior = BS_DEFAULT; + if (dangerLevel > AEL_DANGER // geat danger always makes people turn and run + || NPC->s.weapon == WP_NONE // melee/unarmed guys turn and run, others keep facing you and shooting + || NPC->s.weapon == WP_MELEE || NPC->s.weapon == WP_TUSKEN_STAFF) { + NPCInfo->tempBehavior = BS_FLEE; // we don't want to do this forever! + // FIXME: only make it temp if you have a weapon? Otherwise, permanent? + // NPCInfo->behaviorState = BS_FLEE; + // NPCInfo->tempBehavior = BS_DEFAULT; } - //FIXME: localize this Timer? - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - //FIXME: is this always applicable? + // FIXME: localize this Timer? + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + // FIXME: is this always applicable? NPCInfo->squadState = SQUAD_RETREAT; - TIMER_Set( NPC, "flee", Q_irand( fleeTimeMin, fleeTimeMax ) ); - TIMER_Set( NPC, "panic", Q_irand( 1000, 4000 ) );//how long to wait before trying to nav to a dropped weapon - TIMER_Set( NPC, "duck", 0 ); + TIMER_Set(NPC, "flee", Q_irand(fleeTimeMin, fleeTimeMax)); + TIMER_Set(NPC, "panic", Q_irand(1000, 4000)); // how long to wait before trying to nav to a dropped weapon + TIMER_Set(NPC, "duck", 0); } -void G_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ - if ( !self->NPC ) - {//player +void G_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { + if (!self->NPC) { // player return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - NPC_StartFlee( enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax ); + NPC_StartFlee(enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax); RestoreNPCGlobals(); } -void NPC_BSEmplaced( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSEmplaced(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand( -90, 90 ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) { + if (!Q_irand(0, 30)) { + NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCInfo->desiredPitch = Q_irand(-20, 20); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -2032,66 +1687,58 @@ void NPC_BSEmplaced( void ) qboolean enemyCS = qfalse; qboolean faceEnemy = qfalse; qboolean shoot = qfalse; - vec3_t impactPos; + vec3_t impactPos; - if ( NPC_ClearLOS( NPC->enemy ) ) - { + if (NPC_ClearLOS(NPC->enemy)) { enemyLOS = qtrue; - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + if (hit == NPC->enemy->s.number || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); } } -/* - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { - NPCInfo->enemyLastSeenTime = level.time; - faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy - } -*/ + /* + else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) + { + NPCInfo->enemyLastSeenTime = level.time; + faceEnemy = qtrue; + NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } + */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); - } - else - {//we want to face in the dir we're running - NPC_UpdateAngles( qtrue, qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); + } else { // we want to face in the dir we're running + NPC_UpdateAngles(qtrue, qtrue); } - if ( NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPC->enemy && NPC->enemy->enemy ) - { - if ( NPC->enemy->s.weapon == WP_SABER && NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPC->enemy && NPC->enemy->enemy) { + if (NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue + // blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - if ( shoot ) - {//try to shoot if it's time - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + if (shoot) { // try to shoot if it's time + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } } } diff --git a/code/game/NPC_combat.cpp b/code/game/NPC_combat.cpp index fc60f59f76..a816dce176 100644 --- a/code/game/NPC_combat.cpp +++ b/code/game/NPC_combat.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_combat.cpp +// NPC_combat.cpp #include "b_local.h" #include "g_nav.h" @@ -28,39 +28,33 @@ along with this program; if not, see . #include "wp_saber.h" #include "g_functions.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ); -extern qboolean PM_DroidMelee( int npc_class ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy); +extern qboolean PM_DroidMelee(int npc_class); extern int delayedShutDown; -extern qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ); +extern qboolean G_ValidEnemy(gentity_t *self, gentity_t *enemy); -void ChangeWeapon( gentity_t *ent, int newWeapon ); +void ChangeWeapon(gentity_t *ent, int newWeapon); -void G_ClearEnemy (gentity_t *self) -{ - NPC_CheckLookTarget( self ); +void G_ClearEnemy(gentity_t *self) { + NPC_CheckLookTarget(self); - if ( self->enemy ) - { - if ( ( G_ValidEnemy(self, self->enemy ) ) && ( self->svFlags & SVF_LOCKEDENEMY ) ) - { + if (self->enemy) { + if ((G_ValidEnemy(self, self->enemy)) && (self->svFlags & SVF_LOCKEDENEMY)) { return; } - - if( self->client && self->client->renderInfo.lookTarget == self->enemy->s.number ) - { - NPC_ClearLookTarget( self ); + if (self->client && self->client->renderInfo.lookTarget == self->enemy->s.number) { + NPC_ClearLookTarget(self); } - if ( self->NPC && self->enemy == self->NPC->goalEntity ) - { + if (self->NPC && self->enemy == self->NPC->goalEntity) { self->NPC->goalEntity = NULL; } - //FIXME: set last enemy? + // FIXME: set last enemy? } self->enemy = NULL; @@ -72,21 +66,18 @@ NPC_AngerAlert ------------------------- */ -#define ANGER_ALERT_RADIUS 512 -#define ANGER_ALERT_SOUND_RADIUS 256 +#define ANGER_ALERT_RADIUS 512 +#define ANGER_ALERT_SOUND_RADIUS 256 -void G_AngerAlert( gentity_t *self ) -{ - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... +void G_AngerAlert(gentity_t *self) { + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return; } - if ( !TIMER_Done( self, "interrogating" ) ) - {//I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! + if (!TIMER_Done(self, "interrogating")) { // I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! return; } - //FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? - G_AlertTeam( self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS ); + // FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? + G_AlertTeam(self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS); } /* @@ -95,48 +86,39 @@ G_TeamEnemy ------------------------- */ -qboolean G_TeamEnemy( gentity_t *self ) -{//FIXME: Probably a better way to do this, is a linked list of your teammates already available? - int i; - gentity_t *ent; +qboolean G_TeamEnemy(gentity_t *self) { // FIXME: Probably a better way to do this, is a linked list of your teammates already available? + int i; + gentity_t *ent; - if ( !self->client || self->client->playerTeam == TEAM_FREE ) - { + if (!self->client || self->client->playerTeam == TEAM_FREE) { return qfalse; } - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return qfalse; } - for( i = 1; i < MAX_GENTITIES; i++ ) - { + for (i = 1; i < MAX_GENTITIES; i++) { ent = &g_entities[i]; - if ( ent == self ) - { + if (ent == self) { continue; } - if ( ent->health <= 0 ) - { + if (ent->health <= 0) { continue; } - if ( !ent->client ) - { + if (!ent->client) { continue; } - if ( ent->client->playerTeam != self->client->playerTeam ) - {//ent is not on my team + if (ent->client->playerTeam != self->client->playerTeam) { // ent is not on my team continue; } - if ( ent->enemy ) - {//they have an enemy - if ( !ent->enemy->client || ent->enemy->client->playerTeam != self->client->playerTeam ) - {//the ent's enemy is either a normal ent or is a player/NPC that is not on my team + if (ent->enemy) { // they have an enemy + if (!ent->enemy->client || ent->enemy->client->playerTeam != + self->client->playerTeam) { // the ent's enemy is either a normal ent or is a player/NPC that is not on my team return qtrue; } } @@ -145,105 +127,86 @@ qboolean G_TeamEnemy( gentity_t *self ) return qfalse; } -qboolean G_CheckSaberAllyAttackDelay( gentity_t *self, gentity_t *enemy ) -{ - if ( !self || !self->enemy ) - { +qboolean G_CheckSaberAllyAttackDelay(gentity_t *self, gentity_t *enemy) { + if (!self || !self->enemy) { return qfalse; } - if ( self->NPC - && self->client->leader == player - && self->enemy - && self->enemy->s.weapon != WP_SABER - && self->s.weapon == WP_SABER ) - {//assisting the player and I'm using a saber and my enemy is not - TIMER_Set( self, "allyJediDelay", -level.time ); - //use the distance to the enemy to determine how long to delay - float distance = Distance( enemy->currentOrigin, self->currentOrigin ); - if ( distance < 256 ) - { + if (self->NPC && self->client->leader == player && self->enemy && self->enemy->s.weapon != WP_SABER && + self->s.weapon == WP_SABER) { // assisting the player and I'm using a saber and my enemy is not + TIMER_Set(self, "allyJediDelay", -level.time); + // use the distance to the enemy to determine how long to delay + float distance = Distance(enemy->currentOrigin, self->currentOrigin); + if (distance < 256) { return qtrue; } int delay = 500; - if ( distance > 2048 ) - {//the farther they are, the shorter the delay - delay = 5000-floor(distance);//(6-g_spskill->integer)); - if ( delay < 500 ) - { + if (distance > 2048) { // the farther they are, the shorter the delay + delay = 5000 - floor(distance); //(6-g_spskill->integer)); + if (delay < 500) { delay = 500; } - } - else - {//the close they are, the shorter the delay - delay = floor(distance*4);//(6-g_spskill->integer)); - if ( delay > 5000 ) - { + } else { // the close they are, the shorter the delay + delay = floor(distance * 4); //(6-g_spskill->integer)); + if (delay > 5000) { delay = 5000; } } - TIMER_Set( self, "allyJediDelay", delay ); + TIMER_Set(self, "allyJediDelay", delay); return qtrue; } return qfalse; } -void G_AttackDelay( gentity_t *self, gentity_t *enemy ) -{ - if ( enemy && self->client && self->NPC ) - {//delay their attack based on how far away they're facing from enemy - vec3_t fwd, dir; - int attDelay; +void G_AttackDelay(gentity_t *self, gentity_t *enemy) { + if (enemy && self->client && self->NPC) { // delay their attack based on how far away they're facing from enemy + vec3_t fwd, dir; + int attDelay; - VectorSubtract( self->client->renderInfo.eyePoint, enemy->currentOrigin, dir );//purposely backwards - VectorNormalize( dir ); - AngleVectors( self->client->renderInfo.eyeAngles, fwd, NULL, NULL ); - //dir[2] = fwd[2] = 0;//ignore z diff? + VectorSubtract(self->client->renderInfo.eyePoint, enemy->currentOrigin, dir); // purposely backwards + VectorNormalize(dir); + AngleVectors(self->client->renderInfo.eyeAngles, fwd, NULL, NULL); + // dir[2] = fwd[2] = 0;//ignore z diff? - attDelay = (4-g_spskill->integer)*500;//initial: from 1000ms delay on hard to 2000ms delay on easy - if ( self->client->playerTeam == TEAM_PLAYER ) - {//invert - attDelay = 2000-attDelay; + attDelay = (4 - g_spskill->integer) * 500; // initial: from 1000ms delay on hard to 2000ms delay on easy + if (self->client->playerTeam == TEAM_PLAYER) { // invert + attDelay = 2000 - attDelay; } - attDelay += floor( (DotProduct( fwd, dir )+1.0f) * 2000.0f );//add up to 4000ms delay if they're facing away + attDelay += floor((DotProduct(fwd, dir) + 1.0f) * 2000.0f); // add up to 4000ms delay if they're facing away - //FIXME: should distance matter, too? + // FIXME: should distance matter, too? - //Now modify the delay based on NPC_class, weapon, and team - //NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds - switch ( self->client->NPC_class ) - { - case CLASS_IMPERIAL://they give orders and hang back - attDelay += Q_irand( 500, 1500 ); + // Now modify the delay based on NPC_class, weapon, and team + // NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds + switch (self->client->NPC_class) { + case CLASS_IMPERIAL: // they give orders and hang back + attDelay += Q_irand(500, 1500); break; - case CLASS_STORMTROOPER://stormtroopers shoot sooner - if ( self->NPC->rank >= RANK_LT ) - {//officers shoot even sooner - attDelay -= Q_irand( 500, 1500 ); - } - else - {//normal stormtroopers don't have as fast reflexes as officers - attDelay -= Q_irand( 0, 1000 ); + case CLASS_STORMTROOPER: // stormtroopers shoot sooner + if (self->NPC->rank >= RANK_LT) { // officers shoot even sooner + attDelay -= Q_irand(500, 1500); + } else { // normal stormtroopers don't have as fast reflexes as officers + attDelay -= Q_irand(0, 1000); } break; - case CLASS_SWAMPTROOPER://shoot very quickly? What about guys in water? - attDelay -= Q_irand( 1000, 2000 ); + case CLASS_SWAMPTROOPER: // shoot very quickly? What about guys in water? + attDelay -= Q_irand(1000, 2000); break; - case CLASS_IMPWORKER://they panic, don't fire right away - attDelay += Q_irand( 1000, 2500 ); + case CLASS_IMPWORKER: // they panic, don't fire right away + attDelay += Q_irand(1000, 2500); break; case CLASS_TRANDOSHAN: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; case CLASS_JAN: case CLASS_LANDO: case CLASS_PRISONER: case CLASS_REBEL: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; case CLASS_GALAKMECH: case CLASS_ATST: - attDelay -= Q_irand( 1000, 2000 ); + attDelay -= Q_irand(1000, 2000); break; case CLASS_REELO: case CLASS_UGNAUGHT: @@ -284,8 +247,7 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) break; } - switch ( self->s.weapon ) - { + switch (self->s.weapon) { case WP_NONE: case WP_SABER: return; @@ -293,102 +255,92 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) case WP_BRYAR_PISTOL: break; case WP_BLASTER: - if ( self->NPC->scriptFlags & SCF_ALT_FIRE ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); - } - else - {//regular blaster - attDelay -= Q_irand( 0, 500 ); + if (self->NPC->scriptFlags & SCF_ALT_FIRE) { // rapid-fire blasters + attDelay += Q_irand(0, 500); + } else { // regular blaster + attDelay -= Q_irand(0, 500); } break; case WP_BOWCASTER: - attDelay += Q_irand( 0, 500 ); + attDelay += Q_irand(0, 500); break; case WP_REPEATER: - if ( !(self->NPC->scriptFlags&SCF_ALT_FIRE) ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); + if (!(self->NPC->scriptFlags & SCF_ALT_FIRE)) { // rapid-fire blasters + attDelay += Q_irand(0, 500); } break; case WP_FLECHETTE: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; case WP_ROCKET_LAUNCHER: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; case WP_CONCUSSION: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; - case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster - attDelay -= Q_irand( 500, 1500 ); + case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster + attDelay -= Q_irand(500, 1500); break; - case WP_DISRUPTOR://sniper's don't delay? + case WP_DISRUPTOR: // sniper's don't delay? return; break; - case WP_THERMAL://grenade-throwing has a built-in delay + case WP_THERMAL: // grenade-throwing has a built-in delay return; break; - case WP_MELEE: // Any ol' melee attack + case WP_MELEE: // Any ol' melee attack return; break; case WP_EMPLACED_GUN: return; break; - case WP_TURRET: // turret guns + case WP_TURRET: // turret guns return; break; - case WP_BOT_LASER: // Probe droid - Laser blast + case WP_BOT_LASER: // Probe droid - Laser blast return; break; case WP_NOGHRI_STICK: - attDelay += Q_irand( 0, 500 ); + attDelay += Q_irand(0, 500); break; - /* - case WP_DEMP2: - break; - case WP_TRIP_MINE: - break; - case WP_DET_PACK: - break; - case WP_STUN_BATON: - break; - case WP_ATST_MAIN: - break; - case WP_ATST_SIDE: - break; - case WP_TIE_FIGHTER: - break; - case WP_RAPID_FIRE_CONC: - break; - */ + /* + case WP_DEMP2: + break; + case WP_TRIP_MINE: + break; + case WP_DET_PACK: + break; + case WP_STUN_BATON: + break; + case WP_ATST_MAIN: + break; + case WP_ATST_SIDE: + break; + case WP_TIE_FIGHTER: + break; + case WP_RAPID_FIRE_CONC: + break; + */ } - if ( self->client->playerTeam == TEAM_PLAYER ) - {//clamp it - if ( attDelay > 2000 ) - { + if (self->client->playerTeam == TEAM_PLAYER) { // clamp it + if (attDelay > 2000) { attDelay = 2000; } } - //don't shoot right away - if ( attDelay > 4000+((2-g_spskill->integer)*3000) ) - { - attDelay = 4000+((2-g_spskill->integer)*3000); + // don't shoot right away + if (attDelay > 4000 + ((2 - g_spskill->integer) * 3000)) { + attDelay = 4000 + ((2 - g_spskill->integer) * 3000); } - TIMER_Set( self, "attackDelay", attDelay );//Q_irand( 1500, 4500 ) ); - //don't move right away either - if ( attDelay > 4000 ) - { + TIMER_Set(self, "attackDelay", attDelay); // Q_irand( 1500, 4500 ) ); + // don't move right away either + if (attDelay > 4000) { attDelay = 4000 - Q_irand(500, 1500); - } - else - { + } else { attDelay -= Q_irand(500, 1500); } - TIMER_Set( self, "roamTime", attDelay );//was Q_irand( 1000, 3500 ); + TIMER_Set(self, "roamTime", attDelay); // was Q_irand( 1000, 3500 ); } } /* @@ -396,245 +348,190 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) G_SetEnemy ------------------------- */ -extern gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate ); +extern gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate); -void Saboteur_Cloak( gentity_t *self ); -void G_AimSet( gentity_t *self, int aim ); -void G_SetEnemy( gentity_t *self, gentity_t *enemy ) -{ - int event = 0; +void Saboteur_Cloak(gentity_t *self); +void G_AimSet(gentity_t *self, int aim); +void G_SetEnemy(gentity_t *self, gentity_t *enemy) { + int event = 0; - //Must be valid - if ( enemy == NULL ) + // Must be valid + if (enemy == NULL) return; - //Must be valid - if ( enemy->inuse == 0 ) - { + // Must be valid + if (enemy->inuse == 0) { return; } enemy = G_CheckControlledTurretEnemy(self, enemy, qtrue); - if (!enemy) - { + if (!enemy) { return; } - //Don't take the enemy if in notarget - if ( enemy->flags & FL_NOTARGET ) + // Don't take the enemy if in notarget + if (enemy->flags & FL_NOTARGET) return; - if ( !self->NPC ) - { + if (!self->NPC) { self->enemy = enemy; return; } - if ( self->NPC->confusionTime > level.time ) - {//can't pick up enemies if confused + if (self->NPC->confusionTime > level.time) { // can't pick up enemies if confused return; } #ifdef _DEBUG - if ( self->s.number ) - { - assert( enemy != self ); + if (self->s.number) { + assert(enemy != self); } -#endif// _DEBUG +#endif // _DEBUG -// if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) -// {//unmask the player -// enemy->client->playerTeam = TEAM_PLAYER; -// } + // if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) + // {//unmask the player + // enemy->client->playerTeam = TEAM_PLAYER; + // } - if ( self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam ) - {//Probably a damn script! - if ( self->NPC->charmedTime > level.time ) - {//Probably a damn script! + if (self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam) { // Probably a damn script! + if (self->NPC->charmedTime > level.time) { // Probably a damn script! return; } } - if ( self->NPC && self->client && self->client->ps.weapon == WP_SABER ) - { - //when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. - NPC_Jedi_RateNewEnemy( self, enemy ); + if (self->NPC && self->client && self->client->ps.weapon == WP_SABER) { + // when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. + NPC_Jedi_RateNewEnemy(self, enemy); } - //NOTE: this is not necessarily true! - //self->NPC->enemyLastSeenTime = level.time; + // NOTE: this is not necessarily true! + // self->NPC->enemyLastSeenTime = level.time; - if ( self->enemy == NULL ) - { - //TEMP HACK: turn on our saber - if ( self->health > 0 ) - { + if (self->enemy == NULL) { + // TEMP HACK: turn on our saber + if (self->health > 0) { self->client->ps.SaberActivate(); } - //FIXME: Have to do this to prevent alert cascading - G_ClearEnemy( self ); + // FIXME: Have to do this to prevent alert cascading + G_ClearEnemy(self); self->enemy = enemy; - if (self->client && self->client->NPC_class == CLASS_SABOTEUR) - { - Saboteur_Cloak(NPC); // Cloak - TIMER_Set(self, "decloakwait", 3000); // Wait 3 sec before decloak and attack + if (self->client && self->client->NPC_class == CLASS_SABOTEUR) { + Saboteur_Cloak(NPC); // Cloak + TIMER_Set(self, "decloakwait", 3000); // Wait 3 sec before decloak and attack } - - //Special case- if player is being hunted by his own people, set the player's team to team_free - if ( self->client->playerTeam == TEAM_PLAYER - && enemy->s.number == 0 - && enemy->client - && enemy->client->playerTeam == TEAM_PLAYER ) - {//make the player "evil" so that everyone goes after him + // Special case- if player is being hunted by his own people, set the player's team to team_free + if (self->client->playerTeam == TEAM_PLAYER && enemy->s.number == 0 && enemy->client && + enemy->client->playerTeam == TEAM_PLAYER) { // make the player "evil" so that everyone goes after him enemy->client->enemyTeam = TEAM_FREE; enemy->client->playerTeam = TEAM_FREE; } - //If have an anger script, run that instead of yelling - if( G_ActivateBehavior( self, BSET_ANGER ) ) - { - } - else if ( self->client - && self->client->NPC_class == CLASS_KYLE - && self->client->leader == player - && !TIMER_Done( self, "kyleAngerSoundDebounce" ) ) - {//don't yell that you have an enemy more than once every five seconds - } - else if ( self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam ) - { - //FIXME: Use anger when entire team has no enemy. + // If have an anger script, run that instead of yelling + if (G_ActivateBehavior(self, BSET_ANGER)) { + } else if (self->client && self->client->NPC_class == CLASS_KYLE && self->client->leader == player && + !TIMER_Done(self, "kyleAngerSoundDebounce")) { // don't yell that you have an enemy more than once every five seconds + } else if (self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam) { + // FIXME: Use anger when entire team has no enemy. // Basically, you're first one to notice enemies - if ( self->forcePushTime < level.time ) // not currently being pushed + if (self->forcePushTime < level.time) // not currently being pushed { - if ( !G_TeamEnemy( self ) && self->client->NPC_class != CLASS_BOBAFETT) - {//team did not have an enemy previously - if ( self->NPC - && self->client->playerTeam == TEAM_PLAYER - && enemy->s.number < MAX_CLIENTS - && self->client->clientInfo.customBasicSoundDir - && self->client->clientInfo.customBasicSoundDir[0] - && Q_stricmp( "jedi2", self->client->clientInfo.customBasicSoundDir ) == 0 ) - { - switch ( Q_irand( 0, 2 ) ) - { + if (!G_TeamEnemy(self) && self->client->NPC_class != CLASS_BOBAFETT) { // team did not have an enemy previously + if (self->NPC && self->client->playerTeam == TEAM_PLAYER && enemy->s.number < MAX_CLIENTS && self->client->clientInfo.customBasicSoundDir && + self->client->clientInfo.customBasicSoundDir[0] && Q_stricmp("jedi2", self->client->clientInfo.customBasicSoundDir) == 0) { + switch (Q_irand(0, 2)) { case 0: - G_SoundOnEnt( self, CHAN_VOICE, "sound/chars/jedi2/28je2008.wav" ); + G_SoundOnEnt(self, CHAN_VOICE, "sound/chars/jedi2/28je2008.wav"); break; case 1: - G_SoundOnEnt( self, CHAN_VOICE, "sound/chars/jedi2/28je2009.wav" ); + G_SoundOnEnt(self, CHAN_VOICE, "sound/chars/jedi2/28je2009.wav"); break; case 2: - G_SoundOnEnt( self, CHAN_VOICE, "sound/chars/jedi2/28je2012.wav" ); + G_SoundOnEnt(self, CHAN_VOICE, "sound/chars/jedi2/28je2012.wav"); break; } self->NPC->blockedSpeechDebounceTime = level.time + 2000; - } - else - { - if ( Q_irand( 0, 1 )) - {//hell, we're loading them, might as well use them! + } else { + if (Q_irand(0, 1)) { // hell, we're loading them, might as well use them! event = Q_irand(EV_CHASE1, EV_CHASE3); - } - else - { + } else { event = Q_irand(EV_ANGER1, EV_ANGER3); } } } } - if ( event ) - {//yell - if ( self->client - && self->client->NPC_class == CLASS_KYLE - && self->client->leader == player ) - {//don't yell that you have an enemy more than once every 4-8 seconds - TIMER_Set( self, "kyleAngerSoundDebounce", Q_irand( 4000, 8000 ) ); + if (event) { // yell + if (self->client && self->client->NPC_class == CLASS_KYLE && + self->client->leader == player) { // don't yell that you have an enemy more than once every 4-8 seconds + TIMER_Set(self, "kyleAngerSoundDebounce", Q_irand(4000, 8000)); } - G_AddVoiceEvent( self, event, 2000 ); + G_AddVoiceEvent(self, event, 2000); } } - if ( self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || - self->s.weapon == WP_THERMAL || self->s.weapon == WP_BLASTER_PISTOL - || self->s.weapon == WP_BOWCASTER ) - {//Hmm, how about sniper and bowcaster? - //When first get mad, aim is bad - //Hmm, base on game difficulty, too? Rank? - if ( self->client->playerTeam == TEAM_PLAYER ) - { - G_AimSet( self, Q_irand( self->NPC->stats.aim - (5*(g_spskill->integer)), self->NPC->stats.aim - g_spskill->integer ) ); - } - else - { + if (self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || self->s.weapon == WP_THERMAL || self->s.weapon == WP_BLASTER_PISTOL || + self->s.weapon == WP_BOWCASTER) { // Hmm, how about sniper and bowcaster? + // When first get mad, aim is bad + // Hmm, base on game difficulty, too? Rank? + if (self->client->playerTeam == TEAM_PLAYER) { + G_AimSet(self, Q_irand(self->NPC->stats.aim - (5 * (g_spskill->integer)), self->NPC->stats.aim - g_spskill->integer)); + } else { int minErr = 3; int maxErr = 12; - if ( self->client->NPC_class == CLASS_IMPWORKER ) - { + if (self->client->NPC_class == CLASS_IMPWORKER) { minErr = 15; maxErr = 30; - } - else if ( self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN ) - { + } else if (self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN) { minErr = 5; maxErr = 15; } - G_AimSet( self, Q_irand( self->NPC->stats.aim - (maxErr*(3-g_spskill->integer)), self->NPC->stats.aim - (minErr*(3-g_spskill->integer)) ) ); + G_AimSet(self, Q_irand(self->NPC->stats.aim - (maxErr * (3 - g_spskill->integer)), self->NPC->stats.aim - (minErr * (3 - g_spskill->integer)))); } } - //Alert anyone else in the area - if ( Q_stricmp( "desperado", self->NPC_type ) != 0 && Q_stricmp( "paladin", self->NPC_type ) != 0 ) - {//special holodeck enemies exception - if ( !(self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//gripped people can't call for help - G_AngerAlert( self ); + // Alert anyone else in the area + if (Q_stricmp("desperado", self->NPC_type) != 0 && Q_stricmp("paladin", self->NPC_type) != 0) { // special holodeck enemies exception + if (!(self->client->ps.eFlags & EF_FORCE_GRIPPED)) { // gripped people can't call for help + G_AngerAlert(self); } } - if ( !G_CheckSaberAllyAttackDelay( self, enemy ) ) - {//not a saber ally holding back - //Stormtroopers don't fire right away! - G_AttackDelay( self, enemy ); + if (!G_CheckSaberAllyAttackDelay(self, enemy)) { // not a saber ally holding back + // Stormtroopers don't fire right away! + G_AttackDelay(self, enemy); } - //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way - if ( self->client->ps.weapon == WP_NONE && !Q_stricmpn( self->NPC_type, "imp", 3 ) && !(self->NPC->scriptFlags & SCF_FORCED_MARCH) ) - { - if ( self->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_BLASTER ) ) - { - ChangeWeapon( self, WP_BLASTER ); + // FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way + if (self->client->ps.weapon == WP_NONE && !Q_stricmpn(self->NPC_type, "imp", 3) && !(self->NPC->scriptFlags & SCF_FORCED_MARCH)) { + if (self->client->ps.stats[STAT_WEAPONS] & (1 << WP_BLASTER)) { + ChangeWeapon(self, WP_BLASTER); self->client->ps.weapon = WP_BLASTER; self->client->ps.weaponstate = WEAPON_READY; - G_CreateG2AttachedWeaponModel( self, weaponData[WP_BLASTER].weaponMdl, self->handRBolt, 0 ); - } - else if ( self->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_BLASTER_PISTOL ) ) - { - ChangeWeapon( self, WP_BLASTER_PISTOL ); + G_CreateG2AttachedWeaponModel(self, weaponData[WP_BLASTER].weaponMdl, self->handRBolt, 0); + } else if (self->client->ps.stats[STAT_WEAPONS] & (1 << WP_BLASTER_PISTOL)) { + ChangeWeapon(self, WP_BLASTER_PISTOL); self->client->ps.weapon = WP_BLASTER_PISTOL; self->client->ps.weaponstate = WEAPON_READY; - G_CreateG2AttachedWeaponModel( self, weaponData[WP_BLASTER_PISTOL].weaponMdl, self->handRBolt, 0 ); + G_CreateG2AttachedWeaponModel(self, weaponData[WP_BLASTER_PISTOL].weaponMdl, self->handRBolt, 0); } } return; } - //Otherwise, just picking up another enemy + // Otherwise, just picking up another enemy - if ( event ) - { - G_AddVoiceEvent( self, event, 2000 ); + if (event) { + G_AddVoiceEvent(self, event, 2000); } - //Take the enemy + // Take the enemy G_ClearEnemy(self); self->enemy = enemy; } - /* int ChooseBestWeapon( void ) { @@ -680,10 +577,8 @@ int ChooseBestWeapon( void ) } */ -void ChangeWeapon( gentity_t *ent, int newWeapon ) -{ - if ( !ent || !ent->client || !ent->NPC ) - { +void ChangeWeapon(gentity_t *ent, int newWeapon) { + if (!ent || !ent->client || !ent->NPC) { return; } @@ -693,277 +588,248 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) ent->NPC->attackHold = 0; ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[newWeapon].ammoIndex]; - switch ( newWeapon ) - { - case WP_BRYAR_PISTOL://prifle + switch (newWeapon) { + case WP_BRYAR_PISTOL: // prifle ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_BLASTER_PISTOL: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->weaponModel[1] > 0 ) - {//commando + if (ent->weaponModel[1] > 0) { // commando ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 4; #ifdef BASE_SAVE_COMPAT ent->NPC->burstMean = 8; #endif ent->NPC->burstMax = 12; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 600;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 400;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 600; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 400; // attack debounce else - ent->NPC->burstSpacing = 250;//attack debounce - } - else if ( ent->client->NPC_class == CLASS_SABOTEUR ) - { - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 900;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 600;//attack debounce + ent->NPC->burstSpacing = 250; // attack debounce + } else if (ent->client->NPC_class == CLASS_SABOTEUR) { + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 900; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 600; // attack debounce else - ent->NPC->burstSpacing = 400;//attack debounce - } - else - { - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce + ent->NPC->burstSpacing = 400; // attack debounce + } else { + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce + ent->NPC->burstSpacing = 500; // attack debounce } break; - case WP_BOT_LASER://probe attack + case WP_BOT_LASER: // probe attack ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 600;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 600;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 400;//attack debounce + // ent->NPC->burstSpacing = 600;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 600; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 400; // attack debounce else - ent->NPC->burstSpacing = 200;//attack debounce + ent->NPC->burstSpacing = 200; // attack debounce break; case WP_SABER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 0;//attackdebounce + ent->NPC->burstSpacing = 0; // attackdebounce break; case WP_DISRUPTOR: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - switch( g_spskill->integer ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + switch (g_spskill->integer) { case 0: - ent->NPC->burstSpacing = 2500;//attackdebounce + ent->NPC->burstSpacing = 2500; // attackdebounce break; case 1: - ent->NPC->burstSpacing = 2000;//attackdebounce + ent->NPC->burstSpacing = 2000; // attackdebounce break; case 2: - ent->NPC->burstSpacing = 1500;//attackdebounce + ent->NPC->burstSpacing = 1500; // attackdebounce break; } - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_TUSKEN_RIFLE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - switch( g_spskill->integer ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + switch (g_spskill->integer) { case 0: - ent->NPC->burstSpacing = 2500;//attackdebounce + ent->NPC->burstSpacing = 2500; // attackdebounce break; case 1: - ent->NPC->burstSpacing = 2000;//attackdebounce + ent->NPC->burstSpacing = 2000; // attackdebounce break; case 2: - ent->NPC->burstSpacing = 1500;//attackdebounce + ent->NPC->burstSpacing = 1500; // attackdebounce break; } - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_BOWCASTER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce + ent->NPC->burstSpacing = 500; // attack debounce break; case WP_REPEATER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; #ifdef BASE_SAVE_COMPAT ent->NPC->burstMean = 6; #endif ent->NPC->burstMax = 10; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce + ent->NPC->burstSpacing = 500; // attack debounce } break; case WP_DEMP2: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_FLECHETTE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_ROCKET_LAUNCHER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 2500;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 2500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 2000;//attack debounce + // ent->NPC->burstSpacing = 2500;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 2500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 2000; // attack debounce else - ent->NPC->burstSpacing = 1500;//attack debounce + ent->NPC->burstSpacing = 1500; // attack debounce break; case WP_CONCUSSION: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - {//beam - ent->NPC->burstSpacing = 1200;//attackdebounce - } - else - {//rocket - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 2300;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1800;//attack debounce + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { // beam + ent->NPC->burstSpacing = 1200; // attackdebounce + } else { // rocket + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 2300; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1800; // attack debounce else - ent->NPC->burstSpacing = 1200;//attack debounce + ent->NPC->burstSpacing = 1200; // attack debounce } break; case WP_THERMAL: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 3000;//attackdebounce - if ( g_spskill->integer == 0 ) -// ent->NPC->burstSpacing = 3000;//attack debounce - ent->NPC->burstSpacing = 4500;//attack debounce - else if ( g_spskill->integer == 1 ) -// ent->NPC->burstSpacing = 2500;//attack debounce - ent->NPC->burstSpacing = 3000;//attack debounce + // ent->NPC->burstSpacing = 3000;//attackdebounce + if (g_spskill->integer == 0) + // ent->NPC->burstSpacing = 3000;//attack debounce + ent->NPC->burstSpacing = 4500; // attack debounce + else if (g_spskill->integer == 1) + // ent->NPC->burstSpacing = 2500;//attack debounce + ent->NPC->burstSpacing = 3000; // attack debounce else - ent->NPC->burstSpacing = 2000;//attack debounce + ent->NPC->burstSpacing = 2000; // attack debounce break; - /* - case WP_SABER: - ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; - ent->NPC->burstMin = 5;//0.5 sec - ent->NPC->burstMax = 20;//3 seconds - ent->NPC->burstSpacing = 2000;//2 seconds - ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst - break; - */ + /* + case WP_SABER: + ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; + ent->NPC->burstMin = 5;//0.5 sec + ent->NPC->burstMax = 20;//3 seconds + ent->NPC->burstSpacing = 2000;//2 seconds + ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst + break; + */ case WP_BLASTER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; #ifdef BASE_SAVE_COMPAT ent->NPC->burstMean = 3; #endif ent->NPC->burstMax = 3; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce - } - else - { + ent->NPC->burstSpacing = 500; // attack debounce + } else { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce - // ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 500; // attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce } break; case WP_MELEE: case WP_TUSKEN_STAFF: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_ATST_MAIN: case WP_ATST_SIDE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce break; case WP_EMPLACED_GUN: - //FIXME: give some designer-control over this? - if ( ent->client && ent->client->NPC_class == CLASS_REELO ) - { + // FIXME: give some designer-control over this? + if (ent->client && ent->client->NPC_class == CLASS_REELO) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attack debounce - // if ( g_spskill->integer == 0 ) - // ent->NPC->burstSpacing = 300;//attack debounce - // else if ( g_spskill->integer == 1 ) - // ent->NPC->burstSpacing = 200;//attack debounce - // else - // ent->NPC->burstSpacing = 100;//attack debounce - } - else - { + ent->NPC->burstSpacing = 1000; // attack debounce + // if ( g_spskill->integer == 0 ) + // ent->NPC->burstSpacing = 300;//attack debounce + // else if ( g_spskill->integer == 1 ) + // ent->NPC->burstSpacing = 200;//attack debounce + // else + // ent->NPC->burstSpacing = 100;//attack debounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 2; // 3 shots, really #ifdef BASE_SAVE_COMPAT @@ -971,36 +837,24 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) #endif ent->NPC->burstMax = 2; - if ( ent->owner ) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. + if (ent->owner) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. { - if ( g_spskill->integer == 0 ) - { - ent->NPC->burstSpacing = ent->owner->wait + 400;//attack debounce - ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots + if (g_spskill->integer == 0) { + ent->NPC->burstSpacing = ent->owner->wait + 400; // attack debounce + ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots + } else if (g_spskill->integer == 1) { + ent->NPC->burstSpacing = ent->owner->wait + 200; // attack debounce + } else { + ent->NPC->burstSpacing = ent->owner->wait; // attack debounce } - else if ( g_spskill->integer == 1 ) - { - ent->NPC->burstSpacing = ent->owner->wait + 200;//attack debounce - } - else - { - ent->NPC->burstSpacing = ent->owner->wait;//attack debounce - } - } - else - { - if ( g_spskill->integer == 0 ) - { - ent->NPC->burstSpacing = 1200;//attack debounce + } else { + if (g_spskill->integer == 0) { + ent->NPC->burstSpacing = 1200; // attack debounce ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots - } - else if ( g_spskill->integer == 1 ) - { - ent->NPC->burstSpacing = 1000;//attack debounce - } - else - { - ent->NPC->burstSpacing = 800;//attack debounce + } else if (g_spskill->integer == 1) { + ent->NPC->burstSpacing = 1000; // attack debounce + } else { + ent->NPC->burstSpacing = 800; // attack debounce } } } @@ -1008,12 +862,12 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) case WP_NOGHRI_STICK: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 2250;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1500;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 2250; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1500; // attack debounce else - ent->NPC->burstSpacing = 750;//attack debounce + ent->NPC->burstSpacing = 750; // attack debounce break; default: @@ -1022,27 +876,20 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) } } -void NPC_ChangeWeapon( int newWeapon ) -{ - qboolean changing = qfalse; - if ( newWeapon != NPC->client->ps.weapon ) - { +void NPC_ChangeWeapon(int newWeapon) { + qboolean changing = qfalse; + if (newWeapon != NPC->client->ps.weapon) { changing = qtrue; } - if ( changing ) - { - G_RemoveWeaponModels( NPC ); + if (changing) { + G_RemoveWeaponModels(NPC); } - ChangeWeapon( NPC, newWeapon ); - if ( changing && NPC->client->ps.weapon != WP_NONE ) - { - if ( NPC->client->ps.weapon == WP_SABER ) - { - WP_SaberAddG2SaberModels( NPC ); - } - else - { - G_CreateG2AttachedWeaponModel( NPC, weaponData[NPC->client->ps.weapon].weaponMdl, NPC->handRBolt, 0 ); + ChangeWeapon(NPC, newWeapon); + if (changing && NPC->client->ps.weapon != WP_NONE) { + if (NPC->client->ps.weapon == WP_SABER) { + WP_SaberAddG2SaberModels(NPC); + } else { + G_CreateG2AttachedWeaponModel(NPC, weaponData[NPC->client->ps.weapon].weaponMdl, NPC->handRBolt, 0); } } } @@ -1050,25 +897,21 @@ void NPC_ChangeWeapon( int newWeapon ) void NPC_ApplyWeaponFireDelay(void) How long, if at all, in msec the actual fire should delay from the time the attack was started */ -void NPC_ApplyWeaponFireDelay(void) -{ - if ( NPC->attackDebounceTime > level.time ) - {//Just fired, if attacking again, must be a burst fire, so don't add delay - //NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! +void NPC_ApplyWeaponFireDelay(void) { + if (NPC->attackDebounceTime > level.time) { // Just fired, if attacking again, must be a burst fire, so don't add delay + // NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! return; } - switch(client->ps.weapon) - { + switch (client->ps.weapon) { case WP_BOT_LASER: NPCInfo->burstCount = 0; client->fireDelay = 500; break; case WP_THERMAL: - if ( client->ps.clientNum ) - {//NPCs delay... - //FIXME: player should, too, but would feel weird in 1st person, even though it + if (client->ps.clientNum) { // NPCs delay... + // FIXME: player should, too, but would feel weird in 1st person, even though it // would look right in 3rd person. Really should have a wind-up anim // for player as he holds down the fire button to throw, then play // the actual throw when he lets go... @@ -1078,15 +921,13 @@ void NPC_ApplyWeaponFireDelay(void) case WP_MELEE: case WP_TUSKEN_STAFF: - if ( !PM_DroidMelee( client->NPC_class ) ) - {//FIXME: should be unique per melee anim + if (!PM_DroidMelee(client->NPC_class)) { // FIXME: should be unique per melee anim client->fireDelay = 300; } break; case WP_TUSKEN_RIFLE: - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//FIXME: should be unique per melee anim + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // FIXME: should be unique per melee anim client->fireDelay = 300; } break; @@ -1102,76 +943,52 @@ void NPC_ApplyWeaponFireDelay(void) ShootThink ------------------------- */ -void ShootThink( void ) -{ - int delay; +void ShootThink(void) { + int delay; ucmd.buttons |= BUTTON_ATTACK; - NPCInfo->currentAmmo = client->ps.ammo[weaponData[client->ps.weapon].ammoIndex]; // checkme + NPCInfo->currentAmmo = client->ps.ammo[weaponData[client->ps.weapon].ammoIndex]; // checkme NPC_ApplyWeaponFireDelay(); - if ( NPCInfo->aiFlags & NPCAI_BURST_WEAPON ) - { - if ( !NPCInfo->burstCount ) - { - NPCInfo->burstCount = Q_irand( NPCInfo->burstMin, NPCInfo->burstMax ); + if (NPCInfo->aiFlags & NPCAI_BURST_WEAPON) { + if (!NPCInfo->burstCount) { + NPCInfo->burstCount = Q_irand(NPCInfo->burstMin, NPCInfo->burstMax); delay = 0; - } - else - { + } else { NPCInfo->burstCount--; - if ( NPCInfo->burstCount == 0 ) - { + if (NPCInfo->burstCount == 0) { delay = NPCInfo->burstSpacing + Q_irand(-150, 150); - } - else - { + } else { delay = 0; } } - if ( !delay ) - { + if (!delay) { // HACK: dirty little emplaced bits, but is done because it would otherwise require some sort of new variable... - if ( client->ps.weapon == WP_EMPLACED_GUN ) - { - if ( NPC->owner ) // try and get the debounce values from the chair if we can + if (client->ps.weapon == WP_EMPLACED_GUN) { + if (NPC->owner) // try and get the debounce values from the chair if we can { - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { delay = NPC->owner->random + 150; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { delay = NPC->owner->random + 100; - } - else - { + } else { delay = NPC->owner->random; } - } - else - { - if ( g_spskill->integer == 0 ) - { + } else { + if (g_spskill->integer == 0) { delay = 350; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { delay = 300; - } - else - { + } else { delay = 200; } } } } - } - else - { + } else { delay = NPCInfo->burstSpacing + Q_irand(-150, 150); } @@ -1185,53 +1002,41 @@ FIXME makes this so there's a delay from event that caused us to check to actual Added: hacks for Borg */ -void WeaponThink( qboolean inCombat ) -{ +void WeaponThink(qboolean inCombat) { ucmd.buttons &= ~BUTTON_ATTACK; - if ( client->ps.weaponstate == WEAPON_RAISING || client->ps.weaponstate == WEAPON_DROPPING ) - { + if (client->ps.weaponstate == WEAPON_RAISING || client->ps.weaponstate == WEAPON_DROPPING) { ucmd.weapon = client->ps.weapon; return; } // can't shoot while shield is up - if (NPC->flags&FL_SHIELDED && NPC->client->NPC_class==CLASS_ASSASSIN_DROID) - { + if (NPC->flags & FL_SHIELDED && NPC->client->NPC_class == CLASS_ASSASSIN_DROID) { return; } // Can't Fire While Cloaked - if (NPC->client && - (NPC->client->ps.powerups[PW_CLOAKED] || (level.timeclient->ps.powerups[PW_UNCLOAKING]))) - { + if (NPC->client && (NPC->client->ps.powerups[PW_CLOAKED] || (level.time < NPC->client->ps.powerups[PW_UNCLOAKING]))) { return; } - if ( client->ps.weapon == WP_NONE ) - { + if (client->ps.weapon == WP_NONE) { return; } - if ( client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING && client->ps.weaponstate != WEAPON_IDLE) - { + if (client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING && client->ps.weaponstate != WEAPON_IDLE) { return; } - if ( level.time < NPCInfo->shotTime ) - { + if (level.time < NPCInfo->shotTime) { return; } - -//MCG - Begin - //For now, no-one runs out of ammo - if ( NPC->client->ps.ammo[ weaponData[client->ps.weapon].ammoIndex ] < weaponData[client->ps.weapon].energyPerShot ) - { - Add_Ammo( NPC, client->ps.weapon, weaponData[client->ps.weapon].energyPerShot*10 ); - } - else if ( NPC->client->ps.ammo[ weaponData[client->ps.weapon].ammoIndex ] < weaponData[client->ps.weapon].altEnergyPerShot ) - { - Add_Ammo( NPC, client->ps.weapon, weaponData[client->ps.weapon].altEnergyPerShot*5 ); + // MCG - Begin + // For now, no-one runs out of ammo + if (NPC->client->ps.ammo[weaponData[client->ps.weapon].ammoIndex] < weaponData[client->ps.weapon].energyPerShot) { + Add_Ammo(NPC, client->ps.weapon, weaponData[client->ps.weapon].energyPerShot * 10); + } else if (NPC->client->ps.ammo[weaponData[client->ps.weapon].ammoIndex] < weaponData[client->ps.weapon].altEnergyPerShot) { + Add_Ammo(NPC, client->ps.weapon, weaponData[client->ps.weapon].altEnergyPerShot * 5); } ucmd.weapon = client->ps.weapon; @@ -1242,33 +1047,24 @@ void WeaponThink( qboolean inCombat ) HaveWeapon */ -qboolean HaveWeapon( int weapon ) -{ - return (qboolean)( client->ps.stats[STAT_WEAPONS] & ( 1 << weapon ) ); -} +qboolean HaveWeapon(int weapon) { return (qboolean)(client->ps.stats[STAT_WEAPONS] & (1 << weapon)); } -qboolean EntIsGlass (gentity_t *check) -{ - if(check->classname && - !Q_stricmp("func_breakable", check->classname) && - check->count == 1 && check->health <= 100) - { +qboolean EntIsGlass(gentity_t *check) { + if (check->classname && !Q_stricmp("func_breakable", check->classname) && check->count == 1 && check->health <= 100) { return qtrue; } return qfalse; } -qboolean ShotThroughGlass (trace_t *tr, gentity_t *target, vec3_t spot, int mask) -{ - gentity_t *hit = &g_entities[ tr->entityNum ]; - if(hit != target && EntIsGlass(hit)) - {//ok to shoot through breakable glass - int skip = hit->s.number; - vec3_t muzzle; +qboolean ShotThroughGlass(trace_t *tr, gentity_t *target, vec3_t spot, int mask) { + gentity_t *hit = &g_entities[tr->entityNum]; + if (hit != target && EntIsGlass(hit)) { // ok to shoot through breakable glass + int skip = hit->s.number; + vec3_t muzzle; VectorCopy(tr->endpos, muzzle); - gi.trace (tr, muzzle, NULL, NULL, spot, skip, mask, (EG2_Collision)0, 0 ); + gi.trace(tr, muzzle, NULL, NULL, spot, skip, mask, (EG2_Collision)0, 0); return qtrue; } @@ -1283,72 +1079,62 @@ this function does not check teams, invulnerability, notarget, etc.... Added: If can't shoot center, try head, if not, see if it's close enough to try anyway. */ -qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) -{ - trace_t tr; - vec3_t muzzle; - vec3_t spot, diff; - gentity_t *traceEnt; +qboolean CanShoot(gentity_t *ent, gentity_t *shooter) { + trace_t tr; + vec3_t muzzle; + vec3_t spot, diff; + gentity_t *traceEnt; - CalcEntitySpot( shooter, SPOT_WEAPON, muzzle ); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); //FIXME preferred target locations for some weapons (feet for R/L) + CalcEntitySpot(shooter, SPOT_WEAPON, muzzle); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); // FIXME preferred target locations for some weapons (feet for R/L) - gi.trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; + gi.trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, (EG2_Collision)0, 0); + traceEnt = &g_entities[tr.entityNum]; // point blank, baby! - if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer) ) - { + if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer)) { traceEnt = shooter->NPC->touchedByPlayer; } - if ( ShotThroughGlass( &tr, ent, spot, MASK_SHOT ) ) - { - traceEnt = &g_entities[ tr.entityNum ]; + if (ShotThroughGlass(&tr, ent, spot, MASK_SHOT)) { + traceEnt = &g_entities[tr.entityNum]; } // shot is dead on - if ( traceEnt == ent ) - { + if (traceEnt == ent) { return qtrue; } -//MCG - Begin - else - {//ok, can't hit them in center, try their head - CalcEntitySpot( ent, SPOT_HEAD, spot ); - gi.trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; - if ( traceEnt == ent) - { + // MCG - Begin + else { // ok, can't hit them in center, try their head + CalcEntitySpot(ent, SPOT_HEAD, spot); + gi.trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, (EG2_Collision)0, 0); + traceEnt = &g_entities[tr.entityNum]; + if (traceEnt == ent) { return qtrue; } } - //Actually, we should just check to fire in dir we're facing and if it's close enough, - //and we didn't hit someone on our own team, shoot + // Actually, we should just check to fire in dir we're facing and if it's close enough, + // and we didn't hit someone on our own team, shoot VectorSubtract(spot, tr.endpos, diff); - if(VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) - { + if (VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) { return qtrue; } -//MCG - End - // shot would hit a non-client - if ( !traceEnt->client ) - { + // MCG - End + // shot would hit a non-client + if (!traceEnt->client) { return qfalse; } // shot is blocked by another player // he's already dead, so go ahead - if ( traceEnt->health <= 0 ) - { + if (traceEnt->health <= 0) { return qtrue; } // don't deliberately shoot a teammate - if ( traceEnt->client && ( traceEnt->client->playerTeam == shooter->client->playerTeam ) ) - { + if (traceEnt->client && (traceEnt->client->playerTeam == shooter->client->playerTeam)) { return qfalse; } @@ -1356,62 +1142,51 @@ qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) return qtrue; } - /* void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) Added: hacks for scripted NPCs */ -void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) -{ +void NPC_CheckPossibleEnemy(gentity_t *other, visibility_t vis) { // is he is already our enemy? - if ( other == NPC->enemy ) + if (other == NPC->enemy) return; - if ( other->flags & FL_NOTARGET ) + if (other->flags & FL_NOTARGET) return; // we already have an enemy and this guy is in our FOV, see if this guy would be better - if ( NPC->enemy && vis == VIS_FOV ) - { - if ( NPCInfo->enemyLastSeenTime - level.time < 2000 ) - { + if (NPC->enemy && vis == VIS_FOV) { + if (NPCInfo->enemyLastSeenTime - level.time < 2000) { return; } - if ( enemyVisibility == VIS_UNKNOWN ) - { - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_360|CHECK_FOV ); + if (enemyVisibility == VIS_UNKNOWN) { + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_360 | CHECK_FOV); } - if ( enemyVisibility == VIS_FOV ) - { + if (enemyVisibility == VIS_FOV) { return; } } - if ( !NPC->enemy ) - {//only take an enemy if you don't have one yet - G_SetEnemy( NPC, other ); + if (!NPC->enemy) { // only take an enemy if you don't have one yet + G_SetEnemy(NPC, other); } - if ( vis == VIS_FOV ) - { + if (vis == VIS_FOV) { NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( other->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(other->currentOrigin, NPCInfo->enemyLastSeenLocation); NPCInfo->enemyLastHeardTime = 0; - VectorClear( NPCInfo->enemyLastHeardLocation ); - } - else - { + VectorClear(NPCInfo->enemyLastHeardLocation); + } else { NPCInfo->enemyLastSeenTime = 0; - VectorClear( NPCInfo->enemyLastSeenLocation ); + VectorClear(NPCInfo->enemyLastSeenLocation); NPCInfo->enemyLastHeardTime = level.time; - VectorCopy( other->currentOrigin, NPCInfo->enemyLastHeardLocation ); + VectorCopy(other->currentOrigin, NPCInfo->enemyLastHeardLocation); } } - //========================================== -//MCG Added functions: +// MCG Added functions: //========================================== /* @@ -1421,130 +1196,107 @@ DOES NOT control how fast you can fire Only makes you keep your weapon up after you fire */ -int NPC_AttackDebounceForWeapon (void) -{ - switch ( NPC->client->ps.weapon ) - { -/* - case WP_BLASTER://scav rifle - return 1000; - break; +int NPC_AttackDebounceForWeapon(void) { + switch (NPC->client->ps.weapon) { + /* + case WP_BLASTER://scav rifle + return 1000; + break; - case WP_BRYAR_PISTOL://prifle - return 3000; - break; + case WP_BRYAR_PISTOL://prifle + return 3000; + break; + case WP_SABER: + return 100; + break; + */ case WP_SABER: - return 100; - break; -*/ - case WP_SABER: - if ( NPC->client->NPC_class == CLASS_KYLE - && (NPC->spawnflags&1) ) - { - return Q_irand( 1500, 5000 ); - } - else - { + if (NPC->client->NPC_class == CLASS_KYLE && (NPC->spawnflags & 1)) { + return Q_irand(1500, 5000); + } else { return 0; } break; case WP_BOT_LASER: - if ( g_spskill->integer == 0 ) + if (g_spskill->integer == 0) return 2000; - if ( g_spskill->integer == 1 ) + if (g_spskill->integer == 1) return 1500; return 1000; break; default: - return NPCInfo->burstSpacing + Q_irand(-100, 100);//was 100 by default + return NPCInfo->burstSpacing + Q_irand(-100, 100); // was 100 by default break; } } -//FIXME: need a mindist for explosive weapons -float NPC_MaxDistSquaredForWeapon (void) -{ - if(NPCInfo->stats.shootDistance > 0) - {//overrides default weapon dist +// FIXME: need a mindist for explosive weapons +float NPC_MaxDistSquaredForWeapon(void) { + if (NPCInfo->stats.shootDistance > 0) { // overrides default weapon dist return NPCInfo->stats.shootDistance * NPCInfo->stats.shootDistance; } - switch ( NPC->s.weapon ) - { - case WP_BLASTER://scav rifle - return 1024 * 1024;//should be shorter? + switch (NPC->s.weapon) { + case WP_BLASTER: // scav rifle + return 1024 * 1024; // should be shorter? break; - case WP_BRYAR_PISTOL://prifle + case WP_BRYAR_PISTOL: // prifle return 1024 * 1024; break; - case WP_BLASTER_PISTOL://prifle + case WP_BLASTER_PISTOL: // prifle return 1024 * 1024; break; - case WP_DISRUPTOR://disruptor + case WP_DISRUPTOR: // disruptor case WP_TUSKEN_RIFLE: - if ( NPCInfo->scriptFlags & SCF_ALT_FIRE ) - { - return ( 4096 * 4096 ); - } - else - { + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + return (4096 * 4096); + } else { return 1024 * 1024; } break; -/* - case WP_SABER: - return 1024 * 1024; - break; -*/ + /* + case WP_SABER: + return 1024 * 1024; + break; + */ case WP_SABER: - if ( NPC->client && NPC->client->ps.SaberLength() ) - {//FIXME: account for whether enemy and I are heading towards each other! - return (NPC->client->ps.SaberLength() + NPC->maxs[0]*1.5)*(NPC->client->ps.SaberLength() + NPC->maxs[0]*1.5); - } - else - { - return 48*48; + if (NPC->client && NPC->client->ps.SaberLength()) { // FIXME: account for whether enemy and I are heading towards each other! + return (NPC->client->ps.SaberLength() + NPC->maxs[0] * 1.5) * (NPC->client->ps.SaberLength() + NPC->maxs[0] * 1.5); + } else { + return 48 * 48; } break; default: - return 1024 * 1024;//was 0 + return 1024 * 1024; // was 0 break; } } +qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) { + vec3_t vec; - -qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) -{ - vec3_t vec; - - - if ( !toShoot ) - {//Not trying to actually press fire button with this check - if ( NPC->client->ps.weapon == WP_SABER ) - {//Just have to get to him + if (!toShoot) { // Not trying to actually press fire button with this check + if (NPC->client->ps.weapon == WP_SABER) { // Just have to get to him return qfalse; } } - - if(!dist) - { + if (!dist) { VectorSubtract(NPC->currentOrigin, enemy->currentOrigin, vec); dist = VectorLengthSquared(vec); } - if(dist > NPC_MaxDistSquaredForWeapon()) + if (dist > NPC_MaxDistSquaredForWeapon()) return qtrue; return qfalse; @@ -1567,131 +1319,94 @@ You can mix and match any of those options (example: find closest visible player FIXME: this should go through the snapshot and find the closest enemy */ -gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest ) -{ - int num_choices = 0; - int choice[128];//FIXME: need a different way to determine how many choices? - gentity_t *newenemy = NULL; - gentity_t *closestEnemy = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = Q3_INFINITE; - qboolean failed = qfalse; - int visChecks = (CHECK_360|CHECK_FOV|CHECK_VISRANGE); - int minVis = VIS_FOV; - - if ( enemyTeam == TEAM_NEUTRAL ) - { +gentity_t *NPC_PickEnemy(gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest) { + int num_choices = 0; + int choice[128]; // FIXME: need a different way to determine how many choices? + gentity_t *newenemy = NULL; + gentity_t *closestEnemy = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = Q3_INFINITE; + qboolean failed = qfalse; + int visChecks = (CHECK_360 | CHECK_FOV | CHECK_VISRANGE); + int minVis = VIS_FOV; + + if (enemyTeam == TEAM_NEUTRAL) { return NULL; } - if ( NPCInfo->behaviorState == BS_STAND_AND_SHOOT || - NPCInfo->behaviorState == BS_HUNT_AND_KILL ) - {//Formations guys don't require inFov to pick up a target - //These other behavior states are active battle states and should not - //use FOV. FOV checks are for enemies who are patrolling, guarding, etc. + if (NPCInfo->behaviorState == BS_STAND_AND_SHOOT || NPCInfo->behaviorState == BS_HUNT_AND_KILL) { // Formations guys don't require inFov to pick up a target + // These other behavior states are active battle states and should not + // use FOV. FOV checks are for enemies who are patrolling, guarding, etc. visChecks &= ~CHECK_FOV; minVis = VIS_360; } - if( findPlayersFirst ) - {//try to find a player first + if (findPlayersFirst) { // try to find a player first newenemy = &g_entities[0]; - if( newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if( newenemy->health > 0 ) - { - if( NPC_ValidEnemy( newenemy) )//enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || ( enemyTeam == TEAM_PLAYER ) ) - {//FIXME: check for range and FOV or vis? - if( newenemy != NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if ( gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin) ) - { - if(NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) - { - if(!NPC->enemy) - { - if(!InVisrange(newenemy)) - { + if (newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if (NPC_ValidEnemy(newenemy)) // enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || ( enemyTeam == TEAM_PLAYER ) ) + { // FIXME: check for range and FOV or vis? + if (newenemy != NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) { + if (NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) { + if (!NPC->enemy) { + if (!InVisrange(newenemy)) { failed = qtrue; - } - else if(NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { failed = qtrue; } } } - if ( !failed ) - { - VectorSubtract( closestTo->currentOrigin, newenemy->currentOrigin, diff ); + if (!failed) { + VectorSubtract(closestTo->currentOrigin, newenemy->currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them failed = qtrue; + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { failed = qtrue; } - } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, + newenemy->targetname, newenemy->client->hiddenDist); } } - if(!failed) - { - if(findClosest) - { - if(relDist < bestDist) - { - if(!NPC_EnemyTooFar(newenemy, relDist, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (!failed) { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if(!NPC_EnemyTooFar(newenemy, 0, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) == VIS_FOV) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1704,14 +1419,12 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - if (findClosest && closestEnemy) - { + if (findClosest && closestEnemy) { return closestEnemy; } - if (num_choices) - { - return &g_entities[ choice[rand() % num_choices] ]; + if (num_choices) { + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1726,117 +1439,84 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis bestDist = Q3_INFINITE; closestEnemy = NULL; - for ( entNum = 0; entNum < globals.num_entities; entNum++ ) - { + for (entNum = 0; entNum < globals.num_entities; entNum++) { newenemy = &g_entities[entNum]; - if ( newenemy != NPC && (newenemy->client || newenemy->svFlags & SVF_NONNPC_ENEMY) && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if ( newenemy->health > 0 ) - { - if ( (newenemy->client && NPC_ValidEnemy( newenemy)) - || (!newenemy->client && newenemy->noDamageTeam == enemyTeam) ) - {//FIXME: check for range and FOV or vis? - if ( NPC->client->playerTeam == TEAM_PLAYER && enemyTeam == TEAM_PLAYER ) - {//player allies turning on ourselves? How? - if ( newenemy->s.number ) - {//only turn on the player, not other player allies + if (newenemy != NPC && (newenemy->client || newenemy->svFlags & SVF_NONNPC_ENEMY) && !(newenemy->flags & FL_NOTARGET) && + !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if ((newenemy->client && NPC_ValidEnemy(newenemy)) || + (!newenemy->client && newenemy->noDamageTeam == enemyTeam)) { // FIXME: check for range and FOV or vis? + if (NPC->client->playerTeam == TEAM_PLAYER && enemyTeam == TEAM_PLAYER) { // player allies turning on ourselves? How? + if (newenemy->s.number) { // only turn on the player, not other player allies continue; } } - if ( newenemy != NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if(!gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) - { + if (newenemy != NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (!gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) { continue; } - if ( NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL ) - { - if ( !NPC->enemy ) - { - if ( !InVisrange( newenemy ) ) - { + if (NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) { + if (!NPC->enemy) { + if (!InVisrange(newenemy)) { continue; - } - else if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV ) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { continue; } } } - VectorSubtract( closestTo->currentOrigin, newenemy->currentOrigin, diff ); + VectorSubtract(closestTo->currentOrigin, newenemy->currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client && newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client && newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them continue; + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { continue; } - } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, + newenemy->client->hiddenDist); } } - if ( findClosest ) - { - if ( relDist < bestDist ) - { - if ( !NPC_EnemyTooFar( newenemy, relDist, qfalse ) ) - { - if ( checkVis ) - { - //FIXME: NPCs need to be able to pick up other NPCs behind them, - //but for now, commented out because it was picking up enemies it shouldn't - //if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - if ( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + // FIXME: NPCs need to be able to pick up other NPCs behind them, + // but for now, commented out because it was picking up enemies it shouldn't + // if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if ( !NPC_EnemyTooFar( newenemy, 0, qfalse ) ) - { - if ( checkVis ) - { - //if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + // if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1846,18 +1526,15 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - - if (findClosest) - {//FIXME: you can pick up an enemy around a corner this way. + if (findClosest) { // FIXME: you can pick up an enemy around a corner this way. return closestEnemy; } - if (!num_choices) - { + if (!num_choices) { return NULL; } - return &g_entities[ choice[rand() % num_choices] ]; + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1866,84 +1543,69 @@ gentity_t *NPC_PickAlly ( void ) Simply returns closest visible ally */ -gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly ) -{ - gentity_t *ally = NULL; - gentity_t *closestAlly = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = range; - - for ( entNum = 0; entNum < globals.num_entities; entNum++ ) - { +gentity_t *NPC_PickAlly(qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly) { + gentity_t *ally = NULL; + gentity_t *closestAlly = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = range; + + for (entNum = 0; entNum < globals.num_entities; entNum++) { ally = &g_entities[entNum]; - if ( ally->client ) - { - if ( ally->health > 0 ) - { - if ( ally->client && ( ally->client->playerTeam == NPC->client->playerTeam || - NPC->client->playerTeam == TEAM_ENEMY ) )// && ally->client->playerTeam == TEAM_DISGUISE ) ) ) - {//if on same team or if player is disguised as your team - if ( ignoreGroup ) - { - if ( ally == NPC->client->leader ) - { - //reject + if (ally->client) { + if (ally->health > 0) { + if (ally->client && (ally->client->playerTeam == NPC->client->playerTeam || + NPC->client->playerTeam == TEAM_ENEMY)) // && ally->client->playerTeam == TEAM_DISGUISE ) ) ) + { // if on same team or if player is disguised as your team + if (ignoreGroup) { + if (ally == NPC->client->leader) { + // reject continue; } - if ( ally->client && ally->client->leader && ally->client->leader == NPC ) - { - //reject + if (ally->client && ally->client->leader && ally->client->leader == NPC) { + // reject continue; } } - if(!gi.inPVS(ally->currentOrigin, NPC->currentOrigin)) - { + if (!gi.inPVS(ally->currentOrigin, NPC->currentOrigin)) { continue; } - if ( movingOnly && ally->client && NPC->client ) - {//They have to be moving relative to each other - if ( !DistanceSquared( ally->client->ps.velocity, NPC->client->ps.velocity ) ) - { + if (movingOnly && ally->client && NPC->client) { // They have to be moving relative to each other + if (!DistanceSquared(ally->client->ps.velocity, NPC->client->ps.velocity)) { continue; } } - VectorSubtract( NPC->currentOrigin, ally->currentOrigin, diff ); - relDist = VectorNormalize( diff ); - if ( relDist < bestDist ) - { - if ( facingEachOther ) - { - vec3_t vf; - float dot; + VectorSubtract(NPC->currentOrigin, ally->currentOrigin, diff); + relDist = VectorNormalize(diff); + if (relDist < bestDist) { + if (facingEachOther) { + vec3_t vf; + float dot; - AngleVectors( ally->client->ps.viewangles, vf, NULL, NULL ); + AngleVectors(ally->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot < 0.5 ) - {//Not facing in dir to me + if (dot < 0.5) { // Not facing in dir to me continue; } - //He's facing me, am I facing him? - AngleVectors( NPC->client->ps.viewangles, vf, NULL, NULL ); + // He's facing me, am I facing him? + AngleVectors(NPC->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot > -0.5 ) - {//I'm not facing opposite of dir to me + if (dot > -0.5) { // I'm not facing opposite of dir to me continue; } - //I am facing him + // I am facing him } - if ( NPC_CheckVisibility ( ally, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + if (NPC_CheckVisibility(ally, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { bestDist = relDist; closestAlly = ally; } @@ -1953,102 +1615,78 @@ gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignore } } - return closestAlly; } -gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnemy ) -{ - qboolean forcefindNew = qfalse; - gentity_t *closestTo; - gentity_t *newEnemy = NULL; - //FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot - //someone we can't hit? Rather than hard-coded 10? +gentity_t *NPC_CheckEnemy(qboolean findNew, qboolean tooFarOk, qboolean setEnemy) { + qboolean forcefindNew = qfalse; + gentity_t *closestTo; + gentity_t *newEnemy = NULL; + // FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot + // someone we can't hit? Rather than hard-coded 10? - //FIXME they shouldn't recognize enemy's death instantly + // FIXME they shouldn't recognize enemy's death instantly - //TEMP FIX: - //if(NPC->enemy->client) + // TEMP FIX: + // if(NPC->enemy->client) //{ // NPC->enemy->health = NPC->enemy->client->ps.stats[STAT_HEALTH]; - //} + // } - if ( NPC->enemy ) - { - if ( !NPC->enemy->inuse )//|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! + if (NPC->enemy) { + if (!NPC->enemy->inuse) //|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (setEnemy) { + G_ClearEnemy(NPC); } } } - if ( NPC->svFlags & SVF_IGNORE_ENEMIES ) - {//We're ignoring all enemies for now - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (NPC->svFlags & SVF_IGNORE_ENEMIES) { // We're ignoring all enemies for now + if (setEnemy) { + G_ClearEnemy(NPC); } return NULL; } // Kyle does not get new enemies if not close to his leader - if (NPC->client->NPC_class==CLASS_KYLE && - NPC->client->leader && - Distance(NPC->client->leader->currentOrigin, NPC->currentOrigin)>3000 - ) - { - if (NPC->enemy) - { - G_ClearEnemy( NPC ); + if (NPC->client->NPC_class == CLASS_KYLE && NPC->client->leader && Distance(NPC->client->leader->currentOrigin, NPC->currentOrigin) > 3000) { + if (NPC->enemy) { + G_ClearEnemy(NPC); } return NULL; } - - if ( NPC->svFlags & SVF_LOCKEDENEMY ) - {//keep this enemy until dead - if ( NPC->enemy ) - { - if ( (!NPC->NPC && !(NPC->svFlags & SVF_NONNPC_ENEMY) ) || NPC->enemy->health > 0 ) - {//Enemy never had health (a train or info_not_null, etc) or did and is now dead (NPCs, turrets, etc) + if (NPC->svFlags & SVF_LOCKEDENEMY) { // keep this enemy until dead + if (NPC->enemy) { + if ((!NPC->NPC && !(NPC->svFlags & SVF_NONNPC_ENEMY)) || + NPC->enemy->health > 0) { // Enemy never had health (a train or info_not_null, etc) or did and is now dead (NPCs, turrets, etc) return NULL; } } NPC->svFlags &= ~SVF_LOCKEDENEMY; } - if ( NPC->enemy ) - { - if ( NPC_EnemyTooFar(NPC->enemy, 0, qfalse) ) - { - if(findNew) - {//See if there is a close one and take it if so, else keep this one + if (NPC->enemy) { + if (NPC_EnemyTooFar(NPC->enemy, 0, qfalse)) { + if (findNew) { // See if there is a close one and take it if so, else keep this one forcefindNew = qtrue; - } - else if(!tooFarOk)//FIXME: don't need this extra bool any more + } else if (!tooFarOk) // FIXME: don't need this extra bool any more { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (setEnemy) { + G_ClearEnemy(NPC); } } - } - else if ( !gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin ) ) - {//FIXME: should this be a line-of site check? - //FIXME: a lot of things check PVS AGAIN when deciding whether - //or not to shoot, redundant! - //Should we lose the enemy? - //FIXME: if lose enemy, run lostenemyscript - if ( NPC->enemy->client && NPC->enemy->client->hiddenDist ) - {//He ducked into shadow while we weren't looking - //Drop enemy and see if we should search for him + } else if (!gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) { // FIXME: should this be a line-of site check? + // FIXME: a lot of things check PVS AGAIN when deciding whether + // or not to shoot, redundant! + // Should we lose the enemy? + // FIXME: if lose enemy, run lostenemyscript + if (NPC->enemy->client && NPC->enemy->client->hiddenDist) { // He ducked into shadow while we weren't looking + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); - } - else - {//If we're not chasing him, we need to lose him - //NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up + } else { // If we're not chasing him, we need to lose him + // NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up /* switch( NPCInfo->behaviorState ) @@ -2074,84 +1712,67 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem } } - if ( NPC->enemy ) - { - if ( NPC->enemy->health <= 0 || NPC->enemy->flags & FL_NOTARGET ) - { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (NPC->enemy) { + if (NPC->enemy->health <= 0 || NPC->enemy->flags & FL_NOTARGET) { + if (setEnemy) { + G_ClearEnemy(NPC); } } } closestTo = NPC; - //FIXME: check your defendEnt, if you have one, see if their enemy is different - //than yours, or, if they don't have one, pick the closest enemy to THEM? - if ( NPCInfo->defendEnt ) - {//Trying to protect someone - if ( NPCInfo->defendEnt->health > 0 ) - {//Still alive, We presume we're close to them, navigation should handle this? - if ( NPCInfo->defendEnt->enemy ) - {//They were shot or acquired an enemy - if ( NPC->enemy != NPCInfo->defendEnt->enemy ) - {//They have a different enemy, take it! + // FIXME: check your defendEnt, if you have one, see if their enemy is different + // than yours, or, if they don't have one, pick the closest enemy to THEM? + if (NPCInfo->defendEnt) { // Trying to protect someone + if (NPCInfo->defendEnt->health > 0) { // Still alive, We presume we're close to them, navigation should handle this? + if (NPCInfo->defendEnt->enemy) { // They were shot or acquired an enemy + if (NPC->enemy != NPCInfo->defendEnt->enemy) { // They have a different enemy, take it! newEnemy = NPCInfo->defendEnt->enemy; - if ( setEnemy ) - { - G_SetEnemy( NPC, NPCInfo->defendEnt->enemy ); + if (setEnemy) { + G_SetEnemy(NPC, NPCInfo->defendEnt->enemy); } } - } - else if ( NPC->enemy == NULL ) - {//We don't have an enemy, so find closest to defendEnt + } else if (NPC->enemy == NULL) { // We don't have an enemy, so find closest to defendEnt closestTo = NPCInfo->defendEnt; } } } - if (!NPC->enemy || ( NPC->enemy && NPC->enemy->health <= 0 ) || forcefindNew ) - {//FIXME: NPCs that are moving after an enemy should ignore the can't hit enemy counter- that should only be for NPCs that are standing still - //NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full + if (!NPC->enemy || (NPC->enemy && NPC->enemy->health <= 0) || forcefindNew) { // FIXME: NPCs that are moving after an enemy should ignore the can't hit + // enemy counter- that should only be for NPCs that are standing still + // NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full // 10 seconds, so give up. This means even if we're chasing him, we would // try to find another enemy after 10 seconds (assuming the cantHitEnemyCounter // is allowed to increment in a chasing bState) - qboolean foundenemy = qfalse; + qboolean foundenemy = qfalse; - if(!findNew) - { - if ( setEnemy ) - { + if (!findNew) { + if (setEnemy) { NPC->lastEnemy = NPC->enemy; G_ClearEnemy(NPC); } return NULL; } - //If enemy dead or unshootable, look for others on out enemy's team - if ( NPC->client->enemyTeam != TEAM_NEUTRAL) - { - //NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose + // If enemy dead or unshootable, look for others on out enemy's team + if (NPC->client->enemyTeam != TEAM_NEUTRAL) { + // NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose // means they need to find one that in more than just PVS - //newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - //For now, made it so you ALWAYS have to check VIS - newEnemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, qtrue, qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - if ( newEnemy ) - { + // newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == + // TEAM_STARFLEET) For now, made it so you ALWAYS have to check VIS + newEnemy = NPC_PickEnemy(closestTo, NPC->client->enemyTeam, qtrue, qfalse, qtrue); // 3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) + if (newEnemy) { foundenemy = qtrue; - if ( setEnemy ) - { - G_SetEnemy( NPC, newEnemy ); + if (setEnemy) { + G_SetEnemy(NPC, newEnemy); } } } - //if ( !forcefindNew ) + // if ( !forcefindNew ) { - if ( !foundenemy ) - { - if ( setEnemy ) - { + if (!foundenemy) { + if (setEnemy) { NPC->lastEnemy = NPC->enemy; G_ClearEnemy(NPC); } @@ -2159,19 +1780,14 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem NPC->cantHitEnemyCounter = 0; } - //FIXME: if we can't find any at all, go into INdependant NPC AI, pursue and kill + // FIXME: if we can't find any at all, go into INdependant NPC AI, pursue and kill } - if ( NPC->enemy && NPC->enemy->client ) - { - if(NPC->enemy->client->playerTeam - && NPC->enemy->client->playerTeam != TEAM_FREE) - { -// assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); - if( NPC->client->playerTeam != NPC->enemy->client->playerTeam - && NPC->client->enemyTeam != TEAM_FREE - && NPC->client->enemyTeam != NPC->enemy->client->playerTeam ) - { + if (NPC->enemy && NPC->enemy->client) { + if (NPC->enemy->client->playerTeam && NPC->enemy->client->playerTeam != TEAM_FREE) { + // assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); + if (NPC->client->playerTeam != NPC->enemy->client->playerTeam && NPC->client->enemyTeam != TEAM_FREE && + NPC->client->enemyTeam != NPC->enemy->client->playerTeam) { NPC->client->enemyTeam = NPC->enemy->client->playerTeam; } } @@ -2185,37 +1801,33 @@ NPC_ClearShot ------------------------- */ -qboolean NPC_ClearShot( gentity_t *ent ) -{ - if ( ( NPC == NULL ) || ( ent == NULL ) ) +qboolean NPC_ClearShot(gentity_t *ent) { + if ((NPC == NULL) || (ent == NULL)) return qfalse; - vec3_t muzzle; - trace_t tr; + vec3_t muzzle; + trace_t tr; - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - gi.trace ( &tr, muzzle, mins, maxs, ent->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - } - else - { - gi.trace ( &tr, muzzle, NULL, NULL, ent->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, muzzle, mins, maxs, ent->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + } else { + gi.trace(&tr, muzzle, NULL, NULL, ent->currentOrigin, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); } - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { return qfalse; } - if ( tr.entityNum == ent->s.number ) + if (tr.entityNum == ent->s.number) return qtrue; return qfalse; @@ -2227,71 +1839,62 @@ NPC_ShotEntity ------------------------- */ -int NPC_ShotEntity( gentity_t *ent, vec3_t impactPos ) -{ - if ( ( NPC == NULL ) || ( ent == NULL ) ) +int NPC_ShotEntity(gentity_t *ent, vec3_t impactPos) { + if ((NPC == NULL) || (ent == NULL)) return qfalse; - vec3_t muzzle; + vec3_t muzzle; vec3_t targ; - trace_t tr; + trace_t tr; - if ( NPC->s.weapon == WP_THERMAL ) - {//thermal aims from slightly above head - //FIXME: what about low-angle shots, rolling the thermal under something? - vec3_t angles, forward, end; + if (NPC->s.weapon == WP_THERMAL) { // thermal aims from slightly above head + // FIXME: what about low-angle shots, rolling the thermal under something? + vec3_t angles, forward, end; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - VectorSet( angles, 0, NPC->client->ps.viewangles[1], 0 ); - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( muzzle, 8, forward, end ); + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + VectorSet(angles, 0, NPC->client->ps.viewangles[1], 0); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(muzzle, 8, forward, end); end[2] += 24; - gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - VectorCopy( tr.endpos, muzzle ); - } - else - { - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + VectorCopy(tr.endpos, muzzle); + } else { + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); } - CalcEntitySpot( ent, SPOT_CHEST, targ ); + CalcEntitySpot(ent, SPOT_CHEST, targ); // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - gi.trace ( &tr, muzzle, mins, maxs, targ, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - } - else - { - gi.trace ( &tr, muzzle, NULL, NULL, targ, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - } - //FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? - if ( impactPos ) - {//they want to know *where* the hit would be, too - VectorCopy( tr.endpos, impactPos ); + gi.trace(&tr, muzzle, mins, maxs, targ, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + } else { + gi.trace(&tr, muzzle, NULL, NULL, targ, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); } -/* // NPCs should be able to shoot even if the muzzle would be inside their target - if ( tr.startsolid || tr.allsolid ) - { - return ENTITYNUM_NONE; + // FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? + if (impactPos) { // they want to know *where* the hit would be, too + VectorCopy(tr.endpos, impactPos); } -*/ + /* // NPCs should be able to shoot even if the muzzle would be inside their target + if ( tr.startsolid || tr.allsolid ) + { + return ENTITYNUM_NONE; + } + */ return tr.entityNum; } -qboolean NPC_EvaluateShot( int hit, qboolean glassOK ) -{ - if ( !NPC->enemy ) - { +qboolean NPC_EvaluateShot(int hit, qboolean glassOK) { + if (!NPC->enemy) { return qfalse; } - if ( hit == NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -2303,17 +1906,15 @@ NPC_CheckAttack Simply checks aggression and returns true or false */ -qboolean NPC_CheckAttack (float scale) -{ - if(!scale) +qboolean NPC_CheckAttack(float scale) { + if (!scale) scale = 1.0; - if(((float)NPCInfo->stats.aggression) * scale < Q_flrand(0, 4)) - { + if (((float)NPCInfo->stats.aggression) * scale < Q_flrand(0, 4)) { return qfalse; } - if(NPCInfo->shotTime > level.time) + if (NPCInfo->shotTime > level.time) return qfalse; return qtrue; @@ -2325,93 +1926,81 @@ NPC_CheckDefend Simply checks evasion and returns true or false */ -qboolean NPC_CheckDefend (float scale) -{ - if(!scale) +qboolean NPC_CheckDefend(float scale) { + if (!scale) scale = 1.0; - if((float)(NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) + if ((float)(NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) return qtrue; return qfalse; } - -//NOTE: BE SURE TO CHECK PVS BEFORE THIS! -qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) -{ - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org;//, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; -// qboolean duck_ok = qfalse; - qboolean dead_on = qfalse; - float aim_off; - float max_aim_off = 128 - (16 * (float)NPCInfo->stats.aim); - trace_t tr; - gentity_t *traceEnt = NULL; - - if(NPC->enemy->flags & FL_NOTARGET) - { +// NOTE: BE SURE TO CHECK PVS BEFORE THIS! +qboolean NPC_CheckCanAttack(float attack_scale, qboolean stationary) { + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org; //, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + // qboolean duck_ok = qfalse; + qboolean dead_on = qfalse; + float aim_off; + float max_aim_off = 128 - (16 * (float)NPCInfo->stats.aim); + trace_t tr; + gentity_t *traceEnt = NULL; + + if (NPC->enemy->flags & FL_NOTARGET) { return qfalse; } - //FIXME: only check to see if should duck if that provides cover from the - //enemy!!! - if(!attack_scale) - { + // FIXME: only check to see if should duck if that provides cover from the + // enemy!!! + if (!attack_scale) { attack_scale = 1.0; } - //Yaw to enemy - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + // Yaw to enemy + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); NPC->NPC->desiredYaw = angleToEnemy[YAW]; NPC_UpdateFiringAngles(qfalse, qtrue); - if( NPC_EnemyTooFar(NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue) ) - {//Too far away? Do not attack + if (NPC_EnemyTooFar(NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { // Too far away? Do not attack return qfalse; } - if(client->fireDelay > 0) - {//already waiting for a shot to fire + if (client->fireDelay > 0) { // already waiting for a shot to fire NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); return qfalse; } - if(NPCInfo->scriptFlags & SCF_DONT_FIRE) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { return qfalse; } NPCInfo->enemyLastVisibility = enemyVisibility; - //See if they're in our FOV and we have a clear shot to them - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_360|CHECK_FOV);////CHECK_PVS| + // See if they're in our FOV and we have a clear shot to them + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_360 | CHECK_FOV); ////CHECK_PVS| - if(enemyVisibility >= VIS_FOV) - {//He's in our FOV + if (enemyVisibility >= VIS_FOV) { // He's in our FOV attack_ok = qtrue; - //CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); - - //Check to duck - if ( NPC->enemy->client ) - { - if ( NPC->enemy->enemy == NPC ) - { - if ( NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? - {//duck and don't shoot + // CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + + // Check to duck + if (NPC->enemy->client) { + if (NPC->enemy->enemy == NPC) { + if (NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? + { // duck and don't shoot attack_ok = qfalse; ucmd.upmove = -127; } @@ -2419,14 +2008,13 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if(attack_ok) - { - //are we gonna hit him - //NEW: use actual forward facing - AngleVectors( client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, distanceToEnemy, forward, hitspot ); - gi.trace( &tr, muzzle, NULL, NULL, hitspot, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - ShotThroughGlass( &tr, NPC->enemy, hitspot, MASK_SHOT ); + if (attack_ok) { + // are we gonna hit him + // NEW: use actual forward facing + AngleVectors(client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); + gi.trace(&tr, muzzle, NULL, NULL, hitspot, NPC->s.number, MASK_SHOT, (EG2_Collision)0, 0); + ShotThroughGlass(&tr, NPC->enemy, hitspot, MASK_SHOT); /* //OLD: trace regardless of facing gi.trace ( &tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT ); @@ -2451,21 +2039,15 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } */ - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -2473,75 +2055,60 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - if(traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) - {//easy to kill - go for it - if(traceEnt->e_DieFunc == dieF_ExplodeDeath_Wait && traceEnt->splashDamage) - {//going to explode, don't shoot if close to self + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + if (traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) { // easy to kill - go for it + if (traceEnt->e_DieFunc == dieF_ExplodeDeath_Wait && traceEnt->splashDamage) { // going to explode, don't shoot if close to self VectorSubtract(NPC->currentOrigin, traceEnt->currentOrigin, diff); - if(VectorLengthSquared(diff) < traceEnt->splashRadius*traceEnt->splashRadius) - {//Too close to shoot! + if (VectorLengthSquared(diff) < traceEnt->splashRadius * traceEnt->splashRadius) { // Too close to shoot! attack_ok = qfalse; - } - else - {//Hey, it might kill him, do it! - attack_scale *= 2;// + } else { // Hey, it might kill him, do it! + attack_scale *= 2; // } } - } - else - { - AngleVectors (client->ps.viewangles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + } else { + AngleVectors(client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } - } - else - {//Update pitch anyway + } else { // Update pitch anyway NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); - } - else + } else attack_ok = qfalse; } return attack_ok; } //======================================================================================== -//OLD id-style hunt and kill +// OLD id-style hunt and kill //======================================================================================== /* IdealDistance @@ -2549,13 +2116,11 @@ IdealDistance determines what the NPC's ideal distance from it's enemy should be in the current situation */ -float IdealDistance ( gentity_t *self ) -{ - float ideal; +float IdealDistance(gentity_t *self) { + float ideal; ideal = 225 - 20 * NPCInfo->stats.aggression; - switch ( NPC->s.weapon ) - { + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: ideal += 200; break; @@ -2590,12 +2155,10 @@ LEAN - Lean-type cover, NOT IMPLEMENTED SNIPE - Snipers look for these first, NOT IMPLEMENTED */ -void SP_point_combat( gentity_t *self ) -{ - if(level.numCombatPoints >= MAX_COMBAT_POINTS) - { +void SP_point_combat(gentity_t *self) { + if (level.numCombatPoints >= MAX_COMBAT_POINTS) { #ifndef FINAL_BUILD - gi.Printf(S_COLOR_RED"ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); + gi.Printf(S_COLOR_RED "ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); #endif G_FreeEntity(self); return; @@ -2605,14 +2168,13 @@ void SP_point_combat( gentity_t *self ) G_SetOrigin(self, self->s.origin); gi.linkentity(self); - if ( G_CheckInSolid( self, qtrue ) ) - { + if (G_CheckInSolid(self, qtrue)) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: combat point at %s in solid!\n", vtos(self->currentOrigin) ); + gi.Printf(S_COLOR_RED "ERROR: combat point at %s in solid!\n", vtos(self->currentOrigin)); #endif } - VectorCopy( self->currentOrigin, level.combatPoints[level.numCombatPoints].origin ); + VectorCopy(self->currentOrigin, level.combatPoints[level.numCombatPoints].origin); level.combatPoints[level.numCombatPoints].flags = self->spawnflags; level.combatPoints[level.numCombatPoints].occupied = qfalse; @@ -2624,83 +2186,71 @@ void SP_point_combat( gentity_t *self ) G_FreeEntity(self); }; -void CP_FindCombatPointWaypoints( void ) -{ - for ( int i = 0; i < level.numCombatPoints; i++ ) - { +void CP_FindCombatPointWaypoints(void) { + for (int i = 0; i < level.numCombatPoints; i++) { level.combatPoints[i].waypoint = NAV::GetNearestNode(level.combatPoints[i].origin); - if ( level.combatPoints[i].waypoint == WAYPOINT_NONE ) - { + if (level.combatPoints[i].waypoint == WAYPOINT_NONE) { assert(0); level.combatPoints[i].waypoint = NAV::GetNearestNode(level.combatPoints[i].origin); - gi.Printf( S_COLOR_RED"ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin) ); + gi.Printf(S_COLOR_RED "ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin)); delayedShutDown = level.time + 100; } } } - /* ------------------------- NPC_CollectCombatPoints ------------------------- */ -typedef std::map< float, int > combatPoint_m; +typedef std::map combatPoint_m; -static int NPC_CollectCombatPoints( const vec3_t origin, const float radius, combatPoint_m &points, const int flags ) -{ - float radiusSqr = (radius*radius); - float distance; +static int NPC_CollectCombatPoints(const vec3_t origin, const float radius, combatPoint_m &points, const int flags) { + float radiusSqr = (radius * radius); + float distance; - //Collect all nearest - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - //Must be vacant - if ( level.combatPoints[i].occupied == (int) qtrue ) + // Collect all nearest + for (int i = 0; i < level.numCombatPoints; i++) { + // Must be vacant + if (level.combatPoints[i].occupied == (int)qtrue) continue; - //If we want a duck space, make sure this is one - if ( ( flags & CP_DUCK ) && !( level.combatPoints[i].flags & CPF_DUCK ) ) + // If we want a duck space, make sure this is one + if ((flags & CP_DUCK) && !(level.combatPoints[i].flags & CPF_DUCK)) continue; - //If we want a flee point, make sure this is one - if ( ( flags & CP_FLEE ) && !( level.combatPoints[i].flags & CPF_FLEE ) ) + // If we want a flee point, make sure this is one + if ((flags & CP_FLEE) && !(level.combatPoints[i].flags & CPF_FLEE)) continue; - //If we want a snipe point, make sure this is one - if ( ( flags & CP_SNIPE ) && !( level.combatPoints[i].flags & CPF_SNIPE ) ) + // If we want a snipe point, make sure this is one + if ((flags & CP_SNIPE) && !(level.combatPoints[i].flags & CPF_SNIPE)) continue; - ///Make sure this is an investigate combat point - if ( ( flags & CP_INVESTIGATE ) && ( level.combatPoints[i].flags & CPF_INVESTIGATE ) ) + /// Make sure this is an investigate combat point + if ((flags & CP_INVESTIGATE) && (level.combatPoints[i].flags & CPF_INVESTIGATE)) continue; - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) && ( ( flags & CP_SQUAD ) == qfalse ) ) + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) && ((flags & CP_SQUAD) == qfalse)) continue; - if ( flags&CP_NO_PVS ) - {//must not be within PVS of mu current origin - if ( gi.inPVS( origin, level.combatPoints[i].origin ) ) - { + if (flags & CP_NO_PVS) { // must not be within PVS of mu current origin + if (gi.inPVS(origin, level.combatPoints[i].origin)) { continue; } } - if ( flags&CP_HORZ_DIST_COLL ) - { - distance = DistanceHorizontalSquared( origin, level.combatPoints[i].origin ); - } - else - { - distance = DistanceSquared( origin, level.combatPoints[i].origin ); + if (flags & CP_HORZ_DIST_COLL) { + distance = DistanceHorizontalSquared(origin, level.combatPoints[i].origin); + } else { + distance = DistanceSquared(origin, level.combatPoints[i].origin); } - if ( distance < radiusSqr ) - { - //Using a map will sort nearest automatically - points[ distance ] = i; + if (distance < radiusSqr) { + // Using a map will sort nearest automatically + points[distance] = i; } } @@ -2713,276 +2263,204 @@ NPC_FindCombatPoint ------------------------- */ -#define MIN_AVOID_DOT 0.7f -#define MIN_AVOID_DISTANCE 128 -#define MIN_AVOID_DISTANCE_SQUARED ( MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE ) -#define CP_COLLECT_RADIUS 512.0f - -int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3_t destPosition, const int flags, float avoidDist, const int ignorePoint ) -{ - combatPoint_m points; - combatPoint_m::iterator cpi; - - int best = -1;//, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE, destWaypoint = WAYPOINT_NONE; - trace_t tr; - float collRad = CP_COLLECT_RADIUS; - vec3_t eDir2Me, eDir2CP, weaponOffset; - vec3_t enemyPosition; - float dotToCp; - //float distSqPointToNPC; - float distSqPointToEnemy; - float distSqPointToEnemyHoriz; - float distSqPointToEnemyCheck; - float distSqNPCToEnemy; - float distSqNPCToEnemyHoriz; - float distSqNPCToEnemyCheck; - float visRangeSq = (NPCInfo->stats.visrange*NPCInfo->stats.visrange); - bool useHorizDist = (NPC->s.weapon==WP_THERMAL) || (flags & CP_HORZ_DIST_COLL); - - if (NPC->enemy) - { +#define MIN_AVOID_DOT 0.7f +#define MIN_AVOID_DISTANCE 128 +#define MIN_AVOID_DISTANCE_SQUARED (MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE) +#define CP_COLLECT_RADIUS 512.0f + +int NPC_FindCombatPoint(const vec3_t position, const vec3_t avoidPosition, vec3_t destPosition, const int flags, float avoidDist, const int ignorePoint) { + combatPoint_m points; + combatPoint_m::iterator cpi; + + int best = -1; //, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE, destWaypoint = WAYPOINT_NONE; + trace_t tr; + float collRad = CP_COLLECT_RADIUS; + vec3_t eDir2Me, eDir2CP, weaponOffset; + vec3_t enemyPosition; + float dotToCp; + // float distSqPointToNPC; + float distSqPointToEnemy; + float distSqPointToEnemyHoriz; + float distSqPointToEnemyCheck; + float distSqNPCToEnemy; + float distSqNPCToEnemyHoriz; + float distSqNPCToEnemyCheck; + float visRangeSq = (NPCInfo->stats.visrange * NPCInfo->stats.visrange); + bool useHorizDist = (NPC->s.weapon == WP_THERMAL) || (flags & CP_HORZ_DIST_COLL); + + if (NPC->enemy) { VectorCopy(NPC->enemy->currentOrigin, enemyPosition); - } - else if (avoidPosition) - { + } else if (avoidPosition) { VectorCopy(avoidPosition, enemyPosition); - } - else if (destPosition) - { + } else if (destPosition) { VectorCopy(destPosition, enemyPosition); - } - else - { + } else { VectorCopy(NPC->currentOrigin, enemyPosition); } - if ( avoidDist <= 0 ) - { + if (avoidDist <= 0) { avoidDist = MIN_AVOID_DISTANCE_SQUARED; - } - else - { + } else { avoidDist *= avoidDist; } - - //Collect our nearest points - if ( (flags & CP_NO_PVS) || (flags & CP_TRYFAR)) - {//much larger radius since most will be dropped? - collRad = CP_COLLECT_RADIUS*4; + // Collect our nearest points + if ((flags & CP_NO_PVS) || (flags & CP_TRYFAR)) { // much larger radius since most will be dropped? + collRad = CP_COLLECT_RADIUS * 4; } - NPC_CollectCombatPoints( destPosition, collRad, points, flags );//position + NPC_CollectCombatPoints(destPosition, collRad, points, flags); // position - for ( cpi = points.begin(); cpi != points.end(); ++cpi ) - { + for (cpi = points.begin(); cpi != points.end(); ++cpi) { const int i = (*cpi).second; - //Must not be one we want to ignore - if ( i == ignorePoint ) - { + // Must not be one we want to ignore + if (i == ignorePoint) { continue; } - //Get some distances for reasoning - //distSqPointToNPC = (*cpi).first; - - distSqPointToEnemy = DistanceSquared (level.combatPoints[i].origin, enemyPosition); - distSqPointToEnemyHoriz = DistanceHorizontalSquared(level.combatPoints[i].origin, enemyPosition); - distSqPointToEnemyCheck = (useHorizDist)?(distSqPointToEnemyHoriz):(distSqPointToEnemy); + // Get some distances for reasoning + // distSqPointToNPC = (*cpi).first; - distSqNPCToEnemy = DistanceSquared (NPC->currentOrigin, enemyPosition); - distSqNPCToEnemyHoriz = DistanceHorizontalSquared(NPC->currentOrigin, enemyPosition); - distSqNPCToEnemyCheck = (useHorizDist)?(distSqNPCToEnemyHoriz ):(distSqNPCToEnemy); + distSqPointToEnemy = DistanceSquared(level.combatPoints[i].origin, enemyPosition); + distSqPointToEnemyHoriz = DistanceHorizontalSquared(level.combatPoints[i].origin, enemyPosition); + distSqPointToEnemyCheck = (useHorizDist) ? (distSqPointToEnemyHoriz) : (distSqPointToEnemy); + distSqNPCToEnemy = DistanceSquared(NPC->currentOrigin, enemyPosition); + distSqNPCToEnemyHoriz = DistanceHorizontalSquared(NPC->currentOrigin, enemyPosition); + distSqNPCToEnemyCheck = (useHorizDist) ? (distSqNPCToEnemyHoriz) : (distSqNPCToEnemy); - - //Ignore points that are farther than currently located - if ( (flags & CP_APPROACH_ENEMY) && (distSqPointToEnemyCheck > distSqNPCToEnemyCheck)) - { + // Ignore points that are farther than currently located + if ((flags & CP_APPROACH_ENEMY) && (distSqPointToEnemyCheck > distSqNPCToEnemyCheck)) { continue; } - //Ignore points that are closer than currently located - if ( (flags & CP_RETREAT) && (distSqPointToEnemyCheck < distSqNPCToEnemyCheck)) - { + // Ignore points that are closer than currently located + if ((flags & CP_RETREAT) && (distSqPointToEnemyCheck < distSqNPCToEnemyCheck)) { continue; } - //Ignore points that are out of vis range - if ( (flags & CP_CLEAR) && (distSqPointToEnemyCheck > visRangeSq)) - { + // Ignore points that are out of vis range + if ((flags & CP_CLEAR) && (distSqPointToEnemyCheck > visRangeSq)) { continue; } - //Avoid this position? - if ( avoidPosition && !(flags & CP_AVOID_ENEMY) && (flags & CP_AVOID) && (DistanceSquared(level.combatPoints[i].origin, avoidPosition)= 0.4 ) - { + // Not far enough behind enemy from current pos + if (dotToCp >= 0.4) { continue; } } - //we must have a route to the combat point - if ( (flags & CP_HAS_ROUTE) && !NAV::InSameRegion(NPC, level.combatPoints[i].origin)) - { + // we must have a route to the combat point + if ((flags & CP_HAS_ROUTE) && !NAV::InSameRegion(NPC, level.combatPoints[i].origin)) { continue; } - - //See if we're trying to avoid our enemy - if (flags & CP_AVOID_ENEMY) - { - //Can't be too close to the enemy - if (distSqPointToEnemy(avoidDist) && - !NAV::SafePathExists(position, level.combatPoints[i].origin, enemyPosition, avoidDist)) - { + if (distSqNPCToEnemy > (avoidDist) && !NAV::SafePathExists(position, level.combatPoints[i].origin, enemyPosition, avoidDist)) { continue; } } - //Okay, now make sure it's not blocked - gi.trace( &tr, level.combatPoints[i].origin, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + // Okay, now make sure it's not blocked + gi.trace(&tr, level.combatPoints[i].origin, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { continue; } - if (NPC->enemy) - { + if (NPC->enemy) { // Ignore Points That Do Not Have A Clear LOS To The Player - if ( (flags & CP_CLEAR) ) - { + if ((flags & CP_CLEAR)) { CalcEntitySpot(NPC, SPOT_WEAPON, weaponOffset); VectorSubtract(weaponOffset, NPC->currentOrigin, weaponOffset); VectorAdd(weaponOffset, level.combatPoints[i].origin, weaponOffset); - if (NPC_ClearLOS(weaponOffset, NPC->enemy)==qfalse) - { + if (NPC_ClearLOS(weaponOffset, NPC->enemy) == qfalse) { continue; } } // Ignore points that are not behind cover - if ( (flags & CP_COVER) && NPC_ClearLOS(level.combatPoints[i].origin, NPC->enemy)==qtrue) - { + if ((flags & CP_COVER) && NPC_ClearLOS(level.combatPoints[i].origin, NPC->enemy) == qtrue) { continue; } } - //they are sorted by this distance, so the first one to get this far is the closest + // they are sorted by this distance, so the first one to get this far is the closest return i; } return best; } -int NPC_FindCombatPointRetry( const vec3_t position, - const vec3_t avoidPosition, - vec3_t destPosition, - int *cpFlags, - float avoidDist, - const int ignorePoint ) -{ +int NPC_FindCombatPointRetry(const vec3_t position, const vec3_t avoidPosition, vec3_t destPosition, int *cpFlags, float avoidDist, const int ignorePoint) { int cp = -1; - cp = NPC_FindCombatPoint( position, - avoidPosition, - destPosition, - *cpFlags, - avoidDist, - ignorePoint ); - while ( cp == -1 && (*cpFlags&~CP_HAS_ROUTE) != CP_ANY ) - {//start "OR"ing out certain flags to see if we can find *any* point - if ( *cpFlags & CP_INVESTIGATE ) - {//don't need to investigate + cp = NPC_FindCombatPoint(position, avoidPosition, destPosition, *cpFlags, avoidDist, ignorePoint); + while (cp == -1 && (*cpFlags & ~CP_HAS_ROUTE) != CP_ANY) { // start "OR"ing out certain flags to see if we can find *any* point + if (*cpFlags & CP_INVESTIGATE) { // don't need to investigate *cpFlags &= ~CP_INVESTIGATE; - } - else if ( *cpFlags & CP_SQUAD ) - {//don't need to stick to squads + } else if (*cpFlags & CP_SQUAD) { // don't need to stick to squads *cpFlags &= ~CP_SQUAD; - } - else if ( *cpFlags & CP_DUCK ) - {//don't need to duck + } else if (*cpFlags & CP_DUCK) { // don't need to duck *cpFlags &= ~CP_DUCK; - } - else if ( *cpFlags & CP_NEAREST ) - {//don't need closest one to me + } else if (*cpFlags & CP_NEAREST) { // don't need closest one to me *cpFlags &= ~CP_NEAREST; - } - else if ( *cpFlags & CP_FLANK ) - {//don't need to flank enemy + } else if (*cpFlags & CP_FLANK) { // don't need to flank enemy *cpFlags &= ~CP_FLANK; - } - else if ( *cpFlags & CP_SAFE ) - {//don't need one that hasn't been shot at recently + } else if (*cpFlags & CP_SAFE) { // don't need one that hasn't been shot at recently *cpFlags &= ~CP_SAFE; - } - else if ( *cpFlags & CP_CLOSEST ) - {//don't need to get closest to enemy + } else if (*cpFlags & CP_CLOSEST) { // don't need to get closest to enemy *cpFlags &= ~CP_CLOSEST; - //but let's try to approach at least + // but let's try to approach at least *cpFlags |= CP_APPROACH_ENEMY; - } - else if ( *cpFlags & CP_APPROACH_ENEMY ) - {//don't need to approach enemy + } else if (*cpFlags & CP_APPROACH_ENEMY) { // don't need to approach enemy *cpFlags &= ~CP_APPROACH_ENEMY; - } - else if ( *cpFlags & CP_COVER ) - {//don't need cover + } else if (*cpFlags & CP_COVER) { // don't need cover *cpFlags &= ~CP_COVER; - //but let's pick one that makes us duck + // but let's pick one that makes us duck //*cpFlags |= CP_DUCK; } - // else if ( *cpFlags & CP_CLEAR ) - // {//don't need a clear shot to enemy - // *cpFlags &= ~CP_CLEAR; - // } - // Never Give Up On Avoiding The Enemy - // else if ( *cpFlags & CP_AVOID_ENEMY ) - // {//don't need to avoid enemy - // *cpFlags &= ~CP_AVOID_ENEMY; - // } - else if ( *cpFlags & CP_RETREAT ) - {//don't need to retreat + // else if ( *cpFlags & CP_CLEAR ) + // {//don't need a clear shot to enemy + // *cpFlags &= ~CP_CLEAR; + // } + // Never Give Up On Avoiding The Enemy + // else if ( *cpFlags & CP_AVOID_ENEMY ) + // {//don't need to avoid enemy + // *cpFlags &= ~CP_AVOID_ENEMY; + // } + else if (*cpFlags & CP_RETREAT) { // don't need to retreat *cpFlags &= ~CP_RETREAT; - } - else if ( *cpFlags &CP_FLEE ) - {//don't need to flee + } else if (*cpFlags & CP_FLEE) { // don't need to flee *cpFlags &= ~CP_FLEE; - //but at least avoid enemy and pick one that gives cover - *cpFlags |= (CP_COVER|CP_AVOID_ENEMY); - } - else if ( *cpFlags & CP_AVOID ) - {//okay, even pick one right by me + // but at least avoid enemy and pick one that gives cover + *cpFlags |= (CP_COVER | CP_AVOID_ENEMY); + } else if (*cpFlags & CP_AVOID) { // okay, even pick one right by me *cpFlags &= ~CP_AVOID; - } - else if ( *cpFlags & CP_SHORTEST_PATH ) - {//okay, don't need the one with the shortest path + } else if (*cpFlags & CP_SHORTEST_PATH) { // okay, don't need the one with the shortest path *cpFlags &= ~CP_SHORTEST_PATH; - } - else - {//screw it, we give up! + } else { // screw it, we give up! return -1; /* if ( *cpFlags & CP_HAS_ROUTE ) @@ -2995,13 +2473,8 @@ int NPC_FindCombatPointRetry( const vec3_t position, } */ } - //now try again - cp = NPC_FindCombatPoint( position, - avoidPosition, - destPosition, - *cpFlags, - avoidDist, - ignorePoint ); + // now try again + cp = NPC_FindCombatPoint(position, avoidPosition, destPosition, *cpFlags, avoidDist, ignorePoint); } return cp; } @@ -3011,32 +2484,29 @@ NPC_FindSquadPoint ------------------------- */ -int NPC_FindSquadPoint( vec3_t position ) -{ - float dist, nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - int nearestPoint = -1; +int NPC_FindSquadPoint(vec3_t position) { + float dist, nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + int nearestPoint = -1; - //float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->currentOrigin ); + // float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->currentOrigin ); - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) == qfalse ) + for (int i = 0; i < level.numCombatPoints; i++) { + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) == qfalse) continue; - //Must be vacant - if ( level.combatPoints[i].occupied == qtrue ) + // Must be vacant + if (level.combatPoints[i].occupied == qtrue) continue; - dist = DistanceSquared( position, level.combatPoints[i].origin ); + dist = DistanceSquared(position, level.combatPoints[i].origin); - //The point cannot take us past the player - //if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this + // The point cannot take us past the player + // if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this // continue; - //See if this is closer than the others - if ( dist < nearestDist ) - { + // See if this is closer than the others + if (dist < nearestDist) { nearestPoint = i; nearestDist = dist; } @@ -3051,17 +2521,16 @@ NPC_ReserveCombatPoint ------------------------- */ -qboolean NPC_ReserveCombatPoint( int combatPointID ) -{ - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) +qboolean NPC_ReserveCombatPoint(int combatPointID) { + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's not already occupied - if ( level.combatPoints[combatPointID].occupied ) + // Make sure it's not already occupied + if (level.combatPoints[combatPointID].occupied) return qfalse; - //Reserve it + // Reserve it level.combatPoints[combatPointID].occupied = qtrue; return qtrue; @@ -3073,21 +2542,19 @@ NPC_FreeCombatPoint ------------------------- */ -qboolean NPC_FreeCombatPoint( int combatPointID, qboolean failed ) -{ - if ( failed ) - {//remember that this one failed for us +qboolean NPC_FreeCombatPoint(int combatPointID, qboolean failed) { + if (failed) { // remember that this one failed for us NPCInfo->lastFailedCombatPoint = combatPointID; } - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's currently occupied - if ( level.combatPoints[combatPointID].occupied == qfalse ) + // Make sure it's currently occupied + if (level.combatPoints[combatPointID].occupied == qfalse) return qfalse; - //Free it + // Free it level.combatPoints[combatPointID].occupied = qfalse; return qtrue; @@ -3099,20 +2566,17 @@ NPC_SetCombatPoint ------------------------- */ -qboolean NPC_SetCombatPoint( int combatPointID ) -{ - if (combatPointID==NPCInfo->combatPoint) - { +qboolean NPC_SetCombatPoint(int combatPointID) { + if (combatPointID == NPCInfo->combatPoint) { return qtrue; } - //Free a combat point if we already have one - if ( NPCInfo->combatPoint != -1 ) - { - NPC_FreeCombatPoint( NPCInfo->combatPoint ); + // Free a combat point if we already have one + if (NPCInfo->combatPoint != -1) { + NPC_FreeCombatPoint(NPCInfo->combatPoint); } - if ( NPC_ReserveCombatPoint( combatPointID ) == qfalse ) + if (NPC_ReserveCombatPoint(combatPointID) == qfalse) return qfalse; NPCInfo->combatPoint = combatPointID; @@ -3120,46 +2584,37 @@ qboolean NPC_SetCombatPoint( int combatPointID ) return qtrue; } -extern qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ); -gentity_t *NPC_SearchForWeapons( void ) -{ +extern qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper); +gentity_t *NPC_SearchForWeapons(void) { gentity_t *found = g_entities, *bestFound = NULL; - float dist, bestDist = Q3_INFINITE; + float dist, bestDist = Q3_INFINITE; int i; -// for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) - for ( i = 0; iinuse ) -// { -// continue; -// } - if(!PInUse(i)) + // for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) + for (i = 0; i < globals.num_entities; i++) { + // if ( !found->inuse ) + // { + // continue; + // } + if (!PInUse(i)) continue; - found=&g_entities[i]; + found = &g_entities[i]; - //FIXME: Also look for ammo_racks that have weapons on them? - if ( found->s.eType != ET_ITEM ) - { + // FIXME: Also look for ammo_racks that have weapons on them? + if (found->s.eType != ET_ITEM) { continue; } - if ( found->item->giType != IT_WEAPON ) - { + if (found->item->giType != IT_WEAPON) { continue; } - if ( found->s.eFlags & EF_NODRAW ) - { + if (found->s.eFlags & EF_NODRAW) { continue; } - if ( CheckItemCanBePickedUpByNPC( found, NPC ) ) - { - if ( gi.inPVS( found->currentOrigin, NPC->currentOrigin ) ) - { - dist = DistanceSquared( found->currentOrigin, NPC->currentOrigin ); - if ( dist < bestDist ) - { - if (NAV::InSameRegion(NPC, found)) - {//can nav to it + if (CheckItemCanBePickedUpByNPC(found, NPC)) { + if (gi.inPVS(found->currentOrigin, NPC->currentOrigin)) { + dist = DistanceSquared(found->currentOrigin, NPC->currentOrigin); + if (dist < bestDist) { + if (NAV::InSameRegion(NPC, found)) { // can nav to it bestDist = dist; bestFound = found; } @@ -3171,91 +2626,73 @@ gentity_t *NPC_SearchForWeapons( void ) return bestFound; } -void NPC_SetPickUpGoal( gentity_t *foundWeap ) -{ +void NPC_SetPickUpGoal(gentity_t *foundWeap) { vec3_t org; - //NPCInfo->goalEntity = foundWeap; - VectorCopy( foundWeap->currentOrigin, org ); - org[2] += 24 - (foundWeap->mins[2]*-1);//adjust the origin so that I am on the ground - NPC_SetMoveGoal( NPC, org, foundWeap->maxs[0]*0.75, qfalse, -1, foundWeap ); + // NPCInfo->goalEntity = foundWeap; + VectorCopy(foundWeap->currentOrigin, org); + org[2] += 24 - (foundWeap->mins[2] * -1); // adjust the origin so that I am on the ground + NPC_SetMoveGoal(NPC, org, foundWeap->maxs[0] * 0.75, qfalse, -1, foundWeap); NPCInfo->tempGoal->waypoint = foundWeap->waypoint; NPCInfo->tempBehavior = BS_DEFAULT; NPCInfo->squadState = SQUAD_TRANSITION; } -extern void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ); -extern qboolean G_CanPickUpWeapons( gentity_t *other ); -void NPC_CheckGetNewWeapon( void ) -{ - if ( NPC->client - && !G_CanPickUpWeapons( NPC ) ) - {//this NPC can't pick up weapons... +extern void Q3_TaskIDComplete(gentity_t *ent, taskID_t taskType); +extern qboolean G_CanPickUpWeapons(gentity_t *other); +void NPC_CheckGetNewWeapon(void) { + if (NPC->client && !G_CanPickUpWeapons(NPC)) { // this NPC can't pick up weapons... return; } - if ( NPC->s.weapon == WP_NONE && NPC->enemy ) - {//if running away because dropped weapon... - if ( NPCInfo->goalEntity - && NPCInfo->goalEntity == NPCInfo->tempGoal - && NPCInfo->goalEntity->enemy - && !NPCInfo->goalEntity->enemy->inuse ) - {//maybe was running at a weapon that was picked up + if (NPC->s.weapon == WP_NONE && NPC->enemy) { // if running away because dropped weapon... + if (NPCInfo->goalEntity && NPCInfo->goalEntity == NPCInfo->tempGoal && NPCInfo->goalEntity->enemy && + !NPCInfo->goalEntity->enemy->inuse) { // maybe was running at a weapon that was picked up NPC_ClearGoal(); - Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); - //NPCInfo->goalEntity = NULL; + Q3_TaskIDComplete(NPC, TID_MOVE_NAV); + // NPCInfo->goalEntity = NULL; } - if ( TIMER_Done( NPC, "panic" ) && NPCInfo->goalEntity == NULL ) - {//need a weapon, any lying around? + if (TIMER_Done(NPC, "panic") && NPCInfo->goalEntity == NULL) { // need a weapon, any lying around? gentity_t *foundWeap = NPC_SearchForWeapons(); - if ( foundWeap ) - { - NPC_SetPickUpGoal( foundWeap ); + if (foundWeap) { + NPC_SetPickUpGoal(foundWeap); } } } } -void NPC_AimAdjust( int change ) -{ - if ( !TIMER_Exists( NPC, "aimDebounce" ) ) - { - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_spskill->integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); +void NPC_AimAdjust(int change) { + if (!TIMER_Exists(NPC, "aimDebounce")) { + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); return; } - if ( TIMER_Done( NPC, "aimDebounce" ) ) - { + if (TIMER_Done(NPC, "aimDebounce")) { NPCInfo->currentAim += change; - if ( NPCInfo->currentAim > NPCInfo->stats.aim ) - {//can never be better than max aim + if (NPCInfo->currentAim > NPCInfo->stats.aim) { // can never be better than max aim NPCInfo->currentAim = NPCInfo->stats.aim; - } - else if ( NPCInfo->currentAim < -30 ) - {//can never be worse than this + } else if (NPCInfo->currentAim < -30) { // can never be worse than this NPCInfo->currentAim = -30; } - //Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); + // Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_spskill->integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); } } -void G_AimSet( gentity_t *self, int aim ) -{ - if ( self->NPC ) - { +void G_AimSet(gentity_t *self, int aim) { + if (self->NPC) { self->NPC->currentAim = aim; - //Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); + // Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - // int debounce = 1000+(3-g_spskill->integer)*500; - // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(self, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); } } diff --git a/code/game/NPC_goal.cpp b/code/game/NPC_goal.cpp index 871eefdf6d..930b6cdb4e 100644 --- a/code/game/NPC_goal.cpp +++ b/code/game/NPC_goal.cpp @@ -20,90 +20,76 @@ along with this program; if not, see . =========================================================================== */ -//b_goal.cpp +// b_goal.cpp #include "b_local.h" #include "Q3_Interface.h" #include "g_navigator.h" -extern qboolean FlyingCreature( gentity_t *ent ); +extern qboolean FlyingCreature(gentity_t *ent); /* SetGoal */ -void SetGoal( gentity_t *goal, float rating ) -{ +void SetGoal(gentity_t *goal, float rating) { NPCInfo->goalEntity = goal; -// NPCInfo->goalEntityNeed = rating; + // NPCInfo->goalEntityNeed = rating; NPCInfo->goalTime = level.time; - if ( goal ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); - } - else - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); + if (goal) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); + } else { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); } } - /* NPC_SetGoal */ -void NPC_SetGoal( gentity_t *goal, float rating ) -{ - if ( goal == NPCInfo->goalEntity ) - { +void NPC_SetGoal(gentity_t *goal, float rating) { + if (goal == NPCInfo->goalEntity) { return; } - if ( !goal ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); + if (!goal) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); return; } - if ( goal->client ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); + if (goal->client) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); return; } - if ( NPCInfo->goalEntity ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); + if (NPCInfo->goalEntity) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); NPCInfo->lastGoalEntity = NPCInfo->goalEntity; -// NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; + // NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; } - SetGoal( goal, rating ); + SetGoal(goal, rating); } - /* NPC_ClearGoal */ -void NPC_ClearGoal( void ) -{ - gentity_t *goal; +void NPC_ClearGoal(void) { + gentity_t *goal; - if ( !NPCInfo->lastGoalEntity ) - { - SetGoal( NULL, 0.0 ); + if (!NPCInfo->lastGoalEntity) { + SetGoal(NULL, 0.0); return; } goal = NPCInfo->lastGoalEntity; NPCInfo->lastGoalEntity = NULL; - if ( goal->inuse && !(goal->s.eFlags & EF_NODRAW) ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); - SetGoal( goal, 0 );//, NPCInfo->lastGoalEntityNeed + if (goal->inuse && !(goal->s.eFlags & EF_NODRAW)) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); + SetGoal(goal, 0); //, NPCInfo->lastGoalEntityNeed return; } - SetGoal( NULL, 0.0 ); + SetGoal(NULL, 0.0); } /* @@ -112,52 +98,48 @@ G_BoundsOverlap ------------------------- */ -qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) -{//NOTE: flush up against counts as overlapping - if(mins1[0]>maxs2[0]) +qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) { // NOTE: flush up against counts as overlapping + if (mins1[0] > maxs2[0]) return qfalse; - if(mins1[1]>maxs2[1]) + if (mins1[1] > maxs2[1]) return qfalse; - if(mins1[2]>maxs2[2]) + if (mins1[2] > maxs2[2]) return qfalse; - if(maxs1[0]goalTime = level.time; -//MCG - Begin + // MCG - Begin NPCInfo->aiFlags &= ~NPCAI_MOVING; ucmd.forwardmove = 0; - //Return that the goal was reached - Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); -//MCG - End + // Return that the goal was reached + Q3_TaskIDComplete(NPC, TID_MOVE_NAV); + // MCG - End } /* ReachedGoal id removed checks against waypoints and is now checking surfaces */ -qboolean ReachedGoal( gentity_t *goal ) -{ +qboolean ReachedGoal(gentity_t *goal) { - if ( NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL ) - { + if (NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL) { NPCInfo->aiFlags &= ~NPCAI_TOUCHED_GOAL; return qtrue; } @@ -174,32 +156,27 @@ In fact, doesn't seem to be any waypoint info on entities at all any more? MCG - Since goal is ALWAYS goalEntity, took out a lot of sending goal entity pointers around for no reason */ -gentity_t *UpdateGoal( void ) -{ - //FIXME: CREED should look at this +gentity_t *UpdateGoal(void) { + // FIXME: CREED should look at this // this func doesn't seem to be working correctly for the sand creature - gentity_t *goal; + gentity_t *goal; - if ( !NPCInfo->goalEntity ) - { + if (!NPCInfo->goalEntity) { return NULL; } - if ( !NPCInfo->goalEntity->inuse ) - {//Somehow freed it, but didn't clear it + if (!NPCInfo->goalEntity->inuse) { // Somehow freed it, but didn't clear it NPC_ClearGoal(); return NULL; } goal = NPCInfo->goalEntity; - if ( ReachedGoal( goal ) ) - { + if (ReachedGoal(goal)) { NPC_ReachedGoal(); - goal = NULL;//so they don't keep trying to move to it - }//else if fail, need to tell script so? + goal = NULL; // so they don't keep trying to move to it + } // else if fail, need to tell script so? return goal; } - diff --git a/code/game/NPC_misc.cpp b/code/game/NPC_misc.cpp index 344b13966f..b107b1802d 100644 --- a/code/game/NPC_misc.cpp +++ b/code/game/NPC_misc.cpp @@ -29,11 +29,10 @@ along with this program; if not, see . /* Debug_Printf */ -void Debug_Printf (cvar_t *cv, int debugLevel, char *fmt, ...) -{ - char *color; - va_list argptr; - char msg[1024]; +void Debug_Printf(cvar_t *cv, int debugLevel, char *fmt, ...) { + char *color; + va_list argptr; + char msg[1024]; if (cv->value < debugLevel) return; @@ -49,30 +48,26 @@ void Debug_Printf (cvar_t *cv, int debugLevel, char *fmt, ...) else color = S_COLOR_RED; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); gi.Printf("%s%5i:%s", color, level.time, msg); } - /* Debug_NPCPrintf */ -void Debug_NPCPrintf (gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt, ...) -{ - int color; - va_list argptr; - char msg[1024]; +void Debug_NPCPrintf(gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt, ...) { + int color; + va_list argptr; + char msg[1024]; - if (cv->value < debugLevel) - { + if (cv->value < debugLevel) { return; } - if ( debugNPCName->string[0] && Q_stricmp( debugNPCName->string, printNPC->targetname) != 0 ) - { + if (debugNPCName->string[0] && Q_stricmp(debugNPCName->string, printNPC->targetname) != 0) { return; } @@ -87,9 +82,9 @@ void Debug_NPCPrintf (gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt else color = COLOR_RED; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - gi.Printf ("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); + gi.Printf("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); } diff --git a/code/game/NPC_move.cpp b/code/game/NPC_move.cpp index 3f38d3695d..93e01d5af6 100644 --- a/code/game/NPC_move.cpp +++ b/code/game/NPC_move.cpp @@ -29,91 +29,78 @@ along with this program; if not, see . #include "anims.h" #include "g_navigator.h" -extern qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal ); -extern qboolean NAV_MoveDirSafe( gentity_t *self, usercmd_t *cmd, float distScale = 1.0f ); +extern qboolean NPC_ClearPathToGoal(vec3_t dir, gentity_t *goal); +extern qboolean NAV_MoveDirSafe(gentity_t *self, usercmd_t *cmd, float distScale = 1.0f); qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2); -extern int GetTime ( int lastTime ); +extern int GetTime(int lastTime); -navInfo_t frameNavInfo; -extern qboolean FlyingCreature( gentity_t *ent ); -extern qboolean PM_InKnockDown( playerState_t *ps ); - -extern cvar_t *g_navSafetyChecks; - -extern qboolean Boba_Flying( gentity_t *self ); -extern qboolean PM_InRoll( playerState_t *ps ); - -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f +navInfo_t frameNavInfo; +extern qboolean FlyingCreature(gentity_t *ent); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern cvar_t *g_navSafetyChecks; +extern qboolean Boba_Flying(gentity_t *self); +extern qboolean PM_InRoll(playerState_t *ps); +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f static qboolean NPC_TryJump(); - - - -static qboolean NPC_Jump( vec3_t dest, int goalEntNum ) -{//FIXME: if land on enemy, knock him down & jump off again - float targetDist, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, +static qboolean NPC_Jump(vec3_t dest, int goalEntNum) { // FIXME: if land on enemy, knock him down & jump off again + float targetDist, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, float originalShotSpeed, shotSpeed, speedStep = 50.0f, minShotSpeed = 30.0f, maxShotSpeed = 500.0f; qboolean belowBlocked = qfalse, aboveBlocked = qfalse; - vec3_t targetDir, shotVel, failCase; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, timeStep = 250, hitCount = 0, aboveTries = 0, belowTries = 0, maxHits = 10; - vec3_t lastPos, testPos, bottom; - - VectorSubtract( dest, NPC->currentOrigin, targetDir ); - targetDist = VectorNormalize( targetDir ); - //make our shotSpeed reliant on the distance - originalShotSpeed = targetDist;//DistanceHorizontal( dest, NPC->currentOrigin )/2.0f; - if ( originalShotSpeed > maxShotSpeed ) - { + vec3_t targetDir, shotVel, failCase; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, timeStep = 250, hitCount = 0, aboveTries = 0, belowTries = 0, maxHits = 10; + vec3_t lastPos, testPos, bottom; + + VectorSubtract(dest, NPC->currentOrigin, targetDir); + targetDist = VectorNormalize(targetDir); + // make our shotSpeed reliant on the distance + originalShotSpeed = targetDist; // DistanceHorizontal( dest, NPC->currentOrigin )/2.0f; + if (originalShotSpeed > maxShotSpeed) { originalShotSpeed = maxShotSpeed; - } - else if ( originalShotSpeed < minShotSpeed ) - { + } else if (originalShotSpeed < minShotSpeed) { originalShotSpeed = minShotSpeed; } shotSpeed = originalShotSpeed; - while ( hitCount < maxHits ) - { - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + while (hitCount < maxHits) { + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * NPC->client->ps.gravity; - if ( !hitCount ) - {//save the first one as the worst case scenario - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first one as the worst case scenario + VectorCopy(shotVel, failCase); } - if ( 1 )//tracePath ) - {//do a rough trace of the path + if (1) // tracePath ) + { // do a rough trace of the path blocked = qfalse; - VectorCopy( NPC->currentOrigin, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(NPC->currentOrigin, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( NPC->currentOrigin, lastPos ); - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); + VectorCopy(NPC->currentOrigin, lastPos); + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace + // just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - //FUCK IT, always check for do not enter... - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + // FUCK IT, always check for do not enter... + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, (EG2_Collision)0, 0); /* if ( testPos[2] < lastPos[2] && elapsedTime < floor( travelTime ) ) @@ -126,22 +113,17 @@ static qboolean NPC_Jump( vec3_t dest, int goalEntNum ) } */ - if ( trace.allsolid || trace.startsolid ) - {//started in solid - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( lastPos, trace.endpos, EDGE_RED_TWOSECOND ); + if (trace.allsolid || trace.startsolid) { // started in solid + if (NAVDEBUG_showCollision) { + CG_DrawEdge(lastPos, trace.endpos, EDGE_RED_TWOSECOND); } - return qfalse;//you're hosed, dude + return qfalse; // you're hosed, dude } - if ( trace.fraction < 1.0f ) - {//hit something - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( lastPos, trace.endpos, EDGE_RED_TWOSECOND ); // TryJump + if (trace.fraction < 1.0f) { // hit something + if (NAVDEBUG_showCollision) { + CG_DrawEdge(lastPos, trace.endpos, EDGE_RED_TWOSECOND); // TryJump } - if ( trace.entityNum == goalEntNum ) - {//hit the enemy, that's bad! + if (trace.entityNum == goalEntNum) { // hit the enemy, that's bad! blocked = qtrue; /* if ( g_entities[goalEntNum].client && g_entities[goalEntNum].client->ps.groundEntityNum == ENTITYNUM_NONE ) @@ -154,271 +136,203 @@ static qboolean NPC_Jump( vec3_t dest, int goalEntNum ) } */ break; - } - else - { - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + } else { + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush blocked = qtrue; break; } - if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, dest ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, dest) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, dest ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, dest); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; break; } } - } - else - { - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( lastPos, testPos, EDGE_WHITE_TWOSECOND ); // TryJump + } else { + if (NAVDEBUG_showCollision) { + CG_DrawEdge(lastPos, testPos, EDGE_WHITE_TWOSECOND); // TryJump } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear - if ( trace.fraction >= 1.0f ) - {//hmm, make sure we'll land on the ground... - //FIXME: do we care how far below ourselves or our dest we'll land? - VectorCopy( trace.endpos, bottom ); + if (elapsedTime == floor(travelTime)) { // reached end, all clear + if (trace.fraction >= 1.0f) { // hmm, make sure we'll land on the ground... + // FIXME: do we care how far below ourselves or our dest we'll land? + VectorCopy(trace.endpos, bottom); bottom[2] -= 128; - gi.trace( &trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction >= 1.0f ) - {//would fall too far + gi.trace(&trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (trace.fraction >= 1.0f) { // would fall too far blocked = qtrue; } } break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - //alternate back and forth between trying an arc slightly above or below the ideal - if ( (hitCount%2) && !belowBlocked ) - {//odd + // alternate back and forth between trying an arc slightly above or below the ideal + if ((hitCount % 2) && !belowBlocked) { // odd belowTries++; - shotSpeed = originalShotSpeed - (belowTries*speedStep); - } - else if ( !aboveBlocked ) - {//even + shotSpeed = originalShotSpeed - (belowTries * speedStep); + } else if (!aboveBlocked) { // even aboveTries++; - shotSpeed = originalShotSpeed + (aboveTries*speedStep); - } - else - {//can't go any higher or lower + shotSpeed = originalShotSpeed + (aboveTries * speedStep); + } else { // can't go any higher or lower hitCount = maxHits; break; } - if ( shotSpeed > maxShotSpeed ) - { + if (shotSpeed > maxShotSpeed) { shotSpeed = maxShotSpeed; aboveBlocked = qtrue; - } - else if ( shotSpeed < minShotSpeed ) - { + } else if (shotSpeed < minShotSpeed) { shotSpeed = minShotSpeed; belowBlocked = qtrue; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) return qfalse; - //NOTE: or try failcase? - //VectorCopy( failCase, NPC->client->ps.velocity ); - //return qtrue; + // NOTE: or try failcase? + // VectorCopy( failCase, NPC->client->ps.velocity ); + // return qtrue; } - VectorCopy( shotVel, NPC->client->ps.velocity ); + VectorCopy(shotVel, NPC->client->ps.velocity); return qtrue; } - - - - - #define NPC_JUMP_PREP_BACKUP_DIST 34.0f -trace_t mJumpTrace; - - - -qboolean NPC_CanTryJump() -{ - if (!(NPCInfo->scriptFlags&SCF_NAV_CAN_JUMP) || // Can't Jump - (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) || // If Can't Jump At All - (level.timejumpBackupTime) || // If Backing Up, Don't Try The Jump Again - (level.timejumpNextCheckTime) || // Don't Even Try To Jump Again For This Amount Of Time - (NPCInfo->jumpTime) || // Don't Jump If Already Going - (PM_InKnockDown(&NPC->client->ps)) || // Don't Jump If In Knockdown - (PM_InRoll(&NPC->client->ps)) || // ... Or Roll - (NPC->client->ps.groundEntityNum==ENTITYNUM_NONE) // ... Or In The Air - ) - { +trace_t mJumpTrace; + +qboolean NPC_CanTryJump() { + if (!(NPCInfo->scriptFlags & SCF_NAV_CAN_JUMP) || // Can't Jump + (NPCInfo->scriptFlags & SCF_NO_ACROBATICS) || // If Can't Jump At All + (level.time < NPCInfo->jumpBackupTime) || // If Backing Up, Don't Try The Jump Again + (level.time < NPCInfo->jumpNextCheckTime) || // Don't Even Try To Jump Again For This Amount Of Time + (NPCInfo->jumpTime) || // Don't Jump If Already Going + (PM_InKnockDown(&NPC->client->ps)) || // Don't Jump If In Knockdown + (PM_InRoll(&NPC->client->ps)) || // ... Or Roll + (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) // ... Or In The Air + ) { return qfalse; } return qtrue; } -qboolean NPC_TryJump(const vec3_t& pos, float max_xy_dist, float max_z_diff) -{ - if (NPC_CanTryJump()) - { - NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 2000); +qboolean NPC_TryJump(const vec3_t &pos, float max_xy_dist, float max_z_diff) { + if (NPC_CanTryJump()) { + NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 2000); VectorCopy(pos, NPCInfo->jumpDest); // Can't Try To Jump At A Point In The Air //----------------------------------------- { - vec3_t groundTest; + vec3_t groundTest; VectorCopy(pos, groundTest); - groundTest[2] += (NPC->mins[2]*3); - gi.trace(&mJumpTrace, NPCInfo->jumpDest, vec3_origin, vec3_origin, groundTest, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0 ); - if (mJumpTrace.fraction >= 1.0f) - { - return qfalse; //no ground = no jump + groundTest[2] += (NPC->mins[2] * 3); + gi.trace(&mJumpTrace, NPCInfo->jumpDest, vec3_origin, vec3_origin, groundTest, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); + if (mJumpTrace.fraction >= 1.0f) { + return qfalse; // no ground = no jump } } - NPCInfo->jumpTarget = 0; - NPCInfo->jumpMaxXYDist = (max_xy_dist)?(max_xy_dist):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?1200:750); - NPCInfo->jumpMazZDist = (max_z_diff)?(max_z_diff):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?-1000:-450); - NPCInfo->jumpTime = 0; - NPCInfo->jumpBackupTime = 0; + NPCInfo->jumpTarget = 0; + NPCInfo->jumpMaxXYDist = (max_xy_dist) ? (max_xy_dist) : ((NPC->client->NPC_class == CLASS_ROCKETTROOPER) ? 1200 : 750); + NPCInfo->jumpMazZDist = (max_z_diff) ? (max_z_diff) : ((NPC->client->NPC_class == CLASS_ROCKETTROOPER) ? -1000 : -450); + NPCInfo->jumpTime = 0; + NPCInfo->jumpBackupTime = 0; return NPC_TryJump(); } return qfalse; } -qboolean NPC_TryJump(gentity_t *goal, float max_xy_dist, float max_z_diff) -{ - if (NPC_CanTryJump()) - { - NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 3000); +qboolean NPC_TryJump(gentity_t *goal, float max_xy_dist, float max_z_diff) { + if (NPC_CanTryJump()) { + NPCInfo->jumpNextCheckTime = level.time + Q_irand(1000, 3000); // Can't Jump At Targets In The Air //--------------------------------- - if (goal->client && goal->client->ps.groundEntityNum==ENTITYNUM_NONE) - { + if (goal->client && goal->client->ps.groundEntityNum == ENTITYNUM_NONE) { return qfalse; } VectorCopy(goal->currentOrigin, NPCInfo->jumpDest); - NPCInfo->jumpTarget = goal; - NPCInfo->jumpMaxXYDist = (max_xy_dist)?(max_xy_dist):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?1200:750); - NPCInfo->jumpMazZDist = (max_z_diff)?(max_z_diff):((NPC->client->NPC_class==CLASS_ROCKETTROOPER)?-1000:-400); - NPCInfo->jumpTime = 0; - NPCInfo->jumpBackupTime = 0; + NPCInfo->jumpTarget = goal; + NPCInfo->jumpMaxXYDist = (max_xy_dist) ? (max_xy_dist) : ((NPC->client->NPC_class == CLASS_ROCKETTROOPER) ? 1200 : 750); + NPCInfo->jumpMazZDist = (max_z_diff) ? (max_z_diff) : ((NPC->client->NPC_class == CLASS_ROCKETTROOPER) ? -1000 : -400); + NPCInfo->jumpTime = 0; + NPCInfo->jumpBackupTime = 0; return NPC_TryJump(); } return qfalse; } -void NPC_JumpAnimation() -{ - int jumpAnim = BOTH_JUMP1; +void NPC_JumpAnimation() { + int jumpAnim = BOTH_JUMP1; - if ( NPC->client->NPC_class == CLASS_BOBAFETT - || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) - || NPC->client->NPC_class == CLASS_ROCKETTROOPER - ||( NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + if (NPC->client->NPC_class == CLASS_BOBAFETT || (NPC->client->NPC_class == CLASS_REBORN && NPC->s.weapon != WP_SABER) || + NPC->client->NPC_class == CLASS_ROCKETTROOPER || (NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG)) { // can't do acrobatics jumpAnim = BOTH_FORCEJUMP1; - } - else if (NPC->client->NPC_class != CLASS_HOWLER) - { - if ( NPC->client->NPC_class == CLASS_ALORA && Q_irand( 0, 3 ) ) - { - jumpAnim = Q_irand( BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3 ); - } - else - { + } else if (NPC->client->NPC_class != CLASS_HOWLER) { + if (NPC->client->NPC_class == CLASS_ALORA && Q_irand(0, 3)) { + jumpAnim = Q_irand(BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3); + } else { jumpAnim = BOTH_FLIP_F; } } - NPC_SetAnim( NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } -extern void JET_FlyStart(gentity_t* actor); +extern void JET_FlyStart(gentity_t *actor); -void NPC_JumpSound() -{ - if ( NPC->client->NPC_class == CLASS_HOWLER ) - { - //FIXME: can I delay the actual jump so that it matches the anim...? - } - else if ( NPC->client->NPC_class == CLASS_BOBAFETT - || NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - { +void NPC_JumpSound() { + if (NPC->client->NPC_class == CLASS_HOWLER) { + // FIXME: can I delay the actual jump so that it matches the anim...? + } else if (NPC->client->NPC_class == CLASS_BOBAFETT || NPC->client->NPC_class == CLASS_ROCKETTROOPER) { // does this really need to be here? JET_FlyStart(NPC); - } - else - { - G_SoundOnEnt( NPC, CHAN_BODY, "sound/weapons/force/jump.wav" ); + } else { + G_SoundOnEnt(NPC, CHAN_BODY, "sound/weapons/force/jump.wav"); } } -qboolean NPC_TryJump() -{ - vec3_t targetDirection; - float targetDistanceXY; - float targetDistanceZ; +qboolean NPC_TryJump() { + vec3_t targetDirection; + float targetDistanceXY; + float targetDistanceZ; // Get The Direction And Distances To The Target //----------------------------------------------- VectorSubtract(NPCInfo->jumpDest, NPC->currentOrigin, targetDirection); - targetDirection[2] = 0.0f; - targetDistanceXY = VectorNormalize(targetDirection); - targetDistanceZ = NPCInfo->jumpDest[2] - NPC->currentOrigin[2]; + targetDirection[2] = 0.0f; + targetDistanceXY = VectorNormalize(targetDirection); + targetDistanceZ = NPCInfo->jumpDest[2] - NPC->currentOrigin[2]; - if ((targetDistanceXY>NPCInfo->jumpMaxXYDist) || - (targetDistanceZjumpMazZDist)) - { + if ((targetDistanceXY > NPCInfo->jumpMaxXYDist) || (targetDistanceZ < NPCInfo->jumpMazZDist)) { return qfalse; } - // Test To See If There Is A Wall Directly In Front Of Actor, If So, Backup Some //------------------------------------------------------------------------------- - if (TIMER_Done(NPC, "jumpBackupDebounce")) - { - vec3_t actorProjectedTowardTarget; + if (TIMER_Done(NPC, "jumpBackupDebounce")) { + vec3_t actorProjectedTowardTarget; VectorMA(NPC->currentOrigin, NPC_JUMP_PREP_BACKUP_DIST, targetDirection, actorProjectedTowardTarget); gi.trace(&mJumpTrace, NPC->currentOrigin, vec3_origin, vec3_origin, actorProjectedTowardTarget, NPC->s.number, NPC->clipmask, (EG2_Collision)0, 0); - if ((mJumpTrace.fraction < 1.0f) || - (mJumpTrace.allsolid) || - (mJumpTrace.startsolid)) - { - if (NAVDEBUG_showCollision) - { - CG_DrawEdge(NPC->currentOrigin, actorProjectedTowardTarget, EDGE_RED_TWOSECOND); // TryJump + if ((mJumpTrace.fraction < 1.0f) || (mJumpTrace.allsolid) || (mJumpTrace.startsolid)) { + if (NAVDEBUG_showCollision) { + CG_DrawEdge(NPC->currentOrigin, actorProjectedTowardTarget, EDGE_RED_TWOSECOND); // TryJump } // TODO: We may want to test to see if it is safe to back up here? @@ -428,62 +342,53 @@ qboolean NPC_TryJump() } } + // bool Wounded = (NPC->health < 150); + // bool OnLowerLedge = ((targetDistanceZ<-80.0f) && (targetDistanceZ>-200.0f)); + // bool WithinNormalJumpRange = ((targetDistanceZ<32.0f) && (targetDistanceXY<200.0f)); + bool WithinForceJumpRange = ((fabsf(targetDistanceZ) > 0) || (targetDistanceXY > 128)); -// bool Wounded = (NPC->health < 150); -// bool OnLowerLedge = ((targetDistanceZ<-80.0f) && (targetDistanceZ>-200.0f)); -// bool WithinNormalJumpRange = ((targetDistanceZ<32.0f) && (targetDistanceXY<200.0f)); - bool WithinForceJumpRange = ((fabsf(targetDistanceZ)>0) || (targetDistanceXY>128)); - -/* if (Wounded && OnLowerLedge) - { - ucmd.forwardmove = 127; - VectorClear(NPC->client->ps.moveDir); - TIMER_Set(NPC, "duck", -level.time); - return qtrue; - } + /* if (Wounded && OnLowerLedge) + { + ucmd.forwardmove = 127; + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "duck", -level.time); + return qtrue; + } - if (WithinNormalJumpRange) - { - ucmd.upmove = 127; - ucmd.forwardmove = 127; - VectorClear(NPC->client->ps.moveDir); - TIMER_Set(NPC, "duck", -level.time); - return qtrue; - } -*/ + if (WithinNormalJumpRange) + { + ucmd.upmove = 127; + ucmd.forwardmove = 127; + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "duck", -level.time); + return qtrue; + } + */ - if (!WithinForceJumpRange) - { + if (!WithinForceJumpRange) { return qfalse; } - - // If There Is Any Chance That This Jump Will Land On An Enemy, Try 8 Different Traces Around The Target //------------------------------------------------------------------------------------------------------- - if (NPCInfo->jumpTarget) - { - float minSafeRadius = (NPC->maxs[0]*1.5f) + (NPCInfo->jumpTarget->maxs[0]*1.5f); - float minSafeRadiusSq = (minSafeRadius * minSafeRadius); + if (NPCInfo->jumpTarget) { + float minSafeRadius = (NPC->maxs[0] * 1.5f) + (NPCInfo->jumpTarget->maxs[0] * 1.5f); + float minSafeRadiusSq = (minSafeRadius * minSafeRadius); - if (DistanceSquared(NPCInfo->jumpDest, NPCInfo->jumpTarget->currentOrigin)jumpDest, NPCInfo->jumpTarget->currentOrigin) < minSafeRadiusSq) { + vec3_t startPos; + vec3_t floorPos; VectorCopy(NPCInfo->jumpDest, startPos); - floorPos[2] = NPCInfo->jumpDest[2] + (NPC->mins[2]-32); + floorPos[2] = NPCInfo->jumpDest[2] + (NPC->mins[2] - 32); - for (int sideTryCount=0; sideTryCount<8; sideTryCount++) - { + for (int sideTryCount = 0; sideTryCount < 8; sideTryCount++) { NPCInfo->jumpSide++; - if ( NPCInfo->jumpSide > 7 ) - { + if (NPCInfo->jumpSide > 7) { NPCInfo->jumpSide = 0; } - switch ( NPCInfo->jumpSide ) - { + switch (NPCInfo->jumpSide) { case 0: NPCInfo->jumpDest[0] = startPos[0] + minSafeRadius; NPCInfo->jumpDest[1] = startPos[1]; @@ -514,33 +419,27 @@ qboolean NPC_TryJump() break; case 7: NPCInfo->jumpDest[0] = startPos[0] + minSafeRadius; - NPCInfo->jumpDest[1] = startPos[1] -=minSafeRadius; + NPCInfo->jumpDest[1] = startPos[1] -= minSafeRadius; break; } floorPos[0] = NPCInfo->jumpDest[0]; floorPos[1] = NPCInfo->jumpDest[1]; - gi.trace(&mJumpTrace, NPCInfo->jumpDest, NPC->mins, NPC->maxs, floorPos, (NPCInfo->jumpTarget)?(NPCInfo->jumpTarget->s.number):(NPC->s.number), (NPC->clipmask|CONTENTS_BOTCLIP), (EG2_Collision)0, 0); - if ((mJumpTrace.fraction<1.0f) && - (!mJumpTrace.allsolid) && - (!mJumpTrace.startsolid)) - { + gi.trace(&mJumpTrace, NPCInfo->jumpDest, NPC->mins, NPC->maxs, floorPos, + (NPCInfo->jumpTarget) ? (NPCInfo->jumpTarget->s.number) : (NPC->s.number), (NPC->clipmask | CONTENTS_BOTCLIP), (EG2_Collision)0, 0); + if ((mJumpTrace.fraction < 1.0f) && (!mJumpTrace.allsolid) && (!mJumpTrace.startsolid)) { break; } - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( NPCInfo->jumpDest, floorPos, EDGE_RED_TWOSECOND ); + if (NAVDEBUG_showCollision) { + CG_DrawEdge(NPCInfo->jumpDest, floorPos, EDGE_RED_TWOSECOND); } } // If All Traces Failed, Just Try Going Right Back At The Target Location //------------------------------------------------------------------------ - if ((mJumpTrace.fraction>=1.0f) || - (mJumpTrace.allsolid) || - (mJumpTrace.startsolid)) - { + if ((mJumpTrace.fraction >= 1.0f) || (mJumpTrace.allsolid) || (mJumpTrace.startsolid)) { VectorCopy(startPos, NPCInfo->jumpDest); } } @@ -548,19 +447,18 @@ qboolean NPC_TryJump() // Now, Actually Try The Jump To The Dest Target //----------------------------------------------- - if (NPC_Jump(NPCInfo->jumpDest, (NPCInfo->jumpTarget)?(NPCInfo->jumpTarget->s.number):(NPC->s.number))) - { + if (NPC_Jump(NPCInfo->jumpDest, (NPCInfo->jumpTarget) ? (NPCInfo->jumpTarget->s.number) : (NPC->s.number))) { // We Made IT! //------------- NPC_JumpAnimation(); NPC_JumpSound(); - NPC->client->ps.forceJumpZStart = NPC->currentOrigin[2]; - NPC->client->ps.pm_flags |= PMF_JUMPING; - NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; - NPC->client->ps.forcePowersActive |= ( 1 << FP_LEVITATION ); - ucmd.forwardmove = 0; - NPCInfo->jumpTime = 1; + NPC->client->ps.forceJumpZStart = NPC->currentOrigin[2]; + NPC->client->ps.pm_flags |= PMF_JUMPING; + NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; + NPC->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + ucmd.forwardmove = 0; + NPCInfo->jumpTime = 1; VectorClear(NPC->client->ps.moveDir); TIMER_Set(NPC, "duck", -level.time); @@ -570,42 +468,32 @@ qboolean NPC_TryJump() return qfalse; } -qboolean NPC_Jumping() -{ - if ( NPCInfo->jumpTime ) - { - if ( !(NPC->client->ps.pm_flags & PMF_JUMPING )//forceJumpZStart ) - && !(NPC->client->ps.pm_flags&PMF_TRIGGER_PUSHED)) - {//landed +qboolean NPC_Jumping() { + if (NPCInfo->jumpTime) { + if (!(NPC->client->ps.pm_flags & PMF_JUMPING) // forceJumpZStart ) + && !(NPC->client->ps.pm_flags & PMF_TRIGGER_PUSHED)) { // landed NPCInfo->jumpTime = 0; - } - else - { - // if (NPCInfo->jumpTarget) - // { - // NPC_FaceEntity(NPCInfo->jumpTarget, qtrue); - // } - // else - { - NPC_FacePosition(NPCInfo->jumpDest, qtrue); - } + } else { + // if (NPCInfo->jumpTarget) + // { + // NPC_FaceEntity(NPCInfo->jumpTarget, qtrue); + // } + // else + { NPC_FacePosition(NPCInfo->jumpDest, qtrue); } return qtrue; } } return qfalse; } -qboolean NPC_JumpBackingUp() -{ - if (NPCInfo->jumpBackupTime) - { - if (level.timejumpBackupTime) - { +qboolean NPC_JumpBackingUp() { + if (NPCInfo->jumpBackupTime) { + if (level.time < NPCInfo->jumpBackupTime) { STEER::Activate(NPC); STEER::Flee(NPC, NPCInfo->jumpDest); STEER::DeActivate(NPC, &ucmd); NPC_FacePosition(NPCInfo->jumpDest, qtrue); - NPC_UpdateAngles( qfalse, qtrue ); + NPC_UpdateAngles(qfalse, qtrue); return qtrue; } @@ -615,27 +503,20 @@ qboolean NPC_JumpBackingUp() return qfalse; } - - - /* ------------------------- NPC_CheckCombatMove ------------------------- */ -inline qboolean NPC_CheckCombatMove( void ) -{ - //return NPCInfo->combatMove; - if ( ( NPCInfo->goalEntity && NPC->enemy && NPCInfo->goalEntity == NPC->enemy ) || ( NPCInfo->combatMove ) ) - { +inline qboolean NPC_CheckCombatMove(void) { + // return NPCInfo->combatMove; + if ((NPCInfo->goalEntity && NPC->enemy && NPCInfo->goalEntity == NPC->enemy) || (NPCInfo->combatMove)) { return qtrue; } - if ( NPCInfo->goalEntity && NPCInfo->watchTarget ) - { - if ( NPCInfo->goalEntity != NPCInfo->watchTarget ) - { + if (NPCInfo->goalEntity && NPCInfo->watchTarget) { + if (NPCInfo->goalEntity != NPCInfo->watchTarget) { return qtrue; } } @@ -649,19 +530,17 @@ NPC_LadderMove ------------------------- */ -static void NPC_LadderMove( vec3_t dir ) -{ - //FIXME: this doesn't guarantee we're facing ladder - //ALSO: Need to be able to get off at top - //ALSO: Need to play an anim - //ALSO: Need transitionary anims? +static void NPC_LadderMove(vec3_t dir) { + // FIXME: this doesn't guarantee we're facing ladder + // ALSO: Need to be able to get off at top + // ALSO: Need to play an anim + // ALSO: Need transitionary anims? - if ( ( dir[2] > 0 ) || ( dir[2] < 0 && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) ) - { - //Set our movement direction + if ((dir[2] > 0) || (dir[2] < 0 && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE)) { + // Set our movement direction ucmd.upmove = (dir[2] > 0) ? 127 : -127; - //Don't move around on XY + // Don't move around on XY ucmd.forwardmove = ucmd.rightmove = 0; } } @@ -672,19 +551,18 @@ NPC_GetMoveInformation ------------------------- */ -inline qboolean NPC_GetMoveInformation( vec3_t dir, float *distance ) -{ - //NOTENOTE: Use path stacks! +inline qboolean NPC_GetMoveInformation(vec3_t dir, float *distance) { + // NOTENOTE: Use path stacks! - //Make sure we have somewhere to go - if ( NPCInfo->goalEntity == NULL ) + // Make sure we have somewhere to go + if (NPCInfo->goalEntity == NULL) return qfalse; - //Get our move info - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); - *distance = VectorNormalize( dir ); + // Get our move info + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); + *distance = VectorNormalize(dir); - VectorCopy( NPCInfo->goalEntity->currentOrigin, NPCInfo->blockedTargetPosition ); + VectorCopy(NPCInfo->goalEntity->currentOrigin, NPCInfo->blockedTargetPosition); return qtrue; } @@ -695,40 +573,31 @@ NAV_GetLastMove ------------------------- */ -void NAV_GetLastMove( navInfo_t &info ) -{ - info = frameNavInfo; -} - +void NAV_GetLastMove(navInfo_t &info) { info = frameNavInfo; } -void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ) -{ - vec3_t forward, right; +void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir) { + vec3_t forward, right; - AngleVectors( self->currentAngles, forward, right, NULL ); + AngleVectors(self->currentAngles, forward, right, NULL); dir[2] = 0; - VectorNormalize( dir ); - //NPCs cheat and store this directly because converting movement into a ucmd loses precision - VectorCopy( dir, self->client->ps.moveDir ); - - float fDot = DotProduct( forward, dir ) * 127.0f; - float rDot = DotProduct( right, dir ) * 127.0f; - //Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte - if ( fDot > 127.0f ) - { + VectorNormalize(dir); + // NPCs cheat and store this directly because converting movement into a ucmd loses precision + VectorCopy(dir, self->client->ps.moveDir); + + float fDot = DotProduct(forward, dir) * 127.0f; + float rDot = DotProduct(right, dir) * 127.0f; + // Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte + if (fDot > 127.0f) { fDot = 127.0f; } - if ( fDot < -127.0f ) - { + if (fDot < -127.0f) { fDot = -127.0f; } - if ( rDot > 127.0f ) - { + if (rDot > 127.0f) { rDot = 127.0f; } - if ( rDot < -127.0f ) - { + if (rDot < -127.0f) { rDot = -127.0f; } cmd->forwardmove = floor(fDot); @@ -756,71 +625,62 @@ NPC_MoveToGoal ------------------------- */ -#if AI_TIMERS +#if AI_TIMERS extern int navTime; -#endif// AI_TIMERS -qboolean NPC_MoveToGoal( qboolean tryStraight ) //FIXME: tryStraight not even used! Stop passing it +#endif // AI_TIMERS +qboolean NPC_MoveToGoal(qboolean tryStraight) // FIXME: tryStraight not even used! Stop passing it { -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS - if ( PM_InKnockDown( &NPC->client->ps ) || ( ( NPC->client->ps.legsAnim >= BOTH_PAIN1 ) && ( NPC->client->ps.legsAnim <= BOTH_PAIN18 ) && NPC->client->ps.legsAnimTimer > 0 ) ) - {//If taking full body pain, don't move + if (PM_InKnockDown(&NPC->client->ps) || ((NPC->client->ps.legsAnim >= BOTH_PAIN1) && (NPC->client->ps.legsAnim <= BOTH_PAIN18) && + NPC->client->ps.legsAnimTimer > 0)) { // If taking full body pain, don't move return qtrue; } - if( NPC->s.eFlags & EF_LOCKED_TO_WEAPON ) - {//If in an emplaced gun, never try to navigate! + if (NPC->s.eFlags & EF_LOCKED_TO_WEAPON) { // If in an emplaced gun, never try to navigate! return qtrue; } - if( NPC->s.eFlags & EF_HELD_BY_RANCOR ) - {//If in a rancor's hand, never try to navigate! + if (NPC->s.eFlags & EF_HELD_BY_RANCOR) { // If in a rancor's hand, never try to navigate! return qtrue; } - if( NPC->s.eFlags & EF_HELD_BY_WAMPA ) - {//If in a wampa's hand, never try to navigate! + if (NPC->s.eFlags & EF_HELD_BY_WAMPA) { // If in a wampa's hand, never try to navigate! return qtrue; } - if( NPC->s.eFlags & EF_HELD_BY_SAND_CREATURE ) - {//If in a worm's mouth, never try to navigate! + if (NPC->s.eFlags & EF_HELD_BY_SAND_CREATURE) { // If in a worm's mouth, never try to navigate! return qtrue; } - if ( NPC->watertype & CONTENTS_LADDER ) - {//Do we still want to do this? - vec3_t dir; - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); - VectorNormalize( dir ); - NPC_LadderMove( dir ); + if (NPC->watertype & CONTENTS_LADDER) { // Do we still want to do this? + vec3_t dir; + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); + VectorNormalize(dir); + NPC_LadderMove(dir); } - - bool moveSuccess = true; + bool moveSuccess = true; STEER::Activate(NPC); { // Attempt To Steer Directly To Our Goal //--------------------------------------- - moveSuccess = STEER::GoTo(NPC, NPCInfo->goalEntity, NPCInfo->goalRadius); + moveSuccess = STEER::GoTo(NPC, NPCInfo->goalEntity, NPCInfo->goalRadius); // Perhaps Not Close Enough? Try To Use The Navigation Grid //----------------------------------------------------------- - if (!moveSuccess) - { + if (!moveSuccess) { moveSuccess = NAV::GoTo(NPC, NPCInfo->goalEntity); - if (!moveSuccess) - { + if (!moveSuccess) { STEER::Stop(NPC); } } } STEER::DeActivate(NPC, &ucmd); - - #if AI_TIMERS - navTime += GetTime( startTime ); - #endif// AI_TIMERS +#if AI_TIMERS + navTime += GetTime(startTime); +#endif // AI_TIMERS return (qboolean)moveSuccess; } @@ -831,32 +691,28 @@ void NPC_SlideMoveToGoal( void ) Now assumes goal is goalEntity, if want to use tempGoal, you set that before calling the func ------------------------- */ -qboolean NPC_SlideMoveToGoal( void ) -{ - float saveYaw = NPC->client->ps.viewangles[YAW]; +qboolean NPC_SlideMoveToGoal(void) { + float saveYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->combatMove = qtrue; - qboolean ret = NPC_MoveToGoal( qtrue ); + qboolean ret = NPC_MoveToGoal(qtrue); - NPCInfo->desiredYaw = saveYaw; + NPCInfo->desiredYaw = saveYaw; return ret; } - /* ------------------------- NPC_ApplyRoff ------------------------- */ -void NPC_ApplyRoff(void) -{ - PlayerStateToEntityState( &NPC->client->ps, &NPC->s ); - VectorCopy ( NPC->currentOrigin, NPC->lastOrigin ); +void NPC_ApplyRoff(void) { + PlayerStateToEntityState(&NPC->client->ps, &NPC->s); + VectorCopy(NPC->currentOrigin, NPC->lastOrigin); // use the precise origin for linking gi.linkentity(NPC); } - diff --git a/code/game/NPC_reactions.cpp b/code/game/NPC_reactions.cpp index 643bc7dd93..528f00d815 100644 --- a/code/game/NPC_reactions.cpp +++ b/code/game/NPC_reactions.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_reactions.cpp +// NPC_reactions.cpp #include "b_local.h" #include "anims.h" @@ -28,30 +28,30 @@ along with this program; if not, see . #include "wp_saber.h" #include "g_vehicles.h" -extern qboolean G_CheckForStrongAttackMomentum( gentity_t *self ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void cgi_S_StartSound( const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern void Jedi_Ambush( gentity_t *self ); -extern qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ); - -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SpinningAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); - -extern cvar_t *g_spskill; -extern int teamLastEnemyTime[]; -extern qboolean stop_icarus; +extern qboolean G_CheckForStrongAttackMomentum(gentity_t *self); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void cgi_S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern void Jedi_Ambush(gentity_t *self); +extern qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker); + +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SpinningAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InCartwheel(int anim); + +extern cvar_t *g_spskill; +extern int teamLastEnemyTime[]; +extern qboolean stop_icarus; extern int killPlayerTimer; float g_crosshairEntDist = Q3_INFINITE; @@ -64,89 +64,81 @@ NPC_CheckAttacker ------------------------- */ -static void NPC_CheckAttacker( gentity_t *other, int mod ) -{ - //FIXME: I don't see anything in here that would stop teammates from taking a teammate +static void NPC_CheckAttacker(gentity_t *other, int mod) { + // FIXME: I don't see anything in here that would stop teammates from taking a teammate // as an enemy. Ideally, there would be code before this to prevent that from // happening, but that is presumptuous. - //valid ent - FIXME: a VALIDENT macro would be nice here - if ( !other ) + // valid ent - FIXME: a VALIDENT macro would be nice here + if (!other) return; - if ( other == NPC ) + if (other == NPC) return; - if ( !other->inuse ) + if (!other->inuse) return; - //Don't take a target that doesn't want to be - if ( other->flags & FL_NOTARGET ) + // Don't take a target that doesn't want to be + if (other->flags & FL_NOTARGET) return; - if ( NPC->svFlags & SVF_LOCKEDENEMY ) - {//IF LOCKED, CANNOT CHANGE ENEMY!!!!! + if (NPC->svFlags & SVF_LOCKEDENEMY) { // IF LOCKED, CANNOT CHANGE ENEMY!!!!! return; } - //If we haven't taken a target, just get mad - if ( NPC->enemy == NULL )//was using "other", fixed to NPC + // If we haven't taken a target, just get mad + if (NPC->enemy == NULL) // was using "other", fixed to NPC { - G_SetEnemy( NPC, other ); + G_SetEnemy(NPC, other); return; } - //we have an enemy, see if he's dead - if ( NPC->enemy->health <= 0 ) - { - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, other ); + // we have an enemy, see if he's dead + if (NPC->enemy->health <= 0) { + G_ClearEnemy(NPC); + G_SetEnemy(NPC, other); return; } - //Don't take the same enemy again - if ( other == NPC->enemy ) + // Don't take the same enemy again + if (other == NPC->enemy) return; - if ( NPC->client->ps.weapon == WP_SABER ) - {//I'm a jedi - if ( mod == MOD_SABER ) - {//I was hit by a saber FIXME: what if this was a thrown saber? - //always switch to this enemy if I'm a jedi and hit by another saber - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, other ); + if (NPC->client->ps.weapon == WP_SABER) { // I'm a jedi + if (mod == MOD_SABER) { // I was hit by a saber FIXME: what if this was a thrown saber? + // always switch to this enemy if I'm a jedi and hit by another saber + G_ClearEnemy(NPC); + G_SetEnemy(NPC, other); return; } } - //Special case player interactions - if ( other == &g_entities[0] ) - { - //Account for the skill level to skew the results - float luckThreshold; + // Special case player interactions + if (other == &g_entities[0]) { + // Account for the skill level to skew the results + float luckThreshold; - switch ( g_spskill->integer ) - { - //Easiest difficulty, mild chance of picking up the player + switch (g_spskill->integer) { + // Easiest difficulty, mild chance of picking up the player case 0: luckThreshold = 0.9f; break; - //Medium difficulty, half-half chance of picking up the player + // Medium difficulty, half-half chance of picking up the player case 1: luckThreshold = 0.5f; break; - //Hardest difficulty, always turn on attacking player + // Hardest difficulty, always turn on attacking player case 2: default: luckThreshold = 0.0f; break; } - //Randomly pick up the target - if ( Q_flrand(0.0f, 1.0f) > luckThreshold ) - { - G_ClearEnemy( other ); + // Randomly pick up the target + if (Q_flrand(0.0f, 1.0f) > luckThreshold) { + G_ClearEnemy(other); other->enemy = NPC; } @@ -154,14 +146,11 @@ static void NPC_CheckAttacker( gentity_t *other, int mod ) } } -void NPC_SetPainEvent( gentity_t *self ) -{ - if ( !self->NPC || !(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); - } +void NPC_SetPainEvent(gentity_t *self) { + if (!self->NPC || !(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->max_health * 100.0f)); + } } } @@ -171,37 +160,33 @@ NPC_GetPainChance ------------------------- */ -float NPC_GetPainChance( gentity_t *self, int damage ) -{ - if ( !self->enemy ) - {//surprised, always take pain +float NPC_GetPainChance(gentity_t *self, int damage) { + if (!self->enemy) { // surprised, always take pain return 1.0f; } - if ( damage > self->max_health/2.0f ) - { + if (damage > self->max_health / 2.0f) { return 1.0f; } - float pain_chance = (float)(self->max_health-self->health)/(self->max_health*2.0f) + (float)damage/(self->max_health/2.0f); - switch ( g_spskill->integer ) - { - case 0: //easy - //return 0.75f; + float pain_chance = (float)(self->max_health - self->health) / (self->max_health * 2.0f) + (float)damage / (self->max_health / 2.0f); + switch (g_spskill->integer) { + case 0: // easy + // return 0.75f; break; - case 1://med + case 1: // med pain_chance *= 0.5f; - //return 0.35f; + // return 0.35f; break; - case 2://hard + case 2: // hard default: pain_chance *= 0.1f; - //return 0.05f; + // return 0.05f; break; } - //Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); + // Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); return pain_chance; } @@ -211,186 +196,122 @@ NPC_ChoosePainAnimation ------------------------- */ -#define MIN_PAIN_TIME 200 +#define MIN_PAIN_TIME 200 -extern int G_PickPainAnim( gentity_t *self, const vec3_t point, int damage, int hitLoc ); -void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc, int voiceEvent = -1 ) -{ - //If we've already taken pain, then don't take it again - if ( level.time < self->painDebounceTime && mod != MOD_ELECTROCUTE && mod != MOD_MELEE ) - {//FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? +extern int G_PickPainAnim(gentity_t *self, const vec3_t point, int damage, int hitLoc); +void NPC_ChoosePainAnimation(gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc, int voiceEvent = -1) { + // If we've already taken pain, then don't take it again + if (level.time < self->painDebounceTime && mod != MOD_ELECTROCUTE && + mod != MOD_MELEE) { // FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? return; } - int pain_anim = -1; - float pain_chance; + int pain_anim = -1; + float pain_chance; - if ( self->s.weapon == WP_THERMAL && self->client->fireDelay > 0 ) - {//don't interrupt thermal throwing anim + if (self->s.weapon == WP_THERMAL && self->client->fireDelay > 0) { // don't interrupt thermal throwing anim return; - } - else if (self->client->ps.powerups[PW_GALAK_SHIELD]) - { + } else if (self->client->ps.powerups[PW_GALAK_SHIELD]) { return; - } - else if ( self->client->NPC_class == CLASS_GALAKMECH ) - { - if ( hitLoc == HL_GENERIC1 ) - {//hit the antenna! + } else if (self->client->NPC_class == CLASS_GALAKMECH) { + if (hitLoc == HL_GENERIC1) { // hit the antenna! pain_chance = 1.0f; - self->s.powerups |= ( 1 << PW_SHOCKED ); - self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); - } - else if ( self->client->ps.powerups[PW_GALAK_SHIELD] ) - {//shield up + self->s.powerups |= (1 << PW_SHOCKED); + self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand(500, 2500); + } else if (self->client->ps.powerups[PW_GALAK_SHIELD]) { // shield up return; - } - else if ( self->health > 200 && damage < 100 ) - {//have a *lot* of health + } else if (self->health > 200 && damage < 100) { // have a *lot* of health pain_chance = 0.05f; + } else { // the lower my health and greater the damage, the more likely I am to play a pain anim + pain_chance = (200.0f - self->health) / 100.0f + damage / 50.0f; } - else - {//the lower my health and greater the damage, the more likely I am to play a pain anim - pain_chance = (200.0f-self->health)/100.0f + damage/50.0f; - } - } - else if ( self->client && self->client->playerTeam == TEAM_PLAYER && other && !other->s.number ) - {//ally shot by player always complains + } else if (self->client && self->client->playerTeam == TEAM_PLAYER && other && !other->s.number) { // ally shot by player always complains pain_chance = 1.1f; - } - else - { - if ( other && (other->s.weapon == WP_SABER || mod == MOD_ELECTROCUTE || mod == MOD_CRUSH/*FIXME:MOD_FORCE_GRIP*/) ) - { - if ( self->client->ps.weapon == WP_SABER - && other->s.number < MAX_CLIENTS ) - {//hmm, shouldn't *always* react to damage from player if I have a saber - pain_chance = 1.05f - ((self->NPC->rank)/(float)RANK_CAPTAIN); - } - else - { - pain_chance = 1.0f;//always take pain from saber - } - } - else if ( mod == MOD_GAS ) - { + } else { + if (other && (other->s.weapon == WP_SABER || mod == MOD_ELECTROCUTE || mod == MOD_CRUSH /*FIXME:MOD_FORCE_GRIP*/)) { + if (self->client->ps.weapon == WP_SABER && other->s.number < MAX_CLIENTS) { // hmm, shouldn't *always* react to damage from player if I have a saber + pain_chance = 1.05f - ((self->NPC->rank) / (float)RANK_CAPTAIN); + } else { + pain_chance = 1.0f; // always take pain from saber + } + } else if (mod == MOD_GAS) { pain_chance = 1.0f; - } - else if ( mod == MOD_MELEE ) - {//higher in rank (skill) we are, less likely we are to be fazed by a punch - pain_chance = 1.0f - ((RANK_CAPTAIN-self->NPC->rank)/(float)RANK_CAPTAIN); - } - else if ( self->client->NPC_class == CLASS_PROTOCOL ) - { + } else if (mod == MOD_MELEE) { // higher in rank (skill) we are, less likely we are to be fazed by a punch + pain_chance = 1.0f - ((RANK_CAPTAIN - self->NPC->rank) / (float)RANK_CAPTAIN); + } else if (self->client->NPC_class == CLASS_PROTOCOL) { pain_chance = 1.0f; + } else { + pain_chance = NPC_GetPainChance(self, damage); } - else - { - pain_chance = NPC_GetPainChance( self, damage ); - } - if ( self->client->NPC_class == CLASS_DESANN ) - { + if (self->client->NPC_class == CLASS_DESANN) { pain_chance *= 0.5f; } } - //See if we're going to flinch - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) - { - //Pick and play our animation - if ( (self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - { - G_AddVoiceEvent( self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0 ); - } - else if ( mod == MOD_GAS ) - { - //SIGH... because our choke sounds are inappropriately long, I have to debounce them in code! - if ( TIMER_Done( self, "gasChokeSound" ) ) - { - TIMER_Set( self, "gasChokeSound", Q_irand( 1000, 2000 ) ); - G_AddVoiceEvent( self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0 ); - } - } - else if ( (self->client->ps.eFlags&EF_FORCE_DRAINED) ) - { - NPC_SetPainEvent( self ); - } - else - {//not being force-gripped or force-drained - if ( G_CheckForStrongAttackMomentum( self ) - || PM_SpinningAnim( self->client->ps.legsAnim ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || PM_InKnockDown( &self->client->ps ) - || PM_RollingAnim( self->client->ps.legsAnim ) - || (PM_FlippingAnim( self->client->ps.legsAnim )&&!PM_InCartwheel( self->client->ps.legsAnim )) ) - {//strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain + // See if we're going to flinch + if (Q_flrand(0.0f, 1.0f) < pain_chance) { + // Pick and play our animation + if ((self->client->ps.eFlags & EF_FORCE_GRIPPED)) { + G_AddVoiceEvent(self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0); + } else if (mod == MOD_GAS) { + // SIGH... because our choke sounds are inappropriately long, I have to debounce them in code! + if (TIMER_Done(self, "gasChokeSound")) { + TIMER_Set(self, "gasChokeSound", Q_irand(1000, 2000)); + G_AddVoiceEvent(self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0); + } + } else if ((self->client->ps.eFlags & EF_FORCE_DRAINED)) { + NPC_SetPainEvent(self); + } else { // not being force-gripped or force-drained + if (G_CheckForStrongAttackMomentum(self) || PM_SpinningAnim(self->client->ps.legsAnim) || PM_SaberInSpecialAttack(self->client->ps.torsoAnim) || + PM_InKnockDown(&self->client->ps) || PM_RollingAnim(self->client->ps.legsAnim) || + (PM_FlippingAnim(self->client->ps.legsAnim) && + !PM_InCartwheel(self->client->ps.legsAnim))) { // strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain return; - } - else - {//play an anim - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//only has 1 for now - //FIXME: never plays this, it seems... + } else { // play an anim + if (self->client->NPC_class == CLASS_GALAKMECH) { // only has 1 for now + // FIXME: never plays this, it seems... pain_anim = BOTH_PAIN1; - } - else if ( mod == MOD_MELEE ) - { - pain_anim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); - } - else if ( self->s.weapon == WP_SABER ) - {//temp HACK: these are the only 2 pain anims that look good when holding a saber - pain_anim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); - } - else if ( mod != MOD_ELECTROCUTE ) - { - pain_anim = G_PickPainAnim( self, point, damage, hitLoc ); + } else if (mod == MOD_MELEE) { + pain_anim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else if (self->s.weapon == WP_SABER) { // temp HACK: these are the only 2 pain anims that look good when holding a saber + pain_anim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else if (mod != MOD_ELECTROCUTE) { + pain_anim = G_PickPainAnim(self, point, damage, hitLoc); } - if ( pain_anim == -1 ) - { - pain_anim = PM_PickAnim( self, BOTH_PAIN1, BOTH_PAIN18 ); + if (pain_anim == -1) { + pain_anim = PM_PickAnim(self, BOTH_PAIN1, BOTH_PAIN18); } - self->client->ps.saberAnimLevel = SS_FAST;//next attack must be a quick attack - self->client->ps.saberMove = LS_READY;//don't finish whatever saber move you may have been in + self->client->ps.saberAnimLevel = SS_FAST; // next attack must be a quick attack + self->client->ps.saberMove = LS_READY; // don't finish whatever saber move you may have been in int parts = SETANIM_BOTH; - if ( PM_CrouchAnim( self->client->ps.legsAnim ) || PM_InCartwheel( self->client->ps.legsAnim ) ) - { + if (PM_CrouchAnim(self->client->ps.legsAnim) || PM_InCartwheel(self->client->ps.legsAnim)) { parts = SETANIM_LEGS; } self->NPC->aiFlags &= ~NPCAI_KNEEL; - NPC_SetAnim( self, parts, pain_anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - if ( voiceEvent != -1 ) - { - G_AddVoiceEvent( self, voiceEvent, Q_irand( 2000, 4000 ) ); + NPC_SetAnim(self, parts, pain_anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetPainEvent( self ); + if (voiceEvent != -1) { + G_AddVoiceEvent(self, voiceEvent, Q_irand(2000, 4000)); + } else { + NPC_SetPainEvent(self); } } - //Setup the timing for it - if ( mod == MOD_ELECTROCUTE ) - { + // Setup the timing for it + if (mod == MOD_ELECTROCUTE) { self->painDebounceTime = level.time + 4000; } - self->painDebounceTime = level.time + PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t) pain_anim ); + self->painDebounceTime = level.time + PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)pain_anim); self->client->fireDelay = 0; } } -extern qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ); +extern qboolean G_ValidEnemy(gentity_t *self, gentity_t *enemy); -gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate ) -{ - if ( enemy->e_UseFunc == useF_emplaced_gun_use - || enemy->e_UseFunc == useF_eweb_use ) - { - if ( enemy->activator - && enemy->activator->client ) - {//return the controller of the eweb/emplaced gun - if (validate==qfalse || !self->client || G_ValidEnemy(self, enemy)) - { +gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate) { + if (enemy->e_UseFunc == useF_emplaced_gun_use || enemy->e_UseFunc == useF_eweb_use) { + if (enemy->activator && enemy->activator->client) { // return the controller of the eweb/emplaced gun + if (validate == qfalse || !self->client || G_ValidEnemy(self, enemy)) { return enemy->activator; } } @@ -399,126 +320,100 @@ gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qbool return enemy; } -extern void Boba_Pain( gentity_t *self, gentity_t *inflictor, int damage, int mod); +extern void Boba_Pain(gentity_t *self, gentity_t *inflictor, int damage, int mod); /* =============== NPC_Pain =============== */ -void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc ) -{ +void NPC_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { team_t otherTeam = TEAM_FREE; - int voiceEvent = -1; + int voiceEvent = -1; - if ( self->NPC == NULL ) + if (self->NPC == NULL) return; - if ( other == NULL ) + if (other == NULL) return; - //or just remove ->pain in player_die? - if ( self->client->ps.pm_type == PM_DEAD ) + // or just remove ->pain in player_die? + if (self->client->ps.pm_type == PM_DEAD) return; - if ( other == self ) + if (other == self) return; other = G_CheckControlledTurretEnemy(self, other, qfalse); - if (!other) - { + if (!other) { return; } - //MCG: Ignore damage from your own team for now - if ( other->client ) - { + // MCG: Ignore damage from your own team for now + if (other->client) { otherTeam = other->client->playerTeam; - // if ( otherTeam == TEAM_DISGUISE ) - // { - // otherTeam = TEAM_PLAYER; - // } - } - - if ( self->client->playerTeam - && other->client - && otherTeam == self->client->playerTeam - && (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) - {//hit by a teammate - if ( other != self->enemy && self != other->enemy ) - {//we weren't already enemies - if ( self->enemy || other->enemy - || (other->s.number&&other->s.number!=player->client->ps.viewEntity) - /*|| (!other->s.number&&Q_irand( 0, 3 ))*/ ) - {//if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad (FIXME:accumulate anger+base on diff?) - //FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad - //Still run pain and flee scripts - if ( self->client && self->NPC ) - {//Run any pain instructions - if ( self->health <= (self->max_health/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { - - } - else// if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + // if ( otherTeam == TEAM_DISGUISE ) + // { + // otherTeam = TEAM_PLAYER; + // } + } + + if (self->client->playerTeam && other->client && otherTeam == self->client->playerTeam && + (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) { // hit by a teammate + if (other != self->enemy && self != other->enemy) { // we weren't already enemies + if (self->enemy || other->enemy || (other->s.number && other->s.number != player->client->ps.viewEntity) + /*|| (!other->s.number&&Q_irand( 0, 3 ))*/) { // if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player + // or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad + // (FIXME:accumulate anger+base on diff?) + // FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad + // Still run pain and flee scripts + if (self->client && self->NPC) { // Run any pain instructions + if (self->health <= (self->max_health / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc); } } return; - } - else if ( self->NPC && !other->s.number )//should be assumed, but... - {//dammit, stop that! - if ( self->NPC->charmedTime > level.time ) - {//mindtricked + } else if (self->NPC && !other->s.number) // should be assumed, but... + { // dammit, stop that! + if (self->NPC->charmedTime > level.time) { // mindtricked return; - } - else if ( self->NPC->ffireCount < 3+((2-g_spskill->integer)*2) ) - {//not mad enough yet - //Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc ); + } else if (self->NPC->ffireCount < 3 + ((2 - g_spskill->integer) * 2)) { // not mad enough yet + // Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc); } } return; - } - else if ( G_ActivateBehavior( self, BSET_FFIRE ) ) - {//we have a specific script to run, so do that instead + } else if (G_ActivateBehavior(self, BSET_FFIRE)) { // we have a specific script to run, so do that instead return; - } - else - {//okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and clear any flags that would stop us) + } else { // okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and + // clear any flags that would stop us) self->NPC->blockedSpeechDebounceTime = 0; voiceEvent = EV_FFTURN; self->NPC->behaviorState = self->NPC->tempBehavior = self->NPC->defaultBehavior = BS_DEFAULT; other->flags &= ~FL_NOTARGET; - self->svFlags &= ~(SVF_IGNORE_ENEMIES|SVF_ICARUS_FREEZE|SVF_NO_COMBAT_SOUNDS); - G_SetEnemy( self, other ); + self->svFlags &= ~(SVF_IGNORE_ENEMIES | SVF_ICARUS_FREEZE | SVF_NO_COMBAT_SOUNDS); + G_SetEnemy(self, other); self->svFlags |= SVF_LOCKEDENEMY; - self->NPC->scriptFlags &= ~(SCF_DONT_FIRE|SCF_CROUCHED|SCF_WALKING|SCF_NO_COMBAT_TALK|SCF_FORCED_MARCH); - self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES|SCF_NO_MIND_TRICK); - //NOTE: we also stop ICARUS altogether + self->NPC->scriptFlags &= ~(SCF_DONT_FIRE | SCF_CROUCHED | SCF_WALKING | SCF_NO_COMBAT_TALK | SCF_FORCED_MARCH); + self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES | SCF_NO_MIND_TRICK); + // NOTE: we also stop ICARUS altogether stop_icarus = qtrue; - if ( !killPlayerTimer ) - { + if (!killPlayerTimer) { killPlayerTimer = level.time + 10000; } } @@ -527,54 +422,44 @@ void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const ve } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - //Do extra bits - if ( NPCInfo->ignorePain == qfalse ) - { - NPCInfo->confusionTime = 0;//clear any charm or confusion, regardless - if ( NPC->ghoul2.size() && NPC->headBolt != -1 ) - { - G_StopEffect("force/confusion", NPC->playerModel, NPC->headBolt, NPC->s.number ); + // Do extra bits + if (NPCInfo->ignorePain == qfalse) { + NPCInfo->confusionTime = 0; // clear any charm or confusion, regardless + if (NPC->ghoul2.size() && NPC->headBolt != -1) { + G_StopEffect("force/confusion", NPC->playerModel, NPC->headBolt, NPC->s.number); } - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, voiceEvent ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, voiceEvent); } - //Check to take a new enemy - if ( NPC->enemy != other && NPC != other ) - {//not already mad at them - //if it's an eweb or emplaced gun, get mad at the owner, not the gun - NPC_CheckAttacker( other, mod ); + // Check to take a new enemy + if (NPC->enemy != other && NPC != other) { // not already mad at them + // if it's an eweb or emplaced gun, get mad at the owner, not the gun + NPC_CheckAttacker(other, mod); } } - //Attempt to run any pain instructions - if ( self->client && self->NPC ) - { - //FIXME: This needs better heuristics perhaps - if(self->health <= (self->max_health/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { - } - else //if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + // Attempt to run any pain instructions + if (self->client && self->NPC) { + // FIXME: This needs better heuristics perhaps + if (self->health <= (self->max_health / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - //Attempt to fire any paintargets we might have - if( self->paintarget && self->paintarget[0] ) - { + // Attempt to fire any paintargets we might have + if (self->paintarget && self->paintarget[0]) { G_UseTargets2(self, other, self->paintarget); } - if (self->client && self->client->NPC_class==CLASS_BOBAFETT) - { - Boba_Pain( self, inflictor, damage, mod); + if (self->client && self->client->NPC_class == CLASS_BOBAFETT) { + Boba_Pain(self, inflictor, damage, mod); } - RestoreNPCGlobals(); } @@ -583,120 +468,93 @@ void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const ve NPC_Touch ------------------------- */ -extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); -void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) -{ - if(!self->NPC) +extern qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname); +void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!self->NPC) return; SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if ( self->message && self->health <= 0 ) - {//I am dead and carrying a key - if ( other && player && player->health > 0 && other == player ) - {//player touched me + if (self->message && self->health <= 0) { // I am dead and carrying a key + if (other && player && player->health > 0 && other == player) { // player touched me char *text; - qboolean keyTaken; - //give him my key - if ( Q_stricmp( "goodie", self->message ) == 0 ) - {//a goodie key - if ( (keyTaken = INV_GoodieKeyGive( other )) == qtrue ) - { + qboolean keyTaken; + // give him my key + if (Q_stricmp("goodie", self->message) == 0) { // a goodie key + if ((keyTaken = INV_GoodieKeyGive(other)) == qtrue) { text = "cp @SP_INGAME_TOOK_IMPERIAL_GOODIE_KEY"; - G_AddEvent( other, EV_ITEM_PICKUP, (FindItemForInventory( INV_GOODIE_KEY )-bg_itemlist) ); - } - else - { + G_AddEvent(other, EV_ITEM_PICKUP, (FindItemForInventory(INV_GOODIE_KEY) - bg_itemlist)); + } else { text = "cp @SP_INGAME_CANT_CARRY_GOODIE_KEY"; } - } - else - {//a named security key - if ( (keyTaken = INV_SecurityKeyGive( player, self->message )) == qtrue ) - { + } else { // a named security key + if ((keyTaken = INV_SecurityKeyGive(player, self->message)) == qtrue) { text = "cp @SP_INGAME_TOOK_IMPERIAL_SECURITY_KEY"; - G_AddEvent( other, EV_ITEM_PICKUP, (FindItemForInventory( INV_SECURITY_KEY )-bg_itemlist) ); - } - else - { + G_AddEvent(other, EV_ITEM_PICKUP, (FindItemForInventory(INV_SECURITY_KEY) - bg_itemlist)); + } else { text = "cp @SP_INGAME_CANT_CARRY_SECURITY_KEY"; } } - if ( keyTaken ) - {//remove my key - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm_key", 0x00000002 ); + if (keyTaken) { // remove my key + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm_key", 0x00000002); self->message = NULL; - self->client->ps.eFlags &= ~EF_FORCE_VISIBLE; //remove sight flag - G_Sound( player, G_SoundIndex( "sound/weapons/key_pkup.wav" ) ); + self->client->ps.eFlags &= ~EF_FORCE_VISIBLE; // remove sight flag + G_Sound(player, G_SoundIndex("sound/weapons/key_pkup.wav")); } - gi.SendServerCommand( 0, text ); + gi.SendServerCommand(0, text); } } - if ( other->client ) - {//FIXME: if pushing against another bot, both ucmd.rightmove = 127??? - //Except if not facing one another... - if ( other->health > 0 ) - { + if (other->client) { // FIXME: if pushing against another bot, both ucmd.rightmove = 127??? + // Except if not facing one another... + if (other->health > 0) { NPCInfo->touchedByPlayer = other; } - if ( other == NPCInfo->goalEntity ) - { + if (other == NPCInfo->goalEntity) { NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } - if( !(self->svFlags&SVF_LOCKEDENEMY) && !(self->svFlags&SVF_IGNORE_ENEMIES) && !(other->flags & FL_NOTARGET) ) - { - if ( self->client->enemyTeam ) - {//See if we bumped into an enemy - if ( other->client->playerTeam == self->client->enemyTeam ) - {//bumped into an enemy - if( NPCInfo->behaviorState != BS_HUNT_AND_KILL && !NPCInfo->tempBehavior ) - {//MCG - Begin: checking specific BS mode here, this is bad, a HACK - //FIXME: not medics? - if ( NPC->enemy != other ) - {//not already mad at them - G_SetEnemy( NPC, other ); + if (!(self->svFlags & SVF_LOCKEDENEMY) && !(self->svFlags & SVF_IGNORE_ENEMIES) && !(other->flags & FL_NOTARGET)) { + if (self->client->enemyTeam) { // See if we bumped into an enemy + if (other->client->playerTeam == self->client->enemyTeam) { // bumped into an enemy + if (NPCInfo->behaviorState != BS_HUNT_AND_KILL && + !NPCInfo->tempBehavior) { // MCG - Begin: checking specific BS mode here, this is bad, a HACK + // FIXME: not medics? + if (NPC->enemy != other) { // not already mad at them + G_SetEnemy(NPC, other); } - // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; + // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; } } } } - //FIXME: do this if player is moving toward me and with a certain dist? + // FIXME: do this if player is moving toward me and with a certain dist? /* if ( other->s.number == 0 && self->client->playerTeam == other->client->playerTeam ) { VectorAdd( self->client->pushVec, other->client->ps.velocity, self->client->pushVec ); } */ - } - else - {//FIXME: check for SVF_NONNPC_ENEMY flag here? - if ( other->health > 0 ) - { - if ( NPC->enemy == other && (other->svFlags&SVF_NONNPC_ENEMY) ) - { + } else { // FIXME: check for SVF_NONNPC_ENEMY flag here? + if (other->health > 0) { + if (NPC->enemy == other && (other->svFlags & SVF_NONNPC_ENEMY)) { NPCInfo->touchedByPlayer = other; } } - if ( other == NPCInfo->goalEntity ) - { + if (other == NPCInfo->goalEntity) { NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } } - if ( NPC->client->NPC_class == CLASS_RANCOR ) - {//rancor - if ( NPCInfo->blockedEntity != other && TIMER_Done(NPC, "blockedEntityIgnore")) - {//blocked - //if ( G_EntIsBreakable( other->s.number, NPC ) ) - {//bumped into another breakable, so take that one instead? - NPCInfo->blockedEntity = other;//??? + if (NPC->client->NPC_class == CLASS_RANCOR) { // rancor + if (NPCInfo->blockedEntity != other && TIMER_Done(NPC, "blockedEntityIgnore")) { // blocked + // if ( G_EntIsBreakable( other->s.number, NPC ) ) + { // bumped into another breakable, so take that one instead? + NPCInfo->blockedEntity = other; //??? } } } @@ -710,32 +568,26 @@ NPC_TempLookTarget ------------------------- */ -void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ) -{ - if ( !self->client ) - { +void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime) { + if (!self->client) { return; } - if ( !minLookTime ) - { + if (!minLookTime) { minLookTime = 1000; } - if ( !maxLookTime ) - { + if (!maxLookTime) { maxLookTime = 1000; } - if ( !NPC_CheckLookTarget( self ) ) - {//Not already looking at something else - //Look at him for 1 to 3 seconds - NPC_SetLookTarget( self, lookEntNum, level.time + Q_irand( minLookTime, maxLookTime ) ); + if (!NPC_CheckLookTarget(self)) { // Not already looking at something else + // Look at him for 1 to 3 seconds + NPC_SetLookTarget(self, lookEntNum, level.time + Q_irand(minLookTime, maxLookTime)); } } -void NPC_Respond( gentity_t *self, int userNum ) -{ +void NPC_Respond(gentity_t *self, int userNum) { int event = -1; /* @@ -749,90 +601,58 @@ void NPC_Respond( gentity_t *self, int userNum ) } */ - if ( !Q_irand( 0, 1 ) ) - {//set looktarget to them for a second or two - NPC_TempLookTarget( self, userNum, 1000, 3000 ); + if (!Q_irand(0, 1)) { // set looktarget to them for a second or two + NPC_TempLookTarget(self, userNum, 1000, 3000); } - //some last-minute hacked in responses - switch ( self->client->NPC_class ) - { + // some last-minute hacked in responses + switch (self->client->NPC_class) { case CLASS_JAN: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 2 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 2)) { event = EV_SUSPICIOUS4; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_SOUND1; - } - else - { + } else { event = EV_CONFUSE1; } break; case CLASS_LANDO: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 6 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 6)) { event = EV_SIGHT2; - } - else if ( !Q_irand( 0, 5 ) ) - { + } else if (!Q_irand(0, 5)) { event = EV_GIVEUP4; - } - else if ( Q_irand( 0, 4 ) > 1 ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else - { - event = Q_irand( EV_JDETECTED1, EV_JDETECTED2 ); + } else if (Q_irand(0, 4) > 1) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else { + event = Q_irand(EV_JDETECTED1, EV_JDETECTED2); } break; case CLASS_LUKE: - if ( self->enemy ) - { + if (self->enemy) { event = EV_COVER1; - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_JEDI: case CLASS_KYLE: - if ( !self->enemy ) - { + if (!self->enemy) { /* if ( !(self->svFlags&SVF_IGNORE_ENEMIES) && (self->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) @@ -842,139 +662,89 @@ void NPC_Respond( gentity_t *self, int userNum ) } else */ - { - event = Q_irand( EV_CONFUSE1, EV_CONFUSE3 ); - } + { event = Q_irand(EV_CONFUSE1, EV_CONFUSE3); } } break; case CLASS_PRISONER: - if ( self->enemy ) - { - if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); + if (self->enemy) { + if (Q_irand(0, 1)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_REBEL: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else - { - event = Q_irand( EV_DETECTED1, EV_DETECTED5 ); + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_DETECTED1, EV_DETECTED5); } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_BESPIN_COP: - if ( !Q_stricmp( "bespincop", self->NPC_type ) ) - {//variant 1 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); + if (!Q_stricmp("bespincop", self->NPC_type)) { // variant 1 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT2, EV_SIGHT3 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT2, EV_SIGHT3); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_ESCAPING2; - } - else - { + } else { event = EV_GIVEUP4; } - } - else - {//variant2 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); + } else { // variant2 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT1, EV_SIGHT2 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT1, EV_SIGHT2); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_GIVEUP3; - } - else - { + } else { event = EV_CONFUSE1; } } break; - case CLASS_R2D2: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)))); + case CLASS_R2D2: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)))); break; - case CLASS_R5D2: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)))); + case CLASS_R5D2: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)))); break; - case CLASS_MOUSE: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)))); + case CLASS_MOUSE: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)))); break; - case CLASS_GONK: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)))); + case CLASS_GONK: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)))); break; case CLASS_JAWA: - G_SoundOnEnt(self, CHAN_VOICE, va("sound/chars/jawa/misc/chatter%d.wav",Q_irand(1, 6)) ); - if ( self->NPC ) - { + G_SoundOnEnt(self, CHAN_VOICE, va("sound/chars/jawa/misc/chatter%d.wav", Q_irand(1, 6))); + if (self->NPC) { self->NPC->blockedSpeechDebounceTime = level.time + 2000; } break; @@ -982,16 +752,14 @@ void NPC_Respond( gentity_t *self, int userNum ) break; } - if ( event != -1 ) - { - //hack here because we reuse some "combat" and "extra" sounds - qboolean addFlag = (qboolean)((self->NPC->scriptFlags&SCF_NO_COMBAT_TALK) != 0); + if (event != -1) { + // hack here because we reuse some "combat" and "extra" sounds + qboolean addFlag = (qboolean)((self->NPC->scriptFlags & SCF_NO_COMBAT_TALK) != 0); self->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; - G_AddVoiceEvent( self, event, 3000 ); + G_AddVoiceEvent(self, event, 3000); - if ( addFlag ) - { + if (addFlag) { self->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; } } @@ -1003,51 +771,39 @@ NPC_UseResponse ------------------------- */ -void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) -{ - if ( !self->NPC || !self->client ) - { +void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone) { + if (!self->NPC || !self->client) { return; } - if ( user->s.number != 0 ) - {//not used by the player - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->s.number != 0) { // not used by the player + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( user->client && self->client->playerTeam != user->client->playerTeam && self->client->playerTeam != TEAM_NEUTRAL ) - {//only those on the same team react - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->client && self->client->playerTeam != user->client->playerTeam && self->client->playerTeam != TEAM_NEUTRAL) { // only those on the same team react + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - {//I'm not responding right now + if (self->NPC->blockedSpeechDebounceTime > level.time) { // I'm not responding right now return; } - if ( gi.VoiceVolume[self->s.number] ) - {//I'm talking already - if ( !useWhenDone ) - {//you're not trying to use me + if (gi.VoiceVolume[self->s.number]) { // I'm talking already + if (!useWhenDone) { // you're not trying to use me return; } } - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); - } - else - { - NPC_Respond( self, user->s.number ); + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); + } else { + NPC_Respond(self, user->s.number); } } @@ -1056,99 +812,84 @@ void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) NPC_Use ------------------------- */ -extern void Add_Batteries( gentity_t *ent, int *count ); +extern void Add_Batteries(gentity_t *ent, int *count); -void NPC_Use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if (self->client->ps.pm_type == PM_DEAD) - {//or just remove ->pain in player_die? +void NPC_Use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->client->ps.pm_type == PM_DEAD) { // or just remove ->pain in player_die? return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if(self->client && self->NPC) - { + if (self->client && self->NPC) { // If this is a vehicle, let the other guy board it. Added 12/14/02 by AReis. - if ( self->client->NPC_class == CLASS_VEHICLE ) - { + if (self->client->NPC_class == CLASS_VEHICLE) { Vehicle_t *pVeh = self->m_pVehicle; - if ( pVeh && pVeh->m_pVehicleInfo && other && other->client ) - {//safety - //if I used myself, eject everyone on me - if ( other == self ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); + if (pVeh && pVeh->m_pVehicleInfo && other && other->client) { // safety + // if I used myself, eject everyone on me + if (other == self) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); } // If other is already riding this vehicle (self), eject him. - else if ( other->owner == self ) - { - pVeh->m_pVehicleInfo->Eject( pVeh, other, qfalse ); + else if (other->owner == self) { + pVeh->m_pVehicleInfo->Eject(pVeh, other, qfalse); } // Otherwise board this vehicle. - else - { - pVeh->m_pVehicleInfo->Board( pVeh, other ); + else { + pVeh->m_pVehicleInfo->Board(pVeh, other); } } + } else if (Jedi_WaitingAmbush(NPC)) { + Jedi_Ambush(NPC); } - else if ( Jedi_WaitingAmbush( NPC ) ) - { - Jedi_Ambush( NPC ); - } - //Run any use instructions - if ( activator && activator->s.number == 0 && self->client->NPC_class == CLASS_GONK ) - { + // Run any use instructions + if (activator && activator->s.number == 0 && self->client->NPC_class == CLASS_GONK) { // must be using the gonk, so attempt to give battery power. // NOTE: this will steal up to MAX_BATTERIES for the activator, leaving the residual on the gonk for potential later use. - Add_Batteries( activator, &self->client->ps.batteryCharge ); + Add_Batteries(activator, &self->client->ps.batteryCharge); } // Not using MEDICs anymore -/* - if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) - {//Heal me NOW, dammit! - if ( activator->health < activator->max_health ) - {//person needs help - if ( self->NPC->eventualGoal != activator ) - {//not my current patient already - NPC_TakePatient( activator ); - G_ActivateBehavior( self, BSET_USE ); + /* + if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) + {//Heal me NOW, dammit! + if ( activator->health < activator->max_health ) + {//person needs help + if ( self->NPC->eventualGoal != activator ) + {//not my current patient already + NPC_TakePatient( activator ); + G_ActivateBehavior( self, BSET_USE ); + } + } + else if ( !self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) + {//I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse( self, other, qfalse ); + } } - } - else if ( !self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); - } - } -*/ -// else if ( self->behaviorSet[BSET_USE] ) + */ + // else if ( self->behaviorSet[BSET_USE] ) - if ( self->behaviorSet[BSET_USE] ) - { - NPC_UseResponse( self, other, qtrue ); + if (self->behaviorSet[BSET_USE]) { + NPC_UseResponse(self, other, qtrue); } -// else if ( isMedic( self ) ) -// {//Heal me NOW, dammit! -// NPC_TakePatient( activator ); -// } - else if ( !self->enemy - //&& self->client->NPC_class == CLASS_VEHICLE - && activator->s.number == 0 - && !gi.VoiceVolume[self->s.number] - && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); + // else if ( isMedic( self ) ) + // {//Heal me NOW, dammit! + // NPC_TakePatient( activator ); + // } + else if (!self->enemy + //&& self->client->NPC_class == CLASS_VEHICLE + && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && + !(self->NPC->scriptFlags & SCF_NO_RESPONSE)) { // I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse(self, other, qfalse); } } RestoreNPCGlobals(); } -void NPC_CheckPlayerAim( void ) -{ - //FIXME: need appropriate dialogue +void NPC_CheckPlayerAim(void) { + // FIXME: need appropriate dialogue /* gentity_t *player = &g_entities[0]; @@ -1164,9 +905,8 @@ void NPC_CheckPlayerAim( void ) */ } -void NPC_CheckAllClear( void ) -{ - //FIXME: need to make this happen only once after losing enemies, not over and over again +void NPC_CheckAllClear(void) { + // FIXME: need to make this happen only once after losing enemies, not over and over again /* if ( NPC->client && !NPC->enemy && level.time - teamLastEnemyTime[NPC->client->playerTeam] > 10000 ) {//Team hasn't seen an enemy in 10 seconds diff --git a/code/game/NPC_senses.cpp b/code/game/NPC_senses.cpp index 8b25531d31..9270779397 100644 --- a/code/game/NPC_senses.cpp +++ b/code/game/NPC_senses.cpp @@ -20,13 +20,13 @@ along with this program; if not, see . =========================================================================== */ -//NPC_senses.cpp +// NPC_senses.cpp #include "b_local.h" #include "../cgame/cg_local.h" #include "g_navigator.h" #ifdef _DEBUG - #include +#include #endif extern int eventClearTime; @@ -35,25 +35,21 @@ qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore returns true if can see from point 1 to 2, even through glass (1 pane)- doesn't work with portals */ -qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) -{ - trace_t tr; +qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) { + trace_t tr; - gi.trace ( &tr, point1, NULL, NULL, point2, ignore, clipmask, (EG2_Collision)0, 0 ); - if ( tr.fraction == 1.0 ) - { + gi.trace(&tr, point1, NULL, NULL, point2, ignore, clipmask, (EG2_Collision)0, 0); + if (tr.fraction == 1.0) { return qtrue; } - gentity_t *hit = &g_entities[ tr.entityNum ]; - if(EntIsGlass(hit)) - { - vec3_t newpoint1; + gentity_t *hit = &g_entities[tr.entityNum]; + if (EntIsGlass(hit)) { + vec3_t newpoint1; VectorCopy(tr.endpos, newpoint1); - gi.trace (&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, (EG2_Collision)0, 0); - if ( tr.fraction == 1.0 ) - { + if (tr.fraction == 1.0) { return qtrue; } } @@ -70,73 +66,67 @@ or take any AI related factors (for example, the NPC's reaction time) into accou FIXME do we need fat and thin version of this? */ -qboolean CanSee ( gentity_t *ent ) -{ - trace_t tr; - vec3_t eyes; - vec3_t spot; - - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); - - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { +qboolean CanSee(gentity_t *ent) { + trace_t tr; + vec3_t eyes; + vec3_t spot; + + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); + + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, (EG2_Collision)0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } return qfalse; } -qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ) -{ - vec3_t dir, forward, angles; - float dot; +qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f) { + vec3_t dir, forward, angles; + float dot; - VectorSubtract( spot, from, dir ); + VectorSubtract(spot, from, dir); dir[2] = 0; - VectorNormalize( dir ); + VectorNormalize(dir); - VectorCopy( fromAngles, angles ); + VectorCopy(fromAngles, angles); angles[0] = 0; - AngleVectors( angles, forward, NULL, NULL ); + AngleVectors(angles, forward, NULL, NULL); - dot = DotProduct( dir, forward ); + dot = DotProduct(dir, forward); return (qboolean)(dot > threshHold); } -float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ) -{ - vec3_t dir, forward, angles; - float dot; +float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles) { + vec3_t dir, forward, angles; + float dot; - VectorSubtract( spot, from, dir ); + VectorSubtract(spot, from, dir); dir[2] = 0; - VectorNormalize( dir ); + VectorNormalize(dir); - VectorCopy( fromAngles, angles ); + VectorCopy(fromAngles, angles); angles[0] = 0; - AngleVectors( angles, forward, NULL, NULL ); + AngleVectors(angles, forward, NULL, NULL); - dot = DotProduct( dir, forward ); + dot = DotProduct(dir, forward); return dot; } @@ -147,186 +137,157 @@ IDEA: further off to side of FOV range, higher chance of failing even if technic keep core of 50% to sides as always succeeding */ -//Position compares +// Position compares -qboolean InFOV( vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV ) -{ - vec3_t deltaVector, angles, deltaAngles; +qboolean InFOV(vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV) { + vec3_t deltaVector, angles, deltaAngles; - VectorSubtract ( spot, from, deltaVector ); - vectoangles ( deltaVector, angles ); + VectorSubtract(spot, from, deltaVector); + vectoangles(deltaVector, angles); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -//NPC to position +// NPC to position -qboolean InFOV( vec3_t origin, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t fromAngles, eyes; +qboolean InFOV(vec3_t origin, gentity_t *from, int hFOV, int vFOV) { + vec3_t fromAngles, eyes; - if( from->client ) - { + if (from->client) { VectorCopy(from->client->ps.viewangles, fromAngles); - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD, eyes ); + CalcEntitySpot(from, SPOT_HEAD, eyes); - return InFOV( origin, eyes, fromAngles, hFOV, vFOV ); + return InFOV(origin, eyes, fromAngles, hFOV, vFOV); } -//Entity to entity -qboolean InFOVFromPlayerView ( gentity_t *ent, int hFOV, int vFOV ) -{ - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - vec3_t angles, fromAngles; - vec3_t deltaAngles; +// Entity to entity +qboolean InFOVFromPlayerView(gentity_t *ent, int hFOV, int vFOV) { + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + vec3_t angles, fromAngles; + vec3_t deltaAngles; - if ( !player || !player->client ) - { + if (!player || !player->client) { return qfalse; } - if ( cg.time ) - { - VectorCopy( cg.refdefViewAngles, fromAngles ); - } - else - { - VectorCopy( player->client->ps.viewangles, fromAngles ); + if (cg.time) { + VectorCopy(cg.refdefViewAngles, fromAngles); + } else { + VectorCopy(player->client->ps.viewangles, fromAngles); } - if( cg.time ) - { - VectorCopy( cg.refdef.vieworg, eyes ); - } - else - { - CalcEntitySpot( player, SPOT_HEAD_LEAN, eyes ); + if (cg.time) { + VectorCopy(cg.refdef.vieworg, eyes); + } else { + CalcEntitySpot(player, SPOT_HEAD_LEAN, eyes); } - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -qboolean InFOV ( gentity_t *ent, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - vec3_t angles, fromAngles; - vec3_t deltaAngles; - - if( from->client ) - { - if( from->client->NPC_class != CLASS_RANCOR - && from->client->NPC_class != CLASS_WAMPA - && !VectorCompare( from->client->renderInfo.eyeAngles, vec3_origin ) ) - {//Actual facing of tag_head! - //NOTE: Stasis aliens may have a problem with this? - VectorCopy( from->client->renderInfo.eyeAngles, fromAngles ); - } - else - { - VectorCopy( from->client->ps.viewangles, fromAngles ); +qboolean InFOV(gentity_t *ent, gentity_t *from, int hFOV, int vFOV) { + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + vec3_t angles, fromAngles; + vec3_t deltaAngles; + + if (from->client) { + if (from->client->NPC_class != CLASS_RANCOR && from->client->NPC_class != CLASS_WAMPA && + !VectorCompare(from->client->renderInfo.eyeAngles, vec3_origin)) { // Actual facing of tag_head! + // NOTE: Stasis aliens may have a problem with this? + VectorCopy(from->client->renderInfo.eyeAngles, fromAngles); + } else { + VectorCopy(from->client->ps.viewangles, fromAngles); } - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(from, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -qboolean InVisrange ( gentity_t *ent ) -{//FIXME: make a calculate visibility for ents that takes into account - //lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - float visrange = (NPCInfo->stats.visrange*NPCInfo->stats.visrange); +qboolean InVisrange(gentity_t *ent) { // FIXME: make a calculate visibility for ents that takes into account + // lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + float visrange = (NPCInfo->stats.visrange * NPCInfo->stats.visrange); - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); /*if(ent->client) { @@ -350,8 +311,7 @@ qboolean InVisrange ( gentity_t *ent ) } }*/ - if(VectorLengthSquared(deltaVector) > visrange) - { + if (VectorLengthSquared(deltaVector) > visrange) { return qfalse; } @@ -362,69 +322,54 @@ qboolean InVisrange ( gentity_t *ent ) NPC_CheckVisibility */ -visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) -{ +visibility_t NPC_CheckVisibility(gentity_t *ent, int flags) { // flags should never be 0 - if ( !flags ) - { + if (!flags) { return VIS_NOT; } // check PVS - if ( flags & CHECK_PVS ) - { - if ( !gi.inPVS ( ent->currentOrigin, NPC->currentOrigin ) ) - { + if (flags & CHECK_PVS) { + if (!gi.inPVS(ent->currentOrigin, NPC->currentOrigin)) { return VIS_NOT; } } - if ( !(flags & (CHECK_360|CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_360 | CHECK_FOV | CHECK_SHOOT))) { return VIS_PVS; } // check within visrange - if (flags & CHECK_VISRANGE) - { - if( !InVisrange ( ent ) ) - { + if (flags & CHECK_VISRANGE) { + if (!InVisrange(ent)) { return VIS_PVS; } } // check 360 degree visibility - //Meaning has to be a direct line of site - if ( flags & CHECK_360 ) - { - if ( !CanSee ( ent ) ) - { + // Meaning has to be a direct line of site + if (flags & CHECK_360) { + if (!CanSee(ent)) { return VIS_PVS; } } - if ( !(flags & (CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_FOV | CHECK_SHOOT))) { return VIS_360; } // check FOV - if ( flags & CHECK_FOV ) - { - if ( !InFOV ( ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) ) - { + if (flags & CHECK_FOV) { + if (!InFOV(ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov)) { return VIS_360; } } - if ( !(flags & CHECK_SHOOT) ) - { + if (!(flags & CHECK_SHOOT)) { return VIS_FOV; } // check shootability - if ( flags & CHECK_SHOOT ) - { - if ( !CanShoot ( ent, NPC ) ) - { + if (flags & CHECK_SHOOT) { + if (!CanShoot(ent, NPC)) { return VIS_FOV; } } @@ -437,59 +382,55 @@ visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) NPC_CheckSoundEvents ------------------------- */ -static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel, qboolean onGroundOnly ) -{ - int bestEvent = -1; +static int G_CheckSoundEvents(gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel, qboolean onGroundOnly) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; + int bestTime = -1; float dist, radius; maxHearDist *= maxHearDist; - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( level.alertEvents[i].ID == ignoreAlert ) + for (int i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (level.alertEvents[i].ID == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SOUND ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SOUND) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //must be on the ground? - if ( onGroundOnly && !level.alertEvents[i].onGround ) + // must be on the ground? + if (onGroundOnly && !level.alertEvents[i].onGround) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->currentOrigin); - //can't hear it - if ( dist > maxHearDist ) + // can't hear it + if (dist > maxHearDist) continue; - if ( self->client && self->client->NPC_class != CLASS_SAND_CREATURE ) - {//sand creatures hear all in within their earshot, regardless of quietness and alert sound radius! + if (self->client && self->client->NPC_class != + CLASS_SAND_CREATURE) { // sand creatures hear all in within their earshot, regardless of quietness and alert sound radius! radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - if ( level.alertEvents[i].addLight ) - {//a quiet sound, must have LOS to hear it - if ( G_ClearLOS( self, level.alertEvents[i].position ) == qfalse ) - {//no LOS, didn't hear it + if (level.alertEvents[i].addLight) { // a quiet sound, must have LOS to hear it + if (G_ClearLOS(self, level.alertEvents[i].position) == qfalse) { // no LOS, didn't hear it continue; } } } - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -499,14 +440,13 @@ static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAle return bestEvent; } -float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) -{ - vec3_t ambient={0}, directed, lightDir; - float lightLevel; +float G_GetLightLevel(vec3_t pos, vec3_t fromDir) { + vec3_t ambient = {0}, directed, lightDir; + float lightLevel; - cgi_R_GetLighting( pos, ambient, directed, lightDir ); + cgi_R_GetLighting(pos, ambient, directed, lightDir); - lightLevel = VectorLength( ambient ) + (VectorLength( directed )*DotProduct( lightDir, fromDir )); + lightLevel = VectorLength(ambient) + (VectorLength(directed) * DotProduct(lightDir, fromDir)); return lightLevel; } @@ -515,58 +455,56 @@ float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) NPC_CheckSightEvents ------------------------- */ -static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - int bestEvent = -1; +static int G_CheckSightEvents(gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; - float dist, radius; + int bestTime = -1; + float dist, radius; maxSeeDist *= maxSeeDist; - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( level.alertEvents[i].ID == ignoreAlert ) + for (int i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (level.alertEvents[i].ID == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SIGHT ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SIGHT) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->currentOrigin); - //can't see it - if ( dist > maxSeeDist ) + // can't see it + if (dist > maxSeeDist) continue; radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - //Must be visible - if ( InFOV( level.alertEvents[i].position, self, hFOV, vFOV ) == qfalse ) + // Must be visible + if (InFOV(level.alertEvents[i].position, self, hFOV, vFOV) == qfalse) continue; - if ( G_ClearLOS( self, level.alertEvents[i].position ) == qfalse ) + if (G_ClearLOS(self, level.alertEvents[i].position) == qfalse) continue; - //FIXME: possibly have the light level at this point affect the + // FIXME: possibly have the light level at this point affect the // visibility/alert level of this event? Would also // need to take into account how bright the event // itself is. A lightsaber would stand out more // in the dark... maybe pass in a light level that // is added to the actual light level at this position? - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -576,29 +514,24 @@ static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSee return bestEvent; } -qboolean G_RememberAlertEvent( gentity_t *self, int alertIndex ) -{ - if ( !self || !self->NPC ) - {//not a valid ent +qboolean G_RememberAlertEvent(gentity_t *self, int alertIndex) { + if (!self || !self->NPC) { // not a valid ent return qfalse; } - if ( alertIndex == -1 ) - {//not a valid event + if (alertIndex == -1) { // not a valid event return qfalse; } // Get The Event Struct //---------------------- - alertEvent_t& at = level.alertEvents[alertIndex]; + alertEvent_t &at = level.alertEvents[alertIndex]; - if ( at.ID == self->NPC->lastAlertID ) - {//already know this one + if (at.ID == self->NPC->lastAlertID) { // already know this one return qfalse; } - if (at.owner==self) - {//don't care about events that I made + if (at.owner == self) { // don't care about events that I made return qfalse; } @@ -606,12 +539,11 @@ qboolean G_RememberAlertEvent( gentity_t *self, int alertIndex ) // Now, If It Is Dangerous Enough, We Want To Register This With The Pathfinding System //-------------------------------------------------------------------------------------- - bool IsDangerous = (at.level >= AEL_DANGER); - bool IsFromNPC = (at.owner && at.owner->client); - bool IsFromEnemy = (IsFromNPC && at.owner->client->playerTeam!=self->client->playerTeam); + bool IsDangerous = (at.level >= AEL_DANGER); + bool IsFromNPC = (at.owner && at.owner->client); + bool IsFromEnemy = (IsFromNPC && at.owner->client->playerTeam != self->client->playerTeam); - if (IsDangerous && (!IsFromNPC || IsFromEnemy)) - { + if (IsDangerous && (!IsFromNPC || IsFromEnemy)) { NAV::RegisterDangerSense(self, alertIndex); } @@ -621,15 +553,14 @@ qboolean G_RememberAlertEvent( gentity_t *self, int alertIndex ) ------------------------- NPC_CheckAlertEvents - NOTE: Should all NPCs create alertEvents too so they can detect each other? + NOTE: Should all NPCs create alertEvents too so they can detect each other? ------------------------- */ -int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel, qboolean onGroundOnly ) -{ - if ( &g_entities[0] == NULL || g_entities[0].health <= 0 ) - { - //player is dead +int G_CheckAlertEvents(gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, + int minAlertLevel, qboolean onGroundOnly) { + if (&g_entities[0] == NULL || g_entities[0].health <= 0) { + // player is dead return -1; } @@ -638,115 +569,96 @@ int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSoun int bestSoundAlert = -1; int bestSightAlert = -1; - if ( checkSound ) - { - //get sound event - bestSoundEvent = G_CheckSoundEvents( self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel, onGroundOnly ); - //get sound event alert level - if ( bestSoundEvent >= 0 ) - { + if (checkSound) { + // get sound event + bestSoundEvent = G_CheckSoundEvents(self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel, onGroundOnly); + // get sound event alert level + if (bestSoundEvent >= 0) { bestSoundAlert = level.alertEvents[bestSoundEvent].level; } } - if ( checkSight ) - { - //get sight event - if ( self->NPC ) - { - bestSightEvent = G_CheckSightEvents( self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel ); - } - else - { - bestSightEvent = G_CheckSightEvents( self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel );//FIXME: look at cg_view to get more accurate numbers? + if (checkSight) { + // get sight event + if (self->NPC) { + bestSightEvent = G_CheckSightEvents(self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); + } else { + bestSightEvent = + G_CheckSightEvents(self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); // FIXME: look at cg_view to get more accurate numbers? } - //get sight event alert level - if ( bestSightEvent >= 0 ) - { + // get sight event alert level + if (bestSightEvent >= 0) { bestSightAlert = level.alertEvents[bestSightEvent].level; } - //return the one that has a higher alert (or sound if equal) - //FIXME: This doesn't take the distance of the event into account - - if ( bestSightEvent >= 0 && bestSightAlert > bestSoundAlert ) - {//valid best sight event, more important than the sound event - //get the light level of the alert event for this checker - vec3_t eyePoint, sightDir; - //get eye point - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyePoint ); - VectorSubtract( level.alertEvents[bestSightEvent].position, eyePoint, sightDir ); - level.alertEvents[bestSightEvent].light = level.alertEvents[bestSightEvent].addLight + G_GetLightLevel( level.alertEvents[bestSightEvent].position, sightDir ); - //return the sight event - if ( G_RememberAlertEvent( self, bestSightEvent ) ) - { + // return the one that has a higher alert (or sound if equal) + // FIXME: This doesn't take the distance of the event into account + + if (bestSightEvent >= 0 && bestSightAlert > bestSoundAlert) { // valid best sight event, more important than the sound event + // get the light level of the alert event for this checker + vec3_t eyePoint, sightDir; + // get eye point + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyePoint); + VectorSubtract(level.alertEvents[bestSightEvent].position, eyePoint, sightDir); + level.alertEvents[bestSightEvent].light = + level.alertEvents[bestSightEvent].addLight + G_GetLightLevel(level.alertEvents[bestSightEvent].position, sightDir); + // return the sight event + if (G_RememberAlertEvent(self, bestSightEvent)) { return bestSightEvent; } } } - //return the sound event - if ( G_RememberAlertEvent( self, bestSoundEvent ) ) - { + // return the sound event + if (G_RememberAlertEvent(self, bestSoundEvent)) { return bestSoundEvent; } - //no event or no new event + // no event or no new event return -1; } -int NPC_CheckAlertEvents( qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel, qboolean onGroundOnly ) -{ - return G_CheckAlertEvents( NPC, checkSight, checkSound, NPCInfo->stats.visrange, NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, minAlertLevel, onGroundOnly ); +int NPC_CheckAlertEvents(qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel, qboolean onGroundOnly) { + return G_CheckAlertEvents(NPC, checkSight, checkSound, NPCInfo->stats.visrange, NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, minAlertLevel, + onGroundOnly); } -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); +extern void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); -qboolean G_CheckForDanger( gentity_t *self, int alertEvent ) -{//FIXME: more bStates need to call this? - if ( alertEvent == -1 ) - { +qboolean G_CheckForDanger(gentity_t *self, int alertEvent) { // FIXME: more bStates need to call this? + if (alertEvent == -1) { return qfalse; } - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || (level.alertEvents[alertEvent].owner!=self&&level.alertEvents[alertEvent].owner->client->playerTeam!=self->client->playerTeam) ) - { - if ( self->NPC ) - { - if ( self->NPC->scriptFlags & SCF_DONT_FLEE ) - {//can't flee + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != self && level.alertEvents[alertEvent].owner->client->playerTeam != self->client->playerTeam)) { + if (self->NPC) { + if (self->NPC->scriptFlags & SCF_DONT_FLEE) { // can't flee return qfalse; - } - else - { - if ( level.alertEvents[alertEvent].level >= AEL_DANGER_GREAT || self->s.weapon == WP_NONE || self->s.weapon == WP_MELEE ) - {//flee for a longer period of time - NPC_StartFlee( level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, 6000 ); - } - else if ( !Q_irand( 0, 10 ) )//FIXME: base on rank? aggression? - {//just normal danger and I have a weapon, so just a 25% chance of fleeing only for a few seconds - //FIXME: used to just find a better combat point, need that functionality back - NPC_StartFlee( level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 1000, 3000 ); - } - else - {//didn't flee - TIMER_Set( NPC, "duck", 2000); // something dangerous going on... + } else { + if (level.alertEvents[alertEvent].level >= AEL_DANGER_GREAT || self->s.weapon == WP_NONE || + self->s.weapon == WP_MELEE) { // flee for a longer period of time + NPC_StartFlee(level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, + 6000); + } else if (!Q_irand(0, 10)) // FIXME: base on rank? aggression? + { // just normal danger and I have a weapon, so just a 25% chance of fleeing only for a few seconds + // FIXME: used to just find a better combat point, need that functionality back + NPC_StartFlee(level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 1000, + 3000); + } else { // didn't flee + TIMER_Set(NPC, "duck", 2000); // something dangerous going on... return qfalse; } return qtrue; } - } - else - { + } else { return qtrue; } } } return qfalse; } -qboolean NPC_CheckForDanger( int alertEvent ) -{//FIXME: more bStates need to call this? - return G_CheckForDanger( NPC, alertEvent ); +qboolean NPC_CheckForDanger(int alertEvent) { // FIXME: more bStates need to call this? + return G_CheckForDanger(NPC, alertEvent); } /* @@ -754,52 +666,45 @@ qboolean NPC_CheckForDanger( int alertEvent ) AddSoundEvent ------------------------- */ -qboolean RemoveOldestAlert( void ); -void AddSoundEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS, qboolean onGround ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +qboolean RemoveOldestAlert(void); +void AddSoundEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS, qboolean onGround) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: why are Sand creatures suddenly crashlanding? - if ( owner && owner->client && owner->client->NPC_class == CLASS_SAND_CREATURE ) - { + // FIXME: why are Sand creatures suddenly crashlanding? + if (owner && owner->client && owner->client->NPC_class == CLASS_SAND_CREATURE) { return; } - //FIXME: if owner is not a player or player ally, and there are no player allies present, + // FIXME: if owner is not a player or player ally, and there are no player allies present, // perhaps we don't need to store the alert... unless we want the player to // react to enemy alert events in some way? #ifdef _DEBUG - assert( !Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2]) ); + assert(!Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2])); #endif - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); - - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SOUND; - level.alertEvents[ level.numAlertEvents ].owner = owner; - if ( needLOS ) - {//a very low-level sound, when check this sound event, check for LOS - level.alertEvents[ level.numAlertEvents ].addLight = 1; //will force an LOS trace on this sound - } - else - { - level.alertEvents[ level.numAlertEvents ].addLight = 0; //will force an LOS trace on this sound + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); + + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SOUND; + level.alertEvents[level.numAlertEvents].owner = owner; + if (needLOS) { // a very low-level sound, when check this sound event, check for LOS + level.alertEvents[level.numAlertEvents].addLight = 1; // will force an LOS trace on this sound + } else { + level.alertEvents[level.numAlertEvents].addLight = 0; // will force an LOS trace on this sound } - level.alertEvents[ level.numAlertEvents ].onGround = onGround; + level.alertEvents[level.numAlertEvents].onGround = onGround; - level.alertEvents[ level.numAlertEvents ].ID = ++level.curAlertID; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].ID = ++level.curAlertID; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -809,36 +714,33 @@ AddSightEvent ------------------------- */ -void AddSightEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +void AddSightEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: if owner is not a player or player ally, and there are no player allies present, - // perhaps we don't need to store the alert... unless we want the player to - // react to enemy alert events in some way? + // FIXME: if owner is not a player or player ally, and there are no player allies present, + // perhaps we don't need to store the alert... unless we want the player to + // react to enemy alert events in some way? #ifdef _DEBUG - assert( !Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2]) ); + assert(!Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2])); #endif - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SIGHT; - level.alertEvents[ level.numAlertEvents ].owner = owner; - level.alertEvents[ level.numAlertEvents ].addLight = addLight; //will get added to actual light at that point when it's checked - level.alertEvents[ level.numAlertEvents ].ID = level.curAlertID++; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SIGHT; + level.alertEvents[level.numAlertEvents].owner = owner; + level.alertEvents[level.numAlertEvents].addLight = addLight; // will get added to actual light at that point when it's checked + level.alertEvents[level.numAlertEvents].ID = level.curAlertID++; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -849,74 +751,59 @@ ClearPlayerAlertEvents ------------------------- */ -void ClearPlayerAlertEvents( void ) -{ +void ClearPlayerAlertEvents(void) { int curNumAlerts = level.numAlertEvents; - //loop through them all (max 32) - for ( int i = 0; i < curNumAlerts; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time ) - {//this event has timed out - //drop the count + // loop through them all (max 32) + for (int i = 0; i < curNumAlerts; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time) { // this event has timed out + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (i+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[i], &level.alertEvents[i+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(i+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((i + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[i], &level.alertEvents[i + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (i + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[i], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[i], 0, sizeof(alertEvent_t)); } } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); + // make sure this never drops below zero... if it does, something very very bad happened + assert(level.numAlertEvents >= 0); - if ( eventClearTime < level.time ) - {//this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms + if (eventClearTime < + level.time) { // this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms eventClearTime = level.time + ALERT_CLEAR_TIME; } } -qboolean RemoveOldestAlert( void ) -{ - int oldestEvent = -1, oldestTime = Q3_INFINITE; - //loop through them all (max 32) - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp < oldestTime ) - { +qboolean RemoveOldestAlert(void) { + int oldestEvent = -1, oldestTime = Q3_INFINITE; + // loop through them all (max 32) + for (int i = 0; i < level.numAlertEvents; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp < oldestTime) { oldestEvent = i; oldestTime = level.alertEvents[i].timestamp; } } - if ( oldestEvent != -1 ) - { - //drop the count + if (oldestEvent != -1) { + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (oldestEvent+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(oldestEvent+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((oldestEvent + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (oldestEvent + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[oldestEvent], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[oldestEvent], 0, sizeof(alertEvent_t)); } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); - //return true is have room for one now - return (qboolean)(level.numAlertEvents= 0); + // return true is have room for one now + return (qboolean)(level.numAlertEvents < MAX_ALERT_EVENTS); } /* @@ -926,20 +813,16 @@ G_ClearLOS */ // Position to position -qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) -{ - trace_t tr; - int traceCount = 0; - - //FIXME: ENTITYNUM_NONE ok? - gi.trace ( &tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE/*CONTENTS_SOLID*//*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, (EG2_Collision)0, 0 ); - while ( tr.fraction < 1.0 && traceCount < 3 ) - {//can see through 3 panes of glass - if ( tr.entityNum < ENTITYNUM_WORLD ) - { - if ( &g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].svFlags&SVF_GLASS_BRUSH) ) - {//can see through glass, trace again, ignoring me - gi.trace ( &tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, (EG2_Collision)0, 0 ); +qboolean G_ClearLOS(gentity_t *self, const vec3_t start, const vec3_t end) { + trace_t tr; + int traceCount = 0; + + // FIXME: ENTITYNUM_NONE ok? + gi.trace(&tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE /*CONTENTS_SOLID*/ /*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, (EG2_Collision)0, 0); + while (tr.fraction < 1.0 && traceCount < 3) { // can see through 3 panes of glass + if (tr.entityNum < ENTITYNUM_WORLD) { + if (&g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].svFlags & SVF_GLASS_BRUSH)) { // can see through glass, trace again, ignoring me + gi.trace(&tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, (EG2_Collision)0, 0); traceCount++; continue; } @@ -947,62 +830,58 @@ qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) return qfalse; } - if ( tr.fraction == 1.0 ) + if (tr.fraction == 1.0) return qtrue; return qfalse; } -//Entity to position -qboolean G_ClearLOS( gentity_t *self, gentity_t *ent, const vec3_t end ) -{ - vec3_t eyes; +// Entity to position +qboolean G_ClearLOS(gentity_t *self, gentity_t *ent, const vec3_t end) { + vec3_t eyes; - CalcEntitySpot( ent, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(ent, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } -//Position to entity -qboolean G_ClearLOS( gentity_t *self, const vec3_t start, gentity_t *ent ) -{ - vec3_t spot; +// Position to entity +qboolean G_ClearLOS(gentity_t *self, const vec3_t start, gentity_t *ent) { + vec3_t spot; - //Look for the chest first - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); + // Look for the chest first + CalcEntitySpot(ent, SPOT_ORIGIN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; - //Look for the head next - CalcEntitySpot( ent, SPOT_HEAD_LEAN, spot ); + // Look for the head next + CalcEntitySpot(ent, SPOT_HEAD_LEAN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; return qfalse; } -//NPC's eyes to entity -qboolean G_ClearLOS( gentity_t *self, gentity_t *ent ) -{ - vec3_t eyes; +// NPC's eyes to entity +qboolean G_ClearLOS(gentity_t *self, gentity_t *ent) { + vec3_t eyes; - //Calculate my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); + // Calculate my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, ent ); + return G_ClearLOS(self, eyes, ent); } -//NPC's eyes to position -qboolean G_ClearLOS( gentity_t *self, const vec3_t end ) -{ - vec3_t eyes; +// NPC's eyes to position +qboolean G_ClearLOS(gentity_t *self, const vec3_t end) { + vec3_t eyes; - //Calculate the my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); + // Calculate the my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } /* @@ -1011,21 +890,20 @@ NPC_GetFOVPercentage ------------------------- */ -float NPC_GetHFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float hFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetHFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float hFOV) { + vec3_t deltaVector, angles; + float delta; - VectorSubtract ( spot, from, deltaVector ); + VectorSubtract(spot, from, deltaVector); - vectoangles ( deltaVector, angles ); + vectoangles(deltaVector, angles); - delta = fabs( AngleDelta ( facing[YAW], angles[YAW] ) ); + delta = fabs(AngleDelta(facing[YAW], angles[YAW])); - if ( delta > hFOV ) + if (delta > hFOV) return 0.0f; - return ( ( hFOV - delta ) / hFOV ); + return ((hFOV - delta) / hFOV); } /* @@ -1034,64 +912,56 @@ NPC_GetVFOVPercentage ------------------------- */ -float NPC_GetVFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float vFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetVFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float vFOV) { + vec3_t deltaVector, angles; + float delta; - VectorSubtract ( spot, from, deltaVector ); + VectorSubtract(spot, from, deltaVector); - vectoangles ( deltaVector, angles ); + vectoangles(deltaVector, angles); - delta = fabs( AngleDelta ( facing[PITCH], angles[PITCH] ) ); + delta = fabs(AngleDelta(facing[PITCH], angles[PITCH])); - if ( delta > vFOV ) + if (delta > vFOV) return 0.0f; - return ( ( vFOV - delta ) / vFOV ); + return ((vFOV - delta) / vFOV); } -#define MAX_INTEREST_DIST ( 256 * 256 ) +#define MAX_INTEREST_DIST (256 * 256) /* ------------------------- NPC_FindLocalInterestPoint ------------------------- */ -int G_FindLocalInterestPoint( gentity_t *self ) -{ - int i, bestPoint = ENTITYNUM_NONE; - float dist, bestDist = Q3_INFINITE; - vec3_t diffVec, eyes; - - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); - for ( i = 0; i < level.numInterestPoints; i++ ) - { - //Don't ignore portals? If through a portal, need to look at portal! - if ( gi.inPVS( level.interestPoints[i].origin, eyes ) ) - { - VectorSubtract( level.interestPoints[i].origin, eyes, diffVec ); - if ( (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && - fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 ) - {//Too close to look so far up or down +int G_FindLocalInterestPoint(gentity_t *self) { + int i, bestPoint = ENTITYNUM_NONE; + float dist, bestDist = Q3_INFINITE; + vec3_t diffVec, eyes; + + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); + for (i = 0; i < level.numInterestPoints; i++) { + // Don't ignore portals? If through a portal, need to look at portal! + if (gi.inPVS(level.interestPoints[i].origin, eyes)) { + VectorSubtract(level.interestPoints[i].origin, eyes, diffVec); + if ((fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && + fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2) { // Too close to look so far up or down continue; } - dist = VectorLengthSquared( diffVec ); - //Some priority to more interesting points - //dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); - if ( dist < MAX_INTEREST_DIST && dist < bestDist ) - { - if ( G_ClearLineOfSight( eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE ) ) - { + dist = VectorLengthSquared(diffVec); + // Some priority to more interesting points + // dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); + if (dist < MAX_INTEREST_DIST && dist < bestDist) { + if (G_ClearLineOfSight(eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE)) { bestDist = dist; bestPoint = i; } } } } - if ( bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target ) - { - G_UseTargets2( self, self, level.interestPoints[bestPoint].target ); + if (bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target) { + G_UseTargets2(self, self, level.interestPoints[bestPoint].target); } return bestPoint; } @@ -1102,10 +972,8 @@ A point that a squadmate will look at if standing still target - thing to fire when someone looks at this thing */ -void SP_target_interest( gentity_t *self ) -{//FIXME: rename point_interest - if(level.numInterestPoints >= MAX_INTEREST_POINTS) - { +void SP_target_interest(gentity_t *self) { // FIXME: rename point_interest + if (level.numInterestPoints >= MAX_INTEREST_POINTS) { gi.Printf("ERROR: Too many interest points, limit is %d\n", MAX_INTEREST_POINTS); G_FreeEntity(self); return; @@ -1113,9 +981,8 @@ void SP_target_interest( gentity_t *self ) VectorCopy(self->currentOrigin, level.interestPoints[level.numInterestPoints].origin); - if(self->target && self->target[0]) - { - level.interestPoints[level.numInterestPoints].target = G_NewString( self->target ); + if (self->target && self->target[0]) { + level.interestPoints[level.numInterestPoints].target = G_NewString(self->target); } level.numInterestPoints++; diff --git a/code/game/NPC_sounds.cpp b/code/game/NPC_sounds.cpp index 4f2ca84a68..4f6663943b 100644 --- a/code/game/NPC_sounds.cpp +++ b/code/game/NPC_sounds.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_sounds.cpp +// NPC_sounds.cpp #include "b_local.h" #include "Q3_Interface.h" @@ -42,93 +42,80 @@ void NPC_AngerSound (void) } */ -extern void G_SpeechEvent( gentity_t *self, int event ); -void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ) -{ - if ( !self->NPC ) - { +extern void G_SpeechEvent(gentity_t *self, int event); +void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime) { + if (!self->NPC) { return; } - if ( !self->client || self->client->ps.pm_type >= PM_DEAD ) - { + if (!self->client || self->client->ps.pm_type >= PM_DEAD) { return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - if ( Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { + if (Q3_TaskIDPending(self, TID_CHAN_VOICE)) { return; } - if ( self->client && self->client->NPC_class == CLASS_SABOTEUR ) - { - if ( self->client->ps.powerups[PW_CLOAKED] - || self->client->ps.powerups[PW_UNCLOAKING] > level.time ) - {//I'm cloaked (or still decloaking), so don't talk and give away my position... - //don't make any combat voice noises, but still make pain and death sounds - if ( (event >= EV_ANGER1 && event <= EV_VICTORY3) - || (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5) ) - { + if (self->client && self->client->NPC_class == CLASS_SABOTEUR) { + if (self->client->ps.powerups[PW_CLOAKED] || + self->client->ps.powerups[PW_UNCLOAKING] > level.time) { // I'm cloaked (or still decloaking), so don't talk and give away my position... + // don't make any combat voice noises, but still make pain and death sounds + if ((event >= EV_ANGER1 && event <= EV_VICTORY3) || (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5)) { return; } - if ( event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5 ) - { + if (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5) { return; } } } - if ( (self->NPC->scriptFlags&SCF_NO_COMBAT_TALK) && ( (event >= EV_ANGER1 && event <= EV_VICTORY3) || (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5) ) )//(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) + if ((self->NPC->scriptFlags & SCF_NO_COMBAT_TALK) && + ((event >= EV_ANGER1 && event <= EV_VICTORY3) || + (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5))) //(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) { return; } - if ( (self->NPC->scriptFlags&SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5) ) - { + if ((self->NPC->scriptFlags & SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5)) { return; } - //FIXME: Also needs to check for teammates. Don't want + // FIXME: Also needs to check for teammates. Don't want // everyone babbling at once - //NOTE: was losing too many speech events, so we do it directly now, screw networking! - //G_AddEvent( self, event, 0 ); - G_SpeechEvent( self, event ); + // NOTE: was losing too many speech events, so we do it directly now, screw networking! + // G_AddEvent( self, event, 0 ); + G_SpeechEvent(self, event); - //won't speak again for 5 seconds (unless otherwise specified) - self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime==0) ? 5000 : speakDebounceTime); + // won't speak again for 5 seconds (unless otherwise specified) + self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime == 0) ? 5000 : speakDebounceTime); } -void NPC_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->enemy ||//was mad - !TIMER_Done( self, "enemyLastVisible" ) ||//saw something suspicious - self->client->renderInfo.lookTarget == 0//was looking at player - ) - { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE2, EV_CONFUSE3 ), 2000 ); - } - else if ( self->NPC && self->NPC->investigateDebounceTime+self->NPC->pauseTime > level.time )//was checking something out +void NPC_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->enemy || // was mad + !TIMER_Done(self, "enemyLastVisible") || // saw something suspicious + self->client->renderInfo.lookTarget == 0 // was looking at player + ) { + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE2, EV_CONFUSE3), 2000); + } else if (self->NPC && self->NPC->investigateDebounceTime + self->NPC->pauseTime > level.time) // was checking something out { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, EV_CONFUSE1, 2000 ); + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, EV_CONFUSE1, 2000); } - //G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + // G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } diff --git a/code/game/NPC_spawn.cpp b/code/game/NPC_spawn.cpp index 7e3f820a89..e7008ad442 100644 --- a/code/game/NPC_spawn.cpp +++ b/code/game/NPC_spawn.cpp @@ -20,8 +20,8 @@ along with this program; if not, see . =========================================================================== */ -//b_spawn.cpp -//added by MCG +// b_spawn.cpp +// added by MCG #include "../cgame/cg_local.h" #include "Q3_Interface.h" @@ -31,24 +31,23 @@ along with this program; if not, see . #include "wp_saber.h" #include "g_vehicles.h" -extern qboolean G_CheckInSolid (gentity_t *self, qboolean fix); -extern void ClientUserinfoChanged( int clientNum ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -extern void Jedi_Cloak( gentity_t *self ); -extern void Saboteur_Cloak( gentity_t *self ); +extern qboolean G_CheckInSolid(gentity_t *self, qboolean fix); +extern void ClientUserinfoChanged(int clientNum); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +extern void Jedi_Cloak(gentity_t *self); +extern void Saboteur_Cloak(gentity_t *self); -extern void G_MatchPlayerWeapon( gentity_t *ent ); -extern void Q3_SetParm (int entID, int parmNum, const char *parmValue); +extern void G_MatchPlayerWeapon(gentity_t *ent); +extern void Q3_SetParm(int entID, int parmNum, const char *parmValue); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); - -extern int WP_SaberInitBladeData( gentity_t *ent ); -extern void ST_ClearTimers( gentity_t *ent ); -extern void Jedi_ClearTimers( gentity_t *ent ); -extern void Howler_ClearTimers( gentity_t *self ); -#define NSF_DROP_TO_FLOOR 16 +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern int WP_SaberInitBladeData(gentity_t *ent); +extern void ST_ClearTimers(gentity_t *ent); +extern void Jedi_ClearTimers(gentity_t *ent); +extern void Howler_ClearTimers(gentity_t *self); +#define NSF_DROP_TO_FLOOR 16 /* ------------------------- @@ -56,16 +55,12 @@ NPC_PainFunc ------------------------- */ -painFunc_t NPC_PainFunc( gentity_t *ent ) -{ - painFunc_t func; +painFunc_t NPC_PainFunc(gentity_t *ent) { + painFunc_t func; - if ( ent->client->ps.weapon == WP_SABER ) - { + if (ent->client->ps.weapon == WP_SABER) { func = painF_NPC_Jedi_Pain; - } - else - { + } else { // team no longer indicates race/species, use NPC_class to determine different npc types /* switch ( ent->client->playerTeam ) @@ -75,8 +70,7 @@ painFunc_t NPC_PainFunc( gentity_t *ent ) break; } */ - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { // troopers get special pain case CLASS_SABOTEUR: case CLASS_STORMTROOPER: @@ -146,37 +140,29 @@ painFunc_t NPC_PainFunc( gentity_t *ent ) func = painF_NPC_Pain; break; } - } return func; } - /* ------------------------- NPC_TouchFunc ------------------------- */ -touchFunc_t NPC_TouchFunc( gentity_t *ent ) -{ - return touchF_NPC_Touch; -} +touchFunc_t NPC_TouchFunc(gentity_t *ent) { return touchF_NPC_Touch; } /* ------------------------- NPC_SetMiscDefaultData ------------------------- */ -void G_ClassSetDontFlee( gentity_t *self ) -{ - if ( !self || !self->client || !self->NPC ) - { +void G_ClassSetDontFlee(gentity_t *self) { + if (!self || !self->client || !self->NPC) { return; } - switch ( self->client->NPC_class ) - { + switch (self->client->NPC_class) { case CLASS_ATST: case CLASS_CLAW: case CLASS_DESANN: @@ -186,24 +172,24 @@ void G_ClassSetDontFlee( gentity_t *self ) case CLASS_GLIDER: case CLASS_RANCOR: case CLASS_SAND_CREATURE: - case CLASS_INTERROGATOR: // droid + case CLASS_INTERROGATOR: // droid case CLASS_JAN: case CLASS_JEDI: case CLASS_KYLE: case CLASS_LANDO: case CLASS_LIZARD: case CLASS_LUKE: - case CLASS_MARK1: // droid - case CLASS_MARK2: // droid - case CLASS_GALAKMECH: // droid + case CLASS_MARK1: // droid + case CLASS_MARK2: // droid + case CLASS_GALAKMECH: // droid case CLASS_MONMOTHA: case CLASS_MORGANKATARN: case CLASS_MURJJ: - case CLASS_PROBE: // droid + case CLASS_PROBE: // droid case CLASS_REBORN: case CLASS_REELO: case CLASS_REMOTE: - case CLASS_SEEKER: // droid + case CLASS_SEEKER: // droid case CLASS_SENTRY: case CLASS_SHADOWTROOPER: case CLASS_SWAMP: @@ -219,243 +205,178 @@ void G_ClassSetDontFlee( gentity_t *self ) default: break; } - if ( (self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) - { + if ((self->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) { self->NPC->scriptFlags |= SCF_DONT_FLEE; } - if ( (self->NPC->aiFlags&NPCAI_SUBBOSS_CHARACTER) ) - { + if ((self->NPC->aiFlags & NPCAI_SUBBOSS_CHARACTER)) { self->NPC->scriptFlags |= SCF_DONT_FLEE; } - if ( (self->NPC->aiFlags&NPCAI_ROSH) ) - { + if ((self->NPC->aiFlags & NPCAI_ROSH)) { self->NPC->scriptFlags |= SCF_DONT_FLEE; } - if ( (self->NPC->aiFlags&NPCAI_HEAL_ROSH) ) - { + if ((self->NPC->aiFlags & NPCAI_HEAL_ROSH)) { self->NPC->scriptFlags |= SCF_DONT_FLEE; } } -extern void Vehicle_Register(gentity_t *ent); -extern void RT_FlyStart( gentity_t *self ); -extern void SandCreature_ClearTimers( gentity_t *ent ); -void NPC_SetMiscDefaultData( gentity_t *ent ) -{ - if ( ent->spawnflags & SFB_CINEMATIC ) - {//if a cinematic guy, default us to wait bState +extern void Vehicle_Register(gentity_t *ent); +extern void RT_FlyStart(gentity_t *self); +extern void SandCreature_ClearTimers(gentity_t *ent); +void NPC_SetMiscDefaultData(gentity_t *ent) { + if (ent->spawnflags & SFB_CINEMATIC) { // if a cinematic guy, default us to wait bState ent->NPC->behaviorState = BS_CINEMATIC; } - if ( ent->client->NPC_class == CLASS_RANCOR ) - { - if ( Q_stricmp( "mutant_rancor", ent->NPC_type ) == 0 ) - { - ent->spawnflags |= 1;//just so I know it's a mutant rancor as opposed to a normal one + if (ent->client->NPC_class == CLASS_RANCOR) { + if (Q_stricmp("mutant_rancor", ent->NPC_type) == 0) { + ent->spawnflags |= 1; // just so I know it's a mutant rancor as opposed to a normal one ent->NPC->aiFlags |= NPCAI_NAV_THROUGH_BREAKABLES; ent->mass = 2000; - } - else - { + } else { ent->NPC->aiFlags |= NPCAI_NAV_THROUGH_BREAKABLES; ent->mass = 1000; } ent->flags |= FL_NO_KNOCKBACK; - } - else if ( ent->client->NPC_class == CLASS_SAND_CREATURE ) - {//??? - ent->clipmask = CONTENTS_SOLID|CONTENTS_MONSTERCLIP;//it can go through others - ent->contents = 0;//can't be hit? - ent->takedamage = qfalse;//can't be killed + } else if (ent->client->NPC_class == CLASS_SAND_CREATURE) { //??? + ent->clipmask = CONTENTS_SOLID | CONTENTS_MONSTERCLIP; // it can go through others + ent->contents = 0; // can't be hit? + ent->takedamage = qfalse; // can't be killed ent->flags |= FL_NO_KNOCKBACK; - SandCreature_ClearTimers( ent ); - } - else if ( ent->client->NPC_class == CLASS_BOBAFETT ) - {//set some stuff, precache - ent->client->ps.forcePowersKnown |= ( 1 << FP_LEVITATION ); + SandCreature_ClearTimers(ent); + } else if (ent->client->NPC_class == CLASS_BOBAFETT) { // set some stuff, precache + ent->client->ps.forcePowersKnown |= (1 << FP_LEVITATION); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; - ent->client->ps.forcePower = 100; - ent->NPC->scriptFlags |= (SCF_NAV_CAN_FLY|SCF_FLY_WITH_JET|SCF_NAV_CAN_JUMP); - NPC->flags |= FL_UNDYING; // Can't Kill Boba - } - else if ( ent->client->NPC_class == CLASS_ROCKETTROOPER ) - {//set some stuff, precache - ent->client->ps.forcePowersKnown |= ( 1 << FP_LEVITATION ); + ent->client->ps.forcePower = 100; + ent->NPC->scriptFlags |= (SCF_NAV_CAN_FLY | SCF_FLY_WITH_JET | SCF_NAV_CAN_JUMP); + NPC->flags |= FL_UNDYING; // Can't Kill Boba + } else if (ent->client->NPC_class == CLASS_ROCKETTROOPER) { // set some stuff, precache + ent->client->ps.forcePowersKnown |= (1 << FP_LEVITATION); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.forcePower = 100; - ent->NPC->scriptFlags |= (SCF_NAV_CAN_FLY|SCF_FLY_WITH_JET|SCF_NAV_CAN_JUMP);//no groups, no combat points! - if ( Q_stricmp( "rockettrooper2Officer", ent->NPC_type ) == 0 ) - {//start in the air, use spotlight - //ent->NPC->scriptFlags |= SCF_NO_GROUPS; + ent->NPC->scriptFlags |= (SCF_NAV_CAN_FLY | SCF_FLY_WITH_JET | SCF_NAV_CAN_JUMP); // no groups, no combat points! + if (Q_stricmp("rockettrooper2Officer", ent->NPC_type) == 0) { // start in the air, use spotlight + // ent->NPC->scriptFlags |= SCF_NO_GROUPS; ent->NPC->scriptFlags &= ~SCF_FLY_WITH_JET; - RT_FlyStart( ent ); - NPC_SetMoveGoal( ent, ent->currentOrigin, 16, qfalse, -1, NULL ); - VectorCopy( ent->currentOrigin, ent->pos1 ); + RT_FlyStart(ent); + NPC_SetMoveGoal(ent, ent->currentOrigin, 16, qfalse, -1, NULL); + VectorCopy(ent->currentOrigin, ent->pos1); } - if ( (ent->spawnflags&2) ) - {//spotlight + if ((ent->spawnflags & 2)) { // spotlight ent->client->ps.eFlags |= EF_SPOTLIGHT; } - } - else if (ent->client->NPC_class == CLASS_SABER_DROID) - { + } else if (ent->client->NPC_class == CLASS_SABER_DROID) { ent->flags |= FL_NO_KNOCKBACK; - } - else if ( ent->client->NPC_class == CLASS_SABOTEUR ) - {//can cloak - ent->NPC->aiFlags |= NPCAI_SHIELDS;//give them the ability to cloak - if ( (ent->spawnflags&16) ) - {//start cloaked - Saboteur_Cloak( ent ); - } - } - else if ( ent->client->NPC_class == CLASS_ASSASSIN_DROID ) - { - ent->client->ps.stats[STAT_ARMOR] = 250; // start with full armor - if (ent->s.weapon==WP_BLASTER) - { + } else if (ent->client->NPC_class == CLASS_SABOTEUR) { // can cloak + ent->NPC->aiFlags |= NPCAI_SHIELDS; // give them the ability to cloak + if ((ent->spawnflags & 16)) { // start cloaked + Saboteur_Cloak(ent); + } + } else if (ent->client->NPC_class == CLASS_ASSASSIN_DROID) { + ent->client->ps.stats[STAT_ARMOR] = 250; // start with full armor + if (ent->s.weapon == WP_BLASTER) { ent->NPC->scriptFlags |= SCF_ALT_FIRE; } ent->flags |= (FL_NO_KNOCKBACK); } - if (ent->spawnflags&4096) - { - ent->NPC->scriptFlags |= SCF_NO_GROUPS;//don't use combat points or group AI + if (ent->spawnflags & 4096) { + ent->NPC->scriptFlags |= SCF_NO_GROUPS; // don't use combat points or group AI } - if ( Q_stricmp( "DKothos", ent->NPC_type ) == 0 - || Q_stricmp( "VKothos", ent->NPC_type ) == 0 ) - { + if (Q_stricmp("DKothos", ent->NPC_type) == 0 || Q_stricmp("VKothos", ent->NPC_type) == 0) { ent->NPC->scriptFlags |= SCF_DONT_FIRE; ent->NPC->aiFlags |= NPCAI_HEAL_ROSH; ent->count = 100; - } - else if ( Q_stricmp( "rosh_dark", ent->NPC_type ) == 0 ) - { + } else if (Q_stricmp("rosh_dark", ent->NPC_type) == 0) { ent->NPC->aiFlags |= NPCAI_ROSH; } - if ( Q_stricmpn( ent->NPC_type, "hazardtrooper", 13 ) == 0 ) - {//hazard trooper - ent->NPC->scriptFlags |= SCF_NO_GROUPS;//don't use combat points or group AI - ent->flags |= (FL_SHIELDED|FL_NO_KNOCKBACK);//low-level shots bounce off, no knockback + if (Q_stricmpn(ent->NPC_type, "hazardtrooper", 13) == 0) { // hazard trooper + ent->NPC->scriptFlags |= SCF_NO_GROUPS; // don't use combat points or group AI + ent->flags |= (FL_SHIELDED | FL_NO_KNOCKBACK); // low-level shots bounce off, no knockback } - if ( !Q_stricmp( "Yoda", ent->NPC_type ) ) - {//FIXME: extern this into NPC.cfg? - ent->NPC->scriptFlags |= SCF_NO_FORCE;//force powers don't work on him + if (!Q_stricmp("Yoda", ent->NPC_type)) { // FIXME: extern this into NPC.cfg? + ent->NPC->scriptFlags |= SCF_NO_FORCE; // force powers don't work on him ent->NPC->aiFlags |= NPCAI_BOSS_CHARACTER; } - if ( !Q_stricmp( "emperor", ent->NPC_type ) - || !Q_stricmp( "cultist_grip", ent->NPC_type ) - || !Q_stricmp( "cultist_drain", ent->NPC_type ) - || !Q_stricmp( "cultist_lightning", ent->NPC_type )) - {//FIXME: extern this into NPC.cfg? - ent->NPC->scriptFlags |= SCF_DONT_FIRE;//so he uses only force powers + if (!Q_stricmp("emperor", ent->NPC_type) || !Q_stricmp("cultist_grip", ent->NPC_type) || !Q_stricmp("cultist_drain", ent->NPC_type) || + !Q_stricmp("cultist_lightning", ent->NPC_type)) { // FIXME: extern this into NPC.cfg? + ent->NPC->scriptFlags |= SCF_DONT_FIRE; // so he uses only force powers } - if (!Q_stricmp( "Rax", ent->NPC_type ) ) - { + if (!Q_stricmp("Rax", ent->NPC_type)) { ent->NPC->scriptFlags |= SCF_DONT_FLEE; } - if ( !Q_stricmp( "cultist_destroyer", ent->NPC_type ) ) - { + if (!Q_stricmp("cultist_destroyer", ent->NPC_type)) { ent->splashDamage = 1000; ent->splashRadius = 384; - //FIXME: precache these! - ent->fxID = G_EffectIndex( "force/destruction_exp" ); - ent->NPC->scriptFlags |= (SCF_DONT_FLEE|SCF_IGNORE_ALERTS); + // FIXME: precache these! + ent->fxID = G_EffectIndex("force/destruction_exp"); + ent->NPC->scriptFlags |= (SCF_DONT_FLEE | SCF_IGNORE_ALERTS); ent->NPC->ignorePain = qtrue; } - if ( Q_stricmp( "chewie", ent->NPC_type ) ) - { - //in case chewie ever loses his gun... + if (Q_stricmp("chewie", ent->NPC_type)) { + // in case chewie ever loses his gun... ent->NPC->aiFlags |= NPCAI_HEAVY_MELEE; } //================== - if ( ent->client->ps.saber[0].type != SABER_NONE - && (!(ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON)||!ent->weaponModel[0]) ) - {//if I'm equipped with a saber, initialize it (them) + if (ent->client->ps.saber[0].type != SABER_NONE && + (!(ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) || !ent->weaponModel[0])) { // if I'm equipped with a saber, initialize it (them) ent->client->ps.SaberDeactivate(); - ent->client->ps.SetSaberLength( 0 ); - WP_SaberInitBladeData( ent ); - if ( ent->client->ps.weapon == WP_SABER ) - {//this is our current weapon, add the models now - WP_SaberAddG2SaberModels( ent ); + ent->client->ps.SetSaberLength(0); + WP_SaberInitBladeData(ent); + if (ent->client->ps.weapon == WP_SABER) { // this is our current weapon, add the models now + WP_SaberAddG2SaberModels(ent); } - Jedi_ClearTimers( ent ); + Jedi_ClearTimers(ent); } - if ( ent->client->ps.forcePowersKnown != 0 ) - { - WP_InitForcePowers( ent ); - if (ent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) - { - ent->NPC->scriptFlags |= SCF_NAV_CAN_JUMP; // anyone who has any force jump can jump + if (ent->client->ps.forcePowersKnown != 0) { + WP_InitForcePowers(ent); + if (ent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) { + ent->NPC->scriptFlags |= SCF_NAV_CAN_JUMP; // anyone who has any force jump can jump } } - if ( ent->client->NPC_class == CLASS_HOWLER ) - { - Howler_ClearTimers( ent ); + if (ent->client->NPC_class == CLASS_HOWLER) { + Howler_ClearTimers(ent); ent->NPC->scriptFlags |= SCF_NO_FALLTODEATH; ent->flags |= FL_NO_IMPACT_DMG; - ent->NPC->scriptFlags |= SCF_NAV_CAN_JUMP; // These jokers can jump - } - if ( ent->client->NPC_class == CLASS_DESANN - || ent->client->NPC_class == CLASS_TAVION - || ent->client->NPC_class == CLASS_LUKE - || ent->client->NPC_class == CLASS_KYLE - || Q_stricmp("tavion_scepter", ent->NPC_type ) == 0 - || Q_stricmp("alora_dual", ent->NPC_type ) == 0 ) - { - ent->NPC->aiFlags |= NPCAI_BOSS_CHARACTER; + ent->NPC->scriptFlags |= SCF_NAV_CAN_JUMP; // These jokers can jump } - else if ( Q_stricmp( "alora", ent->NPC_type ) == 0 - || Q_stricmp( "rosh_dark", ent->NPC_type ) == 0 ) - { + if (ent->client->NPC_class == CLASS_DESANN || ent->client->NPC_class == CLASS_TAVION || ent->client->NPC_class == CLASS_LUKE || + ent->client->NPC_class == CLASS_KYLE || Q_stricmp("tavion_scepter", ent->NPC_type) == 0 || Q_stricmp("alora_dual", ent->NPC_type) == 0) { + ent->NPC->aiFlags |= NPCAI_BOSS_CHARACTER; + } else if (Q_stricmp("alora", ent->NPC_type) == 0 || Q_stricmp("rosh_dark", ent->NPC_type) == 0) { ent->NPC->aiFlags |= NPCAI_SUBBOSS_CHARACTER; } - if ( ent->client->NPC_class == CLASS_TUSKEN ) - { - if ( g_spskill->integer > 1 ) - {//on hard, tusken raiders are faster than you + if (ent->client->NPC_class == CLASS_TUSKEN) { + if (g_spskill->integer > 1) { // on hard, tusken raiders are faster than you ent->NPC->stats.runSpeed = 280; ent->NPC->stats.walkSpeed = 65; } } //***I'm not sure whether I should leave this as a TEAM_ switch, I think NPC_class may be more appropriate - dmv - switch(ent->client->playerTeam) - { + switch (ent->client->playerTeam) { case TEAM_PLAYER: - //ent->flags |= FL_NO_KNOCKBACK; - if ( ent->client->NPC_class == CLASS_SEEKER ) - { + // ent->flags |= FL_NO_KNOCKBACK; + if (ent->client->NPC_class == CLASS_SEEKER) { ent->NPC->defaultBehavior = BS_DEFAULT; ent->client->ps.gravity = 0; ent->svFlags |= SVF_CUSTOM_GRAVITY; ent->client->moveType = MT_FLYSWIM; ent->count = 30; // SEEKER shot ammo count return; - } - else if ( ent->client->NPC_class == CLASS_JEDI - || ent->client->NPC_class == CLASS_KYLE - || ent->client->NPC_class == CLASS_LUKE ) - {//good jedi + } else if (ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_KYLE || ent->client->NPC_class == CLASS_LUKE) { // good jedi ent->client->enemyTeam = TEAM_ENEMY; - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher + if (ent->spawnflags & JSF_AMBUSH) { // ambusher ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = true;//hang + ent->client->noclip = true; // hang } - } - else - { - if (ent->client->ps.weapon != WP_NONE - && ent->client->ps.weapon != WP_SABER //sabers done above - && (!(ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON)||!ent->weaponModel[0]) )//they do this themselves + } else { + if (ent->client->ps.weapon != WP_NONE && ent->client->ps.weapon != WP_SABER // sabers done above + && (!(ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) || !ent->weaponModel[0])) // they do this themselves { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL://FIXME: new weapon: imp blaster pistol + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: // FIXME: new weapon: imp blaster pistol case WP_BLASTER_PISTOL: case WP_DISRUPTOR: case WP_BOWCASTER: @@ -468,223 +389,181 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) break; case WP_THERMAL: case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //ent->health = 25; - //FIXME: not necc. a ST - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL ) - {//officers, grenade-throwers use alt-fire - //ent->health = 50; - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // ent->health = 25; + // FIXME: not necc. a ST + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL) { // officers, grenade-throwers use alt-fire + // ent->health = 50; + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } break; } } - if ( ent->client->NPC_class == CLASS_PLAYER - || ent->client->NPC_class == CLASS_VEHICLE - || (ent->spawnflags & SFB_CINEMATIC) ) - { + if (ent->client->NPC_class == CLASS_PLAYER || ent->client->NPC_class == CLASS_VEHICLE || (ent->spawnflags & SFB_CINEMATIC)) { ent->NPC->defaultBehavior = BS_CINEMATIC; - } - else - { + } else { ent->NPC->defaultBehavior = BS_FOLLOW_LEADER; - ent->client->leader = &g_entities[0];//player + ent->client->leader = &g_entities[0]; // player } break; case TEAM_NEUTRAL: - if ( Q_stricmp( ent->NPC_type, "gonk" ) == 0 ) - { + if (Q_stricmp(ent->NPC_type, "gonk") == 0) { // I guess we generically make them player usable ent->svFlags |= SVF_PLAYER_USABLE; // Not even sure if we want to give different levels of batteries? ...Or even that these are the values we'd want to use. - switch ( g_spskill->integer ) - { - case 0: // EASY + switch (g_spskill->integer) { + case 0: // EASY ent->client->ps.batteryCharge = MAX_BATTERIES * 0.8f; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->client->ps.batteryCharge = MAX_BATTERIES * 0.75f; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->client->ps.batteryCharge = MAX_BATTERIES * 0.5f; break; } } break; - case TEAM_ENEMY: - { - ent->NPC->defaultBehavior = BS_DEFAULT; - if ( ent->client->NPC_class == CLASS_SHADOWTROOPER - && Q_stricmpn("shadowtrooper", ent->NPC_type, 13 ) == 0 ) - {//FIXME: a spawnflag? - Jedi_Cloak( ent ); - } - if( ent->client->NPC_class == CLASS_TAVION || - ent->client->NPC_class == CLASS_ALORA || - (ent->client->NPC_class == CLASS_REBORN && ent->client->ps.weapon == WP_SABER) || - ent->client->NPC_class == CLASS_DESANN || - ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - ent->client->enemyTeam = TEAM_PLAYER; - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher - ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = true;//hang - } + case TEAM_ENEMY: { + ent->NPC->defaultBehavior = BS_DEFAULT; + if (ent->client->NPC_class == CLASS_SHADOWTROOPER && Q_stricmpn("shadowtrooper", ent->NPC_type, 13) == 0) { // FIXME: a spawnflag? + Jedi_Cloak(ent); + } + if (ent->client->NPC_class == CLASS_TAVION || ent->client->NPC_class == CLASS_ALORA || + (ent->client->NPC_class == CLASS_REBORN && ent->client->ps.weapon == WP_SABER) || ent->client->NPC_class == CLASS_DESANN || + ent->client->NPC_class == CLASS_SHADOWTROOPER) { + ent->client->enemyTeam = TEAM_PLAYER; + if (ent->spawnflags & JSF_AMBUSH) { // ambusher + ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; + ent->client->noclip = true; // hang } - else if( ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || - ent->client->NPC_class == CLASS_INTERROGATOR || ent->client->NPC_class == CLASS_SENTRY) + } else if (ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_SENTRY) { + ent->NPC->defaultBehavior = BS_DEFAULT; + ent->client->ps.gravity = 0; + ent->svFlags |= SVF_CUSTOM_GRAVITY; + ent->client->moveType = MT_FLYSWIM; + } else { + if (ent->client->ps.weapon != WP_NONE && ent->client->ps.weapon != WP_SABER // sabers done above + && (!(ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) || !ent->weaponModel[0])) // they do this themselves { - ent->NPC->defaultBehavior = BS_DEFAULT; - ent->client->ps.gravity = 0; - ent->svFlags |= SVF_CUSTOM_GRAVITY; - ent->client->moveType = MT_FLYSWIM; + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } - else - { - if ( ent->client->ps.weapon != WP_NONE - && ent->client->ps.weapon != WP_SABER//sabers done above - && (!(ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON)||!ent->weaponModel[0]) )//they do this themselves - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: + break; + case WP_BLASTER_PISTOL: + NPCInfo->scriptFlags |= SCF_PILOT; + if (ent->client->NPC_class == CLASS_REBORN && ent->NPC->rank >= RANK_LT_COMM && + (!(ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) || !ent->weaponModel[0])) // they do this themselves + { // dual blaster pistols, so add the left-hand one, too + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handLBolt, 1); } - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL: - break; - case WP_BLASTER_PISTOL: - NPCInfo->scriptFlags |= SCF_PILOT; - if ( ent->client->NPC_class == CLASS_REBORN - && ent->NPC->rank >= RANK_LT_COMM - && (!(ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON)||!ent->weaponModel[0]) )//they do this themselves - {//dual blaster pistols, so add the left-hand one, too - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handLBolt, 1 ); - } - break; - case WP_DISRUPTOR: - //Sniper - //ent->NPC->scriptFlags |= SCF_ALT_FIRE;//FIXME: use primary fire sometimes? Up close? Different class of NPC? - break; - case WP_BOWCASTER: - NPCInfo->scriptFlags |= SCF_PILOT; - break; - case WP_REPEATER: - NPCInfo->scriptFlags |= SCF_PILOT; - //machine-gunner - break; - case WP_DEMP2: - break; - case WP_FLECHETTE: - NPCInfo->scriptFlags |= SCF_PILOT; - //shotgunner - if ( !Q_stricmp( "stofficeralt", ent->NPC_type ) ) - { - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; - case WP_ROCKET_LAUNCHER: - break; - case WP_CONCUSSION: - break; - case WP_THERMAL: - //Gran, use main, bouncy fire -// ent->NPC->scriptFlags |= SCF_ALT_FIRE; - break; - case WP_MELEE: - break; - case WP_NOGHRI_STICK: - break; - default: - case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //FIXME: not necc. a ST - NPCInfo->scriptFlags |= SCF_PILOT; - - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_COMMANDER ) - {//commanders use alt-fire - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - if ( !Q_stricmp( "rodian2", ent->NPC_type ) ) - { - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; + break; + case WP_DISRUPTOR: + // Sniper + // ent->NPC->scriptFlags |= SCF_ALT_FIRE;//FIXME: use primary fire sometimes? Up close? Different class of NPC? + break; + case WP_BOWCASTER: + NPCInfo->scriptFlags |= SCF_PILOT; + break; + case WP_REPEATER: + NPCInfo->scriptFlags |= SCF_PILOT; + // machine-gunner + break; + case WP_DEMP2: + break; + case WP_FLECHETTE: + NPCInfo->scriptFlags |= SCF_PILOT; + // shotgunner + if (!Q_stricmp("stofficeralt", ent->NPC_type)) { + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; + } + break; + case WP_ROCKET_LAUNCHER: + break; + case WP_CONCUSSION: + break; + case WP_THERMAL: + // Gran, use main, bouncy fire + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; + break; + case WP_MELEE: + break; + case WP_NOGHRI_STICK: + break; + default: + case WP_BLASTER: + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // FIXME: not necc. a ST + NPCInfo->scriptFlags |= SCF_PILOT; + + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_COMMANDER) { // commanders use alt-fire + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; + } + if (!Q_stricmp("rodian2", ent->NPC_type)) { + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } + break; } } - break; + } break; default: ent->NPC->defaultBehavior = BS_DEFAULT; - if ( ent->client->ps.weapon != WP_NONE - && ent->client->ps.weapon != WP_MELEE - && ent->client->ps.weapon != WP_SABER//sabers done above - && (!(ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON)||!ent->weaponModel[0]) )//they do this themselves + if (ent->client->ps.weapon != WP_NONE && ent->client->ps.weapon != WP_MELEE && ent->client->ps.weapon != WP_SABER // sabers done above + && (!(ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) || !ent->weaponModel[0])) // they do this themselves { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } break; } - - if ( ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1 ) // chris/steve/kevin requested that the mark1 be shielded also + if (ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1) // chris/steve/kevin requested that the mark1 be shielded also { - ent->flags |= (FL_SHIELDED|FL_NO_KNOCKBACK); + ent->flags |= (FL_SHIELDED | FL_NO_KNOCKBACK); } // Set CAN FLY Flag for Navigation On The Following Classes //---------------------------------------------------------- - if (ent->client->NPC_class==CLASS_PROBE || - ent->client->NPC_class==CLASS_REMOTE || - ent->client->NPC_class==CLASS_SEEKER || - ent->client->NPC_class==CLASS_SENTRY || - ent->client->NPC_class==CLASS_GLIDER || - ent->client->NPC_class==CLASS_IMPWORKER || - ent->client->NPC_class==CLASS_BOBAFETT || - ent->client->NPC_class==CLASS_ROCKETTROOPER - ) - { + if (ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || ent->client->NPC_class == CLASS_SEEKER || + ent->client->NPC_class == CLASS_SENTRY || ent->client->NPC_class == CLASS_GLIDER || ent->client->NPC_class == CLASS_IMPWORKER || + ent->client->NPC_class == CLASS_BOBAFETT || ent->client->NPC_class == CLASS_ROCKETTROOPER) { ent->NPC->scriptFlags |= SCF_NAV_CAN_FLY; } - if (ent->client->NPC_class==CLASS_VEHICLE) - { + if (ent->client->NPC_class == CLASS_VEHICLE) { Vehicle_Register(ent); } - if ( ent->client->ps.stats[STAT_WEAPONS]&(1<weaponModel[1] ) - {//we have the scepter, so put it in our left hand if we don't already have a second weapon - G_CreateG2AttachedWeaponModel( ent, weaponData[WP_SCEPTER].weaponMdl, ent->handLBolt, 1 ); + if (ent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER)) { + if (!ent->weaponModel[1]) { // we have the scepter, so put it in our left hand if we don't already have a second weapon + G_CreateG2AttachedWeaponModel(ent, weaponData[WP_SCEPTER].weaponMdl, ent->handLBolt, 1); } ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->weaponModel[1]], "*flash"); } - if ( ent->client->ps.saber[0].type == SABER_SITH_SWORD ) - { + if (ent->client->ps.saber[0].type == SABER_SITH_SWORD) { ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->weaponModel[0]], "*flash"); - G_PlayEffect( G_EffectIndex( "scepter/sword.efx" ), ent->weaponModel[0], ent->genericBolt1, ent->s.number, ent->currentOrigin, qtrue, qtrue ); - //how many times can she recharge? - ent->count = g_spskill->integer*2; - //To make sure she can do it at least once + G_PlayEffect(G_EffectIndex("scepter/sword.efx"), ent->weaponModel[0], ent->genericBolt1, ent->s.number, ent->currentOrigin, qtrue, qtrue); + // how many times can she recharge? + ent->count = g_spskill->integer * 2; + // To make sure she can do it at least once ent->flags |= FL_UNDYING; } - if ( ent->client->ps.weapon == WP_NOGHRI_STICK - && ent->weaponModel[0] ) - { + if (ent->client->ps.weapon == WP_NOGHRI_STICK && ent->weaponModel[0]) { ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->weaponModel[0]], "*flash"); } - G_ClassSetDontFlee( ent ); + G_ClassSetDontFlee(ent); } /* @@ -693,216 +572,174 @@ NPC_WeaponsForTeam ------------------------- */ -int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ) -{ +int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type) { //*** not sure how to handle this, should I pass in class instead of team and go from there? - dmv - switch(team) - { - // no longer exists + switch (team) { + // no longer exists -// case TEAM_IMPERIAL: + // case TEAM_IMPERIAL: case TEAM_ENEMY: - if ( Q_stricmp( "tavion", NPC_type ) == 0 || - Q_stricmpn( "reborn", NPC_type, 6 ) == 0 || - Q_stricmp( "desann", NPC_type ) == 0 || - Q_stricmpn( "shadowtrooper", NPC_type, 13 ) == 0 ) - return ( 1 << WP_SABER); -// return ( 1 << WP_IMPERIAL_BLADE); - //NOTENOTE: Falls through if not a knife user - - //FIXME: default weapon in npc config? - if ( Q_stricmpn( "stofficer", NPC_type, 9 ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("tavion", NPC_type) == 0 || Q_stricmpn("reborn", NPC_type, 6) == 0 || Q_stricmp("desann", NPC_type) == 0 || + Q_stricmpn("shadowtrooper", NPC_type, 13) == 0) + return (1 << WP_SABER); + // return ( 1 << WP_IMPERIAL_BLADE); + // NOTENOTE: Falls through if not a knife user + + // FIXME: default weapon in npc config? + if (Q_stricmpn("stofficer", NPC_type, 9) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "stcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("stcommander", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "swamptrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("swamptrooper", NPC_type) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "swamptrooper2", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("swamptrooper2", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "rockettrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_ROCKET_LAUNCHER); + if (Q_stricmp("rockettrooper", NPC_type) == 0) { + return (1 << WP_ROCKET_LAUNCHER); } - if ( Q_stricmpn( "shadowtrooper", NPC_type, 13 ) == 0 ) - { - return ( 1 << WP_SABER);//|( 1 << WP_RAPID_CONCUSSION)? + if (Q_stricmpn("shadowtrooper", NPC_type, 13) == 0) { + return (1 << WP_SABER); //|( 1 << WP_RAPID_CONCUSSION)? } - if ( Q_stricmp( "imperial", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_stricmp("imperial", NPC_type) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_stricmpn( "impworker", NPC_type, 9 ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_stricmpn("impworker", NPC_type, 9) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_stricmp( "stormpilot", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_stricmp("stormpilot", NPC_type) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_stricmp( "galak", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("galak", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "galak_mech", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("galak_mech", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmpn( "ugnaught", NPC_type, 8 ) == 0 ) - { + if (Q_stricmpn("ugnaught", NPC_type, 8) == 0) { return WP_NONE; } - if ( Q_stricmp( "granshooter", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("granshooter", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "granboxer", NPC_type ) == 0 ) - { - return ( 1 << WP_MELEE); + if (Q_stricmp("granboxer", NPC_type) == 0) { + return (1 << WP_MELEE); } - if ( Q_stricmpn( "gran", NPC_type, 4 ) == 0 ) - { - return (( 1 << WP_THERMAL)|( 1 << WP_MELEE)); + if (Q_stricmpn("gran", NPC_type, 4) == 0) { + return ((1 << WP_THERMAL) | (1 << WP_MELEE)); } - if ( Q_stricmp( "rodian", NPC_type ) == 0 ) - { - return ( 1 << WP_DISRUPTOR); + if (Q_stricmp("rodian", NPC_type) == 0) { + return (1 << WP_DISRUPTOR); } - if ( Q_stricmp( "rodian2", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("rodian2", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "interrogator",NPC_type) == 0) || ( Q_stricmp( "sentry",NPC_type) == 0) || (Q_stricmpn( "protocol",NPC_type,8) == 0) ) - { + if ((Q_stricmp("interrogator", NPC_type) == 0) || (Q_stricmp("sentry", NPC_type) == 0) || (Q_stricmpn("protocol", NPC_type, 8) == 0)) { return WP_NONE; } - if ( Q_stricmpn( "weequay", NPC_type, 7 ) == 0 ) - { - return ( 1 << WP_BOWCASTER);//|( 1 << WP_STAFF )(FIXME: new weap?) + if (Q_stricmpn("weequay", NPC_type, 7) == 0) { + return (1 << WP_BOWCASTER); //|( 1 << WP_STAFF )(FIXME: new weap?) } - if ( Q_stricmp( "impofficer", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impofficer", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "impcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impcommander", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "probe", NPC_type ) == 0 ) || ( Q_stricmp( "seeker", NPC_type ) == 0 )) - { - return ( 1 << WP_BOT_LASER); + if ((Q_stricmp("probe", NPC_type) == 0) || (Q_stricmp("seeker", NPC_type) == 0)) { + return (1 << WP_BOT_LASER); } - if ( Q_stricmpn( "remote", NPC_type, 6 ) == 0 ) - { - return ( 1 << WP_BOT_LASER ); + if (Q_stricmpn("remote", NPC_type, 6) == 0) { + return (1 << WP_BOT_LASER); } - if ( Q_stricmp( "trandoshan", NPC_type ) == 0 ) - { - return (1<client->playerTeam, ent->spawnflags, ent->NPC_type ); +void NPC_SetWeapons(gentity_t *ent) { + int bestWeap = WP_NONE; + int weapons = NPC_WeaponsForTeam(ent->client->playerTeam, ent->spawnflags, ent->NPC_type); ent->client->ps.stats[STAT_WEAPONS] = 0; - for ( int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if ( (weapons & ( 1 << curWeap )) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << curWeap ); - RegisterItem( FindItemForWeapon( (weapon_t)(curWeap) ) ); //precache the weapon - ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100;//FIXME: max ammo + for (int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if ((weapons & (1 << curWeap))) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << curWeap); + RegisterItem(FindItemForWeapon((weapon_t)(curWeap))); // precache the weapon + ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100; // FIXME: max ammo - if ( bestWeap == WP_SABER ) - { + if (bestWeap == WP_SABER) { // still want to register other weapons -- force saber to be best weap continue; } - if ( curWeap == WP_MELEE ) - { - if ( bestWeap == WP_NONE ) - {// We'll only consider giving Melee since we haven't found anything better yet. + if (curWeap == WP_MELEE) { + if (bestWeap == WP_NONE) { // We'll only consider giving Melee since we haven't found anything better yet. bestWeap = curWeap; } - } - else if ( curWeap > bestWeap || bestWeap == WP_MELEE ) - { + } else if (curWeap > bestWeap || bestWeap == WP_MELEE) { // This will never override saber as best weap. Also will override WP_MELEE if something better comes later in the list bestWeap = curWeap; } @@ -966,63 +795,52 @@ NPC_SpawnEffect ------------------------- */ -static void NPC_SpawnEffect (gentity_t *ent) -{ -} +static void NPC_SpawnEffect(gentity_t *ent) {} //-------------------------------------------------------------- // NPC_SetFX_SpawnStates // // Set up any special parms for spawn effects //-------------------------------------------------------------- -void NPC_SetFX_SpawnStates( gentity_t *ent ) -{ - ent->client->ps.gravity = g_gravity->value; -} +void NPC_SetFX_SpawnStates(gentity_t *ent) { ent->client->ps.gravity = g_gravity->value; } //-------------------------------------------------------------- -extern qboolean stop_icarus; -void NPC_Begin (gentity_t *ent) -{ - vec3_t spawn_origin, spawn_angles; - gclient_t *client; - usercmd_t ucmd; - gentity_t *spawnPoint = NULL; - - memset( &ucmd, 0, sizeof( ucmd ) ); - - if ( !(ent->spawnflags & SFB_NOTSOLID) ) - {//No NPCs should telefrag - if ( Q_stricmp( ent->NPC_type, "nullDriver") == 0 ) - {//FIXME: should be a better way to check this - } - else if( SpotWouldTelefrag( ent, TEAM_FREE ) )//(team_t)(ent->client->playerTeam) - { - if ( ent->wait < 0 ) - {//remove yourself - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, ent->target3 ); - //Fire off our target3 - G_UseTargets2( ent, ent, ent->target3 ); - - //Kill us +extern qboolean stop_icarus; +void NPC_Begin(gentity_t *ent) { + vec3_t spawn_origin, spawn_angles; + gclient_t *client; + usercmd_t ucmd; + gentity_t *spawnPoint = NULL; + + memset(&ucmd, 0, sizeof(ucmd)); + + if (!(ent->spawnflags & SFB_NOTSOLID)) { // No NPCs should telefrag + if (Q_stricmp(ent->NPC_type, "nullDriver") == 0) { // FIXME: should be a better way to check this + } else if (SpotWouldTelefrag(ent, TEAM_FREE)) //(team_t)(ent->client->playerTeam) + { + if (ent->wait < 0) { // remove yourself + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, + ent->target3); + // Fire off our target3 + G_UseTargets2(ent, ent, ent->target3); + + // Kill us ent->e_ThinkFunc = thinkF_G_FreeEntity; ent->nextthink = level.time + 100; - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "NPC %s at (%5.0f %5.0f %5.0f) couldn't spawn, waiting %4.2f secs to try again\n", - ent->targetname, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], ent->wait/1000.0f ); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "NPC %s at (%5.0f %5.0f %5.0f) couldn't spawn, waiting %4.2f secs to try again\n", + ent->targetname, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], ent->wait / 1000.0f); ent->e_ThinkFunc = thinkF_NPC_Begin; - ent->nextthink = level.time + ent->wait;//try again in half a second + ent->nextthink = level.time + ent->wait; // try again in half a second } return; } } - //Spawn effect - NPC_SpawnEffect( ent ); + // Spawn effect + NPC_SpawnEffect(ent); - VectorCopy( ent->client->ps.origin, spawn_origin); - VectorCopy( ent->s.angles, spawn_angles); + VectorCopy(ent->client->ps.origin, spawn_origin); + VectorCopy(ent->s.angles, spawn_angles); spawn_angles[YAW] = ent->NPC->desiredYaw; client = ent->client; @@ -1035,90 +853,67 @@ void NPC_Begin (gentity_t *ent) client->ps.clientNum = ent->s.number; // clear entity values - if ( ent->health ) // Was health supplied in map + if (ent->health) // Was health supplied in map { ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->health; - } - else if ( ent->NPC->stats.health ) // Was health supplied in NPC.cfg? + } else if (ent->NPC->stats.health) // Was health supplied in NPC.cfg? { - if ( ent->client->NPC_class != CLASS_REBORN - && ent->client->NPC_class != CLASS_SHADOWTROOPER + if (ent->client->NPC_class != CLASS_REBORN && + ent->client->NPC_class != CLASS_SHADOWTROOPER //&& ent->client->NPC_class != CLASS_TAVION //&& ent->client->NPC_class != CLASS_DESANN - && ent->client->NPC_class != CLASS_JEDI ) - {// up everyone except jedi - if ( !Q_stricmp("tavion_sith_sword", ent->NPC_type ) - || !Q_stricmp("tavion_scepter", ent->NPC_type ) - || !Q_stricmp("kyle_boss", ent->NPC_type ) - || !Q_stricmp("alora_dual", ent->NPC_type ) - || !Q_stricmp("alora_boss", ent->NPC_type ) ) - {//bosses are a bit different - ent->NPC->stats.health = ceil((float)ent->NPC->stats.health*0.75f + ((float)ent->NPC->stats.health/4.0f*g_spskill->value)); // 75% on easy, 100% on medium, 125% on hard - } - else - { - ent->NPC->stats.health += ent->NPC->stats.health/4 * g_spskill->integer; // 100% on easy, 125% on medium, 150% on hard + && ent->client->NPC_class != CLASS_JEDI) { // up everyone except jedi + if (!Q_stricmp("tavion_sith_sword", ent->NPC_type) || !Q_stricmp("tavion_scepter", ent->NPC_type) || !Q_stricmp("kyle_boss", ent->NPC_type) || + !Q_stricmp("alora_dual", ent->NPC_type) || !Q_stricmp("alora_boss", ent->NPC_type)) { // bosses are a bit different + ent->NPC->stats.health = ceil((float)ent->NPC->stats.health * 0.75f + + ((float)ent->NPC->stats.health / 4.0f * g_spskill->value)); // 75% on easy, 100% on medium, 125% on hard + } else { + ent->NPC->stats.health += ent->NPC->stats.health / 4 * g_spskill->integer; // 100% on easy, 125% on medium, 150% on hard } } ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->NPC->stats.health; - } - else - { + } else { ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = 100; } - if ( !Q_stricmp( "rodian", ent->NPC_type ) ) - {//sniper - //NOTE: this will get overridden by any aim settings in their spawnscripts - switch ( g_spskill->integer ) - { + if (!Q_stricmp("rodian", ent->NPC_type)) { // sniper + // NOTE: this will get overridden by any aim settings in their spawnscripts + switch (g_spskill->integer) { case 0: ent->NPC->stats.aim = 1; break; case 1: - ent->NPC->stats.aim = Q_irand( 2, 3 ); + ent->NPC->stats.aim = Q_irand(2, 3); break; case 2: - ent->NPC->stats.aim = Q_irand( 3, 4 ); + ent->NPC->stats.aim = Q_irand(3, 4); break; } - } - else if ( ent->client->NPC_class == CLASS_STORMTROOPER - || ent->client->NPC_class == CLASS_SWAMPTROOPER - || ent->client->NPC_class == CLASS_IMPWORKER - || !Q_stricmp( "rodian2", ent->NPC_type ) ) - {//tweak yawspeed for these NPCs based on difficulty - switch ( g_spskill->integer ) - { + } else if (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_IMPWORKER || + !Q_stricmp("rodian2", ent->NPC_type)) { // tweak yawspeed for these NPCs based on difficulty + switch (g_spskill->integer) { case 0: ent->NPC->stats.yawSpeed *= 0.75f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 3, 6 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(3, 6); } break; case 1: - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 2, 4 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(2, 4); } break; case 2: ent->NPC->stats.yawSpeed *= 1.5f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 0, 2 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(0, 2); } break; } - } - else if ( ent->client->NPC_class == CLASS_REBORN - || ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - switch ( g_spskill->integer ) - { + } else if (ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_SHADOWTROOPER) { + switch (g_spskill->integer) { case 1: ent->NPC->stats.yawSpeed *= 1.25f; break; @@ -1128,7 +923,6 @@ void NPC_Begin (gentity_t *ent) } } - ent->s.groundEntityNum = ENTITYNUM_NONE; ent->mass = 10; ent->takedamage = qtrue; @@ -1138,28 +932,25 @@ void NPC_Begin (gentity_t *ent) ent->m_iIcarusID = -1; // ICARUS_INVALID */ assert(ent->inuse); - assert(ent->m_iIcarusID==IIcarusInterface::ICARUS_INVALID); + assert(ent->m_iIcarusID == IIcarusInterface::ICARUS_INVALID); // CRITICAL NOTE! This was already done somewhere else and it was overwriting the previous value!!! - if ( !ent->classname || Q_stricmp( ent->classname, "noclass" ) == 0 ) + if (!ent->classname || Q_stricmp(ent->classname, "noclass") == 0) ent->classname = "NPC"; -// if ( ent->client->race == RACE_HOLOGRAM ) -// {//can shoot through holograms, but not walk through them -// ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces -// ent->clipmask = MASK_NPCSOLID; -// } else - if(!(ent->spawnflags & SFB_NOTSOLID)) - { + // if ( ent->client->race == RACE_HOLOGRAM ) + // {//can shoot through holograms, but not walk through them + // ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces + // ent->clipmask = MASK_NPCSOLID; + // } else + if (!(ent->spawnflags & SFB_NOTSOLID)) { ent->contents = CONTENTS_BODY; ent->clipmask = MASK_NPCSOLID; - } - else - { + } else { ent->contents = 0; - ent->clipmask = MASK_NPCSOLID&~CONTENTS_BODY; + ent->clipmask = MASK_NPCSOLID & ~CONTENTS_BODY; } - if(!ent->client->moveType)//Static? + if (!ent->client->moveType) // Static? { ent->client->moveType = MT_RUNJUMP; } @@ -1167,57 +958,48 @@ void NPC_Begin (gentity_t *ent) ent->waterlevel = 0; ent->watertype = 0; - //visible to player and NPCs - if ( ent->client->NPC_class != CLASS_R2D2 && - ent->client->NPC_class != CLASS_R5D2 && - ent->client->NPC_class != CLASS_MOUSE && - ent->client->NPC_class != CLASS_GONK && - ent->client->NPC_class != CLASS_PROTOCOL ) - { + // visible to player and NPCs + if (ent->client->NPC_class != CLASS_R2D2 && ent->client->NPC_class != CLASS_R5D2 && ent->client->NPC_class != CLASS_MOUSE && + ent->client->NPC_class != CLASS_GONK && ent->client->NPC_class != CLASS_PROTOCOL) { ent->flags &= ~FL_NOTARGET; } ent->s.eFlags &= ~EF_NODRAW; - NPC_SetFX_SpawnStates( ent ); + NPC_SetFX_SpawnStates(ent); client->ps.friction = 6; - if ( ent->client->ps.weapon == WP_NONE ) - {//not set by the NPCs.cfg + if (ent->client->ps.weapon == WP_NONE) { // not set by the NPCs.cfg NPC_SetWeapons(ent); } - //select the weapon + // select the weapon ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex]; ent->client->ps.weaponstate = WEAPON_IDLE; - ChangeWeapon( ent, ent->client->ps.weapon ); + ChangeWeapon(ent, ent->client->ps.weapon); - VectorCopy( spawn_origin, client->ps.origin ); + VectorCopy(spawn_origin, client->ps.origin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; // clear entity state values ent->s.eType = ET_PLAYER; -// ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models + // ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models - VectorCopy (spawn_origin, ent->s.origin); -// ent->s.origin[2] += 1; // make sure off ground + VectorCopy(spawn_origin, ent->s.origin); + // ent->s.origin[2] += 1; // make sure off ground - SetClientViewAngle( ent, spawn_angles ); + SetClientViewAngle(ent, spawn_angles); client->renderInfo.lookTarget = ENTITYNUM_NONE; - //clear IK grabbing stuff + // clear IK grabbing stuff client->ps.heldClient = client->ps.heldByClient = ENTITYNUM_NONE; - if(!(ent->spawnflags & 64)) - { - if ( Q_stricmp( ent->NPC_type, "nullDriver") == 0 ) - {//FIXME: should be a better way to check this - } - else - { - G_KillBox( ent ); + if (!(ent->spawnflags & 64)) { + if (Q_stricmp(ent->NPC_type, "nullDriver") == 0) { // FIXME: should be a better way to check this + } else { + G_KillBox(ent); } - gi.linkentity (ent); + gi.linkentity(ent); } // don't allow full run speed for a bit @@ -1227,98 +1009,86 @@ void NPC_Begin (gentity_t *ent) client->respawnTime = level.time; client->latched_buttons = 0; - if ( ent->client->NPC_class != CLASS_VEHICLE ) - { + if (ent->client->NPC_class != CLASS_VEHICLE) { // set default animations - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - if( spawnPoint ) - { + if (spawnPoint) { // fire the targets of the spawn point - G_UseTargets( spawnPoint, ent ); + G_UseTargets(spawnPoint, ent); } - //ICARUS include - // NOTE! Does this need to be called here? It seems to be getting called twice... - // Once before the level starts, then once again when the entity is spawned! - Quake3Game()->InitEntity( ent ); + // ICARUS include + // NOTE! Does this need to be called here? It seems to be getting called twice... + // Once before the level starts, then once again when the entity is spawned! + Quake3Game()->InitEntity(ent); -//==NPC initialization - SetNPCGlobals( ent ); + //==NPC initialization + SetNPCGlobals(ent); ent->enemy = NPCInfo->eventualGoal; NPCInfo->timeOfDeath = 0; NPCInfo->shotTime = 0; NPC_ClearGoal(); - NPC_ChangeWeapon( ent->client->ps.weapon ); + NPC_ChangeWeapon(ent->client->ps.weapon); -//==Final NPC initialization - ent->e_PainFunc = NPC_PainFunc( ent ); //painF_NPC_Pain; - ent->e_TouchFunc = NPC_TouchFunc( ent ); //touchF_NPC_Touch; -// ent->NPC->side = 1; + //==Final NPC initialization + ent->e_PainFunc = NPC_PainFunc(ent); // painF_NPC_Pain; + ent->e_TouchFunc = NPC_TouchFunc(ent); // touchF_NPC_Touch; + // ent->NPC->side = 1; ent->client->ps.ping = ent->NPC->stats.reactions * 50; - //MCG - Begin: NPC hacks - //FIXME: Set the team correctly + // MCG - Begin: NPC hacks + // FIXME: Set the team correctly ent->client->ps.persistant[PERS_TEAM] = ent->client->playerTeam; - ent->e_UseFunc = useF_NPC_Use; + ent->e_UseFunc = useF_NPC_Use; ent->e_ThinkFunc = thinkF_NPC_Think; ent->nextthink = level.time + FRAMETIME + Q_irand(0, 100); - NPC_SetMiscDefaultData( ent ); - if ( ent->health <= 0 ) - { - //ORIGINAL ID: health will count down towards max_health + NPC_SetMiscDefaultData(ent); + if (ent->health <= 0) { + // ORIGINAL ID: health will count down towards max_health ent->health = client->ps.stats[STAT_HEALTH] = ent->max_health; - } - else - { + } else { client->ps.stats[STAT_HEALTH] = ent->max_health = ent->health; } - ChangeWeapon( ent, ent->client->ps.weapon );//yes, again... sigh + ChangeWeapon(ent, ent->client->ps.weapon); // yes, again... sigh - if ( !(ent->spawnflags & SFB_STARTINSOLID) ) - {//Not okay to start in solid - G_CheckInSolid( ent, qtrue ); + if (!(ent->spawnflags & SFB_STARTINSOLID)) { // Not okay to start in solid + G_CheckInSolid(ent, qtrue); } - VectorClear( ent->NPC->lastClearOrigin ); + VectorClear(ent->NPC->lastClearOrigin); - //Run a script if you have one assigned to you - if ( G_ActivateBehavior( ent, BSET_SPAWN ) ) - { - if( ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID/*ent->taskManager*/ && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( ent->m_iIcarusID ); + // Run a script if you have one assigned to you + if (G_ActivateBehavior(ent, BSET_SPAWN)) { + if (ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID /*ent->taskManager*/ && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(ent->m_iIcarusID); } } - VectorCopy( ent->currentOrigin, ent->client->renderInfo.eyePoint ); + VectorCopy(ent->currentOrigin, ent->client->renderInfo.eyePoint); // run a client frame to drop exactly to the floor, // initialize animations and other things - memset( &ucmd, 0, sizeof( ucmd ) ); - VectorCopyM( client->pers.cmd_angles, ucmd.angles ); + memset(&ucmd, 0, sizeof(ucmd)); + VectorCopyM(client->pers.cmd_angles, ucmd.angles); ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON ) - { - G_MatchPlayerWeapon( ent ); + if (ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) { + G_MatchPlayerWeapon(ent); } - ClientThink( ent->s.number, &ucmd ); + ClientThink(ent->s.number, &ucmd); - gi.linkentity( ent ); + gi.linkentity(ent); - if ( ent->client->playerTeam == TEAM_ENEMY || ent->client->playerTeam == TEAM_FREE ) - {//valid enemy spawned - if ( !(ent->spawnflags&SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC ) - {//not a cinematic enemy - if ( g_entities[0].client ) - { + if (ent->client->playerTeam == TEAM_ENEMY || ent->client->playerTeam == TEAM_FREE) { // valid enemy spawned + if (!(ent->spawnflags & SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC) { // not a cinematic enemy + if (g_entities[0].client) { g_entities[0].client->sess.missionStats.enemiesSpawned++; } } @@ -1373,132 +1143,114 @@ qboolean NPC_StasisSpawn_Go( gentity_t *ent ) return qtrue; } */ -void NPC_DefaultScriptFlags( gentity_t *ent ) -{ - if ( !ent || !ent->NPC ) - { +void NPC_DefaultScriptFlags(gentity_t *ent) { + if (!ent || !ent->NPC) { return; } - //Set up default script flags - ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES|SCF_LOOK_FOR_ENEMIES); + // Set up default script flags + ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES | SCF_LOOK_FOR_ENEMIES); } #define MAX_SAFESPAWN_ENTS 4 -bool NPC_SafeSpawn( gentity_t *ent, float safeRadius ) -{ - gentity_t *radiusEnts[ MAX_SAFESPAWN_ENTS ]; - vec3_t safeMins, safeMaxs; - float distance = 999999; - int numEnts = 0; - float safeRadiusSquared = safeRadius*safeRadius; +bool NPC_SafeSpawn(gentity_t *ent, float safeRadius) { + gentity_t *radiusEnts[MAX_SAFESPAWN_ENTS]; + vec3_t safeMins, safeMaxs; + float distance = 999999; + int numEnts = 0; + float safeRadiusSquared = safeRadius * safeRadius; int i; - if (!ent) - { + if (!ent) { return false; } - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { safeMins[i] = ent->currentOrigin[i] - safeRadius; safeMaxs[i] = ent->currentOrigin[i] + safeRadius; } - //Get a number of entities in a given space - numEnts = gi.EntitiesInBox( safeMins, safeMaxs, radiusEnts, MAX_SAFESPAWN_ENTS ); + // Get a number of entities in a given space + numEnts = gi.EntitiesInBox(safeMins, safeMaxs, radiusEnts, MAX_SAFESPAWN_ENTS); - for ( i = 0; i < numEnts; i++ ) - { - //Don't consider self - if ( radiusEnts[i] == ent ) + for (i = 0; i < numEnts; i++) { + // Don't consider self + if (radiusEnts[i] == ent) continue; - if (radiusEnts[i]->NPC && (radiusEnts[i]->health == 0)) - { + if (radiusEnts[i]->NPC && (radiusEnts[i]->health == 0)) { // ignore dead guys continue; } - distance = DistanceSquared( ent->currentOrigin, radiusEnts[i]->currentOrigin ); + distance = DistanceSquared(ent->currentOrigin, radiusEnts[i]->currentOrigin); - //Found one too close to us - if ( distance < safeRadiusSquared ) - { + // Found one too close to us + if (distance < safeRadiusSquared) { return false; } } return true; } - /* ------------------------- NPC_Spawn_Go ------------------------- */ -gentity_t *NPC_Spawn_Do( gentity_t *ent, qboolean fullSpawnNow ) -{ - gentity_t *newent; - int index; - vec3_t saveOrg; +gentity_t *NPC_Spawn_Do(gentity_t *ent, qboolean fullSpawnNow) { + gentity_t *newent; + int index; + vec3_t saveOrg; -/* //Do extra code for stasis spawners - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ + /* //Do extra code for stasis spawners + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ // 4/18/03 kef -- don't let guys spawn into other guys - if (ent->spawnflags & 4096) - { - if (!NPC_SafeSpawn(ent, 64)) - { + if (ent->spawnflags & 4096) { + if (!NPC_SafeSpawn(ent, 64)) { return NULL; } } - //Test for drop to floor - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - trace_t tr; - vec3_t bottom; + // Test for drop to floor + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + trace_t tr; + vec3_t bottom; - VectorCopy( ent->currentOrigin, saveOrg ); - VectorCopy( ent->currentOrigin, bottom ); + VectorCopy(ent->currentOrigin, saveOrg); + VectorCopy(ent->currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); } } - //Check the spawner's count - if( ent->count != -1 ) - { + // Check the spawner's count + if (ent->count != -1) { ent->count--; - if( ent->count <= 0 ) - { - ent->e_UseFunc = useF_NULL;//never again - //will be removed below + if (ent->count <= 0) { + ent->e_UseFunc = useF_NULL; // never again + // will be removed below } } newent = G_Spawn(); - if ( newent == NULL ) - { - gi.Printf ( S_COLOR_RED"ERROR: NPC G_Spawn failed\n" ); + if (newent == NULL) { + gi.Printf(S_COLOR_RED "ERROR: NPC G_Spawn failed\n"); - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } return NULL; } @@ -1507,17 +1259,14 @@ gentity_t *NPC_Spawn_Do( gentity_t *ent, qboolean fullSpawnNow ) newent->svFlags |= SVF_NPC; - if ( ent->NPC_type == NULL ) - { + if (ent->NPC_type == NULL) { ent->NPC_type = "random"; newent->NPC_type = "random"; - } - else - { - newent->NPC_type = Q_strlwr( G_NewString( ent->NPC_type ) ); //get my own copy so i can free it when i die + } else { + newent->NPC_type = Q_strlwr(G_NewString(ent->NPC_type)); // get my own copy so i can free it when i die } - newent->NPC = (gNPC_t*) gi.Malloc(sizeof(gNPC_t), TAG_G_ALLOC, qtrue); + newent->NPC = (gNPC_t *)gi.Malloc(sizeof(gNPC_t), TAG_G_ALLOC, qtrue); newent->NPC->tempGoal = G_Spawn(); @@ -1525,182 +1274,159 @@ gentity_t *NPC_Spawn_Do( gentity_t *ent, qboolean fullSpawnNow ) newent->NPC->tempGoal->owner = newent; newent->NPC->tempGoal->svFlags |= SVF_NOCLIENT; -//==NPC_Connect( newent, net_name );=================================== + //==NPC_Connect( newent, net_name );=================================== - if ( ent->svFlags & SVF_NO_BASIC_SOUNDS ) - { + if (ent->svFlags & SVF_NO_BASIC_SOUNDS) { newent->svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( ent->svFlags & SVF_NO_COMBAT_SOUNDS ) - { + if (ent->svFlags & SVF_NO_COMBAT_SOUNDS) { newent->svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( ent->svFlags & SVF_NO_EXTRA_SOUNDS ) - { + if (ent->svFlags & SVF_NO_EXTRA_SOUNDS) { newent->svFlags |= SVF_NO_EXTRA_SOUNDS; } - if ( ent->message ) - {//has a key - newent->message = G_NewString(ent->message);//copy the key name - newent->flags |= FL_NO_KNOCKBACK;//don't fall off ledges + if (ent->message) { // has a key + newent->message = G_NewString(ent->message); // copy the key name + newent->flags |= FL_NO_KNOCKBACK; // don't fall off ledges } // If this is a vehicle we need to see what kind it is so we properlly allocate it. - if ( Q_stricmp( ent->classname, "NPC_Vehicle" ) == 0 ) - { + if (Q_stricmp(ent->classname, "NPC_Vehicle") == 0) { // Get the vehicle entry index. - int iVehIndex = BG_VehicleGetIndex( newent->NPC_type ); + int iVehIndex = BG_VehicleGetIndex(newent->NPC_type); - if ( iVehIndex == -1 ) - { - Com_Printf( S_COLOR_RED"ERROR: Attempting to Spawn an unrecognized Vehicle! - %s\n", newent->NPC_type ); - G_FreeEntity( newent ); - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + if (iVehIndex == -1) { + Com_Printf(S_COLOR_RED "ERROR: Attempting to Spawn an unrecognized Vehicle! - %s\n", newent->NPC_type); + G_FreeEntity(newent); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } - return NULL; + return NULL; } - newent->soundSet = G_NewString(ent->soundSet);//get my own copy so i can free it when i die + newent->soundSet = G_NewString(ent->soundSet); // get my own copy so i can free it when i die // NOTE: If you change/add any of these, update NPC_Spawn_f for the new vehicle you // want to be able to spawn in manually. // See what kind of vehicle this is and allocate it properly. - switch( g_vehicleInfo[iVehIndex].type ) - { - case VH_ANIMAL: - // Create the animal (making sure all it's data is initialized). - G_CreateAnimalNPC( &newent->m_pVehicle, newent->NPC_type ); - break; + switch (g_vehicleInfo[iVehIndex].type) { + case VH_ANIMAL: + // Create the animal (making sure all it's data is initialized). + G_CreateAnimalNPC(&newent->m_pVehicle, newent->NPC_type); + break; - case VH_SPEEDER: - // Create the speeder (making sure all it's data is initialized). - G_CreateSpeederNPC( &newent->m_pVehicle, newent->NPC_type ); - break; + case VH_SPEEDER: + // Create the speeder (making sure all it's data is initialized). + G_CreateSpeederNPC(&newent->m_pVehicle, newent->NPC_type); + break; - case VH_FIGHTER: - // Create the fighter (making sure all it's data is initialized). - G_CreateFighterNPC( &newent->m_pVehicle, newent->NPC_type ); - break; - case VH_WALKER: - // Create the animal (making sure all it's data is initialized). - G_CreateWalkerNPC( &newent->m_pVehicle, newent->NPC_type ); - break; + case VH_FIGHTER: + // Create the fighter (making sure all it's data is initialized). + G_CreateFighterNPC(&newent->m_pVehicle, newent->NPC_type); + break; + case VH_WALKER: + // Create the animal (making sure all it's data is initialized). + G_CreateWalkerNPC(&newent->m_pVehicle, newent->NPC_type); + break; - default: - Com_Printf( S_COLOR_RED"ERROR: Attempting to Spawn an unrecognized Vehicle Type! - %s\n", newent->NPC_type ); - G_FreeEntity( newent ); - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); - } - return NULL; + default: + Com_Printf(S_COLOR_RED "ERROR: Attempting to Spawn an unrecognized Vehicle Type! - %s\n", newent->NPC_type); + G_FreeEntity(newent); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); + } + return NULL; } - //grab this from the spawner - if ( (ent->spawnflags&1) ) - {//wants to explode when not in vis of player + // grab this from the spawner + if ((ent->spawnflags & 1)) { // wants to explode when not in vis of player newent->endFrame = ent->endFrame; } // Setup the vehicle. newent->m_pVehicle->m_pParentEntity = newent; - newent->m_pVehicle->m_pVehicleInfo->Initialize( newent->m_pVehicle ); + newent->m_pVehicle->m_pVehicleInfo->Initialize(newent->m_pVehicle); newent->client->NPC_class = CLASS_VEHICLE; - if ( g_vehicleInfo[iVehIndex].type == VH_FIGHTER ) - {//FIXME: EXTERN!!! - newent->flags |= (FL_NO_KNOCKBACK|FL_SHIELDED);//don't get pushed around, blasters bounce off + if (g_vehicleInfo[iVehIndex].type == VH_FIGHTER) { // FIXME: EXTERN!!! + newent->flags |= (FL_NO_KNOCKBACK | FL_SHIELDED); // don't get pushed around, blasters bounce off } - //WTF?!!! Ships spawning in pointing straight down! - //set them up to start landed + // WTF?!!! Ships spawning in pointing straight down! + // set them up to start landed newent->m_pVehicle->m_vOrientation[YAW] = ent->s.angles[YAW]; newent->m_pVehicle->m_vOrientation[PITCH] = newent->m_pVehicle->m_vOrientation[ROLL] = 0.0f; - G_SetAngles( newent, newent->m_pVehicle->m_vOrientation ); - SetClientViewAngle( newent, newent->m_pVehicle->m_vOrientation ); + G_SetAngles(newent, newent->m_pVehicle->m_vOrientation); + SetClientViewAngle(newent, newent->m_pVehicle->m_vOrientation); - //newent->m_pVehicle->m_ulFlags |= VEH_GEARSOPEN; - //why? this would just make it so the initial anim never got played... -rww - //There was no initial anim, it would just open the gear even though it's already on the ground (fixed now, made an initial anim) + // newent->m_pVehicle->m_ulFlags |= VEH_GEARSOPEN; + // why? this would just make it so the initial anim never got played... -rww + // There was no initial anim, it would just open the gear even though it's already on the ground (fixed now, made an initial anim) - //For SUSPEND spawnflag, the amount of time to drop like a rock after SUSPEND turns off + // For SUSPEND spawnflag, the amount of time to drop like a rock after SUSPEND turns off newent->fly_sound_debounce_time = ent->fly_sound_debounce_time; - //for no-pilot-death delay + // for no-pilot-death delay newent->damage = ent->damage; - //no-pilot-death distance + // no-pilot-death distance newent->speed = ent->speed; - newent->model2 = ent->model2;//for droidNPC - } - else - { - newent->client->ps.weapon = WP_NONE;//init for later check in NPC_Begin + newent->model2 = ent->model2; // for droidNPC + } else { + newent->client->ps.weapon = WP_NONE; // init for later check in NPC_Begin } newent->classname = "NPC"; VectorCopy(ent->s.origin, newent->s.origin); VectorCopy(ent->s.origin, newent->client->ps.origin); VectorCopy(ent->s.origin, newent->currentOrigin); - G_SetOrigin(newent, ent->s.origin);//just to be sure! - //NOTE: on vehicles, anything in the .npc file will STOMP data on the NPC that's set by the vehicle - if ( !NPC_ParseParms( ent->NPC_type, newent ) ) - { - gi.Printf ( S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type ); - G_FreeEntity( newent ); - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + G_SetOrigin(newent, ent->s.origin); // just to be sure! + // NOTE: on vehicles, anything in the .npc file will STOMP data on the NPC that's set by the vehicle + if (!NPC_ParseParms(ent->NPC_type, newent)) { + gi.Printf(S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type); + G_FreeEntity(newent); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } return NULL; } - if ( ent->NPC_type ) - { - if ( !Q_stricmp( ent->NPC_type, "player" ) ) - {// Or check NPC_type against player's NPC_type? + if (ent->NPC_type) { + if (!Q_stricmp(ent->NPC_type, "player")) { // Or check NPC_type against player's NPC_type? newent->NPC->aiFlags |= NPCAI_MATCHPLAYERWEAPON; - } - else if ( !Q_stricmp( ent->NPC_type, "test" ) ) - { - int n; - for ( n = 0; n < 1 ; n++) - { - if ( !(g_entities[n].svFlags & SVF_NPC) && g_entities[n].client) - { + } else if (!Q_stricmp(ent->NPC_type, "test")) { + int n; + for (n = 0; n < 1; n++) { + if (!(g_entities[n].svFlags & SVF_NPC) && g_entities[n].client) { VectorCopy(g_entities[n].s.origin, newent->s.origin); newent->client->playerTeam = g_entities[n].client->playerTeam; break; } } newent->NPC->defaultBehavior = newent->NPC->behaviorState = BS_WAIT; - // newent->svFlags |= SVF_NOPUSH; + // newent->svFlags |= SVF_NOPUSH; } } -//===================================================================== - //set the info we want + //===================================================================== + // set the info we want newent->health = ent->health; newent->wait = ent->wait; - //copy strings so we can safely free them + // copy strings so we can safely free them newent->script_targetname = G_NewString(ent->NPC_targetname); newent->targetname = G_NewString(ent->NPC_targetname); - newent->target = G_NewString(ent->NPC_target);//death - newent->target2 = G_NewString(ent->target2);//knocked out death - newent->target3 = G_NewString(ent->target3);//??? - newent->target4 = G_NewString(ent->target4);//ffire death + newent->target = G_NewString(ent->NPC_target); // death + newent->target2 = G_NewString(ent->target2); // knocked out death + newent->target3 = G_NewString(ent->target3); //??? + newent->target4 = G_NewString(ent->target4); // ffire death newent->paintarget = G_NewString(ent->paintarget); newent->opentarget = G_NewString(ent->opentarget); newent->radius = ent->radius; newent->NPC->eventualGoal = ent->enemy; - for( index = BSET_FIRST; index < NUM_BSETS; index++) - { - if ( ent->behaviorSet[index] ) - { + for (index = BSET_FIRST; index < NUM_BSETS; index++) { + if (ent->behaviorSet[index]) { newent->behaviorSet[index] = ent->behaviorSet[index]; } } @@ -1708,91 +1434,74 @@ gentity_t *NPC_Spawn_Do( gentity_t *ent, qboolean fullSpawnNow ) VectorCopy(ent->s.angles, newent->s.angles); VectorCopy(ent->s.angles, newent->currentAngles); VectorCopy(ent->s.angles, newent->client->ps.viewangles); - newent->NPC->desiredYaw =ent->s.angles[YAW]; + newent->NPC->desiredYaw = ent->s.angles[YAW]; - //gi.linkentity(newent); //check: don't need this here? + // gi.linkentity(newent); //check: don't need this here? newent->spawnflags = ent->spawnflags; -//==New stuff===================================================================== - newent->s.eType = ET_PLAYER; + //==New stuff===================================================================== + newent->s.eType = ET_PLAYER; - //FIXME: Call CopyParms - if ( ent->parms ) - { - for ( int parmNum = 0; parmNum < MAX_PARMS; parmNum++ ) - { - if ( ent->parms->parm[parmNum] && ent->parms->parm[parmNum][0] ) - { - Q3_SetParm( newent->s.number, parmNum, ent->parms->parm[parmNum] ); + // FIXME: Call CopyParms + if (ent->parms) { + for (int parmNum = 0; parmNum < MAX_PARMS; parmNum++) { + if (ent->parms->parm[parmNum] && ent->parms->parm[parmNum][0]) { + Q3_SetParm(newent->s.number, parmNum, ent->parms->parm[parmNum]); } } } - //FIXME: copy cameraGroup, store mine in message or other string field + // FIXME: copy cameraGroup, store mine in message or other string field - //set origin + // set origin newent->s.pos.trType = TR_INTERPOLATE; newent->s.pos.trTime = level.time; - VectorCopy( newent->currentOrigin, newent->s.pos.trBase ); - VectorClear( newent->s.pos.trDelta ); + VectorCopy(newent->currentOrigin, newent->s.pos.trBase); + VectorClear(newent->s.pos.trDelta); newent->s.pos.trDuration = 0; - //set angles + // set angles newent->s.apos.trType = TR_INTERPOLATE; newent->s.apos.trTime = level.time; - VectorCopy( newent->currentOrigin, newent->s.apos.trBase ); - VectorClear( newent->s.apos.trDelta ); + VectorCopy(newent->currentOrigin, newent->s.apos.trBase); + VectorClear(newent->s.apos.trDelta); newent->s.apos.trDuration = 0; newent->NPC->combatPoint = -1; - newent->NPC->aiFlags |= ent->bounceCount;//ai flags - + newent->NPC->aiFlags |= ent->bounceCount; // ai flags - newent->flags |= FL_NOTARGET;//So he's ignored until he's fully spawned - newent->s.eFlags |= EF_NODRAW;//So he's ignored until he's fully spawned + newent->flags |= FL_NOTARGET; // So he's ignored until he's fully spawned + newent->s.eFlags |= EF_NODRAW; // So he's ignored until he's fully spawned - if ( fullSpawnNow ) - { + if (fullSpawnNow) { newent->owner = ent->owner; - } - else - { + } else { newent->e_ThinkFunc = thinkF_NPC_Begin; newent->nextthink = level.time + FRAMETIME; } - NPC_DefaultScriptFlags( newent ); + NPC_DefaultScriptFlags(newent); - gi.linkentity (newent); + gi.linkentity(newent); - if(ent->e_UseFunc == useF_NULL) - { - if( ent->target ) - {//use any target we're pointed at - G_UseTargets ( ent, ent ); + if (ent->e_UseFunc == useF_NULL) { + if (ent->target) { // use any target we're pointed at + G_UseTargets(ent, ent); } - if(ent->closetarget) - {//last guy should fire this target when he dies - if (newent->target) - {//zap + if (ent->closetarget) { // last guy should fire this target when he dies + if (newent->target) { // zap gi.Free(newent->target); } newent->target = G_NewString(ent->closetarget); } - G_FreeEntity( ent );//bye! - } - else if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + G_FreeEntity(ent); // bye! + } else if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } - if ( fullSpawnNow ) - { - NPC_Begin( newent ); + if (fullSpawnNow) { + NPC_Begin(newent); } return newent; } -void NPC_Spawn_Go( gentity_t *ent ) -{ - NPC_Spawn_Do( ent, qfalse ); -} +void NPC_Spawn_Go(gentity_t *ent) { NPC_Spawn_Do(ent, qfalse); } /* ------------------------- @@ -1834,27 +1543,24 @@ NPC_ShySpawn ------------------------- */ -#define SHY_THINK_TIME 1000 -#define SHY_SPAWN_DISTANCE 128 -#define SHY_SPAWN_DISTANCE_SQR ( SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE ) +#define SHY_THINK_TIME 1000 +#define SHY_SPAWN_DISTANCE 128 +#define SHY_SPAWN_DISTANCE_SQR (SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE) -void NPC_ShySpawn( gentity_t *ent ) -{ +void NPC_ShySpawn(gentity_t *ent) { ent->nextthink = level.time + SHY_THINK_TIME; ent->e_ThinkFunc = thinkF_NPC_ShySpawn; - if ( DistanceSquared( g_entities[0].currentOrigin, ent->currentOrigin ) <= SHY_SPAWN_DISTANCE_SQR ) + if (DistanceSquared(g_entities[0].currentOrigin, ent->currentOrigin) <= SHY_SPAWN_DISTANCE_SQR) return; - if ( (InFOV( ent, &g_entities[0], 80, 64 )) ) // FIXME: hardcoded fov - if ( (NPC_ClearLOS( &g_entities[0], ent->currentOrigin )) ) + if ((InFOV(ent, &g_entities[0], 80, 64))) // FIXME: hardcoded fov + if ((NPC_ClearLOS(&g_entities[0], ent->currentOrigin))) return; // 4/18/03 kef -- don't let guys spawn into other guys - if (ent->spawnflags & 4096) - { - if (!NPC_SafeSpawn(ent, 64)) - { + if (ent->spawnflags & 4096) { + if (!NPC_SafeSpawn(ent, 64)) { return; } } @@ -1862,7 +1568,7 @@ void NPC_ShySpawn( gentity_t *ent ) ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = 0; - NPC_Spawn_Go( ent ); + NPC_Spawn_Go(ent); } /* @@ -1871,35 +1577,30 @@ NPC_Spawn ------------------------- */ -void NPC_Spawn ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - //delay before spawning NPC - if (other->spawnflags&32) - { +void NPC_Spawn(gentity_t *ent, gentity_t *other, gentity_t *activator) { + // delay before spawning NPC + if (other->spawnflags & 32) { ent->enemy = activator; } - if( ent->delay ) - { -/* //Stasis does an extra step - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ - if ( ent->spawnflags & 2048 ) // SHY + if (ent->delay) { + /* //Stasis does an extra step + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ + if (ent->spawnflags & 2048) // SHY ent->e_ThinkFunc = thinkF_NPC_ShySpawn; else ent->e_ThinkFunc = thinkF_NPC_Spawn_Go; ent->nextthink = level.time + ent->delay; - } - else - { - if ( ent->spawnflags & 2048 ) // SHY - NPC_ShySpawn( ent ); + } else { + if (ent->spawnflags & 2048) // SHY + NPC_ShySpawn(ent); else - NPC_Spawn_Go( ent ); + NPC_Spawn_Go(ent); } } @@ -1944,7 +1645,7 @@ fleescript - default script to run when hit and below 50% health (none by defaul deathscript - default script to run when killed (none by default) These strings can be used to activate behaviors instead of scripts - these are checked first and so no scripts should be names with these names: - default - 0: whatever + default - 0: whatever idle - 1: Stand around, do abolutely nothing roam - 2: Roam around, collect stuff walk - 3: Crouch-Walk toward their goals @@ -1970,115 +1671,91 @@ first and so no scripts should be names with these names: delay - after spawned or triggered, how many seconds to wait to spawn the NPC */ -extern qboolean spawning; // the G_Spawn*() functions are valid (only turned on during one function) -extern void NPC_PrecacheByClassName(const char*); +extern qboolean spawning; // the G_Spawn*() functions are valid (only turned on during one function) +extern void NPC_PrecacheByClassName(const char *); -void SP_NPC_spawner( gentity_t *self) -{ - extern void NPC_PrecacheAnimationCFG( const char *NPC_type ); - float fDelay; +void SP_NPC_spawner(gentity_t *self) { + extern void NPC_PrecacheAnimationCFG(const char *NPC_type); + float fDelay; - //register/precache the models needed for this NPC, not anymore - //self->classname = "NPC_spawner"; + // register/precache the models needed for this NPC, not anymore + // self->classname = "NPC_spawner"; - if(!self->count) - { + if (!self->count) { self->count = 1; } - //NOTE: bounceCount is transferred to the spawned NPC's NPC->aiFlags + // NOTE: bounceCount is transferred to the spawned NPC's NPC->aiFlags self->bounceCount = 0; { - static int garbage; - //Stop loading of certain extra sounds - if ( G_SpawnInt( "noBasicSounds", "0", &garbage ) ) - { + static int garbage; + // Stop loading of certain extra sounds + if (G_SpawnInt("noBasicSounds", "0", &garbage)) { self->svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( G_SpawnInt( "noCombatSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noCombatSounds", "0", &garbage)) { self->svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( G_SpawnInt( "noExtraSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noExtraSounds", "0", &garbage)) { self->svFlags |= SVF_NO_EXTRA_SOUNDS; } - if ( G_SpawnInt( "nodelay", "0", &garbage ) ) - { + if (G_SpawnInt("nodelay", "0", &garbage)) { self->bounceCount |= NPCAI_NO_JEDI_DELAY; } } - - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; - } - else - { - self->wait *= 1000;//1 = 1 msec, 1000 = 1 sec + } else { + self->wait *= 1000; // 1 = 1 msec, 1000 = 1 sec } - G_SpawnFloat( "delay", "0", &fDelay ); - if ( fDelay ) - { - self->delay = ceil(1000.0f*fDelay);//1 = 1 msec, 1000 = 1 sec + G_SpawnFloat("delay", "0", &fDelay); + if (fDelay) { + self->delay = ceil(1000.0f * fDelay); // 1 = 1 msec, 1000 = 1 sec } - if ( self->delay > 0 ) - { + if (self->delay > 0) { self->svFlags |= SVF_NPC_PRECACHE; } - //We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid - NPC_PrecacheAnimationCFG( self->NPC_type ); + // We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid + NPC_PrecacheAnimationCFG(self->NPC_type); - if ( self->targetname ) - {//Wait for triggering + if (self->targetname) { // Wait for triggering self->e_UseFunc = useF_NPC_Spawn; - self->svFlags |= SVF_NPC_PRECACHE;//FIXME: precache my weapons somehow? - //NPC_PrecacheModels( self->NPC_type ); - } - else - { - //NOTE: auto-spawners never check for shy spawning - if ( spawning ) - {//in entity spawn stage - map starting up + self->svFlags |= SVF_NPC_PRECACHE; // FIXME: precache my weapons somehow? + // NPC_PrecacheModels( self->NPC_type ); + } else { + // NOTE: auto-spawners never check for shy spawning + if (spawning) { // in entity spawn stage - map starting up self->e_ThinkFunc = thinkF_NPC_Spawn_Go; self->nextthink = level.time + START_TIME_REMOVE_ENTS + 50; - } - else - {//else spawn right now - NPC_Spawn( self, self, self ); + } else { // else spawn right now + NPC_Spawn(self, self, self); } } - if (!(self->svFlags&SVF_NPC_PRECACHE)) - { + if (!(self->svFlags & SVF_NPC_PRECACHE)) { NPC_PrecacheByClassName(self->NPC_type); } - //FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup - //Or just don't include NPC_spawners in cameraGroupings + // FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup + // Or just don't include NPC_spawners in cameraGroupings - if ( self->message ) - {//may drop a key, precache the key model and pickup sound - G_SoundIndex( "sound/weapons/key_pkup.wav" ); - if ( !Q_stricmp( "goodie", self->message ) ) - { - RegisterItem( FindItemForInventory( INV_GOODIE_KEY ) ); - } - else - { - RegisterItem( FindItemForInventory( INV_SECURITY_KEY ) ); + if (self->message) { // may drop a key, precache the key model and pickup sound + G_SoundIndex("sound/weapons/key_pkup.wav"); + if (!Q_stricmp("goodie", self->message)) { + RegisterItem(FindItemForInventory(INV_GOODIE_KEY)); + } else { + RegisterItem(FindItemForInventory(INV_SECURITY_KEY)); } } } - //============================================================================================= -//VEHICLES +// VEHICLES //============================================================================================= /*QUAKED NPC_Vehicle (1 0 0) (-16 -16 -24) (16 16 32) NO_VIS_DIE x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY SAFE set NPC_type to vehicle name in vehicles.dat @@ -2093,51 +1770,40 @@ SAFE - Won't spawn if an entity is within 64 units "noVisTime" - how long to wait after spawning/last being seen by the player beforw blowing ourselves up (default is 10 seconds) "skin" - which skin to set "red" for example - If no skin it is random */ -void NPC_VehicleSpawnUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_VehicleSpawn( self ); -} +void NPC_VehicleSpawnUse(gentity_t *self, gentity_t *other, gentity_t *activator) { G_VehicleSpawn(self); } -void SP_NPC_Vehicle( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Vehicle(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "swoop"; } - if ( !self->classname ) - { + if (!self->classname) { self->classname = "NPC_Vehicle"; } - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); G_SpawnString("skin", "", &self->soundSet); - //grab this from the spawner - if ( (self->spawnflags&1) ) - {//wants to explode when not in vis of player - if ( !self->endFrame ) - { + // grab this from the spawner + if ((self->spawnflags & 1)) { // wants to explode when not in vis of player + if (!self->endFrame) { self->endFrame = NO_PILOT_DIE_TIME; } } - if ( self->targetname ) - { - self->svFlags |= SVF_NPC_PRECACHE; // Precache The Bike when all other npcs are precached + if (self->targetname) { + self->svFlags |= SVF_NPC_PRECACHE; // Precache The Bike when all other npcs are precached self->e_UseFunc = useF_NPC_VehicleSpawnUse; - //we're not spawning until later, so precache us now - BG_VehicleGetIndex( self->NPC_type ); - } - else - { - G_VehicleSpawn( self ); + // we're not spawning until later, so precache us now + BG_VehicleGetIndex(self->NPC_type); + } else { + G_VehicleSpawn(self); } } //============================================================================================= -//CHARACTERS +// CHARACTERS //============================================================================================= /*QUAKED NPC_Player (1 0 0) (-16 -16 -24) (16 16 32) x RIFLEMAN PHASER TRICORDER DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2146,11 +1812,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Player( gentity_t *self) -{ +void SP_NPC_Player(gentity_t *self) { self->NPC_type = "Player"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Kyle (1 0 0) (-16 -16 -24) (16 16 32) BOSS x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2160,18 +1825,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Kyle( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Kyle(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "Kyle_boss"; - } - else - { + } else { self->NPC_type = "Kyle"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Lando(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2181,11 +1842,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Lando( gentity_t *self) -{ +void SP_NPC_Lando(gentity_t *self) { self->NPC_type = "Lando"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Jan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2195,11 +1855,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Jan( gentity_t *self) -{ +void SP_NPC_Jan(gentity_t *self) { self->NPC_type = "Jan"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Luke(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2209,11 +1868,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Luke( gentity_t *self) -{ +void SP_NPC_Luke(gentity_t *self) { self->NPC_type = "Luke"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MonMothma(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2223,11 +1881,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MonMothma( gentity_t *self) -{ +void SP_NPC_MonMothma(gentity_t *self) { self->NPC_type = "MonMothma"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rosh_Penin (1 0 0) (-16 -16 -24) (16 16 32) DARKSIDE NOFORCE x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2239,22 +1896,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rosh_Penin( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Rosh_Penin(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "rosh_dark"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "rosh_penin_noforce"; - } - else - { + } else { self->NPC_type = "rosh_penin"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tavion (1 0 0) (-16 -16 -24) (16 16 32) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2264,11 +1915,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tavion( gentity_t *self) -{ +void SP_NPC_Tavion(gentity_t *self) { self->NPC_type = "Tavion"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tavion_New (1 0 0) (-16 -16 -24) (16 16 32) SCEPTER SITH_SWORD x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2282,22 +1932,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tavion_New( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Tavion_New(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "tavion_scepter"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "tavion_sith_sword"; - } - else - { + } else { self->NPC_type = "tavion_new"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Alora (1 0 0) (-16 -16 -24) (16 16 32) DUAL x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2310,18 +1954,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Alora( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Alora(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "alora_dual"; - } - else - { + } else { self->NPC_type = "alora"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reelo(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2331,11 +1971,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reelo( gentity_t *self) -{ +void SP_NPC_Reelo(gentity_t *self) { self->NPC_type = "Reelo"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Galak(1 0 0) (-16 -16 -24) (16 16 40) MECH x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2347,9 +1986,7 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Galak( gentity_t *self) -{ -} +void SP_NPC_Galak(gentity_t *self) {} /*QUAKED NPC_Desann(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY CEILING - Sticks to the ceiling until he sees an enemy or takes pain @@ -2358,11 +1995,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Desann( gentity_t *self) -{ +void SP_NPC_Desann(gentity_t *self) { self->NPC_type = "Desann"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rax(1 0 0) (-16 -16 -24) (16 16 40) FUN x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2373,11 +2009,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rax( gentity_t *self ) -{ +void SP_NPC_Rax(gentity_t *self) { self->NPC_type = "Rax"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_BobaFett(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2387,10 +2022,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_BobaFett( gentity_t *self ) -{ +void SP_NPC_BobaFett(gentity_t *self) { self->NPC_type = "Boba_Fett"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Ragnos(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2400,11 +2034,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Ragnos( gentity_t *self ) -{ +void SP_NPC_Ragnos(gentity_t *self) { self->NPC_type = "Ragnos"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Lannik_Racto(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2414,11 +2047,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Lannik_Racto( gentity_t *self ) -{ +void SP_NPC_Lannik_Racto(gentity_t *self) { self->NPC_type = "lannik_racto"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Kothos(1 0 0) (-16 -16 -24) (16 16 40) VIL x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2432,18 +2064,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Kothos( gentity_t *self ) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Kothos(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "VKothos"; - } - else - { + } else { self->NPC_type = "DKothos"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Chewbacca(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2453,11 +2081,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Chewbacca( gentity_t *self ) -{ +void SP_NPC_Chewbacca(gentity_t *self) { self->NPC_type = "Chewie"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Bartender(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2467,11 +2094,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Bartender( gentity_t *self) -{ +void SP_NPC_Bartender(gentity_t *self) { self->NPC_type = "Bartender"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MorganKatarn(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2481,15 +2107,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MorganKatarn( gentity_t *self) -{ +void SP_NPC_MorganKatarn(gentity_t *self) { self->NPC_type = "MorganKatarn"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ALLIES +// ALLIES //============================================================================================= /*QUAKED NPC_Jedi(1 0 0) (-16 -16 -24) (16 16 40) TRAINER MASTER RANDOM x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2504,18 +2129,13 @@ SHY - Spawner is shy Ally Jedi NPC Buddy - tags along with player */ -extern cvar_t *g_char_model; -void SP_NPC_Jedi( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( self->spawnflags & 4 ) - {//random! - int sanityCheck = 20; //just in case - while ( sanityCheck-- ) - { - switch( Q_irand( 0, 11 ) ) - { +extern cvar_t *g_char_model; +void SP_NPC_Jedi(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 4) { // random! + int sanityCheck = 20; // just in case + while (sanityCheck--) { + switch (Q_irand(0, 11)) { case 0: self->NPC_type = "jedi_hf1"; break; @@ -2550,45 +2170,36 @@ void SP_NPC_Jedi( gentity_t *self) self->NPC_type = "jedi_zf1"; break; case 11: - default://just in case + default: // just in case self->NPC_type = "jedi_zf2"; break; } - if ( strstr( self->NPC_type, g_char_model->string ) != NULL ) - {//bah, we're using this one, try again + if (strstr(self->NPC_type, g_char_model->string) != NULL) { // bah, we're using this one, try again continue; } - break; //get out of the while + break; // get out of the while } - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "jedimaster"; - } - else if ( self->spawnflags & 1 ) - { + } else if (self->spawnflags & 1) { self->NPC_type = "jeditrainer"; - } - else - { + } else { /* if ( !Q_irand( 0, 2 ) ) { self->NPC_type = "JediF"; } else - */if ( Q_irand( 0, 1 ) ) - { + */ + if (Q_irand(0, 1)) { self->NPC_type = "Jedi"; - } - else - { + } else { self->NPC_type = "Jedi2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Prisoner(1 0 0) (-16 -16 -24) (16 16 40) ELDER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2598,35 +2209,24 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Prisoner( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( (self->spawnflags&1) ) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Prisoner(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { + if (Q_irand(0, 1)) { self->NPC_type = "elder"; - } - else - { + } else { self->NPC_type = "elder2"; } - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { self->NPC_type = "Prisoner"; - } - else - { + } else { self->NPC_type = "Prisoner2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Merchant(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2636,11 +2236,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Merchant( gentity_t *self) -{ +void SP_NPC_Merchant(gentity_t *self) { self->NPC_type = "merchant"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rebel(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it @@ -2649,18 +2248,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rebel( gentity_t *self) -{ - if(!self->NPC_type) - { +void SP_NPC_Rebel(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "Rebel"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ENEMIES +// ENEMIES //============================================================================================= /*QUAKED NPC_Human_Merc(1 0 0) (-16 -16 -24) (16 16 40) BOWCASTER REPEATER FLECHETTE CONCUSSION DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2673,7 +2270,9 @@ CONCUSSION - Starts with a Concussion Rifle If you want them to start with any other kind of weapon, make a spawnscript for them that sets their weapon. -"message" - turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. NOTE: this overrides all the weapon spawnflags +"message" - turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the +func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. +NOTE: this overrides all the weapon spawnflags DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2681,39 +2280,26 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Human_Merc( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->message ) - { +void SP_NPC_Human_Merc(gentity_t *self) { + if (!self->NPC_type) { + if (self->message) { self->NPC_type = "human_merc_key"; - } - else if ( (self->spawnflags&1) ) - { + } else if ((self->spawnflags & 1)) { self->NPC_type = "human_merc_bow"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "human_merc_rep"; - } - else if ( (self->spawnflags&4) ) - { + } else if ((self->spawnflags & 4)) { self->NPC_type = "human_merc_flc"; - } - else if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 8)) { self->NPC_type = "human_merc_cnc"; - } - else - { + } else { self->NPC_type = "human_merc"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -//TROOPERS============================================================================= +// TROOPERS============================================================================= /*QUAKED NPC_Stormtrooper(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER ALTOFFICER ROCKET DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY COMMANDO 30 health, blaster @@ -2731,42 +2317,28 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Stormtrooper( gentity_t *self) -{ - if ( self->spawnflags & 8 ) - {//rocketer +void SP_NPC_Stormtrooper(gentity_t *self) { + if (self->spawnflags & 8) { // rocketer self->NPC_type = "rockettrooper"; - } - else if ( self->spawnflags & 4 ) - {//alt-officer + } else if (self->spawnflags & 4) { // alt-officer self->NPC_type = "stofficeralt"; - } - else if ( self->spawnflags & 2 ) - {//commander + } else if (self->spawnflags & 2) { // commander self->NPC_type = "stcommander"; - } - else if ( self->spawnflags & 1 ) - {//officer + } else if (self->spawnflags & 1) { // officer self->NPC_type = "stofficer"; - } - else - {//regular trooper - if ( Q_irand( 0, 1 ) ) - { + } else { // regular trooper + if (Q_irand(0, 1)) { self->NPC_type = "StormTrooper"; - } - else - { + } else { self->NPC_type = "StormTrooper2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -void SP_NPC_StormtrooperOfficer( gentity_t *self) -{ +void SP_NPC_StormtrooperOfficer(gentity_t *self) { self->spawnflags |= 1; - SP_NPC_Stormtrooper( self ); + SP_NPC_Stormtrooper(self); } /*QUAKED NPC_Snowtrooper(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY 30 health, blaster @@ -2777,11 +2349,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Snowtrooper( gentity_t *self) -{ +void SP_NPC_Snowtrooper(gentity_t *self) { self->NPC_type = "snowtrooper"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tie_Pilot(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY 30 health, blaster @@ -2792,11 +2363,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tie_Pilot( gentity_t *self) -{ +void SP_NPC_Tie_Pilot(gentity_t *self) { self->NPC_type = "stormpilot"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_RocketTrooper(1 0 0) (-16 -16 -24) (16 16 40) OFFICER SPOTLIGHT x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2811,21 +2381,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_RocketTrooper( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_RocketTrooper(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "rockettrooper2Officer"; - } - else - { + } else { self->NPC_type = "rockettrooper2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_HazardTrooper(1 0 0) (-16 -16 -24) (16 16 40) OFFICER CONCUSSION x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2839,30 +2404,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_HazardTrooper( gentity_t *self) -{ - if ( !self->NPC_type ) - { - +void SP_NPC_HazardTrooper(gentity_t *self) { + if (!self->NPC_type) { - if ( (self->spawnflags&1) ) - { + if ((self->spawnflags & 1)) { self->NPC_type = "hazardtrooperofficer"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "hazardtrooperconcussion"; - } - else - { + } else { self->NPC_type = "hazardtrooper"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -//OTHERS============================================================================= +// OTHERS============================================================================= /*QUAKED NPC_Ugnaught(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it @@ -2871,21 +2428,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Ugnaught( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Ugnaught(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Ugnaught"; - } - else - { + } else { self->NPC_type = "Ugnaught2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Jawa(1 0 0) (-16 -16 -24) (16 16 40) ARMED x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2897,21 +2449,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Jawa( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Jawa(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "jawa_armed"; - } - else - { + } else { self->NPC_type = "jawa"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Gran(1 0 0) (-16 -16 -24) (16 16 40) SHOOTER BOXER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2925,32 +2472,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Gran( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Gran(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "granshooter"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "granboxer"; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { self->NPC_type = "gran"; - } - else - { + } else { self->NPC_type = "gran2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rodian(1 0 0) (-16 -16 -24) (16 16 40) BLASTER NO_HIDE x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2962,21 +2499,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rodian( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags&1 ) - { +void SP_NPC_Rodian(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rodian2"; - } - else - { + } else { self->NPC_type = "rodian"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Weequay(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2986,12 +2518,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Weequay( gentity_t *self) -{ - if ( !self->NPC_type ) - { - switch ( Q_irand( 0, 3 ) ) - { +void SP_NPC_Weequay(gentity_t *self) { + if (!self->NPC_type) { + switch (Q_irand(0, 3)) { case 0: self->NPC_type = "Weequay"; break; @@ -3007,7 +2536,7 @@ void SP_NPC_Weequay( gentity_t *self) } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Trandoshan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3016,15 +2545,13 @@ CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy -*/ -void SP_NPC_Trandoshan( gentity_t *self) -{ - if ( !self->NPC_type ) - { +*/ +void SP_NPC_Trandoshan(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "Trandoshan"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tusken(1 0 0) (-16 -16 -24) (16 16 40) SNIPER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3034,21 +2561,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tusken( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Tusken(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "tuskensniper"; - } - else - { + } else { self->NPC_type = "tusken"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Noghri(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3058,14 +2580,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Noghri( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Noghri(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "noghri"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_SwampTrooper(1 0 0) (-16 -16 -24) (16 16 40) REPEATER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3076,21 +2596,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_SwampTrooper( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_SwampTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "SwampTrooper2"; - } - else - { + } else { self->NPC_type = "SwampTrooper"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Imperial(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3100,7 +2615,9 @@ Greyshirt grunt, uses blaster pistol, 20 health. OFFICER - Brownshirt Officer, uses blaster rifle, 40 health COMMANDER - Blackshirt Commander, uses rapid-fire blaster rifle, 80 healt -"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. +"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of +the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" +spawnflag. DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -3108,25 +2625,18 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Imperial( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Imperial(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "ImpOfficer"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "ImpCommander"; - } - else - { + } else { self->NPC_type = "Imperial"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_ImpWorker(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3136,11 +2646,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_ImpWorker( gentity_t *self) -{ +void SP_NPC_ImpWorker(gentity_t *self) { self->NPC_type = "ImpWorker"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_BespinCop(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3150,21 +2659,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_BespinCop( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_BespinCop(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "BespinCop"; - } - else - { + } else { self->NPC_type = "BespinCop2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reborn(1 0 0) (-16 -16 -24) (16 16 40) FORCE FENCER ACROBAT BOSS CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3184,33 +2688,22 @@ SHY - Spawner is shy nodelay - set to "1" to make the Reborn not stand around and taunt the player before attacking */ -void SP_NPC_Reborn( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Reborn(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rebornforceuser"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "rebornfencer"; - } - else if ( self->spawnflags & 4 ) - { + } else if (self->spawnflags & 4) { self->NPC_type = "rebornacrobat"; - } - else if ( self->spawnflags & 8 ) - { + } else if (self->spawnflags & 8) { self->NPC_type = "rebornboss"; - } - else - { + } else { self->NPC_type = "reborn"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reborn_New(1 0 0) (-16 -16 -24) (16 16 40) DUAL STAFF WEAK MASTER CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3229,58 +2722,36 @@ SHY - Spawner is shy nodelay - set to "1" to make the Reborn not stand around and taunt the player before attacking */ -void SP_NPC_Reborn_New( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&8) ) - {//tougher guys - if ( (self->spawnflags&1) ) - { +void SP_NPC_Reborn_New(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 8)) { // tougher guys + if ((self->spawnflags & 1)) { self->NPC_type = "RebornMasterDual"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "RebornMasterStaff"; - } - else - { + } else { self->NPC_type = "RebornMaster"; } - } - else if ( (self->spawnflags&4) ) - {//weaker guys - if ( (self->spawnflags&1) ) - { + } else if ((self->spawnflags & 4)) { // weaker guys + if ((self->spawnflags & 1)) { self->NPC_type = "reborn_dual2"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "reborn_staff2"; - } - else - { + } else { self->NPC_type = "reborn_new2"; } - } - else - { - if ( (self->spawnflags&1) ) - { + } else { + if ((self->spawnflags & 1)) { self->NPC_type = "reborn_dual"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "reborn_staff"; - } - else - { + } else { self->NPC_type = "reborn_new"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Saber(1 0 0) (-16 -16 -24) (16 16 40) MED STRONG ALL THROW CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3291,7 +2762,8 @@ default fencer uses fast style - weak, but can attack rapidly. Good defense. MED - Uses medium style - average speed and attack strength, average defense. STRONG - Uses strong style, slower than others, but can do a lot of damage with one blow. Weak defense. ALL - Knows all 3 styles, switches between them, good defense. -THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 spawnflags) +THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 +spawnflags) CEILING - Sticks to the ceiling until he sees an enemy or takes pain CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -3301,57 +2773,36 @@ SHY - Spawner is shy nodelay - set to "1" to make the Cultist not stand around and taunt the player before attacking */ -void SP_NPC_Cultist_Saber( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { - if ( (self->spawnflags&8) ) - { +void SP_NPC_Cultist_Saber(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_med_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_med"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_strong_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_strong"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_all_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_all"; } - } - else - { - if ( (self->spawnflags&8) ) - { + } else { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Saber_Powers(1 0 0) (-16 -16 -24) (16 16 40) MED STRONG ALL THROW CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3362,7 +2813,8 @@ default fencer uses fast style - weak, but can attack rapidly. Good defense. MED - Uses medium style - average speed and attack strength, average defense. STRONG - Uses strong style, slower than others, but can do a lot of damage with one blow. Weak defense. ALL - Knows all 3 styles, switches between them, good defense. -THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 spawnflags) +THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 +spawnflags) CEILING - Sticks to the ceiling until he sees an enemy or takes pain CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -3372,57 +2824,36 @@ SHY - Spawner is shy nodelay - set to "1" to make the Cultist not stand around and taunt the player before attacking */ -void SP_NPC_Cultist_Saber_Powers( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { - if ( (self->spawnflags&8) ) - { +void SP_NPC_Cultist_Saber_Powers(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_med_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_med2"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_strong_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_strong2"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_all_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_all2"; } - } - else - { - if ( (self->spawnflags&8) ) - { + } else { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist(1 0 0) (-16 -16 -24) (16 16 40) SABER GRIP LIGHTNING DRAIN CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3442,52 +2873,39 @@ SHY - Spawner is shy nodelay - set to "1" to make the Cultist not stand around and taunt the player before attacking */ -void SP_NPC_Cultist( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Cultist(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = NULL; - self->spawnflags = 0;//fast, no throw - switch ( Q_irand( 0, 2 ) ) - { - case 0://medium + self->spawnflags = 0; // fast, no throw + switch (Q_irand(0, 2)) { + case 0: // medium self->spawnflags |= 1; break; - case 1://strong + case 1: // strong self->spawnflags |= 2; break; - case 2://all + case 2: // all self->spawnflags |= 4; break; } - if ( Q_irand( 0, 1 ) ) - {//throw + if (Q_irand(0, 1)) { // throw self->spawnflags |= 8; } - SP_NPC_Cultist_Saber( self ); + SP_NPC_Cultist_Saber(self); return; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "cultist_grip"; - } - else if ( (self->spawnflags&4) ) - { + } else if ((self->spawnflags & 4)) { self->NPC_type = "cultist_lightning"; - } - else if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 8)) { self->NPC_type = "cultist_drain"; - } - else - { + } else { self->NPC_type = "cultist"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Commando(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3502,13 +2920,11 @@ SHY - Spawner is shy nodelay - set to "1" to make the Cultist not stand around and taunt the player before attacking */ -void SP_NPC_Cultist_Commando( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Cultist_Commando(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "cultistcommando"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Destroyer(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3520,10 +2936,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist_Destroyer( gentity_t *self) -{ +void SP_NPC_Cultist_Destroyer(gentity_t *self) { self->NPC_type = "cultist_destroyer"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_ShadowTrooper(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3535,20 +2950,15 @@ SHY - Spawner is shy nodelay - set to "1" to make the Cultist not stand around and taunt the player before attacking */ -void SP_NPC_ShadowTrooper( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_ShadowTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "ShadowTrooper"; - } - else - { + } else { self->NPC_type = "ShadowTrooper2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Saboteur(1 0 0) (-16 -16 -24) (16 16 40) SNIPER PISTOL x x CLOAKED CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3564,32 +2974,23 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Saboteur( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Saboteur(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "saboteursniper"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "saboteurpistol"; - } - else if ( (self->spawnflags&4) ) - { + } else if ((self->spawnflags & 4)) { self->NPC_type = "saboteurcommando"; - } - else - { + } else { self->NPC_type = "saboteur"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//MONSTERS +// MONSTERS //============================================================================================= /*QUAKED NPC_Monster_Murjj (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3599,11 +3000,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Murjj( gentity_t *self) -{ +void SP_NPC_Monster_Murjj(gentity_t *self) { self->NPC_type = "Murjj"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Swamp (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3613,11 +3013,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Swamp( gentity_t *self) -{ +void SP_NPC_Monster_Swamp(gentity_t *self) { self->NPC_type = "Swamp"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Howler (1 0 0) (-16 -16 -24) (16 16 8) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3627,10 +3026,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Howler( gentity_t *self) -{ +void SP_NPC_Monster_Howler(gentity_t *self) { self->NPC_type = "howler"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Rancor (1 0 0) (-30 -30 -24) (30 30 136) MUTANT FASTKILL x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3644,18 +3042,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Rancor( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Monster_Rancor(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "mutant_rancor"; - } - else - { + } else { self->NPC_type = "rancor"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Mutant_Rancor (1 0 0) (-60 -60 -24) (60 60 360) x FASTKILL x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3668,11 +3062,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Mutant_Rancor( gentity_t *self) -{ +void SP_NPC_Monster_Mutant_Rancor(gentity_t *self) { self->NPC_type = "mutant_rancor"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Wampa (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it @@ -3681,11 +3074,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Wampa( gentity_t *self) -{ +void SP_NPC_Monster_Wampa(gentity_t *self) { self->NPC_type = "wampa"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MineMonster (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it @@ -3694,11 +3086,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MineMonster( gentity_t *self) -{ +void SP_NPC_MineMonster(gentity_t *self) { self->NPC_type = "minemonster"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Claw (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3708,11 +3099,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Claw( gentity_t *self) -{ +void SP_NPC_Monster_Claw(gentity_t *self) { self->NPC_type = "Claw"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Glider (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3722,11 +3112,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Glider( gentity_t *self) -{ +void SP_NPC_Monster_Glider(gentity_t *self) { self->NPC_type = "Glider"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Flier2 (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3736,11 +3125,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Flier2( gentity_t *self) -{ +void SP_NPC_Monster_Flier2(gentity_t *self) { self->NPC_type = "Flier2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Lizard (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3750,11 +3138,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Lizard( gentity_t *self) -{ +void SP_NPC_Monster_Lizard(gentity_t *self) { self->NPC_type = "Lizard"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Fish (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3764,11 +3151,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Fish( gentity_t *self) -{ +void SP_NPC_Monster_Fish(gentity_t *self) { self->NPC_type = "Fish"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Sand_Creature (1 0 0) (-24 -24 -24) (24 24 0) FAST x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3780,22 +3166,18 @@ SHY - Spawner is shy turfrange - if set, they will not go beyond this dist from their spawn position */ -void SP_NPC_Monster_Sand_Creature( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Monster_Sand_Creature(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "sand_creature_fast"; - } - else - { + } else { self->NPC_type = "sand_creature"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//DROIDS +// DROIDS //============================================================================================= /*QUAKED NPC_Droid_Interrogator (1 0 0) (-12 -12 -24) (12 12 0) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3805,11 +3187,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_Interrogator( gentity_t *self) -{ +void SP_NPC_Droid_Interrogator(gentity_t *self) { self->NPC_type = "interrogator"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Probe (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3821,11 +3202,10 @@ SHY - Spawner is shy Imperial Probe Droid - the multilegged floating droid that Han and Chewie shot on the ice planet Hoth */ -void SP_NPC_Droid_Probe( gentity_t *self) -{ +void SP_NPC_Droid_Probe(gentity_t *self) { self->NPC_type = "probe"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Mark1 (1 0 0) (-36 -36 -24) (36 36 80) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3838,11 +3218,10 @@ SHY - Spawner is shy Big walking droid */ -void SP_NPC_Droid_Mark1( gentity_t *self) -{ +void SP_NPC_Droid_Mark1(gentity_t *self) { self->NPC_type = "mark1"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Mark2 (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3855,11 +3234,10 @@ SHY - Spawner is shy Small rolling droid with one gun. */ -void SP_NPC_Droid_Mark2( gentity_t *self) -{ +void SP_NPC_Droid_Mark2(gentity_t *self) { self->NPC_type = "mark2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_ATST (1 0 0) (-40 -40 -24) (40 40 248) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3869,11 +3247,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_ATST( gentity_t *self) -{ +void SP_NPC_Droid_ATST(gentity_t *self) { self->NPC_type = "atst"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Remote (1 0 0) (-4 -4 -24) (4 4 8) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3885,11 +3262,10 @@ SHY - Spawner is shy Remote Droid - the floating round droid used by Obi Wan to train Luke about the force while on the Millenium Falcon. */ -void SP_NPC_Droid_Remote( gentity_t *self) -{ +void SP_NPC_Droid_Remote(gentity_t *self) { self->NPC_type = "remote_sp"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Seeker (1 0 0) (-4 -4 -24) (4 4 8) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3901,11 +3277,10 @@ SHY - Spawner is shy Seeker Droid - floating round droids that shadow troopers spawn */ -void SP_NPC_Droid_Seeker( gentity_t *self) -{ +void SP_NPC_Droid_Seeker(gentity_t *self) { self->NPC_type = "seeker"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Sentry (1 0 0) (-24 -24 -24) (24 24 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3917,12 +3292,10 @@ SHY - Spawner is shy Sentry Droid - Large, armored floating Imperial droids with 3 forward-facing gun turrets */ -void SP_NPC_Droid_Sentry( gentity_t *self) -{ +void SP_NPC_Droid_Sentry(gentity_t *self) { self->NPC_type = "sentry"; - SP_NPC_spawner( self ); - + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Gonk (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3936,11 +3309,10 @@ Gonk Droid - the droid that looks like a walking ice machine. Was in the Jawa la NOTARGET by default */ -void SP_NPC_Droid_Gonk( gentity_t *self) -{ +void SP_NPC_Droid_Gonk(gentity_t *self) { self->NPC_type = "gonk"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Mouse (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3954,11 +3326,10 @@ Mouse Droid - small, box shaped droid, first seen on the Death Star. Chewie yell NOTARGET by default */ -void SP_NPC_Droid_Mouse( gentity_t *self) -{ +void SP_NPC_Droid_Mouse(gentity_t *self) { self->NPC_type = "mouse"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_R2D2 (1 0 0) (-12 -12 -24) (12 12 40) IMPERIAL x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3972,18 +3343,14 @@ R2D2 Droid - you probably know this one already. NOTARGET by default */ -void SP_NPC_Droid_R2D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R2D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r2d2_imp"; - } - else - { + } else { self->NPC_type = "r2d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_R5D2 (1 0 0) (-12 -12 -24) (12 12 40) IMPERIAL ALWAYSDIE x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3998,18 +3365,14 @@ R5D2 Droid - the droid originally chosen by Uncle Owen until it blew a bad motiv NOTARGET by default */ -void SP_NPC_Droid_R5D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R5D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r5d2_imp"; - } - else - { + } else { self->NPC_type = "r5d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Protocol (1 0 0) (-12 -12 -24) (12 12 40) IMPERIAL x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -4021,18 +3384,14 @@ SHY - Spawner is shy NOTARGET by default */ -void SP_NPC_Droid_Protocol( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_Protocol(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "protocol_imp"; - } - else - { + } else { self->NPC_type = "protocol"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Assassin (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -4042,14 +3401,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_Assassin( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Droid_Assassin(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "assassin_droid"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Droid_Saber (1 0 0) (-12 -12 -24) (12 12 40) TRAINING x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -4059,64 +3416,54 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_Saber( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Droid_Saber(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "saber_droid_training"; - } - else - { + } else { self->NPC_type = "saber_droid"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -//NPC console commands +// NPC console commands /* NPC_Spawn_f */ -static void NPC_Spawn_f(void) -{ - gentity_t *NPCspawner = G_Spawn(); - vec3_t forward, end; - trace_t trace; - qboolean isVehicle = qfalse; +static void NPC_Spawn_f(void) { + gentity_t *NPCspawner = G_Spawn(); + vec3_t forward, end; + trace_t trace; + qboolean isVehicle = qfalse; - if(!NPCspawner) - { - gi.Printf( S_COLOR_RED"NPC_Spawn Error: Out of entities!\n" ); + if (!NPCspawner) { + gi.Printf(S_COLOR_RED "NPC_Spawn Error: Out of entities!\n"); return; } NPCspawner->e_ThinkFunc = thinkF_G_FreeEntity; NPCspawner->nextthink = level.time + FRAMETIME; - char *npc_type = gi.argv( 2 ); - if (!npc_type || !npc_type[0] ) - { - gi.Printf( S_COLOR_RED"Error, expected:\n NPC spawn [NPC type (from NCPCs.cfg)]\n" ); + char *npc_type = gi.argv(2); + if (!npc_type || !npc_type[0]) { + gi.Printf(S_COLOR_RED "Error, expected:\n NPC spawn [NPC type (from NCPCs.cfg)]\n"); return; } - if ( !Q_stricmp( "vehicle", npc_type ) ) - {//spawning a vehicle + if (!Q_stricmp("vehicle", npc_type)) { // spawning a vehicle isVehicle = qtrue; - npc_type = gi.argv( 3 ); - if (!npc_type || !npc_type[0] ) - { - gi.Printf( S_COLOR_RED"Error, expected:\n NPC spawn vehicle [NPC type (from NCPCs.cfg)]\n" ); + npc_type = gi.argv(3); + if (!npc_type || !npc_type[0]) { + gi.Printf(S_COLOR_RED "Error, expected:\n NPC spawn vehicle [NPC type (from NCPCs.cfg)]\n"); return; } } - //Spawn it at spot of first player - //FIXME: will gib them! + // Spawn it at spot of first player + // FIXME: will gib them! AngleVectors(g_entities[0].client->ps.viewangles, forward, NULL, NULL); VectorNormalize(forward); VectorMA(g_entities[0].currentOrigin, 64, forward, end); @@ -4128,13 +3475,13 @@ static void NPC_Spawn_f(void) end[2] += 24; G_SetOrigin(NPCspawner, end); VectorCopy(NPCspawner->currentOrigin, NPCspawner->s.origin); - //set the yaw so that they face away from player + // set the yaw so that they face away from player NPCspawner->s.angles[1] = g_entities[0].client->ps.viewangles[1]; gi.linkentity(NPCspawner); - NPCspawner->NPC_type = Q_strlwr( G_NewString( npc_type ) ); - NPCspawner->NPC_targetname = G_NewString(gi.argv( 3 )); + NPCspawner->NPC_type = Q_strlwr(G_NewString(npc_type)); + NPCspawner->NPC_targetname = G_NewString(gi.argv(3)); NPCspawner->count = 1; @@ -4142,40 +3489,32 @@ static void NPC_Spawn_f(void) NPCspawner->wait = 500; - //NPCspawner->spawnflags |= SFB_NOTSOLID; + // NPCspawner->spawnflags |= SFB_NOTSOLID; - //NPCspawner->playerTeam = TEAM_FREE; - //NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; + // NPCspawner->playerTeam = TEAM_FREE; + // NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; - if ( isVehicle ) - {//must let NPC spawn func know this is a vehicle we're trying to spawn + if (isVehicle) { // must let NPC spawn func know this is a vehicle we're trying to spawn NPCspawner->classname = "NPC_Vehicle"; } NPC_PrecacheByClassName(NPCspawner->NPC_type); - if ( !Q_stricmp( "kyle_boss", NPCspawner->NPC_type )) - {//bah + if (!Q_stricmp("kyle_boss", NPCspawner->NPC_type)) { // bah NPCspawner->spawnflags |= 1; } - if ( !Q_stricmp( "key", NPCspawner->NPC_type )) - {//bah + if (!Q_stricmp("key", NPCspawner->NPC_type)) { // bah NPCspawner->message = "key"; NPCspawner->NPC_type = "imperial"; } - if ( !Q_stricmp( "jedi_random", NPCspawner->NPC_type ) ) - {//special case, for testing + if (!Q_stricmp("jedi_random", NPCspawner->NPC_type)) { // special case, for testing NPCspawner->NPC_type = NULL; NPCspawner->spawnflags |= 4; - SP_NPC_Jedi( NPCspawner ); - } - else if ( isVehicle ) - { - SP_NPC_Vehicle( NPCspawner ); - } - else - { - NPC_Spawn( NPCspawner, NPCspawner, NPCspawner ); + SP_NPC_Jedi(NPCspawner); + } else if (isVehicle) { + SP_NPC_Vehicle(NPCspawner); + } else { + NPC_Spawn(NPCspawner, NPCspawner, NPCspawner); } } @@ -4183,80 +3522,65 @@ static void NPC_Spawn_f(void) NPC_Kill_f */ -void NPC_Kill_f( void ) -{ - int n; - gentity_t *player; - char *name; - team_t killTeam = TEAM_FREE; - qboolean killNonSF = qfalse; +void NPC_Kill_f(void) { + int n; + gentity_t *player; + char *name; + team_t killTeam = TEAM_FREE; + qboolean killNonSF = qfalse; - name = gi.argv( 2 ); + name = gi.argv(2); - if ( !*name || !name[0] ) - { - gi.Printf( S_COLOR_RED"Error, Expected:\n"); - gi.Printf( S_COLOR_RED"NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n" ); - gi.Printf( S_COLOR_RED"or\n" ); - gi.Printf( S_COLOR_RED"NPC kill 'all' - kills all NPCs\n" ); - gi.Printf( S_COLOR_RED"or\n" ); - gi.Printf( S_COLOR_RED"NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n" ); + if (!*name || !name[0]) { + gi.Printf(S_COLOR_RED "Error, Expected:\n"); + gi.Printf(S_COLOR_RED "NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n"); + gi.Printf(S_COLOR_RED "or\n"); + gi.Printf(S_COLOR_RED "NPC kill 'all' - kills all NPCs\n"); + gi.Printf(S_COLOR_RED "or\n"); + gi.Printf(S_COLOR_RED "NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n"); return; } - if ( Q_stricmp( "team", name ) == 0 ) - { - name = gi.argv( 3 ); + if (Q_stricmp("team", name) == 0) { + name = gi.argv(3); - if ( !*name || !name[0] ) - { - gi.Printf( S_COLOR_RED"NPC_Kill Error: 'npc kill team' requires a team name!\n" ); - gi.Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED"%s\n", GetStringForID( TeamTable, n ) ); + if (!*name || !name[0]) { + gi.Printf(S_COLOR_RED "NPC_Kill Error: 'npc kill team' requires a team name!\n"); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", GetStringForID(TeamTable, n)); } - gi.Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + gi.Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } - if ( Q_stricmp( "nonally", name ) == 0 ) - { + if (Q_stricmp("nonally", name) == 0) { killNonSF = qtrue; - } - else - { - killTeam = (team_t)GetIDForString( TeamTable, name ); - - if ( killTeam == (team_t)-1 ) - { - gi.Printf( S_COLOR_RED"NPC_Kill Error: team '%s' not recognized\n", name ); - gi.Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED"%s\n", GetStringForID( TeamTable, n ) ); + } else { + killTeam = (team_t)GetIDForString(TeamTable, name); + + if (killTeam == (team_t)-1) { + gi.Printf(S_COLOR_RED "NPC_Kill Error: team '%s' not recognized\n", name); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", GetStringForID(TeamTable, n)); } - gi.Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + gi.Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } } } - for ( n = 1; n < ENTITYNUM_MAX_NORMAL; n++) - { + for (n = 1; n < ENTITYNUM_MAX_NORMAL; n++) { player = &g_entities[n]; if (!player->inuse) { continue; } - if ( killNonSF ) - { - if ( player ) - { - if ( player->client ) - { - if ( player->client->playerTeam != TEAM_PLAYER ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + if (killNonSF) { + if (player) { + if (player->client) { + if (player->client->playerTeam != TEAM_PLAYER) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); /* if ( (player->flags&FL_UNDYING) ) { @@ -4269,22 +3593,17 @@ void NPC_Kill_f( void ) GEntity_DieFunc(player, player, player, player->max_health, MOD_UNKNOWN); } } - } - else if ( player->NPC_type && player->classname && player->classname[0] && Q_stricmp( "NPC_starfleet", player->classname ) != 0 ) - {//A spawner, remove it - gi.Printf( S_COLOR_GREEN"Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname ); - G_FreeEntity( player ); - //FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? + } else if (player->NPC_type && player->classname && player->classname[0] && + Q_stricmp("NPC_starfleet", player->classname) != 0) { // A spawner, remove it + gi.Printf(S_COLOR_GREEN "Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname); + G_FreeEntity(player); + // FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? } } - } - else if ( player && player->NPC && player->client ) - { - if ( killTeam != TEAM_FREE ) - { - if ( player->client->playerTeam == killTeam ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if (player && player->NPC && player->client) { + if (killTeam != TEAM_FREE) { + if (player->client->playerTeam == killTeam) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); /* if ( (player->flags&FL_UNDYING) ) { @@ -4297,11 +3616,8 @@ void NPC_Kill_f( void ) GEntity_DieFunc(player, player, player, player->max_health, MOD_UNKNOWN); } } - } - else if( (player->targetname && Q_stricmp( name, player->targetname ) == 0) - || Q_stricmp( name, "all" ) == 0 ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if ((player->targetname && Q_stricmp(name, player->targetname) == 0) || Q_stricmp(name, "all") == 0) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->client->ps.stats[STAT_HEALTH] = 0; /* if ( (player->flags&FL_UNDYING) ) @@ -4315,84 +3631,59 @@ void NPC_Kill_f( void ) GEntity_DieFunc(player, player, player, 100, MOD_UNKNOWN); } } - } - else if ( player && (player->svFlags&SVF_NPC_PRECACHE) ) - {//a spawner - if( (player->targetname && Q_stricmp( name, player->targetname ) == 0) - || Q_stricmp( name, "all" ) == 0 ) - { - gi.Printf( S_COLOR_GREEN"Removing NPC spawner %s named %s\n", player->NPC_type, player->targetname ); - G_FreeEntity( player ); + } else if (player && (player->svFlags & SVF_NPC_PRECACHE)) { // a spawner + if ((player->targetname && Q_stricmp(name, player->targetname) == 0) || Q_stricmp(name, "all") == 0) { + gi.Printf(S_COLOR_GREEN "Removing NPC spawner %s named %s\n", player->NPC_type, player->targetname); + G_FreeEntity(player); } } } } -void NPC_PrintScore( gentity_t *ent ) -{ - gi.Printf( "%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE] ); -} +void NPC_PrintScore(gentity_t *ent) { gi.Printf("%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE]); } /* Svcmd_NPC_f parse and dispatch bot commands */ -qboolean showBBoxes = qfalse; -void Svcmd_NPC_f( void ) -{ - char *cmd; +qboolean showBBoxes = qfalse; +void Svcmd_NPC_f(void) { + char *cmd; - cmd = gi.argv( 1 ); + cmd = gi.argv(1); - if ( !*cmd ) - { - gi.Printf( "Valid NPC commands are:\n" ); - gi.Printf( " spawn [NPC type (from *.npc files)]\n" ); - gi.Printf( " spawn vehicle [NPC type (from *.npc files, only for NPCs that are CLASS_VEHICLE and have a .veh file)]\n" ); - gi.Printf( " kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n" ); - gi.Printf( " showbounds (draws exact bounding boxes of NPCs)\n" ); - gi.Printf( " score [NPC targetname] (prints number of kills per NPC)\n" ); - } - else if ( Q_stricmp( cmd, "spawn" ) == 0 ) - { + if (!*cmd) { + gi.Printf("Valid NPC commands are:\n"); + gi.Printf(" spawn [NPC type (from *.npc files)]\n"); + gi.Printf(" spawn vehicle [NPC type (from *.npc files, only for NPCs that are CLASS_VEHICLE and have a .veh file)]\n"); + gi.Printf(" kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n"); + gi.Printf(" showbounds (draws exact bounding boxes of NPCs)\n"); + gi.Printf(" score [NPC targetname] (prints number of kills per NPC)\n"); + } else if (Q_stricmp(cmd, "spawn") == 0) { NPC_Spawn_f(); - } - else if ( Q_stricmp( cmd, "kill" ) == 0 ) - { + } else if (Q_stricmp(cmd, "kill") == 0) { NPC_Kill_f(); - } - else if ( Q_stricmp( cmd, "showbounds" ) == 0 ) - {//Toggle on and off + } else if (Q_stricmp(cmd, "showbounds") == 0) { // Toggle on and off showBBoxes = showBBoxes ? qfalse : qtrue; - } - else if ( Q_stricmp ( cmd, "score" ) == 0 ) - { - char *cmd2 = gi.argv(2); + } else if (Q_stricmp(cmd, "score") == 0) { + char *cmd2 = gi.argv(2); gentity_t *ent = NULL; - if ( !cmd2 || !cmd2[0] ) - {//Show the score for all NPCs - gi.Printf( "SCORE LIST:\n" ); - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { + if (!cmd2 || !cmd2[0]) { // Show the score for all NPCs + gi.Printf("SCORE LIST:\n"); + for (int i = 0; i < ENTITYNUM_WORLD; i++) { ent = &g_entities[i]; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { continue; } - NPC_PrintScore( ent ); - } - } - else - { - if ( (ent = G_Find( NULL, FOFS(targetname), cmd2 )) != NULL && ent->client ) - { - NPC_PrintScore( ent ); + NPC_PrintScore(ent); } - else - { - gi.Printf( "ERROR: NPC score - no such NPC %s\n", cmd2 ); + } else { + if ((ent = G_Find(NULL, FOFS(targetname), cmd2)) != NULL && ent->client) { + NPC_PrintScore(ent); + } else { + gi.Printf("ERROR: NPC score - no such NPC %s\n", cmd2); } } } diff --git a/code/game/NPC_stats.cpp b/code/game/NPC_stats.cpp index 1e3ea43cbb..71e649fe50 100644 --- a/code/game/NPC_stats.cpp +++ b/code/game/NPC_stats.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_stats.cpp +// NPC_stats.cpp #include "b_local.h" #include "b_public.h" #include "anims.h" @@ -28,183 +28,160 @@ along with this program; if not, see . #include "g_vehicles.h" #include "../cgame/cg_local.h" #if !defined(RUFL_HSTRING_INC) - #include "../Rufl/hstring.h" +#include "../Rufl/hstring.h" #endif - #include "../Ratl/string_vs.h" - #include "../Rufl/hstring.h" - #include "../Ratl/vector_vs.h" +#include "../Ratl/string_vs.h" +#include "../Rufl/hstring.h" +#include "../Ratl/vector_vs.h" -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); extern qboolean NPCsPrecached; extern vec3_t playerMins; extern vec3_t playerMaxs; extern stringID_table_t WPTable[]; -#define MAX_MODELS_PER_LEVEL 60 - -hstring modelsAlreadyDone[MAX_MODELS_PER_LEVEL]; - - -stringID_table_t animEventTypeTable[] = -{ - ENUM2STRING(AEV_SOUND), //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay - ENUM2STRING(AEV_FOOTSTEP), //# animID AEV_FOOTSTEP framenum footstepType - ENUM2STRING(AEV_EFFECT), //# animID AEV_EFFECT framenum effectpath boltName - ENUM2STRING(AEV_FIRE), //# animID AEV_FIRE framenum altfire chancetofire - ENUM2STRING(AEV_MOVE), //# animID AEV_MOVE framenum forwardpush rightpush uppush - ENUM2STRING(AEV_SOUNDCHAN), //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay - ENUM2STRING(AEV_SABER_SWING), //# animID AEV_SABER_SWING framenum CHANNEL randomlow randomhi chancetoplay - ENUM2STRING(AEV_SABER_SPIN), //# animID AEV_SABER_SPIN framenum CHANNEL chancetoplay - //must be terminated - { NULL,-1 } -}; - -stringID_table_t footstepTypeTable[] = -{ - ENUM2STRING(FOOTSTEP_R), - ENUM2STRING(FOOTSTEP_L), - ENUM2STRING(FOOTSTEP_HEAVY_R), - ENUM2STRING(FOOTSTEP_HEAVY_L), - //must be terminated - { NULL,-1 } -}; - -stringID_table_t FPTable[] = -{ - ENUM2STRING(FP_HEAL), - ENUM2STRING(FP_LEVITATION), - ENUM2STRING(FP_SPEED), - ENUM2STRING(FP_PUSH), - ENUM2STRING(FP_PULL), - ENUM2STRING(FP_TELEPATHY), - ENUM2STRING(FP_GRIP), - ENUM2STRING(FP_LIGHTNING), - ENUM2STRING(FP_SABERTHROW), - ENUM2STRING(FP_SABER_DEFENSE), - ENUM2STRING(FP_SABER_OFFENSE), - //new Jedi Academy powers - ENUM2STRING(FP_RAGE), - ENUM2STRING(FP_PROTECT), - ENUM2STRING(FP_ABSORB), - ENUM2STRING(FP_DRAIN), - ENUM2STRING(FP_SEE), - { "", -1 } -}; - - -stringID_table_t TeamTable[] = -{ - { "free", TEAM_FREE }, // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc - ENUM2STRING(TEAM_FREE), // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc - { "player", TEAM_PLAYER }, +#define MAX_MODELS_PER_LEVEL 60 + +hstring modelsAlreadyDone[MAX_MODELS_PER_LEVEL]; + +stringID_table_t animEventTypeTable[] = {ENUM2STRING(AEV_SOUND), //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay + ENUM2STRING(AEV_FOOTSTEP), //# animID AEV_FOOTSTEP framenum footstepType + ENUM2STRING(AEV_EFFECT), //# animID AEV_EFFECT framenum effectpath boltName + ENUM2STRING(AEV_FIRE), //# animID AEV_FIRE framenum altfire chancetofire + ENUM2STRING(AEV_MOVE), //# animID AEV_MOVE framenum forwardpush rightpush uppush + ENUM2STRING(AEV_SOUNDCHAN), //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay + ENUM2STRING(AEV_SABER_SWING), //# animID AEV_SABER_SWING framenum CHANNEL randomlow randomhi chancetoplay + ENUM2STRING(AEV_SABER_SPIN), //# animID AEV_SABER_SPIN framenum CHANNEL chancetoplay + // must be terminated + {NULL, -1}}; + +stringID_table_t footstepTypeTable[] = {ENUM2STRING(FOOTSTEP_R), + ENUM2STRING(FOOTSTEP_L), + ENUM2STRING(FOOTSTEP_HEAVY_R), + ENUM2STRING(FOOTSTEP_HEAVY_L), + // must be terminated + {NULL, -1}}; + +stringID_table_t FPTable[] = {ENUM2STRING(FP_HEAL), + ENUM2STRING(FP_LEVITATION), + ENUM2STRING(FP_SPEED), + ENUM2STRING(FP_PUSH), + ENUM2STRING(FP_PULL), + ENUM2STRING(FP_TELEPATHY), + ENUM2STRING(FP_GRIP), + ENUM2STRING(FP_LIGHTNING), + ENUM2STRING(FP_SABERTHROW), + ENUM2STRING(FP_SABER_DEFENSE), + ENUM2STRING(FP_SABER_OFFENSE), + // new Jedi Academy powers + ENUM2STRING(FP_RAGE), + ENUM2STRING(FP_PROTECT), + ENUM2STRING(FP_ABSORB), + ENUM2STRING(FP_DRAIN), + ENUM2STRING(FP_SEE), + {"", -1}}; + +stringID_table_t TeamTable[] = { + {"free", TEAM_FREE}, // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc + ENUM2STRING(TEAM_FREE), // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc + {"player", TEAM_PLAYER}, ENUM2STRING(TEAM_PLAYER), - { "enemy", TEAM_ENEMY }, + {"enemy", TEAM_ENEMY}, ENUM2STRING(TEAM_ENEMY), - { "neutral", TEAM_NEUTRAL }, // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator - ENUM2STRING(TEAM_NEUTRAL), // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator - { "", -1 } -}; - + {"neutral", TEAM_NEUTRAL}, // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator + ENUM2STRING(TEAM_NEUTRAL), // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator + {"", -1}}; // this list was made using the model directories, this MUST be in the same order as the CLASS_ enum in teams.h -stringID_table_t ClassTable[] = -{ - ENUM2STRING(CLASS_NONE), // hopefully this will never be used by an npc), just covering all bases - ENUM2STRING(CLASS_ATST), // technically droid... - ENUM2STRING(CLASS_BARTENDER), - ENUM2STRING(CLASS_BESPIN_COP), - ENUM2STRING(CLASS_CLAW), - ENUM2STRING(CLASS_COMMANDO), - ENUM2STRING(CLASS_DESANN), - ENUM2STRING(CLASS_FISH), - ENUM2STRING(CLASS_FLIER2), - ENUM2STRING(CLASS_GALAK), - ENUM2STRING(CLASS_GLIDER), - ENUM2STRING(CLASS_GONK), // droid - ENUM2STRING(CLASS_GRAN), - ENUM2STRING(CLASS_HOWLER), - ENUM2STRING(CLASS_RANCOR), - ENUM2STRING(CLASS_SAND_CREATURE), - ENUM2STRING(CLASS_WAMPA), - ENUM2STRING(CLASS_IMPERIAL), - ENUM2STRING(CLASS_IMPWORKER), - ENUM2STRING(CLASS_INTERROGATOR), // droid - ENUM2STRING(CLASS_JAN), - ENUM2STRING(CLASS_JEDI), - ENUM2STRING(CLASS_KYLE), - ENUM2STRING(CLASS_LANDO), - ENUM2STRING(CLASS_LIZARD), - ENUM2STRING(CLASS_LUKE), - ENUM2STRING(CLASS_MARK1), // droid - ENUM2STRING(CLASS_MARK2), // droid - ENUM2STRING(CLASS_GALAKMECH), // droid - ENUM2STRING(CLASS_MINEMONSTER), - ENUM2STRING(CLASS_MONMOTHA), - ENUM2STRING(CLASS_MORGANKATARN), - ENUM2STRING(CLASS_MOUSE), // droid - ENUM2STRING(CLASS_MURJJ), - ENUM2STRING(CLASS_PRISONER), - ENUM2STRING(CLASS_PROBE), // droid - ENUM2STRING(CLASS_PROTOCOL), // droid - ENUM2STRING(CLASS_R2D2), // droid - ENUM2STRING(CLASS_R5D2), // droid - ENUM2STRING(CLASS_REBEL), - ENUM2STRING(CLASS_REBORN), - ENUM2STRING(CLASS_REELO), - ENUM2STRING(CLASS_REMOTE), - ENUM2STRING(CLASS_RODIAN), - ENUM2STRING(CLASS_SEEKER), // droid - ENUM2STRING(CLASS_SENTRY), - ENUM2STRING(CLASS_SHADOWTROOPER), - ENUM2STRING(CLASS_SABOTEUR), - ENUM2STRING(CLASS_STORMTROOPER), - ENUM2STRING(CLASS_SWAMP), - ENUM2STRING(CLASS_SWAMPTROOPER), - ENUM2STRING(CLASS_NOGHRI), - ENUM2STRING(CLASS_TAVION), - ENUM2STRING(CLASS_ALORA), - ENUM2STRING(CLASS_TRANDOSHAN), - ENUM2STRING(CLASS_UGNAUGHT), - ENUM2STRING(CLASS_JAWA), - ENUM2STRING(CLASS_WEEQUAY), - ENUM2STRING(CLASS_TUSKEN), - ENUM2STRING(CLASS_BOBAFETT), - ENUM2STRING(CLASS_ROCKETTROOPER), - ENUM2STRING(CLASS_SABER_DROID), - ENUM2STRING(CLASS_PLAYER), - ENUM2STRING(CLASS_ASSASSIN_DROID), - ENUM2STRING(CLASS_HAZARD_TROOPER), - ENUM2STRING(CLASS_VEHICLE), - { "", -1 } -}; +stringID_table_t ClassTable[] = {ENUM2STRING(CLASS_NONE), // hopefully this will never be used by an npc), just covering all bases + ENUM2STRING(CLASS_ATST), // technically droid... + ENUM2STRING(CLASS_BARTENDER), + ENUM2STRING(CLASS_BESPIN_COP), + ENUM2STRING(CLASS_CLAW), + ENUM2STRING(CLASS_COMMANDO), + ENUM2STRING(CLASS_DESANN), + ENUM2STRING(CLASS_FISH), + ENUM2STRING(CLASS_FLIER2), + ENUM2STRING(CLASS_GALAK), + ENUM2STRING(CLASS_GLIDER), + ENUM2STRING(CLASS_GONK), // droid + ENUM2STRING(CLASS_GRAN), + ENUM2STRING(CLASS_HOWLER), + ENUM2STRING(CLASS_RANCOR), + ENUM2STRING(CLASS_SAND_CREATURE), + ENUM2STRING(CLASS_WAMPA), + ENUM2STRING(CLASS_IMPERIAL), + ENUM2STRING(CLASS_IMPWORKER), + ENUM2STRING(CLASS_INTERROGATOR), // droid + ENUM2STRING(CLASS_JAN), + ENUM2STRING(CLASS_JEDI), + ENUM2STRING(CLASS_KYLE), + ENUM2STRING(CLASS_LANDO), + ENUM2STRING(CLASS_LIZARD), + ENUM2STRING(CLASS_LUKE), + ENUM2STRING(CLASS_MARK1), // droid + ENUM2STRING(CLASS_MARK2), // droid + ENUM2STRING(CLASS_GALAKMECH), // droid + ENUM2STRING(CLASS_MINEMONSTER), + ENUM2STRING(CLASS_MONMOTHA), + ENUM2STRING(CLASS_MORGANKATARN), + ENUM2STRING(CLASS_MOUSE), // droid + ENUM2STRING(CLASS_MURJJ), + ENUM2STRING(CLASS_PRISONER), + ENUM2STRING(CLASS_PROBE), // droid + ENUM2STRING(CLASS_PROTOCOL), // droid + ENUM2STRING(CLASS_R2D2), // droid + ENUM2STRING(CLASS_R5D2), // droid + ENUM2STRING(CLASS_REBEL), + ENUM2STRING(CLASS_REBORN), + ENUM2STRING(CLASS_REELO), + ENUM2STRING(CLASS_REMOTE), + ENUM2STRING(CLASS_RODIAN), + ENUM2STRING(CLASS_SEEKER), // droid + ENUM2STRING(CLASS_SENTRY), + ENUM2STRING(CLASS_SHADOWTROOPER), + ENUM2STRING(CLASS_SABOTEUR), + ENUM2STRING(CLASS_STORMTROOPER), + ENUM2STRING(CLASS_SWAMP), + ENUM2STRING(CLASS_SWAMPTROOPER), + ENUM2STRING(CLASS_NOGHRI), + ENUM2STRING(CLASS_TAVION), + ENUM2STRING(CLASS_ALORA), + ENUM2STRING(CLASS_TRANDOSHAN), + ENUM2STRING(CLASS_UGNAUGHT), + ENUM2STRING(CLASS_JAWA), + ENUM2STRING(CLASS_WEEQUAY), + ENUM2STRING(CLASS_TUSKEN), + ENUM2STRING(CLASS_BOBAFETT), + ENUM2STRING(CLASS_ROCKETTROOPER), + ENUM2STRING(CLASS_SABER_DROID), + ENUM2STRING(CLASS_PLAYER), + ENUM2STRING(CLASS_ASSASSIN_DROID), + ENUM2STRING(CLASS_HAZARD_TROOPER), + ENUM2STRING(CLASS_VEHICLE), + {"", -1}}; /* NPC_ReactionTime */ -//FIXME use grandom in here -int NPC_ReactionTime ( void ) -{ - return 200 * ( 6 - NPCInfo->stats.reactions ); -} +// FIXME use grandom in here +int NPC_ReactionTime(void) { return 200 * (6 - NPCInfo->stats.reactions); } // // parse support routines // -qboolean G_ParseLiteral( const char **data, const char *string ) -{ - const char *token; +qboolean G_ParseLiteral(const char **data, const char *string) { + const char *token; - token = COM_ParseExt( data, qtrue ); - if ( token[0] == 0 ) - { - gi.Printf( "unexpected EOF\n" ); + token = COM_ParseExt(data, qtrue); + if (token[0] == 0) { + gi.Printf("unexpected EOF\n"); return qtrue; } - if ( Q_stricmp( token, string ) ) - { - gi.Printf( "required string '%s' missing\n", string ); + if (Q_stricmp(token, string)) { + gi.Printf("required string '%s' missing\n", string); return qtrue; } @@ -215,87 +192,70 @@ qboolean G_ParseLiteral( const char **data, const char *string ) // NPC parameters file : ext_data/NPCs/*.npc* // #define MAX_NPC_DATA_SIZE 0x80000 -char NPCParms[MAX_NPC_DATA_SIZE]; +char NPCParms[MAX_NPC_DATA_SIZE]; /* static rank_t TranslateRankName( const char *name ) Should be used to determine pip bolt-ons */ -static rank_t TranslateRankName( const char *name ) -{ - if ( !Q_stricmp( name, "civilian" ) ) - { +static rank_t TranslateRankName(const char *name) { + if (!Q_stricmp(name, "civilian")) { return RANK_CIVILIAN; } - if ( !Q_stricmp( name, "crewman" ) ) - { + if (!Q_stricmp(name, "crewman")) { return RANK_CREWMAN; } - if ( !Q_stricmp( name, "ensign" ) ) - { + if (!Q_stricmp(name, "ensign")) { return RANK_ENSIGN; } - if ( !Q_stricmp( name, "ltjg" ) ) - { + if (!Q_stricmp(name, "ltjg")) { return RANK_LT_JG; } - if ( !Q_stricmp( name, "lt" ) ) - { + if (!Q_stricmp(name, "lt")) { return RANK_LT; } - if ( !Q_stricmp( name, "ltcomm" ) ) - { + if (!Q_stricmp(name, "ltcomm")) { return RANK_LT_COMM; } - if ( !Q_stricmp( name, "commander" ) ) - { + if (!Q_stricmp(name, "commander")) { return RANK_COMMANDER; } - if ( !Q_stricmp( name, "captain" ) ) - { + if (!Q_stricmp(name, "captain")) { return RANK_CAPTAIN; } return RANK_CIVILIAN; } -saber_colors_t TranslateSaberColor( const char *name ) -{ - if ( !Q_stricmp( name, "red" ) ) - { +saber_colors_t TranslateSaberColor(const char *name) { + if (!Q_stricmp(name, "red")) { return SABER_RED; } - if ( !Q_stricmp( name, "orange" ) ) - { + if (!Q_stricmp(name, "orange")) { return SABER_ORANGE; } - if ( !Q_stricmp( name, "yellow" ) ) - { + if (!Q_stricmp(name, "yellow")) { return SABER_YELLOW; } - if ( !Q_stricmp( name, "green" ) ) - { + if (!Q_stricmp(name, "green")) { return SABER_GREEN; } - if ( !Q_stricmp( name, "blue" ) ) - { + if (!Q_stricmp(name, "blue")) { return SABER_BLUE; } - if ( !Q_stricmp( name, "purple" ) ) - { + if (!Q_stricmp(name, "purple")) { return SABER_PURPLE; } - if ( !Q_stricmp( name, "random" ) ) - { - return ((saber_colors_t)(Q_irand( SABER_ORANGE, SABER_PURPLE ))); + if (!Q_stricmp(name, "random")) { + return ((saber_colors_t)(Q_irand(SABER_ORANGE, SABER_PURPLE))); } return SABER_BLUE; } @@ -334,22 +294,14 @@ static int ItemNameToNumber( const char *name, int itemType ) { } */ -static int MoveTypeNameToEnum( const char *name ) -{ - if(!Q_stricmp("runjump", name)) - { +static int MoveTypeNameToEnum(const char *name) { + if (!Q_stricmp("runjump", name)) { return MT_RUNJUMP; - } - else if(!Q_stricmp("walk", name)) - { + } else if (!Q_stricmp("walk", name)) { return MT_WALK; - } - else if(!Q_stricmp("flyswim", name)) - { + } else if (!Q_stricmp("flyswim", name)) { return MT_FLYSWIM; - } - else if(!Q_stricmp("static", name)) - { + } else if (!Q_stricmp("static", name)) { return MT_STATIC; } @@ -357,29 +309,26 @@ static int MoveTypeNameToEnum( const char *name ) } extern void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri); -extern void CG_RegisterClientModels (int entityNum); -extern void CG_RegisterNPCCustomSounds( clientInfo_t *ci ); +extern void CG_RegisterClientModels(int entityNum); +extern void CG_RegisterNPCCustomSounds(clientInfo_t *ci); //#define CONVENIENT_ANIMATION_FILE_DEBUG_THING #ifdef CONVENIENT_ANIMATION_FILE_DEBUG_THING -void SpewDebugStuffToFile(animation_t *bgGlobalAnimations) -{ +void SpewDebugStuffToFile(animation_t *bgGlobalAnimations) { char BGPAFtext[40000]; fileHandle_t f; int i = 0; gi.FS_FOpenFile("file_of_debug_stuff_SP.txt", &f, FS_WRITE); - if (!f) - { + if (!f) { return; } BGPAFtext[0] = 0; - while (i < MAX_ANIMATIONS) - { + while (i < MAX_ANIMATIONS) { strcat(BGPAFtext, va("%i %i\n", i, bgGlobalAnimations[i].frameLerp)); i++; } @@ -389,22 +338,17 @@ void SpewDebugStuffToFile(animation_t *bgGlobalAnimations) } #endif -int CG_CheckAnimFrameForEventType( animevent_t *animEvents, int keyFrame, animEventType_t eventType, unsigned short modelIndex ) -{ - for ( int i = 0; i < MAX_ANIM_EVENTS; i++ ) - { - if ( animEvents[i].keyFrame == keyFrame ) - {//there is an animevent on this frame already - if ( animEvents[i].eventType == eventType ) - {//and it is of the same type - if ( animEvents[i].modelOnly == modelIndex ) - {//and it is for the same model +int CG_CheckAnimFrameForEventType(animevent_t *animEvents, int keyFrame, animEventType_t eventType, unsigned short modelIndex) { + for (int i = 0; i < MAX_ANIM_EVENTS; i++) { + if (animEvents[i].keyFrame == keyFrame) { // there is an animevent on this frame already + if (animEvents[i].eventType == eventType) { // and it is of the same type + if (animEvents[i].modelOnly == modelIndex) { // and it is for the same model return i; } } } } - //nope + // nope return -1; } @@ -413,188 +357,155 @@ int CG_CheckAnimFrameForEventType( animevent_t *animEvents, int keyFrame, animEv ParseAnimationEvtBlock ====================== */ -static void ParseAnimationEvtBlock(int glaIndex, unsigned short modelIndex, const char* aeb_filename, animevent_t *animEvents, animation_t *animations, unsigned char &lastAnimEvent, const char **text_p, bool bIsFrameSkipped) -{ - const char *token; - int num, n, animNum, keyFrame, lowestVal, highestVal, curAnimEvent = 0; - animEventType_t eventType; - char stringData[MAX_QPATH]; +static void ParseAnimationEvtBlock(int glaIndex, unsigned short modelIndex, const char *aeb_filename, animevent_t *animEvents, animation_t *animations, + unsigned char &lastAnimEvent, const char **text_p, bool bIsFrameSkipped) { + const char *token; + int num, n, animNum, keyFrame, lowestVal, highestVal, curAnimEvent = 0; + animEventType_t eventType; + char stringData[MAX_QPATH]; // get past starting bracket - while(1) - { - token = COM_Parse( text_p ); - if ( !Q_stricmp( token, "{" ) ) - { + while (1) { + token = COM_Parse(text_p); + if (!Q_stricmp(token, "{")) { break; } } - //NOTE: instead of a blind increment, increase the index + // NOTE: instead of a blind increment, increase the index // this way if we have an event on an anim that already // has an event of that type, it stomps it // read information for each frame - while ( 1 ) - { + while (1) { // Get base frame of sequence - token = COM_Parse( text_p ); - if ( !token || !token[0]) - { + token = COM_Parse(text_p); + if (!token || !token[0]) { break; } - if ( !Q_stricmp( token, "}" ) ) // At end of block + if (!Q_stricmp(token, "}")) // At end of block { break; } - //Compare to same table as animations used + // Compare to same table as animations used // so we don't have to use actual numbers for animation first frames, // just need offsets. - //This way when animation numbers change, this table won't have to be updated, + // This way when animation numbers change, this table won't have to be updated, // at least not much. animNum = GetIDForString(animTable, token); - if(animNum == -1) - {//Unrecognized ANIM ENUM name, - Com_Printf(S_COLOR_YELLOW"WARNING: Unknown ANIM %s in file %s\n", token, aeb_filename ); - //skip this entry - SkipRestOfLine( text_p ); + if (animNum == -1) { // Unrecognized ANIM ENUM name, + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ANIM %s in file %s\n", token, aeb_filename); + // skip this entry + SkipRestOfLine(text_p); continue; } - if ( animations[animNum].numFrames == 0 ) - {//we don't use this anim + if (animations[animNum].numFrames == 0) { // we don't use this anim #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: %s: anim %s not used by this model\n", aeb_filename, token); + Com_Printf(S_COLOR_YELLOW "WARNING: %s: anim %s not used by this model\n", aeb_filename, token); #endif - //skip this entry - SkipRestOfLine( text_p ); + // skip this entry + SkipRestOfLine(text_p); continue; } - token = COM_Parse( text_p ); + token = COM_Parse(text_p); eventType = (animEventType_t)GetIDForString(animEventTypeTable, token); - if ( eventType == AEV_NONE || eventType == (animEventType_t)-1 ) - {//Unrecognized ANIM EVENT TYPE - Com_Printf(S_COLOR_RED"ERROR: Unknown EVENT %s in animEvent file %s\n", token, aeb_filename ); + if (eventType == AEV_NONE || eventType == (animEventType_t)-1) { // Unrecognized ANIM EVENT TYPE + Com_Printf(S_COLOR_RED "ERROR: Unknown EVENT %s in animEvent file %s\n", token, aeb_filename); continue; } // Get offset to frame within sequence - token = COM_Parse( text_p ); - if ( !token ) - { + token = COM_Parse(text_p); + if (!token) { break; } - keyFrame = atoi( token ); - if ( bIsFrameSkipped && - (animations[animNum].numFrames>2) // important, else frame 1 gets divided down and becomes frame 0. Carcass & Assimilate also work this way - ) - { - keyFrame /= 2; // if we ever use any other value in frame-skipping we'll have to figure out some way of reading it, since it's not stored anywhere + keyFrame = atoi(token); + if (bIsFrameSkipped && + (animations[animNum].numFrames > 2) // important, else frame 1 gets divided down and becomes frame 0. Carcass & Assimilate also work this way + ) { + keyFrame /= 2; // if we ever use any other value in frame-skipping we'll have to figure out some way of reading it, since it's not stored anywhere } - if(keyFrame >= animations[animNum].numFrames) - { - Com_Printf(S_COLOR_YELLOW"WARNING: Event out of range on %s in %s\n", GetStringForID(animTable,animNum), aeb_filename ); + if (keyFrame >= animations[animNum].numFrames) { + Com_Printf(S_COLOR_YELLOW "WARNING: Event out of range on %s in %s\n", GetStringForID(animTable, animNum), aeb_filename); assert(keyFrame < animations[animNum].numFrames); - keyFrame = animations[animNum].numFrames-1; //clamp it + keyFrame = animations[animNum].numFrames - 1; // clamp it } - //set our start frame + // set our start frame keyFrame += animations[animNum].firstFrame; - //see if this frame already has an event of this type on it, if so, overwrite it - curAnimEvent = CG_CheckAnimFrameForEventType( animEvents, keyFrame, eventType, modelIndex ); - if ( curAnimEvent == -1 ) - {//this anim frame doesn't already have an event of this type on it + // see if this frame already has an event of this type on it, if so, overwrite it + curAnimEvent = CG_CheckAnimFrameForEventType(animEvents, keyFrame, eventType, modelIndex); + if (curAnimEvent == -1) { // this anim frame doesn't already have an event of this type on it curAnimEvent = lastAnimEvent; } - //now that we know which event index we're going to plug the data into, start doing it + // now that we know which event index we're going to plug the data into, start doing it animEvents[curAnimEvent].eventType = eventType; - assert(keyFrame >= 0 && keyFrame < 65535); // + assert(keyFrame >= 0 && keyFrame < 65535); // animEvents[curAnimEvent].keyFrame = keyFrame; animEvents[curAnimEvent].glaIndex = glaIndex; animEvents[curAnimEvent].modelOnly = modelIndex; int tempVal; - //now read out the proper data based on the type - switch ( animEvents[curAnimEvent].eventType ) - { - case AEV_SOUNDCHAN: //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay - token = COM_Parse( text_p ); - if ( !token ) - { + // now read out the proper data based on the type + switch (animEvents[curAnimEvent].eventType) { + case AEV_SOUNDCHAN: //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay + token = COM_Parse(text_p); + if (!token) { break; } - if ( Q_stricmp( token, "CHAN_VOICE_ATTEN" ) == 0 ) - { + if (Q_stricmp(token, "CHAN_VOICE_ATTEN") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE_ATTEN; - } - else if ( Q_stricmp( token, "CHAN_VOICE_GLOBAL" ) == 0 ) - { + } else if (Q_stricmp(token, "CHAN_VOICE_GLOBAL") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE_GLOBAL; - } - else if ( Q_stricmp( token, "CHAN_ANNOUNCER" ) == 0 ) - { + } else if (Q_stricmp(token, "CHAN_ANNOUNCER") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_ANNOUNCER; - } - else if ( Q_stricmp( token, "CHAN_BODY" ) == 0 ) - { + } else if (Q_stricmp(token, "CHAN_BODY") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_BODY; - } - else if ( Q_stricmp( token, "CHAN_WEAPON" ) == 0 ) - { + } else if (Q_stricmp(token, "CHAN_WEAPON") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_WEAPON; - } - else if ( Q_stricmp( token, "CHAN_VOICE" ) == 0 ) - { + } else if (Q_stricmp(token, "CHAN_VOICE") == 0) { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE; - } - else - { + } else { animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_AUTO; } - //fall through to normal sound - case AEV_SOUND: //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay - //get soundstring - token = COM_Parse( text_p ); - if ( !token ) - { + // fall through to normal sound + case AEV_SOUND: //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay + // get soundstring + token = COM_Parse(text_p); + if (!token) { break; } strcpy(stringData, token); - //get lowest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get lowest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - lowestVal = atoi( token ); - //get highest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + lowestVal = atoi(token); + // get highest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - highestVal = atoi( token ); - //Now precache all the sounds - //NOTE: If we can be assured sequential handles, we can store the first sound index and count + highestVal = atoi(token); + // Now precache all the sounds + // NOTE: If we can be assured sequential handles, we can store the first sound index and count // unfortunately, if these sounds were previously registered, we cannot be guaranteed sequential indices. Thus an array - if(lowestVal && highestVal) - { + if (lowestVal && highestVal) { assert(highestVal - lowestVal < MAX_RANDOM_ANIM_SOUNDS); - for ( n = lowestVal, num = AED_SOUNDINDEX_START; n <= highestVal && num <= AED_SOUNDINDEX_END; n++, num++ ) - { - animEvents[curAnimEvent].eventData[num] = G_SoundIndex( va( stringData, n ) );//cgi_S_RegisterSound + for (n = lowestVal, num = AED_SOUNDINDEX_START; n <= highestVal && num <= AED_SOUNDINDEX_END; n++, num++) { + animEvents[curAnimEvent].eventData[num] = G_SoundIndex(va(stringData, n)); // cgi_S_RegisterSound } animEvents[curAnimEvent].eventData[AED_SOUND_NUMRANDOMSNDS] = num - 1; - } - else - { - animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] = G_SoundIndex( stringData );//cgi_S_RegisterSound + } else { + animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] = G_SoundIndex(stringData); // cgi_S_RegisterSound #if 0 //#ifndef FINAL_BUILD (only meaningfull if using S_RegisterSound if ( !animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] ) {//couldn't register it - file not found @@ -603,181 +514,146 @@ static void ParseAnimationEvtBlock(int glaIndex, unsigned short modelIndex, cons #endif animEvents[curAnimEvent].eventData[AED_SOUND_NUMRANDOMSNDS] = 0; } - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY] = atoi(token); - //last part - cheat and check and see if it's a special overridable saber sound we know of... - if ( !Q_stricmpn( "sound/weapons/saber/saberhup", stringData, 28 ) ) - {//a saber swing + // last part - cheat and check and see if it's a special overridable saber sound we know of... + if (!Q_stricmpn("sound/weapons/saber/saberhup", stringData, 28)) { // a saber swing animEvents[curAnimEvent].eventType = AEV_SABER_SWING; - animEvents[curAnimEvent].eventData[AED_SABER_SWING_SABERNUM] = 0;//since we don't know which one they meant if we're hacking this, always use first saber + animEvents[curAnimEvent].eventData[AED_SABER_SWING_SABERNUM] = + 0; // since we don't know which one they meant if we're hacking this, always use first saber animEvents[curAnimEvent].eventData[AED_SABER_SWING_PROBABILITY] = animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY]; - if ( lowestVal < 4 ) - {//fast swing + if (lowestVal < 4) { // fast swing animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = SWING_FAST; - } - else if ( lowestVal < 7 ) - {//medium swing + } else if (lowestVal < 7) { // medium swing animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = SWING_MEDIUM; - } - else - {//strong swing + } else { // strong swing animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = SWING_STRONG; } - } - else if ( !Q_stricmpn( "sound/weapons/saber/saberspin", stringData, 29 ) ) - {//a saber spin + } else if (!Q_stricmpn("sound/weapons/saber/saberspin", stringData, 29)) { // a saber spin animEvents[curAnimEvent].eventType = AEV_SABER_SPIN; - animEvents[curAnimEvent].eventData[AED_SABER_SPIN_SABERNUM] = 0;//since we don't know which one they meant if we're hacking this, always use first saber + animEvents[curAnimEvent].eventData[AED_SABER_SPIN_SABERNUM] = + 0; // since we don't know which one they meant if we're hacking this, always use first saber animEvents[curAnimEvent].eventData[AED_SABER_SPIN_PROBABILITY] = animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY]; - if ( stringData[29] == 'o' ) - {//saberspinoff + if (stringData[29] == 'o') { // saberspinoff animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 0; - } - else if ( stringData[29] == '1' ) - {//saberspin1 + } else if (stringData[29] == '1') { // saberspin1 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 2; - } - else if ( stringData[29] == '2' ) - {//saberspin2 + } else if (stringData[29] == '2') { // saberspin2 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 3; - } - else if ( stringData[29] == '3' ) - {//saberspin3 + } else if (stringData[29] == '3') { // saberspin3 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 4; - } - else if ( stringData[29] == '%' ) - {//saberspin%d + } else if (stringData[29] == '%') { // saberspin%d animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 5; - } - else - {//just plain saberspin + } else { // just plain saberspin animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 1; } } break; - case AEV_FOOTSTEP: //# animID AEV_FOOTSTEP framenum footstepType - //get footstep type - token = COM_Parse( text_p ); - if ( !token ) - { + case AEV_FOOTSTEP: //# animID AEV_FOOTSTEP framenum footstepType + // get footstep type + token = COM_Parse(text_p); + if (!token) { break; } animEvents[curAnimEvent].eventData[AED_FOOTSTEP_TYPE] = GetIDForString(footstepTypeTable, token); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FOOTSTEP_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_FOOTSTEP_PROBABILITY] = atoi(token); break; - case AEV_EFFECT: //# animID AEV_EFFECT framenum effectpath boltName - //get effect index - token = COM_Parse( text_p ); - if ( !token ) - { + case AEV_EFFECT: //# animID AEV_EFFECT framenum effectpath boltName + // get effect index + token = COM_Parse(text_p); + if (!token) { break; } - if ( token[0] && Q_stricmp( "special", token ) == 0 ) - {//special hard-coded effects - //let cgame know it's not a real effect + if (token[0] && Q_stricmp("special", token) == 0) { // special hard-coded effects + // let cgame know it's not a real effect animEvents[curAnimEvent].eventData[AED_EFFECTINDEX] = -1; - //get the name of it - token = COM_Parse( text_p ); - animEvents[curAnimEvent].stringData = G_NewString( token ); - } - else - {//regular effect + // get the name of it + token = COM_Parse(text_p); + animEvents[curAnimEvent].stringData = G_NewString(token); + } else { // regular effect tempVal = G_EffectIndex(token); assert(tempVal > -32767 && tempVal < 32767); animEvents[curAnimEvent].eventData[AED_EFFECTINDEX] = tempVal; - //get bolt index - token = COM_Parse( text_p ); - if ( !token ) - { + // get bolt index + token = COM_Parse(text_p); + if (!token) { break; } - if ( Q_stricmp( "none", token ) != 0 && Q_stricmp( "NULL", token ) != 0 ) - {//actually are specifying a bolt to use - animEvents[curAnimEvent].stringData = G_NewString( token ); + if (Q_stricmp("none", token) != 0 && Q_stricmp("NULL", token) != 0) { // actually are specifying a bolt to use + animEvents[curAnimEvent].stringData = G_NewString(token); } } - //NOTE: this string will later be used to add a bolt and store the index, as below: - //animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // NOTE: this string will later be used to add a bolt and store the index, as below: + // animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_EFFECT_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_EFFECT_PROBABILITY] = atoi(token); break; - case AEV_FIRE: //# animID AEV_FIRE framenum altfire chancetofire - //get altfire - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + case AEV_FIRE: //# animID AEV_FIRE framenum altfire chancetofire + // get altfire + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FIRE_ALT] = atoi( token ); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + animEvents[curAnimEvent].eventData[AED_FIRE_ALT] = atoi(token); + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FIRE_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_FIRE_PROBABILITY] = atoi(token); break; - case AEV_MOVE: //# animID AEV_MOVE framenum forwardpush rightpush uppush - //get forward push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + case AEV_MOVE: //# animID AEV_MOVE framenum forwardpush rightpush uppush + // get forward push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } tempVal = atoi(token); assert(tempVal > -32767 && tempVal < 32767); animEvents[curAnimEvent].eventData[AED_MOVE_FWD] = tempVal; - //get right push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get right push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } tempVal = atoi(token); assert(tempVal > -32767 && tempVal < 32767); animEvents[curAnimEvent].eventData[AED_MOVE_RT] = tempVal; - //get upwards push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get upwards push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } tempVal = atoi(token); assert(tempVal > -32767 && tempVal < 32767); animEvents[curAnimEvent].eventData[AED_MOVE_UP] = tempVal; break; - default: //unknown? - SkipRestOfLine( text_p ); + default: // unknown? + SkipRestOfLine(text_p); continue; break; } - if ( curAnimEvent == lastAnimEvent ) - { + if (curAnimEvent == lastAnimEvent) { lastAnimEvent++; } } } - - /* ====================== G_ParseAnimationEvtFile @@ -789,77 +665,68 @@ This file's presence is not required ====================== */ -static -void G_ParseAnimationEvtFile(int glaIndex, const char* eventsDirectory, int fileIndex, int iRealGLAIndex = -1, bool modelSpecific = false) -{ - int len; - const char* token; - char text[80000]; - const char* text_p = text; - fileHandle_t f; - char eventsPath[MAX_QPATH]; - int modelIndex = 0; - - assert(fileIndex>=0 && fileIndex5 && !Q_stricmp(&psAnimFileInternalName[strlen(psAnimFileInternalName)-5],"_skip")); +static void G_ParseAnimationEvtFile(int glaIndex, const char *eventsDirectory, int fileIndex, int iRealGLAIndex = -1, bool modelSpecific = false) { + int len; + const char *token; + char text[80000]; + const char *text_p = text; + fileHandle_t f; + char eventsPath[MAX_QPATH]; + int modelIndex = 0; + + assert(fileIndex >= 0 && fileIndex < MAX_ANIM_FILES); + + const char *psAnimFileInternalName = (iRealGLAIndex == -1 ? NULL : gi.G2API_GetAnimFileInternalNameIndex(iRealGLAIndex)); + bool bIsFrameSkipped = + (psAnimFileInternalName && strlen(psAnimFileInternalName) > 5 && !Q_stricmp(&psAnimFileInternalName[strlen(psAnimFileInternalName) - 5], "_skip")); // Open The File, Make Sure It Is Safe //------------------------------------- Com_sprintf(eventsPath, MAX_QPATH, "models/players/%s/animevents.cfg", eventsDirectory); len = cgi_FS_FOpenFile(eventsPath, &f, FS_READ); - if ( len <= 0 ) - {//no file + if (len <= 0) { // no file return; } - if ( len >= (int)(sizeof( text ) - 1) ) - { - cgi_FS_FCloseFile( f ); - CG_Printf( "File %s too long\n", eventsPath ); + if (len >= (int)(sizeof(text) - 1)) { + cgi_FS_FCloseFile(f); + CG_Printf("File %s too long\n", eventsPath); return; } // Read It To The Buffer, Close The File //--------------------------------------- - cgi_FS_Read( text, len, f ); + cgi_FS_Read(text, len, f); text[len] = 0; - cgi_FS_FCloseFile( f ); - + cgi_FS_FCloseFile(f); // Get The Pointers To The Anim Event Arrays //------------------------------------------- - animFileSet_t& afileset = level.knownAnimFileSets[fileIndex]; - animevent_t *legsAnimEvents = afileset.legsAnimEvents; - animevent_t *torsoAnimEvents = afileset.torsoAnimEvents; - animation_t *animations = afileset.animations; + animFileSet_t &afileset = level.knownAnimFileSets[fileIndex]; + animevent_t *legsAnimEvents = afileset.legsAnimEvents; + animevent_t *torsoAnimEvents = afileset.torsoAnimEvents; + animation_t *animations = afileset.animations; - - if (modelSpecific) - { - hstring modelName(eventsDirectory); + if (modelSpecific) { + hstring modelName(eventsDirectory); modelIndex = modelName.handle(); } - // read information for batches of sounds (UPPER or LOWER) COM_BeginParseSession(); - while ( 1 ) - { + while (1) { // Get base frame of sequence - token = COM_Parse( &text_p ); - if ( !token || !token[0] ) - { + token = COM_Parse(&text_p); + if (!token || !token[0]) { break; } - //these stomp anything set in the include file (if it's an event of the same type on the same frame)! - if ( !Q_stricmp(token,"UPPEREVENTS") ) // A batch of upper events + // these stomp anything set in the include file (if it's an event of the same type on the same frame)! + if (!Q_stricmp(token, "UPPEREVENTS")) // A batch of upper events { ParseAnimationEvtBlock(glaIndex, modelIndex, eventsPath, torsoAnimEvents, animations, afileset.torsoAnimEventCount, &text_p, bIsFrameSkipped); } - else if ( !Q_stricmp(token,"LOWEREVENTS") ) // A batch of lower events + else if (!Q_stricmp(token, "LOWEREVENTS")) // A batch of lower events { ParseAnimationEvtBlock(glaIndex, modelIndex, eventsPath, legsAnimEvents, animations, afileset.legsAnimEventCount, &text_p, bIsFrameSkipped); } @@ -876,150 +743,126 @@ models/players/visor/animation.cfg, etc ====================== */ -qboolean G_ParseAnimationFile(int glaIndex, const char *skeletonName, int fileIndex) -{ - char text[80000]; - int len = 0; - const char *token = 0; - float fps = 0; - const char* text_p = text; - int animNum = 0; - animation_t* animations = level.knownAnimFileSets[fileIndex].animations; - char skeletonPath[MAX_QPATH]; - +qboolean G_ParseAnimationFile(int glaIndex, const char *skeletonName, int fileIndex) { + char text[80000]; + int len = 0; + const char *token = 0; + float fps = 0; + const char *text_p = text; + int animNum = 0; + animation_t *animations = level.knownAnimFileSets[fileIndex].animations; + char skeletonPath[MAX_QPATH]; // Read In The File To The Text Buffer, Make Sure Everything Is Safe To Continue //------------------------------------------------------------------------------- Com_sprintf(skeletonPath, MAX_QPATH, "models/players/%s/%s.cfg", skeletonName, skeletonName); len = gi.RE_GetAnimationCFG(skeletonPath, text, sizeof(text)); - if ( len <= 0 ) - { + if (len <= 0) { Com_sprintf(skeletonPath, MAX_QPATH, "models/players/%s/animation.cfg", skeletonName); len = gi.RE_GetAnimationCFG(skeletonPath, text, sizeof(text)); - if ( len <= 0 ) - { + if (len <= 0) { return qfalse; } } - if ( len >= (int)(sizeof( text ) - 1) ) - { - G_Error( "G_ParseAnimationFile: File %s too long\n (%d > %d)", skeletonName, len, sizeof( text ) - 1); + if (len >= (int)(sizeof(text) - 1)) { + G_Error("G_ParseAnimationFile: File %s too long\n (%d > %d)", skeletonName, len, sizeof(text) - 1); return qfalse; } - - // Read In Each Token //-------------------- COM_BeginParseSession(); - while(1) - { - token = COM_Parse( &text_p ); + while (1) { + token = COM_Parse(&text_p); // If No Token, We've Reached The End Of The File //------------------------------------------------ - if ( !token || !token[0]) - { + if (!token || !token[0]) { break; } // Get The Anim Number Converted From The First Token //---------------------------------------------------- animNum = GetIDForString(animTable, token); - if(animNum == -1) - { + if (animNum == -1) { #ifndef FINAL_BUILD - if (strcmp(token,"ROOT")) - { - Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, skeletonPath); + if (strcmp(token, "ROOT")) { + Com_Printf(S_COLOR_RED "WARNING: Unknown token %s in %s\n", token, skeletonPath); } #endif - //unrecognized animation so skip to end of line, - while (token[0]) - { - token = COM_ParseExt( &text_p, qfalse ); //returns empty string when next token is EOL + // unrecognized animation so skip to end of line, + while (token[0]) { + token = COM_ParseExt(&text_p, qfalse); // returns empty string when next token is EOL } continue; } // GLAIndex //---------- - animations[animNum].glaIndex = glaIndex; // Passed Into This Func + animations[animNum].glaIndex = glaIndex; // Passed Into This Func // First Frame //------------- - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } assert(atoi(token) >= 0 && atoi(token) < 65536); - animations[animNum].firstFrame = atoi( token ); + animations[animNum].firstFrame = atoi(token); // Num Frames //------------ - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } assert(atoi(token) >= 0 && atoi(token) < 65536); - animations[animNum].numFrames = atoi( token ); + animations[animNum].numFrames = atoi(token); // Loop Frames //------------- - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } assert(atoi(token) >= -1 && atoi(token) < 128); - animations[animNum].loopFrames = atoi( token ); + animations[animNum].loopFrames = atoi(token); // FPS //----- - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - fps = atof( token ); - if ( fps == 0 ) - { - fps = 1;//Don't allow divide by zero error + fps = atof(token); + if (fps == 0) { + fps = 1; // Don't allow divide by zero error } // Calculate Frame Lerp //---------------------- int lerp; - if ( fps < 0 ) - {//backwards + if (fps < 0) { // backwards lerp = floor(1000.0f / fps); assert(lerp > -32767 && lerp < 32767); animations[animNum].frameLerp = lerp; assert(animations[animNum].frameLerp <= 1); - } - else - { + } else { lerp = ceil(1000.0f / fps); assert(lerp > -32767 && lerp < 32767); animations[animNum].frameLerp = lerp; assert(animations[animNum].frameLerp >= 1); } -/* lerp = ceil(1000.0f / Q_fabs(fps)); - assert(lerp > -32767 && lerp < 32767); - animations[animNum].initialLerp = lerp; -*/ + /* lerp = ceil(1000.0f / Q_fabs(fps)); + assert(lerp > -32767 && lerp < 32767); + animations[animNum].initialLerp = lerp; + */ } COM_EndParseSession(); - - - #ifdef CONVENIENT_ANIMATION_FILE_DEBUG_THING - if (strstr(af_filename, "humanoid")) - { + if (strstr(af_filename, "humanoid")) { SpewDebugStuffToFile(animations); } #endif @@ -1027,9 +870,6 @@ qboolean G_ParseAnimationFile(int glaIndex, const char *skeletonName, int fileIn return qtrue; } - - - //////////////////////////////////////////////////////////////////////// // G_ParseAnimFileSet // @@ -1037,28 +877,22 @@ qboolean G_ParseAnimationFile(int glaIndex, const char *skeletonName, int fileIn // the animation event file. // //////////////////////////////////////////////////////////////////////// -int G_ParseAnimFileSet(const char *skeletonName, const char *modelName=0) -{ - int fileIndex=0; - +int G_ParseAnimFileSet(const char *skeletonName, const char *modelName = 0) { + int fileIndex = 0; // Try To Find An Existing Skeleton File For This Animation Set //-------------------------------------------------------------- - for (fileIndex=0; fileIndex=level.numKnownAnimFileSets) - { - if (level.numKnownAnimFileSets==MAX_ANIM_FILES) - { - G_Error( "G_ParseAnimFileSet: MAX_ANIM_FILES" ); + if (fileIndex >= level.numKnownAnimFileSets) { + if (level.numKnownAnimFileSets == MAX_ANIM_FILES) { + G_Error("G_ParseAnimFileSet: MAX_ANIM_FILES"); return -1; } @@ -1071,123 +905,108 @@ int G_ParseAnimFileSet(const char *skeletonName, const char *modelName=0) level.knownAnimFileSets[fileIndex].torsoAnimEventCount = 0; level.knownAnimFileSets[fileIndex].legsAnimEventCount = 0; - animation_t* animations = level.knownAnimFileSets[fileIndex].animations; - animevent_t* legsAnimEvents = level.knownAnimFileSets[fileIndex].legsAnimEvents; - animevent_t* torsoAnimEvents = level.knownAnimFileSets[fileIndex].torsoAnimEvents; + animation_t *animations = level.knownAnimFileSets[fileIndex].animations; + animevent_t *legsAnimEvents = level.knownAnimFileSets[fileIndex].legsAnimEvents; + animevent_t *torsoAnimEvents = level.knownAnimFileSets[fileIndex].torsoAnimEvents; int i, j; // Initialize The Frames Information //----------------------------------- - for(i=0; iplayerModel == -1 ) - { +extern cvar_t *g_char_model; +void G_LoadAnimFileSet(gentity_t *ent, const char *pModelName) { + // load its animation config + char animName[MAX_QPATH]; + char *GLAName, *modelName; + char *slash = NULL; + char *strippedName; + + if (ent->playerModel == -1) { return; } - if ( Q_stricmp( "player", pModelName ) == 0 ) - {//model is actually stored on console + if (Q_stricmp("player", pModelName) == 0) { // model is actually stored on console modelName = g_char_model->string; - } - else - { + } else { modelName = (char *)pModelName; } - //get the location of the animation.cfg - GLAName = gi.G2API_GetGLAName( &ent->ghoul2[ent->playerModel] ); - //now load and parse the animation.cfg, animevents.cfg and set the animFileIndex - if ( !GLAName) - { - Com_Printf( S_COLOR_RED"Failed find animation file name models/players/%s\n", modelName ); - strippedName="_humanoid"; //take a guess, maybe it's right? - } - else - { - Q_strncpyz( animName, GLAName, sizeof( animName ) ); - slash = strrchr( animName, '/' ); - if ( slash ) - { + // get the location of the animation.cfg + GLAName = gi.G2API_GetGLAName(&ent->ghoul2[ent->playerModel]); + // now load and parse the animation.cfg, animevents.cfg and set the animFileIndex + if (!GLAName) { + Com_Printf(S_COLOR_RED "Failed find animation file name models/players/%s\n", modelName); + strippedName = "_humanoid"; // take a guess, maybe it's right? + } else { + Q_strncpyz(animName, GLAName, sizeof(animName)); + slash = strrchr(animName, '/'); + if (slash) { *slash = 0; } - strippedName = COM_SkipPath( animName ); + strippedName = COM_SkipPath(animName); } - //now load and parse the animation.cfg, animevents.cfg and set the animFileIndex + // now load and parse the animation.cfg, animevents.cfg and set the animFileIndex ent->client->clientInfo.animFileIndex = G_ParseAnimFileSet(strippedName, modelName); - if (ent->client->clientInfo.animFileIndex<0) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/%s/animation.cfg\n", modelName ); + if (ent->client->clientInfo.animFileIndex < 0) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/%s/animation.cfg\n", modelName); #ifndef FINAL_BUILD Com_Error(ERR_FATAL, "Failed to load animation file set models/players/%s/animation.cfg\n", modelName); #endif } } +void NPC_PrecacheAnimationCFG(const char *NPC_type) { + char filename[MAX_QPATH]; + const char *token; + const char *value; + const char *p; -void NPC_PrecacheAnimationCFG( const char *NPC_type ) -{ - char filename[MAX_QPATH]; - const char *token; - const char *value; - const char *p; - - if ( !Q_stricmp( "random", NPC_type ) ) - {//sorry, can't precache a random just yet + if (!Q_stricmp("random", NPC_type)) { // sorry, can't precache a random just yet return; } @@ -1265,130 +1071,113 @@ void NPC_PrecacheAnimationCFG( const char *NPC_type ) COM_BeginParseSession(); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, NPC_type ) ) - { + if (!Q_stricmp(token, NPC_type)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", NPC_type ); - COM_EndParseSession( ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", NPC_type); + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - //must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt - Q_strncpyz( filename, value, sizeof( filename ) ); - G_ParseAnimFileSet( filename ); - COM_EndParseSession( ); + // must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt + Q_strncpyz(filename, value, sizeof(filename)); + G_ParseAnimFileSet(filename); + COM_EndParseSession(); return; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - char animName[MAX_QPATH]; - char *GLAName; - char *slash = NULL; - char *strippedName; + char animName[MAX_QPATH]; + char *GLAName; + char *slash = NULL; + char *strippedName; - int handle = gi.G2API_PrecacheGhoul2Model( va( "models/players/%s/model.glm", value ) ); - if ( handle > 0 )//FIXME: isn't 0 a valid handle? + int handle = gi.G2API_PrecacheGhoul2Model(va("models/players/%s/model.glm", value)); + if (handle > 0) // FIXME: isn't 0 a valid handle? { - GLAName = gi.G2API_GetAnimFileNameIndex( handle ); - if ( GLAName ) - { - Q_strncpyz( animName, GLAName, sizeof( animName ) ); - slash = strrchr( animName, '/' ); - if ( slash ) - { + GLAName = gi.G2API_GetAnimFileNameIndex(handle); + if (GLAName) { + Q_strncpyz(animName, GLAName, sizeof(animName)); + slash = strrchr(animName, '/'); + if (slash) { *slash = 0; } - strippedName = COM_SkipPath( animName ); + strippedName = COM_SkipPath(animName); - //must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt - Q_strncpyz( filename, value, sizeof( filename ) ); + // must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt + Q_strncpyz(filename, value, sizeof(filename)); G_ParseAnimFileSet(strippedName, filename); - COM_EndParseSession( ); + COM_EndParseSession(); return; } } } } - COM_EndParseSession( ); + COM_EndParseSession(); } -extern int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ); -void NPC_PrecacheWeapons( team_t playerTeam, int spawnflags, char *NPCtype ) -{ - int weapons = NPC_WeaponsForTeam( playerTeam, spawnflags, NPCtype ); - gitem_t *item; - for ( int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if ( (weapons & ( 1 << curWeap )) ) - { - item = FindItemForWeapon( ((weapon_t)(curWeap)) ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - //precache the in-hand/in-world ghoul2 weapon model +extern int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type); +void NPC_PrecacheWeapons(team_t playerTeam, int spawnflags, char *NPCtype) { + int weapons = NPC_WeaponsForTeam(playerTeam, spawnflags, NPCtype); + gitem_t *item; + for (int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if ((weapons & (1 << curWeap))) { + item = FindItemForWeapon(((weapon_t)(curWeap))); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + // precache the in-hand/in-world ghoul2 weapon model char weaponModel[64]; - strcpy (weaponModel, weaponData[curWeap].weaponMdl); - if (char *spot = strstr(weaponModel, ".md3") ) { + strcpy(weaponModel, weaponData[curWeap].weaponMdl); + if (char *spot = strstr(weaponModel, ".md3")) { *spot = 0; - spot = strstr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on + spot = strstr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on if (!spot) { - strcat (weaponModel, "_w"); + strcat(weaponModel, "_w"); } - strcat (weaponModel, ".glm"); //and change to ghoul2 + strcat(weaponModel, ".glm"); // and change to ghoul2 } - gi.G2API_PrecacheGhoul2Model( weaponModel ); // correct way is item->world_model + gi.G2API_PrecacheGhoul2Model(weaponModel); // correct way is item->world_model } } } @@ -1400,621 +1189,488 @@ This runs all the class specific precache functions */ -extern void NPC_ShadowTrooper_Precache( void ); -extern void NPC_Gonk_Precache( void ); -extern void NPC_Mouse_Precache( void ); -extern void NPC_Seeker_Precache( void ); -extern void NPC_Remote_Precache( void ); -extern void NPC_R2D2_Precache(void); -extern void NPC_R5D2_Precache(void); +extern void NPC_ShadowTrooper_Precache(void); +extern void NPC_Gonk_Precache(void); +extern void NPC_Mouse_Precache(void); +extern void NPC_Seeker_Precache(void); +extern void NPC_Remote_Precache(void); +extern void NPC_R2D2_Precache(void); +extern void NPC_R5D2_Precache(void); extern void NPC_Probe_Precache(void); extern void NPC_Interrogator_Precache(gentity_t *self); -extern void NPC_MineMonster_Precache( void ); -extern void NPC_Howler_Precache( void ); -extern void NPC_Rancor_Precache( void ); -extern void NPC_MutantRancor_Precache( void ); -extern void NPC_Wampa_Precache( void ); +extern void NPC_MineMonster_Precache(void); +extern void NPC_Howler_Precache(void); +extern void NPC_Rancor_Precache(void); +extern void NPC_MutantRancor_Precache(void); +extern void NPC_Wampa_Precache(void); extern void NPC_ATST_Precache(void); extern void NPC_Sentry_Precache(void); extern void NPC_Mark1_Precache(void); extern void NPC_Mark2_Precache(void); -extern void NPC_Protocol_Precache( void ); -extern void Boba_Precache( void ); -extern void RT_Precache( void ); -extern void SandCreature_Precache( void ); -extern void NPC_TavionScepter_Precache( void ); -extern void NPC_TavionSithSword_Precache( void ); -extern void NPC_Rosh_Dark_Precache( void ); -extern void NPC_Tusken_Precache( void ); -extern void NPC_Saboteur_Precache( void ); -extern void NPC_CultistDestroyer_Precache( void ); -void NPC_Jawa_Precache( void ) -{ - for ( int i = 1; i < 7; i++ ) - { - G_SoundIndex( va( "sound/chars/jawa/misc/chatter%d.wav", i ) ); - } - G_SoundIndex( "sound/chars/jawa/misc/ooh-tee-nee.wav" ); +extern void NPC_Protocol_Precache(void); +extern void Boba_Precache(void); +extern void RT_Precache(void); +extern void SandCreature_Precache(void); +extern void NPC_TavionScepter_Precache(void); +extern void NPC_TavionSithSword_Precache(void); +extern void NPC_Rosh_Dark_Precache(void); +extern void NPC_Tusken_Precache(void); +extern void NPC_Saboteur_Precache(void); +extern void NPC_CultistDestroyer_Precache(void); +void NPC_Jawa_Precache(void) { + for (int i = 1; i < 7; i++) { + G_SoundIndex(va("sound/chars/jawa/misc/chatter%d.wav", i)); + } + G_SoundIndex("sound/chars/jawa/misc/ooh-tee-nee.wav"); } -void NPC_PrecacheByClassName( const char* type ) -{ - if (!type || !type[0]) - { +void NPC_PrecacheByClassName(const char *type) { + if (!type || !type[0]) { return; } - if ( !Q_stricmp( "gonk", type)) - { + if (!Q_stricmp("gonk", type)) { NPC_Gonk_Precache(); - } - else if ( !Q_stricmp( "mouse", type)) - { + } else if (!Q_stricmp("mouse", type)) { NPC_Mouse_Precache(); - } - else if ( !Q_stricmpn( "r2d2", type, 4)) - { + } else if (!Q_stricmpn("r2d2", type, 4)) { NPC_R2D2_Precache(); - } - else if ( !Q_stricmp( "atst", type)) - { + } else if (!Q_stricmp("atst", type)) { NPC_ATST_Precache(); - } - else if ( !Q_stricmpn( "r5d2", type, 4)) - { + } else if (!Q_stricmpn("r5d2", type, 4)) { NPC_R5D2_Precache(); - } - else if ( !Q_stricmp( "mark1", type)) - { + } else if (!Q_stricmp("mark1", type)) { NPC_Mark1_Precache(); - } - else if ( !Q_stricmp( "mark2", type)) - { + } else if (!Q_stricmp("mark2", type)) { NPC_Mark2_Precache(); - } - else if ( !Q_stricmp( "interrogator", type)) - { + } else if (!Q_stricmp("interrogator", type)) { NPC_Interrogator_Precache(NULL); - } - else if ( !Q_stricmp( "probe", type)) - { + } else if (!Q_stricmp("probe", type)) { NPC_Probe_Precache(); - } - else if ( !Q_stricmp( "seeker", type)) - { + } else if (!Q_stricmp("seeker", type)) { NPC_Seeker_Precache(); - } - else if ( !Q_stricmpn( "remote", type, 6)) - { + } else if (!Q_stricmpn("remote", type, 6)) { NPC_Remote_Precache(); - } - else if ( !Q_stricmpn( "shadowtrooper", type, 13 ) ) - { + } else if (!Q_stricmpn("shadowtrooper", type, 13)) { NPC_ShadowTrooper_Precache(); - } - else if ( !Q_stricmp( "minemonster", type )) - { + } else if (!Q_stricmp("minemonster", type)) { NPC_MineMonster_Precache(); - } - else if ( !Q_stricmp( "howler", type )) - { + } else if (!Q_stricmp("howler", type)) { NPC_Howler_Precache(); - } - else if ( !Q_stricmp( "rancor", type )) - { + } else if (!Q_stricmp("rancor", type)) { NPC_Rancor_Precache(); - } - else if ( !Q_stricmp( "mutant_rancor", type )) - { + } else if (!Q_stricmp("mutant_rancor", type)) { NPC_Rancor_Precache(); NPC_MutantRancor_Precache(); - } - else if ( !Q_stricmp( "wampa", type )) - { + } else if (!Q_stricmp("wampa", type)) { NPC_Wampa_Precache(); - } - else if ( !Q_stricmp( "sand_creature", type )) - { + } else if (!Q_stricmp("sand_creature", type)) { SandCreature_Precache(); - } - else if ( !Q_stricmp( "sentry", type )) - { + } else if (!Q_stricmp("sentry", type)) { NPC_Sentry_Precache(); - } - else if ( !Q_stricmp( "protocol", type )) - { + } else if (!Q_stricmp("protocol", type)) { NPC_Protocol_Precache(); - } - else if ( !Q_stricmp( "boba_fett", type )) - { + } else if (!Q_stricmp("boba_fett", type)) { Boba_Precache(); - } - else if ( !Q_stricmp( "rockettrooper2", type )) - { + } else if (!Q_stricmp("rockettrooper2", type)) { RT_Precache(); - } - else if ( !Q_stricmp( "rockettrooper2Officer", type )) - { + } else if (!Q_stricmp("rockettrooper2Officer", type)) { RT_Precache(); - } - else if ( !Q_stricmp( "tavion_scepter", type )) - { + } else if (!Q_stricmp("tavion_scepter", type)) { NPC_TavionScepter_Precache(); - } - else if ( !Q_stricmp( "tavion_sith_sword", type )) - { + } else if (!Q_stricmp("tavion_sith_sword", type)) { NPC_TavionSithSword_Precache(); - } - else if ( !Q_stricmp( "rosh_dark", type ) ) - { + } else if (!Q_stricmp("rosh_dark", type)) { NPC_Rosh_Dark_Precache(); - } - else if ( !Q_stricmpn( "tusken", type, 6 ) ) - { + } else if (!Q_stricmpn("tusken", type, 6)) { NPC_Tusken_Precache(); - } - else if ( !Q_stricmpn( "saboteur", type, 8 ) ) - { + } else if (!Q_stricmpn("saboteur", type, 8)) { NPC_Saboteur_Precache(); - } - else if ( !Q_stricmp( "cultist_destroyer", type ) ) - { + } else if (!Q_stricmp("cultist_destroyer", type)) { NPC_CultistDestroyer_Precache(); - } - else if ( !Q_stricmpn( "jawa", type, 4 ) ) - { + } else if (!Q_stricmpn("jawa", type, 4)) { NPC_Jawa_Precache(); } } - - /* void NPC_Precache ( char *NPCName ) Precaches NPC skins, tgas and md3s. */ -void CG_NPC_Precache ( gentity_t *spawner ) -{ - clientInfo_t ci={}; - renderInfo_t ri={}; - team_t playerTeam = TEAM_FREE; - const char *token; - const char *value; - const char *p; - char *patch; - char sound[MAX_QPATH]; - qboolean md3Model = qfalse; - char playerModel[MAX_QPATH] = { 0 }; - char customSkin[MAX_QPATH]; - - if ( !Q_stricmp( "random", spawner->NPC_type ) ) - {//sorry, can't precache a random just yet +void CG_NPC_Precache(gentity_t *spawner) { + clientInfo_t ci = {}; + renderInfo_t ri = {}; + team_t playerTeam = TEAM_FREE; + const char *token; + const char *value; + const char *p; + char *patch; + char sound[MAX_QPATH]; + qboolean md3Model = qfalse; + char playerModel[MAX_QPATH] = {0}; + char customSkin[MAX_QPATH]; + + if (!Q_stricmp("random", spawner->NPC_type)) { // sorry, can't precache a random just yet return; } - strcpy(customSkin,"default"); + strcpy(customSkin, "default"); p = NPCParms; COM_BeginParseSession(); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, spawner->NPC_type ) ) - { + if (!Q_stricmp(token, spawner->NPC_type)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return; } // parse the NPC info block - while ( 1 ) - { - COM_EndParseSession(); // if still in session (or using continue;) + while (1) { + COM_EndParseSession(); // if still in session (or using continue;) COM_BeginParseSession(); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type ); - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type); + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { - Q_strncpyz( ri.headModelName, value, sizeof(ri.headModelName)); + if (!Q_stricmp("none", value)) { + } else { + Q_strncpyz(ri.headModelName, value, sizeof(ri.headModelName)); } md3Model = qtrue; continue; } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { - Q_strncpyz( ri.torsoModelName, value, sizeof(ri.torsoModelName)); + if (!Q_stricmp("none", value)) { + } else { + Q_strncpyz(ri.torsoModelName, value, sizeof(ri.torsoModelName)); } md3Model = qtrue; continue; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( ri.legsModelName, value, sizeof(ri.legsModelName)); + Q_strncpyz(ri.legsModelName, value, sizeof(ri.legsModelName)); md3Model = qtrue; continue; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( playerModel, value, sizeof(playerModel)); + Q_strncpyz(playerModel, value, sizeof(playerModel)); md3Model = qfalse; continue; } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( customSkin, value, sizeof(customSkin)); + Q_strncpyz(customSkin, value, sizeof(customSkin)); continue; } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerTeam")) { + if (COM_ParseString(&p, &value)) { continue; } - playerTeam = (team_t)GetIDForString( TeamTable, token ); + playerTeam = (team_t)GetIDForString(TeamTable, token); continue; } - // snd - if ( !Q_stricmp( token, "snd" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customBasicSoundDir = G_NewString( sound ); + ci.customBasicSoundDir = G_NewString(sound); } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customCombatSoundDir = G_NewString( sound ); + ci.customCombatSoundDir = G_NewString(sound); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customExtraSoundDir = G_NewString( sound ); + ci.customExtraSoundDir = G_NewString(sound); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customJediSoundDir = G_NewString( sound ); + ci.customJediSoundDir = G_NewString(sound); } continue; } - //cache weapons - if ( !Q_stricmp( token, "weapon" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // cache weapons + if (!Q_stricmp(token, "weapon")) { + if (COM_ParseString(&p, &value)) { continue; } - int weap = GetIDForString( WPTable, value ); - if ( weap >= WP_NONE && weap < WP_NUM_WEAPONS ) - { - if ( weap > WP_NONE ) - { - RegisterItem( FindItemForWeapon( (weapon_t)(weap) ) ); //precache the weapon + int weap = GetIDForString(WPTable, value); + if (weap >= WP_NONE && weap < WP_NUM_WEAPONS) { + if (weap > WP_NONE) { + RegisterItem(FindItemForWeapon((weapon_t)(weap))); // precache the weapon } } continue; } - //cache sabers - //saber name - if ( !Q_stricmp( token, "saber" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // cache sabers + // saber name + if (!Q_stricmp(token, "saber")) { + if (COM_ParseString(&p, &value)) { continue; } - char *saberName = G_NewString( value ); + char *saberName = G_NewString(value); saberInfo_t saber; - WP_SaberParseParms( saberName, &saber ); - if ( saber.model && saber.model[0] ) - { - G_ModelIndex( saber.model ); + WP_SaberParseParms(saberName, &saber); + if (saber.model && saber.model[0]) { + G_ModelIndex(saber.model); } - if ( saber.skin && saber.skin[0] ) - { - gi.RE_RegisterSkin( saber.skin ); - G_SkinIndex( saber.skin ); + if (saber.skin && saber.skin[0]) { + gi.RE_RegisterSkin(saber.skin); + G_SkinIndex(saber.skin); } - if ( saber.g2MarksShader[0] ) - { - cgi_R_RegisterShader( saber.g2MarksShader ); + if (saber.g2MarksShader[0]) { + cgi_R_RegisterShader(saber.g2MarksShader); } - if ( saber.g2MarksShader2[0] ) - { - cgi_R_RegisterShader( saber.g2MarksShader2 ); + if (saber.g2MarksShader2[0]) { + cgi_R_RegisterShader(saber.g2MarksShader2); } - if ( saber.g2WeaponMarkShader[0] ) - { - cgi_R_RegisterShader( saber.g2WeaponMarkShader ); + if (saber.g2WeaponMarkShader[0]) { + cgi_R_RegisterShader(saber.g2WeaponMarkShader); } - if ( saber.g2WeaponMarkShader2[0] ) - { - cgi_R_RegisterShader( saber.g2WeaponMarkShader2 ); + if (saber.g2WeaponMarkShader2[0]) { + cgi_R_RegisterShader(saber.g2WeaponMarkShader2); } continue; } - //second saber name - if ( !Q_stricmp( token, "saber2" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // second saber name + if (!Q_stricmp(token, "saber2")) { + if (COM_ParseString(&p, &value)) { continue; } - char *saberName = G_NewString( value ); + char *saberName = G_NewString(value); saberInfo_t saber; - WP_SaberParseParms( saberName, &saber ); - if ( saber.model && saber.model[0] ) - { - G_ModelIndex( saber.model ); + WP_SaberParseParms(saberName, &saber); + if (saber.model && saber.model[0]) { + G_ModelIndex(saber.model); } - if ( saber.skin && saber.skin[0] ) - { - gi.RE_RegisterSkin( saber.skin ); - G_SkinIndex( saber.skin ); + if (saber.skin && saber.skin[0]) { + gi.RE_RegisterSkin(saber.skin); + G_SkinIndex(saber.skin); } continue; } } - COM_EndParseSession( ); + COM_EndParseSession(); - if ( md3Model ) - { - CG_RegisterClientRenderInfo( &ci, &ri ); - } - else - { - char skinName[MAX_QPATH]; - //precache ghoul2 model - gi.G2API_PrecacheGhoul2Model( va( "models/players/%s/model.glm", playerModel ) ); - //precache skin - if (strchr(customSkin, '|')) - {//three part skin - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/|%s", playerModel, customSkin ); - } - else - {//standard skin - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_%s.skin", playerModel, customSkin ); + if (md3Model) { + CG_RegisterClientRenderInfo(&ci, &ri); + } else { + char skinName[MAX_QPATH]; + // precache ghoul2 model + gi.G2API_PrecacheGhoul2Model(va("models/players/%s/model.glm", playerModel)); + // precache skin + if (strchr(customSkin, '|')) { // three part skin + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/|%s", playerModel, customSkin); + } else { // standard skin + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_%s.skin", playerModel, customSkin); } // lets see if it's out there - gi.RE_RegisterSkin( skinName ); + gi.RE_RegisterSkin(skinName); } - //precache this NPC's possible weapons - NPC_PrecacheWeapons( playerTeam, spawner->spawnflags, spawner->NPC_type ); + // precache this NPC's possible weapons + NPC_PrecacheWeapons(playerTeam, spawner->spawnflags, spawner->NPC_type); // Anything else special about them - NPC_PrecacheByClassName( spawner->NPC_type ); - - CG_RegisterNPCCustomSounds( &ci ); + NPC_PrecacheByClassName(spawner->NPC_type); - //CG_RegisterNPCEffects( playerTeam ); - //FIXME: Look for a "sounds" directory and precache death, pain, alert sounds -} + CG_RegisterNPCCustomSounds(&ci); -void NPC_BuildRandom( gentity_t *NPC ) -{ + // CG_RegisterNPCEffects( playerTeam ); + // FIXME: Look for a "sounds" directory and precache death, pain, alert sounds } -extern void G_MatchPlayerWeapon( gentity_t *ent ); -extern void G_InitPlayerFromCvars( gentity_t *ent ); -extern void G_SetG2PlayerModel( gentity_t * const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ); -qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) -{ - const char *token; - const char *value; - const char *p; - int n; - float f; - char *patch; - char sound[MAX_QPATH]; - char playerModel[MAX_QPATH]; - char customSkin[MAX_QPATH]; - clientInfo_t *ci = &NPC->client->clientInfo; - renderInfo_t *ri = &NPC->client->renderInfo; - gNPCstats_t *stats = NULL; - qboolean md3Model = qtrue; - char surfOff[1024]={0}; - char surfOn[1024]={0}; +void NPC_BuildRandom(gentity_t *NPC) {} + +extern void G_MatchPlayerWeapon(gentity_t *ent); +extern void G_InitPlayerFromCvars(gentity_t *ent); +extern void G_SetG2PlayerModel(gentity_t *const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn); +qboolean NPC_ParseParms(const char *NPCName, gentity_t *NPC) { + const char *token; + const char *value; + const char *p; + int n; + float f; + char *patch; + char sound[MAX_QPATH]; + char playerModel[MAX_QPATH]; + char customSkin[MAX_QPATH]; + clientInfo_t *ci = &NPC->client->clientInfo; + renderInfo_t *ri = &NPC->client->renderInfo; + gNPCstats_t *stats = NULL; + qboolean md3Model = qtrue; + char surfOff[1024] = {0}; + char surfOn[1024] = {0}; qboolean parsingPlayer = qfalse; - strcpy(customSkin,"default"); - if ( !NPCName || !NPCName[0]) - { + strcpy(customSkin, "default"); + if (!NPCName || !NPCName[0]) { NPCName = "Player"; } - if ( !NPC->s.number && NPC->client != NULL ) - {//player, only want certain data + if (!NPC->s.number && NPC->client != NULL) { // player, only want certain data parsingPlayer = qtrue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats = &NPC->NPC->stats; -/* - NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; - NPC->NPC->allWeaponOrder[1] = WP_SABER; - NPC->NPC->allWeaponOrder[2] = WP_IMOD; - NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; - NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[7] = WP_NONE; -*/ + /* + NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; + NPC->NPC->allWeaponOrder[1] = WP_SABER; + NPC->NPC->allWeaponOrder[2] = WP_IMOD; + NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; + NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[7] = WP_NONE; + */ // fill in defaults - stats->sex = SEX_MALE; - stats->aggression = 3; - stats->aim = 3; - stats->earshot = 1024; - stats->evasion = 3; - stats->hfov = 90; - stats->intelligence = 3; - stats->move = 3; - stats->reactions = 3; - stats->vfov = 60; - stats->vigilance = 0.1f; - stats->visrange = 1024; - if (g_entities[ENTITYNUM_WORLD].max_health && stats->visrange>g_entities[ENTITYNUM_WORLD].max_health) - { - stats->visrange = g_entities[ENTITYNUM_WORLD].max_health; - } - stats->health = 0; - - stats->yawSpeed = 90; - stats->walkSpeed = 90; - stats->runSpeed = 300; - stats->acceleration = 15;//Increase/descrease speed this much per frame (20fps) - } - else - { + stats->sex = SEX_MALE; + stats->aggression = 3; + stats->aim = 3; + stats->earshot = 1024; + stats->evasion = 3; + stats->hfov = 90; + stats->intelligence = 3; + stats->move = 3; + stats->reactions = 3; + stats->vfov = 60; + stats->vigilance = 0.1f; + stats->visrange = 1024; + if (g_entities[ENTITYNUM_WORLD].max_health && stats->visrange > g_entities[ENTITYNUM_WORLD].max_health) { + stats->visrange = g_entities[ENTITYNUM_WORLD].max_health; + } + stats->health = 0; + + stats->yawSpeed = 90; + stats->walkSpeed = 90; + stats->runSpeed = 300; + stats->acceleration = 15; // Increase/descrease speed this much per frame (20fps) + } else { stats = NULL; } - Q_strncpyz( ci->name, NPCName, sizeof( ci->name ) ); + Q_strncpyz(ci->name, NPCName, sizeof(ci->name)); NPC->playerModel = -1; - //Set defaults - //FIXME: should probably put default torso and head models, but what about enemies - //that don't have any- like Stasis? - //Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName), qtrue); - //Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName), qtrue); - //Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName), qtrue); + // Set defaults + // FIXME: should probably put default torso and head models, but what about enemies + // that don't have any- like Stasis? + // Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName), qtrue); + // Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName), qtrue); + // Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName), qtrue); ri->headModelName[0] = 0; - ri->torsoModelName[0]= 0; - ri->legsModelName[0] =0; + ri->torsoModelName[0] = 0; + ri->legsModelName[0] = 0; ri->headYawRangeLeft = 80; ri->headYawRangeRight = 80; @@ -2030,7 +1686,7 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) NPC->client->crouchheight = CROUCH_MAXS_2; NPC->client->standheight = DEFAULT_MAXS_2; - NPC->client->moveType = MT_RUNJUMP; + NPC->client->moveType = MT_RUNJUMP; NPC->client->dismemberProbHead = 100; NPC->client->dismemberProbArms = 100; @@ -2042,683 +1698,587 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) ri->customRGBA[0] = ri->customRGBA[1] = ri->customRGBA[2] = ri->customRGBA[3] = 0xFFu; - if ( !Q_stricmp( "random", NPCName ) ) - {//Randomly assemble an NPC - NPC_BuildRandom( NPC ); - } - else - { + if (!Q_stricmp("random", NPCName)) { // Randomly assemble an NPC + NPC_BuildRandom(NPC); + } else { p = NPCParms; COM_BeginParseSession(); #ifdef _WIN32 #pragma region(NPC Stats) #endif // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, NPCName ) ) - { + if (!Q_stricmp(token, NPCName)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return qfalse; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return qfalse; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", NPCName ); - COM_EndParseSession( ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", NPCName); + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - //===MODEL PROPERTIES=========================================================== + //===MODEL PROPERTIES=========================================================== // custom color - if ( !Q_stricmp( token, "customRGBA" ) ) - { + if (!Q_stricmp(token, "customRGBA")) { // eezstreet TODO: Put these into functions, damn it! They're too big! - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - if ( !Q_stricmp( value, "random") ) - { - ri->customRGBA[0]=Q_irand(0,255); - ri->customRGBA[1]=Q_irand(0,255); - ri->customRGBA[2]=Q_irand(0,255); - ri->customRGBA[3]=255; - } - else if ( !Q_stricmp( value, "random1") ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,5)) - { + if (!Q_stricmp(value, "random")) { + ri->customRGBA[0] = Q_irand(0, 255); + ri->customRGBA[1] = Q_irand(0, 255); + ri->customRGBA[2] = Q_irand(0, 255); + ri->customRGBA[3] = 255; + } else if (!Q_stricmp(value, "random1")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 5)) { default: case 0: - ri->customRGBA[0]=127; - ri->customRGBA[1]=153; - ri->customRGBA[2]=255; + ri->customRGBA[0] = 127; + ri->customRGBA[1] = 153; + ri->customRGBA[2] = 255; break; case 1: - ri->customRGBA[0]=177; - ri->customRGBA[1]=29; - ri->customRGBA[2]=13; + ri->customRGBA[0] = 177; + ri->customRGBA[1] = 29; + ri->customRGBA[2] = 13; break; case 2: - ri->customRGBA[0]=47; - ri->customRGBA[1]=90; - ri->customRGBA[2]=40; + ri->customRGBA[0] = 47; + ri->customRGBA[1] = 90; + ri->customRGBA[2] = 40; break; case 3: - ri->customRGBA[0]=181; - ri->customRGBA[1]=207; - ri->customRGBA[2]=255; + ri->customRGBA[0] = 181; + ri->customRGBA[1] = 207; + ri->customRGBA[2] = 255; break; case 4: - ri->customRGBA[0]=138; - ri->customRGBA[1]=83; - ri->customRGBA[2]=0; + ri->customRGBA[0] = 138; + ri->customRGBA[1] = 83; + ri->customRGBA[2] = 0; break; case 5: - ri->customRGBA[0]=254; - ri->customRGBA[1]=199; - ri->customRGBA[2]=14; + ri->customRGBA[0] = 254; + ri->customRGBA[1] = 199; + ri->customRGBA[2] = 14; break; } - } - else if ( !Q_stricmp( value, "jedi_hf" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,7)) - { + } else if (!Q_stricmp(value, "jedi_hf")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 7)) { default: - case 0://red1 - ri->customRGBA[0]=165; - ri->customRGBA[1]=48; - ri->customRGBA[2]=21; + case 0: // red1 + ri->customRGBA[0] = 165; + ri->customRGBA[1] = 48; + ri->customRGBA[2] = 21; break; - case 1://yellow1 - ri->customRGBA[0]=254; - ri->customRGBA[1]=230; - ri->customRGBA[2]=132; + case 1: // yellow1 + ri->customRGBA[0] = 254; + ri->customRGBA[1] = 230; + ri->customRGBA[2] = 132; break; - case 2://bluegray - ri->customRGBA[0]=181; - ri->customRGBA[1]=207; - ri->customRGBA[2]=255; + case 2: // bluegray + ri->customRGBA[0] = 181; + ri->customRGBA[1] = 207; + ri->customRGBA[2] = 255; break; - case 3://pink - ri->customRGBA[0]=233; - ri->customRGBA[1]=183; - ri->customRGBA[2]=208; + case 3: // pink + ri->customRGBA[0] = 233; + ri->customRGBA[1] = 183; + ri->customRGBA[2] = 208; break; - case 4://lt blue - ri->customRGBA[0]=161; - ri->customRGBA[1]=226; - ri->customRGBA[2]=240; + case 4: // lt blue + ri->customRGBA[0] = 161; + ri->customRGBA[1] = 226; + ri->customRGBA[2] = 240; break; - case 5://blue - ri->customRGBA[0]=101; - ri->customRGBA[1]=159; - ri->customRGBA[2]=255; + case 5: // blue + ri->customRGBA[0] = 101; + ri->customRGBA[1] = 159; + ri->customRGBA[2] = 255; break; - case 6://orange - ri->customRGBA[0]=255; - ri->customRGBA[1]=157; - ri->customRGBA[2]=114; + case 6: // orange + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 157; + ri->customRGBA[2] = 114; break; - case 7://violet - ri->customRGBA[0]=216; - ri->customRGBA[1]=160; - ri->customRGBA[2]=255; + case 7: // violet + ri->customRGBA[0] = 216; + ri->customRGBA[1] = 160; + ri->customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_hm" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,7)) - { + } else if (!Q_stricmp(value, "jedi_hm")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 7)) { default: - case 0://yellow - ri->customRGBA[0]=252; - ri->customRGBA[1]=243; - ri->customRGBA[2]=180; + case 0: // yellow + ri->customRGBA[0] = 252; + ri->customRGBA[1] = 243; + ri->customRGBA[2] = 180; break; - case 1://blue - ri->customRGBA[0]=69; - ri->customRGBA[1]=109; - ri->customRGBA[2]=255; + case 1: // blue + ri->customRGBA[0] = 69; + ri->customRGBA[1] = 109; + ri->customRGBA[2] = 255; break; - case 2://gold - ri->customRGBA[0]=254; - ri->customRGBA[1]=197; - ri->customRGBA[2]=73; + case 2: // gold + ri->customRGBA[0] = 254; + ri->customRGBA[1] = 197; + ri->customRGBA[2] = 73; break; - case 3://orange - ri->customRGBA[0]=178; - ri->customRGBA[1]=78; - ri->customRGBA[2]=18; + case 3: // orange + ri->customRGBA[0] = 178; + ri->customRGBA[1] = 78; + ri->customRGBA[2] = 18; break; - case 4://bluegreen - ri->customRGBA[0]=112; - ri->customRGBA[1]=153; - ri->customRGBA[2]=161; + case 4: // bluegreen + ri->customRGBA[0] = 112; + ri->customRGBA[1] = 153; + ri->customRGBA[2] = 161; break; - case 5://blue2 - ri->customRGBA[0]=123; - ri->customRGBA[1]=182; - ri->customRGBA[2]=255; + case 5: // blue2 + ri->customRGBA[0] = 123; + ri->customRGBA[1] = 182; + ri->customRGBA[2] = 255; break; - case 6://green2 - ri->customRGBA[0]=0; - ri->customRGBA[1]=88; - ri->customRGBA[2]=105; + case 6: // green2 + ri->customRGBA[0] = 0; + ri->customRGBA[1] = 88; + ri->customRGBA[2] = 105; break; - case 7://violet - ri->customRGBA[0]=138; - ri->customRGBA[1]=0; - ri->customRGBA[2]=0; + case 7: // violet + ri->customRGBA[0] = 138; + ri->customRGBA[1] = 0; + ri->customRGBA[2] = 0; break; } - } - else if ( !Q_stricmp( value, "jedi_kdm" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,8)) - { + } else if (!Q_stricmp(value, "jedi_kdm")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 8)) { default: - case 0://blue - ri->customRGBA[0]=85; - ri->customRGBA[1]=120; - ri->customRGBA[2]=255; + case 0: // blue + ri->customRGBA[0] = 85; + ri->customRGBA[1] = 120; + ri->customRGBA[2] = 255; break; - case 1://violet - ri->customRGBA[0]=173; - ri->customRGBA[1]=142; - ri->customRGBA[2]=219; + case 1: // violet + ri->customRGBA[0] = 173; + ri->customRGBA[1] = 142; + ri->customRGBA[2] = 219; break; - case 2://brown1 - ri->customRGBA[0]=254; - ri->customRGBA[1]=197; - ri->customRGBA[2]=73; + case 2: // brown1 + ri->customRGBA[0] = 254; + ri->customRGBA[1] = 197; + ri->customRGBA[2] = 73; break; - case 3://orange - ri->customRGBA[0]=138; - ri->customRGBA[1]=83; - ri->customRGBA[2]=0; + case 3: // orange + ri->customRGBA[0] = 138; + ri->customRGBA[1] = 83; + ri->customRGBA[2] = 0; break; - case 4://gold - ri->customRGBA[0]=254; - ri->customRGBA[1]=199; - ri->customRGBA[2]=14; + case 4: // gold + ri->customRGBA[0] = 254; + ri->customRGBA[1] = 199; + ri->customRGBA[2] = 14; break; - case 5://blue2 - ri->customRGBA[0]=68; - ri->customRGBA[1]=194; - ri->customRGBA[2]=217; + case 5: // blue2 + ri->customRGBA[0] = 68; + ri->customRGBA[1] = 194; + ri->customRGBA[2] = 217; break; - case 6://red1 - ri->customRGBA[0]=170; - ri->customRGBA[1]=3; - ri->customRGBA[2]=30; + case 6: // red1 + ri->customRGBA[0] = 170; + ri->customRGBA[1] = 3; + ri->customRGBA[2] = 30; break; - case 7://yellow1 - ri->customRGBA[0]=225; - ri->customRGBA[1]=226; - ri->customRGBA[2]=144; + case 7: // yellow1 + ri->customRGBA[0] = 225; + ri->customRGBA[1] = 226; + ri->customRGBA[2] = 144; break; - case 8://violet2 - ri->customRGBA[0]=167; - ri->customRGBA[1]=202; - ri->customRGBA[2]=255; + case 8: // violet2 + ri->customRGBA[0] = 167; + ri->customRGBA[1] = 202; + ri->customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_rm" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,8)) - { + } else if (!Q_stricmp(value, "jedi_rm")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 8)) { default: - case 0://blue - ri->customRGBA[0]=127; - ri->customRGBA[1]=153; - ri->customRGBA[2]=255; + case 0: // blue + ri->customRGBA[0] = 127; + ri->customRGBA[1] = 153; + ri->customRGBA[2] = 255; break; - case 1://green1 - ri->customRGBA[0]=208; - ri->customRGBA[1]=249; - ri->customRGBA[2]=85; + case 1: // green1 + ri->customRGBA[0] = 208; + ri->customRGBA[1] = 249; + ri->customRGBA[2] = 85; break; - case 2://blue2 - ri->customRGBA[0]=181; - ri->customRGBA[1]=207; - ri->customRGBA[2]=255; + case 2: // blue2 + ri->customRGBA[0] = 181; + ri->customRGBA[1] = 207; + ri->customRGBA[2] = 255; break; - case 3://gold - ri->customRGBA[0]=138; - ri->customRGBA[1]=83; - ri->customRGBA[2]=0; + case 3: // gold + ri->customRGBA[0] = 138; + ri->customRGBA[1] = 83; + ri->customRGBA[2] = 0; break; - case 4://gold - ri->customRGBA[0]=224; - ri->customRGBA[1]=171; - ri->customRGBA[2]=44; + case 4: // gold + ri->customRGBA[0] = 224; + ri->customRGBA[1] = 171; + ri->customRGBA[2] = 44; break; - case 5://green2 - ri->customRGBA[0]=49; - ri->customRGBA[1]=155; - ri->customRGBA[2]=131; + case 5: // green2 + ri->customRGBA[0] = 49; + ri->customRGBA[1] = 155; + ri->customRGBA[2] = 131; break; - case 6://red1 - ri->customRGBA[0]=163; - ri->customRGBA[1]=79; - ri->customRGBA[2]=17; + case 6: // red1 + ri->customRGBA[0] = 163; + ri->customRGBA[1] = 79; + ri->customRGBA[2] = 17; break; - case 7://violet2 - ri->customRGBA[0]=148; - ri->customRGBA[1]=104; - ri->customRGBA[2]=228; + case 7: // violet2 + ri->customRGBA[0] = 148; + ri->customRGBA[1] = 104; + ri->customRGBA[2] = 228; break; - case 8://green3 - ri->customRGBA[0]=138; - ri->customRGBA[1]=136; - ri->customRGBA[2]=0; + case 8: // green3 + ri->customRGBA[0] = 138; + ri->customRGBA[1] = 136; + ri->customRGBA[2] = 0; break; } - } - else if ( !Q_stricmp( value, "jedi_tf" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,5)) - { + } else if (!Q_stricmp(value, "jedi_tf")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 5)) { default: - case 0://green1 - ri->customRGBA[0]=255; - ri->customRGBA[1]=235; - ri->customRGBA[2]=100; + case 0: // green1 + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 235; + ri->customRGBA[2] = 100; break; - case 1://blue1 - ri->customRGBA[0]=62; - ri->customRGBA[1]=155; - ri->customRGBA[2]=255; + case 1: // blue1 + ri->customRGBA[0] = 62; + ri->customRGBA[1] = 155; + ri->customRGBA[2] = 255; break; - case 2://red1 - ri->customRGBA[0]=255; - ri->customRGBA[1]=110; - ri->customRGBA[2]=120; + case 2: // red1 + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 110; + ri->customRGBA[2] = 120; break; - case 3://purple - ri->customRGBA[0]=180; - ri->customRGBA[1]=150; - ri->customRGBA[2]=255; + case 3: // purple + ri->customRGBA[0] = 180; + ri->customRGBA[1] = 150; + ri->customRGBA[2] = 255; break; - case 4://flesh - ri->customRGBA[0]=255; - ri->customRGBA[1]=200; - ri->customRGBA[2]=212; + case 4: // flesh + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 200; + ri->customRGBA[2] = 212; break; - case 5://base - ri->customRGBA[0]=255; - ri->customRGBA[1]=255; - ri->customRGBA[2]=255; + case 5: // base + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 255; + ri->customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_zf" ) ) - { - ri->customRGBA[3]=255; - switch (Q_irand(0,7)) - { + } else if (!Q_stricmp(value, "jedi_zf")) { + ri->customRGBA[3] = 255; + switch (Q_irand(0, 7)) { default: - case 0://red1 - ri->customRGBA[0]=204; - ri->customRGBA[1]=19; - ri->customRGBA[2]=21; + case 0: // red1 + ri->customRGBA[0] = 204; + ri->customRGBA[1] = 19; + ri->customRGBA[2] = 21; break; - case 1://orange1 - ri->customRGBA[0]=255; - ri->customRGBA[1]=107; - ri->customRGBA[2]=40; + case 1: // orange1 + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 107; + ri->customRGBA[2] = 40; break; - case 2://pink1 - ri->customRGBA[0]=255; - ri->customRGBA[1]=148; - ri->customRGBA[2]=155; + case 2: // pink1 + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 148; + ri->customRGBA[2] = 155; break; - case 3://gold - ri->customRGBA[0]=255; - ri->customRGBA[1]=164; - ri->customRGBA[2]=59; + case 3: // gold + ri->customRGBA[0] = 255; + ri->customRGBA[1] = 164; + ri->customRGBA[2] = 59; break; - case 4://violet1 - ri->customRGBA[0]=216; - ri->customRGBA[1]=160; - ri->customRGBA[2]=255; + case 4: // violet1 + ri->customRGBA[0] = 216; + ri->customRGBA[1] = 160; + ri->customRGBA[2] = 255; break; - case 5://blue1 - ri->customRGBA[0]=101; - ri->customRGBA[1]=159; - ri->customRGBA[2]=255; + case 5: // blue1 + ri->customRGBA[0] = 101; + ri->customRGBA[1] = 159; + ri->customRGBA[2] = 255; break; - case 6://blue2 - ri->customRGBA[0]=161; - ri->customRGBA[1]=226; - ri->customRGBA[2]=240; + case 6: // blue2 + ri->customRGBA[0] = 161; + ri->customRGBA[1] = 226; + ri->customRGBA[2] = 240; break; - case 7://blue3 - ri->customRGBA[0]=37; - ri->customRGBA[1]=155; - ri->customRGBA[2]=181; + case 7: // blue3 + ri->customRGBA[0] = 37; + ri->customRGBA[1] = 155; + ri->customRGBA[2] = 181; break; } - } - else - { - ri->customRGBA[0]=atoi(value); + } else { + ri->customRGBA[0] = atoi(value); - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - ri->customRGBA[1]=n; + ri->customRGBA[1] = n; - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - ri->customRGBA[2]=n; + ri->customRGBA[2] = n; - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - ri->customRGBA[3]=n; + ri->customRGBA[3] = n; } continue; } // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { + if (!Q_stricmp("none", value)) { ri->headModelName[0] = '\0'; - //Zero the head clamp range so the torso & legs don't lag behind - ri->headYawRangeLeft = - ri->headYawRangeRight = - ri->headPitchRangeUp = - ri->headPitchRangeDown = 0; - } - else - { - Q_strncpyz( ri->headModelName, value, sizeof(ri->headModelName)); + // Zero the head clamp range so the torso & legs don't lag behind + ri->headYawRangeLeft = ri->headYawRangeRight = ri->headPitchRangeUp = ri->headPitchRangeDown = 0; + } else { + Q_strncpyz(ri->headModelName, value, sizeof(ri->headModelName)); } continue; } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { + if (!Q_stricmp("none", value)) { ri->torsoModelName[0] = '\0'; - //Zero the torso clamp range so the legs don't lag behind - ri->torsoYawRangeLeft = - ri->torsoYawRangeRight = - ri->torsoPitchRangeUp = - ri->torsoPitchRangeDown = 0; - } - else - { - Q_strncpyz( ri->torsoModelName, value, sizeof(ri->torsoModelName)); + // Zero the torso clamp range so the legs don't lag behind + ri->torsoYawRangeLeft = ri->torsoYawRangeRight = ri->torsoPitchRangeUp = ri->torsoPitchRangeDown = 0; + } else { + Q_strncpyz(ri->torsoModelName, value, sizeof(ri->torsoModelName)); } continue; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( ri->legsModelName, value, sizeof(ri->legsModelName)); - //Need to do this here to get the right index + Q_strncpyz(ri->legsModelName, value, sizeof(ri->legsModelName)); + // Need to do this here to get the right index ci->animFileIndex = G_ParseAnimFileSet(ri->legsModelName); continue; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( playerModel, value, sizeof(playerModel)); + Q_strncpyz(playerModel, value, sizeof(playerModel)); md3Model = qfalse; continue; } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( customSkin, value, sizeof(customSkin)); + Q_strncpyz(customSkin, value, sizeof(customSkin)); continue; } // surfOff - if ( !Q_stricmp( token, "surfOff" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOff")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOff[0] ) - { - Q_strcat( surfOff, sizeof(surfOff), "," ); - Q_strcat( surfOff, sizeof(surfOff), value ); - } - else - { - Q_strncpyz( surfOff, value, sizeof(surfOff)); + if (surfOff[0]) { + Q_strcat(surfOff, sizeof(surfOff), ","); + Q_strcat(surfOff, sizeof(surfOff), value); + } else { + Q_strncpyz(surfOff, value, sizeof(surfOff)); } continue; } // surfOn - if ( !Q_stricmp( token, "surfOn" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOn")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOn[0] ) - { - Q_strcat( surfOn, sizeof(surfOn), "," ); - Q_strcat( surfOn, sizeof(surfOn), value ); - } - else - { - Q_strncpyz( surfOn, value, sizeof(surfOn)); + if (surfOn[0]) { + Q_strcat(surfOn, sizeof(surfOn), ","); + Q_strcat(surfOn, sizeof(surfOn), value); + } else { + Q_strncpyz(surfOn, value, sizeof(surfOn)); } continue; } - //headYawRangeLeft - if ( !Q_stricmp( token, "headYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeLeft + if (!Q_stricmp(token, "headYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeLeft = n; continue; } - //headYawRangeRight - if ( !Q_stricmp( token, "headYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeRight + if (!Q_stricmp(token, "headYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeRight = n; continue; } - //headPitchRangeUp - if ( !Q_stricmp( token, "headPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeUp + if (!Q_stricmp(token, "headPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeUp = n; continue; } - //headPitchRangeDown - if ( !Q_stricmp( token, "headPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeDown + if (!Q_stricmp(token, "headPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeDown = n; continue; } - //torsoYawRangeLeft - if ( !Q_stricmp( token, "torsoYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeLeft + if (!Q_stricmp(token, "torsoYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeLeft = n; continue; } - //torsoYawRangeRight - if ( !Q_stricmp( token, "torsoYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeRight + if (!Q_stricmp(token, "torsoYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeRight = n; continue; } - //torsoPitchRangeUp - if ( !Q_stricmp( token, "torsoPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeUp + if (!Q_stricmp(token, "torsoPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeUp = n; continue; } - //torsoPitchRangeDown - if ( !Q_stricmp( token, "torsoPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeDown + if (!Q_stricmp(token, "torsoPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeDown = n; @@ -2726,323 +2286,283 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // Uniform XYZ scale - if ( !Q_stricmp( token, "scale" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "scale")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = n / 100.0f; } continue; } - //X scale - if ( !Q_stricmp( token, "scaleX" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // X scale + if (!Q_stricmp(token, "scaleX")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[0] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[0] = n / 100.0f; } continue; } - //Y scale - if ( !Q_stricmp( token, "scaleY" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Y scale + if (!Q_stricmp(token, "scaleY")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[1] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[1] = n / 100.0f; } continue; } - //Z scale - if ( !Q_stricmp( token, "scaleZ" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Z scale + if (!Q_stricmp(token, "scaleZ")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[2] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[2] = n / 100.0f; } continue; } - //===AI STATS===================================================================== - if ( !parsingPlayer ) - { + //===AI STATS===================================================================== + if (!parsingPlayer) { // aggression - if ( !Q_stricmp( token, "aggression" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aggression")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aggression = n; } continue; } // aim - if ( !Q_stricmp( token, "aim" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aim")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aim = n; } continue; } // earshot - if ( !Q_stricmp( token, "earshot" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "earshot")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->earshot = f; } continue; } // evasion - if ( !Q_stricmp( token, "evasion" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "evasion")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->evasion = n; } continue; } // hfov - if ( !Q_stricmp( token, "hfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "hfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 180 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 180) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - stats->hfov = n;// / 2; //FIXME: Why was this being done?! + if (NPC->NPC) { + stats->hfov = n; // / 2; //FIXME: Why was this being done?! } continue; } // intelligence - if ( !Q_stricmp( token, "intelligence" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "intelligence")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->intelligence = n; } continue; } // move - if ( !Q_stricmp( token, "move" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "move")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->move = n; } continue; } // reactions - if ( !Q_stricmp( token, "reactions" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "reactions")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->reactions = n; } continue; } // shootDistance - if ( !Q_stricmp( token, "shootDistance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "shootDistance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->shootDistance = f; } continue; } // vfov - if ( !Q_stricmp( token, "vfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 2 || n > 360 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 2 || n > 360) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vfov = n / 2; } continue; } // vigilance - if ( !Q_stricmp( token, "vigilance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vigilance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vigilance = f; } continue; } // visrange - if ( !Q_stricmp( token, "visrange" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "visrange")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->visrange = f; - if (g_entities[ENTITYNUM_WORLD].max_health && stats->visrange>g_entities[ENTITYNUM_WORLD].max_health) - { - stats->visrange = g_entities[ENTITYNUM_WORLD].max_health; + if (g_entities[ENTITYNUM_WORLD].max_health && stats->visrange > g_entities[ENTITYNUM_WORLD].max_health) { + stats->visrange = g_entities[ENTITYNUM_WORLD].max_health; } } continue; } // race - // if ( !Q_stricmp( token, "race" ) ) - // { - // if ( COM_ParseString( &p, &value ) ) - // { - // continue; - // } - // NPC->client->race = TranslateRaceName(value); - // continue; - // } + // if ( !Q_stricmp( token, "race" ) ) + // { + // if ( COM_ParseString( &p, &value ) ) + // { + // continue; + // } + // NPC->client->race = TranslateRaceName(value); + // continue; + // } // rank - if ( !Q_stricmp( token, "rank" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "rank")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->rank = TranslateRankName(value); } continue; @@ -3050,79 +2570,65 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // health - if ( !Q_stricmp( token, "health" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "health")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->health = n; - } - else if ( parsingPlayer ) - { + } else if (parsingPlayer) { NPC->client->ps.stats[STAT_MAX_HEALTH] = NPC->client->pers.maxHealth = NPC->max_health = n; } continue; } // fullName - if ( !Q_stricmp( token, "fullName" ) ) - { + if (!Q_stricmp(token, "fullName")) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_YELLOW"WARNING: fullname ignored in NPC '%s'\n", NPCName ); + gi.Printf(S_COLOR_YELLOW "WARNING: fullname ignored in NPC '%s'\n", NPCName); #endif - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } continue; } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerTeam")) { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->playerTeam = (team_t)GetIDForString( TeamTable, value ); + NPC->client->playerTeam = (team_t)GetIDForString(TeamTable, value); continue; } // enemyTeam - if ( !Q_stricmp( token, "enemyTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "enemyTeam")) { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->enemyTeam = (team_t)GetIDForString( TeamTable, value ); + NPC->client->enemyTeam = (team_t)GetIDForString(TeamTable, value); continue; } // class - if ( !Q_stricmp( token, "class" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "class")) { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->NPC_class = (class_t)GetIDForString( ClassTable, value ); + NPC->client->NPC_class = (class_t)GetIDForString(ClassTable, value); // No md3's for vehicles. - if ( NPC->client->NPC_class == CLASS_VEHICLE ) - { - if ( !NPC->m_pVehicle ) - {//you didn't spawn this guy right! - Com_Printf ( S_COLOR_RED "ERROR: Tried to spawn a vehicle NPC (%s) without using NPC_Vehicle or 'NPC spawn vehicle '!!! Bad, bad, bad! Shame on you!\n", NPCName ); + if (NPC->client->NPC_class == CLASS_VEHICLE) { + if (!NPC->m_pVehicle) { // you didn't spawn this guy right! + Com_Printf(S_COLOR_RED "ERROR: Tried to spawn a vehicle NPC (%s) without using NPC_Vehicle or 'NPC spawn vehicle '!!! " + "Bad, bad, bad! Shame on you!\n", + NPCName); COM_EndParseSession(); return qfalse; } @@ -3133,101 +2639,89 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // dismemberment probability for head - if ( !Q_stricmp( token, "dismemberProbHead" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHead")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbHead = n; } continue; } // dismemberment probability for arms - if ( !Q_stricmp( token, "dismemberProbArms" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbArms")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbArms = n; } continue; } // dismemberment probability for hands - if ( !Q_stricmp( token, "dismemberProbHands" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHands")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbHands = n; } continue; } // dismemberment probability for waist - if ( !Q_stricmp( token, "dismemberProbWaist" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbWaist")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbWaist = n; } continue; } // dismemberment probability for legs - if ( !Q_stricmp( token, "dismemberProbLegs" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbLegs")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbLegs = n; } continue; } - //===MOVEMENT STATS============================================================ + //===MOVEMENT STATS============================================================ - if ( !Q_stricmp( token, "width" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "width")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -3236,39 +2730,30 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !Q_stricmp( token, "height" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "height")) { + if (COM_ParseInt(&p, &n)) { continue; } - if ( NPC->client->NPC_class == CLASS_VEHICLE - && NPC->m_pVehicle - && NPC->m_pVehicle->m_pVehicleInfo - && NPC->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//a flying vehicle's origin must be centered in bbox - NPC->maxs[2] = NPC->client->standheight = (n/2.0f); + if (NPC->client->NPC_class == CLASS_VEHICLE && NPC->m_pVehicle && NPC->m_pVehicle->m_pVehicleInfo && + NPC->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // a flying vehicle's origin must be centered in bbox + NPC->maxs[2] = NPC->client->standheight = (n / 2.0f); NPC->mins[2] = -NPC->maxs[2]; - NPC->s.origin[2] += (DEFAULT_MINS_2-NPC->mins[2])+0.125f; + NPC->s.origin[2] += (DEFAULT_MINS_2 - NPC->mins[2]) + 0.125f; VectorCopy(NPC->s.origin, NPC->client->ps.origin); VectorCopy(NPC->s.origin, NPC->currentOrigin); - G_SetOrigin( NPC, NPC->s.origin ); + G_SetOrigin(NPC, NPC->s.origin); gi.linkentity(NPC); - } - else - { - NPC->mins[2] = DEFAULT_MINS_2;//Cannot change + } else { + NPC->mins[2] = DEFAULT_MINS_2; // Cannot change NPC->maxs[2] = NPC->client->standheight = n + DEFAULT_MINS_2; } NPC->s.radius = n; continue; } - if ( !Q_stricmp( token, "crouchheight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "crouchheight")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -3276,12 +2761,9 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !parsingPlayer ) - { - if ( !Q_stricmp( token, "movetype" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!parsingPlayer) { + if (!Q_stricmp(token, "movetype")) { + if (COM_ParseString(&p, &value)) { continue; } @@ -3290,136 +2772,104 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // yawSpeed - if ( !Q_stricmp( token, "yawSpeed" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "yawSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n <= 0) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n <= 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->yawSpeed = ((float)(n)); } continue; } // walkSpeed - if ( !Q_stricmp( token, "walkSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "walkSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->walkSpeed = n; } continue; } - //runSpeed - if ( !Q_stricmp( token, "runSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // runSpeed + if (!Q_stricmp(token, "runSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->runSpeed = n; } continue; } - //acceleration - if ( !Q_stricmp( token, "acceleration" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // acceleration + if (!Q_stricmp(token, "acceleration")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->acceleration = n; } continue; } - //sex - if ( !Q_stricmp( token, "sex" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { - SkipRestOfLine( &p ); + // sex + if (!Q_stricmp(token, "sex")) { + if (COM_ParseString(&p, &value)) { + SkipRestOfLine(&p); continue; } - if ( value[0] == 'm' ) - {//male + if (value[0] == 'm') { // male stats->sex = SEX_MALE; - } - else if ( value[0] == 'n' ) - {//neutral + } else if (value[0] == 'n') { // neutral stats->sex = SEX_NEUTRAL; - } - else if ( value[0] == 'a' ) - {//asexual? + } else if (value[0] == 'a') { // asexual? stats->sex = SEX_NEUTRAL; - } - else if ( value[0] == 'f' ) - {//female + } else if (value[0] == 'f') { // female stats->sex = SEX_FEMALE; - } - else if ( value[0] == 's' ) - {//shemale? + } else if (value[0] == 's') { // shemale? stats->sex = SEX_SHEMALE; - } - else if ( value[0] == 'h' ) - {//hermaphrodite? + } else if (value[0] == 'h') { // hermaphrodite? stats->sex = SEX_SHEMALE; - } - else if ( value[0] == 't' ) - {//transsexual/transvestite? + } else if (value[0] == 't') { // transsexual/transvestite? stats->sex = SEX_SHEMALE; } continue; } -//===MISC=============================================================================== + //===MISC=============================================================================== // default behavior - if ( !Q_stricmp( token, "behavior" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "behavior")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < BS_DEFAULT || n >= NUM_BSTATES ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < BS_DEFAULT || n >= NUM_BSTATES) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->defaultBehavior = (bState_t)(n); } continue; @@ -3427,249 +2877,198 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // snd - if ( !Q_stricmp( token, "snd" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customBasicSoundDir = G_NewString( sound ); + ci->customBasicSoundDir = G_NewString(sound); } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customCombatSoundDir = G_NewString( sound ); + ci->customCombatSoundDir = G_NewString(sound); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customExtraSoundDir = G_NewString( sound ); + ci->customExtraSoundDir = G_NewString(sound); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customJediSoundDir = G_NewString( sound ); + ci->customJediSoundDir = G_NewString(sound); } continue; } - //New NPC/jedi stats: - //starting weapon - if ( !Q_stricmp( token, "weapon" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // New NPC/jedi stats: + // starting weapon + if (!Q_stricmp(token, "weapon")) { + if (COM_ParseString(&p, &value)) { continue; } - //FIXME: need to precache the weapon, too? (in above func) - int weap = GetIDForString( WPTable, value ); - if ( weap >= WP_NONE && weap < WP_NUM_WEAPONS ) - { + // FIXME: need to precache the weapon, too? (in above func) + int weap = GetIDForString(WPTable, value); + if (weap >= WP_NONE && weap < WP_NUM_WEAPONS) { NPC->client->ps.weapon = weap; - NPC->client->ps.stats[STAT_WEAPONS] |= ( 1 << weap ); - if ( weap > WP_NONE ) - { - RegisterItem( FindItemForWeapon( (weapon_t)(weap) ) ); //precache the weapon + NPC->client->ps.stats[STAT_WEAPONS] |= (1 << weap); + if (weap > WP_NONE) { + RegisterItem(FindItemForWeapon((weapon_t)(weap))); // precache the weapon NPC->client->ps.ammo[weaponData[weap].ammoIndex] = ammoData[weaponData[weap].ammoIndex].max; } } continue; } - if ( !parsingPlayer ) - { - //altFire - if ( !Q_stricmp( token, "altFire" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!parsingPlayer) { + // altFire + if (!Q_stricmp(token, "altFire")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( NPC->NPC ) - { - if ( n != 0 ) - { + if (NPC->NPC) { + if (n != 0) { NPC->NPC->scriptFlags |= SCF_ALT_FIRE; } } continue; } - //Other unique behaviors/numbers that are currently hardcoded? + // Other unique behaviors/numbers that are currently hardcoded? } - //force powers - int fp = GetIDForString( FPTable, token ); - if ( fp >= FP_FIRST && fp < NUM_FORCE_POWERS ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force powers + int fp = GetIDForString(FPTable, token); + if (fp >= FP_FIRST && fp < NUM_FORCE_POWERS) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //FIXME: need to precache the fx, too? (in above func) - //cap - if ( n > 5 ) - { + // FIXME: need to precache the fx, too? (in above func) + // cap + if (n > 5) { n = 5; - } - else if ( n < 0 ) - { + } else if (n < 0) { n = 0; } - if ( n ) - {//set - NPC->client->ps.forcePowersKnown |= ( 1 << fp ); - } - else - {//clear - NPC->client->ps.forcePowersKnown &= ~( 1 << fp ); + if (n) { // set + NPC->client->ps.forcePowersKnown |= (1 << fp); + } else { // clear + NPC->client->ps.forcePowersKnown &= ~(1 << fp); } NPC->client->ps.forcePowerLevel[fp] = n; continue; } - //max force power - if ( !Q_stricmp( token, "forcePowerMax" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // max force power + if (!Q_stricmp(token, "forcePowerMax")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } NPC->client->ps.forcePowerMax = n; continue; } - //force regen rate - default is 100ms - if ( !Q_stricmp( token, "forceRegenRate" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force regen rate - default is 100ms + if (!Q_stricmp(token, "forceRegenRate")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } NPC->client->ps.forcePowerRegenRate = n; continue; } - //force regen amount - default is 1 (points per second) - if ( !Q_stricmp( token, "forceRegenAmount" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force regen amount - default is 1 (points per second) + if (!Q_stricmp(token, "forceRegenAmount")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } NPC->client->ps.forcePowerRegenAmount = n; continue; } - //have a sabers.cfg and just name your saber in your NPCs.cfg/ICARUS script - //saber name - if ( !Q_stricmp( token, "saber" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // have a sabers.cfg and just name your saber in your NPCs.cfg/ICARUS script + // saber name + if (!Q_stricmp(token, "saber")) { + if (COM_ParseString(&p, &value)) { continue; } - char *saberName = G_NewString( value ); - WP_SaberParseParms( saberName, &NPC->client->ps.saber[0] ); - //if it requires a specific style, make sure we know how to use it - if ( NPC->client->ps.saber[0].stylesLearned ) - { + char *saberName = G_NewString(value); + WP_SaberParseParms(saberName, &NPC->client->ps.saber[0]); + // if it requires a specific style, make sure we know how to use it + if (NPC->client->ps.saber[0].stylesLearned) { NPC->client->ps.saberStylesKnown |= NPC->client->ps.saber[0].stylesLearned; } - if ( NPC->client->ps.saber[0].singleBladeStyle ) - { + if (NPC->client->ps.saber[0].singleBladeStyle) { NPC->client->ps.saberStylesKnown |= NPC->client->ps.saber[0].singleBladeStyle; } continue; } - //second saber name - if ( !Q_stricmp( token, "saber2" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // second saber name + if (!Q_stricmp(token, "saber2")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - {//can't use a second saber if first one is a two-handed saber...? - char *saberName = G_NewString( value ); - WP_SaberParseParms( saberName, &NPC->client->ps.saber[1] ); - if ( NPC->client->ps.saber[1].stylesLearned ) - { + if (!(NPC->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { // can't use a second saber if first one is a two-handed saber...? + char *saberName = G_NewString(value); + WP_SaberParseParms(saberName, &NPC->client->ps.saber[1]); + if (NPC->client->ps.saber[1].stylesLearned) { NPC->client->ps.saberStylesKnown |= NPC->client->ps.saber[1].stylesLearned; } - if ( NPC->client->ps.saber[1].singleBladeStyle ) - { + if (NPC->client->ps.saber[1].singleBladeStyle) { NPC->client->ps.saberStylesKnown |= NPC->client->ps.saber[1].singleBladeStyle; } - if ( (NPC->client->ps.saber[1].saberFlags&SFL_TWO_HANDED) ) - {//tsk tsk, can't use a twoHanded saber as second saber - WP_RemoveSaber( NPC, 1 ); - } - else - { + if ((NPC->client->ps.saber[1].saberFlags & SFL_TWO_HANDED)) { // tsk tsk, can't use a twoHanded saber as second saber + WP_RemoveSaber(NPC, 1); + } else { NPC->client->ps.dualSabers = qtrue; } } @@ -3677,361 +3076,269 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // saberColor - if ( !Q_stricmpn( token, "saberColor", 10) ) - { - if ( !NPC->client ) - { + if (!Q_stricmpn(token, "saberColor", 10)) { + if (!NPC->client) { continue; } - if (strlen(token)==10) - { - if ( COM_ParseString( &p, &value ) ) - { + if (strlen(token) == 10) { + if (COM_ParseString(&p, &value)) { continue; } - saber_colors_t color = TranslateSaberColor( value ); - for ( n = 0; n < MAX_BLADES; n++ ) - { + saber_colors_t color = TranslateSaberColor(value); + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[0].blade[n].color = color; } - } - else if (strlen(token)==11) - { - int index = atoi(&token[10])-1; - if (index > 7 || index < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberColor '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 11) { + int index = atoi(&token[10]) - 1; + if (index > 7 || index < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberColor '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->ps.saber[0].blade[index].color = TranslateSaberColor( value ); - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberColor '%s' in %s\n", token, NPCName ); + NPC->client->ps.saber[0].blade[index].color = TranslateSaberColor(value); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberColor '%s' in %s\n", token, NPCName); } continue; } - - if ( !Q_stricmpn( token, "saber2Color", 11 ) ) - { - if ( !NPC->client ) - { + if (!Q_stricmpn(token, "saber2Color", 11)) { + if (!NPC->client) { continue; } - if (strlen(token)==11) - { - if ( COM_ParseString( &p, &value ) ) - { + if (strlen(token) == 11) { + if (COM_ParseString(&p, &value)) { continue; } - saber_colors_t color = TranslateSaberColor( value ); - for ( n = 0; n < MAX_BLADES; n++ ) - { + saber_colors_t color = TranslateSaberColor(value); + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[1].blade[n].color = color; } - } - else if (strlen(token)==12) - { - n = atoi(&token[11])-1; - if (n > 7 || n < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Color '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 12) { + n = atoi(&token[11]) - 1; + if (n > 7 || n < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Color '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->ps.saber[1].blade[n].color = TranslateSaberColor( value ); - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Color '%s' in %s\n", token, NPCName ); + NPC->client->ps.saber[1].blade[n].color = TranslateSaberColor(value); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Color '%s' in %s\n", token, NPCName); } continue; } - - //saber length - if ( !Q_stricmpn( token, "saberLength", 11) ) - { - if (strlen(token)==11) - { + // saber length + if (!Q_stricmpn(token, "saberLength", 11)) { + if (strlen(token) == 11) { n = -1; - } - else if (strlen(token)==12) - { - n = atoi(&token[11])-1; - if (n > 7 || n < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberLength '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 12) { + n = atoi(&token[11]) - 1; + if (n > 7 || n < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberLength '%s' in %s\n", token, NPCName); continue; } - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberLength '%s' in %s\n", token, NPCName ); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberLength '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } - if (n == -1)//do them all + if (n == -1) // do them all { - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[0].blade[n].lengthMax = f; } - } - else //just one + } else // just one { NPC->client->ps.saber[0].blade[n].lengthMax = f; } continue; } - if ( !Q_stricmpn( token, "saber2Length", 12) ) - { - if (strlen(token)==12) - { + if (!Q_stricmpn(token, "saber2Length", 12)) { + if (strlen(token) == 12) { n = -1; - } - else if (strlen(token)==13) - { - n = atoi(&token[12])-1; - if (n > 7 || n < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Length '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 13) { + n = atoi(&token[12]) - 1; + if (n > 7 || n < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Length '%s' in %s\n", token, NPCName); continue; } - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Length '%s' in %s\n", token, NPCName ); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Length '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } - if (n == -1)//do them all + if (n == -1) // do them all { - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[1].blade[n].lengthMax = f; } - } - else //just one + } else // just one { NPC->client->ps.saber[1].blade[n].lengthMax = f; } continue; } - - //saber radius - if ( !Q_stricmpn( token, "saberRadius", 11 ) ) - { - if (strlen(token)==11) - { + // saber radius + if (!Q_stricmpn(token, "saberRadius", 11)) { + if (strlen(token) == 11) { n = -1; - } - else if (strlen(token)==12) - { - n = atoi(&token[11])-1; - if (n > 7 || n < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberRadius '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 12) { + n = atoi(&token[11]) - 1; + if (n > 7 || n < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberRadius '%s' in %s\n", token, NPCName); continue; } - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saberRadius '%s' in %s\n", token, NPCName ); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saberRadius '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } - if (n==-1) - {//NOTE: this fills in the rest of the blades with the same length by default - for ( n = 0; n < MAX_BLADES; n++ ) - { + if (n == -1) { // NOTE: this fills in the rest of the blades with the same length by default + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[0].blade[n].radius = f; } - } - else - { + } else { NPC->client->ps.saber[0].blade[n].radius = f; } continue; } - - if ( !Q_stricmpn( token, "saber2Radius", 12 ) ) - { - if (strlen(token)==12) - { + if (!Q_stricmpn(token, "saber2Radius", 12)) { + if (strlen(token) == 12) { n = -1; - } - else if (strlen(token)==13) - { - n = atoi(&token[12])-1; - if (n > 7 || n < 1 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Radius '%s' in %s\n", token, NPCName ); + } else if (strlen(token) == 13) { + n = atoi(&token[12]) - 1; + if (n > 7 || n < 1) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Radius '%s' in %s\n", token, NPCName); continue; } - } - else - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad saber2Radius '%s' in %s\n", token, NPCName ); + } else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad saber2Radius '%s' in %s\n", token, NPCName); continue; } - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } - if (n==-1) - {//NOTE: this fills in the rest of the blades with the same length by default - for ( n = 0; n < MAX_BLADES; n++ ) - { + if (n == -1) { // NOTE: this fills in the rest of the blades with the same length by default + for (n = 0; n < MAX_BLADES; n++) { NPC->client->ps.saber[1].blade[n].radius = f; } - } - else - { + } else { NPC->client->ps.saber[1].blade[n].radius = f; } continue; } - //ADD: - //saber sounds (on, off, loop) - //loop sound (like Vader's breathing or droid bleeps, etc.) + // ADD: + // saber sounds (on, off, loop) + // loop sound (like Vader's breathing or droid bleeps, etc.) - //starting saber style - if ( !Q_stricmp( token, "saberStyle" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // starting saber style + if (!Q_stricmp(token, "saberStyle")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //cap - if ( n > SS_STAFF ) - { + // cap + if (n > SS_STAFF) { n = SS_STAFF; - } - else if ( n < SS_FAST ) - { + } else if (n < SS_FAST) { n = SS_FAST; } - if ( n ) - {//set - NPC->client->ps.saberStylesKnown |= ( 1 << n ); - } - else - {//clear - NPC->client->ps.saberStylesKnown &= ~( 1 << n ); + if (n) { // set + NPC->client->ps.saberStylesKnown |= (1 << n); + } else { // clear + NPC->client->ps.saberStylesKnown &= ~(1 << n); } NPC->client->ps.saberAnimLevel = n; - if ( parsingPlayer ) - { + if (parsingPlayer) { cg.saberAnimLevelPending = n; } continue; } - if ( !parsingPlayer ) - { - gi.Printf( "WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName ); + if (!parsingPlayer) { + gi.Printf("WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName); } - SkipRestOfLine( &p ); + SkipRestOfLine(&p); } #ifdef _WIN32 #pragma endregion #endif - COM_EndParseSession( ); + COM_EndParseSession(); } ci->infoValid = qfalse; -/* -Ghoul2 Insert Start -*/ - if ( !md3Model ) - { + /* + Ghoul2 Insert Start + */ + if (!md3Model) { NPC->weaponModel[0] = -1; - if ( Q_stricmp( "player", playerModel ) == 0 ) - {//set the model from the console cvars - G_InitPlayerFromCvars( NPC ); - //now set the weapon, etc. - G_MatchPlayerWeapon( NPC ); - //NPC->NPC->aiFlags |= NPCAI_MATCHPLAYERWEAPON;//FIXME: may not always want this - } - else - {//do a normal model load + if (Q_stricmp("player", playerModel) == 0) { // set the model from the console cvars + G_InitPlayerFromCvars(NPC); + // now set the weapon, etc. + G_MatchPlayerWeapon(NPC); + // NPC->NPC->aiFlags |= NPCAI_MATCHPLAYERWEAPON;//FIXME: may not always want this + } else { // do a normal model load // If this is a vehicle, set the model name from the vehicle type array. - if ( NPC->client->NPC_class == CLASS_VEHICLE ) - { - int iVehIndex = BG_VehicleGetIndex( NPC->NPC_type ); - strcpy(customSkin, "default"); // Ignore any custom skin that may have come from the NPC File - Q_strncpyz( playerModel, g_vehicleInfo[iVehIndex].model, sizeof(playerModel)); - if ( g_vehicleInfo[iVehIndex].skin && g_vehicleInfo[iVehIndex].skin[0] ) - { - bool forceSkin = false; + if (NPC->client->NPC_class == CLASS_VEHICLE) { + int iVehIndex = BG_VehicleGetIndex(NPC->NPC_type); + strcpy(customSkin, "default"); // Ignore any custom skin that may have come from the NPC File + Q_strncpyz(playerModel, g_vehicleInfo[iVehIndex].model, sizeof(playerModel)); + if (g_vehicleInfo[iVehIndex].skin && g_vehicleInfo[iVehIndex].skin[0]) { + bool forceSkin = false; // Iterate Over All Possible Skins //--------------------------------- - ratl::vector_vs skinarray; - ratl::string_vs<256> skins(g_vehicleInfo[iVehIndex].skin); - for (ratl::string_vs<256>::tokenizer i = skins.begin("|"); i!=skins.end(); i++) - { - if (NPC->soundSet && NPC->soundSet[0] && Q_stricmp(*i, NPC->soundSet)==0) - { + ratl::vector_vs skinarray; + ratl::string_vs<256> skins(g_vehicleInfo[iVehIndex].skin); + for (ratl::string_vs<256>::tokenizer i = skins.begin("|"); i != skins.end(); i++) { + if (NPC->soundSet && NPC->soundSet[0] && Q_stricmp(*i, NPC->soundSet) == 0) { forceSkin = true; } skinarray.push_back(*i); @@ -4039,20 +3346,17 @@ Ghoul2 Insert Start // Soundset Is The Designer Set Way To Supply A Skin //--------------------------------------------------- - if (forceSkin) - { - Q_strncpyz( customSkin, NPC->soundSet, sizeof(customSkin)); + if (forceSkin) { + Q_strncpyz(customSkin, NPC->soundSet, sizeof(customSkin)); } // Otherwise Choose A Random Skin //-------------------------------- - else - { - if (NPC->soundSet && NPC->soundSet[0]) - { - gi.Printf(S_COLOR_RED"WARNING: Unable to use skin (%s)", NPC->soundSet); + else { + if (NPC->soundSet && NPC->soundSet[0]) { + gi.Printf(S_COLOR_RED "WARNING: Unable to use skin (%s)", NPC->soundSet); } - Q_strncpyz( customSkin, *skinarray[Q_irand(0, skinarray.size()-1)], sizeof(customSkin)); + Q_strncpyz(customSkin, *skinarray[Q_irand(0, skinarray.size() - 1)], sizeof(customSkin)); } if (NPC->soundSet && gi.bIsFromZone(NPC->soundSet, TAG_G_ALLOC)) { gi.Free(NPC->soundSet); @@ -4061,66 +3365,59 @@ Ghoul2 Insert Start } } - G_SetG2PlayerModel( NPC, playerModel, customSkin, surfOff, surfOn ); + G_SetG2PlayerModel(NPC, playerModel, customSkin, surfOff, surfOn); } } -/* -Ghoul2 Insert End -*/ - if( NPCsPrecached ) - {//Spawning in after initial precache, our models are precached, we just need to set our clientInfo - CG_RegisterClientModels( NPC->s.number ); - CG_RegisterNPCCustomSounds( ci ); - //CG_RegisterNPCEffects( NPC->client->playerTeam ); + /* + Ghoul2 Insert End + */ + if (NPCsPrecached) { // Spawning in after initial precache, our models are precached, we just need to set our clientInfo + CG_RegisterClientModels(NPC->s.number); + CG_RegisterNPCCustomSounds(ci); + // CG_RegisterNPCEffects( NPC->client->playerTeam ); } return qtrue; } -void NPC_LoadParms( void ) -{ - int len, totallen, npcExtFNLen, fileCnt, i; - char *buffer, *holdChar, *marker; - char npcExtensionListBuf[2048]; // The list of file names read in +void NPC_LoadParms(void) { + int len, totallen, npcExtFNLen, fileCnt, i; + char *buffer, *holdChar, *marker; + char npcExtensionListBuf[2048]; // The list of file names read in - //gi.Printf( "Parsing ext_data/npcs/*.npc definitions\n" ); + // gi.Printf( "Parsing ext_data/npcs/*.npc definitions\n" ); - //set where to store the first one + // set where to store the first one totallen = 0; marker = NPCParms; marker[0] = '\0'; - //now load in the .npc definitions - fileCnt = gi.FS_GetFileList("ext_data/npcs", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf) ); + // now load in the .npc definitions + fileCnt = gi.FS_GetFileList("ext_data/npcs", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf)); holdChar = npcExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1 ) - { - npcExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1) { + npcExtFNLen = strlen(holdChar); - //gi.Printf( "Parsing %s\n", holdChar ); + // gi.Printf( "Parsing %s\n", holdChar ); - len = gi.FS_ReadFile( va( "ext_data/npcs/%s", holdChar), (void **) &buffer ); + len = gi.FS_ReadFile(va("ext_data/npcs/%s", holdChar), (void **)&buffer); - if ( len == -1 ) - { - gi.Printf( "NPC_LoadParms: error reading file %s\n", holdChar ); - } - else - { - if ( totallen && *(marker-1) == '}' ) - {//don't let previous file end on a } because that must be a stand-alone token - strcat( marker, " " ); + if (len == -1) { + gi.Printf("NPC_LoadParms: error reading file %s\n", holdChar); + } else { + if (totallen && *(marker - 1) == '}') { // don't let previous file end on a } because that must be a stand-alone token + strcat(marker, " "); totallen++; marker++; } - len = COM_Compress( buffer ); + len = COM_Compress(buffer); - if ( totallen + len >= MAX_NPC_DATA_SIZE ) { - G_Error( "NPC_LoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar ); + if (totallen + len >= MAX_NPC_DATA_SIZE) { + G_Error("NPC_LoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar); } - strcat( marker, buffer ); - gi.FS_FreeFile( buffer ); + strcat(marker, buffer); + gi.FS_FreeFile(buffer); totallen += len; marker += len; diff --git a/code/game/NPC_utils.cpp b/code/game/NPC_utils.cpp index 816e2fa2d5..657e5806e8 100644 --- a/code/game/NPC_utils.cpp +++ b/code/game/NPC_utils.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_utils.cpp +// NPC_utils.cpp #include "b_local.h" #include "Q3_Interface.h" @@ -28,14 +28,14 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_nav.h" -extern Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *pEnt); -int teamNumbers[TEAM_NUM_TEAMS]; -int teamStrength[TEAM_NUM_TEAMS]; -int teamCounter[TEAM_NUM_TEAMS]; +int teamNumbers[TEAM_NUM_TEAMS]; +int teamStrength[TEAM_NUM_TEAMS]; +int teamCounter[TEAM_NUM_TEAMS]; -#define VALID_ATTACK_CONE 2.0f //Degrees -void GetAnglesForDirection( const vec3_t p1, const vec3_t p2, vec3_t out ); +#define VALID_ATTACK_CONE 2.0f // Degrees +void GetAnglesForDirection(const vec3_t p1, const vec3_t p2, vec3_t out); /* void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) @@ -46,154 +46,126 @@ Added: Uses shootAngles if a NPC has them extern void ViewHeightFix(const gentity_t *const ent); extern void AddLeanOfs(const gentity_t *const ent, vec3_t point); extern void SubtractLeanOfs(const gentity_t *const ent, vec3_t point); -void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) -{ - vec3_t forward, up, right; - vec3_t start, end; - trace_t tr; +void CalcEntitySpot(const gentity_t *ent, const spot_t spot, vec3_t point) { + vec3_t forward, up, right; + vec3_t start, end; + trace_t tr; - if ( !ent ) - { + if (!ent) { return; } ViewHeightFix(ent); - switch ( spot ) - { + switch (spot) { case SPOT_ORIGIN: - if(VectorCompare(ent->currentOrigin, vec3_origin)) - {//brush - VectorSubtract(ent->absmax, ent->absmin, point);//size + if (VectorCompare(ent->currentOrigin, vec3_origin)) { // brush + VectorSubtract(ent->absmax, ent->absmin, point); // size VectorMA(ent->absmin, 0.5, point, point); - } - else - { - VectorCopy ( ent->currentOrigin, point ); + } else { + VectorCopy(ent->currentOrigin, point); } break; case SPOT_CHEST: case SPOT_HEAD: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && VectorLengthSquared(ent->client->renderInfo.eyePoint) && + (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; + } else if (!ent->s.number) { + SubtractLeanOfs(ent, point); } - else if ( !ent->s.number ) - { - SubtractLeanOfs( ent, point ); - } - } - else - { - VectorCopy ( ent->currentOrigin, point ); - if ( ent->client ) - { + } else { + VectorCopy(ent->currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } } - if ( spot == SPOT_CHEST && ent->client ) - { - if ( ent->client->NPC_class != CLASS_ATST ) - {//adjust up some - point[2] -= ent->maxs[2]*0.2f; + if (spot == SPOT_CHEST && ent->client) { + if (ent->client->NPC_class != CLASS_ATST) { // adjust up some + point[2] -= ent->maxs[2] * 0.2f; } } break; case SPOT_HEAD_LEAN: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && VectorLengthSquared(ent->client->renderInfo.eyePoint) && + (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; + } else if (!ent->s.number) { + SubtractLeanOfs(ent, point); } - else if ( !ent->s.number ) - { - SubtractLeanOfs( ent, point ); - } - //NOTE: automatically takes leaning into account! - } - else - { - VectorCopy ( ent->currentOrigin, point ); - if ( ent->client ) - { + // NOTE: automatically takes leaning into account! + } else { + VectorCopy(ent->currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } - //AddLeanOfs ( ent, point ); + // AddLeanOfs ( ent, point ); } break; - //FIXME: implement... - //case SPOT_CHEST: - //Returns point 3/4 from tag_torso to tag_head? - //break; + // FIXME: implement... + // case SPOT_CHEST: + // Returns point 3/4 from tag_torso to tag_head? + // break; case SPOT_LEGS: - VectorCopy ( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); point[2] += (ent->mins[2] * 0.5); break; case SPOT_WEAPON: - if( ent->NPC && !VectorCompare( ent->NPC->shootAngles, vec3_origin ) && !VectorCompare( ent->NPC->shootAngles, ent->client->ps.viewangles )) - { - AngleVectors( ent->NPC->shootAngles, forward, right, up ); + if (ent->NPC && !VectorCompare(ent->NPC->shootAngles, vec3_origin) && !VectorCompare(ent->NPC->shootAngles, ent->client->ps.viewangles)) { + AngleVectors(ent->NPC->shootAngles, forward, right, up); + } else { + AngleVectors(ent->client->ps.viewangles, forward, right, up); } - else - { - AngleVectors( ent->client->ps.viewangles, forward, right, up ); - } - CalcMuzzlePoint( (gentity_t*)ent, forward, right, up, point, 0 ); - //NOTE: automatically takes leaning into account! + CalcMuzzlePoint((gentity_t *)ent, forward, right, up, point, 0); + // NOTE: automatically takes leaning into account! break; case SPOT_GROUND: // if entity is on the ground, just use it's absmin - if ( ent->s.groundEntityNum != -1 ) - { - VectorCopy( ent->currentOrigin, point ); + if (ent->s.groundEntityNum != -1) { + VectorCopy(ent->currentOrigin, point); point[2] = ent->absmin[2]; break; } // if it is reasonably close to the ground, give the point underneath of it - VectorCopy( ent->currentOrigin, start ); + VectorCopy(ent->currentOrigin, start); start[2] = ent->absmin[2]; - VectorCopy( start, end ); + VectorCopy(start, end); end[2] -= 64; - gi.trace( &tr, start, ent->mins, ent->maxs, end, ent->s.number, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); - if ( tr.fraction < 1.0 ) - { - VectorCopy( tr.endpos, point); + gi.trace(&tr, start, ent->mins, ent->maxs, end, ent->s.number, MASK_PLAYERSOLID, (EG2_Collision)0, 0); + if (tr.fraction < 1.0) { + VectorCopy(tr.endpos, point); break; } // otherwise just use the origin - VectorCopy( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); break; default: - VectorCopy ( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); break; } } - //=================================================================================== /* @@ -205,207 +177,162 @@ Does not include "aim" in it's calculations FIXME: stop compressing angles into shorts!!!! */ -extern cvar_t *g_timescale; -extern bool NPC_IsTrooper( gentity_t *ent ); -qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) -{ +extern cvar_t *g_timescale; +extern bool NPC_IsTrooper(gentity_t *ent); +qboolean NPC_UpdateAngles(qboolean doPitch, qboolean doYaw) { #if 1 - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - qboolean exact = qtrue; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the existing render flag... - dmv - if ( !NPC->enemy && ( (level.time < NPCInfo->aimTime) || NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE) ) - { - if(doPitch) + // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the + // existing render flag... - dmv + if (!NPC->enemy && ((level.time < NPCInfo->aimTime) || NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE)) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { + } else { // we're changing the lockedDesired Pitch/Yaw below so it's lost it's original meaning, get rid of the lock flag NPC->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; - if(doPitch) - { + if (doPitch) { targetPitch = NPCInfo->desiredPitch; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; } - if(doYaw) - { + if (doYaw) { targetYaw = NPCInfo->desiredYaw; NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } } - if ( NPC->s.weapon == WP_EMPLACED_GUN ) - { + if (NPC->s.weapon == WP_EMPLACED_GUN) { // FIXME: this seems to do nothing, actually... yawSpeed = 20; - } - else - { - if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER - && !NPC->enemy ) - {//just slowly lookin' around + } else { + if (NPC->client->NPC_class == CLASS_ROCKETTROOPER && !NPC->enemy) { // just slowly lookin' around yawSpeed = 1; - } - else - { + } else { yawSpeed = NPCInfo->stats.yawSpeed; } } - if ( NPC->s.weapon == WP_SABER && NPC->client->ps.forcePowersActive&(1<value; + if (NPC->s.weapon == WP_SABER && NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) { + yawSpeed *= 1.0f / g_timescale->value; } - if (!NPC_IsTrooper(NPC) - && NPC->enemy - && !G_IsRidingVehicle( NPC ) - && NPC->client->NPC_class != CLASS_VEHICLE ) - { - if (NPC->s.weapon==WP_BLASTER_PISTOL || - NPC->s.weapon==WP_BLASTER || - NPC->s.weapon==WP_BOWCASTER || - NPC->s.weapon==WP_REPEATER || - NPC->s.weapon==WP_FLECHETTE || - NPC->s.weapon==WP_BRYAR_PISTOL || - NPC->s.weapon==WP_NOGHRI_STICK) - { + if (!NPC_IsTrooper(NPC) && NPC->enemy && !G_IsRidingVehicle(NPC) && NPC->client->NPC_class != CLASS_VEHICLE) { + if (NPC->s.weapon == WP_BLASTER_PISTOL || NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BOWCASTER || NPC->s.weapon == WP_REPEATER || + NPC->s.weapon == WP_FLECHETTE || NPC->s.weapon == WP_BRYAR_PISTOL || NPC->s.weapon == WP_NOGHRI_STICK) { yawSpeed *= 10.0f; } } - if( doYaw ) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if( doPitch ) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; - if ( exact && Q3_TaskIDPending( NPC, TID_ANGLE_FACE ) ) - { - Q3_TaskIDComplete( NPC, TID_ANGLE_FACE ); + if (exact && Q3_TaskIDPending(NPC, TID_ANGLE_FACE)) { + Q3_TaskIDComplete(NPC, TID_ANGLE_FACE); } return exact; #else - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - //float runningMod = NPCInfo->currentSpeed/100.0f; - qboolean exact = qtrue; - qboolean doSound = qfalse; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + // float runningMod = NPCInfo->currentSpeed/100.0f; + qboolean exact = qtrue; + qboolean doSound = qfalse; // if angle changes are locked; just keep the current angles - if ( level.time < NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } yawSpeed = NPCInfo->stats.yawSpeed; - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) @@ -445,41 +372,33 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } else*/ - if ( error ) - { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if(doPitch) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) @@ -519,35 +438,29 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } else*/ - if ( error ) - { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; /* if(doSound) @@ -559,23 +472,19 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) return exact; #endif - } -void NPC_AimWiggle( vec3_t enemy_org ) -{ - //shoot for somewhere between the head and torso - //NOTE: yes, I know this looks weird, but it works - if ( NPCInfo->aimErrorDebounceTime < level.time ) - { - NPCInfo->aimOfs[0] = 0.3*Q_flrand(NPC->enemy->mins[0], NPC->enemy->maxs[0]); - NPCInfo->aimOfs[1] = 0.3*Q_flrand(NPC->enemy->mins[1], NPC->enemy->maxs[1]); - if ( NPC->enemy->maxs[2] > 0 ) - { - NPCInfo->aimOfs[2] = NPC->enemy->maxs[2]*Q_flrand(0.0f, -1.0f); +void NPC_AimWiggle(vec3_t enemy_org) { + // shoot for somewhere between the head and torso + // NOTE: yes, I know this looks weird, but it works + if (NPCInfo->aimErrorDebounceTime < level.time) { + NPCInfo->aimOfs[0] = 0.3 * Q_flrand(NPC->enemy->mins[0], NPC->enemy->maxs[0]); + NPCInfo->aimOfs[1] = 0.3 * Q_flrand(NPC->enemy->mins[1], NPC->enemy->maxs[1]); + if (NPC->enemy->maxs[2] > 0) { + NPCInfo->aimOfs[2] = NPC->enemy->maxs[2] * Q_flrand(0.0f, -1.0f); } } - VectorAdd( enemy_org, NPCInfo->aimOfs, enemy_org ); + VectorAdd(enemy_org, NPCInfo->aimOfs, enemy_org); } /* @@ -583,8 +492,7 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) Includes aim when determining angles - so they don't always hit... */ -qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) -{ +qboolean NPC_UpdateFiringAngles(qboolean doPitch, qboolean doYaw) { #if 0 @@ -652,71 +560,58 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) #else - float error, diff; - float decay; - float targetPitch = 0; - float targetYaw = 0; - qboolean exact = qtrue; + float error, diff; + float decay; + float targetPitch = 0; + float targetYaw = 0; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - if ( level.time < NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } - if ( NPCInfo->aimErrorDebounceTime < level.time ) - { - if ( Q_irand(0, 1 ) ) - { + if (NPCInfo->aimErrorDebounceTime < level.time) { + if (Q_irand(0, 1)) { NPCInfo->lastAimErrorYaw = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } - if ( Q_irand(0, 1 ) ) - { + if (Q_irand(0, 1)) { NPCInfo->lastAimErrorPitch = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } NPCInfo->aimErrorDebounceTime = level.time + Q_irand(250, 2000); } - if(doYaw) - { + if (doYaw) { // decay yaw diff - diff = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); + diff = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); - if ( diff) - { + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } @@ -732,32 +627,25 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) } */ - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + diff + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + diff + error) - client->ps.delta_angles[YAW]; } - if(doPitch) - { + if (doPitch) { // decay pitch diff - diff = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( diff) - { + diff = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } @@ -765,15 +653,14 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) error = NPCInfo->lastAimErrorPitch; - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + diff + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + diff + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; return exact; #endif - } //=================================================================================== @@ -783,40 +670,31 @@ static void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doY Does update angles on shootAngles */ -void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) -{//FIXME: shoot angles either not set right or not used! - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; +void NPC_UpdateShootAngles(vec3_t angles, qboolean doPitch, qboolean doYaw) { // FIXME: shoot angles either not set right or not used! + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; - if(doPitch) + if (doPitch) targetPitch = angles[PITCH]; - if(doYaw) + if (doYaw) targetYaw = angles[YAW]; - - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPCInfo->shootAngles[YAW], targetYaw ); - if ( error ) - { + error = AngleDelta(NPCInfo->shootAngles[YAW], targetYaw); + if (error) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -824,27 +702,20 @@ void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) NPCInfo->shootAngles[YAW] = targetYaw + error; } - if(doPitch) - { + if (doPitch) { // decay pitch error - error = AngleDelta ( NPCInfo->shootAngles[PITCH], targetPitch ); - if ( error ) - { + error = AngleDelta(NPCInfo->shootAngles[PITCH], targetPitch); + if (error) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -861,24 +732,20 @@ Sets the number of living clients on each team FIXME: Does not account for non-respawned players! FIXME: Don't include medics? */ -void SetTeamNumbers (void) -{ - gentity_t *found; - int i; +void SetTeamNumbers(void) { + gentity_t *found; + int i; - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - { + for (i = 0; i < TEAM_NUM_TEAMS; i++) { teamNumbers[i] = 0; teamStrength[i] = 0; } - for( i = 0; i < 1 ; i++ ) - { + for (i = 0; i < 1; i++) { found = &g_entities[i]; - if( found->client ) - { - if( found->health > 0 )//FIXME: or if a player! + if (found->client) { + if (found->health > 0) // FIXME: or if a player! { teamNumbers[found->client->playerTeam]++; teamStrength[found->client->playerTeam] += found->health; @@ -886,66 +753,52 @@ void SetTeamNumbers (void) } } - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - {//Get the average health - teamStrength[i] = floor( ((float)(teamStrength[i])) / ((float)(teamNumbers[i])) ); + for (i = 0; i < TEAM_NUM_TEAMS; i++) { // Get the average health + teamStrength[i] = floor(((float)(teamStrength[i])) / ((float)(teamNumbers[i]))); } } extern stringID_table_t BSTable[]; extern stringID_table_t BSETTable[]; -qboolean G_ActivateBehavior (gentity_t *self, int bset ) -{ - bState_t bSID = (bState_t)-1; +qboolean G_ActivateBehavior(gentity_t *self, int bset) { + bState_t bSID = (bState_t)-1; char *bs_name = NULL; - if ( !self ) - { + if (!self) { return qfalse; } bs_name = self->behaviorSet[bset]; - if( !(VALIDSTRING( bs_name )) ) - { + if (!(VALIDSTRING(bs_name))) { return qfalse; } - if ( self->NPC ) - { - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); + if (self->NPC) { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); } - if(bSID != (bState_t)-1) - { + if (bSID != (bState_t)-1) { self->NPC->tempBehavior = BS_DEFAULT; self->NPC->behaviorState = bSID; - if ( bSID == BS_SEARCH || bSID == BS_WANDER ) - { - //FIXME: Reimplement? - if( self->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( self->waypoint, bSID ); - } - else - { + if (bSID == BS_SEARCH || bSID == BS_WANDER) { + // FIXME: Reimplement? + if (self->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(self->waypoint, bSID); + } else { self->waypoint = NAV::GetNearestNode(self); - if( self->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( self->waypoint, bSID ); + if (self->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(self->waypoint, bSID); } } } - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID( BSETTable, bset ), bs_name ); - Quake3Game()->RunScript( self, bs_name ); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID(BSETTable, bset), bs_name); + Quake3Game()->RunScript(self, bs_name); } return qtrue; } - /* ============================================================================= @@ -960,94 +813,79 @@ NPC_ValidEnemy ------------------------- */ -qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ) -{ - //Must be a valid pointer - if ( enemy == NULL ) +qboolean G_ValidEnemy(gentity_t *self, gentity_t *enemy) { + // Must be a valid pointer + if (enemy == NULL) return qfalse; - //Must not be me - if ( enemy == self ) + // Must not be me + if (enemy == self) return qfalse; - //Must not be deleted - if ( enemy->inuse == qfalse ) + // Must not be deleted + if (enemy->inuse == qfalse) return qfalse; - //Must be alive - if ( enemy->health <= 0 ) + // Must be alive + if (enemy->health <= 0) return qfalse; - //In case they're in notarget mode - if ( enemy->flags & FL_NOTARGET ) + // In case they're in notarget mode + if (enemy->flags & FL_NOTARGET) return qfalse; - //Must be an NPC - if ( enemy->client == NULL ) - { - if ( enemy->svFlags&SVF_NONNPC_ENEMY ) - {//still potentially valid - if (self->client) - { - if ( enemy->noDamageTeam == self->client->playerTeam ) - { + // Must be an NPC + if (enemy->client == NULL) { + if (enemy->svFlags & SVF_NONNPC_ENEMY) { // still potentially valid + if (self->client) { + if (enemy->noDamageTeam == self->client->playerTeam) { return qfalse; - } - else - { + } else { return qtrue; } - } - else - { - if ( enemy->noDamageTeam == self->noDamageTeam ) - { + } else { + if (enemy->noDamageTeam == self->noDamageTeam) { return qfalse; - } - else - { + } else { return qtrue; } } - } - else - { + } else { return qfalse; } } - if ( enemy->client->playerTeam == TEAM_FREE && enemy->s.number < MAX_CLIENTS ) - {//An evil player, everyone attacks him + if (enemy->client->playerTeam == TEAM_FREE && enemy->s.number < MAX_CLIENTS) { // An evil player, everyone attacks him return qtrue; } - //Can't be on the same team - if ( enemy->client->playerTeam == self->client->playerTeam ) - { + // Can't be on the same team + if (enemy->client->playerTeam == self->client->playerTeam) { return qfalse; } - //if haven't seen him in a while, give up - //if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? + // if haven't seen him in a while, give up + // if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? // return qfalse; - if ( enemy->client->playerTeam == self->client->enemyTeam //simplest case: they're on my enemy team - || (self->client->enemyTeam == TEAM_FREE && enemy->client->NPC_class != self->client->NPC_class )//I get mad at anyone and this guy isn't the same class as me - || (enemy->client->NPC_class == CLASS_WAMPA && enemy->enemy )//a rampaging wampa - || (enemy->client->NPC_class == CLASS_RANCOR && enemy->enemy )//a rampaging rancor - || (enemy->client->playerTeam == TEAM_FREE && enemy->client->enemyTeam == TEAM_FREE && enemy->enemy && enemy->enemy->client && (enemy->enemy->client->playerTeam == self->client->playerTeam||(enemy->enemy->client->playerTeam != TEAM_ENEMY&&self->client->playerTeam==TEAM_PLAYER))) //enemy is a rampaging non-aligned creature who is attacking someone on our team or a non-enemy (this last condition is used only if we're a good guy - in effect, we protect the innocent) - ) - { + if (enemy->client->playerTeam == self->client->enemyTeam // simplest case: they're on my enemy team + || (self->client->enemyTeam == TEAM_FREE && + enemy->client->NPC_class != self->client->NPC_class) // I get mad at anyone and this guy isn't the same class as me + || (enemy->client->NPC_class == CLASS_WAMPA && enemy->enemy) // a rampaging wampa + || (enemy->client->NPC_class == CLASS_RANCOR && enemy->enemy) // a rampaging rancor + || (enemy->client->playerTeam == TEAM_FREE && enemy->client->enemyTeam == TEAM_FREE && enemy->enemy && enemy->enemy->client && + (enemy->enemy->client->playerTeam == self->client->playerTeam || + (enemy->enemy->client->playerTeam != TEAM_ENEMY && + self->client->playerTeam == TEAM_PLAYER))) // enemy is a rampaging non-aligned creature who is attacking someone on our team or a non-enemy (this + // last condition is used only if we're a good guy - in effect, we protect the innocent) + ) { return qtrue; } - //all other cases = false? + // all other cases = false? return qfalse; } -qboolean NPC_ValidEnemy( gentity_t *ent ) -{ - return G_ValidEnemy( NPC, ent ); -} +qboolean NPC_ValidEnemy(gentity_t *ent) { return G_ValidEnemy(NPC, ent); } /* ------------------------- @@ -1055,18 +893,17 @@ NPC_TargetVisible ------------------------- */ -qboolean NPC_TargetVisible( gentity_t *ent ) -{ - //Make sure we're in a valid range - if ( DistanceSquared( ent->currentOrigin, NPC->currentOrigin ) > ( NPCInfo->stats.visrange * NPCInfo->stats.visrange ) ) +qboolean NPC_TargetVisible(gentity_t *ent) { + // Make sure we're in a valid range + if (DistanceSquared(ent->currentOrigin, NPC->currentOrigin) > (NPCInfo->stats.visrange * NPCInfo->stats.visrange)) return qfalse; - //Check our FOV - if ( InFOV( ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Check our FOV + if (InFOV(ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - //Check for sight - if ( NPC_ClearLOS( ent ) == qfalse ) + // Check for sight + if (NPC_ClearLOS(ent) == qfalse) return qfalse; return qtrue; @@ -1103,53 +940,49 @@ NPC_FindNearestEnemy ------------------------- */ -#define MAX_RADIUS_ENTS 256 //NOTE: This can cause entities to be lost -#define NEAR_DEFAULT_RADIUS 256 -extern gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate ); - -int NPC_FindNearestEnemy( gentity_t *ent ) -{ - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; - gentity_t *nearest; - vec3_t mins, maxs; - int nearestEntID = -1; - float nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - float distance; - int numEnts, numChecks = 0; - int i; - - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { +#define MAX_RADIUS_ENTS 256 // NOTE: This can cause entities to be lost +#define NEAR_DEFAULT_RADIUS 256 +extern gentity_t *G_CheckControlledTurretEnemy(gentity_t *self, gentity_t *enemy, qboolean validate); + +int NPC_FindNearestEnemy(gentity_t *ent) { + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; + gentity_t *nearest; + vec3_t mins, maxs; + int nearestEntID = -1; + float nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + float distance; + int numEnts, numChecks = 0; + int i; + + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = ent->currentOrigin[i] - NPCInfo->stats.visrange; maxs[i] = ent->currentOrigin[i] + NPCInfo->stats.visrange; } - //Get a number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get a number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { nearest = G_CheckControlledTurretEnemy(ent, radiusEnts[i], qtrue); - //Don't consider self - if ( nearest == ent ) + // Don't consider self + if (nearest == ent) continue; - //Must be valid - if ( NPC_ValidEnemy( nearest ) == qfalse ) + // Must be valid + if (NPC_ValidEnemy(nearest) == qfalse) continue; numChecks++; - //Must be visible - if ( NPC_TargetVisible( nearest ) == qfalse ) + // Must be visible + if (NPC_TargetVisible(nearest) == qfalse) continue; - distance = DistanceSquared( ent->currentOrigin, nearest->currentOrigin ); + distance = DistanceSquared(ent->currentOrigin, nearest->currentOrigin); - //Found one closer to us - if ( distance < nearestDist ) - { + // Found one closer to us + if (distance < nearestDist) { nearestEntID = nearest->s.number; nearestDist = distance; } @@ -1164,36 +997,32 @@ NPC_PickEnemyExt ------------------------- */ -gentity_t *NPC_PickEnemyExt( qboolean checkAlerts = qfalse ) -{ - //If we've asked for the closest enemy - int entID = NPC_FindNearestEnemy( NPC ); +gentity_t *NPC_PickEnemyExt(qboolean checkAlerts = qfalse) { + // If we've asked for the closest enemy + int entID = NPC_FindNearestEnemy(NPC); - //If we have a valid enemy, use it - if ( entID >= 0 ) + // If we have a valid enemy, use it + if (entID >= 0) return &g_entities[entID]; - if ( checkAlerts ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); + if (checkAlerts) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { alertEvent_t *event = &level.alertEvents[alertEvent]; - //Don't pay attention to our own alerts - if ( event->owner == NPC ) + // Don't pay attention to our own alerts + if (event->owner == NPC) return NULL; - if ( event->level >= AEL_DISCOVERED ) - { - //If it's the player, attack him - if ( event->owner == &g_entities[0] ) + if (event->level >= AEL_DISCOVERED) { + // If it's the player, attack him + if (event->owner == &g_entities[0]) return event->owner; - //If it's on our team, then take its enemy as well - if ( ( event->owner->client ) && ( event->owner->client->playerTeam == NPC->client->playerTeam ) ) + // If it's on our team, then take its enemy as well + if ((event->owner->client) && (event->owner->client->playerTeam == NPC->client->playerTeam)) return event->owner->enemy; } } @@ -1208,10 +1037,7 @@ NPC_FindPlayer ------------------------- */ -qboolean NPC_FindPlayer( void ) -{ - return NPC_TargetVisible( &g_entities[0] ); -} +qboolean NPC_FindPlayer(void) { return NPC_TargetVisible(&g_entities[0]); } /* ------------------------- @@ -1219,29 +1045,27 @@ NPC_CheckPlayerDistance ------------------------- */ -static qboolean NPC_CheckPlayerDistance( void ) -{ - //Make sure we have an enemy - if ( NPC->enemy == NULL ) +static qboolean NPC_CheckPlayerDistance(void) { + // Make sure we have an enemy + if (NPC->enemy == NULL) return qfalse; - //Only do this for non-players - if ( NPC->enemy->s.number == 0 ) + // Only do this for non-players + if (NPC->enemy->s.number == 0) return qfalse; - //must be set up to get mad at player - if ( !NPC->client || NPC->client->enemyTeam != TEAM_PLAYER ) + // must be set up to get mad at player + if (!NPC->client || NPC->client->enemyTeam != TEAM_PLAYER) return qfalse; - //Must be within our FOV - if ( InFOV( &g_entities[0], NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Must be within our FOV + if (InFOV(&g_entities[0], NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - float distance = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - if ( distance > DistanceSquared( NPC->currentOrigin, g_entities[0].currentOrigin ) ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (distance > DistanceSquared(NPC->currentOrigin, g_entities[0].currentOrigin)) { + G_SetEnemy(NPC, &g_entities[0]); return qtrue; } @@ -1254,52 +1078,45 @@ NPC_FindEnemy ------------------------- */ -qboolean NPC_FindEnemy( qboolean checkAlerts = qfalse ) -{ - //We're ignoring all enemies for now - if( NPC->svFlags & SVF_IGNORE_ENEMIES ) - { - G_ClearEnemy( NPC ); +qboolean NPC_FindEnemy(qboolean checkAlerts = qfalse) { + // We're ignoring all enemies for now + if (NPC->svFlags & SVF_IGNORE_ENEMIES) { + G_ClearEnemy(NPC); return qfalse; } - //we can't pick up any enemies for now - if( NPCInfo->confusionTime > level.time ) - { - G_ClearEnemy( NPC ); + // we can't pick up any enemies for now + if (NPCInfo->confusionTime > level.time) { + G_ClearEnemy(NPC); return qfalse; } - //Don't want a new enemy - if ( ( NPC_ValidEnemy( NPC->enemy ) ) && ( NPC->svFlags & SVF_LOCKEDENEMY ) ) + // Don't want a new enemy + if ((NPC_ValidEnemy(NPC->enemy)) && (NPC->svFlags & SVF_LOCKEDENEMY)) return qtrue; - //See if the player is closer than our current enemy - if ( NPC->client->NPC_class != CLASS_RANCOR - && NPC->client->NPC_class != CLASS_WAMPA - && NPC->client->NPC_class != CLASS_SAND_CREATURE - && NPC_CheckPlayerDistance() ) - {//rancors, wampas & sand creatures don't care if player is closer, they always go with closest + // See if the player is closer than our current enemy + if (NPC->client->NPC_class != CLASS_RANCOR && NPC->client->NPC_class != CLASS_WAMPA && NPC->client->NPC_class != CLASS_SAND_CREATURE && + NPC_CheckPlayerDistance()) { // rancors, wampas & sand creatures don't care if player is closer, they always go with closest return qtrue; } - //Otherwise, turn off the flag + // Otherwise, turn off the flag NPC->svFlags &= ~SVF_LOCKEDENEMY; - //If we've gotten here alright, then our target it still valid - if ( NPC_ValidEnemy( NPC->enemy ) ) + // If we've gotten here alright, then our target it still valid + if (NPC_ValidEnemy(NPC->enemy)) return qtrue; - gentity_t *newenemy = NPC_PickEnemyExt( checkAlerts ); + gentity_t *newenemy = NPC_PickEnemyExt(checkAlerts); - //if we found one, take it as the enemy - if( NPC_ValidEnemy( newenemy ) ) - { - G_SetEnemy( NPC, newenemy ); + // if we found one, take it as the enemy + if (NPC_ValidEnemy(newenemy)) { + G_SetEnemy(NPC, newenemy); return qtrue; } - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); return qfalse; } @@ -1309,20 +1126,19 @@ NPC_CheckEnemyExt ------------------------- */ -qboolean NPC_CheckEnemyExt( qboolean checkAlerts ) -{ - //Make sure we're ready to think again -/* - if ( NPCInfo->enemyCheckDebounceTime > level.time ) - return qfalse; +qboolean NPC_CheckEnemyExt(qboolean checkAlerts) { + // Make sure we're ready to think again + /* + if ( NPCInfo->enemyCheckDebounceTime > level.time ) + return qfalse; - //Get our next think time - NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); + //Get our next think time + NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); - //Attempt to find an enemy - return NPC_FindEnemy(); -*/ - return NPC_FindEnemy( checkAlerts ); + //Attempt to find an enemy + return NPC_FindEnemy(); + */ + return NPC_FindEnemy(checkAlerts); } /* @@ -1331,62 +1147,53 @@ NPC_FacePosition ------------------------- */ -qboolean NPC_FacePosition( vec3_t position, qboolean doPitch ) -{ - vec3_t muzzle; - qboolean facing = qtrue; +qboolean NPC_FacePosition(vec3_t position, qboolean doPitch) { + vec3_t muzzle; + qboolean facing = qtrue; - //Get the positions - if ( NPC->client && (NPC->client->NPC_class == CLASS_RANCOR || NPC->client->NPC_class == CLASS_WAMPA || NPC->client->NPC_class == CLASS_SAND_CREATURE) ) - { - CalcEntitySpot( NPC, SPOT_ORIGIN, muzzle ); + // Get the positions + if (NPC->client && (NPC->client->NPC_class == CLASS_RANCOR || NPC->client->NPC_class == CLASS_WAMPA || NPC->client->NPC_class == CLASS_SAND_CREATURE)) { + CalcEntitySpot(NPC, SPOT_ORIGIN, muzzle); muzzle[2] += NPC->maxs[2] * 0.75f; - } - else if ( NPC->client && NPC->client->NPC_class == CLASS_GALAKMECH ) - { - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - } - else - { - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, muzzle );//SPOT_HEAD - if ( NPC->client->NPC_class == CLASS_ROCKETTROOPER ) - {//*sigh*, look down more + } else if (NPC->client && NPC->client->NPC_class == CLASS_GALAKMECH) { + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); + } else { + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, muzzle); // SPOT_HEAD + if (NPC->client->NPC_class == CLASS_ROCKETTROOPER) { //*sigh*, look down more position[2] -= 32; } } - //Find the desired angles - vec3_t angles; + // Find the desired angles + vec3_t angles; - GetAnglesForDirection( muzzle, position, angles ); + GetAnglesForDirection(muzzle, position, angles); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); - if ( NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_ATST ) - { + if (NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_ATST) { // FIXME: this is kind of dumb, but it was the easiest way to get it to look sort of ok - NPCInfo->desiredYaw += Q_flrand( -5, 5 ) + sin( level.time * 0.004f ) * 7; - NPCInfo->desiredPitch += Q_flrand( -2, 2 ); + NPCInfo->desiredYaw += Q_flrand(-5, 5) + sin(level.time * 0.004f) * 7; + NPCInfo->desiredPitch += Q_flrand(-2, 2); } - //Face that yaw - NPC_UpdateAngles( qtrue, qtrue ); + // Face that yaw + NPC_UpdateAngles(qtrue, qtrue); - //Find the delta between our goal and our current facing - float yawDelta = AngleNormalize360( NPCInfo->desiredYaw - ( SHORT2ANGLE( ucmd.angles[YAW] + client->ps.delta_angles[YAW] ) ) ); + // Find the delta between our goal and our current facing + float yawDelta = AngleNormalize360(NPCInfo->desiredYaw - (SHORT2ANGLE(ucmd.angles[YAW] + client->ps.delta_angles[YAW]))); - //See if we are facing properly - if ( fabs( yawDelta ) > VALID_ATTACK_CONE ) + // See if we are facing properly + if (fabs(yawDelta) > VALID_ATTACK_CONE) facing = qfalse; - if ( doPitch ) - { - //Find the delta between our goal and our current facing - float currentAngles = ( SHORT2ANGLE( ucmd.angles[PITCH] + client->ps.delta_angles[PITCH] ) ); + if (doPitch) { + // Find the delta between our goal and our current facing + float currentAngles = (SHORT2ANGLE(ucmd.angles[PITCH] + client->ps.delta_angles[PITCH])); float pitchDelta = NPCInfo->desiredPitch - currentAngles; - //See if we are facing properly - if ( fabs( pitchDelta ) > VALID_ATTACK_CONE ) + // See if we are facing properly + if (fabs(pitchDelta) > VALID_ATTACK_CONE) facing = qfalse; } @@ -1399,14 +1206,13 @@ NPC_FaceEntity ------------------------- */ -qboolean NPC_FaceEntity( gentity_t *ent, qboolean doPitch ) -{ - vec3_t entPos; +qboolean NPC_FaceEntity(gentity_t *ent, qboolean doPitch) { + vec3_t entPos; - //Get the positions - CalcEntitySpot( ent, SPOT_HEAD_LEAN, entPos ); + // Get the positions + CalcEntitySpot(ent, SPOT_HEAD_LEAN, entPos); - return NPC_FacePosition( entPos, doPitch ); + return NPC_FacePosition(entPos, doPitch); } /* @@ -1415,15 +1221,14 @@ NPC_FaceEnemy ------------------------- */ -qboolean NPC_FaceEnemy( qboolean doPitch ) -{ - if ( NPC == NULL ) +qboolean NPC_FaceEnemy(qboolean doPitch) { + if (NPC == NULL) return qfalse; - if ( NPC->enemy == NULL ) + if (NPC->enemy == NULL) return qfalse; - return NPC_FaceEntity( NPC->enemy, doPitch ); + return NPC_FaceEntity(NPC->enemy, doPitch); } /* @@ -1432,18 +1237,17 @@ NPC_CheckCanAttackExt ------------------------- */ -qboolean NPC_CheckCanAttackExt( void ) -{ - //We don't want them to shoot - if( NPCInfo->scriptFlags & SCF_DONT_FIRE ) +qboolean NPC_CheckCanAttackExt(void) { + // We don't want them to shoot + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) return qfalse; - //Turn to face - if ( NPC_FaceEnemy( qtrue ) == qfalse ) + // Turn to face + if (NPC_FaceEnemy(qtrue) == qfalse) return qfalse; - //Must have a clear line of sight to the target - if ( NPC_ClearShot( NPC->enemy ) == qfalse ) + // Must have a clear line of sight to the target + if (NPC_ClearShot(NPC->enemy) == qfalse) return qfalse; return qtrue; @@ -1455,14 +1259,12 @@ NPC_ClearLookTarget ------------------------- */ -void NPC_ClearLookTarget( gentity_t *self ) -{ - if ( !self->client ) - { +void NPC_ClearLookTarget(gentity_t *self) { + if (!self->client) { return; } - self->client->renderInfo.lookTarget = ENTITYNUM_NONE;//ENTITYNUM_WORLD; + self->client->renderInfo.lookTarget = ENTITYNUM_NONE; // ENTITYNUM_WORLD; self->client->renderInfo.lookTargetClearTime = 0; } @@ -1471,10 +1273,8 @@ void NPC_ClearLookTarget( gentity_t *self ) NPC_SetLookTarget ------------------------- */ -void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) -{ - if ( !self->client ) - { +void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime) { + if (!self->client) { return; } @@ -1487,26 +1287,19 @@ void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) NPC_CheckLookTarget ------------------------- */ -qboolean NPC_CheckLookTarget( gentity_t *self ) -{ - if ( self->client ) - { - if ( self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - {//within valid range - if ( (&g_entities[self->client->renderInfo.lookTarget] == NULL) || !g_entities[self->client->renderInfo.lookTarget].inuse ) - {//lookTarget not inuse or not valid anymore - NPC_ClearLookTarget( self ); - } - else if ( self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time ) - {//Time to clear lookTarget - NPC_ClearLookTarget( self ); - } - else if ( g_entities[self->client->renderInfo.lookTarget].client && self->enemy && (&g_entities[self->client->renderInfo.lookTarget] != self->enemy) ) - {//should always look at current enemy if engaged in battle... FIXME: this could override certain scripted lookTargets...??? - NPC_ClearLookTarget( self ); - } - else - { +qboolean NPC_CheckLookTarget(gentity_t *self) { + if (self->client) { + if (self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { // within valid range + if ((&g_entities[self->client->renderInfo.lookTarget] == NULL) || + !g_entities[self->client->renderInfo.lookTarget].inuse) { // lookTarget not inuse or not valid anymore + NPC_ClearLookTarget(self); + } else if (self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time) { // Time to clear lookTarget + NPC_ClearLookTarget(self); + } else if (g_entities[self->client->renderInfo.lookTarget].client && self->enemy && + (&g_entities[self->client->renderInfo.lookTarget] != self->enemy)) { // should always look at current enemy if engaged in battle... + // FIXME: this could override certain scripted lookTargets...??? + NPC_ClearLookTarget(self); + } else { return qtrue; } } @@ -1520,159 +1313,120 @@ qboolean NPC_CheckLookTarget( gentity_t *self ) NPC_CheckCharmed ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -void G_CheckCharmed( gentity_t *self ) -{ - if ( self - && self->client - && self->client->playerTeam == TEAM_PLAYER - && self->NPC - && self->NPC->charmedTime - && (self->NPC->charmedTime < level.time ||self->health <= 0) ) - {//we were charmed, set us back! - //NOTE: presumptions here... - team_t savTeam = self->client->enemyTeam; +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +void G_CheckCharmed(gentity_t *self) { + if (self && self->client && self->client->playerTeam == TEAM_PLAYER && self->NPC && self->NPC->charmedTime && + (self->NPC->charmedTime < level.time || self->health <= 0)) { // we were charmed, set us back! + // NOTE: presumptions here... + team_t savTeam = self->client->enemyTeam; self->client->enemyTeam = self->client->playerTeam; self->client->playerTeam = savTeam; self->client->leader = NULL; self->NPC->charmedTime = 0; - if ( self->health > 0 ) - { - if ( self->NPC->tempBehavior == BS_FOLLOW_LEADER ) - { + if (self->health > 0) { + if (self->NPC->tempBehavior == BS_FOLLOW_LEADER) { self->NPC->tempBehavior = BS_DEFAULT; } - G_ClearEnemy( self ); - //say something to let player know you've snapped out of it - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + G_ClearEnemy(self); + // say something to let player know you've snapped out of it + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } } - } -void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ) -{ - if ( !self || !self->ghoul2.size() ) - { +void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0) { + if (!self || !self->ghoul2.size()) { return; } - mdxaBone_t boltMatrix; - vec3_t result, angles={0,self->currentAngles[YAW],0}; - - gi.G2API_GetBoltMatrix( self->ghoul2, modelIndex, - boltIndex, - &boltMatrix, angles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); - if ( pos ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, result ); - VectorCopy( result, pos ); + mdxaBone_t boltMatrix; + vec3_t result, angles = {0, self->currentAngles[YAW], 0}; + + gi.G2API_GetBoltMatrix(self->ghoul2, modelIndex, boltIndex, &boltMatrix, angles, self->currentOrigin, (cg.time ? cg.time : level.time), NULL, + self->s.modelScale); + if (pos) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, result); + VectorCopy(result, pos); } } -float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ) -{ - vec3_t org = { 0.0f }; +float NPC_EntRangeFromBolt(gentity_t *targEnt, int boltIndex) { + vec3_t org = {0.0f}; - if ( !targEnt ) - { + if (!targEnt) { return Q3_INFINITE; } - G_GetBoltPosition( NPC, boltIndex, org ); + G_GetBoltPosition(NPC, boltIndex, org); - return (Distance( targEnt->currentOrigin, org )); + return (Distance(targEnt->currentOrigin, org)); } -float NPC_EnemyRangeFromBolt( int boltIndex ) -{ - return (NPC_EntRangeFromBolt( NPC->enemy, boltIndex )); -} +float NPC_EnemyRangeFromBolt(int boltIndex) { return (NPC_EntRangeFromBolt(NPC->enemy, boltIndex)); } -int G_GetEntsNearBolt( gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ) -{ - vec3_t mins, maxs; - int i; +int G_GetEntsNearBolt(gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg) { + vec3_t mins, maxs; + int i; - //get my handRBolt's position - vec3_t org = { 0.0f }; + // get my handRBolt's position + vec3_t org = {0.0f}; - G_GetBoltPosition( self, boltIndex, org ); + G_GetBoltPosition(self, boltIndex, org); - VectorCopy( org, boltOrg ); + VectorCopy(org, boltOrg); - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = boltOrg[i] - radius; maxs[i] = boltOrg[i] + radius; } - //Get the number of entities in a given space - return (gi.EntitiesInBox( mins, maxs, radiusEnts, 128 )); + // Get the number of entities in a given space + return (gi.EntitiesInBox(mins, maxs, radiusEnts, 128)); } -int NPC_GetEntsNearBolt( gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ) -{ - return (G_GetEntsNearBolt( NPC, radiusEnts, radius, boltIndex, boltOrg )); +int NPC_GetEntsNearBolt(gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg) { + return (G_GetEntsNearBolt(NPC, radiusEnts, radius, boltIndex, boltOrg)); } -extern qboolean RT_Flying( gentity_t *self ); -extern void RT_FlyStart( gentity_t *self ); -extern void RT_FlyStop( gentity_t *self ); -extern qboolean Boba_Flying( gentity_t *self ); -extern void Boba_FlyStart( gentity_t *self ); -extern void Boba_FlyStop( gentity_t *self ); +extern qboolean RT_Flying(gentity_t *self); +extern void RT_FlyStart(gentity_t *self); +extern void RT_FlyStop(gentity_t *self); +extern qboolean Boba_Flying(gentity_t *self); +extern void Boba_FlyStart(gentity_t *self); +extern void Boba_FlyStop(gentity_t *self); -qboolean JET_Flying( gentity_t *self ) -{ - if ( !self || !self->client ) - { +qboolean JET_Flying(gentity_t *self) { + if (!self || !self->client) { return qfalse; } - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { + if (self->client->NPC_class == CLASS_BOBAFETT) { return (Boba_Flying(self)); - } - else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { + } else if (self->client->NPC_class == CLASS_ROCKETTROOPER) { return (RT_Flying(self)); - } - else - { + } else { return qfalse; } } -void JET_FlyStart( gentity_t *self ) -{ - if ( !self || !self->client ) - { +void JET_FlyStart(gentity_t *self) { + if (!self || !self->client) { return; } self->lastInAirTime = level.time; - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - Boba_FlyStart( self ); - } - else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { - RT_FlyStart( self ); + if (self->client->NPC_class == CLASS_BOBAFETT) { + Boba_FlyStart(self); + } else if (self->client->NPC_class == CLASS_ROCKETTROOPER) { + RT_FlyStart(self); } } -void JET_FlyStop( gentity_t *self ) -{ - if ( !self || !self->client ) - { +void JET_FlyStop(gentity_t *self) { + if (!self || !self->client) { return; } - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - Boba_FlyStop( self ); - } - else if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { - RT_FlyStop( self ); + if (self->client->NPC_class == CLASS_BOBAFETT) { + Boba_FlyStop(self); + } else if (self->client->NPC_class == CLASS_ROCKETTROOPER) { + RT_FlyStop(self); } } diff --git a/code/game/Q3_Interface.cpp b/code/game/Q3_Interface.cpp index eb344d2b0a..3036ab3f22 100644 --- a/code/game/Q3_Interface.cpp +++ b/code/game/Q3_Interface.cpp @@ -42,458 +42,429 @@ along with this program; if not, see . #include "g_navigator.h" #include "qcommon/ojk_saved_game_helper.h" -extern cvar_t *com_buildScript; - -extern void InitMover( gentity_t *ent ); -extern void MatchTeam( gentity_t *teamLeader, int moverState, int time ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern char *G_GetLocationForEnt( gentity_t *ent ); -extern void NPC_BSSearchStart( int homeWp, bState_t bState ); -extern void InitMoverTrData( gentity_t *ent ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); +extern cvar_t *com_buildScript; + +extern void InitMover(gentity_t *ent); +extern void MatchTeam(gentity_t *teamLeader, int moverState, int time); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern char *G_GetLocationForEnt(gentity_t *ent); +extern void NPC_BSSearchStart(int homeWp, bState_t bState); +extern void InitMoverTrData(gentity_t *ent); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); extern cvar_t *g_sex; extern cvar_t *g_timescale; -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -static void Q3_SetWeapon (int entID, const char *wp_name); -static void Q3_SetItem (int entID, const char *item_name); -extern void CG_ChangeWeapon( int num ); -extern int TAG_GetOrigin2( const char *owner, const char *name, vec3_t origin ); -extern void G_TeamRetaliation ( gentity_t *targ, gentity_t *attacker, qboolean stopIcarus ); -extern void G_PlayDoorLoopSound( gentity_t *ent ); -extern void G_PlayDoorSound( gentity_t *ent, int type ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void WP_SaberSetColor( gentity_t *ent, int saberNum, int bladeNum, char *colorName ); -extern void WP_SetSaber( gentity_t *ent, int saberNum, const char *saberName ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern void G_ChangePlayerModel( gentity_t *ent, const char *newModel ); -extern vehicleType_t TranslateVehicleName( char *name ); -extern void WP_SetSaberOrigin( gentity_t *self, vec3_t newOrg ); -extern void JET_FlyStart( gentity_t *self ); -extern void JET_FlyStop( gentity_t *self ); -extern void Rail_LockCenterOfTrack(const char* trackName); -extern void Rail_UnLockCenterOfTrack(const char* trackName); -extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ); -extern qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ); - -extern int BMS_START; -extern int BMS_MID; -extern int BMS_END; -extern cvar_t *g_skippingcin; - -extern qboolean stop_icarus; - -#define stringIDExpand(str, strEnum) { str, strEnum }, ENUM2STRING(strEnum) - -stringID_table_t BSTable[] = -{ - ENUM2STRING(BS_DEFAULT),//# default behavior for that NPC - ENUM2STRING(BS_ADVANCE_FIGHT),//# Advance to captureGoal and shoot enemies if you can - ENUM2STRING(BS_SLEEP),//# Play awake script when startled by sound - ENUM2STRING(BS_FOLLOW_LEADER),//# Follow your leader and shoot any enemies you come across - ENUM2STRING(BS_JUMP),//# Face navgoal and jump to it. - ENUM2STRING(BS_SEARCH),//# Using current waypoint as a base), search the immediate branches of waypoints for enemies - ENUM2STRING(BS_WANDER),//# Wander down random waypoint paths - ENUM2STRING(BS_NOCLIP),//# Moves through walls), etc. - ENUM2STRING(BS_REMOVE),//# Waits for player to leave PVS then removes itself - ENUM2STRING(BS_CINEMATIC),//# Does nothing but face it's angles and move to a goal if it has one - ENUM2STRING(BS_FLEE),//# Run toward the nav goal, avoiding danger - //the rest are internal only - { "", -1 } -}; - - - -stringID_table_t BSETTable[] = -{ - ENUM2STRING(BSET_SPAWN),//# script to use when first spawned - ENUM2STRING(BSET_USE),//# script to use when used - ENUM2STRING(BSET_AWAKE),//# script to use when awoken/startled - ENUM2STRING(BSET_ANGER),//# script to use when aquire an enemy - ENUM2STRING(BSET_ATTACK),//# script to run when you attack - ENUM2STRING(BSET_VICTORY),//# script to run when you kill someone - ENUM2STRING(BSET_LOSTENEMY),//# script to run when you can't find your enemy - ENUM2STRING(BSET_PAIN),//# script to use when take pain - ENUM2STRING(BSET_FLEE),//# script to use when take pain below 50% of health - ENUM2STRING(BSET_DEATH),//# script to use when killed - ENUM2STRING(BSET_DELAYED),//# script to run when self->delayScriptTime is reached - ENUM2STRING(BSET_BLOCKED),//# script to run when blocked by a friendly NPC or player - ENUM2STRING(BSET_BUMPED),//# script to run when bumped into a friendly NPC or player (can set bumpRadius) - ENUM2STRING(BSET_STUCK),//# script to run when blocked by a wall - ENUM2STRING(BSET_FFIRE),//# script to run when player shoots their own teammates - ENUM2STRING(BSET_FFDEATH),//# script to run when player kills a teammate - stringIDExpand("", BSET_INVALID), - { "", -1 } -}; - -stringID_table_t WPTable[] = -{ - { "NULL", WP_NONE }, - ENUM2STRING(WP_NONE), - // Player weapons - ENUM2STRING(WP_SABER), // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. - ENUM2STRING(WP_BLASTER_PISTOL), // apparently some enemy only version of the blaster - ENUM2STRING(WP_BLASTER), - ENUM2STRING(WP_DISRUPTOR), - ENUM2STRING(WP_BOWCASTER), - ENUM2STRING(WP_REPEATER), - ENUM2STRING(WP_DEMP2), - ENUM2STRING(WP_FLECHETTE), - ENUM2STRING(WP_ROCKET_LAUNCHER), - ENUM2STRING(WP_THERMAL), - ENUM2STRING(WP_TRIP_MINE), - ENUM2STRING(WP_DET_PACK), - ENUM2STRING(WP_CONCUSSION), - ENUM2STRING(WP_MELEE), // Any ol' melee attack - //NOTE: player can only have up to 16 weapons), anything after that is enemy only - ENUM2STRING(WP_STUN_BATON), - // NPC enemy weapons - ENUM2STRING(WP_BRYAR_PISTOL), - ENUM2STRING(WP_EMPLACED_GUN), - ENUM2STRING(WP_BOT_LASER), // Probe droid - Laser blast - ENUM2STRING(WP_TURRET), // turret guns - ENUM2STRING(WP_ATST_MAIN), - ENUM2STRING(WP_ATST_SIDE), - ENUM2STRING(WP_TIE_FIGHTER), - ENUM2STRING(WP_RAPID_FIRE_CONC), - ENUM2STRING(WP_JAWA), - ENUM2STRING(WP_TUSKEN_RIFLE), - ENUM2STRING(WP_TUSKEN_STAFF), - ENUM2STRING(WP_SCEPTER), - ENUM2STRING(WP_NOGHRI_STICK), - { "", 0 } -}; - -stringID_table_t INVTable[] = -{ - ENUM2STRING(INV_ELECTROBINOCULARS), - ENUM2STRING(INV_BACTA_CANISTER), - ENUM2STRING(INV_SEEKER), - ENUM2STRING(INV_LIGHTAMP_GOGGLES), - ENUM2STRING(INV_SENTRY), - { "", 0 } -}; - -stringID_table_t eventTable[] = -{ - //BOTH_h - //END - { "", EV_BAD } -}; - -stringID_table_t DMSTable[] = -{ - { "NULL",-1 }, - ENUM2STRING(DM_AUTO), //# let the game determine the dynamic music as normal - ENUM2STRING(DM_SILENCE), //# stop the music - ENUM2STRING(DM_EXPLORE), //# force the exploration music to play - ENUM2STRING(DM_ACTION), //# force the action music to play - ENUM2STRING(DM_BOSS), //# force the boss battle music to play (if there is any) - ENUM2STRING(DM_DEATH), //# force the "player dead" music to play - { "", -1 } -}; - -stringID_table_t HLTable[] = -{ - { "NULL",-1 }, - ENUM2STRING(HL_FOOT_RT), - ENUM2STRING(HL_FOOT_LT), - ENUM2STRING(HL_LEG_RT), - ENUM2STRING(HL_LEG_LT), - ENUM2STRING(HL_WAIST), - ENUM2STRING(HL_BACK_RT), - ENUM2STRING(HL_BACK_LT), - ENUM2STRING(HL_BACK), - ENUM2STRING(HL_CHEST_RT), - ENUM2STRING(HL_CHEST_LT), - ENUM2STRING(HL_CHEST), - ENUM2STRING(HL_ARM_RT), - ENUM2STRING(HL_ARM_LT), - ENUM2STRING(HL_HAND_RT), - ENUM2STRING(HL_HAND_LT), - ENUM2STRING(HL_HEAD), - ENUM2STRING(HL_GENERIC1), - ENUM2STRING(HL_GENERIC2), - ENUM2STRING(HL_GENERIC3), - ENUM2STRING(HL_GENERIC4), - ENUM2STRING(HL_GENERIC5), - ENUM2STRING(HL_GENERIC6), - { "", -1 } -}; - -stringID_table_t setTable[] = -{ - ENUM2STRING(SET_SPAWNSCRIPT),//0 - ENUM2STRING(SET_USESCRIPT), - ENUM2STRING(SET_AWAKESCRIPT), - ENUM2STRING(SET_ANGERSCRIPT), - ENUM2STRING(SET_ATTACKSCRIPT), - ENUM2STRING(SET_VICTORYSCRIPT), - ENUM2STRING(SET_PAINSCRIPT), - ENUM2STRING(SET_FLEESCRIPT), - ENUM2STRING(SET_DEATHSCRIPT), - ENUM2STRING(SET_DELAYEDSCRIPT), - ENUM2STRING(SET_BLOCKEDSCRIPT), - ENUM2STRING(SET_FFIRESCRIPT), - ENUM2STRING(SET_FFDEATHSCRIPT), - ENUM2STRING(SET_MINDTRICKSCRIPT), - ENUM2STRING(SET_NO_MINDTRICK), - ENUM2STRING(SET_ORIGIN), - ENUM2STRING(SET_TELEPORT_DEST), - ENUM2STRING(SET_ANGLES), - ENUM2STRING(SET_XVELOCITY), - ENUM2STRING(SET_YVELOCITY), - ENUM2STRING(SET_ZVELOCITY), - ENUM2STRING(SET_Z_OFFSET), - ENUM2STRING(SET_ENEMY), - ENUM2STRING(SET_LEADER), - ENUM2STRING(SET_NAVGOAL), - ENUM2STRING(SET_ANIM_UPPER), - ENUM2STRING(SET_ANIM_LOWER), - ENUM2STRING(SET_ANIM_BOTH), - ENUM2STRING(SET_ANIM_HOLDTIME_LOWER), - ENUM2STRING(SET_ANIM_HOLDTIME_UPPER), - ENUM2STRING(SET_ANIM_HOLDTIME_BOTH), - ENUM2STRING(SET_PLAYER_TEAM), - ENUM2STRING(SET_ENEMY_TEAM), - ENUM2STRING(SET_BEHAVIOR_STATE), - ENUM2STRING(SET_BEHAVIOR_STATE), - ENUM2STRING(SET_HEALTH), - ENUM2STRING(SET_ARMOR), - ENUM2STRING(SET_DEFAULT_BSTATE), - ENUM2STRING(SET_CAPTURE), - ENUM2STRING(SET_DPITCH), - ENUM2STRING(SET_DYAW), - ENUM2STRING(SET_EVENT), - ENUM2STRING(SET_TEMP_BSTATE), - ENUM2STRING(SET_COPY_ORIGIN), - ENUM2STRING(SET_VIEWTARGET), - ENUM2STRING(SET_WEAPON), - ENUM2STRING(SET_ITEM), - ENUM2STRING(SET_WALKSPEED), - ENUM2STRING(SET_RUNSPEED), - ENUM2STRING(SET_YAWSPEED), - ENUM2STRING(SET_AGGRESSION), - ENUM2STRING(SET_AIM), - ENUM2STRING(SET_FRICTION), - ENUM2STRING(SET_GRAVITY), - ENUM2STRING(SET_IGNOREPAIN), - ENUM2STRING(SET_IGNOREENEMIES), - ENUM2STRING(SET_IGNOREALERTS), - ENUM2STRING(SET_DONTSHOOT), - ENUM2STRING(SET_DONTFIRE), - ENUM2STRING(SET_LOCKED_ENEMY), - ENUM2STRING(SET_NOTARGET), - ENUM2STRING(SET_LEAN), - ENUM2STRING(SET_CROUCHED), - ENUM2STRING(SET_WALKING), - ENUM2STRING(SET_RUNNING), - ENUM2STRING(SET_CHASE_ENEMIES), - ENUM2STRING(SET_LOOK_FOR_ENEMIES), - ENUM2STRING(SET_FACE_MOVE_DIR), - ENUM2STRING(SET_ALT_FIRE), - ENUM2STRING(SET_DONT_FLEE), - ENUM2STRING(SET_FORCED_MARCH), - ENUM2STRING(SET_NO_RESPONSE), - ENUM2STRING(SET_NO_COMBAT_TALK), - ENUM2STRING(SET_NO_ALERT_TALK), - ENUM2STRING(SET_UNDYING), - ENUM2STRING(SET_TREASONED), - ENUM2STRING(SET_DISABLE_SHADER_ANIM), - ENUM2STRING(SET_SHADER_ANIM), - ENUM2STRING(SET_INVINCIBLE), - ENUM2STRING(SET_NOAVOID), - ENUM2STRING(SET_SHOOTDIST), - ENUM2STRING(SET_TARGETNAME), - ENUM2STRING(SET_TARGET), - ENUM2STRING(SET_TARGET2), - ENUM2STRING(SET_LOCATION), - ENUM2STRING(SET_PAINTARGET), - ENUM2STRING(SET_TIMESCALE), - ENUM2STRING(SET_VISRANGE), - ENUM2STRING(SET_EARSHOT), - ENUM2STRING(SET_VIGILANCE), - ENUM2STRING(SET_HFOV), - ENUM2STRING(SET_VFOV), - ENUM2STRING(SET_DELAYSCRIPTTIME), - ENUM2STRING(SET_FORWARDMOVE), - ENUM2STRING(SET_RIGHTMOVE), - ENUM2STRING(SET_LOCKYAW), - ENUM2STRING(SET_SOLID), - ENUM2STRING(SET_CAMERA_GROUP), - ENUM2STRING(SET_CAMERA_GROUP_Z_OFS), - ENUM2STRING(SET_CAMERA_GROUP_TAG), - ENUM2STRING(SET_LOOK_TARGET), - ENUM2STRING(SET_ADDRHANDBOLT_MODEL), - ENUM2STRING(SET_REMOVERHANDBOLT_MODEL), - ENUM2STRING(SET_ADDLHANDBOLT_MODEL), - ENUM2STRING(SET_REMOVELHANDBOLT_MODEL), - ENUM2STRING(SET_FACEAUX), - ENUM2STRING(SET_FACEBLINK), - ENUM2STRING(SET_FACEBLINKFROWN), - ENUM2STRING(SET_FACEFROWN), - ENUM2STRING(SET_FACESMILE), - ENUM2STRING(SET_FACEGLAD), - ENUM2STRING(SET_FACEHAPPY), - ENUM2STRING(SET_FACESHOCKED), - ENUM2STRING(SET_FACENORMAL), - ENUM2STRING(SET_FACEEYESCLOSED), - ENUM2STRING(SET_FACEEYESOPENED), - ENUM2STRING(SET_SCROLLTEXT), - ENUM2STRING(SET_LCARSTEXT), - ENUM2STRING(SET_CENTERTEXT), - ENUM2STRING(SET_SCROLLTEXTCOLOR), - ENUM2STRING(SET_CAPTIONTEXTCOLOR), - ENUM2STRING(SET_CENTERTEXTCOLOR), - ENUM2STRING(SET_PLAYER_USABLE), - ENUM2STRING(SET_STARTFRAME), - ENUM2STRING(SET_ENDFRAME), - ENUM2STRING(SET_ANIMFRAME), - ENUM2STRING(SET_LOOP_ANIM), - ENUM2STRING(SET_INTERFACE), - ENUM2STRING(SET_SHIELDS), - ENUM2STRING(SET_NO_KNOCKBACK), - ENUM2STRING(SET_INVISIBLE), - ENUM2STRING(SET_VAMPIRE), - ENUM2STRING(SET_FORCE_INVINCIBLE), - ENUM2STRING(SET_GREET_ALLIES), - ENUM2STRING(SET_PLAYER_LOCKED), - ENUM2STRING(SET_LOCK_PLAYER_WEAPONS), - ENUM2STRING(SET_NO_IMPACT_DAMAGE), - ENUM2STRING(SET_PARM1), - ENUM2STRING(SET_PARM2), - ENUM2STRING(SET_PARM3), - ENUM2STRING(SET_PARM4), - ENUM2STRING(SET_PARM5), - ENUM2STRING(SET_PARM6), - ENUM2STRING(SET_PARM7), - ENUM2STRING(SET_PARM8), - ENUM2STRING(SET_PARM9), - ENUM2STRING(SET_PARM10), - ENUM2STRING(SET_PARM11), - ENUM2STRING(SET_PARM12), - ENUM2STRING(SET_PARM13), - ENUM2STRING(SET_PARM14), - ENUM2STRING(SET_PARM15), - ENUM2STRING(SET_PARM16), - ENUM2STRING(SET_DEFEND_TARGET), - ENUM2STRING(SET_WAIT), - ENUM2STRING(SET_COUNT), - ENUM2STRING(SET_SHOT_SPACING), - ENUM2STRING(SET_VIDEO_PLAY), - ENUM2STRING(SET_VIDEO_FADE_IN), - ENUM2STRING(SET_VIDEO_FADE_OUT), - ENUM2STRING(SET_REMOVE_TARGET), - ENUM2STRING(SET_LOADGAME), - ENUM2STRING(SET_MENU_SCREEN), - ENUM2STRING(SET_OBJECTIVE_SHOW), - ENUM2STRING(SET_OBJECTIVE_HIDE), - ENUM2STRING(SET_OBJECTIVE_SUCCEEDED), - ENUM2STRING(SET_OBJECTIVE_SUCCEEDED_NO_UPDATE), - ENUM2STRING(SET_OBJECTIVE_FAILED), - ENUM2STRING(SET_MISSIONFAILED), - ENUM2STRING(SET_TACTICAL_SHOW), - ENUM2STRING(SET_TACTICAL_HIDE), - ENUM2STRING(SET_FOLLOWDIST), - ENUM2STRING(SET_SCALE), - ENUM2STRING(SET_OBJECTIVE_CLEARALL), - ENUM2STRING(SET_OBJECTIVE_LIGHTSIDE), - ENUM2STRING(SET_MISSIONSTATUSTEXT), - ENUM2STRING(SET_WIDTH), - ENUM2STRING(SET_CLOSINGCREDITS), - ENUM2STRING(SET_SKILL), - ENUM2STRING(SET_MISSIONSTATUSTIME), - ENUM2STRING(SET_FORCE_HEAL_LEVEL), - ENUM2STRING(SET_FORCE_JUMP_LEVEL), - ENUM2STRING(SET_FORCE_SPEED_LEVEL), - ENUM2STRING(SET_FORCE_PUSH_LEVEL), - ENUM2STRING(SET_FORCE_PULL_LEVEL), - ENUM2STRING(SET_FORCE_MINDTRICK_LEVEL), - ENUM2STRING(SET_FORCE_GRIP_LEVEL), - ENUM2STRING(SET_FORCE_LIGHTNING_LEVEL), - ENUM2STRING(SET_SABER_THROW), - ENUM2STRING(SET_SABER_DEFENSE), - ENUM2STRING(SET_SABER_OFFENSE), - ENUM2STRING(SET_FORCE_RAGE_LEVEL), - ENUM2STRING(SET_FORCE_PROTECT_LEVEL), - ENUM2STRING(SET_FORCE_ABSORB_LEVEL), - ENUM2STRING(SET_FORCE_DRAIN_LEVEL), - ENUM2STRING(SET_FORCE_SIGHT_LEVEL), - ENUM2STRING(SET_SABER1_COLOR1), - ENUM2STRING(SET_SABER1_COLOR2), - ENUM2STRING(SET_SABER2_COLOR1), - ENUM2STRING(SET_SABER2_COLOR2), - ENUM2STRING(SET_DISMEMBER_LIMB), - - ENUM2STRING(SET_VIEWENTITY), - ENUM2STRING(SET_WATCHTARGET), - ENUM2STRING(SET_SABERACTIVE), - - ENUM2STRING(SET_SABER1BLADEON), - ENUM2STRING(SET_SABER1BLADEOFF), - ENUM2STRING(SET_SABER2BLADEON), - ENUM2STRING(SET_SABER2BLADEOFF), - - ENUM2STRING(SET_ADJUST_AREA_PORTALS), - ENUM2STRING(SET_DMG_BY_HEAVY_WEAP_ONLY), - ENUM2STRING(SET_SHIELDED), - ENUM2STRING(SET_NO_GROUPS), - ENUM2STRING(SET_FIRE_WEAPON), - ENUM2STRING(SET_FIRE_WEAPON_NO_ANIM), - ENUM2STRING(SET_SAFE_REMOVE), - ENUM2STRING(SET_BOBA_JET_PACK), - ENUM2STRING(SET_INACTIVE), - ENUM2STRING(SET_FUNC_USABLE_VISIBLE), - ENUM2STRING(SET_END_SCREENDISSOLVE), - ENUM2STRING(SET_LOOPSOUND), - ENUM2STRING(SET_ICARUS_FREEZE), - ENUM2STRING(SET_ICARUS_UNFREEZE), - ENUM2STRING(SET_SABER1), - ENUM2STRING(SET_SABER2), - ENUM2STRING(SET_PLAYERMODEL), - ENUM2STRING(SET_VEHICLE), - ENUM2STRING(SET_SECURITY_KEY), - ENUM2STRING(SET_DAMAGEENTITY), - ENUM2STRING(SET_USE_CP_NEAREST), - ENUM2STRING(SET_MORELIGHT), - ENUM2STRING(SET_CINEMATIC_SKIPSCRIPT), - ENUM2STRING(SET_RAILCENTERTRACKLOCKED), - ENUM2STRING(SET_RAILCENTERTRACKUNLOCKED), - ENUM2STRING(SET_NO_FORCE), - ENUM2STRING(SET_NO_FALLTODEATH), - ENUM2STRING(SET_DISMEMBERABLE), - ENUM2STRING(SET_NO_ACROBATICS), - ENUM2STRING(SET_MUSIC_STATE), - ENUM2STRING(SET_USE_SUBTITLES), - ENUM2STRING(SET_CLEAN_DAMAGING_ENTS), - ENUM2STRING(SET_HUD), - //JKA - ENUM2STRING(SET_NO_PVS_CULL), - ENUM2STRING(SET_CLOAK), - ENUM2STRING(SET_RENDER_CULL_RADIUS), - ENUM2STRING(SET_DISTSQRD_TO_PLAYER), - ENUM2STRING(SET_FORCE_HEAL), - ENUM2STRING(SET_FORCE_SPEED), - ENUM2STRING(SET_FORCE_PUSH), - ENUM2STRING(SET_FORCE_PUSH_FAKE), - ENUM2STRING(SET_FORCE_PULL), - ENUM2STRING(SET_FORCE_MIND_TRICK), - ENUM2STRING(SET_FORCE_GRIP), - ENUM2STRING(SET_FORCE_LIGHTNING), - ENUM2STRING(SET_FORCE_SABERTHROW), - ENUM2STRING(SET_FORCE_RAGE), - ENUM2STRING(SET_FORCE_PROTECT), - ENUM2STRING(SET_FORCE_ABSORB), - ENUM2STRING(SET_FORCE_DRAIN), - ENUM2STRING(SET_WINTER_GEAR), - ENUM2STRING(SET_NO_ANGLES), - ENUM2STRING(SET_SABER_ORIGIN), - ENUM2STRING(SET_SKIN), - - { "", SET_ } -}; - -qboolean COM_ParseString( char **data, char **s ); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +static void Q3_SetWeapon(int entID, const char *wp_name); +static void Q3_SetItem(int entID, const char *item_name); +extern void CG_ChangeWeapon(int num); +extern int TAG_GetOrigin2(const char *owner, const char *name, vec3_t origin); +extern void G_TeamRetaliation(gentity_t *targ, gentity_t *attacker, qboolean stopIcarus); +extern void G_PlayDoorLoopSound(gentity_t *ent); +extern void G_PlayDoorSound(gentity_t *ent, int type); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void NPC_ClearLookTarget(gentity_t *self); +extern void WP_SaberSetColor(gentity_t *ent, int saberNum, int bladeNum, char *colorName); +extern void WP_SetSaber(gentity_t *ent, int saberNum, const char *saberName); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern void G_ChangePlayerModel(gentity_t *ent, const char *newModel); +extern vehicleType_t TranslateVehicleName(char *name); +extern void WP_SetSaberOrigin(gentity_t *self, vec3_t newOrg); +extern void JET_FlyStart(gentity_t *self); +extern void JET_FlyStop(gentity_t *self); +extern void Rail_LockCenterOfTrack(const char *trackName); +extern void Rail_UnLockCenterOfTrack(const char *trackName); +extern void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0); +extern qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse); + +extern int BMS_START; +extern int BMS_MID; +extern int BMS_END; +extern cvar_t *g_skippingcin; + +extern qboolean stop_icarus; + +#define stringIDExpand(str, strEnum) {str, strEnum}, ENUM2STRING(strEnum) + +stringID_table_t BSTable[] = {ENUM2STRING(BS_DEFAULT), //# default behavior for that NPC + ENUM2STRING(BS_ADVANCE_FIGHT), //# Advance to captureGoal and shoot enemies if you can + ENUM2STRING(BS_SLEEP), //# Play awake script when startled by sound + ENUM2STRING(BS_FOLLOW_LEADER), //# Follow your leader and shoot any enemies you come across + ENUM2STRING(BS_JUMP), //# Face navgoal and jump to it. + ENUM2STRING(BS_SEARCH), //# Using current waypoint as a base), search the immediate branches of waypoints for enemies + ENUM2STRING(BS_WANDER), //# Wander down random waypoint paths + ENUM2STRING(BS_NOCLIP), //# Moves through walls), etc. + ENUM2STRING(BS_REMOVE), //# Waits for player to leave PVS then removes itself + ENUM2STRING(BS_CINEMATIC), //# Does nothing but face it's angles and move to a goal if it has one + ENUM2STRING(BS_FLEE), //# Run toward the nav goal, avoiding danger + // the rest are internal only + {"", -1}}; + +stringID_table_t BSETTable[] = {ENUM2STRING(BSET_SPAWN), //# script to use when first spawned + ENUM2STRING(BSET_USE), //# script to use when used + ENUM2STRING(BSET_AWAKE), //# script to use when awoken/startled + ENUM2STRING(BSET_ANGER), //# script to use when aquire an enemy + ENUM2STRING(BSET_ATTACK), //# script to run when you attack + ENUM2STRING(BSET_VICTORY), //# script to run when you kill someone + ENUM2STRING(BSET_LOSTENEMY), //# script to run when you can't find your enemy + ENUM2STRING(BSET_PAIN), //# script to use when take pain + ENUM2STRING(BSET_FLEE), //# script to use when take pain below 50% of health + ENUM2STRING(BSET_DEATH), //# script to use when killed + ENUM2STRING(BSET_DELAYED), //# script to run when self->delayScriptTime is reached + ENUM2STRING(BSET_BLOCKED), //# script to run when blocked by a friendly NPC or player + ENUM2STRING(BSET_BUMPED), //# script to run when bumped into a friendly NPC or player (can set bumpRadius) + ENUM2STRING(BSET_STUCK), //# script to run when blocked by a wall + ENUM2STRING(BSET_FFIRE), //# script to run when player shoots their own teammates + ENUM2STRING(BSET_FFDEATH), //# script to run when player kills a teammate + stringIDExpand("", BSET_INVALID), + {"", -1}}; + +stringID_table_t WPTable[] = {{"NULL", WP_NONE}, + ENUM2STRING(WP_NONE), + // Player weapons + ENUM2STRING(WP_SABER), // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. + ENUM2STRING(WP_BLASTER_PISTOL), // apparently some enemy only version of the blaster + ENUM2STRING(WP_BLASTER), + ENUM2STRING(WP_DISRUPTOR), + ENUM2STRING(WP_BOWCASTER), + ENUM2STRING(WP_REPEATER), + ENUM2STRING(WP_DEMP2), + ENUM2STRING(WP_FLECHETTE), + ENUM2STRING(WP_ROCKET_LAUNCHER), + ENUM2STRING(WP_THERMAL), + ENUM2STRING(WP_TRIP_MINE), + ENUM2STRING(WP_DET_PACK), + ENUM2STRING(WP_CONCUSSION), + ENUM2STRING(WP_MELEE), // Any ol' melee attack + // NOTE: player can only have up to 16 weapons), anything after that is enemy only + ENUM2STRING(WP_STUN_BATON), + // NPC enemy weapons + ENUM2STRING(WP_BRYAR_PISTOL), + ENUM2STRING(WP_EMPLACED_GUN), + ENUM2STRING(WP_BOT_LASER), // Probe droid - Laser blast + ENUM2STRING(WP_TURRET), // turret guns + ENUM2STRING(WP_ATST_MAIN), + ENUM2STRING(WP_ATST_SIDE), + ENUM2STRING(WP_TIE_FIGHTER), + ENUM2STRING(WP_RAPID_FIRE_CONC), + ENUM2STRING(WP_JAWA), + ENUM2STRING(WP_TUSKEN_RIFLE), + ENUM2STRING(WP_TUSKEN_STAFF), + ENUM2STRING(WP_SCEPTER), + ENUM2STRING(WP_NOGHRI_STICK), + {"", 0}}; + +stringID_table_t INVTable[] = {ENUM2STRING(INV_ELECTROBINOCULARS), ENUM2STRING(INV_BACTA_CANISTER), ENUM2STRING(INV_SEEKER), + ENUM2STRING(INV_LIGHTAMP_GOGGLES), ENUM2STRING(INV_SENTRY), {"", 0}}; + +stringID_table_t eventTable[] = { + // BOTH_h + // END + {"", EV_BAD}}; + +stringID_table_t DMSTable[] = {{"NULL", -1}, + ENUM2STRING(DM_AUTO), //# let the game determine the dynamic music as normal + ENUM2STRING(DM_SILENCE), //# stop the music + ENUM2STRING(DM_EXPLORE), //# force the exploration music to play + ENUM2STRING(DM_ACTION), //# force the action music to play + ENUM2STRING(DM_BOSS), //# force the boss battle music to play (if there is any) + ENUM2STRING(DM_DEATH), //# force the "player dead" music to play + {"", -1}}; + +stringID_table_t HLTable[] = {{"NULL", -1}, + ENUM2STRING(HL_FOOT_RT), + ENUM2STRING(HL_FOOT_LT), + ENUM2STRING(HL_LEG_RT), + ENUM2STRING(HL_LEG_LT), + ENUM2STRING(HL_WAIST), + ENUM2STRING(HL_BACK_RT), + ENUM2STRING(HL_BACK_LT), + ENUM2STRING(HL_BACK), + ENUM2STRING(HL_CHEST_RT), + ENUM2STRING(HL_CHEST_LT), + ENUM2STRING(HL_CHEST), + ENUM2STRING(HL_ARM_RT), + ENUM2STRING(HL_ARM_LT), + ENUM2STRING(HL_HAND_RT), + ENUM2STRING(HL_HAND_LT), + ENUM2STRING(HL_HEAD), + ENUM2STRING(HL_GENERIC1), + ENUM2STRING(HL_GENERIC2), + ENUM2STRING(HL_GENERIC3), + ENUM2STRING(HL_GENERIC4), + ENUM2STRING(HL_GENERIC5), + ENUM2STRING(HL_GENERIC6), + {"", -1}}; + +stringID_table_t setTable[] = {ENUM2STRING(SET_SPAWNSCRIPT), // 0 + ENUM2STRING(SET_USESCRIPT), + ENUM2STRING(SET_AWAKESCRIPT), + ENUM2STRING(SET_ANGERSCRIPT), + ENUM2STRING(SET_ATTACKSCRIPT), + ENUM2STRING(SET_VICTORYSCRIPT), + ENUM2STRING(SET_PAINSCRIPT), + ENUM2STRING(SET_FLEESCRIPT), + ENUM2STRING(SET_DEATHSCRIPT), + ENUM2STRING(SET_DELAYEDSCRIPT), + ENUM2STRING(SET_BLOCKEDSCRIPT), + ENUM2STRING(SET_FFIRESCRIPT), + ENUM2STRING(SET_FFDEATHSCRIPT), + ENUM2STRING(SET_MINDTRICKSCRIPT), + ENUM2STRING(SET_NO_MINDTRICK), + ENUM2STRING(SET_ORIGIN), + ENUM2STRING(SET_TELEPORT_DEST), + ENUM2STRING(SET_ANGLES), + ENUM2STRING(SET_XVELOCITY), + ENUM2STRING(SET_YVELOCITY), + ENUM2STRING(SET_ZVELOCITY), + ENUM2STRING(SET_Z_OFFSET), + ENUM2STRING(SET_ENEMY), + ENUM2STRING(SET_LEADER), + ENUM2STRING(SET_NAVGOAL), + ENUM2STRING(SET_ANIM_UPPER), + ENUM2STRING(SET_ANIM_LOWER), + ENUM2STRING(SET_ANIM_BOTH), + ENUM2STRING(SET_ANIM_HOLDTIME_LOWER), + ENUM2STRING(SET_ANIM_HOLDTIME_UPPER), + ENUM2STRING(SET_ANIM_HOLDTIME_BOTH), + ENUM2STRING(SET_PLAYER_TEAM), + ENUM2STRING(SET_ENEMY_TEAM), + ENUM2STRING(SET_BEHAVIOR_STATE), + ENUM2STRING(SET_BEHAVIOR_STATE), + ENUM2STRING(SET_HEALTH), + ENUM2STRING(SET_ARMOR), + ENUM2STRING(SET_DEFAULT_BSTATE), + ENUM2STRING(SET_CAPTURE), + ENUM2STRING(SET_DPITCH), + ENUM2STRING(SET_DYAW), + ENUM2STRING(SET_EVENT), + ENUM2STRING(SET_TEMP_BSTATE), + ENUM2STRING(SET_COPY_ORIGIN), + ENUM2STRING(SET_VIEWTARGET), + ENUM2STRING(SET_WEAPON), + ENUM2STRING(SET_ITEM), + ENUM2STRING(SET_WALKSPEED), + ENUM2STRING(SET_RUNSPEED), + ENUM2STRING(SET_YAWSPEED), + ENUM2STRING(SET_AGGRESSION), + ENUM2STRING(SET_AIM), + ENUM2STRING(SET_FRICTION), + ENUM2STRING(SET_GRAVITY), + ENUM2STRING(SET_IGNOREPAIN), + ENUM2STRING(SET_IGNOREENEMIES), + ENUM2STRING(SET_IGNOREALERTS), + ENUM2STRING(SET_DONTSHOOT), + ENUM2STRING(SET_DONTFIRE), + ENUM2STRING(SET_LOCKED_ENEMY), + ENUM2STRING(SET_NOTARGET), + ENUM2STRING(SET_LEAN), + ENUM2STRING(SET_CROUCHED), + ENUM2STRING(SET_WALKING), + ENUM2STRING(SET_RUNNING), + ENUM2STRING(SET_CHASE_ENEMIES), + ENUM2STRING(SET_LOOK_FOR_ENEMIES), + ENUM2STRING(SET_FACE_MOVE_DIR), + ENUM2STRING(SET_ALT_FIRE), + ENUM2STRING(SET_DONT_FLEE), + ENUM2STRING(SET_FORCED_MARCH), + ENUM2STRING(SET_NO_RESPONSE), + ENUM2STRING(SET_NO_COMBAT_TALK), + ENUM2STRING(SET_NO_ALERT_TALK), + ENUM2STRING(SET_UNDYING), + ENUM2STRING(SET_TREASONED), + ENUM2STRING(SET_DISABLE_SHADER_ANIM), + ENUM2STRING(SET_SHADER_ANIM), + ENUM2STRING(SET_INVINCIBLE), + ENUM2STRING(SET_NOAVOID), + ENUM2STRING(SET_SHOOTDIST), + ENUM2STRING(SET_TARGETNAME), + ENUM2STRING(SET_TARGET), + ENUM2STRING(SET_TARGET2), + ENUM2STRING(SET_LOCATION), + ENUM2STRING(SET_PAINTARGET), + ENUM2STRING(SET_TIMESCALE), + ENUM2STRING(SET_VISRANGE), + ENUM2STRING(SET_EARSHOT), + ENUM2STRING(SET_VIGILANCE), + ENUM2STRING(SET_HFOV), + ENUM2STRING(SET_VFOV), + ENUM2STRING(SET_DELAYSCRIPTTIME), + ENUM2STRING(SET_FORWARDMOVE), + ENUM2STRING(SET_RIGHTMOVE), + ENUM2STRING(SET_LOCKYAW), + ENUM2STRING(SET_SOLID), + ENUM2STRING(SET_CAMERA_GROUP), + ENUM2STRING(SET_CAMERA_GROUP_Z_OFS), + ENUM2STRING(SET_CAMERA_GROUP_TAG), + ENUM2STRING(SET_LOOK_TARGET), + ENUM2STRING(SET_ADDRHANDBOLT_MODEL), + ENUM2STRING(SET_REMOVERHANDBOLT_MODEL), + ENUM2STRING(SET_ADDLHANDBOLT_MODEL), + ENUM2STRING(SET_REMOVELHANDBOLT_MODEL), + ENUM2STRING(SET_FACEAUX), + ENUM2STRING(SET_FACEBLINK), + ENUM2STRING(SET_FACEBLINKFROWN), + ENUM2STRING(SET_FACEFROWN), + ENUM2STRING(SET_FACESMILE), + ENUM2STRING(SET_FACEGLAD), + ENUM2STRING(SET_FACEHAPPY), + ENUM2STRING(SET_FACESHOCKED), + ENUM2STRING(SET_FACENORMAL), + ENUM2STRING(SET_FACEEYESCLOSED), + ENUM2STRING(SET_FACEEYESOPENED), + ENUM2STRING(SET_SCROLLTEXT), + ENUM2STRING(SET_LCARSTEXT), + ENUM2STRING(SET_CENTERTEXT), + ENUM2STRING(SET_SCROLLTEXTCOLOR), + ENUM2STRING(SET_CAPTIONTEXTCOLOR), + ENUM2STRING(SET_CENTERTEXTCOLOR), + ENUM2STRING(SET_PLAYER_USABLE), + ENUM2STRING(SET_STARTFRAME), + ENUM2STRING(SET_ENDFRAME), + ENUM2STRING(SET_ANIMFRAME), + ENUM2STRING(SET_LOOP_ANIM), + ENUM2STRING(SET_INTERFACE), + ENUM2STRING(SET_SHIELDS), + ENUM2STRING(SET_NO_KNOCKBACK), + ENUM2STRING(SET_INVISIBLE), + ENUM2STRING(SET_VAMPIRE), + ENUM2STRING(SET_FORCE_INVINCIBLE), + ENUM2STRING(SET_GREET_ALLIES), + ENUM2STRING(SET_PLAYER_LOCKED), + ENUM2STRING(SET_LOCK_PLAYER_WEAPONS), + ENUM2STRING(SET_NO_IMPACT_DAMAGE), + ENUM2STRING(SET_PARM1), + ENUM2STRING(SET_PARM2), + ENUM2STRING(SET_PARM3), + ENUM2STRING(SET_PARM4), + ENUM2STRING(SET_PARM5), + ENUM2STRING(SET_PARM6), + ENUM2STRING(SET_PARM7), + ENUM2STRING(SET_PARM8), + ENUM2STRING(SET_PARM9), + ENUM2STRING(SET_PARM10), + ENUM2STRING(SET_PARM11), + ENUM2STRING(SET_PARM12), + ENUM2STRING(SET_PARM13), + ENUM2STRING(SET_PARM14), + ENUM2STRING(SET_PARM15), + ENUM2STRING(SET_PARM16), + ENUM2STRING(SET_DEFEND_TARGET), + ENUM2STRING(SET_WAIT), + ENUM2STRING(SET_COUNT), + ENUM2STRING(SET_SHOT_SPACING), + ENUM2STRING(SET_VIDEO_PLAY), + ENUM2STRING(SET_VIDEO_FADE_IN), + ENUM2STRING(SET_VIDEO_FADE_OUT), + ENUM2STRING(SET_REMOVE_TARGET), + ENUM2STRING(SET_LOADGAME), + ENUM2STRING(SET_MENU_SCREEN), + ENUM2STRING(SET_OBJECTIVE_SHOW), + ENUM2STRING(SET_OBJECTIVE_HIDE), + ENUM2STRING(SET_OBJECTIVE_SUCCEEDED), + ENUM2STRING(SET_OBJECTIVE_SUCCEEDED_NO_UPDATE), + ENUM2STRING(SET_OBJECTIVE_FAILED), + ENUM2STRING(SET_MISSIONFAILED), + ENUM2STRING(SET_TACTICAL_SHOW), + ENUM2STRING(SET_TACTICAL_HIDE), + ENUM2STRING(SET_FOLLOWDIST), + ENUM2STRING(SET_SCALE), + ENUM2STRING(SET_OBJECTIVE_CLEARALL), + ENUM2STRING(SET_OBJECTIVE_LIGHTSIDE), + ENUM2STRING(SET_MISSIONSTATUSTEXT), + ENUM2STRING(SET_WIDTH), + ENUM2STRING(SET_CLOSINGCREDITS), + ENUM2STRING(SET_SKILL), + ENUM2STRING(SET_MISSIONSTATUSTIME), + ENUM2STRING(SET_FORCE_HEAL_LEVEL), + ENUM2STRING(SET_FORCE_JUMP_LEVEL), + ENUM2STRING(SET_FORCE_SPEED_LEVEL), + ENUM2STRING(SET_FORCE_PUSH_LEVEL), + ENUM2STRING(SET_FORCE_PULL_LEVEL), + ENUM2STRING(SET_FORCE_MINDTRICK_LEVEL), + ENUM2STRING(SET_FORCE_GRIP_LEVEL), + ENUM2STRING(SET_FORCE_LIGHTNING_LEVEL), + ENUM2STRING(SET_SABER_THROW), + ENUM2STRING(SET_SABER_DEFENSE), + ENUM2STRING(SET_SABER_OFFENSE), + ENUM2STRING(SET_FORCE_RAGE_LEVEL), + ENUM2STRING(SET_FORCE_PROTECT_LEVEL), + ENUM2STRING(SET_FORCE_ABSORB_LEVEL), + ENUM2STRING(SET_FORCE_DRAIN_LEVEL), + ENUM2STRING(SET_FORCE_SIGHT_LEVEL), + ENUM2STRING(SET_SABER1_COLOR1), + ENUM2STRING(SET_SABER1_COLOR2), + ENUM2STRING(SET_SABER2_COLOR1), + ENUM2STRING(SET_SABER2_COLOR2), + ENUM2STRING(SET_DISMEMBER_LIMB), + + ENUM2STRING(SET_VIEWENTITY), + ENUM2STRING(SET_WATCHTARGET), + ENUM2STRING(SET_SABERACTIVE), + + ENUM2STRING(SET_SABER1BLADEON), + ENUM2STRING(SET_SABER1BLADEOFF), + ENUM2STRING(SET_SABER2BLADEON), + ENUM2STRING(SET_SABER2BLADEOFF), + + ENUM2STRING(SET_ADJUST_AREA_PORTALS), + ENUM2STRING(SET_DMG_BY_HEAVY_WEAP_ONLY), + ENUM2STRING(SET_SHIELDED), + ENUM2STRING(SET_NO_GROUPS), + ENUM2STRING(SET_FIRE_WEAPON), + ENUM2STRING(SET_FIRE_WEAPON_NO_ANIM), + ENUM2STRING(SET_SAFE_REMOVE), + ENUM2STRING(SET_BOBA_JET_PACK), + ENUM2STRING(SET_INACTIVE), + ENUM2STRING(SET_FUNC_USABLE_VISIBLE), + ENUM2STRING(SET_END_SCREENDISSOLVE), + ENUM2STRING(SET_LOOPSOUND), + ENUM2STRING(SET_ICARUS_FREEZE), + ENUM2STRING(SET_ICARUS_UNFREEZE), + ENUM2STRING(SET_SABER1), + ENUM2STRING(SET_SABER2), + ENUM2STRING(SET_PLAYERMODEL), + ENUM2STRING(SET_VEHICLE), + ENUM2STRING(SET_SECURITY_KEY), + ENUM2STRING(SET_DAMAGEENTITY), + ENUM2STRING(SET_USE_CP_NEAREST), + ENUM2STRING(SET_MORELIGHT), + ENUM2STRING(SET_CINEMATIC_SKIPSCRIPT), + ENUM2STRING(SET_RAILCENTERTRACKLOCKED), + ENUM2STRING(SET_RAILCENTERTRACKUNLOCKED), + ENUM2STRING(SET_NO_FORCE), + ENUM2STRING(SET_NO_FALLTODEATH), + ENUM2STRING(SET_DISMEMBERABLE), + ENUM2STRING(SET_NO_ACROBATICS), + ENUM2STRING(SET_MUSIC_STATE), + ENUM2STRING(SET_USE_SUBTITLES), + ENUM2STRING(SET_CLEAN_DAMAGING_ENTS), + ENUM2STRING(SET_HUD), + // JKA + ENUM2STRING(SET_NO_PVS_CULL), + ENUM2STRING(SET_CLOAK), + ENUM2STRING(SET_RENDER_CULL_RADIUS), + ENUM2STRING(SET_DISTSQRD_TO_PLAYER), + ENUM2STRING(SET_FORCE_HEAL), + ENUM2STRING(SET_FORCE_SPEED), + ENUM2STRING(SET_FORCE_PUSH), + ENUM2STRING(SET_FORCE_PUSH_FAKE), + ENUM2STRING(SET_FORCE_PULL), + ENUM2STRING(SET_FORCE_MIND_TRICK), + ENUM2STRING(SET_FORCE_GRIP), + ENUM2STRING(SET_FORCE_LIGHTNING), + ENUM2STRING(SET_FORCE_SABERTHROW), + ENUM2STRING(SET_FORCE_RAGE), + ENUM2STRING(SET_FORCE_PROTECT), + ENUM2STRING(SET_FORCE_ABSORB), + ENUM2STRING(SET_FORCE_DRAIN), + ENUM2STRING(SET_WINTER_GEAR), + ENUM2STRING(SET_NO_ANGLES), + ENUM2STRING(SET_SABER_ORIGIN), + ENUM2STRING(SET_SKIN), + + {"", SET_}}; + +qboolean COM_ParseString(char **data, char **s); //======================================================================= @@ -507,15 +478,13 @@ void Q3_SetTaskID( gentity_t *ent, taskID_t taskType, int taskID ) ------------------------- */ -static void Q3_TaskIDSet( gentity_t *ent, taskID_t taskType, int taskID ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +static void Q3_TaskIDSet(gentity_t *ent, taskID_t taskType, int taskID) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - //Might be stomping an old task, so complete and clear previous task if there was one - Q3_TaskIDComplete( ent, taskType ); + // Might be stomping an old task, so complete and clear previous task if there was one + Q3_TaskIDComplete(ent, taskType); ent->taskID[taskType] = taskID; } @@ -526,44 +495,26 @@ SetTextColor ------------------------- */ -static void SetTextColor ( vec4_t textcolor,const char *color) -{ - - if (Q_stricmp(color,"BLACK") == 0) - { - VectorCopy4( colorTable[CT_BLACK], textcolor ); - } - else if (Q_stricmp(color,"RED") == 0) - { - VectorCopy4( colorTable[CT_RED], textcolor ); - } - else if (Q_stricmp(color,"GREEN") == 0) - { - VectorCopy4( colorTable[CT_GREEN], textcolor ); - } - else if (Q_stricmp(color,"YELLOW") == 0) - { - VectorCopy4( colorTable[CT_YELLOW], textcolor ); - } - else if (Q_stricmp(color,"BLUE") == 0) - { - VectorCopy4( colorTable[CT_BLUE], textcolor ); - } - else if (Q_stricmp(color,"CYAN") == 0) - { - VectorCopy4( colorTable[CT_CYAN], textcolor ); - } - else if (Q_stricmp(color,"MAGENTA") == 0) - { - VectorCopy4( colorTable[CT_MAGENTA], textcolor ); - } - else if (Q_stricmp(color,"WHITE") == 0) - { - VectorCopy4( colorTable[CT_WHITE], textcolor ); - } - else - { - VectorCopy4( colorTable[CT_WHITE], textcolor ); +static void SetTextColor(vec4_t textcolor, const char *color) { + + if (Q_stricmp(color, "BLACK") == 0) { + VectorCopy4(colorTable[CT_BLACK], textcolor); + } else if (Q_stricmp(color, "RED") == 0) { + VectorCopy4(colorTable[CT_RED], textcolor); + } else if (Q_stricmp(color, "GREEN") == 0) { + VectorCopy4(colorTable[CT_GREEN], textcolor); + } else if (Q_stricmp(color, "YELLOW") == 0) { + VectorCopy4(colorTable[CT_YELLOW], textcolor); + } else if (Q_stricmp(color, "BLUE") == 0) { + VectorCopy4(colorTable[CT_BLUE], textcolor); + } else if (Q_stricmp(color, "CYAN") == 0) { + VectorCopy4(colorTable[CT_CYAN], textcolor); + } else if (Q_stricmp(color, "MAGENTA") == 0) { + VectorCopy4(colorTable[CT_MAGENTA], textcolor); + } else if (Q_stricmp(color, "WHITE") == 0) { + VectorCopy4(colorTable[CT_WHITE], textcolor); + } else { + VectorCopy4(colorTable[CT_WHITE], textcolor); } return; @@ -577,29 +528,23 @@ WARNING: Clearing a taskID will make that task never finish unless you intend to return the same taskID from somewhere else. ------------------------- */ -void Q3_TaskIDClear( int *taskID ) -{ - *taskID = -1; -} +void Q3_TaskIDClear(int *taskID) { *taskID = -1; } /* ------------------------- qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) ------------------------- */ -qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) -{ - if ( ent->m_iIcarusID == IIcarusInterface::ICARUS_INVALID /*!ent->sequencer || !ent->taskManager*/ ) - { +qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType) { + if (ent->m_iIcarusID == IIcarusInterface::ICARUS_INVALID /*!ent->sequencer || !ent->taskManager*/) { return qfalse; } - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return qfalse; } - if ( ent->taskID[taskType] >= 0 )//-1 is none + if (ent->taskID[taskType] >= 0) //-1 is none { return qtrue; } @@ -612,31 +557,26 @@ qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ) ------------------------- */ -void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +void Q3_TaskIDComplete(gentity_t *ent, taskID_t taskType) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - if ( ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID /*ent->taskManager*/ && Q3_TaskIDPending( ent, taskType ) ) - {//Complete it - IIcarusInterface::GetIcarus()->Completed( ent->m_iIcarusID, ent->taskID[taskType] ); + if (ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID /*ent->taskManager*/ && Q3_TaskIDPending(ent, taskType)) { // Complete it + IIcarusInterface::GetIcarus()->Completed(ent->m_iIcarusID, ent->taskID[taskType]); - //See if any other tasks have the name number and clear them so we don't complete more than once - int clearTask = ent->taskID[taskType]; - for ( int tid = 0; tid < NUM_TIDS; tid++ ) - { - if ( ent->taskID[tid] == clearTask ) - { - Q3_TaskIDClear( &ent->taskID[tid] ); + // See if any other tasks have the name number and clear them so we don't complete more than once + int clearTask = ent->taskID[taskType]; + for (int tid = 0; tid < NUM_TIDS; tid++) { + if (ent->taskID[tid] == clearTask) { + Q3_TaskIDClear(&ent->taskID[tid]); } } - //clear it - should be cleared in for loop above - //Q3_TaskIDClear( &ent->taskID[taskType] ); + // clear it - should be cleared in for loop above + // Q3_TaskIDClear( &ent->taskID[taskType] ); } - //otherwise, wasn't waiting for a task to complete anyway + // otherwise, wasn't waiting for a task to complete anyway } /* @@ -647,25 +587,19 @@ Q3_CheckStringCounterIncrement Argument : const char *string ============ */ -static float Q3_CheckStringCounterIncrement( const char *string ) -{ - char *numString; - float val = 0.0f; +static float Q3_CheckStringCounterIncrement(const char *string) { + char *numString; + float val = 0.0f; - if ( string[0] == '+' ) - {//We want to increment whatever the value is by whatever follows the + - if ( string[1] ) - { + if (string[0] == '+') { // We want to increment whatever the value is by whatever follows the + + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ); + val = atof(numString); } - } - else if ( string[0] == '-' ) - {//we want to decrement - if ( string[1] ) - { + } else if (string[0] == '-') { // we want to decrement + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ) * -1; + val = atof(numString) * -1; } } @@ -677,17 +611,15 @@ static float Q3_CheckStringCounterIncrement( const char *string ) Q3_GetAnimLower ------------------------- */ -static char *Q3_GetAnimLower( gentity_t *ent ) -{ - if ( ent->client == NULL ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n" ); +static char *Q3_GetAnimLower(gentity_t *ent) { + if (ent->client == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n"); return NULL; } int anim = ent->client->ps.legsAnim; - return (char *) GetStringForID( animTable, anim ); + return (char *)GetStringForID(animTable, anim); } /* @@ -695,17 +627,15 @@ static char *Q3_GetAnimLower( gentity_t *ent ) Q3_GetAnimUpper ------------------------- */ -static char *Q3_GetAnimUpper( gentity_t *ent ) -{ - if ( ent->client == NULL ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n" ); +static char *Q3_GetAnimUpper(gentity_t *ent) { + if (ent->client == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n"); return NULL; } int anim = ent->client->ps.torsoAnim; - return (char *) GetStringForID( animTable, anim ); + return (char *)GetStringForID(animTable, anim); } /* @@ -713,29 +643,25 @@ static char *Q3_GetAnimUpper( gentity_t *ent ) Q3_GetAnimBoth ------------------------- */ -static char *Q3_GetAnimBoth( gentity_t *ent ) -{ - char *lowerName, *upperName; +static char *Q3_GetAnimBoth(gentity_t *ent) { + char *lowerName, *upperName; - lowerName = Q3_GetAnimLower( ent ); - upperName = Q3_GetAnimUpper( ent ); + lowerName = Q3_GetAnimLower(ent); + upperName = Q3_GetAnimUpper(ent); - if ( VALIDSTRING( lowerName ) == false ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n" ); + if (VALIDSTRING(lowerName) == false) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n"); return NULL; } - if ( VALIDSTRING( upperName ) == false ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n" ); + if (VALIDSTRING(upperName) == false) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n"); return NULL; } - if ( Q_stricmp( lowerName, upperName ) ) - { -#ifdef _DEBUG // sigh, cut down on tester reports that aren't important - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n" ); + if (Q_stricmp(lowerName, upperName)) { +#ifdef _DEBUG // sigh, cut down on tester reports that aren't important + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n"); #endif } @@ -747,87 +673,76 @@ static char *Q3_GetAnimBoth( gentity_t *ent ) Q3_SetObjective ------------------------- */ -extern qboolean G_CheckPlayerDarkSide( void ); -static void Q3_SetObjective(const char *ObjEnum, int status) -{ +extern qboolean G_CheckPlayerDarkSide(void); +static void Q3_SetObjective(const char *ObjEnum, int status) { int objectiveID; - gclient_t *client; - objectives_t *objective; - int *objectivesShown; + gclient_t *client; + objectives_t *objective; + int *objectivesShown; client = &level.clients[0]; - objectiveID = GetIDForString( objectiveTable, ObjEnum ); + objectiveID = GetIDForString(objectiveTable, ObjEnum); objective = &client->sess.mission_objectives[objectiveID]; objectivesShown = &client->sess.missionObjectivesShown; - - switch (status) - { - case SET_OBJ_HIDE : + switch (status) { + case SET_OBJ_HIDE: objective->display = (qboolean)(OBJECTIVE_HIDE != 0); break; - case SET_OBJ_SHOW : + case SET_OBJ_SHOW: objective->display = (qboolean)(OBJECTIVE_SHOW != 0); objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text break; - case SET_OBJ_PENDING : + case SET_OBJ_PENDING: objective->status = OBJECTIVE_STAT_PENDING; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; - case SET_OBJ_SUCCEEDED : + case SET_OBJ_SUCCEEDED: objective->status = OBJECTIVE_STAT_SUCCEEDED; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; - case SET_OBJ_FAILED : + case SET_OBJ_FAILED: objective->status = OBJECTIVE_STAT_FAILED; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; } - if ( objectiveID == LIGHTSIDE_OBJ - && status == SET_OBJ_FAILED ) - {//don't do this unless we just set that specific objective (just turned to the dark side) with this SET_OBJECTIVE command + if (objectiveID == LIGHTSIDE_OBJ && + status == SET_OBJ_FAILED) { // don't do this unless we just set that specific objective (just turned to the dark side) with this SET_OBJECTIVE command G_CheckPlayerDarkSide(); } } - /* ------------------------- Q3_SetMissionFailed ------------------------- */ -extern void G_PlayerGuiltDeath( void ); -static void Q3_SetMissionFailed(const char *TextEnum) -{ - gentity_t *ent = &g_entities[0]; +extern void G_PlayerGuiltDeath(void); +static void Q3_SetMissionFailed(const char *TextEnum) { + gentity_t *ent = &g_entities[0]; - if ( ent->health > 0 ) - { + if (ent->health > 0) { G_PlayerGuiltDeath(); } ent->health = 0; - //FIXME: what about other NPCs? Scripts? + // FIXME: what about other NPCs? Scripts? // statusTextIndex is looked at on the client side. - statusTextIndex = GetIDForString( missionFailedTable, TextEnum ); + statusTextIndex = GetIDForString(missionFailedTable, TextEnum); cg.missionStatusShow = qtrue; - if ( ent->client ) - {//hold this screen up for at least 2 seconds + if (ent->client) { // hold this screen up for at least 2 seconds ent->client->respawnTime = level.time + 2000; } } @@ -837,14 +752,12 @@ static void Q3_SetMissionFailed(const char *TextEnum) Q3_SetStatusText ------------------------- */ -static void Q3_SetStatusText(const char *StatusTextEnum) -{ +static void Q3_SetStatusText(const char *StatusTextEnum) { int statusTextID; - statusTextID = GetIDForString( statusTextTable, StatusTextEnum ); + statusTextID = GetIDForString(statusTextTable, StatusTextEnum); - switch (statusTextID) - { + switch (statusTextID) { case STAT_INSUBORDINATION: case STAT_YOUCAUSEDDEATHOFTEAMMATE: case STAT_DIDNTPROTECTTECH: @@ -861,16 +774,14 @@ static void Q3_SetStatusText(const char *StatusTextEnum) } } - /* ------------------------- Q3_ObjectiveClearAll ------------------------- */ -static void Q3_ObjectiveClearAll(void) -{ +static void Q3_ObjectiveClearAll(void) { client = &level.clients[0]; - memset(client->sess.mission_objectives,0,sizeof(client->sess.mission_objectives)); + memset(client->sess.mission_objectives, 0, sizeof(client->sess.mission_objectives)); } /* @@ -880,10 +791,7 @@ Q3_SetCaptionTextColor Change color text prints in ============= */ -static void Q3_SetCaptionTextColor ( const char *color) -{ - SetTextColor(textcolor_caption,color); -} +static void Q3_SetCaptionTextColor(const char *color) { SetTextColor(textcolor_caption, color); } /* ============= @@ -892,10 +800,7 @@ Q3_SetCenterTextColor Change color text prints in ============= */ -static void Q3_SetCenterTextColor ( const char *color) -{ - SetTextColor(textcolor_center,color); -} +static void Q3_SetCenterTextColor(const char *color) { SetTextColor(textcolor_center, color); } /* ============= @@ -904,10 +809,7 @@ Q3_SetScrollTextColor Change color text prints in ============= */ -static void Q3_SetScrollTextColor ( const char *color) -{ - SetTextColor(textcolor_scroll,color); -} +static void Q3_SetScrollTextColor(const char *color) { SetTextColor(textcolor_scroll, color); } /* ============= @@ -916,9 +818,8 @@ Q3_ScrollText Prints a message in the center of the screen ============= */ -static void Q3_ScrollText ( const char *id) -{ - gi.SendServerCommand( 0, "st \"%s\"", id); +static void Q3_ScrollText(const char *id) { + gi.SendServerCommand(0, "st \"%s\"", id); return; } @@ -930,9 +831,8 @@ Q3_LCARSText Prints a message in the center of the screen giving it an LCARS frame around it ============= */ -static void Q3_LCARSText ( const char *id) -{ - gi.SendServerCommand( 0, "lt \"%s\"", id); +static void Q3_LCARSText(const char *id) { + gi.SendServerCommand(0, "lt \"%s\"", id); return; } @@ -991,43 +891,41 @@ And: Take any string, look for "/mr_" replace with "/ms_" based on "sex" returns qtrue if changed to ms ============= */ -static qboolean G_AddSexToPlayerString ( char *string, qboolean qDoBoth ) -{ +static qboolean G_AddSexToPlayerString(char *string, qboolean qDoBoth) { char *start; - if VALIDSTRING( string ) { - if ( g_sex->string[0] == 'f' ) { - start = strstr( string, "jaden_male/" ); - if ( start != NULL ) { - strncpy( start, "jaden_fmle", 10 ); + if VALIDSTRING (string) { + if (g_sex->string[0] == 'f') { + start = strstr(string, "jaden_male/"); + if (start != NULL) { + strncpy(start, "jaden_fmle", 10); return qtrue; } else { - start = strrchr( string, '/' ); //get the last slash before the wav + start = strrchr(string, '/'); // get the last slash before the wav if (start != NULL) { - if (!strncmp( start, "/mr_", 4) ) { - if (qDoBoth) { //we want to change mr to ms - start[2] = 's'; //change mr to ms + if (!strncmp(start, "/mr_", 4)) { + if (qDoBoth) { // we want to change mr to ms + start[2] = 's'; // change mr to ms return qtrue; - } else { //IF qDoBoth - return qfalse; //don't want this one + } else { // IF qDoBoth + return qfalse; // don't want this one } } - } //IF found slash + } // IF found slash } - } //IF Female - else { //i'm male - start = strrchr( string, '/' ); //get the last slash before the wav + } // IF Female + else { // i'm male + start = strrchr(string, '/'); // get the last slash before the wav if (start != NULL) { - if (!strncmp( start, "/ms_", 4) ) { - return qfalse; //don't want this one + if (!strncmp(start, "/ms_", 4)) { + return qfalse; // don't want this one } - } //IF found slash + } // IF found slash } - } //if VALIDSTRING + } // if VALIDSTRING return qtrue; } - /* ============= Q3_SetAngles @@ -1035,32 +933,26 @@ Q3_SetAngles Sets the angles of an entity directly ============= */ -static void Q3_SetDYaw( int entID, float data ); -static void Q3_SetAngles( int entID, vec3_t angles ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDYaw(int entID, float data); +static void Q3_SetAngles(int entID, vec3_t angles) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); return; } - if (ent->client) - { - SetClientViewAngle( ent, angles ); - if ( ent->NPC ) - { - Q3_SetDYaw( entID, angles[YAW] ); + if (ent->client) { + SetClientViewAngle(ent, angles); + if (ent->NPC) { + Q3_SetDYaw(entID, angles[YAW]); } + } else { + VectorCopy(angles, ent->s.angles); + VectorCopy(angles, ent->s.apos.trBase); + VectorCopy(angles, ent->currentAngles); } - else - { - VectorCopy( angles, ent->s.angles ); - VectorCopy( angles, ent->s.apos.trBase ); - VectorCopy( angles, ent->currentAngles ); - } - gi.linkentity( ent ); + gi.linkentity(ent); } /* @@ -1070,41 +962,35 @@ Q3_SetOrigin Sets the origin of an entity directly ============= */ -static void Q3_SetOrigin( int entID, vec3_t origin ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOrigin(int entID, vec3_t origin) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); return; } - gi.unlinkentity (ent); + gi.unlinkentity(ent); - if(ent->client) - { + if (ent->client) { VectorCopy(origin, ent->client->ps.origin); VectorCopy(origin, ent->currentOrigin); ent->client->ps.origin[2] += 1; - VectorClear (ent->client->ps.velocity); - ent->client->ps.pm_time = 160; // hold time + VectorClear(ent->client->ps.velocity); + ent->client->ps.pm_time = 160; // hold time ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; ent->client->ps.eFlags ^= EF_TELEPORT_BIT; -// G_KillBox (ent); - } - else - { - G_SetOrigin( ent, origin ); + // G_KillBox (ent); + } else { + G_SetOrigin(ent, origin); } - gi.linkentity( ent ); + gi.linkentity(ent); } - /* ============ MoveOwner @@ -1113,29 +999,23 @@ MoveOwner Argument : gentity_t *self ============ */ -void MoveOwner( gentity_t *self ) -{ +void MoveOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } - if ( SpotWouldTelefrag2( self->owner, self->currentOrigin ) ) - { + if (SpotWouldTelefrag2(self->owner, self->currentOrigin)) { self->e_ThinkFunc = thinkF_MoveOwner; - } - else - { - G_SetOrigin( self->owner, self->currentOrigin ); - gi.linkentity( self->owner ); - Q3_TaskIDComplete( self->owner, TID_MOVE_NAV ); + } else { + G_SetOrigin(self->owner, self->currentOrigin); + gi.linkentity(self->owner); + Q3_TaskIDComplete(self->owner, TID_MOVE_NAV); } } - /* ============= Q3_SetTeleportDest @@ -1143,29 +1023,24 @@ Q3_SetTeleportDest Copies passed origin to ent running script once there is nothing there blocking the spot ============= */ -static qboolean Q3_SetTeleportDest( int entID, vec3_t org ) -{ - gentity_t *teleEnt = &g_entities[entID]; +static qboolean Q3_SetTeleportDest(int entID, vec3_t org) { + gentity_t *teleEnt = &g_entities[entID]; - if ( teleEnt ) - { - if ( SpotWouldTelefrag2( teleEnt, org ) ) - { + if (teleEnt) { + if (SpotWouldTelefrag2(teleEnt, org)) { gentity_t *teleporter = G_Spawn(); - G_SetOrigin( teleporter, org ); - gi.linkentity( teleporter ); + G_SetOrigin(teleporter, org); + gi.linkentity(teleporter); teleporter->owner = teleEnt; teleporter->e_ThinkFunc = thinkF_MoveOwner; teleporter->nextthink = level.time + FRAMETIME; return qfalse; - } - else - { - G_SetOrigin( teleEnt, org ); - gi.linkentity( teleEnt ); + } else { + G_SetOrigin(teleEnt, org); + gi.linkentity(teleEnt); } } @@ -1179,18 +1054,14 @@ Q3_SetCopyOrigin Copies origin of found ent into ent running script =============` */ -static void Q3_SetCopyOrigin( int entID, const char *name ) -{ - gentity_t *found = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCopyOrigin(int entID, const char *name) { + gentity_t *found = G_Find(NULL, FOFS(targetname), (char *)name); - if(found) - { - Q3_SetOrigin( entID, found->currentOrigin ); - SetClientViewAngle( &g_entities[entID], found->s.angles ); - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); + if (found) { + Q3_SetOrigin(entID, found->currentOrigin); + SetClientViewAngle(&g_entities[entID], found->s.angles); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); } } @@ -1201,23 +1072,20 @@ Q3_SetVelocity Set the velocity of an entity directly ============= */ -static void Q3_SetVelocity( int entID, int axis, float speed ) -{ - gentity_t *found = &g_entities[entID]; - //FIXME: Not supported - if(!found) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); +static void Q3_SetVelocity(int entID, int axis, float speed) { + gentity_t *found = &g_entities[entID]; + // FIXME: Not supported + if (!found) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); return; } - if(!found->client) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); + if (!found->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); return; } - //FIXME: add or set? + // FIXME: add or set? found->client->ps.velocity[axis] += speed; found->client->ps.pm_time = 500; @@ -1233,17 +1101,15 @@ Q3_SetAdjustAreaPortals Argument : qboolean shields ============ */ -static void Q3_SetAdjustAreaPortals( int entID, qboolean adjust ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAdjustAreaPortals(int entID, qboolean adjust) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAdjustAreaPortals: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAdjustAreaPortals: invalid entID %d\n", entID); return; } - ent->svFlags = (adjust) ? (ent->svFlags|SVF_MOVER_ADJ_AREA_PORTALS) : (ent->svFlags&~SVF_MOVER_ADJ_AREA_PORTALS); + ent->svFlags = (adjust) ? (ent->svFlags | SVF_MOVER_ADJ_AREA_PORTALS) : (ent->svFlags & ~SVF_MOVER_ADJ_AREA_PORTALS); } /* @@ -1255,17 +1121,15 @@ Q3_SetDmgByHeavyWeapOnly Argument : qboolean dmg ============ */ -static void Q3_SetDmgByHeavyWeapOnly( int entID, qboolean dmg ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDmgByHeavyWeapOnly(int entID, qboolean dmg) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: invalid entID %d\n", entID); return; } - ent->flags = (dmg) ? (ent->flags|FL_DMG_BY_HEAVY_WEAP_ONLY) : (ent->flags&~FL_DMG_BY_HEAVY_WEAP_ONLY); + ent->flags = (dmg) ? (ent->flags | FL_DMG_BY_HEAVY_WEAP_ONLY) : (ent->flags & ~FL_DMG_BY_HEAVY_WEAP_ONLY); } /* @@ -1277,17 +1141,15 @@ Q3_SetShielded Argument : qboolean dmg ============ */ -static void Q3_SetShielded( int entID, qboolean dmg ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShielded(int entID, qboolean dmg) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetShielded: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetShielded: invalid entID %d\n", entID); return; } - ent->flags = (dmg) ? (ent->flags|FL_SHIELDED) : (ent->flags&~FL_SHIELDED); + ent->flags = (dmg) ? (ent->flags | FL_SHIELDED) : (ent->flags & ~FL_SHIELDED); } /* @@ -1299,23 +1161,20 @@ Q3_SetNoGroups Argument : qboolean dmg ============ */ -static void Q3_SetNoGroups( int entID, qboolean noGroups ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoGroups(int entID, qboolean noGroups) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoGroups: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoGroups: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoGroups: ent %s is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoGroups: ent %s is not an NPC!\n", ent->targetname); return; } - ent->NPC->scriptFlags = noGroups ? (ent->NPC->scriptFlags|SCF_NO_GROUPS) : (ent->NPC->scriptFlags&~SCF_NO_GROUPS); + ent->NPC->scriptFlags = noGroups ? (ent->NPC->scriptFlags | SCF_NO_GROUPS) : (ent->NPC->scriptFlags & ~SCF_NO_GROUPS); } /* @@ -1325,41 +1184,34 @@ moverCallback Utility function ============= */ -extern void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ); -void moverCallback( gentity_t *ent ) -{ - //complete the task - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); +extern void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor); +void moverCallback(gentity_t *ent) { + // complete the task + Q3_TaskIDComplete(ent, TID_MOVE_NAV); // play sound - ent->s.loopSound = 0;//stop looping sound - G_PlayDoorSound( ent, BMS_END );//play end sound + ent->s.loopSound = 0; // stop looping sound + G_PlayDoorSound(ent, BMS_END); // play end sound - if ( ent->moverState == MOVER_1TO2 ) - {//reached open + if (ent->moverState == MOVER_1TO2) { // reached open // reached pos2 - MatchTeam( ent, MOVER_POS2, level.time ); - //SetMoverState( ent, MOVER_POS2, level.time ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//reached closed - MatchTeam( ent, MOVER_POS1, level.time ); - //SetMoverState( ent, MOVER_POS1, level.time ); - //close the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qfalse ); + MatchTeam(ent, MOVER_POS2, level.time); + // SetMoverState( ent, MOVER_POS2, level.time ); + } else if (ent->moverState == MOVER_2TO1) { // reached closed + MatchTeam(ent, MOVER_POS1, level.time); + // SetMoverState( ent, MOVER_POS1, level.time ); + // close the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qfalse); } } - if ( ent->e_BlockedFunc == blockedF_Blocked_Mover ) - { + if (ent->e_BlockedFunc == blockedF_Blocked_Mover) { ent->e_BlockedFunc = blockedF_NULL; } - if ( !Q_stricmp( "misc_model_breakable", ent->classname ) && ent->physicsBounce ) - {//a gravity-affected model - misc_model_breakable_gravity_init( ent, qfalse ); + if (!Q_stricmp("misc_model_breakable", ent->classname) && ent->physicsBounce) { // a gravity-affected model + misc_model_breakable_gravity_init(ent, qfalse); } } @@ -1370,32 +1222,30 @@ anglerCallback Utility function ============= */ -void anglerCallback( gentity_t *ent ) -{ - //Complete the task - Q3_TaskIDComplete( ent, TID_ANGLE_FACE ); +void anglerCallback(gentity_t *ent) { + // Complete the task + Q3_TaskIDComplete(ent, TID_ANGLE_FACE); // play sound - ent->s.loopSound = 0;//stop looping sound - G_PlayDoorSound( ent, BMS_END );//play end sound + ent->s.loopSound = 0; // stop looping sound + G_PlayDoorSound(ent, BMS_END); // play end sound - //Set the currentAngles, clear all movement - VectorMA( ent->s.apos.trBase, (ent->s.apos.trDuration*0.001f), ent->s.apos.trDelta, ent->currentAngles ); - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + // Set the currentAngles, clear all movement + VectorMA(ent->s.apos.trBase, (ent->s.apos.trDuration * 0.001f), ent->s.apos.trDelta, ent->currentAngles); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trDuration = 1; ent->s.apos.trType = TR_STATIONARY; ent->s.apos.trTime = level.time; - //Stop thinking + // Stop thinking ent->e_ReachedFunc = reachedF_NULL; - if ( ent->e_ThinkFunc == thinkF_anglerCallback ) - { + if (ent->e_ThinkFunc == thinkF_anglerCallback) { ent->e_ThinkFunc = thinkF_NULL; } - //link - gi.linkentity( ent ); + // link + gi.linkentity(ent); } /* @@ -1405,35 +1255,31 @@ moveAndRotateCallback Utility function ============= */ -void moveAndRotateCallback( gentity_t *ent ) -{ - //stop turning - anglerCallback( ent ); - //stop moving - moverCallback( ent ); +void moveAndRotateCallback(gentity_t *ent) { + // stop turning + anglerCallback(ent); + // stop moving + moverCallback(ent); } -void Blocked_Mover( gentity_t *ent, gentity_t *other ) { +void Blocked_Mover(gentity_t *ent, gentity_t *other) { // remove anything other than a client -- no longer the case // don't remove security keys or goodie keys - if ( (other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY) ) - { + if ((other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY)) { // should we be doing anything special if a key blocks it... move it somehow..? } // if your not a client, or your a dead client remove yourself... - else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message)) ) - { - if ( !IIcarusInterface::GetIcarus()->IsRunning( other->m_iIcarusID ) /*!other->taskManager || !other->taskManager->IsRunning()*/ ) - { + else if (other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message))) { + if (!IIcarusInterface::GetIcarus()->IsRunning(other->m_iIcarusID) /*!other->taskManager || !other->taskManager->IsRunning()*/) { // if an item or weapon can we do a little explosion..? - G_FreeEntity( other ); + G_FreeEntity(other); return; } } - if ( ent->damage ) { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } } @@ -1670,101 +1516,86 @@ Q3_Lerp2Origin Lerps the origin to the destination value ============= */ -static void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Lerp2Origin(int taskID, int entID, vec3_t origin, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); return; } - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } moverState_t moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); - if ( moverState == MOVER_POS1 ) - {//open the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qtrue ); + if (moverState == MOVER_POS1) { // open the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qtrue); } } moverState = MOVER_1TO2; - } - else if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 ) - { - VectorCopy( ent->currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + } else if (moverState == MOVER_POS2 || moverState == MOVER_1TO2) { + VectorCopy(ent->currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); //FIXME: This will probably break normal things that are being moved... + InitMoverTrData(ent); // FIXME: This will probably break normal things that are being moved... ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); - ent->e_ReachedFunc = reachedF_moverCallback; - if ( ent->damage ) - { + ent->e_ReachedFunc = reachedF_moverCallback; + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - if ( taskID != -1 ) - { - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + if (taskID != -1) { + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); } // starting sound - G_PlayDoorLoopSound( ent );//start looping sound - G_PlayDoorSound( ent, BMS_START ); //play start sound + G_PlayDoorLoopSound(ent); // start looping sound + G_PlayDoorSound(ent, BMS_START); // play start sound - gi.linkentity( ent ); + gi.linkentity(ent); } -static void Q3_SetOriginOffset( int entID, int axis, float offset ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOriginOffset(int entID, int axis, float offset) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); return; } - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); return; } vec3_t origin; - VectorCopy( ent->s.origin, origin ); + VectorCopy(ent->s.origin, origin); origin[axis] += offset; float duration = 0; - if ( ent->speed ) - { - duration = fabs(offset)/fabs(ent->speed)*1000.0f; + if (ent->speed) { + duration = fabs(offset) / fabs(ent->speed) * 1000.0f; } - Q3_Lerp2Origin( -1, entID, origin, duration ); + Q3_Lerp2Origin(-1, entID, origin, duration); } /* ============= @@ -1858,68 +1689,56 @@ Q3_SetNavGoal Sets the navigational goal of an entity ============= */ -static qboolean Q3_SetNavGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[ entID ]; - vec3_t goalPos; +static qboolean Q3_SetNavGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + vec3_t goalPos; - if ( !ent->health ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, ent->script_targetname ); + if (!ent->health) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, + ent->script_targetname); return qfalse; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, + ent->script_targetname); return qfalse; } - if ( !ent->NPC->tempGoal ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, + ent->script_targetname); return qfalse; } - if ( !ent->NPC->tempGoal->inuse ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal->inuse) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname); return qfalse; } - if( Q_stricmp( "null", name) == 0 - || Q_stricmp( "NULL", name) == 0 ) - { + if (Q_stricmp("null", name) == 0 || Q_stricmp("NULL", name) == 0) { ent->NPC->goalEntity = NULL; - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); + Q3_TaskIDComplete(ent, TID_MOVE_NAV); return qfalse; - } - else - { - //Get the position of the goal - if ( TAG_GetOrigin2( NULL, name, goalPos ) == false ) - { - gentity_t *targ = G_Find(NULL, FOFS(targetname), (char*)name); - if ( !targ ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name ); + } else { + // Get the position of the goal + if (TAG_GetOrigin2(NULL, name, goalPos) == false) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), (char *)name); + if (!targ) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name); return qfalse; - } - else - { + } else { ent->NPC->goalEntity = targ; - ent->NPC->goalRadius = sqrt(ent->maxs[0]+ent->maxs[0]) + sqrt(targ->maxs[0]+targ->maxs[0]); + ent->NPC->goalRadius = sqrt(ent->maxs[0] + ent->maxs[0]) + sqrt(targ->maxs[0] + targ->maxs[0]); ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; } - } - else - { - int goalRadius = TAG_GetRadius( NULL, name ); - NPC_SetMoveGoal( ent, goalPos, goalRadius, qtrue ); - //We know we want to clear the lastWaypoint here + } else { + int goalRadius = TAG_GetRadius(NULL, name); + NPC_SetMoveGoal(ent, goalPos, goalRadius, qtrue); + // We know we want to clear the lastWaypoint here ent->NPC->goalEntity->lastWaypoint = WAYPOINT_NONE; ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; - #ifdef _DEBUG - //this is *only* for debugging navigation - ent->NPC->tempGoal->target = G_NewString( name ); - #endif// _DEBUG - return qtrue; +#ifdef _DEBUG + // this is *only* for debugging navigation + ent->NPC->tempGoal->target = G_NewString(name); +#endif // _DEBUG + return qtrue; } } return qfalse; @@ -1936,26 +1755,22 @@ SetLowerAnim Argument : int animID ============ */ -static void SetLowerAnim( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetLowerAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - NPC_SetAnim(ent,SETANIM_LEGS,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(ent, SETANIM_LEGS, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); } - /* ============ SetUpperAnim @@ -1965,23 +1780,20 @@ SetUpperAnim Argument : int animID ============ */ -static void SetUpperAnim ( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetUpperAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - NPC_SetAnim(ent,SETANIM_TORSO,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(ent, SETANIM_TORSO, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); } //----------------------------------------------- @@ -1993,28 +1805,24 @@ Q3_SetAnimUpper Sets the upper animation of an entity ============= */ -static qboolean Q3_SetAnimUpper( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimUpper(int entID, const char *anim_name) { + int animID = 0; - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name); return qfalse; } - if ( !PM_HasAnimation( &g_entities[entID], animID ) ) - { + if (!PM_HasAnimation(&g_entities[entID], animID)) { return qfalse; } - SetUpperAnim( entID, animID ); + SetUpperAnim(entID, animID); return qtrue; } - /* ============= Q3_SetAnimLower @@ -2022,26 +1830,23 @@ Q3_SetAnimLower Sets the lower animation of an entity ============= */ -static qboolean Q3_SetAnimLower( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimLower(int entID, const char *anim_name) { + int animID = 0; - //FIXME: Setting duck anim does not actually duck! + // FIXME: Setting duck anim does not actually duck! - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name); return qfalse; } - if ( !PM_HasAnimation( &g_entities[entID], animID ) ) - { + if (!PM_HasAnimation(&g_entities[entID], animID)) { return qfalse; } - SetLowerAnim( entID, animID ); + SetLowerAnim(entID, animID); return qtrue; } @@ -2055,31 +1860,25 @@ Q3_SetAnimHoldTime Argument : qboolean lower ============ */ -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -static void Q3_SetAnimHoldTime( int entID, int int_data, qboolean lower ) -{ - gentity_t *ent = &g_entities[entID]; +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +static void Q3_SetAnimHoldTime(int entID, int int_data, qboolean lower) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimHoldTime: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimHoldTime: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetAnimHoldTime: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetAnimHoldTime: ent %d is NOT a player or NPC!\n", entID); return; } - if(lower) - { - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, int_data ); - } - else - { - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, int_data ); + if (lower) { + PM_SetLegsAnimTimer(ent, &ent->client->ps.legsAnimTimer, int_data); + } else { + PM_SetTorsoAnimTimer(ent, &ent->client->ps.torsoAnimTimer, int_data); } } @@ -2090,34 +1889,25 @@ Q3_SetEnemy Sets the enemy of an entity ============= */ -static void Q3_SetEnemy( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEnemy(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { - if(ent->NPC) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { + if (ent->NPC) { G_ClearEnemy(ent); - } - else - { + } else { ent->enemy = NULL; } - } - else - { - gentity_t *enemy = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *enemy = G_Find(NULL, FOFS(targetname), (char *)name); - if(enemy == NULL) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name ); + if (enemy == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name); return; } /*else if(enemy->health <= 0) @@ -2125,22 +1915,17 @@ static void Q3_SetEnemy( int entID, const char *name ) //Quake3Game()->DebugPrint( WL_ERROR, "Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; }*/ - else - { - if(ent->NPC) - { - G_SetEnemy( ent, enemy ); + else { + if (ent->NPC) { + G_SetEnemy(ent, enemy); ent->cantHitEnemyCounter = 0; - } - else - { + } else { G_SetEnemy(ent, enemy); } } } } - /* ============= Q3_SetLeader @@ -2148,57 +1933,40 @@ Q3_SetLeader Sets the leader of an NPC ============= */ -static void Q3_SetLeader( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLeader(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { ent->client->leader = NULL; - } - else - { - gentity_t *leader = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *leader = G_Find(NULL, FOFS(targetname), (char *)name); - if(leader == NULL) - { - //Quake3Game()->DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); + if (leader == NULL) { + // Quake3Game()->DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); return; - } - else if(leader->health <= 0) - { - //Quake3Game()->DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); + } else if (leader->health <= 0) { + // Quake3Game()->DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; - } - else - { + } else { ent->client->leader = leader; } } } -stringID_table_t teamTable [] = -{ - ENUM2STRING(TEAM_FREE), - ENUM2STRING(TEAM_PLAYER), - ENUM2STRING(TEAM_ENEMY), - ENUM2STRING(TEAM_NEUTRAL), - { "", TEAM_FREE }, +stringID_table_t teamTable[] = { + ENUM2STRING(TEAM_FREE), ENUM2STRING(TEAM_PLAYER), ENUM2STRING(TEAM_ENEMY), ENUM2STRING(TEAM_NEUTRAL), {"", TEAM_FREE}, }; - /* ============ Q3_SetPlayerTeam @@ -2208,28 +1976,24 @@ Q3_SetPlayerTeam Argument : const char *teamName ============ */ -static void Q3_SetPlayerTeam( int entID, const char *teamName ) -{ - gentity_t *ent = &g_entities[entID]; - team_t newTeam; +static void Q3_SetPlayerTeam(int entID, const char *teamName) { + gentity_t *ent = &g_entities[entID]; + team_t newTeam; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetPlayerTeam: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetPlayerTeam: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetPlayerTeam: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetPlayerTeam: ent %d is NOT a player or NPC!\n", entID); return; } - newTeam = (team_t)GetIDForString( teamTable, teamName ); + newTeam = (team_t)GetIDForString(teamTable, teamName); ent->client->playerTeam = newTeam; } - /* ============ Q3_SetEnemyTeam @@ -2239,26 +2003,22 @@ Q3_SetEnemyTeam Argument : const char *teamName ============ */ -static void Q3_SetEnemyTeam( int entID, const char *teamName ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEnemyTeam(int entID, const char *teamName) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEnemyTeam: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEnemyTeam: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetEnemyTeam: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetEnemyTeam: ent %d is NOT a player or NPC!\n", entID); return; } - ent->client->enemyTeam = (team_t)GetIDForString( teamTable, teamName ); + ent->client->enemyTeam = (team_t)GetIDForString(teamTable, teamName); } - /* ============ Q3_SetHealth @@ -2268,57 +2028,48 @@ Q3_SetHealth Argument : int data ============ */ -static void Q3_SetHealth( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHealth(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); return; } // FIXME : should we really let you set health on a dead guy? // this close to gold I won't change it, but warn you about it - if( ent->health <= 0 ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetHealth: trying to set health on a dead guy! %d\n", entID); + if (ent->health <= 0) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetHealth: trying to set health on a dead guy! %d\n", entID); } - if ( data < 0 ) - { + if (data < 0) { data = 0; } ent->health = data; // should adjust max if new health is higher than max - if ( ent->health > ent->max_health ) - { + if (ent->health > ent->max_health) { ent->max_health = ent->health; } - if(!ent->client) - { + if (!ent->client) { return; } ent->client->ps.stats[STAT_HEALTH] = data; - if ( ent->s.number == 0 ) - {//clamp health to max - if ( ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->s.number == 0) { // clamp health to max + if (ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_HEALTH] = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if ( data == 0 ) - {//artificially "killing" the player", don't let him respawn right away + if (data == 0) { // artificially "killing" the player", don't let him respawn right away ent->client->ps.pm_type = PM_DEAD; - //delay respawn for 2 seconds + // delay respawn for 2 seconds ent->client->respawnTime = level.time + 2000; - //stop all scripts + // stop all scripts stop_icarus = qtrue; - //make the team killable - //G_MakeTeamVulnerable(); + // make the team killable + // G_MakeTeamVulnerable(); } } } @@ -2332,26 +2083,21 @@ Q3_SetArmor Argument : int data ============ */ -static void Q3_SetArmor( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetArmor(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); return; } - if(!ent->client) - { + if (!ent->client) { return; } ent->client->ps.stats[STAT_ARMOR] = data; - if ( ent->s.number == 0 ) - {//clamp armor to max_health - if ( ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->s.number == 0) { // clamp armor to max_health + if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; } } @@ -2368,116 +2114,96 @@ FIXME: this should be a general NPC wrapper function that is called ANY time a bState is changed... ============ */ -static qboolean Q3_SetBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); return qtrue; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { - if ( bSID == BS_SEARCH || bSID == BS_WANDER ) - { - //FIXME: Reimplement + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { + if (bSID == BS_SEARCH || bSID == BS_WANDER) { + // FIXME: Reimplement - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); - } - else - { + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); + } else { ent->waypoint = NAV::GetNearestNode(ent); - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname ); + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname); return qtrue; } } } - - ent->NPC->tempBehavior = BS_DEFAULT;//need to clear any temp behaviour - if ( ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP ) - {//need to rise up out of the floor after noclipping + ent->NPC->tempBehavior = BS_DEFAULT; // need to clear any temp behaviour + if (ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP) { // need to rise up out of the floor after noclipping ent->currentOrigin[2] += 0.125; - G_SetOrigin( ent, ent->currentOrigin ); - gi.linkentity( ent ); + G_SetOrigin(ent, ent->currentOrigin); + gi.linkentity(ent); } ent->NPC->behaviorState = bSID; - if ( bSID == BS_DEFAULT ) - { + if (bSID == BS_DEFAULT) { ent->NPC->defaultBehavior = bSID; } } ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; -// if ( bSID == BS_FLY ) -// {//FIXME: need a set bState wrapper -// ent->client->moveType = MT_FLYSWIM; -// } -// else + // if ( bSID == BS_FLY ) + // {//FIXME: need a set bState wrapper + // ent->client->moveType = MT_FLYSWIM; + // } + // else { - //FIXME: these are presumptions! - //Q3_SetGravity( entID, g_gravity->value ); - //ent->client->moveType = MT_RUNJUMP; + // FIXME: these are presumptions! + // Q3_SetGravity( entID, g_gravity->value ); + // ent->client->moveType = MT_RUNJUMP; } - if ( bSID == BS_NOCLIP ) - { + if (bSID == BS_NOCLIP) { ent->client->noclip = true; - } - else - { + } else { ent->client->noclip = false; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -// if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) - if ( bSID == BS_ADVANCE_FIGHT ) - { - return qfalse;//need to wait for task complete message + // if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) + if (bSID == BS_ADVANCE_FIGHT) { + return qfalse; // need to wait for task complete message } -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - if ( bSID == BS_JUMP ) - { + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + if (bSID == BS_JUMP) { ent->NPC->jumpState = JS_FACING; } - return qtrue;//ok to complete + return qtrue; // ok to complete } - /* ============ Q3_SetTempBState @@ -2487,47 +2213,42 @@ Q3_SetTempBState Argument : const char *bs_name ============ */ -static qboolean Q3_SetTempBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetTempBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); return qtrue; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->tempBehavior = bSID; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - return qtrue;//ok to complete + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + return qtrue; // ok to complete } - /* ============ Q3_SetDefaultBState @@ -2537,31 +2258,26 @@ Q3_SetDefaultBState Argument : const char *bs_name ============ */ -static void Q3_SetDefaultBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static void Q3_SetDefaultBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname); return; } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->defaultBehavior = bSID; } } - /* ============ Q3_SetDPitch @@ -2571,40 +2287,32 @@ Q3_SetDPitch Argument : float data ============ */ -static void Q3_SetDPitch( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDPitch(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); return; } - if ( !ent->NPC || !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC || !ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname); return; } int pitchMin = -ent->client->renderInfo.headPitchRangeUp + 1; int pitchMax = ent->client->renderInfo.headPitchRangeDown - 1; - //clamp angle to -180 -> 180 - data = AngleNormalize180( data ); + // clamp angle to -180 -> 180 + data = AngleNormalize180(data); - //Clamp it to my valid range - if ( data < -1 ) - { - if ( data < pitchMin ) - { + // Clamp it to my valid range + if (data < -1) { + if (data < pitchMin) { data = pitchMin; } - } - else if ( data > 1 ) - { - if ( data > pitchMax ) - { + } else if (data > 1) { + if (data > pitchMax) { data = pitchMax; } } @@ -2612,7 +2320,6 @@ static void Q3_SetDPitch( int entID, float data ) ent->NPC->lockedDesiredPitch = ent->NPC->desiredPitch = data; } - /* ============ Q3_SetDYaw @@ -2622,33 +2329,26 @@ Q3_SetDYaw Argument : float data ============ */ -static void Q3_SetDYaw( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDYaw(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname); return; } - if(!ent->enemy) - {//don't mess with this if they're aiming at someone + if (!ent->enemy) { // don't mess with this if they're aiming at someone ent->NPC->lockedDesiredYaw = ent->NPC->desiredYaw = ent->s.angles[1] = data; - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname ); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname); } } - /* ============ Q3_SetShootDist @@ -2658,26 +2358,22 @@ Q3_SetShootDist Argument : float data ============ */ -static void Q3_SetShootDist( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShootDist(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.shootDistance = data; } - /* ============ Q3_SetVisrange @@ -2687,26 +2383,22 @@ Q3_SetVisrange Argument : float data ============ */ -static void Q3_SetVisrange( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVisrange(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.visrange = data; } - /* ============ Q3_SetEarshot @@ -2716,26 +2408,22 @@ Q3_SetEarshot Argument : float data ============ */ -static void Q3_SetEarshot( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEarshot(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.earshot = data; } - /* ============ Q3_SetVigilance @@ -2745,26 +2433,22 @@ Q3_SetVigilance Argument : float data ============ */ -static void Q3_SetVigilance( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVigilance(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vigilance = data; } - /* ============ Q3_SetVFOV @@ -2774,26 +2458,22 @@ Q3_SetVFOV Argument : int data ============ */ -static void Q3_SetVFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vfov = data; } - /* ============ Q3_SetHFOV @@ -2803,26 +2483,22 @@ Q3_SetHFOV Argument : int data ============ */ -static void Q3_SetHFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.hfov = data; } - /* ============ Q3_SetWidth @@ -2832,23 +2508,20 @@ Q3_SetWidth Argument : float data ============ */ -static void Q3_SetWidth( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetWidth(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWidth: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWidth: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWidth: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWidth: '%s' is not an NPC\n", ent->targetname); return; } - ent->maxs[0] = ent->maxs[1] = data; + ent->maxs[0] = ent->maxs[1] = data; ent->mins[0] = ent->mins[1] = -data; } @@ -2867,7 +2540,6 @@ Q3_GetTimeScale return g_timescale->value; }*/ - /* ============ Q3_SetTimeScale @@ -2877,18 +2549,15 @@ Q3_SetTimeScale Argument : const char *data ============ */ -static void Q3_SetTimeScale( int entID, const char *data ) -{ +static void Q3_SetTimeScale(int entID, const char *data) { // if we're skipping the script DO NOT allow timescale to be set (skipping needs it at 100) - if ( g_skippingcin->integer ) - { + if (g_skippingcin->integer) { return; } gi.cvar_set("timescale", data); } - /* ============ Q3_SetInvisible @@ -2898,30 +2567,23 @@ Q3_SetInvisible Argument : qboolean invisible ============ */ -static void Q3_SetInvisible( int entID, qboolean invisible ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetInvisible(int entID, qboolean invisible) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); return; } - if ( invisible ) - { + if (invisible) { self->s.eFlags |= EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags |= EF_NODRAW; } self->contents = 0; - } - else - { + } else { self->s.eFlags &= ~EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags &= ~EF_NODRAW; } } @@ -2936,22 +2598,17 @@ Q3_SetVampire Argument : qboolean vampire ============ */ -static void Q3_SetVampire( int entID, qboolean vampire ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetVampire(int entID, qboolean vampire) { + gentity_t *self = &g_entities[entID]; - if ( !self || !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetVampire: entID %d not a client\n", entID); + if (!self || !self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetVampire: entID %d not a client\n", entID); return; } - if ( vampire ) - { + if (vampire) { self->client->ps.powerups[PW_DISINT_2] = Q3_INFINITE; - } - else - { + } else { self->client->ps.powerups[PW_DISINT_2] = 0; } } @@ -2964,33 +2621,26 @@ Q3_SetGreetAllies Argument : qboolean greet ============ */ -static void Q3_SetGreetAllies( int entID, qboolean greet ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGreetAllies(int entID, qboolean greet) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname); return; } - if ( greet ) - { + if (greet) { self->NPC->aiFlags |= NPCAI_GREET_ALLIES; - } - else - { + } else { self->NPC->aiFlags &= ~NPCAI_GREET_ALLIES; } } - /* ============ Q3_SetViewTarget @@ -3000,57 +2650,48 @@ Q3_SetViewTarget Argument : const char *name ============ */ -static void Q3_SetViewTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *viewtarget = G_Find( NULL, FOFS(targetname), (char *) name); - vec3_t viewspot, selfspot, viewvec, viewangles; +static void Q3_SetViewTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *viewtarget = G_Find(NULL, FOFS(targetname), (char *)name); + vec3_t viewspot, selfspot, viewvec, viewangles; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname); return; } - //FIXME: Exception handle here - if (viewtarget == NULL) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name ); + // FIXME: Exception handle here + if (viewtarget == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name); return; } - //FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves - //around for a script-specified length of time...? - VectorCopy ( self->currentOrigin, selfspot ); + // FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves + // around for a script-specified length of time...? + VectorCopy(self->currentOrigin, selfspot); selfspot[2] += self->client->ps.viewheight; - if ( viewtarget->client && (!g_skippingcin || !g_skippingcin->integer ) ) - { - VectorCopy ( viewtarget->client->renderInfo.eyePoint, viewspot ); - } - else - { - VectorCopy ( viewtarget->currentOrigin, viewspot ); + if (viewtarget->client && (!g_skippingcin || !g_skippingcin->integer)) { + VectorCopy(viewtarget->client->renderInfo.eyePoint, viewspot); + } else { + VectorCopy(viewtarget->currentOrigin, viewspot); } - VectorSubtract( viewspot, selfspot, viewvec ); + VectorSubtract(viewspot, selfspot, viewvec); - vectoangles( viewvec, viewangles ); + vectoangles(viewvec, viewangles); - Q3_SetDYaw( entID, viewangles[YAW] ); - if ( !g_skippingcin || !g_skippingcin->integer ) - { - Q3_SetDPitch( entID, viewangles[PITCH] ); + Q3_SetDYaw(entID, viewangles[YAW]); + if (!g_skippingcin || !g_skippingcin->integer) { + Q3_SetDPitch(entID, viewangles[PITCH]); } } - /* ============ Q3_SetWatchTarget @@ -3060,88 +2701,70 @@ Q3_SetWatchTarget Argument : const char *name ============ */ -static void Q3_SetWatchTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *watchTarget = NULL; +static void Q3_SetWatchTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *watchTarget = NULL; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname); return; } - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name ) == 0 || ( self->targetname && (Q_stricmp( self->targetname, name ) == 0) ) ) - {//clearing watchTarget + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0 || (self->targetname && (Q_stricmp(self->targetname, name) == 0))) { // clearing + // watchTarget self->NPC->watchTarget = NULL; } - watchTarget = G_Find( NULL, FOFS(targetname), (char *) name); - if ( watchTarget == NULL ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name ); + watchTarget = G_Find(NULL, FOFS(targetname), (char *)name); + if (watchTarget == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name); return; } self->NPC->watchTarget = watchTarget; } -void Q3_SetLoopSound(int entID, const char *name) -{ - sfxHandle_t index; - gentity_t *self = &g_entities[entID]; +void Q3_SetLoopSound(int entID, const char *name) { + sfxHandle_t index; + gentity_t *self = &g_entities[entID]; - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name )==0) - { + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0) { self->s.loopSound = 0; return; } - if ( self->s.eType == ET_MOVER ) - { - index = cgi_S_RegisterSound( name ); - } - else - { - index = G_SoundIndex( name ); + if (self->s.eType == ET_MOVER) { + index = cgi_S_RegisterSound(name); + } else { + index = G_SoundIndex(name); } - if (index) - { + if (index) { self->s.loopSound = index; - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name ); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name); } } -void Q3_SetICARUSFreeze( int entID, const char *name, qboolean freeze ) -{ - gentity_t *self = G_Find( NULL, FOFS(targetname), name ); - if ( !self ) - {//hmm, targetname failed, try script_targetname? - self = G_Find( NULL, FOFS(script_targetname), name ); +void Q3_SetICARUSFreeze(int entID, const char *name, qboolean freeze) { + gentity_t *self = G_Find(NULL, FOFS(targetname), name); + if (!self) { // hmm, targetname failed, try script_targetname? + self = G_Find(NULL, FOFS(script_targetname), name); } - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); return; } - if ( freeze ) - { + if (freeze) { self->svFlags |= SVF_ICARUS_FREEZE; - } - else - { + } else { self->svFlags &= ~SVF_ICARUS_FREEZE; } } @@ -3155,44 +2778,38 @@ Q3_SetViewEntity Argument : const char *name ============ */ -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -void Q3_SetViewEntity(int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *viewtarget = G_Find( NULL, FOFS(targetname), (char *) name); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +void Q3_SetViewEntity(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *viewtarget = G_Find(NULL, FOFS(targetname), (char *)name); - if ( entID != 0 ) - {//only valid on player - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetViewEntity: only valid on player\n", entID); + if (entID != 0) { // only valid on player + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetViewEntity: only valid on player\n", entID); return; } - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetViewEntity: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetViewEntity: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetViewEntity: '%s' is not a player!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetViewEntity: '%s' is not a player!\n", self->targetname); return; } - if ( !name ) - { - G_ClearViewEntity( self ); + if (!name) { + G_ClearViewEntity(self); return; } - if ( viewtarget == NULL ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetViewEntity: can't find ViewEntity: '%s'\n", name ); + if (viewtarget == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetViewEntity: can't find ViewEntity: '%s'\n", name); return; } - G_SetViewEntity( self, viewtarget ); + G_SetViewEntity(self, viewtarget); } /* @@ -3204,107 +2821,89 @@ Q3_SetWeapon Argument : const char *wp_name ============ */ -extern gentity_t *TossClientItems( gentity_t *self ); -void G_SetWeapon( gentity_t *self, int wp ) -{ - qboolean hadWeapon = qfalse; +extern gentity_t *TossClientItems(gentity_t *self); +void G_SetWeapon(gentity_t *self, int wp) { + qboolean hadWeapon = qfalse; - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname); return; } - if ( self->NPC ) - {//since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore + if (self->NPC) { // since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore self->NPC->aiFlags &= ~NPCAI_MATCHPLAYERWEAPON; } - if(wp == WP_NONE) - {//no weapon + if (wp == WP_NONE) { // no weapon self->client->ps.weapon = WP_NONE; - G_RemoveWeaponModels( self ); - if ( self->s.number < MAX_CLIENTS ) - {//make sure the cgame-side knows this - CG_ChangeWeapon( wp ); + G_RemoveWeaponModels(self); + if (self->s.number < MAX_CLIENTS) { // make sure the cgame-side knows this + CG_ChangeWeapon(wp); } return; } - gitem_t *item = FindItemForWeapon( (weapon_t) wp); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup + gitem_t *item = FindItemForWeapon((weapon_t)wp); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup - if ( self->client->ps.stats[STAT_WEAPONS]&( 1 << wp ) ) - { + if (self->client->ps.stats[STAT_WEAPONS] & (1 << wp)) { hadWeapon = qtrue; } - if ( self->NPC ) - {//Should NPCs have only 1 weapon at a time? - self->client->ps.stats[STAT_WEAPONS] = ( 1 << wp ); + if (self->NPC) { // Should NPCs have only 1 weapon at a time? + self->client->ps.stats[STAT_WEAPONS] = (1 << wp); self->client->ps.ammo[weaponData[wp].ammoIndex] = 999; - ChangeWeapon( self, wp ); + ChangeWeapon(self, wp); self->client->ps.weapon = wp; - self->client->ps.weaponstate = WEAPON_READY;//WEAPON_RAISING; - G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - } - else - { - self->client->ps.stats[STAT_WEAPONS] |= ( 1 << wp ); + self->client->ps.weaponstate = WEAPON_READY; // WEAPON_RAISING; + G_AddEvent(self, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); + } else { + self->client->ps.stats[STAT_WEAPONS] |= (1 << wp); self->client->ps.ammo[weaponData[wp].ammoIndex] = ammoData[weaponData[wp].ammoIndex].max; - G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); - //force it to change - CG_ChangeWeapon( wp ); - G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + G_AddEvent(self, EV_ITEM_PICKUP, (item - bg_itemlist)); + // force it to change + CG_ChangeWeapon(wp); + G_AddEvent(self, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); } - G_RemoveWeaponModels( self ); + G_RemoveWeaponModels(self); - if ( wp == WP_SABER ) - { - if ( !hadWeapon ) - { - WP_SaberInitBladeData( self ); + if (wp == WP_SABER) { + if (!hadWeapon) { + WP_SaberInitBladeData(self); } - WP_SaberAddG2SaberModels( self ); - } - else - { - G_CreateG2AttachedWeaponModel( self, weaponData[wp].weaponMdl, self->handRBolt, 0 ); + WP_SaberAddG2SaberModels(self); + } else { + G_CreateG2AttachedWeaponModel(self, weaponData[wp].weaponMdl, self->handRBolt, 0); } } -static void Q3_SetWeapon (int entID, const char *wp_name) -{ - gentity_t *self = &g_entities[entID]; - int wp = GetIDForString( WPTable, wp_name ); +static void Q3_SetWeapon(int entID, const char *wp_name) { + gentity_t *self = &g_entities[entID]; + int wp = GetIDForString(WPTable, wp_name); - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname); return; } - if ( self->NPC ) - {//since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore + if (self->NPC) { // since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore self->NPC->aiFlags &= ~NPCAI_MATCHPLAYERWEAPON; } - if(!Q_stricmp("drop", wp_name)) - {//no weapon, drop it - TossClientItems( self ); + if (!Q_stricmp("drop", wp_name)) { // no weapon, drop it + TossClientItems(self); self->client->ps.weapon = WP_NONE; - G_RemoveWeaponModels( self ); + G_RemoveWeaponModels(self); return; } - G_SetWeapon( self, wp ); + G_SetWeapon(self, wp); } /* @@ -3316,48 +2915,40 @@ Q3_SetItem Argument : const char *wp_name ============ */ -static void Q3_SetItem (int entID, const char *item_name) -{ - gentity_t *self = &g_entities[entID]; - int inv; +static void Q3_SetItem(int entID, const char *item_name) { + gentity_t *self = &g_entities[entID]; + int inv; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname); return; } - inv = GetIDForString( INVTable, item_name ); - + inv = GetIDForString(INVTable, item_name); gitem_t *item = FindItemForInventory(inv); - RegisterItem( item ); //make sure the item is cached in case this runs at startup + RegisterItem(item); // make sure the item is cached in case this runs at startup -// G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); -// G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + // G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); + // G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - self->client->ps.stats[STAT_ITEMS] |= (1<giTag); + self->client->ps.stats[STAT_ITEMS] |= (1 << item->giTag); - if( (inv == INV_ELECTROBINOCULARS) || (inv == INV_LIGHTAMP_GOGGLES) ) - { + if ((inv == INV_ELECTROBINOCULARS) || (inv == INV_LIGHTAMP_GOGGLES)) { self->client->ps.inventory[inv] = 1; return; } // else Bacta, seeker, sentry - if( self->client->ps.inventory[inv] < 5 ) - { + if (self->client->ps.inventory[inv] < 5) { self->client->ps.inventory[inv]++; } } - - /* ============ Q3_SetWalkSpeed @@ -3367,31 +2958,26 @@ Q3_SetWalkSpeed Argument : int int_data ============ */ -static void Q3_SetWalkSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWalkSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.walkSpeed = self->client->ps.speed = 1; } self->NPC->stats.walkSpeed = self->client->ps.speed = int_data; } - /* ============ Q3_SetRunSpeed @@ -3401,31 +2987,26 @@ Q3_SetRunSpeed Argument : int int_data ============ */ -static void Q3_SetRunSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRunSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.runSpeed = self->client->ps.speed = 1; } self->NPC->stats.runSpeed = self->client->ps.speed = int_data; } - /* ============ Q3_SetYawSpeed @@ -3435,26 +3016,22 @@ Q3_SetYawSpeed Argument : float float_data ============ */ -static void Q3_SetYawSpeed (int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetYawSpeed(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->stats.yawSpeed = float_data; } - /* ============ Q3_SetAggression @@ -3464,30 +3041,25 @@ Q3_SetAggression Argument : int int_data ============ */ -static void Q3_SetAggression(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; - +static void Q3_SetAggression(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aggression = int_data; } - /* ============ Q3_SetAim @@ -3497,29 +3069,25 @@ Q3_SetAim Argument : int int_data ============ */ -static void Q3_SetAim(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetAim(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aim = int_data; } - /* ============ Q3_SetFriction @@ -3529,26 +3097,22 @@ Q3_SetFriction Argument : int int_data ============ */ -static void Q3_SetFriction(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFriction(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname); return; } self->client->ps.friction = int_data; } - /* ============ Q3_SetGravity @@ -3558,28 +3122,24 @@ Q3_SetGravity Argument : float float_data ============ */ -static void Q3_SetGravity(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGravity(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname); return; } - //FIXME: what if we want to return them to normal global gravity? + // FIXME: what if we want to return them to normal global gravity? self->svFlags |= SVF_CUSTOM_GRAVITY; self->client->ps.gravity = float_data; } - /* ============ Q3_SetWait @@ -3589,33 +3149,27 @@ Q3_SetWait Argument : float float_data ============ */ -static void Q3_SetWait(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWait(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); return; } self->wait = float_data; } +static void Q3_SetShotSpacing(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; -static void Q3_SetShotSpacing(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; - - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname); return; } @@ -3632,26 +3186,22 @@ Q3_SetFollowDist Argument : float float_data ============ */ -static void Q3_SetFollowDist(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFollowDist(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); return; } - if ( !self->client || !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname ); + if (!self->client || !self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->followDist = float_data; } - /* ============ Q3_SetScale @@ -3661,20 +3211,17 @@ Q3_SetScale Argument : float float_data ============ */ -static void Q3_SetScale(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetScale(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); return; } self->s.scale = float_data; } - /* ============ Q3_SetRenderCullRadius @@ -3684,20 +3231,17 @@ Q3_SetRenderCullRadius Argument : float float_data (the new radius for render culling) ============ */ -static void Q3_SetRenderCullRadius(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRenderCullRadius(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetRenderCullRadius: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetRenderCullRadius: invalid entID %d\n", entID); return; } self->s.radius = float_data; } - /* ============ Q3_SetCount @@ -3707,29 +3251,23 @@ Q3_SetCount Argument : const char *data ============ */ -static void Q3_SetCount(int entID, const char *data) -{ - gentity_t *self = &g_entities[entID]; - float val = 0.0f; +static void Q3_SetCount(int entID, const char *data) { + gentity_t *self = &g_entities[entID]; + float val = 0.0f; - //FIXME: use FOFS() stuff here to make a generic entity field setting? - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); + // FIXME: use FOFS() stuff here to make a generic entity field setting? + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); return; } - if ( (val = Q3_CheckStringCounterIncrement( data )) ) - { + if ((val = Q3_CheckStringCounterIncrement(data))) { self->count += (int)(val); - } - else - { - self->count = atoi((char *) data); + } else { + self->count = atoi((char *)data); } } - /* ============ Q3_SetSquadName @@ -3776,27 +3314,21 @@ Q3_SetTargetName Argument : const char *targetname ============ */ -static void Q3_SetTargetName (int entID, const char *targetname) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTargetName(int entID, const char *targetname) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)targetname))) - { + if (!Q_stricmp("NULL", ((char *)targetname))) { self->targetname = NULL; - } - else - { - self->targetname = G_NewString( targetname ); + } else { + self->targetname = G_NewString(targetname); } } - /* ============ Q3_SetTarget @@ -3806,23 +3338,18 @@ Q3_SetTarget Argument : const char *target ============ */ -static void Q3_SetTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)target))) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target = NULL; - } - else - { - self->target = G_NewString( target ); + } else { + self->target = G_NewString(target); } } @@ -3835,23 +3362,18 @@ Q3_SetTarget2 Argument : const char *target ============ */ -static void Q3_SetTarget2 (int entID, const char *target2) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTarget2(int entID, const char *target2) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetTarget2: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetTarget2: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)target2))) - { + if (!Q_stricmp("NULL", ((char *)target2))) { self->target2 = NULL; - } - else - { - self->target2 = G_NewString( target2 ); + } else { + self->target2 = G_NewString(target2); } } /* @@ -3863,33 +3385,26 @@ Q3_SetRemoveTarget Argument : const char *target ============ */ -static void Q3_SetRemoveTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRemoveTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname); return; } - if( !Q_stricmp("NULL", ((char *)target)) ) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target3 = NULL; - } - else - { - self->target3 = G_NewString( target ); + } else { + self->target3 = G_NewString(target); } } - /* ============ Q3_SetPainTarget @@ -3899,147 +3414,117 @@ Q3_SetPainTarget Argument : const char *targetname ============ */ -static void Q3_SetPainTarget (int entID, const char *targetname) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetPainTarget(int entID, const char *targetname) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetPainTarget: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetPainTarget: invalid entID %d\n", entID); return; } - if(Q_stricmp("NULL", ((char *)targetname)) == 0) - { + if (Q_stricmp("NULL", ((char *)targetname)) == 0) { self->paintarget = NULL; - } - else - { + } else { self->paintarget = G_NewString((char *)targetname); } } -static void Q3_SetMusicState( const char *dms ) -{ - int newDMS = GetIDForString( DMSTable, dms ); - if ( newDMS != -1 ) - { +static void Q3_SetMusicState(const char *dms) { + int newDMS = GetIDForString(DMSTable, dms); + if (newDMS != -1) { level.dmState = newDMS; } } -static void Q3_SetForcePowerLevel ( int entID, int forcePower, int forceLevel ) -{ - if ( forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, (NUM_FORCE_POWERS-1) ); +static void Q3_SetForcePowerLevel(int entID, int forcePower, int forceLevel) { + if (forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, + (NUM_FORCE_POWERS - 1)); return; } - if ( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS ) - { - if ( forcePower != FP_SABER_OFFENSE || forceLevel >= SS_NUM_SABER_STYLES ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel ); + if (forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS) { + if (forcePower != FP_SABER_OFFENSE || forceLevel >= SS_NUM_SABER_STYLES) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel); return; } } - gentity_t *self = &g_entities[entID]; + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname); return; } - if ((forceLevel > self->client->ps.forcePowerLevel[forcePower]) && (entID==0) && (forceLevel > 0)) - { - if (0) - { - if (!cg_updatedDataPadForcePower1.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower1.integer = forcePower+1; - } - else if (!cg_updatedDataPadForcePower2.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower2", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower2.integer = forcePower+1; - } - else if (!cg_updatedDataPadForcePower3.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower3", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower3.integer = forcePower+1; + if ((forceLevel > self->client->ps.forcePowerLevel[forcePower]) && (entID == 0) && (forceLevel > 0)) { + if (0) { + if (!cg_updatedDataPadForcePower1.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower1", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower1.integer = forcePower + 1; + } else if (!cg_updatedDataPadForcePower2.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower2", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower2.integer = forcePower + 1; + } else if (!cg_updatedDataPadForcePower3.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower3", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower3.integer = forcePower + 1; } } } self->client->ps.forcePowerLevel[forcePower] = forceLevel; - if ( forceLevel ) - { - self->client->ps.forcePowersKnown |= ( 1 << forcePower ); - } - else - { - self->client->ps.forcePowersKnown &= ~( 1 << forcePower ); + if (forceLevel) { + self->client->ps.forcePowersKnown |= (1 << forcePower); + } else { + self->client->ps.forcePowersKnown &= ~(1 << forcePower); } } -extern qboolean G_InventorySelectable( int index,gentity_t *other); -static void Q3_GiveSecurityKey( int entID, char *keyname ) -{ - gentity_t *other = &g_entities[entID]; - int i, original; +extern qboolean G_InventorySelectable(int index, gentity_t *other); +static void Q3_GiveSecurityKey(int entID, char *keyname) { + gentity_t *other = &g_entities[entID]; + int i, original; - if ( !other ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_GiveSecurityKey: invalid entID %d\n", entID); + if (!other) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_GiveSecurityKey: invalid entID %d\n", entID); return; } - if ( !other->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_GiveSecurityKey: ent %s is not a player or NPC\n", other->targetname ); + if (!other->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_GiveSecurityKey: ent %s is not a player or NPC\n", other->targetname); return; } - if ( !keyname || !keyname[0] || !Q_stricmp( "none", keyname ) || !Q_stricmp( "null", keyname ) ) - {//remove the key - if ( other->message ) - {//remove it - INV_SecurityKeyTake( other, other->message ); + if (!keyname || !keyname[0] || !Q_stricmp("none", keyname) || !Q_stricmp("null", keyname)) { // remove the key + if (other->message) { // remove it + INV_SecurityKeyTake(other, other->message); } return; } - other->client->ps.stats[STAT_ITEMS] |= (1<client->ps.stats[STAT_ITEMS] |= (1 << INV_SECURITY_KEY); - //give the key - gi.SendServerCommand( 0, "cp @SP_INGAME_YOU_TOOK_SECURITY_KEY" ); - INV_SecurityKeyGive( other, keyname ); + // give the key + gi.SendServerCommand(0, "cp @SP_INGAME_YOU_TOOK_SECURITY_KEY"); + INV_SecurityKeyGive(other, keyname); // Got a security key // Set the inventory select, just in case it hasn't original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + for (i = 0; i < INV_MAX; i++) { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = (INV_MAX - 1); } - if ( G_InventorySelectable( cg.inventorySelect,other ) ) - { + if (G_InventorySelectable(cg.inventorySelect, other)) { return; } cg.inventorySelect++; @@ -4058,49 +3543,39 @@ Q3_SetParm Argument : const char *parmValue ============ */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue) -{ - gentity_t *ent = &g_entities[entID]; - float val; +void Q3_SetParm(int entID, int parmNum, const char *parmValue) { + gentity_t *ent = &g_entities[entID]; + float val; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); return; } - if ( parmNum < 0 || parmNum >= MAX_PARMS ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum ); + if (parmNum < 0 || parmNum >= MAX_PARMS) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum); return; } - if( !ent->parms ) - { - ent->parms = (parms_t *)G_Alloc( sizeof(parms_t) ); - memset( ent->parms, 0, sizeof(parms_t) ); + if (!ent->parms) { + ent->parms = (parms_t *)G_Alloc(sizeof(parms_t)); + memset(ent->parms, 0, sizeof(parms_t)); } - if ( (val = Q3_CheckStringCounterIncrement( parmValue )) ) - { - val += atof( ent->parms->parm[parmNum] ); - Com_sprintf( ent->parms->parm[parmNum], sizeof(ent->parms->parm[parmNum]), "%f", val ); - } - else - {//Just copy the string - //copy only 16 characters - strncpy( ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[parmNum]) ); - //set the last character to null in case we had to truncate their passed string - if ( ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] != 0 ) - {//Tried to set a string that is too long + if ((val = Q3_CheckStringCounterIncrement(parmValue))) { + val += atof(ent->parms->parm[parmNum]); + Com_sprintf(ent->parms->parm[parmNum], sizeof(ent->parms->parm[parmNum]), "%f", val); + } else { // Just copy the string + // copy only 16 characters + strncpy(ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[parmNum])); + // set the last character to null in case we had to truncate their passed string + if (ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] != 0) { // Tried to set a string that is too long ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] = 0; - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum] ); + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum]); } } } - - /* ============= Q3_SetCaptureGoal @@ -4108,32 +3583,27 @@ Q3_SetCaptureGoal Sets the capture spot goal of an entity ============= */ -static void Q3_SetCaptureGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *goal = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCaptureGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *goal = G_Find(NULL, FOFS(targetname), (char *)name); - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname); return; } - //FIXME: Exception handle here - if (goal == NULL) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name ); + // FIXME: Exception handle here + if (goal == NULL) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name); return; } - if(ent->NPC) - { + if (ent->NPC) { ent->NPC->captureGoal = goal; ent->NPC->goalEntity = goal; ent->NPC->goalTime = level.time + 100000; @@ -4147,43 +3617,40 @@ Q3_SetEvent ? ============= */ -static void Q3_SetEvent( int entID, const char *event_name ) -{ - gentity_t *ent = &g_entities[entID]; -// gentity_t *tent = NULL; - int event; -// vec3_t spot; +static void Q3_SetEvent(int entID, const char *event_name) { + gentity_t *ent = &g_entities[entID]; + // gentity_t *tent = NULL; + int event; + // vec3_t spot; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEvent: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEvent: invalid entID %d\n", entID); return; } - event = GetIDForString( eventTable, event_name ); - switch( event ) - { -/* - case EV_DISINTEGRATE: - if( VectorCompare( ent->currentOrigin, vec3_origin ) ) - {//Brush with no origin - VectorSubtract( ent->absmax, ent->absmin, spot ); - VectorMA( ent->absmin, 0.5, spot, spot ); - } - else - { - VectorCopy( ent->currentOrigin, spot ); - spot[2] += ent->maxs[2]/2; - } - tent = G_TempEntity( spot, EV_DISINTEGRATION ); - tent->s.eventParm = PW_REGEN; - tent->owner = ent; - break; - -*/ + event = GetIDForString(eventTable, event_name); + switch (event) { + /* + case EV_DISINTEGRATE: + if( VectorCompare( ent->currentOrigin, vec3_origin ) ) + {//Brush with no origin + VectorSubtract( ent->absmax, ent->absmin, spot ); + VectorMA( ent->absmin, 0.5, spot, spot ); + } + else + { + VectorCopy( ent->currentOrigin, spot ); + spot[2] += ent->maxs[2]/2; + } + tent = G_TempEntity( spot, EV_DISINTEGRATION ); + tent->s.eventParm = PW_REGEN; + tent->owner = ent; + break; + + */ case EV_BAD: default: - //Quake3Game()->DebugPrint( IGameInterface::WL_ERROR,"Q3_SetEvent: Invalid Event %d\n", event ); + // Quake3Game()->DebugPrint( IGameInterface::WL_ERROR,"Q3_SetEvent: Invalid Event %d\n", event ); return; break; } @@ -4215,7 +3682,6 @@ Uses an entity G_UseTargets2(ent, ent, target); }*/ - /* ============ Q3_SetBehaviorSet @@ -4223,19 +3689,16 @@ Q3_SetBehaviorSet ? ============ */ -static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) -{ - gentity_t *ent = &g_entities[entID]; - bSet_t bSet = BSET_INVALID; +static qboolean Q3_SetBehaviorSet(int entID, int toSet, const char *scriptname) { + gentity_t *ent = &g_entities[entID]; + bSet_t bSet = BSET_INVALID; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); return qfalse; } - switch(toSet) - { + switch (toSet) { case SET_SPAWNSCRIPT: bSet = BSET_SPAWN; break; @@ -4283,35 +3746,28 @@ static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) break; } - if(bSet < BSET_SPAWN || bSet >= NUM_BSETS) - { + if (bSet < BSET_SPAWN || bSet >= NUM_BSETS) { return qfalse; } - if(!Q_stricmp("NULL", scriptname)) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// gi.TagFree( ent->behaviorSet[bSet] ); + if (!Q_stricmp("NULL", scriptname)) { + if (ent->behaviorSet[bSet] != NULL) { + // gi.TagFree( ent->behaviorSet[bSet] ); } ent->behaviorSet[bSet] = NULL; - //memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); - } - else - { - if ( scriptname ) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// gi.TagFree( ent->behaviorSet[bSet] ); + // memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); + } else { + if (scriptname) { + if (ent->behaviorSet[bSet] != NULL) { + // gi.TagFree( ent->behaviorSet[bSet] ); } - ent->behaviorSet[bSet] = G_NewString( (char *) scriptname ); //FIXME: This really isn't good... + ent->behaviorSet[bSet] = G_NewString((char *)scriptname); // FIXME: This really isn't good... } - //ent->behaviorSet[bSet] = scriptname; - //strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); + // ent->behaviorSet[bSet] = scriptname; + // strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); } return qtrue; } @@ -4323,20 +3779,17 @@ Q3_SetDelayScriptTime ? ============ */ -static void Q3_SetDelayScriptTime(int entID, int delayTime) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDelayScriptTime(int entID, int delayTime) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDelayScriptTime: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDelayScriptTime: invalid entID %d\n", entID); return; } ent->delayScriptTime = level.time + delayTime; } - /* ============ Q3_SetIgnorePain @@ -4344,19 +3797,16 @@ Q3_SetIgnorePain ? ============ */ -static void Q3_SetIgnorePain( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnorePain(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname); return; } @@ -4370,28 +3820,22 @@ Q3_SetIgnoreEnemies ? ============ */ -static void Q3_SetIgnoreEnemies( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnoreEnemies(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetIgnoreEnemies: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetIgnoreEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetIgnoreEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetIgnoreEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(data) - { + if (data) { ent->svFlags |= SVF_IGNORE_ENEMIES; - } - else - { + } else { ent->svFlags &= ~SVF_IGNORE_ENEMIES; } } @@ -4403,33 +3847,26 @@ Q3_SetIgnoreAlerts ? ============ */ -static void Q3_SetIgnoreAlerts( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnoreAlerts(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname); return; } - if(data) - { + if (data) { ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_IGNORE_ALERTS; } } - /* ============ Q3_SetNoTarget @@ -4437,17 +3874,15 @@ Q3_SetNoTarget ? ============ */ -static void Q3_SetNoTarget( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoTarget(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); return; } - if(data) + if (data) ent->flags |= FL_NOTARGET; else ent->flags &= ~FL_NOTARGET; @@ -4460,22 +3895,17 @@ Q3_SetDontShoot ? ============ */ -static void Q3_SetDontShoot( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontShoot(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); return; } - if(add) - { + if (add) { ent->flags |= FL_DONT_SHOOT; - } - else - { + } else { ent->flags &= ~FL_DONT_SHOOT; } } @@ -4487,28 +3917,22 @@ Q3_SetDontFire ? ============ */ -static void Q3_SetDontFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FIRE; } } @@ -4520,28 +3944,22 @@ Q3_SetFireWeapon ? ============ */ -static void Q3_SetFireWeapon(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFireWeapon(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FIRE_WEAPON; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FIRE_WEAPON; } } @@ -4553,28 +3971,22 @@ Q3_SetFireWeaponNoAnim ? ============ */ -static void Q3_SetFireWeaponNoAnim(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFireWeaponNoAnim(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_FireWeaponNoAnim: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_FireWeaponNoAnim: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetFireWeaponNoAnim: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetFireWeaponNoAnim: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FIRE_WEAPON_NO_ANIM; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FIRE_WEAPON_NO_ANIM; } } @@ -4586,28 +3998,22 @@ Q3_SetSafeRemove If true, NPC will remove itself once player is not in PVS ============ */ -static void Q3_SetSafeRemove(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetSafeRemove(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetSafeRemove: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetSafeRemove: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetSafeRemove: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetSafeRemove: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_SAFE_REMOVE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_SAFE_REMOVE; } } @@ -4619,58 +4025,46 @@ Q3_SetBobaJetPack Turn on/off Boba's jet pack ============ */ -static void Q3_SetBobaJetPack(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetBobaJetPack(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetBobaJetPack: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetBobaJetPack: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetBobaJetPack: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetBobaJetPack: '%s' is not an NPC!\n", ent->targetname); return; } // make sure we this is Boba Fett - if ( ent->client && ent->client->NPC_class != CLASS_BOBAFETT ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetBobaJetPack: '%s' is not Boba Fett!\n", ent->targetname ); + if (ent->client && ent->client->NPC_class != CLASS_BOBAFETT) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetBobaJetPack: '%s' is not Boba Fett!\n", ent->targetname); return; } - if(add) - { - if ( ent->genericBolt1 != -1 ) - { - G_PlayEffect( G_EffectIndex( "boba/jetSP" ), ent->playerModel, ent->genericBolt1, ent->s.number, ent->currentOrigin, qtrue, qtrue ); + if (add) { + if (ent->genericBolt1 != -1) { + G_PlayEffect(G_EffectIndex("boba/jetSP"), ent->playerModel, ent->genericBolt1, ent->s.number, ent->currentOrigin, qtrue, qtrue); } - if ( ent->genericBolt2 != -1 ) - { - G_PlayEffect( G_EffectIndex( "boba/jetSP" ), ent->playerModel, ent->genericBolt2, ent->s.number, ent->currentOrigin, qtrue, qtrue ); + if (ent->genericBolt2 != -1) { + G_PlayEffect(G_EffectIndex("boba/jetSP"), ent->playerModel, ent->genericBolt2, ent->s.number, ent->currentOrigin, qtrue, qtrue); } - //take-off sound - G_SoundOnEnt( ent, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav" ); - //jet loop sound - ent->s.loopSound = G_SoundIndex( "sound/chars/boba/bf_jetpack_lp.wav" ); - } - else - { - if ( ent->genericBolt1 != -1 ) - { - G_StopEffect( "boba/jetSP", ent->playerModel, ent->genericBolt1, ent->s.number ); + // take-off sound + G_SoundOnEnt(ent, CHAN_ITEM, "sound/chars/boba/bf_blast-off.wav"); + // jet loop sound + ent->s.loopSound = G_SoundIndex("sound/chars/boba/bf_jetpack_lp.wav"); + } else { + if (ent->genericBolt1 != -1) { + G_StopEffect("boba/jetSP", ent->playerModel, ent->genericBolt1, ent->s.number); } - if ( ent->genericBolt2 != -1 ) - { - G_StopEffect( "boba/jetSP", ent->playerModel, ent->genericBolt2, ent->s.number ); + if (ent->genericBolt2 != -1) { + G_StopEffect("boba/jetSP", ent->playerModel, ent->genericBolt2, ent->s.number); } - //stop jet loop sound + // stop jet loop sound ent->s.loopSound = 0; - G_SoundOnEnt( ent, CHAN_ITEM, "sound/chars/boba/bf_land.wav" ); - + G_SoundOnEnt(ent, CHAN_ITEM, "sound/chars/boba/bf_land.wav"); } } /* @@ -4680,22 +4074,17 @@ Q3_SetInactive ? ============ */ -static void Q3_SetInactive(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInactive(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); return; } - if(add) - { + if (add) { ent->svFlags |= SVF_INACTIVE; - } - else - { + } else { ent->svFlags &= ~SVF_INACTIVE; } } @@ -4707,26 +4096,21 @@ Q3_SetFuncUsableVisible ? ============ */ -static void Q3_SetFuncUsableVisible(int entID, qboolean visible ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFuncUsableVisible(int entID, qboolean visible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); return; } // Yeah, I know that this doesn't even do half of what the func_usable use code does, but if I've got two things on top of each other...and only // one is visible at a time....and neither can ever be used......and finally, the shader on it has the shader_anim stuff going on....It doesn't seem // like I can easily use the other version without nasty side effects. - if( visible ) - { + if (visible) { ent->svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; - } - else - { + } else { ent->svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; } @@ -4739,29 +4123,23 @@ Q3_SetLockedEnemy ? ============ */ -static void Q3_SetLockedEnemy ( int entID, qboolean locked) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLockedEnemy(int entID, qboolean locked) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLockedEnemy: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLockedEnemy: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetLockedEnemy: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetLockedEnemy: '%s' is not an NPC!\n", ent->targetname); return; } - //FIXME: make an NPCAI_FLAG - if(locked) - { + // FIXME: make an NPCAI_FLAG + if (locked) { ent->svFlags |= SVF_LOCKEDENEMY; - } - else - { + } else { ent->svFlags &= ~SVF_LOCKEDENEMY; } } @@ -4774,18 +4152,13 @@ Q3_SetCinematicSkipScript ============ */ -static void Q3_SetCinematicSkipScript( char *scriptname ) -{ +static void Q3_SetCinematicSkipScript(char *scriptname) { - if(Q_stricmp("none", scriptname) == 0 || Q_stricmp("NULL", scriptname) == 0) - { + if (Q_stricmp("none", scriptname) == 0 || Q_stricmp("NULL", scriptname) == 0) { cinematicSkipScript[0] = 0; + } else { + Q_strncpyz(cinematicSkipScript, scriptname, sizeof(cinematicSkipScript)); } - else - { - Q_strncpyz(cinematicSkipScript,scriptname,sizeof(cinematicSkipScript)); - } - } /* @@ -4795,33 +4168,26 @@ Q3_SetNoMindTrick ? ============ */ -static void Q3_SetNoMindTrick( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoMindTrick(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoMindTrick: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoMindTrick: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoMindTrick: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoMindTrick: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_MIND_TRICK; ent->NPC->confusionTime = 0; - if ( ent->ghoul2.size() && ent->headBolt != -1 ) - { - G_StopEffect("force/confusion", ent->playerModel, ent->headBolt, ent->s.number ); + if (ent->ghoul2.size() && ent->headBolt != -1) { + G_StopEffect("force/confusion", ent->playerModel, ent->headBolt, ent->s.number); } - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_MIND_TRICK; } } @@ -4833,28 +4199,22 @@ Q3_SetCrouched ? ============ */ -static void Q3_SetCrouched( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetCrouched(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CROUCHED; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CROUCHED; } } @@ -4866,28 +4226,22 @@ Q3_SetWalking ? ============ */ -static void Q3_SetWalking( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetWalking(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_WALKING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_WALKING; } } @@ -4899,28 +4253,22 @@ Q3_SetRunning ? ============ */ -static void Q3_SetRunning( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRunning(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_RUNNING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_RUNNING; } } @@ -4932,28 +4280,22 @@ Q3_SetForcedMarch ? ============ */ -static void Q3_SetForcedMarch( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForcedMarch(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FORCED_MARCH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FORCED_MARCH; } } @@ -4964,28 +4306,22 @@ Q3_SetChaseEnemies indicates whether the npc should chase after an enemy ============ */ -static void Q3_SetChaseEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetChaseEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CHASE_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CHASE_ENEMIES; } } @@ -4998,28 +4334,22 @@ if set npc will be on the look out for potential enemies if not set, npc will ignore enemies ============ */ -static void Q3_SetLookForEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLookForEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_LOOK_FOR_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; } } @@ -5030,28 +4360,22 @@ Q3_SetFaceMoveDir ============ */ -static void Q3_SetFaceMoveDir( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFaceMoveDir(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FACE_MOVE_DIR; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FACE_MOVE_DIR; } } @@ -5063,33 +4387,26 @@ Q3_SetAltFire ? ============ */ -static void Q3_SetAltFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAltFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_ALT_FIRE; } - ChangeWeapon( ent, ent->client->ps.weapon ); - + ChangeWeapon(ent, ent->client->ps.weapon); } /* @@ -5099,28 +4416,22 @@ Q3_SetDontFlee ? ============ */ -static void Q3_SetDontFlee( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFlee(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FLEE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FLEE; } } @@ -5132,28 +4443,22 @@ Q3_SetNoResponse ? ============ */ -static void Q3_SetNoResponse( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoResponse(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_RESPONSE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_RESPONSE; } } @@ -5165,28 +4470,22 @@ Q3_SetCombatTalk ? ============ */ -static void Q3_SetCombatTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetCombatTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; } } @@ -5198,28 +4497,22 @@ Q3_SetAlertTalk ? ============ */ -static void Q3_SetAlertTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAlertTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ALERT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ALERT_TALK; } } @@ -5231,28 +4524,22 @@ Q3_SetUseCpNearest ? ============ */ -static void Q3_SetUseCpNearest( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUseCpNearest(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_USE_CP_NEAREST; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_USE_CP_NEAREST; } } @@ -5264,28 +4551,22 @@ Q3_SetNoForce ? ============ */ -static void Q3_SetNoForce( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoForce(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FORCE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FORCE; } } @@ -5297,28 +4578,22 @@ Q3_SetNoAcrobatics ? ============ */ -static void Q3_SetNoAcrobatics( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAcrobatics(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ACROBATICS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ACROBATICS; } } @@ -5330,28 +4605,22 @@ Q3_SetUseSubtitles ? ============ */ -static void Q3_SetUseSubtitles( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUseSubtitles(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetUseSubtitles: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetUseSubtitles: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetUseSubtitles: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetUseSubtitles: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_USE_SUBTITLES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_USE_SUBTITLES; } } @@ -5363,28 +4632,22 @@ Q3_SetNoFallToDeath ? ============ */ -static void Q3_SetNoFallToDeath( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoFallToDeath(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FALLTODEATH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FALLTODEATH; } } @@ -5396,26 +4659,22 @@ Q3_SetDismemberable ? ============ */ -static void Q3_SetDismemberable( int entID, qboolean dismemberable) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDismemberable(int entID, qboolean dismemberable) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDismemberable: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDismemberable: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetDismemberable: '%s' is not an client!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetDismemberable: '%s' is not an client!\n", ent->targetname); return; } ent->client->dismembered = !dismemberable; } - /* ============ Q3_SetMoreLight @@ -5423,28 +4682,22 @@ Q3_SetMoreLight ? ============ */ -static void Q3_SetMoreLight( int entID, qboolean add ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetMoreLight(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetMoreLight: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetMoreLight: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetMoreLight: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetMoreLight: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_MORELIGHT; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_MORELIGHT; } } @@ -5456,22 +4709,17 @@ Q3_SetUndying ? ============ */ -static void Q3_SetUndying( int entID, qboolean undying) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUndying(int entID, qboolean undying) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); return; } - if(undying) - { + if (undying) { ent->flags |= FL_UNDYING; - } - else - { + } else { ent->flags &= ~FL_UNDYING; } } @@ -5483,35 +4731,26 @@ Q3_SetInvincible ? ============ */ -static void Q3_SetInvincible( int entID, qboolean invincible) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInvincible(int entID, qboolean invincible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); return; } - - if ( !Q_stricmp( "func_breakable", ent->classname ) ) - { - if ( invincible ) - { - ent->spawnflags |= 1; - } - else - { + + if (!Q_stricmp("func_breakable", ent->classname)) { + if (invincible) { + ent->spawnflags |= 1; + } else { ent->spawnflags &= ~1; } return; } - if ( invincible ) - { + if (invincible) { ent->flags |= FL_GODMODE; - } - else - { + } else { ent->flags &= ~FL_GODMODE; } } @@ -5524,23 +4763,18 @@ Q3_SetForceInvincible Argument : qboolean forceInv ============ */ -static void Q3_SetForceInvincible( int entID, qboolean forceInv ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetForceInvincible(int entID, qboolean forceInv) { + gentity_t *self = &g_entities[entID]; - if ( !self || !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetForceInvincible: entID %d not a client\n", entID); + if (!self || !self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetForceInvincible: entID %d not a client\n", entID); return; } - Q3_SetInvincible( entID, forceInv ); - if ( forceInv ) - { + Q3_SetInvincible(entID, forceInv); + if (forceInv) { self->client->ps.powerups[PW_INVINCIBLE] = Q3_INFINITE; - } - else - { + } else { self->client->ps.powerups[PW_INVINCIBLE] = 0; } } @@ -5552,28 +4786,22 @@ Q3_SetNoAvoid ? ============ */ -static void Q3_SetNoAvoid( int entID, qboolean noAvoid) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAvoid(int entID, qboolean noAvoid) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname); return; } - if(noAvoid) - { + if (noAvoid) { ent->NPC->aiFlags |= NPCAI_NO_COLL_AVOID; - } - else - { + } else { ent->NPC->aiFlags &= ~NPCAI_NO_COLL_AVOID; } } @@ -5586,34 +4814,27 @@ SolidifyOwner Argument : gentity_t *self ============ */ -void SolidifyOwner( gentity_t *self ) -{ +void SolidifyOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } int oldContents = self->owner->contents; self->owner->contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( self->owner, self->owner->currentOrigin ) ) - { + if (SpotWouldTelefrag2(self->owner, self->owner->currentOrigin)) { self->owner->contents = oldContents; self->e_ThinkFunc = thinkF_SolidifyOwner; - } - else - { - if ( self->owner->NPC && !(self->owner->spawnflags & SFB_NOTSOLID) ) - { + } else { + if (self->owner->NPC && !(self->owner->spawnflags & SFB_NOTSOLID)) { self->owner->clipmask |= CONTENTS_BODY; } - Q3_TaskIDComplete( self->owner, TID_RESIZE ); + Q3_TaskIDComplete(self->owner, TID_RESIZE); } } - /* ============ Q3_SetSolid @@ -5621,22 +4842,18 @@ Q3_SetSolid ? ============ */ -static qboolean Q3_SetSolid( int entID, qboolean solid) -{ - gentity_t *ent = &g_entities[entID]; +static qboolean Q3_SetSolid(int entID, qboolean solid) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); return qtrue; } - if ( solid ) - {//FIXME: Presumption + if (solid) { // FIXME: Presumption int oldContents = ent->contents; ent->contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( ent, ent->currentOrigin ) ) - { + if (SpotWouldTelefrag2(ent, ent->currentOrigin)) { gentity_t *solidifier = G_Spawn(); solidifier->owner = ent; @@ -5648,21 +4865,14 @@ static qboolean Q3_SetSolid( int entID, qboolean solid) return qfalse; } ent->clipmask |= CONTENTS_BODY; - } - else - {//FIXME: Presumption - if ( ent->s.eFlags & EF_NODRAW ) - {//We're invisible too, so set contents to none + } else { // FIXME: Presumption + if (ent->s.eFlags & EF_NODRAW) { // We're invisible too, so set contents to none ent->contents = 0; - } - else - { + } else { ent->contents = CONTENTS_CORPSE; } - if ( ent->NPC ) - { - if(!(ent->spawnflags & SFB_NOTSOLID)) - { + if (ent->NPC) { + if (!(ent->spawnflags & SFB_NOTSOLID)) { ent->clipmask &= ~CONTENTS_BODY; } } @@ -5676,37 +4886,29 @@ Q3_SetLean ? ============ */ -#define LEAN_NONE 0 -#define LEAN_RIGHT 1 -#define LEAN_LEFT 2 -static void Q3_SetLean( int entID, int lean) -{ - gentity_t *ent = &g_entities[entID]; +#define LEAN_NONE 0 +#define LEAN_RIGHT 1 +#define LEAN_LEFT 2 +static void Q3_SetLean(int entID, int lean) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLean: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLean: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetLean: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetLean: '%s' is not an NPC!\n", ent->targetname); return; } - if(lean == LEAN_RIGHT) - { + if (lean == LEAN_RIGHT) { ent->NPC->scriptFlags |= SCF_LEAN_RIGHT; ent->NPC->scriptFlags &= ~SCF_LEAN_LEFT; - } - else if(lean == LEAN_LEFT) - { + } else if (lean == LEAN_LEFT) { ent->NPC->scriptFlags |= SCF_LEAN_LEFT; ent->NPC->scriptFlags &= ~SCF_LEAN_RIGHT; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_LEAN_LEFT; ent->NPC->scriptFlags &= ~SCF_LEAN_RIGHT; } @@ -5719,19 +4921,16 @@ Q3_SetForwardMove ? ============ */ -static void Q3_SetForwardMove( int entID, int fmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForwardMove(int entID, int fmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname); return; } @@ -5745,19 +4944,16 @@ Q3_SetRightMove ? ============ */ -static void Q3_SetRightMove( int entID, int rmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRightMove(int entID, int rmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname); return; } @@ -5771,57 +4967,42 @@ Q3_SetLockAngle ? ============ */ -static void Q3_SetLockAngle( int entID, const char *lockAngle) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLockAngle(int entID, const char *lockAngle) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname); return; } - if(Q_stricmp("off", lockAngle) == 0) - {//free it + if (Q_stricmp("off", lockAngle) == 0) { // free it ent->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; - } - else - { + } else { ent->client->renderInfo.renderFlags |= RF_LOCKEDANGLE; - - if(Q_stricmp("auto", lockAngle) == 0) - {//use current yaw - if( ent->NPC ) // I need this to work on NPCs, so their locked value - { - ent->NPC->lockedDesiredYaw = NPC->client->ps.viewangles[YAW]; // could also set s.angles[1] and desiredYaw to this value... - } - else + if (Q_stricmp("auto", lockAngle) == 0) { // use current yaw + if (ent->NPC) // I need this to work on NPCs, so their locked value { + ent->NPC->lockedDesiredYaw = NPC->client->ps.viewangles[YAW]; // could also set s.angles[1] and desiredYaw to this value... + } else { ent->client->renderInfo.lockYaw = ent->client->ps.viewangles[YAW]; } - } - else - {//specified yaw - if( ent->NPC ) // I need this to work on NPCs, so their locked value + } else { // specified yaw + if (ent->NPC) // I need this to work on NPCs, so their locked value { ent->NPC->lockedDesiredYaw = atof((char *)lockAngle); // could also set s.angles[1] and desiredYaw to this value... - } - else - { + } else { ent->client->renderInfo.lockYaw = atof((char *)lockAngle); } } } } - /* ============ Q3_CameraGroup @@ -5829,20 +5010,18 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroup( int entID, char *camG) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_CameraGroup(int entID, char *camG) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_CameraGroup: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_CameraGroup: invalid entID %d\n", entID); return; } ent->cameraGroup = G_NewString(camG); } -extern camera_t client_camera; +extern camera_t client_camera; /* ============ Q3_CameraGroupZOfs @@ -5850,10 +5029,7 @@ Q3_CameraGroupZOfs ? ============ */ -static void Q3_CameraGroupZOfs( float camGZOfs ) -{ - client_camera.cameraGroupZOfs = camGZOfs; -} +static void Q3_CameraGroupZOfs(float camGZOfs) { client_camera.cameraGroupZOfs = camGZOfs; } /* ============ Q3_CameraGroup @@ -5861,23 +5037,18 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroupTag( char *camGTag ) -{ - Q_strncpyz( client_camera.cameraGroupTag, camGTag, sizeof(client_camera.cameraGroupTag) ); -} +static void Q3_CameraGroupTag(char *camGTag) { Q_strncpyz(client_camera.cameraGroupTag, camGTag, sizeof(client_camera.cameraGroupTag)); } /* ============ Q3_RemoveRHandModel ============ */ -static void Q3_RemoveRHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_RemoveRHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - if ( ent->cinematicModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model(ent->ghoul2,ent->cinematicModel); + if (ent->cinematicModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->cinematicModel); } } @@ -5886,16 +5057,13 @@ static void Q3_RemoveRHandModel( int entID, char *addModel) Q3_AddRHandModel ============ */ -static void Q3_AddRHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_AddRHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex( addModel ), 0, 0, 0, 0); - if ( ent->cinematicModel != -1 ) - { + ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex(addModel), 0, 0, 0, 0); + if (ent->cinematicModel != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], - ent->handRBolt, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], ent->handRBolt, ent->playerModel); } } @@ -5904,16 +5072,13 @@ static void Q3_AddRHandModel( int entID, char *addModel) Q3_AddLHandModel ============ */ -static void Q3_AddLHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_AddLHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex( addModel ), 0, 0, 0, 0); - if ( ent->cinematicModel != -1 ) - { + ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex(addModel), 0, 0, 0, 0); + if (ent->cinematicModel != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], - ent->handLBolt, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], ent->handLBolt, ent->playerModel); } } @@ -5922,12 +5087,10 @@ static void Q3_AddLHandModel( int entID, char *addModel) Q3_RemoveLHandModel ============ */ -static void Q3_RemoveLHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_RemoveLHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - if ( ent->cinematicModel >= 0 ) - { + if (ent->cinematicModel >= 0) { gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->cinematicModel); } } @@ -5939,44 +5102,37 @@ Q3_LookTarget ? ============ */ -static void Q3_LookTarget( int entID, char *targetName) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_LookTarget(int entID, char *targetName) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname); return; } - if(Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) - {//clearing look target - NPC_ClearLookTarget( ent ); + if (Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) { // clearing look target + NPC_ClearLookTarget(ent); return; } - gentity_t *targ = G_Find(NULL, FOFS(targetname), targetName); - if(!targ) - { - targ = G_Find(NULL, FOFS(script_targetname), targetName); - if (!targ) - { - targ = G_Find(NULL, FOFS(NPC_targetname), targetName); - if (!targ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName ); + gentity_t *targ = G_Find(NULL, FOFS(targetname), targetName); + if (!targ) { + targ = G_Find(NULL, FOFS(script_targetname), targetName); + if (!targ) { + targ = G_Find(NULL, FOFS(NPC_targetname), targetName); + if (!targ) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName); return; } } } - NPC_SetLookTarget( ent, targ->s.number, 0 ); + NPC_SetLookTarget(ent, targ->s.number, 0); } /* @@ -5986,27 +5142,23 @@ Q3_Face ? ============ */ -static void Q3_Face( int entID,int expression, float holdtime) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Face(int entID, int expression, float holdtime) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_Face: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_Face: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_Face: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_Face: '%s' is not an NPC/player!\n", ent->targetname); return; } - //FIXME: change to milliseconds to be consistant! + // FIXME: change to milliseconds to be consistant! holdtime *= 1000; - switch(expression) - { + switch (expression) { case SET_FACEEYESCLOSED: ent->client->facial_blink = 1; break; @@ -6022,13 +5174,13 @@ static void Q3_Face( int entID,int expression, float holdtime) break; case SET_FACEBLINKFROWN: ent->client->facial_blink = -(level.time + holdtime); -//fall through + // fall through case SET_FACEFROWN: ent->client->facial_timer = -(level.time + holdtime); ent->client->facial_anim = FACE_FROWN; break; - //Extra facial expressions: + // Extra facial expressions: case SET_FACESMILE: ent->client->facial_blink = -(level.time + holdtime); ent->client->facial_timer = -(level.time + holdtime); @@ -6055,10 +5207,8 @@ static void Q3_Face( int entID,int expression, float holdtime) ent->client->facial_blink = level.time + Q_flrand(3000.0, 5000.0); break; } - } - /* ============ Q3_SetPlayerUsable @@ -6068,22 +5218,17 @@ Q3_SetPlayerUsable Argument : qboolean usable ============ */ -static void Q3_SetPlayerUsable( int entID, qboolean usable ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetPlayerUsable(int entID, qboolean usable) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); return; } - if(usable) - { + if (usable) { ent->svFlags |= SVF_PLAYER_USABLE; - } - else - { + } else { ent->svFlags &= ~SVF_PLAYER_USABLE; } } @@ -6097,22 +5242,17 @@ Q3_SetDisableShaderAnims Argument : int disabled ============ */ -static void Q3_SetDisableShaderAnims( int entID, int disabled ) -{ +static void Q3_SetDisableShaderAnims(int entID, int disabled) { gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetDisableShaderAnims: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetDisableShaderAnims: invalid entID %d\n", entID); return; } - if ( disabled ) - { + if (disabled) { ent->s.eFlags |= EF_DISABLE_SHADER_ANIM; - } - else - { + } else { ent->s.eFlags &= ~EF_DISABLE_SHADER_ANIM; } } @@ -6126,59 +5266,44 @@ Q3_SetShaderAnim Argument : int disabled ============ */ -static void Q3_SetShaderAnim( int entID, int disabled ) -{ +static void Q3_SetShaderAnim(int entID, int disabled) { gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetShaderAnim: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetShaderAnim: invalid entID %d\n", entID); return; } - if ( disabled ) - { + if (disabled) { ent->s.eFlags |= EF_SHADER_ANIM; - } - else - { + } else { ent->s.eFlags &= ~EF_SHADER_ANIM; } } -void Q3_SetBroadcast( int entID, qboolean broadcast ) -{ +void Q3_SetBroadcast(int entID, qboolean broadcast) { gentity_t *ent = &g_entities[entID]; - if ( broadcast ) - { + if (broadcast) { ent->svFlags |= SVF_BROADCAST; - } - else - { + } else { ent->svFlags &= ~SVF_BROADCAST; } } -void Q3_SetForcePower( int entID, int forcePower, qboolean powerOn ) -{ +void Q3_SetForcePower(int entID, int forcePower, qboolean powerOn) { gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetForcePower: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetForcePower: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetForcePower: ent # %d not a client!\n", entID ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetForcePower: ent # %d not a client!\n", entID); return; } - if ( powerOn ) - { - ent->client->ps.forcePowersForced |= (1<client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced |= (1 << forcePower); + } else { + ent->client->ps.forcePowersForced &= ~(1 << forcePower); } } @@ -6191,30 +5316,25 @@ Q3_SetStartFrame Argument : int startFrame ============ */ -static void Q3_SetStartFrame( int entID, int startFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetStartFrame(int entID, int startFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetStartFrame: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetStartFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n" ); + if (ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n"); return; } - if ( startFrame >= 0 ) - { + if (startFrame >= 0) { ent->s.frame = startFrame; ent->startFrame = startFrame; } } - /* ============ Q3_SetEndFrame @@ -6224,24 +5344,20 @@ Q3_SetEndFrame Argument : int endFrame ============ */ -static void Q3_SetEndFrame( int entID, int endFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEndFrame(int entID, int endFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEndFrame: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEndFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetEndFrame: command not valid on players/NPCs!\n" ); + if (ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetEndFrame: command not valid on players/NPCs!\n"); return; } - if ( endFrame >= 0 ) - { + if (endFrame >= 0) { ent->endFrame = endFrame; } } @@ -6255,68 +5371,56 @@ Q3_SetAnimFrame Argument : int startFrame ============ */ -static void Q3_SetAnimFrame( int entID, int animFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAnimFrame(int entID, int animFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimFrame: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimFrame: command not valid on players/NPCs!\n" ); + if (ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimFrame: command not valid on players/NPCs!\n"); return; } - if ( animFrame >= ent->endFrame ) - { + if (animFrame >= ent->endFrame) { ent->s.frame = ent->endFrame; - } - else if ( animFrame >= ent->startFrame ) - { + } else if (animFrame >= ent->startFrame) { ent->s.frame = animFrame; - } - else - { + } else { // FIXME/NOTE: Set s.frame anyway?? - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetAnimFrame: value must be valid number between StartFrame and EndFrame.\n" ); + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetAnimFrame: value must be valid number between StartFrame and EndFrame.\n"); return; } } -void InflateOwner( gentity_t *self ) -{ +void InflateOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } - trace_t trace; + trace_t trace; - gi.trace( &trace, self->currentOrigin, self->mins, self->maxs, self->currentOrigin, self->owner->s.number, self->owner->clipmask&~(CONTENTS_SOLID|CONTENTS_MONSTERCLIP), (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid ) - { + gi.trace(&trace, self->currentOrigin, self->mins, self->maxs, self->currentOrigin, self->owner->s.number, + self->owner->clipmask & ~(CONTENTS_SOLID | CONTENTS_MONSTERCLIP), (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid) { self->e_ThinkFunc = thinkF_InflateOwner; return; } - if ( Q3_TaskIDPending( self->owner, TID_RESIZE ) ) - { - Q3_TaskIDComplete( self->owner, TID_RESIZE ); + if (Q3_TaskIDPending(self->owner, TID_RESIZE)) { + Q3_TaskIDComplete(self->owner, TID_RESIZE); - VectorCopy( self->mins, self->owner->mins ); - VectorCopy( self->maxs, self->owner->maxs ); - gi.linkentity( self->owner ); + VectorCopy(self->mins, self->owner->mins); + VectorCopy(self->maxs, self->owner->maxs); + gi.linkentity(self->owner); } } - /* ============ Q3_SetLoopAnim @@ -6326,26 +5430,22 @@ Q3_SetLoopAnim Argument : qboolean loopAnim ============ */ -static void Q3_SetLoopAnim( int entID, qboolean loopAnim ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLoopAnim(int entID, qboolean loopAnim) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLoopAnim: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLoopAnim: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n" ); + if (ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n"); return; } ent->loopAnim = loopAnim; } - /* ============ Q3_SetShields @@ -6355,28 +5455,22 @@ Q3_SetShields Argument : qboolean shields ============ */ -static void Q3_SetShields( int entID, qboolean shields ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShields(int entID, qboolean shields) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetShields: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetShields: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetShields: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetShields: '%s' is not an NPC!\n", ent->targetname); return; } - if ( shields ) - { + if (shields) { ent->NPC->aiFlags |= NPCAI_SHIELDS; - } - else - { + } else { ent->NPC->aiFlags &= ~NPCAI_SHIELDS; } } @@ -6390,54 +5484,41 @@ Q3_SetSaberActive Argument : qboolean shields ============ */ -static void Q3_SetSaberActive( int entID, qboolean active ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetSaberActive(int entID, qboolean active) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetSaberActive: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetSaberActive: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetSaberActive: '%s' is not an player/NPC!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetSaberActive: '%s' is not an player/NPC!\n", ent->targetname); return; } - if ( ent->client->ps.weapon != WP_SABER ) - { - if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<NPC ) - { - ChangeWeapon( ent, WP_SABER ); - } - else - { - gitem_t *item = FindItemForWeapon( WP_SABER ); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup - G_AddEvent( ent, EV_ITEM_PICKUP, (item - bg_itemlist) ); - CG_ChangeWeapon( WP_SABER ); + if (ent->client->ps.weapon != WP_SABER) { + if ((ent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER))) { // change to it right now + if (ent->NPC) { + ChangeWeapon(ent, WP_SABER); + } else { + gitem_t *item = FindItemForWeapon(WP_SABER); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup + G_AddEvent(ent, EV_ITEM_PICKUP, (item - bg_itemlist)); + CG_ChangeWeapon(WP_SABER); } ent->client->ps.weapon = WP_SABER; ent->client->ps.weaponstate = WEAPON_READY; - G_AddEvent( ent, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetSaberActive: '%s' is not using a saber!\n", ent->targetname ); + G_AddEvent(ent, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetSaberActive: '%s' is not using a saber!\n", ent->targetname); return; } } - if ( active ) - { + if (active) { ent->client->ps.SaberActivate(); - } - else - { + } else { ent->client->ps.SaberDeactivate(); } } @@ -6454,50 +5535,40 @@ static void Q3_SetSaberActive( int entID, qboolean active ) [return] void ============ */ -static void Q3_SetSaberBladeActive( int entID, int iSaber, int iBlade, qboolean bActive = qtrue ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetSaberBladeActive(int entID, int iSaber, int iBlade, qboolean bActive = qtrue) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetSaberBladeActive: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetSaberBladeActive: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetSaberBladeActive: '%s' is not an player/NPC!\n", ent->targetname ); + if (!ent->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetSaberBladeActive: '%s' is not an player/NPC!\n", ent->targetname); return; } - if ( ent->client->ps.weapon != WP_SABER ) - { - if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<NPC ) - { - ChangeWeapon( ent, WP_SABER ); - } - else - { - gitem_t *item = FindItemForWeapon( WP_SABER ); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup - G_AddEvent( ent, EV_ITEM_PICKUP, (item - bg_itemlist) ); - CG_ChangeWeapon( WP_SABER ); + if (ent->client->ps.weapon != WP_SABER) { + if ((ent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER))) { // change to it right now + if (ent->NPC) { + ChangeWeapon(ent, WP_SABER); + } else { + gitem_t *item = FindItemForWeapon(WP_SABER); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup + G_AddEvent(ent, EV_ITEM_PICKUP, (item - bg_itemlist)); + CG_ChangeWeapon(WP_SABER); } ent->client->ps.weapon = WP_SABER; ent->client->ps.weaponstate = WEAPON_READY; - G_AddEvent( ent, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_SetSaberBladeActive: '%s' is not using a saber!\n", ent->targetname ); + G_AddEvent(ent, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_SetSaberBladeActive: '%s' is not using a saber!\n", ent->targetname); return; } } // Activate the Blade. - ent->client->ps.SaberBladeActivate( iSaber, iBlade, bActive ); + ent->client->ps.SaberBladeActivate(iSaber, iBlade, bActive); } /* @@ -6509,22 +5580,17 @@ Q3_SetNoKnockback Argument : qboolean noKnockback ============ */ -static void Q3_SetNoKnockback( int entID, qboolean noKnockback ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoKnockback(int entID, qboolean noKnockback) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); return; } - if ( noKnockback ) - { + if (noKnockback) { ent->flags |= FL_NO_KNOCKBACK; - } - else - { + } else { ent->flags &= ~FL_NO_KNOCKBACK; } } @@ -6536,41 +5602,31 @@ Q3_SetCleanDamagingEnts Return type : void ============ */ -static void Q3_SetCleanDamagingEnts( void ) -{ +static void Q3_SetCleanDamagingEnts(void) { gentity_t *ent = NULL; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { - if ( !PInUse( i )) - { + for (int i = 0; i < ENTITYNUM_WORLD; i++) { + if (!PInUse(i)) { continue; } ent = &g_entities[i]; - if ( ent ) - { - if ( !ent->client && ( ent->s.weapon == WP_DET_PACK || ent->s.weapon == WP_TRIP_MINE || ent->s.weapon == WP_THERMAL )) - { + if (ent) { + if (!ent->client && (ent->s.weapon == WP_DET_PACK || ent->s.weapon == WP_TRIP_MINE || ent->s.weapon == WP_THERMAL)) { // check for a client, otherwise we could remove someone holding this weapon - G_FreeEntity( ent ); - } - else if ( ent->s.weapon == WP_TURRET && ent->activator && ent->activator->s.number == 0 && !Q_stricmp( "PAS", ent->classname )) - { + G_FreeEntity(ent); + } else if (ent->s.weapon == WP_TURRET && ent->activator && ent->activator->s.number == 0 && !Q_stricmp("PAS", ent->classname)) { // is a player owner personal assault sentry gun. - G_FreeEntity( ent ); - } - else if ( ent->client && ent->client->NPC_class == CLASS_SEEKER ) - { + G_FreeEntity(ent); + } else if (ent->client && ent->client->NPC_class == CLASS_SEEKER) { // they blow up when they run out of ammo, so this may as well just do the same. - G_Damage( ent, ent, ent, NULL, NULL, 999, 0, MOD_UNKNOWN ); + G_Damage(ent, ent, ent, NULL, NULL, 999, 0, MOD_UNKNOWN); } } } } - /* ============ Q3_SetInterface @@ -6580,10 +5636,7 @@ Q3_SetInterface Argument : const char *data ============ */ -static void Q3_SetInterface( int entID, const char *data ) -{ - gi.cvar_set("cg_drawStatus", data); -} +static void Q3_SetInterface(int entID, const char *data) { gi.cvar_set("cg_drawStatus", data); } /* ============ @@ -6594,23 +5647,20 @@ Q3_SetLocation Argument : const char *location ============ */ -static qboolean Q3_SetLocation( int entID, const char *location ) -{ - gentity_t *ent = &g_entities[entID]; - char *currentLoc; +static qboolean Q3_SetLocation(int entID, const char *location) { + gentity_t *ent = &g_entities[entID]; + char *currentLoc; - if ( !ent ) - { + if (!ent) { return qtrue; } - currentLoc = G_GetLocationForEnt( ent ); - if ( currentLoc && currentLoc[0] && Q_stricmp( location, currentLoc ) == 0 ) - { + currentLoc = G_GetLocationForEnt(ent); + if (currentLoc && currentLoc[0] && Q_stricmp(location, currentLoc) == 0) { return qtrue; } - ent->message = G_NewString( location ); + ent->message = G_NewString(location); return qfalse; } @@ -6623,14 +5673,12 @@ Q3_SetPlayerLocked Argument : qboolean locked ============ */ -qboolean player_locked = qfalse; -static void Q3_SetPlayerLocked( int entID, qboolean locked ) -{ - gentity_t *ent = &g_entities[0]; +qboolean player_locked = qfalse; +static void Q3_SetPlayerLocked(int entID, qboolean locked) { + gentity_t *ent = &g_entities[0]; player_locked = locked; - if ( ent && ent->client ) - {//stop him too + if (ent && ent->client) { // stop him too VectorClear(ent->client->ps.velocity); } } @@ -6644,20 +5692,16 @@ Q3_SetLockPlayerWeapons Argument : qboolean locked ============ */ -static void Q3_SetLockPlayerWeapons( int entID, qboolean locked ) -{ - gentity_t *ent = &g_entities[0]; +static void Q3_SetLockPlayerWeapons(int entID, qboolean locked) { + gentity_t *ent = &g_entities[0]; ent->flags &= ~FL_LOCK_PLAYER_WEAPONS; - if( locked ) - { + if (locked) { ent->flags |= FL_LOCK_PLAYER_WEAPONS; } - } - /* ============ Q3_SetNoImpactDamage @@ -6667,27 +5711,23 @@ Q3_SetNoImpactDamage Argument : qboolean locked ============ */ -static void Q3_SetNoImpactDamage( int entID, qboolean noImp ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoImpactDamage(int entID, qboolean noImp) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_SetNoImpactDamage: invalid entID %d\n", entID); + if (!ent) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_SetNoImpactDamage: invalid entID %d\n", entID); return; } ent->flags &= ~FL_NO_IMPACT_DMG; - if( noImp ) - { + if (noImp) { ent->flags |= FL_NO_IMPACT_DMG; } - } -extern void CG_CameraAutoAim( const char *name ); -extern void CG_CameraAutoTrack( const char *name ); +extern void CG_CameraAutoAim(const char *name); +extern void CG_CameraAutoTrack(const char *name); /* ============ @@ -6748,24 +5788,19 @@ Q3_RemoveEnt Argument : gentity_t *victim ============ */ -static void Q3_RemoveEnt( gentity_t *victim ) -{ - if (!victim || !victim->inuse) - { +static void Q3_RemoveEnt(gentity_t *victim) { + if (!victim || !victim->inuse) { return; } - if( victim->client ) - { - if ( victim->client->NPC_class == CLASS_VEHICLE ) - {//eject everyone out of a vehicle that's about to remove itself + if (victim->client) { + if (victim->client->NPC_class == CLASS_VEHICLE) { // eject everyone out of a vehicle that's about to remove itself Vehicle_t *pVeh = victim->m_pVehicle; - if ( pVeh && pVeh->m_pVehicleInfo ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); + if (pVeh && pVeh->m_pVehicleInfo) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); } } - //ClientDisconnect(ent); + // ClientDisconnect(ent); victim->s.eFlags |= EF_NODRAW; victim->svFlags &= ~SVF_NPC; victim->s.eType = ET_INVISIBLE; @@ -6773,26 +5808,21 @@ static void Q3_RemoveEnt( gentity_t *victim ) victim->health = 0; victim->targetname = NULL; - if ( victim->NPC && victim->NPC->tempGoal != NULL ) - { - G_FreeEntity( victim->NPC->tempGoal ); + if (victim->NPC && victim->NPC->tempGoal != NULL) { + G_FreeEntity(victim->NPC->tempGoal); victim->NPC->tempGoal = NULL; } - if ( victim->client->ps.saberEntityNum != ENTITYNUM_NONE && victim->client->ps.saberEntityNum > 0 ) - { - if ( g_entities[victim->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[victim->client->ps.saberEntityNum] ); + if (victim->client->ps.saberEntityNum != ENTITYNUM_NONE && victim->client->ps.saberEntityNum > 0) { + if (g_entities[victim->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[victim->client->ps.saberEntityNum]); } victim->client->ps.saberEntityNum = ENTITYNUM_NONE; } - //Disappear in half a second + // Disappear in half a second victim->e_ThinkFunc = thinkF_G_FreeEntity; victim->nextthink = level.time + 500; return; - } - else - { + } else { victim->e_ThinkFunc = thinkF_G_FreeEntity; victim->nextthink = level.time + 100; } @@ -6806,19 +5836,16 @@ MakeOwnerInvis Argument : gentity_t *self ============ */ -void MakeOwnerInvis(gentity_t *self) -{ - if(self->owner && self->owner->client) - { +void MakeOwnerInvis(gentity_t *self) { + if (self->owner && self->owner->client) { self->owner->client->ps.powerups[PW_CLOAKED] = level.time + 500; } - //HACKHGACLHACK!! - MCG + // HACKHGACLHACK!! - MCG self->e_ThinkFunc = thinkF_RemoveOwner; self->nextthink = level.time + 400; } - /* ============ MakeOwnerEnergy @@ -6827,11 +5854,9 @@ MakeOwnerEnergy Argument : gentity_t *self ============ */ -void MakeOwnerEnergy(gentity_t *self) -{ - if(self->owner && self->owner->client) - { -// self->owner->client->ps.powerups[PW_QUAD] = level.time + 1000; +void MakeOwnerEnergy(gentity_t *self) { + if (self->owner && self->owner->client) { + // self->owner->client->ps.powerups[PW_QUAD] = level.time + 1000; } G_FreeEntity(self); @@ -6849,44 +5874,34 @@ Q3_Remove Argument : const char *name ============ */ -static void Q3_Remove( int entID, const char *name ) -{ +static void Q3_Remove(int entID, const char *name) { gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; + gentity_t *victim = NULL; - if( !Q_stricmp( "self", name ) ) - { + if (!Q_stricmp("self", name)) { victim = ent; - if ( !victim ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else if( !Q_stricmp( "enemy", name ) ) - { + Q3_RemoveEnt(victim); + } else if (!Q_stricmp("enemy", name)) { victim = ent->enemy; - if ( !victim ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else - { - victim = G_Find( NULL, FOFS(targetname), (char *) name ); - if ( !victim ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name ); + Q3_RemoveEnt(victim); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); + if (!victim) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - while ( victim ) - { - Q3_RemoveEnt( victim ); - victim = G_Find( victim, FOFS(targetname), (char *) name ); + while (victim) { + Q3_RemoveEnt(victim); + victim = G_Find(victim, FOFS(targetname), (char *)name); } } } @@ -6899,83 +5914,75 @@ RemoveOwner Argument : gentity_t *self ============ */ -void RemoveOwner (gentity_t *self) -{ - if ( self->owner && self->owner->inuse ) - {//I have an owner and they heavn't been freed yet - Q3_Remove( self->owner->s.number, "self" ); +void RemoveOwner(gentity_t *self) { + if (self->owner && self->owner->inuse) { // I have an owner and they heavn't been freed yet + Q3_Remove(self->owner->s.number, "self"); } - G_FreeEntity( self ); + G_FreeEntity(self); } -void Q3_DismemberLimb( int entID, char *hitLocName ) -{ - gentity_t *self = &g_entities[entID]; - int hitLoc = GetIDForString( HLTable, hitLocName ); - vec3_t point; +void Q3_DismemberLimb(int entID, char *hitLocName) { + gentity_t *self = &g_entities[entID]; + int hitLoc = GetIDForString(HLTable, hitLocName); + vec3_t point; - if ( !self ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_WARNING, "Q3_DismemberLimb: invalid entID %d\n", entID); + if (!self) { + Quake3Game()->DebugPrint(IGameInterface::WL_WARNING, "Q3_DismemberLimb: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a player/NPC!\n", self->targetname); return; } - if ( !self->ghoul2.size() ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a ghoul model!\n", self->targetname ); + if (!self->ghoul2.size()) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a ghoul model!\n", self->targetname); return; } - if ( hitLoc <= HL_NONE || hitLoc >= HL_MAX ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a valid hit location!\n", hitLocName ); + if (hitLoc <= HL_NONE || hitLoc >= HL_MAX) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "Q3_DismemberLimb: '%s' is not a valid hit location!\n", hitLocName); return; } - switch ( hitLoc ) - { + switch (hitLoc) { case HL_FOOT_RT: - VectorCopy( self->client->renderInfo.footRPoint, point ); + VectorCopy(self->client->renderInfo.footRPoint, point); break; case HL_FOOT_LT: - VectorCopy( self->client->renderInfo.footLPoint, point ); + VectorCopy(self->client->renderInfo.footLPoint, point); break; case HL_LEG_RT: - G_GetBoltPosition( self, self->kneeRBolt, point ); + G_GetBoltPosition(self, self->kneeRBolt, point); break; case HL_LEG_LT: - G_GetBoltPosition( self, self->kneeLBolt, point ); + G_GetBoltPosition(self, self->kneeLBolt, point); break; case HL_ARM_RT: case HL_CHEST_RT: case HL_BACK_LT: - G_GetBoltPosition( self, self->elbowRBolt, point ); + G_GetBoltPosition(self, self->elbowRBolt, point); break; case HL_ARM_LT: case HL_CHEST_LT: case HL_BACK_RT: - G_GetBoltPosition( self, self->elbowLBolt, point ); + G_GetBoltPosition(self, self->elbowLBolt, point); break; case HL_WAIST: case HL_BACK: case HL_CHEST: - VectorCopy( self->client->renderInfo.torsoPoint, point ); + VectorCopy(self->client->renderInfo.torsoPoint, point); break; case HL_HAND_RT: - VectorCopy( self->client->renderInfo.handRPoint, point ); + VectorCopy(self->client->renderInfo.handRPoint, point); break; case HL_HAND_LT: - VectorCopy( self->client->renderInfo.handLPoint, point ); + VectorCopy(self->client->renderInfo.handLPoint, point); break; case HL_HEAD: - VectorCopy( self->client->renderInfo.headPoint, point ); + VectorCopy(self->client->renderInfo.headPoint, point); break; case HL_GENERIC1: case HL_GENERIC2: @@ -6983,34 +5990,33 @@ void Q3_DismemberLimb( int entID, char *hitLocName ) case HL_GENERIC4: case HL_GENERIC5: case HL_GENERIC6: - VectorCopy( self->currentOrigin, point ); + VectorCopy(self->currentOrigin, point); break; } - G_DoDismemberment( self, point, MOD_SABER, 1000, hitLoc, qtrue ); + G_DoDismemberment(self, point, MOD_SABER, 1000, hitLoc, qtrue); } /* ------------------------- VariableDeclared ------------------------- */ -int CQuake3GameInterface::VariableDeclared( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = m_varStrings.find( name ); +int CQuake3GameInterface::VariableDeclared(const char *name) { + // Check the strings + varString_m::iterator vsi = m_varStrings.find(name); - if ( vsi != m_varStrings.end() ) + if (vsi != m_varStrings.end()) return VTYPE_STRING; - //Check the floats - varFloat_m::iterator vfi = m_varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = m_varFloats.find(name); - if ( vfi != m_varFloats.end() ) + if (vfi != m_varFloats.end()) return VTYPE_FLOAT; - //Check the vectors - varString_m::iterator vvi = m_varVectors.find( name ); + // Check the vectors + varString_m::iterator vvi = m_varVectors.find(name); - if ( vvi != m_varVectors.end() ) + if (vvi != m_varVectors.end()) return VTYPE_VECTOR; return VTYPE_NONE; @@ -7022,43 +6028,37 @@ SetVar ------------------------- */ -void CQuake3GameInterface::SetVar( int taskID, int entID, const char *type_name, const char *data ) -{ - int vret = VariableDeclared( type_name ) ; - float float_data = 0.0f; - float val = 0.0f; +void CQuake3GameInterface::SetVar(int taskID, int entID, const char *type_name, const char *data) { + int vret = VariableDeclared(type_name); + float float_data = 0.0f; + float val = 0.0f; - if ( vret != VTYPE_NONE ) - { - switch ( vret ) - { + if (vret != VTYPE_NONE) { + switch (vret) { case VTYPE_FLOAT: - //Check to see if increment command - if ( (val = Q3_CheckStringCounterIncrement( data )) ) - { - GetFloatVariable( type_name, &float_data ); + // Check to see if increment command + if ((val = Q3_CheckStringCounterIncrement(data))) { + GetFloatVariable(type_name, &float_data); float_data += val; + } else { + float_data = atof((char *)data); } - else - { - float_data = atof((char *) data); - } - SetFloatVariable( type_name, float_data ); + SetFloatVariable(type_name, float_data); break; case VTYPE_STRING: - SetStringVariable( type_name, data ); + SetStringVariable(type_name, data); break; case VTYPE_VECTOR: - SetVectorVariable( type_name, (char *) data ); + SetVectorVariable(type_name, (char *)data); break; } return; } - DebugPrint( WL_ERROR, "%s variable or field not found!\n", type_name ); + DebugPrint(WL_ERROR, "%s variable or field not found!\n", type_name); } /* @@ -7067,13 +6067,11 @@ GetFloatVariable ------------------------- */ -int CQuake3GameInterface::GetFloatVariable( const char *name, float *value ) -{ - //Check the floats - varFloat_m::iterator vfi = m_varFloats.find( name ); +int CQuake3GameInterface::GetFloatVariable(const char *name, float *value) { + // Check the floats + varFloat_m::iterator vfi = m_varFloats.find(name); - if ( vfi != m_varFloats.end() ) - { + if (vfi != m_varFloats.end()) { *value = (*vfi).second; return true; } @@ -7087,14 +6085,12 @@ GetStringVariable ------------------------- */ -int CQuake3GameInterface::GetStringVariable( const char *name, const char **value ) -{ - //Check the strings - varString_m::iterator vsi = m_varStrings.find( name ); +int CQuake3GameInterface::GetStringVariable(const char *name, const char **value) { + // Check the strings + varString_m::iterator vsi = m_varStrings.find(name); - if ( vsi != m_varStrings.end() ) - { - *value = (const char *) ((*vsi).second).c_str(); + if (vsi != m_varStrings.end()) { + *value = (const char *)((*vsi).second).c_str(); return true; } @@ -7107,16 +6103,14 @@ GetVectorVariable ------------------------- */ -int CQuake3GameInterface::GetVectorVariable( const char *name, vec3_t value ) -{ - //Check the strings - varString_m::iterator vvi = m_varVectors.find( name ); +int CQuake3GameInterface::GetVectorVariable(const char *name, vec3_t value) { + // Check the strings + varString_m::iterator vvi = m_varVectors.find(name); - if ( vvi != m_varVectors.end() ) - { + if (vvi != m_varVectors.end()) { const char *str = ((*vvi).second).c_str(); - sscanf( str, "%f %f %f", &value[0], &value[1], &value[2] ); + sscanf(str, "%f %f %f", &value[0], &value[1], &value[2]); return true; } @@ -7129,14 +6123,13 @@ InitVariables ------------------------- */ -void CQuake3GameInterface::InitVariables( void ) -{ +void CQuake3GameInterface::InitVariables(void) { m_varStrings.clear(); m_varFloats.clear(); m_varVectors.clear(); - if ( m_numVariables > 0 ) - DebugPrint( WL_WARNING, "%d residual variables found!\n", m_numVariables ); + if (m_numVariables > 0) + DebugPrint(WL_WARNING, "%d residual variables found!\n", m_numVariables); m_numVariables = 0; } @@ -7147,12 +6140,11 @@ SetVariable_Float ------------------------- */ -int CQuake3GameInterface::SetFloatVariable( const char *name, float value ) -{ - //Check the floats - varFloat_m::iterator vfi = m_varFloats.find( name ); +int CQuake3GameInterface::SetFloatVariable(const char *name, float value) { + // Check the floats + varFloat_m::iterator vfi = m_varFloats.find(name); - if ( vfi == m_varFloats.end() ) + if (vfi == m_varFloats.end()) return VTYPE_FLOAT; (*vfi).second = value; @@ -7166,12 +6158,11 @@ SetVariable_String ------------------------- */ -int CQuake3GameInterface::SetStringVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vsi = m_varStrings.find( name ); +int CQuake3GameInterface::SetStringVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vsi = m_varStrings.find(name); - if ( vsi == m_varStrings.end() ) + if (vsi == m_varStrings.end()) return false; (*vsi).second = value; @@ -7185,12 +6176,11 @@ SetVariable_Vector ------------------------- */ -int CQuake3GameInterface::SetVectorVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vvi = m_varVectors.find( name ); +int CQuake3GameInterface::SetVectorVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vvi = m_varVectors.find(name); - if ( vvi == m_varVectors.end() ) + if (vvi == m_varVectors.end()) return false; (*vvi).second = value; @@ -7204,37 +6194,25 @@ VariableSaveFloats ------------------------- */ -void CQuake3GameInterface::VariableSaveFloats( varFloat_m &fmap ) -{ +void CQuake3GameInterface::VariableSaveFloats(varFloat_m &fmap) { int numFloats = fmap.size(); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('F', 'V', 'A', 'R'), - numFloats); + saved_game.write_chunk(INT_ID('F', 'V', 'A', 'R'), numFloats); - varFloat_m::iterator vfi; - STL_ITERATE( vfi, fmap ) - { - //Save out the map id - int idSize = strlen( ((*vfi).first).c_str() ); + varFloat_m::iterator vfi; + STL_ITERATE(vfi, fmap) { + // Save out the map id + int idSize = strlen(((*vfi).first).c_str()); - //Save out the real data - saved_game.write_chunk( - INT_ID('F', 'I', 'D', 'L'), - idSize); + // Save out the real data + saved_game.write_chunk(INT_ID('F', 'I', 'D', 'L'), idSize); - saved_game.write_chunk( - INT_ID('F', 'I', 'D', 'S'), - ((*vfi).first).c_str(), - idSize); + saved_game.write_chunk(INT_ID('F', 'I', 'D', 'S'), ((*vfi).first).c_str(), idSize); - //Save out the float value - saved_game.write_chunk( - INT_ID('F', 'V', 'A', 'L'), - (*vfi).second); + // Save out the float value + saved_game.write_chunk(INT_ID('F', 'V', 'A', 'L'), (*vfi).second); } } @@ -7244,44 +6222,29 @@ VariableSaveStrings ------------------------- */ -void CQuake3GameInterface::VariableSaveStrings( varString_m &smap ) -{ +void CQuake3GameInterface::VariableSaveStrings(varString_m &smap) { int numStrings = smap.size(); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('S', 'V', 'A', 'R'), - numStrings); + saved_game.write_chunk(INT_ID('S', 'V', 'A', 'R'), numStrings); - varString_m::iterator vsi; - STL_ITERATE( vsi, smap ) - { - //Save out the map id - int idSize = strlen( ((*vsi).first).c_str() ); + varString_m::iterator vsi; + STL_ITERATE(vsi, smap) { + // Save out the map id + int idSize = strlen(((*vsi).first).c_str()); - //Save out the real data - saved_game.write_chunk( - INT_ID('S', 'I', 'D', 'L'), - idSize); + // Save out the real data + saved_game.write_chunk(INT_ID('S', 'I', 'D', 'L'), idSize); - saved_game.write_chunk( - INT_ID('S', 'I', 'D', 'S'), - ((*vsi).first).c_str(), - idSize); + saved_game.write_chunk(INT_ID('S', 'I', 'D', 'S'), ((*vsi).first).c_str(), idSize); - //Save out the string value - idSize = strlen( ((*vsi).second).c_str() ); + // Save out the string value + idSize = strlen(((*vsi).second).c_str()); - saved_game.write_chunk( - INT_ID('S', 'V', 'S', 'Z'), - idSize); + saved_game.write_chunk(INT_ID('S', 'V', 'S', 'Z'), idSize); - saved_game.write_chunk( - INT_ID('S', 'V', 'A', 'L'), - ((*vsi).second).c_str(), - idSize); + saved_game.write_chunk(INT_ID('S', 'V', 'A', 'L'), ((*vsi).second).c_str(), idSize); } } @@ -7291,11 +6254,10 @@ VariableSave ------------------------- */ -int CQuake3GameInterface::VariableSave( void ) -{ - VariableSaveFloats( m_varFloats ); - VariableSaveStrings( m_varStrings ); - VariableSaveStrings( m_varVectors); +int CQuake3GameInterface::VariableSave(void) { + VariableSaveFloats(m_varFloats); + VariableSaveStrings(m_varStrings); + VariableSaveStrings(m_varVectors); return qtrue; } @@ -7306,46 +6268,33 @@ VariableLoadFloats ------------------------- */ -void CQuake3GameInterface::VariableLoadFloats( varFloat_m &fmap ) -{ - int numFloats = 0; - char tempBuffer[1024]; +void CQuake3GameInterface::VariableLoadFloats(varFloat_m &fmap) { + int numFloats = 0; + char tempBuffer[1024]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('F', 'V', 'A', 'R'), - numFloats); + saved_game.read_chunk(INT_ID('F', 'V', 'A', 'R'), numFloats); - for ( int i = 0; i < numFloats; i++ ) - { + for (int i = 0; i < numFloats; i++) { int idSize = 0; - saved_game.read_chunk( - INT_ID('F', 'I', 'D', 'L'), - idSize); + saved_game.read_chunk(INT_ID('F', 'I', 'D', 'L'), idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) - { + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) { ::G_Error("invalid length for FIDS string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('F', 'I', 'D', 'S'), - tempBuffer, - idSize); + saved_game.read_chunk(INT_ID('F', 'I', 'D', 'S'), tempBuffer, idSize); - tempBuffer[ idSize ] = 0; + tempBuffer[idSize] = 0; - float val = 0.0F; + float val = 0.0F; - saved_game.read_chunk( - INT_ID('F', 'V', 'A', 'L'), - val); + saved_game.read_chunk(INT_ID('F', 'V', 'A', 'L'), val); - DeclareVariable( TK_FLOAT, (const char *) &tempBuffer ); - SetFloatVariable( (const char *) &tempBuffer, val ); + DeclareVariable(TK_FLOAT, (const char *)&tempBuffer); + SetFloatVariable((const char *)&tempBuffer, val); } } @@ -7355,65 +6304,47 @@ VariableLoadStrings ------------------------- */ -void CQuake3GameInterface::VariableLoadStrings( int type, varString_m &fmap ) -{ - int numFloats = 0; - char tempBuffer[1024]; - char tempBuffer2[1024]; +void CQuake3GameInterface::VariableLoadStrings(int type, varString_m &fmap) { + int numFloats = 0; + char tempBuffer[1024]; + char tempBuffer2[1024]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('S', 'V', 'A', 'R'), - numFloats); + saved_game.read_chunk(INT_ID('S', 'V', 'A', 'R'), numFloats); - for ( int i = 0; i < numFloats; i++ ) - { + for (int i = 0; i < numFloats; i++) { int idSize = 0; - saved_game.read_chunk( - INT_ID('S', 'I', 'D', 'L'), - idSize); + saved_game.read_chunk(INT_ID('S', 'I', 'D', 'L'), idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) - { + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) { ::G_Error("invalid length for SIDS string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('S', 'I', 'D', 'S'), - tempBuffer, - idSize); + saved_game.read_chunk(INT_ID('S', 'I', 'D', 'S'), tempBuffer, idSize); - tempBuffer[ idSize ] = 0; + tempBuffer[idSize] = 0; - saved_game.read_chunk( - INT_ID('S', 'V', 'S', 'Z'), - idSize); + saved_game.read_chunk(INT_ID('S', 'V', 'S', 'Z'), idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer2)) - { + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer2)) { ::G_Error("invalid length for SVAL string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('S', 'V', 'A', 'L'), - tempBuffer2, - idSize); + saved_game.read_chunk(INT_ID('S', 'V', 'A', 'L'), tempBuffer2, idSize); - tempBuffer2[ idSize ] = 0; + tempBuffer2[idSize] = 0; - switch ( type ) - { + switch (type) { case TK_STRING: - DeclareVariable( TK_STRING, (const char *) &tempBuffer ); - SetStringVariable( (const char *) &tempBuffer, (const char *) &tempBuffer2 ); + DeclareVariable(TK_STRING, (const char *)&tempBuffer); + SetStringVariable((const char *)&tempBuffer, (const char *)&tempBuffer2); break; case TK_VECTOR: - DeclareVariable( TK_VECTOR, (const char *) &tempBuffer ); - SetVectorVariable( (const char *) &tempBuffer, (const char *) &tempBuffer2 ); + DeclareVariable(TK_VECTOR, (const char *)&tempBuffer); + SetVectorVariable((const char *)&tempBuffer, (const char *)&tempBuffer2); break; } } @@ -7425,15 +6356,14 @@ VariableLoad ------------------------- */ -int CQuake3GameInterface::VariableLoad( void ) -{ +int CQuake3GameInterface::VariableLoad(void) { InitVariables(); - VariableLoadFloats( m_varFloats ); + VariableLoadFloats(m_varFloats); - VariableLoadStrings( TK_STRING, m_varStrings ); + VariableLoadStrings(TK_STRING, m_varStrings); - VariableLoadStrings( TK_VECTOR, m_varVectors); + VariableLoadStrings(TK_VECTOR, m_varVectors); return qfalse; } @@ -7447,11 +6377,9 @@ IGameInterface::~IGameInterface() {} int IGameInterface::s_IcarusFlavorsNeeded = 1; // Get this Interface Instance. -IGameInterface *IGameInterface::GetGame( int flavor ) -{ +IGameInterface *IGameInterface::GetGame(int flavor) { // If no instance exists, create one... - if ( !CQuake3GameInterface::m_pInstance ) - { + if (!CQuake3GameInterface::m_pInstance) { CQuake3GameInterface::m_pInstance = new CQuake3GameInterface(); } @@ -7459,18 +6387,15 @@ IGameInterface *IGameInterface::GetGame( int flavor ) } // Destroy the game Instance. -void IGameInterface::Destroy() -{ - if ( CQuake3GameInterface::m_pInstance ) - { +void IGameInterface::Destroy() { + if (CQuake3GameInterface::m_pInstance) { delete CQuake3GameInterface::m_pInstance; CQuake3GameInterface::m_pInstance = NULL; } } // Constructor. -CQuake3GameInterface::CQuake3GameInterface() : IGameInterface() -{ +CQuake3GameInterface::CQuake3GameInterface() : IGameInterface() { m_ScriptList.clear(); m_EntityList.clear(); m_cvars.clear(); @@ -7481,30 +6406,27 @@ CQuake3GameInterface::CQuake3GameInterface() : IGameInterface() player_locked = qfalse; - gclient_t* client = &level.clients[0]; + gclient_t *client = &level.clients[0]; memset(&client->sess, 0, sizeof(client->sess)); } // Destructor. -CQuake3GameInterface::~CQuake3GameInterface() -{ - scriptlist_t::iterator iterScript; - entitylist_t::iterator iterEntity; - gentity_t *ent = &g_entities[0]; +CQuake3GameInterface::~CQuake3GameInterface() { + scriptlist_t::iterator iterScript; + entitylist_t::iterator iterEntity; + gentity_t *ent = &g_entities[0]; // Release all entities Icarus resources. - for ( int i = 0; i < globals.num_entities; i++, ent++ ) - { - if ( !ent->inuse ) + for (int i = 0; i < globals.num_entities; i++, ent++) { + if (!ent->inuse) continue; - FreeEntity( ent ); + FreeEntity(ent); } // Clear out all precached script's. - for ( iterScript = m_ScriptList.begin(); iterScript != m_ScriptList.end(); ++iterScript ) - { - Free( (*iterScript).second->buffer ); + for (iterScript = m_ScriptList.begin(); iterScript != m_ScriptList.end(); ++iterScript) { + Free((*iterScript).second->buffer); delete (*iterScript).second; } @@ -7514,75 +6436,67 @@ CQuake3GameInterface::~CQuake3GameInterface() } // Initialize an Entity by ID. -bool CQuake3GameInterface::InitEntity( gentity_t *pEntity ) -{ - //Make sure this is a fresh entity. - assert( pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID ); +bool CQuake3GameInterface::InitEntity(gentity_t *pEntity) { + // Make sure this is a fresh entity. + assert(pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID); - if ( pEntity->m_iIcarusID != IIcarusInterface::ICARUS_INVALID ) + if (pEntity->m_iIcarusID != IIcarusInterface::ICARUS_INVALID) return false; // Get an Icarus ID. - pEntity->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID( pEntity->s.number ); + pEntity->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID(pEntity->s.number); // Initialize all taskIDs to -1 - memset( &pEntity->taskID, -1, sizeof( pEntity->taskID ) ); + memset(&pEntity->taskID, -1, sizeof(pEntity->taskID)); // Add this entity to a map of valid associated entity's for quick retrieval later. - AssociateEntity( pEntity ); + AssociateEntity(pEntity); - //Precache all the entity's scripts. - PrecacheEntity( pEntity ); + // Precache all the entity's scripts. + PrecacheEntity(pEntity); return false; } // Free an Entity by ID. -void CQuake3GameInterface::FreeEntity( gentity_t *pEntity ) -{ - //Make sure the entity is valid - if ( pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID ) +void CQuake3GameInterface::FreeEntity(gentity_t *pEntity) { + // Make sure the entity is valid + if (pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID) return; // Remove the Entity from the Entity map so that when their g_entity index is reused, // ICARUS doesn't try to affect the new (incorrect) pEntity. - if VALIDSTRING( pEntity->script_targetname ) - { - char temp[1024]; + if VALIDSTRING (pEntity->script_targetname) { + char temp[1024]; - strncpy( (char *) temp, pEntity->script_targetname, 1023 ); - temp[ 1023 ] = 0; + strncpy((char *)temp, pEntity->script_targetname, 1023); + temp[1023] = 0; - entitylist_t::iterator it = m_EntityList.find( Q_strupr(temp) ); + entitylist_t::iterator it = m_EntityList.find(Q_strupr(temp)); - if (it != m_EntityList.end()) - { + if (it != m_EntityList.end()) { m_EntityList.erase(it); } } // Delete the Icarus ID, but lets not construct icarus to do it - if (IIcarusInterface::GetIcarus(0,false)) - { - IIcarusInterface::GetIcarus()->DeleteIcarusID( pEntity->m_iIcarusID ); + if (IIcarusInterface::GetIcarus(0, false)) { + IIcarusInterface::GetIcarus()->DeleteIcarusID(pEntity->m_iIcarusID); } } // Determines whether or not a Game Element needs ICARUS information. -bool CQuake3GameInterface::ValidEntity( gentity_t *pEntity ) -{ +bool CQuake3GameInterface::ValidEntity(gentity_t *pEntity) { int i; // Targeted by a script. - if ( pEntity->script_targetname && pEntity->script_targetname[0] ) + if (pEntity->script_targetname && pEntity->script_targetname[0]) return true; // Potentially able to call a script. - for ( i = 0; i < NUM_BSETS; i++ ) - { - if VALIDSTRING( pEntity->behaviorSet[i] ) - { - //Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", pEntity->s.number, pEntity->targetname ); + for (i = 0; i < NUM_BSETS; i++) { + if VALIDSTRING (pEntity->behaviorSet[i]) { + // Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", pEntity->s.number, pEntity->targetname ); pEntity->script_targetname = G_NewString(pEntity->targetname); return true; } @@ -7592,36 +6506,31 @@ bool CQuake3GameInterface::ValidEntity( gentity_t *pEntity ) } // Associate the entity's id and name so that it can be referenced later. -void CQuake3GameInterface::AssociateEntity( gentity_t *pEntity ) -{ - char temp[1024]; +void CQuake3GameInterface::AssociateEntity(gentity_t *pEntity) { + char temp[1024]; - if ( VALIDSTRING( pEntity->script_targetname ) == false ) + if (VALIDSTRING(pEntity->script_targetname) == false) return; - strncpy( (char *) temp, pEntity->script_targetname, 1023 ); - temp[ 1023 ] = 0; + strncpy((char *)temp, pEntity->script_targetname, 1023); + temp[1023] = 0; - m_EntityList[ Q_strupr( (char *) temp ) ] = pEntity->s.number; + m_EntityList[Q_strupr((char *)temp)] = pEntity->s.number; } // Make a valid script name. -int CQuake3GameInterface::MakeValidScriptName( char **strScriptName ) -{ - if ( !Q_stricmp( *strScriptName, "NULL" ) || !Q_stricmp( *strScriptName, "default" ) ) +int CQuake3GameInterface::MakeValidScriptName(char **strScriptName) { + if (!Q_stricmp(*strScriptName, "NULL") || !Q_stricmp(*strScriptName, "default")) return 0; // ensure "scripts" (Q3_SCRIPT_DIR), which will be missing if this was called recursively... // MAX_FILENAME_LENGTH should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code char sFilename[MAX_FILENAME_LENGTH]; - if ( !Q_stricmpn( *strScriptName, Q3_SCRIPT_DIR, strlen( Q3_SCRIPT_DIR ) ) ) - { - Q_strncpyz( sFilename, *strScriptName, sizeof( sFilename ) ); - } - else - { - Q_strncpyz( sFilename, va( "%s/%s", Q3_SCRIPT_DIR, *strScriptName ), sizeof( sFilename ) ); + if (!Q_stricmpn(*strScriptName, Q3_SCRIPT_DIR, strlen(Q3_SCRIPT_DIR))) { + Q_strncpyz(sFilename, *strScriptName, sizeof(sFilename)); + } else { + Q_strncpyz(sFilename, va("%s/%s", Q3_SCRIPT_DIR, *strScriptName), sizeof(sFilename)); } return 1; @@ -7630,83 +6539,77 @@ int CQuake3GameInterface::MakeValidScriptName( char **strScriptName ) // First looks to see if a script has already been loaded, if so, return SCRIPT_ALREADYREGISTERED. If a script has // NOT been already cached, that script is loaded and the return is SCRIPT_REGISTERED. If a script could not // be found cached and could not be loaded we return SCRIPT_COULDNOTREGISTER. -int CQuake3GameInterface::RegisterScript( const char *strFileName, void **ppBuf, int &iLength ) -{ +int CQuake3GameInterface::RegisterScript(const char *strFileName, void **ppBuf, int &iLength) { // If the file name is invalid, leave. - if ( !strFileName || strFileName[0] == '\0' || !Q_stricmp( strFileName, "NULL" ) || !Q_stricmp( strFileName, "default" ) ) + if (!strFileName || strFileName[0] == '\0' || !Q_stricmp(strFileName, "NULL") || !Q_stricmp(strFileName, "default")) return SCRIPT_COULDNOTREGISTER; // Ensure "scripts" (Q3_SCRIPT_DIR), which will be missing if this was called recursively... // MAX_FILENAME_LENGTH should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code char sFilename[MAX_FILENAME_LENGTH]; - if ( !Q_stricmpn( strFileName, Q3_SCRIPT_DIR, strlen( Q3_SCRIPT_DIR ) ) ) - { - Q_strncpyz( sFilename, strFileName, sizeof( sFilename ) ); - } - else - { - Q_strncpyz( sFilename, va( "%s/%s", Q3_SCRIPT_DIR, strFileName ), sizeof( sFilename ) ); + if (!Q_stricmpn(strFileName, Q3_SCRIPT_DIR, strlen(Q3_SCRIPT_DIR))) { + Q_strncpyz(sFilename, strFileName, sizeof(sFilename)); + } else { + Q_strncpyz(sFilename, va("%s/%s", Q3_SCRIPT_DIR, strFileName), sizeof(sFilename)); } - scriptlist_t::iterator ei; - pscript_t *pscript; + scriptlist_t::iterator ei; + pscript_t *pscript; // Make sure this isn't already cached - ei = m_ScriptList.find( strFileName ); + ei = m_ScriptList.find(strFileName); // If we found the script (didn't get to the end of the list), return true. - if ( ei != m_ScriptList.end() ) - { + if (ei != m_ScriptList.end()) { // Send back the script buffer info. - (*ppBuf) = (*ei).second->buffer; - iLength = (*ei).second->length; + (*ppBuf) = (*ei).second->buffer; + iLength = (*ei).second->length; return SCRIPT_ALREADYREGISTERED; } // Prepare the name with the extension. - char newname[MAX_FILENAME_LENGTH]; - sprintf((char *) newname, "%s%s", sFilename, IBI_EXT ); + char newname[MAX_FILENAME_LENGTH]; + sprintf((char *)newname, "%s%s", sFilename, IBI_EXT); qboolean qbIgnoreFileRead = qfalse; // NOTENOTE: For the moment I've taken this back out, to avoid doubling the number of fopen()'s per file. -/*#if 0//#ifndef FINAL_BUILD - // small update here, if called during interrogate, don't let gi.FS_ReadFile() complain because it can't - // find stuff like BS_RUN_AND_SHOOT as scriptname... During FINALBUILD the message won't appear anyway, hence - // the ifndef, this just cuts down on internal error reports while testing release mode... - // + /*#if 0//#ifndef FINAL_BUILD + // small update here, if called during interrogate, don't let gi.FS_ReadFile() complain because it can't + // find stuff like BS_RUN_AND_SHOOT as scriptname... During FINALBUILD the message won't appear anyway, hence + // the ifndef, this just cuts down on internal error reports while testing release mode... + // - if (bCalledDuringInterrogate) - { - fileHandle_t file; + if (bCalledDuringInterrogate) + { + fileHandle_t file; - gi.FS_FOpenFile( newname, &file, FS_READ ); + gi.FS_FOpenFile( newname, &file, FS_READ ); - if ( file == NULL ) - { - qbIgnoreFileRead = qtrue; // warn disk code further down not to try FS_ReadFile() - } - else - { - gi.FS_FCloseFile( file ); + if ( file == NULL ) + { + qbIgnoreFileRead = qtrue; // warn disk code further down not to try FS_ReadFile() + } + else + { + gi.FS_FCloseFile( file ); + } } - } -#endif*/ + #endif*/ // Read the Script File into the Buffer. char *pBuf = NULL; - iLength = qbIgnoreFileRead ? -1 : gi.FS_ReadFile( newname, (void **) &pBuf ); + iLength = qbIgnoreFileRead ? -1 : gi.FS_ReadFile(newname, (void **)&pBuf); - if ( iLength <= 0 ) - { + if (iLength <= 0) { // File not found, but keep quiet during interrogate stage, because of stuff like BS_RUN_AND_SHOOT as scriptname // -/* if (!bCalledDuringInterrogate) - { - Com_Printf(S_COLOR_RED"Could not open file '%s'\n", newname ); - }*/ + /* if (!bCalledDuringInterrogate) + { + Com_Printf(S_COLOR_RED"Could not open file '%s'\n", newname ); + }*/ return SCRIPT_COULDNOTREGISTER; } @@ -7714,15 +6617,15 @@ int CQuake3GameInterface::RegisterScript( const char *strFileName, void **ppBuf, pscript = new pscript_t; // Allocate a buffer of the size we need then mem copy over the buffer. - pscript->buffer = (char *)Malloc( iLength ); - memcpy( pscript->buffer, pBuf, iLength ); + pscript->buffer = (char *)Malloc(iLength); + memcpy(pscript->buffer, pBuf, iLength); pscript->length = iLength; // We (mem)copied the data over so release the original buffer. - gi.FS_FreeFile( pBuf ); + gi.FS_FreeFile(pBuf); // Keep track of the buffer still. - (*ppBuf) = pscript->buffer; + (*ppBuf) = pscript->buffer; // Add the Script Buffer to the STL map. m_ScriptList[strFileName] = pscript; @@ -7731,31 +6634,26 @@ int CQuake3GameInterface::RegisterScript( const char *strFileName, void **ppBuf, } // Precache all the resources needed by a Script and it's Entity (or vice-versa). -int CQuake3GameInterface::PrecacheEntity( gentity_t *pEntity ) -{ - int i; +int CQuake3GameInterface::PrecacheEntity(gentity_t *pEntity) { + int i; - for ( i = 0; i < NUM_BSETS; i++ ) - { - if ( pEntity->behaviorSet[i] == NULL ) + for (i = 0; i < NUM_BSETS; i++) { + if (pEntity->behaviorSet[i] == NULL) continue; - if ( GetIDForString( BSTable, pEntity->behaviorSet[i] ) == -1 ) - {//not a behavior set + if (GetIDForString(BSTable, pEntity->behaviorSet[i]) == -1) { // not a behavior set char *pBuf = NULL; int iLength = 0; // Try to register this script. - if ( RegisterScript( pEntity->behaviorSet[i], (void **) &pBuf, iLength ) != SCRIPT_COULDNOTREGISTER ) - { - assert( pBuf ); - assert( iLength ); + if (RegisterScript(pEntity->behaviorSet[i], (void **)&pBuf, iLength) != SCRIPT_COULDNOTREGISTER) { + assert(pBuf); + assert(iLength); - if ( pBuf != NULL && iLength > 0 ) + if (pBuf != NULL && iLength > 0) // Tell Icarus to precache the script data. - IIcarusInterface::GetIcarus()->Precache( pBuf, iLength ); - } - else + IIcarusInterface::GetIcarus()->Precache(pBuf, iLength); + } else // otherwise try the next guy, maybe It will work. continue; } @@ -7765,50 +6663,44 @@ int CQuake3GameInterface::PrecacheEntity( gentity_t *pEntity ) } // Run the script. -void CQuake3GameInterface::RunScript( const gentity_t *pEntity, const char *strScriptName ) -{ +void CQuake3GameInterface::RunScript(const gentity_t *pEntity, const char *strScriptName) { char *pBuf = NULL; int iLength = 0; - switch( RegisterScript( strScriptName, (void **) &pBuf, iLength ) ) - { - // If could not be loaded, leave! - case SCRIPT_COULDNOTREGISTER: - DebugPrint( WL_WARNING, "RunScript: Script was not found and could not be loaded!!! %s\n", strScriptName); - return; + switch (RegisterScript(strScriptName, (void **)&pBuf, iLength)) { + // If could not be loaded, leave! + case SCRIPT_COULDNOTREGISTER: + DebugPrint(WL_WARNING, "RunScript: Script was not found and could not be loaded!!! %s\n", strScriptName); + return; - // We loaded the script and registered it, so run it! - case SCRIPT_REGISTERED: - case SCRIPT_ALREADYREGISTERED: - assert( pBuf ); - assert( iLength ); - if ( IIcarusInterface::GetIcarus()->Run( pEntity->m_iIcarusID, pBuf, iLength ) != IIcarusInterface::ICARUS_INVALID ) - DebugPrint( WL_VERBOSE, "%d Script %s executed by %s %s\n", level.time, (char *) strScriptName, pEntity->classname, pEntity->targetname ); - return; + // We loaded the script and registered it, so run it! + case SCRIPT_REGISTERED: + case SCRIPT_ALREADYREGISTERED: + assert(pBuf); + assert(iLength); + if (IIcarusInterface::GetIcarus()->Run(pEntity->m_iIcarusID, pBuf, iLength) != IIcarusInterface::ICARUS_INVALID) + DebugPrint(WL_VERBOSE, "%d Script %s executed by %s %s\n", level.time, (char *)strScriptName, pEntity->classname, pEntity->targetname); + return; } } -void CQuake3GameInterface::Svcmd( void ) -{ - char *cmd = gi.argv( 1 ); +void CQuake3GameInterface::Svcmd(void) { + char *cmd = gi.argv(1); - if ( Q_stricmp( cmd, "log" ) == 0 ) - { + if (Q_stricmp(cmd, "log") == 0) { g_ICARUSDebug->integer = WL_DEBUG; - if ( VALIDSTRING( gi.argv( 2 ) ) ) - { - gentity_t *ent = G_Find( NULL, FOFS( script_targetname ), gi.argv(2) ); + if (VALIDSTRING(gi.argv(2))) { + gentity_t *ent = G_Find(NULL, FOFS(script_targetname), gi.argv(2)); - if ( ent == NULL ) - { - Com_Printf( "Entity \"%s\" not found!\n", gi.argv(2) ); + if (ent == NULL) { + Com_Printf("Entity \"%s\" not found!\n", gi.argv(2)); return; } - //Start logging - Com_Printf("Logging ICARUS info for entity %s\n", gi.argv(2) ); + // Start logging + Com_Printf("Logging ICARUS info for entity %s\n", gi.argv(2)); - m_entFilter = ( ent->s.number == m_entFilter ) ? -1 : ent->s.number; + m_entFilter = (ent->s.number == m_entFilter) ? -1 : ent->s.number; } Com_Printf("Logging ICARUS info for all entities\n"); @@ -7816,145 +6708,127 @@ void CQuake3GameInterface::Svcmd( void ) } // Get the current Game flavor. -int CQuake3GameInterface::GetFlavor() -{ - return 0; -} +int CQuake3GameInterface::GetFlavor() { return 0; } // Reads in a file and attaches the script directory properly. -int CQuake3GameInterface::LoadFile( const char *name, void **buf ) -{ +int CQuake3GameInterface::LoadFile(const char *name, void **buf) { int iLength = 0; // Register the Script (or retrieve it). - RegisterScript( name, buf, iLength ); + RegisterScript(name, buf, iLength); return iLength; } // Prints a message in the center of the screen. -void CQuake3GameInterface::CenterPrint( const char *format, ... ) -{ - va_list argptr; - char text[1024]; +void CQuake3GameInterface::CenterPrint(const char *format, ...) { + va_list argptr; + char text[1024]; - va_start (argptr, format); - Q_vsnprintf (text, sizeof(text), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(text, sizeof(text), format, argptr); + va_end(argptr); // FIXME: added '!' so you can print something that's hasn't been precached, '@' searches only for precache text // this is just a TEMPORARY placeholder until objectives are in!!! -- dmv 11/26/01 - if ((text[0] == '@') || text[0] == '!') // It's a key + if ((text[0] == '@') || text[0] == '!') // It's a key { - if( text[0] == '!') - { - gi.SendServerCommand( 0, "cp \"%s\"", (text+1) ); + if (text[0] == '!') { + gi.SendServerCommand(0, "cp \"%s\"", (text + 1)); return; } - gi.SendServerCommand( 0, "cp \"%s\"", text ); + gi.SendServerCommand(0, "cp \"%s\"", text); } - DebugPrint( WL_VERBOSE, "%s\n", text); // Just a developers note + DebugPrint(WL_VERBOSE, "%s\n", text); // Just a developers note } // Print a debug message. -void CQuake3GameInterface::DebugPrint( e_DebugPrintLevel level, const char *format, ... ) -{ - //Don't print messages they don't want to see - if ( g_ICARUSDebug->integer < level ) +void CQuake3GameInterface::DebugPrint(e_DebugPrintLevel level, const char *format, ...) { + // Don't print messages they don't want to see + if (g_ICARUSDebug->integer < level) return; - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr, format); - Q_vsnprintf (text, sizeof(text), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(text, sizeof(text), format, argptr); + va_end(argptr); - //Add the color formatting - switch ( level ) - { - case WL_ERROR: - Com_Printf ( S_COLOR_RED"ERROR: %s", text ); - break; + // Add the color formatting + switch (level) { + case WL_ERROR: + Com_Printf(S_COLOR_RED "ERROR: %s", text); + break; - case WL_WARNING: - Com_Printf ( S_COLOR_YELLOW"WARNING: %s", text ); - break; + case WL_WARNING: + Com_Printf(S_COLOR_YELLOW "WARNING: %s", text); + break; - case WL_DEBUG: - { - int entNum; - char *buffer; + case WL_DEBUG: { + int entNum; + char *buffer; - sscanf( text, "%d", &entNum ); + sscanf(text, "%d", &entNum); - if ( ( m_entFilter >= 0 ) && ( m_entFilter != entNum ) ) - return; + if ((m_entFilter >= 0) && (m_entFilter != entNum)) + return; - buffer = (char *) text; - buffer += 5; + buffer = (char *)text; + buffer += 5; - if ( ( entNum < 0 ) || ( entNum >= MAX_GENTITIES ) ) - entNum = 0; + if ((entNum < 0) || (entNum >= MAX_GENTITIES)) + entNum = 0; - Com_Printf ( S_COLOR_BLUE"DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer ); - break; - } - default: - case WL_VERBOSE: - Com_Printf ( S_COLOR_GREEN"INFO: %s", text ); - break; + Com_Printf(S_COLOR_BLUE "DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer); + break; + } + default: + case WL_VERBOSE: + Com_Printf(S_COLOR_GREEN "INFO: %s", text); + break; } } -//Gets the current time -unsigned int CQuake3GameInterface::GetTime( void ) -{ - return level.time; -} +// Gets the current time +unsigned int CQuake3GameInterface::GetTime(void) { return level.time; } // DWORD CQuake3GameInterface::GetTimeScale(void ) {} // NOTE: This extern does not really fit here, fix later please... -extern void G_SoundBroadcast( gentity_t *ent, int soundIndex ); +extern void G_SoundBroadcast(gentity_t *ent, int soundIndex); // Plays a sound from an entity. -int CQuake3GameInterface::PlayIcarusSound( int taskID, int entID, const char *name, const char *channel ) -{ - gentity_t *ent = &g_entities[entID]; - char finalName[MAX_QPATH]; - soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch - qboolean type_voice = qfalse; +int CQuake3GameInterface::PlayIcarusSound(int taskID, int entID, const char *name, const char *channel) { + gentity_t *ent = &g_entities[entID]; + char finalName[MAX_QPATH]; + soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch + qboolean type_voice = qfalse; - Q_strncpyz( finalName, name, MAX_QPATH ); + Q_strncpyz(finalName, name, MAX_QPATH); Q_strlwr(finalName); - G_AddSexToPlayerString( finalName, qtrue ); + G_AddSexToPlayerString(finalName, qtrue); - COM_StripExtension( (const char *)finalName, finalName, sizeof(finalName) ); + COM_StripExtension((const char *)finalName, finalName, sizeof(finalName)); - int soundHandle = G_SoundIndex( (char *) finalName ); + int soundHandle = G_SoundIndex((char *)finalName); bool bBroadcast = false; - if ( ( Q_stricmp( channel, "CHAN_ANNOUNCER" ) == 0 ) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname ) == 0) ) { + if ((Q_stricmp(channel, "CHAN_ANNOUNCER") == 0) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname) == 0)) { bBroadcast = true; } - // moved here from further down so I can easily check channel-type without code dup... // - if ( Q_stricmp( channel, "CHAN_VOICE" ) == 0 ) - { + if (Q_stricmp(channel, "CHAN_VOICE") == 0) { voice_chan = CHAN_VOICE; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_ATTEN" ) == 0 ) - { + } else if (Q_stricmp(channel, "CHAN_VOICE_ATTEN") == 0) { voice_chan = CHAN_VOICE_ATTEN; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_GLOBAL" ) == 0 ) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... + } else if (Q_stricmp(channel, "CHAN_VOICE_GLOBAL") == 0) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... { voice_chan = CHAN_VOICE_GLOBAL; type_voice = qtrue; @@ -7964,98 +6838,85 @@ int CQuake3GameInterface::PlayIcarusSound( int taskID, int entID, const char *n // if we're in-camera, check for skipping cinematic and ifso, no subtitle print (since screen is not being // updated anyway during skipping). This stops leftover subtitles being left onscreen after unskipping. // - if (!in_camera || - (!g_skippingcin || !g_skippingcin->integer) - ) // paranoia towards project end + if (!in_camera || (!g_skippingcin || !g_skippingcin->integer)) // paranoia towards project end { // Text on // certain NPC's we always want to use subtitles regardless of subtitle setting - if (g_subtitles->integer == 1 || (ent->NPC && (ent->NPC->scriptFlags & SCF_USE_SUBTITLES) ) ) // Show all text + if (g_subtitles->integer == 1 || (ent->NPC && (ent->NPC->scriptFlags & SCF_USE_SUBTITLES))) // Show all text { - if ( in_camera) // Cinematic + if (in_camera) // Cinematic { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle ); - } - else //if (precacheWav[i].speaker==SP_NONE) // lower screen text + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); + } else // if (precacheWav[i].speaker==SP_NONE) // lower screen text { - gentity_t *ent2 = &g_entities[0]; - // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 by the computer core that was submitted as a bug report... + gentity_t *ent2 = &g_entities[0]; + // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 + // by the computer core that was submitted as a bug report... // - if (bBroadcast || (DistanceSquared(ent->currentOrigin, ent2->currentOrigin) < ((voice_chan == CHAN_VOICE_ATTEN)?(350 * 350):(1200 * 1200)) ) ) - { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle ); + if (bBroadcast || + (DistanceSquared(ent->currentOrigin, ent2->currentOrigin) < ((voice_chan == CHAN_VOICE_ATTEN) ? (350 * 350) : (1200 * 1200)))) { + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); } } } // Cinematic only else if (g_subtitles->integer == 2) // Show only talking head text and CINEMATIC { - if ( in_camera) // Cinematic text + if (in_camera) // Cinematic text { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle); + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); } } } - if ( type_voice ) - { - if ( g_timescale->value > 1.0f ) - {//Skip the damn sound! + if (type_voice) { + if (g_timescale->value > 1.0f) { // Skip the damn sound! return qtrue; - } - else - { - //This the voice channel - G_SoundOnEnt( ent, voice_chan, ((char *) finalName) ); - } - //Remember we're waiting for this - Q3_TaskIDSet( ent, TID_CHAN_VOICE, taskID ); - //do not task_return complete - // if( voice_chan == CHAN_VOICE_GLOBAL ) - // { - // G_SoundBroadcast( ent, soundHandle ); - // } + } else { + // This the voice channel + G_SoundOnEnt(ent, voice_chan, ((char *)finalName)); + } + // Remember we're waiting for this + Q3_TaskIDSet(ent, TID_CHAN_VOICE, taskID); + // do not task_return complete + // if( voice_chan == CHAN_VOICE_GLOBAL ) + // { + // G_SoundBroadcast( ent, soundHandle ); + // } return qfalse; } - if ( bBroadcast ) - {//Broadcast the sound - G_SoundBroadcast( ent, soundHandle ); - } - else - { - G_Sound( ent, soundHandle ); + if (bBroadcast) { // Broadcast the sound + G_SoundBroadcast(ent, soundHandle); + } else { + G_Sound(ent, soundHandle); } return qtrue; } // Lerps the origin and angles of an entity to the destination values. -void CQuake3GameInterface::Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +void CQuake3GameInterface::Lerp2Pos(int taskID, int entID, vec3_t origin, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; - if(!ent) - { - DebugPrint( WL_WARNING, "Lerp2Pos: invalid entID %d\n", entID); + if (!ent) { + DebugPrint(WL_WARNING, "Lerp2Pos: invalid entID %d\n", entID); return; } - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - DebugPrint( WL_ERROR, "Lerp2Pos: ent %d is NOT a mover!\n", entID); + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + DebugPrint(WL_ERROR, "Lerp2Pos: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //Don't allow a zero duration - if ( duration == 0 ) + // Don't allow a zero duration + if (duration == 0) duration = 1; // @@ -8063,57 +6924,48 @@ void CQuake3GameInterface::Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_ moverState_t moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); - if ( moverState == MOVER_POS1 ) - {//open the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qtrue ); + if (moverState == MOVER_POS1) { // open the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qtrue); } } moverState = MOVER_1TO2; - } - else /*if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 )*/ + } else /*if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 )*/ { - VectorCopy( ent->currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); + InitMoverTrData(ent); ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); - //Only do the angles if specified - if ( angles != NULL ) - { + // Only do the angles if specified + if (angles != NULL) { // // Rotation - for ( i = 0; i < 3; i++ ) - { - ang[i] = AngleDelta( angles[i], ent->currentAngles[i] ); - ent->s.apos.trDelta[i] = ( ang[i] / ( duration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleDelta(angles[i], ent->currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (duration * 0.001f)); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trDuration = duration; @@ -8121,100 +6973,88 @@ void CQuake3GameInterface::Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_ ent->s.apos.trTime = level.time; ent->e_ReachedFunc = reachedF_moveAndRotateCallback; - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); - } - else - { - //Setup the last bits of information - ent->e_ReachedFunc = reachedF_moverCallback; + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); + } else { + // Setup the last bits of information + ent->e_ReachedFunc = reachedF_moverCallback; } - if ( ent->damage ) - { + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - gi.linkentity( ent ); + gi.linkentity(ent); } // void CQuake3GameInterface::Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ) {} // Lerps the angles to the destination value. -void CQuake3GameInterface::Lerp2Angles( int taskID, int entID, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +void CQuake3GameInterface::Lerp2Angles(int taskID, int entID, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; - if(!ent) - { - DebugPrint( WL_WARNING, "Lerp2Angles: invalid entID %d\n", entID); + if (!ent) { + DebugPrint(WL_WARNING, "Lerp2Angles: invalid entID %d\n", entID); return; } - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - DebugPrint( WL_ERROR, "Lerp2Angles: ent %d is NOT a mover!\n", entID); + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + DebugPrint(WL_ERROR, "Lerp2Angles: ent %d is NOT a mover!\n", entID); return; } - //If we want an instant move, don't send 0... - ent->s.apos.trDuration = (duration>0) ? duration : 1; + // If we want an instant move, don't send 0... + ent->s.apos.trDuration = (duration > 0) ? duration : 1; - for ( i = 0; i < 3; i++ ) - { - ang [i] = AngleSubtract( angles[i], ent->currentAngles[i]); - ent->s.apos.trDelta[i] = ( ang[i] / ( ent->s.apos.trDuration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleSubtract(angles[i], ent->currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (ent->s.apos.trDuration * 0.001f)); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trTime = level.time; - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); - //ent->e_ReachedFunc = reachedF_NULL; + // ent->e_ReachedFunc = reachedF_NULL; ent->e_ThinkFunc = thinkF_anglerCallback; ent->nextthink = level.time + duration; // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - gi.linkentity( ent ); + gi.linkentity(ent); } // Gets the value of a tag by the give name. -int CQuake3GameInterface::GetTag( int entID, const char *name, int lookup, vec3_t info ) -{ - gentity_t *ent = &g_entities[ entID ]; +int CQuake3GameInterface::GetTag(int entID, const char *name, int lookup, vec3_t info) { + gentity_t *ent = &g_entities[entID]; - VALIDATEB( ent ); + VALIDATEB(ent); - switch ( lookup ) - { + switch (lookup) { case TYPE_ORIGIN: - //return TAG_GetOrigin( ent->targetname, name, info ); - return TAG_GetOrigin( ent->ownername, name, info ); + // return TAG_GetOrigin( ent->targetname, name, info ); + return TAG_GetOrigin(ent->ownername, name, info); break; case TYPE_ANGLES: - //return TAG_GetAngles( ent->targetname, name, info ); - return TAG_GetAngles( ent->ownername, name, info ); + // return TAG_GetAngles( ent->targetname, name, info ); + return TAG_GetAngles(ent->ownername, name, info); break; } @@ -8224,453 +7064,431 @@ int CQuake3GameInterface::GetTag( int entID, const char *name, int lookup, vec3 // void CQuake3GameInterface::Lerp2Start( int taskID, int entID, float duration ) {} // void CQuake3GameInterface::Lerp2End( int taskID, int entID, float duration ) {} -void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, const char *data ) -{ - gentity_t *ent = &g_entities[entID]; - float float_data; - int int_data, toSet; - vec3_t vector_data; +void CQuake3GameInterface::Set(int taskID, int entID, const char *type_name, const char *data) { + gentity_t *ent = &g_entities[entID]; + float float_data; + int int_data, toSet; + vec3_t vector_data; // eezstreet: Add support for cvars getting modified thru ICARUS script - if(strlen(type_name) > 5 && !Q_stricmpn(type_name, "cvar_", 5)) - { - gi.cvar_set(type_name+5, data); + if (strlen(type_name) > 5 && !Q_stricmpn(type_name, "cvar_", 5)) { + gi.cvar_set(type_name + 5, data); return; } - //Set this for callbacks - toSet = GetIDForString( setTable, type_name ); + // Set this for callbacks + toSet = GetIDForString(setTable, type_name); - //TODO: Throw in a showscript command that will list each command and what they're doing... + // TODO: Throw in a showscript command that will list each command and what they're doing... // maybe as simple as printing that line of the script to the console preceeded by the person's name? // showscript can take any number of targetnames or "all"? Groupname? - switch ( toSet ) - { + switch (toSet) { case SET_ORIGIN: - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - G_SetOrigin( ent, vector_data ); - if ( Q_strncmp( "NPC_", ent->classname, 4 ) == 0 ) - {//hack for moving spawners - VectorCopy( vector_data, ent->s.origin); - } - if ( ent->client ) - {//clear jump start positions so we don't take damage when we land... + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + G_SetOrigin(ent, vector_data); + if (Q_strncmp("NPC_", ent->classname, 4) == 0) { // hack for moving spawners + VectorCopy(vector_data, ent->s.origin); + } + if (ent->client) { // clear jump start positions so we don't take damage when we land... ent->client->ps.jumpZStart = ent->client->ps.forceJumpZStart = vector_data[2]; } - gi.linkentity( ent ); + gi.linkentity(ent); break; case SET_TELEPORT_DEST: - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - if ( !Q3_SetTeleportDest( entID, vector_data ) ) - { - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + if (!Q3_SetTeleportDest(entID, vector_data)) { + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); return; } break; case SET_COPY_ORIGIN: - Q3_SetCopyOrigin( entID, (char *) data ); + Q3_SetCopyOrigin(entID, (char *)data); break; case SET_ANGLES: - //Q3_SetAngles( entID, *(vec3_t *) data); - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - Q3_SetAngles( entID, vector_data); + // Q3_SetAngles( entID, *(vec3_t *) data); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + Q3_SetAngles(entID, vector_data); break; case SET_XVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 0, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 0, float_data); break; case SET_YVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 1, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 1, float_data); break; case SET_ZVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 2, float_data); break; case SET_Z_OFFSET: - float_data = atof((char *) data); - Q3_SetOriginOffset( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetOriginOffset(entID, 2, float_data); break; case SET_ENEMY: - Q3_SetEnemy( entID, (char *) data ); + Q3_SetEnemy(entID, (char *)data); break; case SET_LEADER: - Q3_SetLeader( entID, (char *) data ); + Q3_SetLeader(entID, (char *)data); break; case SET_NAVGOAL: - if ( Q3_SetNavGoal( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); - return; //Don't call it back + if (Q3_SetNavGoal(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); + return; // Don't call it back } break; case SET_ANIM_UPPER: - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - return; //Don't call it back + if (Q3_SetAnimUpper(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + return; // Don't call it back } break; case SET_ANIM_LOWER: - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + if (Q3_SetAnimLower(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back } break; - case SET_ANIM_BOTH: - { - int both = 0; - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - both++; - } - else - { - DebugPrint( WL_ERROR, "SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - both++; - } - else - { - DebugPrint( WL_ERROR, "SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( both >= 2 ) - { - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); - } - if ( both ) - { - return; //Don't call it back - } + case SET_ANIM_BOTH: { + int both = 0; + if (Q3_SetAnimUpper(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + both++; + } else { + DebugPrint(WL_ERROR, "SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data); } - break; + if (Q3_SetAnimLower(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + both++; + } else { + DebugPrint(WL_ERROR, "SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data); + } + if (both >= 2) { + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); + } + if (both) { + return; // Don't call it back + } + } break; case SET_ANIM_HOLDTIME_LOWER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back break; case SET_ANIM_HOLDTIME_UPPER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + return; // Don't call it back break; case SET_ANIM_HOLDTIME_BOTH: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back break; case SET_PLAYER_TEAM: - Q3_SetPlayerTeam( entID, (char *) data ); + Q3_SetPlayerTeam(entID, (char *)data); break; case SET_ENEMY_TEAM: - Q3_SetEnemyTeam( entID, (char *) data ); + Q3_SetEnemyTeam(entID, (char *)data); break; case SET_HEALTH: - int_data = atoi((char *) data); - Q3_SetHealth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHealth(entID, int_data); break; case SET_ARMOR: - int_data = atoi((char *) data); - Q3_SetArmor( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetArmor(entID, int_data); break; case SET_BEHAVIOR_STATE: - if( !Q3_SetBState( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_BSTATE, taskID ); - return;//don't complete + if (!Q3_SetBState(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_BSTATE, taskID); + return; // don't complete } break; case SET_DEFAULT_BSTATE: - Q3_SetDefaultBState( entID, (char *) data ); + Q3_SetDefaultBState(entID, (char *)data); break; case SET_TEMP_BSTATE: - if( !Q3_SetTempBState( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_BSTATE, taskID ); - return;//don't complete + if (!Q3_SetTempBState(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_BSTATE, taskID); + return; // don't complete } break; case SET_CAPTURE: - Q3_SetCaptureGoal( entID, (char *) data ); + Q3_SetCaptureGoal(entID, (char *)data); break; - case SET_DPITCH://FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? - float_data = atof((char *) data); - Q3_SetDPitch( entID, float_data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + case SET_DPITCH: // FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? + float_data = atof((char *)data); + Q3_SetDPitch(entID, float_data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_DYAW: - float_data = atof((char *) data); - Q3_SetDYaw( entID, float_data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + float_data = atof((char *)data); + Q3_SetDYaw(entID, float_data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_EVENT: - Q3_SetEvent( entID, (char *) data ); + Q3_SetEvent(entID, (char *)data); break; case SET_VIEWTARGET: - Q3_SetViewTarget( entID, (char *) data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + Q3_SetViewTarget(entID, (char *)data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_WATCHTARGET: - Q3_SetWatchTarget( entID, (char *) data ); + Q3_SetWatchTarget(entID, (char *)data); break; case SET_VIEWENTITY: - Q3_SetViewEntity( entID, (char *) data ); + Q3_SetViewEntity(entID, (char *)data); break; case SET_LOOPSOUND: - Q3_SetLoopSound( entID, (char *) data ); + Q3_SetLoopSound(entID, (char *)data); break; case SET_ICARUS_FREEZE: case SET_ICARUS_UNFREEZE: - Q3_SetICARUSFreeze( entID, (char *) data, (qboolean)(toSet==SET_ICARUS_FREEZE) ); + Q3_SetICARUSFreeze(entID, (char *)data, (qboolean)(toSet == SET_ICARUS_FREEZE)); break; case SET_WEAPON: - Q3_SetWeapon ( entID, (char *) data); + Q3_SetWeapon(entID, (char *)data); break; case SET_ITEM: - Q3_SetItem ( entID, (char *) data); + Q3_SetItem(entID, (char *)data); break; case SET_WALKSPEED: - int_data = atoi((char *) data); - Q3_SetWalkSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetWalkSpeed(entID, int_data); break; case SET_RUNSPEED: - int_data = atoi((char *) data); - Q3_SetRunSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRunSpeed(entID, int_data); break; case SET_WIDTH: - int_data = atoi((char *) data); - Q3_SetWidth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetWidth(entID, int_data); return; break; case SET_YAWSPEED: - float_data = atof((char *) data); - Q3_SetYawSpeed ( entID, float_data); + float_data = atof((char *)data); + Q3_SetYawSpeed(entID, float_data); break; case SET_AGGRESSION: - int_data = atoi((char *) data); - Q3_SetAggression ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAggression(entID, int_data); break; case SET_AIM: - int_data = atoi((char *) data); - Q3_SetAim ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAim(entID, int_data); break; case SET_FRICTION: - int_data = atoi((char *) data); - Q3_SetFriction ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetFriction(entID, int_data); break; case SET_GRAVITY: - float_data = atof((char *) data); - Q3_SetGravity ( entID, float_data); + float_data = atof((char *)data); + Q3_SetGravity(entID, float_data); break; case SET_WAIT: - float_data = atof((char *) data); - Q3_SetWait( entID, float_data); + float_data = atof((char *)data); + Q3_SetWait(entID, float_data); break; case SET_FOLLOWDIST: - float_data = atof((char *) data); - Q3_SetFollowDist( entID, float_data); + float_data = atof((char *)data); + Q3_SetFollowDist(entID, float_data); break; case SET_SCALE: - float_data = atof((char *) data); - Q3_SetScale( entID, float_data); + float_data = atof((char *)data); + Q3_SetScale(entID, float_data); break; case SET_RENDER_CULL_RADIUS: - float_data = atof((char *) data); + float_data = atof((char *)data); Q3_SetRenderCullRadius(entID, float_data); break; case SET_COUNT: - Q3_SetCount( entID, (char *) data); + Q3_SetCount(entID, (char *)data); break; case SET_SHOT_SPACING: - int_data = atoi((char *) data); - Q3_SetShotSpacing( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetShotSpacing(entID, int_data); break; case SET_IGNOREPAIN: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnorePain( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnorePain( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnorePain(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnorePain(entID, qfalse); break; case SET_IGNOREENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qfalse); break; case SET_IGNOREALERTS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qfalse); break; case SET_DONTSHOOT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontShoot( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontShoot( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontShoot(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontShoot(entID, qfalse); break; case SET_DONTFIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFire( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontFire( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFire(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontFire(entID, qfalse); break; case SET_LOCKED_ENEMY: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLockedEnemy( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetLockedEnemy( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockedEnemy(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetLockedEnemy(entID, qfalse); break; case SET_NOTARGET: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoTarget( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetNoTarget( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoTarget(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetNoTarget(entID, qfalse); break; case SET_LEAN: - if(!Q_stricmp("right", ((char *)data))) - Q3_SetLean( entID, LEAN_RIGHT); - else if(!Q_stricmp("left", ((char *)data))) - Q3_SetLean( entID, LEAN_LEFT); + if (!Q_stricmp("right", ((char *)data))) + Q3_SetLean(entID, LEAN_RIGHT); + else if (!Q_stricmp("left", ((char *)data))) + Q3_SetLean(entID, LEAN_LEFT); else - Q3_SetLean( entID, LEAN_NONE); + Q3_SetLean(entID, LEAN_NONE); break; case SET_SHOOTDIST: - float_data = atof((char *) data); - Q3_SetShootDist( entID, float_data ); + float_data = atof((char *)data); + Q3_SetShootDist(entID, float_data); break; case SET_TIMESCALE: - Q3_SetTimeScale( entID, (char *) data ); + Q3_SetTimeScale(entID, (char *)data); break; case SET_VISRANGE: - float_data = atof((char *) data); - Q3_SetVisrange( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVisrange(entID, float_data); break; case SET_EARSHOT: - float_data = atof((char *) data); - Q3_SetEarshot( entID, float_data ); + float_data = atof((char *)data); + Q3_SetEarshot(entID, float_data); break; case SET_VIGILANCE: - float_data = atof((char *) data); - Q3_SetVigilance( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVigilance(entID, float_data); break; case SET_VFOV: - int_data = atoi((char *) data); - Q3_SetVFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetVFOV(entID, int_data); break; case SET_HFOV: - int_data = atoi((char *) data); - Q3_SetHFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHFOV(entID, int_data); break; case SET_TARGETNAME: - Q3_SetTargetName( entID, (char *) data ); + Q3_SetTargetName(entID, (char *)data); break; case SET_TARGET: - Q3_SetTarget( entID, (char *) data ); + Q3_SetTarget(entID, (char *)data); break; case SET_TARGET2: - Q3_SetTarget2( entID, (char *) data ); + Q3_SetTarget2(entID, (char *)data); break; case SET_LOCATION: - if ( !Q3_SetLocation( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_LOCATION, taskID ); + if (!Q3_SetLocation(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_LOCATION, taskID); return; } break; case SET_PAINTARGET: - Q3_SetPainTarget( entID, (char *) data ); + Q3_SetPainTarget(entID, (char *)data); break; case SET_DEFEND_TARGET: - DebugPrint( WL_WARNING, "SetDefendTarget unimplemented\n", entID ); - //Q3_SetEnemy( entID, (char *) data); + DebugPrint(WL_WARNING, "SetDefendTarget unimplemented\n", entID); + // Q3_SetEnemy( entID, (char *) data); break; case SET_PARM1: @@ -8689,7 +7507,7 @@ void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, co case SET_PARM14: case SET_PARM15: case SET_PARM16: - Q3_SetParm( entID, (toSet-SET_PARM1), (char *) data ); + Q3_SetParm(entID, (toSet - SET_PARM1), (char *)data); break; case SET_SPAWNSCRIPT: @@ -8706,170 +7524,169 @@ void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, co case SET_FFIRESCRIPT: case SET_FFDEATHSCRIPT: case SET_MINDTRICKSCRIPT: - if( !Q3_SetBehaviorSet(entID, toSet, (char *) data) ) - DebugPrint( WL_ERROR, "SetBehaviorSet: Invalid bSet %s\n", type_name ); + if (!Q3_SetBehaviorSet(entID, toSet, (char *)data)) + DebugPrint(WL_ERROR, "SetBehaviorSet: Invalid bSet %s\n", type_name); break; case SET_NO_MINDTRICK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoMindTrick( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoMindTrick(entID, qtrue); else - Q3_SetNoMindTrick( entID, qfalse); + Q3_SetNoMindTrick(entID, qfalse); break; - case SET_CINEMATIC_SKIPSCRIPT : - Q3_SetCinematicSkipScript((char *) data); + case SET_CINEMATIC_SKIPSCRIPT: + Q3_SetCinematicSkipScript((char *)data); break; - case SET_RAILCENTERTRACKLOCKED : - Rail_LockCenterOfTrack((char *) data); + case SET_RAILCENTERTRACKLOCKED: + Rail_LockCenterOfTrack((char *)data); break; - case SET_RAILCENTERTRACKUNLOCKED : - Rail_UnLockCenterOfTrack((char *) data); + case SET_RAILCENTERTRACKUNLOCKED: + Rail_UnLockCenterOfTrack((char *)data); break; case SET_DELAYSCRIPTTIME: - int_data = atoi((char *) data); - Q3_SetDelayScriptTime( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetDelayScriptTime(entID, int_data); break; case SET_CROUCHED: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCrouched( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCrouched(entID, qtrue); else - Q3_SetCrouched( entID, qfalse); + Q3_SetCrouched(entID, qfalse); break; case SET_WALKING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetWalking( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetWalking(entID, qtrue); else - Q3_SetWalking( entID, qfalse); + Q3_SetWalking(entID, qfalse); break; case SET_RUNNING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetRunning( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetRunning(entID, qtrue); else - Q3_SetRunning( entID, qfalse); + Q3_SetRunning(entID, qfalse); break; case SET_CHASE_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetChaseEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetChaseEnemies(entID, qtrue); else - Q3_SetChaseEnemies( entID, qfalse); + Q3_SetChaseEnemies(entID, qfalse); break; case SET_LOOK_FOR_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLookForEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLookForEnemies(entID, qtrue); else - Q3_SetLookForEnemies( entID, qfalse); + Q3_SetLookForEnemies(entID, qfalse); break; case SET_FACE_MOVE_DIR: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetFaceMoveDir( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetFaceMoveDir(entID, qtrue); else - Q3_SetFaceMoveDir( entID, qfalse); + Q3_SetFaceMoveDir(entID, qfalse); break; case SET_ALT_FIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAltFire( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAltFire(entID, qtrue); else - Q3_SetAltFire( entID, qfalse); + Q3_SetAltFire(entID, qfalse); break; case SET_DONT_FLEE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFlee( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFlee(entID, qtrue); else - Q3_SetDontFlee( entID, qfalse); + Q3_SetDontFlee(entID, qfalse); break; case SET_FORCED_MARCH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetForcedMarch( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForcedMarch(entID, qtrue); else - Q3_SetForcedMarch( entID, qfalse); + Q3_SetForcedMarch(entID, qfalse); break; case SET_NO_RESPONSE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoResponse( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoResponse(entID, qtrue); else - Q3_SetNoResponse( entID, qfalse); + Q3_SetNoResponse(entID, qfalse); break; case SET_NO_COMBAT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCombatTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCombatTalk(entID, qtrue); else - Q3_SetCombatTalk( entID, qfalse); + Q3_SetCombatTalk(entID, qfalse); break; case SET_NO_ALERT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAlertTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAlertTalk(entID, qtrue); else - Q3_SetAlertTalk( entID, qfalse); + Q3_SetAlertTalk(entID, qfalse); break; case SET_USE_CP_NEAREST: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseCpNearest( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseCpNearest(entID, qtrue); else - Q3_SetUseCpNearest( entID, qfalse); + Q3_SetUseCpNearest(entID, qfalse); break; case SET_NO_FORCE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoForce( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoForce(entID, qtrue); else - Q3_SetNoForce( entID, qfalse); + Q3_SetNoForce(entID, qfalse); break; case SET_NO_ACROBATICS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAcrobatics( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAcrobatics(entID, qtrue); else - Q3_SetNoAcrobatics( entID, qfalse); + Q3_SetNoAcrobatics(entID, qfalse); break; case SET_USE_SUBTITLES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseSubtitles( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseSubtitles(entID, qtrue); else - Q3_SetUseSubtitles( entID, qfalse); + Q3_SetUseSubtitles(entID, qfalse); break; case SET_NO_FALLTODEATH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoFallToDeath( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoFallToDeath(entID, qtrue); else - Q3_SetNoFallToDeath( entID, qfalse); + Q3_SetNoFallToDeath(entID, qfalse); break; case SET_DISMEMBERABLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDismemberable( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDismemberable(entID, qtrue); else - Q3_SetDismemberable( entID, qfalse); + Q3_SetDismemberable(entID, qfalse); break; case SET_MORELIGHT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetMoreLight( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetMoreLight(entID, qtrue); else - Q3_SetMoreLight( entID, qfalse); + Q3_SetMoreLight(entID, qfalse); break; - case SET_TREASONED: - DebugPrint( WL_VERBOSE, "SET_TREASONED is disabled, do not use\n" ); + DebugPrint(WL_VERBOSE, "SET_TREASONED is disabled, do not use\n"); /* G_TeamRetaliation( NULL, &g_entities[0], qfalse ); ffireLevel = FFIRE_LEVEL_RETALIATION; @@ -8877,116 +7694,112 @@ void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, co break; case SET_UNDYING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUndying( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUndying(entID, qtrue); else - Q3_SetUndying( entID, qfalse); + Q3_SetUndying(entID, qfalse); break; case SET_INVINCIBLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetInvincible( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvincible(entID, qtrue); else - Q3_SetInvincible( entID, qfalse); + Q3_SetInvincible(entID, qfalse); break; case SET_NOAVOID: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAvoid( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAvoid(entID, qtrue); else - Q3_SetNoAvoid( entID, qfalse); + Q3_SetNoAvoid(entID, qfalse); break; case SET_SOLID: - if(!Q_stricmp("true", ((char *)data))) - { - if ( !Q3_SetSolid( entID, qtrue) ) - { - Q3_TaskIDSet( ent, TID_RESIZE, taskID ); + if (!Q_stricmp("true", ((char *)data))) { + if (!Q3_SetSolid(entID, qtrue)) { + Q3_TaskIDSet(ent, TID_RESIZE, taskID); return; } - } - else - { - Q3_SetSolid( entID, qfalse); + } else { + Q3_SetSolid(entID, qfalse); } break; case SET_INVISIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetInvisible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvisible(entID, qtrue); else - Q3_SetInvisible( entID, qfalse ); + Q3_SetInvisible(entID, qfalse); break; case SET_VAMPIRE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetVampire( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetVampire(entID, qtrue); else - Q3_SetVampire( entID, qfalse ); + Q3_SetVampire(entID, qfalse); break; case SET_FORCE_INVINCIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetForceInvincible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForceInvincible(entID, qtrue); else - Q3_SetForceInvincible( entID, qfalse ); + Q3_SetForceInvincible(entID, qfalse); break; case SET_GREET_ALLIES: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetGreetAllies( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetGreetAllies(entID, qtrue); else - Q3_SetGreetAllies( entID, qfalse ); + Q3_SetGreetAllies(entID, qfalse); break; case SET_PLAYER_LOCKED: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetPlayerLocked( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetPlayerLocked(entID, qtrue); else - Q3_SetPlayerLocked( entID, qfalse ); + Q3_SetPlayerLocked(entID, qfalse); break; case SET_LOCK_PLAYER_WEAPONS: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetLockPlayerWeapons( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockPlayerWeapons(entID, qtrue); else - Q3_SetLockPlayerWeapons( entID, qfalse ); + Q3_SetLockPlayerWeapons(entID, qfalse); break; case SET_NO_IMPACT_DAMAGE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetNoImpactDamage( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoImpactDamage(entID, qtrue); else - Q3_SetNoImpactDamage( entID, qfalse ); + Q3_SetNoImpactDamage(entID, qfalse); break; case SET_FORWARDMOVE: - int_data = atoi((char *) data); - Q3_SetForwardMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetForwardMove(entID, int_data); break; case SET_RIGHTMOVE: - int_data = atoi((char *) data); - Q3_SetRightMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRightMove(entID, int_data); break; case SET_LOCKYAW: - Q3_SetLockAngle( entID, data); + Q3_SetLockAngle(entID, data); break; case SET_CAMERA_GROUP: Q3_CameraGroup(entID, (char *)data); break; case SET_CAMERA_GROUP_Z_OFS: - float_data = atof((char *) data); - Q3_CameraGroupZOfs( float_data ); + float_data = atof((char *)data); + Q3_CameraGroupZOfs(float_data); break; case SET_CAMERA_GROUP_TAG: - Q3_CameraGroupTag( (char *)data ); + Q3_CameraGroupTag((char *)data); break; - //FIXME: put these into camera commands + // FIXME: put these into camera commands case SET_LOOK_TARGET: Q3_LookTarget(entID, (char *)data); break; @@ -9018,104 +7831,89 @@ void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, co case SET_FACEHAPPY: case SET_FACESHOCKED: case SET_FACENORMAL: - float_data = atof((char *) data); + float_data = atof((char *)data); Q3_Face(entID, toSet, float_data); break; case SET_SCROLLTEXT: - Q3_ScrollText( (char *)data ); + Q3_ScrollText((char *)data); break; case SET_LCARSTEXT: - Q3_LCARSText( (char *)data ); + Q3_LCARSText((char *)data); break; case SET_CENTERTEXT: - CenterPrint( (char *)data ); + CenterPrint((char *)data); break; case SET_CAPTIONTEXTCOLOR: - Q3_SetCaptionTextColor ( (char *)data ); + Q3_SetCaptionTextColor((char *)data); break; case SET_CENTERTEXTCOLOR: - Q3_SetCenterTextColor ( (char *)data ); + Q3_SetCenterTextColor((char *)data); break; case SET_SCROLLTEXTCOLOR: - Q3_SetScrollTextColor ( (char *)data ); + Q3_SetScrollTextColor((char *)data); break; case SET_PLAYER_USABLE: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetPlayerUsable(entID, qtrue); - } - else - { + } else { Q3_SetPlayerUsable(entID, qfalse); } break; case SET_STARTFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetStartFrame(entID, int_data); break; case SET_ENDFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetEndFrame(entID, int_data); - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); return; break; case SET_ANIMFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetAnimFrame(entID, int_data); return; break; case SET_LOOP_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetLoopAnim(entID, qtrue); - } - else - { + } else { Q3_SetLoopAnim(entID, qfalse); } break; case SET_INTERFACE: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetInterface(entID, "1"); - } - else - { + } else { Q3_SetInterface(entID, "0"); } break; case SET_SHIELDS: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetShields(entID, qtrue); - } - else - { + } else { Q3_SetShields(entID, qfalse); } break; case SET_SABERACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetSaberActive( entID, qtrue ); - } - else - { - Q3_SetSaberActive( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetSaberActive(entID, qtrue); + } else { + Q3_SetSaberActive(entID, qfalse); } break; @@ -9123,171 +7921,134 @@ void CQuake3GameInterface::Set( int taskID, int entID, const char *type_name, co // Make a specific Saber 1 Blade active. case SET_SABER1BLADEON: // Get which Blade to activate. - int_data = atoi((char *) data); - Q3_SetSaberBladeActive( entID, 0, int_data, qtrue ); + int_data = atoi((char *)data); + Q3_SetSaberBladeActive(entID, 0, int_data, qtrue); break; // Make a specific Saber 1 Blade inactive. case SET_SABER1BLADEOFF: // Get which Blade to deactivate. - int_data = atoi((char *) data); - Q3_SetSaberBladeActive( entID, 0, int_data, qfalse ); + int_data = atoi((char *)data); + Q3_SetSaberBladeActive(entID, 0, int_data, qfalse); break; // Make a specific Saber 2 Blade active. case SET_SABER2BLADEON: // Get which Blade to activate. - int_data = atoi((char *) data); - Q3_SetSaberBladeActive( entID, 1, int_data, qtrue ); + int_data = atoi((char *)data); + Q3_SetSaberBladeActive(entID, 1, int_data, qtrue); break; // Make a specific Saber 2 Blade inactive. case SET_SABER2BLADEOFF: // Get which Blade to deactivate. - int_data = atoi((char *) data); - Q3_SetSaberBladeActive( entID, 1, int_data, qfalse ); + int_data = atoi((char *)data); + Q3_SetSaberBladeActive(entID, 1, int_data, qfalse); break; case SET_DAMAGEENTITY: - int_data = atoi((char *) data); - G_Damage( ent, ent, ent, NULL, NULL, int_data, 0, MOD_UNKNOWN ); + int_data = atoi((char *)data); + G_Damage(ent, ent, ent, NULL, NULL, int_data, 0, MOD_UNKNOWN); break; case SET_SABER_ORIGIN: - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - WP_SetSaberOrigin( ent, vector_data ); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + WP_SetSaberOrigin(ent, vector_data); break; case SET_ADJUST_AREA_PORTALS: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetAdjustAreaPortals( entID, qtrue ); - } - else - { - Q3_SetAdjustAreaPortals( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetAdjustAreaPortals(entID, qtrue); + } else { + Q3_SetAdjustAreaPortals(entID, qfalse); } break; case SET_DMG_BY_HEAVY_WEAP_ONLY: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetDmgByHeavyWeapOnly( entID, qtrue ); - } - else - { - Q3_SetDmgByHeavyWeapOnly( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetDmgByHeavyWeapOnly(entID, qtrue); + } else { + Q3_SetDmgByHeavyWeapOnly(entID, qfalse); } break; case SET_SHIELDED: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetShielded( entID, qtrue ); - } - else - { - Q3_SetShielded( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetShielded(entID, qtrue); + } else { + Q3_SetShielded(entID, qfalse); } break; case SET_NO_GROUPS: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetNoGroups( entID, qtrue ); - } - else - { - Q3_SetNoGroups( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetNoGroups(entID, qtrue); + } else { + Q3_SetNoGroups(entID, qfalse); } break; case SET_FIRE_WEAPON: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFireWeapon( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFireWeapon( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFireWeapon(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFireWeapon(entID, qfalse); } break; case SET_FIRE_WEAPON_NO_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFireWeaponNoAnim( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFireWeaponNoAnim( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFireWeaponNoAnim(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFireWeaponNoAnim(entID, qfalse); } break; case SET_SAFE_REMOVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetSafeRemove( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetSafeRemove( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetSafeRemove(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetSafeRemove(entID, qfalse); } break; case SET_BOBA_JET_PACK: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetBobaJetPack( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetBobaJetPack( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetBobaJetPack(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetBobaJetPack(entID, qfalse); } break; case SET_INACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetInactive( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetInactive( entID, qfalse); - } - else if(!Q_stricmp("unlocked", ((char *)data))) - { -extern void UnLockDoors(gentity_t *const ent); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetInactive(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetInactive(entID, qfalse); + } else if (!Q_stricmp("unlocked", ((char *)data))) { + extern void UnLockDoors(gentity_t *const ent); UnLockDoors(&g_entities[entID]); - } - else if(!Q_stricmp("locked", ((char *)data))) - { -extern void LockDoors(gentity_t *const ent); + } else if (!Q_stricmp("locked", ((char *)data))) { + extern void LockDoors(gentity_t *const ent); LockDoors(&g_entities[entID]); } break; case SET_END_SCREENDISSOLVE: - gi.SendConsoleCommand( "endscreendissolve\n"); + gi.SendConsoleCommand("endscreendissolve\n"); break; case SET_FUNC_USABLE_VISIBLE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qfalse); } break; case SET_NO_KNOCKBACK: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetNoKnockback(entID, qtrue); - } - else - { + } else { Q3_SetNoKnockback(entID, qfalse); } break; @@ -9297,66 +8058,58 @@ extern void LockDoors(gentity_t *const ent); // the "timescale" and "skippingCinematic" cvars will be set back to normal in the Video code, so doing a // skip will now only skip one section of a multiple-part story (eg VOY1 bridge sequence) // -// if ( g_timescale->value <= 1.0f ) - { - gi.SendConsoleCommand( va("inGameCinematic %s\n", (char *)data) ); - } + // if ( g_timescale->value <= 1.0f ) + { gi.SendConsoleCommand(va("inGameCinematic %s\n", (char *)data)); } break; case SET_VIDEO_FADE_IN: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cl_VidFadeUp", "1"); - } - else - { + } else { gi.cvar_set("cl_VidFadeUp", "0"); } break; case SET_VIDEO_FADE_OUT: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cl_VidFadeDown", "1"); - } - else - { + } else { gi.cvar_set("cl_VidFadeDown", "0"); } break; case SET_REMOVE_TARGET: - Q3_SetRemoveTarget( entID, (const char *) data ); + Q3_SetRemoveTarget(entID, (const char *)data); break; case SET_LOADGAME: - gi.SendConsoleCommand( va("load %s\n", (const char *) data ) ); + gi.SendConsoleCommand(va("load %s\n", (const char *)data)); break; case SET_MENU_SCREEN: - //UI_SetActiveMenu( (const char *) data ); - gi.SendConsoleCommand( va("uimenu %s\n", (char *)data) ); + // UI_SetActiveMenu( (const char *) data ); + gi.SendConsoleCommand(va("uimenu %s\n", (char *)data)); break; case SET_OBJECTIVE_SHOW: - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text gi.cvar_set("cg_updatedDataPadObjective", "1"); - Q3_SetObjective((const char *) data ,SET_OBJ_SHOW); - Q3_SetObjective((const char *) data ,SET_OBJ_PENDING); + Q3_SetObjective((const char *)data, SET_OBJ_SHOW); + Q3_SetObjective((const char *)data, SET_OBJ_PENDING); break; case SET_OBJECTIVE_HIDE: - Q3_SetObjective((const char *) data ,SET_OBJ_HIDE); + Q3_SetObjective((const char *)data, SET_OBJ_HIDE); break; case SET_OBJECTIVE_SUCCEEDED: - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text gi.cvar_set("cg_updatedDataPadObjective", "1"); - Q3_SetObjective((const char *) data ,SET_OBJ_SUCCEEDED); + Q3_SetObjective((const char *)data, SET_OBJ_SUCCEEDED); break; case SET_OBJECTIVE_SUCCEEDED_NO_UPDATE: - Q3_SetObjective((const char *) data ,SET_OBJ_SUCCEEDED); + Q3_SetObjective((const char *)data, SET_OBJ_SUCCEEDED); break; case SET_OBJECTIVE_FAILED: - Q3_SetObjective((const char *) data ,SET_OBJ_FAILED); + Q3_SetObjective((const char *)data, SET_OBJ_FAILED); break; case SET_OBJECTIVE_CLEARALL: @@ -9364,15 +8117,15 @@ extern void LockDoors(gentity_t *const ent); break; case SET_MISSIONFAILED: - Q3_SetMissionFailed((const char *) data); + Q3_SetMissionFailed((const char *)data); break; case SET_MISSIONSTATUSTEXT: - Q3_SetStatusText((const char *) data); + Q3_SetStatusText((const char *)data); break; case SET_MISSIONSTATUSTIME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); cg.missionStatusDeadTime = level.time + int_data; break; @@ -9381,33 +8134,27 @@ extern void LockDoors(gentity_t *const ent); break; case SET_SKILL: -// //can never be set + // //can never be set break; case SET_DISABLE_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetDisableShaderAnims( entID, qtrue); - } - else - { - Q3_SetDisableShaderAnims( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetDisableShaderAnims(entID, qtrue); + } else { + Q3_SetDisableShaderAnims(entID, qfalse); } break; case SET_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetShaderAnim( entID, qtrue); - } - else - { - Q3_SetShaderAnim( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetShaderAnim(entID, qtrue); + } else { + Q3_SetShaderAnim(entID, qfalse); } break; case SET_MUSIC_STATE: - Q3_SetMusicState( (char *) data ); + Q3_SetMusicState((char *)data); break; case SET_CLEAN_DAMAGING_ENTS: @@ -9415,12 +8162,9 @@ extern void LockDoors(gentity_t *const ent); break; case SET_HUD: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cg_drawHUD", "1"); - } - else - { + } else { gi.cvar_set("cg_drawHUD", "0"); } break; @@ -9441,201 +8185,178 @@ extern void LockDoors(gentity_t *const ent); case SET_FORCE_ABSORB_LEVEL: case SET_FORCE_DRAIN_LEVEL: case SET_FORCE_SIGHT_LEVEL: - int_data = atoi((char *) data); - Q3_SetForcePowerLevel( entID, (toSet-SET_FORCE_HEAL_LEVEL), int_data ); + int_data = atoi((char *)data); + Q3_SetForcePowerLevel(entID, (toSet - SET_FORCE_HEAL_LEVEL), int_data); break; case SET_SABER1: case SET_SABER2: - WP_SetSaber( &g_entities[entID], toSet-SET_SABER1, (char *)data ); + WP_SetSaber(&g_entities[entID], toSet - SET_SABER1, (char *)data); break; case SET_PLAYERMODEL: - G_ChangePlayerModel( &g_entities[entID], (const char *)data ); + G_ChangePlayerModel(&g_entities[entID], (const char *)data); break; // NOTE: Preconditions for entering a vehicle still exist. This is not assured to work. -Areis case SET_VEHICLE: - Use( entID, (char *)data ); -// G_DriveVehicle( &g_entities[entID], NULL, (char *)data ); + Use(entID, (char *)data); + // G_DriveVehicle( &g_entities[entID], NULL, (char *)data ); break; case SET_SECURITY_KEY: - Q3_GiveSecurityKey( entID, (char *)data ); + Q3_GiveSecurityKey(entID, (char *)data); break; case SET_SABER1_COLOR1: case SET_SABER1_COLOR2: - WP_SaberSetColor( &g_entities[entID], 0, toSet-SET_SABER1_COLOR1, (char *)data ); + WP_SaberSetColor(&g_entities[entID], 0, toSet - SET_SABER1_COLOR1, (char *)data); break; case SET_SABER2_COLOR1: case SET_SABER2_COLOR2: - WP_SaberSetColor( &g_entities[entID], 1, toSet-SET_SABER2_COLOR1, (char *)data ); + WP_SaberSetColor(&g_entities[entID], 1, toSet - SET_SABER2_COLOR1, (char *)data); break; case SET_DISMEMBER_LIMB: - Q3_DismemberLimb( entID, (char *)data ); + Q3_DismemberLimb(entID, (char *)data); break; case SET_NO_PVS_CULL: - Q3_SetBroadcast( entID, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetBroadcast(entID, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; // Set a Saboteur to cloak (true) or un-cloak (false). - case SET_CLOAK: // Created: 01/08/03 by AReis. -extern void Saboteur_Cloak( gentity_t *self ); - if( Q_stricmp("true", ((char *)data)) == 0 ) - { - Saboteur_Cloak( &g_entities[entID] ); - } - else - { - Saboteur_Decloak( &g_entities[entID] ); + case SET_CLOAK: // Created: 01/08/03 by AReis. + extern void Saboteur_Cloak(gentity_t * self); + if (Q_stricmp("true", ((char *)data)) == 0) { + Saboteur_Cloak(&g_entities[entID]); + } else { + Saboteur_Decloak(&g_entities[entID]); } break; case SET_FORCE_HEAL: - Q3_SetForcePower( entID, FP_HEAL, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_HEAL, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_SPEED: - Q3_SetForcePower( entID, FP_SPEED, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_SPEED, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_PUSH: - Q3_SetForcePower( entID, FP_PUSH, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_PUSH, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_PUSH_FAKE: - ForceThrow( &g_entities[entID], qfalse, qtrue ); + ForceThrow(&g_entities[entID], qfalse, qtrue); break; case SET_FORCE_PULL: - Q3_SetForcePower( entID, FP_PULL, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_PULL, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_MIND_TRICK: - Q3_SetForcePower( entID, FP_TELEPATHY, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_TELEPATHY, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_GRIP: - Q3_SetForcePower( entID, FP_GRIP, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_GRIP, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_LIGHTNING: - Q3_SetForcePower( entID, FP_LIGHTNING, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_LIGHTNING, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_SABERTHROW: - Q3_SetForcePower( entID, FP_SABERTHROW, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_SABERTHROW, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_RAGE: - Q3_SetForcePower( entID, FP_RAGE, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_RAGE, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_PROTECT: - Q3_SetForcePower( entID, FP_PROTECT, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_PROTECT, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_ABSORB: - Q3_SetForcePower( entID, FP_ABSORB, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_ABSORB, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; case SET_FORCE_DRAIN: - Q3_SetForcePower( entID, FP_DRAIN, (qboolean)(Q_stricmp("true",(char*)data)==0) ); + Q3_SetForcePower(entID, FP_DRAIN, (qboolean)(Q_stricmp("true", (char *)data) == 0)); break; -extern cvar_t *g_char_model; -extern cvar_t *g_char_skin_head; -extern cvar_t *g_char_skin_torso; -extern cvar_t *g_char_skin_legs; - case SET_WINTER_GEAR: // Created: 03/26/03 by AReis. + extern cvar_t *g_char_model; + extern cvar_t *g_char_skin_head; + extern cvar_t *g_char_skin_torso; + extern cvar_t *g_char_skin_legs; + case SET_WINTER_GEAR: // Created: 03/26/03 by AReis. { // If this is a (fake) Player NPC or this IS the Player... - if ( entID == 0 || ( ent->NPC_type && Q_stricmp( ent->NPC_type, "player" ) == 0 ) ) - { + if (entID == 0 || (ent->NPC_type && Q_stricmp(ent->NPC_type, "player") == 0)) { char strSkin[MAX_QPATH]; // Set the Winter Gear Skin if true, otherwise set back to normal configuration. - if( Q_stricmp( "true", ((char *)data) ) == 0 ) - { - Com_sprintf( strSkin, sizeof( strSkin ), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, "torso_g1", "lower_e1" ); - } - else if(Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && Q_stricmp(g_char_skin_legs->string, "model_default") == 0) - { - Com_sprintf( strSkin, sizeof( strSkin ), "models/players/%s/model_default.skin", g_char_model->string ); - } - else - { - Com_sprintf( strSkin, sizeof( strSkin ), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string ); + if (Q_stricmp("true", ((char *)data)) == 0) { + Com_sprintf(strSkin, sizeof(strSkin), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, "torso_g1", "lower_e1"); + } else if (Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && + Q_stricmp(g_char_skin_legs->string, "model_default") == 0) { + Com_sprintf(strSkin, sizeof(strSkin), "models/players/%s/model_default.skin", g_char_model->string); + } else { + Com_sprintf(strSkin, sizeof(strSkin), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, + g_char_skin_legs->string); } - int iSkinID = gi.RE_RegisterSkin( strSkin ); - if ( iSkinID ) - { - gi.G2API_SetSkin( &ent->ghoul2[ent->playerModel], G_SkinIndex( strSkin ), iSkinID ); + int iSkinID = gi.RE_RegisterSkin(strSkin); + if (iSkinID) { + gi.G2API_SetSkin(&ent->ghoul2[ent->playerModel], G_SkinIndex(strSkin), iSkinID); } } break; } case SET_NO_ANGLES: - if ( entID >= 0 && entID < ENTITYNUM_WORLD ) - { - if ( (Q_stricmp("true",(char*)data)==0) ) - { + if (entID >= 0 && entID < ENTITYNUM_WORLD) { + if ((Q_stricmp("true", (char *)data) == 0)) { g_entities[entID].flags |= FL_NO_ANGLES; - } - else - { + } else { g_entities[entID].flags &= ~FL_NO_ANGLES; } } break; case SET_SKIN: // If this is a (fake) Player NPC or this IS the Player... - {//just blindly sets whatever skin you set! include full path after "base/"... eg: "models/players/tavion_new/model_possessed.skin" + { // just blindly sets whatever skin you set! include full path after "base/"... eg: "models/players/tavion_new/model_possessed.skin" gentity_t *ent = &g_entities[entID]; - if ( ent && ent->inuse && ent->ghoul2.size() ) - { - int iSkinID = gi.RE_RegisterSkin( (char *)data ); - if ( iSkinID ) - { - gi.G2API_SetSkin( &ent->ghoul2[ent->playerModel], G_SkinIndex( (char *)data ), iSkinID ); + if (ent && ent->inuse && ent->ghoul2.size()) { + int iSkinID = gi.RE_RegisterSkin((char *)data); + if (iSkinID) { + gi.G2API_SetSkin(&ent->ghoul2[ent->playerModel], G_SkinIndex((char *)data), iSkinID); } } } break; default: - //DebugPrint( WL_ERROR, "Set: '%s' is not a valid set field\n", type_name ); - SetVar( taskID, entID, type_name, data ); - PrisonerObjCheck(type_name,data); + // DebugPrint( WL_ERROR, "Set: '%s' is not a valid set field\n", type_name ); + SetVar(taskID, entID, type_name, data); + PrisonerObjCheck(type_name, data); break; } - IIcarusInterface::GetIcarus()->Completed( ent->m_iIcarusID, taskID ); + IIcarusInterface::GetIcarus()->Completed(ent->m_iIcarusID, taskID); } -void CQuake3GameInterface::PrisonerObjCheck(const char *name,const char *data) -{ - float float_data = 0.0f; - int holdData; +void CQuake3GameInterface::PrisonerObjCheck(const char *name, const char *data) { + float float_data = 0.0f; + int holdData; - if (!Q_stricmp("ui_prisonerobj_currtotal",name)) - { - GetFloatVariable( name, &float_data ); - holdData = (int) float_data; - gi.cvar_set("ui_prisonerobj_currtotal", va("%d",holdData)); - } - else if (!Q_stricmp("ui_prisonerobj_maxtotal",name)) - { + if (!Q_stricmp("ui_prisonerobj_currtotal", name)) { + GetFloatVariable(name, &float_data); + holdData = (int)float_data; + gi.cvar_set("ui_prisonerobj_currtotal", va("%d", holdData)); + } else if (!Q_stricmp("ui_prisonerobj_maxtotal", name)) { gi.cvar_set("ui_prisonerobj_maxtotal", data); } - } // Uses an entity. -void CQuake3GameInterface::Use( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +void CQuake3GameInterface::Use(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - DebugPrint( WL_WARNING, "Use: invalid entID %d\n", entID ); + if (!ent) { + DebugPrint(WL_WARNING, "Use: invalid entID %d\n", entID); return; } - if( !name || !name[0] ) - { - DebugPrint( WL_WARNING, "Use: string is NULL!\n" ); + if (!name || !name[0]) { + DebugPrint(WL_WARNING, "Use: string is NULL!\n"); return; } - if ( ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST - GEntity_UseFunc( ent->activator, ent, ent ); + if (ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + GEntity_UseFunc(ent->activator, ent, ent); return; } /* @@ -9644,42 +8365,29 @@ void CQuake3GameInterface::Use( int entID, const char *name ) ent->client->usercmd.buttons |= BUTTON_USE; } */ - G_UseTargets2( ent, ent, name ); + G_UseTargets2(ent, ent, name); } -void CQuake3GameInterface::Activate( int entID, const char *name ) -{ - Q3_SetInactive( entID, qtrue ); -} +void CQuake3GameInterface::Activate(int entID, const char *name) { Q3_SetInactive(entID, qtrue); } -void CQuake3GameInterface::Deactivate( int entID, const char *name ) -{ - Q3_SetInactive( entID, qfalse ); -} +void CQuake3GameInterface::Deactivate(int entID, const char *name) { Q3_SetInactive(entID, qfalse); } // Kill an entity. -void CQuake3GameInterface::Kill( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; - int o_health; +void CQuake3GameInterface::Kill(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *victim = NULL; + int o_health; - if( !Q_stricmp( name, "self") ) - { + if (!Q_stricmp(name, "self")) { victim = ent; - } - else if( !Q_stricmp( name, "enemy" ) ) - { + } else if (!Q_stricmp(name, "enemy")) { victim = ent->enemy; - } - else - { - victim = G_Find (NULL, FOFS(targetname), (char *) name ); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); } - if ( !victim ) - { - DebugPrint( WL_WARNING, "Kill: can't find %s\n", name); + if (!victim) { + DebugPrint(WL_WARNING, "Kill: can't find %s\n", name); return; } @@ -9690,140 +8398,100 @@ void CQuake3GameInterface::Kill( int entID, const char *name ) return; } */ - if ( victim == ent ) - {//don't ICARUS_FreeEnt me, I'm in the middle of a script! (FIXME: shouldn't ICARUS handle this internally?) + if (victim == ent) { // don't ICARUS_FreeEnt me, I'm in the middle of a script! (FIXME: shouldn't ICARUS handle this internally?) victim->svFlags |= SVF_KILLED_SELF; } o_health = victim->health; victim->health = 0; - if ( victim->client ) - { + if (victim->client) { victim->flags |= FL_NO_KNOCKBACK; } - //G_SetEnemy(victim, ent); - if( victim->e_DieFunc != dieF_NULL ) // check can be omitted + // G_SetEnemy(victim, ent); + if (victim->e_DieFunc != dieF_NULL) // check can be omitted { - GEntity_DieFunc( victim, NULL, NULL, o_health, MOD_UNKNOWN ); + GEntity_DieFunc(victim, NULL, NULL, o_health, MOD_UNKNOWN); } } // Remove an entity. -void CQuake3GameInterface::Remove( int entID, const char *name ) -{ +void CQuake3GameInterface::Remove(int entID, const char *name) { gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; + gentity_t *victim = NULL; - if( !Q_stricmp( "self", name ) ) - { + if (!Q_stricmp("self", name)) { victim = ent; - if ( !victim ) - { - DebugPrint( WL_WARNING, "Remove: can't find %s\n", name ); + if (!victim) { + DebugPrint(WL_WARNING, "Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else if( !Q_stricmp( "enemy", name ) ) - { + Q3_RemoveEnt(victim); + } else if (!Q_stricmp("enemy", name)) { victim = ent->enemy; - if ( !victim ) - { - DebugPrint( WL_WARNING, "Remove: can't find %s\n", name ); + if (!victim) { + DebugPrint(WL_WARNING, "Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else - { - victim = G_Find( NULL, FOFS(targetname), (char *) name ); - if ( !victim ) - { - DebugPrint( WL_WARNING, "Remove: can't find %s\n", name ); + Q3_RemoveEnt(victim); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); + if (!victim) { + DebugPrint(WL_WARNING, "Remove: can't find %s\n", name); return; } - while ( victim ) - { - Q3_RemoveEnt( victim ); - victim = G_Find( victim, FOFS(targetname), (char *) name ); + while (victim) { + Q3_RemoveEnt(victim); + victim = G_Find(victim, FOFS(targetname), (char *)name); } } } // Get a random (float) number. -float CQuake3GameInterface::Random( float min, float max ) -{ - return ((rand() * (max - min)) / (float)RAND_MAX) + min; -} +float CQuake3GameInterface::Random(float min, float max) { return ((rand() * (max - min)) / (float)RAND_MAX) + min; } -void CQuake3GameInterface::Play( int taskID, int entID, const char *type, const char *name ) -{ +void CQuake3GameInterface::Play(int taskID, int entID, const char *type, const char *name) { gentity_t *ent = &g_entities[entID]; - if ( !Q_stricmp( type, "PLAY_ROFF" ) ) - { + if (!Q_stricmp(type, "PLAY_ROFF")) { // Try to load the requested ROFF - if ( G_LoadRoff( name ) ) - { - ent->roff = G_NewString( name ); + if (G_LoadRoff(name)) { + ent->roff = G_NewString(name); // Start the roff from the beginning ent->roff_ctr = 0; - //Save this off for later - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + // Save this off for later + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // Let the ROFF playing start. ent->next_roff_time = level.time; // These need to be initialised up front... - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( ent->currentAngles, ent->pos2 ); - gi.linkentity( ent ); + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(ent->currentAngles, ent->pos2); + gi.linkentity(ent); } } } -//Camera functions -void CQuake3GameInterface::CameraPan( vec3_t angles, vec3_t dir, float duration ) -{ - CGCam_Pan( angles, dir, duration ); -} - -void CQuake3GameInterface::CameraMove( vec3_t origin, float duration ) -{ - CGCam_Move( origin, duration ); -} +// Camera functions +void CQuake3GameInterface::CameraPan(vec3_t angles, vec3_t dir, float duration) { CGCam_Pan(angles, dir, duration); } -void CQuake3GameInterface::CameraZoom( float fov, float duration ) -{ - CGCam_Zoom( fov, duration ); -} +void CQuake3GameInterface::CameraMove(vec3_t origin, float duration) { CGCam_Move(origin, duration); } -void CQuake3GameInterface::CameraRoll( float angle, float duration ) -{ - CGCam_Roll( angle, duration ); -} +void CQuake3GameInterface::CameraZoom(float fov, float duration) { CGCam_Zoom(fov, duration); } -void CQuake3GameInterface::CameraFollow( const char *name, float speed, float initLerp ) -{ - CGCam_Follow( name, speed, initLerp ); -} +void CQuake3GameInterface::CameraRoll(float angle, float duration) { CGCam_Roll(angle, duration); } -void CQuake3GameInterface::CameraTrack( const char *name, float speed, float initLerp ) -{ - CGCam_Track( name, speed, initLerp ); -} +void CQuake3GameInterface::CameraFollow(const char *name, float speed, float initLerp) { CGCam_Follow(name, speed, initLerp); } -void CQuake3GameInterface::CameraDistance( float dist, float initLerp ) -{ - CGCam_Distance( dist, initLerp ); -} +void CQuake3GameInterface::CameraTrack(const char *name, float speed, float initLerp) { CGCam_Track(name, speed, initLerp); } -void CQuake3GameInterface::CameraFade( float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration ) -{ - vec4_t src, dst; +void CQuake3GameInterface::CameraDistance(float dist, float initLerp) { CGCam_Distance(dist, initLerp); } + +void CQuake3GameInterface::CameraFade(float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration) { + vec4_t src, dst; src[0] = sr; src[1] = sg; @@ -9835,51 +8503,35 @@ void CQuake3GameInterface::CameraFade( float sr, float sg, float sb, float sa, f dst[2] = db; dst[3] = da; - CGCam_Fade( src, dst, duration ); + CGCam_Fade(src, dst, duration); } -void CQuake3GameInterface::CameraPath( const char *name ) -{ - CGCam_StartRoff( G_NewString( name ) ); -} +void CQuake3GameInterface::CameraPath(const char *name) { CGCam_StartRoff(G_NewString(name)); } -void CQuake3GameInterface::CameraEnable( void ) -{ - CGCam_Enable(); -} +void CQuake3GameInterface::CameraEnable(void) { CGCam_Enable(); } -void CQuake3GameInterface::CameraDisable( void ) -{ - CGCam_Disable(); -} +void CQuake3GameInterface::CameraDisable(void) { CGCam_Disable(); } -void CQuake3GameInterface::CameraShake( float intensity, int duration ) -{ - CGCam_Shake( intensity, duration ); -} +void CQuake3GameInterface::CameraShake(float intensity, int duration) { CGCam_Shake(intensity, duration); } -int CQuake3GameInterface::GetFloat( int entID, const char *name, float *value ) -{ - gentity_t *ent = &g_entities[entID]; -// gclient_t *client; +int CQuake3GameInterface::GetFloat(int entID, const char *name, float *value) { + gentity_t *ent = &g_entities[entID]; + // gclient_t *client; - if ( !ent ) - { + if (!ent) { return false; } - if( strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5) ) - { - *value = (float)gi.Cvar_VariableIntegerValue(name+5); + if (strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5)) { + *value = (float)gi.Cvar_VariableIntegerValue(name + 5); return true; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -9896,12 +8548,11 @@ int CQuake3GameInterface::GetFloat( int entID, const char *name, float *value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if (ent->parms == NULL) - { - DebugPrint( WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname ); - return false; // would prefer qfalse, but I'm fitting in with what's here + if (ent->parms == NULL) { + DebugPrint(WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname); + return false; // would prefer qfalse, but I'm fitting in with what's here } - *value = atof( ent->parms->parm[toGet - SET_PARM1] ); + *value = atof(ent->parms->parm[toGet - SET_PARM1]); break; case SET_COUNT: @@ -9916,28 +8567,25 @@ int CQuake3GameInterface::GetFloat( int entID, const char *name, float *value ) *value = g_spskill->integer; break; - case SET_XVELOCITY://## %f="0.0" # Velocity along X axis - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname ); + case SET_XVELOCITY: //## %f="0.0" # Velocity along X axis + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[0]; break; - case SET_YVELOCITY://## %f="0.0" # Velocity along Y axis - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname ); + case SET_YVELOCITY: //## %f="0.0" # Velocity along Y axis + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[1]; break; - case SET_ZVELOCITY://## %f="0.0" # Velocity along Z axis - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname ); + case SET_ZVELOCITY: //## %f="0.0" # Velocity along Z axis + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[2]; @@ -9947,576 +8595,515 @@ int CQuake3GameInterface::GetFloat( int entID, const char *name, float *value ) *value = ent->currentOrigin[2] - ent->s.origin[2]; break; - case SET_DPITCH://## %f="0.0" # Pitch for NPC to turn to - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_DPITCH, %s not an NPC\n", ent->targetname ); + case SET_DPITCH: //## %f="0.0" # Pitch for NPC to turn to + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_DPITCH, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->desiredPitch; break; - case SET_DYAW://## %f="0.0" # Yaw for NPC to turn to - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_DYAW, %s not an NPC\n", ent->targetname ); + case SET_DYAW: //## %f="0.0" # Yaw for NPC to turn to + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_DYAW, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->desiredPitch; break; - case SET_WIDTH://## %f="0.0" # Width of NPC bounding box - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_WIDTH, %s not an NPC\n", ent->targetname ); + case SET_WIDTH: //## %f="0.0" # Width of NPC bounding box + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_WIDTH, %s not an NPC\n", ent->targetname); return false; } *value = ent->mins[0]; break; - case SET_TIMESCALE://## %f="0.0" # Speed-up slow down game (0 - 1.0) + case SET_TIMESCALE: //## %f="0.0" # Speed-up slow down game (0 - 1.0) *value = g_timescale->value; break; - case SET_CAMERA_GROUP_Z_OFS://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_Z_OFS: //## %s="NULL" # all ents with this cameraGroup will be focused on return false; break; - case SET_VISRANGE://## %f="0.0" # How far away NPC can see - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_VISRANGE, %s not an NPC\n", ent->targetname ); + case SET_VISRANGE: //## %f="0.0" # How far away NPC can see + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_VISRANGE, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.visrange; break; - case SET_EARSHOT://## %f="0.0" # How far an NPC can hear - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_EARSHOT, %s not an NPC\n", ent->targetname ); + case SET_EARSHOT: //## %f="0.0" # How far an NPC can hear + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_EARSHOT, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.earshot; break; - case SET_VIGILANCE://## %f="0.0" # How often to look for enemies (0 - 1.0) - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_VIGILANCE, %s not an NPC\n", ent->targetname ); + case SET_VIGILANCE: //## %f="0.0" # How often to look for enemies (0 - 1.0) + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_VIGILANCE, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.vigilance; break; - case SET_GRAVITY://## %f="0.0" # Change this ent's gravity - 800 default - if ( (ent->svFlags&SVF_CUSTOM_GRAVITY) && ent->client ) - { + case SET_GRAVITY: //## %f="0.0" # Change this ent's gravity - 800 default + if ((ent->svFlags & SVF_CUSTOM_GRAVITY) && ent->client) { *value = ent->client->ps.gravity; - } - else - { + } else { *value = g_gravity->value; } break; case SET_FACEEYESCLOSED: case SET_FACEEYESOPENED: - case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds - case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds - case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds - case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds - case SET_FACESMILE: //## %f="0.0" # Set face to Smile expression for number of seconds - case SET_FACEGLAD: //## %f="0.0" # Set face to Glad expression for number of seconds - case SET_FACEHAPPY: //## %f="0.0" # Set face to Happy expression for number of seconds - case SET_FACESHOCKED: //## %f="0.0" # Set face to Shocked expression for number of seconds - case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds - DebugPrint( WL_WARNING, "GetFloat: SET_FACE___ not implemented\n" ); + case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds + case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds + case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds + case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds + case SET_FACESMILE: //## %f="0.0" # Set face to Smile expression for number of seconds + case SET_FACEGLAD: //## %f="0.0" # Set face to Glad expression for number of seconds + case SET_FACEHAPPY: //## %f="0.0" # Set face to Happy expression for number of seconds + case SET_FACESHOCKED: //## %f="0.0" # Set face to Shocked expression for number of seconds + case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds + DebugPrint(WL_WARNING, "GetFloat: SET_FACE___ not implemented\n"); return false; break; - case SET_WAIT: //## %f="0.0" # Change an entity's wait field + case SET_WAIT: //## %f="0.0" # Change an entity's wait field *value = ent->wait; break; - case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_FOLLOWDIST, %s not an NPC\n", ent->targetname ); + case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_FOLLOWDIST, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->followDist; break; //# #sep ints - case SET_ANIM_HOLDTIME_LOWER://## %d="0" # Hold lower anim for number of milliseconds - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_LOWER: //## %d="0" # Hold lower anim for number of milliseconds + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.legsAnimTimer; break; - case SET_ANIM_HOLDTIME_UPPER://## %d="0" # Hold upper anim for number of milliseconds - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_UPPER: //## %d="0" # Hold upper anim for number of milliseconds + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.torsoAnimTimer; break; - case SET_ANIM_HOLDTIME_BOTH://## %d="0" # Hold lower and upper anims for number of milliseconds - DebugPrint( WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n" ); + case SET_ANIM_HOLDTIME_BOTH: //## %d="0" # Hold lower and upper anims for number of milliseconds + DebugPrint(WL_WARNING, "GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n"); return false; break; - case SET_ARMOR://## %d="0" # Change armor - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_ARMOR, %s not a client\n", ent->targetname ); + case SET_ARMOR: //## %d="0" # Change armor + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_ARMOR, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.stats[STAT_ARMOR]; break; - case SET_WALKSPEED://## %d="0" # Change walkSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_WALKSPEED, %s not an NPC\n", ent->targetname ); + case SET_WALKSPEED: //## %d="0" # Change walkSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_WALKSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.walkSpeed; break; - case SET_RUNSPEED://## %d="0" # Change runSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_RUNSPEED, %s not an NPC\n", ent->targetname ); + case SET_RUNSPEED: //## %d="0" # Change runSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_RUNSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.runSpeed; break; - case SET_YAWSPEED://## %d="0" # Change yawSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_YAWSPEED, %s not an NPC\n", ent->targetname ); + case SET_YAWSPEED: //## %d="0" # Change yawSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_YAWSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.yawSpeed; break; - case SET_AGGRESSION://## %d="0" # Change aggression 1-5 - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_AGGRESSION, %s not an NPC\n", ent->targetname ); + case SET_AGGRESSION: //## %d="0" # Change aggression 1-5 + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_AGGRESSION, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.aggression; break; - case SET_AIM://## %d="0" # Change aim 1-5 - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_AIM, %s not an NPC\n", ent->targetname ); + case SET_AIM: //## %d="0" # Change aim 1-5 + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_AIM, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.aim; break; - case SET_FRICTION://## %d="0" # Change ent's friction - 6 default - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_FRICTION, %s not a client\n", ent->targetname ); + case SET_FRICTION: //## %d="0" # Change ent's friction - 6 default + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_FRICTION, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.friction; break; - case SET_SHOOTDIST://## %d="0" # How far the ent can shoot - 0 uses weapon - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_SHOOTDIST, %s not an NPC\n", ent->targetname ); + case SET_SHOOTDIST: //## %d="0" # How far the ent can shoot - 0 uses weapon + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_SHOOTDIST, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.shootDistance; break; - case SET_HFOV://## %d="0" # Horizontal field of view - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_HFOV, %s not an NPC\n", ent->targetname ); + case SET_HFOV: //## %d="0" # Horizontal field of view + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_HFOV, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.hfov; break; - case SET_VFOV://## %d="0" # Vertical field of view - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_VFOV, %s not an NPC\n", ent->targetname ); + case SET_VFOV: //## %d="0" # Vertical field of view + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_VFOV, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.vfov; break; - case SET_DELAYSCRIPTTIME://## %d="0" # How many seconds to wait before running delayscript + case SET_DELAYSCRIPTTIME: //## %d="0" # How many seconds to wait before running delayscript *value = ent->delayScriptTime - level.time; break; - case SET_FORWARDMOVE://## %d="0" # NPC move forward -127(back) to 127 - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_FORWARDMOVE, %s not a client\n", ent->targetname ); + case SET_FORWARDMOVE: //## %d="0" # NPC move forward -127(back) to 127 + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_FORWARDMOVE, %s not a client\n", ent->targetname); return false; } *value = ent->client->forced_forwardmove; break; - case SET_RIGHTMOVE://## %d="0" # NPC move right -127(left) to 127 - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_RIGHTMOVE, %s not a client\n", ent->targetname ); + case SET_RIGHTMOVE: //## %d="0" # NPC move right -127(left) to 127 + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_RIGHTMOVE, %s not a client\n", ent->targetname); return false; } *value = ent->client->forced_rightmove; break; - case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on + case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on *value = ent->startFrame; break; - case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on + case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on *value = ent->endFrame; break; - case SET_ANIMFRAME: //## %d="0" # of current frame + case SET_ANIMFRAME: //## %d="0" # of current frame *value = ent->s.frame; break; - case SET_SHOT_SPACING://## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_SHOT_SPACING, %s not an NPC\n", ent->targetname ); + case SET_SHOT_SPACING: //## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_SHOT_SPACING, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->burstSpacing; break; - case SET_MISSIONSTATUSTIME://## %d="0" # Amount of time until Mission Status should be shown after death + case SET_MISSIONSTATUSTIME: //## %d="0" # Amount of time until Mission Status should be shown after death *value = cg.missionStatusDeadTime - level.time; break; //# #sep booleans - case SET_IGNOREPAIN://## %t="BOOL_TYPES" # Do not react to pain - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_IGNOREPAIN, %s not an NPC\n", ent->targetname ); + case SET_IGNOREPAIN: //## %t="BOOL_TYPES" # Do not react to pain + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_IGNOREPAIN, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->ignorePain; break; - case SET_IGNOREENEMIES://## %t="BOOL_TYPES" # Do not acquire enemies - *value = (ent->svFlags&SVF_IGNORE_ENEMIES); + case SET_IGNOREENEMIES: //## %t="BOOL_TYPES" # Do not acquire enemies + *value = (ent->svFlags & SVF_IGNORE_ENEMIES); break; - case SET_IGNOREALERTS://## Do not get enemy set by allies in area(ambush) - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_IGNOREALERTS, %s not an NPC\n", ent->targetname ); + case SET_IGNOREALERTS: //## Do not get enemy set by allies in area(ambush) + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_IGNOREALERTS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_IGNORE_ALERTS); + *value = (ent->NPC->scriptFlags & SCF_IGNORE_ALERTS); break; - case SET_DONTSHOOT://## %t="BOOL_TYPES" # Others won't shoot you - *value = (ent->flags&FL_DONT_SHOOT); + case SET_DONTSHOOT: //## %t="BOOL_TYPES" # Others won't shoot you + *value = (ent->flags & FL_DONT_SHOOT); break; - case SET_NOTARGET://## %t="BOOL_TYPES" # Others won't pick you as enemy - *value = (ent->flags&FL_NOTARGET); + case SET_NOTARGET: //## %t="BOOL_TYPES" # Others won't pick you as enemy + *value = (ent->flags & FL_NOTARGET); break; - case SET_DONTFIRE://## %t="BOOL_TYPES" # Don't fire your weapon - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_DONTFIRE, %s not an NPC\n", ent->targetname ); + case SET_DONTFIRE: //## %t="BOOL_TYPES" # Don't fire your weapon + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_DONTFIRE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_DONT_FIRE); + *value = (ent->NPC->scriptFlags & SCF_DONT_FIRE); break; - case SET_LOCKED_ENEMY://## %t="BOOL_TYPES" # Keep current enemy until dead - *value = (ent->svFlags&SVF_LOCKEDENEMY); + case SET_LOCKED_ENEMY: //## %t="BOOL_TYPES" # Keep current enemy until dead + *value = (ent->svFlags & SVF_LOCKEDENEMY); break; - case SET_CROUCHED://## %t="BOOL_TYPES" # Force NPC to crouch - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_CROUCHED, %s not an NPC\n", ent->targetname ); + case SET_CROUCHED: //## %t="BOOL_TYPES" # Force NPC to crouch + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_CROUCHED, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_CROUCHED); + *value = (ent->NPC->scriptFlags & SCF_CROUCHED); break; - case SET_WALKING://## %t="BOOL_TYPES" # Force NPC to move at walkSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_WALKING, %s not an NPC\n", ent->targetname ); + case SET_WALKING: //## %t="BOOL_TYPES" # Force NPC to move at walkSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_WALKING, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_WALKING); + *value = (ent->NPC->scriptFlags & SCF_WALKING); break; - case SET_RUNNING://## %t="BOOL_TYPES" # Force NPC to move at runSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_RUNNING, %s not an NPC\n", ent->targetname ); + case SET_RUNNING: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_RUNNING, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_RUNNING); + *value = (ent->NPC->scriptFlags & SCF_RUNNING); break; - case SET_CHASE_ENEMIES://## %t="BOOL_TYPES" # NPC will chase after enemies - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_CHASE_ENEMIES, %s not an NPC\n", ent->targetname ); + case SET_CHASE_ENEMIES: //## %t="BOOL_TYPES" # NPC will chase after enemies + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_CHASE_ENEMIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_CHASE_ENEMIES); + *value = (ent->NPC->scriptFlags & SCF_CHASE_ENEMIES); break; - case SET_LOOK_FOR_ENEMIES://## %t="BOOL_TYPES" # NPC will be on the lookout for enemies - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_LOOK_FOR_ENEMIES, %s not an NPC\n", ent->targetname ); + case SET_LOOK_FOR_ENEMIES: //## %t="BOOL_TYPES" # NPC will be on the lookout for enemies + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_LOOK_FOR_ENEMIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES); + *value = (ent->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES); break; - case SET_FACE_MOVE_DIR://## %t="BOOL_TYPES" # NPC will face in the direction it's moving - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_FACE_MOVE_DIR, %s not an NPC\n", ent->targetname ); + case SET_FACE_MOVE_DIR: //## %t="BOOL_TYPES" # NPC will face in the direction it's moving + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_FACE_MOVE_DIR, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_FACE_MOVE_DIR); + *value = (ent->NPC->scriptFlags & SCF_FACE_MOVE_DIR); break; - case SET_FORCED_MARCH://## %t="BOOL_TYPES" # Force NPC to move at runSpeed - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_FORCED_MARCH, %s not an NPC\n", ent->targetname ); + case SET_FORCED_MARCH: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_FORCED_MARCH, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SET_FORCED_MARCH); + *value = (ent->NPC->scriptFlags & SET_FORCED_MARCH); break; - case SET_UNDYING://## %t="BOOL_TYPES" # Can take damage down to 1 but not die - *value = (ent->flags&FL_UNDYING); + case SET_UNDYING: //## %t="BOOL_TYPES" # Can take damage down to 1 but not die + *value = (ent->flags & FL_UNDYING); break; - case SET_NOAVOID://## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NOAVOID, %s not an NPC\n", ent->targetname ); + case SET_NOAVOID: //## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NOAVOID, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_NO_COLL_AVOID); + *value = (ent->NPC->aiFlags & NPCAI_NO_COLL_AVOID); break; - case SET_SOLID://## %t="BOOL_TYPES" # Make yourself notsolid or solid + case SET_SOLID: //## %t="BOOL_TYPES" # Make yourself notsolid or solid *value = ent->contents; break; - case SET_PLAYER_USABLE://## %t="BOOL_TYPES" # Can be activateby the player's "use" button - *value = (ent->svFlags&SVF_PLAYER_USABLE); + case SET_PLAYER_USABLE: //## %t="BOOL_TYPES" # Can be activateby the player's "use" button + *value = (ent->svFlags & SVF_PLAYER_USABLE); break; - case SET_LOOP_ANIM://## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence + case SET_LOOP_ANIM: //## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence *value = ent->loopAnim; break; - case SET_INTERFACE://## %t="BOOL_TYPES" # Player interface on/off - DebugPrint( WL_WARNING, "GetFloat: SET_INTERFACE not implemented\n" ); + case SET_INTERFACE: //## %t="BOOL_TYPES" # Player interface on/off + DebugPrint(WL_WARNING, "GetFloat: SET_INTERFACE not implemented\n"); return false; break; - case SET_SHIELDS://## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_SHIELDS, %s not an NPC\n", ent->targetname ); + case SET_SHIELDS: //## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_SHIELDS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_SHIELDS); + *value = (ent->NPC->aiFlags & NPCAI_SHIELDS); break; case SET_SABERACTIVE: - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_SABERACTIVE, %s not a client\n", ent->targetname ); + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_SABERACTIVE, %s not a client\n", ent->targetname); return false; } *value = (ent->client->ps.SaberActive()); break; - case SET_INVISIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - *value = (ent->s.eFlags&EF_NODRAW); + case SET_INVISIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + *value = (ent->s.eFlags & EF_NODRAW); break; - case SET_VAMPIRE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - if ( !ent->client ) - { + case SET_VAMPIRE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + if (!ent->client) { return false; - } - else - { - *value = (ent->client->ps.powerups[PW_DISINT_2]>level.time); + } else { + *value = (ent->client->ps.powerups[PW_DISINT_2] > level.time); } break; - case SET_FORCE_INVINCIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - if ( !ent->client ) - { + case SET_FORCE_INVINCIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + if (!ent->client) { return false; - } - else - { - *value = (ent->client->ps.powerups[PW_INVINCIBLE]>level.time); + } else { + *value = (ent->client->ps.powerups[PW_INVINCIBLE] > level.time); } break; - case SET_GREET_ALLIES://## %t="BOOL_TYPES" # Makes an NPC greet teammates - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_GREET_ALLIES, %s not an NPC\n", ent->targetname ); + case SET_GREET_ALLIES: //## %t="BOOL_TYPES" # Makes an NPC greet teammates + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_GREET_ALLIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_GREET_ALLIES); + *value = (ent->NPC->aiFlags & NPCAI_GREET_ALLIES); break; - case SET_VIDEO_FADE_IN://## %t="BOOL_TYPES" # Makes video playback fade in - DebugPrint( WL_WARNING, "GetFloat: SET_VIDEO_FADE_IN not implemented\n" ); + case SET_VIDEO_FADE_IN: //## %t="BOOL_TYPES" # Makes video playback fade in + DebugPrint(WL_WARNING, "GetFloat: SET_VIDEO_FADE_IN not implemented\n"); return false; break; - case SET_VIDEO_FADE_OUT://## %t="BOOL_TYPES" # Makes video playback fade out - DebugPrint( WL_WARNING, "GetFloat: SET_VIDEO_FADE_OUT not implemented\n" ); + case SET_VIDEO_FADE_OUT: //## %t="BOOL_TYPES" # Makes video playback fade out + DebugPrint(WL_WARNING, "GetFloat: SET_VIDEO_FADE_OUT not implemented\n"); return false; break; - case SET_PLAYER_LOCKED://## %t="BOOL_TYPES" # Makes it so player cannot move + case SET_PLAYER_LOCKED: //## %t="BOOL_TYPES" # Makes it so player cannot move *value = player_locked; break; - case SET_LOCK_PLAYER_WEAPONS://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons - *value = (ent->flags&FL_LOCK_PLAYER_WEAPONS); + case SET_LOCK_PLAYER_WEAPONS: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + *value = (ent->flags & FL_LOCK_PLAYER_WEAPONS); break; - case SET_NO_IMPACT_DAMAGE://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons - *value = (ent->flags&FL_NO_IMPACT_DMG); + case SET_NO_IMPACT_DAMAGE: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + *value = (ent->flags & FL_NO_IMPACT_DMG); break; - case SET_NO_KNOCKBACK://## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons - *value = (ent->flags&FL_NO_KNOCKBACK); + case SET_NO_KNOCKBACK: //## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons + *value = (ent->flags & FL_NO_KNOCKBACK); break; - case SET_ALT_FIRE://## %t="BOOL_TYPES" # Force NPC to use altfire when shooting - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_ALT_FIRE, %s not an NPC\n", ent->targetname ); + case SET_ALT_FIRE: //## %t="BOOL_TYPES" # Force NPC to use altfire when shooting + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_ALT_FIRE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_ALT_FIRE); + *value = (ent->NPC->scriptFlags & SCF_ALT_FIRE); break; - case SET_NO_RESPONSE://## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_RESPONSE, %s not an NPC\n", ent->targetname ); + case SET_NO_RESPONSE: //## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_RESPONSE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_RESPONSE); + *value = (ent->NPC->scriptFlags & SCF_NO_RESPONSE); break; - case SET_INVINCIBLE://## %t="BOOL_TYPES" # Completely unkillable - *value = (ent->flags&FL_GODMODE); + case SET_INVINCIBLE: //## %t="BOOL_TYPES" # Completely unkillable + *value = (ent->flags & FL_GODMODE); break; - case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen + case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen *value = cg.missionStatusShow; break; - case SET_NO_COMBAT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_COMBAT_TALK, %s not an NPC\n", ent->targetname ); + case SET_NO_COMBAT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_COMBAT_TALK, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_COMBAT_TALK); + *value = (ent->NPC->scriptFlags & SCF_NO_COMBAT_TALK); break; - case SET_NO_ALERT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_ALERT_TALK, %s not an NPC\n", ent->targetname ); + case SET_NO_ALERT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_ALERT_TALK, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_ALERT_TALK); + *value = (ent->NPC->scriptFlags & SCF_NO_ALERT_TALK); break; - case SET_USE_CP_NEAREST://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_USE_CP_NEAREST, %s not an NPC\n", ent->targetname ); + case SET_USE_CP_NEAREST: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_USE_CP_NEAREST, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_USE_CP_NEAREST); + *value = (ent->NPC->scriptFlags & SCF_USE_CP_NEAREST); break; - case SET_DISMEMBERABLE://## %t="BOOL_TYPES" # NPC will not be affected by force powers - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_DISMEMBERABLE, %s not a client\n", ent->targetname ); + case SET_DISMEMBERABLE: //## %t="BOOL_TYPES" # NPC will not be affected by force powers + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_DISMEMBERABLE, %s not a client\n", ent->targetname); return false; } *value = !(ent->client->dismembered); break; case SET_NO_FORCE: - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_FORCE, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_FORCE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_FORCE); + *value = (ent->NPC->scriptFlags & SCF_NO_FORCE); break; case SET_NO_ACROBATICS: - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_ACROBATICS, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_ACROBATICS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_ACROBATICS); + *value = (ent->NPC->scriptFlags & SCF_NO_ACROBATICS); break; case SET_USE_SUBTITLES: - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_USE_SUBTITLES, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_USE_SUBTITLES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_USE_SUBTITLES); + *value = (ent->NPC->scriptFlags & SCF_USE_SUBTITLES); break; - case SET_NO_FALLTODEATH://## %t="BOOL_TYPES" # NPC will not be affected by force powers - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_NO_FALLTODEATH, %s not an NPC\n", ent->targetname ); + case SET_NO_FALLTODEATH: //## %t="BOOL_TYPES" # NPC will not be affected by force powers + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_NO_FALLTODEATH, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_FALLTODEATH); + *value = (ent->NPC->scriptFlags & SCF_NO_FALLTODEATH); break; - case SET_MORELIGHT://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetFloat: SET_MORELIGHT, %s not an NPC\n", ent->targetname ); + case SET_MORELIGHT: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetFloat: SET_MORELIGHT, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_MORELIGHT); + *value = (ent->NPC->scriptFlags & SCF_MORELIGHT); break; - case SET_TREASONED://## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig - DebugPrint( WL_VERBOSE, "SET_TREASONED is disabled, do not use\n" ); - *value = 0;//(ffireLevel>=FFIRE_LEVEL_RETALIATION); + case SET_TREASONED: //## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig + DebugPrint(WL_VERBOSE, "SET_TREASONED is disabled, do not use\n"); + *value = 0; //(ffireLevel>=FFIRE_LEVEL_RETALIATION); break; - case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate + case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate *value = (ent->s.eFlags & EF_DISABLE_SHADER_ANIM); break; - case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control + case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control *value = (ent->s.eFlags & EF_SHADER_ANIM); break; - case SET_OBJECTIVE_LIGHTSIDE: - { + case SET_OBJECTIVE_LIGHTSIDE: { *value = level.clients[0].sess.mission_objectives[LIGHTSIDE_OBJ].status; break; } // kef 4/16/03 -- just trying to put together some scripted meta-AI for swoop riders - case SET_DISTSQRD_TO_PLAYER: - { - vec3_t distSquared; + case SET_DISTSQRD_TO_PLAYER: { + vec3_t distSquared; - VectorSubtract(player->currentOrigin, ent->s.origin, distSquared); + VectorSubtract(player->currentOrigin, ent->s.origin, distSquared); - *value = VectorLengthSquared(distSquared); - break; - } + *value = VectorLengthSquared(distSquared); + break; + } default: - if ( VariableDeclared( name ) != VTYPE_FLOAT ) + if (VariableDeclared(name) != VTYPE_FLOAT) return false; - return GetFloatVariable( name, value ); + return GetFloatVariable(name, value); } return true; } -int CQuake3GameInterface::GetVector( int entID, const char *name, vec3_t value ) -{ - gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { +int CQuake3GameInterface::GetVector(int entID, const char *name, vec3_t value) { + gentity_t *ent = &g_entities[entID]; + if (!ent) { return false; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -10533,7 +9120,7 @@ int CQuake3GameInterface::GetVector( int entID, const char *name, vec3_t value case SET_PARM14: case SET_PARM15: case SET_PARM16: - sscanf( ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2] ); + sscanf(ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2]); break; case SET_ORIGIN: @@ -10544,51 +9131,47 @@ int CQuake3GameInterface::GetVector( int entID, const char *name, vec3_t value VectorCopy(ent->currentAngles, value); break; - case SET_TELEPORT_DEST://## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear - DebugPrint( WL_WARNING, "GetVector: SET_TELEPORT_DEST not implemented\n" ); + case SET_TELEPORT_DEST: //## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear + DebugPrint(WL_WARNING, "GetVector: SET_TELEPORT_DEST not implemented\n"); return false; break; default: - if ( VariableDeclared( name ) != VTYPE_VECTOR ) + if (VariableDeclared(name) != VTYPE_VECTOR) return false; - return GetVectorVariable( name, value ); + return GetVectorVariable(name, value); } return true; } -int CQuake3GameInterface::GetString( int entID, const char *name, char **value ) -{ - gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { +int CQuake3GameInterface::GetString(int entID, const char *name, char **value) { + gentity_t *ent = &g_entities[entID]; + if (!ent) { return false; } - if( strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5) ) - { - const char* cvar_name = name + 5; + if (strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5)) { + const char *cvar_name = name + 5; // by allocating and then re-using the same sufficiently large buffer, // we ensure that pointers to it never become invalid, // so we can support expressions using the same cvar twice, // e.g. if(get(cvar_x) == get(cvar_x)) - std::array& buf = m_cvars[cvar_name]; + std::array &buf = m_cvars[cvar_name]; gi.Cvar_VariableStringBuffer(cvar_name, buf.data(), buf.size()); *value = buf.data(); return true; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well - switch ( toGet ) - { + switch (toGet) { case SET_ANIM_BOTH: - *value = (char *) Q3_GetAnimBoth( ent ); + *value = (char *)Q3_GetAnimBoth(ent); - if ( VALIDSTRING( *value ) == false ) + if (VALIDSTRING(*value) == false) return false; break; @@ -10609,543 +9192,505 @@ int CQuake3GameInterface::GetString( int entID, const char *name, char **value case SET_PARM14: case SET_PARM15: case SET_PARM16: - if ( ent->parms ) - { - *value = (char *) ent->parms->parm[toGet - SET_PARM1]; - } - else - { - DebugPrint( WL_WARNING, "GetString: invalid ent %s has no parms!\n", ent->targetname ); + if (ent->parms) { + *value = (char *)ent->parms->parm[toGet - SET_PARM1]; + } else { + DebugPrint(WL_WARNING, "GetString: invalid ent %s has no parms!\n", ent->targetname); return false; } break; case SET_TARGET: - *value = (char *) ent->target; + *value = (char *)ent->target; break; case SET_LOCATION: - *value = G_GetLocationForEnt( ent ); - if ( !value || !value[0] ) - { + *value = G_GetLocationForEnt(ent); + if (!value || !value[0]) { return false; } break; //# #sep Scripts and other file paths - case SET_SPAWNSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to BSET_SPAWN, etc + case SET_SPAWNSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to + //BSET_SPAWN, etc *value = ent->behaviorSet[BSET_SPAWN]; break; - case SET_USESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used + case SET_USESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used *value = ent->behaviorSet[BSET_USE]; break; - case SET_AWAKESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled + case SET_AWAKESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled *value = ent->behaviorSet[BSET_AWAKE]; break; - case SET_ANGERSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time + case SET_ANGERSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time *value = ent->behaviorSet[BSET_ANGER]; break; - case SET_ATTACKSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot + case SET_ATTACKSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot *value = ent->behaviorSet[BSET_ATTACK]; break; - case SET_VICTORYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone + case SET_VICTORYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone *value = ent->behaviorSet[BSET_VICTORY]; break; - case SET_LOSTENEMYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy + case SET_LOSTENEMYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy *value = ent->behaviorSet[BSET_LOSTENEMY]; break; - case SET_PAINSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit + case SET_PAINSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit *value = ent->behaviorSet[BSET_PAIN]; break; - case SET_FLEESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health + case SET_FLEESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health *value = ent->behaviorSet[BSET_FLEE]; break; - case SET_DEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed + case SET_DEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed *value = ent->behaviorSet[BSET_DEATH]; break; - case SET_DELAYEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay + case SET_DELAYEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay *value = ent->behaviorSet[BSET_DELAYED]; break; - case SET_BLOCKEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate + case SET_BLOCKEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate *value = ent->behaviorSet[BSET_BLOCKED]; break; - case SET_FFIRESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly + case SET_FFIRESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly *value = ent->behaviorSet[BSET_FFIRE]; break; - case SET_FFDEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate + case SET_FFDEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate *value = ent->behaviorSet[BSET_FFDEATH]; break; //# #sep Standard strings - case SET_ENEMY://## %s="NULL" # Set enemy by targetname - if ( ent->enemy != NULL ) - { + case SET_ENEMY: //## %s="NULL" # Set enemy by targetname + if (ent->enemy != NULL) { *value = ent->enemy->targetname; - } - else return false; + } else + return false; break; - case SET_LEADER://## %s="NULL" # Set for BS_FOLLOW_LEADER - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetString: SET_LEADER, %s not a client\n", ent->targetname ); + case SET_LEADER: //## %s="NULL" # Set for BS_FOLLOW_LEADER + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetString: SET_LEADER, %s not a client\n", ent->targetname); return false; - } - else if ( ent->client->leader ) - { + } else if (ent->client->leader) { *value = ent->client->leader->targetname; - } - else return false; + } else + return false; break; - case SET_CAPTURE://## %s="NULL" # Set captureGoal by targetname - if ( ent->NPC == NULL ) - { - DebugPrint( WL_WARNING, "GetString: SET_CAPTURE, %s not an NPC\n", ent->targetname ); + case SET_CAPTURE: //## %s="NULL" # Set captureGoal by targetname + if (ent->NPC == NULL) { + DebugPrint(WL_WARNING, "GetString: SET_CAPTURE, %s not an NPC\n", ent->targetname); return false; - } - else if ( ent->NPC->captureGoal != NULL ) - { + } else if (ent->NPC->captureGoal != NULL) { *value = ent->NPC->captureGoal->targetname; - } - else return false; + } else + return false; break; - case SET_TARGETNAME://## %s="NULL" # Set/change your targetname + case SET_TARGETNAME: //## %s="NULL" # Set/change your targetname *value = ent->targetname; break; - case SET_PAINTARGET://## %s="NULL" # Set/change what to use when hit + case SET_PAINTARGET: //## %s="NULL" # Set/change what to use when hit *value = ent->paintarget; break; case SET_PLAYERMODEL: *value = ent->NPC_type; break; - case SET_CAMERA_GROUP://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP: //## %s="NULL" # all ents with this cameraGroup will be focused on *value = ent->cameraGroup; break; - case SET_CAMERA_GROUP_TAG://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_TAG: //## %s="NULL" # all ents with this cameraGroup will be focused on return false; break; - case SET_LOOK_TARGET://## %s="NULL" # object for NPC to look at - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetString: SET_LOOK_TARGET, %s not a client\n", ent->targetname ); + case SET_LOOK_TARGET: //## %s="NULL" # object for NPC to look at + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetString: SET_LOOK_TARGET, %s not a client\n", ent->targetname); return false; - } - else - { + } else { gentity_t *lookTarg = &g_entities[ent->client->renderInfo.lookTarget]; - if ( lookTarg != NULL ) - { + if (lookTarg != NULL) { *value = lookTarg->targetname; - } - else return false; + } else + return false; } break; - case SET_TARGET2://## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo + case SET_TARGET2: //## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo *value = ent->target2; break; - case SET_REMOVE_TARGET://## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState + case SET_REMOVE_TARGET: //## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState *value = ent->target3; break; case SET_WEAPON: - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetString: SET_WEAPON, %s not a client\n", ent->targetname ); + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetString: SET_WEAPON, %s not a client\n", ent->targetname); return false; - } - else - { - *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); + } else { + *value = (char *)GetStringForID(WPTable, ent->client->ps.weapon); } break; case SET_ITEM: - if ( ent->client == NULL ) - { - DebugPrint( WL_WARNING, "GetString: SET_ITEM, %s not a client\n", ent->targetname ); + if (ent->client == NULL) { + DebugPrint(WL_WARNING, "GetString: SET_ITEM, %s not a client\n", ent->targetname); return false; - } - else - { - // *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); + } else { + // *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); } break; case SET_MUSIC_STATE: - *value = (char *)GetStringForID( DMSTable, level.dmState ); + *value = (char *)GetStringForID(DMSTable, level.dmState); break; - //The below cannot be gotten - case SET_NAVGOAL://## %s="NULL" # *Move to this navgoal then continue script - DebugPrint( WL_WARNING, "GetString: SET_NAVGOAL not implemented\n" ); + // The below cannot be gotten + case SET_NAVGOAL: //## %s="NULL" # *Move to this navgoal then continue script + DebugPrint(WL_WARNING, "GetString: SET_NAVGOAL not implemented\n"); return false; break; - case SET_VIEWTARGET://## %s="NULL" # Set angles toward ent by targetname - DebugPrint( WL_WARNING, "GetString: SET_VIEWTARGET not implemented\n" ); + case SET_VIEWTARGET: //## %s="NULL" # Set angles toward ent by targetname + DebugPrint(WL_WARNING, "GetString: SET_VIEWTARGET not implemented\n"); return false; break; - case SET_WATCHTARGET://## %s="NULL" # Set angles toward ent by targetname - if ( ent && ent->NPC && ent->NPC->watchTarget ) - { + case SET_WATCHTARGET: //## %s="NULL" # Set angles toward ent by targetname + if (ent && ent->NPC && ent->NPC->watchTarget) { *value = ent->NPC->watchTarget->targetname; - } - else - { - DebugPrint( WL_WARNING, "GetString: SET_WATCHTARGET no watchTarget!\n" ); + } else { + DebugPrint(WL_WARNING, "GetString: SET_WATCHTARGET no watchTarget!\n"); return false; } break; case SET_VIEWENTITY: - DebugPrint( WL_WARNING, "GetString: SET_VIEWENTITY not implemented\n" ); + DebugPrint(WL_WARNING, "GetString: SET_VIEWENTITY not implemented\n"); return false; break; - case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - DebugPrint( WL_WARNING, "GetString: SET_CAPTIONTEXTCOLOR not implemented\n" ); + case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + DebugPrint(WL_WARNING, "GetString: SET_CAPTIONTEXTCOLOR not implemented\n"); return false; break; - case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - DebugPrint( WL_WARNING, "GetString: SET_CENTERTEXTCOLOR not implemented\n" ); + case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + DebugPrint(WL_WARNING, "GetString: SET_CENTERTEXTCOLOR not implemented\n"); return false; break; - case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - DebugPrint( WL_WARNING, "GetString: SET_SCROLLTEXTCOLOR not implemented\n" ); + case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + DebugPrint(WL_WARNING, "GetString: SET_SCROLLTEXTCOLOR not implemented\n"); return false; break; - case SET_COPY_ORIGIN://## %s="targetname" # Copy the origin of the ent with targetname to your origin - DebugPrint( WL_WARNING, "GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_COPY_ORIGIN: //## %s="targetname" # Copy the origin of the ent with targetname to your origin + DebugPrint(WL_WARNING, "GetString: SET_COPY_ORIGIN not implemented\n"); return false; break; - case SET_DEFEND_TARGET://## %s="targetname" # This NPC will attack the target NPC's enemies - DebugPrint( WL_WARNING, "GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_DEFEND_TARGET: //## %s="targetname" # This NPC will attack the target NPC's enemies + DebugPrint(WL_WARNING, "GetString: SET_COPY_ORIGIN not implemented\n"); return false; break; - case SET_VIDEO_PLAY://## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) - DebugPrint( WL_WARNING, "GetString: SET_VIDEO_PLAY not implemented\n" ); + case SET_VIDEO_PLAY: //## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) + DebugPrint(WL_WARNING, "GetString: SET_VIDEO_PLAY not implemented\n"); return false; break; - case SET_LOADGAME://## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck - DebugPrint( WL_WARNING, "GetString: SET_LOADGAME not implemented\n" ); + case SET_LOADGAME: //## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck + DebugPrint(WL_WARNING, "GetString: SET_LOADGAME not implemented\n"); return false; break; - case SET_LOCKYAW://## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) - DebugPrint( WL_WARNING, "GetString: SET_LOCKYAW not implemented\n" ); + case SET_LOCKYAW: //## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) + DebugPrint(WL_WARNING, "GetString: SET_LOCKYAW not implemented\n"); return false; break; - case SET_SCROLLTEXT: //## %s="" # key of text string to print - DebugPrint( WL_WARNING, "GetString: SET_SCROLLTEXT not implemented\n" ); + case SET_SCROLLTEXT: //## %s="" # key of text string to print + DebugPrint(WL_WARNING, "GetString: SET_SCROLLTEXT not implemented\n"); return false; break; - case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame - DebugPrint( WL_WARNING, "GetString: SET_LCARSTEXT not implemented\n" ); + case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame + DebugPrint(WL_WARNING, "GetString: SET_LCARSTEXT not implemented\n"); return false; break; case SET_CENTERTEXT: - DebugPrint( WL_WARNING, "GetString: SET_CENTERTEXT not implemented\n" ); + DebugPrint(WL_WARNING, "GetString: SET_CENTERTEXT not implemented\n"); return false; break; default: - if ( VariableDeclared( name ) != VTYPE_STRING ) + if (VariableDeclared(name) != VTYPE_STRING) return false; - return GetStringVariable( name, (const char **) value ); + return GetStringVariable(name, (const char **)value); } return true; } -int CQuake3GameInterface::Evaluate( int p1Type, const char *p1, int p2Type, const char *p2, int operatorType ) -{ - float f1=0, f2=0; - vec3_t v1, v2; - char *c1=0, *c2=0; - int i1=0, i2=0; +int CQuake3GameInterface::Evaluate(int p1Type, const char *p1, int p2Type, const char *p2, int operatorType) { + float f1 = 0, f2 = 0; + vec3_t v1, v2; + char *c1 = 0, *c2 = 0; + int i1 = 0, i2 = 0; - //Always demote to int on float to integer comparisons - if ( ( ( p1Type == TK_FLOAT ) && ( p2Type == TK_INT ) ) || ( ( p1Type == TK_INT ) && ( p2Type == TK_FLOAT ) ) ) - { + // Always demote to int on float to integer comparisons + if (((p1Type == TK_FLOAT) && (p2Type == TK_INT)) || ((p1Type == TK_INT) && (p2Type == TK_FLOAT))) { p1Type = TK_INT; p2Type = TK_INT; } - //Cannot compare two disimilar types - if ( p1Type != p2Type ) - { - DebugPrint( WL_ERROR, "Evaluate comparing two disimilar types!\n"); + // Cannot compare two disimilar types + if (p1Type != p2Type) { + DebugPrint(WL_ERROR, "Evaluate comparing two disimilar types!\n"); return false; } - //Format the parameters - switch ( p1Type ) - { + // Format the parameters + switch (p1Type) { case TK_FLOAT: - sscanf( p1, "%f", &f1 ); - sscanf( p2, "%f", &f2 ); + sscanf(p1, "%f", &f1); + sscanf(p2, "%f", &f2); break; case TK_INT: - sscanf( p1, "%d", &i1 ); - sscanf( p2, "%d", &i2 ); + sscanf(p1, "%d", &i1); + sscanf(p2, "%d", &i2); break; case TK_VECTOR: - sscanf( p1, "%f %f %f", &v1[0], &v1[1], &v1[2] ); - sscanf( p2, "%f %f %f", &v2[0], &v2[1], &v2[2] ); + sscanf(p1, "%f %f %f", &v1[0], &v1[1], &v1[2]); + sscanf(p2, "%f %f %f", &v2[0], &v2[1], &v2[2]); break; case TK_STRING: case TK_IDENTIFIER: - c1 = (char *) p1; - c2 = (char *) p2; + c1 = (char *)p1; + c2 = (char *)p2; break; default: - DebugPrint( WL_WARNING, "Evaluate unknown type used!\n"); + DebugPrint(WL_WARNING, "Evaluate unknown type used!\n"); return false; } - //Compare them and return the result + // Compare them and return the result - //FIXME: YUCK!!! Better way to do this? + // FIXME: YUCK!!! Better way to do this? - switch ( operatorType ) - { + switch (operatorType) { // // EQUAL TO // case TK_EQUALS: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 == f2 ); + return (int)(f1 == f2); break; case TK_INT: - return (int) ( i1 == i2 ); + return (int)(i1 == i2); break; case TK_VECTOR: - return (int) VectorCompare( v1, v2 ); + return (int)VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) !Q_stricmp( c1, c2 ); //NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) + return (int)!Q_stricmp(c1, c2); // NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; - // - // GREATER THAN - // + // + // GREATER THAN + // case TK_GREATER_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 > f2 ); + return (int)(f1 > f2); break; case TK_INT: - return (int) ( i1 > i2 ); + return (int)(i1 > i2); break; case TK_VECTOR: - DebugPrint( WL_ERROR, "Evaluate vector comparisons of type GREATER THAN cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate vector comparisons of type GREATER THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - DebugPrint( WL_ERROR, "Evaluate string comparisons of type GREATER THAN cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate string comparisons of type GREATER THAN cannot be performed!"); return false; break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; - // - // LESS THAN - // + // + // LESS THAN + // case TK_LESS_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 < f2 ); + return (int)(f1 < f2); break; case TK_INT: - return (int) ( i1 < i2 ); + return (int)(i1 < i2); break; case TK_VECTOR: - DebugPrint( WL_ERROR, "Evaluate vector comparisons of type LESS THAN cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate vector comparisons of type LESS THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - DebugPrint( WL_ERROR, "Evaluate string comparisons of type LESS THAN cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate string comparisons of type LESS THAN cannot be performed!"); return false; break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; - // - // NOT - // + // + // NOT + // - case TK_NOT: //NOTENOTE: Implied "NOT EQUAL TO" + case TK_NOT: // NOTENOTE: Implied "NOT EQUAL TO" - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 != f2 ); + return (int)(f1 != f2); break; case TK_INT: - return (int) ( i1 != i2 ); + return (int)(i1 != i2); break; case TK_VECTOR: - return (int) !VectorCompare( v1, v2 ); + return (int)!VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) Q_stricmp( c1, c2 ); + return (int)Q_stricmp(c1, c2); break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; - // - // GREATER THAN OR EQUAL TO - // + // + // GREATER THAN OR EQUAL TO + // case TK_GE: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 >= f2 ); + return (int)(f1 >= f2); break; case TK_INT: - return (int) ( i1 >= i2 ); + return (int)(i1 >= i2); break; case TK_VECTOR: - DebugPrint( WL_ERROR, "Evaluate vector comparisons of type GREATER THAN OR EQUAL TO cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate vector comparisons of type GREATER THAN OR EQUAL TO cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - DebugPrint( WL_ERROR, "Evaluate string comparisons of type GREATER THAN OR EQUAL TO cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate string comparisons of type GREATER THAN OR EQUAL TO cannot be performed!"); return false; break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; - // - // LESS THAN OR EQUAL TO - // + // + // LESS THAN OR EQUAL TO + // case TK_LE: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 <= f2 ); + return (int)(f1 <= f2); break; case TK_INT: - return (int) ( i1 <= i2 ); + return (int)(i1 <= i2); break; case TK_VECTOR: - DebugPrint( WL_ERROR, "Evaluate vector comparisons of type LESS THAN OR EQUAL TO cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate vector comparisons of type LESS THAN OR EQUAL TO cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - DebugPrint( WL_ERROR, "Evaluate string comparisons of type LESS THAN OR EQUAL TO cannot be performed!"); + DebugPrint(WL_ERROR, "Evaluate string comparisons of type LESS THAN OR EQUAL TO cannot be performed!"); return false; break; default: - DebugPrint( WL_ERROR, "Evaluate unknown type used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown type used!\n"); return false; } break; default: - DebugPrint( WL_ERROR, "Evaluate unknown operator used!\n"); + DebugPrint(WL_ERROR, "Evaluate unknown operator used!\n"); break; } return false; } -void CQuake3GameInterface::DeclareVariable( int type, const char *name ) -{ - //Cannot declare the same variable twice - if ( VariableDeclared( name ) != VTYPE_NONE ) +void CQuake3GameInterface::DeclareVariable(int type, const char *name) { + // Cannot declare the same variable twice + if (VariableDeclared(name) != VTYPE_NONE) return; - if ( m_numVariables > MAX_VARIABLES ) - { - DebugPrint( WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES ); + if (m_numVariables > MAX_VARIABLES) { + DebugPrint(WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES); return; } - switch( type ) - { + switch (type) { case TK_FLOAT: - m_varFloats[ name ] = 0.0f; + m_varFloats[name] = 0.0f; break; case TK_STRING: - m_varStrings[ name ] = "NULL"; + m_varStrings[name] = "NULL"; break; - case TK_VECTOR: - m_varVectors[ name ] = "0.0 0.0 0.0"; + m_varVectors[name] = "0.0 0.0 0.0"; break; default: - DebugPrint( WL_ERROR, "unknown INT_ID('t','y','p','e') for declare() function!\n" ); + DebugPrint(WL_ERROR, "unknown INT_ID('t','y','p','e') for declare() function!\n"); return; break; } @@ -11153,89 +9698,79 @@ void CQuake3GameInterface::DeclareVariable( int type, const char *name ) m_numVariables++; } -void CQuake3GameInterface::FreeVariable( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = m_varStrings.find( name ); +void CQuake3GameInterface::FreeVariable(const char *name) { + // Check the strings + varString_m::iterator vsi = m_varStrings.find(name); - if ( vsi != m_varStrings.end() ) - { - m_varStrings.erase( vsi ); + if (vsi != m_varStrings.end()) { + m_varStrings.erase(vsi); m_numVariables--; return; } - //Check the floats - varFloat_m::iterator vfi = m_varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = m_varFloats.find(name); - if ( vfi != m_varFloats.end() ) - { - m_varFloats.erase( vfi ); + if (vfi != m_varFloats.end()) { + m_varFloats.erase(vfi); m_numVariables--; return; } - //Check the strings - varString_m::iterator vvi = m_varVectors.find( name ); + // Check the strings + varString_m::iterator vvi = m_varVectors.find(name); - if ( vvi != m_varVectors.end() ) - { - m_varVectors.erase( vvi ); + if (vvi != m_varVectors.end()) { + m_varVectors.erase(vvi); m_numVariables--; return; } } -//Save / Load functions -ojk::ISavedGame* CQuake3GameInterface::get_saved_game_file() -{ - return ::gi.saved_game; -} +// Save / Load functions +ojk::ISavedGame *CQuake3GameInterface::get_saved_game_file() { return ::gi.saved_game; } -int CQuake3GameInterface::LinkGame( int entID, int icarusID ) -{ - gentity_t *pEntity = &g_entities[entID]; +int CQuake3GameInterface::LinkGame(int entID, int icarusID) { + gentity_t *pEntity = &g_entities[entID]; - if ( pEntity == NULL ) + if (pEntity == NULL) return false; // Set the icarus ID. pEntity->m_iIcarusID = icarusID; // Associate this Entity with the entity list. - AssociateEntity( pEntity ); + AssociateEntity(pEntity); return true; } // Access functions -int CQuake3GameInterface::CreateIcarus( int entID ) -{ - gentity_t *pEntity = &g_entities[entID]; +int CQuake3GameInterface::CreateIcarus(int entID) { + gentity_t *pEntity = &g_entities[entID]; // If the entity doesn't have an Icarus ID, obtain and assign a new one. - if ( pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID ) - pEntity->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID( entID ); + if (pEntity->m_iIcarusID == IIcarusInterface::ICARUS_INVALID) + pEntity->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID(entID); return pEntity->m_iIcarusID; } -//Polls the engine for the sequencer of the entity matching the name passed -int CQuake3GameInterface::GetByName( const char *name ) -{ - gentity_t *ent; - entitylist_t::iterator ei; - char temp[1024]; +// Polls the engine for the sequencer of the entity matching the name passed +int CQuake3GameInterface::GetByName(const char *name) { + gentity_t *ent; + entitylist_t::iterator ei; + char temp[1024]; - if ( name == NULL || name[0] == '\0' ) + if (name == NULL || name[0] == '\0') return -1; - strncpy( (char *) temp, name, sizeof(temp) ); - temp[sizeof(temp)-1] = 0; + strncpy((char *)temp, name, sizeof(temp)); + temp[sizeof(temp) - 1] = 0; - ei = m_EntityList.find( Q_strupr( (char *) temp ) ); + ei = m_EntityList.find(Q_strupr((char *)temp)); - if ( ei == m_EntityList.end() ) + if (ei == m_EntityList.end()) return -1; ent = &g_entities[(*ei).second]; @@ -11243,157 +9778,130 @@ int CQuake3GameInterface::GetByName( const char *name ) return ent->s.number; // this now returns the ent instead of the sequencer -- dmv 06/27/01 -// if (ent == NULL) -// return NULL; -// return ent->sequencer; + // if (ent == NULL) + // return NULL; + // return ent->sequencer; } // (g_entities[m_ownerID].svFlags&SVF_ICARUS_FREEZE) // return -1 indicates invalid -int CQuake3GameInterface::IsFrozen( int entID ) -{ - return (g_entities[entID].svFlags & SVF_ICARUS_FREEZE); -} +int CQuake3GameInterface::IsFrozen(int entID) { return (g_entities[entID].svFlags & SVF_ICARUS_FREEZE); } -void CQuake3GameInterface::Free(void* data) -{ - gi.Free( data ); -} +void CQuake3GameInterface::Free(void *data) { gi.Free(data); } -void* CQuake3GameInterface::Malloc( int size ) -{ - return gi.Malloc( size, TAG_ICARUS, qtrue ); -} +void *CQuake3GameInterface::Malloc(int size) { return gi.Malloc(size, TAG_ICARUS, qtrue); } -float CQuake3GameInterface::MaxFloat(void) -{ +float CQuake3GameInterface::MaxFloat(void) { // CHANGE! return 34000000; } // Script Precache functions. -void CQuake3GameInterface::PrecacheRoff( const char *name ) -{ - G_LoadRoff( name ); -} +void CQuake3GameInterface::PrecacheRoff(const char *name) { G_LoadRoff(name); } -void CQuake3GameInterface::PrecacheScript( const char *name ) -{ - char newname[1024]; //static char newname[1024]; +void CQuake3GameInterface::PrecacheScript(const char *name) { + char newname[1024]; // static char newname[1024]; // Strip the extension since we want the real name of the script. - COM_StripExtension( name, (char *) newname, sizeof(newname) ); + COM_StripExtension(name, (char *)newname, sizeof(newname)); char *pBuf = NULL; int iLength = 0; // Try to Register the Script. - switch( RegisterScript( newname, (void **) &pBuf, iLength ) ) - { - // If the script has already been registered (or could not be loaded), leave! - case SCRIPT_COULDNOTREGISTER: - if ( !Q_stricmp( newname, "NULL" ) || !Q_stricmp( newname, "default" ) ) - {//these are not real errors, suppress warning - return; - } - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "PrecacheScript: Failed to load %s!\n", newname ); - assert(SCRIPT_COULDNOTREGISTER); - return; - case SCRIPT_ALREADYREGISTERED: + switch (RegisterScript(newname, (void **)&pBuf, iLength)) { + // If the script has already been registered (or could not be loaded), leave! + case SCRIPT_COULDNOTREGISTER: + if (!Q_stricmp(newname, "NULL") || !Q_stricmp(newname, "default")) { // these are not real errors, suppress warning return; + } + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "PrecacheScript: Failed to load %s!\n", newname); + assert(SCRIPT_COULDNOTREGISTER); + return; + case SCRIPT_ALREADYREGISTERED: + return; - // We loaded the script and registered it, so precache it through Icarus now. - case SCRIPT_REGISTERED: - IIcarusInterface::GetIcarus()->Precache( pBuf, iLength ); - return; + // We loaded the script and registered it, so precache it through Icarus now. + case SCRIPT_REGISTERED: + IIcarusInterface::GetIcarus()->Precache(pBuf, iLength); + return; } } -void CQuake3GameInterface::PrecacheSound( const char *name ) -{ +void CQuake3GameInterface::PrecacheSound(const char *name) { char finalName[MAX_QPATH]; - Q_strncpyz( finalName, name, MAX_QPATH ); + Q_strncpyz(finalName, name, MAX_QPATH); Q_strlwr(finalName); - if (com_buildScript->integer) - { //get the male sound first - G_SoundIndex( finalName ); + if (com_buildScript->integer) { // get the male sound first + G_SoundIndex(finalName); } - G_AddSexToPlayerString( finalName, qtrue ); //now get female + G_AddSexToPlayerString(finalName, qtrue); // now get female - G_SoundIndex( finalName ); + G_SoundIndex(finalName); } -void CQuake3GameInterface::PrecacheFromSet( const char *setname, const char *filename ) -{ - //JW NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) +void CQuake3GameInterface::PrecacheFromSet(const char *setname, const char *filename) { + // JW NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) // Get the id for this set identifier then check against valid types. - switch ( GetIDForString( setTable, setname ) ) - { - case SET_SPAWNSCRIPT: - case SET_USESCRIPT: - case SET_AWAKESCRIPT: - case SET_ANGERSCRIPT: - case SET_ATTACKSCRIPT: - case SET_VICTORYSCRIPT: - case SET_LOSTENEMYSCRIPT: - case SET_PAINSCRIPT: - case SET_FLEESCRIPT: - case SET_DEATHSCRIPT: - case SET_DELAYEDSCRIPT: - case SET_BLOCKEDSCRIPT: - case SET_FFIRESCRIPT: - case SET_FFDEATHSCRIPT: - case SET_MINDTRICKSCRIPT: - case SET_CINEMATIC_SKIPSCRIPT: - PrecacheScript(filename); - break; - - case SET_LOOPSOUND: //like ID_SOUND, but set's looping - G_SoundIndex( filename ); - break; + switch (GetIDForString(setTable, setname)) { + case SET_SPAWNSCRIPT: + case SET_USESCRIPT: + case SET_AWAKESCRIPT: + case SET_ANGERSCRIPT: + case SET_ATTACKSCRIPT: + case SET_VICTORYSCRIPT: + case SET_LOSTENEMYSCRIPT: + case SET_PAINSCRIPT: + case SET_FLEESCRIPT: + case SET_DEATHSCRIPT: + case SET_DELAYEDSCRIPT: + case SET_BLOCKEDSCRIPT: + case SET_FFIRESCRIPT: + case SET_FFDEATHSCRIPT: + case SET_MINDTRICKSCRIPT: + case SET_CINEMATIC_SKIPSCRIPT: + PrecacheScript(filename); + break; - case SET_VIDEO_PLAY: //in game cinematic - if (com_buildScript->integer) - { - fileHandle_t file; - char name[MAX_OSPATH]; + case SET_LOOPSOUND: // like ID_SOUND, but set's looping + G_SoundIndex(filename); + break; - if (strstr( filename, "/") == NULL && strstr( filename, "\\") == NULL) { - Com_sprintf ( name, sizeof(name), "video/%s", filename ); - } else { - Com_sprintf ( name, sizeof(name), "%s", filename ); - } - COM_StripExtension( name, name, sizeof(name) ); - COM_DefaultExtension( name, sizeof( name ), ".roq" ); + case SET_VIDEO_PLAY: // in game cinematic + if (com_buildScript->integer) { + fileHandle_t file; + char name[MAX_OSPATH]; - gi.FS_FOpenFile( name, &file, FS_READ ); // trigger the file copy - if (file) - { - gi.FS_FCloseFile( file ); - } + if (strstr(filename, "/") == NULL && strstr(filename, "\\") == NULL) { + Com_sprintf(name, sizeof(name), "video/%s", filename); + } else { + Com_sprintf(name, sizeof(name), "%s", filename); } - break; + COM_StripExtension(name, name, sizeof(name)); + COM_DefaultExtension(name, sizeof(name), ".roq"); - case SET_ADDRHANDBOLT_MODEL: - case SET_ADDLHANDBOLT_MODEL: - { - gi.G2API_PrecacheGhoul2Model( filename ); - } - break; - case SET_WEAPON: - { - const int wp = GetIDForString( WPTable, filename ); - if (wp > 0) - { - gitem_t *item = FindItemForWeapon( (weapon_t) wp); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup - } + gi.FS_FOpenFile(name, &file, FS_READ); // trigger the file copy + if (file) { + gi.FS_FCloseFile(file); } - break; + } + break; - default: - break; + case SET_ADDRHANDBOLT_MODEL: + case SET_ADDLHANDBOLT_MODEL: { + gi.G2API_PrecacheGhoul2Model(filename); + } break; + case SET_WEAPON: { + const int wp = GetIDForString(WPTable, filename); + if (wp > 0) { + gitem_t *item = FindItemForWeapon((weapon_t)wp); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup + } + } break; + + default: + break; } } ////////////////////////////////////////////////////////////////////////// diff --git a/code/game/SpeederNPC.cpp b/code/game/SpeederNPC.cpp index 80f8464dd5..9644038235 100644 --- a/code/game/SpeederNPC.cpp +++ b/code/game/SpeederNPC.cpp @@ -20,11 +20,11 @@ along with this program; if not, see . =========================================================================== */ -//seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles -//or something, so the headers spew errors on these defs from the previous compile. -//this fixes that. -rww +// seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles +// or something, so the headers spew errors on these defs from the previous compile. +// this fixes that. -rww #ifdef _JK2MP -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins @@ -41,19 +41,19 @@ along with this program; if not, see . #undef MOD_EXPLOSIVE #endif -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif #endif -#ifndef _JK2MP //if single player -#ifndef QAGAME //I don't think we have a QAGAME define -#define QAGAME //but define it cause in sp we're always in the game +#ifndef _JK2MP // if single player +#ifndef QAGAME // I don't think we have a QAGAME define +#define QAGAME // but define it cause in sp we're always in the game #endif #endif -#ifdef QAGAME //including game headers on cgame is FORBIDDEN ^_^ +#ifdef QAGAME // including game headers on cgame is FORBIDDEN ^_^ #include "g_local.h" #elif defined _JK2MP #include "bg_public.h" @@ -69,8 +69,8 @@ along with this program; if not, see . #endif #ifdef _JK2MP -//this is really horrible, but it works! just be sure not to use any locals or anything -//with these names (exluding bool, false, true). -rww +// this is really horrible, but it works! just be sure not to use any locals or anything +// with these names (exluding bool, false, true). -rww #define currentAngles r.currentAngles #define currentOrigin r.currentOrigin #define mins r.mins @@ -87,67 +87,68 @@ along with this program; if not, see . #define MOD_EXPLOSIVE MOD_SUICIDE #else #define bgEntity_t gentity_t -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); #endif -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -#ifdef QAGAME //SP or gameside MP -extern vmCvar_t cg_thirdPersonAlpha; +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +#ifdef QAGAME // SP or gameside MP +extern vmCvar_t cg_thirdPersonAlpha; extern vec3_t playerMins; extern vec3_t playerMaxs; -extern cvar_t *g_speederControlScheme; -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); +extern cvar_t *g_speederControlScheme; +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); #endif #ifdef _JK2MP #include "../namespace_begin.h" -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags, int blendTime); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags, int blendTime); extern int BG_GetTime(void); #endif -//Alright, actually, most of this file is shared between game and cgame for MP. -//I would like to keep it this way, so when modifying for SP please keep in -//mind the bgEntity restrictions imposed. -rww - -#define STRAFERAM_DURATION 8 -#define STRAFERAM_ANGLE 8 +// Alright, actually, most of this file is shared between game and cgame for MP. +// I would like to keep it this way, so when modifying for SP please keep in +// mind the bgEntity restrictions imposed. -rww +#define STRAFERAM_DURATION 8 +#define STRAFERAM_ANGLE 8 #ifndef _JK2MP -bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right) -{ - if (!(pVeh->m_ulFlags&VEH_STRAFERAM)) - { - float speed = VectorLength(pVeh->m_pParentEntity->client->ps.velocity); - if (speed>400.0f) - { +bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right) { + if (!(pVeh->m_ulFlags & VEH_STRAFERAM)) { + float speed = VectorLength(pVeh->m_pParentEntity->client->ps.velocity); + if (speed > 400.0f) { // Compute Pos3 //-------------- - vec3_t right; + vec3_t right; AngleVectors(pVeh->m_vOrientation, 0, right, 0); - VectorMA(pVeh->m_pParentEntity->client->ps.velocity, (Right)?( speed):(-speed), right, pVeh->m_pParentEntity->pos3); - - pVeh->m_ulFlags |= VEH_STRAFERAM; - pVeh->m_fStrafeTime = (Right)?(STRAFERAM_DURATION):(-STRAFERAM_DURATION); - - if (pVeh->m_iSoundDebounceTimerm_pVehicleInfo->soundShift1; break; - case 2: shiftSound=pVeh->m_pVehicleInfo->soundShift2; break; - case 3: shiftSound=pVeh->m_pVehicleInfo->soundShift3; break; - case 4: shiftSound=pVeh->m_pVehicleInfo->soundShift4; break; + VectorMA(pVeh->m_pParentEntity->client->ps.velocity, (Right) ? (speed) : (-speed), right, pVeh->m_pParentEntity->pos3); + + pVeh->m_ulFlags |= VEH_STRAFERAM; + pVeh->m_fStrafeTime = (Right) ? (STRAFERAM_DURATION) : (-STRAFERAM_DURATION); + + if (pVeh->m_iSoundDebounceTimer < level.time && Q_irand(0, 1) == 0) { + int shiftSound = Q_irand(1, 4); + switch (shiftSound) { + case 1: + shiftSound = pVeh->m_pVehicleInfo->soundShift1; + break; + case 2: + shiftSound = pVeh->m_pVehicleInfo->soundShift2; + break; + case 3: + shiftSound = pVeh->m_pVehicleInfo->soundShift3; + break; + case 4: + shiftSound = pVeh->m_pVehicleInfo->soundShift4; + break; } - if (shiftSound) - { + if (shiftSound) { pVeh->m_iSoundDebounceTimer = level.time + Q_irand(1000, 4000); - G_SoundIndexOnEnt( pVeh->m_pParentEntity, CHAN_AUTO, shiftSound); + G_SoundIndexOnEnt(pVeh->m_pParentEntity, CHAN_AUTO, shiftSound); } } return true; @@ -156,74 +157,58 @@ bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right) return false; } #else -bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right, int Duration) -{ - return false; -} +bool VEH_StartStrafeRam(Vehicle_t *pVeh, bool Right, int Duration) { return false; } #endif - -#ifdef QAGAME //game-only.. for now +#ifdef QAGAME // game-only.. for now // Like a think or move command, this updates various vehicle properties. -bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ) ) - { +bool Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { + if (!g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd)) { return false; } // See whether this vehicle should be exploding. - if ( pVeh->m_iDieTime != 0 ) - { - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + if (pVeh->m_iDieTime != 0) { + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); } // Update move direction. -#ifndef _JK2MP //this makes prediction unhappy, and rightfully so. +#ifndef _JK2MP // this makes prediction unhappy, and rightfully so. gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if ( pVeh->m_ulFlags & VEH_FLYING ) - { + if (pVeh->m_ulFlags & VEH_FLYING) { vec3_t vVehAngles; - VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0 ); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); - } - else - { + VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); + } else { vec3_t vVehAngles; - VectorSet(vVehAngles, pVeh->m_vOrientation[PITCH], pVeh->m_vOrientation[YAW], 0 ); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); + VectorSet(vVehAngles, pVeh->m_vOrientation[PITCH], pVeh->m_vOrientation[YAW], 0); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); } // Check For A Strafe Ram //------------------------ - if (!(pVeh->m_ulFlags&VEH_STRAFERAM) && !(pVeh->m_ulFlags&VEH_FLYING)) - { + if (!(pVeh->m_ulFlags & VEH_STRAFERAM) && !(pVeh->m_ulFlags & VEH_FLYING)) { // Started A Strafe //------------------ - if (pVeh->m_ucmd.rightmove && !pVeh->m_fStrafeTime) - { - pVeh->m_fStrafeTime = (pVeh->m_ucmd.rightmove>0)?(level.time):(-1*level.time); + if (pVeh->m_ucmd.rightmove && !pVeh->m_fStrafeTime) { + pVeh->m_fStrafeTime = (pVeh->m_ucmd.rightmove > 0) ? (level.time) : (-1 * level.time); } // Ended A Strafe //---------------- - else if (!pVeh->m_ucmd.rightmove && pVeh->m_fStrafeTime) - { + else if (!pVeh->m_ucmd.rightmove && pVeh->m_fStrafeTime) { // If It Was A Short Burst, Start The Strafe Ram //----------------------------------------------- - if ((level.time - abs(pVeh->m_fStrafeTime))<300) - { - if (!VEH_StartStrafeRam(pVeh, (pVeh->m_fStrafeTime>0))) - { + if ((level.time - abs(pVeh->m_fStrafeTime)) < 300) { + if (!VEH_StartStrafeRam(pVeh, (pVeh->m_fStrafeTime > 0))) { pVeh->m_fStrafeTime = 0; } } // Otherwise, Clear The Timer //---------------------------- - else - { + else { pVeh->m_fStrafeTime = 0; } } @@ -231,189 +216,162 @@ bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) // If Currently In A StrafeRam, Check To See If It Is Done (Timed Out) //--------------------------------------------------------------------- - else if (!pVeh->m_fStrafeTime) - { - pVeh->m_ulFlags &=~VEH_STRAFERAM; + else if (!pVeh->m_fStrafeTime) { + pVeh->m_ulFlags &= ~VEH_STRAFERAM; } - // Exhaust Effects Start And Stop When The Accelerator Is Pressed //---------------------------------------------------------------- - if (pVeh->m_pVehicleInfo->iExhaustFX) - { + if (pVeh->m_pVehicleInfo->iExhaustFX) { // Start It On Each Exhaust Bolt //------------------------------- - if (pVeh->m_ucmd.forwardmove && !(pVeh->m_ulFlags&VEH_ACCELERATORON)) - { + if (pVeh->m_ucmd.forwardmove && !(pVeh->m_ulFlags & VEH_ACCELERATORON)) { pVeh->m_ulFlags |= VEH_ACCELERATORON; - for (int i=0; (im_iExhaustTag[i]!=-1); i++) - { - G_PlayEffect(pVeh->m_pVehicleInfo->iExhaustFX, parent->playerModel, pVeh->m_iExhaustTag[i], parent->s.number, parent->currentOrigin, 1, qtrue); + for (int i = 0; (i < MAX_VEHICLE_EXHAUSTS && pVeh->m_iExhaustTag[i] != -1); i++) { + G_PlayEffect(pVeh->m_pVehicleInfo->iExhaustFX, parent->playerModel, pVeh->m_iExhaustTag[i], parent->s.number, parent->currentOrigin, 1, qtrue); } } // Stop It On Each Exhaust Bolt //------------------------------ - else if (!pVeh->m_ucmd.forwardmove && (pVeh->m_ulFlags&VEH_ACCELERATORON)) - { - pVeh->m_ulFlags &=~VEH_ACCELERATORON; - for (int i=0; (im_iExhaustTag[i]!=-1); i++) - { + else if (!pVeh->m_ucmd.forwardmove && (pVeh->m_ulFlags & VEH_ACCELERATORON)) { + pVeh->m_ulFlags &= ~VEH_ACCELERATORON; + for (int i = 0; (i < MAX_VEHICLE_EXHAUSTS && pVeh->m_iExhaustTag[i] != -1); i++) { G_StopEffect(pVeh->m_pVehicleInfo->iExhaustFX, parent->playerModel, pVeh->m_iExhaustTag[i], parent->s.number); } } } - if (!(pVeh->m_ulFlags&VEH_ARMORLOW) && (pVeh->m_iArmor <= pVeh->m_pVehicleInfo->armor/3)) - { + if (!(pVeh->m_ulFlags & VEH_ARMORLOW) && (pVeh->m_iArmor <= pVeh->m_pVehicleInfo->armor / 3)) { pVeh->m_ulFlags |= VEH_ARMORLOW; - } // Armor Gone Effects (Fire) //--------------------------- - if (pVeh->m_pVehicleInfo->iArmorGoneFX) - { - if (!(pVeh->m_ulFlags&VEH_ARMORGONE) && (pVeh->m_iArmor <= 0)) - { + if (pVeh->m_pVehicleInfo->iArmorGoneFX) { + if (!(pVeh->m_ulFlags & VEH_ARMORGONE) && (pVeh->m_iArmor <= 0)) { pVeh->m_ulFlags |= VEH_ARMORGONE; G_PlayEffect(pVeh->m_pVehicleInfo->iArmorGoneFX, parent->playerModel, parent->crotchBolt, parent->s.number, parent->currentOrigin, 1, qtrue); - parent->s.loopSound = G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); + parent->s.loopSound = G_SoundIndex("sound/vehicles/common/fire_lp.wav"); } } #endif return true; } -#endif //QAGAME - -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +#endif // QAGAME + +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations - float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */speedMin, speedMax; + // Client sets ucmds and such for speed alterations + float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */ speedMin, speedMax; playerState_t *parentPS; - //playerState_t *pilotPS = NULL; - int curTime; + // playerState_t *pilotPS = NULL; + int curTime; #ifdef _JK2MP parentPS = pVeh->m_pParentEntity->playerState; - if (pVeh->m_pPilot) - { - //pilotPS = pVeh->m_pPilot->playerState; + if (pVeh->m_pPilot) { + // pilotPS = pVeh->m_pPilot->playerState; } #else parentPS = &pVeh->m_pParentEntity->client->ps; - if (pVeh->m_pPilot) - { - //pilotPS = &pVeh->m_pPilot->client->ps; + if (pVeh->m_pPilot) { + // pilotPS = &pVeh->m_pPilot->client->ps; } #endif - // If we're flying, make us accelerate at 40% (about half) acceleration rate, and restore the pitch // to origin (straight) position (at 5% increments). - if ( pVeh->m_ulFlags & VEH_FLYING ) - { + if (pVeh->m_ulFlags & VEH_FLYING) { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier * 0.4f; } #ifdef _JK2MP - else if ( !parentPS->m_iVehicleNum ) + else if (!parentPS->m_iVehicleNum) #else - else if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) + else if (!pVeh->m_pVehicleInfo->Inhabited(pVeh)) #endif - {//drifts to a stop + { // drifts to a stop speedInc = 0; - //pVeh->m_ucmd.forwardmove = 127; - } - else - { + // pVeh->m_ucmd.forwardmove = 127; + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } speedIdleDec = pVeh->m_pVehicleInfo->decelIdle * pVeh->m_fTimeModifier; -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP curTime = level.time; -#elif defined QAGAME//MP GAME +#elif defined QAGAME // MP GAME curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif - - - if ( (pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && - (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && pVeh->m_pVehicleInfo->turboSpeed) + if ((pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && + pVeh->m_pVehicleInfo->turboSpeed) #ifdef _JK2MP - || - (parentPS && parentPS->electrifyTime > curTime && pVeh->m_pVehicleInfo->turboSpeed) //make them go! + || (parentPS && parentPS->electrifyTime > curTime && pVeh->m_pVehicleInfo->turboSpeed) // make them go! #endif - ) - { + ) { #ifdef _JK2MP - if ( (parentPS && parentPS->electrifyTime > curTime) || - (pVeh->m_pPilot->playerState && - (pVeh->m_pPilot->playerState->weapon == WP_MELEE || - (pVeh->m_pPilot->playerState->weapon == WP_SABER && pVeh->m_pPilot->playerState->saberHolstered))) ) - { + if ((parentPS && parentPS->electrifyTime > curTime) || + (pVeh->m_pPilot->playerState && (pVeh->m_pPilot->playerState->weapon == WP_MELEE || + (pVeh->m_pPilot->playerState->weapon == WP_SABER && pVeh->m_pPilot->playerState->saberHolstered)))) { #endif - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); - if (pVeh->m_pVehicleInfo->iTurboStartFX) - { + if (pVeh->m_pVehicleInfo->iTurboStartFX) { int i; - for (i=0; (im_iExhaustTag[i]!=-1); i++) - { - #ifndef _JK2MP//SP - // Start The Turbo Fx Start - //-------------------------- - G_PlayEffect(pVeh->m_pVehicleInfo->iTurboStartFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin ); - - // Start The Looping Effect - //-------------------------- - if (pVeh->m_pVehicleInfo->iTurboFX) - { - G_PlayEffect(pVeh->m_pVehicleInfo->iTurboFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin, pVeh->m_pVehicleInfo->turboDuration, qtrue); - } - - #else - #ifdef QAGAME - if (pVeh->m_pParentEntity && - pVeh->m_pParentEntity->ghoul2 && - pVeh->m_pParentEntity->playerState) - { //fine, I'll use a tempent for this, but only because it's played only once at the start of a turbo. - vec3_t boltOrg, boltDir; - mdxaBone_t boltMatrix; - - VectorSet(boltDir, 0.0f, pVeh->m_pParentEntity->playerState->viewangles[YAW], 0.0f); - - trap_G2API_GetBoltMatrix(pVeh->m_pParentEntity->ghoul2, 0, pVeh->m_iExhaustTag[i], &boltMatrix, boltDir, pVeh->m_pParentEntity->playerState->origin, level.time, NULL, pVeh->m_pParentEntity->modelScale); - BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); - BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltDir); - G_PlayEffectID(pVeh->m_pVehicleInfo->iTurboStartFX, boltOrg, boltDir); - } - #endif - #endif + for (i = 0; (i < MAX_VEHICLE_EXHAUSTS && pVeh->m_iExhaustTag[i] != -1); i++) { +#ifndef _JK2MP // SP + // Start The Turbo Fx Start + //-------------------------- + G_PlayEffect(pVeh->m_pVehicleInfo->iTurboStartFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], + pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin); + + // Start The Looping Effect + //-------------------------- + if (pVeh->m_pVehicleInfo->iTurboFX) { + G_PlayEffect(pVeh->m_pVehicleInfo->iTurboFX, pVeh->m_pParentEntity->playerModel, pVeh->m_iExhaustTag[i], + pVeh->m_pParentEntity->s.number, pVeh->m_pParentEntity->currentOrigin, pVeh->m_pVehicleInfo->turboDuration, qtrue); + } + +#else +#ifdef QAGAME + if (pVeh->m_pParentEntity && pVeh->m_pParentEntity->ghoul2 && + pVeh->m_pParentEntity + ->playerState) { // fine, I'll use a tempent for this, but only because it's played only once at the start of a turbo. + vec3_t boltOrg, boltDir; + mdxaBone_t boltMatrix; + + VectorSet(boltDir, 0.0f, pVeh->m_pParentEntity->playerState->viewangles[YAW], 0.0f); + + trap_G2API_GetBoltMatrix(pVeh->m_pParentEntity->ghoul2, 0, pVeh->m_iExhaustTag[i], &boltMatrix, boltDir, + pVeh->m_pParentEntity->playerState->origin, level.time, NULL, pVeh->m_pParentEntity->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltDir); + G_PlayEffectID(pVeh->m_pVehicleInfo->iTurboStartFX, boltOrg, boltDir); + } +#endif +#endif } } - #ifndef _JK2MP //kill me now - if (pVeh->m_pVehicleInfo->soundTurbo) - { +#ifndef _JK2MP // kill me now + if (pVeh->m_pVehicleInfo->soundTurbo) { G_SoundIndexOnEnt(pVeh->m_pParentEntity, CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo); } - #endif - parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed +#endif + parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed } #ifdef _JK2MP } @@ -421,105 +379,72 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) } // Slide Breaking - if (pVeh->m_ulFlags&VEH_SLIDEBREAKING) - { - if (pVeh->m_ucmd.forwardmove>=0 + if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) { + if (pVeh->m_ucmd.forwardmove >= 0 #ifndef _JK2MP - || ((level.time - pVeh->m_pParentEntity->lastMoveTime)>500) + || ((level.time - pVeh->m_pParentEntity->lastMoveTime) > 500) #endif - ) - { + ) { pVeh->m_ulFlags &= ~VEH_SLIDEBREAKING; } parentPS->speed = 0; - } - else if ( - (curTime > pVeh->m_iTurboTime) && - !(pVeh->m_ulFlags&VEH_FLYING) && - pVeh->m_ucmd.forwardmove<0 && - fabs(pVeh->m_vOrientation[ROLL])>25.0f) - { + } else if ((curTime > pVeh->m_iTurboTime) && !(pVeh->m_ulFlags & VEH_FLYING) && pVeh->m_ucmd.forwardmove < 0 && fabs(pVeh->m_vOrientation[ROLL]) > 25.0f) { pVeh->m_ulFlags |= VEH_SLIDEBREAKING; } - - if ( curTime < pVeh->m_iTurboTime ) - { + if (curTime < pVeh->m_iTurboTime) { speedMax = pVeh->m_pVehicleInfo->turboSpeed; - if (parentPS) - { + if (parentPS) { parentPS->eFlags |= EF_JETPACK_ACTIVE; } - } - else - { + } else { speedMax = pVeh->m_pVehicleInfo->speedMax; - if (parentPS) - { + if (parentPS) { parentPS->eFlags &= ~EF_JETPACK_ACTIVE; } } - speedIdle = pVeh->m_pVehicleInfo->speedIdle; - //speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; + // speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( !pVeh->m_pVehicleInfo->strafePerc + } else { + if (!pVeh->m_pVehicleInfo->strafePerc #ifdef _JK2MP - || (0 && pVeh->m_pParentEntity->s.number < MAX_CLIENTS) ) + || (0 && pVeh->m_pParentEntity->s.number < MAX_CLIENTS)) #else - || (!g_speederControlScheme->value && !pVeh->m_pParentEntity->s.number) ) + || (!g_speederControlScheme->value && !pVeh->m_pParentEntity->s.number)) #endif - {//if in a strafe-capable vehicle, clear strafing unless using alternate control scheme - //pVeh->m_ucmd.rightmove = 0; + { // if in a strafe-capable vehicle, clear strafing unless using alternate control scheme + // pVeh->m_ucmd.rightmove = 0; } } - if ( parentPS->speed > speedMax ) - { + if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } @@ -527,33 +452,30 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) // In SP, The AI Pilots Can Directly Control The Speed Of Their Bike In Order To // Match The Speed Of The Person They Are Trying To Chase //------------------------------------------------------------------------------- - if (pVeh->m_pPilot && (pVeh->m_ucmd.buttons&BUTTON_VEH_SPEED)) - { + if (pVeh->m_pPilot && (pVeh->m_ucmd.buttons & BUTTON_VEH_SPEED)) { parentPS->speed = pVeh->m_pPilot->client->ps.speed; } #endif - /********************************************************************************/ /* END Here is where we move the vehicle (forward or back or whatever). END */ /********************************************************************************/ } -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -//Oh, and please, use "< MAX_CLIENTS" to check for "player" and not +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// Oh, and please, use "< MAX_CLIENTS" to check for "player" and not //"!s.number", this is a universal check that will work for both SP -//and MP. -rww -// ProcessOrientCommands the Vehicle. -#ifdef _JK2MP //temp hack til mp speeder controls are sorted -rww +// and MP. -rww +// ProcessOrientCommands the Vehicle. +#ifdef _JK2MP // temp hack til mp speeder controls are sorted -rww extern void AnimalProcessOri(Vehicle_t *pVeh); #endif -void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -563,83 +485,59 @@ void ProcessOrientCommands( Vehicle_t *pVeh ) playerState_t *parentPS; float angDif; - if (pVeh->m_pPilot) - { + if (pVeh->m_pPilot) { riderPS = pVeh->m_pPilot->playerState; - } - else - { + } else { riderPS = pVeh->m_pParentEntity->playerState; } - //parentPS = pVeh->m_pParentEntity->playerState; + // parentPS = pVeh->m_pParentEntity->playerState; - //pVeh->m_vOrientation[YAW] = 0.0f;//riderPS->viewangles[YAW]; + // pVeh->m_vOrientation[YAW] = 0.0f;//riderPS->viewangles[YAW]; angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*4.0f; //magic number hackery - if (s < 0.0f) - { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 4.0f; // magic number hackery + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); - if (parentPS->electrifyTime > pm->cmd.serverTime) - { //do some crazy stuff - pVeh->m_vOrientation[YAW] += (sin(pm->cmd.serverTime/1000.0f)*3.0f)*pVeh->m_fTimeModifier; + if (parentPS->electrifyTime > pm->cmd.serverTime) { // do some crazy stuff + pVeh->m_vOrientation[YAW] += (sin(pm->cmd.serverTime / 1000.0f) * 3.0f) * pVeh->m_fTimeModifier; } } #else - gentity_t *rider = pVeh->m_pParentEntity->owner; - if ( !rider || !rider->client ) - { + gentity_t *rider = pVeh->m_pParentEntity->owner; + if (!rider || !rider->client) { riderPS = &pVeh->m_pParentEntity->client->ps; - } - else - { + } else { riderPS = &rider->client->ps; } - //parentPS = &pVeh->m_pParentEntity->client->ps; + // parentPS = &pVeh->m_pParentEntity->client->ps; - if (pVeh->m_ulFlags & VEH_FLYING) - { + if (pVeh->m_ulFlags & VEH_FLYING) { pVeh->m_vOrientation[YAW] += pVeh->m_vAngularVelocity; - } - else if ( - (pVeh->m_ulFlags & VEH_SLIDEBREAKING) || // No Angles Control While Out Of Control - (pVeh->m_ulFlags & VEH_OUTOFCONTROL) // No Angles Control While Out Of Control - ) - { + } else if ((pVeh->m_ulFlags & VEH_SLIDEBREAKING) || // No Angles Control While Out Of Control + (pVeh->m_ulFlags & VEH_OUTOFCONTROL) // No Angles Control While Out Of Control + ) { // Any ability to change orientation? - } - else if ( - (pVeh->m_ulFlags & VEH_STRAFERAM) // No Angles Control While Strafe Ramming - ) - { - if (pVeh->m_fStrafeTime>0) - { + } else if ((pVeh->m_ulFlags & VEH_STRAFERAM) // No Angles Control While Strafe Ramming + ) { + if (pVeh->m_fStrafeTime > 0) { pVeh->m_fStrafeTime--; - pVeh->m_vOrientation[ROLL] += (pVeh->m_fStrafeTime<( STRAFERAM_DURATION/2))?(-STRAFERAM_ANGLE):( STRAFERAM_ANGLE); - } - else if (pVeh->m_fStrafeTime<0) - { + pVeh->m_vOrientation[ROLL] += (pVeh->m_fStrafeTime < (STRAFERAM_DURATION / 2)) ? (-STRAFERAM_ANGLE) : (STRAFERAM_ANGLE); + } else if (pVeh->m_fStrafeTime < 0) { pVeh->m_fStrafeTime++; - pVeh->m_vOrientation[ROLL] += (pVeh->m_fStrafeTime>(-STRAFERAM_DURATION/2))?( STRAFERAM_ANGLE):(-STRAFERAM_ANGLE); + pVeh->m_vOrientation[ROLL] += (pVeh->m_fStrafeTime > (-STRAFERAM_DURATION / 2)) ? (STRAFERAM_ANGLE) : (-STRAFERAM_ANGLE); } - } - else - { + } else { pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; } #endif @@ -651,70 +549,53 @@ void ProcessOrientCommands( Vehicle_t *pVeh ) #ifdef QAGAME -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); // This function makes sure that the vehicle is properly animated. -void AnimateVehicle( Vehicle_t *pVeh ) -{ -} +void AnimateVehicle(Vehicle_t *pVeh) {} -#endif //QAGAME +#endif // QAGAME -//rest of file is shared +// rest of file is shared -#ifndef _JK2MP -extern void CG_ChangeWeapon( int num ); +#ifndef _JK2MP +extern void CG_ChangeWeapon(int num); #endif - #ifndef _JK2MP -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); #endif - -//NOTE NOTE NOTE NOTE NOTE NOTE -//I want to keep this function BG too, because it's fairly generic already, and it -//would be nice to have proper prediction of animations. -rww -// This function makes sure that the rider's in this vehicle are properly animated. -void AnimateRiders( Vehicle_t *pVeh ) -{ +// NOTE NOTE NOTE NOTE NOTE NOTE +// I want to keep this function BG too, because it's fairly generic already, and it +// would be nice to have proper prediction of animations. -rww +// This function makes sure that the rider's in this vehicle are properly animated. +void AnimateRiders(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_VS_IDLE; - //float fSpeedPercToMax; + // float fSpeedPercToMax; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; playerState_t *pilotPS; - //playerState_t *parentPS; + // playerState_t *parentPS; int curTime; - // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { // We've just started moarding, set the amount of time it will take to finish moarding. - if ( pVeh->m_iBoarding < 0 ) - { + if (pVeh->m_iBoarding < 0) { int iAnimLen; // Boarding from left... - if ( pVeh->m_iBoarding == -1 ) - { + if (pVeh->m_iBoarding == -1) { Anim = BOTH_VS_MOUNT_L; - } - else if ( pVeh->m_iBoarding == -2 ) - { + } else if (pVeh->m_iBoarding == -2) { Anim = BOTH_VS_MOUNT_R; - } - else if ( pVeh->m_iBoarding == -3 ) - { + } else if (pVeh->m_iBoarding == -3) { Anim = BOTH_VS_MOUNTJUMP_L; - } - else if ( pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT) - { + } else if (pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT) { iBlend = 0; Anim = BOTH_VS_MOUNTTHROW_R; - } - else if ( pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT) - { + } else if (pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT) { iBlend = 0; Anim = BOTH_VS_MOUNTTHROW_L; } @@ -722,16 +603,13 @@ void AnimateRiders( Vehicle_t *pVeh ) // Set the delay time (which happens to be the time it takes for the animation to complete). // NOTE: Here I made it so the delay is actually 40% (0.4f) of the animation time. #ifdef _JK2MP - iAnimLen = BG_AnimLength( pVeh->m_pPilot->localAnimIndex, Anim ) * 0.4f; + iAnimLen = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim) * 0.4f; pVeh->m_iBoarding = BG_GetTime() + iAnimLen; #else - iAnimLen = PM_AnimLength( pVeh->m_pPilot->client->clientInfo.animFileIndex, Anim );// * 0.4f; - if (pVeh->m_iBoarding!=VEH_MOUNT_THROW_LEFT && pVeh->m_iBoarding!=VEH_MOUNT_THROW_RIGHT) - { - pVeh->m_iBoarding = level.time + (iAnimLen*0.4f); - } - else - { + iAnimLen = PM_AnimLength(pVeh->m_pPilot->client->clientInfo.animFileIndex, Anim); // * 0.4f; + if (pVeh->m_iBoarding != VEH_MOUNT_THROW_LEFT && pVeh->m_iBoarding != VEH_MOUNT_THROW_RIGHT) { + pVeh->m_iBoarding = level.time + (iAnimLen * 0.4f); + } else { pVeh->m_iBoarding = level.time + iAnimLen; } #endif @@ -740,131 +618,123 @@ void AnimateRiders( Vehicle_t *pVeh ) iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; #ifdef _JK2MP - BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, - SETANIM_BOTH, Anim, iFlags, iBlend); + BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags, iBlend); #else - NPC_SetAnim( pVeh->m_pPilot, SETANIM_BOTH, Anim, iFlags, iBlend ); - if (pVeh->m_pOldPilot) - { - iAnimLen = PM_AnimLength( pVeh->m_pPilot->client->clientInfo.animFileIndex, BOTH_VS_MOUNTTHROWEE); - NPC_SetAnim( pVeh->m_pOldPilot, SETANIM_BOTH, BOTH_VS_MOUNTTHROWEE, iFlags, iBlend ); + NPC_SetAnim(pVeh->m_pPilot, SETANIM_BOTH, Anim, iFlags, iBlend); + if (pVeh->m_pOldPilot) { + iAnimLen = PM_AnimLength(pVeh->m_pPilot->client->clientInfo.animFileIndex, BOTH_VS_MOUNTTHROWEE); + NPC_SetAnim(pVeh->m_pOldPilot, SETANIM_BOTH, BOTH_VS_MOUNTTHROWEE, iFlags, iBlend); } #endif } #ifndef _JK2MP - if (pVeh->m_pOldPilot && pVeh->m_pOldPilot->client->ps.torsoAnimTimer<=0) - { - if (Q_irand(0, player->count)==0) - { + if (pVeh->m_pOldPilot && pVeh->m_pOldPilot->client->ps.torsoAnimTimer <= 0) { + if (Q_irand(0, player->count) == 0) { player->count++; - player->lastEnemy = pVeh->m_pOldPilot; - G_StartMatrixEffect(player, MEF_LOOK_AT_ENEMY|MEF_NO_RANGEVAR|MEF_NO_VERTBOB|MEF_NO_SPIN, 1000); + player->lastEnemy = pVeh->m_pOldPilot; + G_StartMatrixEffect(player, MEF_LOOK_AT_ENEMY | MEF_NO_RANGEVAR | MEF_NO_VERTBOB | MEF_NO_SPIN, 1000); } - gentity_t* oldPilot = pVeh->m_pOldPilot; - pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pOldPilot, qtrue); // will set pointer to zero + gentity_t *oldPilot = pVeh->m_pOldPilot; + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pOldPilot, qtrue); // will set pointer to zero // Kill Him //---------- - oldPilot->client->noRagTime = -1; // no ragdoll for you + oldPilot->client->noRagTime = -1; // no ragdoll for you G_Damage(oldPilot, pVeh->m_pPilot, pVeh->m_pPilot, pVeh->m_pPilot->currentAngles, pVeh->m_pPilot->currentOrigin, 1000, 0, MOD_CRUSH); // Compute THe Throw Direction As Backwards From The Vehicle's Velocity //---------------------------------------------------------------------- - vec3_t throwDir; + vec3_t throwDir; VectorScale(pVeh->m_pParentEntity->client->ps.velocity, -1.0f, throwDir); VectorNormalize(throwDir); - throwDir[2] += 0.3f; // up a little + throwDir[2] += 0.3f; // up a little // Now Throw Him Out //------------------- - G_Throw(oldPilot, throwDir, VectorLength(pVeh->m_pParentEntity->client->ps.velocity)/10.0f); - NPC_SetAnim(oldPilot, SETANIM_BOTH, BOTH_DEATHBACKWARD1, SETANIM_FLAG_OVERRIDE, iBlend ); + G_Throw(oldPilot, throwDir, VectorLength(pVeh->m_pParentEntity->client->ps.velocity) / 10.0f); + NPC_SetAnim(oldPilot, SETANIM_BOTH, BOTH_DEATHBACKWARD1, SETANIM_FLAG_OVERRIDE, iBlend); } #endif return; } -#ifdef _JK2MP //fixme - if (1) return; +#ifdef _JK2MP // fixme + if (1) + return; #endif #ifdef _JK2MP pilotPS = pVeh->m_pPilot->playerState; - //parentPS = pVeh->m_pPilot->playerState; + // parentPS = pVeh->m_pPilot->playerState; #else pilotPS = &pVeh->m_pPilot->client->ps; - //parentPS = &pVeh->m_pParentEntity->client->ps; + // parentPS = &pVeh->m_pParentEntity->client->ps; #endif -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP curTime = level.time; -#elif defined QAGAME//MP GAME +#elif defined QAGAME // MP GAME curTime = level.time; -#elif defined CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif defined CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif // Percentage of maximum speed relative to current speed. - //fSpeedPercToMax = parentPS->speed / pVeh->m_pVehicleInfo->speedMax; + // fSpeedPercToMax = parentPS->speed / pVeh->m_pVehicleInfo->speedMax; -/* // Going in reverse... -#ifdef _JK2MP - if ( pVeh->m_ucmd.forwardmove < 0 && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) -#else - if ( fSpeedPercToMax < -0.018f && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) -#endif - { - Anim = BOTH_VS_REV; - iBlend = 500; - bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - if (HasWeapon) + /* // Going in reverse... + #ifdef _JK2MP + if ( pVeh->m_ucmd.forwardmove < 0 && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) + #else + if ( fSpeedPercToMax < -0.018f && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) + #endif { - if (pVeh->m_pPilot->s.numberweapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + if (HasWeapon) { - CG_ChangeWeapon(WP_NONE); - } + if (pVeh->m_pPilot->s.numberm_pPilot->client->ps.weapon = WP_NONE; - G_RemoveWeaponModels(pVeh->m_pPilot); + pVeh->m_pPilot->client->ps.weapon = WP_NONE; + G_RemoveWeaponModels(pVeh->m_pPilot); + } } - } - else -*/ + else + */ { - bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - bool Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons&BUTTON_ATTACK)); -#ifdef _JK2MP //fixme: flying tends to spaz out a lot - bool Flying = false; - bool Crashing = false; + bool HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + bool Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons & BUTTON_ATTACK)); +#ifdef _JK2MP // fixme: flying tends to spaz out a lot + bool Flying = false; + bool Crashing = false; #else - bool Flying = !!(pVeh->m_ulFlags & VEH_FLYING); - bool Crashing = !!(pVeh->m_ulFlags & VEH_CRASHING); + bool Flying = !!(pVeh->m_ulFlags & VEH_FLYING); + bool Crashing = !!(pVeh->m_ulFlags & VEH_CRASHING); #endif - bool Right = (pVeh->m_ucmd.rightmove>0); - bool Left = (pVeh->m_ucmd.rightmove<0); - bool Turbo = (curTimem_iTurboTime); - EWeaponPose WeaponPose = WPOSE_NONE; - + bool Right = (pVeh->m_ucmd.rightmove > 0); + bool Left = (pVeh->m_ucmd.rightmove < 0); + bool Turbo = (curTime < pVeh->m_iTurboTime); + EWeaponPose WeaponPose = WPOSE_NONE; // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - // Put Away Saber When It Is Not Active //-------------------------------------- #ifndef _JK2MP - if (HasWeapon && - (pVeh->m_pPilot->s.number>=MAX_CLIENTS || (cg.weaponSelectTime+500)weapon==WP_SABER && !pilotPS->SaberActive()))) - { - if (pVeh->m_pPilot->s.numberm_pPilot->client->ps.stats[ STAT_WEAPONS ] |= 1; // Riding means you get WP_NONE + if (HasWeapon && (pVeh->m_pPilot->s.number >= MAX_CLIENTS || (cg.weaponSelectTime + 500) < cg.time) && + (Turbo || (pilotPS->weapon == WP_SABER && !pilotPS->SaberActive()))) { + if (pVeh->m_pPilot->s.number < MAX_CLIENTS) { + pVeh->m_pPilot->client->ps.stats[STAT_WEAPONS] |= 1; // Riding means you get WP_NONE CG_ChangeWeapon(WP_NONE); } @@ -876,19 +746,16 @@ void AnimateRiders( Vehicle_t *pVeh ) // Don't Interrupt Attack Anims //------------------------------ #ifdef _JK2MP - if (pilotPS->weaponTime>0) - { + if (pilotPS->weaponTime > 0) { return; } #else - if (pilotPS->torsoAnim>=BOTH_VS_ATL_S && pilotPS->torsoAnim<=BOTH_VS_ATF_G) - { - float bodyCurrent = 0.0f; - int bodyEnd = 0; - if (!!gi.G2API_GetBoneAnimIndex(&pVeh->m_pPilot->ghoul2[pVeh->m_pPilot->playerModel], pVeh->m_pPilot->rootBone, level.time, &bodyCurrent, NULL, &bodyEnd, NULL, NULL, NULL)) - { - if (bodyCurrent<=((float)(bodyEnd)-1.5f)) - { + if (pilotPS->torsoAnim >= BOTH_VS_ATL_S && pilotPS->torsoAnim <= BOTH_VS_ATF_G) { + float bodyCurrent = 0.0f; + int bodyEnd = 0; + if (!!gi.G2API_GetBoneAnimIndex(&pVeh->m_pPilot->ghoul2[pVeh->m_pPilot->playerModel], pVeh->m_pPilot->rootBone, level.time, &bodyCurrent, NULL, + &bodyEnd, NULL, NULL, NULL)) { + if (bodyCurrent <= ((float)(bodyEnd)-1.5f)) { return; } } @@ -897,247 +764,269 @@ void AnimateRiders( Vehicle_t *pVeh ) // Compute The Weapon Pose //-------------------------- - if (pilotPS->weapon==WP_BLASTER) - { + if (pilotPS->weapon == WP_BLASTER) { WeaponPose = WPOSE_BLASTER; - } - else if (pilotPS->weapon==WP_SABER) - { - if ( (pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VS_ATL_TO_R_S) - { - pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; + } else if (pilotPS->weapon == WP_SABER) { + if ((pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VS_ATL_TO_R_S) { + pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; } - if (!(pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VS_ATR_TO_L_S) - { - pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; + if (!(pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VS_ATR_TO_L_S) { + pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; } - WeaponPose = (pVeh->m_ulFlags&VEH_SABERINLEFTHAND)?(WPOSE_SABERLEFT):(WPOSE_SABERRIGHT); + WeaponPose = (pVeh->m_ulFlags & VEH_SABERINLEFTHAND) ? (WPOSE_SABERLEFT) : (WPOSE_SABERRIGHT); } - - if (Attacking && WeaponPose) - {// Attack! - iBlend = 100; - iFlags = SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART; + if (Attacking && WeaponPose) { // Attack! + iBlend = 100; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART; // Auto Aiming //=============================================== - if (!Left && !Right) // Allow player strafe keys to override + if (!Left && !Right) // Allow player strafe keys to override { #ifndef _JK2MP - if (pVeh->m_pPilot->enemy) - { - vec3_t toEnemy; - //float toEnemyDistance; - vec3_t actorRight; - float actorRightDot; + if (pVeh->m_pPilot->enemy) { + vec3_t toEnemy; + // float toEnemyDistance; + vec3_t actorRight; + float actorRightDot; VectorSubtract(pVeh->m_pPilot->currentOrigin, pVeh->m_pPilot->enemy->currentOrigin, toEnemy); - /*toEnemyDistance = */VectorNormalize(toEnemy); + /*toEnemyDistance = */ VectorNormalize(toEnemy); AngleVectors(pVeh->m_pParentEntity->currentAngles, 0, actorRight, 0); actorRightDot = DotProduct(toEnemy, actorRight); - if (fabsf(actorRightDot)>0.5f || pilotPS->weapon==WP_SABER) - { - Left = (actorRightDot>0.0f); - Right = !Left; - } - else - { + if (fabsf(actorRightDot) > 0.5f || pilotPS->weapon == WP_SABER) { + Left = (actorRightDot > 0.0f); + Right = !Left; + } else { Right = Left = false; } - } - else + } else #endif - if (pilotPS->weapon==WP_SABER && !Left && !Right) - { - Left = (WeaponPose==WPOSE_SABERLEFT); - Right = !Left; + if (pilotPS->weapon == WP_SABER && !Left && !Right) { + Left = (WeaponPose == WPOSE_SABERLEFT); + Right = !Left; } } - - if (Left) - {// Attack Left - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_ATL_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_ATR_TO_L_S; break; - default: assert(0); + if (Left) { // Attack Left + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_ATL_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_ATR_TO_L_S; + break; + default: + assert(0); } - } - else if (Right) - {// Attack Right - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_ATL_TO_R_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_ATR_S; break; - default: assert(0); + } else if (Right) { // Attack Right + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_ATL_TO_R_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_ATR_S; + break; + default: + assert(0); } - } - else - {// Attack Ahead - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATF_G; break; - default: assert(0); + } else { // Attack Ahead + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATF_G; + break; + default: + assert(0); } } - } - else if (Left && pVeh->m_ucmd.buttons&BUTTON_USE) - {// Look To The Left Behind - iBlend = 400; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: Anim = BOTH_VS_LOOKLEFT; + } else if (Left && pVeh->m_ucmd.buttons & BUTTON_USE) { // Look To The Left Behind + iBlend = 400; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + switch (WeaponPose) { + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + Anim = BOTH_VS_LOOKLEFT; } - } - else if (Right && pVeh->m_ucmd.buttons&BUTTON_USE) - {// Look To The Right Behind - iBlend = 400; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: Anim = BOTH_VS_LOOKRIGHT; + } else if (Right && pVeh->m_ucmd.buttons & BUTTON_USE) { // Look To The Right Behind + iBlend = 400; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + switch (WeaponPose) { + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + Anim = BOTH_VS_LOOKRIGHT; } - } - else if (Turbo) - {// Kicked In Turbo - iBlend = 50; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - Anim = BOTH_VS_TURBO; - } - else if (Flying) - {// Off the ground in a jump - iBlend = 800; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + } else if (Turbo) { // Kicked In Turbo + iBlend = 50; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + Anim = BOTH_VS_TURBO; + } else if (Flying) { // Off the ground in a jump + iBlend = 800; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_AIR; break; - case WPOSE_BLASTER: Anim = BOTH_VS_AIR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_AIR_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_AIR_SR; break; - default: assert(0); + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_AIR; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_AIR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_AIR_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_AIR_SR; + break; + default: + assert(0); } - } - else if (Crashing) - {// Hit the ground! - iBlend = 100; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LAND; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LAND_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LAND_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LAND_SR; break; - default: assert(0); + } else if (Crashing) { // Hit the ground! + iBlend = 100; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LAND; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LAND_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LAND_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LAND_SR; + break; + default: + assert(0); } - } - else - {// No Special Moves - iBlend = 300; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - if (pVeh->m_vOrientation[ROLL] <= -20) - {// Lean Left - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LEANL; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LEANL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LEANL_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LEANL_SR; break; - default: assert(0); + } else { // No Special Moves + iBlend = 300; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + if (pVeh->m_vOrientation[ROLL] <= -20) { // Lean Left + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LEANL; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LEANL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LEANL_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LEANL_SR; + break; + default: + assert(0); } - } - else if (pVeh->m_vOrientation[ROLL] >= 20) - {// Lean Right - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LEANR; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LEANR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LEANR_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LEANR_SR; break; - default: assert(0); + } else if (pVeh->m_vOrientation[ROLL] >= 20) { // Lean Right + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LEANR; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LEANR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LEANR_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LEANR_SR; + break; + default: + assert(0); } - } - else - {// No Lean - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_IDLE; break; - case WPOSE_BLASTER: Anim = BOTH_VS_IDLE_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: assert(0); + } else { // No Lean + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_IDLE; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_IDLE_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + assert(0); } } - }// No Special Moves - }// Going backwards? + } // No Special Moves + } // Going backwards? #ifdef _JK2MP iFlags &= ~SETANIM_FLAG_OVERRIDE; - if (pVeh->m_pPilot->playerState->torsoAnim == Anim) - { + if (pVeh->m_pPilot->playerState->torsoAnim == Anim) { pVeh->m_pPilot->playerState->torsoTimer = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim); } - if (pVeh->m_pPilot->playerState->legsAnim == Anim) - { + if (pVeh->m_pPilot->playerState->legsAnim == Anim) { pVeh->m_pPilot->playerState->legsTimer = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim); } - BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, - SETANIM_BOTH, Anim, iFlags|SETANIM_FLAG_HOLD, iBlend); + BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags | SETANIM_FLAG_HOLD, iBlend); #else - NPC_SetAnim( pVeh->m_pPilot, SETANIM_BOTH, Anim, iFlags, iBlend ); + NPC_SetAnim(pVeh->m_pPilot, SETANIM_BOTH, Anim, iFlags, iBlend); #endif } #ifndef QAGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -void G_SetSpeederVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +void G_SetSpeederVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef QAGAME - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; -// pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + // pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; #endif - //shared - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + // shared + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef QAGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef QAGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -1154,26 +1043,24 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -void G_CreateSpeederNPC( Vehicle_t **pVeh, const char *strType ) -{ +void G_CreateSpeederNPC(Vehicle_t **pVeh, const char *strType) { #ifdef _JK2MP #ifdef QAGAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strType)]; #else // Allocate the Vehicle. - (*pVeh) = (Vehicle_t *) gi.Malloc( sizeof(Vehicle_t), TAG_G_ALLOC, qtrue ); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strType )]; + (*pVeh) = (Vehicle_t *)gi.Malloc(sizeof(Vehicle_t), TAG_G_ALLOC, qtrue); + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strType)]; #endif } @@ -1181,7 +1068,7 @@ void G_CreateSpeederNPC( Vehicle_t **pVeh, const char *strType ) #include "../namespace_end.h" -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins diff --git a/code/game/WalkerNPC.cpp b/code/game/WalkerNPC.cpp index 4ec0bb2e53..4994392a16 100644 --- a/code/game/WalkerNPC.cpp +++ b/code/game/WalkerNPC.cpp @@ -20,11 +20,11 @@ along with this program; if not, see . =========================================================================== */ -//seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles -//or something, so the headers spew errors on these defs from the previous compile. -//this fixes that. -rww +// seems to be a compiler bug, it doesn't clean out the #ifdefs between dif-compiles +// or something, so the headers spew errors on these defs from the previous compile. +// this fixes that. -rww #ifdef _JK2MP -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins @@ -41,19 +41,19 @@ along with this program; if not, see . #undef MOD_EXPLOSIVE #endif -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif #endif -#ifndef _JK2MP //if single player -#ifndef QAGAME //I don't think we have a QAGAME define -#define QAGAME //but define it cause in sp we're always in the game +#ifndef _JK2MP // if single player +#ifndef QAGAME // I don't think we have a QAGAME define +#define QAGAME // but define it cause in sp we're always in the game #endif #endif -#ifdef QAGAME //including game headers on cgame is FORBIDDEN ^_^ +#ifdef QAGAME // including game headers on cgame is FORBIDDEN ^_^ #include "g_local.h" #elif defined _JK2MP #include "bg_public.h" @@ -67,8 +67,8 @@ along with this program; if not, see . #endif #ifdef _JK2MP -//this is really horrible, but it works! just be sure not to use any locals or anything -//with these names (exluding bool, false, true). -rww +// this is really horrible, but it works! just be sure not to use any locals or anything +// with these names (exluding bool, false, true). -rww #define currentAngles r.currentAngles #define currentOrigin r.currentOrigin #define mins r.mins @@ -87,30 +87,29 @@ along with this program; if not, see . #define bgEntity_t gentity_t #endif -#ifdef QAGAME //we only want a few of these functions for BG +#ifdef QAGAME // we only want a few of these functions for BG -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -extern vmCvar_t cg_thirdPersonAlpha; +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +extern vmCvar_t cg_thirdPersonAlpha; extern vec3_t playerMins; extern vec3_t playerMaxs; -extern cvar_t *g_speederControlScheme; -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); - -static void RegisterAssets( Vehicle_t *pVeh ) -{ - //atst uses turret weapon +extern cvar_t *g_speederControlScheme; +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); + +static void RegisterAssets(Vehicle_t *pVeh) { + // atst uses turret weapon #ifdef _JK2MP RegisterItem(BG_FindItemForWeapon(WP_TURRET)); #else // PUT SOMETHING HERE... #endif - //call the standard RegisterAssets now - g_vehicleInfo[VEHICLE_BASE].RegisterAssets( pVeh ); + // call the standard RegisterAssets now + g_vehicleInfo[VEHICLE_BASE].RegisterAssets(pVeh); } // Like a think or move command, this updates various vehicle properties. @@ -122,9 +121,8 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) */ // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -static bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Board( pVeh, pEnt ) ) +static bool Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { + if (!g_vehicleInfo[VEHICLE_BASE].Board(pVeh, pEnt)) return false; // Set the board wait time (they won't be able to do anything, including getting off, for this amount of time). @@ -132,27 +130,26 @@ static bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) return true; } -#endif //QAGAME +#endif // QAGAME #ifdef _JK2MP #include "../namespace_begin.h" #endif -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations - float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */speedMin, speedMax; + // Client sets ucmds and such for speed alterations + float speedInc, speedIdleDec, speedIdle, /*speedIdleAccel, */ speedMin, speedMax; float fWalkSpeedMax; bgEntity_t *parent = pVeh->m_pParentEntity; #ifdef _JK2MP @@ -165,69 +162,50 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedMax = pVeh->m_pVehicleInfo->speedMax; speedIdle = pVeh->m_pVehicleInfo->speedIdle; - //speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; + // speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; #ifdef _JK2MP - if ( !parentPS->m_iVehicleNum ) + if (!parentPS->m_iVehicleNum) #else - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh)) #endif - {//drifts to a stop + { // drifts to a stop speedInc = speedIdle * pVeh->m_fTimeModifier; - VectorClear( parentPS->moveDir ); - //m_ucmd.forwardmove = 127; + VectorClear(parentPS->moveDir); + // m_ucmd.forwardmove = 127; parentPS->speed = 0; - } - else - { + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } @@ -241,16 +219,11 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) } fWalkSpeedMax = speedMax * 0.275f; - if ( pVeh->m_ucmd.buttons & BUTTON_WALKING && parentPS->speed > fWalkSpeedMax ) - { + if (pVeh->m_ucmd.buttons & BUTTON_WALKING && parentPS->speed > fWalkSpeedMax) { parentPS->speed = fWalkSpeedMax; - } - else if ( parentPS->speed > speedMax ) - { + } else if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } @@ -260,30 +233,28 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) } #ifdef _JK2MP -extern void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS); //FighterNPC.c -extern void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS); //FighterNPC.c +extern void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS); // FighterNPC.c +extern void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS); // FighterNPC.c #endif -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ - //float speed; + // float speed; bgEntity_t *parent = pVeh->m_pParentEntity; playerState_t *parentPS, *riderPS; #ifdef _JK2MP bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } #else @@ -291,9 +262,9 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #endif #ifdef _JK2MP - if ( !rider ) + if (!rider) #else - if ( !rider || !rider->client ) + if (!rider || !rider->client) #endif { rider = parent; @@ -307,59 +278,51 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) riderPS = &rider->client->ps; #endif - //speed = VectorLength( parentPS->velocity ); + // speed = VectorLength( parentPS->velocity ); // If the player is the rider... - if ( rider->s.number < MAX_CLIENTS ) - {//FIXME: use the vehicle's turning stat in this calc + if (rider->s.number < MAX_CLIENTS) { // FIXME: use the vehicle's turning stat in this calc #ifdef _JK2MP FighterYawAdjust(pVeh, riderPS, parentPS); - //FighterPitchAdjust(pVeh, riderPS, parentPS); + // FighterPitchAdjust(pVeh, riderPS, parentPS); pVeh->m_vOrientation[PITCH] = riderPS->viewangles[PITCH]; #else pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; pVeh->m_vOrientation[PITCH] = riderPS->viewangles[PITCH]; #endif - } - else - { + } else { float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; - if ( !pVeh->m_pVehicleInfo->turnWhenStopped - && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? - {//can't turn when not moving - //FIXME: or ramp up to max turnSpeed? + if (!pVeh->m_pVehicleInfo->turnWhenStopped && !parentPS->speed) // FIXME: or !pVeh->m_ucmd.forwardmove? + { // can't turn when not moving + // FIXME: or ramp up to max turnSpeed? turnSpeed = 0.0f; } #ifdef _JK2MP if (rider->s.eType == ET_NPC) #else - if ( !rider || rider->NPC ) + if (!rider || rider->NPC) #endif - {//help NPCs out some + { // help NPCs out some turnSpeed *= 2.0f; #ifdef _JK2MP if (parentPS->speed > 200.0f) #else - if ( parent->client->ps.speed > 200.0f ) + if (parent->client->ps.speed > 200.0f) #endif { - turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + turnSpeed += turnSpeed * parentPS->speed / 200.0f * 0.05f; } } turnSpeed *= pVeh->m_fTimeModifier; - //default control scheme: strafing turns, mouselook aims - if ( pVeh->m_ucmd.rightmove < 0 ) - { + // default control scheme: strafing turns, mouselook aims + if (pVeh->m_ucmd.rightmove < 0) { pVeh->m_vOrientation[YAW] += turnSpeed; - } - else if ( pVeh->m_ucmd.rightmove > 0 ) - { + } else if (pVeh->m_ucmd.rightmove > 0) { pVeh->m_vOrientation[YAW] -= turnSpeed; } - if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) - {//damaged badly + if (pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel) { // damaged badly } } @@ -368,63 +331,60 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -#ifdef QAGAME //back to our game-only functions +#ifdef QAGAME // back to our game-only functions // This function makes sure that the vehicle is properly animated. -static void AnimateVehicle( Vehicle_t *pVeh ) -{ +static void AnimateVehicle(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_STAND1; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; float fSpeedPercToMax; // We're dead (boarding is reused here so I don't have to make another variable :-). - if ( parent->health <= 0 ) - { - if ( pVeh->m_iBoarding != -999 ) // Animate the death just once! + if (parent->health <= 0) { + if (pVeh->m_iBoarding != -999) // Animate the death just once! { pVeh->m_iBoarding = -999; iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; // FIXME! Why do you keep repeating over and over!!?!?!? Bastard! - //Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_DEATH1, iFlags, iBlend ); + // Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_DEATH1, iFlags, iBlend ); } return; } -// Following is redundant to g_vehicles.c -// if ( pVeh->m_iBoarding ) -// { -// //we have no boarding anim -// if (pVeh->m_iBoarding < level.time) -// { //we are on now -// pVeh->m_iBoarding = 0; -// } -// else -// { -// return; -// } -// } + // Following is redundant to g_vehicles.c + // if ( pVeh->m_iBoarding ) + // { + // //we have no boarding anim + // if (pVeh->m_iBoarding < level.time) + // { //we are on now + // pVeh->m_iBoarding = 0; + // } + // else + // { + // return; + // } + // } // Percentage of maximum speed relative to current speed. - //float fSpeed = VectorLength( client->ps.velocity ); + // float fSpeed = VectorLength( client->ps.velocity ); fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; // If we're moving... - if ( fSpeedPercToMax > 0.0f ) //fSpeedPercToMax >= 0.85f ) + if (fSpeedPercToMax > 0.0f) // fSpeedPercToMax >= 0.85f ) { - //float fYawDelta; + // float fYawDelta; iBlend = 300; iFlags = SETANIM_FLAG_OVERRIDE; - //fYawDelta = pVeh->m_vPrevOrientation[YAW] - pVeh->m_vOrientation[YAW]; + // fYawDelta = pVeh->m_vPrevOrientation[YAW] - pVeh->m_vOrientation[YAW]; // NOTE: Mikes suggestion for fixing the stuttering walk (left/right) is to maintain the // current frame between animations. I have no clue how to do this and have to work on other // stuff so good luck to him :-p AReis // If we're walking (or our speed is less than .275%)... - if ( ( pVeh->m_ucmd.buttons & BUTTON_WALKING ) || fSpeedPercToMax < 0.275f ) - { + if ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax < 0.275f) { // Make them lean if we're turning. /*if ( fYawDelta < -0.0001f ) { @@ -435,13 +395,10 @@ static void AnimateVehicle( Vehicle_t *pVeh ) Anim = BOTH_VT_WALK_FWD_R; } else*/ - { - Anim = BOTH_WALK1; - } + { Anim = BOTH_WALK1; } } // otherwise we're running. - else - { + else { // Make them lean if we're turning. /*if ( fYawDelta < -0.0001f ) { @@ -452,23 +409,16 @@ static void AnimateVehicle( Vehicle_t *pVeh ) Anim = BOTH_VT_RUN_FWD_R; } else*/ - { - Anim = BOTH_RUN1; - } + { Anim = BOTH_RUN1; } } - } - else - { + } else { // Going in reverse... - if ( fSpeedPercToMax < -0.018f ) - { + if (fSpeedPercToMax < -0.018f) { iFlags = SETANIM_FLAG_NORMAL; Anim = BOTH_WALKBACK1; iBlend = 500; - } - else - { - //int iChance = Q_irand( 0, 20000 ); + } else { + // int iChance = Q_irand( 0, 20000 ); // Every once in a while buck or do a different idle... iFlags = SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD; @@ -476,60 +426,57 @@ static void AnimateVehicle( Vehicle_t *pVeh ) #ifdef _JK2MP if (parent->client->ps.m_iVehicleNum) #else - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) #endif - {//occupado + { // occupado Anim = BOTH_STAND1; - } - else - {//wide open for you, baby + } else { // wide open for you, baby Anim = BOTH_STAND2; } } } - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); } -//rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful -//and lagged -#endif //QAGAME +// rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful +// and lagged +#endif // QAGAME #ifndef QAGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -//on the client this function will only set up the process command funcs -void G_SetWalkerVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +// on the client this function will only set up the process command funcs +void G_SetWalkerVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef QAGAME - pVehInfo->AnimateVehicle = AnimateVehicle; -// pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; - pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; - pVehInfo->RegisterAssets = RegisterAssets; + pVehInfo->AnimateVehicle = AnimateVehicle; + // pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + pVehInfo->RegisterAssets = RegisterAssets; // pVehInfo->Initialize = Initialize; // pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; -#endif //QAGAME - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; +#endif // QAGAME + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef QAGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef QAGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -546,27 +493,25 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -//this is a BG function too in MP so don't un-bg-compatibilify it -rww -void G_CreateWalkerNPC( Vehicle_t **pVeh, const char *strAnimalType ) -{ +// this is a BG function too in MP so don't un-bg-compatibilify it -rww +void G_CreateWalkerNPC(Vehicle_t **pVeh, const char *strAnimalType) { // Allocate the Vehicle. #ifdef _JK2MP #ifdef QAGAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; #else - (*pVeh) = (Vehicle_t *) gi.Malloc( sizeof(Vehicle_t), TAG_G_ALLOC, qtrue ); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh) = (Vehicle_t *)gi.Malloc(sizeof(Vehicle_t), TAG_G_ALLOC, qtrue); + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; #endif } @@ -574,7 +519,7 @@ void G_CreateWalkerNPC( Vehicle_t **pVeh, const char *strAnimalType ) #include "../namespace_end.h" -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins diff --git a/code/game/bg_misc.cpp b/code/game/bg_misc.cpp index 8bf42c7f28..46d88366b5 100644 --- a/code/game/bg_misc.cpp +++ b/code/game/bg_misc.cpp @@ -30,11 +30,9 @@ along with this program; if not, see . #include "g_items.h" #include "g_vehicles.h" - extern weaponData_t weaponData[WP_NUM_WEAPONS]; extern ammoData_t ammoData[AMMO_MAX]; - #define PICKUPSOUND "sound/weapons/w_pkup.wav" /*QUAKED weapon_***** ( 0 0 0 ) (-16 -16 -16) (16 16 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY @@ -58,8 +56,8 @@ An item fires all of its targets when it is picked up. If the toucher can't car "enemy" */ -/*QUAKED weapon_stun_baton (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY NOGLOW USEPICKUP STATIONARY -model="/models/weapons2/stun_baton/baton.md3" +/*QUAKED weapon_stun_baton (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY NOGLOW USEPICKUP +STATIONARY model="/models/weapons2/stun_baton/baton.md3" */ /*QUAKED weapon_saber (.3 .3 1) (-16 -16 -8) (16 16 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID LEANING INVISIBLE NOGLOW USEPICKUP STATIONARY SUSPENDED - allow items to hang in the air, otherwise they are dropped to the next surface. @@ -77,12 +75,10 @@ When picked up, will be used as a second saber unless: 3) You set "saberSolo" to "1" 4) You have 2 sabers and the saber pickup is on your right when you touch it -saberType - entry name from sabers.cfg - which kind of saber this is - use "player" to make it so that the saber will be whatever saber the player is configured to use -saberColor - red, orange, yellow, green, blue, and purple -saberLeftHand - always be added as a left-hand saber -saberSolo - set to "1" and this will be the only saber the person who picks this up will be holding -saberPitch - if set "LEANING" flag, you can specify the exact pitch to lean forward/back -count - how many you can pick up before it's removed (default is 1, -1 is infinite) +saberType - entry name from sabers.cfg - which kind of saber this is - use "player" to make it so that the saber will be whatever saber the player is configured +to use saberColor - red, orange, yellow, green, blue, and purple saberLeftHand - always be added as a left-hand saber saberSolo - set to "1" and this will be +the only saber the person who picks this up will be holding saberPitch - if set "LEANING" flag, you can specify the exact pitch to lean forward/back count - how +many you can pick up before it's removed (default is 1, -1 is infinite) */ /*QUAKED weapon_bryar_pistol (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY model="/models/weapons2/briar_pistol/briar_pistol.md3" @@ -137,9 +133,9 @@ model="/models/items/datapad.md3" model="/models/items/binoculars.md3" */ /*QUAKED item_sentry_gun (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_la_goggles (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED ammo_force (.3 .5 1) (-8 -8 -0) (8 8 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID Ammo for the force. */ @@ -166,15 +162,15 @@ Belt of thermal detonators */ /*QUAKED item_medpak_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY -*/ + */ /*QUAKED item_shield_sm_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY -*/ + */ /*QUAKED item_shield_lrg_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND NOPLAYER ALLOWNPC NOTSOLID VERTICAL INVISIBLE NOGLOW USEPICKUP STATIONARY -*/ + */ /*QUAKED item_goodie_key (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_security_key (.3 .3 1) (-8 -8 0) (8 8 16) suspended message - used to differentiate one key from another. */ @@ -237,12 +233,10 @@ force saberthrow pickup item "count" level of force power this holocron gives activator ( range: 0-3, default 1) */ -gitem_t bg_itemlist[ITM_NUM_ITEMS+1];//need a null on the end - -//int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) ; -const int bg_numItems = ITM_NUM_ITEMS; - +gitem_t bg_itemlist[ITM_NUM_ITEMS + 1]; // need a null on the end +// int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) ; +const int bg_numItems = ITM_NUM_ITEMS; /* =============== @@ -250,40 +244,36 @@ FindItemForWeapon =============== */ -gitem_t *FindItemForWeapon( weapon_t weapon ) { - int i; +gitem_t *FindItemForWeapon(weapon_t weapon) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( bg_itemlist[i].giType == IT_WEAPON && bg_itemlist[i].giTag == weapon ) { + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giType == IT_WEAPON && bg_itemlist[i].giTag == weapon) { return &bg_itemlist[i]; } } - Com_Error( ERR_DROP, "Couldn't find item for weapon %i", weapon); + Com_Error(ERR_DROP, "Couldn't find item for weapon %i", weapon); return NULL; } //---------------------------------------------- -gitem_t *FindItemForInventory( int inv ) -{ - int i; - gitem_t *it; +gitem_t *FindItemForInventory(int inv) { + int i; + gitem_t *it; // Now just check for any other kind of item. - for ( i = 1 ; i < bg_numItems ; i++ ) - { + for (i = 1; i < bg_numItems; i++) { it = &bg_itemlist[i]; - if ( it->giType == IT_HOLDABLE ) - { - if ( it->giTag == inv ) - { + if (it->giType == IT_HOLDABLE) { + if (it->giTag == inv) { return it; } } } - Com_Error( ERR_DROP, "Couldn't find item for inventory %i", inv ); + Com_Error(ERR_DROP, "Couldn't find item for inventory %i", inv); return NULL; } @@ -293,19 +283,16 @@ FindItemForWeapon =============== */ -gitem_t *FindItemForAmmo( ammo_t ammo ) -{ - int i; +gitem_t *FindItemForAmmo(ammo_t ammo) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) - { - if ( bg_itemlist[i].giType == IT_AMMO && bg_itemlist[i].giTag == ammo ) - { + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giType == IT_AMMO && bg_itemlist[i].giTag == ammo) { return &bg_itemlist[i]; } } - Com_Error( ERR_DROP, "Couldn't find item for ammo %i", ammo ); + Com_Error(ERR_DROP, "Couldn't find item for ammo %i", ammo); return NULL; } @@ -315,18 +302,17 @@ FindItem =============== */ -gitem_t *FindItem( const char *className ) { - int i; +gitem_t *FindItem(const char *className) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( !Q_stricmp( bg_itemlist[i].classname, className ) ) + for (i = 1; i < bg_numItems; i++) { + if (!Q_stricmp(bg_itemlist[i].classname, className)) return &bg_itemlist[i]; } return NULL; } - /* ================ BG_CanItemBeGrabbed @@ -335,32 +321,28 @@ Returns false if the item should not be picked up. This needs to be the same for client side prediction and server use. ================ */ -qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps ) { - gitem_t *item; +qboolean BG_CanItemBeGrabbed(const entityState_t *ent, const playerState_t *ps) { + gitem_t *item; - if ( ent->modelindex < 1 || ent->modelindex >= bg_numItems ) { - Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" ); + if (ent->modelindex < 1 || ent->modelindex >= bg_numItems) { + Com_Error(ERR_DROP, "BG_CanItemBeGrabbed: index out of range"); } item = &bg_itemlist[ent->modelindex]; - switch( item->giType ) { + switch (item->giType) { case IT_WEAPON: // See if we already have this weapon. - if ( !(ps->stats[ STAT_WEAPONS ] & ( 1 << item->giTag ))) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << item->giTag))) { // Don't have this weapon yet, so pick it up. return qtrue; - } - else if ( item->giTag == WP_SABER ) - {//always pick up a saber, might be a new one? + } else if (item->giTag == WP_SABER) { // always pick up a saber, might be a new one? return qtrue; } // Make sure that we aren't already full on ammo for this weapon - if ( ps->ammo[weaponData[item->giTag].ammoIndex] >= ammoData[weaponData[item->giTag].ammoIndex].max ) - { + if (ps->ammo[weaponData[item->giTag].ammoIndex] >= ammoData[weaponData[item->giTag].ammoIndex].max) { // full, so don't grab the item return qfalse; } @@ -369,69 +351,58 @@ qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps case IT_AMMO: - if (item->giTag != AMMO_FORCE) - { + if (item->giTag != AMMO_FORCE) { // since the ammo is the weapon in this case, picking up ammo should actually give you the weapon - switch( item->giTag ) - { + switch (item->giTag) { case AMMO_THERMAL: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_THERMAL ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_THERMAL))) { return qtrue; } break; case AMMO_DETPACK: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_DET_PACK ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_DET_PACK))) { return qtrue; } break; case AMMO_TRIPMINE: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_TRIP_MINE ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_TRIP_MINE))) { return qtrue; } break; } - if ( ps->ammo[ item->giTag ] >= ammoData[item->giTag].max ) // checkme + if (ps->ammo[item->giTag] >= ammoData[item->giTag].max) // checkme { - return qfalse; // can't hold any more + return qfalse; // can't hold any more } - } - else - { - if (ps->forcePower >= ammoData[item->giTag].max*2) - { - return qfalse; // can't hold any more + } else { + if (ps->forcePower >= ammoData[item->giTag].max * 2) { + return qfalse; // can't hold any more } - } return qtrue; case IT_ARMOR: // we also clamp armor to the maxhealth for handicapping - if ( ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH] ) { + if (ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH]) { return qfalse; } return qtrue; case IT_HEALTH: - if ((ps->forcePowersActive & (1 << FP_RAGE))) - {//ragers can't use health + if ((ps->forcePowersActive & (1 << FP_RAGE))) { // ragers can't use health return qfalse; } // don't pick up if already at max - if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] ) { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) { return qfalse; } return qtrue; case IT_BATTERY: // don't pick up if already at max - if ( ps->batteryCharge >= MAX_BATTERIES ) - { + if (ps->batteryCharge >= MAX_BATTERIES) { return qfalse; } return qtrue; @@ -440,13 +411,10 @@ qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps // pretty lame but for now you can always pick these up return qtrue; - case IT_HOLDABLE: - if ( item->giTag >= INV_ELECTROBINOCULARS && item->giTag <= INV_SENTRY ) - { + if (item->giTag >= INV_ELECTROBINOCULARS && item->giTag <= INV_SENTRY) { // hardcoded--can only pick up five of any holdable - if ( ps->inventory[item->giTag] >= 5 ) - { + if (ps->inventory[item->giTag] >= 5) { return qfalse; } } @@ -467,60 +435,54 @@ EvaluateTrajectory ================ */ -void EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void EvaluateTrajectory(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorCopy( tr->trBase, result ); + VectorCopy(tr->trBase, result); break; case TR_LINEAR: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = (float)sin( deltaTime * M_PI * 2 ); - VectorMA( tr->trBase, phase, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = (float)sin(deltaTime * M_PI * 2); + VectorMA(tr->trBase, phase, tr->trDelta, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - //old totally linear - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - if ( deltaTime < 0 ) - {//going past the total duration + // old totally linear + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + if (deltaTime < 0) { // going past the total duration deltaTime = 0; } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - //new slow-down at end - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { + // new slow-down at end + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { deltaTime = 0; + } else { // FIXME: maybe scale this somehow? So that it starts out faster and stops faster? + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)atTime - tr->trTime) / (float)tr->trDuration)))); } - else - {//FIXME: maybe scale this somehow? So that it starts out faster and stops faster? - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)atTime-tr->trTime)/(float)tr->trDuration)) )); - } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); - result[2] -= 0.5F * g_gravity->value * deltaTime * deltaTime;//DEFAULT_GRAVITY + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); + result[2] -= 0.5F * g_gravity->value * deltaTime * deltaTime; // DEFAULT_GRAVITY break; default: - Com_Error( ERR_DROP, "EvaluateTrajectory: unknown trType: %i", tr->trTime ); + Com_Error(ERR_DROP, "EvaluateTrajectory: unknown trType: %i", tr->trTime); break; } } @@ -532,48 +494,46 @@ EvaluateTrajectoryDelta Returns current speed at given time ================ */ -void EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void EvaluateTrajectoryDelta(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorClear( result ); + VectorClear(result); break; case TR_LINEAR: - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = (float)cos( deltaTime * M_PI * 2 ); // derivative of sin = cos + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = (float)cos(deltaTime * M_PI * 2); // derivative of sin = cos phase *= 0.5; - VectorScale( tr->trDelta, phase, result ); + VectorScale(tr->trDelta, phase, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { - VectorClear( result ); + if (atTime > tr->trTime + tr->trDuration) { + VectorClear(result); return; } - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { - VectorClear( result ); + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { + VectorClear(result); return; } - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)atTime-tr->trTime)/(float)tr->trDuration)) )); - VectorScale( tr->trDelta, deltaTime, result ); + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)atTime - tr->trTime) / (float)tr->trDuration)))); + VectorScale(tr->trDelta, deltaTime, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorCopy( tr->trDelta, result ); - result[2] -= g_gravity->value * deltaTime; // DEFAULT_GRAVITY + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorCopy(tr->trDelta, result); + result[2] -= g_gravity->value * deltaTime; // DEFAULT_GRAVITY break; default: - Com_Error( ERR_DROP, "EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime ); + Com_Error(ERR_DROP, "EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime); break; } } @@ -585,22 +545,19 @@ AddEventToPlayerstate Handles the sequence numbers =============== */ -void AddEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps ) { - ps->events[ps->eventSequence & (MAX_PS_EVENTS-1)] = newEvent; - ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS-1)] = eventParm; +void AddEventToPlayerstate(int newEvent, int eventParm, playerState_t *ps) { + ps->events[ps->eventSequence & (MAX_PS_EVENTS - 1)] = newEvent; + ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS - 1)] = eventParm; ps->eventSequence++; } - /* =============== CurrentPlayerstateEvent =============== */ -int CurrentPlayerstateEvent( playerState_t *ps ) { - return ps->events[ (ps->eventSequence-1) & (MAX_PS_EVENTS-1) ]; -} +int CurrentPlayerstateEvent(playerState_t *ps) { return ps->events[(ps->eventSequence - 1) & (MAX_PS_EVENTS - 1)]; } /* ======================== @@ -610,60 +567,56 @@ This is done after each set of usercmd_t on the server, and after local prediction on the client ======================== */ -void PlayerStateToEntityState( playerState_t *ps, entityState_t *s ) -{ - int i; +void PlayerStateToEntityState(playerState_t *ps, entityState_t *s) { + int i; - if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) - { + if (ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) { s->eType = ET_INVISIBLE; } /*else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) { s->eType = ET_INVISIBLE; } */ - else - { + else { s->eType = ET_PLAYER; } s->number = ps->clientNum; s->pos.trType = TR_INTERPOLATE; - VectorCopy( ps->origin, s->pos.trBase ); - //SnapVector( s->pos.trBase ); + VectorCopy(ps->origin, s->pos.trBase); + // SnapVector( s->pos.trBase ); s->apos.trType = TR_INTERPOLATE; - VectorCopy( ps->viewangles, s->apos.trBase ); - //SnapVector( s->apos.trBase ); + VectorCopy(ps->viewangles, s->apos.trBase); + // SnapVector( s->apos.trBase ); s->angles2[YAW] = ps->movementDir; s->legsAnim = ps->legsAnim; s->torsoAnim = ps->torsoAnim; - s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number - // so corpses can also reference the proper config + s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number + // so corpses can also reference the proper config s->eFlags = ps->eFlags; // new sabre stuff - s->saberActive = ps->SaberActive();//WHY is this on the entityState_t, too??? + s->saberActive = ps->SaberActive(); // WHY is this on the entityState_t, too??? s->saberInFlight = ps->saberInFlight; // NOTE: Although we store this stuff locally on a vehicle, who's to say we // can't bring back these variables and fill them at the appropriate time? -Aurelio // We need to bring these in from the vehicle NPC. - if ( g_entities[ps->clientNum].client && g_entities[ps->clientNum].client->NPC_class == CLASS_VEHICLE && g_entities[ps->clientNum].NPC ) - { + if (g_entities[ps->clientNum].client && g_entities[ps->clientNum].client->NPC_class == CLASS_VEHICLE && g_entities[ps->clientNum].NPC) { Vehicle_t *pVeh = g_entities[ps->clientNum].m_pVehicle; s->vehicleArmor = pVeh->m_iArmor; - VectorCopy( pVeh->m_vOrientation, s->vehicleAngles ); + VectorCopy(pVeh->m_vOrientation, s->vehicleAngles); } s->weapon = ps->weapon; s->groundEntityNum = ps->groundEntityNum; s->powerups = 0; - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { - if ( ps->powerups[ i ] ) { + for (i = 0; i < MAX_POWERUPS; i++) { + if (ps->powerups[i]) { s->powerups |= 1 << i; } } @@ -704,7 +657,6 @@ void PlayerStateToEntityState( playerState_t *ps, entityState_t *s ) #endif } - /* ============ BG_PlayerTouchesItem @@ -712,25 +664,20 @@ BG_PlayerTouchesItem Items can be picked up without actually touching their physical bounds ============ */ -qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime ) { - vec3_t origin = { 0.0f }; +qboolean BG_PlayerTouchesItem(playerState_t *ps, entityState_t *item, int atTime) { + vec3_t origin = {0.0f}; - EvaluateTrajectory( &item->pos, atTime, origin ); + EvaluateTrajectory(&item->pos, atTime, origin); // we are ignoring ducked differences here - if ( ps->origin[0] - origin[0] > 44 - || ps->origin[0] - origin[0] < -50 - || ps->origin[1] - origin[1] > 36 - || ps->origin[1] - origin[1] < -36 - || ps->origin[2] - origin[2] > 36 - || ps->origin[2] - origin[2] < -36 ) { + if (ps->origin[0] - origin[0] > 44 || ps->origin[0] - origin[0] < -50 || ps->origin[1] - origin[1] > 36 || ps->origin[1] - origin[1] < -36 || + ps->origin[2] - origin[2] > 36 || ps->origin[2] - origin[2] < -36) { return qfalse; } return qtrue; } - /* ================= BG_EmplacedView @@ -738,38 +685,27 @@ BG_EmplacedView Shared code for emplaced angle gun constriction ================= */ -int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint) -{ +int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint) { float dif = AngleSubtract(baseAngles[YAW], angles[YAW]); - if (dif > constraint || - dif < -constraint) - { + if (dif > constraint || dif < -constraint) { float amt; - if (dif > constraint) - { - amt = (dif-constraint); + if (dif > constraint) { + amt = (dif - constraint); dif = constraint; - } - else if (dif < -constraint) - { - amt = (dif+constraint); + } else if (dif < -constraint) { + amt = (dif + constraint); dif = -constraint; - } - else - { + } else { amt = 0.0f; } *newYaw = AngleSubtract(angles[YAW], -dif); - if (amt > 1.0f || amt < -1.0f) - { //significant, force the view + if (amt > 1.0f || amt < -1.0f) { // significant, force the view return 2; - } - else - { //just a little out of range + } else { // just a little out of range return 1; } } diff --git a/code/game/bg_pangles.cpp b/code/game/bg_pangles.cpp index 052dc31cf0..289573760a 100644 --- a/code/game/bg_pangles.cpp +++ b/code/game/bg_pangles.cpp @@ -35,105 +35,94 @@ along with this program; if not, see . #include "g_vehicles.h" #include "../ghoul2/ghoul2_gore.h" -extern void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InReboundJump( int anim ); -extern qboolean PM_StabDownAnim( int anim ); -extern qboolean PM_DodgeAnim( int anim ); -extern qboolean PM_DodgeHoldAnim( int anim ); -extern qboolean PM_InReboundHold( int anim ); -extern qboolean PM_InKnockDownNoGetup( playerState_t *ps ); -extern qboolean PM_InGetUpNoRoll( playerState_t *ps ); -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern qboolean G_ControlledByPlayer( gentity_t *self ); +extern void CG_SetClientViewAngles(vec3_t angles, qboolean overrideViewEnt); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InReboundJump(int anim); +extern qboolean PM_StabDownAnim(int anim); +extern qboolean PM_DodgeAnim(int anim); +extern qboolean PM_DodgeHoldAnim(int anim); +extern qboolean PM_InReboundHold(int anim); +extern qboolean PM_InKnockDownNoGetup(playerState_t *ps); +extern qboolean PM_InGetUpNoRoll(playerState_t *ps); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern qboolean G_ControlledByPlayer(gentity_t *self); extern qboolean cg_usingInFrontOf; -extern qboolean player_locked; -extern pmove_t *pm; -extern pml_t pml; +extern qboolean player_locked; +extern pmove_t *pm; +extern pml_t pml; -extern cvar_t *g_debugMelee; +extern cvar_t *g_debugMelee; - -void BG_IK_MoveLimb( CGhoul2Info_v &ghoul2, int boltIndex, char *animBone, char *firstBone, char *secondBone, - int time, entityState_t *ent, int animFileIndex, int basePose, - vec3_t desiredPos, qboolean *ikInProgress, vec3_t origin, - vec3_t angles, vec3_t scale, int blendTime, qboolean forceHalt ) -{ +void BG_IK_MoveLimb(CGhoul2Info_v &ghoul2, int boltIndex, char *animBone, char *firstBone, char *secondBone, int time, entityState_t *ent, int animFileIndex, + int basePose, vec3_t desiredPos, qboolean *ikInProgress, vec3_t origin, vec3_t angles, vec3_t scale, int blendTime, qboolean forceHalt) { mdxaBone_t holdPointMatrix; vec3_t holdPoint; vec3_t torg; float distToDest; - animation_t *anim = &level.knownAnimFileSets[animFileIndex].animations[basePose]; + animation_t *anim = &level.knownAnimFileSets[animFileIndex].animations[basePose]; - assert( ghoul2.size() ); + assert(ghoul2.size()); - assert( anim->firstFrame > 0 );//FIXME: umm...? + assert(anim->firstFrame > 0); // FIXME: umm...? - if ( !*ikInProgress && !forceHalt ) - { + if (!*ikInProgress && !forceHalt) { sharedSetBoneIKStateParams_t ikP; - //restrict the shoulder joint - //VectorSet(ikP.pcjMins,-50.0f,-80.0f,-15.0f); - //VectorSet(ikP.pcjMaxs,15.0f,40.0f,15.0f); + // restrict the shoulder joint + // VectorSet(ikP.pcjMins,-50.0f,-80.0f,-15.0f); + // VectorSet(ikP.pcjMaxs,15.0f,40.0f,15.0f); - //for now, leaving it unrestricted, but restricting elbow joint. - //This lets us break the arm however we want in order to fling people - //in throws, and doesn't look bad. - VectorSet( ikP.pcjMins, 0, 0, 0 ); - VectorSet( ikP.pcjMaxs, 0, 0, 0 ); + // for now, leaving it unrestricted, but restricting elbow joint. + // This lets us break the arm however we want in order to fling people + // in throws, and doesn't look bad. + VectorSet(ikP.pcjMins, 0, 0, 0); + VectorSet(ikP.pcjMaxs, 0, 0, 0); - //give the info on our entity. + // give the info on our entity. ikP.blendTime = blendTime; - VectorCopy( origin, ikP.origin ); - VectorCopy( angles, ikP.angles ); + VectorCopy(origin, ikP.origin); + VectorCopy(angles, ikP.angles); ikP.angles[PITCH] = 0; ikP.pcjOverrides = 0; ikP.radius = 10.0f; - VectorCopy( scale, ikP.scale ); + VectorCopy(scale, ikP.scale); - //base pose frames for the limb + // base pose frames for the limb ikP.startFrame = anim->firstFrame + anim->numFrames; ikP.endFrame = anim->firstFrame + anim->numFrames; - //ikP.forceAnimOnBone = qfalse; //let it use existing anim if it's the same as this one. - - //we want to call with a null bone name first. This will init all of the - //ik system stuff on the g2 instance, because we need ragdoll effectors - //in order for our pcj's to know how to angle properly. - if ( !gi.G2API_SetBoneIKState( ghoul2, time, NULL, IKS_DYNAMIC, &ikP ) ) - { - assert( !"Failed to init IK system for g2 instance!" ); - } - - //Now, create our IK bone state. - if ( gi.G2API_SetBoneIKState( ghoul2, time, "lower_lumbar", IKS_DYNAMIC, &ikP ) ) - { - //restrict the elbow joint - VectorSet( ikP.pcjMins, -90.0f, -20.0f, -20.0f ); - VectorSet( ikP.pcjMaxs, 30.0f, 20.0f, -20.0f ); - if ( gi.G2API_SetBoneIKState( ghoul2, time, "upper_lumbar", IKS_DYNAMIC, &ikP ) ) - { - //restrict the elbow joint - VectorSet( ikP.pcjMins, -90.0f, -20.0f, -20.0f ); - VectorSet( ikP.pcjMaxs, 30.0f, 20.0f, -20.0f ); - if ( gi.G2API_SetBoneIKState( ghoul2, time, "thoracic", IKS_DYNAMIC, &ikP ) ) - { - //restrict the elbow joint - VectorSet( ikP.pcjMins, -90.0f, -20.0f, -20.0f ); - VectorSet( ikP.pcjMaxs, 30.0f, 20.0f, -20.0f ); - if ( gi.G2API_SetBoneIKState( ghoul2, time, secondBone, IKS_DYNAMIC, &ikP ) ) - { - //restrict the elbow joint - VectorSet( ikP.pcjMins, -90.0f, -20.0f, -20.0f ); - VectorSet( ikP.pcjMaxs, 30.0f, 20.0f, -20.0f ); - - if ( gi.G2API_SetBoneIKState( ghoul2, time, firstBone, IKS_DYNAMIC, &ikP ) ) - { //everything went alright. + // ikP.forceAnimOnBone = qfalse; //let it use existing anim if it's the same as this one. + + // we want to call with a null bone name first. This will init all of the + // ik system stuff on the g2 instance, because we need ragdoll effectors + // in order for our pcj's to know how to angle properly. + if (!gi.G2API_SetBoneIKState(ghoul2, time, NULL, IKS_DYNAMIC, &ikP)) { + assert(!"Failed to init IK system for g2 instance!"); + } + + // Now, create our IK bone state. + if (gi.G2API_SetBoneIKState(ghoul2, time, "lower_lumbar", IKS_DYNAMIC, &ikP)) { + // restrict the elbow joint + VectorSet(ikP.pcjMins, -90.0f, -20.0f, -20.0f); + VectorSet(ikP.pcjMaxs, 30.0f, 20.0f, -20.0f); + if (gi.G2API_SetBoneIKState(ghoul2, time, "upper_lumbar", IKS_DYNAMIC, &ikP)) { + // restrict the elbow joint + VectorSet(ikP.pcjMins, -90.0f, -20.0f, -20.0f); + VectorSet(ikP.pcjMaxs, 30.0f, 20.0f, -20.0f); + if (gi.G2API_SetBoneIKState(ghoul2, time, "thoracic", IKS_DYNAMIC, &ikP)) { + // restrict the elbow joint + VectorSet(ikP.pcjMins, -90.0f, -20.0f, -20.0f); + VectorSet(ikP.pcjMaxs, 30.0f, 20.0f, -20.0f); + if (gi.G2API_SetBoneIKState(ghoul2, time, secondBone, IKS_DYNAMIC, &ikP)) { + // restrict the elbow joint + VectorSet(ikP.pcjMins, -90.0f, -20.0f, -20.0f); + VectorSet(ikP.pcjMaxs, 30.0f, 20.0f, -20.0f); + + if (gi.G2API_SetBoneIKState(ghoul2, time, firstBone, IKS_DYNAMIC, &ikP)) { // everything went alright. *ikInProgress = qtrue; } } @@ -142,300 +131,247 @@ void BG_IK_MoveLimb( CGhoul2Info_v &ghoul2, int boltIndex, char *animBone, char } } - if ( *ikInProgress && !forceHalt ) - { //actively update our ik state. + if (*ikInProgress && !forceHalt) { // actively update our ik state. sharedIKMoveParams_t ikM; CRagDollUpdateParams tuParms; vec3_t tAngles; - //set the argument struct up - VectorCopy( desiredPos, ikM.desiredOrigin ); //we want the bone to move here.. if possible + // set the argument struct up + VectorCopy(desiredPos, ikM.desiredOrigin); // we want the bone to move here.. if possible - VectorCopy( angles, tAngles ); + VectorCopy(angles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; - gi.G2API_GetBoltMatrix( ghoul2, 0, boltIndex, &holdPointMatrix, tAngles, origin, time, 0, scale ); - //Get the point position from the matrix. + gi.G2API_GetBoltMatrix(ghoul2, 0, boltIndex, &holdPointMatrix, tAngles, origin, time, 0, scale); + // Get the point position from the matrix. holdPoint[0] = holdPointMatrix.matrix[0][3]; holdPoint[1] = holdPointMatrix.matrix[1][3]; holdPoint[2] = holdPointMatrix.matrix[2][3]; - VectorSubtract( holdPoint, desiredPos, torg ); - distToDest = VectorLength( torg ); + VectorSubtract(holdPoint, desiredPos, torg); + distToDest = VectorLength(torg); - //closer we are, more we want to keep updated. - //if we're far away we don't want to be too fast or we'll start twitching all over. - if ( distToDest < 2 ) - { //however if we're this close we want very precise movement + // closer we are, more we want to keep updated. + // if we're far away we don't want to be too fast or we'll start twitching all over. + if (distToDest < 2) { // however if we're this close we want very precise movement ikM.movementSpeed = 0.4f; - } - else if ( distToDest < 16 ) - { - ikM.movementSpeed = 0.9f;//8.0f; - } - else if ( distToDest < 32 ) - { - ikM.movementSpeed = 0.8f;//4.0f; - } - else if ( distToDest < 64 ) - { - ikM.movementSpeed = 0.7f;//2.0f; - } - else - { + } else if (distToDest < 16) { + ikM.movementSpeed = 0.9f; // 8.0f; + } else if (distToDest < 32) { + ikM.movementSpeed = 0.8f; // 4.0f; + } else if (distToDest < 64) { + ikM.movementSpeed = 0.7f; // 2.0f; + } else { ikM.movementSpeed = 0.6f; } - VectorCopy( origin, ikM.origin ); //our position in the world. + VectorCopy(origin, ikM.origin); // our position in the world. ikM.boneName[0] = 0; - if ( gi.G2API_IKMove( ghoul2, time, &ikM ) ) - { - //now do the standard model animate stuff with ragdoll update params. - VectorCopy( angles, tuParms.angles ); + if (gi.G2API_IKMove(ghoul2, time, &ikM)) { + // now do the standard model animate stuff with ragdoll update params. + VectorCopy(angles, tuParms.angles); tuParms.angles[PITCH] = 0; - VectorCopy( origin, tuParms.position ); - VectorCopy( scale, tuParms.scale ); + VectorCopy(origin, tuParms.position); + VectorCopy(scale, tuParms.scale); tuParms.me = ent->number; - VectorClear( tuParms.velocity ); + VectorClear(tuParms.velocity); - gi.G2API_AnimateG2Models( ghoul2, time, &tuParms ); - } - else - { + gi.G2API_AnimateG2Models(ghoul2, time, &tuParms); + } else { *ikInProgress = qfalse; } - } - else if ( *ikInProgress ) - { //kill it + } else if (*ikInProgress) { // kill it float cFrame, animSpeed; int sFrame, eFrame, flags; - gi.G2API_SetBoneIKState( ghoul2, time, "lower_lumbar", IKS_NONE, NULL ); - gi.G2API_SetBoneIKState( ghoul2, time, "upper_lumbar", IKS_NONE, NULL ); - gi.G2API_SetBoneIKState( ghoul2, time, "thoracic", IKS_NONE, NULL ); - gi.G2API_SetBoneIKState( ghoul2, time, secondBone, IKS_NONE, NULL ); - gi.G2API_SetBoneIKState( ghoul2, time, firstBone, IKS_NONE, NULL ); - - //then reset the angles/anims on these PCJs - gi.G2API_SetBoneAngles( &ghoul2[0], "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time ); - gi.G2API_SetBoneAngles( &ghoul2[0], "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time ); - gi.G2API_SetBoneAngles( &ghoul2[0], "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time ); - gi.G2API_SetBoneAngles( &ghoul2[0], secondBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time ); - gi.G2API_SetBoneAngles( &ghoul2[0], firstBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time ); - - //Get the anim/frames that the pelvis is on exactly, and match the left arm back up with them again. - gi.G2API_GetBoneAnim( &ghoul2[0], animBone, (const int)time, &cFrame, &sFrame, &eFrame, &flags, &animSpeed, 0 ); - gi.G2API_SetBoneAnim( &ghoul2[0], "lower_lumbar", sFrame, eFrame, flags, animSpeed, time, sFrame, 300 ); - gi.G2API_SetBoneAnim( &ghoul2[0], "upper_lumbar", sFrame, eFrame, flags, animSpeed, time, sFrame, 300 ); - gi.G2API_SetBoneAnim( &ghoul2[0], "thoracic", sFrame, eFrame, flags, animSpeed, time, sFrame, 300 ); - gi.G2API_SetBoneAnim( &ghoul2[0], secondBone, sFrame, eFrame, flags, animSpeed, time, sFrame, 300 ); - gi.G2API_SetBoneAnim( &ghoul2[0], firstBone, sFrame, eFrame, flags, animSpeed, time, sFrame, 300 ); - - //And finally, get rid of all the ik state effector data by calling with null bone name (similar to how we init it). - gi.G2API_SetBoneIKState( ghoul2, time, NULL, IKS_NONE, NULL ); + gi.G2API_SetBoneIKState(ghoul2, time, "lower_lumbar", IKS_NONE, NULL); + gi.G2API_SetBoneIKState(ghoul2, time, "upper_lumbar", IKS_NONE, NULL); + gi.G2API_SetBoneIKState(ghoul2, time, "thoracic", IKS_NONE, NULL); + gi.G2API_SetBoneIKState(ghoul2, time, secondBone, IKS_NONE, NULL); + gi.G2API_SetBoneIKState(ghoul2, time, firstBone, IKS_NONE, NULL); + + // then reset the angles/anims on these PCJs + gi.G2API_SetBoneAngles(&ghoul2[0], "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); + gi.G2API_SetBoneAngles(&ghoul2[0], "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); + gi.G2API_SetBoneAngles(&ghoul2[0], "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); + gi.G2API_SetBoneAngles(&ghoul2[0], secondBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); + gi.G2API_SetBoneAngles(&ghoul2[0], firstBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); + + // Get the anim/frames that the pelvis is on exactly, and match the left arm back up with them again. + gi.G2API_GetBoneAnim(&ghoul2[0], animBone, (const int)time, &cFrame, &sFrame, &eFrame, &flags, &animSpeed, 0); + gi.G2API_SetBoneAnim(&ghoul2[0], "lower_lumbar", sFrame, eFrame, flags, animSpeed, time, sFrame, 300); + gi.G2API_SetBoneAnim(&ghoul2[0], "upper_lumbar", sFrame, eFrame, flags, animSpeed, time, sFrame, 300); + gi.G2API_SetBoneAnim(&ghoul2[0], "thoracic", sFrame, eFrame, flags, animSpeed, time, sFrame, 300); + gi.G2API_SetBoneAnim(&ghoul2[0], secondBone, sFrame, eFrame, flags, animSpeed, time, sFrame, 300); + gi.G2API_SetBoneAnim(&ghoul2[0], firstBone, sFrame, eFrame, flags, animSpeed, time, sFrame, 300); + + // And finally, get rid of all the ik state effector data by calling with null bone name (similar to how we init it). + gi.G2API_SetBoneIKState(ghoul2, time, NULL, IKS_NONE, NULL); *ikInProgress = qfalse; } } -void PM_IKUpdate( gentity_t *ent ) -{ - //The bone we're holding them by and the next bone after that +void PM_IKUpdate(gentity_t *ent) { + // The bone we're holding them by and the next bone after that char *animBone = "lower_lumbar"; char *firstBone = "lradius"; char *secondBone = "lhumerus"; char *defaultBoltName = "*r_hand"; - if ( !ent->client ) - { + if (!ent->client) { return; } - if ( ent->client->ps.heldByClient <= ENTITYNUM_WORLD ) - { //then put our arm in this client's hand + if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) { // then put our arm in this client's hand gentity_t *holder = &g_entities[ent->client->ps.heldByClient]; - if ( holder && holder->inuse && holder->client && holder->ghoul2.size()) - { - if ( !ent->client->ps.heldByBolt ) - {//bolt wan't set - ent->client->ps.heldByBolt = gi.G2API_AddBolt( &holder->ghoul2[0], defaultBoltName ); + if (holder && holder->inuse && holder->client && holder->ghoul2.size()) { + if (!ent->client->ps.heldByBolt) { // bolt wan't set + ent->client->ps.heldByBolt = gi.G2API_AddBolt(&holder->ghoul2[0], defaultBoltName); } - } - else - { //they're gone, stop holding me + } else { // they're gone, stop holding me ent->client->ps.heldByClient = 0; return; } - if ( ent->client->ps.heldByBolt ) - { + if (ent->client->ps.heldByBolt) { mdxaBone_t boltMatrix; vec3_t boltOrg; vec3_t tAngles; - VectorCopy( holder->client->ps.viewangles, tAngles ); + VectorCopy(holder->client->ps.viewangles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; - gi.G2API_GetBoltMatrix( holder->ghoul2, 0, ent->client->ps.heldByBolt, &boltMatrix, tAngles, holder->client->ps.origin, level.time, 0, holder->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, boltOrg ); + gi.G2API_GetBoltMatrix(holder->ghoul2, 0, ent->client->ps.heldByBolt, &boltMatrix, tAngles, holder->client->ps.origin, level.time, 0, + holder->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, boltOrg); - int grabbedByBolt = gi.G2API_AddBolt( &ent->ghoul2[0], firstBone ); - if ( grabbedByBolt ) - { - //point the limb - BG_IK_MoveLimb( ent->ghoul2, grabbedByBolt, animBone, firstBone, secondBone, - level.time, &ent->s, ent->client->clientInfo.animFileIndex, - ent->client->ps.torsoAnim/*BOTH_DEAD1*/, boltOrg, &ent->client->ps.ikStatus, - ent->client->ps.origin, ent->client->ps.viewangles, ent->s.modelScale, - 500, qfalse ); - - //now see if we need to be turned and/or pulled + int grabbedByBolt = gi.G2API_AddBolt(&ent->ghoul2[0], firstBone); + if (grabbedByBolt) { + // point the limb + BG_IK_MoveLimb(ent->ghoul2, grabbedByBolt, animBone, firstBone, secondBone, level.time, &ent->s, ent->client->clientInfo.animFileIndex, + ent->client->ps.torsoAnim /*BOTH_DEAD1*/, boltOrg, &ent->client->ps.ikStatus, ent->client->ps.origin, ent->client->ps.viewangles, + ent->s.modelScale, 500, qfalse); + + // now see if we need to be turned and/or pulled vec3_t grabDiff, grabbedByOrg; - VectorCopy( ent->client->ps.viewangles, tAngles ); + VectorCopy(ent->client->ps.viewangles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; - gi.G2API_GetBoltMatrix( ent->ghoul2, 0, grabbedByBolt, &boltMatrix, tAngles, ent->client->ps.origin, level.time, 0, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, grabbedByOrg ); + gi.G2API_GetBoltMatrix(ent->ghoul2, 0, grabbedByBolt, &boltMatrix, tAngles, ent->client->ps.origin, level.time, 0, ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, grabbedByOrg); - //check for turn + // check for turn vec3_t org2Targ, org2Bolt; - VectorSubtract( boltOrg, ent->currentOrigin, org2Targ ); - float org2TargYaw = vectoyaw( org2Targ ); - VectorSubtract( grabbedByOrg, ent->currentOrigin, org2Bolt ); - float org2BoltYaw = vectoyaw( org2Bolt ); - if ( org2TargYaw-1.0f > org2BoltYaw ) - { + VectorSubtract(boltOrg, ent->currentOrigin, org2Targ); + float org2TargYaw = vectoyaw(org2Targ); + VectorSubtract(grabbedByOrg, ent->currentOrigin, org2Bolt); + float org2BoltYaw = vectoyaw(org2Bolt); + if (org2TargYaw - 1.0f > org2BoltYaw) { ent->currentAngles[YAW]++; - G_SetAngles( ent, ent->currentAngles ); - } - else if ( org2TargYaw+1.0f < org2BoltYaw ) - { + G_SetAngles(ent, ent->currentAngles); + } else if (org2TargYaw + 1.0f < org2BoltYaw) { ent->currentAngles[YAW]--; - G_SetAngles( ent, ent->currentAngles ); + G_SetAngles(ent, ent->currentAngles); } - //check for pull - VectorSubtract( boltOrg, grabbedByOrg, grabDiff ); - if ( VectorLength( grabDiff ) > 128.0f ) - {//too far, release me + // check for pull + VectorSubtract(boltOrg, grabbedByOrg, grabDiff); + if (VectorLength(grabDiff) > 128.0f) { // too far, release me ent->client->ps.heldByClient = holder->client->ps.heldClient = ENTITYNUM_NONE; - } - else if ( 1 ) - {//pull me along + } else if (1) { // pull me along trace_t trace; vec3_t destOrg; - VectorAdd( ent->currentOrigin, grabDiff, destOrg ); - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, destOrg, ent->s.number, (ent->clipmask&~holder->contents), (EG2_Collision)0, 0 ); - G_SetOrigin( ent, trace.endpos ); - //FIXME: better yet: do an actual slidemove to the new pos? - //FIXME: if I'm alive, just tell me to walk some? + VectorAdd(ent->currentOrigin, grabDiff, destOrg); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, destOrg, ent->s.number, (ent->clipmask & ~holder->contents), (EG2_Collision)0, + 0); + G_SetOrigin(ent, trace.endpos); + // FIXME: better yet: do an actual slidemove to the new pos? + // FIXME: if I'm alive, just tell me to walk some? } - //FIXME: if I need to turn to keep my bone facing him, do so... + // FIXME: if I need to turn to keep my bone facing him, do so... } - //don't let us fall? - VectorClear( ent->client->ps.velocity ); - //FIXME: also make the holder point his holding limb at you? - } - } - else if ( ent->client->ps.ikStatus ) - { //make sure we aren't IKing if we don't have anyone to hold onto us. - if ( ent && ent->inuse && ent->client && ent->ghoul2.size() ) - { - if ( !ent->client->ps.heldByBolt ) - { - ent->client->ps.heldByBolt = gi.G2API_AddBolt( &ent->ghoul2[0], defaultBoltName ); + // don't let us fall? + VectorClear(ent->client->ps.velocity); + // FIXME: also make the holder point his holding limb at you? + } + } else if (ent->client->ps.ikStatus) { // make sure we aren't IKing if we don't have anyone to hold onto us. + if (ent && ent->inuse && ent->client && ent->ghoul2.size()) { + if (!ent->client->ps.heldByBolt) { + ent->client->ps.heldByBolt = gi.G2API_AddBolt(&ent->ghoul2[0], defaultBoltName); } - } - else - { //This shouldn't happen, but just in case it does, we'll have a failsafe. + } else { // This shouldn't happen, but just in case it does, we'll have a failsafe. ent->client->ps.heldByBolt = 0; ent->client->ps.ikStatus = qfalse; } - if ( ent->client->ps.heldByBolt ) - { - BG_IK_MoveLimb( ent->ghoul2, ent->client->ps.heldByBolt, animBone, firstBone, secondBone, - level.time, &ent->s, ent->client->clientInfo.animFileIndex, - ent->client->ps.torsoAnim/*BOTH_DEAD1*/, (float *)vec3_origin, - &ent->client->ps.ikStatus, ent->client->ps.origin, - ent->client->ps.viewangles, ent->s.modelScale, 500, qtrue ); + if (ent->client->ps.heldByBolt) { + BG_IK_MoveLimb(ent->ghoul2, ent->client->ps.heldByBolt, animBone, firstBone, secondBone, level.time, &ent->s, ent->client->clientInfo.animFileIndex, + ent->client->ps.torsoAnim /*BOTH_DEAD1*/, (float *)vec3_origin, &ent->client->ps.ikStatus, ent->client->ps.origin, + ent->client->ps.viewangles, ent->s.modelScale, 500, qtrue); } } } - -void BG_G2SetBoneAngles( centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations right, const Eorientations forward, qhandle_t *modelList ) -{ - if (boneIndex!=-1) - { - gi.G2API_SetBoneAnglesIndex( ¢->gent->ghoul2[0], boneIndex, angles, flags, up, right, forward, modelList, 0, 0 ); +void BG_G2SetBoneAngles(centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations right, const Eorientations forward, qhandle_t *modelList) { + if (boneIndex != -1) { + gi.G2API_SetBoneAnglesIndex(¢->gent->ghoul2[0], boneIndex, angles, flags, up, right, forward, modelList, 0, 0); } } -#define MAX_YAWSPEED_X_WING 1 -#define MAX_PITCHSPEED_X_WING 1 -void PM_ScaleUcmd( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) -{ - if ( G_IsRidingVehicle( gent ) ) - {//driving a vehicle - //clamp the turn rate - int maxPitchSpeed = MAX_PITCHSPEED_X_WING;//switch, eventually? Or read from file? - int diff = AngleNormalize180(SHORT2ANGLE((cmd->angles[PITCH]+ps->delta_angles[PITCH]))) - floor(ps->viewangles[PITCH]); - - if ( diff > maxPitchSpeed ) - { - cmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] + maxPitchSpeed ) - ps->delta_angles[PITCH]; - } - else if ( diff < -maxPitchSpeed ) - { - cmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] - maxPitchSpeed ) - ps->delta_angles[PITCH]; +#define MAX_YAWSPEED_X_WING 1 +#define MAX_PITCHSPEED_X_WING 1 +void PM_ScaleUcmd(playerState_t *ps, usercmd_t *cmd, gentity_t *gent) { + if (G_IsRidingVehicle(gent)) { // driving a vehicle + // clamp the turn rate + int maxPitchSpeed = MAX_PITCHSPEED_X_WING; // switch, eventually? Or read from file? + int diff = AngleNormalize180(SHORT2ANGLE((cmd->angles[PITCH] + ps->delta_angles[PITCH]))) - floor(ps->viewangles[PITCH]); + + if (diff > maxPitchSpeed) { + cmd->angles[PITCH] = ANGLE2SHORT(ps->viewangles[PITCH] + maxPitchSpeed) - ps->delta_angles[PITCH]; + } else if (diff < -maxPitchSpeed) { + cmd->angles[PITCH] = ANGLE2SHORT(ps->viewangles[PITCH] - maxPitchSpeed) - ps->delta_angles[PITCH]; } - //Um, WTF? When I turn in a certain direction, I start going backwards? Or strafing? - int maxYawSpeed = MAX_YAWSPEED_X_WING;//switch, eventually? Or read from file? - diff = AngleNormalize180(SHORT2ANGLE(cmd->angles[YAW]+ps->delta_angles[YAW]) - floor(ps->viewangles[YAW])); + // Um, WTF? When I turn in a certain direction, I start going backwards? Or strafing? + int maxYawSpeed = MAX_YAWSPEED_X_WING; // switch, eventually? Or read from file? + diff = AngleNormalize180(SHORT2ANGLE(cmd->angles[YAW] + ps->delta_angles[YAW]) - floor(ps->viewangles[YAW])); - //clamp the turn rate - if ( diff > maxYawSpeed ) - { - cmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] + maxYawSpeed ) - ps->delta_angles[YAW]; - } - else if ( diff < -maxYawSpeed ) - { - cmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] - maxYawSpeed ) - ps->delta_angles[YAW]; + // clamp the turn rate + if (diff > maxYawSpeed) { + cmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW] + maxYawSpeed) - ps->delta_angles[YAW]; + } else if (diff < -maxYawSpeed) { + cmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW] - maxYawSpeed) - ps->delta_angles[YAW]; } } } -extern void SetClientViewAngle( gentity_t *ent, vec3_t angle ); -qboolean PM_LockAngles( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +extern void SetClientViewAngle(gentity_t *ent, vec3_t angle); +qboolean PM_LockAngles(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAnglesToGripper( gentity_t *ent, usercmd_t *ucmd ) -{//FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? - if ( ((ent->client->ps.eFlags&EF_FORCE_GRIPPED)||(ent->client->ps.eFlags&EF_FORCE_DRAINED)) && ent->enemy ) - { +qboolean +PM_AdjustAnglesToGripper(gentity_t *ent, + usercmd_t *ucmd) { // FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? + if (((ent->client->ps.eFlags & EF_FORCE_GRIPPED) || (ent->client->ps.eFlags & EF_FORCE_DRAINED)) && ent->enemy) { vec3_t dir, angles; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, dir ); - vectoangles( dir, angles ); - angles[PITCH] = AngleNormalize180( angles[PITCH] ); - angles[YAW] = AngleNormalize180( angles[YAW] ); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, angles ); + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, dir); + vectoangles(dir, angles); + angles[PITCH] = AngleNormalize180(angles[PITCH]); + angles[YAW] = AngleNormalize180(angles[YAW]); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, angles); } ucmd->angles[PITCH] = ANGLE2SHORT(angles[PITCH]) - ent->client->ps.delta_angles[PITCH]; ucmd->angles[YAW] = ANGLE2SHORT(angles[YAW]) - ent->client->ps.delta_angles[YAW]; @@ -444,483 +380,377 @@ qboolean PM_AdjustAnglesToGripper( gentity_t *ent, usercmd_t *ucmd ) return qfalse; } -qboolean PM_AdjustAnglesToPuller( gentity_t *ent, gentity_t *puller, usercmd_t *ucmd, qboolean faceAway ) -{//FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? +qboolean +PM_AdjustAnglesToPuller(gentity_t *ent, gentity_t *puller, usercmd_t *ucmd, + qboolean faceAway) { // FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? vec3_t dir, angles; - VectorSubtract( puller->currentOrigin, ent->currentOrigin, dir ); - vectoangles( dir, angles ); - angles[PITCH] = AngleNormalize180( angles[PITCH] ); - if ( faceAway ) - { + VectorSubtract(puller->currentOrigin, ent->currentOrigin, dir); + vectoangles(dir, angles); + angles[PITCH] = AngleNormalize180(angles[PITCH]); + if (faceAway) { angles[YAW] += 180; } - angles[YAW] = AngleNormalize180( angles[YAW] ); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, angles ); + angles[YAW] = AngleNormalize180(angles[YAW]); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, angles); } ucmd->angles[PITCH] = ANGLE2SHORT(angles[PITCH]) - ent->client->ps.delta_angles[PITCH]; ucmd->angles[YAW] = ANGLE2SHORT(angles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ) -{ - if (( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT || ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT ) && ent->client->ps.legsAnimTimer > 500 ) - {//wall-running and not at end of anim - //stick to wall, if there is one - vec3_t fwd, rt, traceTo, mins = {ent->mins[0],ent->mins[1],0}, maxs = {ent->maxs[0],ent->maxs[1],24}, fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; - trace_t trace; - float dist, yawAdjust=0.0f; +qboolean PM_AdjustAngleForWallRun(gentity_t *ent, usercmd_t *ucmd, qboolean doMove) { + if ((ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT || ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT) && + ent->client->ps.legsAnimTimer > 500) { // wall-running and not at end of anim + // stick to wall, if there is one + vec3_t fwd, rt, traceTo, mins = {ent->mins[0], ent->mins[1], 0}, maxs = {ent->maxs[0], ent->maxs[1], 24}, + fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; + trace_t trace; + float dist, yawAdjust = 0.0f; - AngleVectors( fwdAngles, fwd, rt, NULL ); + AngleVectors(fwdAngles, fwd, rt, NULL); - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { dist = 128; yawAdjust = -90; - } - else - { + } else { dist = -128; yawAdjust = 90; } - VectorMA( ent->currentOrigin, dist, rt, traceTo ); - gi.trace( &trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f - && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f) )//&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) + VectorMA(ent->currentOrigin, dist, rt, traceTo); + gi.trace(&trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f)) //&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) { - trace_t trace2; + trace_t trace2; vec3_t traceTo2; - vec3_t wallRunFwd, wallRunAngles = {0}; + vec3_t wallRunFwd, wallRunAngles = {0}; - wallRunAngles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; - AngleVectors( wallRunAngles, wallRunFwd, NULL, NULL ); + wallRunAngles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; + AngleVectors(wallRunAngles, wallRunFwd, NULL, NULL); - VectorMA( ent->currentOrigin, 32, wallRunFwd, traceTo2 ); - gi.trace( &trace2, ent->currentOrigin, mins, maxs, traceTo2, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace2.fraction < 1.0f && DotProduct( trace2.plane.normal, wallRunFwd ) <= -0.999f ) - {//wall we can't run on in front of us - trace.fraction = 1.0f;//just a way to get it to kick us off the wall below + VectorMA(ent->currentOrigin, 32, wallRunFwd, traceTo2); + gi.trace(&trace2, ent->currentOrigin, mins, maxs, traceTo2, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace2.fraction < 1.0f && DotProduct(trace2.plane.normal, wallRunFwd) <= -0.999f) { // wall we can't run on in front of us + trace.fraction = 1.0f; // just a way to get it to kick us off the wall below } } - if ( trace.fraction < 1.0f - && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f) )//&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//still a vertical wall there - //FIXME: don't pull around 90 turns - //FIXME: simulate stepping up steps here, somehow? - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) - { - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { + if (trace.fraction < 1.0f && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f)) //&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) + { // still a vertical wall there + // FIXME: don't pull around 90 turns + // FIXME: simulate stepping up steps here, somehow? + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent)) || !player_locked) { + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { ucmd->rightmove = 127; - } - else - { + } else { ucmd->rightmove = -127; } } - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - //make me face perpendicular to the wall - ent->client->ps.viewangles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + // make me face perpendicular to the wall + ent->client->ps.viewangles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( (ent->s.number&&!G_ControlledByPlayer(ent)) || !player_locked ) - { - if ( doMove ) - { - //push me forward - float zVel = ent->client->ps.velocity[2]; - if ( zVel > forceJumpStrength[FORCE_LEVEL_2]/2.0f ) - { - zVel = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if ((ent->s.number && !G_ControlledByPlayer(ent)) || !player_locked) { + if (doMove) { + // push me forward + float zVel = ent->client->ps.velocity[2]; + if (zVel > forceJumpStrength[FORCE_LEVEL_2] / 2.0f) { + zVel = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; } - //pull me toward the wall - VectorScale( trace.plane.normal, -128, ent->client->ps.velocity ); - if ( ent->client->ps.legsAnimTimer > 500 ) - {//not at end of anim yet, pushing forward - //FIXME: or MA? + // pull me toward the wall + VectorScale(trace.plane.normal, -128, ent->client->ps.velocity); + if (ent->client->ps.legsAnimTimer > 500) { // not at end of anim yet, pushing forward + // FIXME: or MA? float speed = 175; - if ( ucmd->forwardmove < 0 ) - {//slower + if (ucmd->forwardmove < 0) { // slower speed = 100; + } else if (ucmd->forwardmove > 0) { + speed = 250; // running speed } - else if ( ucmd->forwardmove > 0 ) - { - speed = 250;//running speed - } - VectorMA( ent->client->ps.velocity, speed, fwd, ent->client->ps.velocity ); + VectorMA(ent->client->ps.velocity, speed, fwd, ent->client->ps.velocity); } - ent->client->ps.velocity[2] = zVel;//preserve z velocity - //VectorMA( ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity ); - //pull me toward the wall, too - //VectorMA( ent->client->ps.velocity, dist, rt, ent->client->ps.velocity ); + ent->client->ps.velocity[2] = zVel; // preserve z velocity + // VectorMA( ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity ); + // pull me toward the wall, too + // VectorMA( ent->client->ps.velocity, dist, rt, ent->client->ps.velocity ); } } ucmd->forwardmove = 0; return qtrue; - } - else if ( doMove ) - {//stop it - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (doMove) { // stop it + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } return qfalse; } -extern int PM_AnimLength( int index, animNumber_t anim ); -qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ) -{ - vec3_t newAngles; - float animLength, spinStart, spinEnd, spinAmt, spinLength; - animNumber_t spinAnim; +extern int PM_AnimLength(int index, animNumber_t anim); +qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly) { + vec3_t newAngles; + float animLength, spinStart, spinEnd, spinAmt, spinLength; + animNumber_t spinAnim; - if ( ent->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN ) - { + if (ent->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN) { spinAnim = BOTH_JUMPFLIPSTABDOWN; - spinStart = 300.0f;//700.0f; + spinStart = 300.0f; // 700.0f; spinEnd = 1400.0f; spinAmt = 180.0f; - } - else if ( ent->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 ) - { + } else if (ent->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1) { spinAnim = BOTH_JUMPFLIPSLASHDOWN1; - spinStart = 300.0f;//700.0f;//1500.0f; - spinEnd = 1400.0f;//2300.0f; + spinStart = 300.0f; // 700.0f;//1500.0f; + spinEnd = 1400.0f; // 2300.0f; spinAmt = 180.0f; - } - else - { - if ( !anglesOnly ) - { - if ( (ent->s.numbers.number < MAX_CLIENTS || G_ControlledByPlayer(ent))) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_VOF; cg.overrides.thirdPersonVertOffset = 0; } } return qfalse; } - animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, spinAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); - //face me - if ( elapsedTime >= spinStart && elapsedTime <= spinEnd ) - { + animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, spinAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); + // face me + if (elapsedTime >= spinStart && elapsedTime <= spinEnd) { spinLength = spinEnd - spinStart; - VectorCopy( ent->client->ps.viewangles, newAngles ); - newAngles[YAW] = ent->angle + (spinAmt * (elapsedTime-spinStart) / spinLength); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, newAngles ); - } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( anglesOnly ) - { + VectorCopy(ent->client->ps.viewangles, newAngles); + newAngles[YAW] = ent->angle + (spinAmt * (elapsedTime - spinStart) / spinLength); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, newAngles); + } + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if (anglesOnly) { return qtrue; } - } - else if ( anglesOnly ) - { + } else if (anglesOnly) { return qfalse; } - //push me - if ( ent->client->ps.legsAnimTimer > 300 )//&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//haven't landed or reached end of anim yet - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) - { - vec3_t pushDir, pushAngles = {0,ent->angle,0}; - AngleVectors( pushAngles, pushDir, NULL, NULL ); - if ( DotProduct( ent->client->ps.velocity, pushDir ) < 100 ) - { - VectorMA( ent->client->ps.velocity, 10, pushDir, ent->client->ps.velocity ); + // push me + if (ent->client->ps.legsAnimTimer > 300) //&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) + { // haven't landed or reached end of anim yet + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent)) || !player_locked) { + vec3_t pushDir, pushAngles = {0, ent->angle, 0}; + AngleVectors(pushAngles, pushDir, NULL, NULL); + if (DotProduct(ent->client->ps.velocity, pushDir) < 100) { + VectorMA(ent->client->ps.velocity, 10, pushDir, ent->client->ps.velocity); } } } - //do a dip in the view - if ( (ent->s.numbers.number < MAX_CLIENTS || G_ControlledByPlayer(ent))) { float viewDip = 0; - if ( elapsedTime < animLength/2.0f ) - {//starting anim - viewDip = (elapsedTime/animLength)*-120.0f; - } - else - {//ending anim - viewDip = ((animLength-elapsedTime)/animLength)*-120.0f; + if (elapsedTime < animLength / 2.0f) { // starting anim + viewDip = (elapsedTime / animLength) * -120.0f; + } else { // ending anim + viewDip = ((animLength - elapsedTime) / animLength) * -120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_VOF; - cg.overrides.thirdPersonVertOffset = cg_thirdPersonVertOffset.value+viewDip; - //pm->ps->viewheight = standheight + viewDip; + cg.overrides.thirdPersonVertOffset = cg_thirdPersonVertOffset.value + viewDip; + // pm->ps->viewheight = standheight + viewDip; } return qtrue; } -qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) ) - { +qboolean PM_AdjustAnglesForBackAttack(gentity_t *ent, usercmd_t *ucmd) { + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent))) { return qfalse; } - if ( ( ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || ent->client->ps.saberMove == LS_A_BACKSTAB ) - && PM_InAnimForSaberMove( ent->client->ps.torsoAnim, ent->client->ps.saberMove ) ) - { - if ( ent->client->ps.saberMove != LS_A_BACKSTAB || !ent->enemy || (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) ) - { - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + if ((ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || ent->client->ps.saberMove == LS_A_BACKSTAB) && + PM_InAnimForSaberMove(ent->client->ps.torsoAnim, ent->client->ps.saberMove)) { + if (ent->client->ps.saberMove != LS_A_BACKSTAB || !ent->enemy || (ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent))) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - } - else - {//keep player facing away from their enemy + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + } else { // keep player facing away from their enemy vec3_t enemyBehindDir; - VectorSubtract( ent->currentOrigin, ent->enemy->currentOrigin, enemyBehindDir ); - float enemyBehindYaw = AngleNormalize180( vectoyaw( enemyBehindDir ) ); - float yawError = AngleNormalize180( enemyBehindYaw - AngleNormalize180( ent->client->ps.viewangles[YAW] ) ); - if ( yawError > 1 ) - { + VectorSubtract(ent->currentOrigin, ent->enemy->currentOrigin, enemyBehindDir); + float enemyBehindYaw = AngleNormalize180(vectoyaw(enemyBehindDir)); + float yawError = AngleNormalize180(enemyBehindYaw - AngleNormalize180(ent->client->ps.viewangles[YAW])); + if (yawError > 1) { yawError = 1; - } - else if ( yawError < -1 ) - { + } else if (yawError < -1) { yawError = -1; } - ucmd->angles[YAW] = ANGLE2SHORT( AngleNormalize180( ent->client->ps.viewangles[YAW] + yawError ) ) - ent->client->ps.delta_angles[YAW]; - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(AngleNormalize180(ent->client->ps.viewangles[YAW] + yawError)) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; } return qtrue; } return qfalse; } -qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.saberLockTime > level.time ) - { - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForSaberLock(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.saberLockTime > level.time) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } return qfalse; } -int G_MinGetUpTime( gentity_t *ent ) -{ - if ( ent - && ent->client - && ( ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY - || ent->client->ps.legsAnim == BOTH_LK_DL_ST_T_SB_1_L - || ent->client->ps.legsAnim == BOTH_RELEASED ) ) - {//special cases +int G_MinGetUpTime(gentity_t *ent) { + if (ent && ent->client && + (ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY || ent->client->ps.legsAnim == BOTH_LK_DL_ST_T_SB_1_L || + ent->client->ps.legsAnim == BOTH_RELEASED)) { // special cases return 200; - } - else if ( ent && ent->client && ent->client->NPC_class == CLASS_ALORA ) - {//alora springs up very quickly from knockdowns! + } else if (ent && ent->client && ent->client->NPC_class == CLASS_ALORA) { // alora springs up very quickly from knockdowns! return 1000; - } - else if ( (ent->s.clientNum < MAX_CLIENTS||G_ControlledByPlayer(ent)) ) - {//player can get up faster based on his/her force jump skill + } else if ((ent->s.clientNum < MAX_CLIENTS || G_ControlledByPlayer(ent))) { // player can get up faster based on his/her force jump skill int getUpTime = PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; - if ( ent->client->ps.forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_3 ) - { - return (getUpTime+400);//750 - } - else if ( ent->client->ps.forcePowerLevel[FP_LEVITATION] == FORCE_LEVEL_2 ) - { - return (getUpTime+200);//500 - } - else if ( ent->client->ps.forcePowerLevel[FP_LEVITATION] == FORCE_LEVEL_1 ) - { - return (getUpTime+100);//250 - } - else - { + if (ent->client->ps.forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_3) { + return (getUpTime + 400); // 750 + } else if (ent->client->ps.forcePowerLevel[FP_LEVITATION] == FORCE_LEVEL_2) { + return (getUpTime + 200); // 500 + } else if (ent->client->ps.forcePowerLevel[FP_LEVITATION] == FORCE_LEVEL_1) { + return (getUpTime + 100); // 250 + } else { return getUpTime; } } return 200; } -qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ) -{ - if ( PM_InKnockDown( &ent->client->ps ) ) - {//being knocked down or getting up, can't do anything! - if ( !angleClampOnly ) - { - if ( ent->client->ps.legsAnimTimer > G_MinGetUpTime( ent ) - || (ent->s.number >= MAX_CLIENTS&&!G_ControlledByPlayer(ent)) ) - {//can't get up yet +qboolean PM_AdjustAnglesForKnockdown(gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly) { + if (PM_InKnockDown(&ent->client->ps)) { // being knocked down or getting up, can't do anything! + if (!angleClampOnly) { + if (ent->client->ps.legsAnimTimer > G_MinGetUpTime(ent) || (ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent))) { // can't get up yet ucmd->forwardmove = 0; ucmd->rightmove = 0; } - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - //you can jump up out of a knockdown and you get get up into a crouch from a knockdown - //ucmd->upmove = 0; - //if ( !PM_InForceGetUp( &ent->client->ps ) || ent->client->ps.torsoAnimTimer > 800 || ent->s.weapon != WP_SABER ) - if ( ent->health > 0 ) - {//can only attack if you've started a force-getup and are using the saber + // you can jump up out of a knockdown and you get get up into a crouch from a knockdown + // ucmd->upmove = 0; + // if ( !PM_InForceGetUp( &ent->client->ps ) || ent->client->ps.torsoAnimTimer > 800 || ent->s.weapon != WP_SABER ) + if (ent->health > 0) { // can only attack if you've started a force-getup and are using the saber ucmd->buttons = 0; } } - if ( !PM_InForceGetUp( &ent->client->ps ) ) - {//can't turn unless in a force getup - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + if (!PM_InForceGetUp(&ent->client->ps)) { // can't turn unless in a force getup + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } } return qfalse; } -qboolean PM_AdjustAnglesForDualJumpAttack( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForDualJumpAttack(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAnglesForLongJump( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForLongJump(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAnglesForGrapple( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForGrapple(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAngleForWallRunUp( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ) -{ - if ( ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_START ) - {//wall-running up - //stick to wall, if there is one - vec3_t fwd, traceTo, mins = {ent->mins[0],ent->mins[1],0}, maxs = {ent->maxs[0],ent->maxs[1],24}, fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; - trace_t trace; - float dist = 128; - - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( ent->currentOrigin, dist, fwd, traceTo ); - gi.trace( &trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction > 0.5f ) - {//hmm, some room, see if there's a floor right here - trace_t trace2; - vec3_t top, bottom; - VectorCopy( trace.endpos, top ); - top[2] += (ent->mins[2]*-1) + 4.0f; - VectorCopy( top, bottom ); - bottom[2] -= 64.0f;//was 32.0f - gi.trace( &trace2, top, ent->mins, ent->maxs, bottom, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid - && !trace2.startsolid - && trace2.fraction < 1.0f - && trace2.plane.normal[2] > 0.7f )//slope we can stand on - {//cool, do the alt-flip and land on whetever it is we just scaled up - VectorScale( fwd, 100, ent->client->ps.velocity ); +qboolean PM_AdjustAngleForWallRunUp(gentity_t *ent, usercmd_t *ucmd, qboolean doMove) { + if (ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_START) { // wall-running up + // stick to wall, if there is one + vec3_t fwd, traceTo, mins = {ent->mins[0], ent->mins[1], 0}, maxs = {ent->maxs[0], ent->maxs[1], 24}, + fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; + trace_t trace; + float dist = 128; + + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(ent->currentOrigin, dist, fwd, traceTo); + gi.trace(&trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace.fraction > 0.5f) { // hmm, some room, see if there's a floor right here + trace_t trace2; + vec3_t top, bottom; + VectorCopy(trace.endpos, top); + top[2] += (ent->mins[2] * -1) + 4.0f; + VectorCopy(top, bottom); + bottom[2] -= 64.0f; // was 32.0f + gi.trace(&trace2, top, ent->mins, ent->maxs, bottom, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction < 1.0f && trace2.plane.normal[2] > 0.7f) // slope we can stand on + { // cool, do the alt-flip and land on whetever it is we just scaled up + VectorScale(fwd, 100, ent->client->ps.velocity); ent->client->ps.velocity[2] += 200; - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_ALT, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_ALT, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.pm_flags |= PMF_JUMP_HELD; - ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - ent->client->ps.forcePowersActive |= (1<client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + ent->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + G_AddEvent(ent, EV_JUMP, 0); ucmd->upmove = 0; return qfalse; } } - if ( //ucmd->upmove <= 0 && - ent->client->ps.legsAnimTimer > 0 - && ucmd->forwardmove > 0 - && trace.fraction < 1.0f - && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= MAX_WALL_RUN_Z_NORMAL) ) - {//still a vertical wall there - //make sure there's not a ceiling above us! - trace_t trace2; - VectorCopy( ent->currentOrigin, traceTo ); + if ( // ucmd->upmove <= 0 && + ent->client->ps.legsAnimTimer > 0 && ucmd->forwardmove > 0 && trace.fraction < 1.0f && + (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= MAX_WALL_RUN_Z_NORMAL)) { // still a vertical wall there + // make sure there's not a ceiling above us! + trace_t trace2; + VectorCopy(ent->currentOrigin, traceTo); traceTo[2] += 64; - gi.trace( &trace2, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace2.fraction < 1.0f ) - {//will hit a ceiling, so force jump-off right now - //NOTE: hits any entity or clip brush in the way, too, not just architecture! - } - else - {//all clear, keep going - //FIXME: don't pull around 90 turns - //FIXME: simulate stepping up steps here, somehow? - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) - { + gi.trace(&trace2, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace2.fraction < 1.0f) { // will hit a ceiling, so force jump-off right now + // NOTE: hits any entity or clip brush in the way, too, not just architecture! + } else { // all clear, keep going + // FIXME: don't pull around 90 turns + // FIXME: simulate stepping up steps here, somehow? + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent)) || !player_locked) { ucmd->forwardmove = 127; } - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - //make me face the wall - ent->client->ps.viewangles[YAW] = vectoyaw( trace.plane.normal )+180; - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + // make me face the wall + ent->client->ps.viewangles[YAW] = vectoyaw(trace.plane.normal) + 180; + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) - { - if ( doMove ) - { - //pull me toward the wall - VectorScale( trace.plane.normal, -128, ent->client->ps.velocity ); - //push me up - if ( ent->client->ps.legsAnimTimer > 200 ) - {//not at end of anim yet + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent)) || !player_locked) { + if (doMove) { + // pull me toward the wall + VectorScale(trace.plane.normal, -128, ent->client->ps.velocity); + // push me up + if (ent->client->ps.legsAnimTimer > 200) { // not at end of anim yet float speed = 300; /* if ( ucmd->forwardmove < 0 ) @@ -932,427 +762,358 @@ qboolean PM_AdjustAngleForWallRunUp( gentity_t *ent, usercmd_t *ucmd, qboolean d speed = 250;//running speed } */ - ent->client->ps.velocity[2] = speed;//preserve z velocity + ent->client->ps.velocity[2] = speed; // preserve z velocity } - //pull me toward the wall - //VectorMA( ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity ); + // pull me toward the wall + // VectorMA( ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity ); } } ucmd->forwardmove = 0; return qtrue; } } - //failed! - if ( doMove ) - {//stop it - VectorScale( fwd, WALL_RUN_UP_BACKFLIP_SPEED, ent->client->ps.velocity ); + // failed! + if (doMove) { // stop it + VectorScale(fwd, WALL_RUN_UP_BACKFLIP_SPEED, ent->client->ps.velocity); ent->client->ps.velocity[2] += 200; - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.pm_flags |= PMF_JUMP_HELD; - ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - ent->client->ps.forcePowersActive |= (1<client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + ent->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + G_AddEvent(ent, EV_JUMP, 0); ucmd->upmove = 0; - //return qtrue; + // return qtrue; } } return qfalse; } -float G_ForceWallJumpStrength( void ) -{ - return (forceJumpStrength[FORCE_LEVEL_3]/2.5f); -} +float G_ForceWallJumpStrength(void) { return (forceJumpStrength[FORCE_LEVEL_3] / 2.5f); } -qboolean PM_AdjustAngleForWallJump( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ) -{ - if ( PM_InReboundJump( ent->client->ps.legsAnim ) - || PM_InReboundHold( ent->client->ps.legsAnim ) ) - {//hugging wall, getting ready to jump off - //stick to wall, if there is one - vec3_t checkDir, traceTo, mins = {ent->mins[0],ent->mins[1],0}, maxs = {ent->maxs[0],ent->maxs[1],24}, fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; - trace_t trace; - float dist = 128, yawAdjust; - switch ( ent->client->ps.legsAnim ) - { +qboolean PM_AdjustAngleForWallJump(gentity_t *ent, usercmd_t *ucmd, qboolean doMove) { + if (PM_InReboundJump(ent->client->ps.legsAnim) || PM_InReboundHold(ent->client->ps.legsAnim)) { // hugging wall, getting ready to jump off + // stick to wall, if there is one + vec3_t checkDir, traceTo, mins = {ent->mins[0], ent->mins[1], 0}, maxs = {ent->maxs[0], ent->maxs[1], 24}, + fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; + trace_t trace; + float dist = 128, yawAdjust; + switch (ent->client->ps.legsAnim) { case BOTH_FORCEWALLREBOUND_RIGHT: case BOTH_FORCEWALLHOLD_RIGHT: - AngleVectors( fwdAngles, NULL, checkDir, NULL ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); yawAdjust = -90; break; case BOTH_FORCEWALLREBOUND_LEFT: case BOTH_FORCEWALLHOLD_LEFT: - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); yawAdjust = 90; break; case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEWALLHOLD_FORWARD: - AngleVectors( fwdAngles, checkDir, NULL, NULL ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); yawAdjust = 180; break; case BOTH_FORCEWALLREBOUND_BACK: case BOTH_FORCEWALLHOLD_BACK: - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); yawAdjust = 0; break; default: - //WTF??? + // WTF??? return qfalse; break; } - if ( g_debugMelee->integer ) - {//uber-skillz - if ( ucmd->upmove > 0 ) - {//hold on until you let go manually - if ( PM_InReboundHold( ent->client->ps.legsAnim ) ) - {//keep holding - if ( ent->client->ps.legsAnimTimer < 150 ) - { + if (g_debugMelee->integer) { // uber-skillz + if (ucmd->upmove > 0) { // hold on until you let go manually + if (PM_InReboundHold(ent->client->ps.legsAnim)) { // keep holding + if (ent->client->ps.legsAnimTimer < 150) { ent->client->ps.legsAnimTimer = 150; } - } - else - {//if got to hold part of anim, play hold anim - if ( ent->client->ps.legsAnimTimer <= 300 ) - { + } else { // if got to hold part of anim, play hold anim + if (ent->client->ps.legsAnimTimer <= 300) { ent->client->ps.SaberDeactivate(); - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD+(ent->client->ps.legsAnim-BOTH_FORCEWALLHOLD_FORWARD), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD + (ent->client->ps.legsAnim - BOTH_FORCEWALLHOLD_FORWARD), + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 150; } } } } - VectorMA( ent->currentOrigin, dist, checkDir, traceTo ); - gi.trace( &trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( //ucmd->upmove <= 0 && - ent->client->ps.legsAnimTimer > 100 && - trace.fraction < 1.0f && fabs(trace.plane.normal[2]) <= MAX_WALL_GRAB_SLOPE ) - {//still a vertical wall there - //FIXME: don't pull around 90 turns + VectorMA(ent->currentOrigin, dist, checkDir, traceTo); + gi.trace(&trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if ( // ucmd->upmove <= 0 && + ent->client->ps.legsAnimTimer > 100 && trace.fraction < 1.0f && fabs(trace.plane.normal[2]) <= MAX_WALL_GRAB_SLOPE) { // still a vertical wall there + // FIXME: don't pull around 90 turns /* if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) { ucmd->forwardmove = 127; } */ - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - //align me to the wall - ent->client->ps.viewangles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + // align me to the wall + ent->client->ps.viewangles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( (ent->s.number>=MAX_CLIENTS&&!G_ControlledByPlayer(ent)) || !player_locked ) - { - if ( doMove ) - { - //pull me toward the wall - VectorScale( trace.plane.normal, -128, ent->client->ps.velocity ); + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if ((ent->s.number >= MAX_CLIENTS && !G_ControlledByPlayer(ent)) || !player_locked) { + if (doMove) { + // pull me toward the wall + VectorScale(trace.plane.normal, -128, ent->client->ps.velocity); } } ucmd->upmove = 0; ent->client->ps.pm_flags |= PMF_STUCK_TO_WALL; return qtrue; - } - else if ( doMove - && (ent->client->ps.pm_flags&PMF_STUCK_TO_WALL)) - {//jump off - //push off of it! + } else if (doMove && (ent->client->ps.pm_flags & PMF_STUCK_TO_WALL)) { // jump off + // push off of it! ent->client->ps.pm_flags &= ~PMF_STUCK_TO_WALL; ent->client->ps.velocity[0] = ent->client->ps.velocity[1] = 0; - VectorScale( checkDir, -JUMP_OFF_WALL_SPEED, ent->client->ps.velocity ); + VectorScale(checkDir, -JUMP_OFF_WALL_SPEED, ent->client->ps.velocity); ent->client->ps.velocity[2] = G_ForceWallJumpStrength(); - ent->client->ps.pm_flags |= PMF_JUMPING|PMF_JUMP_HELD; - G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - ent->client->ps.forcePowersActive |= (1<client->ps.legsAnim ) ) - {//if was in hold pose, release now - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD+(ent->client->ps.legsAnim-BOTH_FORCEWALLHOLD_FORWARD), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + ent->client->ps.pm_flags |= PMF_JUMPING | PMF_JUMP_HELD; + G_SoundOnEnt(ent, CHAN_BODY, "sound/weapons/force/jump.wav"); + ent->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + WP_ForcePowerDrain(ent, FP_LEVITATION, 10); + if (PM_InReboundHold(ent->client->ps.legsAnim)) { // if was in hold pose, release now + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD + (ent->client->ps.legsAnim - BOTH_FORCEWALLHOLD_FORWARD), + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //no control for half a second + // no control for half a second ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; ent->client->ps.pm_time = 500; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; - //return qtrue; + // return qtrue; } } ent->client->ps.pm_flags &= ~PMF_STUCK_TO_WALL; return qfalse; } -qboolean PM_AdjustAnglesForBFKick( gentity_t *self, usercmd_t *ucmd, vec3_t fwdAngs, qboolean aimFront ) -{ - //Auto-aim the player at the ent in front/back of them - //FIXME: camera angle should always be in front/behind me for the 2 kicks +qboolean PM_AdjustAnglesForBFKick(gentity_t *self, usercmd_t *ucmd, vec3_t fwdAngs, qboolean aimFront) { + // Auto-aim the player at the ent in front/back of them + // FIXME: camera angle should always be in front/behind me for the 2 kicks // (to hide how far away the two entities really are) - //FIXME: don't let the people we're auto-aiming at move? - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - vec3_t mins, maxs; - int i, e; - int radius = ((self->maxs[0]*1.5f)+(self->maxs[0]*1.5f)+STAFF_KICK_RANGE+24.0f);//a little wide on purpose - vec3_t center, vec2Ent, v_fwd; - float distToEnt, bestDist = Q3_INFINITE; - float dot, bestDot = -1.1f; - float bestYaw = Q3_INFINITE; - - AngleVectors( fwdAngs, v_fwd, NULL, NULL ); - - VectorCopy( self->currentOrigin, center ); - - for ( i = 0 ; i < 3 ; i++ ) - { + // FIXME: don't let the people we're auto-aiming at move? + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + vec3_t mins, maxs; + int i, e; + int radius = ((self->maxs[0] * 1.5f) + (self->maxs[0] * 1.5f) + STAFF_KICK_RANGE + 24.0f); // a little wide on purpose + vec3_t center, vec2Ent, v_fwd; + float distToEnt, bestDist = Q3_INFINITE; + float dot, bestDot = -1.1f; + float bestYaw = Q3_INFINITE; + + AngleVectors(fwdAngs, v_fwd, NULL, NULL); + + VectorCopy(self->currentOrigin, center); + + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - int numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + int numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - //not a client? - if ( !ent->client ) + // not a client? + if (!ent->client) continue; - //ally? - if ( ent->client->playerTeam == self->client->playerTeam ) + // ally? + if (ent->client->playerTeam == self->client->playerTeam) continue; - //on the ground - if ( PM_InKnockDown( &ent->client->ps ) ) + // on the ground + if (PM_InKnockDown(&ent->client->ps)) continue; - //dead? - if ( ent->health <= 0 ) - { - if ( level.time - ent->s.time > 2000 ) - {//died more than 2 seconds ago, forget him + // dead? + if (ent->health <= 0) { + if (level.time - ent->s.time > 2000) { // died more than 2 seconds ago, forget him continue; } } - //too far? - VectorSubtract( ent->currentOrigin, center, vec2Ent ); - distToEnt = VectorNormalize( vec2Ent ); - if ( distToEnt > radius ) + // too far? + VectorSubtract(ent->currentOrigin, center, vec2Ent); + distToEnt = VectorNormalize(vec2Ent); + if (distToEnt > radius) continue; - if ( !aimFront ) - {//aim away from them - VectorScale( vec2Ent, -1, vec2Ent ); + if (!aimFront) { // aim away from them + VectorScale(vec2Ent, -1, vec2Ent); } - dot = DotProduct( vec2Ent, v_fwd ); - if ( dot < 0.0f ) - {//never turn all the way around + dot = DotProduct(vec2Ent, v_fwd); + if (dot < 0.0f) { // never turn all the way around continue; } - if ( dot > bestDot || ((bestDot-dot<0.25f)&&distToEnt-bestDist>8.0f) ) - {//more in front... OR: still relatively close to in front and significantly closer + if (dot > bestDot || + ((bestDot - dot < 0.25f) && distToEnt - bestDist > 8.0f)) { // more in front... OR: still relatively close to in front and significantly closer bestDot = dot; bestDist = distToEnt; - bestYaw = vectoyaw( vec2Ent ); + bestYaw = vectoyaw(vec2Ent); } } - if ( bestYaw != Q3_INFINITE && bestYaw != fwdAngs[YAW] ) - {//aim us at them - AngleNormalize180( bestYaw ); - AngleNormalize180( fwdAngs[YAW] ); - float angDiff = AngleSubtract( bestYaw, fwdAngs[YAW] ); - AngleNormalize180( angDiff ); - if ( fabs(angDiff) <= 3.0f ) - { + if (bestYaw != Q3_INFINITE && bestYaw != fwdAngs[YAW]) { // aim us at them + AngleNormalize180(bestYaw); + AngleNormalize180(fwdAngs[YAW]); + float angDiff = AngleSubtract(bestYaw, fwdAngs[YAW]); + AngleNormalize180(angDiff); + if (fabs(angDiff) <= 3.0f) { self->client->ps.viewangles[YAW] = bestYaw; - } - else if ( angDiff > 0.0f ) - {//more than 3 degrees higher + } else if (angDiff > 0.0f) { // more than 3 degrees higher self->client->ps.viewangles[YAW] += 3.0f; - } - else - {//must be more than 3 less than + } else { // must be more than 3 less than self->client->ps.viewangles[YAW] -= 3.0f; } - if ( self->client->ps.viewEntity <= 0 || self->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( self, self->client->ps.viewangles ); + if (self->client->ps.viewEntity <= 0 || self->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(self, self->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( self->client->ps.viewangles[YAW] ) - self->client->ps.delta_angles[YAW]; + ucmd->angles[YAW] = ANGLE2SHORT(self->client->ps.viewangles[YAW]) - self->client->ps.delta_angles[YAW]; return qtrue; - } - else - {//lock these angles - if ( self->client->ps.viewEntity <= 0 || self->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( self, self->client->ps.viewangles ); + } else { // lock these angles + if (self->client->ps.viewEntity <= 0 || self->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(self, self->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( self->client->ps.viewangles[YAW] ) - self->client->ps.delta_angles[YAW]; + ucmd->angles[YAW] = ANGLE2SHORT(self->client->ps.viewangles[YAW]) - self->client->ps.delta_angles[YAW]; } return qtrue; } -qboolean PM_AdjustAnglesForStabDown( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( PM_StabDownAnim( ent->client->ps.torsoAnim ) - && ent->client->ps.torsoAnimTimer ) - {//lock our angles +qboolean PM_AdjustAnglesForStabDown(gentity_t *ent, usercmd_t *ucmd) { + if (PM_StabDownAnim(ent->client->ps.torsoAnim) && ent->client->ps.torsoAnimTimer) { // lock our angles ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - float elapsedTime = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ) - ent->client->ps.torsoAnimTimer; - //FIXME: scale forwardmove by dist from enemy - none if right next to him (so we don't slide off!) - if ( ent->enemy ) - { - float dist2Enemy = DistanceHorizontal( ent->enemy->currentOrigin, ent->currentOrigin ); - if ( dist2Enemy > (ent->enemy->maxs[0]*1.5f)+(ent->maxs[0]*1.5f) ) - { - ent->client->ps.speed = dist2Enemy*2.0f; - } - else - { + float elapsedTime = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim) - ent->client->ps.torsoAnimTimer; + // FIXME: scale forwardmove by dist from enemy - none if right next to him (so we don't slide off!) + if (ent->enemy) { + float dist2Enemy = DistanceHorizontal(ent->enemy->currentOrigin, ent->currentOrigin); + if (dist2Enemy > (ent->enemy->maxs[0] * 1.5f) + (ent->maxs[0] * 1.5f)) { + ent->client->ps.speed = dist2Enemy * 2.0f; + } else { ent->client->ps.speed = 0; } - } - else - { + } else { ent->client->ps.speed = 150; } - switch ( ent->client->ps.legsAnim ) - { + switch (ent->client->ps.legsAnim) { case BOTH_STABDOWN: - if ( elapsedTime >= 300 && elapsedTime < 900 ) - {//push forward? - //FIXME: speed! + if (elapsedTime >= 300 && elapsedTime < 900) { // push forward? + // FIXME: speed! ucmd->forwardmove = 127; } break; case BOTH_STABDOWN_STAFF: - if ( elapsedTime > 400 && elapsedTime < 950 ) - {//push forward? - //FIXME: speed! + if (elapsedTime > 400 && elapsedTime < 950) { // push forward? + // FIXME: speed! ucmd->forwardmove = 127; } break; case BOTH_STABDOWN_DUAL: - if ( elapsedTime >= 300 && elapsedTime < 900 ) - {//push forward? - //FIXME: speed! + if (elapsedTime >= 300 && elapsedTime < 900) { // push forward? + // FIXME: speed! ucmd->forwardmove = 127; } break; } - VectorClear( ent->client->ps.moveDir ); + VectorClear(ent->client->ps.moveDir); - if ( ent->enemy//still have a valid enemy - && ent->enemy->client//who is a client - && (PM_InKnockDownNoGetup( &ent->enemy->client->ps ) //enemy still on ground - || PM_InGetUpNoRoll( &ent->enemy->client->ps ) ) )//or getting straight up - {//aim at the enemy + if (ent->enemy // still have a valid enemy + && ent->enemy->client // who is a client + && (PM_InKnockDownNoGetup(&ent->enemy->client->ps) // enemy still on ground + || PM_InGetUpNoRoll(&ent->enemy->client->ps))) // or getting straight up + { // aim at the enemy vec3_t enemyDir; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, enemyDir ); - float enemyYaw = AngleNormalize180( vectoyaw( enemyDir ) ); - float yawError = AngleNormalize180( enemyYaw - AngleNormalize180( ent->client->ps.viewangles[YAW] ) ); - if ( yawError > 1 ) - { + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, enemyDir); + float enemyYaw = AngleNormalize180(vectoyaw(enemyDir)); + float yawError = AngleNormalize180(enemyYaw - AngleNormalize180(ent->client->ps.viewangles[YAW])); + if (yawError > 1) { yawError = 1; - } - else if ( yawError < -1 ) - { + } else if (yawError < -1) { yawError = -1; } - ucmd->angles[YAW] = ANGLE2SHORT( AngleNormalize180( ent->client->ps.viewangles[YAW] + yawError ) ) - ent->client->ps.delta_angles[YAW]; - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - } - else - {//can't turn - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + ucmd->angles[YAW] = ANGLE2SHORT(AngleNormalize180(ent->client->ps.viewangles[YAW] + yawError)) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + } else { // can't turn + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; } return qtrue; } return qfalse; } -qboolean PM_AdjustAnglesForSpinProtect( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.torsoAnim == BOTH_A6_SABERPROTECT ) - {//in the dual spin thing - if ( ent->client->ps.torsoAnimTimer ) - {//flatten and lock our angles, pull back camera - //FIXME: lerp this +qboolean PM_AdjustAnglesForSpinProtect(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.torsoAnim == BOTH_A6_SABERPROTECT) { // in the dual spin thing + if (ent->client->ps.torsoAnimTimer) { // flatten and lock our angles, pull back camera + // FIXME: lerp this ent->client->ps.viewangles[PITCH] = 0; - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } } return qfalse; } -qboolean PM_AdjustAnglesForWallRunUpFlipAlt( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForWallRunUpFlipAlt(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean PM_AdjustAnglesForHeldByMonster( gentity_t *ent, gentity_t *monster, usercmd_t *ucmd ) -{ - vec3_t newViewAngles; - if ( !monster || !monster->client ) - { +qboolean PM_AdjustAnglesForHeldByMonster(gentity_t *ent, gentity_t *monster, usercmd_t *ucmd) { + vec3_t newViewAngles; + if (!monster || !monster->client) { return qfalse; } - VectorScale( monster->client->ps.viewangles, -1, newViewAngles ); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, newViewAngles ); + VectorScale(monster->client->ps.viewangles, -1, newViewAngles); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, newViewAngles); } - ucmd->angles[PITCH] = ANGLE2SHORT( newViewAngles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( newViewAngles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(newViewAngles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(newViewAngles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } -qboolean G_OkayToLean( playerState_t *ps, usercmd_t *cmd, qboolean interruptOkay ) -{ - if ( (ps->clientNum < MAX_CLIENTS||G_ControlledByPlayer(&g_entities[ps->clientNum]))//player - && ps->groundEntityNum != ENTITYNUM_NONE//on ground - && ( (interruptOkay//okay to interrupt a lean - && PM_DodgeAnim( ps->torsoAnim ) )//already leaning - || - (!ps->weaponTime//not attacking or being prevented from attacking - && !ps->legsAnimTimer//not in any held legs anim - && !ps->torsoAnimTimer) //not in any held torso anim - ) - && !(cmd->buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_LIGHTNING|BUTTON_USE_FORCE|BUTTON_FORCE_DRAIN|BUTTON_FORCEGRIP))//not trying to attack +qboolean G_OkayToLean(playerState_t *ps, usercmd_t *cmd, qboolean interruptOkay) { + if ((ps->clientNum < MAX_CLIENTS || G_ControlledByPlayer(&g_entities[ps->clientNum])) // player + && ps->groundEntityNum != ENTITYNUM_NONE // on ground + && ((interruptOkay // okay to interrupt a lean + && PM_DodgeAnim(ps->torsoAnim)) // already leaning + || (!ps->weaponTime // not attacking or being prevented from attacking + && !ps->legsAnimTimer // not in any held legs anim + && !ps->torsoAnimTimer) // not in any held torso anim + ) && + !(cmd->buttons & + (BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_LIGHTNING | BUTTON_USE_FORCE | BUTTON_FORCE_DRAIN | BUTTON_FORCEGRIP)) // not trying to attack //&& (ps->forcePowersActive&(1<velocity, vec3_origin )//not moving - && !cg_usingInFrontOf )//use button wouldn't be used for anything else + && VectorCompare(ps->velocity, vec3_origin) // not moving + && !cg_usingInFrontOf) // use button wouldn't be used for anything else { return qtrue; } @@ -1368,41 +1129,36 @@ are being updated isntead of a full move //FIXME: Now that they pmove twice per think, they snap-look really fast ================ */ -void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) -{ - short temp; - float rootPitch = 0, pitchMin=-75, pitchMax=75, yawMin=0, yawMax=0, lockedYawValue = 0; //just to shut up warnings - int i; - vec3_t start, end, tmins, tmaxs, right; - trace_t trace; - qboolean lockedYaw = qfalse/*, clamped = qfalse*/; - - if ( ps->pm_type == PM_INTERMISSION ) - { - return; // no view changes at all +void PM_UpdateViewAngles(playerState_t *ps, usercmd_t *cmd, gentity_t *gent) { + short temp; + float rootPitch = 0, pitchMin = -75, pitchMax = 75, yawMin = 0, yawMax = 0, lockedYawValue = 0; // just to shut up warnings + int i; + vec3_t start, end, tmins, tmaxs, right; + trace_t trace; + qboolean lockedYaw = qfalse /*, clamped = qfalse*/; + + if (ps->pm_type == PM_INTERMISSION) { + return; // no view changes at all } - //TEMP -#if 0 //rww 12/23/02 - I'm disabling this for now, I'm going to try to make it work with my new rag stuff + // TEMP +#if 0 // rww 12/23/02 - I'm disabling this for now, I'm going to try to make it work with my new rag stuff if ( gent != NULL ) { PM_IKUpdate( gent ); } #endif - if ( ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0 ) - { - return; // no view changes at all + if (ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0) { + return; // no view changes at all } -// if ( player_locked ) -// {//can't turn -// return; -// } - if ( ps->clientNum != 0 && gent != NULL && gent->client != NULL ) - { - if(gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) - { + // if ( player_locked ) + // {//can't turn + // return; + // } + if (ps->clientNum != 0 && gent != NULL && gent->client != NULL) { + if (gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) { pitchMin = 0 - gent->client->renderInfo.headPitchRangeUp - gent->client->renderInfo.torsoPitchRangeUp; pitchMax = gent->client->renderInfo.headPitchRangeDown + gent->client->renderInfo.torsoPitchRangeDown; @@ -1411,19 +1167,15 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) lockedYaw = qtrue; lockedYawValue = gent->client->renderInfo.lockYaw; - } - else - { - pitchMin = -gent->client->renderInfo.headPitchRangeUp-gent->client->renderInfo.torsoPitchRangeUp; - pitchMax = gent->client->renderInfo.headPitchRangeDown+gent->client->renderInfo.torsoPitchRangeDown; + } else { + pitchMin = -gent->client->renderInfo.headPitchRangeUp - gent->client->renderInfo.torsoPitchRangeUp; + pitchMax = gent->client->renderInfo.headPitchRangeDown + gent->client->renderInfo.torsoPitchRangeDown; } } - if ( ps->eFlags & EF_LOCKED_TO_WEAPON ) - { + if (ps->eFlags & EF_LOCKED_TO_WEAPON) { // Emplaced guns have different pitch capabilities - if ( gent && gent->owner && gent->owner->e_UseFunc == useF_eweb_use ) - { + if (gent && gent->owner && gent->owner->e_UseFunc == useF_eweb_use) { pitchMin = -15; pitchMax = 10; /* @@ -1432,9 +1184,7 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) yawMin = yawMax *-1; lockedYaw = qtrue; */ - } - else - { + } else { pitchMin = -35; pitchMax = 30; } @@ -1443,37 +1193,30 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) Vehicle_t *pVeh = NULL; // If we're a vehicle, or we're riding a vehicle...? - if ( gent && gent->client && gent->client->NPC_class == CLASS_VEHICLE && gent->m_pVehicle) - { + if (gent && gent->client && gent->client->NPC_class == CLASS_VEHICLE && gent->m_pVehicle) { pVeh = gent->m_pVehicle; // If we're a vehicle... - if (pVeh->m_pVehicleInfo->Inhabited(pVeh) || pVeh->m_iBoarding!=0 || pVeh->m_pVehicleInfo->type!=VH_ANIMAL) - { + if (pVeh->m_pVehicleInfo->Inhabited(pVeh) || pVeh->m_iBoarding != 0 || pVeh->m_pVehicleInfo->type != VH_ANIMAL) { lockedYawValue = pVeh->m_vOrientation[YAW]; yawMax = yawMin = 0; - rootPitch = pVeh->m_vOrientation[PITCH];//??? what if goes over 90 when add the min/max? - pitchMax = 0.0f;//pVeh->m_pVehicleInfo->pitchLimit; - pitchMin = 0.0f;//-pitchMax; + rootPitch = pVeh->m_vOrientation[PITCH]; //??? what if goes over 90 when add the min/max? + pitchMax = 0.0f; // pVeh->m_pVehicleInfo->pitchLimit; + pitchMin = 0.0f; //-pitchMax; lockedYaw = qtrue; } // If we're riding a vehicle... - else if ( (pVeh = G_IsRidingVehicle( gent ) ) != NULL ) - { - if ( pVeh->m_pVehicleInfo->type != VH_ANIMAL ) - {//animals just turn normally, no clamping - lockedYawValue = 0;//gent->owner->client->ps.vehicleAngles[YAW]; + else if ((pVeh = G_IsRidingVehicle(gent)) != NULL) { + if (pVeh->m_pVehicleInfo->type != VH_ANIMAL) { // animals just turn normally, no clamping + lockedYawValue = 0; // gent->owner->client->ps.vehicleAngles[YAW]; lockedYaw = qtrue; yawMax = pVeh->m_pVehicleInfo->lookYaw; yawMin = -yawMax; - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { - rootPitch = pVeh->m_vOrientation[PITCH];//gent->owner->client->ps.vehicleAngles[PITCH];//??? what if goes over 90 when add the min/max? + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + rootPitch = pVeh->m_vOrientation[PITCH]; // gent->owner->client->ps.vehicleAngles[PITCH];//??? what if goes over 90 when add the min/max? pitchMax = pVeh->m_pVehicleInfo->pitchLimit; pitchMin = -pitchMax; - } - else - { - rootPitch = 0;//gent->owner->client->ps.vehicleAngles[PITCH];//??? what if goes over 90 when add the min/max? + } else { + rootPitch = 0; // gent->owner->client->ps.vehicleAngles[PITCH];//??? what if goes over 90 when add the min/max? pitchMax = pVeh->m_pVehicleInfo->lookPitch; pitchMin = -pitchMax; } @@ -1487,30 +1230,25 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) }*/ } - const short pitchClampMin = ANGLE2SHORT(rootPitch+pitchMin); - const short pitchClampMax = ANGLE2SHORT(rootPitch+pitchMax); - const short yawClampMin = ANGLE2SHORT(lockedYawValue+yawMin); - const short yawClampMax = ANGLE2SHORT(lockedYawValue+yawMax); + const short pitchClampMin = ANGLE2SHORT(rootPitch + pitchMin); + const short pitchClampMax = ANGLE2SHORT(rootPitch + pitchMax); + const short yawClampMin = ANGLE2SHORT(lockedYawValue + yawMin); + const short yawClampMax = ANGLE2SHORT(lockedYawValue + yawMax); // circularly clamp the angles with deltas - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { temp = cmd->angles[i] + ps->delta_angles[i]; - if ( i == PITCH ) - { - //FIXME get this limit from the NPCs stats? - // don't let the player look up or down more than 90 degrees - if ( temp > pitchClampMax ) - { - ps->delta_angles[i] = (pitchClampMax - cmd->angles[i]) & 0xffff; //& clamp to short + if (i == PITCH) { + // FIXME get this limit from the NPCs stats? + // don't let the player look up or down more than 90 degrees + if (temp > pitchClampMax) { + ps->delta_angles[i] = (pitchClampMax - cmd->angles[i]) & 0xffff; //& clamp to short temp = pitchClampMax; - //clamped = qtrue; - } - else if ( temp < pitchClampMin ) - { - ps->delta_angles[i] = (pitchClampMin - cmd->angles[i]) & 0xffff; //& clamp to short + // clamped = qtrue; + } else if (temp < pitchClampMin) { + ps->delta_angles[i] = (pitchClampMin - cmd->angles[i]) & 0xffff; //& clamp to short temp = pitchClampMin; - //clamped = qtrue; + // clamped = qtrue; } } /* @@ -1528,7 +1266,7 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) } } */ - //FIXME: Are we losing precision here? Is this why it jitters? + // FIXME: Are we losing precision here? Is this why it jitters? /* if ( i == YAW && lockedYaw ) { @@ -1563,192 +1301,122 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) } } */ - if ( i == YAW && lockedYaw ) - { - //FIXME get this limit from the NPCs stats? - // don't let the player look up or down more than 90 degrees - if ( temp > yawClampMax ) - { - ps->delta_angles[i] = (yawClampMax - cmd->angles[i]) & 0xffff; //& clamp to short + if (i == YAW && lockedYaw) { + // FIXME get this limit from the NPCs stats? + // don't let the player look up or down more than 90 degrees + if (temp > yawClampMax) { + ps->delta_angles[i] = (yawClampMax - cmd->angles[i]) & 0xffff; //& clamp to short temp = yawClampMax; - //clamped = qtrue; - } - else if ( temp < yawClampMin ) - { - ps->delta_angles[i] = (yawClampMin - cmd->angles[i]) & 0xffff; //& clamp to short + // clamped = qtrue; + } else if (temp < yawClampMin) { + ps->delta_angles[i] = (yawClampMin - cmd->angles[i]) & 0xffff; //& clamp to short temp = yawClampMin; - //clamped = qtrue; + // clamped = qtrue; } ps->viewangles[i] = SHORT2ANGLE(temp); - } - else - { + } else { ps->viewangles[i] = SHORT2ANGLE(temp); } } - if ( gent ) - { //only in the real pmove - if ( (cmd->buttons & BUTTON_USE) ) - {//check leaning - if ( cg.renderingThirdPerson ) - {//third person lean - if ( G_OkayToLean( ps, cmd, qtrue ) - && (cmd->rightmove || (cmd->forwardmove && g_debugMelee->integer ) ) )//pushing a direction + if (gent) { // only in the real pmove + if ((cmd->buttons & BUTTON_USE)) { // check leaning + if (cg.renderingThirdPerson) { // third person lean + if (G_OkayToLean(ps, cmd, qtrue) && (cmd->rightmove || (cmd->forwardmove && g_debugMelee->integer))) // pushing a direction { int anim = -1; - if ( cmd->rightmove > 0 ) - {//lean right - if ( cmd->forwardmove > 0 ) - {//lean forward right - if ( ps->torsoAnim == BOTH_DODGE_HOLD_FR ) - { + if (cmd->rightmove > 0) { // lean right + if (cmd->forwardmove > 0) { // lean forward right + if (ps->torsoAnim == BOTH_DODGE_HOLD_FR) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_FR; } - } - else if ( cmd->forwardmove < 0 ) - {//lean backward right - if ( ps->torsoAnim == BOTH_DODGE_HOLD_BR ) - { + } else if (cmd->forwardmove < 0) { // lean backward right + if (ps->torsoAnim == BOTH_DODGE_HOLD_BR) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_BR; } - } - else - {//lean right - if ( ps->torsoAnim == BOTH_DODGE_HOLD_R ) - { + } else { // lean right + if (ps->torsoAnim == BOTH_DODGE_HOLD_R) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_R; } } - } - else if ( cmd->rightmove < 0 ) - {//lean left - if ( cmd->forwardmove > 0 ) - {//lean forward left - if ( ps->torsoAnim == BOTH_DODGE_HOLD_FL ) - { + } else if (cmd->rightmove < 0) { // lean left + if (cmd->forwardmove > 0) { // lean forward left + if (ps->torsoAnim == BOTH_DODGE_HOLD_FL) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_FL; } - } - else if ( cmd->forwardmove < 0 ) - {//lean backward left - if ( ps->torsoAnim == BOTH_DODGE_HOLD_BL ) - { + } else if (cmd->forwardmove < 0) { // lean backward left + if (ps->torsoAnim == BOTH_DODGE_HOLD_BL) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_BL; } - } - else - {//lean left - if ( ps->torsoAnim == BOTH_DODGE_HOLD_L ) - { + } else { // lean left + if (ps->torsoAnim == BOTH_DODGE_HOLD_L) { anim = ps->torsoAnim; - } - else - { + } else { anim = BOTH_DODGE_L; } } - } - else - {//not pressing either side - if ( cmd->forwardmove > 0 ) - {//lean forward - if ( PM_DodgeAnim( ps->torsoAnim ) ) - { + } else { // not pressing either side + if (cmd->forwardmove > 0) { // lean forward + if (PM_DodgeAnim(ps->torsoAnim)) { anim = ps->torsoAnim; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { anim = BOTH_DODGE_FL; - } - else - { + } else { anim = BOTH_DODGE_FR; } - } - else if ( cmd->forwardmove < 0 ) - {//lean backward - if ( PM_DodgeAnim( ps->torsoAnim ) ) - { + } else if (cmd->forwardmove < 0) { // lean backward + if (PM_DodgeAnim(ps->torsoAnim)) { anim = ps->torsoAnim; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { anim = BOTH_DODGE_BL; - } - else - { + } else { anim = BOTH_DODGE_BR; } } } - if ( anim != -1 ) - { + if (anim != -1) { int extraHoldTime = 0; - if ( PM_DodgeAnim( ps->torsoAnim ) - && !PM_DodgeHoldAnim( ps->torsoAnim ) ) - {//already in a dodge - //use the hold pose, don't start it all over again - anim = BOTH_DODGE_HOLD_FL+(anim-BOTH_DODGE_FL); + if (PM_DodgeAnim(ps->torsoAnim) && !PM_DodgeHoldAnim(ps->torsoAnim)) { // already in a dodge + // use the hold pose, don't start it all over again + anim = BOTH_DODGE_HOLD_FL + (anim - BOTH_DODGE_FL); extraHoldTime = 200; } - if ( anim == pm->ps->torsoAnim ) - { - if ( pm->ps->torsoAnimTimer < 100 ) - { + if (anim == pm->ps->torsoAnim) { + if (pm->ps->torsoAnimTimer < 100) { pm->ps->torsoAnimTimer = 100; } + } else { + NPC_SetAnim(gent, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetAnim( gent, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - if ( extraHoldTime && ps->torsoAnimTimer < extraHoldTime ) - { + if (extraHoldTime && ps->torsoAnimTimer < extraHoldTime) { ps->torsoAnimTimer += extraHoldTime; } - if ( ps->groundEntityNum != ENTITYNUM_NONE - && !cmd->upmove ) - { - NPC_SetAnim( gent, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (ps->groundEntityNum != ENTITYNUM_NONE && !cmd->upmove) { + NPC_SetAnim(gent, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ps->legsAnimTimer = ps->torsoAnimTimer; - } - else - { - NPC_SetAnim( gent, SETANIM_LEGS, anim, SETANIM_FLAG_NORMAL ); + } else { + NPC_SetAnim(gent, SETANIM_LEGS, anim, SETANIM_FLAG_NORMAL); } ps->weaponTime = ps->torsoAnimTimer; - ps->leanStopDebounceTime = ceil((float)ps->torsoAnimTimer/50.0f);//20; + ps->leanStopDebounceTime = ceil((float)ps->torsoAnimTimer / 50.0f); // 20; } } - } - else if ( (!cg.renderingThirdPerson||cg.zoomMode) && cmd->rightmove != 0 && !cmd->forwardmove && cmd->upmove <= 0 ) - {//Only lean if holding use button, strafing and not moving forward or back and not jumping + } else if ((!cg.renderingThirdPerson || cg.zoomMode) && cmd->rightmove != 0 && !cmd->forwardmove && + cmd->upmove <= 0) { // Only lean if holding use button, strafing and not moving forward or back and not jumping int leanofs = 0; - vec3_t viewangles; + vec3_t viewangles; - if ( cmd->rightmove > 0 ) - { + if (cmd->rightmove > 0) { /* if( pm->ps->legsAnim != LEGS_LEAN_RIGHT1) { @@ -1757,17 +1425,12 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) pm->ps->legsAnimTimer = 500;//Force it to hold the anim for at least half a sec */ - if ( ps->leanofs <= 28 ) - { + if (ps->leanofs <= 28) { leanofs = ps->leanofs + 4; - } - else - { + } else { leanofs = 32; } - } - else - { + } else { /* if ( pm->ps->legsAnim != LEGS_LEAN_LEFT1 ) { @@ -1776,87 +1439,66 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) pm->ps->legsAnimTimer = 500;//Force it to hold the anim for at least half a sec */ - if ( ps->leanofs >= -28 ) - { + if (ps->leanofs >= -28) { leanofs = ps->leanofs - 4; - } - else - { + } else { leanofs = -32; } } - VectorCopy( ps->origin, start ); + VectorCopy(ps->origin, start); start[2] += ps->viewheight; - VectorCopy( ps->viewangles, viewangles ); + VectorCopy(ps->viewangles, viewangles); viewangles[ROLL] = 0; - AngleVectors( ps->viewangles, NULL, right, NULL ); - VectorNormalize( right ); - right[2] = (leanofs<0)?0.25:-0.25; - VectorMA( start, leanofs, right, end ); - VectorSet( tmins, -8, -8, -4 ); - VectorSet( tmaxs, 8, 8, 4 ); - //if we don't trace EVERY frame, can TURN while leaning and - //end up leaning into solid architecture (sigh) - gi.trace( &trace, start, tmins, tmaxs, end, gent->s.number, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); + AngleVectors(ps->viewangles, NULL, right, NULL); + VectorNormalize(right); + right[2] = (leanofs < 0) ? 0.25 : -0.25; + VectorMA(start, leanofs, right, end); + VectorSet(tmins, -8, -8, -4); + VectorSet(tmaxs, 8, 8, 4); + // if we don't trace EVERY frame, can TURN while leaning and + // end up leaning into solid architecture (sigh) + gi.trace(&trace, start, tmins, tmaxs, end, gent->s.number, MASK_PLAYERSOLID, (EG2_Collision)0, 0); ps->leanofs = floor((float)leanofs * trace.fraction); ps->leanStopDebounceTime = 20; - } - else - { - if ( (cmd->forwardmove || cmd->upmove > 0) ) - { - if( ( pm->ps->legsAnim == LEGS_LEAN_RIGHT1) || - ( pm->ps->legsAnim == LEGS_LEAN_LEFT1) ) - { - pm->ps->legsAnimTimer = 0;//Force it to stop the anim + } else { + if ((cmd->forwardmove || cmd->upmove > 0)) { + if ((pm->ps->legsAnim == LEGS_LEAN_RIGHT1) || (pm->ps->legsAnim == LEGS_LEAN_LEFT1)) { + pm->ps->legsAnimTimer = 0; // Force it to stop the anim } - if ( ps->leanofs > 0 ) - { - ps->leanofs-=4; - if ( ps->leanofs < 0 ) - { + if (ps->leanofs > 0) { + ps->leanofs -= 4; + if (ps->leanofs < 0) { ps->leanofs = 0; } - } - else if ( ps->leanofs < 0 ) - { - ps->leanofs+=4; - if ( ps->leanofs > 0 ) - { + } else if (ps->leanofs < 0) { + ps->leanofs += 4; + if (ps->leanofs > 0) { ps->leanofs = 0; } } } - } - } - else//BUTTON_USE + } else // BUTTON_USE { - if ( ps->leanofs > 0 ) - { - ps->leanofs-=4; - if ( ps->leanofs < 0 ) - { + if (ps->leanofs > 0) { + ps->leanofs -= 4; + if (ps->leanofs < 0) { ps->leanofs = 0; } - } - else if ( ps->leanofs < 0 ) - { - ps->leanofs+=4; - if ( ps->leanofs > 0 ) - { + } else if (ps->leanofs < 0) { + ps->leanofs += 4; + if (ps->leanofs > 0) { ps->leanofs = 0; } } } } - if ( ps->leanStopDebounceTime ) - { + if (ps->leanStopDebounceTime) { ps->leanStopDebounceTime -= 1; cmd->rightmove = 0; cmd->buttons &= ~BUTTON_USE; diff --git a/code/game/bg_panimate.cpp b/code/game/bg_panimate.cpp index 75b7cebce4..d1c2b8f8df 100644 --- a/code/game/bg_panimate.cpp +++ b/code/game/bg_panimate.cpp @@ -22,7 +22,6 @@ along with this program; if not, see . #include "common_headers.h" - // define GAME_INCLUDE so that g_public.h does not define the // short, server-visible gclient_t and gentity_t structures, // because we define the full size ones in this file @@ -38,562 +37,513 @@ along with this program; if not, see . #include "wp_saber.h" #include "g_vehicles.h" -extern pmove_t *pm; -extern pml_t pml; -extern cvar_t *g_ICARUSDebug; -extern cvar_t *g_timescale; -extern cvar_t *g_synchSplitAnims; -extern cvar_t *g_AnimWarning; -extern cvar_t *g_noFootSlide; -extern cvar_t *g_noFootSlideRunScale; -extern cvar_t *g_noFootSlideWalkScale; -extern cvar_t *g_saberAnimSpeed; -extern cvar_t *g_saberAutoAim; -extern cvar_t *g_speederControlScheme; -extern cvar_t *g_saberNewControlScheme; - -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern qboolean ValidAnimFileIndex ( int index ); -extern qboolean PM_ControlledByPlayer( void ); -extern qboolean PM_DroidMelee( int npc_class ); -extern qboolean PM_PainAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern qboolean PM_DodgeAnim( int anim ); -extern qboolean PM_InSlopeAnim( int anim ); -extern qboolean PM_ForceAnim( int anim ); -extern qboolean PM_InKnockDownOnGround( playerState_t *ps ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_RunningAnim( int anim ); -extern qboolean PM_WalkingAnim( int anim ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); -extern qboolean PM_SaberStanceAnim( int anim ); -extern qboolean PM_SaberDrawPutawayAnim( int anim ); -extern void PM_SetJumped( float height, qboolean force ); -extern qboolean PM_InGetUpNoRoll( playerState_t *ps ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean G_TryingKataAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingCartwheel( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingSpecial( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingJumpAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingJumpForwardAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingLungeAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingPullAttack( gentity_t *self, usercmd_t *cmd, qboolean amPulling ); -extern qboolean G_InCinematicSaberAnim( gentity_t *self ); -extern qboolean G_ControlledByPlayer( gentity_t *self ); +extern pmove_t *pm; +extern pml_t pml; +extern cvar_t *g_ICARUSDebug; +extern cvar_t *g_timescale; +extern cvar_t *g_synchSplitAnims; +extern cvar_t *g_AnimWarning; +extern cvar_t *g_noFootSlide; +extern cvar_t *g_noFootSlideRunScale; +extern cvar_t *g_noFootSlideWalkScale; +extern cvar_t *g_saberAnimSpeed; +extern cvar_t *g_saberAutoAim; +extern cvar_t *g_speederControlScheme; +extern cvar_t *g_saberNewControlScheme; + +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern qboolean ValidAnimFileIndex(int index); +extern qboolean PM_ControlledByPlayer(void); +extern qboolean PM_DroidMelee(int npc_class); +extern qboolean PM_PainAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern qboolean PM_DodgeAnim(int anim); +extern qboolean PM_InSlopeAnim(int anim); +extern qboolean PM_ForceAnim(int anim); +extern qboolean PM_InKnockDownOnGround(playerState_t *ps); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_RunningAnim(int anim); +extern qboolean PM_WalkingAnim(int anim); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); +extern qboolean PM_SaberStanceAnim(int anim); +extern qboolean PM_SaberDrawPutawayAnim(int anim); +extern void PM_SetJumped(float height, qboolean force); +extern qboolean PM_InGetUpNoRoll(playerState_t *ps); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean G_TryingKataAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingCartwheel(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingSpecial(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingJumpAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingJumpForwardAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingLungeAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingPullAttack(gentity_t *self, usercmd_t *cmd, qboolean amPulling); +extern qboolean G_InCinematicSaberAnim(gentity_t *self); +extern qboolean G_ControlledByPlayer(gentity_t *self); extern int g_crosshairEntNum; -int PM_AnimLength( int index, animNumber_t anim ); -qboolean PM_LockedAnim( int anim ); -qboolean PM_StandingAnim( int anim ); -qboolean PM_InOnGroundAnim ( playerState_t *ps ); -qboolean PM_SuperBreakWinAnim( int anim ); -qboolean PM_SuperBreakLoseAnim( int anim ); -qboolean PM_LockedAnim( int anim ); -saberMoveName_t PM_SaberFlipOverAttackMove( void ); -qboolean PM_CheckFlipOverAttackMove( qboolean checkEnemy ); -saberMoveName_t PM_SaberJumpForwardAttackMove( void ); -qboolean PM_CheckJumpForwardAttackMove( void ); -saberMoveName_t PM_SaberBackflipAttackMove( void ); -qboolean PM_CheckBackflipAttackMove( void ); -saberMoveName_t PM_SaberDualJumpAttackMove( void ); -qboolean PM_CheckDualJumpAttackMove( void ); -saberMoveName_t PM_SaberLungeAttackMove( qboolean fallbackToNormalLunge ); -qboolean PM_CheckLungeAttackMove( void ); +int PM_AnimLength(int index, animNumber_t anim); +qboolean PM_LockedAnim(int anim); +qboolean PM_StandingAnim(int anim); +qboolean PM_InOnGroundAnim(playerState_t *ps); +qboolean PM_SuperBreakWinAnim(int anim); +qboolean PM_SuperBreakLoseAnim(int anim); +qboolean PM_LockedAnim(int anim); +saberMoveName_t PM_SaberFlipOverAttackMove(void); +qboolean PM_CheckFlipOverAttackMove(qboolean checkEnemy); +saberMoveName_t PM_SaberJumpForwardAttackMove(void); +qboolean PM_CheckJumpForwardAttackMove(void); +saberMoveName_t PM_SaberBackflipAttackMove(void); +qboolean PM_CheckBackflipAttackMove(void); +saberMoveName_t PM_SaberDualJumpAttackMove(void); +qboolean PM_CheckDualJumpAttackMove(void); +saberMoveName_t PM_SaberLungeAttackMove(qboolean fallbackToNormalLunge); +qboolean PM_CheckLungeAttackMove(void); // Okay, here lies the much-dreaded Pat-created FSM movement chart... Heretic II strikes again! // Why am I inflicting this on you? Well, it's better than hardcoded states. // Ideally this will be replaced with an external file or more sophisticated move-picker // once the game gets out of prototype stage. // Silly, but I'm replacing these macros so they are shorter! -#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) +#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) #define AFLAG_ACTIVE (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_WAIT (SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_FINISH (SETANIM_FLAG_HOLD) -//FIXME: add the alternate anims for each style? -saberMoveData_t saberMoveData[LS_MOVE_MAX] = {// NB:randomized +// FIXME: add the alternate anims for each style? +saberMoveData_t saberMoveData[LS_MOVE_MAX] = { + // NB:randomized // name anim(do all styles?)startQ endQ setanimflag blend, blocking chain_idle chain_attack trailLen - {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0 }, // LS_NONE = 0, + {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0}, // LS_NONE = 0, // General movements with saber - {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0 }, // LS_READY, - {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_DRAW, - {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_PUTAWAY, + {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0}, // LS_READY, + {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_DRAW, + {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_PUTAWAY, // Attacks - //UL2LR - {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200 }, // LS_A_TL2BR - //SLASH LEFT - {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200 }, // LS_A_L2R - //LL2UR - {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200 }, // LS_A_BL2TR - //LR2UL - {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200 }, // LS_A_BR2TL - //SLASH RIGHT - {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200 },// LS_A_R2L - //UR2LL - {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200 }, // LS_A_TR2BL - //SLASH DOWN - {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200 }, // LS_A_T2B - //special attacks - {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACKSTAB - {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK - {"CR Back Att", BOTH_CROUCHATTACKBACK1,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK_CR - {"RollStab", BOTH_ROLL_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_ROLL_STAB - {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_LUNGE - {"Jump Att", BOTH_FORCELEAP2_T__B_,Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_JUMP_T__B_ - {"Flip Stab", BOTH_JUMPFLIPSTABDOWN,Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200 }, // LS_A_FLIP_STAB - {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1,Q_L,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200 }, // LS_A_FLIP_SLASH - {"DualJump Atk",BOTH_JUMPATTACK6, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_BL_TR, 200 }, // LS_JUMPATTACK_DUAL - - {"DualJumpAtkL_A",BOTH_ARIAL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TL2BR, 200 }, // LS_JUMPATTACK_ARIAL_LEFT - {"DualJumpAtkR_A",BOTH_ARIAL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TR2BL, 200 }, // LS_JUMPATTACK_ARIAL_RIGHT - - {"DualJumpAtkL_A",BOTH_CARTWHEEL_LEFT, Q_R,Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TL_BR, 200 }, // LS_JUMPATTACK_CART_LEFT - {"DualJumpAtkR_A",BOTH_CARTWHEEL_RIGHT, Q_R,Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TR_BL, 200 }, // LS_JUMPATTACK_CART_RIGHT - - {"DualJumpAtkLStaff", BOTH_BUTTERFLY_FL1,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200 }, // LS_JUMPATTACK_STAFF_LEFT - {"DualJumpAtkRStaff", BOTH_BUTTERFLY_FR1,Q_R,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200 }, // LS_JUMPATTACK_STAFF_RIGHT - - {"ButterflyLeft", BOTH_BUTTERFLY_LEFT,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200 }, // LS_BUTTERFLY_LEFT - {"ButterflyRight", BOTH_BUTTERFLY_RIGHT,Q_R,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200 }, // LS_BUTTERFLY_RIGHT - - {"BkFlip Atk", BOTH_JUMPATTACK7, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200 }, // LS_A_BACKFLIP_ATK - {"DualSpinAtk", BOTH_SPINATTACK6, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK_DUAL - {"StfSpinAtk", BOTH_SPINATTACK7, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK - {"LngLeapAtk", BOTH_FORCELONGLEAP_ATTACK,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_LEAP_ATTACK - {"SwoopAtkR", BOTH_VS_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 200 }, // LS_SWOOP_ATTACK_RIGHT - {"SwoopAtkL", BOTH_VS_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 200 }, // LS_SWOOP_ATTACK_LEFT - {"TauntaunAtkR",BOTH_VT_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_TAUNTAUN_ATTACK_RIGHT - {"TauntaunAtkL",BOTH_VT_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_TAUNTAUN_ATTACK_LEFT - {"StfKickFwd", BOTH_A7_KICK_F, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_F - {"StfKickBack", BOTH_A7_KICK_B, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_B - {"StfKickRight",BOTH_A7_KICK_R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_R - {"StfKickLeft", BOTH_A7_KICK_L, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_L - {"StfKickSpin", BOTH_A7_KICK_S, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_S - {"StfKickBkFwd",BOTH_A7_KICK_BF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_BF - {"StfKickSplit",BOTH_A7_KICK_RL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_RL - {"StfKickFwdAir",BOTH_A7_KICK_F_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_F_AIR - {"StfKickBackAir",BOTH_A7_KICK_B_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_B_AIR - {"StfKickRightAir",BOTH_A7_KICK_R_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_R_AIR - {"StfKickLeftAir",BOTH_A7_KICK_L_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_L_AIR - {"StabDown", BOTH_STABDOWN, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN - {"StabDownStf", BOTH_STABDOWN_STAFF,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN_STAFF - {"StabDownDual",BOTH_STABDOWN_DUAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN_DUAL - {"dualspinprot",BOTH_A6_SABERPROTECT,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500 }, // LS_DUAL_SPIN_PROTECT - {"StfSoulCal", BOTH_A7_SOULCAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500 }, // LS_STAFF_SOULCAL - {"specialfast", BOTH_A1_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A1_SPECIAL - {"specialmed", BOTH_A2_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A2_SPECIAL - {"specialstr", BOTH_A3_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A3_SPECIAL - {"upsidedwnatk",BOTH_FLIP_ATTACK7, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_UPSIDE_DOWN_ATTACK - {"pullatkstab", BOTH_PULL_IMPALE_STAB,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_STAB - {"pullatkswing",BOTH_PULL_IMPALE_SWING,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_SWING - {"AloraSpinAtk",BOTH_ALORA_SPIN_SLASH,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK_ALORA - {"Dual FB Atk", BOTH_A6_FB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_DUAL_FB - {"Dual LR Atk", BOTH_A6_LR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_DUAL_LR - {"StfHiltBash", BOTH_A7_HILT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_HILT_BASH - - //starts - {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200 }, // LS_S_TL2BR - {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200 }, // LS_S_L2R - {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200 }, // LS_S_BL2TR - {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200 }, // LS_S_BR2TL - {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200 }, // LS_S_R2L - {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200 }, // LS_S_TR2BL - {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200 }, // LS_S_T2B - - //returns - {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TL2BR - {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_L2R - {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BL2TR - {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BR2TL - {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_R2L - {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TR2BL - {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_T2B - - //Transitions - {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc bottom right to right - {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) - {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) - {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast weak spin bottom right to top left - {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin bottom right to left - {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin bottom right to bottom left - {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) - {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc right to top right - {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast ar right to top (use: BOTH_T1_T___R) - {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc right to top left - {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin right to left - {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin right to bottom left - {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top right to bottom right - {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top right to right (use: BOTH_T1__R_TR) - {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top right to top (use: BOTH_T1_T__TR) - {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top right to top left - {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top right to left - {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin top right to bottom left - {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top to bottom right - {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top to right - {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top to top right - {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top to top left - {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top to left - {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top to bottom left - {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin top left to bottom right - {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top left to right (use: BOTH_T1__R_TL) - {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) - {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top left to top (use: BOTH_T1_T__TL) - {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top left to left (use: BOTH_T1__L_TL) - {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top left to bottom left - {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin left to bottom right - {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin left to right - {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc left to top right (use: BOTH_T1_TR__L) - {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc left to top (use: BOTH_T1_T___L) - {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc left to top left - {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) - {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin bottom left to bottom right - {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin bottom left to right - {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast weak spin bottom left to top right - {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) - {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) - {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc bottom left to left - - //Bounces - {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - - //Deflected attacks (like bounces, but slide off enemy saber, not straight back) - {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - - //Reflected attacks - {"Reflected BR",BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BR - {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__R - {"Reflected TR",BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TR - {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_T_ - {"Reflected TL",BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TL - {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__L - {"Reflected BL",BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BL - {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_B_ + // UL2LR + {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200}, // LS_A_TL2BR + // SLASH LEFT + {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200}, // LS_A_L2R + // LL2UR + {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200}, // LS_A_BL2TR + // LR2UL + {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200}, // LS_A_BR2TL + // SLASH RIGHT + {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200}, // LS_A_R2L + // UR2LL + {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200}, // LS_A_TR2BL + // SLASH DOWN + {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200}, // LS_A_T2B + // special attacks + {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACKSTAB + {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK + {"CR Back Att", BOTH_CROUCHATTACKBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK_CR + {"RollStab", BOTH_ROLL_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_ROLL_STAB + {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_LUNGE + {"Jump Att", BOTH_FORCELEAP2_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_JUMP_T__B_ + {"Flip Stab", BOTH_JUMPFLIPSTABDOWN, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200}, // LS_A_FLIP_STAB + {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200}, // LS_A_FLIP_SLASH + {"DualJump Atk", BOTH_JUMPATTACK6, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_BL_TR, 200}, // LS_JUMPATTACK_DUAL + + {"DualJumpAtkL_A", BOTH_ARIAL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TL2BR, 200}, // LS_JUMPATTACK_ARIAL_LEFT + {"DualJumpAtkR_A", BOTH_ARIAL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TR2BL, 200}, // LS_JUMPATTACK_ARIAL_RIGHT + + {"DualJumpAtkL_A", BOTH_CARTWHEEL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TL_BR, 200}, // LS_JUMPATTACK_CART_LEFT + {"DualJumpAtkR_A", BOTH_CARTWHEEL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TR_BL, 200}, // LS_JUMPATTACK_CART_RIGHT + + {"DualJumpAtkLStaff", BOTH_BUTTERFLY_FL1, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200}, // LS_JUMPATTACK_STAFF_LEFT + {"DualJumpAtkRStaff", BOTH_BUTTERFLY_FR1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200}, // LS_JUMPATTACK_STAFF_RIGHT + + {"ButterflyLeft", BOTH_BUTTERFLY_LEFT, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200}, // LS_BUTTERFLY_LEFT + {"ButterflyRight", BOTH_BUTTERFLY_RIGHT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200}, // LS_BUTTERFLY_RIGHT + + {"BkFlip Atk", BOTH_JUMPATTACK7, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200}, // LS_A_BACKFLIP_ATK + {"DualSpinAtk", BOTH_SPINATTACK6, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK_DUAL + {"StfSpinAtk", BOTH_SPINATTACK7, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK + {"LngLeapAtk", BOTH_FORCELONGLEAP_ATTACK, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_LEAP_ATTACK + {"SwoopAtkR", BOTH_VS_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 200}, // LS_SWOOP_ATTACK_RIGHT + {"SwoopAtkL", BOTH_VS_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 200}, // LS_SWOOP_ATTACK_LEFT + {"TauntaunAtkR", BOTH_VT_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_TAUNTAUN_ATTACK_RIGHT + {"TauntaunAtkL", BOTH_VT_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_TAUNTAUN_ATTACK_LEFT + {"StfKickFwd", BOTH_A7_KICK_F, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_F + {"StfKickBack", BOTH_A7_KICK_B, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_B + {"StfKickRight", BOTH_A7_KICK_R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_R + {"StfKickLeft", BOTH_A7_KICK_L, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_L + {"StfKickSpin", BOTH_A7_KICK_S, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_S + {"StfKickBkFwd", BOTH_A7_KICK_BF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_BF + {"StfKickSplit", BOTH_A7_KICK_RL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_RL + {"StfKickFwdAir", BOTH_A7_KICK_F_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_F_AIR + {"StfKickBackAir", BOTH_A7_KICK_B_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_B_AIR + {"StfKickRightAir", BOTH_A7_KICK_R_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_R_AIR + {"StfKickLeftAir", BOTH_A7_KICK_L_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_L_AIR + {"StabDown", BOTH_STABDOWN, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN + {"StabDownStf", BOTH_STABDOWN_STAFF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN_STAFF + {"StabDownDual", BOTH_STABDOWN_DUAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN_DUAL + {"dualspinprot", BOTH_A6_SABERPROTECT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500}, // LS_DUAL_SPIN_PROTECT + {"StfSoulCal", BOTH_A7_SOULCAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500}, // LS_STAFF_SOULCAL + {"specialfast", BOTH_A1_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A1_SPECIAL + {"specialmed", BOTH_A2_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A2_SPECIAL + {"specialstr", BOTH_A3_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A3_SPECIAL + {"upsidedwnatk", BOTH_FLIP_ATTACK7, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_UPSIDE_DOWN_ATTACK + {"pullatkstab", BOTH_PULL_IMPALE_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_STAB + {"pullatkswing", BOTH_PULL_IMPALE_SWING, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_SWING + {"AloraSpinAtk", BOTH_ALORA_SPIN_SLASH, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK_ALORA + {"Dual FB Atk", BOTH_A6_FB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_DUAL_FB + {"Dual LR Atk", BOTH_A6_LR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_DUAL_LR + {"StfHiltBash", BOTH_A7_HILT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_HILT_BASH + + // starts + {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200}, // LS_S_TL2BR + {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200}, // LS_S_L2R + {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200}, // LS_S_BL2TR + {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200}, // LS_S_BR2TL + {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200}, // LS_S_R2L + {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200}, // LS_S_TR2BL + {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200}, // LS_S_T2B + + // returns + {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TL2BR + {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_L2R + {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BL2TR + {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BR2TL + {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_R2L + {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TR2BL + {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_T2B + + // Transitions + {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc bottom right to right + {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) + {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) + {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast weak spin bottom right to top left + {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin bottom right to left + {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin bottom right to bottom left + {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, + 150}, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) + {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc right to top right + {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast ar right to top (use: BOTH_T1_T___R) + {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc right to top left + {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin right to left + {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin right to bottom left + {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top right to bottom right + {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top right to right (use: BOTH_T1__R_TR) + {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top right to top (use: BOTH_T1_T__TR) + {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top right to top left + {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top right to left + {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin top right to bottom left + {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top to bottom right + {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top to right + {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc top to top right + {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top to top left + {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top to left + {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top to bottom left + {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin top left to bottom right + {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top left to right (use: BOTH_T1__R_TL) + {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) + {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top left to top (use: BOTH_T1_T__TL) + {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top left to left (use: BOTH_T1__L_TL) + {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top left to bottom left + {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin left to bottom right + {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin left to right + {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc left to top right (use: BOTH_T1_TR__L) + {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc left to top (use: BOTH_T1_T___L) + {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc left to top left + {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, + 150}, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) + {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin bottom left to bottom right + {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin bottom left to right + {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast weak spin bottom left to top right + {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) + {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, + 150}, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) + {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc bottom left to left + + // Bounces + {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + + // Deflected attacks (like bounces, but slide off enemy saber, not straight back) + {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + + // Reflected attacks + {"Reflected BR", BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BR + {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__R + {"Reflected TR", BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TR + {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_T_ + {"Reflected TL", BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TL + {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__L + {"Reflected BL", BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BL + {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_B_ // Broken parries - {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UP, - {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UR, - {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UL, - {"BParry LR", BOTH_H1_S1_BL, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LR, - {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL - {"BParry LL", BOTH_H1_S1_BR, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL + {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UP, + {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UR, + {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UL, + {"BParry LR", BOTH_H1_S1_BL, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LR, + {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LL + {"BParry LL", BOTH_H1_S1_BR, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LL // Knockaways - {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150 }, // LS_PARRY_UP, - {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150 }, // LS_PARRY_UR, - {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150 }, // LS_PARRY_UL, - {"Knock LR", BOTH_K1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150 }, // LS_PARRY_LR, - {"Knock LL", BOTH_K1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150 }, // LS_PARRY_LL + {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150}, // LS_PARRY_UP, + {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150}, // LS_PARRY_UR, + {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150}, // LS_PARRY_UL, + {"Knock LR", BOTH_K1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150}, // LS_PARRY_LR, + {"Knock LL", BOTH_K1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150}, // LS_PARRY_LL // Parry - {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150 }, // LS_PARRY_UP, - {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150 }, // LS_PARRY_UR, - {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150 }, // LS_PARRY_UL, - {"Parry LR", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150 }, // LS_PARRY_LR, - {"Parry LL", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150 }, // LS_PARRY_LL + {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150}, // LS_PARRY_UP, + {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150}, // LS_PARRY_UR, + {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150}, // LS_PARRY_UL, + {"Parry LR", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150}, // LS_PARRY_LR, + {"Parry LL", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150}, // LS_PARRY_LL // Reflecting a missile - {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300 }, // LS_PARRY_UP, - {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300 }, // LS_PARRY_UR, - {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300 }, // LS_PARRY_UL, - {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300 }, // LS_PARRY_LR - {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300 }, // LS_PARRY_LL, + {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300}, // LS_PARRY_UP, + {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300}, // LS_PARRY_UR, + {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300}, // LS_PARRY_UL, + {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300}, // LS_PARRY_LR + {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300}, // LS_PARRY_LL, }; - -saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = -{ +saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = { { - LS_NONE, //Can't transition to same pos! - LS_T1_BR__R,//40 - LS_T1_BR_TR, - LS_T1_BR_T_, - LS_T1_BR_TL, - LS_T1_BR__L, - LS_T1_BR_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE, // Can't transition to same pos! + LS_T1_BR__R, // 40 + LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1__R_BR,//46 - LS_NONE, //Can't transition to same pos! - LS_T1__R_TR, - LS_T1__R_T_, - LS_T1__R_TL, - LS_T1__R__L, - LS_T1__R_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1__R_BR, // 46 + LS_NONE, // Can't transition to same pos! + LS_T1__R_TR, LS_T1__R_T_, LS_T1__R_TL, LS_T1__R__L, LS_T1__R_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_TR_BR,//52 + LS_T1_TR_BR, // 52 LS_T1_TR__R, - LS_NONE, //Can't transition to same pos! - LS_T1_TR_T_, - LS_T1_TR_TL, - LS_T1_TR__L, - LS_T1_TR_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE, // Can't transition to same pos! + LS_T1_TR_T_, LS_T1_TR_TL, LS_T1_TR__L, LS_T1_TR_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_T__BR,//58 - LS_T1_T___R, - LS_T1_T__TR, - LS_NONE, //Can't transition to same pos! - LS_T1_T__TL, - LS_T1_T___L, - LS_T1_T__BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_T__BR, // 58 + LS_T1_T___R, LS_T1_T__TR, + LS_NONE, // Can't transition to same pos! + LS_T1_T__TL, LS_T1_T___L, LS_T1_T__BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_TL_BR,//64 - LS_T1_TL__R, - LS_T1_TL_TR, - LS_T1_TL_T_, - LS_NONE, //Can't transition to same pos! - LS_T1_TL__L, - LS_T1_TL_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_TL_BR, // 64 + LS_T1_TL__R, LS_T1_TL_TR, LS_T1_TL_T_, + LS_NONE, // Can't transition to same pos! + LS_T1_TL__L, LS_T1_TL_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1__L_BR,//70 - LS_T1__L__R, - LS_T1__L_TR, - LS_T1__L_T_, - LS_T1__L_TL, - LS_NONE, //Can't transition to same pos! + LS_T1__L_BR, // 70 + LS_T1__L__R, LS_T1__L_TR, LS_T1__L_T_, LS_T1__L_TL, + LS_NONE, // Can't transition to same pos! LS_T1__L_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_BL_BR,//76 - LS_T1_BL__R, - LS_T1_BL_TR, - LS_T1_BL_T_, - LS_T1_BL_TL, - LS_T1_BL__L, - LS_NONE, //Can't transition to same pos! - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_BL_BR, // 76 + LS_T1_BL__R, LS_T1_BL_TR, LS_T1_BL_T_, LS_T1_BL_TL, LS_T1_BL__L, + LS_NONE, // Can't transition to same pos! + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_BL_BR,//NOTE: there are no transitions from bottom, so re-use the bottom right transitions - LS_T1_BR__R, - LS_T1_BR_TR, - LS_T1_BR_T_, - LS_T1_BR_TL, - LS_T1_BR__L, - LS_T1_BR_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any - } -}; + LS_T1_BL_BR, // NOTE: there are no transitions from bottom, so re-use the bottom right transitions + LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any + }}; -void PM_VelocityForSaberMove( playerState_t *ps, vec3_t throwDir ) -{ - vec3_t vForward = { 0.0f }, vRight = { 0.0f }, vUp = { 0.0f }, startQ = { 0.0f }, endQ = { 0.0f }; +void PM_VelocityForSaberMove(playerState_t *ps, vec3_t throwDir) { + vec3_t vForward = {0.0f}, vRight = {0.0f}, vUp = {0.0f}, startQ = {0.0f}, endQ = {0.0f}; - AngleVectors( ps->viewangles, vForward, vRight, vUp ); + AngleVectors(ps->viewangles, vForward, vRight, vUp); - switch ( saberMoveData[ps->saberMove].startQuad ) - { + switch (saberMoveData[ps->saberMove].startQuad) { case Q_BR: - VectorScale( vRight, 1, startQ ); - VectorMA( startQ, -1, vUp, startQ ); + VectorScale(vRight, 1, startQ); + VectorMA(startQ, -1, vUp, startQ); break; case Q_R: - VectorScale( vRight, 2, startQ ); + VectorScale(vRight, 2, startQ); break; case Q_TR: - VectorScale( vRight, 1, startQ ); - VectorMA( startQ, 1, vUp, startQ ); + VectorScale(vRight, 1, startQ); + VectorMA(startQ, 1, vUp, startQ); break; case Q_T: - VectorScale( vUp, 2, startQ ); + VectorScale(vUp, 2, startQ); break; case Q_TL: - VectorScale( vRight, -1, startQ ); - VectorMA( startQ, 1, vUp, startQ ); + VectorScale(vRight, -1, startQ); + VectorMA(startQ, 1, vUp, startQ); break; case Q_L: - VectorScale( vRight, -2, startQ ); + VectorScale(vRight, -2, startQ); break; case Q_BL: - VectorScale( vRight, -1, startQ ); - VectorMA( startQ, -1, vUp, startQ ); + VectorScale(vRight, -1, startQ); + VectorMA(startQ, -1, vUp, startQ); break; case Q_B: - VectorScale( vUp, -2, startQ ); + VectorScale(vUp, -2, startQ); break; } - switch ( saberMoveData[ps->saberMove].endQuad ) - { + switch (saberMoveData[ps->saberMove].endQuad) { case Q_BR: - VectorScale( vRight, 1, endQ ); - VectorMA( endQ, -1, vUp, endQ ); + VectorScale(vRight, 1, endQ); + VectorMA(endQ, -1, vUp, endQ); break; case Q_R: - VectorScale( vRight, 2, endQ ); + VectorScale(vRight, 2, endQ); break; case Q_TR: - VectorScale( vRight, 1, endQ ); - VectorMA( endQ, 1, vUp, endQ ); + VectorScale(vRight, 1, endQ); + VectorMA(endQ, 1, vUp, endQ); break; case Q_T: - VectorScale( vUp, 2, endQ ); + VectorScale(vUp, 2, endQ); break; case Q_TL: - VectorScale( vRight, -1, endQ ); - VectorMA( endQ, 1, vUp, endQ ); + VectorScale(vRight, -1, endQ); + VectorMA(endQ, 1, vUp, endQ); break; case Q_L: - VectorScale( vRight, -2, endQ ); + VectorScale(vRight, -2, endQ); break; case Q_BL: - VectorScale( vRight, -1, endQ ); - VectorMA( endQ, -1, vUp, endQ ); + VectorScale(vRight, -1, endQ); + VectorMA(endQ, -1, vUp, endQ); break; case Q_B: - VectorScale( vUp, -2, endQ ); + VectorScale(vUp, -2, endQ); break; } - VectorMA( endQ, 2, vForward, endQ ); - VectorScale( throwDir, 125, throwDir );//FIXME: pass in the throw strength? - VectorSubtract( endQ, startQ, throwDir ); + VectorMA(endQ, 2, vForward, endQ); + VectorScale(throwDir, 125, throwDir); // FIXME: pass in the throw strength? + VectorSubtract(endQ, startQ, throwDir); } -qboolean PM_VelocityForBlockedMove( playerState_t *ps, vec3_t throwDir ) -{ - vec3_t vForward, vRight, vUp; - AngleVectors( ps->viewangles, vForward, vRight, vUp ); - switch ( ps->saberBlocked ) - { +qboolean PM_VelocityForBlockedMove(playerState_t *ps, vec3_t throwDir) { + vec3_t vForward, vRight, vUp; + AngleVectors(ps->viewangles, vForward, vRight, vUp); + switch (ps->saberBlocked) { case BLOCKED_UPPER_RIGHT: - VectorScale( vRight, 1, throwDir ); - VectorMA( throwDir, 1, vUp, throwDir ); + VectorScale(vRight, 1, throwDir); + VectorMA(throwDir, 1, vUp, throwDir); break; case BLOCKED_UPPER_LEFT: - VectorScale( vRight, -1, throwDir ); - VectorMA( throwDir, 1, vUp, throwDir ); + VectorScale(vRight, -1, throwDir); + VectorMA(throwDir, 1, vUp, throwDir); break; case BLOCKED_LOWER_RIGHT: - VectorScale( vRight, 1, throwDir ); - VectorMA( throwDir, -1, vUp, throwDir ); + VectorScale(vRight, 1, throwDir); + VectorMA(throwDir, -1, vUp, throwDir); break; case BLOCKED_LOWER_LEFT: - VectorScale( vRight, -1, throwDir ); - VectorMA( throwDir, -1, vUp, throwDir ); + VectorScale(vRight, -1, throwDir); + VectorMA(throwDir, -1, vUp, throwDir); break; case BLOCKED_TOP: - VectorScale( vUp, 2, throwDir ); + VectorScale(vUp, 2, throwDir); break; default: return qfalse; break; } - VectorMA( throwDir, 2, vForward, throwDir ); - VectorScale( throwDir, 250, throwDir );//FIXME: pass in the throw strength? + VectorMA(throwDir, 2, vForward, throwDir); + VectorScale(throwDir, 250, throwDir); // FIXME: pass in the throw strength? return qtrue; } -int PM_AnimLevelForSaberAnim( int anim ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____ ) - { +int PM_AnimLevelForSaberAnim(int anim) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____) { return FORCE_LEVEL_1; } - if ( anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____ ) - { + if (anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____) { return FORCE_LEVEL_2; } - if ( anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____ ) - { + if (anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____) { return FORCE_LEVEL_3; } - if ( anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____ ) - {//desann + if (anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____) { // desann return FORCE_LEVEL_4; } - if ( anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____ ) - {//tavion + if (anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____) { // tavion return FORCE_LEVEL_5; } - if ( anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____ ) - {//dual + if (anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____) { // dual return SS_DUAL; } - if ( anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____ ) - {//staff + if (anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____) { // staff return SS_STAFF; } return FORCE_LEVEL_0; } -int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) -{ +int PM_PowerLevelForSaberAnim(playerState_t *ps, int saberNum) { int anim = ps->torsoAnim; - int animTimeElapsed = PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)anim ) - ps->torsoAnimTimer; - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____ ) - { - //FIXME: these two need their own style - if ( ps->saber[0].type == SABER_LANCE ) - { + int animTimeElapsed = PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)anim) - ps->torsoAnimTimer; + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____) { + // FIXME: these two need their own style + if (ps->saber[0].type == SABER_LANCE) { return FORCE_LEVEL_4; - } - else if ( ps->saber[0].type == SABER_TRIDENT ) - { + } else if (ps->saber[0].type == SABER_TRIDENT) { return FORCE_LEVEL_3; } return FORCE_LEVEL_1; } - if ( anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____ ) - { + if (anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____) { return FORCE_LEVEL_2; } - if ( anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____ ) - { + if (anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____) { return FORCE_LEVEL_3; } - if ( anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____ ) - {//desann + if (anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____) { // desann return FORCE_LEVEL_4; } - if ( anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____ ) - {//tavion + if (anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____) { // tavion return FORCE_LEVEL_2; } - if ( anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____ ) - {//dual + if (anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____) { // dual return FORCE_LEVEL_2; } - if ( anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____ ) - {//staff + if (anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____) { // staff return FORCE_LEVEL_2; } - if ( ( anim >= BOTH_P1_S1_T_ && anim <= BOTH_P1_S1_BR ) - || ( anim >= BOTH_P6_S6_T_ && anim <= BOTH_P6_S6_BR ) - || ( anim >= BOTH_P7_S7_T_ && anim <= BOTH_P7_S7_BR ) ) - {//parries - switch ( ps->saberAnimLevel ) - { + if ((anim >= BOTH_P1_S1_T_ && anim <= BOTH_P1_S1_BR) || (anim >= BOTH_P6_S6_T_ && anim <= BOTH_P6_S6_BR) || + (anim >= BOTH_P7_S7_T_ && anim <= BOTH_P7_S7_BR)) { // parries + switch (ps->saberAnimLevel) { case SS_STRONG: case SS_DESANN: return FORCE_LEVEL_3; @@ -612,47 +562,35 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) break; } } - if ( ( anim >= BOTH_K1_S1_T_ && anim <= BOTH_K1_S1_BR ) - || ( anim >= BOTH_K6_S6_T_ && anim <= BOTH_K6_S6_BR ) - || ( anim >= BOTH_K7_S7_T_ && anim <= BOTH_K7_S7_BR ) ) - {//knockaways + if ((anim >= BOTH_K1_S1_T_ && anim <= BOTH_K1_S1_BR) || (anim >= BOTH_K6_S6_T_ && anim <= BOTH_K6_S6_BR) || + (anim >= BOTH_K7_S7_T_ && anim <= BOTH_K7_S7_BR)) { // knockaways return FORCE_LEVEL_3; } - if ( ( anim >= BOTH_V1_BR_S1 && anim <= BOTH_V1_B__S1 ) - || ( anim >= BOTH_V6_BR_S6 && anim <= BOTH_V6_B__S6 ) - || ( anim >= BOTH_V7_BR_S7 && anim <= BOTH_V7_B__S7 ) ) - {//knocked-away attacks + if ((anim >= BOTH_V1_BR_S1 && anim <= BOTH_V1_B__S1) || (anim >= BOTH_V6_BR_S6 && anim <= BOTH_V6_B__S6) || + (anim >= BOTH_V7_BR_S7 && anim <= BOTH_V7_B__S7)) { // knocked-away attacks return FORCE_LEVEL_1; } - if ( ( anim >= BOTH_H1_S1_T_ && anim <= BOTH_H1_S1_BR ) - || ( anim >= BOTH_H6_S6_T_ && anim <= BOTH_H6_S6_BR ) - || ( anim >= BOTH_H7_S7_T_ && anim <= BOTH_H7_S7_BR ) ) - {//broken parries + if ((anim >= BOTH_H1_S1_T_ && anim <= BOTH_H1_S1_BR) || (anim >= BOTH_H6_S6_T_ && anim <= BOTH_H6_S6_BR) || + (anim >= BOTH_H7_S7_T_ && anim <= BOTH_H7_S7_BR)) { // broken parries return FORCE_LEVEL_0; } - switch ( anim ) - { + switch (anim) { case BOTH_A2_STABBACK1: - if ( ps->torsoAnimTimer < 450 ) - {//end of anim + if (ps->torsoAnimTimer < 450) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_ATTACK_BACK: - if ( ps->torsoAnimTimer < 500 ) - {//end of anim + if (ps->torsoAnimTimer < 500) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_CROUCHATTACKBACK1: - if ( ps->torsoAnimTimer < 800 ) - {//end of anim + if (ps->torsoAnimTimer < 800) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -661,41 +599,35 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) case BOTH_BUTTERFLY_RIGHT: case BOTH_BUTTERFLY_FL1: case BOTH_BUTTERFLY_FR1: - //FIXME: break up? + // FIXME: break up? return FORCE_LEVEL_3; break; case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: - //FIXME: break up? + // FIXME: break up? return FORCE_LEVEL_3; break; - case BOTH_K1_S1_T_: //# knockaway saber top - case BOTH_K1_S1_TR: //# knockaway saber top right - case BOTH_K1_S1_TL: //# knockaway saber top left - case BOTH_K1_S1_BL: //# knockaway saber bottom left - case BOTH_K1_S1_B_: //# knockaway saber bottom - case BOTH_K1_S1_BR: //# knockaway saber bottom right - //FIXME: break up? + case BOTH_K1_S1_T_: //# knockaway saber top + case BOTH_K1_S1_TR: //# knockaway saber top right + case BOTH_K1_S1_TL: //# knockaway saber top left + case BOTH_K1_S1_BL: //# knockaway saber bottom left + case BOTH_K1_S1_B_: //# knockaway saber bottom + case BOTH_K1_S1_BR: //# knockaway saber bottom right + // FIXME: break up? return FORCE_LEVEL_3; break; case BOTH_LUNGE2_B__T_: - if ( ps->torsoAnimTimer < 400 ) - {//end of anim + if (ps->torsoAnimTimer < 400) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 150 ) - {//beginning of anim + } else if (animTimeElapsed < 150) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_FORCELEAP2_T__B_: - if ( ps->torsoAnimTimer < 400 ) - {//end of anim + if (ps->torsoAnimTimer < 400) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 550 ) - {//beginning of anim + } else if (animTimeElapsed < 550) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -704,26 +636,20 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) case BOTH_VS_ATL_S: case BOTH_VT_ATR_S: case BOTH_VT_ATL_S: - return FORCE_LEVEL_3;//??? + return FORCE_LEVEL_3; //??? break; case BOTH_JUMPFLIPSLASHDOWN1: - if ( ps->torsoAnimTimer <= 900 ) - {//end of anim + if (ps->torsoAnimTimer <= 900) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 550 ) - {//beginning of anim + } else if (animTimeElapsed < 550) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_JUMPFLIPSTABDOWN: - if ( ps->torsoAnimTimer <= 1200 ) - {//end of anim + if (ps->torsoAnimTimer <= 1200) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed <= 250 ) - {//beginning of anim + } else if (animTimeElapsed <= 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -741,47 +667,35 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) } } */ - if ( ( ps->torsoAnimTimer >= 1450 - && animTimeElapsed >= 400 ) - ||(ps->torsoAnimTimer >= 400 - && animTimeElapsed >= 1100 ) ) - {//pretty much sideways + if ((ps->torsoAnimTimer >= 1450 && animTimeElapsed >= 400) || (ps->torsoAnimTimer >= 400 && animTimeElapsed >= 1100)) { // pretty much sideways return FORCE_LEVEL_3; } return FORCE_LEVEL_0; break; case BOTH_JUMPATTACK7: - if ( ps->torsoAnimTimer <= 1200 ) - {//end of anim + if (ps->torsoAnimTimer <= 1200) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_SPINATTACK6: - if ( animTimeElapsed <= 200 ) - {//beginning of anim + if (animTimeElapsed <= 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_SPINATTACK7: - if ( ps->torsoAnimTimer <= 500 ) - {//end of anim + if (ps->torsoAnimTimer <= 500) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 500 ) - {//beginning of anim + } else if (animTimeElapsed < 500) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_FORCELONGLEAP_ATTACK: - if ( animTimeElapsed <= 200 ) - {//1st four frames of anim + if (animTimeElapsed <= 200) { // 1st four frames of anim return FORCE_LEVEL_3; } break; @@ -795,70 +709,54 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) break; */ case BOTH_STABDOWN: - if ( ps->torsoAnimTimer <= 900 ) - {//end of anim + if (ps->torsoAnimTimer <= 900) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_STABDOWN_STAFF: - if ( ps->torsoAnimTimer <= 850 ) - {//end of anim + if (ps->torsoAnimTimer <= 850) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_STABDOWN_DUAL: - if ( ps->torsoAnimTimer <= 900 ) - {//end of anim + if (ps->torsoAnimTimer <= 900) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_A6_SABERPROTECT: - if ( ps->torsoAnimTimer < 650 ) - {//end of anim + if (ps->torsoAnimTimer < 650) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A7_SOULCAL: - if ( ps->torsoAnimTimer < 650 ) - {//end of anim + if (ps->torsoAnimTimer < 650) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 600 ) - {//beginning of anim + } else if (animTimeElapsed < 600) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A1_SPECIAL: - if ( ps->torsoAnimTimer < 600 ) - {//end of anim + if (ps->torsoAnimTimer < 600) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A2_SPECIAL: - if ( ps->torsoAnimTimer < 300 ) - {//end of anim + if (ps->torsoAnimTimer < 300) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A3_SPECIAL: - if ( ps->torsoAnimTimer < 700 ) - {//end of anim + if (ps->torsoAnimTimer < 700) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -867,52 +765,41 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) return FORCE_LEVEL_3; break; case BOTH_PULL_IMPALE_STAB: - if ( ps->torsoAnimTimer < 1000 ) - {//end of anim + if (ps->torsoAnimTimer < 1000) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_PULL_IMPALE_SWING: - if ( ps->torsoAnimTimer < 500 )//750 ) - {//end of anim + if (ps->torsoAnimTimer < 500) // 750 ) + { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 650 )//600 ) - {//beginning of anim + } else if (animTimeElapsed < 650) // 600 ) + { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_ALORA_SPIN_SLASH: - if ( ps->torsoAnimTimer < 900 ) - {//end of anim + if (ps->torsoAnimTimer < 900) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A6_FB: - if ( ps->torsoAnimTimer < 250 ) - {//end of anim + if (ps->torsoAnimTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A6_LR: - if ( ps->torsoAnimTimer < 250 ) - {//end of anim + if (ps->torsoAnimTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -920,41 +807,33 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) case BOTH_A7_HILT: return FORCE_LEVEL_0; break; -//===SABERLOCK SUPERBREAKS START=========================================================================== + //===SABERLOCK SUPERBREAKS START=========================================================================== case BOTH_LK_S_DL_T_SB_1_W: - if ( ps->torsoAnimTimer < 700 ) - {//end of anim + if (ps->torsoAnimTimer < 700) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_ST_S_SB_1_W: - if ( ps->torsoAnimTimer < 300 ) - {//end of anim + if (ps->torsoAnimTimer < 300) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_DL_S_SB_1_W: case BOTH_LK_S_S_S_SB_1_W: - if ( ps->torsoAnimTimer < 700 ) - {//end of anim + if (ps->torsoAnimTimer < 700) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_ST_T_SB_1_W: case BOTH_LK_S_S_T_SB_1_W: - if ( ps->torsoAnimTimer < 150 ) - {//end of anim + if (ps->torsoAnimTimer < 150) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -964,49 +843,37 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) break; case BOTH_LK_DL_DL_S_SB_1_W: case BOTH_LK_DL_ST_S_SB_1_W: - if ( animTimeElapsed < 1000 ) - {//beginning of anim + if (animTimeElapsed < 1000) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_ST_T_SB_1_W: - if ( ps->torsoAnimTimer < 950 ) - {//end of anim + if (ps->torsoAnimTimer < 950) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 650 ) - {//beginning of anim + } else if (animTimeElapsed < 650) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_S_S_SB_1_W: - if ( saberNum != 0 ) - {//only right hand saber does damage in this suberbreak + if (saberNum != 0) { // only right hand saber does damage in this suberbreak return FORCE_LEVEL_0; } - if ( ps->torsoAnimTimer < 900 ) - {//end of anim + if (ps->torsoAnimTimer < 900) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 450 ) - {//beginning of anim + } else if (animTimeElapsed < 450) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_S_T_SB_1_W: - if ( saberNum != 0 ) - {//only right hand saber does damage in this suberbreak + if (saberNum != 0) { // only right hand saber does damage in this suberbreak return FORCE_LEVEL_0; } - if ( ps->torsoAnimTimer < 250 ) - {//end of anim + if (ps->torsoAnimTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 150 ) - {//beginning of anim + } else if (animTimeElapsed < 150) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -1015,17 +882,14 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) return FORCE_LEVEL_5; break; case BOTH_LK_ST_DL_T_SB_1_W: - //special suberbreak - doesn't kill, just kicks them backwards + // special suberbreak - doesn't kill, just kicks them backwards return FORCE_LEVEL_0; break; case BOTH_LK_ST_ST_S_SB_1_W: case BOTH_LK_ST_S_S_SB_1_W: - if ( ps->torsoAnimTimer < 800 ) - {//end of anim + if (ps->torsoAnimTimer < 800) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 350 ) - {//beginning of anim + } else if (animTimeElapsed < 350) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -1034,29 +898,21 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) case BOTH_LK_ST_S_T_SB_1_W: return FORCE_LEVEL_5; break; -//===SABERLOCK SUPERBREAKS START=========================================================================== + //===SABERLOCK SUPERBREAKS START=========================================================================== case BOTH_HANG_ATTACK: - //FIME: break up - if ( ps->torsoAnimTimer < 1000 ) - {//end of anim + // FIME: break up + if (ps->torsoAnimTimer < 1000) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; - } - else - {//sweet spot + } else { // sweet spot return FORCE_LEVEL_5; } break; case BOTH_ROLL_STAB: - if ( animTimeElapsed > 400 ) - {//end of anim + if (animTimeElapsed > 400) { // end of anim return FORCE_LEVEL_0; - } - else - { + } else { return FORCE_LEVEL_3; } break; @@ -1064,10 +920,8 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum ) return FORCE_LEVEL_0; } -qboolean PM_InAnimForSaberMove( int anim, int saberMove ) -{ - switch ( anim ) - {//special case anims +qboolean PM_InAnimForSaberMove(int anim, int saberMove) { + switch (anim) { // special case anims case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -1080,8 +934,8 @@ qboolean PM_InAnimForSaberMove( int anim, int saberMove ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_SPINATTACK6: @@ -1138,69 +992,55 @@ qboolean PM_InAnimForSaberMove( int anim, int saberMove ) case BOTH_HANG_ATTACK: return qtrue; } - if ( PM_SaberDrawPutawayAnim( anim ) ) - { - if ( saberMove == LS_DRAW || saberMove == LS_PUTAWAY ) - { + if (PM_SaberDrawPutawayAnim(anim)) { + if (saberMove == LS_DRAW || saberMove == LS_PUTAWAY) { return qtrue; } return qfalse; - } - else if ( PM_SaberStanceAnim( anim ) ) - { - if ( saberMove == LS_READY ) - { + } else if (PM_SaberStanceAnim(anim)) { + if (saberMove == LS_READY) { return qtrue; } return qfalse; } - int animLevel = PM_AnimLevelForSaberAnim( anim ); - if ( animLevel <= 0 ) - {//NOTE: this will always return false for the ready poses and putaway/draw... + int animLevel = PM_AnimLevelForSaberAnim(anim); + if (animLevel <= 0) { // NOTE: this will always return false for the ready poses and putaway/draw... return qfalse; } - //drop the anim to the first level and start the checks there - anim -= (animLevel-FORCE_LEVEL_1)*SABER_ANIM_GROUP_SIZE; - //check level 1 - if ( anim == saberMoveData[saberMove].animToUse ) - { + // drop the anim to the first level and start the checks there + anim -= (animLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + // check level 1 + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 2 + // check level 2 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 3 + // check level 3 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 4 + // check level 4 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 5 + // check level 5 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - if ( anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR ) - {//parries, knockaways and broken parries - return (qboolean)(anim==saberMoveData[saberMove].animToUse); + if (anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR) { // parries, knockaways and broken parries + return (qboolean)(anim == saberMoveData[saberMove].animToUse); } return qfalse; } -qboolean PM_SaberInIdle( int move ) -{ - switch ( move ) - { +qboolean PM_SaberInIdle(int move) { + switch (move) { case LS_NONE: case LS_READY: case LS_DRAW: @@ -1210,10 +1050,8 @@ qboolean PM_SaberInIdle( int move ) } return qfalse; } -qboolean PM_SaberInSpecialAttack( int anim ) -{ - switch ( anim ) - { +qboolean PM_SaberInSpecialAttack(int anim) { + switch (anim) { case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -1226,8 +1064,8 @@ qboolean PM_SaberInSpecialAttack( int anim ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_SPINATTACK6: @@ -1287,22 +1125,17 @@ qboolean PM_SaberInSpecialAttack( int anim ) return qfalse; } -qboolean PM_SaberInAttackPure( int move ) -{ - if ( move >= LS_A_TL2BR && move <= LS_A_T2B ) - { +qboolean PM_SaberInAttackPure(int move) { + if (move >= LS_A_TL2BR && move <= LS_A_T2B) { return qtrue; } return qfalse; } -qboolean PM_SaberInAttack( int move ) -{ - if ( move >= LS_A_TL2BR && move <= LS_A_T2B ) - { +qboolean PM_SaberInAttack(int move) { + if (move >= LS_A_TL2BR && move <= LS_A_T2B) { return qtrue; } - switch ( move ) - { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -1359,107 +1192,79 @@ qboolean PM_SaberInAttack( int move ) } return qfalse; } -qboolean PM_SaberInTransition( int move ) -{ - if ( move >= LS_T1_BR__R && move <= LS_T1_BL__L ) - { +qboolean PM_SaberInTransition(int move) { + if (move >= LS_T1_BR__R && move <= LS_T1_BL__L) { return qtrue; } return qfalse; } -qboolean PM_SaberInStart( int move ) -{ - if ( move >= LS_S_TL2BR && move <= LS_S_T2B ) - { +qboolean PM_SaberInStart(int move) { + if (move >= LS_S_TL2BR && move <= LS_S_T2B) { return qtrue; } return qfalse; } -qboolean PM_SaberInReturn( int move ) -{ - if ( move >= LS_R_TL2BR && move <= LS_R_T2B ) - { +qboolean PM_SaberInReturn(int move) { + if (move >= LS_R_TL2BR && move <= LS_R_T2B) { return qtrue; } return qfalse; } -qboolean PM_SaberInTransitionAny( int move ) -{ - if ( PM_SaberInStart( move ) ) - { +qboolean PM_SaberInTransitionAny(int move) { + if (PM_SaberInStart(move)) { return qtrue; - } - else if ( PM_SaberInTransition( move ) ) - { + } else if (PM_SaberInTransition(move)) { return qtrue; - } - else if ( PM_SaberInReturn( move ) ) - { + } else if (PM_SaberInReturn(move)) { return qtrue; } return qfalse; } -qboolean PM_SaberInBounce( int move ) -{ - if ( move >= LS_B1_BR && move <= LS_B1_BL ) - { +qboolean PM_SaberInBounce(int move) { + if (move >= LS_B1_BR && move <= LS_B1_BL) { return qtrue; } - if ( move >= LS_D1_BR && move <= LS_D1_BL ) - { + if (move >= LS_D1_BR && move <= LS_D1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInBrokenParry( int move ) -{ - if ( move >= LS_V1_BR && move <= LS_V1_B_ ) - { +qboolean PM_SaberInBrokenParry(int move) { + if (move >= LS_V1_BR && move <= LS_V1_B_) { return qtrue; } - if ( move >= LS_H1_T_ && move <= LS_H1_BL ) - { + if (move >= LS_H1_T_ && move <= LS_H1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInDeflect( int move ) -{ - if ( move >= LS_D1_BR && move <= LS_D1_B_ ) - { +qboolean PM_SaberInDeflect(int move) { + if (move >= LS_D1_BR && move <= LS_D1_B_) { return qtrue; } return qfalse; } -qboolean PM_SaberInParry( int move ) -{ - if ( move >= LS_PARRY_UP && move <= LS_PARRY_LL ) - { +qboolean PM_SaberInParry(int move) { + if (move >= LS_PARRY_UP && move <= LS_PARRY_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInKnockaway( int move ) -{ - if ( move >= LS_K1_T_ && move <= LS_K1_BL ) - { +qboolean PM_SaberInKnockaway(int move) { + if (move >= LS_K1_T_ && move <= LS_K1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInReflect( int move ) -{ - if ( move >= LS_REFLECT_UP && move <= LS_REFLECT_LL ) - { +qboolean PM_SaberInReflect(int move) { + if (move >= LS_REFLECT_UP && move <= LS_REFLECT_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInSpecial( int move ) -{ - switch( move ) - { +qboolean PM_SaberInSpecial(int move) { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -1516,10 +1321,8 @@ qboolean PM_SaberInSpecial( int move ) return qfalse; } -qboolean PM_KickMove( int move ) -{ - switch( move ) - { +qboolean PM_KickMove(int move) { + switch (move) { case LS_KICK_F: case LS_KICK_B: case LS_KICK_R: @@ -1537,12 +1340,9 @@ qboolean PM_KickMove( int move ) return qfalse; } -qboolean PM_SaberCanInterruptMove( int move, int anim ) -{ - if ( PM_InAnimForSaberMove( anim, move ) ) - { - switch( move ) - { +qboolean PM_SaberCanInterruptMove(int move, int anim) { + if (PM_InAnimForSaberMove(anim, move)) { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -1587,45 +1387,35 @@ qboolean PM_SaberCanInterruptMove( int move, int anim ) return qfalse; } - if ( PM_SaberInAttackPure( move ) ) - { + if (PM_SaberInAttackPure(move)) { return qfalse; } - if ( PM_SaberInStart( move ) ) - { + if (PM_SaberInStart(move)) { return qfalse; } - if ( PM_SaberInTransition( move ) ) - { + if (PM_SaberInTransition(move)) { return qfalse; } - if ( PM_SaberInBounce( move ) ) - { + if (PM_SaberInBounce(move)) { return qfalse; } - if ( PM_SaberInBrokenParry( move ) ) - { + if (PM_SaberInBrokenParry(move)) { return qfalse; } - if ( PM_SaberInDeflect( move ) ) - { + if (PM_SaberInDeflect(move)) { return qfalse; } - if ( PM_SaberInParry( move ) ) - { + if (PM_SaberInParry(move)) { return qfalse; } - if ( PM_SaberInKnockaway( move ) ) - { + if (PM_SaberInKnockaway(move)) { return qfalse; } - if ( PM_SaberInReflect( move ) ) - { + if (PM_SaberInReflect(move)) { return qfalse; } } - switch ( anim ) - { + switch (anim) { case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -1638,8 +1428,8 @@ qboolean PM_SaberCanInterruptMove( int move, int anim ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_SPINATTACK6: @@ -1691,13 +1481,11 @@ qboolean PM_SaberCanInterruptMove( int move, int anim ) return qtrue; } -saberMoveName_t PM_BrokenParryForAttack( int move ) -{ - //Our attack was knocked away by a knockaway parry - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( saberMoveData[move].startQuad ) - { +saberMoveName_t PM_BrokenParryForAttack(int move) { + // Our attack was knocked away by a knockaway parry + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (saberMoveData[move].startQuad) { case Q_B: return LS_V1_B_; break; @@ -1726,20 +1514,15 @@ saberMoveName_t PM_BrokenParryForAttack( int move ) return LS_NONE; } -saberMoveName_t PM_BrokenParryForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { +saberMoveName_t PM_BrokenParryForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { case LS_PARRY_UP: - //Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back - if ( Q_irand( 0, 1 ) ) - { + // Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back + if (Q_irand(0, 1)) { return LS_H1_B_; - } - else - { + } else { return LS_H1_T_; } break; @@ -1756,42 +1539,38 @@ saberMoveName_t PM_BrokenParryForParry( int move ) return LS_H1_BL; break; case LS_READY: - return LS_H1_B_;//??? + return LS_H1_B_; //??? break; } return LS_NONE; } -saberMoveName_t PM_KnockawayForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { - case BLOCKED_TOP://LS_PARRY_UP: - return LS_K1_T_;//push up +saberMoveName_t PM_KnockawayForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { + case BLOCKED_TOP: // LS_PARRY_UP: + return LS_K1_T_; // push up break; - case BLOCKED_UPPER_RIGHT://LS_PARRY_UR: - default://case LS_READY: - return LS_K1_TR;//push up, slightly to right + case BLOCKED_UPPER_RIGHT: // LS_PARRY_UR: + default: // case LS_READY: + return LS_K1_TR; // push up, slightly to right break; - case BLOCKED_UPPER_LEFT://LS_PARRY_UL: - return LS_K1_TL;//push up and to left + case BLOCKED_UPPER_LEFT: // LS_PARRY_UL: + return LS_K1_TL; // push up and to left break; - case BLOCKED_LOWER_RIGHT://LS_PARRY_LR: - return LS_K1_BR;//push down and to left + case BLOCKED_LOWER_RIGHT: // LS_PARRY_LR: + return LS_K1_BR; // push down and to left break; - case BLOCKED_LOWER_LEFT://LS_PARRY_LL: - return LS_K1_BL;//push down and to right + case BLOCKED_LOWER_LEFT: // LS_PARRY_LL: + return LS_K1_BL; // push down and to right break; } - //return LS_NONE; + // return LS_NONE; } -saberMoveName_t PM_SaberBounceForAttack( int move ) -{ - switch ( saberMoveData[move].startQuad ) - { +saberMoveName_t PM_SaberBounceForAttack(int move) { + switch (saberMoveData[move].startQuad) { case Q_B: case Q_BR: return LS_B1_BR; @@ -1818,10 +1597,8 @@ saberMoveName_t PM_SaberBounceForAttack( int move ) return LS_NONE; } -saberMoveName_t PM_AttackMoveForQuad( int quad ) -{ - switch ( quad ) - { +saberMoveName_t PM_AttackMoveForQuad(int quad) { + switch (quad) { case Q_B: case Q_BR: return LS_A_BR2TL; @@ -1848,143 +1625,122 @@ saberMoveName_t PM_AttackMoveForQuad( int quad ) return LS_NONE; } -int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = -{ - { - 0,//Q_BR,Q_BR, - 45,//Q_BR,Q_R, - 90,//Q_BR,Q_TR, - 135,//Q_BR,Q_T, - 180,//Q_BR,Q_TL, - 215,//Q_BR,Q_L, - 270,//Q_BR,Q_BL, - 45,//Q_BR,Q_B, - }, - { - 45,//Q_R,Q_BR, - 0,//Q_R,Q_R, - 45,//Q_R,Q_TR, - 90,//Q_R,Q_T, - 135,//Q_R,Q_TL, - 180,//Q_R,Q_L, - 215,//Q_R,Q_BL, - 90,//Q_R,Q_B, - }, - { - 90,//Q_TR,Q_BR, - 45,//Q_TR,Q_R, - 0,//Q_TR,Q_TR, - 45,//Q_TR,Q_T, - 90,//Q_TR,Q_TL, - 135,//Q_TR,Q_L, - 180,//Q_TR,Q_BL, - 135,//Q_TR,Q_B, - }, - { - 135,//Q_T,Q_BR, - 90,//Q_T,Q_R, - 45,//Q_T,Q_TR, - 0,//Q_T,Q_T, - 45,//Q_T,Q_TL, - 90,//Q_T,Q_L, - 135,//Q_T,Q_BL, - 180,//Q_T,Q_B, - }, - { - 180,//Q_TL,Q_BR, - 135,//Q_TL,Q_R, - 90,//Q_TL,Q_TR, - 45,//Q_TL,Q_T, - 0,//Q_TL,Q_TL, - 45,//Q_TL,Q_L, - 90,//Q_TL,Q_BL, - 135,//Q_TL,Q_B, - }, - { - 215,//Q_L,Q_BR, - 180,//Q_L,Q_R, - 135,//Q_L,Q_TR, - 90,//Q_L,Q_T, - 45,//Q_L,Q_TL, - 0,//Q_L,Q_L, - 45,//Q_L,Q_BL, - 90,//Q_L,Q_B, - }, - { - 270,//Q_BL,Q_BR, - 215,//Q_BL,Q_R, - 180,//Q_BL,Q_TR, - 135,//Q_BL,Q_T, - 90,//Q_BL,Q_TL, - 45,//Q_BL,Q_L, - 0,//Q_BL,Q_BL, - 45,//Q_BL,Q_B, - }, - { - 45,//Q_B,Q_BR, - 90,//Q_B,Q_R, - 135,//Q_B,Q_TR, - 180,//Q_B,Q_T, - 135,//Q_B,Q_TL, - 90,//Q_B,Q_L, - 45,//Q_B,Q_BL, - 0//Q_B,Q_B, - } -}; - -int PM_SaberAttackChainAngle( int move1, int move2 ) -{ - if ( move1 == -1 || move2 == -1 ) - { +int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = {{ + 0, // Q_BR,Q_BR, + 45, // Q_BR,Q_R, + 90, // Q_BR,Q_TR, + 135, // Q_BR,Q_T, + 180, // Q_BR,Q_TL, + 215, // Q_BR,Q_L, + 270, // Q_BR,Q_BL, + 45, // Q_BR,Q_B, + }, + { + 45, // Q_R,Q_BR, + 0, // Q_R,Q_R, + 45, // Q_R,Q_TR, + 90, // Q_R,Q_T, + 135, // Q_R,Q_TL, + 180, // Q_R,Q_L, + 215, // Q_R,Q_BL, + 90, // Q_R,Q_B, + }, + { + 90, // Q_TR,Q_BR, + 45, // Q_TR,Q_R, + 0, // Q_TR,Q_TR, + 45, // Q_TR,Q_T, + 90, // Q_TR,Q_TL, + 135, // Q_TR,Q_L, + 180, // Q_TR,Q_BL, + 135, // Q_TR,Q_B, + }, + { + 135, // Q_T,Q_BR, + 90, // Q_T,Q_R, + 45, // Q_T,Q_TR, + 0, // Q_T,Q_T, + 45, // Q_T,Q_TL, + 90, // Q_T,Q_L, + 135, // Q_T,Q_BL, + 180, // Q_T,Q_B, + }, + { + 180, // Q_TL,Q_BR, + 135, // Q_TL,Q_R, + 90, // Q_TL,Q_TR, + 45, // Q_TL,Q_T, + 0, // Q_TL,Q_TL, + 45, // Q_TL,Q_L, + 90, // Q_TL,Q_BL, + 135, // Q_TL,Q_B, + }, + { + 215, // Q_L,Q_BR, + 180, // Q_L,Q_R, + 135, // Q_L,Q_TR, + 90, // Q_L,Q_T, + 45, // Q_L,Q_TL, + 0, // Q_L,Q_L, + 45, // Q_L,Q_BL, + 90, // Q_L,Q_B, + }, + { + 270, // Q_BL,Q_BR, + 215, // Q_BL,Q_R, + 180, // Q_BL,Q_TR, + 135, // Q_BL,Q_T, + 90, // Q_BL,Q_TL, + 45, // Q_BL,Q_L, + 0, // Q_BL,Q_BL, + 45, // Q_BL,Q_B, + }, + { + 45, // Q_B,Q_BR, + 90, // Q_B,Q_R, + 135, // Q_B,Q_TR, + 180, // Q_B,Q_T, + 135, // Q_B,Q_TL, + 90, // Q_B,Q_L, + 45, // Q_B,Q_BL, + 0 // Q_B,Q_B, + }}; + +int PM_SaberAttackChainAngle(int move1, int move2) { + if (move1 == -1 || move2 == -1) { return -1; } return saberMoveTransitionAngle[saberMoveData[move1].endQuad][saberMoveData[move2].startQuad]; } -qboolean PM_SaberKataDone( int curmove = LS_NONE, int newmove = LS_NONE ) -{ - if ( pm->ps->forceRageRecoveryTime > level.time ) - {//rage recovery, only 1 swing at a time (tired) - if ( pm->ps->saberAttackChainCount > 0 ) - {//swung once +qboolean PM_SaberKataDone(int curmove = LS_NONE, int newmove = LS_NONE) { + if (pm->ps->forceRageRecoveryTime > level.time) { // rage recovery, only 1 swing at a time (tired) + if (pm->ps->saberAttackChainCount > 0) { // swung once return qtrue; - } - else - {//allow one attack + } else { // allow one attack return qfalse; } - } - else if ( (pm->ps->forcePowersActive&(1<ps->forcePowersActive & (1 << FP_RAGE))) { // infinite chaining when raged return qfalse; - } - else if ( pm->ps->saber[0].maxChain == -1 ) - { + } else if (pm->ps->saber[0].maxChain == -1) { return qfalse; - } - else if ( pm->ps->saber[0].maxChain != 0 ) - { - if ( pm->ps->saberAttackChainCount >= pm->ps->saber[0].maxChain ) - { + } else if (pm->ps->saber[0].maxChain != 0) { + if (pm->ps->saberAttackChainCount >= pm->ps->saber[0].maxChain) { return qtrue; - } - else - { + } else { return qfalse; } } - if ( pm->ps->saberAnimLevel == SS_DESANN || pm->ps->saberAnimLevel == SS_TAVION ) - {//desann and tavion can link up as many attacks as they want + if (pm->ps->saberAnimLevel == SS_DESANN || pm->ps->saberAnimLevel == SS_TAVION) { // desann and tavion can link up as many attacks as they want return qfalse; } - //FIXME: instead of random, apply some sort of logical conditions to whether or + // FIXME: instead of random, apply some sort of logical conditions to whether or // not you can chain? Like if you were completely missed, you can't chain as much, or...? // And/Or based on FP_SABER_OFFENSE level? So number of attacks you can chain // increases with your FP_SABER_OFFENSE skill? - if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - //TEMP: for now, let staff attacks infinitely chain + if (pm->ps->saberAnimLevel == SS_STAFF) { + // TEMP: for now, let staff attacks infinitely chain return qfalse; /* if ( pm->ps->saberAttackChainCount > Q_irand( 3, 4 ) ) @@ -2017,94 +1773,61 @@ qboolean PM_SaberKataDone( int curmove = LS_NONE, int newmove = LS_NONE ) } } */ - } - else if ( pm->ps->saberAnimLevel == SS_DUAL ) - { - //TEMP: for now, let staff attacks infinitely chain + } else if (pm->ps->saberAnimLevel == SS_DUAL) { + // TEMP: for now, let staff attacks infinitely chain return qfalse; - } - else if ( pm->ps->saberAnimLevel == FORCE_LEVEL_3 ) - { - if ( curmove == LS_NONE || newmove == LS_NONE ) - { - if ( pm->ps->saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > Q_irand( 0, 1 ) ) - { + } else if (pm->ps->saberAnimLevel == FORCE_LEVEL_3) { + if (curmove == LS_NONE || newmove == LS_NONE) { + if (pm->ps->saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > Q_irand(0, 1)) { return qtrue; } - } - else if ( pm->ps->saberAttackChainCount > Q_irand( 2, 3 ) ) - { + } else if (pm->ps->saberAttackChainCount > Q_irand(2, 3)) { return qtrue; - } - else if ( pm->ps->saberAttackChainCount > 0 ) - { - int chainAngle = PM_SaberAttackChainAngle( curmove, newmove ); - if ( chainAngle < 135 || chainAngle > 215 ) - {//if trying to chain to a move that doesn't continue the momentum + } else if (pm->ps->saberAttackChainCount > 0) { + int chainAngle = PM_SaberAttackChainAngle(curmove, newmove); + if (chainAngle < 135 || chainAngle > 215) { // if trying to chain to a move that doesn't continue the momentum return qtrue; - } - else if ( chainAngle == 180 ) - {//continues the momentum perfectly, allow it to chain 66% of the time - if ( pm->ps->saberAttackChainCount > 1 ) - { + } else if (chainAngle == 180) { // continues the momentum perfectly, allow it to chain 66% of the time + if (pm->ps->saberAttackChainCount > 1) { return qtrue; } - } - else - {//would continue the movement somewhat, 50% chance of continuing - if ( pm->ps->saberAttackChainCount > 2 ) - { + } else { // would continue the movement somewhat, 50% chance of continuing + if (pm->ps->saberAttackChainCount > 2) { return qtrue; } } } - } - else - {//FIXME: have chainAngle influence fast and medium chains as well? - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == SS_DUAL) - && pm->ps->saberAttackChainCount > Q_irand( 2, 5 ) ) - { + } else { // FIXME: have chainAngle influence fast and medium chains as well? + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == SS_DUAL) && pm->ps->saberAttackChainCount > Q_irand(2, 5)) { return qtrue; } } return qfalse; } -qboolean PM_CheckEnemyInBack( float backCheckDist ) -{ - if ( !pm->gent || !pm->gent->client ) - { +qboolean PM_CheckEnemyInBack(float backCheckDist) { + if (!pm->gent || !pm->gent->client) { return qfalse; } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && !g_saberAutoAim->integer && pm->cmd.forwardmove >= 0 ) - {//don't auto-backstab + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && !g_saberAutoAim->integer && pm->cmd.forwardmove >= 0) { // don't auto-backstab return qfalse; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//only when on ground + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // only when on ground return qfalse; } - trace_t trace; - vec3_t end, fwd, fwdAngles = {0,pm->ps->viewangles[YAW],0}; + trace_t trace; + vec3_t end, fwd, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( pm->ps->origin, -backCheckDist, fwd, end ); + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(pm->ps->origin, -backCheckDist, fwd, end); - pm->trace( &trace, pm->ps->origin, vec3_origin, vec3_origin, end, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f && trace.entityNum < ENTITYNUM_WORLD ) - { + pm->trace(&trace, pm->ps->origin, vec3_origin, vec3_origin, end, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f && trace.entityNum < ENTITYNUM_WORLD) { gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt - && traceEnt->health > 0 - && traceEnt->client - && traceEnt->client->playerTeam == pm->gent->client->enemyTeam - && traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//player - if ( pm->gent ) - {//set player enemy to traceEnt so he auto-aims at him + if (traceEnt && traceEnt->health > 0 && traceEnt->client && traceEnt->client->playerTeam == pm->gent->client->enemyTeam && + traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // player + if (pm->gent) { // set player enemy to traceEnt so he auto-aims at him pm->gent->enemy = traceEnt; } } @@ -2114,92 +1837,60 @@ qboolean PM_CheckEnemyInBack( float backCheckDist ) return qfalse; } -saberMoveName_t PM_PickBackStab( void ) -{ - if ( !pm->gent || !pm->gent->client ) - { +saberMoveName_t PM_PickBackStab(void) { + if (!pm->gent || !pm->gent->client) { return LS_READY; } - if ( pm->ps->dualSabers - && pm->ps->saber[1].Active() ) - { - if ( pm->ps->pm_flags & PMF_DUCKED ) - { + if (pm->ps->dualSabers && pm->ps->saber[1].Active()) { + if (pm->ps->pm_flags & PMF_DUCKED) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } } - if ( pm->gent->client->ps.saberAnimLevel == SS_TAVION ) - { + if (pm->gent->client->ps.saberAnimLevel == SS_TAVION) { return LS_A_BACKSTAB; - } - else if ( pm->gent->client->ps.saberAnimLevel == SS_DESANN ) - { - if ( pm->ps->saberMove == LS_READY || !Q_irand( 0, 3 ) ) - { + } else if (pm->gent->client->ps.saberAnimLevel == SS_DESANN) { + if (pm->ps->saberMove == LS_READY || !Q_irand(0, 3)) { return LS_A_BACKSTAB; - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - { + } else if (pm->ps->pm_flags & PMF_DUCKED) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } - } - else if ( pm->ps->saberAnimLevel == FORCE_LEVEL_2 - || pm->ps->saberAnimLevel == SS_DUAL ) - {//using medium attacks or dual sabers - if ( pm->ps->pm_flags & PMF_DUCKED ) - { + } else if (pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == SS_DUAL) { // using medium attacks or dual sabers + if (pm->ps->pm_flags & PMF_DUCKED) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } - } - else - { + } else { return LS_A_BACKSTAB; } } -saberMoveName_t PM_CheckStabDown( void ) -{ - if ( !pm->gent || !pm->gent->enemy || !pm->gent->enemy->client ) - { +saberMoveName_t PM_CheckStabDown(void) { + if (!pm->gent || !pm->gent->enemy || !pm->gent->enemy->client) { return LS_NONE; } - if ( (pm->ps->saber[0].saberFlags&SFL_NO_STABDOWN) ) - { + if ((pm->ps->saber[0].saberFlags & SFL_NO_STABDOWN)) { return LS_NONE; } - if ( pm->ps->dualSabers - && (pm->ps->saber[1].saberFlags&SFL_NO_STABDOWN) ) - { + if (pm->ps->dualSabers && (pm->ps->saber[1].saberFlags & SFL_NO_STABDOWN)) { return LS_NONE; } - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingKataAttack( pm->gent, &pm->cmd ) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//want to try a special + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingKataAttack(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // want to try a special return LS_NONE; } } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//player - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE )//in air - {//sorry must be on ground (or have just jumped) - if ( level.time-pm->ps->lastOnGround <= 50 && (pm->ps->pm_flags&PMF_JUMPING) ) - {//just jumped, it's okay - } - else - { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // player + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) // in air + { // sorry must be on ground (or have just jumped) + if (level.time - pm->ps->lastOnGround <= 50 && (pm->ps->pm_flags & PMF_JUMPING)) { // just jumped, it's okay + } else { return LS_NONE; } } @@ -2219,141 +1910,106 @@ saberMoveName_t PM_CheckStabDown( void ) */ pm->ps->velocity[2] = 0; pm->cmd.upmove = 0; - } - else if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - {//NPC - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE )//in air - {//sorry must be on ground (or have just jumped) - if ( level.time-pm->ps->lastOnGround <= 250 && (pm->ps->pm_flags&PMF_JUMPING) ) - {//just jumped, it's okay - } - else - { + } else if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { // NPC + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) // in air + { // sorry must be on ground (or have just jumped) + if (level.time - pm->ps->lastOnGround <= 250 && (pm->ps->pm_flags & PMF_JUMPING)) { // just jumped, it's okay + } else { return LS_NONE; } } - if ( !pm->gent->NPC ) - {//wtf??? + if (!pm->gent->NPC) { // wtf??? return LS_NONE; } - if ( Q_irand( 0, RANK_CAPTAIN ) > pm->gent->NPC->rank ) - {//lower ranks do this less often + if (Q_irand(0, RANK_CAPTAIN) > pm->gent->NPC->rank) { // lower ranks do this less often return LS_NONE; } } vec3_t enemyDir, faceFwd, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( facingAngles, faceFwd, NULL, NULL ); - VectorSubtract( pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir ); + AngleVectors(facingAngles, faceFwd, NULL, NULL); + VectorSubtract(pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir); float enemyZDiff = enemyDir[2]; enemyDir[2] = 0; - float enemyHDist = VectorNormalize( enemyDir )-(pm->gent->maxs[0]+pm->gent->enemy->maxs[0]); - float dot = DotProduct( enemyDir, faceFwd ); + float enemyHDist = VectorNormalize(enemyDir) - (pm->gent->maxs[0] + pm->gent->enemy->maxs[0]); + float dot = DotProduct(enemyDir, faceFwd); if ( //(pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) dot > 0.65f //&& enemyHDist >= 32 //was 48 - && enemyHDist <= 164//was 112 - && PM_InKnockDownOnGround( &pm->gent->enemy->client->ps )//still on ground - && !PM_InGetUpNoRoll( &pm->gent->enemy->client->ps )//not getting up yet - && enemyZDiff <= 20 ) - {//guy is on the ground below me, do a top-down attack - if ( pm->gent->enemy->s.number >= MAX_CLIENTS - || !G_ControlledByPlayer( pm->gent->enemy ) ) - {//don't get up while I'm doing this - //stop them from trying to get up for at least another 3 seconds - TIMER_Set( pm->gent->enemy, "noGetUpStraight", 3000 ); - } - //pick the right anim - if ( pm->ps->saberAnimLevel == SS_DUAL - || (pm->ps->dualSabers&&pm->ps->saber[1].Active()) ) - { + && enemyHDist <= 164 // was 112 + && PM_InKnockDownOnGround(&pm->gent->enemy->client->ps) // still on ground + && !PM_InGetUpNoRoll(&pm->gent->enemy->client->ps) // not getting up yet + && enemyZDiff <= 20) { // guy is on the ground below me, do a top-down attack + if (pm->gent->enemy->s.number >= MAX_CLIENTS || !G_ControlledByPlayer(pm->gent->enemy)) { // don't get up while I'm doing this + // stop them from trying to get up for at least another 3 seconds + TIMER_Set(pm->gent->enemy, "noGetUpStraight", 3000); + } + // pick the right anim + if (pm->ps->saberAnimLevel == SS_DUAL || (pm->ps->dualSabers && pm->ps->saber[1].Active())) { return LS_STABDOWN_DUAL; - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { + } else if (pm->ps->saberAnimLevel == SS_STAFF) { return LS_STABDOWN_STAFF; - } - else - { + } else { return LS_STABDOWN; } } return LS_NONE; } -extern saberMoveName_t PM_NPCSaberAttackFromQuad( int quad ); -saberMoveName_t PM_SaberFlipOverAttackMove( void ); -saberMoveName_t PM_AttackForEnemyPos( qboolean allowFB, qboolean allowStabDown ) -{ +extern saberMoveName_t PM_NPCSaberAttackFromQuad(int quad); +saberMoveName_t PM_SaberFlipOverAttackMove(void); +saberMoveName_t PM_AttackForEnemyPos(qboolean allowFB, qboolean allowStabDown) { saberMoveName_t autoMove = LS_INVALID; - if( !pm->gent->enemy ) - { + if (!pm->gent->enemy) { return LS_NONE; } vec3_t enemy_org, enemyDir, faceFwd, faceRight, faceUp, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( facingAngles, faceFwd, faceRight, faceUp ); - //FIXME: predict enemy position? - if ( pm->gent->enemy->client ) - { - //VectorCopy( pm->gent->enemy->currentOrigin, enemy_org ); - //HMM... using this will adjust for bbox size, so let's do that... - vec3_t size; - VectorSubtract( pm->gent->enemy->absmax, pm->gent->enemy->absmin, size ); - VectorMA( pm->gent->enemy->absmin, 0.5, size, enemy_org ); - - VectorSubtract( pm->gent->enemy->client->renderInfo.eyePoint, pm->ps->origin, enemyDir ); - } - else - { - if ( pm->gent->enemy->bmodel && VectorCompare( vec3_origin, pm->gent->enemy->currentOrigin ) ) - {//a brush model without an origin brush - vec3_t size; - VectorSubtract( pm->gent->enemy->absmax, pm->gent->enemy->absmin, size ); - VectorMA( pm->gent->enemy->absmin, 0.5, size, enemy_org ); - } - else - { - VectorCopy( pm->gent->enemy->currentOrigin, enemy_org ); - } - VectorSubtract( enemy_org, pm->ps->origin, enemyDir ); + AngleVectors(facingAngles, faceFwd, faceRight, faceUp); + // FIXME: predict enemy position? + if (pm->gent->enemy->client) { + // VectorCopy( pm->gent->enemy->currentOrigin, enemy_org ); + // HMM... using this will adjust for bbox size, so let's do that... + vec3_t size; + VectorSubtract(pm->gent->enemy->absmax, pm->gent->enemy->absmin, size); + VectorMA(pm->gent->enemy->absmin, 0.5, size, enemy_org); + + VectorSubtract(pm->gent->enemy->client->renderInfo.eyePoint, pm->ps->origin, enemyDir); + } else { + if (pm->gent->enemy->bmodel && VectorCompare(vec3_origin, pm->gent->enemy->currentOrigin)) { // a brush model without an origin brush + vec3_t size; + VectorSubtract(pm->gent->enemy->absmax, pm->gent->enemy->absmin, size); + VectorMA(pm->gent->enemy->absmin, 0.5, size, enemy_org); + } else { + VectorCopy(pm->gent->enemy->currentOrigin, enemy_org); + } + VectorSubtract(enemy_org, pm->ps->origin, enemyDir); } float enemyZDiff = enemyDir[2]; - float enemyDist = VectorNormalize( enemyDir ); - float dot = DotProduct( enemyDir, faceFwd ); - if ( dot > 0 ) - {//enemy is in front - if ( allowStabDown ) - {//okay to try this + float enemyDist = VectorNormalize(enemyDir); + float dot = DotProduct(enemyDir, faceFwd); + if (dot > 0) { // enemy is in front + if (allowStabDown) { // okay to try this saberMoveName_t stabDownMove = PM_CheckStabDown(); - if ( stabDownMove != LS_NONE ) - { + if (stabDownMove != LS_NONE) { return stabDownMove; } } - if ( (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) - && dot > 0.65f - && enemyDist <= 64 && pm->gent->enemy->client - && (enemyZDiff <= 20 || PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) || PM_CrouchAnim( pm->gent->enemy->client->ps.legsAnim ) ) ) - {//swing down at them + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && dot > 0.65f && enemyDist <= 64 && pm->gent->enemy->client && + (enemyZDiff <= 20 || PM_InKnockDownOnGround(&pm->gent->enemy->client->ps) || + PM_CrouchAnim(pm->gent->enemy->client->ps.legsAnim))) { // swing down at them return LS_A_T2B; } - if ( allowFB ) - {//directly in front anim allowed - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_BACK_ATTACK) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_BACK_ATTACK)) ) - {//okay to do backstabs with this saber - if ( enemyDist > 200 || pm->gent->enemy->health <= 0 ) - {//hmm, look in back for an enemy - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//player should never do this automatically - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//only when on ground - if ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 100 ) ) - { + if (allowFB) { // directly in front anim allowed + if (!(pm->ps->saber[0].saberFlags & SFL_NO_BACK_ATTACK) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_BACK_ATTACK))) { // okay to do backstabs with this saber + if (enemyDist > 200 || pm->gent->enemy->health <= 0) { // hmm, look in back for an enemy + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // player should never do this automatically + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // only when on ground + if (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(100)) { return PM_PickBackStab(); } } @@ -2361,97 +2017,65 @@ saberMoveName_t PM_AttackForEnemyPos( qboolean allowFB, qboolean allowStabDown ) } } } - //this is the default only if they're *right* in front... - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) - || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - {//NPC or player not in 1st person - if ( PM_CheckFlipOverAttackMove( qtrue ) ) - {//enemy must be close and in front + // this is the default only if they're *right* in front... + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { // NPC or player not in 1st person + if (PM_CheckFlipOverAttackMove(qtrue)) { // enemy must be close and in front return PM_SaberFlipOverAttackMove(); } } - if ( PM_CheckLungeAttackMove() ) - {//NPC - autoMove = PM_SaberLungeAttackMove( qtrue ); - } - else - { + if (PM_CheckLungeAttackMove()) { // NPC + autoMove = PM_SaberLungeAttackMove(qtrue); + } else { autoMove = LS_A_T2B; } - } - else - {//pick a random one - if ( Q_irand( 0, 1 ) ) - { + } else { // pick a random one + if (Q_irand(0, 1)) { autoMove = LS_A_TR2BL; - } - else - { + } else { autoMove = LS_A_TL2BR; } } - float dotR = DotProduct( enemyDir, faceRight ); - if ( dotR > 0.35 ) - {//enemy is to far right + float dotR = DotProduct(enemyDir, faceRight); + if (dotR > 0.35) { // enemy is to far right autoMove = LS_A_L2R; - } - else if ( dotR < -0.35 ) - {//far left + } else if (dotR < -0.35) { // far left autoMove = LS_A_R2L; - } - else if ( dotR > 0.15 ) - {//enemy is to near right + } else if (dotR > 0.15) { // enemy is to near right autoMove = LS_A_TR2BL; - } - else if ( dotR < -0.15 ) - {//near left + } else if (dotR < -0.15) { // near left autoMove = LS_A_TL2BR; } - if ( DotProduct( enemyDir, faceUp ) > 0.5 ) - {//enemy is above me - if ( autoMove == LS_A_TR2BL ) - { + if (DotProduct(enemyDir, faceUp) > 0.5) { // enemy is above me + if (autoMove == LS_A_TR2BL) { autoMove = LS_A_BL2TR; - } - else if ( autoMove == LS_A_TL2BR ) - { - autoMove = LS_A_BR2TL; + } else if (autoMove == LS_A_TL2BR) { + autoMove = LS_A_BR2TL; } } - } - else if ( allowFB ) - {//back attack allowed - //if ( !PM_InKnockDown( pm->ps ) ) - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_BACK_ATTACK) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_BACK_ATTACK)) ) - {//okay to do backstabs with this saber - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//only when on ground - if ( !pm->gent->enemy->client || pm->gent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//enemy not a client or is a client and on ground - if ( dot < -0.75f - && enemyDist < 128 - && (pm->ps->saberAnimLevel == SS_FAST || pm->ps->saberAnimLevel == SS_STAFF || (pm->gent->client &&(pm->gent->client->NPC_class == CLASS_TAVION||pm->gent->client->NPC_class == CLASS_ALORA)&&Q_irand(0,2))) ) - {//fast back-stab - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//can't do it while ducked? - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG) ) - {//only fencers and above can do this + } else if (allowFB) { // back attack allowed + // if ( !PM_InKnockDown( pm->ps ) ) + if (!(pm->ps->saber[0].saberFlags & SFL_NO_BACK_ATTACK) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_BACK_ATTACK))) { // okay to do backstabs with this saber + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // only when on ground + if (!pm->gent->enemy->client || + pm->gent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // enemy not a client or is a client and on ground + if (dot < -0.75f && enemyDist < 128 && + (pm->ps->saberAnimLevel == SS_FAST || pm->ps->saberAnimLevel == SS_STAFF || + (pm->gent->client && (pm->gent->client->NPC_class == CLASS_TAVION || pm->gent->client->NPC_class == CLASS_ALORA) && + Q_irand(0, 2)))) { // fast back-stab + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // can't do it while ducked? + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || + (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG)) { // only fencers and above can do this autoMove = LS_A_BACKSTAB; } } - } - else if ( pm->ps->saberAnimLevel != SS_FAST - && pm->ps->saberAnimLevel != SS_STAFF ) - {//higher level back spin-attacks - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( (pm->ps->pm_flags&PMF_DUCKED) || pm->cmd.upmove < 0 ) - { + } else if (pm->ps->saberAnimLevel != SS_FAST && pm->ps->saberAnimLevel != SS_STAFF) { // higher level back spin-attacks + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if ((pm->ps->pm_flags & PMF_DUCKED) || pm->cmd.upmove < 0) { autoMove = LS_A_BACK_CR; - } - else - { + } else { autoMove = LS_A_BACK; } } @@ -2463,89 +2087,69 @@ saberMoveName_t PM_AttackForEnemyPos( qboolean allowFB, qboolean allowStabDown ) return autoMove; } -qboolean PM_InSecondaryStyle( void ) -{ - if ( pm->ps->saber[0].numBlades > 1 - && pm->ps->saber[0].singleBladeStyle - && (pm->ps->saber[0].stylesForbidden&(1<ps->saber[0].singleBladeStyle)) - && pm->ps->saberAnimLevel == pm->ps->saber[0].singleBladeStyle ) - { +qboolean PM_InSecondaryStyle(void) { + if (pm->ps->saber[0].numBlades > 1 && pm->ps->saber[0].singleBladeStyle && (pm->ps->saber[0].stylesForbidden & (1 << pm->ps->saber[0].singleBladeStyle)) && + pm->ps->saberAnimLevel == pm->ps->saber[0].singleBladeStyle) { return qtrue; } - if ( pm->ps->dualSabers - && !pm->ps->saber[1].Active() )//pm->ps->saberAnimLevel != SS_DUAL ) + if (pm->ps->dualSabers && !pm->ps->saber[1].Active()) // pm->ps->saberAnimLevel != SS_DUAL ) { return qtrue; } return qfalse; } -saberMoveName_t PM_SaberLungeAttackMove( qboolean fallbackToNormalLunge ) -{ - G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER_FB ); +saberMoveName_t PM_SaberLungeAttackMove(qboolean fallbackToNormalLunge) { + G_DrainPowerForSpecialMove(pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER_FB); - //see if we have an overridden (or cancelled) lunge move - if ( pm->ps->saber[0].lungeAtkMove != LS_INVALID ) - { - if ( pm->ps->saber[0].lungeAtkMove != LS_NONE ) - { + // see if we have an overridden (or cancelled) lunge move + if (pm->ps->saber[0].lungeAtkMove != LS_INVALID) { + if (pm->ps->saber[0].lungeAtkMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].lungeAtkMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].lungeAtkMove != LS_INVALID ) - { - if ( pm->ps->saber[1].lungeAtkMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].lungeAtkMove != LS_INVALID) { + if (pm->ps->saber[1].lungeAtkMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].lungeAtkMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].lungeAtkMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].lungeAtkMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].lungeAtkMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].lungeAtkMove == LS_NONE) { return LS_NONE; } } - //do normal checks - if ( pm->gent->client->NPC_class == CLASS_ALORA && !Q_irand( 0, 3 ) ) - {//alora NPC + // do normal checks + if (pm->gent->client->NPC_class == CLASS_ALORA && !Q_irand(0, 3)) { // alora NPC return LS_SPINATTACK_ALORA; - } - else - { - if ( pm->ps->dualSabers ) - { + } else { + if (pm->ps->dualSabers) { return LS_SPINATTACK_DUAL; } - switch ( pm->ps->saberAnimLevel ) - { + switch (pm->ps->saberAnimLevel) { case SS_DUAL: return LS_SPINATTACK_DUAL; break; case SS_STAFF: return LS_SPINATTACK; break; - default://normal lunge - if ( fallbackToNormalLunge ) - { + default: // normal lunge + if (fallbackToNormalLunge) { vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the lunge - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity ); + // do the lunge + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); pm->ps->velocity[2] = 50; - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); return LS_A_LUNGE; } @@ -2555,78 +2159,54 @@ saberMoveName_t PM_SaberLungeAttackMove( qboolean fallbackToNormalLunge ) return LS_NONE; } -qboolean PM_CheckLungeAttackMove( void ) -{ - //check to see if it's cancelled? - if ( pm->ps->saber[0].lungeAtkMove == LS_NONE ) - { - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].lungeAtkMove == LS_NONE - || pm->ps->saber[1].lungeAtkMove == LS_INVALID ) - { +qboolean PM_CheckLungeAttackMove(void) { + // check to see if it's cancelled? + if (pm->ps->saber[0].lungeAtkMove == LS_NONE) { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].lungeAtkMove == LS_NONE || pm->ps->saber[1].lungeAtkMove == LS_INVALID) { return qfalse; } - } - else - { + } else { return qfalse; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].lungeAtkMove == LS_NONE ) - { - if ( pm->ps->saber[0].lungeAtkMove == LS_NONE - || pm->ps->saber[0].lungeAtkMove == LS_INVALID ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].lungeAtkMove == LS_NONE) { + if (pm->ps->saber[0].lungeAtkMove == LS_NONE || pm->ps->saber[0].lungeAtkMove == LS_INVALID) { return qfalse; } } } - //do normal checks - if ( pm->ps->saberAnimLevel == SS_FAST//fast - || pm->ps->saberAnimLevel == SS_DUAL//dual - || pm->ps->saberAnimLevel == SS_STAFF //staff - || pm->ps->saberAnimLevel == SS_DESANN - || pm->ps->dualSabers ) - {//alt+back+attack using fast, dual or staff attacks - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPC - if ( pm->cmd.upmove < 0 || (pm->ps->pm_flags&PMF_DUCKED) ) - {//ducking - if ( pm->ps->legsAnim == BOTH_STAND2 - || pm->ps->legsAnim == BOTH_SABERFAST_STANCE - || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE - || pm->ps->legsAnim == BOTH_SABERSTAFF_STANCE - || pm->ps->legsAnim == BOTH_SABERDUAL_STANCE - || (level.time-pm->ps->lastStationary) <= 500 ) - {//standing or just stopped standing - if ( pm->gent - && pm->gent->NPC //NPC - && pm->gent->NPC->rank >= RANK_LT_JG //high rank - && ( pm->gent->NPC->rank == RANK_LT_JG || Q_irand( -3, pm->gent->NPC->rank ) >= RANK_LT_JG )//Q_irand( 0, pm->gent->NPC->rank ) >= RANK_LT_JG ) - && !Q_irand( 0, 3-g_spskill->integer ) ) - {//only fencer and higher can do this - if ( pm->ps->saberAnimLevel == SS_DESANN ) - { - if ( !Q_irand( 0, 4 ) ) - { + // do normal checks + if (pm->ps->saberAnimLevel == SS_FAST // fast + || pm->ps->saberAnimLevel == SS_DUAL // dual + || pm->ps->saberAnimLevel == SS_STAFF // staff + || pm->ps->saberAnimLevel == SS_DESANN || pm->ps->dualSabers) { // alt+back+attack using fast, dual or staff attacks + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPC + if (pm->cmd.upmove < 0 || (pm->ps->pm_flags & PMF_DUCKED)) { // ducking + if (pm->ps->legsAnim == BOTH_STAND2 || pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || + pm->ps->legsAnim == BOTH_SABERSTAFF_STANCE || pm->ps->legsAnim == BOTH_SABERDUAL_STANCE || + (level.time - pm->ps->lastStationary) <= 500) { // standing or just stopped standing + if (pm->gent && pm->gent->NPC // NPC + && pm->gent->NPC->rank >= RANK_LT_JG // high rank + && (pm->gent->NPC->rank == RANK_LT_JG || + Q_irand(-3, pm->gent->NPC->rank) >= RANK_LT_JG) // Q_irand( 0, pm->gent->NPC->rank ) >= RANK_LT_JG ) + && !Q_irand(0, 3 - g_spskill->integer)) { // only fencer and higher can do this + if (pm->ps->saberAnimLevel == SS_DESANN) { + if (!Q_irand(0, 4)) { return qtrue; } - } - else - { + } else { return qtrue; } } } } - } - else - {//player - if ( G_TryingLungeAttack( pm->gent, &pm->cmd ) - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB )/*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB*/ )//have enough force power to pull it off + } else { // player + if (G_TryingLungeAttack(pm->gent, &pm->cmd) && + G_EnoughPowerForSpecialMove( + pm->ps->forcePower, + SABER_ALT_ATTACK_POWER_FB) /*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB*/) // have enough force power to pull it off { return qtrue; } @@ -2636,203 +2216,150 @@ qboolean PM_CheckLungeAttackMove( void ) return qfalse; } -saberMoveName_t PM_SaberJumpForwardAttackMove( void ) -{ - G_DrainPowerForSpecialMove( pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_FB ); +saberMoveName_t PM_SaberJumpForwardAttackMove(void) { + G_DrainPowerForSpecialMove(pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_FB); - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].jumpAtkFwdMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkFwdMove != LS_NONE ) - { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].jumpAtkFwdMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].jumpAtkFwdMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove != LS_INVALID ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove != LS_INVALID) { + if (pm->ps->saber[1].jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].jumpAtkFwdMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE) { return LS_NONE; } } - if ( pm->ps->saberAnimLevel == SS_DUAL - || pm->ps->saberAnimLevel == SS_STAFF ) - { - pm->cmd.upmove = 0;//no jump just yet + if (pm->ps->saberAnimLevel == SS_DUAL || pm->ps->saberAnimLevel == SS_STAFF) { + pm->cmd.upmove = 0; // no jump just yet - if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - if ( Q_irand(0, 1) ) - { + if (pm->ps->saberAnimLevel == SS_STAFF) { + if (Q_irand(0, 1)) { return LS_JUMPATTACK_STAFF_LEFT; - } - else - { + } else { return LS_JUMPATTACK_STAFF_RIGHT; } } return LS_JUMPATTACK_DUAL; - } - else - { + } else { vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 200, pm->ps->velocity ); + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 200, pm->ps->velocity); pm->ps->velocity[2] = 180; - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - PM_AddEvent( EV_JUMP ); - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // FIXME: NPCs yell? + PM_AddEvent(EV_JUMP); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); pm->cmd.upmove = 0; return LS_A_JUMP_T__B_; } } -qboolean PM_CheckJumpForwardAttackMove( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +qboolean PM_CheckJumpForwardAttackMove(void) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return qfalse; } - //check to see if it's cancelled? - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE ) - { - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE - || pm->ps->saber[1].jumpAtkFwdMove == LS_INVALID ) - { + // check to see if it's cancelled? + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE) { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE || pm->ps->saber[1].jumpAtkFwdMove == LS_INVALID) { return qfalse; } - } - else - { + } else { return qfalse; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE ) - { - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE - || pm->ps->saber[0].jumpAtkFwdMove == LS_INVALID ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE) { + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE || pm->ps->saber[0].jumpAtkFwdMove == LS_INVALID) { return qfalse; } } } - //do normal checks + // do normal checks - if ( pm->cmd.forwardmove > 0 //going forward - && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && pm->gent && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=250) //on ground or just jumped (if not player) - ) - { - if ( pm->ps->saberAnimLevel == SS_DUAL - || pm->ps->saberAnimLevel == SS_STAFF ) - {//dual and staff - if ( !PM_SaberInTransitionAny( pm->ps->saberMove ) //not going to/from/between an attack anim - && !PM_SaberInAttack( pm->ps->saberMove ) //not in attack anim - && pm->ps->weaponTime <= 0//not busy - && (pm->cmd.buttons&BUTTON_ATTACK) )//want to attack + if (pm->cmd.forwardmove > 0 // going forward + && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && pm->gent && + !(pm->gent->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 250) // on ground or just jumped (if not player) + ) { + if (pm->ps->saberAnimLevel == SS_DUAL || pm->ps->saberAnimLevel == SS_STAFF) { // dual and staff + if (!PM_SaberInTransitionAny(pm->ps->saberMove) // not going to/from/between an attack anim + && !PM_SaberInAttack(pm->ps->saberMove) // not in attack anim + && pm->ps->weaponTime <= 0 // not busy + && (pm->cmd.buttons & BUTTON_ATTACK)) // want to attack { - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPC - if ( pm->cmd.upmove > 0 || (pm->ps->pm_flags&PMF_JUMPING) )//jumping NPC + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPC + if (pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMPING)) // jumping NPC { - if ( pm->gent - && pm->gent->NPC - && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) - { + if (pm->gent && pm->gent->NPC && (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT)) { return qtrue; } } - } - else - {//PLAYER - if ( G_TryingJumpForwardAttack( pm->gent, &pm->cmd ) - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB ) )//have enough power to attack + } else { // PLAYER + if (G_TryingJumpForwardAttack(pm->gent, &pm->cmd) && + G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB)) // have enough power to attack { return qtrue; } } } } - //check strong - else if ( pm->ps->saberAnimLevel == SS_STRONG //strong style - || pm->ps->saberAnimLevel == SS_DESANN )//desann + // check strong + else if (pm->ps->saberAnimLevel == SS_STRONG // strong style + || pm->ps->saberAnimLevel == SS_DESANN) // desann { if ( //&& !PM_InKnockDown( pm->ps ) !pm->ps->dualSabers - //&& (pm->ps->legsAnim == BOTH_STAND2||pm->ps->legsAnim == BOTH_SABERFAST_STANCE||pm->ps->legsAnim == BOTH_SABERSLOW_STANCE||level.time-pm->ps->lastStationary<=500)//standing or just started moving - ) - {//strong attack: jump-hack + //&& (pm->ps->legsAnim == BOTH_STAND2||pm->ps->legsAnim == BOTH_SABERFAST_STANCE||pm->ps->legsAnim == + //BOTH_SABERSLOW_STANCE||level.time-pm->ps->lastStationary<=500)//standing or just started moving + ) { // strong attack: jump-hack /* if ( pm->ps->legsAnim == BOTH_STAND2 || pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || level.time-pm->ps->lastStationary <= 250 )//standing or just started moving */ - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPC - if ( pm->cmd.upmove > 0 || (pm->ps->pm_flags&PMF_JUMPING) )//NPC jumping + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPC + if (pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMPING)) // NPC jumping { - if ( pm->gent - && pm->gent->NPC - && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) - {//only acrobat or boss and higher can do this - if ( pm->ps->legsAnim == BOTH_STAND2 - || pm->ps->legsAnim == BOTH_SABERFAST_STANCE - || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE - || level.time-pm->ps->lastStationary <= 250 ) - {//standing or just started moving - if ( pm->gent->client - && pm->gent->client->NPC_class == CLASS_DESANN ) - { - if ( !Q_irand( 0, 1 ) ) - { + if (pm->gent && pm->gent->NPC && + (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT)) { // only acrobat or boss and higher can do this + if (pm->ps->legsAnim == BOTH_STAND2 || pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || + level.time - pm->ps->lastStationary <= 250) { // standing or just started moving + if (pm->gent->client && pm->gent->client->NPC_class == CLASS_DESANN) { + if (!Q_irand(0, 1)) { return qtrue; } - } - else - { + } else { return qtrue; } } } } - } - else - {//player - if ( G_TryingJumpForwardAttack( pm->gent, &pm->cmd ) - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB ) ) - { + } else { // player + if (G_TryingJumpForwardAttack(pm->gent, &pm->cmd) && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB)) { return qtrue; } } @@ -2842,185 +2369,140 @@ qboolean PM_CheckJumpForwardAttackMove( void ) return qfalse; } -saberMoveName_t PM_SaberFlipOverAttackMove( void ) -{ - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].jumpAtkFwdMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkFwdMove != LS_NONE ) - { +saberMoveName_t PM_SaberFlipOverAttackMove(void) { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].jumpAtkFwdMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].jumpAtkFwdMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove != LS_INVALID ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove != LS_INVALID) { + if (pm->ps->saber[1].jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].jumpAtkFwdMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE) { return LS_NONE; } } - //FIXME: check above for room enough to jump! - //FIXME: while in this jump, keep velocity[2] at a minimum until the end of the anim + // FIXME: check above for room enough to jump! + // FIXME: while in this jump, keep velocity[2] at a minimum until the end of the anim vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity ); + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); pm->ps->velocity[2] = 250; - //250 is normalized for a standing enemy at your z level, about 64 tall... adjust for actual maxs[2]-mins[2] of enemy and for zdiff in origins - if ( pm->gent && pm->gent->enemy ) - { //go higher for taller enemies - pm->ps->velocity[2] *= (pm->gent->enemy->maxs[2]-pm->gent->enemy->mins[2])/64.0f; - //go higher for enemies higher than you, lower for those lower than you + // 250 is normalized for a standing enemy at your z level, about 64 tall... adjust for actual maxs[2]-mins[2] of enemy and for zdiff in origins + if (pm->gent && pm->gent->enemy) { // go higher for taller enemies + pm->ps->velocity[2] *= (pm->gent->enemy->maxs[2] - pm->gent->enemy->mins[2]) / 64.0f; + // go higher for enemies higher than you, lower for those lower than you float zDiff = pm->gent->enemy->currentOrigin[2] - pm->ps->origin[2]; pm->ps->velocity[2] += (zDiff)*1.5f; - //clamp to decent-looking values - //FIXME: still jump too low sometimes - if ( zDiff <= 0 && pm->ps->velocity[2] < 200 ) - {//if we're on same level, don't let me jump so low, I clip into the ground + // clamp to decent-looking values + // FIXME: still jump too low sometimes + if (zDiff <= 0 && pm->ps->velocity[2] < 200) { // if we're on same level, don't let me jump so low, I clip into the ground pm->ps->velocity[2] = 200; - } - else if ( pm->ps->velocity[2] < 50 ) - { + } else if (pm->ps->velocity[2] < 50) { pm->ps->velocity[2] = 50; - } - else if ( pm->ps->velocity[2] > 400 ) - { + } else if (pm->ps->velocity[2] > 400) { pm->ps->velocity[2] = 400; } } - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - PM_AddEvent( EV_JUMP ); - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // FIXME: NPCs yell? + PM_AddEvent(EV_JUMP); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); pm->cmd.upmove = 0; - //FIXME: don't allow this to land on other people + // FIXME: don't allow this to land on other people - pm->gent->angle = pm->ps->viewangles[YAW];//so we know what yaw we started this at + pm->gent->angle = pm->ps->viewangles[YAW]; // so we know what yaw we started this at - G_DrainPowerForSpecialMove( pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_FB ); + G_DrainPowerForSpecialMove(pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_FB); - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { return LS_A_FLIP_STAB; - } - else - { + } else { return LS_A_FLIP_SLASH; } } -qboolean PM_CheckFlipOverAttackMove( qboolean checkEnemy ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +qboolean PM_CheckFlipOverAttackMove(qboolean checkEnemy) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return qfalse; } - //check to see if it's cancelled? - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE ) - { - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE - || pm->ps->saber[1].jumpAtkFwdMove == LS_INVALID ) - { + // check to see if it's cancelled? + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE) { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE || pm->ps->saber[1].jumpAtkFwdMove == LS_INVALID) { return qfalse; } - } - else - { + } else { return qfalse; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkFwdMove == LS_NONE ) - { - if ( pm->ps->saber[0].jumpAtkFwdMove == LS_NONE - || pm->ps->saber[0].jumpAtkFwdMove == LS_INVALID ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkFwdMove == LS_NONE) { + if (pm->ps->saber[0].jumpAtkFwdMove == LS_NONE || pm->ps->saber[0].jumpAtkFwdMove == LS_INVALID) { return qfalse; } } } - //do normal checks + // do normal checks - if ( (pm->ps->saberAnimLevel == SS_MEDIUM //medium - || pm->ps->saberAnimLevel == SS_TAVION )//tavion - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=250) //on ground or just jumped - ) - { + if ((pm->ps->saberAnimLevel == SS_MEDIUM // medium + || pm->ps->saberAnimLevel == SS_TAVION) // tavion + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && + !(pm->gent->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 250) // on ground or just jumped + ) { qboolean tryMove = qfalse; - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPC - if ( pm->cmd.upmove > 0//want to jump - || (pm->ps->pm_flags&PMF_JUMPING) )//jumping - {//flip over-forward down-attack - if ( (pm->gent->NPC - && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) - && !Q_irand(0, 2) ) )//NPC who can do this, 33% chance - {//only player or acrobat or boss and higher can do this + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPC + if (pm->cmd.upmove > 0 // want to jump + || (pm->ps->pm_flags & PMF_JUMPING)) // jumping + { // flip over-forward down-attack + if ((pm->gent->NPC && (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT) && + !Q_irand(0, 2))) // NPC who can do this, 33% chance + { // only player or acrobat or boss and higher can do this tryMove = qtrue; } } - } - else - {//player - if ( G_TryingJumpForwardAttack( pm->gent, &pm->cmd ) - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB ) )//have enough power + } else { // player + if (G_TryingJumpForwardAttack(pm->gent, &pm->cmd) && + G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB)) // have enough power { - if ( !pm->cmd.rightmove ) - { - if ( pm->ps->legsAnim == BOTH_JUMP1 - || pm->ps->legsAnim == BOTH_FORCEJUMP1 - || pm->ps->legsAnim == BOTH_INAIR1 - || pm->ps->legsAnim == BOTH_FORCEINAIR1 ) - {//in a non-flip forward jump + if (!pm->cmd.rightmove) { + if (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_FORCEJUMP1 || pm->ps->legsAnim == BOTH_INAIR1 || + pm->ps->legsAnim == BOTH_FORCEINAIR1) { // in a non-flip forward jump tryMove = qtrue; } } } } - if ( tryMove ) - { - if ( !checkEnemy ) - {//based just on command input + if (tryMove) { + if (!checkEnemy) { // based just on command input return qtrue; - } - else - {//based on presence of enemy - if ( pm->gent->enemy )//have an enemy + } else { // based on presence of enemy + if (pm->gent->enemy) // have an enemy { - vec3_t fwdAngles = {0,pm->ps->viewangles[YAW],0}; - if ( pm->gent->enemy->health > 0 - && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->gent->enemy->maxs[2] > 12 - && (!pm->gent->enemy->client || !PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) ) - && DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ) < 10000 - && InFront( pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, 0.3f ) ) - {//enemy must be alive, not low to ground, close and in front + vec3_t fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + if (pm->gent->enemy->health > 0 && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->gent->enemy->maxs[2] > 12 && (!pm->gent->enemy->client || !PM_InKnockDownOnGround(&pm->gent->enemy->client->ps)) && + DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin) < 10000 && + InFront(pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, + 0.3f)) { // enemy must be alive, not low to ground, close and in front return qtrue; } } @@ -3031,105 +2513,79 @@ qboolean PM_CheckFlipOverAttackMove( qboolean checkEnemy ) return qfalse; } -saberMoveName_t PM_SaberBackflipAttackMove( void ) -{ - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].jumpAtkBackMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkBackMove != LS_NONE ) - { +saberMoveName_t PM_SaberBackflipAttackMove(void) { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].jumpAtkBackMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkBackMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].jumpAtkBackMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkBackMove != LS_INVALID ) - { - if ( pm->ps->saber[1].jumpAtkBackMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkBackMove != LS_INVALID) { + if (pm->ps->saber[1].jumpAtkBackMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].jumpAtkBackMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].jumpAtkBackMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].jumpAtkBackMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkBackMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkBackMove == LS_NONE) { return LS_NONE; } } - pm->cmd.upmove = 0;//no jump just yet + pm->cmd.upmove = 0; // no jump just yet return LS_A_BACKFLIP_ATK; } -qboolean PM_CheckBackflipAttackMove( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +qboolean PM_CheckBackflipAttackMove(void) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return qfalse; } - //check to see if it's cancelled? - if ( pm->ps->saber[0].jumpAtkBackMove == LS_NONE ) - { - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkBackMove == LS_NONE - || pm->ps->saber[1].jumpAtkBackMove == LS_INVALID ) - { + // check to see if it's cancelled? + if (pm->ps->saber[0].jumpAtkBackMove == LS_NONE) { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkBackMove == LS_NONE || pm->ps->saber[1].jumpAtkBackMove == LS_INVALID) { return qfalse; } - } - else - { + } else { return qfalse; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].jumpAtkBackMove == LS_NONE ) - { - if ( pm->ps->saber[0].jumpAtkBackMove == LS_NONE - || pm->ps->saber[0].jumpAtkBackMove == LS_INVALID ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].jumpAtkBackMove == LS_NONE) { + if (pm->ps->saber[0].jumpAtkBackMove == LS_NONE || pm->ps->saber[0].jumpAtkBackMove == LS_INVALID) { return qfalse; } } } - //do normal checks + // do normal checks - if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->gent && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + if (pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->gent && + !(pm->gent->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one //&& (pm->ps->legsAnim == BOTH_SABERSTAFF_STANCE || level.time-pm->ps->lastStationary<=250)//standing or just started moving - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=250) )//on ground or just jumped (if not player) - { - if ( pm->cmd.forwardmove < 0 //moving backwards - && pm->ps->saberAnimLevel == SS_STAFF //using staff - && (pm->cmd.upmove > 0 || (pm->ps->pm_flags&PMF_JUMPING)) )//jumping - {//jumping backwards and using staff - if ( !PM_SaberInTransitionAny( pm->ps->saberMove ) //not going to/from/between an attack anim - && !PM_SaberInAttack( pm->ps->saberMove ) //not in attack anim - && pm->ps->weaponTime <= 0//not busy - && (pm->cmd.buttons&BUTTON_ATTACK) )//want to attack - {//not already attacking - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPC - if ( pm->gent - && pm->gent->NPC - && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) - {//acrobat or boss and higher can do this + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 250)) // on ground or just jumped (if not player) + { + if (pm->cmd.forwardmove < 0 // moving backwards + && pm->ps->saberAnimLevel == SS_STAFF // using staff + && (pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMPING))) // jumping + { // jumping backwards and using staff + if (!PM_SaberInTransitionAny(pm->ps->saberMove) // not going to/from/between an attack anim + && !PM_SaberInAttack(pm->ps->saberMove) // not in attack anim + && pm->ps->weaponTime <= 0 // not busy + && (pm->cmd.buttons & BUTTON_ATTACK)) // want to attack + { // not already attacking + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPC + if (pm->gent && pm->gent->NPC && + (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT)) { // acrobat or boss and higher can do this return qtrue; } - } - else - {//player + } else { // player return qtrue; } } @@ -3138,65 +2594,54 @@ qboolean PM_CheckBackflipAttackMove( void ) return qfalse; } -saberMoveName_t PM_CheckDualSpinProtect( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +saberMoveName_t PM_CheckDualSpinProtect(void) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return LS_NONE; } - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[0].kataMove != LS_NONE ) - { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].kataMove != LS_INVALID) { + if (pm->ps->saber[0].kataMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].kataMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[1].kataMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove != LS_INVALID) { + if (pm->ps->saber[1].kataMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].kataMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].kataMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].kataMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove == LS_NONE) { return LS_NONE; } } - //do normal checks - if ( pm->ps->saberMove == LS_READY//ready - //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY...? - //&& pm->ps->viewangles[0] > 30 //looking down - && pm->ps->saberAnimLevel == SS_DUAL//using dual saber style - && pm->ps->saber[0].Active() && pm->ps->saber[1].Active()//both sabers on + // do normal checks + if (pm->ps->saberMove == LS_READY // ready + //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY...? + //&& pm->ps->viewangles[0] > 30 //looking down + && pm->ps->saberAnimLevel == SS_DUAL // using dual saber style + && pm->ps->saber[0].Active() && + pm->ps->saber[1].Active() // both sabers on //&& pm->ps->forcePowerLevel[FP_PUSH]>=FORCE_LEVEL_3//force push 3 //&& ((pm->ps->forcePowersActive&(1<ps->forcePowerDebounce[FP_PUSH]>level.time)//force-pushing - && G_TryingKataAttack( pm->gent, &pm->cmd )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER, qtrue )//pm->ps->forcePower >= SABER_ALT_ATTACK_POWER//DUAL_SPIN_PROTECT_POWER//force push 3 - && (pm->cmd.buttons&BUTTON_ATTACK)//pressing attack - ) - {//FIXME: some NPC logic to do this? + && G_TryingKataAttack(pm->gent, &pm->cmd) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER, + qtrue) // pm->ps->forcePower >= SABER_ALT_ATTACK_POWER//DUAL_SPIN_PROTECT_POWER//force push 3 + && (pm->cmd.buttons & BUTTON_ATTACK) // pressing attack + ) { // FIXME: some NPC logic to do this? /* if ( (pm->ps->pm_flags&PMF_DUCKED||pm->cmd.upmove<0)//crouching && g_crosshairEntNum >= ENTITYNUM_WORLD ) */ { - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_PUSH, SABER_ALT_ATTACK_POWER, qtrue );//drain the required force power + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_PUSH, SABER_ALT_ATTACK_POWER, qtrue); // drain the required force power } return LS_DUAL_SPIN_PROTECT; } @@ -3204,65 +2649,53 @@ saberMoveName_t PM_CheckDualSpinProtect( void ) return LS_NONE; } -saberMoveName_t PM_CheckStaffKata( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +saberMoveName_t PM_CheckStaffKata(void) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return LS_NONE; } - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[0].kataMove != LS_NONE ) - { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].kataMove != LS_INVALID) { + if (pm->ps->saber[0].kataMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[0].kataMove; } } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[1].kataMove != LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove != LS_INVALID) { + if (pm->ps->saber[1].kataMove != LS_NONE) { return (saberMoveName_t)pm->ps->saber[1].kataMove; } } } - //no overrides, cancelled? - if ( pm->ps->saber[0].kataMove == LS_NONE ) - { + // no overrides, cancelled? + if (pm->ps->saber[0].kataMove == LS_NONE) { return LS_NONE; } - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove == LS_NONE ) - { + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove == LS_NONE) { return LS_NONE; } } - //do normal checks - if ( pm->ps->saberMove == LS_READY//ready - //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY...? - //&& pm->ps->viewangles[0] > 30 //looking down - && pm->ps->saberAnimLevel == SS_STAFF//using dual saber style - && pm->ps->saber[0].Active()//saber on + // do normal checks + if (pm->ps->saberMove == LS_READY // ready + //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY...? + //&& pm->ps->viewangles[0] > 30 //looking down + && pm->ps->saberAnimLevel == SS_STAFF // using dual saber style + && pm->ps->saber[0].Active() // saber on //&& pm->ps->forcePowerLevel[FP_PUSH]>=FORCE_LEVEL_3//force push 3 //&& ((pm->ps->forcePowersActive&(1<ps->forcePowerDebounce[FP_PUSH]>level.time)//force-pushing - && G_TryingKataAttack( pm->gent, &pm->cmd )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER, qtrue )//pm->ps->forcePower >= SABER_ALT_ATTACK_POWER//DUAL_SPIN_PROTECT_POWER//force push 3 - && (pm->cmd.buttons&BUTTON_ATTACK)//pressing attack - ) - {//FIXME: some NPC logic to do this? + && G_TryingKataAttack(pm->gent, &pm->cmd) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER, + qtrue) // pm->ps->forcePower >= SABER_ALT_ATTACK_POWER//DUAL_SPIN_PROTECT_POWER//force push 3 + && (pm->cmd.buttons & BUTTON_ATTACK) // pressing attack + ) { // FIXME: some NPC logic to do this? /* if ( (pm->ps->pm_flags&PMF_DUCKED||pm->cmd.upmove<0)//crouching && g_crosshairEntNum >= ENTITYNUM_WORLD ) */ { - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER, qtrue );//drain the required force power + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER, qtrue); // drain the required force power } return LS_STAFF_SOULCAL; } @@ -3270,116 +2703,89 @@ saberMoveName_t PM_CheckStaffKata( void ) return LS_NONE; } -extern qboolean WP_ForceThrowable( gentity_t *ent, gentity_t *forwardEnt, gentity_t *self, qboolean pull, float cone, float radius, vec3_t forward ); -saberMoveName_t PM_CheckPullAttack( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { +extern qboolean WP_ForceThrowable(gentity_t *ent, gentity_t *forwardEnt, gentity_t *self, qboolean pull, float cone, float radius, vec3_t forward); +saberMoveName_t PM_CheckPullAttack(void) { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { return LS_NONE; } - if ( (pm->ps->saber[0].saberFlags&SFL_NO_PULL_ATTACK) ) - { + if ((pm->ps->saber[0].saberFlags & SFL_NO_PULL_ATTACK)) { return LS_NONE; } - if ( pm->ps->dualSabers - && (pm->ps->saber[1].saberFlags&SFL_NO_PULL_ATTACK) ) - { + if (pm->ps->dualSabers && (pm->ps->saber[1].saberFlags & SFL_NO_PULL_ATTACK)) { return LS_NONE; } - if ( (pm->ps->saberMove == LS_READY||PM_SaberInReturn(pm->ps->saberMove)||PM_SaberInReflect(pm->ps->saberMove))//ready - //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY - && pm->ps->saberAnimLevel >= SS_FAST//single saber styles - FIXME: Tavion? - && pm->ps->saberAnimLevel <= SS_STRONG//single saber styles - FIXME: Tavion? - && G_TryingPullAttack( pm->gent, &pm->cmd, qfalse )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus + if ((pm->ps->saberMove == LS_READY || PM_SaberInReturn(pm->ps->saberMove) || + PM_SaberInReflect(pm->ps->saberMove)) // ready + //&& (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//PLAYER ONLY + && pm->ps->saberAnimLevel >= SS_FAST // single saber styles - FIXME: Tavion? + && pm->ps->saberAnimLevel <= SS_STRONG // single saber styles - FIXME: Tavion? + && G_TryingPullAttack(pm->gent, &pm->cmd, qfalse) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS)//holding focus //&& pm->cmd.forwardmove<0//pulling back - && (pm->cmd.buttons&BUTTON_ATTACK)//attacking - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB )//pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB//have enough power - ) - {//FIXME: some NPC logic to do this? - qboolean doMove = g_saberNewControlScheme->integer?qtrue:qfalse;//in new control scheme, can always do this, even if there's no-one to do it to - if ( g_saberNewControlScheme->integer - || g_crosshairEntNum < ENTITYNUM_WORLD )//in old control scheme, there has to be someone there + && (pm->cmd.buttons & BUTTON_ATTACK) // attacking + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB) // pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB//have enough power + ) { // FIXME: some NPC logic to do this? + qboolean doMove = g_saberNewControlScheme->integer ? qtrue : qfalse; // in new control scheme, can always do this, even if there's no-one to do it to + if (g_saberNewControlScheme->integer || g_crosshairEntNum < ENTITYNUM_WORLD) // in old control scheme, there has to be someone there { saberMoveName_t pullAttackMove = LS_NONE; - if ( pm->ps->saberAnimLevel == SS_FAST ) - { + if (pm->ps->saberAnimLevel == SS_FAST) { pullAttackMove = LS_PULL_ATTACK_STAB; - } - else - { + } else { pullAttackMove = LS_PULL_ATTACK_SWING; } - if ( g_crosshairEntNum < ENTITYNUM_WORLD - && pm->gent && pm->gent->client ) - { + if (g_crosshairEntNum < ENTITYNUM_WORLD && pm->gent && pm->gent->client) { gentity_t *targEnt = &g_entities[g_crosshairEntNum]; - if ( targEnt->client - && targEnt->health > 0 - //FIXME: check other things like in knockdown, saberlock, uninterruptable anims, etc. - && !PM_InOnGroundAnim( &targEnt->client->ps ) - && !PM_LockedAnim( targEnt->client->ps.legsAnim ) - && !PM_SuperBreakLoseAnim( targEnt->client->ps.legsAnim ) - && !PM_SuperBreakWinAnim( targEnt->client->ps.legsAnim ) - && targEnt->client->ps.saberLockTime <= 0 - && WP_ForceThrowable( targEnt, targEnt, pm->gent, qtrue, 1.0f, 0.0f, NULL ) ) - { - if ( !g_saberNewControlScheme->integer ) - {//in old control scheme, make sure they're close or far enough away for the move we'll be doing - float targDist = Distance( targEnt->currentOrigin, pm->ps->origin ); - if ( pullAttackMove == LS_PULL_ATTACK_STAB ) - {//must be closer than 512 - if ( targDist > 384.0f ) - { + if (targEnt->client && + targEnt->health > 0 + // FIXME: check other things like in knockdown, saberlock, uninterruptable anims, etc. + && !PM_InOnGroundAnim(&targEnt->client->ps) && !PM_LockedAnim(targEnt->client->ps.legsAnim) && + !PM_SuperBreakLoseAnim(targEnt->client->ps.legsAnim) && !PM_SuperBreakWinAnim(targEnt->client->ps.legsAnim) && + targEnt->client->ps.saberLockTime <= 0 && WP_ForceThrowable(targEnt, targEnt, pm->gent, qtrue, 1.0f, 0.0f, NULL)) { + if (!g_saberNewControlScheme->integer) { // in old control scheme, make sure they're close or far enough away for the move we'll be doing + float targDist = Distance(targEnt->currentOrigin, pm->ps->origin); + if (pullAttackMove == LS_PULL_ATTACK_STAB) { // must be closer than 512 + if (targDist > 384.0f) { return LS_NONE; } - } - else//if ( pullAttackMove == LS_PULL_ATTACK_SWING ) - {//must be farther than 256 - if ( targDist > 512.0f ) - { + } else // if ( pullAttackMove == LS_PULL_ATTACK_SWING ) + { // must be farther than 256 + if (targDist > 512.0f) { return LS_NONE; } - if ( targDist < 192.0f ) - { + if (targDist < 192.0f) { return LS_NONE; } } } - vec3_t targAngles = {0,targEnt->client->ps.viewangles[YAW],0}; - if ( InFront( pm->ps->origin, targEnt->currentOrigin, targAngles ) ) - { - NPC_SetAnim( targEnt, SETANIM_BOTH, BOTH_PULLED_INAIR_F, SETANIM_FLAG_OVERRIDE, SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( targEnt, SETANIM_BOTH, BOTH_PULLED_INAIR_B, SETANIM_FLAG_OVERRIDE, SETANIM_FLAG_HOLD ); + vec3_t targAngles = {0, targEnt->client->ps.viewangles[YAW], 0}; + if (InFront(pm->ps->origin, targEnt->currentOrigin, targAngles)) { + NPC_SetAnim(targEnt, SETANIM_BOTH, BOTH_PULLED_INAIR_F, SETANIM_FLAG_OVERRIDE, SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(targEnt, SETANIM_BOTH, BOTH_PULLED_INAIR_B, SETANIM_FLAG_OVERRIDE, SETANIM_FLAG_HOLD); } - //hold the anim until I'm with done pull anim - targEnt->client->ps.legsAnimTimer = targEnt->client->ps.torsoAnimTimer = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, (animNumber_t)saberMoveData[pullAttackMove].animToUse ); - //set pullAttackTime - pm->gent->client->ps.pullAttackTime = targEnt->client->ps.pullAttackTime = level.time+targEnt->client->ps.legsAnimTimer; - //make us know about each other + // hold the anim until I'm with done pull anim + targEnt->client->ps.legsAnimTimer = targEnt->client->ps.torsoAnimTimer = + PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, (animNumber_t)saberMoveData[pullAttackMove].animToUse); + // set pullAttackTime + pm->gent->client->ps.pullAttackTime = targEnt->client->ps.pullAttackTime = level.time + targEnt->client->ps.legsAnimTimer; + // make us know about each other pm->gent->client->ps.pullAttackEntNum = g_crosshairEntNum; targEnt->client->ps.pullAttackEntNum = pm->ps->clientNum; - //do effect and sound on me + // do effect and sound on me pm->ps->powerups[PW_FORCE_PUSH] = level.time + 1000; - if ( pm->gent ) - { - G_Sound( pm->gent, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); + if (pm->gent) { + G_Sound(pm->gent, G_SoundIndex("sound/weapons/force/pull.wav")); } doMove = qtrue; } } - if ( doMove ) - { - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_PULL, SABER_ALT_ATTACK_POWER_FB ); + if (doMove) { + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_PULL, SABER_ALT_ATTACK_POWER_FB); } return pullAttackMove; } @@ -3388,15 +2794,10 @@ saberMoveName_t PM_CheckPullAttack( void ) return LS_NONE; } -saberMoveName_t PM_CheckPlayerAttackFromParry( int curmove ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) - { - if ( curmove >= LS_PARRY_UP - && curmove <= LS_REFLECT_LL ) - {//in a parry - switch ( saberMoveData[curmove].endQuad ) - { +saberMoveName_t PM_CheckPlayerAttackFromParry(int curmove) { + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) { + if (curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL) { // in a parry + switch (saberMoveData[curmove].endQuad) { case Q_T: return LS_A_T2B; break; @@ -3412,102 +2813,70 @@ saberMoveName_t PM_CheckPlayerAttackFromParry( int curmove ) case Q_BL: return LS_A_BL2TR; break; - //shouldn't be a parry that ends at L, R or B + // shouldn't be a parry that ends at L, R or B } } } return LS_NONE; } - -saberMoveName_t PM_SaberAttackForMovement( int forwardmove, int rightmove, int curmove ) -{ +saberMoveName_t PM_SaberAttackForMovement(int forwardmove, int rightmove, int curmove) { qboolean noSpecials = qfalse; - if ( pm->ps->clientNum < MAX_CLIENTS - && PM_InSecondaryStyle() ) - { + if (pm->ps->clientNum < MAX_CLIENTS && PM_InSecondaryStyle()) { noSpecials = qtrue; } saberMoveName_t overrideJumpRightAttackMove = LS_INVALID; - if ( pm->ps->saber[0].jumpAtkRightMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkRightMove != LS_NONE ) - {//actually overriding + if (pm->ps->saber[0].jumpAtkRightMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkRightMove != LS_NONE) { // actually overriding overrideJumpRightAttackMove = (saberMoveName_t)pm->ps->saber[0].jumpAtkRightMove; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkRightMove > LS_NONE ) - {//would be cancelling it, but check the second saber, too + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkRightMove > LS_NONE) { // would be cancelling it, but check the second saber, too overrideJumpRightAttackMove = (saberMoveName_t)pm->ps->saber[1].jumpAtkRightMove; - } - else - {//nope, just cancel it + } else { // nope, just cancel it overrideJumpRightAttackMove = LS_NONE; } - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkRightMove != LS_INVALID ) - {//first saber not overridden, check second + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkRightMove != LS_INVALID) { // first saber not overridden, check second overrideJumpRightAttackMove = (saberMoveName_t)pm->ps->saber[1].jumpAtkRightMove; } saberMoveName_t overrideJumpLeftAttackMove = LS_INVALID; - if ( pm->ps->saber[0].jumpAtkLeftMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkLeftMove != LS_NONE ) - {//actually overriding + if (pm->ps->saber[0].jumpAtkLeftMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkLeftMove != LS_NONE) { // actually overriding overrideJumpLeftAttackMove = (saberMoveName_t)pm->ps->saber[0].jumpAtkLeftMove; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkLeftMove > LS_NONE ) - {//would be cancelling it, but check the second saber, too + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkLeftMove > LS_NONE) { // would be cancelling it, but check the second saber, too overrideJumpLeftAttackMove = (saberMoveName_t)pm->ps->saber[1].jumpAtkLeftMove; - } - else - {//nope, just cancel it + } else { // nope, just cancel it overrideJumpLeftAttackMove = LS_NONE; } - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkLeftMove != LS_INVALID ) - {//first saber not overridden, check second + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkLeftMove != LS_INVALID) { // first saber not overridden, check second overrideJumpLeftAttackMove = (saberMoveName_t)pm->ps->saber[1].jumpAtkLeftMove; } - if ( rightmove > 0 ) - {//moving right - if ( !noSpecials - && overrideJumpRightAttackMove != LS_NONE - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=250) //on ground or just jumped - && (pm->cmd.buttons&BUTTON_ATTACK)//hitting attack - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0//have force jump 1 at least - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_LR )//pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR//have enough power - && (((pm->ps->clientNum>=MAX_CLIENTS&&!PM_ControlledByPlayer())&&pm->cmd.upmove > 0)//jumping NPC - ||((pm->ps->clientNumgent, &pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/)) )//focus-holding player - {//cartwheel right + if (rightmove > 0) { // moving right + if (!noSpecials && overrideJumpRightAttackMove != LS_NONE && + (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 250) // on ground or just jumped + && (pm->cmd.buttons & BUTTON_ATTACK) // hitting attack + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // have force jump 1 at least + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_LR) // pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR//have enough power + && (((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) && pm->cmd.upmove > 0) // jumping NPC + || ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + G_TryingCartwheel(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/))) // focus-holding player + { // cartwheel right vec3_t right, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_LR ); + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_LR); } pm->cmd.upmove = 0; - if ( overrideJumpRightAttackMove != LS_INVALID ) - {//overridden with another move + if (overrideJumpRightAttackMove != LS_INVALID) { // overridden with another move return overrideJumpRightAttackMove; - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - AngleVectors( fwdAngles, NULL, right, NULL ); + } else if (pm->ps->saberAnimLevel == SS_STAFF) { + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 190, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, 190, right, pm->ps->velocity); return LS_BUTTERFLY_RIGHT; - } - else - { - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_CARTWHEELS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_CARTWHEELS)) ) - {//okay to do cartwheels with this saber + } else { + if (!(pm->ps->saber[0].saberFlags & SFL_NO_CARTWHEELS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_CARTWHEELS))) { // okay to do cartwheels with this saber /* if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) {//still on ground @@ -3516,80 +2885,62 @@ saberMoveName_t PM_SaberAttackForMovement( int forwardmove, int rightmove, int c } else */ - {//in air - AngleVectors( fwdAngles, NULL, right, NULL ); + { // in air + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 190, right, pm->ps->velocity ); - PM_SetJumped( JUMP_VELOCITY, qtrue ); + VectorMA(pm->ps->velocity, 190, right, pm->ps->velocity); + PM_SetJumped(JUMP_VELOCITY, qtrue); return LS_JUMPATTACK_ARIAL_RIGHT; } } } - } - else if ( pm->ps->legsAnim != BOTH_CARTWHEEL_RIGHT - && pm->ps->legsAnim != BOTH_ARIAL_RIGHT ) - {//not in a cartwheel/arial - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial(pm->gent, &pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/ )//Holding focus - {//if no special worked, do nothing + } else if (pm->ps->legsAnim != BOTH_CARTWHEEL_RIGHT && pm->ps->legsAnim != BOTH_ARIAL_RIGHT) { // not in a cartwheel/arial + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/) // Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //checked all special attacks, if we're in a parry, attack from that move - saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry( curmove ); - if ( parryAttackMove != LS_NONE ) - { + // checked all special attacks, if we're in a parry, attack from that move + saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry(curmove); + if (parryAttackMove != LS_NONE) { return parryAttackMove; } - //check regular attacks - if ( forwardmove > 0 ) - {//forward right = TL2BR slash + // check regular attacks + if (forwardmove > 0) { // forward right = TL2BR slash return LS_A_TL2BR; - } - else if ( forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (forwardmove < 0) { // backward right = BL2TR uppercut return LS_A_BL2TR; - } - else - {//just right is a left slice + } else { // just right is a left slice return LS_A_L2R; } } - } - else if ( rightmove < 0 ) - {//moving left - if ( !noSpecials - && overrideJumpLeftAttackMove != LS_NONE - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=250) //on ground or just jumped - && (pm->cmd.buttons&BUTTON_ATTACK)//hitting attack - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0//have force jump 1 at least - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_LR )//pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR//have enough power - && (((pm->ps->clientNum>=MAX_CLIENTS&&!PM_ControlledByPlayer())&&pm->cmd.upmove > 0)//jumping NPC - ||((pm->ps->clientNumgent, &pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/)) )//focus-holding player - {//cartwheel left + } else if (rightmove < 0) { // moving left + if (!noSpecials && overrideJumpLeftAttackMove != LS_NONE && + (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 250) // on ground or just jumped + && (pm->cmd.buttons & BUTTON_ATTACK) // hitting attack + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // have force jump 1 at least + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_LR) // pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR//have enough power + && (((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) && pm->cmd.upmove > 0) // jumping NPC + || ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + G_TryingCartwheel(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/))) // focus-holding player + { // cartwheel left vec3_t right, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_LR ); + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_LEVITATION, SABER_ALT_ATTACK_POWER_LR); } pm->cmd.upmove = 0; - if ( overrideJumpRightAttackMove != LS_INVALID ) - {//overridden with another move + if (overrideJumpRightAttackMove != LS_INVALID) { // overridden with another move return overrideJumpRightAttackMove; - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - AngleVectors( fwdAngles, NULL, right, NULL ); + } else if (pm->ps->saberAnimLevel == SS_STAFF) { + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -190, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -190, right, pm->ps->velocity); return LS_BUTTERFLY_LEFT; - } - else - { - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_CARTWHEELS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_CARTWHEELS)) ) - {//okay to do cartwheels with this saber + } else { + if (!(pm->ps->saber[0].saberFlags & SFL_NO_CARTWHEELS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_CARTWHEELS))) { // okay to do cartwheels with this saber /* if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) {//still on ground @@ -3599,253 +2950,202 @@ saberMoveName_t PM_SaberAttackForMovement( int forwardmove, int rightmove, int c else */ { - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -190, right, pm->ps->velocity ); - PM_SetJumped( JUMP_VELOCITY, qtrue ); + VectorMA(pm->ps->velocity, -190, right, pm->ps->velocity); + PM_SetJumped(JUMP_VELOCITY, qtrue); return LS_JUMPATTACK_CART_LEFT; } } } - } - else if ( pm->ps->legsAnim != BOTH_CARTWHEEL_LEFT - && pm->ps->legsAnim != BOTH_ARIAL_LEFT ) - {//not in a left cartwheel/arial - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial(pm->gent, &pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/ )//Holding focus - {//if no special worked, do nothing + } else if (pm->ps->legsAnim != BOTH_CARTWHEEL_LEFT && pm->ps->legsAnim != BOTH_ARIAL_LEFT) { // not in a left cartwheel/arial + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/) // Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //checked all special attacks, if we're in a parry, attack from that move - saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry( curmove ); - if ( parryAttackMove != LS_NONE ) - { + // checked all special attacks, if we're in a parry, attack from that move + saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry(curmove); + if (parryAttackMove != LS_NONE) { return parryAttackMove; } - //check regular attacks - if ( forwardmove > 0 ) - {//forward left = TR2BL slash + // check regular attacks + if (forwardmove > 0) { // forward left = TR2BL slash return LS_A_TR2BL; - } - else if ( forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (forwardmove < 0) { // backward left = BR2TL uppercut return LS_A_BR2TL; - } - else - {//just left is a right slice + } else { // just left is a right slice return LS_A_R2L; } } - } - else - {//not moving left or right - if ( forwardmove > 0 ) - {//forward= T2B slash - saberMoveName_t stabDownMove = noSpecials?LS_NONE:PM_CheckStabDown(); - if ( stabDownMove != LS_NONE ) - { + } else { // not moving left or right + if (forwardmove > 0) { // forward= T2B slash + saberMoveName_t stabDownMove = noSpecials ? LS_NONE : PM_CheckStabDown(); + if (stabDownMove != LS_NONE) { return stabDownMove; } - if ( ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) )//player in third person, not zoomed in - {//player in thirdperson, not zoomed in - //flip-over attack logic - if ( !noSpecials && PM_CheckFlipOverAttackMove( qfalse ) ) - {//flip over-forward down-attack + if (((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && + !cg.zoomMode)) // player in third person, not zoomed in + { // player in thirdperson, not zoomed in + // flip-over attack logic + if (!noSpecials && PM_CheckFlipOverAttackMove(qfalse)) { // flip over-forward down-attack return PM_SaberFlipOverAttackMove(); } - //lunge attack logic - else if ( PM_CheckLungeAttackMove() ) - { - return PM_SaberLungeAttackMove( qtrue ); + // lunge attack logic + else if (PM_CheckLungeAttackMove()) { + return PM_SaberLungeAttackMove(qtrue); } - //jump forward attack logic - else if ( !noSpecials && PM_CheckJumpForwardAttackMove() ) - { + // jump forward attack logic + else if (!noSpecials && PM_CheckJumpForwardAttackMove()) { return PM_SaberJumpForwardAttackMove(); } } - //player NPC with enemy: autoMove logic - if ( pm->gent - && pm->gent->enemy - && pm->gent->enemy->client ) - {//I have an active enemy - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) - {//a player who is running at an enemy - //if the enemy is not a jedi, don't use top-down, pick a diagonal or side attack - if ( pm->gent->enemy->s.weapon != WP_SABER - && pm->gent->enemy->client->NPC_class != CLASS_REMOTE//too small to do auto-aiming accurately - && pm->gent->enemy->client->NPC_class != CLASS_SEEKER//too small to do auto-aiming accurately - && pm->gent->enemy->client->NPC_class != CLASS_GONK//too short to do auto-aiming accurately - && pm->gent->enemy->client->NPC_class != CLASS_HOWLER//too short to do auto-aiming accurately - && g_saberAutoAim->integer ) - { - saberMoveName_t autoMove = PM_AttackForEnemyPos( qfalse, (qboolean)(pm->ps->clientNum>=MAX_CLIENTS&&!PM_ControlledByPlayer()) ); - if ( autoMove != LS_INVALID ) - { + // player NPC with enemy: autoMove logic + if (pm->gent && pm->gent->enemy && pm->gent->enemy->client) { // I have an active enemy + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) { // a player who is running at an enemy + // if the enemy is not a jedi, don't use top-down, pick a diagonal or side attack + if (pm->gent->enemy->s.weapon != WP_SABER && pm->gent->enemy->client->NPC_class != CLASS_REMOTE // too small to do auto-aiming accurately + && pm->gent->enemy->client->NPC_class != CLASS_SEEKER // too small to do auto-aiming accurately + && pm->gent->enemy->client->NPC_class != CLASS_GONK // too short to do auto-aiming accurately + && pm->gent->enemy->client->NPC_class != CLASS_HOWLER // too short to do auto-aiming accurately + && g_saberAutoAim->integer) { + saberMoveName_t autoMove = PM_AttackForEnemyPos(qfalse, (qboolean)(pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())); + if (autoMove != LS_INVALID) { return autoMove; } } } - if ( pm->ps->clientNum>=MAX_CLIENTS && !PM_ControlledByPlayer() ) //NPC ONLY - {//NPC - if ( PM_CheckFlipOverAttackMove( qtrue ) ) - { + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) // NPC ONLY + { // NPC + if (PM_CheckFlipOverAttackMove(qtrue)) { return PM_SaberFlipOverAttackMove(); } } } - //Regular NPCs - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) //NPC ONLY - {//NPC or player in third person, not zoomed in - //fwd jump attack logic - if ( PM_CheckJumpForwardAttackMove() ) - { + // Regular NPCs + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) // NPC ONLY + { // NPC or player in third person, not zoomed in + // fwd jump attack logic + if (PM_CheckJumpForwardAttackMove()) { return PM_SaberJumpForwardAttackMove(); } - //lunge attack logic - else if ( PM_CheckLungeAttackMove() ) - { - return PM_SaberLungeAttackMove( qtrue ); + // lunge attack logic + else if (PM_CheckLungeAttackMove()) { + return PM_SaberLungeAttackMove(qtrue); } } - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial(pm->gent,&pm->cmd) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //checked all special attacks, if we're in a parry, attack from that move - saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry( curmove ); - if ( parryAttackMove != LS_NONE ) - { + // checked all special attacks, if we're in a parry, attack from that move + saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry(curmove); + if (parryAttackMove != LS_NONE) { return parryAttackMove; } - //check regular attacks + // check regular attacks return LS_A_T2B; - } - else if ( forwardmove < 0 ) - {//backward= T2B slash//B2T uppercut? - if ( g_saberNewControlScheme->integer ) - { + } else if (forwardmove < 0) { // backward= T2B slash//B2T uppercut? + if (g_saberNewControlScheme->integer) { saberMoveName_t pullAtk = PM_CheckPullAttack(); - if ( pullAtk != LS_NONE ) - { + if (pullAtk != LS_NONE) { return pullAtk; } } - if ( g_saberNewControlScheme->integer - && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) //PLAYER ONLY - && (pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus, trying special backwards attacks - {//player lunge attack logic - if ( ( pm->ps->dualSabers //or dual - || pm->ps->saberAnimLevel == SS_STAFF )//pm->ps->SaberStaff() )//or staff - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB )/*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB*/ )//have enough force power to pull it off - {//alt+back+attack using fast, dual or staff attacks - PM_SaberLungeAttackMove( qfalse ); + if (g_saberNewControlScheme->integer && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + && (pm->cmd.buttons & BUTTON_FORCE_FOCUS)) // Holding focus, trying special backwards attacks + { // player lunge attack logic + if ((pm->ps->dualSabers // or dual + || pm->ps->saberAnimLevel == SS_STAFF) // pm->ps->SaberStaff() )//or staff + && G_EnoughPowerForSpecialMove( + pm->ps->forcePower, + SABER_ALT_ATTACK_POWER_FB) /*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_FB*/) // have enough force power to pull it off + { // alt+back+attack using fast, dual or staff attacks + PM_SaberLungeAttackMove(qfalse); } - } - else if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) //NPC - || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) )//player in third person, not zooomed - {//NPC or player in third person, not zoomed - if ( PM_CheckBackflipAttackMove() ) - { - return PM_SaberBackflipAttackMove();//backflip attack + } else if ((pm->ps->clientNum && !PM_ControlledByPlayer()) // NPC + || ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && + !cg.zoomMode)) // player in third person, not zooomed + { // NPC or player in third person, not zoomed + if (PM_CheckBackflipAttackMove()) { + return PM_SaberBackflipAttackMove(); // backflip attack } - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial(pm->gent,&pm->cmd) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //if ( !PM_InKnockDown( pm->ps ) ) - //check backstabs - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_BACK_ATTACK) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_BACK_ATTACK)) ) - {//okay to do backstabs with this saber - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//only when on ground - if ( pm->gent && pm->gent->enemy ) - {//FIXME: or just trace for a valid enemy standing behind me? And no enemy in front? + // if ( !PM_InKnockDown( pm->ps ) ) + // check backstabs + if (!(pm->ps->saber[0].saberFlags & SFL_NO_BACK_ATTACK) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_BACK_ATTACK))) { // okay to do backstabs with this saber + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // only when on ground + if (pm->gent && pm->gent->enemy) { // FIXME: or just trace for a valid enemy standing behind me? And no enemy in front? vec3_t enemyDir, faceFwd, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( facingAngles, faceFwd, NULL, NULL ); - VectorSubtract( pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir ); - float dot = DotProduct( enemyDir, faceFwd ); - if ( dot < 0 ) - {//enemy is behind me - if ( dot < -0.75f - && DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ) < 16384//128 squared - && (pm->ps->saberAnimLevel == SS_FAST || pm->ps->saberAnimLevel == SS_STAFF || (pm->gent->client &&(pm->gent->client->NPC_class == CLASS_TAVION||pm->gent->client->NPC_class == CLASS_ALORA)&&Q_irand(0,1))) ) - {//fast attacks and Tavion - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//can't do it while ducked? - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG) ) - {//only fencers and above can do this + AngleVectors(facingAngles, faceFwd, NULL, NULL); + VectorSubtract(pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir); + float dot = DotProduct(enemyDir, faceFwd); + if (dot < 0) { // enemy is behind me + if (dot < -0.75f && DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin) < 16384 // 128 squared + && (pm->ps->saberAnimLevel == SS_FAST || pm->ps->saberAnimLevel == SS_STAFF || + (pm->gent->client && (pm->gent->client->NPC_class == CLASS_TAVION || pm->gent->client->NPC_class == CLASS_ALORA) && + Q_irand(0, 1)))) { // fast attacks and Tavion + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // can't do it while ducked? + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || + (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG)) { // only fencers and above can do this return LS_A_BACKSTAB; } } - } - else if ( pm->ps->saberAnimLevel != SS_FAST - && pm->ps->saberAnimLevel != SS_STAFF ) - {//medium and higher attacks - if ( (pm->ps->pm_flags&PMF_DUCKED) || pm->cmd.upmove < 0 ) - { + } else if (pm->ps->saberAnimLevel != SS_FAST && pm->ps->saberAnimLevel != SS_STAFF) { // medium and higher attacks + if ((pm->ps->pm_flags & PMF_DUCKED) || pm->cmd.upmove < 0) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } } - } - else - {//enemy in front - float enemyDistSq = DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ); - if ( ((pm->ps->saberAnimLevel == FORCE_LEVEL_1 || - pm->ps->saberAnimLevel == SS_STAFF || - pm->gent->client->NPC_class == CLASS_TAVION || - pm->gent->client->NPC_class == CLASS_ALORA || - (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0,3))) && - enemyDistSq > 16384) || - pm->gent->enemy->health <= 0 )//128 squared - {//my enemy is pretty far in front of me and I'm using fast attacks - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || - ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 128 ) ) - { + } else { // enemy in front + float enemyDistSq = DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin); + if (((pm->ps->saberAnimLevel == FORCE_LEVEL_1 || pm->ps->saberAnimLevel == SS_STAFF || + pm->gent->client->NPC_class == CLASS_TAVION || pm->gent->client->NPC_class == CLASS_ALORA || + (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0, 3))) && + enemyDistSq > 16384) || + pm->gent->enemy->health <= 0) // 128 squared + { // my enemy is pretty far in front of me and I'm using fast attacks + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN)) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(128)) { return PM_PickBackStab(); } } - } - else if ( ((pm->ps->saberAnimLevel >= FORCE_LEVEL_2 || pm->gent->client->NPC_class == CLASS_DESANN) && enemyDistSq > 40000) || pm->gent->enemy->health <= 0 )//200 squared - {//enemy is very faw away and I'm using medium/strong attacks - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || - ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 164 ) ) - { + } else if (((pm->ps->saberAnimLevel >= FORCE_LEVEL_2 || pm->gent->client->NPC_class == CLASS_DESANN) && enemyDistSq > 40000) || + pm->gent->enemy->health <= 0) // 200 squared + { // enemy is very faw away and I'm using medium/strong attacks + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN)) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(164)) { return PM_PickBackStab(); } } } } - } - else - {//no current enemy - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->gent && pm->gent->client ) - {//only player - if ( PM_CheckEnemyInBack( 128 ) ) - { + } else { // no current enemy + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->gent && pm->gent->client) { // only player + if (PM_CheckEnemyInBack(128)) { return PM_PickBackStab(); } } @@ -3854,154 +3154,115 @@ saberMoveName_t PM_SaberAttackForMovement( int forwardmove, int rightmove, int c } } - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial( pm->gent, &pm->cmd ) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //checked all special attacks, if we're in a parry, attack from that move - saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry( curmove ); - if ( parryAttackMove != LS_NONE ) - { + // checked all special attacks, if we're in a parry, attack from that move + saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry(curmove); + if (parryAttackMove != LS_NONE) { return parryAttackMove; } - //check regular attacks - //else just swing down + // check regular attacks + // else just swing down return LS_A_T2B; - } - else - {//not moving in any direction - if ( PM_SaberInBounce( curmove ) ) - {//bounces should go to their default attack if you don't specify a direction but are attacking - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial(pm->gent,&pm->cmd) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + } else { // not moving in any direction + if (PM_SaberInBounce(curmove)) { // bounces should go to their default attack if you don't specify a direction but are attacking + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } saberMoveName_t newmove; - if ( pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand( 0, 3 ) ) - {//use NPC random - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - {//player uses chain-attack + if (pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand(0, 3)) { // use NPC random + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { // player uses chain-attack newmove = saberMoveData[curmove].chain_attack; } - if ( PM_SaberKataDone( curmove, newmove ) ) - { + if (PM_SaberKataDone(curmove, newmove)) { return saberMoveData[curmove].chain_idle; - } - else - { + } else { return newmove; } - } - else if ( PM_SaberInKnockaway( curmove ) ) - {//bounces should go to their default attack if you don't specify a direction but are attacking - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial( pm->gent, &pm->cmd ) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + } else if (PM_SaberInKnockaway(curmove)) { // bounces should go to their default attack if you don't specify a direction but are attacking + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } saberMoveName_t newmove; - if ( pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand( 0, 3 ) ) - {//use NPC random - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - { - if ( pm->ps->saberAnimLevel == SS_FAST || - pm->ps->saberAnimLevel == SS_TAVION ) - {//player is in fast attacks, so come right back down from the same spot - newmove = PM_AttackMoveForQuad( saberMoveData[curmove].endQuad ); - } - else - {//use a transition to wrap to another attack from a different dir + if (pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand(0, 3)) { // use NPC random + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { + if (pm->ps->saberAnimLevel == SS_FAST || + pm->ps->saberAnimLevel == SS_TAVION) { // player is in fast attacks, so come right back down from the same spot + newmove = PM_AttackMoveForQuad(saberMoveData[curmove].endQuad); + } else { // use a transition to wrap to another attack from a different dir newmove = saberMoveData[curmove].chain_attack; } } - if ( PM_SaberKataDone( curmove, newmove ) ) - { + if (PM_SaberKataDone(curmove, newmove)) { return saberMoveData[curmove].chain_idle; - } - else - { + } else { return newmove; } - } - else if ( curmove == LS_READY - || curmove == LS_A_FLIP_STAB - || curmove == LS_A_FLIP_SLASH - || ( curmove >= LS_PARRY_UP - && curmove <= LS_REFLECT_LL ) ) - {//Not moving at all, not too busy to attack - //push + lookdown + attack + dual sabers = LS_DUAL_SPIN_PROTECT - if ( g_saberNewControlScheme->integer ) - { - if ( PM_CheckDualSpinProtect() ) - { + } else if (curmove == LS_READY || curmove == LS_A_FLIP_STAB || curmove == LS_A_FLIP_SLASH || + (curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL)) { // Not moving at all, not too busy to attack + // push + lookdown + attack + dual sabers = LS_DUAL_SPIN_PROTECT + if (g_saberNewControlScheme->integer) { + if (PM_CheckDualSpinProtect()) { return LS_DUAL_SPIN_PROTECT; } - if ( PM_CheckStaffKata() ) - { + if (PM_CheckStaffKata()) { return LS_STAFF_SOULCAL; } } - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) //PLAYER ONLY - {//player - if ( G_TryingSpecial( pm->gent, &pm->cmd ) )//(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus - {//if no special worked, do nothing + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // PLAYER ONLY + { // player + if (G_TryingSpecial(pm->gent, &pm->cmd)) //(pm->cmd.buttons&BUTTON_FORCE_FOCUS) )//Holding focus + { // if no special worked, do nothing return LS_NONE; } } - //checked all special attacks, if we're in a parry, attack from that move - saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry( curmove ); - if ( parryAttackMove != LS_NONE ) - { + // checked all special attacks, if we're in a parry, attack from that move + saberMoveName_t parryAttackMove = PM_CheckPlayerAttackFromParry(curmove); + if (parryAttackMove != LS_NONE) { return parryAttackMove; } - //check regular attacks - if ( pm->ps->clientNum || g_saberAutoAim->integer ) - {//auto-aim - if ( pm->gent && pm->gent->enemy ) - {//based on enemy position, pick a proper attack - saberMoveName_t autoMove = PM_AttackForEnemyPos( qtrue, (qboolean)(pm->ps->clientNum>=MAX_CLIENTS) ); - if ( autoMove != LS_INVALID ) - { + // check regular attacks + if (pm->ps->clientNum || g_saberAutoAim->integer) { // auto-aim + if (pm->gent && pm->gent->enemy) { // based on enemy position, pick a proper attack + saberMoveName_t autoMove = PM_AttackForEnemyPos(qtrue, (qboolean)(pm->ps->clientNum >= MAX_CLIENTS)); + if (autoMove != LS_INVALID) { return autoMove; } - } - else if ( fabs(pm->ps->viewangles[0]) > 30 ) - {//looking far up or far down uses the top to bottom attack, presuming you want a vertical attack + } else if (fabs(pm->ps->viewangles[0]) > + 30) { // looking far up or far down uses the top to bottom attack, presuming you want a vertical attack return LS_A_T2B; } - } - else - {//for now, just pick a random attack - return ((saberMoveName_t)Q_irand( LS_A_TL2BR, LS_A_T2B )); + } else { // for now, just pick a random attack + return ((saberMoveName_t)Q_irand(LS_A_TL2BR, LS_A_T2B)); } } } } - //FIXME: pick a return? + // FIXME: pick a return? return LS_NONE; } -saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveName_t newmove ) -{ - //FIXME: take FP_SABER_OFFENSE into account here somehow? +saberMoveName_t PM_SaberAnimTransitionMove(saberMoveName_t curmove, saberMoveName_t newmove) { + // FIXME: take FP_SABER_OFFENSE into account here somehow? int retmove = newmove; - if ( curmove == LS_READY ) - {//just standing there - switch ( newmove ) - { + if (curmove == LS_READY) { // just standing there + switch (newmove) { case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -4009,22 +3270,18 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the start - retmove = LS_S_TL2BR + (newmove-LS_A_TL2BR); + // transition is the start + retmove = LS_S_TL2BR + (newmove - LS_A_TL2BR); break; default: break; } - } - else - { - switch ( newmove ) - { - //transitioning to ready pose + } else { + switch (newmove) { + // transitioning to ready pose case LS_READY: - switch ( curmove ) - { - //transitioning from an attack + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -4032,14 +3289,14 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the return - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); + // transition is the return + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); break; default: break; } break; - //transitioning to an attack + // transitioning to an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -4047,29 +3304,20 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - if ( newmove == curmove ) - {//FIXME: need a spin or something or go to next level, but for now, just play the return - //going into another attack... - //allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 - //FIXME: don't let strong attacks chain to an attack in the opposite direction ( > 45 degrees?) - if ( PM_SaberKataDone( curmove, newmove ) ) - {//done with this kata, must return to ready before attack again - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); - } - else - {//okay to chain to another attack + if (newmove == curmove) { // FIXME: need a spin or something or go to next level, but for now, just play the return + // going into another attack... + // allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 + // FIXME: don't let strong attacks chain to an attack in the opposite direction ( > 45 degrees?) + if (PM_SaberKataDone(curmove, newmove)) { // done with this kata, must return to ready before attack again + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); + } else { // okay to chain to another attack retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; } - } - else if ( saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad ) - {//new move starts from same quadrant + } else if (saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad) { // new move starts from same quadrant retmove = newmove; - } - else - { - switch ( curmove ) - { - //transitioning from an attack + } else { + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -4087,7 +3335,7 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_D1_B_: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //transitioning from a return + // transitioning from a return case LS_R_TL2BR: case LS_R_L2R: case LS_R_BL2TR: @@ -4095,7 +3343,7 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_R_R2L: case LS_R_TR2BL: case LS_R_T2B: - //transitioning from a bounce + // transitioning from a bounce /* case LS_BOUNCE_UL2LL: case LS_BOUNCE_LL2UL: @@ -4113,7 +3361,7 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_BOUNCE_LR: case LS_BOUNCE_LL: */ - //transitioning from a parry/reflection/knockaway/broken parry + // transitioning from a parry/reflection/knockaway/broken parry case LS_PARRY_UP: case LS_PARRY_UR: case LS_PARRY_UL: @@ -4144,20 +3392,19 @@ saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveNa case LS_H1_BL: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //NB: transitioning from transitions is fine + // NB: transitioning from transitions is fine default: break; } } break; - //transitioning to any other anim is not supported + // transitioning to any other anim is not supported default: break; } } - if ( retmove == LS_NONE ) - { + if (retmove == LS_NONE) { return newmove; } @@ -4170,82 +3417,70 @@ PM_LegsAnimForFrame Returns animNumber for current frame ------------------------- */ -int PM_LegsAnimForFrame( gentity_t *ent, int legsFrame ) -{ - //Must be a valid client - if ( ent->client == NULL ) +int PM_LegsAnimForFrame(gentity_t *ent, int legsFrame) { + // Must be a valid client + if (ent->client == NULL) return -1; - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return -1; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - int glaIndex = gi.G2API_GetAnimIndex(&(ent->ghoul2[0])); + int glaIndex = gi.G2API_GetAnimIndex(&(ent->ghoul2[0])); - for ( int animation = 0; animation < BOTH_CIN_1; animation++ ) //first anim after last legs + for (int animation = 0; animation < BOTH_CIN_1; animation++) // first anim after last legs { - if ( animation >= TORSO_DROPWEAP1 && animation < LEGS_TURN1 ) //first legs only anim - {//not a possible legs anim + if (animation >= TORSO_DROPWEAP1 && animation < LEGS_TURN1) // first legs only anim + { // not a possible legs anim continue; } - if ( animations[animation].glaIndex != glaIndex ) - { + if (animations[animation].glaIndex != glaIndex) { continue; } - if ( animations[animation].firstFrame > legsFrame ) - {//This anim starts after this frame + if (animations[animation].firstFrame > legsFrame) { // This anim starts after this frame continue; } - if ( animations[animation].firstFrame + animations[animation].numFrames < legsFrame ) - {//This anim ends before this frame + if (animations[animation].firstFrame + animations[animation].numFrames < legsFrame) { // This anim ends before this frame continue; } - //else, must be in this anim! + // else, must be in this anim! return animation; } - //Not in ANY torsoAnim? SHOULD NEVER HAPPEN -// assert(0); + // Not in ANY torsoAnim? SHOULD NEVER HAPPEN + // assert(0); return -1; } -int PM_ValidateAnimRange( const int startFrame, const int endFrame, const float animSpeed ) -{//given a startframe and endframe, see if that lines up with any known animation +int PM_ValidateAnimRange(const int startFrame, const int endFrame, + const float animSpeed) { // given a startframe and endframe, see if that lines up with any known animation animation_t *animations = level.knownAnimFileSets[0].animations; - for ( int anim = 0; anim < MAX_ANIMATIONS; anim++ ) - { - if ( animSpeed < 0 ) - {//playing backwards - if ( animations[anim].firstFrame == endFrame ) - { - if ( animations[anim].numFrames + animations[anim].firstFrame == startFrame ) - { - //Com_Printf( "valid reverse anim: %s\n", animTable[anim].name ); + for (int anim = 0; anim < MAX_ANIMATIONS; anim++) { + if (animSpeed < 0) { // playing backwards + if (animations[anim].firstFrame == endFrame) { + if (animations[anim].numFrames + animations[anim].firstFrame == startFrame) { + // Com_Printf( "valid reverse anim: %s\n", animTable[anim].name ); return anim; } - } - } - else - {//playing forwards - if ( animations[anim].firstFrame == startFrame ) - {//This anim starts on this frame - if ( animations[anim].firstFrame + animations[anim].numFrames == endFrame ) - {//This anim ends on this frame - //Com_Printf( "valid forward anim: %s\n", animTable[anim].name ); + } + } else { // playing forwards + if (animations[anim].firstFrame == startFrame) { // This anim starts on this frame + if (animations[anim].firstFrame + animations[anim].numFrames == endFrame) { // This anim ends on this frame + // Com_Printf( "valid forward anim: %s\n", animTable[anim].name ); return anim; } } } - //else, must not be this anim! + // else, must not be this anim! } - //Not in ANY anim? SHOULD NEVER HAPPEN - Com_Printf( "invalid anim range %d to %d, speed %4.2f\n", startFrame, endFrame, animSpeed ); + // Not in ANY anim? SHOULD NEVER HAPPEN + Com_Printf("invalid anim range %d to %d, speed %4.2f\n", startFrame, endFrame, animSpeed); return -1; } /* @@ -4254,62 +3489,56 @@ PM_TorsoAnimForFrame Returns animNumber for current frame ------------------------- */ -int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ) -{ - //Must be a valid client - if ( ent->client == NULL ) +int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame) { + // Must be a valid client + if (ent->client == NULL) return -1; - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return -1; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - int glaIndex = gi.G2API_GetAnimIndex(&(ent->ghoul2[0])); + int glaIndex = gi.G2API_GetAnimIndex(&(ent->ghoul2[0])); - for ( int animation = 0; animation < LEGS_TURN1; animation++ ) //first legs only anim + for (int animation = 0; animation < LEGS_TURN1; animation++) // first legs only anim { - if ( animations[animation].glaIndex != glaIndex ) - { + if (animations[animation].glaIndex != glaIndex) { continue; } - if ( animations[animation].firstFrame > torsoFrame ) - {//This anim starts after this frame + if (animations[animation].firstFrame > torsoFrame) { // This anim starts after this frame continue; } - if ( animations[animation].firstFrame + animations[animation].numFrames < torsoFrame ) - {//This anim ends before this frame + if (animations[animation].firstFrame + animations[animation].numFrames < torsoFrame) { // This anim ends before this frame continue; } - //else, must be in this anim! + // else, must be in this anim! return animation; } - //Not in ANY torsoAnim? SHOULD NEVER HAPPEN -// assert(0); + // Not in ANY torsoAnim? SHOULD NEVER HAPPEN + // assert(0); return -1; } -qboolean PM_FinishedCurrentLegsAnim( gentity_t *self ) -{ - int junk, curFrame; - float currentFrame, animSpeed; +qboolean PM_FinishedCurrentLegsAnim(gentity_t *self) { + int junk, curFrame; + float currentFrame, animSpeed; - if ( !self->client ) - { + if (!self->client) { return qtrue; } - gi.G2API_GetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &animSpeed, NULL ); - curFrame = floor( currentFrame ); + gi.G2API_GetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, (cg.time ? cg.time : level.time), ¤tFrame, &junk, &junk, &junk, + &animSpeed, NULL); + curFrame = floor(currentFrame); - int legsAnim = self->client->ps.legsAnim; - animation_t *animations = level.knownAnimFileSets[self->client->clientInfo.animFileIndex].animations; + int legsAnim = self->client->ps.legsAnim; + animation_t *animations = level.knownAnimFileSets[self->client->clientInfo.animFileIndex].animations; - if ( curFrame >= animations[legsAnim].firstFrame + (animations[legsAnim].numFrames - 2) ) - { + if (curFrame >= animations[legsAnim].firstFrame + (animations[legsAnim].numFrames - 2)) { return qtrue; } @@ -4322,47 +3551,41 @@ PM_HasAnimation ------------------------- */ -qboolean PM_HasAnimation( gentity_t *ent, int animation ) -{ - //Must be a valid client - if ( !ent || ent->client == NULL ) +qboolean PM_HasAnimation(gentity_t *ent, int animation) { + // Must be a valid client + if (!ent || ent->client == NULL) return qfalse; - //must be a valid anim number - if ( animation < 0 || animation >= MAX_ANIMATIONS ) - { + // must be a valid anim number + if (animation < 0 || animation >= MAX_ANIMATIONS) { return qfalse; } - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return qfalse; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - //No frames, no anim - if ( animations[animation].numFrames == 0 ) + // No frames, no anim + if (animations[animation].numFrames == 0) return qfalse; - //Has the sequence + // Has the sequence return qtrue; } -int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ) -{ +int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim) { int anim; int count = 0; - if ( !self ) - { + if (!self) { return Q_irand(minAnim, maxAnim); } - do - { + do { anim = Q_irand(minAnim, maxAnim); count++; - } - while ( !PM_HasAnimation( self, anim ) && count < 1000 ); + } while (!PM_HasAnimation(self, anim) && count < 1000); return anim; } @@ -4373,12 +3596,12 @@ PM_AnimLength ------------------------- */ -int PM_AnimLength( int index, animNumber_t anim ) { - if ( !ValidAnimFileIndex( index ) || (int)anim < 0 || anim >= MAX_ANIMATIONS ) { +int PM_AnimLength(int index, animNumber_t anim) { + if (!ValidAnimFileIndex(index) || (int)anim < 0 || anim >= MAX_ANIMATIONS) { return 0; } - return level.knownAnimFileSets[index].animations[anim].numFrames * abs( level.knownAnimFileSets[index].animations[anim].frameLerp ); + return level.knownAnimFileSets[index].animations[anim].numFrames * abs(level.knownAnimFileSets[index].animations[anim].frameLerp); } /* @@ -4387,27 +3610,20 @@ PM_SetLegsAnimTimer ------------------------- */ -void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ) -{ +void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time) { *legsAnimTimer = time; - if ( *legsAnimTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional + if (*legsAnimTimer < 0 && time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional *legsAnimTimer = 0; } - if ( !*legsAnimTimer && ent && Q3_TaskIDPending( ent, TID_ANIM_LOWER ) ) - {//Waiting for legsAnimTimer to complete, and it just got set to zero - if ( !Q3_TaskIDPending( ent, TID_ANIM_BOTH) ) - {//Not waiting for top - Q3_TaskIDComplete( ent, TID_ANIM_LOWER ); - } - else - {//Waiting for both to finish before complete - Q3_TaskIDClear( &ent->taskID[TID_ANIM_LOWER] );//Bottom is done, regardless - if ( !Q3_TaskIDPending( ent, TID_ANIM_UPPER) ) - {//top is done and we're done - Q3_TaskIDComplete( ent, TID_ANIM_BOTH ); + if (!*legsAnimTimer && ent && Q3_TaskIDPending(ent, TID_ANIM_LOWER)) { // Waiting for legsAnimTimer to complete, and it just got set to zero + if (!Q3_TaskIDPending(ent, TID_ANIM_BOTH)) { // Not waiting for top + Q3_TaskIDComplete(ent, TID_ANIM_LOWER); + } else { // Waiting for both to finish before complete + Q3_TaskIDClear(&ent->taskID[TID_ANIM_LOWER]); // Bottom is done, regardless + if (!Q3_TaskIDPending(ent, TID_ANIM_UPPER)) { // top is done and we're done + Q3_TaskIDComplete(ent, TID_ANIM_BOTH); } } } @@ -4419,93 +3635,62 @@ PM_SetTorsoAnimTimer ------------------------- */ -void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ) -{ +void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time) { *torsoAnimTimer = time; - if ( *torsoAnimTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional + if (*torsoAnimTimer < 0 && time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional *torsoAnimTimer = 0; } - if ( !*torsoAnimTimer && ent && Q3_TaskIDPending( ent, TID_ANIM_UPPER ) ) - {//Waiting for torsoAnimTimer to complete, and it just got set to zero - if ( !Q3_TaskIDPending( ent, TID_ANIM_BOTH) ) - {//Not waiting for bottom - Q3_TaskIDComplete( ent, TID_ANIM_UPPER ); - } - else - {//Waiting for both to finish before complete - Q3_TaskIDClear( &ent->taskID[TID_ANIM_UPPER] );//Top is done, regardless - if ( !Q3_TaskIDPending( ent, TID_ANIM_LOWER) ) - {//lower is done and we're done - Q3_TaskIDComplete( ent, TID_ANIM_BOTH ); + if (!*torsoAnimTimer && ent && Q3_TaskIDPending(ent, TID_ANIM_UPPER)) { // Waiting for torsoAnimTimer to complete, and it just got set to zero + if (!Q3_TaskIDPending(ent, TID_ANIM_BOTH)) { // Not waiting for bottom + Q3_TaskIDComplete(ent, TID_ANIM_UPPER); + } else { // Waiting for both to finish before complete + Q3_TaskIDClear(&ent->taskID[TID_ANIM_UPPER]); // Top is done, regardless + if (!Q3_TaskIDPending(ent, TID_ANIM_LOWER)) { // lower is done and we're done + Q3_TaskIDComplete(ent, TID_ANIM_BOTH); } } } } -extern qboolean PM_SpinningSaberAnim( int anim ); +extern qboolean PM_SpinningSaberAnim(int anim); extern float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS]; -void PM_SaberStartTransAnim( int saberAnimLevel, int anim, float *animSpeed, gentity_t *gent ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_ROLL_STAB ) - { - if ( g_saberAnimSpeed->value != 1.0f ) - { +void PM_SaberStartTransAnim(int saberAnimLevel, int anim, float *animSpeed, gentity_t *gent) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_ROLL_STAB) { + if (g_saberAnimSpeed->value != 1.0f) { *animSpeed *= g_saberAnimSpeed->value; - } - else if ( gent && gent->client && gent->client->ps.weapon == WP_SABER ) - { - if ( gent->client->ps.saber[0].animSpeedScale != 1.0f ) - { + } else if (gent && gent->client && gent->client->ps.weapon == WP_SABER) { + if (gent->client->ps.saber[0].animSpeedScale != 1.0f) { *animSpeed *= gent->client->ps.saber[0].animSpeedScale; } - if ( gent->client->ps.dualSabers - && gent->client->ps.saber[1].animSpeedScale != 1.0f ) - { + if (gent->client->ps.dualSabers && gent->client->ps.saber[1].animSpeedScale != 1.0f) { *animSpeed *= gent->client->ps.saber[1].animSpeedScale; } } } - if ( gent - && gent->client - && gent->client->ps.stats[STAT_WEAPONS]&(1<client->ps.dualSabers - && saberAnimLevel == SS_DUAL - && gent->weaponModel[1] ) - {//using a scepter and dual style, slow down anims - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_H7_S7_BR ) - { + if (gent && gent->client && gent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER) && gent->client->ps.dualSabers && saberAnimLevel == SS_DUAL && + gent->weaponModel[1]) { // using a scepter and dual style, slow down anims + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_H7_S7_BR) { *animSpeed *= 0.75; } } - if ( gent && gent->client && gent->client->ps.forceRageRecoveryTime > level.time ) - {//rage recovery - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR ) - {//animate slower + if (gent && gent->client && gent->client->ps.forceRageRecoveryTime > level.time) { // rage recovery + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR) { // animate slower *animSpeed *= 0.75; } - } - else if ( gent && gent->NPC && gent->NPC->rank == RANK_CIVILIAN ) - {//grunt reborn - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1 ) - {//his fast attacks are slower - if ( !PM_SpinningSaberAnim( anim ) ) - { + } else if (gent && gent->NPC && gent->NPC->rank == RANK_CIVILIAN) { // grunt reborn + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1) { // his fast attacks are slower + if (!PM_SpinningSaberAnim(anim)) { *animSpeed *= 0.75; } return; } - } - else if ( gent && gent->client ) - { - if ( gent->client->ps.saber[0].type == SABER_LANCE || gent->client->ps.saber[0].type == SABER_TRIDENT ) - {//FIXME: hack for now - these use the fast anims, but slowed down. Should have own style - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1 ) - {//his fast attacks are slower - if ( !PM_SpinningSaberAnim( anim ) ) - { + } else if (gent && gent->client) { + if (gent->client->ps.saber[0].type == SABER_LANCE || + gent->client->ps.saber[0].type == SABER_TRIDENT) { // FIXME: hack for now - these use the fast anims, but slowed down. Should have own style + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1) { // his fast attacks are slower + if (!PM_SpinningSaberAnim(anim)) { *animSpeed *= 0.75; } return; @@ -4513,19 +3698,11 @@ void PM_SaberStartTransAnim( int saberAnimLevel, int anim, float *animSpeed, gen } } - if ( ( anim >= BOTH_T1_BR__R && - anim <= BOTH_T1_BL_TL ) || - ( anim >= BOTH_T3_BR__R && - anim <= BOTH_T3_BL_TL ) || - ( anim >= BOTH_T5_BR__R && - anim <= BOTH_T5_BL_TL ) ) - { - if ( saberAnimLevel == FORCE_LEVEL_1 || saberAnimLevel == FORCE_LEVEL_5 ) - {//FIXME: should not be necc for FORCE_LEVEL_1's + if ((anim >= BOTH_T1_BR__R && anim <= BOTH_T1_BL_TL) || (anim >= BOTH_T3_BR__R && anim <= BOTH_T3_BL_TL) || + (anim >= BOTH_T5_BR__R && anim <= BOTH_T5_BL_TL)) { + if (saberAnimLevel == FORCE_LEVEL_1 || saberAnimLevel == FORCE_LEVEL_5) { // FIXME: should not be necc for FORCE_LEVEL_1's *animSpeed *= 1.5; - } - else if ( saberAnimLevel == FORCE_LEVEL_3 ) - { + } else if (saberAnimLevel == FORCE_LEVEL_3) { *animSpeed *= 0.75; } } @@ -4575,23 +3752,15 @@ void PM_SaberStartTransAnim( int anim, int entNum, int saberOffenseLevel, float return; } */ -extern qboolean player_locked; -extern qboolean MatrixMode; -float PM_GetTimeScaleMod( gentity_t *gent ) -{ - if ( g_timescale->value ) - { - if ( !MatrixMode - && gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_START - && gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_ATTACK - && gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_LAND ) - { - if ( gent && gent->s.clientNum == 0 && !player_locked && gent->client->ps.forcePowersActive&(1<value) { + if (!MatrixMode && gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_START && gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_ATTACK && + gent->client->ps.legsAnim != BOTH_FORCELONGLEAP_LAND) { + if (gent && gent->s.clientNum == 0 && !player_locked && gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { return (1.0 / g_timescale->value); - } - else if ( gent && gent->client && gent->client->ps.forcePowersActive&(1<client && gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { return (1.0 / g_timescale->value); } } @@ -4599,14 +3768,12 @@ float PM_GetTimeScaleMod( gentity_t *gent ) return 1.0f; } -static inline qboolean PM_IsHumanoid( CGhoul2Info *ghlInfo ) -{ - char *GLAName; - GLAName = gi.G2API_GetGLAName( ghlInfo ); +static inline qboolean PM_IsHumanoid(CGhoul2Info *ghlInfo) { + char *GLAName; + GLAName = gi.G2API_GetGLAName(ghlInfo); assert(GLAName); - if ( !Q_stricmp( "models/players/_humanoid/_humanoid", GLAName ) ) - { + if (!Q_stricmp("models/players/_humanoid/_humanoid", GLAName)) { return qtrue; } @@ -4619,124 +3786,104 @@ PM_SetAnimFinal ------------------------- */ #define G2_DEBUG_TIMING (0) -void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, - int setAnimParts,int anim,int setAnimFlags, - int *torsoAnimTimer,int *legsAnimTimer, - gentity_t *gent,int blendTime) // default blendTime=350 +void PM_SetAnimFinal(int *torsoAnim, int *legsAnim, int setAnimParts, int anim, int setAnimFlags, int *torsoAnimTimer, int *legsAnimTimer, gentity_t *gent, + int blendTime) // default blendTime=350 { -// BASIC SETUP AND SAFETY CHECKING -//================================= + // BASIC SETUP AND SAFETY CHECKING + //================================= // If It Is A Busted Entity, Don't Do Anything Here. //--------------------------------------------------- - if (!gent || !gent->client) - { + if (!gent || !gent->client) { return; } // Make Sure This Character Has Such An Anim And A Model //------------------------------------------------------- - if (anim<0 || anim>=MAX_ANIMATIONS || !ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) - { - #ifndef FINAL_BUILD - if (g_AnimWarning->integer) - { - if (anim<0 || anim>=MAX_ANIMATIONS) - { - gi.Printf(S_COLOR_RED"PM_SetAnimFinal: Invalid Anim Index (%d)!\n", anim); - } - else - { - gi.Printf(S_COLOR_RED"PM_SetAnimFinal: Invalid Anim File Index (%d)!\n", gent->client->clientInfo.animFileIndex); + if (anim < 0 || anim >= MAX_ANIMATIONS || !ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) { +#ifndef FINAL_BUILD + if (g_AnimWarning->integer) { + if (anim < 0 || anim >= MAX_ANIMATIONS) { + gi.Printf(S_COLOR_RED "PM_SetAnimFinal: Invalid Anim Index (%d)!\n", anim); + } else { + gi.Printf(S_COLOR_RED "PM_SetAnimFinal: Invalid Anim File Index (%d)!\n", gent->client->clientInfo.animFileIndex); } } - #endif +#endif return; } - // Get Global Time Properties //---------------------------- - float timeScaleMod = PM_GetTimeScaleMod( gent ); - const int actualTime = (cg.time?cg.time:level.time); - const animation_t* animations = level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations; - const animation_t& curAnim = animations[anim]; + float timeScaleMod = PM_GetTimeScaleMod(gent); + const int actualTime = (cg.time ? cg.time : level.time); + const animation_t *animations = level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations; + const animation_t &curAnim = animations[anim]; // Make Sure This Character Has Such An Anim And A Model //------------------------------------------------------- - if (animations[anim].numFrames==0) - { - #ifndef FINAL_BUILD - static int LastAnimWarningNum=0; - if (LastAnimWarningNum!=anim) - { - if ((cg_debugAnim.integer==3) || // 3 = do everyone - (cg_debugAnim.integer==1 && gent->s.number==0) || // 1 = only the player - (cg_debugAnim.integer==2 && gent->s.number!=0) || // 2 = only everyone else - (cg_debugAnim.integer==4 && gent->s.number!=cg_debugAnimTarget.integer) // 4 = specific entnum - ) - { - gi.Printf(S_COLOR_RED"PM_SetAnimFinal: Anim %s does not exist in this model (%s)!\n", animTable[anim].name, gent->NPC_type ); + if (animations[anim].numFrames == 0) { +#ifndef FINAL_BUILD + static int LastAnimWarningNum = 0; + if (LastAnimWarningNum != anim) { + if ((cg_debugAnim.integer == 3) || // 3 = do everyone + (cg_debugAnim.integer == 1 && gent->s.number == 0) || // 1 = only the player + (cg_debugAnim.integer == 2 && gent->s.number != 0) || // 2 = only everyone else + (cg_debugAnim.integer == 4 && gent->s.number != cg_debugAnimTarget.integer) // 4 = specific entnum + ) { + gi.Printf(S_COLOR_RED "PM_SetAnimFinal: Anim %s does not exist in this model (%s)!\n", animTable[anim].name, gent->NPC_type); } } LastAnimWarningNum = anim; - #endif +#endif return; } // If It's Not A Ghoul 2 Model, Just Remember The Anims And Stop, Because Everything Beyond This Is Ghoul2 //--------------------------------------------------------------------------------------------------------- - if (!gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) - { - if (setAnimParts&SETANIM_TORSO) - { + if (!gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) { + if (setAnimParts & SETANIM_TORSO) { (*torsoAnim) = anim; } - if (setAnimParts&SETANIM_LEGS) - { + if (setAnimParts & SETANIM_LEGS) { (*legsAnim) = anim; } return; } - // Lower Offensive Skill Slows Down The Saber Start Attack Animations //-------------------------------------------------------------------- - PM_SaberStartTransAnim( gent->client->ps.saberAnimLevel, anim, &timeScaleMod, gent ); - - - -// SETUP VALUES FOR INCOMMING ANIMATION -//====================================== - const bool animFootMove = (PM_WalkingAnim(anim) || PM_RunningAnim(anim) || anim==BOTH_CROUCH1WALK || anim==BOTH_CROUCH1WALKBACK); - const bool animHoldless = (setAnimFlags&SETANIM_FLAG_HOLDLESS)!=0; - const bool animHold = (setAnimFlags&SETANIM_FLAG_HOLD)!=0; - const bool animRestart = (setAnimFlags&SETANIM_FLAG_RESTART)!=0; - const bool animOverride = (setAnimFlags&SETANIM_FLAG_OVERRIDE)!=0; - const bool animSync = (g_synchSplitAnims->integer!=0 && !animRestart); - float animCurrent = (-1.0f); - float animSpeed = (50.0f / curAnim.frameLerp * timeScaleMod); // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). - const float animFPS = (::abs(curAnim.frameLerp)); - const int animDurMSec = (int)(((curAnim.numFrames - 1) * animFPS) / timeScaleMod); - const int animHoldMSec = ((animHoldless && timeScaleMod==1.0f)?((animDurMSec>1)?(animDurMSec-1):(animFPS)):(animDurMSec)); - int animFlags = (curAnim.loopFrames!=-1)?(BONE_ANIM_OVERRIDE_LOOP):(BONE_ANIM_OVERRIDE_FREEZE); - int animStart = (curAnim.firstFrame); - int animEnd = (curAnim.firstFrame)+(animations[anim].numFrames); + PM_SaberStartTransAnim(gent->client->ps.saberAnimLevel, anim, &timeScaleMod, gent); + + // SETUP VALUES FOR INCOMMING ANIMATION + //====================================== + const bool animFootMove = (PM_WalkingAnim(anim) || PM_RunningAnim(anim) || anim == BOTH_CROUCH1WALK || anim == BOTH_CROUCH1WALKBACK); + const bool animHoldless = (setAnimFlags & SETANIM_FLAG_HOLDLESS) != 0; + const bool animHold = (setAnimFlags & SETANIM_FLAG_HOLD) != 0; + const bool animRestart = (setAnimFlags & SETANIM_FLAG_RESTART) != 0; + const bool animOverride = (setAnimFlags & SETANIM_FLAG_OVERRIDE) != 0; + const bool animSync = (g_synchSplitAnims->integer != 0 && !animRestart); + float animCurrent = (-1.0f); + float animSpeed = (50.0f / curAnim.frameLerp * timeScaleMod); // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). + const float animFPS = (::abs(curAnim.frameLerp)); + const int animDurMSec = (int)(((curAnim.numFrames - 1) * animFPS) / timeScaleMod); + const int animHoldMSec = ((animHoldless && timeScaleMod == 1.0f) ? ((animDurMSec > 1) ? (animDurMSec - 1) : (animFPS)) : (animDurMSec)); + int animFlags = (curAnim.loopFrames != -1) ? (BONE_ANIM_OVERRIDE_LOOP) : (BONE_ANIM_OVERRIDE_FREEZE); + int animStart = (curAnim.firstFrame); + int animEnd = (curAnim.firstFrame) + (animations[anim].numFrames); // If We Have A Blend Timer, Add The Blend Flag //---------------------------------------------- - if (blendTime > 0) - { + if (blendTime > 0) { animFlags |= BONE_ANIM_BLEND; } // If Animation Is Going Backwards, Swap Last And First Frames //------------------------------------------------------------- - if (animSpeed<0.0f) - { -// #ifndef FINAL_BUILD - #if 0 + if (animSpeed < 0.0f) { + // #ifndef FINAL_BUILD +#if 0 if (g_AnimWarning->integer==1) { if (animFlags&BONE_ANIM_OVERRIDE_LOOP) @@ -4744,394 +3891,283 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, gi.Printf(S_COLOR_YELLOW"PM_SetAnimFinal: WARNING: Anim (%s) looping backwards!\n", animTable[anim].name); } } - #endif +#endif - int temp = animEnd; - animEnd = animStart; - animStart = temp; - blendTime = 0; + int temp = animEnd; + animEnd = animStart; + animStart = temp; + blendTime = 0; } // If The Animation Is Walking Or Running, Attempt To Scale The Playback Speed To Match //-------------------------------------------------------------------------------------- - if (g_noFootSlide->integer - && animFootMove - && !(animSpeed<0.0f) - //FIXME: either read speed from animation.cfg or only do this for NPCs + if (g_noFootSlide->integer && animFootMove && + !(animSpeed < 0.0f) + // FIXME: either read speed from animation.cfg or only do this for NPCs // for whom we've specifically determined the proper numbers! - && gent->client->NPC_class != CLASS_HOWLER - && gent->client->NPC_class != CLASS_WAMPA - && gent->client->NPC_class != CLASS_GONK - && gent->client->NPC_class != CLASS_HOWLER - && gent->client->NPC_class != CLASS_MOUSE - && gent->client->NPC_class != CLASS_PROBE - && gent->client->NPC_class != CLASS_PROTOCOL - && gent->client->NPC_class != CLASS_R2D2 - && gent->client->NPC_class != CLASS_R5D2 - && gent->client->NPC_class != CLASS_SEEKER) - { - bool Walking = !!PM_WalkingAnim(anim); - bool HasDual = (gent->client->ps.saberAnimLevel==SS_DUAL); - bool HasStaff = (gent->client->ps.saberAnimLevel==SS_STAFF); - float moveSpeedOfAnim = 150.0f;//g_noFootSlideRunScale->value; - - if (anim==BOTH_CROUCH1WALK || anim==BOTH_CROUCH1WALKBACK) - { + && gent->client->NPC_class != CLASS_HOWLER && gent->client->NPC_class != CLASS_WAMPA && gent->client->NPC_class != CLASS_GONK && + gent->client->NPC_class != CLASS_HOWLER && gent->client->NPC_class != CLASS_MOUSE && gent->client->NPC_class != CLASS_PROBE && + gent->client->NPC_class != CLASS_PROTOCOL && gent->client->NPC_class != CLASS_R2D2 && gent->client->NPC_class != CLASS_R5D2 && + gent->client->NPC_class != CLASS_SEEKER) { + bool Walking = !!PM_WalkingAnim(anim); + bool HasDual = (gent->client->ps.saberAnimLevel == SS_DUAL); + bool HasStaff = (gent->client->ps.saberAnimLevel == SS_STAFF); + float moveSpeedOfAnim = 150.0f; // g_noFootSlideRunScale->value; + + if (anim == BOTH_CROUCH1WALK || anim == BOTH_CROUCH1WALKBACK) { moveSpeedOfAnim = 75.0f; - } - else - { - if (gent->client->NPC_class == CLASS_HAZARD_TROOPER) - { + } else { + if (gent->client->NPC_class == CLASS_HAZARD_TROOPER) { moveSpeedOfAnim = 50.0f; - } - else if (gent->client->NPC_class == CLASS_RANCOR) - { + } else if (gent->client->NPC_class == CLASS_RANCOR) { moveSpeedOfAnim = 173.0f; - } - else - { - if (Walking) - { - if (HasDual || HasStaff) - { + } else { + if (Walking) { + if (HasDual || HasStaff) { moveSpeedOfAnim = 100.0f; + } else { + moveSpeedOfAnim = 50.0f; // g_noFootSlideWalkScale->value; } - else - { - moveSpeedOfAnim = 50.0f;// g_noFootSlideWalkScale->value; - } - } - else - { - if (HasStaff) - { + } else { + if (HasStaff) { moveSpeedOfAnim = 250.0f; - } - else - { + } else { moveSpeedOfAnim = 150.0f; } } } } - - - - - - animSpeed *= (gent->resultspeed/moveSpeedOfAnim); - if (animSpeed<0.01f) - { + animSpeed *= (gent->resultspeed / moveSpeedOfAnim); + if (animSpeed < 0.01f) { animSpeed = 0.01f; } // Make Sure Not To Play Too Fast An Anim //---------------------------------------- - float maxPlaybackSpeed = (1.5f * timeScaleMod); - if (animSpeed>maxPlaybackSpeed) - { + float maxPlaybackSpeed = (1.5f * timeScaleMod); + if (animSpeed > maxPlaybackSpeed) { animSpeed = maxPlaybackSpeed; } } - -// GET VALUES FOR EXISTING BODY ANIMATION -//========================================== - float bodySpeed = 0.0f; - float bodyCurrent = 0.0f; - int bodyStart = 0; - int bodyEnd = 0; - int bodyFlags = 0; - int bodyAnim = (*legsAnim); - int bodyBone = (gent->rootBone); - bool bodyTimerOn = ((*legsAnimTimer>0) || (*legsAnimTimer)==-1); - bool bodyPlay = ((setAnimParts&SETANIM_LEGS) && (bodyBone!=-1) && (animOverride || !bodyTimerOn)); - bool bodyAnimating = !!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], bodyBone, actualTime, &bodyCurrent, &bodyStart, &bodyEnd, &bodyFlags, &bodySpeed, NULL); - bool bodyOnAnimNow = (bodyAnimating && bodyAnim==anim && bodyStart==animStart && bodyEnd==animEnd); - bool bodyMatchTorsFrame = false; - - -// GET VALUES FOR EXISTING TORSO ANIMATION -//=========================================== - float torsSpeed = 0.0f; - float torsCurrent = 0.0f; - int torsStart = 0; - int torsEnd = 0; - int torsFlags = 0; - int torsAnim = (*torsoAnim); - int torsBone = (gent->lowerLumbarBone); - bool torsTimerOn = ((*torsoAnimTimer)>0 || (*torsoAnimTimer)==-1); - bool torsPlay = (gent->client->NPC_class!=CLASS_RANCOR && (setAnimParts&SETANIM_TORSO) && (torsBone!=-1) && (animOverride || !torsTimerOn)); - bool torsAnimating = !!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], torsBone, actualTime, &torsCurrent, &torsStart, &torsEnd, &torsFlags, &torsSpeed, NULL); - bool torsOnAnimNow = (torsAnimating && torsAnim==anim && torsStart==animStart && torsEnd==animEnd); - bool torsMatchBodyFrame = false; - - -// APPLY SYNC TO TORSO -//===================== - if (animSync && torsPlay && !bodyPlay && bodyOnAnimNow && (!torsOnAnimNow || torsCurrent!=bodyCurrent)) - { + // GET VALUES FOR EXISTING BODY ANIMATION + //========================================== + float bodySpeed = 0.0f; + float bodyCurrent = 0.0f; + int bodyStart = 0; + int bodyEnd = 0; + int bodyFlags = 0; + int bodyAnim = (*legsAnim); + int bodyBone = (gent->rootBone); + bool bodyTimerOn = ((*legsAnimTimer > 0) || (*legsAnimTimer) == -1); + bool bodyPlay = ((setAnimParts & SETANIM_LEGS) && (bodyBone != -1) && (animOverride || !bodyTimerOn)); + bool bodyAnimating = + !!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], bodyBone, actualTime, &bodyCurrent, &bodyStart, &bodyEnd, &bodyFlags, &bodySpeed, NULL); + bool bodyOnAnimNow = (bodyAnimating && bodyAnim == anim && bodyStart == animStart && bodyEnd == animEnd); + bool bodyMatchTorsFrame = false; + + // GET VALUES FOR EXISTING TORSO ANIMATION + //=========================================== + float torsSpeed = 0.0f; + float torsCurrent = 0.0f; + int torsStart = 0; + int torsEnd = 0; + int torsFlags = 0; + int torsAnim = (*torsoAnim); + int torsBone = (gent->lowerLumbarBone); + bool torsTimerOn = ((*torsoAnimTimer) > 0 || (*torsoAnimTimer) == -1); + bool torsPlay = (gent->client->NPC_class != CLASS_RANCOR && (setAnimParts & SETANIM_TORSO) && (torsBone != -1) && (animOverride || !torsTimerOn)); + bool torsAnimating = + !!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], torsBone, actualTime, &torsCurrent, &torsStart, &torsEnd, &torsFlags, &torsSpeed, NULL); + bool torsOnAnimNow = (torsAnimating && torsAnim == anim && torsStart == animStart && torsEnd == animEnd); + bool torsMatchBodyFrame = false; + + // APPLY SYNC TO TORSO + //===================== + if (animSync && torsPlay && !bodyPlay && bodyOnAnimNow && (!torsOnAnimNow || torsCurrent != bodyCurrent)) { torsMatchBodyFrame = true; - animCurrent = bodyCurrent; + animCurrent = bodyCurrent; } - if (animSync && bodyPlay && !torsPlay && torsOnAnimNow && (!bodyOnAnimNow || bodyCurrent!=torsCurrent)) - { + if (animSync && bodyPlay && !torsPlay && torsOnAnimNow && (!bodyOnAnimNow || bodyCurrent != torsCurrent)) { bodyMatchTorsFrame = true; - animCurrent = torsCurrent; + animCurrent = torsCurrent; } // If Already Doing These Exact Parameters, Then Don't Play //---------------------------------------------------------- - if (!animRestart) - { - torsPlay &= !(torsOnAnimNow && torsSpeed==animSpeed && !torsMatchBodyFrame); - bodyPlay &= !(bodyOnAnimNow && bodySpeed==animSpeed && !bodyMatchTorsFrame); + if (!animRestart) { + torsPlay &= !(torsOnAnimNow && torsSpeed == animSpeed && !torsMatchBodyFrame); + bodyPlay &= !(bodyOnAnimNow && bodySpeed == animSpeed && !bodyMatchTorsFrame); } #ifndef FINAL_BUILD - if ((cg_debugAnim.integer==3) || // 3 = do everyone - (cg_debugAnim.integer==1 && gent->s.number==0) || // 1 = only the player - (cg_debugAnim.integer==2 && gent->s.number!=0) || // 2 = only everyone else - (cg_debugAnim.integer==4 && gent->s.number!=cg_debugAnimTarget.integer) // 4 = specific entnum - ) - { - if (bodyPlay || torsPlay) - { - char* entName = gent->targetname; - char* location; + if ((cg_debugAnim.integer == 3) || // 3 = do everyone + (cg_debugAnim.integer == 1 && gent->s.number == 0) || // 1 = only the player + (cg_debugAnim.integer == 2 && gent->s.number != 0) || // 2 = only everyone else + (cg_debugAnim.integer == 4 && gent->s.number != cg_debugAnimTarget.integer) // 4 = specific entnum + ) { + if (bodyPlay || torsPlay) { + char *entName = gent->targetname; + char *location; // Select Entity Name //-------------------- - if (!entName || !entName[0]) - { + if (!entName || !entName[0]) { entName = gent->NPC_targetname; } - if (!entName || !entName[0]) - { + if (!entName || !entName[0]) { entName = gent->NPC_type; } - if (!entName || !entName[0]) - { + if (!entName || !entName[0]) { entName = gent->classname; } - if (!entName || !entName[0]) - { + if (!entName || !entName[0]) { entName = "UNKNOWN"; } // Select Play Location //---------------------- - if (bodyPlay && torsPlay) - { + if (bodyPlay && torsPlay) { location = "BOTH "; - } - else if (bodyPlay) - { + } else if (bodyPlay) { location = "LEGS "; - } - else - { + } else { location = "TORSO"; } // Print It! //----------- - Com_Printf("[%10d] ent[%3d-%18s] %s anim[%3d] - %s\n", - actualTime, - gent->s.number, - entName, - location, - anim, - animTable[anim].name ); + Com_Printf("[%10d] ent[%3d-%18s] %s anim[%3d] - %s\n", actualTime, gent->s.number, entName, location, anim, animTable[anim].name); } } #endif - -// PLAY ON THE TORSO -//======================== - if (torsPlay) - { + // PLAY ON THE TORSO + //======================== + if (torsPlay) { *torsoAnim = anim; float oldAnimCurrent = animCurrent; - if (animCurrent!=bodyCurrent && torsOnAnimNow && !animRestart && !torsMatchBodyFrame) - { + if (animCurrent != bodyCurrent && torsOnAnimNow && !animRestart && !torsMatchBodyFrame) { animCurrent = torsCurrent; } gi.G2API_SetAnimIndex(&gent->ghoul2[gent->playerModel], curAnim.glaIndex); - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], torsBone, - animStart, - animEnd, - (torsOnAnimNow && !animRestart)?(animFlags&~BONE_ANIM_BLEND):(animFlags), - animSpeed, - actualTime, - animCurrent, - blendTime); - - if (gent->motionBone!=-1) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, - animStart, - animEnd, - (torsOnAnimNow && !animRestart)?(animFlags&~BONE_ANIM_BLEND):(animFlags), - animSpeed, - actualTime, - animCurrent, - blendTime); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], torsBone, animStart, animEnd, + (torsOnAnimNow && !animRestart) ? (animFlags & ~BONE_ANIM_BLEND) : (animFlags), animSpeed, actualTime, animCurrent, + blendTime); + + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, animStart, animEnd, + (torsOnAnimNow && !animRestart) ? (animFlags & ~BONE_ANIM_BLEND) : (animFlags), animSpeed, actualTime, animCurrent, + blendTime); } animCurrent = oldAnimCurrent; // If This Animation Is To Be Locked And Held, Calculate The Duration And Set The Timer //-------------------------------------------------------------------------------------- - if (animHold || animHoldless) - { + if (animHold || animHoldless) { PM_SetTorsoAnimTimer(gent, torsoAnimTimer, animHoldMSec); } } -// PLAY ON THE WHOLE BODY -//======================== - if (bodyPlay) - { + // PLAY ON THE WHOLE BODY + //======================== + if (bodyPlay) { *legsAnim = anim; - if (bodyOnAnimNow && !animRestart && !bodyMatchTorsFrame) - { + if (bodyOnAnimNow && !animRestart && !bodyMatchTorsFrame) { animCurrent = bodyCurrent; } gi.G2API_SetAnimIndex(&gent->ghoul2[gent->playerModel], curAnim.glaIndex); - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], bodyBone, - animStart, - animEnd, - (bodyOnAnimNow && !animRestart)?(animFlags&~BONE_ANIM_BLEND):(animFlags), - animSpeed, - actualTime, - animCurrent, - blendTime); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], bodyBone, animStart, animEnd, + (bodyOnAnimNow && !animRestart) ? (animFlags & ~BONE_ANIM_BLEND) : (animFlags), animSpeed, actualTime, animCurrent, + blendTime); // If This Animation Is To Be Locked And Held, Calculate The Duration And Set The Timer //-------------------------------------------------------------------------------------- - if (animHold || animHoldless) - { + if (animHold || animHoldless) { PM_SetLegsAnimTimer(gent, legsAnimTimer, animHoldMSec); } } - - - - -// PRINT SOME DEBUG TEXT OF EXISTING VALUES -//========================================== - if (false) - { + // PRINT SOME DEBUG TEXT OF EXISTING VALUES + //========================================== + if (false) { gi.Printf("PLAYANIM: (%3d) Speed(%4.2f) ", anim, animSpeed); - if (bodyAnimating) - { - gi.Printf("BODY: (%4.2f) (%4.2f) ", bodyCurrent, bodySpeed); - } - else - { + if (bodyAnimating) { + gi.Printf("BODY: (%4.2f) (%4.2f) ", bodyCurrent, bodySpeed); + } else { gi.Printf(" "); } - if (torsAnimating) - { - gi.Printf("TORS: (%4.2f) (%4.2f)\n", torsCurrent, torsSpeed); - } - else - { + if (torsAnimating) { + gi.Printf("TORS: (%4.2f) (%4.2f)\n", torsCurrent, torsSpeed); + } else { gi.Printf("\n"); } } } - - -void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime) -{ // FIXME : once torsoAnim and legsAnim are in the same structure for NPC and Players +void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, + int blendTime) { // FIXME : once torsoAnim and legsAnim are in the same structure for NPC and Players // rename PM_SetAnimFinal to PM_SetAnim and have both NPC and Players call PM_SetAnim - if ( pm->ps->pm_type >= PM_DEAD ) - {//FIXME: sometimes we'll want to set anims when your dead... twitches, impacts, etc. + if (pm->ps->pm_type >= PM_DEAD) { // FIXME: sometimes we'll want to set anims when your dead... twitches, impacts, etc. return; } - if ( pm->gent == NULL ) - { + if (pm->gent == NULL) { return; } - if ( !pm->gent || pm->gent->health > 0 ) - {//don't lock anims if the guy is dead - if ( pm->ps->torsoAnimTimer - && PM_LockedAnim( pm->ps->torsoAnim ) - && !PM_LockedAnim( anim ) ) - {//nothing can override these special anims + if (!pm->gent || pm->gent->health > 0) { // don't lock anims if the guy is dead + if (pm->ps->torsoAnimTimer && PM_LockedAnim(pm->ps->torsoAnim) && !PM_LockedAnim(anim)) { // nothing can override these special anims setAnimParts &= ~SETANIM_TORSO; } - if ( pm->ps->legsAnimTimer - && PM_LockedAnim( pm->ps->legsAnim ) - && !PM_LockedAnim( anim ) ) - {//nothing can override these special anims + if (pm->ps->legsAnimTimer && PM_LockedAnim(pm->ps->legsAnim) && !PM_LockedAnim(anim)) { // nothing can override these special anims setAnimParts &= ~SETANIM_LEGS; } } - if ( !setAnimParts ) - { + if (!setAnimParts) { return; } - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { -// pm->ps->animationTimer = 0; + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + // pm->ps->animationTimer = 0; - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( pm->gent, &pm->ps->torsoAnimTimer, 0 ); + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->torsoAnim != anim) { + PM_SetTorsoAnimTimer(pm->gent, &pm->ps->torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->legsAnim != anim ) - { - PM_SetLegsAnimTimer( pm->gent, &pm->ps->legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->legsAnim != anim) { + PM_SetLegsAnimTimer(pm->gent, &pm->ps->legsAnimTimer, 0); } } } - PM_SetAnimFinal(&pm->ps->torsoAnim,&pm->ps->legsAnim,setAnimParts,anim,setAnimFlags,&pm->ps->torsoAnimTimer,&pm->ps->legsAnimTimer,&g_entities[pm->ps->clientNum],blendTime);//was pm->gent + PM_SetAnimFinal(&pm->ps->torsoAnim, &pm->ps->legsAnim, setAnimParts, anim, setAnimFlags, &pm->ps->torsoAnimTimer, &pm->ps->legsAnimTimer, + &g_entities[pm->ps->clientNum], blendTime); // was pm->gent } -bool TorsoAgainstWindTest( gentity_t* ent ) -{ - if (ent&&//valid ent - ent->client&&//a client - (ent->client->ps.weapon!=WP_SABER||ent->client->ps.saberMove==LS_READY)&&//either not holding a saber or the saber is in the ready pose - (ent->s.numbercurrentOrigin) && - gi.WE_IsOutside(ent->currentOrigin) ) - { - if (Q_stricmp(level.mapname, "t2_wedge")!=0) - { - vec3_t fwd; - vec3_t windDir; - if (gi.WE_GetWindVector(windDir, ent->currentOrigin)) - { +bool TorsoAgainstWindTest(gentity_t *ent) { + if (ent && // valid ent + ent->client && // a client + (ent->client->ps.weapon != WP_SABER || ent->client->ps.saberMove == LS_READY) && // either not holding a saber or the saber is in the ready pose + (ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent)) && gi.WE_GetWindGusting(ent->currentOrigin) && gi.WE_IsOutside(ent->currentOrigin)) { + if (Q_stricmp(level.mapname, "t2_wedge") != 0) { + vec3_t fwd; + vec3_t windDir; + if (gi.WE_GetWindVector(windDir, ent->currentOrigin)) { VectorScale(windDir, -1.0f, windDir); AngleVectors(pm->gent->currentAngles, fwd, 0, 0); - if (DotProduct(fwd, windDir)>0.65f) - { - if (ent->client && ent->client->ps.torsoAnim!=BOTH_WIND) - { + if (DotProduct(fwd, windDir) > 0.65f) { + if (ent->client && ent->client->ps.torsoAnim != BOTH_WIND) { NPC_SetAnim(ent, SETANIM_TORSO, BOTH_WIND, SETANIM_FLAG_NORMAL, 400); } return true; @@ -5148,110 +4184,72 @@ PM_TorsoAnimLightsaber ------------------------- */ - // Note that this function is intended to set the animation for the player, but // only does idle-ish anims. Anything that has a timer associated, such as attacks and blocks, // are set by PM_WeaponLightsaber() -extern Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ); -extern qboolean PM_LandingAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); -qboolean PM_InCartwheel( int anim ); -void PM_TorsoAnimLightsaber() -{ +extern Vehicle_t *G_IsRidingVehicle(gentity_t *pEnt); +extern qboolean PM_LandingAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); +qboolean PM_InCartwheel(int anim); +void PM_TorsoAnimLightsaber() { // ********************************************************* // WEAPON_READY // ********************************************************* - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip + if (pm->ps->forcePowersActive & (1 << FP_GRIP) && pm->ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//lightning + if (pm->ps->forcePowersActive & (1 << FP_LIGHTNING) && pm->ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // lightning return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowersActive & (1 << FP_DRAIN)) { // drain return; } - if ( pm->ps->saber[0].blade[0].active - && pm->ps->saber[0].blade[0].length < 3 - && !(pm->ps->saberEventFlags&SEF_HITWALL) - && pm->ps->weaponstate == WEAPON_RAISING ) - { - if (!G_IsRidingVehicle(pm->gent)) - { + if (pm->ps->saber[0].blade[0].active && pm->ps->saber[0].blade[0].length < 3 && !(pm->ps->saberEventFlags & SEF_HITWALL) && + pm->ps->weaponstate == WEAPON_RAISING) { + if (!G_IsRidingVehicle(pm->gent)) { PM_SetSaberMove(LS_DRAW); } return; - } - else if ( !pm->ps->SaberActive() && pm->ps->SaberLength() ) - { - if (!G_IsRidingVehicle(pm->gent)) - { + } else if (!pm->ps->SaberActive() && pm->ps->SaberLength()) { + if (!G_IsRidingVehicle(pm->gent)) { PM_SetSaberMove(LS_PUTAWAY); } return; } - if (pm->ps->weaponTime > 0) - { // weapon is already busy. - if ( pm->ps->torsoAnim == BOTH_TOSS1 - || pm->ps->torsoAnim == BOTH_TOSS2 ) - {//in toss - if ( !pm->ps->torsoAnimTimer ) - {//weird, get out of it, I guess - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + if (pm->ps->weaponTime > 0) { // weapon is already busy. + if (pm->ps->torsoAnim == BOTH_TOSS1 || pm->ps->torsoAnim == BOTH_TOSS2) { // in toss + if (!pm->ps->torsoAnimTimer) { // weird, get out of it, I guess + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); } } return; } - if ( pm->ps->weaponstate == WEAPON_READY || - pm->ps->weaponstate == WEAPON_CHARGING || - pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - {//ready - if ( pm->ps->weapon == WP_SABER && (pm->ps->SaberLength()) ) - {//saber is on + if (pm->ps->weaponstate == WEAPON_READY || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) { // ready + if (pm->ps->weapon == WP_SABER && (pm->ps->SaberLength())) { // saber is on // Select the proper idle Lightsaber attack move from the chart. - if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); - } - else - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - if ( (PM_RunningAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_WALK_STAFF - || pm->ps->legsAnim == BOTH_WALK_DUAL - || pm->ps->legsAnim == BOTH_WALKBACK_STAFF - || pm->ps->legsAnim == BOTH_WALKBACK_DUAL ) - && pm->ps->saberBlockingTime < cg.time ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { + } else { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || + PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + if ((PM_RunningAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_WALK_STAFF || pm->ps->legsAnim == BOTH_WALK_DUAL || + pm->ps->legsAnim == BOTH_WALKBACK_STAFF || pm->ps->legsAnim == BOTH_WALKBACK_DUAL) && + pm->ps->saberBlockingTime < cg.time) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { PM_SetSaberMove(LS_READY); } } @@ -5270,89 +4268,55 @@ void PM_TorsoAnimLightsaber() PM_SetSaberMove( LS_READY ); } */ - } - else if (TorsoAgainstWindTest(pm->gent)) - { - } - else if( pm->ps->legsAnim == BOTH_RUN1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); + } else if (TorsoAgainstWindTest(pm->gent)) { + } else if (pm->ps->legsAnim == BOTH_RUN1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_RUN2 )//&& pm->ps->saberAnimLevel != SS_STAFF ) + } else if (pm->ps->legsAnim == BOTH_RUN2) //&& pm->ps->saberAnimLevel != SS_STAFF ) { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_RUN_STAFF ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN_STAFF,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_STAFF) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN_STAFF, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_RUN_DUAL ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN_DUAL,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_DUAL) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN_DUAL, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK_STAFF ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK_STAFF,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_STAFF) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK_STAFF, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK_DUAL ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK_DUAL,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_DUAL) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK_DUAL, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0 )//player falls through + } else if (pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0) // player falls through { //??? Why nothing? What if you were running??? - //PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_JUMP1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_JUMP1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_JUMP1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_JUMP1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else - {//Used to default to both_stand1 which is an arms-down anim -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 + } else { // Used to default to both_stand1 which is an arms-down anim + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 // Select the next proper pose for the lightsaber assuming that there are no attacks. - if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); - } - else - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { + } else { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || + PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { PM_SetSaberMove(LS_READY); } } @@ -5364,136 +4328,85 @@ void PM_TorsoAnimLightsaber() // WEAPON_IDLE // ********************************************************* - else if ( pm->ps->weaponstate == WEAPON_IDLE ) - { - if (TorsoAgainstWindTest(pm->gent)) - { - } - else if( pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_LOOKAROUND1,SETANIM_FLAG_NORMAL); + else if (pm->ps->weaponstate == WEAPON_IDLE) { + if (TorsoAgainstWindTest(pm->gent)) { + } else if (pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_GUARD_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_IDLE1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_GUARD_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND1IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE2 - || pm->ps->legsAnim == BOTH_STAND3IDLE1 - || pm->ps->legsAnim == BOTH_STAND5IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND1IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE2 || + pm->ps->legsAnim == BOTH_STAND3IDLE1 || pm->ps->legsAnim == BOTH_STAND5IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND2TO4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2TO4,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND2TO4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2TO4, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND4TO2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4TO2,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4TO2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4TO2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else - { -// This is now set in SetSaberMove. + } else { + // This is now set in SetSaberMove. // Idle for Lightsaber - if ( pm->gent && pm->gent->client ) - { -// pm->gent->client->saberTrail.inAction = qfalse; + if (pm->gent && pm->gent->client) { + // pm->gent->client->saberTrail.inAction = qfalse; } qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->saberInFlight - && saberInAir - && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) - || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - if ( pm->ps->torsoAnim != BOTH_LOSE_SABER - || !pm->ps->torsoAnimTimer ) - { - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->saberInFlight && saberInAir && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + if (pm->ps->torsoAnim != BOTH_LOSE_SABER || !pm->ps->torsoAnimTimer) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else - {//saber is on + } else { // saber is on // Idle for Lightsaber - if ( pm->gent && pm->gent->client ) - { - if ( !G_InCinematicSaberAnim( pm->gent ) ) - { - pm->gent->client->ps.SaberDeactivateTrail( 0 ); + if (pm->gent && pm->gent->client) { + if (!G_InCinematicSaberAnim(pm->gent)) { + pm->gent->client->ps.SaberDeactivateTrail(0); } } // Idle for idle/ready Lightsaber -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONIDLE1 + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONIDLE1 // Select the proper idle Lightsaber attack move from the chart. - if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); - } - else - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - if ( (PM_RunningAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_WALK_STAFF - || pm->ps->legsAnim == BOTH_WALK_DUAL - || pm->ps->legsAnim == BOTH_WALKBACK_STAFF - || pm->ps->legsAnim == BOTH_WALKBACK_DUAL ) - && pm->ps->saberBlockingTime < cg.time ) - {//running w/1-handed weapon uses full-body anim + } else { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || + PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + if ((PM_RunningAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_WALK_STAFF || pm->ps->legsAnim == BOTH_WALK_DUAL || + pm->ps->legsAnim == BOTH_WALKBACK_STAFF || pm->ps->legsAnim == BOTH_WALKBACK_DUAL) && + pm->ps->saberBlockingTime < cg.time) { // running w/1-handed weapon uses full-body anim int setFlags = SETANIM_FLAG_NORMAL; - if ( PM_LandingAnim( pm->ps->torsoAnim ) ) - { + if (PM_LandingAnim(pm->ps->torsoAnim)) { setFlags = SETANIM_FLAG_OVERRIDE; } - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,setFlags); - } - else - { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, setFlags); + } else { PM_SetSaberMove(LS_READY); } } @@ -5504,84 +4417,64 @@ void PM_TorsoAnimLightsaber() } } - - - /* ------------------------- PM_TorsoAnimation ------------------------- */ -void PM_TorsoAnimation( void ) -{//FIXME: Write a much smarter and more appropriate anim picking routine logic... -// int oldAnim; - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown +void PM_TorsoAnimation(void) { // FIXME: Write a much smarter and more appropriate anim picking routine logic... + // int oldAnim; + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return; } - if ( (pm->ps->eFlags&EF_HELD_BY_WAMPA) ) - { + if ((pm->ps->eFlags & EF_HELD_BY_WAMPA)) { return; } - if ( (pm->ps->eFlags&EF_FORCE_DRAINED) ) - {//being drained - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((pm->ps->eFlags & EF_FORCE_DRAINED)) { // being drained + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if ( (pm->ps->forcePowersActive&(1<ps->forceDrainEntityNum < ENTITYNUM_WORLD ) - {//draining - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((pm->ps->forcePowersActive & (1 << FP_DRAIN)) && pm->ps->forceDrainEntityNum < ENTITYNUM_WORLD) { // draining + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if( pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags & SCF_FORCED_MARCH) ) - { + if (pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags & SCF_FORCED_MARCH)) { return; } - if(pm->gent != NULL && pm->gent->client) - { + if (pm->gent != NULL && pm->gent->client) { pm->gent->client->renderInfo.torsoFpsMod = 1.0f; } - if ( pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - { - if ( pm->gent->owner && pm->gent->owner->e_UseFunc == useF_emplaced_gun_use )//ugly way to tell, but... - {//full body - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - } - else - {//torso - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL + if (pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { + if (pm->gent->owner && pm->gent->owner->e_UseFunc == useF_emplaced_gun_use) // ugly way to tell, but... + { // full body + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + } else { // torso + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL } return; } -/* else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->ps->clientNum < MAX_CLIENTS && (m_pVehicleInfo[((CVehicleNPC *)pm->gent->NPC)->m_iVehicleTypeID].numHands == 2 || g_speederControlScheme->value == 2) ) - {//can't look around - PM_SetAnim(pm,SETANIM_TORSO,m_pVehicleInfo[((CVehicleNPC *)pm->gent->NPC)->m_iVehicleTypeID].riderAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - return; - }*/ - - if ( pm->ps->taunting > level.time ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_ALORA_TAUNT,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - } - else if ( pm->ps->weapon == WP_SABER && pm->ps->saberAnimLevel == SS_DUAL && PM_HasAnimation( pm->gent, BOTH_DUAL_TAUNT ) ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_DUAL_TAUNT,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - } - else if ( pm->ps->weapon == WP_SABER - && pm->ps->saberAnimLevel == SS_STAFF )//pm->ps->saber[0].type == SABER_STAFF ) - {//turn on the blades - if ( PM_HasAnimation( pm->gent, BOTH_STAFF_TAUNT ) ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_STAFF_TAUNT,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL + /* else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->ps->clientNum < MAX_CLIENTS && + (m_pVehicleInfo[((CVehicleNPC *)pm->gent->NPC)->m_iVehicleTypeID].numHands == 2 || g_speederControlScheme->value == 2) ) + {//can't look around + PM_SetAnim(pm,SETANIM_TORSO,m_pVehicleInfo[((CVehicleNPC *)pm->gent->NPC)->m_iVehicleTypeID].riderAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + return; + }*/ + + if (pm->ps->taunting > level.time) { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_ALORA_TAUNT, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + } else if (pm->ps->weapon == WP_SABER && pm->ps->saberAnimLevel == SS_DUAL && PM_HasAnimation(pm->gent, BOTH_DUAL_TAUNT)) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_DUAL_TAUNT, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + } else if (pm->ps->weapon == WP_SABER && pm->ps->saberAnimLevel == SS_STAFF) // pm->ps->saber[0].type == SABER_STAFF ) + { // turn on the blades + if (PM_HasAnimation(pm->gent, BOTH_STAFF_TAUNT)) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_STAFF_TAUNT, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL } /* else @@ -5608,226 +4501,149 @@ void PM_TorsoAnimation( void ) pm->ps->torsoAnimTimer = pm->ps->legsAnimTimer = (pm->ps->taunting - level.time); } */ - } - else if ( PM_HasAnimation( pm->gent, BOTH_GESTURE1 ) ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GESTURE1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - pm->gent->client->ps.SaberActivateTrail( 100 ); - //FIXME: will this reset? - //FIXME: force-control (yellow glow) effect on hand and saber? - } - else - { - //PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE1,SETANIM_FLAG_NORMAL); + } else if (PM_HasAnimation(pm->gent, BOTH_GESTURE1)) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GESTURE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + pm->gent->client->ps.SaberActivateTrail(100); + // FIXME: will this reset? + // FIXME: force-control (yellow glow) effect on hand and saber? + } else { + // PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE1,SETANIM_FLAG_NORMAL); } return; } - if (pm->ps->weapon == WP_SABER ) // WP_LIGHTSABER + if (pm->ps->weapon == WP_SABER) // WP_LIGHTSABER { qboolean saberInAir = qfalse; - if ( pm->ps->SaberLength() && !pm->ps->saberInFlight ) - { + if (pm->ps->SaberLength() && !pm->ps->saberInFlight) { PM_TorsoAnimLightsaber(); - } - else - { - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip + } else { + if (pm->ps->forcePowersActive & (1 << FP_GRIP) && pm->ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//lightning + if (pm->ps->forcePowersActive & (1 << FP_LIGHTNING) && pm->ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // lightning return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowersActive & (1 << FP_DRAIN)) { // drain return; } saberInAir = qtrue; - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry PM_TorsoAnimLightsaber(); - } - else - { - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + } else { + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } - if ( pm->ps->saberInFlight - && saberInAir - && (!pm->ps->dualSabers //not using 2 sabers - || !pm->ps->saber[1].Active() //left one off - || pm->ps->torsoAnim == BOTH_SABERDUAL_STANCE//not attacking - || pm->ps->torsoAnim == BOTH_SABERPULL//not attacking - || pm->ps->torsoAnim == BOTH_STAND1//not attacking - || PM_RunningAnim( pm->ps->torsoAnim ) //not attacking - || PM_WalkingAnim( pm->ps->torsoAnim ) //not attacking - || PM_JumpingAnim( pm->ps->torsoAnim )//not attacking - || PM_SwimmingAnim( pm->ps->torsoAnim ) )//not attacking - ) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - if ( pm->ps->torsoAnim != BOTH_LOSE_SABER - || !pm->ps->torsoAnimTimer ) - { - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } - } - else - { - if ( PM_InSlopeAnim( pm->ps->legsAnim ) ) - {//HMM... this probably breaks the saber putaway and select anims - if ( pm->ps->SaberLength() > 0 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (pm->ps->saberInFlight && saberInAir && + (!pm->ps->dualSabers // not using 2 sabers + || !pm->ps->saber[1].Active() // left one off + || pm->ps->torsoAnim == BOTH_SABERDUAL_STANCE // not attacking + || pm->ps->torsoAnim == BOTH_SABERPULL // not attacking + || pm->ps->torsoAnim == BOTH_STAND1 // not attacking + || PM_RunningAnim(pm->ps->torsoAnim) // not attacking + || PM_WalkingAnim(pm->ps->torsoAnim) // not attacking + || PM_JumpingAnim(pm->ps->torsoAnim) // not attacking + || PM_SwimmingAnim(pm->ps->torsoAnim)) // not attacking + ) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + if (pm->ps->torsoAnim != BOTH_LOSE_SABER || !pm->ps->torsoAnimTimer) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - else - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is + } else { + if (PM_InSlopeAnim(pm->ps->legsAnim)) { // HMM... this probably breaks the saber putaway and select anims + if (pm->ps->SaberLength() > 0) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); } } } } } - if (pm->ps->weaponTime<= 0 && (pm->ps->saberMove==LS_READY || pm->ps->SaberLength()==0) && !saberInAir) - { + if (pm->ps->weaponTime <= 0 && (pm->ps->saberMove == LS_READY || pm->ps->SaberLength() == 0) && !saberInAir) { TorsoAgainstWindTest(pm->gent); } return; } - if ( PM_ForceAnim( pm->ps->torsoAnim ) - && pm->ps->torsoAnimTimer > 0 ) - {//in a force anim, don't do a stand anim + if (PM_ForceAnim(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer > 0) { // in a force anim, don't do a stand anim return; } - qboolean weaponBusy = qfalse; - if ( pm->ps->weapon == WP_NONE ) - { + if (pm->ps->weapon == WP_NONE) { weaponBusy = qfalse; - } - else if ( pm->ps->weaponstate == WEAPON_FIRING || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + } else if (pm->ps->weaponstate == WEAPON_FIRING || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) { weaponBusy = qtrue; - } - else if ( pm->ps->lastShotTime > level.time - 3000 ) - { + } else if (pm->ps->lastShotTime > level.time - 3000) { weaponBusy = qtrue; - } - else if ( pm->ps->weaponTime > 0 ) - { + } else if (pm->ps->weaponTime > 0) { weaponBusy = qtrue; - } - else if ( pm->gent && pm->gent->client->fireDelay > 0 ) - { + } else if (pm->gent && pm->gent->client->fireDelay > 0) { weaponBusy = qtrue; - } - else if ( TorsoAgainstWindTest(pm->gent) ) - { + } else if (TorsoAgainstWindTest(pm->gent)) { return; - } - else if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.zoomTime > cg.time - 5000 ) - {//if we used binoculars recently, aim weapon + } else if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.zoomTime > cg.time - 5000) { // if we used binoculars recently, aim weapon weaponBusy = qtrue; pm->ps->weaponstate = WEAPON_IDLE; - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - {//ducking is considered on alert... plus looks stupid to have arms hanging down when crouched + } else if (pm->ps->pm_flags & PMF_DUCKED) { // ducking is considered on alert... plus looks stupid to have arms hanging down when crouched weaponBusy = qtrue; } - if ( pm->ps->weapon == WP_NONE || - pm->ps->weaponstate == WEAPON_READY || - pm->ps->weaponstate == WEAPON_CHARGING || - pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { - if ( pm->ps->weapon == WP_SABER && pm->ps->SaberLength() ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 - } - else if( pm->ps->legsAnim == BOTH_RUN1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN2 && !weaponBusy )//&& pm->ps->saberAnimLevel != SS_STAFF ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN4 && !weaponBusy )//&& pm->ps->saberAnimLevel != SS_STAFF ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN4,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN_STAFF && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN_STAFF,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN_DUAL && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN_DUAL,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK2 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK_STAFF && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK_STAFF,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK_DUAL&& !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK_DUAL,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0 )//player falls through + if (pm->ps->weapon == WP_NONE || pm->ps->weaponstate == WEAPON_READY || pm->ps->weaponstate == WEAPON_CHARGING || + pm->ps->weaponstate == WEAPON_CHARGING_ALT) { + if (pm->ps->weapon == WP_SABER && pm->ps->SaberLength()) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_NORMAL); // TORSO_WEAPONREADY1 + } else if (pm->ps->legsAnim == BOTH_RUN1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN2 && !weaponBusy) //&& pm->ps->saberAnimLevel != SS_STAFF ) + { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN4 && !weaponBusy) //&& pm->ps->saberAnimLevel != SS_STAFF ) + { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_STAFF && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN_STAFF, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_DUAL && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN_DUAL, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_STAFF && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK_STAFF, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_DUAL && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK_DUAL, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0) // player falls through { //??? Why nothing? What if you were running??? - //PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_JUMP1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_JUMP1,SETANIM_FLAG_NORMAL, 100); // Only blend over 100ms - } - else if( pm->ps->legsAnim == BOTH_SWIM_IDLE1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIMFORWARD && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else if ( pm->ps->weapon == WP_NONE ) - { + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_JUMP1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_JUMP1, SETANIM_FLAG_NORMAL, 100); // Only blend over 100ms + } else if (pm->ps->legsAnim == BOTH_SWIM_IDLE1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIMFORWARD && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else if (pm->ps->weapon == WP_NONE) { int legsAnim = pm->ps->legsAnim; /* if ( PM_RollingAnim( legsAnim ) || @@ -5836,577 +4652,358 @@ void PM_TorsoAnimation( void ) PM_PainAnim( legsAnim ) || PM_SwimmingAnim( legsAnim ) ) */ - { - PM_SetAnim(pm, SETANIM_TORSO, legsAnim, SETANIM_FLAG_NORMAL ); - } - } - else - {//Used to default to both_stand1 which is an arms-down anim - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else if ( pm->gent != NULL - && (pm->gent->s.numbergent)) - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT ) - {//PLayer- temp hack for weapon frame - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//ignore - } - else if ( pm->ps->weapon == WP_MELEE ) - {//hehe - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + { PM_SetAnim(pm, SETANIM_TORSO, legsAnim, SETANIM_FLAG_NORMAL); } + } else { // Used to default to both_stand1 which is an arms-down anim + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else if (pm->gent != NULL && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent)) && pm->ps->weaponstate != WEAPON_CHARGING && + pm->ps->weaponstate != WEAPON_CHARGING_ALT) { // PLayer- temp hack for weapon frame + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { // ignore + } else if (pm->ps->weapon == WP_MELEE) { // hehe + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//use legs anim - //FIXME: or just use whatever's currently playing? - //PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); - } - else - { - switch(pm->ps->weapon) - { + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // use legs anim + // FIXME: or just use whatever's currently playing? + // PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); + } else { + switch (pm->ps->weapon) { // ******************************************************** - case WP_SABER: // WP_LIGHTSABER + case WP_SABER: // WP_LIGHTSABER // Ready pose for Lightsaber -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 // Select the next proper pose for the lightsaber assuming that there are no attacks. - if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); } break; - // ******************************************************** + // ******************************************************** case WP_BRYAR_PISTOL: - //FIXME: if recently fired, hold the ready! - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); + // FIXME: if recently fired, hold the ready! + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); } break; case WP_BLASTER_PISTOL: - if ( pm->gent - && pm->gent->weaponModel[1] > 0 ) - {//dual pistols - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUNSIT1,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->weaponModel[1] > 0) { // dual pistols + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUNSIT1, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - } - else - {//single pistols - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); + } else { // single pistols + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); } } break; case WP_NONE: - //NOTE: should never get here + // NOTE: should never get here break; case WP_MELEE: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//ignore - } - else if ( pm->gent && pm->gent->client && !PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { // ignore + } else if (pm->gent && pm->gent->client && !PM_DroidMelee(pm->gent->client->NPC_class)) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_TUSKEN_STAFF: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND3, SETANIM_FLAG_NORMAL); } break; case WP_NOGHRI_STICK: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); break; case WP_BLASTER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); break; case WP_DISRUPTOR: case WP_TUSKEN_RIFLE: - if ( (pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT) - || PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running sniper weapon uses normal ready - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); + if ((pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT) || + PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running sniper weapon uses normal ready + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - } - else - { - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL ); + } else { + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL); } } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT - && (PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim )) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && (pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) ) - {//player pulling back to throw - if ( PM_StandingAnim( pm->ps->legsAnim ) ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( pm->ps->legsAnim == BOTH_THERMAL_READY ) - {//sigh... hold it so pm_footsteps doesn't override - if ( pm->ps->legsAnimTimer < 100 ) - { + if (pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT && + (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim))) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + (pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT)) { // player pulling back to throw + if (PM_StandingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (pm->ps->legsAnim == BOTH_THERMAL_READY) { // sigh... hold it so pm_footsteps doesn't override + if (pm->ps->legsAnimTimer < 100) { pm->ps->legsAnimTimer = 100; } } - PM_SetAnim( pm, SETANIM_TORSO, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY10, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY10, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } } break; case WP_REPEATER: - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {// - if ( pm->gent->alt_fire ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY1,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { // + if (pm->gent->alt_fire) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY1, SETANIM_FLAG_NORMAL); } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } break; case WP_TRIP_MINE: case WP_DET_PACK: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; default: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); break; } } } - } - else if ( pm->ps->weaponstate == WEAPON_IDLE ) - { - if( pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_LOOKAROUND1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_GUARD_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND1IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE2 - || pm->ps->legsAnim == BOTH_STAND3IDLE1 - || pm->ps->legsAnim == BOTH_STAND5IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else if (pm->ps->weaponstate == WEAPON_IDLE) { + if (pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_GUARD_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND1IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE2 || + pm->ps->legsAnim == BOTH_STAND3IDLE1 || pm->ps->legsAnim == BOTH_STAND5IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND2TO4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2TO4,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND4TO2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4TO2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIM_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIMFORWARD ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//use legs anim - //FIXME: or just use whatever's currently playing? - //PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); - } - else if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - if ( !weaponBusy - && pm->ps->weapon != WP_BOWCASTER - && pm->ps->weapon != WP_REPEATER - && pm->ps->weapon != WP_FLECHETTE - && pm->ps->weapon != WP_ROCKET_LAUNCHER - && pm->ps->weapon != WP_CONCUSSION - && ( PM_RunningAnim( pm->ps->legsAnim ) - || (PM_WalkingAnim( pm->ps->legsAnim ) && (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) ) - {//running w/1-handed or light 2-handed weapon uses full-body anim if you're not using the weapon right now - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - switch ( pm->ps->weapon ) - { + } else if (pm->ps->legsAnim == BOTH_STAND2TO4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2TO4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4TO2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4TO2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIM_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIMFORWARD) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // use legs anim + // FIXME: or just use whatever's currently playing? + // PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); + } else if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + if (!weaponBusy && pm->ps->weapon != WP_BOWCASTER && pm->ps->weapon != WP_REPEATER && pm->ps->weapon != WP_FLECHETTE && + pm->ps->weapon != WP_ROCKET_LAUNCHER && pm->ps->weapon != WP_CONCUSSION && + (PM_RunningAnim(pm->ps->legsAnim) || (PM_WalkingAnim(pm->ps->legsAnim) && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) || + PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim( + pm->ps->legsAnim))) { // running w/1-handed or light 2-handed weapon uses full-body anim if you're not using the weapon right now + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + switch (pm->ps->weapon) { // ******************************************************** - case WP_SABER: // WP_LIGHTSABER + case WP_SABER: // WP_LIGHTSABER // Shouldn't get here, should go to TorsoAnimLightsaber break; - // ******************************************************** + // ******************************************************** case WP_BRYAR_PISTOL: - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); } break; case WP_BLASTER_PISTOL: - if ( pm->gent - && pm->gent->weaponModel[1] > 0 ) - {//dual pistols - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUNSIT1,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->weaponModel[1] > 0) { // dual pistols + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUNSIT1, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - } - else - {//single pistols - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + } else { // single pistols + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); } } break; case WP_NONE: - //NOTE: should never get here + // NOTE: should never get here break; case WP_MELEE: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//ignore - } - else if ( pm->gent && pm->gent->client && !PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { // ignore + } else if (pm->gent && pm->gent->client && !PM_DroidMelee(pm->gent->client->NPC_class)) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_TUSKEN_STAFF: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND3, SETANIM_FLAG_NORMAL); } break; case WP_NOGHRI_STICK: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; case WP_BLASTER: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; case WP_DISRUPTOR: case WP_TUSKEN_RIFLE: - if ( (pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT) - || PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running sniper weapon uses normal ready - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); + if ((pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT) || + PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running sniper weapon uses normal ready + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - } - else - { - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL ); + } else { + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL); } } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONIDLE10, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE10, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_REPEATER: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; case WP_TRIP_MINE: case WP_DET_PACK: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; default: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; } @@ -6419,57 +5016,48 @@ void PM_TorsoAnimation( void ) // Anim checking utils //========================================================================= -int PM_GetTurnAnim( gentity_t *gent, int anim ) -{ - if ( !gent ) - { +int PM_GetTurnAnim(gentity_t *gent, int anim) { + if (!gent) { return -1; } - switch( anim ) - { - case BOTH_STAND1: //# Standing idle: no weapon: hands down - case BOTH_STAND1IDLE1: //# Random standing idle - case BOTH_STAND2: //# Standing idle with a weapon + switch (anim) { + case BOTH_STAND1: //# Standing idle: no weapon: hands down + case BOTH_STAND1IDLE1: //# Random standing idle + case BOTH_STAND2: //# Standing idle with a weapon case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: - case BOTH_STAND2IDLE1: //# Random standing idle - case BOTH_STAND2IDLE2: //# Random standing idle - case BOTH_STAND3: //# Standing hands behind back: at ease: etc. - case BOTH_STAND3IDLE1: //# Random standing idle - case BOTH_STAND4: //# two handed: gun down: relaxed stand - case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight - case BOTH_STAND5IDLE1: //# Random standing idle - case BOTH_STAND6: //# one handed: gun at side: relaxed stand - case BOTH_STAND2TO4: //# Transition from stand2 to stand4 - case BOTH_STAND4TO2: //# Transition from stand4 to stand2 - case BOTH_GESTURE1: //# Generic gesture: non-specific - case BOTH_GESTURE2: //# Generic gesture: non-specific - case BOTH_TALK1: //# Generic talk anim - case BOTH_TALK2: //# Generic talk anim - if ( PM_HasAnimation( gent, LEGS_TURN1 ) ) - { + case BOTH_STAND2IDLE1: //# Random standing idle + case BOTH_STAND2IDLE2: //# Random standing idle + case BOTH_STAND3: //# Standing hands behind back: at ease: etc. + case BOTH_STAND3IDLE1: //# Random standing idle + case BOTH_STAND4: //# two handed: gun down: relaxed stand + case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight + case BOTH_STAND5IDLE1: //# Random standing idle + case BOTH_STAND6: //# one handed: gun at side: relaxed stand + case BOTH_STAND2TO4: //# Transition from stand2 to stand4 + case BOTH_STAND4TO2: //# Transition from stand4 to stand2 + case BOTH_GESTURE1: //# Generic gesture: non-specific + case BOTH_GESTURE2: //# Generic gesture: non-specific + case BOTH_TALK1: //# Generic talk anim + case BOTH_TALK2: //# Generic talk anim + if (PM_HasAnimation(gent, LEGS_TURN1)) { return LEGS_TURN1; - } - else - { + } else { return -1; } break; - case BOTH_ATTACK1: //# Attack with generic 1-handed weapon - case BOTH_ATTACK2: //# Attack with generic 2-handed weapon - case BOTH_ATTACK3: //# Attack with heavy 2-handed weapon - case BOTH_ATTACK4: //# Attack with ??? - case BOTH_MELEE1: //# First melee attack - case BOTH_MELEE2: //# Second melee attack - case BOTH_GUARD_LOOKAROUND1: //# Cradling weapon and looking around - case BOTH_GUARD_IDLE1: //# Cradling weapon and standing - if ( PM_HasAnimation( gent, LEGS_TURN2 ) ) - { + case BOTH_ATTACK1: //# Attack with generic 1-handed weapon + case BOTH_ATTACK2: //# Attack with generic 2-handed weapon + case BOTH_ATTACK3: //# Attack with heavy 2-handed weapon + case BOTH_ATTACK4: //# Attack with ??? + case BOTH_MELEE1: //# First melee attack + case BOTH_MELEE2: //# Second melee attack + case BOTH_GUARD_LOOKAROUND1: //# Cradling weapon and looking around + case BOTH_GUARD_IDLE1: //# Cradling weapon and standing + if (PM_HasAnimation(gent, LEGS_TURN2)) { return LEGS_TURN2; - } - else - { + } else { return -1; } break; @@ -6479,88 +5067,67 @@ int PM_GetTurnAnim( gentity_t *gent, int anim ) } } -int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ) -{ - if ( !gent ) - { +int PM_TurnAnimForLegsAnim(gentity_t *gent, int anim) { + if (!gent) { return -1; } - switch( anim ) - { - case BOTH_STAND1: //# Standing idle: no weapon: hands down - case BOTH_STAND1IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND1 ) ) - { + switch (anim) { + case BOTH_STAND1: //# Standing idle: no weapon: hands down + case BOTH_STAND1IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND1)) { return BOTH_TURNSTAND1; - } - else - { + } else { return -1; } break; - case BOTH_STAND2: //# Standing idle with a weapon + case BOTH_STAND2: //# Standing idle with a weapon case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: - case BOTH_STAND2IDLE1: //# Random standing idle - case BOTH_STAND2IDLE2: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND2 ) ) - { + case BOTH_STAND2IDLE1: //# Random standing idle + case BOTH_STAND2IDLE2: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND2)) { return BOTH_TURNSTAND2; - } - else - { + } else { return -1; } break; - case BOTH_STAND3: //# Standing hands behind back: at ease: etc. - case BOTH_STAND3IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND3 ) ) - { + case BOTH_STAND3: //# Standing hands behind back: at ease: etc. + case BOTH_STAND3IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND3)) { return BOTH_TURNSTAND3; - } - else - { + } else { return -1; } break; - case BOTH_STAND4: //# two handed: gun down: relaxed stand - if ( PM_HasAnimation( gent, BOTH_TURNSTAND4 ) ) - { + case BOTH_STAND4: //# two handed: gun down: relaxed stand + if (PM_HasAnimation(gent, BOTH_TURNSTAND4)) { return BOTH_TURNSTAND4; - } - else - { + } else { return -1; } break; - case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight - case BOTH_STAND5IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND5 ) ) - { + case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight + case BOTH_STAND5IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND5)) { return BOTH_TURNSTAND5; - } - else - { + } else { return -1; } break; - case BOTH_CROUCH1: //# Transition from standing to crouch - case BOTH_CROUCH1IDLE: //# Crouching idle - /* - case BOTH_UNCROUCH1: //# Transition from crouch to standing - case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 - case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) - case BOTH_UNCROUCH3: //# Desann uncrouching down to Kyle (cin 9) - case BOTH_CROUCH4: //# Slower version of crouch1 for cinematics - case BOTH_UNCROUCH4: //# Slower version of uncrouch1 for cinematics - */ - if ( PM_HasAnimation( gent, BOTH_TURNCROUCH1 ) ) - { + case BOTH_CROUCH1: //# Transition from standing to crouch + case BOTH_CROUCH1IDLE: //# Crouching idle + /* + case BOTH_UNCROUCH1: //# Transition from crouch to standing + case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 + case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) + case BOTH_UNCROUCH3: //# Desann uncrouching down to Kyle (cin 9) + case BOTH_CROUCH4: //# Slower version of crouch1 for cinematics + case BOTH_UNCROUCH4: //# Slower version of uncrouch1 for cinematics + */ + if (PM_HasAnimation(gent, BOTH_TURNCROUCH1)) { return BOTH_TURNCROUCH1; - } - else - { + } else { return -1; } break; @@ -6570,10 +5137,8 @@ int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ) } } -qboolean PM_InOnGroundAnim ( playerState_t *ps ) -{ - switch( ps->legsAnim ) - { +qboolean PM_InOnGroundAnim(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_DEAD1: case BOTH_DEAD2: case BOTH_DEAD3: @@ -6585,24 +5150,22 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) case BOTH_DEADBACKWARD2: case BOTH_LYINGDEATH1: case BOTH_LYINGDEAD1: - case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso + case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso return qtrue; break; - case BOTH_KNOCKDOWN1: //# - case BOTH_KNOCKDOWN2: //# - case BOTH_KNOCKDOWN3: //# - case BOTH_KNOCKDOWN4: //# - case BOTH_KNOCKDOWN5: //# + case BOTH_KNOCKDOWN1: //# + case BOTH_KNOCKDOWN2: //# + case BOTH_KNOCKDOWN3: //# + case BOTH_KNOCKDOWN4: //# + case BOTH_KNOCKDOWN5: //# case BOTH_LK_DL_ST_T_SB_1_L: case BOTH_RELEASED: - if ( ps->legsAnimTimer < 500 ) - {//pretty much horizontal by this point + if (ps->legsAnimTimer < 500) { // pretty much horizontal by this point return qtrue; } break; case BOTH_PLAYER_PA_3_FLY: - if ( ps->legsAnimTimer < 300 ) - {//pretty much horizontal by this point + if (ps->legsAnimTimer < 300) { // pretty much horizontal by this point return qtrue; } /* @@ -6628,8 +5191,8 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( ps->legsAnimTimer > PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim )-400 ) - {//still pretty much horizontal at this point + if (ps->legsAnimTimer > PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - + 400) { // still pretty much horizontal at this point return qtrue; } break; @@ -6638,10 +5201,8 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) return qfalse; } -qboolean PM_InSpecialDeathAnim( int anim ) -{ - switch( pm->ps->legsAnim ) - { +qboolean PM_InSpecialDeathAnim(int anim) { + switch (pm->ps->legsAnim) { case BOTH_DEATH_ROLL: //# Death anim from a roll case BOTH_DEATH_FLIP: //# Death anim from a flip case BOTH_DEATH_SPIN_90_R: //# Death anim when facing 90 degrees right @@ -6649,8 +5210,8 @@ qboolean PM_InSpecialDeathAnim( int anim ) case BOTH_DEATH_SPIN_180: //# Death anim when facing backwards case BOTH_DEATH_LYING_UP: //# Death anim when lying on back case BOTH_DEATH_LYING_DN: //# Death anim when lying on front - case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face - case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back + case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face + case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back case BOTH_DEATH_CROUCHED: //# Death anim when crouched return qtrue; break; @@ -6660,88 +5221,86 @@ qboolean PM_InSpecialDeathAnim( int anim ) } } -qboolean PM_InDeathAnim ( void ) -{//Purposely does not cover stumbledeath and falldeath... - switch( pm->ps->legsAnim ) - { - case BOTH_DEATH1: //# First Death anim - case BOTH_DEATH2: //# Second Death anim - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH8: //# - case BOTH_DEATH9: //# - case BOTH_DEATH10: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH13: //# - case BOTH_DEATH14: //# - case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) - case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) - case BOTH_DEATH15: //# - case BOTH_DEATH16: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATH20: //# - case BOTH_DEATH21: //# - case BOTH_DEATH22: //# - case BOTH_DEATH23: //# - case BOTH_DEATH24: //# - case BOTH_DEATH25: //# - - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom +qboolean PM_InDeathAnim(void) { // Purposely does not cover stumbledeath and falldeath... + switch (pm->ps->legsAnim) { + case BOTH_DEATH1: //# First Death anim + case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH8: //# + case BOTH_DEATH9: //# + case BOTH_DEATH10: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH13: //# + case BOTH_DEATH14: //# + case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) + case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) + case BOTH_DEATH15: //# + case BOTH_DEATH16: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATH20: //# + case BOTH_DEATH21: //# + case BOTH_DEATH22: //# + case BOTH_DEATH23: //# + case BOTH_DEATH24: //# + case BOTH_DEATH25: //# + + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom //# #sep case BOTH_ DEAD POSES # Should be last frame of corresponding previous anims - case BOTH_DEAD1: //# First Death finished pose - case BOTH_DEAD2: //# Second Death finished pose - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD8: //# - case BOTH_DEAD9: //# - case BOTH_DEAD10: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD13: //# - case BOTH_DEAD14: //# - case BOTH_DEAD15: //# - case BOTH_DEAD16: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_DEAD20: //# - case BOTH_DEAD21: //# - case BOTH_DEAD22: //# - case BOTH_DEAD23: //# - case BOTH_DEAD24: //# - case BOTH_DEAD25: //# - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEAD1: //# First Death finished pose + case BOTH_DEAD2: //# Second Death finished pose + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD8: //# + case BOTH_DEAD9: //# + case BOTH_DEAD10: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD13: //# + case BOTH_DEAD14: //# + case BOTH_DEAD15: //# + case BOTH_DEAD16: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_DEAD20: //# + case BOTH_DEAD21: //# + case BOTH_DEAD22: //# + case BOTH_DEAD23: //# + case BOTH_DEAD24: //# + case BOTH_DEAD25: //# + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose //# #sep case BOTH_ DEAD TWITCH/FLOP # React to being shot from death poses case BOTH_DEADFLOP1: //# React to being shot from First Death finished pose case BOTH_DEADFLOP2: //# React to being shot from Second Death finished pose case BOTH_DISMEMBER_HEAD1: //# - case BOTH_DISMEMBER_TORSO1: //# + case BOTH_DISMEMBER_TORSO1: //# case BOTH_DISMEMBER_LLEG: //# case BOTH_DISMEMBER_RLEG: //# case BOTH_DISMEMBER_RARM: //# @@ -6749,15 +5308,13 @@ qboolean PM_InDeathAnim ( void ) return qtrue; break; default: - return PM_InSpecialDeathAnim( pm->ps->legsAnim ); + return PM_InSpecialDeathAnim(pm->ps->legsAnim); break; } } -qboolean PM_InCartwheel( int anim ) -{ - switch ( anim ) - { +qboolean PM_InCartwheel(int anim) { + switch (anim) { case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: case BOTH_ARIAL_F1: @@ -6769,10 +5326,8 @@ qboolean PM_InCartwheel( int anim ) return qfalse; } -qboolean PM_InButterfly( int anim ) -{ - switch ( anim ) - { +qboolean PM_InButterfly(int anim) { + switch (anim) { case BOTH_BUTTERFLY_LEFT: case BOTH_BUTTERFLY_RIGHT: case BOTH_BUTTERFLY_FL1: @@ -6783,10 +5338,8 @@ qboolean PM_InButterfly( int anim ) return qfalse; } -qboolean PM_StandingAnim( int anim ) -{//NOTE: does not check idles or special (cinematic) stands - switch ( anim ) - { +qboolean PM_StandingAnim(int anim) { // NOTE: does not check idles or special (cinematic) stands + switch (anim) { case BOTH_STAND1: case BOTH_STAND2: case BOTH_STAND3: @@ -6798,10 +5351,8 @@ qboolean PM_StandingAnim( int anim ) return qfalse; } -qboolean PM_InAirKickingAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_InAirKickingAnim(int anim) { + switch (anim) { case BOTH_A7_KICK_F_AIR: case BOTH_A7_KICK_B_AIR: case BOTH_A7_KICK_R_AIR: @@ -6811,10 +5362,8 @@ qboolean PM_InAirKickingAnim( int anim ) return qfalse; } -qboolean PM_KickingAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_KickingAnim(int anim) { + switch (anim) { case BOTH_A7_KICK_F: case BOTH_A7_KICK_B: case BOTH_A7_KICK_R: @@ -6822,9 +5371,9 @@ qboolean PM_KickingAnim( int anim ) case BOTH_A7_KICK_S: case BOTH_A7_KICK_BF: case BOTH_A7_KICK_RL: - //NOT a kick, but acts like one: + // NOT a kick, but acts like one: case BOTH_A7_HILT: - //NOT kicks, but do kick traces anyway + // NOT kicks, but do kick traces anyway case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: @@ -6832,16 +5381,14 @@ qboolean PM_KickingAnim( int anim ) return qtrue; break; default: - return PM_InAirKickingAnim( anim ); + return PM_InAirKickingAnim(anim); break; } - //return qfalse; + // return qfalse; } -qboolean PM_StabDownAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_StabDownAnim(int anim) { + switch (anim) { case BOTH_STABDOWN: case BOTH_STABDOWN_STAFF: case BOTH_STABDOWN_DUAL: @@ -6850,24 +5397,21 @@ qboolean PM_StabDownAnim( int anim ) return qfalse; } -qboolean PM_GoingToAttackDown( playerState_t *ps ) -{ - if ( PM_StabDownAnim( ps->torsoAnim )//stabbing downward - || ps->saberMove == LS_A_LUNGE//lunge - || ps->saberMove == LS_A_JUMP_T__B_//death from above - || ps->saberMove == LS_A_T2B//attacking top to bottom - || ps->saberMove == LS_S_T2B//starting at attack downward - || (PM_SaberInTransition( ps->saberMove ) && saberMoveData[ps->saberMove].endQuad == Q_T) )//transitioning to a top to bottom attack +qboolean PM_GoingToAttackDown(playerState_t *ps) { + if (PM_StabDownAnim(ps->torsoAnim) // stabbing downward + || ps->saberMove == LS_A_LUNGE // lunge + || ps->saberMove == LS_A_JUMP_T__B_ // death from above + || ps->saberMove == LS_A_T2B // attacking top to bottom + || ps->saberMove == LS_S_T2B // starting at attack downward + || (PM_SaberInTransition(ps->saberMove) && saberMoveData[ps->saberMove].endQuad == Q_T)) // transitioning to a top to bottom attack { return qtrue; } return qfalse; } -qboolean PM_ForceUsingSaberAnim( int anim ) -{//saber/acrobatic anims that should prevent you from recharging force power while you're in them... - switch ( anim ) - { +qboolean PM_ForceUsingSaberAnim(int anim) { // saber/acrobatic anims that should prevent you from recharging force power while you're in them... + switch (anim) { case BOTH_JUMPFLIPSLASHDOWN1: case BOTH_JUMPFLIPSTABDOWN: case BOTH_FORCELEAP2_T__B_: @@ -6972,23 +5516,16 @@ qboolean PM_ForceUsingSaberAnim( int anim ) return qfalse; } -qboolean G_HasKnockdownAnims( gentity_t *ent ) -{ - if ( PM_HasAnimation( ent, BOTH_KNOCKDOWN1 ) - && PM_HasAnimation( ent, BOTH_KNOCKDOWN2 ) - && PM_HasAnimation( ent, BOTH_KNOCKDOWN3 ) - && PM_HasAnimation( ent, BOTH_KNOCKDOWN4 ) - && PM_HasAnimation( ent, BOTH_KNOCKDOWN5 ) ) - { +qboolean G_HasKnockdownAnims(gentity_t *ent) { + if (PM_HasAnimation(ent, BOTH_KNOCKDOWN1) && PM_HasAnimation(ent, BOTH_KNOCKDOWN2) && PM_HasAnimation(ent, BOTH_KNOCKDOWN3) && + PM_HasAnimation(ent, BOTH_KNOCKDOWN4) && PM_HasAnimation(ent, BOTH_KNOCKDOWN5)) { return qtrue; } return qfalse; } -qboolean PM_InAttackRoll( int anim ) -{ - switch ( anim ) - { +qboolean PM_InAttackRoll(int anim) { + switch (anim) { case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: @@ -6998,10 +5535,8 @@ qboolean PM_InAttackRoll( int anim ) return qfalse; } -qboolean PM_LockedAnim( int anim ) -{//anims that can *NEVER* be overridden, regardless - switch ( anim ) - { +qboolean PM_LockedAnim(int anim) { // anims that can *NEVER* be overridden, regardless + switch (anim) { case BOTH_KYLE_PA_1: case BOTH_KYLE_PA_2: case BOTH_KYLE_PA_3: @@ -7014,127 +5549,119 @@ qboolean PM_LockedAnim( int anim ) case BOTH_SCEPTER_START: case BOTH_SCEPTER_HOLD: case BOTH_SCEPTER_STOP: - //grabbed by wampa - case BOTH_GRABBED: //# - case BOTH_RELEASED: //# when Wampa drops player, transitions into fall on back - case BOTH_HANG_IDLE: //# - case BOTH_HANG_ATTACK: //# - case BOTH_HANG_PAIN: //# + // grabbed by wampa + case BOTH_GRABBED: //# + case BOTH_RELEASED: //# when Wampa drops player, transitions into fall on back + case BOTH_HANG_IDLE: //# + case BOTH_HANG_ATTACK: //# + case BOTH_HANG_PAIN: //# return qtrue; } return qfalse; } -qboolean PM_SuperBreakLoseAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_SB_1_L: //super break I lost - case BOTH_LK_S_DL_T_SB_1_L: //super break I lost - case BOTH_LK_S_ST_S_SB_1_L: //super break I lost - case BOTH_LK_S_ST_T_SB_1_L: //super break I lost - case BOTH_LK_S_S_S_SB_1_L: //super break I lost - case BOTH_LK_S_S_T_SB_1_L: //super break I lost - case BOTH_LK_DL_DL_S_SB_1_L: //super break I lost - case BOTH_LK_DL_DL_T_SB_1_L: //super break I lost - case BOTH_LK_DL_ST_S_SB_1_L: //super break I lost - case BOTH_LK_DL_ST_T_SB_1_L: //super break I lost - case BOTH_LK_DL_S_S_SB_1_L: //super break I lost - case BOTH_LK_DL_S_T_SB_1_L: //super break I lost - case BOTH_LK_ST_DL_S_SB_1_L: //super break I lost - case BOTH_LK_ST_DL_T_SB_1_L: //super break I lost - case BOTH_LK_ST_ST_S_SB_1_L: //super break I lost - case BOTH_LK_ST_ST_T_SB_1_L: //super break I lost - case BOTH_LK_ST_S_S_SB_1_L: //super break I lost - case BOTH_LK_ST_S_T_SB_1_L: //super break I lost +qboolean PM_SuperBreakLoseAnim(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_SB_1_L: // super break I lost + case BOTH_LK_S_DL_T_SB_1_L: // super break I lost + case BOTH_LK_S_ST_S_SB_1_L: // super break I lost + case BOTH_LK_S_ST_T_SB_1_L: // super break I lost + case BOTH_LK_S_S_S_SB_1_L: // super break I lost + case BOTH_LK_S_S_T_SB_1_L: // super break I lost + case BOTH_LK_DL_DL_S_SB_1_L: // super break I lost + case BOTH_LK_DL_DL_T_SB_1_L: // super break I lost + case BOTH_LK_DL_ST_S_SB_1_L: // super break I lost + case BOTH_LK_DL_ST_T_SB_1_L: // super break I lost + case BOTH_LK_DL_S_S_SB_1_L: // super break I lost + case BOTH_LK_DL_S_T_SB_1_L: // super break I lost + case BOTH_LK_ST_DL_S_SB_1_L: // super break I lost + case BOTH_LK_ST_DL_T_SB_1_L: // super break I lost + case BOTH_LK_ST_ST_S_SB_1_L: // super break I lost + case BOTH_LK_ST_ST_T_SB_1_L: // super break I lost + case BOTH_LK_ST_S_S_SB_1_L: // super break I lost + case BOTH_LK_ST_S_T_SB_1_L: // super break I lost return qtrue; break; } return qfalse; } -qboolean PM_SuperBreakWinAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_SB_1_W: //super break I won - case BOTH_LK_S_DL_T_SB_1_W: //super break I won - case BOTH_LK_S_ST_S_SB_1_W: //super break I won - case BOTH_LK_S_ST_T_SB_1_W: //super break I won - case BOTH_LK_S_S_S_SB_1_W: //super break I won - case BOTH_LK_S_S_T_SB_1_W: //super break I won - case BOTH_LK_DL_DL_S_SB_1_W: //super break I won - case BOTH_LK_DL_DL_T_SB_1_W: //super break I won - case BOTH_LK_DL_ST_S_SB_1_W: //super break I won - case BOTH_LK_DL_ST_T_SB_1_W: //super break I won - case BOTH_LK_DL_S_S_SB_1_W: //super break I won - case BOTH_LK_DL_S_T_SB_1_W: //super break I won - case BOTH_LK_ST_DL_S_SB_1_W: //super break I won - case BOTH_LK_ST_DL_T_SB_1_W: //super break I won - case BOTH_LK_ST_ST_S_SB_1_W: //super break I won - case BOTH_LK_ST_ST_T_SB_1_W: //super break I won - case BOTH_LK_ST_S_S_SB_1_W: //super break I won - case BOTH_LK_ST_S_T_SB_1_W: //super break I won +qboolean PM_SuperBreakWinAnim(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_SB_1_W: // super break I won + case BOTH_LK_S_DL_T_SB_1_W: // super break I won + case BOTH_LK_S_ST_S_SB_1_W: // super break I won + case BOTH_LK_S_ST_T_SB_1_W: // super break I won + case BOTH_LK_S_S_S_SB_1_W: // super break I won + case BOTH_LK_S_S_T_SB_1_W: // super break I won + case BOTH_LK_DL_DL_S_SB_1_W: // super break I won + case BOTH_LK_DL_DL_T_SB_1_W: // super break I won + case BOTH_LK_DL_ST_S_SB_1_W: // super break I won + case BOTH_LK_DL_ST_T_SB_1_W: // super break I won + case BOTH_LK_DL_S_S_SB_1_W: // super break I won + case BOTH_LK_DL_S_T_SB_1_W: // super break I won + case BOTH_LK_ST_DL_S_SB_1_W: // super break I won + case BOTH_LK_ST_DL_T_SB_1_W: // super break I won + case BOTH_LK_ST_ST_S_SB_1_W: // super break I won + case BOTH_LK_ST_ST_T_SB_1_W: // super break I won + case BOTH_LK_ST_S_S_SB_1_W: // super break I won + case BOTH_LK_ST_S_T_SB_1_W: // super break I won return qtrue; break; } return qfalse; } -qboolean PM_SaberLockBreakAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_SaberLockBreakAnim(int anim) { + switch (anim) { case BOTH_BF1BREAK: case BOTH_BF2BREAK: case BOTH_CWCIRCLEBREAK: case BOTH_CCWCIRCLEBREAK: - case BOTH_LK_S_DL_S_B_1_L: //normal break I lost - case BOTH_LK_S_DL_S_B_1_W: //normal break I won - case BOTH_LK_S_DL_T_B_1_L: //normal break I lost - case BOTH_LK_S_DL_T_B_1_W: //normal break I won - case BOTH_LK_S_ST_S_B_1_L: //normal break I lost - case BOTH_LK_S_ST_S_B_1_W: //normal break I won - case BOTH_LK_S_ST_T_B_1_L: //normal break I lost - case BOTH_LK_S_ST_T_B_1_W: //normal break I won - case BOTH_LK_S_S_S_B_1_L: //normal break I lost - case BOTH_LK_S_S_S_B_1_W: //normal break I won - case BOTH_LK_S_S_T_B_1_L: //normal break I lost - case BOTH_LK_S_S_T_B_1_W: //normal break I won - case BOTH_LK_DL_DL_S_B_1_L: //normal break I lost - case BOTH_LK_DL_DL_S_B_1_W: //normal break I won - case BOTH_LK_DL_DL_T_B_1_L: //normal break I lost - case BOTH_LK_DL_DL_T_B_1_W: //normal break I won - case BOTH_LK_DL_ST_S_B_1_L: //normal break I lost - case BOTH_LK_DL_ST_S_B_1_W: //normal break I won - case BOTH_LK_DL_ST_T_B_1_L: //normal break I lost - case BOTH_LK_DL_ST_T_B_1_W: //normal break I won - case BOTH_LK_DL_S_S_B_1_L: //normal break I lost - case BOTH_LK_DL_S_S_B_1_W: //normal break I won - case BOTH_LK_DL_S_T_B_1_L: //normal break I lost - case BOTH_LK_DL_S_T_B_1_W: //normal break I won - case BOTH_LK_ST_DL_S_B_1_L: //normal break I lost - case BOTH_LK_ST_DL_S_B_1_W: //normal break I won - case BOTH_LK_ST_DL_T_B_1_L: //normal break I lost - case BOTH_LK_ST_DL_T_B_1_W: //normal break I won - case BOTH_LK_ST_ST_S_B_1_L: //normal break I lost - case BOTH_LK_ST_ST_S_B_1_W: //normal break I won - case BOTH_LK_ST_ST_T_B_1_L: //normal break I lost - case BOTH_LK_ST_ST_T_B_1_W: //normal break I won - case BOTH_LK_ST_S_S_B_1_L: //normal break I lost - case BOTH_LK_ST_S_S_B_1_W: //normal break I won - case BOTH_LK_ST_S_T_B_1_L: //normal break I lost - case BOTH_LK_ST_S_T_B_1_W: //normal break I won - return (qboolean)(PM_SuperBreakLoseAnim(anim)||PM_SuperBreakWinAnim(anim)); + case BOTH_LK_S_DL_S_B_1_L: // normal break I lost + case BOTH_LK_S_DL_S_B_1_W: // normal break I won + case BOTH_LK_S_DL_T_B_1_L: // normal break I lost + case BOTH_LK_S_DL_T_B_1_W: // normal break I won + case BOTH_LK_S_ST_S_B_1_L: // normal break I lost + case BOTH_LK_S_ST_S_B_1_W: // normal break I won + case BOTH_LK_S_ST_T_B_1_L: // normal break I lost + case BOTH_LK_S_ST_T_B_1_W: // normal break I won + case BOTH_LK_S_S_S_B_1_L: // normal break I lost + case BOTH_LK_S_S_S_B_1_W: // normal break I won + case BOTH_LK_S_S_T_B_1_L: // normal break I lost + case BOTH_LK_S_S_T_B_1_W: // normal break I won + case BOTH_LK_DL_DL_S_B_1_L: // normal break I lost + case BOTH_LK_DL_DL_S_B_1_W: // normal break I won + case BOTH_LK_DL_DL_T_B_1_L: // normal break I lost + case BOTH_LK_DL_DL_T_B_1_W: // normal break I won + case BOTH_LK_DL_ST_S_B_1_L: // normal break I lost + case BOTH_LK_DL_ST_S_B_1_W: // normal break I won + case BOTH_LK_DL_ST_T_B_1_L: // normal break I lost + case BOTH_LK_DL_ST_T_B_1_W: // normal break I won + case BOTH_LK_DL_S_S_B_1_L: // normal break I lost + case BOTH_LK_DL_S_S_B_1_W: // normal break I won + case BOTH_LK_DL_S_T_B_1_L: // normal break I lost + case BOTH_LK_DL_S_T_B_1_W: // normal break I won + case BOTH_LK_ST_DL_S_B_1_L: // normal break I lost + case BOTH_LK_ST_DL_S_B_1_W: // normal break I won + case BOTH_LK_ST_DL_T_B_1_L: // normal break I lost + case BOTH_LK_ST_DL_T_B_1_W: // normal break I won + case BOTH_LK_ST_ST_S_B_1_L: // normal break I lost + case BOTH_LK_ST_ST_S_B_1_W: // normal break I won + case BOTH_LK_ST_ST_T_B_1_L: // normal break I lost + case BOTH_LK_ST_ST_T_B_1_W: // normal break I won + case BOTH_LK_ST_S_S_B_1_L: // normal break I lost + case BOTH_LK_ST_S_S_B_1_W: // normal break I won + case BOTH_LK_ST_S_T_B_1_L: // normal break I lost + case BOTH_LK_ST_S_T_B_1_W: // normal break I won + return (qboolean)(PM_SuperBreakLoseAnim(anim) || PM_SuperBreakWinAnim(anim)); break; } return qfalse; } -qboolean PM_GetupAnimNoMove( int legsAnim ) -{ - switch( legsAnim ) - { +qboolean PM_GetupAnimNoMove(int legsAnim) { + switch (legsAnim) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -7155,60 +5682,54 @@ qboolean PM_GetupAnimNoMove( int legsAnim ) return qfalse; } -qboolean PM_KnockDownAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_KnockDownAnim(int anim) { + switch (anim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - /* - //special anims: - case BOTH_RELEASED: - case BOTH_LK_DL_ST_T_SB_1_L: - case BOTH_PLAYER_PA_3_FLY: - */ + /* + //special anims: + case BOTH_RELEASED: + case BOTH_LK_DL_ST_T_SB_1_L: + case BOTH_PLAYER_PA_3_FLY: + */ return qtrue; break; - /* - default: - return PM_InGetUp( ps ); - break; - */ + /* + default: + return PM_InGetUp( ps ); + break; + */ } return qfalse; } -qboolean PM_KnockDownAnimExtended( int anim ) -{ - switch ( anim ) - { +qboolean PM_KnockDownAnimExtended(int anim) { + switch (anim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - //special anims: + // special anims: case BOTH_RELEASED: case BOTH_LK_DL_ST_T_SB_1_L: case BOTH_PLAYER_PA_3_FLY: return qtrue; break; - /* - default: - return PM_InGetUp( ps ); - break; - */ + /* + default: + return PM_InGetUp( ps ); + break; + */ } return qfalse; } -qboolean PM_SaberInKata( saberMoveName_t saberMove ) -{ - switch ( saberMove ) - { +qboolean PM_SaberInKata(saberMoveName_t saberMove) { + switch (saberMove) { case LS_A1_SPECIAL: case LS_A2_SPECIAL: case LS_A3_SPECIAL: @@ -7221,21 +5742,15 @@ qboolean PM_SaberInKata( saberMoveName_t saberMove ) return qfalse; } -qboolean PM_CanRollFromSoulCal( playerState_t *ps ) -{ - if ( ps->legsAnim == BOTH_A7_SOULCAL - && ps->legsAnimTimer < 700 - && ps->legsAnimTimer > 250 ) - { +qboolean PM_CanRollFromSoulCal(playerState_t *ps) { + if (ps->legsAnim == BOTH_A7_SOULCAL && ps->legsAnimTimer < 700 && ps->legsAnimTimer > 250) { return qtrue; } return qfalse; } -qboolean BG_FullBodyTauntAnim( int anim ) -{ - switch ( anim ) - { +qboolean BG_FullBodyTauntAnim(int anim) { + switch (anim) { case BOTH_GESTURE1: case BOTH_DUAL_TAUNT: case BOTH_STAFF_TAUNT: diff --git a/code/game/bg_pmove.cpp b/code/game/bg_pmove.cpp index 46643fd41f..4277db81df 100644 --- a/code/game/bg_pmove.cpp +++ b/code/game/bg_pmove.cpp @@ -25,7 +25,6 @@ along with this program; if not, see . #include "../rd-common/tr_public.h" - // bg_pmove.c -- both games player movement code // takes a playerstate and a usercmd as input and returns a modifed playerstate @@ -33,300 +32,263 @@ along with this program; if not, see . // short, server-visible gclient_t and gentity_t structures, // because we define the full size ones in this file -#define GAME_INCLUDE +#define GAME_INCLUDE #include "../qcommon/q_shared.h" #include "g_shared.h" #include "bg_local.h" #include "g_local.h" #include "g_functions.h" #include "anims.h" -#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... +#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... #include "wp_saber.h" #include "g_vehicles.h" #include -extern qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ); -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -extern int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern saberMoveName_t PM_SaberAnimTransitionMove( saberMoveName_t curmove, saberMoveName_t newmove ); -extern saberMoveName_t PM_AttackMoveForQuad( int quad ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern saberMoveName_t PM_SaberBounceForAttack( int move ); -extern saberMoveName_t PM_SaberAttackForMovement( int forwardmove, int rightmove, int curmove ); -extern saberMoveName_t PM_BrokenParryForParry( int move ); -extern saberMoveName_t PM_KnockawayForParry( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInReturn( int move ); -extern qboolean PM_SaberKataDone( int curmove, int newmove ); -extern qboolean PM_SaberInSpecial( int move ); -extern qboolean PM_InDeathAnim ( void ); -extern qboolean PM_StandingAnim( int anim ); -extern qboolean PM_KickMove( int move ); -extern qboolean PM_KickingAnim( int anim ); -extern qboolean PM_InAirKickingAnim( int anim ); -extern qboolean PM_SuperBreakLoseAnim( int anim ); -extern qboolean PM_SuperBreakWinAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); -extern qboolean PM_InButterfly( int anim ); -extern qboolean PM_CanRollFromSoulCal( playerState_t *ps ); -extern saberMoveName_t PM_SaberFlipOverAttackMove( void ); -extern qboolean PM_CheckFlipOverAttackMove( qboolean checkEnemy ); -extern saberMoveName_t PM_SaberJumpForwardAttackMove( void ); -extern qboolean PM_CheckJumpForwardAttackMove( void ); -extern saberMoveName_t PM_SaberBackflipAttackMove( void ); -extern qboolean PM_CheckBackflipAttackMove( void ); -extern saberMoveName_t PM_SaberDualJumpAttackMove( void ); -extern qboolean PM_CheckDualJumpAttackMove( void ); -extern saberMoveName_t PM_SaberLungeAttackMove( qboolean fallbackToNormalLunge ); -extern qboolean PM_CheckLungeAttackMove( void ); -extern qboolean PM_InSecondaryStyle( void ); -extern qboolean PM_KnockDownAnimExtended( int anim ); -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); -extern qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern float G_ForceWallJumpStrength( void ); -extern qboolean G_CheckRollSafety( gentity_t *self, int anim, float testDist ); -extern saberMoveName_t PM_CheckDualSpinProtect( void ); -extern saberMoveName_t PM_CheckPullAttack( void ); -extern qboolean JET_Flying( gentity_t *self ); -extern void JET_FlyStart( gentity_t *self ); -extern void JET_FlyStop( gentity_t *self ); -extern qboolean PM_LockedAnim( int anim ); -extern qboolean G_TryingKataAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingCartwheel( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingSpecial( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingJumpAttack( gentity_t *self, usercmd_t *cmd ); -extern qboolean G_TryingJumpForwardAttack( gentity_t *self, usercmd_t *cmd ); -extern void WP_SaberSwingSound( gentity_t *ent, int saberNum, swingType_t swingType ); -extern qboolean WP_UseFirstValidSaberStyle( gentity_t *ent, int *saberAnimLevel ); -extern qboolean WP_SaberStyleValidForSaber( gentity_t *ent, int saberAnimLevel ); - -qboolean PM_InKnockDown( playerState_t *ps ); -qboolean PM_InKnockDownOnGround( playerState_t *ps ); -qboolean PM_InGetUp( playerState_t *ps ); -qboolean PM_InRoll( playerState_t *ps ); -qboolean PM_SpinningSaberAnim( int anim ); -qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ); -qboolean PM_SpinningAnim( int anim ); -qboolean PM_FlippingAnim( int anim ); -qboolean PM_PainAnim( int anim ); -qboolean PM_RollingAnim( int anim ); -qboolean PM_SwimmingAnim( int anim ); -qboolean PM_InReboundJump( int anim ); -qboolean PM_ForceJumpingAnim( int anim ); -void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ); +extern qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse); +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +extern int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern saberMoveName_t PM_SaberAnimTransitionMove(saberMoveName_t curmove, saberMoveName_t newmove); +extern saberMoveName_t PM_AttackMoveForQuad(int quad); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern saberMoveName_t PM_SaberBounceForAttack(int move); +extern saberMoveName_t PM_SaberAttackForMovement(int forwardmove, int rightmove, int curmove); +extern saberMoveName_t PM_BrokenParryForParry(int move); +extern saberMoveName_t PM_KnockawayForParry(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInReturn(int move); +extern qboolean PM_SaberKataDone(int curmove, int newmove); +extern qboolean PM_SaberInSpecial(int move); +extern qboolean PM_InDeathAnim(void); +extern qboolean PM_StandingAnim(int anim); +extern qboolean PM_KickMove(int move); +extern qboolean PM_KickingAnim(int anim); +extern qboolean PM_InAirKickingAnim(int anim); +extern qboolean PM_SuperBreakLoseAnim(int anim); +extern qboolean PM_SuperBreakWinAnim(int anim); +extern qboolean PM_InCartwheel(int anim); +extern qboolean PM_InButterfly(int anim); +extern qboolean PM_CanRollFromSoulCal(playerState_t *ps); +extern saberMoveName_t PM_SaberFlipOverAttackMove(void); +extern qboolean PM_CheckFlipOverAttackMove(qboolean checkEnemy); +extern saberMoveName_t PM_SaberJumpForwardAttackMove(void); +extern qboolean PM_CheckJumpForwardAttackMove(void); +extern saberMoveName_t PM_SaberBackflipAttackMove(void); +extern qboolean PM_CheckBackflipAttackMove(void); +extern saberMoveName_t PM_SaberDualJumpAttackMove(void); +extern qboolean PM_CheckDualJumpAttackMove(void); +extern saberMoveName_t PM_SaberLungeAttackMove(qboolean fallbackToNormalLunge); +extern qboolean PM_CheckLungeAttackMove(void); +extern qboolean PM_InSecondaryStyle(void); +extern qboolean PM_KnockDownAnimExtended(int anim); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); +extern void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); +extern qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern float G_ForceWallJumpStrength(void); +extern qboolean G_CheckRollSafety(gentity_t *self, int anim, float testDist); +extern saberMoveName_t PM_CheckDualSpinProtect(void); +extern saberMoveName_t PM_CheckPullAttack(void); +extern qboolean JET_Flying(gentity_t *self); +extern void JET_FlyStart(gentity_t *self); +extern void JET_FlyStop(gentity_t *self); +extern qboolean PM_LockedAnim(int anim); +extern qboolean G_TryingKataAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingCartwheel(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingSpecial(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingJumpAttack(gentity_t *self, usercmd_t *cmd); +extern qboolean G_TryingJumpForwardAttack(gentity_t *self, usercmd_t *cmd); +extern void WP_SaberSwingSound(gentity_t *ent, int saberNum, swingType_t swingType); +extern qboolean WP_UseFirstValidSaberStyle(gentity_t *ent, int *saberAnimLevel); +extern qboolean WP_SaberStyleValidForSaber(gentity_t *ent, int saberAnimLevel); + +qboolean PM_InKnockDown(playerState_t *ps); +qboolean PM_InKnockDownOnGround(playerState_t *ps); +qboolean PM_InGetUp(playerState_t *ps); +qboolean PM_InRoll(playerState_t *ps); +qboolean PM_SpinningSaberAnim(int anim); +qboolean PM_GettingUpFromKnockDown(float standheight, float crouchheight); +qboolean PM_SpinningAnim(int anim); +qboolean PM_FlippingAnim(int anim); +qboolean PM_PainAnim(int anim); +qboolean PM_RollingAnim(int anim); +qboolean PM_SwimmingAnim(int anim); +qboolean PM_InReboundJump(int anim); +qboolean PM_ForceJumpingAnim(int anim); +void PM_CmdForRoll(playerState_t *ps, usercmd_t *pCmd); extern int parryDebounce[]; extern qboolean cg_usingInFrontOf; -extern qboolean player_locked; -extern qboolean MatrixMode; -qboolean waterForceJump; -extern cvar_t *g_timescale; -extern cvar_t *g_speederControlScheme; -extern cvar_t *d_slowmodeath; -extern cvar_t *g_debugMelee; -extern cvar_t *g_saberNewControlScheme; -extern cvar_t *g_stepSlideFix; -extern cvar_t *g_saberAutoBlocking; - -static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype ); - -#define FLY_NONE 0 -#define FLY_NORMAL 1 -#define FLY_VEHICLE 2 -#define FLY_HOVER 3 -int Flying = FLY_NONE; - -pmove_t *pm; -pml_t pml; +extern qboolean player_locked; +extern qboolean MatrixMode; +qboolean waterForceJump; +extern cvar_t *g_timescale; +extern cvar_t *g_speederControlScheme; +extern cvar_t *d_slowmodeath; +extern cvar_t *g_debugMelee; +extern cvar_t *g_saberNewControlScheme; +extern cvar_t *g_stepSlideFix; +extern cvar_t *g_saberAutoBlocking; + +static void PM_SetWaterLevelAtPoint(vec3_t org, int *waterlevel, int *watertype); + +#define FLY_NONE 0 +#define FLY_NORMAL 1 +#define FLY_VEHICLE 2 +#define FLY_HOVER 3 +int Flying = FLY_NONE; + +pmove_t *pm; +pml_t pml; // movement parameters -const float pm_stopspeed = 100.0f; -const float pm_duckScale = 0.50f; -const float pm_swimScale = 0.50f; -float pm_ladderScale = 0.7f; - -const float pm_vehicleaccelerate = 36.0f; -const float pm_accelerate = 12.0f; -const float pm_airaccelerate = 4.0f; -const float pm_wateraccelerate = 4.0f; -const float pm_flyaccelerate = 8.0f; - -const float pm_friction = 6.0f; -const float pm_waterfriction = 1.0f; -const float pm_flightfriction = 3.0f; - -//const float pm_frictionModifier = 3.0f; //Used for "careful" mode (when pressing use) -const float pm_airDecelRate = 1.35f; //Used for air decelleration away from current movement velocity - -int c_pmove = 0; - -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void PM_TorsoAnimation( void ); -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InDeathAnim ( void ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern weaponInfo_t cg_weapons[MAX_WEAPONS]; -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); - -extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace ); - -#define PHASER_RECHARGE_TIME 100 +const float pm_stopspeed = 100.0f; +const float pm_duckScale = 0.50f; +const float pm_swimScale = 0.50f; +float pm_ladderScale = 0.7f; + +const float pm_vehicleaccelerate = 36.0f; +const float pm_accelerate = 12.0f; +const float pm_airaccelerate = 4.0f; +const float pm_wateraccelerate = 4.0f; +const float pm_flyaccelerate = 8.0f; + +const float pm_friction = 6.0f; +const float pm_waterfriction = 1.0f; +const float pm_flightfriction = 3.0f; + +// const float pm_frictionModifier = 3.0f; //Used for "careful" mode (when pressing use) +const float pm_airDecelRate = 1.35f; // Used for air decelleration away from current movement velocity + +int c_pmove = 0; + +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void PM_TorsoAnimation(void); +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InDeathAnim(void); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern weaponInfo_t cg_weapons[MAX_WEAPONS]; +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); + +extern void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace); + +#define PHASER_RECHARGE_TIME 100 extern saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS]; -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -Vehicle_t *PM_RidingVehicle( void ) -{ - return (G_IsRidingVehicle( pm->gent )); -} +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +Vehicle_t *PM_RidingVehicle(void) { return (G_IsRidingVehicle(pm->gent)); } -extern qboolean G_ControlledByPlayer( gentity_t *self ); -qboolean PM_ControlledByPlayer( void ) -{ - return G_ControlledByPlayer( pm->gent ); -} +extern qboolean G_ControlledByPlayer(gentity_t *self); +qboolean PM_ControlledByPlayer(void) { return G_ControlledByPlayer(pm->gent); } -qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ) -{ -/* - if ( 0 && ps->clientNum < MAX_CLIENTS //real client - && ps->m_iVehicleNum//in a vehicle - && pVeh //valid vehicle data pointer - && pVeh->m_pVehicleInfo//valid vehicle info - && pVeh->m_pVehicleInfo->type == VH_FIGHTER )//fighter - //FIXME: specify per vehicle instead of assuming true for all fighters - //FIXME: map/server setting? - {//can roll and pitch without limitation! - return qtrue; - }*/ +qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh) { + /* + if ( 0 && ps->clientNum < MAX_CLIENTS //real client + && ps->m_iVehicleNum//in a vehicle + && pVeh //valid vehicle data pointer + && pVeh->m_pVehicleInfo//valid vehicle info + && pVeh->m_pVehicleInfo->type == VH_FIGHTER )//fighter + //FIXME: specify per vehicle instead of assuming true for all fighters + //FIXME: map/server setting? + {//can roll and pitch without limitation! + return qtrue; + }*/ return qfalse; } - /* =============== PM_AddEvent =============== */ -void PM_AddEvent( int newEvent ) -{ - AddEventToPlayerstate( newEvent, 0, pm->ps ); -} - -qboolean PM_PredictJumpSafe( vec3_t jumpHorizDir, float jumpHorizSpeed, float jumpVertSpeed, int predictTimeLength ) -{ - return qtrue; -} +void PM_AddEvent(int newEvent) { AddEventToPlayerstate(newEvent, 0, pm->ps); } +qboolean PM_PredictJumpSafe(vec3_t jumpHorizDir, float jumpHorizSpeed, float jumpVertSpeed, int predictTimeLength) { return qtrue; } -void PM_GrabWallForJump( int anim ) -{//NOTE!!! assumes an appropriate anim is being passed in!!! - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_RESTART|SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - PM_AddEvent( EV_JUMP );//make sound for grab +void PM_GrabWallForJump(int anim) { // NOTE!!! assumes an appropriate anim is being passed in!!! + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_RESTART | SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + PM_AddEvent(EV_JUMP); // make sound for grab pm->ps->pm_flags |= PMF_STUCK_TO_WALL; } -qboolean PM_CheckGrabWall( trace_t *trace ) -{ - if ( !pm->gent || !pm->gent->client ) - { +qboolean PM_CheckGrabWall(trace_t *trace) { + if (!pm->gent || !pm->gent->client) { return qfalse; } - if ( pm->gent->health <= 0 ) - {//must be alive + if (pm->gent->health <= 0) { // must be alive return qfalse; } - if ( pm->gent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//must be in air + if (pm->gent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // must be in air return qfalse; } - if ( trace->plane.normal[2] != 0 ) - {//must be a flat wall + if (trace->plane.normal[2] != 0) { // must be a flat wall return qfalse; } - if ( !trace->plane.normal[0] && !trace->plane.normal[1] ) - {//invalid normal + if (!trace->plane.normal[0] && !trace->plane.normal[1]) { // invalid normal return qfalse; } - if ( (trace->contents&(CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP)) ) - {//can't jump off of clip brushes + if ((trace->contents & (CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP))) { // can't jump off of clip brushes return qfalse; } - if ( pm->gent->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1 ) - {//must have at least FJ 1 + if (pm->gent->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1) { // must have at least FJ 1 return qfalse; } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->gent->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_3 ) - {//player must have force jump 3 + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + pm->gent->client->ps.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_3) { // player must have force jump 3 return qfalse; } - if ( (pm->ps->saber[0].saberFlags&SFL_NO_WALL_GRAB) ) - { + if ((pm->ps->saber[0].saberFlags & SFL_NO_WALL_GRAB)) { return qfalse; } - if ( pm->ps->dualSabers - && (pm->ps->saber[1].saberFlags&SFL_NO_WALL_GRAB) ) - { + if (pm->ps->dualSabers && (pm->ps->saber[1].saberFlags & SFL_NO_WALL_GRAB)) { return qfalse; } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//player - //only if we were in a longjump - if ( pm->ps->legsAnim != BOTH_FORCELONGLEAP_START - && pm->ps->legsAnim != BOTH_FORCELONGLEAP_ATTACK ) - { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // player + // only if we were in a longjump + if (pm->ps->legsAnim != BOTH_FORCELONGLEAP_START && pm->ps->legsAnim != BOTH_FORCELONGLEAP_ATTACK) { return qfalse; } - //hit a flat wall during our long jump, see if we should grab it + // hit a flat wall during our long jump, see if we should grab it vec3_t moveDir; - VectorCopy( pm->ps->velocity, moveDir ); - VectorNormalize( moveDir ); - if ( DotProduct( moveDir, trace->plane.normal ) > -0.65f ) - {//not enough of a direct impact, just slide off + VectorCopy(pm->ps->velocity, moveDir); + VectorNormalize(moveDir); + if (DotProduct(moveDir, trace->plane.normal) > -0.65f) { // not enough of a direct impact, just slide off return qfalse; } - if ( fabs(trace->plane.normal[2]) > MAX_WALL_GRAB_SLOPE ) - { + if (fabs(trace->plane.normal[2]) > MAX_WALL_GRAB_SLOPE) { return qfalse; } - //grab it! - //FIXME: stop Matrix effect! - VectorClear( pm->ps->velocity ); - //FIXME: stop slidemove! - //NOTE: we know it's forward, so... - PM_GrabWallForJump( BOTH_FORCEWALLREBOUND_FORWARD ); + // grab it! + // FIXME: stop Matrix effect! + VectorClear(pm->ps->velocity); + // FIXME: stop slidemove! + // NOTE: we know it's forward, so... + PM_GrabWallForJump(BOTH_FORCEWALLREBOUND_FORWARD); return qtrue; - } - else - {//NPCs - if ( PM_InReboundJump( pm->ps->legsAnim ) ) - {//already in a rebound! + } else { // NPCs + if (PM_InReboundJump(pm->ps->legsAnim)) { // already in a rebound! return qfalse; } - if ( (pm->ps->eFlags&EF_FORCE_GRIPPED) ) - {//being gripped! + if ((pm->ps->eFlags & EF_FORCE_GRIPPED)) { // being gripped! return qfalse; } /* @@ -339,86 +301,70 @@ qboolean PM_CheckGrabWall( trace_t *trace ) return qfalse; } */ - if ( pm->gent->NPC && (pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//faling to our death! + if (pm->gent->NPC && (pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // faling to our death! return qfalse; } - //FIXME: random chance, based on skill/rank? - if ( pm->ps->legsAnim != BOTH_FORCELONGLEAP_START - && pm->ps->legsAnim != BOTH_FORCELONGLEAP_ATTACK ) - {//not in a long-jump - if ( !pm->gent->enemy ) - {//no enemy + // FIXME: random chance, based on skill/rank? + if (pm->ps->legsAnim != BOTH_FORCELONGLEAP_START && pm->ps->legsAnim != BOTH_FORCELONGLEAP_ATTACK) { // not in a long-jump + if (!pm->gent->enemy) { // no enemy return qfalse; - } - else - {//see if the enemy is in the direction of the wall or above us - //if ( pm->gent->enemy->currentOrigin[2] < (pm->ps->origin[2]-128) ) - {//enemy is way below us + } else { // see if the enemy is in the direction of the wall or above us + // if ( pm->gent->enemy->currentOrigin[2] < (pm->ps->origin[2]-128) ) + { // enemy is way below us vec3_t enemyDir; - VectorSubtract( pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir ); + VectorSubtract(pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir); enemyDir[2] = 0; - VectorNormalize( enemyDir ); - if ( DotProduct( enemyDir, trace->plane.normal ) < 0.65f ) - {//jumping off this wall would not launch me in the general direction of my enemy + VectorNormalize(enemyDir); + if (DotProduct(enemyDir, trace->plane.normal) < 0.65f) { // jumping off this wall would not launch me in the general direction of my enemy return qfalse; } } } } - //FIXME: check for ground close beneath us? - //FIXME: check for obstructions in the dir we're going to jump + // FIXME: check for ground close beneath us? + // FIXME: check for obstructions in the dir we're going to jump // - including "do not enter" brushes! - //hit a flat wall during our long jump, see if we should grab it + // hit a flat wall during our long jump, see if we should grab it vec3_t moveDir; - VectorCopy( pm->ps->velocity, moveDir ); - VectorNormalize( moveDir ); - if ( DotProduct( moveDir, trace->plane.normal ) > -0.65f ) - {//not enough of a direct impact, just slide off + VectorCopy(pm->ps->velocity, moveDir); + VectorNormalize(moveDir); + if (DotProduct(moveDir, trace->plane.normal) > -0.65f) { // not enough of a direct impact, just slide off return qfalse; } - //Okay, now see if jumping off this thing would send us into a do not enter brush - if ( !PM_PredictJumpSafe( trace->plane.normal, JUMP_OFF_WALL_SPEED, G_ForceWallJumpStrength(), 1500 ) ) - {//we would hit a do not enter brush, so don't grab the wall + // Okay, now see if jumping off this thing would send us into a do not enter brush + if (!PM_PredictJumpSafe(trace->plane.normal, JUMP_OFF_WALL_SPEED, G_ForceWallJumpStrength(), + 1500)) { // we would hit a do not enter brush, so don't grab the wall return qfalse; } - //grab it! - //Pick the proper anim + // grab it! + // Pick the proper anim int anim = BOTH_FORCEWALLREBOUND_FORWARD; - vec3_t facingAngles, wallDir, fwdDir, rtDir; - VectorSubtract( trace->endpos, pm->gent->lastOrigin, wallDir ); + vec3_t facingAngles, wallDir, fwdDir, rtDir; + VectorSubtract(trace->endpos, pm->gent->lastOrigin, wallDir); wallDir[2] = 0; - VectorNormalize( wallDir ); - VectorSet( facingAngles, 0, pm->ps->viewangles[YAW], 0 ); - AngleVectors( facingAngles, fwdDir, rtDir, NULL ); - float fDot = DotProduct( fwdDir, wallDir ); - if ( fabs( fDot ) >= 0.5f ) - {//hit a wall in front/behind - if ( fDot > 0.0f ) - {//in front + VectorNormalize(wallDir); + VectorSet(facingAngles, 0, pm->ps->viewangles[YAW], 0); + AngleVectors(facingAngles, fwdDir, rtDir, NULL); + float fDot = DotProduct(fwdDir, wallDir); + if (fabs(fDot) >= 0.5f) { // hit a wall in front/behind + if (fDot > 0.0f) { // in front anim = BOTH_FORCEWALLREBOUND_FORWARD; - } - else - {//behind + } else { // behind anim = BOTH_FORCEWALLREBOUND_BACK; } - } - else if ( DotProduct( rtDir, wallDir ) > 0 ) - {//hit a wall on the right + } else if (DotProduct(rtDir, wallDir) > 0) { // hit a wall on the right anim = BOTH_FORCEWALLREBOUND_RIGHT; - } - else - {//hit a wall on the left + } else { // hit a wall on the left anim = BOTH_FORCEWALLREBOUND_LEFT; } - VectorClear( pm->ps->velocity ); - //FIXME: stop slidemove! - PM_GrabWallForJump( anim ); + VectorClear(pm->ps->velocity); + // FIXME: stop slidemove! + PM_GrabWallForJump(anim); return qtrue; } - //return qfalse; + // return qfalse; } /* =============== @@ -426,39 +372,34 @@ qboolean PM_ClientImpact( trace_t *trace, qboolean damageSelf ) =============== */ -qboolean PM_ClientImpact( trace_t *trace, qboolean damageSelf ) -{ - gentity_t *traceEnt; - int otherEntityNum = trace->entityNum; +qboolean PM_ClientImpact(trace_t *trace, qboolean damageSelf) { + gentity_t *traceEnt; + int otherEntityNum = trace->entityNum; - if ( !pm->gent ) - { + if (!pm->gent) { return qfalse; } traceEnt = &g_entities[otherEntityNum]; - if ( otherEntityNum == ENTITYNUM_WORLD - || (traceEnt->bmodel && traceEnt->s.pos.trType == TR_STATIONARY ) ) - {//hit world or a non-moving brush - if ( PM_CheckGrabWall( trace ) ) - {//stopped on the wall + if (otherEntityNum == ENTITYNUM_WORLD || (traceEnt->bmodel && traceEnt->s.pos.trType == TR_STATIONARY)) { // hit world or a non-moving brush + if (PM_CheckGrabWall(trace)) { // stopped on the wall return qtrue; } } - if( (VectorLength( pm->ps->velocity )*(pm->gent->mass/10)) >= 100 && (pm->gent->client->NPC_class == CLASS_VEHICLE || pm->ps->lastOnGround+100material>=MAT_GLASS&&pm->gent->lastImpact+100<=level.time)) + if ((VectorLength(pm->ps->velocity) * (pm->gent->mass / 10)) >= 100 && + (pm->gent->client->NPC_class == CLASS_VEHICLE || + pm->ps->lastOnGround + 100 < level.time)) // was 300 ||(other->material>=MAT_GLASS&&pm->gent->lastImpact+100<=level.time)) { - DoImpact( pm->gent, &g_entities[otherEntityNum], damageSelf, trace ); + DoImpact(pm->gent, &g_entities[otherEntityNum], damageSelf, trace); } - if ( otherEntityNum >= ENTITYNUM_WORLD ) - { + if (otherEntityNum >= ENTITYNUM_WORLD) { return qfalse; } - if ( !traceEnt || !(traceEnt->contents&pm->tracemask) ) - {//it's dead or not in my way anymore + if (!traceEnt || !(traceEnt->contents & pm->tracemask)) { // it's dead or not in my way anymore return qtrue; } @@ -469,19 +410,19 @@ qboolean PM_ClientImpact( trace_t *trace, qboolean damageSelf ) PM_AddTouchEnt =============== */ -void PM_AddTouchEnt( int entityNum ) { - int i; +void PM_AddTouchEnt(int entityNum) { + int i; - if ( entityNum == ENTITYNUM_WORLD ) { + if (entityNum == ENTITYNUM_WORLD) { return; } - if ( pm->numtouch == MAXTOUCH ) { + if (pm->numtouch == MAXTOUCH) { return; } // see if it is already added - for ( i = 0 ; i < pm->numtouch ; i++ ) { - if ( pm->touchents[ i ] == entityNum ) { + for (i = 0; i < pm->numtouch; i++) { + if (pm->touchents[i] == entityNum) { return; } } @@ -491,9 +432,6 @@ void PM_AddTouchEnt( int entityNum ) { pm->numtouch++; } - - - /* ================== PM_ClipVelocity @@ -506,30 +444,28 @@ Slide off of the impacting surface ================== */ -void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) { - float backoff; - float change; - float oldInZ; - int i; - - if ( (pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//no sliding! - VectorCopy( in, out ); +void PM_ClipVelocity(vec3_t in, vec3_t normal, vec3_t out, float overbounce) { + float backoff; + float change; + float oldInZ; + int i; + + if ((pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // no sliding! + VectorCopy(in, out); return; } oldInZ = in[2]; - backoff = DotProduct (in, normal); + backoff = DotProduct(in, normal); - if ( backoff < 0 ) { + if (backoff < 0) { backoff *= overbounce; } else { backoff /= overbounce; } - for ( i=0 ; i<3 ; i++ ) - { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; /* if ( i == 2 && Flying == FLY_HOVER && change > 0 ) {//don't pull a hovercraft down @@ -537,24 +473,20 @@ void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) { } else */ - { - out[i] = in[i] - change; - } + { out[i] = in[i] - change; } } - if ( g_stepSlideFix->integer ) - { - if ( pm->ps->clientNum < MAX_CLIENTS//normal player - && normal[2] < MIN_WALK_NORMAL )//sliding against a steep slope + if (g_stepSlideFix->integer) { + if (pm->ps->clientNum < MAX_CLIENTS // normal player + && normal[2] < MIN_WALK_NORMAL) // sliding against a steep slope { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE )//on the ground - {//if walking on the ground, don't slide up slopes that are too steep to walk on + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) // on the ground + { // if walking on the ground, don't slide up slopes that are too steep to walk on out[2] = oldInZ; } } } } - /* ================== PM_Friction @@ -562,23 +494,23 @@ PM_Friction Handles both ground friction and water friction ================== */ -static void PM_Friction( void ) { - vec3_t vec; - float *vel; - float speed, newspeed, control; - float drop, friction = pm->ps->friction; +static void PM_Friction(void) { + vec3_t vec; + float *vel; + float speed, newspeed, control; + float drop, friction = pm->ps->friction; vel = pm->ps->velocity; - VectorCopy( vel, vec ); - if ( pml.walking ) { - vec[2] = 0; // ignore slope movement + VectorCopy(vel, vec); + if (pml.walking) { + vec[2] = 0; // ignore slope movement } speed = VectorLength(vec); if (speed < 1) { vel[0] = 0; - vel[1] = 0; // allow sinking underwater + vel[1] = 0; // allow sinking underwater // FIXME: still have z friction underwater? return; } @@ -586,25 +518,19 @@ static void PM_Friction( void ) { drop = 0; // apply ground friction, even if on ladder - if ( pm->gent - && pm->gent->client - && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->m_pVehicle - && pm->gent->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->m_pVehicle && + pm->gent->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { friction = pm->gent->m_pVehicle->m_pVehicleInfo->friction; - if ( pm->gent->m_pVehicle && pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0 ) - {//in a hovering vehicle, have air control - if ( pm->gent->m_pVehicle->m_ulFlags & VEH_FLYING ) - { + if (pm->gent->m_pVehicle && pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) { // in a hovering vehicle, have air control + if (pm->gent->m_pVehicle->m_ulFlags & VEH_FLYING) { friction = 0.10f; } } - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION) ) - { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; /* if ( Flying == FLY_HOVER ) { @@ -627,36 +553,24 @@ static void PM_Friction( void ) { } */ } - } - else if ( Flying != FLY_NORMAL ) - { - if ( (pm->watertype & CONTENTS_LADDER) || pm->waterlevel <= 1 ) - { - if ( (pm->watertype & CONTENTS_LADDER) || (pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK)) ) - { + } else if (Flying != FLY_NORMAL) { + if ((pm->watertype & CONTENTS_LADDER) || pm->waterlevel <= 1) { + if ((pm->watertype & CONTENTS_LADDER) || (pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK))) { // if getting knocked back, no friction - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION) ) - { - if ( pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND ) - {//super forward jump - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//not in air - if ( pm->cmd.forwardmove < 0 ) - {//trying to hold back some - friction *= 0.5f;//0.25f; - } - else - {//free slide - friction *= 0.2f;//0.1f; + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { + if (pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK || + pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND) { // super forward jump + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // not in air + if (pm->cmd.forwardmove < 0) { // trying to hold back some + friction *= 0.5f; // 0.25f; + } else { // free slide + friction *= 0.2f; // 0.1f; } pm->cmd.forwardmove = pm->cmd.rightmove = 0; - if ( pml.groundPlane && pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND ) - { - //slide effect - G_PlayEffect( "env/slide_dust", pml.groundTrace.endpos, pml.groundTrace.plane.normal ); - //FIXME: slide sound + if (pml.groundPlane && pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND) { + // slide effect + G_PlayEffect("env/slide_dust", pml.groundTrace.endpos, pml.groundTrace.plane.normal); + // FIXME: slide sound } } } @@ -671,41 +585,33 @@ static void PM_Friction( void ) { */ control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; } } } - } - else if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && pm->gent->client->moveType == MT_FLYSWIM ) - {//player as Boba - drop += speed*pm_waterfriction*pml.frametime; + } else if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->gent && pm->gent->client && + (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + pm->gent->client->moveType == MT_FLYSWIM) { // player as Boba + drop += speed * pm_waterfriction * pml.frametime; } - if ( Flying == FLY_VEHICLE ) - { - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION) ) - { + if (Flying == FLY_VEHICLE) { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; } } // apply water friction even if just wading - if ( !waterForceJump ) - { - if ( pm->waterlevel && !(pm->watertype & CONTENTS_LADDER)) - { - drop += speed*pm_waterfriction*pm->waterlevel*pml.frametime; + if (!waterForceJump) { + if (pm->waterlevel && !(pm->watertype & CONTENTS_LADDER)) { + drop += speed * pm_waterfriction * pm->waterlevel * pml.frametime; } } // apply flying friction - if ( pm->ps->pm_type == PM_SPECTATOR ) - { - drop += speed*pm_flightfriction*pml.frametime; + if (pm->ps->pm_type == PM_SPECTATOR) { + drop += speed * pm_flightfriction * pml.frametime; } // scale the velocity @@ -720,7 +626,6 @@ static void PM_Friction( void ) { vel[2] = vel[2] * newspeed; } - /* ============== PM_Accelerate @@ -729,24 +634,23 @@ Handles user intended acceleration ============== */ -static void PM_Accelerate( vec3_t wishdir, float wishspeed, float accel ) -{ - int i; - float addspeed, accelspeed, currentspeed; +static void PM_Accelerate(vec3_t wishdir, float wishspeed, float accel) { + int i; + float addspeed, accelspeed, currentspeed; - currentspeed = DotProduct (pm->ps->velocity, wishdir); + currentspeed = DotProduct(pm->ps->velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0) { return; } - accelspeed = ( accel * pml.frametime ) * wishspeed; + accelspeed = (accel * pml.frametime) * wishspeed; if (accelspeed > addspeed) { accelspeed = addspeed; } - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { pm->ps->velocity[i] += accelspeed * wishdir[i]; } } @@ -760,33 +664,29 @@ This allows the clients to use axial -127 to 127 values for all directions without getting a sqrt(2) distortion in speed. ============ */ -static float PM_CmdScale( usercmd_t *cmd ) -{ - int max; - float total; - float scale; +static float PM_CmdScale(usercmd_t *cmd) { + int max; + float total; + float scale; - max = abs( cmd->forwardmove ); + max = abs(cmd->forwardmove); - if ( abs( cmd->rightmove ) > max ) { - max = abs( cmd->rightmove ); + if (abs(cmd->rightmove) > max) { + max = abs(cmd->rightmove); } - if ( abs( cmd->upmove ) > max ) { - max = abs( cmd->upmove ); + if (abs(cmd->upmove) > max) { + max = abs(cmd->upmove); } - if ( !max ) { + if (!max) { return 0; } - total = sqrt( (float)(( cmd->forwardmove * cmd->forwardmove ) - + ( cmd->rightmove * cmd->rightmove ) - + ( cmd->upmove * cmd->upmove )) ); + total = sqrt((float)((cmd->forwardmove * cmd->forwardmove) + (cmd->rightmove * cmd->rightmove) + (cmd->upmove * cmd->upmove))); - scale = (float) pm->ps->speed * max / ( 127.0f * total ); + scale = (float)pm->ps->speed * max / (127.0f * total); return scale; } - /* ================ PM_SetMovementDir @@ -795,48 +695,45 @@ Determine the rotation of the legs reletive to the facing dir ================ */ -static void PM_SetMovementDir( void ) { - if ( pm->cmd.forwardmove || pm->cmd.rightmove ) { - if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0 ) { +static void PM_SetMovementDir(void) { + if (pm->cmd.forwardmove || pm->cmd.rightmove) { + if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 0; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 1; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 2; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 3; - } else if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 4; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 5; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 6; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 7; } } else { // if they aren't actively going directly sideways, // change the animation to the diagonal so they // don't stop too crooked - if ( pm->ps->movementDir == 2 ) { + if (pm->ps->movementDir == 2) { pm->ps->movementDir = 1; - } else if ( pm->ps->movementDir == 6 ) { + } else if (pm->ps->movementDir == 6) { pm->ps->movementDir = 7; } } } - /* ============= PM_CheckJump ============= */ #define METROID_JUMP 1 -qboolean PM_InReboundJump( int anim ) -{ - switch ( anim ) - { +qboolean PM_InReboundJump(int anim) { + switch (anim) { case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEWALLREBOUND_LEFT: case BOTH_FORCEWALLREBOUND_BACK: @@ -847,10 +744,8 @@ qboolean PM_InReboundJump( int anim ) return qfalse; } -qboolean PM_InReboundHold( int anim ) -{ - switch ( anim ) - { +qboolean PM_InReboundHold(int anim) { + switch (anim) { case BOTH_FORCEWALLHOLD_FORWARD: case BOTH_FORCEWALLHOLD_LEFT: case BOTH_FORCEWALLHOLD_BACK: @@ -861,10 +756,8 @@ qboolean PM_InReboundHold( int anim ) return qfalse; } -qboolean PM_InReboundRelease( int anim ) -{ - switch ( anim ) - { +qboolean PM_InReboundRelease(int anim) { + switch (anim) { case BOTH_FORCEWALLRELEASE_FORWARD: case BOTH_FORCEWALLRELEASE_LEFT: case BOTH_FORCEWALLRELEASE_BACK: @@ -875,10 +768,8 @@ qboolean PM_InReboundRelease( int anim ) return qfalse; } -qboolean PM_InBackFlip( int anim ) -{ - switch ( anim ) - { +qboolean PM_InBackFlip(int anim) { + switch (anim) { case BOTH_FLIP_BACK1: case BOTH_FLIP_BACK2: case BOTH_FLIP_BACK3: @@ -889,10 +780,8 @@ qboolean PM_InBackFlip( int anim ) return qfalse; } -qboolean PM_InSpecialJump( int anim ) -{ - switch ( anim ) - { +qboolean PM_InSpecialJump(int anim) { + switch (anim) { case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_RIGHT_STOP: case BOTH_WALL_RUN_RIGHT_FLIP: @@ -909,8 +798,8 @@ qboolean PM_InSpecialJump( int anim ) case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_ARIAL_LEFT: @@ -930,73 +819,59 @@ qboolean PM_InSpecialJump( int anim ) case BOTH_A7_SOULCAL: return qtrue; } - if ( PM_InReboundJump( anim ) ) - { + if (PM_InReboundJump(anim)) { return qtrue; } - if ( PM_InReboundHold( anim ) ) - { + if (PM_InReboundHold(anim)) { return qtrue; } - if ( PM_InReboundRelease( anim ) ) - { + if (PM_InReboundRelease(anim)) { return qtrue; } - if ( PM_InBackFlip( anim ) ) - { + if (PM_InBackFlip(anim)) { return qtrue; } return qfalse; } -extern void CG_PlayerLockedWeaponSpeech( int jumping ); -qboolean PM_ForceJumpingUp( gentity_t *gent ) -{ - if ( !gent || !gent->client ) - { +extern void CG_PlayerLockedWeaponSpeech(int jumping); +qboolean PM_ForceJumpingUp(gentity_t *gent) { + if (!gent || !gent->client) { return qfalse; } - if ( gent->NPC ) - {//this is ONLY for the player - if ( player - && player->client - && player->client->ps.viewEntity == gent->s.number ) - {//okay to jump if an NPC controlled by the player - } - else - { + if (gent->NPC) { // this is ONLY for the player + if (player && player->client && player->client->ps.viewEntity == gent->s.number) { // okay to jump if an NPC controlled by the player + } else { return qfalse; } } - if ( !(gent->client->ps.forcePowersActive&(1<client->ps.forceJumpCharge ) - {//already jumped and let go + if (!(gent->client->ps.forcePowersActive & (1 << FP_LEVITATION)) && gent->client->ps.forceJumpCharge) { // already jumped and let go return qfalse; } - if ( PM_InSpecialJump( gent->client->ps.legsAnim ) ) - { + if (PM_InSpecialJump(gent->client->ps.legsAnim)) { return qfalse; } - if ( PM_InKnockDown( &gent->client->ps ) ) - { + if (PM_InKnockDown(&gent->client->ps)) { return qfalse; } - if ( (gent->s.numbers.number < MAX_CLIENTS || G_ControlledByPlayer(gent)) && in_camera) { // player can't use force powers in cinematic return qfalse; } - if ( gent->client->ps.groundEntityNum == ENTITYNUM_NONE //in air - && ( (gent->client->ps.pm_flags&PMF_JUMPING) && gent->client->ps.velocity[2] > 0 )//jumped & going up or at water surface///*(gent->client->ps.waterHeightLevel==WHL_SHOULDERS&&gent->client->usercmd.upmove>0) ||*/ - && gent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 //force-jump capable - && !(gent->client->ps.pm_flags&PMF_TRIGGER_PUSHED) )//not pushed by a trigger + if (gent->client->ps.groundEntityNum == ENTITYNUM_NONE // in air + && ((gent->client->ps.pm_flags & PMF_JUMPING) && + gent->client->ps.velocity[2] > + 0) // jumped & going up or at water surface///*(gent->client->ps.waterHeightLevel==WHL_SHOULDERS&&gent->client->usercmd.upmove>0) ||*/ + && gent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // force-jump capable + && !(gent->client->ps.pm_flags & PMF_TRIGGER_PUSHED)) // not pushed by a trigger { - if( gent->flags & FL_LOCK_PLAYER_WEAPONS ) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + if (gent->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one { - CG_PlayerLockedWeaponSpeech( qtrue ); + CG_PlayerLockedWeaponSpeech(qtrue); return qfalse; } return qtrue; @@ -1004,80 +879,55 @@ qboolean PM_ForceJumpingUp( gentity_t *gent ) return qfalse; } -static void PM_JumpForDir( void ) -{ +static void PM_JumpForDir(void) { int anim = BOTH_JUMP1; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_JUMPBACK1; pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_JUMPRIGHT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_JUMPLEFT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else - { + } else { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; } - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,anim,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms - } -} - -qboolean PM_GentCantJump( gentity_t *gent ) -{//FIXME: ugh, hacky, set a flag on NPC or something, please... - if ( gent && gent->client && - ( gent->client->NPC_class == CLASS_ATST || - gent->client->NPC_class == CLASS_GONK || - gent->client->NPC_class == CLASS_MARK1 || - gent->client->NPC_class == CLASS_MARK2 || - gent->client->NPC_class == CLASS_MOUSE || - gent->client->NPC_class == CLASS_PROBE || - gent->client->NPC_class == CLASS_PROTOCOL || - gent->client->NPC_class == CLASS_R2D2 || - gent->client->NPC_class == CLASS_R5D2 || - gent->client->NPC_class == CLASS_SEEKER || - gent->client->NPC_class == CLASS_REMOTE || - gent->client->NPC_class == CLASS_SENTRY ) ) - { + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + } +} + +qboolean PM_GentCantJump(gentity_t *gent) { // FIXME: ugh, hacky, set a flag on NPC or something, please... + if (gent && gent->client && + (gent->client->NPC_class == CLASS_ATST || gent->client->NPC_class == CLASS_GONK || gent->client->NPC_class == CLASS_MARK1 || + gent->client->NPC_class == CLASS_MARK2 || gent->client->NPC_class == CLASS_MOUSE || gent->client->NPC_class == CLASS_PROBE || + gent->client->NPC_class == CLASS_PROTOCOL || gent->client->NPC_class == CLASS_R2D2 || gent->client->NPC_class == CLASS_R5D2 || + gent->client->NPC_class == CLASS_SEEKER || gent->client->NPC_class == CLASS_REMOTE || gent->client->NPC_class == CLASS_SENTRY)) { return qtrue; } return qfalse; } -static qboolean PM_CheckJump( void ) -{ - //Don't allow jump until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { +static qboolean PM_CheckJump(void) { + // Don't allow jump until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return qfalse; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps ) ) - {//in knockdown + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return qfalse; } - if ( PM_GentCantJump( pm->gent ) ) - { + if (PM_GentCantJump(pm->gent)) { return qfalse; } - if ( PM_KickingAnim( pm->ps->legsAnim ) && !PM_InAirKickingAnim( pm->ps->legsAnim ) ) - {//can't jump when in a kicking anim + if (PM_KickingAnim(pm->ps->legsAnim) && !PM_InAirKickingAnim(pm->ps->legsAnim)) { // can't jump when in a kicking anim return qfalse; } /* @@ -1088,22 +938,15 @@ static qboolean PM_CheckJump( void ) */ #if METROID_JUMP - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->gent && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) ) - {//player playing as boba fett - if ( pm->cmd.upmove > 0 ) - {//turn on/go up - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE && !(pm->ps->pm_flags&PMF_JUMP_HELD) ) - {//double-tap - must activate while in air - if ( !JET_Flying( pm->gent ) ) - { - JET_FlyStart( pm->gent ); + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->gent && pm->gent->client && + (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER)) { // player playing as boba fett + if (pm->cmd.upmove > 0) { // turn on/go up + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && !(pm->ps->pm_flags & PMF_JUMP_HELD)) { // double-tap - must activate while in air + if (!JET_Flying(pm->gent)) { + JET_FlyStart(pm->gent); } } - } - else if ( pm->cmd.upmove < 0 ) - {//turn it off (or should we just go down)? + } else if (pm->cmd.upmove < 0) { // turn it off (or should we just go down)? /* if ( JET_Flying( pm->gent ) ) { @@ -1111,119 +954,101 @@ static qboolean PM_CheckJump( void ) } */ } - } - else if ( pm->waterlevel < 3 )//|| (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) + } else if (pm->waterlevel < 3) //|| (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) { - if ( pm->ps->gravity > 0 ) - {//can't do this in zero-G - if ( pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND ) - {//in the middle of a force long-jump + if (pm->ps->gravity > 0) { // can't do this in zero-G + if (pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK || + pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND) { // in the middle of a force long-jump /* if ( pm->ps->groundEntityNum == ENTITYNUM_NONE && pm->cmd.upmove > 0 && pm->cmd.forwardmove > 0 ) */ - if ( (pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK) - && pm->ps->legsAnimTimer > 0 ) - {//in the air - //FIXME: need an actual set time so it doesn't matter when the attack happens - //FIXME: make sure we don't jump further than force jump 3 allows - vec3_t jFwdAngs, jFwdVec; - VectorSet( jFwdAngs, 0, pm->ps->viewangles[YAW], 0 ); - AngleVectors( jFwdAngs, jFwdVec, NULL, NULL ); + if ((pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK) && pm->ps->legsAnimTimer > 0) { // in the + // air + // FIXME: need an actual set time so it doesn't matter when the attack happens + // FIXME: make sure we don't jump further than force jump 3 allows + vec3_t jFwdAngs, jFwdVec; + VectorSet(jFwdAngs, 0, pm->ps->viewangles[YAW], 0); + AngleVectors(jFwdAngs, jFwdVec, NULL, NULL); float oldZVel = pm->ps->velocity[2]; - if ( pm->ps->legsAnimTimer > 150 && oldZVel < 0 ) - { + if (pm->ps->legsAnimTimer > 150 && oldZVel < 0) { oldZVel = 0; } - VectorScale( jFwdVec, FORCE_LONG_LEAP_SPEED, pm->ps->velocity ); + VectorScale(jFwdVec, FORCE_LONG_LEAP_SPEED, pm->ps->velocity); pm->ps->velocity[2] = oldZVel; pm->ps->pm_flags |= PMF_JUMP_HELD; - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - pm->ps->forcePowersActive |= (1<ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); return qtrue; - } - else - {//landing-slide - if ( pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK ) - {//still in start anim, but it's run out - pm->ps->forcePowersActive |= (1<ps->groundEntityNum == ENTITYNUM_NONE ) - {//still in air? - //hold it for another 50ms - //PM_SetAnim( pm, SETANIM_BOTH, BOTH_FORCELONGLEAP_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } - else - {//in land-slide anim - //FIXME: force some forward movement? Less if holding back? - } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE//still in air - && pm->ps->origin[2] < pm->ps->jumpZStart )//dropped below original jump start - {//slow down + } else { // landing-slide + if (pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK) { // still in start anim, but it's run + // out + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); + if (pm->ps->groundEntityNum == + ENTITYNUM_NONE) { // still in air? + // hold it for another 50ms + // PM_SetAnim( pm, SETANIM_BOTH, BOTH_FORCELONGLEAP_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } + } else { // in land-slide anim + // FIXME: force some forward movement? Less if holding back? + } + if (pm->ps->groundEntityNum == ENTITYNUM_NONE // still in air + && pm->ps->origin[2] < pm->ps->jumpZStart) // dropped below original jump start + { // slow down pm->ps->velocity[0] *= 0.75f; pm->ps->velocity[1] *= 0.75f; - if ( (pm->ps->velocity[0]+pm->ps->velocity[1])*0.5f<=10.0f ) - {//falling straight down - PM_SetAnim( pm, SETANIM_BOTH, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE ); + if ((pm->ps->velocity[0] + pm->ps->velocity[1]) * 0.5f <= 10.0f) { // falling straight down + PM_SetAnim(pm, SETANIM_BOTH, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE); } } return qfalse; } - } - else if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) //player-only for now - && pm->cmd.upmove > 0 //trying to jump - && pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_3 //force jump 3 or better - && pm->ps->forcePower >= FORCE_LONGJUMP_POWER //this costs 20 force to do - && (pm->ps->forcePowersActive&(1<cmd.forwardmove > 0 //pushing forward - && !pm->cmd.rightmove //not strafing - && pm->ps->groundEntityNum != ENTITYNUM_NONE//not in mid-air - && !(pm->ps->pm_flags&PMF_JUMP_HELD) - //&& (float)(level.time-pm->ps->lastStationary) >= (3000.0f*g_timescale->value)//have to have a 3 second running start - relative to force speed slowdown - && (level.time-pm->ps->forcePowerDebounce[FP_SPEED]) <= 250//have to have just started the force speed within the last half second - && pm->gent ) - {//start a force long-jump! - vec3_t jFwdAngs, jFwdVec; - //BOTH_FORCELONGLEAP_ATTACK if holding attack, too? - PM_SetAnim( pm, SETANIM_BOTH, BOTH_FORCELONGLEAP_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - VectorSet( jFwdAngs, 0, pm->ps->viewangles[YAW], 0 ); - AngleVectors( jFwdAngs, jFwdVec, NULL, NULL ); - VectorScale( jFwdVec, FORCE_LONG_LEAP_SPEED, pm->ps->velocity ); + } else if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // player-only for now + && pm->cmd.upmove > 0 // trying to jump + && pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_3 // force jump 3 or better + && pm->ps->forcePower >= FORCE_LONGJUMP_POWER // this costs 20 force to do + && (pm->ps->forcePowersActive & (1 << FP_SPEED)) // force-speed is on + && pm->cmd.forwardmove > 0 // pushing forward + && !pm->cmd.rightmove // not strafing + && pm->ps->groundEntityNum != ENTITYNUM_NONE // not in mid-air + && !(pm->ps->pm_flags & PMF_JUMP_HELD) + //&& (float)(level.time-pm->ps->lastStationary) >= (3000.0f*g_timescale->value)//have to have a 3 second running start - relative to + //force speed slowdown + && (level.time - pm->ps->forcePowerDebounce[FP_SPEED]) <= 250 // have to have just started the force speed within the last half second + && pm->gent) { // start a force long-jump! + vec3_t jFwdAngs, jFwdVec; + // BOTH_FORCELONGLEAP_ATTACK if holding attack, too? + PM_SetAnim(pm, SETANIM_BOTH, BOTH_FORCELONGLEAP_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + VectorSet(jFwdAngs, 0, pm->ps->viewangles[YAW], 0); + AngleVectors(jFwdAngs, jFwdVec, NULL, NULL); + VectorScale(jFwdVec, FORCE_LONG_LEAP_SPEED, pm->ps->velocity); pm->ps->velocity[2] = 320; pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->groundEntityNum = ENTITYNUM_NONE; pm->ps->jumpZStart = pm->ps->origin[2]; pm->ps->pm_flags |= PMF_JUMP_HELD; - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - //start force jump - pm->ps->forcePowersActive |= (1<ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + // start force jump + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); pm->cmd.upmove = 0; // keep track of force jump stat - if(pm->ps->clientNum == 0) - { - if( pm->gent && pm->gent->client ) - { + if (pm->ps->clientNum == 0) { + if (pm->gent && pm->gent->client) { pm->gent->client->sess.missionStats.forceUsed[(int)FP_LEVITATION]++; } } - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - WP_ForcePowerStop( pm->gent, FP_SPEED ); - WP_ForcePowerDrain( pm->gent, FP_LEVITATION, FORCE_LONGJUMP_POWER );//drain the required force power - G_StartMatrixEffect( pm->gent, 0, pm->ps->legsAnimTimer+500 ); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + WP_ForcePowerStop(pm->gent, FP_SPEED); + WP_ForcePowerDrain(pm->gent, FP_LEVITATION, FORCE_LONGJUMP_POWER); // drain the required force power + G_StartMatrixEffect(pm->gent, 0, pm->ps->legsAnimTimer + 500); return qtrue; + } else if (PM_InCartwheel(pm->ps->legsAnim) || PM_InButterfly(pm->ps->legsAnim)) { // can't keep jumping up in cartwheels, ariels and butterflies } - else if ( PM_InCartwheel( pm->ps->legsAnim ) - || PM_InButterfly( pm->ps->legsAnim ) ) - {//can't keep jumping up in cartwheels, ariels and butterflies - } - //FIXME: still able to pogo-jump... - else if ( PM_ForceJumpingUp( pm->gent ) && (pm->ps->pm_flags&PMF_JUMP_HELD) )//||pm->ps->waterHeightLevel==WHL_SHOULDERS) ) - {//force jumping && holding jump + // FIXME: still able to pogo-jump... + else if (PM_ForceJumpingUp(pm->gent) && (pm->ps->pm_flags & PMF_JUMP_HELD)) //||pm->ps->waterHeightLevel==WHL_SHOULDERS) ) + { // force jumping && holding jump /* if ( !pm->ps->forceJumpZStart && (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) { @@ -1231,55 +1056,42 @@ static qboolean PM_CheckJump( void ) } */ float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart; - //check for max force jump level and cap off & cut z vel - if ( ( curHeight<=forceJumpHeight[0] ||//still below minimum jump height - (pm->ps->forcePower&&pm->cmd.upmove>=10) ) &&////still have force power available and still trying to jump up - curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] )//still below maximum jump height - {//can still go up - //FIXME: after a certain amount of time of held jump, play force jump sound and flip if a dir is being held - //FIXME: if hit a wall... should we cut velocity or allow them to slide up it? - //FIXME: constantly drain force power at a rate by which the usage for maximum height would use up the full cost of force jump - if ( curHeight > forceJumpHeight[0] ) - {//passed normal jump height *2? - if ( !(pm->ps->forcePowersActive&(1<ps->forcePower && pm->cmd.upmove >= 10)) && ////still have force power available and still trying to jump up + curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]) // still below maximum jump height + { // can still go up + // FIXME: after a certain amount of time of held jump, play force jump sound and flip if a dir is being held + // FIXME: if hit a wall... should we cut velocity or allow them to slide up it? + // FIXME: constantly drain force power at a rate by which the usage for maximum height would use up the full cost of force jump + if (curHeight > forceJumpHeight[0]) { // passed normal jump height *2? + if (!(pm->ps->forcePowersActive & (1 << FP_LEVITATION))) // haven't started forcejump yet { - //start force jump - pm->ps->forcePowersActive |= (1<gent ) - { - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // start force jump + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); + if (pm->gent) { + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); // keep track of force jump stat - if(pm->ps->clientNum == 0 && pm->gent->client) - { + if (pm->ps->clientNum == 0 && pm->gent->client) { pm->gent->client->sess.missionStats.forceUsed[(int)FP_LEVITATION]++; } } - //play flip - //FIXME: do this only when they stop the jump (below) or when they're just about to hit the peak of the jump - if ( PM_InAirKickingAnim( pm->ps->legsAnim ) - && pm->ps->legsAnimTimer ) - {//still in kick - } - else if ((pm->cmd.forwardmove || pm->cmd.rightmove) && //pushing in a dir - //pm->ps->legsAnim != BOTH_ARIAL_F1 &&//not already flipping - pm->ps->legsAnim != BOTH_FLIP_F && - pm->ps->legsAnim != BOTH_FLIP_B && - pm->ps->legsAnim != BOTH_FLIP_R && - pm->ps->legsAnim != BOTH_FLIP_L && - pm->ps->legsAnim != BOTH_ALORA_FLIP_1 && - pm->ps->legsAnim != BOTH_ALORA_FLIP_2 && - pm->ps->legsAnim != BOTH_ALORA_FLIP_3 - && cg.renderingThirdPerson//third person only - && !cg.zoomMode //not zoomed in - && !(pm->ps->saber[0].saberFlags&SFL_NO_FLIPS)//okay to do flips with this saber - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_FLIPS) )//okay to do flips with this saber - ) - {//FIXME: this could end up playing twice if the jump is very long... + // play flip + // FIXME: do this only when they stop the jump (below) or when they're just about to hit the peak of the jump + if (PM_InAirKickingAnim(pm->ps->legsAnim) && pm->ps->legsAnimTimer) { // still in kick + } else if ((pm->cmd.forwardmove || pm->cmd.rightmove) && // pushing in a dir + // pm->ps->legsAnim != BOTH_ARIAL_F1 &&//not already flipping + pm->ps->legsAnim != BOTH_FLIP_F && pm->ps->legsAnim != BOTH_FLIP_B && pm->ps->legsAnim != BOTH_FLIP_R && + pm->ps->legsAnim != BOTH_FLIP_L && pm->ps->legsAnim != BOTH_ALORA_FLIP_1 && pm->ps->legsAnim != BOTH_ALORA_FLIP_2 && + pm->ps->legsAnim != BOTH_ALORA_FLIP_3 && cg.renderingThirdPerson // third person only + && !cg.zoomMode // not zoomed in + && !(pm->ps->saber[0].saberFlags & SFL_NO_FLIPS) // okay to do flips with this saber + && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_FLIPS)) // okay to do flips with this saber + ) { // FIXME: this could end up playing twice if the jump is very long... int anim = BOTH_FORCEINAIR1; - int parts = SETANIM_BOTH; + int parts = SETANIM_BOTH; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { /* if ( pm->ps->forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_2 ) { @@ -1287,125 +1099,95 @@ static qboolean PM_CheckJump( void ) } else */ - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA && Q_irand( 0, 3 ) ) - { - anim = Q_irand( BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3 ); - } - else - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA && Q_irand(0, 3)) { + anim = Q_irand(BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3); + } else { anim = BOTH_FLIP_F; } - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FLIP_B; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_FLIP_R; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FLIP_L; } - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//FIXME: really want to know how far off ground we are, probably... + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (pm->ps->forcePowerLevel[FP_LEVITATION] > + FORCE_LEVEL_1) { // FIXME: really want to know how far off ground we are, probably... vec3_t facingFwd, facingRight, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - int anim = -1; - AngleVectors( facingAngles, facingFwd, facingRight, NULL ); - float dotR = DotProduct( facingRight, pm->ps->velocity ); - float dotF = DotProduct( facingFwd, pm->ps->velocity ); - if ( fabs(dotR) > fabs(dotF) * 1.5 ) - { - if ( dotR > 150 ) - { + int anim = -1; + AngleVectors(facingAngles, facingFwd, facingRight, NULL); + float dotR = DotProduct(facingRight, pm->ps->velocity); + float dotF = DotProduct(facingFwd, pm->ps->velocity); + if (fabs(dotR) > fabs(dotF) * 1.5) { + if (dotR > 150) { anim = BOTH_FORCEJUMPRIGHT1; - } - else if ( dotR < -150 ) - { + } else if (dotR < -150) { anim = BOTH_FORCEJUMPLEFT1; } - } - else - { - if ( dotF > 150 ) - { + } else { + if (dotF > 150) { anim = BOTH_FORCEJUMP1; - } - else if ( dotF < -150 ) - { + } else if (dotF < -150) { anim = BOTH_FORCEJUMPBACK1; } } - if ( anim != -1 ) - { + if (anim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else - { - if ( !pm->ps->legsAnimTimer ) - {//not in the middle of a legsAnim + } else { + if (!pm->ps->legsAnimTimer) { // not in the middle of a legsAnim int anim = pm->ps->legsAnim; int newAnim = -1; - switch ( anim ) - { + switch (anim) { case BOTH_FORCEJUMP1: - newAnim = BOTH_FORCELAND1;//BOTH_FORCEINAIR1; + newAnim = BOTH_FORCELAND1; // BOTH_FORCEINAIR1; break; case BOTH_FORCEJUMPBACK1: - newAnim = BOTH_FORCELANDBACK1;//BOTH_FORCEINAIRBACK1; + newAnim = BOTH_FORCELANDBACK1; // BOTH_FORCEINAIRBACK1; break; case BOTH_FORCEJUMPLEFT1: - newAnim = BOTH_FORCELANDLEFT1;//BOTH_FORCEINAIRLEFT1; + newAnim = BOTH_FORCELANDLEFT1; // BOTH_FORCEINAIRLEFT1; break; case BOTH_FORCEJUMPRIGHT1: - newAnim = BOTH_FORCELANDRIGHT1;//BOTH_FORCEINAIRRIGHT1; + newAnim = BOTH_FORCELANDRIGHT1; // BOTH_FORCEINAIRRIGHT1; break; } - if ( newAnim != -1 ) - { + if (newAnim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, newAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, parts, newAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } } - //need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel - pm->ps->velocity[2] = (forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]-curHeight)/forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]*forceJumpStrength[pm->ps->forcePowerLevel[FP_LEVITATION]];//JUMP_VELOCITY; + // need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel + pm->ps->velocity[2] = (forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - curHeight) / + forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] * + forceJumpStrength[pm->ps->forcePowerLevel[FP_LEVITATION]]; // JUMP_VELOCITY; pm->ps->velocity[2] /= 10; pm->ps->velocity[2] += JUMP_VELOCITY; pm->ps->pm_flags |= PMF_JUMP_HELD; - } - else if ( curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - forceJumpHeight[0] ) - {//still have some headroom, don't totally stop it - if ( pm->ps->velocity[2] > JUMP_VELOCITY ) - { + } else if (curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - + forceJumpHeight[0]) { // still have some headroom, don't totally stop it + if (pm->ps->velocity[2] > JUMP_VELOCITY) { pm->ps->velocity[2] = JUMP_VELOCITY; } - } - else - { + } else { pm->ps->velocity[2] = 0; } pm->cmd.upmove = 0; @@ -1416,305 +1198,227 @@ static qboolean PM_CheckJump( void ) #endif - //Not jumping - if ( pm->cmd.upmove < 10 ) { + // Not jumping + if (pm->cmd.upmove < 10) { return qfalse; } // must wait for jump to be released - if ( pm->ps->pm_flags & PMF_JUMP_HELD ) - { + if (pm->ps->pm_flags & PMF_JUMP_HELD) { // clear upmove so cmdscale doesn't lower running speed pm->cmd.upmove = 0; return qfalse; } - if ( pm->ps->gravity <= 0 ) - {//in low grav, you push in the dir you're facing as long as there is something behind you to shove off of - vec3_t forward, back; - trace_t trace; + if (pm->ps->gravity <= 0) { // in low grav, you push in the dir you're facing as long as there is something behind you to shove off of + vec3_t forward, back; + trace_t trace; - AngleVectors( pm->ps->viewangles, forward, NULL, NULL ); - VectorMA( pm->ps->origin, -8, forward, back ); - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask&~(CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP), (EG2_Collision)0, 0 ); + AngleVectors(pm->ps->viewangles, forward, NULL, NULL); + VectorMA(pm->ps->origin, -8, forward, back); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask & ~(CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP), + (EG2_Collision)0, 0); pm->cmd.upmove = 0; - if ( trace.fraction < 1.0f ) - { - VectorMA( pm->ps->velocity, JUMP_VELOCITY/2, forward, pm->ps->velocity ); - //FIXME: kicking off wall anim? At least check what anim we're in? - PM_SetAnim(pm,SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); - } - else - {//else no surf close enough to push off of + if (trace.fraction < 1.0f) { + VectorMA(pm->ps->velocity, JUMP_VELOCITY / 2, forward, pm->ps->velocity); + // FIXME: kicking off wall anim? At least check what anim we're in? + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FORCEJUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { // else no surf close enough to push off of return qfalse; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//need to set some things and return - //Jumping + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // need to set some things and return + // Jumping pm->ps->forceJumpZStart = 0; pml.groundPlane = qfalse; pml.walking = qfalse; - pm->ps->pm_flags |= (PMF_JUMPING|PMF_JUMP_HELD); + pm->ps->pm_flags |= (PMF_JUMPING | PMF_JUMP_HELD); pm->ps->groundEntityNum = ENTITYNUM_NONE; pm->ps->jumpZStart = pm->ps->origin[2]; - if ( pm->gent ) - { - if ( !Q3_TaskIDPending( pm->gent, TID_CHAN_VOICE ) ) - { - PM_AddEvent( EV_JUMP ); + if (pm->gent) { + if (!Q3_TaskIDPending(pm->gent, TID_CHAN_VOICE)) { + PM_AddEvent(EV_JUMP); } - } - else - { - PM_AddEvent( EV_JUMP ); + } else { + PM_AddEvent(EV_JUMP); } return qtrue; - }//else no surf close enough to push off of - } - else if ( pm->cmd.upmove > 0 //want to jump - && pm->waterlevel < 2 //not in water above ankles - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 //have force jump ability - && !(pm->ps->pm_flags&PMF_JUMP_HELD)//not holding jump from a previous jump - //&& !PM_InKnockDown( pm->ps )//not in a knockdown - && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->gent && WP_ForcePowerAvailable( pm->gent, FP_LEVITATION, 0 ) //have enough force power to jump - && ((pm->ps->clientNum&&!PM_ControlledByPlayer())||((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) )) )// yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - { - if ( pm->gent->NPC && pm->gent->NPC->rank != RANK_CREWMAN && pm->gent->NPC->rank <= RANK_LT_JG ) - {//reborn who are not acrobats can't do any of these acrobatics - //FIXME: extern these abilities in the .npc file! - } - else if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - //check for left-wall and right-wall special jumps + } // else no surf close enough to push off of + } else if (pm->cmd.upmove > 0 // want to jump + && pm->waterlevel < 2 // not in water above ankles + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // have force jump ability + && !(pm->ps->pm_flags & PMF_JUMP_HELD) // not holding jump from a previous jump + //&& !PM_InKnockDown( pm->ps )//not in a knockdown + && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->gent && WP_ForcePowerAvailable(pm->gent, FP_LEVITATION, 0) // have enough force power to jump + && ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS)))) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + { + if (pm->gent->NPC && pm->gent->NPC->rank != RANK_CREWMAN && + pm->gent->NPC->rank <= RANK_LT_JG) { // reborn who are not acrobats can't do any of these acrobatics + // FIXME: extern these abilities in the .npc file! + } else if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on the ground + // check for left-wall and right-wall special jumps int anim = -1; - float vertPush = 0; - int forcePowerCostOverride = 0; + float vertPush = 0; + int forcePowerCostOverride = 0; // Cartwheels/ariels/butterflies - if ( (pm->ps->weapon==WP_SABER&&G_TryingCartwheel(pm->gent,&pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/&&(pm->cmd.buttons&BUTTON_ATTACK))//using saber and holding focus + attack -// ||(pm->ps->weapon!=WP_SABER&&((pm->cmd.buttons&BUTTON_ATTACK)||(pm->cmd.buttons&BUTTON_ALT_ATTACK)) ) )//using any other weapon and hitting either attack button - && (((pm->ps->clientNum>=MAX_CLIENTS&&!PM_ControlledByPlayer())&&pm->cmd.upmove > 0&& pm->ps->velocity[2] >= 0 )//jumping NPC, going up already - ||((pm->ps->clientNumgent,&pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/))//focus-holding player - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_LR )/*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR*/ )// have enough power - {//holding attack and jumping - if ( pm->cmd.rightmove > 0 ) - { + if ((pm->ps->weapon == WP_SABER && G_TryingCartwheel(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/ && + (pm->cmd.buttons & BUTTON_ATTACK)) // using saber and holding focus + attack + // ||(pm->ps->weapon!=WP_SABER&&((pm->cmd.buttons&BUTTON_ATTACK)||(pm->cmd.buttons&BUTTON_ALT_ATTACK)) ) )//using any other weapon + //and hitting either attack button + && (((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->velocity[2] >= 0) // jumping NPC, going up already + || ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + G_TryingCartwheel(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/)) // focus-holding player + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, + SABER_ALT_ATTACK_POWER_LR) /*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER_LR*/) // have enough power + { // holding attack and jumping + if (pm->cmd.rightmove > 0) { // If they're using the staff we do different anims. - if ( pm->ps->saberAnimLevel == SS_STAFF - && pm->ps->weapon == WP_SABER ) - { - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) - || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 ) - { + if (pm->ps->saberAnimLevel == SS_STAFF && pm->ps->weapon == WP_SABER) { + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2) { anim = BOTH_BUTTERFLY_RIGHT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); } - } - else if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) - || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - { - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_CARTWHEELS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_CARTWHEELS)) ) - {//okay to do cartwheels with this saber - if ( pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer() ) - {//player: since we're on the ground, always do a cartwheel + } else if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { + if (!(pm->ps->saber[0].saberFlags & SFL_NO_CARTWHEELS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_CARTWHEELS))) { // okay to do cartwheels with this saber + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) { // player: since we're on the ground, always do a cartwheel /* anim = BOTH_CARTWHEEL_RIGHT; forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); */ - } - else - { + } else { vertPush = JUMP_VELOCITY; - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_RIGHT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); - } - else - { + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); + } else { anim = BOTH_CARTWHEEL_RIGHT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); } } } } - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { // If they're using the staff we do different anims. - if ( pm->ps->saberAnimLevel == SS_STAFF - && pm->ps->weapon == WP_SABER ) - { - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) - || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 ) - { + if (pm->ps->saberAnimLevel == SS_STAFF && pm->ps->weapon == WP_SABER) { + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2) { anim = BOTH_BUTTERFLY_LEFT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); } - } - else if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) - || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - { - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_CARTWHEELS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_CARTWHEELS)) ) - {//okay to do cartwheels with this saber - if ( pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer() ) - {//player: since we're on the ground, always do a cartwheel + } else if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) || pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { + if (!(pm->ps->saber[0].saberFlags & SFL_NO_CARTWHEELS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_CARTWHEELS))) { // okay to do cartwheels with this saber + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) { // player: since we're on the ground, always do a cartwheel /* anim = BOTH_CARTWHEEL_LEFT; forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); */ - } - else - { + } else { vertPush = JUMP_VELOCITY; - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_LEFT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); - } - else - { + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); + } else { anim = BOTH_CARTWHEEL_LEFT; - forcePowerCostOverride = G_CostForSpecialMove( SABER_ALT_ATTACK_POWER_LR ); + forcePowerCostOverride = G_CostForSpecialMove(SABER_ALT_ATTACK_POWER_LR); } } } } } - } - else if ( pm->cmd.rightmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing right - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_RUNS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_RUNS)) ) - {//okay to do wall-runs with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + } else if (pm->cmd.rightmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing right + if (pm->cmd.forwardmove > 0) { // wall-run + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_RUNS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_RUNS))) { // okay to do wall-runs with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_RIGHT; } - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_FLIPS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_FLIPS)) ) - {//okay to do wall-flips with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_FLIPS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_FLIPS))) { // okay to do wall-flips with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_RIGHT; } } - } - else if ( pm->cmd.rightmove < 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing left - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_RUNS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_RUNS)) ) - {//okay to do wall-runs with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + } else if (pm->cmd.rightmove < 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing left + if (pm->cmd.forwardmove > 0) { // wall-run + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_RUNS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_RUNS))) { // okay to do wall-runs with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_LEFT; } - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_FLIPS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_FLIPS)) ) - {//okay to do wall-flips with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_FLIPS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_FLIPS))) { // okay to do wall-flips with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_LEFT; } } - } - else if ( /*pm->ps->clientNum >= MAX_CLIENTS//not the player - && !PM_ControlledByPlayer() //not controlled by player - &&*/ pm->cmd.forwardmove > 0 //pushing forward - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 )//have jump 2 or higher - {//step off wall, flip backwards - if ( VectorLengthSquared( pm->ps->velocity ) > 40000 /*200*200*/) - {//have to be moving... FIXME: make sure it's opposite the wall... or at least forward? - if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 ) - {//run all the way up wwall - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_RUNS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_RUNS)) ) - {//okay to do wall-runs with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + } else if ( /*pm->ps->clientNum >= MAX_CLIENTS//not the player + && !PM_ControlledByPlayer() //not controlled by player + &&*/ pm->cmd.forwardmove > 0 // pushing forward + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) // have jump 2 or higher + { // step off wall, flip backwards + if (VectorLengthSquared(pm->ps->velocity) > + 40000 /*200*200*/) { // have to be moving... FIXME: make sure it's opposite the wall... or at least forward? + if (pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2) { // run all the way up wwall + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_RUNS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_RUNS))) { // okay to do wall-runs with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_FORCEWALLRUNFLIP_START; } - } - else - {//run just a couple steps up - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_FLIPS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_FLIPS)) ) - {//okay to do wall-flips with this saber - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else { // run just a couple steps up + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_FLIPS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_FLIPS))) { // okay to do wall-flips with this saber + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_BACK1; } } } - } - else if ( pm->cmd.forwardmove < 0 //pushing back - //&& pm->ps->clientNum//not the player - && !(pm->cmd.buttons&BUTTON_ATTACK) )//not attacking - {//back-jump does backflip... FIXME: always?! What about just doing a normal jump backwards? - if ( pm->ps->velocity[2] >= 0 ) - {//must be going up already - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_FLIPS) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_FLIPS)) ) - {//okay to do backstabs with this saber + } else if (pm->cmd.forwardmove < 0 // pushing back + //&& pm->ps->clientNum//not the player + && !(pm->cmd.buttons & BUTTON_ATTACK)) // not attacking + { // back-jump does backflip... FIXME: always?! What about just doing a normal jump backwards? + if (pm->ps->velocity[2] >= 0) { // must be going up already + if (!(pm->ps->saber[0].saberFlags & SFL_NO_FLIPS) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_FLIPS))) { // okay to do backstabs with this saber vertPush = JUMP_VELOCITY; - if ( pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA && !Q_irand( 0, 2 ) ) - { + if (pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA && !Q_irand(0, 2)) { anim = BOTH_ALORA_FLIP_B; - } - else - { - anim = PM_PickAnim( pm->gent, BOTH_FLIP_BACK1, BOTH_FLIP_BACK3 ); + } else { + anim = PM_PickAnim(pm->gent, BOTH_FLIP_BACK1, BOTH_FLIP_BACK3); } } } - } - else if ( VectorLengthSquared( pm->ps->velocity ) < 256 /*16 squared*/) - {//not moving - if ( pm->ps->weapon == WP_SABER && (pm->cmd.buttons & BUTTON_ATTACK) ) - { + } else if (VectorLengthSquared(pm->ps->velocity) < 256 /*16 squared*/) { // not moving + if (pm->ps->weapon == WP_SABER && (pm->cmd.buttons & BUTTON_ATTACK)) { saberMoveName_t overrideJumpAttackUpMove = LS_INVALID; - if ( pm->ps->saber[0].jumpAtkUpMove != LS_INVALID ) - { - if ( pm->ps->saber[0].jumpAtkUpMove != LS_NONE ) - {//actually overriding + if (pm->ps->saber[0].jumpAtkUpMove != LS_INVALID) { + if (pm->ps->saber[0].jumpAtkUpMove != LS_NONE) { // actually overriding overrideJumpAttackUpMove = (saberMoveName_t)pm->ps->saber[0].jumpAtkUpMove; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkUpMove > LS_NONE ) - {//would be cancelling it, but check the second saber, too + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkUpMove > LS_NONE) { // would be cancelling it, but check the second saber, too overrideJumpAttackUpMove = (saberMoveName_t)pm->ps->saber[1].jumpAtkUpMove; - } - else - {//nope, just cancel it + } else { // nope, just cancel it overrideJumpAttackUpMove = LS_NONE; } - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].jumpAtkUpMove != LS_INVALID ) - {//first saber not overridden, check second + } else if (pm->ps->dualSabers && pm->ps->saber[1].jumpAtkUpMove != LS_INVALID) { // first saber not overridden, check second overrideJumpAttackUpMove = (saberMoveName_t)pm->ps->saber[0].jumpAtkUpMove; } - if ( overrideJumpAttackUpMove != LS_INVALID ) - {//do this move instead - if ( overrideJumpAttackUpMove != LS_NONE ) - { + if (overrideJumpAttackUpMove != LS_INVALID) { // do this move instead + if (overrideJumpAttackUpMove != LS_NONE) { anim = saberMoveData[overrideJumpAttackUpMove].animToUse; } - } - else if ( pm->ps->saberAnimLevel == SS_MEDIUM ) - { + } else if (pm->ps->saberAnimLevel == SS_MEDIUM) { /* //Only tavion does these now if ( pm->ps->clientNum && Q_irand( 0, 1 ) ) @@ -1730,172 +1434,143 @@ static qboolean PM_CheckJump( void ) } } else - */if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() )//NOTE: pretty much useless, so player never does these - {//jump-spin FIXME: does direction matter? - vertPush = forceJumpStrength[FORCE_LEVEL_2]/1.5f; - if ( pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA ) - { + */ + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) // NOTE: pretty much useless, so player never does these + { // jump-spin FIXME: does direction matter? + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 1.5f; + if (pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA) { anim = BOTH_ALORA_SPIN; - } - else - { - anim = Q_irand( BOTH_FJSS_TR_BL, BOTH_FJSS_TL_BR ); + } else { + anim = Q_irand(BOTH_FJSS_TR_BL, BOTH_FJSS_TL_BR); } } } } } - if ( anim != -1 && PM_HasAnimation( pm->gent, anim ) ) - { - vec3_t fwd, right, traceto, mins = {pm->mins[0],pm->mins[1],0}, maxs = {pm->maxs[0],pm->maxs[1],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; + if (anim != -1 && PM_HasAnimation(pm->gent, anim)) { + vec3_t fwd, right, traceto, mins = {pm->mins[0], pm->mins[1], 0}, maxs = {pm->maxs[0], pm->maxs[1], 24}, + fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; qboolean doTrace = qfalse; int contents = CONTENTS_SOLID; - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); - //trace-check for a wall, if necc. - switch ( anim ) - { + // trace-check for a wall, if necc. + switch (anim) { case BOTH_WALL_FLIP_LEFT: - if ( g_debugMelee->integer ) - { + if (g_debugMelee->integer) { contents |= CONTENTS_BODY; } - //NOTE: purposely falls through to next case! + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_LEFT: doTrace = qtrue; - VectorMA( pm->ps->origin, -16, right, traceto ); + VectorMA(pm->ps->origin, -16, right, traceto); break; case BOTH_WALL_FLIP_RIGHT: - if ( g_debugMelee->integer ) - { + if (g_debugMelee->integer) { contents |= CONTENTS_BODY; } - //NOTE: purposely falls through to next case! + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_RIGHT: doTrace = qtrue; - VectorMA( pm->ps->origin, 16, right, traceto ); + VectorMA(pm->ps->origin, 16, right, traceto); break; case BOTH_WALL_FLIP_BACK1: - if ( g_debugMelee->integer ) - { + if (g_debugMelee->integer) { contents |= CONTENTS_BODY; } doTrace = qtrue; - VectorMA( pm->ps->origin, 32, fwd, traceto );//was 16 + VectorMA(pm->ps->origin, 32, fwd, traceto); // was 16 break; case BOTH_FORCEWALLRUNFLIP_START: - if ( g_debugMelee->integer ) - { + if (g_debugMelee->integer) { contents |= CONTENTS_BODY; } doTrace = qtrue; - VectorMA( pm->ps->origin, 32, fwd, traceto );//was 16 + VectorMA(pm->ps->origin, 32, fwd, traceto); // was 16 break; } - vec3_t idealNormal={0}, wallNormal={0}; - if ( doTrace ) - { - //FIXME: all these jump ones should check for head clearance - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - VectorCopy( trace.plane.normal, wallNormal ); - VectorNormalize( wallNormal ); - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); - if ( anim == BOTH_WALL_FLIP_LEFT ) - {//sigh.. check for bottomless pit to the right - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, 128, right, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + vec3_t idealNormal = {0}, wallNormal = {0}; + if (doTrace) { + // FIXME: all these jump ones should check for head clearance + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + VectorCopy(trace.plane.normal, wallNormal); + VectorNormalize(wallNormal); + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); + if (anim == BOTH_WALL_FLIP_LEFT) { // sigh.. check for bottomless pit to the right + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, 128, right, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } - } - else if ( anim == BOTH_WALL_FLIP_RIGHT ) - {//sigh.. check for bottomless pit to the left - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, -128, right, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + } else if (anim == BOTH_WALL_FLIP_RIGHT) { // sigh.. check for bottomless pit to the left + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, -128, right, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } - } - else - { - if ( anim == BOTH_WALL_FLIP_BACK1 - || anim == BOTH_FORCEWALLRUNFLIP_START ) - {//trace up and forward a little to make sure the wall it at least 64 tall - if ( (contents&CONTENTS_BODY)//included entitied - && (trace.contents&CONTENTS_BODY) //hit an entity - && g_entities[trace.entityNum].client )//hit a client - {//no need to trace up, it's all good... - if ( PM_InOnGroundAnim( &g_entities[trace.entityNum].client->ps ) )//on the ground, no jump - {//can't jump off guys on ground - trace.fraction = 1.0f;//way to stop if from doing the jump - } - else if ( anim == BOTH_FORCEWALLRUNFLIP_START ) - {//instead of wall-running up, do the backflip + } else { + if (anim == BOTH_WALL_FLIP_BACK1 || + anim == BOTH_FORCEWALLRUNFLIP_START) { // trace up and forward a little to make sure the wall it at least 64 tall + if ((contents & CONTENTS_BODY) // included entitied + && (trace.contents & CONTENTS_BODY) // hit an entity + && g_entities[trace.entityNum].client) // hit a client + { // no need to trace up, it's all good... + if (PM_InOnGroundAnim(&g_entities[trace.entityNum].client->ps)) // on the ground, no jump + { // can't jump off guys on ground + trace.fraction = 1.0f; // way to stop if from doing the jump + } else if (anim == BOTH_FORCEWALLRUNFLIP_START) { // instead of wall-running up, do the backflip anim = BOTH_WALL_FLIP_BACK1; - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; } - } - else if ( anim == BOTH_WALL_FLIP_BACK1 ) - { - trace_t trace2; - vec3_t start; - VectorCopy( pm->ps->origin, start ); + } else if (anim == BOTH_WALL_FLIP_BACK1) { + trace_t trace2; + vec3_t start; + VectorCopy(pm->ps->origin, start); start[2] += 64; - VectorMA( start, 32, fwd, traceto ); - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( trace2.allsolid - || trace2.startsolid - || trace2.fraction >= 1.0f ) - {//no room above or no wall in front at that height - trace.fraction = 1.0f;//way to stop if from doing the jump + VectorMA(start, 32, fwd, traceto); + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (trace2.allsolid || trace2.startsolid || trace2.fraction >= 1.0f) { // no room above or no wall in front at that height + trace.fraction = 1.0f; // way to stop if from doing the jump } } } - if ( trace.fraction < 1.0f ) - {//still valid to jump - if ( anim == BOTH_WALL_FLIP_BACK1 ) - {//sigh.. check for bottomless pit to the rear - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, -128, fwd, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + if (trace.fraction < 1.0f) { // still valid to jump + if (anim == BOTH_WALL_FLIP_BACK1) { // sigh.. check for bottomless pit to the rear + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, -128, fwd, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, (EG2_Collision)0, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } } @@ -1904,247 +1579,180 @@ static qboolean PM_CheckJump( void ) } gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( !doTrace || (trace.fraction < 1.0f&&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(wallNormal,idealNormal)>0.7)) ) - {//there is a wall there + if (!doTrace || (trace.fraction < 1.0f && ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(wallNormal, idealNormal) > 0.7))) { // there is a wall there - if ( (anim != BOTH_WALL_RUN_LEFT - && anim != BOTH_WALL_RUN_RIGHT - && anim != BOTH_FORCEWALLRUNFLIP_START) - || (wallNormal[2] >= 0.0f && wallNormal[2] <= MAX_WALL_RUN_Z_NORMAL) ) - {//wall-runs can only run on relatively flat walls, sorry. - if ( anim == BOTH_ARIAL_LEFT || anim == BOTH_CARTWHEEL_LEFT ) - { + if ((anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT && anim != BOTH_FORCEWALLRUNFLIP_START) || + (wallNormal[2] >= 0.0f && wallNormal[2] <= MAX_WALL_RUN_Z_NORMAL)) { // wall-runs can only run on relatively flat walls, sorry. + if (anim == BOTH_ARIAL_LEFT || anim == BOTH_CARTWHEEL_LEFT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -185, right, pm->ps->velocity ); - } - else if ( anim == BOTH_ARIAL_RIGHT || anim == BOTH_CARTWHEEL_RIGHT ) - { + VectorMA(pm->ps->velocity, -185, right, pm->ps->velocity); + } else if (anim == BOTH_ARIAL_RIGHT || anim == BOTH_CARTWHEEL_RIGHT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 185, right, pm->ps->velocity ); - } - else if ( anim == BOTH_BUTTERFLY_LEFT ) - { + VectorMA(pm->ps->velocity, 185, right, pm->ps->velocity); + } else if (anim == BOTH_BUTTERFLY_LEFT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -190, right, pm->ps->velocity ); - } - else if ( anim == BOTH_BUTTERFLY_RIGHT ) - { + VectorMA(pm->ps->velocity, -190, right, pm->ps->velocity); + } else if (anim == BOTH_BUTTERFLY_RIGHT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 190, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, 190, right, pm->ps->velocity); } - //move me to side - else if ( anim == BOTH_WALL_FLIP_LEFT ) - { + // move me to side + else if (anim == BOTH_WALL_FLIP_LEFT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_FLIP_RIGHT ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_FLIP_RIGHT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_FLIP_BACK1 - || anim == BOTH_FLIP_BACK2 - || anim == BOTH_FLIP_BACK3 - || anim == BOTH_ALORA_FLIP_B - || anim == BOTH_WALL_FLIP_BACK1 ) - { + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); + } else if (anim == BOTH_FLIP_BACK1 || anim == BOTH_FLIP_BACK2 || anim == BOTH_FLIP_BACK3 || anim == BOTH_ALORA_FLIP_B || + anim == BOTH_WALL_FLIP_BACK1) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, fwd, pm->ps->velocity ); - } - //kick if jumping off an ent - if ( doTrace - && anim != BOTH_WALL_RUN_LEFT - && anim != BOTH_WALL_RUN_RIGHT - && anim != BOTH_FORCEWALLRUNFLIP_START) - { - if ( pm->gent && trace.entityNum < ENTITYNUM_WORLD ) - { - if ( traceEnt - && traceEnt->client - && traceEnt->health > 0 - && traceEnt->takedamage - && traceEnt->client->NPC_class != CLASS_GALAKMECH - && traceEnt->client->NPC_class != CLASS_DESANN - && !(traceEnt->flags&FL_NO_KNOCKBACK) ) - {//push them away and do pain + VectorMA(pm->ps->velocity, -150, fwd, pm->ps->velocity); + } + // kick if jumping off an ent + if (doTrace && anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT && anim != BOTH_FORCEWALLRUNFLIP_START) { + if (pm->gent && trace.entityNum < ENTITYNUM_WORLD) { + if (traceEnt && traceEnt->client && traceEnt->health > 0 && traceEnt->takedamage && + traceEnt->client->NPC_class != CLASS_GALAKMECH && traceEnt->client->NPC_class != CLASS_DESANN && + !(traceEnt->flags & FL_NO_KNOCKBACK)) { // push them away and do pain vec3_t oppDir, fxDir; - float strength = VectorNormalize2( pm->ps->velocity, oppDir ); - VectorScale( oppDir, -1, oppDir ); - //FIXME: need knockdown anim - G_Damage( traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, DAMAGE_NO_ARMOR|DAMAGE_NO_HIT_LOC|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - VectorCopy( fwd, fxDir ); - VectorScale( fxDir, -1, fxDir ); - G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), trace.endpos, fxDir ); - //G_Sound( traceEnt, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); - if ( traceEnt->health > 0 ) - {//didn't kill him - if ( (traceEnt->s.number==0&&!Q_irand(0,g_spskill->integer)) - || (traceEnt->NPC!=NULL&&Q_irand(RANK_CIVILIAN,traceEnt->NPC->rank)+Q_irand(-2,2)ps->velocity, oppDir); + VectorScale(oppDir, -1, oppDir); + // FIXME: need knockdown anim + G_Damage(traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, + DAMAGE_NO_ARMOR | DAMAGE_NO_HIT_LOC | DAMAGE_NO_KNOCKBACK, MOD_MELEE); + VectorCopy(fwd, fxDir); + VectorScale(fxDir, -1, fxDir); + G_PlayEffect(G_EffectIndex("melee/kick_impact"), trace.endpos, fxDir); + // G_Sound( traceEnt, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + if (traceEnt->health > 0) { // didn't kill him + if ((traceEnt->s.number == 0 && !Q_irand(0, g_spskill->integer)) || + (traceEnt->NPC != NULL && Q_irand(RANK_CIVILIAN, traceEnt->NPC->rank) + Q_irand(-2, 2) < RANK_ENSIGN)) { + NPC_SetAnim(traceEnt, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_Throw(traceEnt, oppDir, strength); } } } } } - //up - if ( vertPush ) - { + // up + if (vertPush) { pm->ps->velocity[2] = vertPush; } - //animate me - if ( anim == BOTH_BUTTERFLY_RIGHT ) - { - PM_SetSaberMove( LS_BUTTERFLY_RIGHT ); - } - else if ( anim == BOTH_BUTTERFLY_LEFT ) - { - PM_SetSaberMove( LS_BUTTERFLY_LEFT ); - } - else - {//not a proper saberMove, so do set all the details manually + // animate me + if (anim == BOTH_BUTTERFLY_RIGHT) { + PM_SetSaberMove(LS_BUTTERFLY_RIGHT); + } else if (anim == BOTH_BUTTERFLY_LEFT) { + PM_SetSaberMove(LS_BUTTERFLY_LEFT); + } else { // not a proper saberMove, so do set all the details manually int parts = SETANIM_LEGS; - if ( /*anim == BOTH_BUTTERFLY_LEFT || - anim == BOTH_BUTTERFLY_RIGHT ||*/ - anim == BOTH_FJSS_TR_BL || - anim == BOTH_FJSS_TL_BR ) - { + if (/*anim == BOTH_BUTTERFLY_LEFT || + anim == BOTH_BUTTERFLY_RIGHT ||*/ + anim == BOTH_FJSS_TR_BL || anim == BOTH_FJSS_TL_BR) { parts = SETANIM_BOTH; - pm->cmd.buttons&=~BUTTON_ATTACK; + pm->cmd.buttons &= ~BUTTON_ATTACK; pm->ps->saberMove = LS_NONE; - pm->gent->client->ps.SaberActivateTrail( 300 ); - } - else if ( !pm->ps->weaponTime ) - { + pm->gent->client->ps.SaberActivateTrail(300); + } else if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - if ( /*anim == BOTH_BUTTERFLY_LEFT - || anim == BOTH_BUTTERFLY_RIGHT - ||*/ anim == BOTH_FJSS_TR_BL - || anim == BOTH_FJSS_TL_BR - || anim == BOTH_FORCEWALLRUNFLIP_START ) - { + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (/*anim == BOTH_BUTTERFLY_LEFT + || anim == BOTH_BUTTERFLY_RIGHT + ||*/ anim == BOTH_FJSS_TR_BL || anim == BOTH_FJSS_TL_BR || anim == BOTH_FORCEWALLRUNFLIP_START) { pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else if ( anim == BOTH_WALL_FLIP_LEFT - || anim == BOTH_WALL_FLIP_RIGHT - || anim == BOTH_WALL_FLIP_BACK1 ) - {//let us do some more moves after this + } else if (anim == BOTH_WALL_FLIP_LEFT || anim == BOTH_WALL_FLIP_RIGHT || + anim == BOTH_WALL_FLIP_BACK1) { // let us do some more moves after this pm->ps->saberAttackChainCount = 0; } } - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); pm->cmd.upmove = 0; - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - WP_ForcePowerDrain( pm->gent, FP_LEVITATION, forcePowerCostOverride ); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + WP_ForcePowerDrain(pm->gent, FP_LEVITATION, forcePowerCostOverride); } } } - } - else - {//in the air + } else { // in the air int legsAnim = pm->ps->legsAnim; - if ( legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT ) - {//running on a wall - vec3_t right, traceto, mins = {pm->mins[0],pm->mins[0],0}, maxs = {pm->maxs[0],pm->maxs[0],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; - int anim = -1; + if (legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT) { // running on a wall + vec3_t right, traceto, mins = {pm->mins[0], pm->mins[0], 0}, maxs = {pm->maxs[0], pm->maxs[0], 24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + int anim = -1; - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); - if ( legsAnim == BOTH_WALL_RUN_LEFT ) - { - if ( pm->ps->legsAnimTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_LEFT ); - if ( pm->ps->legsAnimTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, -16, right, traceto ); + if (legsAnim == BOTH_WALL_RUN_LEFT) { + if (pm->ps->legsAnimTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_LEFT); + if (pm->ps->legsAnimTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, -16, right, traceto); anim = BOTH_WALL_RUN_LEFT_FLIP; } } - } - else if ( legsAnim == BOTH_WALL_RUN_RIGHT ) - { - if ( pm->ps->legsAnimTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_RIGHT ); - if ( pm->ps->legsAnimTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, 16, right, traceto ); + } else if (legsAnim == BOTH_WALL_RUN_RIGHT) { + if (pm->ps->legsAnimTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_RIGHT); + if (pm->ps->legsAnimTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, 16, right, traceto); anim = BOTH_WALL_RUN_RIGHT_FLIP; } } } - if ( anim != -1 ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//flip off wall - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + if (anim != -1) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // flip off wall + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; pm->cmd.upmove = 0; } } - if ( pm->cmd.upmove != 0 ) - {//jump failed, so don't try to do normal jump code, just return + if (pm->cmd.upmove != 0) { // jump failed, so don't try to do normal jump code, just return return qfalse; } - } - else if ( pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START ) - {//want to jump off wall - vec3_t fwd, traceto, mins = {pm->mins[0],pm->mins[0],0}, maxs = {pm->maxs[0],pm->maxs[0],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; - int anim = -1; + } else if (pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START) { // want to jump off wall + vec3_t fwd, traceto, mins = {pm->mins[0], pm->mins[0], 0}, maxs = {pm->maxs[0], pm->maxs[0], 24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + int anim = -1; - AngleVectors( fwdAngles, fwd, NULL, NULL ); + AngleVectors(fwdAngles, fwd, NULL, NULL); - float animLen = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, BOTH_FORCEWALLRUNFLIP_START ); - if ( pm->ps->legsAnimTimer < animLen - 250 )//was 400 - {//not at start of anim - VectorMA( pm->ps->origin, 16, fwd, traceto ); + float animLen = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, BOTH_FORCEWALLRUNFLIP_START); + if (pm->ps->legsAnimTimer < animLen - 250) // was 400 + { // not at start of anim + VectorMA(pm->ps->origin, 16, fwd, traceto); anim = BOTH_FORCEWALLRUNFLIP_END; } - if ( anim != -1 ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//flip off wall + if (anim != -1) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // flip off wall pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, WALL_RUN_UP_BACKFLIP_SPEED, fwd, pm->ps->velocity ); + VectorMA(pm->ps->velocity, WALL_RUN_UP_BACKFLIP_SPEED, fwd, pm->ps->velocity); pm->ps->velocity[2] += 200; int parts = SETANIM_LEGS; - if ( !pm->ps->weaponTime ) - {//not attacking, set anim on both + if (!pm->ps->weaponTime) { // not attacking, set anim on both parts = SETANIM_BOTH; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - //FIXME: do damage to traceEnt, like above? - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + // FIXME: do damage to traceEnt, like above? + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; pm->cmd.upmove = 0; - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); } } - if ( pm->cmd.upmove != 0 ) - {//jump failed, so don't try to do normal jump code, just return + if (pm->cmd.upmove != 0) { // jump failed, so don't try to do normal jump code, just return return qfalse; } } @@ -2248,9 +1856,9 @@ static qboolean PM_CheckJump( void ) float strength = VectorNormalize2( pm->ps->velocity, oppDir ); VectorScale( oppDir, -1, oppDir ); //FIXME: need knockdown anim - G_Damage( traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, DAMAGE_NO_ARMOR|DAMAGE_NO_HIT_LOC|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - G_Sound( traceEnt, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); - if ( trace.fraction <= 0.5f ) + G_Damage( traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, + DAMAGE_NO_ARMOR|DAMAGE_NO_HIT_LOC|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); G_Sound( traceEnt, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, + 4)) ) ); if ( trace.fraction <= 0.5f ) {//close to him if ( traceEnt->health > 0 ) {//didn't kill him @@ -2268,116 +1876,96 @@ static qboolean PM_CheckJump( void ) } } */ - else if ( (pm->ps->legsAnimTimer<=100 - ||!PM_InSpecialJump( legsAnim )//not in a special jump anim - ||PM_InReboundJump( legsAnim )//we're already in a rebound - ||PM_InBackFlip( legsAnim ) )//a backflip (needed so you can jump off a wall behind you) - //&& pm->ps->velocity[2] <= 0 - && pm->ps->velocity[2] > -1200 //not falling down very fast - && !(pm->ps->pm_flags&PMF_JUMP_HELD)//have to have released jump since last press - && (pm->cmd.forwardmove||pm->cmd.rightmove)//pushing in a direction - //&& pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2//level 3 jump or better - && pm->ps->forcePower > 10 //have enough force power to do another one - && (level.time-pm->ps->lastOnGround) > 250 //haven't been on the ground in the last 1/4 of a second - && (!(pm->ps->pm_flags&PMF_JUMPING)//not jumping - || ( (level.time-pm->ps->lastOnGround) > 250 //we are jumping, but have been in the air for at least half a second - &&( g_debugMelee->integer//if you know kung fu, no height cap on wall-grab-jumps - || ((pm->ps->origin[2]-pm->ps->forceJumpZStart) < (forceJumpHeightMax[FORCE_LEVEL_3]-(G_ForceWallJumpStrength()/2.0f))) )//can fit at least one more wall jump in (yes, using "magic numbers"... for now) - ) - ) - //&& (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything - ) - {//see if we're pushing at a wall and jump off it if so - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_WALL_GRAB) - && ( !pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_WALL_GRAB) ) ) - {//okay to do wall-grabs with this saber - //FIXME: make sure we have enough force power - //FIXME: check to see if we can go any higher - //FIXME: limit to a certain number of these in a row? - //FIXME: maybe don't require a ucmd direction, just check all 4? - //FIXME: should stick to the wall for a second, then push off... - vec3_t checkDir, traceto, mins = {pm->mins[0],pm->mins[1],0}, maxs = {pm->maxs[0],pm->maxs[1],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; - vec3_t idealNormal; - int anim = -1; - - if ( pm->cmd.rightmove ) - { - if ( pm->cmd.rightmove > 0 ) - { + else if ((pm->ps->legsAnimTimer <= 100 || !PM_InSpecialJump(legsAnim) // not in a special jump anim + || PM_InReboundJump(legsAnim) // we're already in a rebound + || PM_InBackFlip(legsAnim)) // a backflip (needed so you can jump off a wall behind you) + //&& pm->ps->velocity[2] <= 0 + && pm->ps->velocity[2] > -1200 // not falling down very fast + && !(pm->ps->pm_flags & PMF_JUMP_HELD) // have to have released jump since last press + && (pm->cmd.forwardmove || pm->cmd.rightmove) // pushing in a direction + //&& pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 // level 3 jump or better + && pm->ps->forcePower > 10 // have enough force power to do another one + && (level.time - pm->ps->lastOnGround) > 250 // haven't been on the ground in the last 1/4 of a second + && (!(pm->ps->pm_flags & PMF_JUMPING) // not jumping + || ((level.time - pm->ps->lastOnGround) > 250 // we are jumping, but have been in the air for at least half a second + && (g_debugMelee->integer // if you know kung fu, no height cap on wall-grab-jumps + || ((pm->ps->origin[2] - pm->ps->forceJumpZStart) < + (forceJumpHeightMax[FORCE_LEVEL_3] - + (G_ForceWallJumpStrength() / 2.0f)))) // can fit at least one more wall jump in (yes, using "magic numbers"... for now) + )) + //&& (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything + ) { // see if we're pushing at a wall and jump off it if so + if (!(pm->ps->saber[0].saberFlags & SFL_NO_WALL_GRAB) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_WALL_GRAB))) { // okay to do wall-grabs with this saber + // FIXME: make sure we have enough force power + // FIXME: check to see if we can go any higher + // FIXME: limit to a certain number of these in a row? + // FIXME: maybe don't require a ucmd direction, just check all 4? + // FIXME: should stick to the wall for a second, then push off... + vec3_t checkDir, traceto, mins = {pm->mins[0], pm->mins[1], 0}, maxs = {pm->maxs[0], pm->maxs[1], 24}, + fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + vec3_t idealNormal; + int anim = -1; + + if (pm->cmd.rightmove) { + if (pm->cmd.rightmove > 0) { anim = BOTH_FORCEWALLREBOUND_RIGHT; - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - } - else if ( pm->cmd.rightmove < 0 ) - { + AngleVectors(fwdAngles, NULL, checkDir, NULL); + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FORCEWALLREBOUND_LEFT; - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); } - } - else if ( pm->cmd.forwardmove > 0 ) - { + } else if (pm->cmd.forwardmove > 0) { anim = BOTH_FORCEWALLREBOUND_FORWARD; - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - } - else if ( pm->cmd.forwardmove < 0 ) - { + AngleVectors(fwdAngles, checkDir, NULL, NULL); + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FORCEWALLREBOUND_BACK; - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); - } - if ( anim != -1 ) - {//trace in the dir we're pushing in and see if there's a vertical wall there - VectorMA( pm->ps->origin, 16, checkDir, traceto );//was 8 - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, (EG2_Collision)0, 0 );//FIXME: clip brushes too? - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); + } + if (anim != -1) { // trace in the dir we're pushing in and see if there's a vertical wall there + VectorMA(pm->ps->origin, 16, checkDir, traceto); // was 8 + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, (EG2_Collision)0, + 0); // FIXME: clip brushes too? + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.fraction < 1.0f - && fabs(trace.plane.normal[2]) <= MAX_WALL_GRAB_SLOPE - &&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(trace.plane.normal,idealNormal)>0.7) ) - {//there is a wall there - float dot = DotProduct( pm->ps->velocity, trace.plane.normal ); - if ( dot < 1.0f ) - {//can't be heading *away* from the wall! - //grab it! - PM_GrabWallForJump( anim ); + if (trace.fraction < 1.0f && fabs(trace.plane.normal[2]) <= MAX_WALL_GRAB_SLOPE && + ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7)) { // there is a wall there + float dot = DotProduct(pm->ps->velocity, trace.plane.normal); + if (dot < 1.0f) { // can't be heading *away* from the wall! + // grab it! + PM_GrabWallForJump(anim); } } } } - } - else - { - //FIXME: if in a butterfly, kick people away? + } else { + // FIXME: if in a butterfly, kick people away? } } } - if ( pm->gent + if (pm->gent //&& pm->cmd.upmove > 0 - && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->ps->weapon == WP_SABER - && (pm->ps->weaponTime > 0||(pm->cmd.buttons&BUTTON_ATTACK)) - && ((pm->ps->clientNum&&!PM_ControlledByPlayer())||((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) ) - {//okay, we just jumped and we're in an attack - if ( !PM_RollingAnim( pm->ps->legsAnim ) - && !PM_InKnockDown( pm->ps ) - && !PM_InDeathAnim() - && !PM_PainAnim( pm->ps->torsoAnim ) - && !PM_FlippingAnim( pm->ps->legsAnim ) - && !PM_SpinningAnim( pm->ps->legsAnim ) - && !PM_SaberInSpecialAttack( pm->ps->torsoAnim ) ) - {//HMM... do NPCs need this logic? - if ( !PM_SaberInTransitionAny( pm->ps->saberMove ) //not going to/from/between an attack anim - && !PM_SaberInAttack( pm->ps->saberMove ) //not in attack anim - && pm->ps->weaponTime <= 0//not busy - && (pm->cmd.buttons&BUTTON_ATTACK) )//want to attack - {//not in an attack or finishing/starting/transitioning one - if ( PM_CheckBackflipAttackMove() ) - { - PM_SetSaberMove( PM_SaberBackflipAttackMove() );//backflip attack + && pm->ps->forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->ps->weapon == WP_SABER && (pm->ps->weaponTime > 0 || (pm->cmd.buttons & BUTTON_ATTACK)) && + ((pm->ps->clientNum && !PM_ControlledByPlayer()) || ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.renderingThirdPerson && + !cg.zoomMode))) { // okay, we just jumped and we're in an attack + if (!PM_RollingAnim(pm->ps->legsAnim) && !PM_InKnockDown(pm->ps) && !PM_InDeathAnim() && !PM_PainAnim(pm->ps->torsoAnim) && + !PM_FlippingAnim(pm->ps->legsAnim) && !PM_SpinningAnim(pm->ps->legsAnim) && + !PM_SaberInSpecialAttack(pm->ps->torsoAnim)) { // HMM... do NPCs need this logic? + if (!PM_SaberInTransitionAny(pm->ps->saberMove) // not going to/from/between an attack anim + && !PM_SaberInAttack(pm->ps->saberMove) // not in attack anim + && pm->ps->weaponTime <= 0 // not busy + && (pm->cmd.buttons & BUTTON_ATTACK)) // want to attack + { // not in an attack or finishing/starting/transitioning one + if (PM_CheckBackflipAttackMove()) { + PM_SetSaberMove(PM_SaberBackflipAttackMove()); // backflip attack } /* else if ( PM_CheckSaberDualJumpAttackMove() ) @@ -2408,12 +1996,10 @@ static qboolean PM_CheckJump( void ) */ } } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - if ( pm->cmd.upmove > 0 ) - {//no special jumps + if (pm->cmd.upmove > 0) { // no special jumps /* gentity_t *groundEnt = &g_entities[pm->ps->groundEntityNum]; if ( groundEnt && groundEnt->NPC ) @@ -2423,39 +2009,32 @@ static qboolean PM_CheckJump( void ) */ pm->ps->velocity[2] = JUMP_VELOCITY; - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height pm->ps->pm_flags |= PMF_JUMPING; } - if ( d_JediAI->integer ) - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_SABER ) - { - Com_Printf( "jumping\n" ); + if (d_JediAI->integer) { + if (pm->ps->clientNum && pm->ps->weapon == WP_SABER) { + Com_Printf("jumping\n"); } } - //Jumping + // Jumping pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->pm_flags |= PMF_JUMP_HELD; pm->ps->groundEntityNum = ENTITYNUM_NONE; pm->ps->jumpZStart = pm->ps->origin[2]; - if ( pm->gent ) - { - if ( !Q3_TaskIDPending( pm->gent, TID_CHAN_VOICE ) ) - { - PM_AddEvent( EV_JUMP ); + if (pm->gent) { + if (!Q3_TaskIDPending(pm->gent, TID_CHAN_VOICE)) { + PM_AddEvent(EV_JUMP); } - } - else - { - PM_AddEvent( EV_JUMP ); + } else { + PM_AddEvent(EV_JUMP); } - //Set the animations - if ( pm->ps->gravity > 0 && !PM_InSpecialJump( pm->ps->legsAnim ) && !PM_InGetUp( pm->ps ) ) - { + // Set the animations + if (pm->ps->gravity > 0 && !PM_InSpecialJump(pm->ps->legsAnim) && !PM_InGetUp(pm->ps)) { PM_JumpForDir(); } @@ -2467,25 +2046,24 @@ static qboolean PM_CheckJump( void ) PM_CheckWaterJump ============= */ -static qboolean PM_CheckWaterJump( void ) { - vec3_t spot; - int cont; - vec3_t flatforward; +static qboolean PM_CheckWaterJump(void) { + vec3_t spot; + int cont; + vec3_t flatforward; if (pm->ps->pm_time) { return qfalse; } - if ( pm->cmd.forwardmove <= 0 && pm->cmd.upmove <= 0 ) - {//they must not want to get out? + if (pm->cmd.forwardmove <= 0 && pm->cmd.upmove <= 0) { // they must not want to get out? return qfalse; } // check for water jump - if ( pm->waterlevel != 2 ) { + if (pm->waterlevel != 2) { return qfalse; } - if ( pm->watertype & CONTENTS_LADDER ) { + if (pm->watertype & CONTENTS_LADDER) { if (pm->ps->velocity[2] <= 0) return qfalse; } @@ -2493,24 +2071,24 @@ static qboolean PM_CheckWaterJump( void ) { flatforward[0] = pml.forward[0]; flatforward[1] = pml.forward[1]; flatforward[2] = 0; - VectorNormalize( flatforward ); + VectorNormalize(flatforward); - VectorMA( pm->ps->origin, 30, flatforward, spot ); + VectorMA(pm->ps->origin, 30, flatforward, spot); spot[2] += 24; - cont = pm->pointcontents (spot, pm->ps->clientNum ); - if ( !(cont & CONTENTS_SOLID) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (!(cont & CONTENTS_SOLID)) { return qfalse; } spot[2] += 16; - cont = pm->pointcontents( spot, pm->ps->clientNum ); - if ( cont&(CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA|CONTENTS_BODY) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (cont & (CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA | CONTENTS_BODY)) { return qfalse; } // jump out of water - VectorScale( pml.forward, 200, pm->ps->velocity ); - pm->ps->velocity[2] = 350+((pm->ps->waterheight-pm->ps->origin[2])*2); + VectorScale(pml.forward, 200, pm->ps->velocity); + pm->ps->velocity[2] = 350 + ((pm->ps->waterheight - pm->ps->origin[2]) * 2); pm->ps->pm_flags |= PMF_TIME_WATERJUMP; pm->ps->pm_time = 2000; @@ -2520,7 +2098,6 @@ static qboolean PM_CheckWaterJump( void ) { //============================================================================ - /* =================== PM_WaterJumpMove @@ -2528,15 +2105,13 @@ PM_WaterJumpMove Flying out of the water =================== */ -static void PM_WaterJumpMove( void ) -{ +static void PM_WaterJumpMove(void) { // waterjump has no control, but falls - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; - if (pm->ps->velocity[2] < 0) - { + if (pm->ps->velocity[2] < 0) { // cancel as soon as we are falling down again pm->ps->pm_flags &= ~PMF_ALL_TIMES; pm->ps->pm_time = 0; @@ -2549,21 +2124,19 @@ PM_WaterMove =================== */ -static void PM_WaterMove( void ) { - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float vel; - - if ( PM_CheckWaterJump() ) { +static void PM_WaterMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float vel; + + if (PM_CheckWaterJump()) { PM_WaterJumpMove(); return; - } - else if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->waterlevel < 3 ) - { - if ( PM_CheckJump () ) { + } else if (pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->waterlevel < 3) { + if (PM_CheckJump()) { // jumped away return; } @@ -2582,180 +2155,159 @@ static void PM_WaterMove( void ) { } } #endif - PM_Friction (); + PM_Friction(); - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; - if ( pm->watertype & CONTENTS_LADDER ) { + if (pm->watertype & CONTENTS_LADDER) { wishvel[2] = 0; } else { - wishvel[2] = -60; // sink towards bottom + wishvel[2] = -60; // sink towards bottom } } else { - for (i=0 ; i<3 ; i++) { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } wishvel[2] += scale * pm->cmd.upmove; - if ( !(pm->watertype&CONTENTS_LADDER) ) //ladder + if (!(pm->watertype & CONTENTS_LADDER)) // ladder { - float depth = (pm->ps->origin[2]+pm->gent->client->standheight)-pm->ps->waterheight; - if ( depth >= 12 ) - {//too high! - wishvel[2] -= 120; // sink towards bottom - if ( wishvel[2] > 0 ) - { + float depth = (pm->ps->origin[2] + pm->gent->client->standheight) - pm->ps->waterheight; + if (depth >= 12) { // too high! + wishvel[2] -= 120; // sink towards bottom + if (wishvel[2] > 0) { wishvel[2] = 0; } - } - else if ( pm->ps->waterHeightLevel >= WHL_UNDER )//!depth && pm->waterlevel == 3 ) + } else if (pm->ps->waterHeightLevel >= WHL_UNDER) //! depth && pm->waterlevel == 3 ) { - } - else if ( depth < 12 ) - {//still deep - wishvel[2] -= 60; // sink towards bottom - if ( wishvel[2] > 30 ) - { + } else if (depth < 12) { // still deep + wishvel[2] -= 60; // sink towards bottom + if (wishvel[2] > 30) { wishvel[2] = 30; } } } } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); - if ( pm->watertype & CONTENTS_LADDER ) //ladder + if (pm->watertype & CONTENTS_LADDER) // ladder { - if ( wishspeed > pm->ps->speed * pm_ladderScale ) { + if (wishspeed > pm->ps->speed * pm_ladderScale) { wishspeed = pm->ps->speed * pm_ladderScale; } - PM_Accelerate( wishdir, wishspeed, pm_flyaccelerate ); + PM_Accelerate(wishdir, wishspeed, pm_flyaccelerate); } else { - if ( pm->ps->gravity < 0 ) - {//float up + if (pm->ps->gravity < 0) { // float up pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; } - if ( wishspeed > pm->ps->speed * pm_swimScale ) { + if (wishspeed > pm->ps->speed * pm_swimScale) { wishspeed = pm->ps->speed * pm_swimScale; } - PM_Accelerate( wishdir, wishspeed, pm_wateraccelerate ); + PM_Accelerate(wishdir, wishspeed, pm_wateraccelerate); } // make sure we can go up slopes easily under water - if ( pml.groundPlane && DotProduct( pm->ps->velocity, pml.groundTrace.plane.normal ) < 0 ) { + if (pml.groundPlane && DotProduct(pm->ps->velocity, pml.groundTrace.plane.normal) < 0) { vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); VectorNormalize(pm->ps->velocity); VectorScale(pm->ps->velocity, vel, pm->ps->velocity); } - PM_SlideMove( qfalse ); + PM_SlideMove(qfalse); } - /* =================== PM_FlyVehicleMove =================== */ -static void PM_FlyVehicleMove( void ) -{ - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float zVel; - float fmove = 0.0f, smove = 0.0f; +static void PM_FlyVehicleMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float zVel; + float fmove = 0.0f, smove = 0.0f; // We don't use these here because we pre-calculate the movedir in the vehicle update anyways, and if // you leave this, you get strange motion during boarding (the player can move the vehicle). - //fmove = pm->cmd.forwardmove; - //smove = pm->cmd.rightmove; + // fmove = pm->cmd.forwardmove; + // smove = pm->cmd.rightmove; // normal slowdown - if ( pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//falling + if (pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE) { // falling zVel = pm->ps->velocity[2]; - PM_Friction (); + PM_Friction(); pm->ps->velocity[2] = zVel; - } - else - { - PM_Friction (); - if ( pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { - pm->ps->velocity[2] = 0; // ignore slope movement + } else { + PM_Friction(); + if (pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE) { + pm->ps->velocity[2] = 0; // ignore slope movement } } - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // Get The WishVel And WishSpeed //------------------------------- - if ( pm->ps->clientNum && (USENEWNAVSYSTEM || !VectorCompare( pm->ps->moveDir, vec3_origin )) ) - {//NPC + if (pm->ps->clientNum && (USENEWNAVSYSTEM || !VectorCompare(pm->ps->moveDir, vec3_origin))) { // NPC // If The UCmds Were Set, But Never Converted Into A MoveDir, Then Make The WishDir From UCmds //-------------------------------------------------------------------------------------------- - if ((fmove!=0.0f || smove!=0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) - { - //gi.Printf("Generating MoveDir\n"); - for ( i = 0 ; i < 3 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if ((fmove != 0.0f || smove != 0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) { + // gi.Printf("Generating MoveDir\n"); + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } - VectorCopy( wishvel, wishdir ); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Otherwise, Use The Move Dir //----------------------------- - else - { + else { wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); } - } - else - { - for ( i = 0 ; i < 3 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } // when going up or down slopes the wish velocity should Not be zero - // wishvel[2] = 0; + // wishvel[2] = 0; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Handle negative speed. - if ( wishspeed < 0 ) - { + if (wishspeed < 0) { wishspeed = wishspeed * -1.0f; - VectorScale( wishvel, -1.0f, wishvel ); - VectorScale( wishdir, -1.0f, wishdir ); + VectorScale(wishvel, -1.0f, wishvel); + VectorScale(wishdir, -1.0f, wishdir); } - VectorCopy( wishvel, wishdir ); - wishspeed = VectorNormalize( wishdir ); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - PM_Accelerate( wishdir, wishspeed, 100 ); + PM_Accelerate(wishdir, wishspeed, 100); - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); } /* @@ -2765,93 +2317,70 @@ PM_FlyMove Only with the flight powerup =================== */ -static void PM_FlyMove( void ) -{ - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float accel; - qboolean lowGravMove = qfalse; - qboolean jetPackMove = qfalse; +static void PM_FlyMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float accel; + qboolean lowGravMove = qfalse; + qboolean jetPackMove = qfalse; // normal slowdown - PM_Friction (); + PM_Friction(); - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT||pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && pm->gent->client->moveType == MT_FLYSWIM ) - {//jetpack accel + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->gent && pm->gent->client && + (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + pm->gent->client->moveType == MT_FLYSWIM) { // jetpack accel accel = pm_flyaccelerate; jetPackMove = qtrue; - } - else if ( pm->ps->gravity <= 0 - && ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || (pm->gent&&pm->gent->client&&pm->gent->client->moveType == MT_RUNJUMP)) ) - { + } else if (pm->ps->gravity <= 0 && + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || (pm->gent && pm->gent->client && pm->gent->client->moveType == MT_RUNJUMP))) { PM_CheckJump(); accel = 1.0f; pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; - pm->ps->jumpZStart = pm->ps->origin[2];//so we don't take a lot of damage when the gravity comes back on + pm->ps->jumpZStart = pm->ps->origin[2]; // so we don't take a lot of damage when the gravity comes back on lowGravMove = qtrue; - } - else - { + } else { accel = pm_flyaccelerate; } - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) - { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; wishvel[2] = 0; - } - else - { - for (i=0 ; i<3 ; i++) - { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } - if ( jetPackMove ) - { + if (jetPackMove) { wishvel[2] += pm->cmd.upmove; - } - else if ( lowGravMove ) - { + } else if (lowGravMove) { wishvel[2] += scale * pm->cmd.upmove; - VectorScale( wishvel, 0.5f, wishvel ); + VectorScale(wishvel, 0.5f, wishvel); } } - VectorCopy( wishvel, wishdir ); - wishspeed = VectorNormalize( wishdir ); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - PM_Accelerate( wishdir, wishspeed, accel ); + PM_Accelerate(wishdir, wishspeed, accel); - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); } -qboolean PM_GroundSlideOkay( float zNormal ) -{ - if ( zNormal > 0 ) - { - if ( pm->ps->velocity[2] > 0 ) - { - if ( pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP - || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND - || PM_InReboundJump( pm->ps->legsAnim )) - { +qboolean PM_GroundSlideOkay(float zNormal) { + if (zNormal > 0) { + if (pm->ps->velocity[2] > 0) { + if (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START || + pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND || + PM_InReboundJump(pm->ps->legsAnim)) { return qfalse; } } @@ -2864,14 +2393,14 @@ PM_AirMove =================== */ -static void PM_AirMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - usercmd_t cmd; - float gravMod = 1.0f; +static void PM_AirMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + usercmd_t cmd; + float gravMod = 1.0f; #if METROID_JUMP PM_CheckJump(); @@ -2883,7 +2412,7 @@ static void PM_AirMove( void ) { smove = pm->cmd.rightmove; cmd = pm->cmd; - PM_CmdScale( &cmd ); + PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -2891,41 +2420,36 @@ static void PM_AirMove( void ) { // project moves down to flat plane pml.forward[2] = 0; pml.right[2] = 0; - VectorNormalize (pml.forward); - VectorNormalize (pml.right); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); Vehicle_t *pVeh = NULL; - if ( pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { + if (pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { pVeh = pm->gent->m_pVehicle; } - if ( pVeh && pVeh->m_pVehicleInfo->hoverHeight > 0 ) - {//in a hovering vehicle, have air control + if (pVeh && pVeh->m_pVehicleInfo->hoverHeight > 0) { // in a hovering vehicle, have air control // Flying Or Breaking, No Control //-------------------------------- - if ( pVeh->m_ulFlags&VEH_FLYING || pVeh->m_ulFlags&VEH_SLIDEBREAKING) - { + if (pVeh->m_ulFlags & VEH_FLYING || pVeh->m_ulFlags & VEH_SLIDEBREAKING) { wishspeed = 0.0f; - VectorClear( wishvel ); - VectorClear( wishdir ); + VectorClear(wishvel); + VectorClear(wishdir); } // Out Of Control - Maintain pos3 Velocity //----------------------------------------- - else if ((pVeh->m_ulFlags&VEH_OUTOFCONTROL) || (pVeh->m_ulFlags&VEH_STRAFERAM)) - { - VectorCopy(pm->gent->pos3, wishvel); + else if ((pVeh->m_ulFlags & VEH_OUTOFCONTROL) || (pVeh->m_ulFlags & VEH_STRAFERAM)) { + VectorCopy(pm->gent->pos3, wishvel); VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); } // Boarding - Maintain Boarding Velocity //--------------------------------------- - else if (pVeh->m_iBoarding) - { + else if (pVeh->m_iBoarding) { VectorCopy(pVeh->m_vBoardingVelocity, wishvel); VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); @@ -2933,146 +2457,122 @@ static void PM_AirMove( void ) { // Otherwise, Normal Velocity //---------------------------- - else - { + else { wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); } - } - else if ( (pm->ps->pm_flags&PMF_SLOW_MO_FALL) ) - {//no air-control - VectorClear( wishvel ); - } - else - { - for ( i = 0 ; i < 2 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else if ((pm->ps->pm_flags & PMF_SLOW_MO_FALL)) { // no air-control + VectorClear(wishvel); + } else { + for (i = 0; i < 2; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } wishvel[2] = 0; } - VectorCopy (wishvel, wishdir); - wishspeed = VectorNormalize(wishdir); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - if ( ( DotProduct (pm->ps->velocity, wishdir) ) < 0.0f ) - {//Encourage deceleration away from the current velocity + if ((DotProduct(pm->ps->velocity, wishdir)) < 0.0f) { // Encourage deceleration away from the current velocity wishspeed *= pm_airDecelRate; } // not on ground, so little effect on velocity float accelerate = pm_airaccelerate; - if ( pVeh && pVeh->m_pVehicleInfo->type == VH_SPEEDER ) - {//speeders have more control in air - //in mid-air + if (pVeh && pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // speeders have more control in air + // in mid-air accelerate = pVeh->m_pVehicleInfo->acceleration; - if ( pml.groundPlane ) - {//on a slope of some kind, shouldn't have much control and should slide a lot + if (pml.groundPlane) { // on a slope of some kind, shouldn't have much control and should slide a lot accelerate *= 0.5f; } - if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) - { + if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) { VectorScale(pm->ps->velocity, 0.80f, pm->ps->velocity); } - if (pm->ps->velocity[2]>1000.0f) - { + if (pm->ps->velocity[2] > 1000.0f) { pm->ps->velocity[2] = 1000.0f; } } - PM_Accelerate( wishdir, wishspeed, accelerate ); - + PM_Accelerate(wishdir, wishspeed, accelerate); // we may have a ground plane that is very steep, even // though we don't have a groundentity // slide along the steep plane - if ( pml.groundPlane ) - { - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - { - PM_ClipVelocity( pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 - && pm->ps->forceJumpZStart - && pm->ps->velocity[2] > 0 ) - {//I am force jumping and I'm not holding the button anymore - float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart + (pm->ps->velocity[2]*pml.frametime); + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->ps->forceJumpZStart && + pm->ps->velocity[2] > 0) { // I am force jumping and I'm not holding the button anymore + float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart + (pm->ps->velocity[2] * pml.frametime); float maxJumpHeight = forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]; - if ( curHeight >= maxJumpHeight ) - {//reached top, cut velocity + if (curHeight >= maxJumpHeight) { // reached top, cut velocity pm->ps->velocity[2] = 0; } } - if ( (pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - { + if ((pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { gravMod = 0.0f; } - PM_StepSlideMove( gravMod ); + PM_StepSlideMove(gravMod); - if (pVeh && pm->ps->pm_flags&PMF_BUMPED) - { + if (pVeh && pm->ps->pm_flags & PMF_BUMPED) { -/* - // Turn Vehicle In Direction Of Collision - //---------------------------------------- - vec3_t nAngles; - vectoangles(pm->ps->velocity, nAngles); - nAngles[0] = pVeh->m_pParentEntity->client->ps.viewangles[0]; - nAngles[2] = pVeh->m_pParentEntity->client->ps.viewangles[2]; - - // toggle the teleport bit so the client knows to not lerp - player->client->ps.eFlags ^= EF_TELEPORT_BIT; - - // set angles - SetClientViewAngle( pVeh->m_pParentEntity, nAngles ); - if (pVeh->m_pPilot) - { - SetClientViewAngle( pVeh->m_pPilot, nAngles ); - } + /* + // Turn Vehicle In Direction Of Collision + //---------------------------------------- + vec3_t nAngles; + vectoangles(pm->ps->velocity, nAngles); + nAngles[0] = pVeh->m_pParentEntity->client->ps.viewangles[0]; + nAngles[2] = pVeh->m_pParentEntity->client->ps.viewangles[2]; - VectorCopy(nAngles, pVeh->m_vPrevOrientation); - VectorCopy(nAngles, pVeh->m_vOrientation); - pVeh->m_vAngularVelocity = 0.0f; -*/ + // toggle the teleport bit so the client knows to not lerp + player->client->ps.eFlags ^= EF_TELEPORT_BIT; + + // set angles + SetClientViewAngle( pVeh->m_pParentEntity, nAngles ); + if (pVeh->m_pPilot) + { + SetClientViewAngle( pVeh->m_pPilot, nAngles ); + } + + VectorCopy(nAngles, pVeh->m_vPrevOrientation); + VectorCopy(nAngles, pVeh->m_vOrientation); + pVeh->m_vAngularVelocity = 0.0f; + */ // Reduce "Bounce Up Wall" Velocity //---------------------------------- - if (pm->ps->velocity[2]>0) - { + if (pm->ps->velocity[2] > 0) { pm->ps->velocity[2] *= 0.1f; } } } - /* =================== PM_WalkMove =================== */ -static void PM_WalkMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; - usercmd_t cmd; - float accelerate; - float vel; - - if ( pm->ps->gravity < 0 ) - {//float away +static void PM_WalkMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; + usercmd_t cmd; + float accelerate; + float vel; + + if (pm->ps->gravity < 0) { // float away pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; pm->ps->groundEntityNum = ENTITYNUM_NONE; pml.groundPlane = qfalse; pml.walking = qfalse; - if ( pm->waterlevel > 1 ) { + if (pm->waterlevel > 1) { PM_WaterMove(); } else { PM_AirMove(); @@ -3080,16 +2580,15 @@ static void PM_WalkMove( void ) { return; } - if ( pm->waterlevel > 2 && DotProduct( pml.forward, pml.groundTrace.plane.normal ) > 0 ) { + if (pm->waterlevel > 2 && DotProduct(pml.forward, pml.groundTrace.plane.normal) > 0) { // begin swimming PM_WaterMove(); return; } - - if ( PM_CheckJump () ) { + if (PM_CheckJump()) { // jumped away - if ( pm->waterlevel > 1 ) { + if (pm->waterlevel > 1) { PM_WaterMove(); } else { PM_AirMove(); @@ -3097,39 +2596,34 @@ static void PM_WalkMove( void ) { return; } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE &&//on ground - pm->ps->velocity[2] <= 0 &&//not going up - pm->ps->pm_flags&PMF_TIME_KNOCKBACK )//knockback fimter on (stops friction) + if (pm->ps->groundEntityNum != ENTITYNUM_NONE && // on ground + pm->ps->velocity[2] <= 0 && // not going up + pm->ps->pm_flags & PMF_TIME_KNOCKBACK) // knockback fimter on (stops friction) { pm->ps->pm_flags &= ~PMF_TIME_KNOCKBACK; } qboolean slide = qfalse; - if ( pm->ps->pm_type == PM_DEAD ) - {//corpse - if ( g_entities[pm->ps->groundEntityNum].client ) - {//on a client - if ( g_entities[pm->ps->groundEntityNum].health > 0 ) - {//a living client - //no friction + if (pm->ps->pm_type == PM_DEAD) { // corpse + if (g_entities[pm->ps->groundEntityNum].client) { // on a client + if (g_entities[pm->ps->groundEntityNum].health > 0) { // a living client + // no friction slide = qtrue; } } } - if ( !slide ) - { - PM_Friction (); + if (!slide) { + PM_Friction(); } - if ( g_debugMelee->integer ) - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//player - && cg.renderingThirdPerson//in third person - && ((pm->cmd.buttons&BUTTON_USE)||pm->ps->leanStopDebounceTime)//holding use or leaning + if (g_debugMelee->integer) { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // player + && cg.renderingThirdPerson // in third person + && ((pm->cmd.buttons & BUTTON_USE) || pm->ps->leanStopDebounceTime) // holding use or leaning //&& (pm->ps->forcePowersActive&(1<ps->groundEntityNum != ENTITYNUM_NONE//on ground - && !cg_usingInFrontOf )//nothing to use - {//holding use stops you from moving + && pm->ps->groundEntityNum != ENTITYNUM_NONE // on ground + && !cg_usingInFrontOf) // nothing to use + { // holding use stops you from moving return; } } @@ -3137,7 +2631,7 @@ static void PM_WalkMove( void ) { smove = pm->cmd.rightmove; cmd = pm->cmd; - scale = PM_CmdScale( &cmd ); + scale = PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -3147,132 +2641,114 @@ static void PM_WalkMove( void ) { pml.right[2] = 0; // project the forward and right directions onto the ground plane - PM_ClipVelocity (pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP ); - PM_ClipVelocity (pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP ); + PM_ClipVelocity(pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP); + PM_ClipVelocity(pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP); // - VectorNormalize (pml.forward); - VectorNormalize (pml.right); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); -/* if ( ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) && pm->gent->NPC ) - {//speeder control scheme - vec3_t vfwd, vrt; - AngleVectors( ((CVehicleNPC *)pm->gent->NPC)->m_vOrientation, vfwd, vrt, NULL ); + /* if ( ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) && pm->gent->NPC ) + {//speeder control scheme + vec3_t vfwd, vrt; + AngleVectors( ((CVehicleNPC *)pm->gent->NPC)->m_vOrientation, vfwd, vrt, NULL ); - float speed = pm->ps->speed; - if ( fmove < 0 ) - {//going backwards - if ( speed < 0 ) - {//speed is negative, but since our command is reverse, make speed positive - speed = fabs( speed ); - } - else if ( speed > 0 ) - {//trying to move back but speed is still positive, so keep moving forward (we'll slow down eventually) - speed *= -1; + float speed = pm->ps->speed; + if ( fmove < 0 ) + {//going backwards + if ( speed < 0 ) + {//speed is negative, but since our command is reverse, make speed positive + speed = fabs( speed ); + } + else if ( speed > 0 ) + {//trying to move back but speed is still positive, so keep moving forward (we'll slow down eventually) + speed *= -1; + } } + VectorScale( vfwd, speed*fmove/127.0f, wishvel ); + //VectorMA( wishvel, pm->ps->speed*smove/127.0f, vrt, wishvel ); + wishspeed = VectorNormalize2( wishvel, wishdir ); } - VectorScale( vfwd, speed*fmove/127.0f, wishvel ); - //VectorMA( wishvel, pm->ps->speed*smove/127.0f, vrt, wishvel ); - wishspeed = VectorNormalize2( wishvel, wishdir ); - } - else*/ + else*/ // Get The WishVel And WishSpeed //------------------------------- - if ( pm->ps->clientNum && (USENEWNAVSYSTEM || !VectorCompare( pm->ps->moveDir, vec3_origin )) ) - {//NPC + if (pm->ps->clientNum && (USENEWNAVSYSTEM || !VectorCompare(pm->ps->moveDir, vec3_origin))) { // NPC // If The UCmds Were Set, But Never Converted Into A MoveDir, Then Make The WishDir From UCmds //-------------------------------------------------------------------------------------------- - if ((fmove!=0.0f || smove!=0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) - { - //gi.Printf("Generating MoveDir\n"); - for ( i = 0 ; i < 3 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if ((fmove != 0.0f || smove != 0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) { + // gi.Printf("Generating MoveDir\n"); + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } - VectorCopy( wishvel, wishdir ); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Otherwise, Use The Move Dir //----------------------------- - else - { + else { wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); } - } - else - { - for ( i = 0 ; i < 3 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } // when going up or down slopes the wish velocity should Not be zero - // wishvel[2] = 0; + // wishvel[2] = 0; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Handle negative speed. - if ( wishspeed < 0 ) - { + if (wishspeed < 0) { wishspeed = wishspeed * -1.0f; - VectorScale( wishvel, -1.0f, wishvel ); - VectorScale( wishdir, -1.0f, wishdir ); + VectorScale(wishvel, -1.0f, wishvel); + VectorScale(wishdir, -1.0f, wishdir); } // clamp the speed lower if ducking - if ( pm->ps->pm_flags & PMF_DUCKED && !PM_InKnockDown( pm->ps ) ) - { - if ( wishspeed > pm->ps->speed * pm_duckScale ) - { + if (pm->ps->pm_flags & PMF_DUCKED && !PM_InKnockDown(pm->ps)) { + if (wishspeed > pm->ps->speed * pm_duckScale) { wishspeed = pm->ps->speed * pm_duckScale; } } // clamp the speed lower if wading or walking on the bottom - if ( pm->waterlevel ) { - float waterScale; + if (pm->waterlevel) { + float waterScale; waterScale = pm->waterlevel / 3.0; - waterScale = 1.0 - ( 1.0 - pm_swimScale ) * waterScale; - if ( wishspeed > pm->ps->speed * waterScale ) { + waterScale = 1.0 - (1.0 - pm_swimScale) * waterScale; + if (wishspeed > pm->ps->speed * waterScale) { wishspeed = pm->ps->speed * waterScale; } } // when a player gets hit, they temporarily lose // full control, which allows them to be moved a bit - if ( Flying == FLY_HOVER ) - { + if (Flying == FLY_HOVER) { accelerate = pm_vehicleaccelerate; - } - else if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || (pm->ps->pm_flags&PMF_TIME_KNOCKBACK) || (pm->ps->pm_flags&PMF_TIME_NOFRICTION) ) - { + } else if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || (pm->ps->pm_flags & PMF_TIME_KNOCKBACK) || (pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { accelerate = pm_airaccelerate; - } - else - { + } else { accelerate = pm_accelerate; // Wind Affects Acceleration //=================================================== - if (wishspeed>0.0f && pm->gent && !pml.walking) - { - if (gi.WE_GetWindGusting(pm->gent->currentOrigin)) - { - vec3_t windDir; - if (gi.WE_GetWindVector(windDir, pm->gent->currentOrigin)) - { - if (gi.WE_IsOutside(pm->gent->currentOrigin)) - { + if (wishspeed > 0.0f && pm->gent && !pml.walking) { + if (gi.WE_GetWindGusting(pm->gent->currentOrigin)) { + vec3_t windDir; + if (gi.WE_GetWindVector(windDir, pm->gent->currentOrigin)) { + if (gi.WE_IsOutside(pm->gent->currentOrigin)) { VectorScale(windDir, -1.0f, windDir); - accelerate *= (1.0f - (DotProduct(wishdir, windDir)*0.55f)); + accelerate *= (1.0f - (DotProduct(wishdir, windDir) * 0.55f)); } } } @@ -3280,123 +2756,110 @@ static void PM_WalkMove( void ) { //=================================================== } - PM_Accelerate (wishdir, wishspeed, accelerate); + PM_Accelerate(wishdir, wishspeed, accelerate); - //Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); - //Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); + // Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); + // Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); - if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK || (pm->ps->pm_flags&PMF_TIME_NOFRICTION) ) { - if ( pm->ps->gravity >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE && !VectorLengthSquared( pm->ps->velocity ) && pml.groundTrace.plane.normal[2] == 1.0 ) - {//on ground and not moving and on level ground, no reason to do stupid fucking gravity with the clipvelocity!!!! - } - else - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) && !(pm->ps->eFlags&EF_FORCE_DRAINED) ) - { + if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK || (pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { + if (pm->ps->gravity >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE && !VectorLengthSquared(pm->ps->velocity) && + pml.groundTrace.plane.normal[2] == + 1.0) { // on ground and not moving and on level ground, no reason to do stupid fucking gravity with the clipvelocity!!!! + } else { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED) && !(pm->ps->eFlags & EF_FORCE_DRAINED)) { pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; } } } else { // don't reset the z velocity for slopes -// pm->ps->velocity[2] = 0; + // pm->ps->velocity[2] = 0; } vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); // don't decrease velocity when going up or down a slope VectorNormalize(pm->ps->velocity); VectorScale(pm->ps->velocity, vel, pm->ps->velocity); // don't do anything if standing still - if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] ) { + if (!pm->ps->velocity[0] && !pm->ps->velocity[1]) { return; } - if ( pm->ps->gravity <= 0 ) - {//need to apply gravity since we're going to float up from ground - PM_StepSlideMove( 1 ); - } - else - { - PM_StepSlideMove( 0 ); + if (pm->ps->gravity <= 0) { // need to apply gravity since we're going to float up from ground + PM_StepSlideMove(1); + } else { + PM_StepSlideMove(0); } - //Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); - + // Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); } - /* ============== PM_DeadMove ============== */ -static void PM_DeadMove( void ) { - float forward; +static void PM_DeadMove(void) { + float forward; // If this is a vehicle, tell him he's dead, but give him a little while to do his things. -/* if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->NPC && pm->gent->health != -99999 ) - { - pm->gent->health = 1; - ((CVehicleNPC *)pm->gent->NPC)->StartDeathDelay( 0 ); - } - else - { - pm->gent->health = 0; - }*/ + /* if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->NPC && pm->gent->health != -99999 ) + { + pm->gent->health = 1; + ((CVehicleNPC *)pm->gent->NPC)->StartDeathDelay( 0 ); + } + else + { + pm->gent->health = 0; + }*/ - if ( !pml.walking ) { + if (!pml.walking) { return; } // extra friction - forward = VectorLength (pm->ps->velocity); + forward = VectorLength(pm->ps->velocity); forward -= 20; - if ( forward <= 0 ) { - VectorClear (pm->ps->velocity); + if (forward <= 0) { + VectorClear(pm->ps->velocity); } else { - VectorNormalize (pm->ps->velocity); - VectorScale (pm->ps->velocity, forward, pm->ps->velocity); + VectorNormalize(pm->ps->velocity); + VectorScale(pm->ps->velocity, forward, pm->ps->velocity); } } - /* =============== PM_NoclipMove =============== */ -static void PM_NoclipMove( void ) { - float speed, drop, friction, control, newspeed; - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; - - if(pm->gent && pm->gent->client) - { +static void PM_NoclipMove(void) { + float speed, drop, friction, control, newspeed; + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; + + if (pm->gent && pm->gent->client) { pm->ps->viewheight = pm->gent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET; -// if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) -// { -// assert(0); -// } + // if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) + // { + // assert(0); + // } - VectorCopy( pm->gent->mins, pm->mins ); - VectorCopy( pm->gent->maxs, pm->maxs ); - } - else - { - pm->ps->viewheight = DEFAULT_MAXS_2 + STANDARD_VIEWHEIGHT_OFFSET;//DEFAULT_VIEWHEIGHT; + VectorCopy(pm->gent->mins, pm->mins); + VectorCopy(pm->gent->maxs, pm->maxs); + } else { + pm->ps->viewheight = DEFAULT_MAXS_2 + STANDARD_VIEWHEIGHT_OFFSET; // DEFAULT_VIEWHEIGHT; - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -3411,18 +2874,15 @@ static void PM_NoclipMove( void ) { // friction - speed = VectorLength (pm->ps->velocity); - if (speed < 1) - { - VectorCopy (vec3_origin, pm->ps->velocity); - } - else - { + speed = VectorLength(pm->ps->velocity); + if (speed < 1) { + VectorCopy(vec3_origin, pm->ps->velocity); + } else { drop = 0; - friction = pm_friction*1.5; // extra friction + friction = pm_friction * 1.5; // extra friction control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; // scale the velocity newspeed = speed - drop; @@ -3430,87 +2890,73 @@ static void PM_NoclipMove( void ) { newspeed = 0; newspeed /= speed; - VectorScale (pm->ps->velocity, newspeed, pm->ps->velocity); + VectorScale(pm->ps->velocity, newspeed, pm->ps->velocity); } // accelerate - scale = PM_CmdScale( &pm->cmd ); - if (pm->cmd.buttons & BUTTON_ATTACK) { //turbo boost + scale = PM_CmdScale(&pm->cmd); + if (pm->cmd.buttons & BUTTON_ATTACK) { // turbo boost scale *= 10; } - if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { //turbo boost + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // turbo boost scale *= 10; } fmove = pm->cmd.forwardmove; smove = pm->cmd.rightmove; - for (i=0 ; i<3 ; i++) - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + for (i = 0; i < 3; i++) + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; wishvel[2] += pm->cmd.upmove; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; - PM_Accelerate( wishdir, wishspeed, pm_accelerate ); + PM_Accelerate(wishdir, wishspeed, pm_accelerate); // move - VectorMA (pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); + VectorMA(pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); } //============================================================================ -static float PM_DamageForDelta( int delta ) -{ +static float PM_DamageForDelta(int delta) { float damage = delta; - if ( pm->gent->NPC ) - { - if ( pm->ps->weapon == WP_SABER - || (pm->gent->client && pm->gent->client->NPC_class == CLASS_REBORN) ) - {//FIXME: for now Jedi take no falling damage, but really they should if pushed off? + if (pm->gent->NPC) { + if (pm->ps->weapon == WP_SABER || + (pm->gent->client && + pm->gent->client->NPC_class == CLASS_REBORN)) { // FIXME: for now Jedi take no falling damage, but really they should if pushed off? damage = 0; } - } - else if ( pm->ps->clientNum < MAX_CLIENTS ) - { - if ( damage < 50 ) - { - if ( damage > 24 ) - { + } else if (pm->ps->clientNum < MAX_CLIENTS) { + if (damage < 50) { + if (damage > 24) { damage = damage - 25; } - } - else - { + } else { damage *= 0.5f; } } return damage * 0.5f; } -static void PM_CrashLandDamage( int damage ) -{ - if ( pm->gent ) - { +static void PM_CrashLandDamage(int damage) { + if (pm->gent) { int dflags = DAMAGE_NO_ARMOR; - if ( pm->gent->NPC && (pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { + if (pm->gent->NPC && (pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { damage = 1000; dflags |= DAMAGE_DIE_ON_IMPACT; - } - else - { - damage = PM_DamageForDelta( damage ); + } else { + damage = PM_DamageForDelta(damage); - if ( (pm->gent->flags&FL_NO_IMPACT_DMG) ) + if ((pm->gent->flags & FL_NO_IMPACT_DMG)) return; } - if ( damage ) - { - pm->gent->painDebounceTime = level.time + 200; // no normal pain sound - G_Damage( pm->gent, NULL, player, NULL, NULL, damage, dflags, MOD_FALLING ); + if (damage) { + pm->gent->painDebounceTime = level.time + 200; // no normal pain sound + G_Damage(pm->gent, NULL, player, NULL, NULL, damage, dflags, MOD_FALLING); } } } @@ -3562,52 +3008,40 @@ static float PM_CrashLandDelta( vec3_t org, vec3_t prevOrg, vec3_t prev_vel, flo } */ -static float PM_CrashLandDelta( vec3_t prev_vel, int waterlevel ) -{ +static float PM_CrashLandDelta(vec3_t prev_vel, int waterlevel) { float delta; - if ( pm->waterlevel == 3 ) - { + if (pm->waterlevel == 3) { return 0; } - delta = fabs(prev_vel[2])/10;//VectorLength( prev_vel ) + delta = fabs(prev_vel[2]) / 10; // VectorLength( prev_vel ) // reduce falling damage if there is standing water - if ( pm->waterlevel == 2 ) - { + if (pm->waterlevel == 2) { delta *= 0.25; } - if ( pm->waterlevel == 1 ) - { + if (pm->waterlevel == 1) { delta *= 0.5; } return delta; } -int PM_GetLandingAnim( void ) -{ +int PM_GetLandingAnim(void) { int anim = pm->ps->legsAnim; - //special cases: - if ( anim == BOTH_FLIP_ATTACK7 - || anim == BOTH_FLIP_HOLD7 ) - { - return BOTH_FLIP_LAND; - } - else if ( anim == BOTH_FLIP_LAND ) - { - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + // special cases: + if (anim == BOTH_FLIP_ATTACK7 || anim == BOTH_FLIP_HOLD7) { + return BOTH_FLIP_LAND; + } else if (anim == BOTH_FLIP_LAND) { + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } return BOTH_LAND1; - } - else if ( PM_InAirKickingAnim( anim ) ) - { - switch ( anim ) - { + } else if (PM_InAirKickingAnim(anim)) { + switch (anim) { case BOTH_A7_KICK_F_AIR: return BOTH_FORCELAND1; break; @@ -3623,17 +3057,15 @@ int PM_GetLandingAnim( void ) } } - if ( PM_SpinningAnim( anim ) || PM_SaberInSpecialAttack( anim ) ) - { + if (PM_SpinningAnim(anim) || PM_SaberInSpecialAttack(anim)) { return -1; } - switch ( anim ) - { + switch (anim) { case BOTH_FORCEJUMPLEFT1: case BOTH_FORCEINAIRLEFT1: anim = BOTH_FORCELANDLEFT1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3641,16 +3073,16 @@ int PM_GetLandingAnim( void ) case BOTH_FORCEJUMPRIGHT1: case BOTH_FORCEINAIRRIGHT1: anim = BOTH_FORCELANDRIGHT1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } break; case BOTH_FORCEJUMP1: case BOTH_FORCEINAIR1: - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3658,8 +3090,8 @@ int PM_GetLandingAnim( void ) break; case BOTH_FORCEJUMPBACK1: case BOTH_FORCEINAIRBACK1: - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3668,8 +3100,8 @@ int PM_GetLandingAnim( void ) case BOTH_JUMPLEFT1: case BOTH_INAIRLEFT1: anim = BOTH_LANDLEFT1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3677,8 +3109,8 @@ int PM_GetLandingAnim( void ) case BOTH_JUMPRIGHT1: case BOTH_INAIRRIGHT1: anim = BOTH_LANDRIGHT1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3686,8 +3118,8 @@ int PM_GetLandingAnim( void ) case BOTH_JUMP1: case BOTH_INAIR1: anim = BOTH_LAND1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3695,8 +3127,8 @@ int PM_GetLandingAnim( void ) case BOTH_JUMPBACK1: case BOTH_INAIRBACK1: anim = BOTH_LANDBACK1; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3714,8 +3146,8 @@ int PM_GetLandingAnim( void ) case BOTH_ARIAL_F1: case BOTH_CARTWHEEL_LEFT: case BOTH_CARTWHEEL_RIGHT: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_A7_KICK_F: @@ -3745,24 +3177,20 @@ int PM_GetLandingAnim( void ) case BOTH_FORCELONGLEAP_ATTACK: return BOTH_FORCELONGLEAP_LAND; break; - case BOTH_WALL_RUN_LEFT://# - case BOTH_WALL_RUN_RIGHT://# - if ( pm->ps->legsAnimTimer > 500 ) - {//only land at end of anim + case BOTH_WALL_RUN_LEFT: //# + case BOTH_WALL_RUN_RIGHT: //# + if (pm->ps->legsAnimTimer > 500) { // only land at end of anim return -1; } - //NOTE: falls through on purpose! + // NOTE: falls through on purpose! default: - if ( pm->ps->pm_flags & PMF_BACKWARDS_JUMP ) - { + if (pm->ps->pm_flags & PMF_BACKWARDS_JUMP) { anim = BOTH_LANDBACK1; - } - else - { + } else { anim = BOTH_LAND1; } - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } @@ -3771,190 +3199,136 @@ int PM_GetLandingAnim( void ) return anim; } -void G_StartRoll( gentity_t *ent, int anim ) -{ - NPC_SetAnim(ent,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer - 200;//just to make sure it's cleared when roll is done - G_AddEvent( ent, EV_ROLL, 0 ); +void G_StartRoll(gentity_t *ent, int anim) { + NPC_SetAnim(ent, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer - 200; // just to make sure it's cleared when roll is done + G_AddEvent(ent, EV_ROLL, 0); ent->client->ps.saberMove = LS_NONE; } -static qboolean PM_TryRoll( void ) -{ - float rollDist = 192;//was 64; - if ( PM_SaberInAttack( pm->ps->saberMove ) || PM_SaberInSpecialAttack( pm->ps->torsoAnim ) - || PM_SpinningSaberAnim( pm->ps->legsAnim ) - || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&PM_SaberInStart( pm->ps->saberMove )) ) - {//attacking or spinning (or, if player, starting an attack) - if ( PM_CanRollFromSoulCal( pm->ps ) ) - {//hehe - } - else - { +static qboolean PM_TryRoll(void) { + float rollDist = 192; // was 64; + if (PM_SaberInAttack(pm->ps->saberMove) || PM_SaberInSpecialAttack(pm->ps->torsoAnim) || PM_SpinningSaberAnim(pm->ps->legsAnim) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + PM_SaberInStart(pm->ps->saberMove))) { // attacking or spinning (or, if player, starting an attack) + if (PM_CanRollFromSoulCal(pm->ps)) { // hehe + } else { return qfalse; } } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && (!cg.renderingThirdPerson || cg.zoomMode) ) - {//player can't do this in 1st person + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && (!cg.renderingThirdPerson || cg.zoomMode)) { // player can't do this in 1st person return qfalse; } - if ( !pm->gent ) - { + if (!pm->gent) { return qfalse; } - if ( (pm->ps->saber[0].saberFlags&SFL_NO_ROLLS) ) - { + if ((pm->ps->saber[0].saberFlags & SFL_NO_ROLLS)) { return qfalse; } - if ( pm->ps->dualSabers - && (pm->ps->saber[1].saberFlags&SFL_NO_ROLLS) ) - { + if (pm->ps->dualSabers && (pm->ps->saber[1].saberFlags & SFL_NO_ROLLS)) { return qfalse; } - if ( pm->ps->clientNum && pm->gent->NPC ) - {//NPC - if ( pm->gent->NPC->scriptFlags&SCF_NO_ACROBATICS ) - {//scripted to never do acrobatics + if (pm->ps->clientNum && pm->gent->NPC) { // NPC + if (pm->gent->NPC->scriptFlags & SCF_NO_ACROBATICS) { // scripted to never do acrobatics return qfalse; } - if ( pm->ps->weapon == WP_SABER ) - {//jedi/reborn - if ( pm->gent->NPC->rank != RANK_CREWMAN && pm->gent->NPC->rank < RANK_LT_JG ) - {//reborn/jedi who are not acrobats or fencers can't do any of these acrobatics + if (pm->ps->weapon == WP_SABER) { // jedi/reborn + if (pm->gent->NPC->rank != RANK_CREWMAN && + pm->gent->NPC->rank < RANK_LT_JG) { // reborn/jedi who are not acrobats or fencers can't do any of these acrobatics return qfalse; } - } - else - {//non-jedi/reborn - if ( pm->ps->weapon != WP_NONE )//not empty-handed...who would that be??? - {//only jedi/reborn NPCs should be able to do rolls (with a few exceptions) - if ( !pm->gent - || !pm->gent->client - || (pm->gent->client->NPC_class != CLASS_BOBAFETT //boba can roll with it, baby - && pm->gent->client->NPC_class != CLASS_REBORN //reborn using weapons other than saber can still roll - )) - {//can't roll + } else { // non-jedi/reborn + if (pm->ps->weapon != WP_NONE) // not empty-handed...who would that be??? + { // only jedi/reborn NPCs should be able to do rolls (with a few exceptions) + if (!pm->gent || !pm->gent->client || + (pm->gent->client->NPC_class != CLASS_BOBAFETT // boba can roll with it, baby + && pm->gent->client->NPC_class != CLASS_REBORN // reborn using weapons other than saber can still roll + )) { // can't roll return qfalse; } } } } - vec3_t fwd, right, traceto, - mins = { pm->mins[0], pm->mins[1], pm->mins[2] + STEPSIZE }, - maxs = { pm->maxs[0], pm->maxs[1], (float)pm->gent->client->crouchheight }, - fwdAngles = { 0, pm->ps->viewangles[YAW], 0 }; - trace_t trace; - int anim = -1; - AngleVectors( fwdAngles, fwd, right, NULL ); - //FIXME: trace ahead for clearance to roll - if ( pm->cmd.forwardmove ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { + vec3_t fwd, right, traceto, mins = {pm->mins[0], pm->mins[1], pm->mins[2] + STEPSIZE}, + maxs = {pm->maxs[0], pm->maxs[1], (float)pm->gent->client->crouchheight}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + int anim = -1; + AngleVectors(fwdAngles, fwd, right, NULL); + // FIXME: trace ahead for clearance to roll + if (pm->cmd.forwardmove) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { anim = BOTH_ROLL_B; - VectorMA( pm->ps->origin, -rollDist, fwd, traceto ); - } - else - { + VectorMA(pm->ps->origin, -rollDist, fwd, traceto); + } else { anim = BOTH_ROLL_F; - VectorMA( pm->ps->origin, rollDist, fwd, traceto ); + VectorMA(pm->ps->origin, rollDist, fwd, traceto); } - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_ROLL_R; - VectorMA( pm->ps->origin, rollDist, right, traceto ); - } - else if ( pm->cmd.rightmove < 0 ) - { + VectorMA(pm->ps->origin, rollDist, right, traceto); + } else if (pm->cmd.rightmove < 0) { anim = BOTH_ROLL_L; - VectorMA( pm->ps->origin, -rollDist, right, traceto ); + VectorMA(pm->ps->origin, -rollDist, right, traceto); + } else { //??? } - else - {//??? - } - if ( anim != -1 ) - { + if (anim != -1) { qboolean roll = qfalse; - int clipmask = CONTENTS_SOLID; - if ( pm->ps->clientNum ) - { - clipmask |= (CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP); - } - else - { - if ( pm->gent && pm->gent->enemy && pm->gent->enemy->health > 0 ) - {//player can always roll in combat + int clipmask = CONTENTS_SOLID; + if (pm->ps->clientNum) { + clipmask |= (CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); + } else { + if (pm->gent && pm->gent->enemy && pm->gent->enemy->health > 0) { // player can always roll in combat roll = qtrue; - } - else - { + } else { clipmask |= CONTENTS_PLAYERCLIP; } } - if ( !roll ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction >= 1.0f ) - {//okay, clear, check for a bottomless drop - vec3_t top; - VectorCopy( traceto, top ); + if (!roll) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, clipmask, (EG2_Collision)0, 0); + if (trace.fraction >= 1.0f) { // okay, clear, check for a bottomless drop + vec3_t top; + VectorCopy(traceto, top); traceto[2] -= 256; - pm->trace( &trace, top, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//not a bottomless drop + pm->trace(&trace, top, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // not a bottomless drop roll = qtrue; } - } - else - {//hit an architectural obstruction - if ( pm->ps->clientNum ) - {//NPCs don't care about rolling into walls, just off ledges - if ( !(trace.contents&CONTENTS_BOTCLIP) ) - { + } else { // hit an architectural obstruction + if (pm->ps->clientNum) { // NPCs don't care about rolling into walls, just off ledges + if (!(trace.contents & CONTENTS_BOTCLIP)) { roll = qtrue; } - } - else if ( G_EntIsDoor( trace.entityNum ) ) - {//okay to roll into a door - if ( G_EntIsUnlockedDoor( trace.entityNum ) ) - {//if it's an auto-door + } else if (G_EntIsDoor(trace.entityNum)) { // okay to roll into a door + if (G_EntIsUnlockedDoor(trace.entityNum)) { // if it's an auto-door roll = qtrue; } - } - else - {//check other conditions + } else { // check other conditions gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && (traceEnt->svFlags&SVF_GLASS_BRUSH) ) - {//okay to roll through glass + if (traceEnt && (traceEnt->svFlags & SVF_GLASS_BRUSH)) { // okay to roll through glass roll = qtrue; } } } } - if ( roll ) - { - G_StartRoll( pm->gent, anim ); + if (roll) { + G_StartRoll(pm->gent, anim); return qtrue; } } return qfalse; } -extern void CG_LandingEffect( vec3_t origin, vec3_t normal, int material ); -static void PM_CrashLandEffect( void ) -{ - if ( pm->waterlevel ) - { +extern void CG_LandingEffect(vec3_t origin, vec3_t normal, int material); +static void PM_CrashLandEffect(void) { + if (pm->waterlevel) { return; } - float delta = fabs(pml.previous_velocity[2])/10;//VectorLength( pml.previous_velocity );? - if ( delta >= 30 ) - { - vec3_t bottom = {pm->ps->origin[0],pm->ps->origin[1],pm->ps->origin[2]+pm->mins[2]+1}; - CG_LandingEffect( bottom, pml.groundTrace.plane.normal, (pml.groundTrace.surfaceFlags&MATERIAL_MASK) ); + float delta = fabs(pml.previous_velocity[2]) / 10; // VectorLength( pml.previous_velocity );? + if (delta >= 30) { + vec3_t bottom = {pm->ps->origin[0], pm->ps->origin[1], pm->ps->origin[2] + pm->mins[2] + 1}; + CG_LandingEffect(bottom, pml.groundTrace.plane.normal, (pml.groundTrace.surfaceFlags & MATERIAL_MASK)); } } /* @@ -3964,397 +3338,275 @@ PM_CrashLand Check for hard landings that generate sound events ================= */ -static void PM_CrashLand( void ) -{ - float delta = 0; - qboolean forceLanding = qfalse; +static void PM_CrashLand(void) { + float delta = 0; + qboolean forceLanding = qfalse; - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { - if ( pm->gent->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - { - float dot = DotProduct( pm->ps->velocity, pml.groundTrace.plane.normal ); - //Com_Printf("%i:crashland %4.2f\n", c_pmove, pm->ps->velocity[2]); - if ( dot < -100.0f ) - { - //NOTE: never hits this anyway - if ( pm->gent->m_pVehicle->m_pVehicleInfo->iImpactFX ) - {//make sparks - if ( !Q_irand( 0, 3 ) ) - {//FIXME: debounce - G_PlayEffect( pm->gent->m_pVehicle->m_pVehicleInfo->iImpactFX, pm->ps->origin, pml.groundTrace.plane.normal ); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { + if (pm->gent->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { + float dot = DotProduct(pm->ps->velocity, pml.groundTrace.plane.normal); + // Com_Printf("%i:crashland %4.2f\n", c_pmove, pm->ps->velocity[2]); + if (dot < -100.0f) { + // NOTE: never hits this anyway + if (pm->gent->m_pVehicle->m_pVehicleInfo->iImpactFX) { // make sparks + if (!Q_irand(0, 3)) { // FIXME: debounce + G_PlayEffect(pm->gent->m_pVehicle->m_pVehicleInfo->iImpactFX, pm->ps->origin, pml.groundTrace.plane.normal); } } - int damage = floor(fabs(dot+100)/10.0f); - if ( damage >= 0 ) - { - G_Damage( pm->gent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING ); + int damage = floor(fabs(dot + 100) / 10.0f); + if (damage >= 0) { + G_Damage(pm->gent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING); } } } return; } - if ( (pm->ps->pm_flags&PMF_TRIGGER_PUSHED) ) - { - delta = 21;//? + if ((pm->ps->pm_flags & PMF_TRIGGER_PUSHED)) { + delta = 21; //? forceLanding = qtrue; - } - else - { - if ( pm->gent && pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT ) - {//have to do death on impact if we are falling to our death, FIXME: should we avoid any additional damage this func? - PM_CrashLandDamage( 1000 ); - } - else if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT||pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) ) - { - if ( JET_Flying( pm->gent ) ) - { - if ( pm->gent->client->NPC_class == CLASS_BOBAFETT - || (pm->gent->client->NPC_class == CLASS_ROCKETTROOPER&&pm->gent->NPC&&pm->gent->NPC->rankgent ); - } - else - { - pm->ps->velocity[2] += Q_flrand( 100, 200 ); + } else { + if (pm->gent && pm->gent->NPC && + pm->gent->NPC->aiFlags & + NPCAI_DIE_ON_IMPACT) { // have to do death on impact if we are falling to our death, FIXME: should we avoid any additional damage this func? + PM_CrashLandDamage(1000); + } else if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER)) { + if (JET_Flying(pm->gent)) { + if (pm->gent->client->NPC_class == CLASS_BOBAFETT || + (pm->gent->client->NPC_class == CLASS_ROCKETTROOPER && pm->gent->NPC && pm->gent->NPC->rank < RANK_LT)) { + JET_FlyStop(pm->gent); + } else { + pm->ps->velocity[2] += Q_flrand(100, 200); } - PM_AddEvent( EV_FALL_SHORT ); + PM_AddEvent(EV_FALL_SHORT); } - if ( pm->ps->forceJumpZStart ) - {//we were force-jumping + if (pm->ps->forceJumpZStart) { // we were force-jumping forceLanding = qtrue; } delta = 1; - } - else if ( pm->ps->jumpZStart && (pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_1||(pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())) ) - {//we were force-jumping - if ( pm->ps->origin[2] >= pm->ps->jumpZStart ) - {//we landed at same height or higher than we landed - if ( pm->ps->forceJumpZStart ) - {//we were force-jumping + } else if (pm->ps->jumpZStart && (pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_1 || + (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()))) { // we were force-jumping + if (pm->ps->origin[2] >= pm->ps->jumpZStart) { // we landed at same height or higher than we landed + if (pm->ps->forceJumpZStart) { // we were force-jumping forceLanding = qtrue; } delta = 0; - } - else - {//take off some of it, at least - delta = (pm->ps->jumpZStart-pm->ps->origin[2]); + } else { // take off some of it, at least + delta = (pm->ps->jumpZStart - pm->ps->origin[2]); float dropAllow = forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]; - if ( dropAllow < 128 ) - {//always allow a drop from 128, at least + if (dropAllow < 128) { // always allow a drop from 128, at least dropAllow = 128; } - if ( delta > forceJumpHeight[FORCE_LEVEL_1] ) - {//will have to use force jump ability to absorb some of it - forceLanding = qtrue;//absorbed some - just to force the correct animation to play below + if (delta > forceJumpHeight[FORCE_LEVEL_1]) { // will have to use force jump ability to absorb some of it + forceLanding = qtrue; // absorbed some - just to force the correct animation to play below } - delta = (delta - dropAllow)/2; + delta = (delta - dropAllow) / 2; } - if ( delta < 1 ) - { + if (delta < 1) { delta = 1; } } - if ( !delta ) - { - delta = PM_CrashLandDelta( pml.previous_velocity, pm->waterlevel ); + if (!delta) { + delta = PM_CrashLandDelta(pml.previous_velocity, pm->waterlevel); } } PM_CrashLandEffect(); - if ( (pm->ps->pm_flags&PMF_DUCKED) && (level.time-pm->ps->lastOnGround)>500 ) - {//must be crouched and have been inthe air for half a second minimum - if( !PM_InOnGroundAnim( pm->ps ) && !PM_InKnockDown( pm->ps ) ) - {//roll! - if ( PM_TryRoll() ) - {//absorb some impact + if ((pm->ps->pm_flags & PMF_DUCKED) && (level.time - pm->ps->lastOnGround) > 500) { // must be crouched and have been inthe air for half a second minimum + if (!PM_InOnGroundAnim(pm->ps) && !PM_InKnockDown(pm->ps)) { // roll! + if (PM_TryRoll()) { // absorb some impact delta *= 0.5f; } } } // If he just entered the water (from a fall presumably), absorb some of the impact. - if ( pm->waterlevel >= 2 ) - { + if (pm->waterlevel >= 2) { delta *= 0.4f; } - if ( delta < 1 ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 32, AEL_MINOR, qfalse, qtrue ); + if (delta < 1) { + AddSoundEvent(pm->gent, pm->ps->origin, 32, AEL_MINOR, qfalse, qtrue); return; } qboolean deadFallSound = qfalse; - if( !PM_InDeathAnim() ) - { - if ( PM_InAirKickingAnim( pm->ps->legsAnim ) - && pm->ps->torsoAnim == pm->ps->legsAnim ) - { + if (!PM_InDeathAnim()) { + if (PM_InAirKickingAnim(pm->ps->legsAnim) && pm->ps->torsoAnim == pm->ps->legsAnim) { int anim = PM_GetLandingAnim(); - if ( anim != -1 ) - {//interrupting a kick clears everything - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms + if (anim != -1) { // interrupting a kick clears everything + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms pm->ps->saberMove = LS_READY; pm->ps->weaponTime = 0; - if ( !g_allowBunnyhopping->integer ) { - //stick landings some + if (!g_allowBunnyhopping->integer) { + // stick landings some pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; } } - } - else if ( pm->gent - && pm->gent->client - && pm->gent->client->NPC_class == CLASS_ROCKETTROOPER ) - {//rockettroopers are simpler + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) { // rockettroopers are simpler int anim = PM_GetLandingAnim(); - if ( anim != -1 ) - { - if ( pm->gent->NPC - && pm->gent->NPC->rank < RANK_LT ) - {//special case: ground-based rocket troopers *always* play land anim on whole body - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms + if (anim != -1) { + if (pm->gent->NPC && pm->gent->NPC->rank < RANK_LT) { // special case: ground-based rocket troopers *always* play land anim on whole body + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms + } else { + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms } } - } - else if ( pm->cmd.upmove >= 0 && !PM_InKnockDown( pm->ps ) && !PM_InRoll( pm->ps )) - {//not crouching - if ( delta > 10 - || pm->ps->pm_flags & PMF_BACKWARDS_JUMP - || (pm->ps->forcePowersActive&(1<gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_RANCOR || pm->gent->client->NPC_class == CLASS_WAMPA ) ) - { - } - else - { + } else if (pm->cmd.upmove >= 0 && !PM_InKnockDown(pm->ps) && !PM_InRoll(pm->ps)) { // not crouching + if (delta > 10 || pm->ps->pm_flags & PMF_BACKWARDS_JUMP || (pm->ps->forcePowersActive & (1 << FP_LEVITATION)) || + forceLanding) // EV_FALL_SHORT or jumping back or force-land + { // decide which landing animation to use + if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_RANCOR || pm->gent->client->NPC_class == CLASS_WAMPA)) { + } else { int anim = PM_GetLandingAnim(); - if ( anim != -1 ) - { - if ( PM_FlippingAnim( pm->ps->torsoAnim ) - || PM_SpinningAnim( pm->ps->torsoAnim ) - || pm->ps->torsoAnim == BOTH_FLIP_LAND ) - {//interrupt these if we're going to play a land + if (anim != -1) { + if (PM_FlippingAnim(pm->ps->torsoAnim) || PM_SpinningAnim(pm->ps->torsoAnim) || + pm->ps->torsoAnim == BOTH_FLIP_LAND) { // interrupt these if we're going to play a land pm->ps->torsoAnimTimer = 0; } - if ( anim == BOTH_FORCELONGLEAP_LAND ) - { - if ( pm->gent ) - { - G_SoundOnEnt( pm->gent, CHAN_AUTO, "sound/player/slide.wav" ); + if (anim == BOTH_FORCELONGLEAP_LAND) { + if (pm->gent) { + G_SoundOnEnt(pm->gent, CHAN_AUTO, "sound/player/slide.wav"); } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms - } - else if ( anim == BOTH_FLIP_LAND - || (pm->ps->torsoAnim == BOTH_FLIP_LAND) ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms - } - else if ( PM_InAirKickingAnim( pm->ps->legsAnim ) - && pm->ps->torsoAnim == pm->ps->legsAnim ) - {//interrupting a kick clears everything - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms + } else if (anim == BOTH_FLIP_LAND || (pm->ps->torsoAnim == BOTH_FLIP_LAND)) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms + } else if (PM_InAirKickingAnim(pm->ps->legsAnim) && pm->ps->torsoAnim == pm->ps->legsAnim) { // interrupting a kick clears everything + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms pm->ps->saberMove = LS_READY; pm->ps->weaponTime = 0; - } - else if ( PM_ForceJumpingAnim( pm->ps->legsAnim ) - && pm->ps->torsoAnim == pm->ps->legsAnim ) - {//special case: if land during one of these, set the torso, too, if it's not doing something else - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms + } else if (PM_ForceJumpingAnim(pm->ps->legsAnim) && + pm->ps->torsoAnim == + pm->ps->legsAnim) { // special case: if land during one of these, set the torso, too, if it's not doing something else + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms + } else { + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms } } } } } - } - else - { + } else { pm->ps->gravity = 1.0; - //PM_CrashLandDamage( delta ); - if ( pm->gent ) - { + // PM_CrashLandDamage( delta ); + if (pm->gent) { if ((!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) && -// (!(pml.groundTrace.contents & CONTENTS_NODROP)) && - (!(pm->pointcontents(pm->ps->origin,pm->ps->clientNum) & CONTENTS_NODROP))) - { - if ( pm->waterlevel < 2 ) - {//don't play fallsplat when impact in the water + // (!(pml.groundTrace.contents & CONTENTS_NODROP)) && + (!(pm->pointcontents(pm->ps->origin, pm->ps->clientNum) & CONTENTS_NODROP))) { + if (pm->waterlevel < 2) { // don't play fallsplat when impact in the water deadFallSound = qtrue; - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - if ( delta >= 75 ) - { - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/player/fallsplat.wav" ); - } - else - { - G_SoundOnEnt( pm->gent, CHAN_BODY, va("sound/player/bodyfall_human%d.wav",Q_irand(1,3)) ); + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + if (delta >= 75) { + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/player/fallsplat.wav"); + } else { + G_SoundOnEnt(pm->gent, CHAN_BODY, va("sound/player/bodyfall_human%d.wav", Q_irand(1, 3))); } } + } else { + G_SoundOnEnt(pm->gent, CHAN_BODY, va("sound/player/bodyfall_water%d.wav", Q_irand(1, 3))); } - else - { - G_SoundOnEnt( pm->gent, CHAN_BODY, va("sound/player/bodyfall_water%d.wav",Q_irand(1,3)) ); - } - if ( gi.VoiceVolume[pm->ps->clientNum] - && pm->gent->NPC && (pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//I was talking, so cut it off... with a jump sound? - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - G_SoundOnEnt( pm->gent, CHAN_VOICE_ATTEN, "*pain100.wav" ); + if (gi.VoiceVolume[pm->ps->clientNum] && pm->gent->NPC && + (pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // I was talking, so cut it off... with a jump sound? + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + G_SoundOnEnt(pm->gent, CHAN_VOICE_ATTEN, "*pain100.wav"); } } } } - if( pm->ps->legsAnim == BOTH_FALLDEATH1 || pm->ps->legsAnim == BOTH_FALLDEATH1INAIR) - {//FIXME: add a little bounce? - //FIXME: cut voice channel? + if (pm->ps->legsAnim == BOTH_FALLDEATH1 || pm->ps->legsAnim == BOTH_FALLDEATH1INAIR) { // FIXME: add a little bounce? + // FIXME: cut voice channel? int old_pm_type = pm->ps->pm_type; pm->ps->pm_type = PM_NORMAL; - //Hack because for some reason PM_SetAnim just returns if you're dead...??? - PM_SetAnim(pm, SETANIM_BOTH, BOTH_FALLDEATH1LAND, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + // Hack because for some reason PM_SetAnim just returns if you're dead...??? + PM_SetAnim(pm, SETANIM_BOTH, BOTH_FALLDEATH1LAND, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->pm_type = old_pm_type; - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_SUSPICIOUS, qfalse, qtrue ); + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_SUSPICIOUS, qfalse, qtrue); return; } } // create a local entity event to play the sound - if ( pm->gent && pm->gent->client && pm->gent->client->respawnTime >= level.time - 500 ) - {//just spawned in, don't make a noise + if (pm->gent && pm->gent->client && pm->gent->client->respawnTime >= level.time - 500) { // just spawned in, don't make a noise return; } - if ( delta >= 75 ) - { - if ( !deadFallSound ) - { - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - PM_AddEvent( EV_FALL_FAR ); + if (delta >= 75) { + if (!deadFallSound) { + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + PM_AddEvent(EV_FALL_FAR); } } - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } - if ( pm->gent ) - { - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent) { + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_SUSPICIOUS, qfalse, qtrue ); - } - } - else if ( pm->ps->stats[STAT_HEALTH] <= 0 && pm->gent && pm->gent->enemy ) - { - AddSoundEvent( pm->gent->enemy, pm->ps->origin, 256, AEL_DISCOVERED, qfalse, qtrue ); + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_SUSPICIOUS, qfalse, qtrue); } + } else if (pm->ps->stats[STAT_HEALTH] <= 0 && pm->gent && pm->gent->enemy) { + AddSoundEvent(pm->gent->enemy, pm->ps->origin, 256, AEL_DISCOVERED, qfalse, qtrue); } } - } - else if ( delta >= 50 ) - { + } else if (delta >= 50) { // this is a pain grunt, so don't play it if dead - if ( pm->ps->stats[STAT_HEALTH] > 0 ) - { - if ( !deadFallSound ) - { - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - PM_AddEvent( EV_FALL_MEDIUM );//damage is dealt in g_active, ClientEvents + if (pm->ps->stats[STAT_HEALTH] > 0) { + if (!deadFallSound) { + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + PM_AddEvent(EV_FALL_MEDIUM); // damage is dealt in g_active, ClientEvents } } - if ( pm->gent ) - { - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + if (pm->gent) { + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_MINOR, qfalse, qtrue ); - } + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_MINOR, qfalse, qtrue); } } } } - } - else if ( delta >= 30 ) - { - if ( !deadFallSound ) - { - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - PM_AddEvent( EV_FALL_SHORT ); + } else if (delta >= 30) { + if (!deadFallSound) { + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + PM_AddEvent(EV_FALL_SHORT); } } - if ( pm->gent ) - { - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent) { + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 128, AEL_MINOR, qfalse, qtrue ); - } - } - else - { - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 128, AEL_MINOR, qfalse, qtrue); } + } else { + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } } } - } - else - { - if ( !deadFallSound ) - { - if ( !(pm->ps->pm_flags&PMF_DUCKED) || !Q_irand( 0, 3 ) ) - {//only 25% chance of making landing alert when ducked - AddSoundEvent( pm->gent, pm->ps->origin, 32, AEL_MINOR, qfalse, qtrue ); + } else { + if (!deadFallSound) { + if (!(pm->ps->pm_flags & PMF_DUCKED) || !Q_irand(0, 3)) { // only 25% chance of making landing alert when ducked + AddSoundEvent(pm->gent, pm->ps->origin, 32, AEL_MINOR, qfalse, qtrue); } - if ( !(pm->ps->eFlags&EF_NODRAW) ) - {//no sound if no draw - if ( forceLanding ) - {//we were force-jumping - PM_AddEvent( EV_FALL_SHORT ); - } - else - { -//moved to cg_player PM_AddEvent( PM_FootstepForSurface() ); + if (!(pm->ps->eFlags & EF_NODRAW)) { // no sound if no draw + if (forceLanding) { // we were force-jumping + PM_AddEvent(EV_FALL_SHORT); + } else { + // moved to cg_player PM_AddEvent( PM_FootstepForSurface() ); } } } @@ -4362,22 +3614,19 @@ static void PM_CrashLand( void ) // start footstep cycle over pm->ps->bobCycle = 0; - if ( pm->gent && pm->gent->client ) - {//stop the force push effect when you land + if (pm->gent && pm->gent->client) { // stop the force push effect when you land pm->gent->forcePushTime = 0; } } - - /* ============= PM_CorrectAllSolid ============= */ -static void PM_CorrectAllSolid( void ) { - if ( pm->debugLevel ) { - Com_Printf("%i:allsolid\n", c_pmove); //NOTENOTE: If this ever happens, I'd really like to see this print! +static void PM_CorrectAllSolid(void) { + if (pm->debugLevel) { + Com_Printf("%i:allsolid\n", c_pmove); // NOTENOTE: If this ever happens, I'd really like to see this print! } // FIXME: jitter around @@ -4387,384 +3636,315 @@ static void PM_CorrectAllSolid( void ) { pml.walking = qfalse; } -qboolean FlyingCreature( gentity_t *ent ) -{ - if ( ent->client->ps.gravity <= 0 && (ent->svFlags&SVF_CUSTOM_GRAVITY) ) - { +qboolean FlyingCreature(gentity_t *ent) { + if (ent->client->ps.gravity <= 0 && (ent->svFlags & SVF_CUSTOM_GRAVITY)) { return qtrue; } return qfalse; } -qboolean PM_RocketeersAvoidDangerousFalls( void ) -{ - if ( pm->gent->NPC - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT||pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) ) - {//fixme: fall through if jetpack broken? - if ( JET_Flying( pm->gent ) ) - { - if ( pm->gent->client->NPC_class == CLASS_BOBAFETT ) - { +qboolean PM_RocketeersAvoidDangerousFalls(void) { + if (pm->gent->NPC && pm->gent->client && + (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER)) { // fixme: fall through if jetpack broken? + if (JET_Flying(pm->gent)) { + if (pm->gent->client->NPC_class == CLASS_BOBAFETT) { pm->gent->client->jetPackTime = level.time + 2000; - //Wait, what if the effect is already playing, how do we know??? - //G_PlayEffect( G_EffectIndex( "boba/jetSP" ), pm->gent->playerModel, pm->gent->genericBolt1, pm->gent->s.number, pm->gent->currentOrigin, pm->gent->client->jetPackTime-level.time ); - } - else - { + // Wait, what if the effect is already playing, how do we know??? + // G_PlayEffect( G_EffectIndex( "boba/jetSP" ), pm->gent->playerModel, pm->gent->genericBolt1, pm->gent->s.number, pm->gent->currentOrigin, + // pm->gent->client->jetPackTime-level.time ); + } else { pm->gent->client->jetPackTime = Q3_INFINITE; } - } - else - { - TIMER_Set( pm->gent, "jetRecharge", 0 ); - JET_FlyStart( pm->gent ); + } else { + TIMER_Set(pm->gent, "jetRecharge", 0); + JET_FlyStart(pm->gent); } return qtrue; } return qfalse; } -static void PM_FallToDeath( void ) -{ - if ( !pm->gent ) - { +static void PM_FallToDeath(void) { + if (!pm->gent) { return; } - if ( PM_RocketeersAvoidDangerousFalls() ) - { + if (PM_RocketeersAvoidDangerousFalls()) { return; } // If this is a vehicle, more precisely an animal... - if ( pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + if (pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { Vehicle_t *pVeh = pm->gent->m_pVehicle; - pVeh->m_pVehicleInfo->EjectAll( pVeh ); - } - else - { - if ( PM_HasAnimation( pm->gent, BOTH_FALLDEATH1 ) ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_FALLDEATH1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_DEATH1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + pVeh->m_pVehicleInfo->EjectAll(pVeh); + } else { + if (PM_HasAnimation(pm->gent, BOTH_FALLDEATH1)) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - G_SoundOnEnt( pm->gent, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN + G_SoundOnEnt(pm->gent, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN } - if ( pm->gent->NPC ) - { + if (pm->gent->NPC) { pm->gent->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; pm->gent->NPC->nextBStateThink = Q3_INFINITE; } pm->ps->friction = 1; } -int PM_ForceJumpAnimForJumpAnim( int anim ) -{ - switch( anim ) - { - case BOTH_JUMP1: //# Jump - wind-up and leave ground - anim = BOTH_FORCEJUMP1; //# Jump - wind-up and leave ground +int PM_ForceJumpAnimForJumpAnim(int anim) { + switch (anim) { + case BOTH_JUMP1: //# Jump - wind-up and leave ground + anim = BOTH_FORCEJUMP1; //# Jump - wind-up and leave ground break; - case BOTH_INAIR1: //# In air loop (from jump) - anim = BOTH_FORCEINAIR1; //# In air loop (from jump) + case BOTH_INAIR1: //# In air loop (from jump) + anim = BOTH_FORCEINAIR1; //# In air loop (from jump) break; - case BOTH_LAND1: //# Landing (from in air loop) - anim = BOTH_FORCELAND1; //# Landing (from in air loop) + case BOTH_LAND1: //# Landing (from in air loop) + anim = BOTH_FORCELAND1; //# Landing (from in air loop) break; case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground - anim = BOTH_FORCEJUMPBACK1; //# Jump backwards - wind-up and leave ground + anim = BOTH_FORCEJUMPBACK1; //# Jump backwards - wind-up and leave ground break; - case BOTH_INAIRBACK1: //# In air loop (from jump back) - anim = BOTH_FORCEINAIRBACK1; //# In air loop (from jump back) + case BOTH_INAIRBACK1: //# In air loop (from jump back) + anim = BOTH_FORCEINAIRBACK1; //# In air loop (from jump back) break; case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - anim = BOTH_FORCELANDBACK1; //# Landing backwards(from in air loop) + anim = BOTH_FORCELANDBACK1; //# Landing backwards(from in air loop) break; case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground - anim = BOTH_FORCEJUMPLEFT1; //# Jump left - wind-up and leave ground + anim = BOTH_FORCEJUMPLEFT1; //# Jump left - wind-up and leave ground break; - case BOTH_INAIRLEFT1: //# In air loop (from jump left) - anim = BOTH_FORCEINAIRLEFT1; //# In air loop (from jump left) + case BOTH_INAIRLEFT1: //# In air loop (from jump left) + anim = BOTH_FORCEINAIRLEFT1; //# In air loop (from jump left) break; case BOTH_LANDLEFT1: //# Landing left(from in air loop) - anim = BOTH_FORCELANDLEFT1; //# Landing left(from in air loop) + anim = BOTH_FORCELANDLEFT1; //# Landing left(from in air loop) break; - case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground - anim = BOTH_FORCEJUMPRIGHT1; //# Jump right - wind-up and leave ground + case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground + anim = BOTH_FORCEJUMPRIGHT1; //# Jump right - wind-up and leave ground break; - case BOTH_INAIRRIGHT1: //# In air loop (from jump right) - anim = BOTH_FORCEINAIRRIGHT1; //# In air loop (from jump right) + case BOTH_INAIRRIGHT1: //# In air loop (from jump right) + anim = BOTH_FORCEINAIRRIGHT1; //# In air loop (from jump right) break; - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - anim = BOTH_FORCELANDRIGHT1; //# Landing right(from in air loop) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + anim = BOTH_FORCELANDRIGHT1; //# Landing right(from in air loop) break; } return anim; } -static void PM_SetVehicleAngles( vec3_t normal ) -{ - if ( !pm->gent->client || pm->gent->client->NPC_class != CLASS_VEHICLE ) +static void PM_SetVehicleAngles(vec3_t normal) { + if (!pm->gent->client || pm->gent->client->NPC_class != CLASS_VEHICLE) return; Vehicle_t *pVeh = pm->gent->m_pVehicle; - //float curVehicleBankingSpeed; - float vehicleBankingSpeed = pVeh->m_pVehicleInfo->bankingSpeed;//0.25f - vec3_t vAngles; + // float curVehicleBankingSpeed; + float vehicleBankingSpeed = pVeh->m_pVehicleInfo->bankingSpeed; // 0.25f + vec3_t vAngles; - if ( vehicleBankingSpeed <= 0 - || ( pVeh->m_pVehicleInfo->pitchLimit <= 0 && pVeh->m_pVehicleInfo->rollLimit <= 0 ) ) - {//don't bother, this vehicle doesn't bank + if (vehicleBankingSpeed <= 0 || (pVeh->m_pVehicleInfo->pitchLimit <= 0 && pVeh->m_pVehicleInfo->rollLimit <= 0)) { // don't bother, this vehicle doesn't + // bank return; } - //FIXME: do 3 traces to define a plane and use that... smoothes it out some, too... - //pitch_roll_for_slope( pm->gent, normal, vAngles ); - //FIXME: maybe have some pitch control in water and/or air? + // FIXME: do 3 traces to define a plane and use that... smoothes it out some, too... + // pitch_roll_for_slope( pm->gent, normal, vAngles ); + // FIXME: maybe have some pitch control in water and/or air? - //center of gravity affects pitch in air/water (FIXME: what about roll?) - //float pitchBias = 90.0f*pVeh->m_pVehicleInfo->centerOfGravity[0];//if centerOfGravity is all the way back (-1.0f), vehicle pitches up 90 degrees when in air + // center of gravity affects pitch in air/water (FIXME: what about roll?) + // float pitchBias = 90.0f*pVeh->m_pVehicleInfo->centerOfGravity[0];//if centerOfGravity is all the way back (-1.0f), vehicle pitches up 90 degrees when in + // air - VectorClear( vAngles ); + VectorClear(vAngles); - - if (pm->waterlevel>0 || (normal && (pml.groundTrace.contents&(CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)))) - {//in water - // vAngles[PITCH] += (pm->ps->viewangles[PITCH]-vAngles[PITCH])*0.75f + (pitchBias*0.5); - } - else if ( normal ) - {//have a valid surface below me - pitch_roll_for_slope( pm->gent, normal, vAngles ); + if (pm->waterlevel > 0 || (normal && (pml.groundTrace.contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)))) { // in water + // vAngles[PITCH] += (pm->ps->viewangles[PITCH]-vAngles[PITCH])*0.75f + (pitchBias*0.5); + } else if (normal) { // have a valid surface below me + pitch_roll_for_slope(pm->gent, normal, vAngles); float deltaPitch = (vAngles[PITCH] - pVeh->m_vOrientation[PITCH]); - if (deltaPitch< -10.0f) - { + if (deltaPitch < -10.0f) { vAngles[PITCH] = pVeh->m_vOrientation[PITCH] - 10.0f; - } - else if (deltaPitch>10.0f) - { + } else if (deltaPitch > 10.0f) { vAngles[PITCH] = pVeh->m_vOrientation[PITCH] + 10.0f; } - } - else - {//in air, let pitch match view...? - //FIXME: take center of gravity into account - vAngles[PITCH] = pVeh->m_vOrientation[PITCH] - 1; - if (vAngles[PITCH]<-15) - { - vAngles[PITCH]=-15; + } else { // in air, let pitch match view...? + // FIXME: take center of gravity into account + vAngles[PITCH] = pVeh->m_vOrientation[PITCH] - 1; + if (vAngles[PITCH] < -15) { + vAngles[PITCH] = -15; } - //don't bank so fast when in the air + // don't bank so fast when in the air vehicleBankingSpeed *= 0.125f; } - //NOTE: if angles are flat and we're moving through air (not on ground), + // NOTE: if angles are flat and we're moving through air (not on ground), // then pitch/bank? - if (pVeh->m_ulFlags & VEH_SPINNING) - { + if (pVeh->m_ulFlags & VEH_SPINNING) { vAngles[ROLL] = pVeh->m_vOrientation[ROLL] - 25; - } - else if (pVeh->m_ulFlags & VEH_OUTOFCONTROL) - { - //vAngles[ROLL] = pVeh->m_vOrientation[ROLL] + 5; - } - else if ( pVeh->m_pVehicleInfo->rollLimit > 0 ) - { - //roll when banking - vec3_t velocity; - float speed; - VectorCopy( pm->ps->velocity, velocity ); - speed = VectorNormalize( velocity ); - if ( speed>0.01f ) - { - vec3_t rt, tempVAngles; - float side, dotp; - - - VectorCopy( pVeh->m_vOrientation, tempVAngles ); + } else if (pVeh->m_ulFlags & VEH_OUTOFCONTROL) { + // vAngles[ROLL] = pVeh->m_vOrientation[ROLL] + 5; + } else if (pVeh->m_pVehicleInfo->rollLimit > 0) { + // roll when banking + vec3_t velocity; + float speed; + VectorCopy(pm->ps->velocity, velocity); + speed = VectorNormalize(velocity); + if (speed > 0.01f) { + vec3_t rt, tempVAngles; + float side, dotp; + + VectorCopy(pVeh->m_vOrientation, tempVAngles); tempVAngles[ROLL] = 0; - AngleVectors( tempVAngles, NULL, rt, NULL ); - dotp = DotProduct( velocity, rt ); - //if (fabsf(dotp)>0.5f) + AngleVectors(tempVAngles, NULL, rt, NULL); + dotp = DotProduct(velocity, rt); + // if (fabsf(dotp)>0.5f) { speed *= dotp; - // Magic number fun! Speed is used for banking, so modulate the speed by a sine wave - //FIXME: this banks too early - //speed *= sin( (150 + pml.frametime) * 0.003 ); - if (level.time < pVeh->m_iTurboTime) - { + // FIXME: this banks too early + // speed *= sin( (150 + pml.frametime) * 0.003 ); + if (level.time < pVeh->m_iTurboTime) { speed /= pVeh->m_pVehicleInfo->turboSpeed; - } - else - { + } else { speed /= pVeh->m_pVehicleInfo->speedMax; } - /// if (pm->cmd.forwardmove==0) - // { - // speed *= 0.5; - // } - // if (pm->cmd.forwardmove<0) - // { - // speed *= 0.1f; - // } - if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) - { + /// if (pm->cmd.forwardmove==0) + // { + // speed *= 0.5; + // } + // if (pm->cmd.forwardmove<0) + // { + // speed *= 0.1f; + // } + if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) { speed *= 3.0f; } + side = speed * 75.0f; + // if (pVeh->m_ulFlags & VEH_STRAFERAM) + // { + // vAngles[ROLL] += side; + // } + // else + { vAngles[ROLL] -= side; } - side = speed * 75.0f; - // if (pVeh->m_ulFlags & VEH_STRAFERAM) - // { - // vAngles[ROLL] += side; - // } - // else - { - vAngles[ROLL] -= side; - } - - //gi.Printf("VAngles(%f)", vAngles[2]); + // gi.Printf("VAngles(%f)", vAngles[2]); } - if (fabsf(vAngles[ROLL])<0.001f) - { + if (fabsf(vAngles[ROLL]) < 0.001f) { vAngles[ROLL] = 0.0f; } } } - //cap - if ( vAngles[PITCH] > pVeh->m_pVehicleInfo->pitchLimit ) - { + // cap + if (vAngles[PITCH] > pVeh->m_pVehicleInfo->pitchLimit) { vAngles[PITCH] = pVeh->m_pVehicleInfo->pitchLimit; - } - else if ( vAngles[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit ) - { + } else if (vAngles[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit) { vAngles[PITCH] = -pVeh->m_pVehicleInfo->pitchLimit; } - if (!(pVeh->m_ulFlags & VEH_SPINNING)) - { - if ( vAngles[ROLL] > pVeh->m_pVehicleInfo->rollLimit ) - { + if (!(pVeh->m_ulFlags & VEH_SPINNING)) { + if (vAngles[ROLL] > pVeh->m_pVehicleInfo->rollLimit) { vAngles[ROLL] = pVeh->m_pVehicleInfo->rollLimit; - } - else if ( vAngles[ROLL] < -pVeh->m_pVehicleInfo->rollLimit ) - { + } else if (vAngles[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) { vAngles[ROLL] = -pVeh->m_pVehicleInfo->rollLimit; } } - //do it - for ( int i = 0; i < 3; i++ ) - { - if ( i == YAW ) - {//yawing done elsewhere + // do it + for (int i = 0; i < 3; i++) { + if (i == YAW) { // yawing done elsewhere continue; } - if ( i == ROLL && pVeh->m_ulFlags & VEH_STRAFERAM) - {//during strafe ram, roll is done elsewhere + if (i == ROLL && pVeh->m_ulFlags & VEH_STRAFERAM) { // during strafe ram, roll is done elsewhere continue; } - //bank faster the higher the difference is + // bank faster the higher the difference is /* else if ( i == PITCH ) { - curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[PITCH], pVeh->m_vOrientation[PITCH] )))/(g_vehicleInfo[pm->ps->vehicleIndex].pitchLimit/2.0f); + curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[PITCH], pVeh->m_vOrientation[PITCH] + )))/(g_vehicleInfo[pm->ps->vehicleIndex].pitchLimit/2.0f); } else if ( i == ROLL ) { - curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[ROLL], pVeh->m_vOrientation[ROLL] )))/(g_vehicleInfo[pm->ps->vehicleIndex].rollLimit/2.0f); + curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[ROLL], pVeh->m_vOrientation[ROLL] + )))/(g_vehicleInfo[pm->ps->vehicleIndex].rollLimit/2.0f); } if ( curVehicleBankingSpeed ) */ { - // if ( pVeh->m_vOrientation[i] >= vAngles[i] + vehicleBankingSpeed ) - // { - // pVeh->m_vOrientation[i] -= vehicleBankingSpeed; - // } - // else if ( pVeh->m_vOrientation[i] <= vAngles[i] - vehicleBankingSpeed ) - // { - // pVeh->m_vOrientation[i] += vehicleBankingSpeed; - // } - // else - { - pVeh->m_vOrientation[i] = vAngles[i]; - } - } - } - //gi.Printf("Orientation(%f)", pVeh->m_vOrientation[2]); -} - -void BG_ExternThisSoICanRecompileInDebug( Vehicle_t *pVeh, playerState_t *riderPS ) -{/* - float pitchSubtract, pitchDelta, yawDelta; - //Com_Printf( S_COLOR_RED"PITCH: %4.2f, YAW: %4.2f, ROLL: %4.2f\n", riderPS->viewangles[0],riderPS->viewangles[1],riderPS->viewangles[2]); - yawDelta = AngleSubtract(riderPS->viewangles[YAW],pVeh->m_vPrevRiderViewAngles[YAW]); -#ifndef QAGAME - if ( !cg_paused.integer ) - { - //Com_Printf( "%d - yawDelta %4.2f\n", pm->cmd.serverTime, yawDelta ); - } -#endif - yawDelta *= (4.0f*pVeh->m_fTimeModifier); - pVeh->m_vOrientation[ROLL] -= yawDelta; - - pitchDelta = AngleSubtract(riderPS->viewangles[PITCH],pVeh->m_vPrevRiderViewAngles[PITCH]); - pitchDelta *= (2.0f*pVeh->m_fTimeModifier); - pitchSubtract = pitchDelta * (fabs(pVeh->m_vOrientation[ROLL])/90.0f); - pVeh->m_vOrientation[PITCH] += pitchDelta-pitchSubtract; - if ( pVeh->m_vOrientation[ROLL] > 0 ) - { - pVeh->m_vOrientation[YAW] += pitchSubtract; - } - else - { - pVeh->m_vOrientation[YAW] -= pitchSubtract; - } - pVeh->m_vOrientation[PITCH] = AngleNormalize180( pVeh->m_vOrientation[PITCH] ); - pVeh->m_vOrientation[YAW] = AngleNormalize360( pVeh->m_vOrientation[YAW] ); - pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); - - VectorCopy( riderPS->viewangles, pVeh->m_vPrevRiderViewAngles );*/ -} - -void BG_VehicleTurnRateForSpeed( Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride ) -{ - if ( pVeh && pVeh->m_pVehicleInfo ) - { + // if ( pVeh->m_vOrientation[i] >= vAngles[i] + vehicleBankingSpeed ) + // { + // pVeh->m_vOrientation[i] -= vehicleBankingSpeed; + // } + // else if ( pVeh->m_vOrientation[i] <= vAngles[i] - vehicleBankingSpeed ) + // { + // pVeh->m_vOrientation[i] += vehicleBankingSpeed; + // } + // else + { pVeh->m_vOrientation[i] = vAngles[i]; } + } + } + // gi.Printf("Orientation(%f)", pVeh->m_vOrientation[2]); +} + +void BG_ExternThisSoICanRecompileInDebug( + Vehicle_t *pVeh, + playerState_t *riderPS) { /* + float pitchSubtract, pitchDelta, yawDelta; + //Com_Printf( S_COLOR_RED"PITCH: %4.2f, YAW: %4.2f, ROLL: %4.2f\n", + riderPS->viewangles[0],riderPS->viewangles[1],riderPS->viewangles[2]); yawDelta = + AngleSubtract(riderPS->viewangles[YAW],pVeh->m_vPrevRiderViewAngles[YAW]); #ifndef QAGAME if ( !cg_paused.integer ) + { + //Com_Printf( "%d - yawDelta %4.2f\n", pm->cmd.serverTime, yawDelta ); + } + #endif + yawDelta *= (4.0f*pVeh->m_fTimeModifier); + pVeh->m_vOrientation[ROLL] -= yawDelta; + + pitchDelta = AngleSubtract(riderPS->viewangles[PITCH],pVeh->m_vPrevRiderViewAngles[PITCH]); + pitchDelta *= (2.0f*pVeh->m_fTimeModifier); + pitchSubtract = pitchDelta * (fabs(pVeh->m_vOrientation[ROLL])/90.0f); + pVeh->m_vOrientation[PITCH] += pitchDelta-pitchSubtract; + if ( pVeh->m_vOrientation[ROLL] > 0 ) + { + pVeh->m_vOrientation[YAW] += pitchSubtract; + } + else + { + pVeh->m_vOrientation[YAW] -= pitchSubtract; + } + pVeh->m_vOrientation[PITCH] = AngleNormalize180( pVeh->m_vOrientation[PITCH] ); + pVeh->m_vOrientation[YAW] = AngleNormalize360( pVeh->m_vOrientation[YAW] ); + pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); + + VectorCopy( riderPS->viewangles, pVeh->m_vPrevRiderViewAngles );*/ +} + +void BG_VehicleTurnRateForSpeed(Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride) { + if (pVeh && pVeh->m_pVehicleInfo) { float speedFrac = 1.0f; - if ( pVeh->m_pVehicleInfo->speedDependantTurning ) - { - if ( pVeh->m_LandTrace.fraction >= 1.0f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - { - speedFrac = (speed/(pVeh->m_pVehicleInfo->speedMax*0.75f)); - if ( speedFrac < 0.25f ) - { + if (pVeh->m_pVehicleInfo->speedDependantTurning) { + if (pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { + speedFrac = (speed / (pVeh->m_pVehicleInfo->speedMax * 0.75f)); + if (speedFrac < 0.25f) { speedFrac = 0.25f; - } - else if ( speedFrac > 1.0f ) - { + } else if (speedFrac > 1.0f) { speedFrac = 1.0f; } } } - if ( pVeh->m_pVehicleInfo->mousePitch ) - { - *mPitchOverride = pVeh->m_pVehicleInfo->mousePitch*speedFrac; + if (pVeh->m_pVehicleInfo->mousePitch) { + *mPitchOverride = pVeh->m_pVehicleInfo->mousePitch * speedFrac; } - if ( pVeh->m_pVehicleInfo->mouseYaw ) - { - *mYawOverride = pVeh->m_pVehicleInfo->mouseYaw*speedFrac; + if (pVeh->m_pVehicleInfo->mouseYaw) { + *mYawOverride = pVeh->m_pVehicleInfo->mouseYaw * speedFrac; } } } @@ -4775,136 +3955,118 @@ PM_GroundTraceMissed The ground trace didn't hit a surface, so we are in freefall ============= */ -static void PM_GroundTraceMissed( void ) { - trace_t trace; - vec3_t point; - qboolean cliff_fall = qfalse; - - if ( Flying != FLY_HOVER ) - { - if ( !(pm->ps->eFlags&EF_FORCE_DRAINED) ) - { - //FIXME: if in a contents_falldeath brush, play the falling death anim and sound? - if ( pm->ps->clientNum != 0 && pm->gent && pm->gent->NPC && pm->gent->client && pm->gent->client->NPC_class != CLASS_DESANN )//desann never falls to his death - { - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { - if ( pm->ps->stats[STAT_HEALTH] > 0 - && !(pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) - && !(pm->gent->NPC->aiFlags&NPCAI_JUMP) // doing a path jump - && !(pm->gent->NPC->scriptFlags&SCF_NO_FALLTODEATH) - && pm->gent->NPC->behaviorState != BS_JUMP )//not being scripted to jump +static void PM_GroundTraceMissed(void) { + trace_t trace; + vec3_t point; + qboolean cliff_fall = qfalse; + + if (Flying != FLY_HOVER) { + if (!(pm->ps->eFlags & EF_FORCE_DRAINED)) { + // FIXME: if in a contents_falldeath brush, play the falling death anim and sound? + if (pm->ps->clientNum != 0 && pm->gent && pm->gent->NPC && pm->gent->client && + pm->gent->client->NPC_class != CLASS_DESANN) // desann never falls to his death + { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { + if (pm->ps->stats[STAT_HEALTH] > 0 && !(pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT) && + !(pm->gent->NPC->aiFlags & NPCAI_JUMP) // doing a path jump + && !(pm->gent->NPC->scriptFlags & SCF_NO_FALLTODEATH) && pm->gent->NPC->behaviorState != BS_JUMP) // not being scripted to jump { - if ( (level.time - pm->gent->client->respawnTime > 2000)//been in the world for at least 2 seconds - && (!pm->gent->NPC->timeOfDeath || level.time - pm->gent->NPC->timeOfDeath < 1000) && pm->gent->e_ThinkFunc != thinkF_NPC_RemoveBody //Have to do this now because timeOfDeath is used by thinkF_NPC_RemoveBody to debounce removal checks - && !(pm->gent->client->ps.forcePowersActive&(1<gent ) - && g_gravity->value > 0 ) - { - if ( !(pm->gent->flags&FL_UNDYING) - && !(pm->gent->flags&FL_GODMODE) ) - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) - && !(pm->ps->eFlags&EF_FORCE_DRAINED) - && !(pm->ps->pm_flags&PMF_TRIGGER_PUSHED) ) - { - if ( !pm->ps->forceJumpZStart || pm->ps->forceJumpZStart > pm->ps->origin[2] )// && fabs(pm->ps->velocity[0])<10 && fabs(pm->ps->velocity[1])<10 && pm->ps->velocity[2]<0)//either not force-jumping or force-jumped and now fell below original jump start height + if ((level.time - pm->gent->client->respawnTime > 2000) // been in the world for at least 2 seconds + && (!pm->gent->NPC->timeOfDeath || level.time - pm->gent->NPC->timeOfDeath < 1000) && + pm->gent->e_ThinkFunc != + thinkF_NPC_RemoveBody // Have to do this now because timeOfDeath is used by thinkF_NPC_RemoveBody to debounce removal checks + && !(pm->gent->client->ps.forcePowersActive & (1 << FP_LEVITATION))) { + if (!FlyingCreature(pm->gent) && g_gravity->value > 0) { + if (!(pm->gent->flags & FL_UNDYING) && !(pm->gent->flags & FL_GODMODE)) { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED) && !(pm->ps->eFlags & EF_FORCE_DRAINED) && + !(pm->ps->pm_flags & PMF_TRIGGER_PUSHED)) { + if (!pm->ps->forceJumpZStart || + pm->ps->forceJumpZStart > pm->ps->origin[2]) // && fabs(pm->ps->velocity[0])<10 && fabs(pm->ps->velocity[1])<10 && + // pm->ps->velocity[2]<0)//either not force-jumping or force-jumped and + // now fell below original jump start height { /*if ( pm->ps->legsAnim = BOTH_FALLDEATH1 && pm->ps->legsAnim != BOTH_DEATH1 && PM_HasAnimation( pm->gent, BOTH_FALLDEATH1 )*/ - //New method: predict impact, 400 ahead - vec3_t vel; - float time; - - VectorCopy( pm->ps->velocity, vel ); - float speed = VectorLength( vel ); - if ( !speed ) - {//damn divide by zero + // New method: predict impact, 400 ahead + vec3_t vel; + float time; + + VectorCopy(pm->ps->velocity, vel); + float speed = VectorLength(vel); + if (!speed) { // damn divide by zero speed = 1; } - time = 400/speed; + time = 400 / speed; vel[2] -= 0.5 * time * pm->ps->gravity; - speed = VectorLength( vel ); - if ( !speed ) - {//damn divide by zero + speed = VectorLength(vel); + if (!speed) { // damn divide by zero speed = 1; } - time = 400/speed; - VectorScale( vel, time, vel ); - VectorAdd( pm->ps->origin, vel, point ); + time = 400 / speed; + VectorScale(vel, time, vel); + VectorAdd(pm->ps->origin, vel, point); - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); - if ( (trace.contents&CONTENTS_LAVA) - && PM_RocketeersAvoidDangerousFalls() ) - {//got out of it - } - else if ( !trace.allsolid && !trace.startsolid && (pm->ps->origin[2] - trace.endpos[2]) >= 128 )//>=128 so we don't die on steps! + if ((trace.contents & CONTENTS_LAVA) && PM_RocketeersAvoidDangerousFalls()) { // got out of it + } else if (!trace.allsolid && !trace.startsolid && + (pm->ps->origin[2] - trace.endpos[2]) >= 128) //>=128 so we don't die on steps! { - if ( trace.fraction == 1.0 ) - {//didn't hit, we're probably going to die - if ( pm->ps->velocity[2] < 0 && pm->ps->origin[2] - point[2] > 256 ) - {//going down, into a bottomless pit, apparently + if (trace.fraction == 1.0) { // didn't hit, we're probably going to die + if (pm->ps->velocity[2] < 0 && + pm->ps->origin[2] - point[2] > 256) { // going down, into a bottomless pit, apparently PM_FallToDeath(); cliff_fall = qtrue; } - } - else if ( trace.entityNum < ENTITYNUM_NONE - && pm->ps->weapon != WP_SABER - && (!pm->gent || !pm->gent->client || (pm->gent->client->NPC_class != CLASS_BOBAFETT&&pm->gent->client->NPC_class!=CLASS_REBORN&&pm->gent->client->NPC_class!=CLASS_ROCKETTROOPER)) ) - {//Jedi don't scream and die if they're heading for a hard impact + } else if (trace.entityNum < ENTITYNUM_NONE && pm->ps->weapon != WP_SABER && + (!pm->gent || !pm->gent->client || + (pm->gent->client->NPC_class != CLASS_BOBAFETT && pm->gent->client->NPC_class != CLASS_REBORN && + pm->gent->client->NPC_class != + CLASS_ROCKETTROOPER))) { // Jedi don't scream and die if they're heading for a hard impact gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.entityNum == ENTITYNUM_WORLD || (traceEnt && traceEnt->bmodel) ) - {//hit architecture, find impact force - float dmg; + if (trace.entityNum == ENTITYNUM_WORLD || + (traceEnt && traceEnt->bmodel)) { // hit architecture, find impact force + float dmg; - VectorCopy( pm->ps->velocity, vel ); - time = Distance( trace.endpos, pm->ps->origin )/VectorLength( vel ); + VectorCopy(pm->ps->velocity, vel); + time = Distance(trace.endpos, pm->ps->origin) / VectorLength(vel); vel[2] -= 0.5 * time * pm->ps->gravity; - if ( trace.plane.normal[2] > 0.5 ) - {//use falling damage - int waterlevel, junk; - PM_SetWaterLevelAtPoint( trace.endpos, &waterlevel, &junk ); - dmg = PM_CrashLandDelta( vel, waterlevel ); - if ( dmg >= 30 ) - {//there is a minimum fall threshhold - dmg = PM_DamageForDelta( dmg ); - } - else - { + if (trace.plane.normal[2] > 0.5) { // use falling damage + int waterlevel, junk; + PM_SetWaterLevelAtPoint(trace.endpos, &waterlevel, &junk); + dmg = PM_CrashLandDelta(vel, waterlevel); + if (dmg >= 30) { // there is a minimum fall threshhold + dmg = PM_DamageForDelta(dmg); + } else { dmg = 0; } - } - else - {//use impact damage - //guestimate - if ( pm->gent->client && pm->gent->client->ps.forceJumpZStart ) - {//we were force-jumping - if ( pm->gent->currentOrigin[2] >= pm->gent->client->ps.forceJumpZStart ) - {//we landed at same height or higher than we landed + } else { // use impact damage + // guestimate + if (pm->gent->client && pm->gent->client->ps.forceJumpZStart) { // we were force-jumping + if (pm->gent->currentOrigin[2] >= + pm->gent->client->ps.forceJumpZStart) { // we landed at same height or higher than we landed dmg = 0; - } - else - {//FIXME: take off some of it, at least? - dmg = (pm->gent->client->ps.forceJumpZStart-pm->gent->currentOrigin[2])/3; + } else { // FIXME: take off some of it, at least? + dmg = (pm->gent->client->ps.forceJumpZStart - pm->gent->currentOrigin[2]) / 3; } } - dmg = 10 * VectorLength( pm->ps->velocity ); - if ( pm->ps->clientNum < MAX_CLIENTS ) - { + dmg = 10 * VectorLength(pm->ps->velocity); + if (pm->ps->clientNum < MAX_CLIENTS) { dmg /= 2; } - dmg *= 0.01875f;//magic number + dmg *= 0.01875f; // magic number } - float maxDmg = pm->ps->stats[STAT_HEALTH]>20?pm->ps->stats[STAT_HEALTH]:20;//a fall that would do less than 20 points of damage should never make us scream to our deaths - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_HOWLER ) - {//howlers can survive long falls, despire their health + float maxDmg = pm->ps->stats[STAT_HEALTH] > 20 ? pm->ps->stats[STAT_HEALTH] + : 20; // a fall that would do less than 20 points of + // damage should never make us scream to our deaths + if (pm->gent && pm->gent->client && + pm->gent->client->NPC_class == + CLASS_HOWLER) { // howlers can survive long falls, despire their health maxDmg *= 5; } - if ( dmg >= pm->ps->stats[STAT_HEALTH] )//armor? + if (dmg >= pm->ps->stats[STAT_HEALTH]) // armor? { PM_FallToDeath(); cliff_fall = qtrue; @@ -4916,9 +4078,9 @@ static void PM_GroundTraceMissed( void ) { /* vec3_t start; //okay, kind of expensive temp hack here, but let's check to see if we should scream - //FIXME: we should either do a better check (predict using actual velocity) or we should wait until they've been over a bottomless pit for a certain amount of time... - VectorCopy( pm->ps->origin, start ); - if ( pm->ps->forceJumpZStart < start[2] ) + //FIXME: we should either do a better check (predict using actual velocity) or we should wait until they've been + over a bottomless pit for a certain amount of time... VectorCopy( pm->ps->origin, start ); if ( + pm->ps->forceJumpZStart < start[2] ) {//Jedi who are force-jumping should only do this from landing point down? start[2] = pm->ps->forceJumpZStart; } @@ -4940,173 +4102,109 @@ static void PM_GroundTraceMissed( void ) { } } } - if ( !cliff_fall ) - { - if ( pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START - || pm->ps->legsAnim == BOTH_FLIP_LAND ) - {//let it stay on this anim - } - else if ( PM_KnockDownAnimExtended( pm->ps->legsAnim ) ) - {//no in-air anims when in knockdown anim - } - else if ( ( pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_FLIP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_FLIP - || pm->ps->legsAnim == BOTH_WALL_FLIP_RIGHT - || pm->ps->legsAnim == BOTH_WALL_FLIP_LEFT - || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_FORWARD - || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_LEFT - || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_BACK - || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_RIGHT - || pm->ps->legsAnim == BOTH_CEILING_DROP ) - && !pm->ps->legsAnimTimer ) - {//if flip anim is done, okay to use inair - PM_SetAnim( pm, SETANIM_LEGS, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE, 350 ); // Only blend over 100ms - } - else if ( pm->ps->legsAnim == BOTH_FLIP_ATTACK7 - || pm->ps->legsAnim == BOTH_FLIP_HOLD7 ) - { - if ( !pm->ps->legsAnimTimer ) - {//done? - PM_SetAnim( pm, SETANIM_BOTH, BOTH_FLIP_HOLD7, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 350 ); // Only blend over 100ms - } - } - else if ( PM_InCartwheel( pm->ps->legsAnim ) ) - { - if ( pm->ps->legsAnimTimer > 0 ) - {//still playing on bottom - } - else - { - PM_SetAnim( pm, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_NORMAL, 350 ); - } - } - else if ( PM_InAirKickingAnim( pm->ps->legsAnim ) ) - { - if ( pm->ps->legsAnimTimer > 0 ) - {//still playing on bottom - } - else - { - PM_SetAnim( pm, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_NORMAL, 350 ); + if (!cliff_fall) { + if (pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK || + pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START || pm->ps->legsAnim == BOTH_FLIP_LAND) { // let it stay on this anim + } else if (PM_KnockDownAnimExtended(pm->ps->legsAnim)) { // no in-air anims when in knockdown anim + } else if ((pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_FLIP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_FLIP || pm->ps->legsAnim == BOTH_WALL_FLIP_RIGHT || + pm->ps->legsAnim == BOTH_WALL_FLIP_LEFT || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_FORWARD || + pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_LEFT || pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_BACK || + pm->ps->legsAnim == BOTH_FORCEWALLREBOUND_RIGHT || pm->ps->legsAnim == BOTH_CEILING_DROP) && + !pm->ps->legsAnimTimer) { // if flip anim is done, okay to use inair + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE, 350); // Only blend over 100ms + } else if (pm->ps->legsAnim == BOTH_FLIP_ATTACK7 || pm->ps->legsAnim == BOTH_FLIP_HOLD7) { + if (!pm->ps->legsAnimTimer) { // done? + PM_SetAnim(pm, SETANIM_BOTH, BOTH_FLIP_HOLD7, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 350); // Only blend over 100ms + } + } else if (PM_InCartwheel(pm->ps->legsAnim)) { + if (pm->ps->legsAnimTimer > 0) { // still playing on bottom + } else { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_NORMAL, 350); + } + } else if (PM_InAirKickingAnim(pm->ps->legsAnim)) { + if (pm->ps->legsAnimTimer > 0) { // still playing on bottom + } else { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_NORMAL, 350); pm->ps->saberMove = LS_READY; pm->ps->weaponTime = 0; } - } - else if ( !PM_InRoll( pm->ps ) - && !PM_SpinningAnim( pm->ps->legsAnim ) - && !PM_FlippingAnim( pm->ps->legsAnim ) - && !PM_InSpecialJump( pm->ps->legsAnim ) ) - { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { + } else if (!PM_InRoll(pm->ps) && !PM_SpinningAnim(pm->ps->legsAnim) && !PM_FlippingAnim(pm->ps->legsAnim) && + !PM_InSpecialJump(pm->ps->legsAnim)) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // we just transitioned into freefall - if ( pm->debugLevel ) - { + if (pm->debugLevel) { Com_Printf("%i:lift\n", c_pmove); } // if they aren't in a jumping animation and the ground is a ways away, force into it // if we didn't do the trace, the player would be backflipping down staircases - VectorCopy( pm->ps->origin, point ); + VectorCopy(pm->ps->origin, point); point[2] -= 64; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); - if ( trace.fraction == 1.0 ) - {//FIXME: if velocity[2] < 0 and didn't jump, use some falling anim - if ( pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags&PMF_JUMP_HELD)) - { - if(!PM_InDeathAnim()) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (trace.fraction == 1.0) { // FIXME: if velocity[2] < 0 and didn't jump, use some falling anim + if (pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags & PMF_JUMP_HELD)) { + if (!PM_InDeathAnim()) { // If we're a vehicle, set our falling flag. - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { // We're flying in the air. - if ( pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + if (pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { pm->gent->m_pVehicle->m_ulFlags |= VEH_FLYING; } - } - else - { - vec3_t moveDir, lookAngles, lookDir, lookRight; - int anim = BOTH_INAIR1; + } else { + vec3_t moveDir, lookAngles, lookDir, lookRight; + int anim = BOTH_INAIR1; - VectorCopy( pm->ps->velocity, moveDir ); + VectorCopy(pm->ps->velocity, moveDir); moveDir[2] = 0; - VectorNormalize( moveDir ); + VectorNormalize(moveDir); - VectorCopy( pm->ps->viewangles, lookAngles ); + VectorCopy(pm->ps->viewangles, lookAngles); lookAngles[PITCH] = lookAngles[ROLL] = 0; - AngleVectors( lookAngles, lookDir, lookRight, NULL ); + AngleVectors(lookAngles, lookDir, lookRight, NULL); - float dot = DotProduct( moveDir, lookDir ); - if ( dot > 0.5 ) - {//redundant + float dot = DotProduct(moveDir, lookDir); + if (dot > 0.5) { // redundant anim = BOTH_INAIR1; - } - else if ( dot < -0.5 ) - { + } else if (dot < -0.5) { anim = BOTH_INAIRBACK1; - } - else - { - dot = DotProduct( moveDir, lookRight ); - if ( dot > 0.5 ) - { + } else { + dot = DotProduct(moveDir, lookRight); + if (dot > 0.5) { anim = BOTH_INAIRRIGHT1; - } - else if ( dot < -0.5 ) - { + } else if (dot < -0.5) { anim = BOTH_INAIRLEFT1; - } - else - {//redundant + } else { // redundant anim = BOTH_INAIR1; } } - if ( pm->ps->forcePowersActive & ( 1 << FP_LEVITATION ) ) - { - anim = PM_ForceJumpAnimForJumpAnim( anim ); + if (pm->ps->forcePowersActive & (1 << FP_LEVITATION)) { + anim = PM_ForceJumpAnimForJumpAnim(anim); } - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100 ); // Only blend over 100ms + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } } pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( !(pm->ps->forcePowersActive&(1<cmd.forwardmove >= 0 ) - { - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_JUMP1,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + } else if (!(pm->ps->forcePowersActive & (1 << FP_LEVITATION))) { + if (pm->cmd.forwardmove >= 0) { + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove < 0 ) - { - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_JUMPBACK1,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + } else if (pm->cmd.forwardmove < 0) { + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_JUMPBACK1, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; } } - } - else - { + } else { // If we're a vehicle, set our falling flag. - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { // We're on the ground. - if ( pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + if (pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { pm->gent->m_pVehicle->m_ulFlags &= ~VEH_FLYING; } } @@ -5116,8 +4214,7 @@ static void PM_GroundTraceMissed( void ) { } } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { pm->ps->jumpZStart = pm->ps->origin[2]; } } @@ -5126,22 +4223,17 @@ static void PM_GroundTraceMissed( void ) { pml.walking = qfalse; } - /* ============= PM_GroundTrace ============= */ -static void PM_GroundTrace( void ) { - vec3_t point; - trace_t trace; - - if ( (pm->ps->eFlags&EF_LOCKED_TO_WEAPON) - || (pm->ps->eFlags&EF_HELD_BY_RANCOR) - || (pm->ps->eFlags&EF_HELD_BY_WAMPA) - || (pm->ps->eFlags&EF_HELD_BY_SAND_CREATURE) - || PM_RidingVehicle() ) - { +static void PM_GroundTrace(void) { + vec3_t point; + trace_t trace; + + if ((pm->ps->eFlags & EF_LOCKED_TO_WEAPON) || (pm->ps->eFlags & EF_HELD_BY_RANCOR) || (pm->ps->eFlags & EF_HELD_BY_WAMPA) || + (pm->ps->eFlags & EF_HELD_BY_SAND_CREATURE) || PM_RidingVehicle()) { pml.groundPlane = qtrue; pml.walking = qtrue; pm->ps->groundEntityNum = ENTITYNUM_WORLD; @@ -5162,12 +4254,8 @@ static void PM_GroundTrace( void ) { pml.groundTrace.surfaceFlags = 0; */ return; - } - else if ( pm->ps->legsAnimTimer > 300 - && (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START) ) - {//wall-running forces you to be in the air + } else if (pm->ps->legsAnimTimer > 300 && (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || + pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START)) { // wall-running forces you to be in the air pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->groundEntityNum = ENTITYNUM_NONE; @@ -5175,8 +4263,7 @@ static void PM_GroundTrace( void ) { } float minNormal = (float)MIN_WALK_NORMAL; - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - {//FIXME: extern this as part of vehicle data + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { // FIXME: extern this as part of vehicle data minNormal = pm->gent->m_pVehicle->m_pVehicleInfo->maxSlope; } @@ -5184,18 +4271,17 @@ static void PM_GroundTrace( void ) { point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] - 0.25f; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); pml.groundTrace = trace; // do something corrective if the trace starts in a solid... - if ( trace.allsolid ) { + if (trace.allsolid) { PM_CorrectAllSolid(); return; } // if the trace didn't hit anything, we are in free fall - if ( trace.fraction == 1.0 || g_gravity->value <= 0 ) - { + if (trace.fraction == 1.0 || g_gravity->value <= 0) { PM_GroundTraceMissed(); pml.groundPlane = qfalse; pml.walking = qfalse; @@ -5209,40 +4295,23 @@ static void PM_GroundTrace( void ) { } // Not a vehicle and not riding one. - if ( pm->gent - && pm->gent->client - && pm->gent->client->NPC_class != CLASS_SAND_CREATURE - && (pm->gent->client->NPC_class != CLASS_VEHICLE && !PM_RidingVehicle() ) ) - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class != CLASS_SAND_CREATURE && + (pm->gent->client->NPC_class != CLASS_VEHICLE && !PM_RidingVehicle())) { // check if getting thrown off the ground - if ( ((pm->ps->velocity[2]>0&&(pm->ps->pm_flags&PMF_TIME_KNOCKBACK))||pm->ps->velocity[2]>100) && DotProduct( pm->ps->velocity, trace.plane.normal ) > 10 ) - {//either thrown off ground (PMF_TIME_KNOCKBACK) or going off the ground at a large velocity - if ( pm->debugLevel ) { + if (((pm->ps->velocity[2] > 0 && (pm->ps->pm_flags & PMF_TIME_KNOCKBACK)) || pm->ps->velocity[2] > 100) && + DotProduct(pm->ps->velocity, trace.plane.normal) > + 10) { // either thrown off ground (PMF_TIME_KNOCKBACK) or going off the ground at a large velocity + if (pm->debugLevel) { Com_Printf("%i:kickoff\n", c_pmove); } // go into jump animation - if ( PM_FlippingAnim( pm->ps->legsAnim) ) - {//we're flipping - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//special jumps - } - else if ( PM_InKnockDown( pm->ps ) ) - {//in knockdown - } - else if ( PM_InRoll( pm->ps ) ) - {//in knockdown - } - else if ( PM_KickingAnim( pm->ps->legsAnim ) ) - {//in kick - } - else if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_RANCOR || pm->gent->client->NPC_class == CLASS_WAMPA) ) - { - } - else - { + if (PM_FlippingAnim(pm->ps->legsAnim)) { // we're flipping + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // special jumps + } else if (PM_InKnockDown(pm->ps)) { // in knockdown + } else if (PM_InRoll(pm->ps)) { // in knockdown + } else if (PM_KickingAnim(pm->ps->legsAnim)) { // in kick + } else if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_RANCOR || pm->gent->client->NPC_class == CLASS_WAMPA)) { + } else { PM_JumpForDir(); } @@ -5261,8 +4330,8 @@ static void PM_GroundTrace( void ) { */ // slopes that are too steep will not be considered onground - if ( trace.plane.normal[2] < minNormal ) { - if ( pm->debugLevel ) { + if (trace.plane.normal[2] < minNormal) { + if (pm->debugLevel) { Com_Printf("%i:steep\n", c_pmove); } // FIXME: if they can't slide down the slope, let them @@ -5273,37 +4342,35 @@ static void PM_GroundTrace( void ) { return; } - //FIXME: if the ground surface is a "cover surface (like tall grass), add a "cover" flag to me + // FIXME: if the ground surface is a "cover surface (like tall grass), add a "cover" flag to me pml.groundPlane = qtrue; pml.walking = qtrue; // hitting solid ground will end a waterjump - if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) - { + if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { pm->ps->pm_flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND); pm->ps->pm_time = 0; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // just hit the ground - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:Land\n", c_pmove); } - //if ( !PM_ClientImpact( trace.entityNum, qtrue ) ) + // if ( !PM_ClientImpact( trace.entityNum, qtrue ) ) { PM_CrashLand(); // don't do landing time if we were just going down a slope - if ( pml.previous_velocity[2] < -200 ) { + if (pml.previous_velocity[2] < -200) { // don't allow another jump for a little while pm->ps->pm_flags |= PMF_TIME_LAND; pm->ps->pm_time = 250; } if (!pm->cmd.forwardmove && !pm->cmd.rightmove) { - if ( Flying != FLY_HOVER ) - { - pm->ps->velocity[2] = 0; //wouldn't normally want this because of slopes, but we aren't tyring to move... + if (Flying != FLY_HOVER) { + pm->ps->velocity[2] = 0; // wouldn't normally want this because of slopes, but we aren't tyring to move... } } } @@ -5311,127 +4378,105 @@ static void PM_GroundTrace( void ) { pm->ps->groundEntityNum = trace.entityNum; pm->ps->lastOnGround = level.time; - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//if a player, clear the jumping "flag" so can't double-jump + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // if a player, clear the jumping "flag" so can't double-jump pm->ps->forceJumpCharge = 0; } // don't reset the z velocity for slopes -// pm->ps->velocity[2] = 0; + // pm->ps->velocity[2] = 0; - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); } -int LastMatrixJumpTime = 0; -#define DEBUGMATRIXJUMP 0 +int LastMatrixJumpTime = 0; +#define DEBUGMATRIXJUMP 0 -void PM_HoverTrace( void ) -{ - if ( !pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_VEHICLE ) - { +void PM_HoverTrace(void) { + if (!pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_VEHICLE) { return; } Vehicle_t *pVeh = pm->gent->m_pVehicle; float hoverHeight = pVeh->m_pVehicleInfo->hoverHeight; - vec3_t point, vAng, fxAxis[3]; - trace_t *trace = &pml.groundTrace; - int traceContents = pm->tracemask; + vec3_t point, vAng, fxAxis[3]; + trace_t *trace = &pml.groundTrace; + int traceContents = pm->tracemask; pml.groundPlane = qfalse; - float relativeWaterLevel = (pm->ps->waterheight - (pm->ps->origin[2]+pm->mins[2])); - if ( pm->waterlevel && relativeWaterLevel >= 0 ) - {//in water - if ( pVeh->m_pVehicleInfo->bouyancy <= 0.0f ) - {//sink like a rock - } - else - {//rise up - float floatHeight = (pVeh->m_pVehicleInfo->bouyancy * ((pm->maxs[2]-pm->mins[2])*0.5f)) - (hoverHeight*0.5f);//1.0f should make you float half-in, half-out of water - if ( relativeWaterLevel > floatHeight ) - {//too low, should rise up + float relativeWaterLevel = (pm->ps->waterheight - (pm->ps->origin[2] + pm->mins[2])); + if (pm->waterlevel && relativeWaterLevel >= 0) { // in water + if (pVeh->m_pVehicleInfo->bouyancy <= 0.0f) { // sink like a rock + } else { // rise up + float floatHeight = (pVeh->m_pVehicleInfo->bouyancy * ((pm->maxs[2] - pm->mins[2]) * 0.5f)) - + (hoverHeight * 0.5f); // 1.0f should make you float half-in, half-out of water + if (relativeWaterLevel > floatHeight) { // too low, should rise up pm->ps->velocity[2] += (relativeWaterLevel - floatHeight) * pVeh->m_fTimeModifier; } } - if ( pm->ps->waterheight < pm->ps->origin[2]+pm->maxs[2] ) - {//part of us is sticking out of water - if ( fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100 ) - {//moving at a decent speed - if ( Q_irand( pml.frametime, 100 ) >= 50 ) - {//splash + if (pm->ps->waterheight < pm->ps->origin[2] + pm->maxs[2]) { // part of us is sticking out of water + if (fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100) { // moving at a decent speed + if (Q_irand(pml.frametime, 100) >= 50) { // splash vAng[PITCH] = vAng[ROLL] = 0; vAng[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( vAng, fxAxis[2], fxAxis[1], fxAxis[0] ); + AngleVectors(vAng, fxAxis[2], fxAxis[1], fxAxis[0]); vec3_t wakeOrg; - VectorCopy( pm->ps->origin, wakeOrg ); + VectorCopy(pm->ps->origin, wakeOrg); wakeOrg[2] = pm->ps->waterheight; - if ( pVeh->m_pVehicleInfo->iWakeFX ) - { - G_PlayEffect( pVeh->m_pVehicleInfo->iWakeFX, wakeOrg, fxAxis ); + if (pVeh->m_pVehicleInfo->iWakeFX) { + G_PlayEffect(pVeh->m_pVehicleInfo->iWakeFX, wakeOrg, fxAxis); } } } pml.groundPlane = qtrue; } - } - else - { + } else { float minNormal = (float)MIN_WALK_NORMAL; minNormal = pVeh->m_pVehicleInfo->maxSlope; point[0] = pm->ps->origin[0]; point[1] = pm->ps->origin[1]; - point[2] = pm->ps->origin[2] - (hoverHeight*3.0f); + point[2] = pm->ps->origin[2] - (hoverHeight * 3.0f); - //FIXME: check for water, too? If over water, go slower and make wave effect + // FIXME: check for water, too? If over water, go slower and make wave effect // If *in* water, go really slow and use bouyancy stat to determine how far below surface to float - //NOTE: if bouyancy is 2.0f or higher, you float over water like it's solid ground. + // NOTE: if bouyancy is 2.0f or higher, you float over water like it's solid ground. // if it's 1.0f, you sink halfway into water. If it's 0, you sink... - if ( pVeh->m_pVehicleInfo->bouyancy >= 2.0f ) - {//sit on water - traceContents |= (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA); - } - pm->trace( trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, traceContents, (EG2_Collision)0, 0 ); - if ( trace->plane.normal[2] >= minNormal ) - {//not a steep slope, so push us up - if ( trace->fraction < 0.3f ) - {//push up off ground - float hoverForce = pVeh->m_pVehicleInfo->hoverStrength; - pm->ps->velocity[2] += (0.3f-trace->fraction)*hoverForce*pVeh->m_fTimeModifier; - - // if (pm->ps->velocity[2]>60.0f) - // { - // pm->ps->velocity[2] = 60.0f; - // } - - if ( (trace->contents&(CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)) ) - {//hovering on water, make a spash if moving - if ( fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100 ) - {//moving at a decent speed - if ( Q_irand( pml.frametime, 100 ) >= 50 ) - {//splash + if (pVeh->m_pVehicleInfo->bouyancy >= 2.0f) { // sit on water + traceContents |= (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA); + } + pm->trace(trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, traceContents, (EG2_Collision)0, 0); + if (trace->plane.normal[2] >= minNormal) { // not a steep slope, so push us up + if (trace->fraction < 0.3f) { // push up off ground + float hoverForce = pVeh->m_pVehicleInfo->hoverStrength; + pm->ps->velocity[2] += (0.3f - trace->fraction) * hoverForce * pVeh->m_fTimeModifier; + + // if (pm->ps->velocity[2]>60.0f) + // { + // pm->ps->velocity[2] = 60.0f; + // } + + if ((trace->contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { // hovering on water, make a spash if moving + if (fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100) { // moving at a decent speed + if (Q_irand(pml.frametime, 100) >= 50) { // splash vAng[PITCH] = vAng[ROLL] = 0; vAng[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( vAng, fxAxis[2], fxAxis[1], fxAxis[0] ); - if ( pVeh->m_pVehicleInfo->iWakeFX ) - { - G_PlayEffect( pVeh->m_pVehicleInfo->iWakeFX, trace->endpos, fxAxis ); + AngleVectors(vAng, fxAxis[2], fxAxis[1], fxAxis[0]); + if (pVeh->m_pVehicleInfo->iWakeFX) { + G_PlayEffect(pVeh->m_pVehicleInfo->iWakeFX, trace->endpos, fxAxis); } } } } - if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) - { - if ( Q_irand( pml.frametime, 100 ) >= 50 ) - {//dust + if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) { + if (Q_irand(pml.frametime, 100) >= 50) { // dust VectorClear(fxAxis[0]); - fxAxis[0][2] = 1; + fxAxis[0][2] = 1; VectorCopy(pm->ps->velocity, fxAxis[1]); - fxAxis[1][2] *= 0.01f; + fxAxis[1][2] *= 0.01f; VectorMA(pm->ps->origin, 0.25f, fxAxis[1], point); G_PlayEffect("ships/swoop_dust", point, fxAxis[0]); } @@ -5440,76 +4485,62 @@ void PM_HoverTrace( void ) } } } - if ( pml.groundPlane ) - { - PM_SetVehicleAngles( pml.groundTrace.plane.normal ); + if (pml.groundPlane) { + PM_SetVehicleAngles(pml.groundTrace.plane.normal); // We're on the ground. -// if (pVeh->m_ulFlags&VEH_FLYING && level.timem_iTurboTime) -// { -// pVeh->m_iTurboTime = 0; // stop turbo -// } + // if (pVeh->m_ulFlags&VEH_FLYING && level.timem_iTurboTime) + // { + // pVeh->m_iTurboTime = 0; // stop turbo + // } pVeh->m_ulFlags &= ~VEH_FLYING; pVeh->m_vAngularVelocity = 0.0f; - } - else - { - PM_SetVehicleAngles( NULL ); + } else { + PM_SetVehicleAngles(NULL); // We're flying in the air. pVeh->m_ulFlags |= VEH_FLYING; - //groundTrace + // groundTrace - if (pVeh->m_vAngularVelocity==0.0f) - { + if (pVeh->m_vAngularVelocity == 0.0f) { pVeh->m_vAngularVelocity = pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; - if (pVeh->m_vAngularVelocity<-15.0f) - { + if (pVeh->m_vAngularVelocity < -15.0f) { pVeh->m_vAngularVelocity = -15.0f; } - if (pVeh->m_vAngularVelocity> 15.0f) - { - pVeh->m_vAngularVelocity = 15.0f; + if (pVeh->m_vAngularVelocity > 15.0f) { + pVeh->m_vAngularVelocity = 15.0f; } // BEGIN MATRIX MODE INIT FOR JUMP //================================= - if (pm->gent && - pm->gent->owner && - (pm->gent->owner->s.numbergent->owner)) && - pVeh->m_pVehicleInfo->type==VH_SPEEDER && - level.time>(LastMatrixJumpTime+5000) && VectorLength(pm->ps->velocity)>30.0f) - { - LastMatrixJumpTime = level.time; - vec3_t predictedApx; - vec3_t predictedFallVelocity; - vec3_t predictedLandPosition; - - VectorScale(pm->ps->velocity, 2.0f, predictedFallVelocity); // take friction into account - predictedFallVelocity[2] = -(pm->ps->gravity * 1.1f); // take gravity into account - - VectorMA(pm->ps->origin, 0.25f, pm->ps->velocity, predictedApx); - VectorMA(predictedApx, 0.25f, predictedFallVelocity, predictedLandPosition); - + if (pm->gent && pm->gent->owner && (pm->gent->owner->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent->owner)) && + pVeh->m_pVehicleInfo->type == VH_SPEEDER && level.time > (LastMatrixJumpTime + 5000) && VectorLength(pm->ps->velocity) > 30.0f) { + LastMatrixJumpTime = level.time; + vec3_t predictedApx; + vec3_t predictedFallVelocity; + vec3_t predictedLandPosition; + VectorScale(pm->ps->velocity, 2.0f, predictedFallVelocity); // take friction into account + predictedFallVelocity[2] = -(pm->ps->gravity * 1.1f); // take gravity into account + VectorMA(pm->ps->origin, 0.25f, pm->ps->velocity, predictedApx); + VectorMA(predictedApx, 0.25f, predictedFallVelocity, predictedLandPosition); trace_t trace2; - gi.trace( &trace2, predictedApx, pm->mins, pm->maxs, predictedLandPosition, pm->ps->clientNum, traceContents, (EG2_Collision)0, 0); - if (!trace2.startsolid && !trace2.allsolid && trace2.fraction>0.75 && Q_irand(0, 3)==0) - { + gi.trace(&trace2, predictedApx, pm->mins, pm->maxs, predictedLandPosition, pm->ps->clientNum, traceContents, (EG2_Collision)0, 0); + if (!trace2.startsolid && !trace2.allsolid && trace2.fraction > 0.75 && Q_irand(0, 3) == 0) { LastMatrixJumpTime += 20000; - G_StartMatrixEffect(pm->gent, MEF_HIT_GROUND_STOP); -// CG_DrawEdge(pm->ps->origin, predictedApx, EDGE_WHITE_TWOSECOND); -// CG_DrawEdge(predictedApx, predictedLandPosition, EDGE_WHITE_TWOSECOND); + G_StartMatrixEffect(pm->gent, MEF_HIT_GROUND_STOP); + // CG_DrawEdge(pm->ps->origin, predictedApx, EDGE_WHITE_TWOSECOND); + // CG_DrawEdge(predictedApx, predictedLandPosition, EDGE_WHITE_TWOSECOND); } -// else -// { -// CG_DrawEdge(pm->ps->origin, predictedApx, EDGE_RED_TWOSECOND); -// CG_DrawEdge(predictedApx, predictedLandPosition, EDGE_RED_TWOSECOND); -// } + // else + // { + // CG_DrawEdge(pm->ps->origin, predictedApx, EDGE_RED_TWOSECOND); + // CG_DrawEdge(predictedApx, predictedLandPosition, EDGE_RED_TWOSECOND); + // } } //================================= } - pVeh->m_vAngularVelocity *= 0.95f; // Angular Velocity Decays Over Time + pVeh->m_vAngularVelocity *= 0.95f; // Angular Velocity Decays Over Time } PM_GroundTraceMissed(); } @@ -5519,12 +4550,11 @@ void PM_HoverTrace( void ) PM_SetWaterLevelAtPoint FIXME: avoid this twice? certainly if not moving ============= */ -static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype ) -{ - vec3_t point; - int cont; - int sample1; - int sample2; +static void PM_SetWaterLevelAtPoint(vec3_t org, int *waterlevel, int *watertype) { + vec3_t point; + int cont; + int sample1; + int sample2; // // get waterlevel, accounting for ducking @@ -5535,26 +4565,22 @@ static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype point[0] = org[0]; point[1] = org[1]; point[2] = org[2] + DEFAULT_MINS_2 + 1; - if (gi.totalMapContents() & (MASK_WATER|CONTENTS_LADDER)) - { - cont = pm->pointcontents( point, pm->ps->clientNum ); + if (gi.totalMapContents() & (MASK_WATER | CONTENTS_LADDER)) { + cont = pm->pointcontents(point, pm->ps->clientNum); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + if (cont & (MASK_WATER | CONTENTS_LADDER)) { sample2 = pm->ps->viewheight - DEFAULT_MINS_2; sample1 = sample2 / 2; *watertype = cont; *waterlevel = 1; point[2] = org[2] + DEFAULT_MINS_2 + sample1; - cont = pm->pointcontents( point, pm->ps->clientNum ); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & (MASK_WATER | CONTENTS_LADDER)) { *waterlevel = 2; point[2] = org[2] + DEFAULT_MINS_2 + sample2; - cont = pm->pointcontents( point, pm->ps->clientNum ); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & (MASK_WATER | CONTENTS_LADDER)) { *waterlevel = 3; } } @@ -5562,81 +4588,55 @@ static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype } } -void PM_SetWaterHeight( void ) -{ +void PM_SetWaterHeight(void) { pm->ps->waterHeightLevel = WHL_NONE; - if ( pm->waterlevel < 1 ) - { + if (pm->waterlevel < 1) { pm->ps->waterheight = pm->ps->origin[2] + DEFAULT_MINS_2 - 4; return; } trace_t trace; - vec3_t top, bottom; + vec3_t top, bottom; - VectorCopy( pm->ps->origin, top ); - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, top); + VectorCopy(pm->ps->origin, bottom); top[2] += pm->gent->client->standheight; bottom[2] += DEFAULT_MINS_2; - gi.trace( &trace, top, pm->mins, pm->maxs, bottom, pm->ps->clientNum, MASK_WATER, (EG2_Collision)0, 0 ); + gi.trace(&trace, top, pm->mins, pm->maxs, bottom, pm->ps->clientNum, MASK_WATER, (EG2_Collision)0, 0); - if ( trace.startsolid ) - {//under water + if (trace.startsolid) { // under water pm->ps->waterheight = top[2] + 4; - } - else if ( trace.fraction < 1.0f ) - {//partially in and partially out of water - pm->ps->waterheight = trace.endpos[2]+pm->mins[2]; - } - else if ( trace.contents&MASK_WATER ) - {//water is above me + } else if (trace.fraction < 1.0f) { // partially in and partially out of water + pm->ps->waterheight = trace.endpos[2] + pm->mins[2]; + } else if (trace.contents & MASK_WATER) { // water is above me pm->ps->waterheight = top[2] + 4; - } - else - {//water is below me + } else { // water is below me pm->ps->waterheight = bottom[2] - 4; } - float distFromEyes = (pm->ps->origin[2]+pm->gent->client->standheight)-pm->ps->waterheight; + float distFromEyes = (pm->ps->origin[2] + pm->gent->client->standheight) - pm->ps->waterheight; - if ( distFromEyes < 0 ) - { + if (distFromEyes < 0) { pm->ps->waterHeightLevel = WHL_UNDER; - } - else if ( distFromEyes < 6 ) - { + } else if (distFromEyes < 6) { pm->ps->waterHeightLevel = WHL_HEAD; - } - else if ( distFromEyes < 18 ) - { + } else if (distFromEyes < 18) { pm->ps->waterHeightLevel = WHL_SHOULDERS; - } - else if ( distFromEyes < pm->gent->client->standheight-8 ) - {//at least 8 above origin + } else if (distFromEyes < pm->gent->client->standheight - 8) { // at least 8 above origin pm->ps->waterHeightLevel = WHL_TORSO; - } - else - { - float distFromOrg = pm->ps->origin[2]-pm->ps->waterheight; - if ( distFromOrg < 6 ) - { + } else { + float distFromOrg = pm->ps->origin[2] - pm->ps->waterheight; + if (distFromOrg < 6) { pm->ps->waterHeightLevel = WHL_WAIST; - } - else if ( distFromOrg < 16 ) - { + } else if (distFromOrg < 16) { pm->ps->waterHeightLevel = WHL_KNEES; - } - else if ( distFromOrg > fabs(pm->mins[2]) ) - { + } else if (distFromOrg > fabs(pm->mins[2])) { pm->ps->waterHeightLevel = WHL_NONE; - } - else - { + } else { pm->ps->waterHeightLevel = WHL_ANKLES; } } } - /* ============== PM_SetBounds @@ -5644,22 +4644,16 @@ PM_SetBounds Sets mins, maxs ============== */ -static void PM_SetBounds (void) -{ - if ( pm->gent && pm->gent->client ) - { - if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) - { - //assert(0); +static void PM_SetBounds(void) { + if (pm->gent && pm->gent->client) { + if (!pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2]) { + // assert(0); } - VectorCopy( pm->gent->mins, pm->mins ); - VectorCopy( pm->gent->maxs, pm->maxs ); - } - else - { - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + VectorCopy(pm->gent->mins, pm->mins); + VectorCopy(pm->gent->maxs, pm->maxs); + } else { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -5681,36 +4675,26 @@ PM_CheckDuck Sets mins, maxs, and pm->ps->viewheight ============== */ -static void PM_CheckDuck (void) -{ - trace_t trace; - int standheight; - int crouchheight; - int oldHeight; +static void PM_CheckDuck(void) { + trace_t trace; + int standheight; + int crouchheight; + int oldHeight; - if ( pm->gent && pm->gent->client ) - { - if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) - { - //assert(0); + if (pm->gent && pm->gent->client) { + if (!pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2]) { + // assert(0); } - if ( pm->ps->clientNum < MAX_CLIENTS - && (pm->gent->client->NPC_class == CLASS_ATST ||pm->gent->client->NPC_class == CLASS_RANCOR) - && !cg.renderingThirdPerson ) - { + if (pm->ps->clientNum < MAX_CLIENTS && (pm->gent->client->NPC_class == CLASS_ATST || pm->gent->client->NPC_class == CLASS_RANCOR) && + !cg.renderingThirdPerson) { standheight = crouchheight = 128; - } - else - { + } else { standheight = pm->gent->client->standheight; crouchheight = pm->gent->client->crouchheight; } - } - else - { - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + } else { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -5718,24 +4702,21 @@ static void PM_CheckDuck (void) crouchheight = CROUCH_MAXS_2; } - if ( PM_RidingVehicle() || (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) ) - {//riding a vehicle or are a vehicle - //no ducking or rolling when on a vehicle - //right? not even on ones that you just ride on top of? + if (PM_RidingVehicle() || (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE)) { // riding a vehicle or are a vehicle + // no ducking or rolling when on a vehicle + // right? not even on ones that you just ride on top of? pm->ps->pm_flags &= ~PMF_DUCKED; pm->maxs[2] = standheight; - //FIXME: have a crouchviewheight and standviewheight on ent? - pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET;//DEFAULT_VIEWHEIGHT; - //NOTE: we don't clear the pm->cmd.upmove here because - //the vehicle code may need it later... but, for riders, - //it should have already been copied over to the vehicle, right? + // FIXME: have a crouchviewheight and standviewheight on ent? + pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET; // DEFAULT_VIEWHEIGHT; + // NOTE: we don't clear the pm->cmd.upmove here because + // the vehicle code may need it later... but, for riders, + // it should have already been copied over to the vehicle, right? return; } - if ( PM_InGetUp( pm->ps ) ) - {//can't do any kind of crouching when getting up - if ( pm->ps->legsAnim == BOTH_GETUP_CROUCH_B1 || pm->ps->legsAnim == BOTH_GETUP_CROUCH_F1 ) - {//crouched still + if (PM_InGetUp(pm->ps)) { // can't do any kind of crouching when getting up + if (pm->ps->legsAnim == BOTH_GETUP_CROUCH_B1 || pm->ps->legsAnim == BOTH_GETUP_CROUCH_F1) { // crouched still pm->ps->pm_flags |= PMF_DUCKED; pm->maxs[2] = crouchheight; } @@ -5745,8 +4726,7 @@ static void PM_CheckDuck (void) oldHeight = pm->maxs[2]; - if ( PM_InRoll( pm->ps ) ) - { + if (PM_InRoll(pm->ps)) { /* if ( pm->ps->clientNum && pm->gent && pm->gent->client ) { @@ -5758,22 +4738,17 @@ static void PM_CheckDuck (void) } else */ - { - pm->maxs[2] = crouchheight; - } + { pm->maxs[2] = crouchheight; } pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; pm->ps->pm_flags |= PMF_DUCKED; return; } - if ( PM_GettingUpFromKnockDown( standheight, crouchheight ) ) - { + if (PM_GettingUpFromKnockDown(standheight, crouchheight)) { pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; return; } - if ( PM_InKnockDown( pm->ps ) ) - {//forced crouch - if ( pm->gent && pm->gent->client ) - {//interrupted any potential delayed weapon fires + if (PM_InKnockDown(pm->ps)) { // forced crouch + if (pm->gent && pm->gent->client) { // interrupted any potential delayed weapon fires pm->gent->client->fireDelay = 0; } pm->maxs[2] = crouchheight; @@ -5781,118 +4756,93 @@ static void PM_CheckDuck (void) pm->ps->pm_flags |= PMF_DUCKED; return; } - if ( pm->cmd.upmove < 0 ) - { // trying to duck + if (pm->cmd.upmove < 0) { // trying to duck pm->maxs[2] = crouchheight; - pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET;//CROUCH_VIEWHEIGHT; - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE && !PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//Not ducked already and trying to duck in mid-air - //will raise your feet, unducking whilst in air will drop feet - if ( !(pm->ps->pm_flags&PMF_DUCKED) ) - { + pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; // CROUCH_VIEWHEIGHT; + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && !PM_SwimmingAnim(pm->ps->legsAnim)) { // Not ducked already and trying to duck in mid-air + // will raise your feet, unducking whilst in air will drop feet + if (!(pm->ps->pm_flags & PMF_DUCKED)) { pm->ps->eFlags ^= EF_TELEPORT_BIT; } - if ( pm->gent ) - { - pm->ps->origin[2] += oldHeight - pm->maxs[2];//diff will be zero if were already ducking - //Don't worry, we know we fit in a smaller size + if (pm->gent) { + pm->ps->origin[2] += oldHeight - pm->maxs[2]; // diff will be zero if were already ducking + // Don't worry, we know we fit in a smaller size } } pm->ps->pm_flags |= PMF_DUCKED; - if ( d_JediAI->integer ) - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_SABER ) - { - Com_Printf( "ducking\n" ); + if (d_JediAI->integer) { + if (pm->ps->clientNum && pm->ps->weapon == WP_SABER) { + Com_Printf("ducking\n"); } } - } - else - { // want to stop ducking, stand up if possible - if ( pm->ps->pm_flags & PMF_DUCKED ) - {//Was ducking - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//unducking whilst in air will try to drop feet + } else { // want to stop ducking, stand up if possible + if (pm->ps->pm_flags & PMF_DUCKED) { // Was ducking + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // unducking whilst in air will try to drop feet pm->maxs[2] = standheight; pm->ps->origin[2] += oldHeight - pm->maxs[2]; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid ) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (!trace.allsolid) { pm->ps->eFlags ^= EF_TELEPORT_BIT; pm->ps->pm_flags &= ~PMF_DUCKED; - } - else - {//Put us back + } else { // Put us back pm->ps->origin[2] -= oldHeight - pm->maxs[2]; } - //NOTE: this isn't the best way to check this, you may have room to unduck - //while in air, but your feet are close to landing. Probably won't be a - //noticable shortcoming - } - else - { + // NOTE: this isn't the best way to check this, you may have room to unduck + // while in air, but your feet are close to landing. Probably won't be a + // noticable shortcoming + } else { // try to stand up pm->maxs[2] = standheight; - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid ) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (!trace.allsolid) { pm->ps->pm_flags &= ~PMF_DUCKED; } } } - if ( pm->ps->pm_flags & PMF_DUCKED ) - {//Still ducking + if (pm->ps->pm_flags & PMF_DUCKED) { // Still ducking pm->maxs[2] = crouchheight; - pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET;//CROUCH_VIEWHEIGHT; - } - else - {//standing now + pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; // CROUCH_VIEWHEIGHT; + } else { // standing now pm->maxs[2] = standheight; - //FIXME: have a crouchviewheight and standviewheight on ent? - pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET;//DEFAULT_VIEWHEIGHT; + // FIXME: have a crouchviewheight and standviewheight on ent? + pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET; // DEFAULT_VIEWHEIGHT; } } } - - //=================================================================== -qboolean PM_SaberLockAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_BF2LOCK: //# - case BOTH_BF1LOCK: //# - case BOTH_CWCIRCLELOCK: //# - case BOTH_CCWCIRCLELOCK: //# +qboolean PM_SaberLockAnim(int anim) { + switch (anim) { + case BOTH_BF2LOCK: //# + case BOTH_BF1LOCK: //# + case BOTH_CWCIRCLELOCK: //# + case BOTH_CCWCIRCLELOCK: //# return qtrue; } return qfalse; } -qboolean PM_ForceAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_CHOKE1: //being choked...??? - case BOTH_GESTURE1: //taunting... - case BOTH_RESISTPUSH: //# plant yourself to resist force push/pulls. - case BOTH_FORCEPUSH: //# Use off-hand to do force power. - case BOTH_FORCEPULL: //# Use off-hand to do force power. - case BOTH_MINDTRICK1: //# Use off-hand to do mind trick - case BOTH_MINDTRICK2: //# Use off-hand to do distraction - case BOTH_FORCELIGHTNING: //# Use off-hand to do lightning +qboolean PM_ForceAnim(int anim) { + switch (anim) { + case BOTH_CHOKE1: // being choked...??? + case BOTH_GESTURE1: // taunting... + case BOTH_RESISTPUSH: //# plant yourself to resist force push/pulls. + case BOTH_FORCEPUSH: //# Use off-hand to do force power. + case BOTH_FORCEPULL: //# Use off-hand to do force power. + case BOTH_MINDTRICK1: //# Use off-hand to do mind trick + case BOTH_MINDTRICK2: //# Use off-hand to do distraction + case BOTH_FORCELIGHTNING: //# Use off-hand to do lightning case BOTH_FORCELIGHTNING_START: - case BOTH_FORCELIGHTNING_HOLD: //# Use off-hand to do lightning - case BOTH_FORCELIGHTNING_RELEASE: //# Use off-hand to do lightning - case BOTH_FORCEHEAL_START: //# Healing meditation pose start - case BOTH_FORCEHEAL_STOP: //# Healing meditation pose end - case BOTH_FORCEHEAL_QUICK: //# Healing meditation gesture - case BOTH_FORCEGRIP1: //# temp force-grip anim (actually re-using push) - case BOTH_FORCEGRIP_HOLD: //# temp force-grip anim (actually re-using push) - case BOTH_FORCEGRIP_RELEASE: //# temp force-grip anim (actually re-using push) - //case BOTH_FORCEGRIP3: //# force-gripping + case BOTH_FORCELIGHTNING_HOLD: //# Use off-hand to do lightning + case BOTH_FORCELIGHTNING_RELEASE: //# Use off-hand to do lightning + case BOTH_FORCEHEAL_START: //# Healing meditation pose start + case BOTH_FORCEHEAL_STOP: //# Healing meditation pose end + case BOTH_FORCEHEAL_QUICK: //# Healing meditation gesture + case BOTH_FORCEGRIP1: //# temp force-grip anim (actually re-using push) + case BOTH_FORCEGRIP_HOLD: //# temp force-grip anim (actually re-using push) + case BOTH_FORCEGRIP_RELEASE: //# temp force-grip anim (actually re-using push) + // case BOTH_FORCEGRIP3: //# force-gripping case BOTH_FORCE_RAGE: case BOTH_FORCE_2HANDEDLIGHTNING: case BOTH_FORCE_2HANDEDLIGHTNING_START: @@ -5913,19 +4863,15 @@ qboolean PM_ForceAnim( int anim ) return qfalse; } -qboolean PM_InSaberAnim( int anim ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR ) - { +qboolean PM_InSaberAnim(int anim) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR) { return qtrue; } return qfalse; } -qboolean PM_InForceGetUp( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InForceGetUp(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_FORCE_GETUP_F1: case BOTH_FORCE_GETUP_F2: case BOTH_FORCE_GETUP_B1: @@ -5942,8 +4888,7 @@ qboolean PM_InForceGetUp( playerState_t *ps ) case BOTH_GETUP_FROLL_F: case BOTH_GETUP_FROLL_L: case BOTH_GETUP_FROLL_R: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; @@ -5951,10 +4896,8 @@ qboolean PM_InForceGetUp( playerState_t *ps ) return qfalse; } -qboolean PM_InGetUp( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InGetUp(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -5970,23 +4913,20 @@ qboolean PM_InGetUp( playerState_t *ps ) case BOTH_GETUP_FROLL_F: case BOTH_GETUP_FROLL_L: case BOTH_GETUP_FROLL_R: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; default: - return PM_InForceGetUp( ps ); + return PM_InForceGetUp(ps); break; } - //what the hell, redundant, but... + // what the hell, redundant, but... return qfalse; } -qboolean PM_InGetUpNoRoll( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InGetUpNoRoll(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -6002,8 +4942,7 @@ qboolean PM_InGetUpNoRoll( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; @@ -6011,28 +4950,24 @@ qboolean PM_InGetUpNoRoll( playerState_t *ps ) return qfalse; } -qboolean PM_InKnockDown( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InKnockDown(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - //special anims: + // special anims: case BOTH_RELEASED: return qtrue; break; case BOTH_LK_DL_ST_T_SB_1_L: - if ( ps->legsAnimTimer < 550 ) - { + if (ps->legsAnimTimer < 550) { return qtrue; } break; case BOTH_PLAYER_PA_3_FLY: - if ( ps->legsAnimTimer < 300 ) - { + if (ps->legsAnimTimer < 300) { return qtrue; } /* @@ -6044,34 +4979,30 @@ qboolean PM_InKnockDown( playerState_t *ps ) */ break; default: - return PM_InGetUp( ps ); + return PM_InGetUp(ps); break; } return qfalse; } -qboolean PM_InKnockDownNoGetup( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InKnockDownNoGetup(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - //special anims: + // special anims: case BOTH_RELEASED: return qtrue; break; case BOTH_LK_DL_ST_T_SB_1_L: - if ( ps->legsAnimTimer < 550 ) - { + if (ps->legsAnimTimer < 550) { return qtrue; } break; case BOTH_PLAYER_PA_3_FLY: - if ( ps->legsAnimTimer < 300 ) - { + if (ps->legsAnimTimer < 300) { return qtrue; } /* @@ -6086,18 +5017,16 @@ qboolean PM_InKnockDownNoGetup( playerState_t *ps ) return qfalse; } -qboolean PM_InKnockDownOnGround( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InKnockDownOnGround(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: case BOTH_RELEASED: - //if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) - {//at end of fall down anim + // if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) + { // at end of fall down anim return qtrue; } break; @@ -6116,8 +5045,8 @@ qboolean PM_InKnockDownOnGround( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer < 500 ) - {//at beginning of getup anim + if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->legsAnimTimer < + 500) { // at beginning of getup anim return qtrue; } break; @@ -6129,20 +5058,18 @@ qboolean PM_InKnockDownOnGround( playerState_t *ps ) case BOTH_GETUP_FROLL_F: case BOTH_GETUP_FROLL_L: case BOTH_GETUP_FROLL_R: - if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer < 500 ) - {//at beginning of getup anim + if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->legsAnimTimer < + 500) { // at beginning of getup anim return qtrue; } break; case BOTH_LK_DL_ST_T_SB_1_L: - if ( ps->legsAnimTimer < 1000 ) - { + if (ps->legsAnimTimer < 1000) { return qtrue; } break; case BOTH_PLAYER_PA_3_FLY: - if ( ps->legsAnimTimer < 300 ) - { + if (ps->legsAnimTimer < 300) { return qtrue; } /* @@ -6157,13 +5084,11 @@ qboolean PM_InKnockDownOnGround( playerState_t *ps ) return qfalse; } -qboolean PM_CrouchGetup( float crouchheight ) -{ +qboolean PM_CrouchGetup(float crouchheight) { pm->maxs[2] = crouchheight; pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; - int anim = -1; - switch ( pm->ps->legsAnim ) - { + int anim = -1; + switch (pm->ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN4: @@ -6177,197 +5102,125 @@ qboolean PM_CrouchGetup( float crouchheight ) anim = BOTH_GETUP_CROUCH_F1; break; } - if ( anim == -1 ) - {//WTF? stay down? - pm->ps->legsAnimTimer = 100;//hold this anim for another 10th of a second + if (anim == -1) { // WTF? stay down? + pm->ps->legsAnimTimer = 100; // hold this anim for another 10th of a second return qfalse; - } - else - {//get up into crouch anim - if ( PM_LockedAnim( pm->ps->torsoAnim ) ) - {//need to be able to override this anim + } else { // get up into crouch anim + if (PM_LockedAnim(pm->ps->torsoAnim)) { // need to be able to override this anim pm->ps->torsoAnimTimer = 0; } - if ( PM_LockedAnim( pm->ps->legsAnim ) ) - {//need to be able to override this anim + if (PM_LockedAnim(pm->ps->legsAnim)) { // need to be able to override this anim pm->ps->legsAnimTimer = 0; } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS ); - pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in pm->ps->saberBlocked = BLOCKED_NONE; return qtrue; } } -extern qboolean PM_GoingToAttackDown( playerState_t *ps ); -qboolean PM_CheckRollGetup( void ) -{ - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN1 - || pm->ps->legsAnim == BOTH_KNOCKDOWN2 - || pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN4 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L - || pm->ps->legsAnim == BOTH_PLAYER_PA_3_FLY - || pm->ps->legsAnim == BOTH_RELEASED ) - {//lying on back or front - if ( ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && ( pm->cmd.rightmove || (pm->cmd.forwardmove&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) ) )//player pressing left or right - || ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) && pm->gent->NPC//an NPC - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0//have at least force jump 1 - && pm->gent->enemy //I have an enemy - && pm->gent->enemy->client//a client - && pm->gent->enemy->enemy == pm->gent//he's mad at me! - && (PM_GoingToAttackDown( &pm->gent->enemy->client->ps )||!Q_irand(0,2))//he's attacking downward! (or we just feel like doing it this time) - && ((pm->gent->client&&pm->gent->client->NPC_class==CLASS_ALORA)||Q_irand( 0, RANK_CAPTAIN )gent->NPC->rank) ) )//higher rank I am, more likely I am to roll away! - {//roll away! +extern qboolean PM_GoingToAttackDown(playerState_t *ps); +qboolean PM_CheckRollGetup(void) { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN1 || pm->ps->legsAnim == BOTH_KNOCKDOWN2 || pm->ps->legsAnim == BOTH_KNOCKDOWN3 || + pm->ps->legsAnim == BOTH_KNOCKDOWN4 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L || + pm->ps->legsAnim == BOTH_PLAYER_PA_3_FLY || pm->ps->legsAnim == BOTH_RELEASED) { // lying on back or front + if (((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + (pm->cmd.rightmove || (pm->cmd.forwardmove && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0))) // player pressing left or right + || ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) && pm->gent->NPC // an NPC + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // have at least force jump 1 + && pm->gent->enemy // I have an enemy + && pm->gent->enemy->client // a client + && pm->gent->enemy->enemy == pm->gent // he's mad at me! + && (PM_GoingToAttackDown(&pm->gent->enemy->client->ps) || !Q_irand(0, 2)) // he's attacking downward! (or we just feel like doing it this time) + && ((pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA) || + Q_irand(0, RANK_CAPTAIN) < pm->gent->NPC->rank))) // higher rank I am, more likely I am to roll away! + { // roll away! int anim; qboolean forceGetUp = qfalse; - if ( pm->cmd.forwardmove > 0 ) - { - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { + if (pm->cmd.forwardmove > 0) { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { anim = BOTH_GETUP_FROLL_F; - } - else - { + } else { anim = BOTH_GETUP_BROLL_F; } forceGetUp = qtrue; - } - else if ( pm->cmd.forwardmove < 0 ) - { - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { + } else if (pm->cmd.forwardmove < 0) { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { anim = BOTH_GETUP_FROLL_B; - } - else - { + } else { anim = BOTH_GETUP_BROLL_B; } forceGetUp = qtrue; - } - else if ( pm->cmd.rightmove > 0 ) - { - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { + } else if (pm->cmd.rightmove > 0) { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { anim = BOTH_GETUP_FROLL_R; - } - else - { + } else { anim = BOTH_GETUP_BROLL_R; } - } - else if ( pm->cmd.rightmove < 0 ) - { - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { + } else if (pm->cmd.rightmove < 0) { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { anim = BOTH_GETUP_FROLL_L; - } - else - { + } else { anim = BOTH_GETUP_BROLL_L; } - } - else - { - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - {//on your front - anim = Q_irand( BOTH_GETUP_FROLL_B, BOTH_GETUP_FROLL_R ); - } - else - { - anim = Q_irand( BOTH_GETUP_BROLL_B, BOTH_GETUP_BROLL_R ); + } else { + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { // on your front + anim = Q_irand(BOTH_GETUP_FROLL_B, BOTH_GETUP_FROLL_R); + } else { + anim = Q_irand(BOTH_GETUP_BROLL_B, BOTH_GETUP_BROLL_R); } } - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - { - if ( !G_CheckRollSafety( pm->gent, anim, 64 ) ) - {//oops, try other one - if ( pm->ps->legsAnim == BOTH_KNOCKDOWN3 - || pm->ps->legsAnim == BOTH_KNOCKDOWN5 - || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { - if ( anim == BOTH_GETUP_FROLL_R ) - { + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { + if (!G_CheckRollSafety(pm->gent, anim, 64)) { // oops, try other one + if (pm->ps->legsAnim == BOTH_KNOCKDOWN3 || pm->ps->legsAnim == BOTH_KNOCKDOWN5 || pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { + if (anim == BOTH_GETUP_FROLL_R) { anim = BOTH_GETUP_FROLL_L; - } - else if ( anim == BOTH_GETUP_FROLL_F ) - { + } else if (anim == BOTH_GETUP_FROLL_F) { anim = BOTH_GETUP_FROLL_B; - } - else if ( anim == BOTH_GETUP_FROLL_B ) - { + } else if (anim == BOTH_GETUP_FROLL_B) { anim = BOTH_GETUP_FROLL_F; - } - else - { + } else { anim = BOTH_GETUP_FROLL_L; } - if ( !G_CheckRollSafety( pm->gent, anim, 64 ) ) - {//neither side is clear, screw it + if (!G_CheckRollSafety(pm->gent, anim, 64)) { // neither side is clear, screw it return qfalse; } - } - else - { - if ( anim == BOTH_GETUP_BROLL_R ) - { + } else { + if (anim == BOTH_GETUP_BROLL_R) { anim = BOTH_GETUP_BROLL_L; - } - else if ( anim == BOTH_GETUP_BROLL_F ) - { + } else if (anim == BOTH_GETUP_BROLL_F) { anim = BOTH_GETUP_BROLL_B; - } - else if ( anim == BOTH_GETUP_FROLL_B ) - { + } else if (anim == BOTH_GETUP_FROLL_B) { anim = BOTH_GETUP_BROLL_F; - } - else - { + } else { anim = BOTH_GETUP_BROLL_L; } - if ( !G_CheckRollSafety( pm->gent, anim, 64 ) ) - {//neither side is clear, screw it + if (!G_CheckRollSafety(pm->gent, anim, 64)) { // neither side is clear, screw it return qfalse; } } } } pm->cmd.rightmove = pm->cmd.forwardmove = 0; - if ( PM_LockedAnim( pm->ps->torsoAnim ) ) - {//need to be able to override this anim + if (PM_LockedAnim(pm->ps->torsoAnim)) { // need to be able to override this anim pm->ps->torsoAnimTimer = 0; } - if ( PM_LockedAnim( pm->ps->legsAnim ) ) - {//need to be able to override this anim + if (PM_LockedAnim(pm->ps->legsAnim)) { // need to be able to override this anim pm->ps->legsAnimTimer = 0; } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer - 300;//don't attack until near end of this anim - pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->weaponTime = pm->ps->torsoAnimTimer - 300; // don't attack until near end of this anim + pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in pm->ps->saberBlocked = BLOCKED_NONE; - if ( forceGetUp ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY - && pm->gent->NPC && pm->gent->NPC->blockedSpeechDebounceTime < level.time - && !Q_irand( 0, 1 ) ) - { - PM_AddEvent( Q_irand( EV_COMBAT1, EV_COMBAT3 ) ); + if (forceGetUp) { + if (pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY && pm->gent->NPC && + pm->gent->NPC->blockedSpeechDebounceTime < level.time && !Q_irand(0, 1)) { + PM_AddEvent(Q_irand(EV_COMBAT1, EV_COMBAT3)); pm->gent->NPC->blockedSpeechDebounceTime = level.time + 1000; } - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - //launch off ground? - pm->ps->weaponTime = 300;//just to make sure it's cleared + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + // launch off ground? + pm->ps->weaponTime = 300; // just to make sure it's cleared } return qtrue; } @@ -6375,160 +5228,133 @@ qboolean PM_CheckRollGetup( void ) return qfalse; } -extern int G_MinGetUpTime( gentity_t *ent ); -qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ) -{ +extern int G_MinGetUpTime(gentity_t *ent); +qboolean PM_GettingUpFromKnockDown(float standheight, float crouchheight) { int legsAnim = pm->ps->legsAnim; - if ( legsAnim == BOTH_KNOCKDOWN1 - ||legsAnim == BOTH_KNOCKDOWN2 - ||legsAnim == BOTH_KNOCKDOWN3 - ||legsAnim == BOTH_KNOCKDOWN4 - ||legsAnim == BOTH_KNOCKDOWN5 - ||legsAnim == BOTH_PLAYER_PA_3_FLY - ||legsAnim == BOTH_LK_DL_ST_T_SB_1_L - ||legsAnim == BOTH_RELEASED ) - {//in a knockdown - int minTimeLeft = G_MinGetUpTime( pm->gent ); - if ( pm->ps->legsAnimTimer <= minTimeLeft ) - {//if only a quarter of a second left, allow roll-aways - if ( PM_CheckRollGetup() ) - { + if (legsAnim == BOTH_KNOCKDOWN1 || legsAnim == BOTH_KNOCKDOWN2 || legsAnim == BOTH_KNOCKDOWN3 || legsAnim == BOTH_KNOCKDOWN4 || + legsAnim == BOTH_KNOCKDOWN5 || legsAnim == BOTH_PLAYER_PA_3_FLY || legsAnim == BOTH_LK_DL_ST_T_SB_1_L || legsAnim == BOTH_RELEASED) { // in a knockdown + int minTimeLeft = G_MinGetUpTime(pm->gent); + if (pm->ps->legsAnimTimer <= minTimeLeft) { // if only a quarter of a second left, allow roll-aways + if (PM_CheckRollGetup()) { pm->cmd.rightmove = pm->cmd.forwardmove = 0; return qtrue; } } - if ( TIMER_Exists( pm->gent, "noGetUpStraight" ) ) - { - if ( !TIMER_Done2( pm->gent, "noGetUpStraight", qtrue ) ) - {//not allowed to do straight get-ups for another few seconds - if ( pm->ps->legsAnimTimer <= minTimeLeft ) - {//hold it for a bit - pm->ps->legsAnimTimer = minTimeLeft+1; + if (TIMER_Exists(pm->gent, "noGetUpStraight")) { + if (!TIMER_Done2(pm->gent, "noGetUpStraight", qtrue)) { // not allowed to do straight get-ups for another few seconds + if (pm->ps->legsAnimTimer <= minTimeLeft) { // hold it for a bit + pm->ps->legsAnimTimer = minTimeLeft + 1; } } } - if ( !pm->ps->legsAnimTimer || (pm->ps->legsAnimTimer<=minTimeLeft&&(pm->cmd.upmove>0||(pm->gent&&pm->gent->client&&pm->gent->client->NPC_class==CLASS_ALORA))) ) - {//done with the knockdown - FIXME: somehow this is allowing an *instant* getup...??? - //FIXME: if trying to crouch (holding button?), just get up into a crouch? - if ( pm->cmd.upmove < 0 ) - { - return PM_CrouchGetup( crouchheight ); - } - else - { - trace_t trace; + if (!pm->ps->legsAnimTimer || + (pm->ps->legsAnimTimer <= minTimeLeft && + (pm->cmd.upmove > 0 || + (pm->gent && pm->gent->client && + pm->gent->client->NPC_class == CLASS_ALORA)))) { // done with the knockdown - FIXME: somehow this is allowing an *instant* getup...??? + // FIXME: if trying to crouch (holding button?), just get up into a crouch? + if (pm->cmd.upmove < 0) { + return PM_CrouchGetup(crouchheight); + } else { + trace_t trace; // try to stand up pm->maxs[2] = standheight; - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid ) - {//stand up - int anim = BOTH_GETUP1; + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (!trace.allsolid) { // stand up + int anim = BOTH_GETUP1; qboolean forceGetUp = qfalse; pm->maxs[2] = standheight; pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET; - //NOTE: the force power checks will stop fencers and grunts from getting up using force jump - switch ( pm->ps->legsAnim ) - { + // NOTE: the force power checks will stop fencers and grunts from getting up using force jump + switch (pm->ps->legsAnim) { case BOTH_KNOCKDOWN1: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) )//FORCE_LEVEL_1) )FORCE_LEVEL_1) ) + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0)) // FORCE_LEVEL_1) )FORCE_LEVEL_1) ) { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP1; } break; case BOTH_KNOCKDOWN2: case BOTH_PLAYER_PA_3_FLY: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) )//FORCE_LEVEL_1) )FORCE_LEVEL_1) ) + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0)) // FORCE_LEVEL_1) )FORCE_LEVEL_1) ) { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { - anim = BOTH_GETUP2; + } else { + anim = BOTH_GETUP2; } break; case BOTH_KNOCKDOWN3: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) )//FORCE_LEVEL_1) ) + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0)) // FORCE_LEVEL_1) ) { - anim = Q_irand( BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2 ); + anim = Q_irand(BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2); forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP3; } break; case BOTH_KNOCKDOWN4: case BOTH_RELEASED: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) )//FORCE_LEVEL_1) )FORCE_LEVEL_1) ) + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0)) // FORCE_LEVEL_1) )FORCE_LEVEL_1) ) { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP4; } break; case BOTH_KNOCKDOWN5: case BOTH_LK_DL_ST_T_SB_1_L: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) )//FORCE_LEVEL_1) )FORCE_LEVEL_1) ) + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->cmd.upmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0)) // FORCE_LEVEL_1) )FORCE_LEVEL_1) ) { - anim = Q_irand( BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2 ); + anim = Q_irand(BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2); forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP5; } break; } - //Com_Printf( "getupanim = %s\n", animTable[anim].name ); - if ( forceGetUp ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY - && pm->gent->NPC && pm->gent->NPC->blockedSpeechDebounceTime < level.time - && !Q_irand( 0, 1 ) ) - { - PM_AddEvent( Q_irand( EV_COMBAT1, EV_COMBAT3 ) ); + // Com_Printf( "getupanim = %s\n", animTable[anim].name ); + if (forceGetUp) { + if (pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY && pm->gent->NPC && + pm->gent->NPC->blockedSpeechDebounceTime < level.time && !Q_irand(0, 1)) { + PM_AddEvent(Q_irand(EV_COMBAT1, EV_COMBAT3)); pm->gent->NPC->blockedSpeechDebounceTime = level.time + 1000; } - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - //launch off ground? - pm->ps->weaponTime = 300;//just to make sure it's cleared + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + // launch off ground? + pm->ps->weaponTime = 300; // just to make sure it's cleared } - if ( PM_LockedAnim( pm->ps->torsoAnim ) ) - {//need to be able to override this anim + if (PM_LockedAnim(pm->ps->torsoAnim)) { // need to be able to override this anim pm->ps->torsoAnimTimer = 0; } - if ( PM_LockedAnim( pm->ps->legsAnim ) ) - {//need to be able to override this anim + if (PM_LockedAnim(pm->ps->legsAnim)) { // need to be able to override this anim pm->ps->legsAnimTimer = 0; } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS ); - pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in pm->ps->saberBlocked = BLOCKED_NONE; return qtrue; + } else { + return PM_CrouchGetup(crouchheight); } - else - { - return PM_CrouchGetup( crouchheight ); - } - } - } - else - { - if ( pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { - PM_CmdForRoll( pm->ps, &pm->cmd ); } - else - { + } else { + if (pm->ps->legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { + PM_CmdForRoll(pm->ps, &pm->cmd); + } else { pm->cmd.rightmove = pm->cmd.forwardmove = 0; } } @@ -6536,10 +5362,8 @@ qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ) return qfalse; } -void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ) -{ - switch ( ps->legsAnim ) - { +void PM_CmdForRoll(playerState_t *ps, usercmd_t *pCmd) { + switch (ps->legsAnim) { case BOTH_ROLL_F: pCmd->forwardmove = 127; pCmd->rightmove = 0; @@ -6560,117 +5384,94 @@ void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ) case BOTH_GETUP_BROLL_R: pCmd->forwardmove = 0; pCmd->rightmove = 48; - //NOTE: speed is 400 + // NOTE: speed is 400 break; case BOTH_GETUP_FROLL_R: - if ( ps->legsAnimTimer <= 250 ) - {//end of anim + if (ps->legsAnimTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 0; pCmd->rightmove = 48; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_L: pCmd->forwardmove = 0; pCmd->rightmove = -48; - //NOTE: speed is 400 + // NOTE: speed is 400 break; case BOTH_GETUP_FROLL_L: - if ( ps->legsAnimTimer <= 250 ) - {//end of anim + if (ps->legsAnimTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 0; pCmd->rightmove = -48; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_B: - if ( ps->torsoAnimTimer <= 250 ) - {//end of anim + if (ps->torsoAnimTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->torsoAnimTimer < 350 ) - {//beginning of anim + } else if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->torsoAnimTimer < + 350) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = -64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_FROLL_B: - if ( ps->torsoAnimTimer <= 100 ) - {//end of anim + if (ps->torsoAnimTimer <= 100) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->torsoAnimTimer < 200 ) - {//beginning of anim + } else if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->torsoAnimTimer < + 200) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = -64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_F: - if ( ps->torsoAnimTimer <= 550 ) - {//end of anim + if (ps->torsoAnimTimer <= 550) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->torsoAnimTimer < 150 ) - {//beginning of anim + } else if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->torsoAnimTimer < + 150) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_FROLL_F: - if ( ps->torsoAnimTimer <= 100 ) - {//end of anim + if (ps->torsoAnimTimer <= 100) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = 64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_LK_DL_ST_T_SB_1_L: - //kicked backwards - if ( ps->legsAnimTimer < 3050//at least 10 frames in - && ps->legsAnimTimer > 550 )//at least 6 frames from end - {//move backwards + // kicked backwards + if (ps->legsAnimTimer < 3050 // at least 10 frames in + && ps->legsAnimTimer > 550) // at least 6 frames from end + { // move backwards pCmd->forwardmove = -64; pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = pCmd->rightmove = 0; } break; @@ -6679,10 +5480,8 @@ void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ) pCmd->upmove = 0; } -qboolean PM_InRollIgnoreTimer( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InRollIgnoreTimer(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: @@ -6700,78 +5499,69 @@ qboolean PM_InRollIgnoreTimer( playerState_t *ps ) return qfalse; } -qboolean PM_InRoll( playerState_t *ps ) -{ - if ( ps->legsAnimTimer && PM_InRollIgnoreTimer( ps ) ) - { +qboolean PM_InRoll(playerState_t *ps) { + if (ps->legsAnimTimer && PM_InRollIgnoreTimer(ps)) { return qtrue; } return qfalse; } -qboolean PM_CrouchAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SIT1: //# Normal chair sit. - case BOTH_SIT2: //# Lotus position. - case BOTH_SIT3: //# Sitting in tired position: elbows on knees - case BOTH_CROUCH1: //# Transition from standing to crouch - case BOTH_CROUCH1IDLE: //# Crouching idle - case BOTH_CROUCH1WALK: //# Walking while crouched - case BOTH_CROUCH1WALKBACK: //# Walking while crouched - case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 - case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) - case BOTH_KNEES1: //# Tavion on her knees - case BOTH_CROUCHATTACKBACK1://FIXME: not if in middle of anim? +qboolean PM_CrouchAnim(int anim) { + switch (anim) { + case BOTH_SIT1: //# Normal chair sit. + case BOTH_SIT2: //# Lotus position. + case BOTH_SIT3: //# Sitting in tired position: elbows on knees + case BOTH_CROUCH1: //# Transition from standing to crouch + case BOTH_CROUCH1IDLE: //# Crouching idle + case BOTH_CROUCH1WALK: //# Walking while crouched + case BOTH_CROUCH1WALKBACK: //# Walking while crouched + case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 + case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) + case BOTH_KNEES1: //# Tavion on her knees + case BOTH_CROUCHATTACKBACK1: // FIXME: not if in middle of anim? case BOTH_ROLL_STAB: //??? case BOTH_STAND_TO_KNEEL: case BOTH_KNEEL_TO_STAND: case BOTH_TURNCROUCH1: case BOTH_CROUCH4: - case BOTH_KNEES2: //# Tavion on her knees looking down - case BOTH_KNEES2TO1: //# Transition of KNEES2 to KNEES1 + case BOTH_KNEES2: //# Tavion on her knees looking down + case BOTH_KNEES2TO1: //# Transition of KNEES2 to KNEES1 return qtrue; break; } return qfalse; } -qboolean PM_PainAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_PAIN1: //# First take pain anim - case BOTH_PAIN2: //# Second take pain anim - case BOTH_PAIN3: //# Third take pain anim - case BOTH_PAIN4: //# Fourth take pain anim - case BOTH_PAIN5: //# Fifth take pain anim - from behind - case BOTH_PAIN6: //# Sixth take pain anim - from behind - case BOTH_PAIN7: //# Seventh take pain anim - from behind - case BOTH_PAIN8: //# Eigth take pain anim - from behind - case BOTH_PAIN9: //# - case BOTH_PAIN10: //# - case BOTH_PAIN11: //# - case BOTH_PAIN12: //# - case BOTH_PAIN13: //# - case BOTH_PAIN14: //# - case BOTH_PAIN15: //# - case BOTH_PAIN16: //# - case BOTH_PAIN17: //# - case BOTH_PAIN18: //# +qboolean PM_PainAnim(int anim) { + switch (anim) { + case BOTH_PAIN1: //# First take pain anim + case BOTH_PAIN2: //# Second take pain anim + case BOTH_PAIN3: //# Third take pain anim + case BOTH_PAIN4: //# Fourth take pain anim + case BOTH_PAIN5: //# Fifth take pain anim - from behind + case BOTH_PAIN6: //# Sixth take pain anim - from behind + case BOTH_PAIN7: //# Seventh take pain anim - from behind + case BOTH_PAIN8: //# Eigth take pain anim - from behind + case BOTH_PAIN9: //# + case BOTH_PAIN10: //# + case BOTH_PAIN11: //# + case BOTH_PAIN12: //# + case BOTH_PAIN13: //# + case BOTH_PAIN14: //# + case BOTH_PAIN15: //# + case BOTH_PAIN16: //# + case BOTH_PAIN17: //# + case BOTH_PAIN18: //# return qtrue; break; } return qfalse; } - -qboolean PM_DodgeHoldAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_DodgeHoldAnim(int anim) { + switch (anim) { case BOTH_DODGE_HOLD_FL: case BOTH_DODGE_HOLD_FR: case BOTH_DODGE_HOLD_BL: @@ -6784,104 +5574,93 @@ qboolean PM_DodgeHoldAnim( int anim ) return qfalse; } -qboolean PM_DodgeAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_DODGE_FL: //# lean-dodge forward left - case BOTH_DODGE_FR: //# lean-dodge forward right - case BOTH_DODGE_BL: //# lean-dodge backwards left - case BOTH_DODGE_BR: //# lean-dodge backwards right - case BOTH_DODGE_L: //# lean-dodge left - case BOTH_DODGE_R: //# lean-dodge right +qboolean PM_DodgeAnim(int anim) { + switch (anim) { + case BOTH_DODGE_FL: //# lean-dodge forward left + case BOTH_DODGE_FR: //# lean-dodge forward right + case BOTH_DODGE_BL: //# lean-dodge backwards left + case BOTH_DODGE_BR: //# lean-dodge backwards right + case BOTH_DODGE_L: //# lean-dodge left + case BOTH_DODGE_R: //# lean-dodge right return qtrue; break; default: - return PM_DodgeHoldAnim( anim ); + return PM_DodgeHoldAnim(anim); break; } - //return qfalse; -} - -qboolean PM_ForceJumpingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground - case BOTH_FORCEINAIR1: //# In air loop (from jump) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) + // return qfalse; +} + +qboolean PM_ForceJumpingAnim(int anim) { + switch (anim) { + case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground + case BOTH_FORCEINAIR1: //# In air loop (from jump) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_JumpingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_JUMP1: //# Jump - wind-up and leave ground - case BOTH_INAIR1: //# In air loop (from jump) - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_INAIRBACK1: //# In air loop (from jump back) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_INAIRLEFT1: //# In air loop (from jump left) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_INAIRRIGHT1: //# In air loop (from jump right) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_JumpingAnim(int anim) { + switch (anim) { + case BOTH_JUMP1: //# Jump - wind-up and leave ground + case BOTH_INAIR1: //# In air loop (from jump) + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_INAIRBACK1: //# In air loop (from jump back) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_INAIRLEFT1: //# In air loop (from jump left) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_INAIRRIGHT1: //# In air loop (from jump right) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; default: - if ( PM_InAirKickingAnim( anim ) ) - { + if (PM_InAirKickingAnim(anim)) { return qtrue; } - return PM_ForceJumpingAnim( anim ); + return PM_ForceJumpingAnim(anim); break; } - //return qfalse; + // return qfalse; } -qboolean PM_LandingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_LandingAnim(int anim) { + switch (anim) { + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_FlippingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_FLIP_F: //# Flip forward - case BOTH_FLIP_B: //# Flip backwards - case BOTH_FLIP_L: //# Flip left - case BOTH_FLIP_R: //# Flip right +qboolean PM_FlippingAnim(int anim) { + switch (anim) { + case BOTH_FLIP_F: //# Flip forward + case BOTH_FLIP_B: //# Flip backwards + case BOTH_FLIP_L: //# Flip left + case BOTH_FLIP_R: //# Flip right case BOTH_ALORA_FLIP_1: case BOTH_ALORA_FLIP_2: case BOTH_ALORA_FLIP_3: @@ -6894,7 +5673,7 @@ qboolean PM_FlippingAnim( int anim ) case BOTH_FLIP_BACK3: case BOTH_WALL_FLIP_BACK1: case BOTH_ALORA_FLIP_B: - //Not really flips, but... + // Not really flips, but... case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_LEFT: case BOTH_WALL_RUN_RIGHT_STOP: @@ -6913,7 +5692,7 @@ qboolean PM_FlippingAnim( int anim ) case BOTH_JUMPFLIPSTABDOWN: case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: - //JKA + // JKA case BOTH_FORCEWALLRUNFLIP_END: case BOTH_FORCEWALLRUNFLIP_ALT: case BOTH_FLIP_ATTACK7: @@ -6924,31 +5703,27 @@ qboolean PM_FlippingAnim( int anim ) return qfalse; } -qboolean PM_WalkingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_WALK1: //# Normal walk - case BOTH_WALK2: //# Normal walk with saber - case BOTH_WALK_STAFF: //# Normal walk with staff - case BOTH_WALK_DUAL: //# Normal walk with staff - case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) - case BOTH_WALK6: //# Slow walk for Luke (cin 12) - case BOTH_WALK7: //# Fast walk - case BOTH_WALKBACK1: //# Walk1 backwards - case BOTH_WALKBACK2: //# Walk2 backwards - case BOTH_WALKBACK_STAFF: //# Walk backwards with staff - case BOTH_WALKBACK_DUAL: //# Walk backwards with dual +qboolean PM_WalkingAnim(int anim) { + switch (anim) { + case BOTH_WALK1: //# Normal walk + case BOTH_WALK2: //# Normal walk with saber + case BOTH_WALK_STAFF: //# Normal walk with staff + case BOTH_WALK_DUAL: //# Normal walk with staff + case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) + case BOTH_WALK6: //# Slow walk for Luke (cin 12) + case BOTH_WALK7: //# Fast walk + case BOTH_WALKBACK1: //# Walk1 backwards + case BOTH_WALKBACK2: //# Walk2 backwards + case BOTH_WALKBACK_STAFF: //# Walk backwards with staff + case BOTH_WALKBACK_DUAL: //# Walk backwards with dual return qtrue; break; } return qfalse; } -qboolean PM_RunningAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_RunningAnim(int anim) { + switch (anim) { case BOTH_RUN1: case BOTH_RUN2: case BOTH_RUN4: @@ -6957,24 +5732,22 @@ qboolean PM_RunningAnim( int anim ) case BOTH_RUNBACK1: case BOTH_RUNBACK2: case BOTH_RUNBACK_STAFF: - case BOTH_RUN1START: //# Start into full run1 + case BOTH_RUN1START: //# Start into full run1 case BOTH_RUN1STOP: //# Stop from full run1 case BOTH_RUNSTRAFE_LEFT1: //# Sidestep left: should loop - case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop + case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop return qtrue; break; } return qfalse; } -qboolean PM_RollingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_ROLL_F: //# Roll forward - case BOTH_ROLL_B: //# Roll backward - case BOTH_ROLL_L: //# Roll left - case BOTH_ROLL_R: //# Roll right +qboolean PM_RollingAnim(int anim) { + switch (anim) { + case BOTH_ROLL_F: //# Roll forward + case BOTH_ROLL_B: //# Roll backward + case BOTH_ROLL_L: //# Roll left + case BOTH_ROLL_R: //# Roll right case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_BROLL_L: @@ -6989,24 +5762,20 @@ qboolean PM_RollingAnim( int anim ) return qfalse; } -qboolean PM_SwimmingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SWIM_IDLE1: //# Swimming Idle 1 - case BOTH_SWIMFORWARD: //# Swim forward loop - case BOTH_SWIMBACKWARD: //# Swim backward loop +qboolean PM_SwimmingAnim(int anim) { + switch (anim) { + case BOTH_SWIM_IDLE1: //# Swimming Idle 1 + case BOTH_SWIMFORWARD: //# Swim forward loop + case BOTH_SWIMBACKWARD: //# Swim backward loop return qtrue; break; } return qfalse; } -qboolean PM_LeapingSaberAnim( int anim ) -{ - switch ( anim ) - { - //level 7 +qboolean PM_LeapingSaberAnim(int anim) { + switch (anim) { + // level 7 case BOTH_T7_BR_TL: case BOTH_T7__L_BR: case BOTH_T7__L__R: @@ -7019,11 +5788,9 @@ qboolean PM_LeapingSaberAnim( int anim ) return qfalse; } -qboolean PM_SpinningSaberAnim( int anim ) -{ - switch ( anim ) - { - //level 1 - FIXME: level 1 will have *no* spins +qboolean PM_SpinningSaberAnim(int anim) { + switch (anim) { + // level 1 - FIXME: level 1 will have *no* spins case BOTH_T1_BR_BL: case BOTH_T1__R__L: case BOTH_T1__R_BL: @@ -7036,28 +5803,28 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T1_BL_BR: case BOTH_T1_BL__R: case BOTH_T1_BL_TR: - //level 2 + // level 2 case BOTH_T2_BR__L: case BOTH_T2_BR_BL: case BOTH_T2__R_BL: case BOTH_T2__L_BR: case BOTH_T2_BL_BR: case BOTH_T2_BL__R: - //level 3 + // level 3 case BOTH_T3_BR__L: case BOTH_T3_BR_BL: case BOTH_T3__R_BL: case BOTH_T3__L_BR: case BOTH_T3_BL_BR: case BOTH_T3_BL__R: - //level 4 + // level 4 case BOTH_T4_BR__L: case BOTH_T4_BR_BL: case BOTH_T4__R_BL: case BOTH_T4__L_BR: case BOTH_T4_BL_BR: case BOTH_T4_BL__R: - //level 5 + // level 5 case BOTH_T5_BR_BL: case BOTH_T5__R__L: case BOTH_T5__R_BL: @@ -7070,7 +5837,7 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T5_BL_BR: case BOTH_T5_BL__R: case BOTH_T5_BL_TR: - //level 6 + // level 6 case BOTH_T6_BR_TL: case BOTH_T6__R_TL: case BOTH_T6__R__L: @@ -7093,7 +5860,7 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T6_BL_BR: case BOTH_T6_BL__R: case BOTH_T6_BL_TR: - //level 7 + // level 7 case BOTH_T7_BR_TL: case BOTH_T7_BR__L: case BOTH_T7_BR_BL: @@ -7111,8 +5878,8 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T7_T__BR: case BOTH_T7__L_TR: case BOTH_V7_BL_S7: - //special - //case BOTH_A2_STABBACK1: + // special + // case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: case BOTH_BUTTERFLY_LEFT: @@ -7127,8 +5894,7 @@ qboolean PM_SpinningSaberAnim( int anim ) return qfalse; } -qboolean PM_SpinningAnim( int anim ) -{ +qboolean PM_SpinningAnim(int anim) { /* switch ( anim ) { @@ -7137,91 +5903,76 @@ qboolean PM_SpinningAnim( int anim ) break; } */ - return PM_SpinningSaberAnim( anim ); + return PM_SpinningSaberAnim(anim); } -void PM_ResetAnkleAngles( void ) -{ - if ( !pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_ATST ) - { +void PM_ResetAnkleAngles(void) { + if (!pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_ATST) { return; } - if ( pm->gent->footLBone != -1 ) - { - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footLBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (pm->gent->footLBone != -1) { + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footLBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, + 0); } - if ( pm->gent->footRBone != -1 ) - { - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footRBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (pm->gent->footRBone != -1) { + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footRBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, + 0); } } -void PM_AnglesForSlope( const float yaw, const vec3_t slope, vec3_t angles ) -{ - vec3_t nvf, ovf, ovr, new_angles; - float pitch, mod, dot; +void PM_AnglesForSlope(const float yaw, const vec3_t slope, vec3_t angles) { + vec3_t nvf, ovf, ovr, new_angles; + float pitch, mod, dot; - VectorSet( angles, 0, yaw, 0 ); - AngleVectors( angles, ovf, ovr, NULL ); + VectorSet(angles, 0, yaw, 0); + AngleVectors(angles, ovf, ovr, NULL); - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod < 0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); angles[YAW] = 0; angles[PITCH] = dot * pitch; - angles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + angles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } -void PM_FootSlopeTrace( float *pDiff, float *pInterval ) -{ - vec3_t footLOrg, footROrg, footLBot, footRBot; - trace_t trace; - float diff, interval; - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { +void PM_FootSlopeTrace(float *pDiff, float *pInterval) { + vec3_t footLOrg, footROrg, footLBot, footRBot; + trace_t trace; + float diff, interval; + if (pm->gent->client->NPC_class == CLASS_ATST) { interval = 10; - } - else - { - interval = 4;//? + } else { + interval = 4; //? } - if ( pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1 ) - { - if ( pDiff != NULL ) - { + if (pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1) { + if (pDiff != NULL) { *pDiff = 0; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } return; } #if 1 - for ( int i = 0; i < 3; i++ ) - { - if ( Q_isnan( pm->gent->client->renderInfo.footLPoint[i] ) - || Q_isnan( pm->gent->client->renderInfo.footRPoint[i] ) ) - { - if ( pDiff != NULL ) - { + for (int i = 0; i < 3; i++) { + if (Q_isnan(pm->gent->client->renderInfo.footLPoint[i]) || Q_isnan(pm->gent->client->renderInfo.footRPoint[i])) { + if (pDiff != NULL) { *pDiff = 0; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } return; @@ -7229,21 +5980,19 @@ void PM_FootSlopeTrace( float *pDiff, float *pInterval ) } #else - //FIXME: these really should have been gotten on the cgame, but I guess sometimes they're not and we end up with qnan numbers! - mdxaBone_t boltMatrix; - vec3_t G2Angles = {0, pm->gent->client->ps.legsYaw, 0}; - //get the feet - gi.G2API_GetBoltMatrix( pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footLBolt, - &boltMatrix, G2Angles, pm->ps->origin, (cg.time?cg.time:level.time), - NULL, pm->gent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footLPoint ); - - gi.G2API_GetBoltMatrix( pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footRBolt, - &boltMatrix, G2Angles, pm->ps->origin, (cg.time?cg.time:level.time), - NULL, pm->gent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint ); + // FIXME: these really should have been gotten on the cgame, but I guess sometimes they're not and we end up with qnan numbers! + mdxaBone_t boltMatrix; + vec3_t G2Angles = {0, pm->gent->client->ps.legsYaw, 0}; + // get the feet + gi.G2API_GetBoltMatrix(pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footLBolt, &boltMatrix, G2Angles, pm->ps->origin, + (cg.time ? cg.time : level.time), NULL, pm->gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pm->gent->client->renderInfo.footLPoint); + + gi.G2API_GetBoltMatrix(pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footRBolt, &boltMatrix, G2Angles, pm->ps->origin, + (cg.time ? cg.time : level.time), NULL, pm->gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint); #endif - //NOTE: on AT-STs, rotating the foot moves this point, so it will wiggle... + // NOTE: on AT-STs, rotating the foot moves this point, so it will wiggle... // we have to do this extra work (more G2 transforms) to stop the wiggle... is it worth it? /* if ( pm->gent->client->NPC_class == CLASS_ATST ) @@ -7264,82 +6013,74 @@ void PM_FootSlopeTrace( float *pDiff, float *pInterval ) gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint ); } */ - //get these on the cgame and store it, save ourselves a ghoul2 construct skel call - VectorCopy( pm->gent->client->renderInfo.footLPoint, footLOrg ); - VectorCopy( pm->gent->client->renderInfo.footRPoint, footROrg ); + // get these on the cgame and store it, save ourselves a ghoul2 construct skel call + VectorCopy(pm->gent->client->renderInfo.footLPoint, footLOrg); + VectorCopy(pm->gent->client->renderInfo.footRPoint, footROrg); - //step 2: adjust foot tag z height to bottom of bbox+1 + // step 2: adjust foot tag z height to bottom of bbox+1 footLOrg[2] = pm->gent->currentOrigin[2] + pm->gent->mins[2] + 1; footROrg[2] = pm->gent->currentOrigin[2] + pm->gent->mins[2] + 1; - VectorSet( footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval*10 ); - VectorSet( footRBot, footROrg[0], footROrg[1], footROrg[2] - interval*10 ); + VectorSet(footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval * 10); + VectorSet(footRBot, footROrg[0], footROrg[1], footROrg[2] - interval * 10); - //step 3: trace down from each, find difference + // step 3: trace down from each, find difference vec3_t footMins, footMaxs; vec3_t footLSlope, footRSlope; - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { - VectorSet( footMins, -16, -16, 0 ); - VectorSet( footMaxs, 16, 16, 1 ); - } - else - { - VectorSet( footMins, -3, -3, 0 ); - VectorSet( footMaxs, 3, 3, 1 ); + if (pm->gent->client->NPC_class == CLASS_ATST) { + VectorSet(footMins, -16, -16, 0); + VectorSet(footMaxs, 16, 16, 1); + } else { + VectorSet(footMins, -3, -3, 0); + VectorSet(footMaxs, 3, 3, 1); } - pm->trace( &trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); - VectorCopy( trace.endpos, footLBot ); - VectorCopy( trace.plane.normal, footLSlope ); + pm->trace(&trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + VectorCopy(trace.endpos, footLBot); + VectorCopy(trace.plane.normal, footLSlope); - pm->trace( &trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0 ); - VectorCopy( trace.endpos, footRBot ); - VectorCopy( trace.plane.normal, footRSlope ); + pm->trace(&trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + VectorCopy(trace.endpos, footRBot); + VectorCopy(trace.plane.normal, footRSlope); diff = footLBot[2] - footRBot[2]; - //optional step: for atst, tilt the footpads to match the slopes under it... - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { + // optional step: for atst, tilt the footpads to match the slopes under it... + if (pm->gent->client->NPC_class == CLASS_ATST) { vec3_t footAngles; - if ( !VectorCompare( footLSlope, vec3_origin ) ) - {//rotate the ATST's left foot pad to match the slope - PM_AnglesForSlope( pm->gent->client->renderInfo.legsYaw, footLSlope, footAngles ); - //Hmm... lerp this? - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footLBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (!VectorCompare(footLSlope, vec3_origin)) { // rotate the ATST's left foot pad to match the slope + PM_AnglesForSlope(pm->gent->client->renderInfo.legsYaw, footLSlope, footAngles); + // Hmm... lerp this? + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footLBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, + 0, 0); } - if ( !VectorCompare( footRSlope, vec3_origin ) ) - {//rotate the ATST's right foot pad to match the slope - PM_AnglesForSlope( pm->gent->client->renderInfo.legsYaw, footRSlope, footAngles ); - //Hmm... lerp this? - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footRBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (!VectorCompare(footRSlope, vec3_origin)) { // rotate the ATST's right foot pad to match the slope + PM_AnglesForSlope(pm->gent->client->renderInfo.legsYaw, footRSlope, footAngles); + // Hmm... lerp this? + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footRBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, + 0, 0); } } - if ( pDiff != NULL ) - { + if (pDiff != NULL) { *pDiff = diff; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } } -qboolean PM_InSlopeAnim( int anim ) -{ - switch ( anim ) - { - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left +qboolean PM_InSlopeAnim(int anim) { + switch (anim) { + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left case LEGS_S1_LUP1: case LEGS_S1_LUP2: case LEGS_S1_LUP3: @@ -7406,26 +6147,22 @@ qboolean PM_InSlopeAnim( int anim ) return qfalse; } -qboolean PM_SaberStanceAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_STAND1://not really a saberstance anim, actually... "saber off" stance - case BOTH_STAND2://single-saber, medium style - case BOTH_SABERFAST_STANCE://single-saber, fast style - case BOTH_SABERSLOW_STANCE://single-saber, strong style - case BOTH_SABERSTAFF_STANCE://saber staff style - case BOTH_SABERDUAL_STANCE://dual saber style +qboolean PM_SaberStanceAnim(int anim) { + switch (anim) { + case BOTH_STAND1: // not really a saberstance anim, actually... "saber off" stance + case BOTH_STAND2: // single-saber, medium style + case BOTH_SABERFAST_STANCE: // single-saber, fast style + case BOTH_SABERSLOW_STANCE: // single-saber, strong style + case BOTH_SABERSTAFF_STANCE: // saber staff style + case BOTH_SABERDUAL_STANCE: // dual saber style return qtrue; break; } return qfalse; } -qboolean PM_SaberDrawPutawayAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_SaberDrawPutawayAnim(int anim) { + switch (anim) { case BOTH_STAND1TO2: case BOTH_STAND2TO1: case BOTH_S1_S7: @@ -7438,86 +6175,56 @@ qboolean PM_SaberDrawPutawayAnim( int anim ) return qfalse; } -#define SLOPE_RECALC_INT 100 -extern qboolean G_StandardHumanoid( gentity_t *self ); -qboolean PM_AdjustStandAnimForSlope( void ) -{ - if ( !pm->gent || !pm->gent->client ) - { +#define SLOPE_RECALC_INT 100 +extern qboolean G_StandardHumanoid(gentity_t *self); +qboolean PM_AdjustStandAnimForSlope(void) { + if (!pm->gent || !pm->gent->client) { return qfalse; } - if ( pm->gent->client->NPC_class != CLASS_ATST - && (!pm->gent||!G_StandardHumanoid( pm->gent )) ) - {//only ATST and player does this + if (pm->gent->client->NPC_class != CLASS_ATST && (!pm->gent || !G_StandardHumanoid(pm->gent))) { // only ATST and player does this return qfalse; } - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && (!cg.renderingThirdPerson || cg.zoomMode) ) - {//first person doesn't do this + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && (!cg.renderingThirdPerson || cg.zoomMode)) { // first person doesn't do this return qfalse; } - if ( pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1 ) - {//need these bolts! + if (pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1) { // need these bolts! return qfalse; } - //step 1: find the 2 foot tags - float diff; - float interval; - PM_FootSlopeTrace( &diff, &interval ); + // step 1: find the 2 foot tags + float diff; + float interval; + PM_FootSlopeTrace(&diff, &interval); - //step 4: based on difference, choose one of the left/right slope-match intervals - int destAnim; - if ( diff >= interval*5 ) - { + // step 4: based on difference, choose one of the left/right slope-match intervals + int destAnim; + if (diff >= interval * 5) { destAnim = LEGS_LEFTUP5; - } - else if ( diff >= interval*4 ) - { + } else if (diff >= interval * 4) { destAnim = LEGS_LEFTUP4; - } - else if ( diff >= interval*3 ) - { + } else if (diff >= interval * 3) { destAnim = LEGS_LEFTUP3; - } - else if ( diff >= interval*2 ) - { + } else if (diff >= interval * 2) { destAnim = LEGS_LEFTUP2; - } - else if ( diff >= interval ) - { + } else if (diff >= interval) { destAnim = LEGS_LEFTUP1; - } - else if ( diff <= interval*-5 ) - { + } else if (diff <= interval * -5) { destAnim = LEGS_RIGHTUP5; - } - else if ( diff <= interval*-4 ) - { + } else if (diff <= interval * -4) { destAnim = LEGS_RIGHTUP4; - } - else if ( diff <= interval*-3 ) - { + } else if (diff <= interval * -3) { destAnim = LEGS_RIGHTUP3; - } - else if ( diff <= interval*-2 ) - { + } else if (diff <= interval * -2) { destAnim = LEGS_RIGHTUP2; - } - else if ( diff <= interval*-1 ) - { + } else if (diff <= interval * -1) { destAnim = LEGS_RIGHTUP1; - } - else - { + } else { return qfalse; } int legsAnim = pm->ps->legsAnim; - if ( pm->gent->client->NPC_class != CLASS_ATST ) - { - //adjust for current legs anim - switch ( legsAnim ) - { + if (pm->gent->client->NPC_class != CLASS_ATST) { + // adjust for current legs anim + switch (legsAnim) { case BOTH_STAND1: case LEGS_S1_LUP1: case LEGS_S1_LUP2: @@ -7529,24 +6236,24 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S1_RUP3: case LEGS_S1_RUP4: case LEGS_S1_RUP5: - destAnim = LEGS_S1_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S1_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND2: case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: case BOTH_CROUCH1: - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left - //fine + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left + // fine break; case BOTH_STAND3: case LEGS_S3_LUP1: @@ -7559,7 +6266,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S3_RUP3: case LEGS_S3_RUP4: case LEGS_S3_RUP5: - destAnim = LEGS_S3_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S3_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND4: case LEGS_S4_LUP1: @@ -7572,7 +6279,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S4_RUP3: case LEGS_S4_RUP4: case LEGS_S4_RUP5: - destAnim = LEGS_S4_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S4_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND5: case LEGS_S5_LUP1: @@ -7585,7 +6292,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S5_RUP3: case LEGS_S5_RUP4: case LEGS_S5_RUP5: - destAnim = LEGS_S5_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S5_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_SABERDUAL_STANCE: case LEGS_S6_LUP1: @@ -7598,7 +6305,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S6_RUP3: case LEGS_S6_RUP4: case LEGS_S6_RUP5: - destAnim = LEGS_S6_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S6_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_SABERSTAFF_STANCE: case LEGS_S7_LUP1: @@ -7611,7 +6318,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S7_RUP3: case LEGS_S7_RUP4: case LEGS_S7_RUP5: - destAnim = LEGS_S7_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S7_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND6: default: @@ -7619,93 +6326,57 @@ qboolean PM_AdjustStandAnimForSlope( void ) break; } } - //step 5: based on the chosen interval and the current legsAnim, pick the correct anim - //step 6: increment/decrement to the dest anim, not instant - if ( (legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) - || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) - || (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) - || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) - || (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5) - || (legsAnim >= LEGS_S6_LUP1 && legsAnim <= LEGS_S6_LUP5) - || (legsAnim >= LEGS_S7_LUP1 && legsAnim <= LEGS_S7_LUP5) ) - {//already in left-side up - if ( destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + // step 5: based on the chosen interval and the current legsAnim, pick the correct anim + // step 6: increment/decrement to the dest anim, not instant + if ((legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) || + (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) || + (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5) || (legsAnim >= LEGS_S6_LUP1 && legsAnim <= LEGS_S6_LUP5) || + (legsAnim >= LEGS_S7_LUP1 && legsAnim <= LEGS_S7_LUP5)) { // already in left-side up + if (destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim++; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if (destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim--; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - { + } else { destAnim = legsAnim; } - } - else if ( (legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) - || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) - || (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) - || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) - || (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5) - || (legsAnim >= LEGS_S6_RUP1 && legsAnim <= LEGS_S6_RUP5) - || (legsAnim >= LEGS_S7_RUP1 && legsAnim <= LEGS_S7_RUP5) ) - {//already in right-side up - if ( destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if ((legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) || + (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) || + (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5) || (legsAnim >= LEGS_S6_RUP1 && legsAnim <= LEGS_S6_RUP5) || + (legsAnim >= LEGS_S7_RUP1 && legsAnim <= LEGS_S7_RUP5)) { // already in right-side up + if (destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim++; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if (destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim--; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - { + } else { destAnim = legsAnim; } - } - else - {//in a stand of some sort? - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( legsAnim == BOTH_STAND1 || legsAnim == BOTH_STAND2 || legsAnim == BOTH_CROUCH1IDLE ) - { - if ( destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5 ) - {//going into left side up + } else { // in a stand of some sort? + if (pm->gent->client->NPC_class == CLASS_ATST) { + if (legsAnim == BOTH_STAND1 || legsAnim == BOTH_STAND2 || legsAnim == BOTH_CROUCH1IDLE) { + if (destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5) { // going into left side up destAnim = LEGS_LEFTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5) { // going into right side up destAnim = LEGS_RIGHTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } } - } - else - { - switch ( legsAnim ) - { + } else { + switch (legsAnim) { case BOTH_STAND1: - if ( destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5) { // going into left side up destAnim = LEGS_S1_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5) { // going into right side up destAnim = LEGS_S1_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -7713,98 +6384,68 @@ qboolean PM_AdjustStandAnimForSlope( void ) case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: - if ( destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5 ) - {//going into left side up + if (destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5) { // going into left side up destAnim = LEGS_LEFTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5) { // going into right side up destAnim = LEGS_RIGHTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND3: - if ( destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5) { // going into left side up destAnim = LEGS_S3_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5) { // going into right side up destAnim = LEGS_S3_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND4: - if ( destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5) { // going into left side up destAnim = LEGS_S4_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5) { // going into right side up destAnim = LEGS_S4_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND5: - if ( destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5) { // going into left side up destAnim = LEGS_S5_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5) { // going into right side up destAnim = LEGS_S5_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_SABERDUAL_STANCE: - if ( destAnim >= LEGS_S6_LUP1 && destAnim <= LEGS_S6_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S6_LUP1 && destAnim <= LEGS_S6_LUP5) { // going into left side up destAnim = LEGS_S6_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S6_RUP1 && destAnim <= LEGS_S6_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S6_RUP1 && destAnim <= LEGS_S6_RUP5) { // going into right side up destAnim = LEGS_S6_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_SABERSTAFF_STANCE: - if ( destAnim >= LEGS_S7_LUP1 && destAnim <= LEGS_S7_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S7_LUP1 && destAnim <= LEGS_S7_LUP5) { // going into left side up destAnim = LEGS_S7_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S7_RUP1 && destAnim <= LEGS_S7_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S7_RUP1 && destAnim <= LEGS_S7_RUP5) { // going into right side up destAnim = LEGS_S7_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -7815,50 +6456,39 @@ qboolean PM_AdjustStandAnimForSlope( void ) } } } - //step 7: set the anim - PM_SetAnim( pm, SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL ); + // step 7: set the anim + PM_SetAnim(pm, SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL); return qtrue; } -void PM_JetPackAnim( void ) -{ - if ( !PM_ForceJumpingAnim( pm->ps->legsAnim ) )//haven't started forcejump yet +void PM_JetPackAnim(void) { + if (!PM_ForceJumpingAnim(pm->ps->legsAnim)) // haven't started forcejump yet { vec3_t facingFwd, facingRight, facingAngles = {0, pm->ps->viewangles[YAW], 0}; int anim = BOTH_FORCEJUMP1; - AngleVectors( facingAngles, facingFwd, facingRight, NULL ); - float dotR = DotProduct( facingRight, pm->ps->velocity ); - float dotF = DotProduct( facingFwd, pm->ps->velocity ); - if ( fabs(dotR) > fabs(dotF) * 1.5 ) - { - if ( dotR > 150 ) - { + AngleVectors(facingAngles, facingFwd, facingRight, NULL); + float dotR = DotProduct(facingRight, pm->ps->velocity); + float dotF = DotProduct(facingFwd, pm->ps->velocity); + if (fabs(dotR) > fabs(dotF) * 1.5) { + if (dotR > 150) { anim = BOTH_FORCEJUMPRIGHT1; - } - else if ( dotR < -150 ) - { + } else if (dotR < -150) { anim = BOTH_FORCEJUMPLEFT1; } - } - else - { - if ( dotF > 150 ) - { + } else { + if (dotF > 150) { anim = BOTH_FORCEJUMP1; - } - else if ( dotF < -150 ) - { + } else if (dotF < -150) { anim = BOTH_FORCEJUMPBACK1; } } int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } /* else @@ -7896,28 +6526,19 @@ void PM_JetPackAnim( void ) } */ } -void PM_SwimFloatAnim( void ) -{ +void PM_SwimFloatAnim(void) { int legsAnim = pm->ps->legsAnim; - //FIXME: no start or stop anims - if ( pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else - {//stopping - if ( legsAnim == BOTH_SWIMFORWARD ) - {//I was swimming - if ( !pm->ps->legsAnimTimer ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); + // FIXME: no start or stop anims + if (pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else { // stopping + if (legsAnim == BOTH_SWIMFORWARD) { // I was swimming + if (!pm->ps->legsAnimTimer) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); } - } - else - {//idle - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//not crouching - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); + } else { // idle + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // not crouching + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); } } } @@ -7928,227 +6549,165 @@ void PM_SwimFloatAnim( void ) PM_Footsteps =============== */ -static void PM_Footsteps( void ) -{ - float bobmove; - int old, oldAnim; - qboolean footstep = qfalse; - qboolean validNPC = qfalse; - qboolean flipping = qfalse; - int setAnimFlags = SETANIM_FLAG_NORMAL; - - if( pm->gent == NULL || pm->gent->client == NULL ) +static void PM_Footsteps(void) { + float bobmove; + int old, oldAnim; + qboolean footstep = qfalse; + qboolean validNPC = qfalse; + qboolean flipping = qfalse; + int setAnimFlags = SETANIM_FLAG_NORMAL; + + if (pm->gent == NULL || pm->gent->client == NULL) return; - if ( (pm->ps->eFlags&EF_HELD_BY_WAMPA) ) - { - PM_SetAnim( pm, SETANIM_BOTH, BOTH_HANG_IDLE, SETANIM_FLAG_NORMAL ); - if ( pm->ps->legsAnim == BOTH_HANG_IDLE ) - { - if ( pm->ps->torsoAnimTimer < 100 ) - { + if ((pm->ps->eFlags & EF_HELD_BY_WAMPA)) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_HANG_IDLE, SETANIM_FLAG_NORMAL); + if (pm->ps->legsAnim == BOTH_HANG_IDLE) { + if (pm->ps->torsoAnimTimer < 100) { pm->ps->torsoAnimTimer = 100; } - if ( pm->ps->legsAnimTimer < 100 ) - { + if (pm->ps->legsAnimTimer < 100) { pm->ps->legsAnimTimer = 100; } } return; } - if ( PM_SpinningSaberAnim( pm->ps->legsAnim ) && pm->ps->legsAnimTimer ) - {//spinning + if (PM_SpinningSaberAnim(pm->ps->legsAnim) && pm->ps->legsAnimTimer) { // spinning return; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return; } - if ( (pm->ps->eFlags&EF_FORCE_DRAINED) ) - {//being drained - //PM_SetAnim( pm, SETANIM_LEGS, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((pm->ps->eFlags & EF_FORCE_DRAINED)) { // being drained + // PM_SetAnim( pm, SETANIM_LEGS, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if ( (pm->ps->forcePowersActive&(1<ps->forceDrainEntityNum < ENTITYNUM_WORLD ) - {//draining - //PM_SetAnim( pm, SETANIM_LEGS, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((pm->ps->forcePowersActive & (1 << FP_DRAIN)) && pm->ps->forceDrainEntityNum < ENTITYNUM_WORLD) { // draining + // PM_SetAnim( pm, SETANIM_LEGS, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; - } - else if (pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_KNEEL) - {//kneeling + } else if (pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_KNEEL) { // kneeling return; } - if( pm->gent->NPC != NULL ) - { + if (pm->gent->NPC != NULL) { validNPC = qtrue; } pm->gent->client->renderInfo.legsFpsMod = 1.0f; - //PM_ResetAnkleAngles(); + // PM_ResetAnkleAngles(); // // calculate speed and cycle to be used for // all cyclic walking effects // - pm->xyspeed = sqrt( pm->ps->velocity[0] * pm->ps->velocity[0] - + pm->ps->velocity[1] * pm->ps->velocity[1] ); - - if ( pm->ps->legsAnim == BOTH_FLIP_F || - pm->ps->legsAnim == BOTH_FLIP_B || - pm->ps->legsAnim == BOTH_FLIP_L || - pm->ps->legsAnim == BOTH_FLIP_R || - pm->ps->legsAnim == BOTH_ALORA_FLIP_1 || - pm->ps->legsAnim == BOTH_ALORA_FLIP_2 || - pm->ps->legsAnim == BOTH_ALORA_FLIP_3 ) - { + pm->xyspeed = sqrt(pm->ps->velocity[0] * pm->ps->velocity[0] + pm->ps->velocity[1] * pm->ps->velocity[1]); + + if (pm->ps->legsAnim == BOTH_FLIP_F || pm->ps->legsAnim == BOTH_FLIP_B || pm->ps->legsAnim == BOTH_FLIP_L || pm->ps->legsAnim == BOTH_FLIP_R || + pm->ps->legsAnim == BOTH_ALORA_FLIP_1 || pm->ps->legsAnim == BOTH_ALORA_FLIP_2 || pm->ps->legsAnim == BOTH_ALORA_FLIP_3) { flipping = qtrue; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || ( pm->watertype & CONTENTS_LADDER ) - || pm->ps->waterHeightLevel >= WHL_TORSO ) - {//in air or submerged in water or in ladder + if (pm->ps->groundEntityNum == ENTITYNUM_NONE || (pm->watertype & CONTENTS_LADDER) || + pm->ps->waterHeightLevel >= WHL_TORSO) { // in air or submerged in water or in ladder // airborne leaves position in cycle intact, but doesn't advance - if ( pm->waterlevel > 0 ) - { - if ( pm->watertype & CONTENTS_LADDER ) - {//FIXME: check for watertype, save waterlevel for whether to play - //the get off ladder transition anim! - if ( pm->ps->velocity[2] ) - {//going up or down it - int anim; - if ( pm->ps->velocity[2] > 0 ) - { + if (pm->waterlevel > 0) { + if (pm->watertype & CONTENTS_LADDER) { // FIXME: check for watertype, save waterlevel for whether to play + // the get off ladder transition anim! + if (pm->ps->velocity[2]) { // going up or down it + int anim; + if (pm->ps->velocity[2] > 0) { anim = BOTH_LADDER_UP1; - } - else - { + } else { anim = BOTH_LADDER_DWN1; } - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( pm->waterlevel >= 2 ) //arms on ladder + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (pm->waterlevel >= 2) // arms on ladder { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if (fabs(pm->ps->velocity[2]) >5) { - bobmove = 0.005 * fabs(pm->ps->velocity[2]); // climbing bobs slow + if (fabs(pm->ps->velocity[2]) > 5) { + bobmove = 0.005 * fabs(pm->ps->velocity[2]); // climbing bobs slow if (bobmove > 0.3) bobmove = 0.3F; goto DoFootSteps; } - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); pm->ps->legsAnimTimer += 300; - if ( pm->waterlevel >= 2 ) //arms on ladder + if (pm->waterlevel >= 2) // arms on ladder { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); pm->ps->torsoAnimTimer += 300; } } return; - } - else if ( pm->ps->waterHeightLevel >= WHL_TORSO - && ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - ||pm->ps->weapon==WP_SABER||pm->ps->weapon==WP_NONE||pm->ps->weapon==WP_MELEE) )//pm->waterlevel > 1 ) //in deep water - { - if ( !PM_ForceJumpingUp( pm->gent ) ) - { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE && (pm->ps->pm_flags&PMF_DUCKED) ) - { - if ( !flipping ) - {//you can crouch under water if feet are on ground - if ( pm->cmd.forwardmove || pm->cmd.rightmove ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALKBACK,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALK,setAnimFlags); + } else if (pm->ps->waterHeightLevel >= WHL_TORSO && + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || pm->ps->weapon == WP_SABER || pm->ps->weapon == WP_NONE || + pm->ps->weapon == WP_MELEE)) // pm->waterlevel > 1 ) //in deep water + { + if (!PM_ForceJumpingUp(pm->gent)) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE && (pm->ps->pm_flags & PMF_DUCKED)) { + if (!flipping) { // you can crouch under water if feet are on ground + if (pm->cmd.forwardmove || pm->cmd.rightmove) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); } - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } return; } } PM_SwimFloatAnim(); - if ( pm->ps->legsAnim != BOTH_SWIM_IDLE1 ) - {//moving + if (pm->ps->legsAnim != BOTH_SWIM_IDLE1) { // moving old = pm->ps->bobCycle; - bobmove = 0.15f; // swim is a slow cycle - pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255; + bobmove = 0.15f; // swim is a slow cycle + pm->ps->bobCycle = (int)(old + bobmove * pml.msec) & 255; // if we just crossed a cycle boundary, play an apropriate footstep event - if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) - { - PM_AddEvent( EV_SWIM ); + if (((old + 64) ^ (pm->ps->bobCycle + 64)) & 128) { + PM_AddEvent(EV_SWIM); } } } return; - } - else - {//hmm, in water, but not high enough to swim - //fall through to walk/run/stand - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//unless in the air - //NOTE: this is a dupe of the code just below... for when you are not in the water at all - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if ( !flipping ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); - } - } - else if ( pm->ps->gravity <= 0 )//FIXME: or just less than normal? + } else { // hmm, in water, but not high enough to swim + // fall through to walk/run/stand + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // unless in the air + // NOTE: this is a dupe of the code just below... for when you are not in the water at all + if (pm->ps->pm_flags & PMF_DUCKED) { + if (!flipping) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); + } + } else if (pm->ps->gravity <= 0) // FIXME: or just less than normal? { - if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT ||pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) - && pm->gent->client->moveType == MT_FLYSWIM ) - {//flying around with jetpack - //do something else? + if (pm->gent && pm->gent->client && + (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + pm->gent->client->moveType == MT_FLYSWIM) { // flying around with jetpack + // do something else? PM_JetPackAnim(); - } - else - { + } else { PM_SwimFloatAnim(); } } return; } } - } - else - { - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if ( !flipping ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else { + if (pm->ps->pm_flags & PMF_DUCKED) { + if (!flipping) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->ps->gravity <= 0 )//FIXME: or just less than normal? + } else if (pm->ps->gravity <= 0) // FIXME: or just less than normal? { - if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_BOBAFETT||pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) - && pm->gent->client->moveType == MT_FLYSWIM ) - {//flying around with jetpack - //do something else? + if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_BOBAFETT || pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) && + pm->gent->client->moveType == MT_FLYSWIM) { // flying around with jetpack + // do something else? PM_JetPackAnim(); - } - else - { + } else { PM_SwimFloatAnim(); } } @@ -8156,99 +6715,65 @@ static void PM_Footsteps( void ) } } - if ( PM_SwimmingAnim( pm->ps->legsAnim ) && pm->waterlevel < 2 ) - {//legs are in swim anim, and not swimming, be sure to override it + if (PM_SwimmingAnim(pm->ps->legsAnim) && pm->waterlevel < 2) { // legs are in swim anim, and not swimming, be sure to override it setAnimFlags |= SETANIM_FLAG_OVERRIDE; } // if not trying to move - if ( !pm->cmd.forwardmove && !pm->cmd.rightmove ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (!pm->cmd.forwardmove && !pm->cmd.rightmove) { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if( !PM_InOnGroundAnim( pm->ps ) ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->pm_flags & PMF_DUCKED) { + if (!PM_InOnGroundAnim(pm->ps)) { + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } } - } - else - { - if ( pm->ps->legsAnimTimer && PM_LandingAnim( pm->ps->legsAnim ) ) - {//still in a landing anim, let it play + } else { + if (pm->ps->legsAnimTimer && PM_LandingAnim(pm->ps->legsAnim)) { // still in a landing anim, let it play return; } - if ( pm->ps->legsAnimTimer - && (pm->ps->legsAnim == BOTH_THERMAL_READY - ||pm->ps->legsAnim == BOTH_THERMAL_THROW - ||pm->ps->legsAnim == BOTH_ATTACK10) ) - {//still in a thermal anim, let it play + if (pm->ps->legsAnimTimer && (pm->ps->legsAnim == BOTH_THERMAL_READY || pm->ps->legsAnim == BOTH_THERMAL_THROW || + pm->ps->legsAnim == BOTH_ATTACK10)) { // still in a thermal anim, let it play return; } qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {//NOTE: stand1 is with the helmet retracted, stand1to2 is the helmet going into place - PM_SetAnim( pm, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_NORMAL ); - } - else if ( pm->ps->weapon == WP_SABER - && pm->ps->saberInFlight - && saberInAir - && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - if ( pm->ps->legsAnim != BOTH_LOSE_SABER - || !pm->ps->legsAnimTimer ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SABERPULL,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && + pm->gent->client->NPC_class == CLASS_GALAKMECH) { // NOTE: stand1 is with the helmet retracted, stand1to2 is the helmet going into place + PM_SetAnim(pm, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { + if (!PM_AdjustStandAnimForSlope()) { + if (pm->ps->legsAnim != BOTH_LOSE_SABER || !pm->ps->legsAnimTimer) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SABERPULL, SETANIM_FLAG_NORMAL); } } - } - else if ( (pm->ps->weapon == WP_SABER - &&pm->ps->SaberLength()>0 - &&!pm->ps->saberInFlight - &&!PM_SaberDrawPutawayAnim( pm->ps->legsAnim )) ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { + } else if ((pm->ps->weapon == WP_SABER && pm->ps->SaberLength() > 0 && !pm->ps->saberInFlight && !PM_SaberDrawPutawayAnim(pm->ps->legsAnim))) { + if (!PM_AdjustStandAnimForSlope()) { int legsAnim; - if ( (pm->ps->torsoAnim == BOTH_SPINATTACK6 - || pm->ps->torsoAnim == BOTH_SPINATTACK7 - || PM_SaberInAttack( pm->ps->saberMove ) - || PM_SaberInTransitionAny( pm->ps->saberMove )) - && pm->ps->legsAnim != BOTH_FORCELONGLEAP_LAND - && (pm->ps->groundEntityNum == ENTITYNUM_NONE//in air - || (!PM_JumpingAnim( pm->ps->torsoAnim )&&!PM_InAirKickingAnim( pm->ps->torsoAnim ))) )//OR: on ground and torso not in a jump anim + if ((pm->ps->torsoAnim == BOTH_SPINATTACK6 || pm->ps->torsoAnim == BOTH_SPINATTACK7 || PM_SaberInAttack(pm->ps->saberMove) || + PM_SaberInTransitionAny(pm->ps->saberMove)) && + pm->ps->legsAnim != BOTH_FORCELONGLEAP_LAND && + (pm->ps->groundEntityNum == ENTITYNUM_NONE // in air + || (!PM_JumpingAnim(pm->ps->torsoAnim) && !PM_InAirKickingAnim(pm->ps->torsoAnim)))) // OR: on ground and torso not in a jump anim { legsAnim = pm->ps->torsoAnim; - } - else - { - switch ( pm->ps->saberAnimLevel ) - { + } else { + switch (pm->ps->saberAnimLevel) { case SS_FAST: case SS_TAVION: legsAnim = BOTH_SABERFAST_STANCE; @@ -8270,70 +6795,45 @@ static void PM_Footsteps( void ) break; } } - PM_SetAnim(pm,SETANIM_LEGS,legsAnim,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_LEGS, legsAnim, SETANIM_FLAG_NORMAL); } - } - else if( (validNPC && pm->ps->weapon > WP_SABER && pm->ps->weapon < WP_DET_PACK ))//Being careful or carrying a 2-handed weapon - {//Squadmates use BOTH_STAND3 + } else if ((validNPC && pm->ps->weapon > WP_SABER && pm->ps->weapon < WP_DET_PACK)) // Being careful or carrying a 2-handed weapon + { // Squadmates use BOTH_STAND3 oldAnim = pm->ps->legsAnim; - if(oldAnim != BOTH_GUARD_LOOKAROUND1 && oldAnim != BOTH_GUARD_IDLE1 - && oldAnim != BOTH_STAND2TO4 - && oldAnim != BOTH_STAND4TO2 && oldAnim != BOTH_STAND4 ) - {//Don't auto-override the guard idles - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND3,SETANIM_FLAG_NORMAL); - //if(oldAnim != BOTH_STAND2 && pm->ps->legsAnim == BOTH_STAND2) + if (oldAnim != BOTH_GUARD_LOOKAROUND1 && oldAnim != BOTH_GUARD_IDLE1 && oldAnim != BOTH_STAND2TO4 && oldAnim != BOTH_STAND4TO2 && + oldAnim != BOTH_STAND4) { // Don't auto-override the guard idles + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND3, SETANIM_FLAG_NORMAL); + // if(oldAnim != BOTH_STAND2 && pm->ps->legsAnim == BOTH_STAND2) //{ // pm->ps->legsAnimTimer = 500; - //} + // } } } - } - else - { - if ( !PM_AdjustStandAnimForSlope() ) - { + } else { + if (!PM_AdjustStandAnimForSlope()) { // FIXME: Do we need this here... The imps stand is 4, not 1... - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_IMPERIAL ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND4,SETANIM_FLAG_NORMAL); - } - else if ( pm->ps->weapon == WP_TUSKEN_STAFF ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - { - if ( pm->gent->count ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND4,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_IMPERIAL) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->weapon == WP_TUSKEN_STAFF) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { + if (pm->gent->count) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND4, SETANIM_FLAG_NORMAL); + } else if (pm->gent->enemy || pm->gent->wait) { // have an enemy or have had one since we spawned + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND2, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - else if ( pm->gent->enemy || pm->gent->wait ) - {//have an enemy or have had one since we spawned - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND2,SETANIM_FLAG_NORMAL); + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA) { + if (pm->gent->count) { // holding a victim + PM_SetAnim(pm, SETANIM_LEGS, BOTH_HOLD_IDLE /*BOTH_STAND2*/, SETANIM_FLAG_NORMAL); + } else { // not holding a victim + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA ) - { - if ( pm->gent->count ) - {//holding a victim - PM_SetAnim(pm,SETANIM_LEGS,BOTH_HOLD_IDLE/*BOTH_STAND2*/,SETANIM_FLAG_NORMAL); - } - else - {//not holding a victim - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } } @@ -8342,85 +6842,57 @@ static void PM_Footsteps( void ) return; } - //maybe call this every frame, even when moving? - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - PM_FootSlopeTrace( NULL, NULL ); + // maybe call this every frame, even when moving? + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + PM_FootSlopeTrace(NULL, NULL); } - //trying to move laterally - if ( (pm->ps->eFlags&EF_IN_ATST) - || (pm->gent&&pm->gent->client&&pm->gent->client->NPC_class==CLASS_RANCOR)//does this catch NPCs, too? - || (pm->gent&&pm->gent->client&&pm->gent->client->NPC_class==CLASS_WAMPA) )//does this catch NPCs, too? - {//atst, Rancor & Wampa, only override turn anims on legs (no torso) - if ( pm->ps->legsAnim == BOTH_TURN_LEFT1 || - pm->ps->legsAnim == BOTH_TURN_RIGHT1 ) - {//moving overrides turning + // trying to move laterally + if ((pm->ps->eFlags & EF_IN_ATST) || (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) // does this catch NPCs, too? + || (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA)) // does this catch NPCs, too? + { // atst, Rancor & Wampa, only override turn anims on legs (no torso) + if (pm->ps->legsAnim == BOTH_TURN_LEFT1 || pm->ps->legsAnim == BOTH_TURN_RIGHT1) { // moving overrides turning setAnimFlags |= SETANIM_FLAG_OVERRIDE; } - } - else - {//all other NPCs... - if ( (PM_InSaberAnim( pm->ps->legsAnim ) && !PM_SpinningSaberAnim( pm->ps->legsAnim )) - || PM_SaberStanceAnim( pm->ps->legsAnim ) - || PM_SaberDrawPutawayAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_SPINATTACK6//not a full-body spin, just spinning the saber - || pm->ps->legsAnim == BOTH_SPINATTACK7//not a full-body spin, just spinning the saber - || pm->ps->legsAnim == BOTH_BUTTON_HOLD - || pm->ps->legsAnim == BOTH_BUTTON_RELEASE - || pm->ps->legsAnim == BOTH_THERMAL_READY - || pm->ps->legsAnim == BOTH_THERMAL_THROW - || pm->ps->legsAnim == BOTH_ATTACK10 - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_PainAnim( pm->ps->legsAnim ) - || PM_ForceAnim( pm->ps->legsAnim )) - {//legs are in a saber anim, and not spinning, be sure to override it + } else { // all other NPCs... + if ((PM_InSaberAnim(pm->ps->legsAnim) && !PM_SpinningSaberAnim(pm->ps->legsAnim)) || PM_SaberStanceAnim(pm->ps->legsAnim) || + PM_SaberDrawPutawayAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_SPINATTACK6 // not a full-body spin, just spinning the saber + || pm->ps->legsAnim == BOTH_SPINATTACK7 // not a full-body spin, just spinning the saber + || pm->ps->legsAnim == BOTH_BUTTON_HOLD || pm->ps->legsAnim == BOTH_BUTTON_RELEASE || pm->ps->legsAnim == BOTH_THERMAL_READY || + pm->ps->legsAnim == BOTH_THERMAL_THROW || pm->ps->legsAnim == BOTH_ATTACK10 || PM_LandingAnim(pm->ps->legsAnim) || PM_PainAnim(pm->ps->legsAnim) || + PM_ForceAnim(pm->ps->legsAnim)) { // legs are in a saber anim, and not spinning, be sure to override it setAnimFlags |= SETANIM_FLAG_OVERRIDE; } } - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - bobmove = 0.5; // ducked characters bob much faster - if( !PM_InOnGroundAnim( pm->ps ) //not on the ground - && ( !PM_InRollIgnoreTimer( pm->ps )||(!pm->ps->legsAnimTimer&&pm->cmd.upmove<0) ) )//not in a roll (or you just finished one and you're still holding crouch) + if (pm->ps->pm_flags & PMF_DUCKED) { + bobmove = 0.5; // ducked characters bob much faster + if (!PM_InOnGroundAnim(pm->ps) // not on the ground + && (!PM_InRollIgnoreTimer(pm->ps) || + (!pm->ps->legsAnimTimer && pm->cmd.upmove < 0))) // not in a roll (or you just finished one and you're still holding crouch) { qboolean rolled = qfalse; - if ( PM_RunningAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_FORCEHEAL_START - || PM_CanRollFromSoulCal( pm->ps )) - {//roll! + if (PM_RunningAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_FORCEHEAL_START || PM_CanRollFromSoulCal(pm->ps)) { // roll! rolled = PM_TryRoll(); } - if ( !rolled ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALKBACK,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALK,setAnimFlags); + if (!rolled) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); } - if ( !Q_irand( 0, 19 ) ) - {//5% chance of making an alert - AddSoundEvent( pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue ); + if (!Q_irand(0, 19)) { // 5% chance of making an alert + AddSoundEvent(pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue); } - } - else - {//rolling is a little noisy - AddSoundEvent( pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue, qtrue ); + } else { // rolling is a little noisy + AddSoundEvent(pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue, qtrue); } } // ducked characters never play footsteps - } - else if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - {//Moving backwards - if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) - {//running backwards - bobmove = 0.4F; // faster speeds bob faster - if ( pm->ps->weapon == WP_SABER && pm->ps->SaberActive() ) - { + } else if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { // Moving backwards + if (!(pm->cmd.buttons & BUTTON_WALKING)) { // running backwards + bobmove = 0.4F; // faster speeds bob faster + if (pm->ps->weapon == WP_SABER && pm->ps->SaberActive()) { /* if ( pm->ps->saberAnimLevel == SS_STAFF ) { @@ -8428,195 +6900,117 @@ static void PM_Footsteps( void ) } else */ - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUNBACK2,setAnimFlags); - } - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//no run anim - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK1,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUNBACK1,setAnimFlags); + { PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUNBACK2, setAnimFlags); } + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { // no run anim + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK1, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUNBACK1, setAnimFlags); } footstep = qtrue; - } - else - {//walking backwards - bobmove = 0.3F; // faster speeds bob faster - if ( pm->ps->weapon == WP_SABER && pm->ps->SaberActive() ) - { - if ( pm->ps->saberAnimLevel == SS_DUAL ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK_DUAL,setAnimFlags); - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK_STAFF,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK2,setAnimFlags); + } else { // walking backwards + bobmove = 0.3F; // faster speeds bob faster + if (pm->ps->weapon == WP_SABER && pm->ps->SaberActive()) { + if (pm->ps->saberAnimLevel == SS_DUAL) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK_DUAL, setAnimFlags); + } else if (pm->ps->saberAnimLevel == SS_STAFF) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK_STAFF, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK2, setAnimFlags); } + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK1, setAnimFlags); } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK1,setAnimFlags); - } - if ( !Q_irand( 0, 9 ) ) - {//10% chance of a small alert, mainly for the sand_creature - AddSoundEvent( pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue ); - } - } - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - { - bobmove = 0.3F; // walking bobs slow - if ( pm->ps->weapon == WP_NONE ) - {//helmet retracted - PM_SetAnim( pm, SETANIM_BOTH, BOTH_WALK1, SETANIM_FLAG_NORMAL ); - } - else - {//helmet in place - PM_SetAnim( pm, SETANIM_BOTH, BOTH_WALK2, SETANIM_FLAG_NORMAL ); + if (!Q_irand(0, 9)) { // 10% chance of a small alert, mainly for the sand_creature + AddSoundEvent(pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue); } - AddSoundEvent( pm->gent, pm->ps->origin, 128, AEL_SUSPICIOUS, qtrue, qtrue ); } - else - { - if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) - {//running - bobmove = 0.4F; // faster speeds bob faster - if ( pm->ps->weapon == WP_SABER && pm->ps->SaberActive() ) - { - if ( pm->ps->saberAnimLevel == SS_DUAL ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN_DUAL,setAnimFlags); - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN_STAFF,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN2,setAnimFlags); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { + bobmove = 0.3F; // walking bobs slow + if (pm->ps->weapon == WP_NONE) { // helmet retracted + PM_SetAnim(pm, SETANIM_BOTH, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else { // helmet in place + PM_SetAnim(pm, SETANIM_BOTH, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } + AddSoundEvent(pm->gent, pm->ps->origin, 128, AEL_SUSPICIOUS, qtrue, qtrue); + } else { + if (!(pm->cmd.buttons & BUTTON_WALKING)) { // running + bobmove = 0.4F; // faster speeds bob faster + if (pm->ps->weapon == WP_SABER && pm->ps->SaberActive()) { + if (pm->ps->saberAnimLevel == SS_DUAL) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN_DUAL, setAnimFlags); + } else if (pm->ps->saberAnimLevel == SS_STAFF) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN_STAFF, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN2, setAnimFlags); } - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_JAWA ) - { - //if ( pm->gent->enemy && (pm->ps->weapon == WP_NONE || pm->ps->weapon == WP_MELEE) ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN4,setAnimFlags); - } + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_JAWA) { + // if ( pm->gent->enemy && (pm->ps->weapon == WP_NONE || pm->ps->weapon == WP_MELEE) ) + { PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN4, setAnimFlags); } /* else { PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN1,setAnimFlags); } */ - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( pm->ps->legsAnim != BOTH_RUN1 ) - { - if ( pm->ps->legsAnim != BOTH_RUN1START ) - {//Hmm, he should really start slow and have to accelerate... also need to do this for stopping - PM_SetAnim( pm,SETANIM_LEGS, BOTH_RUN1START, setAnimFlags|SETANIM_FLAG_HOLD ); - } - else if ( !pm->ps->legsAnimTimer ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + if (pm->ps->legsAnim != BOTH_RUN1) { + if (pm->ps->legsAnim != + BOTH_RUN1START) { // Hmm, he should really start slow and have to accelerate... also need to do this for stopping + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1START, setAnimFlags | SETANIM_FLAG_HOLD); + } else if (!pm->ps->legsAnimTimer) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); - } - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA ) - { - if ( pm->gent->NPC && pm->gent->NPC->stats.runSpeed == 300 ) - {//full on run, on all fours - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN1,SETANIM_FLAG_NORMAL); - } - else - {//regular, upright run - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN2,SETANIM_FLAG_NORMAL); + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA) { + if (pm->gent->NPC && pm->gent->NPC->stats.runSpeed == 300) { // full on run, on all fours + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, SETANIM_FLAG_NORMAL); + } else { // regular, upright run + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN2, SETANIM_FLAG_NORMAL); } - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//no run anim - PM_SetAnim( pm, SETANIM_LEGS, BOTH_WALK1, setAnimFlags ); - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_RANCOR) { // no run anim + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK1, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } } footstep = qtrue; - } - else - {//walking forward - bobmove = 0.3F; // walking bobs slow - if ( pm->ps->weapon == WP_SABER && pm->ps->SaberActive() ) - { - if ( pm->ps->saberAnimLevel == SS_DUAL ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK_DUAL,setAnimFlags); - } - else if ( pm->ps->saberAnimLevel == SS_STAFF ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK_STAFF,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK2,setAnimFlags); - } - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA ) - { - if ( pm->gent->health <= 50 ) - {//hurt walk - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK2,SETANIM_FLAG_NORMAL); - } - else - {//normal walk - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); + } else { // walking forward + bobmove = 0.3F; // walking bobs slow + if (pm->ps->weapon == WP_SABER && pm->ps->SaberActive()) { + if (pm->ps->saberAnimLevel == SS_DUAL) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK_DUAL, setAnimFlags); + } else if (pm->ps->saberAnimLevel == SS_STAFF) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK_STAFF, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK2, setAnimFlags); + } + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_WAMPA) { + if (pm->gent->health <= 50) { // hurt walk + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } else { // normal walk + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK1, SETANIM_FLAG_NORMAL); } + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK1, setAnimFlags); } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK1,setAnimFlags); - } - //Enemy NPCs always make footsteps for the benefit of the player - if ( pm->gent - && pm->gent->NPC - && pm->gent->client - && pm->gent->client->playerTeam != TEAM_PLAYER ) - { + // Enemy NPCs always make footsteps for the benefit of the player + if (pm->gent && pm->gent->NPC && pm->gent->client && pm->gent->client->playerTeam != TEAM_PLAYER) { footstep = qtrue; - } - else if ( !Q_irand( 0, 9 ) ) - {//10% chance of a small alert, mainly for the sand_creature - AddSoundEvent( pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue ); + } else if (!Q_irand(0, 9)) { // 10% chance of a small alert, mainly for the sand_creature + AddSoundEvent(pm->gent, pm->ps->origin, 16, AEL_MINOR, qtrue, qtrue); } } } } - if(pm->gent != NULL) - { - if( pm->gent->client->renderInfo.legsFpsMod > 2 ) - { + if (pm->gent != NULL) { + if (pm->gent->client->renderInfo.legsFpsMod > 2) { pm->gent->client->renderInfo.legsFpsMod = 2; - } - else if(pm->gent->client->renderInfo.legsFpsMod < 0.5) - { + } else if (pm->gent->client->renderInfo.legsFpsMod < 0.5) { pm->gent->client->renderInfo.legsFpsMod = 0.5; } } @@ -8625,77 +7019,56 @@ static void PM_Footsteps( void ) // check for footstep / splash sounds old = pm->ps->bobCycle; - pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255; + pm->ps->bobCycle = (int)(old + bobmove * pml.msec) & 255; // if we just crossed a cycle boundary, play an apropriate footstep event - if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) - { - if ( pm->watertype & CONTENTS_LADDER ) - { - if ( !pm->noFootsteps ) - { - if (pm->ps->groundEntityNum == ENTITYNUM_NONE) {// on ladder - PM_AddEvent( EV_FOOTSTEP_METAL ); + if (((old + 64) ^ (pm->ps->bobCycle + 64)) & 128) { + if (pm->watertype & CONTENTS_LADDER) { + if (!pm->noFootsteps) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // on ladder + PM_AddEvent(EV_FOOTSTEP_METAL); } else { - //PM_AddEvent( PM_FootstepForSurface() ); //still on ground + // PM_AddEvent( PM_FootstepForSurface() ); //still on ground } } - if ( pm->gent && pm->gent->s.number == 0 ) - { -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue ); - } + if (pm->gent && pm->gent->s.number == 0) { + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue); } } - } - else if ( pm->waterlevel == 0 ) - { + } else if (pm->waterlevel == 0) { // on ground will only play sounds if running - if ( footstep ) - { - if ( !pm->noFootsteps ) - { - //PM_AddEvent( PM_FootstepForSurface() ); + if (footstep) { + if (!pm->noFootsteps) { + // PM_AddEvent( PM_FootstepForSurface() ); } - if ( pm->gent && pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent && pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_MINOR, qtrue, qtrue ); - } + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_MINOR, qtrue, qtrue); } } } - } - else if ( pm->waterlevel == 1 ) - { + } else if (pm->waterlevel == 1) { // splashing - if ( pm->ps->waterHeightLevel >= WHL_KNEES ) - { - PM_AddEvent( EV_FOOTWADE ); - } - else - { - PM_AddEvent( EV_FOOTSPLASH ); + if (pm->ps->waterHeightLevel >= WHL_KNEES) { + PM_AddEvent(EV_FOOTWADE); + } else { + PM_AddEvent(EV_FOOTSPLASH); } - if ( pm->gent && pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent && pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS, qfalse, qtrue );//was bottom - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_MINOR ); + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS, qfalse, qtrue); // was bottom + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_MINOR); } } - } - else if ( pm->waterlevel == 2 ) - { + } else if (pm->waterlevel == 2) { // wading / swimming at surface /* if ( pm->ps->waterHeightLevel >= WHL_TORSO ) @@ -8704,21 +7077,16 @@ static void PM_Footsteps( void ) } else */ - { - PM_AddEvent( EV_FOOTWADE ); - } - if ( pm->gent && pm->gent->s.number == 0 ) - { -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { PM_AddEvent(EV_FOOTWADE); } + if (pm->gent && pm->gent->s.number == 0) { + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR, qfalse, qtrue ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR, qfalse, qtrue); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } - } - else - {// or no sound when completely underwater...? - PM_AddEvent( EV_SWIM ); + } else { // or no sound when completely underwater...? + PM_AddEvent(EV_SWIM); } } } @@ -8730,38 +7098,31 @@ PM_WaterEvents Generate sound events for entering and leaving water ============== */ -static void PM_WaterEvents( void ) { // FIXME? +static void PM_WaterEvents(void) { // FIXME? qboolean impact_splash = qfalse; - if ( pm->watertype & CONTENTS_LADDER ) //fake water for ladder + if (pm->watertype & CONTENTS_LADDER) // fake water for ladder { return; } // // if just entered a water volume, play a sound // - if (!pml.previous_waterlevel && pm->waterlevel) - { - if ( (pm->watertype&CONTENTS_LAVA) ) - { - PM_AddEvent( EV_LAVA_TOUCH ); - } - else - { - PM_AddEvent( EV_WATER_TOUCH ); + if (!pml.previous_waterlevel && pm->waterlevel) { + if ((pm->watertype & CONTENTS_LAVA)) { + PM_AddEvent(EV_LAVA_TOUCH); + } else { + PM_AddEvent(EV_WATER_TOUCH); } - if ( pm->gent ) - { - if ( VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + if (pm->gent) { + if (VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } - if ( pm->ps->clientNum < MAX_CLIENTS ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + if (pm->ps->clientNum < MAX_CLIENTS) { + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } } @@ -8769,58 +7130,46 @@ static void PM_WaterEvents( void ) { // FIXME? // // if just completely exited a water volume, play a sound // - if (pml.previous_waterlevel && !pm->waterlevel) - { - if ( (pm->watertype&CONTENTS_LAVA) ) - { - PM_AddEvent( EV_LAVA_LEAVE ); - } - else - { - PM_AddEvent( EV_WATER_LEAVE ); + if (pml.previous_waterlevel && !pm->waterlevel) { + if ((pm->watertype & CONTENTS_LAVA)) { + PM_AddEvent(EV_LAVA_LEAVE); + } else { + PM_AddEvent(EV_WATER_LEAVE); } - if ( pm->gent && VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + if (pm->gent && VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } - if ( pm->gent && pm->ps->clientNum < MAX_CLIENTS ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + if (pm->gent && pm->ps->clientNum < MAX_CLIENTS) { + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } - if ( impact_splash ) - { - //play the splash effect - trace_t tr; - vec3_t axis[3], angs, start, end; + if (impact_splash) { + // play the splash effect + trace_t tr; + vec3_t axis[3], angs, start, end; - VectorSet( angs, 0, pm->gent->currentAngles[YAW], 0 ); - AngleVectors( angs, axis[2], axis[1], axis[0] ); + VectorSet(angs, 0, pm->gent->currentAngles[YAW], 0); + AngleVectors(angs, axis[2], axis[1], axis[0]); - VectorCopy( pm->ps->origin, start ); - VectorCopy( pm->ps->origin, end ); + VectorCopy(pm->ps->origin, start); + VectorCopy(pm->ps->origin, end); // FIXME: set start and end better start[2] += 10; end[2] -= 40; - gi.trace( &tr, start, vec3_origin, vec3_origin, end, pm->gent->s.number, MASK_WATER, (EG2_Collision)0, 0 ); + gi.trace(&tr, start, vec3_origin, vec3_origin, end, pm->gent->s.number, MASK_WATER, (EG2_Collision)0, 0); - if ( tr.fraction < 1.0f ) - { - if ( (tr.contents&CONTENTS_LAVA) ) - { - G_PlayEffect( "env/lava_splash", tr.endpos, axis ); - } - else if ( (tr.contents&CONTENTS_SLIME) ) - { - G_PlayEffect( "env/acid_splash", tr.endpos, axis ); - } - else //must be water + if (tr.fraction < 1.0f) { + if ((tr.contents & CONTENTS_LAVA)) { + G_PlayEffect("env/lava_splash", tr.endpos, axis); + } else if ((tr.contents & CONTENTS_SLIME)) { + G_PlayEffect("env/acid_splash", tr.endpos, axis); + } else // must be water { - G_PlayEffect( "env/water_impact", tr.endpos, axis ); + G_PlayEffect("env/water_impact", tr.endpos, axis); } } } @@ -8829,19 +7178,15 @@ static void PM_WaterEvents( void ) { // FIXME? // check for head just going under water // if (pml.previous_waterlevel != 3 && pm->waterlevel == 3) { - if ( (pm->watertype&CONTENTS_LAVA) ) - { - PM_AddEvent( EV_LAVA_UNDER ); - } - else - { - PM_AddEvent( EV_WATER_UNDER ); + if ((pm->watertype & CONTENTS_LAVA)) { + PM_AddEvent(EV_LAVA_UNDER); + } else { + PM_AddEvent(EV_WATER_UNDER); } - if ( pm->gent && pm->ps->clientNum < MAX_CLIENTS ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR ); - AddSightEvent( pm->gent, pm->ps->origin, 384, AEL_MINOR ); + if (pm->gent && pm->ps->clientNum < MAX_CLIENTS) { + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR); + AddSightEvent(pm->gent, pm->ps->origin, 384, AEL_MINOR); } } @@ -8849,233 +7194,178 @@ static void PM_WaterEvents( void ) { // FIXME? // check for head just coming out of water // if (pml.previous_waterlevel == 3 && pm->waterlevel != 3) { - if ( !pm->gent || !pm->gent->client || pm->gent->client->airOutTime < level.time + 2000 ) - {//only do this if we were drowning or about to start drowning - PM_AddEvent( EV_WATER_CLEAR ); - } - else - { - if ( (pm->watertype&CONTENTS_LAVA) ) - { - PM_AddEvent( EV_LAVA_LEAVE ); - } - else - { - PM_AddEvent( EV_WATER_LEAVE ); + if (!pm->gent || !pm->gent->client || pm->gent->client->airOutTime < level.time + 2000) { // only do this if we were drowning or about to start drowning + PM_AddEvent(EV_WATER_CLEAR); + } else { + if ((pm->watertype & CONTENTS_LAVA)) { + PM_AddEvent(EV_LAVA_LEAVE); + } else { + PM_AddEvent(EV_WATER_LEAVE); } } - if ( pm->gent && pm->ps->clientNum < MAX_CLIENTS ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR ); - AddSightEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); + if (pm->gent && pm->ps->clientNum < MAX_CLIENTS) { + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR); + AddSightEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); } } } - /* =============== PM_BeginWeaponChange =============== */ -static void PM_BeginWeaponChange( int weapon ) { +static void PM_BeginWeaponChange(int weapon) { - if ( pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500 ) - {//just entered map - if ( weapon == WP_NONE && pm->ps->weapon != weapon ) - {//don't switch to weapon none if just entered map + if (pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500) { // just entered map + if (weapon == WP_NONE && pm->ps->weapon != weapon) { // don't switch to weapon none if just entered map return; } } - if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) { + if (weapon < WP_NONE || weapon >= WP_NUM_WEAPONS) { return; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { return; } - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { return; } - if ( cg.time > 0 ) - {//this way we don't get that annoying change weapon sound every time a map starts - PM_AddEvent( EV_CHANGE_WEAPON ); + if (cg.time > 0) { // this way we don't get that annoying change weapon sound every time a map starts + PM_AddEvent(EV_CHANGE_WEAPON); } pm->ps->weaponstate = WEAPON_DROPPING; pm->ps->weaponTime += 200; - if ( !(pm->ps->eFlags&EF_HELD_BY_WAMPA) && !G_IsRidingVehicle(pm->gent)) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP1,SETANIM_FLAG_HOLD); + if (!(pm->ps->eFlags & EF_HELD_BY_WAMPA) && !G_IsRidingVehicle(pm->gent)) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP1, SETANIM_FLAG_HOLD); } // turn of any kind of zooming when weapon switching....except the LA Goggles // eezstreet edit: also ignore if we change to WP_NONE..sorta hacky fix for binoculars using WP_SABER - if ( pm->ps->clientNum == 0 && cg.weaponSelect != WP_NONE ) - { - if ( cg.zoomMode > 0 && cg.zoomMode < 3 ) - { + if (pm->ps->clientNum == 0 && cg.weaponSelect != WP_NONE) { + if (cg.zoomMode > 0 && cg.zoomMode < 3) { cg.zoomMode = 0; cg.zoomTime = cg.time; } } - if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_ATST||pm->gent->client->NPC_class == CLASS_RANCOR) ) - { - if ( pm->ps->clientNum < MAX_CLIENTS ) - { - gi.cvar_set( "cg_thirdperson", "1" ); + if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_ATST || pm->gent->client->NPC_class == CLASS_RANCOR)) { + if (pm->ps->clientNum < MAX_CLIENTS) { + gi.cvar_set("cg_thirdperson", "1"); } - } - else if ( weapon == WP_SABER ) - {//going to switch to lightsaber - } - else - { - if ( pm->ps->weapon == WP_SABER ) - {//going to switch away from saber - if ( pm->gent ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav" ); + } else if (weapon == WP_SABER) { // going to switch to lightsaber + } else { + if (pm->ps->weapon == WP_SABER) { // going to switch away from saber + if (pm->gent) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav"); } - if (!G_IsRidingVehicle(pm->gent)) - { + if (!G_IsRidingVehicle(pm->gent)) { PM_SetSaberMove(LS_PUTAWAY); } } - //put this back in because saberActive isn't being set somewhere else anymore + // put this back in because saberActive isn't being set somewhere else anymore pm->ps->SaberDeactivate(); - pm->ps->SetSaberLength( 0.0f ); + pm->ps->SetSaberLength(0.0f); } } - /* =============== PM_FinishWeaponChange =============== */ -static void PM_FinishWeaponChange( void ) { - int weapon; - qboolean trueSwitch = qtrue; - - if ( pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500 ) - {//just entered map - if ( pm->cmd.weapon == WP_NONE && pm->ps->weapon != pm->cmd.weapon ) - {//don't switch to weapon none if just entered map +static void PM_FinishWeaponChange(void) { + int weapon; + qboolean trueSwitch = qtrue; + + if (pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500) { // just entered map + if (pm->cmd.weapon == WP_NONE && pm->ps->weapon != pm->cmd.weapon) { // don't switch to weapon none if just entered map return; } } weapon = pm->cmd.weapon; - if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) { + if (weapon < WP_NONE || weapon >= WP_NUM_WEAPONS) { weapon = WP_NONE; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { weapon = WP_NONE; } - if ( pm->ps->weapon == weapon ) - { + if (pm->ps->weapon == weapon) { trueSwitch = qfalse; } - //int oldWeap = pm->ps->weapon; + // int oldWeap = pm->ps->weapon; pm->ps->weapon = weapon; pm->ps->weaponstate = WEAPON_RAISING; pm->ps->weaponTime += 250; - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - {//do nothing - } - else if ( weapon == WP_SABER ) - {//turn on the lightsaber - //FIXME: somehow sometimes I still end up with 2 weapons in hand... usually if I + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { // do nothing + } else if (weapon == WP_SABER) { // turn on the lightsaber + // FIXME: somehow sometimes I still end up with 2 weapons in hand... usually if I // cycle weapons fast enough that I end up in 1st person lightsaber, then // somehow throw the saber and switch to another weapon (all in 1st person), // making my saber drop to the ground... when I switch back to the saber, it // does not remove the current weapon model and then, when I pull the saber // back to my hand, I have 2 weaponModels active...? - if ( pm->gent ) - {// remove gun if we had it. - G_RemoveWeaponModels( pm->gent ); + if (pm->gent) { // remove gun if we had it. + G_RemoveWeaponModels(pm->gent); } - if ( !pm->ps->saberInFlight || pm->ps->dualSabers ) - {//if it's not in flight or lying around, turn it on! - //FIXME: AddSound/Sight Event - //FIXME: don't do this if just loaded a game - if ( trueSwitch ) - {//actually did switch weapons, turn it on - if ( PM_RidingVehicle() ) - {//only turn on the first saber's first blade...? - pm->ps->SaberBladeActivate( 0, 0 ); - } - else - { + if (!pm->ps->saberInFlight || pm->ps->dualSabers) { // if it's not in flight or lying around, turn it on! + // FIXME: AddSound/Sight Event + // FIXME: don't do this if just loaded a game + if (trueSwitch) { // actually did switch weapons, turn it on + if (PM_RidingVehicle()) { // only turn on the first saber's first blade...? + pm->ps->SaberBladeActivate(0, 0); + } else { pm->ps->SaberActivate(); } - pm->ps->SetSaberLength( 0.0f ); + pm->ps->SetSaberLength(0.0f); } - if ( pm->gent ) - { - WP_SaberAddG2SaberModels( pm->gent ); + if (pm->gent) { + WP_SaberAddG2SaberModels(pm->gent); } - } - else - {//FIXME: pull it back to us? + } else { // FIXME: pull it back to us? } - if ( pm->gent ) - { - WP_SaberInitBladeData( pm->gent ); - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - { - gi.cvar_set( "cg_thirdperson", "1" ); + if (pm->gent) { + WP_SaberInitBladeData(pm->gent); + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { + gi.cvar_set("cg_thirdperson", "1"); } } - if ( trueSwitch ) - {//actually did switch weapons, play anim - if (!G_IsRidingVehicle(pm->gent)) - { + if (trueSwitch) { // actually did switch weapons, play anim + if (!G_IsRidingVehicle(pm->gent)) { PM_SetSaberMove(LS_DRAW); } } - } - else - {//switched away from saber - if ( pm->gent ) - { + } else { // switched away from saber + if (pm->gent) { // remove the sabre if we had it. - G_RemoveWeaponModels( pm->gent ); - if (weaponData[weapon].weaponMdl[0]) { //might be NONE, so check if it has a model - G_CreateG2AttachedWeaponModel( pm->gent, weaponData[weapon].weaponMdl, pm->gent->handRBolt, 0 ); + G_RemoveWeaponModels(pm->gent); + if (weaponData[weapon].weaponMdl[0]) { // might be NONE, so check if it has a model + G_CreateG2AttachedWeaponModel(pm->gent, weaponData[weapon].weaponMdl, pm->gent->handRBolt, 0); } } - if ( !(pm->ps->eFlags&EF_HELD_BY_WAMPA) ) - { - if ( pm->ps->weapon != WP_THERMAL - && pm->ps->weapon != WP_TRIP_MINE - && pm->ps->weapon != WP_DET_PACK - && !G_IsRidingVehicle(pm->gent)) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_RAISEWEAP1,SETANIM_FLAG_HOLD); + if (!(pm->ps->eFlags & EF_HELD_BY_WAMPA)) { + if (pm->ps->weapon != WP_THERMAL && pm->ps->weapon != WP_TRIP_MINE && pm->ps->weapon != WP_DET_PACK && !G_IsRidingVehicle(pm->gent)) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_HOLD); } } - if ( pm->ps->clientNum < MAX_CLIENTS - && cg_gunAutoFirst.integer - && !PM_RidingVehicle() -// && oldWeap == WP_SABER - && weapon != WP_NONE ) - { - gi.cvar_set( "cg_thirdperson", "0" ); + if (pm->ps->clientNum < MAX_CLIENTS && cg_gunAutoFirst.integer && + !PM_RidingVehicle() + // && oldWeap == WP_SABER + && weapon != WP_NONE) { + gi.cvar_set("cg_thirdperson", "0"); } pm->ps->saberMove = LS_NONE; pm->ps->saberBlocking = BLK_NO; @@ -9083,15 +7373,12 @@ static void PM_FinishWeaponChange( void ) { } } -int PM_ReadyPoseForSaberAnimLevel( void ) -{ +int PM_ReadyPoseForSaberAnimLevel(void) { int anim = BOTH_STAND2; - if (PM_RidingVehicle()) - { + if (PM_RidingVehicle()) { return -1; } - switch ( pm->ps->saberAnimLevel ) - { + switch (pm->ps->saberAnimLevel) { case SS_DUAL: anim = BOTH_SABERDUAL_STANCE; break; @@ -9115,35 +7402,27 @@ int PM_ReadyPoseForSaberAnimLevel( void ) return anim; } -qboolean PM_CanDoDualDoubleAttacks( void ) -{ - if ( (pm->ps->saber[0].saberFlags&SFL_NO_MIRROR_ATTACKS) ) - { +qboolean PM_CanDoDualDoubleAttacks(void) { + if ((pm->ps->saber[0].saberFlags & SFL_NO_MIRROR_ATTACKS)) { return qfalse; } - if ( pm->ps->dualSabers - && (pm->ps->saber[1].saberFlags&SFL_NO_MIRROR_ATTACKS) ) - { + if (pm->ps->dualSabers && (pm->ps->saber[1].saberFlags & SFL_NO_MIRROR_ATTACKS)) { return qfalse; } - //NOTE: assumes you're using SS_DUAL style and have both sabers on... - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//player + // NOTE: assumes you're using SS_DUAL style and have both sabers on... + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // player return qtrue; } - if ( pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= Q_irand( RANK_LT_COMM, RANK_CAPTAIN+2 ) ) - {//high-rank NPC + if (pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= Q_irand(RANK_LT_COMM, RANK_CAPTAIN + 2)) { // high-rank NPC return qtrue; } - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA ) - {//Alora + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ALORA) { // Alora return qtrue; } return qfalse; } -void PM_SetJumped( float height, qboolean force ) -{ +void PM_SetJumped(float height, qboolean force) { pm->ps->velocity[2] = height; pml.groundPlane = qfalse; pml.walking = qfalse; @@ -9152,30 +7431,24 @@ void PM_SetJumped( float height, qboolean force ) pm->ps->pm_flags |= PMF_JUMPING; pm->cmd.upmove = 0; - if ( force ) - { + if (force) { pm->ps->jumpZStart = pm->ps->origin[2]; pm->ps->pm_flags |= PMF_SLOW_MO_FALL; - //start force jump - pm->ps->forcePowersActive |= (1<gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - else - { - PM_AddEvent( EV_JUMP ); + // start force jump + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + } else { + PM_AddEvent(EV_JUMP); } } - -void PM_SetSaberMove(saberMoveName_t newMove) -{ +void PM_SetSaberMove(saberMoveName_t newMove) { unsigned int setflags; - int anim; + int anim; int parts = SETANIM_TORSO; qboolean manualBlocking = qfalse; - if ( newMove < LS_NONE || newMove >= LS_MOVE_MAX ) - { + if (newMove < LS_NONE || newMove >= LS_MOVE_MAX) { assert(0); return; } @@ -9183,200 +7456,119 @@ void PM_SetSaberMove(saberMoveName_t newMove) setflags = saberMoveData[newMove].animSetFlags; anim = saberMoveData[newMove].animToUse; - if ( (pm->ps->eFlags&EF_HELD_BY_WAMPA) ) - {//no anim + if ((pm->ps->eFlags & EF_HELD_BY_WAMPA)) { // no anim return; } - if ( cg_debugSaber.integer&0x01 && (newMove != LS_READY) ) - { - Com_Printf("SetSaberMove: From '%s' to '%s'\n", - saberMoveData[pm->ps->saberMove].name, - saberMoveData[newMove].name); + if (cg_debugSaber.integer & 0x01 && (newMove != LS_READY)) { + Com_Printf("SetSaberMove: From '%s' to '%s'\n", saberMoveData[pm->ps->saberMove].name, saberMoveData[newMove].name); } - if ( newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH ) - {//finished with a kata (or in a special move) reset attack counter + if (newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH) { // finished with a kata (or in a special move) reset attack counter pm->ps->saberAttackChainCount = 0; - } - else if ( PM_SaberInAttack( newMove ) ) - {//continuing with a kata, increment attack counter - //FIXME: maybe some contextual/style-specific logic in here + } else if (PM_SaberInAttack(newMove)) { // continuing with a kata, increment attack counter + // FIXME: maybe some contextual/style-specific logic in here pm->ps->saberAttackChainCount++; } - if ( newMove == LS_READY ) - { - if ( pm->ps->saberBlockingTime > cg.time ) - { + if (newMove == LS_READY) { + if (pm->ps->saberBlockingTime > cg.time) { manualBlocking = qtrue; - if ( !pm->ps->SaberActive() ) - {//turn on all blades and sabers if none are currently on + if (!pm->ps->SaberActive()) { // turn on all blades and sabers if none are currently on pm->ps->SaberActivate(); } - if ( pm->ps->saber[0].type == SABER_CLAW ) - { - anim = BOTH_INAIR1;//FIXME: is there a better anim for this? - } - else if ( pm->ps->dualSabers && pm->ps->saber[1].Active() ) - { + if (pm->ps->saber[0].type == SABER_CLAW) { + anim = BOTH_INAIR1; // FIXME: is there a better anim for this? + } else if (pm->ps->dualSabers && pm->ps->saber[1].Active()) { anim = BOTH_INAIR1; - } - else - { + } else { anim = BOTH_P1_S1_T_; } - } - else if ( pm->ps->saber[0].readyAnim != -1 ) - { + } else if (pm->ps->saber[0].readyAnim != -1) { anim = pm->ps->saber[0].readyAnim; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].readyAnim != -1 ) - { + } else if (pm->ps->dualSabers && pm->ps->saber[1].readyAnim != -1) { anim = pm->ps->saber[1].readyAnim; - } - else if ( pm->ps->saber[0].type == SABER_ARC ) - {//FIXME: need it's own style? + } else if (pm->ps->saber[0].type == SABER_ARC) { // FIXME: need it's own style? anim = BOTH_SABERFAST_STANCE; - } - else if ( (pm->ps->dualSabers && pm->ps->saber[1].Active()) ) - { + } else if ((pm->ps->dualSabers && pm->ps->saber[1].Active())) { anim = BOTH_SABERDUAL_STANCE; - } - else if ( (pm->ps->SaberStaff() && (!pm->ps->saber[0].singleBladeStyle||pm->ps->saber[0].blade[1].active))//saber staff with more than first blade active - || pm->ps->saber[0].type == SABER_ARC ) - { + } else if ((pm->ps->SaberStaff() && + (!pm->ps->saber[0].singleBladeStyle || pm->ps->saber[0].blade[1].active)) // saber staff with more than first blade active + || pm->ps->saber[0].type == SABER_ARC) { anim = BOTH_SABERSTAFF_STANCE; - } - else if ( pm->ps->saber[0].type == SABER_LANCE || pm->ps->saber[0].type == SABER_TRIDENT ) - {//FIXME: need some 2-handed forward-pointing anim + } else if (pm->ps->saber[0].type == SABER_LANCE || pm->ps->saber[0].type == SABER_TRIDENT) { // FIXME: need some 2-handed forward-pointing anim anim = BOTH_STAND1; - } - else - { + } else { anim = PM_ReadyPoseForSaberAnimLevel(); } - } - else if ( newMove == LS_DRAW ) - { - if ( PM_RunningAnim( pm->ps->torsoAnim ) ) - { + } else if (newMove == LS_DRAW) { + if (PM_RunningAnim(pm->ps->torsoAnim)) { pm->ps->saberMove = newMove; return; } - if ( pm->ps->saber[0].drawAnim != -1 ) - { + if (pm->ps->saber[0].drawAnim != -1) { anim = pm->ps->saber[0].drawAnim; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].drawAnim != -1 ) - { + } else if (pm->ps->dualSabers && pm->ps->saber[1].drawAnim != -1) { anim = pm->ps->saber[1].drawAnim; - } - else if ( pm->ps->saber[0].stylesLearned==(1<ps->saber[0].stylesLearned == (1 << SS_STAFF)) { anim = BOTH_S1_S7; - } - else if ( pm->ps->dualSabers - && !(pm->ps->saber[0].stylesForbidden&(1<ps->saber[1].stylesForbidden&(1<ps->dualSabers && !(pm->ps->saber[0].stylesForbidden & (1 << SS_DUAL)) && !(pm->ps->saber[1].stylesForbidden & (1 << SS_DUAL))) { anim = BOTH_S1_S6; } - if ( pm->ps->torsoAnim == BOTH_STAND1IDLE1 ) - { + if (pm->ps->torsoAnim == BOTH_STAND1IDLE1) { setflags |= SETANIM_FLAG_OVERRIDE; } - } - else if ( newMove == LS_PUTAWAY ) - { - if ( pm->ps->saber[0].putawayAnim != -1 ) - { + } else if (newMove == LS_PUTAWAY) { + if (pm->ps->saber[0].putawayAnim != -1) { anim = pm->ps->saber[0].putawayAnim; - } - else if ( pm->ps->dualSabers - && pm->ps->saber[1].putawayAnim != -1 ) - { + } else if (pm->ps->dualSabers && pm->ps->saber[1].putawayAnim != -1) { anim = pm->ps->saber[1].putawayAnim; - } - else if ( pm->ps->saber[0].stylesLearned==(1<ps->saber[0].blade[1].active ) - { + } else if (pm->ps->saber[0].stylesLearned == (1 << SS_STAFF) && pm->ps->saber[0].blade[1].active) { anim = BOTH_S7_S1; - } - else if ( pm->ps->dualSabers - && !(pm->ps->saber[0].stylesForbidden&(1<ps->saber[1].stylesForbidden&(1<ps->saber[1].Active() ) - { + } else if (pm->ps->dualSabers && !(pm->ps->saber[0].stylesForbidden & (1 << SS_DUAL)) && !(pm->ps->saber[1].stylesForbidden & (1 << SS_DUAL)) && + pm->ps->saber[1].Active()) { anim = BOTH_S6_S1; } - if ( PM_SaberStanceAnim( pm->ps->legsAnim ) && pm->ps->legsAnim != BOTH_STAND1 ) - { - parts = SETANIM_BOTH; - } - else - { - if ( PM_RunningAnim( pm->ps->torsoAnim ) ) - { + if (PM_SaberStanceAnim(pm->ps->legsAnim) && pm->ps->legsAnim != BOTH_STAND1) { + parts = SETANIM_BOTH; + } else { + if (PM_RunningAnim(pm->ps->torsoAnim)) { pm->ps->saberMove = newMove; return; } parts = SETANIM_TORSO; } - //FIXME: also dual - } - else if ( pm->ps->saberAnimLevel == SS_STAFF && newMove >= LS_S_TL2BR && newMove < LS_REFLECT_LL ) - {//staff has an entirely new set of anims, besides special attacks - //FIXME: include ready and draw/putaway? - //FIXME: get hand-made bounces and deflections? - if ( newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL ) - {//there aren't 1-7, just 1, 6 and 7, so just set it - anim = BOTH_P7_S7_T_ + (anim-BOTH_P1_S1_T_);//shift it up to the proper set - } - else - {//add the appropriate animLevel - anim += (pm->ps->saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; - } - } - else if ( (pm->ps->saberAnimLevel == SS_DUAL - || (pm->ps->dualSabers&& pm->ps->saber[1].Active())) - && newMove >= LS_S_TL2BR - && newMove < LS_REFLECT_LL ) - {//staff has an entirely new set of anims, besides special attacks - //FIXME: include ready and draw/putaway? - //FIXME: get hand-made bounces and deflections? - //FIXME: only do the dual FB & LR attacks when on ground? - if ( newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL ) - {//there aren't 1-7, just 1, 6 and 7, so just set it - anim = BOTH_P6_S6_T_ + (anim-BOTH_P1_S1_T_);//shift it up to the proper set - } - else if ( ( newMove == LS_A_R2L || newMove == LS_S_R2L - || newMove == LS_A_L2R || newMove == LS_S_L2R ) - && PM_CanDoDualDoubleAttacks() - && G_CheckEnemyPresence( pm->gent, DIR_RIGHT, 150.0f ) - && G_CheckEnemyPresence( pm->gent, DIR_LEFT, 150.0f ) ) - {//enemy both on left and right + // FIXME: also dual + } else if (pm->ps->saberAnimLevel == SS_STAFF && newMove >= LS_S_TL2BR && + newMove < LS_REFLECT_LL) { // staff has an entirely new set of anims, besides special attacks + // FIXME: include ready and draw/putaway? + // FIXME: get hand-made bounces and deflections? + if (newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL) { // there aren't 1-7, just 1, 6 and 7, so just set it + anim = BOTH_P7_S7_T_ + (anim - BOTH_P1_S1_T_); // shift it up to the proper set + } else { // add the appropriate animLevel + anim += (pm->ps->saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + } + } else if ((pm->ps->saberAnimLevel == SS_DUAL || (pm->ps->dualSabers && pm->ps->saber[1].Active())) && newMove >= LS_S_TL2BR && + newMove < LS_REFLECT_LL) { // staff has an entirely new set of anims, besides special attacks + // FIXME: include ready and draw/putaway? + // FIXME: get hand-made bounces and deflections? + // FIXME: only do the dual FB & LR attacks when on ground? + if (newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL) { // there aren't 1-7, just 1, 6 and 7, so just set it + anim = BOTH_P6_S6_T_ + (anim - BOTH_P1_S1_T_); // shift it up to the proper set + } else if ((newMove == LS_A_R2L || newMove == LS_S_R2L || newMove == LS_A_L2R || newMove == LS_S_L2R) && PM_CanDoDualDoubleAttacks() && + G_CheckEnemyPresence(pm->gent, DIR_RIGHT, 150.0f) && G_CheckEnemyPresence(pm->gent, DIR_LEFT, 150.0f)) { // enemy both on left and right newMove = LS_DUAL_LR; anim = saberMoveData[newMove].animToUse; - //probably already moved, but... + // probably already moved, but... pm->cmd.rightmove = 0; - } - else if ( (newMove == LS_A_T2B || newMove == LS_S_T2B - || newMove == LS_A_BACK || newMove == LS_A_BACK_CR ) - && PM_CanDoDualDoubleAttacks() - && G_CheckEnemyPresence( pm->gent, DIR_FRONT, 150.0f ) - && G_CheckEnemyPresence( pm->gent, DIR_BACK, 150.0f ) ) - {//enemy both in front and back + } else if ((newMove == LS_A_T2B || newMove == LS_S_T2B || newMove == LS_A_BACK || newMove == LS_A_BACK_CR) && PM_CanDoDualDoubleAttacks() && + G_CheckEnemyPresence(pm->gent, DIR_FRONT, 150.0f) && G_CheckEnemyPresence(pm->gent, DIR_BACK, 150.0f)) { // enemy both in front and back newMove = LS_DUAL_FB; anim = saberMoveData[newMove].animToUse; - //probably already moved, but... + // probably already moved, but... pm->cmd.forwardmove = 0; - } - else - {//add the appropriate animLevel - anim += (pm->ps->saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + } else { // add the appropriate animLevel + anim += (pm->ps->saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; } } /* @@ -9386,47 +7578,33 @@ void PM_SetSaberMove(saberMoveName_t newMove) anim = BOTH_SABERSTAFF_STANCE; } */ - else if ( pm->ps->saberAnimLevel > FORCE_LEVEL_1 && - !PM_SaberInIdle( newMove ) && !PM_SaberInParry( newMove ) && !PM_SaberInKnockaway( newMove ) && !PM_SaberInBrokenParry( newMove ) && !PM_SaberInReflect( newMove ) && !PM_SaberInSpecial( newMove )) - {//readies, parries and reflections have only 1 level - if ( pm->ps->saber[0].type == SABER_LANCE || pm->ps->saber[0].type == SABER_TRIDENT ) - {//FIXME: hack for now - these use the fast anims, but slowed down. Should have own style - } - else - {//increment the anim to the next level of saber anims - anim += (pm->ps->saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + else if (pm->ps->saberAnimLevel > FORCE_LEVEL_1 && !PM_SaberInIdle(newMove) && !PM_SaberInParry(newMove) && !PM_SaberInKnockaway(newMove) && + !PM_SaberInBrokenParry(newMove) && !PM_SaberInReflect(newMove) && + !PM_SaberInSpecial(newMove)) { // readies, parries and reflections have only 1 level + if (pm->ps->saber[0].type == SABER_LANCE || + pm->ps->saber[0].type == SABER_TRIDENT) { // FIXME: hack for now - these use the fast anims, but slowed down. Should have own style + } else { // increment the anim to the next level of saber anims + anim += (pm->ps->saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; } - } - else if ( newMove == LS_KICK_F_AIR - || newMove == LS_KICK_B_AIR - || newMove == LS_KICK_R_AIR - || newMove == LS_KICK_L_AIR ) - { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { - PM_SetJumped( 200, qtrue ); + } else if (newMove == LS_KICK_F_AIR || newMove == LS_KICK_B_AIR || newMove == LS_KICK_R_AIR || newMove == LS_KICK_L_AIR) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { + PM_SetJumped(200, qtrue); } } // If the move does the same animation as the last one, we need to force a restart... -// if ( saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) - if ( ( pm->ps->torsoAnim == anim || pm->ps->legsAnim == anim ) - && newMove > LS_PUTAWAY ) - { + // if ( saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) + if ((pm->ps->torsoAnim == anim || pm->ps->legsAnim == anim) && newMove > LS_PUTAWAY) { setflags |= SETANIM_FLAG_RESTART; } - if ( (anim == BOTH_STAND1 && (pm->ps->saber[0].type == SABER_ARC || (pm->ps->dualSabers && pm->ps->saber[1].Active())) ) - || anim == BOTH_STAND2 - //FIXME: temp hack to stop it from using run2 with staff - || (0 && anim == BOTH_SABERSTAFF_STANCE) - || anim == BOTH_SABERDUAL_STANCE - || anim == BOTH_SABERFAST_STANCE - || anim == BOTH_SABERSLOW_STANCE ) - {//match torso anim to walk/run anim if newMove is just LS_READY - //FIXME: play both_stand2_random1 when you've been idle for a while - switch ( pm->ps->legsAnim ) - { + if ((anim == BOTH_STAND1 && (pm->ps->saber[0].type == SABER_ARC || (pm->ps->dualSabers && pm->ps->saber[1].Active()))) || + anim == BOTH_STAND2 + // FIXME: temp hack to stop it from using run2 with staff + || (0 && anim == BOTH_SABERSTAFF_STANCE) || anim == BOTH_SABERDUAL_STANCE || anim == BOTH_SABERFAST_STANCE || + anim == BOTH_SABERSLOW_STANCE) { // match torso anim to walk/run anim if newMove is just LS_READY + // FIXME: play both_stand2_random1 when you've been idle for a while + switch (pm->ps->legsAnim) { case BOTH_WALK1: case BOTH_WALK2: case BOTH_WALK_STAFF: @@ -9447,143 +7625,86 @@ void PM_SetSaberMove(saberMoveName_t newMove) } } - if ( !PM_RidingVehicle() ) - { - if ( !manualBlocking ) - { - if ( newMove == LS_A_LUNGE - || newMove == LS_A_JUMP_T__B_ - || newMove == LS_A_BACKSTAB - || newMove == LS_A_BACK - || newMove == LS_A_BACK_CR - || newMove == LS_ROLL_STAB - || newMove == LS_A_FLIP_STAB - || newMove == LS_A_FLIP_SLASH - || newMove == LS_JUMPATTACK_DUAL - || newMove == LS_JUMPATTACK_ARIAL_LEFT - || newMove == LS_JUMPATTACK_ARIAL_RIGHT - || newMove == LS_JUMPATTACK_CART_LEFT - || newMove == LS_JUMPATTACK_CART_RIGHT - || newMove == LS_JUMPATTACK_STAFF_LEFT - || newMove == LS_JUMPATTACK_STAFF_RIGHT - || newMove == LS_BUTTERFLY_LEFT - || newMove == LS_BUTTERFLY_RIGHT - || newMove == LS_A_BACKFLIP_ATK - || newMove == LS_STABDOWN - || newMove == LS_STABDOWN_STAFF - || newMove == LS_STABDOWN_DUAL - || newMove == LS_DUAL_SPIN_PROTECT - || newMove == LS_STAFF_SOULCAL - || newMove == LS_A1_SPECIAL - || newMove == LS_A2_SPECIAL - || newMove == LS_A3_SPECIAL - || newMove == LS_UPSIDE_DOWN_ATTACK - || newMove == LS_PULL_ATTACK_STAB - || newMove == LS_PULL_ATTACK_SWING - || PM_KickMove( newMove ) ) - { + if (!PM_RidingVehicle()) { + if (!manualBlocking) { + if (newMove == LS_A_LUNGE || newMove == LS_A_JUMP_T__B_ || newMove == LS_A_BACKSTAB || newMove == LS_A_BACK || newMove == LS_A_BACK_CR || + newMove == LS_ROLL_STAB || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH || newMove == LS_JUMPATTACK_DUAL || + newMove == LS_JUMPATTACK_ARIAL_LEFT || newMove == LS_JUMPATTACK_ARIAL_RIGHT || newMove == LS_JUMPATTACK_CART_LEFT || + newMove == LS_JUMPATTACK_CART_RIGHT || newMove == LS_JUMPATTACK_STAFF_LEFT || newMove == LS_JUMPATTACK_STAFF_RIGHT || + newMove == LS_BUTTERFLY_LEFT || newMove == LS_BUTTERFLY_RIGHT || newMove == LS_A_BACKFLIP_ATK || newMove == LS_STABDOWN || + newMove == LS_STABDOWN_STAFF || newMove == LS_STABDOWN_DUAL || newMove == LS_DUAL_SPIN_PROTECT || newMove == LS_STAFF_SOULCAL || + newMove == LS_A1_SPECIAL || newMove == LS_A2_SPECIAL || newMove == LS_A3_SPECIAL || newMove == LS_UPSIDE_DOWN_ATTACK || + newMove == LS_PULL_ATTACK_STAB || newMove == LS_PULL_ATTACK_SWING || PM_KickMove(newMove)) { parts = SETANIM_BOTH; - } - else if ( PM_SpinningSaberAnim( anim ) ) - {//spins must be played on entire body + } else if (PM_SpinningSaberAnim(anim)) { // spins must be played on entire body parts = SETANIM_BOTH; - } - else if ( (!pm->cmd.forwardmove&&!pm->cmd.rightmove&&!pm->cmd.upmove)) - {//not trying to run, duck or jump - if ( !PM_FlippingAnim( pm->ps->legsAnim ) && - !PM_InRoll( pm->ps ) && - !PM_InKnockDown( pm->ps ) && - !PM_JumpingAnim( pm->ps->legsAnim ) && - !PM_PainAnim( pm->ps->legsAnim ) && - !PM_InSpecialJump( pm->ps->legsAnim ) && - !PM_InSlopeAnim( pm->ps->legsAnim ) && - //!PM_CrouchAnim( pm->ps->legsAnim ) && - //pm->cmd.upmove >= 0 && - !(pm->ps->pm_flags & PMF_DUCKED) && - newMove != LS_PUTAWAY ) - { + } else if ((!pm->cmd.forwardmove && !pm->cmd.rightmove && !pm->cmd.upmove)) { // not trying to run, duck or jump + if (!PM_FlippingAnim(pm->ps->legsAnim) && !PM_InRoll(pm->ps) && !PM_InKnockDown(pm->ps) && !PM_JumpingAnim(pm->ps->legsAnim) && + !PM_PainAnim(pm->ps->legsAnim) && !PM_InSpecialJump(pm->ps->legsAnim) && !PM_InSlopeAnim(pm->ps->legsAnim) && + //! PM_CrouchAnim( pm->ps->legsAnim ) && + // pm->cmd.upmove >= 0 && + !(pm->ps->pm_flags & PMF_DUCKED) && newMove != LS_PUTAWAY) { parts = SETANIM_BOTH; - } - else if ( !(pm->ps->pm_flags & PMF_DUCKED) - && ( newMove == LS_SPINATTACK_DUAL || newMove == LS_SPINATTACK ) ) - { + } else if (!(pm->ps->pm_flags & PMF_DUCKED) && (newMove == LS_SPINATTACK_DUAL || newMove == LS_SPINATTACK)) { parts = SETANIM_BOTH; } } } - } - else - { - if (!pm->ps->saberBlocked) - { + } else { + if (!pm->ps->saberBlocked) { parts = SETANIM_BOTH; setflags &= ~SETANIM_FLAG_RESTART; } } - if (anim!=-1) - { - PM_SetAnim( pm, parts, anim, setflags, saberMoveData[newMove].blendTime ); + if (anim != -1) { + PM_SetAnim(pm, parts, anim, setflags, saberMoveData[newMove].blendTime); } - if ( pm->ps->torsoAnim == anim ) - {//successfully changed anims - //special check for *starting* a saber swing - if ( pm->gent && pm->ps->SaberLength() > 1 ) - { - if ( PM_SaberInAttack( newMove ) || PM_SaberInSpecialAttack( anim ) ) - {//playing an attack - if ( pm->ps->saberMove != newMove ) - {//wasn't playing that attack before - if ( PM_SaberInSpecialAttack( anim ) ) - { - WP_SaberSwingSound( pm->gent, 0, SWING_FAST ); - if ( !PM_InCartwheel( pm->ps->torsoAnim ) ) - {//can still attack during a cartwheel/arial - pm->ps->weaponTime = pm->ps->torsoAnimTimer;//so we know our weapon is busy + if (pm->ps->torsoAnim == anim) { // successfully changed anims + // special check for *starting* a saber swing + if (pm->gent && pm->ps->SaberLength() > 1) { + if (PM_SaberInAttack(newMove) || PM_SaberInSpecialAttack(anim)) { // playing an attack + if (pm->ps->saberMove != newMove) { // wasn't playing that attack before + if (PM_SaberInSpecialAttack(anim)) { + WP_SaberSwingSound(pm->gent, 0, SWING_FAST); + if (!PM_InCartwheel(pm->ps->torsoAnim)) { // can still attack during a cartwheel/arial + pm->ps->weaponTime = pm->ps->torsoAnimTimer; // so we know our weapon is busy } - } - else - { - switch ( pm->ps->saberAnimLevel ) - { + } else { + switch (pm->ps->saberAnimLevel) { case SS_DESANN: case SS_STRONG: - WP_SaberSwingSound( pm->gent, 0, SWING_STRONG ); + WP_SaberSwingSound(pm->gent, 0, SWING_STRONG); break; case SS_MEDIUM: case SS_DUAL: case SS_STAFF: - WP_SaberSwingSound( pm->gent, 0, SWING_MEDIUM ); + WP_SaberSwingSound(pm->gent, 0, SWING_MEDIUM); break; case SS_TAVION: case SS_FAST: - WP_SaberSwingSound( pm->gent, 0, SWING_FAST ); + WP_SaberSwingSound(pm->gent, 0, SWING_FAST); break; } } - } - else if ( (setflags&SETANIM_FLAG_RESTART) && PM_SaberInSpecialAttack( anim ) ) - {//sigh, if restarted a special, then set the weaponTime *again* - if ( !PM_InCartwheel( pm->ps->torsoAnim ) ) - {//can still attack during a cartwheel/arial - pm->ps->weaponTime = pm->ps->torsoAnimTimer;//so we know our weapon is busy + } else if ((setflags & SETANIM_FLAG_RESTART) && PM_SaberInSpecialAttack(anim)) { // sigh, if restarted a special, then set the weaponTime + // *again* + if (!PM_InCartwheel(pm->ps->torsoAnim)) { // can still attack during a cartwheel/arial + pm->ps->weaponTime = pm->ps->torsoAnimTimer; // so we know our weapon is busy } } - } - else if ( PM_SaberInStart( newMove ) ) - { - //if ( g_saberRealisticCombat->integer < 1 ) - {//don't damage on the first few frames of a start anim because it may pop from one position to some drastically different one, killing the enemy without hitting them. + } else if (PM_SaberInStart(newMove)) { + // if ( g_saberRealisticCombat->integer < 1 ) + { // don't damage on the first few frames of a start anim because it may pop from one position to some drastically different one, killing the + // enemy without hitting them. int damageDelay = 150; - if ( pm->ps->torsoAnimTimer < damageDelay ) - { + if (pm->ps->torsoAnimTimer < damageDelay) { damageDelay = pm->ps->torsoAnimTimer; } - //ent->client->ps.saberDamageDebounceTime = level.time + damageDelay; + // ent->client->ps.saberDamageDebounceTime = level.time + damageDelay; } - if ( pm->ps->saberAnimLevel == SS_STRONG ) - { - WP_SaberSwingSound( pm->gent, 0, SWING_FAST ); + if (pm->ps->saberAnimLevel == SS_STRONG) { + WP_SaberSwingSound(pm->gent, 0, SWING_FAST); } } } @@ -9597,25 +7718,17 @@ void PM_SetSaberMove(saberMoveName_t newMove) } */ - - //Some special attacks can be started when sabers are off, make sure we turn them on, first! - switch ( newMove ) - {//make sure the saber is on! + // Some special attacks can be started when sabers are off, make sure we turn them on, first! + switch (newMove) { // make sure the saber is on! case LS_A_LUNGE: case LS_ROLL_STAB: - if ( PM_InSecondaryStyle() ) - {//staff as medium or dual as fast - if ( pm->ps->dualSabers ) - {//only force on the first saber + if (PM_InSecondaryStyle()) { // staff as medium or dual as fast + if (pm->ps->dualSabers) { // only force on the first saber pm->ps->saber[0].Activate(); + } else if (pm->ps->saber[0].numBlades > 1) { // only force on the first saber's first blade + pm->ps->SaberBladeActivate(0, 0); } - else if ( pm->ps->saber[0].numBlades > 1 ) - {//only force on the first saber's first blade - pm->ps->SaberBladeActivate(0,0); - } - } - else - {//turn on all blades on all sabers + } else { // turn on all blades on all sabers pm->ps->SaberActivate(); } break; @@ -9627,7 +7740,7 @@ void PM_SetSaberMove(saberMoveName_t newMove) case LS_A3_SPECIAL: case LS_DUAL_SPIN_PROTECT: case LS_STAFF_SOULCAL: - //FIXME: probably more... + // FIXME: probably more... pm->ps->SaberActivate(); break; default: @@ -9637,37 +7750,28 @@ void PM_SetSaberMove(saberMoveName_t newMove) pm->ps->saberMove = newMove; pm->ps->saberBlocking = saberMoveData[newMove].blocking; - if ( pm->ps->clientNum == 0 || PM_ControlledByPlayer() ) - { - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ - && newMove >= LS_REFLECT_UP && newMove <= LS_REFLECT_LL ) - {//don't clear it when blocking projectiles - } - else - { + if (pm->ps->clientNum == 0 || PM_ControlledByPlayer()) { + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ && newMove >= LS_REFLECT_UP && + newMove <= LS_REFLECT_LL) { // don't clear it when blocking projectiles + } else { pm->ps->saberBlocked = BLOCKED_NONE; } - } - else if ( pm->ps->saberBlocked <= BLOCKED_ATK_BOUNCE || !pm->ps->SaberActive() || (newMove < LS_PARRY_UR || newMove > LS_REFLECT_LL) ) - {//NPCs only clear blocked if not blocking? + } else if (pm->ps->saberBlocked <= BLOCKED_ATK_BOUNCE || !pm->ps->SaberActive() || + (newMove < LS_PARRY_UR || newMove > LS_REFLECT_LL)) { // NPCs only clear blocked if not blocking? pm->ps->saberBlocked = BLOCKED_NONE; } - if ( pm->gent && pm->gent->client ) - { - if ( saberMoveData[newMove].trailLength > 0 ) - { - pm->gent->client->ps.SaberActivateTrail( saberMoveData[newMove].trailLength ); // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter - } - else - { - pm->gent->client->ps.SaberDeactivateTrail( 0 ); + if (pm->gent && pm->gent->client) { + if (saberMoveData[newMove].trailLength > 0) { + pm->gent->client->ps.SaberActivateTrail( + saberMoveData[newMove].trailLength); // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter + } else { + pm->gent->client->ps.SaberDeactivateTrail(0); } } } } - /* ============== PM_Use @@ -9677,23 +7781,19 @@ Generates a use event */ #define USE_DELAY 250 -void PM_Use( void ) -{ - if ( pm->ps->useTime > 0 ) - { +void PM_Use(void) { + if (pm->ps->useTime > 0) { pm->ps->useTime -= pml.msec; - if ( pm->ps->useTime < 0 ) - { + if (pm->ps->useTime < 0) { pm->ps->useTime = 0; } } - if ( pm->ps->useTime > 0 ) { + if (pm->ps->useTime > 0) { return; } - if ( ! (pm->cmd.buttons & BUTTON_USE ) ) - { + if (!(pm->cmd.buttons & BUTTON_USE)) { pm->useEvent = 0; pm->ps->useTime = 0; return; @@ -9703,128 +7803,86 @@ void PM_Use( void ) pm->ps->useTime = USE_DELAY; } -extern saberMoveName_t PM_AttackForEnemyPos( qboolean allowFB, qboolean allowStabDown ); -saberMoveName_t PM_NPCSaberAttackFromQuad( int quad ) -{ - //FIXME: this should be an AI decision - // It should be based on the enemy's current LS_ move, saberAnimLevel, - // the jedi's difficulty level, rank and FP_OFFENSE skill... +extern saberMoveName_t PM_AttackForEnemyPos(qboolean allowFB, qboolean allowStabDown); +saberMoveName_t PM_NPCSaberAttackFromQuad(int quad) { + // FIXME: this should be an AI decision + // It should be based on the enemy's current LS_ move, saberAnimLevel, + // the jedi's difficulty level, rank and FP_OFFENSE skill... saberMoveName_t autoMove = LS_NONE; - if ( pm->gent && ((pm->gent->NPC && pm->gent->NPC->rank != RANK_ENSIGN && pm->gent->NPC->rank != RANK_CIVILIAN ) || (pm->gent->client && (pm->gent->client->NPC_class == CLASS_TAVION||pm->gent->client->NPC_class == CLASS_ALORA))) ) - { - autoMove = PM_AttackForEnemyPos( qtrue, qtrue ); + if (pm->gent && ((pm->gent->NPC && pm->gent->NPC->rank != RANK_ENSIGN && pm->gent->NPC->rank != RANK_CIVILIAN) || + (pm->gent->client && (pm->gent->client->NPC_class == CLASS_TAVION || pm->gent->client->NPC_class == CLASS_ALORA)))) { + autoMove = PM_AttackForEnemyPos(qtrue, qtrue); } - if ( autoMove != LS_NONE && PM_SaberInSpecial( autoMove ) ) - {//if have opportunity to do a special attack, do one + if (autoMove != LS_NONE && PM_SaberInSpecial(autoMove)) { // if have opportunity to do a special attack, do one return autoMove; - } - else - {//pick another one + } else { // pick another one saberMoveName_t newmove = LS_NONE; - switch( quad ) - { - case Q_T://blocked top - if ( Q_irand( 0, 1 ) ) - { + switch (quad) { + case Q_T: // blocked top + if (Q_irand(0, 1)) { newmove = LS_A_T2B; - } - else - { + } else { newmove = LS_A_TR2BL; } break; case Q_TR: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_R2L; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_A_TR2BL; - } - else - { + } else { newmove = LS_T1_TR_BR; } break; case Q_TL: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_L2R; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_A_TL2BR; - } - else - { + } else { newmove = LS_T1_TL_BL; } break; case Q_BR: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_BR2TL; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1_BR_TR; - } - else - { + } else { newmove = LS_A_R2L; } break; case Q_BL: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_BL2TR; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1_BL_TL; - } - else - { + } else { newmove = LS_A_L2R; } break; case Q_L: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_L2R; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1__L_T_; - } - else - { + } else { newmove = LS_A_R2L; } break; case Q_R: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_R2L; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1__R_T_; - } - else - { + } else { newmove = LS_A_L2R; } break; case Q_B: - if ( pm->gent - && pm->gent->NPC - && pm->gent->NPC->rank >= RANK_LT_JG ) - {//fencers and above can do bottom-up attack - if ( Q_irand( 0, pm->gent->NPC->rank ) >= RANK_LT_JG ) - {//but not overly likely - newmove = PM_SaberLungeAttackMove( qtrue ); + if (pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG) { // fencers and above can do bottom-up attack + if (Q_irand(0, pm->gent->NPC->rank) >= RANK_LT_JG) { // but not overly likely + newmove = PM_SaberLungeAttackMove(qtrue); } } break; @@ -9835,246 +7893,171 @@ saberMoveName_t PM_NPCSaberAttackFromQuad( int quad ) } } -int PM_SaberMoveQuadrantForMovement( usercmd_t *ucmd ) -{ - if ( ucmd->rightmove > 0 ) - {//moving right - if ( ucmd->forwardmove > 0 ) - {//forward right = TL2BR slash +int PM_SaberMoveQuadrantForMovement(usercmd_t *ucmd) { + if (ucmd->rightmove > 0) { // moving right + if (ucmd->forwardmove > 0) { // forward right = TL2BR slash return Q_TL; - } - else if ( ucmd->forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (ucmd->forwardmove < 0) { // backward right = BL2TR uppercut return Q_BL; - } - else - {//just right is a left slice + } else { // just right is a left slice return Q_L; } - } - else if ( ucmd->rightmove < 0 ) - {//moving left - if ( ucmd->forwardmove > 0 ) - {//forward left = TR2BL slash + } else if (ucmd->rightmove < 0) { // moving left + if (ucmd->forwardmove > 0) { // forward left = TR2BL slash return Q_TR; - } - else if ( ucmd->forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (ucmd->forwardmove < 0) { // backward left = BR2TL uppercut return Q_BR; - } - else - {//just left is a right slice + } else { // just left is a right slice return Q_R; } - } - else - {//not moving left or right - if ( ucmd->forwardmove > 0 ) - {//forward= T2B slash + } else { // not moving left or right + if (ucmd->forwardmove > 0) { // forward= T2B slash return Q_T; - } - else if ( ucmd->forwardmove < 0 ) - {//backward= T2B slash //or B2T uppercut? + } else if (ucmd->forwardmove < 0) { // backward= T2B slash //or B2T uppercut? return Q_T; - } - else //if ( curmove == LS_READY )//??? - {//Not moving at all + } else // if ( curmove == LS_READY )//??? + { // Not moving at all return Q_R; } } - //return Q_R;//???? + // return Q_R;//???? } -void PM_SetAnimFrame( gentity_t *gent, int frame, qboolean torso, qboolean legs ) -{ - if ( !gi.G2API_HaveWeGhoul2Models( gent->ghoul2 ) ) - { +void PM_SetAnimFrame(gentity_t *gent, int frame, qboolean torso, qboolean legs) { + if (!gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) { return; } - int actualTime = (cg.time?cg.time:level.time); - if ( torso && gent->lowerLumbarBone != -1 )//gent->upperLumbarBone + int actualTime = (cg.time ? cg.time : level.time); + if (torso && gent->lowerLumbarBone != -1) // gent->upperLumbarBone { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, //gent->upperLumbarBone - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); - if ( gent->motionBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, //gent->upperLumbarBone - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, // gent->upperLumbarBone + frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, actualTime, frame, 150); + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, // gent->upperLumbarBone + frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, actualTime, frame, 150); } } - if ( legs && gent->rootBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); + if (legs && gent->rootBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, + actualTime, frame, 150); } } -int PM_SaberLockWinAnim( saberLockResult_t result, int breakType ) -{ +int PM_SaberLockWinAnim(saberLockResult_t result, int breakType) { int winAnim = -1; - switch ( pm->ps->torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, animTable[pm->ps->torsoAnim].name ); -#endif -*/ + switch (pm->ps->torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, + animTable[pm->ps->torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { winAnim = BOTH_LK_S_S_T_SB_1_W; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { winAnim = BOTH_BF1BREAK; - } - else - { + } else { pm->ps->saberMove = LS_A_T2B; winAnim = BOTH_A3_T__B_; } break; case BOTH_BF1LOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { winAnim = BOTH_LK_S_S_T_SB_1_W; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { winAnim = BOTH_KNOCKDOWN4; - } - else - { + } else { pm->ps->saberMove = LS_K1_T_; winAnim = BOTH_K1_S1_T_; } break; case BOTH_CWCIRCLELOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { winAnim = BOTH_LK_S_S_S_SB_1_W; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { pm->ps->saberMove = pm->ps->saberBounceMove = LS_V1_BL; pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BL_S1; - } - else - { + } else { winAnim = BOTH_CWCIRCLEBREAK; } break; case BOTH_CCWCIRCLELOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { winAnim = BOTH_LK_S_S_S_SB_1_W; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { pm->ps->saberMove = pm->ps->saberBounceMove = LS_V1_BR; pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BR_S1; - } - else - { + } else { winAnim = BOTH_CCWCIRCLEBREAK; } break; default: - //must be using new system: + // must be using new system: break; } - if ( winAnim != -1 ) - { - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (winAnim != -1) { + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer; pm->ps->saberBlocked = BLOCKED_NONE; pm->ps->weaponstate = WEAPON_FIRING; - if ( breakType == SABERLOCK_SUPERBREAK - && winAnim != BOTH_LK_ST_DL_T_SB_1_W ) - {//going to attack with saber, do a saber trail - pm->ps->SaberActivateTrail( 200 ); + if (breakType == SABERLOCK_SUPERBREAK && winAnim != BOTH_LK_ST_DL_T_SB_1_W) { // going to attack with saber, do a saber trail + pm->ps->SaberActivateTrail(200); } } return winAnim; } -int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result, int breakType ) -{ +int PM_SaberLockLoseAnim(gentity_t *genemy, saberLockResult_t result, int breakType) { int loseAnim = -1; - switch ( genemy->client->ps.torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, animTable[genemy->client->ps.torsoAnim].name ); -#endif -*/ + switch (genemy->client->ps.torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, + animTable[genemy->client->ps.torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { loseAnim = BOTH_LK_S_S_T_SB_1_L; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { loseAnim = BOTH_BF1BREAK; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won genemy->client->ps.saberMove = LS_K1_T_; loseAnim = BOTH_K1_S1_T_; - } - else - {//FIXME: this anim needs to transition back to ready when done + } else { // FIXME: this anim needs to transition back to ready when done loseAnim = BOTH_BF1BREAK; } } break; case BOTH_BF1LOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { loseAnim = BOTH_LK_S_S_T_SB_1_L; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { loseAnim = BOTH_KNOCKDOWN4; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won genemy->client->ps.saberMove = LS_A_T2B; loseAnim = BOTH_A3_T__B_; - } - else - { + } else { loseAnim = BOTH_KNOCKDOWN4; } } break; case BOTH_CWCIRCLELOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { loseAnim = BOTH_LK_S_S_S_SB_1_L; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BL; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won loseAnim = BOTH_CCWCIRCLEBREAK; - } - else - { + } else { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BL; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; @@ -10087,24 +8070,16 @@ int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result, int break } break; case BOTH_CCWCIRCLELOCK: - if ( breakType == SABERLOCK_SUPERBREAK ) - { + if (breakType == SABERLOCK_SUPERBREAK) { loseAnim = BOTH_LK_S_S_S_SB_1_L; - } - else if ( result == LOCK_DRAW ) - { + } else if (result == LOCK_DRAW) { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BR; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won loseAnim = BOTH_CWCIRCLEBREAK; - } - else - { + } else { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BR; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; @@ -10117,230 +8092,183 @@ int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result, int break } break; } - if ( loseAnim != -1 ) - { - NPC_SetAnim( genemy, SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - genemy->client->ps.weaponTime = genemy->client->ps.torsoAnimTimer;// + 250; + if (loseAnim != -1) { + NPC_SetAnim(genemy, SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + genemy->client->ps.weaponTime = genemy->client->ps.torsoAnimTimer; // + 250; genemy->client->ps.saberBlocked = BLOCKED_NONE; genemy->client->ps.weaponstate = WEAPON_READY; } return loseAnim; } -int PM_SaberLockResultAnim( gentity_t *duelist, int lockOrBreakOrSuperBreak, int winOrLose ) -{ +int PM_SaberLockResultAnim(gentity_t *duelist, int lockOrBreakOrSuperBreak, int winOrLose) { int baseAnim = duelist->client->ps.torsoAnim; - switch ( baseAnim ) - { - case BOTH_LK_S_S_S_L_2: //lock if I'm using single vs. a single and other intitiated + switch (baseAnim) { + case BOTH_LK_S_S_S_L_2: // lock if I'm using single vs. a single and other intitiated baseAnim = BOTH_LK_S_S_S_L_1; break; - case BOTH_LK_S_S_T_L_2: //lock if I'm using single vs. a single and other initiated + case BOTH_LK_S_S_T_L_2: // lock if I'm using single vs. a single and other initiated baseAnim = BOTH_LK_S_S_T_L_1; break; - case BOTH_LK_DL_DL_S_L_2: //lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_S_L_2: // lock if I'm using dual vs. dual and other initiated baseAnim = BOTH_LK_DL_DL_S_L_1; break; - case BOTH_LK_DL_DL_T_L_2: //lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_T_L_2: // lock if I'm using dual vs. dual and other initiated baseAnim = BOTH_LK_DL_DL_T_L_1; break; - case BOTH_LK_ST_ST_S_L_2: //lock if I'm using staff vs. a staff and other initiated + case BOTH_LK_ST_ST_S_L_2: // lock if I'm using staff vs. a staff and other initiated baseAnim = BOTH_LK_ST_ST_S_L_1; break; - case BOTH_LK_ST_ST_T_L_2: //lock if I'm using staff vs. a staff and other initiated + case BOTH_LK_ST_ST_T_L_2: // lock if I'm using staff vs. a staff and other initiated baseAnim = BOTH_LK_ST_ST_T_L_1; break; } - //what kind of break? - if ( lockOrBreakOrSuperBreak == SABERLOCK_BREAK ) - { + // what kind of break? + if (lockOrBreakOrSuperBreak == SABERLOCK_BREAK) { baseAnim -= 2; - } - else if ( lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK ) - { + } else if (lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK) { baseAnim += 1; - } - else - {//WTF? Not a valid result + } else { // WTF? Not a valid result return -1; } - //win or lose? - if ( winOrLose == SABERLOCK_WIN ) - { + // win or lose? + if (winOrLose == SABERLOCK_WIN) { baseAnim += 1; } - //play the anim and hold it - NPC_SetAnim( duelist, SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // play the anim and hold it + NPC_SetAnim(duelist, SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK - && winOrLose == SABERLOCK_LOSE ) - {//if you lose a superbreak, you're defenseless - //make saberent not block + if (lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK && winOrLose == SABERLOCK_LOSE) { // if you lose a superbreak, you're defenseless + // make saberent not block gentity_t *saberent = &g_entities[duelist->client->ps.saberEntityNum]; - if ( saberent ) - { + if (saberent) { VectorClear(saberent->mins); VectorClear(saberent->maxs); G_SetOrigin(saberent, duelist->currentOrigin); } - //set sabermove to none + // set sabermove to none duelist->client->ps.saberMove = LS_NONE; - //Hold the anim a little longer than it is - duelist->client->ps.torsoAnimTimer += 250;; + // Hold the anim a little longer than it is + duelist->client->ps.torsoAnimTimer += 250; + ; } - //no attacking during this anim + // no attacking during this anim duelist->client->ps.weaponTime = duelist->client->ps.torsoAnimTimer; duelist->client->ps.saberBlocked = BLOCKED_NONE; - if ( lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK - && winOrLose == SABERLOCK_WIN - && baseAnim != BOTH_LK_ST_DL_T_SB_1_W ) - {//going to attack with saber, do a saber trail - duelist->client->ps.SaberActivateTrail( 200 ); + if (lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK && winOrLose == SABERLOCK_WIN && + baseAnim != BOTH_LK_ST_DL_T_SB_1_W) { // going to attack with saber, do a saber trail + duelist->client->ps.SaberActivateTrail(200); } return baseAnim; } -void PM_SaberLockBreak( gentity_t *gent, gentity_t *genemy, saberLockResult_t result, int victoryStrength ) -{ - int winAnim = -1, loseAnim = -1; +void PM_SaberLockBreak(gentity_t *gent, gentity_t *genemy, saberLockResult_t result, int victoryStrength) { + int winAnim = -1, loseAnim = -1; int breakType = SABERLOCK_BREAK; qboolean singleVsSingle = qtrue; - if ( result == LOCK_VICTORY - && Q_irand(0,7) < victoryStrength ) - { - if ( genemy - && genemy->NPC - && ((genemy->NPC->aiFlags&NPCAI_BOSS_CHARACTER) - ||(genemy->NPC->aiFlags&NPCAI_SUBBOSS_CHARACTER) - ||(genemy->client&&genemy->client->NPC_class == CLASS_SHADOWTROOPER)) - && Q_irand(0, 4) - ) - {//less of a chance of getting a superbreak against a boss + if (result == LOCK_VICTORY && Q_irand(0, 7) < victoryStrength) { + if (genemy && genemy->NPC && + ((genemy->NPC->aiFlags & NPCAI_BOSS_CHARACTER) || (genemy->NPC->aiFlags & NPCAI_SUBBOSS_CHARACTER) || + (genemy->client && genemy->client->NPC_class == CLASS_SHADOWTROOPER)) && + Q_irand(0, 4)) { // less of a chance of getting a superbreak against a boss breakType = SABERLOCK_BREAK; - } - else - { + } else { breakType = SABERLOCK_SUPERBREAK; } - } - else - { + } else { breakType = SABERLOCK_BREAK; } - winAnim = PM_SaberLockWinAnim( result, breakType ); - if ( winAnim != -1 ) - {//a single vs. single break - if ( genemy && genemy->client ) - { - loseAnim = PM_SaberLockLoseAnim( genemy, result, breakType ); + winAnim = PM_SaberLockWinAnim(result, breakType); + if (winAnim != -1) { // a single vs. single break + if (genemy && genemy->client) { + loseAnim = PM_SaberLockLoseAnim(genemy, result, breakType); } - } - else - {//must be a saberlock that's not between single and single... + } else { // must be a saberlock that's not between single and single... singleVsSingle = qfalse; - winAnim = PM_SaberLockResultAnim( gent, breakType, SABERLOCK_WIN ); + winAnim = PM_SaberLockResultAnim(gent, breakType, SABERLOCK_WIN); pm->ps->weaponstate = WEAPON_FIRING; - if ( genemy && genemy->client ) - { - loseAnim = PM_SaberLockResultAnim( genemy, breakType, SABERLOCK_LOSE ); + if (genemy && genemy->client) { + loseAnim = PM_SaberLockResultAnim(genemy, breakType, SABERLOCK_LOSE); genemy->client->ps.weaponstate = WEAPON_READY; } } - if ( d_saberCombat->integer ) - { - Com_Printf( "%s won saber lock, anim = %s!\n", gent->NPC_type, animTable[winAnim].name ); - Com_Printf( "%s lost saber lock, anim = %s!\n", genemy->NPC_type, animTable[loseAnim].name ); + if (d_saberCombat->integer) { + Com_Printf("%s won saber lock, anim = %s!\n", gent->NPC_type, animTable[winAnim].name); + Com_Printf("%s lost saber lock, anim = %s!\n", genemy->NPC_type, animTable[loseAnim].name); } pm->ps->saberLockTime = genemy->client->ps.saberLockTime = 0; pm->ps->saberLockEnemy = genemy->client->ps.saberLockEnemy = ENTITYNUM_NONE; pm->ps->saberMoveNext = LS_NONE; - if ( genemy && genemy->client ) - { + if (genemy && genemy->client) { genemy->client->ps.saberMoveNext = LS_NONE; } - PM_AddEvent( EV_JUMP ); - if ( result == LOCK_STALEMATE ) - {//no-one won - G_AddEvent( genemy, EV_JUMP, 0 ); - } - else - { - if ( pm->ps->clientNum ) - {//an NPC - pm->ps->saberEventFlags |= SEF_LOCK_WON;//tell the winner to press the advantage - } - //painDebounceTime will stop them from doing anything - genemy->painDebounceTime = level.time + genemy->client->ps.torsoAnimTimer + 500; - if ( Q_irand( 0, 1 ) ) - { - G_AddEvent( genemy, EV_PAIN, Q_irand( 0, 75 ) ); + PM_AddEvent(EV_JUMP); + if (result == LOCK_STALEMATE) { // no-one won + G_AddEvent(genemy, EV_JUMP, 0); + } else { + if (pm->ps->clientNum) { // an NPC + pm->ps->saberEventFlags |= SEF_LOCK_WON; // tell the winner to press the advantage } - else - { - if ( genemy->NPC ) - { + // painDebounceTime will stop them from doing anything + genemy->painDebounceTime = level.time + genemy->client->ps.torsoAnimTimer + 500; + if (Q_irand(0, 1)) { + G_AddEvent(genemy, EV_PAIN, Q_irand(0, 75)); + } else { + if (genemy->NPC) { genemy->NPC->blockedSpeechDebounceTime = 0; } - G_AddVoiceEvent( genemy, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 500 ); + G_AddVoiceEvent(genemy, Q_irand(EV_PUSHED1, EV_PUSHED3), 500); } - if ( result == LOCK_VICTORY ) - {//one person won - if ( Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_2 ) < pm->ps->forcePowerLevel[FP_SABER_OFFENSE] ) - { - vec3_t throwDir = {0,0,350}; - int winMove = pm->ps->saberMove; - if ( !singleVsSingle ) - {//all others have their own super breaks - //so it doesn't try to set some other anim below + if (result == LOCK_VICTORY) { // one person won + if (Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_2) < pm->ps->forcePowerLevel[FP_SABER_OFFENSE]) { + vec3_t throwDir = {0, 0, 350}; + int winMove = pm->ps->saberMove; + if (!singleVsSingle) { // all others have their own super breaks + // so it doesn't try to set some other anim below winAnim = -1; - } - else if ( winAnim == BOTH_LK_S_S_S_SB_1_W - || winAnim == BOTH_LK_S_S_T_SB_1_W ) - {//doing a superbreak on single-vs-single, don't do the old superbreaks this time - //so it doesn't try to set some other anim below + } else if (winAnim == BOTH_LK_S_S_S_SB_1_W || + winAnim == BOTH_LK_S_S_T_SB_1_W) { // doing a superbreak on single-vs-single, don't do the old superbreaks this time + // so it doesn't try to set some other anim below winAnim = -1; - } - else - {//JK2-style - switch ( winAnim ) - { + } else { // JK2-style + switch (winAnim) { case BOTH_A3_T__B_: winAnim = BOTH_D1_TL___; winMove = LS_D1_TL; - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_K1_S1_T_: - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_CWCIRCLEBREAK: - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_CCWCIRCLEBREAK: winAnim = BOTH_A1_BR_TL; winMove = LS_A_BR2TL; - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; } - if ( winAnim != BOTH_CCWCIRCLEBREAK ) - { - if ( (!genemy->s.number&&genemy->health<=25)//player low on health - ||(genemy->s.number&&genemy->client->NPC_class!=CLASS_KYLE&&genemy->client->NPC_class!=CLASS_LUKE&&genemy->client->NPC_class!=CLASS_TAVION&&genemy->client->NPC_class!=CLASS_ALORA&&genemy->client->NPC_class!=CLASS_DESANN)//any NPC that's not a boss character - ||(genemy->s.number&&genemy->health<=50) )//boss character with less than 50 health left - {//possibly knock saber out of hand OR cut hand off! - if ( Q_irand( 0, 25 ) < victoryStrength - && ((!genemy->s.number&&genemy->health<=10)||genemy->s.number) ) - { - NPC_SetAnim( genemy, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//force this + if (winAnim != BOTH_CCWCIRCLEBREAK) { + if ((!genemy->s.number && genemy->health <= 25) // player low on health + || (genemy->s.number && genemy->client->NPC_class != CLASS_KYLE && genemy->client->NPC_class != CLASS_LUKE && + genemy->client->NPC_class != CLASS_TAVION && genemy->client->NPC_class != CLASS_ALORA && + genemy->client->NPC_class != CLASS_DESANN) // any NPC that's not a boss character + || (genemy->s.number && genemy->health <= 50)) // boss character with less than 50 health left + { // possibly knock saber out of hand OR cut hand off! + if (Q_irand(0, 25) < victoryStrength && ((!genemy->s.number && genemy->health <= 10) || genemy->s.number)) { + NPC_SetAnim(genemy, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // force this genemy->client->dismembered = false; - G_DoDismemberment( genemy, genemy->client->renderInfo.handRPoint, MOD_SABER, 1000, HL_HAND_RT, qtrue ); - G_Damage( genemy, gent, gent, throwDir, genemy->client->renderInfo.handRPoint, genemy->health+10, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_SABER, HL_NONE ); + G_DoDismemberment(genemy, genemy->client->renderInfo.handRPoint, MOD_SABER, 1000, HL_HAND_RT, qtrue); + G_Damage(genemy, gent, gent, throwDir, genemy->client->renderInfo.handRPoint, genemy->health + 10, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_SABER, HL_NONE); - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer + 500; pm->ps->saberMove = winMove; pm->ps->saberBlocked = BLOCKED_NONE; @@ -10350,38 +8278,30 @@ void PM_SaberLockBreak( gentity_t *gent, gentity_t *genemy, saberLockResult_t re } } } - //else see if we can knock the saber out of their hand - //FIXME: for now, always disarm the right-hand saber - if ( !(genemy->client->ps.saber[0].saberFlags&SFL_NOT_DISARMABLE) ) - { - //add disarmBonus into this check - victoryStrength += pm->ps->SaberDisarmBonus( 0 )*2; - if ( (genemy->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) - || (genemy->client->ps.dualSabers && genemy->client->ps.saber[1].Active()) ) - {//defender gets a bonus for using a 2-handed saber or 2 sabers + // else see if we can knock the saber out of their hand + // FIXME: for now, always disarm the right-hand saber + if (!(genemy->client->ps.saber[0].saberFlags & SFL_NOT_DISARMABLE)) { + // add disarmBonus into this check + victoryStrength += pm->ps->SaberDisarmBonus(0) * 2; + if ((genemy->client->ps.saber[0].saberFlags & SFL_TWO_HANDED) || + (genemy->client->ps.dualSabers && + genemy->client->ps.saber[1].Active())) { // defender gets a bonus for using a 2-handed saber or 2 sabers victoryStrength -= 2; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowersActive & (1 << FP_RAGE)) { victoryStrength += gent->client->ps.forcePowerLevel[FP_RAGE]; - } - else if ( pm->ps->forceRageRecoveryTime > pm->cmd.serverTime ) - { + } else if (pm->ps->forceRageRecoveryTime > pm->cmd.serverTime) { victoryStrength--; } - if ( genemy->client->ps.forceRageRecoveryTime > pm->cmd.serverTime ) - { + if (genemy->client->ps.forceRageRecoveryTime > pm->cmd.serverTime) { victoryStrength++; } - if ( Q_irand( 0, 10 ) < victoryStrength ) - { - if ( !(genemy->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) - || !Q_irand( 0, 1 ) ) - {//if it's a two-handed saber, it has a 50% chance of resisting a disarming - WP_SaberLose( genemy, throwDir ); - if ( winAnim != -1 ) - { - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (Q_irand(0, 10) < victoryStrength) { + if (!(genemy->client->ps.saber[0].saberFlags & SFL_TWO_HANDED) || + !Q_irand(0, 1)) { // if it's a two-handed saber, it has a 50% chance of resisting a disarming + WP_SaberLose(genemy, throwDir); + if (winAnim != -1) { + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer; pm->ps->saberMove = winMove; pm->ps->saberBlocked = BLOCKED_NONE; @@ -10395,60 +8315,40 @@ void PM_SaberLockBreak( gentity_t *gent, gentity_t *genemy, saberLockResult_t re } } -int G_SaberLockStrength( gentity_t *gent ) -{ +int G_SaberLockStrength(gentity_t *gent) { int strength = gent->client->ps.saber[0].lockBonus; - if ( (gent->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - { + if ((gent->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { strength += 1; } - if ( gent->client->ps.dualSabers && gent->client->ps.saber[1].Active() ) - { + if (gent->client->ps.dualSabers && gent->client->ps.saber[1].Active()) { strength += 1 + gent->client->ps.saber[1].lockBonus; } - if ( gent->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_RAGE)) { strength += gent->client->ps.forcePowerLevel[FP_RAGE]; - } - else if ( gent->client->ps.forceRageRecoveryTime > pm->cmd.serverTime ) - { + } else if (gent->client->ps.forceRageRecoveryTime > pm->cmd.serverTime) { strength--; } - if ( gent->s.number >= MAX_CLIENTS ) - { - if ( gent->client->NPC_class == CLASS_DESANN || gent->client->NPC_class == CLASS_LUKE ) - { - strength += 5+Q_irand(0,g_spskill->integer); - } - else - { - strength += gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE]+Q_irand(0,g_spskill->integer); - if ( gent->NPC ) - { - if ( (gent->NPC->aiFlags&NPCAI_BOSS_CHARACTER) - || (gent->NPC->aiFlags&NPCAI_ROSH) - || gent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - strength += Q_irand(0,2); - } - else if ( (gent->NPC->aiFlags&NPCAI_SUBBOSS_CHARACTER) ) - { - strength += Q_irand(-1,1); + if (gent->s.number >= MAX_CLIENTS) { + if (gent->client->NPC_class == CLASS_DESANN || gent->client->NPC_class == CLASS_LUKE) { + strength += 5 + Q_irand(0, g_spskill->integer); + } else { + strength += gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] + Q_irand(0, g_spskill->integer); + if (gent->NPC) { + if ((gent->NPC->aiFlags & NPCAI_BOSS_CHARACTER) || (gent->NPC->aiFlags & NPCAI_ROSH) || gent->client->NPC_class == CLASS_SHADOWTROOPER) { + strength += Q_irand(0, 2); + } else if ((gent->NPC->aiFlags & NPCAI_SUBBOSS_CHARACTER)) { + strength += Q_irand(-1, 1); } } } - } - else - {//player - strength += gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE]+Q_irand(0,g_spskill->integer)+Q_irand(0,1); + } else { // player + strength += gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] + Q_irand(0, g_spskill->integer) + Q_irand(0, 1); } return strength; } -qboolean PM_InSaberLockOld( int anim ) -{ - switch ( anim ) - { +qboolean PM_InSaberLockOld(int anim) { + switch (anim) { case BOTH_BF2LOCK: case BOTH_BF1LOCK: case BOTH_CWCIRCLELOCK: @@ -10458,28 +8358,26 @@ qboolean PM_InSaberLockOld( int anim ) return qfalse; } -qboolean PM_InSaberLock( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_DL_T_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_ST_S_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_ST_T_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_S_S_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_S_T_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_DL_DL_S_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_T_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_ST_S_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_ST_T_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_S_S_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_S_T_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_ST_DL_S_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_DL_T_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_ST_S_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_T_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_S_S_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_S_T_L_1: //lock if I'm using staff vs. a single +qboolean PM_InSaberLock(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_DL_T_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_ST_S_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_ST_T_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_S_S_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_S_T_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_DL_DL_S_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_T_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_ST_S_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_ST_T_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_S_S_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_S_T_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_ST_DL_S_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_DL_T_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_ST_S_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_T_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_S_S_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_S_T_L_1: // lock if I'm using staff vs. a single case BOTH_LK_S_S_S_L_2: case BOTH_LK_S_S_T_L_2: case BOTH_LK_DL_DL_S_L_2: @@ -10489,329 +8387,242 @@ qboolean PM_InSaberLock( int anim ) return qtrue; break; default: - return PM_InSaberLockOld( anim ); + return PM_InSaberLockOld(anim); break; } - //return qfalse; + // return qfalse; } -extern qboolean ValidAnimFileIndex ( int index ); -extern qboolean G_CheckIncrementLockAnim( int anim, int winOrLose ); -qboolean PM_SaberLocked( void ) -{ - //FIXME: maybe kick out of saberlock? - if ( pm->ps->saberLockEnemy == ENTITYNUM_NONE ) - { - if ( PM_InSaberLock( pm->ps->torsoAnim ) ) - {//wtf? Maybe enemy died? - PM_SaberLockWinAnim( LOCK_STALEMATE, SABERLOCK_BREAK ); +extern qboolean ValidAnimFileIndex(int index); +extern qboolean G_CheckIncrementLockAnim(int anim, int winOrLose); +qboolean PM_SaberLocked(void) { + // FIXME: maybe kick out of saberlock? + if (pm->ps->saberLockEnemy == ENTITYNUM_NONE) { + if (PM_InSaberLock(pm->ps->torsoAnim)) { // wtf? Maybe enemy died? + PM_SaberLockWinAnim(LOCK_STALEMATE, SABERLOCK_BREAK); } return qfalse; } gentity_t *gent = pm->gent; - if ( !gent ) - { + if (!gent) { return qfalse; } gentity_t *genemy = &g_entities[pm->ps->saberLockEnemy]; - if ( !genemy ) - { + if (!genemy) { return qfalse; } - if ( PM_InSaberLock( pm->ps->torsoAnim ) && PM_InSaberLock( genemy->client->ps.torsoAnim ) ) - { - if ( pm->ps->saberLockTime <= level.time + 500 - && pm->ps->saberLockEnemy != ENTITYNUM_NONE ) - {//lock just ended - int strength = G_SaberLockStrength( gent ); - int eStrength = G_SaberLockStrength( genemy ); - if ( strength > 1 && eStrength > 1 && !Q_irand( 0, abs(strength-eStrength)+1 ) ) - {//both knock each other down! - PM_SaberLockBreak( gent, genemy, LOCK_DRAW, 0 ); - } - else - {//both "win" - PM_SaberLockBreak( gent, genemy, LOCK_STALEMATE, 0 ); + if (PM_InSaberLock(pm->ps->torsoAnim) && PM_InSaberLock(genemy->client->ps.torsoAnim)) { + if (pm->ps->saberLockTime <= level.time + 500 && pm->ps->saberLockEnemy != ENTITYNUM_NONE) { // lock just ended + int strength = G_SaberLockStrength(gent); + int eStrength = G_SaberLockStrength(genemy); + if (strength > 1 && eStrength > 1 && !Q_irand(0, abs(strength - eStrength) + 1)) { // both knock each other down! + PM_SaberLockBreak(gent, genemy, LOCK_DRAW, 0); + } else { // both "win" + PM_SaberLockBreak(gent, genemy, LOCK_STALEMATE, 0); } return qtrue; - } - else if ( pm->ps->saberLockTime < level.time ) - {//done... tie breaker above should have handled this, but...? - if ( PM_InSaberLock( pm->ps->torsoAnim ) && pm->ps->torsoAnimTimer > 0 ) - { + } else if (pm->ps->saberLockTime < level.time) { // done... tie breaker above should have handled this, but...? + if (PM_InSaberLock(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer > 0) { pm->ps->torsoAnimTimer = 0; } - if ( PM_InSaberLock( pm->ps->legsAnim ) && pm->ps->legsAnimTimer > 0 ) - { + if (PM_InSaberLock(pm->ps->legsAnim) && pm->ps->legsAnimTimer > 0) { pm->ps->legsAnimTimer = 0; } return qfalse; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK ) - {//holding attack - if ( !(pm->ps->pm_flags&PMF_ATTACK_HELD) ) - {//tapping - int remaining = 0; - if( ValidAnimFileIndex( gent->client->clientInfo.animFileIndex ) ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK) { // holding attack + if (!(pm->ps->pm_flags & PMF_ATTACK_HELD)) { // tapping + int remaining = 0; + if (ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) { animation_t *anim; - float currentFrame, junk2; - int curFrame, junk; - int strength = 1; + float currentFrame, junk2; + int curFrame, junk; + int strength = 1; anim = &level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations[pm->ps->torsoAnim]; #ifdef _DEBUG qboolean ret = #endif - gi.G2API_GetBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, - (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, (cg.time ? cg.time : level.time), ¤tFrame, + &junk, &junk, &junk, &junk2, NULL); #ifdef _DEBUG - assert( ret ); // this would be pretty bad, the below code seems to assume the call succeeds. -gil + assert(ret); // this would be pretty bad, the below code seems to assume the call succeeds. -gil #endif - strength = G_SaberLockStrength( gent ); - if ( PM_InSaberLockOld( pm->ps->torsoAnim ) ) - {//old locks - if ( pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK || - pm->ps->torsoAnim == BOTH_BF2LOCK ) - { - curFrame = floor( currentFrame )-strength; - //drop my frame one - if ( curFrame <= anim->firstFrame ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + strength = G_SaberLockStrength(gent); + if (PM_InSaberLockOld(pm->ps->torsoAnim)) { // old locks + if (pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK || pm->ps->torsoAnim == BOTH_BF2LOCK) { + curFrame = floor(currentFrame) - strength; + // drop my frame one + if (curFrame <= anim->firstFrame) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = curFrame-anim->firstFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = curFrame - anim->firstFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } - } - else - { - curFrame = ceil( currentFrame )+strength; - //advance my frame one - if ( curFrame >= anim->firstFrame+anim->numFrames ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + } else { + curFrame = ceil(currentFrame) + strength; + // advance my frame one + if (curFrame >= anim->firstFrame + anim->numFrames) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = anim->firstFrame+anim->numFrames-curFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = anim->firstFrame + anim->numFrames - curFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } } - } - else - {//new locks - if ( G_CheckIncrementLockAnim( pm->ps->torsoAnim, SABERLOCK_WIN ) ) - { - curFrame = ceil( currentFrame )+strength; - //advance my frame one - if ( curFrame >= anim->firstFrame+anim->numFrames ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + } else { // new locks + if (G_CheckIncrementLockAnim(pm->ps->torsoAnim, SABERLOCK_WIN)) { + curFrame = ceil(currentFrame) + strength; + // advance my frame one + if (curFrame >= anim->firstFrame + anim->numFrames) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = anim->firstFrame+anim->numFrames-curFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = anim->firstFrame + anim->numFrames - curFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } - } - else - { - curFrame = floor( currentFrame )-strength; - //drop my frame one - if ( curFrame <= anim->firstFrame ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + } else { + curFrame = floor(currentFrame) - strength; + // drop my frame one + if (curFrame <= anim->firstFrame) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = curFrame-anim->firstFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = curFrame - anim->firstFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } } } - if ( !Q_irand( 0, 2 ) ) - { - if ( pm->ps->clientNum < MAX_CLIENTS ) - { - if ( !Q_irand( 0, 3 ) ) - { - PM_AddEvent( EV_JUMP ); - } - else - { - PM_AddEvent( Q_irand( EV_PUSHED1, EV_PUSHED3 ) ); + if (!Q_irand(0, 2)) { + if (pm->ps->clientNum < MAX_CLIENTS) { + if (!Q_irand(0, 3)) { + PM_AddEvent(EV_JUMP); + } else { + PM_AddEvent(Q_irand(EV_PUSHED1, EV_PUSHED3)); } - } - else - { - if ( gent->NPC && gent->NPC->blockedSpeechDebounceTime < level.time ) - { - switch ( Q_irand( 0, 3 ) ) - { + } else { + if (gent->NPC && gent->NPC->blockedSpeechDebounceTime < level.time) { + switch (Q_irand(0, 3)) { case 0: - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); break; case 1: - PM_AddEvent( Q_irand( EV_ANGER1, EV_ANGER3 ) ); + PM_AddEvent(Q_irand(EV_ANGER1, EV_ANGER3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; case 2: - PM_AddEvent( Q_irand( EV_TAUNT1, EV_TAUNT3 ) ); + PM_AddEvent(Q_irand(EV_TAUNT1, EV_TAUNT3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; case 3: - PM_AddEvent( Q_irand( EV_GLOAT1, EV_GLOAT3 ) ); + PM_AddEvent(Q_irand(EV_GLOAT1, EV_GLOAT3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; } } } } - } - else - { + } else { return qfalse; } - if( ValidAnimFileIndex( genemy->client->clientInfo.animFileIndex ) ) - { + if (ValidAnimFileIndex(genemy->client->clientInfo.animFileIndex)) { animation_t *anim; anim = &level.knownAnimFileSets[genemy->client->clientInfo.animFileIndex].animations[genemy->client->ps.torsoAnim]; /* float currentFrame, junk2; int junk; - gi.G2API_GetBoneAnimIndex( &genemy->ghoul2[genemy->playerModel], genemy->lowerLumbarBone, (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex( &genemy->ghoul2[genemy->playerModel], genemy->lowerLumbarBone, (cg.time?cg.time:level.time), ¤tFrame, + &junk, &junk, &junk, &junk2, NULL ); */ - if ( !Q_irand( 0, 2 ) ) - { - switch ( Q_irand( 0, 3 ) ) - { + if (!Q_irand(0, 2)) { + switch (Q_irand(0, 3)) { case 0: - G_AddEvent( genemy, EV_PAIN, floor((float)genemy->health/genemy->max_health*100.0f) ); + G_AddEvent(genemy, EV_PAIN, floor((float)genemy->health / genemy->max_health * 100.0f)); break; case 1: - G_AddVoiceEvent( genemy, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 500 ); + G_AddVoiceEvent(genemy, Q_irand(EV_PUSHED1, EV_PUSHED3), 500); break; case 2: - G_AddVoiceEvent( genemy, Q_irand( EV_CHOKE1, EV_CHOKE3 ), 500 ); + G_AddVoiceEvent(genemy, Q_irand(EV_CHOKE1, EV_CHOKE3), 500); break; case 3: - G_AddVoiceEvent( genemy, EV_PUSHFAIL, 2000 ); + G_AddVoiceEvent(genemy, EV_PUSHFAIL, 2000); break; } } - if ( PM_InSaberLockOld( genemy->client->ps.torsoAnim ) ) - { - if ( genemy->client->ps.torsoAnim == BOTH_CCWCIRCLELOCK || - genemy->client->ps.torsoAnim == BOTH_BF2LOCK ) - { - PM_SetAnimFrame( genemy, anim->firstFrame+anim->numFrames-remaining, qtrue, qtrue ); - } - else - { - PM_SetAnimFrame( genemy, anim->firstFrame+remaining, qtrue, qtrue ); + if (PM_InSaberLockOld(genemy->client->ps.torsoAnim)) { + if (genemy->client->ps.torsoAnim == BOTH_CCWCIRCLELOCK || genemy->client->ps.torsoAnim == BOTH_BF2LOCK) { + PM_SetAnimFrame(genemy, anim->firstFrame + anim->numFrames - remaining, qtrue, qtrue); + } else { + PM_SetAnimFrame(genemy, anim->firstFrame + remaining, qtrue, qtrue); } - } - else - {//new locks + } else { // new locks //??? - if ( G_CheckIncrementLockAnim( genemy->client->ps.torsoAnim, SABERLOCK_LOSE ) ) - { - PM_SetAnimFrame( genemy, anim->firstFrame+anim->numFrames-remaining, qtrue, qtrue ); - } - else - { - PM_SetAnimFrame( genemy, anim->firstFrame+remaining, qtrue, qtrue ); + if (G_CheckIncrementLockAnim(genemy->client->ps.torsoAnim, SABERLOCK_LOSE)) { + PM_SetAnimFrame(genemy, anim->firstFrame + anim->numFrames - remaining, qtrue, qtrue); + } else { + PM_SetAnimFrame(genemy, anim->firstFrame + remaining, qtrue, qtrue); } } } } + } else { // FIXME: other ways out of a saberlock? + // force-push? (requires more force power?) + // kick? (requires anim ... hit jump key?) + // roll? + // backflip? } - else - {//FIXME: other ways out of a saberlock? - //force-push? (requires more force power?) - //kick? (requires anim ... hit jump key?) - //roll? - //backflip? - } - } - else - {//something broke us out of it - if ( gent->painDebounceTime > level.time && genemy->painDebounceTime > level.time ) - { - PM_SaberLockBreak( gent, genemy, LOCK_DRAW, 0 ); - } - else if ( gent->painDebounceTime > level.time ) - { - PM_SaberLockBreak( genemy, gent, LOCK_VICTORY, 0 ); - } - else if ( genemy->painDebounceTime > level.time ) - { - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, 0 ); - } - else - { - PM_SaberLockBreak( gent, genemy, LOCK_STALEMATE, 0 ); + } else { // something broke us out of it + if (gent->painDebounceTime > level.time && genemy->painDebounceTime > level.time) { + PM_SaberLockBreak(gent, genemy, LOCK_DRAW, 0); + } else if (gent->painDebounceTime > level.time) { + PM_SaberLockBreak(genemy, gent, LOCK_VICTORY, 0); + } else if (genemy->painDebounceTime > level.time) { + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, 0); + } else { + PM_SaberLockBreak(gent, genemy, LOCK_STALEMATE, 0); } } return qtrue; } -qboolean G_EnemyInKickRange( gentity_t *self, gentity_t *enemy ) -{ - if ( !self || !enemy ) - { +qboolean G_EnemyInKickRange(gentity_t *self, gentity_t *enemy) { + if (!self || !enemy) { return qfalse; } - if ( fabs(self->currentOrigin[2]-enemy->currentOrigin[2]) < 32 ) - {//generally at same height - if ( DistanceHorizontal( self->currentOrigin, enemy->currentOrigin ) <= (STAFF_KICK_RANGE+8.0f+(self->maxs[0]*1.5f)+(enemy->maxs[0]*1.5f)) ) - {//within kicking range! + if (fabs(self->currentOrigin[2] - enemy->currentOrigin[2]) < 32) { // generally at same height + if (DistanceHorizontal(self->currentOrigin, enemy->currentOrigin) <= + (STAFF_KICK_RANGE + 8.0f + (self->maxs[0] * 1.5f) + (enemy->maxs[0] * 1.5f))) { // within kicking range! return qtrue; } } return qfalse; } -qboolean G_CanKickEntity( gentity_t *self, gentity_t *target ) -{ - if ( target && target->client - && !PM_InKnockDown( &target->client->ps ) - && G_EnemyInKickRange( self, target ) ) - { +qboolean G_CanKickEntity(gentity_t *self, gentity_t *target) { + if (target && target->client && !PM_InKnockDown(&target->client->ps) && G_EnemyInKickRange(self, target)) { return qtrue; } return qfalse; } -float PM_GroundDistance(void) -{ +float PM_GroundDistance(void) { trace_t tr; vec3_t down; @@ -10826,10 +8637,8 @@ float PM_GroundDistance(void) return VectorLength(down); } -float G_GroundDistance(gentity_t *self) -{ - if ( !self ) - {//wtf?!! +float G_GroundDistance(gentity_t *self) { + if (!self) { // wtf?!! return Q3_INFINITE; } trace_t tr; @@ -10846,63 +8655,44 @@ float G_GroundDistance(gentity_t *self) return VectorLength(down); } -saberMoveName_t G_PickAutoKick( gentity_t *self, gentity_t *enemy, qboolean storeMove ) -{ +saberMoveName_t G_PickAutoKick(gentity_t *self, gentity_t *enemy, qboolean storeMove) { saberMoveName_t kickMove = LS_NONE; - if ( !self || !self->client ) - { + if (!self || !self->client) { return LS_NONE; } - if ( !enemy ) - { + if (!enemy) { return LS_NONE; } - vec3_t v_fwd, v_rt, enemyDir, fwdAngs = {0,self->client->ps.viewangles[YAW],0}; - VectorSubtract( enemy->currentOrigin, self->currentOrigin, enemyDir ); - VectorNormalize( enemyDir );//not necessary, I guess, but doesn't happen often - AngleVectors( fwdAngs, v_fwd, v_rt, NULL ); - float fDot = DotProduct( enemyDir, v_fwd ); - float rDot = DotProduct( enemyDir, v_rt ); - if ( fabs( rDot ) > 0.5f && fabs( fDot ) < 0.5f ) - {//generally to one side - if ( rDot > 0 ) - {//kick right + vec3_t v_fwd, v_rt, enemyDir, fwdAngs = {0, self->client->ps.viewangles[YAW], 0}; + VectorSubtract(enemy->currentOrigin, self->currentOrigin, enemyDir); + VectorNormalize(enemyDir); // not necessary, I guess, but doesn't happen often + AngleVectors(fwdAngs, v_fwd, v_rt, NULL); + float fDot = DotProduct(enemyDir, v_fwd); + float rDot = DotProduct(enemyDir, v_rt); + if (fabs(rDot) > 0.5f && fabs(fDot) < 0.5f) { // generally to one side + if (rDot > 0) { // kick right kickMove = LS_KICK_R; - } - else - {//kick left + } else { // kick left kickMove = LS_KICK_L; } - } - else if ( fabs( fDot ) > 0.5f && fabs( rDot ) < 0.5f ) - {//generally in front or behind us - if ( fDot > 0 ) - {//kick fwd + } else if (fabs(fDot) > 0.5f && fabs(rDot) < 0.5f) { // generally in front or behind us + if (fDot > 0) { // kick fwd kickMove = LS_KICK_F; - } - else - {//kick back + } else { // kick back kickMove = LS_KICK_B; } - } - else - {//diagonal to us, kick would miss - } - if ( kickMove != LS_NONE ) - {//have a valid one to do - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//if in air, convert kick to an in-air kick - float gDist = G_GroundDistance( self ); - //let's only allow air kicks if a certain distance from the ground - //it's silly to be able to do them right as you land. - //also looks wrong to transition from a non-complete flip anim... - if ((!PM_FlippingAnim( self->client->ps.legsAnim ) || self->client->ps.legsAnimTimer <= 0) && - gDist > 64.0f && //strict minimum - gDist > (-self->client->ps.velocity[2])-64.0f //make sure we are high to ground relative to downward velocity as well - ) - { - switch ( kickMove ) - { + } else { // diagonal to us, kick would miss + } + if (kickMove != LS_NONE) { // have a valid one to do + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // if in air, convert kick to an in-air kick + float gDist = G_GroundDistance(self); + // let's only allow air kicks if a certain distance from the ground + // it's silly to be able to do them right as you land. + // also looks wrong to transition from a non-complete flip anim... + if ((!PM_FlippingAnim(self->client->ps.legsAnim) || self->client->ps.legsAnimTimer <= 0) && gDist > 64.0f && // strict minimum + gDist > (-self->client->ps.velocity[2]) - 64.0f // make sure we are high to ground relative to downward velocity as well + ) { + switch (kickMove) { case LS_KICK_F: kickMove = LS_KICK_F_AIR; break; @@ -10915,98 +8705,80 @@ saberMoveName_t G_PickAutoKick( gentity_t *self, gentity_t *enemy, qboolean stor case LS_KICK_L: kickMove = LS_KICK_L_AIR; break; - default: //oh well, can't do any other kick move while in-air + default: // oh well, can't do any other kick move while in-air kickMove = LS_NONE; break; } - } - else - {//leave it as a normal kick unless we're too high up - if ( gDist > 128.0f || self->client->ps.velocity[2] >= 0 ) - { //off ground, but too close to ground + } else { // leave it as a normal kick unless we're too high up + if (gDist > 128.0f || self->client->ps.velocity[2] >= 0) { // off ground, but too close to ground kickMove = LS_NONE; } } } - if ( storeMove ) - { + if (storeMove) { self->client->ps.saberMoveNext = kickMove; } } return kickMove; } -saberMoveName_t PM_PickAutoKick( gentity_t *enemy ) -{ - return G_PickAutoKick( pm->gent, enemy, qfalse ); -} +saberMoveName_t PM_PickAutoKick(gentity_t *enemy) { return G_PickAutoKick(pm->gent, enemy, qfalse); } -saberMoveName_t G_PickAutoMultiKick( gentity_t *self, qboolean allowSingles, qboolean storeMove ) -{ - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - vec3_t mins, maxs; - int i, e; - int radius = ((self->maxs[0]*1.5f)+(self->maxs[0]*1.5f)+STAFF_KICK_RANGE+24.0f);//a little wide on purpose - vec3_t center; +saberMoveName_t G_PickAutoMultiKick(gentity_t *self, qboolean allowSingles, qboolean storeMove) { + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + vec3_t mins, maxs; + int i, e; + int radius = ((self->maxs[0] * 1.5f) + (self->maxs[0] * 1.5f) + STAFF_KICK_RANGE + 24.0f); // a little wide on purpose + vec3_t center; saberMoveName_t kickMove, bestKick = LS_NONE; - float distToEnt, bestDistToEnt = Q3_INFINITE; - gentity_t *bestEnt = NULL; - int enemiesFront = 0; - int enemiesBack = 0; - int enemiesRight = 0; - int enemiesLeft = 0; - int enemiesSpin = 0; - - if ( !self || !self->client ) - { + float distToEnt, bestDistToEnt = Q3_INFINITE; + gentity_t *bestEnt = NULL; + int enemiesFront = 0; + int enemiesBack = 0; + int enemiesRight = 0; + int enemiesLeft = 0; + int enemiesSpin = 0; + + if (!self || !self->client) { return LS_NONE; } - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - int numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + int numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - //not a client? - if ( !ent->client ) + // not a client? + if (!ent->client) continue; - //ally? - if ( ent->client->playerTeam == self->client->playerTeam ) + // ally? + if (ent->client->playerTeam == self->client->playerTeam) continue; - //dead? - if ( ent->health <= 0 ) + // dead? + if (ent->health <= 0) continue; - //too far? - distToEnt = DistanceSquared( ent->currentOrigin, center ); - if ( distToEnt > (radius*radius) ) + // too far? + distToEnt = DistanceSquared(ent->currentOrigin, center); + if (distToEnt > (radius * radius)) continue; - kickMove = G_PickAutoKick( self, ent, qfalse ); - if ( kickMove == LS_KICK_F_AIR - && kickMove == LS_KICK_B_AIR - && kickMove == LS_KICK_R_AIR - && kickMove == LS_KICK_L_AIR ) - {//in air? Can't do multikicks - } - else - { - switch ( kickMove ) - { + kickMove = G_PickAutoKick(self, ent, qfalse); + if (kickMove == LS_KICK_F_AIR && kickMove == LS_KICK_B_AIR && kickMove == LS_KICK_R_AIR && kickMove == LS_KICK_L_AIR) { // in air? Can't do multikicks + } else { + switch (kickMove) { case LS_KICK_F: enemiesFront++; break; @@ -11024,150 +8796,109 @@ saberMoveName_t G_PickAutoMultiKick( gentity_t *self, qboolean allowSingles, qbo break; } } - if ( allowSingles ) - { - if ( kickMove != LS_NONE - && distToEnt < bestDistToEnt ) - { + if (allowSingles) { + if (kickMove != LS_NONE && distToEnt < bestDistToEnt) { bestKick = kickMove; bestEnt = ent; } } } kickMove = LS_NONE; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//can't do the multikicks in air - if ( enemiesFront && enemiesBack - && (enemiesFront+enemiesBack)-(enemiesRight+enemiesLeft)>1 ) - {//more enemies in front/back than left/right + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // can't do the multikicks in air + if (enemiesFront && enemiesBack && (enemiesFront + enemiesBack) - (enemiesRight + enemiesLeft) > 1) { // more enemies in front/back than left/right kickMove = LS_KICK_BF; - } - else if ( enemiesRight && enemiesLeft - && (enemiesRight+enemiesLeft)-(enemiesFront+enemiesBack)>1 ) - {//more enemies on left & right than front/back + } else if (enemiesRight && enemiesLeft && + (enemiesRight + enemiesLeft) - (enemiesFront + enemiesBack) > 1) { // more enemies on left & right than front/back kickMove = LS_KICK_RL; - } - else if ( (enemiesFront || enemiesBack) && (enemiesRight || enemiesLeft) ) - {//at least 2 enemies around us, not aligned + } else if ((enemiesFront || enemiesBack) && (enemiesRight || enemiesLeft)) { // at least 2 enemies around us, not aligned kickMove = LS_KICK_S; - } - else if ( enemiesSpin > 1 ) - {//at least 2 enemies around us, not aligned + } else if (enemiesSpin > 1) { // at least 2 enemies around us, not aligned kickMove = LS_KICK_S; } } - if ( kickMove == LS_NONE - && bestKick != LS_NONE ) - {//no good multi-kick move, but we do have a nice single-kick we found + if (kickMove == LS_NONE && bestKick != LS_NONE) { // no good multi-kick move, but we do have a nice single-kick we found kickMove = bestKick; - //get mad at him so he knows he's being targetted - if ( (self->s.number < MAX_CLIENTS||G_ControlledByPlayer(self)) - && bestEnt != NULL ) - {//player - G_SetEnemy( self, bestEnt ); + // get mad at him so he knows he's being targetted + if ((self->s.number < MAX_CLIENTS || G_ControlledByPlayer(self)) && bestEnt != NULL) { // player + G_SetEnemy(self, bestEnt); } } - if ( kickMove != LS_NONE ) - { - if ( storeMove ) - { + if (kickMove != LS_NONE) { + if (storeMove) { self->client->ps.saberMoveNext = kickMove; } } return kickMove; } -qboolean PM_PickAutoMultiKick( qboolean allowSingles ) -{ - saberMoveName_t kickMove = G_PickAutoMultiKick( pm->gent, allowSingles, qfalse ); - if ( kickMove != LS_NONE ) - { - PM_SetSaberMove( kickMove ); +qboolean PM_PickAutoMultiKick(qboolean allowSingles) { + saberMoveName_t kickMove = G_PickAutoMultiKick(pm->gent, allowSingles, qfalse); + if (kickMove != LS_NONE) { + PM_SetSaberMove(kickMove); return qtrue; } return qfalse; } -qboolean PM_SaberThrowable( void ) -{ - //ugh, hard-coding this is bad... - if ( pm->ps->saberAnimLevel == SS_STAFF ) - { +qboolean PM_SaberThrowable(void) { + // ugh, hard-coding this is bad... + if (pm->ps->saberAnimLevel == SS_STAFF) { return qfalse; } - if ( !(pm->ps->saber[0].saberFlags&SFL_NOT_THROWABLE) ) - {//yes, this saber is always throwable + if (!(pm->ps->saber[0].saberFlags & SFL_NOT_THROWABLE)) { // yes, this saber is always throwable return qtrue; } - //saber is not normally throwable - if ( (pm->ps->saber[0].saberFlags&SFL_SINGLE_BLADE_THROWABLE) ) - {//it is throwable if only one blade is on - if ( pm->ps->saber[0].numBlades > 1 ) - {//it has more than one blade + // saber is not normally throwable + if ((pm->ps->saber[0].saberFlags & SFL_SINGLE_BLADE_THROWABLE)) { // it is throwable if only one blade is on + if (pm->ps->saber[0].numBlades > 1) { // it has more than one blade int numBladesActive = 0; - for ( int i = 0; i < pm->ps->saber[0].numBlades; i++ ) - { - if ( pm->ps->saber[0].blade[i].active ) - { + for (int i = 0; i < pm->ps->saber[0].numBlades; i++) { + if (pm->ps->saber[0].blade[i].active) { numBladesActive++; } } - if ( numBladesActive == 1 ) - {//only 1 blade is on + if (numBladesActive == 1) { // only 1 blade is on return qtrue; } } } - //nope, can't throw it + // nope, can't throw it return qfalse; } -qboolean PM_CheckAltKickAttack( void ) -{ - if ( (pm->cmd.buttons&BUTTON_ALT_ATTACK) - && (!(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD) ||PM_SaberInReturn(pm->ps->saberMove)) - && (!PM_FlippingAnim(pm->ps->legsAnim)||pm->ps->legsAnimTimer<=250) - && (!PM_SaberThrowable()) - && pm->ps->SaberActive() - && !(pm->ps->saber[0].saberFlags&SFL_NO_KICKS)//okay to do kicks with this saber - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_KICKS) )//okay to do kicks with this saber - ) - { +qboolean PM_CheckAltKickAttack(void) { + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && (!(pm->ps->pm_flags & PMF_ALT_ATTACK_HELD) || PM_SaberInReturn(pm->ps->saberMove)) && + (!PM_FlippingAnim(pm->ps->legsAnim) || pm->ps->legsAnimTimer <= 250) && (!PM_SaberThrowable()) && pm->ps->SaberActive() && + !(pm->ps->saber[0].saberFlags & SFL_NO_KICKS) // okay to do kicks with this saber + && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_KICKS)) // okay to do kicks with this saber + ) { return qtrue; } return qfalse; } -qboolean PM_CheckUpsideDownAttack( void ) -{ - if ( pm->ps->saberMove != LS_READY ) - { +qboolean PM_CheckUpsideDownAttack(void) { + if (pm->ps->saberMove != LS_READY) { return qfalse; } - if ( !(pm->cmd.buttons&BUTTON_ATTACK) ) - { + if (!(pm->cmd.buttons & BUTTON_ATTACK)) { return qfalse; } - if ( pm->ps->saberAnimLevel < SS_FAST - || pm->ps->saberAnimLevel > SS_STRONG ) - { + if (pm->ps->saberAnimLevel < SS_FAST || pm->ps->saberAnimLevel > SS_STRONG) { return qfalse; } - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - {//FIXME: check ranks? + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { // FIXME: check ranks? return qfalse; } - //FIXME: enemy below - //FIXME: more than 64 off ground - if ( !g_debugMelee->integer ) - {//hmm, can't get this to work quite the way we wanted... secret move, then! + // FIXME: enemy below + // FIXME: more than 64 off ground + if (!g_debugMelee->integer) { // hmm, can't get this to work quite the way we wanted... secret move, then! return qfalse; } - switch( pm->ps->legsAnim ) - { + switch (pm->ps->legsAnim) { case BOTH_WALL_RUN_RIGHT_FLIP: case BOTH_WALL_RUN_LEFT_FLIP: case BOTH_WALL_FLIP_RIGHT: @@ -11177,131 +8908,114 @@ qboolean PM_CheckUpsideDownAttack( void ) case BOTH_FLIP_BACK3: case BOTH_WALL_FLIP_BACK1: case BOTH_ALORA_FLIP_B: - //JKA - case BOTH_FORCEWALLRUNFLIP_END: - { - float animLength = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, (animNumber_t)pm->ps->legsAnim ); - float elapsedTime = (float)(animLength-pm->ps->legsAnimTimer); - float midPoint = animLength/2.0f; - if ( elapsedTime < midPoint-100.0f - || elapsedTime > midPoint+100.0f ) - {//only a 200ms window (in middle of anim) of opportunity to do this move in these anims - return qfalse; - } + // JKA + case BOTH_FORCEWALLRUNFLIP_END: { + float animLength = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, (animNumber_t)pm->ps->legsAnim); + float elapsedTime = (float)(animLength - pm->ps->legsAnimTimer); + float midPoint = animLength / 2.0f; + if (elapsedTime < midPoint - 100.0f || + elapsedTime > midPoint + 100.0f) { // only a 200ms window (in middle of anim) of opportunity to do this move in these anims + return qfalse; } - //NOTE: falls through on purpose + } + // NOTE: falls through on purpose case BOTH_FLIP_HOLD7: pm->ps->pm_flags |= PMF_SLOW_MO_FALL; - PM_SetSaberMove( LS_UPSIDE_DOWN_ATTACK ); + PM_SetSaberMove(LS_UPSIDE_DOWN_ATTACK); return qtrue; break; } return qfalse; } -qboolean PM_SaberMoveOkayForKata( void ) -{ - if ( g_saberNewControlScheme->integer ) - { - if ( pm->ps->saberMove == LS_READY //not doing anything - || PM_SaberInReflect( pm->ps->saberMove ) )//interrupt a projectile blocking move +qboolean PM_SaberMoveOkayForKata(void) { + if (g_saberNewControlScheme->integer) { + if (pm->ps->saberMove == LS_READY // not doing anything + || PM_SaberInReflect(pm->ps->saberMove)) // interrupt a projectile blocking move { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//old control scheme, allow it to interrupt a start or ready - if ( pm->ps->saberMove == LS_READY - || PM_SaberInReflect( pm->ps->saberMove )//interrupt a projectile blocking move - || PM_SaberInStart( pm->ps->saberMove ) ) - { + } else { // old control scheme, allow it to interrupt a start or ready + if (pm->ps->saberMove == LS_READY || PM_SaberInReflect(pm->ps->saberMove) // interrupt a projectile blocking move + || PM_SaberInStart(pm->ps->saberMove)) { return qtrue; - } - else - { + } else { return qfalse; } } } -qboolean PM_CanDoKata( void ) -{ - if ( PM_InSecondaryStyle() ) - { +qboolean PM_CanDoKata(void) { + if (PM_InSecondaryStyle()) { return qfalse; } - if ( !pm->ps->saberInFlight//not throwing saber + if (!pm->ps->saberInFlight // not throwing saber && PM_SaberMoveOkayForKata() /* && pm->ps->saberAnimLevel >= SS_FAST//fast, med or strong style && pm->ps->saberAnimLevel <= SS_STRONG//FIXME: Tavion, too? */ - && pm->ps->groundEntityNum != ENTITYNUM_NONE//not in the air - && (pm->cmd.buttons&BUTTON_ATTACK)//pressing attack - && pm->cmd.forwardmove >=0 //not moving back (used to be !pm->cmd.forwardmove) - && !pm->cmd.rightmove//not moving r/l - && pm->cmd.upmove <= 0//not jumping...? - && G_TryingKataAttack(pm->gent,&pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*///holding focus - && G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER, qtrue )/*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER*/ )//SINGLE_SPECIAL_POWER )// have enough power - {//FIXME: check rage, etc... + && pm->ps->groundEntityNum != ENTITYNUM_NONE // not in the air + && (pm->cmd.buttons & BUTTON_ATTACK) // pressing attack + && pm->cmd.forwardmove >= 0 // not moving back (used to be !pm->cmd.forwardmove) + && !pm->cmd.rightmove // not moving r/l + && pm->cmd.upmove <= 0 // not jumping...? + && G_TryingKataAttack(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/ // holding focus + && G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER, + qtrue) /*pm->ps->forcePower >= SABER_ALT_ATTACK_POWER*/) // SINGLE_SPECIAL_POWER )// have enough power + { // FIXME: check rage, etc... return qtrue; } return qfalse; } -void PM_SaberDroidWeapon( void ) -{ +void PM_SaberDroidWeapon(void) { // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } // Now we react to a block action by the player's lightsaber. - if ( pm->ps->saberBlocked ) - { - switch ( pm->ps->saberBlocked ) - { - case BLOCKED_PARRY_BROKEN: - PM_SetAnim( pm, SETANIM_BOTH, Q_irand(BOTH_PAIN1,BOTH_PAIN3), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - pm->ps->weaponTime = pm->ps->legsAnimTimer; - break; - case BLOCKED_ATK_BOUNCE: - PM_SetAnim( pm, SETANIM_BOTH, Q_irand(BOTH_PAIN1,BOTH_PAIN3), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - pm->ps->weaponTime = pm->ps->legsAnimTimer; - break; - case BLOCKED_UPPER_RIGHT: - case BLOCKED_UPPER_RIGHT_PROJ: - case BLOCKED_LOWER_RIGHT: - case BLOCKED_LOWER_RIGHT_PROJ: - PM_SetAnim( pm, SETANIM_BOTH, BOTH_P1_S1_TR, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - pm->ps->legsAnimTimer += Q_irand( 200, 1000 ); - pm->ps->weaponTime = pm->ps->legsAnimTimer; - break; - case BLOCKED_UPPER_LEFT: - case BLOCKED_UPPER_LEFT_PROJ: - case BLOCKED_LOWER_LEFT: - case BLOCKED_LOWER_LEFT_PROJ: - PM_SetAnim( pm, SETANIM_BOTH, BOTH_P1_S1_TL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - pm->ps->legsAnimTimer += Q_irand( 200, 1000 ); - pm->ps->weaponTime = pm->ps->legsAnimTimer; - break; - case BLOCKED_TOP: - case BLOCKED_TOP_PROJ: - PM_SetAnim( pm, SETANIM_BOTH, BOTH_P1_S1_T_, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - pm->ps->legsAnimTimer += Q_irand( 200, 1000 ); - pm->ps->weaponTime = pm->ps->legsAnimTimer; - break; - default: - pm->ps->saberBlocked = BLOCKED_NONE; - break; + if (pm->ps->saberBlocked) { + switch (pm->ps->saberBlocked) { + case BLOCKED_PARRY_BROKEN: + PM_SetAnim(pm, SETANIM_BOTH, Q_irand(BOTH_PAIN1, BOTH_PAIN3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + pm->ps->weaponTime = pm->ps->legsAnimTimer; + break; + case BLOCKED_ATK_BOUNCE: + PM_SetAnim(pm, SETANIM_BOTH, Q_irand(BOTH_PAIN1, BOTH_PAIN3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + pm->ps->weaponTime = pm->ps->legsAnimTimer; + break; + case BLOCKED_UPPER_RIGHT: + case BLOCKED_UPPER_RIGHT_PROJ: + case BLOCKED_LOWER_RIGHT: + case BLOCKED_LOWER_RIGHT_PROJ: + PM_SetAnim(pm, SETANIM_BOTH, BOTH_P1_S1_TR, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + pm->ps->legsAnimTimer += Q_irand(200, 1000); + pm->ps->weaponTime = pm->ps->legsAnimTimer; + break; + case BLOCKED_UPPER_LEFT: + case BLOCKED_UPPER_LEFT_PROJ: + case BLOCKED_LOWER_LEFT: + case BLOCKED_LOWER_LEFT_PROJ: + PM_SetAnim(pm, SETANIM_BOTH, BOTH_P1_S1_TL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + pm->ps->legsAnimTimer += Q_irand(200, 1000); + pm->ps->weaponTime = pm->ps->legsAnimTimer; + break; + case BLOCKED_TOP: + case BLOCKED_TOP_PROJ: + PM_SetAnim(pm, SETANIM_BOTH, BOTH_P1_S1_T_, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + pm->ps->legsAnimTimer += Q_irand(200, 1000); + pm->ps->weaponTime = pm->ps->legsAnimTimer; + break; + default: + pm->ps->saberBlocked = BLOCKED_NONE; + break; } pm->ps->saberBlocked = BLOCKED_NONE; @@ -11313,66 +9027,52 @@ void PM_SaberDroidWeapon( void ) } } -void PM_TryGrab( void ) -{ - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE +void PM_TryGrab(void) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE //&& !pm->ps->saberInFlight - && pm->ps->weaponTime <= 0 )//< 200 ) + && pm->ps->weaponTime <= 0) //< 200 ) { - PM_SetAnim( pm, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->torsoAnimTimer += 200; pm->ps->weaponTime = pm->ps->torsoAnimTimer; pm->ps->saberMove = pm->ps->saberMoveNext = LS_READY; - VectorClear( pm->ps->velocity ); - VectorClear( pm->ps->moveDir ); + VectorClear(pm->ps->velocity); + VectorClear(pm->ps->moveDir); pm->cmd.rightmove = pm->cmd.forwardmove = pm->cmd.upmove = 0; - if ( pm->gent ) - { + if (pm->gent) { pm->gent->painDebounceTime = level.time + pm->ps->torsoAnimTimer; } pm->ps->SaberDeactivate(); } } -void PM_TryAirKick( saberMoveName_t kickMove ) -{ - if ( pm->ps->groundEntityNum < ENTITYNUM_NONE ) - {//just do it - PM_SetSaberMove( kickMove ); - } - else - { +void PM_TryAirKick(saberMoveName_t kickMove) { + if (pm->ps->groundEntityNum < ENTITYNUM_NONE) { // just do it + PM_SetSaberMove(kickMove); + } else { float gDist = PM_GroundDistance(); - //let's only allow air kicks if a certain distance from the ground - //it's silly to be able to do them right as you land. - //also looks wrong to transition from a non-complete flip anim... - if ((!PM_FlippingAnim( pm->ps->legsAnim ) || pm->ps->legsAnimTimer <= 0) && - gDist > 64.0f && //strict minimum - gDist > (-pm->ps->velocity[2])-64.0f //make sure we are high to ground relative to downward velocity as well - ) - { - PM_SetSaberMove( kickMove ); - } - else - {//leave it as a normal kick unless we're too high up - if ( gDist > 128.0f || pm->ps->velocity[2] >= 0 ) - { //off ground, but too close to ground - } - else - {//high close enough to ground to do a normal kick, convert it - switch ( kickMove ) - { + // let's only allow air kicks if a certain distance from the ground + // it's silly to be able to do them right as you land. + // also looks wrong to transition from a non-complete flip anim... + if ((!PM_FlippingAnim(pm->ps->legsAnim) || pm->ps->legsAnimTimer <= 0) && gDist > 64.0f && // strict minimum + gDist > (-pm->ps->velocity[2]) - 64.0f // make sure we are high to ground relative to downward velocity as well + ) { + PM_SetSaberMove(kickMove); + } else { // leave it as a normal kick unless we're too high up + if (gDist > 128.0f || pm->ps->velocity[2] >= 0) { // off ground, but too close to ground + } else { // high close enough to ground to do a normal kick, convert it + switch (kickMove) { case LS_KICK_F_AIR: - PM_SetSaberMove( LS_KICK_F ); + PM_SetSaberMove(LS_KICK_F); break; case LS_KICK_B_AIR: - PM_SetSaberMove( LS_KICK_B ); + PM_SetSaberMove(LS_KICK_B); break; case LS_KICK_R_AIR: - PM_SetSaberMove( LS_KICK_R ); + PM_SetSaberMove(LS_KICK_R); break; case LS_KICK_L_AIR: - PM_SetSaberMove( LS_KICK_L ); + PM_SetSaberMove(LS_KICK_L); break; default: break; @@ -11382,49 +9082,31 @@ void PM_TryAirKick( saberMoveName_t kickMove ) } } -void PM_CheckKick( void ) -{ - if ( !PM_KickMove( pm->ps->saberMove )//not already in a kick - && !(pm->ps->pm_flags&PMF_DUCKED)//not ducked - && (pm->cmd.upmove >= 0 ) )//not trying to duck - {//player kicks - //FIXME: only if FP_SABER_OFFENSE >= 3 - if ( pm->cmd.rightmove ) - {//kick to side - if ( pm->cmd.rightmove > 0 ) - {//kick right - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || pm->cmd.upmove > 0 ) - { - PM_TryAirKick( LS_KICK_R_AIR ); - } - else - { - PM_SetSaberMove( LS_KICK_R ); - } - } - else - {//kick left - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || pm->cmd.upmove > 0 ) - { - PM_TryAirKick( LS_KICK_L_AIR ); +void PM_CheckKick(void) { + if (!PM_KickMove(pm->ps->saberMove) // not already in a kick + && !(pm->ps->pm_flags & PMF_DUCKED) // not ducked + && (pm->cmd.upmove >= 0)) // not trying to duck + { // player kicks + // FIXME: only if FP_SABER_OFFENSE >= 3 + if (pm->cmd.rightmove) { // kick to side + if (pm->cmd.rightmove > 0) { // kick right + if (pm->ps->groundEntityNum == ENTITYNUM_NONE || pm->cmd.upmove > 0) { + PM_TryAirKick(LS_KICK_R_AIR); + } else { + PM_SetSaberMove(LS_KICK_R); } - else - { - PM_SetSaberMove( LS_KICK_L ); + } else { // kick left + if (pm->ps->groundEntityNum == ENTITYNUM_NONE || pm->cmd.upmove > 0) { + PM_TryAirKick(LS_KICK_L_AIR); + } else { + PM_SetSaberMove(LS_KICK_L); } } pm->cmd.rightmove = 0; - } - else if ( pm->cmd.forwardmove ) - {//kick front/back - if ( pm->cmd.forwardmove > 0 ) - {//kick fwd - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || pm->cmd.upmove > 0 ) - { - PM_TryAirKick( LS_KICK_F_AIR ); + } else if (pm->cmd.forwardmove) { // kick front/back + if (pm->cmd.forwardmove > 0) { // kick fwd + if (pm->ps->groundEntityNum == ENTITYNUM_NONE || pm->cmd.upmove > 0) { + PM_TryAirKick(LS_KICK_F_AIR); } /* else if ( pm->ps->weapon == WP_SABER @@ -11435,110 +9117,81 @@ void PM_CheckKick( void ) PM_SetSaberMove( LS_HILT_BASH ); } */ - else - { - PM_SetSaberMove( LS_KICK_F ); - } - } - else if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || pm->cmd.upmove > 0 ) - { - PM_TryAirKick( LS_KICK_B_AIR ); - } - else - {//kick back - PM_SetSaberMove( LS_KICK_B ); - } - pm->cmd.forwardmove = 0; - } - else if ( pm->gent - && pm->gent->enemy - && G_CanKickEntity( pm->gent, pm->gent->enemy ) ) - {//auto-pick? - if ( /*(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD) - && (pm->cmd.buttons&BUTTON_ATTACK) - &&*/ PM_PickAutoMultiKick( qfalse ) ) - {//kicked! - if ( pm->ps->saberMove == LS_KICK_RL ) - {//just pull back - if ( d_slowmodeath->integer > 3 ) - { - G_StartMatrixEffect( pm->gent, MEF_NO_SPIN, pm->ps->legsAnimTimer+500 ); - } - } - else - {//normal spin - if ( d_slowmodeath->integer > 3 ) - { - G_StartMatrixEffect( pm->gent, 0, pm->ps->legsAnimTimer+500 ); - } + else { + PM_SetSaberMove(LS_KICK_F); } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - &&( pm->ps->saberMove == LS_KICK_S - ||pm->ps->saberMove == LS_KICK_BF - ||pm->ps->saberMove == LS_KICK_RL ) ) - {//in the air and doing a jump-kick, which is a ground anim, so.... - //cut z velocity...? + } else if (pm->ps->groundEntityNum == ENTITYNUM_NONE || pm->cmd.upmove > 0) { + PM_TryAirKick(LS_KICK_B_AIR); + } else { // kick back + PM_SetSaberMove(LS_KICK_B); + } + pm->cmd.forwardmove = 0; + } else if (pm->gent && pm->gent->enemy && G_CanKickEntity(pm->gent, pm->gent->enemy)) { // auto-pick? + if ( /*(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD) + && (pm->cmd.buttons&BUTTON_ATTACK) + &&*/ + PM_PickAutoMultiKick(qfalse)) { // kicked! + if (pm->ps->saberMove == LS_KICK_RL) { // just pull back + if (d_slowmodeath->integer > 3) { + G_StartMatrixEffect(pm->gent, MEF_NO_SPIN, pm->ps->legsAnimTimer + 500); + } + } else { // normal spin + if (d_slowmodeath->integer > 3) { + G_StartMatrixEffect(pm->gent, 0, pm->ps->legsAnimTimer + 500); + } + } + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && + (pm->ps->saberMove == LS_KICK_S || pm->ps->saberMove == LS_KICK_BF || + pm->ps->saberMove == LS_KICK_RL)) { // in the air and doing a jump-kick, which is a ground anim, so.... + // cut z velocity...? pm->ps->velocity[2] = 0; } pm->cmd.upmove = 0; - } - else - { - saberMoveName_t kickMove = PM_PickAutoKick( pm->gent->enemy ); - if ( kickMove != LS_NONE ) - {//Matrix? - PM_SetSaberMove( kickMove ); + } else { + saberMoveName_t kickMove = PM_PickAutoKick(pm->gent->enemy); + if (kickMove != LS_NONE) { // Matrix? + PM_SetSaberMove(kickMove); int meFlags = 0; - switch ( kickMove ) - { - case LS_KICK_B://just pull back - case LS_KICK_B_AIR://just pull back + switch (kickMove) { + case LS_KICK_B: // just pull back + case LS_KICK_B_AIR: // just pull back meFlags = MEF_NO_SPIN; break; - case LS_KICK_L://spin to the left - case LS_KICK_L_AIR://spin to the left + case LS_KICK_L: // spin to the left + case LS_KICK_L_AIR: // spin to the left meFlags = MEF_REVERSE_SPIN; break; default: break; } - if ( d_slowmodeath->integer > 3 ) - { - G_StartMatrixEffect( pm->gent, meFlags, pm->ps->legsAnimTimer+500 ); + if (d_slowmodeath->integer > 3) { + G_StartMatrixEffect(pm->gent, meFlags, pm->ps->legsAnimTimer + 500); } } } - } - else - { - if ( PM_PickAutoMultiKick( qtrue ) ) - { + } else { + if (PM_PickAutoMultiKick(qtrue)) { int meFlags = 0; - switch ( pm->ps->saberMove ) - { - case LS_KICK_RL://just pull back - case LS_KICK_B://just pull back - case LS_KICK_B_AIR://just pull back + switch (pm->ps->saberMove) { + case LS_KICK_RL: // just pull back + case LS_KICK_B: // just pull back + case LS_KICK_B_AIR: // just pull back meFlags = MEF_NO_SPIN; break; - case LS_KICK_L://spin to the left - case LS_KICK_L_AIR://spin to the left + case LS_KICK_L: // spin to the left + case LS_KICK_L_AIR: // spin to the left meFlags = MEF_REVERSE_SPIN; break; default: break; } - if ( d_slowmodeath->integer > 3 ) - { - G_StartMatrixEffect( pm->gent, meFlags, pm->ps->legsAnimTimer+500 ); + if (d_slowmodeath->integer > 3) { + G_StartMatrixEffect(pm->gent, meFlags, pm->ps->legsAnimTimer + 500); } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - &&( pm->ps->saberMove == LS_KICK_S - ||pm->ps->saberMove == LS_KICK_BF - ||pm->ps->saberMove == LS_KICK_RL ) ) - {//in the air and doing a jump-kick, which is a ground anim, so.... - //cut z velocity...? + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && + (pm->ps->saberMove == LS_KICK_S || pm->ps->saberMove == LS_KICK_BF || + pm->ps->saberMove == LS_KICK_RL)) { // in the air and doing a jump-kick, which is a ground anim, so.... + // cut z velocity...? pm->ps->velocity[2] = 0; } pm->cmd.upmove = 0; @@ -11547,29 +9200,19 @@ void PM_CheckKick( void ) } } -void PM_CheckClearSaberBlock( void ) -{ - if ( pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer() ) - {//player - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ ) - {//blocking a projectile - if ( pm->ps->forcePowerDebounce[FP_SABER_DEFENSE] < level.time ) - {//block is done or breaking out of it with an attack +void PM_CheckClearSaberBlock(void) { + if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) { // player + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ) { // blocking a projectile + if (pm->ps->forcePowerDebounce[FP_SABER_DEFENSE] < level.time) { // block is done or breaking out of it with an attack pm->ps->weaponTime = 0; pm->ps->saberBlocked = BLOCKED_NONE; - } - else if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - {//block is done or breaking out of it with an attack + } else if ((pm->cmd.buttons & BUTTON_ATTACK)) { // block is done or breaking out of it with an attack pm->ps->weaponTime = 0; pm->ps->saberBlocked = BLOCKED_NONE; } - } - else if ( pm->ps->saberBlocked == BLOCKED_UPPER_LEFT - && pm->ps->powerups[PW_SHOCKED] > level.time ) - {//probably blocking lightning - if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - {//trying to attack - //allow the attack + } else if (pm->ps->saberBlocked == BLOCKED_UPPER_LEFT && pm->ps->powerups[PW_SHOCKED] > level.time) { // probably blocking lightning + if ((pm->cmd.buttons & BUTTON_ATTACK)) { // trying to attack + // allow the attack pm->ps->weaponTime = 0; pm->ps->saberBlocked = BLOCKED_NONE; } @@ -11577,32 +9220,23 @@ void PM_CheckClearSaberBlock( void ) } } -qboolean PM_SaberBlocking( void ) -{ +qboolean PM_SaberBlocking(void) { // Now we react to a block action by the player's lightsaber. - if ( pm->ps->saberBlocked ) - { - if ( pm->ps->saberMove > LS_PUTAWAY && pm->ps->saberMove <= LS_A_BL2TR && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && - (pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ || pm->ps->saberBlocked > BLOCKED_TOP_PROJ))//&& Q_irand( 0, 2 ) - {//we parried another lightsaber while attacking, so treat it as a bounce + if (pm->ps->saberBlocked) { + if (pm->ps->saberMove > LS_PUTAWAY && pm->ps->saberMove <= LS_A_BL2TR && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && + (pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ || pm->ps->saberBlocked > BLOCKED_TOP_PROJ)) //&& Q_irand( 0, 2 ) + { // we parried another lightsaber while attacking, so treat it as a bounce pm->ps->saberBlocked = BLOCKED_ATK_BOUNCE; - } - else if ( pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer() )//player + } else if (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // player { - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ - && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ ) - {//blocking a projectile - if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - {//trying to attack - if ( pm->ps->saberMove == LS_READY - || PM_SaberInReflect( pm->ps->saberMove ) ) - {//not already busy or already in projectile deflection - //trying to attack during projectile blocking, so do the attack instead + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ) { // blocking a projectile + if ((pm->cmd.buttons & BUTTON_ATTACK)) { // trying to attack + if (pm->ps->saberMove == LS_READY || PM_SaberInReflect(pm->ps->saberMove)) { // not already busy or already in projectile deflection + // trying to attack during projectile blocking, so do the attack instead pm->ps->saberBlocked = BLOCKED_NONE; pm->ps->saberBounceMove = LS_NONE; pm->ps->weaponstate = WEAPON_READY; - if ( PM_SaberInReflect( pm->ps->saberMove ) && pm->ps->weaponTime > 0 ) - {//interrupt the current deflection move + if (PM_SaberInReflect(pm->ps->saberMove) && pm->ps->weaponTime > 0) { // interrupt the current deflection move pm->ps->weaponTime = 0; } return qfalse; @@ -11624,257 +9258,199 @@ qboolean PM_SaberBlocking( void ) } */ - if ( pm->ps->saberBlocked != BLOCKED_ATK_BOUNCE ) - {//can't attack for twice whatever your skill level's parry debounce time is - if ( pm->ps->clientNum == 0 || PM_ControlledByPlayer() ) - {//player - if ( pm->ps->forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1 ) - { + if (pm->ps->saberBlocked != BLOCKED_ATK_BOUNCE) { // can't attack for twice whatever your skill level's parry debounce time is + if (pm->ps->clientNum == 0 || PM_ControlledByPlayer()) { // player + if (pm->ps->forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1) { pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]]; } - } - else - {//NPC - //pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; - if ( pm->gent ) - { - pm->ps->weaponTime = Jedi_ReCalcParryTime( pm->gent, EVASION_PARRY ); - } - else - {//WTF??? + } else { // NPC + // pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; + if (pm->gent) { + pm->ps->weaponTime = Jedi_ReCalcParryTime(pm->gent, EVASION_PARRY); + } else { // WTF??? pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; } } } - switch ( pm->ps->saberBlocked ) - { - case BLOCKED_PARRY_BROKEN: - //whatever parry we were is in now broken, play the appropriate knocked-away anim - { - saberMoveName_t nextMove; - if ( PM_SaberInBrokenParry( pm->ps->saberBounceMove ) ) - {//already have one...? - nextMove = (saberMoveName_t)pm->ps->saberBounceMove; - } - else - { - nextMove = PM_BrokenParryForParry( (saberMoveName_t)pm->ps->saberMove ); - } - if ( nextMove != LS_NONE ) - { - PM_SetSaberMove( nextMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - {//Maybe in a knockaway? - } - //pm->ps->saberBounceMove = LS_NONE; + switch (pm->ps->saberBlocked) { + case BLOCKED_PARRY_BROKEN: + // whatever parry we were is in now broken, play the appropriate knocked-away anim + { + saberMoveName_t nextMove; + if (PM_SaberInBrokenParry(pm->ps->saberBounceMove)) { // already have one...? + nextMove = (saberMoveName_t)pm->ps->saberBounceMove; + } else { + nextMove = PM_BrokenParryForParry((saberMoveName_t)pm->ps->saberMove); } - break; - case BLOCKED_ATK_BOUNCE: - // If there is absolutely no blocked move in the chart, don't even mess with the animation. - // OR if we are already in a block or parry. - if ( pm->ps->saberMove >= LS_T1_BR__R/*LS_BOUNCE_TOP*/ )//|| saberMoveData[pm->ps->saberMove].bounceMove == LS_NONE ) - {//an actual bounce? Other bounces before this are actually transitions? - pm->ps->saberBlocked = BLOCKED_NONE; + if (nextMove != LS_NONE) { + PM_SetSaberMove(nextMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { // Maybe in a knockaway? } - else if ( PM_SaberInBounce( pm->ps->saberMove ) || !PM_SaberInAttack( pm->ps->saberMove ) ) - {//already in the bounce, go into an attack or transition to ready.. should never get here since can't be blocked in a bounce! - int nextMove; - - if ( pm->cmd.buttons & BUTTON_ATTACK ) - {//transition to a new attack - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPC - nextMove = saberMoveData[pm->ps->saberMove].chain_attack; - } - else - {//player - int newQuad = PM_SaberMoveQuadrantForMovement( &pm->cmd ); - while ( newQuad == saberMoveData[pm->ps->saberMove].startQuad ) - {//player is still in same attack quad, don't repeat that attack because it looks bad, - //FIXME: try to pick one that might look cool? - newQuad = Q_irand( Q_BR, Q_BL ); - //FIXME: sanity check, just in case? - }//else player is switching up anyway, take the new attack dir - nextMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; - } - } - else - {//return to ready - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPC - nextMove = saberMoveData[pm->ps->saberMove].chain_idle; - } - else - {//player - if ( saberMoveData[pm->ps->saberMove].startQuad == Q_T ) - { - nextMove = LS_R_BL2TR; - } - else if ( saberMoveData[pm->ps->saberMove].startQuad < Q_T ) - { - nextMove = LS_R_TL2BR+(saberMoveName_t)(saberMoveData[pm->ps->saberMove].startQuad-Q_BR); - } - else// if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) - { - nextMove = LS_R_BR2TL+(saberMoveName_t)(saberMoveData[pm->ps->saberMove].startQuad-Q_TL); - } + // pm->ps->saberBounceMove = LS_NONE; + } + break; + case BLOCKED_ATK_BOUNCE: + // If there is absolutely no blocked move in the chart, don't even mess with the animation. + // OR if we are already in a block or parry. + if (pm->ps->saberMove >= LS_T1_BR__R /*LS_BOUNCE_TOP*/) //|| saberMoveData[pm->ps->saberMove].bounceMove == LS_NONE ) + { // an actual bounce? Other bounces before this are actually transitions? + pm->ps->saberBlocked = BLOCKED_NONE; + } else if (PM_SaberInBounce(pm->ps->saberMove) || + !PM_SaberInAttack(pm->ps->saberMove)) { // already in the bounce, go into an attack or transition to ready.. should never get here since + // can't be blocked in a bounce! + int nextMove; + + if (pm->cmd.buttons & BUTTON_ATTACK) { // transition to a new attack + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPC + nextMove = saberMoveData[pm->ps->saberMove].chain_attack; + } else { // player + int newQuad = PM_SaberMoveQuadrantForMovement(&pm->cmd); + while ( + newQuad == + saberMoveData[pm->ps->saberMove].startQuad) { // player is still in same attack quad, don't repeat that attack because it looks bad, + // FIXME: try to pick one that might look cool? + newQuad = Q_irand(Q_BR, Q_BL); + // FIXME: sanity check, just in case? + } // else player is switching up anyway, take the new attack dir + nextMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; + } + } else { // return to ready + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPC + nextMove = saberMoveData[pm->ps->saberMove].chain_idle; + } else { // player + if (saberMoveData[pm->ps->saberMove].startQuad == Q_T) { + nextMove = LS_R_BL2TR; + } else if (saberMoveData[pm->ps->saberMove].startQuad < Q_T) { + nextMove = LS_R_TL2BR + (saberMoveName_t)(saberMoveData[pm->ps->saberMove].startQuad - Q_BR); + } else // if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) + { + nextMove = LS_R_BR2TL + (saberMoveName_t)(saberMoveData[pm->ps->saberMove].startQuad - Q_TL); } } - PM_SetSaberMove( (saberMoveName_t)nextMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; } - else - {//start the bounce move - saberMoveName_t bounceMove; - if ( pm->ps->saberBounceMove != LS_NONE ) - { - bounceMove = (saberMoveName_t)pm->ps->saberBounceMove; - } - else - { - bounceMove = PM_SaberBounceForAttack( (saberMoveName_t)pm->ps->saberMove ); - } - PM_SetSaberMove( bounceMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; + PM_SetSaberMove((saberMoveName_t)nextMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { // start the bounce move + saberMoveName_t bounceMove; + if (pm->ps->saberBounceMove != LS_NONE) { + bounceMove = (saberMoveName_t)pm->ps->saberBounceMove; + } else { + bounceMove = PM_SaberBounceForAttack((saberMoveName_t)pm->ps->saberMove); } - //clear the saberBounceMove - //pm->ps->saberBounceMove = LS_NONE; + PM_SetSaberMove(bounceMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } + // clear the saberBounceMove + // pm->ps->saberBounceMove = LS_NONE; - if (cg_debugSaber.integer>=2) - { - Com_Printf("Saber Block: Bounce\n"); - } - break; - case BLOCKED_UPPER_RIGHT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UR ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Bounce\n"); + } + break; + case BLOCKED_UPPER_RIGHT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove((saberMoveName_t)pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UR); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf( "Saber Block: Parry UR\n" ); - } - break; - case BLOCKED_UPPER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_UR ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry UR\n"); + } + break; + case BLOCKED_UPPER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_UR); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect UR\n"); - } - break; - case BLOCKED_UPPER_LEFT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UL ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect UR\n"); + } + break; + case BLOCKED_UPPER_LEFT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove((saberMoveName_t)pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UL); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf( "Saber Block: Parry UL\n" ); - } - break; - case BLOCKED_UPPER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_UL ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry UL\n"); + } + break; + case BLOCKED_UPPER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_UL); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect UL\n"); - } - break; - case BLOCKED_LOWER_RIGHT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_LR ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect UL\n"); + } + break; + case BLOCKED_LOWER_RIGHT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove((saberMoveName_t)pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_LR); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry LR\n"); - } - break; - case BLOCKED_LOWER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_LR ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry LR\n"); + } + break; + case BLOCKED_LOWER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_LR); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect LR\n"); - } - break; - case BLOCKED_LOWER_LEFT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_LL ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect LR\n"); + } + break; + case BLOCKED_LOWER_LEFT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove((saberMoveName_t)pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_LL); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry LL\n"); - } - break; - case BLOCKED_LOWER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_LL); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry LL\n"); + } + break; + case BLOCKED_LOWER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_LL); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect LL\n"); - } - break; - case BLOCKED_TOP: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UP ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect LL\n"); + } + break; + case BLOCKED_TOP: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove((saberMoveName_t)pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UP); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry Top\n"); - } - break; - case BLOCKED_TOP_PROJ: - PM_SetSaberMove( LS_REFLECT_UP ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry Top\n"); + } + break; + case BLOCKED_TOP_PROJ: + PM_SetSaberMove(LS_REFLECT_UP); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect Top\n"); - } - break; - default: - pm->ps->saberBlocked = BLOCKED_NONE; - break; + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect Top\n"); + } + break; + default: + pm->ps->saberBlocked = BLOCKED_NONE; + break; } // Charging is like a lead-up before attacking again. This is an appropriate use, or we can create a new weaponstate for blocking @@ -11887,18 +9463,15 @@ qboolean PM_SaberBlocking( void ) return qfalse; } -qboolean PM_NPCCheckAttackRoll( void ) -{ - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()//NPC - && pm->gent - && pm->gent->NPC +qboolean PM_NPCCheckAttackRoll(void) { + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() // NPC + && pm->gent && + pm->gent->NPC //&& Q_irand(-3,pm->gent->NPC->rank)>RANK_CREWMAN) - && ( pm->gent->NPC->rank > RANK_CREWMAN && !Q_irand(0,3-g_spskill->integer) ) - && pm->gent->enemy - && fabs(pm->gent->enemy->currentOrigin[2]-pm->ps->origin[2])<32 - && DistanceHorizontalSquared(pm->gent->enemy->currentOrigin, pm->ps->origin ) < (128.0f*128.0f) - && InFOV( pm->gent->enemy->currentOrigin, pm->ps->origin, pm->ps->viewangles, 30, 90 ) ) - {//stab! + && (pm->gent->NPC->rank > RANK_CREWMAN && !Q_irand(0, 3 - g_spskill->integer)) && pm->gent->enemy && + fabs(pm->gent->enemy->currentOrigin[2] - pm->ps->origin[2]) < 32 && + DistanceHorizontalSquared(pm->gent->enemy->currentOrigin, pm->ps->origin) < (128.0f * 128.0f) && + InFOV(pm->gent->enemy->currentOrigin, pm->ps->origin, pm->ps->viewangles, 30, 90)) { // stab! return qtrue; } return qfalse; @@ -11913,72 +9486,53 @@ While this is a little different than the Quake 3 code, there is no clean way of */ // Ultimate goal is to set the sabermove to the proper next location // Note that if the resultant animation is NONE, then the animation is essentially "idle", and is set in WP_TorsoAnim -void PM_WeaponLightsaber(void) -{ - int addTime; - qboolean delayed_fire = qfalse, animLevelOverridden = qfalse; - int anim=-1; - int curmove, newmove=LS_NONE; - - if ( pm->gent - && pm->gent->client - && pm->gent->client->NPC_class == CLASS_SABER_DROID ) - {//Saber droid does it's own attack logic +void PM_WeaponLightsaber(void) { + int addTime; + qboolean delayed_fire = qfalse, animLevelOverridden = qfalse; + int anim = -1; + int curmove, newmove = LS_NONE; + + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_SABER_DROID) { // Saber droid does it's own attack logic PM_SaberDroidWeapon(); return; } // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) - { - if ( pm->gent ) - { + if (pm->ps->stats[STAT_HEALTH] <= 0) { + if (pm->gent) { pm->gent->s.loopSound = 0; } return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } - if ( pm->ps->stats[STAT_WEAPONS]&(1<ps->dualSabers - && pm->gent - && pm->gent->weaponModel[1] ) - {//holding scepter in left hand, use dual style + if (pm->ps->stats[STAT_WEAPONS] & (1 << WP_SCEPTER) && !pm->ps->dualSabers && pm->gent && + pm->gent->weaponModel[1]) { // holding scepter in left hand, use dual style pm->ps->saberAnimLevel = SS_DUAL; animLevelOverridden = qtrue; - } - else if ( pm->ps->saber[0].singleBladeStyle != SS_NONE//SaberStaff() - && !pm->ps->dualSabers - && pm->ps->saber[0].blade[0].active - && !pm->ps->saber[0].blade[1].active ) - {//using a staff, but only with first blade turned on, so use is as a normal saber...? - //override so that single-blade staff must be used with specified style - pm->ps->saberAnimLevel = pm->ps->saber[0].singleBladeStyle;//SS_STRONG; + } else if (pm->ps->saber[0].singleBladeStyle != SS_NONE // SaberStaff() + && !pm->ps->dualSabers && pm->ps->saber[0].blade[0].active && + !pm->ps->saber[0].blade[1].active) { // using a staff, but only with first blade turned on, so use is as a normal saber...? + // override so that single-blade staff must be used with specified style + pm->ps->saberAnimLevel = pm->ps->saber[0].singleBladeStyle; // SS_STRONG; animLevelOverridden = qtrue; - } - else if ( pm->gent - && cg.saberAnimLevelPending != pm->ps->saberAnimLevel - && WP_SaberStyleValidForSaber( pm->gent, cg.saberAnimLevelPending ) ) - {//go ahead and use the cg.saberAnimLevelPending below + } else if (pm->gent && cg.saberAnimLevelPending != pm->ps->saberAnimLevel && + WP_SaberStyleValidForSaber(pm->gent, cg.saberAnimLevelPending)) { // go ahead and use the cg.saberAnimLevelPending below animLevelOverridden = qfalse; - } - else if ( pm->gent - && ( WP_SaberStyleValidForSaber( pm->gent, pm->ps->saberAnimLevel ) - || WP_UseFirstValidSaberStyle( pm->gent, &pm->ps->saberAnimLevel ) ) ) - {//style we are using is not valid, switched us to a valid one + } else if (pm->gent && (WP_SaberStyleValidForSaber(pm->gent, pm->ps->saberAnimLevel) || + WP_UseFirstValidSaberStyle(pm->gent, &pm->ps->saberAnimLevel))) { // style we are using is not valid, switched us to a valid one animLevelOverridden = qtrue; } /* @@ -11998,8 +9552,7 @@ void PM_WeaponLightsaber(void) } } */ - else if ( pm->ps->dualSabers ) - { + else if (pm->ps->dualSabers) { /* if ( pm->ps->saber[1].Active() && pm->ps->saber[1].stylesAllowed ) @@ -12016,33 +9569,24 @@ void PM_WeaponLightsaber(void) } } } - else*/ if ( pm->ps->saber[1].Active() ) - {//if second saber is on, must use dual style + else*/ + if (pm->ps->saber[1].Active()) { // if second saber is on, must use dual style pm->ps->saberAnimLevel = SS_DUAL; animLevelOverridden = qtrue; - } - else if ( pm->ps->saber[0].Active() ) - {//with only one saber on, use fast style + } else if (pm->ps->saber[0].Active()) { // with only one saber on, use fast style pm->ps->saberAnimLevel = SS_FAST; animLevelOverridden = qtrue; } } - if ( !animLevelOverridden ) - { - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && cg.saberAnimLevelPending > SS_NONE - && cg.saberAnimLevelPending != pm->ps->saberAnimLevel ) - { - if ( !PM_SaberInStart( pm->ps->saberMove ) - && !PM_SaberInTransition( pm->ps->saberMove ) - && !PM_SaberInAttack( pm->ps->saberMove ) ) - {//don't allow changes when in the middle of an attack set...(or delay the change until it's done) + if (!animLevelOverridden) { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.saberAnimLevelPending > SS_NONE && + cg.saberAnimLevelPending != pm->ps->saberAnimLevel) { + if (!PM_SaberInStart(pm->ps->saberMove) && !PM_SaberInTransition(pm->ps->saberMove) && + !PM_SaberInAttack(pm->ps->saberMove)) { // don't allow changes when in the middle of an attack set...(or delay the change until it's done) pm->ps->saberAnimLevel = cg.saberAnimLevelPending; } } - } - else if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//if overrid the player's saberAnimLevel, let the cgame know + } else if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // if overrid the player's saberAnimLevel, let the cgame know cg.saberAnimLevelPending = pm->ps->saberAnimLevel; } /* @@ -12070,23 +9614,15 @@ void PM_WeaponLightsaber(void) } else */ - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown - if ( pm->ps->legsAnim == BOTH_ROLL_F - && pm->ps->legsAnimTimer <= 250 ) - { - if ( (pm->cmd.buttons&BUTTON_ATTACK) - || PM_NPCCheckAttackRoll() ) - { - if ( G_EnoughPowerForSpecialMove( pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB ) ) - { - if ( !(pm->ps->saber[0].saberFlags&SFL_NO_ROLL_STAB) - && (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags&SFL_NO_ROLL_STAB)) ) - {//okay to do roll-stab - PM_SetSaberMove( LS_ROLL_STAB ); - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER_FB ); + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown + if (pm->ps->legsAnim == BOTH_ROLL_F && pm->ps->legsAnimTimer <= 250) { + if ((pm->cmd.buttons & BUTTON_ATTACK) || PM_NPCCheckAttackRoll()) { + if (G_EnoughPowerForSpecialMove(pm->ps->forcePower, SABER_ALT_ATTACK_POWER_FB)) { + if (!(pm->ps->saber[0].saberFlags & SFL_NO_ROLL_STAB) && + (!pm->ps->dualSabers || !(pm->ps->saber[1].saberFlags & SFL_NO_ROLL_STAB))) { // okay to do roll-stab + PM_SetSaberMove(LS_ROLL_STAB); + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER_FB); } } } @@ -12095,83 +9631,66 @@ void PM_WeaponLightsaber(void) return; } - if ( PM_SaberLocked() ) - { + if (PM_SaberLocked()) { pm->ps->saberMove = LS_NONE; return; } - if ( pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND - || (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START && !(pm->cmd.buttons&BUTTON_ATTACK)) ) - {//if you're in the long-jump and you're not attacking (or are landing), you're not doing anything - if ( pm->ps->torsoAnimTimer ) - { + if (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND || + (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START && + !(pm->cmd.buttons & BUTTON_ATTACK))) { // if you're in the long-jump and you're not attacking (or are landing), you're not doing anything + if (pm->ps->torsoAnimTimer) { return; } } - if ( pm->ps->legsAnim == BOTH_FLIP_HOLD7 - && !(pm->cmd.buttons&BUTTON_ATTACK) ) - {//if you're in the upside-down attack hold, don't do anything unless you're attacking + if (pm->ps->legsAnim == BOTH_FLIP_HOLD7 && + !(pm->cmd.buttons & BUTTON_ATTACK)) { // if you're in the upside-down attack hold, don't do anything unless you're attacking return; } - if ( PM_KickingAnim( pm->ps->legsAnim ) ) - { - if ( pm->ps->legsAnimTimer ) - {//you're kicking, no interruptions + if (PM_KickingAnim(pm->ps->legsAnim)) { + if (pm->ps->legsAnimTimer) { // you're kicking, no interruptions return; } - //done? be immeditately ready to do an attack + // done? be immeditately ready to do an attack pm->ps->saberMove = LS_READY; pm->ps->weaponTime = 0; } - if ( pm->ps->saberMoveNext != LS_NONE - && (pm->ps->saberMove == LS_READY||pm->ps->saberMove == LS_NONE))//ready for another one - {//something is forcing us to set a specific next saberMove - //FIXME: if this is a NPC kick, re-verify it before executing it! - PM_SetSaberMove( (saberMoveName_t)pm->ps->saberMoveNext ); - pm->ps->saberMoveNext = LS_NONE;//clear it now that we played it + if (pm->ps->saberMoveNext != LS_NONE && (pm->ps->saberMove == LS_READY || pm->ps->saberMove == LS_NONE)) // ready for another one + { // something is forcing us to set a specific next saberMove + // FIXME: if this is a NPC kick, re-verify it before executing it! + PM_SetSaberMove((saberMoveName_t)pm->ps->saberMoveNext); + pm->ps->saberMoveNext = LS_NONE; // clear it now that we played it return; } - if ( pm->ps->saberEventFlags&SEF_INWATER )//saber in water + if (pm->ps->saberEventFlags & SEF_INWATER) // saber in water { - pm->cmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS); + pm->cmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS); } qboolean saberInAir = qtrue; - if ( !PM_SaberInBrokenParry( pm->ps->saberMove ) && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && !PM_DodgeAnim( pm->ps->torsoAnim ) && - pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_CHARGING) - {//we're not stuck in a broken parry - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (!PM_SaberInBrokenParry(pm->ps->saberMove) && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && !PM_DodgeAnim(pm->ps->torsoAnim) && + pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_CHARGING) { // we're not stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } - if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) - { - if ( pm->ps->weapon != pm->cmd.weapon ) - { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } - } - else if ( pm->ps->weapon == WP_SABER - && (!pm->ps->dualSabers || !pm->ps->saber[1].Active()) ) - {//guiding saber - if ( saberInAir ) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - if ( pm->ps->torsoAnim != BOTH_LOSE_SABER - || !pm->ps->torsoAnimTimer ) - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (pm->ps->weapon == WP_SABER && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { // guiding saber + if (saberInAir) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + if (pm->ps->torsoAnim != BOTH_LOSE_SABER || !pm->ps->torsoAnimTimer) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } @@ -12180,11 +9699,9 @@ void PM_WeaponLightsaber(void) } } - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually pm->gent->client->fireDelay -= pml.msec; - if ( pm->gent->client->fireDelay <= 0 ) - {//just finished delay timer + if (pm->gent->client->fireDelay <= 0) { // just finished delay timer pm->gent->client->fireDelay = 0; delayed_fire = qtrue; } @@ -12192,62 +9709,50 @@ void PM_WeaponLightsaber(void) PM_CheckClearSaberBlock(); - if ( PM_LockedAnim( pm->ps->torsoAnim ) - && pm->ps->torsoAnimTimer ) - {//can't interrupt these anims ever + if (PM_LockedAnim(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer) { // can't interrupt these anims ever return; } - if ( PM_SuperBreakLoseAnim( pm->ps->torsoAnim ) - && pm->ps->torsoAnimTimer ) - {//don't interrupt these anims + if (PM_SuperBreakLoseAnim(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer) { // don't interrupt these anims return; } - if ( PM_SuperBreakWinAnim( pm->ps->torsoAnim ) - && pm->ps->torsoAnimTimer ) - {//don't interrupt these anims + if (PM_SuperBreakWinAnim(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer) { // don't interrupt these anims return; } - if ( PM_SaberBlocking() ) - {//busy blocking, don't do attacks + if (PM_SaberBlocking()) { // busy blocking, don't do attacks return; } // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - if ( (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_CHARGING) { - if ( pm->ps->weapon != pm->cmd.weapon ) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if ((pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && + pm->ps->weaponstate != WEAPON_CHARGING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) - { - //FIXME: allow some window of opportunity to change your attack + if (pm->ps->weaponTime > 0) { + // FIXME: allow some window of opportunity to change your attack // if it just started and your directional input is different // than it was before... but only 100 milliseconds at most? - //OR: Make it so that attacks don't start until 100ms after you + // OR: Make it so that attacks don't start until 100ms after you // press the attack button...??? - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) //player - && PM_SaberInReturn( pm->ps->saberMove )//in a saber return move - FIXME: what about transitions? + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // player + && PM_SaberInReturn(pm->ps->saberMove) // in a saber return move - FIXME: what about transitions? //&& pm->ps->torsoAnimTimer<=250//towards the end of a saber return anim - && pm->ps->saberBlocked == BLOCKED_NONE//not interacting with any other saber - && !(pm->cmd.buttons&BUTTON_ATTACK)//not trying to swing the saber - && (pm->cmd.forwardmove||pm->cmd.rightmove) )//trying to kick in a specific direction + && pm->ps->saberBlocked == BLOCKED_NONE // not interacting with any other saber + && !(pm->cmd.buttons & BUTTON_ATTACK) // not trying to swing the saber + && (pm->cmd.forwardmove || pm->cmd.rightmove)) // trying to kick in a specific direction { - if ( PM_CheckAltKickAttack() )//trying to do a kick - {//allow them to do the kick now! + if (PM_CheckAltKickAttack()) // trying to do a kick + { // allow them to do the kick now! pm->ps->weaponTime = 0; PM_CheckKick(); return; } - } - else - { - if ( !pm->cmd.rightmove - &&!pm->cmd.forwardmove - &&(pm->cmd.buttons&BUTTON_ATTACK) ) - { + } else { + if (!pm->cmd.rightmove && !pm->cmd.forwardmove && (pm->cmd.buttons & BUTTON_ATTACK)) { /* if ( PM_CheckDualSpinProtect() ) {//check to see if we're going to do the special dual push protect move @@ -12257,19 +9762,15 @@ void PM_WeaponLightsaber(void) } else */ - if ( !g_saberNewControlScheme->integer ) - { + if (!g_saberNewControlScheme->integer) { saberMoveName_t pullAtk = PM_CheckPullAttack(); - if ( pullAtk != LS_NONE ) - { - PM_SetSaberMove( pullAtk ); + if (pullAtk != LS_NONE) { + PM_SetSaberMove(pullAtk); pm->ps->weaponstate = WEAPON_FIRING; return; } } - } - else - { + } else { return; } } @@ -12280,7 +9781,7 @@ void PM_WeaponLightsaber(void) // ********************************************************* // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } @@ -12289,13 +9790,10 @@ void PM_WeaponLightsaber(void) // WEAPON_RAISING // ********************************************************* - if ( pm->ps->weaponstate == WEAPON_RAISING ) - {//Just selected the weapon + if (pm->ps->weaponstate == WEAPON_RAISING) { // Just selected the weapon pm->ps->weaponstate = WEAPON_IDLE; - if(pm->gent && (pm->gent->s.numbergent))) - { - switch ( pm->ps->legsAnim ) - { + if (pm->gent && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent))) { + switch (pm->ps->legsAnim) { case BOTH_WALK1: case BOTH_WALK2: case BOTH_WALK_STAFF: @@ -12311,50 +9809,37 @@ void PM_WeaponLightsaber(void) case BOTH_RUNBACK1: case BOTH_RUNBACK2: case BOTH_RUNBACK_STAFF: - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); break; default: int anim = PM_ReadyPoseForSaberAnimLevel(); - if (anim!=-1) - { - PM_SetAnim(pm,SETANIM_TORSO,anim,SETANIM_FLAG_NORMAL); + if (anim != -1) { + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_NORMAL); } break; } - } - else - { + } else { qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->weapon == WP_SABER - && pm->ps->saberInFlight - && saberInAir - && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) - {//guiding saber - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - if ( pm->ps->torsoAnim != BOTH_LOSE_SABER - || !pm->ps->torsoAnimTimer ) - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { // guiding saber + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + if (pm->ps->torsoAnim != BOTH_LOSE_SABER || !pm->ps->torsoAnimTimer) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else - { + } else { // PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_NORMAL); // Select the proper idle Lightsaber attack move from the chart. PM_SetSaberMove(LS_READY); @@ -12367,183 +9852,134 @@ void PM_WeaponLightsaber(void) // Check for WEAPON ATTACK // ********************************************************* - if ( PM_CanDoKata() ) - { + if (PM_CanDoKata()) { saberMoveName_t overrideMove = LS_INVALID; - //see if we have an overridden (or cancelled) kata move - if ( pm->ps->saber[0].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[0].kataMove != LS_NONE ) - { + // see if we have an overridden (or cancelled) kata move + if (pm->ps->saber[0].kataMove != LS_INVALID) { + if (pm->ps->saber[0].kataMove != LS_NONE) { overrideMove = (saberMoveName_t)pm->ps->saber[0].kataMove; } } - if ( overrideMove == LS_INVALID ) - {//not overridden by first saber, check second - if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove != LS_INVALID ) - { - if ( pm->ps->saber[1].kataMove != LS_NONE ) - { + if (overrideMove == LS_INVALID) { // not overridden by first saber, check second + if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove != LS_INVALID) { + if (pm->ps->saber[1].kataMove != LS_NONE) { overrideMove = (saberMoveName_t)pm->ps->saber[1].kataMove; } } } } - //no overrides, cancelled? - if ( overrideMove == LS_INVALID ) - { - if ( pm->ps->saber[0].kataMove == LS_NONE ) - { + // no overrides, cancelled? + if (overrideMove == LS_INVALID) { + if (pm->ps->saber[0].kataMove == LS_NONE) { overrideMove = LS_NONE; - } - else if ( pm->ps->dualSabers ) - { - if ( pm->ps->saber[1].kataMove == LS_NONE ) - { + } else if (pm->ps->dualSabers) { + if (pm->ps->saber[1].kataMove == LS_NONE) { overrideMove = LS_NONE; } } } - if ( overrideMove == LS_INVALID ) - {//not overridden - //FIXME: make sure to turn on saber(s)! - switch ( pm->ps->saberAnimLevel ) - { + if (overrideMove == LS_INVALID) { // not overridden + // FIXME: make sure to turn on saber(s)! + switch (pm->ps->saberAnimLevel) { case SS_FAST: case SS_TAVION: - PM_SetSaberMove( LS_A1_SPECIAL ); + PM_SetSaberMove(LS_A1_SPECIAL); break; case SS_MEDIUM: - PM_SetSaberMove( LS_A2_SPECIAL ); + PM_SetSaberMove(LS_A2_SPECIAL); break; case SS_STRONG: case SS_DESANN: - PM_SetSaberMove( LS_A3_SPECIAL ); + PM_SetSaberMove(LS_A3_SPECIAL); break; case SS_DUAL: - PM_SetSaberMove( LS_DUAL_SPIN_PROTECT );//PM_CheckDualSpinProtect(); + PM_SetSaberMove(LS_DUAL_SPIN_PROTECT); // PM_CheckDualSpinProtect(); break; case SS_STAFF: - PM_SetSaberMove( LS_STAFF_SOULCAL ); + PM_SetSaberMove(LS_STAFF_SOULCAL); break; } pm->ps->weaponstate = WEAPON_FIRING; - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER, qtrue );//FP_SPEED, SINGLE_SPECIAL_POWER ); - //G_StartMatrixEffect( pm->gent, MEF_REVERSE_SPIN, pm->ps->torsoAnimTimer ); + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER, qtrue); // FP_SPEED, SINGLE_SPECIAL_POWER ); + // G_StartMatrixEffect( pm->gent, MEF_REVERSE_SPIN, pm->ps->torsoAnimTimer ); } - } - else if ( overrideMove != LS_NONE ) - { - PM_SetSaberMove( overrideMove ); + } else if (overrideMove != LS_NONE) { + PM_SetSaberMove(overrideMove); pm->ps->weaponstate = WEAPON_FIRING; - if ( pm->gent ) - { - G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER, qtrue );//FP_SPEED, SINGLE_SPECIAL_POWER ); - //G_StartMatrixEffect( pm->gent, MEF_REVERSE_SPIN, pm->ps->torsoAnimTimer ); + if (pm->gent) { + G_DrainPowerForSpecialMove(pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER, qtrue); // FP_SPEED, SINGLE_SPECIAL_POWER ); + // G_StartMatrixEffect( pm->gent, MEF_REVERSE_SPIN, pm->ps->torsoAnimTimer ); } } - if ( overrideMove != LS_NONE ) - {//not cancelled + if (overrideMove != LS_NONE) { // not cancelled return; } } - if ( PM_CheckAltKickAttack() ) - {//trying to do a kick - //FIXME: in-air kicks? - if ( pm->ps->saberAnimLevel == SS_STAFF - && (pm->ps->clientNum >= MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//NPCs spin the staff - //NOTE: only NPCs can do it the easy way... they kick directly, not through ucmds... - PM_SetSaberMove( LS_SPINATTACK ); + if (PM_CheckAltKickAttack()) { // trying to do a kick + // FIXME: in-air kicks? + if (pm->ps->saberAnimLevel == SS_STAFF && (pm->ps->clientNum >= MAX_CLIENTS || PM_ControlledByPlayer())) { // NPCs spin the staff + // NOTE: only NPCs can do it the easy way... they kick directly, not through ucmds... + PM_SetSaberMove(LS_SPINATTACK); return; - } - else - { + } else { PM_CheckKick(); } return; } - //this is never a valid regular saber attack button - //pm->cmd.buttons &= ~BUTTON_FORCE_FOCUS; + // this is never a valid regular saber attack button + // pm->cmd.buttons &= ~BUTTON_FORCE_FOCUS; - if ( PM_CheckUpsideDownAttack() ) - { + if (PM_CheckUpsideDownAttack()) { return; } - if(!delayed_fire) - { + if (!delayed_fire) { // Start with the current move, and cross index it with the current control states. - if ( pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX ) - { + if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) { curmove = (saberMoveName_t)pm->ps->saberMove; - } - else - { + } else { curmove = LS_READY; } - if ( curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_ ) - {//must transition back to ready from this anim + if (curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_) { // must transition back to ready from this anim newmove = LS_R_T2B; } // check for fire - else if ( !(pm->cmd.buttons & BUTTON_ATTACK) )//(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS)) ) - {//not attacking + else if (!(pm->cmd.buttons & BUTTON_ATTACK)) //(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS)) ) + { // not attacking pm->ps->weaponTime = 0; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//Still firing - pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // Still firing + pm->ps->weaponstate = WEAPON_FIRING; + } else if (pm->ps->weaponstate != WEAPON_READY) { pm->ps->weaponstate = WEAPON_IDLE; } - //Check for finishing an anim if necc. - if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( curmove >= LS_A_TL2BR && curmove <= LS_A_T2B ) - {//finished an attack, must continue from here - newmove = LS_R_TL2BR + (curmove-LS_A_TL2BR); - } - else if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // Check for finishing an anim if necc. + if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (curmove >= LS_A_TL2BR && curmove <= LS_A_T2B) { // finished an attack, must continue from here + newmove = LS_R_TL2BR + (curmove - LS_A_TL2BR); + } else if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( PM_SaberInBounce( curmove ) ) - {//in a bounce - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPCs must play sequential attack - //going into another attack... - //allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 - if ( PM_SaberKataDone( LS_NONE, LS_NONE ) ) - {//done with this kata, must return to ready before attack again + } else if (PM_SaberInBounce(curmove)) { // in a bounce + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPCs must play sequential attack + // going into another attack... + // allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 + if (PM_SaberKataDone(LS_NONE, LS_NONE)) { // done with this kata, must return to ready before attack again newmove = saberMoveData[curmove].chain_idle; - } - else - {//okay to chain to another attack - newmove = saberMoveData[curmove].chain_attack;//we assume they're attacking, even if they're not + } else { // okay to chain to another attack + newmove = saberMoveData[curmove].chain_attack; // we assume they're attacking, even if they're not pm->ps->saberAttackChainCount++; } + } else { // player gets his by directional control + newmove = saberMoveData[curmove].chain_idle; // oops, not attacking, so don't chain } - else - {//player gets his by directional control - newmove = saberMoveData[curmove].chain_idle;//oops, not attacking, so don't chain - } - } - else - {//FIXME: what about returning from a parry? - //PM_SetSaberMove( LS_READY ); - if ( pm->ps->saberBlockingTime > cg.time ) - { - PM_SetSaberMove( LS_READY ); + } else { // FIXME: what about returning from a parry? + // PM_SetSaberMove( LS_READY ); + if (pm->ps->saberBlockingTime > cg.time) { + PM_SetSaberMove(LS_READY); } return; } @@ -12552,119 +9988,88 @@ void PM_WeaponLightsaber(void) // *************************************************** // Pressing attack, so we must look up the proper attack move. qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->weapon == WP_SABER - && pm->ps->saberInFlight - && saberInAir - && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) - {//guiding saber - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - if ( pm->ps->torsoAnim != BOTH_LOSE_SABER - || !pm->ps->torsoAnimTimer ) - { - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir && (!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { // guiding saber + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + if (pm->ps->torsoAnim != BOTH_LOSE_SABER || !pm->ps->torsoAnimTimer) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else if ( pm->ps->weaponTime > 0 ) - { // Last attack is not yet complete. + } else if (pm->ps->weaponTime > 0) { // Last attack is not yet complete. pm->ps->weaponstate = WEAPON_FIRING; return; - } - else - { - int both = qfalse; - if ( pm->ps->torsoAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND ) - {//can't attack in these anims + } else { + int both = qfalse; + if (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_ATTACK || pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND) { // can't attack in these anims return; - } - else if ( pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START ) - {//only 1 attack you can do from this anim - if ( pm->ps->torsoAnimTimer >= 200 ) - {//hit it early enough to do the attack - PM_SetSaberMove( LS_LEAP_ATTACK ); + } else if (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START) { // only 1 attack you can do from this anim + if (pm->ps->torsoAnimTimer >= 200) { // hit it early enough to do the attack + PM_SetSaberMove(LS_LEAP_ATTACK); } return; } - if ( curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL ) - {//from a parry or reflection, can go directly into an attack - if ( pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() ) - {//NPCs - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - { - newmove = PM_SaberAttackForMovement( pm->cmd.forwardmove, pm->cmd.rightmove, curmove ); + if (curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL) { // from a parry or reflection, can go directly into an attack + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // NPCs + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { + newmove = PM_SaberAttackForMovement(pm->cmd.forwardmove, pm->cmd.rightmove, curmove); } } - if ( newmove != LS_NONE ) - {//have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim - if (PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse)) - { + if (newmove != LS_NONE) { // have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { anim = saberMoveData[newmove].animToUse; } } - //FIXME: diagonal dirs use the figure-eight attacks from ready pose? - if ( anim == -1 ) - { - //FIXME: take FP_SABER_OFFENSE into account here somehow? - if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // FIXME: diagonal dirs use the figure-eight attacks from ready pose? + if (anim == -1) { + // FIXME: take FP_SABER_OFFENSE into account here somehow? + if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( PM_SaberInBrokenParry( curmove ) ) - {//broken parries must always return to ready + } else if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (PM_SaberInBrokenParry(curmove)) { // broken parries must always return to ready newmove = LS_READY; - } - else//if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? - {//get attack move from movement command + } else // if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? + { // get attack move from movement command /* if ( PM_SaberKataDone() ) {//we came from a bounce and cannot chain to another attack because our kata is done newmove = saberMoveData[curmove].chain_idle; } else */ - if ( pm->ps->clientNum >= MAX_CLIENTS - && !PM_ControlledByPlayer() - && (Q_irand( 0, pm->ps->forcePowerLevel[FP_SABER_OFFENSE]-1 ) - || (pm->gent&&pm->gent->enemy&&pm->gent->enemy->client&&PM_InKnockDownOnGround(&pm->gent->enemy->client->ps))//enemy knocked down, use some logic - || ( pm->ps->saberAnimLevel == SS_FAST && pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, 1 ) ) ) )//minor change to make fast-attack users use the special attacks more - {//NPCs use more randomized attacks the more skilled they are - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - { - newmove = PM_SaberAttackForMovement( pm->cmd.forwardmove, pm->cmd.rightmove, curmove ); - if ( (PM_SaberInBounce( curmove )||PM_SaberInBrokenParry( curmove )) - && saberMoveData[newmove].startQuad == saberMoveData[curmove].endQuad ) - {//this attack would be a repeat of the last (which was blocked), so don't actually use it, use the default chain attack for this bounce + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer() && + (Q_irand(0, pm->ps->forcePowerLevel[FP_SABER_OFFENSE] - 1) || + (pm->gent && pm->gent->enemy && pm->gent->enemy->client && + PM_InKnockDownOnGround(&pm->gent->enemy->client->ps)) // enemy knocked down, use some logic + || (pm->ps->saberAnimLevel == SS_FAST && pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, 1)))) // minor change to make fast-attack users use the special attacks more + { // NPCs use more randomized attacks the more skilled they are + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { + newmove = PM_SaberAttackForMovement(pm->cmd.forwardmove, pm->cmd.rightmove, curmove); + if ((PM_SaberInBounce(curmove) || PM_SaberInBrokenParry(curmove)) && + saberMoveData[newmove].startQuad == + saberMoveData[curmove].endQuad) { // this attack would be a repeat of the last (which was blocked), so don't actually use it, + // use the default chain attack for this bounce newmove = saberMoveData[curmove].chain_attack; } } - if ( PM_SaberKataDone( curmove, newmove ) ) - {//cannot chain this time + if (PM_SaberKataDone(curmove, newmove)) { // cannot chain this time newmove = saberMoveData[curmove].chain_idle; } } @@ -12675,75 +10080,58 @@ void PM_WeaponLightsaber(void) newmove = PM_AttackMoveForQuad( saberMoveData[curmove].endQuad ); } */ - if ( newmove != LS_NONE ) - { - if ( !PM_InCartwheel( pm->ps->legsAnim ) ) - {//don't do transitions when cartwheeling - could make you spin! - //Now get the proper transition move - newmove = PM_SaberAnimTransitionMove( (saberMoveName_t)curmove, (saberMoveName_t)newmove ); - if ( PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse ) ) - { + if (newmove != LS_NONE) { + if (!PM_InCartwheel(pm->ps->legsAnim)) { // don't do transitions when cartwheeling - could make you spin! + // Now get the proper transition move + newmove = PM_SaberAnimTransitionMove((saberMoveName_t)curmove, (saberMoveName_t)newmove); + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { anim = saberMoveData[newmove].animToUse; } } } } - if (anim == -1) - {//not side-stepping, pick neutral anim - if ( !G_TryingSpecial(pm->gent,&pm->cmd)/*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/ ) - {//but only if not trying one of the special attacks! - if ( PM_InCartwheel( pm->ps->legsAnim ) - && pm->ps->legsAnimTimer > 100 ) - {//if in the middle of a cartwheel, the chain attack is just a normal attack - //NOTE: this should match the switch in PM_InCartwheel! - switch( pm->ps->legsAnim ) - { - case BOTH_ARIAL_LEFT://swing from l to r + if (anim == -1) { // not side-stepping, pick neutral anim + if (!G_TryingSpecial(pm->gent, &pm->cmd) /*(pm->cmd.buttons&BUTTON_FORCE_FOCUS)*/) { // but only if not trying one of the special attacks! + if (PM_InCartwheel(pm->ps->legsAnim) && + pm->ps->legsAnimTimer > 100) { // if in the middle of a cartwheel, the chain attack is just a normal attack + // NOTE: this should match the switch in PM_InCartwheel! + switch (pm->ps->legsAnim) { + case BOTH_ARIAL_LEFT: // swing from l to r case BOTH_CARTWHEEL_LEFT: newmove = LS_A_L2R; break; - case BOTH_ARIAL_RIGHT://swing from r to l + case BOTH_ARIAL_RIGHT: // swing from r to l case BOTH_CARTWHEEL_RIGHT: newmove = LS_A_R2L; break; - case BOTH_ARIAL_F1://random l/r attack - if ( Q_irand( 0, 1 ) ) - { + case BOTH_ARIAL_F1: // random l/r attack + if (Q_irand(0, 1)) { newmove = LS_A_L2R; - } - else - { + } else { newmove = LS_A_R2L; } break; } - } - else - { + } else { // Add randomness for prototype? newmove = saberMoveData[curmove].chain_attack; } - if ( newmove != LS_NONE ) - { - if (PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse)) - { - anim= saberMoveData[newmove].animToUse; + if (newmove != LS_NONE) { + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { + anim = saberMoveData[newmove].animToUse; } } } - if ( !pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//not moving at all, so set the anim on entire body + if (!pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && + pm->ps->groundEntityNum != ENTITYNUM_NONE) { // not moving at all, so set the anim on entire body both = qtrue; } - } - if ( anim == -1) - { - switch ( pm->ps->legsAnim ) - { + if (anim == -1) { + switch (pm->ps->legsAnim) { case BOTH_WALK1: case BOTH_WALK2: case BOTH_WALK_STAFF: @@ -12768,25 +10156,22 @@ void PM_WeaponLightsaber(void) newmove = LS_READY; } - if ( !pm->ps->SaberActive() ) - {//turn on the saber if it's not on + if (!pm->ps->SaberActive()) { // turn on the saber if it's not on pm->ps->SaberActivate(); } - PM_SetSaberMove( (saberMoveName_t)newmove ); + PM_SetSaberMove((saberMoveName_t)newmove); - if ( both && pm->ps->legsAnim != pm->ps->torsoAnim ) - { - PM_SetAnim( pm,SETANIM_LEGS,pm->ps->torsoAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (both && pm->ps->legsAnim != pm->ps->torsoAnim) { + PM_SetAnim(pm, SETANIM_LEGS, pm->ps->torsoAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( pm->gent && pm->gent->client ) - { -// pm->gent->client->saberTrail.inAction = qtrue; -// pm->gent->client->saberTrail.duration = 75; // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter + if (pm->gent && pm->gent->client) { + // pm->gent->client->saberTrail.inAction = qtrue; + // pm->gent->client->saberTrail.duration = 75; // saber trail lasts for 75ms...feel free to change this if you want it longer or + //shorter } - if ( !PM_InCartwheel( pm->ps->torsoAnim ) ) - {//can still attack during a cartwheel/arial - //don't fire again until anim is done + if (!PM_InCartwheel(pm->ps->torsoAnim)) { // can still attack during a cartwheel/arial + // don't fire again until anim is done pm->ps->weaponTime = pm->ps->torsoAnimTimer; } /* @@ -12805,8 +10190,7 @@ void PM_WeaponLightsaber(void) pm->ps->weaponstate = WEAPON_FIRING; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually // Clear these out since we're not actually firing yet pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; @@ -12838,24 +10222,20 @@ void PM_WeaponLightsaber(void) } } } - else */{ - PM_AddEvent( EV_FIRE_WEAPON ); - if ( !addTime ) - { + else */ + { + PM_AddEvent(EV_FIRE_WEAPON); + if (!addTime) { addTime = weaponData[pm->ps->weapon].fireTime; - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || + pm->ps->forcePowersActive & (1 << FP_RAGE))) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client - && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<ps->clientNum].client && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { addTime *= g_timescale->value; } } @@ -12864,49 +10244,40 @@ void PM_WeaponLightsaber(void) } } - if (pm->ps->forcePowersActive & (1 << FP_RAGE)) - { + if (pm->ps->forcePowersActive & (1 << FP_RAGE)) { addTime *= 0.75; - } - else if (pm->ps->forceRageRecoveryTime > pm->cmd.serverTime) - { + } else if (pm->ps->forceRageRecoveryTime > pm->cmd.serverTime) { addTime *= 1.5; } - //If the phaser has been fired, delay the next recharge time - if ( !PM_ControlledByPlayer() ) - { - if( pm->gent && pm->gent->NPC != NULL ) - {//NPCs have their own refire logic - //FIXME: this really should be universal... + // If the phaser has been fired, delay the next recharge time + if (!PM_ControlledByPlayer()) { + if (pm->gent && pm->gent->NPC != NULL) { // NPCs have their own refire logic + // FIXME: this really should be universal... return; } } - if ( !PM_InCartwheel( pm->ps->torsoAnim ) ) - {//can still attack during a cartwheel/arial + if (!PM_InCartwheel(pm->ps->torsoAnim)) { // can still attack during a cartwheel/arial pm->ps->weaponTime = addTime; } } //--------------------------------------- -static bool PM_DoChargedWeapons( void ) +static bool PM_DoChargedWeapons(void) //--------------------------------------- { - qboolean charging = qfalse, - altFire = qfalse; + qboolean charging = qfalse, altFire = qfalse; - //FIXME: make jedi aware they're being aimed at with a charged-up weapon (strafe and be evasive?) - // If you want your weapon to be a charging weapon, just set this bit up - switch( pm->ps->weapon ) - { + // FIXME: make jedi aware they're being aimed at with a charged-up weapon (strafe and be evasive?) + // If you want your weapon to be a charging weapon, just set this bit up + switch (pm->ps->weapon) { //------------------ case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: // alt-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -12917,23 +10288,16 @@ static bool PM_DoChargedWeapons( void ) // alt-fire charges the weapon...but due to zooming being controlled by the alt-button, the main button actually charges...but only when zoomed. // lovely, eh? - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - { - if ( cg.zoomMode == 2 ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { + if (cg.zoomMode == 2) { + if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; altFire = qtrue; // believe it or not, it really is an alt-fire in this case! } } - } - else if ( pm->gent && pm->gent->NPC ) - { - if ( (pm->gent->NPC->scriptFlags&SCF_ALT_FIRE) ) - { - if ( pm->gent->fly_sound_debounce_time > level.time ) - { + } else if (pm->gent && pm->gent->NPC) { + if ((pm->gent->NPC->scriptFlags & SCF_ALT_FIRE)) { + if (pm->gent->fly_sound_debounce_time > level.time) { charging = qtrue; altFire = qtrue; } @@ -12945,8 +10309,7 @@ static bool PM_DoChargedWeapons( void ) case WP_BOWCASTER: // main-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; @@ -12955,8 +10318,7 @@ static bool PM_DoChargedWeapons( void ) case WP_DEMP2: // alt-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -12967,8 +10329,7 @@ static bool PM_DoChargedWeapons( void ) // Not really a charge weapon, but we still want to delay fire until the button comes up so that we can // implement our alt-fire locking stuff - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -12979,13 +10340,10 @@ static bool PM_DoChargedWeapons( void ) // FIXME: Really should have a wind-up anim for player // as he holds down the fire button to throw, then play // the actual throw when he lets go... - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; // override default of not being an alt-fire charging = qtrue; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; @@ -12994,17 +10352,12 @@ static bool PM_DoChargedWeapons( void ) // set up the appropriate weapon state based on the button that's down. // Note that we ALWAYS return if charging is set ( meaning the buttons are still down ) - if ( charging ) - { + if (charging) { - - if ( altFire ) - { - if ( pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_DROPPING ) - { - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) - { - PM_AddEvent( EV_NOAMMO ); + if (altFire) { + if (pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_DROPPING) { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; return true; } @@ -13013,20 +10366,15 @@ static bool PM_DoChargedWeapons( void ) pm->ps->weaponstate = WEAPON_CHARGING_ALT; pm->ps->weaponChargeTime = level.time; - if ( cg_weapons[pm->ps->weapon].altChargeSound ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].altChargeSnd ); + if (cg_weapons[pm->ps->weapon].altChargeSound) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].altChargeSnd); } } - } - else - { + } else { - if ( pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_DROPPING ) - { - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) - { - PM_AddEvent( EV_NOAMMO ); + if (pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_DROPPING) { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; return true; } @@ -13035,9 +10383,9 @@ static bool PM_DoChargedWeapons( void ) pm->ps->weaponstate = WEAPON_CHARGING; pm->ps->weaponChargeTime = level.time; - if ( cg_weapons[pm->ps->weapon].chargeSound && pm->gent && !pm->gent->NPC ) // HACK: !NPC mostly for bowcaster and weequay + if (cg_weapons[pm->ps->weapon].chargeSound && pm->gent && !pm->gent->NPC) // HACK: !NPC mostly for bowcaster and weequay { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].chargeSnd ); + G_SoundOnEnt(pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].chargeSnd); } } } @@ -13047,153 +10395,125 @@ static bool PM_DoChargedWeapons( void ) // Only charging weapons should be able to set these states...so.... // let's see which fire mode we need to set up now that the buttons are up - if ( pm->ps->weaponstate == WEAPON_CHARGING ) - { + if (pm->ps->weaponstate == WEAPON_CHARGING) { // weapon has a charge, so let us do an attack // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ATTACK; pm->ps->eFlags |= EF_FIRING; - } - else if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + } else if (pm->ps->weaponstate == WEAPON_CHARGING_ALT) { // weapon has a charge, so let us do an alt-attack // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ALT_ATTACK; - pm->ps->eFlags |= (EF_FIRING|EF_ALT_FIRING); + pm->ps->eFlags |= (EF_FIRING | EF_ALT_FIRING); } return false; // continue with the rest of the weapon code } - -#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define DEMP2_CHARGE_UNIT 500.0f // ditto -#define DISRUPTOR_CHARGE_UNIT 150.0f // ditto +#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon +#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon +#define DEMP2_CHARGE_UNIT 500.0f // ditto +#define DISRUPTOR_CHARGE_UNIT 150.0f // ditto // Specific weapons can opt to modify the ammo usage based on charges, otherwise if no special case code // is handled below, regular ammo usage will happen //--------------------------------------- -static int PM_DoChargingAmmoUsage( int *amount ) +static int PM_DoChargingAmmoUsage(int *amount) //--------------------------------------- { int count = 0; - if ( pm->ps->weapon == WP_BOWCASTER && !( pm->cmd.buttons & BUTTON_ALT_ATTACK )) - { + if (pm->ps->weapon == WP_BOWCASTER && !(pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the bowcaster alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / BOWCASTER_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / BOWCASTER_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if ( !(count & 1 )) - { + if (!(count & 1)) { // if we aren't odd, knock us down a level count--; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * BOWCASTER_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * BOWCASTER_CHARGE_UNIT); } } // now that count is cool, get the real ammo usage *amount *= count; - } - else if( ( pm->ps->weapon == WP_BRYAR_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK ) - || ( pm->ps->weapon == WP_BLASTER_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK ) ) - { + } else if ((pm->ps->weapon == WP_BRYAR_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK) || + (pm->ps->weapon == WP_BLASTER_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the bryar alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / BRYAR_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / BRYAR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * BRYAR_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * BRYAR_CHARGE_UNIT); } } // now that count is cool, get the real ammo usage *amount *= count; - } - else if ( pm->ps->weapon == WP_DEMP2 && pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + } else if (pm->ps->weapon == WP_DEMP2 && pm->cmd.buttons & BUTTON_ALT_ATTACK) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the demp2 alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / DEMP2_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / DEMP2_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 3 ) - { + } else if (count > 3) { count = 3; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * DEMP2_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * DEMP2_CHARGE_UNIT); } } @@ -13201,43 +10521,36 @@ static int PM_DoChargingAmmoUsage( int *amount ) *amount *= count; // this is an after-thought. should probably re-write the function to do this naturally. - if ( *amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] ) - { + if (*amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]) { *amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]; } - } - else if ( pm->ps->weapon == WP_DISRUPTOR && pm->cmd.buttons & BUTTON_ALT_ATTACK ) // BUTTON_ATTACK will have been mapped to BUTTON_ALT_ATTACK if we are zoomed + } else if (pm->ps->weapon == WP_DISRUPTOR && + pm->cmd.buttons & BUTTON_ALT_ATTACK) // BUTTON_ATTACK will have been mapped to BUTTON_ALT_ATTACK if we are zoomed { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the disruptor alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / DISRUPTOR_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / DISRUPTOR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 10 ) - { + } else if (count > 10) { count = 10; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * DISRUPTOR_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * DISRUPTOR_CHARGE_UNIT); } } @@ -13245,8 +10558,7 @@ static int PM_DoChargingAmmoUsage( int *amount ) *amount *= count; // this is an after-thought. should probably re-write the function to do this naturally. - if ( *amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] ) - { + if (*amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]) { *amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]; } } @@ -13254,64 +10566,50 @@ static int PM_DoChargingAmmoUsage( int *amount ) return count; } -qboolean PM_DroidMelee( int npc_class ) -{ - if ( npc_class == CLASS_PROBE - || npc_class == CLASS_SEEKER - || npc_class == CLASS_INTERROGATOR - || npc_class == CLASS_SENTRY - || npc_class == CLASS_REMOTE ) - { +qboolean PM_DroidMelee(int npc_class) { + if (npc_class == CLASS_PROBE || npc_class == CLASS_SEEKER || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_SENTRY || npc_class == CLASS_REMOTE) { return qtrue; } return qfalse; } -void PM_WeaponWampa( void ) -{ +void PM_WeaponWampa(void) { // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) { - if ( pm->ps->weapon != pm->cmd.weapon ) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { return; } // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } - if ( pm->ps->weapon == WP_SABER - && (pm->cmd.buttons&BUTTON_ATTACK) - && pm->ps->torsoAnim == BOTH_HANG_IDLE ) - { + if (pm->ps->weapon == WP_SABER && (pm->cmd.buttons & BUTTON_ATTACK) && pm->ps->torsoAnim == BOTH_HANG_IDLE) { pm->ps->SaberActivate(); - pm->ps->SaberActivateTrail( 150 ); - PM_SetAnim( pm, SETANIM_BOTH, BOTH_HANG_ATTACK, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + pm->ps->SaberActivateTrail(150); + PM_SetAnim(pm, SETANIM_BOTH, BOTH_HANG_ATTACK, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponstate = WEAPON_FIRING; pm->ps->saberBlocked = BLOCKED_NONE; pm->ps->saberMove = LS_READY; pm->ps->saberMoveNext = LS_NONE; - } - else if ( pm->ps->torsoAnim == BOTH_HANG_IDLE ) - { - pm->ps->SaberDeactivateTrail( 0 ); + } else if (pm->ps->torsoAnim == BOTH_HANG_IDLE) { + pm->ps->SaberDeactivateTrail(0); pm->ps->weaponstate = WEAPON_READY; pm->ps->saberMove = LS_READY; pm->ps->saberMoveNext = LS_NONE; @@ -13324,388 +10622,293 @@ PM_Weapon Generates weapon events and modifes the weapon counter ============== */ -static void PM_Weapon( void ) -{ - int addTime, amount, trueCount = 1; - qboolean delayed_fire = qfalse; +static void PM_Weapon(void) { + int addTime, amount, trueCount = 1; + qboolean delayed_fire = qfalse; - if ( (pm->ps->eFlags&EF_HELD_BY_WAMPA) ) - { + if ((pm->ps->eFlags & EF_HELD_BY_WAMPA)) { PM_WeaponWampa(); return; } - if ( pm->ps->eFlags&EF_FORCE_DRAINED ) - {//being drained + if (pm->ps->eFlags & EF_FORCE_DRAINED) { // being drained return; } - if ( (pm->ps->forcePowersActive&(1<ps->forceDrainEntityNum < ENTITYNUM_WORLD ) - {//draining + if ((pm->ps->forcePowersActive & (1 << FP_DRAIN)) && pm->ps->forceDrainEntityNum < ENTITYNUM_WORLD) { // draining return; } - if (pm->ps->weapon == WP_SABER && (cg.zoomMode==3||!cg.zoomMode||pm->ps->clientNum) ) // WP_LIGHTSABER - { // Separate logic for lightsaber, but not for player when zoomed + if (pm->ps->weapon == WP_SABER && (cg.zoomMode == 3 || !cg.zoomMode || pm->ps->clientNum)) // WP_LIGHTSABER + { // Separate logic for lightsaber, but not for player when zoomed PM_WeaponLightsaber(); - if ( pm->gent && pm->gent->client && pm->ps->saber[0].Active() && pm->ps->saberInFlight ) - {//FIXME: put saberTrail in playerState - if ( pm->gent->client->ps.saberEntityState == SES_RETURNING ) - {//turn off the saber trail - pm->gent->client->ps.SaberDeactivateTrail( 75 ); - } - else - {//turn on the saber trail - pm->gent->client->ps.SaberActivateTrail( 150 ); + if (pm->gent && pm->gent->client && pm->ps->saber[0].Active() && pm->ps->saberInFlight) { // FIXME: put saberTrail in playerState + if (pm->gent->client->ps.saberEntityState == SES_RETURNING) { // turn off the saber trail + pm->gent->client->ps.SaberDeactivateTrail(75); + } else { // turn on the saber trail + pm->gent->client->ps.SaberActivateTrail(150); } } return; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown - if ( pm->ps->weaponTime > 0 ) { + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } return; } - if( pm->gent && pm->gent->client ) - { - if ( pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client) { + if (pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually pm->gent->client->fireDelay -= pml.msec; - if(pm->gent->client->fireDelay <= 0) - {//just finished delay timer - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav" ); + if (pm->gent->client->fireDelay <= 0) { // just finished delay timer + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav"); pm->cmd.buttons |= BUTTON_ALT_ATTACK; } pm->gent->client->fireDelay = 0; delayed_fire = qtrue; - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && pm->ps->weapon == WP_THERMAL - && pm->gent->alt_fire ) - { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && pm->ps->weapon == WP_THERMAL && pm->gent->alt_fire) { pm->cmd.buttons |= BUTTON_ALT_ATTACK; } - } - else - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand( 0, 1 ) ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav" ); + } else { + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand(0, 1)) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav"); } } } } - // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + // don't allow attack until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) - { - if ( pm->gent && pm->gent->client ) - { + if (pm->ps->stats[STAT_HEALTH] <= 0) { + if (pm->gent && pm->gent->client) { pm->ps->weapon = WP_NONE; } - if ( pm->gent ) - { + if (pm->gent) { pm->gent->s.loopSound = 0; } return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - if ( (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_CHARGING) { - if ( pm->ps->weapon != pm->cmd.weapon && (!pm->ps->viewEntity || pm->ps->viewEntity >= ENTITYNUM_WORLD) && !PM_DoChargedWeapons()) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if ((pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && + pm->ps->weaponstate != WEAPON_CHARGING) { + if (pm->ps->weapon != pm->cmd.weapon && (!pm->ps->viewEntity || pm->ps->viewEntity >= ENTITYNUM_WORLD) && !PM_DoChargedWeapons()) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { return; } // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } - if ( pm->ps->weapon == WP_NONE ) - { + if (pm->ps->weapon == WP_NONE) { return; } - if ( pm->ps->weaponstate == WEAPON_RAISING ) - { - //Just selected the weapon + if (pm->ps->weaponstate == WEAPON_RAISING) { + // Just selected the weapon pm->ps->weaponstate = WEAPON_IDLE; - if(pm->gent && (pm->gent->s.numbergent))) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - else - { - switch(pm->ps->weapon) - { + if (pm->gent && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent))) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); + } else { + switch (pm->ps->weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: - if ( pm->gent - && pm->gent->weaponModel[1] > 0 ) - {//dual pistols - //FIXME: should be a better way of detecting a dual-pistols user so it's not hardcoded to the saboteurcommando... - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - else - {//single pistol - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->weaponModel[1] > 0) { // dual pistols + // FIXME: should be a better way of detecting a dual-pistols user so it's not hardcoded to the saboteurcommando... + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); + } else { // single pistol + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); } break; default: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); break; } } return; } - if ( pm->gent ) - {//ready to throw thermal again, add it - if ( pm->ps->weapon == WP_THERMAL - && pm->gent->weaponModel[0] == -1 ) - {//add the thermal model back in our hand + if (pm->gent) { // ready to throw thermal again, add it + if (pm->ps->weapon == WP_THERMAL && pm->gent->weaponModel[0] == -1) { // add the thermal model back in our hand // remove anything if we have anything already - G_RemoveWeaponModels( pm->gent ); - if (weaponData[pm->ps->weapon].weaponMdl[0]) { //might be NONE, so check if it has a model - G_CreateG2AttachedWeaponModel( pm->gent, weaponData[pm->ps->weapon].weaponMdl, pm->gent->handRBolt, 0 ); - //make it sound like we took another one out from... uh.. somewhere... - if ( cg.time > 0 ) - {//this way we don't get that annoying change weapon sound every time a map starts - PM_AddEvent( EV_CHANGE_WEAPON ); + G_RemoveWeaponModels(pm->gent); + if (weaponData[pm->ps->weapon].weaponMdl[0]) { // might be NONE, so check if it has a model + G_CreateG2AttachedWeaponModel(pm->gent, weaponData[pm->ps->weapon].weaponMdl, pm->gent->handRBolt, 0); + // make it sound like we took another one out from... uh.. somewhere... + if (cg.time > 0) { // this way we don't get that annoying change weapon sound every time a map starts + PM_AddEvent(EV_CHANGE_WEAPON); } } } } - if ( !delayed_fire ) - {//didn't just finish a fire delay - if ( PM_DoChargedWeapons()) - { + if (!delayed_fire) { // didn't just finish a fire delay + if (PM_DoChargedWeapons()) { // In some cases the charged weapon code may want us to short circuit the rest of the firing code return; - } - else - { - if ( !pm->gent->client->fireDelay//not already waiting to fire - && (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer())//player - && pm->ps->weapon == WP_THERMAL//holding thermal - && pm->gent//gent - && pm->gent->client//client - && (pm->cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) )//holding fire - {//delay the actual firing of the missile until the anim has played some - if ( PM_StandingAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_THERMAL_READY ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - PM_SetAnim(pm,SETANIM_TORSO,BOTH_THERMAL_THROW,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + } else { + if (!pm->gent->client->fireDelay // not already waiting to fire + && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) // player + && pm->ps->weapon == WP_THERMAL // holding thermal + && pm->gent // gent + && pm->gent->client // client + && (pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) // holding fire + { // delay the actual firing of the missile until the anim has played some + if (PM_StandingAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_THERMAL_READY) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + PM_SetAnim(pm, SETANIM_TORSO, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); pm->gent->client->fireDelay = 300; pm->ps->weaponstate = WEAPON_FIRING; - pm->gent->alt_fire = (qboolean)(pm->cmd.buttons&BUTTON_ALT_ATTACK); + pm->gent->alt_fire = (qboolean)(pm->cmd.buttons & BUTTON_ALT_ATTACK); return; } } } - if(!delayed_fire) - { - if ( pm->ps->weapon == WP_MELEE && (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//melee - if ( (pm->cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) != (BUTTON_ATTACK|BUTTON_ALT_ATTACK) ) - {//not holding both buttons - if ( (pm->cmd.buttons&BUTTON_ATTACK)&&(pm->ps->pm_flags&PMF_ATTACK_HELD) ) - {//held button - //clear it + if (!delayed_fire) { + if (pm->ps->weapon == WP_MELEE && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // melee + if ((pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) != (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) { // not holding both buttons + if ((pm->cmd.buttons & BUTTON_ATTACK) && (pm->ps->pm_flags & PMF_ATTACK_HELD)) { // held button + // clear it pm->cmd.buttons &= ~BUTTON_ATTACK; } - if ( (pm->cmd.buttons&BUTTON_ALT_ATTACK)&&(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD) ) - {//held button - //clear it + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && (pm->ps->pm_flags & PMF_ALT_ATTACK_HELD)) { // held button + // clear it pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } } } // check for fire - if ( !(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - { + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { pm->ps->weaponTime = 0; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//Still firing + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // Still firing pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { - if ( !pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time ) - { + } else if (pm->ps->weaponstate != WEAPON_READY) { + if (!pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time) { pm->ps->weaponstate = WEAPON_IDLE; } } - if ( pm->ps->weapon == WP_MELEE - && (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) - && PM_KickMove( pm->ps->saberMove ) ) - {//melee, not attacking, clear move + if (pm->ps->weapon == WP_MELEE && (pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && + PM_KickMove(pm->ps->saberMove)) { // melee, not attacking, clear move pm->ps->saberMove = LS_NONE; } return; } - if (pm->gent->s.m_iVehicleNum!=0) - { + if (pm->gent->s.m_iVehicleNum != 0) { // No Anims if on Veh } // start the animation even if out of ammo - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ROCKETTROOPER ) - { - if ( pm->gent->client->moveType == MT_FLYSWIM ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ROCKETTROOPER) { + if (pm->gent->client->moveType == MT_FLYSWIM) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } } #ifndef BASE_SAVE_COMPAT - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_HAZARD_TROOPER ) - { + else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_HAZARD_TROOPER) { // Kneel attack //-------------- - if( pm->cmd.upmove == -127 ) - { - PM_SetAnim(pm,SETANIM_TORSO, BOTH_KNEELATTACK, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (pm->cmd.upmove == -127) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_KNEELATTACK, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } // Standing attack //----------------- } #endif - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ASSASSIN_DROID ) - { + else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ASSASSIN_DROID) { // Crouched Attack - if (PM_CrouchAnim(pm->gent->client->ps.legsAnim)) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLDLESS); + if (PM_CrouchAnim(pm->gent->client->ps.legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLDLESS); } // Standing Attack //----------------- - else - { - // if (PM_StandingAnim(pm->gent->client->ps.legsAnim)) - // { - // PM_SetAnim(pm,SETANIM_BOTH,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLDLESS); - // } - // else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLDLESS); - } + else { + // if (PM_StandingAnim(pm->gent->client->ps.legsAnim)) + // { + // PM_SetAnim(pm,SETANIM_BOTH,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLDLESS); + // } + // else + { PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLDLESS); } } - } - else - { - switch(pm->ps->weapon) - { + } else { + switch (pm->ps->weapon) { /* case WP_SABER://1 - handed PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); break; */ - case WP_BRYAR_PISTOL://1-handed - case WP_BLASTER_PISTOL://1-handed - if ( pm->gent && pm->gent->weaponModel[1] > 0 ) - {//dual pistols - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - {//single pistol - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + case WP_BRYAR_PISTOL: // 1-handed + case WP_BLASTER_PISTOL: // 1-handed + if (pm->gent && pm->gent->weaponModel[1] > 0) { // dual pistols + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { // single pistol + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } break; case WP_MELEE: // since there's no RACE_BOTS, I listed all the droids that have might have melee attacks - dmv - if ( pm->gent && pm->gent->client ) - { - if ( PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - if ( rand() & 1 ) - PM_SetAnim(pm,SETANIM_BOTH,BOTH_MELEE1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client) { + if (PM_DroidMelee(pm->gent->client->NPC_class)) { + if (rand() & 1) + PM_SetAnim(pm, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); else - PM_SetAnim(pm,SETANIM_BOTH,BOTH_MELEE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else - { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { int anim = -1; - if ( (pm->ps->clientNum < MAX_CLIENTS ||PM_ControlledByPlayer()) - && g_debugMelee->integer ) - { - if ( (pm->cmd.buttons&BUTTON_ALT_ATTACK) ) - { - if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - { + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && g_debugMelee->integer) { + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK)) { + if ((pm->cmd.buttons & BUTTON_ATTACK)) { PM_TryGrab(); - } - else if ( !(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD) ) - { + } else if (!(pm->ps->pm_flags & PMF_ALT_ATTACK_HELD)) { PM_CheckKick(); } + } else if (!(pm->ps->pm_flags & PMF_ATTACK_HELD)) { + anim = PM_PickAnim(pm->gent, BOTH_MELEE1, BOTH_MELEE2); } - else if ( !(pm->ps->pm_flags&PMF_ATTACK_HELD) ) - { - anim = PM_PickAnim( pm->gent, BOTH_MELEE1, BOTH_MELEE2 ); - } - } - else - { - anim = PM_PickAnim( pm->gent, BOTH_MELEE1, BOTH_MELEE2 ); - } - if ( anim != -1 ) - { - if ( VectorCompare( pm->ps->velocity, vec3_origin ) && pm->cmd.upmove >= 0 ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + } else { + anim = PM_PickAnim(pm->gent, BOTH_MELEE1, BOTH_MELEE2); + } + if (anim != -1) { + if (VectorCompare(pm->ps->velocity, vec3_origin) && pm->cmd.upmove >= 0) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } } } @@ -13713,142 +10916,101 @@ static void PM_Weapon( void ) break; case WP_TUSKEN_RIFLE: - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - {//shoot - //in alt-fire, sniper mode - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//melee - int anim = PM_PickAnim( pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3 ); // Rifle - if ( VectorCompare( pm->ps->velocity, vec3_origin ) && pm->cmd.upmove >= 0 ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // shoot + // in alt-fire, sniper mode + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // melee + int anim = PM_PickAnim(pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3); // Rifle + if (VectorCompare(pm->ps->velocity, vec3_origin) && pm->cmd.upmove >= 0) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } } break; case WP_TUSKEN_STAFF: - if ( pm->gent && pm->gent->client ) - { + if (pm->gent && pm->gent->client) { int anim; - int flags = (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); - if ( (pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) ) - {//player - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + int flags = (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + if ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer())) { // player + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + if (pm->cmd.buttons & BUTTON_ATTACK) { anim = BOTH_TUSKENATTACK3; - } - else - { + } else { anim = BOTH_TUSKENATTACK2; } - } - else - { + } else { anim = BOTH_TUSKENATTACK1; } - } - else - {// npc - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + } else { // npc + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { anim = BOTH_TUSKENLUNGE1; - if (pm->ps->torsoAnimTimer>0) - { + if (pm->ps->torsoAnimTimer > 0) { flags &= ~SETANIM_FLAG_RESTART; } + } else { + anim = PM_PickAnim(pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3); } - else - { - anim = PM_PickAnim( pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3 ); - } - } - if ( VectorCompare( pm->ps->velocity, vec3_origin ) && pm->cmd.upmove >= 0 ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, flags, 0); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, anim, flags, 0); + if (VectorCompare(pm->ps->velocity, vec3_origin) && pm->cmd.upmove >= 0) { + PM_SetAnim(pm, SETANIM_BOTH, anim, flags, 0); + } else { + PM_SetAnim(pm, SETANIM_TORSO, anim, flags, 0); } } break; case WP_NOGHRI_STICK: - if ( pm->gent && pm->gent->client ) - { + if (pm->gent && pm->gent->client) { int anim; - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { - anim = BOTH_ATTACK3; - } - else - { - anim = PM_PickAnim( pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3 ); - } - if ( anim != BOTH_ATTACK3 && VectorCompare( pm->ps->velocity, vec3_origin ) && pm->cmd.upmove >= 0 ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + if (pm->cmd.buttons & BUTTON_ATTACK) { + anim = BOTH_ATTACK3; + } else { + anim = PM_PickAnim(pm->gent, BOTH_TUSKENATTACK1, BOTH_TUSKENATTACK3); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + if (anim != BOTH_ATTACK3 && VectorCompare(pm->ps->velocity, vec3_origin) && pm->cmd.upmove >= 0) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } } break; case WP_BLASTER: - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); break; case WP_DISRUPTOR: - if ( ((pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer())&& pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags&SCF_ALT_FIRE)) || - ((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) && cg.zoomMode == 2 ) ) - {//NPC or player in alt-fire, sniper mode - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//in primary fire mode - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); + if (((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) && pm->gent && pm->gent->NPC && + (pm->gent->NPC->scriptFlags & SCF_ALT_FIRE)) || + ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) && cg.zoomMode == 2)) { // NPC or player in alt-fire, sniper mode + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // in primary fire mode + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - { - if ( PM_StandingAnim( pm->ps->legsAnim ) ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_ATTACK10, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { + if (PM_StandingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_ATTACK10, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK10,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - if ( cg.renderingThirdPerson ) - { - if ( PM_StandingAnim( pm->ps->legsAnim ) - || pm->ps->legsAnim == BOTH_THERMAL_READY ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK10, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + if (cg.renderingThirdPerson) { + if (PM_StandingAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_THERMAL_READY) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - PM_SetAnim(pm,SETANIM_TORSO,BOTH_THERMAL_THROW,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//|SETANIM_FLAG_RESTART - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); //|SETANIM_FLAG_RESTART + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } } break; @@ -13862,174 +11024,132 @@ static void PM_Weapon( void ) break; case WP_REPEATER: - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {// - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { // + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } break; case WP_TRIP_MINE: case WP_DET_PACK: - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK11,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK11, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; - default://2-handed heavy weapon - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + default: // 2-handed heavy weapon + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; } } } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { amount = weaponData[pm->ps->weapon].altEnergyPerShot; - } - else - { + } else { amount = weaponData[pm->ps->weapon].energyPerShot; } - if ( (pm->ps->weaponstate == WEAPON_CHARGING) || (pm->ps->weaponstate == WEAPON_CHARGING_ALT) ) - { + if ((pm->ps->weaponstate == WEAPON_CHARGING) || (pm->ps->weaponstate == WEAPON_CHARGING_ALT)) { // charging weapons may want to do their own ammo logic. - trueCount = PM_DoChargingAmmoUsage( &amount ); + trueCount = PM_DoChargingAmmoUsage(&amount); } pm->ps->weaponstate = WEAPON_FIRING; // take an ammo away if not infinite - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { // enough energy to fire this weapon? - if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) - { + if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) { pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] -= amount; - } - else // Not enough energy + } else // Not enough energy { - if ( !( pm->ps->eFlags & EF_LOCKED_TO_WEAPON )) - { + if (!(pm->ps->eFlags & EF_LOCKED_TO_WEAPON)) { // Switch weapons - PM_AddEvent( EV_NOAMMO ); + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; } return; } } - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually // Clear these out since we're not actually firing yet pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; return; } - if ( pm->ps->weapon == WP_EMPLACED_GUN ) - { - if ( pm->gent - && pm->gent->owner - && pm->gent->owner->e_UseFunc == useF_eweb_use ) - {//eweb always shoots alt-fire, for proper effects and sounds - PM_AddEvent( EV_ALT_FIRE ); + if (pm->ps->weapon == WP_EMPLACED_GUN) { + if (pm->gent && pm->gent->owner && pm->gent->owner->e_UseFunc == useF_eweb_use) { // eweb always shoots alt-fire, for proper effects and sounds + PM_AddEvent(EV_ALT_FIRE); addTime = weaponData[pm->ps->weapon].altFireTime; - } - else - {//emplaced gun always shoots normal fire - PM_AddEvent( EV_FIRE_WEAPON ); + } else { // emplaced gun always shoots normal fire + PM_AddEvent(EV_FIRE_WEAPON); addTime = weaponData[pm->ps->weapon].fireTime; } - } - else if ( (pm->ps->weapon == WP_MELEE && (pm->ps->clientNum>=MAX_CLIENTS||!g_debugMelee->integer) ) - || pm->ps->weapon == WP_TUSKEN_STAFF - || (pm->ps->weapon == WP_TUSKEN_RIFLE&&!(pm->cmd.buttons&BUTTON_ALT_ATTACK)) ) - { - PM_AddEvent( EV_FIRE_WEAPON ); + } else if ((pm->ps->weapon == WP_MELEE && (pm->ps->clientNum >= MAX_CLIENTS || !g_debugMelee->integer)) || pm->ps->weapon == WP_TUSKEN_STAFF || + (pm->ps->weapon == WP_TUSKEN_RIFLE && !(pm->cmd.buttons & BUTTON_ALT_ATTACK))) { + PM_AddEvent(EV_FIRE_WEAPON); addTime = pm->ps->torsoAnimTimer; - } - else if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - PM_AddEvent( EV_ALT_FIRE ); + } else if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_AddEvent(EV_ALT_FIRE); addTime = weaponData[pm->ps->weapon].altFireTime; - if ( pm->ps->weapon == WP_THERMAL ) - {//threw our thermal - if ( pm->gent ) - {// remove the thermal model if we had it. - G_RemoveWeaponModels( pm->gent ); - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - {//NPCs need to know when to put the thermal back in their hand - pm->ps->weaponTime = pm->ps->torsoAnimTimer-500; + if (pm->ps->weapon == WP_THERMAL) { // threw our thermal + if (pm->gent) { // remove the thermal model if we had it. + G_RemoveWeaponModels(pm->gent); + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { // NPCs need to know when to put the thermal back in their hand + pm->ps->weaponTime = pm->ps->torsoAnimTimer - 500; } } } - } - else - { - if ( pm->ps->clientNum //NPC - && !PM_ControlledByPlayer() //not under player control - && pm->ps->weapon == WP_THERMAL //using thermals - && pm->ps->torsoAnim != BOTH_ATTACK10 )//not in the throw anim - {//oops, got knocked out of the anim, don't throw the thermal + } else { + if (pm->ps->clientNum // NPC + && !PM_ControlledByPlayer() // not under player control + && pm->ps->weapon == WP_THERMAL // using thermals + && pm->ps->torsoAnim != BOTH_ATTACK10) // not in the throw anim + { // oops, got knocked out of the anim, don't throw the thermal return; } - PM_AddEvent( EV_FIRE_WEAPON ); + PM_AddEvent(EV_FIRE_WEAPON); addTime = weaponData[pm->ps->weapon].fireTime; - switch( pm->ps->weapon) - { + switch (pm->ps->weapon) { case WP_REPEATER: // repeater is supposed to do smoke after sustained bursts pm->ps->weaponShotCount++; break; case WP_BOWCASTER: - addTime *= (( trueCount < 3 ) ? 0.35f : 1.0f );// if you only did a small charge shot with the bowcaster, use less time between shots + addTime *= ((trueCount < 3) ? 0.35f : 1.0f); // if you only did a small charge shot with the bowcaster, use less time between shots break; case WP_THERMAL: - if ( pm->gent ) - {// remove the thermal model if we had it. - G_RemoveWeaponModels( pm->gent ); - if ( (pm->ps->clientNum >= MAX_CLIENTS&&!PM_ControlledByPlayer()) ) - {//NPCs need to know when to put the thermal back in their hand - pm->ps->weaponTime = pm->ps->torsoAnimTimer-500; + if (pm->gent) { // remove the thermal model if we had it. + G_RemoveWeaponModels(pm->gent); + if ((pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer())) { // NPCs need to know when to put the thermal back in their hand + pm->ps->weaponTime = pm->ps->torsoAnimTimer - 500; } } break; } } - - if(!PM_ControlledByPlayer()) - { - if(pm->gent && pm->gent->NPC != NULL ) - {//NPCs have their own refire logic + if (!PM_ControlledByPlayer()) { + if (pm->gent && pm->gent->NPC != NULL) { // NPCs have their own refire logic return; } } - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client - && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<ps->clientNum].client && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { addTime *= g_timescale->value; } } @@ -14037,17 +11157,15 @@ static void PM_Weapon( void ) } pm->ps->weaponTime += addTime; - pm->ps->lastShotTime = level.time;//so we know when the last time we fired our gun is + pm->ps->lastShotTime = level.time; // so we know when the last time we fired our gun is // HACK!!!!! - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0 ) - { - if ( pm->ps->weapon == WP_THERMAL || pm->ps->weapon == WP_TRIP_MINE ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + if (pm->ps->weapon == WP_THERMAL || pm->ps->weapon == WP_TRIP_MINE) { // because these weapons have the ammo attached to the hand, we should switch weapons when the last one is thrown, otherwise it will look silly // NOTE: could also switch to an empty had version, but was told we aren't getting any new models at this point CG_OutOfAmmoChange(); - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP1 + 2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); // hack weapon down! + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP1 + 2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // hack weapon down! pm->ps->weaponTime = 50; } } @@ -14060,94 +11178,75 @@ PM_VehicleWeapon Generates weapon events and modifes the weapon counter ============== */ -static void PM_VehicleWeapon( void ) -{ - int addTime = 0; - qboolean delayed_fire = qfalse; +static void PM_VehicleWeapon(void) { + int addTime = 0; + qboolean delayed_fire = qfalse; - if ( pm->ps->weapon == WP_NONE ) - { + if (pm->ps->weapon == WP_NONE) { return; } - if(pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually pm->gent->client->fireDelay -= pml.msec; - if(pm->gent->client->fireDelay <= 0) - {//just finished delay timer - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav" ); + if (pm->gent->client->fireDelay <= 0) { // just finished delay timer + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav"); pm->cmd.buttons |= BUTTON_ALT_ATTACK; } pm->gent->client->fireDelay = 0; delayed_fire = qtrue; - } - else - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand( 0, 1 ) ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav" ); + } else { + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand(0, 1)) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav"); } } } - // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + // don't allow attack until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) - { - if ( pm->gent ) - { + if (pm->ps->stats[STAT_HEALTH] <= 0) { + if (pm->gent) { pm->gent->s.loopSound = 0; } return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { return; } // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } - if ( PM_DoChargedWeapons()) - { + if (PM_DoChargedWeapons()) { // In some cases the charged weapon code may want us to short circuit the rest of the firing code return; } - if(!delayed_fire) - { + if (!delayed_fire) { // check for fire - if ( !(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - { + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { pm->ps->weaponTime = 0; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//Still firing + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // Still firing pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { - if ( !pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time ) - { + } else if (pm->ps->weaponstate != WEAPON_READY) { + if (!pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time) { pm->ps->weaponstate = WEAPON_IDLE; } } @@ -14158,44 +11257,35 @@ static void PM_VehicleWeapon( void ) pm->ps->weaponstate = WEAPON_FIRING; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually // Clear these out since we're not actually firing yet pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; return; } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - PM_AddEvent( EV_ALT_FIRE ); - //addTime = weaponData[pm->ps->weapon].altFireTime; - } - else - { - PM_AddEvent( EV_FIRE_WEAPON ); + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_AddEvent(EV_ALT_FIRE); + // addTime = weaponData[pm->ps->weapon].altFireTime; + } else { + PM_AddEvent(EV_FIRE_WEAPON); // TODO: Use the real weapon fire time from the vehicle cfg file. - //addTime = weaponData[pm->ps->weapon].fireTime; + // addTime = weaponData[pm->ps->weapon].fireTime; } -/* if(pm->gent && pm->gent->NPC != NULL ) - {//NPCs have their own refire logic - return; - }*/ + /* if(pm->gent && pm->gent->NPC != NULL ) + {//NPCs have their own refire logic + return; + }*/ - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client - && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<ps->clientNum].client && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { addTime *= g_timescale->value; } } @@ -14203,63 +11293,57 @@ static void PM_VehicleWeapon( void ) } pm->ps->weaponTime += addTime; - pm->ps->lastShotTime = level.time;//so we know when the last time we fired our gun is + pm->ps->lastShotTime = level.time; // so we know when the last time we fired our gun is } - -extern void ForceHeal( gentity_t *self ); -extern void ForceTelepathy( gentity_t *self ); -extern void ForceRage( gentity_t *self ); -extern void ForceProtect( gentity_t *self ); -extern void ForceAbsorb( gentity_t *self ); -extern void ForceSeeing( gentity_t *self ); -void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( !ent ) - { +extern void ForceHeal(gentity_t *self); +extern void ForceTelepathy(gentity_t *self); +extern void ForceRage(gentity_t *self); +extern void ForceProtect(gentity_t *self); +extern void ForceAbsorb(gentity_t *self); +extern void ForceSeeing(gentity_t *self); +void PM_CheckForceUseButton(gentity_t *ent, usercmd_t *ucmd) { + if (!ent) { return; } - if ( ucmd->buttons & BUTTON_USE_FORCE ) - { - if (!(ent->client->ps.pm_flags & PMF_USEFORCE_HELD)) - { - //impulse one shot - switch ( showPowers[cg.forcepowerSelect] ) - { + if (ucmd->buttons & BUTTON_USE_FORCE) { + if (!(ent->client->ps.pm_flags & PMF_USEFORCE_HELD)) { + // impulse one shot + switch (showPowers[cg.forcepowerSelect]) { case FP_HEAL: - ForceHeal( ent ); + ForceHeal(ent); break; case FP_SPEED: - ForceSpeed( ent ); + ForceSpeed(ent); break; case FP_PUSH: - ForceThrow( ent, qfalse ); + ForceThrow(ent, qfalse); break; case FP_PULL: - ForceThrow( ent, qtrue ); + ForceThrow(ent, qtrue); break; case FP_TELEPATHY: - ForceTelepathy( ent ); + ForceTelepathy(ent); break; // Added 01/20/03 by AReis. // New Jedi Academy powers. - case FP_RAGE: //duration - speed, invincibility and extra damage for short period, drains your health and leaves you weak and slow afterwards. - ForceRage( ent ); + case FP_RAGE: // duration - speed, invincibility and extra damage for short period, drains your health and leaves you weak and slow afterwards. + ForceRage(ent); break; - case FP_PROTECT: //duration - protect against physical/energy (level 1 stops blaster/energy bolts, level 2 stops projectiles, level 3 protects against explosions) - ForceProtect( ent ); + case FP_PROTECT: // duration - protect against physical/energy (level 1 stops blaster/energy bolts, level 2 stops projectiles, level 3 protects + // against explosions) + ForceProtect(ent); break; - case FP_ABSORB: //duration - protect against dark force powers (grip, lightning, drain - maybe push/pull, too?) - ForceAbsorb( ent ); + case FP_ABSORB: // duration - protect against dark force powers (grip, lightning, drain - maybe push/pull, too?) + ForceAbsorb(ent); break; - case FP_SEE: //duration - detect/see hidden enemies - ForceSeeing( ent ); + case FP_SEE: // duration - detect/see hidden enemies + ForceSeeing(ent); break; } } - //these stay are okay to call every frame button is down - switch ( showPowers[cg.forcepowerSelect] ) - { + // these stay are okay to call every frame button is down + switch (showPowers[cg.forcepowerSelect]) { case FP_LEVITATION: ucmd->upmove = 127; break; @@ -14273,13 +11357,12 @@ void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ) // FIXME! Failing at WP_ForcePowerUsable(). -AReis ucmd->buttons |= BUTTON_FORCE_DRAIN; break; -// default: -// Com_Printf( "Use Force: Unhandled force: %d\n", showPowers[cg.forcepowerSelect]); -// break; + // default: + // Com_Printf( "Use Force: Unhandled force: %d\n", showPowers[cg.forcepowerSelect]); + // break; } ent->client->ps.pm_flags |= PMF_USEFORCE_HELD; - } - else//not pressing USE_FORCE + } else // not pressing USE_FORCE { ent->client->ps.pm_flags &= ~PMF_USEFORCE_HELD; } @@ -14317,214 +11400,159 @@ static void PM_ForcePower(void) PM_DropTimers ================ */ -static void PM_DropTimers( void ) -{ +static void PM_DropTimers(void) { // drop misc timing counter - if ( pm->ps->pm_time ) - { - if ( pml.msec >= pm->ps->pm_time ) - { + if (pm->ps->pm_time) { + if (pml.msec >= pm->ps->pm_time) { pm->ps->pm_flags &= ~PMF_ALL_TIMES; pm->ps->pm_time = 0; - } - else - { + } else { pm->ps->pm_time -= pml.msec; } } // drop legs animation counter - if ( pm->ps->legsAnimTimer > 0 ) - { + if (pm->ps->legsAnimTimer > 0) { int newTime = pm->ps->legsAnimTimer - pml.msec; - if ( newTime < 0 ) - { + if (newTime < 0) { newTime = 0; } - PM_SetLegsAnimTimer( pm->gent, &pm->ps->legsAnimTimer, newTime ); + PM_SetLegsAnimTimer(pm->gent, &pm->ps->legsAnimTimer, newTime); } // drop torso animation counter - if ( pm->ps->torsoAnimTimer > 0 ) - { + if (pm->ps->torsoAnimTimer > 0) { int newTime = pm->ps->torsoAnimTimer - pml.msec; - if ( newTime < 0 ) - { + if (newTime < 0) { newTime = 0; } - PM_SetTorsoAnimTimer( pm->gent, &pm->ps->torsoAnimTimer, newTime ); + PM_SetTorsoAnimTimer(pm->gent, &pm->ps->torsoAnimTimer, newTime); } } -void PM_SetSpecialMoveValues (void ) -{ +void PM_SetSpecialMoveValues(void) { Flying = 0; - if ( pm->gent ) - { - if ( pm->gent->client && pm->gent->client->moveType == MT_FLYSWIM ) - { + if (pm->gent) { + if (pm->gent->client && pm->gent->client->moveType == MT_FLYSWIM) { Flying = FLY_NORMAL; - } - else if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { - if ( pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - { + } else if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { + if (pm->gent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { Flying = FLY_VEHICLE; - } - else if ( pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0 ) - {//FIXME: or just check for hoverHeight? + } else if (pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) { // FIXME: or just check for hoverHeight? Flying = FLY_HOVER; } } } - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - { - if ( pm->ps->clientNum == 0 && !player_locked && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<value); - } - else if ( g_entities[pm->ps->clientNum].client - && (pm->ps->forcePowersActive&(1<ps->forcePowersActive&(1<value); + if (g_timescale != NULL) { + if (g_timescale->value < 1.0f) { + if (!MatrixMode) { + if (pm->ps->clientNum == 0 && !player_locked && (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { + pml.frametime *= (1.0f / g_timescale->value); + } else if (g_entities[pm->ps->clientNum].client && + (pm->ps->forcePowersActive & (1 << FP_SPEED) || pm->ps->forcePowersActive & (1 << FP_RAGE))) { + pml.frametime *= (1.0f / g_timescale->value); } } } } } -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp //------------------------------------------- -void PM_AdjustAttackStates( pmove_t *pm ) +void PM_AdjustAttackStates(pmove_t *pm) //------------------------------------------- { int amount; - if ( !g_saberAutoBlocking->integer - && !g_saberNewControlScheme->integer - && (pm->cmd.buttons&BUTTON_FORCE_FOCUS) ) - { + if (!g_saberAutoBlocking->integer && !g_saberNewControlScheme->integer && (pm->cmd.buttons & BUTTON_FORCE_FOCUS)) { pm->ps->saberBlockingTime = pm->cmd.serverTime + 100; pm->cmd.buttons &= ~BUTTON_ATTACK; pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } // get ammo usage - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; - } - else - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - weaponData[pm->ps->weapon].energyPerShot; + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; + } else { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].energyPerShot; } - if ( pm->ps->weapon == WP_SABER && (!cg.zoomMode||pm->ps->clientNum) ) - {//don't let the alt-attack be interpreted as an actual attack command - if ( pm->ps->saberInFlight ) - { + if (pm->ps->weapon == WP_SABER && (!cg.zoomMode || pm->ps->clientNum)) { // don't let the alt-attack be interpreted as an actual attack command + if (pm->ps->saberInFlight) { pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; - //FIXME: what about alt-attack modifier button? - if ( (!pm->ps->dualSabers || !pm->ps->saber[1].Active()) ) - {//saber not in hand, can't swing it + // FIXME: what about alt-attack modifier button? + if ((!pm->ps->dualSabers || !pm->ps->saber[1].Active())) { // saber not in hand, can't swing it pm->cmd.buttons &= ~BUTTON_ATTACK; } } - //saber staff alt-attack does a special attack anim, non-throwable sabers do kicks - if ( pm->ps->saberAnimLevel != SS_STAFF - && !(pm->ps->saber[0].saberFlags&SFL_NOT_THROWABLE) ) - {//using a throwable saber, so remove the saber throw button - if ( !g_saberNewControlScheme->integer - && PM_CanDoKata() ) - {//old control scheme - alt-attack + attack does kata - } - else - {//new control scheme - alt-attack doesn't have anything to do with katas, safe to clear it here + // saber staff alt-attack does a special attack anim, non-throwable sabers do kicks + if (pm->ps->saberAnimLevel != SS_STAFF && + !(pm->ps->saber[0].saberFlags & SFL_NOT_THROWABLE)) { // using a throwable saber, so remove the saber throw button + if (!g_saberNewControlScheme->integer && PM_CanDoKata()) { // old control scheme - alt-attack + attack does kata + } else { // new control scheme - alt-attack doesn't have anything to do with katas, safe to clear it here pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } } } // disruptor alt-fire should toggle the zoom mode, but only bother doing this for the player? - if ( pm->ps->weapon == WP_DISRUPTOR && pm->gent && (pm->gent->s.numbergent)) && pm->ps->weaponstate != WEAPON_DROPPING ) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->gent && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent)) && + pm->ps->weaponstate != WEAPON_DROPPING) { // we are not alt-firing yet, but the alt-attack button was just pressed and // we either are ducking ( in which case we don't care if they are moving )...or they are not ducking...and also not moving right/forward. - if ( !(pm->ps->eFlags & EF_ALT_FIRING) && (pm->cmd.buttons & BUTTON_ALT_ATTACK) - && ( pm->cmd.upmove < 0 || ( !pm->cmd.forwardmove && !pm->cmd.rightmove ))) - { + if (!(pm->ps->eFlags & EF_ALT_FIRING) && (pm->cmd.buttons & BUTTON_ALT_ATTACK) && + (pm->cmd.upmove < 0 || (!pm->cmd.forwardmove && !pm->cmd.rightmove))) { // We just pressed the alt-fire key - if ( cg.zoomMode == 0 || cg.zoomMode == 3 ) - { - G_SoundOnEnt( pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomstart.wav" ); + if (cg.zoomMode == 0 || cg.zoomMode == 3) { + G_SoundOnEnt(pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomstart.wav"); // not already zooming, so do it now cg.zoomMode = 2; cg.zoomLocked = qfalse; - cg_zoomFov = 80.0f;//(cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - } - else if ( cg.zoomMode == 2 ) - { - G_SoundOnEnt( pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomend.wav" ); + cg_zoomFov = 80.0f; //(cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + } else if (cg.zoomMode == 2) { + G_SoundOnEnt(pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomend.wav"); // already zooming, so must be wanting to turn it off cg.zoomMode = 0; cg.zoomTime = cg.time; cg.zoomLocked = qfalse; } - } - else if ( !(pm->cmd.buttons & BUTTON_ALT_ATTACK )) - { + } else if (!(pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // Not pressing zoom any more - if ( cg.zoomMode == 2 ) - { + if (cg.zoomMode == 2) { // were zooming in, so now lock the zoom cg.zoomLocked = qtrue; } } - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { // If we are zoomed, we should switch the ammo usage to the alt-fire, otherwise, we'll // just use whatever ammo was selected from above - if ( cg.zoomMode == 2 ) - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - - weaponData[pm->ps->weapon].altEnergyPerShot; + if (cg.zoomMode == 2) { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; } - } - else - { + } else { // alt-fire button pressing doesn't use any ammo amount = 0; } - } // Check for binocular specific mode - if ( cg.zoomMode == 1 && pm->gent && (pm->gent->s.numbergent)) ) // + if (cg.zoomMode == 1 && pm->gent && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent))) // { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->ps->batteryCharge ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->ps->batteryCharge) { // zooming out cg.zoomLocked = qfalse; cg.zoomDir = 1; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK && pm->ps->batteryCharge ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK && pm->ps->batteryCharge) { // zooming in cg.zoomLocked = qfalse; cg.zoomDir = -1; - } - else - { + } else { // if no buttons are down, we should be in a locked state cg.zoomLocked = qtrue; } @@ -14532,35 +11560,27 @@ void PM_AdjustAttackStates( pmove_t *pm ) // kill buttons and associated firing flags so we can't fire pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; - pm->cmd.buttons &= ~(BUTTON_ALT_ATTACK|BUTTON_ATTACK); + pm->cmd.buttons &= ~(BUTTON_ALT_ATTACK | BUTTON_ATTACK); } // set the firing flag for continuous beam weapons, phaser will fire even if out of ammo - if ( (( pm->cmd.buttons & BUTTON_ATTACK || pm->cmd.buttons & BUTTON_ALT_ATTACK ) && ( amount >= 0 || pm->ps->weapon == WP_SABER )) ) - { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (((pm->cmd.buttons & BUTTON_ATTACK || pm->cmd.buttons & BUTTON_ALT_ATTACK) && (amount >= 0 || pm->ps->weapon == WP_SABER))) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { pm->ps->eFlags |= EF_ALT_FIRING; - if ( pm->ps->clientNum < MAX_CLIENTS && pm->gent && (pm->ps->eFlags&EF_IN_ATST) ) - {//switch ATST barrels + if (pm->ps->clientNum < MAX_CLIENTS && pm->gent && (pm->ps->eFlags & EF_IN_ATST)) { // switch ATST barrels pm->gent->alt_fire = qtrue; } - } - else - { + } else { pm->ps->eFlags &= ~EF_ALT_FIRING; - if ( pm->ps->clientNum < MAX_CLIENTS && pm->gent && (pm->ps->eFlags&EF_IN_ATST) ) - {//switch ATST barrels + if (pm->ps->clientNum < MAX_CLIENTS && pm->gent && (pm->ps->eFlags & EF_IN_ATST)) { // switch ATST barrels pm->gent->alt_fire = qfalse; } } // This flag should always get set, even when alt-firing pm->ps->eFlags |= EF_FIRING; - } - else - { -// int iFlags = pm->ps->eFlags; + } else { + // int iFlags = pm->ps->eFlags; // Clear 'em out pm->ps->eFlags &= ~EF_FIRING; @@ -14570,36 +11590,30 @@ void PM_AdjustAttackStates( pmove_t *pm ) // the stronger FFFX so you can hardly feel them. However, if you only do iton these flags then the // repeat-fire weapons like tetrion and dreadnought don't switch off quick enough. So... // -/* // Might need this for beam type weapons - if ( pm->ps->weapon == WP_DREADNOUGHT || (iFlags & (EF_FIRING|EF_ALT_FIRING) ) - { - cgi_FF_StopAllFX(); - } - */ + /* // Might need this for beam type weapons + if ( pm->ps->weapon == WP_DREADNOUGHT || (iFlags & (EF_FIRING|EF_ALT_FIRING) ) + { + cgi_FF_StopAllFX(); + } + */ } // disruptor should convert a main fire to an alt-fire if the gun is currently zoomed - if ( pm->ps->weapon == WP_DISRUPTOR && pm->gent && (pm->gent->s.numbergent)) ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK && cg.zoomMode == 2 ) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->gent && (pm->gent->s.number < MAX_CLIENTS || G_ControlledByPlayer(pm->gent))) { + if (pm->cmd.buttons & BUTTON_ATTACK && cg.zoomMode == 2) { // converting the main fire to an alt-fire pm->cmd.buttons |= BUTTON_ALT_ATTACK; pm->ps->eFlags |= EF_ALT_FIRING; - } - else - { + } else { // don't let an alt-fire through pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } } } -qboolean PM_WeaponOkOnVehicle( int weapon ) -{ - //FIXME: check g_vehicleInfo for our vehicle? - switch ( weapon ) - { +qboolean PM_WeaponOkOnVehicle(int weapon) { + // FIXME: check g_vehicleInfo for our vehicle? + switch (weapon) { case WP_NONE: case WP_SABER: case WP_BLASTER: @@ -14610,26 +11624,23 @@ qboolean PM_WeaponOkOnVehicle( int weapon ) return qfalse; } -void PM_CheckInVehicleSaberAttackAnim( void ) -{//A bit of a hack, but makes the vehicle saber attacks act like any other saber attack... +void PM_CheckInVehicleSaberAttackAnim(void) { // A bit of a hack, but makes the vehicle saber attacks act like any other saber attack... // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } PM_CheckClearSaberBlock(); -/* if ( PM_SaberBlocking() ) - {//busy blocking, don't do attacks - return; - } -*/ + /* if ( PM_SaberBlocking() ) + {//busy blocking, don't do attacks + return; + } + */ saberMoveName_t saberMove = LS_INVALID; - switch ( pm->ps->torsoAnim ) - { + switch (pm->ps->torsoAnim) { case BOTH_VS_ATR_S: saberMove = LS_SWOOP_ATTACK_RIGHT; break; @@ -14643,33 +11654,25 @@ void PM_CheckInVehicleSaberAttackAnim( void ) saberMove = LS_TAUNTAUN_ATTACK_LEFT; break; } - if ( saberMove != LS_INVALID ) - { - if ( pm->ps->saberMove == saberMove ) - {//already playing it - if ( !pm->ps->torsoAnimTimer ) - {//anim was done, set it back to ready - PM_SetSaberMove( LS_READY ); + if (saberMove != LS_INVALID) { + if (pm->ps->saberMove == saberMove) { // already playing it + if (!pm->ps->torsoAnimTimer) { // anim was done, set it back to ready + PM_SetSaberMove(LS_READY); pm->ps->saberMove = LS_READY; pm->ps->weaponstate = WEAPON_IDLE; - if (pm->cmd.buttons&BUTTON_ATTACK) - { - if ( !pm->ps->weaponTime ) - { - PM_SetSaberMove( saberMove ); + if (pm->cmd.buttons & BUTTON_ATTACK) { + if (!pm->ps->weaponTime) { + PM_SetSaberMove(saberMove); pm->ps->weaponstate = WEAPON_FIRING; pm->ps->weaponTime = pm->ps->torsoAnimTimer; } } } - } - else if ( pm->ps->torsoAnimTimer - && !pm->ps->weaponTime ) - { - PM_SetSaberMove( LS_READY ); + } else if (pm->ps->torsoAnimTimer && !pm->ps->weaponTime) { + PM_SetSaberMove(LS_READY); pm->ps->saberMove = LS_READY; pm->ps->weaponstate = WEAPON_IDLE; - PM_SetSaberMove( saberMove ); + PM_SetSaberMove(saberMove); pm->ps->weaponstate = WEAPON_FIRING; pm->ps->weaponTime = pm->ps->torsoAnimTimer; } @@ -14677,20 +11680,17 @@ void PM_CheckInVehicleSaberAttackAnim( void ) pm->ps->saberBlocking = saberMoveData[pm->ps->saberMove].blocking; } -//force the vehicle to turn and travel to its forced destination point -void PM_VehForcedTurning( gentity_t *veh ) -{ +// force the vehicle to turn and travel to its forced destination point +void PM_VehForcedTurning(gentity_t *veh) { gentity_t *dst = &g_entities[pm->ps->vehTurnaroundIndex]; float pitchD, yawD; vec3_t dir; - if (!veh || !veh->m_pVehicle) - { + if (!veh || !veh->m_pVehicle) { return; } - if (!dst) - { //can't find dest ent? + if (!dst) { // can't find dest ent? return; } @@ -14704,13 +11704,13 @@ void PM_VehForcedTurning( gentity_t *veh ) yawD = AngleSubtract(pm->ps->viewangles[YAW], dir[YAW]); pitchD = AngleSubtract(pm->ps->viewangles[PITCH], dir[PITCH]); - yawD *= 0.2f*pml.frametime; - pitchD *= 0.6f*pml.frametime; + yawD *= 0.2f * pml.frametime; + pitchD *= 0.6f * pml.frametime; pm->ps->viewangles[YAW] = AngleSubtract(pm->ps->viewangles[YAW], yawD); pm->ps->viewangles[PITCH] = AngleSubtract(pm->ps->viewangles[PITCH], pitchD); - //PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); + // PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); SetClientViewAngle(pm->gent, pm->ps->viewangles); } /* @@ -14720,8 +11720,7 @@ Pmove Can be called by either the server or the client ================ */ -void Pmove( pmove_t *pmove ) -{ +void Pmove(pmove_t *pmove) { Vehicle_t *pVeh = NULL; pm = pmove; @@ -14735,133 +11734,117 @@ void Pmove( pmove_t *pmove ) pm->waterlevel = 0; // Clear the blocked flag - //pm->ps->pm_flags &= ~PMF_BLOCKED; + // pm->ps->pm_flags &= ~PMF_BLOCKED; pm->ps->pm_flags &= ~PMF_BUMPED; // In certain situations, we may want to control which attack buttons are pressed and what kind of functionality // is attached to them - PM_AdjustAttackStates( pm ); + PM_AdjustAttackStates(pm); // clear the respawned flag if attack and use are cleared - if ( pm->ps->stats[STAT_HEALTH] > 0 && - !( pm->cmd.buttons & BUTTON_ATTACK ) ) - { + if (pm->ps->stats[STAT_HEALTH] > 0 && !(pm->cmd.buttons & BUTTON_ATTACK)) { pm->ps->pm_flags &= ~PMF_RESPAWNED; } // clear all pmove local vars - memset (&pml, 0, sizeof(pml)); + memset(&pml, 0, sizeof(pml)); // determine the time pml.msec = pmove->cmd.serverTime - pm->ps->commandTime; - if ( pml.msec < 1 ) { + if (pml.msec < 1) { pml.msec = 1; - } else if ( pml.msec > 200 ) { + } else if (pml.msec > 200) { pml.msec = 200; } pm->ps->commandTime = pmove->cmd.serverTime; // save old org in case we get stuck - VectorCopy (pm->ps->origin, pml.previous_origin); + VectorCopy(pm->ps->origin, pml.previous_origin); // save old velocity for crashlanding - VectorCopy (pm->ps->velocity, pml.previous_velocity); + VectorCopy(pm->ps->velocity, pml.previous_velocity); pml.frametime = pml.msec * 0.001; - if ( pm->ps->clientNum >= MAX_CLIENTS && - pm->gent && - pm->gent->client && - pm->gent->client->NPC_class == CLASS_VEHICLE ) - { //we are a vehicle + if (pm->ps->clientNum >= MAX_CLIENTS && pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { // we are a vehicle pVeh = pm->gent->m_pVehicle; - assert( pVeh ); - if ( pVeh ) - { - pVeh->m_fTimeModifier = (pml.frametime*60.0f);//at 16.67ms (60fps), should be 1.0f + assert(pVeh); + if (pVeh) { + pVeh->m_fTimeModifier = (pml.frametime * 60.0f); // at 16.67ms (60fps), should be 1.0f } - } - else if ( pm->gent && PM_RidingVehicle() ) - { - if ( pm->ps->vehTurnaroundIndex - && pm->ps->vehTurnaroundTime > pm->cmd.serverTime ) - { //riding this vehicle, turn my view too - PM_VehForcedTurning( &g_entities[pm->gent->s.m_iVehicleNum] ); + } else if (pm->gent && PM_RidingVehicle()) { + if (pm->ps->vehTurnaroundIndex && pm->ps->vehTurnaroundTime > pm->cmd.serverTime) { // riding this vehicle, turn my view too + PM_VehForcedTurning(&g_entities[pm->gent->s.m_iVehicleNum]); } } PM_SetSpecialMoveValues(); // update the viewangles - PM_UpdateViewAngles( pm->ps, &pm->cmd, pm->gent); + PM_UpdateViewAngles(pm->ps, &pm->cmd, pm->gent); - AngleVectors ( pm->ps->viewangles, pml.forward, pml.right, pml.up ); + AngleVectors(pm->ps->viewangles, pml.forward, pml.right, pml.up); - if ( pm->cmd.upmove < 10 ) { + if (pm->cmd.upmove < 10) { // not holding jump pm->ps->pm_flags &= ~PMF_JUMP_HELD; } // decide if backpedaling animations should be used - if ( pm->cmd.forwardmove < 0 ) { + if (pm->cmd.forwardmove < 0) { pm->ps->pm_flags |= PMF_BACKWARDS_RUN; - } else if ( pm->cmd.forwardmove > 0 || ( pm->cmd.forwardmove == 0 && pm->cmd.rightmove ) ) { + } else if (pm->cmd.forwardmove > 0 || (pm->cmd.forwardmove == 0 && pm->cmd.rightmove)) { pm->ps->pm_flags &= ~PMF_BACKWARDS_RUN; } - if ( pm->ps->pm_type >= PM_DEAD ) { + if (pm->ps->pm_type >= PM_DEAD) { pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; pm->cmd.upmove = 0; - if ( pm->ps->viewheight > -12 ) - {//slowly sink view to ground + if (pm->ps->viewheight > -12) { // slowly sink view to ground pm->ps->viewheight -= 1; } } - if ( pm->ps->pm_type == PM_SPECTATOR ) { - PM_CheckDuck (); - PM_FlyMove (); - PM_DropTimers (); + if (pm->ps->pm_type == PM_SPECTATOR) { + PM_CheckDuck(); + PM_FlyMove(); + PM_DropTimers(); return; } - if ( pm->ps->pm_type == PM_NOCLIP ) { - PM_NoclipMove (); - PM_DropTimers (); + if (pm->ps->pm_type == PM_NOCLIP) { + PM_NoclipMove(); + PM_DropTimers(); return; } if (pm->ps->pm_type == PM_FREEZE) { - return; // no movement at all + return; // no movement at all } - if ( pm->ps->pm_type == PM_INTERMISSION ) { - return; // no movement at all + if (pm->ps->pm_type == PM_INTERMISSION) { + return; // no movement at all } - if ( pm->ps->pm_flags & PMF_SLOW_MO_FALL ) - {//half grav + if (pm->ps->pm_flags & PMF_SLOW_MO_FALL) { // half grav pm->ps->gravity *= 0.5; } // set watertype, and waterlevel - PM_SetWaterLevelAtPoint( pm->ps->origin, &pm->waterlevel, &pm->watertype ); + PM_SetWaterLevelAtPoint(pm->ps->origin, &pm->waterlevel, &pm->watertype); PM_SetWaterHeight(); - if ( !(pm->watertype & CONTENTS_LADDER) ) - {//Don't want to remember this for ladders, is only for waterlevel change events (sounds) + if (!(pm->watertype & CONTENTS_LADDER)) { // Don't want to remember this for ladders, is only for waterlevel change events (sounds) pml.previous_waterlevel = pmove->waterlevel; } - waterForceJump = qfalse; - if ( pmove->waterlevel && pm->ps->clientNum ) - { - if ( pm->ps->forceJumpZStart//force jumping - ||(pm->gent&&pm->gent->NPC && level.timegent->NPC->jumpTime)) //TIMER_Done(pm->gent, "forceJumpChasing" )) )//force-jumping + if (pmove->waterlevel && pm->ps->clientNum) { + if (pm->ps->forceJumpZStart // force jumping + || (pm->gent && pm->gent->NPC && level.time < pm->gent->NPC->jumpTime)) // TIMER_Done(pm->gent, "forceJumpChasing" )) )//force-jumping { waterForceJump = qtrue; } @@ -14870,20 +11853,18 @@ void Pmove( pmove_t *pmove ) // set mins, maxs, and viewheight PM_SetBounds(); - if ( !Flying && !(pm->watertype & CONTENTS_LADDER) && pm->ps->pm_type != PM_DEAD ) - {//NOTE: noclippers shouldn't jump or duck either, no? + if (!Flying && !(pm->watertype & CONTENTS_LADDER) && pm->ps->pm_type != PM_DEAD) { // NOTE: noclippers shouldn't jump or duck either, no? PM_CheckDuck(); } // set groundentity PM_GroundTrace(); - if ( Flying == FLY_HOVER ) - {//never stick to the ground + if (Flying == FLY_HOVER) { // never stick to the ground PM_HoverTrace(); } - if ( pm->ps->pm_type == PM_DEAD ) { - PM_DeadMove (); + if (pm->ps->pm_type == PM_DEAD) { + PM_DeadMove(); } PM_DropTimers(); @@ -14893,34 +11874,24 @@ void Pmove( pmove_t *pmove ) { PM_NoclipMove(); } - else */if ( pm->ps && ( (pm->ps->eFlags&EF_LOCKED_TO_WEAPON) - || (pm->ps->eFlags&EF_HELD_BY_RANCOR) - || (pm->ps->eFlags&EF_HELD_BY_WAMPA) - || (pm->ps->eFlags&EF_HELD_BY_SAND_CREATURE) ) ) - {//in an emplaced gun + else */ + if (pm->ps && ((pm->ps->eFlags & EF_LOCKED_TO_WEAPON) || (pm->ps->eFlags & EF_HELD_BY_RANCOR) || (pm->ps->eFlags & EF_HELD_BY_WAMPA) || + (pm->ps->eFlags & EF_HELD_BY_SAND_CREATURE))) { // in an emplaced gun PM_NoclipMove(); - } - else if ( Flying == FLY_NORMAL )//|| pm->ps->gravity <= 0 ) + } else if (Flying == FLY_NORMAL) //|| pm->ps->gravity <= 0 ) { // flight powerup doesn't allow jump and has different friction PM_FlyMove(); - } - else if ( Flying == FLY_VEHICLE ) - { + } else if (Flying == FLY_VEHICLE) { PM_FlyVehicleMove(); - } - else if ( pm->ps->pm_flags & PMF_TIME_WATERJUMP ) - { + } else if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { PM_WaterJumpMove(); - } - else if ( pm->waterlevel > 1 //in water - &&((pm->ps->clientNum < MAX_CLIENTS||PM_ControlledByPlayer()) || !waterForceJump) )//player or NPC not force jumping - {//force-jumping NPCs should + } else if (pm->waterlevel > 1 // in water + && ((pm->ps->clientNum < MAX_CLIENTS || PM_ControlledByPlayer()) || !waterForceJump)) // player or NPC not force jumping + { // force-jumping NPCs should // swimming or in ladder PM_WaterMove(); - } - else if (pm->gent && pm->gent->NPC && pm->gent->NPC->jumpTime!=0) - { + } else if (pm->gent && pm->gent->NPC && pm->gent->NPC->jumpTime != 0) { ucmd.forwardmove = 0; ucmd.rightmove = 0; ucmd.upmove = 0; @@ -14928,54 +11899,41 @@ void Pmove( pmove_t *pmove ) VectorClear(pm->ps->moveDir); PM_AirMove(); - } - else if ( pml.walking ) - {// walking on ground - vec3_t oldOrg; + } else if (pml.walking) { // walking on ground + vec3_t oldOrg; - VectorCopy( pm->ps->origin, oldOrg ); + VectorCopy(pm->ps->origin, oldOrg); PM_WalkMove(); - - float threshHold = 0.001f, movedDist = DistanceSquared( oldOrg, pm->ps->origin ); - if ( PM_StandingAnim( pm->ps->legsAnim ) || pm->ps->legsAnim == BOTH_CROUCH1 ) - { + float threshHold = 0.001f, movedDist = DistanceSquared(oldOrg, pm->ps->origin); + if (PM_StandingAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_CROUCH1) { threshHold = 0.005f; } - if ( movedDist < threshHold ) - {//didn't move, play no legs anim - // pm->cmd.forwardmove = pm->cmd.rightmove = 0; + if (movedDist < threshHold) { // didn't move, play no legs anim + // pm->cmd.forwardmove = pm->cmd.rightmove = 0; } - } - else - { - if ( pm->ps->gravity <= 0 ) - { + } else { + if (pm->ps->gravity <= 0) { PM_FlyMove(); - } - else - { + } else { // airborne PM_AirMove(); } } - //PM_Animate(); + // PM_Animate(); // If we didn't move at all, then why bother doing this again -MW. - if(!(VectorCompare(pm->ps->origin,pml.previous_origin))) - { + if (!(VectorCompare(pm->ps->origin, pml.previous_origin))) { PM_GroundTrace(); - if ( Flying == FLY_HOVER ) - {//never stick to the ground + if (Flying == FLY_HOVER) { // never stick to the ground PM_HoverTrace(); } } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on ground + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on ground pm->ps->forceJumpZStart = 0; pm->ps->jumpZStart = 0; pm->ps->pm_flags &= ~PMF_JUMPING; @@ -14985,80 +11943,65 @@ void Pmove( pmove_t *pmove ) // If we didn't move at all, then why bother doing this again -MW. // Note: ok, so long as we don't have water levels that change. - if(!(VectorCompare(pm->ps->origin,pml.previous_origin))) - { - PM_SetWaterLevelAtPoint( pm->ps->origin, &pm->waterlevel, &pm->watertype ); + if (!(VectorCompare(pm->ps->origin, pml.previous_origin))) { + PM_SetWaterLevelAtPoint(pm->ps->origin, &pm->waterlevel, &pm->watertype); PM_SetWaterHeight(); } -// PM_ForcePower(); sends event to client for client side fx, not used + // PM_ForcePower(); sends event to client for client side fx, not used // If we're a vehicle, do our special weapon function. - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE ) - { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE) { pVeh = pm->gent->m_pVehicle; // Using vehicle weapon... - //if ( pm->cmd.weapon == WP_NONE ) + // if ( pm->cmd.weapon == WP_NONE ) { - //PM_Weapon(); - //PM_AddEvent( EV_FIRE_WEAPON ); + // PM_Weapon(); + // PM_AddEvent( EV_FIRE_WEAPON ); PM_VehicleWeapon(); } } // If we are riding a vehicle... - else if ( PM_RidingVehicle() ) - { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - {// alt attack always does other stuff when riding a vehicle (turbo) - } - else if ( (pm->ps->eFlags&EF_NODRAW) ) - {//inside a vehicle? don't do any weapon stuff - } - else if ( pm->ps->weapon == WP_BLASTER//using blaster - || pm->ps->weapon == WP_THERMAL//using thermal - || pm->ps->weaponstate == WEAPON_DROPPING//changing weapon - dropping - || pm->ps->weaponstate == WEAPON_RAISING//changing weapon - raising - || (pm->cmd.weapon != pm->ps->weapon && PM_WeaponOkOnVehicle( pm->cmd.weapon )) )//FIXME: make this a vehicle call to see if this new weapon is valid for this vehicle - {//either weilding a weapon we can fire with normal weapon logic, or trying to change to a valid weapon - // call normal weapons code... should we override the normal fire anims with vehicle fire anims in here or in a subsequent call to VehicleWeapons or something? - //Maybe break PM_Weapon into PM_Weapon and PM_WeaponAnimate (then call our own PM_VehicleWeaponAnimate)? + else if (PM_RidingVehicle()) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // alt attack always does other stuff when riding a vehicle (turbo) + } else if ((pm->ps->eFlags & EF_NODRAW)) { // inside a vehicle? don't do any weapon stuff + } else if (pm->ps->weapon == WP_BLASTER // using blaster + || pm->ps->weapon == WP_THERMAL // using thermal + || pm->ps->weaponstate == WEAPON_DROPPING // changing weapon - dropping + || pm->ps->weaponstate == WEAPON_RAISING // changing weapon - raising + || (pm->cmd.weapon != pm->ps->weapon && + PM_WeaponOkOnVehicle(pm->cmd.weapon))) // FIXME: make this a vehicle call to see if this new weapon is valid for this vehicle + { // either weilding a weapon we can fire with normal weapon logic, or trying to change to a valid weapon + // call normal weapons code... should we override the normal fire anims with vehicle fire anims in here or in a subsequent call to VehicleWeapons or + // something? + // Maybe break PM_Weapon into PM_Weapon and PM_WeaponAnimate (then call our own PM_VehicleWeaponAnimate)? PM_Weapon(); } - //BUT: now call Vehicle's weapon code, to handle lightsaber and (maybe) overriding weapon ready/firing anims? + // BUT: now call Vehicle's weapon code, to handle lightsaber and (maybe) overriding weapon ready/firing anims? } // otherwise do the normal weapon function. - else - { + else { // weapons PM_Weapon(); } - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { pm->ps->pm_flags |= PMF_ATTACK_HELD; - } - else - { + } else { pm->ps->pm_flags &= ~PMF_ATTACK_HELD; } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { pm->ps->pm_flags |= PMF_ALT_ATTACK_HELD; - } - else - { + } else { pm->ps->pm_flags &= ~PMF_ALT_ATTACK_HELD; } - if ( pm->cmd.buttons & BUTTON_FORCE_FOCUS ) - { + if (pm->cmd.buttons & BUTTON_FORCE_FOCUS) { pm->ps->pm_flags |= PMF_FORCE_FOCUS_HELD; - } - else - { + } else { pm->ps->pm_flags &= ~PMF_FORCE_FOCUS_HELD; } - if ( pm->gent )//&& pm->gent->s.number == 0 )//player only? + if (pm->gent) //&& pm->gent->s.number == 0 )//player only? { // Use PM_Use(); @@ -15066,60 +12009,47 @@ void Pmove( pmove_t *pmove ) // Calculate the resulting speed of the last pmove //------------------------------------------------- - if ( pm->gent ) - { + if (pm->gent) { pm->gent->resultspeed = ((Distance(pm->ps->origin, pm->gent->currentOrigin) / pml.msec) * 1000); - if (pm->gent->resultspeed>5.0f) - { + if (pm->gent->resultspeed > 5.0f) { pm->gent->lastMoveTime = level.time; } // If Have Not Been Moving For A While, Stop //------------------------------------------- - if (pml.walking && (level.time - pm->gent->lastMoveTime)>1000) - { + if (pml.walking && (level.time - pm->gent->lastMoveTime) > 1000) { pm->cmd.forwardmove = pm->cmd.rightmove = 0; } } - // ANIMATION //================================ // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP - if ( pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - { - if ( pm->gent->owner && pm->gent->owner->e_UseFunc == useF_emplaced_gun_use )//ugly way to tell, but... - {//full body - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - } - else - {//stand (or could be overridden by strafe anims) - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { + if (pm->gent->owner && pm->gent->owner->e_UseFunc == useF_emplaced_gun_use) // ugly way to tell, but... + { // full body + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + } else { // stand (or could be overridden by strafe anims) + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->gent && pm->ps && (pm->ps->eFlags&EF_HELD_BY_RANCOR) ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIM_IDLE1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL + } else if (pm->gent && pm->ps && (pm->ps->eFlags & EF_HELD_BY_RANCOR)) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL } // If we are a vehicle, animate... - else if ( pVeh ) - { - pVeh->m_pVehicleInfo->Animate( pVeh ); + else if (pVeh) { + pVeh->m_pVehicleInfo->Animate(pVeh); } // If we're riding a vehicle, don't do anything!. - else if ( ( pVeh = PM_RidingVehicle() ) != 0 ) - { + else if ((pVeh = PM_RidingVehicle()) != 0) { PM_CheckInVehicleSaberAttackAnim(); - } - else // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP + } else // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP { // footstep events / legs animations PM_Footsteps(); } // torso animation - if ( !pVeh ) - {//not riding a vehicle + if (!pVeh) { // not riding a vehicle PM_TorsoAnimation(); } @@ -15129,16 +12059,13 @@ void Pmove( pmove_t *pmove ) // snap some parts of playerstate to save network bandwidth // SnapVector( pm->ps->velocity ); - if ( !pm->cmd.rightmove && !pm->cmd.forwardmove && pm->cmd.upmove <= 0 ) - { - if ( VectorCompare( pm->ps->velocity, vec3_origin ) ) - { + if (!pm->cmd.rightmove && !pm->cmd.forwardmove && pm->cmd.upmove <= 0) { + if (VectorCompare(pm->ps->velocity, vec3_origin)) { pm->ps->lastStationary = level.time; } } - if ( pm->ps->pm_flags & PMF_SLOW_MO_FALL ) - {//half grav + if (pm->ps->pm_flags & PMF_SLOW_MO_FALL) { // half grav pm->ps->gravity *= 2; } } diff --git a/code/game/bg_slidemove.cpp b/code/game/bg_slidemove.cpp index 52d1fb4e0f..828d91dba4 100644 --- a/code/game/bg_slidemove.cpp +++ b/code/game/bg_slidemove.cpp @@ -28,9 +28,9 @@ along with this program; if not, see . #include "bg_local.h" #include "g_vehicles.h" -extern qboolean PM_ClientImpact( trace_t *trace, qboolean damageSelf ); -extern qboolean PM_ControlledByPlayer( void ); -extern qboolean PM_InReboundHold( int anim ); +extern qboolean PM_ClientImpact(trace_t *trace, qboolean damageSelf); +extern qboolean PM_ControlledByPlayer(void); +extern qboolean PM_InReboundHold(int anim); extern cvar_t *g_stepSlideFix; /* @@ -48,46 +48,42 @@ PM_SlideMove Returns qtrue if the velocity was clipped in some way ================== */ -#define MAX_CLIP_PLANES 5 -extern qboolean PM_GroundSlideOkay( float zNormal ); -extern qboolean PM_InSpecialJump( int anim ); -qboolean PM_SlideMove( float gravMod ) { - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t normal, planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity; - vec3_t clipVelocity; - int i, j, k; - trace_t trace; - vec3_t end; - float time_left; - float into; - vec3_t endVelocity; - vec3_t endClipVelocity; - qboolean damageSelf = qtrue; - int slideMoveContents = pm->tracemask; - - if ( pm->ps->clientNum >= MAX_CLIENTS - && !PM_ControlledByPlayer() ) - {//a non-player client, not an NPC under player control - if ( pml.walking //walking on the ground - || (pm->ps->groundEntityNum != ENTITYNUM_NONE //in air - && PM_InSpecialJump( pm->ps->legsAnim )//in a special jump - && !(pm->ps->eFlags&EF_FORCE_GRIPPED)//not being gripped - && !(pm->ps->pm_flags&PMF_TIME_KNOCKBACK) - && pm->gent - && pm->gent->forcePushTime < level.time) )//not being pushed - {// +#define MAX_CLIP_PLANES 5 +extern qboolean PM_GroundSlideOkay(float zNormal); +extern qboolean PM_InSpecialJump(int anim); +qboolean PM_SlideMove(float gravMod) { + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t normal, planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity; + vec3_t clipVelocity; + int i, j, k; + trace_t trace; + vec3_t end; + float time_left; + float into; + vec3_t endVelocity; + vec3_t endClipVelocity; + qboolean damageSelf = qtrue; + int slideMoveContents = pm->tracemask; + + if (pm->ps->clientNum >= MAX_CLIENTS && !PM_ControlledByPlayer()) { // a non-player client, not an NPC under player control + if (pml.walking // walking on the ground + || (pm->ps->groundEntityNum != ENTITYNUM_NONE // in air + && PM_InSpecialJump(pm->ps->legsAnim) // in a special jump + && !(pm->ps->eFlags & EF_FORCE_GRIPPED) // not being gripped + && !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && pm->gent && pm->gent->forcePushTime < level.time)) // not being pushed + { // // If we're a vehicle, ignore this if we're being driven - if ( !pm->gent //not an game ent - || !pm->gent->client //not a client - || pm->gent->client->NPC_class != CLASS_VEHICLE//not a vehicle - || !pm->gent->m_pVehicle //no vehicle - || !pm->gent->m_pVehicle->m_pPilot//no pilot - || pm->gent->m_pVehicle->m_pPilot->s.number >= MAX_CLIENTS )//pilot is not the player - {//then treat do not enter brushes as SOLID + if (!pm->gent // not an game ent + || !pm->gent->client // not a client + || pm->gent->client->NPC_class != CLASS_VEHICLE // not a vehicle + || !pm->gent->m_pVehicle // no vehicle + || !pm->gent->m_pVehicle->m_pPilot // no pilot + || pm->gent->m_pVehicle->m_pPilot->s.number >= MAX_CLIENTS) // pilot is not the player + { // then treat do not enter brushes as SOLID slideMoveContents |= CONTENTS_BOTCLIP; } } @@ -95,23 +91,18 @@ qboolean PM_SlideMove( float gravMod ) { numbumps = 4; - VectorCopy (pm->ps->velocity, primal_velocity); - VectorCopy (pm->ps->velocity, endVelocity); + VectorCopy(pm->ps->velocity, primal_velocity); + VectorCopy(pm->ps->velocity, endVelocity); - if ( gravMod ) - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) && !(pm->ps->eFlags&EF_FORCE_DRAINED) ) - { + if (gravMod) { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED) && !(pm->ps->eFlags & EF_FORCE_DRAINED)) { endVelocity[2] -= pm->ps->gravity * pml.frametime * gravMod; } - pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5; + pm->ps->velocity[2] = (pm->ps->velocity[2] + endVelocity[2]) * 0.5; primal_velocity[2] = endVelocity[2]; - if ( pml.groundPlane ) - { - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - {// slide along the ground plane - PM_ClipVelocity( pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { // slide along the ground plane + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } } @@ -119,109 +110,85 @@ qboolean PM_SlideMove( float gravMod ) { time_left = pml.frametime; // never turn against the ground plane - if ( pml.groundPlane ) - { + if (pml.groundPlane) { numplanes = 1; - VectorCopy( pml.groundTrace.plane.normal, planes[0] ); - if ( !PM_GroundSlideOkay( planes[0][2] ) ) - { + VectorCopy(pml.groundTrace.plane.normal, planes[0]); + if (!PM_GroundSlideOkay(planes[0][2])) { planes[0][2] = 0; - VectorNormalize( planes[0] ); + VectorNormalize(planes[0]); } - } - else - { + } else { numplanes = 0; } // never turn against original velocity - VectorNormalize2( pm->ps->velocity, planes[numplanes] ); + VectorNormalize2(pm->ps->velocity, planes[numplanes]); numplanes++; - for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) { + for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { // calculate position we are trying to move to - VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end ); + VectorMA(pm->ps->origin, time_left, pm->ps->velocity, end); // see if we can make it there - pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, slideMoveContents, (EG2_Collision)0, 0 ); - if ( (trace.contents&CONTENTS_BOTCLIP) - && (slideMoveContents&CONTENTS_BOTCLIP) ) - {//hit a do not enter brush - if ( trace.allsolid || trace.startsolid )//inside the botclip - {//crap, we're in a do not enter brush, take it out for the remainder of the traces and re-trace this one right now without it + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, slideMoveContents, (EG2_Collision)0, 0); + if ((trace.contents & CONTENTS_BOTCLIP) && (slideMoveContents & CONTENTS_BOTCLIP)) { // hit a do not enter brush + if (trace.allsolid || trace.startsolid) // inside the botclip + { // crap, we're in a do not enter brush, take it out for the remainder of the traces and re-trace this one right now without it slideMoveContents &= ~CONTENTS_BOTCLIP; - pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, slideMoveContents, (EG2_Collision)0, 0 ); - } - else if ( trace.plane.normal[2] > 0.0f ) - {//on top of a do not enter brush, it, just redo this one trace without it - pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, (slideMoveContents&~CONTENTS_BOTCLIP), (EG2_Collision)0, 0 ); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, slideMoveContents, (EG2_Collision)0, 0); + } else if (trace.plane.normal[2] > 0.0f) { // on top of a do not enter brush, it, just redo this one trace without it + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, (slideMoveContents & ~CONTENTS_BOTCLIP), (EG2_Collision)0, 0); } } - if ( trace.allsolid ) - {// entity is completely trapped in another solid - pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration + if (trace.allsolid) { // entity is completely trapped in another solid + pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration return qtrue; } - if ( trace.fraction > 0 ) - {// actually covered some distance - VectorCopy( trace.endpos, pm->ps->origin ); + if (trace.fraction > 0) { // actually covered some distance + VectorCopy(trace.endpos, pm->ps->origin); } - if ( trace.fraction == 1 ) - { - break; // moved the entire distance + if (trace.fraction == 1) { + break; // moved the entire distance } - - // save entity for contact - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); - //Hit it - if ( trace.surfaceFlags&SURF_NODAMAGE ) - { + // Hit it + if (trace.surfaceFlags & SURF_NODAMAGE) { damageSelf = qfalse; - } - else if ( trace.entityNum == ENTITYNUM_WORLD && trace.plane.normal[2] > 0.5f ) - {//if we land on the ground, let falling damage do it's thing itself, otherwise do impact damage + } else if (trace.entityNum == ENTITYNUM_WORLD && + trace.plane.normal[2] > 0.5f) { // if we land on the ground, let falling damage do it's thing itself, otherwise do impact damage damageSelf = qfalse; - } - else - { + } else { damageSelf = qtrue; } - if ( PM_ClientImpact( &trace, damageSelf ) ) - { + if (PM_ClientImpact(&trace, damageSelf)) { continue; } - if (pm->gent->client && - pm->gent->client->NPC_class == CLASS_VEHICLE && - trace.plane.normal[2]gent->m_pVehicle->m_pVehicleInfo->maxSlope - ) - { + if (pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && trace.plane.normal[2] < pm->gent->m_pVehicle->m_pVehicleInfo->maxSlope) { pm->ps->pm_flags |= PMF_BUMPED; } time_left -= time_left * trace.fraction; - if ( numplanes >= MAX_CLIP_PLANES ) - {// this shouldn't really happen - VectorClear( pm->ps->velocity ); + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen + VectorClear(pm->ps->velocity); return qtrue; } - VectorCopy( trace.plane.normal, normal ); + VectorCopy(trace.plane.normal, normal); - if ( !PM_GroundSlideOkay( normal[2] ) ) - {//wall-running - //never push up off a sloped wall + if (!PM_GroundSlideOkay(normal[2])) { // wall-running + // never push up off a sloped wall normal[2] = 0; - VectorNormalize( normal ); + VectorNormalize(normal); } // @@ -229,19 +196,18 @@ qboolean PM_SlideMove( float gravMod ) { // out along it, which fixes some epsilon issues with // non-axial planes // - if ( !(pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//no sliding if stuck to wall! - for ( i = 0 ; i < numplanes ; i++ ) { - if ( DotProduct( normal, planes[i] ) > 0.99 ) { - VectorAdd( normal, pm->ps->velocity, pm->ps->velocity ); + if (!(pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // no sliding if stuck to wall! + for (i = 0; i < numplanes; i++) { + if (DotProduct(normal, planes[i]) > 0.99) { + VectorAdd(normal, pm->ps->velocity, pm->ps->velocity); break; } } - if ( i < numplanes ) { + if (i < numplanes) { continue; } } - VectorCopy( normal, planes[numplanes] ); + VectorCopy(normal, planes[numplanes]); numplanes++; // @@ -249,84 +215,84 @@ qboolean PM_SlideMove( float gravMod ) { // // find a plane that it enters - for ( i = 0 ; i < numplanes ; i++ ) { - into = DotProduct( pm->ps->velocity, planes[i] ); - if ( into >= 0.1 ) { - continue; // move doesn't interact with the plane + for (i = 0; i < numplanes; i++) { + into = DotProduct(pm->ps->velocity, planes[i]); + if (into >= 0.1) { + continue; // move doesn't interact with the plane } // see how hard we are hitting things - if ( -into > pml.impactSpeed ) { + if (-into > pml.impactSpeed) { pml.impactSpeed = -into; } // slide along the plane - PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, planes[i], clipVelocity, OVERCLIP); // slide along the plane - PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(endVelocity, planes[i], endClipVelocity, OVERCLIP); // see if there is a second plane that the new move enters - for ( j = 0 ; j < numplanes ; j++ ) { - if ( j == i ) { + for (j = 0; j < numplanes; j++) { + if (j == i) { continue; } - if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[j]) >= 0.1) { + continue; // move doesn't interact with the plane } // try clipping the move to the plane - PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP ); - PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(clipVelocity, planes[j], clipVelocity, OVERCLIP); + PM_ClipVelocity(endClipVelocity, planes[j], endClipVelocity, OVERCLIP); // see if it goes back into the first clip plane - if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) { + if (DotProduct(clipVelocity, planes[i]) >= 0) { continue; } // slide the original velocity along the crease - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, pm->ps->velocity ); - VectorScale( dir, d, clipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, pm->ps->velocity); + VectorScale(dir, d, clipVelocity); - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, endVelocity ); - VectorScale( dir, d, endClipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, endVelocity); + VectorScale(dir, d, endClipVelocity); // see if there is a third plane the the new move enters - for ( k = 0 ; k < numplanes ; k++ ) { - if ( k == i || k == j ) { + for (k = 0; k < numplanes; k++) { + if (k == i || k == j) { continue; } - if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[k]) >= 0.1) { + continue; // move doesn't interact with the plane } // stop dead at a triple plane interaction - VectorClear( pm->ps->velocity ); + VectorClear(pm->ps->velocity); return qtrue; } } // if we have fixed all interactions, try another move - VectorCopy( clipVelocity, pm->ps->velocity ); - VectorCopy( endClipVelocity, endVelocity ); + VectorCopy(clipVelocity, pm->ps->velocity); + VectorCopy(endClipVelocity, endVelocity); break; } } - if ( gravMod ) { - VectorCopy( endVelocity, pm->ps->velocity ); + if (gravMod) { + VectorCopy(endVelocity, pm->ps->velocity); } // don't change velocity if in a timer (FIXME: is this correct?) - if ( pm->ps->pm_time ) { - VectorCopy( primal_velocity, pm->ps->velocity ); + if (pm->ps->pm_time) { + VectorCopy(primal_velocity, pm->ps->velocity); } - return (qboolean)( bumpcount != 0 ); + return (qboolean)(bumpcount != 0); } /* @@ -335,217 +301,168 @@ PM_StepSlideMove ================== */ -void PM_StepSlideMove( float gravMod ) -{ - vec3_t start_o, start_v; - vec3_t down_o, down_v; - vec3_t slideMove, stepUpMove; - trace_t trace; - vec3_t up, down; - qboolean /*cantStepUpFwd, */isGiant = qfalse;; - int stepSize = STEPSIZE; - - VectorCopy (pm->ps->origin, start_o); - VectorCopy (pm->ps->velocity, start_v); - - if ( PM_InReboundHold( pm->ps->legsAnim ) ) - { +void PM_StepSlideMove(float gravMod) { + vec3_t start_o, start_v; + vec3_t down_o, down_v; + vec3_t slideMove, stepUpMove; + trace_t trace; + vec3_t up, down; + qboolean /*cantStepUpFwd, */ isGiant = qfalse; + ; + int stepSize = STEPSIZE; + + VectorCopy(pm->ps->origin, start_o); + VectorCopy(pm->ps->velocity, start_v); + + if (PM_InReboundHold(pm->ps->legsAnim)) { gravMod = 0.0f; } - if ( PM_SlideMove( gravMod ) == 0 ) { - return; // we got exactly where we wanted to go first try - }//else Bumped into something, see if we can step over it + if (PM_SlideMove(gravMod) == 0) { + return; // we got exactly where we wanted to go first try + } // else Bumped into something, see if we can step over it - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0 ) - {//Hovering vehicles don't do steps - //FIXME: maybe make hovering vehicles go up steps, but not down them? + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_VEHICLE && + pm->gent->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) { // Hovering vehicles don't do steps + // FIXME: maybe make hovering vehicles go up steps, but not down them? return; } - if ( pm->gent - && pm->gent->client - && (pm->gent->client->NPC_class == CLASS_ATST||pm->gent->client->NPC_class == CLASS_RANCOR) ) - { + if (pm->gent && pm->gent->client && (pm->gent->client->NPC_class == CLASS_ATST || pm->gent->client->NPC_class == CLASS_RANCOR)) { isGiant = qtrue; - if ( pm->gent->client->NPC_class == CLASS_RANCOR ) - { - if ( (pm->gent->spawnflags&1) ) - { - stepSize = 64;//hack for Mutant Rancor stepping - } - else - { - stepSize = 48;//hack for Rancor stepping + if (pm->gent->client->NPC_class == CLASS_RANCOR) { + if ((pm->gent->spawnflags & 1)) { + stepSize = 64; // hack for Mutant Rancor stepping + } else { + stepSize = 48; // hack for Rancor stepping } + } else { + stepSize = 70; // hack for AT-ST stepping, slightly taller than a standing stormtrooper } - else - { - stepSize = 70;//hack for AT-ST stepping, slightly taller than a standing stormtrooper - } - } - else if ( pm->maxs[2] <= 0 ) - {//short little guys can't go up steps... FIXME: just make this a flag for certain NPCs- especially ones that roll? + } else if (pm->maxs[2] <= 0) { // short little guys can't go up steps... FIXME: just make this a flag for certain NPCs- especially ones that roll? stepSize = 4; } - //Q3Final addition... + // Q3Final addition... VectorCopy(start_o, down); down[2] -= stepSize; - pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + pm->trace(&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); VectorSet(up, 0, 0, 1); // never step up when you still have up velocity - if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || - DotProduct(trace.plane.normal, up) < 0.7)) { + if (pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || DotProduct(trace.plane.normal, up) < 0.7)) { return; } - if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] ) - {//All our velocity was cancelled sliding + if (!pm->ps->velocity[0] && !pm->ps->velocity[1]) { // All our velocity was cancelled sliding return; } - VectorCopy (pm->ps->origin, down_o); - VectorCopy (pm->ps->velocity, down_v); + VectorCopy(pm->ps->origin, down_o); + VectorCopy(pm->ps->velocity, down_v); - VectorCopy (start_o, up); + VectorCopy(start_o, up); up[2] += stepSize; // test the player position if they were a stepheight higher - pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); - if ( trace.allsolid || trace.startsolid || trace.fraction == 0) { - if ( pm->debugLevel ) { + pm->trace(&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid || trace.fraction == 0) { + if (pm->debugLevel) { Com_Printf("%i:bend can't step\n", c_pmove); } - return; // can't step up + return; // can't step up } - if ( pm->debugLevel ) - { - G_DebugLine(start_o,trace.endpos,2000,0xffffff,qtrue); + if (pm->debugLevel) { + G_DebugLine(start_o, trace.endpos, 2000, 0xffffff, qtrue); } -//===Another slidemove forward================================================================================ + //===Another slidemove forward================================================================================ // try slidemove from this position - VectorCopy( trace.endpos, pm->ps->origin ); - VectorCopy( start_v, pm->ps->velocity ); - /*cantStepUpFwd = */PM_SlideMove( gravMod ); -//===Another slidemove forward================================================================================ - - if ( pm->debugLevel ) - { - G_DebugLine(trace.endpos,pm->ps->origin,2000,0xffffff,qtrue); - } - //compare the initial slidemove and this slidemove from a step up position - VectorSubtract( down_o, start_o, slideMove ); - VectorSubtract( trace.endpos, pm->ps->origin, stepUpMove ); + VectorCopy(trace.endpos, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); + /*cantStepUpFwd = */ PM_SlideMove(gravMod); + //===Another slidemove forward================================================================================ - if ( fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared( slideMove ) > VectorLengthSquared( stepUpMove ) ) - { - //slideMove was better, use it - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); + if (pm->debugLevel) { + G_DebugLine(trace.endpos, pm->ps->origin, 2000, 0xffffff, qtrue); } - else - { + // compare the initial slidemove and this slidemove from a step up position + VectorSubtract(down_o, start_o, slideMove); + VectorSubtract(trace.endpos, pm->ps->origin, stepUpMove); + + if (fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared(slideMove) > VectorLengthSquared(stepUpMove)) { + // slideMove was better, use it + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); + } else { qboolean skipStep = qfalse; // push down the final amount - VectorCopy (pm->ps->origin, down); + VectorCopy(pm->ps->origin, down); down[2] -= stepSize; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); - if ( pm->debugLevel ) - { - G_DebugLine(pm->ps->origin,trace.endpos,2000,0xffffff,qtrue); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, (EG2_Collision)0, 0); + if (pm->debugLevel) { + G_DebugLine(pm->ps->origin, trace.endpos, 2000, 0xffffff, qtrue); } - if ( g_stepSlideFix->integer ) - { - if ( pm->ps->clientNum < MAX_CLIENTS - && trace.plane.normal[2] < MIN_WALK_NORMAL ) - {//normal players cannot step up slopes that are too steep to walk on! + if (g_stepSlideFix->integer) { + if (pm->ps->clientNum < MAX_CLIENTS && + trace.plane.normal[2] < MIN_WALK_NORMAL) { // normal players cannot step up slopes that are too steep to walk on! vec3_t stepVec; - //okay, the step up ends on a slope that it too steep to step up onto, - //BUT: - //If the step looks like this: - // (B)\__ - // \_____(A) - //Then it might still be okay, so we figure out the slope of the entire move - //from (A) to (B) and if that slope is walk-upabble, then it's okay - VectorSubtract( trace.endpos, down_o, stepVec ); - VectorNormalize( stepVec ); - if ( stepVec[2] > (1.0f-MIN_WALK_NORMAL) ) - { - if ( pm->debugLevel ) - { - G_DebugLine(down_o,trace.endpos,2000,0x0000ff,qtrue); + // okay, the step up ends on a slope that it too steep to step up onto, + // BUT: + // If the step looks like this: + // (B)\__ + // \_____(A) + // Then it might still be okay, so we figure out the slope of the entire move + // from (A) to (B) and if that slope is walk-upabble, then it's okay + VectorSubtract(trace.endpos, down_o, stepVec); + VectorNormalize(stepVec); + if (stepVec[2] > (1.0f - MIN_WALK_NORMAL)) { + if (pm->debugLevel) { + G_DebugLine(down_o, trace.endpos, 2000, 0x0000ff, qtrue); } skipStep = qtrue; } } } - if ( !trace.allsolid - && !skipStep ) //normal players cannot step up slopes that are too steep to walk on! + if (!trace.allsolid && !skipStep) // normal players cannot step up slopes that are too steep to walk on! { - if ( pm->ps->clientNum - && isGiant - && g_entities[trace.entityNum].client - && pm->gent - && pm->gent->client - && pm->gent->client->NPC_class == CLASS_RANCOR ) - {//Rancor don't step on clients - if ( g_stepSlideFix->integer ) - { - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); - } - else - { - VectorCopy (start_o, pm->ps->origin); - VectorCopy (start_v, pm->ps->velocity); + if (pm->ps->clientNum && isGiant && g_entities[trace.entityNum].client && pm->gent && pm->gent->client && + pm->gent->client->NPC_class == CLASS_RANCOR) { // Rancor don't step on clients + if (g_stepSlideFix->integer) { + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); + } else { + VectorCopy(start_o, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); } - } - else if ( pm->ps->clientNum - && isGiant - && g_entities[trace.entityNum].client - && g_entities[trace.entityNum].client->playerTeam == pm->gent->client->playerTeam ) - {//AT-ST's don't step up on allies - if ( g_stepSlideFix->integer ) - { - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); - } - else - { - VectorCopy (start_o, pm->ps->origin); - VectorCopy (start_v, pm->ps->velocity); + } else if (pm->ps->clientNum && isGiant && g_entities[trace.entityNum].client && + g_entities[trace.entityNum].client->playerTeam == pm->gent->client->playerTeam) { // AT-ST's don't step up on allies + if (g_stepSlideFix->integer) { + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); + } else { + VectorCopy(start_o, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); } - } - else - { - VectorCopy( trace.endpos, pm->ps->origin ); - if ( g_stepSlideFix->integer ) - { - if ( trace.fraction < 1.0 ) - { - PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); + } else { + VectorCopy(trace.endpos, pm->ps->origin); + if (g_stepSlideFix->integer) { + if (trace.fraction < 1.0) { + PM_ClipVelocity(pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP); } } } - } - else - { - if ( g_stepSlideFix->integer ) - { - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); + } else { + if (g_stepSlideFix->integer) { + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); } } - if ( !g_stepSlideFix->integer ) - { - if ( trace.fraction < 1.0 ) - { - PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); + if (!g_stepSlideFix->integer) { + if (trace.fraction < 1.0) { + PM_ClipVelocity(pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP); } } } @@ -573,23 +490,22 @@ void PM_StepSlideMove( float gravMod ) #endif { // use the step move - float delta; + float delta; delta = pm->ps->origin[2] - start_o[2]; - if ( delta > 2 ) { - if ( delta < 7 ) { - PM_AddEvent( EV_STEP_4 ); - } else if ( delta < 11 ) { - PM_AddEvent( EV_STEP_8 ); - } else if ( delta < 15 ) { - PM_AddEvent( EV_STEP_12 ); + if (delta > 2) { + if (delta < 7) { + PM_AddEvent(EV_STEP_4); + } else if (delta < 11) { + PM_AddEvent(EV_STEP_8); + } else if (delta < 15) { + PM_AddEvent(EV_STEP_12); } else { - PM_AddEvent( EV_STEP_16 ); + PM_AddEvent(EV_STEP_16); } } - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:stepped\n", c_pmove); } } } - diff --git a/code/game/bg_vehicleLoad.cpp b/code/game/bg_vehicleLoad.cpp index 3251fad821..79e199daab 100644 --- a/code/game/bg_vehicleLoad.cpp +++ b/code/game/bg_vehicleLoad.cpp @@ -20,34 +20,33 @@ along with this program; if not, see . =========================================================================== */ -//bg_vehicleLoad.c +// bg_vehicleLoad.c -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif #endif #ifdef _JK2MP - #include "../qcommon/q_shared.h" - #include "bg_public.h" - #include "bg_vehicles.h" - #include "bg_weapons.h" +#include "../qcommon/q_shared.h" +#include "bg_public.h" +#include "bg_vehicles.h" +#include "bg_weapons.h" - //Could use strap stuff but I don't particularly care at the moment anyway. +// Could use strap stuff but I don't particularly care at the moment anyway. #include "../namespace_begin.h" - extern int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ); - extern void trap_FS_Read( void *buffer, int len, fileHandle_t f ); - extern void trap_FS_Write( const void *buffer, int len, fileHandle_t f ); - extern void trap_FS_FCloseFile( fileHandle_t f ); - extern int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ); +extern int trap_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode); +extern void trap_FS_Read(void *buffer, int len, fileHandle_t f); +extern void trap_FS_Write(const void *buffer, int len, fileHandle_t f); +extern void trap_FS_FCloseFile(fileHandle_t f); +extern int trap_FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize); #include "../namespace_end.h" #else - #include "g_local.h" - #define QAGAME +#include "g_local.h" +#define QAGAME #endif - #ifdef _JK2MP #ifndef QAGAME #ifndef CGAME @@ -62,32 +61,32 @@ along with this program; if not, see . #endif #ifdef QAGAME -extern void G_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ); -extern int G_ModelIndex( const char *name ); -extern int G_SoundIndex( const char *name ); - #ifdef _JK2MP - extern int G_EffectIndex( const char *name ); - #endif +extern void G_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo); +extern int G_ModelIndex(const char *name); +extern int G_SoundIndex(const char *name); +#ifdef _JK2MP +extern int G_EffectIndex(const char *name); +#endif #elif defined CGAME #include "../namespace_begin.h" -extern qhandle_t trap_R_RegisterModel( const char *name ); // returns rgb axis if not found -extern qhandle_t trap_R_RegisterSkin( const char *name ); // returns all white if not found -extern qhandle_t trap_R_RegisterShader( const char *name ); -extern qhandle_t trap_R_RegisterShaderNoMip( const char *name ); -extern int trap_FX_RegisterEffect(const char *file); -extern sfxHandle_t trap_S_RegisterSound( const char *sample); // returns buzz if not found +extern qhandle_t trap_R_RegisterModel(const char *name); // returns rgb axis if not found +extern qhandle_t trap_R_RegisterSkin(const char *name); // returns all white if not found +extern qhandle_t trap_R_RegisterShader(const char *name); +extern qhandle_t trap_R_RegisterShaderNoMip(const char *name); +extern int trap_FX_RegisterEffect(const char *file); +extern sfxHandle_t trap_S_RegisterSound(const char *sample); // returns buzz if not found #include "../namespace_end.h" -#else//UI +#else // UI #include "../namespace_begin.h" -extern qhandle_t trap_R_RegisterModel( const char *name ); // returns rgb axis if not found -extern qhandle_t trap_R_RegisterSkin( const char *name ); // returns all white if not found -extern qhandle_t trap_R_RegisterShader( const char *name ); // returns all white if not found -extern qhandle_t trap_R_RegisterShaderNoMip( const char *name ); // returns all white if not found -extern sfxHandle_t trap_S_RegisterSound( const char *sample); // returns buzz if not found +extern qhandle_t trap_R_RegisterModel(const char *name); // returns rgb axis if not found +extern qhandle_t trap_R_RegisterSkin(const char *name); // returns all white if not found +extern qhandle_t trap_R_RegisterShader(const char *name); // returns all white if not found +extern qhandle_t trap_R_RegisterShaderNoMip(const char *name); // returns all white if not found +extern sfxHandle_t trap_S_RegisterSound(const char *sample); // returns buzz if not found #include "../namespace_end.h" #endif -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; // These buffers are filled in with the same contents and then just read from in // a few places. We only need one copy on Xbox. @@ -95,19 +94,18 @@ extern stringID_table_t animTable [MAX_ANIMATIONS+1]; #define MAX_VEHICLE_DATA_SIZE 0x100000 #if defined(QAGAME) - char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; - char VehicleParms[MAX_VEHICLE_DATA_SIZE]; +char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; +char VehicleParms[MAX_VEHICLE_DATA_SIZE]; -void BG_ClearVehicleParseParms(void) -{ - //You can't strcat to these forever without clearing them! +void BG_ClearVehicleParseParms(void) { + // You can't strcat to these forever without clearing them! VehWeaponParms[0] = 0; VehicleParms[0] = 0; } #else - extern char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; - extern char VehicleParms[MAX_VEHICLE_DATA_SIZE]; +extern char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; +extern char VehicleParms[MAX_VEHICLE_DATA_SIZE]; #endif #ifdef _JK2MP @@ -115,235 +113,226 @@ void BG_ClearVehicleParseParms(void) #endif #ifndef WE_ARE_IN_THE_UI -//These funcs are actually shared in both projects -extern void G_SetAnimalVehicleFunctions( vehicleInfo_t *pVehInfo ); -extern void G_SetSpeederVehicleFunctions( vehicleInfo_t *pVehInfo ); -extern void G_SetWalkerVehicleFunctions( vehicleInfo_t *pVehInfo ); -extern void G_SetFighterVehicleFunctions( vehicleInfo_t *pVehInfo ); +// These funcs are actually shared in both projects +extern void G_SetAnimalVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetSpeederVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetWalkerVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetFighterVehicleFunctions(vehicleInfo_t *pVehInfo); #endif vehWeaponInfo_t g_vehWeaponInfo[MAX_VEH_WEAPONS]; -int numVehicleWeapons = 1;//first one is null/default +int numVehicleWeapons = 1; // first one is null/default vehicleInfo_t g_vehicleInfo[MAX_VEHICLES]; -int numVehicles = 0;//first one is null/default +int numVehicles = 0; // first one is null/default -void BG_VehicleLoadParms( void ); +void BG_VehicleLoadParms(void); typedef enum { VF_IGNORE, VF_INT, VF_FLOAT, - VF_STRING, // string on disk, pointer in memory + VF_STRING, // string on disk, pointer in memory VF_VECTOR, VF_BOOL, VF_VEHTYPE, VF_ANIM, - VF_WEAPON, // take string, resolve into index into VehWeaponParms - VF_MODEL, // take the string, get the G_ModelIndex - VF_MODEL_CLIENT, // (cgame only) take the string, get the G_ModelIndex - VF_EFFECT, // take the string, get the G_EffectIndex - VF_EFFECT_CLIENT, // (cgame only) take the string, get the index - VF_SHADER, // (cgame only) take the string, call trap_R_RegisterShader - VF_SHADER_NOMIP,// (cgame only) take the string, call trap_R_RegisterShaderNoMip - VF_SOUND, // take the string, get the G_SoundIndex - VF_SOUND_CLIENT // (cgame only) take the string, get the index + VF_WEAPON, // take string, resolve into index into VehWeaponParms + VF_MODEL, // take the string, get the G_ModelIndex + VF_MODEL_CLIENT, // (cgame only) take the string, get the G_ModelIndex + VF_EFFECT, // take the string, get the G_EffectIndex + VF_EFFECT_CLIENT, // (cgame only) take the string, get the index + VF_SHADER, // (cgame only) take the string, call trap_R_RegisterShader + VF_SHADER_NOMIP, // (cgame only) take the string, call trap_R_RegisterShaderNoMip + VF_SOUND, // take the string, get the G_SoundIndex + VF_SOUND_CLIENT // (cgame only) take the string, get the index } vehFieldType_t; -typedef struct -{ - const char *name; - size_t ofs; - vehFieldType_t type; +typedef struct { + const char *name; + size_t ofs; + vehFieldType_t type; } vehField_t; -vehField_t vehWeaponFields[] = -{ - {"name", VWFOFS(name), VF_STRING}, //unique name of the vehicle - {"projectile", VWFOFS(bIsProjectile), VF_BOOL}, //traceline or entity? - {"hasGravity", VWFOFS(bHasGravity), VF_BOOL}, //if a projectile, drops - {"ionWeapon", VWFOFS(bIonWeapon), VF_BOOL}, //disables ship shields and sends them out of control - {"saberBlockable", VWFOFS(bSaberBlockable), VF_BOOL}, //lightsabers can deflect this projectile - {"muzzleFX", VWFOFS(iMuzzleFX), VF_EFFECT_CLIENT}, //index of Muzzle Effect - {"model", VWFOFS(iModel), VF_MODEL_CLIENT}, //handle to the model used by this projectile - {"shotFX", VWFOFS(iShotFX), VF_EFFECT_CLIENT}, //index of Shot Effect - {"impactFX", VWFOFS(iImpactFX), VF_EFFECT_CLIENT}, //index of Impact Effect - {"g2MarkShader", VWFOFS(iG2MarkShaderHandle), VF_SHADER}, //index of shader to use for G2 marks made on other models when hit by this projectile - {"g2MarkSize", VWFOFS(fG2MarkSize), VF_FLOAT}, //size (diameter) of the ghoul2 mark - {"loopSound", VWFOFS(iLoopSound), VF_SOUND_CLIENT}, //index of loopSound - {"speed", VWFOFS(fSpeed), VF_FLOAT}, //speed of projectile/range of traceline - {"homing", VWFOFS(fHoming), VF_FLOAT}, //0.0 = not homing, 0.5 = half vel to targ, half cur vel, 1.0 = all vel to targ - {"homingFOV", VWFOFS(fHomingFOV), VF_FLOAT},//missile will lose lock on if DotProduct of missile direction and direction to target ever drops below this (-1 to 1, -1 = never lose target, 0 = lose if ship gets behind missile, 1 = pretty much will lose it's target right away) - {"lockOnTime", VWFOFS(iLockOnTime), VF_INT}, //0 = no lock time needed, else # of ms needed to lock on - {"damage", VWFOFS(iDamage), VF_INT}, //damage done when traceline or projectile directly hits target - {"splashDamage", VWFOFS(iSplashDamage), VF_INT},//damage done to ents in splashRadius of end of traceline or projectile origin on impact - {"splashRadius", VWFOFS(fSplashRadius), VF_FLOAT},//radius that ent must be in to take splashDamage (linear fall-off) - {"ammoPerShot", VWFOFS(iAmmoPerShot), VF_INT},//how much "ammo" each shot takes - {"health", VWFOFS(iHealth), VF_INT}, //if non-zero, projectile can be shot, takes this much damage before being destroyed - {"width", VWFOFS(fWidth), VF_FLOAT}, //width of traceline or bounding box of projecile (non-rotating!) - {"height", VWFOFS(fHeight), VF_FLOAT}, //height of traceline or bounding box of projecile (non-rotating!) - {"lifetime", VWFOFS(iLifeTime), VF_INT}, //removes itself after this amount of time - {"explodeOnExpire", VWFOFS(bExplodeOnExpire), VF_BOOL}, //when iLifeTime is up, explodes rather than simply removing itself +vehField_t vehWeaponFields[] = { + {"name", VWFOFS(name), VF_STRING}, // unique name of the vehicle + {"projectile", VWFOFS(bIsProjectile), VF_BOOL}, // traceline or entity? + {"hasGravity", VWFOFS(bHasGravity), VF_BOOL}, // if a projectile, drops + {"ionWeapon", VWFOFS(bIonWeapon), VF_BOOL}, // disables ship shields and sends them out of control + {"saberBlockable", VWFOFS(bSaberBlockable), VF_BOOL}, // lightsabers can deflect this projectile + {"muzzleFX", VWFOFS(iMuzzleFX), VF_EFFECT_CLIENT}, // index of Muzzle Effect + {"model", VWFOFS(iModel), VF_MODEL_CLIENT}, // handle to the model used by this projectile + {"shotFX", VWFOFS(iShotFX), VF_EFFECT_CLIENT}, // index of Shot Effect + {"impactFX", VWFOFS(iImpactFX), VF_EFFECT_CLIENT}, // index of Impact Effect + {"g2MarkShader", VWFOFS(iG2MarkShaderHandle), VF_SHADER}, // index of shader to use for G2 marks made on other models when hit by this projectile + {"g2MarkSize", VWFOFS(fG2MarkSize), VF_FLOAT}, // size (diameter) of the ghoul2 mark + {"loopSound", VWFOFS(iLoopSound), VF_SOUND_CLIENT}, // index of loopSound + {"speed", VWFOFS(fSpeed), VF_FLOAT}, // speed of projectile/range of traceline + {"homing", VWFOFS(fHoming), VF_FLOAT}, // 0.0 = not homing, 0.5 = half vel to targ, half cur vel, 1.0 = all vel to targ + {"homingFOV", VWFOFS(fHomingFOV), + VF_FLOAT}, // missile will lose lock on if DotProduct of missile direction and direction to target ever drops below this (-1 to 1, -1 = never lose target, + // 0 = lose if ship gets behind missile, 1 = pretty much will lose it's target right away) + {"lockOnTime", VWFOFS(iLockOnTime), VF_INT}, // 0 = no lock time needed, else # of ms needed to lock on + {"damage", VWFOFS(iDamage), VF_INT}, // damage done when traceline or projectile directly hits target + {"splashDamage", VWFOFS(iSplashDamage), VF_INT}, // damage done to ents in splashRadius of end of traceline or projectile origin on impact + {"splashRadius", VWFOFS(fSplashRadius), VF_FLOAT}, // radius that ent must be in to take splashDamage (linear fall-off) + {"ammoPerShot", VWFOFS(iAmmoPerShot), VF_INT}, // how much "ammo" each shot takes + {"health", VWFOFS(iHealth), VF_INT}, // if non-zero, projectile can be shot, takes this much damage before being destroyed + {"width", VWFOFS(fWidth), VF_FLOAT}, // width of traceline or bounding box of projecile (non-rotating!) + {"height", VWFOFS(fHeight), VF_FLOAT}, // height of traceline or bounding box of projecile (non-rotating!) + {"lifetime", VWFOFS(iLifeTime), VF_INT}, // removes itself after this amount of time + {"explodeOnExpire", VWFOFS(bExplodeOnExpire), VF_BOOL}, // when iLifeTime is up, explodes rather than simply removing itself }; -static const size_t numVehWeaponFields = ARRAY_LEN( vehWeaponFields ); +static const size_t numVehWeaponFields = ARRAY_LEN(vehWeaponFields); -static vehField_t *FindVehWeaponParm( const char *parmName ) -{ +static vehField_t *FindVehWeaponParm(const char *parmName) { size_t i; - for ( i = 0; itype ) - { + switch (vehWeaponField->type) { case VF_INT: - *(int *)(b+vehWeaponField->ofs) = atoi(value); + *(int *)(b + vehWeaponField->ofs) = atoi(value); break; case VF_FLOAT: - *(float *)(b+vehWeaponField->ofs) = atof(value); + *(float *)(b + vehWeaponField->ofs) = atof(value); break; - case VF_STRING: // string on disk, pointer in memory - if (!*(char **)(b+vehWeaponField->ofs)) - { //just use 1024 bytes in case we want to write over the string + case VF_STRING: // string on disk, pointer in memory + if (!*(char **)(b + vehWeaponField->ofs)) { // just use 1024 bytes in case we want to write over the string #ifdef _JK2MP - *(char **)(b+vehWeaponField->ofs) = (char *)BG_Alloc(1024);//(char *)BG_Alloc(strlen(value)); - strcpy(*(char **)(b+vehWeaponField->ofs), value); + *(char **)(b + vehWeaponField->ofs) = (char *)BG_Alloc(1024); //(char *)BG_Alloc(strlen(value)); + strcpy(*(char **)(b + vehWeaponField->ofs), value); #else - (*(char **)(b+vehWeaponField->ofs)) = G_NewString( value ); + (*(char **)(b + vehWeaponField->ofs)) = G_NewString(value); #endif } break; case VF_VECTOR: - _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - //assert(_iFieldsRead==3 ); - if (_iFieldsRead!=3) - { - Com_Printf (S_COLOR_YELLOW"BG_ParseVehWeaponParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); - VectorClear( vec ); + _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + // assert(_iFieldsRead==3 ); + if (_iFieldsRead != 3) { + Com_Printf(S_COLOR_YELLOW "BG_ParseVehWeaponParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + VectorClear(vec); } - ((float *)(b+vehWeaponField->ofs))[0] = vec[0]; - ((float *)(b+vehWeaponField->ofs))[1] = vec[1]; - ((float *)(b+vehWeaponField->ofs))[2] = vec[2]; + ((float *)(b + vehWeaponField->ofs))[0] = vec[0]; + ((float *)(b + vehWeaponField->ofs))[1] = vec[1]; + ((float *)(b + vehWeaponField->ofs))[2] = vec[2]; break; case VF_BOOL: - *(qboolean *)(b+vehWeaponField->ofs) = (qboolean)(atof(value)!=0); + *(qboolean *)(b + vehWeaponField->ofs) = (qboolean)(atof(value) != 0); break; case VF_VEHTYPE: - vehType = (vehicleType_t)GetIDForString( VehicleTable, value ); - *(vehicleType_t *)(b+vehWeaponField->ofs) = vehType; + vehType = (vehicleType_t)GetIDForString(VehicleTable, value); + *(vehicleType_t *)(b + vehWeaponField->ofs) = vehType; break; - case VF_ANIM: - { - int anim = GetIDForString( animTable, value ); - *(int *)(b+vehWeaponField->ofs) = anim; - } - break; - case VF_WEAPON: // take string, resolve into index into VehWeaponParms + case VF_ANIM: { + int anim = GetIDForString(animTable, value); + *(int *)(b + vehWeaponField->ofs) = anim; + } break; + case VF_WEAPON: // take string, resolve into index into VehWeaponParms //*(int *)(b+vehWeaponField->ofs) = VEH_VehWeaponIndexForName( value ); break; - case VF_MODEL:// take the string, get the G_ModelIndex + case VF_MODEL: // take the string, get the G_ModelIndex #ifdef QAGAME - *(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_ModelIndex(value); #else - *(int *)(b+vehWeaponField->ofs) = trap_R_RegisterModel( value ); + *(int *)(b + vehWeaponField->ofs) = trap_R_RegisterModel(value); #endif break; - case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex + case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex #ifndef _JK2MP - *(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_ModelIndex(value); #elif defined QAGAME - //*(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); #else - *(int *)(b+vehWeaponField->ofs) = trap_R_RegisterModel( value ); + *(int *)(b + vehWeaponField->ofs) = trap_R_RegisterModel(value); #endif break; - case VF_EFFECT: // take the string, get the G_EffectIndex + case VF_EFFECT: // take the string, get the G_EffectIndex #ifdef QAGAME - *(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_EffectIndex(value); #elif defined CGAME - *(int *)(b+vehWeaponField->ofs) = trap_FX_RegisterEffect( value ); + *(int *)(b + vehWeaponField->ofs) = trap_FX_RegisterEffect(value); #endif break; - case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the index + case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the index #ifndef _JK2MP - *(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_EffectIndex(value); #elif defined QAGAME - //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); #elif defined CGAME - *(int *)(b+vehWeaponField->ofs) = trap_FX_RegisterEffect( value ); + *(int *)(b + vehWeaponField->ofs) = trap_FX_RegisterEffect(value); #endif break; - case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader + case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader #ifdef WE_ARE_IN_THE_UI - *(int *)(b+vehWeaponField->ofs) = trap_R_RegisterShaderNoMip( value ); + *(int *)(b + vehWeaponField->ofs) = trap_R_RegisterShaderNoMip(value); #elif defined CGAME - *(int *)(b+vehWeaponField->ofs) = trap_R_RegisterShader( value ); + *(int *)(b + vehWeaponField->ofs) = trap_R_RegisterShader(value); #endif break; - case VF_SHADER_NOMIP:// (cgame only) take the string, call trap_R_RegisterShaderNoMip + case VF_SHADER_NOMIP: // (cgame only) take the string, call trap_R_RegisterShaderNoMip #ifndef QAGAME - *(int *)(b+vehWeaponField->ofs) = trap_R_RegisterShaderNoMip( value ); + *(int *)(b + vehWeaponField->ofs) = trap_R_RegisterShaderNoMip(value); #endif break; - case VF_SOUND: // take the string, get the G_SoundIndex + case VF_SOUND: // take the string, get the G_SoundIndex #ifdef QAGAME - *(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_SoundIndex(value); #else - *(int *)(b+vehWeaponField->ofs) = trap_S_RegisterSound( value ); + *(int *)(b + vehWeaponField->ofs) = trap_S_RegisterSound(value); #endif break; - case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the index + case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the index #ifndef _JK2MP - *(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_SoundIndex(value); #elif defined QAGAME - //*(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); #else - *(int *)(b+vehWeaponField->ofs) = trap_S_RegisterSound( value ); + *(int *)(b + vehWeaponField->ofs) = trap_S_RegisterSound(value); #endif break; default: - //Unknown type? + // Unknown type? return qfalse; } return qtrue; } -int VEH_LoadVehWeapon( const char *vehWeaponName ) -{//load up specified vehWeapon and save in array: g_vehWeaponInfo - const char *token; - char parmName[128];//we'll assume that no parm name is longer than 128 - char *value; - const char *p; - vehWeaponInfo_t *vehWeapon = NULL; +int VEH_LoadVehWeapon(const char *vehWeaponName) { // load up specified vehWeapon and save in array: g_vehWeaponInfo + const char *token; + char parmName[128]; // we'll assume that no parm name is longer than 128 + char *value; + const char *p; + vehWeaponInfo_t *vehWeapon = NULL; - //BG_VehWeaponSetDefaults( &g_vehWeaponInfo[0] );//set the first vehicle to default data + // BG_VehWeaponSetDefaults( &g_vehWeaponInfo[0] );//set the first vehicle to default data - //try to parse data out + // try to parse data out p = VehWeaponParms; #ifdef _JK2MP @@ -354,240 +343,221 @@ int VEH_LoadVehWeapon( const char *vehWeaponName ) vehWeapon = &g_vehWeaponInfo[numVehicleWeapons]; // look for the right vehicle weapon - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, vehWeaponName ) ) - { + if (!Q_stricmp(token, vehWeaponName)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return qfalse; } - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//barf - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // barf + COM_EndParseSession(); return VEH_WEAPON_NONE; } - if ( Q_stricmp( token, "{" ) != 0 ) - { - COM_EndParseSession( ); + if (Q_stricmp(token, "{") != 0) { + COM_EndParseSession(); return VEH_WEAPON_NONE; } // parse the vehWeapon info block - while ( 1 ) - { - SkipRestOfLine( &p ); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing Vehicle Weapon '%s'\n", vehWeaponName ); - COM_EndParseSession( ); + while (1) { + SkipRestOfLine(&p); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing Vehicle Weapon '%s'\n", vehWeaponName); + COM_EndParseSession(); return VEH_WEAPON_NONE; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - Q_strncpyz( parmName, token, sizeof(parmName) ); - value = COM_ParseExt( &p, qtrue ); - if ( !value || !value[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Vehicle Weapon token '%s' has no value!\n", parmName ); - } - else - { - if ( !BG_ParseVehWeaponParm( vehWeapon, parmName, value ) ) - { - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle Weapon key/value pair '%s','%s'!\n", parmName, value ); + Q_strncpyz(parmName, token, sizeof(parmName)); + value = COM_ParseExt(&p, qtrue); + if (!value || !value[0]) { + Com_Printf(S_COLOR_RED "ERROR: Vehicle Weapon token '%s' has no value!\n", parmName); + } else { + if (!BG_ParseVehWeaponParm(vehWeapon, parmName, value)) { + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle Weapon key/value pair '%s','%s'!\n", parmName, value); } } } - if ( vehWeapon->fHoming ) - {//all lock-on weapons use these 2 sounds + if (vehWeapon->fHoming) { // all lock-on weapons use these 2 sounds #ifdef QAGAME - //Hmm, no need fo have server register this, is there? - //G_SoundIndex( "sound/weapons/torpedo/tick.wav" ); - //G_SoundIndex( "sound/weapons/torpedo/lock.wav" ); + // Hmm, no need fo have server register this, is there? + // G_SoundIndex( "sound/weapons/torpedo/tick.wav" ); + // G_SoundIndex( "sound/weapons/torpedo/lock.wav" ); #elif defined CGAME - trap_S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" ); - trap_S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" ); + trap_S_RegisterSound("sound/vehicles/weapons/common/tick.wav"); + trap_S_RegisterSound("sound/vehicles/weapons/common/lock.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm1.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm2.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm3.wav"); #else - trap_S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" ); - trap_S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" ); + trap_S_RegisterSound("sound/vehicles/weapons/common/tick.wav"); + trap_S_RegisterSound("sound/vehicles/weapons/common/lock.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm1.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm2.wav"); + trap_S_RegisterSound("sound/vehicles/common/lockalarm3.wav"); #endif } - COM_EndParseSession( ); + COM_EndParseSession(); return (numVehicleWeapons++); } -int VEH_VehWeaponIndexForName( const char *vehWeaponName ) -{ +int VEH_VehWeaponIndexForName(const char *vehWeaponName) { int vw; - if ( !vehWeaponName || !vehWeaponName[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Trying to read Vehicle Weapon with no name!\n" ); + if (!vehWeaponName || !vehWeaponName[0]) { + Com_Printf(S_COLOR_RED "ERROR: Trying to read Vehicle Weapon with no name!\n"); return VEH_WEAPON_NONE; } - for ( vw = VEH_WEAPON_BASE; vw < numVehicleWeapons; vw++ ) - { - if ( g_vehWeaponInfo[vw].name - && Q_stricmp( g_vehWeaponInfo[vw].name, vehWeaponName ) == 0 ) - {//already loaded this one + for (vw = VEH_WEAPON_BASE; vw < numVehicleWeapons; vw++) { + if (g_vehWeaponInfo[vw].name && Q_stricmp(g_vehWeaponInfo[vw].name, vehWeaponName) == 0) { // already loaded this one return vw; } } - //haven't loaded it yet - if ( vw >= MAX_VEH_WEAPONS ) - {//no more room! - Com_Printf( S_COLOR_RED"ERROR: Too many Vehicle Weapons (max 16), aborting load on %s!\n", vehWeaponName ); + // haven't loaded it yet + if (vw >= MAX_VEH_WEAPONS) { // no more room! + Com_Printf(S_COLOR_RED "ERROR: Too many Vehicle Weapons (max 16), aborting load on %s!\n", vehWeaponName); return VEH_WEAPON_NONE; } - //we have room for another one, load it up and return the index - //HMM... should we not even load the .vwp file until we want to? - vw = VEH_LoadVehWeapon( vehWeaponName ); - if ( vw == VEH_WEAPON_NONE ) - { - Com_Printf( S_COLOR_RED"ERROR: Could not find Vehicle Weapon %s!\n", vehWeaponName ); + // we have room for another one, load it up and return the index + // HMM... should we not even load the .vwp file until we want to? + vw = VEH_LoadVehWeapon(vehWeaponName); + if (vw == VEH_WEAPON_NONE) { + Com_Printf(S_COLOR_RED "ERROR: Could not find Vehicle Weapon %s!\n", vehWeaponName); } return vw; } -vehField_t vehicleFields[] = -{ - {"name", VFOFS(name), VF_STRING}, //unique name of the vehicle - - //general data - {"type", VFOFS(type), VF_VEHTYPE}, //what kind of vehicle - {"numHands", VFOFS(numHands), VF_INT}, //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, //How far you can look up and down off the forward of the vehicle - {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, //How far you can look left and right off the forward of the vehicle - {"length", VFOFS(length), VF_FLOAT}, //how long it is - used for body length traces when turning/moving? - {"width", VFOFS(width), VF_FLOAT}, //how wide it is - used for body length traces when turning/moving? - {"height", VFOFS(height), VF_FLOAT}, //how tall it is - used for body length traces when turning/moving? - {"centerOfGravity", VFOFS(centerOfGravity), VF_VECTOR},//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - {"speedMax", VFOFS(speedMax), VF_FLOAT}, //top speed - {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, //turbo speed - {"speedMin", VFOFS(speedMin), VF_FLOAT}, //if < 0, can go in reverse - {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, //what speed it drifts to when no accel/decel input is given - {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, //if speedIdle > 0, how quickly it goes up to that speed - {"acceleration", VFOFS(acceleration), VF_FLOAT}, //when pressing on accelerator - {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, //when giving no input, how quickly it drops to speedIdle - {"throttleSticks", VFOFS(throttleSticks), VF_BOOL},//if true, speed stays at whatever you accel/decel to, unless you turbo or brake - {"strafePerc", VFOFS(strafePerc), VF_FLOAT}, //multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, //how quickly it pitches and rolls (not under player control) - {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, //how far it can roll forward or backward - {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, //how far it can roll to either side - {"braking", VFOFS(braking), VF_FLOAT}, //when pressing on decelerator - {"mouseYaw", VFOFS(mouseYaw), VF_FLOAT}, // The mouse yaw override. - {"mousePitch", VFOFS(mousePitch), VF_FLOAT}, // The mouse yaw override. - {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, //how quickly you can turn - {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL},//whether or not you can turn when not moving - {"traction", VFOFS(traction), VF_FLOAT}, //how much your command input affects velocity - {"friction", VFOFS(friction), VF_FLOAT}, //how much velocity is cut on its own - {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, //the max slope that it can go up with control - {"speedDependantTurning", VFOFS(speedDependantTurning), VF_BOOL},//vehicle turns faster the faster it's going - - //durability stats - {"mass", VFOFS(mass), VF_INT}, //for momentum and impact force (player mass is 10) - {"armor", VFOFS(armor), VF_INT}, //total points of damage it can take - {"shields", VFOFS(shields), VF_INT}, //energy shield damage points - {"shieldRechargeMS", VFOFS(shieldRechargeMS), VF_INT},//energy shield milliseconds per point recharged - {"toughness", VFOFS(toughness), VF_FLOAT}, //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT},//when armor drops to or below this point, start malfunctioning +vehField_t vehicleFields[] = { + {"name", VFOFS(name), VF_STRING}, // unique name of the vehicle + + // general data + {"type", VFOFS(type), VF_VEHTYPE}, // what kind of vehicle + {"numHands", VFOFS(numHands), VF_INT}, // if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, // How far you can look up and down off the forward of the vehicle + {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, // How far you can look left and right off the forward of the vehicle + {"length", VFOFS(length), VF_FLOAT}, // how long it is - used for body length traces when turning/moving? + {"width", VFOFS(width), VF_FLOAT}, // how wide it is - used for body length traces when turning/moving? + {"height", VFOFS(height), VF_FLOAT}, // how tall it is - used for body length traces when turning/moving? + {"centerOfGravity", VFOFS(centerOfGravity), + VF_VECTOR}, // offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) + + // speed stats + {"speedMax", VFOFS(speedMax), VF_FLOAT}, // top speed + {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, // turbo speed + {"speedMin", VFOFS(speedMin), VF_FLOAT}, // if < 0, can go in reverse + {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, // what speed it drifts to when no accel/decel input is given + {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, // if speedIdle > 0, how quickly it goes up to that speed + {"acceleration", VFOFS(acceleration), VF_FLOAT}, // when pressing on accelerator + {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, // when giving no input, how quickly it drops to speedIdle + {"throttleSticks", VFOFS(throttleSticks), VF_BOOL}, // if true, speed stays at whatever you accel/decel to, unless you turbo or brake + {"strafePerc", VFOFS(strafePerc), + VF_FLOAT}, // multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing + + // handling stats + {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, // how quickly it pitches and rolls (not under player control) + {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, // how far it can roll forward or backward + {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, // how far it can roll to either side + {"braking", VFOFS(braking), VF_FLOAT}, // when pressing on decelerator + {"mouseYaw", VFOFS(mouseYaw), VF_FLOAT}, // The mouse yaw override. + {"mousePitch", VFOFS(mousePitch), VF_FLOAT}, // The mouse yaw override. + {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, // how quickly you can turn + {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL}, // whether or not you can turn when not moving + {"traction", VFOFS(traction), VF_FLOAT}, // how much your command input affects velocity + {"friction", VFOFS(friction), VF_FLOAT}, // how much velocity is cut on its own + {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, // the max slope that it can go up with control + {"speedDependantTurning", VFOFS(speedDependantTurning), VF_BOOL}, // vehicle turns faster the faster it's going + + // durability stats + {"mass", VFOFS(mass), VF_INT}, // for momentum and impact force (player mass is 10) + {"armor", VFOFS(armor), VF_INT}, // total points of damage it can take + {"shields", VFOFS(shields), VF_INT}, // energy shield damage points + {"shieldRechargeMS", VFOFS(shieldRechargeMS), VF_INT}, // energy shield milliseconds per point recharged + {"toughness", VFOFS(toughness), + VF_FLOAT}, // modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction + {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT}, // when armor drops to or below this point, start malfunctioning {"surfDestruction", VFOFS(surfDestruction), VF_INT}, - //visuals & sounds - {"model", VFOFS(model), VF_STRING}, //what model to use - if make it an NPC's primary model, don't need this? - {"skin", VFOFS(skin), VF_STRING}, //what skin to use - if make it an NPC's primary model, don't need this? - {"g2radius", VFOFS(g2radius), VF_INT}, //render radius (really diameter, but...) for the ghoul2 model - {"riderAnim", VFOFS(riderAnim), VF_ANIM}, //what animation the rider uses - {"droidNPC", VFOFS(droidNPC), VF_STRING}, //NPC to attach to *droidunit tag (if it exists in the model) + // visuals & sounds + {"model", VFOFS(model), VF_STRING}, // what model to use - if make it an NPC's primary model, don't need this? + {"skin", VFOFS(skin), VF_STRING}, // what skin to use - if make it an NPC's primary model, don't need this? + {"g2radius", VFOFS(g2radius), VF_INT}, // render radius (really diameter, but...) for the ghoul2 model + {"riderAnim", VFOFS(riderAnim), VF_ANIM}, // what animation the rider uses + {"droidNPC", VFOFS(droidNPC), VF_STRING}, // NPC to attach to *droidunit tag (if it exists in the model) #ifdef _JK2MP - {"radarIcon", VFOFS(radarIconHandle), VF_SHADER_NOMIP}, //what icon to show on radar in MP - {"dmgIndicFrame", VFOFS(dmgIndicFrameHandle), VF_SHADER_NOMIP}, //what image to use for the frame of the damage indicator - {"dmgIndicShield", VFOFS(dmgIndicShieldHandle), VF_SHADER_NOMIP},//what image to use for the shield of the damage indicator - {"dmgIndicBackground", VFOFS(dmgIndicBackgroundHandle), VF_SHADER_NOMIP},//what image to use for the background of the damage indicator - {"icon_front", VFOFS(iconFrontHandle), VF_SHADER_NOMIP}, //what image to use for the front of the ship on the damage indicator - {"icon_back", VFOFS(iconBackHandle), VF_SHADER_NOMIP}, //what image to use for the back of the ship on the damage indicator - {"icon_right", VFOFS(iconRightHandle), VF_SHADER_NOMIP}, //what image to use for the right of the ship on the damage indicator - {"icon_left", VFOFS(iconLeftHandle), VF_SHADER_NOMIP}, //what image to use for the left of the ship on the damage indicator - {"crosshairShader", VFOFS(crosshairShaderHandle), VF_SHADER_NOMIP}, //what image to use as the crosshair - {"shieldShader", VFOFS(shieldShaderHandle), VF_SHADER}, //What shader to use when drawing the shield shell - - //individual "area" health -rww + {"radarIcon", VFOFS(radarIconHandle), VF_SHADER_NOMIP}, // what icon to show on radar in MP + {"dmgIndicFrame", VFOFS(dmgIndicFrameHandle), VF_SHADER_NOMIP}, // what image to use for the frame of the damage indicator + {"dmgIndicShield", VFOFS(dmgIndicShieldHandle), VF_SHADER_NOMIP}, // what image to use for the shield of the damage indicator + {"dmgIndicBackground", VFOFS(dmgIndicBackgroundHandle), VF_SHADER_NOMIP}, // what image to use for the background of the damage indicator + {"icon_front", VFOFS(iconFrontHandle), VF_SHADER_NOMIP}, // what image to use for the front of the ship on the damage indicator + {"icon_back", VFOFS(iconBackHandle), VF_SHADER_NOMIP}, // what image to use for the back of the ship on the damage indicator + {"icon_right", VFOFS(iconRightHandle), VF_SHADER_NOMIP}, // what image to use for the right of the ship on the damage indicator + {"icon_left", VFOFS(iconLeftHandle), VF_SHADER_NOMIP}, // what image to use for the left of the ship on the damage indicator + {"crosshairShader", VFOFS(crosshairShaderHandle), VF_SHADER_NOMIP}, // what image to use as the crosshair + {"shieldShader", VFOFS(shieldShaderHandle), VF_SHADER}, // What shader to use when drawing the shield shell + + // individual "area" health -rww {"health_front", VFOFS(health_front), VF_INT}, {"health_back", VFOFS(health_back), VF_INT}, {"health_right", VFOFS(health_right), VF_INT}, {"health_left", VFOFS(health_left), VF_INT}, #else - {"radarIcon", 0, VF_IGNORE}, //what icon to show on radar in MP -#endif - - {"soundOn", VFOFS(soundOn), VF_SOUND},//sound to play when get on it - {"soundOff", VFOFS(soundOff), VF_SOUND},//sound to play when get off - {"soundLoop", VFOFS(soundLoop), VF_SOUND},//sound to loop while riding it - {"soundTakeOff", VFOFS(soundTakeOff), VF_SOUND},//sound to play when ship takes off - {"soundEngineStart",VFOFS(soundEngineStart),VF_SOUND_CLIENT},//sound to play when ship's thrusters first activate - {"soundSpin", VFOFS(soundSpin), VF_SOUND},//sound to loop while spiraling out of control - {"soundTurbo", VFOFS(soundTurbo), VF_SOUND},//sound to play when turbo/afterburner kicks in - {"soundHyper", VFOFS(soundHyper), VF_SOUND_CLIENT},//sound to play when hits hyperspace - {"soundLand", VFOFS(soundLand), VF_SOUND},//sound to play when ship lands - {"soundFlyBy", VFOFS(soundFlyBy), VF_SOUND_CLIENT},//sound to play when they buzz you - {"soundFlyBy2", VFOFS(soundFlyBy2), VF_SOUND_CLIENT},//alternate sound to play when they buzz you - {"soundShift1", VFOFS(soundShift1), VF_SOUND},//sound to play when changing speeds - {"soundShift2", VFOFS(soundShift2), VF_SOUND},//sound to play when changing speeds - {"soundShift3", VFOFS(soundShift3), VF_SOUND},//sound to play when changing speeds - {"soundShift4", VFOFS(soundShift4), VF_SOUND},//sound to play when changing speeds - - {"exhaustFX", VFOFS(iExhaustFX), VF_EFFECT_CLIENT}, //exhaust effect, played from "*exhaust" bolt(s) - {"turboFX", VFOFS(iTurboFX), VF_EFFECT_CLIENT}, //turbo exhaust effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode - {"turboStartFX", VFOFS(iTurboStartFX), VF_EFFECT}, //turbo start effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode - {"trailFX", VFOFS(iTrailFX), VF_EFFECT_CLIENT}, //trail effect, played from "*trail" bolt(s) - {"impactFX", VFOFS(iImpactFX), VF_EFFECT_CLIENT}, //impact effect, for when it bumps into something - {"explodeFX", VFOFS(iExplodeFX), VF_EFFECT}, //explosion effect, for when it blows up (should have the sound built into explosion effect) - {"wakeFX", VFOFS(iWakeFX), VF_EFFECT_CLIENT}, //effect it makes when going across water - {"dmgFX", VFOFS(iDmgFX), VF_EFFECT_CLIENT}, //effect to play on damage from a weapon or something + {"radarIcon", 0, VF_IGNORE}, // what icon to show on radar in MP +#endif + + {"soundOn", VFOFS(soundOn), VF_SOUND}, // sound to play when get on it + {"soundOff", VFOFS(soundOff), VF_SOUND}, // sound to play when get off + {"soundLoop", VFOFS(soundLoop), VF_SOUND}, // sound to loop while riding it + {"soundTakeOff", VFOFS(soundTakeOff), VF_SOUND}, // sound to play when ship takes off + {"soundEngineStart", VFOFS(soundEngineStart), VF_SOUND_CLIENT}, // sound to play when ship's thrusters first activate + {"soundSpin", VFOFS(soundSpin), VF_SOUND}, // sound to loop while spiraling out of control + {"soundTurbo", VFOFS(soundTurbo), VF_SOUND}, // sound to play when turbo/afterburner kicks in + {"soundHyper", VFOFS(soundHyper), VF_SOUND_CLIENT}, // sound to play when hits hyperspace + {"soundLand", VFOFS(soundLand), VF_SOUND}, // sound to play when ship lands + {"soundFlyBy", VFOFS(soundFlyBy), VF_SOUND_CLIENT}, // sound to play when they buzz you + {"soundFlyBy2", VFOFS(soundFlyBy2), VF_SOUND_CLIENT}, // alternate sound to play when they buzz you + {"soundShift1", VFOFS(soundShift1), VF_SOUND}, // sound to play when changing speeds + {"soundShift2", VFOFS(soundShift2), VF_SOUND}, // sound to play when changing speeds + {"soundShift3", VFOFS(soundShift3), VF_SOUND}, // sound to play when changing speeds + {"soundShift4", VFOFS(soundShift4), VF_SOUND}, // sound to play when changing speeds + + {"exhaustFX", VFOFS(iExhaustFX), VF_EFFECT_CLIENT}, // exhaust effect, played from "*exhaust" bolt(s) + {"turboFX", VFOFS(iTurboFX), VF_EFFECT_CLIENT}, // turbo exhaust effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode + {"turboStartFX", VFOFS(iTurboStartFX), VF_EFFECT}, // turbo start effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode + {"trailFX", VFOFS(iTrailFX), VF_EFFECT_CLIENT}, // trail effect, played from "*trail" bolt(s) + {"impactFX", VFOFS(iImpactFX), VF_EFFECT_CLIENT}, // impact effect, for when it bumps into something + {"explodeFX", VFOFS(iExplodeFX), VF_EFFECT}, // explosion effect, for when it blows up (should have the sound built into explosion effect) + {"wakeFX", VFOFS(iWakeFX), VF_EFFECT_CLIENT}, // effect it makes when going across water + {"dmgFX", VFOFS(iDmgFX), VF_EFFECT_CLIENT}, // effect to play on damage from a weapon or something #ifdef _JK2MP - {"injureFX", VFOFS(iInjureFX), VF_EFFECT_CLIENT}, //effect to play on partially damaged ship surface - {"noseFX", VFOFS(iNoseFX), VF_EFFECT_CLIENT}, //effect for nose piece flying away when blown off - {"lwingFX", VFOFS(iLWingFX), VF_EFFECT_CLIENT}, //effect for left wing piece flying away when blown off - {"rwingFX", VFOFS(iRWingFX), VF_EFFECT_CLIENT}, //effect for right wing piece flying away when blown off + {"injureFX", VFOFS(iInjureFX), VF_EFFECT_CLIENT}, // effect to play on partially damaged ship surface + {"noseFX", VFOFS(iNoseFX), VF_EFFECT_CLIENT}, // effect for nose piece flying away when blown off + {"lwingFX", VFOFS(iLWingFX), VF_EFFECT_CLIENT}, // effect for left wing piece flying away when blown off + {"rwingFX", VFOFS(iRWingFX), VF_EFFECT_CLIENT}, // effect for right wing piece flying away when blown off #else - {"armorLowFX", VFOFS(iArmorLowFX), VF_EFFECT_CLIENT}, //effect to play on damage from a weapon or something - {"armorGoneFX", VFOFS(iArmorGoneFX), VF_EFFECT_CLIENT}, //effect to play on damage from a weapon or something + {"armorLowFX", VFOFS(iArmorLowFX), VF_EFFECT_CLIENT}, // effect to play on damage from a weapon or something + {"armorGoneFX", VFOFS(iArmorGoneFX), VF_EFFECT_CLIENT}, // effect to play on damage from a weapon or something #endif // Weapon stuff: - {"weap1", VFOFS(weapon[0].ID), VF_WEAPON}, //weapon used when press fire - {"weap2", VFOFS(weapon[1].ID), VF_WEAPON},//weapon used when press alt-fire + {"weap1", VFOFS(weapon[0].ID), VF_WEAPON}, // weapon used when press fire + {"weap2", VFOFS(weapon[1].ID), VF_WEAPON}, // weapon used when press alt-fire // The delay between shots for this weapon. {"weap1Delay", VFOFS(weapon[0].delay), VF_INT}, {"weap2Delay", VFOFS(weapon[1].delay), VF_INT}, @@ -597,15 +567,15 @@ vehField_t vehicleFields[] = // Whether or not to auto-aim the projectiles at the thing under the crosshair when we fire {"weap1Aim", VFOFS(weapon[0].aimCorrect), VF_BOOL}, {"weap2Aim", VFOFS(weapon[1].aimCorrect), VF_BOOL}, - //maximum ammo + // maximum ammo {"weap1AmmoMax", VFOFS(weapon[0].ammoMax), VF_INT}, {"weap2AmmoMax", VFOFS(weapon[1].ammoMax), VF_INT}, - //ammo recharge rate - milliseconds per unit (minimum of 100, which is 10 ammo per second) + // ammo recharge rate - milliseconds per unit (minimum of 100, which is 10 ammo per second) {"weap1AmmoRechargeMS", VFOFS(weapon[0].ammoRechargeMS), VF_INT}, {"weap2AmmoRechargeMS", VFOFS(weapon[1].ammoRechargeMS), VF_INT}, - //sound to play when out of ammo (plays default "no ammo" sound if none specified) - {"weap1SoundNoAmmo", VFOFS(weapon[0].soundNoAmmo), VF_SOUND_CLIENT},//sound to play when try to fire weapon 1 with no ammo - {"weap2SoundNoAmmo", VFOFS(weapon[1].soundNoAmmo), VF_SOUND_CLIENT},//sound to play when try to fire weapon 2 with no ammo + // sound to play when out of ammo (plays default "no ammo" sound if none specified) + {"weap1SoundNoAmmo", VFOFS(weapon[0].soundNoAmmo), VF_SOUND_CLIENT}, // sound to play when try to fire weapon 1 with no ammo + {"weap2SoundNoAmmo", VFOFS(weapon[1].soundNoAmmo), VF_SOUND_CLIENT}, // sound to play when try to fire weapon 2 with no ammo // Which weapon a muzzle fires (has to match one of the weapons this vehicle has). {"weapMuzzle1", VFOFS(weapMuzzle[0]), VF_WEAPON}, @@ -622,38 +592,39 @@ vehField_t vehicleFields[] = // The max height before this ship (?) starts (auto)landing. {"landingHeight", VFOFS(landingHeight), VF_FLOAT}, - //other misc stats - {"gravity", VFOFS(gravity), VF_INT}, //normal is 800 - {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, //if 0, it's a ground vehicle - {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, //how hard it pushes off ground when less than hover height... causes "bounce", like shocks - {"waterProof", VFOFS(waterProof), VF_BOOL}, //can drive underwater if it has to - {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, //when in water, how high it floats (1 is neutral bouyancy) - {"fuelMax", VFOFS(fuelMax), VF_INT}, //how much fuel it can hold (capacity) - {"fuelRate", VFOFS(fuelRate), VF_INT}, //how quickly is uses up fuel - {"turboDuration", VFOFS(turboDuration), VF_INT}, //how long turbo lasts - {"turboRecharge", VFOFS(turboRecharge), VF_INT}, //how long turbo takes to recharge - {"visibility", VFOFS(visibility), VF_INT}, //for sight alerts - {"loudness", VFOFS(loudness), VF_INT}, //for sound alerts - {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT},//range of explosion - {"explosionDamage", VFOFS(explosionDamage), VF_INT},//damage of explosion - - //new stuff - {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). - {"hideRider", VFOFS(hideRider), VF_BOOL}, // rider (and passengers?) should not be drawn - {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL},//if rider is on vehicle when it dies, they should die - {"flammable", VFOFS(flammable), VF_BOOL}, //whether or not the vehicle should catch on fire before it explodes - {"explosionDelay", VFOFS(explosionDelay), VF_INT}, //how long the vehicle should be on fire/dying before it explodes - //camera stuff - {"cameraOverride", VFOFS(cameraOverride), VF_BOOL},//override the third person camera with the below values - normal is 0 (off) - {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, //how far back the camera should be - normal is 80 - {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT},//how high over the vehicle origin the camera should be - normal is 16 - {"cameraHorzOffset", VFOFS(cameraHorzOffset), VF_FLOAT},//how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT},//a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, //third person camera FOV, default is 80 - {"cameraAlpha", VFOFS(cameraAlpha), VF_FLOAT}, //fade out the vehicle to this alpha (0.1-1.0f) if it's in the way of the crosshair - {"cameraPitchDependantVertOffset", VFOFS(cameraPitchDependantVertOffset), VF_BOOL}, //use the hacky AT-ST pitch dependant vertical offset -//===TURRETS=========================================================================== - //Turret 1 + // other misc stats + {"gravity", VFOFS(gravity), VF_INT}, // normal is 800 + {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, // if 0, it's a ground vehicle + {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, // how hard it pushes off ground when less than hover height... causes "bounce", like shocks + {"waterProof", VFOFS(waterProof), VF_BOOL}, // can drive underwater if it has to + {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, // when in water, how high it floats (1 is neutral bouyancy) + {"fuelMax", VFOFS(fuelMax), VF_INT}, // how much fuel it can hold (capacity) + {"fuelRate", VFOFS(fuelRate), VF_INT}, // how quickly is uses up fuel + {"turboDuration", VFOFS(turboDuration), VF_INT}, // how long turbo lasts + {"turboRecharge", VFOFS(turboRecharge), VF_INT}, // how long turbo takes to recharge + {"visibility", VFOFS(visibility), VF_INT}, // for sight alerts + {"loudness", VFOFS(loudness), VF_INT}, // for sound alerts + {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT}, // range of explosion + {"explosionDamage", VFOFS(explosionDamage), VF_INT}, // damage of explosion + + // new stuff + {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). + {"hideRider", VFOFS(hideRider), VF_BOOL}, // rider (and passengers?) should not be drawn + {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL}, // if rider is on vehicle when it dies, they should die + {"flammable", VFOFS(flammable), VF_BOOL}, // whether or not the vehicle should catch on fire before it explodes + {"explosionDelay", VFOFS(explosionDelay), VF_INT}, // how long the vehicle should be on fire/dying before it explodes + // camera stuff + {"cameraOverride", VFOFS(cameraOverride), VF_BOOL}, // override the third person camera with the below values - normal is 0 (off) + {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, // how far back the camera should be - normal is 80 + {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT}, // how high over the vehicle origin the camera should be - normal is 16 + {"cameraHorzOffset", VFOFS(cameraHorzOffset), + VF_FLOAT}, // how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 + {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT}, // a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 + {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, // third person camera FOV, default is 80 + {"cameraAlpha", VFOFS(cameraAlpha), VF_FLOAT}, // fade out the vehicle to this alpha (0.1-1.0f) if it's in the way of the crosshair + {"cameraPitchDependantVertOffset", VFOFS(cameraPitchDependantVertOffset), VF_BOOL}, // use the hacky AT-ST pitch dependant vertical offset + //===TURRETS=========================================================================== + // Turret 1 {"turret1Weap", VFOFS(turret[0].iWeapon), VF_WEAPON}, {"turret1Delay", VFOFS(turret[0].iDelay), VF_INT}, {"turret1AmmoMax", VFOFS(turret[0].iAmmoMax), VF_INT}, @@ -662,20 +633,20 @@ vehField_t vehicleFields[] = {"turret1PitchBone", VFOFS(turret[0].pitchBone), VF_STRING}, {"turret1YawAxis", VFOFS(turret[0].yawAxis), VF_INT}, {"turret1PitchAxis", VFOFS(turret[0].pitchAxis), VF_INT}, - {"turret1ClampYawL", VFOFS(turret[0].yawClampLeft), VF_FLOAT}, //how far the turret is allowed to turn left - {"turret1ClampYawR", VFOFS(turret[0].yawClampRight), VF_FLOAT}, //how far the turret is allowed to turn right - {"turret1ClampPitchU", VFOFS(turret[0].pitchClampUp), VF_FLOAT}, //how far the turret is allowed to title up - {"turret1ClampPitchD", VFOFS(turret[0].pitchClampDown), VF_FLOAT}, //how far the turret is allowed to tilt down + {"turret1ClampYawL", VFOFS(turret[0].yawClampLeft), VF_FLOAT}, // how far the turret is allowed to turn left + {"turret1ClampYawR", VFOFS(turret[0].yawClampRight), VF_FLOAT}, // how far the turret is allowed to turn right + {"turret1ClampPitchU", VFOFS(turret[0].pitchClampUp), VF_FLOAT}, // how far the turret is allowed to title up + {"turret1ClampPitchD", VFOFS(turret[0].pitchClampDown), VF_FLOAT}, // how far the turret is allowed to tilt down {"turret1Muzzle1", VFOFS(turret[0].iMuzzle[0]), VF_INT}, {"turret1Muzzle2", VFOFS(turret[0].iMuzzle[1]), VF_INT}, {"turret1TurnSpeed", VFOFS(turret[0].fTurnSpeed), VF_FLOAT}, {"turret1AI", VFOFS(turret[0].bAI), VF_BOOL}, {"turret1AILead", VFOFS(turret[0].bAILead), VF_BOOL}, {"turret1AIRange", VFOFS(turret[0].fAIRange), VF_FLOAT}, - {"turret1PassengerNum", VFOFS(turret[0].passengerNum), VF_INT},//which number passenger can control this turret + {"turret1PassengerNum", VFOFS(turret[0].passengerNum), VF_INT}, // which number passenger can control this turret {"turret1GunnerViewTag", VFOFS(turret[0].gunnerViewTag), VF_STRING}, - //Turret 2 + // Turret 2 {"turret2Weap", VFOFS(turret[1].iWeapon), VF_WEAPON}, {"turret2Delay", VFOFS(turret[1].iDelay), VF_INT}, {"turret2AmmoMax", VFOFS(turret[1].iAmmoMax), VF_INT}, @@ -684,367 +655,345 @@ vehField_t vehicleFields[] = {"turret2PitchBone", VFOFS(turret[1].pitchBone), VF_STRING}, {"turret2YawAxis", VFOFS(turret[1].yawAxis), VF_INT}, {"turret2PitchAxis", VFOFS(turret[1].pitchAxis), VF_INT}, - {"turret2ClampYawL", VFOFS(turret[1].yawClampLeft), VF_FLOAT}, //how far the turret is allowed to turn left - {"turret2ClampYawR", VFOFS(turret[1].yawClampRight), VF_FLOAT}, //how far the turret is allowed to turn right - {"turret2ClampPitchU", VFOFS(turret[1].pitchClampUp), VF_FLOAT}, //how far the turret is allowed to title up - {"turret2ClampPitchD", VFOFS(turret[1].pitchClampDown), VF_FLOAT}, //how far the turret is allowed to tilt down + {"turret2ClampYawL", VFOFS(turret[1].yawClampLeft), VF_FLOAT}, // how far the turret is allowed to turn left + {"turret2ClampYawR", VFOFS(turret[1].yawClampRight), VF_FLOAT}, // how far the turret is allowed to turn right + {"turret2ClampPitchU", VFOFS(turret[1].pitchClampUp), VF_FLOAT}, // how far the turret is allowed to title up + {"turret2ClampPitchD", VFOFS(turret[1].pitchClampDown), VF_FLOAT}, // how far the turret is allowed to tilt down {"turret2Muzzle1", VFOFS(turret[1].iMuzzle[0]), VF_INT}, {"turret2Muzzle2", VFOFS(turret[1].iMuzzle[1]), VF_INT}, {"turret2TurnSpeed", VFOFS(turret[1].fTurnSpeed), VF_FLOAT}, {"turret2AI", VFOFS(turret[1].bAI), VF_BOOL}, {"turret2AILead", VFOFS(turret[1].bAILead), VF_BOOL}, {"turret2AIRange", VFOFS(turret[1].fAIRange), VF_FLOAT}, - {"turret2PassengerNum", VFOFS(turret[1].passengerNum), VF_INT},//which number passenger can control this turret + {"turret2PassengerNum", VFOFS(turret[1].passengerNum), VF_INT}, // which number passenger can control this turret {"turret2GunnerViewTag", VFOFS(turret[1].gunnerViewTag), VF_STRING}, -//===END TURRETS=========================================================================== + //===END TURRETS=========================================================================== }; -static const size_t numVehicleFields = ARRAY_LEN( vehicleFields ); - -stringID_table_t VehicleTable[VH_NUM_VEHICLES+1] = -{ - ENUM2STRING(VH_NONE), - ENUM2STRING(VH_WALKER), //something you ride inside of, it walks like you, like an AT-ST - ENUM2STRING(VH_FIGHTER), //something you fly inside of, like an X-Wing or TIE fighter - ENUM2STRING(VH_SPEEDER), //something you ride on that hovers, like a speeder or swoop - ENUM2STRING(VH_ANIMAL), //animal you ride on top of that walks, like a tauntaun - ENUM2STRING(VH_FLIER), //animal you ride on top of that flies, like a giant mynoc? - { 0, -1 } -}; +static const size_t numVehicleFields = ARRAY_LEN(vehicleFields); + +stringID_table_t VehicleTable[VH_NUM_VEHICLES + 1] = {ENUM2STRING(VH_NONE), + ENUM2STRING(VH_WALKER), // something you ride inside of, it walks like you, like an AT-ST + ENUM2STRING(VH_FIGHTER), // something you fly inside of, like an X-Wing or TIE fighter + ENUM2STRING(VH_SPEEDER), // something you ride on that hovers, like a speeder or swoop + ENUM2STRING(VH_ANIMAL), // animal you ride on top of that walks, like a tauntaun + ENUM2STRING(VH_FLIER), // animal you ride on top of that flies, like a giant mynoc? + {0, -1}}; // Setup the shared functions (one's that all vehicles would generally use). -void BG_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +void BG_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef QAGAME - //only do the whole thing if we're on game + // only do the whole thing if we're on game G_SetSharedVehicleFunctions(pVehInfo); #endif #ifndef WE_ARE_IN_THE_UI - switch( pVehInfo->type ) - { - case VH_SPEEDER: - G_SetSpeederVehicleFunctions( pVehInfo ); - break; - case VH_ANIMAL: - G_SetAnimalVehicleFunctions( pVehInfo ); - break; - case VH_FIGHTER: - G_SetFighterVehicleFunctions( pVehInfo ); - break; - case VH_WALKER: - G_SetWalkerVehicleFunctions( pVehInfo ); - break; - default: - break; + switch (pVehInfo->type) { + case VH_SPEEDER: + G_SetSpeederVehicleFunctions(pVehInfo); + break; + case VH_ANIMAL: + G_SetAnimalVehicleFunctions(pVehInfo); + break; + case VH_FIGHTER: + G_SetFighterVehicleFunctions(pVehInfo); + break; + case VH_WALKER: + G_SetWalkerVehicleFunctions(pVehInfo); + break; + default: + break; } #endif } -void BG_VehicleSetDefaults( vehicleInfo_t *vehicle ) -{ +void BG_VehicleSetDefaults(vehicleInfo_t *vehicle) { memset(vehicle, 0, sizeof(vehicleInfo_t)); -/* -#if _JK2MP - if (!vehicle->name) - { - vehicle->name = (char *)BG_Alloc(1024); - } - strcpy(vehicle->name, "default"); -#else - vehicle->name = G_NewString( "default" ); -#endif - - //general data - vehicle->type = VH_SPEEDER; //what kind of vehicle - //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player - vehicle->numHands = 0; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - vehicle->lookPitch = 0; //How far you can look up and down off the forward of the vehicle - vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle - vehicle->length = 0; //how long it is - used for body length traces when turning/moving? - vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? - vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? - VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - note: these are DESIRED speed, not actual current speed/velocity - vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed - vehicle->turboSpeed = 0; //turboBoost - vehicle->speedMin = 0; //if < 0, can go in reverse - vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given - vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed - vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) - vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle - vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) - vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side - vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward - vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) - vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn - vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving - vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity - vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own - vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control - - //durability stats - vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) - vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take - vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning - - //visuals & sounds - //vehicle->model = "models/map_objects/ships/swoop.md3"; //what model to use - if make it an NPC's primary model, don't need this? - if (!vehicle->model) - { - vehicle->model = (char *)BG_Alloc(1024); - } - strcpy(vehicle->model, "models/map_objects/ships/swoop.md3"); - - vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level - vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? - vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses - - vehicle->soundOn = NULL; //sound to play when get on it - vehicle->soundLoop = NULL; //sound to loop while riding it - vehicle->soundOff = NULL; //sound to play when get off - vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) - vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) - vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->wakeFX = NULL; //effect itmakes when going across water - - //other misc stats - vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 - vehicle->hoverHeight = 0;//VEH_DEFAULT_HOVER_HEIGHT; //if 0, it's a ground vehicle - vehicle->hoverStrength = 0;//VEH_DEFAULT_HOVER_STRENGTH;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks - vehicle->waterProof = qtrue; //can drive underwater if it has to - vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) - vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) - vehicle->fuelRate = 1; //how quickly is uses up fuel - vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts - vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts - vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; - vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; - vehicle->maxPassengers = 0; - - //new stuff - vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn - vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die - vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes - vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes - //camera stuff - vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values - vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 - vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 - vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80 - vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair -*/ + /* + #if _JK2MP + if (!vehicle->name) + { + vehicle->name = (char *)BG_Alloc(1024); + } + strcpy(vehicle->name, "default"); + #else + vehicle->name = G_NewString( "default" ); + #endif + + //general data + vehicle->type = VH_SPEEDER; //what kind of vehicle + //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player + vehicle->numHands = 0; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + vehicle->lookPitch = 0; //How far you can look up and down off the forward of the vehicle + vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle + vehicle->length = 0; //how long it is - used for body length traces when turning/moving? + vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? + vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? + VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is + all the way forward) + + //speed stats - note: these are DESIRED speed, not actual current speed/velocity + vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed + vehicle->turboSpeed = 0; //turboBoost + vehicle->speedMin = 0; //if < 0, can go in reverse + vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given + vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed + vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) + vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle + vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going + forward, 0.5 is half, 0 is no strafing + + //handling stats + vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) + vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side + vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward + vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) + vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn + vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving + vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity + vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own + vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control + + //durability stats + vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) + vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take + vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher + materials/construction vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning + + //visuals & sounds + //vehicle->model = "models/map_objects/ships/swoop.md3"; //what model to use - if make it an NPC's primary model, don't need this? + if (!vehicle->model) + { + vehicle->model = (char *)BG_Alloc(1024); + } + strcpy(vehicle->model, "models/map_objects/ships/swoop.md3"); + + vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level + vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? + vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses + + vehicle->soundOn = NULL; //sound to play when get on it + vehicle->soundLoop = NULL; //sound to loop while riding it + vehicle->soundOff = NULL; //sound to play when get off + vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) + vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) + vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->wakeFX = NULL; //effect itmakes when going across water + + //other misc stats + vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 + vehicle->hoverHeight = 0;//VEH_DEFAULT_HOVER_HEIGHT; //if 0, it's a ground vehicle + vehicle->hoverStrength = 0;//VEH_DEFAULT_HOVER_STRENGTH;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks + vehicle->waterProof = qtrue; //can drive underwater if it has to + vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) + vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) + vehicle->fuelRate = 1; //how quickly is uses up fuel + vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts + vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts + vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; + vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; + vehicle->maxPassengers = 0; + + //new stuff + vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn + vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die + vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes + vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes + //camera stuff + vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values + vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 + vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 + vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal + is 0 vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 vehicle->cameraFOV = + 0.0f; //third person camera FOV, default is 80 + vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair + */ } -void BG_VehicleClampData( vehicleInfo_t *vehicle ) -{//sanity check and clamp the vehicle's data - int i; +void BG_VehicleClampData(vehicleInfo_t *vehicle) { // sanity check and clamp the vehicle's data + int i; - for ( i = 0; i < 3; i++ ) - { - if ( vehicle->centerOfGravity[i] > 1.0f ) - { + for (i = 0; i < 3; i++) { + if (vehicle->centerOfGravity[i] > 1.0f) { vehicle->centerOfGravity[i] = 1.0f; - } - else if ( vehicle->centerOfGravity[i] < -1.0f ) - { + } else if (vehicle->centerOfGravity[i] < -1.0f) { vehicle->centerOfGravity[i] = -1.0f; } } // Validate passenger max. - if ( vehicle->maxPassengers > VEH_MAX_PASSENGERS ) - { + if (vehicle->maxPassengers > VEH_MAX_PASSENGERS) { vehicle->maxPassengers = VEH_MAX_PASSENGERS; - } - else if ( vehicle->maxPassengers < 0 ) - { + } else if (vehicle->maxPassengers < 0) { vehicle->maxPassengers = 0; } } -static vehField_t *FindVehicleParm( const char *parmName ) -{ +static vehField_t *FindVehicleParm(const char *parmName) { size_t i; - for ( i = 0; itype ) - { + switch (vehField->type) { case VF_IGNORE: break; case VF_INT: - *(int *)(b+vehField->ofs) = atoi(value); + *(int *)(b + vehField->ofs) = atoi(value); break; case VF_FLOAT: - *(float *)(b+vehField->ofs) = atof(value); + *(float *)(b + vehField->ofs) = atof(value); break; - case VF_STRING: // string on disk, pointer in memory - if (!*(char **)(b+vehField->ofs)) - { //just use 128 bytes in case we want to write over the string + case VF_STRING: // string on disk, pointer in memory + if (!*(char **)(b + vehField->ofs)) { // just use 128 bytes in case we want to write over the string #ifdef _JK2MP - *(char **)(b+vehField->ofs) = (char *)BG_Alloc(128);//(char *)BG_Alloc(strlen(value)); - strcpy(*(char **)(b+vehField->ofs), value); + *(char **)(b + vehField->ofs) = (char *)BG_Alloc(128); //(char *)BG_Alloc(strlen(value)); + strcpy(*(char **)(b + vehField->ofs), value); #else - (*(char **)(b+vehField->ofs)) = G_NewString( value ); + (*(char **)(b + vehField->ofs)) = G_NewString(value); #endif } break; case VF_VECTOR: - _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - //assert(_iFieldsRead==3 ); - if (_iFieldsRead!=3) - { - Com_Printf (S_COLOR_YELLOW"BG_ParseVehicleParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); - VectorClear( vec ); + _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + // assert(_iFieldsRead==3 ); + if (_iFieldsRead != 3) { + Com_Printf(S_COLOR_YELLOW "BG_ParseVehicleParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + VectorClear(vec); } - ((float *)(b+vehField->ofs))[0] = vec[0]; - ((float *)(b+vehField->ofs))[1] = vec[1]; - ((float *)(b+vehField->ofs))[2] = vec[2]; + ((float *)(b + vehField->ofs))[0] = vec[0]; + ((float *)(b + vehField->ofs))[1] = vec[1]; + ((float *)(b + vehField->ofs))[2] = vec[2]; break; case VF_BOOL: - *(qboolean *)(b+vehField->ofs) = (qboolean)(atof(value)!=0); + *(qboolean *)(b + vehField->ofs) = (qboolean)(atof(value) != 0); break; case VF_VEHTYPE: - vehType = (vehicleType_t)GetIDForString( VehicleTable, value ); - *(vehicleType_t *)(b+vehField->ofs) = vehType; - break; - case VF_ANIM: - { - int anim = GetIDForString( animTable, value ); - *(int *)(b+vehField->ofs) = anim; - } + vehType = (vehicleType_t)GetIDForString(VehicleTable, value); + *(vehicleType_t *)(b + vehField->ofs) = vehType; break; - case VF_WEAPON: // take string, resolve into index into VehWeaponParms - *(int *)(b+vehField->ofs) = VEH_VehWeaponIndexForName( value ); + case VF_ANIM: { + int anim = GetIDForString(animTable, value); + *(int *)(b + vehField->ofs) = anim; + } break; + case VF_WEAPON: // take string, resolve into index into VehWeaponParms + *(int *)(b + vehField->ofs) = VEH_VehWeaponIndexForName(value); break; - case VF_MODEL: // take the string, get the G_ModelIndex + case VF_MODEL: // take the string, get the G_ModelIndex #ifdef QAGAME - *(int *)(b+vehField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehField->ofs) = G_ModelIndex(value); #else - *(int *)(b+vehField->ofs) = trap_R_RegisterModel( value ); + *(int *)(b + vehField->ofs) = trap_R_RegisterModel(value); #endif break; - case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex + case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex #ifndef _JK2MP - *(int *)(b+vehField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehField->ofs) = G_ModelIndex(value); #elif defined QAGAME - //*(int *)(b+vehField->ofs) = G_ModelIndex( value ); + //*(int *)(b+vehField->ofs) = G_ModelIndex( value ); #else - *(int *)(b+vehField->ofs) = trap_R_RegisterModel( value ); + *(int *)(b + vehField->ofs) = trap_R_RegisterModel(value); #endif break; - case VF_EFFECT: // take the string, get the G_EffectIndex + case VF_EFFECT: // take the string, get the G_EffectIndex #ifdef QAGAME - *(int *)(b+vehField->ofs) = G_EffectIndex( value ); + *(int *)(b + vehField->ofs) = G_EffectIndex(value); #elif defined CGAME - *(int *)(b+vehField->ofs) = trap_FX_RegisterEffect( value ); + *(int *)(b + vehField->ofs) = trap_FX_RegisterEffect(value); #endif break; - case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the G_EffectIndex + case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the G_EffectIndex #ifndef _JK2MP - *(int *)(b+vehField->ofs) = G_EffectIndex( value ); + *(int *)(b + vehField->ofs) = G_EffectIndex(value); #elif defined QAGAME - //*(int *)(b+vehField->ofs) = G_EffectIndex( value ); + //*(int *)(b+vehField->ofs) = G_EffectIndex( value ); #elif defined CGAME - *(int *)(b+vehField->ofs) = trap_FX_RegisterEffect( value ); + *(int *)(b + vehField->ofs) = trap_FX_RegisterEffect(value); #endif break; - case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader + case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader #ifdef WE_ARE_IN_THE_UI - *(int *)(b+vehField->ofs) = trap_R_RegisterShaderNoMip( value ); + *(int *)(b + vehField->ofs) = trap_R_RegisterShaderNoMip(value); #elif defined CGAME - *(int *)(b+vehField->ofs) = trap_R_RegisterShader( value ); + *(int *)(b + vehField->ofs) = trap_R_RegisterShader(value); #endif break; - case VF_SHADER_NOMIP:// (cgame only) take the string, call trap_R_RegisterShaderNoMip + case VF_SHADER_NOMIP: // (cgame only) take the string, call trap_R_RegisterShaderNoMip #ifndef QAGAME - *(int *)(b+vehField->ofs) = trap_R_RegisterShaderNoMip( value ); + *(int *)(b + vehField->ofs) = trap_R_RegisterShaderNoMip(value); #endif break; - case VF_SOUND: // take the string, get the G_SoundIndex + case VF_SOUND: // take the string, get the G_SoundIndex #ifdef QAGAME - *(int *)(b+vehField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehField->ofs) = G_SoundIndex(value); #else - *(int *)(b+vehField->ofs) = trap_S_RegisterSound( value ); + *(int *)(b + vehField->ofs) = trap_S_RegisterSound(value); #endif break; - case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the G_SoundIndex + case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the G_SoundIndex #ifndef _JK2MP - *(int *)(b+vehField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehField->ofs) = G_SoundIndex(value); #elif defined QAGAME - //*(int *)(b+vehField->ofs) = G_SoundIndex( value ); + //*(int *)(b+vehField->ofs) = G_SoundIndex( value ); #else - *(int *)(b+vehField->ofs) = trap_S_RegisterSound( value ); + *(int *)(b + vehField->ofs) = trap_S_RegisterSound(value); #endif break; default: - //Unknown type? + // Unknown type? return qfalse; } return qtrue; } -int VEH_LoadVehicle( const char *vehicleName ) -{//load up specified vehicle and save in array: g_vehicleInfo - const char *token; - //we'll assume that no parm name is longer than 128 - char parmName[128] = { 0 }; - char weap1[128] = { 0 }, weap2[128] = { 0 }; - char weapMuzzle1[128] = { 0 }; - char weapMuzzle2[128] = { 0 }; - char weapMuzzle3[128] = { 0 }; - char weapMuzzle4[128] = { 0 }; - char weapMuzzle5[128] = { 0 }; - char weapMuzzle6[128] = { 0 }; - char weapMuzzle7[128] = { 0 }; - char weapMuzzle8[128] = { 0 }; - char weapMuzzle9[128] = { 0 }; - char weapMuzzle10[128] = { 0 }; - char *value = NULL; - const char *p = NULL; - vehicleInfo_t *vehicle = NULL; +int VEH_LoadVehicle(const char *vehicleName) { // load up specified vehicle and save in array: g_vehicleInfo + const char *token; + // we'll assume that no parm name is longer than 128 + char parmName[128] = {0}; + char weap1[128] = {0}, weap2[128] = {0}; + char weapMuzzle1[128] = {0}; + char weapMuzzle2[128] = {0}; + char weapMuzzle3[128] = {0}; + char weapMuzzle4[128] = {0}; + char weapMuzzle5[128] = {0}; + char weapMuzzle6[128] = {0}; + char weapMuzzle7[128] = {0}; + char weapMuzzle8[128] = {0}; + char weapMuzzle9[128] = {0}; + char weapMuzzle10[128] = {0}; + char *value = NULL; + const char *p = NULL; + vehicleInfo_t *vehicle = NULL; // Load the vehicle parms if no vehicles have been loaded yet. - if ( numVehicles == 0 ) - { + if (numVehicles == 0) { BG_VehicleLoadParms(); } - //try to parse data out + // try to parse data out p = VehicleParms; #ifdef _JK2MP @@ -1055,409 +1004,338 @@ int VEH_LoadVehicle( const char *vehicleName ) vehicle = &g_vehicleInfo[numVehicles]; // look for the right vehicle - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return VEHICLE_NONE; } - if ( !Q_stricmp( token, vehicleName ) ) - { + if (!Q_stricmp(token, vehicleName)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return VEHICLE_NONE; } - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//barf - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // barf + COM_EndParseSession(); return VEHICLE_NONE; } - if ( Q_stricmp( token, "{" ) != 0 ) - { - COM_EndParseSession( ); + if (Q_stricmp(token, "{") != 0) { + COM_EndParseSession(); return VEHICLE_NONE; } - BG_VehicleSetDefaults( vehicle ); + BG_VehicleSetDefaults(vehicle); // parse the vehicle info block - while ( 1 ) - { - SkipRestOfLine( &p ); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing Vehicle '%s'\n", vehicleName ); - COM_EndParseSession( ); + while (1) { + SkipRestOfLine(&p); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing Vehicle '%s'\n", vehicleName); + COM_EndParseSession(); return VEHICLE_NONE; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - Q_strncpyz( parmName, token, sizeof(parmName) ); - value = COM_ParseExt( &p, qtrue ); - if ( !value || !value[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Vehicle token '%s' has no value!\n", parmName ); - } - else if ( Q_stricmp( "weap1", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weap1, value, sizeof(weap1) ); - } - else if ( Q_stricmp( "weap2", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weap2, value, sizeof(weap2) ); - } - else if ( Q_stricmp( "weapMuzzle1", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle1, value, sizeof(weapMuzzle1) ); - } - else if ( Q_stricmp( "weapMuzzle2", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle2, value, sizeof(weapMuzzle2) ); - } - else if ( Q_stricmp( "weapMuzzle3", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle3, value, sizeof(weapMuzzle3) ); - } - else if ( Q_stricmp( "weapMuzzle4", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle4, value, sizeof(weapMuzzle4) ); - } - else if ( Q_stricmp( "weapMuzzle5", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle5, value, sizeof(weapMuzzle5) ); - } - else if ( Q_stricmp( "weapMuzzle6", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle6, value, sizeof(weapMuzzle6) ); - } - else if ( Q_stricmp( "weapMuzzle7", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle7, value, sizeof(weapMuzzle7) ); - } - else if ( Q_stricmp( "weapMuzzle8", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle8, value, sizeof(weapMuzzle8) ); - } - else if ( Q_stricmp( "weapMuzzle9", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle9, value, sizeof(weapMuzzle9) ); - } - else if ( Q_stricmp( "weapMuzzle10", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle10, value, sizeof(weapMuzzle10) ); - } - else - { - if ( !BG_ParseVehicleParm( vehicle, parmName, value ) ) - { + Q_strncpyz(parmName, token, sizeof(parmName)); + value = COM_ParseExt(&p, qtrue); + if (!value || !value[0]) { + Com_Printf(S_COLOR_RED "ERROR: Vehicle token '%s' has no value!\n", parmName); + } else if (Q_stricmp("weap1", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weap1, value, sizeof(weap1)); + } else if (Q_stricmp("weap2", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weap2, value, sizeof(weap2)); + } else if (Q_stricmp("weapMuzzle1", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle1, value, sizeof(weapMuzzle1)); + } else if (Q_stricmp("weapMuzzle2", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle2, value, sizeof(weapMuzzle2)); + } else if (Q_stricmp("weapMuzzle3", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle3, value, sizeof(weapMuzzle3)); + } else if (Q_stricmp("weapMuzzle4", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle4, value, sizeof(weapMuzzle4)); + } else if (Q_stricmp("weapMuzzle5", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle5, value, sizeof(weapMuzzle5)); + } else if (Q_stricmp("weapMuzzle6", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle6, value, sizeof(weapMuzzle6)); + } else if (Q_stricmp("weapMuzzle7", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle7, value, sizeof(weapMuzzle7)); + } else if (Q_stricmp("weapMuzzle8", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle8, value, sizeof(weapMuzzle8)); + } else if (Q_stricmp("weapMuzzle9", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle9, value, sizeof(weapMuzzle9)); + } else if (Q_stricmp("weapMuzzle10", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle10, value, sizeof(weapMuzzle10)); + } else { + if (!BG_ParseVehicleParm(vehicle, parmName, value)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair '%s', '%s'!\n", parmName, value ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair '%s', '%s'!\n", parmName, value); #endif } } } - //NOW: if we have any weapons, go ahead and load them - if ( weap1[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weap1", weap1 ) ) - { + // NOW: if we have any weapons, go ahead and load them + if (weap1[0]) { + if (!BG_ParseVehicleParm(vehicle, "weap1", weap1)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weap1', '%s'!\n", weap1 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weap1', '%s'!\n", weap1); #endif } } - if ( weap2[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weap2", weap2 ) ) - { + if (weap2[0]) { + if (!BG_ParseVehicleParm(vehicle, "weap2", weap2)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weap2', '%s'!\n", weap2 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weap2', '%s'!\n", weap2); #endif } } - if ( weapMuzzle1[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle1", weapMuzzle1 ) ) - { + if (weapMuzzle1[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle1", weapMuzzle1)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle1', '%s'!\n", weapMuzzle1 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle1', '%s'!\n", weapMuzzle1); #endif } } - if ( weapMuzzle2[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle2", weapMuzzle2 ) ) - { + if (weapMuzzle2[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle2", weapMuzzle2)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle2', '%s'!\n", weapMuzzle2 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle2', '%s'!\n", weapMuzzle2); #endif } } - if ( weapMuzzle3[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle3", weapMuzzle3 ) ) - { + if (weapMuzzle3[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle3", weapMuzzle3)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle3', '%s'!\n", weapMuzzle3 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle3', '%s'!\n", weapMuzzle3); #endif } } - if ( weapMuzzle4[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle4", weapMuzzle4 ) ) - { + if (weapMuzzle4[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle4", weapMuzzle4)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle4', '%s'!\n", weapMuzzle4 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle4', '%s'!\n", weapMuzzle4); #endif } } - if ( weapMuzzle5[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle5", weapMuzzle5 ) ) - { + if (weapMuzzle5[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle5", weapMuzzle5)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle5', '%s'!\n", weapMuzzle5 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle5', '%s'!\n", weapMuzzle5); #endif } } - if ( weapMuzzle6[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle6", weapMuzzle6 ) ) - { + if (weapMuzzle6[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle6", weapMuzzle6)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle6', '%s'!\n", weapMuzzle6 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle6', '%s'!\n", weapMuzzle6); #endif } } - if ( weapMuzzle7[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle7", weapMuzzle7 ) ) - { + if (weapMuzzle7[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle7", weapMuzzle7)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle7', '%s'!\n", weapMuzzle7 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle7', '%s'!\n", weapMuzzle7); #endif } } - if ( weapMuzzle8[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle8", weapMuzzle8 ) ) - { + if (weapMuzzle8[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle8", weapMuzzle8)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle8', '%s'!\n", weapMuzzle8 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle8', '%s'!\n", weapMuzzle8); #endif } } - if ( weapMuzzle9[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle9", weapMuzzle9 ) ) - { + if (weapMuzzle9[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle9", weapMuzzle9)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle9', '%s'!\n", weapMuzzle9 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle9', '%s'!\n", weapMuzzle9); #endif } } - if ( weapMuzzle10[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle10", weapMuzzle10 ) ) - { + if (weapMuzzle10[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle10", weapMuzzle10)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle10', '%s'!\n", weapMuzzle10 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle10', '%s'!\n", weapMuzzle10); #endif } } - COM_EndParseSession( ); + COM_EndParseSession(); #ifdef _JK2MP - //let's give these guys some defaults - if (!vehicle->health_front) - { - vehicle->health_front = vehicle->armor/4; + // let's give these guys some defaults + if (!vehicle->health_front) { + vehicle->health_front = vehicle->armor / 4; } - if (!vehicle->health_back) - { - vehicle->health_back = vehicle->armor/4; + if (!vehicle->health_back) { + vehicle->health_back = vehicle->armor / 4; } - if (!vehicle->health_right) - { - vehicle->health_right = vehicle->armor/4; + if (!vehicle->health_right) { + vehicle->health_right = vehicle->armor / 4; } - if (!vehicle->health_left) - { - vehicle->health_left = vehicle->armor/4; + if (!vehicle->health_left) { + vehicle->health_left = vehicle->armor / 4; } #endif - if ( vehicle->model ) - { + if (vehicle->model) { #ifdef QAGAME - vehicle->modelIndex = G_ModelIndex( va( "models/players/%s/model.glm", vehicle->model ) ); + vehicle->modelIndex = G_ModelIndex(va("models/players/%s/model.glm", vehicle->model)); #else - vehicle->modelIndex = trap_R_RegisterModel( va( "models/players/%s/model.glm", vehicle->model ) ); + vehicle->modelIndex = trap_R_RegisterModel(va("models/players/%s/model.glm", vehicle->model)); #endif } #ifndef _JK2MP - //SP - if ( vehicle->skin - && vehicle->skin[0] ) - { - ratl::string_vs<256> skins(vehicle->skin); - for (ratl::string_vs<256>::tokenizer i = skins.begin("|"); i!=skins.end(); i++) - { - //this will just turn off surfs if there is a *off shader on a surf, the skin will actually get thrown away when cgame starts - gi.RE_RegisterSkin( va( "models/players/%s/model_%s.skin", vehicle->model, *i) ); - //this is for the server-side call, it will propgate down to cgame with configstrings and register it at the same time as all the other skins for ghoul2 models - G_SkinIndex( va( "models/players/%s/model_%s.skin", vehicle->model, *i) ); + // SP + if (vehicle->skin && vehicle->skin[0]) { + ratl::string_vs<256> skins(vehicle->skin); + for (ratl::string_vs<256>::tokenizer i = skins.begin("|"); i != skins.end(); i++) { + // this will just turn off surfs if there is a *off shader on a surf, the skin will actually get thrown away when cgame starts + gi.RE_RegisterSkin(va("models/players/%s/model_%s.skin", vehicle->model, *i)); + // this is for the server-side call, it will propgate down to cgame with configstrings and register it at the same time as all the other skins for + // ghoul2 models + G_SkinIndex(va("models/players/%s/model_%s.skin", vehicle->model, *i)); } - } - else - { - //this will just turn off surfs if there is a *off shader on a surf, the skin will actually get thrown away when cgame starts - gi.RE_RegisterSkin( va( "models/players/%s/model_default.skin", vehicle->model) ); - //this is for the server-side call, it will propgate down to cgame with configstrings and register it at the same time as all the other skins for ghoul2 models - G_SkinIndex( va( "models/players/%s/model_default.skin", vehicle->model) ); + } else { + // this will just turn off surfs if there is a *off shader on a surf, the skin will actually get thrown away when cgame starts + gi.RE_RegisterSkin(va("models/players/%s/model_default.skin", vehicle->model)); + // this is for the server-side call, it will propgate down to cgame with configstrings and register it at the same time as all the other skins for + // ghoul2 models + G_SkinIndex(va("models/players/%s/model_default.skin", vehicle->model)); } #else #ifndef QAGAME - if ( vehicle->skin - && vehicle->skin[0] ) - { - trap_R_RegisterSkin( va( "models/players/%s/model_%s.skin", vehicle->model, vehicle->skin) ); + if (vehicle->skin && vehicle->skin[0]) { + trap_R_RegisterSkin(va("models/players/%s/model_%s.skin", vehicle->model, vehicle->skin)); } #endif #endif - //sanity check and clamp the vehicle's data - BG_VehicleClampData( vehicle ); + // sanity check and clamp the vehicle's data + BG_VehicleClampData(vehicle); // Setup the shared function pointers. - BG_SetSharedVehicleFunctions( vehicle ); - //misc effects... FIXME: not even used in MP, are they? - if ( vehicle->explosionDamage ) - { + BG_SetSharedVehicleFunctions(vehicle); + // misc effects... FIXME: not even used in MP, are they? + if (vehicle->explosionDamage) { #ifdef QAGAME - G_EffectIndex( "ships/ship_explosion_mark" ); + G_EffectIndex("ships/ship_explosion_mark"); #elif defined CGAME - trap_FX_RegisterEffect( "ships/ship_explosion_mark" ); + trap_FX_RegisterEffect("ships/ship_explosion_mark"); #endif } - if ( vehicle->flammable ) - { + if (vehicle->flammable) { #ifdef QAGAME - G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); + G_SoundIndex("sound/vehicles/common/fire_lp.wav"); #elif defined CGAME - trap_S_RegisterSound( "sound/vehicles/common/fire_lp.wav" ); + trap_S_RegisterSound("sound/vehicles/common/fire_lp.wav"); #else - trap_S_RegisterSound( "sound/vehicles/common/fire_lp.wav" ); + trap_S_RegisterSound("sound/vehicles/common/fire_lp.wav"); #endif } - if ( vehicle->hoverHeight > 0 ) - { + if (vehicle->hoverHeight > 0) { #ifndef _JK2MP - G_EffectIndex( "ships/swoop_dust" ); + G_EffectIndex("ships/swoop_dust"); #elif defined QAGAME - G_EffectIndex( "ships/swoop_dust" ); + G_EffectIndex("ships/swoop_dust"); #elif defined CGAME - trap_FX_RegisterEffect( "ships/swoop_dust" ); + trap_FX_RegisterEffect("ships/swoop_dust"); #endif } #ifdef QAGAME - G_EffectIndex( "volumetric/black_smoke" ); - G_EffectIndex( "ships/fire" ); - G_SoundIndex( "sound/vehicles/common/release.wav" ); + G_EffectIndex("volumetric/black_smoke"); + G_EffectIndex("ships/fire"); + G_SoundIndex("sound/vehicles/common/release.wav"); #elif defined CGAME - trap_R_RegisterShader( "gfx/menus/radar/bracket" ); - trap_R_RegisterShader( "gfx/menus/radar/lead" ); - trap_R_RegisterShaderNoMip( "gfx/menus/radar/asteroid" ); - trap_S_RegisterSound( "sound/vehicles/common/impactalarm.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/linkweaps.wav" ); - trap_S_RegisterSound( "sound/vehicles/common/release.wav" ); + trap_R_RegisterShader("gfx/menus/radar/bracket"); + trap_R_RegisterShader("gfx/menus/radar/lead"); + trap_R_RegisterShaderNoMip("gfx/menus/radar/asteroid"); + trap_S_RegisterSound("sound/vehicles/common/impactalarm.wav"); + trap_S_RegisterSound("sound/vehicles/common/linkweaps.wav"); + trap_S_RegisterSound("sound/vehicles/common/release.wav"); trap_FX_RegisterEffect("effects/ships/dest_burning.efx"); trap_FX_RegisterEffect("effects/ships/dest_destroyed.efx"); - trap_FX_RegisterEffect( "volumetric/black_smoke" ); - trap_FX_RegisterEffect( "ships/fire" ); + trap_FX_RegisterEffect("volumetric/black_smoke"); + trap_FX_RegisterEffect("ships/fire"); trap_FX_RegisterEffect("ships/hyperspace_stars"); - if ( vehicle->hideRider ) - { - trap_R_RegisterShaderNoMip( "gfx/menus/radar/circle_base" ); - trap_R_RegisterShaderNoMip( "gfx/menus/radar/circle_base_frame" ); - trap_R_RegisterShaderNoMip( "gfx/menus/radar/circle_base_shield" ); + if (vehicle->hideRider) { + trap_R_RegisterShaderNoMip("gfx/menus/radar/circle_base"); + trap_R_RegisterShaderNoMip("gfx/menus/radar/circle_base_frame"); + trap_R_RegisterShaderNoMip("gfx/menus/radar/circle_base_shield"); } #endif return (numVehicles++); } -int VEH_VehicleIndexForName( const char *vehicleName ) -{ +int VEH_VehicleIndexForName(const char *vehicleName) { int v; - if ( !vehicleName || !vehicleName[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Trying to read Vehicle with no name!\n" ); + if (!vehicleName || !vehicleName[0]) { + Com_Printf(S_COLOR_RED "ERROR: Trying to read Vehicle with no name!\n"); return VEHICLE_NONE; } - for ( v = VEHICLE_BASE; v < numVehicles; v++ ) - { - if ( g_vehicleInfo[v].name - && Q_stricmp( g_vehicleInfo[v].name, vehicleName ) == 0 ) - {//already loaded this one + for (v = VEHICLE_BASE; v < numVehicles; v++) { + if (g_vehicleInfo[v].name && Q_stricmp(g_vehicleInfo[v].name, vehicleName) == 0) { // already loaded this one return v; } } - //haven't loaded it yet - if ( v >= MAX_VEHICLES ) - {//no more room! - Com_Printf( S_COLOR_RED"ERROR: Too many Vehicles (max 64), aborting load on %s!\n", vehicleName ); + // haven't loaded it yet + if (v >= MAX_VEHICLES) { // no more room! + Com_Printf(S_COLOR_RED "ERROR: Too many Vehicles (max 64), aborting load on %s!\n", vehicleName); return VEHICLE_NONE; } - //we have room for another one, load it up and return the index - //HMM... should we not even load the .veh file until we want to? - v = VEH_LoadVehicle( vehicleName ); - if ( v == VEHICLE_NONE ) - { - Com_Printf( S_COLOR_RED"ERROR: Could not find Vehicle %s!\n", vehicleName ); + // we have room for another one, load it up and return the index + // HMM... should we not even load the .veh file until we want to? + v = VEH_LoadVehicle(vehicleName); + if (v == VEHICLE_NONE) { + Com_Printf(S_COLOR_RED "ERROR: Could not find Vehicle %s!\n", vehicleName); } return v; } -void BG_VehWeaponLoadParms( void ) -{ - int len, totallen, vehExtFNLen, mainBlockLen, fileCnt, i; - char *holdChar, *marker; - char vehWeaponExtensionListBuf[2048]; // The list of file names read in - fileHandle_t f; - char *tempReadBuffer; +void BG_VehWeaponLoadParms(void) { + int len, totallen, vehExtFNLen, mainBlockLen, fileCnt, i; + char *holdChar, *marker; + char vehWeaponExtensionListBuf[2048]; // The list of file names read in + fileHandle_t f; + char *tempReadBuffer; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = mainBlockLen = len; - marker = VehWeaponParms+totallen; + marker = VehWeaponParms + totallen; *marker = 0; - //now load in the extra .veh extensions + // now load in the extra .veh extensions #ifdef _JK2MP - fileCnt = trap_FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf) ); + fileCnt = trap_FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf)); #else - fileCnt = gi.FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf) ); + fileCnt = gi.FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf)); #endif holdChar = vehWeaponExtensionListBuf; @@ -1465,32 +1343,28 @@ void BG_VehWeaponLoadParms( void ) #ifdef _JK2MP tempReadBuffer = (char *)BG_TempAlloc(MAX_VEH_WEAPON_DATA_SIZE); #else - tempReadBuffer = (char *)gi.Malloc( MAX_VEH_WEAPON_DATA_SIZE, TAG_G_ALLOC, qtrue ); + tempReadBuffer = (char *)gi.Malloc(MAX_VEH_WEAPON_DATA_SIZE, TAG_G_ALLOC, qtrue); #endif // NOTE: Not use TempAlloc anymore... - //Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before - //the subsequent BG_TempFree or the pool will be screwed. + // Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before + // the subsequent BG_TempFree or the pool will be screwed. - for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 ) - { - vehExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1) { + vehExtFNLen = strlen(holdChar); -// Com_Printf( "Parsing %s\n", holdChar ); + // Com_Printf( "Parsing %s\n", holdChar ); #ifdef _JK2MP - len = trap_FS_FOpenFile(va( "ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); + len = trap_FS_FOpenFile(va("ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); #else -// len = gi.FS_ReadFile( va( "ext_data/vehicles/weapons/%s", holdChar), (void **) &buffer ); - len = gi.FS_FOpenFile(va( "ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); + // len = gi.FS_ReadFile( va( "ext_data/vehicles/weapons/%s", holdChar), (void **) &buffer ); + len = gi.FS_FOpenFile(va("ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); #endif - if ( len == -1 ) - { - Com_Printf( "error reading file\n" ); - } - else - { + if (len == -1) { + Com_Printf("error reading file\n"); + } else { #ifdef _JK2MP trap_FS_Read(tempReadBuffer, len, f); tempReadBuffer[len] = 0; @@ -1500,56 +1374,55 @@ void BG_VehWeaponLoadParms( void ) #endif // Don't let it end on a } because that should be a stand-alone token. - if ( totallen && *(marker-1) == '}' ) - { - strcat( marker, " " ); + if (totallen && *(marker - 1) == '}') { + strcat(marker, " "); totallen++; marker++; } - if ( totallen + len >= MAX_VEH_WEAPON_DATA_SIZE ) { - Com_Error(ERR_DROP, "Vehicle Weapon extensions (*.vwp) are too large" ); + if (totallen + len >= MAX_VEH_WEAPON_DATA_SIZE) { + Com_Error(ERR_DROP, "Vehicle Weapon extensions (*.vwp) are too large"); } - strcat( marker, tempReadBuffer ); + strcat(marker, tempReadBuffer); #ifdef _JK2MP - trap_FS_FCloseFile( f ); + trap_FS_FCloseFile(f); #else - gi.FS_FCloseFile( f ); + gi.FS_FCloseFile(f); #endif totallen += len; - marker = VehWeaponParms+totallen; + marker = VehWeaponParms + totallen; } } #ifdef _JK2MP BG_TempFree(MAX_VEH_WEAPON_DATA_SIZE); #else - gi.Free(tempReadBuffer); tempReadBuffer = NULL; + gi.Free(tempReadBuffer); + tempReadBuffer = NULL; #endif } -void BG_VehicleLoadParms( void ) -{//HMM... only do this if there's a vehicle on the level? - int len, totallen, vehExtFNLen, mainBlockLen, fileCnt, i; -// const char *filename = "ext_data/vehicles.dat"; - char *holdChar, *marker; - char vehExtensionListBuf[2048]; // The list of file names read in - fileHandle_t f; - char *tempReadBuffer; +void BG_VehicleLoadParms(void) { // HMM... only do this if there's a vehicle on the level? + int len, totallen, vehExtFNLen, mainBlockLen, fileCnt, i; + // const char *filename = "ext_data/vehicles.dat"; + char *holdChar, *marker; + char vehExtensionListBuf[2048]; // The list of file names read in + fileHandle_t f; + char *tempReadBuffer; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = mainBlockLen = len; - marker = VehicleParms+totallen; + marker = VehicleParms + totallen; *marker = 0; - //now load in the extra .veh extensions + // now load in the extra .veh extensions #ifdef _JK2MP - fileCnt = trap_FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf) ); + fileCnt = trap_FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf)); #else - fileCnt = gi.FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf) ); + fileCnt = gi.FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf)); #endif holdChar = vehExtensionListBuf; @@ -1557,32 +1430,28 @@ void BG_VehicleLoadParms( void ) #ifdef _JK2MP tempReadBuffer = (char *)BG_TempAlloc(MAX_VEHICLE_DATA_SIZE); #else - tempReadBuffer = (char *)gi.Malloc( MAX_VEHICLE_DATA_SIZE, TAG_G_ALLOC, qtrue ); + tempReadBuffer = (char *)gi.Malloc(MAX_VEHICLE_DATA_SIZE, TAG_G_ALLOC, qtrue); #endif // NOTE: Not use TempAlloc anymore... - //Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before - //the subsequent BG_TempFree or the pool will be screwed. + // Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before + // the subsequent BG_TempFree or the pool will be screwed. - for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 ) - { - vehExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1) { + vehExtFNLen = strlen(holdChar); -// Com_Printf( "Parsing %s\n", holdChar ); + // Com_Printf( "Parsing %s\n", holdChar ); #ifdef _JK2MP - len = trap_FS_FOpenFile(va( "ext_data/vehicles/%s", holdChar), &f, FS_READ); + len = trap_FS_FOpenFile(va("ext_data/vehicles/%s", holdChar), &f, FS_READ); #else -// len = gi.FS_ReadFile( va( "ext_data/vehicles/%s", holdChar), (void **) &buffer ); - len = gi.FS_FOpenFile(va( "ext_data/vehicles/%s", holdChar), &f, FS_READ); + // len = gi.FS_ReadFile( va( "ext_data/vehicles/%s", holdChar), (void **) &buffer ); + len = gi.FS_FOpenFile(va("ext_data/vehicles/%s", holdChar), &f, FS_READ); #endif - if ( len == -1 ) - { - Com_Printf( "error reading file\n" ); - } - else - { + if (len == -1) { + Com_Printf("error reading file\n"); + } else { #ifdef _JK2MP trap_FS_Read(tempReadBuffer, len, f); tempReadBuffer[len] = 0; @@ -1592,106 +1461,93 @@ void BG_VehicleLoadParms( void ) #endif // Don't let it end on a } because that should be a stand-alone token. - if ( totallen && *(marker-1) == '}' ) - { - strcat( marker, " " ); + if (totallen && *(marker - 1) == '}') { + strcat(marker, " "); totallen++; marker++; } - if ( totallen + len >= MAX_VEHICLE_DATA_SIZE ) { - Com_Error(ERR_DROP, "Vehicle extensions (*.veh) are too large" ); + if (totallen + len >= MAX_VEHICLE_DATA_SIZE) { + Com_Error(ERR_DROP, "Vehicle extensions (*.veh) are too large"); } - strcat( marker, tempReadBuffer ); + strcat(marker, tempReadBuffer); #ifdef _JK2MP - trap_FS_FCloseFile( f ); + trap_FS_FCloseFile(f); #else - gi.FS_FCloseFile( f ); + gi.FS_FCloseFile(f); #endif totallen += len; - marker = VehicleParms+totallen; + marker = VehicleParms + totallen; } } #ifdef _JK2MP BG_TempFree(MAX_VEHICLE_DATA_SIZE); #else - gi.Free(tempReadBuffer); tempReadBuffer = NULL; + gi.Free(tempReadBuffer); + tempReadBuffer = NULL; #endif - numVehicles = 1;//first one is null/default - //set the first vehicle to default data - BG_VehicleSetDefaults( &g_vehicleInfo[VEHICLE_BASE] ); - //sanity check and clamp the vehicle's data - BG_VehicleClampData( &g_vehicleInfo[VEHICLE_BASE] ); + numVehicles = 1; // first one is null/default + // set the first vehicle to default data + BG_VehicleSetDefaults(&g_vehicleInfo[VEHICLE_BASE]); + // sanity check and clamp the vehicle's data + BG_VehicleClampData(&g_vehicleInfo[VEHICLE_BASE]); // Setup the shared function pointers. - BG_SetSharedVehicleFunctions( &g_vehicleInfo[VEHICLE_BASE] ); + BG_SetSharedVehicleFunctions(&g_vehicleInfo[VEHICLE_BASE]); - //Load the Vehicle Weapons data, too + // Load the Vehicle Weapons data, too BG_VehWeaponLoadParms(); } -int BG_VehicleGetIndex( const char *vehicleName ) -{ - return (VEH_VehicleIndexForName( vehicleName )); -} +int BG_VehicleGetIndex(const char *vehicleName) { return (VEH_VehicleIndexForName(vehicleName)); } -//We get the vehicle name passed in as modelname -//with a $ in front of it. -//we are expected to then get the model for the -//vehicle and stomp over modelname with it. -void BG_GetVehicleModelName(char *modelname) -{ +// We get the vehicle name passed in as modelname +// with a $ in front of it. +// we are expected to then get the model for the +// vehicle and stomp over modelname with it. +void BG_GetVehicleModelName(char *modelname) { char *vehName = &modelname[1]; int vIndex = BG_VehicleGetIndex(vehName); assert(modelname[0] == '$'); - if (vIndex == VEHICLE_NONE) - { + if (vIndex == VEHICLE_NONE) { Com_Error(ERR_DROP, "BG_GetVehicleModelName: couldn't find vehicle %s", vehName); } - strcpy(modelname, g_vehicleInfo[vIndex].model); + strcpy(modelname, g_vehicleInfo[vIndex].model); } -void BG_GetVehicleSkinName(char *skinname) -{ +void BG_GetVehicleSkinName(char *skinname) { char *vehName = &skinname[1]; int vIndex = BG_VehicleGetIndex(vehName); assert(skinname[0] == '$'); - if (vIndex == VEHICLE_NONE) - { + if (vIndex == VEHICLE_NONE) { Com_Error(ERR_DROP, "BG_GetVehicleSkinName: couldn't find vehicle %s", vehName); } - if ( !g_vehicleInfo[vIndex].skin - || !g_vehicleInfo[vIndex].skin[0] ) - { + if (!g_vehicleInfo[vIndex].skin || !g_vehicleInfo[vIndex].skin[0]) { skinname[0] = 0; - } - else - { + } else { strcpy(skinname, g_vehicleInfo[vIndex].skin); } } #ifdef _JK2MP #ifndef WE_ARE_IN_THE_UI -//so cgame can assign the function pointer for the vehicle attachment without having to -//bother with all the other funcs that don't really exist cgame-side. +// so cgame can assign the function pointer for the vehicle attachment without having to +// bother with all the other funcs that don't really exist cgame-side. extern int BG_GetTime(void); extern int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName); -extern qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, - const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale); -void AttachRidersGeneric( Vehicle_t *pVeh ) -{ +extern qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale); +void AttachRidersGeneric(Vehicle_t *pVeh) { // If we have a pilot, attach him to the driver tag. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles; + vec3_t yawOnlyAngles; bgEntity_t *parent = pVeh->m_pParentEntity; bgEntity_t *pilot = pVeh->m_pPilot; int crotchBolt = trap_G2API_AddBolt(parent->ghoul2, 0, "*driver"); @@ -1701,10 +1557,9 @@ void AttachRidersGeneric( Vehicle_t *pVeh ) VectorSet(yawOnlyAngles, 0, parent->playerState->viewangles[YAW], 0); // Get the driver tag. - trap_G2API_GetBoltMatrix( parent->ghoul2, 0, crotchBolt, &boltMatrix, - yawOnlyAngles, parent->playerState->origin, - BG_GetTime(), NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, pilot->playerState->origin ); + trap_G2API_GetBoltMatrix(parent->ghoul2, 0, crotchBolt, &boltMatrix, yawOnlyAngles, parent->playerState->origin, BG_GetTime(), NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pilot->playerState->origin); } } #endif @@ -1712,4 +1567,3 @@ void AttachRidersGeneric( Vehicle_t *pVeh ) #include "../namespace_end.h" #endif // _JK2MP - diff --git a/code/game/g_active.cpp b/code/game/g_active.cpp index e8b19398bc..988ad7f40e 100644 --- a/code/game/g_active.cpp +++ b/code/game/g_active.cpp @@ -31,178 +31,164 @@ along with this program; if not, see . #include "g_navigator.h" #ifdef _DEBUG - #include +#include #endif //_DEBUG -#define SLOWDOWN_DIST 128.0f -#define MIN_NPC_SPEED 16.0f +#define SLOWDOWN_DIST 128.0f +#define MIN_NPC_SPEED 16.0f -extern void VehicleExplosionDelay( gentity_t *self ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); +extern void VehicleExplosionDelay(gentity_t *self); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); extern void G_MaintainFormations(gentity_t *self); -extern void BG_CalculateOffsetAngles( gentity_t *ent, usercmd_t *ucmd );//in bg_pangles.cpp -extern void TryUse( gentity_t *ent ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void BG_CalculateOffsetAngles(gentity_t *ent, usercmd_t *ucmd); // in bg_pangles.cpp +extern void TryUse(gentity_t *ent); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); extern void ScoreBoardReset(void); -extern void WP_SaberReflectCheck( gentity_t *self, usercmd_t *ucmd ); -extern void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ); -extern void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ); -extern void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ); -extern gentity_t *SeekerAcquiresTarget ( gentity_t *ent, vec3_t pos ); -extern void FireSeeker( gentity_t *owner, gentity_t *target, vec3_t origin, vec3_t dir ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern qboolean PM_LockAngles( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesToGripper( gentity_t *gent, usercmd_t *cmd ); -extern qboolean PM_AdjustAnglesToPuller( gentity_t *ent, gentity_t *puller, usercmd_t *ucmd, qboolean faceAway ); -extern qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); -extern qboolean PM_AdjustAngleForWallRunUp( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); -extern qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ); -extern qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ); -extern qboolean PM_AdjustAnglesForDualJumpAttack( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForLongJump( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForGrapple( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAngleForWallJump( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); -extern qboolean PM_AdjustAnglesForBFKick( gentity_t *ent, usercmd_t *ucmd, vec3_t fwdAngs, qboolean aimFront ); -extern qboolean PM_AdjustAnglesForStabDown( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForSpinProtect( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForWallRunUpFlipAlt( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForHeldByMonster( gentity_t *ent, gentity_t *monster, usercmd_t *ucmd ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern qboolean PM_LeapingSaberAnim( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_KickingAnim( int anim ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern void PM_CmdForRoll( playerState_t *ps, usercmd_t *pCmd ); -extern qboolean PM_InAttackRoll( int anim ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); -extern qboolean PM_StandingAnim( int anim ); -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern qboolean PM_GetupAnimNoMove( int legsAnim ); -extern qboolean PM_SuperBreakLoseAnim( int anim ); -extern qboolean PM_SuperBreakWinAnim( int anim ); -extern qboolean PM_CanRollFromSoulCal( playerState_t *ps ); -extern qboolean BG_FullBodyTauntAnim( int anim ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern void G_AttachToVehicle( gentity_t *ent, usercmd_t **ucmd ); -extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0 ); -extern void G_UpdateEmplacedWeaponData( gentity_t *ent ); -extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); -extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); -extern void NPC_SetPainEvent( gentity_t *self ); -extern qboolean G_HasKnockdownAnims( gentity_t *ent ); -extern int G_GetEntsNearBolt( gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern qboolean PM_LockedAnim( int anim ); -extern qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ); -extern qboolean G_JediInNormalAI( gentity_t *ent ); - -extern bool in_camera; -extern qboolean player_locked; -extern qboolean stop_icarus; -extern qboolean MatrixMode; - -extern cvar_t *g_spskill; -extern cvar_t *g_timescale; -extern cvar_t *g_saberMoveSpeed; -extern cvar_t *g_saberAutoBlocking; -extern cvar_t *g_speederControlScheme; -extern cvar_t *d_slowmodeath; -extern cvar_t *g_debugMelee; -extern vmCvar_t cg_thirdPersonAlpha; -extern vmCvar_t cg_thirdPersonAutoAlpha; - -void ClientEndPowerUps( gentity_t *ent ); - -int G_FindLookItem( gentity_t *self ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent; - int bestEntNum = ENTITYNUM_NONE; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward, dir; - int i, e; - float radius = 256; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? +extern void WP_SaberReflectCheck(gentity_t *self, usercmd_t *ucmd); +extern void WP_SaberUpdate(gentity_t *self, usercmd_t *ucmd); +extern void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd); +extern void WP_ForcePowersUpdate(gentity_t *self, usercmd_t *ucmd); +extern gentity_t *SeekerAcquiresTarget(gentity_t *ent, vec3_t pos); +extern void FireSeeker(gentity_t *owner, gentity_t *target, vec3_t origin, vec3_t dir); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern qboolean PM_LockAngles(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesToGripper(gentity_t *gent, usercmd_t *cmd); +extern qboolean PM_AdjustAnglesToPuller(gentity_t *ent, gentity_t *puller, usercmd_t *ucmd, qboolean faceAway); +extern qboolean PM_AdjustAngleForWallRun(gentity_t *ent, usercmd_t *ucmd, qboolean doMove); +extern qboolean PM_AdjustAngleForWallRunUp(gentity_t *ent, usercmd_t *ucmd, qboolean doMove); +extern qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly); +extern qboolean PM_AdjustAnglesForBackAttack(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForSaberLock(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForKnockdown(gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly); +extern qboolean PM_AdjustAnglesForDualJumpAttack(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForLongJump(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForGrapple(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAngleForWallJump(gentity_t *ent, usercmd_t *ucmd, qboolean doMove); +extern qboolean PM_AdjustAnglesForBFKick(gentity_t *ent, usercmd_t *ucmd, vec3_t fwdAngs, qboolean aimFront); +extern qboolean PM_AdjustAnglesForStabDown(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForSpinProtect(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForWallRunUpFlipAlt(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForHeldByMonster(gentity_t *ent, gentity_t *monster, usercmd_t *ucmd); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern qboolean PM_LeapingSaberAnim(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_KickingAnim(int anim); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern void PM_CmdForRoll(playerState_t *ps, usercmd_t *pCmd); +extern qboolean PM_InAttackRoll(int anim); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_InCartwheel(int anim); +extern qboolean PM_StandingAnim(int anim); +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern qboolean PM_GetupAnimNoMove(int legsAnim); +extern qboolean PM_SuperBreakLoseAnim(int anim); +extern qboolean PM_SuperBreakWinAnim(int anim); +extern qboolean PM_CanRollFromSoulCal(playerState_t *ps); +extern qboolean BG_FullBodyTauntAnim(int anim); +extern qboolean FlyingCreature(gentity_t *ent); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern void G_AttachToVehicle(gentity_t *ent, usercmd_t **ucmd); +extern void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex = 0); +extern void G_UpdateEmplacedWeaponData(gentity_t *ent); +extern void RunEmplacedWeapon(gentity_t *ent, usercmd_t **ucmd); +extern qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs); +extern void NPC_SetPainEvent(gentity_t *self); +extern qboolean G_HasKnockdownAnims(gentity_t *ent); +extern int G_GetEntsNearBolt(gentity_t *self, gentity_t **radiusEnts, float radius, int boltIndex, vec3_t boltOrg); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern qboolean PM_LockedAnim(int anim); +extern qboolean WP_SabersCheckLock2(gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode); +extern qboolean G_JediInNormalAI(gentity_t *ent); + +extern bool in_camera; +extern qboolean player_locked; +extern qboolean stop_icarus; +extern qboolean MatrixMode; + +extern cvar_t *g_spskill; +extern cvar_t *g_timescale; +extern cvar_t *g_saberMoveSpeed; +extern cvar_t *g_saberAutoBlocking; +extern cvar_t *g_speederControlScheme; +extern cvar_t *d_slowmodeath; +extern cvar_t *g_debugMelee; +extern vmCvar_t cg_thirdPersonAlpha; +extern vmCvar_t cg_thirdPersonAutoAlpha; + +void ClientEndPowerUps(gentity_t *ent); + +int G_FindLookItem(gentity_t *self) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent; + int bestEntNum = ENTITYNUM_NONE; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward, dir; + int i, e; + float radius = 256; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - if ( !numListedEntities ) - { + if (!numListedEntities) { return ENTITYNUM_NONE; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( !ent->item ) - { + if (!ent->item) { continue; } - if ( ent->s.eFlags&EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( (ent->spawnflags&4/*ITMSF_MONSTER*/) ) - {//NPCs only + if ((ent->spawnflags & 4 /*ITMSF_MONSTER*/)) { // NPCs only continue; } - if ( !BG_CanItemBeGrabbed( &ent->s, &self->client->ps ) ) - {//don't need it + if (!BG_CanItemBeGrabbed(&ent->s, &self->client->ps)) { // don't need it continue; } - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - if ( ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER ) - {//a weapon_saber pickup - if ( self->client->ps.dualSabers//using 2 sabers already - || (self->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) )//using a 2-handed saber - {//hands are full already, don't look at saber pickups + if (ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER) { // a weapon_saber pickup + if (self->client->ps.dualSabers // using 2 sabers already + || (self->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) // using a 2-handed saber + { // hands are full already, don't look at saber pickups continue; } } - //rate him based on how close & how in front he is - VectorSubtract( ent->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir ); - if ( ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY ) - {//security keys are of the highest importance + // rate him based on how close & how in front he is + VectorSubtract(ent->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir); + if (ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY) { // security keys are of the highest importance rating *= 2.0f; } - if ( rating > bestRating ) - { + if (rating > bestRating) { bestEntNum = ent->s.number; bestRating = rating; } @@ -210,62 +196,53 @@ int G_FindLookItem( gentity_t *self ) return bestEntNum; } -extern void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ); -qboolean G_ClearViewEntity( gentity_t *ent ) -{ - if ( !ent->client->ps.viewEntity ) +extern void CG_SetClientViewAngles(vec3_t angles, qboolean overrideViewEnt); +qboolean G_ClearViewEntity(gentity_t *ent) { + if (!ent->client->ps.viewEntity) return qfalse; - if ( ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_NONE ) - { - if ( g_entities[ent->client->ps.viewEntity].inuse ) - { + if (ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_NONE) { + if (g_entities[ent->client->ps.viewEntity].inuse) { g_entities[ent->client->ps.viewEntity].svFlags &= ~SVF_BROADCAST; - if ( g_entities[ent->client->ps.viewEntity].NPC ) - { + if (g_entities[ent->client->ps.viewEntity].NPC) { g_entities[ent->client->ps.viewEntity].NPC->controlledTime = 0; - SetClientViewAngle( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); - G_SetAngles( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); - VectorCopy( g_entities[ent->client->ps.viewEntity].currentAngles, g_entities[ent->client->ps.viewEntity].NPC->lastPathAngles ); + SetClientViewAngle(&g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles); + G_SetAngles(&g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles); + VectorCopy(g_entities[ent->client->ps.viewEntity].currentAngles, g_entities[ent->client->ps.viewEntity].NPC->lastPathAngles); g_entities[ent->client->ps.viewEntity].NPC->desiredYaw = g_entities[ent->client->ps.viewEntity].currentAngles[YAW]; } } - CG_SetClientViewAngles( ent->pos4, qtrue ); - SetClientViewAngle( ent, ent->pos4 ); + CG_SetClientViewAngles(ent->pos4, qtrue); + SetClientViewAngle(ent, ent->pos4); } ent->client->ps.viewEntity = 0; return qtrue; } -void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ) -{ - if ( !self || !self->client || !viewEntity ) - { +void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity) { + if (!self || !self->client || !viewEntity) { return; } - if ( self->s.number == 0 && cg.zoomMode ) - { + if (self->s.number == 0 && cg.zoomMode) { // yeah, it should really toggle them so it plays the end sound.... cg.zoomMode = 0; } - if ( viewEntity->s.number == self->client->ps.viewEntity ) - { + if (viewEntity->s.number == self->client->ps.viewEntity) { return; } - //clear old one first - G_ClearViewEntity( self ); - //set new one + // clear old one first + G_ClearViewEntity(self); + // set new one self->client->ps.viewEntity = viewEntity->s.number; viewEntity->svFlags |= SVF_BROADCAST; - //remember current angles - VectorCopy( self->client->ps.viewangles, self->pos4 ); - if ( viewEntity->client ) - { - //vec3_t clear = {0,0,0}; - CG_SetClientViewAngles( viewEntity->client->ps.viewangles, qtrue ); - //SetClientViewAngle( self, viewEntity->client->ps.viewangles ); - //SetClientViewAngle( viewEntity, clear ); + // remember current angles + VectorCopy(self->client->ps.viewangles, self->pos4); + if (viewEntity->client) { + // vec3_t clear = {0,0,0}; + CG_SetClientViewAngles(viewEntity->client->ps.viewangles, qtrue); + // SetClientViewAngle( self, viewEntity->client->ps.viewangles ); + // SetClientViewAngle( viewEntity, clear ); /* VectorCopy( viewEntity->client->ps.viewangles, self->client->ps.viewangles ); for ( int i = 0; i < 3; i++ ) @@ -274,182 +251,146 @@ void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ) } */ } - if ( !self->s.number ) - { - CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + if (!self->s.number) { + CG_CenterPrint("@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } } -qboolean G_ControlledByPlayer( gentity_t *self ) -{ - if ( self && self->NPC && self->NPC->controlledTime > level.time ) - {//being controlled +qboolean G_ControlledByPlayer(gentity_t *self) { + if (self && self->NPC && self->NPC->controlledTime > level.time) { // being controlled gentity_t *controller = &g_entities[0]; - if ( controller->client && controller->client->ps.viewEntity == self->s.number ) - {//we're the player's viewEntity + if (controller->client && controller->client->ps.viewEntity == self->s.number) { // we're the player's viewEntity return qtrue; } } return qfalse; } -qboolean G_ValidateLookEnemy( gentity_t *self, gentity_t *enemy ) -{ - if ( !enemy ) - { +qboolean G_ValidateLookEnemy(gentity_t *self, gentity_t *enemy) { + if (!enemy) { return qfalse; } - if ( enemy->flags&FL_NOTARGET ) - { + if (enemy->flags & FL_NOTARGET) { return qfalse; } - if ( (enemy->s.eFlags&EF_NODRAW) ) - { + if ((enemy->s.eFlags & EF_NODRAW)) { return qfalse; } - if ( !enemy || enemy == self || !enemy->inuse ) - { + if (!enemy || enemy == self || !enemy->inuse) { return qfalse; } - if ( !enemy->client || !enemy->NPC ) - {//not valid - if ( (enemy->svFlags&SVF_NONNPC_ENEMY) - && enemy->s.weapon == WP_TURRET - && enemy->noDamageTeam != self->client->playerTeam - && enemy->health > 0 ) - {//a turret - //return qtrue; - } - else - { + if (!enemy->client || !enemy->NPC) { // not valid + if ((enemy->svFlags & SVF_NONNPC_ENEMY) && enemy->s.weapon == WP_TURRET && enemy->noDamageTeam != self->client->playerTeam && + enemy->health > 0) { // a turret + // return qtrue; + } else { return qfalse; } - } - else - { - if ( self->client->playerTeam != TEAM_FREE//evil player hates everybody - && enemy->client->playerTeam == self->client->playerTeam ) - {//on same team + } else { + if (self->client->playerTeam != TEAM_FREE // evil player hates everybody + && enemy->client->playerTeam == self->client->playerTeam) { // on same team return qfalse; } - Vehicle_t *pVeh = G_IsRidingVehicle( self ); - if ( pVeh && pVeh == enemy->m_pVehicle ) - { + Vehicle_t *pVeh = G_IsRidingVehicle(self); + if (pVeh && pVeh == enemy->m_pVehicle) { return qfalse; } - if ( enemy->health <= 0 && ((level.time-enemy->s.time) > 3000||!InFront(enemy->currentOrigin,self->currentOrigin,self->client->ps.viewangles,0.2f)||DistanceHorizontal(enemy->currentOrigin,self->currentOrigin)>16384))//>128 - {//corpse, been dead too long or too out of sight to be interesting - if ( !enemy->message ) - { + if (enemy->health <= 0 && + ((level.time - enemy->s.time) > 3000 || !InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.2f) || + DistanceHorizontal(enemy->currentOrigin, self->currentOrigin) > 16384)) //>128 + { // corpse, been dead too long or too out of sight to be interesting + if (!enemy->message) { return qfalse; } } } - if ( (!InFront( enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || !G_ClearLOS( self, self->client->renderInfo.eyePoint, enemy ) ) - && ( DistanceHorizontalSquared( enemy->currentOrigin, self->currentOrigin ) > 65536 || fabs(enemy->currentOrigin[2]-self->currentOrigin[2]) > 384 ) ) - {//(not in front or not clear LOS) & greater than 256 away + if ((!InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || + !G_ClearLOS(self, self->client->renderInfo.eyePoint, enemy)) && + (DistanceHorizontalSquared(enemy->currentOrigin, self->currentOrigin) > 65536 || + fabs(enemy->currentOrigin[2] - self->currentOrigin[2]) > 384)) { //(not in front or not clear LOS) & greater than 256 away return qfalse; } - //LOS? + // LOS? return qtrue; } -void G_ChooseLookEnemy( gentity_t *self, usercmd_t *ucmd ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent, *bestEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward, dir; - int i, e; - float radius = 256; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? - fwdangles[0] = 0; //Must initialize data! +void G_ChooseLookEnemy(gentity_t *self, usercmd_t *ucmd) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent, *bestEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward, dir; + int i, e; + float radius = 256; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? + fwdangles[0] = 0; // Must initialize data! fwdangles[1] = self->client->ps.viewangles[1]; fwdangles[2] = 0; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - if ( !numListedEntities ) - {//should we clear the enemy? + if (!numListedEntities) { // should we clear the enemy? return; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ValidateLookEnemy( self, ent ) ) - {//doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call + if (!G_ValidateLookEnemy(self, + ent)) { // doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - //rate him based on how close & how in front he is - VectorSubtract( ent->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir )+1.0f; - if ( ent->health <= 0 ) - { - if ( (ucmd->buttons&BUTTON_ATTACK) - || (ucmd->buttons&BUTTON_ALT_ATTACK) - || (ucmd->buttons&BUTTON_FORCE_FOCUS) ) - {//if attacking, don't consider dead enemies + // rate him based on how close & how in front he is + VectorSubtract(ent->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir) + 1.0f; + if (ent->health <= 0) { + if ((ucmd->buttons & BUTTON_ATTACK) || (ucmd->buttons & BUTTON_ALT_ATTACK) || + (ucmd->buttons & BUTTON_FORCE_FOCUS)) { // if attacking, don't consider dead enemies continue; } - if ( ent->message ) - {//keyholder + if (ent->message) { // keyholder rating *= 0.5f; - } - else - { + } else { rating *= 0.1f; } } - if ( ent->s.weapon == WP_SABER ) - { + if (ent->s.weapon == WP_SABER) { rating *= 2.0f; } - if ( ent->enemy == self ) - {//he's mad at me, he's more important + if (ent->enemy == self) { // he's mad at me, he's more important rating *= 2.0f; - } - else if ( ent->NPC && ent->NPC->blockedSpeechDebounceTime > level.time - 6000 ) - {//he's detected me, he's more important - if ( ent->NPC->blockedSpeechDebounceTime > level.time + 4000 ) - { + } else if (ent->NPC && ent->NPC->blockedSpeechDebounceTime > level.time - 6000) { // he's detected me, he's more important + if (ent->NPC->blockedSpeechDebounceTime > level.time + 4000) { rating *= 1.5f; - } - else - {//from 1.0f to 1.5f - rating += rating * ((float)(ent->NPC->blockedSpeechDebounceTime-level.time) + 6000.0f)/20000.0f; + } else { // from 1.0f to 1.5f + rating += rating * ((float)(ent->NPC->blockedSpeechDebounceTime - level.time) + 6000.0f) / 20000.0f; } } /* @@ -458,14 +399,12 @@ void G_ChooseLookEnemy( gentity_t *self, usercmd_t *ucmd ) rading *= 2.0f; } */ - if ( rating > bestRating ) - { + if (rating > bestRating) { bestEnt = ent; bestRating = rating; } } - if ( bestEnt ) - { + if (bestEnt) { self->enemy = bestEnt; } } @@ -480,23 +419,23 @@ damage values to that client for pain blends and kicks, and global pain sound events for all clients. =============== */ -void P_DamageFeedback( gentity_t *player ) { - gclient_t *client; - float count; - vec3_t angles; +void P_DamageFeedback(gentity_t *player) { + gclient_t *client; + float count; + vec3_t angles; client = player->client; - if ( client->ps.pm_type == PM_DEAD ) { + if (client->ps.pm_type == PM_DEAD) { return; } // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor; - if ( count == 0 ) { - return; // didn't take any damage + if (count == 0) { + return; // didn't take any damage } - if ( count > 255 ) { + if (count > 255) { count = 255; } @@ -504,18 +443,15 @@ void P_DamageFeedback( gentity_t *player ) { // world damage (falling, slime, etc) uses a special code // to make the blend blob centered instead of positional - if ( client->damage_fromWorld ) - { + if (client->damage_fromWorld) { client->ps.damagePitch = 255; client->ps.damageYaw = 255; client->damage_fromWorld = false; - } - else - { - vectoangles( client->damage_from, angles ); - client->ps.damagePitch = angles[PITCH]/360.0 * 256; - client->ps.damageYaw = angles[YAW]/360.0 * 256; + } else { + vectoangles(client->damage_from, angles); + client->ps.damagePitch = angles[PITCH] / 360.0 * 256; + client->ps.damageYaw = angles[YAW] / 360.0 * 256; } client->ps.damageCount = count; @@ -527,8 +463,6 @@ void P_DamageFeedback( gentity_t *player ) { client->damage_armor = 0; } - - /* ============= P_WorldEffects @@ -537,65 +471,52 @@ Check for lava / slime contents and drowning ============= */ -extern void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void P_WorldEffects( gentity_t *ent ) { - int mouthContents = 0; +extern void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void P_WorldEffects(gentity_t *ent) { + int mouthContents = 0; - if ( ent->client->noclip ) - { - ent->client->airOutTime = level.time + 12000; // don't need air + if (ent->client->noclip) { + ent->client->airOutTime = level.time + 12000; // don't need air return; } - if ( !in_camera ) - { - if (gi.totalMapContents() & (CONTENTS_WATER|CONTENTS_SLIME)) - { - mouthContents = gi.pointcontents( ent->client->renderInfo.eyePoint, ent->s.number ); + if (!in_camera) { + if (gi.totalMapContents() & (CONTENTS_WATER | CONTENTS_SLIME)) { + mouthContents = gi.pointcontents(ent->client->renderInfo.eyePoint, ent->s.number); } } // // check for drowning // - if ( (mouthContents&(CONTENTS_WATER|CONTENTS_SLIME)) ) - { + if ((mouthContents & (CONTENTS_WATER | CONTENTS_SLIME))) { - if ( ent->client->NPC_class == CLASS_SWAMPTROOPER ) - {//they have air tanks + if (ent->client->NPC_class == CLASS_SWAMPTROOPER) { // they have air tanks ent->client->airOutTime = level.time + 12000; // don't need air ent->damage = 2; - } - else if ( ent->client->airOutTime < level.time) - {// if out of air, start drowning + } else if (ent->client->airOutTime < level.time) { // if out of air, start drowning // drown! ent->client->airOutTime += 1000; - if ( ent->health > 0 ) { + if (ent->health > 0) { // take more damage the longer underwater ent->damage += 2; if (ent->damage > 15) ent->damage = 15; // play a gurp sound instead of a normal pain sound - if (ent->health <= ent->damage) - { - G_AddEvent( ent, EV_WATER_DROWN, 0 ); - } - else - { - G_AddEvent( ent, Q_irand(EV_WATER_GURP1, EV_WATER_GURP2), 0 ); + if (ent->health <= ent->damage) { + G_AddEvent(ent, EV_WATER_DROWN, 0); + } else { + G_AddEvent(ent, Q_irand(EV_WATER_GURP1, EV_WATER_GURP2), 0); } // don't play a normal pain sound ent->painDebounceTime = level.time + 200; - G_Damage (ent, NULL, NULL, NULL, NULL, - ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); + G_Damage(ent, NULL, NULL, NULL, NULL, ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); } } - } - else - { + } else { ent->client->airOutTime = level.time + 12000; ent->damage = 2; } @@ -603,79 +524,57 @@ void P_WorldEffects( gentity_t *ent ) { // // check for sizzle damage (move to pmove?) // - if (ent->waterlevel && - (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) { - if (ent->health > 0 - && ent->painDebounceTime < level.time ) { + if (ent->waterlevel && (ent->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) { + if (ent->health > 0 && ent->painDebounceTime < level.time) { if (ent->watertype & CONTENTS_LAVA) { - G_Damage (ent, NULL, NULL, NULL, NULL, - 15*ent->waterlevel, 0, MOD_LAVA); + G_Damage(ent, NULL, NULL, NULL, NULL, 15 * ent->waterlevel, 0, MOD_LAVA); } if (ent->watertype & CONTENTS_SLIME) { - G_Damage (ent, NULL, NULL, NULL, NULL, - 1, 0, MOD_SLIME); + G_Damage(ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); } } } - if ((ent->health > 0) && - (ent->painDebounceTime < level.time) && - gi.WE_IsOutsideCausingPain(ent->currentOrigin) && - TIMER_Done(ent, "AcidPainDebounce")) - { - if (ent->NPC && ent->client && (ent->client->ps.forcePowersKnown&(1<< FP_PROTECT))) - { - if (!(ent->client->ps.forcePowersActive & (1<health > 0) && (ent->painDebounceTime < level.time) && gi.WE_IsOutsideCausingPain(ent->currentOrigin) && TIMER_Done(ent, "AcidPainDebounce")) { + if (ent->NPC && ent->client && (ent->client->ps.forcePowersKnown & (1 << FP_PROTECT))) { + if (!(ent->client->ps.forcePowersActive & (1 << FP_PROTECT))) { + WP_ForcePowerStart(ent, FP_PROTECT, 0); } - } - else - { - G_Damage (ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); + } else { + G_Damage(ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); } } // Poisoned? - if ((ent->client->poisonDamage) && (ent->client->poisonTime < level.time)) - { + if ((ent->client->poisonDamage) && (ent->client->poisonTime < level.time)) { ent->client->poisonDamage -= 2; ent->client->poisonTime = level.time + 1000; - G_Damage( ent, NULL, NULL, 0, 0, 2, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR, MOD_UNKNOWN );//FIXME: MOD_POISON? + G_Damage(ent, NULL, NULL, 0, 0, 2, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_ARMOR, MOD_UNKNOWN); // FIXME: MOD_POISON? - if (ent->client->poisonDamage<0) - { + if (ent->client->poisonDamage < 0) { ent->client->poisonDamage = 0; } } - //in space? - if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) - { //we're in space, check for suffocating and for exiting - gentity_t *spacetrigger = &g_entities[ent->client->inSpaceIndex]; + // in space? + if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) { // we're in space, check for suffocating and for exiting + gentity_t *spacetrigger = &g_entities[ent->client->inSpaceIndex]; - if (!spacetrigger->inuse || - !G_PointInBounds(ent->client->ps.origin, spacetrigger->absmin, spacetrigger->absmax)) - { //no longer in space then I suppose - ent->client->inSpaceIndex = 0; - } - else - { //check for suffocation - if (ent->client->inSpaceSuffocation < level.time) - { //suffocate! - if (ent->health > 0) - { //if they're still alive.. + if (!spacetrigger->inuse || !G_PointInBounds(ent->client->ps.origin, spacetrigger->absmin, spacetrigger->absmax)) { // no longer in space then I suppose + ent->client->inSpaceIndex = 0; + } else { // check for suffocation + if (ent->client->inSpaceSuffocation < level.time) { // suffocate! + if (ent->health > 0) { // if they're still alive.. G_Damage(ent, spacetrigger, spacetrigger, NULL, ent->client->ps.origin, Q_irand(20, 40), DAMAGE_NO_ARMOR, MOD_SUICIDE); - if (ent->health > 0) - { //did that last one kill them? - //play the choking sound - G_SoundOnEnt( ent, CHAN_VOICE, va( "*choke%d.wav", Q_irand( 1, 3 ) ) ); + if (ent->health > 0) { // did that last one kill them? + // play the choking sound + G_SoundOnEnt(ent, CHAN_VOICE, va("*choke%d.wav", Q_irand(1, 3))); - //make them grasp their throat - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_CHOKE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // make them grasp their throat + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_CHOKE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } @@ -683,626 +582,491 @@ void P_WorldEffects( gentity_t *ent ) { } } } - - } - - /* =============== G_SetClientSound =============== */ -void G_SetClientSound( gentity_t *ent ) { -// if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) -// ent->s.loopSound = G_SoundIndex("sound/weapons/stasis/electricloop.wav"); +void G_SetClientSound(gentity_t *ent) { + // if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) + // ent->s.loopSound = G_SoundIndex("sound/weapons/stasis/electricloop.wav"); -// else -// ent->s.loopSound = 0; + // else + // ent->s.loopSound = 0; } - - //============================================================== -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); -void G_GetMassAndVelocityForEnt( gentity_t *ent, float *mass, vec3_t velocity ) -{ - if( ent->client ) - { - VectorCopy( ent->client->ps.velocity, velocity ); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); +void G_GetMassAndVelocityForEnt(gentity_t *ent, float *mass, vec3_t velocity) { + if (ent->client) { + VectorCopy(ent->client->ps.velocity, velocity); *mass = ent->mass; - } - else - { - VectorCopy( ent->s.pos.trDelta, velocity ); - if ( ent->s.pos.trType == TR_GRAVITY ) - { + } else { + VectorCopy(ent->s.pos.trDelta, velocity); + if (ent->s.pos.trType == TR_GRAVITY) { velocity[2] -= 0.25f * g_gravity->value; } - if( !ent->mass ) - { + if (!ent->mass) { *mass = 1; - } - else if ( ent->mass <= 10 ) - { + } else if (ent->mass <= 10) { *mass = 10; - } - else - { - *mass = ent->mass;///10; + } else { + *mass = ent->mass; /// 10; } } } -void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace ) -{ +void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace) { float magnitude, my_mass; - bool thrown = false; - vec3_t velocity; + bool thrown = false; + vec3_t velocity; Vehicle_t *pSelfVeh = NULL; Vehicle_t *pOtherVeh = NULL; // See if either of these guys are vehicles, if so, keep a pointer to the vehicle npc. - if ( self->client && self->client->NPC_class == CLASS_VEHICLE ) - { + if (self->client && self->client->NPC_class == CLASS_VEHICLE) { pSelfVeh = self->m_pVehicle; } - if ( other->client && other->client->NPC_class == CLASS_VEHICLE ) - { + if (other->client && other->client->NPC_class == CLASS_VEHICLE) { pOtherVeh = other->m_pVehicle; } - G_GetMassAndVelocityForEnt( self, &my_mass, velocity ); + G_GetMassAndVelocityForEnt(self, &my_mass, velocity); - if ( pSelfVeh ) - { - magnitude = VectorLength( velocity ) * pSelfVeh->m_pVehicleInfo->mass / 50.0f; - } - else - { - magnitude = VectorLength( velocity ) * my_mass / 50; - } - - //if vehicle hit another vehicle, factor in their data, too - // TODO: Bring this back in later on, it's not critical right now... -/* if ( self->client && self->client->NPC_class == CLASS_VEHICLE ) - {//we're in a vehicle - if ( other->client && other->client->ps.vehicleIndex != VEHICLE_NONE ) - {//they're in a vehicle - float o_mass; - vec3_t o_velocity; - - G_GetMassAndVelocityForEnt( other, &o_mass, o_velocity ); - - //now combine - if ( DotProduct( o_velocity, velocity ) < 0 ) - {//were heading towards each other, this is going to be a STRONG impact... - vec3_t velocityMod; - - //incorportate mass into each velocity to get directional force - VectorScale( velocity, my_mass/50, velocityMod ); - VectorScale( o_velocity, o_mass/50, o_velocity ); - //figure out the overall magnitude of those 2 directed forces impacting - magnitude = (DotProduct( o_velocity, velocityMod ) * -1.0f)/500.0f; + if (pSelfVeh) { + magnitude = VectorLength(velocity) * pSelfVeh->m_pVehicleInfo->mass / 50.0f; + } else { + magnitude = VectorLength(velocity) * my_mass / 50; + } + + // if vehicle hit another vehicle, factor in their data, too + // TODO: Bring this back in later on, it's not critical right now... + /* if ( self->client && self->client->NPC_class == CLASS_VEHICLE ) + {//we're in a vehicle + if ( other->client && other->client->ps.vehicleIndex != VEHICLE_NONE ) + {//they're in a vehicle + float o_mass; + vec3_t o_velocity; + + G_GetMassAndVelocityForEnt( other, &o_mass, o_velocity ); + + //now combine + if ( DotProduct( o_velocity, velocity ) < 0 ) + {//were heading towards each other, this is going to be a STRONG impact... + vec3_t velocityMod; + + //incorportate mass into each velocity to get directional force + VectorScale( velocity, my_mass/50, velocityMod ); + VectorScale( o_velocity, o_mass/50, o_velocity ); + //figure out the overall magnitude of those 2 directed forces impacting + magnitude = (DotProduct( o_velocity, velocityMod ) * -1.0f)/500.0f; + } } - } - }*/ - - + }*/ // Check For Vehicle On Vehicle Impact (Ramming) //----------------------------------------------- - if ( pSelfVeh && - pSelfVeh->m_pVehicleInfo->type!=VH_ANIMAL && - pOtherVeh && - pSelfVeh->m_pVehicleInfo==pOtherVeh->m_pVehicleInfo - ) - { - gentity_t* attacker = self; - Vehicle_t* attackerVeh = pSelfVeh; - gentity_t* victim = other; - Vehicle_t* victimVeh = pOtherVeh; + if (pSelfVeh && pSelfVeh->m_pVehicleInfo->type != VH_ANIMAL && pOtherVeh && pSelfVeh->m_pVehicleInfo == pOtherVeh->m_pVehicleInfo) { + gentity_t *attacker = self; + Vehicle_t *attackerVeh = pSelfVeh; + gentity_t *victim = other; + Vehicle_t *victimVeh = pOtherVeh; // Is The Attacker Actually Not Attacking? //----------------------------------------- - if (!(attackerVeh->m_ulFlags&VEH_STRAFERAM)) - { + if (!(attackerVeh->m_ulFlags & VEH_STRAFERAM)) { // Ok, So Is The Victim Actually Attacking? //------------------------------------------ - if (victimVeh->m_ulFlags&VEH_STRAFERAM) - { + if (victimVeh->m_ulFlags & VEH_STRAFERAM) { // Ah, Ok. Swap Who Is The Attacker Then //---------------------------------------- - attacker = other; + attacker = other; attackerVeh = pOtherVeh; - victim = self; - victimVeh = pSelfVeh; - } - else - { + victim = self; + victimVeh = pSelfVeh; + } else { // No Attackers, So Stop //----------------------- attacker = victim = 0; } } - if (attacker && victim) - { - // float maxMoveSpeed = pSelfVeh->m_pVehicleInfo->speedMax; - // float minLockingSpeed = maxMoveSpeed * 0.75; + if (attacker && victim) { + // float maxMoveSpeed = pSelfVeh->m_pVehicleInfo->speedMax; + // float minLockingSpeed = maxMoveSpeed * 0.75; - vec3_t attackerMoveDir; + vec3_t attackerMoveDir; - vec3_t victimMoveDir; - vec3_t victimTowardAttacker; - vec3_t victimRight; - float victimRightAccuracy; + vec3_t victimMoveDir; + vec3_t victimTowardAttacker; + vec3_t victimRight; + float victimRightAccuracy; - VectorCopy(attacker->client->ps.velocity, attackerMoveDir); - VectorCopy(victim->client->ps.velocity, victimMoveDir); + VectorCopy(attacker->client->ps.velocity, attackerMoveDir); + VectorCopy(victim->client->ps.velocity, victimMoveDir); AngleVectors(victim->currentAngles, 0, victimRight, 0); VectorSubtract(victim->currentOrigin, attacker->currentOrigin, victimTowardAttacker); - /*victimTowardAttackerDistance = */VectorNormalize(victimTowardAttacker); + /*victimTowardAttackerDistance = */ VectorNormalize(victimTowardAttacker); victimRightAccuracy = DotProduct(victimTowardAttacker, victimRight); - if ( - fabsf(victimRightAccuracy)>0.25 // Must Be Exactly Right Or Left - // && victimTowardAttackerDistance<100.0f // Must Be Close Enough - // && attackerMoveSpeed>minLockingSpeed // Must be moving fast enough - // && fabsf(attackerMoveSpeed - victimMoveSpeed)<100 // Both must be going about the same speed - ) - { + if (fabsf(victimRightAccuracy) > 0.25 // Must Be Exactly Right Or Left + // && victimTowardAttackerDistance<100.0f // Must Be Close Enough + // && attackerMoveSpeed>minLockingSpeed // Must be moving fast enough + // && fabsf(attackerMoveSpeed - victimMoveSpeed)<100 // Both must be going about the same speed + ) { thrown = true; - vec3_t victimRight; - vec3_t victimAngles; + vec3_t victimRight; + vec3_t victimAngles; VectorCopy(victim->currentAngles, victimAngles); victimAngles[2] = 0; AngleVectors(victimAngles, 0, victimRight, 0); - if (attackerVeh->m_fStrafeTime<0) - { + if (attackerVeh->m_fStrafeTime < 0) { VectorScale(victimRight, -1.0f, victimRight); } - if ( !(victim->flags&FL_NO_KNOCKBACK) ) - { + if (!(victim->flags & FL_NO_KNOCKBACK)) { G_Throw(victim, victimRight, 250); } -// if (false) -// { -// VectorMA(victim->currentOrigin, 250.0f, victimRight, victimRight); -// CG_DrawEdge(victim->currentOrigin, victimRight, EDGE_IMPACT_POSSIBLE); -// } - if (victimVeh->m_pVehicleInfo->iImpactFX) - { - G_PlayEffect(victimVeh->m_pVehicleInfo->iImpactFX, victim->currentOrigin, trace->plane.normal ); + // if (false) + // { + // VectorMA(victim->currentOrigin, 250.0f, victimRight, victimRight); + // CG_DrawEdge(victim->currentOrigin, victimRight, EDGE_IMPACT_POSSIBLE); + // } + if (victimVeh->m_pVehicleInfo->iImpactFX) { + G_PlayEffect(victimVeh->m_pVehicleInfo->iImpactFX, victim->currentOrigin, trace->plane.normal); } } } } - - if ( !self->client || self->client->ps.lastOnGround+300client->ps.lastOnGround+100 < level.time ) ) - { + if (!self->client || self->client->ps.lastOnGround + 300 < level.time || (self->client->ps.lastOnGround + 100 < level.time)) { vec3_t dir1, dir2; float force = 0, dot; qboolean vehicleHitOwner = qfalse; - if ( other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || ((other->svFlags&SVF_BBRUSH)&&(other->spawnflags&8/*THIN*/)) )//(other->absmax[0]-other->absmin[0]<=32||other->absmax[1]-other->absmin[1]<=32||other->absmax[2]-other->absmin[2]<=32)) ) - {//glass and thin breakable brushes (axially aligned only, unfortunately) take more impact damage + if (other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || + ((other->svFlags & SVF_BBRUSH) && + (other->spawnflags & + 8 /*THIN*/))) //(other->absmax[0]-other->absmin[0]<=32||other->absmax[1]-other->absmin[1]<=32||other->absmax[2]-other->absmin[2]<=32)) ) + { // glass and thin breakable brushes (axially aligned only, unfortunately) take more impact damage magnitude *= 2; } // See if the vehicle has crashed into the ground. - if ( pSelfVeh && pSelfVeh->m_pVehicleInfo->type!=VH_ANIMAL) - { - if ((magnitude >= 80) && (self->painDebounceTime < level.time)) - { + if (pSelfVeh && pSelfVeh->m_pVehicleInfo->type != VH_ANIMAL) { + if ((magnitude >= 80) && (self->painDebounceTime < level.time)) { // Setup Some Variables //---------------------- - vec3_t vehFwd; + vec3_t vehFwd; VectorCopy(velocity, vehFwd); - float vehSpeed = VectorNormalize(vehFwd); - float vehToughnessAgainstOther = pSelfVeh->m_pVehicleInfo->toughness; - float vehHitPercent = fabsf(DotProduct(vehFwd, trace->plane.normal)); - int vehDFlags = DAMAGE_NO_ARMOR; - bool vehPilotedByPlayer = (pSelfVeh->m_pPilot && pSelfVeh->m_pPilot->s.numberm_iTurboTime>level.time); - - self->painDebounceTime = level.time + 200; + float vehSpeed = VectorNormalize(vehFwd); + float vehToughnessAgainstOther = pSelfVeh->m_pVehicleInfo->toughness; + float vehHitPercent = fabsf(DotProduct(vehFwd, trace->plane.normal)); + int vehDFlags = DAMAGE_NO_ARMOR; + bool vehPilotedByPlayer = (pSelfVeh->m_pPilot && pSelfVeh->m_pPilot->s.number < MAX_CLIENTS); + bool vehInTurbo = (pSelfVeh->m_iTurboTime > level.time); + self->painDebounceTime = level.time + 200; // Modify Magnitude By Hit Percent And Toughness Against Other //------------------------------------------------------------- - if (pSelfVeh->m_ulFlags & VEH_OUTOFCONTROL) - { - vehToughnessAgainstOther *= 0.01f; // If Out Of Control, No Damage Resistance - } - else - { - if (vehPilotedByPlayer) - { + if (pSelfVeh->m_ulFlags & VEH_OUTOFCONTROL) { + vehToughnessAgainstOther *= 0.01f; // If Out Of Control, No Damage Resistance + } else { + if (vehPilotedByPlayer) { vehToughnessAgainstOther *= 1.5f; } - if (other && other->client) - { - vehToughnessAgainstOther *= 15.0f; // Very Tough against other clients (NPCS, Player, etc) + if (other && other->client) { + vehToughnessAgainstOther *= 15.0f; // Very Tough against other clients (NPCS, Player, etc) } } - if (vehToughnessAgainstOther>0.0f) - { + if (vehToughnessAgainstOther > 0.0f) { magnitude *= (vehHitPercent / vehToughnessAgainstOther); - } - else - { + } else { magnitude *= vehHitPercent; } - // If We Hit Architecture //------------------------ - if (!other || !other->client) - { + if (!other || !other->client) { // Turbo Hurts //------------- - if (vehInTurbo) - { + if (vehInTurbo) { magnitude *= 5.0f; } - else if (trace->plane.normal[2]>0.75f && vehHitPercent<0.2f) - { + else if (trace->plane.normal[2] > 0.75f && vehHitPercent < 0.2f) { magnitude /= 10.0f; } - // If No Pilot, Blow This Thing Now //---------------------------------- - if (vehHitPercent>0.9f && !pSelfVeh->m_pPilot && vehSpeed>1000.0f) - { + if (vehHitPercent > 0.9f && !pSelfVeh->m_pPilot && vehSpeed > 1000.0f) { vehDFlags |= DAMAGE_IMPACT_DIE; } // If Out Of Control, And We Hit A Wall Or Landed Or Head On //------------------------------------------------------------ - if ((pSelfVeh->m_ulFlags&VEH_OUTOFCONTROL) && (vehHitPercent>0.5f || trace->plane.normal[2]<0.5f || velocity[2]<-50.0f)) - { + if ((pSelfVeh->m_ulFlags & VEH_OUTOFCONTROL) && (vehHitPercent > 0.5f || trace->plane.normal[2] < 0.5f || velocity[2] < -50.0f)) { vehDFlags |= DAMAGE_IMPACT_DIE; } // If This Is A Direct Impact (Debounced By 4 Seconds) //----------------------------------------------------- - if (vehHitPercent>0.9f && (level.time - self->lastImpact)>2000 && vehSpeed>300.0f) - { + if (vehHitPercent > 0.9f && (level.time - self->lastImpact) > 2000 && vehSpeed > 300.0f) { self->lastImpact = level.time; // The Player Has Harder Requirements to Explode //----------------------------------------------- - if (vehPilotedByPlayer) - { - if ((vehHitPercent>0.99f && vehSpeed>1000.0f && !Q_irand(0,30)) || - (vehHitPercent>0.999f && vehInTurbo)) - { + if (vehPilotedByPlayer) { + if ((vehHitPercent > 0.99f && vehSpeed > 1000.0f && !Q_irand(0, 30)) || (vehHitPercent > 0.999f && vehInTurbo)) { vehDFlags |= DAMAGE_IMPACT_DIE; } - } - else if (player && G_IsRidingVehicle(player) && - (Distance(self->currentOrigin, player->currentOrigin)<800.0f) && - (vehInTurbo || !Q_irand(0,1) || vehHitPercent>0.999f)) - { + } else if (player && G_IsRidingVehicle(player) && (Distance(self->currentOrigin, player->currentOrigin) < 800.0f) && + (vehInTurbo || !Q_irand(0, 1) || vehHitPercent > 0.999f)) { vehDFlags |= DAMAGE_IMPACT_DIE; } } // Make Sure He Dies This Time. I will accept no excuses. //--------------------------------------------------------- - if (vehDFlags&DAMAGE_IMPACT_DIE) - { + if (vehDFlags & DAMAGE_IMPACT_DIE) { // If close enough To The PLayer - if (player && - G_IsRidingVehicle(player) && - self->owner && - Distance(self->currentOrigin, player->currentOrigin)<500.0f) - { - player->lastEnemy = self->owner; - G_StartMatrixEffect(player, MEF_LOOK_AT_ENEMY|MEF_NO_RANGEVAR|MEF_NO_VERTBOB|MEF_NO_SPIN, 1000); + if (player && G_IsRidingVehicle(player) && self->owner && Distance(self->currentOrigin, player->currentOrigin) < 500.0f) { + player->lastEnemy = self->owner; + G_StartMatrixEffect(player, MEF_LOOK_AT_ENEMY | MEF_NO_RANGEVAR | MEF_NO_VERTBOB | MEF_NO_SPIN, 1000); } magnitude = 100000.0f; } } - if (magnitude>10.0f) - { + if (magnitude > 10.0f) { // Play The Impact Effect //------------------------ - if (pSelfVeh->m_pVehicleInfo->iImpactFX && vehSpeed>100.0f) - { - G_PlayEffect( pSelfVeh->m_pVehicleInfo->iImpactFX, self->currentOrigin, trace->plane.normal ); + if (pSelfVeh->m_pVehicleInfo->iImpactFX && vehSpeed > 100.0f) { + G_PlayEffect(pSelfVeh->m_pVehicleInfo->iImpactFX, self->currentOrigin, trace->plane.normal); } // Set The Crashing Flag And Pain Debounce Time //---------------------------------------------- - pSelfVeh->m_ulFlags |= VEH_CRASHING; + pSelfVeh->m_ulFlags |= VEH_CRASHING; } - G_Damage( self, player, player, NULL, self->currentOrigin, magnitude, vehDFlags, MOD_FALLING );//FIXME: MOD_IMPACT + G_Damage(self, player, player, NULL, self->currentOrigin, magnitude, vehDFlags, MOD_FALLING); // FIXME: MOD_IMPACT } - if ( self->owner == other || self->activator == other ) - {//hit owner/activator - if ( self->m_pVehicle && !self->m_pVehicle->m_pVehicleInfo->Inhabited( self->m_pVehicle ) ) - {//empty swoop - if ( self->client->respawnTime - level.time < 1000 ) - {//just spawned in a second ago - //don't actually damage or throw him... + if (self->owner == other || self->activator == other) { // hit owner/activator + if (self->m_pVehicle && !self->m_pVehicle->m_pVehicleInfo->Inhabited(self->m_pVehicle)) { // empty swoop + if (self->client->respawnTime - level.time < 1000) { // just spawned in a second ago + // don't actually damage or throw him... vehicleHitOwner = qtrue; } } } - //if 2 vehicles on same side hit each other, tone it down - //NOTE: we do this here because we still want the impact effect - if ( pOtherVeh ) - { - if ( self->client->playerTeam == other->client->playerTeam ) - { + // if 2 vehicles on same side hit each other, tone it down + // NOTE: we do this here because we still want the impact effect + if (pOtherVeh) { + if (self->client->playerTeam == other->client->playerTeam) { magnitude /= 25; } } - } - else if ( self->client - && (PM_InKnockDown( &self->client->ps )||(self->client->ps.eFlags&EF_FORCE_GRIPPED)) - && magnitude >= 120 ) - {//FORCE-SMACKED into something - if ( TIMER_Done( self, "impactEffect" ) ) - { - G_PlayEffect( G_EffectIndex( "env/impact_dustonly" ), trace->endpos, trace->plane.normal ); - G_Sound( self, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - TIMER_Set( self, "impactEffect", 1000 ); + } else if (self->client && (PM_InKnockDown(&self->client->ps) || (self->client->ps.eFlags & EF_FORCE_GRIPPED)) && + magnitude >= 120) { // FORCE-SMACKED into something + if (TIMER_Done(self, "impactEffect")) { + G_PlayEffect(G_EffectIndex("env/impact_dustonly"), trace->endpos, trace->plane.normal); + G_Sound(self, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); + TIMER_Set(self, "impactEffect", 1000); } } - //damage them - if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD ) - { - VectorCopy( velocity, dir1 ); - VectorNormalize( dir1 ); - if( VectorCompare( other->currentOrigin, vec3_origin ) ) - {//a brush with no origin - VectorCopy ( dir1, dir2 ); - } - else - { - VectorSubtract( other->currentOrigin, self->currentOrigin, dir2 ); - VectorNormalize( dir2 ); + // damage them + if (magnitude >= 100 && other->s.number < ENTITYNUM_WORLD) { + VectorCopy(velocity, dir1); + VectorNormalize(dir1); + if (VectorCompare(other->currentOrigin, vec3_origin)) { // a brush with no origin + VectorCopy(dir1, dir2); + } else { + VectorSubtract(other->currentOrigin, self->currentOrigin, dir2); + VectorNormalize(dir2); } - dot = DotProduct( dir1, dir2 ); + dot = DotProduct(dir1, dir2); - if ( dot >= 0.2 ) - { + if (dot >= 0.2) { force = dot; - } - else - { + } else { force = 0; } - force *= (magnitude/50); + force *= (magnitude / 50); - int cont = gi.pointcontents( other->absmax, other->s.number ); - if( (cont&CONTENTS_WATER) ) - {//water absorbs 2/3 velocity + int cont = gi.pointcontents(other->absmax, other->s.number); + if ((cont & CONTENTS_WATER)) { // water absorbs 2/3 velocity force *= 0.33333f; } - if ( self->NPC && other->s.number == ENTITYNUM_WORLD ) - {//NPCs take less damage + if (self->NPC && other->s.number == ENTITYNUM_WORLD) { // NPCs take less damage force *= 0.5f; } - if ( self->s.number >= MAX_CLIENTS && self->client && (PM_InKnockDown( &self->client->ps )||self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//NPC: I was knocked down or being gripped, impact should be harder - //FIXME: what if I was just thrown - force pushed/pulled or thrown from a grip? + if (self->s.number >= MAX_CLIENTS && self->client && + (PM_InKnockDown(&self->client->ps) || + self->client->ps.eFlags & EF_FORCE_GRIPPED)) { // NPC: I was knocked down or being gripped, impact should be harder + // FIXME: what if I was just thrown - force pushed/pulled or thrown from a grip? force *= 10; } - //FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. - if ( pOtherVeh ) - {//if hit another vehicle, take their toughness into account, too + // FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. + if (pOtherVeh) { // if hit another vehicle, take their toughness into account, too force /= pOtherVeh->m_pVehicleInfo->toughness; } - if( ( (force >= 1 || pSelfVeh) && other->s.number>=MAX_CLIENTS ) || force >= 10) - { - /* - dprint("Damage other ("); - dprint(loser.classname); - dprint("): "); - dprint(ftos(force)); - dprint("\n"); - */ - if ( other->svFlags & SVF_GLASS_BRUSH ) - { - other->splashRadius = (float)(self->maxs[0] - self->mins[0])/4.0f; + if (((force >= 1 || pSelfVeh) && other->s.number >= MAX_CLIENTS) || force >= 10) { + /* + dprint("Damage other ("); + dprint(loser.classname); + dprint("): "); + dprint(ftos(force)); + dprint("\n"); + */ + if (other->svFlags & SVF_GLASS_BRUSH) { + other->splashRadius = (float)(self->maxs[0] - self->mins[0]) / 4.0f; } - if ( pSelfVeh ) - {//if in a vehicle when land on someone, always knockdown, throw, damage - if ( !vehicleHitOwner ) - {//didn't hit owner + if (pSelfVeh) { // if in a vehicle when land on someone, always knockdown, throw, damage + if (!vehicleHitOwner) { // didn't hit owner // If the player was hit don't make the damage so bad... - if ( other && other->s.numbers.number < MAX_CLIENTS) { force *= 0.5f; } - //Hmm, maybe knockdown? - if ( !(other->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( other, dir2, force ); + // Hmm, maybe knockdown? + if (!(other->flags & FL_NO_KNOCKBACK)) { + G_Throw(other, dir2, force); } - G_Knockdown( other, self, dir2, force, qtrue ); - G_Damage( other, self, self, velocity, self->currentOrigin, force, DAMAGE_NO_ARMOR|DAMAGE_EXTRA_KNOCKBACK, MOD_IMPACT ); + G_Knockdown(other, self, dir2, force, qtrue); + G_Damage(other, self, self, velocity, self->currentOrigin, force, DAMAGE_NO_ARMOR | DAMAGE_EXTRA_KNOCKBACK, MOD_IMPACT); } - } - else if ( self->forcePushTime > level.time - 1000//was force pushed/pulled in the last 1600 milliseconds - && self->forcePuller == other->s.number )//hit the person who pushed/pulled me - {//ignore the impact - } - else if ( other->takedamage ) - { - if ( !self->client || other->s.numberclient ) - {//aw, fuck it, clients no longer take impact damage from other clients, unless you're the player - if ( other->client //he's a client - && self->client //I'm a client - && other->client->ps.forceGripEntityNum == self->s.number )//he's force-gripping me - {//don't damage the other guy if he's gripping me - } - else - { - G_Damage( other, self, self, velocity, self->currentOrigin, floor(force), DAMAGE_NO_ARMOR, MOD_IMPACT ); + } else if (self->forcePushTime > level.time - 1000 // was force pushed/pulled in the last 1600 milliseconds + && self->forcePuller == other->s.number) // hit the person who pushed/pulled me + { // ignore the impact + } else if (other->takedamage) { + if (!self->client || other->s.number < MAX_CLIENTS || + !other->client) { // aw, fuck it, clients no longer take impact damage from other clients, unless you're the player + if (other->client // he's a client + && self->client // I'm a client + && other->client->ps.forceGripEntityNum == self->s.number) // he's force-gripping me + { // don't damage the other guy if he's gripping me + } else { + G_Damage(other, self, self, velocity, self->currentOrigin, floor(force), DAMAGE_NO_ARMOR, MOD_IMPACT); } - } - else - { - GEntity_PainFunc( other, self, self, self->currentOrigin, force, MOD_IMPACT ); - //Hmm, maybe knockdown? - if (!thrown) - { - if ( !(other->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( other, dir2, force ); + } else { + GEntity_PainFunc(other, self, self, self->currentOrigin, force, MOD_IMPACT); + // Hmm, maybe knockdown? + if (!thrown) { + if (!(other->flags & FL_NO_KNOCKBACK)) { + G_Throw(other, dir2, force); } } } - if ( other->health > 0 ) - {//still alive? - //TODO: if someone was thrown through the air (in a knockdown or being gripped) + if (other->health > 0) { // still alive? + // TODO: if someone was thrown through the air (in a knockdown or being gripped) // and they hit me hard enough, knock me down - if ( other->client ) - { - if ( self->client ) - { - if ( PM_InKnockDown( &self->client->ps ) || (self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - { - G_Knockdown( other, self, dir2, Q_irand( 200, 400 ), qtrue ); + if (other->client) { + if (self->client) { + if (PM_InKnockDown(&self->client->ps) || (self->client->ps.eFlags & EF_FORCE_GRIPPED)) { + G_Knockdown(other, self, dir2, Q_irand(200, 400), qtrue); } - } - else if ( self->forcePuller != ENTITYNUM_NONE - && g_entities[self->forcePuller].client - && self->mass > Q_irand( 50, 100 ) ) - { - G_Knockdown( other, &g_entities[self->forcePuller], dir2, Q_irand( 200, 400 ), qtrue ); + } else if (self->forcePuller != ENTITYNUM_NONE && g_entities[self->forcePuller].client && self->mass > Q_irand(50, 100)) { + G_Knockdown(other, &g_entities[self->forcePuller], dir2, Q_irand(200, 400), qtrue); } } } - } - else - { - //Hmm, maybe knockdown? - if (!thrown) - { - if ( !(other->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( other, dir2, force ); + } else { + // Hmm, maybe knockdown? + if (!thrown) { + if (!(other->flags & FL_NO_KNOCKBACK)) { + G_Throw(other, dir2, force); } } } } } - if ( damageSelf && self->takedamage && !(self->flags&FL_NO_IMPACT_DMG)) - { - //Now damage me - //FIXME: more lenient falling damage, especially for when driving a vehicle - if ( pSelfVeh && self->client->ps.forceJumpZStart ) - {//we were force-jumping - if ( self->currentOrigin[2] >= self->client->ps.forceJumpZStart ) - {//we landed at same height or higher than we landed + if (damageSelf && self->takedamage && !(self->flags & FL_NO_IMPACT_DMG)) { + // Now damage me + // FIXME: more lenient falling damage, especially for when driving a vehicle + if (pSelfVeh && self->client->ps.forceJumpZStart) { // we were force-jumping + if (self->currentOrigin[2] >= self->client->ps.forceJumpZStart) { // we landed at same height or higher than we landed magnitude = 0; - } - else - {//FIXME: take off some of it, at least? - magnitude = (self->client->ps.forceJumpZStart-self->currentOrigin[2])/3; + } else { // FIXME: take off some of it, at least? + magnitude = (self->client->ps.forceJumpZStart - self->currentOrigin[2]) / 3; } } - if( ( magnitude >= 100 + self->health - && self->s.number >= MAX_CLIENTS - && self->s.weapon != WP_SABER ) - || self->client->NPC_class == CLASS_VEHICLE - || ( magnitude >= 700 ) )//health here is used to simulate structural integrity + if ((magnitude >= 100 + self->health && self->s.number >= MAX_CLIENTS && self->s.weapon != WP_SABER) || self->client->NPC_class == CLASS_VEHICLE || + (magnitude >= 700)) // health here is used to simulate structural integrity { - if ( (self->s.weapon == WP_SABER || self->s.numberclient&&(self->client->NPC_class==CLASS_BOBAFETT||self->client->NPC_class==CLASS_ROCKETTROOPER))) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 ) - {//players and jedi take less impact damage - //allow for some lenience on high falls + if ((self->s.weapon == WP_SABER || self->s.number < MAX_CLIENTS || + (self->client && (self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER))) && + self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000) { // players and jedi take less impact damage + // allow for some lenience on high falls magnitude /= 2; } - //drop it some (magic number... sigh) + // drop it some (magic number... sigh) magnitude /= 40; - //If damage other, subtract half of that damage off of own injury - if ( other->bmodel && other->material != MAT_GLASS ) - {//take off only a little because we broke architecture (not including glass), that should hurt - magnitude = magnitude - force/8; - } - else - {//take off half damage we did to it - magnitude = magnitude - force/2; + // If damage other, subtract half of that damage off of own injury + if (other->bmodel && + other->material != MAT_GLASS) { // take off only a little because we broke architecture (not including glass), that should hurt + magnitude = magnitude - force / 8; + } else { // take off half damage we did to it + magnitude = magnitude - force / 2; } - if ( pSelfVeh ) - { - //FIXME: if hit another vehicle, take their toughness into + if (pSelfVeh) { + // FIXME: if hit another vehicle, take their toughness into // account, too? Or should their toughness only matter // when they hit me? magnitude /= pSelfVeh->m_pVehicleInfo->toughness * 1000.0f; - if ( other->bmodel && other->material != MAT_GLASS ) - {//broke through some architecture, take a good amount of damage - } - else if ( pOtherVeh ) - {//they're tougher - //magnitude /= 4.0f;//FIXME: get the toughness of other from vehicles.cfg - } - else - {//take some off because of give - //NOTE: this covers all other entities and impact with world... - //FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. + if (other->bmodel && other->material != MAT_GLASS) { // broke through some architecture, take a good amount of damage + } else if (pOtherVeh) { // they're tougher + // magnitude /= 4.0f;//FIXME: get the toughness of other from vehicles.cfg + } else { // take some off because of give + // NOTE: this covers all other entities and impact with world... + // FIXME: certain NPCs/entities should be TOUGH - like Ion Cannons, AT-STs, Mark1 droids, etc. magnitude /= 10.0f; } - if ( magnitude < 1.0f ) - { + if (magnitude < 1.0f) { magnitude = 0; } } - if ( magnitude >= 1 ) - { - //FIXME: Put in a thingtype impact sound function - /* - dprint("Damage self ("); - dprint(self.classname); - dprint("): "); - dprint(ftos(magnitude)); - dprint("\n"); - */ - if ( self->NPC && self->s.weapon == WP_SABER ) - {//FIXME: for now Jedi take no falling damage, but really they should if pushed off? + if (magnitude >= 1) { + // FIXME: Put in a thingtype impact sound function + /* + dprint("Damage self ("); + dprint(self.classname); + dprint("): "); + dprint(ftos(magnitude)); + dprint("\n"); + */ + if (self->NPC && self->s.weapon == WP_SABER) { // FIXME: for now Jedi take no falling damage, but really they should if pushed off? magnitude = 0; } - G_Damage( self, NULL, NULL, NULL, self->currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + G_Damage(self, NULL, NULL, NULL, self->currentOrigin, magnitude / 2, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT } } } - //FIXME: slow my velocity some? - - + // FIXME: slow my velocity some? /* if(self.flags&FL_ONGROUND) @@ -1316,33 +1080,32 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t * ClientImpacts ============== */ -void ClientImpacts( gentity_t *ent, pmove_t *pm ) { - int i, j; - trace_t trace; - gentity_t *other; - - memset( &trace, 0, sizeof( trace ) ); - for (i=0 ; inumtouch ; i++) { - for (j=0 ; jtouchents[j] == pm->touchents[i] ) { +void ClientImpacts(gentity_t *ent, pmove_t *pm) { + int i, j; + trace_t trace; + gentity_t *other; + + memset(&trace, 0, sizeof(trace)); + for (i = 0; i < pm->numtouch; i++) { + for (j = 0; j < i; j++) { + if (pm->touchents[j] == pm->touchents[i]) { break; } } if (j != i) { - continue; // duplicated + continue; // duplicated } - other = &g_entities[ pm->touchents[i] ]; + other = &g_entities[pm->touchents[i]]; - if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { // last check unneccessary - GEntity_TouchFunc( ent, other, &trace ); + if ((ent->NPC != NULL) && (ent->e_TouchFunc != touchF_NULL)) { // last check unneccessary + GEntity_TouchFunc(ent, other, &trace); } - if ( other->e_TouchFunc == touchF_NULL ) { // not needed, but I'll leave it I guess (cache-hit issues) + if (other->e_TouchFunc == touchF_NULL) { // not needed, but I'll leave it I guess (cache-hit issues) continue; } - GEntity_TouchFunc( other, ent, &trace ); + GEntity_TouchFunc(other, ent, &trace); } - } /* @@ -1355,85 +1118,76 @@ Spectators will only interact with teleporters. This version checks at 6 unit steps between last and current origins ============ */ -void G_TouchTriggersLerped( gentity_t *ent ) { - int i, num; - float dist, curDist = 0; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t end, mins, maxs, diff; - const vec3_t range = { 40, 40, 52 }; - qboolean touched[MAX_GENTITIES]; - qboolean done = qfalse; - - if ( !ent->client ) { +void G_TouchTriggersLerped(gentity_t *ent) { + int i, num; + float dist, curDist = 0; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t end, mins, maxs, diff; + const vec3_t range = {40, 40, 52}; + qboolean touched[MAX_GENTITIES]; + qboolean done = qfalse; + + if (!ent->client) { return; } // dead NPCs don't activate triggers! - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) - { - if ( ent->s.number>=MAX_CLIENTS ) - { + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { + if (ent->s.number >= MAX_CLIENTS) { return; } } #ifdef _DEBUG - for ( int j = 0; j < 3; j++ ) - { - assert( !Q_isnan(ent->currentOrigin[j])); - assert( !Q_isnan(ent->lastOrigin[j])); + for (int j = 0; j < 3; j++) { + assert(!Q_isnan(ent->currentOrigin[j])); + assert(!Q_isnan(ent->lastOrigin[j])); } -#endif// _DEBUG - VectorSubtract( ent->currentOrigin, ent->lastOrigin, diff ); - dist = VectorNormalize( diff ); +#endif // _DEBUG + VectorSubtract(ent->currentOrigin, ent->lastOrigin, diff); + dist = VectorNormalize(diff); #ifdef _DEBUG - assert( (dist<1024) && "insane distance in G_TouchTriggersLerped!" ); -#endif// _DEBUG + assert((dist < 1024) && "insane distance in G_TouchTriggersLerped!"); +#endif // _DEBUG - if ( dist > 1024 ) - { + if (dist > 1024) { return; } - memset (touched, qfalse, sizeof(touched) ); + memset(touched, qfalse, sizeof(touched)); - for ( curDist = 0; !done && ent->maxs[1]>0; curDist += (float)ent->maxs[1]/2.0f ) - { - if ( curDist >= dist ) - { - VectorCopy( ent->currentOrigin, end ); + for (curDist = 0; !done && ent->maxs[1] > 0; curDist += (float)ent->maxs[1] / 2.0f) { + if (curDist >= dist) { + VectorCopy(ent->currentOrigin, end); done = qtrue; + } else { + VectorMA(ent->lastOrigin, curDist, diff, end); } - else - { - VectorMA( ent->lastOrigin, curDist, diff, end ); - } - VectorSubtract( end, range, mins ); - VectorAdd( end, range, maxs ); + VectorSubtract(end, range, mins); + VectorAdd(end, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( end, ent->mins, mins ); - VectorAdd( end, ent->maxs, maxs ); + VectorAdd(end, ent->mins, mins); + VectorAdd(end, ent->maxs, maxs); - for ( i=0 ; ie_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { + if ((hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL)) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } - if ( touched[i] == qtrue ) { - continue;//already touched this move + if (touched[i] == qtrue) { + continue; // already touched this move } - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) - { - if ( Q_stricmp( "trigger_teleport", hit->classname ) || !(hit->spawnflags&16/*TTSF_DEAD_OK*/) ) - {//dead clients can only touch tiogger_teleports that are marked as touchable + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { + if (Q_stricmp("trigger_teleport", hit->classname) || + !(hit->spawnflags & 16 /*TTSF_DEAD_OK*/)) { // dead clients can only touch tiogger_teleports that are marked as touchable continue; } } @@ -1446,20 +1200,20 @@ void G_TouchTriggersLerped( gentity_t *ent ) { } } else */ { - if ( !gi.EntityContact( mins, maxs, hit ) ) { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } } touched[i] = qtrue; - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } - //WTF? Why would a trigger ever fire off the NPC's touch func??!!! + // WTF? Why would a trigger ever fire off the NPC's touch func??!!! /* if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { GEntity_TouchFunc( ent, hit, &trace ); @@ -1477,38 +1231,38 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_TouchTriggers( gentity_t *ent ) { - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t mins, maxs; - const vec3_t range = { 40, 40, 52 }; - - if ( !ent->client ) { +void G_TouchTriggers(gentity_t *ent) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t mins, maxs; + const vec3_t range = {40, 40, 52}; + + if (!ent->client) { return; } // dead clients don't activate triggers! - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { return; } - VectorSubtract( ent->client->ps.origin, range, mins ); - VectorAdd( ent->client->ps.origin, range, maxs ); + VectorSubtract(ent->client->ps.origin, range, mins); + VectorAdd(ent->client->ps.origin, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( ent->client->ps.origin, ent->mins, mins ); - VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); + VectorAdd(ent->client->ps.origin, ent->mins, mins); + VectorAdd(ent->client->ps.origin, ent->maxs, maxs); - for ( i=0 ; ie_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { + if ((hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL)) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } @@ -1521,24 +1275,23 @@ void G_TouchTriggers( gentity_t *ent ) { } } else */ { - if ( !gi.EntityContact( mins, maxs, hit ) ) { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } - if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { - GEntity_TouchFunc( ent, hit, &trace ); + if ((ent->NPC != NULL) && (ent->e_TouchFunc != touchF_NULL)) { + GEntity_TouchFunc(ent, hit, &trace); } } } - /* ============ G_MoverTouchTriggers @@ -1547,132 +1300,107 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ) -{ - int i, num; - float step, stepSize, dist; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t mins, maxs, dir, size, checkSpot; - const vec3_t range = { 40, 40, 52 }; +void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg) { + int i, num; + float step, stepSize, dist; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t mins, maxs, dir, size, checkSpot; + const vec3_t range = {40, 40, 52}; // non-moving movers don't hit triggers! - if ( !VectorLengthSquared( ent->s.pos.trDelta ) ) - { + if (!VectorLengthSquared(ent->s.pos.trDelta)) { return; } - VectorSubtract( ent->mins, ent->maxs, size ); - stepSize = VectorLength( size ); - if ( stepSize < 1 ) - { + VectorSubtract(ent->mins, ent->maxs, size); + stepSize = VectorLength(size); + if (stepSize < 1) { stepSize = 1; } - VectorSubtract( ent->currentOrigin, oldOrg, dir ); - dist = VectorNormalize( dir ); - for ( step = 0; step <= dist; step += stepSize ) - { - VectorMA( ent->currentOrigin, step, dir, checkSpot ); - VectorSubtract( checkSpot, range, mins ); - VectorAdd( checkSpot, range, maxs ); + VectorSubtract(ent->currentOrigin, oldOrg, dir); + dist = VectorNormalize(dir); + for (step = 0; step <= dist; step += stepSize) { + VectorMA(ent->currentOrigin, step, dir, checkSpot); + VectorSubtract(checkSpot, range, mins); + VectorAdd(checkSpot, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( checkSpot, ent->mins, mins ); - VectorAdd( checkSpot, ent->maxs, maxs ); + VectorAdd(checkSpot, ent->mins, mins); + VectorAdd(checkSpot, ent->maxs, maxs); - for ( i=0 ; is.eType != ET_PUSH_TRIGGER ) - { + if (hit->s.eType != ET_PUSH_TRIGGER) { continue; } - if ( hit->e_TouchFunc == touchF_NULL ) - { + if (hit->e_TouchFunc == touchF_NULL) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) - { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } - - if ( !gi.EntityContact( mins, maxs, hit ) ) - { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) - { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } } } } -void G_MatchPlayerWeapon( gentity_t *ent ) -{ - if ( g_entities[0].inuse && g_entities[0].client ) - {//player is around +void G_MatchPlayerWeapon(gentity_t *ent) { + if (g_entities[0].inuse && g_entities[0].client) { // player is around int newWeap; - if ( g_entities[0].client->ps.weapon > WP_CONCUSSION ) - { + if (g_entities[0].client->ps.weapon > WP_CONCUSSION) { newWeap = WP_BLASTER_PISTOL; - } - else - { + } else { newWeap = g_entities[0].client->ps.weapon; } - if ( newWeap != WP_NONE && ent->client->ps.weapon != newWeap ) - { - G_RemoveWeaponModels( ent ); - ent->client->ps.stats[STAT_WEAPONS] = ( 1 << newWeap ); + if (newWeap != WP_NONE && ent->client->ps.weapon != newWeap) { + G_RemoveWeaponModels(ent); + ent->client->ps.stats[STAT_WEAPONS] = (1 << newWeap); ent->client->ps.ammo[weaponData[newWeap].ammoIndex] = 999; - ChangeWeapon( ent, newWeap ); + ChangeWeapon(ent, newWeap); ent->client->ps.weapon = newWeap; ent->client->ps.weaponstate = WEAPON_READY; - if ( newWeap == WP_SABER ) - { - //FIXME: AddSound/Sight Event - int numSabers = WP_SaberInitBladeData( ent ); - WP_SaberAddG2SaberModels( ent ); - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - //G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[saberNum].model, ent->handRBolt, 0 ); + if (newWeap == WP_SABER) { + // FIXME: AddSound/Sight Event + int numSabers = WP_SaberInitBladeData(ent); + WP_SaberAddG2SaberModels(ent); + for (int saberNum = 0; saberNum < numSabers; saberNum++) { + // G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[saberNum].model, ent->handRBolt, 0 ); ent->client->ps.saber[saberNum].type = g_entities[0].client->ps.saber[saberNum].type; - for ( int bladeNum = 0; bladeNum < ent->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { + for (int bladeNum = 0; bladeNum < ent->client->ps.saber[saberNum].numBlades; bladeNum++) { ent->client->ps.saber[saberNum].blade[0].active = g_entities[0].client->ps.saber[saberNum].blade[bladeNum].active; ent->client->ps.saber[saberNum].blade[0].length = g_entities[0].client->ps.saber[saberNum].blade[bladeNum].length; } } ent->client->ps.saberAnimLevel = g_entities[0].client->ps.saberAnimLevel; ent->client->ps.saberStylesKnown = g_entities[0].client->ps.saberStylesKnown; - } - else - { - G_CreateG2AttachedWeaponModel( ent, weaponData[newWeap].weaponMdl, ent->handRBolt, 0 ); + } else { + G_CreateG2AttachedWeaponModel(ent, weaponData[newWeap].weaponMdl, ent->handRBolt, 0); } } } } -void G_NPCMunroMatchPlayerWeapon( gentity_t *ent ) -{ - //special uber hack for cinematic players to match player's weapon - if ( !in_camera ) - { - if ( ent && ent->client && ent->NPC && (ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON) ) - {//we're a Player NPC - G_MatchPlayerWeapon( ent ); +void G_NPCMunroMatchPlayerWeapon(gentity_t *ent) { + // special uber hack for cinematic players to match player's weapon + if (!in_camera) { + if (ent && ent->client && ent->NPC && (ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON)) { // we're a Player NPC + G_MatchPlayerWeapon(ent); } } } @@ -1684,45 +1412,39 @@ ClientTimerActions Actions that happen once a second ================== */ -void ClientTimerActions( gentity_t *ent, int msec ) { +void ClientTimerActions(gentity_t *ent, int msec) { gclient_t *client; client = ent->client; client->timeResidual += msec; - while ( client->timeResidual >= 1000 ) - { + while (client->timeResidual >= 1000) { client->timeResidual -= 1000; - if ( ent->s.weapon != WP_NONE ) - { + if (ent->s.weapon != WP_NONE) { ent->client->sess.missionStats.weaponUsed[ent->s.weapon]++; } // if we've got the seeker powerup, see if we can shoot it at someone -/* if ( ent->client->ps.powerups[PW_SEEKER] > level.time ) - { - vec3_t seekerPos, dir; - gentity_t *enemy = SeekerAcquiresTarget( ent, seekerPos ); + /* if ( ent->client->ps.powerups[PW_SEEKER] > level.time ) + { + vec3_t seekerPos, dir; + gentity_t *enemy = SeekerAcquiresTarget( ent, seekerPos ); - if ( enemy != NULL ) // set the client's enemy to a valid target - { - FireSeeker( ent, enemy, seekerPos, dir ); + if ( enemy != NULL ) // set the client's enemy to a valid target + { + FireSeeker( ent, enemy, seekerPos, dir ); - gentity_t *tent; - tent = G_TempEntity( seekerPos, EV_POWERUP_SEEKER_FIRE ); - VectorCopy( dir, tent->pos1 ); - tent->s.eventParm = ent->s.number; - } - }*/ - if ( (ent->flags&FL_OVERCHARGED_HEALTH) ) - {//need to gradually reduce health back to max - if ( ent->health > ent->client->ps.stats[STAT_MAX_HEALTH] ) - {//decrement it + gentity_t *tent; + tent = G_TempEntity( seekerPos, EV_POWERUP_SEEKER_FIRE ); + VectorCopy( dir, tent->pos1 ); + tent->s.eventParm = ent->s.number; + } + }*/ + if ((ent->flags & FL_OVERCHARGED_HEALTH)) { // need to gradually reduce health back to max + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) { // decrement it ent->health--; ent->client->ps.stats[STAT_HEALTH] = ent->health; - } - else - {//done + } else { // done ent->flags &= ~FL_OVERCHARGED_HEALTH; } } @@ -1734,19 +1456,18 @@ void ClientTimerActions( gentity_t *ent, int msec ) { ClientIntermissionThink ==================== */ -static qboolean ClientCinematicThink( gclient_t *client ) { +static qboolean ClientCinematicThink(gclient_t *client) { client->ps.eFlags &= ~EF_FIRING; // swap button actions client->oldbuttons = client->buttons; client->buttons = client->usercmd.buttons; - if ( client->buttons & ( BUTTON_USE ) & ( client->oldbuttons ^ client->buttons ) ) { - return( qtrue ); + if (client->buttons & (BUTTON_USE) & (client->oldbuttons ^ client->buttons)) { + return (qtrue); } - return( qfalse ); + return (qfalse); } - /* ================ ClientEvents @@ -1755,27 +1476,27 @@ Events will be passed on to the clients for presentation, but any server game effects are handled here ================ */ -extern void WP_SabersDamageTrace( gentity_t *ent, qboolean noEffects = qfalse ); -extern void WP_SaberUpdateOldBladeData( gentity_t *ent ); -void ClientEvents( gentity_t *ent, int oldEventSequence ) { - int i; - int event; +extern void WP_SabersDamageTrace(gentity_t *ent, qboolean noEffects = qfalse); +extern void WP_SaberUpdateOldBladeData(gentity_t *ent); +void ClientEvents(gentity_t *ent, int oldEventSequence) { + int i; + int event; gclient_t *client; - //int damage; + // int damage; #ifndef FINAL_BUILD - qboolean fired = qfalse; + qboolean fired = qfalse; #endif client = ent->client; - for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) { - event = client->ps.events[ i & (MAX_PS_EVENTS-1) ]; + for (i = oldEventSequence; i < client->ps.eventSequence; i++) { + event = client->ps.events[i & (MAX_PS_EVENTS - 1)]; - switch ( event ) { + switch (event) { case EV_FALL_MEDIUM: - case EV_FALL_FAR://these come from bg_pmove, PM_CrashLand - if ( ent->s.eType != ET_PLAYER ) { - break; // not in the player model + case EV_FALL_FAR: // these come from bg_pmove, PM_CrashLand + if (ent->s.eType != ET_PLAYER) { + break; // not in the player model } /* //FIXME: isn't there a more accurate way to calculate damage from falls? @@ -1794,43 +1515,39 @@ void ClientEvents( gentity_t *ent, int oldEventSequence ) { case EV_FIRE_WEAPON: #ifndef FINAL_BUILD - if ( fired ) { - gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); + if (fired) { + gi.Printf("DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n"); } fired = qtrue; #endif - FireWeapon( ent, qfalse ); + FireWeapon(ent, qfalse); break; case EV_ALT_FIRE: #ifndef FINAL_BUILD - if ( fired ) { - gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); + if (fired) { + gi.Printf("DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n"); } fired = qtrue; #endif - FireWeapon( ent, qtrue ); + FireWeapon(ent, qtrue); break; default: break; } } - //by the way, if you have your saber in hand and it's on, do the damage trace - if ( client->ps.weapon == WP_SABER ) - { - if ( g_timescale->value >= 1.0f || !(client->ps.forcePowersActive&(1<ps.saberDamageDebounceTime - level.time > wait ) - {//when you unpause the game with force speed on, the time gets *really* wiggy... + // by the way, if you have your saber in hand and it's on, do the damage trace + if (client->ps.weapon == WP_SABER) { + if (g_timescale->value >= 1.0f || !(client->ps.forcePowersActive & (1 << FP_SPEED))) { + int wait = FRAMETIME / 2; + // sanity check + if (client->ps.saberDamageDebounceTime - level.time > wait) { // when you unpause the game with force speed on, the time gets *really* wiggy... client->ps.saberDamageDebounceTime = level.time + wait; } - if ( client->ps.saberDamageDebounceTime <= level.time ) - { - WP_SabersDamageTrace( ent ); - WP_SaberUpdateOldBladeData( ent ); + if (client->ps.saberDamageDebounceTime <= level.time) { + WP_SabersDamageTrace(ent); + WP_SaberUpdateOldBladeData(ent); /* if ( g_timescale->value&&client->ps.clientNum==0&&!player_locked&&!MatrixMode&&client->ps.forcePowersActive&(1<client ) - { + if (!hitEnt || !hitEnt->client) { return; } - switch ( hitEnt->client->ps.legsAnim ) + switch (hitEnt->client->ps.legsAnim) { + case BOTH_DEATH9: // fall to knees, fall over + case BOTH_DEATH10: // fall to knees, fall over + case BOTH_DEATH11: // fall to knees, fall over + case BOTH_DEATH13: // stumble back, fall over + case BOTH_DEATH17: // jerky fall to knees, fall over + case BOTH_DEATH18: // grab gut, fall to knees, fall over + case BOTH_DEATH19: // grab gut, fall to knees, fall over + case BOTH_DEATH20: // grab shoulder, fall forward + case BOTH_DEATH21: // grab shoulder, fall forward + case BOTH_DEATH3: // knee collapse, twist & fall forward + case BOTH_DEATH7: // knee collapse, twist & fall forward { - case BOTH_DEATH9://fall to knees, fall over - case BOTH_DEATH10://fall to knees, fall over - case BOTH_DEATH11://fall to knees, fall over - case BOTH_DEATH13://stumble back, fall over - case BOTH_DEATH17://jerky fall to knees, fall over - case BOTH_DEATH18://grab gut, fall to knees, fall over - case BOTH_DEATH19://grab gut, fall to knees, fall over - case BOTH_DEATH20://grab shoulder, fall forward - case BOTH_DEATH21://grab shoulder, fall forward - case BOTH_DEATH3://knee collapse, twist & fall forward - case BOTH_DEATH7://knee collapse, twist & fall forward - { - vec3_t dir2Impact, fwdAngles, facing; - VectorSubtract( impactPoint, hitEnt->currentOrigin, dir2Impact ); - dir2Impact[2] = 0; - VectorNormalize( dir2Impact ); - VectorSet( fwdAngles, 0, hitEnt->client->ps.viewangles[YAW], 0 ); - AngleVectors( fwdAngles, facing, NULL, NULL ); - float dot = DotProduct( facing, dir2Impact );//-1 = hit in front, 0 = hit on side, 1 = hit in back - if ( dot > 0.5f ) - {//kicked in chest, fly backward - switch ( Q_irand( 0, 4 ) ) - {//FIXME: don't start at beginning of anim? - case 0: - anim = BOTH_DEATH1;//thrown backwards - break; - case 1: - anim = BOTH_DEATH2;//fall backwards - break; - case 2: - anim = BOTH_DEATH15;//roll over backwards - break; - case 3: - anim = BOTH_DEATH22;//fast fall back - break; - case 4: - anim = BOTH_DEATH23;//fast fall back - break; - } + vec3_t dir2Impact, fwdAngles, facing; + VectorSubtract(impactPoint, hitEnt->currentOrigin, dir2Impact); + dir2Impact[2] = 0; + VectorNormalize(dir2Impact); + VectorSet(fwdAngles, 0, hitEnt->client->ps.viewangles[YAW], 0); + AngleVectors(fwdAngles, facing, NULL, NULL); + float dot = DotProduct(facing, dir2Impact); //-1 = hit in front, 0 = hit on side, 1 = hit in back + if (dot > 0.5f) { // kicked in chest, fly backward + switch (Q_irand(0, 4)) { // FIXME: don't start at beginning of anim? + case 0: + anim = BOTH_DEATH1; // thrown backwards + break; + case 1: + anim = BOTH_DEATH2; // fall backwards + break; + case 2: + anim = BOTH_DEATH15; // roll over backwards + break; + case 3: + anim = BOTH_DEATH22; // fast fall back + break; + case 4: + anim = BOTH_DEATH23; // fast fall back + break; } - else if ( dot < -0.5f ) - {//kicked in back, fly forward - switch ( Q_irand( 0, 5 ) ) - {//FIXME: don't start at beginning of anim? - case 0: - anim = BOTH_DEATH14; - break; - case 1: - anim = BOTH_DEATH24; - break; - case 2: - anim = BOTH_DEATH25; - break; - case 3: - anim = BOTH_DEATH4;//thrown forwards - break; - case 4: - anim = BOTH_DEATH5;//thrown forwards - break; - case 5: - anim = BOTH_DEATH16;//thrown forwards - break; - } + } else if (dot < -0.5f) { // kicked in back, fly forward + switch (Q_irand(0, 5)) { // FIXME: don't start at beginning of anim? + case 0: + anim = BOTH_DEATH14; + break; + case 1: + anim = BOTH_DEATH24; + break; + case 2: + anim = BOTH_DEATH25; + break; + case 3: + anim = BOTH_DEATH4; // thrown forwards + break; + case 4: + anim = BOTH_DEATH5; // thrown forwards + break; + case 5: + anim = BOTH_DEATH16; // thrown forwards + break; } - else - {//hit on side, spin - switch ( Q_irand( 0, 2 ) ) - {//FIXME: don't start at beginning of anim? - case 0: - anim = BOTH_DEATH12; - break; - case 1: - anim = BOTH_DEATH14; - break; - case 2: - anim = BOTH_DEATH15; - break; - case 3: - anim = BOTH_DEATH6; - break; - case 4: - anim = BOTH_DEATH8; - break; - } + } else { // hit on side, spin + switch (Q_irand(0, 2)) { // FIXME: don't start at beginning of anim? + case 0: + anim = BOTH_DEATH12; + break; + case 1: + anim = BOTH_DEATH14; + break; + case 2: + anim = BOTH_DEATH15; + break; + case 3: + anim = BOTH_DEATH6; + break; + case 4: + anim = BOTH_DEATH8; + break; } } - break; + } break; } - if ( anim != -1 ) - { - NPC_SetAnim( hitEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (anim != -1) { + NPC_SetAnim(hitEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } -gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t kickEnd, int kickDamage, float kickPush, qboolean doSoundOnWalls ) -{ - vec3_t traceOrg, traceEnd, kickMins={-2,-2,-2}, kickMaxs={2,2,2}; - trace_t trace; - gentity_t *hitEnt = NULL; - //FIXME: variable kick height? - if ( kickEnd && !VectorCompare( kickEnd, vec3_origin ) ) - {//they passed us the end point of the trace, just use that - //this makes the trace flat - VectorSet( traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], kickEnd[2] ); - VectorCopy( kickEnd, traceEnd ); - } - else - {//extrude - VectorSet( traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2]+ent->maxs[2]*0.5f ); - VectorMA( traceOrg, kickDist, kickDir, traceEnd ); - } - - gi.trace( &trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 );//clipmask ok? - if ( trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid && trace.entityNum < ENTITYNUM_NONE ) - { +gentity_t *G_KickTrace(gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t kickEnd, int kickDamage, float kickPush, qboolean doSoundOnWalls) { + vec3_t traceOrg, traceEnd, kickMins = {-2, -2, -2}, kickMaxs = {2, 2, 2}; + trace_t trace; + gentity_t *hitEnt = NULL; + // FIXME: variable kick height? + if (kickEnd && !VectorCompare(kickEnd, vec3_origin)) { // they passed us the end point of the trace, just use that + // this makes the trace flat + VectorSet(traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], kickEnd[2]); + VectorCopy(kickEnd, traceEnd); + } else { // extrude + VectorSet(traceOrg, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + ent->maxs[2] * 0.5f); + VectorMA(traceOrg, kickDist, kickDir, traceEnd); + } + + gi.trace(&trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0); // clipmask ok? + if (trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid && trace.entityNum < ENTITYNUM_NONE) { hitEnt = &g_entities[trace.entityNum]; - if ( ent->client->ps.lastKickedEntNum != trace.entityNum ) - { - TIMER_Remove( ent, "kickSoundDebounce" ); + if (ent->client->ps.lastKickedEntNum != trace.entityNum) { + TIMER_Remove(ent, "kickSoundDebounce"); ent->client->ps.lastKickedEntNum = trace.entityNum; } - if ( hitEnt ) - {//we hit an entity - if ( hitEnt->client ) - { - if ( !(hitEnt->client->ps.pm_flags&PMF_TIME_KNOCKBACK) - && TIMER_Done( hitEnt, "kickedDebounce" ) )//not already flying through air? Intended to stop multiple hits, but... - {//FIXME: this should not always work - if ( PM_InKnockDown( &hitEnt->client->ps ) - && !PM_InGetUp( &hitEnt->client->ps ) ) - {//don't hit people who are knocked down or being knocked down (okay to hit people getting up, though) + if (hitEnt) { // we hit an entity + if (hitEnt->client) { + if (!(hitEnt->client->ps.pm_flags & PMF_TIME_KNOCKBACK) && + TIMER_Done(hitEnt, "kickedDebounce")) // not already flying through air? Intended to stop multiple hits, but... + { // FIXME: this should not always work + if (PM_InKnockDown(&hitEnt->client->ps) && + !PM_InGetUp( + &hitEnt->client->ps)) { // don't hit people who are knocked down or being knocked down (okay to hit people getting up, though) return NULL; } - if ( PM_InRoll( &hitEnt->client->ps ) ) - {//can't hit people who are rolling + if (PM_InRoll(&hitEnt->client->ps)) { // can't hit people who are rolling return NULL; } - //don't hit same ent more than once per kick - if ( hitEnt->takedamage ) - {//hurt it - G_Damage( hitEnt, ent, ent, kickDir, trace.endpos, kickDamage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_KILL, MOD_MELEE ); + // don't hit same ent more than once per kick + if (hitEnt->takedamage) { // hurt it + G_Damage(hitEnt, ent, ent, kickDir, trace.endpos, kickDamage, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_KILL, MOD_MELEE); } - //do kick hit sound and impact effect - if ( TIMER_Done( ent, "kickSoundDebounce" ) ) - { - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - { - G_Sound( ent, G_SoundIndex( "sound/movers/objects/saber_slam" ) ); - } - else - { + // do kick hit sound and impact effect + if (TIMER_Done(ent, "kickSoundDebounce")) { + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { + G_Sound(ent, G_SoundIndex("sound/movers/objects/saber_slam")); + } else { vec3_t fxOrg, fxDir; - VectorCopy( kickDir, fxDir ); - VectorMA( trace.endpos, Q_flrand( 5.0f, 10.0f ), fxDir, fxOrg ); - VectorScale( fxDir, -1, fxDir ); - G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), fxOrg, fxDir ); - //G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + VectorCopy(kickDir, fxDir); + VectorMA(trace.endpos, Q_flrand(5.0f, 10.0f), fxDir, fxOrg); + VectorScale(fxDir, -1, fxDir); + G_PlayEffect(G_EffectIndex("melee/kick_impact"), fxOrg, fxDir); + // G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); } - TIMER_Set( ent, "kickSoundDebounce", 2000 ); + TIMER_Set(ent, "kickSoundDebounce", 2000); } - TIMER_Set( hitEnt, "kickedDebounce", 1000 ); - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - {//hit in head - if ( hitEnt->health > 0 ) - {//knock down - if ( kickPush >= 150.0f/*75.0f*/ && !Q_irand( 0, 1 ) ) - {//knock them down - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush/3.0f ); - } - G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); - } - else - {//force them to play a pain anim - if ( hitEnt->s.number < MAX_CLIENTS ) - { - NPC_SetPainEvent( hitEnt ); + TIMER_Set(hitEnt, "kickedDebounce", 1000); + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { // hit in head + if (hitEnt->health > 0) { // knock down + if (kickPush >= 150.0f /*75.0f*/ && !Q_irand(0, 1)) { // knock them down + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush / 3.0f); } - else - { - GEntity_PainFunc( hitEnt, ent, ent, hitEnt->currentOrigin, 0, MOD_MELEE ); + G_Knockdown(hitEnt, ent, kickDir, 300, qtrue); + } else { // force them to play a pain anim + if (hitEnt->s.number < MAX_CLIENTS) { + NPC_SetPainEvent(hitEnt); + } else { + GEntity_PainFunc(hitEnt, ent, ent, hitEnt->currentOrigin, 0, MOD_MELEE); } } - //just so we don't hit him again... + // just so we don't hit him again... hitEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; hitEnt->client->ps.pm_time = 100; - } - else - { - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush ); + } else { + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush); } - //see if we should play a better looking death on them - G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); + // see if we should play a better looking death on them + G_ThrownDeathAnimForDeathAnim(hitEnt, trace.endpos); } - } - else if ( ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B - || ent->client->ps.legsAnim == BOTH_GETUP_BROLL_F - || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B - || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_F ) - { - if ( hitEnt->health > 0 ) - {//knock down - if ( hitEnt->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//he's in the air? Send him flying back - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush ); + } else if (ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_BROLL_F || + ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_F) { + if (hitEnt->health > 0) { // knock down + if (hitEnt->client->ps.groundEntityNum == ENTITYNUM_NONE) { // he's in the air? Send him flying back + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush); } - } - else - { - //just so we don't hit him again... + } else { + // just so we don't hit him again... hitEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; hitEnt->client->ps.pm_time = 100; } - //knock them down - G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); - } - else - { - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush ); + // knock them down + G_Knockdown(hitEnt, ent, kickDir, 300, qtrue); + } else { + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush); } - //see if we should play a better looking death on them - G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); - } - } - else if ( hitEnt->health <= 0 ) - {//we kicked a dead guy - //throw harder - FIXME: no matter how hard I push them, they don't go anywhere... corpses use less physics??? - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush*4 ); + // see if we should play a better looking death on them + G_ThrownDeathAnimForDeathAnim(hitEnt, trace.endpos); } - //see if we should play a better looking death on them - G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); - } - else - { - if ( !(hitEnt->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( hitEnt, kickDir, kickPush ); + } else if (hitEnt->health <= 0) { // we kicked a dead guy + // throw harder - FIXME: no matter how hard I push them, they don't go anywhere... corpses use less physics??? + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush * 4); } - if ( kickPush >= 150.0f/*75.0f*/ && !Q_irand( 0, 2 ) ) - { - G_Knockdown( hitEnt, ent, kickDir, 300, qtrue ); + // see if we should play a better looking death on them + G_ThrownDeathAnimForDeathAnim(hitEnt, trace.endpos); + } else { + if (!(hitEnt->flags & FL_NO_KNOCKBACK)) { + G_Throw(hitEnt, kickDir, kickPush); } - else - { - G_Knockdown( hitEnt, ent, kickDir, kickPush, qtrue ); + if (kickPush >= 150.0f /*75.0f*/ && !Q_irand(0, 2)) { + G_Knockdown(hitEnt, ent, kickDir, 300, qtrue); + } else { + G_Knockdown(hitEnt, ent, kickDir, kickPush, qtrue); } } } - } - else - {//FIXME: don't do this in repeated frames... only allow 1 frame in kick to hit wall? The most extended one? Pass in a bool on that frame. - if ( doSoundOnWalls ) - {//do kick hit sound and impact effect - if ( TIMER_Done( ent, "kickSoundDebounce" ) ) - { - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - { - G_Sound( ent, G_SoundIndex( "sound/movers/objects/saber_slam" ) ); - } - else - { - G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), trace.endpos, trace.plane.normal ); - //G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + } else { // FIXME: don't do this in repeated frames... only allow 1 frame in kick to hit wall? The most extended one? Pass in a bool on that + // frame. + if (doSoundOnWalls) { // do kick hit sound and impact effect + if (TIMER_Done(ent, "kickSoundDebounce")) { + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { + G_Sound(ent, G_SoundIndex("sound/movers/objects/saber_slam")); + } else { + G_PlayEffect(G_EffectIndex("melee/kick_impact"), trace.endpos, trace.plane.normal); + // G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); } - TIMER_Set( ent, "kickSoundDebounce", 2000 ); + TIMER_Set(ent, "kickSoundDebounce", 2000); } } } @@ -2134,251 +1785,203 @@ gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t k return (hitEnt); } -qboolean G_CheckRollSafety( gentity_t *self, int anim, float testDist ) -{ - vec3_t forward, right, testPos, angles; - trace_t trace; - int contents = (CONTENTS_SOLID|CONTENTS_BOTCLIP); +qboolean G_CheckRollSafety(gentity_t *self, int anim, float testDist) { + vec3_t forward, right, testPos, angles; + trace_t trace; + int contents = (CONTENTS_SOLID | CONTENTS_BOTCLIP); - if ( !self || !self->client ) - { + if (!self || !self->client) { return qfalse; } - if ( self->s.number < MAX_CLIENTS ) - {//player + if (self->s.number < MAX_CLIENTS) { // player contents |= CONTENTS_PLAYERCLIP; - } - else - {//NPC + } else { // NPC contents |= CONTENTS_MONSTERCLIP; } - if ( PM_InAttackRoll( self->client->ps.legsAnim ) ) - {//we don't care if people are in the way, we'll knock them down! + if (PM_InAttackRoll(self->client->ps.legsAnim)) { // we don't care if people are in the way, we'll knock them down! contents &= ~CONTENTS_BODY; } angles[PITCH] = angles[ROLL] = 0; - angles[YAW] = self->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); + angles[YAW] = self->client->ps.viewangles[YAW]; // Add ucmd.angles[YAW]? + AngleVectors(angles, forward, right, NULL); - switch ( anim ) - { + switch (anim) { case BOTH_GETUP_BROLL_R: case BOTH_GETUP_FROLL_R: - VectorMA( self->currentOrigin, testDist, right, testPos ); + VectorMA(self->currentOrigin, testDist, right, testPos); break; case BOTH_GETUP_BROLL_L: case BOTH_GETUP_FROLL_L: - VectorMA( self->currentOrigin, -testDist, right, testPos ); + VectorMA(self->currentOrigin, -testDist, right, testPos); break; case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_F: - VectorMA( self->currentOrigin, testDist, forward, testPos ); + VectorMA(self->currentOrigin, testDist, forward, testPos); break; case BOTH_GETUP_BROLL_B: case BOTH_GETUP_FROLL_B: - VectorMA( self->currentOrigin, -testDist, forward, testPos ); + VectorMA(self->currentOrigin, -testDist, forward, testPos); break; - default://FIXME: add normal rolls? Make generic for any forced-movement anim? + default: // FIXME: add normal rolls? Make generic for any forced-movement anim? return qtrue; break; } - gi.trace( &trace, self->currentOrigin, self->mins, self->maxs, testPos, self->s.number, contents, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f - || trace.allsolid - || trace.startsolid ) - {//inside something or will hit something + gi.trace(&trace, self->currentOrigin, self->mins, self->maxs, testPos, self->s.number, contents, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) { // inside something or will hit something return qfalse; } return qtrue; } -void G_CamPullBackForLegsAnim( gentity_t *ent, qboolean useTorso = qfalse ) -{ - if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (useTorso?(animNumber_t)ent->client->ps.torsoAnim:(animNumber_t)ent->client->ps.legsAnim) ); - float elapsedTime = (float)(animLength-(useTorso?ent->client->ps.torsoAnimTimer:ent->client->ps.legsAnimTimer)); +void G_CamPullBackForLegsAnim(gentity_t *ent, qboolean useTorso = qfalse) { + if ((ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent))) { + float animLength = + PM_AnimLength(ent->client->clientInfo.animFileIndex, (useTorso ? (animNumber_t)ent->client->ps.torsoAnim : (animNumber_t)ent->client->ps.legsAnim)); + float elapsedTime = (float)(animLength - (useTorso ? ent->client->ps.torsoAnimTimer : ent->client->ps.legsAnimTimer)); float backDist = 0; - if ( elapsedTime < animLength/2.0f ) - {//starting anim - backDist = (elapsedTime/animLength)*120.0f; - } - else - {//ending anim - backDist = ((animLength-elapsedTime)/animLength)*120.0f; + if (elapsedTime < animLength / 2.0f) { // starting anim + backDist = (elapsedTime / animLength) * 120.0f; + } else { // ending anim + backDist = ((animLength - elapsedTime) / animLength) * 120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; - cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; + cg.overrides.thirdPersonRange = cg_thirdPersonRange.value + backDist; } } -void G_CamCircleForLegsAnim( gentity_t *ent ) -{ - if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); +void G_CamCircleForLegsAnim(gentity_t *ent) { + if ((ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent))) { + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); float angle = 0; - angle = (elapsedTime/animLength)*360.0f; + angle = (elapsedTime / animLength) * 360.0f; cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; + cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value + angle; } } -qboolean G_GrabClient( gentity_t *ent, usercmd_t *ucmd ) -{ - gentity_t *bestEnt = NULL, *radiusEnts[ 128 ]; - int numEnts; - const float radius = 100.0f; - const float radiusSquared = (radius*radius); - float bestDistSq = (radiusSquared+1.0f), distSq; - int i; - vec3_t boltOrg; +qboolean G_GrabClient(gentity_t *ent, usercmd_t *ucmd) { + gentity_t *bestEnt = NULL, *radiusEnts[128]; + int numEnts; + const float radius = 100.0f; + const float radiusSquared = (radius * radius); + float bestDistSq = (radiusSquared + 1.0f), distSq; + int i; + vec3_t boltOrg; - numEnts = G_GetEntsNearBolt( ent, radiusEnts, radius, ent->handRBolt, boltOrg ); + numEnts = G_GetEntsNearBolt(ent, radiusEnts, radius, ent->handRBolt, boltOrg); - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == ent ) - {//Skip the rancor ent + if (radiusEnts[i] == ent) { // Skip the rancor ent continue; } - if ( !radiusEnts[i]->inuse || radiusEnts[i]->health <= 0 ) - {//must be alive + if (!radiusEnts[i]->inuse || radiusEnts[i]->health <= 0) { // must be alive continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client + if (radiusEnts[i]->client == NULL) { // must be a client continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) - ||(radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) - ||(radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR) || (radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_WAMPA) || + (radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE)) { // can't be one being held continue; } - if ( PM_LockedAnim( radiusEnts[i]->client->ps.torsoAnim ) - || PM_LockedAnim( radiusEnts[i]->client->ps.legsAnim ) ) - {//don't interrupt + if (PM_LockedAnim(radiusEnts[i]->client->ps.torsoAnim) || PM_LockedAnim(radiusEnts[i]->client->ps.legsAnim)) { // don't interrupt continue; } - if ( radiusEnts[i]->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//must be on ground + if (radiusEnts[i]->client->ps.groundEntityNum == ENTITYNUM_NONE) { // must be on ground continue; } - if ( PM_InOnGroundAnim( &radiusEnts[i]->client->ps ) ) - {//must be standing up + if (PM_InOnGroundAnim(&radiusEnts[i]->client->ps)) { // must be standing up continue; } - if ( fabs(radiusEnts[i]->currentOrigin[2]-ent->currentOrigin[2])>8.0f ) - {//have to be close in Z + if (fabs(radiusEnts[i]->currentOrigin[2] - ent->currentOrigin[2]) > 8.0f) { // have to be close in Z continue; } - if ( !PM_HasAnimation( radiusEnts[i], BOTH_PLAYER_PA_1 ) ) - {//doesn't have matching anims + if (!PM_HasAnimation(radiusEnts[i], BOTH_PLAYER_PA_1)) { // doesn't have matching anims continue; } - distSq = DistanceSquared( radiusEnts[i]->currentOrigin, boltOrg ); - if ( distSq < bestDistSq ) - { + distSq = DistanceSquared(radiusEnts[i]->currentOrigin, boltOrg); + if (distSq < bestDistSq) { bestDistSq = distSq; bestEnt = radiusEnts[i]; } } - if ( bestEnt != NULL ) - { + if (bestEnt != NULL) { int lockType = LOCK_KYLE_GRAB1; - if ( ucmd->forwardmove > 0 ) - { + if (ucmd->forwardmove > 0) { lockType = LOCK_KYLE_GRAB3; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { lockType = LOCK_KYLE_GRAB2; } - WP_SabersCheckLock2( ent, bestEnt, (sabersLockMode_t)lockType ); + WP_SabersCheckLock2(ent, bestEnt, (sabersLockMode_t)lockType); return qtrue; } return qfalse; } -qboolean G_PullAttack( gentity_t *ent, usercmd_t *ucmd ) -{ +qboolean G_PullAttack(gentity_t *ent, usercmd_t *ucmd) { qboolean overridAngles = qfalse; - if ( ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB - || ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING ) - {//pulling - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB || ent->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING) { // pulling + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - } - else if ( ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_B - || ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_F ) - {//being pulled + } else if (ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_B || ent->client->ps.torsoAnim == BOTH_PULLED_INAIR_F) { // being pulled gentity_t *puller = &g_entities[ent->client->ps.pullAttackEntNum]; - if ( puller - && puller->inuse - && puller->client - && ( puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB - || puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING ) ) - { + if (puller && puller->inuse && puller->client && + (puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB || puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_SWING)) { vec3_t pullDir; vec3_t pullPos; - //calc where to pull me to + // calc where to pull me to /* VectorCopy( puller->client->ps.saber[0].blade[0].muzzlePoint, pullPos ); VectorMA( pullPos, puller->client->ps.saber[0].blade[0].length*0.5f, puller->client->ps.saber[0].blade[0].muzzleDir, pullPos ); */ vec3_t pullerFwd; - AngleVectors( puller->client->ps.viewangles, pullerFwd, NULL, NULL ); - VectorMA( puller->currentOrigin, (puller->maxs[0]*1.5f)+16.0f, pullerFwd, pullPos ); - //pull me towards that pos - VectorSubtract( pullPos, ent->currentOrigin, pullDir ); - float pullDist = VectorNormalize( pullDir ); - int sweetSpotTime = (puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB)?1250:1350; - float pullLength = PM_AnimLength( puller->client->clientInfo.animFileIndex, (animNumber_t)puller->client->ps.torsoAnim )-sweetSpotTime; - if ( pullLength <= 0.25f ) - { + AngleVectors(puller->client->ps.viewangles, pullerFwd, NULL, NULL); + VectorMA(puller->currentOrigin, (puller->maxs[0] * 1.5f) + 16.0f, pullerFwd, pullPos); + // pull me towards that pos + VectorSubtract(pullPos, ent->currentOrigin, pullDir); + float pullDist = VectorNormalize(pullDir); + int sweetSpotTime = (puller->client->ps.torsoAnim == BOTH_PULL_IMPALE_STAB) ? 1250 : 1350; + float pullLength = PM_AnimLength(puller->client->clientInfo.animFileIndex, (animNumber_t)puller->client->ps.torsoAnim) - sweetSpotTime; + if (pullLength <= 0.25f) { pullLength = 0.25f; } - //float pullTimeRemaining = ent->client->ps.pullAttackTime - level.time; + // float pullTimeRemaining = ent->client->ps.pullAttackTime - level.time; - //float pullSpeed = pullDist * (pullTimeRemaining/pullLength); - float pullSpeed = (pullDist*1000.0f)/pullLength; + // float pullSpeed = pullDist * (pullTimeRemaining/pullLength); + float pullSpeed = (pullDist * 1000.0f) / pullLength; - VectorScale( pullDir, pullSpeed, ent->client->ps.velocity ); - //slide, if necessary + VectorScale(pullDir, pullSpeed, ent->client->ps.velocity); + // slide, if necessary ent->client->ps.pm_flags |= PMF_TIME_NOFRICTION; ent->client->ps.pm_time = 100; - //make it so I don't actually hurt them when pulled at them... + // make it so I don't actually hurt them when pulled at them... ent->forcePuller = puller->s.number; ent->forcePushTime = level.time + 100; // let the push effect last for 100 more ms - //look at him - PM_AdjustAnglesToPuller( ent, puller, ucmd, qboolean(ent->client->ps.legsAnim==BOTH_PULLED_INAIR_B) ); + // look at him + PM_AdjustAnglesToPuller(ent, puller, ucmd, qboolean(ent->client->ps.legsAnim == BOTH_PULLED_INAIR_B)); overridAngles = qtrue; - //don't move - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + // don't move + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } @@ -2386,310 +1989,239 @@ qboolean G_PullAttack( gentity_t *ent, usercmd_t *ucmd ) return overridAngles; } -void G_FixMins( gentity_t *ent ) -{ - //do a trace to make sure it's okay - float downdist = (DEFAULT_MINS_2-ent->mins[2]); - vec3_t end={ent->currentOrigin[0],ent->currentOrigin[1],ent->currentOrigin[2]+downdist}; - trace_t trace; - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid ) - { - if ( trace.fraction >= 1.0f ) - {//all clear - //drop the bottom of my bbox back down +void G_FixMins(gentity_t *ent) { + // do a trace to make sure it's okay + float downdist = (DEFAULT_MINS_2 - ent->mins[2]); + vec3_t end = {ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + downdist}; + trace_t trace; + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid) { + if (trace.fraction >= 1.0f) { // all clear + // drop the bottom of my bbox back down ent->mins[2] = DEFAULT_MINS_2; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } - } - else - {//move me up so the bottom of my bbox will be where the trace ended, at least - //need to trace up, too - float updist = ((1.0f-trace.fraction) * -downdist); - end[2] = ent->currentOrigin[2]+updist; - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.allsolid && !trace.startsolid ) - { - if ( trace.fraction >= 1.0f ) - {//all clear - //move me up + } else { // move me up so the bottom of my bbox will be where the trace ended, at least + // need to trace up, too + float updist = ((1.0f - trace.fraction) * -downdist); + end[2] = ent->currentOrigin[2] + updist; + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (!trace.allsolid && !trace.startsolid) { + if (trace.fraction >= 1.0f) { // all clear + // move me up ent->currentOrigin[2] += updist; - //drop the bottom of my bbox back down + // drop the bottom of my bbox back down ent->mins[2] = DEFAULT_MINS_2; - G_SetOrigin( ent, ent->currentOrigin ); - gi.linkentity( ent ); - if ( ent->client ) - { + G_SetOrigin(ent, ent->currentOrigin); + gi.linkentity(ent); + if (ent->client) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } - } - else - {//crap, no room to expand! - if ( ent->client->ps.legsAnimTimer <= 200 ) - {//at the end of the anim, and we can't leave ourselves like this - //so drop the maxs, put the mins back and move us up + } else { // crap, no room to expand! + if (ent->client->ps.legsAnimTimer <= 200) { // at the end of the anim, and we can't leave ourselves like this + // so drop the maxs, put the mins back and move us up ent->maxs[2] += downdist; ent->currentOrigin[2] -= downdist; ent->mins[2] = DEFAULT_MINS_2; - G_SetOrigin( ent, ent->currentOrigin ); - gi.linkentity( ent ); - //this way we'll be in a crouch when we're done + G_SetOrigin(ent, ent->currentOrigin); + gi.linkentity(ent); + // this way we'll be in a crouch when we're done ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; ent->client->ps.pm_flags |= PMF_DUCKED; - //FIXME: do we need to set a crouch anim here? - if ( ent->client ) - { + // FIXME: do we need to set a crouch anim here? + if (ent->client) { ent->client->ps.pm_flags &= ~PMF_FIX_MINS; } } } - }//crap, stuck + } // crap, stuck } - }//crap, stuck! + } // crap, stuck! } - -qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) -{ +qboolean G_CheckClampUcmd(gentity_t *ent, usercmd_t *ucmd) { qboolean overridAngles = qfalse; - if ( ent->client->NPC_class == CLASS_PROTOCOL - || ent->client->NPC_class == CLASS_R2D2 - || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_GONK - || ent->client->NPC_class == CLASS_MOUSE ) - {//these droids *cannot* strafe (looks bad) - if ( ucmd->rightmove ) - { - //clear the strafe + if (ent->client->NPC_class == CLASS_PROTOCOL || ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || + ent->client->NPC_class == CLASS_GONK || ent->client->NPC_class == CLASS_MOUSE) { // these droids *cannot* strafe (looks bad) + if (ucmd->rightmove) { + // clear the strafe ucmd->rightmove = 0; - //movedir is invalid now, but PM_WalkMove will rebuild it from the ucmds, with the appropriate speed - VectorClear( ent->client->ps.moveDir ); + // movedir is invalid now, but PM_WalkMove will rebuild it from the ucmds, with the appropriate speed + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.pullAttackEntNum < ENTITYNUM_WORLD - && ent->client->ps.pullAttackTime > level.time ) - { - return G_PullAttack( ent, ucmd ); + if (ent->client->ps.pullAttackEntNum < ENTITYNUM_WORLD && ent->client->ps.pullAttackTime > level.time) { + return G_PullAttack(ent, ucmd); } - if ( (ent->s.number < MAX_CLIENTS||G_ControlledByPlayer(ent)) - && ent->s.weapon == WP_MELEE - && ent->client->ps.torsoAnim == BOTH_KYLE_GRAB ) - {//see if we grabbed enemy - if ( ent->client->ps.torsoAnimTimer <= 200 ) - {//close to end of anim - if ( G_GrabClient( ent, ucmd ) ) - {//grabbed someone! - } - else - {//missed - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent)) && ent->s.weapon == WP_MELEE && + ent->client->ps.torsoAnim == BOTH_KYLE_GRAB) { // see if we grabbed enemy + if (ent->client->ps.torsoAnimTimer <= 200) { // close to end of anim + if (G_GrabClient(ent, ucmd)) { // grabbed someone! + } else { // missed + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; } } ucmd->rightmove = ucmd->forwardmove = ucmd->upmove = 0; } - if ( (!ent->s.number&&ent->aimDebounceTime>level.time) - || (ent->client->ps.pm_time && (ent->client->ps.pm_flags&PMF_TIME_KNOCKBACK)) - || ent->forcePushTime > level.time ) - {//being knocked back, can't do anything! + if ((!ent->s.number && ent->aimDebounceTime > level.time) || (ent->client->ps.pm_time && (ent->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) || + ent->forcePushTime > level.time) { // being knocked back, can't do anything! ucmd->buttons = 0; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - overridAngles = (PM_AdjustAnglesForKnockdown( ent, ucmd, qfalse )?qtrue:overridAngles); - if ( PM_GetupAnimNoMove( ent->client->ps.legsAnim ) ) - { - ucmd->forwardmove = ucmd->rightmove = 0;//ucmd->upmove = ? + overridAngles = (PM_AdjustAnglesForKnockdown(ent, ucmd, qfalse) ? qtrue : overridAngles); + if (PM_GetupAnimNoMove(ent->client->ps.legsAnim)) { + ucmd->forwardmove = ucmd->rightmove = 0; // ucmd->upmove = ? } - //check saberlock - if ( ent->client->ps.saberLockTime > level.time ) - {//in saberlock + // check saberlock + if (ent->client->ps.saberLockTime > level.time) { // in saberlock ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.saberLockTime - level.time > SABER_LOCK_DELAYED_TIME ) - {//2 second delay before either can push - //FIXME: base on difficulty + if (ent->client->ps.saberLockTime - level.time > SABER_LOCK_DELAYED_TIME) { // 2 second delay before either can push + // FIXME: base on difficulty ucmd->buttons = 0; + } else { + ucmd->buttons &= ~(ucmd->buttons & ~BUTTON_ATTACK); } - else - { - ucmd->buttons &= ~(ucmd->buttons&~BUTTON_ATTACK); - } - overridAngles = (PM_AdjustAnglesForSaberLock( ent, ucmd )?qtrue:overridAngles); - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + overridAngles = (PM_AdjustAnglesForSaberLock(ent, ucmd) ? qtrue : overridAngles); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - //check force drain - if ( (ent->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_DRAIN))) { // draining ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS); - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.saberMove == LS_A_LUNGE ) - {//can't move during lunge + if (ent->client->ps.saberMove == LS_A_LUNGE) { // can't move during lunge ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.legsAnimTimer > 500 && (ent->s.number || !player_locked) ) - { + if (ent->client->ps.legsAnimTimer > 500 && (ent->s.number || !player_locked)) { ucmd->forwardmove = 127; - } - else - { + } else { ucmd->forwardmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_ALT - && ent->client->ps.legsAnimTimer ) - { - vec3_t vFwd, fwdAng = {0,ent->currentAngles[YAW],0}; - AngleVectors( fwdAng, vFwd, NULL, NULL ); - if ( ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + if (ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_ALT && ent->client->ps.legsAnimTimer) { + vec3_t vFwd, fwdAng = {0, ent->currentAngles[YAW], 0}; + AngleVectors(fwdAng, vFwd, NULL, NULL); + if (ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { float savZ = ent->client->ps.velocity[2]; - VectorScale( vFwd, 100, ent->client->ps.velocity ); + VectorScale(vFwd, 100, ent->client->ps.velocity); ent->client->ps.velocity[2] = savZ; } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - overridAngles = (PM_AdjustAnglesForWallRunUpFlipAlt( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_AdjustAnglesForWallRunUpFlipAlt(ent, ucmd) ? qtrue : overridAngles); } - if ( ent->client->ps.saberMove == LS_A_JUMP_T__B_ ) - {//can't move during leap - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE || (!ent->s.number && player_locked) ) - {//hit the ground + if (ent->client->ps.saberMove == LS_A_JUMP_T__B_) { // can't move during leap + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE || (!ent->s.number && player_locked)) { // hit the ground ucmd->forwardmove = 0; } ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.saberMove == LS_A_BACKFLIP_ATK - && ent->client->ps.legsAnim == BOTH_JUMPATTACK7 ) - {//backflip attack - if ( ent->client->ps.legsAnimTimer > 800 //not at end - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK7 ) - ent->client->ps.legsAnimTimer >= 400 )//not in beginning - {//middle of anim - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? + if (ent->client->ps.saberMove == LS_A_BACKFLIP_ATK && ent->client->ps.legsAnim == BOTH_JUMPATTACK7) { // backflip attack + if (ent->client->ps.legsAnimTimer > 800 // not at end + && PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK7) - ent->client->ps.legsAnimTimer >= 400) // not in beginning + { // middle of anim + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // still on ground? vec3_t yawAngles, backDir; - //push backwards some? - VectorSet( yawAngles, 0, ent->client->ps.viewangles[YAW]+180, 0 ); - AngleVectors( yawAngles, backDir, 0, 0 ); - VectorScale( backDir, 100, ent->client->ps.velocity ); + // push backwards some? + VectorSet(yawAngles, 0, ent->client->ps.viewangles[YAW] + 180, 0); + AngleVectors(yawAngles, backDir, 0, 0); + VectorScale(backDir, 100, ent->client->ps.velocity); - //jump! + // jump! ent->client->ps.velocity[2] = 180; - ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height - ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + ent->client->ps.forceJumpZStart = ent->client->ps.origin[2]; // so we don't take damage if we land at same height + ent->client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - G_AddEvent( ent, EV_JUMP, 0 ); - G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - ucmd->upmove = 0;//clear any actual jump command + // FIXME: NPCs yell? + G_AddEvent(ent, EV_JUMP, 0); + G_SoundOnEnt(ent, CHAN_BODY, "sound/weapons/force/jump.wav"); + ucmd->upmove = 0; // clear any actual jump command } } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - - if ( ent->client->ps.legsAnim == BOTH_JUMPATTACK6 - && ent->client->ps.legsAnimTimer > 0 ) - { + if (ent->client->ps.legsAnim == BOTH_JUMPATTACK6 && ent->client->ps.legsAnimTimer > 0) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - //FIXME: don't slide off people/obstacles? - if ( ent->client->ps.legsAnimTimer >= 100 //not at end - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 250 )//not in beginning - {//middle of anim - //push forward + // FIXME: don't slide off people/obstacles? + if (ent->client->ps.legsAnimTimer >= 100 // not at end + && PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6) - ent->client->ps.legsAnimTimer >= 250) // not in beginning + { // middle of anim + // push forward ucmd->forwardmove = 127; } - if ( (ent->client->ps.legsAnimTimer >= 900 //not at end - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 950 ) //not in beginning - || ( ent->client->ps.legsAnimTimer >= 1600 - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 400 ) )//not in beginning - {//one of the two jumps - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? - //jump! + if ((ent->client->ps.legsAnimTimer >= 900 // not at end + && PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6) - ent->client->ps.legsAnimTimer >= 950) // not in beginning + || (ent->client->ps.legsAnimTimer >= 1600 && + PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6) - ent->client->ps.legsAnimTimer >= 400)) // not in beginning + { // one of the two jumps + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // still on ground? + // jump! ent->client->ps.velocity[2] = 250; - ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height - ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - G_AddEvent( ent, EV_JUMP, 0 ); - G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - else - {//FIXME: if this is the second jump, maybe we should just stop the anim? + ent->client->ps.forceJumpZStart = ent->client->ps.origin[2]; // so we don't take damage if we land at same height + ent->client->ps.pm_flags |= PMF_JUMPING; //|PMF_SLOW_MO_FALL; + // FIXME: NPCs yell? + G_AddEvent(ent, EV_JUMP, 0); + G_SoundOnEnt(ent, CHAN_BODY, "sound/weapons/force/jump.wav"); + } else { // FIXME: if this is the second jump, maybe we should just stop the anim? } } - //else - {//disallow turning unless in the middle frame when you're on the ground - //overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); + // else + { // disallow turning unless in the middle frame when you're on the ground + // overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); } - //dynamically reduce bounding box to let character sail over heads of enemies - if ( ( ent->client->ps.legsAnimTimer >= 1450 - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 400 ) - ||(ent->client->ps.legsAnimTimer >= 400 - && PM_AnimLength( ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6 ) - ent->client->ps.legsAnimTimer >= 1100 ) ) - {//in a part of the anim that we're pretty much sideways in, raise up the mins + // dynamically reduce bounding box to let character sail over heads of enemies + if ((ent->client->ps.legsAnimTimer >= 1450 && + PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6) - ent->client->ps.legsAnimTimer >= 400) || + (ent->client->ps.legsAnimTimer >= 400 && PM_AnimLength(ent->client->clientInfo.animFileIndex, BOTH_JUMPATTACK6) - ent->client->ps.legsAnimTimer >= + 1100)) { // in a part of the anim that we're pretty much sideways in, raise up the mins ent->mins[2] = 0; ent->client->ps.pm_flags |= PMF_FIX_MINS; + } else if ((ent->client->ps.pm_flags & PMF_FIX_MINS)) { // drop the mins back down + G_FixMins(ent); } - else if ( (ent->client->ps.pm_flags&PMF_FIX_MINS) ) - {//drop the mins back down - G_FixMins( ent ); - } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } + } else if ((ent->client->ps.pm_flags & PMF_FIX_MINS)) { + G_FixMins(ent); } - else if ( (ent->client->ps.pm_flags&PMF_FIX_MINS) ) - { - G_FixMins( ent ); - } - - if ( ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 - && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_LEFT ) - || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 - && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_RIGHT ) - || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT - && ent->client->ps.saberMove == LS_BUTTERFLY_RIGHT ) - || ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT - && ent->client->ps.saberMove == LS_BUTTERFLY_LEFT ) ) - {//forward flip/spin attack + + if ((ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_LEFT) || + (ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 && ent->client->ps.saberMove == LS_JUMPATTACK_STAFF_RIGHT) || + (ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT && ent->client->ps.saberMove == LS_BUTTERFLY_RIGHT) || + (ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT && ent->client->ps.saberMove == LS_BUTTERFLY_LEFT)) { // forward flip/spin attack ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; /*if ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 @@ -2697,333 +2229,231 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) || ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || ent->client->ps.legsAnim == BOTH_BUTTERFLY RIGHT )*/ { - //FIXME: don't slide off people/obstacles? - if ( ent->client->ps.legsAnim != BOTH_BUTTERFLY_LEFT - && ent->client->ps.legsAnim != BOTH_BUTTERFLY_RIGHT ) - { - if ( ent->client->ps.legsAnimTimer >= 100 //not at end - && PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ) - ent->client->ps.legsAnimTimer >= 250 )//not in beginning - {//middle of anim - //push forward + // FIXME: don't slide off people/obstacles? + if (ent->client->ps.legsAnim != BOTH_BUTTERFLY_LEFT && ent->client->ps.legsAnim != BOTH_BUTTERFLY_RIGHT) { + if (ent->client->ps.legsAnimTimer >= 100 // not at end + && PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim) - ent->client->ps.legsAnimTimer >= + 250) // not in beginning + { // middle of anim + // push forward ucmd->forwardmove = 127; } } - if ( ent->client->ps.legsAnimTimer >= 1700 && ent->client->ps.legsAnimTimer < 1800 ) - {//one of the two jumps - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? - //jump! + if (ent->client->ps.legsAnimTimer >= 1700 && ent->client->ps.legsAnimTimer < 1800) { // one of the two jumps + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // still on ground? + // jump! ent->client->ps.velocity[2] = 250; - ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height - ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - G_AddEvent( ent, EV_JUMP, 0 ); - G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - else - {//FIXME: if this is the second jump, maybe we should just stop the anim? + ent->client->ps.forceJumpZStart = ent->client->ps.origin[2]; // so we don't take damage if we land at same height + ent->client->ps.pm_flags |= PMF_JUMPING; //|PMF_SLOW_MO_FALL; + // FIXME: NPCs yell? + G_AddEvent(ent, EV_JUMP, 0); + G_SoundOnEnt(ent, CHAN_BODY, "sound/weapons/force/jump.wav"); + } else { // FIXME: if this is the second jump, maybe we should just stop the anim? } } - //disallow turning unless in the middle frame when you're on the ground - //overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); + // disallow turning unless in the middle frame when you're on the ground + // overridAngles = (PM_AdjustAnglesForDualJumpAttack( ent, ucmd )?qtrue:overridAngles); } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.legsAnim == BOTH_A7_SOULCAL - && ent->client->ps.saberMove == LS_STAFF_SOULCAL ) - {//forward spinning staff attack + if (ent->client->ps.legsAnim == BOTH_A7_SOULCAL && ent->client->ps.saberMove == LS_STAFF_SOULCAL) { // forward spinning staff attack ucmd->upmove = 0; - if ( PM_CanRollFromSoulCal( &ent->client->ps ) ) - { + if (PM_CanRollFromSoulCal(&ent->client->ps)) { ucmd->upmove = -127; - } - else - { + } else { ucmd->rightmove = 0; - //FIXME: don't slide off people/obstacles? - if ( ent->client->ps.legsAnimTimer >= 2750 ) - {//not at end - //push forward + // FIXME: don't slide off people/obstacles? + if (ent->client->ps.legsAnimTimer >= 2750) { // not at end + // push forward ucmd->forwardmove = 64; - } - else - { + } else { ucmd->forwardmove = 0; } } - if ( ent->client->ps.legsAnimTimer >= 2650 - && ent->client->ps.legsAnimTimer < 2850 ) - {//the jump - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? - //jump! + if (ent->client->ps.legsAnimTimer >= 2650 && ent->client->ps.legsAnimTimer < 2850) { // the jump + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // still on ground? + // jump! ent->client->ps.velocity[2] = 250; - ent->client->ps.forceJumpZStart = ent->client->ps.origin[2];//so we don't take damage if we land at same height - ent->client->ps.pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - G_AddEvent( ent, EV_JUMP, 0 ); - G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + ent->client->ps.forceJumpZStart = ent->client->ps.origin[2]; // so we don't take damage if we land at same height + ent->client->ps.pm_flags |= PMF_JUMPING; //|PMF_SLOW_MO_FALL; + // FIXME: NPCs yell? + G_AddEvent(ent, EV_JUMP, 0); + G_SoundOnEnt(ent, CHAN_BODY, "sound/weapons/force/jump.wav"); } } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.torsoAnim == BOTH_LK_DL_S_T_SB_1_W ) - { - G_CamPullBackForLegsAnim( ent, qtrue ); + if (ent->client->ps.torsoAnim == BOTH_LK_DL_S_T_SB_1_W) { + G_CamPullBackForLegsAnim(ent, qtrue); } - if ( ent->client->ps.torsoAnim == BOTH_A6_FB - || ent->client->ps.torsoAnim == BOTH_A6_LR ) - {//can't turn or move during dual attack - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->client->ps.torsoAnim == BOTH_A6_FB || ent->client->ps.torsoAnim == BOTH_A6_LR) { // can't turn or move during dual attack + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - } - else if ( ent->client->ps.legsAnim == BOTH_ROLL_STAB ) - { - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + } else if (ent->client->ps.legsAnim == BOTH_ROLL_STAB) { + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.legsAnimTimer ) - { + if (ent->client->ps.legsAnimTimer) { ucmd->upmove = -127; } - if ( ent->client->ps.dualSabers && ent->client->ps.saber[1].Active() ) - { - G_CamPullBackForLegsAnim( ent ); + if (ent->client->ps.dualSabers && ent->client->ps.saber[1].Active()) { + G_CamPullBackForLegsAnim(ent); } - } - else if ( PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) ) - {//can't turn during Kyle's grappling - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + } else if (PM_SuperBreakLoseAnim(ent->client->ps.torsoAnim)) { // can't turn during Kyle's grappling + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.legsAnim == BOTH_LK_DL_ST_T_SB_1_L ) - { - PM_CmdForRoll( &ent->client->ps, ucmd ); - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->client->ps.legsAnim == BOTH_LK_DL_ST_T_SB_1_L) { + PM_CmdForRoll(&ent->client->ps, ucmd); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } ent->client->ps.speed = 400; } - } - else if ( ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_START - || ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_HOLD - || ent->client->ps.torsoAnim==BOTH_FORCE_DRAIN_GRAB_END - || ent->client->ps.legsAnim==BOTH_FORCE_DRAIN_GRABBED ) - {//can't turn or move - if ( ent->s.number < MAX_CLIENTS - || G_ControlledByPlayer(ent) ) - {//player + } else if (ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD || + ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END || ent->client->ps.legsAnim == BOTH_FORCE_DRAIN_GRABBED) { // can't turn or move + if (ent->s.number < MAX_CLIENTS || G_ControlledByPlayer(ent)) { // player float forceDrainAngle = 90.0f; - if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START ) - {//starting drain - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); - float angle = (elapsedTime/animLength)*forceDrainAngle; + if (ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START) { // starting drain + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); + float angle = (elapsedTime / animLength) * forceDrainAngle; cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; - } - else if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) - {//draining + cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value + angle; + } else if (ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD) { // draining cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+forceDrainAngle; - } - else if ( ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END ) - {//ending drain - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); - float angle = forceDrainAngle-((elapsedTime/animLength)*forceDrainAngle); + cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value + forceDrainAngle; + } else if (ent->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END) { // ending drain + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); + float angle = forceDrainAngle - ((elapsedTime / animLength) * forceDrainAngle); cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value+angle; + cg.overrides.thirdPersonAngle = cg_thirdPersonAngle.value + angle; } } - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - overridAngles = PM_LockAngles( ent, ucmd )?qtrue:overridAngles; - } - else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_1 - || ent->client->ps.legsAnim==BOTH_PLAYER_PA_2 - || ent->client->ps.legsAnim==BOTH_PLAYER_PA_3 - || ent->client->ps.legsAnim==BOTH_PLAYER_PA_3_FLY - || ent->client->ps.legsAnim==BOTH_KYLE_PA_1 - || ent->client->ps.legsAnim==BOTH_KYLE_PA_2 - || ent->client->ps.legsAnim==BOTH_KYLE_PA_3 ) - {//can't turn during Kyle's grappling - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); - } - overridAngles = PM_AdjustAnglesForGrapple( ent, ucmd )?qtrue:overridAngles; - //if ( g_debugMelee->integer ) - {//actually do some damage during sequence + overridAngles = PM_LockAngles(ent, ucmd) ? qtrue : overridAngles; + } else if (ent->client->ps.legsAnim == BOTH_PLAYER_PA_1 || ent->client->ps.legsAnim == BOTH_PLAYER_PA_2 || ent->client->ps.legsAnim == BOTH_PLAYER_PA_3 || + ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY || ent->client->ps.legsAnim == BOTH_KYLE_PA_1 || ent->client->ps.legsAnim == BOTH_KYLE_PA_2 || + ent->client->ps.legsAnim == BOTH_KYLE_PA_3) { // can't turn during Kyle's grappling + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); + } + overridAngles = PM_AdjustAnglesForGrapple(ent, ucmd) ? qtrue : overridAngles; + // if ( g_debugMelee->integer ) + { // actually do some damage during sequence int damage = 0; - int dflags = (DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR|DAMAGE_NO_KILL); - if ( TIMER_Done( ent, "grappleDamageDebounce" ) ) - { - switch ( ent->client->ps.legsAnim ) - { + int dflags = (DAMAGE_NO_KNOCKBACK | DAMAGE_NO_ARMOR | DAMAGE_NO_KILL); + if (TIMER_Done(ent, "grappleDamageDebounce")) { + switch (ent->client->ps.legsAnim) { case BOTH_PLAYER_PA_1: - if ( ent->client->ps.legsAnimTimer <= 3150 - && ent->client->ps.legsAnimTimer > 3050 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 1, 3 ); - } - else - { - damage = Q_irand( 3, 5 ); + if (ent->client->ps.legsAnimTimer <= 3150 && ent->client->ps.legsAnimTimer > 3050) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(1, 3); + } else { + damage = Q_irand(3, 5); } } - if ( ent->client->ps.legsAnimTimer <= 1150 - && ent->client->ps.legsAnimTimer > 1050 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 3, 5 ); - } - else - { - damage = Q_irand( 5, 8 ); + if (ent->client->ps.legsAnimTimer <= 1150 && ent->client->ps.legsAnimTimer > 1050) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(3, 5); + } else { + damage = Q_irand(5, 8); } } - if ( ent->client->ps.legsAnimTimer <= 100 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 5, 8 ); - } - else - { - damage = Q_irand( 10, 20 ); + if (ent->client->ps.legsAnimTimer <= 100) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(5, 8); + } else { + damage = Q_irand(10, 20); } dflags &= ~DAMAGE_NO_KILL; } break; case BOTH_PLAYER_PA_2: - if ( ent->client->ps.legsAnimTimer <= 5700 - && ent->client->ps.legsAnimTimer > 5600 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 3, 6 ); - } - else - { - damage = Q_irand( 7, 10 ); + if (ent->client->ps.legsAnimTimer <= 5700 && ent->client->ps.legsAnimTimer > 5600) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(3, 6); + } else { + damage = Q_irand(7, 10); } } - if ( ent->client->ps.legsAnimTimer <= 5200 - && ent->client->ps.legsAnimTimer > 5100 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 1, 3 ); - } - else - { - damage = Q_irand( 3, 5 ); + if (ent->client->ps.legsAnimTimer <= 5200 && ent->client->ps.legsAnimTimer > 5100) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(1, 3); + } else { + damage = Q_irand(3, 5); } } - if ( ent->client->ps.legsAnimTimer <= 4550 - && ent->client->ps.legsAnimTimer > 4450 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 3, 6 ); - } - else - { - damage = Q_irand( 10, 15 ); + if (ent->client->ps.legsAnimTimer <= 4550 && ent->client->ps.legsAnimTimer > 4450) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(3, 6); + } else { + damage = Q_irand(10, 15); } } - if ( ent->client->ps.legsAnimTimer <= 3550 - && ent->client->ps.legsAnimTimer > 3450 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 3, 6 ); - } - else - { - damage = Q_irand( 10, 20 ); + if (ent->client->ps.legsAnimTimer <= 3550 && ent->client->ps.legsAnimTimer > 3450) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(3, 6); + } else { + damage = Q_irand(10, 20); } dflags &= ~DAMAGE_NO_KILL; } break; case BOTH_PLAYER_PA_3: - if ( ent->client->ps.legsAnimTimer <= 3800 - && ent->client->ps.legsAnimTimer > 3700 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 2, 5 ); - } - else - { - damage = Q_irand( 5, 8 ); + if (ent->client->ps.legsAnimTimer <= 3800 && ent->client->ps.legsAnimTimer > 3700) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(2, 5); + } else { + damage = Q_irand(5, 8); } } - if ( ent->client->ps.legsAnimTimer <= 3100 - && ent->client->ps.legsAnimTimer > 3000 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 2, 5 ); - } - else - { - damage = Q_irand( 5, 8 ); + if (ent->client->ps.legsAnimTimer <= 3100 && ent->client->ps.legsAnimTimer > 3000) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(2, 5); + } else { + damage = Q_irand(5, 8); } } - if ( ent->client->ps.legsAnimTimer <= 1650 - && ent->client->ps.legsAnimTimer > 1550 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - if ( ent->s.number < MAX_CLIENTS ) - {//special case - damage = Q_irand( 3, 6 ); - } - else - { - damage = Q_irand( 7, 12 ); + if (ent->client->ps.legsAnimTimer <= 1650 && ent->client->ps.legsAnimTimer > 1550) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + if (ent->s.number < MAX_CLIENTS) { // special case + damage = Q_irand(3, 6); + } else { + damage = Q_irand(7, 12); } } break; @@ -3039,49 +2469,43 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) dflags &= ~DAMAGE_NO_KILL; } } - else*/ if ( ent->client->ps.legsAnimTimer <= 100 ) - { - TIMER_Set( ent, "grappleDamageDebounce", 150 ); - damage = Q_irand( 10, 20 ); + else*/ + if (ent->client->ps.legsAnimTimer <= 100) { + TIMER_Set(ent, "grappleDamageDebounce", 150); + damage = Q_irand(10, 20); dflags &= ~DAMAGE_NO_KILL; } break; } - if ( damage ) - { - G_Damage( ent, ent->enemy, ent->enemy, NULL, ent->currentOrigin, damage, dflags, MOD_MELEE );//MOD_IMPACT? + if (damage) { + G_Damage(ent, ent->enemy, ent->enemy, NULL, ent->currentOrigin, damage, dflags, MOD_MELEE); // MOD_IMPACT? } } } qboolean clearMove = qtrue; int endOfAnimTime = 100; - if ( ent->s.number < MAX_CLIENTS - && ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY ) - {//player holds extra long so you have more time to decide to do the quick getup - //endOfAnimTime += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; - if ( ent->client->ps.legsAnimTimer <= endOfAnimTime )//PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME ) + if (ent->s.number < MAX_CLIENTS && + ent->client->ps.legsAnim == BOTH_PLAYER_PA_3_FLY) { // player holds extra long so you have more time to decide to do the quick getup + // endOfAnimTime += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; + if (ent->client->ps.legsAnimTimer <= endOfAnimTime) // PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME ) { clearMove = qfalse; } } - if ( clearMove ) - { + if (clearMove) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } - if ( ent->client->ps.legsAnimTimer <= endOfAnimTime ) - {//pretty much done with the anim, so get up now - if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_3 ) - { - vec3_t ang = {10,ent->currentAngles[YAW],0}; + if (ent->client->ps.legsAnimTimer <= endOfAnimTime) { // pretty much done with the anim, so get up now + if (ent->client->ps.legsAnim == BOTH_PLAYER_PA_3) { + vec3_t ang = {10, ent->currentAngles[YAW], 0}; vec3_t throwDir; - AngleVectors( ang, throwDir, NULL, NULL ); - if ( !(ent->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( ent, throwDir, -100 ); + AngleVectors(ang, throwDir, NULL, NULL); + if (!(ent->flags & FL_NO_KNOCKBACK)) { + G_Throw(ent, throwDir, -100); } ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_PLAYER_PA_3_FLY, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_PLAYER_PA_3_FLY, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.weaponTime = ent->client->ps.legsAnimTimer; /* if ( ent->s.number < MAX_CLIENTS ) @@ -3090,28 +2514,24 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) ent->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } */ - //force-thrown - FIXME: start earlier? + // force-thrown - FIXME: start earlier? ent->forcePushTime = level.time + 500; - } - else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_1 ) - { - vec3_t ang = {10,ent->currentAngles[YAW],0}; + } else if (ent->client->ps.legsAnim == BOTH_PLAYER_PA_1) { + vec3_t ang = {10, ent->currentAngles[YAW], 0}; vec3_t throwDir; - AngleVectors( ang, throwDir, NULL, NULL ); - if ( !(ent->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( ent, throwDir, -100 ); + AngleVectors(ang, throwDir, NULL, NULL); + if (!(ent->flags & FL_NO_KNOCKBACK)) { + G_Throw(ent, throwDir, -100); } ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ent->client->ps.weaponTime = ent->client->ps.legsAnimTimer; - if ( ent->s.number < MAX_CLIENTS ) - {//player holds extra long so you have more time to decide to do the quick getup + if (ent->s.number < MAX_CLIENTS) { // player holds extra long so you have more time to decide to do the quick getup ent->client->ps.legsAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; ent->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } } - //FIXME: should end so you can do a getup + // FIXME: should end so you can do a getup /* else if ( ent->client->ps.legsAnim==BOTH_PLAYER_PA_2 ) { @@ -3121,300 +2541,223 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) } */ } - if ( d_slowmodeath->integer <= 3 - && ent->s.number < MAX_CLIENTS ) - {//no matrix effect, so slide the camera back and to the side - G_CamPullBackForLegsAnim( ent ); - G_CamCircleForLegsAnim( ent ); - } - } - else if ( ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_START - || ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_ATTACK - || ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_LAND ) - {//can't turn during force leap - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); - } - overridAngles = PM_AdjustAnglesForLongJump( ent, ucmd )?qtrue:overridAngles; - } - else if ( PM_KickingAnim( ent->client->ps.legsAnim ) - || ent->client->ps.legsAnim == BOTH_ARIAL_F1 - || ent->client->ps.legsAnim == BOTH_ARIAL_LEFT - || ent->client->ps.legsAnim == BOTH_ARIAL_RIGHT - || ent->client->ps.legsAnim == BOTH_CARTWHEEL_LEFT - || ent->client->ps.legsAnim == BOTH_CARTWHEEL_RIGHT - || ent->client->ps.legsAnim == BOTH_JUMPATTACK7 - || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 - || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 - || ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT - || ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT - || ent->client->ps.legsAnim == BOTH_A7_SOULCAL ) - {//can't move, check for damage frame - if ( PM_KickingAnim( ent->client->ps.legsAnim ) ) - { + if (d_slowmodeath->integer <= 3 && ent->s.number < MAX_CLIENTS) { // no matrix effect, so slide the camera back and to the side + G_CamPullBackForLegsAnim(ent); + G_CamCircleForLegsAnim(ent); + } + } else if (ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_START || ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_ATTACK || + ent->client->ps.legsAnim == BOTH_FORCELONGLEAP_LAND) { // can't turn during force leap + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); + } + overridAngles = PM_AdjustAnglesForLongJump(ent, ucmd) ? qtrue : overridAngles; + } else if (PM_KickingAnim(ent->client->ps.legsAnim) || ent->client->ps.legsAnim == BOTH_ARIAL_F1 || ent->client->ps.legsAnim == BOTH_ARIAL_LEFT || + ent->client->ps.legsAnim == BOTH_ARIAL_RIGHT || ent->client->ps.legsAnim == BOTH_CARTWHEEL_LEFT || + ent->client->ps.legsAnim == BOTH_CARTWHEEL_RIGHT || ent->client->ps.legsAnim == BOTH_JUMPATTACK7 || + ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1 || ent->client->ps.legsAnim == BOTH_BUTTERFLY_FR1 || + ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT || ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || + ent->client->ps.legsAnim == BOTH_A7_SOULCAL) { // can't move, check for damage frame + if (PM_KickingAnim(ent->client->ps.legsAnim)) { ucmd->forwardmove = ucmd->rightmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - vec3_t kickDir={0,0,0}, kickDir2={0,0,0}, kickEnd={0,0,0}, kickEnd2={0,0,0}, fwdAngs = {0,ent->client->ps.viewangles[YAW],0}; - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); - float remainingTime = (animLength-elapsedTime); - float kickDist = (ent->maxs[0]*1.5f)+STAFF_KICK_RANGE+8.0f;//fudge factor of 8 + vec3_t kickDir = {0, 0, 0}, kickDir2 = {0, 0, 0}, kickEnd = {0, 0, 0}, kickEnd2 = {0, 0, 0}, fwdAngs = {0, ent->client->ps.viewangles[YAW], 0}; + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.legsAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); + float remainingTime = (animLength - elapsedTime); + float kickDist = (ent->maxs[0] * 1.5f) + STAFF_KICK_RANGE + 8.0f; // fudge factor of 8 float kickDist2 = kickDist; - int kickDamage = Q_irand( 3, 8 ); - int kickDamage2 = Q_irand( 3, 8 ); - int kickPush = Q_flrand( 100.0f, 200.0f );//Q_flrand( 50.0f, 100.0f ); - int kickPush2 = Q_flrand( 100.0f, 200.0f );//Q_flrand( 50.0f, 100.0f ); + int kickDamage = Q_irand(3, 8); + int kickDamage2 = Q_irand(3, 8); + int kickPush = Q_flrand(100.0f, 200.0f); // Q_flrand( 50.0f, 100.0f ); + int kickPush2 = Q_flrand(100.0f, 200.0f); // Q_flrand( 50.0f, 100.0f ); qboolean doKick = qfalse; qboolean doKick2 = qfalse; qboolean kickSoundOnWalls = qfalse; - //HMM... or maybe trace from origin to footRBolt/footLBolt? Which one? G2 trace? Will do hitLoc, if so... - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - { - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + // HMM... or maybe trace from origin to footRBolt/footLBolt? Which one? G2 trace? Will do hitLoc, if so... + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ent->handRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->handRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->handRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->handRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - } - else - { - switch ( ent->client->ps.legsAnim ) - { + } else { + switch (ent->client->ps.legsAnim) { case BOTH_A7_SOULCAL: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); - if ( elapsedTime >= 1400 && elapsedTime <= 1500 ) - {//right leg + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); + if (elapsedTime >= 1400 && elapsedTime <= 1500) { // right leg doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; case BOTH_ARIAL_F1: - if ( elapsedTime >= 550 && elapsedTime <= 1000 ) - {//right leg + if (elapsedTime >= 550 && elapsedTime <= 1000) { // right leg doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 800 && elapsedTime <= 1200 ) - {//left leg + if (elapsedTime >= 800 && elapsedTime <= 1200) { // left leg doKick2 = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: - if ( elapsedTime >= 200 && elapsedTime <= 600 ) - {//lead leg - int footBolt = (ent->client->ps.legsAnim==BOTH_ARIAL_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims + if (elapsedTime >= 200 && elapsedTime <= 600) { // lead leg + int footBolt = (ent->client->ps.legsAnim == BOTH_ARIAL_LEFT) ? ent->footRBolt : ent->footLBolt; // mirrored anims doKick = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 400 && elapsedTime <= 850 ) - {//trailing leg - int footBolt = (ent->client->ps.legsAnim==BOTH_ARIAL_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims + if (elapsedTime >= 400 && elapsedTime <= 850) { // trailing leg + int footBolt = (ent->client->ps.legsAnim == BOTH_ARIAL_LEFT) ? ent->footLBolt : ent->footRBolt; // mirrored anims doKick2 = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; case BOTH_CARTWHEEL_LEFT: case BOTH_CARTWHEEL_RIGHT: - if ( elapsedTime >= 200 && elapsedTime <= 600 ) - {//lead leg - int footBolt = (ent->client->ps.legsAnim==BOTH_CARTWHEEL_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims + if (elapsedTime >= 200 && elapsedTime <= 600) { // lead leg + int footBolt = (ent->client->ps.legsAnim == BOTH_CARTWHEEL_LEFT) ? ent->footRBolt : ent->footLBolt; // mirrored anims doKick = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 350 && elapsedTime <= 650 ) - {//trailing leg - int footBolt = (ent->client->ps.legsAnim==BOTH_CARTWHEEL_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims + if (elapsedTime >= 350 && elapsedTime <= 650) { // trailing leg + int footBolt = (ent->client->ps.legsAnim == BOTH_CARTWHEEL_LEFT) ? ent->footLBolt : ent->footRBolt; // mirrored anims doKick2 = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; case BOTH_JUMPATTACK7: - if ( elapsedTime >= 300 && elapsedTime <= 900 ) - {//right knee + if (elapsedTime >= 300 && elapsedTime <= 900) { // right knee doKick = qtrue; - if ( ent->kneeRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->kneeRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->kneeRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->kneeRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 600 && elapsedTime <= 900 ) - {//left leg + if (elapsedTime >= 600 && elapsedTime <= 900) { // left leg doKick2 = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; case BOTH_BUTTERFLY_FL1: case BOTH_BUTTERFLY_FR1: - if ( elapsedTime >= 950 && elapsedTime <= 1300 ) - {//lead leg - int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_FL1)?ent->footRBolt:ent->footLBolt;//mirrored anims + if (elapsedTime >= 950 && elapsedTime <= 1300) { // lead leg + int footBolt = (ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1) ? ent->footRBolt : ent->footLBolt; // mirrored anims doKick = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 1150 && elapsedTime <= 1600 ) - {//trailing leg - int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_FL1)?ent->footLBolt:ent->footRBolt;//mirrored anims + if (elapsedTime >= 1150 && elapsedTime <= 1600) { // trailing leg + int footBolt = (ent->client->ps.legsAnim == BOTH_BUTTERFLY_FL1) ? ent->footLBolt : ent->footRBolt; // mirrored anims doKick2 = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; case BOTH_BUTTERFLY_LEFT: case BOTH_BUTTERFLY_RIGHT: - if ( (elapsedTime >= 100 && elapsedTime <= 450) - || (elapsedTime >= 1100 && elapsedTime <= 1350) ) - {//lead leg - int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_LEFT)?ent->footLBolt:ent->footRBolt;//mirrored anims + if ((elapsedTime >= 100 && elapsedTime <= 450) || (elapsedTime >= 1100 && elapsedTime <= 1350)) { // lead leg + int footBolt = (ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT) ? ent->footLBolt : ent->footRBolt; // mirrored anims doKick = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( elapsedTime >= 900 && elapsedTime <= 1600 ) - {//trailing leg - int footBolt = (ent->client->ps.legsAnim==BOTH_BUTTERFLY_LEFT)?ent->footRBolt:ent->footLBolt;//mirrored anims + if (elapsedTime >= 900 && elapsedTime <= 1600) { // trailing leg + int footBolt = (ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT) ? ent->footRBolt : ent->footLBolt; // mirrored anims doKick2 = qtrue; - if ( footBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, footBolt, kickEnd2 ); - VectorSubtract( kickEnd2, ent->currentOrigin, kickDir2 ); - kickDir2[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir2 ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir2, NULL, NULL ); + if (footBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, footBolt, kickEnd2); + VectorSubtract(kickEnd2, ent->currentOrigin, kickDir2); + kickDir2[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir2); + } else { // guess + AngleVectors(fwdAngs, kickDir2, NULL, NULL); } } break; @@ -3422,579 +2765,426 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: case BOTH_GETUP_FROLL_F: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - if ( ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B - || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B ) - {//rolling back, pull back the view - G_CamPullBackForLegsAnim( ent ); + if (ent->client->ps.legsAnim == BOTH_GETUP_BROLL_B || ent->client->ps.legsAnim == BOTH_GETUP_FROLL_B) { // rolling back, pull back the view + G_CamPullBackForLegsAnim(ent); } break; case BOTH_A7_KICK_F_AIR: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; - if ( elapsedTime >= 100 && remainingTime >= 500 ) - {//front + if (elapsedTime >= 100 && remainingTime >= 500) { // front doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; case BOTH_A7_KICK_F: kickSoundOnWalls = qtrue; - //FIXME: push forward? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + // FIXME: push forward? + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; case BOTH_A7_KICK_B_AIR: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; - if ( elapsedTime >= 100 && remainingTime >= 400 ) - {//back + if (elapsedTime >= 100 && remainingTime >= 400) { // back doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_B: kickSoundOnWalls = qtrue; - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//back + if (elapsedTime >= 250 && remainingTime >= 250) { // back doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_R_AIR: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; - if ( elapsedTime >= 150 && remainingTime >= 300 ) - {//left + if (elapsedTime >= 150 && remainingTime >= 300) { // left doKick = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_R: kickSoundOnWalls = qtrue; - //FIXME: push right? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//right + // FIXME: push right? + if (elapsedTime >= 250 && remainingTime >= 250) { // right doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); } } break; case BOTH_A7_KICK_L_AIR: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); kickSoundOnWalls = qtrue; - if ( elapsedTime >= 150 && remainingTime >= 300 ) - {//left + if (elapsedTime >= 150 && remainingTime >= 300) { // left doKick = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_L: kickSoundOnWalls = qtrue; - //FIXME: push left? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//left + // FIXME: push left? + if (elapsedTime >= 250 && remainingTime >= 250) { // left doKick = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_S: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - if ( elapsedTime >= 550 - && elapsedTime <= 1050 ) - { + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); + if (ent->footRBolt != -1) { // actually trace to a bolt + if (elapsedTime >= 550 && elapsedTime <= 1050) { doKick = qtrue; - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8.0f, kickDir, kickEnd ); + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8.0f, kickDir, kickEnd); } - } - else - {//guess - if ( elapsedTime >= 400 && elapsedTime < 500 ) - {//front + } else { // guess + if (elapsedTime >= 400 && elapsedTime < 500) { // front doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 500 && elapsedTime < 600 ) - {//front-right? + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 500 && elapsedTime < 600) { // front-right? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 600 && elapsedTime < 700 ) - {//right + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 600 && elapsedTime < 700) { // right doKick = qtrue; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - } - else if ( elapsedTime >= 700 && elapsedTime < 800 ) - {//back-right? + AngleVectors(fwdAngs, NULL, kickDir, NULL); + } else if (elapsedTime >= 700 && elapsedTime < 800) { // back-right? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - } - else if ( elapsedTime >= 800 && elapsedTime < 900 ) - {//back + AngleVectors(fwdAngs, NULL, kickDir, NULL); + } else if (elapsedTime >= 800 && elapsedTime < 900) { // back doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); - } - else if ( elapsedTime >= 900 && elapsedTime < 1000 ) - {//back-left? + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); + } else if (elapsedTime >= 900 && elapsedTime < 1000) { // back-left? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 1000 && elapsedTime < 1100 ) - {//left + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 1000 && elapsedTime < 1100) { // left doKick = qtrue; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); - } - else if ( elapsedTime >= 1100 && elapsedTime < 1200 ) - {//front-left? + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); + } else if (elapsedTime >= 1100 && elapsedTime < 1200) { // front-left? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_BF: - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); - if ( elapsedTime < 1500 ) - {//auto-aim! - overridAngles = PM_AdjustAnglesForBFKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; - //FIXME: if we haven't done the back kick yet and there's no-one there to + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); + if (elapsedTime < 1500) { // auto-aim! + overridAngles = PM_AdjustAnglesForBFKick(ent, ucmd, fwdAngs, qboolean(elapsedTime < 850)) ? qtrue : overridAngles; + // FIXME: if we haven't done the back kick yet and there's no-one there to // kick anymore, go into some anim that returns us to our base stance } - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - if ( ( elapsedTime >= 750 && elapsedTime < 850 ) - || ( elapsedTime >= 1400 && elapsedTime < 1500 ) ) - {//right, though either would do + if (ent->footRBolt != -1) { // actually trace to a bolt + if ((elapsedTime >= 750 && elapsedTime < 850) || (elapsedTime >= 1400 && elapsedTime < 1500)) { // right, though either would do doKick = qtrue; - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); } - } - else - {//guess - if ( elapsedTime >= 250 && elapsedTime < 350 ) - {//front + } else { // guess + if (elapsedTime >= 250 && elapsedTime < 350) { // front doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 350 && elapsedTime < 450 ) - {//back + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 350 && elapsedTime < 450) { // back doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_RL: kickSoundOnWalls = qtrue; - kickPush = Q_flrand( 150.0f, 250.0f );//Q_flrand( 75.0f, 125.0f ); - //FIXME: auto aim at enemies on the side of us? - //overridAngles = PM_AdjustAnglesForRLKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; - if ( elapsedTime >= 250 && elapsedTime < 350 ) - {//right + kickPush = Q_flrand(150.0f, 250.0f); // Q_flrand( 75.0f, 125.0f ); + // FIXME: auto aim at enemies on the side of us? + // overridAngles = PM_AdjustAnglesForRLKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; + if (elapsedTime >= 250 && elapsedTime < 350) { // right doKick = qtrue; - if ( ent->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footRBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); + if (ent->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footRBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); } - } - else if ( elapsedTime >= 350 && elapsedTime < 450 ) - {//left + } else if (elapsedTime >= 350 && elapsedTime < 450) { // left doKick = qtrue; - if ( ent->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ent->footLBolt, kickEnd ); - VectorSubtract( kickEnd, ent->currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ent->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ent->footLBolt, kickEnd); + VectorSubtract(kickEnd, ent->currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; } } - if ( doKick ) - { - G_KickTrace( ent, kickDir, kickDist, kickEnd, kickDamage, kickPush, kickSoundOnWalls ); + if (doKick) { + G_KickTrace(ent, kickDir, kickDist, kickEnd, kickDamage, kickPush, kickSoundOnWalls); } - if ( doKick2 ) - { - G_KickTrace( ent, kickDir2, kickDist2, kickEnd2, kickDamage2, kickPush2, kickSoundOnWalls ); + if (doKick2) { + G_KickTrace(ent, kickDir2, kickDist2, kickEnd2, kickDamage2, kickPush2, kickSoundOnWalls); } - } - else if ( ent->client->ps.saberMove == LS_DUAL_FB ) - { - //pull back the view - G_CamPullBackForLegsAnim( ent ); - } - else if ( ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR - || ent->client->ps.saberMove == LS_A_BACKSTAB ) - {//can't move or turn during back attacks + } else if (ent->client->ps.saberMove == LS_DUAL_FB) { + // pull back the view + G_CamPullBackForLegsAnim(ent); + } else if (ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || + ent->client->ps.saberMove == LS_A_BACKSTAB) { // can't move or turn during back attacks ucmd->forwardmove = ucmd->rightmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); - } - if ( (overridAngles = (PM_AdjustAnglesForBackAttack( ent, ucmd )?qtrue:overridAngles)) == qtrue ) - { - //pull back the view - G_CamPullBackForLegsAnim( ent ); - } - } - else if ( ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK1 - || ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK2 - || ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_END - || ent->client->ps.legsAnim == BOTH_FORCEWALLREBOUND_BACK ) - { - //pull back the view - G_CamPullBackForLegsAnim( ent ); - } - else if ( ent->client->ps.torsoAnim == BOTH_A6_SABERPROTECT ) - { + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); + } + if ((overridAngles = (PM_AdjustAnglesForBackAttack(ent, ucmd) ? qtrue : overridAngles)) == qtrue) { + // pull back the view + G_CamPullBackForLegsAnim(ent); + } + } else if (ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK1 || ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK2 || + ent->client->ps.legsAnim == BOTH_FORCEWALLRUNFLIP_END || ent->client->ps.legsAnim == BOTH_FORCEWALLREBOUND_BACK) { + // pull back the view + G_CamPullBackForLegsAnim(ent); + } else if (ent->client->ps.torsoAnim == BOTH_A6_SABERPROTECT) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); ent->client->ps.forceJumpCharge = 0; } - if ( !ent->s.number ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); + if (!ent->s.number) { + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.torsoAnimTimer); float backDist = 0; - if ( elapsedTime <= 300.0f ) - {//starting anim - backDist = (elapsedTime/300.0f)*90.0f; - } - else if ( ent->client->ps.torsoAnimTimer <= 300.0f ) - {//ending anim - backDist = (ent->client->ps.torsoAnimTimer/300.0f)*90.0f; - } - else - {//in middle of anim + if (elapsedTime <= 300.0f) { // starting anim + backDist = (elapsedTime / 300.0f) * 90.0f; + } else if (ent->client->ps.torsoAnimTimer <= 300.0f) { // ending anim + backDist = (ent->client->ps.torsoAnimTimer / 300.0f) * 90.0f; + } else { // in middle of anim backDist = 90.0f; } - //back off and look down - cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF); - cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; - cg.overrides.thirdPersonPitchOffset = cg_thirdPersonPitchOffset.value+(backDist/2.0f); + // back off and look down + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_POF); + cg.overrides.thirdPersonRange = cg_thirdPersonRange.value + backDist; + cg.overrides.thirdPersonPitchOffset = cg_thirdPersonPitchOffset.value + (backDist / 2.0f); } - overridAngles = (PM_AdjustAnglesForSpinProtect( ent, ucmd )?qtrue:overridAngles); - } - else if ( ent->client->ps.legsAnim == BOTH_A3_SPECIAL ) - {//push forward - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); + overridAngles = (PM_AdjustAnglesForSpinProtect(ent, ucmd) ? qtrue : overridAngles); + } else if (ent->client->ps.legsAnim == BOTH_A3_SPECIAL) { // push forward + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.torsoAnimTimer); ucmd->upmove = ucmd->rightmove = 0; ucmd->forwardmove = 0; - if ( elapsedTime >= 350 && elapsedTime < 1500 ) - {//push forward + if (elapsedTime >= 350 && elapsedTime < 1500) { // push forward ucmd->forwardmove = 64; ent->client->ps.speed = 200.0f; } - //FIXME: pull back camera? - } - else if ( ent->client->ps.legsAnim == BOTH_A2_SPECIAL ) - {//push forward + // FIXME: pull back camera? + } else if (ent->client->ps.legsAnim == BOTH_A2_SPECIAL) { // push forward ucmd->upmove = ucmd->rightmove = 0; ucmd->forwardmove = 0; - if ( ent->client->ps.legsAnimTimer > 200.0f ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); - if ( elapsedTime < 750 - || (elapsedTime >= 1650 && elapsedTime < 2400) ) - {//push forward + if (ent->client->ps.legsAnimTimer > 200.0f) { + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.torsoAnimTimer); + if (elapsedTime < 750 || (elapsedTime >= 1650 && elapsedTime < 2400)) { // push forward ucmd->forwardmove = 64; ent->client->ps.speed = 200.0f; } } - //FIXME: pull back camera? - }//FIXME: fast special? - else if ( ent->client->ps.legsAnim == BOTH_A1_SPECIAL - && (ucmd->forwardmove || ucmd->rightmove || (VectorCompare( ent->client->ps.moveDir, vec3_origin )&&ent->client->ps.speed>0)) ) - {//moving during full-body fast special - ent->client->ps.legsAnimTimer = 0;//don't hold this legsAnim, allow them to run - //FIXME: just add this to the list of overridable special moves in PM_Footsteps? - } - else if ( ent->client->ps.legsAnim == BOTH_FLIP_LAND ) - {//moving during full-body fast special - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.torsoAnimTimer); + // FIXME: pull back camera? + } // FIXME: fast special? + else if (ent->client->ps.legsAnim == BOTH_A1_SPECIAL && + (ucmd->forwardmove || ucmd->rightmove || + (VectorCompare(ent->client->ps.moveDir, vec3_origin) && ent->client->ps.speed > 0))) { // moving during full-body fast special + ent->client->ps.legsAnimTimer = 0; // don't hold this legsAnim, allow them to run + // FIXME: just add this to the list of overridable special moves in PM_Footsteps? + } else if (ent->client->ps.legsAnim == BOTH_FLIP_LAND) { // moving during full-body fast special + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.torsoAnimTimer); ucmd->upmove = ucmd->rightmove = ucmd->forwardmove = 0; - if ( elapsedTime > 600 && elapsedTime < 800 - && ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//jump - FIXME: how do we stop double-jumps? + if (elapsedTime > 600 && elapsedTime < 800 && ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // jump - FIXME: how do we stop double-jumps? ent->client->ps.pm_flags |= PMF_JUMP_HELD; ent->client->ps.groundEntityNum = ENTITYNUM_NONE; ent->client->ps.jumpZStart = ent->currentOrigin[2]; ent->client->ps.velocity[2] = JUMP_VELOCITY; - G_AddEvent( ent, EV_JUMP, 0 ); + G_AddEvent(ent, EV_JUMP, 0); } - } - else if ( ( PM_SuperBreakWinAnim( ent->client->ps.torsoAnim ) - || PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) ) - && ent->client->ps.torsoAnimTimer ) - {//can't move or turn + } else if ((PM_SuperBreakWinAnim(ent->client->ps.torsoAnim) || PM_SuperBreakLoseAnim(ent->client->ps.torsoAnim)) && + ent->client->ps.torsoAnimTimer) { // can't move or turn ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); ent->client->ps.forceJumpCharge = 0; } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); - } - else if ( BG_FullBodyTauntAnim( ent->client->ps.legsAnim ) - && BG_FullBodyTauntAnim( ent->client->ps.torsoAnim ) ) - { - if ( (ucmd->buttons&BUTTON_ATTACK) - || (ucmd->buttons&BUTTON_ALT_ATTACK) - || (ucmd->buttons&BUTTON_USE_FORCE) - || (ucmd->buttons&BUTTON_FORCEGRIP) - || (ucmd->buttons&BUTTON_FORCE_LIGHTNING) - || (ucmd->buttons&BUTTON_FORCE_DRAIN) - || ucmd->upmove ) - {//stop the anim - if ( ent->client->ps.legsAnim == BOTH_MEDITATE - && ent->client->ps.torsoAnim == BOTH_MEDITATE ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_MEDITATE_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - } - else - { + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); + } else if (BG_FullBodyTauntAnim(ent->client->ps.legsAnim) && BG_FullBodyTauntAnim(ent->client->ps.torsoAnim)) { + if ((ucmd->buttons & BUTTON_ATTACK) || (ucmd->buttons & BUTTON_ALT_ATTACK) || (ucmd->buttons & BUTTON_USE_FORCE) || + (ucmd->buttons & BUTTON_FORCEGRIP) || (ucmd->buttons & BUTTON_FORCE_LIGHTNING) || (ucmd->buttons & BUTTON_FORCE_DRAIN) || + ucmd->upmove) { // stop the anim + if (ent->client->ps.legsAnim == BOTH_MEDITATE && ent->client->ps.torsoAnim == BOTH_MEDITATE) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_MEDITATE_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + } else { ent->client->ps.legsAnimTimer = ent->client->ps.torsoAnimTimer = 0; } - } - else - { - if ( ent->client->ps.legsAnim == BOTH_MEDITATE ) - { - if ( ent->client->ps.legsAnimTimer < 100 ) - { + } else { + if (ent->client->ps.legsAnim == BOTH_MEDITATE) { + if (ent->client->ps.legsAnimTimer < 100) { ent->client->ps.legsAnimTimer = 100; } } - if ( ent->client->ps.torsoAnim == BOTH_MEDITATE ) - { - if ( ent->client->ps.torsoAnimTimer < 100 ) - { + if (ent->client->ps.torsoAnim == BOTH_MEDITATE) { + if (ent->client->ps.torsoAnimTimer < 100) { ent->client->ps.legsAnimTimer = 100; } } - if ( ent->client->ps.legsAnimTimer > 0 || ent->client->ps.torsoAnimTimer > 0 ) - { + if (ent->client->ps.legsAnimTimer > 0 || ent->client->ps.torsoAnimTimer > 0) { ucmd->rightmove = 0; ucmd->upmove = 0; ucmd->forwardmove = 0; ucmd->buttons = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); ent->client->ps.forceJumpCharge = 0; } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); } - } - } - else if ( ent->client->ps.legsAnim == BOTH_MEDITATE_END - && ent->client->ps.legsAnimTimer > 0 ) - { - ucmd->rightmove = 0; + } + } else if (ent->client->ps.legsAnim == BOTH_MEDITATE_END && ent->client->ps.legsAnimTimer > 0) { + ucmd->rightmove = 0; ucmd->upmove = 0; ucmd->forwardmove = 0; ucmd->buttons = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); ent->client->ps.forceJumpCharge = 0; } - overridAngles = (PM_LockAngles( ent, ucmd )?qtrue:overridAngles); - } - else if ( !ent->s.number ) - { - if ( ent->client->NPC_class != CLASS_ATST ) - { + overridAngles = (PM_LockAngles(ent, ucmd) ? qtrue : overridAngles); + } else if (!ent->s.number) { + if (ent->client->NPC_class != CLASS_ATST) { // Not in a vehicle. - if ( ent->s.m_iVehicleNum == 0 ) - { - if ( !MatrixMode ) - { - cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_ANG); + if (ent->s.m_iVehicleNum == 0) { + if (!MatrixMode) { + cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_POF | CG_OVERRIDE_3RD_PERSON_ANG); cg.overrides.thirdPersonRange = 0; } } } } - - if ( PM_InRoll( &ent->client->ps ) ) - { - if ( ent->s.number >= MAX_CLIENTS || !player_locked ) - { - //FIXME: NPCs should try to face us during this roll, so they roll around us...? - PM_CmdForRoll( &ent->client->ps, ucmd ); - if ( ent->s.number >= MAX_CLIENTS ) - {//make sure it doesn't roll me off a ledge - if ( !G_CheckRollSafety( ent, ent->client->ps.legsAnim, 24 ) ) - {//crap! I guess all we can do is stop... UGH + if (PM_InRoll(&ent->client->ps)) { + if (ent->s.number >= MAX_CLIENTS || !player_locked) { + // FIXME: NPCs should try to face us during this roll, so they roll around us...? + PM_CmdForRoll(&ent->client->ps, ucmd); + if (ent->s.number >= MAX_CLIENTS) { // make sure it doesn't roll me off a ledge + if (!G_CheckRollSafety(ent, ent->client->ps.legsAnim, 24)) { // crap! I guess all we can do is stop... UGH ucmd->rightmove = ucmd->forwardmove = 0; } } } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } ent->client->ps.speed = 400; } - if ( PM_InCartwheel( ent->client->ps.legsAnim ) ) - {//can't keep moving in cartwheel - if ( ent->client->ps.legsAnimTimer > 100 ) - {//still have time left in the anim + if (PM_InCartwheel(ent->client->ps.legsAnim)) { // can't keep moving in cartwheel + if (ent->client->ps.legsAnimTimer > 100) { // still have time left in the anim ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - if ( ent->s.number || !player_locked ) - { - switch ( ent->client->ps.legsAnim ) - { + if (ent->s.number || !player_locked) { + switch (ent->client->ps.legsAnim) { case BOTH_ARIAL_LEFT: case BOTH_CARTWHEEL_LEFT: ucmd->rightmove = -127; @@ -4013,130 +3203,100 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) } } - if ( ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT - || ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT ) - { - if ( ent->client->ps.legsAnimTimer > 100 ) - {//still have time left in the anim + if (ent->client->ps.legsAnim == BOTH_BUTTERFLY_LEFT || ent->client->ps.legsAnim == BOTH_BUTTERFLY_RIGHT) { + if (ent->client->ps.legsAnimTimer > 100) { // still have time left in the anim ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); - } - if ( ent->s.number || !player_locked ) - { - if ( ent->client->ps.legsAnimTimer > 450 ) - { - switch ( ent->client->ps.legsAnim ) - { - case BOTH_BUTTERFLY_LEFT: - ucmd->rightmove = -127; - break; - case BOTH_BUTTERFLY_RIGHT: - ucmd->rightmove = 127; - break; - default: - break; + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); + } + if (ent->s.number || !player_locked) { + if (ent->client->ps.legsAnimTimer > 450) { + switch (ent->client->ps.legsAnim) { + case BOTH_BUTTERFLY_LEFT: + ucmd->rightmove = -127; + break; + case BOTH_BUTTERFLY_RIGHT: + ucmd->rightmove = 127; + break; + default: + break; } } } } } - overridAngles = (PM_AdjustAnglesForStabDown( ent, ucmd )?qtrue:overridAngles); - overridAngles = (PM_AdjustAngleForWallJump( ent, ucmd, qtrue )?qtrue:overridAngles); - overridAngles = (PM_AdjustAngleForWallRunUp( ent, ucmd, qtrue )?qtrue:overridAngles); - overridAngles = (PM_AdjustAngleForWallRun( ent, ucmd, qtrue )?qtrue:overridAngles); + overridAngles = (PM_AdjustAnglesForStabDown(ent, ucmd) ? qtrue : overridAngles); + overridAngles = (PM_AdjustAngleForWallJump(ent, ucmd, qtrue) ? qtrue : overridAngles); + overridAngles = (PM_AdjustAngleForWallRunUp(ent, ucmd, qtrue) ? qtrue : overridAngles); + overridAngles = (PM_AdjustAngleForWallRun(ent, ucmd, qtrue) ? qtrue : overridAngles); return overridAngles; } -void BG_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd ) -{ - vec3_t forward, right, moveDir; - float pushSpeed, fMove, rMove; +void BG_AddPushVecToUcmd(gentity_t *self, usercmd_t *ucmd) { + vec3_t forward, right, moveDir; + float pushSpeed, fMove, rMove; - if ( !self->client ) - { + if (!self->client) { return; } pushSpeed = VectorLengthSquared(self->client->pushVec); - if(!pushSpeed) - {//not being pushed + if (!pushSpeed) { // not being pushed return; } AngleVectors(self->client->ps.viewangles, forward, right, NULL); - VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir); - VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir); - //moveDir is now our intended move velocity + VectorScale(forward, ucmd->forwardmove / 127.0f * self->client->ps.speed, moveDir); + VectorMA(moveDir, ucmd->rightmove / 127.0f * self->client->ps.speed, right, moveDir); + // moveDir is now our intended move velocity VectorAdd(moveDir, self->client->pushVec, moveDir); self->client->ps.speed = VectorNormalize(moveDir); - //moveDir is now our intended move velocity plus our push Vector + // moveDir is now our intended move velocity plus our push Vector fMove = 127.0 * DotProduct(forward, moveDir); rMove = 127.0 * DotProduct(right, moveDir); - ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive - ucmd->rightmove = floor(rMove);//If in the same dir , will be positive + ucmd->forwardmove = floor(fMove); // If in the same dir , will be positive + ucmd->rightmove = floor(rMove); // If in the same dir , will be positive - if ( self->client->pushVecTime < level.time ) - { - VectorClear( self->client->pushVec ); + if (self->client->pushVecTime < level.time) { + VectorClear(self->client->pushVec); } } -void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc ) -{ - if ( !ent->client || !ent->NPC ) - { +void NPC_Accelerate(gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc) { + if (!ent->client || !ent->NPC) { return; } - if ( !ent->NPC->stats.acceleration ) - {//No acceleration means just start and stop + if (!ent->NPC->stats.acceleration) { // No acceleration means just start and stop ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - //FIXME: in cinematics always accel/decel? - else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed ) - {//Only accelerate if at walkSpeeds - if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - { - //ent->client->ps.friction = 0; + // FIXME: in cinematics always accel/decel? + else if (ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed) { // Only accelerate if at walkSpeeds + if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - { - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - {//decelerate even when walking + } else if (fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { // decelerate even when walking ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//stop on a dime + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // stop on a dime ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - } - else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) - {//Only decelerate if at runSpeeds - if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - {//Accelerate to runspeed - //ent->client->ps.friction = 0; + } else // if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) + { // Only decelerate if at runSpeeds + if (fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { // Accelerate to runspeed + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - {//accelerate instantly - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { // accelerate instantly + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - { + } else if (fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - { + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } @@ -4148,16 +3308,14 @@ NPC_GetWalkSpeed ------------------------- */ -static int NPC_GetWalkSpeed( gentity_t *ent ) -{ - int walkSpeed = 0; +static int NPC_GetWalkSpeed(gentity_t *ent) { + int walkSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; - switch ( ent->client->playerTeam ) - { - case TEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code) + switch (ent->client->playerTeam) { + case TEAM_PLAYER: // To shutup compiler, will add entries later (this is stub code) default: walkSpeed = ent->NPC->stats.walkSpeed; break; @@ -4171,22 +3329,20 @@ static int NPC_GetWalkSpeed( gentity_t *ent ) NPC_GetRunSpeed ------------------------- */ -#define BORG_RUN_INCR 25 -#define SPECIES_RUN_INCR 25 -#define STASIS_RUN_INCR 20 -#define WARBOT_RUN_INCR 20 +#define BORG_RUN_INCR 25 +#define SPECIES_RUN_INCR 25 +#define STASIS_RUN_INCR 20 +#define WARBOT_RUN_INCR 20 -static int NPC_GetRunSpeed( gentity_t *ent ) -{ - int runSpeed = 0; +static int NPC_GetRunSpeed(gentity_t *ent) { + int runSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; // team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types - switch( ent->client->NPC_class) - { - case CLASS_PROBE: // droid cases here to shut-up compiler + switch (ent->client->NPC_class) { + case CLASS_PROBE: // droid cases here to shut-up compiler case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: @@ -4208,44 +3364,36 @@ static int NPC_GetRunSpeed( gentity_t *ent ) return runSpeed; } -void G_HeldByMonster( gentity_t *ent, usercmd_t **ucmd ) -{ - if ( ent && ent->activator && ent->activator->inuse && ent->activator->health > 0 ) - { +void G_HeldByMonster(gentity_t *ent, usercmd_t **ucmd) { + if (ent && ent->activator && ent->activator->inuse && ent->activator->health > 0) { gentity_t *monster = ent->activator; - //take the monster's waypoint as your own + // take the monster's waypoint as your own ent->waypoint = monster->waypoint; - //update the actual origin of the victim - mdxaBone_t boltMatrix; + // update the actual origin of the victim + mdxaBone_t boltMatrix; // Getting the bolt here - int boltIndex = monster->gutBolt;//default to being held in his mouth - if ( monster->count == 1 ) - {//being held in hand rather than the mouth, so use *that* bolt + int boltIndex = monster->gutBolt; // default to being held in his mouth + if (monster->count == 1) { // being held in hand rather than the mouth, so use *that* bolt boltIndex = monster->handRBolt; } vec3_t monAngles = {0}; - monAngles[YAW] = monster->currentAngles[YAW];//only use YAW when passing angles to G2 - gi.G2API_GetBoltMatrix( monster->ghoul2, monster->playerModel, boltIndex, - &boltMatrix, monAngles, monster->currentOrigin, (cg.time?cg.time:level.time), - NULL, monster->s.modelScale ); + monAngles[YAW] = monster->currentAngles[YAW]; // only use YAW when passing angles to G2 + gi.G2API_GetBoltMatrix(monster->ghoul2, monster->playerModel, boltIndex, &boltMatrix, monAngles, monster->currentOrigin, + (cg.time ? cg.time : level.time), NULL, monster->s.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->ps.origin ); - gi.linkentity( ent ); - //lock view angles - PM_AdjustAnglesForHeldByMonster( ent, monster, *ucmd ); - if ( monster->client && monster->client->NPC_class == CLASS_WAMPA ) - {//can only hit attack button - (*ucmd)->buttons &= ~((*ucmd)->buttons&~BUTTON_ATTACK); - } - } - else if (ent) - {//doh, my captor died! + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->ps.origin); + gi.linkentity(ent); + // lock view angles + PM_AdjustAnglesForHeldByMonster(ent, monster, *ucmd); + if (monster->client && monster->client->NPC_class == CLASS_WAMPA) { // can only hit attack button + (*ucmd)->buttons &= ~((*ucmd)->buttons & ~BUTTON_ATTACK); + } + } else if (ent) { // doh, my captor died! ent->activator = NULL; - if (ent->client) - { - ent->client->ps.eFlags &= ~(EF_HELD_BY_WAMPA|EF_HELD_BY_RANCOR); + if (ent->client) { + ent->client->ps.eFlags &= ~(EF_HELD_BY_WAMPA | EF_HELD_BY_RANCOR); } } // don't allow movement, weapon switching, and most kinds of button presses @@ -4255,59 +3403,42 @@ void G_HeldByMonster( gentity_t *ent, usercmd_t **ucmd ) } // yes... so stop skipping... -void G_StopCinematicSkip( void ) -{ +void G_StopCinematicSkip(void) { gi.cvar_set("skippingCinematic", "0"); gi.cvar_set("timescale", "1"); } -void G_StartCinematicSkip( void ) -{ +void G_StartCinematicSkip(void) { - if (cinematicSkipScript[0]) - { - Quake3Game()->RunScript( &g_entities[0], cinematicSkipScript ); + if (cinematicSkipScript[0]) { + Quake3Game()->RunScript(&g_entities[0], cinematicSkipScript); cinematicSkipScript[0] = 0; gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); - } - else - { + } else { // no... so start skipping... gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); } } -void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( !ent || !ent->client || ent->health <= 0 ) - { +void G_CheckClientIdle(gentity_t *ent, usercmd_t *ucmd) { + if (!ent || !ent->client || ent->health <= 0) { return; } - if ( !ent->s.number && ( !cg.renderingThirdPerson || cg.zoomMode ) ) - { - if ( ent->client->idleTime < level.time ) - { + if (!ent->s.number && (!cg.renderingThirdPerson || cg.zoomMode)) { + if (ent->client->idleTime < level.time) { ent->client->idleTime = level.time; } return; } - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || !PM_StandingAnim( ent->client->ps.legsAnim ) - || ent->enemy - || ent->client->ps.legsAnimTimer - || ent->client->ps.torsoAnimTimer ) - {//FIXME: also check for turning? - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || ent->enemy ) - { - //if in an idle, break out - switch ( ent->client->ps.legsAnim ) - { + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || + !PM_StandingAnim(ent->client->ps.legsAnim) || ent->enemy || ent->client->ps.legsAnimTimer || + ent->client->ps.torsoAnimTimer) { // FIXME: also check for turning? + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || ent->enemy) { + // if in an idle, break out + switch (ent->client->ps.legsAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -4316,8 +3447,7 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) ent->client->ps.legsAnimTimer = 0; break; } - switch ( ent->client->ps.torsoAnim ) - { + switch (ent->client->ps.torsoAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -4328,21 +3458,17 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) } } // - if ( ent->client->idleTime < level.time ) - { + if (ent->client->idleTime < level.time) { ent->client->idleTime = level.time; } - } - else if ( level.time - ent->client->idleTime > 5000 ) - {//been idle for 5 seconds - int idleAnim = -1; - switch ( ent->client->ps.legsAnim ) - { + } else if (level.time - ent->client->idleTime > 5000) { // been idle for 5 seconds + int idleAnim = -1; + switch (ent->client->ps.legsAnim) { case BOTH_STAND1: idleAnim = BOTH_STAND1IDLE1; break; case BOTH_STAND2: - idleAnim = Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); + idleAnim = Q_irand(BOTH_STAND2IDLE1, BOTH_STAND2IDLE2); break; case BOTH_STAND3: idleAnim = BOTH_STAND3IDLE1; @@ -4351,58 +3477,49 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) idleAnim = BOTH_STAND5IDLE1; break; } - if ( idleAnim != -1 && PM_HasAnimation( ent, idleAnim ) ) - { - NPC_SetAnim( ent, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't idle again after this anim for a while - ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); + if (idleAnim != -1 && PM_HasAnimation(ent, idleAnim)) { + NPC_SetAnim(ent, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't idle again after this anim for a while + ent->client->idleTime = level.time + PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim) + Q_irand(0, 2000); } } } -void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client ) - { - if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir - || ucmd->forwardmove || ucmd->rightmove//moving using ucmds - || (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move - || (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move +void G_CheckMovingLoopingSounds(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client) { + if ((ent->NPC && !VectorCompare(vec3_origin, ent->client->ps.moveDir)) // moving using moveDir + || ucmd->forwardmove || ucmd->rightmove // moving using ucmds + || (ucmd->upmove && FlyingCreature(ent)) // flier using ucmds to move + || (FlyingCreature(ent) && !VectorCompare(vec3_origin, ent->client->ps.velocity) && ent->health > 0)) // flier using velocity to move { - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_R2D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); break; case CLASS_R5D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); break; case CLASS_MARK2: - ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); break; case CLASS_MOUSE: - ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); break; case CLASS_PROBE: - ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + ent->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); break; default: break; } - } - else - {//not moving under your own control, stop loopSound - if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_PROBE ) - { + } else { // not moving under your own control, stop loopSound + if (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_MARK2 || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_PROBE) { ent->s.loopSound = 0; } } } } - /* ============== ClientAlterSpeed @@ -4410,159 +3527,120 @@ ClientAlterSpeed This function is called ONLY from ClientThinkReal, and is responsible for setting client ps.speed ============== */ -void ClientAlterSpeed(gentity_t *ent, usercmd_t *ucmd, qboolean controlledByPlayer, float vehicleFrameTimeModifier) -{ - gclient_t *client = ent->client; +void ClientAlterSpeed(gentity_t *ent, usercmd_t *ucmd, qboolean controlledByPlayer, float vehicleFrameTimeModifier) { + gclient_t *client = ent->client; Vehicle_t *pVeh = NULL; - if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent->client && ent->client->NPC_class == CLASS_VEHICLE) { pVeh = ent->m_pVehicle; } // set speed // This may be wrong: If we're an npc and we are in a vehicle??? - if ( ent->NPC != NULL && ent->client && ( ent->s.m_iVehicleNum != 0 )/*&& ent->client->NPC_class == CLASS_VEHICLE*/ ) - {//we don't actually scale the ucmd, we use actual speeds - //FIXME: swoop should keep turning (and moving forward?) for a little bit? - if ( ent->NPC->combatMove == qfalse ) - { - if ( !(ucmd->buttons & BUTTON_USE) ) - {//Not leaning + if (ent->NPC != NULL && ent->client && + (ent->s.m_iVehicleNum != 0) /*&& ent->client->NPC_class == CLASS_VEHICLE*/) { // we don't actually scale the ucmd, we use actual speeds + // FIXME: swoop should keep turning (and moving forward?) for a little bit? + if (ent->NPC->combatMove == qfalse) { + if (!(ucmd->buttons & BUTTON_USE)) { // Not leaning qboolean Flying = (qboolean)(ucmd->upmove && ent->client->moveType == MT_FLYSWIM); - qboolean Climbing = (qboolean)(ucmd->upmove && ent->watertype&CONTENTS_LADDER ); + qboolean Climbing = (qboolean)(ucmd->upmove && ent->watertype & CONTENTS_LADDER); client->ps.friction = 6; - if ( ucmd->forwardmove || ucmd->rightmove || Flying ) - { - //if ( ent->NPC->behaviorState != BS_FORMATION ) - {//In - Formation NPCs set thier desiredSpeed themselves - if ( ucmd->buttons & BUTTON_WALKING ) + if (ucmd->forwardmove || ucmd->rightmove || Flying) { + // if ( ent->NPC->behaviorState != BS_FORMATION ) + { // In - Formation NPCs set thier desiredSpeed themselves + if (ucmd->buttons & BUTTON_WALKING) { + ent->NPC->desiredSpeed = NPC_GetWalkSpeed(ent); // ent->NPC->stats.walkSpeed; + } else // running { - ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed; - } - else//running - { - ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed; + ent->NPC->desiredSpeed = NPC_GetRunSpeed(ent); // ent->NPC->stats.runSpeed; } - if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer ) - {//At higher speeds, need to slow down close to stuff - //Slow down as you approach your goal - if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 + if (ent->NPC->currentSpeed >= 80 && !controlledByPlayer) { // At higher speeds, need to slow down close to stuff + // Slow down as you approach your goal + if (ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags & NPCAI_NO_SLOWDOWN)) // 128 { - if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED ) - { + if (ent->NPC->desiredSpeed > MIN_NPC_SPEED) { float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST; ent->NPC->desiredSpeed = ceil(slowdownSpeed); - if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED ) - {//don't slow down too much + if (ent->NPC->desiredSpeed < MIN_NPC_SPEED) { // don't slow down too much ent->NPC->desiredSpeed = MIN_NPC_SPEED; } } } } } - } - else if ( Climbing ) - { + } else if (Climbing) { ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed; - } - else - {//We want to stop + } else { // We want to stop ent->NPC->desiredSpeed = 0; } - NPC_Accelerate( ent, qfalse, qfalse ); + NPC_Accelerate(ent, qfalse, qfalse); - if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//No-one walks this slow - client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop + if (ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // No-one walks this slow + client->ps.speed = ent->NPC->currentSpeed = 0; // Full stop ucmd->forwardmove = 0; ucmd->rightmove = 0; - } - else - { - if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed ) - {//Play the walkanim + } else { + if (ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed) { // Play the walkanim ucmd->buttons |= BUTTON_WALKING; - } - else - { + } else { ucmd->buttons &= ~BUTTON_WALKING; } - if ( ent->NPC->currentSpeed > 0 ) - {//We should be moving - if ( Climbing || Flying ) - { - if ( !ucmd->upmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove; + if (ent->NPC->currentSpeed > 0) { // We should be moving + if (Climbing || Flying) { + if (!ucmd->upmove) { // We need to force them to take a couple more steps until stopped + ucmd->upmove = ent->NPC->last_ucmd.upmove; // was last_upmove; } - } - else if ( !ucmd->forwardmove && !ucmd->rightmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove; - ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove; + } else if (!ucmd->forwardmove && !ucmd->rightmove) { // We need to force them to take a couple more steps until stopped + ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove; // was last_forwardmove; + ucmd->rightmove = ent->NPC->last_ucmd.rightmove; // was last_rightmove; } } client->ps.speed = ent->NPC->currentSpeed; - if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) - { - } - else - { - //Slow down on turns - don't orbit!!! + if (player && player->client && player->client->ps.viewEntity == ent->s.number) { + } else { + // Slow down on turns - don't orbit!!! float turndelta = 0; - // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw - if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... - { - turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180; - } - else + // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always + // thinks it trying to turn according to desiredYaw + if (client->renderInfo.renderFlags & RF_LOCKEDANGLE) // yeah I know the RF_ flag is a pretty ugly hack... { - turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->desiredYaw ) ))/180; + turndelta = (180 - fabs(AngleDelta(ent->currentAngles[YAW], ent->NPC->lockedDesiredYaw))) / 180; + } else { + turndelta = (180 - fabs(AngleDelta(ent->currentAngles[YAW], ent->NPC->desiredYaw))) / 180; } - if ( turndelta < 0.75f ) - { + if (turndelta < 0.75f) { client->ps.speed = 0; - } - else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 ) - {//Turn is greater than 45 degrees or closer than 100 to goal - client->ps.speed = floor(((float)(client->ps.speed))*turndelta); + } else if (ent->NPC->distToGoal < 100 && turndelta < 1.0) { // Turn is greater than 45 degrees or closer than 100 to goal + client->ps.speed = floor(((float)(client->ps.speed)) * turndelta); } } } } - } - else - { - ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent ); + } else { + ent->NPC->desiredSpeed = (ucmd->buttons & BUTTON_WALKING) ? NPC_GetWalkSpeed(ent) : NPC_GetRunSpeed(ent); client->ps.speed = ent->NPC->desiredSpeed; } - } - else - {//Client sets ucmds and such for speed alterations + } else { // Client sets ucmds and such for speed alterations { - client->ps.speed = g_speed->value;//default is 320 + client->ps.speed = g_speed->value; // default is 320 /*if ( !ent->s.number && ent->painDebounceTime>level.time ) { client->ps.speed *= 0.25f; } - else */if (ent->client->ps.heldClient < ENTITYNUM_WORLD) - { + else */ + if (ent->client->ps.heldClient < ENTITYNUM_WORLD) { client->ps.speed *= 0.3f; - } - else if ( PM_SaberInAttack( ent->client->ps.saberMove ) && ucmd->forwardmove < 0 ) - {//if running backwards while attacking, don't run as fast. - switch( client->ps.saberAnimLevel ) - { + } else if (PM_SaberInAttack(ent->client->ps.saberMove) && ucmd->forwardmove < 0) { // if running backwards while attacking, don't run as fast. + switch (client->ps.saberAnimLevel) { case SS_FAST: client->ps.speed *= 0.75f; break; @@ -4575,28 +3653,19 @@ void ClientAlterSpeed(gentity_t *ent, usercmd_t *ucmd, qboolean controlledByPlay client->ps.speed *= 0.45f; break; } - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } - } - else if ( PM_LeapingSaberAnim( client->ps.legsAnim ) ) - {//no mod on speed when leaping - //FIXME: maybe jump? - } - else if ( PM_SpinningSaberAnim( client->ps.legsAnim ) ) - { + } else if (PM_LeapingSaberAnim(client->ps.legsAnim)) { // no mod on speed when leaping + // FIXME: maybe jump? + } else if (PM_SpinningSaberAnim(client->ps.legsAnim)) { client->ps.speed *= 0.5f; - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } - } - else if ( client->ps.weapon == WP_SABER && ( ucmd->buttons & BUTTON_ATTACK ) ) - {//if attacking with saber while running, drop your speed - //FIXME: should be weaponTime? Or in certain anims? - switch( client->ps.saberAnimLevel ) - { + } else if (client->ps.weapon == WP_SABER && (ucmd->buttons & BUTTON_ATTACK)) { // if attacking with saber while running, drop your speed + // FIXME: should be weaponTime? Or in certain anims? + switch (client->ps.saberAnimLevel) { case SS_MEDIUM: case SS_DUAL: case SS_STAFF: @@ -4606,85 +3675,64 @@ void ClientAlterSpeed(gentity_t *ent, usercmd_t *ucmd, qboolean controlledByPlay client->ps.speed *= 0.70f; break; } - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } } } } - if ( client->NPC_class == CLASS_ATST && client->ps.legsAnim == BOTH_RUN1START ) - {//HACK: when starting to move as atst, ramp up speed - //float animLength = PM_AnimLength( client->clientInfo.animFileIndex, (animNumber_t)client->ps.legsAnim); - //client->ps.speed *= ( animLength - client->ps.legsAnimTimer)/animLength; - if ( client->ps.legsAnimTimer > 100 ) - { + if (client->NPC_class == CLASS_ATST && client->ps.legsAnim == BOTH_RUN1START) { // HACK: when starting to move as atst, ramp up speed + // float animLength = PM_AnimLength( client->clientInfo.animFileIndex, (animNumber_t)client->ps.legsAnim); + // client->ps.speed *= ( animLength - client->ps.legsAnimTimer)/animLength; + if (client->ps.legsAnimTimer > 100) { client->ps.speed = 0; } } - //Apply forced movement - if ( client->forced_forwardmove ) - { + // Apply forced movement + if (client->forced_forwardmove) { ucmd->forwardmove = client->forced_forwardmove; - if ( !client->ps.speed ) - { - if ( ent->NPC != NULL ) - { + if (!client->ps.speed) { + if (ent->NPC != NULL) { client->ps.speed = ent->NPC->stats.runSpeed; - } - else - { - client->ps.speed = g_speed->value;//default is 320 + } else { + client->ps.speed = g_speed->value; // default is 320 } } } - if ( client->forced_rightmove ) - { + if (client->forced_rightmove) { ucmd->rightmove = client->forced_rightmove; - if ( !client->ps.speed ) - { - if ( ent->NPC != NULL ) - { + if (!client->ps.speed) { + if (ent->NPC != NULL) { client->ps.speed = ent->NPC->stats.runSpeed; - } - else - { - client->ps.speed = g_speed->value;//default is 320 + } else { + client->ps.speed = g_speed->value; // default is 320 } } } - if ( !pVeh ) - { - if ( ucmd->forwardmove < 0 && !(ucmd->buttons&BUTTON_WALKING) && client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//running backwards is slower than running forwards + if (!pVeh) { + if (ucmd->forwardmove < 0 && !(ucmd->buttons & BUTTON_WALKING) && + client->ps.groundEntityNum != ENTITYNUM_NONE) { // running backwards is slower than running forwards client->ps.speed *= 0.75; } - if (client->ps.forceRageRecoveryTime > level.time ) - { + if (client->ps.forceRageRecoveryTime > level.time) { client->ps.speed *= 0.75; } - if ( client->ps.weapon == WP_SABER ) - { - if ( client->ps.saber[0].moveSpeedScale != 1.0f ) - { + if (client->ps.weapon == WP_SABER) { + if (client->ps.saber[0].moveSpeedScale != 1.0f) { client->ps.speed *= client->ps.saber[0].moveSpeedScale; } - if ( client->ps.dualSabers - && client->ps.saber[1].moveSpeedScale != 1.0f ) - { + if (client->ps.dualSabers && client->ps.saber[1].moveSpeedScale != 1.0f) { client->ps.speed *= client->ps.saber[1].moveSpeedScale; } } - } } - extern qboolean ForceDrain2(gentity_t *ent); extern void ForceGrip(gentity_t *ent); extern void ForceLightning(gentity_t *ent); @@ -4694,16 +3742,15 @@ extern void ForceSeeing(gentity_t *ent); extern void ForceTelepathy(gentity_t *ent); extern void ForceAbsorb(gentity_t *ent); extern void ForceHeal(gentity_t *ent); -static void ProcessGenericCmd(gentity_t *ent, byte cmd) -{ - switch(cmd) { +static void ProcessGenericCmd(gentity_t *ent, byte cmd) { + switch (cmd) { default: break; case GENCMD_FORCE_HEAL: - ForceHeal( ent ); + ForceHeal(ent); break; case GENCMD_FORCE_SPEED: - ForceSpeed( ent ); + ForceSpeed(ent); break; case GENCMD_FORCE_THROW: ForceThrow(ent, qfalse); @@ -4730,7 +3777,7 @@ static void ProcessGenericCmd(gentity_t *ent, byte cmd) ForceAbsorb(ent); break; case GENCMD_FORCE_DRAIN: - ForceDrain2( ent ); + ForceDrain2(ent); break; case GENCMD_FORCE_SEEING: ForceSeeing(ent); @@ -4738,7 +3785,6 @@ static void ProcessGenericCmd(gentity_t *ent, byte cmd) } } - /* ============== ClientThink @@ -4749,429 +3795,322 @@ usually be a couple times for each server frame on fast clients. ============== */ -extern int G_FindLocalInterestPoint( gentity_t *self ); -extern float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUmcd ); +extern int G_FindLocalInterestPoint(gentity_t *self); +extern float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUmcd); -void ClientThink_real( gentity_t *ent, usercmd_t *ucmd ) -{ - gclient_t *client; - pmove_t pm; - vec3_t oldOrigin; - int oldEventSequence; - int msec; - qboolean inSpinFlipAttack = PM_AdjustAnglesForSpinningFlip( ent, ucmd, qfalse ); - qboolean controlledByPlayer = qfalse; +void ClientThink_real(gentity_t *ent, usercmd_t *ucmd) { + gclient_t *client; + pmove_t pm; + vec3_t oldOrigin; + int oldEventSequence; + int msec; + qboolean inSpinFlipAttack = PM_AdjustAnglesForSpinningFlip(ent, ucmd, qfalse); + qboolean controlledByPlayer = qfalse; Vehicle_t *pVeh = NULL; - if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent->client && ent->client->NPC_class == CLASS_VEHICLE) { pVeh = ent->m_pVehicle; } - //Don't let the player do anything if in a camera - if ( (ent->s.eFlags&EF_HELD_BY_RANCOR) - || (ent->s.eFlags&EF_HELD_BY_WAMPA) ) - { - G_HeldByMonster( ent, &ucmd ); + // Don't let the player do anything if in a camera + if ((ent->s.eFlags & EF_HELD_BY_RANCOR) || (ent->s.eFlags & EF_HELD_BY_WAMPA)) { + G_HeldByMonster(ent, &ucmd); } - if ( ent->s.number == 0 ) - { -extern cvar_t *g_skippingcin; + if (ent->s.number == 0) { + extern cvar_t *g_skippingcin; - if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { - G_UpdateEmplacedWeaponData( ent ); - RunEmplacedWeapon( ent, &ucmd ); + if (ent->s.eFlags & EF_LOCKED_TO_WEAPON) { + G_UpdateEmplacedWeaponData(ent); + RunEmplacedWeapon(ent, &ucmd); } - if ( ent->client->ps.saberLockTime > level.time && ent->client->ps.saberLockEnemy != ENTITYNUM_NONE ) - { - NPC_SetLookTarget( ent, ent->client->ps.saberLockEnemy, level.time+1000 ); - } - if ( ent->client->renderInfo.lookTargetClearTime < level.time //NOTE: here this is used as a debounce, not an actual timer - && ent->health > 0 //must be alive - && (!ent->enemy || ent->client->ps.saberMove != LS_A_BACKSTAB) )//don't update if in backstab unless don't currently have an enemy - {//NOTE: doesn't keep updating to nearest enemy once you're dead - int newLookTarget; - if ( !G_ValidateLookEnemy( ent, ent->enemy ) ) - { + if (ent->client->ps.saberLockTime > level.time && ent->client->ps.saberLockEnemy != ENTITYNUM_NONE) { + NPC_SetLookTarget(ent, ent->client->ps.saberLockEnemy, level.time + 1000); + } + if (ent->client->renderInfo.lookTargetClearTime < level.time // NOTE: here this is used as a debounce, not an actual timer + && ent->health > 0 // must be alive + && (!ent->enemy || ent->client->ps.saberMove != LS_A_BACKSTAB)) // don't update if in backstab unless don't currently have an enemy + { // NOTE: doesn't keep updating to nearest enemy once you're dead + int newLookTarget; + if (!G_ValidateLookEnemy(ent, ent->enemy)) { ent->enemy = NULL; } - //FIXME: make this a little prescient? - G_ChooseLookEnemy( ent, ucmd ); - if ( ent->enemy ) - {//target + // FIXME: make this a little prescient? + G_ChooseLookEnemy(ent, ucmd); + if (ent->enemy) { // target newLookTarget = ent->enemy->s.number; - //so we don't change our minds in the next 1 second - ent->client->renderInfo.lookTargetClearTime = level.time+1000; + // so we don't change our minds in the next 1 second + ent->client->renderInfo.lookTargetClearTime = level.time + 1000; ent->client->renderInfo.lookMode = LM_ENT; - } - else - {//no target - //FIXME: what about sightalerts and missiles? + } else { // no target + // FIXME: what about sightalerts and missiles? newLookTarget = ENTITYNUM_NONE; - newLookTarget = G_FindLocalInterestPoint( ent ); - if ( newLookTarget != ENTITYNUM_NONE ) - {//found something of interest + newLookTarget = G_FindLocalInterestPoint(ent); + if (newLookTarget != ENTITYNUM_NONE) { // found something of interest ent->client->renderInfo.lookMode = LM_INTEREST; - } - else - {//okay, no interesting things and no enemies, so look for items - newLookTarget = G_FindLookItem( ent ); + } else { // okay, no interesting things and no enemies, so look for items + newLookTarget = G_FindLookItem(ent); ent->client->renderInfo.lookMode = LM_ENT; } } - if ( ent->client->renderInfo.lookTarget != newLookTarget ) - {//transitioning - NPC_SetLookTarget( ent, newLookTarget, level.time+1000 ); + if (ent->client->renderInfo.lookTarget != newLookTarget) { // transitioning + NPC_SetLookTarget(ent, newLookTarget, level.time + 1000); } } - if ( in_camera ) - { + if (in_camera) { // watch the code here, you MUST "return" within this IF(), *unless* you're stopping the cinematic skip. // - if ( ClientCinematicThink(ent->client) ) - { - if (g_skippingcin->integer) // already doing cinematic skip? - {// yes... so stop skipping... + if (ClientCinematicThink(ent->client)) { + if (g_skippingcin->integer) // already doing cinematic skip? + { // yes... so stop skipping... G_StopCinematicSkip(); - } - else - {// no... so start skipping... + } else { // no... so start skipping... G_StartCinematicSkip(); return; } - } - else - { + } else { return; } } // If he's riding the vehicle... - else if ( ent->s.m_iVehicleNum != 0 && ent->health > 0 ) - { - } - else - { - if ( g_skippingcin->integer ) - {//We're skipping the cinematic and it's over now + else if (ent->s.m_iVehicleNum != 0 && ent->health > 0) { + } else { + if (g_skippingcin->integer) { // We're skipping the cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } - if ( ent->client->ps.pm_type == PM_DEAD && cg.missionStatusDeadTime < level.time ) - {//mission status screen is up because player is dead, stop all scripts + if (ent->client->ps.pm_type == PM_DEAD && + cg.missionStatusDeadTime < level.time) { // mission status screen is up because player is dead, stop all scripts stop_icarus = qtrue; } } -// // Don't allow the player to adjust the pitch when they are in third person overhead cam. -//extern vmCvar_t cg_thirdPerson; -// if ( cg_thirdPerson.integer == 2 ) -// { -// ucmd->angles[PITCH] = 0; -// } + // // Don't allow the player to adjust the pitch when they are in third person overhead cam. + // extern vmCvar_t cg_thirdPerson; + // if ( cg_thirdPerson.integer == 2 ) + // { + // ucmd->angles[PITCH] = 0; + // } - if ( cg.zoomMode == 2 ) - { + if (cg.zoomMode == 2) { // Any kind of movement when the player is NOT ducked when the disruptor gun is zoomed will cause us to auto-magically un-zoom - if ( ( (ucmd->forwardmove||ucmd->rightmove) - && ucmd->upmove >= 0 //crouching-moving is ok - && !(ucmd->buttons&BUTTON_USE)/*leaning is ok*/ - ) - || ucmd->upmove > 0 //jumping not allowed - ) - { + if (((ucmd->forwardmove || ucmd->rightmove) && ucmd->upmove >= 0 // crouching-moving is ok + && !(ucmd->buttons & BUTTON_USE) /*leaning is ok*/ + ) || + ucmd->upmove > 0 // jumping not allowed + ) { // already zooming, so must be wanting to turn it off - G_Sound( ent, G_SoundIndex( "sound/weapons/disruptor/zoomend.wav" )); + G_Sound(ent, G_SoundIndex("sound/weapons/disruptor/zoomend.wav")); cg.zoomMode = 0; cg.zoomTime = cg.time; cg.zoomLocked = qfalse; } } - if ( (player_locked - || (ent->client->ps.eFlags&EF_FORCE_GRIPPED) - || (ent->client->ps.eFlags&EF_FORCE_DRAINED) - || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_1) - || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_2) - || (ent->client->ps.legsAnim==BOTH_PLAYER_PA_3)) - && ent->client->ps.pm_type < PM_DEAD ) // unless dead - {//lock out player control - if ( !player_locked ) - { - VectorClearM( ucmd->angles ); + if ((player_locked || (ent->client->ps.eFlags & EF_FORCE_GRIPPED) || (ent->client->ps.eFlags & EF_FORCE_DRAINED) || + (ent->client->ps.legsAnim == BOTH_PLAYER_PA_1) || (ent->client->ps.legsAnim == BOTH_PLAYER_PA_2) || + (ent->client->ps.legsAnim == BOTH_PLAYER_PA_3)) && + ent->client->ps.pm_type < PM_DEAD) // unless dead + { // lock out player control + if (!player_locked) { + VectorClearM(ucmd->angles); } ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->buttons = 0; ucmd->upmove = 0; - PM_AdjustAnglesToGripper( ent, ucmd ); + PM_AdjustAnglesToGripper(ent, ucmd); } - if ( ent->client->ps.leanofs ) - {//no shooting while leaning + if (ent->client->ps.leanofs) { // no shooting while leaning ucmd->buttons &= ~BUTTON_ATTACK; - if ( ent->client->ps.weapon != WP_DISRUPTOR ) - {//can still zoom around corners + if (ent->client->ps.weapon != WP_DISRUPTOR) { // can still zoom around corners ucmd->buttons &= ~BUTTON_ALT_ATTACK; } } - } - else - { - if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { - G_UpdateEmplacedWeaponData( ent ); + } else { + if (ent->s.eFlags & EF_LOCKED_TO_WEAPON) { + G_UpdateEmplacedWeaponData(ent); } - if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) - { + if (player && player->client && player->client->ps.viewEntity == ent->s.number) { controlledByPlayer = qtrue; int sav_weapon = ucmd->weapon; - memcpy( ucmd, &player->client->usercmd, sizeof( usercmd_t ) ); + memcpy(ucmd, &player->client->usercmd, sizeof(usercmd_t)); ucmd->weapon = sav_weapon; ent->client->usercmd = *ucmd; } // Transfer over our driver's commands to us (the vehicle). - if ( ent->owner && ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { - memcpy( ucmd, &ent->owner->client->usercmd, sizeof( usercmd_t ) ); - ucmd->buttons &= ~BUTTON_USE;//Vehicles NEVER try to use ANYTHING!!! - //ucmd->weapon = ent->client->ps.weapon; // but keep our weapon. + if (ent->owner && ent->client && ent->client->NPC_class == CLASS_VEHICLE) { + memcpy(ucmd, &ent->owner->client->usercmd, sizeof(usercmd_t)); + ucmd->buttons &= ~BUTTON_USE; // Vehicles NEVER try to use ANYTHING!!! + // ucmd->weapon = ent->client->ps.weapon; // but keep our weapon. ent->client->usercmd = *ucmd; } - G_NPCMunroMatchPlayerWeapon( ent ); + G_NPCMunroMatchPlayerWeapon(ent); } // If we are a vehicle, update ourself. - if ( pVeh - && (pVeh->m_pVehicleInfo->Inhabited(pVeh) - || pVeh->m_iBoarding!=0 - || pVeh->m_pVehicleInfo->type!=VH_ANIMAL) ) - { - pVeh->m_pVehicleInfo->Update( pVeh, ucmd ); - } - else if ( ent->client ) - {//this is any client that is not a vehicle (OR: is a vehicle and it not being ridden, is not being boarded, or is a TaunTaun...! - if ( ent->client->NPC_class == CLASS_GONK || - ent->client->NPC_class == CLASS_MOUSE || - ent->client->NPC_class == CLASS_R2D2 || - ent->client->NPC_class == CLASS_R5D2 ) - {//no jumping or strafing in these guys + if (pVeh && (pVeh->m_pVehicleInfo->Inhabited(pVeh) || pVeh->m_iBoarding != 0 || pVeh->m_pVehicleInfo->type != VH_ANIMAL)) { + pVeh->m_pVehicleInfo->Update(pVeh, ucmd); + } else if (ent->client) { // this is any client that is not a vehicle (OR: is a vehicle and it not being ridden, is not being boarded, or is a TaunTaun...! + if (ent->client->NPC_class == CLASS_GONK || ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_R2D2 || + ent->client->NPC_class == CLASS_R5D2) { // no jumping or strafing in these guys ucmd->upmove = ucmd->rightmove = 0; - } - else if ( ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_RANCOR ) - {//no jumping in atst - if (ent->client->ps.pm_type != PM_NOCLIP) - { + } else if (ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_RANCOR) { // no jumping in atst + if (ent->client->ps.pm_type != PM_NOCLIP) { ucmd->upmove = 0; } - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//ATST crushes anything underneath it - gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; - if ( under && under->health && under->takedamage ) - { - vec3_t down = {0,0,-1}; - //FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin - G_Damage( under, ent, ent, down, under->currentOrigin, 100, 0, MOD_CRUSH ); + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // ATST crushes anything underneath it + gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; + if (under && under->health && under->takedamage) { + vec3_t down = {0, 0, -1}; + // FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin + G_Damage(under, ent, ent, down, under->currentOrigin, 100, 0, MOD_CRUSH); } - //so they know to run like hell when I get close - //FIXME: project this in the direction I'm moving? - if ( ent->client->NPC_class != CLASS_RANCOR && !Q_irand( 0, 10 ) ) - {//not so often... - AddSoundEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER, qfalse, qtrue ); - AddSightEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER, 100 ); + // so they know to run like hell when I get close + // FIXME: project this in the direction I'm moving? + if (ent->client->NPC_class != CLASS_RANCOR && !Q_irand(0, 10)) { // not so often... + AddSoundEvent(ent, ent->currentOrigin, ent->maxs[1] * 5, AEL_DANGER, qfalse, qtrue); + AddSightEvent(ent, ent->currentOrigin, ent->maxs[1] * 5, AEL_DANGER, 100); } } - } - else if ( ent->client->ps.groundEntityNum < ENTITYNUM_WORLD && !ent->client->ps.forceJumpCharge ) - {//standing on an entity and not currently force jumping + } else if (ent->client->ps.groundEntityNum < ENTITYNUM_WORLD && + !ent->client->ps.forceJumpCharge) { // standing on an entity and not currently force jumping gentity_t *groundEnt = &g_entities[ent->client->ps.groundEntityNum]; - if ( groundEnt && groundEnt->client ) - { + if (groundEnt && groundEnt->client) { // If you landed on a speeder or animal vehicle... - if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_VEHICLE ) - { - if ( ent->client->NPC_class != CLASS_VEHICLE ) - {//um... vehicles shouldn't ride other vehicles, mmkay? - if ( (groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL && PM_HasAnimation( ent, BOTH_VT_IDLE )) - || (groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && PM_HasAnimation( ent, BOTH_VS_IDLE )) ) - { - //groundEnt->m_pVehicle->m_iBoarding = -3; // Land From Behind - groundEnt->m_pVehicle->m_pVehicleInfo->Board( groundEnt->m_pVehicle, ent ); + if (groundEnt->client && groundEnt->client->NPC_class == CLASS_VEHICLE) { + if (ent->client->NPC_class != CLASS_VEHICLE) { // um... vehicles shouldn't ride other vehicles, mmkay? + if ((groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL && PM_HasAnimation(ent, BOTH_VT_IDLE)) || + (groundEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && PM_HasAnimation(ent, BOTH_VS_IDLE))) { + // groundEnt->m_pVehicle->m_iBoarding = -3; // Land From Behind + groundEnt->m_pVehicle->m_pVehicleInfo->Board(groundEnt->m_pVehicle, ent); } } - } - else if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_SAND_CREATURE - && G_HasKnockdownAnims( ent ) ) - {//step on a sand creature = *you* fall down - G_Knockdown( ent, groundEnt, vec3_origin, 300, qtrue ); - } - else if ( groundEnt->client && groundEnt->client->NPC_class == CLASS_RANCOR ) - {//step on a Rancor, it bucks & throws you off - if ( groundEnt->client->ps.legsAnim != BOTH_ATTACK3 - && groundEnt->client->ps.legsAnim != BOTH_ATTACK4 - && groundEnt->client->ps.legsAnim != BOTH_BUCK_RIDER ) - {//don't interrupt special anims - vec3_t throwDir, right; - AngleVectors( groundEnt->currentAngles, throwDir, right, NULL ); - VectorScale(throwDir,-1,throwDir); - VectorMA( throwDir, Q_flrand( -0.5f, 0.5f), right, throwDir ); + } else if (groundEnt->client && groundEnt->client->NPC_class == CLASS_SAND_CREATURE && + G_HasKnockdownAnims(ent)) { // step on a sand creature = *you* fall down + G_Knockdown(ent, groundEnt, vec3_origin, 300, qtrue); + } else if (groundEnt->client && groundEnt->client->NPC_class == CLASS_RANCOR) { // step on a Rancor, it bucks & throws you off + if (groundEnt->client->ps.legsAnim != BOTH_ATTACK3 && groundEnt->client->ps.legsAnim != BOTH_ATTACK4 && + groundEnt->client->ps.legsAnim != BOTH_BUCK_RIDER) { // don't interrupt special anims + vec3_t throwDir, right; + AngleVectors(groundEnt->currentAngles, throwDir, right, NULL); + VectorScale(throwDir, -1, throwDir); + VectorMA(throwDir, Q_flrand(-0.5f, 0.5f), right, throwDir); throwDir[2] = 0.2f; - VectorNormalize( throwDir ); - if ( !(ent->flags&FL_NO_KNOCKBACK) ) - { - G_Throw( ent, throwDir, Q_flrand( 50, 200 ) ); + VectorNormalize(throwDir); + if (!(ent->flags & FL_NO_KNOCKBACK)) { + G_Throw(ent, throwDir, Q_flrand(50, 200)); } - if ( G_HasKnockdownAnims( ent ) ) - { - G_Knockdown( ent, groundEnt, vec3_origin, 300, qtrue ); + if (G_HasKnockdownAnims(ent)) { + G_Knockdown(ent, groundEnt, vec3_origin, 300, qtrue); } - NPC_SetAnim( groundEnt, SETANIM_BOTH, BOTH_BUCK_RIDER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(groundEnt, SETANIM_BOTH, BOTH_BUCK_RIDER, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else if ( groundEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && - groundEnt->health > 0 && !PM_InRoll( &groundEnt->client->ps ) - && !(groundEnt->client->ps.eFlags&EF_LOCKED_TO_WEAPON) - && !(groundEnt->client->ps.eFlags&EF_HELD_BY_RANCOR) - && !(groundEnt->client->ps.eFlags&EF_HELD_BY_WAMPA) - && !(groundEnt->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - && !inSpinFlipAttack ) - - {//landed on a live client who is on the ground, jump off them and knock them down + } else if (groundEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && groundEnt->health > 0 && !PM_InRoll(&groundEnt->client->ps) && + !(groundEnt->client->ps.eFlags & EF_LOCKED_TO_WEAPON) && !(groundEnt->client->ps.eFlags & EF_HELD_BY_RANCOR) && + !(groundEnt->client->ps.eFlags & EF_HELD_BY_WAMPA) && !(groundEnt->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) && + !inSpinFlipAttack) + + { // landed on a live client who is on the ground, jump off them and knock them down qboolean forceKnockdown = qfalse; // If in a vehicle when land on someone, always knockdown. - if ( pVeh ) - { + if (pVeh) { forceKnockdown = qtrue; - } - else if ( ent->s.number - && ent->NPC - && ent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 )//ent->s.weapon == WP_SABER ) - {//force-jumper landed on someone - //don't jump off, too many ledges, plus looks weird - if ( groundEnt->client->playerTeam != ent->client->playerTeam ) - {//don't knock down own guys - forceKnockdown = (qboolean)(Q_irand( 0, RANK_CAPTAIN+4 )NPC->rank); + } else if (ent->s.number && ent->NPC && ent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) // ent->s.weapon == WP_SABER ) + { // force-jumper landed on someone + // don't jump off, too many ledges, plus looks weird + if (groundEnt->client->playerTeam != ent->client->playerTeam) { // don't knock down own guys + forceKnockdown = (qboolean)(Q_irand(0, RANK_CAPTAIN + 4) < ent->NPC->rank); } - //now what... push the groundEnt out of the way? - if ( !ent->client->ps.velocity[0] - && !ent->client->ps.velocity[1] ) - {//not moving, shove us a little + // now what... push the groundEnt out of the way? + if (!ent->client->ps.velocity[0] && !ent->client->ps.velocity[1]) { // not moving, shove us a little vec3_t slideFwd; - AngleVectors( ent->client->ps.viewangles, slideFwd, NULL, NULL ); + AngleVectors(ent->client->ps.viewangles, slideFwd, NULL, NULL); slideFwd[2] = 0.0f; - VectorNormalize( slideFwd ); - ent->client->ps.velocity[0] = slideFwd[0]*10.0f; - ent->client->ps.velocity[1] = slideFwd[1]*10.0f; + VectorNormalize(slideFwd); + ent->client->ps.velocity[0] = slideFwd[0] * 10.0f; + ent->client->ps.velocity[1] = slideFwd[1] * 10.0f; } - //slide for a little + // slide for a little ent->client->ps.pm_flags |= PMF_TIME_NOFRICTION; ent->client->ps.pm_time = 100; - } - else if ( ent->health > 0 ) - { - if ( !PM_InRoll( &ent->client->ps ) - && !PM_FlippingAnim( ent->client->ps.legsAnim ) ) - { - if ( ent->s.number && ent->s.weapon == WP_SABER ) - { - ent->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently? - } - else if ( !ucmd->upmove ) - {//if not ducking (which should cause a roll), then jump + } else if (ent->health > 0) { + if (!PM_InRoll(&ent->client->ps) && !PM_FlippingAnim(ent->client->ps.legsAnim)) { + if (ent->s.number && ent->s.weapon == WP_SABER) { + ent->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently? + } else if (!ucmd->upmove) { // if not ducking (which should cause a roll), then jump ucmd->upmove = 127; } - if ( !ucmd->forwardmove && !ucmd->rightmove ) - {// If not moving, don't want to jump straight up - //FIXME: trace for clear di? - if ( !Q_irand( 0, 3 ) ) - { + if (!ucmd->forwardmove && !ucmd->rightmove) { // If not moving, don't want to jump straight up + // FIXME: trace for clear di? + if (!Q_irand(0, 3)) { ucmd->forwardmove = 127; - } - else if ( !Q_irand( 0, 3 ) ) - { + } else if (!Q_irand(0, 3)) { ucmd->forwardmove = -127; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { ucmd->rightmove = 127; - } - else - { + } else { ucmd->rightmove = -127; } } - if ( !ent->s.number && ucmd->upmove < 0 ) - {//player who should roll- force it - int rollAnim = BOTH_ROLL_F; - if ( ucmd->forwardmove >= 0 ) - { + if (!ent->s.number && ucmd->upmove < 0) { // player who should roll- force it + int rollAnim = BOTH_ROLL_F; + if (ucmd->forwardmove >= 0) { rollAnim = BOTH_ROLL_F; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { rollAnim = BOTH_ROLL_B; - } - else if ( ucmd->rightmove > 0 ) - { + } else if (ucmd->rightmove > 0) { rollAnim = BOTH_ROLL_R; - } - else if ( ucmd->rightmove < 0 ) - { + } else if (ucmd->rightmove < 0) { rollAnim = BOTH_ROLL_L; } - NPC_SetAnim(ent,SETANIM_BOTH,rollAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - G_AddEvent( ent, EV_ROLL, 0 ); + NPC_SetAnim(ent, SETANIM_BOTH, rollAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(ent, EV_ROLL, 0); ent->client->ps.saberMove = LS_NONE; } } - } - else - {//a corpse? Shit - //Hmm, corpses should probably *always* knockdown... + } else { // a corpse? Shit + // Hmm, corpses should probably *always* knockdown... forceKnockdown = qtrue; ent->clipmask &= ~CONTENTS_BODY; } - //FIXME: need impact sound event - GEntity_PainFunc( groundEnt, ent, ent, groundEnt->currentOrigin, 0, MOD_CRUSH ); - if ( !forceKnockdown - && groundEnt->client->NPC_class == CLASS_DESANN - && ent->client->NPC_class != CLASS_LUKE ) - {//can't knock down desann unless you're luke - //FIXME: should he smack you away like Galak Mech? - } - else if ( forceKnockdown //forced - || ent->client->NPC_class == CLASS_DESANN //desann always knocks people down - || ( ( (groundEnt->s.number&&(groundEnt->s.weapon!=WP_SABER||!groundEnt->NPC||groundEnt->NPC->ranks.number||G_ControlledByPlayer(groundEnt)) && !Q_irand( 0, 3 )&&cg.renderingThirdPerson&&!cg.zoomMode) )//or a player in third person, 25% of the time - && groundEnt->client->playerTeam != ent->client->playerTeam//and not on the same team - && ent->client->ps.legsAnim != BOTH_JUMPATTACK6 ) )//not in the sideways-spinning jump attack + // FIXME: need impact sound event + GEntity_PainFunc(groundEnt, ent, ent, groundEnt->currentOrigin, 0, MOD_CRUSH); + if (!forceKnockdown && groundEnt->client->NPC_class == CLASS_DESANN && + ent->client->NPC_class != CLASS_LUKE) { // can't knock down desann unless you're luke + // FIXME: should he smack you away like Galak Mech? + } else if (forceKnockdown // forced + || ent->client->NPC_class == CLASS_DESANN // desann always knocks people down + || (((groundEnt->s.number && + (groundEnt->s.weapon != WP_SABER || !groundEnt->NPC || + groundEnt->NPC->rank < Q_irand(RANK_CIVILIAN, RANK_CAPTAIN + 1))) // an NPC who is either not a saber user or passed the + // rank-based probability test + || ((!ent->s.number || G_ControlledByPlayer(groundEnt)) && !Q_irand(0, 3) && cg.renderingThirdPerson && + !cg.zoomMode)) // or a player in third person, 25% of the time + && groundEnt->client->playerTeam != ent->client->playerTeam // and not on the same team + && ent->client->ps.legsAnim != BOTH_JUMPATTACK6)) // not in the sideways-spinning jump attack { int knockAnim = BOTH_KNOCKDOWN1; - if ( PM_CrouchAnim( groundEnt->client->ps.legsAnim ) ) - {//knockdown from crouch + if (PM_CrouchAnim(groundEnt->client->ps.legsAnim)) { // knockdown from crouch knockAnim = BOTH_KNOCKDOWN4; - } - else - { - vec3_t gEFwd, gEAngles = {0,groundEnt->client->ps.viewangles[YAW],0}; - AngleVectors( gEAngles, gEFwd, NULL, NULL ); - if ( DotProduct( ent->client->ps.velocity, gEFwd ) > 50 ) - {//pushing him forward + } else { + vec3_t gEFwd, gEAngles = {0, groundEnt->client->ps.viewangles[YAW], 0}; + AngleVectors(gEAngles, gEFwd, NULL, NULL); + if (DotProduct(ent->client->ps.velocity, gEFwd) > 50) { // pushing him forward knockAnim = BOTH_KNOCKDOWN3; } } - NPC_SetAnim( groundEnt, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(groundEnt, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } } } - client = ent->client; // mark the time, so the connection sprite can be removed @@ -5179,296 +4118,243 @@ extern cvar_t *g_skippingcin; client->pers.lastCommand = *ucmd; // sanity check the command time to prevent speedup cheating - if ( ucmd->serverTime > level.time + 200 ) - { + if (ucmd->serverTime > level.time + 200) { ucmd->serverTime = level.time + 200; } - if ( ucmd->serverTime < level.time - 1000 ) - { + if (ucmd->serverTime < level.time - 1000) { ucmd->serverTime = level.time - 1000; } msec = ucmd->serverTime - client->ps.commandTime; - if ( msec < 1 ) - { + if (msec < 1) { msec = 1; } - if ( msec > 200 ) - { + if (msec > 200) { msec = 200; } - if ( client->noclip ) - { + if (client->noclip) { client->ps.pm_type = PM_NOCLIP; - } - else if ( client->ps.stats[STAT_HEALTH] <= 0 ) - { + } else if (client->ps.stats[STAT_HEALTH] <= 0) { client->ps.pm_type = PM_DEAD; - } - else - { + } else { client->ps.pm_type = PM_NORMAL; } - //FIXME: if global gravity changes this should update everyone's personal gravity... - if ( !(ent->svFlags & SVF_CUSTOM_GRAVITY) ) - { - if (ent->client->inSpaceIndex) - { //in space, so no gravity... + // FIXME: if global gravity changes this should update everyone's personal gravity... + if (!(ent->svFlags & SVF_CUSTOM_GRAVITY)) { + if (ent->client->inSpaceIndex) { // in space, so no gravity... client->ps.gravity = 0.0f; - } - else - { + } else { client->ps.gravity = g_gravity->value; } } - if (!USENEWNAVSYSTEM || ent->s.number==0) - { + if (!USENEWNAVSYSTEM || ent->s.number == 0) { ClientAlterSpeed(ent, ucmd, controlledByPlayer, 0); } + // FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) + BG_AddPushVecToUcmd(ent, ucmd); - //FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) - BG_AddPushVecToUcmd( ent, ucmd ); + G_CheckClampUcmd(ent, ucmd); - G_CheckClampUcmd( ent, ucmd ); + WP_ForcePowersUpdate(ent, ucmd); - WP_ForcePowersUpdate( ent, ucmd ); - - //if we have the saber in hand, check for starting a block to reflect shots - if ( ent->s.number < MAX_CLIENTS//player - || ( ent->NPC && G_JediInNormalAI( ent ) ) )//NPC jedi not in a special AI mode + // if we have the saber in hand, check for starting a block to reflect shots + if (ent->s.number < MAX_CLIENTS // player + || (ent->NPC && G_JediInNormalAI(ent))) // NPC jedi not in a special AI mode { - WP_SaberStartMissileBlockCheck( ent, ucmd ); + WP_SaberStartMissileBlockCheck(ent, ucmd); } // Update the position of the saber, and check to see if we're throwing it - if ( client->ps.saberEntityNum != ENTITYNUM_NONE ) - { + if (client->ps.saberEntityNum != ENTITYNUM_NONE) { int updates = 1; - if ( ent->NPC ) - { - updates = 3;//simulate player update rate? + if (ent->NPC) { + updates = 3; // simulate player update rate? } - for ( int update = 0; update < updates; update++ ) - { - WP_SaberUpdate( ent, ucmd ); + for (int update = 0; update < updates; update++) { + WP_SaberUpdate(ent, ucmd); } } - //NEED to do this every frame, since these overrides do not go into the save/load data - if ( ent->client && ent->s.m_iVehicleNum != 0 && !ent->s.number && !MatrixMode) - {//FIXME: extern and read from g_vehicleInfo? + // NEED to do this every frame, since these overrides do not go into the save/load data + if (ent->client && ent->s.m_iVehicleNum != 0 && !ent->s.number && !MatrixMode) { // FIXME: extern and read from g_vehicleInfo? Vehicle_t *pPlayerVeh = ent->owner->m_pVehicle; - if ( pPlayerVeh && pPlayerVeh->m_pVehicleInfo->cameraOverride ) - { + if (pPlayerVeh && pPlayerVeh->m_pVehicleInfo->cameraOverride) { // Vehicle Camera Overrides //-------------------------- - cg.overrides.active |= ( CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_FOV | CG_OVERRIDE_3RD_PERSON_VOF | CG_OVERRIDE_3RD_PERSON_POF ); - cg.overrides.thirdPersonRange = pPlayerVeh->m_pVehicleInfo->cameraRange; - cg.overrides.fov = pPlayerVeh->m_pVehicleInfo->cameraFOV; - cg.overrides.thirdPersonVertOffset = pPlayerVeh->m_pVehicleInfo->cameraVertOffset; - cg.overrides.thirdPersonPitchOffset = pPlayerVeh->m_pVehicleInfo->cameraPitchOffset; + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_FOV | CG_OVERRIDE_3RD_PERSON_VOF | CG_OVERRIDE_3RD_PERSON_POF); + cg.overrides.thirdPersonRange = pPlayerVeh->m_pVehicleInfo->cameraRange; + cg.overrides.fov = pPlayerVeh->m_pVehicleInfo->cameraFOV; + cg.overrides.thirdPersonVertOffset = pPlayerVeh->m_pVehicleInfo->cameraVertOffset; + cg.overrides.thirdPersonPitchOffset = pPlayerVeh->m_pVehicleInfo->cameraPitchOffset; - if ( pPlayerVeh->m_pVehicleInfo->cameraAlpha ) - { - cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; + if (pPlayerVeh->m_pVehicleInfo->cameraAlpha) { + cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; } // If In A Speeder (NOT DURING TURBO) //------------------------------------ - if ((level.time>pPlayerVeh->m_iTurboTime) && pPlayerVeh->m_pVehicleInfo->type==VH_SPEEDER) - { + if ((level.time > pPlayerVeh->m_iTurboTime) && pPlayerVeh->m_pVehicleInfo->type == VH_SPEEDER) { // If Using Strafe And Use Keys //------------------------------ - if ((pPlayerVeh->m_ucmd.rightmove!=0) && -// (pPlayerVeh->m_pParentEntity->client->ps.speed>=0) && - (pPlayerVeh->m_ucmd.buttons&BUTTON_USE) - ) - { - cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; // Turn On Angle Offset - cg.overrides.thirdPersonRange *= -2; // Camera In Front Of Player - cg.overrides.thirdPersonAngle = (pPlayerVeh->m_ucmd.rightmove>0)?(20):(-20); + if ((pPlayerVeh->m_ucmd.rightmove != 0) && + // (pPlayerVeh->m_pParentEntity->client->ps.speed>=0) && + (pPlayerVeh->m_ucmd.buttons & BUTTON_USE)) { + cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; // Turn On Angle Offset + cg.overrides.thirdPersonRange *= -2; // Camera In Front Of Player + cg.overrides.thirdPersonAngle = (pPlayerVeh->m_ucmd.rightmove > 0) ? (20) : (-20); } // Auto Pullback Of Camera To Show Enemy //--------------------------------------- - else - { - cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_ANG; // Turn Off Angle Offset - if (ent->enemy) - { - vec3_t actorDirection; - vec3_t enemyDirection; + else { + cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_ANG; // Turn Off Angle Offset + if (ent->enemy) { + vec3_t actorDirection; + vec3_t enemyDirection; AngleVectors(ent->currentAngles, actorDirection, 0, 0); VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, enemyDirection); - float enemyDistance = VectorNormalize(enemyDirection); + float enemyDistance = VectorNormalize(enemyDirection); - if (enemyDistance>cg.overrides.thirdPersonRange && enemyDistance<400 && DotProduct(actorDirection, enemyDirection)<-0.5f) - { + if (enemyDistance > cg.overrides.thirdPersonRange && enemyDistance < 400 && DotProduct(actorDirection, enemyDirection) < -0.5f) { cg.overrides.thirdPersonRange = enemyDistance; } } } } } - } - else if ( client->ps.eFlags&EF_IN_ATST ) - { - cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_VOF); + } else if (client->ps.eFlags & EF_IN_ATST) { + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_POF | CG_OVERRIDE_3RD_PERSON_VOF); cg.overrides.thirdPersonRange = 240; - if ( cg_thirdPersonAutoAlpha.integer ) - { - if ( ent->health > 0 && ent->client->ps.viewangles[PITCH] < 15 && ent->client->ps.viewangles[PITCH] > 0 ) - { + if (cg_thirdPersonAutoAlpha.integer) { + if (ent->health > 0 && ent->client->ps.viewangles[PITCH] < 15 && ent->client->ps.viewangles[PITCH] > 0) { cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; - if ( cg.overrides.thirdPersonAlpha > 0.525f ) - { + if (cg.overrides.thirdPersonAlpha > 0.525f) { cg.overrides.thirdPersonAlpha -= 0.025f; - } - else if ( cg.overrides.thirdPersonAlpha > 0.5f ) - { + } else if (cg.overrides.thirdPersonAlpha > 0.5f) { cg.overrides.thirdPersonAlpha = 0.5f; } - } - else if ( cg.overrides.active&CG_OVERRIDE_3RD_PERSON_APH ) - { - if ( cg.overrides.thirdPersonAlpha > cg_thirdPersonAlpha.value ) - { + } else if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_APH) { + if (cg.overrides.thirdPersonAlpha > cg_thirdPersonAlpha.value) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; - } - else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value-0.1f ) - { + } else if (cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value - 0.1f) { cg.overrides.thirdPersonAlpha += 0.1f; - } - else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value ) - { + } else if (cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value) { cg.overrides.thirdPersonAlpha = cg_thirdPersonAlpha.value; cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; } } } - if ( ent->client->ps.viewangles[PITCH] > 0 ) - { - cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; - cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-10; - if ( cg.overrides.thirdPersonVertOffset < 0 ) - { + if (ent->client->ps.viewangles[PITCH] > 0) { + cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH] * -0.75; + cg.overrides.thirdPersonVertOffset = 300 + ent->client->ps.viewangles[PITCH] * -10; + if (cg.overrides.thirdPersonVertOffset < 0) { cg.overrides.thirdPersonVertOffset = 0; } - } - else if ( ent->client->ps.viewangles[PITCH] < 0 ) - { - cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; - cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-5; - if ( cg.overrides.thirdPersonVertOffset > 300 ) - { + } else if (ent->client->ps.viewangles[PITCH] < 0) { + cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH] * -0.75; + cg.overrides.thirdPersonVertOffset = 300 + ent->client->ps.viewangles[PITCH] * -5; + if (cg.overrides.thirdPersonVertOffset > 300) { cg.overrides.thirdPersonVertOffset = 300; } - } - else - { + } else { cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonVertOffset = 200; } } - //play/stop any looping sounds tied to controlled movement - G_CheckMovingLoopingSounds( ent, ucmd ); + // play/stop any looping sounds tied to controlled movement + G_CheckMovingLoopingSounds(ent, ucmd); - //remember your last angles - VectorCopy ( ent->client->ps.viewangles, ent->lastAngles ); + // remember your last angles + VectorCopy(ent->client->ps.viewangles, ent->lastAngles); // set up for pmove oldEventSequence = client->ps.eventSequence; - memset( &pm, 0, sizeof(pm) ); + memset(&pm, 0, sizeof(pm)); pm.gent = ent; pm.ps = &client->ps; pm.cmd = *ucmd; -// pm.tracemask = MASK_PLAYERSOLID; // used differently for navgen + // pm.tracemask = MASK_PLAYERSOLID; // used differently for navgen pm.tracemask = ent->clipmask; pm.trace = gi.trace; pm.pointcontents = gi.pointcontents; pm.debugLevel = g_debugMove->integer; - pm.noFootsteps = qfalse;//( g_dmflags->integer & DF_NO_FOOTSTEPS ) > 0; + pm.noFootsteps = qfalse; //( g_dmflags->integer & DF_NO_FOOTSTEPS ) > 0; - if ( ent->client && ent->NPC ) - { + if (ent->client && ent->NPC) { pm.cmd.weapon = ent->client->ps.weapon; } - VectorCopy( client->ps.origin, oldOrigin ); + VectorCopy(client->ps.origin, oldOrigin); // perform a pmove - Pmove( &pm ); + Pmove(&pm); pm.gent = 0; ProcessGenericCmd(ent, pm.cmd.generic_cmd); // save results of pmove - if ( ent->client->ps.eventSequence != oldEventSequence ) - { + if (ent->client->ps.eventSequence != oldEventSequence) { ent->eventTime = level.time; { - int seq; + int seq; - seq = (ent->client->ps.eventSequence-1) & (MAX_PS_EVENTS-1); - ent->s.event = ent->client->ps.events[ seq ] | ( ( ent->client->ps.eventSequence & 3 ) << 8 ); - ent->s.eventParm = ent->client->ps.eventParms[ seq ]; + seq = (ent->client->ps.eventSequence - 1) & (MAX_PS_EVENTS - 1); + ent->s.event = ent->client->ps.events[seq] | ((ent->client->ps.eventSequence & 3) << 8); + ent->s.eventParm = ent->client->ps.eventParms[seq]; } } - PlayerStateToEntityState( &ent->client->ps, &ent->s ); + PlayerStateToEntityState(&ent->client->ps, &ent->s); - VectorCopy ( ent->currentOrigin, ent->lastOrigin ); + VectorCopy(ent->currentOrigin, ent->lastOrigin); #if 1 // use the precise origin for linking - VectorCopy( ent->client->ps.origin, ent->currentOrigin ); + VectorCopy(ent->client->ps.origin, ent->currentOrigin); #else - //We don't use prediction anymore, so screw this - // use the snapped origin for linking so it matches client predicted versions - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); + // We don't use prediction anymore, so screw this + // use the snapped origin for linking so it matches client predicted versions + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); #endif + // Had to leave this in, some legacy code must still be using s.angles + // Shouldn't interfere with interpolation of angles, should it? + VectorCopy(ent->client->ps.viewangles, ent->currentAngles); + // if (pVeh) + // { + // gi.Printf("%d\n", ucmd->angles[2]); + // } - //Had to leave this in, some legacy code must still be using s.angles - //Shouldn't interfere with interpolation of angles, should it? - VectorCopy(ent->client->ps.viewangles , ent->currentAngles ); -// if (pVeh) -// { -// gi.Printf("%d\n", ucmd->angles[2]); -// } - - VectorCopy( pm.mins, ent->mins ); - VectorCopy( pm.maxs, ent->maxs ); + VectorCopy(pm.mins, ent->mins); + VectorCopy(pm.maxs, ent->maxs); ent->waterlevel = pm.waterlevel; ent->watertype = pm.watertype; - VectorCopyM( ucmd->angles, client->pers.cmd_angles ); + VectorCopyM(ucmd->angles, client->pers.cmd_angles); // execute client events - ClientEvents( ent, oldEventSequence ); + ClientEvents(ent, oldEventSequence); - if ( pm.useEvent ) - { - //TODO: Use - TryUse( ent ); + if (pm.useEvent) { + // TODO: Use + TryUse(ent); } // link entity now, after any personal teleporters have been used - gi.linkentity( ent ); + gi.linkentity(ent); ent->client->hiddenDist = 0; - if ( !ent->client->noclip ) - { - G_TouchTriggersLerped( ent ); + if (!ent->client->noclip) { + G_TouchTriggersLerped(ent); } // touch other objects - ClientImpacts( ent, &pm ); + ClientImpacts(ent, &pm); // swap and latch button actions client->oldbuttons = client->buttons; @@ -5476,11 +4362,9 @@ extern cvar_t *g_skippingcin; client->latched_buttons |= client->buttons & ~client->oldbuttons; // check for respawning - if ( client->ps.stats[STAT_HEALTH] <= 0 ) - { + if (client->ps.stats[STAT_HEALTH] <= 0) { // wait for the attack button to be pressed - if ( ent->NPC == NULL && level.time > client->respawnTime ) - { + if (ent->NPC == NULL && level.time > client->respawnTime) { // don't allow respawn if they are still flying through the // air, unless 10 extra seconds have passed, meaning something // strange is going on, like the corpse is caught in a wind tunnel @@ -5495,33 +4379,21 @@ extern cvar_t *g_skippingcin; */ // pressing attack or use is the normal respawn method - if ( ucmd->buttons & ( BUTTON_ATTACK ) ) - { - respawn( ent ); + if (ucmd->buttons & (BUTTON_ATTACK)) { + respawn(ent); } } - if ( ent - && !ent->s.number - && ent->enemy - && ent->enemy != ent - && ent->enemy->s.number < ENTITYNUM_WORLD - && ent->enemy->inuse - && !(cg.overrides.active&CG_OVERRIDE_3RD_PERSON_ANG) ) - {//keep facing enemy + if (ent && !ent->s.number && ent->enemy && ent->enemy != ent && ent->enemy->s.number < ENTITYNUM_WORLD && ent->enemy->inuse && + !(cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG)) { // keep facing enemy vec3_t deadDir; float deadYaw; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, deadDir ); - deadYaw = AngleNormalize180( vectoyaw ( deadDir ) ); - if ( deadYaw > ent->client->ps.stats[STAT_DEAD_YAW] + 1 ) - { + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, deadDir); + deadYaw = AngleNormalize180(vectoyaw(deadDir)); + if (deadYaw > ent->client->ps.stats[STAT_DEAD_YAW] + 1) { ent->client->ps.stats[STAT_DEAD_YAW]++; - } - else if ( deadYaw < ent->client->ps.stats[STAT_DEAD_YAW] - 1 ) - { + } else if (deadYaw < ent->client->ps.stats[STAT_DEAD_YAW] - 1) { ent->client->ps.stats[STAT_DEAD_YAW]--; - } - else - { + } else { ent->client->ps.stats[STAT_DEAD_YAW] = deadYaw; } } @@ -5529,11 +4401,11 @@ extern cvar_t *g_skippingcin; } // perform once-a-second actions - ClientTimerActions( ent, msec ); + ClientTimerActions(ent, msec); - ClientEndPowerUps( ent ); - //try some idle anims on ent if getting no input and not moving for some time - G_CheckClientIdle( ent, ucmd ); + ClientEndPowerUps(ent); + // try some idle anims on ent if getting no input and not moving for some time + G_CheckClientIdle(ent, ucmd); } /* @@ -5543,120 +4415,103 @@ ClientThink A new command has arrived from the client ================== */ -extern void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_GentCantJump( gentity_t *gent ); -extern qboolean PM_WeaponOkOnVehicle( int weapon ); -void ClientThink( int clientNum, usercmd_t *ucmd ) { +extern void PM_CheckForceUseButton(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_GentCantJump(gentity_t *gent); +extern qboolean PM_WeaponOkOnVehicle(int weapon); +void ClientThink(int clientNum, usercmd_t *ucmd) { gentity_t *ent; qboolean restore_ucmd = qfalse; usercmd_t sav_ucmd = {0}; ent = g_entities + clientNum; - if ( ent->s.numberclient->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//you're controlling another NPC + if (ent->s.number < MAX_CLIENTS) { + if (ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_WORLD) { // you're controlling another NPC gentity_t *controlled = &g_entities[ent->client->ps.viewEntity]; qboolean freed = qfalse; - if ( controlled->NPC - && controlled->NPC->controlledTime - && ent->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//An NPC I'm controlling with mind trick - if ( controlled->NPC->controlledTime < level.time ) - {//time's up! - G_ClearViewEntity( ent ); + if (controlled->NPC && controlled->NPC->controlledTime && + ent->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // An NPC I'm controlling with mind trick + if (controlled->NPC->controlledTime < level.time) { // time's up! + G_ClearViewEntity(ent); freed = qtrue; - } - else if ( ucmd->upmove > 0 ) - {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? - G_ClearViewEntity( ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; - //stop player from doing anything for a half second after + } else if (ucmd->upmove > 0) { // jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have + // total control over an NPC? + G_ClearViewEntity(ent); + ucmd->upmove = 0; // ucmd->buttons = 0; + // stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } - } - else if ( controlled->client //an NPC - && PM_GentCantJump( controlled ) //that cannot jump - && controlled->client->moveType != MT_FLYSWIM ) //and does not use upmove to fly - {//these types use jump to get out - if ( ucmd->upmove > 0 ) - {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? - G_ClearViewEntity( ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; - //stop player from doing anything for a half second after + } else if (controlled->client // an NPC + && PM_GentCantJump(controlled) // that cannot jump + && controlled->client->moveType != MT_FLYSWIM) // and does not use upmove to fly + { // these types use jump to get out + if (ucmd->upmove > 0) { // jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total + // control over an NPC? + G_ClearViewEntity(ent); + ucmd->upmove = 0; // ucmd->buttons = 0; + // stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } } - if ( !freed ) - {//still controlling, save off my ucmd and clear it for my actual run through pmove + if (!freed) { // still controlling, save off my ucmd and clear it for my actual run through pmove restore_ucmd = qtrue; - memcpy( &sav_ucmd, ucmd, sizeof( usercmd_t ) ); - memset( ucmd, 0, sizeof( usercmd_t ) ); - //to keep pointing in same dir, need to set ucmd->angles - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + memcpy(&sav_ucmd, ucmd, sizeof(usercmd_t)); + memset(ucmd, 0, sizeof(usercmd_t)); + // to keep pointing in same dir, need to set ucmd->angles + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; - if ( controlled->NPC ) - { - VectorClear( controlled->client->ps.moveDir ); - controlled->client->ps.speed = (sav_ucmd.buttons&BUTTON_WALKING)?controlled->NPC->stats.walkSpeed:controlled->NPC->stats.runSpeed; + if (controlled->NPC) { + VectorClear(controlled->client->ps.moveDir); + controlled->client->ps.speed = (sav_ucmd.buttons & BUTTON_WALKING) ? controlled->NPC->stats.walkSpeed : controlled->NPC->stats.runSpeed; } - } - else - { - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + } else { + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; } - } - else if ( ent->client->NPC_class == CLASS_ATST ) - { - if ( ucmd->upmove > 0 ) - {//get out of ATST - GEntity_UseFunc( ent->activator, ent, ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; + } else if (ent->client->NPC_class == CLASS_ATST) { + if (ucmd->upmove > 0) { // get out of ATST + GEntity_UseFunc(ent->activator, ent, ent); + ucmd->upmove = 0; // ucmd->buttons = 0; } } - - PM_CheckForceUseButton( ent, ucmd ); + PM_CheckForceUseButton(ent, ucmd); } Vehicle_t *pVeh = NULL; // Rider logic. // NOTE: Maybe this should be extracted into a RiderUpdate() within the vehicle. - if ( ( pVeh = G_IsRidingVehicle( ent ) ) != 0 ) - { + if ((pVeh = G_IsRidingVehicle(ent)) != 0) { // If we're still in the vehicle... - if ( pVeh->m_pVehicleInfo->UpdateRider( pVeh, ent, ucmd ) ) - { + if (pVeh->m_pVehicleInfo->UpdateRider(pVeh, ent, ucmd)) { restore_ucmd = qtrue; - memcpy( &sav_ucmd, ucmd, sizeof( usercmd_t ) ); - memset( ucmd, 0, sizeof( usercmd_t ) ); - //to keep pointing in same dir, need to set ucmd->angles - //ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - //ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - //ucmd->angles[ROLL] = 0; + memcpy(&sav_ucmd, ucmd, sizeof(usercmd_t)); + memset(ucmd, 0, sizeof(usercmd_t)); + // to keep pointing in same dir, need to set ucmd->angles + // ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; + // ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + // ucmd->angles[ROLL] = 0; ucmd->angles[PITCH] = sav_ucmd.angles[PITCH]; ucmd->angles[YAW] = sav_ucmd.angles[YAW]; ucmd->angles[ROLL] = sav_ucmd.angles[ROLL]; - //if ( sav_ucmd.weapon != ent->client->ps.weapon && PM_WeaponOkOnVehicle( sav_ucmd.weapon ) ) - {//trying to change weapons to a valid weapon for this vehicle, to preserve this weapon change command + // if ( sav_ucmd.weapon != ent->client->ps.weapon && PM_WeaponOkOnVehicle( sav_ucmd.weapon ) ) + { // trying to change weapons to a valid weapon for this vehicle, to preserve this weapon change command ucmd->weapon = sav_ucmd.weapon; } - //else - {//keep our current weapon - // ucmd->weapon = ent->client->ps.weapon; - // if ( ent->client->ps.weapon != WP_NONE ) - {//not changing weapons and we are using one of our weapons, not using vehicle weapon - //so we actually want to do our fire weapon on us, not the vehicle - ucmd->buttons = (sav_ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)); - // sav_ucmd.buttons &= ~ucmd->buttons; + // else + { // keep our current weapon + // ucmd->weapon = ent->client->ps.weapon; + // if ( ent->client->ps.weapon != WP_NONE ) + { // not changing weapons and we are using one of our weapons, not using vehicle weapon + // so we actually want to do our fire weapon on us, not the vehicle + ucmd->buttons = (sav_ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)); + // sav_ucmd.buttons &= ~ucmd->buttons; } } } @@ -5664,45 +4519,35 @@ void ClientThink( int clientNum, usercmd_t *ucmd ) { ent->client->usercmd = *ucmd; -// if ( !g_syncronousClients->integer ) - { - ClientThink_real( ent, ucmd ); - } + // if ( !g_syncronousClients->integer ) + { ClientThink_real(ent, ucmd); } // If a vehicle, make sure to attach our driver and passengers here (after we pmove, which is done in Think_Real)) - if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent->client && ent->client->NPC_class == CLASS_VEHICLE) { pVeh = ent->m_pVehicle; - pVeh->m_pVehicleInfo->AttachRiders( pVeh ); + pVeh->m_pVehicleInfo->AttachRiders(pVeh); } - // ClientThink_real can end up freeing this ent, need to check - if ( restore_ucmd && ent->client ) - {//restore ucmd for later so NPC you're controlling can refer to them - memcpy( &ent->client->usercmd, &sav_ucmd, sizeof( usercmd_t ) ); + if (restore_ucmd && ent->client) { // restore ucmd for later so NPC you're controlling can refer to them + memcpy(&ent->client->usercmd, &sav_ucmd, sizeof(usercmd_t)); } - if ( ent->s.number ) - {//NPCs drown, burn from lava, etc, also - P_WorldEffects( ent ); + if (ent->s.number) { // NPCs drown, burn from lava, etc, also + P_WorldEffects(ent); } } -void ClientEndPowerUps( gentity_t *ent ) -{ - int i; +void ClientEndPowerUps(gentity_t *ent) { + int i; - if ( ent == NULL || ent->client == NULL ) - { + if (ent == NULL || ent->client == NULL) { return; } // turn off any expired powerups - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) - { - if ( ent->client->ps.powerups[ i ] < level.time ) - { - ent->client->ps.powerups[ i ] = 0; + for (i = 0; i < MAX_POWERUPS; i++) { + if (ent->client->ps.powerups[i] < level.time) { + ent->client->ps.powerups[i] = 0; } } } @@ -5715,18 +4560,17 @@ A fast client will have multiple ClientThink for each ClientEdFrame, while a slow client may have multiple ClientEndFrame between ClientThink. ============== */ -void ClientEndFrame( gentity_t *ent ) -{ +void ClientEndFrame(gentity_t *ent) { // // If the end of unit layout is displayed, don't give // the player any normal movement attributes // // burn from lava, etc - P_WorldEffects (ent); + P_WorldEffects(ent); // apply all the damage taken this frame - P_DamageFeedback (ent); + P_DamageFeedback(ent); // add the EF_CONNECTION flag if we haven't gotten commands recently /* @@ -5737,9 +4581,7 @@ void ClientEndFrame( gentity_t *ent ) } */ - ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... + ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... -// G_SetClientSound (ent); + // G_SetClientSound (ent); } - - diff --git a/code/game/g_breakable.cpp b/code/game/g_breakable.cpp index ae7c860e44..15223efb81 100644 --- a/code/game/g_breakable.cpp +++ b/code/game/g_breakable.cpp @@ -25,52 +25,50 @@ along with this program; if not, see . #include "../cgame/cg_media.h" #include "g_navigator.h" -//client side shortcut hacks from cg_local.h -extern void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ); -extern void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale, int customSound = 0 ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); +// client side shortcut hacks from cg_local.h +extern void CG_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType); +extern void CG_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale, int customSound = 0); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); -extern gentity_t *G_CreateObject ( gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType, int effectID ); +extern gentity_t *G_CreateObject(gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType, int effectID); -extern qboolean player_locked; +extern qboolean player_locked; //--------------------------------------------------- -static void CacheChunkEffects( material_t material ) -{ - switch( material ) - { +static void CacheChunkEffects(material_t material) { + switch (material) { case MAT_GLASS: - G_EffectIndex( "chunks/glassbreak" ); + G_EffectIndex("chunks/glassbreak"); break; case MAT_GLASS_METAL: - G_EffectIndex( "chunks/glassbreak" ); - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/glassbreak"); + G_EffectIndex("chunks/metalexplode"); break; case MAT_ELECTRICAL: case MAT_ELEC_METAL: - G_EffectIndex( "chunks/sparkexplode" ); + G_EffectIndex("chunks/sparkexplode"); break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: case MAT_CRATE1: case MAT_CRATE2: - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/metalexplode"); break; case MAT_GRATE1: - G_EffectIndex( "chunks/grateexplode" ); + G_EffectIndex("chunks/grateexplode"); break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: case MAT_WHITE_METAL: // what is this crap really supposed to be?? - G_EffectIndex( "chunks/rockbreaklg" ); - G_EffectIndex( "chunks/rockbreakmed" ); + G_EffectIndex("chunks/rockbreaklg"); + G_EffectIndex("chunks/rockbreakmed"); break; case MAT_ROPE: - G_EffectIndex( "chunks/ropebreak" ); -// G_SoundIndex(); // FIXME: give it a sound + G_EffectIndex("chunks/ropebreak"); + // G_SoundIndex(); // FIXME: give it a sound break; default: break; @@ -78,28 +76,25 @@ static void CacheChunkEffects( material_t material ) } //-------------------------------------- -void funcBBrushDieGo (gentity_t *self) -{ - vec3_t org, dir, up; - gentity_t *attacker = self->enemy; - float scale; - int numChunks, size = 0; - material_t chunkType = self->material; +void funcBBrushDieGo(gentity_t *self) { + vec3_t org, dir, up; + gentity_t *attacker = self->enemy; + float scale; + int numChunks, size = 0; + material_t chunkType = self->material; // if a missile is stuck to us, blow it up so we don't look dumb // FIXME: flag me so I should know to do this check! - for ( int i = 0; i < MAX_GENTITIES; i++ ) - { - if ( g_entities[i].s.groundEntityNum == self->s.number && ( g_entities[i].s.eFlags & EF_MISSILE_STICK )) - { - G_Damage( &g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH ); //?? MOD? + for (int i = 0; i < MAX_GENTITIES; i++) { + if (g_entities[i].s.groundEntityNum == self->s.number && (g_entities[i].s.eFlags & EF_MISSILE_STICK)) { + G_Damage(&g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH); //?? MOD? } } - //NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! - gi.AdjustAreaPortalState( self, qtrue ); + // NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! + gi.AdjustAreaPortalState(self, qtrue); - //So chunks don't get stuck inside me + // So chunks don't get stuck inside me self->s.solid = 0; self->contents = 0; self->clipmask = 0; @@ -107,89 +102,77 @@ void funcBBrushDieGo (gentity_t *self) VectorSet(up, 0, 0, 1); - if ( self->target && attacker != NULL ) - { + if (self->target && attacker != NULL) { G_UseTargets(self, attacker); } - VectorSubtract( self->absmax, self->absmin, org );// size + VectorSubtract(self->absmax, self->absmin, org); // size numChunks = Q_flrand(0.0f, 1.0f) * 6 + 18; // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = sqrt( sqrt( org[0] * org[1] * org[2] )) * 1.75f; + scale = sqrt(sqrt(org[0] * org[1] * org[2])) * 1.75f; - if ( scale > 48 ) - { + if (scale > 48) { size = 2; - } - else if ( scale > 24 ) - { + } else if (scale > 24) { size = 1; } scale = scale / numChunks; - if ( self->radius > 0.0f ) - { + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit + //weak numChunks *= self->radius; } - VectorMA( self->absmin, 0.5, org, org ); - VectorAdd( self->absmin,self->absmax, org ); - VectorScale( org, 0.5f, org ); + VectorMA(self->absmin, 0.5, org, org); + VectorAdd(self->absmin, self->absmax, org); + VectorScale(org, 0.5f, org); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( org, attacker->currentOrigin, dir ); - VectorNormalize( dir ); - } - else - { + if (attacker != NULL && attacker->client) { + VectorSubtract(org, attacker->currentOrigin, dir); + VectorNormalize(dir); + } else { VectorCopy(up, dir); } - if ( !(self->spawnflags & 2048) ) // NO_EXPLOSION + if (!(self->spawnflags & 2048)) // NO_EXPLOSION { // we are allowed to explode - CG_MiscModelExplosion( self->absmin, self->absmax, size, chunkType ); + CG_MiscModelExplosion(self->absmin, self->absmax, size, chunkType); } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - //explode - AddSightEvent( attacker, org, 256, AEL_DISCOVERED, 100 ); - AddSoundEvent( attacker, org, 128, AEL_DISCOVERED, qfalse, qtrue );//FIXME: am I on ground or not? - G_RadiusDamage( org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + // explode + AddSightEvent(attacker, org, 256, AEL_DISCOVERED, 100); + AddSoundEvent(attacker, org, 128, AEL_DISCOVERED, qfalse, qtrue); // FIXME: am I on ground or not? + G_RadiusDamage(org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); - gentity_t *te = G_TempEntity( org, EV_GENERAL_SOUND ); + gentity_t *te = G_TempEntity(org, EV_GENERAL_SOUND); te->s.eventParm = G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - } - else - {//just break - AddSightEvent( attacker, org, 128, AEL_DISCOVERED ); - AddSoundEvent( attacker, org, 64, AEL_SUSPICIOUS, qfalse, qtrue );//FIXME: am I on ground or not? + } else { // just break + AddSightEvent(attacker, org, 128, AEL_DISCOVERED); + AddSoundEvent(attacker, org, 64, AEL_SUSPICIOUS, qfalse, qtrue); // FIXME: am I on ground or not? } - //FIXME: base numChunks off size? - CG_Chunks( self->s.number, org, dir, self->absmin, self->absmax, 300, numChunks, chunkType, 0, scale, self->noise_index ); + // FIXME: base numChunks off size? + CG_Chunks(self->s.number, org, dir, self->absmin, self->absmax, 300, numChunks, chunkType, 0, scale, self->noise_index); self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + 50; - //G_FreeEntity( self ); + // G_FreeEntity( self ); } -void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc) -{ - self->takedamage = qfalse;//stop chain reaction runaway loops +void funcBBrushDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + self->takedamage = qfalse; // stop chain reaction runaway loops G_SetEnemy(self, attacker); - if(self->delay) - { + if (self->delay) { self->e_ThinkFunc = thinkF_funcBBrushDieGo; self->nextthink = level.time + floor(self->delay * 1000.0f); return; @@ -198,63 +181,48 @@ void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, funcBBrushDieGo(self); } -void funcBBrushUse (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior( self, BSET_USE ); - if(self->spawnflags & 64) - {//Using it doesn't break it, makes it use it's targets - if(self->target && self->target[0]) - { +void funcBBrushUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + if (self->spawnflags & 64) { // Using it doesn't break it, makes it use it's targets + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - } - else - { + } else { funcBBrushDie(self, other, activator, self->health, MOD_UNKNOWN); } } -void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod,int hitLoc) -{ - if ( self->painDebounceTime > level.time ) - { +void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->painDebounceTime > level.time) { return; } - if ( self->paintarget ) - { - G_UseTargets2 (self, self->activator, self->paintarget); + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); - if ( self->material == MAT_DRK_STONE - || self->material == MAT_LT_STONE - || self->material == MAT_GREY_STONE ) - { - vec3_t org, dir; - float scale; - VectorSubtract( self->absmax, self->absmin, org );// size + if (self->material == MAT_DRK_STONE || self->material == MAT_LT_STONE || self->material == MAT_GREY_STONE) { + vec3_t org, dir; + float scale; + VectorSubtract(self->absmax, self->absmin, org); // size // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = VectorLength( org ) / 100.0f; - VectorMA( self->absmin, 0.5, org, org ); - VectorAdd( self->absmin,self->absmax, org ); - VectorScale( org, 0.5f, org ); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( attacker->currentOrigin, org, dir ); - VectorNormalize( dir ); - } - else - { - VectorSet( dir, 0, 0, 1 ); + scale = VectorLength(org) / 100.0f; + VectorMA(self->absmin, 0.5, org, org); + VectorAdd(self->absmin, self->absmax, org); + VectorScale(org, 0.5f, org); + if (attacker != NULL && attacker->client) { + VectorSubtract(attacker->currentOrigin, org, dir); + VectorNormalize(dir); + } else { + VectorSet(dir, 0, 0, 1); } - CG_Chunks( self->s.number, org, dir, self->absmin, self->absmax, 300, Q_irand( 1, 3 ), self->material, 0, scale ); + CG_Chunks(self->s.number, org, dir, self->absmin, self->absmax, 300, Q_irand(1, 3), self->material, 0, scale); } - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->e_PainFunc = painF_NULL; return; } @@ -262,15 +230,14 @@ void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, self->painDebounceTime = level.time + self->wait; } -static void InitBBrush ( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +static void InitBBrush(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); ent->e_DieFunc = dieF_funcBBrushDie; @@ -278,52 +245,47 @@ static void InitBBrush ( gentity_t *ent ) // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 ) - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + if (ent->model2) { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) - { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } - if(ent->spawnflags & 128) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } ent->s.eType = ET_MOVER; - gi.linkentity (ent); + gi.linkentity(ent); ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); } -void funcBBrushTouch( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ -} +void funcBBrushTouch(gentity_t *ent, gentity_t *other, trace_t *trace) {} /*QUAKED func_breakable (0 .8 .5) ? INVINCIBLE IMPACT CRUSHER THIN SABERONLY HEAVY_WEAP USE_NOT_BREAK PLAYER_USE NO_EXPLOSION INVINCIBLE - can only be broken by being used @@ -346,10 +308,9 @@ When destroyed, fires it's trigger and chunks and plays sound "noise" or sound f "modelAngles" md3 model's angles (in addition to any rotation on the part of the brush entity itself) "target" all entities with a matching targetname will be used when this is destoryed "health" default is 10 -"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks -"NPC_targetname" - Only the NPC with this name can damage this -"forcevisible" - When you turn on force sight (any level), you can see these draw through the entire level... -"redCrosshair" - crosshair turns red when you look at this +"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many +chunks, (2) is twice as many chunks "NPC_targetname" - Only the NPC with this name can damage this "forcevisible" - When you turn on force sight (any level), +you can see these draw through the entire level... "redCrosshair" - crosshair turns red when you look at this Damage: default is none "splashDamage" - damage to do @@ -383,49 +344,40 @@ Don't know if these work: 15 = MAT_WHITE_METAL (white angular chunks for Stu, NS_hideout ) */ -void SP_func_breakable( gentity_t *self ) -{ - if(!(self->spawnflags & 1)) - { - if(!self->health) - { +void SP_func_breakable(gentity_t *self) { + if (!(self->spawnflags & 1)) { + if (!self->health) { self->health = 10; } } - if ( self->spawnflags & 16 ) // saber only + if (self->spawnflags & 16) // saber only { self->flags |= FL_DMG_BY_SABER_ONLY; - } - else if ( self->spawnflags & 32 ) // heavy weap + } else if (self->spawnflags & 32) // heavy weap { self->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; } - if (self->health) - { + if (self->health) { self->takedamage = qtrue; } - G_SoundIndex("sound/weapons/explosions/cargoexplode.wav");//precaching - G_SpawnFloat( "radius", "1", &self->radius ); // used to scale chunk code if desired by a designer - G_SpawnInt( "material", "0", (int*)&self->material ); - CacheChunkEffects( self->material ); + G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); // precaching + G_SpawnFloat("radius", "1", &self->radius); // used to scale chunk code if desired by a designer + G_SpawnInt("material", "0", (int *)&self->material); + CacheChunkEffects(self->material); self->e_UseFunc = useF_funcBBrushUse; - //if ( self->paintarget ) - { - self->e_PainFunc = painF_funcBBrushPain; - } + // if ( self->paintarget ) + { self->e_PainFunc = painF_funcBBrushPain; } self->e_TouchFunc = touchF_funcBBrushTouch; - if ( self->team && self->team[0] ) - { - self->noDamageTeam = (team_t)GetIDForString( TeamTable, self->team ); - if(self->noDamageTeam == TEAM_FREE) - { + if (self->team && self->team[0]) { + self->noDamageTeam = (team_t)GetIDForString(TeamTable, self->team); + if (self->noDamageTeam == TEAM_FREE) { G_Error("team name %s not recognized\n", self->team); } } @@ -433,119 +385,105 @@ void SP_func_breakable( gentity_t *self ) if (!self->model) { G_Error("func_breakable with NULL model\n"); } - InitBBrush( self ); + InitBBrush(self); - char buffer[MAX_QPATH]; - char *s; - if ( G_SpawnString( "noise", "*NOSOUND*", &s ) ) - { - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); + char buffer[MAX_QPATH]; + char *s; + if (G_SpawnString("noise", "*NOSOUND*", &s)) { + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); self->noise_index = G_SoundIndex(buffer); } int forceVisible = 0; - G_SpawnInt( "forcevisible", "0", &forceVisible ); - if ( forceVisible ) - {//can see these through walls with force sight, so must be broadcast - if ( VectorCompare( self->s.origin, vec3_origin ) ) - {//no origin brush + G_SpawnInt("forcevisible", "0", &forceVisible); + if (forceVisible) { // can see these through walls with force sight, so must be broadcast + if (VectorCompare(self->s.origin, vec3_origin)) { // no origin brush self->svFlags |= SVF_BROADCAST; } self->s.eFlags |= EF_FORCE_VISIBLE; } int redCrosshair = 0; - G_SpawnInt( "redCrosshair", "0", &redCrosshair ); - if ( redCrosshair ) - {//can see these through walls with force sight, so must be broadcast + G_SpawnInt("redCrosshair", "0", &redCrosshair); + if (redCrosshair) { // can see these through walls with force sight, so must be broadcast self->flags |= FL_RED_CROSSHAIR; } } - -void misc_model_breakable_pain ( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->health > 0 ) - { +void misc_model_breakable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->health > 0) { // still alive, react to the pain - if ( self->paintarget ) - { - G_UseTargets2 (self, self->activator, self->paintarget); + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } // Don't do script if dead - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); } } -void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ - int numChunks; - float size = 0, scale; - vec3_t dir, up, dis; +void misc_model_breakable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { + int numChunks; + float size = 0, scale; + vec3_t dir, up, dis; - if (self->e_DieFunc == dieF_NULL) //i was probably already killed since my die func was removed + if (self->e_DieFunc == dieF_NULL) // i was probably already killed since my die func was removed { #ifndef FINAL_BUILD - gi.Printf(S_COLOR_YELLOW"Recursive misc_model_breakable_die. Use targets probably pointing back at self.\n"); + gi.Printf(S_COLOR_YELLOW "Recursive misc_model_breakable_die. Use targets probably pointing back at self.\n"); #endif - return; //this happens when you have a cyclic target chain! + return; // this happens when you have a cyclic target chain! } - //NOTE: Stop any scripts that are currently running (FLUSH)... ? - //Turn off animation + // NOTE: Stop any scripts that are currently running (FLUSH)... ? + // Turn off animation self->s.frame = self->startFrame = self->endFrame = 0; self->svFlags &= ~SVF_ANIMATING; self->health = 0; - //Throw some chunks - AngleVectors( self->s.apos.trBase, dir, NULL, NULL ); - VectorNormalize( dir ); + // Throw some chunks + AngleVectors(self->s.apos.trBase, dir, NULL, NULL); + VectorNormalize(dir); numChunks = Q_flrand(0.0f, 1.0f) * 6 + 20; - VectorSubtract( self->absmax, self->absmin, dis ); + VectorSubtract(self->absmax, self->absmin, dis); // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = sqrt( sqrt( dis[0] * dis[1] * dis[2] )) * 1.75f; + scale = sqrt(sqrt(dis[0] * dis[1] * dis[2])) * 1.75f; - if ( scale > 48 ) - { + if (scale > 48) { size = 2; - } - else if ( scale > 24 ) - { + } else if (scale > 24) { size = 1; } scale = scale / numChunks; - if ( self->radius > 0.0f ) - { + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit + //weak numChunks *= self->radius; } - VectorAdd( self->absmax, self->absmin, dis ); - VectorScale( dis, 0.5f, dis ); + VectorAdd(self->absmax, self->absmin, dis); + VectorScale(dis, 0.5f, dis); - CG_Chunks( self->s.number, dis, dir, self->absmin, self->absmax, 300, numChunks, self->material, self->s.modelindex3, scale ); + CG_Chunks(self->s.number, dis, dir, self->absmin, self->absmax, 300, numChunks, self->material, self->s.modelindex3, scale); self->e_PainFunc = painF_NULL; - self->e_DieFunc = dieF_NULL; -// self->e_UseFunc = useF_NULL; + self->e_DieFunc = dieF_NULL; + // self->e_UseFunc = useF_NULL; self->takedamage = qfalse; - if ( !(self->spawnflags & 4) ) - {//We don't want to stay solid + if (!(self->spawnflags & 4)) { // We don't want to stay solid self->s.solid = 0; self->contents = 0; self->clipmask = 0; - if (self!=0) - { + if (self != 0) { NAV::WayEdgesNowClear(self); } gi.linkentity(self); @@ -553,60 +491,50 @@ void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t VectorSet(up, 0, 0, 1); - if(self->target) - { + if (self->target) { G_UseTargets(self, attacker); } - if(inflictor->client) - { - VectorSubtract( self->currentOrigin, inflictor->currentOrigin, dir ); - VectorNormalize( dir ); - } - else - { + if (inflictor->client) { + VectorSubtract(self->currentOrigin, inflictor->currentOrigin, dir); + VectorNormalize(dir); + } else { VectorCopy(up, dir); } - if ( !(self->spawnflags & 2048) ) // NO_EXPLOSION + if (!(self->spawnflags & 2048)) // NO_EXPLOSION { // Ok, we are allowed to explode, so do it now! - if(self->splashDamage > 0 && self->splashRadius > 0) - {//explode + if (self->splashDamage > 0 && self->splashRadius > 0) { // explode vec3_t org; - AddSightEvent( attacker, self->currentOrigin, 256, AEL_DISCOVERED, 100 ); - AddSoundEvent( attacker, self->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue );//FIXME: am I on ground or not? - //FIXME: specify type of explosion? (barrel, electrical, etc.) Also, maybe just use the explosion effect below since it's + AddSightEvent(attacker, self->currentOrigin, 256, AEL_DISCOVERED, 100); + AddSoundEvent(attacker, self->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue); // FIXME: am I on ground or not? + // FIXME: specify type of explosion? (barrel, electrical, etc.) Also, maybe just use the explosion effect below since it's // a bit better? - // up the origin a little for the damage check, because several models have their origin on the ground, so they don't alwasy do damage, not the optimal solution... - VectorCopy( self->currentOrigin, org ); - if ( self->mins[2] > -4 ) - {//origin is going to be below it or very very low in the model - //center the origin - org[2] = self->currentOrigin[2] + self->mins[2] + (self->maxs[2] - self->mins[2])/2.0f; + // up the origin a little for the damage check, because several models have their origin on the ground, so they don't alwasy do damage, not the + // optimal solution... + VectorCopy(self->currentOrigin, org); + if (self->mins[2] > -4) { // origin is going to be below it or very very low in the model + // center the origin + org[2] = self->currentOrigin[2] + self->mins[2] + (self->maxs[2] - self->mins[2]) / 2.0f; } - G_RadiusDamage( org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + G_RadiusDamage(org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); - if ( self->model && ( Q_stricmp( "models/map_objects/ships/tie_fighter.md3", self->model ) == 0 || - Q_stricmp( "models/map_objects/ships/tie_bomber.md3", self->model ) == 0 ) ) - {//TEMP HACK for Tie Fighters- they're HUGE - G_PlayEffect( "explosions/fighter_explosion2", self->currentOrigin ); - G_Sound( self, G_SoundIndex( "sound/weapons/tie_fighter/TIEexplode.wav" ) ); + if (self->model && (Q_stricmp("models/map_objects/ships/tie_fighter.md3", self->model) == 0 || + Q_stricmp("models/map_objects/ships/tie_bomber.md3", self->model) == 0)) { // TEMP HACK for Tie Fighters- they're HUGE + G_PlayEffect("explosions/fighter_explosion2", self->currentOrigin); + G_Sound(self, G_SoundIndex("sound/weapons/tie_fighter/TIEexplode.wav")); self->s.loopSound = 0; - } - else - { - CG_MiscModelExplosion( self->absmin, self->absmax, size, self->material ); - G_Sound( self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav") ); + } else { + CG_MiscModelExplosion(self->absmin, self->absmax, size, self->material); + G_Sound(self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav")); self->s.loopSound = 0; } - } - else - {//just break - AddSightEvent( attacker, self->currentOrigin, 128, AEL_DISCOVERED ); - AddSoundEvent( attacker, self->currentOrigin, 64, AEL_SUSPICIOUS, qfalse, qtrue );//FIXME: am I on ground or not? + } else { // just break + AddSightEvent(attacker, self->currentOrigin, 128, AEL_DISCOVERED); + AddSoundEvent(attacker, self->currentOrigin, 64, AEL_SUSPICIOUS, qfalse, qtrue); // FIXME: am I on ground or not? // This is the default explosion - CG_MiscModelExplosion( self->absmin, self->absmax, size, self->material ); + CG_MiscModelExplosion(self->absmin, self->absmax, size, self->material); G_Sound(self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav")); } } @@ -614,121 +542,95 @@ void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - if(self->s.modelindex2 != -1 && !(self->spawnflags & 8)) - {//FIXME: modelindex doesn't get set to -1 if the damage model doesn't exist + if (self->s.modelindex2 != -1 && !(self->spawnflags & 8)) { // FIXME: modelindex doesn't get set to -1 if the damage model doesn't exist self->svFlags |= SVF_BROKEN; self->s.modelindex = self->s.modelindex2; - G_ActivateBehavior( self, BSET_DEATH ); - } - else - { - G_FreeEntity( self ); + G_ActivateBehavior(self, BSET_DEATH); + } else { + G_FreeEntity(self); } } -void misc_model_throw_at_target4( gentity_t *self, gentity_t *activator ) -{ - vec3_t pushDir, kvel; - float knockback = 200; - float mass = self->mass; - gentity_t *target = G_Find( NULL, FOFS(targetname), self->target4 ); - if ( !target ) - {//nothing to throw ourselves at... +void misc_model_throw_at_target4(gentity_t *self, gentity_t *activator) { + vec3_t pushDir, kvel; + float knockback = 200; + float mass = self->mass; + gentity_t *target = G_Find(NULL, FOFS(targetname), self->target4); + if (!target) { // nothing to throw ourselves at... return; } - VectorSubtract( target->currentOrigin, self->currentOrigin, pushDir ); - knockback -= VectorNormalize( pushDir ); - if ( knockback < 100 ) - { + VectorSubtract(target->currentOrigin, self->currentOrigin, pushDir); + knockback -= VectorNormalize(pushDir); + if (knockback < 100) { knockback = 100; } - VectorCopy( self->currentOrigin, self->s.pos.trBase ); - self->s.pos.trTime = level.time; // move a bit on the very first frame - if ( self->s.pos.trType != TR_INTERPOLATE ) - {//don't do this to rolling missiles + VectorCopy(self->currentOrigin, self->s.pos.trBase); + self->s.pos.trTime = level.time; // move a bit on the very first frame + if (self->s.pos.trType != TR_INTERPOLATE) { // don't do this to rolling missiles self->s.pos.trType = TR_GRAVITY; } - if ( mass < 50 ) - {//??? + if (mass < 50) { //??? mass = 50; } - if ( g_gravity->value > 0 ) - { - VectorScale( pushDir, g_knockback->value * knockback / mass * 0.8, kvel ); + if (g_gravity->value > 0) { + VectorScale(pushDir, g_knockback->value * knockback / mass * 0.8, kvel); kvel[2] = pushDir[2] * g_knockback->value * knockback / mass * 1.5; - } - else - { - VectorScale( pushDir, g_knockback->value * knockback / mass, kvel ); + } else { + VectorScale(pushDir, g_knockback->value * knockback / mass, kvel); } - VectorAdd( self->s.pos.trDelta, kvel, self->s.pos.trDelta ); - if ( g_gravity->value > 0 ) - { - if ( self->s.pos.trDelta[2] < knockback ) - { + VectorAdd(self->s.pos.trDelta, kvel, self->s.pos.trDelta); + if (g_gravity->value > 0) { + if (self->s.pos.trDelta[2] < knockback) { self->s.pos.trDelta[2] = knockback; } } - //no trDuration? - if ( self->e_ThinkFunc != thinkF_G_RunObject ) - {//objects spin themselves? - //spin it - //FIXME: messing with roll ruins the rotational center??? + // no trDuration? + if (self->e_ThinkFunc != thinkF_G_RunObject) { // objects spin themselves? + // spin it + // FIXME: messing with roll ruins the rotational center??? self->s.apos.trTime = level.time; self->s.apos.trType = TR_LINEAR; - VectorClear( self->s.apos.trDelta ); - self->s.apos.trDelta[1] = Q_irand( -800, 800 ); + VectorClear(self->s.apos.trDelta); + self->s.apos.trDelta[1] = Q_irand(-800, 800); } self->forcePushTime = level.time + 600; // let the push effect last for 600 ms - if ( activator ) - { - self->forcePuller = activator->s.number;//remember this regardless - } - else - { + if (activator) { + self->forcePuller = activator->s.number; // remember this regardless + } else { self->forcePuller = 0; } } -void misc_model_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->target4 ) - {//throw me at my target! - misc_model_throw_at_target4( self, activator ); +void misc_model_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->target4) { // throw me at my target! + misc_model_throw_at_target4(self, activator); return; } - if ( self->health <= 0 && self->max_health > 0) - {//used while broken fired target3 - G_UseTargets2( self, activator, self->target3 ); + if (self->health <= 0 && self->max_health > 0) { // used while broken fired target3 + G_UseTargets2(self, activator, self->target3); return; } // Become solid again. - if ( !self->count ) - { + if (!self->count) { self->count = 1; self->activator = activator; self->svFlags &= ~SVF_NOCLIENT; self->s.eFlags &= ~EF_NODRAW; } - G_ActivateBehavior( self, BSET_USE ); - //Don't explode if they've requested it to not - if ( self->spawnflags & 64 ) - {//Usemodels toggling - if ( self->spawnflags & 32 ) - { - if( self->s.modelindex == self->sound1to2 ) - { + G_ActivateBehavior(self, BSET_USE); + // Don't explode if they've requested it to not + if (self->spawnflags & 64) { // Usemodels toggling + if (self->spawnflags & 32) { + if (self->s.modelindex == self->sound1to2) { self->s.modelindex = self->sound2to1; - } - else - { + } else { self->s.modelindex = self->sound1to2; } } @@ -736,119 +638,100 @@ void misc_model_use (gentity_t *self, gentity_t *other, gentity_t *activator) return; } - self->e_DieFunc = dieF_misc_model_breakable_die; - misc_model_breakable_die( self, other, activator, self->health, MOD_UNKNOWN ); + self->e_DieFunc = dieF_misc_model_breakable_die; + misc_model_breakable_die(self, other, activator, self->health, MOD_UNKNOWN); } -#define MDL_OTHER 0 -#define MDL_ARMOR_HEALTH 1 -#define MDL_AMMO 2 +#define MDL_OTHER 0 +#define MDL_ARMOR_HEALTH 1 +#define MDL_AMMO 2 -void misc_model_breakable_init( gentity_t *ent ) -{ - int type; +void misc_model_breakable_init(gentity_t *ent) { + int type; type = MDL_OTHER; if (!ent->model) { - G_Error("no model set on %s at (%.1f %.1f %.1f)\n", ent->classname, ent->s.origin[0],ent->s.origin[1],ent->s.origin[2]); + G_Error("no model set on %s at (%.1f %.1f %.1f)\n", ent->classname, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2]); } - //Main model - ent->s.modelindex = ent->sound2to1 = G_ModelIndex( ent->model ); + // Main model + ent->s.modelindex = ent->sound2to1 = G_ModelIndex(ent->model); - if ( ent->spawnflags & 1 ) - {//Blocks movement - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//Was CONTENTS_SOLID, but only architecture should be this - } - else if ( ent->health ) - {//Can only be shot + if (ent->spawnflags & 1) { // Blocks movement + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | + CONTENTS_BOTCLIP; // Was CONTENTS_SOLID, but only architecture should be this + } else if (ent->health) { // Can only be shot ent->contents = CONTENTS_SHOTCLIP; } - if (type == MDL_OTHER) - { + if (type == MDL_OTHER) { ent->e_UseFunc = useF_misc_model_use; - } - else if ( type == MDL_ARMOR_HEALTH ) - { -// G_SoundIndex("sound/player/suithealth.wav"); + } else if (type == MDL_ARMOR_HEALTH) { + // G_SoundIndex("sound/player/suithealth.wav"); ent->e_UseFunc = useF_health_use; - if (!ent->count) - { + if (!ent->count) { ent->count = 100; } ent->health = 60; - } - else if ( type == MDL_AMMO ) - { -// G_SoundIndex("sound/player/suitenergy.wav"); + } else if (type == MDL_AMMO) { + // G_SoundIndex("sound/player/suitenergy.wav"); ent->e_UseFunc = useF_ammo_use; - if (!ent->count) - { + if (!ent->count) { ent->count = 100; } ent->health = 60; } - if ( ent->health ) - { + if (ent->health) { G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); ent->max_health = ent->health; ent->takedamage = qtrue; ent->e_PainFunc = painF_misc_model_breakable_pain; - ent->e_DieFunc = dieF_misc_model_breakable_die; + ent->e_DieFunc = dieF_misc_model_breakable_die; } } -void TieFighterThink ( gentity_t *self ) -{ +void TieFighterThink(gentity_t *self) { gentity_t *player = &g_entities[0]; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } self->nextthink = level.time + FRAMETIME; - if ( player ) - { - vec3_t playerDir, fighterDir, fwd, rt; - float playerDist, fighterSpeed; + if (player) { + vec3_t playerDir, fighterDir, fwd, rt; + float playerDist, fighterSpeed; - //use player eyepoint - VectorSubtract( player->currentOrigin, self->currentOrigin, playerDir ); - playerDist = VectorNormalize( playerDir ); - VectorSubtract( self->currentOrigin, self->lastOrigin, fighterDir ); - VectorCopy( self->currentOrigin, self->lastOrigin ); - fighterSpeed = VectorNormalize( fighterDir )*1000; - AngleVectors( self->currentAngles, fwd, rt, NULL ); + // use player eyepoint + VectorSubtract(player->currentOrigin, self->currentOrigin, playerDir); + playerDist = VectorNormalize(playerDir); + VectorSubtract(self->currentOrigin, self->lastOrigin, fighterDir); + VectorCopy(self->currentOrigin, self->lastOrigin); + fighterSpeed = VectorNormalize(fighterDir) * 1000; + AngleVectors(self->currentAngles, fwd, rt, NULL); - if ( fighterSpeed ) - { - float side; + if (fighterSpeed) { + float side; // Magic number fun! Speed is used for banking, so modulate the speed by a sine wave - fighterSpeed *= sin( ( 100 ) * 0.003 ); + fighterSpeed *= sin((100) * 0.003); // Clamp to prevent harsh rolling - if ( fighterSpeed > 10 ) + if (fighterSpeed > 10) fighterSpeed = 10; - side = fighterSpeed * DotProduct( fighterDir, rt ); + side = fighterSpeed * DotProduct(fighterDir, rt); self->s.apos.trBase[2] -= side; } - //FIXME: bob up/down, strafe left/right some - float dot = DotProduct( playerDir, fighterDir ); - if ( dot > 0 ) - {//heading toward the player - if ( playerDist < 1024 ) - { - if ( DotProduct( playerDir, fwd ) > 0.7 ) - {//facing the player - if ( self->attackDebounceTime < level.time ) - { - gentity_t *bolt; + // FIXME: bob up/down, strafe left/right some + float dot = DotProduct(playerDir, fighterDir); + if (dot > 0) { // heading toward the player + if (playerDist < 1024) { + if (DotProduct(playerDir, fwd) > 0.7) { // facing the player + if (self->attackDebounceTime < level.time) { + gentity_t *bolt; bolt = G_Spawn(); @@ -859,64 +742,54 @@ void TieFighterThink ( gentity_t *self ) bolt->s.weapon = WP_BLASTER; bolt->owner = self; bolt->damage = 30; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; - bolt->methodOfDeath = MOD_ENERGY; // ? + bolt->methodOfDeath = MOD_ENERGY; // ? bolt->clipmask = MASK_SHOT; bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( self->currentOrigin, bolt->s.pos.trBase ); - VectorScale( fwd, 8000, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( self->currentOrigin, bolt->currentOrigin); - - if ( !Q_irand( 0, 2 ) ) - { - G_SoundOnEnt( bolt, CHAN_VOICE, "sound/weapons/tie_fighter/tie_fire.wav" ); - } - else - { - G_SoundOnEnt( bolt, CHAN_VOICE, va( "sound/weapons/tie_fighter/tie_fire%d.wav", Q_irand( 2, 3 ) ) ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(self->currentOrigin, bolt->s.pos.trBase); + VectorScale(fwd, 8000, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(self->currentOrigin, bolt->currentOrigin); + + if (!Q_irand(0, 2)) { + G_SoundOnEnt(bolt, CHAN_VOICE, "sound/weapons/tie_fighter/tie_fire.wav"); + } else { + G_SoundOnEnt(bolt, CHAN_VOICE, va("sound/weapons/tie_fighter/tie_fire%d.wav", Q_irand(2, 3))); } - self->attackDebounceTime = level.time + Q_irand( 300, 2000 ); + self->attackDebounceTime = level.time + Q_irand(300, 2000); } } } } - if ( playerDist < 1024 )//512 ) - {//within range to start our sound - if ( dot > 0 ) - { - if ( !self->fly_sound_debounce_time ) - {//start sound - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/tie_fighter/tiepass%d.wav", Q_irand( 1, 5 ) ) ); + if (playerDist < 1024) // 512 ) + { // within range to start our sound + if (dot > 0) { + if (!self->fly_sound_debounce_time) { // start sound + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/tie_fighter/tiepass%d.wav", Q_irand(1, 5))); self->fly_sound_debounce_time = 2000; - } - else - {//sound already started + } else { // sound already started self->fly_sound_debounce_time = -1; } } - } - else if ( self->fly_sound_debounce_time < level.time ) - { + } else if (self->fly_sound_debounce_time < level.time) { self->fly_sound_debounce_time = 0; } } } -void TieFighterUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !self || !other || !activator ) +void TieFighterUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!self || !other || !activator) return; - vec3_t fwd, rt; - AngleVectors( self->currentAngles, fwd, rt, NULL ); + vec3_t fwd, rt; + AngleVectors(self->currentAngles, fwd, rt, NULL); - gentity_t *bolt; + gentity_t *bolt; bolt = G_Spawn(); bolt->classname = "tie_proj"; @@ -926,20 +799,20 @@ void TieFighterUse( gentity_t *self, gentity_t *other, gentity_t *activator ) bolt->s.weapon = WP_TIE_FIGHTER; bolt->owner = self; bolt->damage = 30; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; - bolt->methodOfDeath = MOD_ENERGY; // ? + bolt->methodOfDeath = MOD_ENERGY; // ? bolt->clipmask = MASK_SHOT; bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( self->currentOrigin, bolt->s.pos.trBase ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(self->currentOrigin, bolt->s.pos.trBase); rt[2] += 2.0f; - VectorMA( bolt->s.pos.trBase, -15.0, rt, bolt->s.pos.trBase ); - VectorScale( fwd, 3000, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( self->currentOrigin, bolt->currentOrigin); + VectorMA(bolt->s.pos.trBase, -15.0, rt, bolt->s.pos.trBase); + VectorScale(fwd, 3000, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(self->currentOrigin, bolt->currentOrigin); bolt = G_Spawn(); @@ -950,43 +823,40 @@ void TieFighterUse( gentity_t *self, gentity_t *other, gentity_t *activator ) bolt->s.weapon = WP_TIE_FIGHTER; bolt->owner = self; bolt->damage = 30; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; - bolt->methodOfDeath = MOD_ENERGY; // ? + bolt->methodOfDeath = MOD_ENERGY; // ? bolt->clipmask = MASK_SHOT; bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( self->currentOrigin, bolt->s.pos.trBase ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(self->currentOrigin, bolt->s.pos.trBase); rt[2] -= 4.0f; - VectorMA( bolt->s.pos.trBase, 15.0, rt, bolt->s.pos.trBase ); - VectorScale( fwd, 3000, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( self->currentOrigin, bolt->currentOrigin); + VectorMA(bolt->s.pos.trBase, 15.0, rt, bolt->s.pos.trBase); + VectorScale(fwd, 3000, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(self->currentOrigin, bolt->currentOrigin); } -void TouchTieBomb( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void TouchTieBomb(gentity_t *self, gentity_t *other, trace_t *trace) { // Stop the effect. - G_StopEffect( G_EffectIndex( "ships/tiebomber_bomb_falling" ), self->playerModel, gi.G2API_AddBolt( &self->ghoul2[0], "model_root" ), self->s.number ); + G_StopEffect(G_EffectIndex("ships/tiebomber_bomb_falling"), self->playerModel, gi.G2API_AddBolt(&self->ghoul2[0], "model_root"), self->s.number); self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + FRAMETIME; - G_PlayEffect( G_EffectIndex( "ships/tiebomber_explosion2" ), self->currentOrigin, self->currentAngles ); - G_RadiusDamage( self->currentOrigin, self, 900, 500, self, MOD_EXPLOSIVE_SPLASH ); + G_PlayEffect(G_EffectIndex("ships/tiebomber_explosion2"), self->currentOrigin, self->currentAngles); + G_RadiusDamage(self->currentOrigin, self, 900, 500, self, MOD_EXPLOSIVE_SPLASH); } -#define MIN_PLAYER_DIST 1600 +#define MIN_PLAYER_DIST 1600 -void TieBomberThink( gentity_t *self ) -{ +void TieBomberThink(gentity_t *self) { // NOTE: Lerp2Angles will think this thinkfunc if the model is a misc_model_breakable. Watchout // for that in a script (try to just use ROFF's?). // Stop thinking, you're dead. - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } @@ -994,36 +864,36 @@ void TieBomberThink( gentity_t *self ) self->nextthink = level.time + FRAMETIME; gentity_t *player = &g_entities[0]; - vec3_t playerDir; - float playerDist; + vec3_t playerDir; + float playerDist; - //use player eyepoint - VectorSubtract( player->currentOrigin, self->currentOrigin, playerDir ); - playerDist = VectorNormalize( playerDir ); + // use player eyepoint + VectorSubtract(player->currentOrigin, self->currentOrigin, playerDir); + playerDist = VectorNormalize(playerDir); // Time to attack? - if ( player->health > 0 && playerDist < MIN_PLAYER_DIST && self->attackDebounceTime < level.time ) - { + if (player->health > 0 && playerDist < MIN_PLAYER_DIST && self->attackDebounceTime < level.time) { // Doesn't matter what model gets loaded here, as long as it exists. // It's only used as a point on to which the falling effect for the bomb // can be attached to (kinda inefficient, I know). char name1[200] = "models/players/gonk/model.glm"; - gentity_t *bomb = G_CreateObject( self, self->s.pos.trBase, self->s.apos.trBase, 0, 0, TR_GRAVITY, 0 ); - bomb->s.modelindex = G_ModelIndex( name1 ); - gi.G2API_InitGhoul2Model( bomb->ghoul2, name1, bomb->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + gentity_t *bomb = G_CreateObject(self, self->s.pos.trBase, self->s.apos.trBase, 0, 0, TR_GRAVITY, 0); + bomb->s.modelindex = G_ModelIndex(name1); + gi.G2API_InitGhoul2Model(bomb->ghoul2, name1, bomb->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); bomb->s.radius = 50; bomb->s.eFlags |= EF_NODRAW; // Make the bombs go forward in the bombers direction a little. - vec3_t fwd, rt; - AngleVectors( self->currentAngles, fwd, rt, NULL ); + vec3_t fwd, rt; + AngleVectors(self->currentAngles, fwd, rt, NULL); rt[2] -= 0.5f; - VectorMA( bomb->s.pos.trBase, -30.0, rt, bomb->s.pos.trBase ); - VectorScale( fwd, 300, bomb->s.pos.trDelta ); - SnapVector( bomb->s.pos.trDelta ); // save net bandwidth + VectorMA(bomb->s.pos.trBase, -30.0, rt, bomb->s.pos.trBase); + VectorScale(fwd, 300, bomb->s.pos.trDelta); + SnapVector(bomb->s.pos.trDelta); // save net bandwidth // Start the effect. - G_PlayEffect( G_EffectIndex( "ships/tiebomber_bomb_falling" ), bomb->playerModel, gi.G2API_AddBolt( &bomb->ghoul2[0], "model_root" ), bomb->s.number, bomb->currentOrigin, 1000, qtrue ); + G_PlayEffect(G_EffectIndex("ships/tiebomber_bomb_falling"), bomb->playerModel, gi.G2API_AddBolt(&bomb->ghoul2[0], "model_root"), bomb->s.number, + bomb->currentOrigin, 1000, qtrue); // Set the tie bomb to have a touch function, so when it hits the ground (or whatever), there's a nice 'boom'. bomb->e_TouchFunc = touchF_TouchTieBomb; @@ -1032,79 +902,66 @@ void TieBomberThink( gentity_t *self ) } } -void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ) -{ - //G_SoundIndex( "sound/movers/objects/objectHurt.wav" ); - G_EffectIndex( "melee/kick_impact" ); - G_EffectIndex( "melee/kick_impact_silent" ); - //G_SoundIndex( "sound/weapons/melee/punch1.mp3" ); - //G_SoundIndex( "sound/weapons/melee/punch2.mp3" ); - //G_SoundIndex( "sound/weapons/melee/punch3.mp3" ); - //G_SoundIndex( "sound/weapons/melee/punch4.mp3" ); - G_SoundIndex( "sound/movers/objects/objectHit.wav" ); - G_SoundIndex( "sound/movers/objects/objectHitHeavy.wav" ); - G_SoundIndex( "sound/movers/objects/objectBreak.wav" ); - //FIXME: dust impact effect when hits ground? +void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor) { + // G_SoundIndex( "sound/movers/objects/objectHurt.wav" ); + G_EffectIndex("melee/kick_impact"); + G_EffectIndex("melee/kick_impact_silent"); + // G_SoundIndex( "sound/weapons/melee/punch1.mp3" ); + // G_SoundIndex( "sound/weapons/melee/punch2.mp3" ); + // G_SoundIndex( "sound/weapons/melee/punch3.mp3" ); + // G_SoundIndex( "sound/weapons/melee/punch4.mp3" ); + G_SoundIndex("sound/movers/objects/objectHit.wav"); + G_SoundIndex("sound/movers/objects/objectHitHeavy.wav"); + G_SoundIndex("sound/movers/objects/objectBreak.wav"); + // FIXME: dust impact effect when hits ground? ent->s.eType = ET_GENERAL; ent->s.eFlags |= EF_BOUNCE_HALF; - ent->clipmask = MASK_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//? - if ( !ent->mass ) - {//not overridden by designer - ent->mass = VectorLength( ent->maxs ) + VectorLength( ent->mins ); + ent->clipmask = MASK_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; //? + if (!ent->mass) { // not overridden by designer + ent->mass = VectorLength(ent->maxs) + VectorLength(ent->mins); } ent->physicsBounce = ent->mass; - //drop to floor - trace_t tr; - vec3_t top, bottom; + // drop to floor + trace_t tr; + vec3_t top, bottom; - if ( dropToFloor ) - { - VectorCopy( ent->currentOrigin, top ); + if (dropToFloor) { + VectorCopy(ent->currentOrigin, top); top[2] += 1; - VectorCopy( ent->currentOrigin, bottom ); + VectorCopy(ent->currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - gi.trace( &tr, top, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); - gi.linkentity( ent ); + gi.trace(&tr, top, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, (EG2_Collision)0, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); + gi.linkentity(ent); } + } else { + G_SetOrigin(ent, ent->currentOrigin); + gi.linkentity(ent); } - else - { - G_SetOrigin( ent, ent->currentOrigin ); - gi.linkentity( ent ); - } - //set up for object thinking - if ( VectorCompare( ent->s.pos.trDelta, vec3_origin ) ) - {//not moving + // set up for object thinking + if (VectorCompare(ent->s.pos.trDelta, vec3_origin)) { // not moving ent->s.pos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.pos.trType = TR_GRAVITY; } - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; - if ( VectorCompare( ent->s.apos.trDelta, vec3_origin ) ) - {//not moving + if (VectorCompare(ent->s.apos.trDelta, vec3_origin)) { // not moving ent->s.apos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.apos.trType = TR_LINEAR; } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trTime = level.time; ent->nextthink = level.time + FRAMETIME; ent->e_ThinkFunc = thinkF_G_RunObject; } -/*QUAKED misc_model_breakable (1 0 0) (-16 -16 -16) (16 16 16) SOLID AUTOANIMATE DEADSOLID NO_DMODEL NO_SMOKE USE_MODEL USE_NOT_BREAK PLAYER_USE NO_EXPLOSION START_OFF -SOLID - Movement is blocked by it, if not set, can still be broken by explosions and shots if it has health -AUTOANIMATE - Will cycle it's anim +/*QUAKED misc_model_breakable (1 0 0) (-16 -16 -16) (16 16 16) SOLID AUTOANIMATE DEADSOLID NO_DMODEL NO_SMOKE USE_MODEL USE_NOT_BREAK PLAYER_USE NO_EXPLOSION +START_OFF SOLID - Movement is blocked by it, if not set, can still be broken by explosions and shots if it has health AUTOANIMATE - Will cycle it's anim DEADSOLID - Stay solid even when destroyed (in case damage model is rather large). NO_DMODEL - Makes it NOT display a damage model when destroyed, even if one exists USE_MODEL - When used, will toggle to it's usemodel (model + "_u1.md3")... this obviously does nothing if USE_NOT_BREAK is not checked @@ -1116,21 +973,18 @@ START_OFF - Will start off and will not appear until used. "model" arbitrary .md3 file to display "modelscale" "x" uniform scale "modelscale_vec" "x y z" scale model in each axis - height, width and length - bbox will scale with it -"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block NPCs or players from moving -"targetname" when used, dies and displays damagemodel (model + "_d1.md3"), if any (if not, removes itself) -"target" What to use when it dies -"target2" What to use when it's repaired -"target3" What to use when it's used while it's broken -"paintarget" target to fire when hit (but not destroyed) +"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block +NPCs or players from moving "targetname" when used, dies and displays damagemodel (model + "_d1.md3"), if any (if not, removes itself) "target" What to use when +it dies "target2" What to use when it's repaired "target3" What to use when it's used while it's broken "paintarget" target to fire when hit (but not destroyed) "count" the amount of armor/health/ammo given (default 50) -"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks -"NPC_targetname" - Only the NPC with this name can damage this -"forcevisible" - When you turn on force sight (any level), you can see these draw through the entire level... -"redCrosshair" - crosshair turns red when you look at this +"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many +chunks, (2) is twice as many chunks "NPC_targetname" - Only the NPC with this name can damage this "forcevisible" - When you turn on force sight (any level), +you can see these draw through the entire level... "redCrosshair" - crosshair turns red when you look at this "gravity" if set to 1, this will be affected by gravity "throwtarget" if set (along with gravity), this thing, when used, will throw itself at the entity whose targetname matches this string -"mass" if gravity is on, this determines how much damage this thing does when it hits someone. Default is the size of the object from one corner to the other, that works very well. Only override if this is an object whose mass should be very high or low for it's size (density) +"mass" if gravity is on, this determines how much damage this thing does when it hits someone. Default is the size of the object from one corner to the +other, that works very well. Only override if this is an object whose mass should be very high or low for it's size (density) Damage: default is none "splashDamage" - damage to do (will make it explode on death) @@ -1159,214 +1013,195 @@ Damage: default is none 14 = MAT_CRATE2 (red multi-colored crate chunks) 15 = MAT_WHITE_METAL (white angular chunks for Stu, NS_hideout ) */ -void SP_misc_model_breakable( gentity_t *ent ) -{ - char damageModel[MAX_QPATH]; - char chunkModel[MAX_QPATH]; - char useModel[MAX_QPATH]; - int len; +void SP_misc_model_breakable(gentity_t *ent) { + char damageModel[MAX_QPATH]; + char chunkModel[MAX_QPATH]; + char useModel[MAX_QPATH]; + int len; // Chris F. requested default for misc_model_breakable to be NONE...so don't arbitrarily change this. - G_SpawnInt( "material", "8", (int*)&ent->material ); - G_SpawnFloat( "radius", "1", &ent->radius ); // used to scale chunk code if desired by a designer + G_SpawnInt("material", "8", (int *)&ent->material); + G_SpawnFloat("radius", "1", &ent->radius); // used to scale chunk code if desired by a designer qboolean bHasScale = G_SpawnVector("modelscale_vec", "0 0 0", ent->s.modelScale); - if (!bHasScale) - { + if (!bHasScale) { float temp; - G_SpawnFloat( "modelscale", "0", &temp); - if (temp != 0.0f) - { - ent->s.modelScale[ 0 ] = ent->s.modelScale[ 1 ] = ent->s.modelScale[ 2 ] = temp; + G_SpawnFloat("modelscale", "0", &temp); + if (temp != 0.0f) { + ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = temp; bHasScale = qtrue; } } - CacheChunkEffects( ent->material ); - misc_model_breakable_init( ent ); + CacheChunkEffects(ent->material); + misc_model_breakable_init(ent); - len = strlen( ent->model ) - 4; - assert(ent->model[len]=='.');//we're expecting ".md3" - strncpy( damageModel, ent->model, sizeof(damageModel) ); - damageModel[len] = 0; //chop extension - strncpy( chunkModel, damageModel, sizeof(chunkModel)); - strncpy( useModel, damageModel, sizeof(useModel)); + len = strlen(ent->model) - 4; + assert(ent->model[len] == '.'); // we're expecting ".md3" + strncpy(damageModel, ent->model, sizeof(damageModel)); + damageModel[len] = 0; // chop extension + strncpy(chunkModel, damageModel, sizeof(chunkModel)); + strncpy(useModel, damageModel, sizeof(useModel)); if (ent->takedamage) { - //Dead/damaged model - if( !(ent->spawnflags & 8) ) { //no dmodel - strcat( damageModel, "_d1.md3" ); - ent->s.modelindex2 = G_ModelIndex( damageModel ); + // Dead/damaged model + if (!(ent->spawnflags & 8)) { // no dmodel + strcat(damageModel, "_d1.md3"); + ent->s.modelindex2 = G_ModelIndex(damageModel); } - //Chunk model - strcat( chunkModel, "_c1.md3" ); - ent->s.modelindex3 = G_ModelIndex( chunkModel ); + // Chunk model + strcat(chunkModel, "_c1.md3"); + ent->s.modelindex3 = G_ModelIndex(chunkModel); } - //Use model - if( ent->spawnflags & 32 ) { //has umodel - strcat( useModel, "_u1.md3" ); - ent->sound1to2 = G_ModelIndex( useModel ); + // Use model + if (ent->spawnflags & 32) { // has umodel + strcat(useModel, "_u1.md3"); + ent->sound1to2 = G_ModelIndex(useModel); } - if ( !ent->mins[0] && !ent->mins[1] && !ent->mins[2] ) - { - VectorSet (ent->mins, -16, -16, -16); + if (!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) { + VectorSet(ent->mins, -16, -16, -16); } - if ( !ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2] ) - { - VectorSet (ent->maxs, 16, 16, 16); + if (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2]) { + VectorSet(ent->maxs, 16, 16, 16); } // Scale up the tie-bomber bbox a little. - if ( ent->model && Q_stricmp( "models/map_objects/ships/tie_bomber.md3", ent->model ) == 0 ) - { - VectorSet (ent->mins, -80, -80, -80); - VectorSet (ent->maxs, 80, 80, 80); + if (ent->model && Q_stricmp("models/map_objects/ships/tie_bomber.md3", ent->model) == 0) { + VectorSet(ent->mins, -80, -80, -80); + VectorSet(ent->maxs, 80, 80, 80); - //ent->s.modelScale[ 0 ] = ent->s.modelScale[ 1 ] = ent->s.modelScale[ 2 ] *= 2.0f; - //bHasScale = qtrue; + // ent->s.modelScale[ 0 ] = ent->s.modelScale[ 1 ] = ent->s.modelScale[ 2 ] *= 2.0f; + // bHasScale = qtrue; } - if (bHasScale) - { - //scale the x axis of the bbox up. - ent->maxs[0] *= ent->s.modelScale[0];//*scaleFactor; - ent->mins[0] *= ent->s.modelScale[0];//*scaleFactor; + if (bHasScale) { + // scale the x axis of the bbox up. + ent->maxs[0] *= ent->s.modelScale[0]; //*scaleFactor; + ent->mins[0] *= ent->s.modelScale[0]; //*scaleFactor; - //scale the y axis of the bbox up. - ent->maxs[1] *= ent->s.modelScale[1];//*scaleFactor; - ent->mins[1] *= ent->s.modelScale[1];//*scaleFactor; + // scale the y axis of the bbox up. + ent->maxs[1] *= ent->s.modelScale[1]; //*scaleFactor; + ent->mins[1] *= ent->s.modelScale[1]; //*scaleFactor; - //scale the z axis of the bbox up and adjust origin accordingly + // scale the z axis of the bbox up and adjust origin accordingly ent->maxs[2] *= ent->s.modelScale[2]; float oldMins2 = ent->mins[2]; ent->mins[2] *= ent->s.modelScale[2]; - ent->s.origin[2] += (oldMins2-ent->mins[2]); + ent->s.origin[2] += (oldMins2 - ent->mins[2]); } - if ( ent->spawnflags & 2 ) - { + if (ent->spawnflags & 2) { ent->s.eFlags |= EF_ANIM_ALLFAST; } - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + gi.linkentity(ent); - if ( ent->spawnflags & 128 ) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = (team_t)GetIDForString( TeamTable, ent->team ); - if ( ent->noDamageTeam == TEAM_FREE ) - { + if (ent->team && ent->team[0]) { + ent->noDamageTeam = (team_t)GetIDForString(TeamTable, ent->team); + if (ent->noDamageTeam == TEAM_FREE) { G_Error("team name %s not recognized\n", ent->team); } } ent->team = NULL; - //HACK - if ( ent->model && Q_stricmp( "models/map_objects/ships/x_wing_nogear.md3", ent->model ) == 0 ) - { - if( ent->splashDamage > 0 && ent->splashRadius > 0 ) - { - ent->s.loopSound = G_SoundIndex( "sound/vehicles/x-wing/loop.wav" ); + // HACK + if (ent->model && Q_stricmp("models/map_objects/ships/x_wing_nogear.md3", ent->model) == 0) { + if (ent->splashDamage > 0 && ent->splashRadius > 0) { + ent->s.loopSound = G_SoundIndex("sound/vehicles/x-wing/loop.wav"); ent->s.eFlags |= EF_LESS_ATTEN; } - } - else if ( ent->model && Q_stricmp( "models/map_objects/ships/tie_fighter.md3", ent->model ) == 0 ) - {//run a think - G_EffectIndex( "explosions/fighter_explosion2" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass1.wav" ); -/* G_SoundIndex( "sound/weapons/tie_fighter/tiepass2.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass3.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass4.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass5.wav" );*/ - G_SoundIndex( "sound/weapons/tie_fighter/tie_fire.wav" ); -/* G_SoundIndex( "sound/weapons/tie_fighter/tie_fire2.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tie_fire3.wav" );*/ - G_SoundIndex( "sound/weapons/tie_fighter/TIEexplode.wav" ); - RegisterItem( FindItemForWeapon( WP_TIE_FIGHTER )); + } else if (ent->model && Q_stricmp("models/map_objects/ships/tie_fighter.md3", ent->model) == 0) { // run a think + G_EffectIndex("explosions/fighter_explosion2"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass1.wav"); + /* G_SoundIndex( "sound/weapons/tie_fighter/tiepass2.wav" ); + G_SoundIndex( "sound/weapons/tie_fighter/tiepass3.wav" ); + G_SoundIndex( "sound/weapons/tie_fighter/tiepass4.wav" ); + G_SoundIndex( "sound/weapons/tie_fighter/tiepass5.wav" );*/ + G_SoundIndex("sound/weapons/tie_fighter/tie_fire.wav"); + /* G_SoundIndex( "sound/weapons/tie_fighter/tie_fire2.wav" ); + G_SoundIndex( "sound/weapons/tie_fighter/tie_fire3.wav" );*/ + G_SoundIndex("sound/weapons/tie_fighter/TIEexplode.wav"); + RegisterItem(FindItemForWeapon(WP_TIE_FIGHTER)); ent->s.eFlags |= EF_LESS_ATTEN; - if( ent->splashDamage > 0 && ent->splashRadius > 0 ) - { - ent->s.loopSound = G_SoundIndex( "sound/vehicles/tie-bomber/loop.wav" ); - //ent->e_ThinkFunc = thinkF_TieFighterThink; - //ent->e_UseFunc = thinkF_TieFighterThink; - //ent->nextthink = level.time + FRAMETIME; + if (ent->splashDamage > 0 && ent->splashRadius > 0) { + ent->s.loopSound = G_SoundIndex("sound/vehicles/tie-bomber/loop.wav"); + // ent->e_ThinkFunc = thinkF_TieFighterThink; + // ent->e_UseFunc = thinkF_TieFighterThink; + // ent->nextthink = level.time + FRAMETIME; ent->e_UseFunc = useF_TieFighterUse; // Yeah, I could have just made this value changable from the editor, but I // need it immediately! - float light; - vec3_t color; - qboolean lightSet, colorSet; + float light; + vec3_t color; + qboolean lightSet, colorSet; // if the "color" or "light" keys are set, setup constantLight - lightSet = qtrue;//G_SpawnFloat( "light", "100", &light ); + lightSet = qtrue; // G_SpawnFloat( "light", "100", &light ); light = 255; - //colorSet = "1 1 1"//G_SpawnVector( "color", "1 1 1", color ); + // colorSet = "1 1 1"//G_SpawnVector( "color", "1 1 1", color ); colorSet = qtrue; - color[0] = 1; color[1] = 1; color[2] = 1; - if ( lightSet || colorSet ) - { - int r, g, b, i; + color[0] = 1; + color[1] = 1; + color[2] = 1; + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } } - } - else if ( ent->model && Q_stricmp( "models/map_objects/ships/tie_bomber.md3", ent->model ) == 0 ) - { - G_EffectIndex( "ships/tiebomber_bomb_falling" ); - G_EffectIndex( "ships/tiebomber_explosion2" ); - G_EffectIndex( "explosions/fighter_explosion2" ); - G_SoundIndex( "sound/weapons/tie_fighter/TIEexplode.wav" ); + } else if (ent->model && Q_stricmp("models/map_objects/ships/tie_bomber.md3", ent->model) == 0) { + G_EffectIndex("ships/tiebomber_bomb_falling"); + G_EffectIndex("ships/tiebomber_explosion2"); + G_EffectIndex("explosions/fighter_explosion2"); + G_SoundIndex("sound/weapons/tie_fighter/TIEexplode.wav"); ent->e_ThinkFunc = thinkF_TieBomberThink; ent->nextthink = level.time + FRAMETIME; ent->attackDebounceTime = level.time + 1000; // We only take damage from a heavy weapon class missiles. ent->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; - ent->s.loopSound = G_SoundIndex( "sound/vehicles/tie-bomber/loop.wav" ); + ent->s.loopSound = G_SoundIndex("sound/vehicles/tie-bomber/loop.wav"); ent->s.eFlags |= EF_LESS_ATTEN; } float grav = 0; - G_SpawnFloat( "gravity", "0", &grav ); - if ( grav ) - {//affected by gravity - G_SetAngles( ent, ent->s.angles ); - G_SetOrigin( ent, ent->currentOrigin ); - G_SpawnString( "throwtarget", NULL, &ent->target4 ); // used to throw itself at something - misc_model_breakable_gravity_init( ent, qtrue ); + G_SpawnFloat("gravity", "0", &grav); + if (grav) { // affected by gravity + G_SetAngles(ent, ent->s.angles); + G_SetOrigin(ent, ent->currentOrigin); + G_SpawnString("throwtarget", NULL, &ent->target4); // used to throw itself at something + misc_model_breakable_gravity_init(ent, qtrue); } // Start off. - if ( ent->spawnflags & 4096 ) - { - ent->spawnContents = ent->contents; // It Navs can temporarly turn it "on" + if (ent->spawnflags & 4096) { + ent->spawnContents = ent->contents; // It Navs can temporarly turn it "on" ent->s.solid = 0; ent->contents = 0; ent->clipmask = 0; @@ -1376,22 +1211,19 @@ void SP_misc_model_breakable( gentity_t *ent ) } int forceVisible = 0; - G_SpawnInt( "forcevisible", "0", &forceVisible ); - if ( forceVisible ) - {//can see these through walls with force sight, so must be broadcast - //ent->svFlags |= SVF_BROADCAST; + G_SpawnInt("forcevisible", "0", &forceVisible); + if (forceVisible) { // can see these through walls with force sight, so must be broadcast + // ent->svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_FORCE_VISIBLE; } int redCrosshair = 0; - G_SpawnInt( "redCrosshair", "0", &redCrosshair ); - if ( redCrosshair ) - {//can see these through walls with force sight, so must be broadcast + G_SpawnInt("redCrosshair", "0", &redCrosshair); + if (redCrosshair) { // can see these through walls with force sight, so must be broadcast ent->flags |= FL_RED_CROSSHAIR; } } - //---------------------------------- // // Breaking Glass Technology @@ -1399,72 +1231,67 @@ void SP_misc_model_breakable( gentity_t *ent ) //---------------------------------- // Really naughty cheating. Put in an EVENT at some point... -extern void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal ); -extern void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius ); -extern cgs_t cgs; +extern void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal); +extern void CG_DoGlass(vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius); +extern cgs_t cgs; //----------------------------------------------------- -void funcGlassDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ - vec3_t verts[4], normal; +void funcGlassDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + vec3_t verts[4], normal; // if a missile is stuck to us, blow it up so we don't look dumb....we could, alternately, just let the missile drop off?? - for ( int i = 0; i < MAX_GENTITIES; i++ ) - { - if ( g_entities[i].s.groundEntityNum == self->s.number && ( g_entities[i].s.eFlags & EF_MISSILE_STICK )) - { - G_Damage( &g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH ); //?? MOD? + for (int i = 0; i < MAX_GENTITIES; i++) { + if (g_entities[i].s.groundEntityNum == self->s.number && (g_entities[i].s.eFlags & EF_MISSILE_STICK)) { + G_Damage(&g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH); //?? MOD? } } // Really naughty cheating. Put in an EVENT at some point... - cgi_R_GetBModelVerts( cgs.inlineDrawModel[self->s.modelindex], verts, normal ); - CG_DoGlass( verts, normal, self->pos1, self->pos2, self->splashRadius ); + cgi_R_GetBModelVerts(cgs.inlineDrawModel[self->s.modelindex], verts, normal); + CG_DoGlass(verts, normal, self->pos1, self->pos2, self->splashRadius); - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops - G_SetEnemy( self, self->enemy ); + G_SetEnemy(self, self->enemy); - //NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! - gi.AdjustAreaPortalState( self, qtrue ); + // NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! + gi.AdjustAreaPortalState(self, qtrue); - //So chunks don't get stuck inside me + // So chunks don't get stuck inside me self->s.solid = 0; self->contents = 0; self->clipmask = 0; gi.linkentity(self); - if ( self->target && attacker != NULL ) - { - G_UseTargets( self, attacker ); + if (self->target && attacker != NULL) { + G_UseTargets(self, attacker); } - G_FreeEntity( self ); + G_FreeEntity(self); } //----------------------------------------------------- -void funcGlassUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void funcGlassUse(gentity_t *self, gentity_t *other, gentity_t *activator) { vec3_t temp1, temp2; // For now, we just break on use - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - VectorAdd( self->mins, self->maxs, temp1 ); - VectorScale( temp1, 0.5f, temp1 ); + VectorAdd(self->mins, self->maxs, temp1); + VectorScale(temp1, 0.5f, temp1); - VectorAdd( other->mins, other->maxs, temp2 ); - VectorScale( temp2, 0.5f, temp2 ); + VectorAdd(other->mins, other->maxs, temp2); + VectorScale(temp2, 0.5f, temp2); - VectorSubtract( temp1, temp2, self->pos2 ); - VectorCopy( temp1, self->pos1 ); + VectorSubtract(temp1, temp2, self->pos2); + VectorCopy(temp1, self->pos1); - VectorNormalize( self->pos2 ); - VectorScale( self->pos2, 390, self->pos2 ); + VectorNormalize(self->pos2); + VectorScale(self->pos2, 390, self->pos2); self->splashRadius = 40; // ?? some random number, maybe it's ok? - funcGlassDie( self, other, activator, self->health, MOD_UNKNOWN ); + funcGlassDie(self, other, activator, self->health, MOD_UNKNOWN); } //----------------------------------------------------- @@ -1479,78 +1306,63 @@ INVINCIBLE - can only be broken by being used "health" default is 1 */ //----------------------------------------------------- -void SP_func_glass( gentity_t *self ) -{ - if ( !(self->spawnflags & 1 )) - { - if ( !self->health ) - { +void SP_func_glass(gentity_t *self) { + if (!(self->spawnflags & 1)) { + if (!self->health) { self->health = 1; } } - if ( self->health ) - { + if (self->health) { self->takedamage = qtrue; } self->e_UseFunc = useF_funcGlassUse; self->e_DieFunc = dieF_funcGlassDie; - VectorCopy( self->s.origin, self->pos1 ); + VectorCopy(self->s.origin, self->pos1); - gi.SetBrushModel( self, self->model ); - self->svFlags |= (SVF_GLASS_BRUSH|SVF_BBRUSH); + gi.SetBrushModel(self, self->model); + self->svFlags |= (SVF_GLASS_BRUSH | SVF_BBRUSH); self->material = MAT_GLASS; self->s.eType = ET_MOVER; self->s.pos.trType = TR_STATIONARY; - VectorCopy( self->pos1, self->s.pos.trBase ); + VectorCopy(self->pos1, self->s.pos.trBase); - G_SoundIndex( "sound/effects/glassbreak1.wav" ); - G_EffectIndex( "misc/glass_impact" ); + G_SoundIndex("sound/effects/glassbreak1.wav"); + G_EffectIndex("misc/glass_impact"); - gi.linkentity( self ); + gi.linkentity(self); } -qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ) -{//breakable brush/model that can actually be broken - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker) { // breakable brush/model that can actually be broken + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } gentity_t *ent = &g_entities[entityNum]; - if ( !ent->takedamage ) - { + if (!ent->takedamage) { return qfalse; } - if ( ent->NPC_targetname ) - {//only a specific entity can break this! - if ( !breaker - || !breaker->targetname - || Q_stricmp( ent->NPC_targetname, breaker->targetname ) != 0 ) - {//I'm not the one who can break it + if (ent->NPC_targetname) { // only a specific entity can break this! + if (!breaker || !breaker->targetname || Q_stricmp(ent->NPC_targetname, breaker->targetname) != 0) { // I'm not the one who can break it return qfalse; } } - if ( (ent->svFlags&SVF_GLASS_BRUSH) ) - { + if ((ent->svFlags & SVF_GLASS_BRUSH)) { return qtrue; } - if ( (ent->svFlags&SVF_BBRUSH) ) - { + if ((ent->svFlags & SVF_BBRUSH)) { return qtrue; } - if ( !Q_stricmp( "misc_model_breakable", ent->classname ) ) - { + if (!Q_stricmp("misc_model_breakable", ent->classname)) { return qtrue; } - if ( !Q_stricmp( "misc_maglock", ent->classname ) ) - { + if (!Q_stricmp("misc_maglock", ent->classname)) { return qtrue; } diff --git a/code/game/g_camera.cpp b/code/game/g_camera.cpp index 5bbacfa6da..c6c36fa0c4 100644 --- a/code/game/g_camera.cpp +++ b/code/game/g_camera.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//g_camera.cpp +// g_camera.cpp #include "g_local.h" #include "../cgame/cg_camera.h" #include "g_functions.h" @@ -65,11 +65,9 @@ The focal point for a camera in a scene "speed" angular speed modifier - 100 is normal */ -void SP_misc_camera_focus (gentity_t *self) -{ - if(!self->targetname) - { - gi.Printf(S_COLOR_RED"ERROR: misc_camera_focus with no targetname\n"); +void SP_misc_camera_focus(gentity_t *self) { + if (!self->targetname) { + gi.Printf(S_COLOR_RED "ERROR: misc_camera_focus with no targetname\n"); G_FreeEntity(self); return; } @@ -86,7 +84,7 @@ void SP_misc_camera_focus (gentity_t *self) */ self->speed = 0; self->script_targetname = G_NewString(self->targetname); -// self->e_UseFunc = useF_misc_camera_focus_use; + // self->e_UseFunc = useF_misc_camera_focus_use; } /* @@ -181,66 +179,59 @@ use "path_corner"s - path it should stay on- if that path_corner has a speed val "radius" - How far camera should try to stay from it's subject, default is 0 (dist doesn't matter), can pick this up from a path_corner too */ -void SP_misc_camera_track (gentity_t *self) -{ - if(!self->targetname || !self->targetname[0]) - { - gi.Printf(S_COLOR_RED"ERROR: misc_camera_track with no targetname\n"); +void SP_misc_camera_track(gentity_t *self) { + if (!self->targetname || !self->targetname[0]) { + gi.Printf(S_COLOR_RED "ERROR: misc_camera_track with no targetname\n"); G_FreeEntity(self); return; } self->script_targetname = G_NewString(self->targetname); - //self->moveInfo.speed = self->speed/10; + // self->moveInfo.speed = self->speed/10; -// self->e_UseFunc = useF_misc_camera_track_use; + // self->e_UseFunc = useF_misc_camera_track_use; } - //------------------------------------------------- // Bezier camera stuff //------------------------------------------------- -void cam_point_link( gentity_t *ent ) -{ +void cam_point_link(gentity_t *ent) {} -} +void cam_ctrl_point_link(gentity_t *ent) { + /* gentity_t *target2 = NULL; -void cam_ctrl_point_link( gentity_t *ent ) -{ -/* gentity_t *target2 = NULL; + target2 = G_Find( NULL, FOFS(targetname), ent->target2 ); - target2 = G_Find( NULL, FOFS(targetname), ent->target2 ); + if ( !target2 ) + { + // Bah, you fool! Target2 not found + Com_Printf( "cam_point_link: target2 specified but not found: %s\n", ent->target2 ); + G_FreeEntity( ent ); + return; + } - if ( !target2 ) - { - // Bah, you fool! Target2 not found - Com_Printf( "cam_point_link: target2 specified but not found: %s\n", ent->target2 ); - G_FreeEntity( ent ); - return; - } + // Store the control point here + VectorCopy( target2->s.origin, ent->pos1 ); - // Store the control point here - VectorCopy( target2->s.origin, ent->pos1 ); + //--------------------- + if ( ent->target ) + { + gentity_t *target = NULL; - //--------------------- - if ( ent->target ) - { - gentity_t *target = NULL; + target = G_Find( NULL, FOFS(targetname), ent->target ); - target = G_Find( NULL, FOFS(targetname), ent->target ); + if ( !target ) + { + // Bah, you fool! Target not found + Com_Printf( "cam_point_link: target specified but not found: %s\n", ent->target ); + G_FreeEntity( ent ); + return; + } - if ( !target ) - { - // Bah, you fool! Target not found - Com_Printf( "cam_point_link: target specified but not found: %s\n", ent->target ); - G_FreeEntity( ent ); - return; + ent->nextTrain = target; } - - ent->nextTrain = target; - } -*/ + */ } /*QUAK-ED cam_point (0.25 0 0.5) (-2 -2 -2) (2 2 2) @@ -249,23 +240,22 @@ A camera point used to construct a camera bezier path Every cam_point MUST be targeted (target2) at one and only one control point */ -void SP_cam_point( gentity_t *ent ) -{ -/* if ( !ent->target2 ) - { - // Bah, you fool! Target2 not found so we have no idea how to make the curve - Com_Printf( "cam_point_link: target2 was required but not found\n" ); - G_FreeEntity( ent ); - return; +void SP_cam_point(gentity_t *ent) { + /* if ( !ent->target2 ) + { + // Bah, you fool! Target2 not found so we have no idea how to make the curve + Com_Printf( "cam_point_link: target2 was required but not found\n" ); + G_FreeEntity( ent ); + return; - } + } - // The thing we are targeting may not be spawned in yet so, wait a bit to try and link to it - ent->e_ThinkFunc = thinkF_cam_ctrl_point_link; - ent->nextthink = level.time + 200; + // The thing we are targeting may not be spawned in yet so, wait a bit to try and link to it + ent->e_ThinkFunc = thinkF_cam_ctrl_point_link; + ent->nextthink = level.time + 200; - // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); - gi.linkentity( ent ); -*/ + // Save our position and link us up! + G_SetOrigin( ent, ent->s.origin ); + gi.linkentity( ent ); + */ } \ No newline at end of file diff --git a/code/game/g_client.cpp b/code/game/g_client.cpp index 053a8f10d9..d71771295d 100644 --- a/code/game/g_client.cpp +++ b/code/game/g_client.cpp @@ -32,23 +32,23 @@ along with this program; if not, see . #include "objectives.h" #include "b_local.h" -extern int WP_SaberInitBladeData( gentity_t *ent ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); -extern qboolean CheatsOk( gentity_t *ent ); -extern void Boba_Precache( void ); - -extern cvar_t *g_char_model; -extern cvar_t *g_char_skin_head; -extern cvar_t *g_char_skin_torso; -extern cvar_t *g_char_skin_legs; -extern cvar_t *g_char_color_red; -extern cvar_t *g_char_color_green; -extern cvar_t *g_char_color_blue; -extern cvar_t *g_saber; -extern cvar_t *g_saber2; -extern cvar_t *g_saber_color; -extern cvar_t *g_saber2_color; -extern cvar_t *g_saberDarkSideSaberColor; +extern int WP_SaberInitBladeData(gentity_t *ent); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); +extern qboolean CheatsOk(gentity_t *ent); +extern void Boba_Precache(void); + +extern cvar_t *g_char_model; +extern cvar_t *g_char_skin_head; +extern cvar_t *g_char_skin_torso; +extern cvar_t *g_char_skin_legs; +extern cvar_t *g_char_color_red; +extern cvar_t *g_char_color_green; +extern cvar_t *g_char_color_blue; +extern cvar_t *g_saber; +extern cvar_t *g_saber2; +extern cvar_t *g_saber_color; +extern cvar_t *g_saber2_color; +extern cvar_t *g_saberDarkSideSaberColor; // g_client.c -- client functions that don't happen every frame @@ -56,33 +56,35 @@ float DEFAULT_MINS_0 = -16; float DEFAULT_MINS_1 = -16; float DEFAULT_MAXS_0 = 16; float DEFAULT_MAXS_1 = 16; -float DEFAULT_PLAYER_RADIUS = sqrt((DEFAULT_MAXS_0*DEFAULT_MAXS_0) + (DEFAULT_MAXS_1*DEFAULT_MAXS_1)); +float DEFAULT_PLAYER_RADIUS = sqrt((DEFAULT_MAXS_0 * DEFAULT_MAXS_0) + (DEFAULT_MAXS_1 * DEFAULT_MAXS_1)); vec3_t playerMins = {DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2}; -vec3_t playerMinsStep = {DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2+STEPSIZE}; +vec3_t playerMinsStep = {DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE}; vec3_t playerMaxs = {DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2}; -void SP_misc_teleporter_dest (gentity_t *ent); +void SP_misc_teleporter_dest(gentity_t *ent); /*QUAK-ED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) KEEP_PREV DROPTOFLOOR x x x STUN_BATON NOWEAPON x potential spawning position for deathmatch games. Targets will be fired when someone spawns in on them. */ void SP_info_player_deathmatch(gentity_t *ent) { - SP_misc_teleporter_dest (ent); + SP_misc_teleporter_dest(ent); - if ( ent->spawnflags & 32 ) // STUN_BATON + if (ent->spawnflags & 32) // STUN_BATON { - RegisterItem( FindItemForWeapon( WP_STUN_BATON )); - } - else - { - RegisterItem( FindItemForWeapon( WP_SABER ) ); //these are given in ClientSpawn(), but we register them now before cgame starts - saberInfo_t saber; - WP_SaberParseParms( g_saber->string, &saber );//get saber sounds and models cached before client begins - if (saber.model) G_ModelIndex( saber.model ); - if (saber.brokenSaber1) G_ModelIndex( saber.brokenSaber1 ); - if (saber.brokenSaber2) G_ModelIndex( saber.brokenSaber2 ); - if (saber.skin) G_SkinIndex( saber.skin ); + RegisterItem(FindItemForWeapon(WP_STUN_BATON)); + } else { + RegisterItem(FindItemForWeapon(WP_SABER)); // these are given in ClientSpawn(), but we register them now before cgame starts + saberInfo_t saber; + WP_SaberParseParms(g_saber->string, &saber); // get saber sounds and models cached before client begins + if (saber.model) + G_ModelIndex(saber.model); + if (saber.brokenSaber1) + G_ModelIndex(saber.brokenSaber1); + if (saber.brokenSaber2) + G_ModelIndex(saber.brokenSaber2); + if (saber.skin) + G_SkinIndex(saber.skin); WP_SaberFreeStrings(saber); } } @@ -98,11 +100,9 @@ equivalant to info_player_deathmatch void SP_info_player_start(gentity_t *ent) { ent->classname = "info_player_deathmatch"; - SP_info_player_deathmatch( ent ); + SP_info_player_deathmatch(ent); } - - /* ======================================================================= @@ -117,35 +117,30 @@ SpotWouldTelefrag ================ */ -qboolean SpotWouldTelefrag( gentity_t *spot, team_t checkteam ) -{ - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag(gentity_t *spot, team_t checkteam) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; // If we have a mins, use that instead of the hardcoded bounding box - if ( !VectorCompare(spot->mins, vec3_origin) && VectorLength( spot->mins ) ) - VectorAdd( spot->s.origin, spot->mins, mins ); + if (!VectorCompare(spot->mins, vec3_origin) && VectorLength(spot->mins)) + VectorAdd(spot->s.origin, spot->mins, mins); else - VectorAdd( spot->s.origin, playerMins, mins ); + VectorAdd(spot->s.origin, playerMins, mins); // If we have a maxs, use that instead of the hardcoded bounding box - if ( !VectorCompare(spot->maxs, vec3_origin) && VectorLength( spot->maxs ) ) - VectorAdd( spot->s.origin, spot->maxs, maxs ); + if (!VectorCompare(spot->maxs, vec3_origin) && VectorLength(spot->maxs)) + VectorAdd(spot->s.origin, spot->maxs, maxs); else - VectorAdd( spot->s.origin, playerMaxs, maxs ); + VectorAdd(spot->s.origin, playerMaxs, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient && hit->client->ps.stats[STAT_HEALTH] > 0 ) - { - if ( hit->contents & CONTENTS_BODY ) - { - if( checkteam == TEAM_FREE || hit->client->playerTeam == checkteam ) - {//checking against teammates only...? + if (hit != spot && hit->client && hit->client->ps.stats[STAT_HEALTH] > 0) { + if (hit->contents & CONTENTS_BODY) { + if (checkteam == TEAM_FREE || hit->client->playerTeam == checkteam) { // checking against teammates only...? return qtrue; } } @@ -155,26 +150,22 @@ qboolean SpotWouldTelefrag( gentity_t *spot, team_t checkteam ) return qfalse; } -qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ) -{ - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; - VectorAdd( dest, mover->mins, mins ); - VectorAdd( dest, mover->maxs, maxs ); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(dest, mover->mins, mins); + VectorAdd(dest, mover->maxs, maxs); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; icontents & mover->contents ) - { + if (hit->contents & mover->contents) { return qtrue; } } @@ -188,17 +179,17 @@ SelectNearestDeathmatchSpawnPoint Find the spot that we DON'T want to use ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { - gentity_t *spot; - float dist, nearestDist; - gentity_t *nearestSpot; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectNearestDeathmatchSpawnPoint(vec3_t from, team_t team) { + gentity_t *spot; + float dist, nearestDist; + gentity_t *nearestSpot; - nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; + nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; nearestSpot = NULL; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { /*if ( team == TEAM_RED && ( spot->spawnflags & 2 ) ) { continue; } @@ -206,12 +197,12 @@ gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { continue; }*/ - if ( spot->targetname != NULL ) { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted continue; } - dist = DistanceSquared( spot->s.origin, from ); - if ( dist < nearestDist ) { + dist = DistanceSquared(spot->s.origin, from); + if (dist < nearestDist) { nearestDist = dist; nearestSpot = spot; } @@ -220,7 +211,6 @@ gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { return nearestSpot; } - /* ================ SelectRandomDeathmatchSpawnPoint @@ -228,17 +218,17 @@ SelectRandomDeathmatchSpawnPoint go to a random point that doesn't telefrag ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectRandomDeathmatchSpawnPoint( team_t team ) { - gentity_t *spot; - int count; - int selection; - gentity_t *spots[MAX_SPAWN_POINTS]; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectRandomDeathmatchSpawnPoint(team_t team) { + gentity_t *spot; + int count; + int selection; + gentity_t *spots[MAX_SPAWN_POINTS]; count = 0; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { /*if ( team == TEAM_RED && ( spot->spawnflags & 2 ) ) { continue; } @@ -246,39 +236,34 @@ gentity_t *SelectRandomDeathmatchSpawnPoint( team_t team ) { continue; }*/ - if ( spot->targetname != NULL ) { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted continue; } - if ( SpotWouldTelefrag( spot, TEAM_FREE ) ) { + if (SpotWouldTelefrag(spot, TEAM_FREE)) { continue; } - spots[ count ] = spot; + spots[count] = spot; count++; } - if ( !count ) { // no spots that won't telefrag - spot = G_Find( NULL, FOFS(classname), "info_player_deathmatch"); - if ( !spot ) - { + if (!count) { // no spots that won't telefrag + spot = G_Find(NULL, FOFS(classname), "info_player_deathmatch"); + if (!spot) { return NULL; } - if ( spot->targetname != NULL ) - { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted return NULL; - } - else - { + } else { return spot; } } selection = rand() % count; - return spots[ selection ]; + return spots[selection]; } - /* =========== SelectSpawnPoint @@ -286,78 +271,66 @@ SelectSpawnPoint Chooses a player start, deathmatch start, etc ============ */ -gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, team_t team, vec3_t origin, vec3_t angles ) { - gentity_t *spot; - gentity_t *nearestSpot; - - if ( level.spawntarget[0] ) - {//we have a spawnpoint specified, try to find it - if ( (nearestSpot = spot = G_Find( NULL, FOFS(targetname), level.spawntarget )) == NULL ) - {//you HAVE to be able to find the desired spot - G_Error( "Couldn't find spawntarget %s\n", level.spawntarget ); +gentity_t *SelectSpawnPoint(vec3_t avoidPoint, team_t team, vec3_t origin, vec3_t angles) { + gentity_t *spot; + gentity_t *nearestSpot; + + if (level.spawntarget[0]) { // we have a spawnpoint specified, try to find it + if ((nearestSpot = spot = G_Find(NULL, FOFS(targetname), level.spawntarget)) == NULL) { // you HAVE to be able to find the desired spot + G_Error("Couldn't find spawntarget %s\n", level.spawntarget); return NULL; } - } - else - {//not looking for a special startspot - nearestSpot = SelectNearestDeathmatchSpawnPoint( avoidPoint, team ); + } else { // not looking for a special startspot + nearestSpot = SelectNearestDeathmatchSpawnPoint(avoidPoint, team); - spot = SelectRandomDeathmatchSpawnPoint ( team ); - if ( spot == nearestSpot ) { + spot = SelectRandomDeathmatchSpawnPoint(team); + if (spot == nearestSpot) { // roll again if it would be real close to point of death - spot = SelectRandomDeathmatchSpawnPoint ( team ); + spot = SelectRandomDeathmatchSpawnPoint(team); } } // find a single player start spot if (!spot) { - G_Error( "Couldn't find a spawn point\n" ); + G_Error("Couldn't find a spawn point\n"); } - - VectorCopy( spot->s.origin, origin ); - if ( spot->spawnflags & 2 ) - { - trace_t tr; + VectorCopy(spot->s.origin, origin); + if (spot->spawnflags & 2) { + trace_t tr; origin[2] = MIN_WORLD_COORD; - gi.trace(&tr, spot->s.origin, playerMins, playerMaxs, origin, ENTITYNUM_NONE, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); - if ( tr.fraction < 1.0 && !tr.allsolid && !tr.startsolid ) - {//found a floor - VectorCopy(tr.endpos, origin ); - } - else - {//In solid or too far - VectorCopy( spot->s.origin, origin ); + gi.trace(&tr, spot->s.origin, playerMins, playerMaxs, origin, ENTITYNUM_NONE, MASK_PLAYERSOLID, (EG2_Collision)0, 0); + if (tr.fraction < 1.0 && !tr.allsolid && !tr.startsolid) { // found a floor + VectorCopy(tr.endpos, origin); + } else { // In solid or too far + VectorCopy(spot->s.origin, origin); } } origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } - //====================================================================== - /* ================== SetClientViewAngle ================== */ -void SetClientViewAngle( gentity_t *ent, vec3_t angle ) { - int i; +void SetClientViewAngle(gentity_t *ent, vec3_t angle) { + int i; // set the delta angle - for (i=0 ; i<3 ; i++) - { - ent->client->ps.delta_angles[i] = (ANGLE2SHORT(angle[i]) - ent->client->pers.cmd_angles[i])&0xffff; + for (i = 0; i < 3; i++) { + ent->client->ps.delta_angles[i] = (ANGLE2SHORT(angle[i]) - ent->client->pers.cmd_angles[i]) & 0xffff; } - VectorCopy( angle, ent->s.angles ); - VectorCopy (ent->s.angles, ent->client->ps.viewangles); + VectorCopy(angle, ent->s.angles); + VectorCopy(ent->s.angles, ent->client->ps.viewangles); } /* @@ -365,9 +338,9 @@ void SetClientViewAngle( gentity_t *ent, vec3_t angle ) { respawn ================ */ -void respawn( gentity_t *ent ) { +void respawn(gentity_t *ent) { - gi.SendConsoleCommand("load *respawn\n"); // special case + gi.SendConsoleCommand("load *respawn\n"); // special case } /* @@ -375,39 +348,32 @@ void respawn( gentity_t *ent ) { ClientCheckName ============ */ -static void ClientCleanName( const char *in, char *out, int outSize ) -{ +static void ClientCleanName(const char *in, char *out, int outSize) { int outpos = 0, colorlessLen = 0, spaces = 0, ats = 0; // discard leading spaces - for ( ; *in == ' '; in++); + for (; *in == ' '; in++) + ; // discard leading asterisk's (fail raven for using * as a skipnotify) // apparently .* causes the issue too so... derp - //for(; *in == '*'; in++); + // for(; *in == '*'; in++); - for(; *in && outpos < outSize - 1; in++) - { + for (; *in && outpos < outSize - 1; in++) { out[outpos] = *in; - if ( *in == ' ' ) - {// don't allow too many consecutive spaces - if ( spaces > 2 ) + if (*in == ' ') { // don't allow too many consecutive spaces + if (spaces > 2) continue; spaces++; - } - else if ( *in == '@' ) - {// don't allow too many consecutive at signs - if ( ats > 2 ) + } else if (*in == '@') { // don't allow too many consecutive at signs + if (ats > 2) continue; ats++; - } - else if ( outpos > 0 && out[outpos-1] == Q_COLOR_ESCAPE ) - { - if ( Q_IsColorStringExt( &out[outpos-1] ) ) - { + } else if (outpos > 0 && out[outpos - 1] == Q_COLOR_ESCAPE) { + if (Q_IsColorStringExt(&out[outpos - 1])) { colorlessLen--; #if 0 @@ -417,15 +383,11 @@ static void ClientCleanName( const char *in, char *out, int outSize ) continue; } #endif - } - else - { + } else { spaces = ats = 0; colorlessLen++; } - } - else - { + } else { spaces = ats = 0; colorlessLen++; } @@ -436,8 +398,8 @@ static void ClientCleanName( const char *in, char *out, int outSize ) out[outpos] = '\0'; // don't allow empty names - if ( *out == '\0' || colorlessLen == 0 ) - Q_strncpyz( out, "Padawan", outSize ); + if (*out == '\0' || colorlessLen == 0) + Q_strncpyz(out, "Padawan", outSize); } /* @@ -451,15 +413,14 @@ The game can override any of the settings and call gi.SetUserinfo if desired. ============ */ -void ClientUserinfoChanged( int clientNum ) { - gentity_t *ent = g_entities + clientNum; - gclient_t *client = ent->client; - int health=100, maxHealth=100; - const char *s=NULL; - char userinfo[MAX_INFO_STRING]={0}, buf[MAX_INFO_STRING]={0}, - sound[MAX_STRING_CHARS]={0}, oldname[34]={0}; +void ClientUserinfoChanged(int clientNum) { + gentity_t *ent = g_entities + clientNum; + gclient_t *client = ent->client; + int health = 100, maxHealth = 100; + const char *s = NULL; + char userinfo[MAX_INFO_STRING] = {0}, buf[MAX_INFO_STRING] = {0}, sound[MAX_STRING_CHARS] = {0}, oldname[34] = {0}; - gi.GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + gi.GetUserinfo(clientNum, userinfo, sizeof(userinfo)); // check for malformed or illegal info strings /*if ( !Info_Validate(userinfo) ) { @@ -467,36 +428,35 @@ void ClientUserinfoChanged( int clientNum ) { }*/ // set name - Q_strncpyz ( oldname, client->pers.netname, sizeof( oldname ) ); - s = Info_ValueForKey (userinfo, "name"); - ClientCleanName( s, client->pers.netname, sizeof( client->pers.netname ) ); + Q_strncpyz(oldname, client->pers.netname, sizeof(oldname)); + s = Info_ValueForKey(userinfo, "name"); + ClientCleanName(s, client->pers.netname, sizeof(client->pers.netname)); // set max health maxHealth = 100; - health = Com_Clampi( 1, 100, atoi( Info_ValueForKey( userinfo, "handicap" ) ) ); + health = Com_Clampi(1, 100, atoi(Info_ValueForKey(userinfo, "handicap"))); client->pers.maxHealth = health; - if ( client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth ) + if (client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth) client->pers.maxHealth = 100; client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth; // sounds - Q_strncpyz( sound, Info_ValueForKey (userinfo, "snd"), sizeof( sound ) ); + Q_strncpyz(sound, Info_ValueForKey(userinfo, "snd"), sizeof(sound)); // send over a subset of the userinfo keys so other clients can // print scoreboards, display models, and play custom sounds buf[0] = '\0'; - Q_strcat( buf, sizeof( buf ), va( "n\\%s\\", client->pers.netname ) ); - Q_strcat( buf, sizeof( buf ), va( "t\\%i\\", client->sess.sessionTeam ) ); - Q_strcat( buf, sizeof( buf ), "headModel\\\\" ); - Q_strcat( buf, sizeof( buf ), "torsoModel\\\\" ); - Q_strcat( buf, sizeof( buf ), "legsModel\\\\" ); - Q_strcat( buf, sizeof( buf ), va( "hc\\%i\\", client->pers.maxHealth ) ); - Q_strcat( buf, sizeof( buf ), va( "snd\\%s\\", sound ) ); - - gi.SetConfigstring( CS_PLAYERS+clientNum, buf ); + Q_strcat(buf, sizeof(buf), va("n\\%s\\", client->pers.netname)); + Q_strcat(buf, sizeof(buf), va("t\\%i\\", client->sess.sessionTeam)); + Q_strcat(buf, sizeof(buf), "headModel\\\\"); + Q_strcat(buf, sizeof(buf), "torsoModel\\\\"); + Q_strcat(buf, sizeof(buf), "legsModel\\\\"); + Q_strcat(buf, sizeof(buf), va("hc\\%i\\", client->pers.maxHealth)); + Q_strcat(buf, sizeof(buf), va("snd\\%s\\", sound)); + + gi.SetConfigstring(CS_PLAYERS + clientNum, buf); } - /* =========== ClientConnect @@ -517,51 +477,47 @@ to the server machine, but qfalse on map changes and tournement restarts. ============ */ -char *ClientConnect( int clientNum, qboolean firstTime, SavedGameJustLoaded_e eSavedGameJustLoaded ) -{ - gentity_t *ent = &g_entities[ clientNum ]; - char userinfo[MAX_INFO_STRING] = {0}; +char *ClientConnect(int clientNum, qboolean firstTime, SavedGameJustLoaded_e eSavedGameJustLoaded) { + gentity_t *ent = &g_entities[clientNum]; + char userinfo[MAX_INFO_STRING] = {0}; - gi.GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + gi.GetUserinfo(clientNum, userinfo, sizeof(userinfo)); // they can connect ent->client = level.clients + clientNum; gclient_t *client = ent->client; -// if (!qbFromSavedGame) - if (eSavedGameJustLoaded != eFULL) - { - clientSession_t savedSess = client->sess; // - memset( client, 0, sizeof(*client) ); + // if (!qbFromSavedGame) + if (eSavedGameJustLoaded != eFULL) { + clientSession_t savedSess = client->sess; // + memset(client, 0, sizeof(*client)); client->sess = savedSess; - if ( firstTime ) { //not loading full, and directconnect - client->playerTeam = TEAM_PLAYER; //set these now because after an auto_load kyle can see your team for a bit before you really join. + if (firstTime) { // not loading full, and directconnect + client->playerTeam = TEAM_PLAYER; // set these now because after an auto_load kyle can see your team for a bit before you really join. client->enemyTeam = TEAM_ENEMY; } } client->pers.connected = CON_CONNECTING; - if (eSavedGameJustLoaded == eFULL)//qbFromSavedGame) + if (eSavedGameJustLoaded == eFULL) // qbFromSavedGame) { // G_WriteClientSessionData( client ); // forget it, this is DM stuff anyway // get and distribute relevent paramters - ClientUserinfoChanged( clientNum ); - } - else - { + ClientUserinfoChanged(clientNum); + } else { // read or initialize the session data - if ( firstTime ) { - G_InitSessionData( client, userinfo ); + if (firstTime) { + G_InitSessionData(client, userinfo); } - G_ReadSessionData( client ); + G_ReadSessionData(client); // get and distribute relevent paramters - ClientUserinfoChanged( clientNum ); + ClientUserinfoChanged(clientNum); // don't do the "xxx connected" messages if they were caried over from previous level - if ( firstTime ) { - gi.SendServerCommand( -1, "print \"%s connected\n\"", client->pers.netname); + if (firstTime) { + gi.SendServerCommand(-1, "print \"%s connected\n\"", client->pers.netname); } } @@ -577,44 +533,41 @@ to be placed into the level. This will happen every level load, and on transition between teams, but doesn't happen on respawns ============ */ -void ClientBegin( int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded) +void ClientBegin(int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded) // qboolean qbFromSavedGame { - gentity_t *ent; - gclient_t *client; + gentity_t *ent; + gclient_t *client; ent = g_entities + clientNum; client = level.clients + clientNum; - if (eSavedGameJustLoaded == eFULL)//qbFromSavedGame) + if (eSavedGameJustLoaded == eFULL) // qbFromSavedGame) { client->pers.connected = CON_CONNECTED; ent->client = client; - ClientSpawn( ent, eSavedGameJustLoaded ); - } - else - { - if ( ent->linked ) { - gi.unlinkentity( ent ); + ClientSpawn(ent, eSavedGameJustLoaded); + } else { + if (ent->linked) { + gi.unlinkentity(ent); } - G_InitGentity( ent, qfalse ); + G_InitGentity(ent, qfalse); ent->e_TouchFunc = touchF_NULL; - ent->e_PainFunc = painF_PlayerPain;//painF_NULL; + ent->e_PainFunc = painF_PlayerPain; // painF_NULL; ent->client = client; client->pers.connected = CON_CONNECTED; client->pers.teamState.state = TEAM_BEGIN; - VectorCopyM( cmd->angles, client->pers.cmd_angles ); + VectorCopyM(cmd->angles, client->pers.cmd_angles); - memset( &client->ps, 0, sizeof( client->ps ) ); - if( gi.Cvar_VariableIntegerValue( "g_clearstats" ) ) - { - memset( &client->sess.missionStats, 0, sizeof( client->sess.missionStats ) ); + memset(&client->ps, 0, sizeof(client->ps)); + if (gi.Cvar_VariableIntegerValue("g_clearstats")) { + memset(&client->sess.missionStats, 0, sizeof(client->sess.missionStats)); client->sess.missionStats.totalSecrets = gi.Cvar_VariableIntegerValue("newTotalSecrets"); } // locate ent at a spawn point - if ( ClientSpawn( ent, eSavedGameJustLoaded) ) // SavedGameJustLoaded_e + if (ClientSpawn(ent, eSavedGameJustLoaded)) // SavedGameJustLoaded_e { // send teleport event } @@ -623,8 +576,6 @@ void ClientBegin( int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGam } } - - /* ============ Player_CacheFromPrevLevel @@ -633,39 +584,34 @@ Player_CacheFromPrevLevel Argument : void ============ */ -void Player_CacheFromPrevLevel(void) -{ - char s[MAX_STRING_CHARS]; +void Player_CacheFromPrevLevel(void) { + char s[MAX_STRING_CHARS]; int i; - gi.Cvar_VariableStringBuffer( sCVARNAME_PLAYERSAVE, s, sizeof(s) ); + gi.Cvar_VariableStringBuffer(sCVARNAME_PLAYERSAVE, s, sizeof(s)); - if (s[0]) // actually this would be safe anyway because of the way sscanf() works, but this is clearer + if (s[0]) // actually this would be safe anyway because of the way sscanf() works, but this is clearer { int iDummy, bits, ibits; - sscanf( s, "%i %i %i %i", - &iDummy,//client->ps.stats[STAT_HEALTH], - &iDummy,//client->ps.stats[STAT_ARMOR], - &bits, //client->ps.stats[STAT_WEAPONS] - &ibits //client->ps.stats[STAT_ITEMS] - ); + sscanf(s, "%i %i %i %i", + &iDummy, // client->ps.stats[STAT_HEALTH], + &iDummy, // client->ps.stats[STAT_ARMOR], + &bits, // client->ps.stats[STAT_WEAPONS] + &ibits // client->ps.stats[STAT_ITEMS] + ); - for ( i = 1 ; i < 16 ; i++ ) - { - if ( bits & ( 1 << i ) ) - { - RegisterItem( FindItemForWeapon( (weapon_t)i ) ); + for (i = 1; i < 16; i++) { + if (bits & (1 << i)) { + RegisterItem(FindItemForWeapon((weapon_t)i)); } } -extern gitem_t *FindItemForInventory( int inv ); + extern gitem_t *FindItemForInventory(int inv); - for ( i = 0 ; i < 16 ; i++ ) - { - if ( ibits & ( 1 << i ) ) - { - RegisterItem( FindItemForInventory( i )); + for (i = 0; i < 16; i++) { + if (ibits & (1 << i)) { + RegisterItem(FindItemForInventory(i)); } } } @@ -679,89 +625,48 @@ Player_RestoreFromPrevLevel Argument : gentity_t *ent ============ */ -static void Player_RestoreFromPrevLevel(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded) -{ - gclient_t *client = ent->client; - int i; +static void Player_RestoreFromPrevLevel(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded) { + gclient_t *client = ent->client; + int i; assert(client); - if (client) // though I can't see it not being true... + if (client) // though I can't see it not being true... { - char s[MAX_STRING_CHARS]; - char saber0Name[MAX_QPATH]; - char saber1Name[MAX_QPATH]; - const char *var; + char s[MAX_STRING_CHARS]; + char saber0Name[MAX_QPATH]; + char saber1Name[MAX_QPATH]; + const char *var; - gi.Cvar_VariableStringBuffer( sCVARNAME_PLAYERSAVE, s, sizeof(s) ); + gi.Cvar_VariableStringBuffer(sCVARNAME_PLAYERSAVE, s, sizeof(s)); - if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer - {// |general info |-force powers |-saber 1 |-saber 2 |-general saber + if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer + { // |general info |-force powers |-saber 1 |-saber 2 + //|-general saber int saber1BladeActive[8]; int saber2BladeActive[8]; unsigned int saber1BladeColor[8]; unsigned int saber2BladeColor[8]; - sscanf( s, "%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %s %i %i %i %i %i %i %i %i %u %u %u %u %u %u %u %u %s %i %i %i %i %i %i %i %i %u %u %u %u %u %u %u %u %i %i %i %i", - &client->ps.stats[STAT_HEALTH], - &client->ps.stats[STAT_ARMOR], - &client->ps.stats[STAT_WEAPONS], - &client->ps.stats[STAT_ITEMS], - &client->ps.weapon, - &client->ps.weaponstate, - &client->ps.batteryCharge, - &client->ps.viewangles[0], - &client->ps.viewangles[1], - &client->ps.viewangles[2], - //force power data - &client->ps.forcePowersKnown, - &client->ps.forcePower, - &client->ps.forcePowerMax, - &client->ps.forcePowerRegenRate, - &client->ps.forcePowerRegenAmount, - //saber 1 data - saber0Name, - &saber1BladeActive[0], - &saber1BladeActive[1], - &saber1BladeActive[2], - &saber1BladeActive[3], - &saber1BladeActive[4], - &saber1BladeActive[5], - &saber1BladeActive[6], - &saber1BladeActive[7], - &saber1BladeColor[0], - &saber1BladeColor[1], - &saber1BladeColor[2], - &saber1BladeColor[3], - &saber1BladeColor[4], - &saber1BladeColor[5], - &saber1BladeColor[6], - &saber1BladeColor[7], - //saber 2 data - saber1Name, - &saber2BladeActive[0], - &saber2BladeActive[1], - &saber2BladeActive[2], - &saber2BladeActive[3], - &saber2BladeActive[4], - &saber2BladeActive[5], - &saber2BladeActive[6], - &saber2BladeActive[7], - &saber2BladeColor[0], - &saber2BladeColor[1], - &saber2BladeColor[2], - &saber2BladeColor[3], - &saber2BladeColor[4], - &saber2BladeColor[5], - &saber2BladeColor[6], - &saber2BladeColor[7], - //general saber data - &client->ps.saberStylesKnown, - &client->ps.saberAnimLevel, - &client->ps.saberLockEnemy, - &client->ps.saberLockTime - ); - for (int j = 0; j < 8; j++) - { + sscanf(s, + "%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %s %i %i %i %i %i %i %i %i %u %u %u %u %u %u %u %u %s %i %i %i %i %i %i %i %i %u %u %u %u %u " + "%u %u %u %i %i %i %i", + &client->ps.stats[STAT_HEALTH], &client->ps.stats[STAT_ARMOR], &client->ps.stats[STAT_WEAPONS], &client->ps.stats[STAT_ITEMS], + &client->ps.weapon, &client->ps.weaponstate, &client->ps.batteryCharge, &client->ps.viewangles[0], &client->ps.viewangles[1], + &client->ps.viewangles[2], + // force power data + &client->ps.forcePowersKnown, &client->ps.forcePower, &client->ps.forcePowerMax, &client->ps.forcePowerRegenRate, + &client->ps.forcePowerRegenAmount, + // saber 1 data + saber0Name, &saber1BladeActive[0], &saber1BladeActive[1], &saber1BladeActive[2], &saber1BladeActive[3], &saber1BladeActive[4], + &saber1BladeActive[5], &saber1BladeActive[6], &saber1BladeActive[7], &saber1BladeColor[0], &saber1BladeColor[1], &saber1BladeColor[2], + &saber1BladeColor[3], &saber1BladeColor[4], &saber1BladeColor[5], &saber1BladeColor[6], &saber1BladeColor[7], + // saber 2 data + saber1Name, &saber2BladeActive[0], &saber2BladeActive[1], &saber2BladeActive[2], &saber2BladeActive[3], &saber2BladeActive[4], + &saber2BladeActive[5], &saber2BladeActive[6], &saber2BladeActive[7], &saber2BladeColor[0], &saber2BladeColor[1], &saber2BladeColor[2], + &saber2BladeColor[3], &saber2BladeColor[4], &saber2BladeColor[5], &saber2BladeColor[6], &saber2BladeColor[7], + // general saber data + &client->ps.saberStylesKnown, &client->ps.saberAnimLevel, &client->ps.saberLockEnemy, &client->ps.saberLockTime); + for (int j = 0; j < 8; j++) { client->ps.saber[0].blade[j].active = saber1BladeActive[j] ? qtrue : qfalse; client->ps.saber[0].blade[j].color = (saber_colors_t)saber1BladeColor[j]; client->ps.saber[1].blade[j].active = saber2BladeActive[j] ? qtrue : qfalse; @@ -770,77 +675,69 @@ static void Player_RestoreFromPrevLevel(gentity_t *ent, SavedGameJustLoaded_e eS ent->health = client->ps.stats[STAT_HEALTH]; - if(ent->client->ps.saber[0].name && gi.bIsFromZone(ent->client->ps.saber[0].name, TAG_G_ALLOC)) { + if (ent->client->ps.saber[0].name && gi.bIsFromZone(ent->client->ps.saber[0].name, TAG_G_ALLOC)) { gi.Free(ent->client->ps.saber[0].name); } - ent->client->ps.saber[0].name=0; + ent->client->ps.saber[0].name = 0; - if(ent->client->ps.saber[1].name && gi.bIsFromZone(ent->client->ps.saber[1].name, TAG_G_ALLOC) ) { + if (ent->client->ps.saber[1].name && gi.bIsFromZone(ent->client->ps.saber[1].name, TAG_G_ALLOC)) { gi.Free(ent->client->ps.saber[1].name); } - ent->client->ps.saber[1].name=0; - //NOTE: if sscanf can get a "(null)" out of strings that had NULL string pointers plugged into the original string - if ( saber0Name[0] && Q_stricmp( "(null)", saber0Name ) != 0 ) - { - ent->client->ps.saber[0].name = G_NewString( saber0Name ); + ent->client->ps.saber[1].name = 0; + // NOTE: if sscanf can get a "(null)" out of strings that had NULL string pointers plugged into the original string + if (saber0Name[0] && Q_stricmp("(null)", saber0Name) != 0) { + ent->client->ps.saber[0].name = G_NewString(saber0Name); } - if ( saber1Name[0] && Q_stricmp( "(null)", saber1Name ) != 0 ) - {//have a second saber - ent->client->ps.saber[1].name = G_NewString( saber1Name ); + if (saber1Name[0] && Q_stricmp("(null)", saber1Name) != 0) { // have a second saber + ent->client->ps.saber[1].name = G_NewString(saber1Name); ent->client->ps.dualSabers = qtrue; - } - else - {//have only 1 saber + } else { // have only 1 saber ent->client->ps.dualSabers = qfalse; } -// slight issue with ths for the moment in that although it'll correctly restore angles it doesn't take into account -// the overall map orientation, so (eg) exiting east to enter south will be out by 90 degrees, best keep spawn angles for now -// -// VectorClear (ent->client->pers.cmd_angles); -// -// SetClientViewAngle( ent, ent->client->ps.viewangles); + // slight issue with ths for the moment in that although it'll correctly restore angles it doesn't take into account + // the overall map orientation, so (eg) exiting east to enter south will be out by 90 degrees, best keep spawn angles for now + // + // VectorClear (ent->client->pers.cmd_angles); + // + // SetClientViewAngle( ent, ent->client->ps.viewangles); - //ammo - gi.Cvar_VariableStringBuffer( "playerammo", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->ps.ammo[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); - } - assert (i==AMMO_MAX); - - //inventory - gi.Cvar_VariableStringBuffer( "playerinv", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->ps.inventory[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + // ammo + gi.Cvar_VariableStringBuffer("playerammo", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->ps.ammo[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==INV_MAX); + assert(i == AMMO_MAX); + // inventory + gi.Cvar_VariableStringBuffer("playerinv", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->ps.inventory[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); + } + assert(i == INV_MAX); // the new JK2 stuff - force powers, etc... // - gi.Cvar_VariableStringBuffer( "playerfplvl", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { + gi.Cvar_VariableStringBuffer("playerfplvl", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { /* While there are tokens in "s" */ - client->ps.forcePowerLevel[i++] = atoi(var); + client->ps.forcePowerLevel[i++] = atoi(var); /* Get next token: */ - var = strtok( NULL, " " ); + var = strtok(NULL, " "); } - assert (i==NUM_FORCE_POWERS); + assert(i == NUM_FORCE_POWERS); client->ps.forceGripEntityNum = client->ps.forceDrainEntityNum = ENTITYNUM_NONE; } @@ -851,40 +748,31 @@ static void Player_RestoreFromPrevLevel(gentity_t *ent, SavedGameJustLoaded_e eS Ghoul2 Insert Start */ -static void G_SetSkin( gentity_t *ent ) -{ - char skinName[MAX_QPATH]; - //ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. - if (Q_stricmp( "hoth2", level.mapname ) == 0 //hack, is this the only map? - || - Q_stricmp( "hoth3", level.mapname ) == 0 // no! ;-) - ) - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, "torso_g1", "lower_e1" ); - } - else if(Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && Q_stricmp(g_char_skin_legs->string, "model_default") == 0) - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_default.skin", g_char_model->string ); - } - else - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string ); +static void G_SetSkin(gentity_t *ent) { + char skinName[MAX_QPATH]; + // ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. + if (Q_stricmp("hoth2", level.mapname) == 0 // hack, is this the only map? + || Q_stricmp("hoth3", level.mapname) == 0 // no! ;-) + ) { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, "torso_g1", "lower_e1"); + } else if (Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && + Q_stricmp(g_char_skin_legs->string, "model_default") == 0) { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_default.skin", g_char_model->string); + } else { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, + g_char_skin_legs->string); } // lets see if it's out there - int skin = gi.RE_RegisterSkin( skinName ); - if ( skin ) - {//what if this returns 0 because *one* part of a multi-skin didn't load? + int skin = gi.RE_RegisterSkin(skinName); + if (skin) { // what if this returns 0 because *one* part of a multi-skin didn't load? // put it in the config strings // and set the ghoul2 model to use it - gi.G2API_SetSkin( &ent->ghoul2[ent->playerModel], G_SkinIndex( skinName ), skin ); + gi.G2API_SetSkin(&ent->ghoul2[ent->playerModel], G_SkinIndex(skinName), skin); } - //color tinting - if ( g_char_color_red->integer - || g_char_color_green->integer - || g_char_color_blue->integer ) - { + // color tinting + if (g_char_color_red->integer || g_char_color_green->integer || g_char_color_blue->integer) { ent->client->renderInfo.customRGBA[0] = g_char_color_red->integer; ent->client->renderInfo.customRGBA[1] = g_char_color_green->integer; ent->client->renderInfo.customRGBA[2] = g_char_color_blue->integer; @@ -892,56 +780,44 @@ static void G_SetSkin( gentity_t *ent ) } } -qboolean G_StandardHumanoid( gentity_t *self ) -{ - if ( !self || !self->ghoul2.size() ) - { +qboolean G_StandardHumanoid(gentity_t *self) { + if (!self || !self->ghoul2.size()) { return qfalse; } - if ( self->playerModel < 0 || self->playerModel >= self->ghoul2.size() ) - { + if (self->playerModel < 0 || self->playerModel >= self->ghoul2.size()) { return qfalse; } - const char *GLAName = gi.G2API_GetGLAName( &self->ghoul2[self->playerModel] ); + const char *GLAName = gi.G2API_GetGLAName(&self->ghoul2[self->playerModel]); assert(GLAName); - if (GLAName) - { - if ( !Q_stricmpn( "models/players/_humanoid", GLAName, 24 ) )///_humanoid", GLAName, 36) ) - {//only _humanoid skeleton is expected to have these + if (GLAName) { + if (!Q_stricmpn("models/players/_humanoid", GLAName, 24)) ///_humanoid", GLAName, 36) ) + { // only _humanoid skeleton is expected to have these return qtrue; } - if ( !Q_stricmp( "models/players/protocol/protocol", GLAName ) ) - {//protocol droid duplicates many of these + if (!Q_stricmp("models/players/protocol/protocol", GLAName)) { // protocol droid duplicates many of these return qtrue; } - if ( !Q_stricmp( "models/players/assassin_droid/model", GLAName ) ) - {//assassin_droid duplicates many of these + if (!Q_stricmp("models/players/assassin_droid/model", GLAName)) { // assassin_droid duplicates many of these return qtrue; } - if ( !Q_stricmp( "models/players/saber_droid/model", GLAName ) ) - {//saber_droid duplicates many of these + if (!Q_stricmp("models/players/saber_droid/model", GLAName)) { // saber_droid duplicates many of these return qtrue; } - if ( !Q_stricmp( "models/players/hazardtrooper/hazardtrooper", GLAName ) ) - {//hazardtrooper duplicates many of these + if (!Q_stricmp("models/players/hazardtrooper/hazardtrooper", GLAName)) { // hazardtrooper duplicates many of these return qtrue; } - if ( !Q_stricmp( "models/players/rockettrooper/rockettrooper", GLAName ) ) - {//rockettrooper duplicates many of these + if (!Q_stricmp("models/players/rockettrooper/rockettrooper", GLAName)) { // rockettrooper duplicates many of these return qtrue; } - if ( !Q_stricmp( "models/players/wampa/wampa", GLAName ) ) - {//rockettrooper duplicates many of these + if (!Q_stricmp("models/players/wampa/wampa", GLAName)) { // rockettrooper duplicates many of these return qtrue; } } return qfalse; } -qboolean G_ClassHasBadBones( int NPC_class ) -{ - switch ( NPC_class ) - { +qboolean G_ClassHasBadBones(int NPC_class) { + switch (NPC_class) { case CLASS_WAMPA: case CLASS_ROCKETTROOPER: case CLASS_SABER_DROID: @@ -953,75 +829,63 @@ qboolean G_ClassHasBadBones( int NPC_class ) return qfalse; } -const char *AxesNames[] = -{ - "ORIGIN",//ORIGIN, - "POSITIVE_X",//POSITIVE_X, - "POSITIVE_Z",//POSITIVE_Z, - "POSITIVE_Y",//POSITIVE_Y, - "NEGATIVE_X",//NEGATIVE_X, - "NEGATIVE_Z",//NEGATIVE_Z, - "NEGATIVE_Y"//NEGATIVE_Y +const char *AxesNames[] = { + "ORIGIN", // ORIGIN, + "POSITIVE_X", // POSITIVE_X, + "POSITIVE_Z", // POSITIVE_Z, + "POSITIVE_Y", // POSITIVE_Y, + "NEGATIVE_X", // NEGATIVE_X, + "NEGATIVE_Z", // NEGATIVE_Z, + "NEGATIVE_Y" // NEGATIVE_Y }; -Eorientations testAxes[3]={POSITIVE_X,POSITIVE_Z,POSITIVE_Y}; +Eorientations testAxes[3] = {POSITIVE_X, POSITIVE_Z, POSITIVE_Y}; int axes_0 = POSITIVE_X; int axes_1 = POSITIVE_Z; int axes_2 = POSITIVE_Y; -void G_NextTestAxes( void ) -{ +void G_NextTestAxes(void) { static int whichAxes = 0; int axesCount = 0; - do - { + do { whichAxes++; - if ( whichAxes > 216 ) - { + if (whichAxes > 216) { whichAxes = 0; - Com_Printf( S_COLOR_RED"WRAPPED\n" ); + Com_Printf(S_COLOR_RED "WRAPPED\n"); break; } axesCount = 0; axes_0 = 0; axes_1 = 0; axes_2 = 0; - for ( axes_0 = 0; axes_0 < 6 && (axesCountplayerModel != -1 ) - {// we found the model ok - vec3_t angles = {0,0,0}; - const char *token; - const char *p; - - //Now turn on/off any surfaces - if ( surfOff && surfOff[0] ) - { +extern void G_LoadAnimFileSet(gentity_t *ent, const char *modelName); +qboolean G_SetG2PlayerModelInfo(gentity_t *ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn) { + if (ent->playerModel != -1) { // we found the model ok + vec3_t angles = {0, 0, 0}; + const char *token; + const char *p; + + // Now turn on/off any surfaces + if (surfOff && surfOff[0]) { p = surfOff; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn off this surf - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], token, 0x00000002/*G2SURFACEFLAG_OFF*/ ); - + // turn off this surf + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], token, 0x00000002 /*G2SURFACEFLAG_OFF*/); } COM_EndParseSession(); } - if ( surfOn && surfOn[0] ) - { + if (surfOn && surfOn[0]) { p = surfOn; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn on this surf - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], token, 0 ); + // turn on this surf + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], token, 0); } COM_EndParseSession(); } - if ( ent->client->NPC_class == CLASS_IMPERIAL && ent->message ) - {//carrying a key, turn on the key sleeve surface (assuming we have one) - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "l_arm_key", 0 ); + if (ent->client->NPC_class == CLASS_IMPERIAL && ent->message) { // carrying a key, turn on the key sleeve surface (assuming we have one) + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "l_arm_key", 0); } - G_LoadAnimFileSet( ent, modelName ); + G_LoadAnimFileSet(ent, modelName); - ent->headBolt = ent->cervicalBolt = ent->torsoBolt = ent->gutBolt = ent->chestBolt = - ent->crotchBolt = ent->elbowLBolt = ent->elbowRBolt = ent->handLBolt = - ent->handRBolt = ent->kneeLBolt = ent->kneeRBolt = ent->footLBolt = - ent->footRBolt = -1; + ent->headBolt = ent->cervicalBolt = ent->torsoBolt = ent->gutBolt = ent->chestBolt = ent->crotchBolt = ent->elbowLBolt = ent->elbowRBolt = + ent->handLBolt = ent->handRBolt = ent->kneeLBolt = ent->kneeRBolt = ent->footLBolt = ent->footRBolt = -1; // now turn on the bolt in the hand - this one would be best always turned on. - if ( G_StandardHumanoid( ent ) ) - {//only _humanoid skeleton is expected to have these + if (G_StandardHumanoid(ent)) { // only _humanoid skeleton is expected to have these ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_eyes"); - ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical" ); - if ( !Q_stricmp("protocol", modelName ) ) - {//*sigh*, no thoracic bone + ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical"); + if (!Q_stricmp("protocol", modelName)) { //*sigh*, no thoracic bone ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); ent->chestBolt = ent->gutBolt; - } - else - { + } else { ent->chestBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "thoracic"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); } @@ -1190,21 +1026,15 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->kneeRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*hips_r_knee"); ent->footLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_leg_foot"); ent->footRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_leg_foot"); - if ( ent->client->NPC_class == CLASS_BOBAFETT - || ent->client->NPC_class == CLASS_ROCKETTROOPER ) - {//get jet bolts - ent->genericBolt1 = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*jet1" ); - ent->genericBolt2 = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*jet2" ); - } - if ( ent->client->NPC_class == CLASS_BOBAFETT ) - {//get the flamethrower bolt + if (ent->client->NPC_class == CLASS_BOBAFETT || ent->client->NPC_class == CLASS_ROCKETTROOPER) { // get jet bolts + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*jet1"); + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*jet2"); + } + if (ent->client->NPC_class == CLASS_BOBAFETT) { // get the flamethrower bolt ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flamethrower"); } - } - else - { - if ( ent->client->NPC_class == CLASS_VEHICLE ) - {//do vehicles tags + } else { + if (ent->client->NPC_class == CLASS_VEHICLE) { // do vehicles tags // Setup the driver tag (where the driver is mounted to). ent->crotchBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*driver"); @@ -1215,98 +1045,71 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch char strTemp[128]; // Setup the Exhausts. - for ( int i = 0; i < MAX_VEHICLE_EXHAUSTS; i++ ) - { - Com_sprintf( strTemp, 128, "*exhaust%d", i + 1 ); - ent->m_pVehicle->m_iExhaustTag[i] = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], strTemp ); + for (int i = 0; i < MAX_VEHICLE_EXHAUSTS; i++) { + Com_sprintf(strTemp, 128, "*exhaust%d", i + 1); + ent->m_pVehicle->m_iExhaustTag[i] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], strTemp); } // Setup the Muzzles. - for ( int i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - Com_sprintf( strTemp, 128, "*muzzle%d", i + 1 ); - ent->m_pVehicle->m_iMuzzleTag[i] = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], strTemp ); - if ( ent->m_pVehicle->m_iMuzzleTag[i] == -1 ) - {//ergh, try *flash? - Com_sprintf( strTemp, 128, "*flash%d", i + 1 ); - ent->m_pVehicle->m_iMuzzleTag[i] = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], strTemp ); + for (int i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + Com_sprintf(strTemp, 128, "*muzzle%d", i + 1); + ent->m_pVehicle->m_iMuzzleTag[i] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], strTemp); + if (ent->m_pVehicle->m_iMuzzleTag[i] == -1) { // ergh, try *flash? + Com_sprintf(strTemp, 128, "*flash%d", i + 1); + ent->m_pVehicle->m_iMuzzleTag[i] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], strTemp); } } - } - else if ( ent->client->NPC_class == CLASS_HOWLER ) - { - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Tongue01" );// tongue base - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Tongue08" );// tongue tip - } - else if ( !Q_stricmp( "gonk", modelName ) || !Q_stricmp( "seeker", modelName ) || !Q_stricmp( "remote", modelName ) - || !Q_stricmpn( "r2d2", modelName, 4 ) || !Q_stricmpn( "r5d2", modelName, 4 ) ) - {//TEMP HACK: not a non-humanoid droid + } else if (ent->client->NPC_class == CLASS_HOWLER) { + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Tongue01"); // tongue base + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Tongue08"); // tongue tip + } else if (!Q_stricmp("gonk", modelName) || !Q_stricmp("seeker", modelName) || !Q_stricmp("remote", modelName) || + !Q_stricmpn("r2d2", modelName, 4) || !Q_stricmpn("r5d2", modelName, 4)) { // TEMP HACK: not a non-humanoid droid ent->headBolt = -1; - } - else if (!Q_stricmp( "interrogator",modelName)) - { + } else if (!Q_stricmp("interrogator", modelName)) { ent->headBolt = -1; - } - else if (!Q_stricmpn( "probe",modelName, 5)) - { - ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); // head pivot point - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Gun 1 - } - else if (!Q_stricmp( "sentry",modelName)) - { + } else if (!Q_stricmpn("probe", modelName, 5)) { + ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); // head pivot point + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Gun 1 + } else if (!Q_stricmp("sentry", modelName)) { ent->headBolt = -1; - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Gun 1 - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Gun 2 - ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash03"); // Gun 3 - } - else if (!Q_stricmp( "mark1",modelName)) - { + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Gun 1 + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Gun 2 + ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash03"); // Gun 3 + } else if (!Q_stricmp("mark1", modelName)) { ent->headBolt = -1; - ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Blaster Gun 1 - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Blaster Gun 2 - ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Blaster Gun 3 - ent->genericBolt4 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Blaster Gun 4 - ent->genericBolt5 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash5"); // Missile Gun 1 - } - else if (!Q_stricmp( "mark2",modelName)) - { + ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Blaster Gun 1 + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Blaster Gun 2 + ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Blaster Gun 3 + ent->genericBolt4 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Blaster Gun 4 + ent->genericBolt5 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash5"); // Missile Gun 1 + } else if (!Q_stricmp("mark2", modelName)) { ent->headBolt = -1; - ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Blaster Gun 1 - } - else if (!Q_stricmp( "atst",modelName) )//&& (ent->client->playerTeam != TEAM_PLAYER)) + ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Blaster Gun 1 + } else if (!Q_stricmp("atst", modelName)) //&& (ent->client->playerTeam != TEAM_PLAYER)) { ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head"); - ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Front guns + ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Front guns ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Left side gun - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Right side missle launcher + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Left side gun + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Right side missle launcher ent->footLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_foot"); ent->footRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_foot"); - } - else if ( !Q_stricmp( "minemonster", modelName )) - { + } else if (!Q_stricmp("minemonster", modelName)) { ent->handRBolt = ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_f1"); - } - else if ( !Q_stricmp( "rancor", modelName ) - || !Q_stricmp( "mutant_rancor", modelName )) - { + } else if (!Q_stricmp("rancor", modelName) || !Q_stricmp("mutant_rancor", modelName)) { ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_hand"); ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_hand"); ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_eyes"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_mouth"); - } - else if ( !Q_stricmp( "sand_creature", modelName )) - { + } else if (!Q_stricmp("sand_creature", modelName)) { ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*mouth"); ent->crotchBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*ground"); - } - else if ( !Q_stricmp( "wampa", modelName )) - { + } else if (!Q_stricmp("wampa", modelName)) { ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_eyes"); - ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "neck_bone" ); + ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "neck_bone"); ent->chestBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_spine"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "mid_spine"); ent->torsoBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "lower_spine"); @@ -1319,14 +1122,11 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->kneeRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*hips_r_knee"); ent->footLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_leg_foot"); ent->footRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_leg_foot"); - } - else - {//TEMP HACK: not a non-humanoid droid - ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*weapon");//should be r_hand - if ( Q_stricmp( "atst", modelName ) ) - {//not an ATST + } else { // TEMP HACK: not a non-humanoid droid + ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*weapon"); // should be r_hand + if (Q_stricmp("atst", modelName)) { // not an ATST ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*headg"); - ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical" ); + ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical"); ent->torsoBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "lower_lumbar"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); ent->chestBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "thoracic"); @@ -1350,186 +1150,154 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->lowerLumbarBone = BONE_INDEX_INVALID; ent->motionBone = BONE_INDEX_INVALID; ent->hipsBone = BONE_INDEX_INVALID; - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); #ifndef FINAL_BUILD - if ( g_developer->integer && ent->rootBone == -1 ) - { - Com_Error(ERR_DROP,"ERROR: model %s has no model_root bone (and hence cannot animate)!!!\n", modelName ); + if (g_developer->integer && ent->rootBone == -1) { + Com_Error(ERR_DROP, "ERROR: model %s has no model_root bone (and hence cannot animate)!!!\n", modelName); } #endif ent->footLBone = BONE_INDEX_INVALID; ent->footRBone = BONE_INDEX_INVALID; - ent->humerusRBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "rhumerus", qtrue ); + ent->humerusRBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "rhumerus", qtrue); // now add overrides on specific joints so the client can set angle overrides on the legs, torso and head - if ( ent->client->NPC_class == CLASS_VEHICLE ) - {//do vehicles tags - //vehicleInfo_t *vehicle = ent->m_pVehicle->m_pVehicleInfo; - } - else if ( ent->client->NPC_class == CLASS_HOWLER ) - { - } - else if ( !Q_stricmp( "gonk", modelName ) || !Q_stricmp( "seeker", modelName ) || !Q_stricmp( "remote", modelName ) ) - {// - } - else if (!Q_stricmp( "sentry",modelName)) - { - } - else if (!Q_stricmpn( "probe", modelName, 5 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "pelvis", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if (!Q_stricmp( "interrogator", modelName )) - { - ent->genericBone1 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "left_arm", qtrue ); - if (ent->genericBone1>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->genericBone2 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "right_arm", qtrue ); - if (ent->genericBone2>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone2, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->genericBone3 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "claw", qtrue ); - if (ent->genericBone3>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone3, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if (!Q_stricmpn( "r2d2", modelName, 4 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "body", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->genericBone1 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "f_eye", qtrue ); - if (ent->genericBone1>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if (!Q_stricmpn( "r5d2", modelName, 4 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "body", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if ( !Q_stricmp( "atst", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->footLBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "l_tarsal", qtrue ); - if (ent->footLBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->footLBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); - } - ent->footRBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "r_tarsal", qtrue ); - if (ent->footRBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->footRBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); - } - } - else if ( !Q_stricmp( "mark1", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->upperLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if ( !Q_stricmp( "mark2", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if ( !Q_stricmp( "minemonster", modelName )) - { - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic1", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - } - } - else if ( ent->client->NPC_class == CLASS_RANCOR ) - /*!Q_stricmp( "rancor", modelName ) || !Q_stricmp( "mutant_rancor", modelName ) )*/ + if (ent->client->NPC_class == CLASS_VEHICLE) { // do vehicles tags + // vehicleInfo_t *vehicle = ent->m_pVehicle->m_pVehicleInfo; + } else if (ent->client->NPC_class == CLASS_HOWLER) { + } else if (!Q_stricmp("gonk", modelName) || !Q_stricmp("seeker", modelName) || !Q_stricmp("remote", modelName)) { // + } else if (!Q_stricmp("sentry", modelName)) { + } else if (!Q_stricmpn("probe", modelName, 5)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "pelvis", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (!Q_stricmp("interrogator", modelName)) { + ent->genericBone1 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "left_arm", qtrue); + if (ent->genericBone1 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); + } + ent->genericBone2 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "right_arm", qtrue); + if (ent->genericBone2 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone2, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); + } + ent->genericBone3 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "claw", qtrue); + if (ent->genericBone3 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone3, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (!Q_stricmpn("r2d2", modelName, 4)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "body", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->genericBone1 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "f_eye", qtrue); + if (ent->genericBone1 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (!Q_stricmpn("r5d2", modelName, 4)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "body", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (!Q_stricmp("atst", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->footLBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "l_tarsal", qtrue); + if (ent->footLBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->footLBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, + NULL, 0, 0); + } + ent->footRBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "r_tarsal", qtrue); + if (ent->footRBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->footRBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, + NULL, 0, 0); + } + } else if (!Q_stricmp("mark1", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->upperLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); + } + } else if (!Q_stricmp("mark2", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (!Q_stricmp("minemonster", modelName)) { + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic1", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + } + } else if (ent->client->NPC_class == CLASS_RANCOR) + /*!Q_stricmp( "rancor", modelName ) || !Q_stricmp( "mutant_rancor", modelName ) )*/ { Eorientations oUp, oRt, oFwd; - //regular bones we need - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "lower_spine", qtrue ); - if (ent->lowerLumbarBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); - } - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "mid_spine", qtrue ); - if (ent->upperLumbarBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); - } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "upper_spine", qtrue ); - if (ent->thoracicBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); - } - } - else if ( !Q_stricmp( "sand_creature", modelName )) - { - } - else if ( !Q_stricmp( "wampa", modelName ) ) - { - //Eorientations oUp, oRt, oFwd; - //bone needed for turning anims + // regular bones we need + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "lower_spine", qtrue); + if (ent->lowerLumbarBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); + } + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "mid_spine", qtrue); + if (ent->upperLumbarBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); + } + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "upper_spine", qtrue); + if (ent->thoracicBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); + } + } else if (!Q_stricmp("sand_creature", modelName)) { + } else if (!Q_stricmp("wampa", modelName)) { + // Eorientations oUp, oRt, oFwd; + // bone needed for turning anims /* //SIGH... fucks him up BAD ent->hipsBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "pelvis", qtrue ); @@ -1575,154 +1343,128 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL ); } */ - } - else if ( !Q_stricmp( "rockettrooper", modelName ) - || !Q_stricmp( "hazardtrooper", modelName ) - || !Q_stricmp( "saber_droid", modelName ) - || !Q_stricmp( "assassin_droid", modelName ) ) - { + } else if (!Q_stricmp("rockettrooper", modelName) || !Q_stricmp("hazardtrooper", modelName) || !Q_stricmp("saber_droid", modelName) || + !Q_stricmp("assassin_droid", modelName)) { Eorientations oUp, oRt, oFwd; - if ( Q_stricmp( "saber_droid", modelName ) ) - {//saber droid doesn't use these lower bones - //regular bones we need - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue ); - if (ent->upperLumbarBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); + if (Q_stricmp("saber_droid", modelName)) { // saber droid doesn't use these lower bones + // regular bones we need + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue); + if (ent->upperLumbarBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "upper_lumbar", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); } - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue ); - if (ent->lowerLumbarBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue); + if (ent->lowerLumbarBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "lower_lumbar", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); } } - if ( Q_stricmp( "hazardtrooper", modelName ) ) - {//hazard trooper doesn't have these upper bones - if ( Q_stricmp( "saber_droid", modelName ) ) - {//saber droid doesn't use thoracic bone - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); + if (Q_stricmp("hazardtrooper", modelName)) { // hazard trooper doesn't have these upper bones + if (Q_stricmp("saber_droid", modelName)) { // saber droid doesn't use thoracic bone + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "thoracic", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, + 0); } } - ent->cervicalBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cervical", qtrue ); - if (ent->cervicalBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "cervical", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); + ent->cervicalBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cervical", qtrue); + if (ent->cervicalBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "cervical", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - G_BoneOrientationsForClass( ent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0 ); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + G_BoneOrientationsForClass(ent->client->NPC_class, "cranium", &oUp, &oRt, &oFwd); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, oUp, oRt, oFwd, NULL, 0, 0); } } - } - else - { - //special case motion bone - to match up split anims - ent->motionBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "Motion", qtrue ); - if (ent->motionBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->motionBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, NULL, 0, 0 ); + } else { + // special case motion bone - to match up split anims + ent->motionBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "Motion", qtrue); + if (ent->motionBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->motionBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, + NULL, 0, 0); } ent->motionBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Motion"); - //bone needed for turning anims - ent->hipsBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "pelvis", qtrue ); - if (ent->hipsBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->hipsBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + // bone needed for turning anims + ent->hipsBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "pelvis", qtrue); + if (ent->hipsBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->hipsBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - //regular bones we need - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue ); - if (ent->upperLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + // regular bones we need + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue); + if (ent->upperLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); } - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue ); - if (ent->lowerLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue); + if (ent->lowerLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); } - ent->faceBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "face", qtrue ); - if (ent->faceBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->faceBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->faceBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "face", qtrue); + if (ent->faceBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->faceBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->cervicalBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cervical", qtrue ); - if (ent->cervicalBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->cervicalBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cervical", qtrue); + if (ent->cervicalBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } } ent->client->clientInfo.infoValid = qtrue; - } - if ( ent->client->NPC_class == CLASS_SAND_CREATURE ) - { + if (ent->client->NPC_class == CLASS_SAND_CREATURE) { ent->s.radius = 256; - } - else if ( ent->client->NPC_class == CLASS_RANCOR ) - { - if ( (ent->spawnflags&1) ) - {//mutant + } else if (ent->client->NPC_class == CLASS_RANCOR) { + if ((ent->spawnflags & 1)) { // mutant ent->s.radius = 300; - } - else - { + } else { ent->s.radius = 150; } - } - else if ( ent->s.radius <= 0 )//radius cannot be negative or zero - {//set the radius to be the largest axial distance on the entity - float max; - max = ent->mins[0];//NOTE: mins is always negative - if ( max > ent->mins[1] ) - { + } else if (ent->s.radius <= 0) // radius cannot be negative or zero + { // set the radius to be the largest axial distance on the entity + float max; + max = ent->mins[0]; // NOTE: mins is always negative + if (max > ent->mins[1]) { max = ent->mins[1]; } - if ( max > ent->mins[2] ) - { + if (max > ent->mins[2]) { max = ent->mins[2]; } - max = fabs(max);//convert to positive to compare with maxs - if ( max < ent->maxs[0] ) - { + max = fabs(max); // convert to positive to compare with maxs + if (max < ent->maxs[0]) { max = ent->maxs[0]; } - if ( max < ent->maxs[1] ) - { + if (max < ent->maxs[1]) { max = ent->maxs[1]; } - if ( max < ent->maxs[2] ) - { + if (max < ent->maxs[2]) { max = ent->maxs[2]; } ent->s.radius = (int)max; - if (!ent->s.radius) // Still no radius? + if (!ent->s.radius) // Still no radius? { ent->s.radius = 60; } @@ -1731,198 +1473,144 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch // set the weaponmodel to -1 so we don't try to remove it in Pmove before we have it built ent->weaponModel[0] = -1; - if ( ent->playerModel == -1 ) - { + if (ent->playerModel == -1) { return qfalse; } return qtrue; } -void G_SetG2PlayerModel( gentity_t * const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ) -{ - char skinName[MAX_QPATH]; +void G_SetG2PlayerModel(gentity_t *const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn) { + char skinName[MAX_QPATH]; - //ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. - if ( !customSkin ) - {//use the default - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_default.skin", modelName ); - } - else - { - if (strchr(customSkin, '|')) - {//three part skin - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/|%s", modelName, customSkin ); - } - else - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_%s.skin", modelName, customSkin ); + // ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. + if (!customSkin) { // use the default + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_default.skin", modelName); + } else { + if (strchr(customSkin, '|')) { // three part skin + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/|%s", modelName, customSkin); + } else { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_%s.skin", modelName, customSkin); } } - int skin = gi.RE_RegisterSkin( skinName ); - //now generate the ghoul2 model this client should be. - if ( ent->client->NPC_class == CLASS_VEHICLE ) - {//vehicles actually grab their model from the appropriate vehicle data entry + int skin = gi.RE_RegisterSkin(skinName); + // now generate the ghoul2 model this client should be. + if (ent->client->NPC_class == CLASS_VEHICLE) { // vehicles actually grab their model from the appropriate vehicle data entry // This will register the model and other assets. Vehicle_t *pVeh = ent->m_pVehicle; - pVeh->m_pVehicleInfo->RegisterAssets( pVeh ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, va("models/players/%s/model.glm", modelName), pVeh->m_pVehicleInfo->modelIndex, G_SkinIndex( skinName ), NULL_HANDLE, 0, 0 ); - } - else - { - //NOTE: it still loads the default skin's tga's because they're referenced in the .glm. - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, va("models/players/%s/model.glm", modelName), G_ModelIndex( va("models/players/%s/model.glm", modelName) ), G_SkinIndex( skinName ), NULL_HANDLE, 0, 0 ); - } - if (ent->playerModel == -1) - {//try the stormtrooper as a default - gi.Printf( S_COLOR_RED"G_SetG2PlayerModel: cannot load model %s\n", modelName ); + pVeh->m_pVehicleInfo->RegisterAssets(pVeh); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, va("models/players/%s/model.glm", modelName), pVeh->m_pVehicleInfo->modelIndex, + G_SkinIndex(skinName), NULL_HANDLE, 0, 0); + } else { + // NOTE: it still loads the default skin's tga's because they're referenced in the .glm. + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, va("models/players/%s/model.glm", modelName), + G_ModelIndex(va("models/players/%s/model.glm", modelName)), G_SkinIndex(skinName), NULL_HANDLE, 0, 0); + } + if (ent->playerModel == -1) { // try the stormtrooper as a default + gi.Printf(S_COLOR_RED "G_SetG2PlayerModel: cannot load model %s\n", modelName); modelName = "stormtrooper"; - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_default.skin", modelName ); - skin = gi.RE_RegisterSkin( skinName ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, va("models/players/%s/model.glm", modelName), G_ModelIndex( va("models/players/%s/model.glm", modelName) ), NULL_HANDLE, NULL_HANDLE, 0, 0 ); + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_default.skin", modelName); + skin = gi.RE_RegisterSkin(skinName); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, va("models/players/%s/model.glm", modelName), + G_ModelIndex(va("models/players/%s/model.glm", modelName)), NULL_HANDLE, NULL_HANDLE, 0, 0); } - if (ent->playerModel == -1) - {//very bad thing here! + if (ent->playerModel == -1) { // very bad thing here! Com_Error(ERR_DROP, "Cannot fall back to default model %s!", modelName); } - gi.G2API_SetSkin( &ent->ghoul2[ent->playerModel], G_SkinIndex( skinName ), skin );//this is going to set the surfs on/off matching the skin file + gi.G2API_SetSkin(&ent->ghoul2[ent->playerModel], G_SkinIndex(skinName), skin); // this is going to set the surfs on/off matching the skin file // did we find a ghoul2 model? if so, load the animation.cfg file - if ( !G_SetG2PlayerModelInfo( ent, modelName, customSkin, surfOff, surfOn ) ) - {//couldn't set g2 info, fall back to a mouse md3 - NPC_ParseParms( "mouse", ent ); - Com_Printf( S_COLOR_RED"couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName) ); + if (!G_SetG2PlayerModelInfo(ent, modelName, customSkin, surfOff, surfOn)) { // couldn't set g2 info, fall back to a mouse md3 + NPC_ParseParms("mouse", ent); + Com_Printf(S_COLOR_RED "couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName)); } } /* Ghoul2 Insert End */ -void G_RemovePlayerModel( gentity_t *ent ) -{ - if ( ent->playerModel >= 0 && ent->ghoul2.size() ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->playerModel ); +void G_RemovePlayerModel(gentity_t *ent) { + if (ent->playerModel >= 0 && ent->ghoul2.size()) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->playerModel); ent->playerModel = -1; } } -void G_RemoveWeaponModels( gentity_t *ent ) -{ - if ( ent->ghoul2.size() ) - { - if ( ent->weaponModel[0] > 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[0] ); +void G_RemoveWeaponModels(gentity_t *ent) { + if (ent->ghoul2.size()) { + if (ent->weaponModel[0] > 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[0]); ent->weaponModel[0] = -1; } - if ( ent->weaponModel[1] > 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[1] ); + if (ent->weaponModel[1] > 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[1]); ent->weaponModel[1] = -1; } } } -void G_AddWeaponModels( gentity_t *ent ) -{ - if ( !ent || !ent->client ) - { +void G_AddWeaponModels(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if ( ent->weaponModel[0] == -1 ) - { - if ( ent->client->ps.weapon == WP_SABER ) - { - WP_SaberAddG2SaberModels( ent ); - } - else if ( ent->client->ps.weapon != WP_NONE ) - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + if (ent->weaponModel[0] == -1) { + if (ent->client->ps.weapon == WP_SABER) { + WP_SaberAddG2SaberModels(ent); + } else if (ent->client->ps.weapon != WP_NONE) { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } } } -extern saber_colors_t TranslateSaberColor( const char *name ); -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); -void G_ChangePlayerModel( gentity_t *ent, const char *newModel ); -void G_SetSabersFromCVars( gentity_t *ent ) -{ - if ( g_saber->string - && g_saber->string[0] - && Q_stricmp( "none", g_saber->string ) - && Q_stricmp( "NULL", g_saber->string ) ) - {//FIXME: how to specify second saber? - WP_SaberParseParms( g_saber->string, &ent->client->ps.saber[0] ); - if ( ent->client->ps.saber[0].stylesLearned ) - { +extern saber_colors_t TranslateSaberColor(const char *name); +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); +void G_ChangePlayerModel(gentity_t *ent, const char *newModel); +void G_SetSabersFromCVars(gentity_t *ent) { + if (g_saber->string && g_saber->string[0] && Q_stricmp("none", g_saber->string) && + Q_stricmp("NULL", g_saber->string)) { // FIXME: how to specify second saber? + WP_SaberParseParms(g_saber->string, &ent->client->ps.saber[0]); + if (ent->client->ps.saber[0].stylesLearned) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[0].stylesLearned; } - if ( ent->client->ps.saber[0].singleBladeStyle ) - { + if (ent->client->ps.saber[0].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[0].singleBladeStyle; } } - if ( player - && player->client - && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2 - && g_saberDarkSideSaberColor->integer ) - {//dark side! - //always use red - for ( int n = 0; n < MAX_BLADES; n++ ) - { + if (player && player->client && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2 && g_saberDarkSideSaberColor->integer) { // dark side! + // always use red + for (int n = 0; n < MAX_BLADES; n++) { ent->client->ps.saber[0].blade[n].color = SABER_RED; } - } - else if ( g_saber_color->string ) - {//FIXME: how to specify color for each blade and/or color for second saber? - saber_colors_t color = TranslateSaberColor( g_saber_color->string ); - for ( int n = 0; n < MAX_BLADES; n++ ) - { + } else if (g_saber_color->string) { // FIXME: how to specify color for each blade and/or color for second saber? + saber_colors_t color = TranslateSaberColor(g_saber_color->string); + for (int n = 0; n < MAX_BLADES; n++) { ent->client->ps.saber[0].blade[n].color = color; } } - if ( g_saber2->string - && g_saber2->string[0] - && Q_stricmp( "none", g_saber2->string ) - && Q_stricmp( "NULL", g_saber2->string ) ) - { - if ( !(ent->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - {//can't use a second saber if first one is a two-handed saber...? - WP_SaberParseParms( g_saber2->string, &ent->client->ps.saber[1] ); - if ( ent->client->ps.saber[1].stylesLearned ) - { + if (g_saber2->string && g_saber2->string[0] && Q_stricmp("none", g_saber2->string) && Q_stricmp("NULL", g_saber2->string)) { + if (!(ent->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { // can't use a second saber if first one is a two-handed saber...? + WP_SaberParseParms(g_saber2->string, &ent->client->ps.saber[1]); + if (ent->client->ps.saber[1].stylesLearned) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].stylesLearned; } - if ( ent->client->ps.saber[1].singleBladeStyle ) - { + if (ent->client->ps.saber[1].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].singleBladeStyle; } - if ( (ent->client->ps.saber[1].saberFlags&SFL_TWO_HANDED) ) - {//tsk tsk, can't use a twoHanded saber as second saber - WP_RemoveSaber( ent, 1 ); - } - else - { + if ((ent->client->ps.saber[1].saberFlags & SFL_TWO_HANDED)) { // tsk tsk, can't use a twoHanded saber as second saber + WP_RemoveSaber(ent, 1); + } else { ent->client->ps.dualSabers = qtrue; - if ( player - && player->client - && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2 - && g_saberDarkSideSaberColor->integer ) - {//dark side! - //always use red - for ( int n = 0; n < MAX_BLADES; n++ ) - { + if (player && player->client && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2 && + g_saberDarkSideSaberColor->integer) { // dark side! + // always use red + for (int n = 0; n < MAX_BLADES; n++) { ent->client->ps.saber[1].blade[n].color = SABER_RED; } - } - else if ( g_saber2_color->string ) - {//FIXME: how to specify color for each blade and/or color for second saber? - saber_colors_t color = TranslateSaberColor( g_saber2_color->string ); - for ( int n = 0; n < MAX_BLADES; n++ ) - { + } else if (g_saber2_color->string) { // FIXME: how to specify color for each blade and/or color for second saber? + saber_colors_t color = TranslateSaberColor(g_saber2_color->string); + for (int n = 0; n < MAX_BLADES; n++) { ent->client->ps.saber[1].blade[n].color = color; } } @@ -1931,49 +1619,45 @@ void G_SetSabersFromCVars( gentity_t *ent ) } } -void G_InitPlayerFromCvars( gentity_t *ent ) -{ - //set model based on cvars - if(Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && Q_stricmp(g_char_skin_legs->string, "model_default") == 0) - G_ChangePlayerModel( ent, va("%s|model_default", g_char_model->string) ); +void G_InitPlayerFromCvars(gentity_t *ent) { + // set model based on cvars + if (Q_stricmp(g_char_skin_head->string, "model_default") == 0 && Q_stricmp(g_char_skin_torso->string, "model_default") == 0 && + Q_stricmp(g_char_skin_legs->string, "model_default") == 0) + G_ChangePlayerModel(ent, va("%s|model_default", g_char_model->string)); else - G_ChangePlayerModel( ent, va("%s|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string) ); + G_ChangePlayerModel(ent, va("%s|%s|%s|%s", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string)); - //FIXME: parse these 2 from some cvar or require playermodel to be in a *.npc? - if( ent->NPC_type && gi.bIsFromZone(ent->NPC_type, TAG_G_ALLOC) ) { + // FIXME: parse these 2 from some cvar or require playermodel to be in a *.npc? + if (ent->NPC_type && gi.bIsFromZone(ent->NPC_type, TAG_G_ALLOC)) { gi.Free(ent->NPC_type); } // Bad casting I know, but NPC_type can also come the memory manager, // and you can't free a const-pointer later on. This seemed like the // better options. - ent->NPC_type = (char *)"player";//default for now - if( ent->client->clientInfo.customBasicSoundDir && gi.bIsFromZone(ent->client->clientInfo.customBasicSoundDir, TAG_G_ALLOC) ) { + ent->NPC_type = (char *)"player"; // default for now + if (ent->client->clientInfo.customBasicSoundDir && gi.bIsFromZone(ent->client->clientInfo.customBasicSoundDir, TAG_G_ALLOC)) { gi.Free(ent->client->clientInfo.customBasicSoundDir); } char snd[512]; - gi.Cvar_VariableStringBuffer( "snd", snd, sizeof(snd) ); - - ent->client->clientInfo.customBasicSoundDir = G_NewString(snd); //copy current cvar - - //set the lightsaber - G_RemoveWeaponModels( ent ); - G_SetSabersFromCVars( ent ); - //set up weapon models, etc. - G_AddWeaponModels( ent ); - NPC_SetAnim( ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - NPC_SetAnim( ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - if ( !ent->s.number ) - {//the actual player, not an NPC pretending to be a player - ClientUserinfoChanged( ent->s.number ); - } - //color tinting - //FIXME: the customRGBA shouldn't be set if the shader this guys .skin is using doesn't have the tinting on it - if ( g_char_color_red->integer - || g_char_color_green->integer - || g_char_color_blue->integer ) - { + gi.Cvar_VariableStringBuffer("snd", snd, sizeof(snd)); + + ent->client->clientInfo.customBasicSoundDir = G_NewString(snd); // copy current cvar + + // set the lightsaber + G_RemoveWeaponModels(ent); + G_SetSabersFromCVars(ent); + // set up weapon models, etc. + G_AddWeaponModels(ent); + NPC_SetAnim(ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + NPC_SetAnim(ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + if (!ent->s.number) { // the actual player, not an NPC pretending to be a player + ClientUserinfoChanged(ent->s.number); + } + // color tinting + // FIXME: the customRGBA shouldn't be set if the shader this guys .skin is using doesn't have the tinting on it + if (g_char_color_red->integer || g_char_color_green->integer || g_char_color_blue->integer) { ent->client->renderInfo.customRGBA[0] = g_char_color_red->integer; ent->client->renderInfo.customRGBA[1] = g_char_color_green->integer; ent->client->renderInfo.customRGBA[2] = g_char_color_blue->integer; @@ -1981,103 +1665,81 @@ void G_InitPlayerFromCvars( gentity_t *ent ) } } -void G_ChangePlayerModel( gentity_t *ent, const char *newModel ) -{ - if ( !ent || !ent->client || !newModel ) - { +void G_ChangePlayerModel(gentity_t *ent, const char *newModel) { + if (!ent || !ent->client || !newModel) { return; } - G_RemovePlayerModel( ent ); - if ( Q_stricmp( "player", newModel ) == 0 ) - { - G_InitPlayerFromCvars( ent ); + G_RemovePlayerModel(ent); + if (Q_stricmp("player", newModel) == 0) { + G_InitPlayerFromCvars(ent); return; } - //attempt to free the string (currently can't since it's always "player" ) - if( ent->NPC_type && gi.bIsFromZone(ent->NPC_type, TAG_G_ALLOC) ) { + // attempt to free the string (currently can't since it's always "player" ) + if (ent->NPC_type && gi.bIsFromZone(ent->NPC_type, TAG_G_ALLOC)) { gi.Free(ent->NPC_type); } - ent->NPC_type = G_NewString( newModel ); - G_RemoveWeaponModels( ent ); + ent->NPC_type = G_NewString(newModel); + G_RemoveWeaponModels(ent); - if ( strchr(newModel,'|') ) - { + if (strchr(newModel, '|')) { char name[MAX_QPATH]; strcpy(name, newModel); char *p = strchr(name, '|'); - *p=0; + *p = 0; p++; - if ( strstr(p, "model_default" ) ) - G_SetG2PlayerModel( ent, name, NULL, NULL, NULL ); + if (strstr(p, "model_default")) + G_SetG2PlayerModel(ent, name, NULL, NULL, NULL); else - G_SetG2PlayerModel( ent, name, p, NULL, NULL ); - } - else - { - //FIXME: everything but force powers gets reset, those should, too... + G_SetG2PlayerModel(ent, name, p, NULL, NULL); + } else { + // FIXME: everything but force powers gets reset, those should, too... // currently leaves them as is except where otherwise noted in the NPCs.cfg? - //FIXME: remove all weapons? - if ( NPC_ParseParms( ent->NPC_type, ent ) ) - { - G_AddWeaponModels( ent ); - NPC_SetAnim( ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - NPC_SetAnim( ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - ClientUserinfoChanged( ent->s.number ); - //Ugh, kind of a hack for now: - if ( ent->client->NPC_class == CLASS_BOBAFETT - || ent->client->NPC_class == CLASS_ROCKETTROOPER ) - { - //FIXME: remove saber, too? - Boba_Precache(); // player as boba? - } - } - else - { - gi.Printf( S_COLOR_RED"G_ChangePlayerModel: cannot find NPC %s\n", newModel ); - G_ChangePlayerModel( ent, "stormtrooper" ); //need a better fallback? + // FIXME: remove all weapons? + if (NPC_ParseParms(ent->NPC_type, ent)) { + G_AddWeaponModels(ent); + NPC_SetAnim(ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + NPC_SetAnim(ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + ClientUserinfoChanged(ent->s.number); + // Ugh, kind of a hack for now: + if (ent->client->NPC_class == CLASS_BOBAFETT || ent->client->NPC_class == CLASS_ROCKETTROOPER) { + // FIXME: remove saber, too? + Boba_Precache(); // player as boba? + } + } else { + gi.Printf(S_COLOR_RED "G_ChangePlayerModel: cannot find NPC %s\n", newModel); + G_ChangePlayerModel(ent, "stormtrooper"); // need a better fallback? } } } -void G_ReloadSaberData( gentity_t *ent ) -{ - //dualSabers should already be set - if ( ent->client->ps.saber[0].name != NULL ) - { - WP_SaberParseParms( ent->client->ps.saber[0].name, &ent->client->ps.saber[0], qfalse ); - if ( ent->client->ps.saber[0].stylesLearned ) - { +void G_ReloadSaberData(gentity_t *ent) { + // dualSabers should already be set + if (ent->client->ps.saber[0].name != NULL) { + WP_SaberParseParms(ent->client->ps.saber[0].name, &ent->client->ps.saber[0], qfalse); + if (ent->client->ps.saber[0].stylesLearned) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[0].stylesLearned; } - if ( ent->client->ps.saber[0].singleBladeStyle ) - { + if (ent->client->ps.saber[0].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[0].singleBladeStyle; } } - if ( ent->client->ps.saber[1].name != NULL ) - { - WP_SaberParseParms( ent->client->ps.saber[1].name, &ent->client->ps.saber[1], qfalse ); - if ( ent->client->ps.saber[1].stylesLearned ) - { + if (ent->client->ps.saber[1].name != NULL) { + WP_SaberParseParms(ent->client->ps.saber[1].name, &ent->client->ps.saber[1], qfalse); + if (ent->client->ps.saber[1].stylesLearned) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].stylesLearned; } - if ( ent->client->ps.saber[1].singleBladeStyle ) - { + if (ent->client->ps.saber[1].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].singleBladeStyle; } } } -qboolean G_PlayerSpawned( void ) -{ - if ( !player - || !player->client - || player->client->pers.teamState.state != TEAM_ACTIVE - || level.time - player->client->pers.enterTime < 100 ) - {//player hasn't spawned yet +qboolean G_PlayerSpawned(void) { + if (!player || !player->client || player->client->pers.teamState.state != TEAM_ACTIVE || + level.time - player->client->pers.enterTime < 100) { // player hasn't spawned yet return qfalse; } return qtrue; @@ -2093,49 +1755,44 @@ Initializes all non-persistant parts of playerState ============ */ -qboolean G_CheckPlayerDarkSide( void ) -{ - if ( player && player->client && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2 ) - {//dark side player! +qboolean G_CheckPlayerDarkSide(void) { + if (player && player->client && player->client->sess.mission_objectives[LIGHTSIDE_OBJ].status == 2) { // dark side player! player->client->playerTeam = TEAM_FREE; player->client->enemyTeam = TEAM_FREE; - if ( g_saberDarkSideSaberColor->integer ) - {//dark side! - //always use red - for ( int n = 0; n < MAX_BLADES; n++ ) - { + if (g_saberDarkSideSaberColor->integer) { // dark side! + // always use red + for (int n = 0; n < MAX_BLADES; n++) { player->client->ps.saber[0].blade[n].color = player->client->ps.saber[1].blade[n].color = SABER_RED; } } - G_SoundIndex( "sound/chars/jedi2/28je2008.wav" ); - G_SoundIndex( "sound/chars/jedi2/28je2009.wav" ); - G_SoundIndex( "sound/chars/jedi2/28je2012.wav" ); + G_SoundIndex("sound/chars/jedi2/28je2008.wav"); + G_SoundIndex("sound/chars/jedi2/28je2009.wav"); + G_SoundIndex("sound/chars/jedi2/28je2012.wav"); return qtrue; } return qfalse; } -void G_ChangePlayerModel( gentity_t *ent, const char *newModel ); -qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ) -{ - int index; - vec3_t spawn_origin, spawn_angles; - gclient_t *client; - int i; - clientPersistant_t saved; - clientSession_t savedSess; - clientInfo_t savedCi; - int persistant[MAX_PERSISTANT]; - usercmd_t ucmd; - gentity_t *spawnPoint; - qboolean beamInEffect = qfalse; +void G_ChangePlayerModel(gentity_t *ent, const char *newModel); +qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded) { + int index; + vec3_t spawn_origin, spawn_angles; + gclient_t *client; + int i; + clientPersistant_t saved; + clientSession_t savedSess; + clientInfo_t savedCi; + int persistant[MAX_PERSISTANT]; + usercmd_t ucmd; + gentity_t *spawnPoint; + qboolean beamInEffect = qfalse; extern qboolean g_qbLoadTransition; index = ent - g_entities; client = ent->client; - if ( eSavedGameJustLoaded == eFULL && g_qbLoadTransition == qfalse )//qbFromSavedGame) - {//loading up a full save game + if (eSavedGameJustLoaded == eFULL && g_qbLoadTransition == qfalse) // qbFromSavedGame) + { // loading up a full save game ent->client->pers.teamState.state = TEAM_ACTIVE; // increment the spawncount so the client will detect the respawn @@ -2144,71 +1801,61 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->airOutTime = level.time + 12000; - for (i=0; i<3; i++) - { + for (i = 0; i < 3; i++) { ent->client->pers.cmd_angles[i] = 0.0f; } - SetClientViewAngle( ent, ent->client->ps.viewangles);//spawn_angles ); + SetClientViewAngle(ent, ent->client->ps.viewangles); // spawn_angles ); - gi.linkentity (ent); + gi.linkentity(ent); // run the presend to set anything else - ClientEndFrame( ent ); + ClientEndFrame(ent); // clear entity state values - PlayerStateToEntityState( &client->ps, &ent->s ); + PlayerStateToEntityState(&client->ps, &ent->s); // ALL OF MY RAGE... they decided it would be a great idea to treat NPC_type like a player model here, // which is all kinds of unbelievable. I will be having a stern talk with James later. --eez - if( ent->NPC_type && - Q_stricmp( ent->NPC_type, "player" ) ) - { + if (ent->NPC_type && Q_stricmp(ent->NPC_type, "player")) { // FIXME: game doesn't like it when you pass ent->NPC_type into this func. Insert all kinds of noises here --eez char bleh[MAX_SPAWN_VARS_CHARS]; Q_strncpyz(bleh, ent->NPC_type, sizeof(bleh)); - G_ChangePlayerModel( ent, bleh ); - } - else - { - G_LoadAnimFileSet( ent, ent->NPC_type ); - G_SetSkin( ent ); + G_ChangePlayerModel(ent, bleh); + } else { + G_LoadAnimFileSet(ent, ent->NPC_type); + G_SetSkin(ent); } - //setup sabers - G_ReloadSaberData( ent ); - //force power levels should already be set - } - else - { + // setup sabers + G_ReloadSaberData(ent); + // force power levels should already be set + } else { // find a spawn point // do it before setting health back up, so farthest // ranging doesn't count this client // don't spawn near existing origin if possible - spawnPoint = SelectSpawnPoint ( ent->client->ps.origin, - (team_t) ent->client->ps.persistant[PERS_TEAM], spawn_origin, spawn_angles); + spawnPoint = SelectSpawnPoint(ent->client->ps.origin, (team_t)ent->client->ps.persistant[PERS_TEAM], spawn_origin, spawn_angles); ent->client->pers.teamState.state = TEAM_ACTIVE; // clear everything but the persistant data saved = client->pers; savedSess = client->sess; - for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) - { + for (i = 0; i < MAX_PERSISTANT; i++) { persistant[i] = client->ps.persistant[i]; } - //Preserve clientInfo - memcpy (&savedCi, &client->clientInfo, sizeof(clientInfo_t)); + // Preserve clientInfo + memcpy(&savedCi, &client->clientInfo, sizeof(clientInfo_t)); - memset (client, 0, sizeof(*client)); + memset(client, 0, sizeof(*client)); - memcpy (&client->clientInfo, &savedCi, sizeof(clientInfo_t)); + memcpy(&client->clientInfo, &savedCi, sizeof(clientInfo_t)); client->pers = saved; client->sess = savedSess; - for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) - { + for (i = 0; i < MAX_PERSISTANT; i++) { client->ps.persistant[i] = persistant[i]; } @@ -2227,14 +1874,12 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ent->inuse = qtrue; SetInUse(ent); ent->m_iIcarusID = IIcarusInterface::ICARUS_INVALID; - if ( !ent->NPC_type ) - { + if (!ent->NPC_type) { ent->NPC_type = (char *)"player"; } ent->classname = "player"; ent->targetname = ent->script_targetname = "player"; - if ( ent->client->NPC_class == CLASS_NONE ) - { + if (ent->client->NPC_class == CLASS_NONE) { ent->client->NPC_class = CLASS_PLAYER; } client->playerTeam = TEAM_PLAYER; @@ -2251,61 +1896,55 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->renderInfo.lookTargetClearTime = 0; client->renderInfo.lookMode = LM_ENT; - VectorCopy (playerMins, ent->mins); - VectorCopy (playerMaxs, ent->maxs); + VectorCopy(playerMins, ent->mins); + VectorCopy(playerMaxs, ent->maxs); client->crouchheight = CROUCH_MAXS_2; client->standheight = DEFAULT_MAXS_2; client->ps.clientNum = index; // give default weapons - //these are precached in g_items, ClearRegisteredItems() - client->ps.stats[STAT_WEAPONS] = ( 1 << WP_NONE ); - //client->ps.inventory[INV_ELECTROBINOCULARS] = 1; - //ent->client->ps.inventory[INV_BACTA_CANISTER] = 1; + // these are precached in g_items, ClearRegisteredItems() + client->ps.stats[STAT_WEAPONS] = (1 << WP_NONE); + // client->ps.inventory[INV_ELECTROBINOCULARS] = 1; + // ent->client->ps.inventory[INV_BACTA_CANISTER] = 1; // give EITHER the saber or the stun baton..never both - if ( spawnPoint->spawnflags & 32 ) // STUN_BATON + if (spawnPoint->spawnflags & 32) // STUN_BATON { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_STUN_BATON ); + client->ps.stats[STAT_WEAPONS] |= (1 << WP_STUN_BATON); client->ps.weapon = WP_STUN_BATON; - } - else - { // give the saber because most test maps will not have the STUN BATON flag set - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_SABER ); //this is precached in SP_info_player_deathmatch + } else { // give the saber because most test maps will not have the STUN BATON flag set + client->ps.stats[STAT_WEAPONS] |= (1 << WP_SABER); // this is precached in SP_info_player_deathmatch client->ps.weapon = WP_SABER; } // force the base weapon up client->ps.weaponstate = WEAPON_READY; - for ( i = FIRST_WEAPON; i < MAX_PLAYER_WEAPONS; i++ ) // don't give ammo for explosives + for (i = FIRST_WEAPON; i < MAX_PLAYER_WEAPONS; i++) // don't give ammo for explosives { - if ( (client->ps.stats[STAT_WEAPONS]&(1<ps.stats[STAT_WEAPONS] & (1 << i))) { // if starting with this weapon, gimme max ammo for it client->ps.ammo[weaponData[i].ammoIndex] = ammoData[weaponData[i].ammoIndex].max; } } - if ( eSavedGameJustLoaded == eNO ) - { - //FIXME: get player's info from NPCs.cfg + if (eSavedGameJustLoaded == eNO) { + // FIXME: get player's info from NPCs.cfg client->ps.dualSabers = qfalse; - WP_SaberParseParms( g_saber->string, &client->ps.saber[0] );//get saber info + WP_SaberParseParms(g_saber->string, &client->ps.saber[0]); // get saber info - client->ps.saberStylesKnown |= (1<ps.saberStylesKnown |= (1 << gi.Cvar_VariableIntegerValue("g_fighting_style")); -// if ( client->ps.saber[0].stylesLearned ) -// { -// client->ps.saberStylesKnown |= client->ps.saber[0].stylesLearned; -// } -// if ( ent->client->ps.saber[1].singleSaberStyle ) -// { -// ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].singleSaberStyle; -// } - WP_InitForcePowers( ent );//Initialize force powers - } - else - {//autoload, will be taken care of below + // if ( client->ps.saber[0].stylesLearned ) + // { + // client->ps.saberStylesKnown |= client->ps.saber[0].stylesLearned; + // } + // if ( ent->client->ps.saber[1].singleSaberStyle ) + // { + // ent->client->ps.saberStylesKnown |= ent->client->ps.saber[1].singleSaberStyle; + // } + WP_InitForcePowers(ent); // Initialize force powers + } else { // autoload, will be taken care of below } // @@ -2318,16 +1957,16 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ent->client->ps.batteryCharge = 2500; - VectorCopy( spawn_origin, client->ps.origin ); - VectorCopy( spawn_origin, ent->currentOrigin ); + VectorCopy(spawn_origin, client->ps.origin); + VectorCopy(spawn_origin, ent->currentOrigin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; - SetClientViewAngle( ent, spawn_angles ); + SetClientViewAngle(ent, spawn_angles); - G_KillBox( ent ); - gi.linkentity (ent); + G_KillBox(ent); + gi.linkentity(ent); // don't allow full run speed for a bit client->ps.pm_flags |= PMF_TIME_KNOCKBACK; @@ -2340,98 +1979,89 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->ps.torsoAnim = BOTH_STAND2; client->ps.legsAnim = BOTH_STAND2; - //clear IK grabbing stuff + // clear IK grabbing stuff client->ps.heldClient = client->ps.heldByClient = ENTITYNUM_NONE; - client->ps.saberLockEnemy = ENTITYNUM_NONE; //duh, don't think i'm locking with myself + client->ps.saberLockEnemy = ENTITYNUM_NONE; // duh, don't think i'm locking with myself // restore some player data // Player_RestoreFromPrevLevel(ent, eSavedGameJustLoaded); - //FIXME: put this BEFORE the Player_RestoreFromPrevLevel check above? - if (eSavedGameJustLoaded == eNO) - {//fresh start - if (!(spawnPoint->spawnflags&1)) // not KEEP_PREV - {//then restore health and armor + // FIXME: put this BEFORE the Player_RestoreFromPrevLevel check above? + if (eSavedGameJustLoaded == eNO) { // fresh start + if (!(spawnPoint->spawnflags & 1)) // not KEEP_PREV + { // then restore health and armor ent->health = client->ps.stats[STAT_ARMOR] = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH]; ent->client->ps.forcePower = ent->client->ps.forcePowerMax; } - G_InitPlayerFromCvars( ent ); - } - else - {//autoload - if( ent->NPC_type && - Q_stricmp( ent->NPC_type, "player" ) ) - { + G_InitPlayerFromCvars(ent); + } else { // autoload + if (ent->NPC_type && Q_stricmp(ent->NPC_type, "player")) { // FIXME: game doesn't like it when you pass ent->NPC_type into this func. Insert all kinds of noises here --eez char bleh[MAX_SPAWN_VARS_CHARS]; Q_strncpyz(bleh, ent->NPC_type, sizeof(bleh)); - G_ChangePlayerModel( ent, bleh ); + G_ChangePlayerModel(ent, bleh); + } else { + G_LoadAnimFileSet(ent, ent->NPC_type); + G_SetSkin(ent); } - else - { - G_LoadAnimFileSet( ent, ent->NPC_type ); - G_SetSkin( ent ); - } - G_ReloadSaberData( ent ); - //force power levels should already be set + G_ReloadSaberData(ent); + // force power levels should already be set } - //NEVER start a map with either of your sabers or blades on... + // NEVER start a map with either of your sabers or blades on... ent->client->ps.SaberDeactivate(); // run a client frame to drop exactly to the floor, // initialize animations and other things client->ps.commandTime = level.time - 100; ucmd = client->pers.lastCommand; ucmd.serverTime = level.time; - VectorCopyM( client->pers.cmd_angles, ucmd.angles ); - ucmd.weapon = client->ps.weapon; // client think calls Pmove which sets the client->ps.weapon to ucmd.weapon, so ... + VectorCopyM(client->pers.cmd_angles, ucmd.angles); + ucmd.weapon = client->ps.weapon; // client think calls Pmove which sets the client->ps.weapon to ucmd.weapon, so ... ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - ClientThink( ent-g_entities, &ucmd ); + ClientThink(ent - g_entities, &ucmd); // run the presend to set anything else - ClientEndFrame( ent ); + ClientEndFrame(ent); // clear entity state values - PlayerStateToEntityState( &client->ps, &ent->s ); + PlayerStateToEntityState(&client->ps, &ent->s); - //ICARUS include - Quake3Game()->FreeEntity( ent ); - Quake3Game()->InitEntity( ent ); + // ICARUS include + Quake3Game()->FreeEntity(ent); + Quake3Game()->InitEntity(ent); // Make sure no Sequencer exists then Get a new one. - IIcarusInterface::GetIcarus()->DeleteIcarusID( ent->m_iIcarusID ); - ent->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID( ent->s.number ); + IIcarusInterface::GetIcarus()->DeleteIcarusID(ent->m_iIcarusID); + ent->m_iIcarusID = IIcarusInterface::GetIcarus()->GetIcarusID(ent->s.number); - if ( spawnPoint->spawnflags & 64 ) //NOWEAPON - {//player starts with absolutely no weapons - ent->client->ps.stats[STAT_WEAPONS] = ( 1 << WP_NONE ); + if (spawnPoint->spawnflags & 64) // NOWEAPON + { // player starts with absolutely no weapons + ent->client->ps.stats[STAT_WEAPONS] = (1 << WP_NONE); ent->client->ps.ammo[weaponData[WP_NONE].ammoIndex] = 32000; ent->client->ps.weapon = WP_NONE; ent->client->ps.weaponstate = WEAPON_READY; ent->client->ps.dualSabers = qfalse; } - if ( ent->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_SABER ) ) - {//set up so has lightsaber - WP_SaberInitBladeData( ent ); - if ( (ent->weaponModel[0] <= 0 || (ent->weaponModel[1]<=0&&ent->client->ps.dualSabers)) //one or both of the saber models is not initialized - && ent->client->ps.weapon == WP_SABER )//current weapon is saber - {//add the proper models - WP_SaberAddG2SaberModels( ent ); + if (ent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { // set up so has lightsaber + WP_SaberInitBladeData(ent); + if ((ent->weaponModel[0] <= 0 || (ent->weaponModel[1] <= 0 && ent->client->ps.dualSabers)) // one or both of the saber models is not initialized + && ent->client->ps.weapon == WP_SABER) // current weapon is saber + { // add the proper models + WP_SaberAddG2SaberModels(ent); } } - if ( ent->weaponModel[0] == -1 && ent->client->ps.weapon != WP_NONE ) - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + if (ent->weaponModel[0] == -1 && ent->client->ps.weapon != WP_NONE) { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } { // fire the targets of the spawn point - G_UseTargets( spawnPoint, ent ); - //Designers needed them to fire off target2's as well... this is kind of messy - G_UseTargets2( spawnPoint, ent, spawnPoint->target2 ); + G_UseTargets(spawnPoint, ent); + // Designers needed them to fire off target2's as well... this is kind of messy + G_UseTargets2(spawnPoint, ent, spawnPoint->target2); /* // select the highest weapon number available, after any @@ -2446,30 +2076,26 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded } } - client->pers.enterTime = level.time;//needed mainly to stop the weapon switch to WP_NONE that happens on loads + client->pers.enterTime = level.time; // needed mainly to stop the weapon switch to WP_NONE that happens on loads ent->max_health = client->ps.stats[STAT_MAX_HEALTH]; - if ( eSavedGameJustLoaded == eNO ) - {//on map transitions, Ghoul2 frame gets reset to zero, restart our anim - NPC_SetAnim( ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - NPC_SetAnim( ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); + if (eSavedGameJustLoaded == eNO) { // on map transitions, Ghoul2 frame gets reset to zero, restart our anim + NPC_SetAnim(ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + NPC_SetAnim(ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); } - if ( ent->s.number == 0 ) - {//player + if (ent->s.number == 0) { // player G_CheckPlayerDarkSide(); } - if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<client->ps.saberStylesKnown ) - {//um, if you have a saber, you need at least 1 style to use it with... - ent->client->ps.saberStylesKnown |= (1<client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) && + !ent->client->ps.saberStylesKnown) { // um, if you have a saber, you need at least 1 style to use it with... + ent->client->ps.saberStylesKnown |= (1 << SS_MEDIUM); } return beamInEffect; } - /* =========== ClientDisconnect @@ -2478,22 +2104,22 @@ Called when a player drops from the server. Will not be called between levels. ============ */ -void ClientDisconnect( int clientNum ) { - gentity_t *ent; +void ClientDisconnect(int clientNum) { + gentity_t *ent; ent = g_entities + clientNum; - if ( !ent->client ) { + if (!ent->client) { return; } // send effect if they were completely connected -/* if ( ent->client->pers.connected == CON_CONNECTED ) { - // They don't get to take powerups with them! - // Especially important for stuff like CTF flags - TossClientItems ( ent ); - } -*/ - gi.unlinkentity (ent); + /* if ( ent->client->pers.connected == CON_CONNECTED ) { + // They don't get to take powerups with them! + // Especially important for stuff like CTF flags + TossClientItems ( ent ); + } + */ + gi.unlinkentity(ent); ent->s.modelindex = 0; ent->inuse = qfalse; ClearInUse(ent); @@ -2501,11 +2127,7 @@ void ClientDisconnect( int clientNum ) { ent->client->pers.connected = CON_DISCONNECTED; ent->client->ps.persistant[PERS_TEAM] = TEAM_FREE; - gi.SetConfigstring( CS_PLAYERS + clientNum, ""); + gi.SetConfigstring(CS_PLAYERS + clientNum, ""); IIcarusInterface::GetIcarus()->DeleteIcarusID(ent->m_iIcarusID); - } - - - diff --git a/code/game/g_cmds.cpp b/code/game/g_cmds.cpp index f0a7a62a5a..78ead28d16 100644 --- a/code/game/g_cmds.cpp +++ b/code/game/g_cmds.cpp @@ -29,61 +29,60 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "b_local.h" -extern bool in_camera; +extern bool in_camera; extern stringID_table_t SaberStyleTable[]; -extern void ForceHeal( gentity_t *self ); -extern void ForceGrip( gentity_t *self ); -extern void ForceTelepathy( gentity_t *self ); -extern void ForceRage( gentity_t *self ); -extern void ForceProtect( gentity_t *self ); -extern void ForceAbsorb( gentity_t *self ); -extern void ForceSeeing( gentity_t *self ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *psWeaponModel, int boltNum, int weaponNum ); -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); +extern void ForceHeal(gentity_t *self); +extern void ForceGrip(gentity_t *self); +extern void ForceTelepathy(gentity_t *self); +extern void ForceRage(gentity_t *self); +extern void ForceProtect(gentity_t *self); +extern void ForceAbsorb(gentity_t *self); +extern void ForceSeeing(gentity_t *self); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *psWeaponModel, int boltNum, int weaponNum); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); extern void ItemUse_Bacta(gentity_t *ent); -extern gentity_t *G_GetSelfForPlayerCmd( void ); +extern gentity_t *G_GetSelfForPlayerCmd(void); /* ================== CheatsOk ================== */ -qboolean CheatsOk( gentity_t *ent ) { - if ( !g_cheats->integer ) { - gi.SendServerCommand( ent-g_entities, "print \"Cheats are not enabled on this server.\n\""); +qboolean CheatsOk(gentity_t *ent) { + if (!g_cheats->integer) { + gi.SendServerCommand(ent - g_entities, "print \"Cheats are not enabled on this server.\n\""); return qfalse; } - if ( ent->health <= 0 ) { - gi.SendServerCommand( ent-g_entities, "print \"You must be alive to use this command.\n\""); + if (ent->health <= 0) { + gi.SendServerCommand(ent - g_entities, "print \"You must be alive to use this command.\n\""); return qfalse; } return qtrue; } - /* ================== ConcatArgs ================== */ -char *ConcatArgs( int start ) { - int i, c, tlen; - static char line[MAX_STRING_CHARS]; - int len; - const char *arg; +char *ConcatArgs(int start) { + int i, c, tlen; + static char line[MAX_STRING_CHARS]; + int len; + const char *arg; len = 0; c = gi.argc(); - for ( i = start ; i < c ; i++ ) { - arg = gi.argv( i ); - tlen = strlen( arg ); - if ( len + tlen >= MAX_STRING_CHARS - 1 ) { + for (i = start; i < c; i++) { + arg = gi.argv(i); + tlen = strlen(arg); + if (len + tlen >= MAX_STRING_CHARS - 1) { break; } - memcpy( line + len, arg, tlen ); + memcpy(line + len, arg, tlen); len += tlen; - if ( i != c - 1 ) { + if (i != c - 1) { line[len] = ' '; len++; } @@ -101,17 +100,17 @@ SanitizeString Remove case and control characters ================== */ -void SanitizeString( char *in, char *out ) { - while ( *in ) { - if ( *in == 94 ) { - in += 2; // skip color code +void SanitizeString(char *in, char *out) { + while (*in) { + if (*in == 94) { + in += 2; // skip color code continue; } - if ( *in < 32 ) { + if (*in < 32) { in++; continue; } - *out++ = tolower( *in++ ); + *out++ = tolower(*in++); } *out = 0; @@ -125,119 +124,111 @@ Returns a player number for either a number or name string Returns -1 if invalid ================== */ -int ClientNumberFromString( gentity_t *to, char *s ) { - gclient_t *cl; - int idnum; - char s2[MAX_STRING_CHARS]; - char n2[MAX_STRING_CHARS]; +int ClientNumberFromString(gentity_t *to, char *s) { + gclient_t *cl; + int idnum; + char s2[MAX_STRING_CHARS]; + char n2[MAX_STRING_CHARS]; // numeric values are just slot numbers if (s[0] >= '0' && s[0] <= '9') { - idnum = atoi( s ); - if ( idnum < 0 || idnum >= level.maxclients ) { - gi.SendServerCommand( to-g_entities, "print \"Bad client slot: %i\n\"", idnum); + idnum = atoi(s); + if (idnum < 0 || idnum >= level.maxclients) { + gi.SendServerCommand(to - g_entities, "print \"Bad client slot: %i\n\"", idnum); return -1; } cl = &level.clients[idnum]; - if ( cl->pers.connected != CON_CONNECTED ) { - gi.SendServerCommand( to-g_entities, "print \"Client %i is not active\n\"", idnum); + if (cl->pers.connected != CON_CONNECTED) { + gi.SendServerCommand(to - g_entities, "print \"Client %i is not active\n\"", idnum); return -1; } return idnum; } // check for a name match - SanitizeString( s, s2 ); - for ( idnum=0,cl=level.clients ; idnum < level.maxclients ; idnum++,cl++ ) { - if ( cl->pers.connected != CON_CONNECTED ) { + SanitizeString(s, s2); + for (idnum = 0, cl = level.clients; idnum < level.maxclients; idnum++, cl++) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - SanitizeString( cl->pers.netname, n2 ); - if ( !strcmp( n2, s2 ) ) { + SanitizeString(cl->pers.netname, n2); + if (!strcmp(n2, s2)) { return idnum; } } - gi.SendServerCommand( to-g_entities, "print \"User %s is not on the server\n\"", s); + gi.SendServerCommand(to - g_entities, "print \"User %s is not on the server\n\"", s); return -1; } -void G_Give( gentity_t *ent, const char *name, const char *args, int argc ) -{ - gitem_t *it; - int i; - qboolean give_all = qfalse; +void G_Give(gentity_t *ent, const char *name, const char *args, int argc) { + gitem_t *it; + int i; + qboolean give_all = qfalse; - if ( !Q_stricmp( name, "all" ) ) + if (!Q_stricmp(name, "all")) give_all = qtrue; - if ( give_all || !Q_stricmp( name, "health") ) - { - if ( argc == 3 ) - ent->health = Com_Clampi( 1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); + if (give_all || !Q_stricmp(name, "health")) { + if (argc == 3) + ent->health = Com_Clampi(1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); else ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "armor" ) || !Q_stricmp( name, "shield" ) ) - { - if ( argc == 3 ) - ent->client->ps.stats[STAT_ARMOR] = Com_Clampi( 0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); + if (give_all || !Q_stricmp(name, "armor") || !Q_stricmp(name, "shield")) { + if (argc == 3) + ent->client->ps.stats[STAT_ARMOR] = Com_Clampi(0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); else ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "force" ) ) - { - if ( argc == 3 ) - ent->client->ps.forcePower = Com_Clampi( 0, ent->client->ps.forcePowerMax, atoi( args ) ); + if (give_all || !Q_stricmp(name, "force")) { + if (argc == 3) + ent->client->ps.forcePower = Com_Clampi(0, ent->client->ps.forcePowerMax, atoi(args)); else ent->client->ps.forcePower = ent->client->ps.forcePowerMax; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "weapons" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] = (1 << (WP_MELEE)) - ( 1 << WP_NONE ); - if ( !give_all ) + if (give_all || !Q_stricmp(name, "weapons")) { + ent->client->ps.stats[STAT_WEAPONS] = (1 << (WP_MELEE)) - (1 << WP_NONE); + if (!give_all) return; } - if ( !give_all && !Q_stricmp( name, "weaponnum" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi( args )); + if (!give_all && !Q_stricmp(name, "weaponnum")) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi(args)); return; } - if ( !give_all && !Q_stricmp( name, "eweaps" ) ) //for developing, gives you all the weapons, including enemy + if (!give_all && !Q_stricmp(name, "eweaps")) // for developing, gives you all the weapons, including enemy { - ent->client->ps.stats[STAT_WEAPONS] = (unsigned)(1 << WP_NUM_WEAPONS) - ( 1 << WP_NONE ); // NOTE: this wasn't giving the last weapon in the list + ent->client->ps.stats[STAT_WEAPONS] = (unsigned)(1 << WP_NUM_WEAPONS) - (1 << WP_NONE); // NOTE: this wasn't giving the last weapon in the list return; } - if ( give_all || !Q_stricmp( name, "ammo" ) ) - { + if (give_all || !Q_stricmp(name, "ammo")) { int num = 999; - if ( argc == 3 ) - num = Com_Clampi( -1, 999, atoi( args ) ); - for ( i=AMMO_BLASTER; iclient->ps.ammo[i] = num != -1 ? num : ammoData[i].max; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "batteries" ) ) - { - if ( argc == 3 ) - ent->client->ps.batteryCharge = Com_Clampi( 0, MAX_BATTERIES, atoi( args ) ); + if (give_all || !Q_stricmp(name, "batteries")) { + if (argc == 3) + ent->client->ps.batteryCharge = Com_Clampi(0, MAX_BATTERIES, atoi(args)); else ent->client->ps.batteryCharge = MAX_BATTERIES; @@ -246,170 +237,136 @@ void G_Give( gentity_t *ent, const char *name, const char *args, int argc ) } // spawn a specific item right on the player - if ( !give_all ) { - gentity_t *it_ent; - trace_t trace; - it = FindItem (args); + if (!give_all) { + gentity_t *it_ent; + trace_t trace; + it = FindItem(args); if (!it) { - it = FindItem (name); + it = FindItem(name); if (!it) { - gi.SendServerCommand( ent-g_entities, "print \"unknown item\n\""); + gi.SendServerCommand(ent - g_entities, "print \"unknown item\n\""); return; } } it_ent = G_Spawn(); - VectorCopy( ent->currentOrigin, it_ent->s.origin ); + VectorCopy(ent->currentOrigin, it_ent->s.origin); it_ent->classname = G_NewString(it->classname); - G_SpawnItem (it_ent, it); - FinishSpawningItem(it_ent ); - memset( &trace, 0, sizeof( trace ) ); - Touch_Item (it_ent, ent, &trace); + G_SpawnItem(it_ent, it); + FinishSpawningItem(it_ent); + memset(&trace, 0, sizeof(trace)); + Touch_Item(it_ent, ent, &trace); if (it_ent->inuse) { - G_FreeEntity( it_ent ); + G_FreeEntity(it_ent); } } } -void Cmd_Give_f( gentity_t *ent ) -{ - if ( !CheatsOk( ent ) ) { +void Cmd_Give_f(gentity_t *ent) { + if (!CheatsOk(ent)) { return; } - G_Give( ent, gi.argv(1), ConcatArgs( 2 ), gi.argc() ); + G_Give(ent, gi.argv(1), ConcatArgs(2), gi.argc()); } //------------------ -void Cmd_Fx( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *fx_ent = NULL; +void Cmd_Fx(gentity_t *ent) { + vec3_t dir; + gentity_t *fx_ent = NULL; - if ( Q_stricmp( gi.argv(1), "play" ) == 0 ) - { - if ( gi.argc() == 3 ) - { + if (Q_stricmp(gi.argv(1), "play") == 0) { + if (gi.argc() == 3) { // I guess, only allow one active at a time - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - G_FreeEntity( fx_ent ); + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + G_FreeEntity(fx_ent); } fx_ent = G_Spawn(); - fx_ent->fxFile = gi.argv( 2 ); + fx_ent->fxFile = gi.argv(2); // Move out in front of the person spawning the effect - AngleVectors( ent->currentAngles, dir, NULL, NULL ); - VectorMA( ent->currentOrigin, 32, dir, fx_ent->s.origin ); + AngleVectors(ent->currentAngles, dir, NULL, NULL); + VectorMA(ent->currentOrigin, 32, dir, fx_ent->s.origin); -extern void SP_fx_runner( gentity_t *ent ); + extern void SP_fx_runner(gentity_t * ent); - SP_fx_runner( fx_ent ); - fx_ent->delay = 2000; // adjusting delay - fx_ent->classname = "cmd_fx"; // and classname + SP_fx_runner(fx_ent); + fx_ent->delay = 2000; // adjusting delay + fx_ent->classname = "cmd_fx"; // and classname return; } - } - else if ( Q_stricmp( gi.argv(1), "stop" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - G_FreeEntity( fx_ent ); + } else if (Q_stricmp(gi.argv(1), "stop") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + G_FreeEntity(fx_ent); } return; - } - else if ( Q_stricmp( gi.argv(1), "delay" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 3 ) - { - fx_ent->delay = atoi( gi.argv( 2 )); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current delay is: %i\n", fx_ent->delay ); + } else if (Q_stricmp(gi.argv(1), "delay") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 3) { + fx_ent->delay = atoi(gi.argv(2)); + } else { + gi.Printf(S_COLOR_GREEN "FX: current delay is: %i\n", fx_ent->delay); } return; } - } - else if ( Q_stricmp( gi.argv(1), "random" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 3 ) - { - fx_ent->random = atoi( gi.argv( 2 )); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current random is: %6.2f\n", fx_ent->random ); + } else if (Q_stricmp(gi.argv(1), "random") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 3) { + fx_ent->random = atoi(gi.argv(2)); + } else { + gi.Printf(S_COLOR_GREEN "FX: current random is: %6.2f\n", fx_ent->random); } return; } - } - else if ( Q_stricmp( gi.argv(1), "origin" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 5 ) - { - fx_ent->s.origin[0] = atof( gi.argv( 2 )); - fx_ent->s.origin[1] = atof( gi.argv( 3 )); - fx_ent->s.origin[2] = atof( gi.argv( 4 )); - - G_SetOrigin( fx_ent, fx_ent->s.origin ); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current origin is: <%6.2f %6.2f %6.2f>\n", - fx_ent->currentOrigin[0], fx_ent->currentOrigin[1], fx_ent->currentOrigin[2] ); + } else if (Q_stricmp(gi.argv(1), "origin") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 5) { + fx_ent->s.origin[0] = atof(gi.argv(2)); + fx_ent->s.origin[1] = atof(gi.argv(3)); + fx_ent->s.origin[2] = atof(gi.argv(4)); + + G_SetOrigin(fx_ent, fx_ent->s.origin); + } else { + gi.Printf(S_COLOR_GREEN "FX: current origin is: <%6.2f %6.2f %6.2f>\n", fx_ent->currentOrigin[0], fx_ent->currentOrigin[1], + fx_ent->currentOrigin[2]); } return; } - } - else if ( Q_stricmp( gi.argv(1), "dir" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 5 ) - { - fx_ent->s.angles[0] = atof( gi.argv( 2 )); - fx_ent->s.angles[1] = atof( gi.argv( 3 )); - fx_ent->s.angles[2] = atof( gi.argv( 4 )); - - if ( !VectorNormalize( fx_ent->s.angles )) - { + } else if (Q_stricmp(gi.argv(1), "dir") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 5) { + fx_ent->s.angles[0] = atof(gi.argv(2)); + fx_ent->s.angles[1] = atof(gi.argv(3)); + fx_ent->s.angles[2] = atof(gi.argv(4)); + + if (!VectorNormalize(fx_ent->s.angles)) { // must have been zero length fx_ent->s.angles[2] = 1; } - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current dir is: <%6.2f %6.2f %6.2f>\n", - fx_ent->s.angles[0], fx_ent->s.angles[1], fx_ent->s.angles[2] ); + } else { + gi.Printf(S_COLOR_GREEN "FX: current dir is: <%6.2f %6.2f %6.2f>\n", fx_ent->s.angles[0], fx_ent->s.angles[1], fx_ent->s.angles[2]); } return; } } - gi.Printf( S_COLOR_CYAN"Fx--------------------------------------------------------\n" ); - gi.Printf( S_COLOR_CYAN"commands: sample usage:\n" ); - gi.Printf( S_COLOR_CYAN"----------------------------------------------------------\n" ); - gi.Printf( S_COLOR_CYAN"fx play fx play sparks, fx play env/fire\n" ); - gi.Printf( S_COLOR_CYAN"fx stop fx stop\n" ); - gi.Printf( S_COLOR_CYAN"fx delay <#> fx delay 1000\n" ); - gi.Printf( S_COLOR_CYAN"fx random <#> fx random 200\n" ); - gi.Printf( S_COLOR_CYAN"fx origin <#><#><#> fx origin 10 20 30\n" ); - gi.Printf( S_COLOR_CYAN"fx dir <#><#><#> fx dir 0 0 -1\n\n" ); + gi.Printf(S_COLOR_CYAN "Fx--------------------------------------------------------\n"); + gi.Printf(S_COLOR_CYAN "commands: sample usage:\n"); + gi.Printf(S_COLOR_CYAN "----------------------------------------------------------\n"); + gi.Printf(S_COLOR_CYAN "fx play fx play sparks, fx play env/fire\n"); + gi.Printf(S_COLOR_CYAN "fx stop fx stop\n"); + gi.Printf(S_COLOR_CYAN "fx delay <#> fx delay 1000\n"); + gi.Printf(S_COLOR_CYAN "fx random <#> fx random 200\n"); + gi.Printf(S_COLOR_CYAN "fx origin <#><#><#> fx origin 10 20 30\n"); + gi.Printf(S_COLOR_CYAN "fx dir <#><#><#> fx dir 0 0 -1\n\n"); } /* @@ -421,21 +378,20 @@ Sets client to godmode argv(0) god ================== */ -void Cmd_God_f (gentity_t *ent) -{ - const char *msg; +void Cmd_God_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_GODMODE; - if (!(ent->flags & FL_GODMODE) ) + if (!(ent->flags & FL_GODMODE)) msg = "godmode OFF\n"; else msg = "godmode ON\n"; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } /* @@ -447,32 +403,24 @@ Sets client to undead mode argv(0) undying ================== */ -void Cmd_Undying_f (gentity_t *ent) -{ - const char *msg; +void Cmd_Undying_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) - { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_UNDYING; - if (!(ent->flags & FL_UNDYING) ) - { + if (!(ent->flags & FL_UNDYING)) { msg = "undead mode OFF\n"; - } - else - { - int max; - const char *cmd; + } else { + int max; + const char *cmd; cmd = gi.argv(1); - if ( cmd && atoi( cmd ) ) - { - max = atoi( cmd ); - } - else - { + if (cmd && atoi(cmd)) { + max = atoi(cmd); + } else { max = 999; } @@ -480,13 +428,12 @@ void Cmd_Undying_f (gentity_t *ent) msg = "undead mode ON\n"; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.stats[STAT_HEALTH] = ent->client->ps.stats[STAT_MAX_HEALTH] = 999; } } - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } /* @@ -498,23 +445,22 @@ Sets client to notarget argv(0) notarget ================== */ -void Cmd_Notarget_f( gentity_t *ent ) { - const char *msg; +void Cmd_Notarget_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_NOTARGET; - if (!(ent->flags & FL_NOTARGET) ) + if (!(ent->flags & FL_NOTARGET)) msg = "notarget OFF\n"; else msg = "notarget ON\n"; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } - /* ================== Cmd_Noclip_f @@ -522,24 +468,23 @@ Cmd_Noclip_f argv(0) noclip ================== */ -void Cmd_Noclip_f( gentity_t *ent ) { - const char *msg; +void Cmd_Noclip_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } - if ( ent->client->noclip ) { + if (ent->client->noclip) { msg = "noclip OFF\n"; } else { msg = "noclip ON\n"; } ent->client->noclip = !ent->client->noclip; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } - /* ================== Cmd_LevelShot_f @@ -550,98 +495,92 @@ and sends over a command to the client to resize the view, hide the scoreboard, and take a special screenshot ================== */ -void Cmd_LevelShot_f( gentity_t *ent ) { - if ( !CheatsOk( ent ) ) { +void Cmd_LevelShot_f(gentity_t *ent) { + if (!CheatsOk(ent)) { return; } - gi.SendServerCommand( ent-g_entities, "clientLevelShot" ); + gi.SendServerCommand(ent - g_entities, "clientLevelShot"); } - /* ================= Cmd_Kill_f ================= */ -void Cmd_Kill_f( gentity_t *ent ) { - if( ( level.time - ent->client->respawnTime ) < 5000 ) { - gi.SendServerCommand( ent-g_entities, "cp @SP_INGAME_ONE_KILL_PER_5_SECONDS"); +void Cmd_Kill_f(gentity_t *ent) { + if ((level.time - ent->client->respawnTime) < 5000) { + gi.SendServerCommand(ent - g_entities, "cp @SP_INGAME_ONE_KILL_PER_5_SECONDS"); return; } ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = 0; - player_die (ent, ent, ent, 100000, MOD_SUICIDE); + player_die(ent, ent, ent, 100000, MOD_SUICIDE); } - /* ================== Cmd_Where_f ================== */ -void Cmd_Where_f( gentity_t *ent ) { +void Cmd_Where_f(gentity_t *ent) { const char *s = gi.argv(1); const int len = strlen(s); - gentity_t *check; + gentity_t *check; - if ( gi.argc () < 2 ) { + if (gi.argc() < 2) { gi.Printf("usage: where classname\n"); return; } - for (int i = 0; i < globals.num_entities; i++) - { - if(!PInUse(i)) + for (int i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if(!check || !check->inuse) { -// continue; -// } + // if(!check || !check->inuse) { + // continue; + // } check = &g_entities[i]; - if (!Q_stricmpn(s, check->classname, len) ) { - gi.SendServerCommand( ent-g_entities, "print \"%s %s\n\"", check->classname, vtos( check->s.pos.trBase ) ); + if (!Q_stricmpn(s, check->classname, len)) { + gi.SendServerCommand(ent - g_entities, "print \"%s %s\n\"", check->classname, vtos(check->s.pos.trBase)); } } } - /* ------------------------- UserSpawn ------------------------- */ -extern qboolean G_CallSpawn( gentity_t *ent ); +extern qboolean G_CallSpawn(gentity_t *ent); -void UserSpawn( gentity_t *ent, const char *name ) -{ - vec3_t origin; - vec3_t vf; - vec3_t angles; - gentity_t *ent2; +void UserSpawn(gentity_t *ent, const char *name) { + vec3_t origin; + vec3_t vf; + vec3_t angles; + gentity_t *ent2; - //Spawn the ent + // Spawn the ent ent2 = G_Spawn(); - ent2->classname = G_NewString( name ); + ent2->classname = G_NewString(name); - //TODO: This should ultimately make sure this is a safe spawn! + // TODO: This should ultimately make sure this is a safe spawn! - //Spawn the entity and place it there - VectorSet( angles, 0, ent->s.apos.trBase[YAW], 0 ); - AngleVectors( angles, vf, NULL, NULL ); - VectorMA( ent->s.pos.trBase, 96, vf, origin ); //FIXME: Find the radius size of the object, and push out 32 + radius + // Spawn the entity and place it there + VectorSet(angles, 0, ent->s.apos.trBase[YAW], 0); + AngleVectors(angles, vf, NULL, NULL); + VectorMA(ent->s.pos.trBase, 96, vf, origin); // FIXME: Find the radius size of the object, and push out 32 + radius origin[2] += 8; - VectorCopy( origin, ent2->s.pos.trBase ); - VectorCopy( origin, ent2->s.origin ); - VectorCopy( ent->s.apos.trBase, ent2->s.angles ); + VectorCopy(origin, ent2->s.pos.trBase); + VectorCopy(origin, ent2->s.origin); + VectorCopy(ent->s.apos.trBase, ent2->s.angles); - gi.linkentity( ent2 ); + gi.linkentity(ent2); - //Find a valid spawning spot - if ( G_CallSpawn( ent2 ) == qfalse ) - { - gi.SendServerCommand( ent-g_entities, "print \"Failed to spawn '%s'\n\"", name ); - G_FreeEntity( ent2 ); + // Find a valid spawning spot + if (G_CallSpawn(ent2) == qfalse) { + gi.SendServerCommand(ent - g_entities, "print \"Failed to spawn '%s'\n\"", name); + G_FreeEntity(ent2); return; } } @@ -652,15 +591,14 @@ Cmd_Spawn ------------------------- */ -void Cmd_Spawn( gentity_t *ent ) -{ - char *name; +void Cmd_Spawn(gentity_t *ent) { + char *name; - name = ConcatArgs( 1 ); + name = ConcatArgs(1); - gi.SendServerCommand( ent-g_entities, "print \"Spawning '%s'\n\"", name ); + gi.SendServerCommand(ent - g_entities, "print \"Spawning '%s'\n\"", name); - UserSpawn( ent, name ); + UserSpawn(ent, name); } /* @@ -668,58 +606,52 @@ void Cmd_Spawn( gentity_t *ent ) Cmd_SetViewpos_f ================= */ -void Cmd_SetViewpos_f( gentity_t *ent ) { - vec3_t origin, angles; - int i; +void Cmd_SetViewpos_f(gentity_t *ent) { + vec3_t origin, angles; + int i; - if ( !g_cheats->integer ) { - gi.SendServerCommand( ent-g_entities, va("print \"Cheats are not enabled on this server.\n\"")); + if (!g_cheats->integer) { + gi.SendServerCommand(ent - g_entities, va("print \"Cheats are not enabled on this server.\n\"")); return; } - if ( gi.argc() != 5 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); + if (gi.argc() != 5) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); return; } - VectorClear( angles ); - for ( i = 0 ; i < 3 ; i++ ) { - origin[i] = atof( gi.argv( i+1 ) ); + VectorClear(angles); + for (i = 0; i < 3; i++) { + origin[i] = atof(gi.argv(i + 1)); } - origin[2] -= 25; //acount for eye height from viewpos cmd + origin[2] -= 25; // acount for eye height from viewpos cmd - angles[YAW] = atof( gi.argv( 4 ) ); + angles[YAW] = atof(gi.argv(4)); - TeleportPlayer( ent, origin, angles ); + TeleportPlayer(ent, origin, angles); } - - /* ================= Cmd_SetObjective_f ================= */ -qboolean G_CheckPlayerDarkSide( void ); +qboolean G_CheckPlayerDarkSide(void); -void Cmd_SetObjective_f( gentity_t *ent ) -{ - int objectiveI,status,displayStatus; +void Cmd_SetObjective_f(gentity_t *ent) { + int objectiveI, status, displayStatus; - if ( gi.argc() == 2 ) { + if (gi.argc() == 2) { objectiveI = atoi(gi.argv(1)); - gi.Printf("objective #%d display status=%d, status=%d\n",objectiveI, - ent->client->sess.mission_objectives[objectiveI].display, - ent->client->sess.mission_objectives[objectiveI].status - ); + gi.Printf("objective #%d display status=%d, status=%d\n", objectiveI, ent->client->sess.mission_objectives[objectiveI].display, + ent->client->sess.mission_objectives[objectiveI].status); return; } - if ( gi.argc() != 4 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: setobjective \n\"")); + if (gi.argc() != 4) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: setobjective \n\"")); return; } - if ( !CheatsOk( ent ) ) - { + if (!CheatsOk(ent)) { return; } @@ -737,40 +669,37 @@ void Cmd_SetObjective_f( gentity_t *ent ) Cmd_ViewObjective_f ================= */ -void Cmd_ViewObjective_f( gentity_t *ent ) -{ +void Cmd_ViewObjective_f(gentity_t *ent) { int objectiveI; - if ( gi.argc() != 2 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: viewobjective \n\"")); + if (gi.argc() != 2) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: viewobjective \n\"")); return; } objectiveI = atoi(gi.argv(1)); - gi.SendServerCommand( ent-g_entities, va("print \"Objective %d Display Status(1=show): %d Status:%d\n\"",objectiveI,ent->client->sess.mission_objectives[objectiveI].display,ent->client->sess.mission_objectives[objectiveI].status)); + gi.SendServerCommand(ent - g_entities, + va("print \"Objective %d Display Status(1=show): %d Status:%d\n\"", objectiveI, + ent->client->sess.mission_objectives[objectiveI].display, ent->client->sess.mission_objectives[objectiveI].status)); } - /* ================ Cmd_UseElectrobinoculars_f ================ */ -void Cmd_UseElectrobinoculars_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseElectrobinoculars_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - if ( ent->client->ps.inventory[INV_ELECTROBINOCULARS] <= 0 ) - { + if (ent->client->ps.inventory[INV_ELECTROBINOCULARS] <= 0) { // have none to place...play sound? return; } - G_AddEvent( ent, EV_USE_INV_BINOCULARS, 0 ); + G_AddEvent(ent, EV_USE_INV_BINOCULARS, 0); } /* @@ -778,10 +707,8 @@ void Cmd_UseElectrobinoculars_f(gentity_t *ent) Cmd_UseBacta_f ================ */ -void Cmd_UseBacta_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseBacta_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } @@ -789,60 +716,55 @@ void Cmd_UseBacta_f(gentity_t *ent) } //---------------------------------------------------------------------------------- -qboolean PickSeekerSpawnPoint( vec3_t org, vec3_t fwd, vec3_t right, int skip, vec3_t spot ) -{ - vec3_t mins, maxs, forward, end; +qboolean PickSeekerSpawnPoint(vec3_t org, vec3_t fwd, vec3_t right, int skip, vec3_t spot) { + vec3_t mins, maxs, forward, end; trace_t tr; - VectorSet( maxs, -8, -8, -24); // ?? size - VectorSet( maxs, 8, 8, 8 ); + VectorSet(maxs, -8, -8, -24); // ?? size + VectorSet(maxs, 8, 8, 8); - VectorCopy( fwd, forward ); + VectorCopy(fwd, forward); // to the front and side a bit forward[2] = 0.3f; // start up a bit - VectorMA( org, 48, forward, end ); - VectorMA( end, -8, right, end ); + VectorMA(org, 48, forward, end); + VectorMA(end, -8, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // side - VectorMA( org, 48, right, end ); + VectorMA(org, 48, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // other side - VectorMA( org, -48, right, end ); + VectorMA(org, -48, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // behind - VectorMA( org, -48, fwd, end ); + VectorMA(org, -48, fwd, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, (EG2_Collision)0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } @@ -854,41 +776,35 @@ qboolean PickSeekerSpawnPoint( vec3_t org, vec3_t fwd, vec3_t right, int skip, v Cmd_UseSeeker_f ================ */ -void Cmd_UseSeeker_f( gentity_t *ent ) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseSeeker_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } // don't use them if we don't have any...also don't use them if one is already going - if ( ent->client && ent->client->ps.inventory[INV_SEEKER] > 0 && level.time > ent->client->ps.powerups[PW_SEEKER] ) - { - gentity_t *tent = G_Spawn(); + if (ent->client && ent->client->ps.inventory[INV_SEEKER] > 0 && level.time > ent->client->ps.powerups[PW_SEEKER]) { + gentity_t *tent = G_Spawn(); - if ( tent ) - { - vec3_t fwd, right, spot; + if (tent) { + vec3_t fwd, right, spot; - AngleVectors( ent->client->ps.viewangles, fwd, right, NULL ); + AngleVectors(ent->client->ps.viewangles, fwd, right, NULL); - VectorCopy( ent->currentOrigin, spot ); // does nothing really, just initialize the goods... + VectorCopy(ent->currentOrigin, spot); // does nothing really, just initialize the goods... - if ( PickSeekerSpawnPoint( ent->currentOrigin, fwd, right, ent->s.number, spot )) - { - VectorCopy( spot, tent->s.origin ); - G_SetOrigin( tent, spot ); - G_SetAngles( tent, ent->currentAngles ); + if (PickSeekerSpawnPoint(ent->currentOrigin, fwd, right, ent->s.number, spot)) { + VectorCopy(spot, tent->s.origin); + G_SetOrigin(tent, spot); + G_SetAngles(tent, ent->currentAngles); -extern void SP_NPC_Droid_Seeker( gentity_t *ent ); + extern void SP_NPC_Droid_Seeker(gentity_t * ent); - SP_NPC_Droid_Seeker( tent ); - G_Sound( tent, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + SP_NPC_Droid_Seeker(tent); + G_Sound(tent, G_SoundIndex("sound/chars/seeker/misc/hiss")); // make sure that we even have some ent->client->ps.inventory[INV_SEEKER]--; - ent->client->ps.powerups[PW_SEEKER] = level.time + 1000;// can only drop one every second..maybe this is annoying? - + ent->client->ps.powerups[PW_SEEKER] = level.time + 1000; // can only drop one every second..maybe this is annoying? } } } @@ -899,16 +815,13 @@ extern void SP_NPC_Droid_Seeker( gentity_t *ent ); Cmd_UseGoggles_f ================ */ -void Cmd_UseGoggles_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseGoggles_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - if ( ent->client && ent->client->ps.inventory[INV_LIGHTAMP_GOGGLES] > 0 ) - { - G_AddEvent( ent, EV_USE_INV_LIGHTAMP_GOGGLES, 0 ); + if (ent->client && ent->client->ps.inventory[INV_LIGHTAMP_GOGGLES] > 0) { + G_AddEvent(ent, EV_USE_INV_LIGHTAMP_GOGGLES, 0); } } @@ -917,27 +830,21 @@ void Cmd_UseGoggles_f(gentity_t *ent) Cmd_UseSentry_f ================ */ -qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t dir ); -void Cmd_UseSentry_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +qboolean place_portable_assault_sentry(gentity_t *self, vec3_t origin, vec3_t dir); +void Cmd_UseSentry_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - if ( ent->client->ps.inventory[INV_SENTRY] <= 0 ) - { + if (ent->client->ps.inventory[INV_SENTRY] <= 0) { // have none to place...play sound? return; } - if ( place_portable_assault_sentry( ent, ent->currentOrigin, ent->client->ps.viewangles )) - { + if (place_portable_assault_sentry(ent, ent->currentOrigin, ent->client->ps.viewangles)) { ent->client->ps.inventory[INV_SENTRY]--; - G_AddEvent( ent, EV_USE_INV_SENTRY, 0 ); - } - else - { + G_AddEvent(ent, EV_USE_INV_SENTRY, 0); + } else { // couldn't be placed....play a notification sound!! } } @@ -947,91 +854,64 @@ void Cmd_UseSentry_f(gentity_t *ent) Cmd_UseInventory_f ================ */ -void Cmd_UseInventory_f(gentity_t *ent) -{ - switch (cg.inventorySelect) - { - case INV_ELECTROBINOCULARS : - Cmd_UseElectrobinoculars_f(ent); - return; - // WTF WHY WAS THIS COMMENTED OUT --eez - case INV_BACTA_CANISTER : - Cmd_UseBacta_f(ent); - return; - case INV_SEEKER : - Cmd_UseSeeker_f(ent); - return; - case INV_LIGHTAMP_GOGGLES : - Cmd_UseGoggles_f(ent); - return; - case INV_SENTRY : - Cmd_UseSentry_f(ent); - return; - default : - return; - +void Cmd_UseInventory_f(gentity_t *ent) { + switch (cg.inventorySelect) { + case INV_ELECTROBINOCULARS: + Cmd_UseElectrobinoculars_f(ent); + return; + // WTF WHY WAS THIS COMMENTED OUT --eez + case INV_BACTA_CANISTER: + Cmd_UseBacta_f(ent); + return; + case INV_SEEKER: + Cmd_UseSeeker_f(ent); + return; + case INV_LIGHTAMP_GOGGLES: + Cmd_UseGoggles_f(ent); + return; + case INV_SENTRY: + Cmd_UseSentry_f(ent); + return; + default: + return; } } -void Cmd_FlushCamFile_f(gentity_t *ent) -{ - gi.FlushCamFile(); -} +void Cmd_FlushCamFile_f(gentity_t *ent) { gi.FlushCamFile(); } -void G_Taunt( gentity_t *ent ) -{ - if ( ent->client ) - { - if ( ent->client->ps.weapon == WP_SABER - && (ent->client->ps.saberAnimLevel == SS_STAFF //ent->client->ps.saber[0].type == SABER_STAFF - || ent->client->ps.dualSabers) ) - { +void G_Taunt(gentity_t *ent) { + if (ent->client) { + if (ent->client->ps.weapon == WP_SABER && (ent->client->ps.saberAnimLevel == SS_STAFF // ent->client->ps.saber[0].type == SABER_STAFF + || ent->client->ps.dualSabers)) { ent->client->ps.taunting = level.time + 100; - //make sure all sabers are on + // make sure all sabers are on ent->client->ps.SaberActivate(); - } - else - { + } else { ent->client->ps.taunting = level.time + 100; } } } -void G_Victory( gentity_t *ent ) -{ - if ( ent->health > 0 ) - {//say something and put away saber - G_SoundOnEnt( ent, CHAN_VOICE, "sound/chars/kyle/misc/taunt1.wav" ); - if ( ent->client ) - { +void G_Victory(gentity_t *ent) { + if (ent->health > 0) { // say something and put away saber + G_SoundOnEnt(ent, CHAN_VOICE, "sound/chars/kyle/misc/taunt1.wav"); + if (ent->client) { ent->client->ps.SaberDeactivate(); } } } -enum -{ - TAUNT_TAUNT = 0, - TAUNT_BOW, - TAUNT_MEDITATE, - TAUNT_FLOURISH, - TAUNT_GLOAT -}; - -extern void G_SpeechEvent( gentity_t *self, int event ); -void G_TauntSound( gentity_t *ent, int taunt ) -{ - switch ( taunt ) - { +enum { TAUNT_TAUNT = 0, TAUNT_BOW, TAUNT_MEDITATE, TAUNT_FLOURISH, TAUNT_GLOAT }; + +extern void G_SpeechEvent(gentity_t *self, int event); +void G_TauntSound(gentity_t *ent, int taunt) { + switch (taunt) { case TAUNT_TAUNT: default: - if ( Q_irand( 0, 1 ) ) - { - G_SpeechEvent( ent, Q_irand( EV_ANGER1, EV_ANGER3 ) ); - } - else - { - G_SpeechEvent( ent, Q_irand( EV_TAUNT1, EV_TAUNT3 ) ); + if (Q_irand(0, 1)) { + G_SpeechEvent(ent, Q_irand(EV_ANGER1, EV_ANGER3)); + } else { + G_SpeechEvent(ent, Q_irand(EV_TAUNT1, EV_TAUNT3)); } break; case TAUNT_BOW: @@ -1039,62 +919,40 @@ void G_TauntSound( gentity_t *ent, int taunt ) case TAUNT_MEDITATE: break; case TAUNT_FLOURISH: - if ( Q_irand( 0, 1 ) ) - { - G_SpeechEvent( ent, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ) ); - } - else - { - G_SpeechEvent( ent, Q_irand( EV_GLOAT1, EV_GLOAT3 ) ); + if (Q_irand(0, 1)) { + G_SpeechEvent(ent, Q_irand(EV_DEFLECT1, EV_DEFLECT3)); + } else { + G_SpeechEvent(ent, Q_irand(EV_GLOAT1, EV_GLOAT3)); } break; case TAUNT_GLOAT: - G_SpeechEvent( ent, Q_irand( EV_VICTORY1, EV_VICTORY3 ) ); + G_SpeechEvent(ent, Q_irand(EV_VICTORY1, EV_VICTORY3)); break; } } -void G_SetTauntAnim( gentity_t *ent, int taunt ) -{ - if ( !ent || !ent->client ) - { +void G_SetTauntAnim(gentity_t *ent, int taunt) { + if (!ent || !ent->client) { return; } - if ( !ent->client->ps.torsoAnimTimer - && !ent->client->ps.legsAnimTimer - && !ent->client->ps.weaponTime - && ent->client->ps.saberLockTime < level.time ) - { + if (!ent->client->ps.torsoAnimTimer && !ent->client->ps.legsAnimTimer && !ent->client->ps.weaponTime && ent->client->ps.saberLockTime < level.time) { int anim = -1; - switch ( taunt ) - { + switch (taunt) { case TAUNT_TAUNT: - if ( ent->client->ps.weapon != WP_SABER ) - { + if (ent->client->ps.weapon != WP_SABER) { anim = BOTH_ENGAGETAUNT; - } - else if ( ent->client->ps.saber[0].tauntAnim != -1 ) - { + } else if (ent->client->ps.saber[0].tauntAnim != -1) { anim = ent->client->ps.saber[0].tauntAnim; - } - else if ( ent->client->ps.dualSabers - && ent->client->ps.saber[1].tauntAnim != -1 ) - { + } else if (ent->client->ps.dualSabers && ent->client->ps.saber[1].tauntAnim != -1) { anim = ent->client->ps.saber[1].tauntAnim; - } - else - { - switch ( ent->client->ps.saberAnimLevel ) - { + } else { + switch (ent->client->ps.saberAnimLevel) { case SS_FAST: case SS_TAVION: - if ( ent->client->ps.saber[1].Active() ) - {//turn off second saber - G_Sound( ent, ent->client->ps.saber[1].soundOff ); - } - else if ( ent->client->ps.saber[0].Active() ) - {//turn off first - G_Sound( ent, ent->client->ps.saber[0].soundOff ); + if (ent->client->ps.saber[1].Active()) { // turn off second saber + G_Sound(ent, ent->client->ps.saber[1].soundOff); + } else if (ent->client->ps.saber[0].Active()) { // turn off first + G_Sound(ent, ent->client->ps.saber[0].soundOff); } ent->client->ps.SaberDeactivate(); anim = BOTH_GESTURE1; @@ -1116,84 +974,52 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; case TAUNT_BOW: - if ( ent->client->ps.weapon != WP_SABER ) - { + if (ent->client->ps.weapon != WP_SABER) { anim = BOTH_BOW; - } - else if ( ent->client->ps.saber[0].bowAnim != -1 ) - { + } else if (ent->client->ps.saber[0].bowAnim != -1) { anim = ent->client->ps.saber[0].bowAnim; - } - else if ( ent->client->ps.dualSabers - && ent->client->ps.saber[1].bowAnim != -1 ) - { + } else if (ent->client->ps.dualSabers && ent->client->ps.saber[1].bowAnim != -1) { anim = ent->client->ps.saber[1].bowAnim; - } - else - { + } else { anim = BOTH_BOW; } - if ( ent->client->ps.weapon == WP_SABER ) - { - if ( ent->client->ps.saber[1].Active() ) - {//turn off second saber - G_Sound( ent, ent->client->ps.saber[1].soundOff ); - } - else if ( ent->client->ps.saber[0].Active() ) - {//turn off first - G_Sound( ent, ent->client->ps.saber[0].soundOff ); + if (ent->client->ps.weapon == WP_SABER) { + if (ent->client->ps.saber[1].Active()) { // turn off second saber + G_Sound(ent, ent->client->ps.saber[1].soundOff); + } else if (ent->client->ps.saber[0].Active()) { // turn off first + G_Sound(ent, ent->client->ps.saber[0].soundOff); } ent->client->ps.SaberDeactivate(); } break; case TAUNT_MEDITATE: - if ( ent->client->ps.weapon != WP_SABER ) - { + if (ent->client->ps.weapon != WP_SABER) { anim = BOTH_MEDITATE; - } - else if ( ent->client->ps.saber[0].meditateAnim != -1 ) - { + } else if (ent->client->ps.saber[0].meditateAnim != -1) { anim = ent->client->ps.saber[0].meditateAnim; - } - else if ( ent->client->ps.dualSabers - && ent->client->ps.saber[1].meditateAnim != -1 ) - { + } else if (ent->client->ps.dualSabers && ent->client->ps.saber[1].meditateAnim != -1) { anim = ent->client->ps.saber[1].meditateAnim; - } - else - { + } else { anim = BOTH_MEDITATE; } - if ( ent->client->ps.weapon == WP_SABER ) - { - if ( ent->client->ps.saber[1].Active() ) - {//turn off second saber - G_Sound( ent, ent->client->ps.saber[1].soundOff ); - } - else if ( ent->client->ps.saber[0].Active() ) - {//turn off first - G_Sound( ent, ent->client->ps.saber[0].soundOff ); + if (ent->client->ps.weapon == WP_SABER) { + if (ent->client->ps.saber[1].Active()) { // turn off second saber + G_Sound(ent, ent->client->ps.saber[1].soundOff); + } else if (ent->client->ps.saber[0].Active()) { // turn off first + G_Sound(ent, ent->client->ps.saber[0].soundOff); } ent->client->ps.SaberDeactivate(); } break; case TAUNT_FLOURISH: - if ( ent->client->ps.weapon == WP_SABER ) - { + if (ent->client->ps.weapon == WP_SABER) { ent->client->ps.SaberActivate(); - if ( ent->client->ps.saber[0].flourishAnim != -1 ) - { + if (ent->client->ps.saber[0].flourishAnim != -1) { anim = ent->client->ps.saber[0].flourishAnim; - } - else if ( ent->client->ps.dualSabers - && ent->client->ps.saber[1].flourishAnim != -1 ) - { + } else if (ent->client->ps.dualSabers && ent->client->ps.saber[1].flourishAnim != -1) { anim = ent->client->ps.saber[1].flourishAnim; - } - else - { - switch ( ent->client->ps.saberAnimLevel ) - { + } else { + switch (ent->client->ps.saberAnimLevel) { case SS_FAST: case SS_TAVION: anim = BOTH_SHOWOFF_FAST; @@ -1216,21 +1042,13 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; case TAUNT_GLOAT: - if ( ent->client->ps.weapon == WP_SABER ) - { - if ( ent->client->ps.saber[0].gloatAnim != -1 ) - { + if (ent->client->ps.weapon == WP_SABER) { + if (ent->client->ps.saber[0].gloatAnim != -1) { anim = ent->client->ps.saber[0].gloatAnim; - } - else if ( ent->client->ps.dualSabers - && ent->client->ps.saber[1].gloatAnim != -1 ) - { + } else if (ent->client->ps.dualSabers && ent->client->ps.saber[1].gloatAnim != -1) { anim = ent->client->ps.saber[1].gloatAnim; - } - else - { - switch ( ent->client->ps.saberAnimLevel ) - { + } else { + switch (ent->client->ps.saberAnimLevel) { case SS_FAST: case SS_TAVION: anim = BOTH_VICTORY_FAST; @@ -1256,105 +1074,78 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; } - if ( anim != -1 ) - { - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { + if (anim != -1) { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { int parts = SETANIM_TORSO; - if ( anim != BOTH_ENGAGETAUNT ) - { + if (anim != BOTH_ENGAGETAUNT) { parts = SETANIM_BOTH; - VectorClear( ent->client->ps.velocity ); + VectorClear(ent->client->ps.velocity); } - NPC_SetAnim( ent, parts, anim, (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD) ); + NPC_SetAnim(ent, parts, anim, (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD)); } - if ( taunt != TAUNT_MEDITATE - && taunt != TAUNT_BOW ) - {//no sound for meditate or bow - G_TauntSound( ent, taunt ); + if (taunt != TAUNT_MEDITATE && taunt != TAUNT_BOW) { // no sound for meditate or bow + G_TauntSound(ent, taunt); } } } } -extern cvar_t *g_saberPickuppableDroppedSabers; -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); -extern void CG_ChangeWeapon( int num ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -void Cmd_SaberDrop_f( gentity_t *ent, int saberNum ) -{ - if ( saberNum < 0 ) - { +extern cvar_t *g_saberPickuppableDroppedSabers; +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); +extern void CG_ChangeWeapon(int num); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +void Cmd_SaberDrop_f(gentity_t *ent, int saberNum) { + if (saberNum < 0) { return; } - if ( saberNum > 1 ) - { + if (saberNum > 1) { return; } - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - if ( ent->weaponModel[saberNum] <= 0 ) - { + if (ent->weaponModel[saberNum] <= 0) { return; } - if ( ent->client->ps.weapon != WP_SABER ) - { + if (ent->client->ps.weapon != WP_SABER) { return; } - if ( ent->client->ps.weaponTime > 0 ) - { + if (ent->client->ps.weaponTime > 0) { return; } - if ( ent->client->ps.saberMove != LS_READY - && ent->client->ps.saberMove != LS_PUTAWAY - && ent->client->ps.saberMove != LS_DRAW - && ent->client->ps.saberMove != LS_NONE ) - { + if (ent->client->ps.saberMove != LS_READY && ent->client->ps.saberMove != LS_PUTAWAY && ent->client->ps.saberMove != LS_DRAW && + ent->client->ps.saberMove != LS_NONE) { return; } - if ( !g_saberPickuppableDroppedSabers->integer ) - { + if (!g_saberPickuppableDroppedSabers->integer) { return; } - if ( !ent->client->ps.saber[saberNum].name - || !ent->client->ps.saber[saberNum].name[0] ) - { + if (!ent->client->ps.saber[saberNum].name || !ent->client->ps.saber[saberNum].name[0]) { return; } - //have a valid string to use for saberType - - //turn it into a pick-uppable item! - if ( G_DropSaberItem( ent->client->ps.saber[saberNum].name, - ent->client->ps.saber[saberNum].blade[0].color, - (saberNum==0?ent->client->renderInfo.handRPoint:ent->client->renderInfo.handLPoint), - ent->client->ps.velocity, - ent->currentAngles ) - != NULL ) - {//dropped it - WP_RemoveSaber( ent, saberNum ); - } - - if ( ent->weaponModel[0] <= 0 - && ent->weaponModel[1] <= 0 ) - {//no sabers left! - //remove saber from inventory - ent->client->ps.stats[STAT_WEAPONS] &= ~(1<s.number < MAX_CLIENTS ) - {//player - CG_ChangeWeapon( WP_NONE ); - } - else - { - ChangeWeapon( ent, WP_NONE ); + // have a valid string to use for saberType + + // turn it into a pick-uppable item! + if (G_DropSaberItem(ent->client->ps.saber[saberNum].name, ent->client->ps.saber[saberNum].blade[0].color, + (saberNum == 0 ? ent->client->renderInfo.handRPoint : ent->client->renderInfo.handLPoint), ent->client->ps.velocity, + ent->currentAngles) != NULL) { // dropped it + WP_RemoveSaber(ent, saberNum); + } + + if (ent->weaponModel[0] <= 0 && ent->weaponModel[1] <= 0) { // no sabers left! + // remove saber from inventory + ent->client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_SABER); + // change weapons + if (ent->s.number < MAX_CLIENTS) { // player + CG_ChangeWeapon(WP_NONE); + } else { + ChangeWeapon(ent, WP_NONE); } ent->client->ps.weapon = WP_NONE; } @@ -1365,169 +1156,124 @@ void Cmd_SaberDrop_f( gentity_t *ent, int saberNum ) ClientCommand ================= */ -void ClientCommand( int clientNum ) { +void ClientCommand(int clientNum) { gentity_t *ent; - const char *cmd; + const char *cmd; ent = g_entities + clientNum; - if ( !ent->client ) { - return; // not fully in game yet + if (!ent->client) { + return; // not fully in game yet } cmd = gi.argv(0); - if (Q_stricmp (cmd, "spawn") == 0) - { - Cmd_Spawn( ent ); + if (Q_stricmp(cmd, "spawn") == 0) { + Cmd_Spawn(ent); return; } - if (Q_stricmp (cmd, "give") == 0) - Cmd_Give_f (ent); - else if (Q_stricmp (cmd, "god") == 0) - Cmd_God_f (ent); - else if (Q_stricmp (cmd, "undying") == 0) - Cmd_Undying_f (ent); - else if (Q_stricmp (cmd, "notarget") == 0) - Cmd_Notarget_f (ent); - else if (Q_stricmp (cmd, "noclip") == 0) - { - Cmd_Noclip_f (ent); - } - else if (Q_stricmp (cmd, "kill") == 0) - { - if ( !CheatsOk( ent ) ) - { + if (Q_stricmp(cmd, "give") == 0) + Cmd_Give_f(ent); + else if (Q_stricmp(cmd, "god") == 0) + Cmd_God_f(ent); + else if (Q_stricmp(cmd, "undying") == 0) + Cmd_Undying_f(ent); + else if (Q_stricmp(cmd, "notarget") == 0) + Cmd_Notarget_f(ent); + else if (Q_stricmp(cmd, "noclip") == 0) { + Cmd_Noclip_f(ent); + } else if (Q_stricmp(cmd, "kill") == 0) { + if (!CheatsOk(ent)) { return; } - Cmd_Kill_f (ent); - } - else if (Q_stricmp (cmd, "levelshot") == 0) - Cmd_LevelShot_f (ent); - else if (Q_stricmp (cmd, "where") == 0) - Cmd_Where_f (ent); - else if (Q_stricmp (cmd, "setviewpos") == 0) - Cmd_SetViewpos_f( ent ); - else if (Q_stricmp (cmd, "setobjective") == 0) - Cmd_SetObjective_f( ent ); - else if (Q_stricmp (cmd, "viewobjective") == 0) - Cmd_ViewObjective_f( ent ); - else if (Q_stricmp (cmd, "force_throw") == 0) - { + Cmd_Kill_f(ent); + } else if (Q_stricmp(cmd, "levelshot") == 0) + Cmd_LevelShot_f(ent); + else if (Q_stricmp(cmd, "where") == 0) + Cmd_Where_f(ent); + else if (Q_stricmp(cmd, "setviewpos") == 0) + Cmd_SetViewpos_f(ent); + else if (Q_stricmp(cmd, "setobjective") == 0) + Cmd_SetObjective_f(ent); + else if (Q_stricmp(cmd, "viewobjective") == 0) + Cmd_ViewObjective_f(ent); + else if (Q_stricmp(cmd, "force_throw") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceThrow( ent, qfalse ); - } - else if (Q_stricmp (cmd, "force_pull") == 0) - { + ForceThrow(ent, qfalse); + } else if (Q_stricmp(cmd, "force_pull") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceThrow( ent, qtrue ); - } - else if (Q_stricmp (cmd, "force_speed") == 0) - { + ForceThrow(ent, qtrue); + } else if (Q_stricmp(cmd, "force_speed") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceSpeed( ent ); - } - else if (Q_stricmp (cmd, "force_heal") == 0) - { + ForceSpeed(ent); + } else if (Q_stricmp(cmd, "force_heal") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceHeal( ent ); - } - else if (Q_stricmp (cmd, "force_grip") == 0) - { + ForceHeal(ent); + } else if (Q_stricmp(cmd, "force_grip") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceGrip( ent ); - } - else if (Q_stricmp (cmd, "force_distract") == 0) - { + ForceGrip(ent); + } else if (Q_stricmp(cmd, "force_distract") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceTelepathy( ent ); - } - else if (Q_stricmp (cmd, "force_rage") == 0) - { + ForceTelepathy(ent); + } else if (Q_stricmp(cmd, "force_rage") == 0) { ent = G_GetSelfForPlayerCmd(); ForceRage(ent); - } - else if (Q_stricmp (cmd, "force_protect") == 0) - { + } else if (Q_stricmp(cmd, "force_protect") == 0) { ent = G_GetSelfForPlayerCmd(); ForceProtect(ent); - } - else if (Q_stricmp (cmd, "force_absorb") == 0) - { + } else if (Q_stricmp(cmd, "force_absorb") == 0) { ent = G_GetSelfForPlayerCmd(); ForceAbsorb(ent); - } - else if (Q_stricmp (cmd, "force_sight") == 0) - { + } else if (Q_stricmp(cmd, "force_sight") == 0) { ent = G_GetSelfForPlayerCmd(); ForceSeeing(ent); - } - else if (Q_stricmp (cmd, "addsaberstyle") == 0) - { + } else if (Q_stricmp(cmd, "addsaberstyle") == 0) { ent = G_GetSelfForPlayerCmd(); - if ( !ent || !ent->client ) - {//wtf? + if (!ent || !ent->client) { // wtf? return; } - if ( gi.argc() < 2 ) - { - gi.SendServerCommand( ent-g_entities, va("print \"usage: addsaberstyle \n\"")); - gi.SendServerCommand( ent-g_entities, va("print \"Valid styles: SS_FAST, SS_MEDIUM, SS_STRONG, SS_DESANN, SS_TAVION, SS_DUAL and SS_STAFF\n\"")); + if (gi.argc() < 2) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: addsaberstyle \n\"")); + gi.SendServerCommand(ent - g_entities, va("print \"Valid styles: SS_FAST, SS_MEDIUM, SS_STRONG, SS_DESANN, SS_TAVION, SS_DUAL and SS_STAFF\n\"")); return; } - int addStyle = GetIDForString( SaberStyleTable, gi.argv(1) ); - if ( addStyle > SS_NONE && addStyle < SS_STAFF ) - { - ent->client->ps.saberStylesKnown |= (1< SS_NONE && addStyle < SS_STAFF) { + ent->client->ps.saberStylesKnown |= (1 << addStyle); } - } - else if (Q_stricmp (cmd, "setsaberstyle") == 0) - { + } else if (Q_stricmp(cmd, "setsaberstyle") == 0) { ent = G_GetSelfForPlayerCmd(); - if ( !ent || !ent->client ) - {//wtf? + if (!ent || !ent->client) { // wtf? return; } - if ( gi.argc() < 2 ) - { - gi.SendServerCommand( ent-g_entities, va("print \"usage: setsaberstyle \n\"")); - gi.SendServerCommand( ent-g_entities, va("print \"Valid styles: SS_FAST, SS_MEDIUM, SS_STRONG, SS_DESANN, SS_TAVION, SS_DUAL and SS_STAFF\n\"")); + if (gi.argc() < 2) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: setsaberstyle \n\"")); + gi.SendServerCommand(ent - g_entities, va("print \"Valid styles: SS_FAST, SS_MEDIUM, SS_STRONG, SS_DESANN, SS_TAVION, SS_DUAL and SS_STAFF\n\"")); return; } - int setStyle = GetIDForString( SaberStyleTable, gi.argv(1) ); - if ( setStyle > SS_NONE && setStyle < SS_STAFF ) - { - ent->client->ps.saberStylesKnown = (1< SS_NONE && setStyle < SS_STAFF) { + ent->client->ps.saberStylesKnown = (1 << setStyle); cg.saberAnimLevelPending = ent->client->ps.saberAnimLevel = setStyle; } - } - else if (Q_stricmp (cmd, "taunt") == 0) - { + } else if (Q_stricmp(cmd, "taunt") == 0) { ent = G_GetSelfForPlayerCmd(); -// G_Taunt( ent ); - G_SetTauntAnim( ent, TAUNT_TAUNT ); - } - else if (Q_stricmp (cmd, "bow") == 0) - { + // G_Taunt( ent ); + G_SetTauntAnim(ent, TAUNT_TAUNT); + } else if (Q_stricmp(cmd, "bow") == 0) { ent = G_GetSelfForPlayerCmd(); - G_SetTauntAnim( ent, TAUNT_BOW ); - } - else if (Q_stricmp (cmd, "meditate") == 0) - { + G_SetTauntAnim(ent, TAUNT_BOW); + } else if (Q_stricmp(cmd, "meditate") == 0) { ent = G_GetSelfForPlayerCmd(); - G_SetTauntAnim( ent, TAUNT_MEDITATE ); - } - else if (Q_stricmp (cmd, "flourish") == 0) - { + G_SetTauntAnim(ent, TAUNT_MEDITATE); + } else if (Q_stricmp(cmd, "flourish") == 0) { ent = G_GetSelfForPlayerCmd(); - G_SetTauntAnim( ent, TAUNT_FLOURISH ); - } - else if (Q_stricmp (cmd, "gloat") == 0) - { + G_SetTauntAnim(ent, TAUNT_FLOURISH); + } else if (Q_stricmp(cmd, "gloat") == 0) { ent = G_GetSelfForPlayerCmd(); - G_SetTauntAnim( ent, TAUNT_GLOAT ); + G_SetTauntAnim(ent, TAUNT_GLOAT); } /* else if (Q_stricmp (cmd, "drive") == 0) @@ -1545,75 +1291,56 @@ void ClientCommand( int clientNum ) { G_DriveVehicle( ent, NULL, gi.argv(1) ); } */ - else if (Q_stricmp (cmd, "NPCdrive") == 0) - { - if ( !CheatsOk( ent ) ) - { + else if (Q_stricmp(cmd, "NPCdrive") == 0) { + if (!CheatsOk(ent)) { return; } - if ( gi.argc() < 3 ) - { - gi.SendServerCommand( ent-g_entities, va("print \"usage: drive \n\"")); - gi.SendServerCommand( ent-g_entities, va("print \"Vehicles will be in vehicles.cfg, try using 'speeder' for now\n\"")); + if (gi.argc() < 3) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: drive \n\"")); + gi.SendServerCommand(ent - g_entities, va("print \"Vehicles will be in vehicles.cfg, try using 'speeder' for now\n\"")); return; } - gentity_t *found = G_Find( NULL, FOFS(targetname), gi.argv(1) ); - if ( found && found->health > 0 && found->client ) - { + gentity_t *found = G_Find(NULL, FOFS(targetname), gi.argv(1)); + if (found && found->health > 0 && found->client) { // TEMPORARY! BRING BACK LATER!!! - //G_DriveVehicle( found, NULL, gi.argv(2) ); + // G_DriveVehicle( found, NULL, gi.argv(2) ); } - } - else if (Q_stricmp (cmd, "thereisnospoon") == 0) - G_StartMatrixEffect( ent ); - else if (Q_stricmp (cmd, "use_electrobinoculars") == 0) - Cmd_UseElectrobinoculars_f( ent ); - else if (Q_stricmp (cmd, "use_bacta") == 0) - Cmd_UseBacta_f( ent ); - else if (Q_stricmp (cmd, "use_seeker") == 0) - Cmd_UseSeeker_f( ent ); - else if (Q_stricmp (cmd, "use_lightamp_goggles") == 0) - Cmd_UseGoggles_f( ent ); - else if (Q_stricmp (cmd, "use_sentry") == 0) - Cmd_UseSentry_f( ent ); - else if (Q_stricmp (cmd, "fx") == 0) - Cmd_Fx( ent ); - else if (Q_stricmp (cmd, "invuse") == 0) - { - Cmd_UseInventory_f( ent ); - } - else if (Q_stricmp (cmd, "playmusic") == 0) - { + } else if (Q_stricmp(cmd, "thereisnospoon") == 0) + G_StartMatrixEffect(ent); + else if (Q_stricmp(cmd, "use_electrobinoculars") == 0) + Cmd_UseElectrobinoculars_f(ent); + else if (Q_stricmp(cmd, "use_bacta") == 0) + Cmd_UseBacta_f(ent); + else if (Q_stricmp(cmd, "use_seeker") == 0) + Cmd_UseSeeker_f(ent); + else if (Q_stricmp(cmd, "use_lightamp_goggles") == 0) + Cmd_UseGoggles_f(ent); + else if (Q_stricmp(cmd, "use_sentry") == 0) + Cmd_UseSentry_f(ent); + else if (Q_stricmp(cmd, "fx") == 0) + Cmd_Fx(ent); + else if (Q_stricmp(cmd, "invuse") == 0) { + Cmd_UseInventory_f(ent); + } else if (Q_stricmp(cmd, "playmusic") == 0) { const char *cmd2 = gi.argv(1); - if ( cmd2 ) - { - gi.SetConfigstring( CS_MUSIC, cmd2 ); + if (cmd2) { + gi.SetConfigstring(CS_MUSIC, cmd2); } - } - else if (Q_stricmp (cmd, "flushcam") == 0) - { - Cmd_FlushCamFile_f( ent ); - } - else if ( Q_stricmp( cmd, "dropsaber" ) == 0 ) - { + } else if (Q_stricmp(cmd, "flushcam") == 0) { + Cmd_FlushCamFile_f(ent); + } else if (Q_stricmp(cmd, "dropsaber") == 0) { const char *cmd2 = gi.argv(1); - int saberNum = 2;//by default, drop both - if ( cmd2 && cmd2[0] ) - { + int saberNum = 2; // by default, drop both + if (cmd2 && cmd2[0]) { saberNum = atoi(cmd2); } - if ( saberNum > 1 ) - {//drop both - Cmd_SaberDrop_f( ent, 1 ); - Cmd_SaberDrop_f( ent, 0 ); + if (saberNum > 1) { // drop both + Cmd_SaberDrop_f(ent, 1); + Cmd_SaberDrop_f(ent, 0); + } else { // drop either left or right + Cmd_SaberDrop_f(ent, saberNum); } - else - {//drop either left or right - Cmd_SaberDrop_f( ent, saberNum ); - } - } - else - { - gi.SendServerCommand( clientNum, va("print \"Unknown command %s\n\"", cmd ) ); + } else { + gi.SendServerCommand(clientNum, va("print \"Unknown command %s\n\"", cmd)); } } diff --git a/code/game/g_combat.cpp b/code/game/g_combat.cpp index 32fee2e01d..300aa4263b 100644 --- a/code/game/g_combat.cpp +++ b/code/game/g_combat.cpp @@ -34,73 +34,72 @@ along with this program; if not, see . #include "Q3_Interface.h" #include "g_navigator.h" -#define TURN_OFF 0x00000100 - -extern qboolean Rosh_TwinPresent( gentity_t *self ); -extern void G_CheckCharmed( gentity_t *self ); -extern qboolean Wampa_CheckDropVictim( gentity_t *self, qboolean excludeMe ); - -extern cvar_t *g_debugDamage; -extern qboolean stop_icarus; -extern cvar_t *g_dismemberment; -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *g_saberPickuppableDroppedSabers; -extern cvar_t *g_timescale; -extern cvar_t *d_slowmodeath; +#define TURN_OFF 0x00000100 + +extern qboolean Rosh_TwinPresent(gentity_t *self); +extern void G_CheckCharmed(gentity_t *self); +extern qboolean Wampa_CheckDropVictim(gentity_t *self, qboolean excludeMe); + +extern cvar_t *g_debugDamage; +extern qboolean stop_icarus; +extern cvar_t *g_dismemberment; +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *g_saberPickuppableDroppedSabers; +extern cvar_t *g_timescale; +extern cvar_t *d_slowmodeath; extern gentity_t *player; -extern cvar_t *debug_subdivision; -extern cvar_t *g_dismemberProbabilities; +extern cvar_t *debug_subdivision; +extern cvar_t *g_dismemberProbabilities; gentity_t *g_lastClientDamaged; extern int killPlayerTimer; -extern void G_VehicleStartExplosionDelay( gentity_t *self ); -extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern qboolean G_TeamEnemy( gentity_t *self ); -extern void CG_ChangeWeapon( int num ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern void G_ATSTCheckPain( gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern qboolean PM_SpinningAnim( int anim ); -extern qboolean PM_RunningAnim( int anim ); -extern int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum = 0 ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInReturn( int move ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_LockedAnim( int anim ); -extern qboolean PM_KnockDownAnim( int anim ); -extern void G_SpeechEvent( gentity_t *self, int event ); -extern qboolean Rosh_BeingHealed( gentity_t *self ); - -static int G_CheckForLedge( gentity_t *self, vec3_t fallCheckDir, float checkDist ); -static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ); -static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ); -static void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod ); -static qboolean G_Dismemberable( gentity_t *self, int hitLoc ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); - - -qboolean G_GetRootSurfNameWithVariant( gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize ); +extern void G_VehicleStartExplosionDelay(gentity_t *self); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern qboolean G_TeamEnemy(gentity_t *self); +extern void CG_ChangeWeapon(int num); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); + +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern void G_ATSTCheckPain(gentity_t *self, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern qboolean PM_SpinningAnim(int anim); +extern qboolean PM_RunningAnim(int anim); +extern int PM_PowerLevelForSaberAnim(playerState_t *ps, int saberNum = 0); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInReturn(int move); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_LockedAnim(int anim); +extern qboolean PM_KnockDownAnim(int anim); +extern void G_SpeechEvent(gentity_t *self, int event); +extern qboolean Rosh_BeingHealed(gentity_t *self); + +static int G_CheckForLedge(gentity_t *self, vec3_t fallCheckDir, float checkDist); +static int G_CheckSpecialDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc); +static int G_PickDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc); +static void G_TrackWeaponUsage(gentity_t *self, gentity_t *inflictor, int add, int mod); +static qboolean G_Dismemberable(gentity_t *self, int hitLoc); +extern gitem_t *FindItemForAmmo(ammo_t ammo); +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); + +qboolean G_GetRootSurfNameWithVariant(gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize); /* ============ AddScore @@ -108,8 +107,8 @@ AddScore Adds score to both the client and his team ============ */ -void AddScore( gentity_t *ent, int score ) { - if ( !ent->client ) { +void AddScore(gentity_t *ent, int score) { + if (!ent->client) { return; } // no scoring during pre-match warmup @@ -123,100 +122,69 @@ TossClientItems Toss the weapon and powerups for the killed player ================= */ -extern gentity_t *WP_DropThermal( gentity_t *ent ); -extern qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -gentity_t *TossClientItems( gentity_t *self ) -{ - //FIXME: drop left-hand weapon, too? - gentity_t *dropped = NULL; - gitem_t *item = NULL; - int weapon; - - if ( self->client->NPC_class == CLASS_SEEKER - || self->client->NPC_class == CLASS_REMOTE - || self->client->NPC_class == CLASS_SABER_DROID - || self->client->NPC_class == CLASS_VEHICLE - || self->client->NPC_class == CLASS_ATST) - { +extern gentity_t *WP_DropThermal(gentity_t *ent); +extern qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +gentity_t *TossClientItems(gentity_t *self) { + // FIXME: drop left-hand weapon, too? + gentity_t *dropped = NULL; + gitem_t *item = NULL; + int weapon; + + if (self->client->NPC_class == CLASS_SEEKER || self->client->NPC_class == CLASS_REMOTE || self->client->NPC_class == CLASS_SABER_DROID || + self->client->NPC_class == CLASS_VEHICLE || self->client->NPC_class == CLASS_ATST) { // these things are so small that they shouldn't bother throwing anything return NULL; } // drop the weapon if not a saber or enemy-only weapon weapon = self->s.weapon; - if ( weapon == WP_SABER ) - { - if ( self->weaponModel[0] < 0 ) - {//don't have one in right hand + if (weapon == WP_SABER) { + if (self->weaponModel[0] < 0) { // don't have one in right hand self->s.weapon = WP_NONE; - } - else if ( !(self->client->ps.saber[0].saberFlags&SFL_NOT_DISARMABLE) - || g_saberPickuppableDroppedSabers->integer ) - {//okay to drop it - if ( WP_SaberLose( self, NULL ) ) - { + } else if (!(self->client->ps.saber[0].saberFlags & SFL_NOT_DISARMABLE) || g_saberPickuppableDroppedSabers->integer) { // okay to drop it + if (WP_SaberLose(self, NULL)) { self->s.weapon = WP_NONE; } } - if ( g_saberPickuppableDroppedSabers->integer ) - {//drop your left one, too - if ( self->weaponModel[1] >= 0 ) - {//have one in left - if ( !(self->client->ps.saber[0].saberFlags&SFL_NOT_DISARMABLE) - || g_saberPickuppableDroppedSabers->integer ) - {//okay to drop it - //just drop an item - if ( self->client->ps.saber[1].name - && self->client->ps.saber[1].name[0] ) - {//have a valid string to use for saberType - //turn it into a pick-uppable item! - if ( G_DropSaberItem( self->client->ps.saber[1].name, self->client->ps.saber[1].blade[0].color, self->client->renderInfo.handLPoint, self->client->ps.velocity, self->currentAngles ) != NULL ) - {//dropped it - WP_RemoveSaber( self, 1 ); + if (g_saberPickuppableDroppedSabers->integer) { // drop your left one, too + if (self->weaponModel[1] >= 0) { // have one in left + if (!(self->client->ps.saber[0].saberFlags & SFL_NOT_DISARMABLE) || g_saberPickuppableDroppedSabers->integer) { // okay to drop it + // just drop an item + if (self->client->ps.saber[1].name && self->client->ps.saber[1].name[0]) { // have a valid string to use for saberType + // turn it into a pick-uppable item! + if (G_DropSaberItem(self->client->ps.saber[1].name, self->client->ps.saber[1].blade[0].color, self->client->renderInfo.handLPoint, + self->client->ps.velocity, self->currentAngles) != NULL) { // dropped it + WP_RemoveSaber(self, 1); } } } } } - } - else if ( weapon == WP_BLASTER_PISTOL ) - {//FIXME: either drop the pistol and make the pickup only give ammo or drop ammo - } - else if ( weapon == WP_STUN_BATON - || weapon == WP_MELEE ) - {//never drop these - } - else if ( weapon > WP_SABER && weapon <= MAX_PLAYER_WEAPONS )//&& self->client->ps.ammo[ weaponData[weapon].ammoIndex ] + } else if (weapon == WP_BLASTER_PISTOL) { // FIXME: either drop the pistol and make the pickup only give ammo or drop ammo + } else if (weapon == WP_STUN_BATON || weapon == WP_MELEE) { // never drop these + } else if (weapon > WP_SABER && weapon <= MAX_PLAYER_WEAPONS) //&& self->client->ps.ammo[ weaponData[weapon].ammoIndex ] { self->s.weapon = WP_NONE; - if ( weapon == WP_THERMAL && self->client->ps.torsoAnim == BOTH_ATTACK10 ) - {//we were getting ready to throw the thermal, drop it! - self->client->ps.weaponChargeTime = level.time - FRAMETIME;//so it just kind of drops it - dropped = WP_DropThermal( self ); - } - else - {// find the item type for this weapon - item = FindItemForWeapon( (weapon_t) weapon ); + if (weapon == WP_THERMAL && self->client->ps.torsoAnim == BOTH_ATTACK10) { // we were getting ready to throw the thermal, drop it! + self->client->ps.weaponChargeTime = level.time - FRAMETIME; // so it just kind of drops it + dropped = WP_DropThermal(self); + } else { // find the item type for this weapon + item = FindItemForWeapon((weapon_t)weapon); } - if ( item && !dropped ) - { + if (item && !dropped) { // spawn the item - dropped = Drop_Item( self, item, 0, qtrue ); - //TEST: dropped items never go away + dropped = Drop_Item(self, item, 0, qtrue); + // TEST: dropped items never go away dropped->e_ThinkFunc = thinkF_NULL; dropped->nextthink = -1; - if ( !self->s.number ) - {//player's dropped items never go away - //dropped->e_ThinkFunc = thinkF_NULL; - //dropped->nextthink = -1; - dropped->count = 0;//no ammo - } - else - {//FIXME: base this on the NPC's actual amount of ammo he's used up... - switch ( weapon ) - { + if (!self->s.number) { // player's dropped items never go away + // dropped->e_ThinkFunc = thinkF_NULL; + // dropped->nextthink = -1; + dropped->count = 0; // no ammo + } else { // FIXME: base this on the NPC's actual amount of ammo he's used up... + switch (weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: dropped->count = 20; @@ -243,7 +211,7 @@ gentity_t *TossClientItems( gentity_t *self ) dropped->count = 3; break; case WP_CONCUSSION: - dropped->count = 200;//12; + dropped->count = 200; // 12; break; case WP_THERMAL: dropped->count = 4; @@ -263,75 +231,58 @@ gentity_t *TossClientItems( gentity_t *self ) } } // well, dropped weapons are G2 models, so they have to be initialised if they want to draw..give us a radius so we don't get prematurely culled - if ( weapon != WP_THERMAL - && weapon != WP_TRIP_MINE - && weapon != WP_DET_PACK ) - { - gi.G2API_InitGhoul2Model( dropped->ghoul2, item->world_model, G_ModelIndex( item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0); + if (weapon != WP_THERMAL && weapon != WP_TRIP_MINE && weapon != WP_DET_PACK) { + gi.G2API_InitGhoul2Model(dropped->ghoul2, item->world_model, G_ModelIndex(item->world_model), NULL_HANDLE, NULL_HANDLE, 0, 0); dropped->s.radius = 10; } } } -// else if (( self->client->NPC_class == CLASS_SENTRY ) || ( self->client->NPC_class == CLASS_PROBE )) // Looks dumb, Steve told us to take it out. -// { -// item = FindItemForAmmo( AMMO_BLASTER ); -// Drop_Item( self, item, 0, qtrue ); -// } - else if ( self->client->NPC_class == CLASS_MARK1 ) - { + // else if (( self->client->NPC_class == CLASS_SENTRY ) || ( self->client->NPC_class == CLASS_PROBE )) // Looks dumb, Steve told us to take it out. + // { + // item = FindItemForAmmo( AMMO_BLASTER ); + // Drop_Item( self, item, 0, qtrue ); + // } + else if (self->client->NPC_class == CLASS_MARK1) { - if (Q_irand( 1, 2 )>1) - { - item = FindItemForAmmo( AMMO_METAL_BOLTS ); - } - else - { - item = FindItemForAmmo( AMMO_BLASTER ); + if (Q_irand(1, 2) > 1) { + item = FindItemForAmmo(AMMO_METAL_BOLTS); + } else { + item = FindItemForAmmo(AMMO_BLASTER); } - Drop_Item( self, item, 0, qtrue ); - } - else if ( self->client->NPC_class == CLASS_MARK2 ) - { + Drop_Item(self, item, 0, qtrue); + } else if (self->client->NPC_class == CLASS_MARK2) { - if (Q_irand( 1, 2 )>1) - { - item = FindItemForAmmo( AMMO_METAL_BOLTS ); - } - else - { - item = FindItemForAmmo( AMMO_POWERCELL ); + if (Q_irand(1, 2) > 1) { + item = FindItemForAmmo(AMMO_METAL_BOLTS); + } else { + item = FindItemForAmmo(AMMO_POWERCELL); } - Drop_Item( self, item, 0, qtrue ); + Drop_Item(self, item, 0, qtrue); } - return dropped;//NOTE: presumes only drop one thing + return dropped; // NOTE: presumes only drop one thing } -void G_DropKey( gentity_t *self ) -{//drop whatever security key I was holding - gitem_t *item = NULL; - if ( !Q_stricmp( "goodie", self->message ) ) - { - item = FindItemForInventory( INV_GOODIE_KEY ); +void G_DropKey(gentity_t *self) { // drop whatever security key I was holding + gitem_t *item = NULL; + if (!Q_stricmp("goodie", self->message)) { + item = FindItemForInventory(INV_GOODIE_KEY); + } else { + item = FindItemForInventory(INV_SECURITY_KEY); } - else - { - item = FindItemForInventory( INV_SECURITY_KEY ); - } - gentity_t *dropped = Drop_Item( self, item, 0, qtrue ); - //Don't throw the key - VectorClear( dropped->s.pos.trDelta ); + gentity_t *dropped = Drop_Item(self, item, 0, qtrue); + // Don't throw the key + VectorClear(dropped->s.pos.trDelta); dropped->message = self->message; self->message = NULL; } -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) -{ - if(self->target) +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { + if (self->target) G_UseTargets(self, attacker); - //remove my script_targetname - G_FreeEntity( self ); + // remove my script_targetname + G_FreeEntity(self); } /* ================== @@ -339,129 +290,101 @@ ExplodeDeath ================== */ -//FIXME: all hacked up... +// FIXME: all hacked up... -void ExplodeDeath( gentity_t *self ) -{ -// gentity_t *tent; - vec3_t forward; +void ExplodeDeath(gentity_t *self) { + // gentity_t *tent; + vec3_t forward; - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops self->s.loopSound = 0; - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); -// tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); - AngleVectors(self->s.angles, forward, NULL, NULL); // FIXME: letting effect always shoot up? Might be ok. + // tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); + AngleVectors(self->s.angles, forward, NULL, NULL); // FIXME: letting effect always shoot up? Might be ok. - if ( self->fxID > 0 ) - { - G_PlayEffect( self->fxID, self->currentOrigin, forward ); + if (self->fxID > 0) { + G_PlayEffect(self->fxID, self->currentOrigin, forward); } -// else -// { -// CG_SurfaceExplosion( self->currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all exploders! -// G_Sound(self, self->sounds ); -// } + // else + // { + // CG_SurfaceExplosion( self->currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all + //exploders! G_Sound(self, self->sounds ); + // } - if(self->splashDamage > 0 && self->splashRadius > 0) - { + if (self->splashDamage > 0 && self->splashRadius > 0) { gentity_t *attacker = self; - if ( self->owner ) - { + if (self->owner) { attacker = self->owner; } - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, - attacker, MOD_UNKNOWN ); + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - ObjectDie( self, self, self, 20, 0 ); + ObjectDie(self, self, self, 20, 0); } -void ExplodeDeath_Wait( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ +void ExplodeDeath_Wait(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { self->e_DieFunc = dieF_NULL; self->nextthink = level.time + Q_irand(100, 500); self->e_ThinkFunc = thinkF_ExplodeDeath; } -void ExplodeDeath( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ +void ExplodeDeath(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { self->currentOrigin[2] += 16; // me bad for hacking this. should either do it in the effect file or make a custom explode death?? - ExplodeDeath( self ); + ExplodeDeath(self); } -void GoExplodeDeath( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void GoExplodeDeath(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - self->targetname = NULL; //Make sure this entity cannot be told to explode again (recursive death fix) + self->targetname = NULL; // Make sure this entity cannot be told to explode again (recursive death fix) - ExplodeDeath( self ); + ExplodeDeath(self); } -qboolean G_ActivateBehavior (gentity_t *self, int bset ); -void G_CheckVictoryScript(gentity_t *self) -{ - if ( !G_ActivateBehavior( self, BSET_VICTORY ) ) - { - if ( self->NPC && self->s.weapon == WP_SABER ) - {//Jedi taunt from within their AI - self->NPC->blockedSpeechDebounceTime = 0;//get them ready to taunt +qboolean G_ActivateBehavior(gentity_t *self, int bset); +void G_CheckVictoryScript(gentity_t *self) { + if (!G_ActivateBehavior(self, BSET_VICTORY)) { + if (self->NPC && self->s.weapon == WP_SABER) { // Jedi taunt from within their AI + self->NPC->blockedSpeechDebounceTime = 0; // get them ready to taunt return; } - if ( self->client && self->client->NPC_class == CLASS_GALAKMECH ) - { + if (self->client && self->client->NPC_class == CLASS_GALAKMECH) { self->wait = 1; - TIMER_Set( self, "gloatTime", Q_irand( 5000, 8000 ) ); - self->NPC->blockedSpeechDebounceTime = 0;//get him ready to taunt + TIMER_Set(self, "gloatTime", Q_irand(5000, 8000)); + self->NPC->blockedSpeechDebounceTime = 0; // get him ready to taunt return; } - //FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? - if ( self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand( 0, 2 ) ) - {//sometimes have the group commander speak instead - self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); - } - else if ( self->NPC ) - { - self->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + // FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? + if (self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && + self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand(0, 2)) { // sometimes have the group commander speak instead + self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + } else if (self->NPC) { + self->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); } } } -qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) -{ - if ( ent1->s.number < MAX_CLIENTS - && ent1->client - && ent1->client->playerTeam == TEAM_FREE ) - {//evil player *has* no allies +qboolean OnSameTeam(gentity_t *ent1, gentity_t *ent2) { + if (ent1->s.number < MAX_CLIENTS && ent1->client && ent1->client->playerTeam == TEAM_FREE) { // evil player *has* no allies return qfalse; } - if ( ent2->s.number < MAX_CLIENTS - && ent2->client - && ent2->client->playerTeam == TEAM_FREE ) - {//evil player *has* no allies + if (ent2->s.number < MAX_CLIENTS && ent2->client && ent2->client->playerTeam == TEAM_FREE) { // evil player *has* no allies return qfalse; } - if ( !ent1->client || !ent2->client ) - { - if ( ent1->noDamageTeam ) - { - if ( ent2->client && ent2->client->playerTeam == ent1->noDamageTeam ) - { + if (!ent1->client || !ent2->client) { + if (ent1->noDamageTeam) { + if (ent2->client && ent2->client->playerTeam == ent1->noDamageTeam) { return qtrue; - } - else if ( ent2->noDamageTeam == ent1->noDamageTeam ) - { - if ( ent1->splashDamage && ent2->splashDamage && Q_stricmp("ambient_etherian_fliers", ent1->classname) != 0 ) - {//Barrels, exploding breakables and mines will blow each other up + } else if (ent2->noDamageTeam == ent1->noDamageTeam) { + if (ent1->splashDamage && ent2->splashDamage && + Q_stricmp("ambient_etherian_fliers", ent1->classname) != 0) { // Barrels, exploding breakables and mines will blow each other up return qfalse; - } - else - { + } else { return qtrue; } } @@ -470,105 +393,97 @@ qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) } // shouldn't need this anymore, there were problems with certain droids, but now they have been labeled TEAM_ENEMY so this isn't needed -// if ((( ent1->client->playerTeam == TEAM_IMPERIAL ) && ( ent1->client->playerTeam == TEAM_BOTS )) || -// (( ent1->client->playerTeam == TEAM_BOTS ) && ( ent1->client->playerTeam == TEAM_IMPERIAL ))) -// { -// return qtrue; -// } + // if ((( ent1->client->playerTeam == TEAM_IMPERIAL ) && ( ent1->client->playerTeam == TEAM_BOTS )) || + // (( ent1->client->playerTeam == TEAM_BOTS ) && ( ent1->client->playerTeam == TEAM_IMPERIAL ))) + // { + // return qtrue; + // } - return (qboolean)( ent1->client->playerTeam == ent2->client->playerTeam ); + return (qboolean)(ent1->client->playerTeam == ent2->client->playerTeam); } - /* ------------------------- G_AlertTeam ------------------------- */ -void G_AlertTeam( gentity_t *victim, gentity_t *attacker, float radius, float soundDist ) -{ - gentity_t *radiusEnts[ 128 ]; - vec3_t mins, maxs; - int numEnts; - int i; - float distSq, sndDistSq = (soundDist*soundDist); +void G_AlertTeam(gentity_t *victim, gentity_t *attacker, float radius, float soundDist) { + gentity_t *radiusEnts[128]; + vec3_t mins, maxs; + int numEnts; + int i; + float distSq, sndDistSq = (soundDist * soundDist); - if ( attacker == NULL || attacker->client == NULL ) + if (attacker == NULL || attacker->client == NULL) return; - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = victim->currentOrigin[i] - radius; maxs[i] = victim->currentOrigin[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - //Cull this list - for ( i = 0; i < numEnts; i++ ) - { - //Validate clients - if ( radiusEnts[i]->client == NULL ) + // Cull this list + for (i = 0; i < numEnts; i++) { + // Validate clients + if (radiusEnts[i]->client == NULL) continue; - //only want NPCs - if ( radiusEnts[i]->NPC == NULL ) + // only want NPCs + if (radiusEnts[i]->NPC == NULL) continue; - //Don't bother if they're ignoring enemies - if ( radiusEnts[i]->svFlags & SVF_IGNORE_ENEMIES ) + // Don't bother if they're ignoring enemies + if (radiusEnts[i]->svFlags & SVF_IGNORE_ENEMIES) continue; - //This NPC specifically flagged to ignore alerts - if ( radiusEnts[i]->NPC->scriptFlags & SCF_IGNORE_ALERTS ) + // This NPC specifically flagged to ignore alerts + if (radiusEnts[i]->NPC->scriptFlags & SCF_IGNORE_ALERTS) continue; - //This NPC specifically flagged to ignore alerts - if ( !(radiusEnts[i]->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) + // This NPC specifically flagged to ignore alerts + if (!(radiusEnts[i]->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES)) continue; - //this ent does not participate in group AI - if ( (radiusEnts[i]->NPC->scriptFlags&SCF_NO_GROUPS) ) + // this ent does not participate in group AI + if ((radiusEnts[i]->NPC->scriptFlags & SCF_NO_GROUPS)) continue; - //Skip the requested avoid radiusEnts[i] if present - if ( radiusEnts[i] == victim ) + // Skip the requested avoid radiusEnts[i] if present + if (radiusEnts[i] == victim) continue; - //Skip the attacker - if ( radiusEnts[i] == attacker ) + // Skip the attacker + if (radiusEnts[i] == attacker) continue; - //Must be on the same team - if ( radiusEnts[i]->client->playerTeam != victim->client->playerTeam ) + // Must be on the same team + if (radiusEnts[i]->client->playerTeam != victim->client->playerTeam) continue; - //Must be alive - if ( radiusEnts[i]->health <= 0 ) + // Must be alive + if (radiusEnts[i]->health <= 0) continue; - if ( radiusEnts[i]->enemy == NULL ) - {//only do this if they're not already mad at someone - distSq = DistanceSquared( radiusEnts[i]->currentOrigin, victim->currentOrigin ); - if ( distSq > 16384 /*128 squared*/ && !gi.inPVS( victim->currentOrigin, radiusEnts[i]->currentOrigin ) ) - {//not even potentially visible/hearable + if (radiusEnts[i]->enemy == NULL) { // only do this if they're not already mad at someone + distSq = DistanceSquared(radiusEnts[i]->currentOrigin, victim->currentOrigin); + if (distSq > 16384 /*128 squared*/ && !gi.inPVS(victim->currentOrigin, radiusEnts[i]->currentOrigin)) { // not even potentially visible/hearable continue; } - //NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... - if ( soundDist <= 0 || distSq > sndDistSq ) - {//out of sound range - if ( !InFOV( victim, radiusEnts[i], radiusEnts[i]->NPC->stats.hfov, radiusEnts[i]->NPC->stats.vfov ) - || !NPC_ClearLOS( radiusEnts[i], victim->currentOrigin ) ) - {//out of FOV or no LOS + // NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... + if (soundDist <= 0 || distSq > sndDistSq) { // out of sound range + if (!InFOV(victim, radiusEnts[i], radiusEnts[i]->NPC->stats.hfov, radiusEnts[i]->NPC->stats.vfov) || + !NPC_ClearLOS(radiusEnts[i], victim->currentOrigin)) { // out of FOV or no LOS continue; } } - //FIXME: This can have a nasty cascading effect if setup wrong... - G_SetEnemy( radiusEnts[i], attacker ); + // FIXME: This can have a nasty cascading effect if setup wrong... + G_SetEnemy(radiusEnts[i], attacker); } } } @@ -579,12 +494,11 @@ G_DeathAlert ------------------------- */ -#define DEATH_ALERT_RADIUS 512 -#define DEATH_ALERT_SOUND_RADIUS 512 +#define DEATH_ALERT_RADIUS 512 +#define DEATH_ALERT_SOUND_RADIUS 512 -void G_DeathAlert( gentity_t *victim, gentity_t *attacker ) -{//FIXME: with all the other alert stuff, do we really need this? - G_AlertTeam( victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS ); +void G_DeathAlert(gentity_t *victim, gentity_t *attacker) { // FIXME: with all the other alert stuff, do we really need this? + G_AlertTeam(victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS); } /* @@ -596,277 +510,247 @@ Not to be confused with NPC_RemoveBodyEffects (NPC.cpp), which only applies effe ---------------------------------------- */ -void DeathFX( gentity_t *ent ) -{ - if ( !ent || !ent->client ) +void DeathFX(gentity_t *ent) { + if (!ent || !ent->client) return; -/* - switch( ent->client->playerTeam ) - { - case TEAM_BOTS: - if (!Q_stricmp( ent->NPC_type, "mouse" )) + /* + switch( ent->client->playerTeam ) { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] -= 20; + case TEAM_BOTS: + if (!Q_stricmp( ent->NPC_type, "mouse" )) + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] -= 20; - G_PlayEffect( "mouseexplosion1", effectPos ); - G_PlayEffect( "smaller_chunks", effectPos ); + G_PlayEffect( "mouseexplosion1", effectPos ); + G_PlayEffect( "smaller_chunks", effectPos ); - } - else if (!Q_stricmp( ent->NPC_type, "probe" )) - { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] += 50; + } + else if (!Q_stricmp( ent->NPC_type, "probe" )) + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] += 50; - G_PlayEffect( "probeexplosion1", effectPos ); - G_PlayEffect( "small_chunks", effectPos ); - } - else - { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); - G_PlayEffect( "small_chunks", effectPos ); - } + G_PlayEffect( "probeexplosion1", effectPos ); + G_PlayEffect( "small_chunks", effectPos ); + } + else + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] -= 15; + G_PlayEffect( "droidexplosion1", effectPos ); + G_PlayEffect( "small_chunks", effectPos ); + } - break; + break; - default: - break; - } -*/ + default: + break; + } + */ // team no longer indicates species/race. NPC_class should be used to identify certain npc types - vec3_t effectPos, right; - switch(ent->client->NPC_class) - { + vec3_t effectPos, right; + switch (ent->client->NPC_class) { case CLASS_MOUSE: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 20; - G_PlayEffect( "env/small_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mouse/misc/death1" ); + G_PlayEffect("env/small_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mouse/misc/death1"); break; case CLASS_PROBE: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] += 50; - G_PlayEffect( "explosions/probeexplosion1", effectPos ); + G_PlayEffect("explosions/probeexplosion1", effectPos); break; case CLASS_ATST: - AngleVectors( ent->currentAngles, NULL, right, NULL ); - VectorMA( ent->currentOrigin, 20, right, effectPos ); + AngleVectors(ent->currentAngles, NULL, right, NULL); + VectorMA(ent->currentOrigin, 20, right, effectPos); effectPos[2] += 180; - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - VectorMA( effectPos, -40, right, effectPos ); - G_PlayEffect( "explosions/droidexplosion1", effectPos ); + G_PlayEffect("explosions/droidexplosion1", effectPos); + VectorMA(effectPos, -40, right, effectPos); + G_PlayEffect("explosions/droidexplosion1", effectPos); break; case CLASS_SEEKER: case CLASS_REMOTE: - G_PlayEffect( "env/small_explode", ent->currentOrigin ); + G_PlayEffect("env/small_explode", ent->currentOrigin); break; case CLASS_GONK: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 5; -// statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); - G_SoundOnEnt( ent, CHAN_AUTO, va("sound/chars/gonk/misc/death%d.wav",Q_irand( 1, 3 )) ); - G_PlayEffect( "env/med_explode", effectPos ); + // statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); + G_SoundOnEnt(ent, CHAN_AUTO, va("sound/chars/gonk/misc/death%d.wav", Q_irand(1, 3))); + G_PlayEffect("env/med_explode", effectPos); break; // should list all remaining droids here, hope I didn't miss any case CLASS_R2D2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffect( "env/med_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("env/med_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; - case CLASS_PROTOCOL://?? + case CLASS_PROTOCOL: //?? case CLASS_R5D2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffect( "env/med_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("env/med_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; case CLASS_MARK2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("explosions/droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; case CLASS_INTERROGATOR: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/interrogator/misc/int_droid_explo" ); + G_PlayEffect("explosions/droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/interrogator/misc/int_droid_explo"); break; case CLASS_MARK1: - AngleVectors( ent->currentAngles, NULL, right, NULL ); - VectorMA( ent->currentOrigin, 10, right, effectPos ); + AngleVectors(ent->currentAngles, NULL, right, NULL); + VectorMA(ent->currentOrigin, 10, right, effectPos); effectPos[2] -= 15; - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffect( "explosions/droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark1/misc/mark1_explo" ); + G_PlayEffect("explosions/droidexplosion1", effectPos); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffect("explosions/droidexplosion1", effectPos); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffect("explosions/droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark1/misc/mark1_explo"); break; case CLASS_SENTRY: - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/sentry/misc/sentry_explo" ); - VectorCopy( ent->currentOrigin, effectPos ); - G_PlayEffect( "env/med_explode", effectPos ); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/sentry/misc/sentry_explo"); + VectorCopy(ent->currentOrigin, effectPos); + G_PlayEffect("env/med_explode", effectPos); break; default: break; - } - } -void G_SetMissionStatusText( gentity_t *attacker, int mod ) -{ - if ( statusTextIndex >= 0 ) - { +void G_SetMissionStatusText(gentity_t *attacker, int mod) { + if (statusTextIndex >= 0) { return; } - if ( mod == MOD_FALLING ) - {//fell to your death + if (mod == MOD_FALLING) { // fell to your death statusTextIndex = STAT_WATCHYOURSTEP; - } - else if ( mod == MOD_CRUSH ) - {//crushed + } else if (mod == MOD_CRUSH) { // crushed statusTextIndex = STAT_JUDGEMENTMUCHDESIRED; - } - else if ( attacker && Q_stricmp( "trigger_hurt", attacker->classname ) == 0 ) - {//Killed by something that should have been clearly dangerous -// statusTextIndex = Q_irand( IGT_JUDGEMENTDESIRED, IGT_JUDGEMENTMUCHDESIRED ); + } else if (attacker && Q_stricmp("trigger_hurt", attacker->classname) == 0) { // Killed by something that should have been clearly dangerous + // statusTextIndex = Q_irand( IGT_JUDGEMENTDESIRED, IGT_JUDGEMENTMUCHDESIRED ); statusTextIndex = STAT_JUDGEMENTMUCHDESIRED; - } - else if ( attacker && attacker->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) - {//killed by a teammate + } else if (attacker && attacker->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER) { // killed by a teammate statusTextIndex = STAT_INSUBORDINATION; } } -void G_MakeTeamVulnerable( void ) -{ +void G_MakeTeamVulnerable(void) { int i, newhealth; gentity_t *ent; gentity_t *self = &g_entities[0]; - if ( !self->client ) - { + if (!self->client) { return; } -// for ( i = 0; i < globals.num_entities ; i++, ent++) - for ( i = 0; i < globals.num_entities ; i++) - { - if(!PInUse(i)) + // for ( i = 0; i < globals.num_entities ; i++, ent++) + for (i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if ( !ent->inuse ) -// { -// continue; -// } -// if ( !ent ) -// { -// continue; -// } - ent=&g_entities[i]; - if ( !ent->client ) - { + // if ( !ent->inuse ) + // { + // continue; + // } + // if ( !ent ) + // { + // continue; + // } + ent = &g_entities[i]; + if (!ent->client) { continue; } - if ( ent->client->playerTeam != TEAM_PLAYER ) - { + if (ent->client->playerTeam != TEAM_PLAYER) { continue; } - if ( !(ent->flags&FL_UNDYING) ) - { + if (!(ent->flags & FL_UNDYING)) { continue; } ent->flags &= ~FL_UNDYING; - newhealth = Q_irand( 5, 40 ); - if ( ent->health > newhealth ) - { + newhealth = Q_irand(5, 40); + if (ent->health > newhealth) { ent->health = newhealth; } } } -void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ) -{ - //FIXME: allow them to specify a different focal entity or point? - if ( g_timescale->value != 1.0 || in_camera ) - {//already in some slow-mo mode or in_camera +void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0) { + // FIXME: allow them to specify a different focal entity or point? + if (g_timescale->value != 1.0 || in_camera) { // already in some slow-mo mode or in_camera return; } - gentity_t *matrix = G_Spawn(); - if ( matrix ) - { - G_SetOrigin( matrix, ent->currentOrigin ); - gi.linkentity( matrix ); + gentity_t *matrix = G_Spawn(); + if (matrix) { + G_SetOrigin(matrix, ent->currentOrigin); + gi.linkentity(matrix); matrix->s.otherEntityNum = ent->s.number; matrix->e_clThinkFunc = clThinkF_CG_MatrixEffect; matrix->s.eType = ET_THINKER; - matrix->svFlags |= SVF_BROADCAST;// Broadcast to all clients + matrix->svFlags |= SVF_BROADCAST; // Broadcast to all clients matrix->s.time = level.time; matrix->s.eventParm = length; - //now the cgame decides when to remove us... in case the framerate chugs so severely that it never finishes the effect before it removes itself! - //matrix->e_ThinkFunc = thinkF_G_FreeEntity; - //matrix->nextthink = level.time + length + 500; + // now the cgame decides when to remove us... in case the framerate chugs so severely that it never finishes the effect before it removes itself! + // matrix->e_ThinkFunc = thinkF_G_FreeEntity; + // matrix->nextthink = level.time + length + 500; matrix->s.boltInfo = meFlags; matrix->s.time2 = spinTime; matrix->s.angles2[0] = timeScale; } } -qboolean G_JediInRoom( vec3_t from ) -{ +qboolean G_JediInRoom(vec3_t from) { gentity_t *ent; int i; -// for ( i = 1, ent = &g_entities[1]; i < globals.num_entities; i++, ent++ ) - for ( i = 1; i < globals.num_entities; i++) - { - if(!PInUse(i)) + // for ( i = 1, ent = &g_entities[1]; i < globals.num_entities; i++, ent++ ) + for (i = 1; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if ( !ent->inuse ) -// { -// continue; -// } -// if ( !ent ) -// { -// continue; -// } + // if ( !ent->inuse ) + // { + // continue; + // } + // if ( !ent ) + // { + // continue; + // } ent = &g_entities[i]; - if ( !ent->NPC ) - { + if (!ent->NPC) { continue; } - if ( ent->health <= 0 ) - { + if (ent->health <= 0) { continue; } - if ( ent->s.eFlags&EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( ent->s.weapon != WP_SABER ) - { + if (ent->s.weapon != WP_SABER) { continue; } - if ( !gi.inPVS( ent->currentOrigin, from ) ) - { + if (!gi.inPVS(ent->currentOrigin, from)) { continue; } return qtrue; @@ -874,436 +758,299 @@ qboolean G_JediInRoom( vec3_t from ) return qfalse; } -qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod, saberType_t saberType ) -{ +qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod, saberType_t saberType) { qboolean dismember = qfalse; *hitLoc = HL_NONE; - if ( !surfName || !surfName[0] ) - { + if (!surfName || !surfName[0]) { return qfalse; } - if( !ent->client ) - { + if (!ent->client) { return qfalse; } - if ( ent->client - && ( ent->client->NPC_class == CLASS_R2D2 - || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_GONK - || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_SENTRY - || ent->client->NPC_class == CLASS_INTERROGATOR - || ent->client->NPC_class == CLASS_PROBE ) ) - {//we don't care about per-surface hit-locations or dismemberment for these guys + if (ent->client && (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_GONK || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_SENTRY || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_PROBE)) { // we don't care about per-surface hit-locations or dismemberment for these guys return qfalse; } - if ( ent->client && (ent->client->NPC_class == CLASS_ATST) ) - { - //FIXME: almost impossible to hit these... perhaps we should + if (ent->client && (ent->client->NPC_class == CLASS_ATST)) { + // FIXME: almost impossible to hit these... perhaps we should // check for splashDamage and do radius damage to these parts? // Or, if we ever get bbox G2 traces, that may fix it, too - if (!Q_stricmp("head_light_blaster_cann",surfName)) - { + if (!Q_stricmp("head_light_blaster_cann", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("head_concussion_charger",surfName)) - { + } else if (!Q_stricmp("head_concussion_charger", surfName)) { *hitLoc = HL_ARM_RT; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK1) ) - { - if (!Q_stricmp("l_arm",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK1)) { + if (!Q_stricmp("l_arm", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("r_arm",surfName)) - { + } else if (!Q_stricmp("r_arm", surfName)) { *hitLoc = HL_ARM_RT; - } - else if (!Q_stricmp("torso_front",surfName)) - { + } else if (!Q_stricmp("torso_front", surfName)) { *hitLoc = HL_CHEST; - } - else if (!Q_stricmp("torso_tube1",surfName)) - { + } else if (!Q_stricmp("torso_tube1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_tube2",surfName)) - { + } else if (!Q_stricmp("torso_tube2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_tube3",surfName)) - { + } else if (!Q_stricmp("torso_tube3", surfName)) { *hitLoc = HL_GENERIC3; - } - else if (!Q_stricmp("torso_tube4",surfName)) - { + } else if (!Q_stricmp("torso_tube4", surfName)) { *hitLoc = HL_GENERIC4; - } - else if (!Q_stricmp("torso_tube5",surfName)) - { + } else if (!Q_stricmp("torso_tube5", surfName)) { *hitLoc = HL_GENERIC5; - } - else if (!Q_stricmp("torso_tube6",surfName)) - { + } else if (!Q_stricmp("torso_tube6", surfName)) { *hitLoc = HL_GENERIC6; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK2) ) - { - if (!Q_stricmp("torso_canister1",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK2)) { + if (!Q_stricmp("torso_canister1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_canister2",surfName)) - { + } else if (!Q_stricmp("torso_canister2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_canister3",surfName)) - { + } else if (!Q_stricmp("torso_canister3", surfName)) { *hitLoc = HL_GENERIC3; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_GALAKMECH) ) - { - if (!Q_stricmp("torso_antenna",surfName)||!Q_stricmp("torso_antenna_base",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_GALAKMECH)) { + if (!Q_stricmp("torso_antenna", surfName) || !Q_stricmp("torso_antenna_base", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_shield",surfName)) - { + } else if (!Q_stricmp("torso_shield", surfName)) { *hitLoc = HL_GENERIC2; - } - else - { + } else { *hitLoc = HL_CHEST; } - return(qfalse); + return (qfalse); } - - //FIXME: check the hitLoc and hitDir against the cap tag for the place - //where the split will be- if the hit dir is roughly perpendicular to - //the direction of the cap, then the split is allowed, otherwise we - //hit it at the wrong angle and should not dismember... - int actualTime = (cg.time?cg.time:level.time); - if ( !Q_stricmpn( "hips", surfName, 4 ) ) - {//FIXME: test properly for legs + // FIXME: check the hitLoc and hitDir against the cap tag for the place + // where the split will be- if the hit dir is roughly perpendicular to + // the direction of the cap, then the split is allowed, otherwise we + // hit it at the wrong angle and should not dismember... + int actualTime = (cg.time ? cg.time : level.time); + if (!Q_stricmpn("hips", surfName, 4)) { // FIXME: test properly for legs *hitLoc = HL_WAIST; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->kneeLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->kneeLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->kneeLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->kneeLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_LT; } } - if (*hitLoc == HL_WAIST) - { - if (ent->kneeRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->kneeRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (*hitLoc == HL_WAIST) { + if (ent->kneeRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->kneeRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_RT; } } } } - } - else if ( !Q_stricmpn( "torso", surfName, 5 ) ) - { - if ( !ent->client ) - { + } else if (!Q_stricmpn("torso", surfName, 5)) { + if (!ent->client) { *hitLoc = HL_CHEST; - } - else - { - vec3_t t_fwd, t_rt, t_up, dirToImpact; + } else { + vec3_t t_fwd, t_rt, t_up, dirToImpact; float frontSide, rightSide, upSide; - AngleVectors( ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up ); - VectorSubtract( point, ent->client->renderInfo.torsoPoint, dirToImpact ); - frontSide = DotProduct( t_fwd, dirToImpact ); - rightSide = DotProduct( t_rt, dirToImpact ); - upSide = DotProduct( t_up, dirToImpact ); - if ( upSide < -10 ) - {//hit at waist + AngleVectors(ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up); + VectorSubtract(point, ent->client->renderInfo.torsoPoint, dirToImpact); + frontSide = DotProduct(t_fwd, dirToImpact); + rightSide = DotProduct(t_rt, dirToImpact); + upSide = DotProduct(t_up, dirToImpact); + if (upSide < -10) { // hit at waist *hitLoc = HL_WAIST; - } - else - {//hit on upper torso - if ( rightSide > 4 ) - { + } else { // hit on upper torso + if (rightSide > 4) { *hitLoc = HL_ARM_RT; - } - else if ( rightSide < -4 ) - { + } else if (rightSide < -4) { *hitLoc = HL_ARM_LT; - } - else if ( rightSide > 2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide > 2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_RT; - } - else - { + } else { *hitLoc = HL_BACK_RT; } - } - else if ( rightSide < -2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide < -2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_LT; - } - else - { + } else { *hitLoc = HL_BACK_LT; } - } - else if ( upSide > -3 && mod == MOD_SABER ) - { + } else if (upSide > -3 && mod == MOD_SABER) { *hitLoc = HL_HEAD; - } - else if ( frontSide > 0 ) - { + } else if (frontSide > 0) { *hitLoc = HL_CHEST; - } - else - { + } else { *hitLoc = HL_BACK; } } } - } - else if ( !Q_stricmpn( "head", surfName, 4 ) ) - { + } else if (!Q_stricmpn("head", surfName, 4)) { *hitLoc = HL_HEAD; - } - else if ( !Q_stricmpn( "r_arm", surfName, 5 ) ) - { + } else if (!Q_stricmpn("r_arm", surfName, 5)) { *hitLoc = HL_ARM_RT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->handRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->handRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->handRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_RT; } } } - } - else if ( !Q_stricmpn( "l_arm", surfName, 5 ) ) - { + } else if (!Q_stricmpn("l_arm", surfName, 5)) { *hitLoc = HL_ARM_LT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->handLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->handLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->handLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_LT; } } } - } - else if ( !Q_stricmpn( "r_leg", surfName, 5 ) ) - { + } else if (!Q_stricmpn("r_leg", surfName, 5)) { *hitLoc = HL_LEG_RT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->footRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->footRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->footRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->footRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_RT; } } } - } - else if ( !Q_stricmpn( "l_leg", surfName, 5 ) ) - { + } else if (!Q_stricmpn("l_leg", surfName, 5)) { *hitLoc = HL_LEG_LT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->footLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->footLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->footLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->footLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_LT; } } } - } - else if ( mod == MOD_SABER && WP_BreakSaber( ent, surfName, saberType ) ) - {//saber hit and broken + } else if (mod == MOD_SABER && WP_BreakSaber(ent, surfName, saberType)) { // saber hit and broken *hitLoc = HL_HAND_RT; - } - else if ( !Q_stricmpn( "r_hand", surfName, 6 ) || !Q_stricmpn( "w_", surfName, 2 ) ) - {//right hand or weapon - //FIXME: if hit weapon, chance of breaking saber (if sabers.cfg entry shows it as breakable) + } else if (!Q_stricmpn("r_hand", surfName, 6) || !Q_stricmpn("w_", surfName, 2)) { // right hand or weapon + // FIXME: if hit weapon, chance of breaking saber (if sabers.cfg entry shows it as breakable) // if breaks, remove saber and replace with the 2 replacement sabers (preserve color, length, etc.) *hitLoc = HL_HAND_RT; - } - else if ( !Q_stricmpn( "l_hand", surfName, 6 ) ) - { + } else if (!Q_stricmpn("l_hand", surfName, 6)) { *hitLoc = HL_HAND_LT; - } - else if ( ent->client && ent->client->ps.powerups[PW_GALAK_SHIELD] && !Q_stricmp( "force_shield", surfName ) ) - { + } else if (ent->client && ent->client->ps.powerups[PW_GALAK_SHIELD] && !Q_stricmp("force_shield", surfName)) { *hitLoc = HL_GENERIC2; } #ifdef _DEBUG - else - { - Com_Printf( "ERROR: surface %s does not belong to any hitLocation!!!\n", surfName ); + else { + Com_Printf("ERROR: surface %s does not belong to any hitLocation!!!\n", surfName); } #endif //_DEBUG - if ( g_saberRealisticCombat->integer > 1 - || debug_subdivision->integer ) - { + if (g_saberRealisticCombat->integer > 1 || debug_subdivision->integer) { dismember = qtrue; - } - else if ( ent->client && ent->client->NPC_class == CLASS_PROTOCOL ) - { + } else if (ent->client && ent->client->NPC_class == CLASS_PROTOCOL) { dismember = qtrue; - } - else if ( ent->client && ent->client->NPC_class == CLASS_ASSASSIN_DROID ) - { + } else if (ent->client && ent->client->NPC_class == CLASS_ASSASSIN_DROID) { dismember = qtrue; - } - else if ( ent->client && ent->client->NPC_class == CLASS_SABER_DROID ) - { + } else if (ent->client && ent->client->NPC_class == CLASS_SABER_DROID) { dismember = qtrue; - } - else if ( debug_subdivision->integer || !ent->client->dismembered ) - { - if ( dir && (dir[0] || dir[1] || dir[2]) && - bladeDir && (bladeDir[0] || bladeDir[1] || bladeDir[2]) ) - {//we care about direction (presumably for dismemberment) - if ( g_dismemberProbabilities->value<=0.0f||G_Dismemberable( ent, *hitLoc ) ) - {//the probability let us continue + } else if (debug_subdivision->integer || !ent->client->dismembered) { + if (dir && (dir[0] || dir[1] || dir[2]) && bladeDir && + (bladeDir[0] || bladeDir[1] || bladeDir[2])) { // we care about direction (presumably for dismemberment) + if (g_dismemberProbabilities->value <= 0.0f || G_Dismemberable(ent, *hitLoc)) { // the probability let us continue const char *tagName = NULL; - float aoa = 0.5f; - //dir must be roughly perpendicular to the hitLoc's cap bolt - switch ( *hitLoc ) - { - case HL_LEG_RT: - tagName = "*hips_cap_r_leg"; - break; - case HL_LEG_LT: - tagName = "*hips_cap_l_leg"; - break; - case HL_WAIST: - tagName = "*hips_cap_torso"; - aoa = 0.25f; - break; - case HL_CHEST_RT: - case HL_ARM_RT: - case HL_BACK_LT: - tagName = "*torso_cap_r_arm"; - break; - case HL_CHEST_LT: - case HL_ARM_LT: - case HL_BACK_RT: - tagName = "*torso_cap_l_arm"; - break; - case HL_HAND_RT: - tagName = "*r_arm_cap_r_hand"; - break; - case HL_HAND_LT: - tagName = "*l_arm_cap_l_hand"; - break; - case HL_HEAD: - tagName = "*torso_cap_head"; - aoa = 0.25f; - break; - case HL_CHEST: - case HL_BACK: - case HL_FOOT_RT: - case HL_FOOT_LT: - default: - //no dismemberment possible with these, so no checks needed - break; + float aoa = 0.5f; + // dir must be roughly perpendicular to the hitLoc's cap bolt + switch (*hitLoc) { + case HL_LEG_RT: + tagName = "*hips_cap_r_leg"; + break; + case HL_LEG_LT: + tagName = "*hips_cap_l_leg"; + break; + case HL_WAIST: + tagName = "*hips_cap_torso"; + aoa = 0.25f; + break; + case HL_CHEST_RT: + case HL_ARM_RT: + case HL_BACK_LT: + tagName = "*torso_cap_r_arm"; + break; + case HL_CHEST_LT: + case HL_ARM_LT: + case HL_BACK_RT: + tagName = "*torso_cap_l_arm"; + break; + case HL_HAND_RT: + tagName = "*r_arm_cap_r_hand"; + break; + case HL_HAND_LT: + tagName = "*l_arm_cap_l_hand"; + break; + case HL_HEAD: + tagName = "*torso_cap_head"; + aoa = 0.25f; + break; + case HL_CHEST: + case HL_BACK: + case HL_FOOT_RT: + case HL_FOOT_LT: + default: + // no dismemberment possible with these, so no checks needed + break; } - if ( tagName ) - { - int tagBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], tagName ); - if ( tagBolt != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, tagDir, angles; - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, tagBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, tagDir ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//hit close - float dot = DotProduct( dir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//hit roughly perpendicular - dot = DotProduct( bladeDir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//blade was roughly perpendicular + if (tagName) { + int tagBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], tagName); + if (tagBolt != -1) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, tagDir, angles; + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, tagBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tagDir); + if (DistanceSquared(point, tagOrg) < 256) { // hit close + float dot = DotProduct(dir, tagDir); + if (dot < aoa && dot > -aoa) { // hit roughly perpendicular + dot = DotProduct(bladeDir, tagDir); + if (dot < aoa && dot > -aoa) { // blade was roughly perpendicular dismember = qtrue; } } @@ -1316,286 +1063,225 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit return dismember; } -int G_GetHitLocation ( gentity_t *target, const vec3_t ppoint ) -{ - vec3_t point, point_dir; - vec3_t forward, right, up; - vec3_t tangles, tcenter; - float udot, fdot, rdot; - int Vertical, Forward, Lateral; - int HitLoc; - -//get target forward, right and up - if(target->client) - {//ignore player's pitch and roll +int G_GetHitLocation(gentity_t *target, const vec3_t ppoint) { + vec3_t point, point_dir; + vec3_t forward, right, up; + vec3_t tangles, tcenter; + float udot, fdot, rdot; + int Vertical, Forward, Lateral; + int HitLoc; + + // get target forward, right and up + if (target->client) { // ignore player's pitch and roll VectorSet(tangles, 0, target->currentAngles[YAW], 0); } AngleVectors(tangles, forward, right, up); -//get center of target + // get center of target VectorAdd(target->absmin, target->absmax, tcenter); VectorScale(tcenter, 0.5, tcenter); -//get impact point - if(ppoint && !VectorCompare(ppoint, vec3_origin)) - { + // get impact point + if (ppoint && !VectorCompare(ppoint, vec3_origin)) { VectorCopy(ppoint, point); - } - else - { + } else { return HL_NONE; } -/* -//get impact dir - if(pdir && !VectorCompare(pdir, vec3_origin)) - { - VectorCopy(pdir, dir); - } - else - { - return; - } + /* + //get impact dir + if(pdir && !VectorCompare(pdir, vec3_origin)) + { + VectorCopy(pdir, dir); + } + else + { + return; + } -//put point at controlled distance from center - VectorSubtract(point, tcenter, tempvec); - tempvec[2] = 0; - hdist = VectorLength(tempvec); + //put point at controlled distance from center + VectorSubtract(point, tcenter, tempvec); + tempvec[2] = 0; + hdist = VectorLength(tempvec); - VectorMA(point, hdist - tradius, dir, point); - //now a point on the surface of a cylinder with a radius of tradius -*/ + VectorMA(point, hdist - tradius, dir, point); + //now a point on the surface of a cylinder with a radius of tradius + */ VectorSubtract(point, tcenter, point_dir); VectorNormalize(point_dir); - //Get bottom to top (Vertical) position index + // Get bottom to top (Vertical) position index udot = DotProduct(up, point_dir); - if(udot>.800) + if (udot > .800) Vertical = 4; - else if(udot>.400) + else if (udot > .400) Vertical = 3; - else if(udot>-.333) + else if (udot > -.333) Vertical = 2; - else if(udot>-.666) + else if (udot > -.666) Vertical = 1; else Vertical = 0; - //Get back to front (Forward) position index + // Get back to front (Forward) position index fdot = DotProduct(forward, point_dir); - if(fdot>.666) + if (fdot > .666) Forward = 4; - else if(fdot>.333) + else if (fdot > .333) Forward = 3; - else if(fdot>-.333) + else if (fdot > -.333) Forward = 2; - else if(fdot>-.666) + else if (fdot > -.666) Forward = 1; else Forward = 0; - //Get left to right (Lateral) position index + // Get left to right (Lateral) position index rdot = DotProduct(right, point_dir); - if(rdot>.666) + if (rdot > .666) Lateral = 4; - else if(rdot>.333) + else if (rdot > .333) Lateral = 3; - else if(rdot>-.333) + else if (rdot > -.333) Lateral = 2; - else if(rdot>-.666) + else if (rdot > -.666) Lateral = 1; else Lateral = 0; HitLoc = Vertical * 25 + Forward * 5 + Lateral; - if(HitLoc <= 10) - {//feet - if ( rdot > 0 ) - { + if (HitLoc <= 10) { // feet + if (rdot > 0) { return HL_FOOT_RT; - } - else - { + } else { return HL_FOOT_LT; } - } - else if(HitLoc <= 50) - {//legs - if ( rdot > 0 ) - { + } else if (HitLoc <= 50) { // legs + if (rdot > 0) { return HL_LEG_RT; - } - else - { + } else { return HL_LEG_LT; } - } - else if ( HitLoc == 56||HitLoc == 60||HitLoc == 61||HitLoc == 65||HitLoc == 66||HitLoc == 70 ) - {//hands - if ( rdot > 0 ) - { + } else if (HitLoc == 56 || HitLoc == 60 || HitLoc == 61 || HitLoc == 65 || HitLoc == 66 || HitLoc == 70) { // hands + if (rdot > 0) { return HL_HAND_RT; - } - else - { + } else { return HL_HAND_LT; } - } - else if ( HitLoc == 83||HitLoc == 87||HitLoc == 88||HitLoc == 92||HitLoc == 93||HitLoc == 97 ) - {//arms - if ( rdot > 0 ) - { + } else if (HitLoc == 83 || HitLoc == 87 || HitLoc == 88 || HitLoc == 92 || HitLoc == 93 || HitLoc == 97) { // arms + if (rdot > 0) { return HL_ARM_RT; - } - else - { + } else { return HL_ARM_LT; } - } - else if((HitLoc >= 107 && HitLoc <= 109)|| - (HitLoc >= 112 && HitLoc <= 114)|| - (HitLoc >= 117 && HitLoc <= 119)) - {//head + } else if ((HitLoc >= 107 && HitLoc <= 109) || (HitLoc >= 112 && HitLoc <= 114) || (HitLoc >= 117 && HitLoc <= 119)) { // head return HL_HEAD; - } - else - { - if ( udot < 0.3 ) - { + } else { + if (udot < 0.3) { return HL_WAIST; - } - else if ( fdot < 0 ) - { - if ( rdot > 0.4 ) - { + } else if (fdot < 0) { + if (rdot > 0.4) { return HL_BACK_RT; - } - else if ( rdot < -0.4 ) - { + } else if (rdot < -0.4) { return HL_BACK_LT; - } - else - { + } else { return HL_BACK; } - } - else - { - if ( rdot > 0.3 ) - { + } else { + if (rdot > 0.3) { return HL_CHEST_RT; - } - else if ( rdot < -0.3 ) - { + } else if (rdot < -0.3) { return HL_CHEST_LT; - } - else - { + } else { return HL_CHEST; } } } - //return HL_NONE; + // return HL_NONE; } -int G_PickPainAnim( gentity_t *self, const vec3_t point, int damage, int hitLoc = HL_NONE ) -{ - if ( hitLoc == HL_NONE ) - { - hitLoc = G_GetHitLocation( self, point ); +int G_PickPainAnim(gentity_t *self, const vec3_t point, int damage, int hitLoc = HL_NONE) { + if (hitLoc == HL_NONE) { + hitLoc = G_GetHitLocation(self, point); } - switch( hitLoc ) - { + switch (hitLoc) { case HL_FOOT_RT: return BOTH_PAIN12; - //PAIN12 = right foot + // PAIN12 = right foot break; case HL_FOOT_LT: return -1; break; case HL_LEG_RT: - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { return BOTH_PAIN11; - } - else - { + } else { return BOTH_PAIN13; } - //PAIN11 = twitch right leg - //PAIN13 = right knee + // PAIN11 = twitch right leg + // PAIN13 = right knee break; case HL_LEG_LT: return BOTH_PAIN14; - //PAIN14 = twitch left leg + // PAIN14 = twitch left leg break; case HL_BACK_RT: return BOTH_PAIN7; - //PAIN7 = med left shoulder + // PAIN7 = med left shoulder break; case HL_BACK_LT: - return Q_irand( BOTH_PAIN15, BOTH_PAIN16 ); - //PAIN15 = med right shoulder - //PAIN16 = twitch right shoulder + return Q_irand(BOTH_PAIN15, BOTH_PAIN16); + // PAIN15 = med right shoulder + // PAIN16 = twitch right shoulder break; case HL_BACK: - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { return BOTH_PAIN1; - } - else - { + } else { return BOTH_PAIN5; } - //PAIN1 = back - //PAIN5 = same as 1 + // PAIN1 = back + // PAIN5 = same as 1 break; case HL_CHEST_RT: return BOTH_PAIN3; - //PAIN3 = long, right shoulder + // PAIN3 = long, right shoulder break; case HL_CHEST_LT: return BOTH_PAIN2; - //PAIN2 = long, left shoulder + // PAIN2 = long, left shoulder break; case HL_WAIST: case HL_CHEST: - if ( !Q_irand( 0, 3 ) ) - { + if (!Q_irand(0, 3)) { return BOTH_PAIN6; - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 2)) { return BOTH_PAIN8; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { return BOTH_PAIN17; - } - else - { + } else { return BOTH_PAIN18; } - //PAIN6 = gut - //PAIN8 = chest - //PAIN17 = twitch crotch - //PAIN19 = med crotch + // PAIN6 = gut + // PAIN8 = chest + // PAIN17 = twitch crotch + // PAIN19 = med crotch break; case HL_ARM_RT: case HL_HAND_RT: return BOTH_PAIN9; - //PAIN9 = twitch right arm + // PAIN9 = twitch right arm break; case HL_ARM_LT: case HL_HAND_LT: return BOTH_PAIN10; - //PAIN10 = twitch left arm + // PAIN10 = twitch left arm break; case HL_HEAD: return BOTH_PAIN4; - //PAIN4 = head + // PAIN4 = head break; default: return -1; @@ -1603,359 +1289,286 @@ int G_PickPainAnim( gentity_t *self, const vec3_t point, int damage, int hitLoc } } -extern void G_BounceMissile( gentity_t *ent, trace_t *trace ); -void LimbThink( gentity_t *ent ) -{//FIXME: just use object thinking? - vec3_t origin; - trace_t tr; - +extern void G_BounceMissile(gentity_t *ent, trace_t *trace); +void LimbThink(gentity_t *ent) { // FIXME: just use object thinking? + vec3_t origin; + trace_t tr; ent->nextthink = level.time + FRAMETIME; - if ( ent->owner - && ent->owner->client - && (ent->owner->client->ps.eFlags&EF_HELD_BY_RANCOR) ) - { + if (ent->owner && ent->owner->client && (ent->owner->client->ps.eFlags & EF_HELD_BY_RANCOR)) { ent->e_ThinkFunc = thinkF_G_FreeEntity; return; } - if ( ent->enemy ) - {//alert people that I am a piece of one of their friends - AddSightEvent( ent->enemy, ent->currentOrigin, 384, AEL_DISCOVERED ); + if (ent->enemy) { // alert people that I am a piece of one of their friends + AddSightEvent(ent->enemy, ent->currentOrigin, 384, AEL_DISCOVERED); } - if ( ent->s.pos.trType == TR_STATIONARY ) - {//stopped - if ( level.time > ent->s.apos.trTime + ent->s.apos.trDuration ) - { - if (ent->owner && ent->owner->m_pVehicle) - { - ent->nextthink = level.time + Q_irand( 10000, 15000 ); - } - else - { - ent->nextthink = level.time + Q_irand( 5000, 15000 ); + if (ent->s.pos.trType == TR_STATIONARY) { // stopped + if (level.time > ent->s.apos.trTime + ent->s.apos.trDuration) { + if (ent->owner && ent->owner->m_pVehicle) { + ent->nextthink = level.time + Q_irand(10000, 15000); + } else { + ent->nextthink = level.time + Q_irand(5000, 15000); } ent->e_ThinkFunc = thinkF_G_FreeEntity; - //FIXME: these keep drawing for a frame or so after being freed?! See them lerp to origin of world... - } - else - { - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + // FIXME: these keep drawing for a frame or so after being freed?! See them lerp to origin of world... + } else { + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); } return; } // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); // get current angles - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, (EG2_Collision)0, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, (EG2_Collision)0, 0); - VectorCopy( tr.endpos, ent->currentOrigin ); - if ( tr.startsolid ) - { + VectorCopy(tr.endpos, ent->currentOrigin); + if (tr.startsolid) { tr.fraction = 0; } + gi.linkentity(ent); - gi.linkentity( ent ); - - if ( tr.fraction != 1 ) - { - G_BounceMissile( ent, &tr ); - if ( ent->s.pos.trType == TR_STATIONARY ) - {//stopped, stop spinning - //lay flat - //pitch - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - vec3_t flatAngles; - if ( ent->s.angles2[0] == -1 ) - {//any pitch is okay + if (tr.fraction != 1) { + G_BounceMissile(ent, &tr); + if (ent->s.pos.trType == TR_STATIONARY) { // stopped, stop spinning + // lay flat + // pitch + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + vec3_t flatAngles; + if (ent->s.angles2[0] == -1) { // any pitch is okay flatAngles[0] = ent->currentAngles[0]; - } - else - {//lay flat - if ( ent->owner - && ent->owner->client - && ent->owner->client->NPC_class == CLASS_PROTOCOL - && ent->count == BOTH_DISMEMBER_TORSO1 ) - { - if ( ent->currentAngles[0] > 0 || ent->currentAngles[0] < -180 ) - { + } else { // lay flat + if (ent->owner && ent->owner->client && ent->owner->client->NPC_class == CLASS_PROTOCOL && ent->count == BOTH_DISMEMBER_TORSO1) { + if (ent->currentAngles[0] > 0 || ent->currentAngles[0] < -180) { flatAngles[0] = -90; + } else { + flatAngles[0] = 90; } - else - { - flatAngles[0] = 90; - } - } - else - { - if ( ent->currentAngles[0] > 90 || ent->currentAngles[0] < -90 ) - { - flatAngles[0] = 180; - } - else - { + } else { + if (ent->currentAngles[0] > 90 || ent->currentAngles[0] < -90) { + flatAngles[0] = 180; + } else { flatAngles[0] = 0; } } } - //yaw + // yaw flatAngles[1] = ent->currentAngles[1]; - //roll - if ( ent->s.angles2[2] == -1 ) - {//any roll is okay + // roll + if (ent->s.angles2[2] == -1) { // any roll is okay flatAngles[2] = ent->currentAngles[2]; - } - else - { - if ( ent->currentAngles[2] > 90 || ent->currentAngles[2] < -90 ) - { + } else { + if (ent->currentAngles[2] > 90 || ent->currentAngles[2] < -90) { flatAngles[2] = 180; - } - else - { + } else { flatAngles[2] = 0; } } - VectorSubtract( flatAngles, ent->s.apos.trBase, ent->s.apos.trDelta ); - for ( int i = 0; i < 3; i++ ) - { - ent->s.apos.trDelta[i] = AngleNormalize180( ent->s.apos.trDelta[i] ); + VectorSubtract(flatAngles, ent->s.apos.trBase, ent->s.apos.trDelta); + for (int i = 0; i < 3; i++) { + ent->s.apos.trDelta[i] = AngleNormalize180(ent->s.apos.trDelta[i]); } ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 1000; ent->s.apos.trType = TR_LINEAR_STOP; - //VectorClear( ent->s.apos.trDelta ); + // VectorClear( ent->s.apos.trDelta ); } } } -float hitLocHealthPercentage[HL_MAX] = -{ - 0.0f, //HL_NONE = 0, - 0.05f, //HL_FOOT_RT, - 0.05f, //HL_FOOT_LT, - 0.20f, //HL_LEG_RT, - 0.20f, //HL_LEG_LT, - 0.30f, //HL_WAIST, - 0.15f, //HL_BACK_RT, - 0.15f, //HL_BACK_LT, - 0.30f, //HL_BACK, - 0.15f, //HL_CHEST_RT, - 0.15f, //HL_CHEST_LT, - 0.30f, //HL_CHEST, - 0.05f, //HL_ARM_RT, - 0.05f, //HL_ARM_LT, - 0.01f, //HL_HAND_RT, - 0.01f, //HL_HAND_LT, - 0.10f, //HL_HEAD - 0.0f, //HL_GENERIC1, - 0.0f, //HL_GENERIC2, - 0.0f, //HL_GENERIC3, - 0.0f, //HL_GENERIC4, - 0.0f, //HL_GENERIC5, - 0.0f //HL_GENERIC6 +float hitLocHealthPercentage[HL_MAX] = { + 0.0f, // HL_NONE = 0, + 0.05f, // HL_FOOT_RT, + 0.05f, // HL_FOOT_LT, + 0.20f, // HL_LEG_RT, + 0.20f, // HL_LEG_LT, + 0.30f, // HL_WAIST, + 0.15f, // HL_BACK_RT, + 0.15f, // HL_BACK_LT, + 0.30f, // HL_BACK, + 0.15f, // HL_CHEST_RT, + 0.15f, // HL_CHEST_LT, + 0.30f, // HL_CHEST, + 0.05f, // HL_ARM_RT, + 0.05f, // HL_ARM_LT, + 0.01f, // HL_HAND_RT, + 0.01f, // HL_HAND_LT, + 0.10f, // HL_HEAD + 0.0f, // HL_GENERIC1, + 0.0f, // HL_GENERIC2, + 0.0f, // HL_GENERIC3, + 0.0f, // HL_GENERIC4, + 0.0f, // HL_GENERIC5, + 0.0f // HL_GENERIC6 }; -const char *hitLocName[HL_MAX] = -{ - "none", //HL_NONE = 0, - "right foot", //HL_FOOT_RT, - "left foot", //HL_FOOT_LT, - "right leg", //HL_LEG_RT, - "left leg", //HL_LEG_LT, - "waist", //HL_WAIST, - "back right shoulder", //HL_BACK_RT, - "back left shoulder", //HL_BACK_LT, - "back", //HL_BACK, - "front right shouler", //HL_CHEST_RT, - "front left shoulder", //HL_CHEST_LT, - "chest", //HL_CHEST, - "right arm", //HL_ARM_RT, - "left arm", //HL_ARM_LT, - "right hand", //HL_HAND_RT, - "left hand", //HL_HAND_LT, - "head", //HL_HEAD - "generic1", //HL_GENERIC1, - "generic2", //HL_GENERIC2, - "generic3", //HL_GENERIC3, - "generic4", //HL_GENERIC4, - "generic5", //HL_GENERIC5, - "generic6" //HL_GENERIC6 +const char *hitLocName[HL_MAX] = { + "none", // HL_NONE = 0, + "right foot", // HL_FOOT_RT, + "left foot", // HL_FOOT_LT, + "right leg", // HL_LEG_RT, + "left leg", // HL_LEG_LT, + "waist", // HL_WAIST, + "back right shoulder", // HL_BACK_RT, + "back left shoulder", // HL_BACK_LT, + "back", // HL_BACK, + "front right shouler", // HL_CHEST_RT, + "front left shoulder", // HL_CHEST_LT, + "chest", // HL_CHEST, + "right arm", // HL_ARM_RT, + "left arm", // HL_ARM_LT, + "right hand", // HL_HAND_RT, + "left hand", // HL_HAND_LT, + "head", // HL_HEAD + "generic1", // HL_GENERIC1, + "generic2", // HL_GENERIC2, + "generic3", // HL_GENERIC3, + "generic4", // HL_GENERIC4, + "generic5", // HL_GENERIC5, + "generic6" // HL_GENERIC6 }; -qboolean G_LimbLost( gentity_t *ent, int hitLoc ) -{ - switch ( hitLoc ) - { +qboolean G_LimbLost(gentity_t *ent, int hitLoc) { + switch (hitLoc) { case HL_FOOT_RT: - if ( ent->locationDamage[HL_FOOT_RT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_FOOT_RT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_LEG_RT: - //NOTE: feet fall through - if ( ent->locationDamage[HL_LEG_RT] >= Q3_INFINITE ) - { + // NOTE: feet fall through + if (ent->locationDamage[HL_LEG_RT] >= Q3_INFINITE) { return qtrue; } return qfalse; break; case HL_FOOT_LT: - if ( ent->locationDamage[HL_FOOT_LT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_FOOT_LT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_LEG_LT: - //NOTE: feet fall through - if ( ent->locationDamage[HL_LEG_LT] >= Q3_INFINITE ) - { + // NOTE: feet fall through + if (ent->locationDamage[HL_LEG_LT] >= Q3_INFINITE) { return qtrue; } return qfalse; break; case HL_HAND_LT: - if ( ent->locationDamage[HL_HAND_LT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HAND_LT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_ARM_LT: case HL_CHEST_LT: case HL_BACK_RT: - //NOTE: hand falls through - if ( ent->locationDamage[HL_ARM_LT] >= Q3_INFINITE - || ent->locationDamage[HL_CHEST_LT] >= Q3_INFINITE - || ent->locationDamage[HL_BACK_RT] >= Q3_INFINITE - || ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: hand falls through + if (ent->locationDamage[HL_ARM_LT] >= Q3_INFINITE || ent->locationDamage[HL_CHEST_LT] >= Q3_INFINITE || + ent->locationDamage[HL_BACK_RT] >= Q3_INFINITE || ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; break; case HL_HAND_RT: - if ( ent->locationDamage[HL_HAND_RT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HAND_RT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_ARM_RT: case HL_CHEST_RT: case HL_BACK_LT: - //NOTE: hand falls through - if ( ent->locationDamage[HL_ARM_RT] >= Q3_INFINITE - || ent->locationDamage[HL_CHEST_RT] >= Q3_INFINITE - || ent->locationDamage[HL_BACK_LT] >= Q3_INFINITE - || ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: hand falls through + if (ent->locationDamage[HL_ARM_RT] >= Q3_INFINITE || ent->locationDamage[HL_CHEST_RT] >= Q3_INFINITE || + ent->locationDamage[HL_BACK_LT] >= Q3_INFINITE || ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; break; case HL_HEAD: - if ( ent->locationDamage[HL_HEAD] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HEAD] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_WAIST: - //NOTE: head falls through - if ( ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: head falls through + if (ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; default: - return (qboolean)(ent->locationDamage[hitLoc]>=Q3_INFINITE); + return (qboolean)(ent->locationDamage[hitLoc] >= Q3_INFINITE); } } -extern qboolean G_GetRootSurfNameWithVariant( gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize ); -void G_RemoveWeaponsWithLimbs( gentity_t *ent, gentity_t *limb, int limbAnim ) -{ - int weaponModelNum = 0, checkAnim; - char handName[MAX_QPATH]; +extern qboolean G_GetRootSurfNameWithVariant(gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize); +void G_RemoveWeaponsWithLimbs(gentity_t *ent, gentity_t *limb, int limbAnim) { + int weaponModelNum = 0, checkAnim; + char handName[MAX_QPATH]; - for ( weaponModelNum = 0; weaponModelNum < MAX_INHAND_WEAPONS; weaponModelNum++ ) - { - if ( ent->weaponModel[weaponModelNum] >= 0 ) - {//have a weapon in this hand - if ( weaponModelNum == 0 && ent->client->ps.saberInFlight ) - {//this is the right-hand weapon and it's a saber in-flight (i.e.: not in-hand, so no need to worry about it) + for (weaponModelNum = 0; weaponModelNum < MAX_INHAND_WEAPONS; weaponModelNum++) { + if (ent->weaponModel[weaponModelNum] >= 0) { // have a weapon in this hand + if (weaponModelNum == 0 && + ent->client->ps.saberInFlight) { // this is the right-hand weapon and it's a saber in-flight (i.e.: not in-hand, so no need to worry about it) continue; } - //otherwise, the corpse hasn't dropped their weapon - switch ( weaponModelNum ) - { - case 0://right hand + // otherwise, the corpse hasn't dropped their weapon + switch (weaponModelNum) { + case 0: // right hand checkAnim = BOTH_DISMEMBER_RARM; - G_GetRootSurfNameWithVariant( ent, "r_hand", handName, sizeof(handName) ); + G_GetRootSurfNameWithVariant(ent, "r_hand", handName, sizeof(handName)); break; - case 1://left hand + case 1: // left hand checkAnim = BOTH_DISMEMBER_LARM; - G_GetRootSurfNameWithVariant( ent, "l_hand", handName, sizeof(handName) ); + G_GetRootSurfNameWithVariant(ent, "l_hand", handName, sizeof(handName)); break; - default://not handled/valid + default: // not handled/valid continue; break; } - if ( limbAnim == checkAnim || limbAnim == BOTH_DISMEMBER_TORSO1 )//either/both hands - {//FIXME: is this first check needed with this lower one? - if ( !gi.G2API_GetSurfaceRenderStatus( &limb->ghoul2[0], handName ) ) - {//only copy the weapon over if the hand is actually on this limb... - //copy it to limb - if ( ent->s.weapon != WP_NONE ) - {//only if they actually still have a weapon + if (limbAnim == checkAnim || limbAnim == BOTH_DISMEMBER_TORSO1) // either/both hands + { // FIXME: is this first check needed with this lower one? + if (!gi.G2API_GetSurfaceRenderStatus(&limb->ghoul2[0], handName)) { // only copy the weapon over if the hand is actually on this limb... + // copy it to limb + if (ent->s.weapon != WP_NONE) { // only if they actually still have a weapon limb->s.weapon = ent->s.weapon; limb->weaponModel[weaponModelNum] = ent->weaponModel[weaponModelNum]; - }//else - weaponModel is not -1 but don't have a weapon? Oops, somehow G2 model wasn't removed? - //remove it on owner - if ( ent->weaponModel[weaponModelNum] > 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[weaponModelNum] ); + } // else - weaponModel is not -1 but don't have a weapon? Oops, somehow G2 model wasn't removed? + // remove it on owner + if (ent->weaponModel[weaponModelNum] > 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[weaponModelNum]); ent->weaponModel[weaponModelNum] = -1; } - if ( !ent->client->ps.saberInFlight ) - {//saberent isn't flying through the air, it's in-hand and attached to player - if ( ent->client->ps.saberEntityNum != ENTITYNUM_NONE && ent->client->ps.saberEntityNum > 0 ) - {//remove the owner ent's saber model and entity - if ( g_entities[ent->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[ent->client->ps.saberEntityNum] ); + if (!ent->client->ps.saberInFlight) { // saberent isn't flying through the air, it's in-hand and attached to player + if (ent->client->ps.saberEntityNum != ENTITYNUM_NONE && + ent->client->ps.saberEntityNum > 0) { // remove the owner ent's saber model and entity + if (g_entities[ent->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[ent->client->ps.saberEntityNum]); } ent->client->ps.saberEntityNum = ENTITYNUM_NONE; } } - } - else - {//the hand had already been removed - if ( ent->weaponModel[weaponModelNum] > 0 ) - {//still a weapon associated with it, remove it from the limb - gi.G2API_RemoveGhoul2Model( limb->ghoul2, ent->weaponModel[weaponModelNum] ); + } else { // the hand had already been removed + if (ent->weaponModel[weaponModelNum] > 0) { // still a weapon associated with it, remove it from the limb + gi.G2API_RemoveGhoul2Model(limb->ghoul2, ent->weaponModel[weaponModelNum]); limb->weaponModel[weaponModelNum] = -1; } } - } - else - {//this weapon isn't affected by this dismemberment - if ( ent->weaponModel[weaponModelNum] > 0 ) - {//but a weapon was copied over to the limb, so remove it - gi.G2API_RemoveGhoul2Model( limb->ghoul2, ent->weaponModel[weaponModelNum] ); + } else { // this weapon isn't affected by this dismemberment + if (ent->weaponModel[weaponModelNum] > 0) { // but a weapon was copied over to the limb, so remove it + gi.G2API_RemoveGhoul2Model(limb->ghoul2, ent->weaponModel[weaponModelNum]); limb->weaponModel[weaponModelNum] = -1; } } @@ -1963,45 +1576,40 @@ void G_RemoveWeaponsWithLimbs( gentity_t *ent, gentity_t *limb, int limbAnim ) } } -static qboolean G_Dismember( gentity_t *ent, vec3_t point, - const char *limbBone, const char *rotateBone, const char *limbName, - const char *limbCapName, const char *stubCapName, const char *limbTagName, const char *stubTagName, - int limbAnim, float limbRollBase, float limbPitchBase, - int damage, int hitLoc ) -{ - //int newBolt; - vec3_t dir, newPoint, limbAngles = {0,ent->client->ps.legsYaw,0}; +static qboolean G_Dismember(gentity_t *ent, vec3_t point, const char *limbBone, const char *rotateBone, const char *limbName, const char *limbCapName, + const char *stubCapName, const char *limbTagName, const char *stubTagName, int limbAnim, float limbRollBase, float limbPitchBase, + int damage, int hitLoc) { + // int newBolt; + vec3_t dir, newPoint, limbAngles = {0, ent->client->ps.legsYaw, 0}; gentity_t *limb; - trace_t trace; - - //make sure this limb hasn't been lopped off already! - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], limbName ) == 0x00000100/*G2SURFACEFLAG_NODESCENDANTS*/ ) - {//already lost this limb - //NOTE: we now check for off wth no decendants - //because the torso surface can be off with - //the torso variations on when this is one of - //our "choose your own jedi" models + trace_t trace; + + // make sure this limb hasn't been lopped off already! + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], limbName) == 0x00000100 /*G2SURFACEFLAG_NODESCENDANTS*/) { // already lost this limb + // NOTE: we now check for off wth no decendants + // because the torso surface can be off with + // the torso variations on when this is one of + // our "choose your own jedi" models return qfalse; } - //NOTE: only reason I have this next part is because G2API_GetSurfaceRenderStatus is *not* working - if ( G_LimbLost( ent, hitLoc ) ) - {//already lost this limb + // NOTE: only reason I have this next part is because G2API_GetSurfaceRenderStatus is *not* working + if (G_LimbLost(ent, hitLoc)) { // already lost this limb return qfalse; } - //FIXME: when timescale is high, can sometimes cut off a surf that includes a surf that was already cut off -//0) create a limb ent - VectorCopy( point, newPoint ); + // FIXME: when timescale is high, can sometimes cut off a surf that includes a surf that was already cut off + // 0) create a limb ent + VectorCopy(point, newPoint); newPoint[2] += 6; limb = G_Spawn(); - G_SetOrigin( limb, newPoint ); - //VectorCopy(ent->currentAngles,limbAngles); - //G_SetAngles( limb, ent->currentAngles ); - VectorCopy( newPoint, limb->s.pos.trBase ); -//1) copy the g2 instance of the victim into the limb - gi.G2API_CopyGhoul2Instance( ent->ghoul2, limb->ghoul2, 0 ); - limb->playerModel = 0;//assumption! + G_SetOrigin(limb, newPoint); + // VectorCopy(ent->currentAngles,limbAngles); + // G_SetAngles( limb, ent->currentAngles ); + VectorCopy(newPoint, limb->s.pos.trBase); + // 1) copy the g2 instance of the victim into the limb + gi.G2API_CopyGhoul2Instance(ent->ghoul2, limb->ghoul2, 0); + limb->playerModel = 0; // assumption! limb->craniumBone = ent->craniumBone; limb->cervicalBone = ent->cervicalBone; limb->thoracicBone = ent->thoracicBone; @@ -2009,9 +1617,8 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, limb->lowerLumbarBone = ent->lowerLumbarBone; limb->hipsBone = ent->hipsBone; limb->rootBone = ent->rootBone; -//2) set the root surf on the limb - if ( limbTagName ) - {//add smoke to cap tag + // 2) set the root surf on the limb + if (limbTagName) { // add smoke to cap tag /*newBolt = gi.G2API_AddBolt( &limb->ghoul2[limb->playerModel], limbTagName ); if ( newBolt != -1 ) { @@ -2026,9 +1633,9 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "upper_lumbar" ); } */ - gi.G2API_StopBoneAnimIndex( &limb->ghoul2[limb->playerModel], limb->hipsBone ); + gi.G2API_StopBoneAnimIndex(&limb->ghoul2[limb->playerModel], limb->hipsBone); - gi.G2API_SetRootSurface( limb->ghoul2, limb->playerModel, limbName ); + gi.G2API_SetRootSurface(limb->ghoul2, limb->playerModel, limbName); /* if ( limbBone && hitLoc != HL_WAIST ) {//play the dismember anim on the limb? @@ -2040,39 +1647,33 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time); } */ - if ( limbBone && hitLoc == HL_WAIST && ent->client->NPC_class == CLASS_PROTOCOL ) - {//play the dismember anim on the limb? - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "model_root" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "motion" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "pelvis" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "upper_lumbar" ); - //FIXME: screws up origin + if (limbBone && hitLoc == HL_WAIST && ent->client->NPC_class == CLASS_PROTOCOL) { // play the dismember anim on the limb? + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "model_root"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "motion"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "pelvis"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "upper_lumbar"); + // FIXME: screws up origin animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - //play the proper dismember anim on the limb + // play the proper dismember anim on the limb gi.G2API_SetBoneAnim(&limb->ghoul2[limb->playerModel], 0, animations[limbAnim].firstFrame, - animations[limbAnim].numFrames + animations[limbAnim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, -1, -1 ); - } - if ( rotateBone ) - { - gi.G2API_SetNewOrigin( &limb->ghoul2[0], gi.G2API_AddBolt( &limb->ghoul2[0], rotateBone ) ); - - //now let's try to position the limb at the *exact* right spot - int newBolt = gi.G2API_AddBolt( &ent->ghoul2[0], rotateBone ); - if ( newBolt != -1 ) - { - int actualTime = (cg.time?cg.time:level.time); - mdxaBone_t boltMatrix; - vec3_t angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, newBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, limb->s.origin ); - G_SetOrigin( limb, limb->s.origin ); - VectorCopy( limb->s.origin, limb->s.pos.trBase ); - //angles, too + animations[limbAnim].numFrames + animations[limbAnim].firstFrame, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, -1, -1); + } + if (rotateBone) { + gi.G2API_SetNewOrigin(&limb->ghoul2[0], gi.G2API_AddBolt(&limb->ghoul2[0], rotateBone)); + + // now let's try to position the limb at the *exact* right spot + int newBolt = gi.G2API_AddBolt(&ent->ghoul2[0], rotateBone); + if (newBolt != -1) { + int actualTime = (cg.time ? cg.time : level.time); + mdxaBone_t boltMatrix; + vec3_t angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, newBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, limb->s.origin); + G_SetOrigin(limb, limb->s.origin); + VectorCopy(limb->s.origin, limb->s.pos.trBase); + // angles, too /* vec3_t limbF, limbR; newBolt = gi.G2API_AddBolt( &ent->ghoul2[0], limbBone ); @@ -2091,20 +1692,18 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, */ } } - if ( limbCapName ) - {//turn on caps - gi.G2API_SetSurfaceOnOff( &limb->ghoul2[limb->playerModel], limbCapName, 0 ); - } -//3) turn off w/descendants that surf in original model -//NOTE: we actually change the ent's stuff on the cgame side so that there is no 50ms lag -// this is neccessary because the Ghoul2 info does not have to go over the network, -// cgame looks at game's data. The new limb ent will be delayed so we will see -// that a limb is missing before the chopped off limb appears. -// also, if the limb was going to start in solid, we can delete it and return - if ( stubTagName ) - {//add smoke to cap surf, spawn effect - //do it later - limb->target = G_NewString( stubTagName ); + if (limbCapName) { // turn on caps + gi.G2API_SetSurfaceOnOff(&limb->ghoul2[limb->playerModel], limbCapName, 0); + } + // 3) turn off w/descendants that surf in original model + // NOTE: we actually change the ent's stuff on the cgame side so that there is no 50ms lag + // this is neccessary because the Ghoul2 info does not have to go over the network, + // cgame looks at game's data. The new limb ent will be delayed so we will see + // that a limb is missing before the chopped off limb appears. + // also, if the limb was going to start in solid, we can delete it and return + if (stubTagName) { // add smoke to cap surf, spawn effect + // do it later + limb->target = G_NewString(stubTagName); /* newBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], stubTagName ); if ( newBolt != -1 ) @@ -2113,71 +1712,66 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, } */ } - if ( limbName ) - { - limb->target2 = G_NewString( limbName ); - //gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], limbName, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS + if (limbName) { + limb->target2 = G_NewString(limbName); + // gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], limbName, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS } - if ( stubCapName ) - {//turn on caps - limb->target3 = G_NewString( stubCapName ); - //gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], stubCapName, 0 ); + if (stubCapName) { // turn on caps + limb->target3 = G_NewString(stubCapName); + // gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], stubCapName, 0 ); } limb->count = limbAnim; -// + // limb->s.radius = 60; -//4) toss the limb away + // 4) toss the limb away limb->classname = "limb"; limb->owner = ent; limb->enemy = ent->enemy; - //remove weapons/move them to limb (if applicable in this dismemberment) - G_RemoveWeaponsWithLimbs( ent, limb, limbAnim ); + // remove weapons/move them to limb (if applicable in this dismemberment) + G_RemoveWeaponsWithLimbs(ent, limb, limbAnim); limb->e_clThinkFunc = clThinkF_CG_Limb; limb->e_ThinkFunc = thinkF_LimbThink; limb->nextthink = level.time + FRAMETIME; - gi.linkentity( limb ); - //need size, contents, clipmask + gi.linkentity(limb); + // need size, contents, clipmask limb->svFlags = SVF_USE_CURRENT_ORIGIN; limb->clipmask = MASK_SOLID; limb->contents = CONTENTS_CORPSE; - VectorSet( limb->mins, -3.0f, -3.0f, -6.0f ); - VectorSet( limb->maxs, 3.0f, 3.0f, 6.0f ); + VectorSet(limb->mins, -3.0f, -3.0f, -6.0f); + VectorSet(limb->maxs, 3.0f, 3.0f, 6.0f); - //make sure it doesn't start in solid - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - if ( trace.startsolid ) - { + // make sure it doesn't start in solid + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] -= limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - if ( trace.startsolid ) - { + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] += limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - if ( trace.startsolid ) - {//stuck? don't remove - G_FreeEntity( limb ); + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0); + if (trace.startsolid) { // stuck? don't remove + G_FreeEntity(limb); return qfalse; } } } - //move it - VectorCopy( limb->s.pos.trBase, limb->currentOrigin ); - gi.linkentity( limb ); + // move it + VectorCopy(limb->s.pos.trBase, limb->currentOrigin); + gi.linkentity(limb); - limb->s.eType = ET_THINKER;//ET_GENERAL; + limb->s.eType = ET_THINKER; // ET_GENERAL; limb->physicsBounce = 0.2f; limb->s.pos.trType = TR_GRAVITY; - limb->s.pos.trTime = level.time; // move a bit on the very first frame - VectorSubtract( point, ent->currentOrigin, dir ); - VectorNormalize( dir ); - //no trDuration? - //spin it - //new way- try to preserve the exact angle and position of the limb as it was when attached - VectorSet( limb->s.angles2, limbPitchBase, 0, limbRollBase ); - VectorCopy( limbAngles, limb->s.apos.trBase ); + limb->s.pos.trTime = level.time; // move a bit on the very first frame + VectorSubtract(point, ent->currentOrigin, dir); + VectorNormalize(dir); + // no trDuration? + // spin it + // new way- try to preserve the exact angle and position of the limb as it was when attached + VectorSet(limb->s.angles2, limbPitchBase, 0, limbRollBase); + VectorCopy(limbAngles, limb->s.apos.trBase); /* //old way- just set an angle... limb->s.apos.trBase[0] += limbPitchBase; @@ -2186,44 +1780,38 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, */ limb->s.apos.trTime = level.time; limb->s.apos.trType = TR_LINEAR; - VectorClear( limb->s.apos.trDelta ); + VectorClear(limb->s.apos.trDelta); - if ( hitLoc == HL_HAND_RT || hitLoc == HL_HAND_LT ) - {//hands fly farther - VectorMA( ent->client->ps.velocity, 200, dir, limb->s.pos.trDelta ); - //make it bounce some + if (hitLoc == HL_HAND_RT || hitLoc == HL_HAND_LT) { // hands fly farther + VectorMA(ent->client->ps.velocity, 200, dir, limb->s.pos.trDelta); + // make it bounce some limb->s.eFlags |= EF_BOUNCE_HALF; - limb->s.apos.trDelta[0] = Q_irand( -300, 300 ); - limb->s.apos.trDelta[1] = Q_irand( -800, 800 ); - } - else if ( limbAnim == BOTH_DISMEMBER_HEAD1 - || limbAnim == BOTH_DISMEMBER_LARM - || limbAnim == BOTH_DISMEMBER_RARM ) - {//head and arms don't fly as far + limb->s.apos.trDelta[0] = Q_irand(-300, 300); + limb->s.apos.trDelta[1] = Q_irand(-800, 800); + } else if (limbAnim == BOTH_DISMEMBER_HEAD1 || limbAnim == BOTH_DISMEMBER_LARM || limbAnim == BOTH_DISMEMBER_RARM) { // head and arms don't fly as far limb->s.eFlags |= EF_BOUNCE_SHRAPNEL; - VectorMA( ent->client->ps.velocity, 150, dir, limb->s.pos.trDelta ); - limb->s.apos.trDelta[0] = Q_irand( -200, 200 ); - limb->s.apos.trDelta[1] = Q_irand( -400, 400 ); - } - else// if ( limbAnim == BOTH_DISMEMBER_TORSO1 || limbAnim == BOTH_DISMEMBER_LLEG || limbAnim == BOTH_DISMEMBER_RLEG ) - {//everything else just kinda falls off + VectorMA(ent->client->ps.velocity, 150, dir, limb->s.pos.trDelta); + limb->s.apos.trDelta[0] = Q_irand(-200, 200); + limb->s.apos.trDelta[1] = Q_irand(-400, 400); + } else // if ( limbAnim == BOTH_DISMEMBER_TORSO1 || limbAnim == BOTH_DISMEMBER_LLEG || limbAnim == BOTH_DISMEMBER_RLEG ) + { // everything else just kinda falls off limb->s.eFlags |= EF_BOUNCE_SHRAPNEL; - VectorMA( ent->client->ps.velocity, 100, dir, limb->s.pos.trDelta ); - limb->s.apos.trDelta[0] = Q_irand( -100, 100 ); - limb->s.apos.trDelta[1] = Q_irand( -200, 200 ); + VectorMA(ent->client->ps.velocity, 100, dir, limb->s.pos.trDelta); + limb->s.apos.trDelta[0] = Q_irand(-100, 100); + limb->s.apos.trDelta[1] = Q_irand(-200, 200); } - //roll? No, doesn't work... - //limb->s.apos.trDelta[2] = Q_irand( -300, 300 );//FIXME: this scales it down @ 80% and does weird stuff in timescale != 1.0 - //limb->s.apos.trDelta[2] = limbRoll; + // roll? No, doesn't work... + // limb->s.apos.trDelta[2] = Q_irand( -300, 300 );//FIXME: this scales it down @ 80% and does weird stuff in timescale != 1.0 + // limb->s.apos.trDelta[2] = limbRoll; - //preserve scale so giants don't have tiny limbs - VectorCopy( ent->s.modelScale, limb->s.modelScale ); + // preserve scale so giants don't have tiny limbs + VectorCopy(ent->s.modelScale, limb->s.modelScale); - //mark ent as dismembered - ent->locationDamage[hitLoc] = Q3_INFINITE;//mark this limb as gone + // mark ent as dismembered + ent->locationDamage[hitLoc] = Q3_INFINITE; // mark this limb as gone ent->client->dismembered = true; - //copy the custom RGB to the limb (for skin coloring) + // copy the custom RGB to the limb (for skin coloring) limb->startRGBA[0] = ent->client->renderInfo.customRGBA[0]; limb->startRGBA[1] = ent->client->renderInfo.customRGBA[1]; limb->startRGBA[2] = ent->client->renderInfo.customRGBA[2]; @@ -2231,21 +1819,16 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, return qtrue; } -static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) -{ - if ( self->client->dismembered ) - {//cannot dismember me right now +static qboolean G_Dismemberable(gentity_t *self, int hitLoc) { + if (self->client->dismembered) { // cannot dismember me right now return qfalse; } - if ( !debug_subdivision->integer && g_saberRealisticCombat->integer < 2 ) - { - if ( g_dismemberProbabilities->value > 0.0f ) - {//use the ent-specific dismemberProbabilities + if (!debug_subdivision->integer && g_saberRealisticCombat->integer < 2) { + if (g_dismemberProbabilities->value > 0.0f) { // use the ent-specific dismemberProbabilities float dismemberProb = 0; // check which part of the body it is. Then check the npc's probability // of that body part coming off, if it doesn't pass, return out. - switch ( hitLoc ) - { + switch (hitLoc) { case HL_LEG_RT: case HL_LEG_LT: dismemberProb = self->client->dismemberProbLegs; @@ -2273,8 +1856,9 @@ static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) break; } - //check probability of this happening on this npc - if ( floor((Q_flrand( 1, 100 )*g_dismemberProbabilities->value)) > dismemberProb*2.0f )//probabilities seemed really really low, had to crank them up + // check probability of this happening on this npc + if (floor((Q_flrand(1, 100) * g_dismemberProbabilities->value)) > + dismemberProb * 2.0f) // probabilities seemed really really low, had to crank them up { return qfalse; } @@ -2283,18 +1867,15 @@ static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) return qtrue; } -static qboolean G_Dismemberable2( gentity_t *self, int hitLoc ) -{ - if ( self->client->dismembered ) - {//cannot dismember me right now +static qboolean G_Dismemberable2(gentity_t *self, int hitLoc) { + if (self->client->dismembered) { // cannot dismember me right now return qfalse; } - if ( !debug_subdivision->integer && g_saberRealisticCombat->integer < 2 ) - { - if ( g_dismemberProbabilities->value <= 0.0f ) - {//add the passed-in damage to the locationDamage array, check to see if it's taken enough damage to actually dismember - if ( self->locationDamage[hitLoc] < (self->client->ps.stats[STAT_MAX_HEALTH]*hitLocHealthPercentage[hitLoc]) ) - {//this location has not taken enough damage to dismember + if (!debug_subdivision->integer && g_saberRealisticCombat->integer < 2) { + if (g_dismemberProbabilities->value <= + 0.0f) { // add the passed-in damage to the locationDamage array, check to see if it's taken enough damage to actually dismember + if (self->locationDamage[hitLoc] < + (self->client->ps.stats[STAT_MAX_HEALTH] * hitLocHealthPercentage[hitLoc])) { // this location has not taken enough damage to dismember return qfalse; } } @@ -2302,67 +1883,59 @@ static qboolean G_Dismemberable2( gentity_t *self, int hitLoc ) return qtrue; } -#define MAX_VARIANTS 8 -qboolean G_GetRootSurfNameWithVariant( gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize ) -{ - if ( !gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], rootSurfName ) ) - {//see if the basic name without variants is on - Q_strncpyz( returnSurfName, rootSurfName, returnSize ); +#define MAX_VARIANTS 8 +qboolean G_GetRootSurfNameWithVariant(gentity_t *ent, const char *rootSurfName, char *returnSurfName, int returnSize) { + if (!gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], rootSurfName)) { // see if the basic name without variants is on + Q_strncpyz(returnSurfName, rootSurfName, returnSize); return qtrue; - } - else - {//check variants + } else { // check variants int i; - for ( i = 0; i < MAX_VARIANTS; i++ ) - { - Com_sprintf( returnSurfName, returnSize, "%s%c", rootSurfName, 'a'+i ); - if ( !gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], returnSurfName ) ) - { + for (i = 0; i < MAX_VARIANTS; i++) { + Com_sprintf(returnSurfName, returnSize, "%s%c", rootSurfName, 'a' + i); + if (!gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], returnSurfName)) { return qtrue; } } } - Q_strncpyz( returnSurfName, rootSurfName, returnSize ); + Q_strncpyz(returnSurfName, rootSurfName, returnSize); return qfalse; } -extern qboolean G_StandardHumanoid( gentity_t *self ); -qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ) -{ -//extern cvar_t *g_iscensored; - // dismemberment -- FIXME: should have a check for how long npc has been dead so people can't - // continue to dismember a dead body long after it's been dead - //NOTE that you can only cut one thing off unless the debug_subdivisions is on - if ( ( g_dismemberment->integer || g_saberRealisticCombat->integer > 1 ) && mod == MOD_SABER )//only lightsaber - {//FIXME: don't do strcmps here - if ( G_StandardHumanoid( self ) - && (force||g_dismemberProbabilities->value>0.0f||G_Dismemberable2( self, hitLoc )) ) - {//either it's a forced dismemberment or we're using probabilities (which are checked before this) or we've done enough damage to this location - //FIXME: check the hitLoc and hitDir against the cap tag for the place - //where the split will be- if the hit dir is roughly perpendicular to - //the direction of the cap, then the split is allowed, otherwise we - //hit it at the wrong angle and should not dismember... - const char *limbBone = NULL, *rotateBone = NULL, *limbTagName = NULL, *stubTagName = NULL; - int anim = -1; - float limbRollBase = 0, limbPitchBase = 0; +extern qboolean G_StandardHumanoid(gentity_t *self); +qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse) { + // extern cvar_t *g_iscensored; + // dismemberment -- FIXME: should have a check for how long npc has been dead so people can't + // continue to dismember a dead body long after it's been dead + // NOTE that you can only cut one thing off unless the debug_subdivisions is on + if ((g_dismemberment->integer || g_saberRealisticCombat->integer > 1) && mod == MOD_SABER) // only lightsaber + { // FIXME: don't do strcmps here + if (G_StandardHumanoid(self) && (force || g_dismemberProbabilities->value > 0.0f || + G_Dismemberable2(self, hitLoc))) { // either it's a forced dismemberment or we're using probabilities (which are + // checked before this) or we've done enough damage to this location + // FIXME: check the hitLoc and hitDir against the cap tag for the place + // where the split will be- if the hit dir is roughly perpendicular to + // the direction of the cap, then the split is allowed, otherwise we + // hit it at the wrong angle and should not dismember... + const char *limbBone = NULL, *rotateBone = NULL, *limbTagName = NULL, *stubTagName = NULL; + int anim = -1; + float limbRollBase = 0, limbPitchBase = 0; qboolean doDismemberment = qfalse; - char limbName[MAX_QPATH]; - char stubName[MAX_QPATH]; - char limbCapName[MAX_QPATH]; - char stubCapName[MAX_QPATH]; + char limbName[MAX_QPATH]; + char stubName[MAX_QPATH]; + char limbCapName[MAX_QPATH]; + char stubCapName[MAX_QPATH]; - switch( hitLoc )//self->hitLoc + switch (hitLoc) // self->hitLoc { case HL_LEG_RT: - if ( g_dismemberment->integer > 1 ) - { + if (g_dismemberment->integer > 1) { doDismemberment = qtrue; limbBone = "rtibia"; rotateBone = "rtalus"; - G_GetRootSurfNameWithVariant( self, "r_leg", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "hips", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_hips", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_leg", stubName ); + G_GetRootSurfNameWithVariant(self, "r_leg", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "hips", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_hips", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_leg", stubName); limbTagName = "*r_leg_cap_hips"; stubTagName = "*hips_cap_r_leg"; anim = BOTH_DISMEMBER_RLEG; @@ -2371,15 +1944,14 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, } break; case HL_LEG_LT: - if ( g_dismemberment->integer > 1 ) - { + if (g_dismemberment->integer > 1) { doDismemberment = qtrue; limbBone = "ltibia"; rotateBone = "ltalus"; - G_GetRootSurfNameWithVariant( self, "l_leg", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "hips", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_hips", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_leg", stubName ); + G_GetRootSurfNameWithVariant(self, "l_leg", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "hips", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_hips", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_leg", stubName); limbTagName = "*l_leg_cap_hips"; stubTagName = "*hips_cap_l_leg"; anim = BOTH_DISMEMBER_LLEG; @@ -2388,15 +1960,13 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, } break; case HL_WAIST: - if ( g_dismemberment->integer > 2 && - (!self->s.number||!self->message)) - { + if (g_dismemberment->integer > 2 && (!self->s.number || !self->message)) { doDismemberment = qtrue; limbBone = "pelvis"; rotateBone = "thoracic"; - Q_strncpyz( limbName, "torso", sizeof( limbName ) ); - Q_strncpyz( limbCapName, "torso_cap_hips", sizeof( limbCapName ) ); - Q_strncpyz( stubCapName, "hips_cap_torso", sizeof( stubCapName ) ); + Q_strncpyz(limbName, "torso", sizeof(limbName)); + Q_strncpyz(limbCapName, "torso_cap_hips", sizeof(limbCapName)); + Q_strncpyz(stubCapName, "hips_cap_torso", sizeof(stubCapName)); limbTagName = "*torso_cap_hips"; stubTagName = "*hips_cap_torso"; anim = BOTH_DISMEMBER_TORSO1; @@ -2407,15 +1977,14 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, case HL_CHEST_RT: case HL_ARM_RT: case HL_BACK_RT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "rhumerus"; rotateBone = "rradius"; - G_GetRootSurfNameWithVariant( self, "r_arm", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "torso", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_torso", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_arm", stubName ); + G_GetRootSurfNameWithVariant(self, "r_arm", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "torso", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_torso", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_arm", stubName); limbTagName = "*r_arm_cap_torso"; stubTagName = "*torso_cap_r_arm"; anim = BOTH_DISMEMBER_RARM; @@ -2426,16 +1995,14 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, case HL_CHEST_LT: case HL_ARM_LT: case HL_BACK_LT: - if ( g_dismemberment->integer && - (!self->s.number||!self->message)) - {//either the player or not carrying a key on my arm + if (g_dismemberment->integer && (!self->s.number || !self->message)) { // either the player or not carrying a key on my arm doDismemberment = qtrue; limbBone = "lhumerus"; rotateBone = "lradius"; - G_GetRootSurfNameWithVariant( self, "l_arm", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "torso", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_torso", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_arm", stubName ); + G_GetRootSurfNameWithVariant(self, "l_arm", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "torso", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_torso", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_arm", stubName); limbTagName = "*l_arm_cap_torso"; stubTagName = "*torso_cap_l_arm"; anim = BOTH_DISMEMBER_LARM; @@ -2444,15 +2011,14 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, } break; case HL_HAND_RT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "rradiusX"; rotateBone = "rhand"; - G_GetRootSurfNameWithVariant( self, "r_hand", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "r_arm", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_r_arm", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_hand", stubName ); + G_GetRootSurfNameWithVariant(self, "r_hand", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "r_arm", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_r_arm", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_hand", stubName); limbTagName = "*r_hand_cap_r_arm"; stubTagName = "*r_arm_cap_r_hand"; anim = BOTH_DISMEMBER_RARM; @@ -2461,15 +2027,14 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, } break; case HL_HAND_LT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "lradiusX"; rotateBone = "lhand"; - G_GetRootSurfNameWithVariant( self, "l_hand", limbName, sizeof(limbName) ); - G_GetRootSurfNameWithVariant( self, "l_arm", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_l_arm", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_hand", stubName ); + G_GetRootSurfNameWithVariant(self, "l_hand", limbName, sizeof(limbName)); + G_GetRootSurfNameWithVariant(self, "l_arm", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_l_arm", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_hand", stubName); limbTagName = "*l_hand_cap_l_arm"; stubTagName = "*l_arm_cap_l_hand"; anim = BOTH_DISMEMBER_LARM; @@ -2478,14 +2043,13 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, } break; case HL_HEAD: - if ( g_dismemberment->integer > 2 ) - { + if (g_dismemberment->integer > 2) { doDismemberment = qtrue; limbBone = "cervical"; rotateBone = "cranium"; - Q_strncpyz( limbName, "head", sizeof( limbName ) ); - Q_strncpyz( limbCapName, "head_cap_torso", sizeof( limbCapName ) ); - Q_strncpyz( stubCapName, "torso_cap_head", sizeof( stubCapName ) ); + Q_strncpyz(limbName, "head", sizeof(limbName)); + Q_strncpyz(limbCapName, "head_cap_torso", sizeof(limbCapName)); + Q_strncpyz(stubCapName, "torso_cap_head", sizeof(stubCapName)); limbTagName = "*head_cap_torso"; stubTagName = "*torso_cap_head"; anim = BOTH_DISMEMBER_HEAD1; @@ -2500,685 +2064,473 @@ qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, default: break; } - if ( doDismemberment ) - { - return G_Dismember( self, point, limbBone, rotateBone, limbName, - limbCapName, stubCapName, limbTagName, stubTagName, - anim, limbRollBase, limbPitchBase, damage, hitLoc ); + if (doDismemberment) { + return G_Dismember(self, point, limbBone, rotateBone, limbName, limbCapName, stubCapName, limbTagName, stubTagName, anim, limbRollBase, + limbPitchBase, damage, hitLoc); } } } return qfalse; } -static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{ +static int G_CheckSpecialDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc) { int deathAnim = -1; - if ( self->client->ps.legsAnim == BOTH_GETUP_BROLL_L - || self->client->ps.legsAnim == BOTH_GETUP_BROLL_R ) - {//rolling away to the side on our back + if (self->client->ps.legsAnim == BOTH_GETUP_BROLL_L || self->client->ps.legsAnim == BOTH_GETUP_BROLL_R) { // rolling away to the side on our back deathAnim = BOTH_DEATH_LYING_UP; - } - else if ( self->client->ps.legsAnim == BOTH_GETUP_FROLL_L - || self->client->ps.legsAnim == BOTH_GETUP_FROLL_R ) - {//rolling away to the side on our front + } else if (self->client->ps.legsAnim == BOTH_GETUP_FROLL_L || self->client->ps.legsAnim == BOTH_GETUP_FROLL_R) { // rolling away to the side on our front deathAnim = BOTH_DEATH_LYING_DN; - } - else if ( self->client->ps.legsAnim == BOTH_GETUP_BROLL_F - && self->client->ps.legsAnimTimer > 350 ) - {//kicking up + } else if (self->client->ps.legsAnim == BOTH_GETUP_BROLL_F && self->client->ps.legsAnimTimer > 350) { // kicking up deathAnim = BOTH_DEATH_FALLING_UP; - } - else if ( self->client->ps.legsAnim == BOTH_GETUP_BROLL_B - && self->client->ps.legsAnimTimer > 950 ) - {//on back, rolling back to get up + } else if (self->client->ps.legsAnim == BOTH_GETUP_BROLL_B && self->client->ps.legsAnimTimer > 950) { // on back, rolling back to get up deathAnim = BOTH_DEATH_LYING_UP; - } - else if ( self->client->ps.legsAnim == BOTH_GETUP_BROLL_B - && self->client->ps.legsAnimTimer <= 950 - && self->client->ps.legsAnimTimer > 250 ) - {//flipping over backwards + } else if (self->client->ps.legsAnim == BOTH_GETUP_BROLL_B && self->client->ps.legsAnimTimer <= 950 && + self->client->ps.legsAnimTimer > 250) { // flipping over backwards deathAnim = BOTH_FALLDEATH1LAND; - } - else if ( self->client->ps.legsAnim == BOTH_GETUP_FROLL_B - && self->client->ps.legsAnimTimer <= 1100 - && self->client->ps.legsAnimTimer > 250 ) - {//flipping over backwards + } else if (self->client->ps.legsAnim == BOTH_GETUP_FROLL_B && self->client->ps.legsAnimTimer <= 1100 && + self->client->ps.legsAnimTimer > 250) { // flipping over backwards deathAnim = BOTH_FALLDEATH1LAND; - } - else if ( PM_InRoll( &self->client->ps ) ) - { - deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll - } - else if ( PM_FlippingAnim( self->client->ps.legsAnim ) ) - { - deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip - } - else if ( PM_SpinningAnim( self->client->ps.legsAnim ) ) - { + } else if (PM_InRoll(&self->client->ps)) { + deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll + } else if (PM_FlippingAnim(self->client->ps.legsAnim)) { + deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip + } else if (PM_SpinningAnim(self->client->ps.legsAnim)) { float yawDiff = AngleNormalize180(AngleNormalize180(self->client->renderInfo.torsoAngles[YAW]) - AngleNormalize180(self->client->ps.viewangles[YAW])); - if ( yawDiff > 135 || yawDiff < -135 ) - { - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( yawDiff < -60 ) - { - deathAnim = BOTH_DEATH_SPIN_90_R; //# Death anim when facing 90 degrees right - } - else if ( yawDiff > 60 ) - { - deathAnim = BOTH_DEATH_SPIN_90_L; //# Death anim when facing 90 degrees left - } - } - else if ( PM_InKnockDown( &self->client->ps ) ) - {//since these happen a lot, let's handle them case by case - int animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ); - if ( self->s.number < MAX_CLIENTS ) - { - switch ( self->client->ps.legsAnim ) - { + if (yawDiff > 135 || yawDiff < -135) { + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (yawDiff < -60) { + deathAnim = BOTH_DEATH_SPIN_90_R; //# Death anim when facing 90 degrees right + } else if (yawDiff > 60) { + deathAnim = BOTH_DEATH_SPIN_90_L; //# Death anim when facing 90 degrees left + } + } else if (PM_InKnockDown(&self->client->ps)) { // since these happen a lot, let's handle them case by case + int animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim); + if (self->s.number < MAX_CLIENTS) { + switch (self->client->ps.legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - //case BOTH_PLAYER_PA_3_FLY: + // case BOTH_PLAYER_PA_3_FLY: animLength += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; break; } } - switch ( self->client->ps.legsAnim ) - { + switch (self->client->ps.legsAnim) { case BOTH_KNOCKDOWN1: - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 100) { // on our way down + if (self->client->ps.legsAnimTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_PLAYER_PA_3_FLY: case BOTH_KNOCKDOWN2: - if ( animLength - self->client->ps.legsAnimTimer > 700 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 700) { // on our way down + if (self->client->ps.legsAnimTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_KNOCKDOWN3: - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 1300 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 100) { // on our way down + if (self->client->ps.legsAnimTimer > 1300) { // still partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_KNOCKDOWN4: case BOTH_RELEASED: - if ( animLength - self->client->ps.legsAnimTimer > 300 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 350 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 300) { // on our way down + if (self->client->ps.legsAnimTimer > 350) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } - } - else - {//crouch death + } else { // crouch death vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } } break; case BOTH_KNOCKDOWN5: case BOTH_LK_DL_ST_T_SB_1_L: - if ( self->client->ps.legsAnimTimer < 750 ) - {//flat + if (self->client->ps.legsAnimTimer < 750) { // flat deathAnim = BOTH_DEATH_LYING_DN; } break; case BOTH_GETUP1: - if ( self->client->ps.legsAnimTimer < 350 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 350) { // standing up + } else if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 450 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 450) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP2: - if ( self->client->ps.legsAnimTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 850 ) - {//crouching + if (self->client->ps.legsAnimTimer < 150) { // standing up + } else if (self->client->ps.legsAnimTimer < 850) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 500 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 500) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP3: - if ( self->client->ps.legsAnimTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 600 ) - {//crouching + if (self->client->ps.legsAnimTimer < 250) { // standing up + } else if (self->client->ps.legsAnimTimer < 600) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP4: - if ( self->client->ps.legsAnimTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 600 ) - {//crouching + if (self->client->ps.legsAnimTimer < 250) { // standing up + } else if (self->client->ps.legsAnimTimer < 600) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 850 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 850) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP5: - if ( self->client->ps.legsAnimTimer > 850 ) - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 1500 ) - {//partially up + if (self->client->ps.legsAnimTimer > 850) { // lying down + if (animLength - self->client->ps.legsAnimTimer > 1500) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP_CROUCH_B1: - if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 400 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 400) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP_CROUCH_F1: - if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_B1: - if ( self->client->ps.legsAnimTimer < 325 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 725 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsAnimTimer < 900 ) - {//crouching + if (self->client->ps.legsAnimTimer < 325) { // standing up + } else if (self->client->ps.legsAnimTimer < 725) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsAnimTimer < 900) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 50 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B2: - if ( self->client->ps.legsAnimTimer < 575 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 875 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsAnimTimer < 900 ) - {//crouching + if (self->client->ps.legsAnimTimer < 575) { // standing up + } else if (self->client->ps.legsAnimTimer < 875) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsAnimTimer < 900) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - //partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B3: - if ( self->client->ps.legsAnimTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 775 ) - {//flipping - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - //partially up + if (self->client->ps.legsAnimTimer < 150) { // standing up + } else if (self->client->ps.legsAnimTimer < 775) { // flipping + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B4: - if ( self->client->ps.legsAnimTimer < 325 ) - {//standing up - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + if (self->client->ps.legsAnimTimer < 325) { // standing up + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B5: - if ( self->client->ps.legsAnimTimer < 550 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 1025 ) - {//kicking up - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 50 ) - {//partially up + if (self->client->ps.legsAnimTimer < 550) { // standing up + } else if (self->client->ps.legsAnimTimer < 1025) { // kicking up + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B6: - if ( self->client->ps.legsAnimTimer < 225 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 425 ) - {//crouching up + if (self->client->ps.legsAnimTimer < 225) { // standing up + } else if (self->client->ps.legsAnimTimer < 425) { // crouching up vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else if ( self->client->ps.legsAnimTimer < 825 ) - {//flipping up - deathAnim = BOTH_DEATHFORWARD3; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 225 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else if (self->client->ps.legsAnimTimer < 825) { // flipping up + deathAnim = BOTH_DEATHFORWARD3; // backflip + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_F1: - if ( self->client->ps.legsAnimTimer < 275 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 750 ) - {//flipping + if (self->client->ps.legsAnimTimer < 275) { // standing up + } else if (self->client->ps.legsAnimTimer < 750) { // flipping deathAnim = BOTH_DEATH14; - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 100) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_F2: - if ( self->client->ps.legsAnimTimer < 1200 ) - {//standing - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 225 ) - {//partially up + if (self->client->ps.legsAnimTimer < 1200) { // standing + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; } - } - else if ( PM_InOnGroundAnim( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back - } - else - { - deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front + } else if (PM_InOnGroundAnim(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back + } else { + deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front } - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - { + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -200 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -200) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } } return deathAnim; } -extern qboolean PM_FinishedCurrentLegsAnim( gentity_t *self ); -static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{//FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called +extern qboolean PM_FinishedCurrentLegsAnim(gentity_t *self); +static int G_PickDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, + int hitLoc) { // FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called int deathAnim = -1; - if ( hitLoc == HL_NONE ) - { - hitLoc = G_GetHitLocation( self, point );//self->hitLoc + if (hitLoc == HL_NONE) { + hitLoc = G_GetHitLocation(self, point); // self->hitLoc } - //dead flops...if you are already playing a death animation, I guess it can just return directly - switch( self->client->ps.legsAnim ) - { - case BOTH_DEATH1: //# First Death anim + // dead flops...if you are already playing a death animation, I guess it can just return directly + switch (self->client->ps.legsAnim) { + case BOTH_DEATH1: //# First Death anim case BOTH_DEAD1: - case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH2: //# Second Death anim case BOTH_DEAD2: - case BOTH_DEATH8: //# + case BOTH_DEATH8: //# case BOTH_DEAD8: - case BOTH_DEATH13: //# + case BOTH_DEATH13: //# case BOTH_DEAD13: - case BOTH_DEATH14: //# + case BOTH_DEATH14: //# case BOTH_DEAD14: - case BOTH_DEATH16: //# + case BOTH_DEATH16: //# case BOTH_DEAD16: - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose - //return -2; - //break; - if ( PM_FinishedCurrentLegsAnim( self ) ) - {//done with the anim + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + // return -2; + // break; + if (PM_FinishedCurrentLegsAnim(self)) { // done with the anim deathAnim = BOTH_DEADFLOP2; - } - else - { + } else { deathAnim = -2; } return deathAnim; break; case BOTH_DEADFLOP2: - //return -2; + // return -2; return BOTH_DEADFLOP2; break; - case BOTH_DEATH10: //# + case BOTH_DEATH10: //# case BOTH_DEAD10: - case BOTH_DEATH15: //# + case BOTH_DEATH15: //# case BOTH_DEAD15: - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose - //return -2; - //break; - if ( PM_FinishedCurrentLegsAnim( self ) ) - {//done with the anim + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + // return -2; + // break; + if (PM_FinishedCurrentLegsAnim(self)) { // done with the anim deathAnim = BOTH_DEADFLOP1; - } - else - { + } else { deathAnim = -2; } return deathAnim; break; case BOTH_DEADFLOP1: - //return -2; + // return -2; return BOTH_DEADFLOP1; break; - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD9: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_DEAD20: //# - case BOTH_DEAD21: //# - case BOTH_DEAD22: //# - case BOTH_DEAD23: //# - case BOTH_DEAD24: //# - case BOTH_DEAD25: //# - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH9: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATH20: //# - case BOTH_DEATH21: //# - case BOTH_DEATH22: //# - case BOTH_DEATH23: //# - case BOTH_DEATH24: //# - case BOTH_DEATH25: //# - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHFORWARD3: //# Second Death in which they get thrown forward - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD9: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_DEAD20: //# + case BOTH_DEAD21: //# + case BOTH_DEAD22: //# + case BOTH_DEAD23: //# + case BOTH_DEAD24: //# + case BOTH_DEAD25: //# + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH9: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATH20: //# + case BOTH_DEATH21: //# + case BOTH_DEATH22: //# + case BOTH_DEATH23: //# + case BOTH_DEATH24: //# + case BOTH_DEATH25: //# + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHFORWARD3: //# Second Death in which they get thrown forward + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom return -2; break; case BOTH_DEATH_ROLL: //# Death anim from a roll @@ -3188,135 +2540,89 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, case BOTH_DEATH_SPIN_180: //# Death anim when facing backwards case BOTH_DEATH_LYING_UP: //# Death anim when lying on back case BOTH_DEATH_LYING_DN: //# Death anim when lying on front - case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face - case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back + case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face + case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back case BOTH_DEATH_CROUCHED: //# Death anim when crouched case BOTH_RIGHTHANDCHOPPEDOFF: return -2; break; } // Not currently playing a death animation, so try and get an appropriate one now. - if ( deathAnim == -1 ) - { - deathAnim = G_CheckSpecialDeathAnim( self, point, damage, mod, hitLoc ); + if (deathAnim == -1) { + deathAnim = G_CheckSpecialDeathAnim(self, point, damage, mod, hitLoc); - if ( deathAnim == -1 ) - {//base on hitLoc + if (deathAnim == -1) { // base on hitLoc vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - //death anims - switch( hitLoc ) - { + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + // death anims + switch (hitLoc) { case HL_FOOT_RT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH24;//right foot trips up, spin - } - else if ( !Q_irand( 0, 1 ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH24; // right foot trips up, spin + } else if (!Q_irand(0, 1)) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH16; // same as 1 } - else - { - deathAnim = BOTH_DEATH16;//same as 1 - } - } - else - { - deathAnim = BOTH_DEATH5;//same as 4 + } else { + deathAnim = BOTH_DEATH5; // same as 4 } break; case HL_FOOT_LT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH25;//left foot trips up, spin - } - else if ( !Q_irand( 0, 1 ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH25; // left foot trips up, spin + } else if (!Q_irand(0, 1)) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH16; // same as 1 } - else - { - deathAnim = BOTH_DEATH16;//same as 1 - } - } - else - { - deathAnim = BOTH_DEATH5;//same as 4 + } else { + deathAnim = BOTH_DEATH5; // same as 4 } break; case HL_LEG_RT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH3;//right leg collapse - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else - { - deathAnim = BOTH_DEATH16;//same as 1 + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH3; // right leg collapse + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH16; // same as 1 } } break; case HL_LEG_LT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH7;//left leg collapse - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else - { - deathAnim = BOTH_DEATH16;//same as 1 + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH7; // left leg collapse + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH16; // same as 1 } } break; case HL_BACK: - if ( fabs(thrown) < 50 || (fabs(thrown) < 200&&!Q_irand(0,3)) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - deathAnim = BOTH_DEATH10;//back: bend back, fall forward - } - } - else - { - if ( !Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward + if (fabs(thrown) < 50 || (fabs(thrown) < 200 && !Q_irand(0, 3))) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + deathAnim = BOTH_DEATH10; // back: bend back, fall forward } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//back: forward - } - else - { - deathAnim = BOTH_DEATH16;//same as 1 + } else { + if (!Q_irand(0, 2)) { + deathAnim = BOTH_DEATH4; // back: forward + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // back: forward + } else { + deathAnim = BOTH_DEATH16; // same as 1 } } break; @@ -3324,99 +2630,71 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, case HL_CHEST_RT: case HL_ARM_RT: case HL_BACK_LT: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,2)) || !Q_irand( 0, 10 ) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward - } - else - { - deathAnim = BOTH_DEATH20;//chest right: snap, fall forward - } - } - else if ( (damage <= self->max_health*0.5&&Q_irand(0,1)) || !Q_irand( 0, 10 ) ) - { - deathAnim = BOTH_DEATH3;//chest right: back - } - else if ( (damage <= self->max_health*0.75&&Q_irand(0,1)) || !Q_irand( 0, 10 ) ) - { - deathAnim = BOTH_DEATH6;//chest right: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH8;//chest right: spin high + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 2)) || !Q_irand(0, 10)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward + } else { + deathAnim = BOTH_DEATH20; // chest right: snap, fall forward } - else - { - switch ( Q_irand( 0, 3 ) ) - { + } else if ((damage <= self->max_health * 0.5 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH3; // chest right: back + } else if ((damage <= self->max_health * 0.75 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH6; // chest right: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH8; // chest right: spin high + } else { + switch (Q_irand(0, 3)) { default: case 0: - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH3;//chest right: back + deathAnim = BOTH_DEATH3; // chest right: back break; case 2: - deathAnim = BOTH_DEATH6;//chest right: spin + deathAnim = BOTH_DEATH6; // chest right: spin break; case 3: - deathAnim = BOTH_DEATH20;//chest right: spin + deathAnim = BOTH_DEATH20; // chest right: spin break; } } } break; case HL_CHEST_LT: - case HL_ARM_LT: - case HL_HAND_LT: - case HL_BACK_RT: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,2)) || !Q_irand(0, 10) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward - } - else - { - deathAnim = BOTH_DEATH21;//chest left: snap, fall forward - } - } - else if ( (damage <= self->max_health*0.5&&Q_irand(0,1)) || !Q_irand(0, 10) ) - { - deathAnim = BOTH_DEATH7;//chest left: back - } - else if ( (damage <= self->max_health*0.75&&Q_irand(0,1)) || !Q_irand(0, 10) ) - { - deathAnim = BOTH_DEATH12;//chest left: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH14;//chest left: spin high + case HL_ARM_LT: + case HL_HAND_LT: + case HL_BACK_RT: + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 2)) || !Q_irand(0, 10)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward + } else { + deathAnim = BOTH_DEATH21; // chest left: snap, fall forward } - else - { - switch ( Q_irand( 0, 3 ) ) - { + } else if ((damage <= self->max_health * 0.5 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH7; // chest left: back + } else if ((damage <= self->max_health * 0.75 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH12; // chest left: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH14; // chest left: spin high + } else { + switch (Q_irand(0, 3)) { default: case 0: - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH7;//chest left: back + deathAnim = BOTH_DEATH7; // chest left: back break; case 2: - deathAnim = BOTH_DEATH12;//chest left: spin + deathAnim = BOTH_DEATH12; // chest left: spin break; case 3: - deathAnim = BOTH_DEATH21;//chest left: spin + deathAnim = BOTH_DEATH21; // chest left: spin break; } } @@ -3424,66 +2702,40 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, break; case HL_CHEST: case HL_WAIST: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || thrown > -50 ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH18;//gut: fall right - } - else - { - deathAnim = BOTH_DEATH19;//gut: fall left - } - } - else if ( (damage <= self->max_health*0.5&&!Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,3)) ) - { - if ( Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH2;//chest: backward short + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || thrown > -50) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH18; // gut: fall right + } else { + deathAnim = BOTH_DEATH19; // gut: fall left } - else if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH22;//chest: backward short + } else if ((damage <= self->max_health * 0.5 && !Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 3))) { + if (Q_irand(0, 2)) { + deathAnim = BOTH_DEATH2; // chest: backward short + } else if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH22; // chest: backward short + } else { + deathAnim = BOTH_DEATH23; // chest: backward short } - else - { - deathAnim = BOTH_DEATH23;//chest: backward short + } else if (thrown < -300 && Q_irand(0, 1)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATHBACKWARD1; // chest: fly back + } else { + deathAnim = BOTH_DEATHBACKWARD2; // chest: flip back } - } - else if ( thrown < -300 && Q_irand( 0, 1 ) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATHBACKWARD1;//chest: fly back - } - else - { - deathAnim = BOTH_DEATHBACKWARD2;//chest: flip back - } - } - else if ( thrown < -200 && Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH15;//chest: roll backward - } - else - { - deathAnim = BOTH_DEATH1;//chest: backward med + } else if (thrown < -200 && Q_irand(0, 1)) { + deathAnim = BOTH_DEATH15; // chest: roll backward + } else { + deathAnim = BOTH_DEATH1; // chest: backward med } break; case HL_HEAD: - if ( damage <= self->max_health*0.5 && Q_irand(0,2) ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - if ( Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH13;//head: stumble, fall back - } - else - { - deathAnim = BOTH_DEATH10;//head: stumble, fall back + if (damage <= self->max_health * 0.5 && Q_irand(0, 2)) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + if (Q_irand(0, 2)) { + deathAnim = BOTH_DEATH13; // head: stumble, fall back + } else { + deathAnim = BOTH_DEATH10; // head: stumble, fall back } } break; @@ -3494,98 +2746,76 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, } // Validate..... - if ( deathAnim == -1 || !PM_HasAnimation( self, deathAnim )) - { - if ( deathAnim == BOTH_DEADFLOP1 - || deathAnim == BOTH_DEADFLOP2 ) - {//if don't have deadflop, don't do anything + if (deathAnim == -1 || !PM_HasAnimation(self, deathAnim)) { + if (deathAnim == BOTH_DEADFLOP1 || deathAnim == BOTH_DEADFLOP2) { // if don't have deadflop, don't do anything deathAnim = -1; - } - else - { + } else { // I guess we'll take what we can get..... - deathAnim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); + deathAnim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); } } return deathAnim; } -int G_CheckLedgeDive( gentity_t *self, float checkDist, const vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp ) -{ +int G_CheckLedgeDive(gentity_t *self, float checkDist, const vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp) { // Intelligent Ledge-Diving Deaths: // If I'm an NPC, check for nearby ledges and fall off it if possible // How should/would/could this interact with knockback if we already have some? // Ideally - apply knockback if there are no ledges or a ledge in that dir // But if there is a ledge and it's not in the dir of my knockback, fall off the ledge instead - if ( !self || !self->client ) - { + if (!self || !self->client) { return 0; } - vec3_t fallForwardDir, fallRightDir; - vec3_t angles = {0}; - int cliff_fall = 0; + vec3_t fallForwardDir, fallRightDir; + vec3_t angles = {0}; + int cliff_fall = 0; - if ( checkVel && !VectorCompare( checkVel, vec3_origin ) ) - {//already moving in a dir - angles[1] = vectoyaw( self->client->ps.velocity ); - AngleVectors( angles, fallForwardDir, fallRightDir, NULL ); - } - else - {//try forward first + if (checkVel && !VectorCompare(checkVel, vec3_origin)) { // already moving in a dir + angles[1] = vectoyaw(self->client->ps.velocity); + AngleVectors(angles, fallForwardDir, fallRightDir, NULL); + } else { // try forward first angles[1] = self->client->ps.viewangles[1]; - AngleVectors( angles, fallForwardDir, fallRightDir, NULL ); + AngleVectors(angles, fallForwardDir, fallRightDir, NULL); } - VectorNormalize( fallForwardDir ); - float fallDist = G_CheckForLedge( self, fallForwardDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallForwardDir, 85 ); + VectorNormalize(fallForwardDir); + float fallDist = G_CheckForLedge(self, fallForwardDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallForwardDir, 85); self->client->ps.velocity[2] = 100; self->client->ps.groundEntityNum = ENTITYNUM_NONE; - } - else if ( tryOpposite ) - { - VectorScale( fallForwardDir, -1, fallForwardDir ); - fallDist = G_CheckForLedge( self, fallForwardDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallForwardDir, 85 ); + } else if (tryOpposite) { + VectorScale(fallForwardDir, -1, fallForwardDir); + fallDist = G_CheckForLedge(self, fallForwardDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallForwardDir, 85); self->client->ps.velocity[2] = 100; self->client->ps.groundEntityNum = ENTITYNUM_NONE; } } - if ( !cliff_fall && tryPerp ) - {//try sides - VectorNormalize( fallRightDir ); - fallDist = G_CheckForLedge( self, fallRightDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallRightDir, 85 ); + if (!cliff_fall && tryPerp) { // try sides + VectorNormalize(fallRightDir); + fallDist = G_CheckForLedge(self, fallRightDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallRightDir, 85); self->client->ps.velocity[2] = 100; - } - else - { - VectorScale( fallRightDir, -1, fallRightDir ); - fallDist = G_CheckForLedge( self, fallRightDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallRightDir, 85 ); + } else { + VectorScale(fallRightDir, -1, fallRightDir); + fallDist = G_CheckForLedge(self, fallRightDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallRightDir, 85); self->client->ps.velocity[2] = 100; } } } - if ( fallDist >= 256 ) - { + if (fallDist >= 256) { cliff_fall = 2; - } - else if ( fallDist >= 128 ) - { + } else if (fallDist >= 128) { cliff_fall = 1; } return cliff_fall; @@ -3596,32 +2826,29 @@ int G_CheckLedgeDive( gentity_t *self, float checkDist, const vec3_t checkVel, q player_die ================== */ -void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void AI_DeleteSelfFromGroup( gentity_t *self ); -extern void AI_GroupMemberKilled( gentity_t *self ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern void G_DrivableATSTDie( gentity_t *self ); -extern void JET_FlyStop( gentity_t *self ); -extern void VehicleExplosionDelay( gentity_t *self ); -extern void NPC_LeaveTroop(gentity_t* actor); -extern void Rancor_DropVictim( gentity_t *self ); -extern void Wampa_DropVictim( gentity_t *self ); -extern void WP_StopForceHealEffects( gentity_t *self ); -void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dflags, int hitLoc ) -{ - int anim; - int contents; - qboolean deathScript = qfalse; - qboolean lastInGroup = qfalse; - qboolean specialAnim = qfalse; - qboolean holdingSaber = qfalse; - int cliff_fall = 0; - - //FIXME: somehow people are sometimes not completely dying??? - if ( self->client->ps.pm_type == PM_DEAD && (meansOfDeath != MOD_SNIPER || (self->flags & FL_DISINTEGRATED)) ) - {//do dismemberment/twitching - if ( self->client->NPC_class == CLASS_MARK1 ) - { +void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void AI_DeleteSelfFromGroup(gentity_t *self); +extern void AI_GroupMemberKilled(gentity_t *self); +extern qboolean FlyingCreature(gentity_t *ent); +extern void G_DrivableATSTDie(gentity_t *self); +extern void JET_FlyStop(gentity_t *self); +extern void VehicleExplosionDelay(gentity_t *self); +extern void NPC_LeaveTroop(gentity_t *actor); +extern void Rancor_DropVictim(gentity_t *self); +extern void Wampa_DropVictim(gentity_t *self); +extern void WP_StopForceHealEffects(gentity_t *self); +void player_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dflags, int hitLoc) { + int anim; + int contents; + qboolean deathScript = qfalse; + qboolean lastInGroup = qfalse; + qboolean specialAnim = qfalse; + qboolean holdingSaber = qfalse; + int cliff_fall = 0; + + // FIXME: somehow people are sometimes not completely dying??? + if (self->client->ps.pm_type == PM_DEAD && (meansOfDeath != MOD_SNIPER || (self->flags & FL_DISINTEGRATED))) { // do dismemberment/twitching + if (self->client->NPC_class == CLASS_MARK1) { DeathFX(self); self->takedamage = qfalse; self->client->ps.eFlags |= EF_NODRAW; @@ -3629,95 +2856,73 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int // G_FreeEntity( self ); // Is this safe? I can't see why we'd mark it nodraw and then just leave it around?? self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + FRAMETIME; - } - else - { - anim = G_PickDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); - if ( dflags & DAMAGE_DISMEMBER ) - { - G_DoDismemberment( self, self->pos1, meansOfDeath, damage, hitLoc ); + } else { + anim = G_PickDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); + if (dflags & DAMAGE_DISMEMBER) { + G_DoDismemberment(self, self->pos1, meansOfDeath, damage, hitLoc); } - if ( anim >= 0 ) - { - NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (anim >= 0) { + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } } return; } // If the entity is in a vehicle. - if ( self->client && self->client->NPC_class != CLASS_VEHICLE && self->s.m_iVehicleNum != 0 ) - { + if (self->client && self->client->NPC_class != CLASS_VEHICLE && self->s.m_iVehicleNum != 0) { Vehicle_t *pVeh = g_entities[self->s.m_iVehicleNum].m_pVehicle; - if (pVeh) - { - if ( pVeh->m_pOldPilot != self - && pVeh->m_pPilot != self ) - {//whaaa? I'm not on this bike? er.... + if (pVeh) { + if (pVeh->m_pOldPilot != self && pVeh->m_pPilot != self) { // whaaa? I'm not on this bike? er.... assert(!!"How did we get to this point?"); - } - else - { // Get thrown out. - pVeh->m_pVehicleInfo->Eject( pVeh, self, qtrue ); + } else { // Get thrown out. + pVeh->m_pVehicleInfo->Eject(pVeh, self, qtrue); // Now Send The Vehicle Flying To It's Death - if (pVeh->m_pVehicleInfo->type==VH_SPEEDER && pVeh->m_pParentEntity && pVeh->m_pParentEntity->client) - { - gentity_t* parent = pVeh->m_pParentEntity; - float CurSpeed = VectorLength(parent->client->ps.velocity); + if (pVeh->m_pVehicleInfo->type == VH_SPEEDER && pVeh->m_pParentEntity && pVeh->m_pParentEntity->client) { + gentity_t *parent = pVeh->m_pParentEntity; + float CurSpeed = VectorLength(parent->client->ps.velocity); // If Moving //----------- - if (CurSpeed>(pVeh->m_pVehicleInfo->speedMax*0.5f)) - { + if (CurSpeed > (pVeh->m_pVehicleInfo->speedMax * 0.5f)) { // Send The Bike Out Of Control //------------------------------ pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 10000); - pVeh->m_ulFlags |= (VEH_OUTOFCONTROL); + pVeh->m_ulFlags |= (VEH_OUTOFCONTROL); VectorScale(parent->client->ps.velocity, 1.25f, parent->pos3); - // Try To Accelerate A Slowing Moving Vehicle To Full Speed //---------------------------------------------------------- - if (CurSpeed<(pVeh->m_pVehicleInfo->speedMax*0.9f)) - { + if (CurSpeed < (pVeh->m_pVehicleInfo->speedMax * 0.9f)) { VectorNormalize(parent->pos3); - if (fabsf(parent->pos3[2])<0.3f) - { + if (fabsf(parent->pos3[2]) < 0.3f) { VectorScale(parent->pos3, (pVeh->m_pVehicleInfo->speedMax * 1.25f), parent->pos3); - } - else - { + } else { VectorClear(parent->pos3); } } // Throw The Pilot //---------------- - if (parent->pos3[0] || parent->pos3[1]) - { - vec3_t throwDir; + if (parent->pos3[0] || parent->pos3[1]) { + vec3_t throwDir; VectorCopy(parent->client->ps.velocity, throwDir); VectorNormalize(throwDir); - throwDir[2] += 0.3f; // up a little + throwDir[2] += 0.3f; // up a little - self->client->noRagTime = -1; // no ragdoll for you + self->client->noRagTime = -1; // no ragdoll for you CurSpeed /= 10.0f; - if (CurSpeed<50.0) - { + if (CurSpeed < 50.0) { CurSpeed = 50.0f; } - if (throwDir[2]<0.0f) - { + if (throwDir[2] < 0.0f) { throwDir[2] = fabsf(throwDir[2]); } - if (fabsf(throwDir[0])<0.2f) - { + if (fabsf(throwDir[0]) < 0.2f) { throwDir[0] = Q_flrand(-0.5f, 0.5f); } - if (fabsf(throwDir[1])<0.2f) - { + if (fabsf(throwDir[1]) < 0.2f) { throwDir[1] = Q_flrand(-0.5f, 0.5f); } G_Throw(self, throwDir, CurSpeed); @@ -3725,302 +2930,213 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } } } - } - else - { + } else { assert(!!"How did we get to this point?"); } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer && attacker && attacker->client ) - { - gi.Printf( S_COLOR_YELLOW"combatant %s died, killer anim = %s\n", self->targetname, animTable[attacker->client->ps.torsoAnim].name ); + if (d_saberCombat->integer && attacker && attacker->client) { + gi.Printf(S_COLOR_YELLOW "combatant %s died, killer anim = %s\n", self->targetname, animTable[attacker->client->ps.torsoAnim].name); } -#endif//FINAL_BUILD - if ( self->NPC ) - { - if (NAV::HasPath(self)) - { +#endif // FINAL_BUILD + if (self->NPC) { + if (NAV::HasPath(self)) { NAV::ClearPath(self); } - if (self->NPC->troop) - { + if (self->NPC->troop) { NPC_LeaveTroop(self); } // STEER_TODO: Do we need to free the steer user too? - //clear charmed - G_CheckCharmed( self ); + // clear charmed + G_CheckCharmed(self); // Remove The Bubble Shield From The Assassin Droid - if (self->client && self->client->NPC_class==CLASS_ASSASSIN_DROID && (self->flags&FL_SHIELDED)) - { + if (self->client && self->client->NPC_class == CLASS_ASSASSIN_DROID && (self->flags & FL_SHIELDED)) { self->flags &= ~FL_SHIELDED; self->client->ps.stats[STAT_ARMOR] = 0; self->client->ps.powerups[PW_GALAK_SHIELD] = 0; - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "force_shield", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "force_shield", TURN_OFF); } - if (self->client && self->client->NPC_class==CLASS_HOWLER) - { - G_StopEffect( G_EffectIndex( "howler/sonic" ), self->playerModel, self->genericBolt1, self->s.number ); + if (self->client && self->client->NPC_class == CLASS_HOWLER) { + G_StopEffect(G_EffectIndex("howler/sonic"), self->playerModel, self->genericBolt1, self->s.number); } - - - if ( self->client && Jedi_WaitingAmbush( self ) ) - {//ambushing trooper + if (self->client && Jedi_WaitingAmbush(self)) { // ambushing trooper self->client->noclip = false; } - NPC_FreeCombatPoint( self->NPC->combatPoint ); - if ( self->NPC->group ) - { + NPC_FreeCombatPoint(self->NPC->combatPoint); + if (self->NPC->group) { lastInGroup = (qboolean)(self->NPC->group->numGroup < 2); - AI_GroupMemberKilled( self ); - AI_DeleteSelfFromGroup( self ); + AI_GroupMemberKilled(self); + AI_DeleteSelfFromGroup(self); } - if ( self->NPC->tempGoal ) - { - G_FreeEntity( self->NPC->tempGoal ); + if (self->NPC->tempGoal) { + G_FreeEntity(self->NPC->tempGoal); self->NPC->tempGoal = NULL; } - if ( self->s.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (self->s.eFlags & EF_LOCKED_TO_WEAPON) { // dumb, just get the NPC out of the chair -extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); + extern void RunEmplacedWeapon(gentity_t * ent, usercmd_t * *ucmd); usercmd_t cmd, *ad_cmd; - memset( &cmd, 0, sizeof( usercmd_t )); + memset(&cmd, 0, sizeof(usercmd_t)); - //gentity_t *old = self->owner; + // gentity_t *old = self->owner; - if ( self->owner ) - { + if (self->owner) { self->owner->s.frame = self->owner->startFrame = self->owner->endFrame = 0; self->owner->svFlags &= ~SVF_ANIMATING; } cmd.buttons |= BUTTON_USE; ad_cmd = &cmd; - RunEmplacedWeapon( self, &ad_cmd ); - //self->owner = old; + RunEmplacedWeapon(self, &ad_cmd); + // self->owner = old; } - if ( self->client->NPC_class == CLASS_BOBAFETT - || self->client->NPC_class == CLASS_ROCKETTROOPER ) - { - if ( self->client->moveType == MT_FLYSWIM ) - { - JET_FlyStop( self ); + if (self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) { + if (self->client->moveType == MT_FLYSWIM) { + JET_FlyStop(self); } } - if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { + if (self->client->NPC_class == CLASS_ROCKETTROOPER) { self->client->ps.eFlags &= ~EF_SPOTLIGHT; } - if ( self->client->NPC_class == CLASS_SAND_CREATURE ) - { + if (self->client->NPC_class == CLASS_SAND_CREATURE) { self->client->ps.eFlags &= ~EF_NODRAW; self->s.eFlags &= ~EF_NODRAW; } - if ( self->client->NPC_class == CLASS_RANCOR ) - { - if ( self->count ) - { - Rancor_DropVictim( self ); + if (self->client->NPC_class == CLASS_RANCOR) { + if (self->count) { + Rancor_DropVictim(self); } } - if ( self->client->NPC_class == CLASS_WAMPA ) - { - if ( self->count ) - { - if ( self->activator && attacker == self->activator && meansOfDeath == MOD_SABER ) - { + if (self->client->NPC_class == CLASS_WAMPA) { + if (self->count) { + if (self->activator && attacker == self->activator && meansOfDeath == MOD_SABER) { self->client->dismembered = false; - //FIXME: the limb should just disappear, cuz I ate it - G_DoDismemberment( self, self->currentOrigin, MOD_SABER, 1000, HL_ARM_RT, qtrue ); + // FIXME: the limb should just disappear, cuz I ate it + G_DoDismemberment(self, self->currentOrigin, MOD_SABER, 1000, HL_ARM_RT, qtrue); } - Wampa_DropVictim( self ); + Wampa_DropVictim(self); } } - if ( (self->NPC->aiFlags&NPCAI_HEAL_ROSH) ) - { - if ( self->client->leader ) - { + if ((self->NPC->aiFlags & NPCAI_HEAL_ROSH)) { + if (self->client->leader) { self->client->leader->flags &= ~FL_UNDYING; - if ( self->client->leader->client ) - { + if (self->client->leader->client) { self->client->leader->client->ps.forcePowersKnown &= ~FORCE_POWERS_ROSH_FROM_TWINS; } } } - if ( (self->client->ps.stats[STAT_WEAPONS]&(1<weaponModel[1], self->genericBolt1, self->s.number ); - G_StopEffect( G_EffectIndex( "scepter/beam.efx" ), self->weaponModel[1], self->genericBolt1, self->s.number ); - G_StopEffect( G_EffectIndex( "scepter/slam_warmup.efx" ), self->weaponModel[1], self->genericBolt1, self->s.number ); + if ((self->client->ps.stats[STAT_WEAPONS] & (1 << WP_SCEPTER))) { + G_StopEffect(G_EffectIndex("scepter/beam_warmup.efx"), self->weaponModel[1], self->genericBolt1, self->s.number); + G_StopEffect(G_EffectIndex("scepter/beam.efx"), self->weaponModel[1], self->genericBolt1, self->s.number); + G_StopEffect(G_EffectIndex("scepter/slam_warmup.efx"), self->weaponModel[1], self->genericBolt1, self->s.number); self->s.loopSound = 0; } } - if ( attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self ) - { + if (attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self) { attacker->NPC->group->enemy = NULL; } - if ( self->s.weapon == WP_SABER ) - { + if (self->s.weapon == WP_SABER) { holdingSaber = qtrue; } - if ( self->client->ps.saberEntityNum != ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0 ) - { - if ( self->client->ps.saberInFlight ) - {//just drop it + if (self->client->ps.saberEntityNum != ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0) { + if (self->client->ps.saberInFlight) { // just drop it self->client->ps.saber[0].Deactivate(); - } - else - { - if ( g_saberPickuppableDroppedSabers->integer ) - {//always drop your sabers - TossClientItems( self ); + } else { + if (g_saberPickuppableDroppedSabers->integer) { // always drop your sabers + TossClientItems(self); self->client->ps.weapon = self->s.weapon = WP_NONE; - } - else if ( ( - (hitLoc != HL_HAND_RT&&hitLoc !=HL_CHEST_RT&&hitLoc!=HL_ARM_RT&&hitLoc!=HL_BACK_LT) - || self->client->dismembered - || meansOfDeath != MOD_SABER - )//if might get hand cut off, leave saber in hand - && holdingSaber - && ( Q_irand( 0, 1 ) - || meansOfDeath == MOD_EXPLOSIVE - || meansOfDeath == MOD_REPEATER_ALT - || meansOfDeath == MOD_FLECHETTE_ALT - || meansOfDeath == MOD_ROCKET - || meansOfDeath == MOD_ROCKET_ALT - || meansOfDeath == MOD_CONC - || meansOfDeath == MOD_CONC_ALT - || meansOfDeath == MOD_THERMAL - || meansOfDeath == MOD_THERMAL_ALT - || meansOfDeath == MOD_DETPACK - || meansOfDeath == MOD_LASERTRIP - || meansOfDeath == MOD_LASERTRIP_ALT - || meansOfDeath == MOD_MELEE - || meansOfDeath == MOD_FORCE_GRIP - || meansOfDeath == MOD_KNOCKOUT - || meansOfDeath == MOD_CRUSH - || meansOfDeath == MOD_IMPACT - || meansOfDeath == MOD_FALLING - || meansOfDeath == MOD_EXPLOSIVE_SPLASH ) ) - {//drop it - TossClientItems( self ); + } else if (((hitLoc != HL_HAND_RT && hitLoc != HL_CHEST_RT && hitLoc != HL_ARM_RT && hitLoc != HL_BACK_LT) || self->client->dismembered || + meansOfDeath != MOD_SABER) // if might get hand cut off, leave saber in hand + && holdingSaber && + (Q_irand(0, 1) || meansOfDeath == MOD_EXPLOSIVE || meansOfDeath == MOD_REPEATER_ALT || meansOfDeath == MOD_FLECHETTE_ALT || + meansOfDeath == MOD_ROCKET || meansOfDeath == MOD_ROCKET_ALT || meansOfDeath == MOD_CONC || meansOfDeath == MOD_CONC_ALT || + meansOfDeath == MOD_THERMAL || meansOfDeath == MOD_THERMAL_ALT || meansOfDeath == MOD_DETPACK || meansOfDeath == MOD_LASERTRIP || + meansOfDeath == MOD_LASERTRIP_ALT || meansOfDeath == MOD_MELEE || meansOfDeath == MOD_FORCE_GRIP || meansOfDeath == MOD_KNOCKOUT || + meansOfDeath == MOD_CRUSH || meansOfDeath == MOD_IMPACT || meansOfDeath == MOD_FALLING || + meansOfDeath == MOD_EXPLOSIVE_SPLASH)) { // drop it + TossClientItems(self); self->client->ps.weapon = self->s.weapon = WP_NONE; - } - else - {//just free it - if ( g_entities[self->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[self->client->ps.saberEntityNum] ); + } else { // just free it + if (g_entities[self->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[self->client->ps.saberEntityNum]); } self->client->ps.saberEntityNum = ENTITYNUM_NONE; } } } - if ( self->client->NPC_class == CLASS_SHADOWTROOPER ) - {//drop a force crystal - if ( Q_stricmpn("shadowtrooper", self->NPC_type, 13 ) == 0 ) - { - gitem_t *item; - item = FindItemForAmmo( AMMO_FORCE ); - Drop_Item( self, item, 0, qtrue ); + if (self->client->NPC_class == CLASS_SHADOWTROOPER) { // drop a force crystal + if (Q_stricmpn("shadowtrooper", self->NPC_type, 13) == 0) { + gitem_t *item; + item = FindItemForAmmo(AMMO_FORCE); + Drop_Item(self, item, 0, qtrue); } } - //Use any target we had - if ( meansOfDeath != MOD_KNOCKOUT ) - { - G_UseTargets( self, self ); + // Use any target we had + if (meansOfDeath != MOD_KNOCKOUT) { + G_UseTargets(self, self); } - if ( attacker ) - { - if ( attacker->client && !attacker->s.number ) - { - if ( self->client ) - {//killed a client - if ( self->client->playerTeam == TEAM_ENEMY - || self->client->playerTeam == TEAM_FREE - || (self->NPC && self->NPC->charmedTime > level.time) ) - {//killed an enemy + if (attacker) { + if (attacker->client && !attacker->s.number) { + if (self->client) { // killed a client + if (self->client->playerTeam == TEAM_ENEMY || self->client->playerTeam == TEAM_FREE || + (self->NPC && self->NPC->charmedTime > level.time)) { // killed an enemy attacker->client->sess.missionStats.enemiesKilled++; } } - if ( attacker != self ) - { - G_TrackWeaponUsage( attacker, inflictor, 30, meansOfDeath ); + if (attacker != self) { + G_TrackWeaponUsage(attacker, inflictor, 30, meansOfDeath); } } G_CheckVictoryScript(attacker); - //player killing a jedi with a lightsaber spawns a matrix-effect entity - if ( d_slowmodeath->integer ) - { - if ( !self->s.number ) - {//what the hell, always do slow-mo when player dies - //FIXME: don't do this when crushed to death? - if ( meansOfDeath == MOD_FALLING && self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//falling to death, have not hit yet - G_StartMatrixEffect( self, (MEF_NO_VERTBOB|MEF_HIT_GROUND_STOP|MEF_MULTI_SPIN), 10000, 0.25f ); - } - else if ( meansOfDeath != MOD_CRUSH ) - {//for all deaths except being crushed - G_StartMatrixEffect( self ); - } - } - else if ( d_slowmodeath->integer < 4 ) - {//any jedi killed by player-saber - if ( d_slowmodeath->integer < 3 ) - {//must be the last jedi in the room - if ( !G_JediInRoom( attacker->currentOrigin ) ) - { + // player killing a jedi with a lightsaber spawns a matrix-effect entity + if (d_slowmodeath->integer) { + if (!self->s.number) { // what the hell, always do slow-mo when player dies + // FIXME: don't do this when crushed to death? + if (meansOfDeath == MOD_FALLING && self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // falling to death, have not hit yet + G_StartMatrixEffect(self, (MEF_NO_VERTBOB | MEF_HIT_GROUND_STOP | MEF_MULTI_SPIN), 10000, 0.25f); + } else if (meansOfDeath != MOD_CRUSH) { // for all deaths except being crushed + G_StartMatrixEffect(self); + } + } else if (d_slowmodeath->integer < 4) { // any jedi killed by player-saber + if (d_slowmodeath->integer < 3) { // must be the last jedi in the room + if (!G_JediInRoom(attacker->currentOrigin)) { lastInGroup = qtrue; - } - else - { + } else { lastInGroup = qfalse; } } - if ( !attacker->s.number - && (holdingSaber||self->client->NPC_class==CLASS_WAMPA) - && meansOfDeath == MOD_SABER - && attacker->client - && attacker->client->ps.weapon == WP_SABER - && !attacker->client->ps.saberInFlight //FIXME: if dualSabers, should still do slowmo if this killing blow was struck with the left-hand saber... - && (d_slowmodeath->integer > 2||lastInGroup) )//either slow mo death level 3 (any jedi) or 2 and I was the last jedi in the room - {//Matrix! - if ( attacker->client->ps.torsoAnim == BOTH_A6_SABERPROTECT ) - {//don't override the range and vertbob - G_StartMatrixEffect( self, (MEF_NO_RANGEVAR|MEF_NO_VERTBOB) ); - } - else - { - G_StartMatrixEffect( self ); + if (!attacker->s.number && (holdingSaber || self->client->NPC_class == CLASS_WAMPA) && meansOfDeath == MOD_SABER && attacker->client && + attacker->client->ps.weapon == WP_SABER && + !attacker->client->ps + .saberInFlight // FIXME: if dualSabers, should still do slowmo if this killing blow was struck with the left-hand saber... + && (d_slowmodeath->integer > 2 || lastInGroup)) // either slow mo death level 3 (any jedi) or 2 and I was the last jedi in the room + { // Matrix! + if (attacker->client->ps.torsoAnim == BOTH_A6_SABERPROTECT) { // don't override the range and vertbob + G_StartMatrixEffect(self, (MEF_NO_RANGEVAR | MEF_NO_VERTBOB)); + } else { + G_StartMatrixEffect(self); } } - } - else - {//all player-saber kills - if ( !attacker->s.number - && meansOfDeath == MOD_SABER - && attacker->client - && attacker->client->ps.weapon == WP_SABER - && !attacker->client->ps.saberInFlight - && (d_slowmodeath->integer > 4||lastInGroup||holdingSaber||self->client->NPC_class==CLASS_WAMPA))//either slow mo death level 5 (any enemy) or 4 and I was the last in my group or I'm a saber user - {//Matrix! - if ( attacker->client->ps.torsoAnim == BOTH_A6_SABERPROTECT ) - {//don't override the range and vertbob - G_StartMatrixEffect( self, (MEF_NO_RANGEVAR|MEF_NO_VERTBOB) ); - } - else - { - G_StartMatrixEffect( self ); + } else { // all player-saber kills + if (!attacker->s.number && meansOfDeath == MOD_SABER && attacker->client && attacker->client->ps.weapon == WP_SABER && + !attacker->client->ps.saberInFlight && + (d_slowmodeath->integer > 4 || lastInGroup || holdingSaber || + self->client->NPC_class == + CLASS_WAMPA)) // either slow mo death level 5 (any enemy) or 4 and I was the last in my group or I'm a saber user + { // Matrix! + if (attacker->client->ps.torsoAnim == BOTH_A6_SABERPROTECT) { // don't override the range and vertbob + G_StartMatrixEffect(self, (MEF_NO_RANGEVAR | MEF_NO_VERTBOB)); + } else { + G_StartMatrixEffect(self); } } } @@ -4031,84 +3147,65 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->client->renderInfo.lookTarget = ENTITYNUM_NONE; self->client->ps.persistant[PERS_KILLED]++; - if ( self->client->playerTeam == TEAM_PLAYER ) - {//FIXME: just HazTeam members in formation on away missions? - //or more controlled- via deathscripts? - // Don't count player - if (( g_entities[0].inuse && g_entities[0].client ) && (self->s.number != 0)) - {//add to the number of teammates lost + if (self->client->playerTeam == TEAM_PLAYER) { // FIXME: just HazTeam members in formation on away missions? + // or more controlled- via deathscripts? + // Don't count player + if ((g_entities[0].inuse && g_entities[0].client) && (self->s.number != 0)) { // add to the number of teammates lost g_entities[0].client->ps.persistant[PERS_TEAMMATES_KILLED]++; - } - else // Player died, fire off scoreboard soon + } else // Player died, fire off scoreboard soon { - cg.missionStatusDeadTime = level.time + 1000; // Too long?? Too short?? - cg.zoomMode = 0; // turn off zooming when we die + cg.missionStatusDeadTime = level.time + 1000; // Too long?? Too short?? + cg.zoomMode = 0; // turn off zooming when we die } } - if ( self->s.number == 0 && attacker ) - { -// G_SetMissionStatusText( attacker, meansOfDeath ); - //TEST: If player killed, unmark all teammates from being undying so they can buy it too - //NOTE: we want this to happen ONLY on our squad ONLY on missions... in the tutorial or on voyager levels this could be really weird. + if (self->s.number == 0 && attacker) { + // G_SetMissionStatusText( attacker, meansOfDeath ); + // TEST: If player killed, unmark all teammates from being undying so they can buy it too + // NOTE: we want this to happen ONLY on our squad ONLY on missions... in the tutorial or on voyager levels this could be really weird. G_MakeTeamVulnerable(); } - if ( attacker && attacker->client) - { - if ( attacker == self || OnSameTeam (self, attacker ) ) - { - AddScore( attacker, -1 ); - } - else - { - AddScore( attacker, 1 ); + if (attacker && attacker->client) { + if (attacker == self || OnSameTeam(self, attacker)) { + AddScore(attacker, -1); + } else { + AddScore(attacker, 1); } - } - else - { - AddScore( self, -1 ); + } else { + AddScore(self, -1); } // if client is in a nodrop area, don't drop anything - contents = gi.pointcontents( self->currentOrigin, -1 ); - if ( !holdingSaber + contents = gi.pointcontents(self->currentOrigin, -1); + if (!holdingSaber //&& self->s.number != 0 - && !( contents & CONTENTS_NODROP ) - && meansOfDeath != MOD_SNIPER - && (!self->client||self->client->NPC_class!=CLASS_GALAKMECH)) - { - TossClientItems( self ); + && !(contents & CONTENTS_NODROP) && meansOfDeath != MOD_SNIPER && (!self->client || self->client->NPC_class != CLASS_GALAKMECH)) { + TossClientItems(self); } - if ( meansOfDeath == MOD_SNIPER ) - {//I was disintegrated - if ( self->message ) - {//I was holding a key - //drop the key - G_DropKey( self ); + if (meansOfDeath == MOD_SNIPER) { // I was disintegrated + if (self->message) { // I was holding a key + // drop the key + G_DropKey(self); } } - if ( holdingSaber ) - {//never drop a lightsaber! - if ( self->client->ps.SaberActive() ) - { + if (holdingSaber) { // never drop a lightsaber! + if (self->client->ps.SaberActive()) { self->client->ps.SaberDeactivate(); - G_SoundIndexOnEnt( self, CHAN_AUTO, self->client->ps.saber[0].soundOff ); + G_SoundIndexOnEnt(self, CHAN_AUTO, self->client->ps.saber[0].soundOff); } - } - else if ( self->s.weapon != WP_BRYAR_PISTOL ) - {//since player can't pick up bryar pistols, never drop those + } else if (self->s.weapon != WP_BRYAR_PISTOL) { // since player can't pick up bryar pistols, never drop those self->s.weapon = WP_NONE; - G_RemoveWeaponModels( self ); + G_RemoveWeaponModels(self); } - self->s.powerups &= ~PW_REMOVE_AT_DEATH;//removes everything but electricity and force push + self->s.powerups &= ~PW_REMOVE_AT_DEATH; // removes everything but electricity and force push - //FIXME: do this on a callback? So people can't walk through long death anims? - //Maybe set on last frame? Would be cool for big blocking corpses if the never got set? - //self->contents = CONTENTS_CORPSE;//now done a second after death + // FIXME: do this on a callback? So people can't walk through long death anims? + // Maybe set on last frame? Would be cool for big blocking corpses if the never got set? + // self->contents = CONTENTS_CORPSE;//now done a second after death /* self->takedamage = qfalse; // no gibbing if ( self->client->playerTeam == TEAM_PARASITE ) @@ -4121,94 +3218,69 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->maxs[2] = -8; } */ - if ( !self->s.number ) - {//player + if (!self->s.number) { // player self->contents = CONTENTS_CORPSE; self->maxs[2] = -8; } - self->clipmask&=~(CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP);//so dead NPC can fly off ledges + self->clipmask &= ~(CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); // so dead NPC can fly off ledges - //FACING========================================================== - if ( attacker && self->s.number == 0 ) - { - self->client->ps.stats[STAT_DEAD_YAW] = AngleNormalize180( self->client->ps.viewangles[YAW] ); + // FACING========================================================== + if (attacker && self->s.number == 0) { + self->client->ps.stats[STAT_DEAD_YAW] = AngleNormalize180(self->client->ps.viewangles[YAW]); } self->currentAngles[PITCH] = 0; self->currentAngles[ROLL] = 0; - if ( self->NPC ) - { + if (self->NPC) { self->NPC->desiredYaw = 0; self->NPC->desiredPitch = 0; self->NPC->confusionTime = 0; self->NPC->charmedTime = 0; - if ( self->ghoul2.size() ) - { - if ( self->chestBolt != -1 ) - { - G_StopEffect("force/rage2", self->playerModel, self->chestBolt, self->s.number ); + if (self->ghoul2.size()) { + if (self->chestBolt != -1) { + G_StopEffect("force/rage2", self->playerModel, self->chestBolt, self->s.number); } - if ( self->headBolt != -1 ) - { - G_StopEffect("force/confusion", self->playerModel, self->headBolt, self->s.number ); + if (self->headBolt != -1) { + G_StopEffect("force/confusion", self->playerModel, self->headBolt, self->s.number); } - WP_StopForceHealEffects( self ); + WP_StopForceHealEffects(self); } } - VectorCopy( self->currentAngles, self->client->ps.viewangles ); - //FACING========================================================== - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - {//I was the player's viewentity and I died, kick him back to his normal view - G_ClearViewEntity( player ); - } - else if ( !self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE ) - { - G_ClearViewEntity( self ); - } - else if ( !self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE ) - { - G_ClearViewEntity( self ); + VectorCopy(self->currentAngles, self->client->ps.viewangles); + // FACING========================================================== + if (player && player->client && + player->client->ps.viewEntity == self->s.number) { // I was the player's viewentity and I died, kick him back to his normal view + G_ClearViewEntity(player); + } else if (!self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE) { + G_ClearViewEntity(self); + } else if (!self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE) { + G_ClearViewEntity(self); } self->s.loopSound = 0; // remove powerups - memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) ); - - if ( (self->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (self->client->ps.eFlags&EF_HELD_BY_SAND_CREATURE) - || (self->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//do nothing special here - } - else if ( self->client->NPC_class == CLASS_MARK1 ) - { - Mark1_die( self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc ); - } - else if ( self->client->NPC_class == CLASS_INTERROGATOR ) - { - Interrogator_die( self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc ); - } - else if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//FIXME: need keyframed explosions? - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); - } - else if ( self->client->NPC_class == CLASS_ATST ) - {//FIXME: need keyframed explosions - if ( !self->s.number ) - { - G_DrivableATSTDie( self ); - } - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data - if ( anim != -1 ) - { - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } - else if ( self->s.number && self->message && meansOfDeath != MOD_SNIPER ) - {//imp with a key on his arm - //pick a death anim that leaves key visible - switch ( Q_irand( 0, 3 ) ) - { + memset(self->client->ps.powerups, 0, sizeof(self->client->ps.powerups)); + + if ((self->client->ps.eFlags & EF_HELD_BY_RANCOR) || (self->client->ps.eFlags & EF_HELD_BY_SAND_CREATURE) || + (self->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // do nothing special here + } else if (self->client->NPC_class == CLASS_MARK1) { + Mark1_die(self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc); + } else if (self->client->NPC_class == CLASS_INTERROGATOR) { + Interrogator_die(self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc); + } else if (self->client->NPC_class == CLASS_GALAKMECH) { // FIXME: need keyframed explosions? + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); + } else if (self->client->NPC_class == CLASS_ATST) { // FIXME: need keyframed explosions + if (!self->s.number) { + G_DrivableATSTDie(self); + } + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data + if (anim != -1) { + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + } else if (self->s.number && self->message && meansOfDeath != MOD_SNIPER) { // imp with a key on his arm + // pick a death anim that leaves key visible + switch (Q_irand(0, 3)) { case 0: anim = BOTH_DEATH4; break; @@ -4223,139 +3295,95 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); anim = BOTH_DEATH18; break; } - //FIXME: verify we have this anim? - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else if ( meansOfDeath == MOD_FORCE_DRAIN ) - { - G_AddEvent( self, EV_WATER_DROWN, 0 ); - } - else if ( meansOfDeath == MOD_GAS ) - { - G_AddEvent( self, EV_WATER_DROWN, 0 ); - } - else - { - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); - } - } - else if ( meansOfDeath == MOD_FALLING || (self->client->ps.legsAnim == BOTH_FALLDEATH1INAIR && self->client->ps.torsoAnim == BOTH_FALLDEATH1INAIR) || (self->client->ps.legsAnim == BOTH_FALLDEATH1 && self->client->ps.torsoAnim == BOTH_FALLDEATH1) ) - { - //FIXME: no good way to predict you're going to fall to your death... need falling bushes/triggers? - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE //in the air - && self->client->ps.velocity[2] < 0 //falling - && self->client->ps.legsAnim != BOTH_FALLDEATH1INAIR //not already in falling loop - && self->client->ps.torsoAnim != BOTH_FALLDEATH1INAIR )//not already in falling loop - { - NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1INAIR, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - if ( !self->NPC ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - } - else if (!(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - //so we don't do this again + // FIXME: verify we have this anim? + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE) { + G_AddEvent(self, EV_JUMP, 0); + } else if (meansOfDeath == MOD_FORCE_DRAIN) { + G_AddEvent(self, EV_WATER_DROWN, 0); + } else if (meansOfDeath == MOD_GAS) { + G_AddEvent(self, EV_WATER_DROWN, 0); + } else { + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); + } + } else if (meansOfDeath == MOD_FALLING || (self->client->ps.legsAnim == BOTH_FALLDEATH1INAIR && self->client->ps.torsoAnim == BOTH_FALLDEATH1INAIR) || + (self->client->ps.legsAnim == BOTH_FALLDEATH1 && self->client->ps.torsoAnim == BOTH_FALLDEATH1)) { + // FIXME: no good way to predict you're going to fall to your death... need falling bushes/triggers? + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE // in the air + && self->client->ps.velocity[2] < 0 // falling + && self->client->ps.legsAnim != BOTH_FALLDEATH1INAIR // not already in falling loop + && self->client->ps.torsoAnim != BOTH_FALLDEATH1INAIR) // not already in falling loop + { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1INAIR, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (!self->NPC) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + } else if (!(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + // so we don't do this again self->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; - //self->client->ps.gravity *= 0.5;//Fall a bit slower + // self->client->ps.gravity *= 0.5;//Fall a bit slower self->client->ps.friction = 1; } - } - else - { - int deathAnim = BOTH_FALLDEATH1LAND; - if ( PM_InOnGroundAnim( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back - } - else - { - deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front - } - } - else if ( PM_InKnockDown( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_FALLING_UP; //# Death anim when falling on back - } - else - { - deathAnim = BOTH_DEATH_FALLING_DN; //# Death anim when falling on face - } - } - NPC_SetAnim(self, SETANIM_BOTH, deathAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - //HMM: check for nodrop? - G_SoundOnEnt( self, CHAN_BODY, "sound/player/fallsplat.wav" ); - if ( gi.VoiceVolume[self->s.number] - && self->NPC && (self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//I was talking, so cut it off... with a jump sound? - G_SoundOnEnt( self, CHAN_VOICE_ATTEN, "*pain100.wav" ); - } - } - } - else - {// normal death - anim = G_CheckSpecialDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); - if ( anim == -1 ) - { - if ( PM_InOnGroundAnim( &self->client->ps ) && PM_HasAnimation( self, BOTH_LYINGDEATH1 ) ) - {//on ground, need different death anim + } else { + int deathAnim = BOTH_FALLDEATH1LAND; + if (PM_InOnGroundAnim(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back + } else { + deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front + } + } else if (PM_InKnockDown(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_FALLING_UP; //# Death anim when falling on back + } else { + deathAnim = BOTH_DEATH_FALLING_DN; //# Death anim when falling on face + } + } + NPC_SetAnim(self, SETANIM_BOTH, deathAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // HMM: check for nodrop? + G_SoundOnEnt(self, CHAN_BODY, "sound/player/fallsplat.wav"); + if (gi.VoiceVolume[self->s.number] && self->NPC && + (self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // I was talking, so cut it off... with a jump sound? + G_SoundOnEnt(self, CHAN_VOICE_ATTEN, "*pain100.wav"); + } + } + } else { // normal death + anim = G_CheckSpecialDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); + if (anim == -1) { + if (PM_InOnGroundAnim(&self->client->ps) && PM_HasAnimation(self, BOTH_LYINGDEATH1)) { // on ground, need different death anim anim = BOTH_LYINGDEATH1; - } - else if ( meansOfDeath == MOD_TRIGGER_HURT && (self->s.powerups&(1<s.powerups & (1 << PW_SHOCKED))) { // electrocuted anim = BOTH_DEATH17; - } - else if ( meansOfDeath == MOD_WATER || meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN ) - {//drowned + } else if (meansOfDeath == MOD_WATER || meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN) { // drowned anim = BOTH_DEATH17; - } - else if ( meansOfDeath != MOD_SNIPER //disintegrates - && meansOfDeath != MOD_CONC_ALT )//does its own death throw + } else if (meansOfDeath != MOD_SNIPER // disintegrates + && meansOfDeath != MOD_CONC_ALT) // does its own death throw { - cliff_fall = G_CheckLedgeDive( self, 128, self->client->ps.velocity, qtrue, qfalse ); - if ( cliff_fall == 2 ) - { - if ( !FlyingCreature( self ) && g_gravity->value > 0 ) - { - if ( !self->NPC ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - } - else if (!(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN + cliff_fall = G_CheckLedgeDive(self, 128, self->client->ps.velocity, qtrue, qfalse); + if (cliff_fall == 2) { + if (!FlyingCreature(self) && g_gravity->value > 0) { + if (!self->NPC) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + } else if (!(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN self->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; self->client->ps.friction = 0; } } } - if ( self->client->ps.pm_time > 0 && self->client->ps.pm_flags & PMF_TIME_KNOCKBACK && self->client->ps.velocity[2] > 0 ) - { - float thrown, dot; - vec3_t throwdir, forward; + if (self->client->ps.pm_time > 0 && self->client->ps.pm_flags & PMF_TIME_KNOCKBACK && self->client->ps.velocity[2] > 0) { + float thrown, dot; + vec3_t throwdir, forward; AngleVectors(self->currentAngles, forward, NULL, NULL); thrown = VectorNormalize2(self->client->ps.velocity, throwdir); dot = DotProduct(forward, throwdir); - if ( thrown > 100 ) - { - if ( dot > 0.3 ) - {//falling forward - if ( cliff_fall == 2 && PM_HasAnimation( self, BOTH_FALLDEATH1 ) ) - { + if (thrown > 100) { + if (dot > 0.3) { // falling forward + if (cliff_fall == 2 && PM_HasAnimation(self, BOTH_FALLDEATH1)) { anim = BOTH_FALLDEATH1; - } - else - { - switch ( Q_irand( 0, 7 ) ) - { + } else { + switch (Q_irand(0, 7)) { case 0: case 1: anim = BOTH_DEATH4; @@ -4375,38 +3403,25 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); anim = BOTH_DEATH14; break; } - if ( PM_HasAnimation( self, anim )) - { + if (PM_HasAnimation(self, anim)) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { + } else { anim = -1; } } - } - else if ( dot < -0.3 ) - { - if ( thrown >= 250 && !Q_irand( 0, 3 ) ) - { - if ( Q_irand( 0, 1 ) ) - { + } else if (dot < -0.3) { + if (thrown >= 250 && !Q_irand(0, 3)) { + if (Q_irand(0, 1)) { anim = BOTH_DEATHBACKWARD1; - } - else - { + } else { anim = BOTH_DEATHBACKWARD2; } - } - else - { - switch ( Q_irand( 0, 7 ) ) - { + } else { + switch (Q_irand(0, 7)) { case 0: case 1: anim = BOTH_DEATH1; @@ -4425,27 +3440,19 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); break; } } - if ( PM_HasAnimation( self, anim ) ) - { + if (PM_HasAnimation(self, anim)) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { + } else { anim = -1; } - } - else - {//falling to one of the sides - if ( cliff_fall == 2 && PM_HasAnimation( self, BOTH_FALLDEATH1 ) ) - { + } else { // falling to one of the sides + if (cliff_fall == 2 && PM_HasAnimation(self, BOTH_FALLDEATH1)) { anim = BOTH_FALLDEATH1; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } } @@ -4453,270 +3460,201 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); } } } - } - else - { + } else { specialAnim = qtrue; } - if ( anim == -1 ) - { - if ( meansOfDeath == MOD_ELECTROCUTE - || (meansOfDeath == MOD_CRUSH && self->s.eFlags&EF_FORCE_GRIPPED) - || (meansOfDeath == MOD_FORCE_DRAIN && self->s.eFlags&EF_FORCE_DRAINED)) - {//electrocuted or choked to death + if (anim == -1) { + if (meansOfDeath == MOD_ELECTROCUTE || (meansOfDeath == MOD_CRUSH && self->s.eFlags & EF_FORCE_GRIPPED) || + (meansOfDeath == MOD_FORCE_DRAIN && self->s.eFlags & EF_FORCE_DRAINED)) { // electrocuted or choked to death anim = BOTH_DEATH17; - } - else - { - anim = G_PickDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); + } else { + anim = G_PickDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); } } - if ( anim == -1 ) - { - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data - //TEMP HACK: these spinny deaths should happen less often - if ( ( anim == BOTH_DEATH8 || anim == BOTH_DEATH14 ) && Q_irand( 0, 1 ) ) - { - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data + if (anim == -1) { + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data + // TEMP HACK: these spinny deaths should happen less often + if ((anim == BOTH_DEATH8 || anim == BOTH_DEATH14) && Q_irand(0, 1)) { + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data } + } else if (!PM_HasAnimation(self, anim)) { // crap, still missing an anim, so pick one that we do have + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data } - else if ( !PM_HasAnimation( self, anim ) ) - {//crap, still missing an anim, so pick one that we do have - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data - } - - if ( meansOfDeath == MOD_KNOCKOUT ) - { - //FIXME: knock-out sound, and don't remove me - G_AddEvent( self, EV_JUMP, 0 ); - G_UseTargets2( self, self, self->target2 ); - G_AlertTeam( self, attacker, 512, 32 ); - if ( self->NPC ) - {//stick around for a while + if (meansOfDeath == MOD_KNOCKOUT) { + // FIXME: knock-out sound, and don't remove me + G_AddEvent(self, EV_JUMP, 0); + G_UseTargets2(self, self, self->target2); + G_AlertTeam(self, attacker, 512, 32); + if (self->NPC) { // stick around for a while self->NPC->timeOfDeath = level.time + 10000; } - } - else if ( meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN ) - { - G_AddEvent( self, EV_WATER_DROWN, 0 ); - G_AlertTeam( self, attacker, 512, 32 ); - if ( self->NPC ) - {//stick around for a while + } else if (meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN) { + G_AddEvent(self, EV_WATER_DROWN, 0); + G_AlertTeam(self, attacker, 512, 32); + if (self->NPC) { // stick around for a while self->NPC->timeOfDeath = level.time + 10000; } - } - else if ( meansOfDeath == MOD_SNIPER ) - { - gentity_t *tent; - vec3_t spot; + } else if (meansOfDeath == MOD_SNIPER) { + gentity_t *tent; + vec3_t spot; - VectorCopy( self->currentOrigin, spot ); + VectorCopy(self->currentOrigin, spot); self->flags |= FL_DISINTEGRATED; self->svFlags |= SVF_BROADCAST; - tent = G_TempEntity( spot, EV_DISINTEGRATION ); + tent = G_TempEntity(spot, EV_DISINTEGRATION); tent->s.eventParm = PW_DISRUPTION; tent->svFlags |= SVF_BROADCAST; tent->owner = self; - G_AlertTeam( self, attacker, 512, 88 ); + G_AlertTeam(self, attacker, 512, 88); - if ( self->playerModel >= 0 ) - { + if (self->playerModel >= 0) { // don't let 'em animate - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, cg.time ); - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->motionBone, cg.time ); - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->lowerLumbarBone, cg.time ); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, cg.time); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->motionBone, cg.time); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->lowerLumbarBone, cg.time); anim = -1; } - //not solid anymore + // not solid anymore self->contents = 0; self->maxs[2] = -8; - if ( self->NPC ) - { - //need to pad deathtime some to stick around long enough for death effect to play + if (self->NPC) { + // need to pad deathtime some to stick around long enough for death effect to play self->NPC->timeOfDeath = level.time + 2000; } - } - else - { - if ( hitLoc == HL_HEAD - && !(dflags&DAMAGE_RADIUS) - && meansOfDeath!=MOD_REPEATER_ALT - && meansOfDeath!=MOD_FLECHETTE_ALT - && meansOfDeath!=MOD_ROCKET - && meansOfDeath!=MOD_ROCKET_ALT - && meansOfDeath!=MOD_CONC - && meansOfDeath!=MOD_THERMAL - && meansOfDeath!=MOD_THERMAL_ALT - && meansOfDeath!=MOD_DETPACK - && meansOfDeath!=MOD_LASERTRIP - && meansOfDeath!=MOD_LASERTRIP_ALT - && meansOfDeath!=MOD_EXPLOSIVE - && meansOfDeath!=MOD_EXPLOSIVE_SPLASH ) - {//no sound when killed by headshot (explosions don't count) - G_AlertTeam( self, attacker, 512, 0 ); - if ( gi.VoiceVolume[self->s.number] ) - {//I was talking, so cut it off... with a jump sound? - G_SoundOnEnt( self, CHAN_VOICE, "*jump1.wav" ); - } - } - else - { - if ( (self->client->ps.eFlags&EF_FORCE_GRIPPED) || (self->client->ps.eFlags&EF_FORCE_DRAINED) ) - {//killed while gripped - no loud scream - G_AlertTeam( self, attacker, 512, 32 ); + } else { + if (hitLoc == HL_HEAD && !(dflags & DAMAGE_RADIUS) && meansOfDeath != MOD_REPEATER_ALT && meansOfDeath != MOD_FLECHETTE_ALT && + meansOfDeath != MOD_ROCKET && meansOfDeath != MOD_ROCKET_ALT && meansOfDeath != MOD_CONC && meansOfDeath != MOD_THERMAL && + meansOfDeath != MOD_THERMAL_ALT && meansOfDeath != MOD_DETPACK && meansOfDeath != MOD_LASERTRIP && meansOfDeath != MOD_LASERTRIP_ALT && + meansOfDeath != MOD_EXPLOSIVE && meansOfDeath != MOD_EXPLOSIVE_SPLASH) { // no sound when killed by headshot (explosions don't count) + G_AlertTeam(self, attacker, 512, 0); + if (gi.VoiceVolume[self->s.number]) { // I was talking, so cut it off... with a jump sound? + G_SoundOnEnt(self, CHAN_VOICE, "*jump1.wav"); } - else if ( cliff_fall != 2 ) - { - if ( meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else if ( meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN ) - { - G_AddEvent( self, EV_WATER_DROWN, 0 ); - } - else - { - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); + } else { + if ((self->client->ps.eFlags & EF_FORCE_GRIPPED) || (self->client->ps.eFlags & EF_FORCE_DRAINED)) { // killed while gripped - no loud scream + G_AlertTeam(self, attacker, 512, 32); + } else if (cliff_fall != 2) { + if (meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE) { + G_AddEvent(self, EV_JUMP, 0); + } else if (meansOfDeath == MOD_GAS || meansOfDeath == MOD_FORCE_DRAIN) { + G_AddEvent(self, EV_WATER_DROWN, 0); + } else { + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); } - G_DeathAlert( self, attacker ); - } - else - {//screaming death is louder - G_AlertTeam( self, attacker, 512, 1024 ); + G_DeathAlert(self, attacker); + } else { // screaming death is louder + G_AlertTeam(self, attacker, 512, 1024); } } } - if ( attacker && attacker->s.number == 0 ) - {//killed by player - //FIXME: this should really be wherever my body comes to rest... - AddSightEvent( attacker, self->currentOrigin, 384, AEL_DISCOVERED, 10 ); - //FIXME: danger event so that others will run away from this area since it's obviously dangerous + if (attacker && attacker->s.number == 0) { // killed by player + // FIXME: this should really be wherever my body comes to rest... + AddSightEvent(attacker, self->currentOrigin, 384, AEL_DISCOVERED, 10); + // FIXME: danger event so that others will run away from this area since it's obviously dangerous } - if ( anim >= 0 )//can be -1 if it fails, -2 if it's already in a death anim + if (anim >= 0) // can be -1 if it fails, -2 if it's already in a death anim { - NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - //do any dismemberment if there's any to do... - if ( (dflags&DAMAGE_DISMEMBER) - && G_DoDismemberment( self, self->pos1, meansOfDeath, damage, hitLoc ) - && !specialAnim ) - {//we did dismemberment and our death anim is okay to override - if ( hitLoc == HL_HAND_RT && self->locationDamage[hitLoc] >= Q3_INFINITE && cliff_fall != 2 && self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//just lost our right hand and we're on the ground, use the special anim - NPC_SetAnim( self, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // do any dismemberment if there's any to do... + if ((dflags & DAMAGE_DISMEMBER) && G_DoDismemberment(self, self->pos1, meansOfDeath, damage, hitLoc) && + !specialAnim) { // we did dismemberment and our death anim is okay to override + if (hitLoc == HL_HAND_RT && self->locationDamage[hitLoc] >= Q3_INFINITE && cliff_fall != 2 && + self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // just lost our right hand and we're on the ground, use the special anim + NPC_SetAnim(self, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } // don't allow player to respawn for a few seconds - self->client->respawnTime = level.time + 2000;//self->client->ps.legsAnimTimer; + self->client->respawnTime = level.time + 2000; // self->client->ps.legsAnimTimer; -//rww - RAGDOLL_BEGIN - if (gi.Cvar_VariableIntegerValue("broadsword")) - { - if ( self->client && (!self->NPC || !G_StandardHumanoid( self ) ) ) - { - PM_SetLegsAnimTimer( self, &self->client->ps.legsAnimTimer, -1 ); - PM_SetTorsoAnimTimer( self, &self->client->ps.torsoAnimTimer, -1 ); + // rww - RAGDOLL_BEGIN + if (gi.Cvar_VariableIntegerValue("broadsword")) { + if (self->client && (!self->NPC || !G_StandardHumanoid(self))) { + PM_SetLegsAnimTimer(self, &self->client->ps.legsAnimTimer, -1); + PM_SetTorsoAnimTimer(self, &self->client->ps.torsoAnimTimer, -1); } - } - else - { - if ( self->client ) - { - PM_SetLegsAnimTimer( self, &self->client->ps.legsAnimTimer, -1 ); - PM_SetTorsoAnimTimer( self, &self->client->ps.torsoAnimTimer, -1 ); + } else { + if (self->client) { + PM_SetLegsAnimTimer(self, &self->client->ps.legsAnimTimer, -1); + PM_SetTorsoAnimTimer(self, &self->client->ps.torsoAnimTimer, -1); } } -//rww - RAGDOLL_END + // rww - RAGDOLL_END - //Flying creatures should drop when killed - //FIXME: This may screw up certain things that expect to float even while dead + // Flying creatures should drop when killed + // FIXME: This may screw up certain things that expect to float even while dead self->svFlags &= ~SVF_CUSTOM_GRAVITY; self->client->ps.pm_type = PM_DEAD; self->client->ps.pm_flags &= ~PMF_STUCK_TO_WALL; - //need to update STAT_HEALTH here because ClientThink_real for self may happen before STAT_HEALTH is updated from self->health and pmove will stomp death anim with a move anim + // need to update STAT_HEALTH here because ClientThink_real for self may happen before STAT_HEALTH is updated from self->health and pmove will stomp death + // anim with a move anim self->client->ps.stats[STAT_HEALTH] = self->health; - if ( self->NPC ) - {//If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths + if (self->NPC) { // If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths self->NPC->nextBStateThink = level.time; } - if ( G_ActivateBehavior( self, BSET_DEATH ) ) - { + if (G_ActivateBehavior(self, BSET_DEATH)) { deathScript = qtrue; } - if ( self->NPC && (self->NPC->scriptFlags&SCF_FFDEATH) ) - { - if ( G_ActivateBehavior( self, BSET_FFDEATH ) ) - {//FIXME: should running this preclude running the normal deathscript? + if (self->NPC && (self->NPC->scriptFlags & SCF_FFDEATH)) { + if (G_ActivateBehavior(self, BSET_FFDEATH)) { // FIXME: should running this preclude running the normal deathscript? deathScript = qtrue; } - G_UseTargets2( self, self, self->target4 ); + G_UseTargets2(self, self, self->target4); } - if ( !deathScript && !(self->svFlags&SVF_KILLED_SELF) ) - { - //Should no longer run scripts - //WARNING!!! DO NOT DO THIS WHILE RUNNING A SCRIPT, ICARUS WILL HANDLE IT, but it's bad - Quake3Game()->FreeEntity( self ); + if (!deathScript && !(self->svFlags & SVF_KILLED_SELF)) { + // Should no longer run scripts + // WARNING!!! DO NOT DO THIS WHILE RUNNING A SCRIPT, ICARUS WILL HANDLE IT, but it's bad + Quake3Game()->FreeEntity(self); } // Free up any timers we may have on us. - TIMER_Clear( self->s.number ); + TIMER_Clear(self->s.number); // Set pending objectives to failed OBJ_SetPendingObjectives(self); - gi.linkentity (self); + gi.linkentity(self); self->bounceCount = -1; // This is a cheap hack for optimizing the pointcontents check in deadthink - if ( self->NPC ) - { - self->NPC->timeOfDeath = level.time;//this will change - used for debouncing post-death events - self->s.time = level.time;//this will not chage- this is actual time of death + if (self->NPC) { + self->NPC->timeOfDeath = level.time; // this will change - used for debouncing post-death events + self->s.time = level.time; // this will not chage- this is actual time of death } // Start any necessary death fx for this entity - DeathFX( self ); + DeathFX(self); } -qboolean G_CheckForStrongAttackMomentum( gentity_t *self ) -{//see if our saber attack has too much momentum to be interrupted - if ( PM_PowerLevelForSaberAnim( &self->client->ps ) > FORCE_LEVEL_2 ) - {//strong attacks can't be interrupted - if ( PM_InAnimForSaberMove( self->client->ps.torsoAnim, self->client->ps.saberMove ) ) - {//our saberMove was not already interupted by some other anim (like pain) - if ( PM_SaberInStart( self->client->ps.saberMove ) ) - { - float animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.torsoAnim ); - if ( animLength - self->client->ps.torsoAnimTimer > 750 ) - {//start anim is already 3/4 of a second into it, can't interrupt it now +qboolean G_CheckForStrongAttackMomentum(gentity_t *self) { // see if our saber attack has too much momentum to be interrupted + if (PM_PowerLevelForSaberAnim(&self->client->ps) > FORCE_LEVEL_2) { // strong attacks can't be interrupted + if (PM_InAnimForSaberMove(self->client->ps.torsoAnim, + self->client->ps.saberMove)) { // our saberMove was not already interupted by some other anim (like pain) + if (PM_SaberInStart(self->client->ps.saberMove)) { + float animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.torsoAnim); + if (animLength - self->client->ps.torsoAnimTimer > 750) { // start anim is already 3/4 of a second into it, can't interrupt it now return qtrue; } - } - else if ( PM_SaberInReturn( self->client->ps.saberMove ) ) - { - if ( self->client->ps.torsoAnimTimer > 750 ) - {//still have a good amount of time left in the return anim, can't interrupt it + } else if (PM_SaberInReturn(self->client->ps.saberMove)) { + if (self->client->ps.torsoAnimTimer > 750) { // still have a good amount of time left in the return anim, can't interrupt it return qtrue; } - } - else - {//cannot interrupt actual transitions and attacks + } else { // cannot interrupt actual transitions and attacks return qtrue; } } @@ -4724,90 +3662,70 @@ qboolean G_CheckForStrongAttackMomentum( gentity_t *self ) return qfalse; } -void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc ) -{ - if ( self->client->NPC_class == CLASS_ATST ) - {//different kind of pain checking altogether - G_ATSTCheckPain( self, other, point, damage, mod, hitLoc ); - int blasterTest = gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head_light_blaster_cann" ); - int chargerTest = gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head_concussion_charger" ); - if ( blasterTest && chargerTest ) - {//lost both side guns - //take away that weapon - self->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_ATST_SIDE ); - //switch to primary guns - if ( self->client->ps.weapon == WP_ATST_SIDE ) - { - CG_ChangeWeapon( WP_ATST_MAIN ); +void PlayerPain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->client->NPC_class == CLASS_ATST) { // different kind of pain checking altogether + G_ATSTCheckPain(self, other, point, damage, mod, hitLoc); + int blasterTest = gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head_light_blaster_cann"); + int chargerTest = gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head_concussion_charger"); + if (blasterTest && chargerTest) { // lost both side guns + // take away that weapon + self->client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_ATST_SIDE); + // switch to primary guns + if (self->client->ps.weapon == WP_ATST_SIDE) { + CG_ChangeWeapon(WP_ATST_MAIN); } } - } - else - { + } else { // play an apropriate pain sound - if ( level.time > self->painDebounceTime && !(self->flags & FL_GODMODE) ) - {//first time hit this frame and not in godmode + if (level.time > self->painDebounceTime && !(self->flags & FL_GODMODE)) { // first time hit this frame and not in godmode self->client->ps.damageEvent++; - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - if ( self->client->damage_blood ) - {//took damage myself, not just armor - if ( mod == MOD_GAS ) - { - //SIGH... because our choke sounds are inappropriately long, I have to debounce them in code! - if ( TIMER_Done( self, "gasChokeSound" ) ) - { - TIMER_Set( self, "gasChokeSound", Q_irand( 1000, 2000 ) ); - G_SpeechEvent( self, Q_irand(EV_CHOKE1, EV_CHOKE3) ); + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + if (self->client->damage_blood) { // took damage myself, not just armor + if (mod == MOD_GAS) { + // SIGH... because our choke sounds are inappropriately long, I have to debounce them in code! + if (TIMER_Done(self, "gasChokeSound")) { + TIMER_Set(self, "gasChokeSound", Q_irand(1000, 2000)); + G_SpeechEvent(self, Q_irand(EV_CHOKE1, EV_CHOKE3)); } - if ( self->painDebounceTime <= level.time ) - { + if (self->painDebounceTime <= level.time) { self->painDebounceTime = level.time + 50; } - } - else - { - G_AddEvent( self, EV_PAIN, self->health ); + } else { + G_AddEvent(self, EV_PAIN, self->health); } } } } - if ( damage != -1 && (mod==MOD_MELEE || damage==0/*fake damage*/ || (Q_irand( 0, 10 ) <= damage && self->client->damage_blood)) ) - {//-1 == don't play pain anim - if ( ( ((mod==MOD_SABER||mod==MOD_MELEE)&&self->client->damage_blood) || mod == MOD_CRUSH ) && (self->s.weapon == WP_SABER||self->s.weapon==WP_MELEE||cg.renderingThirdPerson) )//FIXME: not only if using saber, but if in third person at all? But then 1st/third person functionality is different... - {//FIXME: only strong-level saber attacks should make me play pain anim? - if ( !G_CheckForStrongAttackMomentum( self ) && !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - {//strong attacks and spins cannot be interrupted by pain, no pain when in knockdown - int parts = SETANIM_BOTH; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && - !PM_SpinningSaberAnim( self->client->ps.legsAnim ) && - !PM_FlippingAnim( self->client->ps.legsAnim ) && - !PM_InSpecialJump( self->client->ps.legsAnim ) && - !PM_RollingAnim( self->client->ps.legsAnim )&& - !PM_CrouchAnim( self->client->ps.legsAnim )&& - !PM_RunningAnim( self->client->ps.legsAnim )) - {//if on a surface and not in a spin or flip, play full body pain + if (damage != -1 && + (mod == MOD_MELEE || damage == 0 /*fake damage*/ || (Q_irand(0, 10) <= damage && self->client->damage_blood))) { //-1 == don't play pain anim + if ((((mod == MOD_SABER || mod == MOD_MELEE) && self->client->damage_blood) || mod == MOD_CRUSH) && + (self->s.weapon == WP_SABER || self->s.weapon == WP_MELEE || + cg.renderingThirdPerson)) // FIXME: not only if using saber, but if in third person at all? But then 1st/third person functionality is + // different... + { // FIXME: only strong-level saber attacks should make me play pain anim? + if (!G_CheckForStrongAttackMomentum(self) && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_SaberInSpecialAttack(self->client->ps.torsoAnim) && + !PM_InKnockDown(&self->client->ps)) { // strong attacks and spins cannot be interrupted by pain, no pain when in knockdown + int parts = SETANIM_BOTH; + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_InSpecialJump(self->client->ps.legsAnim) && + !PM_RollingAnim(self->client->ps.legsAnim) && !PM_CrouchAnim(self->client->ps.legsAnim) && + !PM_RunningAnim(self->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body pain parts = SETANIM_BOTH; - } - else - {//play pain just in torso + } else { // play pain just in torso parts = SETANIM_TORSO; } - if ( self->painDebounceTime < level.time ) - { - //temp HACK: these are the only 2 pain anims that look good when holding a saber - NPC_SetAnim( self, parts, PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = LS_READY;//don't finish whatever saber move you may have been in - //WTF - insn't working - if ( self->health < 10 && d_slowmodeath->integer > 5 ) - { - G_StartMatrixEffect( self ); + if (self->painDebounceTime < level.time) { + // temp HACK: these are the only 2 pain anims that look good when holding a saber + NPC_SetAnim(self, parts, PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = LS_READY; // don't finish whatever saber move you may have been in + // WTF - insn't working + if (self->health < 10 && d_slowmodeath->integer > 5) { + G_StartMatrixEffect(self); } } - if ( (parts == SETANIM_BOTH && damage > 30) || (self->painDebounceTime>level.time&&damage>10)) - {//took a lot of damage in 1 hit //or took 2 hits in quick succession + if ((parts == SETANIM_BOTH && damage > 30) || + (self->painDebounceTime > level.time && damage > 10)) { // took a lot of damage in 1 hit //or took 2 hits in quick succession self->aimDebounceTime = level.time + self->client->ps.torsoAnimTimer; self->client->ps.pm_time = self->client->ps.torsoAnimTimer; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; @@ -4819,8 +3737,7 @@ void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const } } } - if ( mod != MOD_GAS && self->painDebounceTime <= level.time ) - { + if (mod != MOD_GAS && self->painDebounceTime <= level.time) { self->painDebounceTime = level.time + 700; } } @@ -4829,11 +3746,10 @@ void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const CheckArmor ================ */ -int CheckArmor (gentity_t *ent, int damage, int dflags, int mod) -{ - gclient_t *client; - int save; - int count; +int CheckArmor(gentity_t *ent, int damage, int dflags, int mod) { + gclient_t *client; + int save; + int count; if (!damage) return 0; @@ -4843,42 +3759,34 @@ int CheckArmor (gentity_t *ent, int damage, int dflags, int mod) if (!client) return 0; - if ( (dflags&DAMAGE_NO_ARMOR) ) - { + if ((dflags & DAMAGE_NO_ARMOR)) { // If this isn't a vehicle, leave. - if ( client->NPC_class != CLASS_VEHICLE ) - { + if (client->NPC_class != CLASS_VEHICLE) { return 0; } } - if (client->NPC_class==CLASS_ASSASSIN_DROID) - { + if (client->NPC_class == CLASS_ASSASSIN_DROID) { // The Assassin Always Completely Ignores These Damage Types //----------------------------------------------------------- - if (mod==MOD_GAS || mod==MOD_IMPACT || mod==MOD_LAVA || mod==MOD_SLIME || mod==MOD_WATER || - mod==MOD_FORCE_GRIP || mod==MOD_FORCE_DRAIN || mod==MOD_SEEKER || mod==MOD_MELEE || - mod==MOD_BOWCASTER || mod==MOD_BRYAR || mod==MOD_BRYAR_ALT || mod==MOD_BLASTER || mod==MOD_BLASTER_ALT || - mod==MOD_SNIPER || mod==MOD_BOWCASTER || mod==MOD_BOWCASTER_ALT || mod==MOD_REPEATER || mod==MOD_REPEATER_ALT) - { + if (mod == MOD_GAS || mod == MOD_IMPACT || mod == MOD_LAVA || mod == MOD_SLIME || mod == MOD_WATER || mod == MOD_FORCE_GRIP || mod == MOD_FORCE_DRAIN || + mod == MOD_SEEKER || mod == MOD_MELEE || mod == MOD_BOWCASTER || mod == MOD_BRYAR || mod == MOD_BRYAR_ALT || mod == MOD_BLASTER || + mod == MOD_BLASTER_ALT || mod == MOD_SNIPER || mod == MOD_BOWCASTER || mod == MOD_BOWCASTER_ALT || mod == MOD_REPEATER || mod == MOD_REPEATER_ALT) { return damage; } // The Assassin Always Takes Half Of These Damage Types //------------------------------------------------------ - if (mod==MOD_GAS || mod==MOD_IMPACT || mod==MOD_LAVA || mod==MOD_SLIME || mod==MOD_WATER) - { - return damage/2; + if (mod == MOD_GAS || mod == MOD_IMPACT || mod == MOD_LAVA || mod == MOD_SLIME || mod == MOD_WATER) { + return damage / 2; } // If The Shield Is Not On, No Additional Protection //--------------------------------------------------- - if (!(ent->flags&FL_SHIELDED)) - { + if (!(ent->flags & FL_SHIELDED)) { // He Does Ignore Half Saber Damage, Even Shield Down //---------------------------------------------------- - if (mod==MOD_SABER) - { + if (mod == MOD_SABER) { return (int)((float)(damage)*0.75f); } return 0; @@ -4886,78 +3794,60 @@ int CheckArmor (gentity_t *ent, int damage, int dflags, int mod) // If The Shield Is Up, He Ignores These Damage Types //---------------------------------------------------- - if (mod==MOD_SABER || mod==MOD_FLECHETTE || mod==MOD_FLECHETTE_ALT || mod==MOD_DISRUPTOR) - { + if (mod == MOD_SABER || mod == MOD_FLECHETTE || mod == MOD_FLECHETTE_ALT || mod == MOD_DISRUPTOR) { return damage; } // The Demp Completely Destroys The Shield //----------------------------------------- - if (mod==MOD_DEMP2 || mod==MOD_DEMP2_ALT) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { client->ps.stats[STAT_ARMOR] = 0; return 0; } // Otherwise, The Shield Absorbs As Much Damage As Possible //---------------------------------------------------------- - int previousArmor = client->ps.stats[STAT_ARMOR]; + int previousArmor = client->ps.stats[STAT_ARMOR]; client->ps.stats[STAT_ARMOR] -= damage; - if (client->ps.stats[STAT_ARMOR]<0) - { + if (client->ps.stats[STAT_ARMOR] < 0) { client->ps.stats[STAT_ARMOR] = 0; } return (previousArmor - client->ps.stats[STAT_ARMOR]); } - - - if ( client->NPC_class == CLASS_GALAKMECH) - {//special case - if ( client->ps.stats[STAT_ARMOR] <= 0 ) - {//no shields + if (client->NPC_class == CLASS_GALAKMECH) { // special case + if (client->ps.stats[STAT_ARMOR] <= 0) { // no shields client->ps.powerups[PW_GALAK_SHIELD] = 0; return 0; - } - else - {//shields take all the damage + } else { // shields take all the damage client->ps.stats[STAT_ARMOR] -= damage; - if ( client->ps.stats[STAT_ARMOR] <= 0 ) - { + if (client->ps.stats[STAT_ARMOR] <= 0) { client->ps.powerups[PW_GALAK_SHIELD] = 0; client->ps.stats[STAT_ARMOR] = 0; } return damage; } - } - else - { + } else { // armor count = client->ps.stats[STAT_ARMOR]; // No damage to entity until armor is at less than 50% strength - if (count > (client->ps.stats[STAT_MAX_HEALTH]/2)) // MAX_HEALTH is considered max armor. Or so I'm told. + if (count > (client->ps.stats[STAT_MAX_HEALTH] / 2)) // MAX_HEALTH is considered max armor. Or so I'm told. { save = damage; - } - else - { - if ( !ent->s.number && client->NPC_class == CLASS_ATST ) - {//player in ATST... armor takes *all* the damage + } else { + if (!ent->s.number && client->NPC_class == CLASS_ATST) { // player in ATST... armor takes *all* the damage save = damage; - } - else - { - save = ceil( (float) damage * ARMOR_PROTECTION ); + } else { + save = ceil((float)damage * ARMOR_PROTECTION); } } - //Always round up - if (damage == 1) - { - if ( client->ps.stats[STAT_ARMOR] > 0 ) + // Always round up + if (damage == 1) { + if (client->ps.stats[STAT_ARMOR] > 0) client->ps.stats[STAT_ARMOR] -= save; - //WTF? returns false 0 if armor absorbs only 1 point of damage + // WTF? returns false 0 if armor absorbs only 1 point of damage return 0; } @@ -4973,107 +3863,74 @@ int CheckArmor (gentity_t *ent, int damage, int dflags, int mod) } } -extern void NPC_SetPainEvent( gentity_t *self ); -extern qboolean Boba_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown = qfalse ); -extern qboolean Jedi_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir ); -void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ) -{ - if ( !self || !self->client || !attacker || !attacker->client ) - { +extern void NPC_SetPainEvent(gentity_t *self); +extern qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown = qfalse); +extern qboolean Jedi_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir); +void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock) { + if (!self || !self->client || !attacker || !attacker->client) { return; } - if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { + if (self->client->NPC_class == CLASS_ROCKETTROOPER) { return; } - if ( Boba_StopKnockdown( self, attacker, pushDir ) ) - { + if (Boba_StopKnockdown(self, attacker, pushDir)) { return; - } - else if ( Jedi_StopKnockdown( self, attacker, pushDir ) ) - {//They can sometimes backflip instead of be knocked down + } else if (Jedi_StopKnockdown(self, attacker, pushDir)) { // They can sometimes backflip instead of be knocked down return; - } - else if ( PM_LockedAnim( self->client->ps.legsAnim ) ) - {//stuck doing something else + } else if (PM_LockedAnim(self->client->ps.legsAnim)) { // stuck doing something else return; - } - else if ( Rosh_BeingHealed( self ) ) - { + } else if (Rosh_BeingHealed(self)) { return; } - //break out of a saberLock? - if ( self->client->ps.saberLockTime > level.time ) - { - if ( breakSaberLock ) - { + // break out of a saberLock? + if (self->client->ps.saberLockTime > level.time) { + if (breakSaberLock) { self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; - } - else - { + } else { return; } } - if ( self->health > 0 ) - { - if ( !self->s.number ) - { - NPC_SetPainEvent( self ); - } - else - { - GEntity_PainFunc( self, attacker, attacker, self->currentOrigin, 0, MOD_MELEE ); + if (self->health > 0) { + if (!self->s.number) { + NPC_SetPainEvent(self); + } else { + GEntity_PainFunc(self, attacker, attacker, self->currentOrigin, 0, MOD_MELEE); } - G_CheckLedgeDive( self, 72, pushDir, qfalse, qfalse ); + G_CheckLedgeDive(self, 72, pushDir, qfalse, qfalse); - if ( !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - { - int knockAnim = BOTH_KNOCKDOWN1;//default knockdown - if ( !self->s.number && ( strength < 300 ) )//!g_spskill->integer || - {//player only knocked down if pushed *hard* + if (!PM_SpinningSaberAnim(self->client->ps.legsAnim) && !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && + !PM_InKnockDown(&self->client->ps)) { + int knockAnim = BOTH_KNOCKDOWN1; // default knockdown + if (!self->s.number && (strength < 300)) //! g_spskill->integer || + { // player only knocked down if pushed *hard* return; - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - {//crouched knockdown + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { // crouched knockdown knockAnim = BOTH_KNOCKDOWN4; - } - else - {//plain old knockdown - vec3_t pLFwd, pLAngles = {0,self->client->ps.viewangles[YAW],0}; - AngleVectors( pLAngles, pLFwd, NULL, NULL ); - if ( DotProduct( pLFwd, pushDir ) > 0.2f ) - {//pushing him from behind + } else { // plain old knockdown + vec3_t pLFwd, pLAngles = {0, self->client->ps.viewangles[YAW], 0}; + AngleVectors(pLAngles, pLFwd, NULL, NULL); + if (DotProduct(pLFwd, pushDir) > 0.2f) { // pushing him from behind knockAnim = BOTH_KNOCKDOWN3; - } - else - {//pushing him from front + } else { // pushing him from front knockAnim = BOTH_KNOCKDOWN1; } } - if ( knockAnim == BOTH_KNOCKDOWN1 && strength > 150 ) - {//push *hard* + if (knockAnim == BOTH_KNOCKDOWN1 && strength > 150) { // push *hard* knockAnim = BOTH_KNOCKDOWN2; } - NPC_SetAnim( self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->s.number >= MAX_CLIENTS ) - {//randomize getup times - int addTime = Q_irand( -200, 200 ); + NPC_SetAnim(self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (self->s.number >= MAX_CLIENTS) { // randomize getup times + int addTime = Q_irand(-200, 200); self->client->ps.legsAnimTimer += addTime; self->client->ps.torsoAnimTimer += addTime; - } - else - {//player holds extra long so you have more time to decide to do the quick getup - if ( PM_KnockDownAnim( self->client->ps.legsAnim ) ) - { + } else { // player holds extra long so you have more time to decide to do the quick getup + if (PM_KnockDownAnim(self->client->ps.legsAnim)) { self->client->ps.legsAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; self->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } @@ -5082,142 +3939,104 @@ void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, fl } } -void G_CheckKnockdown( gentity_t *targ, gentity_t *attacker, vec3_t newDir, int dflags, int mod ) -{ - if ( !targ || !attacker ) - { +void G_CheckKnockdown(gentity_t *targ, gentity_t *attacker, vec3_t newDir, int dflags, int mod) { + if (!targ || !attacker) { return; } - if ( !(dflags&DAMAGE_RADIUS) ) - {//not inherently explosive damage, check mod - if ( mod!=MOD_REPEATER_ALT - &&mod!=MOD_FLECHETTE_ALT - &&mod!=MOD_ROCKET - &&mod!=MOD_ROCKET_ALT - &&mod!=MOD_CONC - &&mod!=MOD_CONC_ALT - &&mod!=MOD_THERMAL - &&mod!=MOD_THERMAL_ALT - &&mod!=MOD_DETPACK - &&mod!=MOD_LASERTRIP - &&mod!=MOD_LASERTRIP_ALT - &&mod!=MOD_EXPLOSIVE - &&mod!=MOD_EXPLOSIVE_SPLASH ) - { + if (!(dflags & DAMAGE_RADIUS)) { // not inherently explosive damage, check mod + if (mod != MOD_REPEATER_ALT && mod != MOD_FLECHETTE_ALT && mod != MOD_ROCKET && mod != MOD_ROCKET_ALT && mod != MOD_CONC && mod != MOD_CONC_ALT && + mod != MOD_THERMAL && mod != MOD_THERMAL_ALT && mod != MOD_DETPACK && mod != MOD_LASERTRIP && mod != MOD_LASERTRIP_ALT && mod != MOD_EXPLOSIVE && + mod != MOD_EXPLOSIVE_SPLASH) { return; } } - if ( !targ->client || targ->client->NPC_class == CLASS_PROTOCOL || !G_StandardHumanoid( targ ) ) - { + if (!targ->client || targ->client->NPC_class == CLASS_PROTOCOL || !G_StandardHumanoid(targ)) { return; } - if ( targ->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//already in air + if (targ->client->ps.groundEntityNum == ENTITYNUM_NONE) { // already in air return; } - if ( !targ->s.number ) - {//player less likely to be knocked down - if ( !g_spskill->integer ) - {//never in easy + if (!targ->s.number) { // player less likely to be knocked down + if (!g_spskill->integer) { // never in easy return; } - if ( !cg.renderingThirdPerson || cg.zoomMode ) - {//never if not in chase camera view (so more likely with saber out) + if (!cg.renderingThirdPerson || cg.zoomMode) { // never if not in chase camera view (so more likely with saber out) return; } - if ( g_spskill->integer == 1 ) - {//33% chance on medium - if ( Q_irand( 0, 2 ) ) - { + if (g_spskill->integer == 1) { // 33% chance on medium + if (Q_irand(0, 2)) { return; } - } - else - {//50% chance on hard - if ( Q_irand( 0, 1 ) ) - { + } else { // 50% chance on hard + if (Q_irand(0, 1)) { return; } } } - float strength = VectorLength( targ->client->ps.velocity ); - if ( targ->client->ps.velocity[2] > 100 && strength > Q_irand( 150, 350 ) )//600 ) ) - {//explosive concussion possibly do a knockdown? - G_Knockdown( targ, attacker, newDir, strength, qtrue ); + float strength = VectorLength(targ->client->ps.velocity); + if (targ->client->ps.velocity[2] > 100 && strength > Q_irand(150, 350)) // 600 ) ) + { // explosive concussion possibly do a knockdown? + G_Knockdown(targ, attacker, newDir, strength, qtrue); } } -void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) -{ - vec3_t kvel; - float mass; - - if ( targ - && targ->client - && ( targ->client->NPC_class == CLASS_ATST - || targ->client->NPC_class == CLASS_RANCOR - || targ->client->NPC_class == CLASS_SAND_CREATURE - || targ->client->NPC_class == CLASS_WAMPA) ) - {//much to large to *ever* throw +void G_ApplyKnockback(gentity_t *targ, vec3_t newDir, float knockback) { + vec3_t kvel; + float mass; + + if (targ && targ->client && + (targ->client->NPC_class == CLASS_ATST || targ->client->NPC_class == CLASS_RANCOR || targ->client->NPC_class == CLASS_SAND_CREATURE || + targ->client->NPC_class == CLASS_WAMPA)) { // much to large to *ever* throw return; } //--- TEMP TEST - if ( newDir[2] <= 0.0f ) - { + if (newDir[2] <= 0.0f) { - newDir[2] += (( 0.0f - newDir[2] ) * 1.2f ); + newDir[2] += ((0.0f - newDir[2]) * 1.2f); } knockback *= 2.0f; - if ( knockback > 120 ) - { + if (knockback > 120) { knockback = 120; } //--- TEMP TEST - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass mass = targ->physicsBounce; else mass = 200; - if ( g_gravity->value > 0 ) - { - VectorScale( newDir, g_knockback->value * (float)knockback / mass * 0.8, kvel ); - kvel[2] = newDir[2] * ( g_knockback->value * (float)knockback ) / ( mass * 1.5 ) + 20; - } - else - { - VectorScale( newDir, g_knockback->value * (float)knockback / mass, kvel ); + if (g_gravity->value > 0) { + VectorScale(newDir, g_knockback->value * (float)knockback / mass * 0.8, kvel); + kvel[2] = newDir[2] * (g_knockback->value * (float)knockback) / (mass * 1.5) + 20; + } else { + VectorScale(newDir, g_knockback->value * (float)knockback / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = knockback * 2; - if ( t < 50 ) { + if (t < 50) { t = 50; } - if ( t > 200 ) { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -5225,54 +4044,47 @@ void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) } } -static int G_CheckForLedge( gentity_t *self, vec3_t fallCheckDir, float checkDist ) -{ - vec3_t start, end; - trace_t tr; +static int G_CheckForLedge(gentity_t *self, vec3_t fallCheckDir, float checkDist) { + vec3_t start, end; + trace_t tr; - VectorMA( self->currentOrigin, checkDist, fallCheckDir, end ); - //Should have clip burshes masked out by now and have bbox resized to death size - gi.trace( &tr, self->currentOrigin, self->mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + VectorMA(self->currentOrigin, checkDist, fallCheckDir, end); + // Should have clip burshes masked out by now and have bbox resized to death size + gi.trace(&tr, self->currentOrigin, self->mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { return 0; } - VectorCopy( tr.endpos, start ); - VectorCopy( start, end ); + VectorCopy(tr.endpos, start); + VectorCopy(start, end); end[2] -= 256; - gi.trace( &tr, start, self->mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + gi.trace(&tr, start, self->mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { return 0; } - if ( tr.fraction >= 1.0 ) - { - return (start[2]-tr.endpos[2]); + if (tr.fraction >= 1.0) { + return (start[2] - tr.endpos[2]); } return 0; } -static void G_FriendlyFireReaction( gentity_t *self, gentity_t *other, int dflags ) -{ - if ( (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) - {//hit by a teammate - if ( other != self->enemy && self != other->enemy ) - {//we weren't already enemies - if ( self->enemy || other->enemy || (other->s.number&&other->s.number!=player->client->ps.viewEntity) ) - {//if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad (FIXME:accumulate anger+base on diff?) +static void G_FriendlyFireReaction(gentity_t *self, gentity_t *other, int dflags) { + if ((!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) { // hit by a teammate + if (other != self->enemy && self != other->enemy) { // we weren't already enemies + if (self->enemy || other->enemy || + (other->s.number && + other->s.number != player->client->ps.viewEntity)) { // if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit + // by player or someone controlled by player OR player hit ally and didn't get 25% chance + // of getting mad (FIXME:accumulate anger+base on diff?) return; - } - else if ( self->NPC && !other->s.number )//should be assumed, but... - {//dammit, stop that! - if ( !(dflags&DAMAGE_RADIUS) ) - { - //if it's radius damage, ignore it - if ( self->NPC->ffireDebounce < level.time ) - { - //FIXME: way something? NEED DIALOGUE + } else if (self->NPC && !other->s.number) // should be assumed, but... + { // dammit, stop that! + if (!(dflags & DAMAGE_RADIUS)) { + // if it's radius damage, ignore it + if (self->NPC->ffireDebounce < level.time) { + // FIXME: way something? NEED DIALOGUE self->NPC->ffireCount++; - //Com_Printf( "incr: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); + // Com_Printf( "incr: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); self->NPC->ffireDebounce = level.time + 500; } } @@ -5281,52 +4093,46 @@ static void G_FriendlyFireReaction( gentity_t *self, gentity_t *other, int dflag } } -float damageModifier[HL_MAX] = -{ - 1.0f, //HL_NONE, - 0.25f, //HL_FOOT_RT, - 0.25f, //HL_FOOT_LT, - 0.75f, //HL_LEG_RT, - 0.75f, //HL_LEG_LT, - 1.0f, //HL_WAIST, - 1.0f, //HL_BACK_RT, - 1.0f, //HL_BACK_LT, - 1.0f, //HL_BACK, - 1.0f, //HL_CHEST_RT, - 1.0f, //HL_CHEST_LT, - 1.0f, //HL_CHEST, - 0.5f, //HL_ARM_RT, - 0.5f, //HL_ARM_LT, - 0.25f, //HL_HAND_RT, - 0.25f, //HL_HAND_LT, - 2.0f, //HL_HEAD, - 1.0f, //HL_GENERIC1, - 1.0f, //HL_GENERIC2, - 1.0f, //HL_GENERIC3, - 1.0f, //HL_GENERIC4, - 1.0f, //HL_GENERIC5, - 1.0f, //HL_GENERIC6, +float damageModifier[HL_MAX] = { + 1.0f, // HL_NONE, + 0.25f, // HL_FOOT_RT, + 0.25f, // HL_FOOT_LT, + 0.75f, // HL_LEG_RT, + 0.75f, // HL_LEG_LT, + 1.0f, // HL_WAIST, + 1.0f, // HL_BACK_RT, + 1.0f, // HL_BACK_LT, + 1.0f, // HL_BACK, + 1.0f, // HL_CHEST_RT, + 1.0f, // HL_CHEST_LT, + 1.0f, // HL_CHEST, + 0.5f, // HL_ARM_RT, + 0.5f, // HL_ARM_LT, + 0.25f, // HL_HAND_RT, + 0.25f, // HL_HAND_LT, + 2.0f, // HL_HEAD, + 1.0f, // HL_GENERIC1, + 1.0f, // HL_GENERIC2, + 1.0f, // HL_GENERIC3, + 1.0f, // HL_GENERIC4, + 1.0f, // HL_GENERIC5, + 1.0f, // HL_GENERIC6, }; -void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod ) -{ - if ( !self || !self->client || self->s.number ) - {//player only +void G_TrackWeaponUsage(gentity_t *self, gentity_t *inflictor, int add, int mod) { + if (!self || !self->client || self->s.number) { // player only return; } int weapon = WP_NONE; - //FIXME: need to check the MOD to find out what weapon (if *any*) actually did the killing - if ( inflictor && !inflictor->client && mod != MOD_SABER && inflictor->lastEnemy && inflictor->lastEnemy != self ) - {//a missile that was reflected, ie: not owned by me originally - if ( inflictor->owner == self && self->s.weapon == WP_SABER ) - {//we reflected it + // FIXME: need to check the MOD to find out what weapon (if *any*) actually did the killing + if (inflictor && !inflictor->client && mod != MOD_SABER && inflictor->lastEnemy && + inflictor->lastEnemy != self) { // a missile that was reflected, ie: not owned by me originally + if (inflictor->owner == self && self->s.weapon == WP_SABER) { // we reflected it weapon = WP_SABER; } } - if ( weapon == WP_NONE ) - { - switch ( mod ) - { + if (weapon == WP_NONE) { + switch (mod) { case MOD_SABER: weapon = WP_SABER; break; @@ -5378,87 +4184,53 @@ void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod weapon = WP_TRIP_MINE; break; case MOD_MELEE: - if ( self->s.weapon == WP_STUN_BATON ) - { + if (self->s.weapon == WP_STUN_BATON) { weapon = WP_STUN_BATON; - } - else if ( self->s.weapon == WP_MELEE ) - { + } else if (self->s.weapon == WP_MELEE) { weapon = WP_MELEE; } break; } } - if ( weapon != WP_NONE ) - { + if (weapon != WP_NONE) { self->client->sess.missionStats.weaponUsed[weapon] += add; } } -qboolean G_NonLocationSpecificDamage( int meansOfDeath ) -{ - if ( meansOfDeath == MOD_EXPLOSIVE - || meansOfDeath == MOD_REPEATER_ALT - || meansOfDeath == MOD_FLECHETTE_ALT - || meansOfDeath == MOD_ROCKET - || meansOfDeath == MOD_ROCKET_ALT - || meansOfDeath == MOD_CONC - || meansOfDeath == MOD_THERMAL - || meansOfDeath == MOD_THERMAL_ALT - || meansOfDeath == MOD_DETPACK - || meansOfDeath == MOD_LASERTRIP - || meansOfDeath == MOD_LASERTRIP_ALT - || meansOfDeath == MOD_MELEE - || meansOfDeath == MOD_FORCE_GRIP - || meansOfDeath == MOD_KNOCKOUT - || meansOfDeath == MOD_CRUSH - || meansOfDeath == MOD_EXPLOSIVE_SPLASH ) - { +qboolean G_NonLocationSpecificDamage(int meansOfDeath) { + if (meansOfDeath == MOD_EXPLOSIVE || meansOfDeath == MOD_REPEATER_ALT || meansOfDeath == MOD_FLECHETTE_ALT || meansOfDeath == MOD_ROCKET || + meansOfDeath == MOD_ROCKET_ALT || meansOfDeath == MOD_CONC || meansOfDeath == MOD_THERMAL || meansOfDeath == MOD_THERMAL_ALT || + meansOfDeath == MOD_DETPACK || meansOfDeath == MOD_LASERTRIP || meansOfDeath == MOD_LASERTRIP_ALT || meansOfDeath == MOD_MELEE || + meansOfDeath == MOD_FORCE_GRIP || meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_CRUSH || meansOfDeath == MOD_EXPLOSIVE_SPLASH) { return qtrue; } return qfalse; } -qboolean G_ImmuneToGas( gentity_t *ent ) -{ - if ( !ent || !ent->client ) - {//only effects living clients +qboolean G_ImmuneToGas(gentity_t *ent) { + if (!ent || !ent->client) { // only effects living clients return qtrue; } - if ( ent->s.weapon == WP_NOGHRI_STICK//assumes user is immune - || ent->client->NPC_class == CLASS_HAZARD_TROOPER - || ent->client->NPC_class == CLASS_ATST - || ent->client->NPC_class == CLASS_GONK - || ent->client->NPC_class == CLASS_SAND_CREATURE - || ent->client->NPC_class == CLASS_INTERROGATOR - || ent->client->NPC_class == CLASS_MARK1 - || ent->client->NPC_class == CLASS_MARK2 - || ent->client->NPC_class == CLASS_GALAKMECH - || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_PROBE // droid - || ent->client->NPC_class == CLASS_PROTOCOL // droid - || ent->client->NPC_class == CLASS_R2D2 // droid - || ent->client->NPC_class == CLASS_R5D2 // droid - || ent->client->NPC_class == CLASS_REMOTE - || ent->client->NPC_class == CLASS_SEEKER // droid - || ent->client->NPC_class == CLASS_SENTRY - || ent->client->NPC_class == CLASS_SWAMPTROOPER - || ent->client->NPC_class == CLASS_TUSKEN - || ent->client->NPC_class == CLASS_BOBAFETT - || ent->client->NPC_class == CLASS_ROCKETTROOPER - || ent->client->NPC_class == CLASS_SABER_DROID - || ent->client->NPC_class == CLASS_ASSASSIN_DROID - || ent->client->NPC_class == CLASS_HAZARD_TROOPER - || ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent->s.weapon == WP_NOGHRI_STICK // assumes user is immune + || ent->client->NPC_class == CLASS_HAZARD_TROOPER || ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_GONK || + ent->client->NPC_class == CLASS_SAND_CREATURE || ent->client->NPC_class == CLASS_INTERROGATOR || ent->client->NPC_class == CLASS_MARK1 || + ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_GALAKMECH || ent->client->NPC_class == CLASS_MOUSE || + ent->client->NPC_class == CLASS_PROBE // droid + || ent->client->NPC_class == CLASS_PROTOCOL // droid + || ent->client->NPC_class == CLASS_R2D2 // droid + || ent->client->NPC_class == CLASS_R5D2 // droid + || ent->client->NPC_class == CLASS_REMOTE || ent->client->NPC_class == CLASS_SEEKER // droid + || ent->client->NPC_class == CLASS_SENTRY || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_TUSKEN || + ent->client->NPC_class == CLASS_BOBAFETT || ent->client->NPC_class == CLASS_ROCKETTROOPER || ent->client->NPC_class == CLASS_SABER_DROID || + ent->client->NPC_class == CLASS_ASSASSIN_DROID || ent->client->NPC_class == CLASS_HAZARD_TROOPER || ent->client->NPC_class == CLASS_VEHICLE) { return qtrue; } return qfalse; } -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern void G_StartRoll( gentity_t *ent, int anim ); -extern void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern void G_StartRoll(gentity_t *ent, int anim); +extern void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt); /* ============ @@ -5484,110 +4256,79 @@ dflags these flags are used to control how T_Damage works DAMAGE_NO_HIT_LOC Damage not based on hit location ============ */ -void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const vec3_t dir, const vec3_t point, int damage, int dflags, int mod, int hitLoc ) -{ - gclient_t *client; - int take; - int asave = 0; - int knockback; - vec3_t newDir; - qboolean alreadyDead = qfalse; +void G_Damage(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const vec3_t dir, const vec3_t point, int damage, int dflags, int mod, int hitLoc) { + gclient_t *client; + int take; + int asave = 0; + int knockback; + vec3_t newDir; + qboolean alreadyDead = qfalse; if (!targ->takedamage) { - if ( targ->client //client - && targ->client->NPC_class == CLASS_SAND_CREATURE//sand creature - && targ->activator//something in our mouth - && targ->activator == inflictor )//inflictor of damage is the thing in our mouth - {//being damaged by the thing in our mouth, allow the damage - } - else - { + if (targ->client // client + && targ->client->NPC_class == CLASS_SAND_CREATURE // sand creature + && targ->activator // something in our mouth + && targ->activator == inflictor) // inflictor of damage is the thing in our mouth + { // being damaged by the thing in our mouth, allow the damage + } else { return; } } - if ( targ->health <= 0 && !targ->client ) - { // allow corpses to be disintegrated - if( mod != MOD_SNIPER || (targ->flags & FL_DISINTEGRATED) ) - return; + if (targ->health <= 0 && !targ->client) { // allow corpses to be disintegrated + if (mod != MOD_SNIPER || (targ->flags & FL_DISINTEGRATED)) + return; } // if we are the player and we are locked to an emplaced gun, we have to reroute damage to the gun....sigh. - if ( targ->s.eFlags & EF_LOCKED_TO_WEAPON - && targ->s.number == 0 - && targ->owner - && !targ->owner->bounceCount //not an EWeb - && !( targ->owner->flags & FL_GODMODE )) - { + if (targ->s.eFlags & EF_LOCKED_TO_WEAPON && targ->s.number == 0 && targ->owner && !targ->owner->bounceCount // not an EWeb + && !(targ->owner->flags & FL_GODMODE)) { // swapping the gun into our place to absorb our damage targ = targ->owner; } - if ( (targ->flags&FL_SHIELDED) && mod != MOD_SABER && !targ->client) - {//magnetically protected, this thing can only be damaged by lightsabers + if ((targ->flags & FL_SHIELDED) && mod != MOD_SABER && !targ->client) { // magnetically protected, this thing can only be damaged by lightsabers return; } - if ( (targ->flags&FL_DMG_BY_SABER_ONLY) && mod != MOD_SABER ) - {//can only be damaged by lightsabers (but no shield... yeah, it's redundant, but whattayagonnado?) + if ((targ->flags & FL_DMG_BY_SABER_ONLY) && + mod != MOD_SABER) { // can only be damaged by lightsabers (but no shield... yeah, it's redundant, but whattayagonnado?) return; } - if (( targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY ) && !( dflags & DAMAGE_HEAVY_WEAP_CLASS )) - { + if ((targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) && !(dflags & DAMAGE_HEAVY_WEAP_CLASS)) { // can only be damaged by an heavy type weapon...but impacting missile was in the heavy weap class...so we just aren't taking damage from this missile return; } - if ( (targ->svFlags&SVF_BBRUSH) - || (!targ->client && Q_stricmp( "misc_model_breakable", targ->classname ) == 0 ) )//FIXME: flag misc_model_breakables? - {//breakable brush or misc_model_breakable - if ( targ->NPC_targetname ) - {//only a certain attacker can destroy this - if ( !attacker - || !attacker->targetname - || Q_stricmp( targ->NPC_targetname, attacker->targetname ) != 0 ) - {//and it's not this one, do nothing + if ((targ->svFlags & SVF_BBRUSH) || (!targ->client && Q_stricmp("misc_model_breakable", targ->classname) == 0)) // FIXME: flag misc_model_breakables? + { // breakable brush or misc_model_breakable + if (targ->NPC_targetname) { // only a certain attacker can destroy this + if (!attacker || !attacker->targetname || Q_stricmp(targ->NPC_targetname, attacker->targetname) != 0) { // and it's not this one, do nothing return; } } } - if ( targ->client && targ->client->NPC_class == CLASS_ATST ) - { + if (targ->client && targ->client->NPC_class == CLASS_ATST) { // extra checks can be done here - if ( mod == MOD_SNIPER - || mod == MOD_DISRUPTOR - || mod == MOD_CONC_ALT ) - { + if (mod == MOD_SNIPER || mod == MOD_DISRUPTOR || mod == MOD_CONC_ALT) { // disruptor does not hurt an atst return; } } - if ( targ->client - && targ->client->NPC_class == CLASS_RANCOR - && (!attacker||!attacker->client||attacker->client->NPC_class!=CLASS_RANCOR) ) - { + if (targ->client && targ->client->NPC_class == CLASS_RANCOR && (!attacker || !attacker->client || attacker->client->NPC_class != CLASS_RANCOR)) { // I guess always do 10 points of damage...feel free to tweak as needed - if ( damage < 10 ) - {//ignore piddly little damage + if (damage < 10) { // ignore piddly little damage damage = 0; - } - else if ( damage >= 10 ) - { + } else if (damage >= 10) { damage = 10; } - } - else if ( mod == MOD_SABER ) - {//sabers do less damage to mark1's and atst's, and to hazard troopers and assassin droids - if ( targ->client ) - { - if ( targ->client->NPC_class == CLASS_ATST - || targ->client->NPC_class == CLASS_MARK1 ) - { + } else if (mod == MOD_SABER) { // sabers do less damage to mark1's and atst's, and to hazard troopers and assassin droids + if (targ->client) { + if (targ->client->NPC_class == CLASS_ATST || targ->client->NPC_class == CLASS_MARK1) { // I guess always do 5 points of damage...feel free to tweak as needed - if ( damage > 5 ) - { + if (damage > 5) { damage = 5; } } @@ -5613,179 +4354,118 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const } } - if ( !inflictor ) { + if (!inflictor) { inflictor = &g_entities[ENTITYNUM_WORLD]; } - if ( !attacker ) { + if (!attacker) { attacker = &g_entities[ENTITYNUM_WORLD]; } // no more weakling allies! -// if ( attacker->s.number != 0 && damage >= 2 && targ->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) -// {//player-helpers do only half damage to enemies -// damage = ceil((float)damage/2.0f); -// } + // if ( attacker->s.number != 0 && damage >= 2 && targ->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) + // {//player-helpers do only half damage to enemies + // damage = ceil((float)damage/2.0f); + // } client = targ->client; - if ( client ) { - if ( client->noclip && !targ->s.number ) { + if (client) { + if (client->noclip && !targ->s.number) { return; } } - if ( mod == MOD_GAS ) - {//certain NPCs are immune - if ( G_ImmuneToGas( targ ) ) - {//immune + if (mod == MOD_GAS) { // certain NPCs are immune + if (G_ImmuneToGas(targ)) { // immune return; } dflags |= DAMAGE_NO_ARMOR; } - if ( dflags&DAMAGE_NO_DAMAGE ) - { + if (dflags & DAMAGE_NO_DAMAGE) { damage = 0; } - if ( dir == NULL ) - { + if (dir == NULL) { dflags |= DAMAGE_NO_KNOCKBACK; - } - else - { - VectorNormalize2( dir, newDir ); + } else { + VectorNormalize2(dir, newDir); } - if ( targ->s.number != 0 ) - {//not the player - if ( (targ->flags&FL_GODMODE) || (targ->flags&FL_UNDYING) ) - {//have god or undying on, so ignore no protection flag + if (targ->s.number != 0) { // not the player + if ((targ->flags & FL_GODMODE) || (targ->flags & FL_UNDYING)) { // have god or undying on, so ignore no protection flag dflags &= ~DAMAGE_NO_PROTECTION; } } - if ( client && PM_InOnGroundAnim( &client->ps )) - { + if (client && PM_InOnGroundAnim(&client->ps)) { dflags |= DAMAGE_NO_KNOCKBACK; } - if ( !attacker->s.number && targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam ) - {//player doesn't do knockback against allies unless he kills them + if (!attacker->s.number && targ->client && attacker->client && + targ->client->playerTeam == attacker->client->playerTeam) { // player doesn't do knockback against allies unless he kills them dflags |= DAMAGE_DEATH_KNOCKBACK; } - if (targ->client && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) ) - { + if (targ->client && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT)) { TIMER_Set(targ, "DEMP2_StunTime", Q_irand(1000, 2000)); } - if ((client) && - (mod==MOD_DEMP2 || mod==MOD_DEMP2_ALT) && - ( - client->NPC_class == CLASS_SABER_DROID || - client->NPC_class == CLASS_ASSASSIN_DROID || - client->NPC_class == CLASS_GONK || - client->NPC_class == CLASS_MOUSE || - client->NPC_class == CLASS_PROBE || - client->NPC_class == CLASS_PROTOCOL || - client->NPC_class == CLASS_R2D2 || - client->NPC_class == CLASS_R5D2 || - client->NPC_class == CLASS_SEEKER || - client->NPC_class == CLASS_INTERROGATOR - ) - ) - { + if ((client) && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && + (client->NPC_class == CLASS_SABER_DROID || client->NPC_class == CLASS_ASSASSIN_DROID || client->NPC_class == CLASS_GONK || + client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_R2D2 || + client->NPC_class == CLASS_R5D2 || client->NPC_class == CLASS_SEEKER || client->NPC_class == CLASS_INTERROGATOR)) { damage *= 7; } - if ( client && client->NPC_class == CLASS_HAZARD_TROOPER ) - { - if ( mod == MOD_SABER - && damage>0 - && !(dflags&DAMAGE_NO_PROTECTION) ) - { + if (client && client->NPC_class == CLASS_HAZARD_TROOPER) { + if (mod == MOD_SABER && damage > 0 && !(dflags & DAMAGE_NO_PROTECTION)) { damage /= 10; } } - if ( client - && client->NPC_class == CLASS_GALAKMECH - && !(dflags&DAMAGE_NO_PROTECTION) ) - {//hit Galak - if ( client->ps.stats[STAT_ARMOR] > 0 ) - {//shields are up - dflags &= ~DAMAGE_NO_ARMOR;//always affect armor - if ( mod == MOD_ELECTROCUTE - || mod == MOD_DEMP2 - || mod == MOD_DEMP2_ALT ) - {//shield protects us from this + if (client && client->NPC_class == CLASS_GALAKMECH && !(dflags & DAMAGE_NO_PROTECTION)) { // hit Galak + if (client->ps.stats[STAT_ARMOR] > 0) { // shields are up + dflags &= ~DAMAGE_NO_ARMOR; // always affect armor + if (mod == MOD_ELECTROCUTE || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { // shield protects us from this damage = 0; } - } - else - {//shields down - if ( mod == MOD_MELEE - || (mod == MOD_CRUSH && attacker && attacker->client) ) - {//Galak takes no impact damage + } else { // shields down + if (mod == MOD_MELEE || (mod == MOD_CRUSH && attacker && attacker->client)) { // Galak takes no impact damage return; } - if ( (dflags & DAMAGE_RADIUS) - || mod == MOD_REPEATER_ALT - || mod == MOD_FLECHETTE_ALT - || mod == MOD_ROCKET - || mod == MOD_ROCKET_ALT - || mod == MOD_CONC - || mod == MOD_THERMAL - || mod == MOD_THERMAL_ALT - || mod == MOD_DETPACK - || mod == MOD_LASERTRIP - || mod == MOD_LASERTRIP_ALT - || mod == MOD_EXPLOSIVE_SPLASH - || mod == MOD_ENERGY_SPLASH - || mod == MOD_SABER ) - {//galak without shields takes quarter damage from explosives and lightsaber - damage = ceil((float)damage/4.0f); + if ((dflags & DAMAGE_RADIUS) || mod == MOD_REPEATER_ALT || mod == MOD_FLECHETTE_ALT || mod == MOD_ROCKET || mod == MOD_ROCKET_ALT || + mod == MOD_CONC || mod == MOD_THERMAL || mod == MOD_THERMAL_ALT || mod == MOD_DETPACK || mod == MOD_LASERTRIP || mod == MOD_LASERTRIP_ALT || + mod == MOD_EXPLOSIVE_SPLASH || mod == MOD_ENERGY_SPLASH || + mod == MOD_SABER) { // galak without shields takes quarter damage from explosives and lightsaber + damage = ceil((float)damage / 4.0f); } } } - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { - if ( client ) - { - if ( client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || - client->NPC_class == CLASS_R2D2 || client->NPC_class == CLASS_R5D2 || - client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { + if (client) { + if (client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || client->NPC_class == CLASS_R2D2 || + client->NPC_class == CLASS_R5D2 || client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK) { // DEMP2 does more damage to these guys. damage *= 2; - } - else if ( client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || - client->NPC_class == CLASS_MARK1 || client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || - client->NPC_class == CLASS_ATST ) - { + } else if (client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || client->NPC_class == CLASS_MARK1 || + client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || client->NPC_class == CLASS_ATST) { // DEMP2 does way more damage to these guys. damage *= 5; } - } - else if ( targ->s.weapon == WP_TURRET ) - { - damage *= 6;// more damage to turret things + } else if (targ->s.weapon == WP_TURRET) { + damage *= 6; // more damage to turret things } } - if (targ - && targ->client - && !(dflags&DAMAGE_NO_PROTECTION) - && !(dflags&DAMAGE_DIE_ON_IMPACT) )//falling to you death ignores force protect and force rage (but obeys godmode and undying flags) - {//force protections - //rage - if ( (targ->client->ps.forcePowersActive & (1 << FP_RAGE))) - { - damage = floor((float)damage/(float)(targ->client->ps.forcePowerLevel[FP_RAGE]*2)); + if (targ && targ->client && !(dflags & DAMAGE_NO_PROTECTION) && + !(dflags & DAMAGE_DIE_ON_IMPACT)) // falling to you death ignores force protect and force rage (but obeys godmode and undying flags) + { // force protections + // rage + if ((targ->client->ps.forcePowersActive & (1 << FP_RAGE))) { + damage = floor((float)damage / (float)(targ->client->ps.forcePowerLevel[FP_RAGE] * 2)); } - //protect - if ( (targ->client->ps.forcePowersActive & (1 << FP_PROTECT)) ) - { + // protect + if ((targ->client->ps.forcePowersActive & (1 << FP_PROTECT))) { /* qboolean doSound = qfalse; switch ( targ->client->ps.forcePowerLevel[FP_PROTECT] ) @@ -5851,20 +4531,13 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const break; } */ - //New way: just cut all physical damage by force level - if ( mod == MOD_FALLING - && targ->NPC - && (targ->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//if falling to your death, protect can't save you - } - else - { + // New way: just cut all physical damage by force level + if (mod == MOD_FALLING && targ->NPC && (targ->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // if falling to your death, protect can't save you + } else { qboolean doSound = qfalse; - switch ( mod ) - { + switch (mod) { case MOD_CRUSH: - if ( attacker && attacker->client ) - {//need to still be crushed by AT-ST + if (attacker && attacker->client) { // need to still be crushed by AT-ST break; } case MOD_REPEATER_ALT: @@ -5902,64 +4575,50 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const case MOD_LAVA: case MOD_FALLING: case MOD_MELEE: - doSound = (qboolean)(Q_irand(0,4)==0); - switch ( targ->client->ps.forcePowerLevel[FP_PROTECT] ) - { + doSound = (qboolean)(Q_irand(0, 4) == 0); + switch (targ->client->ps.forcePowerLevel[FP_PROTECT]) { case FORCE_LEVEL_4: - //je suis invincible!!! - if ( targ->client - && attacker->client - && targ->client->playerTeam == attacker->client->playerTeam - && (!targ->NPC || !targ->NPC->charmedTime) ) - {//complain, but don't turn on them - G_FriendlyFireReaction( targ, attacker, dflags ); + // je suis invincible!!! + if (targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam && + (!targ->NPC || !targ->NPC->charmedTime)) { // complain, but don't turn on them + G_FriendlyFireReaction(targ, attacker, dflags); } return; break; case FORCE_LEVEL_3: - //one-tenth damage - if ( damage <= 1 ) - { + // one-tenth damage + if (damage <= 1) { damage = 0; - } - else - { - damage = ceil((float)damage*0.25f);//was 0.1f); + } else { + damage = ceil((float)damage * 0.25f); // was 0.1f); } break; case FORCE_LEVEL_2: - //half damage - if ( damage <= 1 ) - { + // half damage + if (damage <= 1) { damage = 0; - } - else - { - damage = ceil((float)damage*0.5f); + } else { + damage = ceil((float)damage * 0.5f); } break; case FORCE_LEVEL_1: - //three-quarters damage - if ( damage <= 1 ) - { + // three-quarters damage + if (damage <= 1) { damage = 0; - } - else - { - damage = ceil((float)damage*0.75f); + } else { + damage = ceil((float)damage * 0.75f); } break; } break; } - if ( doSound ) - { - //make protect sound - G_SoundOnEnt( targ, CHAN_ITEM, "sound/weapons/force/protecthit.wav" ); + if (doSound) { + // make protect sound + G_SoundOnEnt(targ, CHAN_ITEM, "sound/weapons/force/protecthit.wav"); } } } - //absorb + // absorb /* if ( (targ->client->ps.forcePowersActive & (1 << FP_ABSORB)) ) { @@ -5985,92 +4644,66 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const knockback = damage; - //Attempt to apply extra knockback - if ( dflags & DAMAGE_EXTRA_KNOCKBACK ) - { + // Attempt to apply extra knockback + if (dflags & DAMAGE_EXTRA_KNOCKBACK) { knockback *= 2; } - if ( knockback > 200 ) { + if (knockback > 200) { knockback = 200; } - if ( targ->client - && (targ->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_3 ) - {//pretend there was no damage? + if (targ->client && (targ->client->ps.forcePowersActive & (1 << FP_PROTECT)) && + targ->client->ps.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_3) { // pretend there was no damage? knockback = 0; - } - else if ( mod == MOD_CRUSH ) - { + } else if (mod == MOD_CRUSH) { knockback = 0; - } - else if ( targ->flags & FL_NO_KNOCKBACK ) - { + } else if (targ->flags & FL_NO_KNOCKBACK) { knockback = 0; - } - else if ( targ->NPC - && targ->NPC->jumpState == JS_JUMPING ) - { + } else if (targ->NPC && targ->NPC->jumpState == JS_JUMPING) { knockback = 0; - } - else if ( attacker->s.number >= MAX_CLIENTS//an NPC fired - && targ->client //hit a client - && attacker->client //attacker is a client - && targ->client->playerTeam == attacker->client->playerTeam )//on same team - {//crap, ignore knockback + } else if (attacker->s.number >= MAX_CLIENTS // an NPC fired + && targ->client // hit a client + && attacker->client // attacker is a client + && targ->client->playerTeam == attacker->client->playerTeam) // on same team + { // crap, ignore knockback knockback = 0; - } - else if ( dflags & DAMAGE_NO_KNOCKBACK ) - { + } else if (dflags & DAMAGE_NO_KNOCKBACK) { knockback = 0; } - if ( (dflags&DAMAGE_SABER_KNOCKBACK1) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK1)) { + if (attacker && attacker->client) { knockback *= attacker->client->ps.saber[0].knockbackScale; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK1_B2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK1_B2)) { + if (attacker && attacker->client) { knockback *= attacker->client->ps.saber[0].knockbackScale2; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK2)) { + if (attacker && attacker->client) { knockback *= attacker->client->ps.saber[1].knockbackScale; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK2_B2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK2_B2)) { + if (attacker && attacker->client) { knockback *= attacker->client->ps.saber[1].knockbackScale2; } } // figure momentum add, even if the damage won't be taken - if ( knockback && !(dflags&DAMAGE_DEATH_KNOCKBACK) ) //&& targ->client + if (knockback && !(dflags & DAMAGE_DEATH_KNOCKBACK)) //&& targ->client { - G_ApplyKnockback( targ, newDir, knockback ); - G_CheckKnockdown( targ, attacker, newDir, dflags, mod ); + G_ApplyKnockback(targ, newDir, knockback); + G_CheckKnockdown(targ, attacker, newDir, dflags, mod); } // check for godmode, completely getting out of the damage - if ( ( (targ->flags&FL_GODMODE) || (targ->client&&targ->client->ps.powerups[PW_INVINCIBLE]>level.time) ) - && !(dflags&DAMAGE_NO_PROTECTION) ) - { - if ( targ->client - && attacker->client - && targ->client->playerTeam == attacker->client->playerTeam - && (!targ->NPC || !targ->NPC->charmedTime) ) - {//complain, but don't turn on them - G_FriendlyFireReaction( targ, attacker, dflags ); + if (((targ->flags & FL_GODMODE) || (targ->client && targ->client->ps.powerups[PW_INVINCIBLE] > level.time)) && !(dflags & DAMAGE_NO_PROTECTION)) { + if (targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam && + (!targ->NPC || !targ->NPC->charmedTime)) { // complain, but don't turn on them + G_FriendlyFireReaction(targ, attacker, dflags); } return; } @@ -6109,18 +4742,18 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const */ // add to the attacker's hit counter - if ( attacker->client && targ != attacker && targ->health > 0 ) { - if ( OnSameTeam( targ, attacker ) ) { -// attacker->client->ps.persistant[PERS_HITS] -= damage; + if (attacker->client && targ != attacker && targ->health > 0) { + if (OnSameTeam(targ, attacker)) { + // attacker->client->ps.persistant[PERS_HITS] -= damage; } else { -// attacker->client->ps.persistant[PERS_HITS] += damage; + // attacker->client->ps.persistant[PERS_HITS] += damage; } } take = damage; - //FIXME: Do not use this method of difficulty changing - // Scale the amount of damage given to the player based on the skill setting + // FIXME: Do not use this method of difficulty changing + // Scale the amount of damage given to the player based on the skill setting /* if ( targ->s.number == 0 && targ != attacker ) { @@ -6131,44 +4764,35 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const take = 1; } */ - if ( client ) - { - //don't lose armor if on same team - // save some from armor - asave = CheckArmor (targ, take, dflags, mod); - if ( !asave ) - {//nothing was absorbed (or just ran out?) - } - else if ( targ->client->NPC_class != CLASS_VEHICLE ) - {//vehicles don't have personal shields + if (client) { + // don't lose armor if on same team + // save some from armor + asave = CheckArmor(targ, take, dflags, mod); + if (!asave) { // nothing was absorbed (or just ran out?) + } else if (targ->client->NPC_class != CLASS_VEHICLE) { // vehicles don't have personal shields targ->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; - if ( targ->client->ps.stats[STAT_ARMOR] <= 0 ) - {//all out of armor - //remove Galak's shield + if (targ->client->ps.stats[STAT_ARMOR] <= 0) { // all out of armor + // remove Galak's shield targ->client->ps.powerups[PW_BATTLESUIT] = 0; } } - if (mod==MOD_SLIME || mod==MOD_LAVA) - { + if (mod == MOD_SLIME || mod == MOD_LAVA) { // Hazard Troopers Don't Mind Acid Rain - if (targ->client->NPC_class == CLASS_HAZARD_TROOPER - && !(dflags&DAMAGE_NO_PROTECTION) ) - { + if (targ->client->NPC_class == CLASS_HAZARD_TROOPER && !(dflags & DAMAGE_NO_PROTECTION)) { take = 0; } - if (mod==MOD_SLIME) - { - trace_t testTrace; - vec3_t testDirection; - vec3_t testStartPos; - vec3_t testEndPos; - //int numPuffs = Q_irand(1, 2); + if (mod == MOD_SLIME) { + trace_t testTrace; + vec3_t testDirection; + vec3_t testStartPos; + vec3_t testEndPos; + // int numPuffs = Q_irand(1, 2); - //for (int i=0; icurrentOrigin, 60.0f, testDirection, testStartPos); @@ -6177,16 +4801,12 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const testEndPos[1] += (Q_flrand(0.0f, 1.0f) * 8.0f) - 4.0f; testEndPos[2] += (Q_flrand(0.0f, 1.0f) * 8.0f); - gi.trace (&testTrace, testStartPos, NULL, NULL, testEndPos, ENTITYNUM_NONE, MASK_SHOT, G2_COLLIDE, 0); + gi.trace(&testTrace, testStartPos, NULL, NULL, testEndPos, ENTITYNUM_NONE, MASK_SHOT, G2_COLLIDE, 0); - if (!testTrace.startsolid && - !testTrace.allsolid && - testTrace.entityNum==targ->s.number && - testTrace.G2CollisionMap[0].mEntityNum!=-1) - { - G_PlayEffect( "world/acid_fizz", testTrace.G2CollisionMap[0].mCollisionPosition ); + if (!testTrace.startsolid && !testTrace.allsolid && testTrace.entityNum == targ->s.number && testTrace.G2CollisionMap[0].mEntityNum != -1) { + G_PlayEffect("world/acid_fizz", testTrace.G2CollisionMap[0].mCollisionPosition); } -// CG_DrawEdge(testStartPos, testEndPos, EDGE_IMPACT_POSSIBLE); + // CG_DrawEdge(testStartPos, testEndPos, EDGE_IMPACT_POSSIBLE); float chanceOfFizz = gi.WE_GetChanceOfSaberFizz(); TIMER_Set(targ, "AcidPainDebounce", 200 + (10000.0f * Q_flrand(0.0f, 1.0f) * chanceOfFizz)); hitLoc = HL_CHEST; @@ -6196,529 +4816,423 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const take -= asave; - if ( targ->client->NPC_class == CLASS_VEHICLE ) - { - if ( targ->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + if (targ->client->NPC_class == CLASS_VEHICLE) { + if (targ->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { //((CVehicleNPC *)targ->NPC)->m_ulFlags |= CVehicleNPC::VEH_BUCKING; } - if ( (damage > 0) && // Actually took some damage - (mod!=MOD_SABER) && // and damage didn't come from a saber - (targ->m_pVehicle->m_pVehicleInfo->type==VH_SPEEDER) && // and is a speeder - // (targ->client->ps.speed > 30.0f) && // and is moving - (attacker) && // and there is an attacker - (attacker->client) && // who is a client - (attacker->s.number 0) && // Actually took some damage + (mod != MOD_SABER) && // and damage didn't come from a saber + (targ->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) && // and is a speeder + // (targ->client->ps.speed > 30.0f) && // and is moving + (attacker) && // and there is an attacker + (attacker->client) && // who is a client + (attacker->s.number < MAX_CLIENTS) && // who is the player + (G_IsRidingVehicle(attacker)) // who is riding a bike + ) { + vec3_t vehFwd; + vec3_t actorFwd; AngleVectors(targ->currentAngles, actorFwd, 0, 0); - - Vehicle_t* pVeh = G_IsRidingVehicle(attacker); + Vehicle_t *pVeh = G_IsRidingVehicle(attacker); VectorCopy(pVeh->m_pParentEntity->client->ps.velocity, vehFwd); VectorNormalize(vehFwd); - if (DotProduct(vehFwd, actorFwd)>0.5) - { + if (DotProduct(vehFwd, actorFwd) > 0.5) { damage *= 10.0f; } } - if ( (damage > 0) && // Actually took some damage - (mod==MOD_SABER) && // If Attacked By A Saber - (targ->m_pVehicle->m_pVehicleInfo->type==VH_SPEEDER) && // and is a speeder - !(targ->m_pVehicle->m_ulFlags & VEH_OUTOFCONTROL) && // and is not already spinning - (targ->client->ps.speed > 30.0f) && // and is moving - (attacker==inflictor || Q_irand(0, 30)==0) // and EITHER saber is held, or 1 in 30 chance of hitting when thrown - ) - { - Vehicle_t* pVeh = targ->m_pVehicle; - gentity_t* parent = pVeh->m_pParentEntity; - float CurSpeed = VectorLength(parent->client->ps.velocity); - pVeh->m_iArmor = 0; // Remove all remaining Armor + if ((damage > 0) && // Actually took some damage + (mod == MOD_SABER) && // If Attacked By A Saber + (targ->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) && // and is a speeder + !(targ->m_pVehicle->m_ulFlags & VEH_OUTOFCONTROL) && // and is not already spinning + (targ->client->ps.speed > 30.0f) && // and is moving + (attacker == inflictor || Q_irand(0, 30) == 0) // and EITHER saber is held, or 1 in 30 chance of hitting when thrown + ) { + Vehicle_t *pVeh = targ->m_pVehicle; + gentity_t *parent = pVeh->m_pParentEntity; + float CurSpeed = VectorLength(parent->client->ps.velocity); + pVeh->m_iArmor = 0; // Remove all remaining Armor pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 10000); - pVeh->m_ulFlags |= (VEH_OUTOFCONTROL|VEH_SPINNING); + pVeh->m_ulFlags |= (VEH_OUTOFCONTROL | VEH_SPINNING); VectorScale(parent->client->ps.velocity, 1.25f, parent->pos3); - if (CurSpeedm_pVehicleInfo->speedMax) - { + if (CurSpeed < pVeh->m_pVehicleInfo->speedMax) { VectorNormalize(parent->pos3); - if (CurSpeedm_pVehicleInfo->speedMax) - { + if (CurSpeed < pVeh->m_pVehicleInfo->speedMax) { VectorNormalize(parent->pos3); - if (fabsf(parent->pos3[2])<0.25f) - { + if (fabsf(parent->pos3[2]) < 0.25f) { VectorScale(parent->pos3, (pVeh->m_pVehicleInfo->speedMax * 1.25f), parent->pos3); - } - else - { + } else { VectorScale(parent->client->ps.velocity, 1.25f, parent->pos3); } } } - // TODO: Play Huge Spark Effect & Start Rolling Sound - if (attacker==inflictor && (!G_IsRidingVehicle(attacker) || Q_irand(0, 3)==0)) - { - attacker->lastEnemy = targ; - G_StartMatrixEffect(attacker, MEF_LOOK_AT_ENEMY|MEF_NO_RANGEVAR|MEF_NO_VERTBOB|MEF_NO_SPIN, 1000); - if (!G_IsRidingVehicle(attacker)) - { - G_StartRoll(attacker, (Q_irand(0,1)==0)?(BOTH_ROLL_L):(BOTH_ROLL_R)); + if (attacker == inflictor && (!G_IsRidingVehicle(attacker) || Q_irand(0, 3) == 0)) { + attacker->lastEnemy = targ; + G_StartMatrixEffect(attacker, MEF_LOOK_AT_ENEMY | MEF_NO_RANGEVAR | MEF_NO_VERTBOB | MEF_NO_SPIN, 1000); + if (!G_IsRidingVehicle(attacker)) { + G_StartRoll(attacker, (Q_irand(0, 1) == 0) ? (BOTH_ROLL_L) : (BOTH_ROLL_R)); } } - if (targ->m_pVehicle->m_pPilot && targ->m_pVehicle->m_pPilot->s.number>=MAX_CLIENTS) - { - G_SoundOnEnt(targ->m_pVehicle->m_pPilot, CHAN_VOICE, "*falling1.wav" ); + if (targ->m_pVehicle->m_pPilot && targ->m_pVehicle->m_pPilot->s.number >= MAX_CLIENTS) { + G_SoundOnEnt(targ->m_pVehicle->m_pPilot, CHAN_VOICE, "*falling1.wav"); } - - // DISMEMBER THE FRONT PART OF THE MODEL { - trace_t trace; + trace_t trace; gentity_t *limb = G_Spawn(); - // Setup Basic Limb Entity Properties //------------------------------------ - limb->s.radius = 60; - limb->s.eType = ET_THINKER; - limb->s.eFlags |= EF_BOUNCE_HALF; - limb->classname = "limb"; - limb->owner = targ; - limb->enemy = targ->enemy; - limb->svFlags = SVF_USE_CURRENT_ORIGIN; - limb->playerModel = 0; - limb->clipmask = MASK_SOLID; - limb->contents = CONTENTS_CORPSE; + limb->s.radius = 60; + limb->s.eType = ET_THINKER; + limb->s.eFlags |= EF_BOUNCE_HALF; + limb->classname = "limb"; + limb->owner = targ; + limb->enemy = targ->enemy; + limb->svFlags = SVF_USE_CURRENT_ORIGIN; + limb->playerModel = 0; + limb->clipmask = MASK_SOLID; + limb->contents = CONTENTS_CORPSE; limb->e_clThinkFunc = clThinkF_CG_Limb; - limb->e_ThinkFunc = thinkF_LimbThink; - limb->nextthink = level.time + FRAMETIME; + limb->e_ThinkFunc = thinkF_LimbThink; + limb->nextthink = level.time + FRAMETIME; limb->physicsBounce = 0.2f; - limb->craniumBone = targ->craniumBone; - limb->cervicalBone = targ->cervicalBone; - limb->thoracicBone = targ->thoracicBone; + limb->craniumBone = targ->craniumBone; + limb->cervicalBone = targ->cervicalBone; + limb->thoracicBone = targ->thoracicBone; limb->upperLumbarBone = targ->upperLumbarBone; limb->lowerLumbarBone = targ->lowerLumbarBone; - limb->hipsBone = targ->hipsBone; - limb->rootBone = targ->rootBone; - + limb->hipsBone = targ->hipsBone; + limb->rootBone = targ->rootBone; // Calculate The Location Of The New Limb //---------------------------------------- - G_SetOrigin( limb, targ->currentOrigin ); - - VectorCopy( targ->currentOrigin, limb->s.pos.trBase ); - VectorSet( limb->mins, -3.0f, -3.0f, -6.0f ); - VectorSet( limb->maxs, 3.0f, 3.0f, 6.0f ); - VectorCopy( targ->s.modelScale, limb->s.modelScale ); + G_SetOrigin(limb, targ->currentOrigin); + VectorCopy(targ->currentOrigin, limb->s.pos.trBase); + VectorSet(limb->mins, -3.0f, -3.0f, -6.0f); + VectorSet(limb->maxs, 3.0f, 3.0f, 6.0f); + VectorCopy(targ->s.modelScale, limb->s.modelScale); - - - //copy the g2 instance of the victim into the limb + // copy the g2 instance of the victim into the limb //------------------------------------------------- - gi.G2API_CopyGhoul2Instance(targ->ghoul2, limb->ghoul2, -1); + gi.G2API_CopyGhoul2Instance(targ->ghoul2, limb->ghoul2, -1); gi.G2API_SetRootSurface(limb->ghoul2, limb->playerModel, "lfront"); gi.G2API_SetSurfaceOnOff(&targ->ghoul2[targ->playerModel], "lfront", TURN_OFF); animation_t *animations = level.knownAnimFileSets[targ->client->clientInfo.animFileIndex].animations; - //play the proper dismember anim on the limb + // play the proper dismember anim on the limb gi.G2API_SetBoneAnim(&limb->ghoul2[limb->playerModel], 0, animations[BOTH_A1_BL_TR].firstFrame, - animations[BOTH_A1_BL_TR].numFrames + animations[BOTH_A1_BL_TR].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE, 1, level.time, -1, -1 ); - + animations[BOTH_A1_BL_TR].numFrames + animations[BOTH_A1_BL_TR].firstFrame, BONE_ANIM_OVERRIDE_FREEZE, 1, level.time, + -1, -1); // Check For Start In Solid //-------------------------- - gi.linkentity( limb ); - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - if ( trace.startsolid ) - { + gi.linkentity(limb); + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] -= limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - if ( trace.startsolid ) - { + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] += limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, 0 ); - + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, (EG2_Collision)0, + 0); } } // If Started In Solid, Remove //----------------------------- - if ( trace.startsolid ) - { - G_FreeEntity( limb ); + if (trace.startsolid) { + G_FreeEntity(limb); } // Otherwise, Send It Flying //--------------------------- - else - { - VectorCopy( limb->s.pos.trBase, limb->currentOrigin ); - VectorScale( targ->client->ps.velocity, 1.0f, limb->s.pos.trDelta ); - limb->s.pos.trType = TR_GRAVITY; - limb->s.pos.trTime = level.time; - - VectorCopy( targ->currentAngles, limb->s.apos.trBase ); - VectorClear( limb->s.apos.trDelta ); - limb->s.apos.trTime = level.time; - limb->s.apos.trType = TR_LINEAR; - limb->s.apos.trDelta[0] = Q_irand( -300, 300 ); - limb->s.apos.trDelta[1] = Q_irand( -800, 800 ); - - gi.linkentity( limb ); + else { + VectorCopy(limb->s.pos.trBase, limb->currentOrigin); + VectorScale(targ->client->ps.velocity, 1.0f, limb->s.pos.trDelta); + limb->s.pos.trType = TR_GRAVITY; + limb->s.pos.trTime = level.time; + + VectorCopy(targ->currentAngles, limb->s.apos.trBase); + VectorClear(limb->s.apos.trDelta); + limb->s.apos.trTime = level.time; + limb->s.apos.trType = TR_LINEAR; + limb->s.apos.trDelta[0] = Q_irand(-300, 300); + limb->s.apos.trDelta[1] = Q_irand(-800, 800); + + gi.linkentity(limb); } } } targ->m_pVehicle->m_iShields = targ->client->ps.stats[STAT_ARMOR]; targ->m_pVehicle->m_iArmor -= take; - if ( targ->m_pVehicle->m_iArmor < 0 ) - { + if (targ->m_pVehicle->m_iArmor < 0) { targ->m_pVehicle->m_iArmor = 0; } - if ( ( targ->m_pVehicle->m_iArmor <= 0 ) - && targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - {//vehicle all out of armor + if ((targ->m_pVehicle->m_iArmor <= 0) && targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { // vehicle all out of armor Vehicle_t *pVeh = targ->m_pVehicle; - if (dflags&DAMAGE_IMPACT_DIE) - { + if (dflags & DAMAGE_IMPACT_DIE) { // kill it now - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, -1/* -1 causes instant death */ ); - } - else - { - if ( pVeh->m_iDieTime == 0 ) - {//just start the flaming effect and explosion delay, if it's not going already... - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, Q_irand( 4000, 5500 ) ); + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, -1 /* -1 causes instant death */); + } else { + if (pVeh->m_iDieTime == 0) { // just start the flaming effect and explosion delay, if it's not going already... + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, Q_irand(4000, 5500)); } } - } - else if (targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) - { + } else if (targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { take = 0; } } } - if ( !(dflags&DAMAGE_NO_HIT_LOC) || !(dflags&DAMAGE_RADIUS)) - { - if ( !G_NonLocationSpecificDamage( mod ) ) - {//certain kinds of damage don't care about hitlocation - take = ceil( (float)take*damageModifier[hitLoc] ); + if (!(dflags & DAMAGE_NO_HIT_LOC) || !(dflags & DAMAGE_RADIUS)) { + if (!G_NonLocationSpecificDamage(mod)) { // certain kinds of damage don't care about hitlocation + take = ceil((float)take * damageModifier[hitLoc]); } } - if ( g_debugDamage->integer ) { - gi.Printf( "[%d]client:%i health:%i damage:%i armor:%i hitloc:%s\n", level.time, targ->s.number, targ->health, take, asave, hitLocName[hitLoc] ); + if (g_debugDamage->integer) { + gi.Printf("[%d]client:%i health:%i damage:%i armor:%i hitloc:%s\n", level.time, targ->s.number, targ->health, take, asave, hitLocName[hitLoc]); } // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame - if ( client ) { - client->ps.persistant[PERS_ATTACKER] = attacker->s.number; //attack can be the world ent + if (client) { + client->ps.persistant[PERS_ATTACKER] = attacker->s.number; // attack can be the world ent client->damage_armor += asave; client->damage_blood += take; - if ( dir ) { //can't check newdir since it's local, newdir is dir normalized - VectorCopy ( newDir, client->damage_from ); + if (dir) { // can't check newdir since it's local, newdir is dir normalized + VectorCopy(newDir, client->damage_from); client->damage_fromWorld = false; } else { - VectorCopy ( targ->currentOrigin, client->damage_from ); + VectorCopy(targ->currentOrigin, client->damage_from); client->damage_fromWorld = true; } } // do the damage - if ( targ->health <= 0 ) - { + if (targ->health <= 0) { alreadyDead = qtrue; } // Undying If: //-------------------------------------------------------------------------- - qboolean targUndying = (qboolean)( - !alreadyDead && - !(dflags & DAMAGE_NO_PROTECTION) && - ((targ->flags&FL_UNDYING) || - (dflags&DAMAGE_NO_KILL) || - ((targ->client) && - (targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && - !(dflags&DAMAGE_NO_PROTECTION) && - !(dflags&DAMAGE_DIE_ON_IMPACT)))); - - if ( targ->client - && targ->client->NPC_class == CLASS_WAMPA - && targ->count - && take >= targ->health ) - {//wampa holding someone, don't die unless you can release them! + qboolean targUndying = (qboolean)(!alreadyDead && !(dflags & DAMAGE_NO_PROTECTION) && + ((targ->flags & FL_UNDYING) || (dflags & DAMAGE_NO_KILL) || + ((targ->client) && (targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && !(dflags & DAMAGE_NO_PROTECTION) && + !(dflags & DAMAGE_DIE_ON_IMPACT)))); + + if (targ->client && targ->client->NPC_class == CLASS_WAMPA && targ->count && + take >= targ->health) { // wampa holding someone, don't die unless you can release them! qboolean removeArm = qfalse; - if ( targ->activator - && attacker == targ->activator - && mod == MOD_SABER ) - { + if (targ->activator && attacker == targ->activator && mod == MOD_SABER) { removeArm = qtrue; } - if ( Wampa_CheckDropVictim( targ, qtrue ) ) - {//released our victim - if ( removeArm ) - { + if (Wampa_CheckDropVictim(targ, qtrue)) { // released our victim + if (removeArm) { targ->client->dismembered = false; - //FIXME: the limb should just disappear, cuz I ate it - G_DoDismemberment( targ, targ->currentOrigin, MOD_SABER, 1000, HL_ARM_RT, qtrue ); + // FIXME: the limb should just disappear, cuz I ate it + G_DoDismemberment(targ, targ->currentOrigin, MOD_SABER, 1000, HL_ARM_RT, qtrue); } - } - else - {//couldn't release him + } else { // couldn't release him targUndying = qtrue; } } - if ( attacker && attacker->client && !attacker->s.number ) - { - if ( !alreadyDead ) - { + if (attacker && attacker->client && !attacker->s.number) { + if (!alreadyDead) { int add; - if ( take > targ->health ) - { + if (take > targ->health) { add = targ->health; - } - else - { + } else { add = take; } add += asave; - add = ceil(add/10.0f); - if ( attacker != targ ) - { - G_TrackWeaponUsage( attacker, inflictor, add, mod ); + add = ceil(add / 10.0f); + if (attacker != targ) { + G_TrackWeaponUsage(attacker, inflictor, add, mod); } } } - if ( take || (dflags&DAMAGE_NO_DAMAGE) ) - { - if ( !targ->client || !attacker->client ) - { + if (take || (dflags & DAMAGE_NO_DAMAGE)) { + if (!targ->client || !attacker->client) { targ->health = targ->health - take; - if (targ->health < 0) - { + if (targ->health < 0) { targ->health = 0; } - if ( targUndying ) - { - if(targ->health < 1) - { - G_ActivateBehavior( targ, BSET_DEATH ); + if (targUndying) { + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } } - } - else - {//two clients - team_t targTeam = TEAM_FREE; - team_t attackerTeam = TEAM_FREE; + } else { // two clients + team_t targTeam = TEAM_FREE; + team_t attackerTeam = TEAM_FREE; - if ( player->client->ps.viewEntity && targ->s.number == player->client->ps.viewEntity ) - { + if (player->client->ps.viewEntity && targ->s.number == player->client->ps.viewEntity) { targTeam = player->client->playerTeam; - } - else if ( targ->client ) { + } else if (targ->client) { targTeam = targ->client->playerTeam; - } - else { + } else { targTeam = targ->noDamageTeam; } - // if ( targTeam == TEAM_DISGUISE ) { - // targTeam = TEAM_PLAYER; - // } - if ( player->client->ps.viewEntity && attacker->s.number == player->client->ps.viewEntity ) - { + // if ( targTeam == TEAM_DISGUISE ) { + // targTeam = TEAM_PLAYER; + // } + if (player->client->ps.viewEntity && attacker->s.number == player->client->ps.viewEntity) { attackerTeam = player->client->playerTeam; - } - else if ( attacker->client ) { + } else if (attacker->client) { attackerTeam = attacker->client->playerTeam; - } - else { + } else { attackerTeam = attacker->noDamageTeam; } - // if ( attackerTeam == TEAM_DISGUISE ) { - // attackerTeam = TEAM_PLAYER; - // } + // if ( attackerTeam == TEAM_DISGUISE ) { + // attackerTeam = TEAM_PLAYER; + // } - if ( targTeam != attackerTeam - || (targ->s.number < MAX_CLIENTS && targTeam == TEAM_FREE)//evil player hit - || (attacker && attacker->s.number < MAX_CLIENTS && attackerTeam == TEAM_FREE) )//evil player attacked - {//on opposite team + if (targTeam != attackerTeam || (targ->s.number < MAX_CLIENTS && targTeam == TEAM_FREE) // evil player hit + || (attacker && attacker->s.number < MAX_CLIENTS && attackerTeam == TEAM_FREE)) // evil player attacked + { // on opposite team targ->health = targ->health - take; - //MCG - Falling should never kill player- only if a trigger_hurt does so. - if ( mod == MOD_FALLING && targ->s.number == 0 && targ->health < 1 ) - { + // MCG - Falling should never kill player- only if a trigger_hurt does so. + if (mod == MOD_FALLING && targ->s.number == 0 && targ->health < 1) { targ->health = 1; - } - else if (targ->health < 0) - { + } else if (targ->health < 0) { targ->health = 0; } - if (targUndying) - { - if ( targ->health < 1 ) - { - if ( targ->NPC == NULL || !(targ->NPC->aiFlags&NPCAI_ROSH) || !Rosh_TwinPresent( targ ) ) - {//NOTE: Rosh won't run his deathscript until he doesn't have the twins to heal him - G_ActivateBehavior( targ, BSET_DEATH ); + if (targUndying) { + if (targ->health < 1) { + if (targ->NPC == NULL || !(targ->NPC->aiFlags & NPCAI_ROSH) || + !Rosh_TwinPresent(targ)) { // NOTE: Rosh won't run his deathscript until he doesn't have the twins to heal him + G_ActivateBehavior(targ, BSET_DEATH); } targ->health = 1; } - } - else if ( targ->health < 1 && attacker->client ) - { // The player or NPC just killed an enemy so increment the kills counter + } else if (targ->health < 1 && attacker->client) { // The player or NPC just killed an enemy so increment the kills counter attacker->client->ps.persistant[PERS_ENEMIES_KILLED]++; } - } - else if ( targTeam == TEAM_PLAYER ) - {//on the same team, and target is an ally + } else if (targTeam == TEAM_PLAYER) { // on the same team, and target is an ally qboolean takeDamage = qtrue; qboolean yellAtAttacker = qtrue; - //1) player doesn't take damage from teammates unless they're angry at him - if ( targ->s.number == 0 ) - {//the player - if ( attacker->enemy != targ && attacker != targ ) - {//an NPC shot the player by accident + // 1) player doesn't take damage from teammates unless they're angry at him + if (targ->s.number == 0) { // the player + if (attacker->enemy != targ && attacker != targ) { // an NPC shot the player by accident takeDamage = qfalse; } } - //2) NPCs don't take any damage from player during combat - else - {//an NPC - if ( ((dflags & DAMAGE_RADIUS)) && !(dflags&DAMAGE_IGNORE_TEAM) ) - {//An NPC got hit by player and this is during combat or it was slash damage - //NOTE: though it's not realistic to have teammates not take splash damage, + // 2) NPCs don't take any damage from player during combat + else { // an NPC + if (((dflags & DAMAGE_RADIUS)) && + !(dflags & DAMAGE_IGNORE_TEAM)) { // An NPC got hit by player and this is during combat or it was slash damage + // NOTE: though it's not realistic to have teammates not take splash damage, // even when not in combat, it feels really bad to have them able to // actually be killed by the player's splash damage takeDamage = qfalse; } - if ( (dflags & DAMAGE_RADIUS) ) - {//you're fighting and it's just radius damage, so don't even mention it + if ((dflags & DAMAGE_RADIUS)) { // you're fighting and it's just radius damage, so don't even mention it yellAtAttacker = qfalse; } } - if ( takeDamage ) - { + if (takeDamage) { targ->health = targ->health - take; - if ( !alreadyDead && ((((targ->flags&FL_UNDYING)||targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && !(dflags&DAMAGE_NO_PROTECTION) && attacker->s.number != 0) || (dflags&DAMAGE_NO_KILL) ) ) - {//guy is marked undying and we're not the player or we're in combat - if ( targ->health < 1 ) - { - G_ActivateBehavior( targ, BSET_DEATH ); + if (!alreadyDead && ((((targ->flags & FL_UNDYING) || targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && + !(dflags & DAMAGE_NO_PROTECTION) && attacker->s.number != 0) || + (dflags & DAMAGE_NO_KILL))) { // guy is marked undying and we're not the player or we're in combat + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } - } - else if ( !alreadyDead && ((((targ->flags&FL_UNDYING)||targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && !(dflags&DAMAGE_NO_PROTECTION) && !attacker->s.number && !targ->s.number) || (dflags&DAMAGE_NO_KILL)) ) - {// player is undying and he's attacking himself, don't let him die - if ( targ->health < 1 ) - { - G_ActivateBehavior( targ, BSET_DEATH ); + } else if (!alreadyDead && ((((targ->flags & FL_UNDYING) || targ->client->ps.forcePowersActive & (1 << FP_RAGE)) && + !(dflags & DAMAGE_NO_PROTECTION) && !attacker->s.number && !targ->s.number) || + (dflags & DAMAGE_NO_KILL))) { // player is undying and he's attacking himself, don't let him die + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } - } - else if ( targ->health < 0 ) - { + } else if (targ->health < 0) { targ->health = 0; - if ( attacker->s.number == 0 && targ->NPC ) - { + if (attacker->s.number == 0 && targ->NPC) { targ->NPC->scriptFlags |= SCF_FFDEATH; } } } - if ( yellAtAttacker ) - { - if ( !targ->NPC || !targ->NPC->charmedTime ) - { - G_FriendlyFireReaction( targ, attacker, dflags ); + if (yellAtAttacker) { + if (!targ->NPC || !targ->NPC->charmedTime) { + G_FriendlyFireReaction(targ, attacker, dflags); } } - } - else - { - + } else { } } - if ( targ->client ) { + if (targ->client) { targ->client->ps.stats[STAT_HEALTH] = targ->health; g_lastClientDamaged = targ; } - //TEMP HACK FOR PLAYER LOOK AT ENEMY CODE - //FIXME: move this to a player pain func? - if ( targ->s.number == 0 ) - { - if ( !targ->enemy //player does not have an enemy yet - || targ->enemy->s.weapon != WP_SABER //or player's enemy is not a jedi - || attacker->s.weapon == WP_SABER )//and attacker is a jedi - //keep enemy jedi over shooters + // TEMP HACK FOR PLAYER LOOK AT ENEMY CODE + // FIXME: move this to a player pain func? + if (targ->s.number == 0) { + if (!targ->enemy // player does not have an enemy yet + || targ->enemy->s.weapon != WP_SABER // or player's enemy is not a jedi + || attacker->s.weapon == WP_SABER) // and attacker is a jedi + // keep enemy jedi over shooters { - if ( attacker->enemy == targ || !OnSameTeam( targ, attacker ) ) - {//don't set player's enemy to teammates that hit him by accident + if (attacker->enemy == targ || !OnSameTeam(targ, attacker)) { // don't set player's enemy to teammates that hit him by accident targ->enemy = attacker; } - NPC_SetLookTarget( targ, attacker->s.number, level.time+1000 ); + NPC_SetLookTarget(targ, attacker->s.number, level.time + 1000); } - } - else if ( attacker->s.number == 0 && (!targ->NPC || !targ->NPC->timeOfDeath) && (mod == MOD_SABER || attacker->s.weapon != WP_SABER || !attacker->enemy || attacker->enemy->s.weapon != WP_SABER) )//keep enemy jedi over shooters - {//this looks dumb when they're on the ground and you keep hitting them, so only do this when first kill them - if ( !OnSameTeam( targ, attacker ) ) - {//don't set player's enemy to teammates that he hits by accident + } else if (attacker->s.number == 0 && (!targ->NPC || !targ->NPC->timeOfDeath) && + (mod == MOD_SABER || attacker->s.weapon != WP_SABER || !attacker->enemy || + attacker->enemy->s.weapon != WP_SABER)) // keep enemy jedi over shooters + { // this looks dumb when they're on the ground and you keep hitting them, so only do this when first kill them + if (!OnSameTeam(targ, attacker)) { // don't set player's enemy to teammates that he hits by accident attacker->enemy = targ; } - NPC_SetLookTarget( attacker, targ->s.number, level.time+1000 ); + NPC_SetLookTarget(attacker, targ->s.number, level.time + 1000); } - //TEMP HACK FOR PLAYER LOOK AT ENEMY CODE + // TEMP HACK FOR PLAYER LOOK AT ENEMY CODE - //add up the damage to the location - if ( targ->client ) - { - if ( targ->locationDamage[hitLoc] < Q3_INFINITE ) - { + // add up the damage to the location + if (targ->client) { + if (targ->locationDamage[hitLoc] < Q3_INFINITE) { targ->locationDamage[hitLoc] += take; } } - - if ( targ->health > 0 && targ->NPC && targ->NPC->surrenderTime > level.time ) - {//he was surrendering, goes down with one hit - if (!targ->client || targ->client->NPC_class!=CLASS_BOBAFETT) - { + if (targ->health > 0 && targ->NPC && targ->NPC->surrenderTime > level.time) { // he was surrendering, goes down with one hit + if (!targ->client || targ->client->NPC_class != CLASS_BOBAFETT) { targ->health = 0; } } - if ( targ->health <= 0 ) - { - if ( knockback && (dflags&DAMAGE_DEATH_KNOCKBACK) )//&& targ->client - {//only do knockback on death - if ( mod == MOD_FLECHETTE ) - {//special case because this is shotgun-ish damage, we need to multiply the knockback - knockback *= 12;//*6 for 6 flechette shots + if (targ->health <= 0) { + if (knockback && (dflags & DAMAGE_DEATH_KNOCKBACK)) //&& targ->client + { // only do knockback on death + if (mod == MOD_FLECHETTE) { // special case because this is shotgun-ish damage, we need to multiply the knockback + knockback *= 12; //*6 for 6 flechette shots } - G_ApplyKnockback( targ, newDir, knockback ); + G_ApplyKnockback(targ, newDir, knockback); } /* @@ -6730,45 +5244,34 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, const targ->health = -999; // If we are a breaking glass brush, store the damage point so we can do cool things with it. - if ( targ->svFlags & SVF_GLASS_BRUSH ) - { - VectorCopy( point, targ->pos1 ); - VectorCopy( dir, targ->pos2 ); + if (targ->svFlags & SVF_GLASS_BRUSH) { + VectorCopy(point, targ->pos1); + VectorCopy(dir, targ->pos2); } - if ( targ->client ) - {//HACK - if ( point ) - { - VectorCopy( point, targ->pos1 ); - } - else - { - VectorCopy( targ->currentOrigin, targ->pos1 ); + if (targ->client) { // HACK + if (point) { + VectorCopy(point, targ->pos1); + } else { + VectorCopy(targ->currentOrigin, targ->pos1); } } - if ( !alreadyDead && !targ->enemy ) - {//just killed and didn't have an enemy before + if (!alreadyDead && !targ->enemy) { // just killed and didn't have an enemy before targ->enemy = attacker; } - GEntity_DieFunc( targ, inflictor, attacker, take, mod, dflags, hitLoc ); - } - else - { - GEntity_PainFunc( targ, inflictor, attacker, point, take, mod, hitLoc ); - if ( targ->s.number == 0 ) - {//player run painscript - G_ActivateBehavior( targ, BSET_PAIN ); - if ( targ->health <= 25 ) - { - G_ActivateBehavior( targ, BSET_FLEE ); + GEntity_DieFunc(targ, inflictor, attacker, take, mod, dflags, hitLoc); + } else { + GEntity_PainFunc(targ, inflictor, attacker, point, take, mod, hitLoc); + if (targ->s.number == 0) { // player run painscript + G_ActivateBehavior(targ, BSET_PAIN); + if (targ->health <= 25) { + G_ActivateBehavior(targ, BSET_FLEE); } } } } } - /* ============ CanDamage @@ -6777,205 +5280,186 @@ Returns qtrue if the inflictor can directly damage the target. Used for explosions and melee attacks. ============ */ -qboolean CanDamage (gentity_t *targ, const vec3_t origin) { - vec3_t dest; - trace_t tr; - vec3_t midpoint; +qboolean CanDamage(gentity_t *targ, const vec3_t origin) { + vec3_t dest; + trace_t tr; + vec3_t midpoint; qboolean cantHitEnt = qtrue; - if ( (targ->contents&MASK_SOLID) ) - {//can hit it - if ( targ->s.solid == SOLID_BMODEL ) - {//but only if it's a brushmodel + if ((targ->contents & MASK_SOLID)) { // can hit it + if (targ->s.solid == SOLID_BMODEL) { // but only if it's a brushmodel cantHitEnt = qfalse; } } // use the midpoint of the bounds instead of the origin, because // bmodels may have their origin at 0,0,0 - VectorAdd (targ->absmin, targ->absmax, midpoint); - VectorScale (midpoint, 0.5, midpoint); + VectorAdd(targ->absmin, targ->absmax, midpoint); + VectorScale(midpoint, 0.5, midpoint); - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); /* vec3_t blah; VectorCopy( origin, blah); G_DebugLine(blah, dest, 5000, 0x0000ff, qtrue ); */ - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); - if (( tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number ) // if we also test the entitynum's we can bust up bbrushes better! + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); + if ((tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number) // if we also test the entitynum's we can bust up bbrushes better! return qtrue; // this should probably check in the plane of projection, // rather than in world coordinate, and also include Z - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] += 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); - if (( tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); + if ((tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] -= 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); - if (( tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); + if ((tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] += 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); - if (( tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); + if ((tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] -= 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); - if (( tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, (EG2_Collision)0, 0); + if ((tr.fraction == 1.0 && cantHitEnt) || tr.entityNum == targ->s.number) return qtrue; - return qfalse; } -extern void Boba_DustFallNear(const vec3_t origin, int dustcount); -extern void G_GetMassAndVelocityForEnt( gentity_t *ent, float *mass, vec3_t velocity ); +extern void Boba_DustFallNear(const vec3_t origin, int dustcount); +extern void G_GetMassAndVelocityForEnt(gentity_t *ent, float *mass, vec3_t velocity); /* ============ G_RadiusDamage ============ */ -void G_RadiusDamage ( const vec3_t origin, gentity_t *attacker, float damage, float radius, - gentity_t *ignore, int mod) { - float points, dist; - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - vec3_t dir; - int i, e; - int dFlags = DAMAGE_RADIUS; - - if ( radius < 1 ) { +void G_RadiusDamage(const vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, int mod) { + float points, dist; + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + vec3_t dir; + int i, e; + int dFlags = DAMAGE_RADIUS; + + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - if (mod==MOD_ROCKET) - { + if (mod == MOD_ROCKET) { Boba_DustFallNear(origin, 10); } - if ( mod == MOD_GAS ) - { + if (mod == MOD_GAS) { dFlags |= DAMAGE_NO_KNOCKBACK; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( ent == ignore ) + if (ent == ignore) continue; - if ( !ent->takedamage ) + if (!ent->takedamage) continue; - if ( !ent->contents ) + if (!ent->contents) continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) { - if ( origin[i] < ent->absmin[i] ) { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - origin[i]; - } else if ( origin[i] > ent->absmax[i] ) { + } else if (origin[i] > ent->absmax[i]) { v[i] = origin[i] - ent->absmax[i]; } else { v[i] = 0; } } - dist = VectorLength( v ); - if ( dist >= radius ) { + dist = VectorLength(v); + if (dist >= radius) { continue; } - points = damage * ( 1.0 - dist / radius ); + points = damage * (1.0 - dist / radius); // Lessen damage to vehicles that are moving away from the explosion - if (ent->client && (ent->client->NPC_class==CLASS_VEHICLE || G_IsRidingVehicle(ent))) - { - gentity_t* bike = ent; + if (ent->client && (ent->client->NPC_class == CLASS_VEHICLE || G_IsRidingVehicle(ent))) { + gentity_t *bike = ent; - if (G_IsRidingVehicle(ent) && ent->owner) - { + if (G_IsRidingVehicle(ent) && ent->owner) { bike = ent->owner; } - vec3_t vehMoveDirection; - float vehMoveSpeed; + vec3_t vehMoveDirection; + float vehMoveSpeed; - vec3_t explosionDirection; - float explosionDirectionSimilarity; + vec3_t explosionDirection; + float explosionDirectionSimilarity; - float mass; - G_GetMassAndVelocityForEnt( bike, &mass, vehMoveDirection ); - vehMoveSpeed = VectorNormalize(vehMoveDirection); - if (vehMoveSpeed>300.0f) - { + float mass; + G_GetMassAndVelocityForEnt(bike, &mass, vehMoveDirection); + vehMoveSpeed = VectorNormalize(vehMoveDirection); + if (vehMoveSpeed > 300.0f) { VectorSubtract(bike->currentOrigin, origin, explosionDirection); VectorNormalize(explosionDirection); explosionDirectionSimilarity = DotProduct(vehMoveDirection, explosionDirection); - if (explosionDirectionSimilarity>0.0f) - { + if (explosionDirectionSimilarity > 0.0f) { points *= (1.0f - explosionDirectionSimilarity); } } } - if (CanDamage (ent, origin)) - {//FIXME: still do a little damage in in PVS and close? - if ( ent->svFlags & (SVF_GLASS_BRUSH|SVF_BBRUSH) ) - { - VectorAdd( ent->absmin, ent->absmax, v ); - VectorScale( v, 0.5f, v ); - } - else - { - VectorCopy( ent->currentOrigin, v ); + if (CanDamage(ent, origin)) { // FIXME: still do a little damage in in PVS and close? + if (ent->svFlags & (SVF_GLASS_BRUSH | SVF_BBRUSH)) { + VectorAdd(ent->absmin, ent->absmax, v); + VectorScale(v, 0.5f, v); + } else { + VectorCopy(ent->currentOrigin, v); } - VectorSubtract( v, origin, dir); + VectorSubtract(v, origin, dir); // push the center of mass higher than the origin so players // get knocked into the air more dir[2] += 24; - if ( ent->svFlags & SVF_GLASS_BRUSH ) - { - if ( points > 1.0f ) - { + if (ent->svFlags & SVF_GLASS_BRUSH) { + if (points > 1.0f) { // we want to cap this at some point, otherwise it just gets crazy - if ( points > 6.0f ) - { - VectorScale( dir, 6.0f, dir ); - } - else - { - VectorScale( dir, points, dir ); + if (points > 6.0f) { + VectorScale(dir, 6.0f, dir); + } else { + VectorScale(dir, points, dir); } } - ent->splashRadius = radius;// * ( 1.0 - dist / radius ); + ent->splashRadius = radius; // * ( 1.0 - dist / radius ); } - G_Damage (ent, NULL, attacker, dir, origin, (int)points, dFlags, mod); + G_Damage(ent, NULL, attacker, dir, origin, (int)points, dFlags, mod); } } } diff --git a/code/game/g_emplaced.cpp b/code/game/g_emplaced.cpp index 9ef53cf6e3..826bf910c6 100644 --- a/code/game/g_emplaced.cpp +++ b/code/game/g_emplaced.cpp @@ -28,127 +28,107 @@ along with this program; if not, see . #include "b_local.h" #include "g_navigator.h" -extern Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *pEnt); -//lock the owner into place relative to the cannon pos -void EWebPositionUser(gentity_t *owner, gentity_t *eweb) -{ +// lock the owner into place relative to the cannon pos +void EWebPositionUser(gentity_t *owner, gentity_t *eweb) { mdxaBone_t boltMatrix; vec3_t p, p2, d; trace_t tr; qboolean traceOver = qtrue; - if ( owner->s.number < MAX_CLIENTS ) - {//extra checks + if (owner->s.number < MAX_CLIENTS) { // extra checks gi.trace(&tr, owner->currentOrigin, owner->mins, owner->maxs, owner->currentOrigin, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); - if ( tr.startsolid || tr.allsolid ) - {//crap, they're already in solid somehow, don't bother tracing over + if (tr.startsolid || tr.allsolid) { // crap, they're already in solid somehow, don't bother tracing over traceOver = qfalse; } } - if ( traceOver ) - {//trace up - VectorCopy( owner->currentOrigin, p2 ); + if (traceOver) { // trace up + VectorCopy(owner->currentOrigin, p2); p2[2] += STEPSIZE; gi.trace(&tr, owner->currentOrigin, owner->mins, owner->maxs, p2, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); - if (!tr.startsolid && !tr.allsolid ) - { - VectorCopy( tr.endpos, p2 ); - } - else - { - VectorCopy( owner->currentOrigin, p2 ); + if (!tr.startsolid && !tr.allsolid) { + VectorCopy(tr.endpos, p2); + } else { + VectorCopy(owner->currentOrigin, p2); } } - //trace over - gi.G2API_GetBoltMatrix( eweb->ghoul2, 0, eweb->headBolt, &boltMatrix, - eweb->s.apos.trBase, eweb->currentOrigin, - (cg.time?cg.time:level.time), NULL, eweb->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, p ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, d ); + // trace over + gi.G2API_GetBoltMatrix(eweb->ghoul2, 0, eweb->headBolt, &boltMatrix, eweb->s.apos.trBase, eweb->currentOrigin, (cg.time ? cg.time : level.time), NULL, + eweb->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, p); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, d); d[2] = 0; - VectorNormalize( d ); - VectorMA( p, -44.0f, d, p ); - if ( !traceOver ) - { - VectorCopy( p, tr.endpos ); + VectorNormalize(d); + VectorMA(p, -44.0f, d, p); + if (!traceOver) { + VectorCopy(p, tr.endpos); tr.allsolid = tr.startsolid = qfalse; - } - else - { + } else { p[2] = p2[2]; - if ( owner->s.number < MAX_CLIENTS ) - {//extra checks - //just see if end point is not in solid + if (owner->s.number < MAX_CLIENTS) { // extra checks + // just see if end point is not in solid gi.trace(&tr, p, owner->mins, owner->maxs, p, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); - if ( tr.startsolid || tr.allsolid ) - {//would be in solid there, so just trace over, I guess? + if (tr.startsolid || tr.allsolid) { // would be in solid there, so just trace over, I guess? gi.trace(&tr, p2, owner->mins, owner->maxs, p, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); } - } - else - {//trace over + } else { // trace over gi.trace(&tr, p2, owner->mins, owner->maxs, p, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); } } - if (!tr.startsolid && !tr.allsolid ) - { - //trace down - VectorCopy( tr.endpos, p ); - VectorCopy( p, p2 ); + if (!tr.startsolid && !tr.allsolid) { + // trace down + VectorCopy(tr.endpos, p); + VectorCopy(p, p2); p2[2] -= STEPSIZE; gi.trace(&tr, p, owner->mins, owner->maxs, p2, owner->s.number, owner->clipmask, (EG2_Collision)0, 0); - if (!tr.startsolid && !tr.allsolid )//&& tr.fraction == 1.0f) - { //all clear, we can move there - vec3_t moveDir; + if (!tr.startsolid && !tr.allsolid) //&& tr.fraction == 1.0f) + { // all clear, we can move there + vec3_t moveDir; float moveDist; - VectorCopy( tr.endpos, p ); - VectorSubtract( p, eweb->pos4, moveDir ); - moveDist = VectorNormalize( moveDir ); - if ( moveDist > 4.0f ) - {//moved past the threshold from last position - vec3_t oRight; - int strafeAnim; - - VectorCopy( p, eweb->pos4 );//update the position - //find out what direction he moved in - AngleVectors( owner->currentAngles, NULL, oRight, NULL ); - if ( DotProduct( moveDir, oRight ) > 0 ) - {//moved to his right, play right strafe + VectorCopy(tr.endpos, p); + VectorSubtract(p, eweb->pos4, moveDir); + moveDist = VectorNormalize(moveDir); + if (moveDist > 4.0f) { // moved past the threshold from last position + vec3_t oRight; + int strafeAnim; + + VectorCopy(p, eweb->pos4); // update the position + // find out what direction he moved in + AngleVectors(owner->currentAngles, NULL, oRight, NULL); + if (DotProduct(moveDir, oRight) > 0) { // moved to his right, play right strafe strafeAnim = BOTH_STRAFE_RIGHT1; - } - else - {//moved left, play left strafe + } else { // moved left, play left strafe strafeAnim = BOTH_STRAFE_LEFT1; } - NPC_SetAnim( owner, SETANIM_LEGS, strafeAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(owner, SETANIM_LEGS, strafeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } G_SetOrigin(owner, p); VectorCopy(p, owner->client->ps.origin); - gi.linkentity( owner ); + gi.linkentity(owner); } } - //FIXME: IK the hands to the handles of the gun? + // FIXME: IK the hands to the handles of the gun? } //=============================================== -//End E-Web +// End E-Web //=============================================== //---------------------------------------------------------- //=============================================== -//Emplaced Gun +// Emplaced Gun //=============================================== // spawnflag -#define EMPLACED_INACTIVE 1 -#define EMPLACED_FACING 2 -#define EMPLACED_VULNERABLE 4 -#define EWEB_INVULNERABLE 4 -#define EMPLACED_PLAYERUSE 8 +#define EMPLACED_INACTIVE 1 +#define EMPLACED_FACING 2 +#define EMPLACED_VULNERABLE 4 +#define EWEB_INVULNERABLE 4 +#define EMPLACED_PLAYERUSE 8 /*QUAKED emplaced_eweb (0 0 1) (-12 -12 -24) (12 12 24) INACTIVE FACING INVULNERABLE PLAYERUSE @@ -168,48 +148,39 @@ void EWebPositionUser(gentity_t *owner, gentity_t *eweb) will run usescript, painscript and deathscript */ //---------------------------------------------------------- -void eweb_pain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->health <= 0 ) - { +void eweb_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->health <= 0) { // play pain effect? - } - else - { - if ( self->paintarget ) - { - G_UseTargets2( self, self->activator, self->paintarget ); + } else { + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } // Don't do script if dead - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); } } //---------------------------------------------------------- -void eweb_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void eweb_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { vec3_t org; // turn off any firing animations it may have been doing self->s.frame = self->startFrame = self->endFrame = 0; - self->svFlags &= ~(SVF_ANIMATING|SVF_PLAYER_USABLE); - + self->svFlags &= ~(SVF_ANIMATING | SVF_PLAYER_USABLE); self->health = 0; -// self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon + // self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon self->takedamage = qfalse; self->lastEnemy = attacker; - if ( self->activator && self->activator->client ) - { - if ( self->activator->NPC ) - { + if (self->activator && self->activator->client) { + if (self->activator->NPC) { vec3_t right; // radius damage seems to throw them, but add an extra bit to throw them away from the weapon - AngleVectors( self->currentAngles, NULL, right, NULL ); - VectorMA( self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity ); + AngleVectors(self->currentAngles, NULL, right, NULL); + VectorMA(self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity); self->activator->client->ps.velocity[2] = -100; // kill them @@ -223,162 +194,142 @@ void eweb_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int d self->e_PainFunc = painF_NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_RadiusDamage( self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + G_RadiusDamage(self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 20; - G_PlayEffect( "emplaced/explode", org ); + G_PlayEffect("emplaced/explode", org); // Turn the top of the eweb off. -#define TURN_OFF 0x00000100//G2SURFACEFLAG_NODESCENDANTS - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "eweb_damage", TURN_OFF ); +#define TURN_OFF 0x00000100 // G2SURFACEFLAG_NODESCENDANTS + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "eweb_damage", TURN_OFF); // create some persistent smoke by using a dynamically created fx runner gentity_t *ent = G_Spawn(); - if ( ent ) - { + if (ent) { ent->delay = 200; ent->random = 100; - ent->fxID = G_EffectIndex( "emplaced/dead_smoke" ); + ent->fxID = G_EffectIndex("emplaced/dead_smoke"); ent->e_ThinkFunc = thinkF_fx_runner_think; ent->nextthink = level.time + 50; // move up above the gun origin - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 35; - G_SetOrigin( ent, org ); - VectorCopy( org, ent->s.origin ); + G_SetOrigin(ent, org); + VectorCopy(org, ent->s.origin); - VectorSet( ent->s.angles, -90, 0, 0 ); // up - G_SetAngles( ent, ent->s.angles ); + VectorSet(ent->s.angles, -90, 0, 0); // up + G_SetAngles(ent, ent->s.angles); - gi.linkentity( ent ); + gi.linkentity(ent); } - G_ActivateBehavior( self, BSET_DEATH ); + G_ActivateBehavior(self, BSET_DEATH); } -qboolean eweb_can_be_used( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->health <= 0 ) - { +qboolean eweb_can_be_used(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->health <= 0) { // can't use a dead gun. return qfalse; } - if ( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return qfalse; // can't use inactive gun } - if ( !activator->client ) - { + if (!activator->client) { return qfalse; // only a client can use it. } - if ( self->activator ) - { + if (self->activator) { // someone is already in the gun. return qfalse; } - if ( other && other->client && G_IsRidingVehicle( other ) ) - {//can't use eweb when on a vehicle + if (other && other->client && G_IsRidingVehicle(other)) { // can't use eweb when on a vehicle return qfalse; } - if ( activator && activator->client && G_IsRidingVehicle( activator ) ) - {//can't use eweb when on a vehicle + if (activator && activator->client && G_IsRidingVehicle(activator)) { // can't use eweb when on a vehicle return qfalse; } - if ( activator && activator->client && (activator->client->ps.pm_flags&PMF_DUCKED) ) - {//stand up, ya cowardly varmint! + if (activator && activator->client && (activator->client->ps.pm_flags & PMF_DUCKED)) { // stand up, ya cowardly varmint! return qfalse; } - if ( activator && activator->health <= 0 ) - {//dead men ain't got no more use fer guns... + if (activator && activator->health <= 0) { // dead men ain't got no more use fer guns... return qfalse; } vec3_t fwd1, fwd2; - vec3_t facingAngles; + vec3_t facingAngles; - VectorAdd( self->s.angles, self->pos1, facingAngles ); - if ( activator->s.number < MAX_CLIENTS ) - {//player must be facing general direction of the turret head + VectorAdd(self->s.angles, self->pos1, facingAngles); + if (activator->s.number < MAX_CLIENTS) { // player must be facing general direction of the turret head // Let's get some direction vectors for the users - AngleVectors( activator->client->ps.viewangles, fwd1, NULL, NULL ); + AngleVectors(activator->client->ps.viewangles, fwd1, NULL, NULL); fwd1[2] = 0; // Get the gun's direction vector - AngleVectors( facingAngles, fwd2, NULL, NULL ); + AngleVectors(facingAngles, fwd2, NULL, NULL); fwd2[2] = 0; - float dot = DotProduct( fwd1, fwd2 ); + float dot = DotProduct(fwd1, fwd2); // Must be reasonably facing the way the gun points ( 90 degrees or so ), otherwise we don't allow to use it. - if ( dot < 0.75f ) - { + if (dot < 0.75f) { return qfalse; } } - if ( self->delay + 500 < level.time ) - { + if (self->delay + 500 < level.time) { return qtrue; } return qfalse; } -void eweb_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !eweb_can_be_used( self, other, activator ) ) - { +void eweb_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!eweb_can_be_used(self, other, activator)) { return; } - int oldWeapon = activator->s.weapon; + int oldWeapon = activator->s.weapon; - if ( oldWeapon == WP_SABER ) - { + if (oldWeapon == WP_SABER) { self->alt_fire = activator->client->ps.SaberActive(); } // swap the users weapon with the emplaced gun and add the ammo the gun has to the player activator->client->ps.weapon = self->s.weapon; - Add_Ammo( activator, WP_EMPLACED_GUN, self->count ); - activator->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_EMPLACED_GUN ); + Add_Ammo(activator, WP_EMPLACED_GUN, self->count); + activator->client->ps.stats[STAT_WEAPONS] |= (1 << WP_EMPLACED_GUN); // Allow us to point from one to the other activator->owner = self; // kind of dumb, but when we are locked to the weapon, we are owned by it. self->activator = activator; - G_RemoveWeaponModels( activator ); + G_RemoveWeaponModels(activator); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - if ( activator->NPC ) - { - ChangeWeapon( activator, WP_EMPLACED_GUN ); - } - else if ( activator->s.number == 0 ) - { + extern void ChangeWeapon(gentity_t * ent, int newWeapon); + if (activator->NPC) { + ChangeWeapon(activator, WP_EMPLACED_GUN); + } else if (activator->s.number == 0) { // we don't want for it to draw the weapon select stuff cg.weaponSelect = WP_EMPLACED_GUN; - CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + CG_CenterPrint("@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } - VectorCopy( activator->currentOrigin, self->pos4 );//keep this around so we know when to make them play the strafe anim + VectorCopy(activator->currentOrigin, self->pos4); // keep this around so we know when to make them play the strafe anim // the gun will track which weapon we used to have self->s.weapon = oldWeapon; @@ -390,110 +341,108 @@ extern void ChangeWeapon( gentity_t *ent, int newWeapon ); self->delay = level.time; // can't disconnect from the thing for half a second // Let the gun be considered an enemy - //Ugh, so much AI code seems to assume enemies are clients, maybe this shouldn't be on, but it's too late in the game to change it now without knowing what side-effects this will have + // Ugh, so much AI code seems to assume enemies are clients, maybe this shouldn't be on, but it's too late in the game to change it now without knowing what + // side-effects this will have self->svFlags |= SVF_NONNPC_ENEMY; self->noDamageTeam = activator->client->playerTeam; - //FIXME: should really wait a bit after spawn and get this just once? + // FIXME: should really wait a bit after spawn and get this just once? self->waypoint = NAV::GetNearestNode(self); #ifdef _DEBUG - if ( self->waypoint == -1 ) - { - gi.Printf( S_COLOR_RED"ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin) ); + if (self->waypoint == -1) { + gi.Printf(S_COLOR_RED "ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin)); } #endif - G_Sound( self, G_SoundIndex( "sound/weapons/eweb/eweb_mount.mp3" )); + G_Sound(self, G_SoundIndex("sound/weapons/eweb/eweb_mount.mp3")); - if ( !(self->spawnflags&EMPLACED_PLAYERUSE) || activator->s.number == 0 ) - {//player-only usescript or any usescript + if (!(self->spawnflags & EMPLACED_PLAYERUSE) || activator->s.number == 0) { // player-only usescript or any usescript // Run use script - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); } } //---------------------------------------------------------- -void SP_emplaced_eweb( gentity_t *ent ) -{ +void SP_emplaced_eweb(gentity_t *ent) { char name[] = "models/map_objects/hoth/eweb_model.glm"; ent->svFlags |= SVF_PLAYER_USABLE; ent->contents = CONTENTS_BODY; - if ( ent->spawnflags & EMPLACED_INACTIVE ) - { + if (ent->spawnflags & EMPLACED_INACTIVE) { ent->svFlags |= SVF_INACTIVE; } - VectorSet( ent->mins, -12, -12, -24 ); - VectorSet( ent->maxs, 12, 12, 24 ); + VectorSet(ent->mins, -12, -12, -24); + VectorSet(ent->maxs, 12, 12, 24); ent->takedamage = qtrue; - if ( ( ent->spawnflags & EWEB_INVULNERABLE )) - { + if ((ent->spawnflags & EWEB_INVULNERABLE)) { ent->flags |= FL_GODMODE; } ent->s.radius = 80; ent->spawnflags |= 4; // deadsolid - //ent->e_ThinkFunc = thinkF_NULL; + // ent->e_ThinkFunc = thinkF_NULL; ent->e_PainFunc = painF_eweb_pain; - ent->e_DieFunc = dieF_eweb_die; + ent->e_DieFunc = dieF_eweb_die; - G_EffectIndex( "emplaced/explode" ); - G_EffectIndex( "emplaced/dead_smoke" ); + G_EffectIndex("emplaced/explode"); + G_EffectIndex("emplaced/dead_smoke"); - G_SoundIndex( "sound/weapons/eweb/eweb_aim.wav" ); - G_SoundIndex( "sound/weapons/eweb/eweb_dismount.mp3" ); - //G_SoundIndex( "sound/weapons/eweb/eweb_empty.wav" ); - G_SoundIndex( "sound/weapons/eweb/eweb_fire.wav" ); - G_SoundIndex( "sound/weapons/eweb/eweb_hitplayer.wav" ); - G_SoundIndex( "sound/weapons/eweb/eweb_hitsurface.wav" ); - //G_SoundIndex( "sound/weapons/eweb/eweb_load.wav" ); - G_SoundIndex( "sound/weapons/eweb/eweb_mount.mp3" ); + G_SoundIndex("sound/weapons/eweb/eweb_aim.wav"); + G_SoundIndex("sound/weapons/eweb/eweb_dismount.mp3"); + // G_SoundIndex( "sound/weapons/eweb/eweb_empty.wav" ); + G_SoundIndex("sound/weapons/eweb/eweb_fire.wav"); + G_SoundIndex("sound/weapons/eweb/eweb_hitplayer.wav"); + G_SoundIndex("sound/weapons/eweb/eweb_hitsurface.wav"); + // G_SoundIndex( "sound/weapons/eweb/eweb_load.wav" ); + G_SoundIndex("sound/weapons/eweb/eweb_mount.mp3"); // Set up our defaults and override with custom amounts as necessary - G_SpawnInt( "count", "999", &ent->count ); - G_SpawnInt( "health", "250", &ent->health ); - G_SpawnInt( "splashDamage", "40", &ent->splashDamage ); - G_SpawnInt( "splashRadius", "100", &ent->splashRadius ); - G_SpawnFloat( "delay", "200", &ent->random ); // NOTE: spawning into a different field!! - G_SpawnFloat( "wait", "800", &ent->wait ); + G_SpawnInt("count", "999", &ent->count); + G_SpawnInt("health", "250", &ent->health); + G_SpawnInt("splashDamage", "40", &ent->splashDamage); + G_SpawnInt("splashRadius", "100", &ent->splashRadius); + G_SpawnFloat("delay", "200", &ent->random); // NOTE: spawning into a different field!! + G_SpawnFloat("wait", "800", &ent->wait); ent->max_health = ent->health; ent->dflags |= DAMAGE_CUSTOM_HUD; // dumb, but we draw a custom hud - ent->s.modelindex = G_ModelIndex( name ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + ent->s.modelindex = G_ModelIndex(name); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); // Activate our tags and bones - ent->handLBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*cannonflash" ); //muzzle bolt - ent->headBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "cannon_Xrot" ); //for placing the owner relative to rotation - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cannon_Yrot", qtrue ); - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cannon_Xrot", qtrue ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, NULL, 0, 0); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, NULL, 0, 0); - //gi.G2API_SetBoneAngles( &ent->ghoul2[0], "cannon_Yrot", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL); - //set the constraints for this guy as an emplaced weapon, and his constraint angles - //ent->s.origin2[0] = 60.0f; //60 degrees in either direction - - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); + ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*cannonflash"); // muzzle bolt + ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cannon_Xrot"); // for placing the owner relative to rotation + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cannon_Yrot", qtrue); + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cannon_Xrot", qtrue); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, + NULL, 0, 0); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, + NULL, 0, 0); + // gi.G2API_SetBoneAngles( &ent->ghoul2[0], "cannon_Yrot", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL); + // set the constraints for this guy as an emplaced weapon, and his constraint angles + // ent->s.origin2[0] = 60.0f; //60 degrees in either direction + + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); ent->s.weapon = WP_EMPLACED_GUN; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - VectorCopy( ent->s.angles, ent->lastAngles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + VectorCopy(ent->s.angles, ent->lastAngles); // store base angles for later - VectorClear( ent->pos1 ); + VectorClear(ent->pos1); ent->e_UseFunc = useF_eweb_use; - ent->bounceCount = 1;//to distinguish it from the emplaced gun + ent->bounceCount = 1; // to distinguish it from the emplaced gun - gi.linkentity (ent); + gi.linkentity(ent); } /*QUAKED emplaced_gun (0 0 1) (-24 -24 0) (24 24 64) INACTIVE x VULNERABLE PLAYERUSE @@ -514,113 +463,99 @@ void SP_emplaced_eweb( gentity_t *ent ) */ //---------------------------------------------------------- -void emplaced_gun_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void emplaced_gun_use(gentity_t *self, gentity_t *other, gentity_t *activator) { vec3_t fwd1, fwd2; - if ( self->health <= 0 ) - { + if (self->health <= 0) { // can't use a dead gun. return; } - if ( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; // can't use inactive gun } - if ( !activator->client ) - { + if (!activator->client) { return; // only a client can use it. } - if ( self->activator ) - { + if (self->activator) { // someone is already in the gun. return; } - if ( other && other->client && G_IsRidingVehicle( other ) ) - {//can't use eweb when on a vehicle + if (other && other->client && G_IsRidingVehicle(other)) { // can't use eweb when on a vehicle return; } - if ( activator && activator->client && G_IsRidingVehicle( activator ) ) - {//can't use eweb when on a vehicle + if (activator && activator->client && G_IsRidingVehicle(activator)) { // can't use eweb when on a vehicle return; } // We'll just let the designers duke this one out....I mean, as to whether they even want to limit such a thing. - if ( self->spawnflags & EMPLACED_FACING ) - { + if (self->spawnflags & EMPLACED_FACING) { // Let's get some direction vectors for the users - AngleVectors( activator->client->ps.viewangles, fwd1, NULL, NULL ); + AngleVectors(activator->client->ps.viewangles, fwd1, NULL, NULL); // Get the guns direction vector - AngleVectors( self->pos1, fwd2, NULL, NULL ); + AngleVectors(self->pos1, fwd2, NULL, NULL); - float dot = DotProduct( fwd1, fwd2 ); + float dot = DotProduct(fwd1, fwd2); // Must be reasonably facing the way the gun points ( 90 degrees or so ), otherwise we don't allow to use it. - if ( dot < 0.0f ) - { + if (dot < 0.0f) { return; } } // don't allow using it again for half a second - if ( self->delay + 500 < level.time ) - { - int oldWeapon = activator->s.weapon; + if (self->delay + 500 < level.time) { + int oldWeapon = activator->s.weapon; - if ( oldWeapon == WP_SABER ) - { + if (oldWeapon == WP_SABER) { self->alt_fire = activator->client->ps.SaberActive(); } // swap the users weapon with the emplaced gun and add the ammo the gun has to the player activator->client->ps.weapon = self->s.weapon; - Add_Ammo( activator, WP_EMPLACED_GUN, self->count ); - activator->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_EMPLACED_GUN ); + Add_Ammo(activator, WP_EMPLACED_GUN, self->count); + activator->client->ps.stats[STAT_WEAPONS] |= (1 << WP_EMPLACED_GUN); // Allow us to point from one to the other activator->owner = self; // kind of dumb, but when we are locked to the weapon, we are owned by it. self->activator = activator; - G_RemoveWeaponModels( activator ); + G_RemoveWeaponModels(activator); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - if ( activator->NPC ) - { - ChangeWeapon( activator, WP_EMPLACED_GUN ); - } - else if ( activator->s.number == 0 ) - { + extern void ChangeWeapon(gentity_t * ent, int newWeapon); + if (activator->NPC) { + ChangeWeapon(activator, WP_EMPLACED_GUN); + } else if (activator->s.number == 0) { // we don't want for it to draw the weapon select stuff cg.weaponSelect = WP_EMPLACED_GUN; - CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + CG_CenterPrint("@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } - // Since we move the activator inside of the gun, we reserve a solid spot where they were standing in order to be able to get back out without being in solid - if ( self->nextTrain ) - {//you never know - G_FreeEntity( self->nextTrain ); + // Since we move the activator inside of the gun, we reserve a solid spot where they were standing in order to be able to get back out without being in + // solid + if (self->nextTrain) { // you never know + G_FreeEntity(self->nextTrain); } self->nextTrain = G_Spawn(); - //self->nextTrain->classname = "emp_placeholder"; - self->nextTrain->contents = CONTENTS_MONSTERCLIP|CONTENTS_PLAYERCLIP;//hmm... playerclip too now that we're doing it for NPCs? - G_SetOrigin( self->nextTrain, activator->client->ps.origin ); - VectorCopy( activator->mins, self->nextTrain->mins ); - VectorCopy( activator->maxs, self->nextTrain->maxs ); - gi.linkentity( self->nextTrain ); + // self->nextTrain->classname = "emp_placeholder"; + self->nextTrain->contents = CONTENTS_MONSTERCLIP | CONTENTS_PLAYERCLIP; // hmm... playerclip too now that we're doing it for NPCs? + G_SetOrigin(self->nextTrain, activator->client->ps.origin); + VectorCopy(activator->mins, self->nextTrain->mins); + VectorCopy(activator->maxs, self->nextTrain->maxs); + gi.linkentity(self->nextTrain); - //need to inflate the activator's mins/maxs since the gunsit anim puts them outside of their bbox - VectorSet( activator->mins, -24, -24, -24 ); - VectorSet( activator->maxs, 24, 24, 40 ); + // need to inflate the activator's mins/maxs since the gunsit anim puts them outside of their bbox + VectorSet(activator->mins, -24, -24, -24); + VectorSet(activator->maxs, 24, 24, 40); // Move the activator into the center of the gun. For NPC's the only way the can get out of the gun is to die. - VectorCopy( self->s.origin, activator->client->ps.origin ); + VectorCopy(self->s.origin, activator->client->ps.origin); activator->client->ps.origin[2] += 30; // move them up so they aren't standing in the floor - gi.linkentity( activator ); + gi.linkentity(activator); // the gun will track which weapon we used to have self->s.weapon = oldWeapon; @@ -632,65 +567,57 @@ extern void ChangeWeapon( gentity_t *ent, int newWeapon ); self->delay = level.time; // can't disconnect from the thing for half a second // Let the gun be considered an enemy - //Ugh, so much AI code seems to assume enemies are clients, maybe this shouldn't be on, but it's too late in the game to change it now without knowing what side-effects this will have + // Ugh, so much AI code seems to assume enemies are clients, maybe this shouldn't be on, but it's too late in the game to change it now without knowing + // what side-effects this will have self->svFlags |= SVF_NONNPC_ENEMY; self->noDamageTeam = activator->client->playerTeam; // FIXME: don't do this, we'll try and actually put the player in this beast // move the player to the center of the gun -// activator->contents = 0; -// VectorCopy( self->currentOrigin, activator->client->ps.origin ); + // activator->contents = 0; + // VectorCopy( self->currentOrigin, activator->client->ps.origin ); - SetClientViewAngle( activator, self->pos1 ); + SetClientViewAngle(activator, self->pos1); - //FIXME: should really wait a bit after spawn and get this just once? + // FIXME: should really wait a bit after spawn and get this just once? self->waypoint = NAV::GetNearestNode(self); #ifdef _DEBUG - if ( self->waypoint == -1 ) - { - gi.Printf( S_COLOR_RED"ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin) ); + if (self->waypoint == -1) { + gi.Printf(S_COLOR_RED "ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin)); } #endif - G_Sound( self, G_SoundIndex( "sound/weapons/emplaced/emplaced_mount.mp3" )); + G_Sound(self, G_SoundIndex("sound/weapons/emplaced/emplaced_mount.mp3")); - if ( !(self->spawnflags&EMPLACED_PLAYERUSE) || activator->s.number == 0 ) - {//player-only usescript or any usescript + if (!(self->spawnflags & EMPLACED_PLAYERUSE) || activator->s.number == 0) { // player-only usescript or any usescript // Run use script - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); } } } //---------------------------------------------------------- -void emplaced_gun_pain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->health <= 0 ) - { +void emplaced_gun_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->health <= 0) { // play pain effect? - } - else - { - if ( self->paintarget ) - { - G_UseTargets2( self, self->activator, self->paintarget ); + } else { + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } // Don't do script if dead - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); } } //---------------------------------------------------------- -void emplaced_blow( gentity_t *ent ) -{ +void emplaced_blow(gentity_t *ent) { ent->e_DieFunc = dieF_NULL; - emplaced_gun_die( ent, ent->lastEnemy, ent->lastEnemy, 0, MOD_UNKNOWN ); + emplaced_gun_die(ent, ent->lastEnemy, ent->lastEnemy, 0, MOD_UNKNOWN); } //---------------------------------------------------------- -void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void emplaced_gun_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { vec3_t org; // turn off any firing animations it may have been doing @@ -698,28 +625,25 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->svFlags &= ~SVF_ANIMATING; self->health = 0; -// self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon + // self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon self->takedamage = qfalse; self->lastEnemy = attacker; // we defer explosion so the player has time to get out - if ( self->e_DieFunc ) - { + if (self->e_DieFunc) { self->e_ThinkFunc = thinkF_emplaced_blow; self->nextthink = level.time + 3000; // don't blow for a couple of seconds return; } - if ( self->activator && self->activator->client ) - { - if ( self->activator->NPC ) - { + if (self->activator && self->activator->client) { + if (self->activator->NPC) { vec3_t right; // radius damage seems to throw them, but add an extra bit to throw them away from the weapon - AngleVectors( self->currentAngles, NULL, right, NULL ); - VectorMA( self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity ); + AngleVectors(self->currentAngles, NULL, right, NULL); + VectorMA(self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity); self->activator->client->ps.velocity[2] = -100; // kill them @@ -734,12 +658,11 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->e_PainFunc = painF_NULL; self->e_ThinkFunc = thinkF_NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_RadiusDamage( self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + G_RadiusDamage(self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); // when the gun is dead, add some ugliness to it. vec3_t ugly; @@ -747,173 +670,162 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke ugly[YAW] = 4; ugly[PITCH] = self->lastAngles[PITCH] * 0.8f + Q_flrand(-1.0f, 1.0f) * 6; ugly[ROLL] = Q_flrand(-1.0f, 1.0f) * 7; - gi.G2API_SetBoneAnglesIndex( &self->ghoul2[self->playerModel], self->lowerLumbarBone, ugly, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); + gi.G2API_SetBoneAnglesIndex(&self->ghoul2[self->playerModel], self->lowerLumbarBone, ugly, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + 0, 0); - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 20; - G_PlayEffect( "emplaced/explode", org ); + G_PlayEffect("emplaced/explode", org); // create some persistent smoke by using a dynamically created fx runner gentity_t *ent = G_Spawn(); - if ( ent ) - { + if (ent) { ent->delay = 200; ent->random = 100; - ent->fxID = G_EffectIndex( "emplaced/dead_smoke" ); + ent->fxID = G_EffectIndex("emplaced/dead_smoke"); ent->e_ThinkFunc = thinkF_fx_runner_think; ent->nextthink = level.time + 50; // move up above the gun origin - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 35; - G_SetOrigin( ent, org ); - VectorCopy( org, ent->s.origin ); + G_SetOrigin(ent, org); + VectorCopy(org, ent->s.origin); - VectorSet( ent->s.angles, -90, 0, 0 ); // up - G_SetAngles( ent, ent->s.angles ); + VectorSet(ent->s.angles, -90, 0, 0); // up + G_SetAngles(ent, ent->s.angles); - gi.linkentity( ent ); + gi.linkentity(ent); } - G_ActivateBehavior( self, BSET_DEATH ); + G_ActivateBehavior(self, BSET_DEATH); } //---------------------------------------------------------- -void SP_emplaced_gun( gentity_t *ent ) -{ +void SP_emplaced_gun(gentity_t *ent) { char name[] = "models/map_objects/imp_mine/turret_chair.glm"; ent->svFlags |= SVF_PLAYER_USABLE; - ent->contents = CONTENTS_BODY;//CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP;//CONTENTS_SOLID; + ent->contents = CONTENTS_BODY; // CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP;//CONTENTS_SOLID; - if ( ent->spawnflags & EMPLACED_INACTIVE ) - { + if (ent->spawnflags & EMPLACED_INACTIVE) { ent->svFlags |= SVF_INACTIVE; } - VectorSet( ent->mins, -30, -30, -5 ); - VectorSet( ent->maxs, 30, 30, 60 ); + VectorSet(ent->mins, -30, -30, -5); + VectorSet(ent->maxs, 30, 30, 60); ent->takedamage = qtrue; - if ( !( ent->spawnflags & EMPLACED_VULNERABLE )) - { + if (!(ent->spawnflags & EMPLACED_VULNERABLE)) { ent->flags |= FL_GODMODE; } ent->s.radius = 110; ent->spawnflags |= 4; // deadsolid - //ent->e_ThinkFunc = thinkF_NULL; + // ent->e_ThinkFunc = thinkF_NULL; ent->e_PainFunc = painF_emplaced_gun_pain; - ent->e_DieFunc = dieF_emplaced_gun_die; + ent->e_DieFunc = dieF_emplaced_gun_die; - G_EffectIndex( "emplaced/explode" ); - G_EffectIndex( "emplaced/dead_smoke" ); + G_EffectIndex("emplaced/explode"); + G_EffectIndex("emplaced/dead_smoke"); - G_SoundIndex( "sound/weapons/emplaced/emplaced_mount.mp3" ); - G_SoundIndex( "sound/weapons/emplaced/emplaced_dismount.mp3" ); - G_SoundIndex( "sound/weapons/emplaced/emplaced_move_lp.wav" ); + G_SoundIndex("sound/weapons/emplaced/emplaced_mount.mp3"); + G_SoundIndex("sound/weapons/emplaced/emplaced_dismount.mp3"); + G_SoundIndex("sound/weapons/emplaced/emplaced_move_lp.wav"); // Set up our defaults and override with custom amounts as necessary - G_SpawnInt( "count", "999", &ent->count ); - G_SpawnInt( "health", "250", &ent->health ); - G_SpawnInt( "splashDamage", "80", &ent->splashDamage ); - G_SpawnInt( "splashRadius", "128", &ent->splashRadius ); - G_SpawnFloat( "delay", "200", &ent->random ); // NOTE: spawning into a different field!! - G_SpawnFloat( "wait", "800", &ent->wait ); + G_SpawnInt("count", "999", &ent->count); + G_SpawnInt("health", "250", &ent->health); + G_SpawnInt("splashDamage", "80", &ent->splashDamage); + G_SpawnInt("splashRadius", "128", &ent->splashRadius); + G_SpawnFloat("delay", "200", &ent->random); // NOTE: spawning into a different field!! + G_SpawnFloat("wait", "800", &ent->wait); ent->max_health = ent->health; ent->dflags |= DAMAGE_CUSTOM_HUD; // dumb, but we draw a custom hud - ent->s.modelindex = G_ModelIndex( name ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + ent->s.modelindex = G_ModelIndex(name); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); // Activate our tags and bones - ent->headBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*seat" ); - ent->handLBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*flash01" ); - ent->handRBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*flash02" ); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "base_bone", qtrue ); - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "swivel_bone", qtrue ); - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); - - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); + ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*seat"); + ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash01"); + ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash02"); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "base_bone", qtrue); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "swivel_bone", qtrue); + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, + NULL, 0, 0); + + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); ent->s.weapon = WP_EMPLACED_GUN; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - VectorCopy( ent->s.angles, ent->lastAngles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + VectorCopy(ent->s.angles, ent->lastAngles); // store base angles for later - VectorCopy( ent->s.angles, ent->pos1 ); + VectorCopy(ent->s.angles, ent->pos1); ent->e_UseFunc = useF_emplaced_gun_use; - ent->bounceCount = 0;//to distinguish it from the eweb + ent->bounceCount = 0; // to distinguish it from the eweb - gi.linkentity (ent); + gi.linkentity(ent); } //==================================================== -//General Emplaced Weapon Funcs called in g_active.cpp +// General Emplaced Weapon Funcs called in g_active.cpp //==================================================== -void G_UpdateEmplacedWeaponData( gentity_t *ent ) -{ - if ( ent && ent->owner && ent->health > 0 ) - { +void G_UpdateEmplacedWeaponData(gentity_t *ent) { + if (ent && ent->owner && ent->health > 0) { gentity_t *chair = ent->owner; - if ( chair->e_UseFunc == useF_emplaced_gun_use )//yeah, crappy way to check this, but... - {//one that you sit in - //take the emplaced gun's waypoint as your own + if (chair->e_UseFunc == useF_emplaced_gun_use) // yeah, crappy way to check this, but... + { // one that you sit in + // take the emplaced gun's waypoint as your own ent->waypoint = chair->waypoint; - //update the actual origin of the sitter - mdxaBone_t boltMatrix; - vec3_t chairAng = {0, ent->client->ps.viewangles[YAW], 0}; + // update the actual origin of the sitter + mdxaBone_t boltMatrix; + vec3_t chairAng = {0, ent->client->ps.viewangles[YAW], 0}; // Getting the seat bolt here - gi.G2API_GetBoltMatrix( chair->ghoul2, chair->playerModel, chair->headBolt, - &boltMatrix, chairAng, chair->currentOrigin, (cg.time?cg.time:level.time), - NULL, chair->s.modelScale ); + gi.G2API_GetBoltMatrix(chair->ghoul2, chair->playerModel, chair->headBolt, &boltMatrix, chairAng, chair->currentOrigin, + (cg.time ? cg.time : level.time), NULL, chair->s.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->ps.origin ); - gi.linkentity( ent ); - } - else if ( chair->e_UseFunc == useF_eweb_use )//yeah, crappy way to check this, but... - {//standing at an E-Web - EWebPositionUser( ent, chair ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->ps.origin); + gi.linkentity(ent); + } else if (chair->e_UseFunc == useF_eweb_use) // yeah, crappy way to check this, but... + { // standing at an E-Web + EWebPositionUser(ent, chair); } } } -void ExitEmplacedWeapon( gentity_t *ent ) -{ +void ExitEmplacedWeapon(gentity_t *ent) { // requesting to unlock from the weapon // We'll leave the gun pointed in the direction it was last facing, though we'll cut out the pitch - if ( ent->client ) - { + if (ent->client) { // if we are the player we will have put down a brush that blocks NPCs so that we have a clear spot to get back out. - //gentity_t *place = G_Find( NULL, FOFS(classname), "emp_placeholder" ); + // gentity_t *place = G_Find( NULL, FOFS(classname), "emp_placeholder" ); - if ( ent->health > 0 ) - {//he's still alive, and we have a placeholder, so put him back - if ( ent->owner->nextTrain ) - { + if (ent->health > 0) { // he's still alive, and we have a placeholder, so put him back + if (ent->owner->nextTrain) { // reset the players position - VectorCopy( ent->owner->nextTrain->currentOrigin, ent->client->ps.origin ); - //reset ent's size to normal - VectorCopy( ent->owner->nextTrain->mins, ent->mins ); - VectorCopy( ent->owner->nextTrain->maxs, ent->maxs ); - //free the placeholder - G_FreeEntity( ent->owner->nextTrain ); - //re-link the ent - gi.linkentity( ent ); - } - else if ( ent->owner->e_UseFunc == useF_eweb_use )//yeah, crappy way to check this, but... + VectorCopy(ent->owner->nextTrain->currentOrigin, ent->client->ps.origin); + // reset ent's size to normal + VectorCopy(ent->owner->nextTrain->mins, ent->mins); + VectorCopy(ent->owner->nextTrain->maxs, ent->maxs); + // free the placeholder + G_FreeEntity(ent->owner->nextTrain); + // re-link the ent + gi.linkentity(ent); + } else if (ent->owner->e_UseFunc == useF_eweb_use) // yeah, crappy way to check this, but... { // so give 'em a push away from us vec3_t backDir, start, end; @@ -923,150 +835,119 @@ void ExitEmplacedWeapon( gentity_t *ent ) float minRadius, maxRadius; qboolean safeExit = qfalse; - VectorSubtract( ent->currentOrigin, eweb->currentOrigin, backDir ); + VectorSubtract(ent->currentOrigin, eweb->currentOrigin, backDir); backDir[2] = 0; - minRadius = VectorNormalize( backDir )-8.0f; + minRadius = VectorNormalize(backDir) - 8.0f; - maxRadius = (ent->maxs[0]+ent->maxs[1])*0.5f; - maxRadius += (eweb->maxs[0]+eweb->maxs[1])*0.5f; + maxRadius = (ent->maxs[0] + ent->maxs[1]) * 0.5f; + maxRadius += (eweb->maxs[0] + eweb->maxs[1]) * 0.5f; maxRadius *= 1.5f; - if ( minRadius >= maxRadius - 1.0f ) - { + if (minRadius >= maxRadius - 1.0f) { maxRadius = minRadius + 8.0f; } - ent->owner = NULL;//so his trace hits me + ent->owner = NULL; // so his trace hits me - for ( curRadius = minRadius; curRadius <= maxRadius; curRadius += 4.0f ) - { - VectorMA( ent->currentOrigin, curRadius, backDir, start ); - //make sure they're not in the ground - VectorCopy( start, end ); + for (curRadius = minRadius; curRadius <= maxRadius; curRadius += 4.0f) { + VectorMA(ent->currentOrigin, curRadius, backDir, start); + // make sure they're not in the ground + VectorCopy(start, end); start[2] += 18; end[2] -= 18; gi.trace(&trace, start, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); - if ( !trace.allsolid && !trace.startsolid ) - { - G_SetOrigin( ent, trace.endpos ); - gi.linkentity( ent ); + if (!trace.allsolid && !trace.startsolid) { + G_SetOrigin(ent, trace.endpos); + gi.linkentity(ent); safeExit = qtrue; break; } } - //Hmm... otherwise, don't allow them to get off? + // Hmm... otherwise, don't allow them to get off? ent->owner = eweb; - if ( !safeExit ) - {//don't try again for a second + if (!safeExit) { // don't try again for a second ent->owner->delay = level.time + 500; return; } } - } - else if ( ent->health <= 0 ) - { + } else if (ent->health <= 0) { // dead, so give 'em a push out of the chair vec3_t dir; - AngleVectors( ent->owner->s.angles, NULL, dir, NULL ); + AngleVectors(ent->owner->s.angles, NULL, dir, NULL); - if ( rand() & 1 ) - { - VectorScale( dir, -1, dir ); + if (rand() & 1) { + VectorScale(dir, -1, dir); } - VectorMA( ent->client->ps.velocity, 75, dir, ent->client->ps.velocity ); + VectorMA(ent->client->ps.velocity, 75, dir, ent->client->ps.velocity); } - //don't let them move towards me for a couple frames so they don't step back into me while I'm becoming solid to them - if ( ent->s.number < MAX_CLIENTS ) - { - if ( ent->client->ps.pm_time < 100 ) - { + // don't let them move towards me for a couple frames so they don't step back into me while I'm becoming solid to them + if (ent->s.number < MAX_CLIENTS) { + if (ent->client->ps.pm_time < 100) { ent->client->ps.pm_time = 100; } - ent->client->ps.pm_flags |= (PMF_TIME_NOFRICTION|PMF_TIME_KNOCKBACK); + ent->client->ps.pm_flags |= (PMF_TIME_NOFRICTION | PMF_TIME_KNOCKBACK); } - if ( !ent->owner->bounceCount ) - {//not an EWeb - the overridden bone angles will remember the angle we left it at - VectorCopy( ent->client->ps.viewangles, ent->owner->s.angles ); + if (!ent->owner->bounceCount) { // not an EWeb - the overridden bone angles will remember the angle we left it at + VectorCopy(ent->client->ps.viewangles, ent->owner->s.angles); ent->owner->s.angles[PITCH] = 0; - G_SetAngles( ent->owner, ent->owner->s.angles ); - VectorCopy( ent->owner->s.angles, ent->owner->pos1 ); + G_SetAngles(ent->owner, ent->owner->s.angles); + VectorCopy(ent->owner->s.angles, ent->owner->pos1); } } // Remove the emplaced gun from our inventory - ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_EMPLACED_GUN ); + ent->client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_EMPLACED_GUN); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void CG_ChangeWeapon( int num ); - if ( ent->health <= 0 ) - {//when die, don't set weapon back on when ejected from emplaced/eweb - //empty hands + extern void ChangeWeapon(gentity_t * ent, int newWeapon); + extern void CG_ChangeWeapon(int num); + if (ent->health <= 0) { // when die, don't set weapon back on when ejected from emplaced/eweb + // empty hands ent->client->ps.weapon = WP_NONE; - if ( ent->NPC ) - { - ChangeWeapon( ent, ent->client->ps.weapon ); // should be OK actually. + if (ent->NPC) { + ChangeWeapon(ent, ent->client->ps.weapon); // should be OK actually. + } else { + CG_ChangeWeapon(ent->client->ps.weapon); } - else - { - CG_ChangeWeapon( ent->client->ps.weapon ); + if (ent->s.number < MAX_CLIENTS) { + gi.cvar_set("cg_thirdperson", "1"); } - if ( ent->s.number < MAX_CLIENTS ) - { - gi.cvar_set( "cg_thirdperson", "1" ); - } - } - else - { + } else { // when we lock or unlock from the the gun, we get our old weapon back ent->client->ps.weapon = ent->owner->s.weapon; - if ( ent->NPC ) - {//BTW, if a saber-using NPC ever gets off of an emplaced gun/eweb, this will not work, look at NPC_ChangeWeapon for the proper way - ChangeWeapon( ent, ent->client->ps.weapon ); - } - else - { - G_RemoveWeaponModels( ent ); - CG_ChangeWeapon( ent->client->ps.weapon ); - if ( ent->client->ps.weapon == WP_SABER ) - { - WP_SaberAddG2SaberModels( ent ); - } - else - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + if (ent->NPC) { // BTW, if a saber-using NPC ever gets off of an emplaced gun/eweb, this will not work, look at NPC_ChangeWeapon for the proper way + ChangeWeapon(ent, ent->client->ps.weapon); + } else { + G_RemoveWeaponModels(ent); + CG_ChangeWeapon(ent->client->ps.weapon); + if (ent->client->ps.weapon == WP_SABER) { + WP_SaberAddG2SaberModels(ent); + } else { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0); } - if ( ent->s.number < MAX_CLIENTS ) - { - if ( ent->client->ps.weapon == WP_SABER ) - { - gi.cvar_set( "cg_thirdperson", "1" ); - } - else if ( ent->client->ps.weapon != WP_SABER && cg_gunAutoFirst.integer ) - { - gi.cvar_set( "cg_thirdperson", "0" ); + if (ent->s.number < MAX_CLIENTS) { + if (ent->client->ps.weapon == WP_SABER) { + gi.cvar_set("cg_thirdperson", "1"); + } else if (ent->client->ps.weapon != WP_SABER && cg_gunAutoFirst.integer) { + gi.cvar_set("cg_thirdperson", "0"); } } } - if ( ent->client->ps.weapon == WP_SABER ) - { - if ( ent->owner->alt_fire ) - { + if (ent->client->ps.weapon == WP_SABER) { + if (ent->owner->alt_fire) { ent->client->ps.SaberActivate(); - } - else - { + } else { ent->client->ps.SaberDeactivate(); } } } - //set the emplaced gun/eweb's weapon back to the emplaced gun + // set the emplaced gun/eweb's weapon back to the emplaced gun ent->owner->s.weapon = WP_EMPLACED_GUN; -// gi.G2API_DetachG2Model( &ent->ghoul2[ent->playerModel] ); + // gi.G2API_DetachG2Model( &ent->ghoul2[ent->playerModel] ); ent->s.eFlags &= ~EF_LOCKED_TO_WEAPON; ent->client->ps.eFlags &= ~EF_LOCKED_TO_WEAPON; @@ -1076,69 +957,54 @@ extern void CG_ChangeWeapon( int num ); ent->owner->delay = level.time; ent->owner->activator = NULL; - if ( !ent->NPC ) - { + if (!ent->NPC) { // by keeping the owner, a dead npc can be pushed out of the chair without colliding with it ent->owner = NULL; } } -void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ) -{ - if (( (*ucmd)->buttons & BUTTON_USE || (*ucmd)->forwardmove < 0 || (*ucmd)->upmove > 0 ) && ent->owner && ent->owner->delay + 500 < level.time ) - { +void RunEmplacedWeapon(gentity_t *ent, usercmd_t **ucmd) { + if (((*ucmd)->buttons & BUTTON_USE || (*ucmd)->forwardmove < 0 || (*ucmd)->upmove > 0) && ent->owner && ent->owner->delay + 500 < level.time) { ent->owner->s.loopSound = 0; - if ( ent->owner->e_UseFunc == useF_eweb_use )//yeah, crappy way to check this, but... + if (ent->owner->e_UseFunc == useF_eweb_use) // yeah, crappy way to check this, but... { - G_Sound( ent, G_SoundIndex( "sound/weapons/eweb/eweb_dismount.mp3" )); + G_Sound(ent, G_SoundIndex("sound/weapons/eweb/eweb_dismount.mp3")); + } else { + G_Sound(ent, G_SoundIndex("sound/weapons/emplaced/emplaced_dismount.mp3")); } - else - { - G_Sound( ent, G_SoundIndex( "sound/weapons/emplaced/emplaced_dismount.mp3" )); - } - - ExitEmplacedWeapon( ent ); + ExitEmplacedWeapon(ent); (*ucmd)->buttons &= ~BUTTON_USE; - if ( (*ucmd)->upmove > 0 ) - {//don't actually jump + if ((*ucmd)->upmove > 0) { // don't actually jump (*ucmd)->upmove = 0; } - } - else - { + } else { // this is a crappy way to put sounds on a moving eweb.... - if ( ent->owner - && ent->owner->e_UseFunc == useF_eweb_use )//yeah, crappy way to check this, but... + if (ent->owner && ent->owner->e_UseFunc == useF_eweb_use) // yeah, crappy way to check this, but... { - if ( !VectorCompare( ent->client->ps.viewangles, ent->owner->movedir )) - { - ent->owner->s.loopSound = G_SoundIndex( "sound/weapons/eweb/eweb_aim.wav" ); + if (!VectorCompare(ent->client->ps.viewangles, ent->owner->movedir)) { + ent->owner->s.loopSound = G_SoundIndex("sound/weapons/eweb/eweb_aim.wav"); ent->owner->fly_sound_debounce_time = level.time; - } - else - { - if ( ent->owner->fly_sound_debounce_time + 100 <= level.time ) - { + } else { + if (ent->owner->fly_sound_debounce_time + 100 <= level.time) { ent->owner->s.loopSound = 0; } } - VectorCopy( ent->client->ps.viewangles, ent->owner->movedir ); + VectorCopy(ent->client->ps.viewangles, ent->owner->movedir); } // don't allow movement, weapon switching, and most kinds of button presses (*ucmd)->forwardmove = 0; (*ucmd)->rightmove = 0; (*ucmd)->upmove = 0; - (*ucmd)->buttons &= (BUTTON_ATTACK|BUTTON_ALT_ATTACK); + (*ucmd)->buttons &= (BUTTON_ATTACK | BUTTON_ALT_ATTACK); - (*ucmd)->weapon = ent->client->ps.weapon; //WP_EMPLACED_GUN; + (*ucmd)->weapon = ent->client->ps.weapon; // WP_EMPLACED_GUN; - if ( ent->health <= 0 ) - { - ExitEmplacedWeapon( ent ); + if (ent->health <= 0) { + ExitEmplacedWeapon(ent); } } } diff --git a/code/game/g_functions.cpp b/code/game/g_functions.cpp index 822f4413e5..02f3a72e3f 100644 --- a/code/game/g_functions.cpp +++ b/code/game/g_functions.cpp @@ -29,391 +29,393 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -void GEntity_ThinkFunc(gentity_t *self) -{ -#define THINKCASE(blah) case thinkF_ ## blah: blah(self); break; +void GEntity_ThinkFunc(gentity_t *self) { +#define THINKCASE(blah) \ + case thinkF_##blah: \ + blah(self); \ + break; - switch (self->e_ThinkFunc) - { + switch (self->e_ThinkFunc) { case thinkF_NULL: break; - THINKCASE( funcBBrushDieGo ) - THINKCASE( ExplodeDeath ) - THINKCASE( RespawnItem ) - THINKCASE( G_FreeEntity ) - THINKCASE( FinishSpawningItem ) - THINKCASE( locateCamera ) - THINKCASE( G_RunObject ) - THINKCASE( ReturnToPos1 ) - THINKCASE( Use_BinaryMover_Go ) - THINKCASE( Think_MatchTeam ) - THINKCASE( Think_BeginMoving ) - THINKCASE( Think_SetupTrainTargets ) - THINKCASE( Think_SpawnNewDoorTrigger ) - THINKCASE( ref_link ) - THINKCASE( Think_Target_Delay ) - THINKCASE( target_laser_think ) - THINKCASE( target_laser_start ) - THINKCASE( target_location_linkup ) - THINKCASE( scriptrunner_run ) - THINKCASE( multi_wait ) - THINKCASE( multi_trigger_run ) - THINKCASE( trigger_always_think ) - THINKCASE( AimAtTarget ) - THINKCASE( func_timer_think ) - THINKCASE( NPC_RemoveBody ) - THINKCASE( Disappear ) - THINKCASE( NPC_Think ) - THINKCASE( NPC_Spawn_Go ) - THINKCASE( NPC_Begin ) - THINKCASE( moverCallback ) - THINKCASE( anglerCallback ) - // This RemoveOwner need to exist here anymore??? - THINKCASE( RemoveOwner ) - THINKCASE( MakeOwnerInvis ) - THINKCASE( MakeOwnerEnergy ) - THINKCASE( func_usable_think ) - THINKCASE( misc_dlight_think ) - THINKCASE( health_think ) - THINKCASE( ammo_think ) - THINKCASE( trigger_teleporter_find_closest_portal ) - THINKCASE( thermalDetonatorExplode ) - THINKCASE( WP_ThermalThink ) - THINKCASE( trigger_hurt_reset ) - THINKCASE( turret_base_think ) - THINKCASE( turret_head_think ) - THINKCASE( laser_arm_fire ) - THINKCASE( laser_arm_start ) - THINKCASE( trigger_visible_check_player_visibility ) - THINKCASE( target_relay_use_go ) - THINKCASE( trigger_cleared_fire ) - THINKCASE( MoveOwner ) - THINKCASE( SolidifyOwner ) - THINKCASE( cycleCamera ) - THINKCASE( spawn_ammo_crystal_trigger ) - THINKCASE( NPC_ShySpawn ) - THINKCASE( func_wait_return_solid ) - THINKCASE( InflateOwner ) - THINKCASE( mega_ammo_think ) - THINKCASE( misc_replicator_item_finish_spawn ) - THINKCASE( fx_runner_link ) - THINKCASE( fx_runner_think ) - THINKCASE( fx_rain_think ) // delay flagging entities as portal entities (for sky portals) - THINKCASE( removeBoltSurface) - THINKCASE( set_MiscAnim) - THINKCASE( LimbThink ) - THINKCASE( laserTrapThink ) - THINKCASE( TieFighterThink ) - THINKCASE( TieBomberThink ) - THINKCASE( rocketThink ) - THINKCASE( prox_mine_think ) - THINKCASE( emplaced_blow ) - THINKCASE( WP_Explode ) - THINKCASE( pas_think ) // personal assault sentry - THINKCASE( ion_cannon_think ) - THINKCASE( maglock_link ) - THINKCASE( WP_flechette_alt_blow ) - THINKCASE( WP_prox_mine_think ) - THINKCASE( camera_aim ) - THINKCASE( fx_explosion_trail_link ) - THINKCASE( fx_explosion_trail_think ) - THINKCASE( fx_target_beam_link ) - THINKCASE( fx_target_beam_think ) - THINKCASE( spotlight_think ) - THINKCASE( spotlight_link ) - THINKCASE( trigger_push_checkclear ) - THINKCASE( DEMP2_AltDetonate ) - THINKCASE( DEMP2_AltRadiusDamage ) - THINKCASE( panel_turret_think ) - THINKCASE( welder_think ) - THINKCASE( gas_random_jet ) - THINKCASE( poll_converter ) // dumb loop sound handling - THINKCASE( spawn_rack_goods ) // delay spawn of goods to help on ents - THINKCASE( NoghriGasCloudThink ) - - THINKCASE( G_PortalifyEntities ) // delay flagging entities as portal entities (for sky portals) - - THINKCASE( misc_weapon_shooter_aim ) - THINKCASE( misc_weapon_shooter_fire ) - - THINKCASE( beacon_think ) + THINKCASE(funcBBrushDieGo) + THINKCASE(ExplodeDeath) + THINKCASE(RespawnItem) + THINKCASE(G_FreeEntity) + THINKCASE(FinishSpawningItem) + THINKCASE(locateCamera) + THINKCASE(G_RunObject) + THINKCASE(ReturnToPos1) + THINKCASE(Use_BinaryMover_Go) + THINKCASE(Think_MatchTeam) + THINKCASE(Think_BeginMoving) + THINKCASE(Think_SetupTrainTargets) + THINKCASE(Think_SpawnNewDoorTrigger) + THINKCASE(ref_link) + THINKCASE(Think_Target_Delay) + THINKCASE(target_laser_think) + THINKCASE(target_laser_start) + THINKCASE(target_location_linkup) + THINKCASE(scriptrunner_run) + THINKCASE(multi_wait) + THINKCASE(multi_trigger_run) + THINKCASE(trigger_always_think) + THINKCASE(AimAtTarget) + THINKCASE(func_timer_think) + THINKCASE(NPC_RemoveBody) + THINKCASE(Disappear) + THINKCASE(NPC_Think) + THINKCASE(NPC_Spawn_Go) + THINKCASE(NPC_Begin) + THINKCASE(moverCallback) + THINKCASE(anglerCallback) + // This RemoveOwner need to exist here anymore??? + THINKCASE(RemoveOwner) + THINKCASE(MakeOwnerInvis) + THINKCASE(MakeOwnerEnergy) + THINKCASE(func_usable_think) + THINKCASE(misc_dlight_think) + THINKCASE(health_think) + THINKCASE(ammo_think) + THINKCASE(trigger_teleporter_find_closest_portal) + THINKCASE(thermalDetonatorExplode) + THINKCASE(WP_ThermalThink) + THINKCASE(trigger_hurt_reset) + THINKCASE(turret_base_think) + THINKCASE(turret_head_think) + THINKCASE(laser_arm_fire) + THINKCASE(laser_arm_start) + THINKCASE(trigger_visible_check_player_visibility) + THINKCASE(target_relay_use_go) + THINKCASE(trigger_cleared_fire) + THINKCASE(MoveOwner) + THINKCASE(SolidifyOwner) + THINKCASE(cycleCamera) + THINKCASE(spawn_ammo_crystal_trigger) + THINKCASE(NPC_ShySpawn) + THINKCASE(func_wait_return_solid) + THINKCASE(InflateOwner) + THINKCASE(mega_ammo_think) + THINKCASE(misc_replicator_item_finish_spawn) + THINKCASE(fx_runner_link) + THINKCASE(fx_runner_think) + THINKCASE(fx_rain_think) // delay flagging entities as portal entities (for sky portals) + THINKCASE(removeBoltSurface) + THINKCASE(set_MiscAnim) + THINKCASE(LimbThink) + THINKCASE(laserTrapThink) + THINKCASE(TieFighterThink) + THINKCASE(TieBomberThink) + THINKCASE(rocketThink) + THINKCASE(prox_mine_think) + THINKCASE(emplaced_blow) + THINKCASE(WP_Explode) + THINKCASE(pas_think) // personal assault sentry + THINKCASE(ion_cannon_think) + THINKCASE(maglock_link) + THINKCASE(WP_flechette_alt_blow) + THINKCASE(WP_prox_mine_think) + THINKCASE(camera_aim) + THINKCASE(fx_explosion_trail_link) + THINKCASE(fx_explosion_trail_think) + THINKCASE(fx_target_beam_link) + THINKCASE(fx_target_beam_think) + THINKCASE(spotlight_think) + THINKCASE(spotlight_link) + THINKCASE(trigger_push_checkclear) + THINKCASE(DEMP2_AltDetonate) + THINKCASE(DEMP2_AltRadiusDamage) + THINKCASE(panel_turret_think) + THINKCASE(welder_think) + THINKCASE(gas_random_jet) + THINKCASE(poll_converter) // dumb loop sound handling + THINKCASE(spawn_rack_goods) // delay spawn of goods to help on ents + THINKCASE(NoghriGasCloudThink) + + THINKCASE(G_PortalifyEntities) // delay flagging entities as portal entities (for sky portals) + + THINKCASE(misc_weapon_shooter_aim) + THINKCASE(misc_weapon_shooter_fire) + + THINKCASE(beacon_think) default: - Com_Error(ERR_DROP, "GEntity_ThinkFunc: case %d not handled!\n",self->e_ThinkFunc); + Com_Error(ERR_DROP, "GEntity_ThinkFunc: case %d not handled!\n", self->e_ThinkFunc); break; } } // note different switch-case code for CEntity as opposed to GEntity (CEntity goes through parent GEntity first)... // -void CEntity_ThinkFunc(centity_s *cent) -{ -#define CLTHINKCASE(blah) case clThinkF_ ## blah: blah(cent); break; +void CEntity_ThinkFunc(centity_s *cent) { +#define CLTHINKCASE(blah) \ + case clThinkF_##blah: \ + blah(cent); \ + break; - switch (cent->gent->e_clThinkFunc) - { + switch (cent->gent->e_clThinkFunc) { case clThinkF_NULL: break; - CLTHINKCASE( CG_DLightThink ) - CLTHINKCASE( CG_MatrixEffect ) - CLTHINKCASE( CG_Limb ) + CLTHINKCASE(CG_DLightThink) + CLTHINKCASE(CG_MatrixEffect) + CLTHINKCASE(CG_Limb) default: - Com_Error(ERR_DROP, "CEntity_ThinkFunc: case %d not handled!\n",cent->gent->e_clThinkFunc); + Com_Error(ERR_DROP, "CEntity_ThinkFunc: case %d not handled!\n", cent->gent->e_clThinkFunc); break; } } +void GEntity_ReachedFunc(gentity_t *self) { +#define REACHEDCASE(blah) \ + case reachedF_##blah: \ + blah(self); \ + break; -void GEntity_ReachedFunc(gentity_t *self) -{ -#define REACHEDCASE(blah) case reachedF_ ## blah: blah(self); break; - - switch (self->e_ReachedFunc) - { + switch (self->e_ReachedFunc) { case reachedF_NULL: break; - REACHEDCASE( Reached_BinaryMover ) - REACHEDCASE( Reached_Train ) - REACHEDCASE( moverCallback ) - REACHEDCASE( moveAndRotateCallback ) + REACHEDCASE(Reached_BinaryMover) + REACHEDCASE(Reached_Train) + REACHEDCASE(moverCallback) + REACHEDCASE(moveAndRotateCallback) default: - Com_Error(ERR_DROP, "GEntity_ReachedFunc: case %d not handled!\n",self->e_ReachedFunc); + Com_Error(ERR_DROP, "GEntity_ReachedFunc: case %d not handled!\n", self->e_ReachedFunc); break; } } +void GEntity_BlockedFunc(gentity_t *self, gentity_t *other) { +#define BLOCKEDCASE(blah) \ + case blockedF_##blah: \ + blah(self, other); \ + break; - -void GEntity_BlockedFunc(gentity_t *self, gentity_t *other) -{ -#define BLOCKEDCASE(blah) case blockedF_ ## blah: blah(self,other); break; - - switch (self->e_BlockedFunc) - { + switch (self->e_BlockedFunc) { case blockedF_NULL: break; - BLOCKEDCASE( Blocked_Door ) - BLOCKEDCASE( Blocked_Mover ) + BLOCKEDCASE(Blocked_Door) + BLOCKEDCASE(Blocked_Mover) default: - Com_Error(ERR_DROP, "GEntity_BlockedFunc: case %d not handled!\n",self->e_BlockedFunc); + Com_Error(ERR_DROP, "GEntity_BlockedFunc: case %d not handled!\n", self->e_BlockedFunc); break; } } -void GEntity_TouchFunc(gentity_t *self, gentity_t *other, trace_t *trace) -{ -#define TOUCHCASE(blah) case touchF_ ## blah: blah(self,other,trace); break; +void GEntity_TouchFunc(gentity_t *self, gentity_t *other, trace_t *trace) { +#define TOUCHCASE(blah) \ + case touchF_##blah: \ + blah(self, other, trace); \ + break; - switch (self->e_TouchFunc) - { + switch (self->e_TouchFunc) { case touchF_NULL: break; - TOUCHCASE( Touch_Item ) - TOUCHCASE( teleporter_touch ) - TOUCHCASE( charge_stick ) - TOUCHCASE( Touch_DoorTrigger ) - TOUCHCASE( Touch_PlatCenterTrigger ) - TOUCHCASE( Touch_Plat ) - TOUCHCASE( Touch_Button ) - TOUCHCASE( Touch_Multi ) - TOUCHCASE( trigger_push_touch ) - TOUCHCASE( trigger_teleporter_touch ) - TOUCHCASE( hurt_touch ) - TOUCHCASE( NPC_Touch ) - TOUCHCASE( touch_ammo_crystal_tigger ) - TOUCHCASE( funcBBrushTouch ) - TOUCHCASE( touchLaserTrap ) - TOUCHCASE( prox_mine_stick ) - TOUCHCASE( func_rotating_touch ) - TOUCHCASE( TouchTieBomb ) + TOUCHCASE(Touch_Item) + TOUCHCASE(teleporter_touch) + TOUCHCASE(charge_stick) + TOUCHCASE(Touch_DoorTrigger) + TOUCHCASE(Touch_PlatCenterTrigger) + TOUCHCASE(Touch_Plat) + TOUCHCASE(Touch_Button) + TOUCHCASE(Touch_Multi) + TOUCHCASE(trigger_push_touch) + TOUCHCASE(trigger_teleporter_touch) + TOUCHCASE(hurt_touch) + TOUCHCASE(NPC_Touch) + TOUCHCASE(touch_ammo_crystal_tigger) + TOUCHCASE(funcBBrushTouch) + TOUCHCASE(touchLaserTrap) + TOUCHCASE(prox_mine_stick) + TOUCHCASE(func_rotating_touch) + TOUCHCASE(TouchTieBomb) default: - Com_Error(ERR_DROP, "GEntity_TouchFunc: case %d not handled!\n",self->e_TouchFunc); + Com_Error(ERR_DROP, "GEntity_TouchFunc: case %d not handled!\n", self->e_TouchFunc); } } -void GEntity_UseFunc(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( !self || (self->svFlags&SVF_INACTIVE) ) - { +void GEntity_UseFunc(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!self || (self->svFlags & SVF_INACTIVE)) { return; } -#define USECASE(blah) case useF_ ## blah: blah(self,other,activator); break; +#define USECASE(blah) \ + case useF_##blah: \ + blah(self, other, activator); \ + break; - switch (self->e_UseFunc) - { + switch (self->e_UseFunc) { case useF_NULL: break; - USECASE( funcBBrushUse ) - USECASE( misc_model_use ) - USECASE( Use_Item ) - USECASE( Use_Shooter ) - USECASE( GoExplodeDeath ) - USECASE( Use_BinaryMover ) - USECASE( use_wall ) - USECASE( Use_Target_Give ) - USECASE( Use_Target_Delay ) - USECASE( Use_Target_Score ) - USECASE( Use_Target_Print ) - USECASE( Use_Target_Speaker ) - USECASE( target_laser_use ) - USECASE( target_relay_use ) - USECASE( target_kill_use ) - USECASE( target_counter_use ) - USECASE( target_random_use ) - USECASE( target_scriptrunner_use ) - USECASE( target_gravity_change_use ) - USECASE( target_friction_change_use ) - USECASE( target_teleporter_use ) - USECASE( Use_Multi ) - USECASE( Use_target_push ) - USECASE( hurt_use ) - USECASE( func_timer_use ) - USECASE( trigger_entdist_use ) - USECASE( func_usable_use ) - USECASE( target_activate_use ) - USECASE( target_deactivate_use ) - USECASE( NPC_Use ) - USECASE( NPC_Spawn ) - USECASE( misc_dlight_use ) - USECASE( health_use ) - USECASE( ammo_use ) - USECASE( mega_ammo_use ) - USECASE( target_level_change_use ) - USECASE( target_change_parm_use ) - USECASE( turret_base_use ) - USECASE( laser_arm_use ) - USECASE( func_static_use ) - USECASE( target_play_music_use ) - USECASE( misc_model_useup ) - USECASE( misc_portal_use ) - USECASE( target_autosave_use ) - USECASE( switch_models ) - USECASE( misc_replicator_item_spawn ) - USECASE( misc_replicator_item_remove ) - USECASE( target_secret_use) - USECASE( func_bobbing_use ) - USECASE( func_rotating_use ) - USECASE( fx_runner_use ) - USECASE( funcGlassUse ) - USECASE( TrainUse ) - USECASE( misc_trip_mine_activate ) - USECASE( emplaced_gun_use ) - USECASE( shield_power_converter_use ) - USECASE( ammo_power_converter_use ) - USECASE( bomb_planted_use ) - USECASE( beacon_use ) - USECASE( security_panel_use ) - USECASE( ion_cannon_use ) - USECASE( camera_use ) - USECASE( fx_explosion_trail_use ) - USECASE( fx_target_beam_use ) - USECASE( sentry_use ) - USECASE( spotlight_use ) - USECASE( misc_atst_use ) - USECASE( panel_turret_use ) - USECASE( welder_use ) - USECASE( jabba_cam_use ) - USECASE( misc_use ) - USECASE( pas_use ) - USECASE( item_spawn_use ) - USECASE( NPC_VehicleSpawnUse ) - USECASE( misc_weapon_shooter_use ) - USECASE( eweb_use ) - USECASE( TieFighterUse ); + USECASE(funcBBrushUse) + USECASE(misc_model_use) + USECASE(Use_Item) + USECASE(Use_Shooter) + USECASE(GoExplodeDeath) + USECASE(Use_BinaryMover) + USECASE(use_wall) + USECASE(Use_Target_Give) + USECASE(Use_Target_Delay) + USECASE(Use_Target_Score) + USECASE(Use_Target_Print) + USECASE(Use_Target_Speaker) + USECASE(target_laser_use) + USECASE(target_relay_use) + USECASE(target_kill_use) + USECASE(target_counter_use) + USECASE(target_random_use) + USECASE(target_scriptrunner_use) + USECASE(target_gravity_change_use) + USECASE(target_friction_change_use) + USECASE(target_teleporter_use) + USECASE(Use_Multi) + USECASE(Use_target_push) + USECASE(hurt_use) + USECASE(func_timer_use) + USECASE(trigger_entdist_use) + USECASE(func_usable_use) + USECASE(target_activate_use) + USECASE(target_deactivate_use) + USECASE(NPC_Use) + USECASE(NPC_Spawn) + USECASE(misc_dlight_use) + USECASE(health_use) + USECASE(ammo_use) + USECASE(mega_ammo_use) + USECASE(target_level_change_use) + USECASE(target_change_parm_use) + USECASE(turret_base_use) + USECASE(laser_arm_use) + USECASE(func_static_use) + USECASE(target_play_music_use) + USECASE(misc_model_useup) + USECASE(misc_portal_use) + USECASE(target_autosave_use) + USECASE(switch_models) + USECASE(misc_replicator_item_spawn) + USECASE(misc_replicator_item_remove) + USECASE(target_secret_use) + USECASE(func_bobbing_use) + USECASE(func_rotating_use) + USECASE(fx_runner_use) + USECASE(funcGlassUse) + USECASE(TrainUse) + USECASE(misc_trip_mine_activate) + USECASE(emplaced_gun_use) + USECASE(shield_power_converter_use) + USECASE(ammo_power_converter_use) + USECASE(bomb_planted_use) + USECASE(beacon_use) + USECASE(security_panel_use) + USECASE(ion_cannon_use) + USECASE(camera_use) + USECASE(fx_explosion_trail_use) + USECASE(fx_target_beam_use) + USECASE(sentry_use) + USECASE(spotlight_use) + USECASE(misc_atst_use) + USECASE(panel_turret_use) + USECASE(welder_use) + USECASE(jabba_cam_use) + USECASE(misc_use) + USECASE(pas_use) + USECASE(item_spawn_use) + USECASE(NPC_VehicleSpawnUse) + USECASE(misc_weapon_shooter_use) + USECASE(eweb_use) + USECASE(TieFighterUse); default: - Com_Error(ERR_DROP, "GEntity_UseFunc: case %d not handled!\n",self->e_UseFunc); + Com_Error(ERR_DROP, "GEntity_UseFunc: case %d not handled!\n", self->e_UseFunc); } } -void GEntity_PainFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod,int hitLoc) -{ -#define PAINCASE(blah) case painF_ ## blah: blah(self,inflictor,attacker,point,damage,mod,hitLoc); break; +void GEntity_PainFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { +#define PAINCASE(blah) \ + case painF_##blah: \ + blah(self, inflictor, attacker, point, damage, mod, hitLoc); \ + break; - switch (self->e_PainFunc) - { + switch (self->e_PainFunc) { case painF_NULL: break; - PAINCASE( funcBBrushPain ) - PAINCASE( misc_model_breakable_pain ) - PAINCASE( NPC_Pain ) - PAINCASE( station_pain ) - PAINCASE( func_usable_pain ) - PAINCASE( NPC_ATST_Pain ) - PAINCASE( NPC_ST_Pain ) - PAINCASE( NPC_Jedi_Pain ) - PAINCASE( NPC_Droid_Pain ) - PAINCASE( NPC_Probe_Pain ) - PAINCASE( NPC_MineMonster_Pain ) - PAINCASE( NPC_Howler_Pain ) - PAINCASE( NPC_Rancor_Pain ) - PAINCASE( NPC_Wampa_Pain ) - PAINCASE( NPC_SandCreature_Pain ) - PAINCASE( NPC_Seeker_Pain ) - PAINCASE( NPC_Remote_Pain ) - PAINCASE( emplaced_gun_pain ) - PAINCASE( NPC_Mark1_Pain ) - PAINCASE( NPC_Sentry_Pain ) - PAINCASE( NPC_Mark2_Pain ) - PAINCASE( PlayerPain ) - PAINCASE( GasBurst ) - PAINCASE( CrystalCratePain ) - PAINCASE( TurretPain ) - PAINCASE( eweb_pain ) + PAINCASE(funcBBrushPain) + PAINCASE(misc_model_breakable_pain) + PAINCASE(NPC_Pain) + PAINCASE(station_pain) + PAINCASE(func_usable_pain) + PAINCASE(NPC_ATST_Pain) + PAINCASE(NPC_ST_Pain) + PAINCASE(NPC_Jedi_Pain) + PAINCASE(NPC_Droid_Pain) + PAINCASE(NPC_Probe_Pain) + PAINCASE(NPC_MineMonster_Pain) + PAINCASE(NPC_Howler_Pain) + PAINCASE(NPC_Rancor_Pain) + PAINCASE(NPC_Wampa_Pain) + PAINCASE(NPC_SandCreature_Pain) + PAINCASE(NPC_Seeker_Pain) + PAINCASE(NPC_Remote_Pain) + PAINCASE(emplaced_gun_pain) + PAINCASE(NPC_Mark1_Pain) + PAINCASE(NPC_Sentry_Pain) + PAINCASE(NPC_Mark2_Pain) + PAINCASE(PlayerPain) + PAINCASE(GasBurst) + PAINCASE(CrystalCratePain) + PAINCASE(TurretPain) + PAINCASE(eweb_pain) default: - Com_Error(ERR_DROP, "GEntity_PainFunc: case %d not handled!\n",self->e_PainFunc); + Com_Error(ERR_DROP, "GEntity_PainFunc: case %d not handled!\n", self->e_PainFunc); } } +void GEntity_DieFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { +#define DIECASE(blah) \ + case dieF_##blah: \ + blah(self, inflictor, attacker, damage, mod, dFlags, hitLoc); \ + break; -void GEntity_DieFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) -{ -#define DIECASE(blah) case dieF_ ## blah: blah(self,inflictor,attacker,damage,mod,dFlags,hitLoc); break; - - switch (self->e_DieFunc) - { + switch (self->e_DieFunc) { case dieF_NULL: break; - DIECASE( funcBBrushDie ) - DIECASE( misc_model_breakable_die ) - DIECASE( misc_model_cargo_die ) - DIECASE( func_train_die ) - DIECASE( player_die ) - DIECASE( ExplodeDeath_Wait ) - DIECASE( ExplodeDeath ) - DIECASE( func_usable_die ) - DIECASE( turret_die ) - DIECASE( funcGlassDie ) -// DIECASE( laserTrapDelayedExplode ) - DIECASE( emplaced_gun_die ) - DIECASE( WP_ExplosiveDie ) - DIECASE( ion_cannon_die ) - DIECASE( maglock_die ) - DIECASE( camera_die ) - DIECASE( Mark1_die ) - DIECASE( Interrogator_die ) - DIECASE( misc_atst_die ) - DIECASE( misc_panel_turret_die ) - DIECASE( thermal_die ) - DIECASE( eweb_die ) + DIECASE(funcBBrushDie) + DIECASE(misc_model_breakable_die) + DIECASE(misc_model_cargo_die) + DIECASE(func_train_die) + DIECASE(player_die) + DIECASE(ExplodeDeath_Wait) + DIECASE(ExplodeDeath) + DIECASE(func_usable_die) + DIECASE(turret_die) + DIECASE(funcGlassDie) + // DIECASE( laserTrapDelayedExplode ) + DIECASE(emplaced_gun_die) + DIECASE(WP_ExplosiveDie) + DIECASE(ion_cannon_die) + DIECASE(maglock_die) + DIECASE(camera_die) + DIECASE(Mark1_die) + DIECASE(Interrogator_die) + DIECASE(misc_atst_die) + DIECASE(misc_panel_turret_die) + DIECASE(thermal_die) + DIECASE(eweb_die) default: - Com_Error(ERR_DROP, "GEntity_DieFunc: case %d not handled!\n",self->e_DieFunc); + Com_Error(ERR_DROP, "GEntity_DieFunc: case %d not handled!\n", self->e_DieFunc); } } //////////////////// eof ///////////////////// - diff --git a/code/game/g_fx.cpp b/code/game/g_fx.cpp index 41fe80fb81..49a513c9cb 100644 --- a/code/game/g_fx.cpp +++ b/code/game/g_fx.cpp @@ -24,13 +24,13 @@ along with this program; if not, see . #include "g_functions.h" #include "b_local.h" -extern int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ); +extern int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create); #define FX_ENT_RADIUS 32 -extern int BMS_START; -extern int BMS_MID; -extern int BMS_END; +extern int BMS_START; +extern int BMS_MID; +extern int BMS_END; //---------------------------------------------------------- @@ -53,105 +53,88 @@ Runs the specified effect, can also be targeted at an info_notnull to orient the #define FX_RUNNER_RESERVED 0x800000 //---------------------------------------------------------- -void fx_runner_think( gentity_t *ent ) -{ +void fx_runner_think(gentity_t *ent) { vec3_t temp; - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); // call the effect with the desired position and orientation - G_AddEvent( ent, EV_PLAY_EFFECT, ent->fxID ); + G_AddEvent(ent, EV_PLAY_EFFECT, ent->fxID); // Assume angles, we'll do a cross product on the other end to finish up - AngleVectors( ent->currentAngles, ent->pos3, NULL, NULL ); - MakeNormalVectors( ent->pos3, ent->pos4, temp ); // there IS a reason this is done...it's so that it doesn't break every effect in the game... + AngleVectors(ent->currentAngles, ent->pos3, NULL, NULL); + MakeNormalVectors(ent->pos3, ent->pos4, temp); // there IS a reason this is done...it's so that it doesn't break every effect in the game... ent->nextthink = level.time + ent->delay + Q_flrand(0.0f, 1.0f) * ent->random; - if ( ent->spawnflags & 4 ) // damage + if (ent->spawnflags & 4) // damage { - G_RadiusDamage( ent->currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, MOD_UNKNOWN ); + G_RadiusDamage(ent->currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, MOD_UNKNOWN); } - if ( ent->target2 ) - { + if (ent->target2) { // let our target know that we have spawned an effect - G_UseTargets2( ent, ent, ent->target2 ); + G_UseTargets2(ent, ent, ent->target2); } - if ( !(ent->spawnflags & 2 ) && !ent->s.loopSound ) // NOT ONESHOT...this is an assy thing to do + if (!(ent->spawnflags & 2) && !ent->s.loopSound) // NOT ONESHOT...this is an assy thing to do { - if ( VALIDSTRING( ent->soundSet ) == true ) - { - ent->s.loopSound = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + if (VALIDSTRING(ent->soundSet) == true) { + ent->s.loopSound = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( ent->s.loopSound < 0 ) - { + if (ent->s.loopSound < 0) { ent->s.loopSound = 0; } } } - } //---------------------------------------------------------- -void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if (self->s.isPortalEnt) - { //rww - mark it as broadcast upon first use if it's within the area of a skyportal +void fx_runner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->s.isPortalEnt) { // rww - mark it as broadcast upon first use if it's within the area of a skyportal self->svFlags |= SVF_BROADCAST; } - if ( self->spawnflags & 2 ) // ONESHOT + if (self->spawnflags & 2) // ONESHOT { // call the effect with the desired position and orientation, as a safety thing, // make sure we aren't thinking at all. - fx_runner_think( self ); + fx_runner_think(self); self->nextthink = -1; - if ( self->target2 ) - { + if (self->target2) { // let our target know that we have spawned an effect - G_UseTargets2( self, self, self->target2 ); + G_UseTargets2(self, self, self->target2); } - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); } - } - else - { + } else { // ensure we are working with the right think function self->e_ThinkFunc = thinkF_fx_runner_think; // toggle our state - if ( self->nextthink == -1 ) - { + if (self->nextthink == -1) { // NOTE: we fire the effect immediately on use, the fx_runner_think func will set // up the nextthink time. - fx_runner_think( self ); + fx_runner_think(self); - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - self->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + self->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); - if ( self->s.loopSound < 0 ) - { + if (self->s.loopSound < 0) { self->s.loopSound = 0; } } - } - else - { + } else { // turn off for now self->nextthink = -1; - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_END )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_END)); self->s.loopSound = 0; } } @@ -159,61 +142,50 @@ void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } //---------------------------------------------------------- -void fx_runner_link( gentity_t *ent ) -{ - vec3_t dir; +void fx_runner_link(gentity_t *ent) { + vec3_t dir; - if ( ent->target ) - { + if (ent->target) { // try to use the target to override the orientation - gentity_t *target = NULL; + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { + if (!target) { // Bah, no good, dump a warning, but continue on and use the UP vector - Com_Printf( "fx_runner_link: target specified but not found: %s\n", ent->target ); - Com_Printf( " -assuming UP orientation.\n" ); - } - else - { + Com_Printf("fx_runner_link: target specified but not found: %s\n", ent->target); + Com_Printf(" -assuming UP orientation.\n"); + } else { // Our target is valid so let's override the default UP vector - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); } } // don't really do anything with this right now other than do a check to warn the designers if the target2 is bogus - if ( ent->target2 ) - { - gentity_t *target = NULL; + if (ent->target2) { + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target2 ); + target = G_Find(target, FOFS(targetname), ent->target2); - if ( !target ) - { + if (!target) { // Target2 is bogus, but we can still continue - Com_Printf( "fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2 ); + Com_Printf("fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2); } } - G_SetAngles( ent, ent->s.angles ); + G_SetAngles(ent, ent->s.angles); - if ( ent->spawnflags & 1 || ent->spawnflags & 2 ) // STARTOFF || ONESHOT + if (ent->spawnflags & 1 || ent->spawnflags & 2) // STARTOFF || ONESHOT { // We won't even consider thinking until we are used ent->nextthink = -1; - } - else - { - if ( VALIDSTRING( ent->soundSet ) == true ) - { - ent->s.loopSound = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + } else { + if (VALIDSTRING(ent->soundSet) == true) { + ent->s.loopSound = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( ent->s.loopSound < 0 ) - { + if (ent->s.loopSound < 0) { ent->s.loopSound = 0; } } @@ -224,37 +196,33 @@ void fx_runner_link( gentity_t *ent ) } // make us useable if we can be targeted - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_fx_runner_use; } } //---------------------------------------------------------- -void SP_fx_runner( gentity_t *ent ) -{ +void SP_fx_runner(gentity_t *ent) { // Get our defaults - G_SpawnInt( "delay", "200", &ent->delay ); - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnInt( "splashRadius", "16", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "5", &ent->splashDamage ); + G_SpawnInt("delay", "200", &ent->delay); + G_SpawnFloat("random", "0", &ent->random); + G_SpawnInt("splashRadius", "16", &ent->splashRadius); + G_SpawnInt("splashDamage", "5", &ent->splashDamage); - if ( !G_SpawnAngleHack( "angle", "0", ent->s.angles )) - { + if (!G_SpawnAngleHack("angle", "0", ent->s.angles)) { // didn't have angles, so give us the default of up - VectorSet( ent->s.angles, -90, 0, 0 ); + VectorSet(ent->s.angles, -90, 0, 0); } - if ( !ent->fxFile ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin) ); - G_FreeEntity( ent ); + if (!ent->fxFile) { + gi.Printf(S_COLOR_RED "ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin)); + G_FreeEntity(ent); return; } // Try and associate an effect file, unfortunately we won't know if this worked or not // until the CGAME trys to register it... - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); ent->s.eType = ET_MOVER; @@ -263,52 +231,39 @@ void SP_fx_runner( gentity_t *ent ) ent->nextthink = level.time + 400; // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - /*QUAKED fx_snow (1 0 0) (-16 -16 -16) (16 16 16) LIGHT MEDIUM HEAVY MISTY_FOG This world effect will spawn snow globally into the level. */ -void SP_CreateSnow( gentity_t *ent ) -{ - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); - if ( r_weatherScale->value == 0.0f ) - { +void SP_CreateSnow(gentity_t *ent) { + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); + if (r_weatherScale->value == 0.0f) { return; } - // Different Types Of Rain //------------------------- - if (ent->spawnflags & 1) - { + if (ent->spawnflags & 1) { G_FindConfigstringIndex("lightsnow", CS_WORLD_FX, MAX_WORLD_FX, qtrue); - } - else if (ent->spawnflags & 2) - { + } else if (ent->spawnflags & 2) { G_FindConfigstringIndex("snow", CS_WORLD_FX, MAX_WORLD_FX, qtrue); - } - else if (ent->spawnflags & 4) - { + } else if (ent->spawnflags & 4) { G_FindConfigstringIndex("heavysnow", CS_WORLD_FX, MAX_WORLD_FX, qtrue); - } - else - { + } else { G_FindConfigstringIndex("snow", CS_WORLD_FX, MAX_WORLD_FX, qtrue); G_FindConfigstringIndex("fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } - // MISTY FOG //=========== - if (ent->spawnflags & 8) - { + if (ent->spawnflags & 8) { G_FindConfigstringIndex("fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } } @@ -324,62 +279,53 @@ SWIRLING causes random swirls of wind "angles" the direction for constant wind "speed" the speed for constant wind */ -void SP_CreateWind( gentity_t *ent ) -{ - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); - if ( r_weatherScale->value <= 0.0f ) - { +void SP_CreateWind(gentity_t *ent) { + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); + if (r_weatherScale->value <= 0.0f) { return; } - char temp[256]; + char temp[256]; // Normal Wind //------------- - if (ent->spawnflags & 1) - { + if (ent->spawnflags & 1) { G_FindConfigstringIndex("wind", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // Constant Wind //--------------- - if (ent->spawnflags & 2) - { - vec3_t windDir; + if (ent->spawnflags & 2) { + vec3_t windDir; AngleVectors(ent->s.angles, windDir, 0, 0); - G_SpawnFloat( "speed", "500", &ent->speed ); + G_SpawnFloat("speed", "500", &ent->speed); VectorScale(windDir, ent->speed, windDir); - sprintf( temp, "constantwind ( %f %f %f )", windDir[0], windDir[1], windDir[2] ); + sprintf(temp, "constantwind ( %f %f %f )", windDir[0], windDir[1], windDir[2]); G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // Gusting Wind //-------------- - if (ent->spawnflags & 4) - { + if (ent->spawnflags & 4) { G_FindConfigstringIndex("gustingwind", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // Swirling Wind //--------------- - if (ent->spawnflags & 8) - { + if (ent->spawnflags & 8) { G_FindConfigstringIndex("swirlingwind", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } - // MISTY FOG //=========== - if (ent->spawnflags & 32) - { + if (ent->spawnflags & 32) { G_FindConfigstringIndex("fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // MISTY FOG //=========== - if (ent->spawnflags & 64) - { + if (ent->spawnflags & 64) { G_FindConfigstringIndex("light_fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } } @@ -390,32 +336,25 @@ Generates local wind forces "angles" the direction for constant wind "speed" the speed for constant wind */ -void SP_CreateWindZone( gentity_t *ent ) -{ - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); - if ( r_weatherScale->value <= 0.0f ) - { +void SP_CreateWindZone(gentity_t *ent) { + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); + if (r_weatherScale->value <= 0.0f) { return; } gi.SetBrushModel(ent, ent->model); - vec3_t windDir; - AngleVectors(ent->s.angles, windDir, 0, 0); - G_SpawnFloat( "speed", "500", &ent->speed ); + vec3_t windDir; + AngleVectors(ent->s.angles, windDir, 0, 0); + G_SpawnFloat("speed", "500", &ent->speed); VectorScale(windDir, ent->speed, windDir); - char temp[256]; - sprintf( temp, "windzone ( %f %f %f ) ( %f %f %f ) ( %f %f %f )", - ent->mins[0], ent->mins[1], ent->mins[2], - ent->maxs[0], ent->maxs[1], ent->maxs[2], - windDir[0], windDir[1], windDir[2] - ); + char temp[256]; + sprintf(temp, "windzone ( %f %f %f ) ( %f %f %f ) ( %f %f %f )", ent->mins[0], ent->mins[1], ent->mins[2], ent->maxs[0], ent->maxs[1], ent->maxs[2], + windDir[0], windDir[1], windDir[2]); G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); } - - /*QUAKED fx_rain (1 0 0) (-16 -16 -16) (16 16 16) LIGHT MEDIUM HEAVY ACID OUTSIDE_SHAKE MISTY_FOG This world effect will spawn rain globally into the level. @@ -438,65 +377,49 @@ The following fields are for lightning: //---------------------------------------------------------- //---------------------------------------------------------- -extern void G_SoundAtSpot( vec3_t org, int soundIndex, qboolean broadcast ); +extern void G_SoundAtSpot(vec3_t org, int soundIndex, qboolean broadcast); -void fx_rain_think( gentity_t *ent ) -{ - if (player) - { - if (ent->count!=0) - { +void fx_rain_think(gentity_t *ent) { + if (player) { + if (ent->count != 0) { ent->count--; - if (ent->count==0 || (ent->count%2)==0) - { - gi.WE_SetTempGlobalFogColor(ent->pos2); // Turn Off - if (ent->count==0) - { + if (ent->count == 0 || (ent->count % 2) == 0) { + gi.WE_SetTempGlobalFogColor(ent->pos2); // Turn Off + if (ent->count == 0) { ent->nextthink = level.time + Q_irand(1000, 12000); - } - else if (ent->count==2) - { + } else if (ent->count == 2) { ent->nextthink = level.time + Q_irand(150, 450); - } - else - { + } else { ent->nextthink = level.time + Q_irand(50, 150); } - } - else - { - gi.WE_SetTempGlobalFogColor(ent->pos3); // Turn On + } else { + gi.WE_SetTempGlobalFogColor(ent->pos3); // Turn On ent->nextthink = level.time + 50; } - } - else if (gi.WE_IsOutside(player->currentOrigin)) - { - vec3_t effectPos; - vec3_t effectDir; + } else if (gi.WE_IsOutside(player->currentOrigin)) { + vec3_t effectPos; + vec3_t effectDir; VectorClear(effectDir); - effectDir[0] += Q_flrand(-1.0f, 1.0f); + effectDir[0] += Q_flrand(-1.0f, 1.0f); effectDir[1] += Q_flrand(-1.0f, 1.0f); - bool PlayEffect = Q_irand(1,ent->aimDebounceTime)==1; - bool PlayFlicker = Q_irand(1,ent->attackDebounceTime)==1; - bool PlaySound = (PlayEffect || PlayFlicker || Q_irand(1,ent->pushDebounceTime)==1); + bool PlayEffect = Q_irand(1, ent->aimDebounceTime) == 1; + bool PlayFlicker = Q_irand(1, ent->attackDebounceTime) == 1; + bool PlaySound = (PlayEffect || PlayFlicker || Q_irand(1, ent->pushDebounceTime) == 1); // Play The Sound //---------------- - if (PlaySound && !PlayEffect) - { + if (PlaySound && !PlayEffect) { VectorMA(player->currentOrigin, 250.0f, effectDir, effectPos); - G_SoundAtSpot(effectPos, G_SoundIndex(va("sound/ambience/thunder%d", Q_irand(1,4))), qtrue); + G_SoundAtSpot(effectPos, G_SoundIndex(va("sound/ambience/thunder%d", Q_irand(1, 4))), qtrue); } // Play The Effect //----------------- - if (PlayEffect) - { - VectorMA(player->currentOrigin, 400.0f, effectDir, effectPos); - if (PlaySound) - { - G_Sound(player, G_SoundIndex(va("sound/ambience/thunder_close%d", Q_irand(1,2)))); + if (PlayEffect) { + VectorMA(player->currentOrigin, 400.0f, effectDir, effectPos); + if (PlaySound) { + G_Sound(player, G_SoundIndex(va("sound/ambience/thunder_close%d", Q_irand(1, 2)))); } // Raise It Up Into The Sky @@ -504,7 +427,7 @@ void fx_rain_think( gentity_t *ent ) effectPos[2] += Q_flrand(600.0f, 1000.0f); VectorClear(effectDir); - effectDir[2] = -1.0f; + effectDir[2] = -1.0f; G_PlayEffect("env/huge_lightning", effectPos, effectDir); ent->nextthink = level.time + Q_irand(100, 200); @@ -512,97 +435,77 @@ void fx_rain_think( gentity_t *ent ) // Change The Fog Color //---------------------- - if (PlayFlicker) - { - ent->count = (Q_irand(1,4) * 2); + if (PlayFlicker) { + ent->count = (Q_irand(1, 4) * 2); ent->nextthink = level.time + 50; gi.WE_SetTempGlobalFogColor(ent->pos3); - } - else - { + } else { ent->nextthink = level.time + Q_irand(1000, ent->delay); } - } - else - { + } else { ent->nextthink = level.time + Q_irand(1000, ent->delay); } - } - else - { + } else { ent->nextthink = level.time + Q_irand(1000, ent->delay); } } -void SP_CreateRain( gentity_t *ent ) -{ +void SP_CreateRain(gentity_t *ent) { // Different Types Of Rain //------------------------- - if (ent->spawnflags & 1) - { + if (ent->spawnflags & 1) { G_FindConfigstringIndex("lightrain", CS_WORLD_FX, MAX_WORLD_FX, qtrue); - } - else if (ent->spawnflags & 2) - { + } else if (ent->spawnflags & 2) { G_FindConfigstringIndex("rain", CS_WORLD_FX, MAX_WORLD_FX, qtrue); - } - else if (ent->spawnflags & 4) - { + } else if (ent->spawnflags & 4) { G_FindConfigstringIndex("heavyrain", CS_WORLD_FX, MAX_WORLD_FX, qtrue); // Automatically Get Heavy Fog //----------------------------- - G_FindConfigstringIndex("heavyrainfog", CS_WORLD_FX, MAX_WORLD_FX, qtrue ); + G_FindConfigstringIndex("heavyrainfog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); // Automatically Get Lightning & Thunder //--------------------------------------- ent->spawnflags |= 64; - } - else if (ent->spawnflags & 8) - { - G_EffectIndex( "world/acid_fizz" ); + } else if (ent->spawnflags & 8) { + G_EffectIndex("world/acid_fizz"); G_FindConfigstringIndex("acidrain", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } - // OUTSIDE SHAKE //=============== - if (ent->spawnflags & 16) - { + if (ent->spawnflags & 16) { G_FindConfigstringIndex("outsideShake", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // MISTY FOG //=========== - if (ent->spawnflags & 32) - { - G_FindConfigstringIndex("fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue ); + if (ent->spawnflags & 32) { + G_FindConfigstringIndex("fog", CS_WORLD_FX, MAX_WORLD_FX, qtrue); } // LIGHTNING //=========== - if (ent->spawnflags & 64) - { + if (ent->spawnflags & 64) { G_SoundIndex("sound/ambience/thunder1"); G_SoundIndex("sound/ambience/thunder2"); G_SoundIndex("sound/ambience/thunder3"); G_SoundIndex("sound/ambience/thunder4"); G_SoundIndex("sound/ambience/thunder_close1"); G_SoundIndex("sound/ambience/thunder_close2"); - G_EffectIndex( "env/huge_lightning" ); + G_EffectIndex("env/huge_lightning"); ent->e_ThinkFunc = thinkF_fx_rain_think; ent->nextthink = level.time + Q_irand(4000, 8000); - if (!G_SpawnVector( "flashcolor", "200 200 200", ent->pos3)) - { + if (!G_SpawnVector("flashcolor", "200 200 200", ent->pos3)) { VectorSet(ent->pos3, 200, 200, 200); } - VectorClear(ent->pos2); // the "off" color + VectorClear(ent->pos2); // the "off" color - G_SpawnInt("flashdelay", "12000", &ent->delay); - G_SpawnInt("chanceflicker", "2", &ent->attackDebounceTime); - G_SpawnInt("chancesound", "3", &ent->pushDebounceTime); - G_SpawnInt("chanceeffect", "4", &ent->aimDebounceTime); + G_SpawnInt("flashdelay", "12000", &ent->delay); + G_SpawnInt("chanceflicker", "2", &ent->attackDebounceTime); + G_SpawnInt("chancesound", "3", &ent->pushDebounceTime); + G_SpawnInt("chanceeffect", "4", &ent->aimDebounceTime); } } @@ -673,64 +576,58 @@ blowing size ( minX minY minZ ) default: ( 1000 300 300 ) */ //---------------------------------------------------------- -void SP_CreatePuffSystem( gentity_t *ent ) -{ - char temp[128]; +void SP_CreatePuffSystem(gentity_t *ent) { + char temp[128]; // Initialize the puff system to either 1000 particles or whatever they choose. - G_SpawnInt( "count", "1000", &ent->count ); - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); + G_SpawnInt("count", "1000", &ent->count); + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); // See which puff system to use. int iPuffSystem = 0; int iVal = 0; - if ( G_SpawnInt( "whichsystem", "0", &iVal ) ) - { + if (G_SpawnInt("whichsystem", "0", &iVal)) { iPuffSystem = iVal; - if ( iPuffSystem < 0 || iPuffSystem > 1 ) - { + if (iPuffSystem < 0 || iPuffSystem > 1) { iPuffSystem = 0; - //ri.Error( ERR_DROP, "Weather Effect: Invalid value for whichsystem key" ); - Com_Printf( "Weather Effect: Invalid value for whichsystem key\n" ); + // ri.Error( ERR_DROP, "Weather Effect: Invalid value for whichsystem key" ); + Com_Printf("Weather Effect: Invalid value for whichsystem key\n"); } } - if ( r_weatherScale->value > 0.0f ) - { - sprintf( temp, "puff%i init %i", iPuffSystem, (int)( ent->count * r_weatherScale->value )); + if (r_weatherScale->value > 0.0f) { + sprintf(temp, "puff%i init %i", iPuffSystem, (int)(ent->count * r_weatherScale->value)); - G_FindConfigstringIndex( temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue ); + G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); // Should return here??? It didn't originally... } // See whether we should have the saber spark from the puff system. iVal = 0; - G_SpawnInt( "sabersparks", "0", &iVal ); - if ( iVal == 1 ) + G_SpawnInt("sabersparks", "0", &iVal); + if (iVal == 1) level.worldFlags |= WF_PUFFING; else level.worldFlags &= ~WF_PUFFING; // Go through all the fields and assign the values to the created puff system now. - for ( int i = 0; i < 20; i++ ) - { + for (int i = 0; i < 20; i++) { char *key = NULL; char *value = NULL; // Fetch a field. - if ( !G_SpawnField( i, &key, &value ) ) + if (!G_SpawnField(i, &key, &value)) continue; // Make sure we don't get key's that are worthless. - if ( Q_stricmp( key, "origin" ) == 0 || Q_stricmp( key, "classname" ) == 0 || - Q_stricmp( key, "count" ) == 0 || Q_stricmp( key, "targetname" ) == 0 || - Q_stricmp( key, "sabersparks" ) == 0 || Q_stricmp( key, "whichsystem" ) == 0 ) + if (Q_stricmp(key, "origin") == 0 || Q_stricmp(key, "classname") == 0 || Q_stricmp(key, "count") == 0 || Q_stricmp(key, "targetname") == 0 || + Q_stricmp(key, "sabersparks") == 0 || Q_stricmp(key, "whichsystem") == 0) continue; // Send the command. - Com_sprintf( temp, 128, "puff%i %s %s", iPuffSystem, key, value ); - G_FindConfigstringIndex( temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue ); - } + Com_sprintf(temp, 128, "puff%i %s %s", iPuffSystem, key, value); + G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); + } } // Don't use this! Too powerful! - Aurelio @@ -767,68 +664,57 @@ void SP_CreatePuffSystem( gentity_t *ent ) //----------------- //---------------------------------------------------------- -void fx_explosion_trail_think( gentity_t *ent ) -{ - vec3_t origin; - trace_t tr; +void fx_explosion_trail_think(gentity_t *ent) { + vec3_t origin; + trace_t tr; - if ( ent->spawnflags & 1 ) // gravity + if (ent->spawnflags & 1) // gravity { ent->s.pos.trType = TR_GRAVITY; - } - else - { + } else { ent->s.pos.trType = TR_LINEAR; } - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); - gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, - ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10 ); + gi.trace(&tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10); - if ( tr.fraction < 1.0f ) - { + if (tr.fraction < 1.0f) { // never explode or bounce on sky - if ( !( tr.surfaceFlags & SURF_NOIMPACT )) - { - if ( ent->splashDamage && ent->splashRadius ) - { - G_RadiusDamage( tr.endpos, ent, ent->splashDamage, ent->splashRadius, ent, MOD_EXPLOSIVE_SPLASH ); + if (!(tr.surfaceFlags & SURF_NOIMPACT)) { + if (ent->splashDamage && ent->splashRadius) { + G_RadiusDamage(tr.endpos, ent, ent->splashDamage, ent->splashRadius, ent, MOD_EXPLOSIVE_SPLASH); } } - if ( ent->cameraGroup ) - { + if (ent->cameraGroup) { // fxFile2....in other words, impact fx - G_PlayEffect( ent->cameraGroup, tr.endpos, tr.plane.normal ); + G_PlayEffect(ent->cameraGroup, tr.endpos, tr.plane.normal); } - if ( VALIDSTRING( ent->soundSet ) == true ) - { - G_AddEvent( ent, EV_BMODEL_SOUND, CAS_GetBModelSound( ent->soundSet, BMS_END )); + if (VALIDSTRING(ent->soundSet) == true) { + G_AddEvent(ent, EV_BMODEL_SOUND, CAS_GetBModelSound(ent->soundSet, BMS_END)); } - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } - G_RadiusDamage( origin, ent, ent->damage, ent->radius, ent, MOD_EXPLOSIVE_SPLASH ); + G_RadiusDamage(origin, ent, ent->damage, ent->radius, ent, MOD_EXPLOSIVE_SPLASH); // call the effect with the desired position and orientation - G_PlayEffect( ent->fxID, origin, ent->currentAngles ); + G_PlayEffect(ent->fxID, origin, ent->currentAngles); ent->nextthink = level.time + 50; - gi.linkentity( ent ); + gi.linkentity(ent); } //---------------------------------------------------------- -void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void fx_explosion_trail_use(gentity_t *self, gentity_t *other, gentity_t *activator) { gentity_t *missile = G_Spawn(); // We aren't a missile in the truest sense, rather we just move through the world and spawn effects - if ( missile ) - { + if (missile) { missile->classname = "fx_exp_trail"; missile->nextthink = level.time + 50; @@ -841,40 +727,36 @@ void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activ missile->s.modelindex = self->s.modelindex2; missile->s.pos.trTime = level.time; - G_SetOrigin( missile, self->currentOrigin ); - if ( self->spawnflags & 1 ) // gravity + G_SetOrigin(missile, self->currentOrigin); + if (self->spawnflags & 1) // gravity { missile->s.pos.trType = TR_GRAVITY; - } - else - { + } else { missile->s.pos.trType = TR_LINEAR; } missile->spawnflags = self->spawnflags; - G_SetAngles( missile, self->currentAngles ); - VectorScale( self->currentAngles, self->speed, missile->s.pos.trDelta ); + G_SetAngles(missile, self->currentAngles); + VectorScale(self->currentAngles, self->speed, missile->s.pos.trDelta); missile->s.pos.trTime = level.time; missile->radius = self->radius; missile->damage = self->damage; missile->splashDamage = self->splashDamage; missile->splashRadius = self->splashRadius; missile->fxID = self->fxID; - missile->cameraGroup = self->cameraGroup; //fxfile2 + missile->cameraGroup = self->cameraGroup; // fxfile2 missile->clipmask = MASK_SHOT; - gi.linkentity( missile ); + gi.linkentity(missile); - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - missile->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); - missile->soundSet = G_NewString(self->soundSet);//get my own copy so i can free it when i die + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + missile->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); + missile->soundSet = G_NewString(self->soundSet); // get my own copy so i can free it when i die - if ( missile->s.loopSound < 0 ) - { + if (missile->s.loopSound < 0) { missile->s.loopSound = 0; } } @@ -882,38 +764,33 @@ void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activ } //---------------------------------------------------------- -void fx_explosion_trail_link( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *target = NULL; +void fx_explosion_trail_link(gentity_t *ent) { + vec3_t dir; + gentity_t *target = NULL; // we ony activate when used ent->e_UseFunc = useF_fx_explosion_trail_use; - if ( ent->target ) - { + if (ent->target) { // try to use the target to override the orientation - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_explosion_trail %s could not find target %s\n", ent->targetname, ent->target ); - G_FreeEntity( ent ); + if (!target) { + gi.Printf(S_COLOR_RED "ERROR: fx_explosion_trail %s could not find target %s\n", ent->targetname, ent->target); + G_FreeEntity(ent); return; } // Our target is valid so lets use that - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - } - else - { + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + } else { // we are assuming that we have angles, but there are no checks to verify this - AngleVectors( ent->s.angles, dir, NULL, NULL ); + AngleVectors(ent->s.angles, dir, NULL, NULL); } // NOTE: this really isn't an angle, but rather an orientation vector - G_SetAngles( ent, dir ); + G_SetAngles(ent, dir); } /*QUAKED fx_explosion_trail (0 0 1) (-8 -8 -8) (8 8 8) GRAVITY @@ -939,33 +816,29 @@ Can also be used for something like a meteor, just add an impact effect ( fxFile */ //---------------------------------------------------------- -void SP_fx_explosion_trail( gentity_t *ent ) -{ +void SP_fx_explosion_trail(gentity_t *ent) { // We have to be useable, otherwise we won't spawn in - if ( !ent->targetname ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_explosion_trail at %s has no targetname specified\n", vtos( ent->s.origin )); - G_FreeEntity( ent ); + if (!ent->targetname) { + gi.Printf(S_COLOR_RED "ERROR: fx_explosion_trail at %s has no targetname specified\n", vtos(ent->s.origin)); + G_FreeEntity(ent); return; } // Get our defaults - G_SpawnString( "fxFile", "env/exp_trail_comp", &ent->fxFile ); - G_SpawnInt( "damage", "128", &ent->damage ); - G_SpawnFloat( "radius", "128", &ent->radius ); - G_SpawnFloat( "speed", "350", &ent->speed ); + G_SpawnString("fxFile", "env/exp_trail_comp", &ent->fxFile); + G_SpawnInt("damage", "128", &ent->damage); + G_SpawnFloat("radius", "128", &ent->radius); + G_SpawnFloat("speed", "350", &ent->speed); // Try to associate an effect file, unfortunately we won't know if this worked or not until the CGAME trys to register it... - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); - if ( ent->cameraGroup ) - { - G_EffectIndex( ent->cameraGroup ); + if (ent->cameraGroup) { + G_EffectIndex(ent->cameraGroup); } - if ( ent->model ) - { - ent->s.modelindex2 = G_ModelIndex( ent->model ); + if (ent->model) { + ent->s.modelindex2 = G_ModelIndex(ent->model); } // Give us a bit of time to spawn in the other entities, since we may have to target one of 'em @@ -973,99 +846,77 @@ void SP_fx_explosion_trail( gentity_t *ent ) ent->nextthink = level.time + 500; // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - // // //------------------------------------------ -void fx_target_beam_set_debounce( gentity_t *self ) -{ - if ( self->wait >= FRAMETIME ) - { - self->attackDebounceTime = level.time + self->wait + Q_irand( -self->random, self->random ); - } - else if ( self->wait < 0 ) - { +void fx_target_beam_set_debounce(gentity_t *self) { + if (self->wait >= FRAMETIME) { + self->attackDebounceTime = level.time + self->wait + Q_irand(-self->random, self->random); + } else if (self->wait < 0) { self->e_UseFunc = useF_NULL; - } - else - { - self->attackDebounceTime = level.time + FRAMETIME + Q_irand( -self->random, self->random ); + } else { + self->attackDebounceTime = level.time + FRAMETIME + Q_irand(-self->random, self->random); } } //------------------------------------------ -void fx_target_beam_fire( gentity_t *ent ) -{ - trace_t trace; - vec3_t dir, org, end; - qboolean open; +void fx_target_beam_fire(gentity_t *ent) { + trace_t trace; + vec3_t dir, org, end; + qboolean open; - if ( !ent->enemy || !ent->enemy->inuse ) - {//info_null most likely - //ignore = ent->s.number; + if (!ent->enemy || !ent->enemy->inuse) { // info_null most likely + // ignore = ent->s.number; ent->enemy = NULL; - VectorCopy( ent->s.origin2, org ); - } - else - { - //ignore = ent->enemy->s.number; - VectorCopy( ent->enemy->currentOrigin, org ); + VectorCopy(ent->s.origin2, org); + } else { + // ignore = ent->enemy->s.number; + VectorCopy(ent->enemy->currentOrigin, org); } - VectorCopy( org, ent->s.origin2 ); - VectorSubtract( org, ent->s.origin, dir ); - VectorNormalize( dir ); + VectorCopy(org, ent->s.origin2); + VectorSubtract(org, ent->s.origin, dir); + VectorNormalize(dir); - gi.trace( &trace, ent->s.origin, NULL, NULL, org, ENTITYNUM_NONE, MASK_SHOT, (EG2_Collision)0, 0 );//ignore - if ( ent->spawnflags & 2 ) - { + gi.trace(&trace, ent->s.origin, NULL, NULL, org, ENTITYNUM_NONE, MASK_SHOT, (EG2_Collision)0, 0); // ignore + if (ent->spawnflags & 2) { open = qtrue; - VectorCopy( org, end ); - } - else - { + VectorCopy(org, end); + } else { open = qfalse; - VectorCopy( trace.endpos, end ); + VectorCopy(trace.endpos, end); } - if ( trace.fraction < 1.0 ) - { - if ( trace.entityNum < ENTITYNUM_WORLD ) - { + if (trace.fraction < 1.0) { + if (trace.entityNum < ENTITYNUM_WORLD) { gentity_t *victim = &g_entities[trace.entityNum]; - if ( victim && victim->takedamage ) - { - if ( ent->spawnflags & 4 ) // NO_KNOCKBACK + if (victim && victim->takedamage) { + if (ent->spawnflags & 4) // NO_KNOCKBACK { - G_Damage( victim, ent, ent->activator, dir, trace.endpos, ent->damage, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN ); - } - else - { - G_Damage( victim, ent, ent->activator, dir, trace.endpos, ent->damage, 0, MOD_UNKNOWN ); + G_Damage(victim, ent, ent->activator, dir, trace.endpos, ent->damage, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN); + } else { + G_Damage(victim, ent, ent->activator, dir, trace.endpos, ent->damage, 0, MOD_UNKNOWN); } } } } - G_AddEvent( ent, EV_TARGET_BEAM_DRAW, ent->fxID ); - VectorCopy( end, ent->s.origin2 ); + G_AddEvent(ent, EV_TARGET_BEAM_DRAW, ent->fxID); + VectorCopy(end, ent->s.origin2); - if ( open ) - { - VectorScale( dir, -1, ent->pos1 ); - } - else - { - VectorCopy( trace.plane.normal, ent->pos1 ); + if (open) { + VectorScale(dir, -1, ent->pos1); + } else { + VectorCopy(trace.plane.normal, ent->pos1); } ent->e_ThinkFunc = thinkF_fx_target_beam_think; @@ -1073,92 +924,80 @@ void fx_target_beam_fire( gentity_t *ent ) } //------------------------------------------ -void fx_target_beam_fire_start( gentity_t *self ) -{ - fx_target_beam_set_debounce( self ); - self->e_ThinkFunc = thinkF_fx_target_beam_think; - self->nextthink = level.time + FRAMETIME; - self->painDebounceTime = level.time + self->speed + Q_irand( -500, 500 ); - fx_target_beam_fire( self ); +void fx_target_beam_fire_start(gentity_t *self) { + fx_target_beam_set_debounce(self); + self->e_ThinkFunc = thinkF_fx_target_beam_think; + self->nextthink = level.time + FRAMETIME; + self->painDebounceTime = level.time + self->speed + Q_irand(-500, 500); + fx_target_beam_fire(self); } //------------------------------------------ -void fx_target_beam_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->spawnflags & 8 ) // one shot +void fx_target_beam_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->spawnflags & 8) // one shot { - fx_target_beam_fire( self ); - self->e_ThinkFunc = thinkF_NULL; - } - else if ( self->e_ThinkFunc == thinkF_NULL ) - { - self->e_ThinkFunc = thinkF_fx_target_beam_think; - self->nextthink = level.time + 50; - } - else - { - self->e_ThinkFunc = thinkF_NULL; + fx_target_beam_fire(self); + self->e_ThinkFunc = thinkF_NULL; + } else if (self->e_ThinkFunc == thinkF_NULL) { + self->e_ThinkFunc = thinkF_fx_target_beam_think; + self->nextthink = level.time + 50; + } else { + self->e_ThinkFunc = thinkF_NULL; } self->activator = activator; } //------------------------------------------ -void fx_target_beam_think( gentity_t *ent ) -{ - if ( ent->attackDebounceTime > level.time ) - { +void fx_target_beam_think(gentity_t *ent) { + if (ent->attackDebounceTime > level.time) { ent->nextthink = level.time + FRAMETIME; return; } - fx_target_beam_fire_start( ent ); + fx_target_beam_fire_start(ent); } //------------------------------------------ -void fx_target_beam_link( gentity_t *ent ) -{ - gentity_t *target = NULL; - vec3_t dir; +void fx_target_beam_link(gentity_t *ent) { + gentity_t *target = NULL; + vec3_t dir; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - Com_Printf( "bolt_link: unable to find target %s\n", ent->target ); - G_FreeEntity( ent ); + if (!target) { + Com_Printf("bolt_link: unable to find target %s\n", ent->target); + G_FreeEntity(ent); return; } ent->attackDebounceTime = level.time; - if ( !target->classname || Q_stricmp( "info_null", target->classname ) ) - {//don't want to set enemy to something that's going to free itself... actually, this could be bad in other ways, too... ent pointer could be freed up and re-used by the time we check it next - G_SetEnemy( ent, target ); + if (!target->classname || + Q_stricmp("info_null", target->classname)) { // don't want to set enemy to something that's going to free itself... actually, this could be bad in other + // ways, too... ent pointer could be freed up and re-used by the time we check it next + G_SetEnemy(ent, target); } - VectorSubtract( target->s.origin, ent->s.origin, dir );//er, does it ever use dir? - /*len = */VectorNormalize( dir );//er, does it use len or dir? - vectoangles( dir, ent->s.angles );//er, does it use s.angles? + VectorSubtract(target->s.origin, ent->s.origin, dir); // er, does it ever use dir? + /*len = */ VectorNormalize(dir); // er, does it use len or dir? + vectoangles(dir, ent->s.angles); // er, does it use s.angles? - VectorCopy( target->s.origin, ent->s.origin2 ); + VectorCopy(target->s.origin, ent->s.origin2); - if ( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { // Do nothing - ent->e_ThinkFunc = thinkF_NULL; - } - else - { - if ( !(ent->spawnflags & 8 )) // one_shot, only calls when used + ent->e_ThinkFunc = thinkF_NULL; + } else { + if (!(ent->spawnflags & 8)) // one_shot, only calls when used { // switch think functions to avoid doing the bolt_link every time ent->e_ThinkFunc = thinkF_fx_target_beam_think; - ent->nextthink = level.time + FRAMETIME; + ent->nextthink = level.time + FRAMETIME; } } ent->e_UseFunc = useF_fx_target_beam_use; - gi.linkentity( ent ); + gi.linkentity(ent); } /*QUAKED fx_target_beam (1 0.5 0.5) (-8 -8 -8) (8 8 8) STARTOFF OPEN NO_KNOCKBACK ONE_SHOT NO_IMPACT @@ -1178,47 +1017,42 @@ NO_KNOCKBACK - beam damage does no knockback "target" - ent to point at- you MUST have this. This can be anything you want, including a moving ent - for static beams, just use info_null */ //------------------------------------------ -void SP_fx_target_beam( gentity_t *ent ) -{ - G_SetOrigin( ent, ent->s.origin ); +void SP_fx_target_beam(gentity_t *ent) { + G_SetOrigin(ent, ent->s.origin); - ent->speed *= 1000; - ent->wait *= 1000; + ent->speed *= 1000; + ent->wait *= 1000; ent->random *= 1000; - if ( ent->speed < FRAMETIME ) - { + if (ent->speed < FRAMETIME) { ent->speed = FRAMETIME; } - G_SpawnInt( "damage", "0", &ent->damage ); - G_SpawnString( "fxFile", "env/targ_beam", &ent->fxFile ); + G_SpawnInt("damage", "0", &ent->damage); + G_SpawnString("fxFile", "env/targ_beam", &ent->fxFile); - if ( ent->spawnflags & 16 ) // NO_IMPACT FX + if (ent->spawnflags & 16) // NO_IMPACT FX { ent->delay = 0; - } - else - { - G_SpawnString( "fxFile2", "env/targ_beam_impact", &ent->cameraGroup ); - ent->delay = G_EffectIndex( ent->cameraGroup ); + } else { + G_SpawnString("fxFile2", "env/targ_beam_impact", &ent->cameraGroup); + ent->delay = G_EffectIndex(ent->cameraGroup); } - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); ent->activator = ent; - ent->owner = NULL; + ent->owner = NULL; ent->e_ThinkFunc = thinkF_fx_target_beam_link; - ent->nextthink = level.time + START_TIME_LINK_ENTS; + ent->nextthink = level.time + START_TIME_LINK_ENTS; - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - /*QUAKED fx_cloudlayer (1 0.3 0.5) (-8 -8 -8) (8 8 8) TUBE ALT Creates a scalable scrolling cloud layer, mostly for bespin undercity but could be used other places @@ -1232,22 +1066,21 @@ void SP_fx_target_beam( gentity_t *ent ) */ -void SP_fx_cloudlayer( gentity_t *ent ) -{ +void SP_fx_cloudlayer(gentity_t *ent) { // HACK: this effect is never played, rather it just caches the shaders I need cgame side - G_EffectIndex( "world/haze_cache" ); + G_EffectIndex("world/haze_cache"); - G_SpawnFloat( "radius", "2048", &ent->radius ); - G_SpawnFloat( "random", "128", &ent->random ); - G_SpawnFloat( "wait", "0", &ent->wait ); + G_SpawnFloat("radius", "2048", &ent->radius); + G_SpawnFloat("random", "128", &ent->random); + G_SpawnFloat("wait", "0", &ent->wait); ent->s.eType = ET_CLOUD; // dumb - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); ent->contents = 0; - VectorSet( ent->maxs, 200, 200, 200 ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, 200, 200, 200); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } diff --git a/code/game/g_inventory.cpp b/code/game/g_inventory.cpp index 8cb3eb539a..b6df558871 100644 --- a/code/game/g_inventory.cpp +++ b/code/game/g_inventory.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//g_inventory.cpp +// g_inventory.cpp #include "g_local.h" /* @@ -28,48 +28,39 @@ along with this program; if not, see . Goodie Keys ================ */ -qboolean INV_GoodieKeyGive( gentity_t *target ) -{ - if ( !target || !target->client ) - { +qboolean INV_GoodieKeyGive(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } target->client->ps.inventory[INV_GOODIE_KEY]++; return (qtrue); - } -qboolean INV_GoodieKeyTake( gentity_t *target ) -{ - if ( !target || !target->client ) - { +qboolean INV_GoodieKeyTake(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } - if (target->client->ps.inventory[INV_GOODIE_KEY]) - { + if (target->client->ps.inventory[INV_GOODIE_KEY]) { target->client->ps.inventory[INV_GOODIE_KEY]--; return (qtrue); } - //had no keys + // had no keys return (qfalse); } -int INV_GoodieKeyCheck( gentity_t *target ) -{ - if ( !target || !target->client ) - { +int INV_GoodieKeyCheck(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } - if ( target->client->ps.inventory[INV_GOODIE_KEY] ) - {//found a key + if (target->client->ps.inventory[INV_GOODIE_KEY]) { // found a key return (INV_GOODIE_KEY); } - //no keys + // no keys return (qfalse); } @@ -78,40 +69,31 @@ int INV_GoodieKeyCheck( gentity_t *target ) Security Keys ================ */ -qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ) -{ - if ( target == NULL || keyname == NULL || target->client == NULL ) - { +qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname) { + if (target == NULL || keyname == NULL || target->client == NULL) { return qfalse; } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.security_key_message[i][0] == '\0' ) - {//fill in the first empty slot we find with this key - target->client->ps.inventory[INV_SECURITY_KEY]++; // He got the key - Q_strncpyz( target->client->ps.security_key_message[i], keyname, MAX_SECURITY_KEY_MESSSAGE ); + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.security_key_message[i][0] == '\0') { // fill in the first empty slot we find with this key + target->client->ps.inventory[INV_SECURITY_KEY]++; // He got the key + Q_strncpyz(target->client->ps.security_key_message[i], keyname, MAX_SECURITY_KEY_MESSSAGE); return qtrue; } } - //couldn't find an empty slot + // couldn't find an empty slot return qfalse; } -void INV_SecurityKeyTake( gentity_t *target, const char *keyname ) -{ - if ( !target || !keyname || !target->client ) - { +void INV_SecurityKeyTake(gentity_t *target, const char *keyname) { + if (!target || !keyname || !target->client) { return; } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.security_key_message[i][0] != '\0' ) - { - if ( !Q_stricmp( keyname, target->client->ps.security_key_message[i] ) ) - { - target->client->ps.inventory[INV_SECURITY_KEY]--; // Take the key + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.security_key_message[i][0] != '\0') { + if (!Q_stricmp(keyname, target->client->ps.security_key_message[i])) { + target->client->ps.inventory[INV_SECURITY_KEY]--; // Take the key target->client->ps.security_key_message[i][0] = '\0'; return; } @@ -126,19 +108,14 @@ void INV_SecurityKeyTake( gentity_t *target, const char *keyname ) } } -qboolean INV_SecurityKeyCheck( gentity_t *target, const char *keyname ) -{ - if ( !target || !keyname || !target->client ) - { +qboolean INV_SecurityKeyCheck(gentity_t *target, const char *keyname) { + if (!target || !keyname || !target->client) { return (qfalse); } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.inventory[INV_SECURITY_KEY] && target->client->ps.security_key_message[i][0] != '\0' ) - { - if ( !Q_stricmp( keyname, target->client->ps.security_key_message[i] ) ) - { + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.inventory[INV_SECURITY_KEY] && target->client->ps.security_key_message[i][0] != '\0') { + if (!Q_stricmp(keyname, target->client->ps.security_key_message[i])) { return (qtrue); } } diff --git a/code/game/g_itemLoad.cpp b/code/game/g_itemLoad.cpp index d0cca821d5..b2c66845fd 100644 --- a/code/game/g_itemLoad.cpp +++ b/code/game/g_itemLoad.cpp @@ -20,63 +20,48 @@ along with this program; if not, see . =========================================================================== */ -//g_itemLoad.cpp -//reads in ext_data\items.dat to bg_itemlist[] +// g_itemLoad.cpp +// reads in ext_data\items.dat to bg_itemlist[] #include "g_local.h" #include "g_items.h" #define PICKUPSOUND "sound/weapons/w_pkup.wav" -//qboolean COM_ParseInt( char **data, int *i ); -//qboolean COM_ParseString( char **data, char **s ); -//qboolean COM_ParseFloat( char **data, float *f ); +// qboolean COM_ParseInt( char **data, int *i ); +// qboolean COM_ParseString( char **data, char **s ); +// qboolean COM_ParseFloat( char **data, float *f ); -extern gitem_t bg_itemlist[]; +extern gitem_t bg_itemlist[]; -struct itemParms_s -{ - int itemNum; +struct itemParms_s { + int itemNum; } itemParms; - -static void IT_ClassName (const char **holdBuf); -static void IT_Count (const char **holdBuf); -static void IT_Icon (const char **holdBuf); -static void IT_Min (const char **holdBuf); -static void IT_Max (const char **holdBuf); -static void IT_Name (const char **holdBuf); -static void IT_PickupSound (const char **holdBuf); -static void IT_Tag (const char **holdBuf); -static void IT_Type (const char **holdBuf); -static void IT_WorldModel (const char **holdBuf); - - -typedef struct -{ - const char *parmName; - void (*func)(const char **holdBuf); +static void IT_ClassName(const char **holdBuf); +static void IT_Count(const char **holdBuf); +static void IT_Icon(const char **holdBuf); +static void IT_Min(const char **holdBuf); +static void IT_Max(const char **holdBuf); +static void IT_Name(const char **holdBuf); +static void IT_PickupSound(const char **holdBuf); +static void IT_Tag(const char **holdBuf); +static void IT_Type(const char **holdBuf); +static void IT_WorldModel(const char **holdBuf); + +typedef struct { + const char *parmName; + void (*func)(const char **holdBuf); } itemParms_t; - #define IT_PARM_MAX 10 -itemParms_t ItemParms[IT_PARM_MAX] = -{ - { "itemname", IT_Name }, - { "classname", IT_ClassName }, - { "count", IT_Count }, - { "icon", IT_Icon }, - { "min", IT_Min }, - { "max", IT_Max }, - { "pickupsound", IT_PickupSound }, - { "tag", IT_Tag }, - { "type", IT_Type }, - { "worldmodel", IT_WorldModel }, +itemParms_t ItemParms[IT_PARM_MAX] = { + {"itemname", IT_Name}, {"classname", IT_ClassName}, {"count", IT_Count}, {"icon", IT_Icon}, {"min", IT_Min}, + {"max", IT_Max}, {"pickupsound", IT_PickupSound}, {"tag", IT_Tag}, {"type", IT_Type}, {"worldmodel", IT_WorldModel}, }; -static void IT_SetDefaults() -{ +static void IT_SetDefaults() { bg_itemlist[itemParms.itemNum].mins[0] = -16; bg_itemlist[itemParms.itemNum].mins[1] = -16; @@ -86,404 +71,324 @@ static void IT_SetDefaults() bg_itemlist[itemParms.itemNum].maxs[1] = 16; bg_itemlist[itemParms.itemNum].maxs[2] = 16; - - bg_itemlist[itemParms.itemNum].pickup_sound = PICKUPSOUND; //give it a default sound + bg_itemlist[itemParms.itemNum].pickup_sound = PICKUPSOUND; // give it a default sound bg_itemlist[itemParms.itemNum].precaches = NULL; bg_itemlist[itemParms.itemNum].sounds = NULL; } -static void IT_Name(const char **holdBuf) -{ +static void IT_Name(const char **holdBuf) { int itemNum; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - - if (!Q_stricmp(tokenStr,"ITM_NONE")) + if (!Q_stricmp(tokenStr, "ITM_NONE")) itemNum = ITM_NONE; - else if (!Q_stricmp(tokenStr,"ITM_STUN_BATON_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_STUN_BATON_PICKUP")) itemNum = ITM_STUN_BATON_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SABER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SABER_PICKUP")) itemNum = ITM_SABER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BRYAR_PISTOL_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BRYAR_PISTOL_PICKUP")) itemNum = ITM_BRYAR_PISTOL_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BLASTER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BLASTER_PICKUP")) itemNum = ITM_BLASTER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_DISRUPTOR_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_DISRUPTOR_PICKUP")) itemNum = ITM_DISRUPTOR_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BOWCASTER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BOWCASTER_PICKUP")) itemNum = ITM_BOWCASTER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_REPEATER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_REPEATER_PICKUP")) itemNum = ITM_REPEATER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_DEMP2_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_DEMP2_PICKUP")) itemNum = ITM_DEMP2_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_FLECHETTE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_FLECHETTE_PICKUP")) itemNum = ITM_FLECHETTE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_ROCKET_LAUNCHER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_ROCKET_LAUNCHER_PICKUP")) itemNum = ITM_ROCKET_LAUNCHER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_THERMAL_DET_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_THERMAL_DET_PICKUP")) itemNum = ITM_THERMAL_DET_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_TRIP_MINE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_TRIP_MINE_PICKUP")) itemNum = ITM_TRIP_MINE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_DET_PACK_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_DET_PACK_PICKUP")) itemNum = ITM_DET_PACK_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BOT_LASER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BOT_LASER_PICKUP")) itemNum = ITM_BOT_LASER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_EMPLACED_GUN_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_EMPLACED_GUN_PICKUP")) itemNum = ITM_EMPLACED_GUN_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_TURRET_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_TURRET_PICKUP")) itemNum = ITM_TURRET_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_MELEE")) + else if (!Q_stricmp(tokenStr, "ITM_MELEE")) itemNum = ITM_MELEE; - else if (!Q_stricmp(tokenStr,"ITM_ATST_MAIN_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_ATST_MAIN_PICKUP")) itemNum = ITM_ATST_MAIN_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_ATST_SIDE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_ATST_SIDE_PICKUP")) itemNum = ITM_ATST_SIDE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_TIE_FIGHTER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_TIE_FIGHTER_PICKUP")) itemNum = ITM_TIE_FIGHTER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_RAPID_FIRE_CONC_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_RAPID_FIRE_CONC_PICKUP")) itemNum = ITM_RAPID_FIRE_CONC_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_JAWA_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_JAWA_PICKUP")) itemNum = ITM_JAWA_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_TUSKEN_RIFLE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_TUSKEN_RIFLE_PICKUP")) itemNum = ITM_TUSKEN_RIFLE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_TUSKEN_STAFF_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_TUSKEN_STAFF_PICKUP")) itemNum = ITM_TUSKEN_STAFF_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SCEPTER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SCEPTER_PICKUP")) itemNum = ITM_SCEPTER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_NOGHRI_STICK_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_NOGHRI_STICK_PICKUP")) itemNum = ITM_NOGHRI_STICK_PICKUP; - //ammo - else if (!Q_stricmp(tokenStr,"ITM_AMMO_FORCE_PICKUP")) + // ammo + else if (!Q_stricmp(tokenStr, "ITM_AMMO_FORCE_PICKUP")) itemNum = ITM_AMMO_FORCE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_BLASTER_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_BLASTER_PICKUP")) itemNum = ITM_AMMO_BLASTER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_POWERCELL_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_POWERCELL_PICKUP")) itemNum = ITM_AMMO_POWERCELL_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_METAL_BOLTS_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_METAL_BOLTS_PICKUP")) itemNum = ITM_AMMO_METAL_BOLTS_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_ROCKETS_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_ROCKETS_PICKUP")) itemNum = ITM_AMMO_ROCKETS_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_EMPLACED_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_EMPLACED_PICKUP")) itemNum = ITM_AMMO_EMPLACED_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_THERMAL_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_THERMAL_PICKUP")) itemNum = ITM_AMMO_THERMAL_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_TRIPMINE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_TRIPMINE_PICKUP")) itemNum = ITM_AMMO_TRIPMINE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_AMMO_DETPACK_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_AMMO_DETPACK_PICKUP")) itemNum = ITM_AMMO_DETPACK_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_FORCE_HEAL_PICKUP")) - { + else if (!Q_stricmp(tokenStr, "ITM_FORCE_HEAL_PICKUP")) { itemNum = ITM_FORCE_HEAL_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_LEVITATION_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_LEVITATION_PICKUP")) { itemNum = ITM_FORCE_LEVITATION_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_SPEED_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_SPEED_PICKUP")) { itemNum = ITM_FORCE_SPEED_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_PUSH_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_PUSH_PICKUP")) { itemNum = ITM_FORCE_PUSH_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_PULL_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_PULL_PICKUP")) { itemNum = ITM_FORCE_PULL_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_TELEPATHY_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_TELEPATHY_PICKUP")) { itemNum = ITM_FORCE_TELEPATHY_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_GRIP_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_GRIP_PICKUP")) { itemNum = ITM_FORCE_GRIP_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_LIGHTNING_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_LIGHTNING_PICKUP")) { itemNum = ITM_FORCE_LIGHTNING_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_FORCE_SABERTHROW_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_SABERTHROW_PICKUP")) { itemNum = ITM_FORCE_SABERTHROW_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_BATTERY_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_BATTERY_PICKUP")) { itemNum = ITM_BATTERY_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_SEEKER_PICKUP")) + } else if (!Q_stricmp(tokenStr, "ITM_SEEKER_PICKUP")) itemNum = ITM_SEEKER_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SHIELD_PICKUP")) itemNum = ITM_SHIELD_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BACTA_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BACTA_PICKUP")) itemNum = ITM_BACTA_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_DATAPAD_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_DATAPAD_PICKUP")) itemNum = ITM_DATAPAD_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BINOCULARS_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BINOCULARS_PICKUP")) itemNum = ITM_BINOCULARS_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SENTRY_GUN_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SENTRY_GUN_PICKUP")) itemNum = ITM_SENTRY_GUN_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_LA_GOGGLES_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_LA_GOGGLES_PICKUP")) itemNum = ITM_LA_GOGGLES_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_BLASTER_PISTOL_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_BLASTER_PISTOL_PICKUP")) itemNum = ITM_BLASTER_PISTOL_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_CONCUSSION_RIFLE_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_CONCUSSION_RIFLE_PICKUP")) itemNum = ITM_CONCUSSION_RIFLE_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_MEDPAK_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_MEDPAK_PICKUP")) itemNum = ITM_MEDPAK_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_SM_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SHIELD_SM_PICKUP")) itemNum = ITM_SHIELD_SM_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_LRG_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SHIELD_LRG_PICKUP")) itemNum = ITM_SHIELD_LRG_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_GOODIE_KEY_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_GOODIE_KEY_PICKUP")) itemNum = ITM_GOODIE_KEY_PICKUP; - else if (!Q_stricmp(tokenStr,"ITM_SECURITY_KEY_PICKUP")) + else if (!Q_stricmp(tokenStr, "ITM_SECURITY_KEY_PICKUP")) itemNum = ITM_SECURITY_KEY_PICKUP; - else - { + else { itemNum = 0; gi.Printf("WARNING: bad itemname in external item data '%s'\n", tokenStr); } itemParms.itemNum = itemNum; -// ++bg_numItems; + // ++bg_numItems; IT_SetDefaults(); } -static void IT_ClassName(const char **holdBuf) -{ +static void IT_ClassName(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 32) - { + if (len > 32) { len = 32; gi.Printf("WARNING: weaponclass too long in external ITEMS.DAT '%s'\n", tokenStr); } bg_itemlist[itemParms.itemNum].classname = G_NewString(tokenStr); -// Q_strncpyz(bg_itemlist[itemParms.itemNum].classname,tokenStr,len); - + // Q_strncpyz(bg_itemlist[itemParms.itemNum].classname,tokenStr,len); } -static void IT_WorldModel(const char **holdBuf) -{ +static void IT_WorldModel(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; gi.Printf("WARNING: world model too long in external ITEMS.DAT '%s'\n", tokenStr); } bg_itemlist[itemParms.itemNum].world_model = G_NewString(tokenStr); -// Q_strncpyz(bg_itemlist[itemParms.itemNum].world_model[0],tokenStr,len); - + // Q_strncpyz(bg_itemlist[itemParms.itemNum].world_model[0],tokenStr,len); } -static void IT_Tag(const char **holdBuf) -{ +static void IT_Tag(const char **holdBuf) { int tag; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if (!Q_stricmp(tokenStr,"WP_NONE")) + if (!Q_stricmp(tokenStr, "WP_NONE")) tag = WP_NONE; - else if (!Q_stricmp(tokenStr,"WP_STUN_BATON")) + else if (!Q_stricmp(tokenStr, "WP_STUN_BATON")) tag = WP_STUN_BATON; - else if (!Q_stricmp(tokenStr,"WP_SABER")) + else if (!Q_stricmp(tokenStr, "WP_SABER")) tag = WP_SABER; - else if (!Q_stricmp(tokenStr,"WP_BLASTER_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER_PISTOL")) tag = WP_BLASTER_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_BRYAR_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BRYAR_PISTOL")) tag = WP_BRYAR_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_BLASTER")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER")) tag = WP_BLASTER; - else if (!Q_stricmp(tokenStr,"WP_DISRUPTOR")) + else if (!Q_stricmp(tokenStr, "WP_DISRUPTOR")) tag = WP_DISRUPTOR; - else if (!Q_stricmp(tokenStr,"WP_BOWCASTER")) + else if (!Q_stricmp(tokenStr, "WP_BOWCASTER")) tag = WP_BOWCASTER; - else if (!Q_stricmp(tokenStr,"WP_REPEATER")) + else if (!Q_stricmp(tokenStr, "WP_REPEATER")) tag = WP_REPEATER; - else if (!Q_stricmp(tokenStr,"WP_DEMP2")) + else if (!Q_stricmp(tokenStr, "WP_DEMP2")) tag = WP_DEMP2; - else if (!Q_stricmp(tokenStr,"WP_FLECHETTE")) + else if (!Q_stricmp(tokenStr, "WP_FLECHETTE")) tag = WP_FLECHETTE; - else if (!Q_stricmp(tokenStr,"WP_ROCKET_LAUNCHER")) + else if (!Q_stricmp(tokenStr, "WP_ROCKET_LAUNCHER")) tag = WP_ROCKET_LAUNCHER; - else if (!Q_stricmp(tokenStr,"WP_CONCUSSION")) + else if (!Q_stricmp(tokenStr, "WP_CONCUSSION")) tag = WP_CONCUSSION; - else if (!Q_stricmp(tokenStr,"WP_THERMAL")) + else if (!Q_stricmp(tokenStr, "WP_THERMAL")) tag = WP_THERMAL; - else if (!Q_stricmp(tokenStr,"WP_TRIP_MINE")) + else if (!Q_stricmp(tokenStr, "WP_TRIP_MINE")) tag = WP_TRIP_MINE; - else if (!Q_stricmp(tokenStr,"WP_DET_PACK")) + else if (!Q_stricmp(tokenStr, "WP_DET_PACK")) tag = WP_DET_PACK; - else if (!Q_stricmp(tokenStr,"WP_BOT_LASER")) + else if (!Q_stricmp(tokenStr, "WP_BOT_LASER")) tag = WP_BOT_LASER; - else if (!Q_stricmp(tokenStr,"WP_EMPLACED_GUN")) + else if (!Q_stricmp(tokenStr, "WP_EMPLACED_GUN")) tag = WP_EMPLACED_GUN; - else if (!Q_stricmp(tokenStr,"WP_MELEE")) + else if (!Q_stricmp(tokenStr, "WP_MELEE")) tag = WP_MELEE; - else if (!Q_stricmp(tokenStr,"WP_TURRET")) + else if (!Q_stricmp(tokenStr, "WP_TURRET")) tag = WP_TURRET; - else if (!Q_stricmp(tokenStr,"WP_ATST_MAIN")) + else if (!Q_stricmp(tokenStr, "WP_ATST_MAIN")) tag = WP_ATST_MAIN; - else if (!Q_stricmp(tokenStr,"WP_ATST_SIDE")) + else if (!Q_stricmp(tokenStr, "WP_ATST_SIDE")) tag = WP_ATST_SIDE; - else if (!Q_stricmp(tokenStr,"WP_TIE_FIGHTER")) + else if (!Q_stricmp(tokenStr, "WP_TIE_FIGHTER")) tag = WP_TIE_FIGHTER; - else if (!Q_stricmp(tokenStr,"WP_RAPID_FIRE_CONC")) + else if (!Q_stricmp(tokenStr, "WP_RAPID_FIRE_CONC")) tag = WP_RAPID_FIRE_CONC; - else if (!Q_stricmp(tokenStr,"WP_BLASTER_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER_PISTOL")) tag = WP_BLASTER_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_JAWA")) + else if (!Q_stricmp(tokenStr, "WP_JAWA")) tag = WP_JAWA; - else if (!Q_stricmp(tokenStr,"WP_TUSKEN_RIFLE")) + else if (!Q_stricmp(tokenStr, "WP_TUSKEN_RIFLE")) tag = WP_TUSKEN_RIFLE; - else if (!Q_stricmp(tokenStr,"WP_TUSKEN_STAFF")) + else if (!Q_stricmp(tokenStr, "WP_TUSKEN_STAFF")) tag = WP_TUSKEN_STAFF; - else if (!Q_stricmp(tokenStr,"WP_SCEPTER")) + else if (!Q_stricmp(tokenStr, "WP_SCEPTER")) tag = WP_SCEPTER; - else if (!Q_stricmp(tokenStr,"WP_NOGHRI_STICK")) + else if (!Q_stricmp(tokenStr, "WP_NOGHRI_STICK")) tag = WP_NOGHRI_STICK; - else if (!Q_stricmp(tokenStr,"AMMO_FORCE")) + else if (!Q_stricmp(tokenStr, "AMMO_FORCE")) tag = AMMO_FORCE; - else if (!Q_stricmp(tokenStr,"AMMO_BLASTER")) + else if (!Q_stricmp(tokenStr, "AMMO_BLASTER")) tag = AMMO_BLASTER; - else if (!Q_stricmp(tokenStr,"AMMO_POWERCELL")) + else if (!Q_stricmp(tokenStr, "AMMO_POWERCELL")) tag = AMMO_POWERCELL; - else if (!Q_stricmp(tokenStr,"AMMO_METAL_BOLTS")) + else if (!Q_stricmp(tokenStr, "AMMO_METAL_BOLTS")) tag = AMMO_METAL_BOLTS; - else if (!Q_stricmp(tokenStr,"AMMO_ROCKETS")) + else if (!Q_stricmp(tokenStr, "AMMO_ROCKETS")) tag = AMMO_ROCKETS; - else if (!Q_stricmp(tokenStr,"AMMO_EMPLACED")) + else if (!Q_stricmp(tokenStr, "AMMO_EMPLACED")) tag = AMMO_EMPLACED; - else if (!Q_stricmp(tokenStr,"AMMO_THERMAL")) + else if (!Q_stricmp(tokenStr, "AMMO_THERMAL")) tag = AMMO_THERMAL; - else if (!Q_stricmp(tokenStr,"AMMO_TRIPMINE")) + else if (!Q_stricmp(tokenStr, "AMMO_TRIPMINE")) tag = AMMO_TRIPMINE; - else if (!Q_stricmp(tokenStr,"AMMO_DETPACK")) + else if (!Q_stricmp(tokenStr, "AMMO_DETPACK")) tag = AMMO_DETPACK; - else if (!Q_stricmp(tokenStr,"FP_HEAL")) - { + else if (!Q_stricmp(tokenStr, "FP_HEAL")) { tag = FP_HEAL; - } - else if (!Q_stricmp(tokenStr,"FP_LEVITATION")) - { + } else if (!Q_stricmp(tokenStr, "FP_LEVITATION")) { tag = FP_LEVITATION; - } - else if (!Q_stricmp(tokenStr,"FP_SPEED")) - { + } else if (!Q_stricmp(tokenStr, "FP_SPEED")) { tag = FP_SPEED; - } - else if (!Q_stricmp(tokenStr,"FP_PUSH")) - { + } else if (!Q_stricmp(tokenStr, "FP_PUSH")) { tag = FP_PUSH; - } - else if (!Q_stricmp(tokenStr,"FP_PULL")) - { + } else if (!Q_stricmp(tokenStr, "FP_PULL")) { tag = FP_PULL; - } - else if (!Q_stricmp(tokenStr,"FP_TELEPATHY")) - { + } else if (!Q_stricmp(tokenStr, "FP_TELEPATHY")) { tag = FP_TELEPATHY; - } - else if (!Q_stricmp(tokenStr,"FP_GRIP")) - { + } else if (!Q_stricmp(tokenStr, "FP_GRIP")) { tag = FP_GRIP; - } - else if (!Q_stricmp(tokenStr,"FP_LIGHTNING")) - { + } else if (!Q_stricmp(tokenStr, "FP_LIGHTNING")) { tag = FP_LIGHTNING; - } - else if (!Q_stricmp(tokenStr,"FP_SABERTHROW")) - { + } else if (!Q_stricmp(tokenStr, "FP_SABERTHROW")) { tag = FP_SABERTHROW; - } - else if (!Q_stricmp(tokenStr,"ITM_BATTERY_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_BATTERY_PICKUP")) { tag = ITM_BATTERY_PICKUP; - } - else if (!Q_stricmp(tokenStr,"INV_SEEKER")) - { + } else if (!Q_stricmp(tokenStr, "INV_SEEKER")) { tag = INV_SEEKER; - } - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_PICKUP")) { tag = ITM_SHIELD_PICKUP; - } - else if (!Q_stricmp(tokenStr,"INV_BACTA_CANISTER")) - { + } else if (!Q_stricmp(tokenStr, "INV_BACTA_CANISTER")) { tag = INV_BACTA_CANISTER; - } - else if (!Q_stricmp(tokenStr,"ITM_DATAPAD_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_DATAPAD_PICKUP")) { tag = ITM_DATAPAD_PICKUP; - } - else if (!Q_stricmp(tokenStr,"INV_ELECTROBINOCULARS")) - { + } else if (!Q_stricmp(tokenStr, "INV_ELECTROBINOCULARS")) { tag = INV_ELECTROBINOCULARS; - } - else if (!Q_stricmp(tokenStr,"INV_SENTRY")) - { + } else if (!Q_stricmp(tokenStr, "INV_SENTRY")) { tag = INV_SENTRY; - } - else if (!Q_stricmp(tokenStr,"INV_LIGHTAMP_GOGGLES")) - { + } else if (!Q_stricmp(tokenStr, "INV_LIGHTAMP_GOGGLES")) { tag = INV_LIGHTAMP_GOGGLES; - } - else if (!Q_stricmp(tokenStr,"INV_GOODIE_KEY")) - { + } else if (!Q_stricmp(tokenStr, "INV_GOODIE_KEY")) { tag = INV_GOODIE_KEY; - } - else if (!Q_stricmp(tokenStr,"INV_SECURITY_KEY")) - { + } else if (!Q_stricmp(tokenStr, "INV_SECURITY_KEY")) { tag = INV_SECURITY_KEY; - } - else if (!Q_stricmp(tokenStr,"ITM_MEDPAK_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_MEDPAK_PICKUP")) { tag = ITM_MEDPAK_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_SM_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_SM_PICKUP")) { tag = ITM_SHIELD_SM_PICKUP; - } - else if (!Q_stricmp(tokenStr,"ITM_SHIELD_LRG_PICKUP")) - { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_LRG_PICKUP")) { tag = ITM_SHIELD_LRG_PICKUP; - } - else - { + } else { tag = WP_BRYAR_PISTOL; - //This error was slipping through too much, causing runaway exceptions and shutting down, so now it's a real error when not in Final + // This error was slipping through too much, causing runaway exceptions and shutting down, so now it's a real error when not in Final #ifndef FINAL_BUILD G_Error("ERROR: bad tagname in external item data '%s'\n", tokenStr); #else @@ -492,59 +397,51 @@ static void IT_Tag(const char **holdBuf) } bg_itemlist[itemParms.itemNum].giTag = tag; - } -static void IT_Type(const char **holdBuf) -{ +static void IT_Type(const char **holdBuf) { int type; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if (!Q_stricmp(tokenStr,"IT_BAD")) + if (!Q_stricmp(tokenStr, "IT_BAD")) type = IT_BAD; - else if (!Q_stricmp(tokenStr,"IT_WEAPON")) + else if (!Q_stricmp(tokenStr, "IT_WEAPON")) type = IT_WEAPON; - else if (!Q_stricmp(tokenStr,"IT_AMMO")) + else if (!Q_stricmp(tokenStr, "IT_AMMO")) type = IT_AMMO; - else if (!Q_stricmp(tokenStr,"IT_ARMOR")) + else if (!Q_stricmp(tokenStr, "IT_ARMOR")) type = IT_ARMOR; - else if (!Q_stricmp(tokenStr,"IT_HEALTH")) + else if (!Q_stricmp(tokenStr, "IT_HEALTH")) type = IT_HEALTH; - else if (!Q_stricmp(tokenStr,"IT_HOLDABLE")) + else if (!Q_stricmp(tokenStr, "IT_HOLDABLE")) type = IT_HOLDABLE; - else if (!Q_stricmp(tokenStr,"IT_BATTERY")) + else if (!Q_stricmp(tokenStr, "IT_BATTERY")) type = IT_BATTERY; - else if (!Q_stricmp(tokenStr,"IT_HOLOCRON")) + else if (!Q_stricmp(tokenStr, "IT_HOLOCRON")) type = IT_HOLOCRON; - else - { + else { type = IT_BAD; gi.Printf("WARNING: bad itemname in external item data '%s'\n", tokenStr); } - bg_itemlist[itemParms.itemNum].giType = (itemType_t) type; - + bg_itemlist[itemParms.itemNum].giType = (itemType_t)type; } -static void IT_Icon(const char **holdBuf) -{ +static void IT_Icon(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 32) - { + if (len > 32) { len = 32; gi.Printf("WARNING: icon too long in external ITEMS.DAT '%s'\n", tokenStr); } @@ -552,76 +449,61 @@ static void IT_Icon(const char **holdBuf) bg_itemlist[itemParms.itemNum].icon = G_NewString(tokenStr); } -static void IT_Count(const char **holdBuf) -{ - int tokenInt; +static void IT_Count(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 1000)) // FIXME :What are the right values? { gi.Printf("WARNING: bad Count in external item data '%d'\n", tokenInt); return; } bg_itemlist[itemParms.itemNum].quantity = tokenInt; - } +static void IT_Min(const char **holdBuf) { + int tokenInt; + int i; -static void IT_Min(const char **holdBuf) -{ - int tokenInt; - int i; - - for (i=0;i<3;++i) - { - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } bg_itemlist[itemParms.itemNum].mins[i] = tokenInt; } - } -static void IT_Max(const char **holdBuf) -{ - int tokenInt; - int i; +static void IT_Max(const char **holdBuf) { + int tokenInt; + int i; - for (i=0;i<3;++i) - { - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } bg_itemlist[itemParms.itemNum].maxs[i] = tokenInt; } - } -static void IT_PickupSound(const char **holdBuf) -{ +static void IT_PickupSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 32) - { + if (len > 32) { len = 32; gi.Printf("WARNING: Pickup Sound too long in external ITEMS.DAT '%s'\n", tokenStr); } @@ -629,30 +511,25 @@ static void IT_PickupSound(const char **holdBuf) bg_itemlist[itemParms.itemNum].pickup_sound = G_NewString(tokenStr); } -static void IT_ParseWeaponParms(const char **holdBuf) -{ - const char *token; - int i; +static void IT_ParseWeaponParms(const char **holdBuf) { + const char *token; + int i; + while (holdBuf) { + token = COM_ParseExt(holdBuf, qtrue); - while (holdBuf) - { - token = COM_ParseExt( holdBuf, qtrue ); - - if (!Q_stricmp( token, "}" )) // End of data for this weapon + if (!Q_stricmp(token, "}")) // End of data for this weapon break; // Loop through possible parameters - for (i=0;i. #include "../cgame/cg_local.h" #include "b_local.h" -extern qboolean missionInfo_Updated; +extern qboolean missionInfo_Updated; extern void CrystalAmmoSettings(gentity_t *ent); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); -extern void WP_SetSaber( gentity_t *ent, int saberNum, const char *saberName ); -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); -extern void WP_SaberFallSound( gentity_t *owner, gentity_t *saber ); -extern saber_colors_t TranslateSaberColor( const char *name ); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); +extern void WP_SetSaber(gentity_t *ent, int saberNum, const char *saberName); +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); +extern void WP_SaberFallSound(gentity_t *owner, gentity_t *saber); +extern saber_colors_t TranslateSaberColor(const char *name); -extern cvar_t *g_spskill; -extern cvar_t *g_sex; -extern cvar_t *g_saberPickuppableDroppedSabers; +extern cvar_t *g_spskill; +extern cvar_t *g_sex; +extern cvar_t *g_saberPickuppableDroppedSabers; -#define MAX_BACTA_HEAL_AMOUNT 25 +#define MAX_BACTA_HEAL_AMOUNT 25 /* @@ -59,15 +59,15 @@ extern cvar_t *g_saberPickuppableDroppedSabers; */ // Item Spawn flags -#define ITMSF_SUSPEND 1 -#define ITMSF_NOPLAYER 2 -#define ITMSF_ALLOWNPC 4 -#define ITMSF_NOTSOLID 8 -#define ITMSF_VERTICAL 16 -#define ITMSF_INVISIBLE 32 -#define ITMSF_NOGLOW 64 -#define ITMSF_USEPICKUP 128 -#define ITMSF_STATIONARY 2048 +#define ITMSF_SUSPEND 1 +#define ITMSF_NOPLAYER 2 +#define ITMSF_ALLOWNPC 4 +#define ITMSF_NOTSOLID 8 +#define ITMSF_VERTICAL 16 +#define ITMSF_INVISIBLE 32 +#define ITMSF_NOGLOW 64 +#define ITMSF_USEPICKUP 128 +#define ITMSF_STATIONARY 2048 //====================================================================== @@ -76,53 +76,42 @@ extern cvar_t *g_saberPickuppableDroppedSabers; G_InventorySelectable =============== */ -qboolean G_InventorySelectable( int index,gentity_t *other) -{ - if (other->client->ps.inventory[index]) - { +qboolean G_InventorySelectable(int index, gentity_t *other) { + if (other->client->ps.inventory[index]) { return qtrue; } return qfalse; } -extern qboolean INV_GoodieKeyGive( gentity_t *target ); -extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); -int Pickup_Holdable( gentity_t *ent, gentity_t *other ) -{ - int i,original; - - other->client->ps.stats[STAT_ITEMS] |= (1<item->giTag); - - if ( ent->item->giTag == INV_SECURITY_KEY ) - {//give the key - //FIXME: temp message - gi.SendServerCommand( 0, "cp @SP_INGAME_YOU_TOOK_SECURITY_KEY" ); - INV_SecurityKeyGive( other, ent->message ); - } - else if ( ent->item->giTag == INV_GOODIE_KEY ) - {//give the key - //FIXME: temp message - gi.SendServerCommand( 0, "cp @SP_INGAME_YOU_TOOK_SUPPLY_KEY" ); - INV_GoodieKeyGive( other ); - } - else - {// Picking up a normal item? +extern qboolean INV_GoodieKeyGive(gentity_t *target); +extern qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname); +int Pickup_Holdable(gentity_t *ent, gentity_t *other) { + int i, original; + + other->client->ps.stats[STAT_ITEMS] |= (1 << ent->item->giTag); + + if (ent->item->giTag == INV_SECURITY_KEY) { // give the key + // FIXME: temp message + gi.SendServerCommand(0, "cp @SP_INGAME_YOU_TOOK_SECURITY_KEY"); + INV_SecurityKeyGive(other, ent->message); + } else if (ent->item->giTag == INV_GOODIE_KEY) { // give the key + // FIXME: temp message + gi.SendServerCommand(0, "cp @SP_INGAME_YOU_TOOK_SUPPLY_KEY"); + INV_GoodieKeyGive(other); + } else { // Picking up a normal item? other->client->ps.inventory[ent->item->giTag]++; } // Got a security key // Set the inventory select, just in case it hasn't original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + for (i = 0; i < INV_MAX; i++) { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = (INV_MAX - 1); } - if ( G_InventorySelectable( cg.inventorySelect,other ) ) - { + if (G_InventorySelectable(cg.inventorySelect, other)) { return 60; } cg.inventorySelect++; @@ -133,309 +122,248 @@ int Pickup_Holdable( gentity_t *ent, gentity_t *other ) return 60; } - //====================================================================== -int Add_Ammo2 (gentity_t *ent, int ammoType, int count) -{ +int Add_Ammo2(gentity_t *ent, int ammoType, int count) { - if (ammoType != AMMO_FORCE) - { + if (ammoType != AMMO_FORCE) { ent->client->ps.ammo[ammoType] += count; // since the ammo is the weapon in this case, picking up ammo should actually give you the weapon - switch( ammoType ) - { + switch (ammoType) { case AMMO_THERMAL: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_THERMAL ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_THERMAL); break; case AMMO_DETPACK: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_DET_PACK ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_DET_PACK); break; case AMMO_TRIPMINE: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_TRIP_MINE ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_TRIP_MINE); break; } - if ( ent->client->ps.ammo[ammoType] > ammoData[ammoType].max ) - { + if (ent->client->ps.ammo[ammoType] > ammoData[ammoType].max) { ent->client->ps.ammo[ammoType] = ammoData[ammoType].max; return qfalse; } - } - else - { - if ( ent->client->ps.forcePower >= ammoData[ammoType].max ) - {//if have full force, just get 25 extra per crystal + } else { + if (ent->client->ps.forcePower >= ammoData[ammoType].max) { // if have full force, just get 25 extra per crystal ent->client->ps.forcePower += 25; - } - else - {//else if don't have full charge, give full amount, up to max + 25 + } else { // else if don't have full charge, give full amount, up to max + 25 ent->client->ps.forcePower += count; - if ( ent->client->ps.forcePower >= ammoData[ammoType].max + 25 ) - {//cap at max + 25 + if (ent->client->ps.forcePower >= ammoData[ammoType].max + 25) { // cap at max + 25 ent->client->ps.forcePower = ammoData[ammoType].max + 25; } } - if ( ent->client->ps.forcePower >= ammoData[ammoType].max*2 ) - {//always cap at twice a full charge - ent->client->ps.forcePower = ammoData[ammoType].max*2; - return qfalse; // can't hold any more + if (ent->client->ps.forcePower >= ammoData[ammoType].max * 2) { // always cap at twice a full charge + ent->client->ps.forcePower = ammoData[ammoType].max * 2; + return qfalse; // can't hold any more } } return qtrue; } //------------------------------------------------------- -void Add_Ammo (gentity_t *ent, int weapon, int count) -{ - Add_Ammo2(ent,weaponData[weapon].ammoIndex,count); -} +void Add_Ammo(gentity_t *ent, int weapon, int count) { Add_Ammo2(ent, weaponData[weapon].ammoIndex, count); } //------------------------------------------------------- -int Pickup_Ammo (gentity_t *ent, gentity_t *other) -{ - int quantity; +int Pickup_Ammo(gentity_t *ent, gentity_t *other) { + int quantity; - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; } - Add_Ammo2 (other, ent->item->giTag, quantity); + Add_Ammo2(other, ent->item->giTag, quantity); return 30; } //====================================================================== -void Add_Batteries( gentity_t *ent, int *count ) -{ - if ( ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count ) - { - if ( *count + ent->client->ps.batteryCharge > MAX_BATTERIES ) - { +void Add_Batteries(gentity_t *ent, int *count) { + if (ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count) { + if (*count + ent->client->ps.batteryCharge > MAX_BATTERIES) { // steal what we need, then leave the rest for later - *count -= ( MAX_BATTERIES - ent->client->ps.batteryCharge ); + *count -= (MAX_BATTERIES - ent->client->ps.batteryCharge); ent->client->ps.batteryCharge = MAX_BATTERIES; - } - else - { + } else { // just drain all of the batteries ent->client->ps.batteryCharge += *count; *count = 0; } - G_AddEvent( ent, EV_BATTERIES_CHARGED, 0 ); + G_AddEvent(ent, EV_BATTERIES_CHARGED, 0); } } //------------------------------------------------------- -int Pickup_Battery( gentity_t *ent, gentity_t *other ) -{ - int quantity; +int Pickup_Battery(gentity_t *ent, gentity_t *other) { + int quantity; - if ( ent->count ) - { + if (ent->count) { quantity = ent->count; - } - else - { + } else { quantity = ent->item->quantity; } // There may be some left over in quantity if the player is close to full, but with pickup items, this amount will just be lost - Add_Batteries( other, &quantity ); + Add_Batteries(other, &quantity); return 30; } //====================================================================== -void G_CopySaberItemValues( gentity_t *pickUpSaber, gentity_t *oldSaber ) -{ - if ( oldSaber && pickUpSaber ) - { +void G_CopySaberItemValues(gentity_t *pickUpSaber, gentity_t *oldSaber) { + if (oldSaber && pickUpSaber) { oldSaber->spawnflags = pickUpSaber->spawnflags; oldSaber->random = pickUpSaber->random; oldSaber->flags = pickUpSaber->flags; } } -gentity_t *G_DropSaberItem( const char *saberType, saber_colors_t saberColor, vec3_t saberPos, vec3_t saberVel, vec3_t saberAngles, gentity_t *copySaber ) -{//turn it into a pick-uppable item! +gentity_t *G_DropSaberItem(const char *saberType, saber_colors_t saberColor, vec3_t saberPos, vec3_t saberVel, vec3_t saberAngles, + gentity_t *copySaber) { // turn it into a pick-uppable item! gentity_t *newItem = NULL; - if ( saberType - && saberType[0] ) - {//have a valid string to use for saberType + if (saberType && saberType[0]) { // have a valid string to use for saberType newItem = G_Spawn(); - if ( newItem ) - { - newItem->classname = G_NewString( "weapon_saber" ); - VectorCopy( saberPos, newItem->s.origin ); - G_SetOrigin( newItem, newItem->s.origin ); - VectorCopy( saberAngles, newItem->s.angles ); - G_SetAngles( newItem, newItem->s.angles ); - newItem->spawnflags = 128;/*ITMSF_USEPICKUP*/ - newItem->spawnflags |= 64;/*ITMSF_NOGLOW*/ - newItem->NPC_type = G_NewString( saberType );//saberType - //FIXME: transfer per-blade color somehow? + if (newItem) { + newItem->classname = G_NewString("weapon_saber"); + VectorCopy(saberPos, newItem->s.origin); + G_SetOrigin(newItem, newItem->s.origin); + VectorCopy(saberAngles, newItem->s.angles); + G_SetAngles(newItem, newItem->s.angles); + newItem->spawnflags = 128; /*ITMSF_USEPICKUP*/ + newItem->spawnflags |= 64; /*ITMSF_NOGLOW*/ + newItem->NPC_type = G_NewString(saberType); // saberType + // FIXME: transfer per-blade color somehow? newItem->NPC_targetname = (char *)saberColorStringForColor[saberColor]; newItem->count = 1; newItem->flags = FL_DROPPED_ITEM; - G_SpawnItem( newItem, FindItemForWeapon( WP_SABER ) ); + G_SpawnItem(newItem, FindItemForWeapon(WP_SABER)); newItem->s.pos.trType = TR_GRAVITY; newItem->s.pos.trTime = level.time; - VectorCopy( saberVel, newItem->s.pos.trDelta ); - //newItem->s.eFlags |= EF_BOUNCE_HALF; - //copy some values from another saber, if provided: - G_CopySaberItemValues( copySaber, newItem ); - //don't *think* about calling FinishSpawningItem, just do it! + VectorCopy(saberVel, newItem->s.pos.trDelta); + // newItem->s.eFlags |= EF_BOUNCE_HALF; + // copy some values from another saber, if provided: + G_CopySaberItemValues(copySaber, newItem); + // don't *think* about calling FinishSpawningItem, just do it! newItem->e_ThinkFunc = thinkF_NULL; newItem->nextthink = -1; - FinishSpawningItem( newItem ); - newItem->delay = level.time + 500;//so you can't pick it back up right away + FinishSpawningItem(newItem); + newItem->delay = level.time + 500; // so you can't pick it back up right away } } return newItem; } -extern void G_SetSabersFromCVars( gentity_t *ent ); -qboolean Pickup_Saber( gentity_t *self, qboolean hadSaber, gentity_t *pickUpSaber ) -{ - //NOTE: loopAnim = saberSolo, alt_fire = saberLeftHand, NPC_type = saberType, NPC_targetname = saberColor +extern void G_SetSabersFromCVars(gentity_t *ent); +qboolean Pickup_Saber(gentity_t *self, qboolean hadSaber, gentity_t *pickUpSaber) { + // NOTE: loopAnim = saberSolo, alt_fire = saberLeftHand, NPC_type = saberType, NPC_targetname = saberColor qboolean foundIt = qfalse; - if ( !pickUpSaber || !self || !self->client ) - { + if (!pickUpSaber || !self || !self->client) { return qfalse; } - //G_RemoveWeaponModels( ent );//??? - if ( Q_stricmp( "player", pickUpSaber->NPC_type ) == 0 ) - {//"player" means use cvar info - G_SetSabersFromCVars( self ); + // G_RemoveWeaponModels( ent );//??? + if (Q_stricmp("player", pickUpSaber->NPC_type) == 0) { //"player" means use cvar info + G_SetSabersFromCVars(self); foundIt = qtrue; - } - else - { - saberInfo_t newSaber={0}; + } else { + saberInfo_t newSaber = {0}; qboolean swapSabers = qfalse; - if ( self->client->ps.weapon == WP_SABER - && self->client->ps.weaponTime > 0 ) - {//can't pick up a new saber while the old one is busy (also helps to work as a debouncer so you don't swap out sabers rapidly when touching more than one at a time) + if (self->client->ps.weapon == WP_SABER && + self->client->ps.weaponTime > 0) { // can't pick up a new saber while the old one is busy (also helps to work as a debouncer so you don't swap out + // sabers rapidly when touching more than one at a time) return qfalse; } - if ( pickUpSaber->count == 1 - && g_saberPickuppableDroppedSabers->integer ) - { + if (pickUpSaber->count == 1 && g_saberPickuppableDroppedSabers->integer) { swapSabers = qtrue; } - if ( WP_SaberParseParms( pickUpSaber->NPC_type, &newSaber ) ) - {//successfully found a saber .sab entry to use - int saberNum = 0; + if (WP_SaberParseParms(pickUpSaber->NPC_type, &newSaber)) { // successfully found a saber .sab entry to use + int saberNum = 0; qboolean removeLeftSaber = qfalse; - if ( pickUpSaber->alt_fire ) - {//always go in the left hand - if ( !hadSaber ) - {//can't have a saber only in your left hand! + if (pickUpSaber->alt_fire) { // always go in the left hand + if (!hadSaber) { // can't have a saber only in your left hand! return qfalse; } saberNum = 1; - //just in case... + // just in case... removeLeftSaber = qtrue; - } - else if ( !hadSaber ) - {//don't have a saber at all yet, put it in our right hand + } else if (!hadSaber) { // don't have a saber at all yet, put it in our right hand saberNum = 0; - //just in case... + // just in case... removeLeftSaber = qtrue; - } - else if ( pickUpSaber->loopAnim//only supposed to use this one saber when grab this pickup - || (newSaber.saberFlags&SFL_TWO_HANDED) //new saber is two-handed - || (hadSaber && (self->client->ps.saber[0].saberFlags&SFL_TWO_HANDED)) )//old saber is two-handed - {//replace the old right-hand saber and remove the left hand one + } else if (pickUpSaber->loopAnim // only supposed to use this one saber when grab this pickup + || (newSaber.saberFlags & SFL_TWO_HANDED) // new saber is two-handed + || (hadSaber && (self->client->ps.saber[0].saberFlags & SFL_TWO_HANDED))) // old saber is two-handed + { // replace the old right-hand saber and remove the left hand one saberNum = 0; removeLeftSaber = qtrue; - } - else - {//have, at least, a saber in our right hand and the new one could go in either left or right hand - if ( self->client->ps.dualSabers ) - {//I already have 2 sabers + } else { // have, at least, a saber in our right hand and the new one could go in either left or right hand + if (self->client->ps.dualSabers) { // I already have 2 sabers vec3_t dir2Saber, rightDir; - //to determine which one to replace, see which side of me it's on - VectorSubtract( pickUpSaber->currentOrigin, self->currentOrigin, dir2Saber ); + // to determine which one to replace, see which side of me it's on + VectorSubtract(pickUpSaber->currentOrigin, self->currentOrigin, dir2Saber); dir2Saber[2] = 0; - AngleVectors( self->currentAngles, NULL, rightDir, NULL ); + AngleVectors(self->currentAngles, NULL, rightDir, NULL); rightDir[2] = 0; - if ( DotProduct( rightDir, dir2Saber ) > 0 ) - { + if (DotProduct(rightDir, dir2Saber) > 0) { saberNum = 0; - } - else - { + } else { saberNum = 1; - //just in case... + // just in case... removeLeftSaber = qtrue; } - } - else - {//just add it as a second saber + } else { // just add it as a second saber saberNum = 1; - //just in case... + // just in case... removeLeftSaber = qtrue; } } - if ( saberNum == 0 ) - {//want to reach out with right hand - if ( self->client->ps.torsoAnim == BOTH_BUTTON_HOLD ) - {//but only if already playing the pickup with left hand anim... - NPC_SetAnim( self, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (saberNum == 0) { // want to reach out with right hand + if (self->client->ps.torsoAnim == BOTH_BUTTON_HOLD) { // but only if already playing the pickup with left hand anim... + NPC_SetAnim(self, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( swapSabers ) - {//drop first one where the one we're picking up is - G_DropSaberItem( self->client->ps.saber[saberNum].name, self->client->ps.saber[saberNum].blade[0].color, pickUpSaber->currentOrigin, (float *)vec3_origin, pickUpSaber->currentAngles, pickUpSaber ); - if ( removeLeftSaber ) - {//drop other one at my origin - G_DropSaberItem( self->client->ps.saber[1].name, self->client->ps.saber[1].blade[0].color, self->currentOrigin, (float *)vec3_origin, self->currentAngles, pickUpSaber ); + if (swapSabers) { // drop first one where the one we're picking up is + G_DropSaberItem(self->client->ps.saber[saberNum].name, self->client->ps.saber[saberNum].blade[0].color, pickUpSaber->currentOrigin, + (float *)vec3_origin, pickUpSaber->currentAngles, pickUpSaber); + if (removeLeftSaber) { // drop other one at my origin + G_DropSaberItem(self->client->ps.saber[1].name, self->client->ps.saber[1].blade[0].color, self->currentOrigin, (float *)vec3_origin, + self->currentAngles, pickUpSaber); } } - } - else - { - if ( swapSabers ) - { - G_DropSaberItem( self->client->ps.saber[saberNum].name, self->client->ps.saber[saberNum].blade[0].color, pickUpSaber->currentOrigin, (float *)vec3_origin, pickUpSaber->currentAngles, pickUpSaber ); + } else { + if (swapSabers) { + G_DropSaberItem(self->client->ps.saber[saberNum].name, self->client->ps.saber[saberNum].blade[0].color, pickUpSaber->currentOrigin, + (float *)vec3_origin, pickUpSaber->currentAngles, pickUpSaber); } } - if ( removeLeftSaber ) - { - WP_RemoveSaber( self, 1 ); + if (removeLeftSaber) { + WP_RemoveSaber(self, 1); } - WP_SetSaber( self, saberNum, pickUpSaber->NPC_type ); - WP_SaberInitBladeData( self ); - if ( self->client->ps.saber[saberNum].stylesLearned ) - { + WP_SetSaber(self, saberNum, pickUpSaber->NPC_type); + WP_SaberInitBladeData(self); + if (self->client->ps.saber[saberNum].stylesLearned) { self->client->ps.saberStylesKnown |= self->client->ps.saber[saberNum].stylesLearned; } - if ( self->client->ps.saber[saberNum].singleBladeStyle ) - { + if (self->client->ps.saber[saberNum].singleBladeStyle) { self->client->ps.saberStylesKnown |= self->client->ps.saber[saberNum].singleBladeStyle; } - if ( pickUpSaber->NPC_targetname != NULL ) - {//NPC_targetname = saberColor - saber_colors_t saber_color = TranslateSaberColor( pickUpSaber->NPC_targetname ); - for ( int bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++ ) - { + if (pickUpSaber->NPC_targetname != NULL) { // NPC_targetname = saberColor + saber_colors_t saber_color = TranslateSaberColor(pickUpSaber->NPC_targetname); + for (int bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++) { self->client->ps.saber[saberNum].blade[bladeNum].color = saber_color; } } - if ( self->client->ps.torsoAnim == BOTH_BUTTON_HOLD - || self->client->ps.torsoAnim == BOTH_SABERPULL ) - {//don't let them attack right away, force them to finish the anim + if (self->client->ps.torsoAnim == BOTH_BUTTON_HOLD || + self->client->ps.torsoAnim == BOTH_SABERPULL) { // don't let them attack right away, force them to finish the anim self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; } foundIt = qtrue; @@ -445,11 +373,10 @@ qboolean Pickup_Saber( gentity_t *self, qboolean hadSaber, gentity_t *pickUpSabe return foundIt; } -extern void CG_ChangeWeapon( int num ); -int Pickup_Weapon (gentity_t *ent, gentity_t *other) -{ - int quantity; - qboolean hadWeapon = qfalse; +extern void CG_ChangeWeapon(int num); +int Pickup_Weapon(gentity_t *ent, gentity_t *other) { + int quantity; + qboolean hadWeapon = qfalse; /* if ( ent->count || (ent->activator && !ent->activator->s.number) ) @@ -463,88 +390,67 @@ int Pickup_Weapon (gentity_t *ent, gentity_t *other) */ // dropped items are always picked up - if ( ent->flags & FL_DROPPED_ITEM ) - { + if (ent->flags & FL_DROPPED_ITEM) { quantity = ent->count; - } - else - {//wasn't dropped - quantity = ent->item->quantity?ent->item->quantity:50; + } else { // wasn't dropped + quantity = ent->item->quantity ? ent->item->quantity : 50; } // add the weapon - if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) ) - { + if (other->client->ps.stats[STAT_WEAPONS] & (1 << ent->item->giTag)) { hadWeapon = qtrue; } - other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag ); + other->client->ps.stats[STAT_WEAPONS] |= (1 << ent->item->giTag); - if ( ent->item->giTag == WP_SABER && (!hadWeapon || ent->NPC_type != NULL) ) - {//didn't have a saber or it is specifying a certain kind of saber to use - if ( !Pickup_Saber( other, hadWeapon, ent ) ) - { + if (ent->item->giTag == WP_SABER && (!hadWeapon || ent->NPC_type != NULL)) { // didn't have a saber or it is specifying a certain kind of saber to use + if (!Pickup_Saber(other, hadWeapon, ent)) { return 0; } } - if ( other->s.number ) - {//NPC - if ( other->s.weapon == WP_NONE - || ent->item->giTag == WP_SABER ) - {//NPC with no weapon picked up a weapon, change to this weapon - //FIXME: clear/set the alt-fire flag based on the picked up weapon and my class? + if (other->s.number) { // NPC + if (other->s.weapon == WP_NONE || ent->item->giTag == WP_SABER) { // NPC with no weapon picked up a weapon, change to this weapon + // FIXME: clear/set the alt-fire flag based on the picked up weapon and my class? other->client->ps.weapon = ent->item->giTag; other->client->ps.weaponstate = WEAPON_RAISING; - ChangeWeapon( other, ent->item->giTag ); - if ( ent->item->giTag == WP_SABER ) - { + ChangeWeapon(other, ent->item->giTag); + if (ent->item->giTag == WP_SABER) { other->client->ps.SaberActivate(); - WP_SaberAddG2SaberModels( other ); - } - else - { - G_CreateG2AttachedWeaponModel( other, weaponData[ent->item->giTag].weaponMdl, other->handRBolt, 0 ); + WP_SaberAddG2SaberModels(other); + } else { + G_CreateG2AttachedWeaponModel(other, weaponData[ent->item->giTag].weaponMdl, other->handRBolt, 0); } } } - if ( ent->item->giTag == WP_SABER ) - {//picked up a saber - if ( other->s.weapon != WP_SABER ) - {//player picking up saber + if (ent->item->giTag == WP_SABER) { // picked up a saber + if (other->s.weapon != WP_SABER) { // player picking up saber other->client->ps.weapon = WP_SABER; other->client->ps.weaponstate = WEAPON_RAISING; - if ( other->s.number < MAX_CLIENTS ) - {//make sure the cgame-side knows this - CG_ChangeWeapon( WP_SABER ); - } - else - {//make sure the cgame-side knows this - ChangeWeapon( other, WP_SABER ); + if (other->s.number < MAX_CLIENTS) { // make sure the cgame-side knows this + CG_ChangeWeapon(WP_SABER); + } else { // make sure the cgame-side knows this + ChangeWeapon(other, WP_SABER); } } - if ( !other->client->ps.SaberActive() ) - {//turn it/them on! + if (!other->client->ps.SaberActive()) { // turn it/them on! other->client->ps.SaberActivate(); } } - if ( quantity ) - { + if (quantity) { // Give ammo - Add_Ammo( other, ent->item->giTag, quantity ); + Add_Ammo(other, ent->item->giTag, quantity); } return 5; } - //====================================================================== -int ITM_AddHealth (gentity_t *ent, int count) -{ +int ITM_AddHealth(gentity_t *ent, int count) { ent->health += count; - if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health { ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; @@ -552,16 +458,15 @@ int ITM_AddHealth (gentity_t *ent, int count) } return qtrue; - } -int Pickup_Health (gentity_t *ent, gentity_t *other) { - int max; - int quantity; +int Pickup_Health(gentity_t *ent, gentity_t *other) { + int max; + int quantity; max = other->client->ps.stats[STAT_MAX_HEALTH]; - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; @@ -569,11 +474,11 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { other->health += quantity; - if (other->health > max ) { + if (other->health > max) { other->health = max; } - if ( ent->item->giTag == 100 ) { // mega health respawns slow + if (ent->item->giTag == 100) { // mega health respawns slow return 120; } @@ -582,13 +487,11 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { //====================================================================== -int ITM_AddArmor (gentity_t *ent, int count) -{ +int ITM_AddArmor(gentity_t *ent, int count) { ent->client->ps.stats[STAT_ARMOR] += count; - if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; return qfalse; } @@ -596,51 +499,44 @@ int ITM_AddArmor (gentity_t *ent, int count) return qtrue; } - -int Pickup_Armor( gentity_t *ent, gentity_t *other ) { +int Pickup_Armor(gentity_t *ent, gentity_t *other) { // make sure that the shield effect is on other->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; other->client->ps.stats[STAT_ARMOR] += ent->item->quantity; - if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] ) { + if (other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH]) { other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH]; } return 30; } - - //====================================================================== -int Pickup_Holocron( gentity_t *ent, gentity_t *other ) -{ +int Pickup_Holocron(gentity_t *ent, gentity_t *other) { int forcePower = ent->item->giTag; int forceLevel = ent->count; // check if out of range - if( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS ) - { - gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel ); + if (forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS) { + gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel); return 1; } // don't pick up if already known AND your level is higher than pickup level - if ( ( other->client->ps.forcePowersKnown & ( 1 << forcePower )) ) - { - //don't pickup if item is lower than current level - if( other->client->ps.forcePowerLevel[forcePower] >= forceLevel ) - { + if ((other->client->ps.forcePowersKnown & (1 << forcePower))) { + // don't pickup if item is lower than current level + if (other->client->ps.forcePowerLevel[forcePower] >= forceLevel) { return 1; } } other->client->ps.forcePowerLevel[forcePower] = forceLevel; - other->client->ps.forcePowersKnown |= ( 1 << forcePower ); + other->client->ps.forcePowersKnown |= (1 << forcePower); - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine. - cg_updatedDataPadForcePower1.integer = forcePower+1; + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower1", va("%d", forcePower + 1)); // The +1 is offset in the print routine. + cg_updatedDataPadForcePower1.integer = forcePower + 1; gi.cvar_set("cg_updatedDataPadForcePower2", "0"); // The +1 is offset in the print routine. cg_updatedDataPadForcePower2.integer = 0; gi.cvar_set("cg_updatedDataPadForcePower3", "0"); // The +1 is offset in the print routine. @@ -649,7 +545,6 @@ int Pickup_Holocron( gentity_t *ent, gentity_t *other ) return 1; } - //====================================================================== /* @@ -657,29 +552,20 @@ int Pickup_Holocron( gentity_t *ent, gentity_t *other ) RespawnItem =============== */ -void RespawnItem( gentity_t *ent ) { -} - +void RespawnItem(gentity_t *ent) {} -qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) -{ - if ( !item->item ) { +qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper) { + if (!item->item) { return qfalse; } - if ( item->item->giType == IT_HOLDABLE && - item->item->giTag == INV_SECURITY_KEY ) { + if (item->item->giType == IT_HOLDABLE && item->item->giTag == INV_SECURITY_KEY) { return qfalse; } - if ( (item->flags&FL_DROPPED_ITEM) - && item->activator != &g_entities[0] - && pickerupper->s.number - && pickerupper->s.weapon == WP_NONE - && pickerupper->enemy - && pickerupper->painDebounceTime < level.time - && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time //not surrendering - && !(pickerupper->NPC->scriptFlags&SCF_FORCED_MARCH) ) // not being forced to march - {//non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key - if ( level.time - item->s.time < 3000 )//was 5000 + if ((item->flags & FL_DROPPED_ITEM) && item->activator != &g_entities[0] && pickerupper->s.number && pickerupper->s.weapon == WP_NONE && + pickerupper->enemy && pickerupper->painDebounceTime < level.time && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time // not surrendering + && !(pickerupper->NPC->scriptFlags & SCF_FORCED_MARCH)) // not being forced to march + { // non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key + if (level.time - item->s.time < 3000) // was 5000 { return qfalse; } @@ -688,14 +574,11 @@ qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) return qfalse; } -qboolean G_CanPickUpWeapons( gentity_t *other ) -{ - if ( !other || !other->client ) - { +qboolean G_CanPickUpWeapons(gentity_t *other) { + if (!other || !other->client) { return qfalse; } - switch ( other->client->NPC_class ) - { + switch (other->client->NPC_class) { case CLASS_ATST: case CLASS_GONK: case CLASS_MARK1: @@ -709,8 +592,8 @@ qboolean G_CanPickUpWeapons( gentity_t *other ) case CLASS_REMOTE: case CLASS_RANCOR: case CLASS_WAMPA: - case CLASS_JAWA: //FIXME: in some cases it's okay? - case CLASS_UGNAUGHT: //FIXME: in some cases it's okay? + case CLASS_JAWA: // FIXME: in some cases it's okay? + case CLASS_UGNAUGHT: // FIXME: in some cases it's okay? case CLASS_SENTRY: return qfalse; break; @@ -724,123 +607,99 @@ qboolean G_CanPickUpWeapons( gentity_t *other ) Touch_Item =============== */ -extern cvar_t *g_timescale; -void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { - int respawn = 0; +extern cvar_t *g_timescale; +void Touch_Item(gentity_t *ent, gentity_t *other, trace_t *trace) { + int respawn = 0; if (!other->client) return; if (other->health < 1) - return; // dead people can't pickup + return; // dead people can't pickup - if ( other->client->ps.pm_time > 0 ) - {//cant pick up when out of control + if (other->client->ps.pm_time > 0) { // cant pick up when out of control return; } // NPCs can pick it up - if ((ent->spawnflags & ITMSF_ALLOWNPC) && (!other->s.number)) - { + if ((ent->spawnflags & ITMSF_ALLOWNPC) && (!other->s.number)) { return; } // Players cannot pick it up - if ( (ent->spawnflags & ITMSF_NOPLAYER) && (other->s.number) ) - { + if ((ent->spawnflags & ITMSF_NOPLAYER) && (other->s.number)) { return; } - if ( ent->noDamageTeam != TEAM_FREE && other->client->playerTeam != ent->noDamageTeam ) - {//only one team can pick it up + if (ent->noDamageTeam != TEAM_FREE && other->client->playerTeam != ent->noDamageTeam) { // only one team can pick it up return; } - if ( !G_CanPickUpWeapons( other ) ) - {//FIXME: some flag would be better - //droids can't pick up items/weapons! + if (!G_CanPickUpWeapons(other)) { // FIXME: some flag would be better + // droids can't pick up items/weapons! return; } - //FIXME: need to make them run toward a dropped weapon when fleeing without one? - //FIXME: need to make them come out of flee mode when pick up their old weapon? - if ( CheckItemCanBePickedUpByNPC( ent, other ) ) - { - if ( other->NPC && other->NPC->goalEntity && other->NPC->goalEntity == ent ) - {//they were running to pick me up, they did, so clear goal - other->NPC->goalEntity = NULL; - other->NPC->squadState = SQUAD_STAND_AND_SHOOT; - NPCInfo->tempBehavior = BS_DEFAULT; + // FIXME: need to make them run toward a dropped weapon when fleeing without one? + // FIXME: need to make them come out of flee mode when pick up their old weapon? + if (CheckItemCanBePickedUpByNPC(ent, other)) { + if (other->NPC && other->NPC->goalEntity && other->NPC->goalEntity == ent) { // they were running to pick me up, they did, so clear goal + other->NPC->goalEntity = NULL; + other->NPC->squadState = SQUAD_STAND_AND_SHOOT; + NPCInfo->tempBehavior = BS_DEFAULT; TIMER_Set(other, "flee", -1); - } - else - { + } else { return; } - } - else if ( !(ent->spawnflags & ITMSF_ALLOWNPC) ) - {// NPCs cannot pick it up - if ( other->s.number != 0 ) - {// Not the player? + } else if (!(ent->spawnflags & ITMSF_ALLOWNPC)) { // NPCs cannot pick it up + if (other->s.number != 0) { // Not the player? return; } } // the same pickup rules are used for client side and server side - if ( !BG_CanItemBeGrabbed( &ent->s, &other->client->ps ) ) { + if (!BG_CanItemBeGrabbed(&ent->s, &other->client->ps)) { return; } - if ( other->client ) - { - if ( (other->client->ps.eFlags&EF_FORCE_GRIPPED) || (other->client->ps.eFlags&EF_FORCE_DRAINED) ) - {//can't pick up anything while being gripped + if (other->client) { + if ((other->client->ps.eFlags & EF_FORCE_GRIPPED) || (other->client->ps.eFlags & EF_FORCE_DRAINED)) { // can't pick up anything while being gripped return; } - if ( PM_InKnockDown( &other->client->ps ) && !PM_InGetUp( &other->client->ps ) ) - {//can't pick up while in a knockdown + if (PM_InKnockDown(&other->client->ps) && !PM_InGetUp(&other->client->ps)) { // can't pick up while in a knockdown return; } } - if (!ent->item) { //not an item! - gi.Printf( "Touch_Item: %s is not an item!\n", ent->classname); + if (!ent->item) { // not an item! + gi.Printf("Touch_Item: %s is not an item!\n", ent->classname); return; } - if ( ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER ) - {//a saber - if ( ent->delay > level.time ) - {//just picked it up, don't pick up again right away + if (ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER) { // a saber + if (ent->delay > level.time) { // just picked it up, don't pick up again right away return; } } - if ( other->s.number < MAX_CLIENTS - && (ent->spawnflags&ITMSF_USEPICKUP) ) - {//only if player is holing use button - if ( !(other->client->usercmd.buttons&BUTTON_USE) ) - {//not holding use? + if (other->s.number < MAX_CLIENTS && (ent->spawnflags & ITMSF_USEPICKUP)) { // only if player is holing use button + if (!(other->client->usercmd.buttons & BUTTON_USE)) { // not holding use? return; } } qboolean bHadWeapon = qfalse; // call the item-specific pickup function - switch( ent->item->giType ) - { + switch (ent->item->giType) { case IT_WEAPON: - if ( other->NPC && other->s.weapon == WP_NONE ) - {//Make them duck and sit here for a few seconds - int pickUpTime = Q_irand( 1000, 3000 ); - TIMER_Set( other, "duck", pickUpTime ); - TIMER_Set( other, "roamTime", pickUpTime ); - TIMER_Set( other, "stick", pickUpTime ); - TIMER_Set( other, "verifyCP", pickUpTime ); - TIMER_Set( other, "attackDelay", 600 ); + if (other->NPC && other->s.weapon == WP_NONE) { // Make them duck and sit here for a few seconds + int pickUpTime = Q_irand(1000, 3000); + TIMER_Set(other, "duck", pickUpTime); + TIMER_Set(other, "roamTime", pickUpTime); + TIMER_Set(other, "stick", pickUpTime); + TIMER_Set(other, "verifyCP", pickUpTime); + TIMER_Set(other, "attackDelay", 600); respawn = 0; } - if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) ) - { + if (other->client->ps.stats[STAT_WEAPONS] & (1 << ent->item->giTag)) { bHadWeapon = qtrue; } respawn = Pickup_Weapon(ent, other); @@ -858,64 +717,53 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { respawn = Pickup_Holdable(ent, other); break; case IT_BATTERY: - respawn = Pickup_Battery( ent, other ); + respawn = Pickup_Battery(ent, other); break; case IT_HOLOCRON: - respawn = Pickup_Holocron( ent, other ); + respawn = Pickup_Holocron(ent, other); break; default: return; } - if ( !respawn ) - { + if (!respawn) { return; } // play the normal pickup sound - if ( !other->s.number && g_timescale->value < 1.0f ) - {//SIGH... with timescale on, you lose events left and right -extern void CG_ItemPickup( int itemNum, qboolean bHadItem ); + if (!other->s.number && g_timescale->value < 1.0f) { // SIGH... with timescale on, you lose events left and right + extern void CG_ItemPickup(int itemNum, qboolean bHadItem); // but we're SP so we'll cheat - cgi_S_StartSound( NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound( ent->item->pickup_sound ) ); + cgi_S_StartSound(NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound(ent->item->pickup_sound)); // show icon and name on status bar - CG_ItemPickup( ent->s.modelindex, bHadWeapon ); - } - else - { - if ( bHadWeapon ) - { - G_AddEvent( other, EV_ITEM_PICKUP, -ent->s.modelindex ); - } - else - { - G_AddEvent( other, EV_ITEM_PICKUP, ent->s.modelindex ); + CG_ItemPickup(ent->s.modelindex, bHadWeapon); + } else { + if (bHadWeapon) { + G_AddEvent(other, EV_ITEM_PICKUP, -ent->s.modelindex); + } else { + G_AddEvent(other, EV_ITEM_PICKUP, ent->s.modelindex); } } // fire item targets - G_UseTargets (ent, other); + G_UseTargets(ent, other); - if ( ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER ) - {//a saber that was picked up - if ( ent->count < 0 ) - {//infinite supply + if (ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER) { // a saber that was picked up + if (ent->count < 0) { // infinite supply ent->delay = level.time + 500; return; } ent->count--; - if ( ent->count > 0 ) - {//still have more to pick up + if (ent->count > 0) { // still have more to pick up ent->delay = level.time + 500; return; } } // wait of -1 will not respawn -// if ( ent->wait == -1 ) + // if ( ent->wait == -1 ) { - //why not just remove me? - G_FreeEntity( ent ); + // why not just remove me? + G_FreeEntity(ent); /* //NOTE: used to do this: (for respawning?) ent->svFlags |= SVF_NOCLIENT; @@ -927,7 +775,6 @@ extern void CG_ItemPickup( int itemNum, qboolean bHadItem ); } } - //====================================================================== /* @@ -937,47 +784,40 @@ LaunchItem Spawns an item and tosses it forward ================ */ -gentity_t *LaunchItem( gitem_t *item, const vec3_t origin, const vec3_t velocity, char *target ) { - gentity_t *dropped; +gentity_t *LaunchItem(gitem_t *item, const vec3_t origin, const vec3_t velocity, char *target) { + gentity_t *dropped; dropped = G_Spawn(); dropped->s.eType = ET_ITEM; - dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex - dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item + dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex + dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item - dropped->classname = G_NewString(item->classname); //copy it so it can be freed safely + dropped->classname = G_NewString(item->classname); // copy it so it can be freed safely dropped->item = item; // try using the "correct" mins/maxs first - VectorSet( dropped->mins, item->mins[0], item->mins[1], item->mins[2] ); - VectorSet( dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2] ); + VectorSet(dropped->mins, item->mins[0], item->mins[1], item->mins[2]); + VectorSet(dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2]); - if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) && - (!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2])) - { - VectorSet( dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS ); - VectorScale( dropped->maxs, -1, dropped->mins ); + if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) && (!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2])) { + VectorSet(dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); + VectorScale(dropped->maxs, -1, dropped->mins); } - dropped->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them + dropped->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; // CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them - if ( target && target[0] ) - { - dropped->target = G_NewString( target ); - } - else - { + if (target && target[0]) { + dropped->target = G_NewString(target); + } else { // if not targeting something, auto-remove after 30 seconds // only if it's NOT a security or goodie key - if (dropped->item->giTag != INV_SECURITY_KEY ) - { + if (dropped->item->giTag != INV_SECURITY_KEY) { dropped->e_ThinkFunc = thinkF_G_FreeEntity; dropped->nextthink = level.time + 30000; } - if ( dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE ) - { + if (dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE) { dropped->nextthink = -1; dropped->e_ThinkFunc = thinkF_NULL; } @@ -985,29 +825,24 @@ gentity_t *LaunchItem( gitem_t *item, const vec3_t origin, const vec3_t velocity dropped->e_TouchFunc = touchF_Touch_Item; - if ( item->giType == IT_WEAPON ) - { + if (item->giType == IT_WEAPON) { // give weapon items zero pitch, a random yaw, and rolled onto their sides...but would be bad to do this for a bowcaster - if ( item->giTag != WP_BOWCASTER - && item->giTag != WP_THERMAL - && item->giTag != WP_TRIP_MINE - && item->giTag != WP_DET_PACK ) - { - VectorSet( dropped->s.angles, 0, Q_flrand(-1.0f, 1.0f) * 180, 90.0f ); - G_SetAngles( dropped, dropped->s.angles ); + if (item->giTag != WP_BOWCASTER && item->giTag != WP_THERMAL && item->giTag != WP_TRIP_MINE && item->giTag != WP_DET_PACK) { + VectorSet(dropped->s.angles, 0, Q_flrand(-1.0f, 1.0f) * 180, 90.0f); + G_SetAngles(dropped, dropped->s.angles); } } - G_SetOrigin( dropped, origin ); + G_SetOrigin(dropped, origin); dropped->s.pos.trType = TR_GRAVITY; dropped->s.pos.trTime = level.time; - VectorCopy( velocity, dropped->s.pos.trDelta ); + VectorCopy(velocity, dropped->s.pos.trDelta); dropped->s.eFlags |= EF_BOUNCE_HALF; dropped->flags = FL_DROPPED_ITEM; - gi.linkentity (dropped); + gi.linkentity(dropped); return dropped; } @@ -1019,34 +854,30 @@ Drop_Item Spawns an item and tosses it forward ================ */ -gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle, qboolean copytarget ) { - gentity_t *dropped = NULL; - vec3_t velocity; - vec3_t angles; +gentity_t *Drop_Item(gentity_t *ent, gitem_t *item, float angle, qboolean copytarget) { + gentity_t *dropped = NULL; + vec3_t velocity; + vec3_t angles; - VectorCopy( ent->s.apos.trBase, angles ); + VectorCopy(ent->s.apos.trBase, angles); angles[YAW] += angle; - angles[PITCH] = 0; // always forward + angles[PITCH] = 0; // always forward - AngleVectors( angles, velocity, NULL, NULL ); - VectorScale( velocity, 150, velocity ); + AngleVectors(angles, velocity, NULL, NULL); + VectorScale(velocity, 150, velocity); velocity[2] += 200 + Q_flrand(-1.0f, 1.0f) * 50; - if ( copytarget ) - { - dropped = LaunchItem( item, ent->s.pos.trBase, velocity, ent->opentarget ); - } - else - { - dropped = LaunchItem( item, ent->s.pos.trBase, velocity, NULL ); + if (copytarget) { + dropped = LaunchItem(item, ent->s.pos.trBase, velocity, ent->opentarget); + } else { + dropped = LaunchItem(item, ent->s.pos.trBase, velocity, NULL); } - dropped->activator = ent;//so we know who we belonged to so they can pick it back up later - dropped->s.time = level.time;//mark this time so we aren't picked up instantly by the guy who dropped us + dropped->activator = ent; // so we know who we belonged to so they can pick it back up later + dropped->s.time = level.time; // mark this time so we aren't picked up instantly by the guy who dropped us return dropped; } - /* ================ Use_Item @@ -1054,33 +885,27 @@ Use_Item Respawn the item ================ */ -void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - if ( (ent->svFlags&SVF_PLAYER_USABLE) && other && !other->s.number ) - {//used directly by the player, pick me up - if ( (ent->spawnflags&ITMSF_USEPICKUP) ) - {//player has to be touching me and hit use to pick it up, so don't allow this - if ( !G_BoundsOverlap( ent->absmin, ent->absmax, other->absmin, other->absmax ) ) - {//not touching +void Use_Item(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if ((ent->svFlags & SVF_PLAYER_USABLE) && other && !other->s.number) { // used directly by the player, pick me up + if ((ent->spawnflags & ITMSF_USEPICKUP)) { // player has to be touching me and hit use to pick it up, so don't allow this + if (!G_BoundsOverlap(ent->absmin, ent->absmax, other->absmin, other->absmax)) { // not touching return; } } - GEntity_TouchFunc( ent, other, NULL ); - } - else - {//use me - if ( ent->spawnflags & 32 ) // invisible + GEntity_TouchFunc(ent, other, NULL); + } else { // use me + if (ent->spawnflags & 32) // invisible { // If it was invisible, first use makes it visible.... ent->s.eFlags &= ~EF_NODRAW; - ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM; + ent->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; ent->spawnflags &= ~32; return; } - G_ActivateBehavior( ent, BSET_USE ); - RespawnItem( ent ); + G_ActivateBehavior(ent, BSET_USE); + RespawnItem(ent); } } @@ -1095,188 +920,158 @@ free fall from their spawn points ================ */ extern int delayedShutDown; -extern cvar_t *g_saber; -void FinishSpawningItem( gentity_t *ent ) { - trace_t tr; - vec3_t dest; - gitem_t *item; - int itemNum; - - itemNum=1; - for ( item = bg_itemlist + 1 ; item->classname ; item++,itemNum++) - { - if (!strcmp(item->classname,ent->classname)) - { +extern cvar_t *g_saber; +void FinishSpawningItem(gentity_t *ent) { + trace_t tr; + vec3_t dest; + gitem_t *item; + int itemNum; + + itemNum = 1; + for (item = bg_itemlist + 1; item->classname; item++, itemNum++) { + if (!strcmp(item->classname, ent->classname)) { break; } } // Set bounding box for item - VectorSet( ent->mins, item->mins[0],item->mins[1] ,item->mins[2]); - VectorSet( ent->maxs, item->maxs[0],item->maxs[1] ,item->maxs[2]); + VectorSet(ent->mins, item->mins[0], item->mins[1], item->mins[2]); + VectorSet(ent->maxs, item->maxs[0], item->maxs[1], item->maxs[2]); - if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) && - (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2])) - { - VectorSet (ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2);//to match the comments in the items.dat file! - VectorSet (ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); + if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) && (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2])) { + VectorSet(ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2); // to match the comments in the items.dat file! + VectorSet(ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); } - if ((item->quantity) && (item->giType == IT_AMMO)) - { + if ((item->quantity) && (item->giType == IT_AMMO)) { ent->count = item->quantity; } - if ((item->quantity) && (item->giType == IT_BATTERY)) - { + if ((item->quantity) && (item->giType == IT_BATTERY)) { ent->count = item->quantity; } ent->s.radius = 20; - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); - if ( ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER - && ent->NPC_type - && ent->NPC_type[0] ) - { + if (ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER && ent->NPC_type && ent->NPC_type[0]) { saberInfo_t itemSaber; - if ( Q_stricmp( "player", ent->NPC_type ) == 0 - && g_saber->string - && g_saber->string[0] - && Q_stricmp( "none", g_saber->string ) - && Q_stricmp( "NULL", g_saber->string ) ) - {//player's saber - WP_SaberParseParms( g_saber->string, &itemSaber ); - } - else - {//specific saber - WP_SaberParseParms( ent->NPC_type, &itemSaber ); + if (Q_stricmp("player", ent->NPC_type) == 0 && g_saber->string && g_saber->string[0] && Q_stricmp("none", g_saber->string) && + Q_stricmp("NULL", g_saber->string)) { // player's saber + WP_SaberParseParms(g_saber->string, &itemSaber); + } else { // specific saber + WP_SaberParseParms(ent->NPC_type, &itemSaber); } - //NOTE: should I keep this string around for any reason? Will I ever need it later? - //ent->??? = G_NewString( itemSaber.model ); - gi.G2API_InitGhoul2Model( ent->ghoul2, itemSaber.model, G_ModelIndex( itemSaber.model ), NULL_HANDLE, NULL_HANDLE, 0, 0); + // NOTE: should I keep this string around for any reason? Will I ever need it later? + // ent->??? = G_NewString( itemSaber.model ); + gi.G2API_InitGhoul2Model(ent->ghoul2, itemSaber.model, G_ModelIndex(itemSaber.model), NULL_HANDLE, NULL_HANDLE, 0, 0); WP_SaberFreeStrings(itemSaber); - } - else - { - gi.G2API_InitGhoul2Model( ent->ghoul2, ent->item->world_model, G_ModelIndex( ent->item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0); + } else { + gi.G2API_InitGhoul2Model(ent->ghoul2, ent->item->world_model, G_ModelIndex(ent->item->world_model), NULL_HANDLE, NULL_HANDLE, 0, 0); } // Set crystal ammo amount based on skill level -/* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) || - (itemNum == ITM_AMMO_CRYSTAL_DN) || - (itemNum == ITM_AMMO_CRYSTAL_FORGE) || - (itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) || - (itemNum == ITM_AMMO_CRYSTAL_STASIS)) - { - CrystalAmmoSettings(ent); - } -*/ + /* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) || + (itemNum == ITM_AMMO_CRYSTAL_DN) || + (itemNum == ITM_AMMO_CRYSTAL_FORGE) || + (itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) || + (itemNum == ITM_AMMO_CRYSTAL_STASIS)) + { + CrystalAmmoSettings(ent); + } + */ ent->s.eType = ET_ITEM; - ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex - ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item + ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex + ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item - ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_BODY;//CONTENTS_TRIGGER| + ent->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; // CONTENTS_BODY;//CONTENTS_TRIGGER| ent->e_TouchFunc = touchF_Touch_Item; // useing an item causes it to respawn ent->e_UseFunc = useF_Use_Item; - ent->svFlags |= SVF_PLAYER_USABLE;//so player can pick it up + ent->svFlags |= SVF_PLAYER_USABLE; // so player can pick it up // Hang in air? - ent->s.origin[2] += 1;//just to get it off the damn ground because coplanar = insolid - if ( (ent->spawnflags&ITMSF_SUSPEND) - || (ent->flags&FL_DROPPED_ITEM) ) - { + ent->s.origin[2] += 1; // just to get it off the damn ground because coplanar = insolid + if ((ent->spawnflags & ITMSF_SUSPEND) || (ent->flags & FL_DROPPED_ITEM)) { // suspended - G_SetOrigin( ent, ent->s.origin ); - } - else - { + G_SetOrigin(ent, ent->s.origin); + } else { // drop to floor - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD ); - gi.trace( &tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID|CONTENTS_PLAYERCLIP, (EG2_Collision)0, 0 ); - if ( tr.startsolid ) - { - if ( g_entities[tr.entityNum].inuse ) - { - gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), g_entities[tr.entityNum].classname ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD); + gi.trace(&tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID | CONTENTS_PLAYERCLIP, (EG2_Collision)0, 0); + if (tr.startsolid) { + if (g_entities[tr.entityNum].inuse) { + gi.Printf(S_COLOR_RED "FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), + g_entities[tr.entityNum].classname); + } else { + gi.Printf(S_COLOR_RED "FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin)); } - else - { - gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin) ); - } - assert( 0 && "item starting in solid"); - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + assert(0 && "item starting in solid"); + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region delayedShutDown = level.time + 100; } - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } // allow to ride movers ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); } -/* ? don't need this - // team slaves and targeted items aren't present at start - if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) { - ent->s.eFlags |= EF_NODRAW; - ent->contents = 0; - return; - } -*/ - if ( ent->spawnflags & ITMSF_INVISIBLE ) // invisible + /* ? don't need this + // team slaves and targeted items aren't present at start + if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) { + ent->s.eFlags |= EF_NODRAW; + ent->contents = 0; + return; + } + */ + if (ent->spawnflags & ITMSF_INVISIBLE) // invisible { ent->s.eFlags |= EF_NODRAW; ent->contents = 0; } - if ( ent->spawnflags & ITMSF_NOTSOLID ) // not solid + if (ent->spawnflags & ITMSF_NOTSOLID) // not solid { ent->contents = 0; } - if ( (ent->spawnflags&ITMSF_STATIONARY) ) - {//can't be pushed around + if ((ent->spawnflags & ITMSF_STATIONARY)) { // can't be pushed around ent->flags |= FL_NO_KNOCKBACK; } - if ( (ent->flags&FL_DROPPED_ITEM) ) - {//go away after 30 seconds + if ((ent->flags & FL_DROPPED_ITEM)) { // go away after 30 seconds ent->e_ThinkFunc = thinkF_G_FreeEntity; ent->nextthink = level.time + 30000; } - gi.linkentity (ent); + gi.linkentity(ent); } - -char itemRegistered[MAX_ITEMS+1]; - +char itemRegistered[MAX_ITEMS + 1]; /* ============== ClearRegisteredItems ============== */ -void ClearRegisteredItems( void ) { - for ( int i = 0; i < bg_numItems; i++ ) - { +void ClearRegisteredItems(void) { + for (int i = 0; i < bg_numItems; i++) { itemRegistered[i] = '0'; } - itemRegistered[ bg_numItems ] = 0; + itemRegistered[bg_numItems] = 0; - //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. - //RegisterItem( FindItemForWeapon( WP_NONE ) ); //has no item - RegisterItem( FindItemForInventory( INV_ELECTROBINOCULARS )); - //RegisterItem( FindItemForInventory( INV_BACTA_CANISTER )); - // saber or baton is cached in SP_info_player_deathmatch now. + // these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. + // RegisterItem( FindItemForWeapon( WP_NONE ) ); //has no item + RegisterItem(FindItemForInventory(INV_ELECTROBINOCULARS)); + // RegisterItem( FindItemForInventory( INV_BACTA_CANISTER )); + // saber or baton is cached in SP_info_player_deathmatch now. -extern void Player_CacheFromPrevLevel(void);//g_client.cpp - Player_CacheFromPrevLevel(); //reads from transition carry-over; + extern void Player_CacheFromPrevLevel(void); // g_client.cpp + Player_CacheFromPrevLevel(); // reads from transition carry-over; } /* @@ -1286,15 +1081,14 @@ RegisterItem The item will be added to the precache list =============== */ -void RegisterItem( gitem_t *item ) { - if ( !item ) { - G_Error( "RegisterItem: NULL" ); +void RegisterItem(gitem_t *item) { + if (!item) { + G_Error("RegisterItem: NULL"); } - itemRegistered[ item - bg_itemlist ] = '1'; - gi.SetConfigstring(CS_ITEMS, itemRegistered); //Write the needed items to a config string + itemRegistered[item - bg_itemlist] = '1'; + gi.SetConfigstring(CS_ITEMS, itemRegistered); // Write the needed items to a config string } - /* =============== SaveRegisteredItems @@ -1303,25 +1097,25 @@ Write the needed items to a config string so the client will know which ones to precache =============== */ -void SaveRegisteredItems( void ) { -/* char string[MAX_ITEMS+1]; - int i; - int count; - - count = 0; - for ( i = 0 ; i < bg_numItems ; i++ ) { - if ( itemRegistered[i] ) { - count++; - string[i] = '1'; - } else { - string[i] = '0'; +void SaveRegisteredItems(void) { + /* char string[MAX_ITEMS+1]; + int i; + int count; + + count = 0; + for ( i = 0 ; i < bg_numItems ; i++ ) { + if ( itemRegistered[i] ) { + count++; + string[i] = '1'; + } else { + string[i] = '0'; + } } - } - string[ bg_numItems ] = 0; + string[ bg_numItems ] = 0; - gi.Printf( "%i items registered\n", count ); - gi.SetConfigstring(CS_ITEMS, string); -*/ + gi.Printf( "%i items registered\n", count ); + gi.SetConfigstring(CS_ITEMS, string); + */ gi.SetConfigstring(CS_ITEMS, itemRegistered); } @@ -1332,7 +1126,7 @@ item_spawn_use if an item is given a targetname, it will be spawned in when used ============ */ -void item_spawn_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void item_spawn_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { self->nextthink = level.time + 50; @@ -1351,194 +1145,154 @@ Items can't be immediately dropped to floor, because they might be on an entity that hasn't spawned yet. ============ */ -void G_SpawnItem (gentity_t *ent, gitem_t *item) { - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnFloat( "wait", "0", &ent->wait ); +void G_SpawnItem(gentity_t *ent, gitem_t *item) { + G_SpawnFloat("random", "0", &ent->random); + G_SpawnFloat("wait", "0", &ent->wait); - RegisterItem( item ); + RegisterItem(item); ent->item = item; // targetname indicates they want to spawn it later - if( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_item_spawn_use; - } - else - { // some movers spawn on the second frame, so delay item + } else { // some movers spawn on the second frame, so delay item // spawns until the third frame so they can ride trains ent->nextthink = level.time + START_TIME_MOVERS_SPAWNED + 50; ent->e_ThinkFunc = thinkF_FinishSpawningItem; } - ent->physicsBounce = 0.50; // items are bouncy + ent->physicsBounce = 0.50; // items are bouncy // Set a default infoString text color // NOTE: if we want to do cool cross-hair colors for items, we can just modify this, but for now, don't do it - VectorSet( ent->startRGBA, 1.0f, 1.0f, 1.0f ); + VectorSet(ent->startRGBA, 1.0f, 1.0f, 1.0f); - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = (team_t)GetIDForString( TeamTable, ent->team ); - if ( ent->noDamageTeam == TEAM_FREE ) - { + if (ent->team && ent->team[0]) { + ent->noDamageTeam = (team_t)GetIDForString(TeamTable, ent->team); + if (ent->noDamageTeam == TEAM_FREE) { G_Error("team name %s not recognized\n", ent->team); } } - if ( ent->item - && ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER ) - {//weapon_saber item - if ( !ent->count ) - {//can only pick up once + if (ent->item && ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER) { // weapon_saber item + if (!ent->count) { // can only pick up once ent->count = 1; } } ent->team = NULL; } - /* ================ G_BounceItem ================ */ -void G_BounceItem( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceItem(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; qboolean droppedSaber = qtrue; - if ( ent->item - && ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER - && (ent->flags&FL_DROPPED_ITEM) ) - { + if (ent->item && ent->item->giType == IT_WEAPON && ent->item->giTag == WP_SABER && (ent->flags & FL_DROPPED_ITEM)) { droppedSaber = qtrue; } // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); // cut the velocity to keep from bouncing forever - VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta ); + VectorScale(ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta); - if ( droppedSaber ) - {//a dropped saber item - //FIXME: use NPC_type (as saberType) to get proper bounce sound? - WP_SaberFallSound( NULL, ent ); + if (droppedSaber) { // a dropped saber item + // FIXME: use NPC_type (as saberType) to get proper bounce sound? + WP_SaberFallSound(NULL, ent); } // check for stop - if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) - {//stop - G_SetOrigin( ent, trace->endpos ); + if (trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40) { // stop + G_SetOrigin(ent, trace->endpos); ent->s.groundEntityNum = trace->entityNum; - if ( droppedSaber ) - {//a dropped saber item - //stop rotation - VectorClear( ent->s.apos.trDelta ); + if (droppedSaber) { // a dropped saber item + // stop rotation + VectorClear(ent->s.apos.trDelta); ent->currentAngles[PITCH] = SABER_PITCH_HACK; ent->currentAngles[ROLL] = 0; - if ( ent->NPC_type - && ent->NPC_type[0] ) - {//we have a valid saber for this + if (ent->NPC_type && ent->NPC_type[0]) { // we have a valid saber for this saberInfo_t saber; - if ( WP_SaberParseParms( ent->NPC_type, &saber ) ) - { - if ( (saber.saberFlags&SFL_BOLT_TO_WRIST) ) - { + if (WP_SaberParseParms(ent->NPC_type, &saber)) { + if ((saber.saberFlags & SFL_BOLT_TO_WRIST)) { ent->currentAngles[PITCH] = 0; } } } - pitch_roll_for_slope( ent, trace->plane.normal, ent->currentAngles, qtrue ); - G_SetAngles( ent, ent->currentAngles ); + pitch_roll_for_slope(ent, trace->plane.normal, ent->currentAngles, qtrue); + G_SetAngles(ent, ent->currentAngles); } return; } - //bounce - if ( droppedSaber ) - {//a dropped saber item - //change rotation - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + // bounce + if (droppedSaber) { // a dropped saber item + // change rotation + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; ent->s.apos.trTime = level.time; - VectorSet( ent->s.apos.trDelta, Q_irand( -300, 300 ), Q_irand( -300, 300 ), Q_irand( -300, 300 ) ); + VectorSet(ent->s.apos.trDelta, Q_irand(-300, 300), Q_irand(-300, 300), Q_irand(-300, 300)); } - VectorAdd( ent->currentOrigin, trace->plane.normal, ent->currentOrigin); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorAdd(ent->currentOrigin, trace->plane.normal, ent->currentOrigin); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } - /* ================ G_RunItem ================ */ -void G_RunItem( gentity_t *ent ) { - vec3_t origin; - trace_t tr; - int contents; - int mask; +void G_RunItem(gentity_t *ent) { + vec3_t origin; + trace_t tr; + int contents; + int mask; // if groundentity has been set to -1, it may have been pushed off an edge - if ( ent->s.groundEntityNum == ENTITYNUM_NONE ) - { - if ( ent->s.pos.trType != TR_GRAVITY ) - { + if (ent->s.groundEntityNum == ENTITYNUM_NONE) { + if (ent->s.pos.trType != TR_GRAVITY) { ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; } } - if ( ent->s.pos.trType == TR_STATIONARY ) - { + if (ent->s.pos.trType == TR_STATIONARY) { // check think function - G_RunThink( ent ); - if ( !g_gravity->value ) - { + G_RunThink(ent); + if (!g_gravity->value) { ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; ent->s.pos.trDelta[0] += Q_flrand(-1.0f, 1.0f) * 40.0f; // I dunno, just do this?? ent->s.pos.trDelta[1] += Q_flrand(-1.0f, 1.0f) * 40.0f; ent->s.pos.trDelta[2] += Q_flrand(0.0f, 1.0f) * 20.0f; - } - else if ( (ent->flags&FL_DROPPED_ITEM) - && ent->item - && ent->item->giType == IT_WEAPON - && ent->item->giTag == WP_SABER ) - {//a dropped saber item, check below, just in case + } else if ((ent->flags & FL_DROPPED_ITEM) && ent->item && ent->item->giType == IT_WEAPON && + ent->item->giTag == WP_SABER) { // a dropped saber item, check below, just in case int ignore = ENTITYNUM_NONE; - if ( ent->clipmask ) - { + if (ent->clipmask) { mask = ent->clipmask; + } else { + mask = MASK_SOLID | CONTENTS_PLAYERCLIP; // shouldn't be able to get anywhere player can't } - else - { - mask = MASK_SOLID|CONTENTS_PLAYERCLIP;//shouldn't be able to get anywhere player can't - } - if ( ent->owner ) - { + if (ent->owner) { ignore = ent->owner->s.number; - } - else if ( ent->activator ) - { + } else if (ent->activator) { ignore = ent->activator->s.number; } - VectorSet( origin, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2]-1 ); - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, (EG2_Collision)0, 0 ); - if ( !tr.allsolid - && !tr.startsolid - && tr.fraction > 0.001f ) - {//wha? fall.... + VectorSet(origin, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] - 1); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, (EG2_Collision)0, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction > 0.001f) { // wha? fall.... ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; } @@ -1547,63 +1301,51 @@ void G_RunItem( gentity_t *ent ) { } // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); - if ( ent->s.apos.trType != TR_STATIONARY ) - { - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); - G_SetAngles( ent, ent->currentAngles ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); + if (ent->s.apos.trType != TR_STATIONARY) { + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); + G_SetAngles(ent, ent->currentAngles); } // trace a line from the previous position to the current position - if ( ent->clipmask ) - { + if (ent->clipmask) { mask = ent->clipmask; - } - else - { - mask = MASK_SOLID|CONTENTS_PLAYERCLIP;//shouldn't be able to get anywhere player can't + } else { + mask = MASK_SOLID | CONTENTS_PLAYERCLIP; // shouldn't be able to get anywhere player can't } int ignore = ENTITYNUM_NONE; - if ( ent->owner ) - { + if (ent->owner) { ignore = ent->owner->s.number; - } - else if ( ent->activator ) - { + } else if (ent->activator) { ignore = ent->activator->s.number; } - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, (EG2_Collision)0, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, (EG2_Collision)0, 0); - VectorCopy( tr.endpos, ent->currentOrigin ); + VectorCopy(tr.endpos, ent->currentOrigin); - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( ent ); // FIXME: avoid this for stationary? + gi.linkentity(ent); // FIXME: avoid this for stationary? // check think function - G_RunThink( ent ); + G_RunThink(ent); - if ( tr.fraction == 1 ) - { - if ( g_gravity->value <= 0 ) - { - if ( ent->s.apos.trType != TR_LINEAR ) - { - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + if (tr.fraction == 1) { + if (g_gravity->value <= 0) { + if (ent->s.apos.trType != TR_LINEAR) { + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; - ent->s.apos.trDelta[1] = Q_flrand( -300, 300 ); - ent->s.apos.trDelta[0] = Q_flrand( -10, 10 ); - ent->s.apos.trDelta[2] = Q_flrand( -10, 10 ); + ent->s.apos.trDelta[1] = Q_flrand(-300, 300); + ent->s.apos.trDelta[0] = Q_flrand(-10, 10); + ent->s.apos.trDelta[2] = Q_flrand(-10, 10); ent->s.apos.trTime = level.time; } } - //friction in zero-G - if ( !g_gravity->value ) - { + // friction in zero-G + if (!g_gravity->value) { float friction = 0.975f; /*friction -= ent->mass/1000.0f; if ( friction < 0.1 ) @@ -1611,24 +1353,22 @@ void G_RunItem( gentity_t *ent ) { friction = 0.1f; } */ - VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(ent->s.pos.trDelta, friction, ent->s.pos.trDelta); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } return; } // if it is in a nodrop volume, remove it - contents = gi.pointcontents( ent->currentOrigin, -1 ); - if ( contents & CONTENTS_NODROP ) - { - G_FreeEntity( ent ); + contents = gi.pointcontents(ent->currentOrigin, -1); + if (contents & CONTENTS_NODROP) { + G_FreeEntity(ent); return; } - if ( !tr.startsolid ) - { - G_BounceItem( ent, &tr ); + if (!tr.startsolid) { + G_BounceItem(ent, &tr); } } @@ -1638,27 +1378,22 @@ ItemUse_Bacta ================ */ -void ItemUse_Bacta(gentity_t *ent) -{ - if (!ent || !ent->client) - { +void ItemUse_Bacta(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER] ) - { + if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER]) { return; } ent->health += MAX_BACTA_HEAL_AMOUNT; - if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } ent->client->ps.inventory[INV_BACTA_CANISTER]--; - G_SoundOnEnt( ent, CHAN_VOICE, va( "sound/weapons/force/heal%d_%c.mp3", Q_irand( 1, 4 ), g_sex->string[0] ) ); + G_SoundOnEnt(ent, CHAN_VOICE, va("sound/weapons/force/heal%d_%c.mp3", Q_irand(1, 4), g_sex->string[0])); } - diff --git a/code/game/g_main.cpp b/code/game/g_main.cpp index dceac508eb..a4a269dbc3 100644 --- a/code/game/g_main.cpp +++ b/code/game/g_main.cpp @@ -30,71 +30,63 @@ along with this program; if not, see . #include "b_local.h" #include "anims.h" #include "objectives.h" -#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... +#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #include "../ghoul2/ghoul2_gore.h" -//rww - RAGDOLL_END +// rww - RAGDOLL_END #include "qcommon/ojk_saved_game_helper.h" #include "qcommon/q_version.h" -extern void WP_SaberLoadParms( void ); -extern qboolean G_PlayerSpawned( void ); +extern void WP_SaberLoadParms(void); +extern qboolean G_PlayerSpawned(void); -extern void Rail_Initialize( void ); -extern void Rail_Update( void ); -extern void Rail_Reset(void); +extern void Rail_Initialize(void); +extern void Rail_Update(void); +extern void Rail_Reset(void); -extern void Troop_Initialize( void ); -extern void Troop_Update( void ); -extern void Troop_Reset(void); +extern void Troop_Initialize(void); +extern void Troop_Update(void); +extern void Troop_Reset(void); -extern void Pilot_Reset(void); -extern void Pilot_Update(void); +extern void Pilot_Reset(void); +extern void Pilot_Update(void); extern void G_ASPreCacheFree(void); - -int eventClearTime = 0; +int eventClearTime = 0; extern qboolean g_bCollidableRoffs; +#define STEPSIZE 18 -#define STEPSIZE 18 +level_locals_t level; +game_import_t gi; +game_export_t globals; +gentity_t g_entities[MAX_GENTITIES]; +unsigned int g_entityInUseBits[MAX_GENTITIES / 32]; -level_locals_t level; -game_import_t gi; -game_export_t globals; -gentity_t g_entities[MAX_GENTITIES]; -unsigned int g_entityInUseBits[MAX_GENTITIES/32]; +static void ClearAllInUse(void) { memset(g_entityInUseBits, 0, sizeof(g_entityInUseBits)); } -static void ClearAllInUse(void) -{ - memset(g_entityInUseBits,0,sizeof(g_entityInUseBits)); +void SetInUse(gentity_t *ent) { + assert(((uintptr_t)ent) >= (uintptr_t)g_entities); + assert(((uintptr_t)ent) <= (uintptr_t)(g_entities + MAX_GENTITIES - 1)); + unsigned int entNum = ent - g_entities; + g_entityInUseBits[entNum / 32] |= ((unsigned int)1) << (entNum & 0x1f); } -void SetInUse(gentity_t *ent) -{ - assert(((uintptr_t)ent)>=(uintptr_t)g_entities); - assert(((uintptr_t)ent)<=(uintptr_t)(g_entities+MAX_GENTITIES-1)); - unsigned int entNum=ent-g_entities; - g_entityInUseBits[entNum/32]|=((unsigned int)1)<<(entNum&0x1f); -} - -void ClearInUse(gentity_t *ent) -{ - assert(((uintptr_t)ent)>=(uintptr_t)g_entities); - assert(((uintptr_t)ent)<=(uintptr_t)(g_entities+MAX_GENTITIES-1)); - unsigned int entNum=ent-g_entities; - g_entityInUseBits[entNum/32]&=~(((unsigned int)1)<<(entNum&0x1f)); +void ClearInUse(gentity_t *ent) { + assert(((uintptr_t)ent) >= (uintptr_t)g_entities); + assert(((uintptr_t)ent) <= (uintptr_t)(g_entities + MAX_GENTITIES - 1)); + unsigned int entNum = ent - g_entities; + g_entityInUseBits[entNum / 32] &= ~(((unsigned int)1) << (entNum & 0x1f)); } -qboolean PInUse(unsigned int entNum) -{ - assert(entNum>=0); - assert(entNum= 0); + assert(entNum < MAX_GENTITIES); + return (qboolean)((g_entityInUseBits[entNum / 32] & (((unsigned int)1) << (entNum & 0x1f))) != 0); } /*qboolean PInUse2(gentity_t *ent) @@ -106,139 +98,128 @@ qboolean PInUse(unsigned int entNum) } */ -void WriteInUseBits() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void WriteInUseBits() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('I', 'N', 'U', 'S'), - ::g_entityInUseBits); + saved_game.write_chunk(INT_ID('I', 'N', 'U', 'S'), ::g_entityInUseBits); } -void ReadInUseBits() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void ReadInUseBits() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('I', 'N', 'U', 'S'), - ::g_entityInUseBits); + saved_game.read_chunk(INT_ID('I', 'N', 'U', 'S'), ::g_entityInUseBits); // This is only temporary. Once I have converted all the ent->inuse refs, // it won;t be needed -MW. - for(int i=0;ihealth <= 0 && player->max_health > 0 ) - {//defeat music - if ( level.dmState != DM_DEATH ) - { + if (player->health <= 0 && player->max_health > 0) { // defeat music + if (level.dmState != DM_DEATH) { level.dmState = DM_DEATH; } } - if ( level.dmState == DM_DEATH ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "death" ); + if (level.dmState == DM_DEATH) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "death"); return; } - if ( level.dmState == DM_BOSS ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "boss" ); + if (level.dmState == DM_BOSS) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "boss"); return; } - if ( level.dmState == DM_SILENCE ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "silence" ); + if (level.dmState == DM_SILENCE) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "silence"); return; } - if ( level.dmBeatTime > level.time ) - {//not on a beat + if (level.dmBeatTime > level.time) { // not on a beat return; } - level.dmBeatTime = level.time + 1000;//1 second beats + level.dmBeatTime = level.time + 1000; // 1 second beats - if ( player->health <= 20 ) - { + if (player->health <= 20) { danger = 1; } - //enemy-based - VectorCopy( player->currentOrigin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + // enemy-based + VectorCopy(player->currentOrigin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; - if ( !ent || !ent->inuse ) - { + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; + if (!ent || !ent->inuse) { continue; } - if ( !ent->client || !ent->NPC ) - { - if ( ent->classname && (!Q_stricmp( "PAS", ent->classname )||!Q_stricmp( "misc_turret", ent->classname )) ) - {//a turret + if (!ent->client || !ent->NPC) { + if (ent->classname && (!Q_stricmp("PAS", ent->classname) || !Q_stricmp("misc_turret", ent->classname))) { // a turret entTeam = ent->noDamageTeam; - } - else - { + } else { continue; } - } - else - {//an NPC + } else { // an NPC entTeam = ent->client->playerTeam; } - if ( entTeam == player->client->playerTeam ) - {//ally + if (entTeam == player->client->playerTeam) { // ally continue; } - if ( entTeam == TEAM_NEUTRAL && (!ent->enemy || !ent->enemy->client || ent->enemy->client->playerTeam != player->client->playerTeam) ) - {//a droid that is not mad at me or my allies + if (entTeam == TEAM_NEUTRAL && (!ent->enemy || !ent->enemy->client || + ent->enemy->client->playerTeam != player->client->playerTeam)) { // a droid that is not mad at me or my allies continue; } - if ( !gi.inPVS( player->currentOrigin, ent->currentOrigin ) ) - {//not potentially visible + if (!gi.inPVS(player->currentOrigin, ent->currentOrigin)) { // not potentially visible continue; } - if ( ent->client && ent->s.weapon == WP_NONE ) - {//they don't have a weapon... FIXME: only do this for droids? + if (ent->client && ent->s.weapon == WP_NONE) { // they don't have a weapon... FIXME: only do this for droids? continue; } LOScalced = clearLOS = qfalse; - if ( (ent->enemy==player&&(!ent->NPC||ent->NPC->confusionTimeclient&&ent->client->ps.weaponTime) || (!ent->client&&ent->attackDebounceTime>level.time)) - {//mad - if ( ent->health > 0 ) - {//alive - //FIXME: do I really need this check? - if ( ent->s.weapon == WP_SABER && ent->client && !ent->client->ps.SaberActive() && ent->enemy != player ) - {//a Jedi who has not yet gotten made at me + if ((ent->enemy == player && (!ent->NPC || ent->NPC->confusionTime < level.time)) || (ent->client && ent->client->ps.weaponTime) || + (!ent->client && ent->attackDebounceTime > level.time)) { // mad + if (ent->health > 0) { // alive + // FIXME: do I really need this check? + if (ent->s.weapon == WP_SABER && ent->client && !ent->client->ps.SaberActive() && + ent->enemy != player) { // a Jedi who has not yet gotten made at me continue; } - if ( ent->NPC && ent->NPC->behaviorState == BS_CINEMATIC ) - {//they're not actually going to do anything about being mad at me... + if (ent->NPC && ent->NPC->behaviorState == BS_CINEMATIC) { // they're not actually going to do anything about being mad at me... continue; } - //okay, they're in my PVS, but how close are they? Are they actively attacking me? - if ( !ent->client && ent->s.weapon == WP_TURRET && ent->fly_sound_debounce_time && ent->fly_sound_debounce_time - level.time < 10000 ) - {//a turret that shot at me less than ten seconds ago - } - else if ( ent->client && ent->client->ps.lastShotTime && ent->client->ps.lastShotTime - level.time < 10000 ) - {//an NPC that shot at me less than ten seconds ago - } - else - {//not actively attacking me lately, see how far away they are - distSq = DistanceSquared( ent->currentOrigin, player->currentOrigin ); - if ( distSq > 4194304/*2048*2048*/ ) - {//> 2048 away + // okay, they're in my PVS, but how close are they? Are they actively attacking me? + if (!ent->client && ent->s.weapon == WP_TURRET && ent->fly_sound_debounce_time && + ent->fly_sound_debounce_time - level.time < 10000) { // a turret that shot at me less than ten seconds ago + } else if (ent->client && ent->client->ps.lastShotTime && + ent->client->ps.lastShotTime - level.time < 10000) { // an NPC that shot at me less than ten seconds ago + } else { // not actively attacking me lately, see how far away they are + distSq = DistanceSquared(ent->currentOrigin, player->currentOrigin); + if (distSq > 4194304 /*2048*2048*/) { //> 2048 away continue; - } - else if ( distSq > 1048576/*1024*1024*/ ) - {//> 1024 away - clearLOS = G_ClearLOS( player, player->client->renderInfo.eyePoint, ent ); + } else if (distSq > 1048576 /*1024*1024*/) { //> 1024 away + clearLOS = G_ClearLOS(player, player->client->renderInfo.eyePoint, ent); LOScalced = qtrue; - if ( clearLOS == qfalse ) - {//No LOS + if (clearLOS == qfalse) { // No LOS continue; } } @@ -411,57 +361,48 @@ static void G_DynamicMusicUpdate( void ) } } - if ( level.dmState == DM_EXPLORE ) - {//only do these visibility checks if you're still in exploration mode - if ( !InFront( ent->currentOrigin, player->currentOrigin, player->client->ps.viewangles, 0.0f) ) - {//not in front + if (level.dmState == DM_EXPLORE) { // only do these visibility checks if you're still in exploration mode + if (!InFront(ent->currentOrigin, player->currentOrigin, player->client->ps.viewangles, 0.0f)) { // not in front continue; } - if ( !LOScalced ) - { - clearLOS = G_ClearLOS( player, player->client->renderInfo.eyePoint, ent ); + if (!LOScalced) { + clearLOS = G_ClearLOS(player, player->client->renderInfo.eyePoint, ent); } - if ( !clearLOS ) - {//can't see them directly + if (!clearLOS) { // can't see them directly continue; } } - if ( ent->health <= 0 ) - {//dead - if ( !ent->client || level.time - ent->s.time > 10000 ) - {//corpse has been dead for more than 10 seconds - //FIXME: coming across corpses should cause danger sounds too? + if (ent->health <= 0) { // dead + if (!ent->client || level.time - ent->s.time > 10000) { // corpse has been dead for more than 10 seconds + // FIXME: coming across corpses should cause danger sounds too? continue; } } - //we see enemies and/or corpses + // we see enemies and/or corpses danger++; } - if ( !battle ) - {//no active enemies, but look for missiles, shot impacts, etc... - int alert = G_CheckAlertEvents( player, qtrue, qtrue, 1024, 1024, -1, qfalse, AEL_SUSPICIOUS ); - if ( alert != -1 ) - {//FIXME: maybe tripwires and other FIXED things need their own sound, some kind of danger/caution theme - if ( G_CheckForDanger( player, alert ) ) - {//found danger near by + if (!battle) { // no active enemies, but look for missiles, shot impacts, etc... + int alert = G_CheckAlertEvents(player, qtrue, qtrue, 1024, 1024, -1, qfalse, AEL_SUSPICIOUS); + if (alert != -1) { // FIXME: maybe tripwires and other FIXED things need their own sound, some kind of danger/caution theme + if (G_CheckForDanger(player, alert)) { // found danger near by danger++; battle = 1; - } - else if ( level.alertEvents[alert].owner && (level.alertEvents[alert].owner == player->enemy || (level.alertEvents[alert].owner->client && level.alertEvents[alert].owner->client->playerTeam == player->client->enemyTeam) ) ) - {//NPC on enemy team of player made some noise - switch ( level.alertEvents[alert].level ) - { + } else if (level.alertEvents[alert].owner && + (level.alertEvents[alert].owner == player->enemy || + (level.alertEvents[alert].owner->client && + level.alertEvents[alert].owner->client->playerTeam == player->client->enemyTeam))) { // NPC on enemy team of player made some noise + switch (level.alertEvents[alert].level) { case AEL_DISCOVERED: - //dangerNear = qtrue; + // dangerNear = qtrue; break; case AEL_SUSPICIOUS: - //suspicious = qtrue; + // suspicious = qtrue; break; case AEL_MINOR: - //distraction = qtrue; + // distraction = qtrue; break; default: break; @@ -470,32 +411,22 @@ static void G_DynamicMusicUpdate( void ) } } - if ( battle ) - {//battle - this can interrupt level.dmDebounceTime of lower intensity levels - //play battle - if ( level.dmState != DM_ACTION ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "action" ); + if (battle) { // battle - this can interrupt level.dmDebounceTime of lower intensity levels + // play battle + if (level.dmState != DM_ACTION) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "action"); } level.dmState = DM_ACTION; - if ( battle > 5 ) - { - //level.dmDebounceTime = level.time + 8000;//don't change again for 5 seconds - } - else - { - //level.dmDebounceTime = level.time + 3000 + 1000*battle; + if (battle > 5) { + // level.dmDebounceTime = level.time + 8000;//don't change again for 5 seconds + } else { + // level.dmDebounceTime = level.time + 3000 + 1000*battle; } - } - else - { - if ( level.dmDebounceTime > level.time ) - {//not ready to switch yet + } else { + if (level.dmDebounceTime > level.time) { // not ready to switch yet return; - } - else - {//at least 1 second (for beats) - //level.dmDebounceTime = level.time + 1000;//FIXME: define beat time? + } else { // at least 1 second (for beats) + // level.dmDebounceTime = level.time + 1000;//FIXME: define beat time? } /* if ( danger || dangerNear ) @@ -516,23 +447,21 @@ static void G_DynamicMusicUpdate( void ) } else */ - {//still nothing dangerous going on - if ( level.dmState != DM_EXPLORE ) - {//just went to explore, hold it for a couple seconds at least - //level.dmDebounceTime = level.time + 2000; - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "explore" ); + { // still nothing dangerous going on + if (level.dmState != DM_EXPLORE) { // just went to explore, hold it for a couple seconds at least + // level.dmDebounceTime = level.time + 2000; + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "explore"); } level.dmState = DM_EXPLORE; - //FIXME: look for interest points and play "mysterious" music instead of exploration? - //FIXME: suspicious and distraction sounds should play some cue or change music in a subtle way? - //play exploration + // FIXME: look for interest points and play "mysterious" music instead of exploration? + // FIXME: suspicious and distraction sounds should play some cue or change music in a subtle way? + // play exploration } - //FIXME: when do we go to silence? + // FIXME: when do we go to silence? } } -void G_ConnectNavs( const char *mapname, int checkSum ) -{ +void G_ConnectNavs(const char *mapname, int checkSum) { NAV::LoadFromEntitiesAndSaveToFile(mapname, checkSum); CP_FindCombatPointWaypoints(); } @@ -548,21 +477,20 @@ All but the first will have the FL_TEAMSLAVE flag set and teammaster field set All but the last will have the teamchain field set to the next one ================ */ -void G_FindTeams( void ) { - gentity_t *e, *e2; - int i, j; - int c, c2; +void G_FindTeams(void) { + gentity_t *e, *e2; + int i, j; + int c, c2; c = 0; c2 = 0; -// for ( i=1, e=g_entities,i ; i < globals.num_entities ; i++,e++ ) - for ( i=MAX_CLIENTS ; i < globals.num_entities ; i++ ) - { -// if (!e->inuse) -// continue; - if(!PInUse(i)) + // for ( i=1, e=g_entities,i ; i < globals.num_entities ; i++,e++ ) + for (i = MAX_CLIENTS; i < globals.num_entities; i++) { + // if (!e->inuse) + // continue; + if (!PInUse(i)) continue; - e=&g_entities[i]; + e = &g_entities[i]; if (!e->team) continue; @@ -571,21 +499,19 @@ void G_FindTeams( void ) { e->teammaster = e; c++; c2++; -// for (j=i+1, e2=e+1 ; j < globals.num_entities ; j++,e2++) - for (j=i+1; j < globals.num_entities ; j++) - { -// if (!e2->inuse) -// continue; - if(!PInUse(j)) + // for (j=i+1, e2=e+1 ; j < globals.num_entities ; j++,e2++) + for (j = i + 1; j < globals.num_entities; j++) { + // if (!e2->inuse) + // continue; + if (!PInUse(j)) continue; - e2=&g_entities[j]; + e2 = &g_entities[j]; if (!e2->team) continue; if (e2->flags & FL_TEAMSLAVE) continue; - if (!strcmp(e->team, e2->team)) - { + if (!strcmp(e->team, e2->team)) { c2++; e2->teamchain = e->teamchain; e->teamchain = e2; @@ -593,7 +519,7 @@ void G_FindTeams( void ) { e2->flags |= FL_TEAMSLAVE; // make sure that targets only point at the master - if ( e2->targetname ) { + if (e2->targetname) { e->targetname = G_NewString(e2->targetname); e2->targetname = NULL; } @@ -601,113 +527,111 @@ void G_FindTeams( void ) { } } - //gi.Printf ("%i teams with %i entities\n", c, c2); + // gi.Printf ("%i teams with %i entities\n", c, c2); } - /* ============ G_InitCvars ============ */ -void G_InitCvars( void ) { +void G_InitCvars(void) { // don't override the cheat state set by the system - g_cheats = gi.cvar ("helpUsObi", "", 0); - g_developer = gi.cvar ("developer", "", 0); + g_cheats = gi.cvar("helpUsObi", "", 0); + g_developer = gi.cvar("developer", "", 0); // noset vars - gi.cvar( "gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_ROM ); - gi.cvar( "gamedate", SOURCE_DATE , CVAR_ROM ); - g_skippingcin = gi.cvar ("skippingCinematic", "0", CVAR_ROM); + gi.cvar("gamename", GAMEVERSION, CVAR_SERVERINFO | CVAR_ROM); + gi.cvar("gamedate", SOURCE_DATE, CVAR_ROM); + g_skippingcin = gi.cvar("skippingCinematic", "0", CVAR_ROM); // latched vars // change anytime vars - g_speed = gi.cvar( "g_speed", "250", CVAR_CHEAT ); - g_gravity = gi.cvar( "g_gravity", "800", CVAR_SAVEGAME|CVAR_ROM ); - g_stepSlideFix = gi.cvar( "g_stepSlideFix", "1", CVAR_ARCHIVE ); - g_sex = gi.cvar ("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_spskill = gi.cvar ("g_spskill", "0", CVAR_ARCHIVE | CVAR_SAVEGAME|CVAR_NORESTART); - g_knockback = gi.cvar( "g_knockback", "1000", CVAR_CHEAT ); - g_dismemberment = gi.cvar ( "g_dismemberment", "3", CVAR_ARCHIVE );//0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head + g_speed = gi.cvar("g_speed", "250", CVAR_CHEAT); + g_gravity = gi.cvar("g_gravity", "800", CVAR_SAVEGAME | CVAR_ROM); + g_stepSlideFix = gi.cvar("g_stepSlideFix", "1", CVAR_ARCHIVE); + g_sex = gi.cvar("sex", "f", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_spskill = gi.cvar("g_spskill", "0", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_knockback = gi.cvar("g_knockback", "1000", CVAR_CHEAT); + g_dismemberment = gi.cvar("g_dismemberment", "3", CVAR_ARCHIVE); // 0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head // for now I'm making default 10 seconds - g_corpseRemovalTime = gi.cvar ( "g_corpseRemovalTime", "10", CVAR_ARCHIVE );//number of seconds bodies stick around for, at least... 0 = never go away - g_synchSplitAnims = gi.cvar ( "g_synchSplitAnims", "1", 0 ); + g_corpseRemovalTime = gi.cvar("g_corpseRemovalTime", "10", CVAR_ARCHIVE); // number of seconds bodies stick around for, at least... 0 = never go away + g_synchSplitAnims = gi.cvar("g_synchSplitAnims", "1", 0); #ifndef FINAL_BUILD - g_AnimWarning = gi.cvar ( "g_AnimWarning", "1", 0 ); + g_AnimWarning = gi.cvar("g_AnimWarning", "1", 0); #endif - g_noFootSlide = gi.cvar ( "g_noFootSlide", "1", 0 ); - g_noFootSlideRunScale = gi.cvar ( "g_noFootSlideRunScale", "150.0", 0 ); - g_noFootSlideWalkScale = gi.cvar ( "g_noFootSlideWalkScale", "50.0", 0 ); + g_noFootSlide = gi.cvar("g_noFootSlide", "1", 0); + g_noFootSlideRunScale = gi.cvar("g_noFootSlideRunScale", "150.0", 0); + g_noFootSlideWalkScale = gi.cvar("g_noFootSlideWalkScale", "50.0", 0); - g_nav1 = gi.cvar ( "g_nav1", "", 0 ); - g_nav2 = gi.cvar ( "g_nav2", "", 0 ); + g_nav1 = gi.cvar("g_nav1", "", 0); + g_nav2 = gi.cvar("g_nav2", "", 0); - g_bobaDebug = gi.cvar ( "g_bobaDebug", "", 0 ); + g_bobaDebug = gi.cvar("g_bobaDebug", "", 0); - g_delayedShutdown = gi.cvar ( "g_delayedShutdown", "0", 0 ); + g_delayedShutdown = gi.cvar("g_delayedShutdown", "0", 0); - g_inactivity = gi.cvar ("g_inactivity", "0", 0); - g_debugMove = gi.cvar ("g_debugMove", "0", CVAR_CHEAT ); - g_debugDamage = gi.cvar ("g_debugDamage", "0", CVAR_CHEAT ); - g_ICARUSDebug = gi.cvar( "g_ICARUSDebug", "0", CVAR_CHEAT ); - g_timescale = gi.cvar( "timescale", "1", 0 ); - g_npcdebug = gi.cvar( "g_npcdebug", "0", 0 ); - g_navSafetyChecks = gi.cvar( "g_navSafetyChecks", "0", 0 ); + g_inactivity = gi.cvar("g_inactivity", "0", 0); + g_debugMove = gi.cvar("g_debugMove", "0", CVAR_CHEAT); + g_debugDamage = gi.cvar("g_debugDamage", "0", CVAR_CHEAT); + g_ICARUSDebug = gi.cvar("g_ICARUSDebug", "0", CVAR_CHEAT); + g_timescale = gi.cvar("timescale", "1", 0); + g_npcdebug = gi.cvar("g_npcdebug", "0", 0); + g_navSafetyChecks = gi.cvar("g_navSafetyChecks", "0", 0); // NOTE : I also create this is UI_Init() - g_subtitles = gi.cvar( "g_subtitles", "0", CVAR_ARCHIVE ); - com_buildScript = gi.cvar ("com_buildscript", "0", 0); - - g_saberAutoBlocking = gi.cvar( "g_saberAutoBlocking", "1", CVAR_CHEAT );//must press +block button to do any blocking - g_saberRealisticCombat = gi.cvar( "g_saberMoreRealistic", "0", CVAR_ARCHIVE );//makes collision more precise, increases damage - debug_subdivision = gi.cvar( "debug_subdivision", "0", CVAR_ARCHIVE );//debug for dismemberment - g_dismemberProbabilities = gi.cvar ( "g_dismemberProbabilities", "1", CVAR_ARCHIVE );//0 = ignore probabilities, 1 = use probabilities - g_saberDamageCapping = gi.cvar( "g_saberDamageCapping", "1", CVAR_CHEAT );//caps damage of sabers vs players and NPC who use sabers - g_saberMoveSpeed = gi.cvar( "g_saberMoveSpeed", "1", CVAR_CHEAT );//how fast you run while attacking with a saber - g_saberAnimSpeed = gi.cvar( "g_saberAnimSpeed", "1", CVAR_CHEAT );//how fast saber animations run - g_saberAutoAim = gi.cvar( "g_saberAutoAim", "1", CVAR_CHEAT );//auto-aims at enemies when not moving or when just running forward - g_saberNewControlScheme = gi.cvar( "g_saberNewControlScheme", "0", CVAR_ARCHIVE );//use +forcefocus to pull off all the special moves - g_debugSaberLock = gi.cvar( "g_debugSaberLock", "0", CVAR_CHEAT );//just for debugging/development, makes saberlocks happen all the time - g_saberLockRandomNess = gi.cvar( "g_saberLockRandomNess", "2", CVAR_ARCHIVE );//just for debugging/development, controls frequency of saberlocks - g_debugMelee = gi.cvar( "g_debugMelee", "0", CVAR_CHEAT );//just for debugging/development, test kicks and grabs - g_saberRestrictForce = gi.cvar( "g_saberRestrictForce", "0", CVAR_ARCHIVE );//restricts certain force powers when using a 2-handed saber or 2 sabers - g_saberPickuppableDroppedSabers = gi.cvar( "g_saberPickuppableDroppedSabers", "0", CVAR_CHEAT );//lets you pick up sabers that are dropped - - g_AIsurrender = gi.cvar( "g_AIsurrender", "0", CVAR_CHEAT ); - g_numEntities = gi.cvar( "g_numEntities", "0", 0 ); - - gi.cvar( "newTotalSecrets", "0", CVAR_ROM ); - gi.cvar_set("newTotalSecrets", "0");//used to carry over the count from SP_target_secret to ClientBegin - //g_iscensored = gi.cvar( "ui_iscensored", "0", CVAR_ARCHIVE|CVAR_ROM|CVAR_INIT|CVAR_CHEAT|CVAR_NORESTART ); - - g_speederControlScheme = gi.cvar( "g_speederControlScheme", "2", CVAR_ARCHIVE );//2 is default, 1 is alternate - - g_char_model = gi.cvar( "g_char_model", "jedi_tf", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_skin_head = gi.cvar( "g_char_skin_head", "head_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_skin_torso = gi.cvar( "g_char_skin_torso", "torso_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_skin_legs = gi.cvar( "g_char_skin_legs", "lower_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_color_red = gi.cvar( "g_char_color_red", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_color_green = gi.cvar( "g_char_color_green", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_char_color_blue = gi.cvar( "g_char_color_blue", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_saber = gi.cvar( "g_saber", "single_1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_saber2 = gi.cvar( "g_saber2", "", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_saber_color = gi.cvar( "g_saber_color", "yellow", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_saber2_color = gi.cvar( "g_saber2_color", "yellow", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_saberDarkSideSaberColor = gi.cvar( "g_saberDarkSideSaberColor", "0", CVAR_ARCHIVE ); //when you turn evil, it turns your saber red! - - g_broadsword = gi.cvar( "broadsword", "1", 0); - - g_allowBunnyhopping = gi.cvar( "g_allowBunnyhopping", "0", 0 ); - - gi.cvar( "tier_storyinfo", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - gi.cvar( "tiers_complete", "", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - - gi.cvar( "ui_prisonerobj_currtotal", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - gi.cvar( "ui_prisonerobj_maxtotal", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - - gi.cvar( "g_clearstats", "1", CVAR_ROM|CVAR_NORESTART); - + g_subtitles = gi.cvar("g_subtitles", "0", CVAR_ARCHIVE); + com_buildScript = gi.cvar("com_buildscript", "0", 0); + + g_saberAutoBlocking = gi.cvar("g_saberAutoBlocking", "1", CVAR_CHEAT); // must press +block button to do any blocking + g_saberRealisticCombat = gi.cvar("g_saberMoreRealistic", "0", CVAR_ARCHIVE); // makes collision more precise, increases damage + debug_subdivision = gi.cvar("debug_subdivision", "0", CVAR_ARCHIVE); // debug for dismemberment + g_dismemberProbabilities = gi.cvar("g_dismemberProbabilities", "1", CVAR_ARCHIVE); // 0 = ignore probabilities, 1 = use probabilities + g_saberDamageCapping = gi.cvar("g_saberDamageCapping", "1", CVAR_CHEAT); // caps damage of sabers vs players and NPC who use sabers + g_saberMoveSpeed = gi.cvar("g_saberMoveSpeed", "1", CVAR_CHEAT); // how fast you run while attacking with a saber + g_saberAnimSpeed = gi.cvar("g_saberAnimSpeed", "1", CVAR_CHEAT); // how fast saber animations run + g_saberAutoAim = gi.cvar("g_saberAutoAim", "1", CVAR_CHEAT); // auto-aims at enemies when not moving or when just running forward + g_saberNewControlScheme = gi.cvar("g_saberNewControlScheme", "0", CVAR_ARCHIVE); // use +forcefocus to pull off all the special moves + g_debugSaberLock = gi.cvar("g_debugSaberLock", "0", CVAR_CHEAT); // just for debugging/development, makes saberlocks happen all the time + g_saberLockRandomNess = gi.cvar("g_saberLockRandomNess", "2", CVAR_ARCHIVE); // just for debugging/development, controls frequency of saberlocks + g_debugMelee = gi.cvar("g_debugMelee", "0", CVAR_CHEAT); // just for debugging/development, test kicks and grabs + g_saberRestrictForce = gi.cvar("g_saberRestrictForce", "0", CVAR_ARCHIVE); // restricts certain force powers when using a 2-handed saber or 2 sabers + g_saberPickuppableDroppedSabers = gi.cvar("g_saberPickuppableDroppedSabers", "0", CVAR_CHEAT); // lets you pick up sabers that are dropped + + g_AIsurrender = gi.cvar("g_AIsurrender", "0", CVAR_CHEAT); + g_numEntities = gi.cvar("g_numEntities", "0", 0); + + gi.cvar("newTotalSecrets", "0", CVAR_ROM); + gi.cvar_set("newTotalSecrets", "0"); // used to carry over the count from SP_target_secret to ClientBegin + // g_iscensored = gi.cvar( "ui_iscensored", "0", CVAR_ARCHIVE|CVAR_ROM|CVAR_INIT|CVAR_CHEAT|CVAR_NORESTART ); + + g_speederControlScheme = gi.cvar("g_speederControlScheme", "2", CVAR_ARCHIVE); // 2 is default, 1 is alternate + + g_char_model = gi.cvar("g_char_model", "jedi_tf", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_skin_head = gi.cvar("g_char_skin_head", "head_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_skin_torso = gi.cvar("g_char_skin_torso", "torso_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_skin_legs = gi.cvar("g_char_skin_legs", "lower_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_color_red = gi.cvar("g_char_color_red", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_color_green = gi.cvar("g_char_color_green", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_char_color_blue = gi.cvar("g_char_color_blue", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_saber = gi.cvar("g_saber", "single_1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_saber2 = gi.cvar("g_saber2", "", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_saber_color = gi.cvar("g_saber_color", "yellow", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_saber2_color = gi.cvar("g_saber2_color", "yellow", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_saberDarkSideSaberColor = gi.cvar("g_saberDarkSideSaberColor", "0", CVAR_ARCHIVE); // when you turn evil, it turns your saber red! + + g_broadsword = gi.cvar("broadsword", "1", 0); + + g_allowBunnyhopping = gi.cvar("g_allowBunnyhopping", "0", 0); + + gi.cvar("tier_storyinfo", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + gi.cvar("tiers_complete", "", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + + gi.cvar("ui_prisonerobj_currtotal", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + gi.cvar("ui_prisonerobj_maxtotal", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + + gi.cvar("g_clearstats", "1", CVAR_ROM | CVAR_NORESTART); } /* ============ @@ -722,9 +646,9 @@ InitGame int giMapChecksum; SavedGameJustLoaded_e g_eSavedGameJustLoaded; qboolean g_qbLoadTransition = qfalse; -void InitGame( const char *mapname, const char *spawntarget, int checkSum, const char *entities, int levelTime, int randomSeed, int globalTime, SavedGameJustLoaded_e eSavedGameJustLoaded, qboolean qbLoadTransition ) -{ - //rww - default this to 0, we will auto-set it to 1 if we run into a terrain ent +void InitGame(const char *mapname, const char *spawntarget, int checkSum, const char *entities, int levelTime, int randomSeed, int globalTime, + SavedGameJustLoaded_e eSavedGameJustLoaded, qboolean qbLoadTransition) { + // rww - default this to 0, we will auto-set it to 1 if we run into a terrain ent gi.cvar_set("RMG", "0"); g_bCollidableRoffs = qfalse; @@ -733,40 +657,36 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons g_eSavedGameJustLoaded = eSavedGameJustLoaded; g_qbLoadTransition = qbLoadTransition; - gi.Printf ("------- Game Initialization -------\n"); - gi.Printf ("gamename: %s\n", GAMEVERSION); - gi.Printf ("gamedate: %s\n", SOURCE_DATE); + gi.Printf("------- Game Initialization -------\n"); + gi.Printf("gamename: %s\n", GAMEVERSION); + gi.Printf("gamedate: %s\n", SOURCE_DATE); - srand( randomSeed ); + srand(randomSeed); G_InitCvars(); G_InitMemory(); // set some level globals - memset( &level, 0, sizeof( level ) ); + memset(&level, 0, sizeof(level)); level.time = levelTime; level.globalTime = globalTime; - Q_strncpyz( level.mapname, mapname, sizeof(level.mapname) ); - if ( spawntarget != NULL && spawntarget[0] ) - { - Q_strncpyz( level.spawntarget, spawntarget, sizeof(level.spawntarget) ); - } - else - { + Q_strncpyz(level.mapname, mapname, sizeof(level.mapname)); + if (spawntarget != NULL && spawntarget[0]) { + Q_strncpyz(level.spawntarget, spawntarget, sizeof(level.spawntarget)); + } else { level.spawntarget[0] = 0; } - G_InitWorldSession(); // initialize all entities for this game - memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) ); + memset(g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0])); globals.gentities = g_entities; ClearAllInUse(); // initialize all clients for this game level.maxclients = 1; - level.clients = (gclient_t*) G_Alloc( level.maxclients * sizeof(level.clients[0]) ); + level.clients = (gclient_t *)G_Alloc(level.maxclients * sizeof(level.clients[0])); memset(level.clients, 0, level.maxclients * sizeof(level.clients[0])); // set client fields on player @@ -777,9 +697,9 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons // range are NEVER anything but clients globals.num_entities = MAX_CLIENTS; - //Load sabers.cfg data + // Load sabers.cfg data WP_SaberLoadParms(); - //Set up NPC init data + // Set up NPC init data NPC_InitGame(); TIMER_Clear(); @@ -787,7 +707,7 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons Troop_Reset(); Pilot_Reset(); - IT_LoadItemParms (); + IT_LoadItemParms(); ClearRegisteredItems(); @@ -795,27 +715,26 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons NAV::LoadFromFile(level.mapname, giMapChecksum); // parse the key/value pairs and spawn gentities - G_SpawnEntitiesFromString( entities ); + G_SpawnEntitiesFromString(entities); // general initialization G_FindTeams(); -// SaveRegisteredItems(); + // SaveRegisteredItems(); - gi.Printf ("-----------------------------------\n"); + gi.Printf("-----------------------------------\n"); Rail_Initialize(); Troop_Initialize(); - player = &g_entities[0]; - //Init dynamic music + // Init dynamic music level.dmState = DM_EXPLORE; level.dmDebounceTime = 0; level.dmBeatTime = 0; - level.curAlertID = 1;//0 is default for lastAlertEvent, so... + level.curAlertID = 1; // 0 is default for lastAlertEvent, so... eventClearTime = 0; } @@ -824,8 +743,7 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons ShutdownGame ================= */ -void ShutdownGame( void ) -{ +void ShutdownGame(void) { // write all the client session data so we can get it back G_WriteSessionData(); @@ -838,12 +756,11 @@ void ShutdownGame( void ) // Destroy the Game Interface again. Only way to really free everything. IGameInterface::Destroy(); - TAG_Init(); //Clear the reference tags -/* -Ghoul2 Insert Start -*/ - for (int i=0; is.number] ) - {//not playing a voice sound - //return task_complete - Q3_TaskIDComplete( ent, TID_CHAN_VOICE ); +static void G_CheckTasksCompleted(gentity_t *ent) { + if (Q3_TaskIDPending(ent, TID_CHAN_VOICE)) { + if (!gi.VoiceVolume[ent->s.number]) { // not playing a voice sound + // return task_complete + Q3_TaskIDComplete(ent, TID_CHAN_VOICE); } } - if ( Q3_TaskIDPending( ent, TID_LOCATION ) ) - { - char *currentLoc = G_GetLocationForEnt( ent ); + if (Q3_TaskIDPending(ent, TID_LOCATION)) { + char *currentLoc = G_GetLocationForEnt(ent); - if ( currentLoc && currentLoc[0] && Q_stricmp( ent->message, currentLoc ) == 0 ) - {//we're in the desired location - Q3_TaskIDComplete( ent, TID_LOCATION ); + if (currentLoc && currentLoc[0] && Q_stricmp(ent->message, currentLoc) == 0) { // we're in the desired location + Q3_TaskIDComplete(ent, TID_LOCATION); } - //FIXME: else see if were in other trigger_locations? + // FIXME: else see if were in other trigger_locations? } } -static void G_CheckSpecialPersistentEvents( gentity_t *ent ) -{//special-case alerts that would be a pain in the ass to have the ent's think funcs generate - if ( ent == NULL ) - { +static void G_CheckSpecialPersistentEvents(gentity_t *ent) { // special-case alerts that would be a pain in the ass to have the ent's think funcs generate + if (ent == NULL) { return; } - if ( ent->s.eType == ET_MISSILE && ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY ) - { - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); + if (ent->s.eType == ET_MISSILE && ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY) { + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER); } } - if ( ent->forcePushTime >= level.time ) - {//being pushed - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - //NOTE: presumes the player did the pushing, this is not always true, but shouldn't really matter? - if ( ent->item && ent->item->giTag == INV_SECURITY_KEY ) - { - AddSightEvent( player, ent->currentOrigin, 128, AEL_DISCOVERED );//security keys are more important - } - else - { - AddSightEvent( player, ent->currentOrigin, 128, AEL_SUSPICIOUS );//hmm... or should this always be discovered? + if (ent->forcePushTime >= level.time) { // being pushed + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + // NOTE: presumes the player did the pushing, this is not always true, but shouldn't really matter? + if (ent->item && ent->item->giTag == INV_SECURITY_KEY) { + AddSightEvent(player, ent->currentOrigin, 128, AEL_DISCOVERED); // security keys are more important + } else { + AddSightEvent(player, ent->currentOrigin, 128, AEL_SUSPICIOUS); // hmm... or should this always be discovered? } } } - if ( ent->contents == CONTENTS_LIGHTSABER && !Q_stricmp( "lightsaber", ent->classname ) ) - {//lightsaber - if( ent->owner && ent->owner->client ) - { - if ( ent->owner->client->ps.SaberLength() > 0 ) - {//it's on - //sight event - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED ); + if (ent->contents == CONTENTS_LIGHTSABER && !Q_stricmp("lightsaber", ent->classname)) { // lightsaber + if (ent->owner && ent->owner->client) { + if (ent->owner->client->ps.SaberLength() > 0) { // it's on + // sight event + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED); } } } @@ -1059,29 +952,25 @@ G_RunThink Runs thinking code for this frame if necessary ============= */ -void G_RunThink (gentity_t *ent) -{ - if ( (ent->nextthink <= 0) || (ent->nextthink > level.time) ) - { +void G_RunThink(gentity_t *ent) { + if ((ent->nextthink <= 0) || (ent->nextthink > level.time)) { goto runicarus; } ent->nextthink = 0; - if ( ent->e_ThinkFunc == thinkF_NULL ) // actually you don't need this since I check for it in the next function -slc + if (ent->e_ThinkFunc == thinkF_NULL) // actually you don't need this since I check for it in the next function -slc { goto runicarus; } - GEntity_ThinkFunc( ent ); + GEntity_ThinkFunc(ent); runicarus: - if ( ent->inuse ) // GEntity_ThinkFunc( ent ) can have freed up this ent if it was a type flier_child (stasis1 crash) + if (ent->inuse) // GEntity_ThinkFunc( ent ) can have freed up this ent if it was a type flier_child (stasis1 crash) { - if ( ent->NPC == NULL ) - { - if ( ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( ent->m_iIcarusID ); + if (ent->NPC == NULL) { + if (ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(ent->m_iIcarusID); } } } @@ -1093,46 +982,36 @@ G_Animate ------------------------- */ -static void G_Animate ( gentity_t *self ) -{ - if ( self->s.eFlags & EF_SHADER_ANIM ) - { +static void G_Animate(gentity_t *self) { + if (self->s.eFlags & EF_SHADER_ANIM) { return; } - if ( self->s.frame == self->endFrame ) - { - if ( self->svFlags & SVF_ANIMATING ) - { + if (self->s.frame == self->endFrame) { + if (self->svFlags & SVF_ANIMATING) { // ghoul2 requires some extra checks to see if the animation is done since it doesn't set the current frame directly - if ( self->ghoul2.size() ) - { + if (self->ghoul2.size()) { float frame, junk2; int junk; // I guess query ghoul2 to find out what the current frame is and see if we are done. - gi.G2API_GetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, - (cg.time?cg.time:level.time), &frame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, (cg.time ? cg.time : level.time), &frame, &junk, &junk, &junk, + &junk2, NULL); // It NEVER seems to get to what you'd think the last frame would be, so I'm doing this to try and catch when the animation has stopped - if ( frame + 1 >= self->endFrame ) - { + if (frame + 1 >= self->endFrame) { self->svFlags &= ~SVF_ANIMATING; - Q3_TaskIDComplete( self, TID_ANIM_BOTH ); + Q3_TaskIDComplete(self, TID_ANIM_BOTH); } - } - else // not ghoul2 + } else // not ghoul2 { - if ( self->loopAnim ) - { + if (self->loopAnim) { self->s.frame = self->startFrame; - } - else - { + } else { self->svFlags &= ~SVF_ANIMATING; } - //Finished sequence - FIXME: only do this once even on looping anims? - Q3_TaskIDComplete( self, TID_ANIM_BOTH ); + // Finished sequence - FIXME: only do this once even on looping anims? + Q3_TaskIDComplete(self, TID_ANIM_BOTH); } } return; @@ -1141,39 +1020,27 @@ static void G_Animate ( gentity_t *self ) self->svFlags |= SVF_ANIMATING; // With ghoul2, we'll just set the desired start and end frame and let it do it's thing. - if ( self->ghoul2.size()) - { + if (self->ghoul2.size()) { self->s.frame = self->endFrame; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, - self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, + -1, -1); return; } - if ( self->startFrame < self->endFrame ) - { - if ( self->s.frame < self->startFrame || self->s.frame > self->endFrame ) - { + if (self->startFrame < self->endFrame) { + if (self->s.frame < self->startFrame || self->s.frame > self->endFrame) { self->s.frame = self->startFrame; - } - else - { + } else { self->s.frame++; } - } - else if ( self->startFrame > self->endFrame ) - { - if ( self->s.frame > self->startFrame || self->s.frame < self->endFrame ) - { + } else if (self->startFrame > self->endFrame) { + if (self->s.frame > self->startFrame || self->s.frame < self->endFrame) { self->s.frame = self->startFrame; - } - else - { + } else { self->s.frame--; } - } - else - { + } else { self->s.frame = self->endFrame; } } @@ -1253,73 +1120,57 @@ void UpdateTeamCounters( gentity_t *ent ) teamEnemyCount[ent->client->playerTeam]++; } */ -void G_PlayerGuiltDeath( void ) -{ - if ( player && player->client ) - {//simulate death +void G_PlayerGuiltDeath(void) { + if (player && player->client) { // simulate death player->client->ps.stats[STAT_HEALTH] = 0; - //turn off saber - if ( player->client->ps.weapon == WP_SABER && player->client->ps.SaberActive() ) - { - G_SoundIndexOnEnt( player, CHAN_WEAPON, player->client->ps.saber[0].soundOff ); + // turn off saber + if (player->client->ps.weapon == WP_SABER && player->client->ps.SaberActive()) { + G_SoundIndexOnEnt(player, CHAN_WEAPON, player->client->ps.saber[0].soundOff); player->client->ps.SaberDeactivate(); } - //play the "what have I done?!" anim - NPC_SetAnim( player, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // play the "what have I done?!" anim + NPC_SetAnim(player, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); player->client->ps.legsAnimTimer = player->client->ps.torsoAnimTimer = -1; - //look at yourself - player->client->ps.stats[STAT_DEAD_YAW] = player->client->ps.viewangles[YAW]+180; + // look at yourself + player->client->ps.stats[STAT_DEAD_YAW] = player->client->ps.viewangles[YAW] + 180; } } -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_MakeTeamVulnerable( void ); +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_MakeTeamVulnerable(void); int killPlayerTimer = 0; -static void G_CheckEndLevelTimers( gentity_t *ent ) -{ - if ( killPlayerTimer && level.time > killPlayerTimer ) - { +static void G_CheckEndLevelTimers(gentity_t *ent) { + if (killPlayerTimer && level.time > killPlayerTimer) { killPlayerTimer = 0; ent->health = 0; - if ( ent->client && ent->client->ps.stats[STAT_HEALTH] > 0 ) - { + if (ent->client && ent->client->ps.stats[STAT_HEALTH] > 0) { G_PlayerGuiltDeath(); - //cg.missionStatusShow = qtrue; + // cg.missionStatusShow = qtrue; statusTextIndex = MISSIONFAILED_TURNED; - //debounce respawn time + // debounce respawn time ent->client->respawnTime = level.time + 2000; - //stop all scripts + // stop all scripts stop_icarus = qtrue; - //make the team killable + // make the team killable G_MakeTeamVulnerable(); } } } - - -//rww - RAGDOLL_BEGIN -class CGameRagDollUpdateParams : public CRagDollUpdateParams -{ - void EffectorCollision(const SRagDollEffectorCollision &data) - { - //Com_Printf("Effector Collision at (%f %f %f)\n",data.effectorPosition[0],data.effectorPosition[1],data.effectorPosition[2]); +// rww - RAGDOLL_BEGIN +class CGameRagDollUpdateParams : public CRagDollUpdateParams { + void EffectorCollision(const SRagDollEffectorCollision &data) { + // Com_Printf("Effector Collision at (%f %f %f)\n",data.effectorPosition[0],data.effectorPosition[1],data.effectorPosition[2]); vec3_t effectorPosDif; - if (data.useTracePlane) - { - float magicFactor42=64.0f; - VectorScale(data.tr.plane.normal,magicFactor42,effectorPosDif); - } - else - { + if (data.useTracePlane) { + float magicFactor42 = 64.0f; + VectorScale(data.tr.plane.normal, magicFactor42, effectorPosDif); + } else { gentity_t *thisguy = &g_entities[me]; - if (thisguy && thisguy->client) - { + if (thisguy && thisguy->client) { VectorSubtract(thisguy->client->ps.origin, data.effectorPosition, effectorPosDif); - } - else - { + } else { return; } } @@ -1329,90 +1180,70 @@ class CGameRagDollUpdateParams : public CRagDollUpdateParams hasEffectorData = qtrue; return; } - void RagDollBegin() - { - return; - } - virtual void RagDollSettled() - { - return; - } - void Collision() // we had a collision, please stop animating and (sometime soon) call SetRagDoll RP_DEATH_COLLISION + void RagDollBegin() { return; } + virtual void RagDollSettled() { return; } + void Collision() // we had a collision, please stop animating and (sometime soon) call SetRagDoll RP_DEATH_COLLISION { return; } #ifdef _DEBUG - void DebugLine(vec3_t p1,vec3_t p2,int color,bool bbox) - { - if (!bbox) - { + void DebugLine(vec3_t p1, vec3_t p2, int color, bool bbox) { + if (!bbox) { CG_TestLine(p1, p2, 50, color, 1); } return; } #endif -public: + public: vec3_t effectorTotal; qboolean hasEffectorData; }; -//list of valid ragdoll effectors -static const char *g_effectorStringTable[] = -{ //commented out the ones I don't want dragging to affect -// "thoracic", -// "rhand", - "lhand", - "rtibia", - "ltibia", - "rtalus", - "ltalus", -// "rradiusX", - "lradiusX", - "rfemurX", - "lfemurX", -// "ceyebrow", - NULL //always terminate +// list of valid ragdoll effectors +static const char *g_effectorStringTable[] = { + // commented out the ones I don't want dragging to affect + // "thoracic", + // "rhand", + "lhand", "rtibia", "ltibia", "rtalus", "ltalus", + // "rradiusX", + "lradiusX", "rfemurX", "lfemurX", + // "ceyebrow", + NULL // always terminate }; -extern qboolean G_StandardHumanoid( gentity_t *self ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern qboolean G_ReleaseEntity( gentity_t *grabber ); +extern qboolean G_StandardHumanoid(gentity_t *self); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern qboolean G_ReleaseEntity(gentity_t *grabber); -static void G_BodyDragUpdate(gentity_t *ent, gentity_t *dragger) -{ +static void G_BodyDragUpdate(gentity_t *ent, gentity_t *dragger) { vec3_t handVec; float handDist; - assert(ent && ent->inuse && ent->client && ent->ghoul2.size() && - dragger && dragger->inuse && dragger->client && dragger->ghoul2.size()); + assert(ent && ent->inuse && ent->client && ent->ghoul2.size() && dragger && dragger->inuse && dragger->client && dragger->ghoul2.size()); VectorSubtract(dragger->client->renderInfo.handRPoint, ent->client->renderInfo.torsoPoint, handVec); handDist = VectorLength(handVec); - if (handDist > 64.0f) - { + if (handDist > 64.0f) { G_ReleaseEntity(dragger); - } - else if (handDist > 12.0f) - { + } else if (handDist > 12.0f) { VectorNormalize(handVec); VectorScale(handVec, 256.0f, handVec); handVec[2] = 0; - //VectorAdd(ent->client->ps.velocity, handVec, ent->client->ps.velocity); - //VectorCopy(handVec, ent->client->ps.velocity); + // VectorAdd(ent->client->ps.velocity, handVec, ent->client->ps.velocity); + // VectorCopy(handVec, ent->client->ps.velocity); ent->client->ps.velocity[0] = handVec[0]; ent->client->ps.velocity[1] = handVec[1]; } } -//we want to see which way the pelvis is facing to get a relatively oriented base settling frame -//this is to avoid the arms stretching in opposite directions on the body trying to reach the base -//pose if the pelvis is flipped opposite of the base pose or something -rww -static int G_RagAnimForPositioning(gentity_t *ent) -{ +// we want to see which way the pelvis is facing to get a relatively oriented base settling frame +// this is to avoid the arms stretching in opposite directions on the body trying to reach the base +// pose if the pelvis is flipped opposite of the base pose or something -rww +static int G_RagAnimForPositioning(gentity_t *ent) { vec3_t dir; mdxaBone_t matrix; assert(ent->client); @@ -1421,177 +1252,143 @@ static int G_RagAnimForPositioning(gentity_t *ent) assert(ent->ghoul2.size() > 0); assert(ent->crotchBolt > -1); - gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->crotchBolt, &matrix, G2Angles, ent->client->ps.origin, - (cg.time?cg.time:level.time), NULL, ent->s.modelScale); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->crotchBolt, &matrix, G2Angles, ent->client->ps.origin, (cg.time ? cg.time : level.time), NULL, + ent->s.modelScale); gi.G2API_GiveMeVectorFromMatrix(matrix, NEGATIVE_Z, dir); - if (dir[2] > 0.1f) - { //facing up + if (dir[2] > 0.1f) { // facing up return BOTH_DEADFLOP2; - } - else - { //facing down + } else { // facing down return BOTH_DEADFLOP1; } } -static inline qboolean G_RagWantsHumanoidsOnly( CGhoul2Info *ghlInfo ) -{ - char *GLAName; - GLAName = gi.G2API_GetGLAName( ghlInfo ); +static inline qboolean G_RagWantsHumanoidsOnly(CGhoul2Info *ghlInfo) { + char *GLAName; + GLAName = gi.G2API_GetGLAName(ghlInfo); assert(GLAName); - if ( !Q_stricmp( "models/players/_humanoid/_humanoid", GLAName ) ) - {//only _humanoid skeleton is expected to have these + if (!Q_stricmp("models/players/_humanoid/_humanoid", GLAName)) { // only _humanoid skeleton is expected to have these return qtrue; } return qfalse; } -//rww - game interface for the ragdoll stuff. -//Returns qtrue if the entity is now in a ragdoll state, otherwise qfalse. +// rww - game interface for the ragdoll stuff. +// Returns qtrue if the entity is now in a ragdoll state, otherwise qfalse. //(ported from MP's CG version) -qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) -{ +qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) { vec3_t G2Angles; vec3_t usedOrg; qboolean inSomething = qfalse; int ragAnim; - //int ragVar = gi.Cvar_VariableIntegerValue("broadsword"); + // int ragVar = gi.Cvar_VariableIntegerValue("broadsword"); int ragVar = g_broadsword->integer; - if (!ragVar) - { + if (!ragVar) { return qfalse; } - if (!ent || - !ent->inuse || - !ent->client || - ent->health > 0 || - ent->client->noRagTime >= level.time || - ent->client->noRagTime==-1 || - (ent->s.powerups & (1 << PW_DISRUPTION)) || - !ent->e_DieFunc || - ent->playerModel < 0 || - !ent->ghoul2.size() || - !G_RagWantsHumanoidsOnly(&ent->ghoul2[ent->playerModel]) - ) - { + if (!ent || !ent->inuse || !ent->client || ent->health > 0 || ent->client->noRagTime >= level.time || ent->client->noRagTime == -1 || + (ent->s.powerups & (1 << PW_DISRUPTION)) || !ent->e_DieFunc || ent->playerModel < 0 || !ent->ghoul2.size() || + !G_RagWantsHumanoidsOnly(&ent->ghoul2[ent->playerModel])) { return qfalse; } VectorCopy(forcedAngles, G2Angles); - //forcedAngles[0] = forcedAngles[2] = 0; + // forcedAngles[0] = forcedAngles[2] = 0; - if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) - { + if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) { gentity_t *grabbedBy = &g_entities[ent->client->ps.heldByClient]; - if (grabbedBy->inuse && grabbedBy->client && - grabbedBy->ghoul2.size()) - { + if (grabbedBy->inuse && grabbedBy->client && grabbedBy->ghoul2.size()) { G_BodyDragUpdate(ent, grabbedBy); } } //--FIXME: do not go into ragdoll if in a spinning death anim or something, it really messes things up - //rww 12/17/02 - should be ok now actually with my new stuff + // rww 12/17/02 - should be ok now actually with my new stuff VectorCopy(ent->client->ps.origin, usedOrg); - if (!ent->client->isRagging) - { //If we're not in a ragdoll state, perform the checks. - if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) - { //want to rag no matter what then + if (!ent->client->isRagging) { // If we're not in a ragdoll state, perform the checks. + if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) { // want to rag no matter what then inSomething = qtrue; - } - else if (ent->client->ps.groundEntityNum == ENTITYNUM_NONE) - { + } else if (ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { vec3_t cVel; VectorCopy(ent->client->ps.velocity, cVel); - if (VectorNormalize(cVel) > 400) - { //if he's flying through the air at a good enough speed, switch into ragdoll + if (VectorNormalize(cVel) > 400) { // if he's flying through the air at a good enough speed, switch into ragdoll inSomething = qtrue; } } - if (ragVar > 1) - { //go into rag instantly upon death + if (ragVar > 1) { // go into rag instantly upon death inSomething = qtrue; - //also shove them a tad so they don't just collapse onto the floor - //VectorScale(ent->client->ps.velocity, 1.3f, ent->client->ps.velocity); + // also shove them a tad so they don't just collapse onto the floor + // VectorScale(ent->client->ps.velocity, 1.3f, ent->client->ps.velocity); ent->client->ps.velocity[2] += 32; } - if (!inSomething) - { + if (!inSomething) { int i = 0; int boltChecks[5]; vec3_t boltPoints[5]; vec3_t trStart, trEnd; vec3_t tAng; - //qboolean deathDone = qfalse; + // qboolean deathDone = qfalse; trace_t tr; mdxaBone_t boltMatrix; - VectorSet( tAng, 0, ent->client->ps.viewangles[YAW], 0 ); + VectorSet(tAng, 0, ent->client->ps.viewangles[YAW], 0); - if (ent->client->ps.legsAnimTimer <= 0) - { //Looks like the death anim is done playing - //deathDone = qtrue; + if (ent->client->ps.legsAnimTimer <= 0) { // Looks like the death anim is done playing + // deathDone = qtrue; } - //if (deathDone) - if (1) - { //only trace from the hands if the death anim is already done. + // if (deathDone) + if (1) { // only trace from the hands if the death anim is already done. boltChecks[0] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "rhand"); boltChecks[1] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "lhand"); - } - else - { //otherwise start the trace loop at the cranium. + } else { // otherwise start the trace loop at the cranium. i = 2; } boltChecks[2] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); boltChecks[3] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "rtalus"); boltChecks[4] = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "ltalus"); - //Do the head first, because the hands reference it anyway. - gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[2], &boltMatrix, tAng, ent->client->ps.origin, (cg.time?cg.time:level.time), NULL, ent->s.modelScale); + // Do the head first, because the hands reference it anyway. + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[2], &boltMatrix, tAng, ent->client->ps.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, boltPoints[2]); - while (i < 5) - { - if (i < 2) - { //when doing hands, trace to the head instead of origin - gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[i], &boltMatrix, tAng, ent->client->ps.origin, (cg.time?cg.time:level.time), NULL, ent->s.modelScale); + while (i < 5) { + if (i < 2) { // when doing hands, trace to the head instead of origin + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[i], &boltMatrix, tAng, ent->client->ps.origin, + (cg.time ? cg.time : level.time), NULL, ent->s.modelScale); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, boltPoints[i]); VectorCopy(boltPoints[i], trStart); VectorCopy(boltPoints[2], trEnd); - } - else - { - if (i > 2) - { //2 is the head, which already has the bolt point. - gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[i], &boltMatrix, tAng, ent->client->ps.origin, (cg.time?cg.time:level.time), NULL, ent->s.modelScale); + } else { + if (i > 2) { // 2 is the head, which already has the bolt point. + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, boltChecks[i], &boltMatrix, tAng, ent->client->ps.origin, + (cg.time ? cg.time : level.time), NULL, ent->s.modelScale); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, boltPoints[i]); } VectorCopy(boltPoints[i], trStart); VectorCopy(ent->client->ps.origin, trEnd); } - //Now that we have all that sorted out, trace between the two points we desire. + // Now that we have all that sorted out, trace between the two points we desire. gi.trace(&tr, trStart, NULL, NULL, trEnd, ent->s.number, MASK_SOLID, (EG2_Collision)0, 0); - if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) - { //Hit something or start in solid, so flag it and break. - //This is a slight hack, but if we aren't done with the death anim, we don't really want to - //go into ragdoll unless our body has a relatively "flat" pitch. + if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) { // Hit something or start in solid, so flag it and break. + // This is a slight hack, but if we aren't done with the death anim, we don't really + // want to go into ragdoll unless our body has a relatively "flat" pitch. #if 0 vec3_t vSub; @@ -1614,8 +1411,7 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) } } - if (inSomething) - { + if (inSomething) { /* PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, 0 ); PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); @@ -1627,8 +1423,7 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) } } - if (ent->client->isRagging) - { //We're in a ragdoll state, so make the call to keep our positions updated and whatnot. + if (ent->client->isRagging) { // We're in a ragdoll state, so make the call to keep our positions updated and whatnot. CRagDollParams tParms; CGameRagDollUpdateParams tuParms; @@ -1642,9 +1437,10 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) } */ - //these will be used as "base" frames for the ragoll settling. + // these will be used as "base" frames for the ragoll settling. tParms.startFrame = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations[ragAnim].firstFrame; - tParms.endFrame = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations[ragAnim].firstFrame+level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations[ragAnim].numFrames; + tParms.endFrame = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations[ragAnim].firstFrame + + level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations[ragAnim].numFrames; #if 1 { float currentFrame; @@ -1652,21 +1448,28 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) int flags; float animSpeed; - if (gi.G2API_GetBoneAnim(&ent->ghoul2[0], "model_root", (cg.time?cg.time:level.time), ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL)) - { //lock the anim on the current frame. + if (gi.G2API_GetBoneAnim(&ent->ghoul2[0], "model_root", (cg.time ? cg.time : level.time), ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, + NULL)) { // lock the anim on the current frame. int blendTime = 500; - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "lower_lumbar", currentFrame, currentFrame+1, flags, animSpeed,(cg.time?cg.time:level.time), currentFrame, blendTime); - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", currentFrame, currentFrame+1, flags, animSpeed, (cg.time?cg.time:level.time), currentFrame, blendTime); - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "Motion", currentFrame, currentFrame+1, flags, animSpeed, (cg.time?cg.time:level.time), currentFrame, blendTime); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "lower_lumbar", currentFrame, currentFrame + 1, flags, animSpeed, (cg.time ? cg.time : level.time), + currentFrame, blendTime); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", currentFrame, currentFrame + 1, flags, animSpeed, (cg.time ? cg.time : level.time), + currentFrame, blendTime); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "Motion", currentFrame, currentFrame + 1, flags, animSpeed, (cg.time ? cg.time : level.time), + currentFrame, blendTime); } } #endif - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, (cg.time?cg.time:level.time) ); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, (cg.time?cg.time:level.time) ); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, (cg.time?cg.time:level.time) ); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "cervical", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, (cg.time?cg.time:level.time) ); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, + (cg.time ? cg.time : level.time)); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, + (cg.time ? cg.time : level.time)); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, + (cg.time ? cg.time : level.time)); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "cervical", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 100, + (cg.time ? cg.time : level.time)); VectorCopy(G2Angles, tParms.angles); VectorCopy(usedOrg, tParms.position); @@ -1675,12 +1478,11 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) tParms.groundEnt = ent->client->ps.groundEntityNum; tParms.collisionType = 1; - tParms.RagPhase=CRagDollParams::RP_DEATH_COLLISION; + tParms.RagPhase = CRagDollParams::RP_DEATH_COLLISION; tParms.fShotStrength = 4; gi.G2API_SetRagDoll(ent->ghoul2, &tParms); - tuParms.hasEffectorData = qfalse; VectorClear(tuParms.effectorTotal); @@ -1688,28 +1490,23 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) VectorCopy(usedOrg, tuParms.position); VectorCopy(ent->s.modelScale, tuParms.scale); tuParms.me = ent->s.number; - tuParms.settleFrame = tParms.endFrame-1; + tuParms.settleFrame = tParms.endFrame - 1; tuParms.groundEnt = ent->client->ps.groundEntityNum; - if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) - { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { VectorClear(tuParms.velocity); - } - else - { + } else { VectorScale(ent->client->ps.velocity, 0.4f, tuParms.velocity); } - gi.G2API_AnimateG2Models(ent->ghoul2, (cg.time?cg.time:level.time), &tuParms); + gi.G2API_AnimateG2Models(ent->ghoul2, (cg.time ? cg.time : level.time), &tuParms); - if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) - { + if (ent->client->ps.heldByClient <= ENTITYNUM_WORLD) { gentity_t *grabEnt; grabEnt = &g_entities[ent->client->ps.heldByClient]; - if (grabEnt->client && grabEnt->ghoul2.size()) - { + if (grabEnt->client && grabEnt->ghoul2.size()) { vec3_t bOrg; vec3_t thisHand; vec3_t hands; @@ -1718,48 +1515,45 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) vec3_t thorPoint; float difLen; - //Get the person who is holding our hand's hand location - //gi.G2API_GetBoltMatrix(grabEnt->ghoul2, 0, grabEnt->gent->client->renderInfo.handRPoint, &matrix, grabEnt->turAngles, grabEnt->lerpOrigin, + // Get the person who is holding our hand's hand location + // gi.G2API_GetBoltMatrix(grabEnt->ghoul2, 0, grabEnt->gent->client->renderInfo.handRPoint, &matrix, grabEnt->turAngles, grabEnt->lerpOrigin, // cg.time, cgs.gameModels, grabEnt->modelScale); - //BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, bOrg); + // BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, bOrg); VectorCopy(grabEnt->client->renderInfo.handRPoint, bOrg); - //Get our hand's location - //trap_G2API_GetBoltMatrix(cent->ghoul2, 0, 0, &matrix, cent->turAngles, cent->lerpOrigin, + // Get our hand's location + // trap_G2API_GetBoltMatrix(cent->ghoul2, 0, 0, &matrix, cent->turAngles, cent->lerpOrigin, // cg.time, cgs.gameModels, cent->modelScale); - //BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thisHand); + // BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thisHand); VectorCopy(ent->client->renderInfo.handRPoint, thisHand); - //Get the position of the thoracic bone for hinting its velocity later on - //thorBolt = trap_G2API_AddBolt(cent->ghoul2, 0, "thoracic"); - //trap_G2API_GetBoltMatrix(cent->ghoul2, 0, thorBolt, &matrix, cent->turAngles, cent->lerpOrigin, + // Get the position of the thoracic bone for hinting its velocity later on + // thorBolt = trap_G2API_AddBolt(cent->ghoul2, 0, "thoracic"); + // trap_G2API_GetBoltMatrix(cent->ghoul2, 0, thorBolt, &matrix, cent->turAngles, cent->lerpOrigin, // cg.time, cgs.gameModels, cent->modelScale); - //BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thorPoint); + // BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thorPoint); VectorCopy(ent->client->renderInfo.torsoPoint, thorPoint); VectorSubtract(bOrg, thisHand, hands); - if (VectorLength(hands) < 3.0f) - { + if (VectorLength(hands) < 3.0f) { gi.G2API_RagForceSolve(ent->ghoul2, qfalse); - } - else - { + } else { gi.G2API_RagForceSolve(ent->ghoul2, qtrue); } - //got the hand pos of him, now we want to make our hand go to it + // got the hand pos of him, now we want to make our hand go to it gi.G2API_RagEffectorGoal(ent->ghoul2, "rhand", bOrg); gi.G2API_RagEffectorGoal(ent->ghoul2, "rradius", bOrg); gi.G2API_RagEffectorGoal(ent->ghoul2, "rradiusX", bOrg); gi.G2API_RagEffectorGoal(ent->ghoul2, "rhumerusX", bOrg); gi.G2API_RagEffectorGoal(ent->ghoul2, "rhumerus", bOrg); - //Make these two solve quickly so we can update decently + // Make these two solve quickly so we can update decently gi.G2API_RagPCJGradientSpeed(ent->ghoul2, "rhumerus", 1.5f); gi.G2API_RagPCJGradientSpeed(ent->ghoul2, "rradius", 1.5f); - //Break the constraints on them I suppose + // Break the constraints on them I suppose VectorSet(pcjMin, -999, -999, -999); VectorSet(pcjMax, 999, 999, 999); gi.G2API_RagPCJConstraint(ent->ghoul2, "rhumerus", pcjMin, pcjMax); @@ -1767,7 +1561,7 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) ent->client->overridingBones = level.time + 2000; - //hit the thoracic velocity to the hand point + // hit the thoracic velocity to the hand point VectorSubtract(bOrg, thorPoint, hands); VectorNormalize(hands); VectorScale(hands, 2048.0f, hands); @@ -1777,27 +1571,23 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) VectorSubtract(ent->client->ragLastOrigin, ent->client->ps.origin, pDif); VectorCopy(ent->client->ps.origin, ent->client->ragLastOrigin); - if (ent->client->ragLastOriginTime >= level.time && ent->client->ps.groundEntityNum != ENTITYNUM_NONE) - { //make sure it's reasonably updated + if (ent->client->ragLastOriginTime >= level.time && ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // make sure it's reasonably updated difLen = VectorLength(pDif); - if (difLen > 0.0f) - { //if we're being dragged, then kick all the bones around a bit + if (difLen > 0.0f) { // if we're being dragged, then kick all the bones around a bit vec3_t dVel; vec3_t rVel; int i = 0; - if (difLen < 12.0f) - { - VectorScale(pDif, 12.0f/difLen, pDif); + if (difLen < 12.0f) { + VectorScale(pDif, 12.0f / difLen, pDif); difLen = 12.0f; } - while (g_effectorStringTable[i]) - { + while (g_effectorStringTable[i]) { VectorCopy(pDif, dVel); dVel[2] = 0; - //Factor in a random velocity + // Factor in a random velocity VectorSet(rVel, Q_flrand(-0.1f, 0.1f), Q_flrand(-0.1f, 0.1f), Q_flrand(0.1f, 0.5)); VectorScale(rVel, 8.0f, rVel); @@ -1812,13 +1602,11 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) } ent->client->ragLastOriginTime = level.time + 1000; } - } - else if (ent->client->overridingBones) - { //reset things to their normal rag state + } else if (ent->client->overridingBones) { // reset things to their normal rag state vec3_t pcjMin, pcjMax; vec3_t dVel; - //got the hand pos of him, now we want to make our hand go to it + // got the hand pos of him, now we want to make our hand go to it gi.G2API_RagEffectorGoal(ent->ghoul2, "rhand", NULL); gi.G2API_RagEffectorGoal(ent->ghoul2, "rradius", NULL); gi.G2API_RagEffectorGoal(ent->ghoul2, "rradiusX", NULL); @@ -1831,27 +1619,23 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) gi.G2API_RagPCJGradientSpeed(ent->ghoul2, "rhumerus", 0.0f); gi.G2API_RagPCJGradientSpeed(ent->ghoul2, "rradius", 0.0f); - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); gi.G2API_RagPCJConstraint(ent->ghoul2, "rhumerus", pcjMin, pcjMax); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); gi.G2API_RagPCJConstraint(ent->ghoul2, "rradius", pcjMin, pcjMax); - if (ent->client->overridingBones < level.time) - { + if (ent->client->overridingBones < level.time) { gi.G2API_RagForceSolve(ent->ghoul2, qfalse); ent->client->overridingBones = 0; - } - else - { + } else { gi.G2API_RagForceSolve(ent->ghoul2, qtrue); } } - if (tuParms.hasEffectorData) - { + if (tuParms.hasEffectorData) { /* vec3_t efDir; vec3_t existingVelocity; @@ -1881,8 +1665,7 @@ qboolean G_RagDoll(gentity_t *ent, vec3_t forcedAngles) return qfalse; } -//rww - RAGDOLL_END - +// rww - RAGDOLL_END /* ================ @@ -1891,69 +1674,61 @@ G_RunFrame Advances the non-player objects in the world ================ */ -#if AI_TIMERS +#if AI_TIMERS int AITime = 0; int navTime = 0; -#endif// AI_TIMERS - +#endif // AI_TIMERS -void G_RunFrame( int levelTime ) { - int i; - gentity_t *ent; - int ents_inuse=0; // someone's gonna be pissed I put this here... -#if AI_TIMERS +void G_RunFrame(int levelTime) { + int i; + gentity_t *ent; + int ents_inuse = 0; // someone's gonna be pissed I put this here... +#if AI_TIMERS AITime = 0; navTime = 0; -#endif// AI_TIMERS +#endif // AI_TIMERS level.framenum++; level.previousTime = level.time; level.time = levelTime; - //ResetTeamCounters(); + // ResetTeamCounters(); NAV::DecayDangerSenses(); Rail_Update(); Troop_Update(); Pilot_Update(); - - if (player && gi.WE_IsShaking(player->currentOrigin)) - { - CGCam_Shake(0.45f, 100); + if (player && gi.WE_IsShaking(player->currentOrigin)) { + CGCam_Shake(0.45f, 100); } - AI_UpdateGroups(); - - - - //Look to clear out old events + // Look to clear out old events ClearPlayerAlertEvents(); - //Run the frame for all entities -// for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) - for ( i = 0; i < globals.num_entities ; i++) - { -// if ( !ent->inuse ) -// continue; + // Run the frame for all entities + // for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) + for (i = 0; i < globals.num_entities; i++) { + // if ( !ent->inuse ) + // continue; - if(!PInUse(i)) + if (!PInUse(i)) continue; ents_inuse++; ent = &g_entities[i]; // clear events that are too old - if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) { - if ( ent->s.event ) { - ent->s.event = 0; // &= EV_EVENT_BITS; - if ( ent->client ) { + if (level.time - ent->eventTime > EVENT_VALID_MSEC) { + if (ent->s.event) { + ent->s.event = 0; // &= EV_EVENT_BITS; + if (ent->client) { ent->client->ps.externalEvent = 0; } } - if ( ent->freeAfterEvent ) { + if (ent->freeAfterEvent) { // tempEntities or dropped items completely go away after their event - G_FreeEntity( ent ); + G_FreeEntity(ent); continue; } /* // This is never set to true anywhere. Killing the field (BTO - VV) @@ -1966,190 +1741,142 @@ void G_RunFrame( int levelTime ) { } // temporary entities don't think - if ( ent->freeAfterEvent ) + if (ent->freeAfterEvent) continue; G_CheckTasksCompleted(ent); - G_Roff( ent ); + G_Roff(ent); - if( !ent->client ) - { - if ( !(ent->svFlags & SVF_SELF_ANIMATING) ) - {//FIXME: make sure this is done only for models with frames? - //Or just flag as animating? - if ( ent->s.eFlags & EF_ANIM_ONCE ) - { + if (!ent->client) { + if (!(ent->svFlags & SVF_SELF_ANIMATING)) { // FIXME: make sure this is done only for models with frames? + // Or just flag as animating? + if (ent->s.eFlags & EF_ANIM_ONCE) { ent->s.frame++; - } - else if ( !(ent->s.eFlags & EF_ANIM_ALLFAST) ) - { - G_Animate( ent ); + } else if (!(ent->s.eFlags & EF_ANIM_ALLFAST)) { + G_Animate(ent); } } } - G_CheckSpecialPersistentEvents( ent ); + G_CheckSpecialPersistentEvents(ent); - if ( ent->s.eType == ET_MISSILE ) - { - G_RunMissile( ent ); + if (ent->s.eType == ET_MISSILE) { + G_RunMissile(ent); continue; } - if ( ent->s.eType == ET_ITEM ) - { - G_RunItem( ent ); + if (ent->s.eType == ET_ITEM) { + G_RunItem(ent); continue; } - if ( ent->s.eType == ET_MOVER ) - { + if (ent->s.eType == ET_MOVER) { // FIXME string comparison in per-frame thinks wut??? - if ( ent->model && Q_stricmp( "models/test/mikeg/tie_fighter.md3", ent->model ) == 0 ) - { - TieFighterThink( ent ); + if (ent->model && Q_stricmp("models/test/mikeg/tie_fighter.md3", ent->model) == 0) { + TieFighterThink(ent); } - G_RunMover( ent ); + G_RunMover(ent); continue; } - //The player - if ( i == 0 ) - { + // The player + if (i == 0) { // decay batteries if the goggles are active - if ( cg.zoomMode == 1 && ent->client->ps.batteryCharge > 0 ) - { + if (cg.zoomMode == 1 && ent->client->ps.batteryCharge > 0) { ent->client->ps.batteryCharge--; - } - else if ( cg.zoomMode == 3 && ent->client->ps.batteryCharge > 0 ) - { + } else if (cg.zoomMode == 3 && ent->client->ps.batteryCharge > 0) { ent->client->ps.batteryCharge -= 2; - if ( ent->client->ps.batteryCharge < 0 ) - { + if (ent->client->ps.batteryCharge < 0) { ent->client->ps.batteryCharge = 0; } } - G_CheckEndLevelTimers( ent ); - //Recalculate the nearest waypoint for the coming NPC updates - NAV::GetNearestNode( ent ); + G_CheckEndLevelTimers(ent); + // Recalculate the nearest waypoint for the coming NPC updates + NAV::GetNearestNode(ent); - - if( ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus ) - { - IIcarusInterface::GetIcarus()->Update( ent->m_iIcarusID ); + if (ent->m_iIcarusID != IIcarusInterface::ICARUS_INVALID && !stop_icarus) { + IIcarusInterface::GetIcarus()->Update(ent->m_iIcarusID); } - //dead - if ( ent->health <= 0 ) - { - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - pitch_roll_for_slope( ent ); + // dead + if (ent->health <= 0) { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on the ground + pitch_roll_for_slope(ent); } } - continue; // players are ucmd driven + continue; // players are ucmd driven } - G_RunThink( ent ); // be aware that ent may be free after returning from here, at least one func frees them - ClearNPCGlobals(); // but these 2 funcs are ok - //UpdateTeamCounters( ent ); // to call anyway on a freed ent. + G_RunThink(ent); // be aware that ent may be free after returning from here, at least one func frees them + ClearNPCGlobals(); // but these 2 funcs are ok + // UpdateTeamCounters( ent ); // to call anyway on a freed ent. } // perform final fixups on the player ent = &g_entities[0]; - if ( ent->inuse ) - { - ClientEndFrame( ent ); + if (ent->inuse) { + ClientEndFrame(ent); } - if( g_numEntities->integer ) - { - gi.Printf( S_COLOR_WHITE"Number of Entities in use : %d\n", ents_inuse ); + if (g_numEntities->integer) { + gi.Printf(S_COLOR_WHITE "Number of Entities in use : %d\n", ents_inuse); } - //DEBUG STUFF + // DEBUG STUFF NAV::ShowDebugInfo(ent->currentOrigin, ent->waypoint); NPC_ShowDebugInfo(); G_DynamicMusicUpdate(); -#if AI_TIMERS +#if AI_TIMERS AITime -= navTime; - if ( AITime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: total AI time: %d\n", AITime ); - } - else if ( AITime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: total AI time: %d\n", AITime ); - } - else if ( AITime > 2 ) - { - gi.Printf( S_COLOR_GREEN"total AI time: %d\n", AITime ); - } - if ( navTime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: total nav time: %d\n", navTime ); - } - else if ( navTime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: total nav time: %d\n", navTime ); - } - else if ( navTime > 2 ) - { - gi.Printf( S_COLOR_GREEN"total nav time: %d\n", navTime ); - } -#endif// AI_TIMERS - -extern int delayedShutDown; - if ( g_delayedShutdown->integer && delayedShutDown != 0 && delayedShutDown < level.time ) - { + if (AITime > 20) { + gi.Printf(S_COLOR_RED "ERROR: total AI time: %d\n", AITime); + } else if (AITime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: total AI time: %d\n", AITime); + } else if (AITime > 2) { + gi.Printf(S_COLOR_GREEN "total AI time: %d\n", AITime); + } + if (navTime > 20) { + gi.Printf(S_COLOR_RED "ERROR: total nav time: %d\n", navTime); + } else if (navTime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: total nav time: %d\n", navTime); + } else if (navTime > 2) { + gi.Printf(S_COLOR_GREEN "total nav time: %d\n", navTime); + } +#endif // AI_TIMERS + + extern int delayedShutDown; + if (g_delayedShutdown->integer && delayedShutDown != 0 && delayedShutDown < level.time) { assert(0); - G_Error( "Game Errors. Scroll up the console to read them.\n" ); + G_Error("Game Errors. Scroll up the console to read them.\n"); } #ifdef _DEBUG - if(!(level.framenum&0xff)) - { + if (!(level.framenum & 0xff)) { ValidateInUseBits(); } #endif } - - extern qboolean player_locked; -void G_LoadSave_WriteMiscData() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void G_LoadSave_WriteMiscData() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('L', 'C', 'K', 'D'), - ::player_locked); + saved_game.write_chunk(INT_ID('L', 'C', 'K', 'D'), ::player_locked); } +void G_LoadSave_ReadMiscData() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - -void G_LoadSave_ReadMiscData() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.read_chunk( - INT_ID('L', 'C', 'K', 'D'), - ::player_locked); + saved_game.read_chunk(INT_ID('L', 'C', 'K', 'D'), ::player_locked); } - /* void PrintEntClassname( int gentNum ) { Com_Printf( "%d: %s in snapshot\n", gentNum, g_entities[gentNum].classname ); } */ -IGhoul2InfoArray &TheGameGhoul2InfoArray() -{ - return gi.TheGhoul2InfoArray(); -} +IGhoul2InfoArray &TheGameGhoul2InfoArray() { return gi.TheGhoul2InfoArray(); } diff --git a/code/game/g_mem.cpp b/code/game/g_mem.cpp index 62a6ab34f3..9700811d04 100644 --- a/code/game/g_mem.cpp +++ b/code/game/g_mem.cpp @@ -27,30 +27,26 @@ along with this program; if not, see . #include "g_local.h" - /*#define POOLSIZE (2 * 1024 * 1024) static char memoryPool[POOLSIZE]; */ -static int allocPoint; -static cvar_t *g_debugalloc; +static int allocPoint; +static cvar_t *g_debugalloc; -void *G_Alloc( int size ) { - if ( g_debugalloc->integer ) { - gi.Printf( "G_Alloc of %i bytes\n", size ); +void *G_Alloc(int size) { + if (g_debugalloc->integer) { + gi.Printf("G_Alloc of %i bytes\n", size); } - allocPoint += size; return gi.Malloc(size, TAG_G_ALLOC, qfalse); } -void G_InitMemory( void ) { +void G_InitMemory(void) { allocPoint = 0; - g_debugalloc = gi.cvar ("g_debugalloc", "0", 0); + g_debugalloc = gi.cvar("g_debugalloc", "0", 0); } -void Svcmd_GameMem_f( void ) { - gi.Printf( "Game memory status: %i allocated\n", allocPoint ); -} +void Svcmd_GameMem_f(void) { gi.Printf("Game memory status: %i allocated\n", allocPoint); } diff --git a/code/game/g_misc.cpp b/code/game/g_misc.cpp index 345b635b43..57b1deb6f3 100644 --- a/code/game/g_misc.cpp +++ b/code/game/g_misc.cpp @@ -30,51 +30,46 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "b_local.h" -extern gentity_t *G_FindDoorTrigger( gentity_t *door ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern void SetMiscModelDefaults( gentity_t *ent, useFunc_t use_func, const char *material, int solid_mask,int animFlag, - qboolean take_damage, qboolean damage_model); +extern gentity_t *G_FindDoorTrigger(gentity_t *door); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern void SetMiscModelDefaults(gentity_t *ent, useFunc_t use_func, const char *material, int solid_mask, int animFlag, qboolean take_damage, + qboolean damage_model); #define MAX_AMMO_GIVE 4 - - /*QUAKED func_group (0 0 0) ? Used to group brushes together just for editor convenience. They are turned into normal brushes by the utilities. q3map_onlyvertexlighting 1 = brush only gets vertex lighting (reduces bsp size!) */ - /*QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4) LIGHT Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay. -LIGHT - If this info_null is only targeted by a non-switchable light (a light without a targetname), it does NOT spawn in at all and doesn't count towards the # of entities on the map, even at map spawn/load +LIGHT - If this info_null is only targeted by a non-switchable light (a light without a targetname), it does NOT spawn in at all and doesn't count towards the # +of entities on the map, even at map spawn/load */ -void SP_info_null( gentity_t *self ) { - if ( (self->spawnflags&1) ) - {//only used as a light target, so bugger off - G_FreeEntity( self ); +void SP_info_null(gentity_t *self) { + if ((self->spawnflags & 1)) { // only used as a light target, so bugger off + G_FreeEntity(self); return; } - //FIXME: store targetname and vector (origin) in a list for further reference... remove after 1st second of game? - G_SetOrigin( self, self->s.origin ); + // FIXME: store targetname and vector (origin) in a list for further reference... remove after 1st second of game? + G_SetOrigin(self, self->s.origin); self->e_ThinkFunc = thinkF_G_FreeEntity; - //Give other ents time to link + // Give other ents time to link self->nextthink = level.time + START_TIME_REMOVE_ENTS; } - /*QUAKED info_notnull (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. target_position does the same thing */ -void SP_info_notnull( gentity_t *self ){ - //FIXME: store in ref_tag system? - G_SetOrigin( self, self->s.origin ); +void SP_info_notnull(gentity_t *self) { + // FIXME: store in ref_tag system? + G_SetOrigin(self, self->s.origin); } - /*QUAKED lightJunior (0 0.7 0.3) (-8 -8 -8) (8 8 8) nonlinear angle negative_spot negative_point Non-displayed light that only affects dynamic game models, but does not contribute to lightmaps "light" overrides the default 300 intensity. @@ -96,9 +91,9 @@ Lights pointed at a target will be spotlights. "scale" multiplier for the light intensity - does not affect size (default 1) greater than 1 is brighter, between 0 and 1 is dimmer. "color" sets the light's color -"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, styles or start_off flag) -"style" to specify a specify light style, even for switchable lights! -"style_off" light style to use when switched off (Only for switchable lights) +"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, +styles or start_off flag) "style" to specify a specify light style, even for switchable lights! "style_off" light style to use when switched off (Only for +switchable lights) 1 FLICKER (first variety) 2 SLOW STRONG PULSE @@ -114,65 +109,57 @@ Lights pointed at a target will be spotlights. 12 FAST PULSE FOR JEREMY 13 Test Blending */ -static void misc_lightstyle_set ( gentity_t *ent) -{ +static void misc_lightstyle_set(gentity_t *ent) { const int mLightStyle = ent->count; const int mLightSwitchStyle = ent->bounceCount; const int mLightOffStyle = ent->fly_sound_debounce_time; - if (!ent->misc_dlight_active) - { //turn off - if (mLightOffStyle) //i have a light style i'd like to use when off + if (!ent->misc_dlight_active) { // turn off + if (mLightOffStyle) // i have a light style i'd like to use when off { char lightstyle[32]; - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+0, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 0, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+1, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 1, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+2, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - }else - { - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "a"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "a"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "a"); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 2, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "a"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "a"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "a"); } - } - else - { //Turn myself on now - if (mLightSwitchStyle) //i have a light style i'd like to use when on + } else { // Turn myself on now + if (mLightSwitchStyle) // i have a light style i'd like to use when on { char lightstyle[32]; - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+0, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 0, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+1, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 1, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+2, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - } - else - { - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "z"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "z"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "z"); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 2, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "z"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "z"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "z"); } } } -void SP_light( gentity_t *self ) { - if (!self->targetname ) - {//if i don't have a light style switch, the i go away - G_FreeEntity( self ); +void SP_light(gentity_t *self) { + if (!self->targetname) { // if i don't have a light style switch, the i go away + G_FreeEntity(self); return; } - G_SpawnInt( "style", "0", &self->count ); - G_SpawnInt( "switch_style", "0", &self->bounceCount ); - G_SpawnInt( "style_off", "0", &self->fly_sound_debounce_time ); - G_SetOrigin( self, self->s.origin ); - gi.linkentity( self ); + G_SpawnInt("style", "0", &self->count); + G_SpawnInt("switch_style", "0", &self->bounceCount); + G_SpawnInt("style_off", "0", &self->fly_sound_debounce_time); + G_SetOrigin(self, self->s.origin); + gi.linkentity(self); self->e_UseFunc = useF_misc_dlight_use; self->e_clThinkFunc = clThinkF_NULL; @@ -181,22 +168,19 @@ void SP_light( gentity_t *self ) { self->misc_dlight_active = qfalse; self->svFlags |= SVF_NOCLIENT; - if ( !(self->spawnflags & 4) ) - { //turn myself on now + if (!(self->spawnflags & 4)) { // turn myself on now self->misc_dlight_active = qtrue; } - misc_lightstyle_set (self); + misc_lightstyle_set(self); } -void misc_dlight_use ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void misc_dlight_use(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - ent->misc_dlight_active = (qboolean)!ent->misc_dlight_active; //toggle - misc_lightstyle_set (ent); + ent->misc_dlight_active = (qboolean)!ent->misc_dlight_active; // toggle + misc_lightstyle_set(ent); } - /* ================================================================================= @@ -205,171 +189,159 @@ TELEPORTERS ================================================================================= */ -void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ) -{ - if ( player->NPC && ( player->NPC->aiFlags&NPCAI_FORM_TELE_NAV ) ) - { - //My leader teleported, I was trying to catch up, take this off +void TeleportPlayer(gentity_t *player, vec3_t origin, vec3_t angles) { + if (player->NPC && (player->NPC->aiFlags & NPCAI_FORM_TELE_NAV)) { + // My leader teleported, I was trying to catch up, take this off player->NPC->aiFlags &= ~NPCAI_FORM_TELE_NAV; - } // unlink to make sure it can't possibly interfere with G_KillBox - gi.unlinkentity (player); + gi.unlinkentity(player); - VectorCopy ( origin, player->client->ps.origin ); + VectorCopy(origin, player->client->ps.origin); player->client->ps.origin[2] += 1; - VectorCopy ( player->client->ps.origin, player->currentOrigin ); + VectorCopy(player->client->ps.origin, player->currentOrigin); // spit the player out - AngleVectors( angles, player->client->ps.velocity, NULL, NULL ); - VectorScale( player->client->ps.velocity, 0, player->client->ps.velocity ); - //player->client->ps.pm_time = 160; // hold time - //player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; + AngleVectors(angles, player->client->ps.velocity, NULL, NULL); + VectorScale(player->client->ps.velocity, 0, player->client->ps.velocity); + // player->client->ps.pm_time = 160; // hold time + // player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; // toggle the teleport bit so the client knows to not lerp player->client->ps.eFlags ^= EF_TELEPORT_BIT; // set angles - SetClientViewAngle( player, angles ); + SetClientViewAngle(player, angles); // kill anything at the destination - G_KillBox (player); + G_KillBox(player); // save results of pmove - PlayerStateToEntityState( &player->client->ps, &player->s ); + PlayerStateToEntityState(&player->client->ps, &player->s); - gi.linkentity (player); + gi.linkentity(player); } -void TeleportMover( gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle ) -{//FIXME: need an effect - vec3_t oldAngle, newAngle; - float speed; +void TeleportMover(gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle) { // FIXME: need an effect + vec3_t oldAngle, newAngle; + float speed; // unlink to make sure it can't possibly interfere with G_KillBox - gi.unlinkentity (mover); - - //reposition it - VectorCopy( origin, mover->s.pos.trBase ); - VectorCopy( origin, mover->currentOrigin ); - - //Maintain their previous speed, but adjusted for new direction - if ( snapAngle ) - {//not a diffAngle, actually an absolute angle - vec3_t dir; - - VectorCopy( diffAngles, newAngle ); - AngleVectors( newAngle, dir, NULL, NULL ); - VectorNormalize( dir );//necessary? - speed = VectorLength( mover->s.pos.trDelta ); - VectorScale( dir, speed, mover->s.pos.trDelta ); + gi.unlinkentity(mover); + + // reposition it + VectorCopy(origin, mover->s.pos.trBase); + VectorCopy(origin, mover->currentOrigin); + + // Maintain their previous speed, but adjusted for new direction + if (snapAngle) { // not a diffAngle, actually an absolute angle + vec3_t dir; + + VectorCopy(diffAngles, newAngle); + AngleVectors(newAngle, dir, NULL, NULL); + VectorNormalize(dir); // necessary? + speed = VectorLength(mover->s.pos.trDelta); + VectorScale(dir, speed, mover->s.pos.trDelta); mover->s.pos.trTime = level.time; - VectorSubtract( newAngle, mover->s.apos.trBase, diffAngles ); - VectorCopy( newAngle, mover->s.apos.trBase ); - } - else - { - speed = VectorNormalize( mover->s.pos.trDelta ); + VectorSubtract(newAngle, mover->s.apos.trBase, diffAngles); + VectorCopy(newAngle, mover->s.apos.trBase); + } else { + speed = VectorNormalize(mover->s.pos.trDelta); - vectoangles( mover->s.pos.trDelta, oldAngle ); - VectorAdd( oldAngle, diffAngles, newAngle ); + vectoangles(mover->s.pos.trDelta, oldAngle); + VectorAdd(oldAngle, diffAngles, newAngle); - AngleVectors( newAngle, mover->s.pos.trDelta, NULL, NULL ); - VectorNormalize( mover->s.pos.trDelta ); + AngleVectors(newAngle, mover->s.pos.trDelta, NULL, NULL); + VectorNormalize(mover->s.pos.trDelta); - VectorScale( mover->s.pos.trDelta, speed, mover->s.pos.trDelta ); + VectorScale(mover->s.pos.trDelta, speed, mover->s.pos.trDelta); mover->s.pos.trTime = level.time; - //Maintain their previous angles, but adjusted to new orientation - VectorAdd( mover->s.apos.trBase, diffAngles, mover->s.apos.trBase ); + // Maintain their previous angles, but adjusted to new orientation + VectorAdd(mover->s.apos.trBase, diffAngles, mover->s.apos.trBase); } - //Maintain their previous anglespeed, but adjusted to new orientation - speed = VectorNormalize( mover->s.apos.trDelta ); - VectorAdd( mover->s.apos.trDelta, diffAngles, mover->s.apos.trDelta ); - VectorNormalize( mover->s.apos.trDelta ); - VectorScale( mover->s.apos.trDelta, speed, mover->s.apos.trDelta ); + // Maintain their previous anglespeed, but adjusted to new orientation + speed = VectorNormalize(mover->s.apos.trDelta); + VectorAdd(mover->s.apos.trDelta, diffAngles, mover->s.apos.trDelta); + VectorNormalize(mover->s.apos.trDelta); + VectorScale(mover->s.apos.trDelta, speed, mover->s.apos.trDelta); mover->s.apos.trTime = level.time; - //Tell them it was teleported this move + // Tell them it was teleported this move mover->s.eFlags |= EF_TELEPORT_BIT; // kill anything at the destination - //G_KillBox (mover); - //FIXME: call touch func instead of killbox? + // G_KillBox (mover); + // FIXME: call touch func instead of killbox? - gi.linkentity (mover); + gi.linkentity(mover); } -void teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace) -{ - gentity_t *dest; +void teleporter_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *dest; if (!other->client) return; - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - gi.Printf ("Couldn't find teleporter destination\n"); + gi.Printf("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( other, dest->s.origin, dest->s.angles ); + TeleportPlayer(other, dest->s.origin, dest->s.angles); } /*QUAK-D misc_teleporter (1 0 0) (-32 -32 -24) (32 32 -16) Stepping onto this disc will teleport players to the targeted misc_teleporter_dest object. */ -void SP_misc_teleporter (gentity_t *ent) -{ - gentity_t *trig; +void SP_misc_teleporter(gentity_t *ent) { + gentity_t *trig; - if (!ent->target) - { - gi.Printf ("teleporter without a target.\n"); - G_FreeEntity( ent ); + if (!ent->target) { + gi.Printf("teleporter without a target.\n"); + G_FreeEntity(ent); return; } - ent->s.modelindex = G_ModelIndex( "models/objects/dmspot.md3" ); + ent->s.modelindex = G_ModelIndex("models/objects/dmspot.md3"); ent->s.clientNum = 1; -// ent->s.loopSound = G_SoundIndex("sound/world/amb10.wav"); + // ent->s.loopSound = G_SoundIndex("sound/world/amb10.wav"); ent->contents = CONTENTS_SOLID; - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet (ent->mins, -32, -32, -24); - VectorSet (ent->maxs, 32, 32, -16); - gi.linkentity (ent); + VectorSet(ent->mins, -32, -32, -24); + VectorSet(ent->maxs, 32, 32, -16); + gi.linkentity(ent); - trig = G_Spawn (); + trig = G_Spawn(); trig->e_TouchFunc = touchF_teleporter_touch; trig->contents = CONTENTS_TRIGGER; trig->target = ent->target; trig->owner = ent; - G_SetOrigin( trig, ent->s.origin ); - VectorSet (trig->mins, -8, -8, 8); - VectorSet (trig->maxs, 8, 8, 24); - gi.linkentity (trig); - + G_SetOrigin(trig, ent->s.origin); + VectorSet(trig->mins, -8, -8, 8); + VectorSet(trig->maxs, 8, 8, 24); + gi.linkentity(trig); } /*QUAK-D misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16) - - NODRAW Point teleporters at these. */ -void SP_misc_teleporter_dest( gentity_t *ent ) { - if ( ent->spawnflags & 4 ){ +void SP_misc_teleporter_dest(gentity_t *ent) { + if (ent->spawnflags & 4) { return; } - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - gi.linkentity (ent); + gi.linkentity(ent); } - //=========================================================== /*QUAKED misc_model (1 0 0) (-16 -16 -16) (16 16 16) RMG SOLID @@ -380,9 +352,7 @@ void SP_misc_teleporter_dest( gentity_t *ent ) { "_remap" "from to" remap a shader in this model turns into BSP triangles - not solid by default (click SOLID or use _clipmodel shader) */ -void SP_misc_model( gentity_t *ent ) { - G_FreeEntity( ent ); -} +void SP_misc_model(gentity_t *ent) { G_FreeEntity(ent); } /*QUAKED misc_model_static (1 0 0) (-16 -16 0) (16 16 16) "model" arbitrary .md3 file to display @@ -397,132 +367,105 @@ void SP_misc_model( gentity_t *ent ) { loaded as a model in the renderer - does not take up precious bsp space! */ -extern void CG_CreateMiscEntFromGent(gentity_t *ent, const vec3_t scale, float zOff); //cg_main.cpp -void SP_misc_model_static(gentity_t *ent) -{ - char *value; - float temp; - float zOff; - vec3_t scale; +extern void CG_CreateMiscEntFromGent(gentity_t *ent, const vec3_t scale, float zOff); // cg_main.cpp +void SP_misc_model_static(gentity_t *ent) { + char *value; + float temp; + float zOff; + vec3_t scale; G_SpawnString("modelscale_vec", "1 1 1", &value); - sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); + sscanf(value, "%f %f %f", &scale[0], &scale[1], &scale[2]); - G_SpawnFloat( "modelscale", "0", &temp); - if (temp != 0.0f) - { - scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp; + G_SpawnFloat("modelscale", "0", &temp); + if (temp != 0.0f) { + scale[0] = scale[1] = scale[2] = temp; } - G_SpawnFloat( "zoffset", "0", &zOff); + G_SpawnFloat("zoffset", "0", &zOff); - if (!ent->model) - { - Com_Error( ERR_DROP,"misc_model_static at %s with out a MODEL!\n", vtos(ent->s.origin) ); + if (!ent->model) { + Com_Error(ERR_DROP, "misc_model_static at %s with out a MODEL!\n", vtos(ent->s.origin)); } - //we can be horrible and cheat since this is SP! + // we can be horrible and cheat since this is SP! CG_CreateMiscEntFromGent(ent, scale, zOff); - G_FreeEntity( ent ); + G_FreeEntity(ent); } //=========================================================== -void setCamera ( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *target = 0; +void setCamera(gentity_t *ent) { + vec3_t dir; + gentity_t *target = 0; // frame holds the rotate speed - if ( ent->owner->spawnflags & 1 ) - { + if (ent->owner->spawnflags & 1) { ent->s.frame = 25; - } - else if ( ent->owner->spawnflags & 2 ) - { + } else if (ent->owner->spawnflags & 2) { ent->s.frame = 75; } // clientNum holds the rotate offset ent->s.clientNum = ent->owner->s.clientNum; - VectorCopy( ent->owner->s.origin, ent->s.origin2 ); + VectorCopy(ent->owner->s.origin, ent->s.origin2); // see if the portal_camera has a target if (ent->owner->target) { - target = G_PickTarget( ent->owner->target ); + target = G_PickTarget(ent->owner->target); } - if ( target ) - { - VectorSubtract( target->s.origin, ent->owner->s.origin, dir ); - VectorNormalize( dir ); - } - else - { - G_SetMovedir( ent->owner->s.angles, dir ); + if (target) { + VectorSubtract(target->s.origin, ent->owner->s.origin, dir); + VectorNormalize(dir); + } else { + G_SetMovedir(ent->owner->s.angles, dir); } - ent->s.eventParm = DirToByte( dir ); + ent->s.eventParm = DirToByte(dir); } -void cycleCamera( gentity_t *self ) -{ - self->owner = G_Find( self->owner, FOFS(targetname), self->target ); - if ( self->owner == NULL ) - { - //Uh oh! Not targeted at any ents! Or reached end of list? Which is it? - //for now assume reached end of list and are cycling - self->owner = G_Find( self->owner, FOFS(targetname), self->target ); - if ( self->owner == NULL ) - {//still didn't find one - gi.Printf( "Couldn't find target for misc_portal_surface\n" ); - G_FreeEntity( self ); +void cycleCamera(gentity_t *self) { + self->owner = G_Find(self->owner, FOFS(targetname), self->target); + if (self->owner == NULL) { + // Uh oh! Not targeted at any ents! Or reached end of list? Which is it? + // for now assume reached end of list and are cycling + self->owner = G_Find(self->owner, FOFS(targetname), self->target); + if (self->owner == NULL) { // still didn't find one + gi.Printf("Couldn't find target for misc_portal_surface\n"); + G_FreeEntity(self); return; } } - setCamera( self ); + setCamera(self); - if ( self->e_ThinkFunc == thinkF_cycleCamera ) - { - if ( self->owner->wait > 0 ) - { + if (self->e_ThinkFunc == thinkF_cycleCamera) { + if (self->owner->wait > 0) { self->nextthink = level.time + self->owner->wait; - } - else - { + } else { self->nextthink = level.time + self->wait; } } } -void misc_portal_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - cycleCamera( self ); -} +void misc_portal_use(gentity_t *self, gentity_t *other, gentity_t *activator) { cycleCamera(self); } -void locateCamera( gentity_t *ent ) -{//FIXME: make this fadeout with distance from misc_camera_portal +void locateCamera(gentity_t *ent) { // FIXME: make this fadeout with distance from misc_camera_portal ent->owner = G_Find(NULL, FOFS(targetname), ent->target); - if ( !ent->owner ) - { - gi.Printf( "Couldn't find target for misc_portal_surface\n" ); - G_FreeEntity( ent ); + if (!ent->owner) { + gi.Printf("Couldn't find target for misc_portal_surface\n"); + G_FreeEntity(ent); return; } - setCamera( ent ); + setCamera(ent); - if ( !ent->targetname ) - {//not targetted, so auto-cycle - if ( G_Find(ent->owner, FOFS(targetname), ent->target) != NULL ) - {//targeted at more than one thing + if (!ent->targetname) { // not targetted, so auto-cycle + if (G_Find(ent->owner, FOFS(targetname), ent->target) != NULL) { // targeted at more than one thing ent->e_ThinkFunc = thinkF_cycleCamera; - if ( ent->owner->wait > 0 ) - { + if (ent->owner->wait > 0) { ent->nextthink = level.time + ent->owner->wait; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } } @@ -538,27 +481,22 @@ wait - makes it auto-cycle between all cameras it's pointed at at intevervals of cameras will be cycled through in the order they were created on the map. */ -void SP_misc_portal_surface(gentity_t *ent) -{ - VectorClear( ent->mins ); - VectorClear( ent->maxs ); - gi.linkentity (ent); +void SP_misc_portal_surface(gentity_t *ent) { + VectorClear(ent->mins); + VectorClear(ent->maxs); + gi.linkentity(ent); ent->svFlags = SVF_PORTAL; ent->s.eType = ET_PORTAL; ent->wait *= 1000; - if ( !ent->target ) - {//mirror? - VectorCopy( ent->s.origin, ent->s.origin2 ); - } - else - { + if (!ent->target) { // mirror? + VectorCopy(ent->s.origin, ent->s.origin2); + } else { ent->e_ThinkFunc = thinkF_locateCamera; ent->nextthink = level.time + 100; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_portal_use; } } @@ -569,15 +507,15 @@ The target for a misc_portal_surface. You can set either angles or target anoth "roll" an angle modifier to orient the camera around the target vector; */ void SP_misc_portal_camera(gentity_t *ent) { - float roll; + float roll; - VectorClear( ent->mins ); - VectorClear( ent->maxs ); - gi.linkentity (ent); + VectorClear(ent->mins); + VectorClear(ent->maxs); + gi.linkentity(ent); - G_SpawnFloat( "roll", "0", &roll ); + G_SpawnFloat("roll", "0", &roll); - ent->s.clientNum = roll/360.0 * 256; + ent->s.clientNum = roll / 360.0 * 256; ent->wait *= 1000; } @@ -586,16 +524,14 @@ void G_SubBSPSpawnEntitiesFromString(const char *entityString, vec3_t posOffset, /*QUAKED misc_bsp (1 0 0) (-16 -16 -16) (16 16 16) "bspmodel" arbitrary .bsp file to display */ -void SP_misc_bsp(gentity_t *ent) -{ - char temp[MAX_QPATH]; - char *out; - float newAngle; - int tempint; - - G_SpawnFloat( "angle", "0", &newAngle ); - if (newAngle != 0.0) - { +void SP_misc_bsp(gentity_t *ent) { + char temp[MAX_QPATH]; + char *out; + float newAngle; + int tempint; + + G_SpawnFloat("angle", "0", &newAngle); + if (newAngle != 0.0) { ent->s.angles[1] = newAngle; } // don't support rotation any other way @@ -607,13 +543,13 @@ void SP_misc_bsp(gentity_t *ent) ent->s.eFlags = EF_PERMANENT; // Mainly for debugging - G_SpawnInt( "spacing", "0", &tempint); + G_SpawnInt("spacing", "0", &tempint); ent->s.time2 = tempint; - G_SpawnInt( "flatten", "0", &tempint); + G_SpawnInt("flatten", "0", &tempint); ent->s.time = tempint; Com_sprintf(temp, MAX_QPATH, "#%s", out); - gi.SetBrushModel( ent, temp ); // SV_SetBrushModel -- sets mins and maxs + gi.SetBrushModel(ent, temp); // SV_SetBrushModel -- sets mins and maxs G_BSPIndex(temp); level.mNumBSPInstances++; @@ -624,18 +560,17 @@ void SP_misc_bsp(gentity_t *ent) level.hasBspInstances = qtrue; level.mBSPInstanceDepth++; - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - VectorCopy( ent->s.angles, ent->currentAngles ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + VectorCopy(ent->s.angles, ent->currentAngles); ent->s.eType = ET_MOVER; - gi.linkentity (ent); + gi.linkentity(ent); const char *ents = gi.SetActiveSubBSP(ent->s.modelindex); - if (ents) - { + if (ents) { G_SubBSPSpawnEntitiesFromString(ents, ent->s.origin, ent->s.angles); } gi.SetActiveSubBSP(-1); @@ -643,7 +578,7 @@ void SP_misc_bsp(gentity_t *ent) level.mBSPInstanceDepth--; } -#define MAX_INSTANCE_TYPES 16 +#define MAX_INSTANCE_TYPES 16 void AddSpawnField(char *field, char *value); @@ -665,41 +600,34 @@ miscentDef - defines which client models spawn on the terrain (file is base/ext_ densityMap - how dense the client models are packed */ -void SP_terrain(gentity_t *ent) -{ - G_FreeEntity( ent ); -} - -//rww - Called by skyportal entities. This will check through entities and flag them -//as portal ents if they are in the same pvs as a skyportal entity and pass -//a direct point trace check between origins. I really wanted to use an eFlag for -//flagging portal entities, but too many entities like to reset their eFlags. -//Note that this was not part of the original wolf sky portal stuff. -void G_PortalifyEntities(gentity_t *ent) -{ +void SP_terrain(gentity_t *ent) { G_FreeEntity(ent); } + +// rww - Called by skyportal entities. This will check through entities and flag them +// as portal ents if they are in the same pvs as a skyportal entity and pass +// a direct point trace check between origins. I really wanted to use an eFlag for +// flagging portal entities, but too many entities like to reset their eFlags. +// Note that this was not part of the original wolf sky portal stuff. +void G_PortalifyEntities(gentity_t *ent) { int i = 0; gentity_t *scan = NULL; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { scan = &g_entities[i]; - if (scan && scan->inuse && scan->s.number != ent->s.number && gi.inPVS(ent->s.origin, scan->currentOrigin)) - { + if (scan && scan->inuse && scan->s.number != ent->s.number && gi.inPVS(ent->s.origin, scan->currentOrigin)) { trace_t tr; gi.trace(&tr, ent->s.origin, vec3_origin, vec3_origin, scan->currentOrigin, ent->s.number, CONTENTS_SOLID, G2_NOCOLLIDE, 0); - if (tr.fraction == 1.0 || (tr.entityNum == scan->s.number && tr.entityNum != ENTITYNUM_NONE && tr.entityNum != ENTITYNUM_WORLD)) - { - scan->s.isPortalEnt = qtrue; //he's flagged now + if (tr.fraction == 1.0 || (tr.entityNum == scan->s.number && tr.entityNum != ENTITYNUM_NONE && tr.entityNum != ENTITYNUM_WORLD)) { + scan->s.isPortalEnt = qtrue; // he's flagged now } } i++; } - ent->e_ThinkFunc = thinkF_G_FreeEntity; //the portal entity is no longer needed because its information is stored in a config string. + ent->e_ThinkFunc = thinkF_G_FreeEntity; // the portal entity is no longer needed because its information is stored in a config string. ent->nextthink = level.time; } @@ -711,163 +639,136 @@ To have the portal sky fogged, enter any of the following values: rww - NOTE: fog doesn't work with these currently (at least not in this way). Use a fog brush instead. */ -void SP_misc_skyportal (gentity_t *ent) -{ - vec3_t fogv; //----(SA) - int fogn; //----(SA) - int fogf; //----(SA) - int isfog = 0; // (SA) +void SP_misc_skyportal(gentity_t *ent) { + vec3_t fogv; //----(SA) + int fogn; //----(SA) + int fogf; //----(SA) + int isfog = 0; // (SA) - isfog += G_SpawnVector ("fogcolor", "0 0 0", fogv); - isfog += G_SpawnInt ("fognear", "0", &fogn); - isfog += G_SpawnInt ("fogfar", "300", &fogf); + isfog += G_SpawnVector("fogcolor", "0 0 0", fogv); + isfog += G_SpawnInt("fognear", "0", &fogn); + isfog += G_SpawnInt("fogfar", "300", &fogf); - gi.SetConfigstring( CS_SKYBOXORG, va("%.2f %.2f %.2f %i %.2f %.2f %.2f %i %i", ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], isfog, fogv[0], fogv[1], fogv[2], fogn, fogf ) ); + gi.SetConfigstring(CS_SKYBOXORG, va("%.2f %.2f %.2f %i %.2f %.2f %.2f %i %i", ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], isfog, fogv[0], fogv[1], + fogv[2], fogn, fogf)); ent->e_ThinkFunc = thinkF_G_PortalifyEntities; - ent->nextthink = level.time + 1050; //give it some time first so that all other entities are spawned. + ent->nextthink = level.time + 1050; // give it some time first so that all other entities are spawned. } -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern void SP_fx_runner( gentity_t *ent ); -void camera_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - { - G_UseTargets2( self, player, self->target4 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern void SP_fx_runner(gentity_t *ent); +void camera_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (player && player->client && player->client->ps.viewEntity == self->s.number) { + G_UseTargets2(self, player, self->target4); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); } - G_UseTargets2( self, player, self->closetarget ); - //FIXME: explosion fx/sound - //leave sparks at origin- where base's pole is still at? + G_UseTargets2(self, player, self->closetarget); + // FIXME: explosion fx/sound + // leave sparks at origin- where base's pole is still at? gentity_t *sparks = G_Spawn(); - if ( sparks ) - { + if (sparks) { sparks->fxFile = "sparks/spark"; sparks->delay = 100; sparks->random = 500; - sparks->s.angles[0] = 180;//point down - VectorCopy( self->s.origin, sparks->s.origin ); - SP_fx_runner( sparks ); + sparks->s.angles[0] = 180; // point down + VectorCopy(self->s.origin, sparks->s.origin); + SP_fx_runner(sparks); } - //bye! + // bye! self->takedamage = qfalse; self->contents = 0; self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; } -void camera_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator || !activator->client || activator->s.number ) - {//really only usable by the player +void camera_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || !activator->client || activator->s.number) { // really only usable by the player return; } - self->painDebounceTime = level.time + (self->wait*1000);//FRAMETIME*5;//don't check for player buttons for 500 ms + self->painDebounceTime = level.time + (self->wait * 1000); // FRAMETIME*5;//don't check for player buttons for 500 ms // FIXME: I guess we are allowing them to switch to a dead camera. Maybe we should conditionally do this though? - if ( /*self->health <= 0 ||*/ (player && player->client && player->client->ps.viewEntity == self->s.number) ) - {//I'm already viewEntity, or I'm destroyed, find next + if (/*self->health <= 0 ||*/ (player && player->client && + player->client->ps.viewEntity == self->s.number)) { // I'm already viewEntity, or I'm destroyed, find next gentity_t *next = NULL; - if ( self->target2 != NULL ) - { - next = G_Find( NULL, FOFS(targetname), self->target2 ); + if (self->target2 != NULL) { + next = G_Find(NULL, FOFS(targetname), self->target2); } - if ( next ) - {//found another one - if ( !Q_stricmp( "misc_camera", next->classname ) ) - {//make sure it's another camera - camera_use( next, other, activator ); + if (next) { // found another one + if (!Q_stricmp("misc_camera", next->classname)) { // make sure it's another camera + camera_use(next, other, activator); } - } - else //if ( self->health > 0 ) - {//I was the last (only?) one, clear out the viewentity - G_UseTargets2( self, activator, self->target4 ); - G_ClearViewEntity( activator ); - G_Sound( activator, self->soundPos2 ); - } - } - else - {//set me as view entity - G_UseTargets2( self, activator, self->target3 ); + } else // if ( self->health > 0 ) + { // I was the last (only?) one, clear out the viewentity + G_UseTargets2(self, activator, self->target4); + G_ClearViewEntity(activator); + G_Sound(activator, self->soundPos2); + } + } else { // set me as view entity + G_UseTargets2(self, activator, self->target3); self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; - G_SetViewEntity( activator, self ); - G_Sound( activator, self->soundPos1 ); + G_SetViewEntity(activator, self); + G_Sound(activator, self->soundPos1); } } -void camera_aim( gentity_t *self ) -{ +void camera_aim(gentity_t *self) { self->nextthink = level.time + FRAMETIME; - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - {//I am the viewEntity - if ( player->client->usercmd.forwardmove || player->client->usercmd.rightmove || player->client->usercmd.upmove ) - {//player wants to back out of camera - G_UseTargets2( self, player, self->target4 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); - self->painDebounceTime = level.time + (self->wait*1000);//FRAMETIME*5;//don't check for player buttons for 500 ms - if ( player->client->usercmd.upmove > 0 ) - {//stop player from doing anything for a half second after + if (player && player->client && player->client->ps.viewEntity == self->s.number) { // I am the viewEntity + if (player->client->usercmd.forwardmove || player->client->usercmd.rightmove || player->client->usercmd.upmove) { // player wants to back out of camera + G_UseTargets2(self, player, self->target4); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); + self->painDebounceTime = level.time + (self->wait * 1000); // FRAMETIME*5;//don't check for player buttons for 500 ms + if (player->client->usercmd.upmove > 0) { // stop player from doing anything for a half second after player->aimDebounceTime = level.time + 500; } - } - else if ( self->painDebounceTime < level.time ) - {//check for use button - if ( (player->client->usercmd.buttons&BUTTON_USE) ) - {//player pressed use button, wants to cycle to next - camera_use( self, player, player ); + } else if (self->painDebounceTime < level.time) { // check for use button + if ((player->client->usercmd.buttons & BUTTON_USE)) { // player pressed use button, wants to cycle to next + camera_use(self, player, player); } - } - else - {//don't draw me when being looked through + } else { // don't draw me when being looked through self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; } - } - else if ( self->health > 0 ) - {//still alive, can draw me again + } else if (self->health > 0) { // still alive, can draw me again self->s.eFlags &= ~EF_NODRAW; self->s.modelindex = self->s.modelindex3; } - //update my aim - if ( self->target ) - { - gentity_t *targ = G_Find( NULL, FOFS(targetname), self->target ); - if ( targ ) - { + // update my aim + if (self->target) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), self->target); + if (targ) { vec3_t angles, dir; - VectorSubtract( targ->currentOrigin, self->currentOrigin, dir ); - vectoangles( dir, angles ); - //FIXME: if a G2 model, do a bone override..??? - VectorCopy( self->currentAngles, self->s.apos.trBase ); - - for( int i = 0; i < 3; i++ ) - { - angles[i] = AngleNormalize180( angles[i] ); - self->s.apos.trDelta[i] = AngleNormalize180( (angles[i]-self->currentAngles[i])*10 ); + VectorSubtract(targ->currentOrigin, self->currentOrigin, dir); + vectoangles(dir, angles); + // FIXME: if a G2 model, do a bone override..??? + VectorCopy(self->currentAngles, self->s.apos.trBase); + + for (int i = 0; i < 3; i++) { + angles[i] = AngleNormalize180(angles[i]); + self->s.apos.trDelta[i] = AngleNormalize180((angles[i] - self->currentAngles[i]) * 10); } - //VectorSubtract( angles, self->currentAngles, self->s.apos.trDelta ); - //VectorScale( self->s.apos.trDelta, 10, self->s.apos.trDelta ); + // VectorSubtract( angles, self->currentAngles, self->s.apos.trDelta ); + // VectorScale( self->s.apos.trDelta, 10, self->s.apos.trDelta ); self->s.apos.trTime = level.time; self->s.apos.trDuration = FRAMETIME; - VectorCopy( angles, self->currentAngles ); + VectorCopy(angles, self->currentAngles); - if ( DistanceSquared( self->currentAngles, self->lastAngles ) > 0.01f ) // if it moved at all, start a loop sound? not exactly the "bestest" solution - { - self->s.loopSound = G_SoundIndex( "sound/movers/objects/cameramove_lp2" ); - } - else + if (DistanceSquared(self->currentAngles, self->lastAngles) > 0.01f) // if it moved at all, start a loop sound? not exactly the "bestest" solution { + self->s.loopSound = G_SoundIndex("sound/movers/objects/cameramove_lp2"); + } else { self->s.loopSound = 0; // not moving so don't bother } - VectorCopy( self->currentAngles, self->lastAngles ); - //G_SetAngles( self, angles ); + VectorCopy(self->currentAngles, self->lastAngles); + // G_SetAngles( self, angles ); } } } @@ -885,38 +786,36 @@ VULNERABLE - allow camera to be destroyed "closetarget" - (sigh...) yet another target, fired this when it's destroyed "wait" - how long to wait between being used (default 0.5) */ -void SP_misc_camera( gentity_t *self ) -{ - G_SpawnFloat( "wait", "0.5", &self->wait ); +void SP_misc_camera(gentity_t *self) { + G_SpawnFloat("wait", "0.5", &self->wait); - //FIXME: spawn base, too + // FIXME: spawn base, too gentity_t *base = G_Spawn(); - if ( base ) - { - base->s.modelindex = G_ModelIndex( "models/map_objects/kejim/impcam_base.md3" ); - VectorCopy( self->s.origin, base->s.origin ); + if (base) { + base->s.modelindex = G_ModelIndex("models/map_objects/kejim/impcam_base.md3"); + VectorCopy(self->s.origin, base->s.origin); base->s.origin[2] += 16; - G_SetOrigin( base, base->s.origin ); - G_SetAngles( base, self->s.angles ); - gi.linkentity( base ); - } - self->s.modelindex3 = self->s.modelindex = G_ModelIndex( "models/map_objects/kejim/impcam.md3" ); - self->soundPos1 = G_SoundIndex( "sound/movers/camera_on.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/camera_off.mp3" ); - G_SoundIndex( "sound/movers/objects/cameramove_lp2" ); - - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); - self->s.apos.trType = TR_LINEAR_STOP;//TR_INTERPOLATE;// + G_SetOrigin(base, base->s.origin); + G_SetAngles(base, self->s.angles); + gi.linkentity(base); + } + self->s.modelindex3 = self->s.modelindex = G_ModelIndex("models/map_objects/kejim/impcam.md3"); + self->soundPos1 = G_SoundIndex("sound/movers/camera_on.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/camera_off.mp3"); + G_SoundIndex("sound/movers/objects/cameramove_lp2"); + + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); + self->s.apos.trType = TR_LINEAR_STOP; // TR_INTERPOLATE;// self->alt_fire = qtrue; - VectorSet( self->mins, -8, -8, -12 ); - VectorSet( self->maxs, 8, 8, 0 ); + VectorSet(self->mins, -8, -8, -12); + VectorSet(self->maxs, 8, 8, 0); self->contents = CONTENTS_SOLID; - gi.linkentity( self ); + gi.linkentity(self); - self->fxID = G_EffectIndex( "sparks/spark" ); + self->fxID = G_EffectIndex("sparks/spark"); - if ( self->spawnflags & 1 ) // VULNERABLE + if (self->spawnflags & 1) // VULNERABLE { self->takedamage = qtrue; } @@ -937,58 +836,49 @@ void SP_misc_camera( gentity_t *self ) ====================================================================== */ -void Use_Shooter( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); -} +void Use_Shooter(gentity_t *ent, gentity_t *other, gentity_t *activator) { G_ActivateBehavior(ent, BSET_USE); } -void InitShooter( gentity_t *ent, int weapon ) { +void InitShooter(gentity_t *ent, int weapon) { ent->e_UseFunc = useF_Use_Shooter; ent->s.weapon = weapon; - RegisterItem( FindItemForWeapon( (weapon_t) weapon ) ); + RegisterItem(FindItemForWeapon((weapon_t)weapon)); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); - if ( !ent->random ) { + if (!ent->random) { ent->random = 1.0; } - ent->random = sin( M_PI * ent->random / 180 ); + ent->random = sin(M_PI * ent->random / 180); // target might be a moving object, so we can't set movedir for it - if ( ent->target ) { - G_SetEnemy(ent, G_PickTarget( ent->target )); + if (ent->target) { + G_SetEnemy(ent, G_PickTarget(ent->target)); } - gi.linkentity( ent ); + gi.linkentity(ent); } /*QUAK-ED shooter_rocket (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_rocket( gentity_t *ent ) -{ -// InitShooter( ent, WP_TETRION_DISRUPTOR ); +void SP_shooter_rocket(gentity_t *ent) { + // InitShooter( ent, WP_TETRION_DISRUPTOR ); } /*QUAK-ED shooter_plasma (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" is the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_plasma( gentity_t *ent ) -{ - InitShooter( ent, WP_BRYAR_PISTOL); -} +void SP_shooter_plasma(gentity_t *ent) { InitShooter(ent, WP_BRYAR_PISTOL); } /*QUAK-ED shooter_grenade (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" is the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_grenade( gentity_t *ent ) -{ -// InitShooter( ent, WP_GRENADE_LAUNCHER); +void SP_shooter_grenade(gentity_t *ent) { + // InitShooter( ent, WP_GRENADE_LAUNCHER); } - /*QUAKED object_cargo_barrel1 (1 0 0) (-16 -16 -16) (16 16 29) SMALLER KLINGON NO_SMOKE POWDERKEG Cargo Barrel if given a targetname, using it makes it explode @@ -1002,60 +892,50 @@ health default = 20 splashDamage default = 100 splashRadius default = 200 */ -void SP_object_cargo_barrel1(gentity_t *ent) -{ - if(ent->spawnflags & 8) - { - ent->s.modelindex = G_ModelIndex( "/models/mapobjects/cargo/barrel_wood2.md3" ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode3.wav"); - } - else if(ent->spawnflags & 2) - { - ent->s.modelindex = G_ModelIndex( "/models/mapobjects/scavenger/k_barrel.md3" ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode4.wav"); - } - else - { - ent->s.modelindex = G_ModelIndex( va("/models/mapobjects/cargo/barrel%i.md3", Q_irand( 0, 2 )) ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode1.wav"); +void SP_object_cargo_barrel1(gentity_t *ent) { + if (ent->spawnflags & 8) { + ent->s.modelindex = G_ModelIndex("/models/mapobjects/cargo/barrel_wood2.md3"); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode3.wav"); + } else if (ent->spawnflags & 2) { + ent->s.modelindex = G_ModelIndex("/models/mapobjects/scavenger/k_barrel.md3"); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode4.wav"); + } else { + ent->s.modelindex = G_ModelIndex(va("/models/mapobjects/cargo/barrel%i.md3", Q_irand(0, 2))); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode1.wav"); } - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE; + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE; - if ( ent->spawnflags & 1 ) - { - VectorSet (ent->mins, -8, -8, -16); - VectorSet (ent->maxs, 8, 8, 8); - } - else - { - VectorSet (ent->mins, -16, -16, -16); - VectorSet (ent->maxs, 16, 16, 29); + if (ent->spawnflags & 1) { + VectorSet(ent->mins, -8, -8, -16); + VectorSet(ent->maxs, 8, 8, 8); + } else { + VectorSet(ent->mins, -16, -16, -16); + VectorSet(ent->maxs, 16, 16, 29); } - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); - if(!ent->health) + if (!ent->health) ent->health = 20; - if(!ent->splashDamage) + if (!ent->splashDamage) ent->splashDamage = 100; - if(!ent->splashRadius) + if (!ent->splashRadius) ent->splashRadius = 200; ent->takedamage = qtrue; ent->e_DieFunc = dieF_ExplodeDeath_Wait; - if(ent->targetname) + if (ent->targetname) ent->e_UseFunc = useF_GoExplodeDeath; - gi.linkentity (ent); + gi.linkentity(ent); } - /*QUAKED misc_dlight (0.2 0.8 0.2) (-4 -4 -4) (4 4 4) STARTOFF FADEON FADEOFF PULSE Dynamic light, toggles on and off when used @@ -1076,63 +956,50 @@ starttime - how long to hold at start (seconds) TODO: Add random to speed/radius? */ -void SP_misc_dlight(gentity_t *ent) -{ - G_SetOrigin( ent, ent->s.origin ); - gi.linkentity( ent ); +void SP_misc_dlight(gentity_t *ent) { + G_SetOrigin(ent, ent->s.origin); + gi.linkentity(ent); ent->speed *= 1000; ent->wait *= 1000; ent->radius *= 1000; - //FIXME: attach self to a train or something? + // FIXME: attach self to a train or something? ent->e_UseFunc = useF_misc_dlight_use; ent->misc_dlight_active = qfalse; ent->e_clThinkFunc = clThinkF_NULL; ent->s.eType = ET_GENERAL; - //Delay first think so we can find owner - if ( ent->ownername ) - { + // Delay first think so we can find owner + if (ent->ownername) { ent->e_ThinkFunc = thinkF_misc_dlight_think; ent->nextthink = level.time + START_TIME_LINK_ENTS; } - if ( !(ent->spawnflags & 1) ) - {//Turn myself on now - GEntity_UseFunc( ent, ent, ent ); + if (!(ent->spawnflags & 1)) { // Turn myself on now + GEntity_UseFunc(ent, ent, ent); } } -void misc_dlight_use_old ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void misc_dlight_use_old(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - if ( ent->misc_dlight_active ) - {//We're on, turn off - if ( ent->spawnflags & 4 ) - {//fade off + if (ent->misc_dlight_active) { // We're on, turn off + if (ent->spawnflags & 4) { // fade off ent->pushDebounceTime = 3; - } - else - { + } else { ent->misc_dlight_active = qfalse; ent->e_clThinkFunc = clThinkF_NULL; ent->s.eType = ET_GENERAL; ent->svFlags &= ~SVF_BROADCAST; } - } - else - { - //Start at start regardless of when we were turned off - if ( ent->spawnflags & 4 ) - {//fade on + } else { + // Start at start regardless of when we were turned off + if (ent->spawnflags & 4) { // fade on ent->pushDebounceTime = 2; - } - else - {//Just start on + } else { // Just start on ent->pushDebounceTime = 0; } ent->painDebounceTime = level.time; @@ -1145,35 +1012,29 @@ void misc_dlight_use_old ( gentity_t *ent, gentity_t *other, gentity_t *activato ent->e_clThinkFunc = clThinkF_CG_DLightThink; ent->s.eType = ET_THINKER; - ent->svFlags |= SVF_BROADCAST;// Broadcast to all clients + ent->svFlags |= SVF_BROADCAST; // Broadcast to all clients } } -void misc_dlight_think ( gentity_t *ent ) -{ - //Stay Attached to owner - if ( ent->owner ) - { - G_SetOrigin( ent, ent->owner->currentOrigin ); - gi.linkentity( ent ); - } - else if ( ent->ownername ) - { - ent->owner = G_Find( NULL, FOFS(targetname), ent->ownername ); +void misc_dlight_think(gentity_t *ent) { + // Stay Attached to owner + if (ent->owner) { + G_SetOrigin(ent, ent->owner->currentOrigin); + gi.linkentity(ent); + } else if (ent->ownername) { + ent->owner = G_Find(NULL, FOFS(targetname), ent->ownername); ent->ownername = NULL; } ent->nextthink = level.time + FRAMETIME; } - -void station_pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod,int hitLoc ) -{ -// self->s.modelindex = G_ModelIndex("/models/mapobjects/stasis/plugin2_in.md3"); -// self->s.eFlags &= ~ EF_ANIM_ALLFAST; -// self->s.eFlags |= EF_ANIM_ONCE; -// gi.linkentity (self); +void station_pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, const vec3_t point, int damage, int mod, int hitLoc) { + // self->s.modelindex = G_ModelIndex("/models/mapobjects/stasis/plugin2_in.md3"); + // self->s.eFlags &= ~ EF_ANIM_ALLFAST; + // self->s.eFlags |= EF_ANIM_ONCE; + // gi.linkentity (self); self->s.modelindex = self->s.modelindex2; - gi.linkentity (self); + gi.linkentity(self); } // -------------------------------------------------------------------- @@ -1182,134 +1043,107 @@ void station_pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, cons // // -------------------------------------------------------------------- -void health_use( gentity_t *self, gentity_t *other, gentity_t *activator); -int ITM_AddArmor (gentity_t *ent, int count); -int ITM_AddHealth (gentity_t *ent, int count); +void health_use(gentity_t *self, gentity_t *other, gentity_t *activator); +int ITM_AddArmor(gentity_t *ent, int count); +int ITM_AddHealth(gentity_t *ent, int count); -void health_shutdown( gentity_t *self ) -{ - if (!(self->s.eFlags & EF_ANIM_ONCE)) - { - self->s.eFlags &= ~ EF_ANIM_ALLFAST; +void health_shutdown(gentity_t *self) { + if (!(self->s.eFlags & EF_ANIM_ONCE)) { + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; // Switch to and animate its used up model. - if (!Q_stricmp(self->model,"models/mapobjects/stasis/plugin2.md3")) - { + if (!Q_stricmp(self->model, "models/mapobjects/stasis/plugin2.md3")) { self->s.modelindex = self->s.modelindex2; - } - else if (!Q_stricmp(self->model,"models/mapobjects/borg/plugin2.md3")) - { + } else if (!Q_stricmp(self->model, "models/mapobjects/borg/plugin2.md3")) { self->s.modelindex = self->s.modelindex2; - } - else if (!Q_stricmp(self->model,"models/mapobjects/stasis/plugin2_floor.md3")) - { + } else if (!Q_stricmp(self->model, "models/mapobjects/stasis/plugin2_floor.md3")) { self->s.modelindex = self->s.modelindex2; -// G_Sound(self, G_SoundIndex("sound/ambience/stasis/shrinkage1.wav") ); - } - else if (!Q_stricmp(self->model,"models/mapobjects/forge/panels.md3")) - { + // G_Sound(self, G_SoundIndex("sound/ambience/stasis/shrinkage1.wav") ); + } else if (!Q_stricmp(self->model, "models/mapobjects/forge/panels.md3")) { self->s.modelindex = self->s.modelindex2; } - gi.linkentity (self); + gi.linkentity(self); } } -void health_think( gentity_t *ent ) -{ +void health_think(gentity_t *ent) { int dif; // He's dead, Jim. Don't give him health - if (ent->enemy->health<1) - { + if (ent->enemy->health < 1) { ent->count = 0; ent->e_ThinkFunc = thinkF_NULL; } // Still has power to give - if (ent->count > 0) - { + if (ent->count > 0) { // For every 3 points of health, you get 1 point of armor // BUT!!! after health is filled up, you get the full energy going to armor dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - ent->enemy->health; - if (dif > 3 ) - { - dif= 3; - } - else if (dif < 0) - { - dif= 0; + if (dif > 3) { + dif = 3; + } else if (dif < 0) { + dif = 0; } - if (dif > ent->count) // Can't give more than count + if (dif > ent->count) // Can't give more than count { dif = ent->count; } - if ((ITM_AddHealth (ent->enemy,dif)) && (dif>0)) - { - ITM_AddArmor (ent->enemy,1); // 1 armor for every 3 health + if ((ITM_AddHealth(ent->enemy, dif)) && (dif > 0)) { + ITM_AddArmor(ent->enemy, 1); // 1 armor for every 3 health - ent->count-=dif; + ent->count -= dif; ent->nextthink = level.time + 10; - } - else // User has taken all health he can hold, see about giving it all to armor + } else // User has taken all health he can hold, see about giving it all to armor { - dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - - ent->enemy->client->ps.stats[STAT_ARMOR]; + dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - ent->enemy->client->ps.stats[STAT_ARMOR]; - if (dif > 3) - { + if (dif > 3) { dif = 3; - } - else if (dif < 0) - { - dif= 0; + } else if (dif < 0) { + dif = 0; } - if (ent->count < dif) // Can't give more than count + if (ent->count < dif) // Can't give more than count { dif = ent->count; } - if ((!ITM_AddArmor(ent->enemy,dif)) || (dif<=0)) - { + if ((!ITM_AddArmor(ent->enemy, dif)) || (dif <= 0)) { ent->e_UseFunc = useF_health_use; ent->e_ThinkFunc = thinkF_NULL; - } - else - { - ent->count-=dif; + } else { + ent->count -= dif; ent->nextthink = level.time + 10; } } } - if (ent->count < 1) - { + if (ent->count < 1) { health_shutdown(ent); } } -void misc_model_useup( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void misc_model_useup(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - self->s.eFlags &= ~ EF_ANIM_ALLFAST; + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; // Switch to and animate its used up model. self->s.modelindex = self->s.modelindex2; - gi.linkentity (self); + gi.linkentity(self); // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; @@ -1317,78 +1151,64 @@ void misc_model_useup( gentity_t *self, gentity_t *other, gentity_t *activator) self->nextthink = -1; } -void health_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{//FIXME: Heal entire team? Or only those that are undying...? +void health_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // FIXME: Heal entire team? Or only those that are undying...? int dif; int dif2; int hold; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if (self->e_ThinkFunc != thinkF_NULL) - { + if (self->e_ThinkFunc != thinkF_NULL) { self->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { - if (other->client) - { + if (other->client) { // He's dead, Jim. Don't give him health - if (other->client->ps.stats[STAT_HEALTH]<1) - { + if (other->client->ps.stats[STAT_HEALTH] < 1) { dif = 1; self->count = 0; - } - else - { // Health + } else { // Health dif = other->client->ps.stats[STAT_MAX_HEALTH] - other->client->ps.stats[STAT_HEALTH]; // Armor dif2 = other->client->ps.stats[STAT_MAX_HEALTH] - other->client->ps.stats[STAT_ARMOR]; hold = (dif2 - dif); // For every 3 points of health, you get 1 point of armor // BUT!!! after health is filled up, you get the full energy going to armor - if (hold>0) // Need more armor than health + if (hold > 0) // Need more armor than health { // Calculate total amount of station energy needed. - hold = dif / 3; // For every 3 points of health, you get 1 point of armor + hold = dif / 3; // For every 3 points of health, you get 1 point of armor dif2 -= hold; dif2 += dif; dif = dif2; } } - } - else - { // Being triggered to be used up + } else { // Being triggered to be used up dif = 1; self->count = 0; } // Does player already have full health and full armor? - if (dif > 0) - { -// G_Sound(self, G_SoundIndex("sound/player/suithealth.wav") ); + if (dif > 0) { + // G_Sound(self, G_SoundIndex("sound/player/suithealth.wav") ); - if ((dif >= self->count) || (self->count<1)) // use it all up? + if ((dif >= self->count) || (self->count < 1)) // use it all up? { health_shutdown(self); } // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; self->enemy = other; self->e_ThinkFunc = thinkF_health_think; self->nextthink = level.time + 50; - } - else - { -// G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); + } else { + // G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); } } } @@ -1398,137 +1218,114 @@ void health_use( gentity_t *self, gentity_t *other, gentity_t *activator) // AMMO plugin functions // // -------------------------------------------------------------------- -void ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator); -int Add_Ammo2 (gentity_t *ent, int ammoType, int count); +void ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator); +int Add_Ammo2(gentity_t *ent, int ammoType, int count); -void ammo_shutdown( gentity_t *self ) -{ - if (!(self->s.eFlags & EF_ANIM_ONCE)) - { - self->s.eFlags &= ~ EF_ANIM_ALLFAST; +void ammo_shutdown(gentity_t *self) { + if (!(self->s.eFlags & EF_ANIM_ONCE)) { + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; - gi.linkentity (self); + gi.linkentity(self); } } -void ammo_think( gentity_t *ent ) -{ +void ammo_think(gentity_t *ent) { int dif; // Still has ammo to give - if (ent->count > 0 && ent->enemy ) - { - dif = ammoData[AMMO_BLASTER].max - ent->enemy->client->ps.ammo[AMMO_BLASTER]; + if (ent->count > 0 && ent->enemy) { + dif = ammoData[AMMO_BLASTER].max - ent->enemy->client->ps.ammo[AMMO_BLASTER]; - if (dif > 2 ) - { - dif= 2; - } - else if (dif < 0) - { - dif= 0; + if (dif > 2) { + dif = 2; + } else if (dif < 0) { + dif = 0; } - if (ent->count < dif) // Can't give more than count + if (ent->count < dif) // Can't give more than count { dif = ent->count; } // Give player ammo - if (Add_Ammo2(ent->enemy,AMMO_BLASTER,dif) && (dif!=0)) - { - ent->count-=dif; + if (Add_Ammo2(ent->enemy, AMMO_BLASTER, dif) && (dif != 0)) { + ent->count -= dif; ent->nextthink = level.time + 10; - } - else // User has taken all ammo he can hold + } else // User has taken all ammo he can hold { ent->e_UseFunc = useF_ammo_use; ent->e_ThinkFunc = thinkF_NULL; } } - if (ent->count < 1) - { + if (ent->count < 1) { ammo_shutdown(ent); } } //------------------------------------------------------------ -void ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ +void ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator) { int dif; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if (self->e_ThinkFunc != thinkF_NULL) - { - if (self->e_UseFunc != useF_NULL) - { + if (self->e_ThinkFunc != thinkF_NULL) { + if (self->e_UseFunc != useF_NULL) { self->e_ThinkFunc = thinkF_NULL; } - } - else - { - if (other->client) - { + } else { + if (other->client) { dif = ammoData[AMMO_BLASTER].max - other->client->ps.ammo[AMMO_BLASTER]; - } - else - { // Being triggered to be used up + } else { // Being triggered to be used up dif = 1; self->count = 0; } // Does player already have full ammo? - if (dif > 0) - { -// G_Sound(self, G_SoundIndex("sound/player/suitenergy.wav") ); + if (dif > 0) { + // G_Sound(self, G_SoundIndex("sound/player/suitenergy.wav") ); - if ((dif >= self->count) || (self->count<1)) // use it all up? + if ((dif >= self->count) || (self->count < 1)) // use it all up? { ammo_shutdown(self); } - } - else - { -// G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); + } else { + // G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); } // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->e_ThinkFunc = thinkF_ammo_think; self->nextthink = level.time + 50; } } //------------------------------------------------------------ -void mega_ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior( self, BSET_USE ); +void mega_ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); // Use target when used - G_UseTargets( self, activator ); + G_UseTargets(self, activator); // first use, adjust the max ammo a person can hold for each type of ammo - ammoData[AMMO_BLASTER].max = 999; - ammoData[AMMO_POWERCELL].max = 999; + ammoData[AMMO_BLASTER].max = 999; + ammoData[AMMO_POWERCELL].max = 999; // Set up our count with whatever the max difference will be - if ( other->client->ps.ammo[AMMO_POWERCELL] > other->client->ps.ammo[AMMO_BLASTER] ) + if (other->client->ps.ammo[AMMO_POWERCELL] > other->client->ps.ammo[AMMO_BLASTER]) self->count = ammoData[AMMO_BLASTER].max - other->client->ps.ammo[AMMO_BLASTER]; else self->count = ammoData[AMMO_POWERCELL].max - other->client->ps.ammo[AMMO_POWERCELL]; -// G_Sound( self, G_SoundIndex("sound/player/superenergy.wav") ); + // G_Sound( self, G_SoundIndex("sound/player/superenergy.wav") ); // Clear our usefunc, then think until our ammo is full self->e_UseFunc = useF_NULL; - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->e_ThinkFunc = thinkF_mega_ammo_think; self->nextthink = level.time + 50; @@ -1537,82 +1334,72 @@ void mega_ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } //------------------------------------------------------------ -void mega_ammo_think( gentity_t *self ) -{ - int ammo_add = 5; +void mega_ammo_think(gentity_t *self) { + int ammo_add = 5; // If the middle model is done animating, and we haven't switched to the last model yet... // chuck up the last model. - if (!Q_stricmp(self->model,"models/mapobjects/forge/power_up_boss.md3")) // Because the normal forge_ammo model can use this too + if (!Q_stricmp(self->model, "models/mapobjects/forge/power_up_boss.md3")) // Because the normal forge_ammo model can use this too { - if ( self->s.frame > 16 && self->s.modelindex != self->s.modelindex2 ) + if (self->s.frame > 16 && self->s.modelindex != self->s.modelindex2) self->s.modelindex = self->s.modelindex2; } - if ( self->enemy && self->count > 0 ) - { + if (self->enemy && self->count > 0) { // Add an equal ammount of ammo to each type - self->enemy->client->ps.ammo[AMMO_BLASTER] += ammo_add; - self->enemy->client->ps.ammo[AMMO_POWERCELL] += ammo_add; + self->enemy->client->ps.ammo[AMMO_BLASTER] += ammo_add; + self->enemy->client->ps.ammo[AMMO_POWERCELL] += ammo_add; // Now cap to prevent overflows - if ( self->enemy->client->ps.ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max ) + if (self->enemy->client->ps.ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max) self->enemy->client->ps.ammo[AMMO_BLASTER] = ammoData[AMMO_BLASTER].max; - if ( self->enemy->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) + if (self->enemy->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) self->enemy->client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; // Decrement the count given counter self->count -= ammo_add; // If we've given all we should, prevent giving any more, even if they player is no longer full - if ( self->count <= 0 ) - { + if (self->count <= 0) { self->count = 0; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - } - else + } else self->nextthink = 20; } } - //------------------------------------------------------------ -void switch_models( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void switch_models(gentity_t *self, gentity_t *other, gentity_t *activator) { // FIXME: need a sound here!! - if ( self->s.modelindex2 ) + if (self->s.modelindex2) self->s.modelindex = self->s.modelindex2; } //------------------------------------------------------------ -void touch_ammo_crystal_tigger( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if ( !other->client ) +void touch_ammo_crystal_tigger(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other->client) return; // dead people can't pick things up - if ( other->health < 1 ) + if (other->health < 1) return; // Only player can pick it up - if ( other->s.number != 0 ) - { + if (other->s.number != 0) { return; } - if ( other->client->ps.ammo[ AMMO_POWERCELL ] >= ammoData[AMMO_POWERCELL].max ) - { - return; // can't hold any more + if (other->client->ps.ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max) { + return; // can't hold any more } // Add the ammo other->client->ps.ammo[AMMO_POWERCELL] += self->owner->count; - if ( other->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) - { + if (other->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) { other->client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; } @@ -1623,71 +1410,64 @@ void touch_ammo_crystal_tigger( gentity_t *self, gentity_t *other, trace_t *trac self->owner->s.modelindex = self->owner->s.modelindex2; // play the normal pickup sound -// G_AddEvent( other, EV_ITEM_PICKUP, ITM_AMMO_CRYSTAL_BORG ); + // G_AddEvent( other, EV_ITEM_PICKUP, ITM_AMMO_CRYSTAL_BORG ); // fire item targets - G_UseTargets( self->owner, other ); + G_UseTargets(self->owner, other); } //------------------------------------------------------------ -void spawn_ammo_crystal_trigger( gentity_t *ent ) -{ - gentity_t *other; - vec3_t mins, maxs; +void spawn_ammo_crystal_trigger(gentity_t *ent) { + gentity_t *other; + vec3_t mins, maxs; // Set the base bounds - VectorCopy( ent->s.origin, mins ); - VectorCopy( ent->s.origin, maxs ); + VectorCopy(ent->s.origin, mins); + VectorCopy(ent->s.origin, maxs); // Now add an area of influence around the thing - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { maxs[i] += 48; mins[i] -= 48; } // create a trigger with this size - other = G_Spawn( ); + other = G_Spawn(); - VectorCopy( mins, other->mins ); - VectorCopy( maxs, other->maxs ); + VectorCopy(mins, other->mins); + VectorCopy(maxs, other->maxs); // set up the other bits that the engine needs to know other->owner = ent; other->contents = CONTENTS_TRIGGER; other->e_TouchFunc = touchF_touch_ammo_crystal_tigger; - gi.linkentity( other ); + gi.linkentity(other); } -void misc_replicator_item_remove ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void misc_replicator_item_remove(gentity_t *self, gentity_t *other, gentity_t *activator) { self->s.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->contents = 0; self->s.modelindex = 0; self->e_UseFunc = useF_misc_replicator_item_spawn; - //FIXME: pickup sound? - if ( activator->client ) - { + // FIXME: pickup sound? + if (activator->client) { activator->health += 5; - if ( activator->health > activator->client->ps.stats[STAT_MAX_HEALTH] ) // Past max health + if (activator->health > activator->client->ps.stats[STAT_MAX_HEALTH]) // Past max health { activator->health = activator->client->ps.stats[STAT_MAX_HEALTH]; } } } -void misc_replicator_item_finish_spawn( gentity_t *self ) -{ - //self->contents = CONTENTS_ITEM; - //FIXME: blinks out for a couple frames when transporter effect is done? +void misc_replicator_item_finish_spawn(gentity_t *self) { + // self->contents = CONTENTS_ITEM; + // FIXME: blinks out for a couple frames when transporter effect is done? self->e_UseFunc = useF_misc_replicator_item_remove; } -void misc_replicator_item_spawn ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - switch ( Q_irand( 1, self->count ) ) - { +void misc_replicator_item_spawn(gentity_t *self, gentity_t *other, gentity_t *activator) { + switch (Q_irand(1, self->count)) { case 1: self->s.modelindex = self->bounceCount; break; @@ -1703,16 +1483,16 @@ void misc_replicator_item_spawn ( gentity_t *self, gentity_t *other, gentity_t * case 5: self->s.modelindex = self->attackDebounceTime; break; - case 6://max + case 6: // max self->s.modelindex = self->pushDebounceTime; break; } self->s.eFlags &= ~EF_NODRAW; self->e_ThinkFunc = thinkF_misc_replicator_item_finish_spawn; - self->nextthink = level.time + 4000;//shorter? + self->nextthink = level.time + 4000; // shorter? self->e_UseFunc = useF_NULL; - gentity_t *tent = G_TempEntity( self->currentOrigin, EV_REPLICATOR ); + gentity_t *tent = G_TempEntity(self->currentOrigin, EV_REPLICATOR); tent->owner = self; } @@ -1728,37 +1508,31 @@ model4 - fourth random model key model5 - fifth random model key model6 - sixth random model key -NOTE: do not skip one of these model names, start with the lowest and fill in each next highest one with a value. A gap will cause the item to not work correctly. +NOTE: do not skip one of these model names, start with the lowest and fill in each next highest one with a value. A gap will cause the item to not work +correctly. NOTE: if you use an invalid model, it will still try to use it and show the NULL axis model (or nothing at all) targetname - how you refer to it for using it */ -void SP_misc_replicator_item ( gentity_t *self ) -{ - if ( self->model ) - { - self->bounceCount = G_ModelIndex( self->model ); +void SP_misc_replicator_item(gentity_t *self) { + if (self->model) { + self->bounceCount = G_ModelIndex(self->model); self->count++; - if ( self->model2 ) - { - self->fly_sound_debounce_time = G_ModelIndex( self->model2 ); + if (self->model2) { + self->fly_sound_debounce_time = G_ModelIndex(self->model2); self->count++; - if ( self->target ) - { - self->painDebounceTime = G_ModelIndex( self->target ); + if (self->target) { + self->painDebounceTime = G_ModelIndex(self->target); self->count++; - if ( self->target2 ) - { - self->disconnectDebounceTime = G_ModelIndex( self->target2 ); + if (self->target2) { + self->disconnectDebounceTime = G_ModelIndex(self->target2); self->count++; - if ( self->target3 ) - { - self->attackDebounceTime = G_ModelIndex( self->target3 ); + if (self->target3) { + self->attackDebounceTime = G_ModelIndex(self->target3); self->count++; - if ( self->target4 ) - { - self->pushDebounceTime = G_ModelIndex( self->target4 ); + if (self->target4) { + self->pushDebounceTime = G_ModelIndex(self->target4); self->count++; } } @@ -1766,18 +1540,18 @@ void SP_misc_replicator_item ( gentity_t *self ) } } } -// G_SoundIndex( "sound/movers/switches/replicator.wav" ); + // G_SoundIndex( "sound/movers/switches/replicator.wav" ); self->e_UseFunc = useF_misc_replicator_item_spawn; self->s.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->contents = 0; - VectorSet( self->mins, -4, -4, 0 ); - VectorSet( self->maxs, 4, 4, 8 ); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); + VectorSet(self->mins, -4, -4, 0); + VectorSet(self->maxs, 4, 4, 8); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); - gi.linkentity( self ); + gi.linkentity(self); } /*QUAKED misc_trip_mine (0.2 0.8 0.2) (-4 -4 -4) (4 4 4) START_ON BROADCAST START_OFF @@ -1793,149 +1567,136 @@ targetname - starts off, when used, turns on (toggles) FIXME: sometimes we want these to not be shootable... maybe just put them behind a force field? */ -extern void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ); -extern void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ); +extern void touchLaserTrap(gentity_t *ent, gentity_t *other, trace_t *trace); +extern void CreateLaserTrap(gentity_t *laserTrap, vec3_t start, gentity_t *owner); -void misc_trip_mine_activate( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->e_ThinkFunc == thinkF_laserTrapThink ) - { +void misc_trip_mine_activate(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->e_ThinkFunc == thinkF_laserTrapThink) { self->s.eFlags &= ~EF_FIRING; self->s.loopSound = 0; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - } - else - { + } else { self->e_ThinkFunc = thinkF_laserTrapThink; self->nextthink = level.time + FRAMETIME; self->s.eFlags &= ~EF_NODRAW; - self->contents = CONTENTS_SHOTCLIP;//CAN'T USE CONTENTS_SOLID because only ARCHITECTURE is contents_solid!!! + self->contents = CONTENTS_SHOTCLIP; // CAN'T USE CONTENTS_SOLID because only ARCHITECTURE is contents_solid!!! self->takedamage = qtrue; } } -void SP_misc_trip_mine( gentity_t *self ) -{ - vec3_t forward, end; - trace_t trace; +void SP_misc_trip_mine(gentity_t *self) { + vec3_t forward, end; + trace_t trace; - AngleVectors( self->s.angles, forward, NULL, NULL ); - VectorMA( self->s.origin, 128, forward, end ); + AngleVectors(self->s.angles, forward, NULL, NULL); + VectorMA(self->s.origin, 128, forward, end); - gi.trace( &trace, self->s.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&trace, self->s.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( trace.allsolid || trace.startsolid ) - { - Com_Error( ERR_DROP,"misc_trip_mine at %s in solid\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.allsolid || trace.startsolid) { + Com_Error(ERR_DROP, "misc_trip_mine at %s in solid\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( trace.fraction == 1.0 ) - { - Com_Error( ERR_DROP,"misc_trip_mine at %s pointed at no surface\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.fraction == 1.0) { + Com_Error(ERR_DROP, "misc_trip_mine at %s pointed at no surface\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - RegisterItem( FindItemForWeapon( WP_TRIP_MINE )); //precache the weapon + RegisterItem(FindItemForWeapon(WP_TRIP_MINE)); // precache the weapon - self->count = 2/*TRIPWIRE_STYLE*/; + self->count = 2 /*TRIPWIRE_STYLE*/; - vectoangles( trace.plane.normal, end ); - G_SetOrigin( self, trace.endpos ); - G_SetAngles( self, end ); + vectoangles(trace.plane.normal, end); + G_SetOrigin(self, trace.endpos); + G_SetAngles(self, end); - CreateLaserTrap( self, trace.endpos, self ); - touchLaserTrap( self, self, &trace ); + CreateLaserTrap(self, trace.endpos, self); + touchLaserTrap(self, self, &trace); self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - if ( !self->targetname || (self->spawnflags&1) ) - {//starts on - misc_trip_mine_activate( self, self, self ); + if (!self->targetname || (self->spawnflags & 1)) { // starts on + misc_trip_mine_activate(self, self, self); } - if ( self->targetname ) - { + if (self->targetname) { self->e_UseFunc = useF_misc_trip_mine_activate; } - if (( self->spawnflags & 2 )) // broadcast...should only be used in very rare cases. could fix networking, perhaps, but james suggested this because it's easier + if ((self->spawnflags & + 2)) // broadcast...should only be used in very rare cases. could fix networking, perhaps, but james suggested this because it's easier { self->svFlags |= SVF_BROADCAST; } // Whether to start completelly off or not. - if ( self->targetname && self->spawnflags & 4 ) - { + if (self->targetname && self->spawnflags & 4) { self->s.eFlags = EF_NODRAW; self->contents = 0; self->takedamage = qfalse; } - gi.linkentity( self ); + gi.linkentity(self); } /*QUAKED misc_maglock (0 .5 .8) (-8 -8 -8) (8 8 8) x x x x x x x x -Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door it's attached to +Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door +it's attached to NOTE: place these half-way in the door to make it flush with the door's surface. "target" thing to use when destoryed (not doors - it automatically unlocks the door it was angled at) "health" default is 10 */ -void maglock_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - //unlock our door if we're the last lock pointed at the door - if ( self->activator ) - { +void maglock_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + // unlock our door if we're the last lock pointed at the door + if (self->activator) { self->activator->lockCount--; - if ( !self->activator->lockCount ) - { + if (!self->activator->lockCount) { self->activator->svFlags &= ~SVF_INACTIVE; } } - //use targets - G_UseTargets( self, attacker ); - //die - WP_Explode( self ); + // use targets + G_UseTargets(self, attacker); + // die + WP_Explode(self); } -void SP_misc_maglock ( gentity_t *self ) -{ - //NOTE: May have to make these only work on doors that are either untargeted +void SP_misc_maglock(gentity_t *self) { + // NOTE: May have to make these only work on doors that are either untargeted // or are targeted by a trigger, not doors fired off by scripts, counters // or other such things? - self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - self->fxID = G_EffectIndex( "maglock/explosion" ); + self->s.modelindex = G_ModelIndex("models/map_objects/imp_detention/door_lock.md3"); + self->fxID = G_EffectIndex("maglock/explosion"); - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_ThinkFunc = thinkF_maglock_link; - //FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the START_TIME_FIND_LINKS - self->nextthink = level.time + START_TIME_FIND_LINKS+200;//START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! + // FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the + // START_TIME_FIND_LINKS + self->nextthink = + level.time + START_TIME_FIND_LINKS + 200; // START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! } -void maglock_link( gentity_t *self ) -{ - //find what we're supposed to be attached to - vec3_t forward, start, end; - trace_t trace; +void maglock_link(gentity_t *self) { + // find what we're supposed to be attached to + vec3_t forward, start, end; + trace_t trace; - AngleVectors( self->s.angles, forward, NULL, NULL ); - VectorMA( self->s.origin, 128, forward, end ); - VectorMA( self->s.origin, -4, forward, start ); + AngleVectors(self->s.angles, forward, NULL, NULL); + VectorMA(self->s.origin, 128, forward, end); + VectorMA(self->s.origin, -4, forward, start); - gi.trace( &trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( trace.allsolid || trace.startsolid ) - { - Com_Error( ERR_DROP,"misc_maglock at %s in solid\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.allsolid || trace.startsolid) { + Com_Error(ERR_DROP, "misc_maglock at %s in solid\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { self->e_ThinkFunc = thinkF_maglock_link; self->nextthink = level.time + 100; /* @@ -1945,45 +1706,43 @@ void maglock_link( gentity_t *self ) return; } gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp( "func_door", traceEnt->classname ) ) - { + if (trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp("func_door", traceEnt->classname)) { self->e_ThinkFunc = thinkF_maglock_link; self->nextthink = level.time + 100; - //Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); - //G_FreeEntity( self ); + // Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); + // G_FreeEntity( self ); return; } - //check the traceEnt, make sure it's a door and give it a lockCount and deactivate it - //find the trigger for the door - self->activator = G_FindDoorTrigger( traceEnt ); - if ( !self->activator ) - { + // check the traceEnt, make sure it's a door and give it a lockCount and deactivate it + // find the trigger for the door + self->activator = G_FindDoorTrigger(traceEnt); + if (!self->activator) { self->activator = traceEnt; } self->activator->lockCount++; self->activator->svFlags |= SVF_INACTIVE; - //now position and orient it - vectoangles( trace.plane.normal, end ); - G_SetOrigin( self, trace.endpos ); - G_SetAngles( self, end ); + // now position and orient it + vectoangles(trace.plane.normal, end); + G_SetOrigin(self, trace.endpos); + G_SetAngles(self, end); - //make it hittable - //FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? - //self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - VectorSet( self->mins, -8, -8, -8 ); - VectorSet( self->maxs, 8, 8, 8 ); + // make it hittable + // FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? + // self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); + VectorSet(self->mins, -8, -8, -8); + VectorSet(self->maxs, 8, 8, 8); self->contents = CONTENTS_CORPSE; - //make it destroyable - self->flags |= FL_SHIELDED;//only damagable by lightsabers + // make it destroyable + self->flags |= FL_SHIELDED; // only damagable by lightsabers self->takedamage = qtrue; self->health = 10; self->e_DieFunc = dieF_maglock_die; - //self->fxID = G_EffectIndex( "maglock/explosion" ); + // self->fxID = G_EffectIndex( "maglock/explosion" ); - gi.linkentity( self ); + gi.linkentity(self); } /* @@ -1991,22 +1750,19 @@ void maglock_link( gentity_t *self ) EnergyShieldStationSettings ================ */ -void EnergyShieldStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void EnergyShieldStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } @@ -2018,37 +1774,30 @@ void EnergyShieldStationSettings(gentity_t *ent) shield_power_converter_use ================ */ -void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int dif,add; +void shield_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int dif, add; - if ( !activator || activator->s.number != 0 ) - { - //only the player gets to use these + if (!activator || activator->s.number != 0) { + // only the player gets to use these return; } - G_ActivateBehavior( self,BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - if ( self->setTime < level.time ) - { + if (self->setTime < level.time) { self->setTime = level.time + 100; dif = 100 - activator->client->ps.stats[STAT_ARMOR]; // FIXME: define for max armor? - if ( dif > 0 && self->count ) // Already at full armor?..and do I even have anything to give + if (dif > 0 && self->count) // Already at full armor?..and do I even have anything to give { - if ( dif > MAX_AMMO_GIVE ) - { + if (dif > MAX_AMMO_GIVE) { add = MAX_AMMO_GIVE; - } - else - { + } else { add = dif; } - if ( self->count < add ) - { + if (self->count < add) { add = self->count; } @@ -2056,51 +1805,43 @@ void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *a activator->client->ps.stats[STAT_ARMOR] += add; - self->s.loopSound = G_SoundIndex( "sound/interface/shieldcon_run.wav" ); + self->s.loopSound = G_SoundIndex("sound/interface/shieldcon_run.wav"); } - if ( self->count <= 0 ) - { + if (self->count <= 0) { // play empty sound self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much - G_Sound( self, G_SoundIndex( "sound/interface/shieldcon_empty.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/shieldcon_empty.mp3")); self->s.loopSound = 0; - if ( self->s.eFlags & EF_SHADER_ANIM ) - { - self->s.frame = 1; + if (self->s.eFlags & EF_SHADER_ANIM) { + self->s.frame = 1; } - } - else if ( activator->client->ps.stats[STAT_ARMOR] >= 100 ) // FIXME: define for max + } else if (activator->client->ps.stats[STAT_ARMOR] >= 100) // FIXME: define for max { // play full sound - G_Sound( self, G_SoundIndex( "sound/interface/shieldcon_done.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/shieldcon_done.mp3")); self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much self->s.loopSound = 0; } } - if ( self->s.loopSound ) - { + if (self->s.loopSound) { // we will have to shut of the loop sound, so I guess try and do it intelligently...NOTE: this could get completely stomped every time through the loop // this is fine, since it just controls shutting off the sound when there are situations that could start the sound but not shut it off self->e_ThinkFunc = thinkF_poll_converter; self->nextthink = level.time + 500; - } - else - { + } else { // sound is already off, so we don't need to "think" about it. self->e_ThinkFunc = thinkF_NULL; self->nextthink = 0; } - if ( activator->client->ps.stats[STAT_ARMOR] > 0 ) - { + if (activator->client->ps.stats[STAT_ARMOR] > 0) { activator->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; } } - /*QUAKED misc_model_shield_power_converter (1 0 0) (-16 -16 -16) (16 16 16) x x x USETARGET model="models/items/psd_big.md3" Gives shield energy when used. @@ -2114,9 +1855,8 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_model_shield_power_converter( gentity_t *ent ) -{ - SetMiscModelDefaults( ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); +void SP_misc_model_shield_power_converter(gentity_t *ent) { + SetMiscModelDefaults(ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2126,25 +1866,21 @@ void SP_misc_model_shield_power_converter( gentity_t *ent ) G_SoundIndex("sound/interface/shieldcon_done.mp3"); G_SoundIndex("sound/interface/shieldcon_empty.mp3"); - ent->s.modelindex = G_ModelIndex("models/items/psd_big.md3"); // Precache model - ent->s.modelindex2 = G_ModelIndex("models/items/psd_big.md3"); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/psd_big.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("models/items/psd_big.md3"); // Precache model } -void bomb_planted_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->count == 2 ) - { +void bomb_planted_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->count == 2) { self->s.eFlags &= ~EF_NODRAW; self->contents = CONTENTS_SOLID; self->count = 1; self->s.loopSound = self->noise_index; - } - else if ( self->count == 1 ) - { + } else if (self->count == 1) { self->count = 0; // play disarm sound self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much - G_Sound( self, G_SoundIndex("sound/weapons/overchargeend")); + G_Sound(self, G_SoundIndex("sound/weapons/overchargeend")); self->s.loopSound = 0; // this pauses the shader on one frame (more or less) @@ -2154,8 +1890,8 @@ void bomb_planted_use( gentity_t *self, gentity_t *other, gentity_t *activator) self->s.eFlags |= EF_ANIM_ONCE; self->s.frame = 0; - //use targets - G_UseTargets( self, activator ); + // use targets + G_UseTargets(self, activator); } } @@ -2167,28 +1903,26 @@ Planted by evil men for evil purposes. "forcevisible" - When you turn on force sight (any level), you can see these draw through the entire level... */ //------------------------------------------------------------ -void SP_misc_model_bomb_planted( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 70 ); +void SP_misc_model_bomb_planted(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 70); - SetMiscModelDefaults( ent, useF_bomb_planted_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_bomb_planted_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; G_SoundIndex("sound/weapons/overchargeend"); ent->s.modelindex = G_ModelIndex("models/map_objects/factory/bomb_new_deact.md3"); // Precache model - ent->s.modelindex2 = G_ModelIndex("models/map_objects/factory/bomb_new_deact.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("models/map_objects/factory/bomb_new_deact.md3"); // Precache model ent->noise_index = G_SoundIndex("sound/interface/ammocon_run"); ent->s.loopSound = ent->noise_index; - //ent->s.eFlags |= EF_SHADER_ANIM; - //ent->s.frame = ent->startFrame = 0; + // ent->s.eFlags |= EF_SHADER_ANIM; + // ent->s.frame = ent->startFrame = 0; ent->count = 1; // If we have a targetname, we're are invisible until we are spawned in by being used. - if ( ent->targetname ) - { + if (ent->targetname) { ent->s.eFlags = EF_NODRAW; ent->contents = 0; ent->count = 2; @@ -2196,16 +1930,14 @@ void SP_misc_model_bomb_planted( gentity_t *ent ) } int forceVisible = 0; - G_SpawnInt( "forcevisible", "0", &forceVisible ); - if ( forceVisible ) - {//can see these through walls with force sight, so must be broadcast - //ent->svFlags |= SVF_BROADCAST; + G_SpawnInt("forcevisible", "0", &forceVisible); + if (forceVisible) { // can see these through walls with force sight, so must be broadcast + // ent->svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_FORCE_VISIBLE; } } -void beacon_deploy( gentity_t *ent ) -{ +void beacon_deploy(gentity_t *ent) { ent->e_ThinkFunc = thinkF_beacon_think; ent->nextthink = level.time + FRAMETIME * 0.5f; @@ -2215,13 +1947,11 @@ void beacon_deploy( gentity_t *ent ) ent->loopAnim = qfalse; } -void beacon_think( gentity_t *ent ) -{ +void beacon_think(gentity_t *ent) { ent->nextthink = level.time + FRAMETIME * 0.5f; // Deploy animation complete? Stop thinking and just animate signal forever. - if ( ent->s.frame == 30 ) - { + if (ent->s.frame == 30) { ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = -1; @@ -2233,19 +1963,15 @@ void beacon_think( gentity_t *ent ) } } -void beacon_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ +void beacon_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Every time it's used it will be toggled on or off. - if ( self->count == 0 ) - { + if (self->count == 0) { self->s.eFlags &= ~EF_NODRAW; self->contents = CONTENTS_SOLID; self->count = 1; self->svFlags = SVF_ANIMATING; - beacon_deploy( self ); - } - else - { + beacon_deploy(self); + } else { self->s.eFlags = EF_NODRAW; self->contents = 0; self->count = 0; @@ -2261,40 +1987,35 @@ An animating beacon model. "forcevisible" - When you turn on force sight (any level), you can see these draw through the entire level... */ //------------------------------------------------------------ -void SP_misc_model_beacon( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 24 ); +void SP_misc_model_beacon(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 24); - SetMiscModelDefaults( ent, useF_beacon_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_beacon_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; - //G_SoundIndex("sound/weapons/overchargeend"); + // G_SoundIndex("sound/weapons/overchargeend"); - ent->s.modelindex = G_ModelIndex("models/map_objects/wedge/beacon.md3"); // Precache model - ent->s.modelindex2 = G_ModelIndex("models/map_objects/wedge/beacon.md3"); // Precache model + ent->s.modelindex = G_ModelIndex("models/map_objects/wedge/beacon.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("models/map_objects/wedge/beacon.md3"); // Precache model ent->noise_index = G_SoundIndex("sound/interface/ammocon_run"); // If we have a targetname, we're are invisible until we are spawned in by being used. - if ( ent->targetname ) - { + if (ent->targetname) { ent->s.eFlags = EF_NODRAW; ent->contents = 0; ent->s.loopSound = 0; ent->count = 0; - } - else - { + } else { ent->count = 1; - beacon_deploy( ent ); + beacon_deploy(ent); } int forceVisible = 0; - G_SpawnInt( "forcevisible", "0", &forceVisible ); - if ( forceVisible ) - {//can see these through walls with force sight, so must be broadcast - //ent->svFlags |= SVF_BROADCAST; + G_SpawnInt("forcevisible", "0", &forceVisible); + if (forceVisible) { // can see these through walls with force sight, so must be broadcast + // ent->svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_FORCE_VISIBLE; } } @@ -2312,12 +2033,11 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_shield_floor_unit( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 32 ); +void SP_misc_shield_floor_unit(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 32); - SetMiscModelDefaults( ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2327,32 +2047,28 @@ void SP_misc_shield_floor_unit( gentity_t *ent ) G_SoundIndex("sound/interface/shieldcon_done.mp3"); G_SoundIndex("sound/interface/shieldcon_empty.mp3"); - ent->s.modelindex = G_ModelIndex( "models/items/a_shield_converter.md3" ); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/a_shield_converter.md3"); // Precache model ent->s.eFlags |= EF_SHADER_ANIM; } - /* ================ EnergyAmmoShieldStationSettings ================ */ -void EnergyAmmoStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void EnergyAmmoStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } @@ -2362,8 +2078,7 @@ void EnergyAmmoStationSettings(gentity_t *ent) // There has to be an easier way to turn off the looping sound...but // it's the night before beta and my brain is fried //------------------------------------------------------------------ -void poll_converter( gentity_t *self ) -{ +void poll_converter(gentity_t *self) { self->s.loopSound = 0; self->nextthink = 0; self->e_ThinkFunc = thinkF_NULL; @@ -2374,105 +2089,84 @@ void poll_converter( gentity_t *self ) ammo_power_converter_use ================ */ -void ammo_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int add; - int difBlaster,difPowerCell,difMetalBolts; +void ammo_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int add; + int difBlaster, difPowerCell, difMetalBolts; playerState_t *ps; - if ( !activator || activator->s.number != 0 ) - {//only the player gets to use these + if (!activator || activator->s.number != 0) { // only the player gets to use these return; } - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); ps = &activator->client->ps; - if ( self->setTime < level.time ) - { - difBlaster = ammoData[AMMO_BLASTER].max - ps->ammo[AMMO_BLASTER]; - difPowerCell = ammoData[AMMO_POWERCELL].max - ps->ammo[AMMO_POWERCELL]; - difMetalBolts = ammoData[AMMO_METAL_BOLTS].max - ps->ammo[AMMO_METAL_BOLTS]; + if (self->setTime < level.time) { + difBlaster = ammoData[AMMO_BLASTER].max - ps->ammo[AMMO_BLASTER]; + difPowerCell = ammoData[AMMO_POWERCELL].max - ps->ammo[AMMO_POWERCELL]; + difMetalBolts = ammoData[AMMO_METAL_BOLTS].max - ps->ammo[AMMO_METAL_BOLTS]; // Has it got any power left...and can we even use any of it? - if ( self->count && ( difBlaster > 0 || difPowerCell > 0 || difMetalBolts > 0 )) - { + if (self->count && (difBlaster > 0 || difPowerCell > 0 || difMetalBolts > 0)) { // at least one of the ammo types could stand to take on a bit more ammo self->setTime = level.time + 100; - self->s.loopSound = G_SoundIndex( "sound/interface/ammocon_run.wav" ); + self->s.loopSound = G_SoundIndex("sound/interface/ammocon_run.wav"); // dole out ammo in little packets - if ( self->count > MAX_AMMO_GIVE ) - { + if (self->count > MAX_AMMO_GIVE) { add = MAX_AMMO_GIVE; - } - else if ( self->count < 0 ) - { + } else if (self->count < 0) { add = 0; - } - else - { + } else { add = self->count; } // all weapons fill at same rate... - ps->ammo[AMMO_BLASTER] += add; - ps->ammo[AMMO_POWERCELL] += add; - ps->ammo[AMMO_METAL_BOLTS] += add; + ps->ammo[AMMO_BLASTER] += add; + ps->ammo[AMMO_POWERCELL] += add; + ps->ammo[AMMO_METAL_BOLTS] += add; // ...then get clamped to max - if ( ps->ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max ) - { + if (ps->ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max) { ps->ammo[AMMO_BLASTER] = ammoData[AMMO_BLASTER].max; } - if ( ps->ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) - { + if (ps->ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) { ps->ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; } - if ( ps->ammo[AMMO_METAL_BOLTS] > ammoData[AMMO_METAL_BOLTS].max ) - { + if (ps->ammo[AMMO_METAL_BOLTS] > ammoData[AMMO_METAL_BOLTS].max) { ps->ammo[AMMO_METAL_BOLTS] = ammoData[AMMO_METAL_BOLTS].max; } self->count -= add; } - if ( self->count <= 0 ) - { + if (self->count <= 0) { // play empty sound self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much - G_Sound( self, G_SoundIndex( "sound/interface/ammocon_empty.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/ammocon_empty.mp3")); self->s.loopSound = 0; - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 1; } - } - else if ( ps->ammo[AMMO_BLASTER] >= ammoData[AMMO_BLASTER].max - && ps->ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max - && ps->ammo[AMMO_METAL_BOLTS] >= ammoData[AMMO_METAL_BOLTS].max ) - { + } else if (ps->ammo[AMMO_BLASTER] >= ammoData[AMMO_BLASTER].max && ps->ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max && + ps->ammo[AMMO_METAL_BOLTS] >= ammoData[AMMO_METAL_BOLTS].max) { // play full sound - G_Sound( self, G_SoundIndex( "sound/interface/ammocon_done.wav" )); + G_Sound(self, G_SoundIndex("sound/interface/ammocon_done.wav")); self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much self->s.loopSound = 0; } } - - if ( self->s.loopSound ) - { + if (self->s.loopSound) { // we will have to shut of the loop sound, so I guess try and do it intelligently...NOTE: this could get completely stomped every time through the loop // this is fine, since it just controls shutting off the sound when there are situations that could start the sound but not shut it off self->e_ThinkFunc = thinkF_poll_converter; self->nextthink = level.time + 500; - } - else - { + } else { // sound is already off, so we don't need to "think" about it. self->e_ThinkFunc = thinkF_NULL; self->nextthink = 0; @@ -2492,9 +2186,8 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_model_ammo_power_converter( gentity_t *ent ) -{ - SetMiscModelDefaults( ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); +void SP_misc_model_ammo_power_converter(gentity_t *ent) { + SetMiscModelDefaults(ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2504,8 +2197,8 @@ void SP_misc_model_ammo_power_converter( gentity_t *ent ) G_SoundIndex("sound/interface/ammocon_done.mp3"); G_SoundIndex("sound/interface/ammocon_empty.mp3"); - ent->s.modelindex = G_ModelIndex("models/items/power_converter.md3"); // Precache model - ent->s.modelindex2 = G_ModelIndex("models/items/power_converter.md3"); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/power_converter.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("models/items/power_converter.md3"); // Precache model } /*QUAKED misc_ammo_floor_unit (1 0 0) (-16 -16 0) (16 16 32) x x x USETARGET @@ -2521,12 +2214,11 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_ammo_floor_unit( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 32 ); +void SP_misc_ammo_floor_unit(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 32); - SetMiscModelDefaults( ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2536,51 +2228,44 @@ void SP_misc_ammo_floor_unit( gentity_t *ent ) G_SoundIndex("sound/interface/ammocon_done.mp3"); G_SoundIndex("sound/interface/ammocon_empty.mp3"); - ent->s.modelindex = G_ModelIndex("models/items/a_pwr_converter.md3"); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/a_pwr_converter.md3"); // Precache model ent->s.eFlags |= EF_SHADER_ANIM; } - /* ================ welder_think ================ */ -void welder_think( gentity_t *self ) -{ +void welder_think(gentity_t *self) { self->nextthink = level.time + 200; - vec3_t org, - dir; - mdxaBone_t boltMatrix; + vec3_t org, dir; + mdxaBone_t boltMatrix; - if( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; } int newBolt; // could alternate between the two... or make it random... ? - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash" ); -// newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash01" ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash"); + // newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash01" ); - if ( newBolt != -1 ) - { - G_Sound( self, self->noise_index ); - // G_PlayEffect( "blueWeldSparks", self->playerModel, newBolt, self->s.number); + if (newBolt != -1) { + G_Sound(self, self->noise_index); + // G_PlayEffect( "blueWeldSparks", self->playerModel, newBolt, self->s.number); // The welder gets rotated around a lot, and since the origin is offset by 352 I have to make this super expensive call to position the hurt... - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, newBolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, newBolt, &boltMatrix, self->currentAngles, self->currentOrigin, + (cg.time ? cg.time : level.time), NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - VectorSubtract( self->currentOrigin, org, dir ); - VectorNormalize( dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + VectorSubtract(self->currentOrigin, org, dir); + VectorNormalize(dir); // we want the welder effect to face inwards.... - G_PlayEffect( "sparks/blueWeldSparks", org, dir ); - G_RadiusDamage( org, self, 10, 45, self, MOD_UNKNOWN ); + G_PlayEffect("sparks/blueWeldSparks", org, dir); + G_RadiusDamage(org, self, 10, 45, self, MOD_UNKNOWN); } - } /* @@ -2588,19 +2273,14 @@ void welder_think( gentity_t *self ) welder_use ================ */ -void welder_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void welder_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle on and off - if( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->nextthink = -1; } self->spawnflags = (self->spawnflags ^ 1); - } /*QUAKED misc_model_welder (1 0 0) (-16 -16 -16) (16 16 16) START_OFF @@ -2611,50 +2291,45 @@ START_OFF - welder starts off, using it toggles it on/off */ //------------------------------------------------------------ -void SP_misc_model_welder( gentity_t *ent ) -{ - VectorSet( ent->mins, 336, -16, 0 ); - VectorSet( ent->maxs, 368, 16, 32 ); +void SP_misc_model_welder(gentity_t *ent) { + VectorSet(ent->mins, 336, -16, 0); + VectorSet(ent->maxs, 368, 16, 32); - SetMiscModelDefaults( ent, useF_welder_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_welder_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; ent->contents = 0; - G_EffectIndex( "sparks/blueWeldSparks" ); - ent->noise_index = G_SoundIndex( "sound/movers/objects/welding.wav" ); + G_EffectIndex("sparks/blueWeldSparks"); + ent->noise_index = G_SoundIndex("sound/movers/objects/welding.wav"); - ent->s.modelindex = G_ModelIndex( "models/map_objects/cairn/welder.glm" ); -// ent->s.modelindex2 = G_ModelIndex( "models/map_objects/cairn/welder.md3" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/map_objects/cairn/welder.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->s.radius = 400.0f;// the origin of the welder is offset by approximately 352, so we need the big radius + ent->s.modelindex = G_ModelIndex("models/map_objects/cairn/welder.glm"); + // ent->s.modelindex2 = G_ModelIndex( "models/map_objects/cairn/welder.md3" ); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, "models/map_objects/cairn/welder.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->s.radius = 400.0f; // the origin of the welder is offset by approximately 352, so we need the big radius ent->e_ThinkFunc = thinkF_welder_think; ent->nextthink = level.time + 1000; - if( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { ent->nextthink = -1; } } - /* ================ jabba_cam_use ================ */ -void jabba_cam_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if( self->spawnflags & 1 ) - { +void jabba_cam_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->spawnflags & 1) { self->spawnflags &= ~1; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 15, 0, BONE_ANIM_OVERRIDE_FREEZE, -1.5f, (cg.time?cg.time:level.time), -1, 0 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 15, 0, BONE_ANIM_OVERRIDE_FREEZE, -1.5f, (cg.time ? cg.time : level.time), + -1, 0); - } - else - { + } else { self->spawnflags |= 1; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 1.5f, (cg.time?cg.time:level.time), -1, 0 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 1.5f, (cg.time ? cg.time : level.time), + -1, 0); } } @@ -2669,41 +2344,38 @@ The eye camera that popped out of Jabba's front door */ //----------------------------------------------------- -void SP_misc_model_jabba_cam( gentity_t *ent ) +void SP_misc_model_jabba_cam(gentity_t *ent) //----------------------------------------------------- { - VectorSet( ent->mins, -60.0f, -8.0f, 0.0f ); - VectorSet( ent->maxs, 60.0f, 8.0f, 16.0f ); + VectorSet(ent->mins, -60.0f, -8.0f, 0.0f); + VectorSet(ent->maxs, 60.0f, 8.0f, 16.0f); - SetMiscModelDefaults( ent, useF_jabba_cam_use, "4", 0, 0, qfalse, qfalse ); - G_SetAngles( ent, ent->s.angles ); + SetMiscModelDefaults(ent, useF_jabba_cam_use, "4", 0, 0, qfalse, qfalse); + G_SetAngles(ent, ent->s.angles); - ent->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/jabacam/jabacam.glm" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/map_objects/nar_shaddar/jabacam/jabacam.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->s.radius = 150.0f; //...... - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); + ent->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/jabacam/jabacam.glm"); + ent->playerModel = + gi.G2API_InitGhoul2Model(ent->ghoul2, "models/map_objects/nar_shaddar/jabacam/jabacam.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->s.radius = 150.0f; //...... + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); ent->e_UseFunc = useF_jabba_cam_use; ent->takedamage = qfalse; // start extended.. - if ( ent->spawnflags & 1 ) - { - gi.G2API_SetBoneAnimIndex( &ent->ghoul2[ent->playerModel], ent->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); + if (ent->spawnflags & 1) { + gi.G2API_SetBoneAnimIndex(&ent->ghoul2[ent->playerModel], ent->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1); } - gi.linkentity( ent ); + gi.linkentity(ent); } //------------------------------------------------------------------------ -void misc_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - misc_model_breakable_die( self, other, activator, 100, MOD_UNKNOWN ); -} +void misc_use(gentity_t *self, gentity_t *other, gentity_t *activator) { misc_model_breakable_die(self, other, activator, 100, MOD_UNKNOWN); } /*QUAKED misc_exploding_crate (1 0 0.25) (-24 -24 0) (24 24 64) model="models/map_objects/nar_shaddar/crate_xplode.md3" @@ -2719,33 +2391,31 @@ Basic exploding crate */ //------------------------------------------------------------ -void SP_misc_exploding_crate( gentity_t *ent ) -{ - G_SpawnInt( "health", "40", &ent->health ); - G_SpawnInt( "splashRadius", "128", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "50", &ent->splashDamage ); +void SP_misc_exploding_crate(gentity_t *ent) { + G_SpawnInt("health", "40", &ent->health); + G_SpawnInt("splashRadius", "128", &ent->splashRadius); + G_SpawnInt("splashDamage", "50", &ent->splashDamage); - ent->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/crate_xplode.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/crate_xplode.md3"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/metalexplode"); - VectorSet( ent->mins, -24, -24, 0 ); - VectorSet( ent->maxs, 24, 24, 64 ); + VectorSet(ent->mins, -24, -24, 0); + VectorSet(ent->maxs, 24, 24, 64); - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//CONTENTS_SOLID; + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // CONTENTS_SOLID; ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } ent->material = MAT_CRATE1; - ent->e_DieFunc = dieF_misc_model_breakable_die;//ExplodeDeath; + ent->e_DieFunc = dieF_misc_model_breakable_die; // ExplodeDeath; } /*QUAKED misc_gas_tank (1 0 0.25) (-4 -4 0) (4 4 40) @@ -2762,63 +2432,59 @@ Basic exploding oxygen tank */ -void gas_random_jet( gentity_t *self ) -{ +void gas_random_jet(gentity_t *self) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 50; - G_PlayEffect( "env/mini_gasjet", pt ); + G_PlayEffect("env/mini_gasjet", pt); self->nextthink = level.time + Q_flrand(0.0f, 1.0f) * 16000 + 12000; // do this rarely } //------------------------------------------------------------ -void GasBurst( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc ) -{ +void GasBurst(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 46; - G_PlayEffect( "env/mini_flamejet", pt ); + G_PlayEffect("env/mini_flamejet", pt); // do some damage to anything that may be standing on top of it when it bursts into flame pt[2] += 32; - G_RadiusDamage( pt, self, 32, 32, self, MOD_UNKNOWN ); + G_RadiusDamage(pt, self, 32, 32, self, MOD_UNKNOWN); // only get one burst self->e_PainFunc = painF_NULL; } //------------------------------------------------------------ -void SP_misc_gas_tank( gentity_t *ent ) -{ - G_SpawnInt( "health", "20", &ent->health ); - G_SpawnInt( "splashRadius", "48", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "32", &ent->splashDamage ); +void SP_misc_gas_tank(gentity_t *ent) { + G_SpawnInt("health", "20", &ent->health); + G_SpawnInt("splashRadius", "48", &ent->splashRadius); + G_SpawnInt("splashDamage", "32", &ent->splashDamage); - ent->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/tank.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/tank.md3"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - G_EffectIndex( "chunks/metalexplode" ); - G_EffectIndex( "env/mini_flamejet" ); - G_EffectIndex( "env/mini_gasjet" ); + G_EffectIndex("chunks/metalexplode"); + G_EffectIndex("env/mini_flamejet"); + G_EffectIndex("env/mini_gasjet"); - VectorSet( ent->mins, -4, -4, 0 ); - VectorSet( ent->maxs, 4, 4, 40 ); + VectorSet(ent->mins, -4, -4, 0); + VectorSet(ent->maxs, 4, 4, 40); ent->contents = CONTENTS_SOLID; ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); ent->e_PainFunc = painF_GasBurst; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } @@ -2847,56 +2513,52 @@ NON_SOLID - can only be shot */ //------------------------------------------------------------ -void CrystalCratePain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc ) -{ +void CrystalCratePain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 36; - G_PlayEffect( "env/crystal_crate", pt ); + G_PlayEffect("env/crystal_crate", pt); // do some damage, heh pt[2] += 32; - G_RadiusDamage( pt, self, 16, 32, self, MOD_UNKNOWN ); - + G_RadiusDamage(pt, self, 16, 32, self, MOD_UNKNOWN); } //------------------------------------------------------------ -void SP_misc_crystal_crate( gentity_t *ent ) -{ - G_SpawnInt( "health", "80", &ent->health ); - G_SpawnInt( "splashRadius", "80", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "40", &ent->splashDamage ); - - ent->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/crate_open.md3" ); - ent->fxID = G_EffectIndex( "thermal/explosion" ); // FIXME: temp - G_EffectIndex( "env/crystal_crate" ); +void SP_misc_crystal_crate(gentity_t *ent) { + G_SpawnInt("health", "80", &ent->health); + G_SpawnInt("splashRadius", "80", &ent->splashRadius); + G_SpawnInt("splashDamage", "40", &ent->splashDamage); + + ent->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/crate_open.md3"); + ent->fxID = G_EffectIndex("thermal/explosion"); // FIXME: temp + G_EffectIndex("env/crystal_crate"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - VectorSet( ent->mins, -34, -34, 0 ); - VectorSet( ent->maxs, 34, 34, 44 ); + VectorSet(ent->mins, -34, -34, 0); + VectorSet(ent->maxs, 34, 34, 44); - //Blocks movement - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//Was CONTENTS_SOLID, but only architecture should be this + // Blocks movement + ent->contents = + CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // Was CONTENTS_SOLID, but only architecture should be this - if ( ent->spawnflags & 1 ) // non-solid - { // Override earlier contents flag... - //Can only be shot + if (ent->spawnflags & 1) // non-solid + { // Override earlier contents flag... + // Can only be shot ent->contents = CONTENTS_SHOTCLIP; } - ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); ent->e_PainFunc = painF_CrystalCratePain; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } @@ -2914,247 +2576,221 @@ Drivable ATST, when used by player, they become the ATST. When the player hits "target" - what to use when it dies */ -void misc_atst_setanim( gentity_t *self, int bone, int anim ) -{ - if ( bone < 0 || anim < 0 ) - { +void misc_atst_setanim(gentity_t *self, int bone, int anim) { + if (bone < 0 || anim < 0) { return; } - int firstFrame = -1; - int lastFrame = -1; + int firstFrame = -1; + int lastFrame = -1; float animSpeed = 0; - //try to get anim ranges from the animation.cfg for an AT-ST - for ( int i = 0; i < level.numKnownAnimFileSets; i++ ) - { - if ( !Q_stricmp( "atst", level.knownAnimFileSets[i].filename ) ) - { + // try to get anim ranges from the animation.cfg for an AT-ST + for (int i = 0; i < level.numKnownAnimFileSets; i++) { + if (!Q_stricmp("atst", level.knownAnimFileSets[i].filename)) { firstFrame = level.knownAnimFileSets[i].animations[anim].firstFrame; - lastFrame = firstFrame+level.knownAnimFileSets[i].animations[anim].numFrames; + lastFrame = firstFrame + level.knownAnimFileSets[i].animations[anim].numFrames; animSpeed = 50.0f / level.knownAnimFileSets[i].animations[anim].frameLerp; break; } } - if ( firstFrame != -1 && lastFrame != -1 && animSpeed != 0 ) - { - if (!gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], bone, firstFrame, - lastFrame, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, animSpeed, - (cg.time?cg.time:level.time), -1, 150 )) - { - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], bone, firstFrame, - lastFrame, BONE_ANIM_OVERRIDE_FREEZE, animSpeed, - (cg.time?cg.time:level.time), -1, 150 ); + if (firstFrame != -1 && lastFrame != -1 && animSpeed != 0) { + if (!gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], bone, firstFrame, lastFrame, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, + (cg.time ? cg.time : level.time), -1, 150)) { + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], bone, firstFrame, lastFrame, BONE_ANIM_OVERRIDE_FREEZE, animSpeed, + (cg.time ? cg.time : level.time), -1, 150); } } } -void misc_atst_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{//ATST was destroyed while you weren't in it - //can't be used anymore +void misc_atst_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, + int hitLoc) { // ATST was destroyed while you weren't in it + // can't be used anymore self->e_UseFunc = useF_NULL; - //sigh... remove contents so we don't block the player's path... + // sigh... remove contents so we don't block the player's path... self->contents = CONTENTS_CORPSE; self->takedamage = qfalse; self->maxs[2] = 48; - //FIXME: match to slope + // FIXME: match to slope vec3_t effectPos; - VectorCopy( self->currentOrigin, effectPos ); + VectorCopy(self->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "explosions/droidexplosion1", effectPos ); -// G_PlayEffect( "small_chunks", effectPos ); - //set these to defaults that work in a worst-case scenario (according to current animation.cfg) - gi.G2API_StopBoneAnimIndex( &self->ghoul2[self->playerModel], self->craniumBone ); - misc_atst_setanim( self, self->rootBone, BOTH_DEATH1 ); -} - -extern void G_DriveATST( gentity_t *ent, gentity_t *atst ); -extern void SetClientViewAngle( gentity_t *ent, vec3_t angle ); -extern qboolean PM_InSlopeAnim( int anim ); -void misc_atst_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator || activator->s.number ) - {//only player can do this + G_PlayEffect("explosions/droidexplosion1", effectPos); + // G_PlayEffect( "small_chunks", effectPos ); + // set these to defaults that work in a worst-case scenario (according to current animation.cfg) + gi.G2API_StopBoneAnimIndex(&self->ghoul2[self->playerModel], self->craniumBone); + misc_atst_setanim(self, self->rootBone, BOTH_DEATH1); +} + +extern void G_DriveATST(gentity_t *ent, gentity_t *atst); +extern void SetClientViewAngle(gentity_t *ent, vec3_t angle); +extern qboolean PM_InSlopeAnim(int anim); +void misc_atst_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || activator->s.number) { // only player can do this return; } - int tempLocDmg[HL_MAX]; - int hl, tempHealth; + int tempLocDmg[HL_MAX]; + int hl, tempHealth; - if ( activator->client->NPC_class != CLASS_ATST ) - {//get in the ATST - if ( activator->client->ps.groundEntityNum != self->s.number ) - {//can only get in if on top of me... - //we *could* even check for the hatch surf...? + if (activator->client->NPC_class != CLASS_ATST) { // get in the ATST + if (activator->client->ps.groundEntityNum != self->s.number) { // can only get in if on top of me... + // we *could* even check for the hatch surf...? return; } - //copy origin - G_SetOrigin( activator, self->currentOrigin ); + // copy origin + G_SetOrigin(activator, self->currentOrigin); - //copy angles - VectorCopy( self->s.angles2, self->currentAngles ); - G_SetAngles( activator, self->currentAngles ); - SetClientViewAngle( activator, self->currentAngles ); + // copy angles + VectorCopy(self->s.angles2, self->currentAngles); + G_SetAngles(activator, self->currentAngles); + SetClientViewAngle(activator, self->currentAngles); - //set player to my g2 instance - gi.G2API_StopBoneAnimIndex( &self->ghoul2[self->playerModel], self->craniumBone ); - G_DriveATST( activator, self ); + // set player to my g2 instance + gi.G2API_StopBoneAnimIndex(&self->ghoul2[self->playerModel], self->craniumBone); + G_DriveATST(activator, self); activator->activator = self; self->s.eFlags |= EF_NODRAW; self->svFlags |= SVF_NOCLIENT; self->contents = 0; self->takedamage = qfalse; - //transfer armor + // transfer armor tempHealth = self->health; self->health = activator->client->ps.stats[STAT_ARMOR]; activator->client->ps.stats[STAT_ARMOR] = tempHealth; - //transfer locationDamage - for ( hl = HL_NONE; hl < HL_MAX; hl++ ) - { + // transfer locationDamage + for (hl = HL_NONE; hl < HL_MAX; hl++) { tempLocDmg[hl] = activator->locationDamage[hl]; activator->locationDamage[hl] = self->locationDamage[hl]; self->locationDamage[hl] = tempLocDmg[hl]; } - if ( !self->s.number ) - { - CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + if (!self->s.number) { + CG_CenterPrint("@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } - } - else - {//get out of ATST + } else { // get out of ATST int legsAnim = activator->client->ps.legsAnim; - if ( legsAnim != BOTH_STAND1 - && !PM_InSlopeAnim( legsAnim ) - && legsAnim != BOTH_TURN_RIGHT1 && legsAnim != BOTH_TURN_LEFT1 ) - {//can't get out of it while it's still moving + if (legsAnim != BOTH_STAND1 && !PM_InSlopeAnim(legsAnim) && legsAnim != BOTH_TURN_RIGHT1 && + legsAnim != BOTH_TURN_LEFT1) { // can't get out of it while it's still moving return; } - //FIXME: after a load/save, this crashes, BAD... somewhere in G2 - G_SetOrigin( self, activator->currentOrigin ); - VectorSet( self->currentAngles, 0, activator->client->ps.legsYaw, 0 ); - //self->currentAngles[PITCH] = activator->currentAngles[ROLL] = 0; - G_SetAngles( self, self->currentAngles ); - VectorCopy( activator->currentAngles, self->s.angles2 ); - //remove my G2 - if ( self->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->playerModel ); + // FIXME: after a load/save, this crashes, BAD... somewhere in G2 + G_SetOrigin(self, activator->currentOrigin); + VectorSet(self->currentAngles, 0, activator->client->ps.legsYaw, 0); + // self->currentAngles[PITCH] = activator->currentAngles[ROLL] = 0; + G_SetAngles(self, self->currentAngles); + VectorCopy(activator->currentAngles, self->s.angles2); + // remove my G2 + if (self->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->playerModel); self->playerModel = -1; } - //copy player's - gi.G2API_CopyGhoul2Instance( activator->ghoul2, self->ghoul2, -1 ); - self->playerModel = 0;//assumption - //reset player to kyle - G_DriveATST( activator, NULL ); + // copy player's + gi.G2API_CopyGhoul2Instance(activator->ghoul2, self->ghoul2, -1); + self->playerModel = 0; // assumption + // reset player to kyle + G_DriveATST(activator, NULL); activator->activator = NULL; self->s.eFlags &= ~EF_NODRAW; self->svFlags &= ~SVF_NOCLIENT; - self->contents = CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + self->contents = CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; self->takedamage = qtrue; - //transfer armor + // transfer armor tempHealth = self->health; self->health = activator->client->ps.stats[STAT_ARMOR]; activator->client->ps.stats[STAT_ARMOR] = tempHealth; - //transfer locationDamage - for ( hl = HL_NONE; hl < HL_MAX; hl++ ) - { + // transfer locationDamage + for (hl = HL_NONE; hl < HL_MAX; hl++) { tempLocDmg[hl] = self->locationDamage[hl]; self->locationDamage[hl] = activator->locationDamage[hl]; activator->locationDamage[hl] = tempLocDmg[hl]; } - //link me back in - gi.linkentity ( self ); - //put activator on top of me? - vec3_t newOrg = {activator->currentOrigin[0], activator->currentOrigin[1], activator->currentOrigin[2] + (self->maxs[2]-self->mins[2]) + 1 }; - G_SetOrigin( activator, newOrg ); - //open the hatch - misc_atst_setanim( self, self->craniumBone, BOTH_STAND2 ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_hatchcover", 0 ); - G_Sound( self, G_SoundIndex( "sound/chars/atst/atst_hatch_open" )); + // link me back in + gi.linkentity(self); + // put activator on top of me? + vec3_t newOrg = {activator->currentOrigin[0], activator->currentOrigin[1], activator->currentOrigin[2] + (self->maxs[2] - self->mins[2]) + 1}; + G_SetOrigin(activator, newOrg); + // open the hatch + misc_atst_setanim(self, self->craniumBone, BOTH_STAND2); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_hatchcover", 0); + G_Sound(self, G_SoundIndex("sound/chars/atst/atst_hatch_open")); } } -void SP_misc_atst_drivable( gentity_t *ent ) -{ +void SP_misc_atst_drivable(gentity_t *ent) { extern void NPC_ATST_Precache(void); - extern void NPC_PrecacheAnimationCFG( const char *NPC_type ); - - ent->s.modelindex = G_ModelIndex( "models/players/atst/model.glm" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/players/atst/model.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); //FIXME: need to somehow set the anim/frame to the equivalent of BOTH_STAND1... use to be that BOTH_STAND1 was the first frame of the glm, but not anymore + extern void NPC_PrecacheAnimationCFG(const char *NPC_type); + + ent->s.modelindex = G_ModelIndex("models/players/atst/model.glm"); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, "models/players/atst/model.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", + qtrue); // FIXME: need to somehow set the anim/frame to the equivalent of BOTH_STAND1... use to be that + // BOTH_STAND1 was the first frame of the glm, but not anymore ent->s.radius = 320; - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); - //register my weapons, sounds and model - RegisterItem( FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_ATST_SIDE )); //precache the weapon - //HACKHACKHACKTEMP - until ATST gets real weapons of it's own? - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); //precache the weapon -// RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon -// RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon - //HACKHACKHACKTEMP - until ATST gets real weapons of it's own? + // register my weapons, sounds and model + RegisterItem(FindItemForWeapon(WP_ATST_MAIN)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_ATST_SIDE)); // precache the weapon + // HACKHACKHACKTEMP - until ATST gets real weapons of it's own? + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); // precache the weapon + // RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon + // RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon + // HACKHACKHACKTEMP - until ATST gets real weapons of it's own? - G_SoundIndex( "sound/chars/atst/atst_hatch_open" ); - G_SoundIndex( "sound/chars/atst/atst_hatch_close" ); + G_SoundIndex("sound/chars/atst/atst_hatch_open"); + G_SoundIndex("sound/chars/atst/atst_hatch_close"); NPC_ATST_Precache(); ent->NPC_type = (char *)"atst"; - NPC_PrecacheAnimationCFG( ent->NPC_type ); - //open the hatch - misc_atst_setanim( ent, ent->rootBone, BOTH_STAND2 ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "head_hatchcover", 0 ); + NPC_PrecacheAnimationCFG(ent->NPC_type); + // open the hatch + misc_atst_setanim(ent, ent->rootBone, BOTH_STAND2); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "head_hatchcover", 0); - VectorSet( ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2 ); - VectorSet( ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2 ); + VectorSet(ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2); + VectorSet(ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2); - ent->contents = CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + ent->contents = CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; ent->flags |= FL_SHIELDED; ent->takedamage = qtrue; - if ( !ent->health ) - { + if (!ent->health) { ent->health = 800; } ent->s.radius = 320; ent->max_health = ent->health; // cg_draw needs this - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - VectorCopy( ent->currentAngles, ent->s.angles2 ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + VectorCopy(ent->currentAngles, ent->s.angles2); - gi.linkentity ( ent ); + gi.linkentity(ent); - //FIXME: test the origin to make sure I'm clear? + // FIXME: test the origin to make sure I'm clear? ent->e_UseFunc = useF_misc_atst_use; ent->svFlags |= SVF_PLAYER_USABLE; - //make it able to take damage and die when you're not in it... - //do an explosion and play the death anim, remove use func. + // make it able to take damage and die when you're not in it... + // do an explosion and play the death anim, remove use func. ent->e_DieFunc = dieF_misc_atst_die; } -extern int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ); +extern int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create); /*QUAKED misc_weather_zone (0 .5 .8) ? Determines a region to check for weather contents - (optional, used to reduce load times) Place surrounding your inside/outside brushes. It will not check for weather contents outside of these zones. */ -void SP_misc_weather_zone( gentity_t *ent ) -{ +void SP_misc_weather_zone(gentity_t *ent) { gi.SetBrushModel(ent, ent->model); - char temp[256]; - sprintf( temp, "zone ( %f %f %f ) ( %f %f %f )", - ent->mins[0], ent->mins[1], ent->mins[2], - ent->maxs[0], ent->maxs[1], ent->maxs[2] ); + char temp[256]; + sprintf(temp, "zone ( %f %f %f ) ( %f %f %f )", ent->mins[0], ent->mins[1], ent->mins[2], ent->maxs[0], ent->maxs[1], ent->maxs[2]); G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); -// gi.WE_AddWeatherZone(ent->mins, ent->maxs); + // gi.WE_AddWeatherZone(ent->mins, ent->maxs); G_FreeEntity(ent); } -void SP_misc_cubemap( gentity_t *ent ) -{ - G_FreeEntity( ent ); -} +void SP_misc_cubemap(gentity_t *ent) { G_FreeEntity(ent); } diff --git a/code/game/g_misc_model.cpp b/code/game/g_misc_model.cpp index e73d224bf2..0858b03704 100644 --- a/code/game/g_misc_model.cpp +++ b/code/game/g_misc_model.cpp @@ -30,118 +30,106 @@ extern cvar_t *g_spskill; // Helper functions // //------------------------------------------------------------ -void SetMiscModelModels( char *modelNameString, gentity_t *ent, qboolean damage_model ) -{ - char damageModel[MAX_QPATH]; - char chunkModel[MAX_QPATH]; - int len; +void SetMiscModelModels(char *modelNameString, gentity_t *ent, qboolean damage_model) { + char damageModel[MAX_QPATH]; + char chunkModel[MAX_QPATH]; + int len; - //Main model - ent->s.modelindex = G_ModelIndex( modelNameString ); + // Main model + ent->s.modelindex = G_ModelIndex(modelNameString); - if ( damage_model ) - { - len = strlen( modelNameString ) - 4; // extract the extension + if (damage_model) { + len = strlen(modelNameString) - 4; // extract the extension - //Dead/damaged model - strncpy( damageModel, modelNameString, len ); + // Dead/damaged model + strncpy(damageModel, modelNameString, len); damageModel[len] = 0; - strncpy( chunkModel, damageModel, sizeof(chunkModel)); - strcat( damageModel, "_d1.md3" ); - ent->s.modelindex2 = G_ModelIndex( damageModel ); + strncpy(chunkModel, damageModel, sizeof(chunkModel)); + strcat(damageModel, "_d1.md3"); + ent->s.modelindex2 = G_ModelIndex(damageModel); ent->spawnflags |= 4; // deadsolid - //Chunk model - strcat( chunkModel, "_c1.md3" ); - ent->s.modelindex3 = G_ModelIndex( chunkModel ); + // Chunk model + strcat(chunkModel, "_c1.md3"); + ent->s.modelindex3 = G_ModelIndex(chunkModel); } } //------------------------------------------------------------ -void SetMiscModelDefaults( gentity_t *ent, useFunc_t use_func, const char *material, int solid_mask,int animFlag, - qboolean take_damage, qboolean damage_model = qfalse ) -{ +void SetMiscModelDefaults(gentity_t *ent, useFunc_t use_func, const char *material, int solid_mask, int animFlag, qboolean take_damage, + qboolean damage_model = qfalse) { // Apply damage and chunk models if they exist - SetMiscModelModels( ent->model, ent, damage_model ); + SetMiscModelModels(ent->model, ent, damage_model); ent->s.eFlags = animFlag; ent->svFlags |= SVF_PLAYER_USABLE; ent->contents = solid_mask; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); // Set a generic use function ent->e_UseFunc = use_func; -/* if (use_func == useF_health_use) - { - G_SoundIndex("sound/player/suithealth.wav"); - } - else if (use_func == useF_ammo_use ) - { - G_SoundIndex("sound/player/suitenergy.wav"); - } -*/ - G_SpawnInt( "material", material, (int *)&ent->material ); + /* if (use_func == useF_health_use) + { + G_SoundIndex("sound/player/suithealth.wav"); + } + else if (use_func == useF_ammo_use ) + { + G_SoundIndex("sound/player/suitenergy.wav"); + } + */ + G_SpawnInt("material", material, (int *)&ent->material); - if (ent->health) - { + if (ent->health) { ent->max_health = ent->health; ent->takedamage = take_damage; ent->e_PainFunc = painF_misc_model_breakable_pain; - ent->e_DieFunc = dieF_misc_model_breakable_die; + ent->e_DieFunc = dieF_misc_model_breakable_die; } } -void HealthStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void HealthStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } } } +void CrystalAmmoSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); -void CrystalAmmoSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); - - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 75; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 75; break; } } } - //------------------------------------------------------------ //------------------------------------------------------------ @@ -151,84 +139,74 @@ void CrystalAmmoSettings(gentity_t *ent) */ //------------------------------------------------------------ #include "anims.h" -extern int G_ParseAnimFileSet( const char *skeletonName, const char *modelName=0); +extern int G_ParseAnimFileSet(const char *skeletonName, const char *modelName = 0); int temp_animFileIndex; -void set_MiscAnim( gentity_t *ent) -{ +void set_MiscAnim(gentity_t *ent) { animation_t *animations = level.knownAnimFileSets[temp_animFileIndex].animations; - if (ent->playerModel & 1) - { + if (ent->playerModel & 1) { int anim = BOTH_STAND3; float animSpeed = 50.0f / animations[anim].frameLerp; // yes, its the same animation, so work out where we are in the leg anim, and blend us - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND , animSpeed, (cg.time?cg.time:level.time), -1, 350); - } - else - { + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time ? cg.time : level.time), -1, 350); + } else { int anim = BOTH_PAIN3; float animSpeed = 50.0f / animations[anim].frameLerp; - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time?cg.time:level.time), -1, 350); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time ? cg.time : level.time), -1, 350); } ent->nextthink = level.time + 900; ent->playerModel++; - } -void SP_misc_model_ghoul( gentity_t *ent ) -{ +void SP_misc_model_ghoul(gentity_t *ent) { #if 1 - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); gi.G2API_InitGhoul2Model(ent->ghoul2, ent->model, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); ent->s.radius = 50; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - qboolean bHasScale = G_SpawnVector( "modelscale_vec", "1 1 1", ent->s.modelScale ); - if ( !bHasScale ) { + qboolean bHasScale = G_SpawnVector("modelscale_vec", "1 1 1", ent->s.modelScale); + if (!bHasScale) { float temp; - G_SpawnFloat( "modelscale", "0", &temp ); - if ( temp != 0.0f ) { + G_SpawnFloat("modelscale", "0", &temp); + if (temp != 0.0f) { ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = temp; bHasScale = qtrue; } } - if ( bHasScale ) { - //scale the x axis of the bbox up. + if (bHasScale) { + // scale the x axis of the bbox up. ent->maxs[0] *= ent->s.modelScale[0]; ent->mins[0] *= ent->s.modelScale[0]; - //scale the y axis of the bbox up. + // scale the y axis of the bbox up. ent->maxs[1] *= ent->s.modelScale[1]; ent->mins[1] *= ent->s.modelScale[1]; - //scale the z axis of the bbox up and adjust origin accordingly + // scale the z axis of the bbox up and adjust origin accordingly ent->maxs[2] *= ent->s.modelScale[2]; float oldMins2 = ent->mins[2]; ent->mins[2] *= ent->s.modelScale[2]; ent->s.origin[2] += (oldMins2 - ent->mins[2]); } - gi.linkentity (ent); + gi.linkentity(ent); #else char name1[200] = "models/players/kyle/model.glm"; - ent->s.modelindex = G_ModelIndex( name1 ); + ent->s.modelindex = G_ModelIndex(name1); gi.G2API_InitGhoul2Model(ent->ghoul2, name1, ent->s.modelindex); ent->s.radius = 150; - // we found the model ok - load it's animation config + // we found the model ok - load it's animation config temp_animFileIndex = G_ParseAnimFileSet("_humanoid", "kyle"); - if ( temp_animFileIndex<0 ) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/jedi/animation.cfg\n"); - } - + if (temp_animFileIndex < 0) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/jedi/animation.cfg\n"); + } ent->s.angles[0] = 0; ent->s.angles[1] = 90; @@ -236,54 +214,51 @@ void SP_misc_model_ghoul( gentity_t *ent ) ent->s.origin[2] = 20; ent->s.origin[1] = 80; -// ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = 0.8f; - - VectorSet (ent->mins, -16, -16, -37); - VectorSet (ent->maxs, 16, 16, 32); -//#if _DEBUG -//loadsavecrash -// VectorCopy(ent->mins, ent->s.mins); -// VectorCopy(ent->maxs, ent->s.maxs); -//#endif + // ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = 0.8f; + + VectorSet(ent->mins, -16, -16, -37); + VectorSet(ent->maxs, 16, 16, 32); + //#if _DEBUG + // loadsavecrash + // VectorCopy(ent->mins, ent->s.mins); + // VectorCopy(ent->maxs, ent->s.maxs); + //#endif ent->contents = CONTENTS_BODY; ent->clipmask = MASK_NPCSOLID; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->health = 1000; -// ent->s.modelindex = G_ModelIndex( "models/weapons2/blaster_r/g2blaster_w.glm" ); -// gi.G2API_InitGhoul2Model(ent->ghoul2, "models/weapons2/blaster_r/g2blaster_w.glm", ent->s.modelindex); -// gi.G2API_AddBolt(&ent->ghoul2[0], "*weapon"); -// gi.G2API_AttachG2Model(&ent->ghoul2[1],&ent->ghoul2[0], 0, 0); + // ent->s.modelindex = G_ModelIndex( "models/weapons2/blaster_r/g2blaster_w.glm" ); + // gi.G2API_InitGhoul2Model(ent->ghoul2, "models/weapons2/blaster_r/g2blaster_w.glm", ent->s.modelindex); + // gi.G2API_AddBolt(&ent->ghoul2[0], "*weapon"); + // gi.G2API_AttachG2Model(&ent->ghoul2[1],&ent->ghoul2[0], 0, 0); - gi.linkentity (ent); + gi.linkentity(ent); animation_t *animations = level.knownAnimFileSets[temp_animFileIndex].animations; int anim = BOTH_STAND3; float animSpeed = 50.0f / animations[anim].frameLerp; - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE , animSpeed, cg.time); - -// int test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); -// gi.G2API_SetSurfaceOnOff(&ent->ghoul2[0], "l_arm",0x00000100); -// test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE, animSpeed, cg.time); -// gi.G2API_SetNewOrigin(&ent->ghoul2[0], gi.G2API_AddBolt(&ent->ghoul2[0], "rhang_tag_bone")); -// ent->s.apos.trDelta[1] = 10; -// ent->s.apos.trType = TR_LINEAR; + // int test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + // gi.G2API_SetSurfaceOnOff(&ent->ghoul2[0], "l_arm",0x00000100); + // test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + // gi.G2API_SetNewOrigin(&ent->ghoul2[0], gi.G2API_AddBolt(&ent->ghoul2[0], "rhang_tag_bone")); + // ent->s.apos.trDelta[1] = 10; + // ent->s.apos.trType = TR_LINEAR; ent->nextthink = level.time + 1000; ent->e_ThinkFunc = thinkF_set_MiscAnim; #endif } - -#define RACK_BLASTER 1 -#define RACK_REPEATER 2 -#define RACK_ROCKET 4 +#define RACK_BLASTER 1 +#define RACK_REPEATER 2 +#define RACK_ROCKET 4 /*QUAKED misc_model_gun_rack (1 0 0.25) (-14 -14 -4) (14 14 30) BLASTER REPEATER ROCKET model="models/map_objects/kejim/weaponsrack.md3" @@ -294,24 +269,20 @@ REPEATER - Puts one or more repeater guns on the rack. ROCKET - Puts one or more rocket launchers on the rack. */ -void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fright, float fup ) -{ - vec3_t fwd, right; - gentity_t *it_ent = G_Spawn(); - qboolean rotate = qtrue; +void GunRackAddItem(gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fright, float fup) { + vec3_t fwd, right; + gentity_t *it_ent = G_Spawn(); + qboolean rotate = qtrue; - AngleVectors( angs, fwd, right, NULL ); + AngleVectors(angs, fwd, right, NULL); - if ( it_ent && gun ) - { + if (it_ent && gun) { // FIXME: scaling the ammo will probably need to be tweaked to a reasonable amount...adjust as needed // Set base ammo per type - if ( gun->giType == IT_WEAPON ) - { - it_ent->spawnflags |= 16;// VERTICAL + if (gun->giType == IT_WEAPON) { + it_ent->spawnflags |= 16; // VERTICAL - switch( gun->giTag ) - { + switch (gun->giTag) { case WP_BLASTER: it_ent->count = 15; break; @@ -322,37 +293,30 @@ void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fr it_ent->count = 4; break; } - } - else - { + } else { rotate = qfalse; // must deliberately make it small, or else the objects will spawn inside of each other. - VectorSet( it_ent->maxs, 6.75f, 6.75f, 6.75f ); - VectorScale( it_ent->maxs, -1, it_ent->mins ); + VectorSet(it_ent->maxs, 6.75f, 6.75f, 6.75f); + VectorScale(it_ent->maxs, -1, it_ent->mins); } - it_ent->spawnflags |= 1;// ITMSF_SUSPEND - it_ent->classname = G_NewString(gun->classname); //copy it so it can be freed safely - G_SpawnItem( it_ent, gun ); + it_ent->spawnflags |= 1; // ITMSF_SUSPEND + it_ent->classname = G_NewString(gun->classname); // copy it so it can be freed safely + G_SpawnItem(it_ent, gun); // FinishSpawningItem handles everything, so clear the thinkFunc that was set in G_SpawnItem - FinishSpawningItem( it_ent ); + FinishSpawningItem(it_ent); - if ( gun->giType == IT_AMMO ) - { - if ( gun->giTag == AMMO_BLASTER ) // I guess this just has to use different logic?? + if (gun->giType == IT_AMMO) { + if (gun->giTag == AMMO_BLASTER) // I guess this just has to use different logic?? { - if ( g_spskill->integer >= 2 ) - { + if (g_spskill->integer >= 2) { it_ent->count += 10; // give more on higher difficulty because there will be more/harder enemies? } - } - else - { + } else { // scale ammo based on skill - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: // do default break; case 1: @@ -367,127 +331,110 @@ void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fr it_ent->nextthink = 0; - VectorCopy( org, it_ent->s.origin ); - VectorMA( it_ent->s.origin, fright, right, it_ent->s.origin ); - VectorMA( it_ent->s.origin, ffwd, fwd, it_ent->s.origin ); + VectorCopy(org, it_ent->s.origin); + VectorMA(it_ent->s.origin, fright, right, it_ent->s.origin); + VectorMA(it_ent->s.origin, ffwd, fwd, it_ent->s.origin); it_ent->s.origin[2] += fup; - VectorCopy( angs, it_ent->s.angles ); + VectorCopy(angs, it_ent->s.angles); // by doing this, we can force the amount of ammo we desire onto the weapon for when it gets picked-up - it_ent->flags |= ( FL_DROPPED_ITEM | FL_FORCE_PULLABLE_ONLY ); + it_ent->flags |= (FL_DROPPED_ITEM | FL_FORCE_PULLABLE_ONLY); it_ent->physicsBounce = 0.1f; - for ( int t = 0; t < 3; t++ ) - { - if ( rotate ) - { - if ( t == YAW ) - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + 180 + Q_flrand(-1.0f, 1.0f) * 14 ); - } - else - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + Q_flrand(-1.0f, 1.0f) * 4 ); + for (int t = 0; t < 3; t++) { + if (rotate) { + if (t == YAW) { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + 180 + Q_flrand(-1.0f, 1.0f) * 14); + } else { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + Q_flrand(-1.0f, 1.0f) * 4); } - } - else - { - if ( t == YAW ) - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + 90 + Q_flrand(-1.0f, 1.0f) * 4 ); + } else { + if (t == YAW) { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + 90 + Q_flrand(-1.0f, 1.0f) * 4); } } } - G_SetAngles( it_ent, it_ent->s.angles ); - G_SetOrigin( it_ent, it_ent->s.origin ); - gi.linkentity( it_ent ); + G_SetAngles(it_ent, it_ent->s.angles); + G_SetOrigin(it_ent, it_ent->s.origin); + gi.linkentity(it_ent); } } //--------------------------------------------- -void SP_misc_model_gun_rack( gentity_t *ent ) -{ - gitem_t *blaster = NULL, *repeater = NULL, *rocket = NULL; - int ct = 0; - float ofz[3]; - gitem_t *itemList[3]; +void SP_misc_model_gun_rack(gentity_t *ent) { + gitem_t *blaster = NULL, *repeater = NULL, *rocket = NULL; + int ct = 0; + float ofz[3]; + gitem_t *itemList[3]; // If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_REPEATER | RACK_ROCKET ))) - { - blaster = FindItemForWeapon( WP_BLASTER ); + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_REPEATER | RACK_ROCKET))) { + blaster = FindItemForWeapon(WP_BLASTER); } - if (( ent->spawnflags & RACK_REPEATER )) - { - repeater = FindItemForWeapon( WP_REPEATER ); + if ((ent->spawnflags & RACK_REPEATER)) { + repeater = FindItemForWeapon(WP_REPEATER); } - if (( ent->spawnflags & RACK_ROCKET )) - { - rocket = FindItemForWeapon( WP_ROCKET_LAUNCHER ); + if ((ent->spawnflags & RACK_ROCKET)) { + rocket = FindItemForWeapon(WP_ROCKET_LAUNCHER); } //---------weapon types - if ( blaster ) - { + if (blaster) { ofz[ct] = 23.0f; itemList[ct++] = blaster; } - if ( repeater ) - { + if (repeater) { ofz[ct] = 24.5f; itemList[ct++] = repeater; } - if ( rocket ) - { + if (rocket) { ofz[ct] = 25.5f; itemList[ct++] = rocket; } - if ( ct ) //..should always have at least one item on their, but just being safe + if (ct) //..should always have at least one item on their, but just being safe { - for ( ; ct < 3 ; ct++ ) - { + for (; ct < 3; ct++) { ofz[ct] = ofz[0]; itemList[ct] = itemList[0]; // first weapon ALWAYS propagates to fill up the shelf } } // now actually add the items to the shelf...validate that we have a list to add - if ( ct ) - { - for ( int i = 0; i < ct; i++ ) - { - GunRackAddItem( itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, ( i - 1 ) * 9 + Q_flrand(-1.0f, 1.0f) * 2, ofz[i] ); + if (ct) { + for (int i = 0; i < ct; i++) { + GunRackAddItem(itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, (i - 1) * 9 + Q_flrand(-1.0f, 1.0f) * 2, ofz[i]); } } - ent->s.modelindex = G_ModelIndex( "models/map_objects/kejim/weaponsrack.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/kejim/weaponsrack.md3"); - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); ent->contents = CONTENTS_SOLID; - gi.linkentity( ent ); + gi.linkentity(ent); } -#define RACK_METAL_BOLTS 2 -#define RACK_ROCKETS 4 -#define RACK_WEAPONS 8 -#define RACK_HEALTH 16 -#define RACK_PWR_CELL 32 -#define RACK_NO_FILL 64 +#define RACK_METAL_BOLTS 2 +#define RACK_ROCKETS 4 +#define RACK_WEAPONS 8 +#define RACK_HEALTH 16 +#define RACK_PWR_CELL 32 +#define RACK_NO_FILL 64 /*QUAKED misc_model_ammo_rack (1 0 0.25) (-14 -14 -4) (14 14 30) BLASTER METAL_BOLTS ROCKETS WEAPON HEALTH PWR_CELL NO_FILL model="models/map_objects/kejim/weaponsrung.md3" -NOTE: can mix and match these spawnflags to get multi-ammo racks. If only one type is checked the rack will be full of that ammo. Only three ammo packs max can be displayed. +NOTE: can mix and match these spawnflags to get multi-ammo racks. If only one type is checked the rack will be full of that ammo. Only three ammo packs max +can be displayed. BLASTER - Adds one or more ammo packs that are compatible with Blasters and the Bryar pistol. @@ -499,216 +446,177 @@ PWR_CELL - Adds one or more power cell packs that are compatible with the Disupt NO_FILL - Only puts selected ammo on the rack, it never fills up all three slots if only one or two items were checked */ -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +extern gitem_t *FindItemForAmmo(ammo_t ammo); //--------------------------------------------- -void SP_misc_model_ammo_rack( gentity_t *ent ) -{ -// If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_BLASTER )); +void SP_misc_model_ammo_rack(gentity_t *ent) { + // If BLASTER is checked...or nothing is checked then we'll do blasters + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_BLASTER)); } - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } - if (( ent->spawnflags & RACK_METAL_BOLTS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_REPEATER )); + if ((ent->spawnflags & RACK_METAL_BOLTS)) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_REPEATER)); } - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS )); + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); } - if (( ent->spawnflags & RACK_ROCKETS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); + if ((ent->spawnflags & RACK_ROCKETS)) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_ROCKET_LAUNCHER)); } - RegisterItem( FindItemForAmmo( AMMO_ROCKETS )); + RegisterItem(FindItemForAmmo(AMMO_ROCKETS)); } - if (( ent->spawnflags & RACK_PWR_CELL )) - { - RegisterItem( FindItemForAmmo( AMMO_POWERCELL )); + if ((ent->spawnflags & RACK_PWR_CELL)) { + RegisterItem(FindItemForAmmo(AMMO_POWERCELL)); } - if (( ent->spawnflags & RACK_HEALTH )) - { - RegisterItem( FindItem( "item_medpak_instant" )); + if ((ent->spawnflags & RACK_HEALTH)) { + RegisterItem(FindItem("item_medpak_instant")); } ent->e_ThinkFunc = thinkF_spawn_rack_goods; ent->nextthink = level.time + 100; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - ent->contents = CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//CONTENTS_SOLID;//so use traces can go through them + ent->contents = CONTENTS_SHOTCLIP | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // CONTENTS_SOLID;//so use traces can go through them - gi.linkentity( ent ); + gi.linkentity(ent); } // AMMO RACK!! -void spawn_rack_goods( gentity_t *ent ) -{ - float v_off = 0; - gitem_t *blaster = NULL, *metal_bolts = NULL, *rockets = NULL, *it = NULL; - gitem_t *am_blaster = NULL, *am_metal_bolts = NULL, *am_rockets = NULL, *am_pwr_cell = NULL; - gitem_t *health = NULL; - int pos = 0, ct = 0; - gitem_t *itemList[4]; // allocating 4, but we only use 3. done so I don't have to validate that the array isn't full before I add another +void spawn_rack_goods(gentity_t *ent) { + float v_off = 0; + gitem_t *blaster = NULL, *metal_bolts = NULL, *rockets = NULL, *it = NULL; + gitem_t *am_blaster = NULL, *am_metal_bolts = NULL, *am_rockets = NULL, *am_pwr_cell = NULL; + gitem_t *health = NULL; + int pos = 0, ct = 0; + gitem_t *itemList[4]; // allocating 4, but we only use 3. done so I don't have to validate that the array isn't full before I add another - gi.unlinkentity( ent ); + gi.unlinkentity(ent); // If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - blaster = FindItemForWeapon( WP_BLASTER ); + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { + if (ent->spawnflags & RACK_WEAPONS) { + blaster = FindItemForWeapon(WP_BLASTER); } - am_blaster = FindItemForAmmo( AMMO_BLASTER ); + am_blaster = FindItemForAmmo(AMMO_BLASTER); } - if (( ent->spawnflags & RACK_METAL_BOLTS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - metal_bolts = FindItemForWeapon( WP_REPEATER ); + if ((ent->spawnflags & RACK_METAL_BOLTS)) { + if (ent->spawnflags & RACK_WEAPONS) { + metal_bolts = FindItemForWeapon(WP_REPEATER); } - am_metal_bolts = FindItemForAmmo( AMMO_METAL_BOLTS ); + am_metal_bolts = FindItemForAmmo(AMMO_METAL_BOLTS); } - if (( ent->spawnflags & RACK_ROCKETS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - rockets = FindItemForWeapon( WP_ROCKET_LAUNCHER ); + if ((ent->spawnflags & RACK_ROCKETS)) { + if (ent->spawnflags & RACK_WEAPONS) { + rockets = FindItemForWeapon(WP_ROCKET_LAUNCHER); } - am_rockets = FindItemForAmmo( AMMO_ROCKETS ); + am_rockets = FindItemForAmmo(AMMO_ROCKETS); } - if (( ent->spawnflags & RACK_PWR_CELL )) - { - am_pwr_cell = FindItemForAmmo( AMMO_POWERCELL ); + if ((ent->spawnflags & RACK_PWR_CELL)) { + am_pwr_cell = FindItemForAmmo(AMMO_POWERCELL); } - if (( ent->spawnflags & RACK_HEALTH )) - { - health = FindItem( "item_medpak_instant" ); - RegisterItem( health ); + if ((ent->spawnflags & RACK_HEALTH)) { + health = FindItem("item_medpak_instant"); + RegisterItem(health); } //---------Ammo types - if ( am_blaster ) - { + if (am_blaster) { itemList[ct++] = am_blaster; } - if ( am_metal_bolts ) - { + if (am_metal_bolts) { itemList[ct++] = am_metal_bolts; } - if ( am_pwr_cell ) - { + if (am_pwr_cell) { itemList[ct++] = am_pwr_cell; } - if ( am_rockets ) - { + if (am_rockets) { itemList[ct++] = am_rockets; } - if ( !(ent->spawnflags & RACK_NO_FILL) && ct ) //double negative..should always have at least one item on there, but just being safe + if (!(ent->spawnflags & RACK_NO_FILL) && ct) // double negative..should always have at least one item on there, but just being safe { - for ( ; ct < 3 ; ct++ ) - { + for (; ct < 3; ct++) { itemList[ct] = itemList[0]; // first item ALWAYS propagates to fill up the shelf } } // now actually add the items to the shelf...validate that we have a list to add - if ( ct ) - { - for ( int i = 0; i < ct; i++ ) - { - GunRackAddItem( itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (i-1)* 8, 7.0f ); + if (ct) { + for (int i = 0; i < ct; i++) { + GunRackAddItem(itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (i - 1) * 8, 7.0f); } } // -----Weapon option - if ( ent->spawnflags & RACK_WEAPONS ) - { - if ( !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { + if (ent->spawnflags & RACK_WEAPONS) { + if (!(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { // nothing was selected, so we assume blaster pack it = blaster; - } - else - { + } else { // if weapon is checked...and so are one or more ammo types, then pick a random weapon to display..always give weaker weapons first - if ( blaster ) - { + if (blaster) { it = blaster; v_off = 25.5f; - } - else if ( metal_bolts ) - { + } else if (metal_bolts) { it = metal_bolts; v_off = 27.0f; - } - else if ( rockets ) - { + } else if (rockets) { it = rockets; v_off = 28.0f; } } - if ( it ) - { + if (it) { // since we may have to put up a health pack on the shelf, we should know where we randomly put // the gun so we don't put the pack on the same spot..so pick either the left or right side - pos = ( Q_flrand(0.0f, 1.0f) > .5 ) ? -1 : 1; + pos = (Q_flrand(0.0f, 1.0f) > .5) ? -1 : 1; - GunRackAddItem( it, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, ( Q_flrand(0.0f, 1.0f) * 6 + 4 ) * pos, v_off ); + GunRackAddItem(it, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, (Q_flrand(0.0f, 1.0f) * 6 + 4) * pos, v_off); } } // ------Medpack - if (( ent->spawnflags & RACK_HEALTH ) && health ) - { - if ( !pos ) - { + if ((ent->spawnflags & RACK_HEALTH) && health) { + if (!pos) { // we haven't picked a side already... - pos = ( Q_flrand(0.0f, 1.0f) > .5 ) ? -1 : 1; - } - else - { + pos = (Q_flrand(0.0f, 1.0f) > .5) ? -1 : 1; + } else { // switch to the opposite side pos *= -1; } - GunRackAddItem( health, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, ( Q_flrand(0.0f, 1.0f) * 4 + 4 ) * pos, 24 ); + GunRackAddItem(health, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (Q_flrand(0.0f, 1.0f) * 4 + 4) * pos, 24); } - ent->s.modelindex = G_ModelIndex( "models/map_objects/kejim/weaponsrung.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/kejim/weaponsrung.md3"); - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - gi.linkentity( ent ); + gi.linkentity(ent); } -#define DROP_MEDPACK 1 -#define DROP_SHIELDS 2 -#define DROP_BACTA 4 -#define DROP_BATTERIES 8 +#define DROP_MEDPACK 1 +#define DROP_SHIELDS 2 +#define DROP_BACTA 4 +#define DROP_BATTERIES 8 /*QUAKED misc_model_cargo_small (1 0 0.25) (-14 -14 -4) (14 14 30) MEDPACK SHIELDS BACTA BATTERIES model="models/map_objects/kejim/cargo_small.md3" @@ -725,110 +633,96 @@ BATTERIES - "splashDamage" - damage to do within explode range ( default 1 ) */ -extern gentity_t *LaunchItem( gitem_t *item, const vec3_t origin, const vec3_t velocity, char *target ); +extern gentity_t *LaunchItem(gitem_t *item, const vec3_t origin, const vec3_t velocity, char *target); -void misc_model_cargo_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - int flags; - vec3_t org, temp; +void misc_model_cargo_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + int flags; + vec3_t org, temp; gitem_t *health = NULL, *shields = NULL, *bacta = NULL, *batteries = NULL; // copy these for later flags = self->spawnflags; - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); // we already had spawn flags, but we don't care what they were...we just need to set up the flags we want for misc_model_breakable_die self->spawnflags = 8; // NO_DMODEL // pass through to get the effects and such - misc_model_breakable_die( self, inflictor, attacker, damage, mod ); + misc_model_breakable_die(self, inflictor, attacker, damage, mod); // now that the model is broken, we can safely spawn these in it's place without them being in solid temp[2] = org[2] + 16; // annoying, but spawn each thing in its own little quadrant so that they don't end up on top of each other - if (( flags & DROP_MEDPACK )) - { - health = FindItem( "item_medpak_instant" ); + if ((flags & DROP_MEDPACK)) { + health = FindItem("item_medpak_instant"); - if ( health ) - { + if (health) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 + 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 + 16; - LaunchItem( health, temp, vec3_origin, NULL ); + LaunchItem(health, temp, vec3_origin, NULL); } } - if (( flags & DROP_SHIELDS )) - { - shields = FindItem( "item_shield_sm_instant" ); + if ((flags & DROP_SHIELDS)) { + shields = FindItem("item_shield_sm_instant"); - if ( shields ) - { + if (shields) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 - 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 + 16; - LaunchItem( shields, temp, vec3_origin, NULL ); + LaunchItem(shields, temp, vec3_origin, NULL); } } - if (( flags & DROP_BACTA )) - { - bacta = FindItem( "item_bacta" ); + if ((flags & DROP_BACTA)) { + bacta = FindItem("item_bacta"); - if ( bacta ) - { + if (bacta) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 - 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 - 16; - LaunchItem( bacta, temp, vec3_origin, NULL ); + LaunchItem(bacta, temp, vec3_origin, NULL); } } - if (( flags & DROP_BATTERIES )) - { - batteries = FindItem( "item_battery" ); + if ((flags & DROP_BATTERIES)) { + batteries = FindItem("item_battery"); - if ( batteries ) - { + if (batteries) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 + 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 - 16; - LaunchItem( batteries, temp, vec3_origin, NULL ); + LaunchItem(batteries, temp, vec3_origin, NULL); } } } //--------------------------------------------- -void SP_misc_model_cargo_small( gentity_t *ent ) -{ - G_SpawnInt( "splashRadius", "96", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "1", &ent->splashDamage ); +void SP_misc_model_cargo_small(gentity_t *ent) { + G_SpawnInt("splashRadius", "96", &ent->splashRadius); + G_SpawnInt("splashDamage", "1", &ent->splashDamage); - if (( ent->spawnflags & DROP_MEDPACK )) - { - RegisterItem( FindItem( "item_medpak_instant" )); + if ((ent->spawnflags & DROP_MEDPACK)) { + RegisterItem(FindItem("item_medpak_instant")); } - if (( ent->spawnflags & DROP_SHIELDS )) - { - RegisterItem( FindItem( "item_shield_sm_instant" )); + if ((ent->spawnflags & DROP_SHIELDS)) { + RegisterItem(FindItem("item_shield_sm_instant")); } - if (( ent->spawnflags & DROP_BACTA )) - { -// RegisterItem( FindItem( "item_bacta" )); + if ((ent->spawnflags & DROP_BACTA)) { + // RegisterItem( FindItem( "item_bacta" )); } - if (( ent->spawnflags & DROP_BATTERIES )) - { - RegisterItem( FindItem( "item_battery" )); + if ((ent->spawnflags & DROP_BATTERIES)) { + RegisterItem(FindItem("item_battery")); } - G_SpawnInt( "health", "25", &ent->health ); + G_SpawnInt("health", "25", &ent->health); - SetMiscModelDefaults( ent, useF_NULL, "11", CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, 0, qtrue, qfalse ); - ent->s.modelindex2 = G_ModelIndex("/models/map_objects/kejim/cargo_small.md3"); // Precache model + SetMiscModelDefaults(ent, useF_NULL, "11", CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, 0, qtrue, qfalse); + ent->s.modelindex2 = G_ModelIndex("/models/map_objects/kejim/cargo_small.md3"); // Precache model // we only take damage from a heavy weapon class missile ent->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; @@ -837,4 +731,3 @@ void SP_misc_model_cargo_small( gentity_t *ent ) ent->radius = 1.5f; // scale number of chunks spawned } - diff --git a/code/game/g_missile.cpp b/code/game/g_missile.cpp index e5f955b566..eb50cf651d 100644 --- a/code/game/g_missile.cpp +++ b/code/game/g_missile.cpp @@ -29,92 +29,79 @@ along with this program; if not, see . #include "b_local.h" #ifdef _DEBUG - #include +#include #endif //_DEBUG -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +qboolean LogAccuracyHit(gentity_t *target, gentity_t *attacker); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); //------------------------------------------------------------------------- -void G_MissileBounceEffect( gentity_t *ent, vec3_t org, vec3_t dir, qboolean hitWorld ) -{ - //FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect - switch( ent->s.weapon ) - { +void G_MissileBounceEffect(gentity_t *ent, vec3_t org, vec3_t dir, qboolean hitWorld) { + // FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect + switch (ent->s.weapon) { case WP_BOWCASTER: - if ( hitWorld ) - { - G_PlayEffect( "bowcaster/bounce_wall", org, dir ); - } - else - { - G_PlayEffect( "bowcaster/deflect", ent->currentOrigin, dir ); + if (hitWorld) { + G_PlayEffect("bowcaster/bounce_wall", org, dir); + } else { + G_PlayEffect("bowcaster/deflect", ent->currentOrigin, dir); } break; case WP_BLASTER: case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: - G_PlayEffect( "blaster/deflect", ent->currentOrigin, dir ); - break; - default: - { - gentity_t *tent = G_TempEntity( org, EV_GRENADE_BOUNCE ); - VectorCopy( dir, tent->pos1 ); - tent->s.weapon = ent->s.weapon; - } + G_PlayEffect("blaster/deflect", ent->currentOrigin, dir); break; + default: { + gentity_t *tent = G_TempEntity(org, EV_GRENADE_BOUNCE); + VectorCopy(dir, tent->pos1); + tent->s.weapon = ent->s.weapon; + } break; } } -void G_MissileReflectEffect( gentity_t *ent, vec3_t org, vec3_t dir ) -{ - //FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect - switch( ent->s.weapon ) - { +void G_MissileReflectEffect(gentity_t *ent, vec3_t org, vec3_t dir) { + // FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect + switch (ent->s.weapon) { case WP_BOWCASTER: - G_PlayEffect( "bowcaster/deflect", ent->currentOrigin, dir ); + G_PlayEffect("bowcaster/deflect", ent->currentOrigin, dir); break; case WP_BLASTER: case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: default: - G_PlayEffect( "blaster/deflect", ent->currentOrigin, dir ); + G_PlayEffect("blaster/deflect", ent->currentOrigin, dir); break; } } //------------------------------------------------------------------------- -static void G_MissileStick( gentity_t *missile, gentity_t *other, trace_t *tr ) -{ - if ( other->NPC || !Q_stricmp( other->classname, "misc_model_breakable" )) - { +static void G_MissileStick(gentity_t *missile, gentity_t *other, trace_t *tr) { + if (other->NPC || !Q_stricmp(other->classname, "misc_model_breakable")) { // we bounce off of NPC's and misc model breakables because sticking to them requires too much effort vec3_t velocity; - int hitTime = level.previousTime + ( level.time - level.previousTime ) * tr->fraction; + int hitTime = level.previousTime + (level.time - level.previousTime) * tr->fraction; - EvaluateTrajectoryDelta( &missile->s.pos, hitTime, velocity ); + EvaluateTrajectoryDelta(&missile->s.pos, hitTime, velocity); - float dot = DotProduct( velocity, tr->plane.normal ); - G_SetOrigin( missile, tr->endpos ); - VectorMA( velocity, -1.6f * dot, tr->plane.normal, missile->s.pos.trDelta ); - VectorMA( missile->s.pos.trDelta, 10, tr->plane.normal, missile->s.pos.trDelta ); + float dot = DotProduct(velocity, tr->plane.normal); + G_SetOrigin(missile, tr->endpos); + VectorMA(velocity, -1.6f * dot, tr->plane.normal, missile->s.pos.trDelta); + VectorMA(missile->s.pos.trDelta, 10, tr->plane.normal, missile->s.pos.trDelta); missile->s.pos.trTime = level.time - 10; // move a bit on the first frame // check for stop - if ( tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_WORLD && - tr->plane.normal[2] > 0.7 && missile->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_WORLD && tr->plane.normal[2] > 0.7 && + missile->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { missile->nextthink = level.time + 100; - } - else - { + } else { // fall till we hit the ground missile->s.pos.trType = TR_GRAVITY; } @@ -122,15 +109,13 @@ static void G_MissileStick( gentity_t *missile, gentity_t *other, trace_t *tr ) return; // don't stick yet } - if ( missile->e_TouchFunc != touchF_NULL ) - { - GEntity_TouchFunc( missile, other, tr ); + if (missile->e_TouchFunc != touchF_NULL) { + GEntity_TouchFunc(missile, other, tr); } - G_AddEvent( missile, EV_MISSILE_STICK, 0 ); + G_AddEvent(missile, EV_MISSILE_STICK, 0); - if ( other->s.eType == ET_MOVER || other->e_DieFunc == dieF_funcBBrushDie || other->e_DieFunc == dieF_funcGlassDie) - { + if (other->s.eType == ET_MOVER || other->e_DieFunc == dieF_funcBBrushDie || other->e_DieFunc == dieF_funcGlassDie) { // movers and breakable brushes need extra info...so sticky missiles can ride lifts and blow up when the thing they are attached to goes away. missile->s.groundEntityNum = tr->entityNum; } @@ -143,155 +128,116 @@ G_ReflectMissile Reflect the missile roughly back at it's owner ================ */ -extern gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float minDot ); -void G_ReflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ) -{ - vec3_t bounce_dir; - int i; - float speed; +extern gentity_t *Jedi_FindEnemyInCone(gentity_t *self, gentity_t *fallback, float minDot); +void G_ReflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward) { + vec3_t bounce_dir; + int i; + float speed; qboolean reflected = qfalse; - gentity_t *owner = ent; + gentity_t *owner = ent; - if ( ent->owner ) - { + if (ent->owner) { owner = ent->owner; } - //save the original speed - speed = VectorNormalize( missile->s.pos.trDelta ); + // save the original speed + speed = VectorNormalize(missile->s.pos.trDelta); - if ( ent && owner && owner->client && !owner->client->ps.saberInFlight && - (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 || (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_1&&!Q_irand( 0, 3 )) ) ) - {//if high enough defense skill and saber in-hand (100% at level 3, 25% at level 2, 0% at level 1), reflections are perfectly deflected toward an enemy + if (ent && owner && owner->client && !owner->client->ps.saberInFlight && + (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 || + (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && + !Q_irand(0, 3)))) { // if high enough defense skill and saber in-hand (100% at level 3, 25% at level 2, 0% at level 1), reflections are perfectly + // deflected toward an enemy gentity_t *enemy; - if ( owner->enemy && Q_irand( 0, 3 ) ) - {//toward current enemy 75% of the time + if (owner->enemy && Q_irand(0, 3)) { // toward current enemy 75% of the time enemy = owner->enemy; + } else { // find another enemy + enemy = Jedi_FindEnemyInCone(owner, owner->enemy, 0.3f); } - else - {//find another enemy - enemy = Jedi_FindEnemyInCone( owner, owner->enemy, 0.3f ); - } - if ( enemy ) - { - vec3_t bullseye; - CalcEntitySpot( enemy, SPOT_HEAD, bullseye ); - bullseye[0] += Q_irand( -4, 4 ); - bullseye[1] += Q_irand( -4, 4 ); - bullseye[2] += Q_irand( -16, 4 ); - VectorSubtract( bullseye, missile->currentOrigin, bounce_dir ); - VectorNormalize( bounce_dir ); - if ( !PM_SaberInParry( owner->client->ps.saberMove ) - && !PM_SaberInReflect( owner->client->ps.saberMove ) - && !PM_SaberInIdle( owner->client->ps.saberMove ) ) - {//a bit more wild - if ( PM_SaberInAttack( owner->client->ps.saberMove ) - || PM_SaberInTransitionAny( owner->client->ps.saberMove ) - || PM_SaberInSpecialAttack( owner->client->ps.torsoAnim ) ) - {//moderately more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + if (enemy) { + vec3_t bullseye; + CalcEntitySpot(enemy, SPOT_HEAD, bullseye); + bullseye[0] += Q_irand(-4, 4); + bullseye[1] += Q_irand(-4, 4); + bullseye[2] += Q_irand(-16, 4); + VectorSubtract(bullseye, missile->currentOrigin, bounce_dir); + VectorNormalize(bounce_dir); + if (!PM_SaberInParry(owner->client->ps.saberMove) && !PM_SaberInReflect(owner->client->ps.saberMove) && + !PM_SaberInIdle(owner->client->ps.saberMove)) { // a bit more wild + if (PM_SaberInAttack(owner->client->ps.saberMove) || PM_SaberInTransitionAny(owner->client->ps.saberMove) || + PM_SaberInSpecialAttack(owner->client->ps.torsoAnim)) { // moderately more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } - } - else - {//mildly more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.1f, 0.1f ); + } else { // mildly more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.1f, 0.1f); } } } - VectorNormalize( bounce_dir ); + VectorNormalize(bounce_dir); reflected = qtrue; } } - if ( !reflected ) - { - if ( missile->owner && missile->s.weapon != WP_SABER ) - {//bounce back at them if you can - VectorSubtract( missile->owner->currentOrigin, missile->currentOrigin, bounce_dir ); - VectorNormalize( bounce_dir ); - } - else - { + if (!reflected) { + if (missile->owner && missile->s.weapon != WP_SABER) { // bounce back at them if you can + VectorSubtract(missile->owner->currentOrigin, missile->currentOrigin, bounce_dir); + VectorNormalize(bounce_dir); + } else { vec3_t missile_dir; - VectorSubtract( ent->currentOrigin, missile->currentOrigin, missile_dir ); - VectorCopy( missile->s.pos.trDelta, bounce_dir ); - VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); - VectorNormalize( bounce_dir ); + VectorSubtract(ent->currentOrigin, missile->currentOrigin, missile_dir); + VectorCopy(missile->s.pos.trDelta, bounce_dir); + VectorScale(bounce_dir, DotProduct(forward, missile_dir), bounce_dir); + VectorNormalize(bounce_dir); } - if ( owner->s.weapon == WP_SABER && owner->client ) - {//saber - if ( owner->client->ps.saberInFlight ) - {//reflecting off a thrown saber is totally wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.8f, 0.8f ); + if (owner->s.weapon == WP_SABER && owner->client) { // saber + if (owner->client->ps.saberInFlight) { // reflecting off a thrown saber is totally wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.8f, 0.8f); } - } - else if ( owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1 ) - {// at level 1 - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.4f, 0.4f ); + } else if (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1) { // at level 1 + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.4f, 0.4f); } - } - else - {// at level 2 - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + } else { // at level 2 + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } } - if ( !PM_SaberInParry( owner->client->ps.saberMove ) - && !PM_SaberInReflect( owner->client->ps.saberMove ) - && !PM_SaberInIdle( owner->client->ps.saberMove ) ) - {//a bit more wild - if ( PM_SaberInAttack( owner->client->ps.saberMove ) - || PM_SaberInTransitionAny( owner->client->ps.saberMove ) - || PM_SaberInSpecialAttack( owner->client->ps.torsoAnim ) ) - {//really wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.3f, 0.3f ); + if (!PM_SaberInParry(owner->client->ps.saberMove) && !PM_SaberInReflect(owner->client->ps.saberMove) && + !PM_SaberInIdle(owner->client->ps.saberMove)) { // a bit more wild + if (PM_SaberInAttack(owner->client->ps.saberMove) || PM_SaberInTransitionAny(owner->client->ps.saberMove) || + PM_SaberInSpecialAttack(owner->client->ps.torsoAnim)) { // really wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.3f, 0.3f); } - } - else - {//mildly more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.1f, 0.1f ); + } else { // mildly more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.1f, 0.1f); } } } - } - else - {//some other kind of reflection - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + } else { // some other kind of reflection + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } } } - VectorNormalize( bounce_dir ); - VectorScale( bounce_dir, speed, missile->s.pos.trDelta ); + VectorNormalize(bounce_dir); + VectorScale(bounce_dir, speed, missile->s.pos.trDelta); #ifdef _DEBUG - assert( !Q_isnan(missile->s.pos.trDelta[0])&&!Q_isnan(missile->s.pos.trDelta[1])&&!Q_isnan(missile->s.pos.trDelta[2])); -#endif// _DEBUG - missile->s.pos.trTime = level.time - 10; // move a bit on the very first frame - VectorCopy( missile->currentOrigin, missile->s.pos.trBase ); - if ( missile->s.weapon != WP_SABER ) - {//you are mine, now! - if ( !missile->lastEnemy ) - {//remember who originally shot this missile + assert(!Q_isnan(missile->s.pos.trDelta[0]) && !Q_isnan(missile->s.pos.trDelta[1]) && !Q_isnan(missile->s.pos.trDelta[2])); +#endif // _DEBUG + missile->s.pos.trTime = level.time - 10; // move a bit on the very first frame + VectorCopy(missile->currentOrigin, missile->s.pos.trBase); + if (missile->s.weapon != WP_SABER) { // you are mine, now! + if (!missile->lastEnemy) { // remember who originally shot this missile missile->lastEnemy = missile->owner; } missile->owner = owner; } - if ( missile->s.weapon == WP_ROCKET_LAUNCHER ) - {//stop homing + if (missile->s.weapon == WP_ROCKET_LAUNCHER) { // stop homing missile->e_ThinkFunc = thinkF_NULL; } } @@ -302,58 +248,53 @@ G_BounceRollMissile ================ */ -void G_BounceRollMissile( gentity_t *ent, trace_t *trace ) -{ - vec3_t velocity, normal; - float dot, speedXY, velocityZ, normalZ; - int hitTime; +void G_BounceRollMissile(gentity_t *ent, trace_t *trace) { + vec3_t velocity, normal; + float dot, speedXY, velocityZ, normalZ; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - //Do horizontal - //FIXME: Need to roll up, down slopes + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + // Do horizontal + // FIXME: Need to roll up, down slopes velocityZ = velocity[2]; velocity[2] = 0; - speedXY = VectorLength( velocity );//friction - VectorCopy( trace->plane.normal, normal ); + speedXY = VectorLength(velocity); // friction + VectorCopy(trace->plane.normal, normal); normalZ = normal[2]; normal[2] = 0; - dot = DotProduct( velocity, normal ); - VectorMA( velocity, -2*dot, normal, ent->s.pos.trDelta ); - //now do the z reflection - //FIXME: Bobbles when it stops - VectorSet( velocity, 0, 0, velocityZ ); - VectorSet( normal, 0, 0, normalZ ); - dot = DotProduct( velocity, normal )*-1; - if ( dot > 10 ) - { - ent->s.pos.trDelta[2] = dot*0.3f;//not very bouncy - } - else - { + dot = DotProduct(velocity, normal); + VectorMA(velocity, -2 * dot, normal, ent->s.pos.trDelta); + // now do the z reflection + // FIXME: Bobbles when it stops + VectorSet(velocity, 0, 0, velocityZ); + VectorSet(normal, 0, 0, normalZ); + dot = DotProduct(velocity, normal) * -1; + if (dot > 10) { + ent->s.pos.trDelta[2] = dot * 0.3f; // not very bouncy + } else { ent->s.pos.trDelta[2] = 0; } // check for stop - if ( speedXY <= 0 ) - { - G_SetOrigin( ent, trace->endpos ); - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + if (speedXY <= 0) { + G_SetOrigin(ent, trace->endpos); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trType = TR_STATIONARY; return; } - //FIXME: rolling needs to match direction - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorCopy( ent->s.pos.trDelta, ent->s.apos.trDelta ); + // FIXME: rolling needs to match direction + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorCopy(ent->s.pos.trDelta, ent->s.apos.trDelta); - //remember this spot - VectorCopy( trace->endpos, ent->currentOrigin ); + // remember this spot + VectorCopy(trace->endpos, ent->currentOrigin); ent->s.pos.trTime = hitTime - 10; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - //VectorCopy( trace->plane.normal, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + // VectorCopy( trace->plane.normal, ent->pos1 ); } /* @@ -362,51 +303,44 @@ G_BounceMissile ================ */ -void G_BounceMissile( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceMissile(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); - if ( ent->s.eFlags & EF_BOUNCE_SHRAPNEL ) - { - VectorScale( ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta ); + if (ent->s.eFlags & EF_BOUNCE_SHRAPNEL) { + VectorScale(ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta); ent->s.pos.trType = TR_GRAVITY; // check for stop - if ( trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - G_SetOrigin( ent, trace->endpos ); + G_SetOrigin(ent, trace->endpos); ent->nextthink = level.time + 100; return; } - } - else if ( ent->s.eFlags & EF_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); + } else if (ent->s.eFlags & EF_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta); // check for stop - if ( trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - if ( ent->s.weapon == WP_THERMAL ) - {//roll when you "stop" + if (ent->s.weapon == WP_THERMAL) { // roll when you "stop" ent->s.pos.trType = TR_INTERPOLATE; - } - else - { - G_SetOrigin( ent, trace->endpos ); + } else { + G_SetOrigin(ent, trace->endpos); ent->nextthink = level.time + 500; return; } } - if ( ent->s.weapon == WP_THERMAL ) - { + if (ent->s.weapon == WP_THERMAL) { ent->has_bounced = qtrue; } } @@ -419,26 +353,20 @@ void G_BounceMissile( gentity_t *ent, trace_t *trace ) { #else // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... - VectorAdd( trace->endpos, trace->plane.normal, ent->currentOrigin ); - if ( hitTime >= level.time ) - {//trace fraction must have been 1 + VectorAdd(trace->endpos, trace->plane.normal, ent->currentOrigin); + if (hitTime >= level.time) { // trace fraction must have been 1 ent->s.pos.trTime = level.time - 10; - } - else - { + } else { ent->s.pos.trTime = hitTime - 10; // this is kinda dumb hacking, but it pushes the missile away from the impact plane a bit } #endif - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorCopy( trace->plane.normal, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorCopy(trace->plane.normal, ent->pos1); - if ( ent->s.weapon != WP_SABER - && ent->s.weapon != WP_THERMAL - && ent->e_clThinkFunc != clThinkF_CG_Limb - && ent->e_ThinkFunc != thinkF_LimbThink ) - {//not a saber, bouncing thermal or limb - //now you can damage the guy you came from + if (ent->s.weapon != WP_SABER && ent->s.weapon != WP_THERMAL && ent->e_clThinkFunc != clThinkF_CG_Limb && + ent->e_ThinkFunc != thinkF_LimbThink) { // not a saber, bouncing thermal or limb + // now you can damage the guy you came from ent->owner = NULL; } } @@ -450,106 +378,86 @@ G_MissileImpact ================ */ -void NoghriGasCloudThink( gentity_t *self ) -{ +void NoghriGasCloudThink(gentity_t *self) { self->nextthink = level.time + FRAMETIME; - AddSightEvent( self->owner, self->currentOrigin, 200, AEL_DANGER, 50 ); + AddSightEvent(self->owner, self->currentOrigin, 200, AEL_DANGER, 50); - if ( self->fx_time < level.time ) - { - vec3_t up = {0,0,1}; - G_PlayEffect( "noghri_stick/gas_cloud", self->currentOrigin, up ); + if (self->fx_time < level.time) { + vec3_t up = {0, 0, 1}; + G_PlayEffect("noghri_stick/gas_cloud", self->currentOrigin, up); self->fx_time = level.time + 250; } - if ( level.time - self->s.time <= 2500 ) - { - if ( !Q_irand( 0, 3-g_spskill->integer ) ) - { - G_RadiusDamage( self->currentOrigin, self->owner, Q_irand( 1, 4 ), self->splashRadius, - self->owner, self->splashMethodOfDeath ); + if (level.time - self->s.time <= 2500) { + if (!Q_irand(0, 3 - g_spskill->integer)) { + G_RadiusDamage(self->currentOrigin, self->owner, Q_irand(1, 4), self->splashRadius, self->owner, self->splashMethodOfDeath); } } - if ( level.time - self->s.time > 3000 ) - { - G_FreeEntity( self ); + if (level.time - self->s.time > 3000) { + G_FreeEntity(self); } } -void G_SpawnNoghriGasCloud( gentity_t *ent ) -{//FIXME: force-pushable/dispersable? +void G_SpawnNoghriGasCloud(gentity_t *ent) { // FIXME: force-pushable/dispersable? ent->freeAfterEvent = qfalse; ent->e_TouchFunc = touchF_NULL; - //ent->s.loopSound = G_SoundIndex( "sound/weapons/noghri/smoke.wav" ); - //G_SoundOnEnt( ent, CHAN_AUTO, "sound/weapons/noghri/smoke.wav" ); + // ent->s.loopSound = G_SoundIndex( "sound/weapons/noghri/smoke.wav" ); + // G_SoundOnEnt( ent, CHAN_AUTO, "sound/weapons/noghri/smoke.wav" ); - G_SetOrigin( ent, ent->currentOrigin ); + G_SetOrigin(ent, ent->currentOrigin); ent->e_ThinkFunc = thinkF_NoghriGasCloudThink; ent->nextthink = level.time + FRAMETIME; - vec3_t up = {0,0,1}; - G_PlayEffect( "noghri_stick/gas_cloud", ent->currentOrigin, up ); + vec3_t up = {0, 0, 1}; + G_PlayEffect("noghri_stick/gas_cloud", ent->currentOrigin, up); ent->fx_time = level.time + 250; ent->s.time = level.time; } -extern void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ); -extern qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ); -void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc=HL_NONE ) -{ +extern void laserTrapStick(gentity_t *ent, vec3_t endpos, vec3_t normal); +extern qboolean W_AccuracyLoggableWeapon(int weapon, qboolean alt_fire, int mod); +void G_MissileImpacted(gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc = HL_NONE) { // impact damage - if ( other->takedamage ) - { + if (other->takedamage) { // FIXME: wrong damage direction? - if ( ent->damage ) - { - vec3_t velocity; + if (ent->damage) { + vec3_t velocity; - EvaluateTrajectoryDelta( &ent->s.pos, level.time, velocity ); - if ( VectorLength( velocity ) == 0 ) - { - velocity[2] = 1; // stepped on a grenade + EvaluateTrajectoryDelta(&ent->s.pos, level.time, velocity); + if (VectorLength(velocity) == 0) { + velocity[2] = 1; // stepped on a grenade } int damage = ent->damage; - if( other->client ) - { - class_t npc_class = other->client->NPC_class; + if (other->client) { + class_t npc_class = other->client->NPC_class; // If we are a robot and we aren't currently doing the full body electricity... - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || //npc_class == CLASS_PROTOCOL ||//no protocol, looks odd - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || npc_class == CLASS_MARK1 || + npc_class == CLASS_MARK2 || // npc_class == CLASS_PROTOCOL ||//no protocol, looks odd + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { // special droid only behaviors - if ( other->client->ps.powerups[PW_SHOCKED] < level.time + 100 ) - { + if (other->client->ps.powerups[PW_SHOCKED] < level.time + 100) { // ... do the effect for a split second for some more feedback - other->s.powerups |= ( 1 << PW_SHOCKED ); + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = level.time + 450; } - //FIXME: throw some sparks off droids,too + // FIXME: throw some sparks off droids,too } } - G_Damage( other, ent, ent->owner, velocity, - impactPos, damage, - ent->dflags, ent->methodOfDeath, hitLoc); - - if ( ent->s.weapon == WP_DEMP2 ) - {//a hit with demp2 decloaks saboteurs - if ( other && other->client && other->client->NPC_class == CLASS_SABOTEUR ) - {//FIXME: make this disabled cloak hold for some amount of time? - Saboteur_Decloak( other, Q_irand( 3000, 10000 ) ); - if ( ent->methodOfDeath == MOD_DEMP2_ALT ) - {//direct hit with alt disabled cloak forever - if ( other->NPC ) - {//permanently disable the saboteur's cloak + G_Damage(other, ent, ent->owner, velocity, impactPos, damage, ent->dflags, ent->methodOfDeath, hitLoc); + + if (ent->s.weapon == WP_DEMP2) { // a hit with demp2 decloaks saboteurs + if (other && other->client && other->client->NPC_class == CLASS_SABOTEUR) { // FIXME: make this disabled cloak hold for some amount of time? + Saboteur_Decloak(other, Q_irand(3000, 10000)); + if (ent->methodOfDeath == MOD_DEMP2_ALT) { // direct hit with alt disabled cloak forever + if (other->NPC) { // permanently disable the saboteur's cloak other->NPC->aiFlags &= ~NPCAI_SHIELDS; } } @@ -560,26 +468,23 @@ void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3 // is it cheaper in bandwidth to just remove this ent and create a new // one, rather than changing the missile into the explosion? - //G_FreeEntity(ent); + // G_FreeEntity(ent); - if ( (other->takedamage && other->client ) || (ent->s.weapon == WP_FLECHETTE && other->contents&CONTENTS_LIGHTSABER) ) - { - G_AddEvent( ent, EV_MISSILE_HIT, DirToByte( normal ) ); + if ((other->takedamage && other->client) || (ent->s.weapon == WP_FLECHETTE && other->contents & CONTENTS_LIGHTSABER)) { + G_AddEvent(ent, EV_MISSILE_HIT, DirToByte(normal)); ent->s.otherEntityNum = other->s.number; - } - else - { - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( normal ) ); + } else { + G_AddEvent(ent, EV_MISSILE_MISS, DirToByte(normal)); ent->s.otherEntityNum = other->s.number; } - VectorCopy( normal, ent->pos1 ); + VectorCopy(normal, ent->pos1); - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - AddSoundEvent( ent->owner, ent->currentOrigin, 256, AEL_SUSPICIOUS, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75 ); + // Add the event + AddSoundEvent(ent->owner, ent->currentOrigin, 256, AEL_SUSPICIOUS, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75); } ent->freeAfterEvent = qtrue; @@ -587,106 +492,84 @@ void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3 // change over to a normal entity right at the point of impact ent->s.eType = ET_GENERAL; - //SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth - VectorCopy( impactPos, ent->s.pos.trBase ); + // SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth + VectorCopy(impactPos, ent->s.pos.trBase); - G_SetOrigin( ent, impactPos ); + G_SetOrigin(ent, impactPos); // splash damage (doesn't apply to person directly hit) - if ( ent->splashDamage ) - { - G_RadiusDamage( impactPos, ent->owner, ent->splashDamage, ent->splashRadius, - other, ent->splashMethodOfDeath ); + if (ent->splashDamage) { + G_RadiusDamage(impactPos, ent->owner, ent->splashDamage, ent->splashRadius, other, ent->splashMethodOfDeath); } - if ( ent->s.weapon == WP_NOGHRI_STICK ) - { - G_SpawnNoghriGasCloud( ent ); + if (ent->s.weapon == WP_NOGHRI_STICK) { + G_SpawnNoghriGasCloud(ent); } - gi.linkentity( ent ); + gi.linkentity(ent); } //------------------------------------------------ -static void G_MissileAddAlerts( gentity_t *ent ) -{ - //Add the event - if ( ent->s.weapon == WP_THERMAL && ((ent->delay-level.time) < 2000 || ent->s.pos.trType == TR_INTERPOLATE) ) - {//a thermal about to explode or rolling - if ( (ent->delay-level.time) < 500 ) - {//half a second before it explodes! - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER_GREAT, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER_GREAT, 20 ); +static void G_MissileAddAlerts(gentity_t *ent) { + // Add the event + if (ent->s.weapon == WP_THERMAL && ((ent->delay - level.time) < 2000 || ent->s.pos.trType == TR_INTERPOLATE)) { // a thermal about to explode or rolling + if ((ent->delay - level.time) < 500) { // half a second before it explodes! + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER_GREAT, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER_GREAT, 20); + } else { // 2 seconds until it explodes or it's rolling + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER, 20); } - else - {//2 seconds until it explodes or it's rolling - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, 20 ); - } - } - else - { - AddSoundEvent( ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED ); - AddSightEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 40 ); + } else { + AddSoundEvent(ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED); + AddSightEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 40); } } //------------------------------------------------------ -void G_MissileImpact( gentity_t *ent, trace_t *trace, int hitLoc=HL_NONE ) -{ - gentity_t *other; - vec3_t diff; +void G_MissileImpact(gentity_t *ent, trace_t *trace, int hitLoc = HL_NONE) { + gentity_t *other; + vec3_t diff; other = &g_entities[trace->entityNum]; - if ( other == ent ) - { - assert(0&&"missile hit itself!!!"); + if (other == ent) { + assert(0 && "missile hit itself!!!"); return; } - if ( trace->plane.normal[0] == 0.0f && - trace->plane.normal[1] == 0.0f && - trace->plane.normal[2] == 0.0f - ) - {//model moved into missile in flight probably... + if (trace->plane.normal[0] == 0.0f && trace->plane.normal[1] == 0.0f && trace->plane.normal[2] == 0.0f) { // model moved into missile in flight probably... trace->plane.normal[0] = -ent->s.pos.trDelta[0]; trace->plane.normal[1] = -ent->s.pos.trDelta[1]; trace->plane.normal[2] = -ent->s.pos.trDelta[2]; VectorNormalize(trace->plane.normal); } - if ( ent->owner && (other->takedamage||other->client) ) - { - if ( !ent->lastEnemy || ent->lastEnemy == ent->owner ) - {//a missile that was not reflected or, if so, still is owned by original owner - if( LogAccuracyHit( other, ent->owner ) ) - { + if (ent->owner && (other->takedamage || other->client)) { + if (!ent->lastEnemy || ent->lastEnemy == ent->owner) { // a missile that was not reflected or, if so, still is owned by original owner + if (LogAccuracyHit(other, ent->owner)) { ent->owner->client->ps.persistant[PERS_ACCURACY_HITS]++; } - if ( ent->owner->client && !ent->owner->s.number ) - { - if ( W_AccuracyLoggableWeapon( ent->s.weapon, qfalse, ent->methodOfDeath ) ) - { + if (ent->owner->client && !ent->owner->s.number) { + if (W_AccuracyLoggableWeapon(ent->s.weapon, qfalse, ent->methodOfDeath)) { ent->owner->client->sess.missionStats.hits++; } } } } // check for bounce - //OR: if the surfaceParm is has a reflect property (magnetic shielding) and the missile isn't an exploding missile - qboolean bounce = (qboolean)( (!other->takedamage && (ent->s.eFlags&(EF_BOUNCE|EF_BOUNCE_HALF))) || (((trace->surfaceFlags&SURF_FORCEFIELD)||(other->flags&FL_SHIELDED))&&!ent->splashDamage&&!ent->splashRadius&&ent->s.weapon != WP_NOGHRI_STICK) ); + // OR: if the surfaceParm is has a reflect property (magnetic shielding) and the missile isn't an exploding missile + qboolean bounce = (qboolean)((!other->takedamage && (ent->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF))) || + (((trace->surfaceFlags & SURF_FORCEFIELD) || (other->flags & FL_SHIELDED)) && !ent->splashDamage && !ent->splashRadius && + ent->s.weapon != WP_NOGHRI_STICK)); - if ( ent->dflags & DAMAGE_HEAVY_WEAP_CLASS ) - { + if (ent->dflags & DAMAGE_HEAVY_WEAP_CLASS) { // heavy class missiles generally never bounce. bounce = qfalse; } - if ( other->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED )) - { + if (other->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED)) { // Dumb assumption, but I guess we must be a shielded ion_cannon?? We should probably verify // if it's an ion_cannon that's Heavy Weapon only, we don't want to make it shielded do we...? - if ( (!strcmp( "misc_ion_cannon", other->classname )) && (other->flags & FL_SHIELDED) ) - { + if ((!strcmp("misc_ion_cannon", other->classname)) && (other->flags & FL_SHIELDED)) { // Anything will bounce off of us. bounce = qtrue; @@ -695,133 +578,117 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace, int hitLoc=HL_NONE ) } } - if ( ent->s.weapon == WP_DEMP2 ) - { + if (ent->s.weapon == WP_DEMP2) { // demp2 shots can never bounce bounce = qfalse; // in fact, alt-charge shots will not call the regular impact functions - if ( ent->alt_fire ) - { + if (ent->alt_fire) { // detonate at the trace end - VectorCopy( trace->endpos, ent->currentOrigin ); - VectorCopy( trace->plane.normal, ent->pos1 ); - DEMP2_AltDetonate( ent ); + VectorCopy(trace->endpos, ent->currentOrigin); + VectorCopy(trace->plane.normal, ent->pos1); + DEMP2_AltDetonate(ent); return; } } - if ( bounce ) - { + if (bounce) { // Check to see if there is a bounce count - if ( ent->bounceCount ) - { + if (ent->bounceCount) { // decrement number of bounces and then see if it should be done bouncing - if ( !(--ent->bounceCount) ) { + if (!(--ent->bounceCount)) { // He (or she) will bounce no more (after this current bounce, that is). - ent->s.eFlags &= ~( EF_BOUNCE | EF_BOUNCE_HALF ); + ent->s.eFlags &= ~(EF_BOUNCE | EF_BOUNCE_HALF); } } - if ( other->NPC ) - { - G_Damage( other, ent, ent->owner, ent->currentOrigin, ent->s.pos.trDelta, 0, DAMAGE_NO_DAMAGE, MOD_UNKNOWN ); + if (other->NPC) { + G_Damage(other, ent, ent->owner, ent->currentOrigin, ent->s.pos.trDelta, 0, DAMAGE_NO_DAMAGE, MOD_UNKNOWN); } - G_BounceMissile( ent, trace ); + G_BounceMissile(ent, trace); - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->owner) //&& ent->owner->s.number == 0 ) { - G_MissileAddAlerts( ent ); + G_MissileAddAlerts(ent); } - G_MissileBounceEffect( ent, trace->endpos, trace->plane.normal, (qboolean)(trace->entityNum==ENTITYNUM_WORLD) ); + G_MissileBounceEffect(ent, trace->endpos, trace->plane.normal, (qboolean)(trace->entityNum == ENTITYNUM_WORLD)); return; } // I would glom onto the EF_BOUNCE code section above, but don't feel like risking breaking something else - if ( (!other->takedamage && ( ent->s.eFlags&(EF_BOUNCE_SHRAPNEL) ) ) - || ((trace->surfaceFlags&SURF_FORCEFIELD)&&!ent->splashDamage&&!ent->splashRadius) ) - { - if ( !(other->contents&CONTENTS_LIGHTSABER) - || g_spskill->integer <= 0//on easy, it reflects all shots - || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 )//on medium it won't reflect flechette or demp shots - || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && ent->s.weapon != WP_REPEATER )//on hard it won't reflect flechette, demp, repeater or bowcaster shots - ) - { - G_BounceMissile( ent, trace ); - - if ( --ent->bounceCount < 0 ) - { + if ((!other->takedamage && (ent->s.eFlags & (EF_BOUNCE_SHRAPNEL))) || + ((trace->surfaceFlags & SURF_FORCEFIELD) && !ent->splashDamage && !ent->splashRadius)) { + if (!(other->contents & CONTENTS_LIGHTSABER) || g_spskill->integer <= 0 // on easy, it reflects all shots + || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2) // on medium it won't reflect flechette or demp shots + || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && + ent->s.weapon != WP_REPEATER) // on hard it won't reflect flechette, demp, repeater or bowcaster shots + ) { + G_BounceMissile(ent, trace); + + if (--ent->bounceCount < 0) { ent->s.eFlags &= ~EF_BOUNCE_SHRAPNEL; } - G_MissileBounceEffect( ent, trace->endpos, trace->plane.normal, (qboolean)(trace->entityNum==ENTITYNUM_WORLD) ); + G_MissileBounceEffect(ent, trace->endpos, trace->plane.normal, (qboolean)(trace->entityNum == ENTITYNUM_WORLD)); return; } } - if ( (!other->takedamage || (other->client && other->health <= 0)) - && ent->s.weapon == WP_THERMAL - && !ent->alt_fire ) - {//rolling thermal det - FIXME: make this an eFlag like bounce & stick!!! - //G_BounceRollMissile( ent, trace ); - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if ((!other->takedamage || (other->client && other->health <= 0)) && ent->s.weapon == WP_THERMAL && + !ent->alt_fire) { // rolling thermal det - FIXME: make this an eFlag like bounce & stick!!! + // G_BounceRollMissile( ent, trace ); + if (ent->owner) //&& ent->owner->s.number == 0 ) { - G_MissileAddAlerts( ent ); + G_MissileAddAlerts(ent); } - //gi.linkentity( ent ); + // gi.linkentity( ent ); return; } // check for sticking - if ( ent->s.eFlags & EF_MISSILE_STICK ) - { - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->s.eFlags & EF_MISSILE_STICK) { + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - if ( ent->s.weapon == WP_TRIP_MINE ) - { - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius/2, AEL_DISCOVERED/*AEL_DANGER*/, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DISCOVERED/*AEL_DANGER*/, 60 ); + // Add the event + if (ent->s.weapon == WP_TRIP_MINE) { + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius / 2, AEL_DISCOVERED /*AEL_DANGER*/, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DISCOVERED /*AEL_DANGER*/, 60); /* AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, qfalse, qtrue ); AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, 60 ); */ - } - else - { - AddSoundEvent( ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue ); - AddSightEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 10 ); + } else { + AddSoundEvent(ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue); + AddSightEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 10); } } - G_MissileStick( ent, other, trace ); + G_MissileStick(ent, other, trace); return; } -extern bool WP_DoingMoronicForcedAnimationForForcePowers(gentity_t *ent); + extern bool WP_DoingMoronicForcedAnimationForForcePowers(gentity_t * ent); // check for hitting a lightsaber - if ( other->contents & CONTENTS_LIGHTSABER ) - { - if ( other->owner && !other->owner->s.number && other->owner->client ) - { + if (other->contents & CONTENTS_LIGHTSABER) { + if (other->owner && !other->owner->s.number && other->owner->client) { other->owner->client->sess.missionStats.saberBlocksCnt++; } - if ( ( g_spskill->integer <= 0//on easy, it reflects all shots - || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 )//on medium it won't reflect flechette or demp shots - || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && ent->s.weapon != WP_REPEATER )//on hard it won't reflect flechette, demp, repeater or bowcaster shots - ) - && (!ent->splashDamage || !ent->splashRadius) //this would be cool, though, to "bat" the thermal det away... - && ent->s.weapon != WP_NOGHRI_STICK )//gas bomb, don't reflect + if ((g_spskill->integer <= 0 // on easy, it reflects all shots + || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2) // on medium it won't reflect flechette or demp shots + || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && + ent->s.weapon != WP_REPEATER) // on hard it won't reflect flechette, demp, repeater or bowcaster shots + ) && + (!ent->splashDamage || !ent->splashRadius) // this would be cool, though, to "bat" the thermal det away... + && ent->s.weapon != WP_NOGHRI_STICK) // gas bomb, don't reflect { - //FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? - if ( !other->owner || !other->owner->client || other->owner->client->ps.saberInFlight - || (InFront( ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, SABER_REFLECT_MISSILE_CONE ) && - !WP_DoingMoronicForcedAnimationForForcePowers(other)) )//other->owner->s.number != 0 || - {//Jedi cannot block shots from behind! + // FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? + if (!other->owner || !other->owner->client || other->owner->client->ps.saberInFlight || + (InFront(ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, SABER_REFLECT_MISSILE_CONE) && + !WP_DoingMoronicForcedAnimationForForcePowers(other))) // other->owner->s.number != 0 || + { // Jedi cannot block shots from behind! int blockChance = 0; - switch ( other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) - {//level 1 reflects 50% of the time, level 2 reflects 75% of the time + switch (other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) { // level 1 reflects 50% of the time, level 2 reflects 75% of the time case FORCE_LEVEL_3: blockChance = 10; break; @@ -832,34 +699,29 @@ extern bool WP_DoingMoronicForcedAnimationForForcePowers(gentity_t *ent); blockChance = 1; break; } - if ( blockChance && (other->owner->client->ps.forcePowersActive&(1<owner->client->ps.forcePowerLevel[FP_SPEED]*2; + if (blockChance && (other->owner->client->ps.forcePowersActive & (1 << FP_SPEED))) { // in in force speed, better chance of deflecting the shot + blockChance += other->owner->client->ps.forcePowerLevel[FP_SPEED] * 2; } - if ( Q_irand( 0, blockChance ) ) - { + if (Q_irand(0, blockChance)) { VectorSubtract(ent->currentOrigin, other->currentOrigin, diff); VectorNormalize(diff); - G_ReflectMissile( other, ent, diff); - if ( other->owner && other->owner->client ) - { + G_ReflectMissile(other, ent, diff); + if (other->owner && other->owner->client) { other->owner->client->ps.saberEventFlags |= SEF_DEFLECTED; } - //do the effect - VectorCopy( ent->s.pos.trDelta, diff ); - VectorNormalize( diff ); - G_MissileReflectEffect( ent, trace->endpos, trace->plane.normal ); + // do the effect + VectorCopy(ent->s.pos.trDelta, diff); + VectorNormalize(diff); + G_MissileReflectEffect(ent, trace->endpos, trace->plane.normal); return; } } - } - else - {//still do the bounce effect - G_MissileReflectEffect( ent, trace->endpos, trace->plane.normal ); + } else { // still do the bounce effect + G_MissileReflectEffect(ent, trace->endpos, trace->plane.normal); } } - G_MissileImpacted( ent, other, trace->endpos, trace->plane.normal, hitLoc ); + G_MissileImpacted(ent, other, trace->endpos, trace->plane.normal, hitLoc); } /* @@ -869,60 +731,53 @@ G_ExplodeMissile Explode a missile without an impact ================ */ -void G_ExplodeMissile( gentity_t *ent ) -{ - vec3_t dir; - vec3_t origin; +void G_ExplodeMissile(gentity_t *ent) { + vec3_t dir; + vec3_t origin; - EvaluateTrajectory( &ent->s.pos, level.time, origin ); - SnapVector( origin ); - G_SetOrigin( ent, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); + SnapVector(origin); + G_SetOrigin(ent, origin); // we don't have a valid direction, so just point straight up dir[0] = dir[1] = 0; dir[2] = 1; - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - AddSoundEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, qfalse, qtrue );//FIXME: are we on ground or not? - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 100 ); + // Add the event + AddSoundEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, qfalse, qtrue); // FIXME: are we on ground or not? + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 100); } -/* ent->s.eType = ET_GENERAL; - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); + /* ent->s.eType = ET_GENERAL; + G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); - ent->freeAfterEvent = qtrue;*/ + ent->freeAfterEvent = qtrue;*/ // splash damage - if ( ent->splashDamage ) - { - G_RadiusDamage( ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL - , ent->splashMethodOfDeath ); + if (ent->splashDamage) { + G_RadiusDamage(ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, ent->splashMethodOfDeath); } G_FreeEntity(ent); - //gi.linkentity( ent ); + // gi.linkentity( ent ); } - -void G_RunStuckMissile( gentity_t *ent ) -{ - if ( ent->takedamage ) - { - if ( ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD ) - { +void G_RunStuckMissile(gentity_t *ent) { + if (ent->takedamage) { + if (ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD) { gentity_t *other = &g_entities[ent->s.groundEntityNum]; - if ( (!VectorCompare( vec3_origin, other->s.pos.trDelta ) && other->s.pos.trType != TR_STATIONARY) || - (!VectorCompare( vec3_origin, other->s.apos.trDelta ) && other->s.apos.trType != TR_STATIONARY) ) - {//thing I stuck to is moving or rotating now, kill me - G_Damage( ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH ); + if ((!VectorCompare(vec3_origin, other->s.pos.trDelta) && other->s.pos.trType != TR_STATIONARY) || + (!VectorCompare(vec3_origin, other->s.apos.trDelta) && + other->s.apos.trType != TR_STATIONARY)) { // thing I stuck to is moving or rotating now, kill me + G_Damage(ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH); return; } } } // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -932,45 +787,40 @@ G_GroundTrace ================== */ -int G_GroundTrace( gentity_t *ent, pml_t *pPml ) -{ - vec3_t point; - trace_t trace; +int G_GroundTrace(gentity_t *ent, pml_t *pPml) { + vec3_t point; + trace_t trace; point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; point[2] = ent->currentOrigin[2] - 0.25; - gi.trace ( &trace, ent->currentOrigin, ent->mins, ent->maxs, point, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, point, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); pPml->groundTrace = trace; // do something corrective if the trace starts in a solid... - if ( trace.allsolid ) - { + if (trace.allsolid) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } // if the trace didn't hit anything, we are in free fall - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } // check if getting thrown off the ground - if ( ent->s.pos.trDelta[2] > 0 && DotProduct( ent->s.pos.trDelta, trace.plane.normal ) > 10 ) - { + if (ent->s.pos.trDelta[2] > 0 && DotProduct(ent->s.pos.trDelta, trace.plane.normal) > 10) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } // slopes that are too steep will not be considered onground - if ( trace.plane.normal[2] < MIN_WALK_NORMAL ) - { + if (trace.plane.normal[2] < MIN_WALK_NORMAL) { pPml->groundPlane = qtrue; pPml->walking = qfalse; return ENTITYNUM_NONE; @@ -989,23 +839,21 @@ int G_GroundTrace( gentity_t *ent, pml_t *pPml ) return trace.entityNum; } -void G_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) -{ - float backoff; - float change; - int i; +void G_ClipVelocity(vec3_t in, vec3_t normal, vec3_t out, float overbounce) { + float backoff; + float change; + int i; - backoff = DotProduct (in, normal); + backoff = DotProduct(in, normal); - if ( backoff < 0 ) { + if (backoff < 0) { backoff *= overbounce; } else { backoff /= overbounce; } - for ( i=0 ; i<3 ; i++ ) - { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; out[i] = in[i] - change; } } @@ -1024,59 +872,54 @@ Also gets stuck inside thrower if looking down when thrown ================== */ -#define MAX_CLIP_PLANES 5 -#define BUMPCLIP 1.5f -void G_RollMissile( gentity_t *ent ) -{ - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity; - vec3_t clipVelocity; - int i, j, k; - trace_t trace; - vec3_t end; - float time_left; - float into; - vec3_t endVelocity; - vec3_t endClipVelocity; - pml_t objPML; - float bounceAmt = BUMPCLIP; - gentity_t *hitEnt = NULL; - - memset( &objPML, 0, sizeof( objPML ) ); - - G_GroundTrace( ent, &objPML ); - - objPML.frametime = (level.time - level.previousTime)*0.001; +#define MAX_CLIP_PLANES 5 +#define BUMPCLIP 1.5f +void G_RollMissile(gentity_t *ent) { + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity; + vec3_t clipVelocity; + int i, j, k; + trace_t trace; + vec3_t end; + float time_left; + float into; + vec3_t endVelocity; + vec3_t endClipVelocity; + pml_t objPML; + float bounceAmt = BUMPCLIP; + gentity_t *hitEnt = NULL; + + memset(&objPML, 0, sizeof(objPML)); + + G_GroundTrace(ent, &objPML); + + objPML.frametime = (level.time - level.previousTime) * 0.001; numbumps = 4; - VectorCopy ( ent->s.pos.trDelta, primal_velocity ); + VectorCopy(ent->s.pos.trDelta, primal_velocity); - VectorCopy( ent->s.pos.trDelta, endVelocity ); + VectorCopy(ent->s.pos.trDelta, endVelocity); endVelocity[2] -= g_gravity->value * objPML.frametime; - ent->s.pos.trDelta[2] = ( ent->s.pos.trDelta[2] + endVelocity[2] ) * 0.5; + ent->s.pos.trDelta[2] = (ent->s.pos.trDelta[2] + endVelocity[2]) * 0.5; primal_velocity[2] = endVelocity[2]; - if ( objPML.groundPlane ) - {//FIXME: never happens! + if (objPML.groundPlane) { // FIXME: never happens! // slide along the ground plane - G_ClipVelocity( ent->s.pos.trDelta, objPML.groundTrace.plane.normal, ent->s.pos.trDelta, BUMPCLIP ); - VectorScale( ent->s.pos.trDelta, 0.9f, ent->s.pos.trDelta ); + G_ClipVelocity(ent->s.pos.trDelta, objPML.groundTrace.plane.normal, ent->s.pos.trDelta, BUMPCLIP); + VectorScale(ent->s.pos.trDelta, 0.9f, ent->s.pos.trDelta); } time_left = objPML.frametime; // never turn against the ground plane - if ( objPML.groundPlane ) - { + if (objPML.groundPlane) { numplanes = 1; - VectorCopy( objPML.groundTrace.plane.normal, planes[0] ); - } - else - { + VectorCopy(objPML.groundTrace.plane.normal, planes[0]); + } else { numplanes = 0; } @@ -1086,55 +929,48 @@ void G_RollMissile( gentity_t *ent ) numplanes++; */ - for ( bumpcount = 0; bumpcount < numbumps; bumpcount++ ) - { + for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { // calculate position we are trying to move to - VectorMA( ent->currentOrigin, time_left, ent->s.pos.trDelta, end ); + VectorMA(ent->currentOrigin, time_left, ent->s.pos.trDelta, end); // see if we can make it there - gi.trace ( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10 ); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10); - //TEMP HACK: - //had to move this up above the trace.allsolid check now that for some reason ghoul2 impacts tell me I'm allsolid?! - //this needs to be fixed, really - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit another ent + // TEMP HACK: + // had to move this up above the trace.allsolid check now that for some reason ghoul2 impacts tell me I'm allsolid?! + // this needs to be fixed, really + if (trace.entityNum < ENTITYNUM_WORLD) { // hit another ent hitEnt = &g_entities[trace.entityNum]; - if ( hitEnt && (hitEnt->takedamage || (hitEnt->contents&CONTENTS_LIGHTSABER) ) ) - { - G_MissileImpact( ent, &trace ); - if ( ent->s.eType == ET_GENERAL ) - {//exploded + if (hitEnt && (hitEnt->takedamage || (hitEnt->contents & CONTENTS_LIGHTSABER))) { + G_MissileImpact(ent, &trace); + if (ent->s.eType == ET_GENERAL) { // exploded return; } } } - if ( trace.allsolid ) - { + if (trace.allsolid) { // entity is completely trapped in another solid - //FIXME: this happens a lot now when we hit a G2 ent... WTF? - ent->s.pos.trDelta[2] = 0; // don't build up falling damage, but allow sideways acceleration - return;// qtrue; + // FIXME: this happens a lot now when we hit a G2 ent... WTF? + ent->s.pos.trDelta[2] = 0; // don't build up falling damage, but allow sideways acceleration + return; // qtrue; } - if ( trace.fraction > 0 ) - { + if (trace.fraction > 0) { // actually covered some distance - VectorCopy( trace.endpos, ent->currentOrigin ); + VectorCopy(trace.endpos, ent->currentOrigin); } - if ( trace.fraction == 1 ) - { - break; // moved the entire distance + if (trace.fraction == 1) { + break; // moved the entire distance } - //pm->ps->pm_flags |= PMF_BUMPED; + // pm->ps->pm_flags |= PMF_BUMPED; // save entity for contact - //PM_AddTouchEnt( trace.entityNum ); + // PM_AddTouchEnt( trace.entityNum ); - //Hit it + // Hit it /* if ( PM_ClientImpact( trace.entityNum, qtrue ) ) { @@ -1144,11 +980,10 @@ void G_RollMissile( gentity_t *ent ) time_left -= time_left * trace.fraction; - if ( numplanes >= MAX_CLIP_PLANES ) - { + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen - VectorClear( ent->s.pos.trDelta ); - return;// qtrue; + VectorClear(ent->s.pos.trDelta); + return; // qtrue; } // @@ -1156,114 +991,98 @@ void G_RollMissile( gentity_t *ent ) // out along it, which fixes some epsilon issues with // non-axial planes // - for ( i = 0 ; i < numplanes ; i++ ) - { - if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) - { - VectorAdd( trace.plane.normal, ent->s.pos.trDelta, ent->s.pos.trDelta ); + for (i = 0; i < numplanes; i++) { + if (DotProduct(trace.plane.normal, planes[i]) > 0.99) { + VectorAdd(trace.plane.normal, ent->s.pos.trDelta, ent->s.pos.trDelta); break; } } - if ( i < numplanes ) - { + if (i < numplanes) { continue; } - VectorCopy( trace.plane.normal, planes[numplanes] ); + VectorCopy(trace.plane.normal, planes[numplanes]); numplanes++; // // modify velocity so it parallels all of the clip planes // - if ( g_entities[trace.entityNum].inuse && g_entities[trace.entityNum].client ) - {//hit a person, bounce off much less + if (g_entities[trace.entityNum].inuse && g_entities[trace.entityNum].client) { // hit a person, bounce off much less bounceAmt = OVERCLIP; - } - else - { + } else { bounceAmt = BUMPCLIP; } // find a plane that it enters - for ( i = 0 ; i < numplanes ; i++ ) - { - into = DotProduct( ent->s.pos.trDelta, planes[i] ); - if ( into >= 0.1 ) - { - continue; // move doesn't interact with the plane + for (i = 0; i < numplanes; i++) { + into = DotProduct(ent->s.pos.trDelta, planes[i]); + if (into >= 0.1) { + continue; // move doesn't interact with the plane } // see how hard we are hitting things - if ( -into > pml.impactSpeed ) - { + if (-into > pml.impactSpeed) { pml.impactSpeed = -into; } // slide along the plane - G_ClipVelocity( ent->s.pos.trDelta, planes[i], clipVelocity, bounceAmt ); + G_ClipVelocity(ent->s.pos.trDelta, planes[i], clipVelocity, bounceAmt); // slide along the plane - G_ClipVelocity( endVelocity, planes[i], endClipVelocity, bounceAmt ); + G_ClipVelocity(endVelocity, planes[i], endClipVelocity, bounceAmt); // see if there is a second plane that the new move enters - for ( j = 0 ; j < numplanes ; j++ ) - { - if ( j == i ) - { + for (j = 0; j < numplanes; j++) { + if (j == i) { continue; } - if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) - { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[j]) >= 0.1) { + continue; // move doesn't interact with the plane } // try clipping the move to the plane - G_ClipVelocity( clipVelocity, planes[j], clipVelocity, bounceAmt ); - G_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, bounceAmt ); + G_ClipVelocity(clipVelocity, planes[j], clipVelocity, bounceAmt); + G_ClipVelocity(endClipVelocity, planes[j], endClipVelocity, bounceAmt); // see if it goes back into the first clip plane - if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) - { + if (DotProduct(clipVelocity, planes[i]) >= 0) { continue; } // slide the original velocity along the crease - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, ent->s.pos.trDelta ); - VectorScale( dir, d, clipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, ent->s.pos.trDelta); + VectorScale(dir, d, clipVelocity); - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, endVelocity ); - VectorScale( dir, d, endClipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, endVelocity); + VectorScale(dir, d, endClipVelocity); // see if there is a third plane the the new move enters - for ( k = 0 ; k < numplanes ; k++ ) - { - if ( k == i || k == j ) - { + for (k = 0; k < numplanes; k++) { + if (k == i || k == j) { continue; } - if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) - { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[k]) >= 0.1) { + continue; // move doesn't interact with the plane } // stop dead at a triple plane interaction - VectorClear( ent->s.pos.trDelta ); - return;// qtrue; + VectorClear(ent->s.pos.trDelta); + return; // qtrue; } } // if we have fixed all interactions, try another move - VectorCopy( clipVelocity, ent->s.pos.trDelta ); - VectorCopy( endClipVelocity, endVelocity ); + VectorCopy(clipVelocity, ent->s.pos.trDelta); + VectorCopy(endClipVelocity, endVelocity); break; } - VectorScale( endVelocity, 0.975f, endVelocity ); + VectorScale(endVelocity, 0.975f, endVelocity); } - VectorCopy( endVelocity, ent->s.pos.trDelta ); + VectorCopy(endVelocity, ent->s.pos.trDelta); // don't change velocity if in a timer (FIXME: is this correct?) /* @@ -1273,7 +1092,7 @@ void G_RollMissile( gentity_t *ent ) } */ - return;// ( bumpcount != 0 ); + return; // ( bumpcount != 0 ); } /* ================ @@ -1281,163 +1100,143 @@ G_RunMissile ================ */ -void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); -void G_RunMissile( gentity_t *ent ) -{ - vec3_t oldOrg; - trace_t tr; - int trHitLoc=HL_NONE; - - if ( (ent->s.eFlags&EF_HELD_BY_SAND_CREATURE) ) - {//in a sand creature's mouth - if ( ent->activator ) - { - mdxaBone_t boltMatrix; +void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg); +void G_RunMissile(gentity_t *ent) { + vec3_t oldOrg; + trace_t tr; + int trHitLoc = HL_NONE; + + if ((ent->s.eFlags & EF_HELD_BY_SAND_CREATURE)) { // in a sand creature's mouth + if (ent->activator) { + mdxaBone_t boltMatrix; // Getting the bolt here - //in hand + // in hand vec3_t scAngles = {0}; scAngles[YAW] = ent->activator->currentAngles[YAW]; - gi.G2API_GetBoltMatrix( ent->activator->ghoul2, ent->activator->playerModel, ent->activator->gutBolt, - &boltMatrix, scAngles, ent->activator->currentOrigin, (cg.time?cg.time:level.time), - NULL, ent->activator->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->activator->ghoul2, ent->activator->playerModel, ent->activator->gutBolt, &boltMatrix, scAngles, + ent->activator->currentOrigin, (cg.time ? cg.time : level.time), NULL, ent->activator->s.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->currentOrigin ); - G_SetOrigin( ent, ent->currentOrigin ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->currentOrigin); + G_SetOrigin(ent, ent->currentOrigin); } // check think function - G_RunThink( ent ); + G_RunThink(ent); return; } - VectorCopy( ent->currentOrigin, oldOrg ); + VectorCopy(ent->currentOrigin, oldOrg); // get current position - if ( ent->s.pos.trType == TR_INTERPOLATE ) - {//rolling missile? - //FIXME: WTF?!! Sticks to stick missiles? - //FIXME: they stick inside the player - G_RollMissile( ent ); - if ( ent->s.eType != ET_GENERAL ) - {//didn't explode - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - gi.trace( &tr, oldOrg, ent->mins, ent->maxs, ent->currentOrigin, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10 ); - if ( VectorCompare( ent->s.pos.trDelta, vec3_origin ) ) - { - //VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); - } - else - { - vec3_t ang, fwdDir, rtDir; - float speed; + if (ent->s.pos.trType == TR_INTERPOLATE) { // rolling missile? + // FIXME: WTF?!! Sticks to stick missiles? + // FIXME: they stick inside the player + G_RollMissile(ent); + if (ent->s.eType != ET_GENERAL) { // didn't explode + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + gi.trace(&tr, oldOrg, ent->mins, ent->maxs, ent->currentOrigin, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10); + if (VectorCompare(ent->s.pos.trDelta, vec3_origin)) { + // VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorClear(ent->s.apos.trDelta); + } else { + vec3_t ang, fwdDir, rtDir; + float speed; ent->s.apos.trType = TR_INTERPOLATE; - VectorSet( ang, 0, ent->s.apos.trBase[1], 0 ); - AngleVectors( ang, fwdDir, rtDir, NULL ); - speed = VectorLength( ent->s.pos.trDelta )*4; + VectorSet(ang, 0, ent->s.apos.trBase[1], 0); + AngleVectors(ang, fwdDir, rtDir, NULL); + speed = VectorLength(ent->s.pos.trDelta) * 4; - //HMM, this works along an axis-aligned dir, but not along diagonals - //This is because when roll gets to 90, pitch becomes yaw, and vice-versa - //Maybe need to just set the angles directly? - ent->s.apos.trDelta[0] = DotProduct( fwdDir, ent->s.pos.trDelta ); - ent->s.apos.trDelta[1] = 0;//never spin! - ent->s.apos.trDelta[2] = DotProduct( rtDir, ent->s.pos.trDelta ); + // HMM, this works along an axis-aligned dir, but not along diagonals + // This is because when roll gets to 90, pitch becomes yaw, and vice-versa + // Maybe need to just set the angles directly? + ent->s.apos.trDelta[0] = DotProduct(fwdDir, ent->s.pos.trDelta); + ent->s.apos.trDelta[1] = 0; // never spin! + ent->s.apos.trDelta[2] = DotProduct(rtDir, ent->s.pos.trDelta); - VectorNormalize( ent->s.apos.trDelta ); - VectorScale( ent->s.apos.trDelta, speed, ent->s.apos.trDelta ); + VectorNormalize(ent->s.apos.trDelta); + VectorScale(ent->s.apos.trDelta, speed, ent->s.apos.trDelta); ent->s.apos.trTime = level.previousTime; } } - } - else - { - vec3_t origin; - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + } else { + vec3_t origin; + EvaluateTrajectory(&ent->s.pos, level.time, origin); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_COLLIDE, 10 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_COLLIDE, 10); - if ( tr.entityNum != ENTITYNUM_NONE ) - { + if (tr.entityNum != ENTITYNUM_NONE) { gentity_t *other = &g_entities[tr.entityNum]; // check for hitting a lightsaber - if ( other->contents & CONTENTS_LIGHTSABER ) - {//hit a lightsaber bbox - if ( other->owner - && other->owner->client - && !other->owner->client->ps.saberInFlight - && ( Q_irand( 0, (other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]*other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) ) == 0 - || !InFront( ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, SABER_REFLECT_MISSILE_CONE ) ) )//other->owner->s.number == 0 && - {//Jedi cannot block shots from behind! - //re-trace from here, ignoring the lightsaber - gi.trace( &tr, tr.endpos, ent->mins, ent->maxs, origin, tr.entityNum, ent->clipmask, G2_RETURNONHIT, 10 ); + if (other->contents & CONTENTS_LIGHTSABER) { // hit a lightsaber bbox + if (other->owner && other->owner->client && !other->owner->client->ps.saberInFlight && + (Q_irand(0, (other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] * other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE])) == + 0 || + !InFront(ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, + SABER_REFLECT_MISSILE_CONE))) // other->owner->s.number == 0 && + { // Jedi cannot block shots from behind! + // re-trace from here, ignoring the lightsaber + gi.trace(&tr, tr.endpos, ent->mins, ent->maxs, origin, tr.entityNum, ent->clipmask, G2_RETURNONHIT, 10); } } } - VectorCopy( tr.endpos, ent->currentOrigin ); + VectorCopy(tr.endpos, ent->currentOrigin); } // get current angles - VectorMA( ent->s.apos.trBase, (level.time - ent->s.apos.trTime) * 0.001, ent->s.apos.trDelta, ent->s.apos.trBase ); + VectorMA(ent->s.apos.trBase, (level.time - ent->s.apos.trTime) * 0.001, ent->s.apos.trDelta, ent->s.apos.trBase); - //FIXME: Rolling things hitting G2 polys is weird + // FIXME: Rolling things hitting G2 polys is weird /////////////////////////////////////////////////////// -//? if ( tr.fraction != 1 ) + //? if ( tr.fraction != 1 ) { - // did we hit or go near a Ghoul2 model? -// qboolean hitModel = qfalse; - for (int i=0; i < MAX_G2_COLLISIONS; i++) - { - if (tr.G2CollisionMap[i].mEntityNum == -1) - { + // did we hit or go near a Ghoul2 model? + // qboolean hitModel = qfalse; + for (int i = 0; i < MAX_G2_COLLISIONS; i++) { + if (tr.G2CollisionMap[i].mEntityNum == -1) { break; } CCollisionRecord &coll = tr.G2CollisionMap[i]; - gentity_t *hitEnt = &g_entities[coll.mEntityNum]; + gentity_t *hitEnt = &g_entities[coll.mEntityNum]; // process collision records here... // make sure we only do this once, not for all the entrance wounds we might generate - if ((coll.mFlags & G2_FRONTFACE)/* && !(hitModel)*/ && hitEnt->health) - { - if (trHitLoc==HL_NONE) - { - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &trHitLoc, coll.mCollisionPosition, NULL, NULL, ent->methodOfDeath ); + if ((coll.mFlags & G2_FRONTFACE) /* && !(hitModel)*/ && hitEnt->health) { + if (trHitLoc == HL_NONE) { + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &trHitLoc, + coll.mCollisionPosition, NULL, NULL, ent->methodOfDeath); } break; // NOTE: the way this whole section was working, it would only get inside of this IF once anyway, might as well break out now } } } -///////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////// - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( ent ); + gi.linkentity(ent); - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//stuck missiles should check some special stuff - G_RunStuckMissile( ent ); + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // stuck missiles should check some special stuff + G_RunStuckMissile(ent); return; } // check think function - G_RunThink( ent ); + G_RunThink(ent); - if ( ent->s.eType != ET_MISSILE ) - { - return; // exploded + if (ent->s.eType != ET_MISSILE) { + return; // exploded } - if ( ent->mass ) - { - G_MoverTouchPushTriggers( ent, oldOrg ); + if (ent->mass) { + G_MoverTouchPushTriggers(ent, oldOrg); } /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) ) @@ -1454,48 +1253,35 @@ void G_RunMissile( gentity_t *ent ) } */ - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75 );//wakes them up when see a shot passes in front of them - if ( !Q_irand( 0, 10 ) ) - {//not so often... - if ( ent->splashDamage && ent->splashRadius ) - {//I'm an exploder, let people around me know danger is coming - if ( ent->s.weapon == WP_TRIP_MINE ) - {//??? - } - else - { - if ( ent->s.weapon == WP_ROCKET_LAUNCHER && ent->e_ThinkFunc == thinkF_rocketThink ) - {//homing rocket- run like hell! - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER_GREAT, 50 ); - } - else - { - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER, 50 ); + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75); // wakes them up when see a shot passes in front of them + if (!Q_irand(0, 10)) { // not so often... + if (ent->splashDamage && ent->splashRadius) { // I'm an exploder, let people around me know danger is coming + if (ent->s.weapon == WP_TRIP_MINE) { //??? + } else { + if (ent->s.weapon == WP_ROCKET_LAUNCHER && ent->e_ThinkFunc == thinkF_rocketThink) { // homing rocket- run like hell! + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER_GREAT, 50); + } else { + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER, 50); } - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER ); + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER); } - } - else - {//makes them run from near misses - AddSightEvent( ent->owner, ent->currentOrigin, 48, AEL_DANGER, 50 ); + } else { // makes them run from near misses + AddSightEvent(ent->owner, ent->currentOrigin, 48, AEL_DANGER, 50); } } - if ( tr.fraction == 1 ) - { - if ( ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_INTERPOLATE ) - {//a rolling thermal that didn't hit anything - G_MissileAddAlerts( ent ); + if (tr.fraction == 1) { + if (ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_INTERPOLATE) { // a rolling thermal that didn't hit anything + G_MissileAddAlerts(ent); } return; } // never explode or bounce on sky - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { - G_FreeEntity( ent ); + if (tr.surfaceFlags & SURF_NOIMPACT) { + G_FreeEntity(ent); return; } - G_MissileImpact( ent, &tr, trHitLoc ); + G_MissileImpact(ent, &tr, trHitLoc); } diff --git a/code/game/g_mover.cpp b/code/game/g_mover.cpp index 47919bd955..cb7e531a79 100644 --- a/code/game/g_mover.cpp +++ b/code/game/g_mover.cpp @@ -29,14 +29,13 @@ along with this program; if not, see . #include "../icarus/IcarusInterface.h" +int BMS_START = 0; +int BMS_MID = 1; +int BMS_END = 2; -int BMS_START = 0; -int BMS_MID = 1; -int BMS_END = 2; - -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ); -void InitMover( gentity_t *ent ) ; +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +void CalcTeamDoorCenter(gentity_t *ent, vec3_t center); +void InitMover(gentity_t *ent); /* =============================================================================== @@ -46,17 +45,16 @@ PUSHMOVE =============================================================================== */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ); +void MatchTeam(gentity_t *teamLeader, int moverState, int time); extern qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2); typedef struct { - gentity_t *ent; - vec3_t origin; - vec3_t angles; - float deltayaw; + gentity_t *ent; + vec3_t origin; + vec3_t angles; + float deltayaw; } pushed_t; -pushed_t pushed[MAX_GENTITIES], *pushed_p; - +pushed_t pushed[MAX_GENTITIES], *pushed_p; /* ------------------------- @@ -64,15 +62,13 @@ G_SetLoopSound ------------------------- */ -void G_PlayDoorLoopSound( gentity_t *ent ) -{ - if ( VALIDSTRING( ent->soundSet ) == false ) +void G_PlayDoorLoopSound(gentity_t *ent) { + if (VALIDSTRING(ent->soundSet) == false) return; - sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + sfxHandle_t sfx = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( sfx == -1 ) - { + if (sfx == -1) { ent->s.loopSound = 0; return; } @@ -86,24 +82,22 @@ G_PlayDoorSound ------------------------- */ -void G_PlayDoorSound( gentity_t *ent, int type ) -{ - if ( VALIDSTRING( ent->soundSet ) == false ) +void G_PlayDoorSound(gentity_t *ent, int type) { + if (VALIDSTRING(ent->soundSet) == false) return; - sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, type ); + sfxHandle_t sfx = CAS_GetBModelSound(ent->soundSet, type); - if ( sfx == -1 ) + if (sfx == -1) return; - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSoundEvent( ent->activator, doorcenter, 128, AEL_MINOR, qfalse, qtrue ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSoundEvent(ent->activator, doorcenter, 128, AEL_MINOR, qfalse, qtrue); } - G_AddEvent( ent, EV_BMODEL_SOUND, sfx ); + G_AddEvent(ent, EV_BMODEL_SOUND, sfx); } /* @@ -112,41 +106,33 @@ G_TestEntityPosition ============ */ -gentity_t *G_TestEntityPosition( gentity_t *ent ) { - trace_t tr; - int mask; +gentity_t *G_TestEntityPosition(gentity_t *ent) { + trace_t tr; + int mask; - if ( (ent->client && ent->health <= 0) || !ent->clipmask ) - {//corpse or something with no clipmask + if ((ent->client && ent->health <= 0) || !ent->clipmask) { // corpse or something with no clipmask mask = MASK_SOLID; - } - else - { + } else { mask = ent->clipmask; } - if ( ent->client ) - { - gi.trace( &tr, ent->client->ps.origin, ent->mins, ent->maxs, ent->client->ps.origin, ent->s.number, mask, (EG2_Collision)0, 0 ); - } - else - { - if ( ent->s.eFlags & EF_MISSILE_STICK )//Arggh, this is dumb...but when it used the bbox, it was pretty much always in solid when it is riding something..which is wrong..so I changed it to basically be a point contents check - { - gi.trace( &tr, ent->s.pos.trBase, vec3_origin, vec3_origin, ent->s.pos.trBase, ent->s.number, mask, (EG2_Collision)0, 0 ); - } - else + if (ent->client) { + gi.trace(&tr, ent->client->ps.origin, ent->mins, ent->maxs, ent->client->ps.origin, ent->s.number, mask, (EG2_Collision)0, 0); + } else { + if (ent->s.eFlags & EF_MISSILE_STICK) // Arggh, this is dumb...but when it used the bbox, it was pretty much always in solid when it is riding + // something..which is wrong..so I changed it to basically be a point contents check { - gi.trace( &tr, ent->s.pos.trBase, ent->mins, ent->maxs, ent->s.pos.trBase, ent->s.number, mask, (EG2_Collision)0, 0 ); + gi.trace(&tr, ent->s.pos.trBase, vec3_origin, vec3_origin, ent->s.pos.trBase, ent->s.number, mask, (EG2_Collision)0, 0); + } else { + gi.trace(&tr, ent->s.pos.trBase, ent->mins, ent->maxs, ent->s.pos.trBase, ent->s.number, mask, (EG2_Collision)0, 0); } } if (tr.startsolid) - return &g_entities[ tr.entityNum ]; + return &g_entities[tr.entityNum]; return NULL; } - /* ================== G_TryPushingEntity @@ -154,12 +140,12 @@ G_TryPushingEntity Returns qfalse if the move is blocked ================== */ -extern qboolean G_OkayToRemoveCorpse( gentity_t *self ); +extern qboolean G_OkayToRemoveCorpse(gentity_t *self); -qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) { - vec3_t forward, right, up; - vec3_t org, org2, move2; - gentity_t *block; +qboolean G_TryPushingEntity(gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove) { + vec3_t forward, right, up; + vec3_t org, org2, move2; + gentity_t *block; /* // EF_MOVER_STOP will just stop when contacting another entity @@ -172,42 +158,42 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v // save off the old position if (pushed_p > &pushed[MAX_GENTITIES]) { - G_Error( "pushed_p > &pushed[MAX_GENTITIES]" ); + G_Error("pushed_p > &pushed[MAX_GENTITIES]"); } pushed_p->ent = check; - VectorCopy (check->s.pos.trBase, pushed_p->origin); - VectorCopy (check->s.apos.trBase, pushed_p->angles); - if ( check->client ) { + VectorCopy(check->s.pos.trBase, pushed_p->origin); + VectorCopy(check->s.apos.trBase, pushed_p->angles); + if (check->client) { pushed_p->deltayaw = check->client->ps.delta_angles[YAW]; - VectorCopy (check->client->ps.origin, pushed_p->origin); + VectorCopy(check->client->ps.origin, pushed_p->origin); } pushed_p++; // we need this for pushing things later - VectorSubtract (vec3_origin, amove, org); - AngleVectors (org, forward, right, up); + VectorSubtract(vec3_origin, amove, org); + AngleVectors(org, forward, right, up); // try moving the contacted entity - VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase); + VectorAdd(check->s.pos.trBase, move, check->s.pos.trBase); if (check->client) { // make sure the client's view rotates when on a rotating mover check->client->ps.delta_angles[YAW] += ANGLE2SHORT(amove[YAW]); } // figure movement due to the pusher's amove - VectorSubtract (check->s.pos.trBase, pusher->currentOrigin, org); - org2[0] = DotProduct (org, forward); - org2[1] = -DotProduct (org, right); - org2[2] = DotProduct (org, up); - VectorSubtract (org2, org, move2); - VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase); - if ( check->client ) { - VectorAdd (check->client->ps.origin, move, check->client->ps.origin); - VectorAdd (check->client->ps.origin, move2, check->client->ps.origin); + VectorSubtract(check->s.pos.trBase, pusher->currentOrigin, org); + org2[0] = DotProduct(org, forward); + org2[1] = -DotProduct(org, right); + org2[2] = DotProduct(org, up); + VectorSubtract(org2, org, move2); + VectorAdd(check->s.pos.trBase, move2, check->s.pos.trBase); + if (check->client) { + VectorAdd(check->client->ps.origin, move, check->client->ps.origin); + VectorAdd(check->client->ps.origin, move2, check->client->ps.origin); } // may have pushed them off an edge - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { check->s.groundEntityNum = ENTITYNUM_NONE; } @@ -217,54 +203,50 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v return qtrue; } */ - block = G_TestEntityPosition( check ); + block = G_TestEntityPosition(check); if (!block) { // pushed ok - if ( check->client ) { - VectorCopy( check->client->ps.origin, check->currentOrigin ); + if (check->client) { + VectorCopy(check->client->ps.origin, check->currentOrigin); } else { - VectorCopy( check->s.pos.trBase, check->currentOrigin ); + VectorCopy(check->s.pos.trBase, check->currentOrigin); } - gi.linkentity (check); + gi.linkentity(check); return qtrue; } // if it is ok to leave in the old position, do it // this is only relevent for riding entities, not pushed // Sliding trapdoors can cause this. - VectorCopy( (pushed_p-1)->origin, check->s.pos.trBase); - if ( check->client ) { - VectorCopy( (pushed_p-1)->origin, check->client->ps.origin); + VectorCopy((pushed_p - 1)->origin, check->s.pos.trBase); + if (check->client) { + VectorCopy((pushed_p - 1)->origin, check->client->ps.origin); } - VectorCopy( (pushed_p-1)->angles, check->s.apos.trBase ); - block = G_TestEntityPosition (check); - if ( !block ) { + VectorCopy((pushed_p - 1)->angles, check->s.apos.trBase); + block = G_TestEntityPosition(check); + if (!block) { check->s.groundEntityNum = ENTITYNUM_NONE; pushed_p--; return qtrue; } // blocked - if ( pusher->damage ) - {//Do damage - if ( (pusher->spawnflags&MOVER_CRUSHER)//a crusher - && check->s.clientNum >= MAX_CLIENTS//not the player - && check->client //NPC - && check->health <= 0 //dead - && G_OkayToRemoveCorpse( check ) )//okay to remove him - {//crusher stuck on a non->player corpse that does not have a key and is not running a script - G_FreeEntity( check ); - } - else - { - G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH ); + if (pusher->damage) { // Do damage + if ((pusher->spawnflags & MOVER_CRUSHER) // a crusher + && check->s.clientNum >= MAX_CLIENTS // not the player + && check->client // NPC + && check->health <= 0 // dead + && G_OkayToRemoveCorpse(check)) // okay to remove him + { // crusher stuck on a non->player corpse that does not have a key and is not running a script + G_FreeEntity(check); + } else { + G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH); } } return qfalse; } - /* ============ G_MoverPush @@ -274,95 +256,79 @@ otherwise riders would continue to slide. If qfalse is returned, *obstacle will be the blocking entity ============ */ -qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle ) { - qboolean notMoving; - int i, e; - int listedEntities; - vec3_t mins, maxs; - vec3_t pusherMins, pusherMaxs, totalMins, totalMaxs; - pushed_t *p; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *check; +qboolean G_MoverPush(gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle) { + qboolean notMoving; + int i, e; + int listedEntities; + vec3_t mins, maxs; + vec3_t pusherMins, pusherMaxs, totalMins, totalMaxs; + pushed_t *p; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *check; *obstacle = NULL; - - if ( !pusher->bmodel ) - {//misc_model_breakable - VectorAdd( pusher->currentOrigin, pusher->mins, pusherMins ); - VectorAdd( pusher->currentOrigin, pusher->maxs, pusherMaxs ); + if (!pusher->bmodel) { // misc_model_breakable + VectorAdd(pusher->currentOrigin, pusher->mins, pusherMins); + VectorAdd(pusher->currentOrigin, pusher->maxs, pusherMaxs); } // mins/maxs are the bounds at the destination // totalMins / totalMaxs are the bounds for the entire move - if ( pusher->currentAngles[0] || pusher->currentAngles[1] || pusher->currentAngles[2] - || amove[0] || amove[1] || amove[2] ) - { - float radius; + if (pusher->currentAngles[0] || pusher->currentAngles[1] || pusher->currentAngles[2] || amove[0] || amove[1] || amove[2]) { + float radius; - radius = RadiusFromBounds( pusher->mins, pusher->maxs ); - for ( i = 0 ; i < 3 ; i++ ) - { + radius = RadiusFromBounds(pusher->mins, pusher->maxs); + for (i = 0; i < 3; i++) { mins[i] = pusher->currentOrigin[i] + move[i] - radius; maxs[i] = pusher->currentOrigin[i] + move[i] + radius; totalMins[i] = mins[i] - move[i]; totalMaxs[i] = maxs[i] - move[i]; } - } - else - { - for (i=0 ; i<3 ; i++) - { + } else { + for (i = 0; i < 3; i++) { mins[i] = pusher->absmin[i] + move[i]; maxs[i] = pusher->absmax[i] + move[i]; } - VectorCopy( pusher->absmin, totalMins ); - VectorCopy( pusher->absmax, totalMaxs ); - for (i=0 ; i<3 ; i++) - { - if ( move[i] > 0 ) - { + VectorCopy(pusher->absmin, totalMins); + VectorCopy(pusher->absmax, totalMaxs); + for (i = 0; i < 3; i++) { + if (move[i] > 0) { totalMaxs[i] += move[i]; - } - else - { + } else { totalMins[i] += move[i]; } } } // unlink the pusher so we don't get it in the entityList - gi.unlinkentity( pusher ); + gi.unlinkentity(pusher); - listedEntities = gi.EntitiesInBox( totalMins, totalMaxs, entityList, MAX_GENTITIES ); + listedEntities = gi.EntitiesInBox(totalMins, totalMaxs, entityList, MAX_GENTITIES); // move the pusher to it's final position - VectorAdd( pusher->currentOrigin, move, pusher->currentOrigin ); - VectorAdd( pusher->currentAngles, amove, pusher->currentAngles ); - gi.linkentity( pusher ); + VectorAdd(pusher->currentOrigin, move, pusher->currentOrigin); + VectorAdd(pusher->currentAngles, amove, pusher->currentAngles); + gi.linkentity(pusher); - notMoving = (qboolean)(VectorCompare( vec3_origin, move )&&VectorCompare( vec3_origin, amove )); + notMoving = (qboolean)(VectorCompare(vec3_origin, move) && VectorCompare(vec3_origin, amove)); // see if any solid entities are inside the final position - for ( e = 0 ; e < listedEntities ; e++ ) { - check = entityList[ e ]; + for (e = 0; e < listedEntities; e++) { + check = entityList[e]; - if (( check->s.eFlags & EF_MISSILE_STICK ) && (notMoving || check->s.groundEntityNum < 0 || check->s.groundEntityNum >= ENTITYNUM_NONE )) - { + if ((check->s.eFlags & EF_MISSILE_STICK) && (notMoving || check->s.groundEntityNum < 0 || check->s.groundEntityNum >= ENTITYNUM_NONE)) { // special case hack for sticky things, destroy it if we aren't attached to the thing that is moving, but the moving thing is pushing us - G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH ); + G_Damage(check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH); continue; } // only push items and players - if ( check->s.eType != ET_ITEM ) - { - //FIXME: however it allows items to be pushed through stuff, do same for corpses? - if ( check->s.eType != ET_PLAYER ) - { - if ( !( check->s.eFlags & EF_MISSILE_STICK )) - { + if (check->s.eType != ET_ITEM) { + // FIXME: however it allows items to be pushed through stuff, do same for corpses? + if (check->s.eType != ET_PLAYER) { + if (!(check->s.eFlags & EF_MISSILE_STICK)) { // cannot be pushed by this mover continue; } @@ -373,97 +339,77 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** continue; } */ - else if ( !pusher->bmodel ) - { - vec3_t checkMins, checkMaxs; + else if (!pusher->bmodel) { + vec3_t checkMins, checkMaxs; - VectorAdd( check->currentOrigin, check->mins, checkMins ); - VectorAdd( check->currentOrigin, check->maxs, checkMaxs ); + VectorAdd(check->currentOrigin, check->mins, checkMins); + VectorAdd(check->currentOrigin, check->maxs, checkMaxs); - if ( G_BoundsOverlap( checkMins, checkMaxs, pusherMins, pusherMaxs ) ) - {//They're inside me already, no push - FIXME: we're testing a moves spot, aren't we, so we could have just moved inside them? + if (G_BoundsOverlap(checkMins, checkMaxs, pusherMins, pusherMaxs)) { // They're inside me already, no push - FIXME: we're testing a moves spot, + // aren't we, so we could have just moved inside them? continue; } } } - - if ( check->maxs[0] - check->mins[0] <= 0 && - check->maxs[1] - check->mins[1] <= 0 && - check->maxs[2] - check->mins[2] <= 0 ) - {//no size, don't push + if (check->maxs[0] - check->mins[0] <= 0 && check->maxs[1] - check->mins[1] <= 0 && check->maxs[2] - check->mins[2] <= 0) { // no size, don't push continue; } // if the entity is standing on the pusher, it will definitely be moved - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { // see if the ent needs to be tested - if ( check->absmin[0] >= maxs[0] - || check->absmin[1] >= maxs[1] - || check->absmin[2] >= maxs[2] - || check->absmax[0] <= mins[0] - || check->absmax[1] <= mins[1] - || check->absmax[2] <= mins[2] ) { + if (check->absmin[0] >= maxs[0] || check->absmin[1] >= maxs[1] || check->absmin[2] >= maxs[2] || check->absmax[0] <= mins[0] || + check->absmax[1] <= mins[1] || check->absmax[2] <= mins[2]) { continue; } // see if the ent's bbox is inside the pusher's final position // this does allow a fast moving object to pass through a thin entity... - if ( G_TestEntityPosition( check ) != pusher ) - { + if (G_TestEntityPosition(check) != pusher) { continue; } } - if ( ((pusher->spawnflags&2)&&!Q_stricmp("func_breakable",pusher->classname)) - ||((pusher->spawnflags&16)&&!Q_stricmp("func_static",pusher->classname)) ) - {//ugh, avoid stricmp with a unique flag - //Damage on impact - if ( pusher->damage ) - {//Do damage - G_Damage( check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH ); - if ( pusher->health >= 0 && pusher->takedamage && !(pusher->spawnflags&1) ) - {//do some damage to me, too - G_Damage( pusher, check, pusher->activator, move, pusher->s.pos.trBase, floor(pusher->damage/4.0f), 0, MOD_CRUSH ); + if (((pusher->spawnflags & 2) && !Q_stricmp("func_breakable", pusher->classname)) || + ((pusher->spawnflags & 16) && !Q_stricmp("func_static", pusher->classname))) { // ugh, avoid stricmp with a unique flag + // Damage on impact + if (pusher->damage) { // Do damage + G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH); + if (pusher->health >= 0 && pusher->takedamage && !(pusher->spawnflags & 1)) { // do some damage to me, too + G_Damage(pusher, check, pusher->activator, move, pusher->s.pos.trBase, floor(pusher->damage / 4.0f), 0, MOD_CRUSH); } } } // really need a flag like MOVER_TOUCH that calls the ent's touch function here, instead of this stricmp crap - else if ( (pusher->spawnflags&2) && !Q_stricmp( "func_rotating", pusher->classname ) ) - { - GEntity_TouchFunc( pusher, check, NULL ); - continue; // don't want it blocking so skip past it + else if ((pusher->spawnflags & 2) && !Q_stricmp("func_rotating", pusher->classname)) { + GEntity_TouchFunc(pusher, check, NULL); + continue; // don't want it blocking so skip past it } vec3_t oldOrg; - VectorCopy( check->s.pos.trBase, oldOrg ); + VectorCopy(check->s.pos.trBase, oldOrg); // the entity needs to be pushed - if ( G_TryPushingEntity( check, pusher, move, amove ) ) - { + if (G_TryPushingEntity(check, pusher, move, amove)) { // the mover wasn't blocked - if ( check->s.eFlags & EF_MISSILE_STICK ) - { - if ( !VectorCompare( oldOrg, check->s.pos.trBase )) - { + if (check->s.eFlags & EF_MISSILE_STICK) { + if (!VectorCompare(oldOrg, check->s.pos.trBase)) { // and the rider was actually pushed, so interpolate position change to smooth out the ride check->s.pos.trType = TR_INTERPOLATE; continue; } - //else..the mover wasn't blocked & we are riding the mover & but the rider did not move even though the mover itself did...so + // else..the mover wasn't blocked & we are riding the mover & but the rider did not move even though the mover itself did...so // drop through and let it blow up the rider up - } - else - { + } else { continue; } } // the move was blocked even after pushing this rider - if ( check->s.eFlags & EF_MISSILE_STICK ) - { + if (check->s.eFlags & EF_MISSILE_STICK) { // so nuke 'em so they don't block us anymore - G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH ); + G_Damage(check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH); continue; } @@ -473,14 +419,14 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** // move back any entities we already moved // go backwards, so if the same entity was pushed // twice, it goes back to the original position - for ( p=pushed_p-1 ; p>=pushed ; p-- ) { - VectorCopy (p->origin, p->ent->s.pos.trBase); - VectorCopy (p->angles, p->ent->s.apos.trBase); - if ( p->ent->client ) { + for (p = pushed_p - 1; p >= pushed; p--) { + VectorCopy(p->origin, p->ent->s.pos.trBase); + VectorCopy(p->angles, p->ent->s.apos.trBase); + if (p->ent->client) { p->ent->client->ps.delta_angles[YAW] = p->deltayaw; - VectorCopy (p->origin, p->ent->client->ps.origin); + VectorCopy(p->origin, p->ent->client->ps.origin); } - gi.linkentity (p->ent); + gi.linkentity(p->ent); } return qfalse; } @@ -488,16 +434,15 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** return qtrue; } - /* ================= G_MoverTeam ================= */ -void G_MoverTeam( gentity_t *ent ) { - vec3_t move, amove; - gentity_t *part, *obstacle; - vec3_t origin, angles; +void G_MoverTeam(gentity_t *ent) { + vec3_t move, amove; + gentity_t *part, *obstacle; + vec3_t origin, angles; obstacle = NULL; @@ -505,52 +450,43 @@ void G_MoverTeam( gentity_t *ent ) { // any moves or calling any think functions // if the move is blocked, all moved objects will be backed out pushed_p = pushed; - for (part = ent ; part ; part=part->teamchain) - { + for (part = ent; part; part = part->teamchain) { // get current position part->s.eFlags &= ~EF_BLOCKED_MOVER; - EvaluateTrajectory( &part->s.pos, level.time, origin ); - EvaluateTrajectory( &part->s.apos, level.time, angles ); - VectorSubtract( origin, part->currentOrigin, move ); - VectorSubtract( angles, part->currentAngles, amove ); - if ( !G_MoverPush( part, move, amove, &obstacle ) ) - { - break; // move was blocked + EvaluateTrajectory(&part->s.pos, level.time, origin); + EvaluateTrajectory(&part->s.apos, level.time, angles); + VectorSubtract(origin, part->currentOrigin, move); + VectorSubtract(angles, part->currentAngles, amove); + if (!G_MoverPush(part, move, amove, &obstacle)) { + break; // move was blocked } } - if (part) - { + if (part) { // if the pusher has a "blocked" function, call it // go back to the previous position - for ( part = ent ; part ; part = part->teamchain ) - { - //Push up time so it doesn't wiggle when blocked + for (part = ent; part; part = part->teamchain) { + // Push up time so it doesn't wiggle when blocked part->s.pos.trTime += level.time - level.previousTime; part->s.apos.trTime += level.time - level.previousTime; - EvaluateTrajectory( &part->s.pos, level.time, part->currentOrigin ); - EvaluateTrajectory( &part->s.apos, level.time, part->currentAngles ); - gi.linkentity( part ); + EvaluateTrajectory(&part->s.pos, level.time, part->currentOrigin); + EvaluateTrajectory(&part->s.apos, level.time, part->currentAngles); + gi.linkentity(part); part->s.eFlags |= EF_BLOCKED_MOVER; } - if ( ent->e_BlockedFunc != blockedF_NULL ) - {// this check no longer necessary, done internally below, but it's here for reference - GEntity_BlockedFunc( ent, obstacle ); + if (ent->e_BlockedFunc != blockedF_NULL) { // this check no longer necessary, done internally below, but it's here for reference + GEntity_BlockedFunc(ent, obstacle); } return; } // the move succeeded - for ( part = ent ; part ; part = part->teamchain ) - { + for (part = ent; part; part = part->teamchain) { // call the reached function if time is at or past end point - if ( part->s.pos.trType == TR_LINEAR_STOP || - part->s.pos.trType == TR_NONLINEAR_STOP ) - { - if ( level.time >= part->s.pos.trTime + part->s.pos.trDuration ) - { - GEntity_ReachedFunc( part ); + if (part->s.pos.trType == TR_LINEAR_STOP || part->s.pos.trType == TR_NONLINEAR_STOP) { + if (level.time >= part->s.pos.trTime + part->s.pos.trDuration) { + GEntity_ReachedFunc(part); } } } @@ -562,25 +498,25 @@ G_RunMover ================ */ -void G_RunMover( gentity_t *ent ) { +void G_RunMover(gentity_t *ent) { // if not a team captain, don't do anything, because // the captain will handle everything - if ( ent->flags & FL_TEAMSLAVE ) { + if (ent->flags & FL_TEAMSLAVE) { return; } // if stationary at one of the positions, don't move anything - if ( ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY ) { - G_MoverTeam( ent ); + if (ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY) { + G_MoverTeam(ent); } -/* if ( ent->classname && Q_stricmp("misc_turret", ent->classname ) == 0 ) - { - rebolt_turret( ent ); - } -*/ + /* if ( ent->classname && Q_stricmp("misc_turret", ent->classname ) == 0 ) + { + rebolt_turret( ent ); + } + */ // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -599,20 +535,18 @@ CalcTeamDoorCenter Finds all the doors of a team and returns their center position */ -void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) -{ - vec3_t slavecenter; - gentity_t *slave; +void CalcTeamDoorCenter(gentity_t *ent, vec3_t center) { + vec3_t slavecenter; + gentity_t *slave; - //Start with our center + // Start with our center VectorAdd(ent->mins, ent->maxs, center); VectorScale(center, 0.5, center); - for ( slave = ent->teamchain ; slave ; slave = slave->teamchain ) - { - //Find slave's center + for (slave = ent->teamchain; slave; slave = slave->teamchain) { + // Find slave's center VectorAdd(slave->mins, slave->maxs, slavecenter); VectorScale(slavecenter, 0.5, slavecenter); - //Add that to our own, find middle + // Add that to our own, find middle VectorAdd(center, slavecenter, center); VectorScale(center, 0.5, center); } @@ -623,61 +557,54 @@ void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) SetMoverState =============== */ -void SetMoverState( gentity_t *ent, moverState_t moverState, int time ) { - vec3_t delta; - float f; +void SetMoverState(gentity_t *ent, moverState_t moverState, int time) { + vec3_t delta; + float f; ent->moverState = moverState; ent->s.pos.trTime = time; - if ( ent->s.pos.trDuration <= 0 ) - {//Don't allow divide by zero! + if (ent->s.pos.trDuration <= 0) { // Don't allow divide by zero! ent->s.pos.trDuration = 1; } - switch( moverState ) { + switch (moverState) { case MOVER_POS1: - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_POS2: - VectorCopy( ent->pos2, ent->s.pos.trBase ); + VectorCopy(ent->pos2, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_1TO2: - VectorCopy( ent->pos1, ent->s.pos.trBase ); - VectorSubtract( ent->pos2, ent->pos1, delta ); + VectorCopy(ent->pos1, ent->s.pos.trBase); + VectorSubtract(ent->pos2, ent->pos1, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; case MOVER_2TO1: - VectorCopy( ent->pos2, ent->s.pos.trBase ); - VectorSubtract( ent->pos1, ent->pos2, delta ); + VectorCopy(ent->pos2, ent->s.pos.trBase); + VectorSubtract(ent->pos1, ent->pos2, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; } - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); - gi.linkentity( ent ); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); + gi.linkentity(ent); } /* @@ -688,345 +615,289 @@ All entities in a mover team will move from pos1 to pos2 in the same amount of time ================ */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ) { - gentity_t *slave; +void MatchTeam(gentity_t *teamLeader, int moverState, int time) { + gentity_t *slave; - for ( slave = teamLeader ; slave ; slave = slave->teamchain ) { - SetMoverState( slave, (moverState_t) moverState, time ); + for (slave = teamLeader; slave; slave = slave->teamchain) { + SetMoverState(slave, (moverState_t)moverState, time); } } - - /* ================ ReturnToPos1 ================ */ -void ReturnToPos1( gentity_t *ent ) { +void ReturnToPos1(gentity_t *ent) { ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = 0; ent->s.time = level.time; - MatchTeam( ent, MOVER_2TO1, level.time ); + MatchTeam(ent, MOVER_2TO1, level.time); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? } - /* ================ Reached_BinaryMover ================ */ -void Reached_BinaryMover( gentity_t *ent ) -{ +void Reached_BinaryMover(gentity_t *ent) { // stop the looping sound ent->s.loopSound = 0; - if ( ent->moverState == MOVER_1TO2 ) - {//reached open + if (ent->moverState == MOVER_1TO2) { // reached open // reached pos2 - SetMoverState( ent, MOVER_POS2, level.time ); + SetMoverState(ent, MOVER_POS2, level.time); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); - if ( ent->wait < 0 ) - {//Done for good + if (ent->wait < 0) { // Done for good ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = -1; ent->e_UseFunc = useF_NULL; - } - else - { + } else { // return to pos1 after a delay ent->e_ThinkFunc = thinkF_ReturnToPos1; - if(ent->spawnflags & 8) - {//Toggle, keep think, wait for next use? + if (ent->spawnflags & 8) { // Toggle, keep think, wait for next use? ent->nextthink = -1; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } } // fire targets - if ( !ent->activator ) - { + if (!ent->activator) { ent->activator = ent; } - G_UseTargets2( ent, ent->activator, ent->opentarget ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//closed + G_UseTargets2(ent, ent->activator, ent->opentarget); + } else if (ent->moverState == MOVER_2TO1) { // closed // reached pos1 - SetMoverState( ent, MOVER_POS1, level.time ); + SetMoverState(ent, MOVER_POS1, level.time); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); // close areaportals - if ( ent->teammaster == ent || !ent->teammaster ) - { - gi.AdjustAreaPortalState( ent, qfalse ); + if (ent->teammaster == ent || !ent->teammaster) { + gi.AdjustAreaPortalState(ent, qfalse); } - G_UseTargets2( ent, ent->activator, ent->closetarget ); - } - else - { - G_Error( "Reached_BinaryMover: bad moverState" ); + G_UseTargets2(ent, ent->activator, ent->closetarget); + } else { + G_Error("Reached_BinaryMover: bad moverState"); } } - /* ================ Use_BinaryMover_Go ================ */ -void Use_BinaryMover_Go( gentity_t *ent ) -{ - int total; - int partial; -// gentity_t *other = ent->enemy; - gentity_t *activator = ent->activator; +void Use_BinaryMover_Go(gentity_t *ent) { + int total; + int partial; + // gentity_t *other = ent->enemy; + gentity_t *activator = ent->activator; ent->activator = activator; - if ( ent->moverState == MOVER_POS1 ) - { + if (ent->moverState == MOVER_POS1) { // start moving 50 msec later, becase if this was player // triggered, level.time hasn't been advanced yet - MatchTeam( ent, MOVER_1TO2, level.time + 50 ); + MatchTeam(ent, MOVER_1TO2, level.time + 50); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); ent->s.time = level.time; // open areaportal - if ( ent->teammaster == ent || !ent->teammaster ) { - gi.AdjustAreaPortalState( ent, qtrue ); + if (ent->teammaster == ent || !ent->teammaster) { + gi.AdjustAreaPortalState(ent, qtrue); } - G_UseTargets( ent, ent->activator ); + G_UseTargets(ent, ent->activator); return; } // if all the way up, just delay before coming down - if ( ent->moverState == MOVER_POS2 ) { - //have to do this because the delay sets our think to Use_BinaryMover_Go + if (ent->moverState == MOVER_POS2) { + // have to do this because the delay sets our think to Use_BinaryMover_Go ent->e_ThinkFunc = thinkF_ReturnToPos1; - if ( ent->spawnflags & 8 ) - {//TOGGLE doors don't use wait! + if (ent->spawnflags & 8) { // TOGGLE doors don't use wait! ent->nextthink = level.time + FRAMETIME; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } - G_UseTargets2( ent, ent->activator, ent->target2 ); + G_UseTargets2(ent, ent->activator, ent->target2); return; } // only partway down before reversing - if ( ent->moverState == MOVER_2TO1 ) - { - total = ent->s.pos.trDuration-50; - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_2TO1) { + total = ent->s.pos.trDuration - 50; + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; - VectorSubtract( ent->currentOrigin, ent->pos1, curDelta ); - float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + VectorSubtract(ent->currentOrigin, ent->pos1, curDelta); + float fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { - partial = level.time - ent->s.pos.trTime;//ent->s.time; + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { + partial = level.time - ent->s.pos.trTime; // ent->s.time; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; - MatchTeam( ent, MOVER_1TO2, ent->s.pos.trTime ); + MatchTeam(ent, MOVER_1TO2, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } // only partway up before reversing - if ( ent->moverState == MOVER_1TO2 ) - { - total = ent->s.pos.trDuration-50; - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_1TO2) { + total = ent->s.pos.trDuration - 50; + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; - VectorSubtract( ent->currentOrigin, ent->pos2, curDelta ); - float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + VectorSubtract(ent->currentOrigin, ent->pos2, curDelta); + float fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { - partial = level.time - ent->s.pos.trTime;//ent->s.time; + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { + partial = level.time - ent->s.pos.trTime; // ent->s.time; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; - MatchTeam( ent, MOVER_2TO1, ent->s.pos.trTime ); + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; + MatchTeam(ent, MOVER_2TO1, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } } -void UnLockDoors(gentity_t *const ent) -{ - //noise? - //go through and unlock the door and all the slaves - gentity_t *slave = ent; - do - { // want to allow locked toggle doors, so keep the targetname - if( !(slave->spawnflags & MOVER_TOGGLE) ) - { - slave->targetname = NULL;//not usable ever again +void UnLockDoors(gentity_t *const ent) { + // noise? + // go through and unlock the door and all the slaves + gentity_t *slave = ent; + do { // want to allow locked toggle doors, so keep the targetname + if (!(slave->spawnflags & MOVER_TOGGLE)) { + slave->targetname = NULL; // not usable ever again } slave->spawnflags &= ~MOVER_LOCKED; - slave->s.frame = 1;//second stage of anim + slave->s.frame = 1; // second stage of anim slave = slave->teamchain; - } while ( slave ); + } while (slave); } -void LockDoors(gentity_t *const ent) -{ - //noise? - //go through and lock the door and all the slaves - gentity_t *slave = ent; - do - { +void LockDoors(gentity_t *const ent) { + // noise? + // go through and lock the door and all the slaves + gentity_t *slave = ent; + do { slave->spawnflags |= MOVER_LOCKED; - slave->s.frame = 0;//first stage of anim + slave->s.frame = 0; // first stage of anim slave = slave->teamchain; - } while ( slave ); + } while (slave); } /* ================ Use_BinaryMover ================ */ -void Use_BinaryMover( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - int key; +void Use_BinaryMover(gentity_t *ent, gentity_t *other, gentity_t *activator) { + int key; const char *text; - if ( ent->e_UseFunc == useF_NULL ) - {//I cannot be used anymore, must be a door with a wait of -1 that's opened. + if (ent->e_UseFunc == useF_NULL) { // I cannot be used anymore, must be a door with a wait of -1 that's opened. return; } // only the master should be used - if ( ent->flags & FL_TEAMSLAVE ) - { - Use_BinaryMover( ent->teammaster, other, activator ); + if (ent->flags & FL_TEAMSLAVE) { + Use_BinaryMover(ent->teammaster, other, activator); return; } - if ( ent->svFlags & SVF_INACTIVE ) - { + if (ent->svFlags & SVF_INACTIVE) { return; } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, unlock it + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, unlock it UnLockDoors(ent); return; } - if ( ent->spawnflags & MOVER_GOODIE ) - { - if ( ent->fly_sound_debounce_time > level.time ) - { + if (ent->spawnflags & MOVER_GOODIE) { + if (ent->fly_sound_debounce_time > level.time) { return; - } - else - { - key = INV_GoodieKeyCheck( activator ); - if (key) - {//activator has a goodie key, remove it + } else { + key = INV_GoodieKeyCheck(activator); + if (key) { // activator has a goodie key, remove it activator->client->ps.inventory[key]--; - G_Sound( activator, G_SoundIndex( "sound/movers/goodie_pass.wav" ) ); + G_Sound(activator, G_SoundIndex("sound/movers/goodie_pass.wav")); // once the goodie mover has been used, it no longer requires a goodie key ent->spawnflags &= ~MOVER_GOODIE; - } - else - { //don't have a goodie key - G_Sound( activator, G_SoundIndex( "sound/movers/goodie_fail.wav" ) ); + } else { // don't have a goodie key + G_Sound(activator, G_SoundIndex("sound/movers/goodie_fail.wav")); ent->fly_sound_debounce_time = level.time + 5000; text = "cp @SP_INGAME_NEED_KEY_TO_OPEN"; - //FIXME: temp message, only on certain difficulties?, graphic instead of text? - gi.SendServerCommand( 0, text ); + // FIXME: temp message, only on certain difficulties?, graphic instead of text? + gi.SendServerCommand(0, text); return; } } } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - G_SetEnemy( ent, other ); + G_SetEnemy(ent, other); ent->activator = activator; - if(ent->delay) - { + if (ent->delay) { ent->e_ThinkFunc = thinkF_Use_BinaryMover_Go; ent->nextthink = level.time + ent->delay; - } - else - { + } else { Use_BinaryMover_Go(ent); } } - - /* ================ InitMover @@ -1035,102 +906,90 @@ InitMover so the movement delta can be calculated ================ */ -void InitMoverTrData( gentity_t *ent ) -{ - vec3_t move; - float distance; +void InitMoverTrData(gentity_t *ent) { + vec3_t move; + float distance; ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); // calculate time to reach second position from speed - VectorSubtract( ent->pos2, ent->pos1, move ); - distance = VectorLength( move ); - if ( ! ent->speed ) - { + VectorSubtract(ent->pos2, ent->pos1, move); + distance = VectorLength(move); + if (!ent->speed) { ent->speed = 100; } - VectorScale( move, ent->speed, ent->s.pos.trDelta ); + VectorScale(move, ent->speed, ent->s.pos.trDelta); ent->s.pos.trDuration = distance * 1000 / ent->speed; - if ( ent->s.pos.trDuration <= 0 ) - { + if (ent->s.pos.trDuration <= 0) { ent->s.pos.trDuration = 1; } } -void InitMover( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +void InitMover(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 ) - { - if ( strstr( ent->model2, ".glm" )) - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, ent->model2, ent->s.modelindex2, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - if ( ent->playerModel >= 0 ) - { - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + if (ent->model2) { + if (strstr(ent->model2, ".glm")) { + ent->s.modelindex2 = G_ModelIndex(ent->model2); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, ent->model2, ent->s.modelindex2, NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->playerModel >= 0) { + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); } ent->s.radius = 120; - } - else - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + } else { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } - ent->e_UseFunc = useF_Use_BinaryMover; + ent->e_UseFunc = useF_Use_BinaryMover; ent->e_ReachedFunc = reachedF_Reached_BinaryMover; ent->moverState = MOVER_POS1; ent->svFlags = SVF_USE_CURRENT_ORIGIN; - if ( ent->spawnflags & MOVER_INACTIVE ) - {// Make it inactive + if (ent->spawnflags & MOVER_INACTIVE) { // Make it inactive ent->svFlags |= SVF_INACTIVE; } - if(ent->spawnflags & MOVER_PLAYER_USE) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & MOVER_PLAYER_USE) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } ent->s.eType = ET_MOVER; - VectorCopy( ent->pos1, ent->currentOrigin ); - gi.linkentity( ent ); + VectorCopy(ent->pos1, ent->currentOrigin); + gi.linkentity(ent); - InitMoverTrData( ent ); + InitMoverTrData(ent); } - /* =============================================================================== @@ -1147,75 +1006,64 @@ targeted by another entity. Blocked_Door ================ */ -void Blocked_Door( gentity_t *ent, gentity_t *other ) { +void Blocked_Door(gentity_t *ent, gentity_t *other) { // remove anything other than a client -- no longer the case // don't remove security keys or goodie keys - if ( (other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY) ) - { + if ((other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY)) { // should we be doing anything special if a key blocks it... move it somehow..? } // if your not a client, or your a dead client remove yourself... - else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message)) ) - { - if ( !IIcarusInterface::GetIcarus()->IsRunning( other->m_iIcarusID ) /*!other->taskManager || !other->taskManager->IsRunning()*/ ) - { + else if (other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message))) { + if (!IIcarusInterface::GetIcarus()->IsRunning(other->m_iIcarusID) /*!other->taskManager || !other->taskManager->IsRunning()*/) { // if an item or weapon can we do a little explosion..? - G_FreeEntity( other ); + G_FreeEntity(other); return; } } - if ( ent->damage ) - { - if ( (ent->spawnflags&MOVER_CRUSHER)//a crusher - && other->s.clientNum >= MAX_CLIENTS//not the player - && other->client //NPC - && other->health <= 0 //dead - && G_OkayToRemoveCorpse( other ) )//okay to remove him - {//crusher stuck on a non->player corpse that does not have a key and is not running a script - G_FreeEntity( other ); - } - else - { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + if ((ent->spawnflags & MOVER_CRUSHER) // a crusher + && other->s.clientNum >= MAX_CLIENTS // not the player + && other->client // NPC + && other->health <= 0 // dead + && G_OkayToRemoveCorpse(other)) // okay to remove him + { // crusher stuck on a non->player corpse that does not have a key and is not running a script + G_FreeEntity(other); + } else { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } } - if ( ent->spawnflags & MOVER_CRUSHER ) { - return; // crushers don't reverse + if (ent->spawnflags & MOVER_CRUSHER) { + return; // crushers don't reverse } // reverse direction - Use_BinaryMover( ent, ent, other ); + Use_BinaryMover(ent, ent, other); } - /* ================ Touch_DoorTrigger ================ */ -void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ - if ( ent->svFlags & SVF_INACTIVE ) - { +void Touch_DoorTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (ent->svFlags & SVF_INACTIVE) { return; } - if ( ent->owner->spawnflags & MOVER_LOCKED ) - {//don't even try to use the door if it's locked + if (ent->owner->spawnflags & MOVER_LOCKED) { // don't even try to use the door if it's locked return; } - if ( ent->owner->moverState != MOVER_1TO2 ) - {//Door is not already opening - //if ( ent->owner->moverState == MOVER_POS1 || ent->owner->moverState == MOVER_2TO1 ) + if (ent->owner->moverState != MOVER_1TO2) { // Door is not already opening + // if ( ent->owner->moverState == MOVER_POS1 || ent->owner->moverState == MOVER_2TO1 ) //{//only check these if closed or closing - //If door is closed, opening or open, check this - Use_BinaryMover( ent->owner, ent, other ); + // If door is closed, opening or open, check this + Use_BinaryMover(ent->owner, ent, other); } /* @@ -1234,34 +1082,31 @@ All of the parts of a door have been spawned, so create a trigger that encloses all of them ====================== */ -void Think_SpawnNewDoorTrigger( gentity_t *ent ) -{ - gentity_t *other; - vec3_t mins, maxs; - int i, best; +void Think_SpawnNewDoorTrigger(gentity_t *ent) { + gentity_t *other; + vec3_t mins, maxs; + int i, best; // set all of the slaves as shootable - if ( ent->takedamage ) - { - for ( other = ent ; other ; other = other->teamchain ) - { + if (ent->takedamage) { + for (other = ent; other; other = other->teamchain) { other->takedamage = qtrue; } } // find the bounds of everything on the team - VectorCopy (ent->absmin, mins); - VectorCopy (ent->absmax, maxs); + VectorCopy(ent->absmin, mins); + VectorCopy(ent->absmax, maxs); - for (other = ent->teamchain ; other ; other=other->teamchain) { - AddPointToBounds (other->absmin, mins, maxs); - AddPointToBounds (other->absmax, mins, maxs); + for (other = ent->teamchain; other; other = other->teamchain) { + AddPointToBounds(other->absmin, mins, maxs); + AddPointToBounds(other->absmax, mins, maxs); } // find the thinnest axis, which will be the one we expand best = 0; - for ( i = 1 ; i < 3 ; i++ ) { - if ( maxs[i] - mins[i] < maxs[best] - mins[best] ) { + for (i = 1; i < 3; i++) { + if (maxs[i] - mins[i] < maxs[best] - mins[best]) { best = i; } } @@ -1269,74 +1114,58 @@ void Think_SpawnNewDoorTrigger( gentity_t *ent ) mins[best] -= 120; // create a trigger with this size - other = G_Spawn (); - VectorCopy (mins, other->mins); - VectorCopy (maxs, other->maxs); + other = G_Spawn(); + VectorCopy(mins, other->mins); + VectorCopy(maxs, other->maxs); other->owner = ent; other->contents = CONTENTS_TRIGGER; other->e_TouchFunc = touchF_Touch_DoorTrigger; - gi.linkentity (other); + gi.linkentity(other); other->classname = "trigger_door"; - MatchTeam( ent, ent->moverState, level.time ); + MatchTeam(ent, ent->moverState, level.time); } -void Think_MatchTeam( gentity_t *ent ) -{ - MatchTeam( ent, ent->moverState, level.time ); -} +void Think_MatchTeam(gentity_t *ent) { MatchTeam(ent, ent->moverState, level.time); } -qboolean G_EntIsDoor( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_EntIsDoor(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } gentity_t *ent = &g_entities[entityNum]; - if ( ent && !Q_stricmp( "func_door", ent->classname ) ) - {//blocked by a door + if (ent && !Q_stricmp("func_door", ent->classname)) { // blocked by a door return qtrue; } return qfalse; } -gentity_t *G_FindDoorTrigger( gentity_t *ent ) -{ +gentity_t *G_FindDoorTrigger(gentity_t *ent) { gentity_t *owner = NULL; gentity_t *door = ent; - if ( door->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( door->teammaster && (door->flags&FL_TEAMSLAVE)) - { + if (door->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (door->teammaster && (door->flags & FL_TEAMSLAVE)) { door = door->teammaster; } } - if ( door->targetname ) - {//find out what is targeting it - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), door->targetname )) != NULL ) - { - if ( owner && (owner->contents&CONTENTS_TRIGGER) ) - { + if (door->targetname) { // find out what is targeting it + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), door->targetname)) != NULL) { + if (owner && (owner->contents & CONTENTS_TRIGGER)) { return owner; } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), door->targetname )) != NULL ) - { - if ( owner && (owner->contents&CONTENTS_TRIGGER) ) - { + while ((owner = G_Find(owner, FOFS(target2), door->targetname)) != NULL) { + if (owner && (owner->contents & CONTENTS_TRIGGER)) { return owner; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( classname ), "trigger_door" )) != NULL ) - { - if ( owner->owner == door ) - { + while ((owner = G_Find(owner, FOFS(classname), "trigger_door")) != NULL) { + if (owner->owner == door) { return owner; } } @@ -1344,67 +1173,50 @@ gentity_t *G_FindDoorTrigger( gentity_t *ent ) return NULL; } -qboolean G_TriggerActive( gentity_t *self ); -qboolean G_EntIsUnlockedDoor( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_TriggerActive(gentity_t *self); +qboolean G_EntIsUnlockedDoor(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } - if ( G_EntIsDoor( entityNum ) ) - { + if (G_EntIsDoor(entityNum)) { gentity_t *ent = &g_entities[entityNum]; gentity_t *owner = NULL; - if ( ent->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( ent->teammaster && (ent->flags&FL_TEAMSLAVE)) - { + if (ent->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (ent->teammaster && (ent->flags & FL_TEAMSLAVE)) { ent = ent->teammaster; } } - if ( ent->targetname ) - {//find out what is targetting it + if (ent->targetname) { // find out what is targetting it owner = NULL; - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) - || !Q_stricmp( "trigger_once", owner->classname ) )//FIXME: other triggers okay too? + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname) || !Q_stricmp("trigger_once", owner->classname)) // FIXME: other triggers okay too? { - if ( G_TriggerActive( owner ) ) - { + if (G_TriggerActive(owner)) { return qtrue; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too? + while ((owner = G_Find(owner, FOFS(target2), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname)) // FIXME: other triggers okay too? { - if ( G_TriggerActive( owner ) ) - { + if (G_TriggerActive(owner)) { return qtrue; } } } return qfalse; - } - else - {//check the door's auto-created trigger instead - owner = G_FindDoorTrigger( ent ); - if ( owner && (owner->svFlags&SVF_INACTIVE) ) - {//owning auto-created trigger is inactive + } else { // check the door's auto-created trigger instead + owner = G_FindDoorTrigger(ent); + if (owner && (owner->svFlags & SVF_INACTIVE)) { // owning auto-created trigger is inactive return qfalse; } } - if ( !(ent->svFlags & SVF_INACTIVE) && //assumes that the reactivate trigger isn't right next to the door! - !ent->health && - !(ent->spawnflags & MOVER_PLAYER_USE) && - !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && - !(ent->spawnflags & MOVER_LOCKED)) - //FIXME: what about MOVER_GOODIE? + if (!(ent->svFlags & SVF_INACTIVE) && // assumes that the reactivate trigger isn't right next to the door! + !ent->health && !(ent->spawnflags & MOVER_PLAYER_USE) && !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && !(ent->spawnflags & MOVER_LOCKED)) + // FIXME: what about MOVER_GOODIE? { return qtrue; } @@ -1412,16 +1224,13 @@ qboolean G_EntIsUnlockedDoor( int entityNum ) return qfalse; } - /*QUAKED func_door (0 .5 .8) ? START_OPEN FORCE_ACTIVATE CRUSHER TOGGLE LOCKED GOODIE PLAYER_USE INACTIVE -START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors). -FORCE_ACTIVATE Can only be activated by a force push or pull -CRUSHER ? +START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when +triggered (not useful for touch or takedamage doors). FORCE_ACTIVATE Can only be activated by a force push or pull CRUSHER ? TOGGLE wait in both the start and end states for a trigger event - does NOT work on Trek doors. -LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates normally. Note that you cannot use the door again after this. -GOODIE Door will not work unless activator has a "goodie key" in his inventory -PLAYER_USE Player can use it with the use button -INACTIVE must be used by a target_activate before it can be used +LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates +normally. Note that you cannot use the door again after this. GOODIE Door will not work unless activator has a "goodie key" in his inventory PLAYER_USE +Player can use it with the use button INACTIVE must be used by a target_activate before it can be used "target" Door fires this when it starts moving from it's closed position to its open position. "opentarget" Door fires this after reaching its "open" position @@ -1443,19 +1252,17 @@ INACTIVE must be used by a target_activate before it can be used "linear" set to 1 and it will move linearly rather than with acceleration (default is 0) 0 - no sound (default) */ -void SP_func_door (gentity_t *ent) -{ - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_door(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; ent->e_BlockedFunc = blockedF_Blocked_Door; - if ( ent->spawnflags & MOVER_GOODIE ) - { - G_SoundIndex( "sound/movers/goodie_fail.wav" ); - G_SoundIndex( "sound/movers/goodie_pass.wav" ); + if (ent->spawnflags & MOVER_GOODIE) { + G_SoundIndex("sound/movers/goodie_fail.wav"); + G_SoundIndex("sound/movers/goodie_pass.wav"); } // default speed of 400 @@ -1470,65 +1277,57 @@ void SP_func_door (gentity_t *ent) ent->delay *= 1000; // default lip of 8 units - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("lip", "8", &lip); // default damage of 2 points - G_SpawnInt( "dmg", "2", &ent->damage ); - if ( ent->damage < 0 ) - { + G_SpawnInt("dmg", "2", &ent->damage); + if (ent->damage < 0) { ent->damage = 0; } // first position at start - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - gi.SetBrushModel( ent, ent->model ); - G_SetMovedir( ent->s.angles, ent->movedir ); - abs_movedir[0] = fabs( ent->movedir[0] ); - abs_movedir[1] = fabs( ent->movedir[1] ); - abs_movedir[2] = fabs( ent->movedir[2] ); - VectorSubtract( ent->maxs, ent->mins, size ); - distance = DotProduct( abs_movedir, size ) - lip; - VectorMA( ent->pos1, distance, ent->movedir, ent->pos2 ); + gi.SetBrushModel(ent, ent->model); + G_SetMovedir(ent->s.angles, ent->movedir); + abs_movedir[0] = fabs(ent->movedir[0]); + abs_movedir[1] = fabs(ent->movedir[1]); + abs_movedir[2] = fabs(ent->movedir[2]); + VectorSubtract(ent->maxs, ent->mins, size); + distance = DotProduct(abs_movedir, size) - lip; + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); // if "start_open", reverse position 1 and 2 - if ( ent->spawnflags & 1 ) - { - vec3_t temp; + if (ent->spawnflags & 1) { + vec3_t temp; - VectorCopy( ent->pos2, temp ); - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( temp, ent->pos1 ); + VectorCopy(ent->pos2, temp); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(temp, ent->pos1); } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, set up as locked until used directly - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, set up as locked until used directly + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim } - InitMover( ent ); + InitMover(ent); ent->nextthink = level.time + FRAMETIME; - if ( !(ent->flags&FL_TEAMSLAVE) ) - { + if (!(ent->flags & FL_TEAMSLAVE)) { int health; - G_SpawnInt( "health", "0", &health ); + G_SpawnInt("health", "0", &health); - if ( health ) - { + if (health) { ent->takedamage = qtrue; } - if ( !(ent->spawnflags&MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE) ) - { + if (!(ent->spawnflags & MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE)) { // non touch/shoot doors ent->e_ThinkFunc = thinkF_Think_MatchTeam; - } - else - {//locked doors still spawn a trigger + } else { // locked doors still spawn a trigger ent->e_ThinkFunc = thinkF_Think_SpawnNewDoorTrigger; } } @@ -1549,13 +1348,13 @@ Touch_Plat Don't allow decent if a living player is on it =============== */ -void Touch_Plat( gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client || other->client->ps.stats[STAT_HEALTH] <= 0 ) { +void Touch_Plat(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client || other->client->ps.stats[STAT_HEALTH] <= 0) { return; } // delay return-to-pos1 by one second - if ( ent->moverState == MOVER_POS2 ) { + if (ent->moverState == MOVER_POS2) { ent->nextthink = level.time + 1000; } } @@ -1567,17 +1366,16 @@ Touch_PlatCenterTrigger If the plat is at the bottom position, start it going up =============== */ -void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->owner->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent->owner, ent, other ); + if (ent->owner->moverState == MOVER_POS1) { + Use_BinaryMover(ent->owner, ent, other); } } - /* ================ SpawnPlatTrigger @@ -1587,9 +1385,9 @@ Elevator cars require that the trigger extend through the entire low position, not just sit on top of it. ================ */ -void SpawnPlatTrigger( gentity_t *ent ) { - gentity_t *trigger; - vec3_t tmin, tmax; +void SpawnPlatTrigger(gentity_t *ent) { + gentity_t *trigger; + vec3_t tmin, tmax; // the middle trigger will be a thin trigger just // above the starting position @@ -1606,22 +1404,21 @@ void SpawnPlatTrigger( gentity_t *ent ) { tmax[1] = ent->pos1[1] + ent->maxs[1] - 33; tmax[2] = ent->pos1[2] + ent->maxs[2] + 8; - if ( tmax[0] <= tmin[0] ) { - tmin[0] = ent->pos1[0] + (ent->mins[0] + ent->maxs[0]) *0.5; + if (tmax[0] <= tmin[0]) { + tmin[0] = ent->pos1[0] + (ent->mins[0] + ent->maxs[0]) * 0.5; tmax[0] = tmin[0] + 1; } - if ( tmax[1] <= tmin[1] ) { - tmin[1] = ent->pos1[1] + (ent->mins[1] + ent->maxs[1]) *0.5; + if (tmax[1] <= tmin[1]) { + tmin[1] = ent->pos1[1] + (ent->mins[1] + ent->maxs[1]) * 0.5; tmax[1] = tmin[1] + 1; } - VectorCopy (tmin, trigger->mins); - VectorCopy (tmax, trigger->maxs); + VectorCopy(tmin, trigger->mins); + VectorCopy(tmax, trigger->maxs); - gi.linkentity (trigger); + gi.linkentity(trigger); } - /*QUAKED func_plat (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used @@ -1637,34 +1434,34 @@ Plats are always drawn in the extended position so they will light correctly. "color" constantLight color "light" constantLight radius */ -void SP_func_plat (gentity_t *ent) { - float lip, height; +void SP_func_plat(gentity_t *ent) { + float lip, height; -// ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); -// ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); + // ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); + // ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); - VectorClear (ent->s.angles); + VectorClear(ent->s.angles); - G_SpawnFloat( "speed", "200", &ent->speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "wait", "1", &ent->wait ); - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("speed", "200", &ent->speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("wait", "1", &ent->wait); + G_SpawnFloat("lip", "8", &lip); ent->wait = 1000; // create second position - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); - if ( !G_SpawnFloat( "height", "0", &height ) ) { + if (!G_SpawnFloat("height", "0", &height)) { height = (ent->maxs[2] - ent->mins[2]) - lip; } // pos1 is the rest (bottom) position, pos2 is the top - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( ent->pos2, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(ent->pos2, ent->pos1); ent->pos1[2] -= height; - InitMover( ent ); + InitMover(ent); // touch function keeps the plat from returning while // a live player is standing on it @@ -1672,15 +1469,14 @@ void SP_func_plat (gentity_t *ent) { ent->e_BlockedFunc = blockedF_Blocked_Door; - ent->owner = ent; // so it can be treated as a door + ent->owner = ent; // so it can be treated as a door // spawn the trigger if one hasn't been custom made - if ( !ent->targetname ) { + if (!ent->targetname) { SpawnPlatTrigger(ent); } } - /* =============================================================================== @@ -1695,22 +1491,22 @@ Touch_Button =============== */ -void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent, other, other ); + if (ent->moverState == MOVER_POS1) { + Use_BinaryMover(ent, other, other); } } - /*QUAKED func_button (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used -When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again. +When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original +position where it can be triggered again. "model2" .md3 model to also draw "modelAngles" md3 model's angles (in addition to any rotation on the part of the brush entity itself) @@ -1723,38 +1519,38 @@ When a button is touched, it moves some distance in the direction of it's angle, "color" constantLight color "light" constantLight radius */ -void SP_func_button( gentity_t *ent ) { - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_button(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; -// ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); + // ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); - if ( !ent->speed ) { + if (!ent->speed) { ent->speed = 40; } - if ( !ent->wait ) { + if (!ent->wait) { ent->wait = 1; } ent->wait *= 1000; // first position - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); - G_SpawnFloat( "lip", "4", &lip ); + G_SpawnFloat("lip", "4", &lip); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); abs_movedir[0] = fabs(ent->movedir[0]); abs_movedir[1] = fabs(ent->movedir[1]); abs_movedir[2] = fabs(ent->movedir[2]); - VectorSubtract( ent->maxs, ent->mins, size ); + VectorSubtract(ent->maxs, ent->mins, size); distance = abs_movedir[0] * size[0] + abs_movedir[1] * size[1] + abs_movedir[2] * size[2] - lip; - VectorMA (ent->pos1, distance, ent->movedir, ent->pos2); + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); if (ent->health) { // shootable button @@ -1764,11 +1560,9 @@ void SP_func_button( gentity_t *ent ) { ent->e_TouchFunc = touchF_Touch_Button; } - InitMover( ent ); + InitMover(ent); } - - /* =============================================================================== @@ -1777,10 +1571,9 @@ TRAIN =============================================================================== */ - -#define TRAIN_START_ON 1 -#define TRAIN_TOGGLE 2 -#define TRAIN_BLOCK_STOPS 4 +#define TRAIN_START_ON 1 +#define TRAIN_TOGGLE 2 +#define TRAIN_BLOCK_STOPS 4 /* =============== @@ -1789,21 +1582,17 @@ Think_BeginMoving The wait time at a corner has completed, so start moving again =============== */ -void Think_BeginMoving( gentity_t *ent ) { +void Think_BeginMoving(gentity_t *ent) { - if ( ent->spawnflags & 2048 ) - { + if (ent->spawnflags & 2048) { // this tie fighter hack is done for doom_detention, where the shooting gallery takes place. let them draw again when they start moving ent->s.eFlags &= ~EF_NODRAW; } ent->s.pos.trTime = level.time; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } } @@ -1813,136 +1602,117 @@ void Think_BeginMoving( gentity_t *ent ) { Reached_Train =============== */ -void Reached_Train( gentity_t *ent ) { - gentity_t *next; - float speed; - vec3_t move; - float length; +void Reached_Train(gentity_t *ent) { + gentity_t *next; + float speed; + vec3_t move; + float length; // copy the apropriate values next = ent->nextTrain; - if ( !next || !next->nextTrain ) { - //FIXME: can we go backwards- say if we are toggle-able? - return; // just stop + if (!next || !next->nextTrain) { + // FIXME: can we go backwards- say if we are toggle-able? + return; // just stop } // fire all other targets - G_UseTargets( next, ent ); + G_UseTargets(next, ent); // set the new trajectory ent->nextTrain = next->nextTrain; - VectorCopy( next->s.origin, ent->pos1 ); - VectorCopy( next->nextTrain->s.origin, ent->pos2 ); + VectorCopy(next->s.origin, ent->pos1); + VectorCopy(next->nextTrain->s.origin, ent->pos2); // if the path_corner has a speed, use that - if ( next->speed ) { + if (next->speed) { speed = next->speed; } else { // otherwise use the train's speed speed = ent->speed; } - if ( speed < 1 ) { + if (speed < 1) { speed = 1; } // calculate duration - VectorSubtract( ent->pos2, ent->pos1, move ); - length = VectorLength( move ); + VectorSubtract(ent->pos2, ent->pos1, move); + length = VectorLength(move); ent->s.pos.trDuration = length * 1000 / speed; // looping sound -/* - if ( VALIDSTRING( next->soundSet ) ) - { - ent->s.loopSound = CAS_GetBModelSound( next->soundSet, BMS_MID );//ent->soundLoop; - } -*/ - G_PlayDoorLoopSound( ent ); + /* + if ( VALIDSTRING( next->soundSet ) ) + { + ent->s.loopSound = CAS_GetBModelSound( next->soundSet, BMS_MID );//ent->soundLoop; + } + */ + G_PlayDoorLoopSound(ent); // start it going - SetMoverState( ent, MOVER_1TO2, level.time ); + SetMoverState(ent, MOVER_1TO2, level.time); - if (( next->spawnflags & 1 )) - { + if ((next->spawnflags & 1)) { vec3_t angs; - vectoangles( move, angs ); - AnglesSubtract( angs, ent->currentAngles, angs ); + vectoangles(move, angs); + AnglesSubtract(angs, ent->currentAngles, angs); - for ( int i = 0; i < 3; i++ ) - { - AngleNormalize360( angs[i] ); + for (int i = 0; i < 3; i++) { + AngleNormalize360(angs[i]); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorScale( angs, 0.5f, ent->s.apos.trDelta ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorScale(angs, 0.5f, ent->s.apos.trDelta); ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 2000; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } - } - else - { - if (( next->spawnflags & 4 )) - {//yaw + } else { + if ((next->spawnflags & 4)) { // yaw vec3_t angs; - vectoangles( move, angs ); - AnglesSubtract( angs, ent->currentAngles, angs ); + vectoangles(move, angs); + AnglesSubtract(angs, ent->currentAngles, angs); - for ( int i = 0; i < 3; i++ ) - { - AngleNormalize360( angs[i] ); + for (int i = 0; i < 3; i++) { + AngleNormalize360(angs[i]); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trDelta[YAW] = angs[YAW] * 0.5f; - if (( next->spawnflags & 8 )) - {//roll, too + if ((next->spawnflags & 8)) { // roll, too ent->s.apos.trDelta[ROLL] = angs[YAW] * -0.1f; } ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 2000; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } } } - // This is for the tie fighter shooting gallery on doom detention, you could see them waiting under the bay, but the architecture couldn't easily be changed.. - if (( next->spawnflags & 2 )) - { + // This is for the tie fighter shooting gallery on doom detention, you could see them waiting under the bay, but the architecture couldn't easily be + // changed.. + if ((next->spawnflags & 2)) { ent->s.eFlags |= EF_NODRAW; // make us invisible until we start moving again } // if there is a "wait" value on the target, don't start moving yet - if ( next->wait ) - { + if (next->wait) { ent->nextthink = level.time + next->wait * 1000; ent->e_ThinkFunc = thinkF_Think_BeginMoving; ent->s.pos.trType = TR_STATIONARY; - } - else if (!( next->spawnflags & 2 )) - { + } else if (!(next->spawnflags & 2)) { // we aren't waiting to start, so let us draw right away ent->s.eFlags &= ~EF_NODRAW; } } -void TrainUse( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - Reached_Train( ent ); -} +void TrainUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { Reached_Train(ent); } /* =============== @@ -1951,36 +1721,34 @@ Think_SetupTrainTargets Link all the corners together =============== */ -void Think_SetupTrainTargets( gentity_t *ent ) { - gentity_t *path, *next, *start; +void Think_SetupTrainTargets(gentity_t *ent) { + gentity_t *path, *next, *start; - ent->nextTrain = G_Find( NULL, FOFS(targetname), ent->target ); - if ( !ent->nextTrain ) { - gi.Printf( "func_train at %s with an unfound target\n", vtos(ent->absmin) ); - //Free me?` + ent->nextTrain = G_Find(NULL, FOFS(targetname), ent->target); + if (!ent->nextTrain) { + gi.Printf("func_train at %s with an unfound target\n", vtos(ent->absmin)); + // Free me?` return; } - //FIXME: this can go into an infinite loop if last path_corner doesn't link to first - //path_corner, like so: - // t1---->t2---->t3 - // ^ | - // \_____| + // FIXME: this can go into an infinite loop if last path_corner doesn't link to first + // path_corner, like so: + // t1---->t2---->t3 + // ^ | + // \_____| start = NULL; next = NULL; - int iterations = 2000; //max attempts to find our path start - for ( path = ent->nextTrain ; path != start ; path = next ) { - if (!iterations--) - { - G_Error( "Think_SetupTrainTargets: last path_corner doesn't link back to first on func_train(%s)", vtos(ent->absmin) ); + int iterations = 2000; // max attempts to find our path start + for (path = ent->nextTrain; path != start; path = next) { + if (!iterations--) { + G_Error("Think_SetupTrainTargets: last path_corner doesn't link back to first on func_train(%s)", vtos(ent->absmin)); } - if (!start) - { + if (!start) { start = path; } - if ( !path->target ) { -// gi.Printf( "Train corner at %s without a target\n", vtos(path->s.origin) ); - //end of path + if (!path->target) { + // gi.Printf( "Train corner at %s without a target\n", vtos(path->s.origin) ); + // end of path break; } @@ -1989,37 +1757,29 @@ void Think_SetupTrainTargets( gentity_t *ent ) { // is reached next = NULL; do { - next = G_Find( next, FOFS(targetname), path->target ); - if ( !next ) { -// gi.Printf( "Train corner at %s without a target path_corner\n", vtos(path->s.origin) ); - //end of path + next = G_Find(next, FOFS(targetname), path->target); + if (!next) { + // gi.Printf( "Train corner at %s without a target path_corner\n", vtos(path->s.origin) ); + // end of path break; } - } while ( strcmp( next->classname, "path_corner" ) ); + } while (strcmp(next->classname, "path_corner")); - if ( next ) - { + if (next) { path->nextTrain = next; - } - else - { + } else { break; } } - if ( !ent->targetname || (ent->spawnflags&1) /*start on*/) - { + if (!ent->targetname || (ent->spawnflags & 1) /*start on*/) { // start the train moving from the first corner - Reached_Train( ent ); - } - else - { - G_SetOrigin( ent, ent->s.origin ); + Reached_Train(ent); + } else { + G_SetOrigin(ent, ent->s.origin); } } - - /*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8) TURN_TRAIN INVISIBLE YAW_TRAIN ROLL_TRAIN TURN_TRAIN func_train moving on this path will turn to face the next path_corner within 2 seconds @@ -2031,28 +1791,25 @@ Target: next path corner and other targets to fire "speed" speed to move to the next corner "wait" seconds to wait before behining move to next corner */ -void SP_path_corner( gentity_t *self ) { - if ( !self->targetname ) { - gi.Printf ("path_corner with no targetname at %s\n", vtos(self->s.origin)); - G_FreeEntity( self ); +void SP_path_corner(gentity_t *self) { + if (!self->targetname) { + gi.Printf("path_corner with no targetname at %s\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } // path corners don't need to be linked in VectorCopy(self->s.origin, self->currentOrigin); } - -void func_train_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - if ( self->target3 ) - { - G_UseTargets2( self, self, self->target3 ); +void func_train_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (self->target3) { + G_UseTargets2(self, self, self->target3); } - //HACKHACKHACKHACK - G_PlayEffect( "explosions/fighter_explosion2", self->currentOrigin ); - G_FreeEntity( self ); - //HACKHACKHACKHACK + // HACKHACKHACKHACK + G_PlayEffect("explosions/fighter_explosion2", self->currentOrigin); + G_FreeEntity(self); + // HACKHACKHACKHACK } /*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS x x LOOP PLAYER_USE INACTIVE TIE @@ -2080,8 +1837,8 @@ The train spawns at the first target it is pointing at. "startframe" default 0...ghoul2 animation start frame "endframe" default 0...ghoul2 animation end frame */ -void SP_func_train (gentity_t *self) { - VectorClear (self->s.angles); +void SP_func_train(gentity_t *self) { + VectorClear(self->s.angles); if (self->spawnflags & TRAIN_BLOCK_STOPS) { self->damage = 0; @@ -2091,49 +1848,46 @@ void SP_func_train (gentity_t *self) { } } - if ( !self->speed ) { + if (!self->speed) { self->speed = 100; } - if ( !self->target ) { - gi.Printf ("func_train without a target at %s\n", vtos(self->absmin)); - G_FreeEntity( self ); + if (!self->target) { + gi.Printf("func_train without a target at %s\n", vtos(self->absmin)); + G_FreeEntity(self); return; } char *noise; - G_SpawnInt( "startframe", "0", &self->startFrame ); - G_SpawnInt( "endframe", "0", &self->endFrame ); + G_SpawnInt("startframe", "0", &self->startFrame); + G_SpawnInt("endframe", "0", &self->endFrame); - if ( G_SpawnString( "noise", "", &noise ) ) - { - if ( VALIDSTRING( noise ) ) - { - self->s.loopSound = cgi_S_RegisterSound( noise );//G_SoundIndex( noise ); + if (G_SpawnString("noise", "", &noise)) { + if (VALIDSTRING(noise)) { + self->s.loopSound = cgi_S_RegisterSound(noise); // G_SoundIndex( noise ); } } - gi.SetBrushModel( self, self->model ); - InitMover( self ); + gi.SetBrushModel(self, self->model); + InitMover(self); - if ( self->spawnflags & 2048 ) // TIE HACK + if (self->spawnflags & 2048) // TIE HACK { - //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK - self->s.modelindex2 = G_ModelIndex( "models/map_objects/ships/tie_fighter.md3" ); - G_EffectIndex( "explosions/fighter_explosion2" ); + // HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK + self->s.modelindex2 = G_ModelIndex("models/map_objects/ships/tie_fighter.md3"); + G_EffectIndex("explosions/fighter_explosion2"); self->contents = CONTENTS_SHOTCLIP; self->takedamage = qtrue; - VectorSet( self->maxs, 112, 112, 112 ); - VectorSet( self->mins, -112, -112, -112 ); - self->e_DieFunc = dieF_func_train_die; - gi.linkentity( self ); - //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK + VectorSet(self->maxs, 112, 112, 112); + VectorSet(self->mins, -112, -112, -112); + self->e_DieFunc = dieF_func_train_die; + gi.linkentity(self); + // HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK } - if ( self->targetname ) - { + if (self->targetname) { self->e_UseFunc = useF_TrainUse; } @@ -2144,12 +1898,13 @@ void SP_func_train (gentity_t *self) { self->nextthink = level.time + START_TIME_LINK_ENTS; self->e_ThinkFunc = thinkF_Think_SetupTrainTargets; - - if ( self->playerModel >= 0 && self->spawnflags & 32 ) // loop...dunno, could support it on other things, but for now I need it for the glider...so...kill the flag + if (self->playerModel >= 0 && + self->spawnflags & 32) // loop...dunno, could support it on other things, but for now I need it for the glider...so...kill the flag { self->spawnflags &= ~32; // once only - gi.G2API_SetBoneAnim( &self->ghoul2[self->playerModel], "model_root", self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_LOOP, 1.0f + Q_flrand(-1.0f, 1.0f) * 0.1f, 0, -1, -1 ); + gi.G2API_SetBoneAnim(&self->ghoul2[self->playerModel], "model_root", self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_LOOP, + 1.0f + Q_flrand(-1.0f, 1.0f) * 0.1f, 0, -1, -1); self->endFrame = 0; // don't allow it to do anything with the animation function in G_main } } @@ -2182,59 +1937,50 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls "linear" set to 1 and it will move linearly rather than with acceleration (default is 0) "NPC_targetname" if set up to be push/pullable, only this NPC can push/pull it (for the player, use "player") */ -void SP_func_static( gentity_t *ent ) -{ - gi.SetBrushModel( ent, ent->model ); +void SP_func_static(gentity_t *ent) { + gi.SetBrushModel(ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); + InitMover(ent); - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); ent->e_UseFunc = useF_func_static_use; ent->e_ReachedFunc = reachedF_NULL; - - if( ent->spawnflags & 2048 ) - { // yes this is very very evil, but for now (pre-alpha) it's a solution + if (ent->spawnflags & 2048) { // yes this is very very evil, but for now (pre-alpha) it's a solution ent->svFlags |= SVF_BROADCAST; // I need to rotate something that is huge and it's touching too many area portals... } - if ( ent->spawnflags & 4/*SWITCH_SHADER*/ ) - { - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim - ent->spawnflags &= ~4;//this is the CRUSHER spawnflag! remove it! + if (ent->spawnflags & 4 /*SWITCH_SHADER*/) { + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim + ent->spawnflags &= ~4; // this is the CRUSHER spawnflag! remove it! } - if ( ent->spawnflags & 8 ) - {//!!! 8 is NOT the crusher spawnflag, 4 is!!! + if (ent->spawnflags & 8) { //!!! 8 is NOT the crusher spawnflag, 4 is!!! ent->spawnflags &= ~8; ent->spawnflags |= MOVER_CRUSHER; - if ( !ent->damage ) - { + if (!ent->damage) { ent->damage = 2; } } - gi.linkentity( ent ); + gi.linkentity(ent); - if (level.mBSPInstanceDepth) - { // this means that this guy will never be updated, moved, changed, etc. + if (level.mBSPInstanceDepth) { // this means that this guy will never be updated, moved, changed, etc. ent->s.eFlags = EF_PERMANENT; } } -void func_static_use ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior( self, BSET_USE ); +void func_static_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 4/*SWITCH_SHADER*/ ) - { - self->s.frame = self->s.frame ? 0 : 1;//toggle frame + if (self->spawnflags & 4 /*SWITCH_SHADER*/) { + self->s.frame = self->s.frame ? 0 : 1; // toggle frame } - G_UseTargets( self, activator ); + G_UseTargets(self, activator); } /* @@ -2244,49 +1990,40 @@ ROTATING =============================================================================== */ -void func_rotating_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ -// vec3_t spot; -// gentity_t *tent; - if( !other->client ) // don't want to disintegrate items or weapons, etc... +void func_rotating_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + // vec3_t spot; + // gentity_t *tent; + if (!other->client) // don't want to disintegrate items or weapons, etc... { return; } // yeah, this is a bit hacky... - if( self->s.apos.trType != TR_STATIONARY && !(other->flags & FL_DISINTEGRATED) ) // only damage if it's moving + if (self->s.apos.trType != TR_STATIONARY && !(other->flags & FL_DISINTEGRATED)) // only damage if it's moving { -// VectorCopy( self->currentOrigin, spot ); -// tent = G_TempEntity( spot, EV_DISINTEGRATION ); -// tent->s.eventParm = PW_DISRUPTION; -// tent->owner = self; + // VectorCopy( self->currentOrigin, spot ); + // tent = G_TempEntity( spot, EV_DISINTEGRATION ); + // tent->s.eventParm = PW_DISRUPTION; + // tent->owner = self; // let G_Damage call the fx instead, beside, this way you can disintegrate a corpse this way - G_Sound( other, G_SoundIndex( "sound/effects/energy_crackle.wav" ) ); - G_Damage( other, self, self, NULL, NULL, 10000, DAMAGE_NO_KNOCKBACK, MOD_SNIPER ); + G_Sound(other, G_SoundIndex("sound/effects/energy_crackle.wav")); + G_Damage(other, self, self, NULL, NULL, 10000, DAMAGE_NO_KNOCKBACK, MOD_SNIPER); } } - -void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if( self->s.apos.trType == TR_LINEAR ) - { +void func_rotating_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->s.apos.trType == TR_LINEAR) { self->s.apos.trType = TR_STATIONARY; // stop the sound if it stops moving self->s.loopSound = 0; // play stop sound too? - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_END )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_END)); } - } - else - { - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - self->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); - if ( self->s.loopSound < 0 ) - { + } else { + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + self->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); + if (self->s.loopSound < 0) { self->s.loopSound = 0; } } @@ -2294,7 +2031,6 @@ void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator } } - /*QUAKED func_rotating (0 .5 .8) ? START_ON TOUCH_KILL X_AXIS Y_AXIS x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button TOUCH_KILL Inflicts massive damage upon touching it, disitegrates bodies @@ -2311,21 +2047,20 @@ check either the X_AXIS or Y_AXIS box to change that. "color" constantLight color "light" constantLight radius */ -void SP_func_rotating (gentity_t *ent) { - if ( !ent->speed ) { +void SP_func_rotating(gentity_t *ent) { + if (!ent->speed) { ent->speed = 100; } - ent->s.apos.trType = TR_STATIONARY; - if( ent->spawnflags & 1 ) // start on + if (ent->spawnflags & 1) // start on { ent->s.apos.trType = TR_LINEAR; } // set the axis of rotation - if ( ent->spawnflags & 4 ) { + if (ent->spawnflags & 4) { ent->s.apos.trDelta[2] = ent->speed; - } else if ( ent->spawnflags & 8 ) { + } else if (ent->spawnflags & 8) { ent->s.apos.trDelta[0] = ent->speed; } else { ent->s.apos.trDelta[1] = ent->speed; @@ -2335,28 +2070,24 @@ void SP_func_rotating (gentity_t *ent) { ent->damage = 2; } + gi.SetBrushModel(ent, ent->model); + InitMover(ent); - gi.SetBrushModel( ent, ent->model ); - InitMover( ent ); - - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_func_rotating_use; } - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); - VectorCopy( ent->s.apos.trBase, ent->currentAngles ); - if( ent->spawnflags & 2 ) - { + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); + VectorCopy(ent->s.apos.trBase, ent->currentAngles); + if (ent->spawnflags & 2) { ent->e_TouchFunc = touchF_func_rotating_touch; - G_SoundIndex( "sound/effects/energy_crackle.wav" ); + G_SoundIndex("sound/effects/energy_crackle.wav"); } - gi.linkentity( ent ); + gi.linkentity(ent); } - /* =============================================================================== @@ -2365,26 +2096,22 @@ BOBBING =============================================================================== */ -void func_bobbing_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void func_bobbing_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle our move state - if ( self->s.pos.trType == TR_SINE ) - { + if (self->s.pos.trType == TR_SINE) { self->s.pos.trType = TR_INTERPOLATE; // Save off roughly where we were - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); // Store the current phase value so we know how to start up where we left off. - self->radius = ( level.time - self->s.pos.trTime ) / (float)self->s.pos.trDuration; - } - else - { + self->radius = (level.time - self->s.pos.trTime) / (float)self->s.pos.trDuration; + } else { self->s.pos.trType = TR_SINE; // Set the time based on the saved phase value self->s.pos.trTime = level.time - self->s.pos.trDuration * self->radius; // Always make sure we are starting with a fresh base - VectorCopy( self->s.origin, self->s.pos.trBase ); + VectorCopy(self->s.origin, self->s.pos.trBase); } } @@ -2403,25 +2130,25 @@ Normally bobs on the Z axis "light" constantLight radius "targetname" turns on/off when used */ -void SP_func_bobbing (gentity_t *ent) { - float height; - float phase; +void SP_func_bobbing(gentity_t *ent) { + float height; + float phase; - G_SpawnFloat( "speed", "4", &ent->speed ); - G_SpawnFloat( "height", "32", &height ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "4", &ent->speed); + G_SpawnFloat("height", "32", &height); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - gi.SetBrushModel( ent, ent->model ); - InitMover( ent ); + gi.SetBrushModel(ent, ent->model); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // set the axis of bobbing - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.pos.trDelta[0] = height; - } else if ( ent->spawnflags & 2 ) { + } else if (ent->spawnflags & 2) { ent->s.pos.trDelta[1] = height; } else { ent->s.pos.trDelta[2] = height; @@ -2430,22 +2157,19 @@ void SP_func_bobbing (gentity_t *ent) { ent->s.pos.trDuration = ent->speed * 1000; ent->s.pos.trTime = ent->s.pos.trDuration * phase; - if ( ent->spawnflags & 4 ) // start_off + if (ent->spawnflags & 4) // start_off { ent->s.pos.trType = TR_INTERPOLATE; // Now use the phase to calculate where it should be at the start. ent->radius = phase; - phase = (float)sin( phase * M_PI * 2 ); - VectorMA( ent->s.pos.trBase, phase, ent->s.pos.trDelta, ent->s.pos.trBase ); + phase = (float)sin(phase * M_PI * 2); + VectorMA(ent->s.pos.trBase, phase, ent->s.pos.trDelta, ent->s.pos.trBase); - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_func_bobbing_use; } - } - else - { + } else { ent->s.pos.trType = TR_SINE; } } @@ -2458,7 +2182,6 @@ PENDULUM =============================================================================== */ - /*QUAKED func_pendulum (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used @@ -2475,33 +2198,33 @@ Pendulum frequency is a physical constant based on the length of the beam and gr "light" constantLight radius */ void SP_func_pendulum(gentity_t *ent) { - float freq; - float length; - float phase; - float speed; + float freq; + float length; + float phase; + float speed; - G_SpawnFloat( "speed", "30", &speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "30", &speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); // find pendulum length - length = fabs( ent->mins[2] ); - if ( length < 8 ) { + length = fabs(ent->mins[2]); + if (length < 8) { length = 8; } - freq = 1 / ( M_PI * 2 ) * sqrt( g_gravity->value / ( 3 * length ) ); + freq = 1 / (M_PI * 2) * sqrt(g_gravity->value / (3 * length)); - ent->s.pos.trDuration = ( 1000 / freq ); + ent->s.pos.trDuration = (1000 / freq); - InitMover( ent ); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->s.apos.trDuration = 1000 / freq; ent->s.apos.trTime = ent->s.apos.trDuration * phase; @@ -2518,33 +2241,29 @@ WALL =============================================================================== */ -//static -slc -void use_wall( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +// static -slc +void use_wall(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); // Not there so make it there - //if (!(ent->contents & CONTENTS_SOLID)) + // if (!(ent->contents & CONTENTS_SOLID)) if (!ent->count) // off { ent->svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; ent->count = 1; - //NOTE: reset the brush model because we need to get *all* the contents back - //ent->contents |= CONTENTS_SOLID; - gi.SetBrushModel( ent, ent->model ); - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( ent, qfalse ); + // NOTE: reset the brush model because we need to get *all* the contents back + // ent->contents |= CONTENTS_SOLID; + gi.SetBrushModel(ent, ent->model); + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(ent, qfalse); } } // Make it go away - else - { - //NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( ent, qtrue ); + else { + // NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(ent, qtrue); } ent->contents = 0; ent->svFlags |= SVF_NOCLIENT; @@ -2553,9 +2272,8 @@ void use_wall( gentity_t *ent, gentity_t *other, gentity_t *activator ) } } -#define FUNC_WALL_OFF 1 -#define FUNC_WALL_ANIM 2 - +#define FUNC_WALL_OFF 1 +#define FUNC_WALL_ANIM 2 /*QUAKED func_wall (0 .5 .8) ? START_OFF AUTOANIMATE x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button @@ -2570,23 +2288,21 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls START_OFF - the wall will not be there AUTOANIMATE - if a model is used it will animate */ -void SP_func_wall( gentity_t *ent ) -{ - gi.SetBrushModel( ent, ent->model ); +void SP_func_wall(gentity_t *ent) { + gi.SetBrushModel(ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + InitMover(ent); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // count is used as an on/off switch (start it on) ent->count = 1; // it must be START_OFF - if (ent->spawnflags & FUNC_WALL_OFF) - { + if (ent->spawnflags & FUNC_WALL_OFF) { ent->spawnContents = ent->contents; ent->contents = 0; ent->svFlags |= SVF_NOCLIENT; @@ -2595,55 +2311,43 @@ void SP_func_wall( gentity_t *ent ) ent->count = 0; } - if (!(ent->spawnflags & FUNC_WALL_ANIM)) - { + if (!(ent->spawnflags & FUNC_WALL_ANIM)) { ent->s.eFlags |= EF_ANIM_ALLFAST; } ent->e_UseFunc = useF_use_wall; - gi.linkentity (ent); - + gi.linkentity(ent); } - -void security_panel_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator ) - { +void security_panel_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator) { return; } - if ( INV_SecurityKeyCheck( activator, self->message ) ) - {//congrats! - gi.SendServerCommand( 0, "cp @SP_INGAME_SECURITY_KEY_UNLOCKEDDOOR" ); - //use targets - G_UseTargets( self, activator ); - //take key - INV_SecurityKeyTake( activator, self->message ); - if ( activator->ghoul2.size() ) - { - gi.G2API_SetSurfaceOnOff( &activator->ghoul2[activator->playerModel], "l_arm_key", 0x00000002 ); - } - //FIXME: maybe set frame on me to have key sticking out? - //self->s.frame = 1; - //play sound - G_Sound( self, self->soundPos2 ); - //unusable + if (INV_SecurityKeyCheck(activator, self->message)) { // congrats! + gi.SendServerCommand(0, "cp @SP_INGAME_SECURITY_KEY_UNLOCKEDDOOR"); + // use targets + G_UseTargets(self, activator); + // take key + INV_SecurityKeyTake(activator, self->message); + if (activator->ghoul2.size()) { + gi.G2API_SetSurfaceOnOff(&activator->ghoul2[activator->playerModel], "l_arm_key", 0x00000002); + } + // FIXME: maybe set frame on me to have key sticking out? + // self->s.frame = 1; + // play sound + G_Sound(self, self->soundPos2); + // unusable self->e_UseFunc = useF_NULL; - } - else - {//failure sound/display - if ( activator->message ) - {//have a key, just the wrong one - gi.SendServerCommand( 0, "cp @SP_INGAME_INCORRECT_KEY" ); - } - else - {//don't have a key at all - gi.SendServerCommand( 0, "cp @SP_INGAME_NEED_SECURITY_KEY" ); - } - G_UseTargets2( self, activator, self->target2 ); - //FIXME: change display? Maybe shader animmap change? - //play sound - G_Sound( self, self->soundPos1 ); + } else { // failure sound/display + if (activator->message) { // have a key, just the wrong one + gi.SendServerCommand(0, "cp @SP_INGAME_INCORRECT_KEY"); + } else { // don't have a key at all + gi.SendServerCommand(0, "cp @SP_INGAME_NEED_SECURITY_KEY"); + } + G_UseTargets2(self, activator, self->target2); + // FIXME: change display? Maybe shader animmap change? + // play sound + G_Sound(self, self->soundPos1); } } @@ -2657,22 +2361,20 @@ INACTIVE - Start off, has to be activated to be usable "target" thing to use when successfully opened "target2" thing to use when player uses the panel without the key */ -void SP_misc_security_panel ( gentity_t *self ) -{ - self->s.modelindex = G_ModelIndex( "models/map_objects/kejim/sec_panel.md3" ); - self->soundPos1 = G_SoundIndex( "sound/movers/sec_panel_fail.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/sec_panel_pass.mp3" ); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); - VectorSet( self->mins, -8, -8, -8 ); - VectorSet( self->maxs, 8, 8, 8 ); +void SP_misc_security_panel(gentity_t *self) { + self->s.modelindex = G_ModelIndex("models/map_objects/kejim/sec_panel.md3"); + self->soundPos1 = G_SoundIndex("sound/movers/sec_panel_fail.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/sec_panel_pass.mp3"); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); + VectorSet(self->mins, -8, -8, -8); + VectorSet(self->maxs, 8, 8, 8); self->contents = CONTENTS_SOLID; - gi.linkentity( self ); + gi.linkentity(self); - //NOTE: self->message is the key + // NOTE: self->message is the key self->svFlags |= SVF_PLAYER_USABLE; - if(self->spawnflags & 128) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } self->e_UseFunc = useF_security_panel_use; diff --git a/code/game/g_nav.cpp b/code/game/g_nav.cpp index 75059068b9..f2a2a6a296 100644 --- a/code/game/g_nav.cpp +++ b/code/game/g_nav.cpp @@ -24,78 +24,68 @@ along with this program; if not, see . #include "g_nav.h" #include "g_navigator.h" -//Global navigator -//CNavigator navigator; - -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean G_EntIsRemovableUsable( int entNum ); -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -//For debug graphics -extern void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ); -extern qboolean FlyingCreature( gentity_t *ent ); - +// Global navigator +// CNavigator navigator; + +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean G_EntIsRemovableUsable(int entNum); +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +// For debug graphics +extern void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha); +extern qboolean FlyingCreature(gentity_t *ent); extern vec3_t NPCDEBUG_RED; - /* ------------------------- NPC_SetMoveGoal ------------------------- */ -void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt ) -{ - //Must be an NPC - if ( ent->NPC == NULL ) - { +void NPC_SetMoveGoal(gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt) { + // Must be an NPC + if (ent->NPC == NULL) { return; } - if ( ent->NPC->tempGoal == NULL ) - {//must still have a goal + if (ent->NPC->tempGoal == NULL) { // must still have a goal return; } - //Copy the origin - //VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! - VectorCopy( point, ent->NPC->tempGoal->currentOrigin ); - - //Copy the mins and maxs to the tempGoal - VectorCopy( ent->mins, ent->NPC->tempGoal->mins ); - VectorCopy( ent->mins, ent->NPC->tempGoal->maxs ); - - //FIXME: TESTING let's try making sure the tempGoal isn't stuck in the ground? - if ( 0 ) - { - trace_t trace; - vec3_t bottom = {ent->NPC->tempGoal->currentOrigin[0],ent->NPC->tempGoal->currentOrigin[1],ent->NPC->tempGoal->currentOrigin[2]+ent->NPC->tempGoal->mins[2]}; - gi.trace( &trace, ent->NPC->tempGoal->currentOrigin, vec3_origin, vec3_origin, bottom, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f ) - {//in the ground, raise it up - ent->NPC->tempGoal->currentOrigin[2] -= ent->NPC->tempGoal->mins[2]*(1.0f-trace.fraction)-0.125f; + // Copy the origin + // VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! + VectorCopy(point, ent->NPC->tempGoal->currentOrigin); + + // Copy the mins and maxs to the tempGoal + VectorCopy(ent->mins, ent->NPC->tempGoal->mins); + VectorCopy(ent->mins, ent->NPC->tempGoal->maxs); + + // FIXME: TESTING let's try making sure the tempGoal isn't stuck in the ground? + if (0) { + trace_t trace; + vec3_t bottom = {ent->NPC->tempGoal->currentOrigin[0], ent->NPC->tempGoal->currentOrigin[1], + ent->NPC->tempGoal->currentOrigin[2] + ent->NPC->tempGoal->mins[2]}; + gi.trace(&trace, ent->NPC->tempGoal->currentOrigin, vec3_origin, vec3_origin, bottom, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f) { // in the ground, raise it up + ent->NPC->tempGoal->currentOrigin[2] -= ent->NPC->tempGoal->mins[2] * (1.0f - trace.fraction) - 0.125f; } } ent->NPC->tempGoal->target = NULL; ent->NPC->tempGoal->clipmask = ent->clipmask; ent->NPC->tempGoal->svFlags &= ~SVF_NAVGOAL; - if ( targetEnt && targetEnt->waypoint >= 0 ) - { + if (targetEnt && targetEnt->waypoint >= 0) { ent->NPC->tempGoal->waypoint = targetEnt->waypoint; - } - else - { + } else { ent->NPC->tempGoal->waypoint = WAYPOINT_NONE; } ent->NPC->tempGoal->noWaypointTime = 0; - if ( isNavGoal ) - { + if (isNavGoal) { assert(ent->NPC->tempGoal->owner); ent->NPC->tempGoal->svFlags |= SVF_NAVGOAL; } @@ -105,9 +95,9 @@ void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGo ent->NPC->goalEntity = ent->NPC->tempGoal; ent->NPC->goalRadius = radius; - ent->NPC->aiFlags &= ~NPCAI_STOP_AT_LOS; + ent->NPC->aiFlags &= ~NPCAI_STOP_AT_LOS; - gi.linkentity( ent->NPC->goalEntity ); + gi.linkentity(ent->NPC->goalEntity); } /* ------------------------- @@ -115,26 +105,25 @@ waypoint_testDirection ------------------------- */ -static float waypoint_testDirection( vec3_t origin, float yaw, float minDist ) -{ - vec3_t trace_dir, test_pos; - vec3_t maxs, mins; - trace_t tr; +static float waypoint_testDirection(vec3_t origin, float yaw, float minDist) { + vec3_t trace_dir, test_pos; + vec3_t maxs, mins; + trace_t tr; - //Setup the mins and max - VectorSet( maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2 ); - VectorSet( mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE ); + // Setup the mins and max + VectorSet(maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); + VectorSet(mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE); - //Get our test direction - vec3_t angles = { 0, yaw, 0 }; - AngleVectors( angles, trace_dir, NULL, NULL ); + // Get our test direction + vec3_t angles = {0, yaw, 0}; + AngleVectors(angles, trace_dir, NULL, NULL); - //Move ahead - VectorMA( origin, minDist, trace_dir, test_pos ); + // Move ahead + VectorMA(origin, minDist, trace_dir, test_pos); - gi.trace( &tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, ( CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP ), (EG2_Collision)0, 0 ); + gi.trace(&tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, (CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP), (EG2_Collision)0, 0); - return ( minDist * tr.fraction ); //return actual dist completed + return (minDist * tr.fraction); // return actual dist completed } /* @@ -143,16 +132,14 @@ waypoint_getRadius ------------------------- */ -static float waypoint_getRadius( gentity_t *ent ) -{ - float minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; - float dist; +static float waypoint_getRadius(gentity_t *ent) { + float minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; + float dist; - for ( int i = 0; i < YAW_ITERATIONS; i++ ) - { - dist = waypoint_testDirection( ent->currentOrigin, ((360.0f/YAW_ITERATIONS) * i), minDist ); + for (int i = 0; i < YAW_ITERATIONS; i++) { + dist = waypoint_testDirection(ent->currentOrigin, ((360.0f / YAW_ITERATIONS) * i), minDist); - if ( dist < minDist ) + if (dist < minDist) minDist = dist; } @@ -162,97 +149,89 @@ static float waypoint_getRadius( gentity_t *ent ) /*QUAKED waypoint (0.7 0.7 0) (-20 -20 -24) (20 20 45) SOLID_OK DROP_TO_FLOOR a place to go. -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) -DROP_TO_FLOOR - will cause the point to auto drop to the floor +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) DROP_TO_FLOOR - will cause the point to auto drop to the floor radius is automatically calculated in-world. "targetJump" is a special edge that only guys who can jump will cross (so basically Jedi) */ extern int delayedShutDown; -void SP_waypoint ( gentity_t *ent ) -{ - VectorSet(ent->mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2); - VectorSet(ent->maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); +void SP_waypoint(gentity_t *ent) { + VectorSet(ent->mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2); + VectorSet(ent->maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); - ent->contents = CONTENTS_TRIGGER; - ent->clipmask = MASK_DEADSOLID; + ent->contents = CONTENTS_TRIGGER; + ent->clipmask = MASK_DEADSOLID; - gi.linkentity( ent ); + gi.linkentity(ent); - ent->count = -1; - ent->classname = "waypoint"; + ent->count = -1; + ent->classname = "waypoint"; - if (ent->spawnflags&2) - { - ent->currentOrigin[2] += 128.0f; - } + if (ent->spawnflags & 2) { + ent->currentOrigin[2] += 128.0f; + } - if( !(ent->spawnflags&1) && G_CheckInSolid (ent, qtrue)) - {//if not SOLID_OK, and in solid - ent->maxs[2] = CROUCH_MAXS_2; - if(G_CheckInSolid (ent, qtrue)) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); - assert(0 && "Waypoint in solid!"); -// if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region -// G_Error("Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); -// } - delayedShutDown = level.time + 100; - G_FreeEntity(ent); - return; - } + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { // if not SOLID_OK, and in solid + ent->maxs[2] = CROUCH_MAXS_2; + if (G_CheckInSolid(ent, qtrue)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + assert(0 && "Waypoint in solid!"); + // if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + // G_Error("Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + // } + delayedShutDown = level.time + 100; + G_FreeEntity(ent); + return; } + } - //G_SpawnString("targetJump", "", &ent->targetJump); - ent->radius = waypoint_getRadius( ent ); - NAV::SpawnedPoint(ent); + // G_SpawnString("targetJump", "", &ent->targetJump); + ent->radius = waypoint_getRadius(ent); + NAV::SpawnedPoint(ent); - G_FreeEntity(ent); - return; + G_FreeEntity(ent); + return; } /*QUAKED waypoint_small (0.7 0.7 0) (-2 -2 -24) (2 2 32) SOLID_OK -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) -DROP_TO_FLOOR - will cause the point to auto drop to the floor +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) DROP_TO_FLOOR - will cause the point to auto drop to the floor */ -void SP_waypoint_small (gentity_t *ent) -{ - VectorSet(ent->mins, -2, -2, DEFAULT_MINS_2); - VectorSet(ent->maxs, 2, 2, DEFAULT_MAXS_2); - - ent->contents = CONTENTS_TRIGGER; - ent->clipmask = MASK_DEADSOLID; - - gi.linkentity( ent ); - - ent->count = -1; - ent->classname = "waypoint"; - - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qtrue ) ) - { - ent->maxs[2] = CROUCH_MAXS_2; - if ( G_CheckInSolid( ent, qtrue ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); - assert(0); +void SP_waypoint_small(gentity_t *ent) { + VectorSet(ent->mins, -2, -2, DEFAULT_MINS_2); + VectorSet(ent->maxs, 2, 2, DEFAULT_MAXS_2); + + ent->contents = CONTENTS_TRIGGER; + ent->clipmask = MASK_DEADSOLID; + + gi.linkentity(ent); + + ent->count = -1; + ent->classname = "waypoint"; + + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { + ent->maxs[2] = CROUCH_MAXS_2; + if (G_CheckInSolid(ent, qtrue)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + assert(0); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region - G_Error("Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); - } -#endif - G_FreeEntity(ent); - return; + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region + G_Error("Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); } +#endif + G_FreeEntity(ent); + return; } + } - ent->radius = 2; // radius - NAV::SpawnedPoint(ent); + ent->radius = 2; // radius + NAV::SpawnedPoint(ent); - G_FreeEntity(ent); - return; + G_FreeEntity(ent); + return; } - /*QUAKED waypoint_navgoal (0.3 1 0.3) (-20 -20 -24) (20 20 40) SOLID_OK DROP_TO_FLOOR NO_AUTO_CONNECT A waypoint for script navgoals Not included in navigation data @@ -261,7 +240,8 @@ DROP_TO_FLOOR - will cause the point to auto drop to the floor NO_AUTO_CONNECT - will not automatically connect to any other points, you must then connect it by hand -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -273,30 +253,28 @@ radius - how far from the navgoal an ent can be before it thinks it reached it - */ -void SP_waypoint_navgoal( gentity_t *ent ) -{ - int radius = ( ent->radius ) ? (ent->radius) : 12; +void SP_waypoint_navgoal(gentity_t *ent) { + int radius = (ent->radius) ? (ent->radius) : 12; - VectorSet( ent->mins, -16, -16, -24 ); - VectorSet( ent->maxs, 16, 16, 32 ); + VectorSet(ent->mins, -16, -16, -24); + VectorSet(ent->maxs, 16, 16, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); } #endif } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL); ent->classname = "navgoal"; NAV::SpawnedPoint(ent, NAV::PT_GOALNODE); - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /* @@ -305,121 +283,83 @@ Svcmd_Nav_f ------------------------- */ -void Svcmd_Nav_f( void ) -{ - const char *cmd = gi.argv( 1 ); +void Svcmd_Nav_f(void) { + const char *cmd = gi.argv(1); - if ( Q_stricmp( cmd, "show" ) == 0 ) - { - cmd = gi.argv( 2 ); + if (Q_stricmp(cmd, "show") == 0) { + cmd = gi.argv(2); - if ( Q_stricmp( cmd, "all" ) == 0 ) - { + if (Q_stricmp(cmd, "all") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - //NOTENOTE: This causes the two states to sync up if they aren't already - NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = - NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = - NAVDEBUG_showEdges = NAVDEBUG_showNearest = NAVDEBUG_showRadius = NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "nodes" ) == 0 ) - { + // NOTENOTE: This causes the two states to sync up if they aren't already + NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = NAVDEBUG_showEdges = NAVDEBUG_showNearest = + NAVDEBUG_showRadius = NAVDEBUG_showNodes; + } else if (Q_stricmp(cmd, "nodes") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "radius" ) == 0 ) - { + } else if (Q_stricmp(cmd, "radius") == 0) { NAVDEBUG_showRadius = !NAVDEBUG_showRadius; - } - else if ( Q_stricmp( cmd, "edges" ) == 0 ) - { + } else if (Q_stricmp(cmd, "edges") == 0) { NAVDEBUG_showEdges = !NAVDEBUG_showEdges; - } - else if ( Q_stricmp( cmd, "testpath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "testpath") == 0) { NAVDEBUG_showTestPath = !NAVDEBUG_showTestPath; - } - else if ( Q_stricmp( cmd, "enemypath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "enemypath") == 0) { NAVDEBUG_showEnemyPath = !NAVDEBUG_showEnemyPath; - } - else if ( Q_stricmp( cmd, "combatpoints" ) == 0 ) - { + } else if (Q_stricmp(cmd, "combatpoints") == 0) { NAVDEBUG_showCombatPoints = !NAVDEBUG_showCombatPoints; - } - else if ( Q_stricmp( cmd, "navgoals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "navgoals") == 0) { NAVDEBUG_showNavGoals = !NAVDEBUG_showNavGoals; - } - else if ( Q_stricmp( cmd, "collision" ) == 0 ) - { + } else if (Q_stricmp(cmd, "collision") == 0) { NAVDEBUG_showCollision = !NAVDEBUG_showCollision; - } - else if ( Q_stricmp( cmd, "grid" ) == 0 ) - { + } else if (Q_stricmp(cmd, "grid") == 0) { NAVDEBUG_showGrid = !NAVDEBUG_showGrid; - } - else if ( Q_stricmp( cmd, "nearest" ) == 0 ) - { + } else if (Q_stricmp(cmd, "nearest") == 0) { NAVDEBUG_showNearest = !NAVDEBUG_showNearest; - } - else if ( Q_stricmp( cmd, "lines" ) == 0 ) - { + } else if (Q_stricmp(cmd, "lines") == 0) { NAVDEBUG_showPointLines = !NAVDEBUG_showPointLines; } - } - else if ( Q_stricmp( cmd, "set" ) == 0 ) - { - cmd = gi.argv( 2 ); + } else if (Q_stricmp(cmd, "set") == 0) { + cmd = gi.argv(2); - if ( Q_stricmp( cmd, "testgoal" ) == 0 ) - { - // NAVDEBUG_curGoal = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + if (Q_stricmp(cmd, "testgoal") == 0) { + // NAVDEBUG_curGoal = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); } - } - else if ( Q_stricmp( cmd, "goto" ) == 0 ) - { - cmd = gi.argv( 2 ); + } else if (Q_stricmp(cmd, "goto") == 0) { + cmd = gi.argv(2); NAV::TeleportTo(&(g_entities[0]), cmd); - } - else if ( Q_stricmp( cmd, "gotonum" ) == 0 ) - { - cmd = gi.argv( 2 ); + } else if (Q_stricmp(cmd, "gotonum") == 0) { + cmd = gi.argv(2); NAV::TeleportTo(&(g_entities[0]), atoi(cmd)); - } - else if ( Q_stricmp( cmd, "totals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "totals") == 0) { NAV::ShowStats(); - } - else - { - //Print the available commands - Com_Printf("nav - valid commands\n---\n" ); + } else { + // Print the available commands + Com_Printf("nav - valid commands\n---\n"); Com_Printf("show\n - nodes\n - edges\n - testpath\n - enemypath\n - combatpoints\n - navgoals\n---\n"); - Com_Printf("goto\n ---\n" ); - Com_Printf("gotonum\n ---\n" ); - Com_Printf("totals\n ---\n" ); - Com_Printf("set\n - testgoal\n---\n" ); + Com_Printf("goto\n ---\n"); + Com_Printf("gotonum\n ---\n"); + Com_Printf("totals\n ---\n"); + Com_Printf("set\n - testgoal\n---\n"); } } // -//JWEIER ADDITIONS START - -bool navCalculatePaths = false; - -bool NAVDEBUG_showNodes = false; -bool NAVDEBUG_showRadius = false; -bool NAVDEBUG_showEdges = false; -bool NAVDEBUG_showTestPath = false; -bool NAVDEBUG_showEnemyPath = false; -bool NAVDEBUG_showCombatPoints = false; -bool NAVDEBUG_showNavGoals = false; -bool NAVDEBUG_showCollision = false; -int NAVDEBUG_curGoal = 0; -bool NAVDEBUG_showGrid = false; -bool NAVDEBUG_showNearest = false; -bool NAVDEBUG_showPointLines = false; - +// JWEIER ADDITIONS START + +bool navCalculatePaths = false; + +bool NAVDEBUG_showNodes = false; +bool NAVDEBUG_showRadius = false; +bool NAVDEBUG_showEdges = false; +bool NAVDEBUG_showTestPath = false; +bool NAVDEBUG_showEnemyPath = false; +bool NAVDEBUG_showCombatPoints = false; +bool NAVDEBUG_showNavGoals = false; +bool NAVDEBUG_showCollision = false; +int NAVDEBUG_curGoal = 0; +bool NAVDEBUG_showGrid = false; +bool NAVDEBUG_showNearest = false; +bool NAVDEBUG_showPointLines = false; // -//JWEIER ADDITIONS END +// JWEIER ADDITIONS END diff --git a/code/game/g_navigator.cpp b/code/game/g_navigator.cpp index 5ffaf66fbb..1ef21c15a1 100644 --- a/code/game/g_navigator.cpp +++ b/code/game/g_navigator.cpp @@ -37,27 +37,34 @@ along with this program; if not, see . //////////////////////////////////////////////////////////////////////////////////////// // HFile Bindings //////////////////////////////////////////////////////////////////////////////////////// -bool HFILEopen_read(int& handle, const char* filepath) {gi.FS_FOpenFile(filepath, &handle, FS_READ); return (handle!=0);} -bool HFILEopen_write(int& handle, const char* filepath) {gi.FS_FOpenFile(filepath, &handle, FS_WRITE); return (handle!=0);} -bool HFILEread(int& handle, void* data, int size) {return (gi.FS_Read(data, size, handle)!=0);} -bool HFILEwrite(int& handle, const void* data, int size) {return (gi.FS_Write(data, size, handle)!=0);} -bool HFILEclose(int& handle) {gi.FS_FCloseFile(handle); return true;} - - +bool HFILEopen_read(int &handle, const char *filepath) { + gi.FS_FOpenFile(filepath, &handle, FS_READ); + return (handle != 0); +} +bool HFILEopen_write(int &handle, const char *filepath) { + gi.FS_FOpenFile(filepath, &handle, FS_WRITE); + return (handle != 0); +} +bool HFILEread(int &handle, void *data, int size) { return (gi.FS_Read(data, size, handle) != 0); } +bool HFILEwrite(int &handle, const void *data, int size) { return (gi.FS_Write(data, size, handle) != 0); } +bool HFILEclose(int &handle) { + gi.FS_FCloseFile(handle); + return true; +} //////////////////////////////////////////////////////////////////////////////////////// // Externs //////////////////////////////////////////////////////////////////////////////////////// -extern gentity_t* G_FindDoorTrigger( gentity_t *ent ); -extern qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ); -extern qboolean G_CheckInSolidTeleport (const vec3_t& teleportPos, gentity_t *self); +extern gentity_t *G_FindDoorTrigger(gentity_t *ent); +extern qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker); +extern qboolean G_CheckInSolidTeleport(const vec3_t &teleportPos, gentity_t *self); -extern cvar_t* g_nav1; -extern cvar_t* g_nav2; -extern cvar_t* g_developer; -extern int delayedShutDown; -extern vec3_t playerMinsStep; -extern vec3_t playerMaxs; +extern cvar_t *g_nav1; +extern cvar_t *g_nav2; +extern cvar_t *g_developer; +extern int delayedShutDown; +extern vec3_t playerMinsStep; +extern vec3_t playerMaxs; //////////////////////////////////////////////////////////////////////////////////////// // Includes @@ -65,173 +72,141 @@ extern vec3_t playerMaxs; #include "b_local.h" #include "g_navigator.h" #if !defined(RAGL_GRAPH_VS_INC) - #include "../Ragl/graph_vs.h" +#include "../Ragl/graph_vs.h" #endif #if !defined(RATL_GRAPH_REGION_INC) - #include "../Ragl/graph_region.h" +#include "../Ragl/graph_region.h" #endif #if !defined(RATL_VECTOR_VS_INC) - #include "../Ratl/vector_vs.h" +#include "../Ratl/vector_vs.h" #endif #if !defined(RUFL_HSTRING_INC) - #include "../Rufl/hstring.h" +#include "../Rufl/hstring.h" #endif #if !defined(RUFL_HFILE_INC) - #include "../Rufl/hfile.h" +#include "../Rufl/hfile.h" #endif #if !defined(RAVL_BOUNDS_INC) - #include "../Ravl/CBounds.h" +#include "../Ravl/CBounds.h" #endif - - - //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define NAV_VERSION 1.3f -#define NEIGHBORING_DIST 200.0f -#define SAFE_NEIGHBORINGPOINT_DIST 400.0f -#define SAFE_AT_NAV_DIST_SQ 6400.0f //80*80 -#define SAFE_GOTO_DIST_SQ 19600.0f //140*140 - -namespace NAV -{ - enum - { - NUM_NODES = 1024, - // now 5 bytes each - NUM_EDGES = 3*NUM_NODES, - NUM_EDGES_PER_NODE = 20, - +#define NAV_VERSION 1.3f +#define NEIGHBORING_DIST 200.0f +#define SAFE_NEIGHBORINGPOINT_DIST 400.0f +#define SAFE_AT_NAV_DIST_SQ 6400.0f // 80*80 +#define SAFE_GOTO_DIST_SQ 19600.0f // 140*140 - NUM_REGIONS = NUM_NODES/3, // Had to raise this up for bounty - NUM_CELLS = 32, // should be the square root of NUM_NODES - NUM_NODES_PER_CELL = 60, // had to raise this for t3_bounty - NUM_TARGETS = 5, // max number of outgoing edges from a given node +namespace NAV { +enum { + NUM_NODES = 1024, + // now 5 bytes each + NUM_EDGES = 3 * NUM_NODES, + NUM_EDGES_PER_NODE = 20, - CELL_RANGE = 1000, - VIEW_RANGE = 550, + NUM_REGIONS = NUM_NODES / 3, // Had to raise this up for bounty + NUM_CELLS = 32, // should be the square root of NUM_NODES + NUM_NODES_PER_CELL = 60, // had to raise this for t3_bounty + NUM_TARGETS = 5, // max number of outgoing edges from a given node - BIAS_NONWAYPOINT = 500, - BIAS_DANGER = 8000, - BIAS_TOOSMALL = 10000, + CELL_RANGE = 1000, + VIEW_RANGE = 550, - NULL_PATH_USER_INDEX= -1, - MAX_PATH_USERS = 100, - MAX_PATH_SIZE = NUM_NODES/7, + BIAS_NONWAYPOINT = 500, + BIAS_DANGER = 8000, + BIAS_TOOSMALL = 10000, - Z_CULL_OFFSET = 60, + NULL_PATH_USER_INDEX = -1, + MAX_PATH_USERS = 100, + MAX_PATH_SIZE = NUM_NODES / 7, - MAX_NODES_PER_NAME = 30, - MAX_EDGE_SEG_LEN = 100, - MAX_EDGE_FLOOR_DIST = 60, - MAX_EDGE_AUTO_LEN = 500, + Z_CULL_OFFSET = 60, - MAX_EDGES_PER_ENT = 10, - MAX_BLOCKING_ENTS = 100, - MAX_ALERTS_PER_AGENT= 10, - MAX_ALERT_TIME = 10000, + MAX_NODES_PER_NAME = 30, + MAX_EDGE_SEG_LEN = 100, + MAX_EDGE_FLOOR_DIST = 60, + MAX_EDGE_AUTO_LEN = 500, - MIN_WAY_NEIGHBORS = 4, - MAX_NONWP_NEIGHBORS = 1, + MAX_EDGES_PER_ENT = 10, + MAX_BLOCKING_ENTS = 100, + MAX_ALERTS_PER_AGENT = 10, + MAX_ALERT_TIME = 10000, + MIN_WAY_NEIGHBORS = 4, + MAX_NONWP_NEIGHBORS = 1, - // Human Sized - //------------- - SC_MEDIUM_RADIUS = 20, - SC_MEDIUM_HEIGHT = 60, - - // Rancor Sized - //-------------- - SC_LARGE_RADIUS = 60, - SC_LARGE_HEIGHT = 120, + // Human Sized + //------------- + SC_MEDIUM_RADIUS = 20, + SC_MEDIUM_HEIGHT = 60, + // Rancor Sized + //-------------- + SC_LARGE_RADIUS = 60, + SC_LARGE_HEIGHT = 120, - SAVE_LOAD = 0, + SAVE_LOAD = 0, - CHECK_JUMP = 0, - CHECK_START_OPEN = 1, - CHECK_START_SOLID = 1, - }; + CHECK_JUMP = 0, + CHECK_START_OPEN = 1, + CHECK_START_SOLID = 1, +}; } -namespace STEER -{ - enum - { - NULL_STEER_USER_INDEX= -1, - MAX_NEIGHBORS = 20, - Z_CULL_OFFSET = 60, - SIDE_LOCKED_TIMER = 2000, - NEIGHBOR_RANGE = 60, - }; +namespace STEER { +enum { + NULL_STEER_USER_INDEX = -1, + MAX_NEIGHBORS = 20, + Z_CULL_OFFSET = 60, + SIDE_LOCKED_TIMER = 2000, + NEIGHBOR_RANGE = 60, +}; } - - //////////////////////////////////////////////////////////////////////////////////////// // Total Memory - 11 Bytes (can save 5 bytes by removing Name and Targets) //////////////////////////////////////////////////////////////////////////////////////// -class CWayNode -{ -public: - CVec3 mPoint; - float mRadius; - NAV::EPointType mType; - hstring mName; // TODO OPTIMIZATION: Remove This? - hstring mTargets[NAV::NUM_TARGETS]; // TODO OPTIMIZATION: Remove This - enum EWayNodeFlags - { - WN_NONE = 0, - WN_ISLAND, - WN_FLOATING, - WN_DROPTOFLOOR, - WN_NOAUTOCONNECT, - WN_MAX - }; - ratl::bits_vs mFlags; +class CWayNode { + public: + CVec3 mPoint; + float mRadius; + NAV::EPointType mType; + hstring mName; // TODO OPTIMIZATION: Remove This? + hstring mTargets[NAV::NUM_TARGETS]; // TODO OPTIMIZATION: Remove This + enum EWayNodeFlags { WN_NONE = 0, WN_ISLAND, WN_FLOATING, WN_DROPTOFLOOR, WN_NOAUTOCONNECT, WN_MAX }; + ratl::bits_vs mFlags; //////////////////////////////////////////////////////////////////////////////////// // Access Operator (For Cells)(For Triangulation) //////////////////////////////////////////////////////////////////////////////////// - float operator[](int dimension) - { - return mPoint[dimension]; - } + float operator[](int dimension) { return mPoint[dimension]; } //////////////////////////////////////////////////////////////////////////////////// // Left Right Test (For Triangulation) //////////////////////////////////////////////////////////////////////////////////// - virtual ESide LRTest(const CWayNode& A, const CWayNode& B) const - { - return (mPoint.LRTest(A.mPoint, B.mPoint)); - } + virtual ESide LRTest(const CWayNode &A, const CWayNode &B) const { return (mPoint.LRTest(A.mPoint, B.mPoint)); } //////////////////////////////////////////////////////////////////////////////////// // Point In Circle (For Triangulation) //////////////////////////////////////////////////////////////////////////////////// - virtual bool InCircle(const CWayNode& A, const CWayNode& B, const CWayNode& C) const - { - return (mPoint.PtInCircle(A.mPoint, B.mPoint, C.mPoint)); - } + virtual bool InCircle(const CWayNode &A, const CWayNode &B, const CWayNode &C) const { return (mPoint.PtInCircle(A.mPoint, B.mPoint, C.mPoint)); } }; -const CWayNode& GetNode(int Handle); +const CWayNode &GetNode(int Handle); //////////////////////////////////////////////////////////////////////////////////////// // Total Memory - 5 bytes //////////////////////////////////////////////////////////////////////////////////////// -class CWayEdge -{ -public: - int mNodeA; // DO NOT REMOVE THIS: Handles are full ints because upper bits are used - int mNodeB; // DO NOT REMOVE THIS: Handles are full ints because upper bits are used - float mDistance; // DO NOT REMOVE THIS: It's a serious runtime optimization for A* +class CWayEdge { + public: + int mNodeA; // DO NOT REMOVE THIS: Handles are full ints because upper bits are used + int mNodeB; // DO NOT REMOVE THIS: Handles are full ints because upper bits are used + float mDistance; // DO NOT REMOVE THIS: It's a serious runtime optimization for A* - unsigned short mOwnerNum; // Converted to short. Largest entity number is 1024 - unsigned short mEntityNum; // Converted to short. Largest entity number is 1024 - enum EWayEdgeFlags - { + unsigned short mOwnerNum; // Converted to short. Largest entity number is 1024 + unsigned short mEntityNum; // Converted to short. Largest entity number is 1024 + enum EWayEdgeFlags { WE_NONE = 0, WE_SIZE_MEDIUM, @@ -250,125 +225,94 @@ class CWayEdge WE_MAX }; - ratl::bits_vs mFlags; // Should be only one int - + ratl::bits_vs mFlags; // Should be only one int //////////////////////////////////////////////////////////////////////////////////// // Size Function //////////////////////////////////////////////////////////////////////////////////// - inline int Blocking() - { - if (mFlags.get_bit(WE_BLOCKING_BREAK)) - { + inline int Blocking() { + if (mFlags.get_bit(WE_BLOCKING_BREAK)) { return WE_BLOCKING_BREAK; } - if (mFlags.get_bit(WE_BLOCKING_WALL)) - { + if (mFlags.get_bit(WE_BLOCKING_WALL)) { return WE_BLOCKING_WALL; } - if (mFlags.get_bit(WE_BLOCKING_DOOR)) - { + if (mFlags.get_bit(WE_BLOCKING_DOOR)) { return WE_BLOCKING_DOOR; } return 0; } - inline bool BlockingBreakable() {return (mFlags.get_bit(WE_BLOCKING_BREAK));} - inline bool BlockingWall() {return (mFlags.get_bit(WE_BLOCKING_WALL));} - inline bool BlockingDoor() {return (mFlags.get_bit(WE_BLOCKING_DOOR));} - + inline bool BlockingBreakable() { return (mFlags.get_bit(WE_BLOCKING_BREAK)); } + inline bool BlockingWall() { return (mFlags.get_bit(WE_BLOCKING_WALL)); } + inline bool BlockingDoor() { return (mFlags.get_bit(WE_BLOCKING_DOOR)); } //////////////////////////////////////////////////////////////////////////////////// // Size Function //////////////////////////////////////////////////////////////////////////////////// - inline int Size() const - { - return (mFlags.get_bit(WE_SIZE_MEDIUM)?(WE_SIZE_MEDIUM):(WE_SIZE_LARGE)); - } + inline int Size() const { return (mFlags.get_bit(WE_SIZE_MEDIUM) ? (WE_SIZE_MEDIUM) : (WE_SIZE_LARGE)); } //////////////////////////////////////////////////////////////////////////////////// // Access Operator (For Cells)(For Triangulation) //////////////////////////////////////////////////////////////////////////////////// - float operator[](int dimension) const - { - CVec3 Half(GetNode(mNodeA).mPoint + GetNode(mNodeB).mPoint); + float operator[](int dimension) const { + CVec3 Half(GetNode(mNodeA).mPoint + GetNode(mNodeB).mPoint); return (Half[dimension] * 0.5f); } //////////////////////////////////////////////////////////////////////////////////// // Point - returns the center of the edge //////////////////////////////////////////////////////////////////////////////////// - void Point(CVec3& Half) const - { + void Point(CVec3 &Half) const { Half = GetNode(mNodeA).mPoint; Half += GetNode(mNodeB).mPoint; Half *= 0.5f; - } //////////////////////////////////////////////////////////////////////////////////// // GetPoint A //////////////////////////////////////////////////////////////////////////////////// - const CVec3& PointA() const - { - return GetNode(mNodeA).mPoint; - } + const CVec3 &PointA() const { return GetNode(mNodeA).mPoint; } //////////////////////////////////////////////////////////////////////////////////// // GetPoint B //////////////////////////////////////////////////////////////////////////////////// - const CVec3& PointB() const - { - return GetNode(mNodeB).mPoint; - } - + const CVec3 &PointB() const { return GetNode(mNodeB).mPoint; } }; -const CWayEdge& GetEdge(int Handle); - +const CWayEdge &GetEdge(int Handle); -struct SNodeSort -{ - NAV::TNodeHandle mHandle; - float mDistance; - bool mInRadius; +struct SNodeSort { + NAV::TNodeHandle mHandle; + float mDistance; + bool mInRadius; - - bool operator < (const SNodeSort& other) const - { - return (mDistance TGraph; -typedef ragl::graph_region TGraphRegion; -typedef TGraph::cells TGraphCells; -typedef ratl::vector_vs TNearestNavSort; +typedef ragl::graph_vs TGraph; +typedef ragl::graph_region TGraphRegion; +typedef TGraph::cells TGraphCells; +typedef ratl::vector_vs TNearestNavSort; -typedef ratl::array_vs TAlertList; -typedef ratl::array_vs TEntityAlertList; -typedef ratl::vector_vs TNamedNodeList; -typedef ratl::map_vs TNameToNodeMap; - -typedef ratl::vector_vs TEdgesPerEnt; -typedef ratl::map_vs TEntEdgeMap; +typedef ratl::array_vs TAlertList; +typedef ratl::array_vs TEntityAlertList; +typedef ratl::vector_vs TNamedNodeList; +typedef ratl::map_vs TNameToNodeMap; +typedef ratl::vector_vs TEdgesPerEnt; +typedef ratl::map_vs TEntEdgeMap; //////////////////////////////////////////////////////////////////////////////////////// // Path Point @@ -376,101 +320,90 @@ typedef ratl::map_vs T // This is actual vector and speed location (as well as node handle of that the agent // has planned to go to. //////////////////////////////////////////////////////////////////////////////////////// -struct SPathPoint -{ - CVec3 mPoint; - float mSpeed; - float mSlowingRadius; - float mReachedRadius; - float mDist; - float mETA; - NAV::TNodeHandle mNode; +struct SPathPoint { + CVec3 mPoint; + float mSpeed; + float mSlowingRadius; + float mReachedRadius; + float mDist; + float mETA; + NAV::TNodeHandle mNode; }; -typedef ratl::vector_vs TPath; - +typedef ratl::vector_vs TPath; //////////////////////////////////////////////////////////////////////////////////////// // Path User // // This is the cached path for a given actor //////////////////////////////////////////////////////////////////////////////////////// -struct SPathUser -{ - int mEnd; - bool mSuccess; - int mLastUseTime; - int mLastAStarTime; - TPath mPath; +struct SPathUser { + int mEnd; + bool mSuccess; + int mLastUseTime; + int mLastAStarTime; + TPath mPath; }; -typedef ratl::pool_vs TPathUsers; -typedef ratl::array_vs TPathUserIndex; +typedef ratl::pool_vs TPathUsers; +typedef ratl::array_vs TPathUserIndex; - -typedef ratl::vector_vs TNeighbors; +typedef ratl::vector_vs TNeighbors; //////////////////////////////////////////////////////////////////////////////////////// // Steer User // // This is the cached steering data for a given actor //////////////////////////////////////////////////////////////////////////////////////// -struct SSteerUser -{ +struct SSteerUser { // Constant Values In Entity //--------------------------- - float mMaxForce; - float mMaxSpeed; - float mRadius; - float mMass; - + float mMaxForce; + float mMaxSpeed; + float mRadius; + float mMass; // Current Values //---------------- - TNeighbors mNeighbors; + TNeighbors mNeighbors; - CVec3 mOrientation; - CVec3 mPosition; - - CVec3 mVelocity; - float mSpeed; + CVec3 mOrientation; + CVec3 mPosition; + CVec3 mVelocity; + float mSpeed; // Values Projected From Current Values //-------------------------------------- - CVec3 mProjectFwd; - CVec3 mProjectSide; - CVec3 mProjectPath; - + CVec3 mProjectFwd; + CVec3 mProjectSide; + CVec3 mProjectPath; // Temporary Values //------------------ - CVec3 mDesiredVelocity; - float mDesiredSpeed; - float mDistance; - CVec3 mSeekLocation; + CVec3 mDesiredVelocity; + float mDesiredSpeed; + float mDistance; + CVec3 mSeekLocation; - int mIgnoreEntity; + int mIgnoreEntity; - bool mBlocked; - int mBlockedTgtEntity; - CVec3 mBlockedTgtPosition; + bool mBlocked; + int mBlockedTgtEntity; + CVec3 mBlockedTgtPosition; // Steering //---------- - CVec3 mSteering; - float mNewtons; + CVec3 mSteering; + float mNewtons; }; -typedef ratl::pool_vs TSteerUsers; -typedef ratl::array_vs TSteerUserIndex; -typedef ratl::bits_vs TEntBits; - - -TAlertList& GetAlerts(gentity_t* actor); -TGraph& GetGraph(); -int GetAirRegion(); -int GetIslandRegion(); - +typedef ratl::pool_vs TSteerUsers; +typedef ratl::array_vs TSteerUserIndex; +typedef ratl::bits_vs TEntBits; +TAlertList &GetAlerts(gentity_t *actor); +TGraph &GetGraph(); +int GetAirRegion(); +int GetIslandRegion(); //////////////////////////////////////////////////////////////////////////////////////// // The Graph User @@ -480,85 +413,63 @@ int GetIslandRegion(); // cross the nodes at any given time. // //////////////////////////////////////////////////////////////////////////////////////// -class CGraphUser : public TGraph::user -{ -private: - gentity_t* mActor; - int mActorSize; - - CVec3 mDangerSpot; - float mDangerSpotRadiusSq; +class CGraphUser : public TGraph::user { + private: + gentity_t *mActor; + int mActorSize; + CVec3 mDangerSpot; + float mDangerSpotRadiusSq; -public: + public: //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - void SetActor(gentity_t* actor) - { - mActor = actor; - mActorSize = NAV::ClassifyEntSize(actor); - mDangerSpotRadiusSq = 0; + void SetActor(gentity_t *actor) { + mActor = actor; + mActorSize = NAV::ClassifyEntSize(actor); + mDangerSpotRadiusSq = 0; } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - void ClearActor() - { + void ClearActor() { mActor = 0; mActorSize = 0; mDangerSpotRadiusSq = 0; } - gentity_t* GetActor() - { - return mActor; - } + gentity_t *GetActor() { return mActor; } - void SetDangerSpot(const CVec3& Spot, float RadiusSq) - { + void SetDangerSpot(const CVec3 &Spot, float RadiusSq) { mDangerSpot = Spot; mDangerSpotRadiusSq = RadiusSq; } - void ClearDangerSpot() - { - mDangerSpotRadiusSq = 0; - } - - - + void ClearDangerSpot() { mDangerSpotRadiusSq = 0; } -public: + public: //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - virtual bool can_be_invalid(const CWayEdge& Edge) const - { - return (Edge.mFlags.get_bit(CWayEdge::WE_CANBEINVAL)); - } - + virtual bool can_be_invalid(const CWayEdge &Edge) const { return (Edge.mFlags.get_bit(CWayEdge::WE_CANBEINVAL)); } //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - virtual bool is_valid(CWayEdge& Edge, int EndPoint=0) const - { + virtual bool is_valid(CWayEdge &Edge, int EndPoint = 0) const { // If The Actor Can't Fly, But This Is A Flying Edge, It's Invalid //----------------------------------------------------------------- - if (mActor && Edge.mFlags.get_bit(CWayEdge::WE_FLYING) && mActor->NPC && !(mActor->NPC->scriptFlags&SCF_NAV_CAN_FLY)) - { + if (mActor && Edge.mFlags.get_bit(CWayEdge::WE_FLYING) && mActor->NPC && !(mActor->NPC->scriptFlags & SCF_NAV_CAN_FLY)) { return false; } // If The Actor Can't Fly, But This Is A Flying Edge, It's Invalid //----------------------------------------------------------------- - if (mActor && Edge.mFlags.get_bit(CWayEdge::WE_JUMPING) && mActor->NPC && !(mActor->NPC->scriptFlags&SCF_NAV_CAN_JUMP)) - { + if (mActor && Edge.mFlags.get_bit(CWayEdge::WE_JUMPING) && mActor->NPC && !(mActor->NPC->scriptFlags & SCF_NAV_CAN_JUMP)) { return false; } - // If The Actor Is Too Big, This Is Not A Valid Edge For Him //----------------------------------------------------------- if (mActor && Edge.Size()NPC) && - (mActor->NPC->aiFlags&NPCAI_NAV_THROUGH_BREAKABLES) && - (Edge.BlockingBreakable()) && - (G_EntIsBreakable(Edge.mEntityNum, mActor)) - ) - { + if ((mActor) && (mActor->NPC) && (mActor->NPC->aiFlags & NPCAI_NAV_THROUGH_BREAKABLES) && (Edge.BlockingBreakable()) && + (G_EntIsBreakable(Edge.mEntityNum, mActor))) { return true; } // Is This A Door? //----------------- - if (Edge.BlockingDoor()) - { - bool StartOpen = (ent->spawnflags & 1); - bool Closed = (StartOpen)?(ent->moverState==MOVER_POS2):(ent->moverState==MOVER_POS1); + if (Edge.BlockingDoor()) { + bool StartOpen = (ent->spawnflags & 1); + bool Closed = (StartOpen) ? (ent->moverState == MOVER_POS2) : (ent->moverState == MOVER_POS1); // If It Is Closed, We Want To Check If It Will Auto Open For Us //--------------------------------------------------------------- - if (Closed) - { - gentity_t* owner = &g_entities[Edge.mOwnerNum]; - if (owner) - { + if (Closed) { + gentity_t *owner = &g_entities[Edge.mOwnerNum]; + if (owner) { // Check To See If The Owner Is Inactive Or Locked, Or Unavailable To The NPC //---------------------------------------------------------------------------- if ((owner->svFlags & SVF_INACTIVE) || - (owner==ent && (owner->spawnflags & (MOVER_PLAYER_USE|MOVER_FORCE_ACTIVATE|MOVER_LOCKED))) || - (owner!=ent && (owner->spawnflags & (1 /*PLAYERONLY*/|4 /*USE_BOTTON*/)))) - { + (owner == ent && (owner->spawnflags & (MOVER_PLAYER_USE | MOVER_FORCE_ACTIVATE | MOVER_LOCKED))) || + (owner != ent && (owner->spawnflags & (1 /*PLAYERONLY*/ | 4 /*USE_BOTTON*/)))) { return false; } - // Look For A Key //---------------- - if (mActor!=0 && (owner->spawnflags & MOVER_GOODIE)) - { + if (mActor != 0 && (owner->spawnflags & MOVER_GOODIE)) { int key = INV_GoodieKeyCheck(mActor); - if (!key) - { + if (!key) { return false; } } @@ -623,8 +520,7 @@ class CGraphUser : public TGraph::user // No Owner? This Must Be A Scripted Door Or Other Contraption //-------------------------------------------------------------- - else - { + else { return false; } } @@ -633,19 +529,15 @@ class CGraphUser : public TGraph::user // If This Is A Wall, Check If It Has Contents Now //------------------------------------------------- - else if (Edge.BlockingWall()) - { - return !(ent->contents&CONTENTS_SOLID); + else if (Edge.BlockingWall()) { + return !(ent->contents & CONTENTS_SOLID); } } - } - else if ( Edge.BlockingBreakable()) - {//we had a breakable in our way, now it's gone, see if there is anything else in the way - if ( NAV::TestEdge( Edge.mNodeA, Edge.mNodeB, qfalse ) ) - {//clear it + } else if (Edge.BlockingBreakable()) { // we had a breakable in our way, now it's gone, see if there is anything else in the way + if (NAV::TestEdge(Edge.mNodeA, Edge.mNodeB, qfalse)) { // clear it Edge.mFlags.clear_bit(CWayEdge::WE_BLOCKING_BREAK); } - //NOTE: if this fails with the SC_LARGE size + // NOTE: if this fails with the SC_LARGE size } return (Edge.mFlags.get_bit(CWayEdge::WE_VALID)); @@ -654,46 +546,35 @@ class CGraphUser : public TGraph::user //////////////////////////////////////////////////////////////////////////////////// // This is the cost estimate from any node to any other node (usually the goal) //////////////////////////////////////////////////////////////////////////////////// - virtual float cost(const CWayNode& A, const CWayNode& B) const - { - return (A.mPoint.Dist(B.mPoint)); - } + virtual float cost(const CWayNode &A, const CWayNode &B) const { return (A.mPoint.Dist(B.mPoint)); } //////////////////////////////////////////////////////////////////////////////////// // This is the cost estimate for traversing a particular edge //////////////////////////////////////////////////////////////////////////////////// - virtual float cost(const CWayEdge& Edge, const CWayNode& B) const - { - float DangerBias = 0.0f; - if (mActor) - { - int eHandle = GetGraph().edge_index(Edge); - TAlertList& al = GetAlerts(mActor); - for (int alIndex=0; alIndex0.0f) - { - DangerBias += (al[alIndex].mDanger*NAV::BIAS_DANGER); + virtual float cost(const CWayEdge &Edge, const CWayNode &B) const { + float DangerBias = 0.0f; + if (mActor) { + int eHandle = GetGraph().edge_index(Edge); + TAlertList &al = GetAlerts(mActor); + for (int alIndex = 0; alIndex < TAlertList::CAPACITY; alIndex++) { + if (al[alIndex].mHandle == eHandle && al[alIndex].mDanger > 0.0f) { + DangerBias += (al[alIndex].mDanger * NAV::BIAS_DANGER); } } // If The Actor Is Too Big, Bias This Edge For Him //------------------------------------------------- - if (Edge.Size() mDangerSpot.DistToLine2(Edge.PointA(), Edge.PointB())) - { + if (mDangerSpotRadiusSq > mDangerSpot.DistToLine2(Edge.PointA(), Edge.PointB())) { DangerBias += NAV::BIAS_DANGER; } - - if (B.mType==NAV::PT_WAYNODE) - { - return (Edge.mDistance + DangerBias); + if (B.mType == NAV::PT_WAYNODE) { + return (Edge.mDistance + DangerBias); } return ((Edge.mDistance + DangerBias) + NAV::BIAS_NONWAYPOINT); } @@ -701,11 +582,7 @@ class CGraphUser : public TGraph::user //////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////// - virtual bool on_same_floor(const CWayNode& A, const CWayNode& B) const - { - return (fabsf(A.mPoint[2] - B.mPoint[2])<100.0f); - } - + virtual bool on_same_floor(const CWayNode &A, const CWayNode &B) const { return (fabsf(A.mPoint[2] - B.mPoint[2]) < 100.0f); } //////////////////////////////////////////////////////////////////////////////////// // setup the edge (For Triangulation) @@ -713,126 +590,97 @@ class CGraphUser : public TGraph::user // This function is here because it evaluates the base cost from NodeA to NodeB, which // //////////////////////////////////////////////////////////////////////////////////// - virtual void setup_edge(CWayEdge& Edge, int A, int B, bool OnHull, const CWayNode& NodeA, const CWayNode& NodeB, bool CanBeInvalid=false) - { - Edge.mNodeA = A; - Edge.mNodeB = B; - Edge.mDistance = NodeA.mPoint.Dist(NodeB.mPoint); - Edge.mEntityNum = ENTITYNUM_NONE; - Edge.mOwnerNum = ENTITYNUM_NONE; + virtual void setup_edge(CWayEdge &Edge, int A, int B, bool OnHull, const CWayNode &NodeA, const CWayNode &NodeB, bool CanBeInvalid = false) { + Edge.mNodeA = A; + Edge.mNodeB = B; + Edge.mDistance = NodeA.mPoint.Dist(NodeB.mPoint); + Edge.mEntityNum = ENTITYNUM_NONE; + Edge.mOwnerNum = ENTITYNUM_NONE; Edge.mFlags.clear(); Edge.mFlags.set_bit(CWayEdge::WE_VALID); - if (CanBeInvalid) - { + if (CanBeInvalid) { Edge.mFlags.set_bit(CWayEdge::WE_CANBEINVAL); } - if (OnHull) - { + if (OnHull) { Edge.mFlags.set_bit(CWayEdge::WE_ONHULL); } } }; - - //////////////////////////////////////////////////////////////////////////////////////// // The Global Public Objects //////////////////////////////////////////////////////////////////////////////////////// -TGraph mGraph; -TGraphRegion mRegion(mGraph); -TGraphCells mCells(mGraph); - -TGraph::search mSearch; -CGraphUser mUser; - - -TNameToNodeMap mNodeNames; -TEntEdgeMap mEntEdgeMap; +TGraph mGraph; +TGraphRegion mRegion(mGraph); +TGraphCells mCells(mGraph); -TNearestNavSort mNearestNavSort; +TGraph::search mSearch; +CGraphUser mUser; -TPathUsers mPathUsers; -TPathUserIndex mPathUserIndex; -SPathUser mPathUserMaster; +TNameToNodeMap mNodeNames; +TEntEdgeMap mEntEdgeMap; -TSteerUsers mSteerUsers; -TSteerUserIndex mSteerUserIndex; +TNearestNavSort mNearestNavSort; -TEntityAlertList mEntityAlertList; +TPathUsers mPathUsers; +TPathUserIndex mPathUserIndex; +SPathUser mPathUserMaster; -vec3_t mZeroVec; -trace_t mMoveTrace; -trace_t mViewTrace; +TSteerUsers mSteerUsers; +TSteerUserIndex mSteerUserIndex; -int mMoveTraceCount = 0; -int mViewTraceCount = 0; -int mConnectTraceCount = 0; -int mConnectTime = 0; -int mIslandCount = 0; -int mIslandRegion = 0; -int mAirRegion = 0; -char mLocStringA[256] = {0}; -char mLocStringB[256] = {0}; +TEntityAlertList mEntityAlertList; +vec3_t mZeroVec; +trace_t mMoveTrace; +trace_t mViewTrace; +int mMoveTraceCount = 0; +int mViewTraceCount = 0; +int mConnectTraceCount = 0; +int mConnectTime = 0; +int mIslandCount = 0; +int mIslandRegion = 0; +int mAirRegion = 0; +char mLocStringA[256] = {0}; +char mLocStringB[256] = {0}; //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -TAlertList& GetAlerts(gentity_t* actor) -{ - return mEntityAlertList[actor->s.number]; -} +TAlertList &GetAlerts(gentity_t *actor) { return mEntityAlertList[actor->s.number]; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -TGraph& GetGraph() -{ - return mGraph; -} +TGraph &GetGraph() { return mGraph; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const CWayNode& GetNode(int Handle) -{ - return mGraph.get_node(Handle); -} +const CWayNode &GetNode(int Handle) { return mGraph.get_node(Handle); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const CWayEdge& GetEdge(int Handle) -{ - return mGraph.get_edge(Handle); -} +const CWayEdge &GetEdge(int Handle) { return mGraph.get_edge(Handle); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -int GetAirRegion() -{ - return mAirRegion; -} -int GetIslandRegion() -{ - return mIslandRegion; -} - +int GetAirRegion() { return mAirRegion; } +int GetIslandRegion() { return mIslandRegion; } //////////////////////////////////////////////////////////////////////////////////////// // Helper Function : View Trace //////////////////////////////////////////////////////////////////////////////////////// -bool ViewTrace(const CVec3& a, const CVec3& b) -{ - int contents = (CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_MONSTERCLIP); +bool ViewTrace(const CVec3 &a, const CVec3 &b) { + int contents = (CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_MONSTERCLIP); mViewTraceCount++; gi.trace(&mViewTrace, a.v, 0, 0, b.v, ENTITYNUM_NONE, contents, (EG2_Collision)0, 0); - if ((mViewTrace.allsolid==qfalse) && (mViewTrace.startsolid==qfalse ) && (mViewTrace.fraction==1.0f)) - { + if ((mViewTrace.allsolid == qfalse) && (mViewTrace.startsolid == qfalse) && (mViewTrace.fraction == 1.0f)) { return true; } return false; @@ -841,15 +689,13 @@ bool ViewTrace(const CVec3& a, const CVec3& b) //////////////////////////////////////////////////////////////////////////////////////// // Helper Function : View Trace //////////////////////////////////////////////////////////////////////////////////////// -bool ViewNavTrace(const CVec3& a, const CVec3& b) -{ - int contents = (CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP); +bool ViewNavTrace(const CVec3 &a, const CVec3 &b) { + int contents = (CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); mViewTraceCount++; gi.trace(&mViewTrace, a.v, 0, 0, b.v, ENTITYNUM_NONE, contents, (EG2_Collision)0, 0); - if ((mViewTrace.allsolid==qfalse) && (mViewTrace.startsolid==qfalse ) && (mViewTrace.fraction==1.0f)) - { + if ((mViewTrace.allsolid == qfalse) && (mViewTrace.startsolid == qfalse) && (mViewTrace.fraction == 1.0f)) { return true; } return false; @@ -858,45 +704,33 @@ bool ViewNavTrace(const CVec3& a, const CVec3& b) //////////////////////////////////////////////////////////////////////////////////////// // Helper Function : Move Trace //////////////////////////////////////////////////////////////////////////////////////// -bool MoveTrace(const CVec3& Start, const CVec3& Stop, const CVec3& Mins, const CVec3& Maxs, - int IgnoreEnt=0, - bool CheckForDoNotEnter=false, - bool RetryIfStartInDoNotEnter=true, - bool IgnoreAllEnts=false, - int OverrideContents=0) -{ - int contents = (MASK_NPCSOLID); - if (OverrideContents) - { - contents = OverrideContents; +bool MoveTrace(const CVec3 &Start, const CVec3 &Stop, const CVec3 &Mins, const CVec3 &Maxs, int IgnoreEnt = 0, bool CheckForDoNotEnter = false, + bool RetryIfStartInDoNotEnter = true, bool IgnoreAllEnts = false, int OverrideContents = 0) { + int contents = (MASK_NPCSOLID); + if (OverrideContents) { + contents = OverrideContents; } - if (CheckForDoNotEnter) - { + if (CheckForDoNotEnter) { contents |= CONTENTS_BOTCLIP; } - if (IgnoreAllEnts) - { + if (IgnoreAllEnts) { contents &= ~CONTENTS_BODY; } - // Run The Trace //--------------- mMoveTraceCount++; gi.trace(&mMoveTrace, Start.v, Mins.v, Maxs.v, Stop.v, IgnoreEnt, contents, (EG2_Collision)0, 0); - // Did It Make It? //----------------- - if ((mMoveTrace.allsolid==qfalse) && (mMoveTrace.startsolid==qfalse ) && (mMoveTrace.fraction==1.0f)) - { + if ((mMoveTrace.allsolid == qfalse) && (mMoveTrace.startsolid == qfalse) && (mMoveTrace.fraction == 1.0f)) { return true; } // If We Started In Solid, Try Removing The "Do Not Enter" Contents Type, And Trace Again //---------------------------------------------------------------------------------------- - if (CheckForDoNotEnter && RetryIfStartInDoNotEnter && ((mMoveTrace.allsolid==qtrue) || (mMoveTrace.startsolid==qtrue))) - { + if (CheckForDoNotEnter && RetryIfStartInDoNotEnter && ((mMoveTrace.allsolid == qtrue) || (mMoveTrace.startsolid == qtrue))) { contents &= ~CONTENTS_BOTCLIP; // Run The Trace @@ -906,8 +740,7 @@ bool MoveTrace(const CVec3& Start, const CVec3& Stop, const CVec3& Mins, const // Did It Make It? //----------------- - if ((mMoveTrace.allsolid==qfalse) && (mMoveTrace.startsolid==qfalse ) && (mMoveTrace.fraction==1.0f)) - { + if ((mMoveTrace.allsolid == qfalse) && (mMoveTrace.startsolid == qfalse) && (mMoveTrace.fraction == 1.0f)) { return true; } } @@ -917,69 +750,56 @@ bool MoveTrace(const CVec3& Start, const CVec3& Stop, const CVec3& Mins, const //////////////////////////////////////////////////////////////////////////////////////// // Helper Function : Move Trace (with actor) //////////////////////////////////////////////////////////////////////////////////////// -bool MoveTrace(gentity_t* actor, const CVec3& goalPosition, bool IgnoreAllEnts=false) -{ - assert(actor!=0); - CVec3 Mins(actor->mins); - CVec3 Maxs(actor->maxs); +bool MoveTrace(gentity_t *actor, const CVec3 &goalPosition, bool IgnoreAllEnts = false) { + assert(actor != 0); + CVec3 Mins(actor->mins); + CVec3 Maxs(actor->maxs); - Mins[2] += (STEPSIZE*1); + Mins[2] += (STEPSIZE * 1); - return MoveTrace(actor->currentOrigin, goalPosition, Mins, Maxs, actor->s.number, true, true, IgnoreAllEnts/*, actor->contents*/); + return MoveTrace(actor->currentOrigin, goalPosition, Mins, Maxs, actor->s.number, true, true, IgnoreAllEnts /*, actor->contents*/); } - - - //////////////////////////////////////////////////////////////////////////////////////// // GoTo // // This Function serves as a master control for finding, updating, and following a path //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::GoTo(gentity_t* actor, TNodeHandle target, float MaxDangerLevel) -{ - assert(actor!=0 && actor->client!=0); +bool NAV::GoTo(gentity_t *actor, TNodeHandle target, float MaxDangerLevel) { + assert(actor != 0 && actor->client != 0); // Check If We Already Have A Path //--------------------------------- - bool HasPath = NAV::HasPath(actor); + bool HasPath = NAV::HasPath(actor); // If So Update It //----------------- - if (HasPath) - { + if (HasPath) { HasPath = NAV::UpdatePath(actor, target, MaxDangerLevel); } // If No Path, Try To Find One //----------------------------- - if (!HasPath) - { + if (!HasPath) { HasPath = NAV::FindPath(actor, target, MaxDangerLevel); } // If We Have A Path, Now Try To Follow It //----------------------------------------- - if (HasPath) - { - HasPath = (STEER::Path(actor)!=0.0f); - if (HasPath) - { - if (STEER::AvoidCollisions(actor, actor->client->leader)) - { + if (HasPath) { + HasPath = (STEER::Path(actor) != 0.0f); + if (HasPath) { + if (STEER::AvoidCollisions(actor, actor->client->leader)) { STEER::Blocked(actor, NAV::NextPosition(actor)); } - } - else - { + } else { STEER::Blocked(actor, NAV::GetNodePosition(target)); } } // Nope, No Path At All... Bad //------------------------------ - else - { + else { STEER::Blocked(actor, NAV::GetNodePosition(target)); } @@ -989,29 +809,25 @@ bool NAV::GoTo(gentity_t* actor, TNodeHandle target, float MaxDangerLevel) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::GoTo(gentity_t* actor, gentity_t* target, float MaxDangerLevel) -{ - assert(actor!=0 && actor->client!=0); +bool NAV::GoTo(gentity_t *actor, gentity_t *target, float MaxDangerLevel) { + assert(actor != 0 && actor->client != 0); - bool HasPath = false; - TNodeHandle targetNode = GetNearestNode(target, true); + bool HasPath = false; + TNodeHandle targetNode = GetNearestNode(target, true); // If The Target Has No Nearest Nav Point, Go To His Last Valid Waypoint Instead //------------------------------------------------------------------------------- - if (targetNode==0) - { + if (targetNode == 0) { targetNode = target->lastWaypoint; } // Has He EVER Had A Valid Waypoint? //----------------------------------- - if (targetNode!=0) - { + if (targetNode != 0) { // If On An Edge, Pick The Safest Of The Two Points //-------------------------------------------------- - if (targetNode<0) - { - targetNode = (Q_irand(0,1)==0)?(mGraph.get_edge(abs(targetNode)).mNodeA):(mGraph.get_edge(abs(targetNode)).mNodeB); + if (targetNode < 0) { + targetNode = (Q_irand(0, 1) == 0) ? (mGraph.get_edge(abs(targetNode)).mNodeA) : (mGraph.get_edge(abs(targetNode)).mNodeB); } // Check If We Already Have A Path @@ -1020,52 +836,43 @@ bool NAV::GoTo(gentity_t* actor, gentity_t* target, float MaxDangerLevel) // If So Update It //----------------- - if (HasPath) - { + if (HasPath) { HasPath = NAV::UpdatePath(actor, targetNode, MaxDangerLevel); } // If No Path, Try To Find One //----------------------------- - if (!HasPath) - { + if (!HasPath) { HasPath = NAV::FindPath(actor, targetNode, MaxDangerLevel); } // If We Have A Path, Now Try To Follow It //----------------------------------------- - if (HasPath) - { - HasPath = (STEER::Path(actor)!=0.0f); - if (HasPath) - { + if (HasPath) { + HasPath = (STEER::Path(actor) != 0.0f); + if (HasPath) { // Attempt To Avoid Collisions Along The Path //-------------------------------------------- - if (STEER::AvoidCollisions(actor, actor->client->leader)) - { + if (STEER::AvoidCollisions(actor, actor->client->leader)) { // Have A Path, Currently Blocked By Something //--------------------------------------------- STEER::Blocked(actor, NAV::NextPosition(actor)); } - } - else - { + } else { STEER::Blocked(actor, target); } } // Nope, No Path At All... Bad //------------------------------ - else - { + else { STEER::Blocked(actor, target); } } // No Waypoint Near //------------------ - else - { + else { STEER::Blocked(actor, target); } @@ -1075,19 +882,16 @@ bool NAV::GoTo(gentity_t* actor, gentity_t* target, float MaxDangerLevel) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::GoTo(gentity_t* actor, const vec3_t& position, float MaxDangerLevel) -{ - assert(actor!=0 && actor->client!=0); +bool NAV::GoTo(gentity_t *actor, const vec3_t &position, float MaxDangerLevel) { + assert(actor != 0 && actor->client != 0); - bool HasPath = false; - TNodeHandle targetNode = GetNearestNode(position); - if (targetNode!=0) - { + bool HasPath = false; + TNodeHandle targetNode = GetNearestNode(position); + if (targetNode != 0) { // If On An Edge, Pick The Safest Of The Two Points //-------------------------------------------------- - if (targetNode<0) - { - targetNode = (Q_irand(0,1)==0)?(mGraph.get_edge(abs(targetNode)).mNodeA):(mGraph.get_edge(abs(targetNode)).mNodeB); + if (targetNode < 0) { + targetNode = (Q_irand(0, 1) == 0) ? (mGraph.get_edge(abs(targetNode)).mNodeA) : (mGraph.get_edge(abs(targetNode)).mNodeB); } // Check If We Already Have A Path @@ -1096,72 +900,58 @@ bool NAV::GoTo(gentity_t* actor, const vec3_t& position, float MaxDangerLevel) // If So Update It //----------------- - if (HasPath) - { + if (HasPath) { HasPath = NAV::UpdatePath(actor, targetNode, MaxDangerLevel); } // If No Path, Try To Find One //----------------------------- - if (!HasPath) - { + if (!HasPath) { HasPath = NAV::FindPath(actor, targetNode, MaxDangerLevel); } // If We Have A Path, Now Try To Follow It //----------------------------------------- - if (HasPath) - { - HasPath = (STEER::Path(actor)!=0.0f); - if (HasPath) - { + if (HasPath) { + HasPath = (STEER::Path(actor) != 0.0f); + if (HasPath) { // Attempt To Avoid Collisions Along The Path //-------------------------------------------- - if (STEER::AvoidCollisions(actor, actor->client->leader)) - { + if (STEER::AvoidCollisions(actor, actor->client->leader)) { // Have A Path, Currently Blocked By Something //--------------------------------------------- STEER::Blocked(actor, NAV::NextPosition(actor)); } - } - else - { + } else { STEER::Blocked(actor, NAV::NextPosition(actor)); } } // Nope, No Path At All... Bad //------------------------------ - else - { + else { STEER::Blocked(actor, position); } } // No Waypoint Near //------------------ - else - { + else { STEER::Blocked(actor, position); } return HasPath; } - //////////////////////////////////////////////////////////////////////////////////////// // This function exists as a wrapper so that the graph can write to the gi.Printf() //////////////////////////////////////////////////////////////////////////////////////// -void stupid_print(const char* data) -{ - gi.Printf(data); -} +void stupid_print(const char *data) { gi.Printf(data); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::LoadFromFile(const char *filename, int checksum) -{ +bool NAV::LoadFromFile(const char *filename, int checksum) { mZeroVec[0] = 0; mZeroVec[1] = 0; mZeroVec[2] = 0; @@ -1189,11 +979,9 @@ bool NAV::LoadFromFile(const char *filename, int checksum) mNodeNames.clear(); mNearestNavSort.clear(); - if (SAVE_LOAD) - { - hfile navFile(va("maps/%s.navNEW")); - if (!navFile.open_read(NAV_VERSION, checksum)) - { + if (SAVE_LOAD) { + hfile navFile(va("maps/%s.navNEW")); + if (!navFile.open_read(NAV_VERSION, checksum)) { return false; } navFile.load(&mGraph, sizeof(mGraph)); @@ -1208,136 +996,102 @@ bool NAV::LoadFromFile(const char *filename, int checksum) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge ) -{ - int atHandle = mGraph.get_edge_across( NodeA, NodeB ); - CWayEdge& at = mGraph.get_edge(atHandle); - CWayNode& a = mGraph.get_node(at.mNodeA); - CWayNode& b = mGraph.get_node(at.mNodeB); - CVec3 Mins(-15.0f, -15.0f, 0.0f); // These were the old "sizeless" defaults - CVec3 Maxs(15.0f, 15.0f, 40.0f); - bool CanGo = false; - bool HitCharacter = false; - int EntHit = ENTITYNUM_NONE; - int i = (int)(at.Size()); +bool NAV::TestEdge(TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge) { + int atHandle = mGraph.get_edge_across(NodeA, NodeB); + CWayEdge &at = mGraph.get_edge(atHandle); + CWayNode &a = mGraph.get_node(at.mNodeA); + CWayNode &b = mGraph.get_node(at.mNodeB); + CVec3 Mins(-15.0f, -15.0f, 0.0f); // These were the old "sizeless" defaults + CVec3 Maxs(15.0f, 15.0f, 40.0f); + bool CanGo = false; + bool HitCharacter = false; + int EntHit = ENTITYNUM_NONE; + int i = (int)(at.Size()); a.mPoint.ToStr(mLocStringA); b.mPoint.ToStr(mLocStringB); - const char* aName = (a.mName.empty())?(mLocStringA):(a.mName.c_str()); - const char* bName = (b.mName.empty())?(mLocStringB):(b.mName.c_str()); + const char *aName = (a.mName.empty()) ? (mLocStringA) : (a.mName.c_str()); + const char *bName = (b.mName.empty()) ? (mLocStringB) : (b.mName.c_str()); - float radius = (at.Size()==CWayEdge::WE_SIZE_LARGE)?(SC_LARGE_RADIUS):(SC_MEDIUM_RADIUS); - float height = (at.Size()==CWayEdge::WE_SIZE_LARGE)?(SC_LARGE_HEIGHT):(SC_MEDIUM_HEIGHT); + float radius = (at.Size() == CWayEdge::WE_SIZE_LARGE) ? (SC_LARGE_RADIUS) : (SC_MEDIUM_RADIUS); + float height = (at.Size() == CWayEdge::WE_SIZE_LARGE) ? (SC_LARGE_HEIGHT) : (SC_MEDIUM_HEIGHT); Mins[0] = Mins[1] = (radius) * -1.0f; Maxs[0] = Maxs[1] = (radius); - Maxs[2] = (height); - + Maxs[2] = (height); // If Either Start Or End Points Are Too Small, Don' Bother At This Size //----------------------------------------------------------------------- - if ((a.mType==PT_WAYNODE && a.mRadius(%s): Size Too Big\n", aName, bName, i); } CanGo = false; return CanGo; } - // Try It //-------- - CanGo = MoveTrace(a.mPoint, b.mPoint, Mins, Maxs, 0, true, false); - EntHit = mMoveTrace.entityNum; + CanGo = MoveTrace(a.mPoint, b.mPoint, Mins, Maxs, 0, true, false); + EntHit = mMoveTrace.entityNum; // Check For A Flying Edge //------------------------- - if (a.mFlags.get_bit(CWayNode::WN_FLOATING) || b.mFlags.get_bit(CWayNode::WN_FLOATING)) - { + if (a.mFlags.get_bit(CWayNode::WN_FLOATING) || b.mFlags.get_bit(CWayNode::WN_FLOATING)) { at.mFlags.set_bit(CWayEdge::WE_FLYING); - if (!a.mFlags.get_bit(CWayNode::WN_FLOATING) || !b.mFlags.get_bit(CWayNode::WN_FLOATING)) - { + if (!a.mFlags.get_bit(CWayNode::WN_FLOATING) || !b.mFlags.get_bit(CWayNode::WN_FLOATING)) { at.mFlags.set_bit(CWayEdge::WE_CANBEINVAL); } } - // Well, It' Can't Go, But Possibly If We Hit An Entity And Remove That Entity, We Can Go? //----------------------------------------------------------------------------------------- - if (!CanGo && - !mMoveTrace.startsolid && - EntHit!=ENTITYNUM_WORLD && - EntHit!=ENTITYNUM_NONE && - (&g_entities[EntHit])!=0) - { - gentity_t* ent = &g_entities[EntHit]; + if (!CanGo && !mMoveTrace.startsolid && EntHit != ENTITYNUM_WORLD && EntHit != ENTITYNUM_NONE && (&g_entities[EntHit]) != 0) { + gentity_t *ent = &g_entities[EntHit]; - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Hit Entity Type (%s), TargetName (%s)\n", aName, bName, ent->classname, ent->targetname); } - // Find Out What Type Of Entity This Is //-------------------------------------- - if (!Q_stricmp("func_door", ent->classname)) - { + if (!Q_stricmp("func_door", ent->classname)) { at.mFlags.set_bit(CWayEdge::WE_BLOCKING_DOOR); - } - else if ( - !Q_stricmp("func_wall", ent->classname) || - !Q_stricmp("func_static", ent->classname) || - !Q_stricmp("func_usable", ent->classname)) - { + } else if (!Q_stricmp("func_wall", ent->classname) || !Q_stricmp("func_static", ent->classname) || !Q_stricmp("func_usable", ent->classname)) { at.mFlags.set_bit(CWayEdge::WE_BLOCKING_WALL); - } - else if ( - !Q_stricmp("func_glass", ent->classname) || - !Q_stricmp("func_breakable", ent->classname) || - !Q_stricmp("misc_model_breakable", ent->classname)) - { + } else if (!Q_stricmp("func_glass", ent->classname) || !Q_stricmp("func_breakable", ent->classname) || + !Q_stricmp("misc_model_breakable", ent->classname)) { at.mFlags.set_bit(CWayEdge::WE_BLOCKING_BREAK); - } - else if (ent->NPC || ent->s.number==0) - { + } else if (ent->NPC || ent->s.number == 0) { HitCharacter = true; } // Don't Care About Any Other Entity Types //----------------------------------------- - else - { - if (IsDebugEdge) - { + else { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Unable To Ignore Ent, Going A Size Down\n", aName, bName); } - return CanGo; // Go To Next Size Down + return CanGo; // Go To Next Size Down } - // If It Is A Door, Try Opening The Door To See If We Can Get In //--------------------------------------------------------------- - if (at.BlockingDoor()) - { + if (at.BlockingDoor()) { // Find The Master //----------------- gentity_t *master = ent; - while (master && master->teammaster && (master->flags&FL_TEAMSLAVE)) - { + while (master && master->teammaster && (master->flags & FL_TEAMSLAVE)) { master = master->teammaster; } - bool DoorIsStartOpen = master->spawnflags&1; + bool DoorIsStartOpen = master->spawnflags & 1; // Open The Chain //---------------- gentity_t *slave = master; - while (slave) - { - VectorCopy((DoorIsStartOpen)?(slave->pos1):(slave->pos2), slave->currentOrigin); + while (slave) { + VectorCopy((DoorIsStartOpen) ? (slave->pos1) : (slave->pos2), slave->currentOrigin); gi.linkentity(slave); slave = slave->teamchain; } @@ -1345,15 +1099,11 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Try The Trace //--------------- CanGo = MoveTrace(a.mPoint, b.mPoint, Mins, Maxs, 0, true, false); - if (CanGo) - { - ent = master; - EntHit = master->s.number; - } - else - { - if (IsDebugEdge) - { + if (CanGo) { + ent = master; + EntHit = master->s.number; + } else { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Unable Pass Through Door Even When Open, Going A Size Down\n", aName, bName); } } @@ -1361,9 +1111,8 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Close The Door //---------------- slave = master; - while (slave) - { - VectorCopy((DoorIsStartOpen)?(slave->pos2):(slave->pos1), slave->currentOrigin); + while (slave) { + VectorCopy((DoorIsStartOpen) ? (slave->pos2) : (slave->pos1), slave->currentOrigin); gi.linkentity(slave); slave = slave->teamchain; } @@ -1371,51 +1120,39 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Assume Breakable Walls Will Be Clear Later //----------------------------------------------------- - else if (at.BlockingBreakable()) - {//we'll do the trace again later if this ent gets broken + else if (at.BlockingBreakable()) { // we'll do the trace again later if this ent gets broken CanGo = true; } // Otherwise, Try It, Pretending The Ent is Not There //---------------------------------------------------- - else - { + else { CanGo = MoveTrace(a.mPoint, b.mPoint, Mins, Maxs, EntHit, true, false); - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Unable Pass Through Even If Entity Was Gone, Going A Size Down\n", aName, bName); } } - - // If We Can Now Go, Ignoring The Entity, Remember That (But Don't Remember Characters - They Won't Stay Anyway) //--------------------------------------------------------------------------------------------------------------- - if (CanGo && !HitCharacter) - { - ent->wayedge = atHandle; - at.mEntityNum = EntHit; + if (CanGo && !HitCharacter) { + ent->wayedge = atHandle; + at.mEntityNum = EntHit; at.mFlags.set_bit(CWayEdge::WE_CANBEINVAL); // Add It To The Edge Map //------------------------ TEntEdgeMap::iterator eemiter = mEntEdgeMap.find(EntHit); - if (eemiter==mEntEdgeMap.end()) - { - TEdgesPerEnt EdgesPerEnt; + if (eemiter == mEntEdgeMap.end()) { + TEdgesPerEnt EdgesPerEnt; EdgesPerEnt.push_back(atHandle); mEntEdgeMap.insert(EntHit, EdgesPerEnt); - } - else - { - if (!eemiter->full()) - { + } else { + if (!eemiter->full()) { eemiter->push_back(atHandle); - } - else - { + } else { #ifndef FINAL_BUILD - assert("Max Edges Perh Handle Reached, Unable To Add To Edge Map!"==0); + assert("Max Edges Perh Handle Reached, Unable To Add To Edge Map!" == 0); gi.Printf("WARNING: Too many nav edges pass through entity %d (%s)\n", EntHit, g_entities[EntHit].targetname); #endif } @@ -1423,36 +1160,28 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Check For Special Conditions For The Different Types //------------------------------------------------------- - if (at.BlockingDoor()) - { + if (at.BlockingDoor()) { // Doors Need To Know Their "owner" Entity - The Thing That Controlls // When The Door Is Open (or can "auto open") // // We'll start by assuming the door is it's own master //----------------------------------------------------- at.mOwnerNum = ent->s.number; - gentity_t* owner = 0; + gentity_t *owner = 0; // If There Is A Target Name, See If This Thing Is Controlled From A Switch Or Something //--------------------------------------------------------------------------------------- - if (ent->targetname) - { + if (ent->targetname) { // Try Target //------------ owner = G_Find(owner, FOFS(target), ent->targetname); - if (owner && - (!Q_stricmp("trigger_multiple", owner->classname) || !Q_stricmp("trigger_once", owner->classname))) - { + if (owner && (!Q_stricmp("trigger_multiple", owner->classname) || !Q_stricmp("trigger_once", owner->classname))) { at.mOwnerNum = owner->s.number; - } - else - { + } else { // Try Target2 //------------- owner = G_Find(owner, FOFS(target2), ent->targetname); - if (owner && - (!Q_stricmp("trigger_multiple", owner->classname) || !Q_stricmp("trigger_once", owner->classname))) - { + if (owner && (!Q_stricmp("trigger_multiple", owner->classname) || !Q_stricmp("trigger_once", owner->classname))) { at.mOwnerNum = owner->s.number; } } @@ -1460,11 +1189,9 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Otherwise, See If There Is An Auto Door Opener Trigger //-------------------------------------------------------- - else - { + else { owner = G_FindDoorTrigger(ent); - if (owner) - { + if (owner) { at.mOwnerNum = owner->s.number; } } @@ -1472,8 +1199,7 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Breakable Walls Are Not Valid Until Broken. Period //----------------------------------------------------- - else if (at.BlockingBreakable()) - {//we'll do the trace again later if this ent gets broken + else if (at.BlockingBreakable()) { // we'll do the trace again later if this ent gets broken at.mFlags.clear_bit(CWayEdge::WE_VALID); } } @@ -1481,23 +1207,21 @@ bool NAV::TestEdge( TNodeHandle NodeA, TNodeHandle NodeB, qboolean IsDebugEdge // Now Search For Any Holes In The Ground //---------------------------------------- - if (CHECK_JUMP && CanGo) - { - CVec3 Mins(-15.0f, -15.0f, 0.0f); // These were the old "sizeless" defaults - CVec3 Maxs(15.0f, 15.0f, 40.0f); + if (CHECK_JUMP && CanGo) { + CVec3 Mins(-15.0f, -15.0f, 0.0f); // These were the old "sizeless" defaults + CVec3 Maxs(15.0f, 15.0f, 40.0f); - CVec3 AtoB(b.mPoint - a.mPoint); - float AtoBDist = AtoB.SafeNorm(); - int AtoBSegs = (AtoBDist / MAX_EDGE_SEG_LEN); + CVec3 AtoB(b.mPoint - a.mPoint); + float AtoBDist = AtoB.SafeNorm(); + int AtoBSegs = (AtoBDist / MAX_EDGE_SEG_LEN); AtoB *= MAX_EDGE_SEG_LEN; - CVec3 Start(a.mPoint); - CVec3 Stop; + CVec3 Start(a.mPoint); + CVec3 Stop; - for (int curSeg=1; (curSeginuse) - { + TEntBits Doors; + TEntBits Walls; + TEntBits NPCs; + if (CHECK_START_OPEN) { + for (int curEnt = 0; curEnt < MAX_GENTITIES; curEnt++) { + gentity_t *ent = &g_entities[curEnt]; + + if (!ent || !ent->inuse) { continue; } // Is It An NPC or Vehicle? //-------------------------------------- - if (ent->NPC || (ent->NPC_type && Q_stricmp(ent->NPC_type, "atst")==0)) - { + if (ent->NPC || (ent->NPC_type && Q_stricmp(ent->NPC_type, "atst") == 0)) { NPCs.set_bit(curEnt); ent->lastMoveTime = ent->contents; ent->contents = 0; gi.linkentity(ent); } - - // Is This Ent "Start Off" or "Start Open"? //------------------------------------------ - if (!(ent->spawnflags&1)) - { + if (!(ent->spawnflags & 1)) { continue; } - // Is It A Door? Then Close It //-------------------------------------- - if (!Q_stricmp("func_door", ent->classname)) - { + if (!Q_stricmp("func_door", ent->classname)) { Doors.set_bit(curEnt); VectorCopy(ent->pos2, ent->currentOrigin); gi.linkentity(ent); @@ -1569,8 +1282,7 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) // Is It A Wall? Then Turn It On //-------------------------------------- - else if (!Q_stricmp("func_wall", ent->classname) || !Q_stricmp("func_usable", ent->classname)) - { + else if (!Q_stricmp("func_wall", ent->classname) || !Q_stricmp("func_usable", ent->classname)) { Walls.set_bit(curEnt); ent->contents = ent->spawnContents; gi.linkentity(ent); @@ -1578,140 +1290,117 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) } } - // PHASE I: TRIANGULATE ALL NODES IN THE GRAPH //============================================= -/* TGraphTriang *Triang = new TGraphTriang(mGraph); - Triang->clear(); - Triang->insertion_hull(); - Triang->delaunay_edge_flip(); - Triang->floor_shape(mUser, 1000.0f); - Triang->alpha_shape(mUser, 1000.0f); - Triang->finish(mUser); - delete Triang; -*/ + /* TGraphTriang *Triang = new TGraphTriang(mGraph); + Triang->clear(); + Triang->insertion_hull(); + Triang->delaunay_edge_flip(); + Triang->floor_shape(mUser, 1000.0f); + Triang->alpha_shape(mUser, 1000.0f); + Triang->finish(mUser); + delete Triang; + */ mCells.fill_cells_nodes(NAV::CELL_RANGE); - - - - - // PHASE II: SCAN THROUGH EXISTING NODES AND GENERATE EDGES TO OTHER NODES WAY POINTS //==================================================================================== - CWayNode* at; - int atHandle; + CWayNode *at; + int atHandle; #ifdef _DEBUG - const char* atNameStr; + const char *atNameStr; #endif // _DEBUG - int tgtNum; - int tgtHandle; - hstring tgtName; + int tgtNum; + int tgtHandle; + hstring tgtName; #ifdef _DEBUG - const char* tgtNameStr; + const char *tgtNameStr; #endif // _DEBUG - CWayEdge atToTgt; - CVec3 atFloor; - CVec3 atRoof; - bool atOnFloor; + CWayEdge atToTgt; + CVec3 atFloor; + CVec3 atRoof; + bool atOnFloor; + TNameToNodeMap::iterator nameFinder; + TGraph::TNodes::iterator nodeIter; + TGraph::TEdges::iterator edgeIter; - TNameToNodeMap::iterator nameFinder; - TGraph::TNodes::iterator nodeIter; - TGraph::TEdges::iterator edgeIter; - - ratl::ratl_compare closestNbrs[MIN_WAY_NEIGHBORS]; + ratl::ratl_compare closestNbrs[MIN_WAY_NEIGHBORS]; // Drop To Floor And Mark Floating //--------------------------------- - for (nodeIter=mGraph.nodes_begin(); nodeIter!=mGraph.nodes_end(); nodeIter++) - { - at = &(*nodeIter); - atRoof = at->mPoint; - atFloor = at->mPoint; - if (at->mFlags.get_bit(CWayNode::WN_DROPTOFLOOR)) - { - atFloor[2] -= MAX_EDGE_FLOOR_DIST; - } - atFloor[2] -= (MAX_EDGE_FLOOR_DIST * 1.5f); - atOnFloor = !ViewTrace(atRoof, atFloor); - if (at->mFlags.get_bit(CWayNode::WN_DROPTOFLOOR)) - { - at->mPoint = mViewTrace.endpos; - at->mPoint[2] += 5.0f; - } - else if (!atOnFloor && (at->mType==PT_WAYNODE || at->mType==PT_GOALNODE)) - { + for (nodeIter = mGraph.nodes_begin(); nodeIter != mGraph.nodes_end(); nodeIter++) { + at = &(*nodeIter); + atRoof = at->mPoint; + atFloor = at->mPoint; + if (at->mFlags.get_bit(CWayNode::WN_DROPTOFLOOR)) { + atFloor[2] -= MAX_EDGE_FLOOR_DIST; + } + atFloor[2] -= (MAX_EDGE_FLOOR_DIST * 1.5f); + atOnFloor = !ViewTrace(atRoof, atFloor); + if (at->mFlags.get_bit(CWayNode::WN_DROPTOFLOOR)) { + at->mPoint = mViewTrace.endpos; + at->mPoint[2] += 5.0f; + } else if (!atOnFloor && (at->mType == PT_WAYNODE || at->mType == PT_GOALNODE)) { at->mFlags.set_bit(CWayNode::WN_FLOATING); } } - - for (nodeIter=mGraph.nodes_begin(); nodeIter!=mGraph.nodes_end(); nodeIter++) - { + for (nodeIter = mGraph.nodes_begin(); nodeIter != mGraph.nodes_end(); nodeIter++) { nodeIter->mPoint.ToStr(mLocStringA); - at = &(*nodeIter); - atHandle = (nodeIter.index()); + at = &(*nodeIter); + atHandle = (nodeIter.index()); #ifdef _DEBUG - atNameStr = (at->mName.empty())?(mLocStringA):(at->mName.c_str()); + atNameStr = (at->mName.empty()) ? (mLocStringA) : (at->mName.c_str()); #endif // _DEBUG // Connect To Hand Designed Targets //---------------------------------- - for (tgtNum=0; tgtNummTargets[tgtNum]; - if (!tgtName || tgtName.empty()) - { + tgtName = at->mTargets[tgtNum]; + if (!tgtName || tgtName.empty()) { continue; } #ifdef _DEBUG - tgtNameStr = tgtName.c_str(); + tgtNameStr = tgtName.c_str(); #endif // _DEBUG // Clear The Name In The Array, So Save Is Not Corrupted //------------------------------------------------------- at->mTargets[tgtNum] = 0; - // Try To Find The Node This Target Name Refers To //------------------------------------------------- - nameFinder = mNodeNames.find(tgtName); - if (nameFinder==mNodeNames.end()) - { + nameFinder = mNodeNames.find(tgtName); + if (nameFinder == mNodeNames.end()) { #ifdef _DEBUG - gi.Printf( S_COLOR_YELLOW "WARNING: nav unable to locate target (%s) from node (%s)\n", tgtNameStr, - atNameStr ); + gi.Printf(S_COLOR_YELLOW "WARNING: nav unable to locate target (%s) from node (%s)\n", tgtNameStr, atNameStr); #endif // _DEBUG continue; } // For Each One //-------------- - for (int tgtNameIndex=0; tgtNameIndex<(*nameFinder).size(); tgtNameIndex++) - { + for (int tgtNameIndex = 0; tgtNameIndex < (*nameFinder).size(); tgtNameIndex++) { // Connect The Two Nodes In The Graph //------------------------------------ - tgtHandle = (*nameFinder)[tgtNameIndex]; + tgtHandle = (*nameFinder)[tgtNameIndex]; // Only If The Target Is NOT The Same As The Source //-------------------------------------------------- - if (atHandle!=tgtHandle) - { + if (atHandle != tgtHandle) { int edge = mGraph.get_edge_across(atHandle, tgtHandle); // If The Edge Already Exists, Just Make Sure To Add Any Flags //------------------------------------------------------------- - if (edge) - { + if (edge) { // If It Is The Jump Edge (Last Target), Mark It //----------------------------------------------- - if (tgtNum == (NAV::NUM_TARGETS-1)) - { + if (tgtNum == (NAV::NUM_TARGETS - 1)) { mGraph.get_edge(edge).mFlags.set_bit(CWayEdge::WE_JUMPING); } mGraph.get_edge(edge).mFlags.set_bit(CWayEdge::WE_DESIGNERPLACED); @@ -1725,8 +1414,7 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) // If It Is The Jump Edge (Last Target), Mark It //----------------------------------------------- - if (tgtNum == (NAV::NUM_TARGETS-1)) - { + if (tgtNum == (NAV::NUM_TARGETS - 1)) { atToTgt.mFlags.set_bit(CWayEdge::WE_JUMPING); } @@ -1737,105 +1425,87 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) } } - // If It Is A Combat Or Goal Nav, Try To "Auto Connect" To A Few Nearby Way Points //--------------------------------------------------------------------------------- - if (!at->mFlags.get_bit(CWayNode::WN_NOAUTOCONNECT) && - (at->mType==NAV::PT_COMBATNODE || at->mType==NAV::PT_GOALNODE)) - { + if (!at->mFlags.get_bit(CWayNode::WN_NOAUTOCONNECT) && (at->mType == NAV::PT_COMBATNODE || at->mType == NAV::PT_GOALNODE)) { // Get The List Of Nodes For This Cell Of The Map //------------------------------------------------ - TGraphCells::SCell& Cell = mCells.get_cell(at->mPoint[0], at->mPoint[1]); + TGraphCells::SCell &Cell = mCells.get_cell(at->mPoint[0], at->mPoint[1]); // Create A Closest Neighbors Array And Initialize It Empty //---------------------------------------------------------- - for (int i=0; imPoint[2])>NAV::MAX_EDGE_FLOOR_DIST) - { + if (fabsf(node.mPoint[2] - at->mPoint[2]) > NAV::MAX_EDGE_FLOOR_DIST) { continue; } // Ignore Ones That Are Too Far //------------------------------ float cost = node.mPoint.Dist(at->mPoint); - if (cost>NAV::MAX_EDGE_AUTO_LEN) - { + if (cost > NAV::MAX_EDGE_AUTO_LEN) { continue; } // Connecting To Another Combat Point Or Goal Node It Must Be Half The Max Connect Distance //------------------------------------------------------------------------------------------ - if (node.mType==NAV::PT_COMBATNODE || node.mType==NAV::PT_GOALNODE) - { + if (node.mType == NAV::PT_COMBATNODE || node.mType == NAV::PT_GOALNODE) { nonWPCount++; - if (nonWPCount>NAV::MAX_NONWP_NEIGHBORS) - { + if (nonWPCount > NAV::MAX_NONWP_NEIGHBORS) { continue; } - if (cost>(NAV::MAX_EDGE_AUTO_LEN/2.0f)) - { + if (cost > (NAV::MAX_EDGE_AUTO_LEN / 2.0f)) { continue; } } // If We Already Have Points, Ignore Anything Farther Than The Current Farthest //------------------------------------------------------------------------------ - if (closestNbrs[highestCost].mHandle!=0 && closestNbrs[highestCost].mCostmPoint.v))) - { + if (!(gi.inPVS(node.mPoint.v, at->mPoint.v))) { continue; } - // Now Record This Point Over The One With The Highest Cost //---------------------------------------------------------- - closestNbrs[highestCost].mHandle = tgtHandle; - closestNbrs[highestCost].mCost = node.mPoint.Dist(at->mPoint); + closestNbrs[highestCost].mHandle = tgtHandle; + closestNbrs[highestCost].mCost = node.mPoint.Dist(at->mPoint); // Find The New Highest Cost //--------------------------- - for (int i=0; iclosestNbrs[highestCost].mCost) - { + if (closestNbrs[i].mCost > closestNbrs[highestCost].mCost) { highestCost = i; } } @@ -1843,10 +1513,8 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) // Now Connect All The Closest Neighbors //--------------------------------------- - for (int i=0; i *ToBeRemoved = new ratl::vector_vs; - for (edgeIter=mGraph.edges_begin(); edgeIter!=mGraph.edges_end(); edgeIter++) - { - CWayEdge& at = (*edgeIter); - int atHandle = edgeIter.index(); - CWayNode& a = mGraph.get_node(at.mNodeA); - CWayNode& b = mGraph.get_node(at.mNodeB); + ratl::vector_vs *ToBeRemoved = new ratl::vector_vs; + for (edgeIter = mGraph.edges_begin(); edgeIter != mGraph.edges_end(); edgeIter++) { + CWayEdge &at = (*edgeIter); + int atHandle = edgeIter.index(); + CWayNode &a = mGraph.get_node(at.mNodeA); + CWayNode &b = mGraph.get_node(at.mNodeB); mGraph.get_node(at.mNodeA).mPoint.ToStr(mLocStringA); mGraph.get_node(at.mNodeB).mPoint.ToStr(mLocStringB); - const char* aName = (a.mName.empty())?(mLocStringA):(a.mName.c_str()); - const char* bName = (b.mName.empty())?(mLocStringB):(b.mName.c_str()); + const char *aName = (a.mName.empty()) ? (mLocStringA) : (a.mName.c_str()); + const char *bName = (b.mName.empty()) ? (mLocStringB) : (b.mName.c_str()); - - if (at.mFlags.get_bit(CWayEdge::WE_JUMPING)) - { + if (at.mFlags.get_bit(CWayEdge::WE_JUMPING)) { at.mFlags.set_bit(CWayEdge::WE_SIZE_LARGE); at.mFlags.set_bit(CWayEdge::WE_CANBEINVAL); at.mFlags.set_bit(CWayEdge::WE_DESIGNERPLACED); continue; } - // Cycle through the different sizes, starting with the largest //-------------------------------------------------------------- - bool CanGo = false; - bool IsDebugEdge = - (g_nav1->string[0] && g_nav2->string[0] && - (!Q_stricmp(*(a.mName), g_nav1->string) || !Q_stricmp(*(b.mName), g_nav1->string)) && - (!Q_stricmp(*(a.mName), g_nav2->string) || !Q_stricmp(*(b.mName), g_nav2->string))); + bool CanGo = false; + bool IsDebugEdge = (g_nav1->string[0] && g_nav2->string[0] && (!Q_stricmp(*(a.mName), g_nav1->string) || !Q_stricmp(*(b.mName), g_nav1->string)) && + (!Q_stricmp(*(a.mName), g_nav2->string) || !Q_stricmp(*(b.mName), g_nav2->string))); // For debugging a connection between two known points: //------------------------------------------------------ - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("===============================\n"); gi.Printf("Nav(%s)<->(%s): DEBUGGING START\n", aName, bName); - assert(0); // Break Here + assert(0); // Break Here } // Try Large //----------- at.mFlags.set_bit(CWayEdge::WE_SIZE_LARGE); - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Attempting Size Large...\n", aName, bName); } // Try Medium //------------ - CanGo = TestEdge( at.mNodeA, at.mNodeB, (qboolean)IsDebugEdge ); - if (!CanGo) - { + CanGo = TestEdge(at.mNodeA, at.mNodeB, (qboolean)IsDebugEdge); + if (!CanGo) { at.mFlags.clear_bit(CWayEdge::WE_SIZE_LARGE); at.mFlags.set_bit(CWayEdge::WE_SIZE_MEDIUM); - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Attempting Size Medium...\n", aName, bName); } - CanGo = TestEdge( at.mNodeA, at.mNodeB, (qboolean)IsDebugEdge ); + CanGo = TestEdge(at.mNodeA, at.mNodeB, (qboolean)IsDebugEdge); } // If This Edge Can't Go At Any Size, Dump It //-------------------------------------------- - if (!CanGo) - { + if (!CanGo) { ToBeRemoved->push_back(atHandle); - if (IsDebugEdge) - { - CVec3 ContactNormal(mMoveTrace.plane.normal); - CVec3 ContactPoint( mMoveTrace.endpos); + if (IsDebugEdge) { + CVec3 ContactNormal(mMoveTrace.plane.normal); + CVec3 ContactPoint(mMoveTrace.endpos); - char cpointstr[256] = {0}; - char cnormstr[256] = {0}; + char cpointstr[256] = {0}; + char cnormstr[256] = {0}; ContactNormal.ToStr(cnormstr); ContactPoint.ToStr(cpointstr); @@ -1943,39 +1595,27 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) gi.Printf("Nav(%s)<->(%s): The last trace hit:\n", aName, bName); gi.Printf("Nav(%s)<->(%s): at %s,\n", aName, bName, cpointstr); gi.Printf("Nav(%s)<->(%s): normal %s\n", aName, bName, cnormstr); - if (mMoveTrace.entityNum!=ENTITYNUM_WORLD) - { - gentity_t* ent = &g_entities[mMoveTrace.entityNum]; + if (mMoveTrace.entityNum != ENTITYNUM_WORLD) { + gentity_t *ent = &g_entities[mMoveTrace.entityNum]; gi.Printf("Nav(%s)<->(%s): on entity Type (%s), TargetName (%s)\n", aName, bName, ent->classname, ent->targetname); } - if ((mMoveTrace.contents)&CONTENTS_MONSTERCLIP) - { + if ((mMoveTrace.contents) & CONTENTS_MONSTERCLIP) { gi.Printf("Nav(%s)<->(%s): with contents BLOCKNPC\n", aName, bName); - } - else if ((mMoveTrace.contents)&CONTENTS_BOTCLIP) - { + } else if ((mMoveTrace.contents) & CONTENTS_BOTCLIP) { gi.Printf("Nav(%s)<->(%s): with contents DONOTENTER\n", aName, bName); - } - else if ((mMoveTrace.contents)&CONTENTS_SOLID) - { + } else if ((mMoveTrace.contents) & CONTENTS_SOLID) { gi.Printf("Nav(%s)<->(%s): with contents SOLID\n", aName, bName); - } - else if ((mMoveTrace.contents)&CONTENTS_WATER) - { + } else if ((mMoveTrace.contents) & CONTENTS_WATER) { gi.Printf("Nav(%s)<->(%s): with contents WATER\n", aName, bName); } } - } - else - { - if (IsDebugEdge) - { + } else { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): Success!\n", aName, bName); } } - if (IsDebugEdge) - { + if (IsDebugEdge) { gi.Printf("Nav(%s)<->(%s): DEBUGGING END\n", aName, bName); gi.Printf("===============================\n"); } @@ -1983,22 +1623,19 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) // Now Go Ahead And Remove Dead Edges //------------------------------------ - for (int RemIndex=0;RemIndexsize(); RemIndex++) - { - CWayEdge& at = mGraph.get_edge((*ToBeRemoved)[RemIndex]); - if (at.mFlags.get_bit(CWayEdge::WE_DESIGNERPLACED)) - { + for (int RemIndex = 0; RemIndex < ToBeRemoved->size(); RemIndex++) { + CWayEdge &at = mGraph.get_edge((*ToBeRemoved)[RemIndex]); + if (at.mFlags.get_bit(CWayEdge::WE_DESIGNERPLACED)) { #ifdef _DEBUG - hstring aHstr = mGraph.get_node(at.mNodeA).mName; - hstring bHstr = mGraph.get_node(at.mNodeB).mName; + hstring aHstr = mGraph.get_node(at.mNodeA).mName; + hstring bHstr = mGraph.get_node(at.mNodeB).mName; #endif // _DEBUG mGraph.get_node(at.mNodeA).mPoint.ToStr(mLocStringA); mGraph.get_node(at.mNodeB).mPoint.ToStr(mLocStringB); #ifdef _DEBUG - gi.Printf( S_COLOR_RED "ERROR: Nav connect failed: %s@%s <-> %s@%s\n", aHstr.c_str(), mLocStringA, - bHstr.c_str(), mLocStringB ); + gi.Printf(S_COLOR_RED "ERROR: Nav connect failed: %s@%s <-> %s@%s\n", aHstr.c_str(), mLocStringA, bHstr.c_str(), mLocStringB); #endif // _DEBUG delayedShutDown = level.time + 100; } @@ -2009,34 +1646,29 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) // Detect Point Islands //---------------------- - for (nodeIter=mGraph.nodes_begin(); nodeIter!=mGraph.nodes_end(); nodeIter++) - { - at = &(*nodeIter); - atHandle = nodeIter.index(); + for (nodeIter = mGraph.nodes_begin(); nodeIter != mGraph.nodes_end(); nodeIter++) { + at = &(*nodeIter); + atHandle = nodeIter.index(); - if (!mGraph.node_has_neighbors(atHandle)) - { + if (!mGraph.node_has_neighbors(atHandle)) { at->mPoint.ToStr(mLocStringA); at->mFlags.set_bit(CWayNode::WN_ISLAND); mIslandCount++; - if (at->mType==NAV::PT_COMBATNODE) - { + if (at->mType == NAV::PT_COMBATNODE) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: Combat Point %s@%s Is Not Connected To Anything\n", at->mName.c_str(), mLocStringA); + gi.Printf(S_COLOR_RED "ERROR: Combat Point %s@%s Is Not Connected To Anything\n", at->mName.c_str(), mLocStringA); delayedShutDown = level.time + 100; #endif } - if (at->mType==NAV::PT_GOALNODE) - { + if (at->mType == NAV::PT_GOALNODE) { // Try To Trace Down, If We Don't Hit Any Ground, Assume This Is An "Air Point" //------------------------------------------------------------------------------ CVec3 Down(at->mPoint); Down[2] -= 100; - if (!ViewTrace(at->mPoint, Down)) - { + if (!ViewTrace(at->mPoint, Down)) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: Nav Goal %s@%s Is Not Connected To Anything\n", at->mName.c_str(), mLocStringA); + gi.Printf(S_COLOR_RED "ERROR: Nav Goal %s@%s Is Not Connected To Anything\n", at->mName.c_str(), mLocStringA); delayedShutDown = level.time + 100; #endif } @@ -2044,88 +1676,71 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) } } - - // PHASE IV: SCAN EDGES FOR REGIONS //================================== mRegion.clear(); - mIslandRegion = mRegion.reserve(); -// mAirRegion = mRegion.reserve(); - for (nodeIter=mGraph.nodes_begin(); nodeIter!=mGraph.nodes_end(); nodeIter++) - { - at = &(*nodeIter); - if (at->mFlags.get_bit(CWayNode::WN_ISLAND)) - { + mIslandRegion = mRegion.reserve(); + // mAirRegion = mRegion.reserve(); + for (nodeIter = mGraph.nodes_begin(); nodeIter != mGraph.nodes_end(); nodeIter++) { + at = &(*nodeIter); + if (at->mFlags.get_bit(CWayNode::WN_ISLAND)) { mRegion.assign_region(nodeIter.index(), mIslandRegion); } - // else if (at->mFlags.get_bit(CWayNode::WN_FLOATING)) - // { - // mRegion.assign_region(nodeIter.index(), mAirRegion); - // } + // else if (at->mFlags.get_bit(CWayNode::WN_FLOATING)) + // { + // mRegion.assign_region(nodeIter.index(), mAirRegion); + // } } - if (!mRegion.find_regions(mUser)) - { + if (!mRegion.find_regions(mUser)) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: Too Many Regions!\n"); + gi.Printf(S_COLOR_RED "ERROR: Too Many Regions!\n"); delayedShutDown = level.time + 100; #endif } - if (!mRegion.find_region_edges()) - { + if (!mRegion.find_region_edges()) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: Too Many Region Edges!\n"); + gi.Printf(S_COLOR_RED "ERROR: Too Many Region Edges!\n"); delayedShutDown = level.time + 100; #endif } - // PHASE V: SCAN NODES AND FILL CELLS //=================================== mCells.fill_cells_edges(NAV::CELL_RANGE); - // PHASE VI: SCAN ALL ENTITIES AND RE OPEN / TURN THEM OFF //========================================================= - if (CHECK_START_OPEN) - { - for (int curEnt=0; curEntinuse) - { + gentity_t *ent = &g_entities[curEnt]; + if (!ent || !ent->inuse) { continue; } - // Is It A Door? //-------------------------------------- - if (Doors.get_bit(curEnt)) - { + if (Doors.get_bit(curEnt)) { VectorCopy(ent->pos1, ent->currentOrigin); gi.linkentity(ent); } // Is It A Wall? //-------------------------------------- - else if (Walls.get_bit(curEnt)) - { + else if (Walls.get_bit(curEnt)) { ent->contents = 0; gi.linkentity(ent); } // Is It An NPC? //-------------------------------------- - else if (NPCs.get_bit(curEnt)) - { + else if (NPCs.get_bit(curEnt)) { ent->contents = ent->lastMoveTime; ent->lastMoveTime = 0; gi.linkentity(ent); } - - } } mConnectTraceCount = mMoveTraceCount; @@ -2133,14 +1748,11 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) mConnectTime = gi.Milliseconds() - mConnectTime; - // PHASE VI: SAVE TO FILE //======================== - if (SAVE_LOAD) - { - hfile navFile(va("maps/%s.navNEW")); - if (!navFile.open_write(NAV_VERSION, checksum)) - { + if (SAVE_LOAD) { + hfile navFile(va("maps/%s.navNEW")); + if (!navFile.open_write(NAV_VERSION, checksum)) { return false; } navFile.save(&mGraph, sizeof(mGraph)); @@ -2154,22 +1766,17 @@ bool NAV::LoadFromEntitiesAndSaveToFile(const char *filename, int checksum) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void NAV::DecayDangerSenses() -{ - float PerFrameDecay = (50.0f) / (float)(NAV::MAX_ALERT_TIME); - for (int entIndex=0; entIndexs.number]; - alertEvent_t& ae = level.alertEvents[alertEventIndex]; + TAlertList &al = mEntityAlertList[actor->s.number]; + alertEvent_t &ae = level.alertEvents[alertEventIndex]; - if (ae.radius<=0.0f) - { + if (ae.radius <= 0.0f) { return; } // DEBUG GRAPHICS //===================================================== - if (NAVDEBUG_showRadius) - { + if (NAVDEBUG_showRadius) { CG_DrawRadius(ae.position, ae.radius, NODE_GOAL); } //===================================================== - - CVec3 DangerPoint(ae.position); + CVec3 DangerPoint(ae.position); // Look Through The Nearby Edges And Record Any That Are Affected //---------------------------------------------------------------- - TGraphCells::TCellNodes& cellEdges = mCells.get_cell(DangerPoint[0], DangerPoint[1]).mEdges; - for (int cellEdgeIndex=0; cellEdgeIndex0.0f) - { + TGraphCells::TCellNodes &cellEdges = mCells.get_cell(DangerPoint[0], DangerPoint[1]).mEdges; + for (int cellEdgeIndex = 0; cellEdgeIndex < cellEdges.size(); cellEdgeIndex++) { + int edgeHandle = cellEdges[cellEdgeIndex]; + CWayEdge &edge = mGraph.get_edge(edgeHandle); + float edgeDanger = ((ae.radius - DangerPoint.DistToLine(edge.PointA(), edge.PointB())) / (ae.radius)); + if (edgeDanger > 0.0f) { // Record The Square, So That Danger Drops Off Quadradically Rather Than Linearly //-------------------------------------------------------------------------------- edgeDanger *= edgeDanger; - // Now Find The Index We Will "Replace" With This New Information //---------------------------------------------------------------- - int replaceIndex = -1; - for (int alIndex=0; alIndexwayedge = 0; int EdgeHandle; - int EntNum = ent->s.number; + int EntNum = ent->s.number; TEntEdgeMap::iterator finder = mEntEdgeMap.find(EntNum); - if (finder!=mEntEdgeMap.end()) - { - for (int i=0; isize(); i++) - { + if (finder != mEntEdgeMap.end()) { + for (int i = 0; i < finder->size(); i++) { EdgeHandle = (*finder)[i]; - if (EdgeHandle!=0) - { - CWayEdge& edge = mGraph.get_edge(EdgeHandle); + if (EdgeHandle != 0) { + CWayEdge &edge = mGraph.get_edge(EdgeHandle); edge.mFlags.set_bit(CWayEdge::WE_VALID); edge.mEntityNum = ENTITYNUM_NONE; edge.mOwnerNum = ENTITYNUM_NONE; @@ -2296,110 +1886,96 @@ void NAV::WayEdgesNowClear(gentity_t* ent) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void NAV::SpawnedPoint(gentity_t* ent, NAV::EPointType type) -{ - if (mGraph.size_nodes()>=NUM_NODES) - { +void NAV::SpawnedPoint(gentity_t *ent, NAV::EPointType type) { + if (mGraph.size_nodes() >= NUM_NODES) { #ifndef FINAL_BUILD - gi.Printf( "SpawnedPoint: Max Nav points reached (%d)!\n",NUM_NODES ); + gi.Printf("SpawnedPoint: Max Nav points reached (%d)!\n", NUM_NODES); #endif - return; + return; } CVec3 Mins; CVec3 Maxs; - Mins[0] = Mins[1] = (SC_MEDIUM_RADIUS) * -1.0f; Maxs[0] = Maxs[1] = (SC_MEDIUM_RADIUS); Mins[2] = 0.0f; Maxs[2] = SC_MEDIUM_HEIGHT; - CVec3 Start(ent->currentOrigin); CVec3 Stop(ent->currentOrigin); Stop[2] += 5.0f; Start.ToStr(mLocStringA); - const char* pointName = (ent->targetname && ent->targetname[0])?(ent->targetname):"?"; + const char *pointName = (ent->targetname && ent->targetname[0]) ? (ent->targetname) : "?"; - if (CHECK_START_SOLID) - { + if (CHECK_START_SOLID) { // Try It //-------- - if (!MoveTrace(Start, Stop, Mins, Maxs, 0, true, false)) - { - assert("ERROR: Nav in solid!"==0); - gi.Printf( S_COLOR_RED"ERROR: Nav(%d) in solid: %s@%s\n", type, pointName, mLocStringA); + if (!MoveTrace(Start, Stop, Mins, Maxs, 0, true, false)) { + assert("ERROR: Nav in solid!" == 0); + gi.Printf(S_COLOR_RED "ERROR: Nav(%d) in solid: %s@%s\n", type, pointName, mLocStringA); delayedShutDown = level.time + 100; return; } } - CWayNode node; + CWayNode node; - node.mPoint = ent->currentOrigin; - node.mRadius = ent->radius; - node.mType = type; + node.mPoint = ent->currentOrigin; + node.mRadius = ent->radius; + node.mType = type; node.mFlags.clear(); - if (type==NAV::PT_WAYNODE && (ent->spawnflags & 2)) - { + if (type == NAV::PT_WAYNODE && (ent->spawnflags & 2)) { node.mFlags.set_bit(CWayNode::WN_DROPTOFLOOR); } - if (ent->spawnflags & 4) - { + if (ent->spawnflags & 4) { node.mFlags.set_bit(CWayNode::WN_NOAUTOCONNECT); } // TO AVOID PROBLEMS WITH THE TRIANGULATION, WE MOVE THE POINTS AROUND JUST A BIT //================================================================================ - //node.mPoint += CVec3(Q_flrand(-RANDOM_PERMUTE, RANDOM_PERMUTE), Q_flrand(-RANDOM_PERMUTE, RANDOM_PERMUTE), 0.0f); + // node.mPoint += CVec3(Q_flrand(-RANDOM_PERMUTE, RANDOM_PERMUTE), Q_flrand(-RANDOM_PERMUTE, RANDOM_PERMUTE), 0.0f); //================================================================================ // Validate That The New Location Is Still Safe //---------------------------------------------- - if (false && CHECK_START_SOLID) - { + if (false && CHECK_START_SOLID) { Start = (node.mPoint); Stop = (node.mPoint); Stop[2] += 5.0f; // Try It Again //-------------- - if (!MoveTrace(Start, Stop, Mins, Maxs, 0, true, false)) - { - gi.Printf( S_COLOR_YELLOW"WARNING: Nav Moved To Solid, Resetting: (%s)\n", pointName); - assert("WARNING: Nav Moved To Solid, Resetting!"==0); - node.mPoint = ent->currentOrigin; + if (!MoveTrace(Start, Stop, Mins, Maxs, 0, true, false)) { + gi.Printf(S_COLOR_YELLOW "WARNING: Nav Moved To Solid, Resetting: (%s)\n", pointName); + assert("WARNING: Nav Moved To Solid, Resetting!" == 0); + node.mPoint = ent->currentOrigin; } } - node.mTargets[0] = ent->target; - node.mTargets[1] = ent->target2; - node.mTargets[2] = ent->target3; - node.mTargets[3] = ent->target4; - node.mTargets[4] = ent->targetJump; - node.mName = ent->targetname; + node.mTargets[0] = ent->target; + node.mTargets[1] = ent->target2; + node.mTargets[2] = ent->target3; + node.mTargets[3] = ent->target4; + node.mTargets[4] = ent->targetJump; + node.mName = ent->targetname; - int NodeHandle = mGraph.insert_node(node); + int NodeHandle = mGraph.insert_node(node); - ent->waypoint = NodeHandle; + ent->waypoint = NodeHandle; mCells.expand_bounds(NodeHandle); - if (!node.mName.empty()) - { - TNameToNodeMap::iterator nameFinder = mNodeNames.find(node.mName); + if (!node.mName.empty()) { + TNameToNodeMap::iterator nameFinder = mNodeNames.find(node.mName); - if (nameFinder==mNodeNames.end()) - { - TNamedNodeList list; + if (nameFinder == mNodeNames.end()) { + TNamedNodeList list; list.clear(); list.push_back(NodeHandle); mNodeNames.insert(node.mName, list); - } - else - { + } else { (*nameFinder).push_back(NodeHandle); } } @@ -2408,27 +1984,17 @@ void NAV::SpawnedPoint(gentity_t* ent, NAV::EPointType type) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::GetNearestNode(gentity_t* ent, bool forceRecalcNow, NAV::TNodeHandle goal) -{ - if (!ent) - { +NAV::TNodeHandle NAV::GetNearestNode(gentity_t *ent, bool forceRecalcNow, NAV::TNodeHandle goal) { + if (!ent) { return 0; } - if (ent->waypoint==WAYPOINT_NONE || forceRecalcNow || (level.time>ent->noWaypointTime)) - { - if (ent->waypoint) - { - ent->lastWaypoint = ent->waypoint; + if (ent->waypoint == WAYPOINT_NONE || forceRecalcNow || (level.time > ent->noWaypointTime)) { + if (ent->waypoint) { + ent->lastWaypoint = ent->waypoint; } - ent->waypoint = - GetNearestNode( - ent->currentOrigin, - ent->waypoint, - goal, - ent->s.number, - (ent->client && ent->client->moveType==MT_FLYSWIM)); - ent->noWaypointTime = level.time + 1000; // Don't Erase This Result For 5 Seconds + ent->waypoint = GetNearestNode(ent->currentOrigin, ent->waypoint, goal, ent->s.number, (ent->client && ent->client->moveType == MT_FLYSWIM)); + ent->noWaypointTime = level.time + 1000; // Don't Erase This Result For 5 Seconds } return ent->waypoint; @@ -2437,88 +2003,74 @@ NAV::TNodeHandle NAV::GetNearestNode(gentity_t* ent, bool forceRecalcNow, NAV:: //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::GetNearestNode(const vec3_t& position, NAV::TNodeHandle previous, NAV::TNodeHandle goal, int ignoreEnt, bool allowZOffset) -{ - if (mGraph.size_edges()>0) - { +NAV::TNodeHandle NAV::GetNearestNode(const vec3_t &position, NAV::TNodeHandle previous, NAV::TNodeHandle goal, int ignoreEnt, bool allowZOffset) { + if (mGraph.size_edges() > 0) { // Get The List Of Nodes For This Cell Of The Map //------------------------------------------------ - TGraphCells::SCell& Cell = mCells.get_cell(position[0], position[1]); - if (Cell.mNodes.empty() && Cell.mEdges.empty()) - { + TGraphCells::SCell &Cell = mCells.get_cell(position[0], position[1]); + if (Cell.mNodes.empty() && Cell.mEdges.empty()) { #ifndef FINAL_BUILD - if (g_developer->value) - { + if (g_developer->value) { gi.Printf("WARNING: Failure To Find A Node Here, Examine Cell Layout\n"); } #endif return WAYPOINT_NONE; } - CVec3 Pos(position); - SNodeSort NodeSort; + CVec3 Pos(position); + SNodeSort NodeSort; // PHASE I - TEST NAV POINTS //=========================== { mNearestNavSort.clear(); - for (int i=0; i(VIEW_RANGE / 4)) - { + if (!allowZOffset) { + float ZOff = fabsf(node.mPoint[2] - Pos[2]); + if (ZOff > (VIEW_RANGE / 4)) { continue; } - if (ZOff>30.0f) - { - NodeSort.mDistance += (ZOff*ZOff); + if (ZOff > 30.0f) { + NodeSort.mDistance += (ZOff * ZOff); } } // Ignore Points That Are Too Far //-------------------------------- - if (NodeSort.mDistance>(NAV::VIEW_RANGE*NAV::VIEW_RANGE)) - { + if (NodeSort.mDistance > (NAV::VIEW_RANGE * NAV::VIEW_RANGE)) { continue; } // Bias Points That Are Not Connected To Anything //------------------------------------------------ - if (node.mFlags.get_bit(CWayNode::WN_ISLAND)) - { + if (node.mFlags.get_bit(CWayNode::WN_ISLAND)) { NodeSort.mDistance *= 3.0f; } - if (previous && previous!=NodeSort.mHandle && !NAV::InSameRegion(previous, NodeSort.mHandle)) - { - NodeSort.mDistance += (100.0f*100.0f); + if (previous && previous != NodeSort.mHandle && !NAV::InSameRegion(previous, NodeSort.mHandle)) { + NodeSort.mDistance += (100.0f * 100.0f); } - if (previous>0 && previous!=NodeSort.mHandle && !mGraph.get_edge_across(previous, NodeSort.mHandle)) - { - NodeSort.mDistance += (200.0f*200.0f); + if (previous > 0 && previous != NodeSort.mHandle && !mGraph.get_edge_across(previous, NodeSort.mHandle)) { + NodeSort.mDistance += (200.0f * 200.0f); } - if (goal && goal!=NodeSort.mHandle && !NAV::InSameRegion(goal, NodeSort.mHandle)) - { - NodeSort.mDistance += (300.0f*300.0f); + if (goal && goal != NodeSort.mHandle && !NAV::InSameRegion(goal, NodeSort.mHandle)) { + NodeSort.mDistance += (300.0f * 300.0f); } - // Bias Combat And Goal Nodes Some //--------------------------------- - // if (node.mType==NAV::PT_COMBATNODE || node.mType==NAV::PT_GOALNODE) - // { - // NodeSort.mDistance += 50.0f; - // } + // if (node.mType==NAV::PT_COMBATNODE || node.mType==NAV::PT_GOALNODE) + // { + // NodeSort.mDistance += 50.0f; + // } mNearestNavSort.push_back(NodeSort); } @@ -2529,19 +2081,16 @@ NAV::TNodeHandle NAV::GetNearestNode(const vec3_t& position, NAV::TNodeHandle p // Now , Run Through Each Of The Sorted Nodes, Starting With The Closest One //--------------------------------------------------------------------------- - for (int j=0; j(VIEW_RANGE / 4)) - { + if (!allowZOffset) { + float ZOff = fabsf(Point[2] - Pos[2]); + if (ZOff > (VIEW_RANGE / 4)) { continue; } - if (ZOff>30.0f) - { - NodeSort.mDistance += (ZOff*ZOff); + if (ZOff > 30.0f) { + NodeSort.mDistance += (ZOff * ZOff); } } // Ignore Points That Are Too Far //-------------------------------- - if (NodeSort.mDistance>(NAV::VIEW_RANGE*NAV::VIEW_RANGE)) - { + if (NodeSort.mDistance > (NAV::VIEW_RANGE * NAV::VIEW_RANGE)) { continue; } mNearestNavSort.push_back(NodeSort); @@ -2593,20 +2137,17 @@ NAV::TNodeHandle NAV::GetNearestNode(const vec3_t& position, NAV::TNodeHandle p // Now , Run Through Each Of The Sorted Edges, Starting With The Closest One //--------------------------------------------------------------------------- - for (int j=0; j0.0f && PointOnEdgeRange<1.0f) - { + if (PointOnEdgeRange > 0.0f && PointOnEdgeRange < 1.0f) { // Otherwise, We Need To Trace To It //----------------------------------- - if (ViewNavTrace(Pos, PointOnEdge)) - { - return (mNearestNavSort[j].mHandle * -1); // "Edges" have negative IDs + if (ViewNavTrace(Pos, PointOnEdge)) { + return (mNearestNavSort[j].mHandle * -1); // "Edges" have negative IDs } } } @@ -2618,14 +2159,11 @@ NAV::TNodeHandle NAV::GetNearestNode(const vec3_t& position, NAV::TNodeHandle p //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::ChooseRandomNeighbor(NAV::TNodeHandle NodeHandle) -{ - if (NodeHandle!=WAYPOINT_NONE && NodeHandle>0) - { - TGraph::TNodeNeighbors& neighbors = mGraph.get_node_neighbors(NodeHandle); - if (neighbors.size()>0) - { - return (neighbors[Q_irand(0, neighbors.size()-1)].mNode); +NAV::TNodeHandle NAV::ChooseRandomNeighbor(NAV::TNodeHandle NodeHandle) { + if (NodeHandle != WAYPOINT_NONE && NodeHandle > 0) { + TGraph::TNodeNeighbors &neighbors = mGraph.get_node_neighbors(NodeHandle); + if (neighbors.size() > 0) { + return (neighbors[Q_irand(0, neighbors.size() - 1)].mNode); } } return WAYPOINT_NONE; @@ -2634,24 +2172,19 @@ NAV::TNodeHandle NAV::ChooseRandomNeighbor(NAV::TNodeHandle NodeHandle) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::ChooseRandomNeighbor(TNodeHandle NodeHandle, const vec3_t& position, float maxDistance) -{ - if (NodeHandle!=WAYPOINT_NONE && NodeHandle>0) - { +NAV::TNodeHandle NAV::ChooseRandomNeighbor(TNodeHandle NodeHandle, const vec3_t &position, float maxDistance) { + if (NodeHandle != WAYPOINT_NONE && NodeHandle > 0) { CVec3 Pos(position); - TGraph::TNodeNeighbors& neighbors = mGraph.get_node_neighbors(NodeHandle); + TGraph::TNodeNeighbors &neighbors = mGraph.get_node_neighbors(NodeHandle); // Remove All Neighbors That Are Too Far //--------------------------------------- - for (int i=0; imaxDistance) - { + for (int i = 0; i < neighbors.size(); i++) { + if (mGraph.get_node(neighbors[i].mNode).mPoint.Dist(Pos) > maxDistance) { neighbors.erase_swap(i); i--; - if (neighbors.empty()) - { + if (neighbors.empty()) { return WAYPOINT_NONE; } } @@ -2659,9 +2192,8 @@ NAV::TNodeHandle NAV::ChooseRandomNeighbor(TNodeHandle NodeHandle, const vec3_t // Now, Randomly Pick From What Is Left //-------------------------------------- - if (neighbors.size()>0) - { - return (neighbors[Q_irand(0, neighbors.size()-1)].mNode); + if (neighbors.size() > 0) { + return (neighbors[Q_irand(0, neighbors.size() - 1)].mNode); } } return WAYPOINT_NONE; @@ -2670,26 +2202,22 @@ NAV::TNodeHandle NAV::ChooseRandomNeighbor(TNodeHandle NodeHandle, const vec3_t //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::ChooseClosestNeighbor(NAV::TNodeHandle NodeHandle, const vec3_t& position) -{ - if (NodeHandle!=WAYPOINT_NONE && NodeHandle>0) - { - CVec3 pos(position); - TGraph::TNodeNeighbors& neighbors = mGraph.get_node_neighbors(NodeHandle); +NAV::TNodeHandle NAV::ChooseClosestNeighbor(NAV::TNodeHandle NodeHandle, const vec3_t &position) { + if (NodeHandle != WAYPOINT_NONE && NodeHandle > 0) { + CVec3 pos(position); + TGraph::TNodeNeighbors &neighbors = mGraph.get_node_neighbors(NodeHandle); - NAV::TNodeHandle Cur = WAYPOINT_NONE; - float CurDist = 0.0f; - NAV::TNodeHandle Best = NodeHandle; - float BestDist = mGraph.get_node(Cur).mPoint.Dist2(pos); + NAV::TNodeHandle Cur = WAYPOINT_NONE; + float CurDist = 0.0f; + NAV::TNodeHandle Best = NodeHandle; + float BestDist = mGraph.get_node(Cur).mPoint.Dist2(pos); - for (int i=0; i0) - { - CVec3 pos(position); - TGraph::TNodeNeighbors& neighbors = mGraph.get_node_neighbors(NodeHandle); +NAV::TNodeHandle NAV::ChooseFarthestNeighbor(NAV::TNodeHandle NodeHandle, const vec3_t &position) { + if (NodeHandle != WAYPOINT_NONE && NodeHandle > 0) { + CVec3 pos(position); + TGraph::TNodeNeighbors &neighbors = mGraph.get_node_neighbors(NodeHandle); - NAV::TNodeHandle Cur = WAYPOINT_NONE; - float CurDist = 0.0f; - NAV::TNodeHandle Best = NodeHandle; - float BestDist = mGraph.get_node(Cur).mPoint.Dist2(pos); + NAV::TNodeHandle Cur = WAYPOINT_NONE; + float CurDist = 0.0f; + NAV::TNodeHandle Best = NodeHandle; + float BestDist = mGraph.get_node(Cur).mPoint.Dist2(pos); - for (int i=0; iCurDist) - { - Best = Cur; - BestDist = CurDist; + if (Best == WAYPOINT_NONE || BestDist > CurDist) { + Best = Cur; + BestDist = CurDist; } } return Best; @@ -2730,100 +2254,86 @@ NAV::TNodeHandle NAV::ChooseFarthestNeighbor(NAV::TNodeHandle NodeHandle, const //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -NAV::TNodeHandle NAV::ChooseFarthestNeighbor(gentity_t* actor, const vec3_t& target, float maxSafeDot) -{ - CVec3 actorPos(actor->currentOrigin); - CVec3 targetPos(target); - CVec3 actorToTgt(targetPos - actorPos); - float actorToTgtDist = actorToTgt.Norm(); +NAV::TNodeHandle NAV::ChooseFarthestNeighbor(gentity_t *actor, const vec3_t &target, float maxSafeDot) { + CVec3 actorPos(actor->currentOrigin); + CVec3 targetPos(target); + CVec3 actorToTgt(targetPos - actorPos); + float actorToTgtDist = actorToTgt.Norm(); - NAV::TNodeHandle cur = GetNearestNode(actor); + NAV::TNodeHandle cur = GetNearestNode(actor); // If Not Anywhere, Give Up //-------------------------- - if (cur==WAYPOINT_NONE) - { + if (cur == WAYPOINT_NONE) { return WAYPOINT_NONE; } // If On An Edge, Pick The Safest Of The Two Points //-------------------------------------------------- - if (cur<0) - { - CWayEdge& edge = mGraph.get_edge(abs(cur)); - if (edge.PointA().Dist2(targetPos)>edge.PointA().Dist2(actorPos)) - { + if (cur < 0) { + CWayEdge &edge = mGraph.get_edge(abs(cur)); + if (edge.PointA().Dist2(targetPos) > edge.PointA().Dist2(actorPos)) { return edge.mNodeA; } return edge.mNodeB; } - CVec3 curPos(mGraph.get_node(cur).mPoint); - CVec3 curToTgt(targetPos - curPos); - float curDist = curToTgt.SafeNorm(); -// float curDot = curToTgt.Dot(actorToTgt); - NAV::TNodeHandle best = WAYPOINT_NONE; - float bestDist = 0.0f; - TGraph::TNodeNeighbors& neighbors = mGraph.get_node_neighbors(cur); - + CVec3 curPos(mGraph.get_node(cur).mPoint); + CVec3 curToTgt(targetPos - curPos); + float curDist = curToTgt.SafeNorm(); + // float curDot = curToTgt.Dot(actorToTgt); + NAV::TNodeHandle best = WAYPOINT_NONE; + float bestDist = 0.0f; + TGraph::TNodeNeighbors &neighbors = mGraph.get_node_neighbors(cur); // If The Actor's Current Point Is Valid, Initialize The Best One To That //------------------------------------------------------------------------ - if (curDist>actorToTgtDist && actorPos.Dist(curPos)>300.0f)//curDot actorToTgtDist && actorPos.Dist(curPos) > 300.0f) // curDotbestDist && curDist>actorToTgtDist)//curDot bestDist && curDist > actorToTgtDist) // curDots.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { - if (mPathUsers.full()) - { - assert("NAV: No more unused path users, possibly change MAX_PATH_USERS"==0); + if (pathUserNum == NULL_PATH_USER_INDEX) { + if (mPathUsers.full()) { + assert("NAV: No more unused path users, possibly change MAX_PATH_USERS" == 0); return false; } pathUserNum = mPathUsers.alloc(); - mPathUsers[pathUserNum].mEnd = WAYPOINT_NONE; - mPathUsers[pathUserNum].mSuccess = false; - mPathUsers[pathUserNum].mLastAStarTime = 0; - mPathUserIndex[actor->s.number] = pathUserNum; + mPathUsers[pathUserNum].mEnd = WAYPOINT_NONE; + mPathUsers[pathUserNum].mSuccess = false; + mPathUsers[pathUserNum].mLastAStarTime = 0; + mPathUserIndex[actor->s.number] = pathUserNum; } - SPathUser& puser = mPathUsers[pathUserNum]; + SPathUser &puser = mPathUsers[pathUserNum]; puser.mLastUseTime = level.time; - // Now, Check To See If He Already Has Found A Path To This Target //----------------------------------------------------------------- - if (puser.mEnd==target && level.time0 && !mRegion.has_valid_edge(mSearch.mStart, mSearch.mEnd, mUser)) - { + if (mRegion.size() > 0 && !mRegion.has_valid_edge(mSearch.mStart, mSearch.mEnd, mUser)) { puser.mSuccess = false; return puser.mSuccess; } - - // Now, Run A* //------------- - if (actor->enemy && actor->enemy->client) - { - if (actor->enemy->client->ps.weapon==WP_SABER) - { + if (actor->enemy && actor->enemy->client) { + if (actor->enemy->client->ps.weapon == WP_SABER) { mUser.SetDangerSpot(actor->enemy->currentOrigin, 200.0f); - } - else if ( - actor->enemy->client->NPC_class==CLASS_RANCOR || - actor->enemy->client->NPC_class==CLASS_WAMPA) - { + } else if (actor->enemy->client->NPC_class == CLASS_RANCOR || actor->enemy->client->NPC_class == CLASS_WAMPA) { mUser.SetDangerSpot(actor->enemy->currentOrigin, 400.0f); } } @@ -2895,30 +2389,22 @@ bool NAV::FindPath(gentity_t* actor, NAV::TNodeHandle target, float MaxDangerLev puser.mLastAStarTime = level.time + Q_irand(3000, 6000); puser.mSuccess = mSearch.success(); - if (!puser.mSuccess) - { + if (!puser.mSuccess) { return puser.mSuccess; } - // Grab A Couple "Current Conditions" //------------------------------------ - CVec3 At(actor->currentOrigin); - float AtTime = level.time; - float AtSpeed = actor->NPC->stats.runSpeed; - if (!(actor->NPC->scriptFlags&SCF_RUNNING) && - ((actor->NPC->scriptFlags&SCF_WALKING) || - (actor->NPC->aiFlags&NPCAI_WALKING) || - (ucmd.buttons&BUTTON_WALKING) - )) - { - AtSpeed = actor->NPC->stats.walkSpeed; + CVec3 At(actor->currentOrigin); + float AtTime = level.time; + float AtSpeed = actor->NPC->stats.runSpeed; + if (!(actor->NPC->scriptFlags & SCF_RUNNING) && + ((actor->NPC->scriptFlags & SCF_WALKING) || (actor->NPC->aiFlags & NPCAI_WALKING) || (ucmd.buttons & BUTTON_WALKING))) { + AtSpeed = actor->NPC->stats.walkSpeed; } - AtSpeed *= 0.001f; // Convert units/sec to units/millisec for comparison against level.time - AtSpeed *= 0.25; // Cut the speed in half to account for accel & decel & some slop - - + AtSpeed *= 0.001f; // Convert units/sec to units/millisec for comparison against level.time + AtSpeed *= 0.25; // Cut the speed in half to account for accel & decel & some slop // Get The Size Of This Actor //---------------------------- @@ -2926,242 +2412,203 @@ bool NAV::FindPath(gentity_t* actor, NAV::TNodeHandle target, float MaxDangerLev float maxRadius = Max(actor->maxs[0], actor->maxs[1]); float radius = Max(fabsf(minRadius), maxRadius); - if (radius>20.0f) - { + if (radius > 20.0f) { radius = 20.0f; } - // Copy The Search Results Into The Path //--------------------------------------- { SPathPoint PPoint = {}; puser.mPath.clear(); - for (mSearch.path_begin(); !mSearch.path_end() && !puser.mPath.full(); mSearch.path_inc()) - { - if (puser.mPath.full()) - { + for (mSearch.path_begin(); !mSearch.path_end() && !puser.mPath.full(); mSearch.path_inc()) { + if (puser.mPath.full()) { // NAV_TODO: If the path is longer than the max length, we want to store the first valid ones, instead of returning false - assert("This Is A Test To See If We Hit This Condition Anymore... It Should Be Handled Properly"==0); + assert("This Is A Test To See If We Hit This Condition Anymore... It Should Be Handled Properly" == 0); mPathUsers.free(pathUserNum); - mPathUserIndex[actor->s.number] = NULL_PATH_USER_INDEX; + mPathUserIndex[actor->s.number] = NULL_PATH_USER_INDEX; return false; } - PPoint.mNode = mSearch.path_at(); - PPoint.mPoint = mGraph.get_node(PPoint.mNode).mPoint; - PPoint.mSpeed = AtSpeed; - PPoint.mSlowingRadius = 0.0f; - PPoint.mReachedRadius = Max(radius*3.0f, (mGraph.get_node(PPoint.mNode).mRadius * 0.40f)); - if (mGraph.get_node(PPoint.mNode).mFlags.get_bit(CWayNode::WN_FLOATING)) - { - PPoint.mReachedRadius = 20.0f; + PPoint.mNode = mSearch.path_at(); + PPoint.mPoint = mGraph.get_node(PPoint.mNode).mPoint; + PPoint.mSpeed = AtSpeed; + PPoint.mSlowingRadius = 0.0f; + PPoint.mReachedRadius = Max(radius * 3.0f, (mGraph.get_node(PPoint.mNode).mRadius * 0.40f)); + if (mGraph.get_node(PPoint.mNode).mFlags.get_bit(CWayNode::WN_FLOATING)) { + PPoint.mReachedRadius = 20.0f; } - PPoint.mReachedRadius *= PPoint.mReachedRadius; // squared, for faster checks later - PPoint.mDist = 0.0f; - PPoint.mETA = 0.0f; + PPoint.mReachedRadius *= PPoint.mReachedRadius; // squared, for faster checks later + PPoint.mDist = 0.0f; + PPoint.mETA = 0.0f; puser.mPath.push_back(PPoint); } - assert(puser.mPath.size()>0); - + assert(puser.mPath.size() > 0); // Last Point On The Path Always Gets A Slowing Radius //----------------------------------------------------- - puser.mPath[0].mSlowingRadius = Max(70.0f, (mGraph.get_node(PPoint.mNode).mRadius * 0.75f)); - puser.mPath[0].mReachedRadius = Max(radius, (mGraph.get_node(PPoint.mNode).mRadius * 0.15f)); - puser.mPath[0].mReachedRadius *= puser.mPath[0].mReachedRadius; // squared, for faster checks later + puser.mPath[0].mSlowingRadius = Max(70.0f, (mGraph.get_node(PPoint.mNode).mRadius * 0.75f)); + puser.mPath[0].mReachedRadius = Max(radius, (mGraph.get_node(PPoint.mNode).mRadius * 0.15f)); + puser.mPath[0].mReachedRadius *= puser.mPath[0].mReachedRadius; // squared, for faster checks later } - int numEdges = (puser.mPath.size()-1); - + int numEdges = (puser.mPath.size() - 1); // Trim Out Backtracking Edges //----------------------------- - for (int edge=0; edge0.1f && AtOnEdgeScale<0.9f) - { - if (AtDistToEdge<(radius) || (AtDistToEdge<(radius*20.0f) && MoveTrace(At, AtOnEdge, actor->mins, actor->maxs, actor->s.number, true, true, false))) - { - puser.mPath.resize(edge+2); // +2 because every edge needs at least 2 points - puser.mPath[edge+1].mPoint = AtOnEdge; + for (int edge = 0; edge < numEdges; edge++) { + CVec3 PointA(puser.mPath[edge].mPoint); + CVec3 PointB(puser.mPath[edge + 1].mPoint); + + CVec3 AtOnEdge(At); + float AtOnEdgeScale = AtOnEdge.ProjectToLineSeg(PointA, PointB); + float AtDistToEdge = AtOnEdge.Dist(At); + + if (AtOnEdgeScale > 0.1f && AtOnEdgeScale < 0.9f) { + if (AtDistToEdge < (radius) || + (AtDistToEdge < (radius * 20.0f) && MoveTrace(At, AtOnEdge, actor->mins, actor->maxs, actor->s.number, true, true, false))) { + puser.mPath.resize(edge + 2); // +2 because every edge needs at least 2 points + puser.mPath[edge + 1].mPoint = AtOnEdge; break; } } } - - // For All Points On The Path, Compute ETA, And Check For Sharp Corners //---------------------------------------------------------------------- - CVec3 AtToNext; - CVec3 NextToBeyond; - float NextToBeyondDistance; - float NextToBeyondDot; + CVec3 AtToNext; + CVec3 NextToBeyond; + float NextToBeyondDistance; + float NextToBeyondDot; - for (int i=puser.mPath.size()-1; i>-1; i--) - { - SPathPoint& PPoint = puser.mPath[i]; // For Debugging And A Tad Speed Improvement, Get A Ref Directly + for (int i = puser.mPath.size() - 1; i > -1; i--) { + SPathPoint &PPoint = puser.mPath[i]; // For Debugging And A Tad Speed Improvement, Get A Ref Directly - AtToNext = (PPoint.mPoint - At); - if (fabsf(AtToNext[2])>Z_CULL_OFFSET) - { + AtToNext = (PPoint.mPoint - At); + if (fabsf(AtToNext[2]) > Z_CULL_OFFSET) { AtToNext[2] = 0.0f; } - PPoint.mDist = AtToNext.Norm(); // Get The Distance And Norm The Direction - PPoint.mETA = (PPoint.mDist / PPoint.mSpeed); // Estimate Our Eta By Distance/Speed - PPoint.mETA += AtTime; - + PPoint.mDist = AtToNext.Norm(); // Get The Distance And Norm The Direction + PPoint.mETA = (PPoint.mDist / PPoint.mSpeed); // Estimate Our Eta By Distance/Speed + PPoint.mETA += AtTime; // Check To See If This Is The Apex Of A Sharp Turn //-------------------------------------------------- - if (i!=0 && //is there a next point? - !mGraph.get_node(PPoint.mNode).mFlags.get_bit(CWayNode::WN_FLOATING) - ) - { - NextToBeyond = (puser.mPath[i-1].mPoint - PPoint.mPoint); - if (fabsf(NextToBeyond[2])>Z_CULL_OFFSET) - { + if (i != 0 && // is there a next point? + !mGraph.get_node(PPoint.mNode).mFlags.get_bit(CWayNode::WN_FLOATING)) { + NextToBeyond = (puser.mPath[i - 1].mPoint - PPoint.mPoint); + if (fabsf(NextToBeyond[2]) > Z_CULL_OFFSET) { NextToBeyond[2] = 0.0f; } NextToBeyondDistance = NextToBeyond.Norm(); NextToBeyondDot = NextToBeyond.Dot(AtToNext); - if ((NextToBeyondDistance>150.0f && PPoint.mDist>150.0f && NextToBeyondDot<0.64f) || - (NextToBeyondDistance>30.0f && NextToBeyondDot<0.5f)) - { - PPoint.mSlowingRadius = Max(40.0f, mGraph.get_node(PPoint.mNode).mRadius); // Force A Stop Here + if ((NextToBeyondDistance > 150.0f && PPoint.mDist > 150.0f && NextToBeyondDot < 0.64f) || + (NextToBeyondDistance > 30.0f && NextToBeyondDot < 0.5f)) { + PPoint.mSlowingRadius = Max(40.0f, mGraph.get_node(PPoint.mNode).mRadius); // Force A Stop Here } } // Update Our Time And Location For The Next Point //------------------------------------------------- - AtTime = PPoint.mETA; - At = PPoint.mPoint; + AtTime = PPoint.mETA; + At = PPoint.mPoint; } // Failed To Find An Acceptibly Safe Path //---------------------------------------- - if (MaxDangerLevel!=1.0f && NAV::PathDangerLevel(NPC)>MaxDangerLevel) - { + if (MaxDangerLevel != 1.0f && NAV::PathDangerLevel(NPC) > MaxDangerLevel) { puser.mSuccess = false; } - - assert(puser.mPath.size()>0); + assert(puser.mPath.size() > 0); return puser.mSuccess; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::SafePathExists(const CVec3& startVec, const CVec3& stopVec, const CVec3& danger, float dangerDistSq) -{ +bool NAV::SafePathExists(const CVec3 &startVec, const CVec3 &stopVec, const CVec3 &danger, float dangerDistSq) { mUser.ClearActor(); - // If Either Start Or End Is Invalid, We Can't Do Any Pathing //------------------------------------------------------------ - NAV::TNodeHandle target = GetNearestNode(stopVec.v, 0, 0, 0, true); - if (target==WAYPOINT_NONE) - { + NAV::TNodeHandle target = GetNearestNode(stopVec.v, 0, 0, 0, true); + if (target == WAYPOINT_NONE) { return false; } - NAV::TNodeHandle start = GetNearestNode(startVec.v, 0, target, 0, true); - if (start==WAYPOINT_NONE) - { + NAV::TNodeHandle start = GetNearestNode(startVec.v, 0, target, 0, true); + if (start == WAYPOINT_NONE) { return false; } // Convert Edges To Points //------------------------ - if (start<0) - { + if (start < 0) { start = mGraph.get_edge(abs(start)).mNodeA; } - if (target<0) - { + if (target < 0) { target = mGraph.get_edge(abs(target)).mNodeA; } - if (start==target) - { + if (start == target) { return true; } - // First Step: Find The Actor And Make Sure He Has A Path User Struct //-------------------------------------------------------------------- - SPathUser& puser = mPathUserMaster; + SPathUser &puser = mPathUserMaster; puser.mLastUseTime = level.time; - // Now, Check To See If He Already Has Found A Path To This Target //----------------------------------------------------------------- - if (puser.mEnd==target && level.time0 && !mRegion.has_valid_edge(mSearch.mStart, mSearch.mEnd, mUser)) - { + if (mRegion.size() > 0 && !mRegion.has_valid_edge(mSearch.mStart, mSearch.mEnd, mUser)) { puser.mSuccess = false; return puser.mSuccess; } // Now, Run A* //------------- -// mUser.SetDangerSpot(danger, dangerDistSq); + // mUser.SetDangerSpot(danger, dangerDistSq); mGraph.astar(mSearch, mUser); -// mUser.ClearDangerSpot(); + // mUser.ClearDangerSpot(); - puser.mLastAStarTime = level.time + Q_irand(3000, 6000);; + puser.mLastAStarTime = level.time + Q_irand(3000, 6000); + ; puser.mSuccess = mSearch.success(); - if (!puser.mSuccess) - { + if (!puser.mSuccess) { return puser.mSuccess; } - // Failed To Find An Acceptibly Safe Path //---------------------------------------- - CVec3 Prev(stopVec); - CVec3 Next; - for (mSearch.path_begin(); !mSearch.path_end(); mSearch.path_inc()) - { + CVec3 Prev(stopVec); + CVec3 Next; + for (mSearch.path_begin(); !mSearch.path_end(); mSearch.path_inc()) { Next = mGraph.get_node(mSearch.path_at()).mPoint; - if (dangerDistSq > danger.DistToLine2(Next, Prev)) - { + if (dangerDistSq > danger.DistToLine2(Next, Prev)) { puser.mSuccess = false; break; } Prev = Next; } - if (puser.mSuccess) - { + if (puser.mSuccess) { Next = startVec; - if (dangerDistSq > danger.DistToLine2(Prev, Next)) - { + if (dangerDistSq > danger.DistToLine2(Prev, Next)) { puser.mSuccess = false; } } @@ -3169,17 +2616,12 @@ bool NAV::SafePathExists(const CVec3& startVec, const CVec3& stopVec, const CV return puser.mSuccess; } - - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float NAV::EstimateCostToGoal(const vec3_t& position, TNodeHandle Goal) -{ - if (Goal!=0 && Goal!=WAYPOINT_NONE) - { - return (Distance(position, GetNodePosition(Goal))); +float NAV::EstimateCostToGoal(const vec3_t &position, TNodeHandle Goal) { + if (Goal != 0 && Goal != WAYPOINT_NONE) { + return (Distance(position, GetNodePosition(Goal))); } return 0.0f; } @@ -3187,11 +2629,9 @@ float NAV::EstimateCostToGoal(const vec3_t& position, TNodeHandle Goal) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float NAV::EstimateCostToGoal(TNodeHandle Start, TNodeHandle Goal) -{ +float NAV::EstimateCostToGoal(TNodeHandle Start, TNodeHandle Goal) { mUser.ClearActor(); - if (Goal!=0 && Goal!=WAYPOINT_NONE && Start!=0 && Start!=WAYPOINT_NONE) - { + if (Goal != 0 && Goal != WAYPOINT_NONE && Start != 0 && Start != WAYPOINT_NONE) { return (Distance(GetNodePosition(Start), GetNodePosition(Goal))); } return 0.0f; @@ -3200,36 +2640,27 @@ float NAV::EstimateCostToGoal(TNodeHandle Start, TNodeHandle Goal) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::OnSamePoint(gentity_t* actor, gentity_t* target) -{ - return (GetNearestNode(actor)==GetNearestNode(target)); -} +bool NAV::OnSamePoint(gentity_t *actor, gentity_t *target) { return (GetNearestNode(actor) == GetNearestNode(target)); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::InSameRegion(gentity_t* actor, gentity_t* target) -{ +bool NAV::InSameRegion(gentity_t *actor, gentity_t *target) { mUser.ClearActor(); - if (mRegion.size()>0) - { - NAV::TNodeHandle actNode = GetNearestNode(actor); - NAV::TNodeHandle tgtNode = GetNearestNode(target); - if (actNode==WAYPOINT_NONE || tgtNode==WAYPOINT_NONE) - { + if (mRegion.size() > 0) { + NAV::TNodeHandle actNode = GetNearestNode(actor); + NAV::TNodeHandle tgtNode = GetNearestNode(target); + if (actNode == WAYPOINT_NONE || tgtNode == WAYPOINT_NONE) { return false; } - if (actNode==tgtNode) - { + if (actNode == tgtNode) { return true; } - if (actNode<0) - { + if (actNode < 0) { actNode = mGraph.get_edge(abs(actNode)).mNodeA; } - if (tgtNode<0) - { + if (tgtNode < 0) { tgtNode = mGraph.get_edge(abs(tgtNode)).mNodeA; } @@ -3243,29 +2674,23 @@ bool NAV::InSameRegion(gentity_t* actor, gentity_t* target) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::InSameRegion(gentity_t* actor, const vec3_t& position) -{ +bool NAV::InSameRegion(gentity_t *actor, const vec3_t &position) { mUser.ClearActor(); - if (mRegion.size()>0) - { - NAV::TNodeHandle actNode = GetNearestNode(actor); - NAV::TNodeHandle tgtNode = GetNearestNode(position); + if (mRegion.size() > 0) { + NAV::TNodeHandle actNode = GetNearestNode(actor); + NAV::TNodeHandle tgtNode = GetNearestNode(position); - if (actNode==WAYPOINT_NONE || tgtNode==WAYPOINT_NONE) - { + if (actNode == WAYPOINT_NONE || tgtNode == WAYPOINT_NONE) { return false; } - if (actNode==tgtNode) - { + if (actNode == tgtNode) { return true; } - if (actNode<0) - { + if (actNode < 0) { actNode = mGraph.get_edge(abs(actNode)).mNodeA; } - if (tgtNode<0) - { + if (tgtNode < 0) { tgtNode = mGraph.get_edge(abs(tgtNode)).mNodeA; } @@ -3279,36 +2704,29 @@ bool NAV::InSameRegion(gentity_t* actor, const vec3_t& position) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::InSameRegion(NAV::TNodeHandle A, NAV::TNodeHandle B) -{ - if (mRegion.size()>0) - { - NAV::TNodeHandle actNode = A; - NAV::TNodeHandle tgtNode = B; +bool NAV::InSameRegion(NAV::TNodeHandle A, NAV::TNodeHandle B) { + if (mRegion.size() > 0) { + NAV::TNodeHandle actNode = A; + NAV::TNodeHandle tgtNode = B; - if (actNode==WAYPOINT_NONE || tgtNode==WAYPOINT_NONE) - { + if (actNode == WAYPOINT_NONE || tgtNode == WAYPOINT_NONE) { return false; } - if (actNode==tgtNode) - { + if (actNode == tgtNode) { return true; } - if (actNode<0) - { + if (actNode < 0) { actNode = mGraph.get_edge(abs(actNode)).mNodeA; } - if (tgtNode<0) - { + if (tgtNode < 0) { tgtNode = mGraph.get_edge(abs(tgtNode)).mNodeA; } - gentity_t* tempActor = mUser.GetActor(); + gentity_t *tempActor = mUser.GetActor(); mUser.ClearActor(); - bool hasEdge = mRegion.has_valid_edge(actNode, tgtNode, mUser); - if (tempActor) - { + bool hasEdge = mRegion.has_valid_edge(actNode, tgtNode, mUser); + if (tempActor) { mUser.SetActor(tempActor); } return hasEdge; @@ -3319,23 +2737,17 @@ bool NAV::InSameRegion(NAV::TNodeHandle A, NAV::TNodeHandle B) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::OnNeighboringPoints(TNodeHandle A, TNodeHandle B) -{ - if (A==B) - { +bool NAV::OnNeighboringPoints(TNodeHandle A, TNodeHandle B) { + if (A == B) { return true; } - if (A<=0 || B<=0) - { + if (A <= 0 || B <= 0) { return false; } int edgeNum = mGraph.get_edge_across(A, B); - if (edgeNum && - !mGraph.get_edge(edgeNum).mFlags.get_bit(CWayEdge::WE_JUMPING) && - !mGraph.get_edge(edgeNum).mFlags.get_bit(CWayEdge::WE_FLYING) && - mGraph.get_edge(edgeNum).mDistancecurrentOrigin, target->currentOrigin)currentOrigin, target->currentOrigin)) - { - return true; - } +bool NAV::OnNeighboringPoints(gentity_t *actor, gentity_t *target) { + if (OnNeighboringPoints(GetNearestNode(actor), GetNearestNode(target))) { + if (Distance(actor->currentOrigin, target->currentOrigin) < NEIGHBORING_DIST) { + // if (ViewNavTrace(actor->currentOrigin, target->currentOrigin)) + { return true; } } } return false; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::OnNeighboringPoints(gentity_t* actor, const vec3_t& position) -{ - if (OnNeighboringPoints(GetNearestNode(actor), GetNearestNode(position))) - { - if (Distance(actor->currentOrigin, position)currentOrigin, position)) - { - return true; - } +bool NAV::OnNeighboringPoints(gentity_t *actor, const vec3_t &position) { + if (OnNeighboringPoints(GetNearestNode(actor), GetNearestNode(position))) { + if (Distance(actor->currentOrigin, position) < NEIGHBORING_DIST) { + // if (ViewNavTrace(actor->currentOrigin, position)) + { return true; } } } return false; @@ -3382,81 +2783,64 @@ bool NAV::OnNeighboringPoints(gentity_t* actor, const vec3_t& position) // Is The Position (at) within the safe radius of the atNode, targetNode, or the edge // between? //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::InSafeRadius(CVec3 at, TNodeHandle atNode, TNodeHandle targetNode) -{ +bool NAV::InSafeRadius(CVec3 at, TNodeHandle atNode, TNodeHandle targetNode) { // Uh, No //-------- - if (atNode<=0) - { + if (atNode <= 0) { return false; } // If In The Radius Of Nearest Nav Point //--------------------------------------- - if (Distance(at.v, GetNodePosition(atNode))0 && atNode!=targetNode) - { + if (targetNode > 0 && atNode != targetNode) { // If In The Radius Of Target Nav Point //--------------------------------------- - if (Distance(at.v, GetNodePosition(targetNode))waypoint==WAYPOINT_NONE) - { +bool NAV::FindPath(gentity_t *actor, gentity_t *target, float MaxDangerLevel) { + assert(target != 0 && actor != 0); + if (target != 0 && actor != 0) { + if (target->waypoint == WAYPOINT_NONE) { GetNearestNode(target); } - if (target->waypoint!=WAYPOINT_NONE) - { + if (target->waypoint != WAYPOINT_NONE) { return FindPath(actor, target->waypoint, MaxDangerLevel); - } - else if (target->lastWaypoint!=WAYPOINT_NONE) - { + } else if (target->lastWaypoint != WAYPOINT_NONE) { return FindPath(actor, target->lastWaypoint, MaxDangerLevel); } } @@ -3466,52 +2850,45 @@ bool NAV::FindPath(gentity_t* actor, gentity_t* target, float MaxDangerLevel) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::FindPath(gentity_t* actor, const vec3_t& position, float MaxDangerLevel) -{ - return FindPath(actor, GetNearestNode(position), MaxDangerLevel); -} +bool NAV::FindPath(gentity_t *actor, const vec3_t &position, float MaxDangerLevel) { return FindPath(actor, GetNearestNode(position), MaxDangerLevel); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const vec3_t& NAV::NextPosition(gentity_t* actor) -{ +const vec3_t &NAV::NextPosition(gentity_t *actor) { assert(HasPath(actor)); - TPath& path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; + TPath &path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; - return (path[path.size()-1].mPoint.v); + return (path[path.size() - 1].mPoint.v); } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::NextPosition(gentity_t* actor, CVec3& Position) -{ +bool NAV::NextPosition(gentity_t *actor, CVec3 &Position) { assert(HasPath(actor)); - TPath& path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; - Position = path[path.size()-1].mPoint; + TPath &path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; + Position = path[path.size() - 1].mPoint; return true; } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::NextPosition(gentity_t* actor, CVec3& Position, float& SlowingRadius, bool& Fly, bool& Jump) -{ +bool NAV::NextPosition(gentity_t *actor, CVec3 &Position, float &SlowingRadius, bool &Fly, bool &Jump) { assert(HasPath(actor)); - TPath& path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; - SPathPoint& next = path[path.size()-1]; - CWayNode& node = mGraph.get_node(next.mNode); - int curNodeIndex = NAV::GetNearestNode(actor); - int edgeIndex = (curNodeIndex>0)?(mGraph.get_edge_across(curNodeIndex, next.mNode)):(abs(curNodeIndex)); + TPath &path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; + SPathPoint &next = path[path.size() - 1]; + CWayNode &node = mGraph.get_node(next.mNode); + int curNodeIndex = NAV::GetNearestNode(actor); + int edgeIndex = (curNodeIndex > 0) ? (mGraph.get_edge_across(curNodeIndex, next.mNode)) : (abs(curNodeIndex)); - SlowingRadius = next.mSlowingRadius; - Position = next.mPoint; - Fly = node.mFlags.get_bit(CWayNode::WN_FLOATING); + SlowingRadius = next.mSlowingRadius; + Position = next.mPoint; + Fly = node.mFlags.get_bit(CWayNode::WN_FLOATING); - if (edgeIndex) - { - Jump = mGraph.get_edge(edgeIndex).mFlags.get_bit(CWayEdge::WE_JUMPING); + if (edgeIndex) { + Jump = mGraph.get_edge(edgeIndex).mFlags.get_bit(CWayEdge::WE_JUMPING); } return true; @@ -3520,11 +2897,9 @@ bool NAV::NextPosition(gentity_t* actor, CVec3& Position, float& SlowingRadius // This function completely removes any pathfinding information related to this agent // and frees up this path user structure for someone else to use. //////////////////////////////////////////////////////////////////////////////////////// -void NAV::ClearPath(gentity_t* actor) -{ +void NAV::ClearPath(gentity_t *actor) { int pathUserNum = mPathUserIndex[actor->s.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { + if (pathUserNum == NULL_PATH_USER_INDEX) { return; } @@ -3532,93 +2907,76 @@ void NAV::ClearPath(gentity_t* actor) mPathUserIndex[actor->s.number] = NULL_PATH_USER_INDEX; } - //////////////////////////////////////////////////////////////////////////////////////// // Update Path // // Removes points that have been reached, and frees the user if no points remain. // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::UpdatePath(gentity_t* actor, TNodeHandle target, float MaxDangerLevel) -{ +bool NAV::UpdatePath(gentity_t *actor, TNodeHandle target, float MaxDangerLevel) { int pathUserNum = mPathUserIndex[actor->s.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { + if (pathUserNum == NULL_PATH_USER_INDEX) { return false; } - if (!mPathUsers[pathUserNum].mSuccess) - { + if (!mPathUsers[pathUserNum].mSuccess) { return false; } - if (!mPathUsers[pathUserNum].mPath.size()) - { + if (!mPathUsers[pathUserNum].mPath.size()) { return false; } - // Remove Any Points We Have Reached //----------------------------------- - CVec3 At(actor->currentOrigin); - TPath& path = mPathUsers[pathUserNum].mPath; - bool InReachedRadius = false; - bool ReachedAnything = false; - assert(path.size()>0); - - do - { - SPathPoint& PPoint = path[path.size()-1]; - CVec3 Dir(PPoint.mPoint - At); - if (fabsf(At[2] - PPoint.mPoint[2])currentOrigin); + TPath &path = mPathUsers[pathUserNum].mPath; + bool InReachedRadius = false; + bool ReachedAnything = false; + assert(path.size() > 0); + + do { + SPathPoint &PPoint = path[path.size() - 1]; + CVec3 Dir(PPoint.mPoint - At); + if (fabsf(At[2] - PPoint.mPoint[2]) < Z_CULL_OFFSET) { Dir[2] = 0.0f; } - InReachedRadius = (Dir.Len2()0); - + } while (InReachedRadius && path.size() > 0); // If We've Reached The End Of The Path, Return With no path! //------------------------------------------------------------ - if (path.empty()) - { + if (path.empty()) { return false; } - if (ReachedAnything) - { - if (target!=PT_NONE && mPathUsers[pathUserNum].mEnd!=target) - { + if (ReachedAnything) { + if (target != PT_NONE && mPathUsers[pathUserNum].mEnd != target) { return false; } } // If Not, Time To Double Check To See If The Path Is Still Valid //---------------------------------------------------------------- - if (path[path.size()-1].mETAMaxDangerLevel)) - { + if (path[path.size() - 1].mETA < level.time || (MaxDangerLevel != 1.0f && PathDangerLevel(NPC) > MaxDangerLevel)) { // Hmmm. Should Have Reached This Point By Now, Or Too Dangerous. Try To Recompute The Path //-------------------------------------------------------------------------------------------- - NAV::TNodeHandle target = mPathUsers[pathUserNum].mEnd; // Remember The End As Our Target - if (target==WAYPOINT_NONE) - { + NAV::TNodeHandle target = mPathUsers[pathUserNum].mEnd; // Remember The End As Our Target + if (target == WAYPOINT_NONE) { ClearPath(actor); return false; } - mPathUsers[pathUserNum].mEnd = WAYPOINT_NONE; // Clear Out The Old End - if (!FindPath(actor, target, MaxDangerLevel)) - { + mPathUsers[pathUserNum].mEnd = WAYPOINT_NONE; // Clear Out The Old End + if (!FindPath(actor, target, MaxDangerLevel)) { mPathUsers[pathUserNum].mEnd = target; return false; } return true; } - // Ok, We Have A Path, And Are On-Route //-------------------------------------- return true; @@ -3627,23 +2985,18 @@ bool NAV::UpdatePath(gentity_t* actor, TNodeHandle target, float MaxDangerLeve //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -bool NAV::HasPath(gentity_t* actor, TNodeHandle target) -{ +bool NAV::HasPath(gentity_t *actor, TNodeHandle target) { int pathUserNum = mPathUserIndex[actor->s.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { + if (pathUserNum == NULL_PATH_USER_INDEX) { return false; } - if (!mPathUsers[pathUserNum].mSuccess) - { + if (!mPathUsers[pathUserNum].mSuccess) { return false; } - if (!mPathUsers[pathUserNum].mPath.size()) - { + if (!mPathUsers[pathUserNum].mPath.size()) { return false; } - if (target!=PT_NONE && mPathUsers[pathUserNum].mEnd!=target) - { + if (target != PT_NONE && mPathUsers[pathUserNum].mEnd != target) { return false; } @@ -3653,75 +3006,58 @@ bool NAV::HasPath(gentity_t* actor, TNodeHandle target) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -float NAV::PathDangerLevel(gentity_t* actor) -{ - if (!actor) - { - assert("No Actor!!!"==0); +float NAV::PathDangerLevel(gentity_t *actor) { + if (!actor) { + assert("No Actor!!!" == 0); return 0.0f; } int pathUserNum = mPathUserIndex[actor->s.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { + if (pathUserNum == NULL_PATH_USER_INDEX) { return 0.0f; } - TPath& Path = mPathUsers[pathUserNum].mPath; + TPath &Path = mPathUsers[pathUserNum].mPath; // If it only has one point, let's say it's not dangerous //-------------------------------------------------------- - if (Path.size()<2) - { + if (Path.size() < 2) { return 0.0f; } - float DangerLevel = 0.0f; - CVec3 enemyPos; - float enemySafeDist = 0.0f; - float enemyDangerLevel = 0.0f; - TEdgeHandle curEdge = 0; - int curPathAt = Path.size()-1; - TAlertList& al = mEntityAlertList[actor->s.number]; - int alIndex = 0; - TNodeHandle prevNode = (GetNearestNode(actor)); - CVec3 prevPoint(actor->currentOrigin); - + float DangerLevel = 0.0f; + CVec3 enemyPos; + float enemySafeDist = 0.0f; + float enemyDangerLevel = 0.0f; + TEdgeHandle curEdge = 0; + int curPathAt = Path.size() - 1; + TAlertList &al = mEntityAlertList[actor->s.number]; + int alIndex = 0; + TNodeHandle prevNode = (GetNearestNode(actor)); + CVec3 prevPoint(actor->currentOrigin); // Some Special Enemies Always Cause Persistant Danger //----------------------------------------------------- - if (actor->enemy && actor->enemy->client) - { - if (actor->enemy->client->ps.weapon==WP_SABER || - actor->enemy->client->NPC_class==CLASS_RANCOR || - actor->enemy->client->NPC_class==CLASS_WAMPA) - { + if (actor->enemy && actor->enemy->client) { + if (actor->enemy->client->ps.weapon == WP_SABER || actor->enemy->client->NPC_class == CLASS_RANCOR || actor->enemy->client->NPC_class == CLASS_WAMPA) { enemyPos = (actor->enemy->currentOrigin); enemySafeDist = actor->enemy->radius * 10.0f; } } - // Go Through All Remaining Points On The Path //--------------------------------------------- - for (; curPathAt>=0; curPathAt--) - { - SPathPoint& PPoint = Path[curPathAt]; + for (; curPathAt >= 0; curPathAt--) { + SPathPoint &PPoint = Path[curPathAt]; // If Any Edges On The Path Have Been Registered As Dangerous //------------------------------------------------------------- - if (prevNode<0 || mGraph.get_edge_across(prevNode, PPoint.mNode)) - { - if (prevNode<0) - { + if (prevNode < 0 || mGraph.get_edge_across(prevNode, PPoint.mNode)) { + if (prevNode < 0) { curEdge = prevNode; - } - else - { + } else { curEdge = mGraph.get_edge_across(prevNode, PPoint.mNode); } - for (alIndex=0; alIndexDangerLevel) - { + for (alIndex = 0; alIndex < TAlertList::CAPACITY; alIndex++) { + if (al[alIndex].mHandle == curEdge && al[alIndex].mDanger > DangerLevel) { DangerLevel = al[alIndex].mDanger; } } @@ -3729,17 +3065,15 @@ float NAV::PathDangerLevel(gentity_t* actor) // Check For Enemy Position Proximity To This Next Edge (using actual Edge Locations) //------------------------------------------------------------------------------------ - if (enemySafeDist!=0.0f) - { - enemyDangerLevel = enemyPos.DistToLine(prevPoint, PPoint.mPoint)/enemySafeDist; - if (enemyDangerLevel>DangerLevel) - { + if (enemySafeDist != 0.0f) { + enemyDangerLevel = enemyPos.DistToLine(prevPoint, PPoint.mPoint) / enemySafeDist; + if (enemyDangerLevel > DangerLevel) { DangerLevel = enemyDangerLevel; } } - prevNode = PPoint.mNode; - prevPoint = PPoint.mPoint; + prevNode = PPoint.mNode; + prevPoint = PPoint.mPoint; } return DangerLevel; } @@ -3747,30 +3081,22 @@ float NAV::PathDangerLevel(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -int NAV::PathNodesRemaining(gentity_t* actor) -{ +int NAV::PathNodesRemaining(gentity_t *actor) { int pathUserNum = mPathUserIndex[actor->s.number]; - if (pathUserNum==NULL_PATH_USER_INDEX) - { + if (pathUserNum == NULL_PATH_USER_INDEX) { return false; } return mPathUsers[pathUserNum].mPath.size(); - } //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -const vec3_t& NAV::GetNodePosition(TNodeHandle NodeHandle) -{ - if (NodeHandle!=0) - { - if (NodeHandle>0) - { +const vec3_t &NAV::GetNodePosition(TNodeHandle NodeHandle) { + if (NodeHandle != 0) { + if (NodeHandle > 0) { return (mGraph.get_node(NodeHandle).mPoint.v); - } - else - { + } else { return (mGraph.get_edge(abs(NodeHandle)).PointA().v); } } @@ -3780,16 +3106,11 @@ const vec3_t& NAV::GetNodePosition(TNodeHandle NodeHandle) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void NAV::GetNodePosition(TNodeHandle NodeHandle, vec3_t& position) -{ - if (NodeHandle!=0) - { - if (NodeHandle>0) - { +void NAV::GetNodePosition(TNodeHandle NodeHandle, vec3_t &position) { + if (NodeHandle != 0) { + if (NodeHandle > 0) { VectorCopy(mGraph.get_node(NodeHandle).mPoint.v, position); - } - else - { + } else { VectorCopy(mGraph.get_edge(abs(NodeHandle)).PointA().v, position); } } @@ -3798,17 +3119,14 @@ void NAV::GetNodePosition(TNodeHandle NodeHandle, vec3_t& position) //////////////////////////////////////////////////////////////////////////////////////// // Call This function to get the size classification for a given entity //////////////////////////////////////////////////////////////////////////////////////// -unsigned int NAV::ClassifyEntSize(gentity_t* ent) -{ - if (ent) - { +unsigned int NAV::ClassifyEntSize(gentity_t *ent) { + if (ent) { float minRadius = Min(ent->mins[0], ent->mins[1]); float maxRadius = Max(ent->maxs[0], ent->maxs[1]); float radius = Max(fabsf(minRadius), maxRadius); float height = ent->maxs[2]; - if ((radius > SC_MEDIUM_RADIUS) || height > (SC_MEDIUM_HEIGHT)) - { + if ((radius > SC_MEDIUM_RADIUS) || height > (SC_MEDIUM_HEIGHT)) { return CWayEdge::WE_SIZE_LARGE; } return CWayEdge::WE_SIZE_MEDIUM; @@ -3816,83 +3134,53 @@ unsigned int NAV::ClassifyEntSize(gentity_t* ent) return 0; } - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void NAV::ShowDebugInfo(const vec3_t& PlayerPosition, int PlayerWaypoint) -{ +void NAV::ShowDebugInfo(const vec3_t &PlayerPosition, int PlayerWaypoint) { mUser.ClearActor(); - CVec3 atEnd; + CVec3 atEnd; // Show Nodes //------------ - if (NAVDEBUG_showNodes || NAVDEBUG_showCombatPoints || NAVDEBUG_showNavGoals) - { - for (TGraph::TNodes::iterator atIter=mGraph.nodes_begin(); atIter!=mGraph.nodes_end(); atIter++) - { - CWayNode& at = (*atIter); - atEnd = at.mPoint; - atEnd[2] += 30.0f; - - - if (gi.inPVS(PlayerPosition, at.mPoint.v)) - { - if (at.mType==NAV::PT_WAYNODE && NAVDEBUG_showNodes) - { - if (NAVDEBUG_showPointLines) - { - if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) - { - CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_FLOATING ); + if (NAVDEBUG_showNodes || NAVDEBUG_showCombatPoints || NAVDEBUG_showNavGoals) { + for (TGraph::TNodes::iterator atIter = mGraph.nodes_begin(); atIter != mGraph.nodes_end(); atIter++) { + CWayNode &at = (*atIter); + atEnd = at.mPoint; + atEnd[2] += 30.0f; + + if (gi.inPVS(PlayerPosition, at.mPoint.v)) { + if (at.mType == NAV::PT_WAYNODE && NAVDEBUG_showNodes) { + if (NAVDEBUG_showPointLines) { + if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) { + CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_FLOATING); + } else { + CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_NORMAL); } - else - { - CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_NORMAL ); + } else { + if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) { + CG_DrawNode(at.mPoint.v, NODE_FLOATING); + } else { + CG_DrawNode(at.mPoint.v, NODE_NORMAL); } } - else - { - if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) - { - CG_DrawNode(at.mPoint.v, NODE_FLOATING ); - } - else - { - CG_DrawNode(at.mPoint.v, NODE_NORMAL ); + if (NAVDEBUG_showRadius && at.mPoint.Dist2(PlayerPosition) < (at.mRadius * at.mRadius)) { + if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) { + CG_DrawRadius(at.mPoint.v, at.mRadius, NODE_FLOATING); + } else { + CG_DrawRadius(at.mPoint.v, at.mRadius, NODE_NORMAL); } } - if (NAVDEBUG_showRadius && at.mPoint.Dist2(PlayerPosition)<(at.mRadius*at.mRadius)) - { - if (at.mFlags.get_bit(CWayNode::WN_FLOATING)) - { - CG_DrawRadius(at.mPoint.v, at.mRadius, NODE_FLOATING ); - } - else - { - CG_DrawRadius(at.mPoint.v, at.mRadius, NODE_NORMAL ); - } - } - } - else if (at.mType==NAV::PT_COMBATNODE && NAVDEBUG_showCombatPoints) - { - if (NAVDEBUG_showPointLines) - { - CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_COMBAT ); - } - else - { + } else if (at.mType == NAV::PT_COMBATNODE && NAVDEBUG_showCombatPoints) { + if (NAVDEBUG_showPointLines) { + CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_COMBAT); + } else { CG_DrawCombatPoint(at.mPoint.v, 0); } - } - else if (at.mType==NAV::PT_GOALNODE && NAVDEBUG_showNavGoals) - { - if (NAVDEBUG_showPointLines) - { - CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_GOAL ); - } - else - { + } else if (at.mType == NAV::PT_GOALNODE && NAVDEBUG_showNavGoals) { + if (NAVDEBUG_showPointLines) { + CG_DrawEdge(at.mPoint.v, atEnd.v, EDGE_NODE_GOAL); + } else { CG_DrawNode(at.mPoint.v, NODE_NAVGOAL); } } @@ -3900,108 +3188,82 @@ void NAV::ShowDebugInfo(const vec3_t& PlayerPosition, int PlayerWaypoint) } } - // Show Edges //------------ - if (NAVDEBUG_showEdges) - { - for (TGraph::TEdges::iterator atIter=mGraph.edges_begin(); atIter!=mGraph.edges_end(); atIter++) - { - CWayEdge& at = (*atIter); - CWayNode& a = mGraph.get_node(at.mNodeA); - CWayNode& b = mGraph.get_node(at.mNodeB); - CVec3 AvePos = a.mPoint + b.mPoint; + if (NAVDEBUG_showEdges) { + for (TGraph::TEdges::iterator atIter = mGraph.edges_begin(); atIter != mGraph.edges_end(); atIter++) { + CWayEdge &at = (*atIter); + CWayNode &a = mGraph.get_node(at.mNodeA); + CWayNode &b = mGraph.get_node(at.mNodeB); + CVec3 AvePos = a.mPoint + b.mPoint; AvePos *= 0.5f; - if (AvePos.Dist2(PlayerPosition)<(500.0f*500.0f) && gi.inPVS(PlayerPosition, AvePos.v)) - { - if (mUser.is_valid(at)) - { - if (at.mFlags.get_bit(CWayEdge::WE_JUMPING)) - { + if (AvePos.Dist2(PlayerPosition) < (500.0f * 500.0f) && gi.inPVS(PlayerPosition, AvePos.v)) { + if (mUser.is_valid(at)) { + if (at.mFlags.get_bit(CWayEdge::WE_JUMPING)) { CG_DrawEdge(a.mPoint.v, b.mPoint.v, EDGE_JUMP); - } - else if (at.mFlags.get_bit(CWayEdge::WE_FLYING)) - { + } else if (at.mFlags.get_bit(CWayEdge::WE_FLYING)) { CG_DrawEdge(a.mPoint.v, b.mPoint.v, EDGE_FLY); - } - else if (at.Size()==CWayEdge::WE_SIZE_LARGE) - { + } else if (at.Size() == CWayEdge::WE_SIZE_LARGE) { CG_DrawEdge(a.mPoint.v, b.mPoint.v, EDGE_LARGE); - } - else - { + } else { CG_DrawEdge(a.mPoint.v, b.mPoint.v, EDGE_NORMAL); } - } - else - { + } else { CG_DrawEdge(a.mPoint.v, b.mPoint.v, EDGE_BLOCKED); } } } } - if (NAVDEBUG_showGrid) - { + if (NAVDEBUG_showGrid) { float x1, y1; float x2, y2; float z = 0.0f; - for (int x=0; xwaypoint!=0 || player->lastWaypoint!=0)) - { - PlayerWaypoint = (player->waypoint)?(player->waypoint):(player->lastWaypoint); - CVec3 PPos(PlayerPosition); - if (PlayerWaypoint>0) - { - CWayNode& node = mGraph.get_node(PlayerWaypoint); + if (NAVDEBUG_showNearest && player && (player->waypoint != 0 || player->lastWaypoint != 0)) { + PlayerWaypoint = (player->waypoint) ? (player->waypoint) : (player->lastWaypoint); + CVec3 PPos(PlayerPosition); + if (PlayerWaypoint > 0) { + CWayNode &node = mGraph.get_node(PlayerWaypoint); - CG_DrawEdge(PPos.v, node.mPoint.v, (player->waypoint)?(EDGE_NEARESTVALID):(EDGE_NEARESTINVALID)); - } - else - { - CWayEdge& edge = mGraph.get_edge(abs(PlayerWaypoint)); + CG_DrawEdge(PPos.v, node.mPoint.v, (player->waypoint) ? (EDGE_NEARESTVALID) : (EDGE_NEARESTINVALID)); + } else { + CWayEdge &edge = mGraph.get_edge(abs(PlayerWaypoint)); CVec3 PosOnLine(PlayerPosition); PosOnLine.ProjectToLineSeg(edge.PointA(), edge.PointB()); - CG_DrawEdge(PPos.v, PosOnLine.v, (player->waypoint)?(EDGE_NEARESTVALID):(EDGE_NEARESTINVALID)); + CG_DrawEdge(PPos.v, PosOnLine.v, (player->waypoint) ? (EDGE_NEARESTVALID) : (EDGE_NEARESTINVALID)); } } } @@ -4009,8 +3271,7 @@ void NAV::ShowDebugInfo(const vec3_t& PlayerPosition, int PlayerWaypoint) //////////////////////////////////////////////////////////////////////////////////// // Show Stats //////////////////////////////////////////////////////////////////////////////////// -void NAV::ShowStats() -{ +void NAV::ShowStats() { #if !defined(FINAL_BUILD) mGraph.ProfileSpew(); mRegion.ProfileSpew(); @@ -4025,30 +3286,19 @@ void NAV::ShowStats() mGraph.ProfilePrint(""); mGraph.ProfilePrint("MEMORY CONSUMPTION (In Bytes)"); mGraph.ProfilePrint("Cells : (%d)", (sizeof(mCells))); - mGraph.ProfilePrint("Path : (%d)", (sizeof(mPathUsers)+sizeof(mPathUserIndex))); - mGraph.ProfilePrint("Steer : (%d)", (sizeof(mSteerUsers)+sizeof(mSteerUserIndex))); + mGraph.ProfilePrint("Path : (%d)", (sizeof(mPathUsers) + sizeof(mPathUserIndex))); + mGraph.ProfilePrint("Steer : (%d)", (sizeof(mSteerUsers) + sizeof(mSteerUserIndex))); mGraph.ProfilePrint("Alerts : (%d)", (sizeof(mEntityAlertList))); - float totalBytes = ( - sizeof(mCells)+ - sizeof(mGraph)+ - sizeof(mRegion)+ - sizeof(mPathUsers)+ - sizeof(mPathUserIndex)+ - sizeof(mSteerUsers)+ - sizeof(mSteerUserIndex)+ - sizeof(mEntityAlertList)); - - mGraph.ProfilePrint("TOTAL : (KiloBytes): (%5.3f) MeggaBytes(%3.3f)", - ((float)(totalBytes)/1024.0f), - ((float)(totalBytes)/1048576.0f) - ); - mGraph.ProfilePrint(""); + float totalBytes = (sizeof(mCells) + sizeof(mGraph) + sizeof(mRegion) + sizeof(mPathUsers) + sizeof(mPathUserIndex) + sizeof(mSteerUsers) + + sizeof(mSteerUserIndex) + sizeof(mEntityAlertList)); + mGraph.ProfilePrint("TOTAL : (KiloBytes): (%5.3f) MeggaBytes(%3.3f)", ((float)(totalBytes) / 1024.0f), ((float)(totalBytes) / 1048576.0f)); + mGraph.ProfilePrint(""); mGraph.ProfilePrint("Connect Stats: Milliseconds(%d) Traces(%d)", mConnectTime, mConnectTraceCount); mGraph.ProfilePrint(""); - mGraph.ProfilePrint("Move Trace: Count(%d) PerFrame(%f)", mMoveTraceCount, (float)(mMoveTraceCount)/(float)(level.time)); - mGraph.ProfilePrint("View Trace: Count(%d) PerFrame(%f)", mViewTraceCount, (float)(mViewTraceCount)/(float)(level.time)); + mGraph.ProfilePrint("Move Trace: Count(%d) PerFrame(%f)", mMoveTraceCount, (float)(mMoveTraceCount) / (float)(level.time)); + mGraph.ProfilePrint("View Trace: Count(%d) PerFrame(%f)", mViewTraceCount, (float)(mViewTraceCount) / (float)(level.time)); #endif } @@ -4056,15 +3306,12 @@ void NAV::ShowStats() //////////////////////////////////////////////////////////////////////////////////// // TeleportTo //////////////////////////////////////////////////////////////////////////////////// -void NAV::TeleportTo(gentity_t* actor, const char* pointName) -{ - assert(actor!=0); - hstring nName(pointName); - TNameToNodeMap::iterator nameFinder= mNodeNames.find(nName); - if (nameFinder!=mNodeNames.end()) - { - if ((*nameFinder).size()>1) - { +void NAV::TeleportTo(gentity_t *actor, const char *pointName) { + assert(actor != 0); + hstring nName(pointName); + TNameToNodeMap::iterator nameFinder = mNodeNames.find(nName); + if (nameFinder != mNodeNames.end()) { + if ((*nameFinder).size() > 1) { gi.Printf("WARNING: More than one point named (%s). Going to first one./n", pointName); } TeleportPlayer(actor, mGraph.get_node((*nameFinder)[0]).mPoint.v, actor->currentAngles); @@ -4076,29 +3323,22 @@ void NAV::TeleportTo(gentity_t* actor, const char* pointName) //////////////////////////////////////////////////////////////////////////////////// // TeleportTo //////////////////////////////////////////////////////////////////////////////////// -void NAV::TeleportTo(gentity_t* actor, int pointNum) -{ - assert(actor!=0); +void NAV::TeleportTo(gentity_t *actor, int pointNum) { + assert(actor != 0); TeleportPlayer(actor, mGraph.get_node(pointNum).mPoint.v, actor->currentAngles); return; } - - - //////////////////////////////////////////////////////////////////////////////////// // Activate //////////////////////////////////////////////////////////////////////////////////// -void STEER::Activate(gentity_t* actor) -{ - assert(!Active(actor) && actor && actor->client && actor->NPC); // Can't Activate If Already Active - +void STEER::Activate(gentity_t *actor) { + assert(!Active(actor) && actor && actor->client && actor->NPC); // Can't Activate If Already Active -// PHASE I - ACTIVATE THE STEER USER FOR THIS ACTOR -//================================================== - if (mSteerUsers.full()) - { - assert("STEER: No more unused steer users, possibly change size"==0); + // PHASE I - ACTIVATE THE STEER USER FOR THIS ACTOR + //================================================== + if (mSteerUsers.full()) { + assert("STEER: No more unused steer users, possibly change size" == 0); return; } @@ -4106,29 +3346,24 @@ void STEER::Activate(gentity_t* actor) //-------------------------------- int steerUserNum = mSteerUsers.alloc(); mSteerUserIndex[actor->s.number] = steerUserNum; - SSteerUser& suser = mSteerUsers[steerUserNum]; - - -// PHASE II - Copy Data For This Actor Into The SUser -//==================================================== - suser.mPosition = actor->currentOrigin; - suser.mOrientation = actor->currentAngles; - suser.mVelocity = actor->client->ps.velocity; - suser.mSpeed = suser.mVelocity.Len(); - - suser.mBlocked = false; - - suser.mMaxSpeed = actor->NPC->stats.runSpeed; - suser.mRadius = RadiusFromBounds(actor->mins, actor->maxs); - suser.mMaxForce = 150.0f; //STEER_TODO: Get From actor Somehow - suser.mMass = 1.0f; //STEER_TODO: Get From actor Somehow - if (!(actor->NPC->scriptFlags&SCF_RUNNING) && - ((actor->NPC->scriptFlags&SCF_WALKING) || - (actor->NPC->aiFlags&NPCAI_WALKING) || - (ucmd.buttons&BUTTON_WALKING) - )) - { - suser.mMaxSpeed = actor->NPC->stats.walkSpeed; + SSteerUser &suser = mSteerUsers[steerUserNum]; + + // PHASE II - Copy Data For This Actor Into The SUser + //==================================================== + suser.mPosition = actor->currentOrigin; + suser.mOrientation = actor->currentAngles; + suser.mVelocity = actor->client->ps.velocity; + suser.mSpeed = suser.mVelocity.Len(); + + suser.mBlocked = false; + + suser.mMaxSpeed = actor->NPC->stats.runSpeed; + suser.mRadius = RadiusFromBounds(actor->mins, actor->maxs); + suser.mMaxForce = 150.0f; // STEER_TODO: Get From actor Somehow + suser.mMass = 1.0f; // STEER_TODO: Get From actor Somehow + if (!(actor->NPC->scriptFlags & SCF_RUNNING) && + ((actor->NPC->scriptFlags & SCF_WALKING) || (actor->NPC->aiFlags & NPCAI_WALKING) || (ucmd.buttons & BUTTON_WALKING))) { + suser.mMaxSpeed = actor->NPC->stats.walkSpeed; } #ifdef _DEBUG @@ -4137,54 +3372,47 @@ void STEER::Activate(gentity_t* actor) assert(suser.mVelocity.IsFinite()); #endif - // Find Our Neighbors //-------------------- suser.mNeighbors.clear(); - float RangeSize = suser.mRadius + STEER::NEIGHBOR_RANGE; + float RangeSize = suser.mRadius + STEER::NEIGHBOR_RANGE; - CVec3 Range(RangeSize, RangeSize, (actor->client->moveType==MT_FLYSWIM)?(RangeSize):(suser.mRadius*2.0f)); - CVec3 Mins(suser.mPosition - Range); - CVec3 Maxs(suser.mPosition + Range); + CVec3 Range(RangeSize, RangeSize, (actor->client->moveType == MT_FLYSWIM) ? (RangeSize) : (suser.mRadius * 2.0f)); + CVec3 Mins(suser.mPosition - Range); + CVec3 Maxs(suser.mPosition + Range); - gentity_t* EntityList[MAX_GENTITIES]; - gentity_t* neighbor = 0; + gentity_t *EntityList[MAX_GENTITIES]; + gentity_t *neighbor = 0; - int numFound = gi.EntitiesInBox(Mins.v, Maxs.v, EntityList, MAX_GENTITIES); - for (int i=0; is.number==actor->s.number || neighbor==actor->enemy || !neighbor->client || neighbor->health<=0 || !neighbor->inuse) - { + if (neighbor->s.number == actor->s.number || neighbor == actor->enemy || !neighbor->client || neighbor->health <= 0 || !neighbor->inuse) { continue; } suser.mNeighbors.push_back(neighbor); } - // Clear Out Steering, So If No STEER Operations Are Called, Net Effect Is Zero //------------------------------------------------------------------------------ suser.mSteering.Clear(); - suser.mNewtons = 0.0f; + suser.mNewtons = 0.0f; VectorClear(actor->client->ps.moveDir); - actor->client->ps.speed = 0; - - -// PHASE III - Project The Current Velocity Forward, To The Side, And Onto The Path -//================================================================================== - suser.mProjectFwd = suser.mPosition + (suser.mVelocity * 1.0f); - suser.mProjectSide = (suser.mVelocity * 0.3f); - suser.mProjectSide.Reposition(suser.mPosition, (actor->NPC->avoidSide==Side_Left)?(40.0f):(-40.0f)); + actor->client->ps.speed = 0; + // PHASE III - Project The Current Velocity Forward, To The Side, And Onto The Path + //================================================================================== + suser.mProjectFwd = suser.mPosition + (suser.mVelocity * 1.0f); + suser.mProjectSide = (suser.mVelocity * 0.3f); + suser.mProjectSide.Reposition(suser.mPosition, (actor->NPC->avoidSide == Side_Left) ? (40.0f) : (-40.0f)); // STEER_TODO: Project The Point The Path (If The character has one) //------------------------------------------------------------------- - //suser.mProjectPath = ; - + // suser.mProjectPath = ; } ////////////////////////////////////////////////////////////////////// @@ -4198,235 +3426,181 @@ void STEER::Activate(gentity_t* actor) // Finaly, the results are copied onto the entity and the steer user // struct is freed for use by another entity. ////////////////////////////////////////////////////////////////////// -void STEER::DeActivate(gentity_t* actor, usercmd_t* ucmd) -{ - assert(Active(actor) && actor && actor->client && actor->NPC); // Can't Deactivate If Never Activated - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - +void STEER::DeActivate(gentity_t *actor, usercmd_t *ucmd) { + assert(Active(actor) && actor && actor->client && actor->NPC); // Can't Deactivate If Never Activated + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; #ifdef _DEBUG assert(suser.mPosition.IsFinite()); assert(suser.mOrientation.IsFinite()); assert(suser.mSteering.IsFinite()); - assert(suser.mMass!=0.0f); + assert(suser.mMass != 0.0f); #endif - - -// PHASE I - TRUNCATE STEERING AND APPLY TO VELOCITY -//=================================================== - suser.mNewtons = suser.mSteering.Truncate(suser.mMaxForce); - if (suser.mNewtons>1E-10) - { + // PHASE I - TRUNCATE STEERING AND APPLY TO VELOCITY + //=================================================== + suser.mNewtons = suser.mSteering.Truncate(suser.mMaxForce); + if (suser.mNewtons > 1E-10) { suser.mSteering /= suser.mMass; suser.mVelocity += suser.mSteering; - suser.mSpeed = suser.mVelocity.Truncate(suser.mMaxSpeed); + suser.mSpeed = suser.mVelocity.Truncate(suser.mMaxSpeed); // DEBUG GRAPHICS //================================================================= - if (NAVDEBUG_showCollision) - { - CVec3 EndThrust(suser.mPosition+suser.mSteering); - CVec3 EndVelocity(suser.mPosition+suser.mVelocity); + if (NAVDEBUG_showCollision) { + CVec3 EndThrust(suser.mPosition + suser.mSteering); + CVec3 EndVelocity(suser.mPosition + suser.mVelocity); - CG_DrawEdge(suser.mPosition.v, EndThrust.v, EDGE_THRUST); - CG_DrawEdge(suser.mPosition.v, EndVelocity.v, EDGE_VELOCITY); + CG_DrawEdge(suser.mPosition.v, EndThrust.v, EDGE_THRUST); + CG_DrawEdge(suser.mPosition.v, EndVelocity.v, EDGE_VELOCITY); } //================================================================= } - if (suser.mSpeed<10.0f) - { + if (suser.mSpeed < 10.0f) { suser.mSpeed = 0.0f; } + // PHASE II - CONVERT VELOCITY TO MOVE DIRECTION & ANGLES + //======================================================== + if (!NPC_Jumping()) { + CVec3 MoveDir(suser.mVelocity); + CVec3 Angles(actor->NPC->lastPathAngles); - - - - - -// PHASE II - CONVERT VELOCITY TO MOVE DIRECTION & ANGLES -//======================================================== - if (!NPC_Jumping()) - { - CVec3 MoveDir(suser.mVelocity); - CVec3 Angles(actor->NPC->lastPathAngles); - - if (suser.mSpeed>0.0f && MoveDir!=CVec3::mZero) - { + if (suser.mSpeed > 0.0f && MoveDir != CVec3::mZero) { MoveDir.Norm(); - CVec3 NewAngles(suser.mVelocity); + CVec3 NewAngles(suser.mVelocity); NewAngles.VecToAng(); - Angles = NewAngles;//((Angles + NewAngles)*0.75f); + Angles = NewAngles; //((Angles + NewAngles)*0.75f); } #ifdef _DEBUG assert(MoveDir.IsFinite()); assert(Angles.IsFinite()); #endif - - -// PHASE III - ASSIGN ALL THIS DATA TO THE ACTOR ENTITY -//====================================================== + // PHASE III - ASSIGN ALL THIS DATA TO THE ACTOR ENTITY + //====================================================== actor->NPC->aiFlags |= NPCAI_NO_SLOWDOWN; - VectorCopy(MoveDir.v, - actor->client->ps.moveDir); - actor->client->ps.speed = suser.mSpeed; - - VectorCopy(Angles.v, - actor->NPC->lastPathAngles); - actor->NPC->desiredPitch = 0.0f; - actor->NPC->desiredYaw = AngleNormalize360(Angles[YAW]); + VectorCopy(MoveDir.v, actor->client->ps.moveDir); + actor->client->ps.speed = suser.mSpeed; + VectorCopy(Angles.v, actor->NPC->lastPathAngles); + actor->NPC->desiredPitch = 0.0f; + actor->NPC->desiredYaw = AngleNormalize360(Angles[YAW]); // Convert Movement To User Command //---------------------------------- - if (suser.mSpeed > 0.0f) - { - vec3_t forward, right, up; - AngleVectors(actor->currentAngles, forward, right, up); // Use Current Angles + if (suser.mSpeed > 0.0f) { + vec3_t forward, right, up; + AngleVectors(actor->currentAngles, forward, right, up); // Use Current Angles - float fDot = Com_Clamp(-127.0f, 127.0f, DotProduct(forward, MoveDir.v)*127.0f); - float rDot = Com_Clamp(-127.0f, 127.0f, DotProduct(right, MoveDir.v)*127.0f); + float fDot = Com_Clamp(-127.0f, 127.0f, DotProduct(forward, MoveDir.v) * 127.0f); + float rDot = Com_Clamp(-127.0f, 127.0f, DotProduct(right, MoveDir.v) * 127.0f); - ucmd->forwardmove = floor(fDot); - ucmd->rightmove = floor(rDot); - ucmd->upmove = 0.0f; + ucmd->forwardmove = floor(fDot); + ucmd->rightmove = floor(rDot); + ucmd->upmove = 0.0f; - if (suser.mSpeed<(actor->NPC->stats.walkSpeed + 5.0f)) - { + if (suser.mSpeed < (actor->NPC->stats.walkSpeed + 5.0f)) { ucmd->buttons |= BUTTON_WALKING; - } - else - { + } else { ucmd->buttons &= ~BUTTON_WALKING; } // Handle Fly Swim Movement //-------------------------- - if (actor->client->moveType==MT_FLYSWIM) - { - ucmd->forwardmove = 0.0f; - ucmd->rightmove = 0.0f; + if (actor->client->moveType == MT_FLYSWIM) { + ucmd->forwardmove = 0.0f; + ucmd->rightmove = 0.0f; VectorCopy(suser.mVelocity.v, actor->client->ps.velocity); } - } - else - { - ucmd->forwardmove = 0.0f; - ucmd->rightmove = 0.0f; - ucmd->upmove = 0.0f; + } else { + ucmd->forwardmove = 0.0f; + ucmd->rightmove = 0.0f; + ucmd->upmove = 0.0f; // Handle Fly Swim Movement //-------------------------- - if (actor->client->moveType==MT_FLYSWIM) - { + if (actor->client->moveType == MT_FLYSWIM) { VectorClear(actor->client->ps.velocity); } } // Slow Down If Going Backwards //------------------------------ - if (ucmd->forwardmove<0.0f) - { - client->ps.speed *= 0.75f; - suser.mSpeed *= 0.75f; + if (ucmd->forwardmove < 0.0f) { + client->ps.speed *= 0.75f; + suser.mSpeed *= 0.75f; } - -// PHASE IV - UPDATE BLOCKING INFORMATION -//======================================== - if (suser.mBlocked) - { + // PHASE IV - UPDATE BLOCKING INFORMATION + //======================================== + if (suser.mBlocked) { // If Not Previously Blocked, Record The Start Time And Any Entites Involved //--------------------------------------------------------------------------- - if (!(actor->NPC->aiFlags&NPCAI_BLOCKED)) - { - actor->NPC->aiFlags |= NPCAI_BLOCKED; - actor->NPC->blockedDebounceTime = level.time; + if (!(actor->NPC->aiFlags & NPCAI_BLOCKED)) { + actor->NPC->aiFlags |= NPCAI_BLOCKED; + actor->NPC->blockedDebounceTime = level.time; } // If Navigation Or Steering Had A Target Entity (Trying To Go To), Record That Here //----------------------------------------------------------------------------------- - actor->NPC->blockedTargetEntity = 0; - if (suser.mBlockedTgtEntity!=ENTITYNUM_NONE) - { - actor->NPC->blockedTargetEntity = &g_entities[suser.mBlockedTgtEntity]; + actor->NPC->blockedTargetEntity = 0; + if (suser.mBlockedTgtEntity != ENTITYNUM_NONE) { + actor->NPC->blockedTargetEntity = &g_entities[suser.mBlockedTgtEntity]; } VectorCopy(suser.mBlockedTgtPosition.v, actor->NPC->blockedTargetPosition); - } - else - { + } else { // Nothing Blocking, So Turn Off The Blocked Stuff If It Is There //---------------------------------------------------------------- - if (actor->NPC->aiFlags&NPCAI_BLOCKED) - { - actor->NPC->aiFlags &= ~NPCAI_BLOCKED; - actor->NPC->blockedDebounceTime = 0; - actor->NPC->blockedTargetEntity = 0; + if (actor->NPC->aiFlags & NPCAI_BLOCKED) { + actor->NPC->aiFlags &= ~NPCAI_BLOCKED; + actor->NPC->blockedDebounceTime = 0; + actor->NPC->blockedTargetEntity = 0; } } // If We've Been Blocked For More Than 2 Seconds, May Want To Take Corrective Action //----------------------------------------------------------------------------------- - if (STEER::HasBeenBlockedFor(actor, 2000)) - { - if (NAVDEBUG_showEnemyPath) - { + if (STEER::HasBeenBlockedFor(actor, 2000)) { + if (NAVDEBUG_showEnemyPath) { CG_DrawEdge(actor->currentOrigin, actor->NPC->blockedTargetPosition, EDGE_PATHBLOCKED); - if (actor->waypoint) - { - CVec3 Dumb(NAV::GetNodePosition(actor->waypoint)); + if (actor->waypoint) { + CVec3 Dumb(NAV::GetNodePosition(actor->waypoint)); CG_DrawEdge(actor->currentOrigin, Dumb.v, EDGE_BLOCKED); } } // If He Can Fly Or Jump, Try That //--------------------------------- - if ((actor->NPC->scriptFlags&SCF_NAV_CAN_FLY) || - (actor->NPC->scriptFlags&SCF_NAV_CAN_JUMP) - ) - { + if ((actor->NPC->scriptFlags & SCF_NAV_CAN_FLY) || (actor->NPC->scriptFlags & SCF_NAV_CAN_JUMP)) { // Ok, Well, How About Jumping To The Last Waypoint We Had That Was Valid //------------------------------------------------------------------------ if ((STEER::HasBeenBlockedFor(actor, 8000)) && - (!actor->waypoint || Distance(NAV::GetNodePosition(actor->waypoint), actor->currentOrigin)>150.0f) && - (actor->lastWaypoint)) - { - if (player && - (STEER::HasBeenBlockedFor(actor, 15000)) && - !gi.inPVS(player->currentOrigin, NAV::GetNodePosition(actor->lastWaypoint)) && - !gi.inPVS(player->currentOrigin, actor->currentOrigin) && - !G_CheckInSolidTeleport(NAV::GetNodePosition(actor->lastWaypoint), actor) - ) - { + (!actor->waypoint || Distance(NAV::GetNodePosition(actor->waypoint), actor->currentOrigin) > 150.0f) && (actor->lastWaypoint)) { + if (player && (STEER::HasBeenBlockedFor(actor, 15000)) && !gi.inPVS(player->currentOrigin, NAV::GetNodePosition(actor->lastWaypoint)) && + !gi.inPVS(player->currentOrigin, actor->currentOrigin) && !G_CheckInSolidTeleport(NAV::GetNodePosition(actor->lastWaypoint), actor)) { G_SetOrigin(actor, NAV::GetNodePosition(actor->lastWaypoint)); - G_SoundOnEnt( NPC, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - else - { + G_SoundOnEnt(NPC, CHAN_BODY, "sound/weapons/force/jump.wav"); + } else { NPC_TryJump(NAV::GetNodePosition(actor->lastWaypoint)); } } // First, Try Jumping Directly To Our Target Desired Location //------------------------------------------------------------ - else - { + else { // If We Had A Target Entity, Try Jumping There //---------------------------------------------- - if (NPCInfo->blockedTargetEntity) - { + if (NPCInfo->blockedTargetEntity) { NPC_TryJump(NPCInfo->blockedTargetEntity); } // Otherwise Try Jumping To The Target Position //---------------------------------------------- - else - { + else { NPC_TryJump(NPCInfo->blockedTargetPosition); } } @@ -4434,8 +3608,8 @@ void STEER::DeActivate(gentity_t* actor, usercmd_t* ucmd) } } -// PHASE V - FREE UP THE STEER USER -//=================================== + // PHASE V - FREE UP THE STEER USER + //=================================== mSteerUsers.free(mSteerUserIndex[actor->s.number]); mSteerUserIndex[actor->s.number] = NULL_STEER_USER_INDEX; } @@ -4447,67 +3621,51 @@ void STEER::DeActivate(gentity_t* actor, usercmd_t* ucmd) // already. // ////////////////////////////////////////////////////////////////////// -bool STEER::Active(gentity_t* actor) -{ - return (mSteerUserIndex[actor->s.number]!=NULL_STEER_USER_INDEX); -} +bool STEER::Active(gentity_t *actor) { return (mSteerUserIndex[actor->s.number] != NULL_STEER_USER_INDEX); } //////////////////////////////////////////////////////////////////////////////////// // SafeToGoTo - returns true if it is safe for the actor to steer toward the target // position //////////////////////////////////////////////////////////////////////////////////// -bool STEER::SafeToGoTo(gentity_t* actor, const vec3_t& targetPosition, int targetNode) -{ - int actorNode = NAV::GetNearestNode(actor, true, targetNode); - float actorToTargetDistance = Distance(actor->currentOrigin, targetPosition); - +bool STEER::SafeToGoTo(gentity_t *actor, const vec3_t &targetPosition, int targetNode) { + int actorNode = NAV::GetNearestNode(actor, true, targetNode); + float actorToTargetDistance = Distance(actor->currentOrigin, targetPosition); // Are They Close Enough To Just Go There //---------------------------------------- - if (actorToTargetDistance<110.0f && fabsf(targetPosition[2]-actor->currentOrigin[2])<50.0f) - { + if (actorToTargetDistance < 110.0f && fabsf(targetPosition[2] - actor->currentOrigin[2]) < 50.0f) { return true; } // Are They Both Within The Radius Of Their Nearest Nav Point? //------------------------------------------------------------- - if (actorToTargetDistance<500.0f) - { + if (actorToTargetDistance < 500.0f) { // Are Both Actor And Target In Safe Radius? //------------------------------------------- - if (NAV::OnNeighboringPoints(actorNode, targetNode) && - NAV::InSafeRadius(actor->currentOrigin, actorNode, targetNode) && - NAV::InSafeRadius(targetPosition, targetNode, actorNode)) - { + if (NAV::OnNeighboringPoints(actorNode, targetNode) && NAV::InSafeRadius(actor->currentOrigin, actorNode, targetNode) && + NAV::InSafeRadius(targetPosition, targetNode, actorNode)) { return true; } // If Close Enough, We May Be Able To Go Anyway, So Try A Trace //-------------------------------------------------------------- - if (actorToTargetDistance<400.0f)//250.0f) + if (actorToTargetDistance < 400.0f) // 250.0f) { - if (!TIMER_Done(actor, "SafeToGoToDURATION")) - { + if (!TIMER_Done(actor, "SafeToGoToDURATION")) { return true; } - if (TIMER_Done(actor, "SafeToGoToCHECK")) - { - TIMER_Set( actor, "SafeToGoToCHECK", 1500); // Check Every 1.5 Seconds - if (MoveTrace(actor, targetPosition, true)) - { - TIMER_Set(actor, "SafeToGoToDURATION", 2000); // Safe For 2 Seconds + if (TIMER_Done(actor, "SafeToGoToCHECK")) { + TIMER_Set(actor, "SafeToGoToCHECK", 1500); // Check Every 1.5 Seconds + if (MoveTrace(actor, targetPosition, true)) { + TIMER_Set(actor, "SafeToGoToDURATION", 2000); // Safe For 2 Seconds - if (NAVDEBUG_showCollision) - { + if (NAVDEBUG_showCollision) { CVec3 Dumb(targetPosition); CG_DrawEdge(actor->currentOrigin, Dumb.v, EDGE_WHITE_TWOSECOND); } - } - else - { - if (NAVDEBUG_showCollision) - { + } else { + if (NAVDEBUG_showCollision) { CVec3 Dumb(targetPosition); CG_DrawEdge(actor->currentOrigin, Dumb.v, EDGE_RED_TWOSECOND); } @@ -4521,12 +3679,10 @@ bool STEER::SafeToGoTo(gentity_t* actor, const vec3_t& targetPosition, int tar //////////////////////////////////////////////////////////////////////////////////// // Master Functions //////////////////////////////////////////////////////////////////////////////////// -bool STEER::GoTo(gentity_t* actor, gentity_t* target, float reachedRadius, bool avoidCollisions) -{ +bool STEER::GoTo(gentity_t *actor, gentity_t *target, float reachedRadius, bool avoidCollisions) { // Can't Steer To A Guy In The Air //--------------------------------- - if (!target) - { + if (!target) { NAV::ClearPath(actor); STEER::Stop(actor); return true; @@ -4534,8 +3690,7 @@ bool STEER::GoTo(gentity_t* actor, gentity_t* target, float reachedRadius, bo // If Within Reached Radius, Just Stop Right Here //------------------------------------------------ - if (STEER::Reached(actor, target->currentOrigin, reachedRadius, (actor->client && actor->client->moveType==MT_FLYSWIM))) - { + if (STEER::Reached(actor, target->currentOrigin, reachedRadius, (actor->client && actor->client->moveType == MT_FLYSWIM))) { NAV::ClearPath(actor); STEER::Stop(actor); return true; @@ -4545,26 +3700,21 @@ bool STEER::GoTo(gentity_t* actor, gentity_t* target, float reachedRadius, bo //--------------------------------------------------------------------------- if ( //(target->client && target->client->ps.groundEntityNum==ENTITYNUM_NONE) || - !STEER::SafeToGoTo(actor, target->currentOrigin, NAV::GetNearestNode(target)) - ) - { + !STEER::SafeToGoTo(actor, target->currentOrigin, NAV::GetNearestNode(target))) { return false; } // Ok, It Is, So Clear The Path, And Go Toward Our Target //-------------------------------------------------------- NAV::ClearPath(actor); - STEER::Persue(actor, target, reachedRadius*4.0f); - if (avoidCollisions) - { - if (STEER::AvoidCollisions(actor, actor->client->leader)!=0.0f) - { - STEER::Blocked(actor, target); // Collision Detected + STEER::Persue(actor, target, reachedRadius * 4.0f); + if (avoidCollisions) { + if (STEER::AvoidCollisions(actor, actor->client->leader) != 0.0f) { + STEER::Blocked(actor, target); // Collision Detected } } - if (NAVDEBUG_showEnemyPath) - { + if (NAVDEBUG_showEnemyPath) { CG_DrawEdge(actor->currentOrigin, target->currentOrigin, EDGE_FOLLOWPOS); } return true; @@ -4573,12 +3723,10 @@ bool STEER::GoTo(gentity_t* actor, gentity_t* target, float reachedRadius, bo //////////////////////////////////////////////////////////////////////////////////// // Master Function- GoTo //////////////////////////////////////////////////////////////////////////////////// -bool STEER::GoTo(gentity_t* actor, const vec3_t& position, float reachedRadius, bool avoidCollisions) -{ +bool STEER::GoTo(gentity_t *actor, const vec3_t &position, float reachedRadius, bool avoidCollisions) { // If Within Reached Radius, Just Stop Right Here //------------------------------------------------ - if (STEER::Reached(actor, position, reachedRadius, (actor->client && actor->client->moveType==MT_FLYSWIM))) - { + if (STEER::Reached(actor, position, reachedRadius, (actor->client && actor->client->moveType == MT_FLYSWIM))) { NAV::ClearPath(actor); STEER::Stop(actor); return true; @@ -4586,67 +3734,56 @@ bool STEER::GoTo(gentity_t* actor, const vec3_t& position, float reachedRadius // Check To See If It Is Safe To Attempt Steering Toward The Target Position //--------------------------------------------------------------------------- - if (!STEER::SafeToGoTo(actor, position, NAV::GetNearestNode(position))) - { + if (!STEER::SafeToGoTo(actor, position, NAV::GetNearestNode(position))) { return false; } // Ok, It Is, So Clear The Path, And Go Toward Our Target //-------------------------------------------------------- NAV::ClearPath(actor); - STEER::Seek(actor, position, reachedRadius*2.0f); - if (avoidCollisions) - { - if (STEER::AvoidCollisions(actor, actor->client->leader)!=0.0f) - { - STEER::Blocked(actor, position); // Collision Detected + STEER::Seek(actor, position, reachedRadius * 2.0f); + if (avoidCollisions) { + if (STEER::AvoidCollisions(actor, actor->client->leader) != 0.0f) { + STEER::Blocked(actor, position); // Collision Detected } } - if (NAVDEBUG_showEnemyPath) - { - CVec3 Dumb(position); + if (NAVDEBUG_showEnemyPath) { + CVec3 Dumb(position); CG_DrawEdge(actor->currentOrigin, Dumb.v, EDGE_FOLLOWPOS); } return true; } - //////////////////////////////////////////////////////////////////////////////////// // Blocked Recorder //////////////////////////////////////////////////////////////////////////////////// -void STEER::Blocked(gentity_t* actor, gentity_t* target) -{ +void STEER::Blocked(gentity_t *actor, gentity_t *target) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - suser.mBlocked = true; - suser.mBlockedTgtEntity = target->s.number; - suser.mBlockedTgtPosition = target->currentOrigin; + suser.mBlocked = true; + suser.mBlockedTgtEntity = target->s.number; + suser.mBlockedTgtPosition = target->currentOrigin; } //////////////////////////////////////////////////////////////////////////////////// // Blocked Recorder //////////////////////////////////////////////////////////////////////////////////// -void STEER::Blocked(gentity_t* actor, const vec3_t& target) -{ +void STEER::Blocked(gentity_t *actor, const vec3_t &target) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - suser.mBlocked = true; - suser.mBlockedTgtEntity = ENTITYNUM_NONE; - suser.mBlockedTgtPosition = target; + suser.mBlocked = true; + suser.mBlockedTgtEntity = ENTITYNUM_NONE; + suser.mBlockedTgtPosition = target; } //////////////////////////////////////////////////////////////////////////////////// // Blocked Recorder //////////////////////////////////////////////////////////////////////////////////// -bool STEER::HasBeenBlockedFor(gentity_t* actor, int duration) -{ - return ( - (actor->NPC->aiFlags&NPCAI_BLOCKED) && - (level.time - actor->NPC->blockedDebounceTime)>duration - ); +bool STEER::HasBeenBlockedFor(gentity_t *actor, int duration) { + return ((actor->NPC->aiFlags & NPCAI_BLOCKED) && (level.time - actor->NPC->blockedDebounceTime) > duration); } ////////////////////////////////////////////////////////////////////// @@ -4655,21 +3792,18 @@ bool STEER::HasBeenBlockedFor(gentity_t* actor, int duration) // Just Decelerate. // ////////////////////////////////////////////////////////////////////// -float STEER::Stop(gentity_t* actor, float weight) -{ +float STEER::Stop(gentity_t *actor, float weight) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; suser.mDesiredVelocity.Clear(); - suser.mDistance = 0.0f; - suser.mDesiredSpeed = 0.0f; - suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); + suser.mDistance = 0.0f; + suser.mDesiredSpeed = 0.0f; + suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); - if (actor->NPC->aiFlags&NPCAI_FLY) - { + if (actor->NPC->aiFlags & NPCAI_FLY) { int nearestNode = NAV::GetNearestNode(actor); - if (nearestNode>0 && !mGraph.get_node(nearestNode).mFlags.get_bit(CWayNode::WN_FLOATING)) - { + if (nearestNode > 0 && !mGraph.get_node(nearestNode).mFlags.get_bit(CWayNode::WN_FLOATING)) { actor->NPC->aiFlags &= ~NPCAI_FLY; } } @@ -4684,26 +3818,23 @@ float STEER::Stop(gentity_t* actor, float weight) ////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////// -float STEER::MatchSpeed(gentity_t* actor, float speed, float weight) -{ +float STEER::MatchSpeed(gentity_t *actor, float speed, float weight) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - suser.mDesiredVelocity = suser.mVelocity; + suser.mDesiredVelocity = suser.mVelocity; suser.mDesiredVelocity.Truncate(speed); - suser.mDistance = 0.0f; - suser.mDesiredSpeed = 0.0f; - suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); + suser.mDistance = 0.0f; + suser.mDesiredSpeed = 0.0f; + suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); #ifdef _DEBUG assert(suser.mSteering.IsFinite()); #endif return 0.0f; - } - //////////////////////////////////////////////////////////////////////////////////// // Seek // @@ -4711,39 +3842,32 @@ float STEER::MatchSpeed(gentity_t* actor, float speed, float weight) // the steering vector // //////////////////////////////////////////////////////////////////////////////////// -float STEER::Seek(gentity_t* actor, const CVec3& pos, float slowingDistance, float weight, float desiredSpeed) -{ +float STEER::Seek(gentity_t *actor, const CVec3 &pos, float slowingDistance, float weight, float desiredSpeed) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - suser.mSeekLocation = pos; - suser.mDesiredVelocity = suser.mSeekLocation - suser.mPosition; + suser.mSeekLocation = pos; + suser.mDesiredVelocity = suser.mSeekLocation - suser.mPosition; - //If The Difference In Height Is Small Enough, Just Kill It + // If The Difference In Height Is Small Enough, Just Kill It //---------------------------------------------------------- - if (fabsf(suser.mDesiredVelocity[2]) < 10.0f) - { + if (fabsf(suser.mDesiredVelocity[2]) < 10.0f) { suser.mDesiredVelocity[2] = 0.0f; } - - suser.mDistance = suser.mDesiredVelocity.SafeNorm(); - if (suser.mDistance>0.0f) - { - suser.mDesiredSpeed = (desiredSpeed!=0.0f)?(desiredSpeed):(suser.mMaxSpeed); - if (slowingDistance!=0.0f && suser.mDistance < slowingDistance) - { - suser.mDesiredSpeed *= (suser.mDistance/slowingDistance); + suser.mDistance = suser.mDesiredVelocity.SafeNorm(); + if (suser.mDistance > 0.0f) { + suser.mDesiredSpeed = (desiredSpeed != 0.0f) ? (desiredSpeed) : (suser.mMaxSpeed); + if (slowingDistance != 0.0f && suser.mDistance < slowingDistance) { + suser.mDesiredSpeed *= (suser.mDistance / slowingDistance); } - suser.mDesiredVelocity *= suser.mDesiredSpeed; - } - else - { + suser.mDesiredVelocity *= suser.mDesiredSpeed; + } else { suser.mDesiredSpeed = 0.0f; suser.mDesiredVelocity.Clear(); } - suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); + suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); #ifdef _DEBUG assert(suser.mSteering.IsFinite()); @@ -4760,18 +3884,16 @@ float STEER::Seek(gentity_t* actor, const CVec3& pos, float slowingDistance, f // from the target. // //////////////////////////////////////////////////////////////////////////////////// -float STEER::Flee(gentity_t* actor, const CVec3& pos, float weight) -{ +float STEER::Flee(gentity_t *actor, const CVec3 &pos, float weight) { assert(Active(actor)); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - - suser.mDesiredVelocity = suser.mPosition - pos; - suser.mDistance = suser.mDesiredVelocity.SafeNorm(); - suser.mDesiredSpeed = suser.mMaxSpeed; - suser.mDesiredVelocity *= suser.mDesiredSpeed; - suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); - suser.mSeekLocation = pos + suser.mDesiredVelocity; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + suser.mDesiredVelocity = suser.mPosition - pos; + suser.mDistance = suser.mDesiredVelocity.SafeNorm(); + suser.mDesiredSpeed = suser.mMaxSpeed; + suser.mDesiredVelocity *= suser.mDesiredSpeed; + suser.mSteering += ((suser.mDesiredVelocity - suser.mVelocity) * weight); + suser.mSeekLocation = pos + suser.mDesiredVelocity; #ifdef _DEBUG assert(suser.mSteering.IsFinite()); @@ -4780,28 +3902,24 @@ float STEER::Flee(gentity_t* actor, const CVec3& pos, float weight) return suser.mDistance; } - //////////////////////////////////////////////////////////////////////////////////// // Persue // // Predict the target's position and seek that. // //////////////////////////////////////////////////////////////////////////////////// -float STEER::Persue(gentity_t* actor, gentity_t* target, float slowingDistance) -{ +float STEER::Persue(gentity_t *actor, gentity_t *target, float slowingDistance) { assert(Active(actor) && target); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - CVec3 ProjectedTargetPosition(target->currentOrigin); + CVec3 ProjectedTargetPosition(target->currentOrigin); - if (target->client) - { - float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); + if (target->client) { + float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); - CVec3 TargetVelocity(target->client->ps.velocity); - float TargetSpeed = TargetVelocity.SafeNorm(); - if (TargetSpeed>0.0f) - { + CVec3 TargetVelocity(target->client->ps.velocity); + float TargetSpeed = TargetVelocity.SafeNorm(); + if (TargetSpeed > 0.0f) { TargetVelocity *= (DistToTarget + 5.0f); ProjectedTargetPosition += TargetVelocity; } @@ -4810,30 +3928,27 @@ float STEER::Persue(gentity_t* actor, gentity_t* target, float slowingDistance return Seek(actor, ProjectedTargetPosition, slowingDistance); } - //////////////////////////////////////////////////////////////////////////////////// // Persue // // Predict the target's position and seek that. // //////////////////////////////////////////////////////////////////////////////////// -float STEER::Persue(gentity_t* actor, gentity_t* target, float slowingDistance, float offsetForward, float offsetRight, float offsetUp, bool relativeToTargetFacing) -{ +float STEER::Persue(gentity_t *actor, gentity_t *target, float slowingDistance, float offsetForward, float offsetRight, float offsetUp, + bool relativeToTargetFacing) { assert(Active(actor) && target); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - CVec3 ProjectedTargetPosition(target->currentOrigin); + CVec3 ProjectedTargetPosition(target->currentOrigin); // If Target Is A Client, Take His Velocity Into Account And Project His Position //-------------------------------------------------------------------------------- - if (target->client) - { - float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); + if (target->client) { + float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); - CVec3 TargetVelocity(target->client->ps.velocity); - float TargetSpeed = TargetVelocity.SafeNorm(); - if (TargetSpeed>0.0f) - { + CVec3 TargetVelocity(target->client->ps.velocity); + float TargetSpeed = TargetVelocity.SafeNorm(); + if (TargetSpeed > 0.0f) { TargetVelocity[2] *= 0.1f; TargetVelocity *= (DistToTarget + 5.0f); ProjectedTargetPosition += TargetVelocity; @@ -4842,58 +3957,48 @@ float STEER::Persue(gentity_t* actor, gentity_t* target, float slowingDistance // Get The Direction Toward The Target //------------------------------------- - CVec3 DirectionToTarget(ProjectedTargetPosition); - DirectionToTarget -= suser.mPosition; - DirectionToTarget.SafeNorm(); - + CVec3 DirectionToTarget(ProjectedTargetPosition); + DirectionToTarget -= suser.mPosition; + DirectionToTarget.SafeNorm(); - CVec3 ProjectForward(DirectionToTarget); - CVec3 ProjectRight; - CVec3 ProjectUp; + CVec3 ProjectForward(DirectionToTarget); + CVec3 ProjectRight; + CVec3 ProjectUp; - if (relativeToTargetFacing) - { + if (relativeToTargetFacing) { AngleVectors(target->currentAngles, ProjectForward.v, ProjectRight.v, ProjectUp.v); - if (ProjectRight.Dot(DirectionToTarget)>0.0f) - { - ProjectRight *= -1.0f; // If Going In Same Direction As Target Right, Project Toward Target Left + if (ProjectRight.Dot(DirectionToTarget) > 0.0f) { + ProjectRight *= -1.0f; // If Going In Same Direction As Target Right, Project Toward Target Left } - } - else - { + } else { MakeNormalVectors(ProjectForward.v, ProjectRight.v, ProjectUp.v); } ProjectedTargetPosition.ScaleAdd(ProjectForward, offsetForward); - ProjectedTargetPosition.ScaleAdd(ProjectRight, offsetRight); - ProjectedTargetPosition.ScaleAdd(ProjectUp, offsetUp); + ProjectedTargetPosition.ScaleAdd(ProjectRight, offsetRight); + ProjectedTargetPosition.ScaleAdd(ProjectUp, offsetUp); return Seek(actor, ProjectedTargetPosition, slowingDistance); } - //////////////////////////////////////////////////////////////////////////////////// // Evade // // Predict the target's position and flee that. // //////////////////////////////////////////////////////////////////////////////////// -float STEER::Evade(gentity_t* actor, gentity_t* target) -{ +float STEER::Evade(gentity_t *actor, gentity_t *target) { assert(Active(actor) && target); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - - CVec3 ProjectedTargetPosition(target->currentOrigin); + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - if (target->client) - { - float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); + CVec3 ProjectedTargetPosition(target->currentOrigin); + if (target->client) { + float DistToTarget = ProjectedTargetPosition.Dist(suser.mPosition); - CVec3 TargetVelocity(target->client->ps.velocity); - float TargetSpeed = TargetVelocity.SafeNorm(); - if (TargetSpeed>0.0f) - { + CVec3 TargetVelocity(target->client->ps.velocity); + float TargetSpeed = TargetVelocity.SafeNorm(); + if (TargetSpeed > 0.0f) { TargetVelocity *= (DistToTarget + 5.0f); ProjectedTargetPosition += TargetVelocity; } @@ -4902,34 +4007,27 @@ float STEER::Evade(gentity_t* actor, gentity_t* target) return Flee(actor, ProjectedTargetPosition); } - //////////////////////////////////////////////////////////////////////////////////// // Separation //////////////////////////////////////////////////////////////////////////////////// -float STEER::Separation(gentity_t* actor, float Scale) -{ +float STEER::Separation(gentity_t *actor, float Scale) { assert(Active(actor) && actor); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - - if (!suser.mNeighbors.empty()) - { - for (int i=0; is.number>actor->s.number) - { - CVec3 NbrPos(suser.mNeighbors[i]->currentOrigin); - CVec3 NbrToAct(suser.mPosition - NbrPos); - float NbrToActDist = NbrToAct.Len2(); - if (NbrToActDist>1.0f) - { - NbrToActDist = (1.0f/NbrToActDist); + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + + if (!suser.mNeighbors.empty()) { + for (int i = 0; i < suser.mNeighbors.size(); i++) { + if (suser.mNeighbors[i]->s.number > actor->s.number) { + CVec3 NbrPos(suser.mNeighbors[i]->currentOrigin); + CVec3 NbrToAct(suser.mPosition - NbrPos); + float NbrToActDist = NbrToAct.Len2(); + if (NbrToActDist > 1.0f) { + NbrToActDist = (1.0f / NbrToActDist); NbrToAct *= NbrToActDist * (suser.mMaxSpeed * 10.0f) * Scale; - suser.mSteering += NbrToAct; + suser.mSteering += NbrToAct; - if (NAVDEBUG_showCollision) - { - CVec3 Prj(suser.mPosition + NbrToAct); - CG_DrawEdge(suser.mPosition.v, Prj.v, EDGE_IMPACT_POSSIBLE); // Separation + if (NAVDEBUG_showCollision) { + CVec3 Prj(suser.mPosition + NbrToAct); + CG_DrawEdge(suser.mPosition.v, Prj.v, EDGE_IMPACT_POSSIBLE); // Separation } } } @@ -4946,27 +4044,21 @@ float STEER::Separation(gentity_t* actor, float Scale) //////////////////////////////////////////////////////////////////////////////////// // Alignment //////////////////////////////////////////////////////////////////////////////////// -float STEER::Alignment(gentity_t* actor, float Scale) -{ - return 0.0f; -} +float STEER::Alignment(gentity_t *actor, float Scale) { return 0.0f; } //////////////////////////////////////////////////////////////////////////////////// // Cohesion //////////////////////////////////////////////////////////////////////////////////// -float STEER::Cohesion(gentity_t* actor, float Scale) -{ +float STEER::Cohesion(gentity_t *actor, float Scale) { assert(Active(actor) && actor); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - if (!suser.mNeighbors.empty()) - { - CVec3 AvePosition( 0.0f, 0.0f, 0.0f ); - for (int i=0; icurrentOrigin); } - AvePosition *= 1.0f/suser.mNeighbors.size(); + AvePosition *= 1.0f / suser.mNeighbors.size(); return Seek(actor, AvePosition); } return 0.0f; @@ -4975,18 +4067,14 @@ float STEER::Cohesion(gentity_t* actor, float Scale) //////////////////////////////////////////////////////////////////////////////////// // Find Nearest Leader //////////////////////////////////////////////////////////////////////////////////// -gentity_t* STEER::SelectLeader(gentity_t* actor) -{ +gentity_t *STEER::SelectLeader(gentity_t *actor) { assert(Active(actor) && actor); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - for (int i=0; is.number>actor->s.number && !Q_stricmp(suser.mNeighbors[i]->NPC_type, actor->NPC_type )) - { + for (int i = 0; i < suser.mNeighbors.size(); i++) { + if (suser.mNeighbors[i]->s.number > actor->s.number && !Q_stricmp(suser.mNeighbors[i]->NPC_type, actor->NPC_type)) { return suser.mNeighbors[i]; } - } return 0; } @@ -4994,56 +4082,46 @@ gentity_t* STEER::SelectLeader(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////// // Path - Seek to the next position on the path (or jump) //////////////////////////////////////////////////////////////////////////////////// -float STEER::Path(gentity_t* actor) -{ - if (NAV::HasPath(actor)) - { - CVec3 NextPosition; - float NextSlowingRadius; - bool Fly = false; - bool Jump = false; - - if (!NAV::NextPosition(actor, NextPosition, NextSlowingRadius, Fly, Jump)) - { - assert("STEER: Unable to obtain the next path position"==0); +float STEER::Path(gentity_t *actor) { + if (NAV::HasPath(actor)) { + CVec3 NextPosition; + float NextSlowingRadius; + bool Fly = false; + bool Jump = false; + + if (!NAV::NextPosition(actor, NextPosition, NextSlowingRadius, Fly, Jump)) { + assert("STEER: Unable to obtain the next path position" == 0); return 0.0f; } // Start Flying If Next Point Is In The Air //------------------------------------------ - if (Fly) - { + if (Fly) { actor->NPC->aiFlags |= NPCAI_FLY; } // Otherwise, If Next Point Is On The Ground, No Need To Fly Any Longer //---------------------------------------------------------------------- - else if (actor->NPC->aiFlags&NPCAI_FLY) - { + else if (actor->NPC->aiFlags & NPCAI_FLY) { actor->NPC->aiFlags &= ~NPCAI_FLY; } // Start Jumping If Next Point Is A Jump //--------------------------------------- - if (Jump) - { - if (NPC_TryJump(NextPosition.v)) - { + if (Jump) { + if (NPC_TryJump(NextPosition.v)) { actor->NPC->aiFlags |= NPCAI_JUMP; return 1.0f; } } - actor->NPC->aiFlags &=~NPCAI_JUMP; - + actor->NPC->aiFlags &= ~NPCAI_JUMP; // Preview His Path //------------------ - if (NAVDEBUG_showEnemyPath) - { - CVec3 Prev(actor->currentOrigin); - TPath& path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; - for (int i=path.size()-1; i>=0; i--) - { + if (NAVDEBUG_showEnemyPath) { + CVec3 Prev(actor->currentOrigin); + TPath &path = mPathUsers[mPathUserIndex[actor->s.number]].mPath; + for (int i = path.size() - 1; i >= 0; i--) { CG_DrawEdge(Prev.v, path[i].mPoint.v, EDGE_PATH); Prev = path[i].mPoint; } @@ -5051,10 +4129,9 @@ float STEER::Path(gentity_t* actor) // If Jump Was On, But We Reached This Point, It Must Have Failed //---------------------------------------------------------------- - if (Jump) - { + if (Jump) { Stop(actor); - return 0.0f; // We've Failed! + return 0.0f; // We've Failed! } // Otherwise, Go! @@ -5067,16 +4144,13 @@ float STEER::Path(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////// // Wander //////////////////////////////////////////////////////////////////////////////////// -float STEER::Wander(gentity_t* actor) -{ +float STEER::Wander(gentity_t *actor) { assert(Active(actor) && actor); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; CVec3 Direction(CVec3::mX); - if (suser.mSpeed>0.1f) - { + if (suser.mSpeed > 0.1f) { Direction = suser.mVelocity; Direction.VecToAng(); Direction[2] += Q_irand(-5, 5); @@ -5084,7 +4158,7 @@ float STEER::Wander(gentity_t* actor) } Direction *= 70.0f; - Seek(actor, suser.mPosition+Direction); + Seek(actor, suser.mPosition + Direction); return 0.0f; } @@ -5092,35 +4166,30 @@ float STEER::Wander(gentity_t* actor) //////////////////////////////////////////////////////////////////////////////////// // Follow A Leader Entity //////////////////////////////////////////////////////////////////////////////////// -float STEER::FollowLeader(gentity_t* actor, gentity_t* leader, float dist) -{ +float STEER::FollowLeader(gentity_t *actor, gentity_t *leader, float dist) { assert(Active(actor) && actor && leader && leader->client); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; - float LeaderSpeed = leader->resultspeed; - int TimeRemaining = (leader->followPosRecalcTime - level.time); + float LeaderSpeed = leader->resultspeed; + int TimeRemaining = (leader->followPosRecalcTime - level.time); - if (TimeRemaining<0 || (LeaderSpeed>0.0f && TimeRemaining>1000)) - { - CVec3 LeaderPosition(leader->currentOrigin); - CVec3 LeaderDirection(leader->currentAngles); + if (TimeRemaining < 0 || (LeaderSpeed > 0.0f && TimeRemaining > 1000)) { + CVec3 LeaderPosition(leader->currentOrigin); + CVec3 LeaderDirection(leader->currentAngles); LeaderDirection.pitch() = 0; LeaderDirection.AngToVec(); - if (!actor->enemy && !leader->enemy) - { + if (!actor->enemy && !leader->enemy) { LeaderDirection = (LeaderPosition - suser.mPosition); LeaderDirection.Norm(); } - CVec3 FollowPosition(LeaderDirection); - FollowPosition *= (-1.0f * (fabsf(dist)+suser.mRadius)); + CVec3 FollowPosition(LeaderDirection); + FollowPosition *= (-1.0f * (fabsf(dist) + suser.mRadius)); FollowPosition += LeaderPosition; MoveTrace(leader, FollowPosition, true); - if (mMoveTrace.fraction>0.1) - { + if (mMoveTrace.fraction > 0.1) { FollowPosition = mMoveTrace.endpos; FollowPosition += (LeaderDirection * suser.mRadius); @@ -5128,29 +4197,23 @@ float STEER::FollowLeader(gentity_t* actor, gentity_t* leader, float dist) leader->followPosWaypoint = NAV::GetNearestNode(leader->followPos, leader->waypoint, 0, leader->s.number); } - float MaxSpeed = (g_speed->value); - if (LeaderSpeed>MaxSpeed) - { + float MaxSpeed = (g_speed->value); + if (LeaderSpeed > MaxSpeed) { MaxSpeed = LeaderSpeed; } - float SpeedScale = (1.0f - (LeaderSpeed / MaxSpeed)); + float SpeedScale = (1.0f - (LeaderSpeed / MaxSpeed)); leader->followPosRecalcTime = - (level.time) + - (Q_irand(50, 500)) + - (SpeedScale * Q_irand(3000, 8000)) + - ((!actor->enemy && !leader->enemy)?(Q_irand(8000, 15000)):(0)); + (level.time) + (Q_irand(50, 500)) + (SpeedScale * Q_irand(3000, 8000)) + ((!actor->enemy && !leader->enemy) ? (Q_irand(8000, 15000)) : (0)); } - if (NAVDEBUG_showEnemyPath) - { + if (NAVDEBUG_showEnemyPath) { CG_DrawEdge(leader->currentOrigin, leader->followPos, EDGE_FOLLOWPOS); } return 0.0; } - ////////////////////////////////////////////////////////////////////// // Test For A Collision // @@ -5159,33 +4222,26 @@ float STEER::FollowLeader(gentity_t* actor, gentity_t* leader, float dist) // Returns true when a collision is detected (not safe) // ////////////////////////////////////////////////////////////////////// -bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVelocity, float ProjectSpeed, ESide Side, float weight=1.0f) -{ +bool TestCollision(gentity_t *actor, SSteerUser &suser, const CVec3 &ProjectVelocity, float ProjectSpeed, ESide Side, float weight = 1.0f) { // Test To See If The Projected Position Is Safe //----------------------------------------------- - bool Safe = (Side==Side_None)?(MoveTrace(actor, suser.mProjectFwd)):(MoveTrace(actor, suser.mProjectSide)); - if (mMoveTrace.entityNum!=ENTITYNUM_NONE && mMoveTrace.entityNum!=ENTITYNUM_WORLD) - { + bool Safe = (Side == Side_None) ? (MoveTrace(actor, suser.mProjectFwd)) : (MoveTrace(actor, suser.mProjectSide)); + if (mMoveTrace.entityNum != ENTITYNUM_NONE && mMoveTrace.entityNum != ENTITYNUM_WORLD) { // The Ignore Entity Is Safe //--------------------------- - if (mMoveTrace.entityNum==suser.mIgnoreEntity) - { + if (mMoveTrace.entityNum == suser.mIgnoreEntity) { Safe = true; } // Doors Are Always Safe //----------------------- - if (g_entities[mMoveTrace.entityNum].classname && - Q_stricmp(g_entities[mMoveTrace.entityNum].classname, "func_door")==0) - { + if (g_entities[mMoveTrace.entityNum].classname && Q_stricmp(g_entities[mMoveTrace.entityNum].classname, "func_door") == 0) { Safe = true; } // If It's Breakable And We Can Go Through It, Then That's Safe Too //------------------------------------------------------------------ - if ((actor->NPC->aiFlags&NPCAI_NAV_THROUGH_BREAKABLES) && - G_EntIsBreakable(mMoveTrace.entityNum, actor)) - { + if ((actor->NPC->aiFlags & NPCAI_NAV_THROUGH_BREAKABLES) && G_EntIsBreakable(mMoveTrace.entityNum, actor)) { Safe = true; } @@ -5195,59 +4251,51 @@ bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVel // Need These Vectors To Draw The Lines Below //-------------------------------------------- - CVec3 ContactNormal(mMoveTrace.plane.normal); - CVec3 ContactPoint( mMoveTrace.endpos); - int ContactNum = mMoveTrace.entityNum; - + CVec3 ContactNormal(mMoveTrace.plane.normal); + CVec3 ContactPoint(mMoveTrace.endpos); + int ContactNum = mMoveTrace.entityNum; - if (!Safe && Side==Side_None) - { + if (!Safe && Side == Side_None) { // Did We Hit A Client? //---------------------- - if (ContactNum!=ENTITYNUM_WORLD && ContactNum!=ENTITYNUM_NONE && g_entities[ContactNum].client!=0) - { - gentity_t* Contact = &g_entities[ContactNum]; - //bool ContactIsPlayer = (Contact->client->ps.clientNum==0); - CVec3 ContactVelocity (Contact->client->ps.velocity); - CVec3 ContactPosition (Contact->currentOrigin); - float ContactSpeed = (ContactVelocity.Len()); + if (ContactNum != ENTITYNUM_WORLD && ContactNum != ENTITYNUM_NONE && g_entities[ContactNum].client != 0) { + gentity_t *Contact = &g_entities[ContactNum]; + // bool ContactIsPlayer = (Contact->client->ps.clientNum==0); + CVec3 ContactVelocity(Contact->client->ps.velocity); + CVec3 ContactPosition(Contact->currentOrigin); + float ContactSpeed = (ContactVelocity.Len()); // If He Is Moving, We Might Be Able To Just Slow Down Some And Stay Behind Him //------------------------------------------------------------------------------ - if (ContactSpeed>0.01f) - { - if (ContactSpeed 0.01f) { + if (ContactSpeed < ProjectSpeed) { + CVec3 MyDirection(ProjectVelocity); + CVec3 ContactDirection(ContactVelocity); ContactDirection.Norm(); MyDirection.Norm(); - float DirectionSimilarity = fabsf(MyDirection.Dot(ContactDirection)); - if (DirectionSimilarity>0.5) - { + float DirectionSimilarity = fabsf(MyDirection.Dot(ContactDirection)); + if (DirectionSimilarity > 0.5) { // Match Speed //------------- - suser.mDesiredVelocity = suser.mVelocity; + suser.mDesiredVelocity = suser.mVelocity; suser.mDesiredVelocity.Truncate(ContactSpeed); - suser.mSteering += ((suser.mDesiredVelocity - ProjectVelocity) * DirectionSimilarity); - suser.mIgnoreEntity = ContactNum; // So The Side Trace Does Not Care About This Guy + suser.mSteering += ((suser.mDesiredVelocity - ProjectVelocity) * DirectionSimilarity); + suser.mIgnoreEntity = ContactNum; // So The Side Trace Does Not Care About This Guy #ifdef _DEBUG assert(suser.mSteering.IsFinite()); #endif - Safe = true; // We'll Say It's Safe For Now + Safe = true; // We'll Say It's Safe For Now } } } // Ok, He's Just Standing There... //--------------------------------- - else - { - CVec3 Next(suser.mSeekLocation); - if (NAV::HasPath(actor)) - { + else { + CVec3 Next(suser.mSeekLocation); + if (NAV::HasPath(actor)) { Next = CVec3(NAV::NextPosition(actor)); } @@ -5256,35 +4304,32 @@ bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVel // Is The Contact Standing Over Our Next Position? //------------------------------------------------- - if (Next>AbsMin && Next AbsMin && Next < AbsMax) { // Ok, Just Give Up And Stop For Now //----------------------------------- - suser.mSteering -= ProjectVelocity; - suser.mIgnoreEntity = ContactNum; + suser.mSteering -= ProjectVelocity; + suser.mIgnoreEntity = ContactNum; #ifdef _DEBUG assert(suser.mSteering.IsFinite()); #endif - Safe = true; // We say it is "Safe" because We Don't Want To Try And Steer Around + Safe = true; // We say it is "Safe" because We Don't Want To Try And Steer Around } } } // Ignore Shallow Slopes //----------------------- - if (!Safe && ContactNormal[2]>0.0f && ContactNormal[2] 0.0f && ContactNormal[2] < MIN_WALK_NORMAL) { Safe = true; } // If Still Not Safe //------------------- - if (!Safe) - { + if (!Safe) { // Normalize Projected Velocity And Dot It With The Contact Normal //----------------------------------------------------------------- - CVec3 ProjectDirection(ProjectVelocity); + CVec3 ProjectDirection(ProjectVelocity); ProjectDirection.Norm(); // Cross The Contact Normal With Z In Order To Get A Parallel Vector @@ -5293,23 +4338,19 @@ bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVel // Only Force A Particular Steering Side For A Max Of 2 Seconds, Then Retest Dot Product //--------------------------------------------------------------------------------------- - if (actor->NPC->lastAvoidSteerSide!=Side_None && actor->NPC->lastAvoidSteerSideDebouncerNPC->lastAvoidSteerSide = Side_None; - actor->NPC->lastAvoidSteerSideDebouncer = level.time + Q_irand(500, STEER::SIDE_LOCKED_TIMER); + if (actor->NPC->lastAvoidSteerSide != Side_None && actor->NPC->lastAvoidSteerSideDebouncer < level.time) { + actor->NPC->lastAvoidSteerSide = Side_None; + actor->NPC->lastAvoidSteerSideDebouncer = level.time + Q_irand(500, STEER::SIDE_LOCKED_TIMER); } // Make Sure The Normal Is Going The Same Way As The Velocity //----------------------------------------------------------- - if (((ESide)(actor->NPC->lastAvoidSteerSide)==Side_Right) || - ((ESide)(actor->NPC->lastAvoidSteerSide)==Side_None && ContactNormal.Dot(ProjectDirection)<0.0f)) - { + if (((ESide)(actor->NPC->lastAvoidSteerSide) == Side_Right) || + ((ESide)(actor->NPC->lastAvoidSteerSide) == Side_None && ContactNormal.Dot(ProjectDirection) < 0.0f)) { ContactNormal *= -1.0f; - actor->NPC->lastAvoidSteerSide = Side_Right; - } - else - { - actor->NPC->lastAvoidSteerSide = Side_Left; + actor->NPC->lastAvoidSteerSide = Side_Right; + } else { + actor->NPC->lastAvoidSteerSide = Side_Left; } ContactNormal[2] = 0.0f; @@ -5325,30 +4366,21 @@ bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVel // If It Was Safe, Reset Our Avoid Side Data //------------------------------------------- - else if (Side==Side_None) - { + else if (Side == Side_None) { actor->NPC->lastAvoidSteerSide = Side_None; } } - - - - // DEBUG GRAPHICS //================================================================= - if (NAVDEBUG_showCollision) - { - CVec3 Prj((Side==Side_None)?(suser.mProjectFwd):(suser.mProjectSide)); + if (NAVDEBUG_showCollision) { + CVec3 Prj((Side == Side_None) ? (suser.mProjectFwd) : (suser.mProjectSide)); - if (Safe) - { - CG_DrawEdge(suser.mPosition.v, Prj.v, EDGE_IMPACT_SAFE); // WHITE LINE - } - else - { - CG_DrawEdge(suser.mPosition.v, mMoveTrace.endpos, EDGE_IMPACT_POSSIBLE); // RED LINE - CG_DrawEdge(mMoveTrace.endpos, ContactPoint.v, EDGE_IMPACT_POSSIBLE); // RED LINE + if (Safe) { + CG_DrawEdge(suser.mPosition.v, Prj.v, EDGE_IMPACT_SAFE); // WHITE LINE + } else { + CG_DrawEdge(suser.mPosition.v, mMoveTrace.endpos, EDGE_IMPACT_POSSIBLE); // RED LINE + CG_DrawEdge(mMoveTrace.endpos, ContactPoint.v, EDGE_IMPACT_POSSIBLE); // RED LINE } } //================================================================= @@ -5363,76 +4395,62 @@ bool TestCollision(gentity_t* actor, SSteerUser& suser, const CVec3& ProjectVel // attempts to avoid collisions with nearby entities and architecture by thrusing // away from them. //////////////////////////////////////////////////////////////////////////////////// -float STEER::AvoidCollisions(gentity_t* actor, gentity_t* leader) -{ +float STEER::AvoidCollisions(gentity_t *actor, gentity_t *leader) { assert(Active(actor) && actor && actor->client); - SSteerUser& suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; + SSteerUser &suser = mSteerUsers[mSteerUserIndex[actor->s.number]]; suser.mIgnoreEntity = -5; - // Simulate The Results Of Any Current Steering To The Velocity //-------------------------------------------------------------- - CVec3 ProjectedSteering(suser.mSteering); - CVec3 ProjectedVelocity(suser.mVelocity); - float ProjectedSpeed = suser.mSpeed; - float Newtons; + CVec3 ProjectedSteering(suser.mSteering); + CVec3 ProjectedVelocity(suser.mVelocity); + float ProjectedSpeed = suser.mSpeed; + float Newtons; - Newtons = ProjectedSteering.Truncate(suser.mMaxForce); - if (Newtons>1E-10) - { - ProjectedSteering /= suser.mMass; - ProjectedVelocity += ProjectedSteering; - ProjectedSpeed = ProjectedVelocity.Truncate(suser.mMaxSpeed); + Newtons = ProjectedSteering.Truncate(suser.mMaxForce); + if (Newtons > 1E-10) { + ProjectedSteering /= suser.mMass; + ProjectedVelocity += ProjectedSteering; + ProjectedSpeed = ProjectedVelocity.Truncate(suser.mMaxSpeed); } - // Select An Ignore Entity //------------------------- - if (actor->NPC->behaviorState!=BS_CINEMATIC) - { - if (actor->NPC->greetEnt && actor->NPC->greetEnt->owner==NPC) - { + if (actor->NPC->behaviorState != BS_CINEMATIC) { + if (actor->NPC->greetEnt && actor->NPC->greetEnt->owner == NPC) { suser.mIgnoreEntity = actor->NPC->greetEnt->s.clientNum; - } - else if (actor->enemy) - { + } else if (actor->enemy) { suser.mIgnoreEntity = actor->enemy->s.clientNum; - } - else if (leader) - { + } else if (leader) { suser.mIgnoreEntity = leader->s.clientNum; } } - // If Moving //----------- - if (ProjectedSpeed>0.01f) - { - CVec3 ProjectVelocitySide(ProjectedVelocity); - ProjectVelocitySide.Reposition(CVec3::mZero, (actor->NPC->avoidSide==Side_Left)?(40.0f):(-40.0f)); + if (ProjectedSpeed > 0.01f) { + CVec3 ProjectVelocitySide(ProjectedVelocity); + ProjectVelocitySide.Reposition(CVec3::mZero, (actor->NPC->avoidSide == Side_Left) ? (40.0f) : (-40.0f)); // Project Based On Our ProjectedVelocity //----------------------------------------- - suser.mProjectFwd = suser.mPosition + (ProjectedVelocity * 1.0f); - suser.mProjectSide = suser.mPosition + (ProjectVelocitySide * 0.3f); + suser.mProjectFwd = suser.mPosition + (ProjectedVelocity * 1.0f); + suser.mProjectSide = suser.mPosition + (ProjectVelocitySide * 0.3f); // Test For Collisions In The Front And On The Sides //--------------------------------------------------- - bool HitFront = TestCollision(actor, suser, ProjectedVelocity, ProjectedSpeed, Side_None, 1.0f); - bool HitSide = TestCollision(actor, suser, ProjectedVelocity, ProjectedSpeed, (ESide)actor->NPC->avoidSide, 0.5f); - if (!HitSide) - { + bool HitFront = TestCollision(actor, suser, ProjectedVelocity, ProjectedSpeed, Side_None, 1.0f); + bool HitSide = TestCollision(actor, suser, ProjectedVelocity, ProjectedSpeed, (ESide)actor->NPC->avoidSide, 0.5f); + if (!HitSide) { // If The Side Is Clear, Try The Other Side //------------------------------------------ - actor->NPC->avoidSide = (actor->NPC->avoidSide==Side_Left)?(Side_Right):(Side_Left); + actor->NPC->avoidSide = (actor->NPC->avoidSide == Side_Left) ? (Side_Right) : (Side_Left); } // Hit Something! //---------------- - if (HitFront || HitSide) - { + if (HitFront || HitSide) { return ProjectedSpeed; } } @@ -5442,21 +4460,18 @@ float STEER::AvoidCollisions(gentity_t* actor, gentity_t* leader) //////////////////////////////////////////////////////////////////////////////////// // Reached //////////////////////////////////////////////////////////////////////////////////// -bool STEER::Reached(gentity_t* actor, gentity_t* target, float targetRadius, bool flying) -{ - if (!actor || !target) - { +bool STEER::Reached(gentity_t *actor, gentity_t *target, float targetRadius, bool flying) { + if (!actor || !target) { return false; } - CVec3 ActorPos(actor->currentOrigin); - CVec3 ActorMins(actor->absmin); - CVec3 ActorMaxs(actor->absmax); + CVec3 ActorPos(actor->currentOrigin); + CVec3 ActorMins(actor->absmin); + CVec3 ActorMaxs(actor->absmax); - CVec3 TargetPos(target->currentOrigin); + CVec3 TargetPos(target->currentOrigin); - if (TargetPos.Dist2(ActorPos)<(targetRadius*targetRadius) || (TargetPos>ActorMins && TargetPos ActorMins && TargetPos < ActorMaxs)) { return true; } return false; @@ -5465,21 +4480,18 @@ bool STEER::Reached(gentity_t* actor, gentity_t* target, float targetRadius, boo //////////////////////////////////////////////////////////////////////////////////// // Reached //////////////////////////////////////////////////////////////////////////////////// -bool STEER::Reached(gentity_t* actor, NAV::TNodeHandle target, float targetRadius, bool flying) -{ - if (!actor || !target) - { +bool STEER::Reached(gentity_t *actor, NAV::TNodeHandle target, float targetRadius, bool flying) { + if (!actor || !target) { return false; } - CVec3 ActorPos(actor->currentOrigin); - CVec3 ActorMins(actor->absmin); - CVec3 ActorMaxs(actor->absmax); + CVec3 ActorPos(actor->currentOrigin); + CVec3 ActorMins(actor->absmin); + CVec3 ActorMaxs(actor->absmax); - CVec3 TargetPos(NAV::GetNodePosition(target)); + CVec3 TargetPos(NAV::GetNodePosition(target)); - if (TargetPos.Dist2(ActorPos)<(targetRadius*targetRadius) || (TargetPos>ActorMins && TargetPos ActorMins && TargetPos < ActorMaxs)) { return true; } return false; @@ -5488,57 +4500,43 @@ bool STEER::Reached(gentity_t* actor, NAV::TNodeHandle target, float targetRadiu //////////////////////////////////////////////////////////////////////////////////// // Reached //////////////////////////////////////////////////////////////////////////////////// -bool STEER::Reached(gentity_t* actor, const vec3_t& target, float targetRadius, bool flying) -{ - if (!actor || VectorCompare(target, vec3_origin) ) - { +bool STEER::Reached(gentity_t *actor, const vec3_t &target, float targetRadius, bool flying) { + if (!actor || VectorCompare(target, vec3_origin)) { return false; } - CVec3 ActorPos(actor->currentOrigin); - CVec3 ActorMins(actor->absmin); - CVec3 ActorMaxs(actor->absmax); + CVec3 ActorPos(actor->currentOrigin); + CVec3 ActorMins(actor->absmin); + CVec3 ActorMaxs(actor->absmax); - CVec3 TargetPos(target); + CVec3 TargetPos(target); - if (TargetPos.Dist2(ActorPos)<(targetRadius*targetRadius) || (TargetPos>ActorMins && TargetPos ActorMins && TargetPos < ActorMaxs)) { return true; } -// if (target->client && target->client->ps.groundEntityNum == ENTITYNUM_NONE) -// { -// TargetPos -= ActorPos; -// if (fabsf(TargetPos[2]<(targetRadius*8))) -// { -// TargetPos[2] = 0.0f; -// if (TargetPos.Len2()<((targetRadius*2.0f)*(targetRadius*2.0f))) -// { -// return true; -// } -// } -// } + // if (target->client && target->client->ps.groundEntityNum == ENTITYNUM_NONE) + // { + // TargetPos -= ActorPos; + // if (fabsf(TargetPos[2]<(targetRadius*8))) + // { + // TargetPos[2] = 0.0f; + // if (TargetPos.Len2()<((targetRadius*2.0f)*(targetRadius*2.0f))) + // { + // return true; + // } + // } + // } return false; } - - // Clean up all of the krufty structures that only grow, never shrink, eventually // causing asserts and subsequent memory trashing. -void ClearAllNavStructures(void) -{ +void ClearAllNavStructures(void) { TEntEdgeMap::iterator i = mEntEdgeMap.begin(); - for ( ; i != mEntEdgeMap.end(); ++i) - { + for (; i != mEntEdgeMap.end(); ++i) { i->clear(); } mEntEdgeMap.clear(); } - - - - - - - diff --git a/code/game/g_navnew.cpp b/code/game/g_navnew.cpp index 2cd87f368b..6aecbc9a62 100644 --- a/code/game/g_navnew.cpp +++ b/code/game/g_navnew.cpp @@ -24,62 +24,54 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "b_local.h" -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean FlyingCreature(gentity_t *ent); -#define MIN_DOOR_BLOCK_DIST 16 -#define MIN_DOOR_BLOCK_DIST_SQR ( MIN_DOOR_BLOCK_DIST * MIN_DOOR_BLOCK_DIST ) +#define MIN_DOOR_BLOCK_DIST 16 +#define MIN_DOOR_BLOCK_DIST_SQR (MIN_DOOR_BLOCK_DIST * MIN_DOOR_BLOCK_DIST) /* ------------------------- NAV_HitNavGoal ------------------------- */ -qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying ) -{ - vec3_t dmins, dmaxs, pmins, pmaxs; +qboolean NAV_HitNavGoal(vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying) { + vec3_t dmins, dmaxs, pmins, pmaxs; - if ( radius ) - { - //NOTE: This needs to do a DistanceSquared on navgoals that had + if (radius) { + // NOTE: This needs to do a DistanceSquared on navgoals that had // a radius manually set! We can't do the smaller navgoals against // walls to get around this because player-sized traces to them // from angles will not work... - MCG - if ( !flying ) - {//Allow for a little z difference - vec3_t diff; - VectorSubtract( point, dest, diff ); - if ( fabs(diff[2]) <= 24 ) - { + if (!flying) { // Allow for a little z difference + vec3_t diff; + VectorSubtract(point, dest, diff); + if (fabs(diff[2]) <= 24) { diff[2] = 0; } - return (qboolean)( VectorLengthSquared( diff ) <= (radius*radius) ); - } - else - {//must hit exactly - return (qboolean)( DistanceSquared(dest, point) <= (radius*radius) ); + return (qboolean)(VectorLengthSquared(diff) <= (radius * radius)); + } else { // must hit exactly + return (qboolean)(DistanceSquared(dest, point) <= (radius * radius)); } - //There is probably a better way to do this, either by preserving the original + // There is probably a better way to do this, either by preserving the original // mins and maxs of the navgoal and doing this check ONLY if the radius // is non-zero (like the original implementation) or some boolean to // tell us to do this check rather than the fake bbox overlap check... - } - else - { - //Construct a dummy bounding box from our radius value - VectorSet( dmins, -radius, -radius, -radius ); - VectorSet( dmaxs, radius, radius, radius ); - - //Translate it - VectorAdd( dmins, dest, dmins ); - VectorAdd( dmaxs, dest, dmaxs ); - - //Translate the starting box - VectorAdd( point, mins, pmins ); - VectorAdd( point, maxs, pmaxs ); - - //See if they overlap - return G_BoundsOverlap( pmins, pmaxs, dmins, dmaxs ); + } else { + // Construct a dummy bounding box from our radius value + VectorSet(dmins, -radius, -radius, -radius); + VectorSet(dmaxs, radius, radius, radius); + + // Translate it + VectorAdd(dmins, dest, dmins); + VectorAdd(dmaxs, dest, dmaxs); + + // Translate the starting box + VectorAdd(point, mins, pmins); + VectorAdd(point, maxs, pmaxs); + + // See if they overlap + return G_BoundsOverlap(pmins, pmaxs, dmins, dmaxs); } } @@ -89,48 +81,44 @@ NAV_CheckAhead ------------------------- */ -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ) -{ - vec3_t mins; +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask) { + vec3_t mins; - //Offset the step height - VectorSet( mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE); - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, (EG2_Collision)0, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, (EG2_Collision)0, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) return qtrue; - //See if we're too far above - if ( fabs( self->currentOrigin[2] - end[2] ) > 48 ) + // See if we're too far above + if (fabs(self->currentOrigin[2] - end[2]) > 48) return qfalse; - //This is a work around - float radius = ( self->maxs[0] > self->maxs[1] ) ? self->maxs[0] : self->maxs[1]; - float dist = Distance( self->currentOrigin, end ); - float tFrac = 1.0f - ( radius / dist ); + // This is a work around + float radius = (self->maxs[0] > self->maxs[1]) ? self->maxs[0] : self->maxs[1]; + float dist = Distance(self->currentOrigin, end); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; - //Do a special check for doors - if ( trace.entityNum < ENTITYNUM_WORLD ) - { - gentity_t *blocker = &g_entities[trace.entityNum]; + // Do a special check for doors + if (trace.entityNum < ENTITYNUM_WORLD) { + gentity_t *blocker = &g_entities[trace.entityNum]; - if VALIDSTRING( blocker->classname ) - { - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + if VALIDSTRING (blocker->classname) { + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { - //We're too close, try and avoid the door (most likely stuck on a lip) - if ( DistanceSquared( self->currentOrigin, trace.endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) + // We're too close, try and avoid the door (most likely stuck on a lip) + if (DistanceSquared(self->currentOrigin, trace.endpos) < MIN_DOOR_BLOCK_DIST_SQR) return qfalse; return qtrue; @@ -147,43 +135,38 @@ NPC_ClearPathToGoal ------------------------- */ -qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal ) -{ - trace_t trace; +qboolean NPC_ClearPathToGoal(vec3_t dir, gentity_t *goal) { + trace_t trace; - //FIXME: What does do about area portals? THIS IS BROKEN - //if ( gi.inPVS( NPC->currentOrigin, goal->currentOrigin ) == qfalse ) + // FIXME: What does do about area portals? THIS IS BROKEN + // if ( gi.inPVS( NPC->currentOrigin, goal->currentOrigin ) == qfalse ) // return qfalse; - //Look ahead and see if we're clear to move to our goal position - if ( NAV_CheckAhead( NPC, goal->currentOrigin, trace, ( NPC->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - //VectorSubtract( goal->currentOrigin, NPC->currentOrigin, dir ); + // Look ahead and see if we're clear to move to our goal position + if (NAV_CheckAhead(NPC, goal->currentOrigin, trace, (NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + // VectorSubtract( goal->currentOrigin, NPC->currentOrigin, dir ); return qtrue; } - if (!FlyingCreature(NPC)) - { - //See if we're too far above - if ( fabs( NPC->currentOrigin[2] - goal->currentOrigin[2] ) > 48 ) + if (!FlyingCreature(NPC)) { + // See if we're too far above + if (fabs(NPC->currentOrigin[2] - goal->currentOrigin[2]) > 48) return qfalse; } - //This is a work around - float radius = ( NPC->maxs[0] > NPC->maxs[1] ) ? NPC->maxs[0] : NPC->maxs[1]; - float dist = Distance( NPC->currentOrigin, goal->currentOrigin ); - float tFrac = 1.0f - ( radius / dist ); + // This is a work around + float radius = (NPC->maxs[0] > NPC->maxs[1]) ? NPC->maxs[0] : NPC->maxs[1]; + float dist = Distance(NPC->currentOrigin, goal->currentOrigin); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; - //See if we're looking for a navgoal - if ( goal->svFlags & SVF_NAVGOAL ) - { - //Okay, didn't get all the way there, let's see if we got close enough: - if ( NAV_HitNavGoal( trace.endpos, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature( NPC ) ) ) - { - //VectorSubtract(goal->currentOrigin, NPC->currentOrigin, dir); + // See if we're looking for a navgoal + if (goal->svFlags & SVF_NAVGOAL) { + // Okay, didn't get all the way there, let's see if we got close enough: + if (NAV_HitNavGoal(trace.endpos, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature(NPC))) { + // VectorSubtract(goal->currentOrigin, NPC->currentOrigin, dir); return qtrue; } } @@ -191,59 +174,49 @@ qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal ) return qfalse; } -qboolean NAV_DirSafe( gentity_t *self, vec3_t dir, float dist ) -{ - vec3_t mins, end; - trace_t trace; +qboolean NAV_DirSafe(gentity_t *self, vec3_t dir, float dist) { + vec3_t mins, end; + trace_t trace; - VectorMA( self->currentOrigin, dist, dir, end ); + VectorMA(self->currentOrigin, dist, dir, end); - //Offset the step height - VectorSet( mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE); - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, CONTENTS_BOTCLIP, (EG2_Collision)0, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, CONTENTS_BOTCLIP, (EG2_Collision)0, 0); - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) - { + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) { return qtrue; } return qfalse; } -qboolean NAV_MoveDirSafe( gentity_t *self, usercmd_t *cmd, float distScale = 1.0f ) -{ - vec3_t moveDir; +qboolean NAV_MoveDirSafe(gentity_t *self, usercmd_t *cmd, float distScale = 1.0f) { + vec3_t moveDir; - if ( !self || !self->client ) - { + if (!self || !self->client) { return qtrue; } - if ( !self->client->ps.speed ) - { + if (!self->client->ps.speed) { return qtrue; } - if ( FlyingCreature( self ) ) - { + if (FlyingCreature(self)) { return qtrue; } - if ( VectorCompare( self->client->ps.moveDir, vec3_origin ) ) - {//no movedir, build from cmd - if ( !cmd->forwardmove && !cmd->rightmove ) - {//not moving at all + if (VectorCompare(self->client->ps.moveDir, vec3_origin)) { // no movedir, build from cmd + if (!cmd->forwardmove && !cmd->rightmove) { // not moving at all return qtrue; } vec3_t fwd, right, fwdAngs = {0, self->currentAngles[YAW], 0}; - AngleVectors( fwdAngs, fwd, right, NULL ); - VectorScale( fwd, cmd->forwardmove, fwd ); - VectorScale( right, cmd->rightmove, right ); - VectorAdd( fwd, right, moveDir ); - VectorNormalize( moveDir ); - } - else - { - VectorCopy( self->client->ps.moveDir, moveDir ); + AngleVectors(fwdAngs, fwd, right, NULL); + VectorScale(fwd, cmd->forwardmove, fwd); + VectorScale(right, cmd->rightmove, right); + VectorAdd(fwd, right, moveDir); + VectorNormalize(moveDir); + } else { + VectorCopy(self->client->ps.moveDir, moveDir); } - return (NAV_DirSafe( self, moveDir, (self->client->ps.speed/10.0f)*distScale )); + return (NAV_DirSafe(self, moveDir, (self->client->ps.speed / 10.0f) * distScale)); } diff --git a/code/game/g_object.cpp b/code/game/g_object.cpp index db653e5b2c..5fb903d9dd 100644 --- a/code/game/g_object.cpp +++ b/code/game/g_object.cpp @@ -24,8 +24,8 @@ along with this program; if not, see . #include "g_functions.h" #include "b_local.h" -extern void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); -void G_StopObjectMoving( gentity_t *object ); +extern void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg); +void G_StopObjectMoving(gentity_t *object); /* ================ @@ -33,37 +33,36 @@ G_BounceMissile ================ */ -void G_BounceObject( gentity_t *ent, trace_t *trace ) -{ - vec3_t velocity; - float dot; - int hitTime; +void G_BounceObject(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - float bounceFactor = 60/ent->mass; - if ( bounceFactor > 1.0f ) - { + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + float bounceFactor = 60 / ent->mass; + if (bounceFactor > 1.0f) { bounceFactor = 1.0f; } - VectorMA( velocity, -2*dot*bounceFactor, trace->plane.normal, ent->s.pos.trDelta ); + VectorMA(velocity, -2 * dot * bounceFactor, trace->plane.normal, ent->s.pos.trDelta); - //FIXME: customized or material-based impact/bounce sounds - if ( ent->s.eFlags & EF_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); + // FIXME: customized or material-based impact/bounce sounds + if (ent->s.eFlags & EF_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta); // check for stop - if ( ((trace->plane.normal[2] > 0.7&&g_gravity->value>0) || (trace->plane.normal[2]<-0.7&&g_gravity->value<0)) && ((ent->s.pos.trDelta[2]<40&&g_gravity->value>0)||(ent->s.pos.trDelta[2]>-40&&g_gravity->value<0)) ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (((trace->plane.normal[2] > 0.7 && g_gravity->value > 0) || (trace->plane.normal[2] < -0.7 && g_gravity->value < 0)) && + ((ent->s.pos.trDelta[2] < 40 && g_gravity->value > 0) || + (ent->s.pos.trDelta[2] > -40 && g_gravity->value < 0))) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - //G_SetOrigin( ent, trace->endpos ); - //ent->nextthink = level.time + 500; + // G_SetOrigin( ent, trace->endpos ); + // ent->nextthink = level.time + 500; ent->s.apos.trType = TR_STATIONARY; - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorCopy( trace->endpos, ent->currentOrigin ); - VectorCopy( trace->endpos, ent->s.pos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorCopy(trace->endpos, ent->currentOrigin); + VectorCopy(trace->endpos, ent->s.pos.trBase); ent->s.pos.trTime = level.time; return; } @@ -72,11 +71,11 @@ void G_BounceObject( gentity_t *ent, trace_t *trace ) // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... // FIXME: Should we still consider adding the normal though?? - VectorCopy( trace->endpos, ent->currentOrigin ); + VectorCopy(trace->endpos, ent->currentOrigin); ent->s.pos.trTime = hitTime; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorCopy( trace->plane.normal, ent->pos1 );//??? + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorCopy(trace->plane.normal, ent->pos1); //??? } /* @@ -87,54 +86,48 @@ G_RunObject TODO: When free-floating in air, apply some friction to your trDelta (based on mass?) ================ */ -extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace ); -void G_RunObject( gentity_t *ent ) -{ - vec3_t origin, oldOrg; - trace_t tr; - gentity_t *traceEnt = NULL; - - //FIXME: floaters need to stop floating up after a while, even if gravity stays negative? - if ( ent->s.pos.trType == TR_STATIONARY )//g_gravity->value <= 0 && +extern void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf, trace_t *trace); +void G_RunObject(gentity_t *ent) { + vec3_t origin, oldOrg; + trace_t tr; + gentity_t *traceEnt = NULL; + + // FIXME: floaters need to stop floating up after a while, even if gravity stays negative? + if (ent->s.pos.trType == TR_STATIONARY) // g_gravity->value <= 0 && { ent->s.pos.trType = TR_GRAVITY; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - ent->s.pos.trTime = level.previousTime;//?necc? - if ( !g_gravity->value ) - { + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + ent->s.pos.trTime = level.previousTime; //?necc? + if (!g_gravity->value) { ent->s.pos.trDelta[2] += 100; } } ent->nextthink = level.time + FRAMETIME; - VectorCopy( ent->currentOrigin, oldOrg ); + VectorCopy(ent->currentOrigin, oldOrg); // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); - //Get current angles? - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); + // Get current angles? + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); - if ( VectorCompare( ent->currentOrigin, origin ) ) - {//error - didn't move at all! + if (VectorCompare(ent->currentOrigin, origin)) { // error - didn't move at all! return; } // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, (EG2_Collision)0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction ) - { - VectorCopy( tr.endpos, ent->currentOrigin ); - gi.linkentity( ent ); - } - else - //if ( tr.startsolid ) + if (!tr.startsolid && !tr.allsolid && tr.fraction) { + VectorCopy(tr.endpos, ent->currentOrigin); + gi.linkentity(ent); + } else + // if ( tr.startsolid ) { tr.fraction = 0; } - G_MoverTouchPushTriggers( ent, oldOrg ); + G_MoverTouchPushTriggers(ent, oldOrg); /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) && !(ent->svFlags & SVF_NO_TELEPORT) ) { @@ -150,23 +143,19 @@ void G_RunObject( gentity_t *ent ) } */ - if ( tr.fraction == 1 ) - { - if ( g_gravity->value <= 0 ) - { - if ( ent->s.apos.trType == TR_STATIONARY ) - { - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + if (tr.fraction == 1) { + if (g_gravity->value <= 0) { + if (ent->s.apos.trType == TR_STATIONARY) { + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; - ent->s.apos.trDelta[1] = Q_flrand( -300, 300 ); - ent->s.apos.trDelta[0] = Q_flrand( -10, 10 ); - ent->s.apos.trDelta[2] = Q_flrand( -10, 10 ); + ent->s.apos.trDelta[1] = Q_flrand(-300, 300); + ent->s.apos.trDelta[0] = Q_flrand(-10, 10); + ent->s.apos.trDelta[2] = Q_flrand(-10, 10); ent->s.apos.trTime = level.time; } } - //friction in zero-G - if ( !g_gravity->value ) - { + // friction in zero-G + if (!g_gravity->value) { float friction = 0.975f; /*friction -= ent->mass/1000.0f; if ( friction < 0.1 ) @@ -174,108 +163,87 @@ void G_RunObject( gentity_t *ent ) friction = 0.1f; } */ - VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(ent->s.pos.trDelta, friction, ent->s.pos.trDelta); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } return; } - //hit something + // hit something - //Do impact damage + // Do impact damage traceEnt = &g_entities[tr.entityNum]; - if ( tr.fraction || (traceEnt && traceEnt->takedamage) ) - { - if ( !VectorCompare( ent->currentOrigin, oldOrg ) ) - {//moved and impacted - if ( (traceEnt && traceEnt->takedamage) ) - {//hurt someone + if (tr.fraction || (traceEnt && traceEnt->takedamage)) { + if (!VectorCompare(ent->currentOrigin, oldOrg)) { // moved and impacted + if ((traceEnt && traceEnt->takedamage)) { // hurt someone vec3_t fxDir; - VectorNormalize2( ent->s.pos.trDelta, fxDir ); - VectorScale( fxDir, -1, fxDir ); - G_PlayEffect( G_EffectIndex( "melee/kick_impact" ), tr.endpos, fxDir ); - //G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - } - else - { - G_PlayEffect( G_EffectIndex( "melee/kick_impact_silent" ), tr.endpos, tr.plane.normal ); - } - if ( ent->mass > 100 ) - { - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHitHeavy.wav" ) ); + VectorNormalize2(ent->s.pos.trDelta, fxDir); + VectorScale(fxDir, -1, fxDir); + G_PlayEffect(G_EffectIndex("melee/kick_impact"), tr.endpos, fxDir); + // G_Sound( ent, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + } else { + G_PlayEffect(G_EffectIndex("melee/kick_impact_silent"), tr.endpos, tr.plane.normal); } - else - { - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHit.wav" ) ); + if (ent->mass > 100) { + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectHitHeavy.wav")); + } else { + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectHit.wav")); } } - DoImpact( ent, traceEnt, (qboolean)!(tr.surfaceFlags&SURF_NODAMAGE), &tr ); + DoImpact(ent, traceEnt, (qboolean) !(tr.surfaceFlags & SURF_NODAMAGE), &tr); } - if ( !ent || (ent->takedamage&&ent->health <= 0) ) - {//been destroyed by impact - //chunks? - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectBreak.wav" ) ); + if (!ent || (ent->takedamage && ent->health <= 0)) { // been destroyed by impact + // chunks? + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectBreak.wav")); return; } - //do impact physics - if ( ent->s.pos.trType == TR_GRAVITY )//tr.fraction < 1.0 && - {//FIXME: only do this if no trDelta - if ( g_gravity->value <= 0 || tr.plane.normal[2] < 0.7 ) - { - if ( ent->s.eFlags&(EF_BOUNCE|EF_BOUNCE_HALF) ) - { - if ( tr.fraction <= 0.0f ) - { - VectorCopy( tr.endpos, ent->currentOrigin ); - VectorCopy( tr.endpos, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + // do impact physics + if (ent->s.pos.trType == TR_GRAVITY) // tr.fraction < 1.0 && + { // FIXME: only do this if no trDelta + if (g_gravity->value <= 0 || tr.plane.normal[2] < 0.7) { + if (ent->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF)) { + if (tr.fraction <= 0.0f) { + VectorCopy(tr.endpos, ent->currentOrigin); + VectorCopy(tr.endpos, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; + } else { + G_BounceObject(ent, &tr); } - else - { - G_BounceObject( ent, &tr ); - } - } - else - {//slide down? - //FIXME: slide off the slope + } else { // slide down? + // FIXME: slide off the slope } - } - else - { + } else { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->currentAngles[0] = 0;//FIXME: match to slope - //ent->currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - //okay, we hit the floor, might as well stop or prediction will - //make us go through the floor! - //FIXME: this means we can't fall if something is pulled out from under us... - G_StopObjectMoving( ent ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->currentAngles[0] = 0;//FIXME: match to slope + // ent->currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + // okay, we hit the floor, might as well stop or prediction will + // make us go through the floor! + // FIXME: this means we can't fall if something is pulled out from under us... + G_StopObjectMoving(ent); } - } - else - { + } else { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->currentAngles[0] = 0;//FIXME: match to slope - //ent->currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->currentAngles[0] = 0;//FIXME: match to slope + // ent->currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->currentAngles, ent->s.apos.trBase); } - //call touch func - GEntity_TouchFunc( ent, &g_entities[tr.entityNum], &tr ); + // call touch func + GEntity_TouchFunc(ent, &g_entities[tr.entityNum], &tr); } -void G_StopObjectMoving( gentity_t *object ) -{ +void G_StopObjectMoving(gentity_t *object) { object->s.pos.trType = TR_STATIONARY; - VectorCopy( object->currentOrigin, object->s.origin ); - VectorCopy( object->currentOrigin, object->s.pos.trBase ); - VectorClear( object->s.pos.trDelta ); + VectorCopy(object->currentOrigin, object->s.origin); + VectorCopy(object->currentOrigin, object->s.pos.trBase); + VectorClear(object->s.pos.trDelta); /* //Stop spinning @@ -286,14 +254,13 @@ void G_StopObjectMoving( gentity_t *object ) */ } -void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t trType ) -{ - VectorNormalize (dir); +void G_StartObjectMoving(gentity_t *object, vec3_t dir, float speed, trType_t trType) { + VectorNormalize(dir); - //object->s.eType = ET_GENERAL; + // object->s.eType = ET_GENERAL; object->s.pos.trType = trType; - VectorCopy( object->currentOrigin, object->s.pos.trBase ); - VectorScale(dir, speed, object->s.pos.trDelta ); + VectorCopy(object->currentOrigin, object->s.pos.trBase); + VectorScale(dir, speed, object->s.pos.trDelta); object->s.pos.trTime = level.time; /* @@ -304,72 +271,67 @@ void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t t object->s.apos.trTime = level.time; */ - //FIXME: make these objects go through G_RunObject automatically, like missiles do - if ( object->e_ThinkFunc == thinkF_NULL ) - { + // FIXME: make these objects go through G_RunObject automatically, like missiles do + if (object->e_ThinkFunc == thinkF_NULL) { object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; - } - else - {//You're responsible for calling RunObject + } else { // You're responsible for calling RunObject } } -gentity_t *G_CreateObject ( gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType, int effectID = 0 ) -{ - gentity_t *object; +gentity_t *G_CreateObject(gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType, int effectID = 0) { + gentity_t *object; object = G_Spawn(); - if ( object == NULL ) - { + if (object == NULL) { return NULL; } - object->classname = "object";//? + object->classname = "object"; //? object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; object->s.eType = ET_GENERAL; - object->s.eFlags |= EF_AUTO_SIZE;//CG_Ents will create the mins & max itself based on model bounds + object->s.eFlags |= EF_AUTO_SIZE; // CG_Ents will create the mins & max itself based on model bounds object->s.modelindex = modelIndex; - //FIXME: allow to set a targetname/script_targetname and animation info? + // FIXME: allow to set a targetname/script_targetname and animation info? object->s.frame = object->startFrame = object->endFrame = frame; object->owner = owner; - //object->damage = 100; - //object->splashDamage = 200; - //object->splashRadius = 200; - //object->methodOfDeath = MOD_EXPLOSIVE; - //object->splashMethodOfDeath = MOD_EXPLOSIVE_SPLASH; - object->clipmask = MASK_SOLID;//? - //object->e_TouchFunc = touchF_charge_stick; + // object->damage = 100; + // object->splashDamage = 200; + // object->splashRadius = 200; + // object->methodOfDeath = MOD_EXPLOSIVE; + // object->splashMethodOfDeath = MOD_EXPLOSIVE_SPLASH; + object->clipmask = MASK_SOLID; //? + // object->e_TouchFunc = touchF_charge_stick; // The effect to play. object->count = effectID; - //Give it SOME size for now - VectorSet( object->mins, -4, -4, -4 ); - VectorSet( object->maxs, 4, 4, 4 ); + // Give it SOME size for now + VectorSet(object->mins, -4, -4, -4); + VectorSet(object->maxs, 4, 4, 4); - //Origin - G_SetOrigin( object, origin ); + // Origin + G_SetOrigin(object, origin); object->s.pos.trType = trType; - VectorCopy( origin, object->s.pos.trBase ); - //Velocity - VectorClear( object->s.pos.trDelta ); + VectorCopy(origin, object->s.pos.trBase); + // Velocity + VectorClear(object->s.pos.trDelta); object->s.pos.trTime = level.time; - //VectorScale( dir, 300, object->s.pos.trDelta ); - //object->s.pos.trTime = level.time; - - //Angles - VectorCopy( angles, object->s.angles ); - VectorCopy( object->s.angles, object->s.apos.trBase ); - //Angular Velocity - VectorClear( object->s.apos.trDelta ); + // VectorScale( dir, 300, object->s.pos.trDelta ); + // object->s.pos.trTime = level.time; + + // Angles + VectorCopy(angles, object->s.angles); + VectorCopy(object->s.angles, object->s.apos.trBase); + // Angular Velocity + VectorClear(object->s.apos.trDelta); object->s.apos.trTime = level.time; - //VectorSet( object->s.apos.trDelta, 300, 0, 0 ); - //object->s.apos.trTime = level.time; + // VectorSet( object->s.apos.trDelta, 300, 0, 0 ); + // object->s.apos.trTime = level.time; - gi.linkentity( object ); + gi.linkentity(object); return object; } diff --git a/code/game/g_objectives.cpp b/code/game/g_objectives.cpp index 5073cf8d83..cab333b54c 100644 --- a/code/game/g_objectives.cpp +++ b/code/game/g_objectives.cpp @@ -20,34 +20,29 @@ along with this program; if not, see . =========================================================================== */ -//g_objectives.cpp -//reads in ext_data\objectives.dat to objectives[] +// g_objectives.cpp +// reads in ext_data\objectives.dat to objectives[] #include "g_local.h" #include "g_items.h" -#define G_OBJECTIVES_CPP +#define G_OBJECTIVES_CPP #include "objectives.h" #include "qcommon/ojk_saved_game_helper.h" -qboolean missionInfo_Updated; - +qboolean missionInfo_Updated; /* ============ OBJ_SetPendingObjectives ============ */ -void OBJ_SetPendingObjectives(gentity_t *ent) -{ +void OBJ_SetPendingObjectives(gentity_t *ent) { int i; - for (i=0;iclient->sess.mission_objectives[i].status == OBJECTIVE_STAT_PENDING) && - (ent->client->sess.mission_objectives[i].display)) - { + for (i = 0; i < MAX_OBJECTIVES; ++i) { + if ((ent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_PENDING) && (ent->client->sess.mission_objectives[i].display)) { ent->client->sess.mission_objectives[i].status = OBJECTIVE_STAT_FAILED; } } @@ -58,29 +53,23 @@ void OBJ_SetPendingObjectives(gentity_t *ent) OBJ_SaveMissionObjectives ============ */ -void OBJ_SaveMissionObjectives( gclient_t *client ) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.write_chunk( - INT_ID('O', 'B', 'J', 'T'), - client->sess.mission_objectives); -} +void OBJ_SaveMissionObjectives(gclient_t *client) { + ojk::SavedGameHelper saved_game(::gi.saved_game); + saved_game.write_chunk(INT_ID('O', 'B', 'J', 'T'), client->sess.mission_objectives); +} /* ============ OBJ_SaveObjectiveData ============ */ -void OBJ_SaveObjectiveData(void) -{ +void OBJ_SaveObjectiveData(void) { gclient_t *client; client = &level.clients[0]; - OBJ_SaveMissionObjectives( client ); + OBJ_SaveMissionObjectives(client); } /* @@ -88,27 +77,21 @@ void OBJ_SaveObjectiveData(void) OBJ_LoadMissionObjectives ============ */ -void OBJ_LoadMissionObjectives( gclient_t *client ) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.read_chunk( - INT_ID('O', 'B', 'J', 'T'), - client->sess.mission_objectives); -} +void OBJ_LoadMissionObjectives(gclient_t *client) { + ojk::SavedGameHelper saved_game(::gi.saved_game); + saved_game.read_chunk(INT_ID('O', 'B', 'J', 'T'), client->sess.mission_objectives); +} /* ============ OBJ_LoadObjectiveData ============ */ -void OBJ_LoadObjectiveData(void) -{ +void OBJ_LoadObjectiveData(void) { gclient_t *client; client = &level.clients[0]; - OBJ_LoadMissionObjectives( client ); + OBJ_LoadMissionObjectives(client); } diff --git a/code/game/g_rail.cpp b/code/game/g_rail.cpp index d98d8875ce..59d001a374 100644 --- a/code/game/g_rail.cpp +++ b/code/game/g_rail.cpp @@ -38,57 +38,54 @@ along with this program; if not, see . //////////////////////////////////////////////////////////////////////////////////////// // Externs & Fwd Decl. //////////////////////////////////////////////////////////////////////////////////////// -extern void G_SoundAtSpot( vec3_t org, int soundIndex, qboolean broadcast ); -extern void CG_DrawEdge( vec3_t start, vec3_t end, int type ); - -class CRailTrack; -class CRailLane; -class CRailMover; +extern void G_SoundAtSpot(vec3_t org, int soundIndex, qboolean broadcast); +extern void CG_DrawEdge(vec3_t start, vec3_t end, int type); +class CRailTrack; +class CRailLane; +class CRailMover; //////////////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////////////////////////// #include "b_local.h" #if !defined(RATL_ARRAY_VS_INC) - #include "../Ratl/array_vs.h" +#include "../Ratl/array_vs.h" #endif #if !defined(RATL_VECTOR_VS_INC) - #include "../Ratl/vector_vs.h" +#include "../Ratl/vector_vs.h" #endif #if !defined(RAVL_VEC_INC) - #include "../Ravl/CVec.h" +#include "../Ravl/CVec.h" #endif #if !defined(RUFL_HSTRING_INC) - #include "../Rufl/hstring.h" +#include "../Rufl/hstring.h" #endif #if !defined(RATL_GRID_VS_INC) - #include "../Ratl/grid_vs.h" +#include "../Ratl/grid_vs.h" #endif #if !defined(RATL_POOL_VS_INC) - #include "../Ratl/pool_vs.h" +#include "../Ratl/pool_vs.h" #endif //////////////////////////////////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////////////////////////////////// -#define MAX_TRACKS 4 -#define MAX_LANES 8 -#define MAX_MOVERS 150 -#define MAX_MOVER_ENTS 10 -#define MAX_MOVERS_TRACK 80 -#define MAX_COLS 32 -#define MAX_ROWS 96 -#define MAX_ROW_HISTORY 10 - -#define WOOSH_DEBUG 0 -#define WOOSH_ALL_RANGE 1500.0f -#define WOOSH_SUPPORT_RANGE 2500.0f -#define WOOSH_TUNNEL_RANGE 3000.0f - +#define MAX_TRACKS 4 +#define MAX_LANES 8 +#define MAX_MOVERS 150 +#define MAX_MOVER_ENTS 10 +#define MAX_MOVERS_TRACK 80 +#define MAX_COLS 32 +#define MAX_ROWS 96 +#define MAX_ROW_HISTORY 10 -bool mRailSystemActive = false; +#define WOOSH_DEBUG 0 +#define WOOSH_ALL_RANGE 1500.0f +#define WOOSH_SUPPORT_RANGE 2500.0f +#define WOOSH_TUNNEL_RANGE 3000.0f +bool mRailSystemActive = false; //////////////////////////////////////////////////////////////////////////////////////// // The Rail Track @@ -97,183 +94,157 @@ bool mRailSystemActive = false; // repositry of all movers and maintain the list of available movers as well as // //////////////////////////////////////////////////////////////////////////////////////// -class CRailTrack -{ -public: - void Setup(gentity_t *ent) - { - mName = ent->targetname; - mSpeedGridCellsPerSecond = ent->speed; - mNumMoversPerRow = ent->count; - mMins = ent->mins; - mMaxs = ent->maxs; - mStartTime = ent->delay + level.time; - mGridCellSize = (ent->radius!=0.0f)?(ent->radius):(1.0f); - mVertical = (ent->s.angles[1]==90.0f || ent->s.angles[1]==270.0f); - mNegative = (ent->s.angles[1]==180.0f || ent->s.angles[1]==270.0f); // From Maxs To Mins - mWAxis = (mVertical)?(0):(1); - mHAxis = (mVertical)?(1):(0); - mTravelDistanceUnits = ent->maxs[mHAxis] - ent->mins[mHAxis]; - - mRow = 0; - mNextUpdateTime = 0; - - mCenterLocked = false; +class CRailTrack { + public: + void Setup(gentity_t *ent) { + mName = ent->targetname; + mSpeedGridCellsPerSecond = ent->speed; + mNumMoversPerRow = ent->count; + mMins = ent->mins; + mMaxs = ent->maxs; + mStartTime = ent->delay + level.time; + mGridCellSize = (ent->radius != 0.0f) ? (ent->radius) : (1.0f); + mVertical = (ent->s.angles[1] == 90.0f || ent->s.angles[1] == 270.0f); + mNegative = (ent->s.angles[1] == 180.0f || ent->s.angles[1] == 270.0f); // From Maxs To Mins + mWAxis = (mVertical) ? (0) : (1); + mHAxis = (mVertical) ? (1) : (0); + mTravelDistanceUnits = ent->maxs[mHAxis] - ent->mins[mHAxis]; + + mRow = 0; + mNextUpdateTime = 0; + + mCenterLocked = false; SnapVectorToGrid(mMins); SnapVectorToGrid(mMaxs); // Calculate Number Of Rows And Columns //-------------------------------------- - mRows = ((mMaxs[mHAxis] - mMins[mHAxis]) / mGridCellSize); - mCols = ((mMaxs[mWAxis] - mMins[mWAxis]) / mGridCellSize); + mRows = ((mMaxs[mHAxis] - mMins[mHAxis]) / mGridCellSize); + mCols = ((mMaxs[mWAxis] - mMins[mWAxis]) / mGridCellSize); // Calculate Grid Center //----------------------- - mGridCenter = ((mMins+mMaxs)*0.5f); + mGridCenter = ((mMins + mMaxs) * 0.5f); SnapVectorToGrid(mGridCenter); // Calculate Speed & Velocity //---------------------------- - mSpeedUnitsPerMillisecond = mSpeedGridCellsPerSecond * mGridCellSize / 1000.0f; - mTravelTimeMilliseconds = mTravelDistanceUnits / mSpeedUnitsPerMillisecond; + mSpeedUnitsPerMillisecond = mSpeedGridCellsPerSecond * mGridCellSize / 1000.0f; + mTravelTimeMilliseconds = mTravelDistanceUnits / mSpeedUnitsPerMillisecond; AngleVectors(ent->s.angles, mDirection.v, 0, 0); mDirection.SafeNorm(); - mVelocity = mDirection; - mVelocity *= (mSpeedGridCellsPerSecond * mGridCellSize); - - mNextUpdateDelay = 1000.0f / (float)(mSpeedGridCellsPerSecond); + mVelocity = mDirection; + mVelocity *= (mSpeedGridCellsPerSecond * mGridCellSize); + mNextUpdateDelay = 1000.0f / (float)(mSpeedGridCellsPerSecond); // Calculate Bottom Left Corner //------------------------------ mGridBottomLeftCorner = ent->mins; - if (ent->s.angles[1]==180.0f) - { + if (ent->s.angles[1] == 180.0f) { mGridBottomLeftCorner[0] = mMaxs[0]; - } - else if (ent->s.angles[1]==270.0f) - { + } else if (ent->s.angles[1] == 270.0f) { mGridBottomLeftCorner[1] = mMaxs[1]; } SnapVectorToGrid(mGridBottomLeftCorner); - - mCells.set_size(mCols/*xSize*/, mRows/*ySize*/); + mCells.set_size(mCols /*xSize*/, mRows /*ySize*/); mCells.init(0); mMovers.clear(); - - if (!mNumMoversPerRow) - { + if (!mNumMoversPerRow) { mNumMoversPerRow = 3; } // Safe Clamp Number Of Rows & Cols //---------------------------------- - if (mRows>(MAX_ROWS-1)) - { - mRows = (MAX_ROWS-1); + if (mRows > (MAX_ROWS - 1)) { + mRows = (MAX_ROWS - 1); assert(0); } - if (mCols>(MAX_COLS-1)) - { - mCols = (MAX_COLS-1); + if (mCols > (MAX_COLS - 1)) { + mCols = (MAX_COLS - 1); assert(0); } } - void SnapVectorToGrid(CVec3& Vec) - { + void SnapVectorToGrid(CVec3 &Vec) { SnapFloatToGrid(Vec[0]); SnapFloatToGrid(Vec[1]); } - void SnapFloatToGrid(float& f) - { + void SnapFloatToGrid(float &f) { f = (int)(f); - bool fNeg = (f<0); - if (fNeg) - { - f *= -1; // Temporarly make it positive + bool fNeg = (f < 0); + if (fNeg) { + f *= -1; // Temporarly make it positive } - int Offset = ((int)(f) % (int)(mGridCellSize)); - int OffsetAbs = abs(Offset); - if (OffsetAbs>(mGridCellSize/2)) - { + int Offset = ((int)(f) % (int)(mGridCellSize)); + int OffsetAbs = abs(Offset); + if (OffsetAbs > (mGridCellSize / 2)) { Offset = (mGridCellSize - OffsetAbs) * -1; } f -= Offset; - if (fNeg) - { - f *= -1; // Put It Back To Negative + if (fNeg) { + f *= -1; // Put It Back To Negative } f = (int)(f); - assert(((int)(f)%(int)(mGridCellSize)) == 0); + assert(((int)(f) % (int)(mGridCellSize)) == 0); } + void Update(); + bool TestMoverInCells(CRailMover *mover, int atCol); + void InsertMoverInCells(CRailMover *mover, int atCol); + void RandomizeTestCols(int startCol, int stopCol); + public: + hstring mName; + int mRow; + int mNumMoversPerRow; + int mNextUpdateTime; + int mNextUpdateDelay; + int mStartTime; - void Update(); - bool TestMoverInCells(CRailMover* mover, int atCol); - void InsertMoverInCells(CRailMover* mover, int atCol); - void RandomizeTestCols(int startCol, int stopCol); - - - - + int mRows; + int mCols; + bool mVertical; + bool mNegative; + int mHAxis; + int mWAxis; + int mSpeedGridCellsPerSecond; + float mSpeedUnitsPerMillisecond; + int mTravelTimeMilliseconds; + float mTravelDistanceUnits; + CVec3 mDirection; + CVec3 mVelocity; -public: - hstring mName; + CVec3 mMins; + CVec3 mMaxs; - int mRow; - int mNumMoversPerRow; + CVec3 mGridBottomLeftCorner; + CVec3 mGridCenter; + float mGridCellSize; - int mNextUpdateTime; - int mNextUpdateDelay; - int mStartTime; + bool mCenterLocked; - int mRows; - int mCols; - - bool mVertical; - bool mNegative; - int mHAxis; - int mWAxis; - - int mSpeedGridCellsPerSecond; - float mSpeedUnitsPerMillisecond; - int mTravelTimeMilliseconds; - float mTravelDistanceUnits; - CVec3 mDirection; - CVec3 mVelocity; - - CVec3 mMins; - CVec3 mMaxs; - - CVec3 mGridBottomLeftCorner; - CVec3 mGridCenter; - float mGridCellSize; - - bool mCenterLocked; - - ratl::grid2_vs mCells; - ratl::vector_vs mMovers; - ratl::vector_vs mTestCols; + ratl::grid2_vs mCells; + ratl::vector_vs mMovers; + ratl::vector_vs mTestCols; }; -ratl::vector_vs mRailTracks; +ratl::vector_vs mRailTracks; //////////////////////////////////////////////////////////////////////////////////////// /*QUAKED rail_track (0 .5 .8) ? x x x x x x x x @@ -286,8 +257,7 @@ A rail track determines what location and direction rail_mover entities go. Don "delay" How long the ent will wait from the start of the level before placing movers */ //////////////////////////////////////////////////////////////////////////////////////// -void SP_rail_track(gentity_t *ent) -{ +void SP_rail_track(gentity_t *ent) { gi.SetBrushModel(ent, ent->model); G_SpawnInt("delay", "0", &ent->delay); mRailTracks.push_back().Setup(ent); @@ -295,82 +265,72 @@ void SP_rail_track(gentity_t *ent) mRailSystemActive = true; } - - - - //////////////////////////////////////////////////////////////////////////////////////// // The Rail Lane // // // //////////////////////////////////////////////////////////////////////////////////////// -class CRailLane -{ -public: +class CRailLane { + public: //////////////////////////////////////////////////////////////////////////////////// // From Entity Setup Spawn //////////////////////////////////////////////////////////////////////////////////// - void Setup(gentity_t* ent) - { - mName = ent->targetname; - mNameTrack = ent->target; - mMins = ent->mins; - mMaxs = ent->maxs; - mStartTime = ent->delay + level.time; + void Setup(gentity_t *ent) { + mName = ent->targetname; + mNameTrack = ent->target; + mMins = ent->mins; + mMaxs = ent->maxs; + mStartTime = ent->delay + level.time; } - hstring mName; - hstring mNameTrack; - CVec3 mMins; - CVec3 mMaxs; - int mStartTime; + hstring mName; + hstring mNameTrack; + CVec3 mMins; + CVec3 mMaxs; + int mStartTime; -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize // // This function scans through the list of tracks and hooks itself up with the // track //////////////////////////////////////////////////////////////////////////////////// - void Initialize() - { - mTrack = 0; - mMinCol = 0; - mMaxCol = 0; - -// int dummy; - for (int i=0; iSnapVectorToGrid(mMins); mTrack->SnapVectorToGrid(mMaxs); - mMinCol = (int)((mMins[mTrack->mWAxis] - mTrack->mMins[mTrack->mWAxis])/mTrack->mGridCellSize); - mMaxCol = (int)((mMaxs[mTrack->mWAxis] - mTrack->mMins[mTrack->mWAxis] - (mTrack->mGridCellSize/2.0f))/mTrack->mGridCellSize); + mMinCol = (int)((mMins[mTrack->mWAxis] - mTrack->mMins[mTrack->mWAxis]) / mTrack->mGridCellSize); + mMaxCol = (int)((mMaxs[mTrack->mWAxis] - mTrack->mMins[mTrack->mWAxis] - (mTrack->mGridCellSize / 2.0f)) / mTrack->mGridCellSize); - //if (mTrack->mNegative) + // if (mTrack->mNegative) //{ // mMinCol = (mTrack->mCols - mMinCol - 1); // mMaxCol = (mTrack->mCols - mMaxCol - 1); - //} - + // } -// mTrack->mCells.get_cell_coords(mMins[mTrack->mWAxis], 0, mMinCol, dummy); -// mTrack->mCells.get_cell_coords((mMaxs[mTrack->mWAxis]-10.0f), 0, mMaxCol, dummy); + // mTrack->mCells.get_cell_coords(mMins[mTrack->mWAxis], 0, mMinCol, dummy); + // mTrack->mCells.get_cell_coords((mMaxs[mTrack->mWAxis]-10.0f), 0, mMaxCol, dummy); break; } } - assert(mTrack!=0); + assert(mTrack != 0); } - CRailTrack* mTrack; - int mMinCol; - int mMaxCol; + CRailTrack *mTrack; + int mMinCol; + int mMaxCol; }; -ratl::vector_vs mRailLanes; +ratl::vector_vs mRailLanes; //////////////////////////////////////////////////////////////////////////////////////// /*QUAKED rail_lane (0 .5 .8) ? x x x x x x x x @@ -379,136 +339,115 @@ Use rail lanes to split up tracks. Just target it to a track that you want to b "delay" How long the ent will wait from the start of the level before placing movers */ //////////////////////////////////////////////////////////////////////////////////////// -void SP_rail_lane(gentity_t *ent) -{ - gi.SetBrushModel(ent, ent->model); +void SP_rail_lane(gentity_t *ent) { + gi.SetBrushModel(ent, ent->model); G_SpawnInt("delay", "0", &ent->delay); mRailLanes.push_back().Setup(ent); G_FreeEntity(ent); } - - - - //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -class CRailMover -{ -public: +class CRailMover { + public: //////////////////////////////////////////////////////////////////////////////////// // From Entity Setup Spawn //////////////////////////////////////////////////////////////////////////////////// - void Setup(gentity_t* ent) - { - mEnt = ent; - mCenter = (ent->spawnflags&1); - mSoundPlayed = false; - mOriginOffset = ent->mins; - mOriginOffset += ent->maxs; - mOriginOffset *= 0.5f; - mOriginOffset[2] = 0;//((ent->maxs[2] - ent->mins[2]) * 0.5); - - ent->e_ReachedFunc = reachedF_NULL; - ent->moverState = MOVER_POS1; - ent->svFlags = SVF_USE_CURRENT_ORIGIN; - ent->s.eType = ET_MOVER; - ent->s.eFlags |= EF_NODRAW; - ent->contents = 0; - ent->clipmask = 0; - - ent->s.pos.trType = TR_STATIONARY; - ent->s.pos.trDuration = 0; - ent->s.pos.trTime = 0; - - VectorCopy( ent->pos1, ent->currentOrigin ); - VectorCopy( ent->pos1, ent->s.pos.trBase ); - + void Setup(gentity_t *ent) { + mEnt = ent; + mCenter = (ent->spawnflags & 1); + mSoundPlayed = false; + mOriginOffset = ent->mins; + mOriginOffset += ent->maxs; + mOriginOffset *= 0.5f; + mOriginOffset[2] = 0; //((ent->maxs[2] - ent->mins[2]) * 0.5); + + ent->e_ReachedFunc = reachedF_NULL; + ent->moverState = MOVER_POS1; + ent->svFlags = SVF_USE_CURRENT_ORIGIN; + ent->s.eType = ET_MOVER; + ent->s.eFlags |= EF_NODRAW; + ent->contents = 0; + ent->clipmask = 0; + + ent->s.pos.trType = TR_STATIONARY; + ent->s.pos.trDuration = 0; + ent->s.pos.trTime = 0; + + VectorCopy(ent->pos1, ent->currentOrigin); + VectorCopy(ent->pos1, ent->s.pos.trBase); gi.linkentity(ent); } - gentity_t* mEnt; - bool mCenter; - CVec3 mOriginOffset; - bool mSoundPlayed; - - - bool Active() - { - assert(mEnt!=0); - return (level.time<(mEnt->s.pos.trDuration + mEnt->s.pos.trTime)); + gentity_t *mEnt; + bool mCenter; + CVec3 mOriginOffset; + bool mSoundPlayed; + + bool Active() { + assert(mEnt != 0); + return (level.time < (mEnt->s.pos.trDuration + mEnt->s.pos.trTime)); } - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize // // This function scans through the list of tracks and hooks itself up with the // track (and possibly lane) //////////////////////////////////////////////////////////////////////////////////// - void Initialize() - { - mTrack = 0; - mLane = 0; - mCols = 0; - mRows = 0; - - hstring target = mEnt->target; - for (int track=0; tracktarget; + for (int track = 0; track < mRailTracks.size(); track++) { + if (mRailTracks[track].mName == target) { mTrack = &(mRailTracks[track]); break; } } - if (mTrack==0) - { - for (int lane=0; lanemTrack; + if (mTrack == 0) { + for (int lane = 0; lane < mRailLanes.size(); lane++) { + if (mRailLanes[lane].mName == target) { + mLane = &(mRailLanes[lane]); + mTrack = mLane->mTrack; break; } } } - assert(mTrack!=0); - if (mTrack) - { + assert(mTrack != 0); + if (mTrack) { mTrack->mMovers.push_back(this); - mCols = (int)((mEnt->maxs[mTrack->mWAxis] - mEnt->mins[mTrack->mWAxis]) / mTrack->mGridCellSize) + 1; - mRows = (int)((mEnt->maxs[mTrack->mHAxis] - mEnt->mins[mTrack->mHAxis]) / mTrack->mGridCellSize) + 1; + mCols = (int)((mEnt->maxs[mTrack->mWAxis] - mEnt->mins[mTrack->mWAxis]) / mTrack->mGridCellSize) + 1; + mRows = (int)((mEnt->maxs[mTrack->mHAxis] - mEnt->mins[mTrack->mHAxis]) / mTrack->mGridCellSize) + 1; // Make Sure The Mover Fits In The Track And Lane //------------------------------------------------ - if (mRows>mTrack->mRows) - { -// assert(0); + if (mRows > mTrack->mRows) { + // assert(0); mRows = mTrack->mRows; } - if (mCols>mTrack->mCols) - { -// assert(0); + if (mCols > mTrack->mCols) { + // assert(0); mCols = mTrack->mCols; } - if (mLane && mCols>(mLane->mMaxCol - mLane->mMinCol + 1)) - { -// assert(0); + if (mLane && mCols > (mLane->mMaxCol - mLane->mMinCol + 1)) { + // assert(0); mCols = (mLane->mMaxCol - mLane->mMinCol + 1); } } } - CRailTrack* mTrack; - CRailLane* mLane; - int mCols; - int mRows; + CRailTrack *mTrack; + CRailLane *mLane; + int mCols; + int mRows; }; -ratl::vector_vs mRailMovers; +ratl::vector_vs mRailMovers; //////////////////////////////////////////////////////////////////////////////////////// /*QUAKED rail_mover (0 .5 .8) ? CENTER x x x x x x x @@ -521,27 +460,21 @@ CENTER Will force this mover to attempt to center in the track or lane "angle" Random angle rotation allowable on this thing */ //////////////////////////////////////////////////////////////////////////////////////// -void SP_rail_mover(gentity_t *ent) -{ +void SP_rail_mover(gentity_t *ent) { gi.SetBrushModel(ent, ent->model); mRailMovers.push_back().Setup(ent); } - -ratl::vector_vs mWooshSml; // Small Building -ratl::vector_vs mWooshMed; // Medium Building -ratl::vector_vs mWooshLar; // Large Building -ratl::vector_vs mWooshSup; // Track Support -ratl::vector_vs mWooshTun; // Tunnel - - - +ratl::vector_vs mWooshSml; // Small Building +ratl::vector_vs mWooshMed; // Medium Building +ratl::vector_vs mWooshLar; // Large Building +ratl::vector_vs mWooshSup; // Track Support +ratl::vector_vs mWooshTun; // Tunnel //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Rail_Reset() -{ +void Rail_Reset() { mRailSystemActive = false; mRailTracks.clear(); mRailLanes.clear(); @@ -557,22 +490,18 @@ void Rail_Reset() //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Rail_Initialize() -{ - for (int lane=0; lanemRailTracks[track].mNextUpdateTime && !mRailTracks[track].mMovers.empty()) - { + for (int track = 0; track < mRailTracks.size(); track++) { + if (level.time > mRailTracks[track].mNextUpdateTime && !mRailTracks[track].mMovers.empty()) { mRailTracks[track].Update(); } } // Is The Player Outside? //------------------------ - if (player && gi.WE_IsOutside(player->currentOrigin)) - { - int wooshSound; - vec3_t wooshSoundPos; - vec3_t moverOrigin; - vec3_t playerToMover; - float playerToMoverDistance; - float playerToMoverDistanceFraction; + if (player && gi.WE_IsOutside(player->currentOrigin)) { + int wooshSound; + vec3_t wooshSoundPos; + vec3_t moverOrigin; + vec3_t playerToMover; + float playerToMoverDistance; + float playerToMoverDistanceFraction; // Iterate Over All The Movers //----------------------------- - for (int moverIndex=0; moverIndexcurrentOrigin, mover.mOriginOffset.v, moverOrigin); - VectorSubtract(moverOrigin, player->currentOrigin, playerToMover); - playerToMover[2] = 0.0f; - playerToMoverDistance = VectorNormalize(playerToMover); - + if (mover.Active() && !mover.mSoundPlayed) { + VectorAdd(mover.mEnt->currentOrigin, mover.mOriginOffset.v, moverOrigin); + VectorSubtract(moverOrigin, player->currentOrigin, playerToMover); + playerToMover[2] = 0.0f; + playerToMoverDistance = VectorNormalize(playerToMover); // Is It Close Enough? //--------------------- - if ((( mover.mLane || !mover.mCenter) && // Not Center Track - (playerToMoverDistancemDirection.v)>-0.45f)) // And On The Side - || //OR - ((!mover.mLane && mover.mCenter) && // Is Center Track - (playerToMoverDistance10)) // Or Close Enough For Tunnel - )) - { + if (((mover.mLane || !mover.mCenter) && // Not Center Track + (playerToMoverDistance < WOOSH_ALL_RANGE) && // And Close Enough + (DotProduct(playerToMover, mover.mTrack->mDirection.v) > -0.45f)) // And On The Side + || // OR + ((!mover.mLane && mover.mCenter) && // Is Center Track + (playerToMoverDistance < WOOSH_SUPPORT_RANGE || // And Close Enough for Support + (playerToMoverDistance < WOOSH_TUNNEL_RANGE && mover.mRows > 10)) // Or Close Enough For Tunnel + )) { mover.mSoundPlayed = true; wooshSound = 0; // The Centered Entities Play Right On The Player's Head For Full Volume //----------------------------------------------------------------------- - if (mover.mCenter && !mover.mLane) - { - VectorCopy(player->currentOrigin, wooshSoundPos); - wooshSoundPos[2] += 50; + if (mover.mCenter && !mover.mLane) { + VectorCopy(player->currentOrigin, wooshSoundPos); + wooshSoundPos[2] += 50; // If It Is Very Long, Play The Tunnel Sound //------------------------------------------- - if (mover.mRows>10) - { - wooshSound = mWooshTun[Q_irand(0, mWooshTun.size()-1)]; + if (mover.mRows > 10) { + wooshSound = mWooshTun[Q_irand(0, mWooshTun.size() - 1)]; } // Otherwise It Is A Support //--------------------------- - else - { - wooshSound = mWooshSup[Q_irand(0, mWooshSup.size()-1)]; + else { + wooshSound = mWooshSup[Q_irand(0, mWooshSup.size() - 1)]; } } // All Other Entities Play At A Fraction Of Their Normal Range //------------------------------------------------------------- - else - { + else { // Scale The Play Pos By The Square Of The Distance //-------------------------------------------------- - playerToMoverDistanceFraction = playerToMoverDistance/WOOSH_ALL_RANGE; - playerToMoverDistanceFraction *= playerToMoverDistanceFraction; + playerToMoverDistanceFraction = playerToMoverDistance / WOOSH_ALL_RANGE; + playerToMoverDistanceFraction *= playerToMoverDistanceFraction; playerToMoverDistanceFraction *= 0.6f; playerToMoverDistance *= playerToMoverDistanceFraction; - VectorMA(player->currentOrigin, playerToMoverDistance, playerToMover, wooshSoundPos); + VectorMA(player->currentOrigin, playerToMoverDistance, playerToMover, wooshSoundPos); // Large Building //---------------- - if (mover.mRows>4) - { - wooshSound = mWooshLar[Q_irand(0, mWooshLar.size()-1)]; + if (mover.mRows > 4) { + wooshSound = mWooshLar[Q_irand(0, mWooshLar.size() - 1)]; } // Medium Building //----------------- - else if (mover.mRows>2) - { - wooshSound = mWooshMed[Q_irand(0, mWooshMed.size()-1)]; + else if (mover.mRows > 2) { + wooshSound = mWooshMed[Q_irand(0, mWooshMed.size() - 1)]; } // Small Building //---------------- - else - { - wooshSound = mWooshSml[Q_irand(0, mWooshSml.size()-1)]; + else { + wooshSound = mWooshSml[Q_irand(0, mWooshSml.size() - 1)]; } } // If A Woosh Sound Was Selected, Play It Now //-------------------------------------------- - if (wooshSound) - { + if (wooshSound) { G_SoundAtSpot(wooshSoundPos, wooshSound, qfalse); - if (WOOSH_DEBUG) - { + if (WOOSH_DEBUG) { CG_DrawEdge(player->currentOrigin, wooshSoundPos, EDGE_WHITE_TWOSECOND); } } @@ -738,13 +650,10 @@ void Rail_Update() //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void Rail_LockCenterOfTrack(const char* trackName) -{ - hstring name = trackName; - for (int track=0; trackActive()) - { + CRailMover *mover = mMovers[Q_irand(0, mMovers.size() - 1)]; + if (mover->Active()) { continue; } // Don't Spawn Until Start Time Has Expired //------------------------------------------ - if (level.time < ((mover->mLane)?(mover->mLane->mStartTime):(mStartTime))) - { + if (level.time < ((mover->mLane) ? (mover->mLane->mStartTime) : (mStartTime))) { continue; } // If Center Locked, Stop Spawning Center Track Movers //----------------------------------------------------- - if (mover->mCenter && mCenterLocked) - { + if (mover->mCenter && mCenterLocked) { continue; } - // Restrict It To A Lane //----------------------- - if (mover->mLane) - { - startCol = mover->mLane->mMinCol; - stopCol = mover->mLane->mMaxCol+1; + if (mover->mLane) { + startCol = mover->mLane->mMinCol; + stopCol = mover->mLane->mMaxCol + 1; } // Or Let It Go Anywhere On The Track //------------------------------------ - else - { - startCol = 0; - stopCol = mCols; + else { + startCol = 0; + stopCol = mCols; } - stopCol -= (mover->mCols-1); - + stopCol -= (mover->mCols - 1); // If The Mover Is Too Big To Fit In The Lane, Go On To Next Attempt //------------------------------------------------------------------- - if (stopCol<=startCol) - { - assert(0); // Should Not Happen + if (stopCol <= startCol) { + assert(0); // Should Not Happen continue; } // Force It To Center //-------------------- - if (mover->mCenter && stopCol!=(startCol+1)) - { - startCol = ((mCols/2) - (mover->mCols/2)); - stopCol = startCol+1; + if (mover->mCenter && stopCol != (startCol + 1)) { + startCol = ((mCols / 2) - (mover->mCols / 2)); + stopCol = startCol + 1; } - // Construct A List Of Columns To Test For Insertion //--------------------------------------------------- mTestCols.clear(); - for (int i=startCol; imCols/2.0f) * mGridCellSize)); - StartPos[mHAxis] += (((mover->mRows/2.0f) * mGridCellSize) * ((mNegative)?(1):(-1))); + CVec3 StartPos(mGridBottomLeftCorner); + StartPos[mWAxis] += ((atCol * mGridCellSize) + ((mover->mCols / 2.0f) * mGridCellSize)); + StartPos[mHAxis] += (((mover->mRows / 2.0f) * mGridCellSize) * ((mNegative) ? (1) : (-1))); StartPos[2] = 0; // If Centered, Actually Put It At EXACTLY The Right Position On The Width Axis //------------------------------------------------------------------------------ - if (mover->mCenter) - { + if (mover->mCenter) { StartPos[mWAxis] = mGridCenter[mWAxis]; - float deltaOffset = mGridCenter[mWAxis] - mover->mOriginOffset[mWAxis]; - if (deltaOffset<(mGridCellSize*0.5f) ) - { + float deltaOffset = mGridCenter[mWAxis] - mover->mOriginOffset[mWAxis]; + if (deltaOffset < (mGridCellSize * 0.5f)) { StartPos[mWAxis] -= deltaOffset; } } @@ -895,13 +783,12 @@ void CRailTrack::Update() //----------------- VectorCopy(StartPos.v, mover->mEnt->s.pos.trBase); VectorCopy(mVelocity.v, mover->mEnt->s.pos.trDelta); - mover->mEnt->s.pos.trTime = level.time; - mover->mEnt->s.pos.trDuration = mTravelTimeMilliseconds + (mNextUpdateDelay*mover->mRows); - mover->mEnt->s.pos.trType = TR_LINEAR_STOP; - mover->mEnt->s.eFlags &= ~EF_NODRAW; - - mover->mSoundPlayed = false; + mover->mEnt->s.pos.trTime = level.time; + mover->mEnt->s.pos.trDuration = mTravelTimeMilliseconds + (mNextUpdateDelay * mover->mRows); + mover->mEnt->s.pos.trType = TR_LINEAR_STOP; + mover->mEnt->s.eFlags &= ~EF_NODRAW; + mover->mSoundPlayed = false; // Successfully Inserted This Mover. Now Move On To The Next Mover //------------------------------------------------------------------ @@ -913,20 +800,17 @@ void CRailTrack::Update() // Incriment The Current Row //--------------------------- mRow++; - if (mRow>=mRows) - { + if (mRow >= mRows) { mRow = 0; } // Erase The Erase Row //--------------------- - int EraseRow = mRow - MAX_ROW_HISTORY; - if (EraseRow<0) - { + int EraseRow = mRow - MAX_ROW_HISTORY; + if (EraseRow < 0) { EraseRow += mRows; } - for (int col=0; colmRows); moverRow++) +bool CRailTrack::TestMoverInCells(CRailMover *mover, int atCol) { + // for (int moverRow=0; (moverRowmRows); moverRow++) //{ - for (int moverCol=0; (moverColmCols); moverCol++) - { - if (mCells.get(atCol+moverCol, mRow/*+moverRow*/)!=0) - { - return false; - } + for (int moverCol = 0; (moverCol < mover->mCols); moverCol++) { + if (mCells.get(atCol + moverCol, mRow /*+moverRow*/) != 0) { + return false; } + } //} return true; } @@ -974,21 +850,16 @@ bool CRailTrack::TestMoverInCells(CRailMover* mover, int atCol) //////////////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////////////// -void CRailTrack::InsertMoverInCells(CRailMover* mover, int atCol) -{ - for (int moverCol=0; (moverColmCols); moverCol++) - { - int col = atCol+moverCol; - for (int moverRow=0; (moverRowmRows); moverRow++) - { - int row = mRow+moverRow; - if (row>=mRows) - { +void CRailTrack::InsertMoverInCells(CRailMover *mover, int atCol) { + for (int moverCol = 0; (moverCol < mover->mCols); moverCol++) { + int col = atCol + moverCol; + for (int moverRow = 0; (moverRow < mover->mRows); moverRow++) { + int row = mRow + moverRow; + if (row >= mRows) { row -= mRows; } - assert(mCells.get(col, row)==0); + assert(mCells.get(col, row) == 0); mCells.get(col, row) = mover; } } } - diff --git a/code/game/g_ref.cpp b/code/game/g_ref.cpp index 9e40bce481..8c6482b136 100644 --- a/code/game/g_ref.cpp +++ b/code/game/g_ref.cpp @@ -27,20 +27,19 @@ along with this program; if not, see . extern int delayedShutDown; -#define TAG_GENERIC_NAME "__WORLD__" //If a designer chooses this name, cut a finger off as an example to the others +#define TAG_GENERIC_NAME "__WORLD__" // If a designer chooses this name, cut a finger off as an example to the others -typedef std::vector < reference_tag_t * > refTag_v; -typedef std::map < std::string, reference_tag_t * > refTag_m; +typedef std::vector refTag_v; +typedef std::map refTag_m; -typedef struct tagOwner_s -{ - refTag_v tags; - refTag_m tagMap; +typedef struct tagOwner_s { + refTag_v tags; + refTag_m tagMap; } tagOwner_t; -typedef std::map < std::string, tagOwner_t * > refTagOwner_m; +typedef std::map refTagOwner_m; -refTagOwner_m refTagOwnerMap; +refTagOwner_m refTagOwnerMap; /* ------------------------- @@ -48,19 +47,15 @@ TAG_ShowTags ------------------------- */ -void TAG_ShowTags( int flags ) -{ - refTagOwner_m::iterator rtoi; - - STL_ITERATE( rtoi, refTagOwnerMap ) - { - refTag_v::iterator rti; - STL_ITERATE( rti, (((*rtoi).second)->tags) ) - { - if ( (*rti)->flags & RTF_NAVGOAL ) - { - if ( gi.inPVS( g_entities[0].currentOrigin, (*rti)->origin ) ) - CG_DrawNode( (*rti)->origin, NODE_NAVGOAL ); +void TAG_ShowTags(int flags) { + refTagOwner_m::iterator rtoi; + + STL_ITERATE(rtoi, refTagOwnerMap) { + refTag_v::iterator rti; + STL_ITERATE(rti, (((*rtoi).second)->tags)) { + if ((*rti)->flags & RTF_NAVGOAL) { + if (gi.inPVS(g_entities[0].currentOrigin, (*rti)->origin)) + CG_DrawNode((*rti)->origin, NODE_NAVGOAL); } } } @@ -72,43 +67,38 @@ TAG_Init ------------------------- */ -void TAG_Init( void ) -{ - refTagOwner_m::iterator rtoi; +void TAG_Init(void) { + refTagOwner_m::iterator rtoi; - //Delete all owners - for ( rtoi = refTagOwnerMap.begin(); rtoi != refTagOwnerMap.end(); ++rtoi ) - { - if ( (*rtoi).second == NULL ) - { - assert( 0 ); //FIXME: This is not good + // Delete all owners + for (rtoi = refTagOwnerMap.begin(); rtoi != refTagOwnerMap.end(); ++rtoi) { + if ((*rtoi).second == NULL) { + assert(0); // FIXME: This is not good continue; } - refTag_v::iterator rti; + refTag_v::iterator rti; - //Delete all tags within the owner's scope - for ( rti = ((*rtoi).second)->tags.begin(); rti != ((*rtoi).second)->tags.end(); ++rti ) - { - if ( (*rti) == NULL ) - { - assert( 0 ); //FIXME: Bad bad + // Delete all tags within the owner's scope + for (rti = ((*rtoi).second)->tags.begin(); rti != ((*rtoi).second)->tags.end(); ++rti) { + if ((*rti) == NULL) { + assert(0); // FIXME: Bad bad continue; } - //Free it + // Free it delete (*rti); } - //Clear the containers + // Clear the containers ((*rtoi).second)->tags.clear(); ((*rtoi).second)->tagMap.clear(); - //Delete the owner + // Delete the owner delete ((*rtoi).second); } - //Clear the container + // Clear the container refTagOwnerMap.clear(); } @@ -118,13 +108,12 @@ TAG_FindOwner ------------------------- */ -tagOwner_t *TAG_FindOwner( const char *owner ) -{ - refTagOwner_m::iterator rtoi; +tagOwner_t *TAG_FindOwner(const char *owner) { + refTagOwner_m::iterator rtoi; - rtoi = refTagOwnerMap.find( owner ); + rtoi = refTagOwnerMap.find(owner); - if ( rtoi == refTagOwnerMap.end() ) + if (rtoi == refTagOwnerMap.end()) return NULL; return (*rtoi).second; @@ -136,41 +125,38 @@ TAG_Find ------------------------- */ -reference_tag_t *TAG_Find( const char *owner, const char *name ) -{ - tagOwner_t *tagOwner; +reference_tag_t *TAG_Find(const char *owner, const char *name) { + tagOwner_t *tagOwner; - tagOwner = VALIDSTRING( owner ) ? TAG_FindOwner( owner ) : TAG_FindOwner( TAG_GENERIC_NAME ); + tagOwner = VALIDSTRING(owner) ? TAG_FindOwner(owner) : TAG_FindOwner(TAG_GENERIC_NAME); - //Not found... - if ( tagOwner == NULL ) - { - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + // Not found... + if (tagOwner == NULL) { + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if ( tagOwner == NULL ) + if (tagOwner == NULL) return NULL; } - refTag_m::iterator rti; + refTag_m::iterator rti; - rti = tagOwner->tagMap.find( name ); + rti = tagOwner->tagMap.find(name); - if ( rti == tagOwner->tagMap.end() ) - { - //Try the generic owner instead - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + if (rti == tagOwner->tagMap.end()) { + // Try the generic owner instead + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if ( tagOwner == NULL ) + if (tagOwner == NULL) return NULL; - char tempName[ MAX_REFNAME ]; + char tempName[MAX_REFNAME]; - Q_strncpyz( (char *) tempName, name, MAX_REFNAME ); - Q_strlwr( (char *) tempName ); //NOTENOTE: For case insensitive searches on a map + Q_strncpyz((char *)tempName, name, MAX_REFNAME); + Q_strlwr((char *)tempName); // NOTENOTE: For case insensitive searches on a map - rti = tagOwner->tagMap.find( tempName ); + rti = tagOwner->tagMap.find(tempName); - if ( rti == tagOwner->tagMap.end() ) + if (rti == tagOwner->tagMap.end()) return NULL; } @@ -183,67 +169,60 @@ TAG_Add ------------------------- */ -reference_tag_t *TAG_Add( const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags ) -{ - reference_tag_t *tag = new reference_tag_t; - VALIDATEP( tag ); +reference_tag_t *TAG_Add(const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags) { + reference_tag_t *tag = new reference_tag_t; + VALIDATEP(tag); - //Copy the information - VectorCopy( origin, tag->origin ); - VectorCopy( angles, tag->angles ); + // Copy the information + VectorCopy(origin, tag->origin); + VectorCopy(angles, tag->angles); tag->radius = radius; - tag->flags = flags; + tag->flags = flags; - if ( VALIDSTRING( name ) == false ) - { - //gi.Error("Nameless ref_tag found at (%i %i %i)", (int)origin[0], (int)origin[1], (int)origin[2]); - gi.Printf(S_COLOR_RED"ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); + if (VALIDSTRING(name) == false) { + // gi.Error("Nameless ref_tag found at (%i %i %i)", (int)origin[0], (int)origin[1], (int)origin[2]); + gi.Printf(S_COLOR_RED "ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); delayedShutDown = level.time + 100; delete tag; return NULL; } - //Copy the name - Q_strncpyz( (char *) tag->name, name, MAX_REFNAME ); - Q_strlwr( (char *) tag->name ); //NOTENOTE: For case insensitive searches on a map + // Copy the name + Q_strncpyz((char *)tag->name, name, MAX_REFNAME); + Q_strlwr((char *)tag->name); // NOTENOTE: For case insensitive searches on a map - //Make sure this tag's name isn't alread in use - if ( TAG_Find( owner, name ) ) - { + // Make sure this tag's name isn't alread in use + if (TAG_Find(owner, name)) { delayedShutDown = level.time + 100; - gi.Printf(S_COLOR_RED"ERROR: Duplicate tag name \"%s\"\n", name ); + gi.Printf(S_COLOR_RED "ERROR: Duplicate tag name \"%s\"\n", name); delete tag; return NULL; } - //Attempt to add this to the owner's list - if ( VALIDSTRING( owner ) == false ) - { - //If the owner isn't found, use the generic world name + // Attempt to add this to the owner's list + if (VALIDSTRING(owner) == false) { + // If the owner isn't found, use the generic world name owner = TAG_GENERIC_NAME; } - tagOwner_t *tagOwner = TAG_FindOwner( owner ); + tagOwner_t *tagOwner = TAG_FindOwner(owner); - //If the owner is valid, add this tag to it - if VALID( tagOwner ) - { - tagOwner->tags.insert( tagOwner->tags.end(), tag ); - tagOwner->tagMap[ (char*) &tag->name ] = tag; - } - else - { - //Create a new owner list - tagOwner_t *tagOwner = new tagOwner_t; + // If the owner is valid, add this tag to it + if VALID (tagOwner) { + tagOwner->tags.insert(tagOwner->tags.end(), tag); + tagOwner->tagMap[(char *)&tag->name] = tag; + } else { + // Create a new owner list + tagOwner_t *tagOwner = new tagOwner_t; - VALIDATEP( tagOwner ); + VALIDATEP(tagOwner); - //Insert the information - tagOwner->tags.insert( tagOwner->tags.end(), tag ); - tagOwner->tagMap[ (char *) tag->name ] = tag; + // Insert the information + tagOwner->tags.insert(tagOwner->tags.end(), tag); + tagOwner->tagMap[(char *)tag->name] = tag; - //Map it - refTagOwnerMap[ owner ] = tagOwner; + // Map it + refTagOwnerMap[owner] = tagOwner; } return tag; @@ -255,19 +234,17 @@ TAG_GetOrigin ------------------------- */ -int TAG_GetOrigin( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { VectorClear(origin); return false; } - VALIDATEB( tag ); + VALIDATEB(tag); - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return true; } @@ -279,16 +256,14 @@ Had to get rid of that damn assert for dev ------------------------- */ -int TAG_GetOrigin2( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin2(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if( tag == NULL ) - { + if (tag == NULL) { return qfalse; } - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return qtrue; } @@ -298,13 +273,12 @@ TAG_GetAngles ------------------------- */ -int TAG_GetAngles( const char *owner, const char *name, vec3_t angles ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetAngles(const char *owner, const char *name, vec3_t angles) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); - VectorCopy( tag->angles, angles ); + VectorCopy(tag->angles, angles); return true; } @@ -315,11 +289,10 @@ TAG_GetRadius ------------------------- */ -int TAG_GetRadius( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetRadius(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); return tag->radius; } @@ -330,11 +303,10 @@ TAG_GetFlags ------------------------- */ -int TAG_GetFlags( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetFlags(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); return tag->flags; } @@ -373,47 +345,38 @@ ownername - the owner of this tag target - use to point the tag at something for angles */ -void ref_link ( gentity_t *ent ) -{ - if ( ent->target ) - { - //TODO: Find the target and set our angles to that direction - gentity_t *target = G_Find( NULL, FOFS(targetname), ent->target ); - vec3_t dir; - - if ( target ) - { - //Find the direction to the target - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); - - //FIXME: Does pitch get flipped? - } - else - { - gi.Printf( S_COLOR_RED"ERROR: ref_tag (%s) has invalid target (%s)", ent->targetname, ent->target ); +void ref_link(gentity_t *ent) { + if (ent->target) { + // TODO: Find the target and set our angles to that direction + gentity_t *target = G_Find(NULL, FOFS(targetname), ent->target); + vec3_t dir; + + if (target) { + // Find the direction to the target + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); + + // FIXME: Does pitch get flipped? + } else { + gi.Printf(S_COLOR_RED "ERROR: ref_tag (%s) has invalid target (%s)", ent->targetname, ent->target); } } - //Add the tag - /*tag = */TAG_Add( ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0 ); + // Add the tag + /*tag = */ TAG_Add(ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0); - //Delete immediately, cannot be refered to as an entity again - //NOTE: this means if you wanted to link them in a chain for, say, a path, you can't - G_FreeEntity( ent ); + // Delete immediately, cannot be refered to as an entity again + // NOTE: this means if you wanted to link them in a chain for, say, a path, you can't + G_FreeEntity(ent); } -void SP_reference_tag ( gentity_t *ent ) -{ - if ( ent->target ) - { - //Init cannot occur until all entities have been spawned +void SP_reference_tag(gentity_t *ent) { + if (ent->target) { + // Init cannot occur until all entities have been spawned ent->e_ThinkFunc = thinkF_ref_link; ent->nextthink = level.time + START_TIME_LINK_ENTS; - } - else - { - ref_link( ent ); + } else { + ref_link(ent); } } \ No newline at end of file diff --git a/code/game/g_roff.cpp b/code/game/g_roff.cpp index 5dd6381f42..84cc1de277 100644 --- a/code/game/g_roff.cpp +++ b/code/game/g_roff.cpp @@ -28,18 +28,15 @@ along with this program; if not, see . #include "g_functions.h" #include "qcommon/ojk_saved_game_helper.h" - // The list of precached ROFFs -roff_list_t roffs[MAX_ROFFS]; -int num_roffs = 0; +roff_list_t roffs[MAX_ROFFS]; +int num_roffs = 0; qboolean g_bCollidableRoffs = qfalse; -extern void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ); - +extern void Q3_TaskIDComplete(gentity_t *ent, taskID_t taskType); -static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) -{ +static void G_RoffNotetrackCallback(gentity_t *ent, const char *notetrack) { int i = 0, r = 0, r2 = 0, objectID = 0, anglesGathered = 0, posoffsetGathered = 0; char type[256]; char argument[512]; @@ -50,19 +47,18 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) int addlArgs = 0; vec3_t parsedAngles, parsedOffset, useAngles, useOrigin, forward, right, up; - if (!ent || !notetrack) - { + if (!ent || !notetrack) { return; } ////////////////////////////////////////////////////////////////////////////////////////////////////////// - //Supported notetrack types: effect, sound, USE, loop + // Supported notetrack types: effect, sound, USE, loop // - //General notetrack format: [additionalArguments] - //Note: <> denote required argument, [] denote optional argument, | denotes argument choices + // General notetrack format: [additionalArguments] + // Note: <> denote required argument, [] denote optional argument, | denotes argument choices // - //Examples: - //effect notetrack format: effect [originOffset] [rotationOffset] + // Examples: + // effect notetrack format: effect [originOffset] [rotationOffset] // notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; //'effect' notes: // (1) the '+' and '-' are delimiters and not positive/negative signs; e.g., negative origin offset would be: -10+-20+-10 @@ -70,23 +66,23 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) // (3) optional additional argument for rotationOffset requires the originOffset preceding it. // // - //sound notetrack format: sound + // sound notetrack format: sound // notetrack = "sound sound/vehicles/tie/flyby2.mp3"; //'sound' notes: // (1) supported sound file formats are: .mp3, .wav // // - //USE notetrack format: USE + // USE notetrack format: USE // notetrack = "USE shuttlemap/shuttletakeoff"; // // - //loop notetrack format: loop < absolute | relative > + // loop notetrack format: loop < absolute | relative > // loop < relative_soundfilepath.ext | kill > // notetrack = "loop rof absolute"; // notetrack = "loop rof relative"; // notetrack = "loop sfx sound/vehicles/tie/loop.wav"; // notetrack = "loop sfx kill"; - //'loop rof' notes: + //'loop rof' notes: // (1) absolute ==> reset rof to original delta position/rotation world location before looping. // (2) relative ==> reset rof to original delta position/rotation at current location before looping. //'loop sfx' notes: @@ -95,25 +91,21 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) // ////////////////////////////////////////////////////////////////////////////////////////////////////////// - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (notetrack[i] != ' ') - { //didn't pass in a valid notetrack type, or forgot the argument for it + if (notetrack[i] != ' ') { // didn't pass in a valid notetrack type, or forgot the argument for it return; } i++; - while (notetrack[i] && notetrack[i] != ' ') - { - if (notetrack[i] != '\n' && notetrack[i] != '\r') - { //don't read line ends for an argument + while (notetrack[i] && notetrack[i] != ' ') { + if (notetrack[i] != '\n' && notetrack[i] != '\r') { // don't read line ends for an argument argument[r] = notetrack[i]; r++; } @@ -121,19 +113,16 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) } argument[r] = '\0'; - if (!r) - { + if (!r) { return; } - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -141,29 +130,24 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "effect") == 0) - { - if (!addlArgs) - { + if (strcmp(type, "effect") == 0) { + if (!addlArgs) { VectorClear(parsedOffset); goto defaultoffsetposition; } i = 0; - while (posoffsetGathered < 3) - { + while (posoffsetGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') - { + while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') { t[r] = addlArg[i]; r++; i++; } t[r] = '\0'; i++; - if (!r) - { //failure... + if (!r) { // failure... VectorClear(parsedOffset); i = 0; goto defaultoffsetposition; @@ -172,41 +156,35 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) posoffsetGathered++; } - if (posoffsetGathered < 3) - { + if (posoffsetGathered < 3) { sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); goto functionend; } i--; - if (addlArg[i] != ' ') - { + if (addlArg[i] != ' ') { addlArgs = 0; } -defaultoffsetposition: + defaultoffsetposition: r = 0; - if (argument[r] == '/') - { + if (argument[r] == '/') { r++; } - while (argument[r] && argument[r] != '/') - { + while (argument[r] && argument[r] != '/') { teststr[r2] = argument[r]; r2++; r++; } teststr[r2] = '\0'; - if (r2 && strstr(teststr, "effects")) - { //get rid of the leading "effects" since it's auto-inserted + if (r2 && strstr(teststr, "effects")) { // get rid of the leading "effects" since it's auto-inserted r++; r2 = 0; - while (argument[r]) - { + while (argument[r]) { teststr[r2] = argument[r]; r2++; r++; @@ -219,16 +197,12 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) objectID = G_EffectIndex(argument); r = 0; - if (objectID) - { - if (addlArgs) - { //if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE + if (objectID) { + if (addlArgs) { // if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE i++; - while (anglesGathered < 3) - { + while (anglesGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '-') - { + while (addlArg[i] && addlArg[i] != '-') { t[r] = addlArg[i]; r++; i++; @@ -236,8 +210,7 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) t[r] = '\0'; i++; - if (!r) - { //failed to get a new part of the vector + if (!r) { // failed to get a new part of the vector anglesGathered = 0; break; } @@ -246,17 +219,12 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) anglesGathered++; } - if (anglesGathered) - { + if (anglesGathered) { VectorCopy(parsedAngles, useAngles); - } - else - { //failed to parse angles from the extra argument provided... + } else { // failed to parse angles from the extra argument provided... VectorCopy(ent->s.apos.trBase, useAngles); } - } - else - { //if no constant angles, play in direction entity is facing + } else { // if no constant angles, play in direction entity is facing VectorCopy(ent->s.apos.trBase, useAngles); } @@ -264,66 +232,52 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) VectorCopy(ent->s.pos.trBase, useOrigin); - //forward - useOrigin[0] += forward[0]*parsedOffset[0]; - useOrigin[1] += forward[1]*parsedOffset[0]; - useOrigin[2] += forward[2]*parsedOffset[0]; + // forward + useOrigin[0] += forward[0] * parsedOffset[0]; + useOrigin[1] += forward[1] * parsedOffset[0]; + useOrigin[2] += forward[2] * parsedOffset[0]; - //right - useOrigin[0] += right[0]*parsedOffset[1]; - useOrigin[1] += right[1]*parsedOffset[1]; - useOrigin[2] += right[2]*parsedOffset[1]; + // right + useOrigin[0] += right[0] * parsedOffset[1]; + useOrigin[1] += right[1] * parsedOffset[1]; + useOrigin[2] += right[2] * parsedOffset[1]; - //up - useOrigin[0] += up[0]*parsedOffset[2]; - useOrigin[1] += up[1]*parsedOffset[2]; - useOrigin[2] += up[2]*parsedOffset[2]; + // up + useOrigin[0] += up[0] * parsedOffset[2]; + useOrigin[1] += up[1] * parsedOffset[2]; + useOrigin[2] += up[2] * parsedOffset[2]; - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } G_PlayEffect(objectID, useOrigin, useAngles); } - } - else if (strcmp(type, "sound") == 0) - { - if (g_developer->integer) - { + } else if (strcmp(type, "sound") == 0) { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } - //check for eType and play the sound - if (ent->s.eType == ET_MOVER) - { + // check for eType and play the sound + if (ent->s.eType == ET_MOVER) { objectID = cgi_S_RegisterSound(argument); cgi_S_StartSound(ent->s.pos.trBase, ent->s.number, CHAN_BODY, objectID); - } - else - { + } else { G_SoundOnEnt(ent, CHAN_BODY, argument); } - } - else if (strcmp(type, "USE") == 0) - { - //try to cache the script + } else if (strcmp(type, "USE") == 0) { + // try to cache the script Quake3Game()->PrecacheScript(argument); - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } - //run the IBI script + // run the IBI script Quake3Game()->RunScript(ent, argument); - } - else if (strcmp(type, "loop") == 0) - { - if (strcmp(argument, "rof") == 0) - { - if (strcmp(addlArg, "absolute") == 0) - { + } else if (strcmp(type, "loop") == 0) { + if (strcmp(argument, "rof") == 0) { + if (strcmp(addlArg, "absolute") == 0) { VectorClear(ent->pos1); VectorClear(ent->pos2); @@ -335,16 +289,12 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) VectorClear(ent->s.origin2); VectorClear(ent->s.angles2); - } - else if (strcmp(addlArg, "relative") == 0) - { + } else if (strcmp(addlArg, "relative") == 0) { VectorCopy(ent->s.origin2, ent->s.pos.trBase); VectorCopy(ent->s.origin2, ent->currentOrigin); VectorCopy(ent->s.angles2, ent->s.apos.trBase); VectorCopy(ent->s.angles2, ent->currentAngles); - } - else - { + } else { sprintf(errMsg, "Invalid additional argument <%s> for type 'loop rof'", addlArg); goto functionend; } @@ -355,122 +305,94 @@ static void G_RoffNotetrackCallback( gentity_t *ent, const char *notetrack) // Let the ROFF playing start ent->next_roff_time = level.time; - //Re-link entity + // Re-link entity gi.linkentity(ent); - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } // Re-apply the ROFF G_Roff(ent); - } - else if (strcmp(argument, "sfx") == 0) - { - //check additional argument for relative sound path + } else if (strcmp(argument, "sfx") == 0) { + // check additional argument for relative sound path r = 0; r2 = 0; - if (addlArg[r] == '/') - { + if (addlArg[r] == '/') { r++; } - while (addlArg[r] && addlArg[r] != '/') - { + while (addlArg[r] && addlArg[r] != '/') { teststr[r2] = addlArg[r]; r2++; r++; } teststr[r2] = '\0'; - if (r2 && strstr(teststr, "kill")) - { // kill the looping sound + if (r2 && strstr(teststr, "kill")) { // kill the looping sound ent->s.loopSound = 0; - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } - } - else if (r2 && strstr(teststr, "sound")) - { // OK... we should have a relative sound path - //try to register the sound and add it to the entitystate loopSound parameter - if (ent->s.eType == ET_MOVER) - { + } else if (r2 && strstr(teststr, "sound")) { // OK... we should have a relative sound path + // try to register the sound and add it to the entitystate loopSound parameter + if (ent->s.eType == ET_MOVER) { objectID = cgi_S_RegisterSound(addlArg); - if (objectID) - { + if (objectID) { ent->s.loopSound = objectID; - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } - } - else - { + } else { ent->s.loopSound = 0; - sprintf(errMsg, "cgi_S_RegisterSound(%s) failed to return a valid sfxHandle_t for additional argument. Setting 'loopSound' to 0.", addlArg); + sprintf(errMsg, "cgi_S_RegisterSound(%s) failed to return a valid sfxHandle_t for additional argument. Setting 'loopSound' to 0.", + addlArg); goto functionend; } - } - else - { + } else { ent->s.loopSound = G_SoundIndex(addlArg); - if (g_developer->integer) - { + if (g_developer->integer) { Com_Printf(S_COLOR_GREEN "NoteTrack: \"%s\"\n", notetrack); } } - } - else - { + } else { sprintf(errMsg, "Invalid additional argument <%s> for type 'loop sfx'", addlArg); goto functionend; } - } - else - { + } else { sprintf(errMsg, "Invalid argument <%s> for type 'loop' notetrack.", argument); goto functionend; } } - //else if ... - else - { - if (type[0]) - { - Com_Printf(S_COLOR_YELLOW"Warning: \"%s\" is an invalid ROFF NoteTrack function\n", type); - } - else - { - Com_Printf(S_COLOR_YELLOW"Warning: NoteTrack is missing function and/or arguments\n"); + // else if ... + else { + if (type[0]) { + Com_Printf(S_COLOR_YELLOW "Warning: \"%s\" is an invalid ROFF NoteTrack function\n", type); + } else { + Com_Printf(S_COLOR_YELLOW "Warning: NoteTrack is missing function and/or arguments\n"); } } return; functionend: - Com_Printf(S_COLOR_RED"Type-specific NoteTrack error: %s\n", errMsg); + Com_Printf(S_COLOR_RED "Type-specific NoteTrack error: %s\n", errMsg); return; } - //------------------------------------------------------- // G_ValidRoff // // Checks header to verify we have a valid .ROF file //------------------------------------------------------- -static qboolean G_ValidRoff( roff_hdr2_t *header ) -{ - if ( !strncmp( header->mHeader, "ROFF", 4 )) - { - if ( LittleLong(header->mVersion) == ROFF_VERSION2 && LittleLong(header->mCount) > 0 ) - { +static qboolean G_ValidRoff(roff_hdr2_t *header) { + if (!strncmp(header->mHeader, "ROFF", 4)) { + if (LittleLong(header->mVersion) == ROFF_VERSION2 && LittleLong(header->mCount) > 0) { return qtrue; - } - else if ( LittleLong(header->mVersion) == ROFF_VERSION && LittleFloat(((roff_hdr_t*)header)->mCount) > 0.0f ) - { // version 1 defines the count as a float, so we best do the count check as a float or we'll get bogus results + } else if (LittleLong(header->mVersion) == ROFF_VERSION && + LittleFloat(((roff_hdr_t *)header)->mCount) > + 0.0f) { // version 1 defines the count as a float, so we best do the count check as a float or we'll get bogus results return qtrue; } } @@ -478,62 +400,55 @@ static qboolean G_ValidRoff( roff_hdr2_t *header ) return qfalse; } - //------------------------------------------------------- // G_FreeRoff // // Deletes all .ROF files from memory //------------------------------------------------------- -static void G_FreeRoff(int index) -{ - if(roffs[index].mNumNoteTracks) { - delete [] roffs[index].mNoteTrackIndexes[0]; - delete [] roffs[index].mNoteTrackIndexes; +static void G_FreeRoff(int index) { + if (roffs[index].mNumNoteTracks) { + delete[] roffs[index].mNoteTrackIndexes[0]; + delete[] roffs[index].mNoteTrackIndexes; } } - //------------------------------------------------------- // G_InitRoff // // Initializes the .ROF file //------------------------------------------------------- -static qboolean G_InitRoff( char *file, unsigned char *data ) -{ +static qboolean G_InitRoff(char *file, unsigned char *data) { roff_hdr_t *header = (roff_hdr_t *)data; - int count; + int count; int i; - roffs[num_roffs].fileName = G_NewString( file ); + roffs[num_roffs].fileName = G_NewString(file); - if ( LittleLong(header->mVersion) == ROFF_VERSION ) - { + if (LittleLong(header->mVersion) == ROFF_VERSION) { count = (int)LittleFloat(header->mCount); // We are Old School(tm) roffs[num_roffs].type = 1; - roffs[num_roffs].data = (void *) G_Alloc( count * sizeof( move_rotate_t ) ); - move_rotate_t *mem = (move_rotate_t *)roffs[num_roffs].data; + roffs[num_roffs].data = (void *)G_Alloc(count * sizeof(move_rotate_t)); + move_rotate_t *mem = (move_rotate_t *)roffs[num_roffs].data; roffs[num_roffs].mFrameTime = 100; // old school ones have a hard-coded frame time roffs[num_roffs].mLerp = 10; roffs[num_roffs].mNumNoteTracks = 0; roffs[num_roffs].mNoteTrackIndexes = NULL; - if ( mem ) - { + if (mem) { // The allocation worked, so stash this stuff off so we can reference the data later if needed - roffs[num_roffs].frames = count; + roffs[num_roffs].frames = count; // Step past the header to get to the goods - move_rotate_t *roff_data = ( move_rotate_t *)&header[1]; + move_rotate_t *roff_data = (move_rotate_t *)&header[1]; // Copy all of the goods into our ROFF cache - for ( i = 0; i < count; i++, roff_data++, mem++ ) - { + for (i = 0; i < count; i++, roff_data++, mem++) { // Copy just the delta position and orientation which can be applied to anything at a later point #ifdef Q3_BIG_ENDIAN mem->origin_delta[0] = LittleFloat(roff_data->origin_delta[0]); @@ -543,43 +458,38 @@ static qboolean G_InitRoff( char *file, unsigned char *data ) mem->rotate_delta[1] = LittleFloat(roff_data->rotate_delta[1]); mem->rotate_delta[2] = LittleFloat(roff_data->rotate_delta[2]); #else - VectorCopy( roff_data->origin_delta, mem->origin_delta ); - VectorCopy( roff_data->rotate_delta, mem->rotate_delta ); + VectorCopy(roff_data->origin_delta, mem->origin_delta); + VectorCopy(roff_data->rotate_delta, mem->rotate_delta); #endif } return qtrue; } - } - else if ( LittleLong(header->mVersion) == ROFF_VERSION2 ) - { + } else if (LittleLong(header->mVersion) == ROFF_VERSION2) { // Version 2.0, heck yeah! roff_hdr2_t *hdr = (roff_hdr2_t *)data; count = LittleLong(hdr->mCount); - roffs[num_roffs].frames = count; - roffs[num_roffs].data = (void *) G_Alloc( count * sizeof( move_rotate2_t )); - move_rotate2_t *mem = (move_rotate2_t *)roffs[num_roffs].data; + roffs[num_roffs].frames = count; + roffs[num_roffs].data = (void *)G_Alloc(count * sizeof(move_rotate2_t)); + move_rotate2_t *mem = (move_rotate2_t *)roffs[num_roffs].data; - if ( mem ) - { - roffs[num_roffs].mFrameTime = LittleLong(hdr->mFrameRate); - roffs[num_roffs].mLerp = 1000 / LittleLong(hdr->mFrameRate); - roffs[num_roffs].mNumNoteTracks = LittleLong(hdr->mNumNotes); + if (mem) { + roffs[num_roffs].mFrameTime = LittleLong(hdr->mFrameRate); + roffs[num_roffs].mLerp = 1000 / LittleLong(hdr->mFrameRate); + roffs[num_roffs].mNumNoteTracks = LittleLong(hdr->mNumNotes); - if (roffs[num_roffs].mFrameTime < 50) - { - Com_Printf(S_COLOR_RED"Error: \"%s\" has an invalid ROFF framerate (%d < 50)\n", file, roffs[num_roffs].mFrameTime); + if (roffs[num_roffs].mFrameTime < 50) { + Com_Printf(S_COLOR_RED "Error: \"%s\" has an invalid ROFF framerate (%d < 50)\n", file, roffs[num_roffs].mFrameTime); } - assert( roffs[num_roffs].mFrameTime >= 50 );//HAS to be at least 50 to be reliable + assert(roffs[num_roffs].mFrameTime >= 50); // HAS to be at least 50 to be reliable - // Step past the header to get to the goods - move_rotate2_t *roff_data = ( move_rotate2_t *)&hdr[1]; + // Step past the header to get to the goods + move_rotate2_t *roff_data = (move_rotate2_t *)&hdr[1]; - roffs[num_roffs].type = 2; //rww - any reason this wasn't being set already? + roffs[num_roffs].type = 2; // rww - any reason this wasn't being set already? // Copy all of the goods into our ROFF cache - for ( i = 0; i < count; i++ ) - { + for (i = 0; i < count; i++) { #ifdef Q3_BIG_ENDIAN mem[i].origin_delta[0] = LittleFloat(roff_data[i].origin_delta[0]); mem[i].origin_delta[1] = LittleFloat(roff_data[i].origin_delta[1]); @@ -588,24 +498,22 @@ static qboolean G_InitRoff( char *file, unsigned char *data ) mem[i].rotate_delta[1] = LittleFloat(roff_data[i].rotate_delta[1]); mem[i].rotate_delta[2] = LittleFloat(roff_data[i].rotate_delta[2]); #else - VectorCopy( roff_data[i].origin_delta, mem[i].origin_delta ); - VectorCopy( roff_data[i].rotate_delta, mem[i].rotate_delta ); + VectorCopy(roff_data[i].origin_delta, mem[i].origin_delta); + VectorCopy(roff_data[i].rotate_delta, mem[i].rotate_delta); #endif mem[i].mStartNote = LittleLong(roff_data[i].mStartNote); mem[i].mNumNotes = LittleLong(roff_data[i].mNumNotes); } - if ( LittleLong(hdr->mNumNotes) ) - { - int size; - char *ptr, *start; + if (LittleLong(hdr->mNumNotes)) { + int size; + char *ptr, *start; ptr = start = (char *)&roff_data[i]; size = 0; - for( i = 0; i < LittleLong(hdr->mNumNotes); i++ ) - { + for (i = 0; i < LittleLong(hdr->mNumNotes); i++) { size += strlen(ptr) + 1; ptr += strlen(ptr) + 1; } @@ -615,8 +523,7 @@ static qboolean G_InitRoff( char *file, unsigned char *data ) ptr = roffs[num_roffs].mNoteTrackIndexes[0] = new char[size]; memcpy(roffs[num_roffs].mNoteTrackIndexes[0], start, size); - for( i = 1; i < LittleLong(hdr->mNumNotes); i++ ) - { + for (i = 1; i < LittleLong(hdr->mNumNotes); i++) { ptr += strlen(ptr) + 1; roffs[num_roffs].mNoteTrackIndexes[i] = ptr; } @@ -629,7 +536,6 @@ static qboolean G_InitRoff( char *file, unsigned char *data ) return qfalse; } - //------------------------------------------------------- // G_LoadRoff // @@ -638,27 +544,23 @@ static qboolean G_InitRoff( char *file, unsigned char *data ) // ID to the cached file. //------------------------------------------------------- -int G_LoadRoff( const char *fileName ) -{ - char file[MAX_QPATH]; - byte *data; - int len, i, roff_id = 0; +int G_LoadRoff(const char *fileName) { + char file[MAX_QPATH]; + byte *data; + int len, i, roff_id = 0; // Before even bothering with all of this, make sure we have a place to store it. - if ( num_roffs >= MAX_ROFFS ) - { - Com_Printf( S_COLOR_RED"MAX_ROFFS count exceeded. Skipping load of .ROF '%s'\n", fileName ); + if (num_roffs >= MAX_ROFFS) { + Com_Printf(S_COLOR_RED "MAX_ROFFS count exceeded. Skipping load of .ROF '%s'\n", fileName); return roff_id; } // The actual path - sprintf( file, "%s/%s.rof", Q3_SCRIPT_DIR, fileName ); + sprintf(file, "%s/%s.rof", Q3_SCRIPT_DIR, fileName); // See if I'm already precached - for ( i = 0; i < num_roffs; i++ ) - { - if ( Q_stricmp( file, roffs[i].fileName ) == 0 ) - { + for (i = 0; i < num_roffs; i++) { + if (Q_stricmp(file, roffs[i].fileName) == 0) { // Good, just return me...avoid zero index return i + 1; } @@ -669,11 +571,10 @@ int G_LoadRoff( const char *fileName ) #endif // Read the file in one fell swoop - len = gi.FS_ReadFile( file, (void**) &data); + len = gi.FS_ReadFile(file, (void **)&data); - if ( len <= 0 ) - { - Com_Printf( S_COLOR_RED"Could not open .ROF file '%s'\n", fileName ); + if (len <= 0) { + Com_Printf(S_COLOR_RED "Could not open .ROF file '%s'\n", fileName); return roff_id; } @@ -681,173 +582,147 @@ int G_LoadRoff( const char *fileName ) roff_hdr2_t *header = (roff_hdr2_t *)data; // ..and make sure it's reasonably valid - if ( !G_ValidRoff( header )) - { - Com_Printf( S_COLOR_RED"Invalid .ROF format '%s'\n", fileName ); - } - else - { - G_InitRoff( file, data ); + if (!G_ValidRoff(header)) { + Com_Printf(S_COLOR_RED "Invalid .ROF format '%s'\n", fileName); + } else { + G_InitRoff(file, data); // Done loading this roff, so save off an id to it..increment first to avoid zero index roff_id = ++num_roffs; } - gi.FS_FreeFile( data ); + gi.FS_FreeFile(data); return roff_id; } - -void G_FreeRoffs(void) -{ - while(num_roffs) { +void G_FreeRoffs(void) { + while (num_roffs) { G_FreeRoff(num_roffs - 1); num_roffs--; } } - //------------------------------------------------------- // G_Roff // // Handles applying the roff data to the specified ent //------------------------------------------------------- -void G_Roff( gentity_t *ent ) -{ - if ( !ent->next_roff_time ) - { +void G_Roff(gentity_t *ent) { + if (!ent->next_roff_time) { return; } - if ( ent->next_roff_time > level.time ) - {// either I don't think or it's just not time to have me think yet + if (ent->next_roff_time > level.time) { // either I don't think or it's just not time to have me think yet return; } - const int roff_id = G_LoadRoff( ent->roff ); + const int roff_id = G_LoadRoff(ent->roff); - if ( !roff_id ) - { // Couldn't cache this rof + if (!roff_id) { // Couldn't cache this rof return; } // The ID is one higher than the array index - const roff_list_t * roff = &roffs[ roff_id - 1 ]; - vec3_t org, ang; - - if ( roff->type == 2 ) - { - move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ ent->roff_ctr ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); - - if ( data->mStartNote != -1 ) - { - for ( int n = 0; n < data->mNumNotes; n++ ) - { + const roff_list_t *roff = &roffs[roff_id - 1]; + vec3_t org, ang; + + if (roff->type == 2) { + move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ent->roff_ctr]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); + + if (data->mStartNote != -1) { + for (int n = 0; n < data->mNumNotes; n++) { G_RoffNotetrackCallback(ent, roffs[roff_id - 1].mNoteTrackIndexes[data->mStartNote + n]); } } - } - else - { - move_rotate_t *data = &((move_rotate_t *)roff->data)[ ent->roff_ctr ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); + } else { + move_rotate_t *data = &((move_rotate_t *)roff->data)[ent->roff_ctr]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); } #ifdef _DEBUG - if ( g_developer->integer ) - { - Com_Printf( S_COLOR_GREEN"ROFF dat: num: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", - ent->roff_ctr, - org[0], org[1], org[2], - ang[0], ang[1], ang[2] ); + if (g_developer->integer) { + Com_Printf(S_COLOR_GREEN "ROFF dat: num: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", ent->roff_ctr, org[0], org[1], org[2], ang[0], ang[1], ang[2]); } #endif - if ( ent->client ) - { + if (ent->client) { // Set up the angle interpolation //------------------------------------- - VectorAdd( ent->s.apos.trBase, ang, ent->s.apos.trBase ); + VectorAdd(ent->s.apos.trBase, ang, ent->s.apos.trBase); ent->s.apos.trTime = level.time; ent->s.apos.trType = TR_INTERPOLATE; // Store what the next apos->trBase should be - VectorCopy( ent->s.apos.trBase, ent->client->ps.viewangles ); - VectorCopy( ent->s.apos.trBase, ent->currentAngles ); - VectorCopy( ent->s.apos.trBase, ent->s.angles ); - if ( ent->NPC ) - { - //ent->NPC->desiredPitch = ent->s.apos.trBase[PITCH]; + VectorCopy(ent->s.apos.trBase, ent->client->ps.viewangles); + VectorCopy(ent->s.apos.trBase, ent->currentAngles); + VectorCopy(ent->s.apos.trBase, ent->s.angles); + if (ent->NPC) { + // ent->NPC->desiredPitch = ent->s.apos.trBase[PITCH]; ent->NPC->desiredYaw = ent->s.apos.trBase[YAW]; } // Set up the origin interpolation //------------------------------------- - VectorAdd( ent->s.pos.trBase, org, ent->s.pos.trBase ); + VectorAdd(ent->s.pos.trBase, org, ent->s.pos.trBase); ent->s.pos.trTime = level.time; ent->s.pos.trType = TR_INTERPOLATE; // Store what the next pos->trBase should be - VectorCopy( ent->s.pos.trBase, ent->client->ps.origin ); - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); - //VectorCopy( ent->s.pos.trBase, ent->s.origin ); - } - else - { + VectorCopy(ent->s.pos.trBase, ent->client->ps.origin); + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); + // VectorCopy( ent->s.pos.trBase, ent->s.origin ); + } else { // Set up the angle interpolation //------------------------------------- - VectorScale( ang, roff->mLerp, ent->s.apos.trDelta ); - VectorCopy( ent->pos2, ent->s.apos.trBase ); + VectorScale(ang, roff->mLerp, ent->s.apos.trDelta); + VectorCopy(ent->pos2, ent->s.apos.trBase); ent->s.apos.trTime = level.time; ent->s.apos.trType = TR_LINEAR; // Store what the next apos->trBase should be - VectorAdd( ent->pos2, ang, ent->pos2 ); + VectorAdd(ent->pos2, ang, ent->pos2); // Set up the origin interpolation //------------------------------------- - VectorScale( org, roff->mLerp, ent->s.pos.trDelta ); - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorScale(org, roff->mLerp, ent->s.pos.trDelta); + VectorCopy(ent->pos1, ent->s.pos.trBase); ent->s.pos.trTime = level.time; ent->s.pos.trType = TR_LINEAR; // Store what the next apos->trBase should be - VectorAdd( ent->pos1, org, ent->pos1 ); + VectorAdd(ent->pos1, org, ent->pos1); - //make it true linear... FIXME: sticks around after ROFF is done, but do we really care? + // make it true linear... FIXME: sticks around after ROFF is done, but do we really care? ent->alt_fire = qtrue; - if ( ent->e_ThinkFunc == thinkF_TieFighterThink || ent->e_ThinkFunc == thinkF_TieBomberThink || - ( !ent->e_ThinkFunc - && ent->s.eType != ET_MISSILE - && ent->s.eType != ET_ITEM - && ent->s.eType != ET_MOVER ) ) - {//will never set currentAngles & currentOrigin itself ( why do we limit which one's get set?, just set all the time? ) - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); + if (ent->e_ThinkFunc == thinkF_TieFighterThink || ent->e_ThinkFunc == thinkF_TieBomberThink || + (!ent->e_ThinkFunc && ent->s.eType != ET_MISSILE && ent->s.eType != ET_ITEM && + ent->s.eType != + ET_MOVER)) { // will never set currentAngles & currentOrigin itself ( why do we limit which one's get set?, just set all the time? ) + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); } } // Link just in case. - gi.linkentity( ent ); + gi.linkentity(ent); // See if the ROFF playback is done //------------------------------------- - if ( ++ent->roff_ctr >= roff->frames ) - { + if (++ent->roff_ctr >= roff->frames) { // We are done, so let me think no more, then tell the task that we're done. ent->next_roff_time = 0; // Stop any rotation or movement. - VectorClear( ent->s.pos.trDelta ); - VectorClear( ent->s.apos.trDelta ); + VectorClear(ent->s.pos.trDelta); + VectorClear(ent->s.apos.trDelta); - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); + Q3_TaskIDComplete(ent, TID_MOVE_NAV); return; } @@ -855,79 +730,56 @@ void G_Roff( gentity_t *ent ) ent->next_roff_time = level.time + roff->mFrameTime; } - //------------------------------------------------------- // G_SaveCachedRoffs // // Really fun savegame stuff //------------------------------------------------------- -void G_SaveCachedRoffs() -{ +void G_SaveCachedRoffs() { int i, len = 0; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // Write out the number of cached ROFFs - saved_game.write_chunk( - INT_ID('R', 'O', 'F', 'F'), - ::num_roffs); + saved_game.write_chunk(INT_ID('R', 'O', 'F', 'F'), ::num_roffs); // Now dump out the cached ROFF file names in order so they can be loaded on the other end - for ( i = 0; i < num_roffs; i++ ) - { + for (i = 0; i < num_roffs; i++) { // Dump out the string length to make things a bit easier on the other end...heh heh. - len = strlen( roffs[i].fileName ) + 1; + len = strlen(roffs[i].fileName) + 1; - saved_game.write_chunk( - INT_ID('S', 'L', 'E', 'N'), - len); + saved_game.write_chunk(INT_ID('S', 'L', 'E', 'N'), len); - saved_game.write_chunk( - INT_ID('R', 'S', 'T', 'R'), - roffs[i].fileName, - len); + saved_game.write_chunk(INT_ID('R', 'S', 'T', 'R'), roffs[i].fileName, len); } } - //------------------------------------------------------- // G_LoadCachedRoffs // // Really fun loadgame stuff //------------------------------------------------------- -void G_LoadCachedRoffs() -{ - int i, count = 0, len = 0; - char buffer[MAX_QPATH]; +void G_LoadCachedRoffs() { + int i, count = 0, len = 0; + char buffer[MAX_QPATH]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // Get the count of goodies we need to revive - saved_game.read_chunk( - INT_ID('R', 'O', 'F', 'F'), - count); + saved_game.read_chunk(INT_ID('R', 'O', 'F', 'F'), count); // Now bring 'em back to life - for ( i = 0; i < count; i++ ) - { - saved_game.read_chunk( - INT_ID('S', 'L', 'E', 'N'), - len); - - if (len < 0 || static_cast(len) >= sizeof(buffer)) - { + for (i = 0; i < count; i++) { + saved_game.read_chunk(INT_ID('S', 'L', 'E', 'N'), len); + + if (len < 0 || static_cast(len) >= sizeof(buffer)) { ::G_Error("invalid length for RSTR string in save game: %d bytes\n", len); } - saved_game.read_chunk( - INT_ID('R', 'S', 'T', 'R'), - buffer, - len); + saved_game.read_chunk(INT_ID('R', 'S', 'T', 'R'), buffer, len); - G_LoadRoff( buffer ); + G_LoadRoff(buffer); } } diff --git a/code/game/g_savegame.cpp b/code/game/g_savegame.cpp index 0b3d0dbed4..7fcd4f14b1 100644 --- a/code/game/g_savegame.cpp +++ b/code/game/g_savegame.cpp @@ -36,170 +36,146 @@ extern void OBJ_LoadTacticalInfo(void); extern void G_LoadSave_WriteMiscData(void); extern void G_LoadSave_ReadMiscData(void); -extern void G_ReloadSaberData( gentity_t *ent ); -extern void FX_Read( void ); -extern void FX_Write( void ); - - -static const save_field_t savefields_gEntity[] = -{ - {strFOFS(client), F_GCLIENT}, - {strFOFS(owner), F_GENTITY}, - {strFOFS(classname), F_STRING}, - {strFOFS(model), F_STRING}, - {strFOFS(model2), F_STRING}, -// {strFOFS(model3), F_STRING}, - MCG - {strFOFS(nextTrain), F_GENTITY}, - {strFOFS(prevTrain), F_GENTITY}, - {strFOFS(message), F_STRING}, - {strFOFS(target), F_STRING}, - {strFOFS(target2), F_STRING}, - {strFOFS(target3), F_STRING}, - {strFOFS(target4), F_STRING}, - {strFOFS(targetJump), F_STRING}, - {strFOFS(targetname), F_STRING}, - {strFOFS(team), F_STRING}, - {strFOFS(roff), F_STRING}, -// {strFOFS(target_ent), F_GENTITY}, - MCG - {strFOFS(chain), F_GENTITY}, - {strFOFS(enemy), F_GENTITY}, - {strFOFS(activator), F_GENTITY}, - {strFOFS(teamchain), F_GENTITY}, - {strFOFS(teammaster), F_GENTITY}, - {strFOFS(item), F_ITEM}, - {strFOFS(NPC_type), F_STRING}, - {strFOFS(closetarget), F_STRING}, - {strFOFS(opentarget), F_STRING}, - {strFOFS(paintarget), F_STRING}, - {strFOFS(NPC_targetname), F_STRING}, - {strFOFS(NPC_target), F_STRING}, - {strFOFS(ownername), F_STRING}, - {strFOFS(lastEnemy), F_GENTITY}, - {strFOFS(behaviorSet), F_BEHAVIORSET}, - {strFOFS(script_targetname),F_STRING}, - {strFOFS(m_iIcarusID), F_NULL}, - {strFOFS(NPC), F_BOOLPTR}, - {strFOFS(soundSet), F_STRING}, - {strFOFS(cameraGroup), F_STRING}, - {strFOFS(parms), F_BOOLPTR}, - {strFOFS(m_pVehicle), F_BOOLPTR}, - - {NULL, 0, F_IGNORE} -}; - -static const save_field_t savefields_gNPC[] = -{ -// {strNPCOFS(pendingEnemy), F_GENTITY}, - {strNPCOFS(touchedByPlayer), F_GENTITY}, - {strNPCOFS(aimingBeam), F_GENTITY}, - {strNPCOFS(eventOwner), F_GENTITY}, - {strNPCOFS(coverTarg), F_GENTITY}, - {strNPCOFS(tempGoal), F_GENTITY}, - {strNPCOFS(goalEntity), F_GENTITY}, - {strNPCOFS(lastGoalEntity), F_GENTITY}, - {strNPCOFS(eventualGoal), F_GENTITY}, - {strNPCOFS(captureGoal), F_GENTITY}, - {strNPCOFS(defendEnt), F_GENTITY}, - {strNPCOFS(greetEnt), F_GENTITY}, - {strNPCOFS(group), F_GROUP}, - {strNPCOFS(blockedEntity), F_GENTITY}, - {strNPCOFS(blockedTargetEntity),F_GENTITY}, - {strNPCOFS(jumpTarget), F_GENTITY}, - {strNPCOFS(watchTarget), F_GENTITY}, - {NULL, 0, F_IGNORE} -}; - -static const save_field_t savefields_LevelLocals[] = -{ - {strLLOFS(locationHead), F_GENTITY}, - {strLLOFS(alertEvents), F_ALERTEVENT}, - {strLLOFS(groups), F_AIGROUPS}, - {strLLOFS(knownAnimFileSets),F_ANIMFILESETS}, - {NULL, 0, F_IGNORE} -}; - -static const save_field_t savefields_gVHIC[] = -{ - {strVHICOFS(m_pPilot), F_GENTITY}, - {strVHICOFS(m_pOldPilot), F_GENTITY}, - {strVHICOFS(m_pDroidUnit), F_GENTITY}, - {strVHICOFS(m_pParentEntity), F_GENTITY}, - - //m_ppPassengers //!ptr array?! - {strVHICOFS(m_pVehicleInfo), F_VEHINFO}, //!another ptr! store name field instead and re-hook on load? - - {NULL, 0, F_IGNORE} -}; - -static const save_field_t savefields_gClient[] = -{ +extern void G_ReloadSaberData(gentity_t *ent); +extern void FX_Read(void); +extern void FX_Write(void); + +static const save_field_t savefields_gEntity[] = {{strFOFS(client), F_GCLIENT}, + {strFOFS(owner), F_GENTITY}, + {strFOFS(classname), F_STRING}, + {strFOFS(model), F_STRING}, + {strFOFS(model2), F_STRING}, + // {strFOFS(model3), F_STRING}, - MCG + {strFOFS(nextTrain), F_GENTITY}, + {strFOFS(prevTrain), F_GENTITY}, + {strFOFS(message), F_STRING}, + {strFOFS(target), F_STRING}, + {strFOFS(target2), F_STRING}, + {strFOFS(target3), F_STRING}, + {strFOFS(target4), F_STRING}, + {strFOFS(targetJump), F_STRING}, + {strFOFS(targetname), F_STRING}, + {strFOFS(team), F_STRING}, + {strFOFS(roff), F_STRING}, + // {strFOFS(target_ent), F_GENTITY}, - MCG + {strFOFS(chain), F_GENTITY}, + {strFOFS(enemy), F_GENTITY}, + {strFOFS(activator), F_GENTITY}, + {strFOFS(teamchain), F_GENTITY}, + {strFOFS(teammaster), F_GENTITY}, + {strFOFS(item), F_ITEM}, + {strFOFS(NPC_type), F_STRING}, + {strFOFS(closetarget), F_STRING}, + {strFOFS(opentarget), F_STRING}, + {strFOFS(paintarget), F_STRING}, + {strFOFS(NPC_targetname), F_STRING}, + {strFOFS(NPC_target), F_STRING}, + {strFOFS(ownername), F_STRING}, + {strFOFS(lastEnemy), F_GENTITY}, + {strFOFS(behaviorSet), F_BEHAVIORSET}, + {strFOFS(script_targetname), F_STRING}, + {strFOFS(m_iIcarusID), F_NULL}, + {strFOFS(NPC), F_BOOLPTR}, + {strFOFS(soundSet), F_STRING}, + {strFOFS(cameraGroup), F_STRING}, + {strFOFS(parms), F_BOOLPTR}, + {strFOFS(m_pVehicle), F_BOOLPTR}, + + {NULL, 0, F_IGNORE}}; + +static const save_field_t savefields_gNPC[] = { + // {strNPCOFS(pendingEnemy), F_GENTITY}, + {strNPCOFS(touchedByPlayer), F_GENTITY}, + {strNPCOFS(aimingBeam), F_GENTITY}, + {strNPCOFS(eventOwner), F_GENTITY}, + {strNPCOFS(coverTarg), F_GENTITY}, + {strNPCOFS(tempGoal), F_GENTITY}, + {strNPCOFS(goalEntity), F_GENTITY}, + {strNPCOFS(lastGoalEntity), F_GENTITY}, + {strNPCOFS(eventualGoal), F_GENTITY}, + {strNPCOFS(captureGoal), F_GENTITY}, + {strNPCOFS(defendEnt), F_GENTITY}, + {strNPCOFS(greetEnt), F_GENTITY}, + {strNPCOFS(group), F_GROUP}, + {strNPCOFS(blockedEntity), F_GENTITY}, + {strNPCOFS(blockedTargetEntity), F_GENTITY}, + {strNPCOFS(jumpTarget), F_GENTITY}, + {strNPCOFS(watchTarget), F_GENTITY}, + {NULL, 0, F_IGNORE}}; + +static const save_field_t savefields_LevelLocals[] = {{strLLOFS(locationHead), F_GENTITY}, + {strLLOFS(alertEvents), F_ALERTEVENT}, + {strLLOFS(groups), F_AIGROUPS}, + {strLLOFS(knownAnimFileSets), F_ANIMFILESETS}, + {NULL, 0, F_IGNORE}}; + +static const save_field_t savefields_gVHIC[] = {{strVHICOFS(m_pPilot), F_GENTITY}, + {strVHICOFS(m_pOldPilot), F_GENTITY}, + {strVHICOFS(m_pDroidUnit), F_GENTITY}, + {strVHICOFS(m_pParentEntity), F_GENTITY}, + + // m_ppPassengers //!ptr array?! + {strVHICOFS(m_pVehicleInfo), F_VEHINFO}, //! another ptr! store name field instead and re-hook on load? + + {NULL, 0, F_IGNORE}}; + +static const save_field_t savefields_gClient[] = { // sabers are stomped over by specific code elsewhere, it seems, but the first two fields MUST be saved // or it crashes on reload - {strCLOFS(ps.saber[0].name),F_STRING}, -/* {strCLOFS(ps.saber[0].model),F_STRING}, - {strCLOFS(ps.saber[0].skin),F_STRING}, - {strCLOFS(ps.saber[0].brokenSaber1),F_STRING}, - {strCLOFS(ps.saber[0].brokenSaber2),F_STRING}, -*/ - {strCLOFS(ps.saber[1].name),F_STRING}, -/* {strCLOFS(ps.saber[1].model),F_STRING}, - {strCLOFS(ps.saber[1].skin),F_STRING}, - {strCLOFS(ps.saber[1].brokenSaber1),F_STRING}, - {strCLOFS(ps.saber[1].brokenSaber2),F_STRING}, -*/ - {strCLOFS(leader), F_GENTITY}, - {strCLOFS(clientInfo.customBasicSoundDir),F_STRING}, - {strCLOFS(clientInfo.customCombatSoundDir),F_STRING}, - {strCLOFS(clientInfo.customExtraSoundDir),F_STRING}, - {strCLOFS(clientInfo.customJediSoundDir),F_STRING}, - - {NULL, 0, F_IGNORE} -}; + {strCLOFS(ps.saber[0].name), F_STRING}, + /* {strCLOFS(ps.saber[0].model),F_STRING}, + {strCLOFS(ps.saber[0].skin),F_STRING}, + {strCLOFS(ps.saber[0].brokenSaber1),F_STRING}, + {strCLOFS(ps.saber[0].brokenSaber2),F_STRING}, + */ + {strCLOFS(ps.saber[1].name), F_STRING}, + /* {strCLOFS(ps.saber[1].model),F_STRING}, + {strCLOFS(ps.saber[1].skin),F_STRING}, + {strCLOFS(ps.saber[1].brokenSaber1),F_STRING}, + {strCLOFS(ps.saber[1].brokenSaber2),F_STRING}, + */ + {strCLOFS(leader), F_GENTITY}, + {strCLOFS(clientInfo.customBasicSoundDir), F_STRING}, + {strCLOFS(clientInfo.customCombatSoundDir), F_STRING}, + {strCLOFS(clientInfo.customExtraSoundDir), F_STRING}, + {strCLOFS(clientInfo.customJediSoundDir), F_STRING}, + + {NULL, 0, F_IGNORE}}; // TODO FIXME mrwonko: this has no business being a global variable. WTF Raven? static std::list strList; - /////////// char * ///////////// // // -static int GetStringNum(const char *psString) -{ - assert( psString != (char *)0xcdcdcdcd ); +static int GetStringNum(const char *psString) { + assert(psString != (char *)0xcdcdcdcd); // NULL ptrs I'll write out as a strlen of -1... // - if (!psString) - { + if (!psString) { return -1; } - strList.push_back( psString ); - return strlen(psString) + 1; // this gives us the chunk length for the reader later + strList.push_back(psString); + return strlen(psString) + 1; // this gives us the chunk length for the reader later } -static char *GetStringPtr(int iStrlen, char *psOriginal/*may be NULL*/) -{ - if (iStrlen != -1) - { - char sString[768]; // arb, inc if nec. +static char *GetStringPtr(int iStrlen, char *psOriginal /*may be NULL*/) { + if (iStrlen != -1) { + char sString[768]; // arb, inc if nec. - sString[0]=0; + sString[0] = 0; - assert(iStrlen+1<=(int)sizeof(sString)); + assert(iStrlen + 1 <= (int)sizeof(sString)); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('S', 'T', 'R', 'G'), - sString, - iStrlen); + saved_game.read_chunk(INT_ID('S', 'T', 'R', 'G'), sString, iStrlen); // TAG_G_ALLOC is always blown away, we can never recycle if (psOriginal && gi.bIsFromZone(psOriginal, TAG_G_ALLOC)) { - if (!strcmp(psOriginal,sString)) - {//it's a legal ptr and they're the same so let's just reuse it instead of free/alloc + if (!strcmp(psOriginal, sString)) { // it's a legal ptr and they're the same so let's just reuse it instead of free/alloc return psOriginal; } gi.Free(psOriginal); @@ -214,18 +190,13 @@ static char *GetStringPtr(int iStrlen, char *psOriginal/*may be NULL*/) // //////////////////////////////// - - - /////////// gentity_t * //////// // // -static intptr_t GetGEntityNum(gentity_t* ent) -{ - assert( ent != (gentity_t *) 0xcdcdcdcd); +static intptr_t GetGEntityNum(gentity_t *ent) { + assert(ent != (gentity_t *)0xcdcdcdcd); - if (ent == NULL) - { + if (ent == NULL) { return -1; } @@ -235,17 +206,14 @@ static intptr_t GetGEntityNum(gentity_t* ent) // ptrdiff_t iReturnIndex = ent - g_entities; - if (iReturnIndex < 0 || iReturnIndex >= MAX_GENTITIES) - { - iReturnIndex = -1; // will get a NULL ptr on reload + if (iReturnIndex < 0 || iReturnIndex >= MAX_GENTITIES) { + iReturnIndex = -1; // will get a NULL ptr on reload } return iReturnIndex; } -static gentity_t *GetGEntityPtr(intptr_t iEntNum) -{ - if (iEntNum == -1) - { +static gentity_t *GetGEntityPtr(intptr_t iEntNum) { + if (iEntNum == -1) { return NULL; } assert(iEntNum >= 0); @@ -256,29 +224,22 @@ static gentity_t *GetGEntityPtr(intptr_t iEntNum) // //////////////////////////////// +static intptr_t GetGroupNumber(AIGroupInfo_t *pGroup) { + assert(pGroup != (AIGroupInfo_t *)0xcdcdcdcd); - -static intptr_t GetGroupNumber(AIGroupInfo_t *pGroup) -{ - assert( pGroup != (AIGroupInfo_t *) 0xcdcdcdcd); - - if (pGroup == NULL) - { + if (pGroup == NULL) { return -1; } int iReturnIndex = pGroup - level.groups; - if (iReturnIndex < 0 || iReturnIndex >= (int)(sizeof(level.groups) / sizeof(level.groups[0])) ) - { - iReturnIndex = -1; // will get a NULL ptr on reload + if (iReturnIndex < 0 || iReturnIndex >= (int)(sizeof(level.groups) / sizeof(level.groups[0]))) { + iReturnIndex = -1; // will get a NULL ptr on reload } return iReturnIndex; } -static AIGroupInfo_t *GetGroupPtr(intptr_t iGroupNum) -{ - if (iGroupNum == -1) - { +static AIGroupInfo_t *GetGroupPtr(intptr_t iGroupNum) { + if (iGroupNum == -1) { return NULL; } assert(iGroupNum >= 0); @@ -286,42 +247,32 @@ static AIGroupInfo_t *GetGroupPtr(intptr_t iGroupNum) return (level.groups + iGroupNum); } - - /////////// gclient_t * //////// // // -static intptr_t GetGClientNum(gclient_t *c, gentity_t *ent) -{ +static intptr_t GetGClientNum(gclient_t *c, gentity_t *ent) { // unfortunately, I now need to see if this is a INT_ID('r','e','a','l') client (and therefore resolve to an enum), or // whether it's one of the NPC or SP_misc_weapon_shooter // assert(c != (gclient_t *)0xcdcdcdcd); - if (c == NULL) - { + if (c == NULL) { return -1; } - if (ent->s.number < MAX_CLIENTS) - { // regular client... + if (ent->s.number < MAX_CLIENTS) { // regular client... return (c - level.clients); - } - else - { // this must be an NPC or weapon_shooter, so mark it as special... - return -2; // yeuch, but distinguishes it from a valid 0 index, or -1 for client==NULL + } else { // this must be an NPC or weapon_shooter, so mark it as special... + return -2; // yeuch, but distinguishes it from a valid 0 index, or -1 for client==NULL } } -static gclient_t *GetGClientPtr(intptr_t c) -{ - if (c == -1) - { +static gclient_t *GetGClientPtr(intptr_t c) { + if (c == -1) { return NULL; } - if (c == -2) - { - return (gclient_t *) -2; // preserve this value so that I know to load in one of Mike's private NPC clients later + if (c == -2) { + return (gclient_t *)-2; // preserve this value so that I know to load in one of Mike's private NPC clients later } assert(c >= 0); @@ -332,26 +283,21 @@ static gclient_t *GetGClientPtr(intptr_t c) // //////////////////////////////// - /////////// gitem_t * ////////// // // -static int GetGItemNum (gitem_t *pItem) -{ - assert(pItem != (gitem_t*) 0xcdcdcdcd); +static int GetGItemNum(gitem_t *pItem) { + assert(pItem != (gitem_t *)0xcdcdcdcd); - if (pItem == NULL) - { + if (pItem == NULL) { return -1; } return pItem - bg_itemlist; } -static gitem_t *GetGItemPtr(int iItem) -{ - if (iItem == -1) - { +static gitem_t *GetGItemPtr(int iItem) { + if (iItem == -1) { return NULL; } @@ -363,26 +309,21 @@ static gitem_t *GetGItemPtr(int iItem) // //////////////////////////////// - /////////// vehicleInfo_t * ////////// // // -static int GetVehicleInfoNum(vehicleInfo_t *pVehicleInfo) -{ - assert(pVehicleInfo != (vehicleInfo_t*) 0xcdcdcdcd); +static int GetVehicleInfoNum(vehicleInfo_t *pVehicleInfo) { + assert(pVehicleInfo != (vehicleInfo_t *)0xcdcdcdcd); - if (pVehicleInfo == NULL) - { + if (pVehicleInfo == NULL) { return -1; } return pVehicleInfo - g_vehicleInfo; } -static vehicleInfo_t *GetVehicleInfoPtr(int iVehicleIndex) -{ - if (iVehicleIndex == -1) - { +static vehicleInfo_t *GetVehicleInfoPtr(int iVehicleIndex) { + if (iVehicleIndex == -1) { return NULL; } @@ -394,13 +335,10 @@ static vehicleInfo_t *GetVehicleInfoPtr(int iVehicleIndex) // //////////////////////////////// - -static void EnumerateField(const save_field_t *pField, const byte *pbBase) -{ +static void EnumerateField(const save_field_t *pField, const byte *pbBase) { void *pv = (void *)(pbBase + pField->iOffset); - switch (pField->eFieldType) - { + switch (pField->eFieldType) { case F_STRING: *(int *)pv = GetStringNum(*(char **)pv); break; @@ -414,7 +352,7 @@ static void EnumerateField(const save_field_t *pField, const byte *pbBase) break; case F_GCLIENT: - *(intptr_t *)pv = GetGClientNum(*(gclient_t **)pv, (gentity_t *) pbBase); + *(intptr_t *)pv = GetGClientNum(*(gclient_t **)pv, (gentity_t *)pbBase); break; case F_ITEM: @@ -425,69 +363,59 @@ static void EnumerateField(const save_field_t *pField, const byte *pbBase) *(int *)pv = GetVehicleInfoNum(*(vehicleInfo_t **)pv); break; - case F_BEHAVIORSET: - { - const char **p = (const char **) pv; - for (int i=0; ii = GetStringNum( ptAnimEventStringData ); - const char *plAnimEventStringData = p[i].legsAnimEvents[j].stringData; - baLegs->i = GetStringNum( plAnimEventStringData ); - } + } break; + + case F_ANIMFILESETS: { + animFileSet_t *p = (animFileSet_t *)pv; + + for (int i = 0; i < MAX_ANIM_FILES; i++) { + for (int j = 0; j < MAX_ANIM_EVENTS; j++) { + byteAlias_t *baTorso = (byteAlias_t *)&p[i].torsoAnimEvents[j].stringData, *baLegs = (byteAlias_t *)&p[i].legsAnimEvents[j].stringData; + const char *ptAnimEventStringData = p[i].torsoAnimEvents[j].stringData; + baTorso->i = GetStringNum(ptAnimEventStringData); + const char *plAnimEventStringData = p[i].legsAnimEvents[j].stringData; + baLegs->i = GetStringNum(plAnimEventStringData); } } - break; + } break; case F_BOOLPTR: *(qboolean *)pv = (qboolean)(*(int *)pv != 0); @@ -502,67 +430,49 @@ static void EnumerateField(const save_field_t *pField, const byte *pbBase) break; default: - G_Error ("EnumerateField: unknown field type"); + G_Error("EnumerateField: unknown field type"); break; } } -template -static void EnumerateFields( - const save_field_t* pFields, - const T* src_instance, - unsigned int ulChid) -{ +template static void EnumerateFields(const save_field_t *pFields, const T *src_instance, unsigned int ulChid) { strList.clear(); - const byte* pbData = reinterpret_cast( - src_instance); + const byte *pbData = reinterpret_cast(src_instance); // enumerate all the fields... // - if (pFields) - { - for (auto pField = pFields; pField->psName; ++pField) - { + if (pFields) { + for (auto pField = pFields; pField->psName; ++pField) { assert(pField->iOffset < sizeof(T)); ::EnumerateField(pField, pbData); } } - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // save out raw data... // saved_game.reset_buffer(); - src_instance->sg_export( - saved_game); + src_instance->sg_export(saved_game); - saved_game.write_chunk( - ulChid); + saved_game.write_chunk(ulChid); // save out any associated strings.. // - for (const auto& it : strList) - { - saved_game.write_chunk( - INT_ID('S', 'T', 'R', 'G'), - it.c_str(), - static_cast(it.length() + 1)); + for (const auto &it : strList) { + saved_game.write_chunk(INT_ID('S', 'T', 'R', 'G'), it.c_str(), static_cast(it.length() + 1)); } } - -static void EvaluateField(const save_field_t *pField, byte *pbBase, byte *pbOriginalRefData/* may be NULL*/) -{ - void *pv = (void *)(pbBase + pField->iOffset); +static void EvaluateField(const save_field_t *pField, byte *pbBase, byte *pbOriginalRefData /* may be NULL*/) { + void *pv = (void *)(pbBase + pField->iOffset); void *pvOriginal = (void *)(pbOriginalRefData + pField->iOffset); - switch (pField->eFieldType) - { + switch (pField->eFieldType) { case F_STRING: - *(char **)pv = GetStringPtr(*(int *)pv, pbOriginalRefData?*(char**)pvOriginal:NULL); + *(char **)pv = GetStringPtr(*(int *)pv, pbOriginalRefData ? *(char **)pvOriginal : NULL); break; case F_GENTITY: @@ -585,69 +495,57 @@ static void EvaluateField(const save_field_t *pField, byte *pbBase, byte *pbOrig *(vehicleInfo_t **)pv = GetVehicleInfoPtr(*(int *)pv); break; - case F_BEHAVIORSET: - { - char **p = (char **) pv; - char **pO= (char **) pvOriginal; - for (int i=0; iui = BigLong( chid ); + ba->ui = BigLong(chid); chidtext[4] = '\0'; return chidtext; } -extern void WP_SaberSetDefaults( saberInfo_t *saber, qboolean setColors); +extern void WP_SaberSetDefaults(saberInfo_t *saber, qboolean setColors); -void saberInfoRetail_t::sg_export( - saberInfo_t& dst) const -{ - ::WP_SaberSetDefaults( - &dst, - qfalse); +void saberInfoRetail_t::sg_export(saberInfo_t &dst) const { + ::WP_SaberSetDefaults(&dst, qfalse); - if (!activeBlocking) - { + if (!activeBlocking) { dst.saberFlags |= SFL_NOT_ACTIVE_BLOCKING; } - ::memcpy( - dst.blade, - blade, - sizeof(blade)); + ::memcpy(dst.blade, blade, sizeof(blade)); dst.breakParryBonus = breakParryBonus; dst.brokenSaber1 = brokenSaber1; dst.brokenSaber2 = brokenSaber2; - if (!disarmable) - { + if (!disarmable) { dst.saberFlags |= SFL_NOT_DISARMABLE; } @@ -705,8 +593,7 @@ void saberInfoRetail_t::sg_export( dst.forceRestrictions = forceRestrictions; dst.fullName = fullName; - if (!lockable) - { + if (!lockable) { dst.saberFlags |= SFL_NOT_LOCKABLE; } @@ -717,15 +604,13 @@ void saberInfoRetail_t::sg_export( dst.numBlades = numBlades; dst.parryBonus = parryBonus; - if (returnDamage) - { + if (returnDamage) { dst.saberFlags |= SFL_RETURN_DAMAGE; } dst.singleBladeStyle = singleBladeStyle; - if (singleBladeThrowable) - { + if (singleBladeThrowable) { dst.saberFlags |= SFL_SINGLE_BLADE_THROWABLE; } @@ -734,114 +619,70 @@ void saberInfoRetail_t::sg_export( dst.soundOff = soundOff; dst.soundOn = soundOn; - if (style != SS_NONE && style < SS_NUM_SABER_STYLES) - { - //OLD WAY: only allowed ONE style - //learn only this style + if (style != SS_NONE && style < SS_NUM_SABER_STYLES) { + // OLD WAY: only allowed ONE style + // learn only this style dst.stylesLearned = 1 << style; - //forbid all other styles + // forbid all other styles dst.stylesForbidden = 0; - for (int styleNum = SS_NONE + 1; styleNum < SS_NUM_SABER_STYLES; ++styleNum) - { - if (styleNum != style) - { + for (int styleNum = SS_NONE + 1; styleNum < SS_NUM_SABER_STYLES; ++styleNum) { + if (styleNum != style) { dst.stylesForbidden |= 1 << styleNum; } } } - if (!throwable) - { + if (!throwable) { dst.saberFlags |= SFL_NOT_THROWABLE; } - if (twoHanded) - { + if (twoHanded) { dst.saberFlags |= SFL_TWO_HANDED; } dst.type = type; } -static void copy_retail_gclient_to_current( - const RetailGClient& src, - gclient_t& dst) -{ +static void copy_retail_gclient_to_current(const RetailGClient &src, gclient_t &dst) { const size_t src_pre_size = offsetof(RetailGClient, ps.saber[0]); const size_t src_post_offset = offsetof(RetailGClient, ps.dualSabers); const size_t src_post_size = sizeof(RetailGClient) - src_post_offset; const size_t dst_post_offset = offsetof(gclient_t, ps.dualSabers); - ::memcpy( - reinterpret_cast(&dst), - reinterpret_cast(&src), - src_pre_size); + ::memcpy(reinterpret_cast(&dst), reinterpret_cast(&src), src_pre_size); - for (int i = 0; i < MAX_SABERS; ++i) - { - src.ps.saber[i].sg_export( - dst.ps.saber[i]); + for (int i = 0; i < MAX_SABERS; ++i) { + src.ps.saber[i].sg_export(dst.ps.saber[i]); } - ::memcpy( - reinterpret_cast(&dst) + src_post_offset, - reinterpret_cast(&src) + dst_post_offset, - src_post_size); + ::memcpy(reinterpret_cast(&dst) + src_post_offset, reinterpret_cast(&src) + dst_post_offset, src_post_size); } -template -static void EvaluateFields( - const save_field_t* pFields, - T* pbData, - byte* pbOriginalRefData, - unsigned int ulChid) -{ - T& instance = *pbData; +template static void EvaluateFields(const save_field_t *pFields, T *pbData, byte *pbOriginalRefData, unsigned int ulChid) { + T &instance = *pbData; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - if (ulChid != INT_ID('G', 'C', 'L', 'I')) - { - saved_game.read_chunk( - ulChid, - instance); - } - else - { - if (!saved_game.try_read_chunk( - ulChid, - instance)) - { + if (ulChid != INT_ID('G', 'C', 'L', 'I')) { + saved_game.read_chunk(ulChid, instance); + } else { + if (!saved_game.try_read_chunk(ulChid, instance)) { RetailGClient retail_client; saved_game.reset_buffer_offset(); - if (saved_game.try_read( - retail_client)) - { - copy_retail_gclient_to_current( - retail_client, - *reinterpret_cast(pbData)); - } - else - { - ::G_Error( - ::va("EvaluateFields(): variable-sized chunk '%s' without handler!", - ::SG_GetChidText(ulChid))); + if (saved_game.try_read(retail_client)) { + copy_retail_gclient_to_current(retail_client, *reinterpret_cast(pbData)); + } else { + ::G_Error(::va("EvaluateFields(): variable-sized chunk '%s' without handler!", ::SG_GetChidText(ulChid))); } } } - if (pFields) - { - for (const save_field_t* pField = pFields; pField->psName; ++pField) - { - ::EvaluateField( - pField, - reinterpret_cast(pbData), - pbOriginalRefData); + if (pFields) { + for (const save_field_t *pField = pFields; pField->psName; ++pField) { + ::EvaluateField(pField, reinterpret_cast(pbData), pbOriginalRefData); } } } @@ -853,12 +694,11 @@ WriteLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ -static void WriteLevelLocals () -{ +static void WriteLevelLocals() { level_locals_t *temp = (level_locals_t *)gi.Malloc(sizeof(level_locals_t), TAG_TEMP_WORKSPACE, qfalse); - *temp = level; // copy out all data into a temp space + *temp = level; // copy out all data into a temp space - EnumerateFields(savefields_LevelLocals, temp, INT_ID('L','V','L','C')); + EnumerateFields(savefields_LevelLocals, temp, INT_ID('L', 'V', 'L', 'C')); gi.Free(temp); } @@ -869,91 +709,74 @@ ReadLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ -static void ReadLevelLocals () -{ +static void ReadLevelLocals() { // preserve client ptr either side of the load, because clients are already saved/loaded through Read/Writegame... // - gclient_t *pClients = level.clients; // save clients + gclient_t *pClients = level.clients; // save clients level_locals_t *temp = (level_locals_t *)gi.Malloc(sizeof(level_locals_t), TAG_TEMP_WORKSPACE, qfalse); - *temp = level; // struct copy - EvaluateFields(savefields_LevelLocals, temp, (byte *)&level, INT_ID('L','V','L','C')); - level = *temp; // struct copy + *temp = level; // struct copy + EvaluateFields(savefields_LevelLocals, temp, (byte *)&level, INT_ID('L', 'V', 'L', 'C')); + level = *temp; // struct copy - level.clients = pClients; // restore clients + level.clients = pClients; // restore clients gi.Free(temp); } -static void WriteGEntities(qboolean qbAutosave) -{ +static void WriteGEntities(qboolean qbAutosave) { int iCount = 0; int i; - for (i=0; i<(qbAutosave?1:globals.num_entities); i++) - { - gentity_t* ent = &g_entities[i]; + for (i = 0; i < (qbAutosave ? 1 : globals.num_entities); i++) { + gentity_t *ent = &g_entities[i]; - if ( ent->inuse ) - { + if (ent->inuse) { iCount++; } } - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('N', 'M', 'E', 'D'), - iCount); + saved_game.write_chunk(INT_ID('N', 'M', 'E', 'D'), iCount); - for (i=0; i<(qbAutosave?1:globals.num_entities); i++) - { - gentity_t* ent = &g_entities[i]; + for (i = 0; i < (qbAutosave ? 1 : globals.num_entities); i++) { + gentity_t *ent = &g_entities[i]; - if ( ent->inuse) - { - saved_game.write_chunk( - INT_ID('E', 'D', 'N', 'M'), - i); + if (ent->inuse) { + saved_game.write_chunk(INT_ID('E', 'D', 'N', 'M'), i); qboolean qbLinked = ent->linked; - gi.unlinkentity( ent ); - gentity_t tempEnt = *ent; // make local copy + gi.unlinkentity(ent); + gentity_t tempEnt = *ent; // make local copy tempEnt.linked = qbLinked; - if (qbLinked) - { - gi.linkentity( ent ); + if (qbLinked) { + gi.linkentity(ent); } - EnumerateFields(savefields_gEntity, &tempEnt, INT_ID('G','E','N','T')); + EnumerateFields(savefields_gEntity, &tempEnt, INT_ID('G', 'E', 'N', 'T')); // now for any fiddly bits that would be rather awkward to build into the enumerator... // - if (tempEnt.NPC) - { - gNPC_t npc = *ent->NPC; // NOT *tempEnt.NPC; !! :-) + if (tempEnt.NPC) { + gNPC_t npc = *ent->NPC; // NOT *tempEnt.NPC; !! :-) - EnumerateFields(savefields_gNPC, &npc, INT_ID('G','N','P','C')); + EnumerateFields(savefields_gNPC, &npc, INT_ID('G', 'N', 'P', 'C')); } - if (tempEnt.client == (gclient_t *)-2) // I know, I know... + if (tempEnt.client == (gclient_t *)-2) // I know, I know... { - gclient_t client = *ent->client; // NOT *tempEnt.client!! - EnumerateFields(savefields_gClient, &client, INT_ID('G','C','L','I')); + gclient_t client = *ent->client; // NOT *tempEnt.client!! + EnumerateFields(savefields_gClient, &client, INT_ID('G', 'C', 'L', 'I')); } - if (tempEnt.parms) - { - saved_game.write_chunk( - INT_ID('P', 'A', 'R', 'M'), - *ent->parms); + if (tempEnt.parms) { + saved_game.write_chunk(INT_ID('P', 'A', 'R', 'M'), *ent->parms); } - if (tempEnt.m_pVehicle) - { - Vehicle_t vehicle = *ent->m_pVehicle; // NOT *tempEnt.m_pVehicle!! - EnumerateFields(savefields_gVHIC, &vehicle, INT_ID('V','H','I','C')); + if (tempEnt.m_pVehicle) { + Vehicle_t vehicle = *ent->m_pVehicle; // NOT *tempEnt.m_pVehicle!! + EnumerateFields(savefields_gVHIC, &vehicle, INT_ID('V', 'H', 'I', 'C')); } // the scary ghoul2 saver stuff... (fingers crossed) @@ -963,12 +786,11 @@ static void WriteGEntities(qboolean qbAutosave) } } - //Write out all entity timers - TIMER_Save();//WriteEntityTimers(); + // Write out all entity timers + TIMER_Save(); // WriteEntityTimers(); - if (!qbAutosave) - { - //Save out ICARUS information + if (!qbAutosave) { + // Save out ICARUS information IIcarusInterface::GetIcarus()->Save(); // this marker needs to be here, it lets me know if Icarus doesn't load everything back later, @@ -977,47 +799,35 @@ static void WriteGEntities(qboolean qbAutosave) // static int iBlah = 1234; - saved_game.write_chunk( - INT_ID('I', 'C', 'O', 'K'), - iBlah); + saved_game.write_chunk(INT_ID('I', 'C', 'O', 'K'), iBlah); } - if (!qbAutosave )//really shouldn't need to write these bits at all, just restore them from the ents... + if (!qbAutosave) // really shouldn't need to write these bits at all, just restore them from the ents... { WriteInUseBits(); } } -static void ReadGEntities(qboolean qbAutosave) -{ - int iCount = 0; - int i; +static void ReadGEntities(qboolean qbAutosave) { + int iCount = 0; + int i; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('N', 'M', 'E', 'D'), - iCount); + saved_game.read_chunk(INT_ID('N', 'M', 'E', 'D'), iCount); int iPreviousEntRead = -1; - for (i=0; i( - INT_ID('E', 'D', 'N', 'M'), - iEntIndex); + saved_game.read_chunk(INT_ID('E', 'D', 'N', 'M'), iEntIndex); - if (iEntIndex >= globals.num_entities) - { + if (iEntIndex >= globals.num_entities) { globals.num_entities = iEntIndex + 1; } - if (iPreviousEntRead != iEntIndex-1) - { - for (int j=iPreviousEntRead+1; j!=iEntIndex; j++) - { - if ( g_entities[j].inuse ) // not actually necessary + if (iPreviousEntRead != iEntIndex - 1) { + for (int j = iPreviousEntRead + 1; j != iEntIndex; j++) { + if (g_entities[j].inuse) // not actually necessary { G_FreeEntity(&g_entities[j]); } @@ -1027,52 +837,49 @@ static void ReadGEntities(qboolean qbAutosave) // slightly naff syntax here, but makes a few ops clearer later... // - gentity_t entity; - gentity_t* pEntOriginal = &entity; - gentity_t* pEnt = &g_entities[iEntIndex]; - *pEntOriginal = *pEnt; // struct copy, so we can refer to original + gentity_t entity; + gentity_t *pEntOriginal = &entity; + gentity_t *pEnt = &g_entities[iEntIndex]; + *pEntOriginal = *pEnt; // struct copy, so we can refer to original pEntOriginal->ghoul2.kill(); gi.unlinkentity(pEnt); - Quake3Game()->FreeEntity( pEnt ); + Quake3Game()->FreeEntity(pEnt); // // sneaky: destroy the ghoul2 object within this struct before binary-loading over the top of it... // gi.G2API_LoadSaveCodeDestructGhoul2Info(pEnt->ghoul2); pEnt->ghoul2.kill(); - EvaluateFields(savefields_gEntity, pEnt, (byte *)pEntOriginal, INT_ID('G','E','N','T')); + EvaluateFields(savefields_gEntity, pEnt, (byte *)pEntOriginal, INT_ID('G', 'E', 'N', 'T')); pEnt->ghoul2.kill(); // now for any fiddly bits... // - if (pEnt->NPC) // will be qtrue/qfalse + if (pEnt->NPC) // will be qtrue/qfalse { gNPC_t tempNPC; - EvaluateFields(savefields_gNPC, &tempNPC,(byte *)pEntOriginal->NPC, INT_ID('G','N','P','C')); + EvaluateFields(savefields_gNPC, &tempNPC, (byte *)pEntOriginal->NPC, INT_ID('G', 'N', 'P', 'C')); // so can we pinch the original's one or do we have to alloc a new one?... // - if (pEntOriginal->NPC) - { + if (pEntOriginal->NPC) { // pinch this G_Alloc handle... // pEnt->NPC = pEntOriginal->NPC; - } - else - { + } else { // original didn't have one (hmmm...), so make a new one... // - //assert(0); // I want to know about this, though not in release - pEnt->NPC = (gNPC_t *) G_Alloc(sizeof(*pEnt->NPC)); + // assert(0); // I want to know about this, though not in release + pEnt->NPC = (gNPC_t *)G_Alloc(sizeof(*pEnt->NPC)); } // copy over the one we've just loaded... // - *pEnt->NPC = tempNPC; // struct copy + *pEnt->NPC = tempNPC; // struct copy - //FIXME: do we need to do these too? + // FIXME: do we need to do these too? /* if ( pEnt->s.number ) {//not player @@ -1082,122 +889,106 @@ static void ReadGEntities(qboolean qbAutosave) */ } - if (pEnt->client == (gclient_t*) -2) // one of Mike G's NPC clients? + if (pEnt->client == (gclient_t *)-2) // one of Mike G's NPC clients? { gclient_t tempGClient; - EvaluateFields(savefields_gClient, &tempGClient, (byte *)pEntOriginal->client, INT_ID('G','C','L','I')); + EvaluateFields(savefields_gClient, &tempGClient, (byte *)pEntOriginal->client, INT_ID('G', 'C', 'L', 'I')); // can we pinch the original's client handle or do we have to alloc a new one?... // - if (pEntOriginal->client) - { + if (pEntOriginal->client) { // pinch this G_Alloc handle... // pEnt->client = pEntOriginal->client; - } - else - { + } else { // original didn't have one (hmmm...) so make a new one... // - pEnt->client = (gclient_t *) G_Alloc(sizeof(*pEnt->client)); + pEnt->client = (gclient_t *)G_Alloc(sizeof(*pEnt->client)); } // copy over the one we've just loaded.... // - *pEnt->client = tempGClient; // struct copy + *pEnt->client = tempGClient; // struct copy - if ( pEnt->s.number ) - {//not player - G_ReloadSaberData( pEnt ); + if (pEnt->s.number) { // not player + G_ReloadSaberData(pEnt); } } // Some Icarus thing... (probably) // - if (pEnt->parms) // will be qtrue/qfalse + if (pEnt->parms) // will be qtrue/qfalse { parms_t tempParms; - saved_game.read_chunk( - INT_ID('P', 'A', 'R', 'M'), - tempParms); + saved_game.read_chunk(INT_ID('P', 'A', 'R', 'M'), tempParms); // so can we pinch the original's one or do we have to alloc a new one?... // - if (pEntOriginal->parms) - { + if (pEntOriginal->parms) { // pinch this G_Alloc handle... // pEnt->parms = pEntOriginal->parms; - } - else - { + } else { // original didn't have one, so make a new one... // - pEnt->parms = (parms_t *) G_Alloc(sizeof(*pEnt->parms)); + pEnt->parms = (parms_t *)G_Alloc(sizeof(*pEnt->parms)); } // copy over the one we've just loaded... // - *pEnt->parms = tempParms; // struct copy + *pEnt->parms = tempParms; // struct copy } - if (pEnt->m_pVehicle) // will be qtrue/qfalse + if (pEnt->m_pVehicle) // will be qtrue/qfalse { Vehicle_t tempVehicle; - EvaluateFields(savefields_gVHIC, &tempVehicle,(byte *)pEntOriginal->m_pVehicle, INT_ID('V','H','I','C')); + EvaluateFields(savefields_gVHIC, &tempVehicle, (byte *)pEntOriginal->m_pVehicle, INT_ID('V', 'H', 'I', 'C')); // so can we pinch the original's one or do we have to alloc a new one?... // - if (pEntOriginal->m_pVehicle) - { + if (pEntOriginal->m_pVehicle) { // pinch this G_Alloc handle... // pEnt->m_pVehicle = pEntOriginal->m_pVehicle; - } - else - { + } else { // original didn't have one, so make a new one... // - pEnt->m_pVehicle = (Vehicle_t *) gi.Malloc( sizeof(Vehicle_t), TAG_G_ALLOC, qfalse ); + pEnt->m_pVehicle = (Vehicle_t *)gi.Malloc(sizeof(Vehicle_t), TAG_G_ALLOC, qfalse); } // copy over the one we've just loaded... // - *pEnt->m_pVehicle = tempVehicle; // struct copy + *pEnt->m_pVehicle = tempVehicle; // struct copy } // the scary ghoul2 stuff... (fingers crossed) // { - saved_game.read_chunk( - INT_ID('G', 'H', 'L', '2')); + saved_game.read_chunk(INT_ID('G', 'H', 'L', '2')); gi.G2API_LoadGhoul2Models(pEnt->ghoul2, nullptr); } -// gi.unlinkentity (pEntOriginal); -// ICARUS_FreeEnt( pEntOriginal ); -// *pEntOriginal = *pEnt; // struct copy -// qboolean qbLinked = pEntOriginal->linked; -// pEntOriginal->linked = qfalse; -// if (qbLinked) -// { -// gi.linkentity (pEntOriginal); -// } + // gi.unlinkentity (pEntOriginal); + // ICARUS_FreeEnt( pEntOriginal ); + // *pEntOriginal = *pEnt; // struct copy + // qboolean qbLinked = pEntOriginal->linked; + // pEntOriginal->linked = qfalse; + // if (qbLinked) + // { + // gi.linkentity (pEntOriginal); + // } // because the sytem stores sfx_t handles directly instead of the set, we have to reget the set's sfx_t... // - if (pEnt->s.eType == ET_MOVER && pEnt->s.loopSound>0) - { - if ( VALIDSTRING( pEnt->soundSet )) - { - extern int BMS_MID; // from g_mover - pEnt->s.loopSound = CAS_GetBModelSound( pEnt->soundSet, BMS_MID ); - if (pEnt->s.loopSound == -1) - { + if (pEnt->s.eType == ET_MOVER && pEnt->s.loopSound > 0) { + if (VALIDSTRING(pEnt->soundSet)) { + extern int BMS_MID; // from g_mover + pEnt->s.loopSound = CAS_GetBModelSound(pEnt->soundSet, BMS_MID); + if (pEnt->s.loopSound == -1) { pEnt->s.loopSound = 0; } } @@ -1208,29 +999,26 @@ static void ReadGEntities(qboolean qbAutosave) qboolean qbLinked = pEnt->linked; pEnt->linked = qfalse; - if (qbLinked) - { - gi.linkentity (pEnt); + if (qbLinked) { + gi.linkentity(pEnt); } } - //Read in all the entity timers - TIMER_Load();//ReadEntityTimers(); + // Read in all the entity timers + TIMER_Load(); // ReadEntityTimers(); - if (!qbAutosave) - { + if (!qbAutosave) { // now zap any g_ents that were inuse when the level was loaded, but are no longer in use in the saved version // that we've just loaded... // - for (i=iPreviousEntRead+1; iClearEntityList(); IIcarusInterface::GetIcarus()->Load(); @@ -1239,27 +1027,22 @@ static void ReadGEntities(qboolean qbAutosave) // static int iBlah = 1234; - saved_game.read_chunk( - INT_ID('I', 'C', 'O', 'K'), - iBlah); + saved_game.read_chunk(INT_ID('I', 'C', 'O', 'K'), iBlah); } - if (!qbAutosave) - { - ReadInUseBits();//really shouldn't need to read these bits in at all, just restore them from the ents... + if (!qbAutosave) { + ReadInUseBits(); // really shouldn't need to read these bits in at all, just restore them from the ents... } } - -void WriteLevel(qboolean qbAutosave) -{ +void WriteLevel(qboolean qbAutosave) { if (!qbAutosave) //-always save the client { // write out one client - us! // - assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way ReadGame works + assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way ReadGame works gclient_t client = level.clients[0]; - EnumerateFields(savefields_gClient, &client, INT_ID('G','C','L','I')); - WriteLevelLocals(); // level_locals_t level + EnumerateFields(savefields_gClient, &client, INT_ID('G', 'C', 'L', 'I')); + WriteLevelLocals(); // level_locals_t level } OBJ_SaveObjectiveData(); @@ -1279,61 +1062,52 @@ void WriteLevel(qboolean qbAutosave) // static int iDONE = 1234; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('D', 'O', 'N', 'E'), - iDONE); + saved_game.write_chunk(INT_ID('D', 'O', 'N', 'E'), iDONE); } -void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) { + ojk::SavedGameHelper saved_game(::gi.saved_game); - if ( qbLoadTransition ) - { + if (qbLoadTransition) { // I STRONGLY SUSPECT THAT THIS WILL JUST ERR_DROP BECAUSE OF THE LOAD SWAPPING OF THE CHUNK-ORDER // BELOW BETWEEN OBJECTIVES AND LEVEL_LOCALS, SO I'M GUESSING THIS IS SOME OLD EF1 JUNK? // IN ANY CASE, LET'S MAKE SURE... // -ste (no idea who wrote the comment stuff below, did it ever work?) // assert(0); // - //loadtransitions do not need to read the objectives and client data from the level they're going to - //In a loadtransition, client data is carried over on the server and will be stomped later anyway. - //The objective info (in client->sess data), however, is read in from G_ReadSessionData which is called before this func, - //we do NOT want to stomp that session data when doing a load transition + // loadtransitions do not need to read the objectives and client data from the level they're going to + // In a loadtransition, client data is carried over on the server and will be stomped later anyway. + // The objective info (in client->sess data), however, is read in from G_ReadSessionData which is called before this func, + // we do NOT want to stomp that session data when doing a load transition - //However, we should still save this info out because these savegames may need to be - //loaded normally later- perhaps if you die and need to respawn, perhaps as some kind - //of emergency savegame for resuming, etc. + // However, we should still save this info out because these savegames may need to be + // loaded normally later- perhaps if you die and need to respawn, perhaps as some kind + // of emergency savegame for resuming, etc. - //SO: We read it in, but throw it away. + // SO: We read it in, but throw it away. - //Read & throw away gclient info + // Read & throw away gclient info gclient_t junkClient; - EvaluateFields(savefields_gClient, &junkClient, (byte *)&level.clients[0], INT_ID('G','C','L','I')); + EvaluateFields(savefields_gClient, &junkClient, (byte *)&level.clients[0], INT_ID('G', 'C', 'L', 'I')); - ReadLevelLocals(); // level_locals_t level + ReadLevelLocals(); // level_locals_t level - //Read & throw away objective info - saved_game.read_chunk( - INT_ID('O', 'B', 'J', 'T')); - } - else - { - if (!qbAutosave )//always load the client unless it's an autosave + // Read & throw away objective info + saved_game.read_chunk(INT_ID('O', 'B', 'J', 'T')); + } else { + if (!qbAutosave) // always load the client unless it's an autosave { - assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way things work + assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way things work gclient_t GClient; - EvaluateFields(savefields_gClient, &GClient, (byte *)&level.clients[0], INT_ID('G','C','L','I')); - level.clients[0] = GClient; // struct copy - ReadLevelLocals(); // level_locals_t level + EvaluateFields(savefields_gClient, &GClient, (byte *)&level.clients[0], INT_ID('G', 'C', 'L', 'I')); + level.clients[0] = GClient; // struct copy + ReadLevelLocals(); // level_locals_t level } - OBJ_LoadObjectiveData();//loads mission objectives AND tactical info + OBJ_LoadObjectiveData(); // loads mission objectives AND tactical info } FX_Read(); @@ -1353,15 +1127,10 @@ void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) // static int iDONE = 1234; - saved_game.read_chunk( - INT_ID('D', 'O', 'N', 'E'), - iDONE); + saved_game.read_chunk(INT_ID('D', 'O', 'N', 'E'), iDONE); } extern int killPlayerTimer; -qboolean GameAllowedToSaveHere(void) -{ - return (qboolean)(!in_camera&&!killPlayerTimer); -} +qboolean GameAllowedToSaveHere(void) { return (qboolean)(!in_camera && !killPlayerTimer); } //////////////////// eof ///////////////////// diff --git a/code/game/g_session.cpp b/code/game/g_session.cpp index 6cde682b0c..3bda5f8e94 100644 --- a/code/game/g_session.cpp +++ b/code/game/g_session.cpp @@ -24,7 +24,6 @@ along with this program; if not, see . #include "g_local.h" #include "objectives.h" - /* ======================================================================= @@ -42,67 +41,52 @@ G_WriteClientSessionData Called on game shutdown ================ */ -void G_WriteClientSessionData( gclient_t *client ) { - const char *s; - const char *s2; - const char *var; - int i; +void G_WriteClientSessionData(gclient_t *client) { + const char *s; + const char *s2; + const char *var; + int i; - s = va("%i", client->sess.sessionTeam ); - var = va( "session%i", client - level.clients ); - gi.cvar_set( var, s ); + s = va("%i", client->sess.sessionTeam); + var = va("session%i", client - level.clients); + gi.cvar_set(var, s); s2 = ""; // Throw all status info into a string -// for (i=0;i< MAX_OBJECTIVES; i++) -// { -// s2 = va("%s %i %i", s2, client->sess.mission_objectives[i].display, client->sess.mission_objectives[i].status); -// } + // for (i=0;i< MAX_OBJECTIVES; i++) + // { + // s2 = va("%s %i %i", s2, client->sess.mission_objectives[i].display, client->sess.mission_objectives[i].status); + // } // We're saving only one objective - s2 = va("%i %i", client->sess.mission_objectives[LIGHTSIDE_OBJ].display, client->sess.mission_objectives[LIGHTSIDE_OBJ].status); + s2 = va("%i %i", client->sess.mission_objectives[LIGHTSIDE_OBJ].display, client->sess.mission_objectives[LIGHTSIDE_OBJ].status); - var = va( "sessionobj%i", client - level.clients ); - gi.cvar_set( var, s2 ); + var = va("sessionobj%i", client - level.clients); + gi.cvar_set(var, s2); // Throw all mission stats in to a string - s2 = va("%i %i %i %i %i %i %i %i %i %i %i %i", - client->sess.missionStats.secretsFound, - client->sess.missionStats.totalSecrets, - client->sess.missionStats.shotsFired, - client->sess.missionStats.hits, - client->sess.missionStats.enemiesSpawned, - client->sess.missionStats.enemiesKilled, - client->sess.missionStats.saberThrownCnt, - client->sess.missionStats.saberBlocksCnt, - client->sess.missionStats.legAttacksCnt, - client->sess.missionStats.armAttacksCnt, - client->sess.missionStats.torsoAttacksCnt, - client->sess.missionStats.otherAttacksCnt - ); - - var = va( "missionstats%i", client - level.clients ); - gi.cvar_set( var, s2 ); + s2 = va("%i %i %i %i %i %i %i %i %i %i %i %i", client->sess.missionStats.secretsFound, client->sess.missionStats.totalSecrets, + client->sess.missionStats.shotsFired, client->sess.missionStats.hits, client->sess.missionStats.enemiesSpawned, + client->sess.missionStats.enemiesKilled, client->sess.missionStats.saberThrownCnt, client->sess.missionStats.saberBlocksCnt, + client->sess.missionStats.legAttacksCnt, client->sess.missionStats.armAttacksCnt, client->sess.missionStats.torsoAttacksCnt, + client->sess.missionStats.otherAttacksCnt); + var = va("missionstats%i", client - level.clients); + gi.cvar_set(var, s2); s2 = ""; - for (i=0;i< NUM_FORCE_POWERS; i++) - { - s2 = va("%s %i",s2, client->sess.missionStats.forceUsed[i]); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + s2 = va("%s %i", s2, client->sess.missionStats.forceUsed[i]); } - var = va( "sessionpowers%i", client - level.clients ); - gi.cvar_set( var, s2 ); - + var = va("sessionpowers%i", client - level.clients); + gi.cvar_set(var, s2); s2 = ""; - for (i=0;i< WP_NUM_WEAPONS; i++) - { - s2 = va("%s %i",s2, client->sess.missionStats.weaponUsed[i]); + for (i = 0; i < WP_NUM_WEAPONS; i++) { + s2 = va("%s %i", s2, client->sess.missionStats.weaponUsed[i]); } - var = va( "sessionweapons%i", client - level.clients ); - gi.cvar_set( var, s2 ); - - + var = va("sessionweapons%i", client - level.clients); + gi.cvar_set(var, s2); } /* @@ -112,91 +96,76 @@ G_ReadSessionData Called on a reconnect ================ */ -void G_ReadSessionData( gclient_t *client ) { - char s[MAX_STRING_CHARS]; - const char *var; - int i; - int lightsideDisplay; +void G_ReadSessionData(gclient_t *client) { + char s[MAX_STRING_CHARS]; + const char *var; + int i; + int lightsideDisplay; - var = va( "session%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); + var = va("session%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); - sscanf( s, "%i", &i ); + sscanf(s, "%i", &i); client->sess.sessionTeam = (team_t)i; - var = va( "sessionobj%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); + var = va("sessionobj%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); var = s; -// var++; - -// for (i=0;i< MAX_OBJECTIVES; i++) -// { -// sscanf( var, "%i %i", -// &client->sess.mission_objectives[i].display, -// &client->sess.mission_objectives[i].status); -// var+=4; -// } + // var++; + + // for (i=0;i< MAX_OBJECTIVES; i++) + // { + // sscanf( var, "%i %i", + // &client->sess.mission_objectives[i].display, + // &client->sess.mission_objectives[i].status); + // var+=4; + // } // Clear the objectives out - for (i=0;i< MAX_OBJECTIVES; i++) - { + for (i = 0; i < MAX_OBJECTIVES; i++) { client->sess.mission_objectives[i].display = qfalse; client->sess.mission_objectives[i].status = OBJECTIVE_STAT_PENDING; } // Now load the LIGHTSIDE objective. That's the only cross level objective. - sscanf( var, "%i %i", - &lightsideDisplay, - &client->sess.mission_objectives[LIGHTSIDE_OBJ].status); + sscanf(var, "%i %i", &lightsideDisplay, &client->sess.mission_objectives[LIGHTSIDE_OBJ].status); client->sess.mission_objectives[LIGHTSIDE_OBJ].display = lightsideDisplay ? qtrue : qfalse; - var = va( "missionstats%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - sscanf( s, "%i %i %i %i %i %i %i %i %i %i %i %i", - &client->sess.missionStats.secretsFound, - &client->sess.missionStats.totalSecrets, - &client->sess.missionStats.shotsFired, - &client->sess.missionStats.hits, - &client->sess.missionStats.enemiesSpawned, - &client->sess.missionStats.enemiesKilled, - &client->sess.missionStats.saberThrownCnt, - &client->sess.missionStats.saberBlocksCnt, - &client->sess.missionStats.legAttacksCnt, - &client->sess.missionStats.armAttacksCnt, - &client->sess.missionStats.torsoAttacksCnt, - &client->sess.missionStats.otherAttacksCnt); - - - var = va( "sessionpowers%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->sess.missionStats.forceUsed[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + var = va("missionstats%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + sscanf(s, "%i %i %i %i %i %i %i %i %i %i %i %i", &client->sess.missionStats.secretsFound, &client->sess.missionStats.totalSecrets, + &client->sess.missionStats.shotsFired, &client->sess.missionStats.hits, &client->sess.missionStats.enemiesSpawned, + &client->sess.missionStats.enemiesKilled, &client->sess.missionStats.saberThrownCnt, &client->sess.missionStats.saberBlocksCnt, + &client->sess.missionStats.legAttacksCnt, &client->sess.missionStats.armAttacksCnt, &client->sess.missionStats.torsoAttacksCnt, + &client->sess.missionStats.otherAttacksCnt); + + var = va("sessionpowers%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->sess.missionStats.forceUsed[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==NUM_FORCE_POWERS); - - var = va( "sessionweapons%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->sess.missionStats.weaponUsed[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + assert(i == NUM_FORCE_POWERS); + + var = va("sessionweapons%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->sess.missionStats.weaponUsed[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==WP_NUM_WEAPONS); + assert(i == WP_NUM_WEAPONS); } - /* ================ G_InitSessionData @@ -204,25 +173,23 @@ G_InitSessionData Called on a first-time connect ================ */ -void G_InitSessionData( gclient_t *client, char *userinfo ) { - clientSession_t *sess; +void G_InitSessionData(gclient_t *client, char *userinfo) { + clientSession_t *sess; sess = &client->sess; sess->sessionTeam = TEAM_FREE; - G_WriteClientSessionData( client ); + G_WriteClientSessionData(client); } - /* ================== G_InitWorldSession ================== */ -void G_InitWorldSession( void ) { -} +void G_InitWorldSession(void) {} /* ================== @@ -230,14 +197,14 @@ G_WriteSessionData ================== */ -void G_WriteSessionData( void ) { - int i; +void G_WriteSessionData(void) { + int i; - gi.cvar_set( "session", 0) ; + gi.cvar_set("session", 0); - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected == CON_CONNECTED ) { - G_WriteClientSessionData( &level.clients[i] ); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { + G_WriteClientSessionData(&level.clients[i]); } } } diff --git a/code/game/g_spawn.cpp b/code/game/g_spawn.cpp index d279621b0e..0c0721d61f 100644 --- a/code/game/g_spawn.cpp +++ b/code/game/g_spawn.cpp @@ -32,43 +32,39 @@ extern cvar_t *g_delayedShutdown; // these vars I moved here out of the level_locals_t struct simply because it's pointless to try saving them, // and the level_locals_t struct is included in the save process... -slc // -qboolean spawning = qfalse; // the G_Spawn*() functions are valid (only turned on during one function) -int numSpawnVars; -char *spawnVars[MAX_SPAWN_VARS][2]; // key / value pairs -int numSpawnVarChars; -char spawnVarChars[MAX_SPAWN_VARS_CHARS]; +qboolean spawning = qfalse; // the G_Spawn*() functions are valid (only turned on during one function) +int numSpawnVars; +char *spawnVars[MAX_SPAWN_VARS][2]; // key / value pairs +int numSpawnVarChars; +char spawnVarChars[MAX_SPAWN_VARS_CHARS]; -int delayedShutDown = 0; +int delayedShutDown = 0; #include "../qcommon/sstring.h" -//NOTENOTE: Be sure to change the mirrored code in cgmain.cpp -typedef std::map< sstring_t, unsigned char > namePrecache_m; -namePrecache_m *as_preCacheMap = NULL; +// NOTENOTE: Be sure to change the mirrored code in cgmain.cpp +typedef std::map namePrecache_m; +namePrecache_m *as_preCacheMap = NULL; -char *G_AddSpawnVarToken( const char *string ); +char *G_AddSpawnVarToken(const char *string); -void AddSpawnField(char *field, char *value) -{ - int i; +void AddSpawnField(char *field, char *value) { + int i; - for(i=0;i= numSpawnVars ) +qboolean G_SpawnField(unsigned int uiField, char **ppKey, char **ppValue) { + if ((int)uiField >= numSpawnVars) return qfalse; (*ppKey) = spawnVars[uiField][0]; @@ -77,16 +73,16 @@ qboolean G_SpawnField( unsigned int uiField, char **ppKey, char **ppValue ) return qtrue; } -qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) { - int i; +qboolean G_SpawnString(const char *key, const char *defaultString, char **out) { + int i; - if ( !spawning ) { + if (!spawning) { *out = (char *)defaultString; -// G_Error( "G_SpawnString() called while not spawning" ); + // G_Error( "G_SpawnString() called while not spawning" ); } - for ( i = 0 ; i < numSpawnVars ; i++ ) { - if ( !Q_stricmp( key, spawnVars[i][0] ) ) { + for (i = 0; i < numSpawnVars; i++) { + if (!Q_stricmp(key, spawnVars[i][0])) { *out = spawnVars[i][1]; return qtrue; } @@ -96,56 +92,50 @@ qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) return qfalse; } -qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnFloat(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atof( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atof(s); return present; } -qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ) { - char *s; - qboolean present; +qboolean G_SpawnInt(const char *key, const char *defaultString, int *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atoi( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atoi(s); return present; } -qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnVector(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f %f %f", &out[0], &out[1], &out[2]); return present; } -qboolean G_SpawnVector4( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnVector4(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f %f %f %f", &out[0], &out[1], &out[2], &out[3] ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f %f %f %f", &out[0], &out[1], &out[2], &out[3]); return present; } -qboolean G_SpawnFlag( const char *key, int flag, int *out ) -{ - //find that key - for ( int i = 0 ; i < numSpawnVars ; i++ ) - { - if ( !strcmp( key, spawnVars[i][0] ) ) - { - //found the key - if ( atoi( spawnVars[i][1] ) != 0 ) - {//if it's non-zero, and in the flag +qboolean G_SpawnFlag(const char *key, int flag, int *out) { + // find that key + for (int i = 0; i < numSpawnVars; i++) { + if (!strcmp(key, spawnVars[i][0])) { + // found the key + if (atoi(spawnVars[i][1]) != 0) { // if it's non-zero, and in the flag *out |= flag; - } - else - {//if it's zero, or out the flag + } else { // if it's zero, or out the flag *out &= ~flag; } return qtrue; @@ -155,14 +145,13 @@ qboolean G_SpawnFlag( const char *key, int flag, int *out ) return qfalse; } -qboolean G_SpawnAngleHack( const char *key, const char *defaultString, float *out ) -{ - char *s; - qboolean present; - float temp = 0; +qboolean G_SpawnAngleHack(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; + float temp = 0; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f", &temp ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f", &temp); out[0] = 0; out[1] = temp; @@ -171,12 +160,10 @@ qboolean G_SpawnAngleHack( const char *key, const char *defaultString, float *ou return present; } -stringID_table_t flagTable [] = -{ +stringID_table_t flagTable[] = { //"noTED", EF_NO_TED, - //stringID_table_t Must end with a null entry - { "", 0 } -}; + // stringID_table_t Must end with a null entry + {"", 0}}; // // fields are needed for spawning from the entity string @@ -184,49 +171,48 @@ stringID_table_t flagTable [] = typedef enum { F_INT, F_FLOAT, - F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL - F_GSTRING, // string on disk, pointer in memory, TAG_GAME + F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL + F_GSTRING, // string on disk, pointer in memory, TAG_GAME F_VECTOR, F_VECTOR4, F_ANGLEHACK, - F_ENTITY, // index on disk, pointer in memory - F_ITEM, // index on disk, pointer in memory - F_CLIENT, // index on disk, pointer in memory - F_PARM1, // Special case for parms - F_PARM2, // Special case for parms - F_PARM3, // Special case for parms - F_PARM4, // Special case for parms - F_PARM5, // Special case for parms - F_PARM6, // Special case for parms - F_PARM7, // Special case for parms - F_PARM8, // Special case for parms - F_PARM9, // Special case for parms - F_PARM10, // Special case for parms - F_PARM11, // Special case for parms - F_PARM12, // Special case for parms - F_PARM13, // Special case for parms - F_PARM14, // Special case for parms - F_PARM15, // Special case for parms - F_PARM16, // Special case for parms - F_FLAG, // special case for flags + F_ENTITY, // index on disk, pointer in memory + F_ITEM, // index on disk, pointer in memory + F_CLIENT, // index on disk, pointer in memory + F_PARM1, // Special case for parms + F_PARM2, // Special case for parms + F_PARM3, // Special case for parms + F_PARM4, // Special case for parms + F_PARM5, // Special case for parms + F_PARM6, // Special case for parms + F_PARM7, // Special case for parms + F_PARM8, // Special case for parms + F_PARM9, // Special case for parms + F_PARM10, // Special case for parms + F_PARM11, // Special case for parms + F_PARM12, // Special case for parms + F_PARM13, // Special case for parms + F_PARM14, // Special case for parms + F_PARM15, // Special case for parms + F_PARM16, // Special case for parms + F_FLAG, // special case for flags F_IGNORE } fieldtype_t; -typedef struct -{ - const char *name; - size_t ofs; - fieldtype_t type; - int flags; +typedef struct { + const char *name; + size_t ofs; + fieldtype_t type; + int flags; } field_t; field_t fields[] = { - //Fields for benefit of Radiant only + // Fields for benefit of Radiant only {"autobound", FOFS(classname), F_IGNORE}, {"groupname", FOFS(classname), F_IGNORE}, - {"noBasicSounds", FOFS(classname), F_IGNORE},//will be looked at separately - {"noCombatSounds", FOFS(classname), F_IGNORE},//will be looked at separately - {"noExtraSounds", FOFS(classname), F_IGNORE},//will be looked at separately + {"noBasicSounds", FOFS(classname), F_IGNORE}, // will be looked at separately + {"noCombatSounds", FOFS(classname), F_IGNORE}, // will be looked at separately + {"noExtraSounds", FOFS(classname), F_IGNORE}, // will be looked at separately {"classname", FOFS(classname), F_LSTRING}, {"origin", FOFS(s.origin), F_VECTOR}, @@ -234,14 +220,14 @@ field_t fields[] = { {"maxs", FOFS(maxs), F_VECTOR}, {"model", FOFS(model), F_LSTRING}, {"model2", FOFS(model2), F_LSTRING}, - {"model3", FOFS(target), F_LSTRING},//for misc_replicator_item only!!! - {"model4", FOFS(target2), F_LSTRING},//for misc_replicator_item only!!! - {"model5", FOFS(target3), F_LSTRING},//for misc_replicator_item only!!! - {"model6", FOFS(target4), F_LSTRING},//for misc_replicator_item only!!! + {"model3", FOFS(target), F_LSTRING}, // for misc_replicator_item only!!! + {"model4", FOFS(target2), F_LSTRING}, // for misc_replicator_item only!!! + {"model5", FOFS(target3), F_LSTRING}, // for misc_replicator_item only!!! + {"model6", FOFS(target4), F_LSTRING}, // for misc_replicator_item only!!! {"spawnflags", FOFS(spawnflags), F_INT}, {"speed", FOFS(speed), F_FLOAT}, - {"duration", FOFS(speed), F_FLOAT},//for psycho jism - {"interest", FOFS(health), F_INT},//For target_interest + {"duration", FOFS(speed), F_FLOAT}, // for psycho jism + {"interest", FOFS(health), F_INT}, // For target_interest {"target", FOFS(target), F_LSTRING}, {"target2", FOFS(target2), F_LSTRING}, {"target3", FOFS(target3), F_LSTRING}, @@ -253,13 +239,13 @@ field_t fields[] = { {"team", FOFS(team), F_LSTRING}, {"mapname", FOFS(message), F_LSTRING}, {"wait", FOFS(wait), F_FLOAT}, - {"finaltime", FOFS(wait), F_FLOAT},//For dlight + {"finaltime", FOFS(wait), F_FLOAT}, // For dlight {"random", FOFS(random), F_FLOAT}, - {"FOV", FOFS(random), F_FLOAT},//for ref_tags and trigger_visibles + {"FOV", FOFS(random), F_FLOAT}, // for ref_tags and trigger_visibles {"count", FOFS(count), F_INT}, {"bounceCount", FOFS(bounceCount), F_INT}, {"health", FOFS(health), F_INT}, - {"friction", FOFS(health), F_INT},//For target_friction_change + {"friction", FOFS(health), F_INT}, // For target_friction_change {"light", 0, F_IGNORE}, {"dmg", FOFS(damage), F_INT}, {"angles", FOFS(s.angles), F_VECTOR}, @@ -267,18 +253,18 @@ field_t fields[] = { {"modelAngles", FOFS(modelAngles), F_VECTOR}, {"cameraGroup", FOFS(cameraGroup), F_LSTRING}, {"radius", FOFS(radius), F_FLOAT}, - {"hiderange", FOFS(radius), F_FLOAT},//for triggers only - {"starttime", FOFS(radius), F_FLOAT},//for dlight - {"turfrange", FOFS(radius), F_FLOAT},//for sand creatures - {"type", FOFS(count), F_FLOAT},//for fx_crew_beam_in + {"hiderange", FOFS(radius), F_FLOAT}, // for triggers only + {"starttime", FOFS(radius), F_FLOAT}, // for dlight + {"turfrange", FOFS(radius), F_FLOAT}, // for sand creatures + {"type", FOFS(count), F_FLOAT}, // for fx_crew_beam_in {"fxfile", FOFS(fxFile), F_LSTRING}, {"fxfile2", FOFS(cameraGroup), F_LSTRING}, - {"noVisTime", FOFS(endFrame), F_INT},//for NPC_Vehicle - {"endFrame", FOFS(endFrame), F_INT},//for func_usable shader animation - {"linear", FOFS(alt_fire), F_INT},//for movers to use linear movement - {"weapon",FOFS(paintarget),F_LSTRING},//for misc_weapon_shooter only + {"noVisTime", FOFS(endFrame), F_INT}, // for NPC_Vehicle + {"endFrame", FOFS(endFrame), F_INT}, // for func_usable shader animation + {"linear", FOFS(alt_fire), F_INT}, // for movers to use linear movement + {"weapon", FOFS(paintarget), F_LSTRING}, // for misc_weapon_shooter only -//Script parms - will this handle clamping to 16 or whatever length of parm[0] is? + // Script parms - will this handle clamping to 16 or whatever length of parm[0] is? {"parm1", 0, F_PARM1}, {"parm2", 0, F_PARM2}, {"parm3", 0, F_PARM3}, @@ -297,59 +283,59 @@ field_t fields[] = { {"parm16", 0, F_PARM16}, //{"noTED", FOFS(s.eFlags), F_FLAG}, -//MCG - Begin - //extra fields for ents + // MCG - Begin + // extra fields for ents {"delay", FOFS(delay), F_INT}, {"sounds", FOFS(sounds), F_INT}, - {"closetarget", FOFS(closetarget), F_LSTRING},//for doors - {"opentarget", FOFS(opentarget), F_LSTRING},//for doors - {"paintarget", FOFS(paintarget), F_LSTRING},//for doors - {"soundGroup", FOFS(paintarget), F_LSTRING},//for target_speakers - {"backwardstarget", FOFS(paintarget), F_LSTRING},//for trigger_bidirectional + {"closetarget", FOFS(closetarget), F_LSTRING}, // for doors + {"opentarget", FOFS(opentarget), F_LSTRING}, // for doors + {"paintarget", FOFS(paintarget), F_LSTRING}, // for doors + {"soundGroup", FOFS(paintarget), F_LSTRING}, // for target_speakers + {"backwardstarget", FOFS(paintarget), F_LSTRING}, // for trigger_bidirectional {"splashDamage", FOFS(splashDamage), F_INT}, {"splashRadius", FOFS(splashRadius), F_INT}, - //Script stuff - {"spawnscript", FOFS(behaviorSet[BSET_SPAWN]), F_LSTRING},//name of script to run - {"usescript", FOFS(behaviorSet[BSET_USE]), F_LSTRING},//name of script to run - {"awakescript", FOFS(behaviorSet[BSET_AWAKE]), F_LSTRING},//name of script to run - {"angerscript", FOFS(behaviorSet[BSET_ANGER]), F_LSTRING},//name of script to run - {"attackscript", FOFS(behaviorSet[BSET_ATTACK]), F_LSTRING},//name of script to run - {"victoryscript", FOFS(behaviorSet[BSET_VICTORY]), F_LSTRING},//name of script to run - {"lostenemyscript", FOFS(behaviorSet[BSET_LOSTENEMY]), F_LSTRING},//name of script to run - {"painscript", FOFS(behaviorSet[BSET_PAIN]), F_LSTRING},//name of script to run - {"fleescript", FOFS(behaviorSet[BSET_FLEE]), F_LSTRING},//name of script to run - {"deathscript", FOFS(behaviorSet[BSET_DEATH]), F_LSTRING},//name of script to run - {"delayscript", FOFS(behaviorSet[BSET_DELAYED]), F_LSTRING},//name of script to run - {"delayscripttime", FOFS(delayScriptTime), F_INT},//name of script to run - {"blockedscript", FOFS(behaviorSet[BSET_BLOCKED]), F_LSTRING},//name of script to run - {"ffirescript", FOFS(behaviorSet[BSET_FFIRE]), F_LSTRING},//name of script to run - {"ffdeathscript", FOFS(behaviorSet[BSET_FFDEATH]), F_LSTRING},//name of script to run - {"mindtrickscript", FOFS(behaviorSet[BSET_MINDTRICK]), F_LSTRING},//name of script to run - {"script_targetname", FOFS(script_targetname), F_LSTRING},//scripts look for this when "affecting" - //For NPCs + // Script stuff + {"spawnscript", FOFS(behaviorSet[BSET_SPAWN]), F_LSTRING}, // name of script to run + {"usescript", FOFS(behaviorSet[BSET_USE]), F_LSTRING}, // name of script to run + {"awakescript", FOFS(behaviorSet[BSET_AWAKE]), F_LSTRING}, // name of script to run + {"angerscript", FOFS(behaviorSet[BSET_ANGER]), F_LSTRING}, // name of script to run + {"attackscript", FOFS(behaviorSet[BSET_ATTACK]), F_LSTRING}, // name of script to run + {"victoryscript", FOFS(behaviorSet[BSET_VICTORY]), F_LSTRING}, // name of script to run + {"lostenemyscript", FOFS(behaviorSet[BSET_LOSTENEMY]), F_LSTRING}, // name of script to run + {"painscript", FOFS(behaviorSet[BSET_PAIN]), F_LSTRING}, // name of script to run + {"fleescript", FOFS(behaviorSet[BSET_FLEE]), F_LSTRING}, // name of script to run + {"deathscript", FOFS(behaviorSet[BSET_DEATH]), F_LSTRING}, // name of script to run + {"delayscript", FOFS(behaviorSet[BSET_DELAYED]), F_LSTRING}, // name of script to run + {"delayscripttime", FOFS(delayScriptTime), F_INT}, // name of script to run + {"blockedscript", FOFS(behaviorSet[BSET_BLOCKED]), F_LSTRING}, // name of script to run + {"ffirescript", FOFS(behaviorSet[BSET_FFIRE]), F_LSTRING}, // name of script to run + {"ffdeathscript", FOFS(behaviorSet[BSET_FFDEATH]), F_LSTRING}, // name of script to run + {"mindtrickscript", FOFS(behaviorSet[BSET_MINDTRICK]), F_LSTRING}, // name of script to run + {"script_targetname", FOFS(script_targetname), F_LSTRING}, // scripts look for this when "affecting" + // For NPCs //{"playerTeam", FOFS(playerTeam), F_INT}, //{"enemyTeam", FOFS(enemyTeam), F_INT}, {"NPC_targetname", FOFS(NPC_targetname), F_LSTRING}, {"NPC_target", FOFS(NPC_target), F_LSTRING}, - {"NPC_target2", FOFS(target2), F_LSTRING},//NPC_spawner only - {"NPC_target4", FOFS(target4), F_LSTRING},//NPC_spawner only + {"NPC_target2", FOFS(target2), F_LSTRING}, // NPC_spawner only + {"NPC_target4", FOFS(target4), F_LSTRING}, // NPC_spawner only {"NPC_type", FOFS(NPC_type), F_LSTRING}, {"ownername", FOFS(ownername), F_LSTRING}, - //for weapon_saber + // for weapon_saber {"saberType", FOFS(NPC_type), F_LSTRING}, {"saberColor", FOFS(NPC_targetname), F_LSTRING}, {"saberLeftHand", FOFS(alt_fire), F_INT}, {"saberSolo", FOFS(loopAnim), F_INT}, {"saberPitch", FOFS(random), F_FLOAT}, - //freaky camera shit + // freaky camera shit {"startRGBA", FOFS(startRGBA), F_VECTOR4}, {"finalRGBA", FOFS(finalRGBA), F_VECTOR4}, -//MCG - End + // MCG - End {"soundSet", FOFS(soundSet), F_LSTRING}, - {"mass", FOFS(mass), F_FLOAT}, //really only used for pushable misc_model_breakables + {"mass", FOFS(mass), F_FLOAT}, // really only used for pushable misc_model_breakables -//q3map stuff + // q3map stuff {"scale", 0, F_IGNORE}, {"modelscale", 0, F_IGNORE}, {"modelscale_vec", 0, F_IGNORE}, @@ -357,508 +343,501 @@ field_t fields[] = { {"lip", 0, F_IGNORE}, {"switch_style", 0, F_IGNORE}, {"height", 0, F_IGNORE}, - {"noise", 0, F_IGNORE}, //SP_target_speaker - {"gravity", 0, F_IGNORE}, //SP_target_gravity_change + {"noise", 0, F_IGNORE}, // SP_target_speaker + {"gravity", 0, F_IGNORE}, // SP_target_gravity_change - {"storyhead", 0, F_IGNORE}, //SP_target_level_change - {"tier_storyinfo", 0, F_IGNORE}, //SP_target_level_change - {"zoffset", 0, F_IGNORE}, //used by misc_model_static - {"music", 0, F_IGNORE}, //used by target_play_music - {"forcevisible", 0, F_IGNORE}, //for force sight on multiple model entities - {"redcrosshair", 0, F_IGNORE}, //for red crosshairs on breakables - {"nodelay", 0, F_IGNORE}, //for Reborn & Cultist NPCs - - {NULL} -}; + {"storyhead", 0, F_IGNORE}, // SP_target_level_change + {"tier_storyinfo", 0, F_IGNORE}, // SP_target_level_change + {"zoffset", 0, F_IGNORE}, // used by misc_model_static + {"music", 0, F_IGNORE}, // used by target_play_music + {"forcevisible", 0, F_IGNORE}, // for force sight on multiple model entities + {"redcrosshair", 0, F_IGNORE}, // for red crosshairs on breakables + {"nodelay", 0, F_IGNORE}, // for Reborn & Cultist NPCs + {NULL}}; typedef struct { - const char *name; - void (*spawn)(gentity_t *ent); + const char *name; + void (*spawn)(gentity_t *ent); } spawn_t; -void SP_info_player_start (gentity_t *ent); -void SP_info_player_deathmatch (gentity_t *ent); -void SP_info_player_intermission (gentity_t *ent); +void SP_info_player_start(gentity_t *ent); +void SP_info_player_deathmatch(gentity_t *ent); +void SP_info_player_intermission(gentity_t *ent); void SP_info_firstplace(gentity_t *ent); void SP_info_secondplace(gentity_t *ent); void SP_info_thirdplace(gentity_t *ent); -void SP_func_plat (gentity_t *ent); -void SP_func_static (gentity_t *ent); -void SP_func_rotating (gentity_t *ent); -void SP_func_bobbing (gentity_t *ent); -void SP_func_breakable (gentity_t *self); -void SP_func_glass( gentity_t *self ); -void SP_func_pendulum( gentity_t *ent ); -void SP_func_button (gentity_t *ent); -void SP_func_door (gentity_t *ent); -void SP_func_train (gentity_t *ent); -void SP_func_timer (gentity_t *self); -void SP_func_wall (gentity_t *ent); -void SP_func_usable( gentity_t *self ); -void SP_rail_mover( gentity_t *self ); -void SP_rail_track( gentity_t *self ); -void SP_rail_lane( gentity_t *self ); - - - -void SP_trigger_always (gentity_t *ent); -void SP_trigger_multiple (gentity_t *ent); -void SP_trigger_once (gentity_t *ent); -void SP_trigger_push (gentity_t *ent); -void SP_trigger_teleport (gentity_t *ent); -void SP_trigger_hurt (gentity_t *ent); -void SP_trigger_bidirectional (gentity_t *ent); -void SP_trigger_entdist (gentity_t *self); -void SP_trigger_location( gentity_t *ent ); -void SP_trigger_visible( gentity_t *self ); +void SP_func_plat(gentity_t *ent); +void SP_func_static(gentity_t *ent); +void SP_func_rotating(gentity_t *ent); +void SP_func_bobbing(gentity_t *ent); +void SP_func_breakable(gentity_t *self); +void SP_func_glass(gentity_t *self); +void SP_func_pendulum(gentity_t *ent); +void SP_func_button(gentity_t *ent); +void SP_func_door(gentity_t *ent); +void SP_func_train(gentity_t *ent); +void SP_func_timer(gentity_t *self); +void SP_func_wall(gentity_t *ent); +void SP_func_usable(gentity_t *self); +void SP_rail_mover(gentity_t *self); +void SP_rail_track(gentity_t *self); +void SP_rail_lane(gentity_t *self); + +void SP_trigger_always(gentity_t *ent); +void SP_trigger_multiple(gentity_t *ent); +void SP_trigger_once(gentity_t *ent); +void SP_trigger_push(gentity_t *ent); +void SP_trigger_teleport(gentity_t *ent); +void SP_trigger_hurt(gentity_t *ent); +void SP_trigger_bidirectional(gentity_t *ent); +void SP_trigger_entdist(gentity_t *self); +void SP_trigger_location(gentity_t *ent); +void SP_trigger_visible(gentity_t *self); void SP_trigger_space(gentity_t *self); void SP_trigger_shipboundary(gentity_t *self); -void SP_target_give (gentity_t *ent); -void SP_target_delay (gentity_t *ent); -void SP_target_speaker (gentity_t *ent); -void SP_target_print (gentity_t *ent); -void SP_target_laser (gentity_t *self); -void SP_target_character (gentity_t *ent); -void SP_target_score( gentity_t *ent ); -void SP_target_teleporter( gentity_t *ent ); -void SP_target_relay (gentity_t *ent); -void SP_target_kill (gentity_t *ent); -void SP_target_position (gentity_t *ent); -void SP_target_location (gentity_t *ent); -void SP_target_push (gentity_t *ent); -void SP_target_random (gentity_t *self); -void SP_target_counter (gentity_t *self); -void SP_target_scriptrunner (gentity_t *self); -void SP_target_interest (gentity_t *self); -void SP_target_activate (gentity_t *self); -void SP_target_deactivate (gentity_t *self); -void SP_target_gravity_change( gentity_t *self ); -void SP_target_friction_change( gentity_t *self ); -void SP_target_level_change( gentity_t *self ); -void SP_target_change_parm( gentity_t *self ); -void SP_target_play_music( gentity_t *self ); -void SP_target_autosave( gentity_t *self ); -void SP_target_secret( gentity_t *self ); - -void SP_light (gentity_t *self); -void SP_info_null (gentity_t *self); -void SP_info_notnull (gentity_t *self); -void SP_path_corner (gentity_t *self); - -void SP_misc_teleporter (gentity_t *self); -void SP_misc_teleporter_dest (gentity_t *self); +void SP_target_give(gentity_t *ent); +void SP_target_delay(gentity_t *ent); +void SP_target_speaker(gentity_t *ent); +void SP_target_print(gentity_t *ent); +void SP_target_laser(gentity_t *self); +void SP_target_character(gentity_t *ent); +void SP_target_score(gentity_t *ent); +void SP_target_teleporter(gentity_t *ent); +void SP_target_relay(gentity_t *ent); +void SP_target_kill(gentity_t *ent); +void SP_target_position(gentity_t *ent); +void SP_target_location(gentity_t *ent); +void SP_target_push(gentity_t *ent); +void SP_target_random(gentity_t *self); +void SP_target_counter(gentity_t *self); +void SP_target_scriptrunner(gentity_t *self); +void SP_target_interest(gentity_t *self); +void SP_target_activate(gentity_t *self); +void SP_target_deactivate(gentity_t *self); +void SP_target_gravity_change(gentity_t *self); +void SP_target_friction_change(gentity_t *self); +void SP_target_level_change(gentity_t *self); +void SP_target_change_parm(gentity_t *self); +void SP_target_play_music(gentity_t *self); +void SP_target_autosave(gentity_t *self); +void SP_target_secret(gentity_t *self); + +void SP_light(gentity_t *self); +void SP_info_null(gentity_t *self); +void SP_info_notnull(gentity_t *self); +void SP_path_corner(gentity_t *self); + +void SP_misc_teleporter(gentity_t *self); +void SP_misc_teleporter_dest(gentity_t *self); void SP_misc_model(gentity_t *ent); void SP_misc_model_static(gentity_t *ent); -void SP_misc_turret (gentity_t *base); -void SP_misc_ns_turret (gentity_t *base); -void SP_laser_arm (gentity_t *base); -void SP_misc_ion_cannon( gentity_t *ent ); -void SP_misc_maglock( gentity_t *ent ); -void SP_misc_panel_turret( gentity_t *ent ); -void SP_misc_model_welder( gentity_t *ent ); -void SP_misc_model_jabba_cam( gentity_t *ent ); - -void SP_misc_model_shield_power_converter( gentity_t *ent ); -void SP_misc_model_ammo_power_converter( gentity_t *ent ); -void SP_misc_model_bomb_planted( gentity_t *ent ); -void SP_misc_model_beacon( gentity_t *ent ); - -void SP_misc_shield_floor_unit( gentity_t *ent ); -void SP_misc_ammo_floor_unit( gentity_t *ent ); - -void SP_misc_model_gun_rack( gentity_t *ent ); -void SP_misc_model_ammo_rack( gentity_t *ent ); -void SP_misc_model_cargo_small( gentity_t *ent ); - -void SP_misc_exploding_crate( gentity_t *ent ); -void SP_misc_gas_tank( gentity_t *ent ); -void SP_misc_crystal_crate( gentity_t *ent ); -void SP_misc_atst_drivable( gentity_t *ent ); - -void SP_misc_model_breakable(gentity_t *ent);//stays as an ent -void SP_misc_model_ghoul(gentity_t *ent);//stays as an ent +void SP_misc_turret(gentity_t *base); +void SP_misc_ns_turret(gentity_t *base); +void SP_laser_arm(gentity_t *base); +void SP_misc_ion_cannon(gentity_t *ent); +void SP_misc_maglock(gentity_t *ent); +void SP_misc_panel_turret(gentity_t *ent); +void SP_misc_model_welder(gentity_t *ent); +void SP_misc_model_jabba_cam(gentity_t *ent); + +void SP_misc_model_shield_power_converter(gentity_t *ent); +void SP_misc_model_ammo_power_converter(gentity_t *ent); +void SP_misc_model_bomb_planted(gentity_t *ent); +void SP_misc_model_beacon(gentity_t *ent); + +void SP_misc_shield_floor_unit(gentity_t *ent); +void SP_misc_ammo_floor_unit(gentity_t *ent); + +void SP_misc_model_gun_rack(gentity_t *ent); +void SP_misc_model_ammo_rack(gentity_t *ent); +void SP_misc_model_cargo_small(gentity_t *ent); + +void SP_misc_exploding_crate(gentity_t *ent); +void SP_misc_gas_tank(gentity_t *ent); +void SP_misc_crystal_crate(gentity_t *ent); +void SP_misc_atst_drivable(gentity_t *ent); + +void SP_misc_model_breakable(gentity_t *ent); // stays as an ent +void SP_misc_model_ghoul(gentity_t *ent); // stays as an ent void SP_misc_portal_camera(gentity_t *ent); void SP_misc_bsp(gentity_t *ent); void SP_terrain(gentity_t *ent); -void SP_misc_skyportal (gentity_t *ent); +void SP_misc_skyportal(gentity_t *ent); void SP_misc_portal_surface(gentity_t *ent); -void SP_misc_camera_focus (gentity_t *self); -void SP_misc_camera_track (gentity_t *self); -void SP_misc_dlight (gentity_t *ent); -void SP_misc_security_panel (gentity_t *ent); -void SP_misc_camera( gentity_t *ent ); -void SP_misc_spotlight( gentity_t *ent ); - -void SP_shooter_rocket( gentity_t *ent ); -void SP_shooter_plasma( gentity_t *ent ); -void SP_shooter_grenade( gentity_t *ent ); -void SP_misc_replicator_item( gentity_t *ent ); -void SP_misc_trip_mine( gentity_t *self ); -void SP_PAS( gentity_t *ent ); -void SP_misc_weapon_shooter( gentity_t *self ); -void SP_misc_weather_zone( gentity_t *ent ); - -void SP_misc_cubemap( gentity_t *ent ); - -//New spawn functions -void SP_reference_tag ( gentity_t *ent ); - -void SP_NPC_spawner( gentity_t *self ); - -void SP_NPC_Vehicle( gentity_t *self ); -void SP_NPC_Player( gentity_t *self ); -void SP_NPC_Kyle( gentity_t *self ); -void SP_NPC_Lando( gentity_t *self ); -void SP_NPC_Jan( gentity_t *self ); -void SP_NPC_Luke( gentity_t *self ); -void SP_NPC_MonMothma( gentity_t *self ); -void SP_NPC_Rosh_Penin( gentity_t *self ); -void SP_NPC_Tavion( gentity_t *self ); -void SP_NPC_Tavion_New( gentity_t *self ); -void SP_NPC_Alora( gentity_t *self ); -void SP_NPC_Reelo( gentity_t *self ); -void SP_NPC_Galak( gentity_t *self ); -void SP_NPC_Desann( gentity_t *self ); -void SP_NPC_Rax( gentity_t *self ); -void SP_NPC_BobaFett( gentity_t *self ); -void SP_NPC_Ragnos( gentity_t *self ); -void SP_NPC_Lannik_Racto( gentity_t *self ); -void SP_NPC_Kothos( gentity_t *self ); -void SP_NPC_Chewbacca( gentity_t *self ); -void SP_NPC_Bartender( gentity_t *self ); -void SP_NPC_MorganKatarn( gentity_t *self ); -void SP_NPC_Jedi( gentity_t *self ); -void SP_NPC_Prisoner( gentity_t *self ); -void SP_NPC_Merchant( gentity_t *self ); -void SP_NPC_Rebel( gentity_t *self ); -void SP_NPC_Human_Merc( gentity_t *self ); -void SP_NPC_Stormtrooper( gentity_t *self ); -void SP_NPC_StormtrooperOfficer( gentity_t *self ); -void SP_NPC_Tie_Pilot( gentity_t *self ); -void SP_NPC_Snowtrooper( gentity_t *self ); -void SP_NPC_RocketTrooper( gentity_t *self); -void SP_NPC_HazardTrooper( gentity_t *self); -void SP_NPC_Ugnaught( gentity_t *self ); -void SP_NPC_Jawa( gentity_t *self ); -void SP_NPC_Gran( gentity_t *self ); -void SP_NPC_Rodian( gentity_t *self ); -void SP_NPC_Weequay( gentity_t *self ); -void SP_NPC_Trandoshan( gentity_t *self ); -void SP_NPC_Tusken( gentity_t *self ); -void SP_NPC_Noghri( gentity_t *self ); -void SP_NPC_SwampTrooper( gentity_t *self ); -void SP_NPC_Imperial( gentity_t *self ); -void SP_NPC_ImpWorker( gentity_t *self ); -void SP_NPC_BespinCop( gentity_t *self ); -void SP_NPC_Reborn( gentity_t *self ); -void SP_NPC_Reborn_New( gentity_t *self); -void SP_NPC_Cultist( gentity_t *self ); -void SP_NPC_Cultist_Saber( gentity_t *self ); -void SP_NPC_Cultist_Saber_Powers( gentity_t *self ); -void SP_NPC_Cultist_Destroyer( gentity_t *self ); -void SP_NPC_Cultist_Commando( gentity_t *self ); -void SP_NPC_ShadowTrooper( gentity_t *self ); -void SP_NPC_Saboteur( gentity_t *self ); -void SP_NPC_Monster_Murjj( gentity_t *self ); -void SP_NPC_Monster_Swamp( gentity_t *self ); -void SP_NPC_Monster_Howler( gentity_t *self ); -void SP_NPC_Monster_Rancor( gentity_t *self ); -void SP_NPC_Monster_Mutant_Rancor( gentity_t *self ); -void SP_NPC_Monster_Wampa( gentity_t *self ); -void SP_NPC_Monster_Claw( gentity_t *self ); -void SP_NPC_Monster_Glider( gentity_t *self ); -void SP_NPC_Monster_Flier2( gentity_t *self ); -void SP_NPC_Monster_Lizard( gentity_t *self ); -void SP_NPC_Monster_Fish( gentity_t *self ); -void SP_NPC_Monster_Sand_Creature( gentity_t *self ); -void SP_NPC_MineMonster( gentity_t *self ); -void SP_NPC_Droid_Interrogator( gentity_t *self ); -void SP_NPC_Droid_Probe( gentity_t *self ); -void SP_NPC_Droid_Mark1( gentity_t *self ); -void SP_NPC_Droid_Mark2( gentity_t *self ); -void SP_NPC_Droid_ATST( gentity_t *self ); -void SP_NPC_Droid_Seeker( gentity_t *self ); -void SP_NPC_Droid_Remote( gentity_t *self ); -void SP_NPC_Droid_Sentry( gentity_t *self ); -void SP_NPC_Droid_Gonk( gentity_t *self ); -void SP_NPC_Droid_Mouse( gentity_t *self ); -void SP_NPC_Droid_R2D2( gentity_t *self ); -void SP_NPC_Droid_R5D2( gentity_t *self ); -void SP_NPC_Droid_Protocol( gentity_t *self ); -void SP_NPC_Droid_Assassin( gentity_t *self); -void SP_NPC_Droid_Saber( gentity_t *self); - -void SP_waypoint (gentity_t *ent); -void SP_waypoint_small (gentity_t *ent); -void SP_waypoint_navgoal (gentity_t *ent); - -void SP_fx_runner( gentity_t *ent ); -void SP_fx_explosion_trail( gentity_t *ent ); -void SP_fx_target_beam( gentity_t *ent ); -void SP_fx_cloudlayer( gentity_t *ent ); - -void SP_CreateSnow( gentity_t *ent ); -void SP_CreateRain( gentity_t *ent ); -void SP_CreateWind( gentity_t *ent ); -void SP_CreateWindZone( gentity_t *ent ); +void SP_misc_camera_focus(gentity_t *self); +void SP_misc_camera_track(gentity_t *self); +void SP_misc_dlight(gentity_t *ent); +void SP_misc_security_panel(gentity_t *ent); +void SP_misc_camera(gentity_t *ent); +void SP_misc_spotlight(gentity_t *ent); + +void SP_shooter_rocket(gentity_t *ent); +void SP_shooter_plasma(gentity_t *ent); +void SP_shooter_grenade(gentity_t *ent); +void SP_misc_replicator_item(gentity_t *ent); +void SP_misc_trip_mine(gentity_t *self); +void SP_PAS(gentity_t *ent); +void SP_misc_weapon_shooter(gentity_t *self); +void SP_misc_weather_zone(gentity_t *ent); + +void SP_misc_cubemap(gentity_t *ent); + +// New spawn functions +void SP_reference_tag(gentity_t *ent); + +void SP_NPC_spawner(gentity_t *self); + +void SP_NPC_Vehicle(gentity_t *self); +void SP_NPC_Player(gentity_t *self); +void SP_NPC_Kyle(gentity_t *self); +void SP_NPC_Lando(gentity_t *self); +void SP_NPC_Jan(gentity_t *self); +void SP_NPC_Luke(gentity_t *self); +void SP_NPC_MonMothma(gentity_t *self); +void SP_NPC_Rosh_Penin(gentity_t *self); +void SP_NPC_Tavion(gentity_t *self); +void SP_NPC_Tavion_New(gentity_t *self); +void SP_NPC_Alora(gentity_t *self); +void SP_NPC_Reelo(gentity_t *self); +void SP_NPC_Galak(gentity_t *self); +void SP_NPC_Desann(gentity_t *self); +void SP_NPC_Rax(gentity_t *self); +void SP_NPC_BobaFett(gentity_t *self); +void SP_NPC_Ragnos(gentity_t *self); +void SP_NPC_Lannik_Racto(gentity_t *self); +void SP_NPC_Kothos(gentity_t *self); +void SP_NPC_Chewbacca(gentity_t *self); +void SP_NPC_Bartender(gentity_t *self); +void SP_NPC_MorganKatarn(gentity_t *self); +void SP_NPC_Jedi(gentity_t *self); +void SP_NPC_Prisoner(gentity_t *self); +void SP_NPC_Merchant(gentity_t *self); +void SP_NPC_Rebel(gentity_t *self); +void SP_NPC_Human_Merc(gentity_t *self); +void SP_NPC_Stormtrooper(gentity_t *self); +void SP_NPC_StormtrooperOfficer(gentity_t *self); +void SP_NPC_Tie_Pilot(gentity_t *self); +void SP_NPC_Snowtrooper(gentity_t *self); +void SP_NPC_RocketTrooper(gentity_t *self); +void SP_NPC_HazardTrooper(gentity_t *self); +void SP_NPC_Ugnaught(gentity_t *self); +void SP_NPC_Jawa(gentity_t *self); +void SP_NPC_Gran(gentity_t *self); +void SP_NPC_Rodian(gentity_t *self); +void SP_NPC_Weequay(gentity_t *self); +void SP_NPC_Trandoshan(gentity_t *self); +void SP_NPC_Tusken(gentity_t *self); +void SP_NPC_Noghri(gentity_t *self); +void SP_NPC_SwampTrooper(gentity_t *self); +void SP_NPC_Imperial(gentity_t *self); +void SP_NPC_ImpWorker(gentity_t *self); +void SP_NPC_BespinCop(gentity_t *self); +void SP_NPC_Reborn(gentity_t *self); +void SP_NPC_Reborn_New(gentity_t *self); +void SP_NPC_Cultist(gentity_t *self); +void SP_NPC_Cultist_Saber(gentity_t *self); +void SP_NPC_Cultist_Saber_Powers(gentity_t *self); +void SP_NPC_Cultist_Destroyer(gentity_t *self); +void SP_NPC_Cultist_Commando(gentity_t *self); +void SP_NPC_ShadowTrooper(gentity_t *self); +void SP_NPC_Saboteur(gentity_t *self); +void SP_NPC_Monster_Murjj(gentity_t *self); +void SP_NPC_Monster_Swamp(gentity_t *self); +void SP_NPC_Monster_Howler(gentity_t *self); +void SP_NPC_Monster_Rancor(gentity_t *self); +void SP_NPC_Monster_Mutant_Rancor(gentity_t *self); +void SP_NPC_Monster_Wampa(gentity_t *self); +void SP_NPC_Monster_Claw(gentity_t *self); +void SP_NPC_Monster_Glider(gentity_t *self); +void SP_NPC_Monster_Flier2(gentity_t *self); +void SP_NPC_Monster_Lizard(gentity_t *self); +void SP_NPC_Monster_Fish(gentity_t *self); +void SP_NPC_Monster_Sand_Creature(gentity_t *self); +void SP_NPC_MineMonster(gentity_t *self); +void SP_NPC_Droid_Interrogator(gentity_t *self); +void SP_NPC_Droid_Probe(gentity_t *self); +void SP_NPC_Droid_Mark1(gentity_t *self); +void SP_NPC_Droid_Mark2(gentity_t *self); +void SP_NPC_Droid_ATST(gentity_t *self); +void SP_NPC_Droid_Seeker(gentity_t *self); +void SP_NPC_Droid_Remote(gentity_t *self); +void SP_NPC_Droid_Sentry(gentity_t *self); +void SP_NPC_Droid_Gonk(gentity_t *self); +void SP_NPC_Droid_Mouse(gentity_t *self); +void SP_NPC_Droid_R2D2(gentity_t *self); +void SP_NPC_Droid_R5D2(gentity_t *self); +void SP_NPC_Droid_Protocol(gentity_t *self); +void SP_NPC_Droid_Assassin(gentity_t *self); +void SP_NPC_Droid_Saber(gentity_t *self); + +void SP_waypoint(gentity_t *ent); +void SP_waypoint_small(gentity_t *ent); +void SP_waypoint_navgoal(gentity_t *ent); + +void SP_fx_runner(gentity_t *ent); +void SP_fx_explosion_trail(gentity_t *ent); +void SP_fx_target_beam(gentity_t *ent); +void SP_fx_cloudlayer(gentity_t *ent); + +void SP_CreateSnow(gentity_t *ent); +void SP_CreateRain(gentity_t *ent); +void SP_CreateWind(gentity_t *ent); +void SP_CreateWindZone(gentity_t *ent); // Added 10/20/02 by Aurelio Reis -void SP_CreatePuffSystem( gentity_t *ent ); - -void SP_object_cargo_barrel1( gentity_t *ent ); - -void SP_point_combat (gentity_t *self); - -void SP_emplaced_eweb( gentity_t *self ); -void SP_emplaced_gun( gentity_t *self ); - -void SP_misc_turbobattery( gentity_t *base ); - - -spawn_t spawns[] = { - {"info_player_start", SP_info_player_start}, - {"info_player_deathmatch", SP_info_player_deathmatch}, - - {"func_plat", SP_func_plat}, - {"func_button", SP_func_button}, - {"func_door", SP_func_door}, - {"func_static", SP_func_static}, - {"func_rotating", SP_func_rotating}, - {"func_bobbing", SP_func_bobbing}, - {"func_breakable", SP_func_breakable}, - {"func_pendulum", SP_func_pendulum}, - {"func_train", SP_func_train}, - {"func_timer", SP_func_timer}, // rename trigger_timer? - {"func_wall", SP_func_wall}, - {"func_usable", SP_func_usable}, - {"func_glass", SP_func_glass}, - - {"rail_mover", SP_rail_mover}, - {"rail_track", SP_rail_track}, - {"rail_lane", SP_rail_lane}, - - {"trigger_always", SP_trigger_always}, - {"trigger_multiple", SP_trigger_multiple}, - {"trigger_once", SP_trigger_once}, - {"trigger_push", SP_trigger_push}, - {"trigger_teleport", SP_trigger_teleport}, - {"trigger_hurt", SP_trigger_hurt}, - {"trigger_bidirectional", SP_trigger_bidirectional}, - {"trigger_entdist", SP_trigger_entdist}, - {"trigger_location", SP_trigger_location}, - {"trigger_visible", SP_trigger_visible}, - {"trigger_space", SP_trigger_space}, - {"trigger_shipboundary", SP_trigger_shipboundary}, - - {"target_give", SP_target_give}, - {"target_delay", SP_target_delay}, - {"target_speaker", SP_target_speaker}, - {"target_print", SP_target_print}, - {"target_laser", SP_target_laser}, - {"target_score", SP_target_score}, - {"target_teleporter", SP_target_teleporter}, - {"target_relay", SP_target_relay}, - {"target_kill", SP_target_kill}, - {"target_position", SP_target_position}, - {"target_location", SP_target_location}, - {"target_push", SP_target_push}, - {"target_random", SP_target_random}, - {"target_counter", SP_target_counter}, - {"target_scriptrunner", SP_target_scriptrunner}, - {"target_interest", SP_target_interest}, - {"target_activate", SP_target_activate}, - {"target_deactivate", SP_target_deactivate}, - {"target_gravity_change", SP_target_gravity_change}, - {"target_friction_change", SP_target_friction_change}, - {"target_level_change", SP_target_level_change}, - {"target_change_parm", SP_target_change_parm}, - {"target_play_music", SP_target_play_music}, - {"target_autosave", SP_target_autosave}, - {"target_secret", SP_target_secret}, - - {"light", SP_light}, - {"info_null", SP_info_null}, - {"func_group", SP_info_null}, - {"info_notnull", SP_info_notnull}, // use target_position instead - {"path_corner", SP_path_corner}, - - {"misc_teleporter", SP_misc_teleporter}, - {"misc_teleporter_dest", SP_misc_teleporter_dest}, - {"misc_model", SP_misc_model}, - {"misc_model_static", SP_misc_model_static}, - {"misc_turret", SP_misc_turret}, - {"misc_ns_turret", SP_misc_ns_turret}, - {"misc_laser_arm", SP_laser_arm}, - {"misc_ion_cannon", SP_misc_ion_cannon}, - {"misc_sentry_turret", SP_PAS}, - {"misc_maglock", SP_misc_maglock}, - {"misc_weapon_shooter", SP_misc_weapon_shooter}, - {"misc_weather_zone", SP_misc_weather_zone}, - - {"misc_model_ghoul", SP_misc_model_ghoul}, - {"misc_model_breakable", SP_misc_model_breakable}, - {"misc_portal_surface", SP_misc_portal_surface}, - {"misc_portal_camera", SP_misc_portal_camera}, - - {"misc_bsp", SP_misc_bsp}, - {"terrain", SP_terrain}, - {"misc_skyportal", SP_misc_skyportal}, - - {"misc_camera_focus", SP_misc_camera_focus}, - {"misc_camera_track", SP_misc_camera_track}, - {"misc_dlight", SP_misc_dlight}, - {"misc_replicator_item", SP_misc_replicator_item}, - {"misc_trip_mine", SP_misc_trip_mine}, - {"misc_security_panel", SP_misc_security_panel}, - {"misc_camera", SP_misc_camera}, - {"misc_spotlight", SP_misc_spotlight}, - {"misc_panel_turret", SP_misc_panel_turret}, - {"misc_model_welder", SP_misc_model_welder}, - {"misc_model_jabba_cam", SP_misc_model_jabba_cam}, - {"misc_model_shield_power_converter", SP_misc_model_shield_power_converter}, - {"misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter}, - {"misc_model_bomb_planted", SP_misc_model_bomb_planted}, - {"misc_model_beacon", SP_misc_model_beacon}, - {"misc_shield_floor_unit", SP_misc_shield_floor_unit}, - {"misc_ammo_floor_unit", SP_misc_ammo_floor_unit}, - - {"misc_model_gun_rack", SP_misc_model_gun_rack}, - {"misc_model_ammo_rack", SP_misc_model_ammo_rack}, - {"misc_model_cargo_small", SP_misc_model_cargo_small}, - - {"misc_exploding_crate", SP_misc_exploding_crate}, - {"misc_gas_tank", SP_misc_gas_tank}, - {"misc_crystal_crate", SP_misc_crystal_crate}, - {"misc_atst_drivable", SP_misc_atst_drivable}, - - {"misc_cubemap", SP_misc_cubemap}, - - {"shooter_rocket", SP_shooter_rocket}, - {"shooter_grenade", SP_shooter_grenade}, - {"shooter_plasma", SP_shooter_plasma}, - - {"ref_tag", SP_reference_tag}, - - //new NPC ents - {"NPC_spawner", SP_NPC_spawner}, - - {"NPC_Vehicle", SP_NPC_Vehicle }, - {"NPC_Player", SP_NPC_Player }, - {"NPC_Kyle", SP_NPC_Kyle }, - {"NPC_Lando", SP_NPC_Lando }, - {"NPC_Jan", SP_NPC_Jan }, - {"NPC_Luke", SP_NPC_Luke }, - {"NPC_MonMothma", SP_NPC_MonMothma }, - {"NPC_Rosh_Penin", SP_NPC_Rosh_Penin }, - {"NPC_Tavion", SP_NPC_Tavion }, - {"NPC_Tavion_New", SP_NPC_Tavion_New }, - {"NPC_Alora", SP_NPC_Alora }, - {"NPC_Reelo", SP_NPC_Reelo }, - {"NPC_Galak", SP_NPC_Galak }, - {"NPC_Desann", SP_NPC_Desann }, - {"NPC_Rax", SP_NPC_Rax }, - {"NPC_BobaFett", SP_NPC_BobaFett }, - {"NPC_Ragnos", SP_NPC_Ragnos }, - {"NPC_Lannik_Racto", SP_NPC_Lannik_Racto }, - {"NPC_Kothos", SP_NPC_Kothos }, - {"NPC_Chewbacca", SP_NPC_Chewbacca }, - {"NPC_Bartender", SP_NPC_Bartender }, - {"NPC_MorganKatarn", SP_NPC_MorganKatarn }, - {"NPC_Jedi", SP_NPC_Jedi }, - {"NPC_Prisoner", SP_NPC_Prisoner }, - {"NPC_Merchant", SP_NPC_Merchant }, - {"NPC_Rebel", SP_NPC_Rebel }, - {"NPC_Human_Merc", SP_NPC_Human_Merc }, - {"NPC_Stormtrooper", SP_NPC_Stormtrooper }, - {"NPC_StormtrooperOfficer", SP_NPC_StormtrooperOfficer }, - {"NPC_Tie_Pilot", SP_NPC_Tie_Pilot }, - {"NPC_Snowtrooper", SP_NPC_Snowtrooper }, - {"NPC_RocketTrooper", SP_NPC_RocketTrooper }, - {"NPC_HazardTrooper", SP_NPC_HazardTrooper }, - - {"NPC_Ugnaught", SP_NPC_Ugnaught }, - {"NPC_Jawa", SP_NPC_Jawa }, - {"NPC_Gran", SP_NPC_Gran }, - {"NPC_Rodian", SP_NPC_Rodian }, - {"NPC_Weequay", SP_NPC_Weequay }, - {"NPC_Trandoshan", SP_NPC_Trandoshan }, - {"NPC_Tusken", SP_NPC_Tusken }, - {"NPC_Noghri", SP_NPC_Noghri }, - {"NPC_SwampTrooper", SP_NPC_SwampTrooper }, - {"NPC_Imperial", SP_NPC_Imperial }, - {"NPC_ImpWorker", SP_NPC_ImpWorker }, - {"NPC_BespinCop", SP_NPC_BespinCop }, - {"NPC_Reborn", SP_NPC_Reborn }, - {"NPC_Reborn_New", SP_NPC_Reborn_New }, - {"NPC_Cultist", SP_NPC_Cultist }, - {"NPC_Cultist_Saber", SP_NPC_Cultist_Saber }, - {"NPC_Cultist_Saber_Powers", SP_NPC_Cultist_Saber_Powers }, - {"NPC_Cultist_Destroyer", SP_NPC_Cultist_Destroyer }, - {"NPC_Cultist_Commando", SP_NPC_Cultist_Commando }, - {"NPC_ShadowTrooper", SP_NPC_ShadowTrooper }, - {"NPC_Saboteur", SP_NPC_Saboteur }, - {"NPC_Monster_Murjj", SP_NPC_Monster_Murjj }, - {"NPC_Monster_Swamp", SP_NPC_Monster_Swamp }, - {"NPC_Monster_Howler", SP_NPC_Monster_Howler }, - {"NPC_Monster_Rancor", SP_NPC_Monster_Rancor }, - {"NPC_Monster_Mutant_Rancor", SP_NPC_Monster_Mutant_Rancor }, - {"NPC_Monster_Wampa", SP_NPC_Monster_Wampa }, - {"NPC_MineMonster", SP_NPC_MineMonster }, - {"NPC_Monster_Claw", SP_NPC_Monster_Claw }, - {"NPC_Monster_Glider", SP_NPC_Monster_Glider }, - {"NPC_Monster_Flier2", SP_NPC_Monster_Flier2 }, - {"NPC_Monster_Lizard", SP_NPC_Monster_Lizard }, - {"NPC_Monster_Fish", SP_NPC_Monster_Fish }, - {"NPC_Monster_Sand_Creature", SP_NPC_Monster_Sand_Creature }, - {"NPC_Droid_Interrogator", SP_NPC_Droid_Interrogator }, - {"NPC_Droid_Probe", SP_NPC_Droid_Probe }, - {"NPC_Droid_Mark1", SP_NPC_Droid_Mark1 }, - {"NPC_Droid_Mark2", SP_NPC_Droid_Mark2 }, - {"NPC_Droid_ATST", SP_NPC_Droid_ATST }, - {"NPC_Droid_Seeker", SP_NPC_Droid_Seeker }, - {"NPC_Droid_Remote", SP_NPC_Droid_Remote }, - {"NPC_Droid_Sentry", SP_NPC_Droid_Sentry }, - {"NPC_Droid_Gonk", SP_NPC_Droid_Gonk }, - {"NPC_Droid_Mouse", SP_NPC_Droid_Mouse }, - {"NPC_Droid_R2D2", SP_NPC_Droid_R2D2 }, - {"NPC_Droid_R5D2", SP_NPC_Droid_R5D2 }, - {"NPC_Droid_Protocol", SP_NPC_Droid_Protocol }, - {"NPC_Droid_Assassin", SP_NPC_Droid_Assassin }, - {"NPC_Droid_Saber", SP_NPC_Droid_Saber }, - - //rwwFIXMEFIXME: Faked for testing NPCs (another other things) in RMG with sof2 assets - {"NPC_Colombian_Soldier", SP_NPC_Reborn }, - {"NPC_Colombian_Rebel", SP_NPC_Reborn }, - {"NPC_Colombian_EmplacedGunner", SP_NPC_ShadowTrooper }, - {"NPC_Manuel_Vergara_RMG", SP_NPC_Desann }, -// {"info_NPCnav", SP_waypoint}, - - {"waypoint", SP_waypoint}, - {"waypoint_small", SP_waypoint_small}, - {"waypoint_navgoal", SP_waypoint_navgoal}, - - {"fx_runner", SP_fx_runner}, - {"fx_explosion_trail", SP_fx_explosion_trail}, - {"fx_target_beam", SP_fx_target_beam}, - {"fx_cloudlayer", SP_fx_cloudlayer}, - {"fx_rain", SP_CreateRain}, - {"fx_wind", SP_CreateWind}, - {"fx_snow", SP_CreateSnow}, - {"fx_puff", SP_CreatePuffSystem}, - {"fx_wind_zone", SP_CreateWindZone}, - - {"object_cargo_barrel1", SP_object_cargo_barrel1}, - {"point_combat", SP_point_combat}, - - {"emplaced_gun", SP_emplaced_gun}, - {"emplaced_eweb", SP_emplaced_eweb}, - - {NULL, NULL} -}; +void SP_CreatePuffSystem(gentity_t *ent); + +void SP_object_cargo_barrel1(gentity_t *ent); + +void SP_point_combat(gentity_t *self); + +void SP_emplaced_eweb(gentity_t *self); +void SP_emplaced_gun(gentity_t *self); + +void SP_misc_turbobattery(gentity_t *base); + +spawn_t spawns[] = {{"info_player_start", SP_info_player_start}, + {"info_player_deathmatch", SP_info_player_deathmatch}, + + {"func_plat", SP_func_plat}, + {"func_button", SP_func_button}, + {"func_door", SP_func_door}, + {"func_static", SP_func_static}, + {"func_rotating", SP_func_rotating}, + {"func_bobbing", SP_func_bobbing}, + {"func_breakable", SP_func_breakable}, + {"func_pendulum", SP_func_pendulum}, + {"func_train", SP_func_train}, + {"func_timer", SP_func_timer}, // rename trigger_timer? + {"func_wall", SP_func_wall}, + {"func_usable", SP_func_usable}, + {"func_glass", SP_func_glass}, + + {"rail_mover", SP_rail_mover}, + {"rail_track", SP_rail_track}, + {"rail_lane", SP_rail_lane}, + + {"trigger_always", SP_trigger_always}, + {"trigger_multiple", SP_trigger_multiple}, + {"trigger_once", SP_trigger_once}, + {"trigger_push", SP_trigger_push}, + {"trigger_teleport", SP_trigger_teleport}, + {"trigger_hurt", SP_trigger_hurt}, + {"trigger_bidirectional", SP_trigger_bidirectional}, + {"trigger_entdist", SP_trigger_entdist}, + {"trigger_location", SP_trigger_location}, + {"trigger_visible", SP_trigger_visible}, + {"trigger_space", SP_trigger_space}, + {"trigger_shipboundary", SP_trigger_shipboundary}, + + {"target_give", SP_target_give}, + {"target_delay", SP_target_delay}, + {"target_speaker", SP_target_speaker}, + {"target_print", SP_target_print}, + {"target_laser", SP_target_laser}, + {"target_score", SP_target_score}, + {"target_teleporter", SP_target_teleporter}, + {"target_relay", SP_target_relay}, + {"target_kill", SP_target_kill}, + {"target_position", SP_target_position}, + {"target_location", SP_target_location}, + {"target_push", SP_target_push}, + {"target_random", SP_target_random}, + {"target_counter", SP_target_counter}, + {"target_scriptrunner", SP_target_scriptrunner}, + {"target_interest", SP_target_interest}, + {"target_activate", SP_target_activate}, + {"target_deactivate", SP_target_deactivate}, + {"target_gravity_change", SP_target_gravity_change}, + {"target_friction_change", SP_target_friction_change}, + {"target_level_change", SP_target_level_change}, + {"target_change_parm", SP_target_change_parm}, + {"target_play_music", SP_target_play_music}, + {"target_autosave", SP_target_autosave}, + {"target_secret", SP_target_secret}, + + {"light", SP_light}, + {"info_null", SP_info_null}, + {"func_group", SP_info_null}, + {"info_notnull", SP_info_notnull}, // use target_position instead + {"path_corner", SP_path_corner}, + + {"misc_teleporter", SP_misc_teleporter}, + {"misc_teleporter_dest", SP_misc_teleporter_dest}, + {"misc_model", SP_misc_model}, + {"misc_model_static", SP_misc_model_static}, + {"misc_turret", SP_misc_turret}, + {"misc_ns_turret", SP_misc_ns_turret}, + {"misc_laser_arm", SP_laser_arm}, + {"misc_ion_cannon", SP_misc_ion_cannon}, + {"misc_sentry_turret", SP_PAS}, + {"misc_maglock", SP_misc_maglock}, + {"misc_weapon_shooter", SP_misc_weapon_shooter}, + {"misc_weather_zone", SP_misc_weather_zone}, + + {"misc_model_ghoul", SP_misc_model_ghoul}, + {"misc_model_breakable", SP_misc_model_breakable}, + {"misc_portal_surface", SP_misc_portal_surface}, + {"misc_portal_camera", SP_misc_portal_camera}, + + {"misc_bsp", SP_misc_bsp}, + {"terrain", SP_terrain}, + {"misc_skyportal", SP_misc_skyportal}, + + {"misc_camera_focus", SP_misc_camera_focus}, + {"misc_camera_track", SP_misc_camera_track}, + {"misc_dlight", SP_misc_dlight}, + {"misc_replicator_item", SP_misc_replicator_item}, + {"misc_trip_mine", SP_misc_trip_mine}, + {"misc_security_panel", SP_misc_security_panel}, + {"misc_camera", SP_misc_camera}, + {"misc_spotlight", SP_misc_spotlight}, + {"misc_panel_turret", SP_misc_panel_turret}, + {"misc_model_welder", SP_misc_model_welder}, + {"misc_model_jabba_cam", SP_misc_model_jabba_cam}, + {"misc_model_shield_power_converter", SP_misc_model_shield_power_converter}, + {"misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter}, + {"misc_model_bomb_planted", SP_misc_model_bomb_planted}, + {"misc_model_beacon", SP_misc_model_beacon}, + {"misc_shield_floor_unit", SP_misc_shield_floor_unit}, + {"misc_ammo_floor_unit", SP_misc_ammo_floor_unit}, + + {"misc_model_gun_rack", SP_misc_model_gun_rack}, + {"misc_model_ammo_rack", SP_misc_model_ammo_rack}, + {"misc_model_cargo_small", SP_misc_model_cargo_small}, + + {"misc_exploding_crate", SP_misc_exploding_crate}, + {"misc_gas_tank", SP_misc_gas_tank}, + {"misc_crystal_crate", SP_misc_crystal_crate}, + {"misc_atst_drivable", SP_misc_atst_drivable}, + + {"misc_cubemap", SP_misc_cubemap}, + + {"shooter_rocket", SP_shooter_rocket}, + {"shooter_grenade", SP_shooter_grenade}, + {"shooter_plasma", SP_shooter_plasma}, + + {"ref_tag", SP_reference_tag}, + + // new NPC ents + {"NPC_spawner", SP_NPC_spawner}, + + {"NPC_Vehicle", SP_NPC_Vehicle}, + {"NPC_Player", SP_NPC_Player}, + {"NPC_Kyle", SP_NPC_Kyle}, + {"NPC_Lando", SP_NPC_Lando}, + {"NPC_Jan", SP_NPC_Jan}, + {"NPC_Luke", SP_NPC_Luke}, + {"NPC_MonMothma", SP_NPC_MonMothma}, + {"NPC_Rosh_Penin", SP_NPC_Rosh_Penin}, + {"NPC_Tavion", SP_NPC_Tavion}, + {"NPC_Tavion_New", SP_NPC_Tavion_New}, + {"NPC_Alora", SP_NPC_Alora}, + {"NPC_Reelo", SP_NPC_Reelo}, + {"NPC_Galak", SP_NPC_Galak}, + {"NPC_Desann", SP_NPC_Desann}, + {"NPC_Rax", SP_NPC_Rax}, + {"NPC_BobaFett", SP_NPC_BobaFett}, + {"NPC_Ragnos", SP_NPC_Ragnos}, + {"NPC_Lannik_Racto", SP_NPC_Lannik_Racto}, + {"NPC_Kothos", SP_NPC_Kothos}, + {"NPC_Chewbacca", SP_NPC_Chewbacca}, + {"NPC_Bartender", SP_NPC_Bartender}, + {"NPC_MorganKatarn", SP_NPC_MorganKatarn}, + {"NPC_Jedi", SP_NPC_Jedi}, + {"NPC_Prisoner", SP_NPC_Prisoner}, + {"NPC_Merchant", SP_NPC_Merchant}, + {"NPC_Rebel", SP_NPC_Rebel}, + {"NPC_Human_Merc", SP_NPC_Human_Merc}, + {"NPC_Stormtrooper", SP_NPC_Stormtrooper}, + {"NPC_StormtrooperOfficer", SP_NPC_StormtrooperOfficer}, + {"NPC_Tie_Pilot", SP_NPC_Tie_Pilot}, + {"NPC_Snowtrooper", SP_NPC_Snowtrooper}, + {"NPC_RocketTrooper", SP_NPC_RocketTrooper}, + {"NPC_HazardTrooper", SP_NPC_HazardTrooper}, + + {"NPC_Ugnaught", SP_NPC_Ugnaught}, + {"NPC_Jawa", SP_NPC_Jawa}, + {"NPC_Gran", SP_NPC_Gran}, + {"NPC_Rodian", SP_NPC_Rodian}, + {"NPC_Weequay", SP_NPC_Weequay}, + {"NPC_Trandoshan", SP_NPC_Trandoshan}, + {"NPC_Tusken", SP_NPC_Tusken}, + {"NPC_Noghri", SP_NPC_Noghri}, + {"NPC_SwampTrooper", SP_NPC_SwampTrooper}, + {"NPC_Imperial", SP_NPC_Imperial}, + {"NPC_ImpWorker", SP_NPC_ImpWorker}, + {"NPC_BespinCop", SP_NPC_BespinCop}, + {"NPC_Reborn", SP_NPC_Reborn}, + {"NPC_Reborn_New", SP_NPC_Reborn_New}, + {"NPC_Cultist", SP_NPC_Cultist}, + {"NPC_Cultist_Saber", SP_NPC_Cultist_Saber}, + {"NPC_Cultist_Saber_Powers", SP_NPC_Cultist_Saber_Powers}, + {"NPC_Cultist_Destroyer", SP_NPC_Cultist_Destroyer}, + {"NPC_Cultist_Commando", SP_NPC_Cultist_Commando}, + {"NPC_ShadowTrooper", SP_NPC_ShadowTrooper}, + {"NPC_Saboteur", SP_NPC_Saboteur}, + {"NPC_Monster_Murjj", SP_NPC_Monster_Murjj}, + {"NPC_Monster_Swamp", SP_NPC_Monster_Swamp}, + {"NPC_Monster_Howler", SP_NPC_Monster_Howler}, + {"NPC_Monster_Rancor", SP_NPC_Monster_Rancor}, + {"NPC_Monster_Mutant_Rancor", SP_NPC_Monster_Mutant_Rancor}, + {"NPC_Monster_Wampa", SP_NPC_Monster_Wampa}, + {"NPC_MineMonster", SP_NPC_MineMonster}, + {"NPC_Monster_Claw", SP_NPC_Monster_Claw}, + {"NPC_Monster_Glider", SP_NPC_Monster_Glider}, + {"NPC_Monster_Flier2", SP_NPC_Monster_Flier2}, + {"NPC_Monster_Lizard", SP_NPC_Monster_Lizard}, + {"NPC_Monster_Fish", SP_NPC_Monster_Fish}, + {"NPC_Monster_Sand_Creature", SP_NPC_Monster_Sand_Creature}, + {"NPC_Droid_Interrogator", SP_NPC_Droid_Interrogator}, + {"NPC_Droid_Probe", SP_NPC_Droid_Probe}, + {"NPC_Droid_Mark1", SP_NPC_Droid_Mark1}, + {"NPC_Droid_Mark2", SP_NPC_Droid_Mark2}, + {"NPC_Droid_ATST", SP_NPC_Droid_ATST}, + {"NPC_Droid_Seeker", SP_NPC_Droid_Seeker}, + {"NPC_Droid_Remote", SP_NPC_Droid_Remote}, + {"NPC_Droid_Sentry", SP_NPC_Droid_Sentry}, + {"NPC_Droid_Gonk", SP_NPC_Droid_Gonk}, + {"NPC_Droid_Mouse", SP_NPC_Droid_Mouse}, + {"NPC_Droid_R2D2", SP_NPC_Droid_R2D2}, + {"NPC_Droid_R5D2", SP_NPC_Droid_R5D2}, + {"NPC_Droid_Protocol", SP_NPC_Droid_Protocol}, + {"NPC_Droid_Assassin", SP_NPC_Droid_Assassin}, + {"NPC_Droid_Saber", SP_NPC_Droid_Saber}, + + // rwwFIXMEFIXME: Faked for testing NPCs (another other things) in RMG with sof2 assets + {"NPC_Colombian_Soldier", SP_NPC_Reborn}, + {"NPC_Colombian_Rebel", SP_NPC_Reborn}, + {"NPC_Colombian_EmplacedGunner", SP_NPC_ShadowTrooper}, + {"NPC_Manuel_Vergara_RMG", SP_NPC_Desann}, + // {"info_NPCnav", SP_waypoint}, + + {"waypoint", SP_waypoint}, + {"waypoint_small", SP_waypoint_small}, + {"waypoint_navgoal", SP_waypoint_navgoal}, + + {"fx_runner", SP_fx_runner}, + {"fx_explosion_trail", SP_fx_explosion_trail}, + {"fx_target_beam", SP_fx_target_beam}, + {"fx_cloudlayer", SP_fx_cloudlayer}, + {"fx_rain", SP_CreateRain}, + {"fx_wind", SP_CreateWind}, + {"fx_snow", SP_CreateSnow}, + {"fx_puff", SP_CreatePuffSystem}, + {"fx_wind_zone", SP_CreateWindZone}, + + {"object_cargo_barrel1", SP_object_cargo_barrel1}, + {"point_combat", SP_point_combat}, + + {"emplaced_gun", SP_emplaced_gun}, + {"emplaced_eweb", SP_emplaced_eweb}, + + {NULL, NULL}}; /* =============== @@ -868,35 +847,35 @@ Finds the spawn function for the entity and calls it, returning qfalse if not found =============== */ -qboolean G_CallSpawn( gentity_t *ent ) { - spawn_t *s; - gitem_t *item; +qboolean G_CallSpawn(gentity_t *ent) { + spawn_t *s; + gitem_t *item; - if ( !ent->classname ) { - gi.Printf (S_COLOR_RED"G_CallSpawn: NULL classname\n"); + if (!ent->classname) { + gi.Printf(S_COLOR_RED "G_CallSpawn: NULL classname\n"); return qfalse; } // check item spawn functions - for ( item=bg_itemlist+1 ; item->classname ; item++ ) { - if ( !strcmp(item->classname, ent->classname) ) { + for (item = bg_itemlist + 1; item->classname; item++) { + if (!strcmp(item->classname, ent->classname)) { // found it - G_SpawnItem( ent, item ); + G_SpawnItem(ent, item); return qtrue; } } // check normal spawn functions - for ( s=spawns ; s->name ; s++ ) { - if ( !strcmp(s->name, ent->classname) ) { + for (s = spawns; s->name; s++) { + if (!strcmp(s->name, ent->classname)) { // found it s->spawn(ent); return qtrue; } } - char* str; - G_SpawnString( "origin", "?", &str ); - gi.Printf (S_COLOR_RED"ERROR: %s is not a spawn function @(%s)\n", ent->classname, str); + char *str; + G_SpawnString("origin", "?", &str); + gi.Printf(S_COLOR_RED "ERROR: %s is not a spawn function @(%s)\n", ent->classname, str); delayedShutDown = level.time + 100; return qfalse; } @@ -909,25 +888,24 @@ Builds a copy of the string, translating \n to real linefeeds so message texts can be multi-line ============= */ -char *G_NewString( const char *string ) { - char *newb, *new_p; - int i,l; +char *G_NewString(const char *string) { + char *newb, *new_p; + int i, l; - if(!string || !string[0]) - { - //gi.Printf(S_COLOR_RED"Error: G_NewString called with NULL string!\n"); + if (!string || !string[0]) { + // gi.Printf(S_COLOR_RED"Error: G_NewString called with NULL string!\n"); return NULL; } l = strlen(string) + 1; - newb = (char *) G_Alloc( l ); + newb = (char *)G_Alloc(l); new_p = newb; // turn \n into a real linefeed - for ( i=0 ; i< l ; i++ ) { - if (string[i] == '\\' && i < l-1) { + for (i = 0; i < l; i++) { + if (string[i] == '\\' && i < l - 1) { i++; if (string[i] == 'n') { *new_p++ = '\n'; @@ -942,9 +920,6 @@ char *G_NewString( const char *string ) { return newb; } - - - /* =============== G_ParseField @@ -953,63 +928,59 @@ Takes a key/value pair and sets the binary values in a gentity =============== */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue); -void G_ParseField( const char *key, const char *value, gentity_t *ent ) { - field_t *f; - byte *b; - float v; - vec3_t vec; - vec4_t vec4; - - for ( f=fields ; f->name ; f++ ) { - if ( !Q_stricmp(f->name, key) ) { +void Q3_SetParm(int entID, int parmNum, const char *parmValue); +void G_ParseField(const char *key, const char *value, gentity_t *ent) { + field_t *f; + byte *b; + float v; + vec3_t vec; + vec4_t vec4; + + for (f = fields; f->name; f++) { + if (!Q_stricmp(f->name, key)) { // found it b = (byte *)ent; - switch( f->type ) { + switch (f->type) { case F_LSTRING: - *(char **)(b+f->ofs) = G_NewString (value); + *(char **)(b + f->ofs) = G_NewString(value); break; - case F_VECTOR: - { - int _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - assert(_iFieldsRead==3); - if (_iFieldsRead!=3) - { - gi.Printf (S_COLOR_YELLOW"G_ParseField: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + case F_VECTOR: { + int _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + assert(_iFieldsRead == 3); + if (_iFieldsRead != 3) { + gi.Printf(S_COLOR_YELLOW "G_ParseField: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); delayedShutDown = level.time + 100; } - ((float *)(b+f->ofs))[0] = vec[0]; - ((float *)(b+f->ofs))[1] = vec[1]; - ((float *)(b+f->ofs))[2] = vec[2]; + ((float *)(b + f->ofs))[0] = vec[0]; + ((float *)(b + f->ofs))[1] = vec[1]; + ((float *)(b + f->ofs))[2] = vec[2]; break; } - case F_VECTOR4: - { - int _iFieldsRead = sscanf (value, "%f %f %f %f", &vec4[0], &vec4[1], &vec4[2], &vec4[3]); - assert(_iFieldsRead==4); - if (_iFieldsRead!=4) - { - gi.Printf (S_COLOR_YELLOW"G_ParseField: VEC4 sscanf() failed to read 4 floats\n"); + case F_VECTOR4: { + int _iFieldsRead = sscanf(value, "%f %f %f %f", &vec4[0], &vec4[1], &vec4[2], &vec4[3]); + assert(_iFieldsRead == 4); + if (_iFieldsRead != 4) { + gi.Printf(S_COLOR_YELLOW "G_ParseField: VEC4 sscanf() failed to read 4 floats\n"); delayedShutDown = level.time + 100; } - ((float *)(b+f->ofs))[0] = vec4[0]; - ((float *)(b+f->ofs))[1] = vec4[1]; - ((float *)(b+f->ofs))[2] = vec4[2]; - ((float *)(b+f->ofs))[3] = vec4[3]; + ((float *)(b + f->ofs))[0] = vec4[0]; + ((float *)(b + f->ofs))[1] = vec4[1]; + ((float *)(b + f->ofs))[2] = vec4[2]; + ((float *)(b + f->ofs))[3] = vec4[3]; break; } case F_INT: - *(int *)(b+f->ofs) = atoi(value); + *(int *)(b + f->ofs) = atoi(value); break; case F_FLOAT: - *(float *)(b+f->ofs) = atof(value); + *(float *)(b + f->ofs) = atof(value); break; case F_ANGLEHACK: v = atof(value); - ((float *)(b+f->ofs))[0] = 0; - ((float *)(b+f->ofs))[1] = v; - ((float *)(b+f->ofs))[2] = 0; + ((float *)(b + f->ofs))[0] = 0; + ((float *)(b + f->ofs))[1] = v; + ((float *)(b + f->ofs))[2] = 0; break; case F_PARM1: case F_PARM2: @@ -1027,24 +998,19 @@ void G_ParseField( const char *key, const char *value, gentity_t *ent ) { case F_PARM14: case F_PARM15: case F_PARM16: - Q3_SetParm( ent->s.number, (f->type - F_PARM1), (char *) value ); + Q3_SetParm(ent->s.number, (f->type - F_PARM1), (char *)value); break; - case F_FLAG: - {//try to find the proper flag for that key: - int flag = GetIDForString ( flagTable, key ); - - if ( flag > 0 ) - { - G_SpawnFlag( key, flag, (int *)(b+f->ofs) ); - } - else - { + case F_FLAG: { // try to find the proper flag for that key: + int flag = GetIDForString(flagTable, key); + + if (flag > 0) { + G_SpawnFlag(key, flag, (int *)(b + f->ofs)); + } else { #ifndef FINAL_BUILD - gi.Printf (S_COLOR_YELLOW"WARNING: G_ParseField: can't find flag for key %s\n", key); + gi.Printf(S_COLOR_YELLOW "WARNING: G_ParseField: can't find flag for key %s\n", key); #endif - } } - break; + } break; default: case F_IGNORE: break; @@ -1053,21 +1019,19 @@ void G_ParseField( const char *key, const char *value, gentity_t *ent ) { } } #ifndef FINAL_BUILD - //didn't find it? - if (key[0]!='_') - { - gi.Printf ( S_COLOR_YELLOW"WARNING: G_ParseField: no such field: %s\n", key ); + // didn't find it? + if (key[0] != '_') { + gi.Printf(S_COLOR_YELLOW "WARNING: G_ParseField: no such field: %s\n", key); } #endif } -static qboolean SpawnForCurrentDifficultySetting( gentity_t *ent ) -{ -extern cvar_t *com_buildScript; - if (com_buildScript->integer) { //always spawn when building a pak file +static qboolean SpawnForCurrentDifficultySetting(gentity_t *ent) { + extern cvar_t *com_buildScript; + if (com_buildScript->integer) { // always spawn when building a pak file return qtrue; } - if ( ent->spawnflags & ( 1 << (8 + g_spskill->integer )) ) {// easy -256 medium -512 hard -1024 + if (ent->spawnflags & (1 << (8 + g_spskill->integer))) { // easy -256 medium -512 hard -1024 return qfalse; } else { return qtrue; @@ -1083,62 +1047,59 @@ level.spawnVars[], then call the class specfic spawn function =================== */ -void G_SpawnGEntityFromSpawnVars( void ) { - int i; - gentity_t *ent; +void G_SpawnGEntityFromSpawnVars(void) { + int i; + gentity_t *ent; // get the next free entity ent = G_Spawn(); - for ( i = 0 ; i < numSpawnVars ; i++ ) { - G_ParseField( spawnVars[i][0], spawnVars[i][1], ent ); + for (i = 0; i < numSpawnVars; i++) { + G_ParseField(spawnVars[i][0], spawnVars[i][1], ent); } - G_SpawnInt( "notsingle", "0", &i ); - if ( i || !SpawnForCurrentDifficultySetting( ent ) ) { - G_FreeEntity( ent ); + G_SpawnInt("notsingle", "0", &i); + if (i || !SpawnForCurrentDifficultySetting(ent)) { + G_FreeEntity(ent); return; } // move editor origin to pos - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // if we didn't get a classname, don't bother spawning anything - if ( !G_CallSpawn( ent ) ) { - G_FreeEntity( ent ); + if (!G_CallSpawn(ent)) { + G_FreeEntity(ent); return; } - //Tag on the ICARUS scripting information only to valid recipients - if ( Quake3Game()->ValidEntity( ent ) ) - { - Quake3Game()->InitEntity( ent ); //ICARUS_InitEnt( ent ); + // Tag on the ICARUS scripting information only to valid recipients + if (Quake3Game()->ValidEntity(ent)) { + Quake3Game()->InitEntity(ent); // ICARUS_InitEnt( ent ); - if ( ent->classname && ent->classname[0] ) - { - if ( Q_strncmp( "NPC_", ent->classname, 4 ) != 0 ) - {//Not an NPC_spawner - G_ActivateBehavior( ent, BSET_SPAWN ); + if (ent->classname && ent->classname[0]) { + if (Q_strncmp("NPC_", ent->classname, 4) != 0) { // Not an NPC_spawner + G_ActivateBehavior(ent, BSET_SPAWN); } } } } -void G_SpawnSubBSPGEntityFromSpawnVars( vec3_t posOffset, vec3_t angOffset ) { - int i; - gentity_t *ent; +void G_SpawnSubBSPGEntityFromSpawnVars(vec3_t posOffset, vec3_t angOffset) { + int i; + gentity_t *ent; // get the next free entity ent = G_Spawn(); - for ( i = 0 ; i < numSpawnVars ; i++ ) { - G_ParseField( spawnVars[i][0], spawnVars[i][1], ent ); + for (i = 0; i < numSpawnVars; i++) { + G_ParseField(spawnVars[i][0], spawnVars[i][1], ent); } - G_SpawnInt( "notsingle", "0", &i ); - if ( i || !SpawnForCurrentDifficultySetting( ent ) ) { - G_FreeEntity( ent ); + G_SpawnInt("notsingle", "0", &i); + if (i || !SpawnForCurrentDifficultySetting(ent)) { + G_FreeEntity(ent); return; } @@ -1149,48 +1110,44 @@ void G_SpawnSubBSPGEntityFromSpawnVars( vec3_t posOffset, vec3_t angOffset ) { VectorCopy(ent->s.angles, ent->currentAngles); // move editor origin to pos - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // if we didn't get a classname, don't bother spawning anything - if ( !G_CallSpawn( ent ) ) { - G_FreeEntity( ent ); + if (!G_CallSpawn(ent)) { + G_FreeEntity(ent); return; } - //Tag on the ICARUS scripting information only to valid recipients - if ( Quake3Game()->ValidEntity( ent ) ) - { + // Tag on the ICARUS scripting information only to valid recipients + if (Quake3Game()->ValidEntity(ent)) { - Quake3Game()->InitEntity( ent ); // ICARUS_InitEnt( ent ); + Quake3Game()->InitEntity(ent); // ICARUS_InitEnt( ent ); - if ( ent->classname && ent->classname[0] ) - { - if ( Q_strncmp( "NPC_", ent->classname, 4 ) != 0 ) - {//Not an NPC_spawner - G_ActivateBehavior( ent, BSET_SPAWN ); + if (ent->classname && ent->classname[0]) { + if (Q_strncmp("NPC_", ent->classname, 4) != 0) { // Not an NPC_spawner + G_ActivateBehavior(ent, BSET_SPAWN); } } } } - /* ==================== G_AddSpawnVarToken ==================== */ -char *G_AddSpawnVarToken( const char *string ) { - int l; - char *dest; +char *G_AddSpawnVarToken(const char *string) { + int l; + char *dest; - l = strlen( string ); - if ( numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) { - G_Error( "G_AddSpawnVarToken: MAX_SPAWN_VARS" ); + l = strlen(string); + if (numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS) { + G_Error("G_AddSpawnVarToken: MAX_SPAWN_VARS"); } dest = spawnVarChars + numSpawnVarChars; - memcpy( dest, string, l+1 ); + memcpy(dest, string, l + 1); numSpawnVarChars += l + 1; @@ -1207,57 +1164,57 @@ level's entity strings into level.spawnVars[] This does not actually spawn an entity. ==================== */ -qboolean G_ParseSpawnVars( const char **data ) { - char keyname[MAX_STRING_CHARS]; - const char *com_token; +qboolean G_ParseSpawnVars(const char **data) { + char keyname[MAX_STRING_CHARS]; + const char *com_token; numSpawnVars = 0; numSpawnVarChars = 0; // parse the opening brace COM_BeginParseSession(); - com_token = COM_Parse( data ); - if ( !*data ) { + com_token = COM_Parse(data); + if (!*data) { // end of spawn string COM_EndParseSession(); return qfalse; } - if ( com_token[0] != '{' ) { + if (com_token[0] != '{') { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: found %s when expecting {",com_token ); + G_Error("G_ParseSpawnVars: found %s when expecting {", com_token); } // go through all the key / value pairs - while ( 1 ) { + while (1) { // parse key - com_token = COM_Parse( data ); - if ( !*data ) { + com_token = COM_Parse(data); + if (!*data) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: EOF without closing brace" ); + G_Error("G_ParseSpawnVars: EOF without closing brace"); } - if ( com_token[0] == '}' ) { + if (com_token[0] == '}') { break; } - Q_strncpyz( keyname, com_token, sizeof(keyname) ); + Q_strncpyz(keyname, com_token, sizeof(keyname)); // parse value - com_token = COM_Parse( data ); - if ( !*data ) { + com_token = COM_Parse(data); + if (!*data) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: EOF without closing brace" ); + G_Error("G_ParseSpawnVars: EOF without closing brace"); } - if ( com_token[0] == '}' ) { + if (com_token[0] == '}') { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: closing brace without data" ); + G_Error("G_ParseSpawnVars: closing brace without data"); } - if ( numSpawnVars == MAX_SPAWN_VARS ) { + if (numSpawnVars == MAX_SPAWN_VARS) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: MAX_SPAWN_VARS" ); + G_Error("G_ParseSpawnVars: MAX_SPAWN_VARS"); } - spawnVars[ numSpawnVars ][0] = G_AddSpawnVarToken( keyname ); - spawnVars[ numSpawnVars ][1] = G_AddSpawnVarToken( com_token ); + spawnVars[numSpawnVars][0] = G_AddSpawnVarToken(keyname); + spawnVars[numSpawnVars][1] = G_AddSpawnVarToken(com_token); numSpawnVars++; } @@ -1265,170 +1222,72 @@ qboolean G_ParseSpawnVars( const char **data ) { return qtrue; } -static const char *defaultStyles[LS_NUM_STYLES][3] = -{ - { // 0 normal - "z", - "z", - "z" - }, - { // 1 FLICKER (first variety) - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo" - }, - { // 2 SLOW STRONG PULSE - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb" - }, - { // 3 CANDLE (first variety) - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg" - }, - { // 4 FAST STROBE - "mamamamamama", - "mamamamamama", - "mamamamamama" - }, - { // 5 GENTLE PULSE 1 - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj" - }, - { // 6 FLICKER (second variety) - "nmonqnmomnmomomno", - "nmonqnmomnmomomno", - "nmonqnmomnmomomno" - }, - { // 7 CANDLE (second variety) - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm" - }, - { // 8 CANDLE (third variety) - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa" - }, - { // 9 SLOW STROBE (fourth variety) - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz" - }, - { // 10 FLUORESCENT FLICKER - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma" - }, - { // 11 SLOW PULSE NOT FADE TO BLACK - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba" - }, - { // 12 FAST PULSE FOR JEREMY - "mkigegik", - "mkigegik", - "mkigegik" - }, - { // 13 Test Blending - "abcdefghijklmqrstuvwxyz", - "zyxwvutsrqmlkjihgfedcba", - "aammbbzzccllcckkffyyggp" - }, - { // 14 - "", - "", - "" - }, - { // 15 - "", - "", - "" - }, - { // 16 - "", - "", - "" - }, - { // 17 - "", - "", - "" - }, - { // 18 - "", - "", - "" - }, - { // 19 - "", - "", - "" - }, - { // 20 - "", - "", - "" - }, - { // 21 - "", - "", - "" - }, - { // 22 - "", - "", - "" - }, - { // 23 - "", - "", - "" - }, - { // 24 - "", - "", - "" - }, - { // 25 - "", - "", - "" - }, - { // 26 - "", - "", - "" - }, - { // 27 - "", - "", - "" - }, - { // 28 - "", - "", - "" - }, - { // 29 - "", - "", - "" - }, - { // 30 - "", - "", - "" - }, - { // 31 - "", - "", - "" - } -}; - +static const char *defaultStyles[LS_NUM_STYLES][3] = { + {// 0 normal + "z", "z", "z"}, + {// 1 FLICKER (first variety) + "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo"}, + {// 2 SLOW STRONG PULSE + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb"}, + {// 3 CANDLE (first variety) + "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg"}, + {// 4 FAST STROBE + "mamamamamama", "mamamamamama", "mamamamamama"}, + {// 5 GENTLE PULSE 1 + "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj"}, + {// 6 FLICKER (second variety) + "nmonqnmomnmomomno", "nmonqnmomnmomomno", "nmonqnmomnmomomno"}, + {// 7 CANDLE (second variety) + "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm"}, + {// 8 CANDLE (third variety) + "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa"}, + {// 9 SLOW STROBE (fourth variety) + "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz"}, + {// 10 FLUORESCENT FLICKER + "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma"}, + {// 11 SLOW PULSE NOT FADE TO BLACK + "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba"}, + {// 12 FAST PULSE FOR JEREMY + "mkigegik", "mkigegik", "mkigegik"}, + {// 13 Test Blending + "abcdefghijklmqrstuvwxyz", "zyxwvutsrqmlkjihgfedcba", "aammbbzzccllcckkffyyggp"}, + {// 14 + "", "", ""}, + {// 15 + "", "", ""}, + {// 16 + "", "", ""}, + {// 17 + "", "", ""}, + {// 18 + "", "", ""}, + {// 19 + "", "", ""}, + {// 20 + "", "", ""}, + {// 21 + "", "", ""}, + {// 22 + "", "", ""}, + {// 23 + "", "", ""}, + {// 24 + "", "", ""}, + {// 25 + "", "", ""}, + {// 26 + "", "", ""}, + {// 27 + "", "", ""}, + {// 28 + "", "", ""}, + {// 29 + "", "", ""}, + {// 30 + "", "", ""}, + {// 31 + "", "", ""}}; /*QUAKED worldspawn (0 0 0) ? Every map should have exactly one worldspawn. @@ -1454,90 +1313,81 @@ Game Options "clearstats" default 1, if 0 loading this map will not clear the stats for player "tier_storyinfo" sets 'tier_storyinfo' cvar */ -void SP_worldspawn( void ) { - char *s; - int i; +void SP_worldspawn(void) { + char *s; + int i; g_entities[ENTITYNUM_WORLD].max_health = 0; - for ( i = 0 ; i < numSpawnVars ; i++ ) - { - if ( Q_stricmp( "spawnscript", spawnVars[i][0] ) == 0 ) - {//ONly let them set spawnscript, we don't want them setting an angle or something on the world. - G_ParseField( spawnVars[i][0], spawnVars[i][1], &g_entities[ENTITYNUM_WORLD] ); + for (i = 0; i < numSpawnVars; i++) { + if (Q_stricmp("spawnscript", spawnVars[i][0]) == 0) { // ONly let them set spawnscript, we don't want them setting an angle or something on the world. + G_ParseField(spawnVars[i][0], spawnVars[i][1], &g_entities[ENTITYNUM_WORLD]); } - if ( Q_stricmp( "region", spawnVars[i][0] ) == 0 ) - { + if (Q_stricmp("region", spawnVars[i][0]) == 0) { g_entities[ENTITYNUM_WORLD].s.radius = atoi(spawnVars[i][1]); } - if ( Q_stricmp( "distancecull", spawnVars[i][0] ) == 0 ) - { + if (Q_stricmp("distancecull", spawnVars[i][0]) == 0) { g_entities[ENTITYNUM_WORLD].max_health = (int)((float)(atoi(spawnVars[i][1])) * 0.7f); } } - G_SpawnString( "classname", "", &s ); - if ( Q_stricmp( s, "worldspawn" ) ) { - G_Error( "SP_worldspawn: The first entity isn't 'worldspawn'" ); + G_SpawnString("classname", "", &s); + if (Q_stricmp(s, "worldspawn")) { + G_Error("SP_worldspawn: The first entity isn't 'worldspawn'"); } // make some data visible to connecting client - G_SpawnString( "music", "", &s ); - gi.SetConfigstring( CS_MUSIC, s ); + G_SpawnString("music", "", &s); + gi.SetConfigstring(CS_MUSIC, s); - G_SpawnString( "message", "", &s ); - gi.SetConfigstring( CS_MESSAGE, s ); // map specific message + G_SpawnString("message", "", &s); + gi.SetConfigstring(CS_MESSAGE, s); // map specific message - G_SpawnString( "gravity", "800", &s ); + G_SpawnString("gravity", "800", &s); extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; - if (g_eSavedGameJustLoaded != eFULL) - { - gi.cvar_set( "g_gravity", s ); + if (g_eSavedGameJustLoaded != eFULL) { + gi.cvar_set("g_gravity", s); } - G_SpawnString( "soundSet", "default", &s ); - gi.SetConfigstring( CS_AMBIENT_SET, s ); + G_SpawnString("soundSet", "default", &s); + gi.SetConfigstring(CS_AMBIENT_SET, s); - //Lightstyles - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+0, defaultStyles[0][0]); - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+1, defaultStyles[0][1]); - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+2, defaultStyles[0][2]); + // Lightstyles + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 0, defaultStyles[0][0]); + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 1, defaultStyles[0][1]); + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 2, defaultStyles[0][2]); - for(i=1;iclear(); - for ( int i = 0; i < globals.num_entities; i++ ) - { + for (int i = 0; i < globals.num_entities; i++) { ent = &g_entities[i]; - if VALIDSTRING( ent->soundSet ) - { - (*as_preCacheMap)[ (char *) ent->soundSet ] = 1; + if VALIDSTRING (ent->soundSet) { + (*as_preCacheMap)[(char *)ent->soundSet] = 1; } } } - -void G_ASPreCacheFree(void) -{ - if(as_preCacheMap) { +void G_ASPreCacheFree(void) { + if (as_preCacheMap) { delete as_preCacheMap; as_preCacheMap = NULL; } @@ -1589,17 +1434,13 @@ Parses textual entity definitions out of an entstring and spawns gentities. ============== */ extern int num_waypoints; -extern void RG_RouteGen(void); +extern void RG_RouteGen(void); extern qboolean NPCsPrecached; -qboolean SP_bsp_worldspawn ( void ) -{ - return qtrue; -} +qboolean SP_bsp_worldspawn(void) { return qtrue; } -void G_SubBSPSpawnEntitiesFromString(const char *entityString, vec3_t posOffset, vec3_t angOffset) -{ - const char *entities; +void G_SubBSPSpawnEntitiesFromString(const char *entityString, vec3_t posOffset, vec3_t angOffset) { + const char *entities; entities = entityString; @@ -1611,25 +1452,23 @@ void G_SubBSPSpawnEntitiesFromString(const char *entityString, vec3_t posOffset, // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) - if ( !G_ParseSpawnVars( &entities ) ) { - G_Error( "SpawnEntities: no entities" ); + if (!G_ParseSpawnVars(&entities)) { + G_Error("SpawnEntities: no entities"); } // Skip this guy if its worldspawn fails - if ( !SP_bsp_worldspawn() ) - { + if (!SP_bsp_worldspawn()) { return; } // parse ents - while( G_ParseSpawnVars(&entities) ) - { + while (G_ParseSpawnVars(&entities)) { G_SpawnSubBSPGEntityFromSpawnVars(posOffset, angOffset); } } -void G_SpawnEntitiesFromString( const char *entityString ) { - const char *entities; +void G_SpawnEntitiesFromString(const char *entityString) { + const char *entities; entities = entityString; @@ -1641,50 +1480,44 @@ void G_SpawnEntitiesFromString( const char *entityString ) { // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) - if ( !G_ParseSpawnVars( &entities ) ) { - G_Error( "SpawnEntities: no entities" ); + if (!G_ParseSpawnVars(&entities)) { + G_Error("SpawnEntities: no entities"); } SP_worldspawn(); // parse ents - while( G_ParseSpawnVars( &entities ) ) - { + while (G_ParseSpawnVars(&entities)) { G_SpawnGEntityFromSpawnVars(); } - //Search the entities for precache information + // Search the entities for precache information G_ParsePrecaches(); - - if( g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0] ) - {//World has a spawn script, but we don't want the world in ICARUS and running scripts, - //so make a scriptrunner and start it going. + if (g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && + g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0]) { // World has a spawn script, but we don't want the world in ICARUS and running scripts, + // so make a scriptrunner and start it going. gentity_t *script_runner = G_Spawn(); - if ( script_runner ) - { + if (script_runner) { script_runner->behaviorSet[BSET_USE] = g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN]; script_runner->count = 1; script_runner->e_ThinkFunc = thinkF_scriptrunner_run; script_runner->nextthink = level.time + 100; - if ( Quake3Game()->ValidEntity( script_runner ) ) - { - Quake3Game()->InitEntity( script_runner ); //ICARUS_InitEnt( script_runner ); + if (Quake3Game()->ValidEntity(script_runner)) { + Quake3Game()->InitEntity(script_runner); // ICARUS_InitEnt( script_runner ); } } } - //gi.Printf(S_COLOR_YELLOW"Total waypoints: %d\n", num_waypoints); - //Automatically run routegen - //RG_RouteGen(); + // gi.Printf(S_COLOR_YELLOW"Total waypoints: %d\n", num_waypoints); + // Automatically run routegen + // RG_RouteGen(); - spawning = qfalse; // any future calls to G_Spawn*() will be errors + spawning = qfalse; // any future calls to G_Spawn*() will be errors - if ( g_delayedShutdown->integer && delayedShutDown ) - { + if (g_delayedShutdown->integer && delayedShutDown) { assert(0); - G_Error( "Errors loading map, check the console for them." ); + G_Error("Errors loading map, check the console for them."); } } - diff --git a/code/game/g_svcmds.cpp b/code/game/g_svcmds.cpp index f7d4faa344..c51ae08d06 100644 --- a/code/game/g_svcmds.cpp +++ b/code/game/g_svcmds.cpp @@ -28,98 +28,98 @@ along with this program; if not, see . #include "wp_saber.h" #include "g_functions.h" -extern void G_NextTestAxes( void ); -extern void G_ChangePlayerModel( gentity_t *ent, const char *newModel ); -extern void G_InitPlayerFromCvars( gentity_t *ent ); +extern void G_NextTestAxes(void); +extern void G_ChangePlayerModel(gentity_t *ent, const char *newModel); +extern void G_InitPlayerFromCvars(gentity_t *ent); extern void Q3_SetViewEntity(int entID, const char *name); -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); -extern void WP_SetSaber( gentity_t *ent, int saberNum, const char *saberName ); -extern void WP_RemoveSaber( gentity_t *ent, int saberNum ); -extern saber_colors_t TranslateSaberColor( const char *name ); -extern qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); -extern qboolean WP_UseFirstValidSaberStyle( gentity_t *ent, int *saberAnimLevel ); +extern void WP_SetSaber(gentity_t *ent, int saberNum, const char *saberName); +extern void WP_RemoveSaber(gentity_t *ent, int saberNum); +extern saber_colors_t TranslateSaberColor(const char *name); +extern qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); +extern qboolean WP_UseFirstValidSaberStyle(gentity_t *ent, int *saberAnimLevel); -extern void G_SetWeapon( gentity_t *self, int wp ); +extern void G_SetWeapon(gentity_t *self, int wp); extern stringID_table_t WPTable[]; -extern cvar_t *g_char_model; -extern cvar_t *g_char_skin_head; -extern cvar_t *g_char_skin_torso; -extern cvar_t *g_char_skin_legs; -extern cvar_t *g_char_color_red; -extern cvar_t *g_char_color_green; -extern cvar_t *g_char_color_blue; -extern cvar_t *g_saber; -extern cvar_t *g_saber2; -extern cvar_t *g_saber_color; -extern cvar_t *g_saber2_color; +extern cvar_t *g_char_model; +extern cvar_t *g_char_skin_head; +extern cvar_t *g_char_skin_torso; +extern cvar_t *g_char_skin_legs; +extern cvar_t *g_char_color_red; +extern cvar_t *g_char_color_green; +extern cvar_t *g_char_color_blue; +extern cvar_t *g_saber; +extern cvar_t *g_saber2; +extern cvar_t *g_saber_color; +extern cvar_t *g_saber2_color; /* =================== Svcmd_EntityList_f =================== */ -void Svcmd_EntityList_f (void) { - int e; - gentity_t *check; +void Svcmd_EntityList_f(void) { + int e; + gentity_t *check; check = g_entities; - for (e = 0; e < globals.num_entities ; e++, check++) { - if ( !check->inuse ) { + for (e = 0; e < globals.num_entities; e++, check++) { + if (!check->inuse) { continue; } gi.Printf("%3i:", e); - switch ( check->s.eType ) { + switch (check->s.eType) { case ET_GENERAL: - gi.Printf( "ET_GENERAL " ); + gi.Printf("ET_GENERAL "); break; case ET_PLAYER: - gi.Printf( "ET_PLAYER " ); + gi.Printf("ET_PLAYER "); break; case ET_ITEM: - gi.Printf( "ET_ITEM " ); + gi.Printf("ET_ITEM "); break; case ET_MISSILE: - gi.Printf( "ET_MISSILE " ); + gi.Printf("ET_MISSILE "); break; case ET_MOVER: - gi.Printf( "ET_MOVER " ); + gi.Printf("ET_MOVER "); break; case ET_BEAM: - gi.Printf( "ET_BEAM " ); + gi.Printf("ET_BEAM "); break; case ET_PORTAL: - gi.Printf( "ET_PORTAL " ); + gi.Printf("ET_PORTAL "); break; case ET_SPEAKER: - gi.Printf( "ET_SPEAKER " ); + gi.Printf("ET_SPEAKER "); break; case ET_PUSH_TRIGGER: - gi.Printf( "ET_PUSH_TRIGGER " ); + gi.Printf("ET_PUSH_TRIGGER "); break; case ET_TELEPORT_TRIGGER: - gi.Printf( "ET_TELEPORT_TRIGGER " ); + gi.Printf("ET_TELEPORT_TRIGGER "); break; case ET_INVISIBLE: - gi.Printf( "ET_INVISIBLE " ); + gi.Printf("ET_INVISIBLE "); break; case ET_THINKER: - gi.Printf( "ET_THINKER " ); + gi.Printf("ET_THINKER "); break; case ET_CLOUD: - gi.Printf( "ET_CLOUD " ); + gi.Printf("ET_CLOUD "); break; case ET_TERRAIN: - gi.Printf( "ET_TERRAIN " ); + gi.Printf("ET_TERRAIN "); break; default: - gi.Printf( "%-3i ", check->s.eType ); + gi.Printf("%-3i ", check->s.eType); break; } - if ( check->classname ) { + if (check->classname) { gi.Printf("%s", check->classname); } gi.Printf("\n"); @@ -127,149 +127,116 @@ void Svcmd_EntityList_f (void) { } //--------------------------- -extern void G_StopCinematicSkip( void ); -extern void G_StartCinematicSkip( void ); -extern void ExitEmplacedWeapon( gentity_t *ent ); -static void Svcmd_ExitView_f( void ) -{ -extern cvar_t *g_skippingcin; +extern void G_StopCinematicSkip(void); +extern void G_StartCinematicSkip(void); +extern void ExitEmplacedWeapon(gentity_t *ent); +static void Svcmd_ExitView_f(void) { + extern cvar_t *g_skippingcin; static int exitViewDebounce = 0; - if ( exitViewDebounce > level.time ) - { + if (exitViewDebounce > level.time) { return; } exitViewDebounce = level.time + 500; - if ( in_camera ) - {//see if we need to exit an in-game cinematic - if ( g_skippingcin->integer ) // already doing cinematic skip? - {// yes... so stop skipping... + if (in_camera) { // see if we need to exit an in-game cinematic + if (g_skippingcin->integer) // already doing cinematic skip? + { // yes... so stop skipping... G_StopCinematicSkip(); - } - else - {// no... so start skipping... + } else { // no... so start skipping... G_StartCinematicSkip(); } - } - else if ( !G_ClearViewEntity( player ) ) - {//didn't exit control of a droid or turret - //okay, now try exiting emplaced guns or AT-ST's - if ( player->s.eFlags & EF_LOCKED_TO_WEAPON ) - {//get out of emplaced gun - ExitEmplacedWeapon( player ); - } - else if ( player->client && player->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST - GEntity_UseFunc( player->activator, player, player ); + } else if (!G_ClearViewEntity(player)) { // didn't exit control of a droid or turret + // okay, now try exiting emplaced guns or AT-ST's + if (player->s.eFlags & EF_LOCKED_TO_WEAPON) { // get out of emplaced gun + ExitEmplacedWeapon(player); + } else if (player->client && player->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + GEntity_UseFunc(player->activator, player, player); } } } -gentity_t *G_GetSelfForPlayerCmd( void ) -{ - if ( g_entities[0].client->ps.viewEntity > 0 - && g_entities[0].client->ps.viewEntity < ENTITYNUM_WORLD - && g_entities[g_entities[0].client->ps.viewEntity].client - && g_entities[g_entities[0].client->ps.viewEntity].s.weapon == WP_SABER ) - {//you're controlling another NPC +gentity_t *G_GetSelfForPlayerCmd(void) { + if (g_entities[0].client->ps.viewEntity > 0 && g_entities[0].client->ps.viewEntity < ENTITYNUM_WORLD && + g_entities[g_entities[0].client->ps.viewEntity].client && + g_entities[g_entities[0].client->ps.viewEntity].s.weapon == WP_SABER) { // you're controlling another NPC return (&g_entities[g_entities[0].client->ps.viewEntity]); - } - else - { + } else { return (&g_entities[0]); } } -static void Svcmd_Saber_f() -{ +static void Svcmd_Saber_f() { const char *saber = gi.argv(1); const char *saber2 = gi.argv(2); char name[MAX_CVAR_VALUE_STRING] = {0}; - if ( gi.argc() < 2 ) - { - gi.Printf( "Usage: saber \n" ); - gi.Cvar_VariableStringBuffer( "g_saber", name, sizeof(name) ); + if (gi.argc() < 2) { + gi.Printf("Usage: saber \n"); + gi.Cvar_VariableStringBuffer("g_saber", name, sizeof(name)); gi.Printf("g_saber is set to %s\n", name); - gi.Cvar_VariableStringBuffer( "g_saber2", name, sizeof(name) ); - if ( name[0] ) + gi.Cvar_VariableStringBuffer("g_saber2", name, sizeof(name)); + if (name[0]) gi.Printf("g_saber2 is set to %s\n", name); return; } - if ( !g_entities[0].client || !saber || !saber[0] ) - { + if (!g_entities[0].client || !saber || !saber[0]) { return; } - gi.cvar_set( "g_saber", saber ); - WP_SetSaber( &g_entities[0], 0, saber ); - if ( saber2 && saber2[0] && !(g_entities[0].client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - {//want to use a second saber and first one is not twoHanded - gi.cvar_set( "g_saber2", saber2 ); - WP_SetSaber( &g_entities[0], 1, saber2 ); - } - else - { - gi.cvar_set( "g_saber2", "" ); - WP_RemoveSaber( &g_entities[0], 1 ); + gi.cvar_set("g_saber", saber); + WP_SetSaber(&g_entities[0], 0, saber); + if (saber2 && saber2[0] && !(g_entities[0].client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { // want to use a second saber and first one is not twoHanded + gi.cvar_set("g_saber2", saber2); + WP_SetSaber(&g_entities[0], 1, saber2); + } else { + gi.cvar_set("g_saber2", ""); + WP_RemoveSaber(&g_entities[0], 1); } } -static void Svcmd_SaberBlade_f() -{ - if ( gi.argc() < 2 ) - { - gi.Printf( "USAGE: saberblade [0 = off, 1 = on, no arg = toggle]\n" ); +static void Svcmd_SaberBlade_f() { + if (gi.argc() < 2) { + gi.Printf("USAGE: saberblade [0 = off, 1 = on, no arg = toggle]\n"); return; } - if ( &g_entities[0] == NULL || g_entities[0].client == NULL ) - { + if (&g_entities[0] == NULL || g_entities[0].client == NULL) { return; } int sabernum = atoi(gi.argv(1)) - 1; - if ( sabernum < 0 || sabernum > 1 ) - { + if (sabernum < 0 || sabernum > 1) { return; } - if ( sabernum > 0 && !g_entities[0].client->ps.dualSabers ) - { + if (sabernum > 0 && !g_entities[0].client->ps.dualSabers) { return; } - //FIXME: what if don't even have a single saber at all? + // FIXME: what if don't even have a single saber at all? int bladenum = atoi(gi.argv(2)) - 1; - if ( bladenum < 0 || bladenum >= g_entities[0].client->ps.saber[sabernum].numBlades ) - { + if (bladenum < 0 || bladenum >= g_entities[0].client->ps.saber[sabernum].numBlades) { return; } qboolean turnOn; - if ( gi.argc() > 2 ) - {//explicit - turnOn = (qboolean)(atoi(gi.argv(3))!=0); - } - else - {//toggle + if (gi.argc() > 2) { // explicit + turnOn = (qboolean)(atoi(gi.argv(3)) != 0); + } else { // toggle turnOn = (qboolean)!g_entities[0].client->ps.saber[sabernum].blade[bladenum].active; } - g_entities[0].client->ps.SaberBladeActivate( sabernum, bladenum, turnOn ); + g_entities[0].client->ps.SaberBladeActivate(sabernum, bladenum, turnOn); } -static void Svcmd_SaberColor_f() -{//FIXME: just list the colors, each additional listing sets that blade +static void Svcmd_SaberColor_f() { // FIXME: just list the colors, each additional listing sets that blade int saberNum = atoi(gi.argv(1)); const char *color[MAX_BLADES]; int bladeNum; - for ( bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++ ) - { - color[bladeNum] = gi.argv(2+bladeNum); + for (bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++) { + color[bladeNum] = gi.argv(2 + bladeNum); } - if ( saberNum < 1 || saberNum > 2 || gi.argc() < 3 ) - { - gi.Printf( "Usage: saberColor ... \n" ); - gi.Printf( "valid saberNums: 1 or 2\n" ); - gi.Printf( "valid colors: red, orange, yellow, green, blue, and purple\n" ); + if (saberNum < 1 || saberNum > 2 || gi.argc() < 3) { + gi.Printf("Usage: saberColor ... \n"); + gi.Printf("valid saberNums: 1 or 2\n"); + gi.Printf("valid colors: red, orange, yellow, green, blue, and purple\n"); return; } @@ -277,25 +244,18 @@ static void Svcmd_SaberColor_f() gentity_t *self = G_GetSelfForPlayerCmd(); - for ( bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++ ) - { - if ( !color[bladeNum] || !color[bladeNum][0] ) - { + for (bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++) { + if (!color[bladeNum] || !color[bladeNum][0]) { break; - } - else - { - self->client->ps.saber[saberNum].blade[bladeNum].color = TranslateSaberColor( color[bladeNum] ); + } else { + self->client->ps.saber[saberNum].blade[bladeNum].color = TranslateSaberColor(color[bladeNum]); } } - if ( saberNum == 0 ) - { - gi.cvar_set( "g_saber_color", color[0] ); - } - else if ( saberNum == 1 ) - { - gi.cvar_set( "g_saber2_color", color[0] ); + if (saberNum == 0) { + gi.cvar_set("g_saber_color", color[0]); + } else if (saberNum == 1) { + gi.cvar_set("g_saber2_color", color[0]); } } @@ -306,125 +266,96 @@ struct SetForceCmd { }; SetForceCmd SetForceTable[NUM_FORCE_POWERS] = { - { "forceHeal", "setForceHeal", FORCE_LEVEL_3 }, - { "forceJump", "setForceJump", FORCE_LEVEL_3 }, - { "forceSpeed", "setForceSpeed", FORCE_LEVEL_3 }, - { "forcePush", "setForcePush", FORCE_LEVEL_3 }, - { "forcePull", "setForcePull", FORCE_LEVEL_3 }, - { "forceMindTrick", "setForceMindTrick", FORCE_LEVEL_4 }, - { "forceGrip", "setForceGrip", FORCE_LEVEL_3 }, - { "forceLightning", "setForceLightning", FORCE_LEVEL_3 }, - { "saberThrow", "setSaberThrow", FORCE_LEVEL_3 }, - { "saberDefense", "setSaberDefense", FORCE_LEVEL_3 }, - { "saberOffense", "setSaberOffense", SS_NUM_SABER_STYLES-1 }, - { "forceRage", "setForceRage", FORCE_LEVEL_3 }, - { "forceProtect", "setForceProtect", FORCE_LEVEL_3 }, - { "forceAbsorb", "setForceAbsorb", FORCE_LEVEL_3 }, - { "forceDrain", "setForceDrain", FORCE_LEVEL_3 }, - { "forceSight", "setForceSight", FORCE_LEVEL_3 }, + {"forceHeal", "setForceHeal", FORCE_LEVEL_3}, + {"forceJump", "setForceJump", FORCE_LEVEL_3}, + {"forceSpeed", "setForceSpeed", FORCE_LEVEL_3}, + {"forcePush", "setForcePush", FORCE_LEVEL_3}, + {"forcePull", "setForcePull", FORCE_LEVEL_3}, + {"forceMindTrick", "setForceMindTrick", FORCE_LEVEL_4}, + {"forceGrip", "setForceGrip", FORCE_LEVEL_3}, + {"forceLightning", "setForceLightning", FORCE_LEVEL_3}, + {"saberThrow", "setSaberThrow", FORCE_LEVEL_3}, + {"saberDefense", "setSaberDefense", FORCE_LEVEL_3}, + {"saberOffense", "setSaberOffense", SS_NUM_SABER_STYLES - 1}, + {"forceRage", "setForceRage", FORCE_LEVEL_3}, + {"forceProtect", "setForceProtect", FORCE_LEVEL_3}, + {"forceAbsorb", "setForceAbsorb", FORCE_LEVEL_3}, + {"forceDrain", "setForceDrain", FORCE_LEVEL_3}, + {"forceSight", "setForceSight", FORCE_LEVEL_3}, }; -static void Svcmd_ForceSetLevel_f( int forcePower ) -{ - if ( !&g_entities[0] || !g_entities[0].client ) - { +static void Svcmd_ForceSetLevel_f(int forcePower) { + if (!&g_entities[0] || !g_entities[0].client) { return; } const char *newVal = gi.argv(1); - if ( !VALIDSTRING( newVal ) ) - { - gi.Printf( "Current %s level is %d\n", SetForceTable[forcePower].desc, g_entities[0].client->ps.forcePowerLevel[forcePower] ); - gi.Printf( "Usage: %s (0 - %i)\n", SetForceTable[forcePower].cmdname, SetForceTable[forcePower].maxlevel ); + if (!VALIDSTRING(newVal)) { + gi.Printf("Current %s level is %d\n", SetForceTable[forcePower].desc, g_entities[0].client->ps.forcePowerLevel[forcePower]); + gi.Printf("Usage: %s (0 - %i)\n", SetForceTable[forcePower].cmdname, SetForceTable[forcePower].maxlevel); return; } int val = atoi(newVal); - if ( val > FORCE_LEVEL_0 ) - { - g_entities[0].client->ps.forcePowersKnown |= ( 1 << forcePower ); - } - else - { - g_entities[0].client->ps.forcePowersKnown &= ~( 1 << forcePower ); + if (val > FORCE_LEVEL_0) { + g_entities[0].client->ps.forcePowersKnown |= (1 << forcePower); + } else { + g_entities[0].client->ps.forcePowersKnown &= ~(1 << forcePower); } g_entities[0].client->ps.forcePowerLevel[forcePower] = val; - if ( g_entities[0].client->ps.forcePowerLevel[forcePower] < FORCE_LEVEL_0 ) - { + if (g_entities[0].client->ps.forcePowerLevel[forcePower] < FORCE_LEVEL_0) { g_entities[0].client->ps.forcePowerLevel[forcePower] = FORCE_LEVEL_0; - } - else if ( g_entities[0].client->ps.forcePowerLevel[forcePower] > SetForceTable[forcePower].maxlevel ) - { + } else if (g_entities[0].client->ps.forcePowerLevel[forcePower] > SetForceTable[forcePower].maxlevel) { g_entities[0].client->ps.forcePowerLevel[forcePower] = SetForceTable[forcePower].maxlevel; } } -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean WP_SaberCanTurnOffSomeBlades( saberInfo_t *saber ); -void Svcmd_SaberAttackCycle_f( void ) -{ - if ( !&g_entities[0] || !g_entities[0].client ) - { +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInAttack(int move); +extern qboolean WP_SaberCanTurnOffSomeBlades(saberInfo_t *saber); +void Svcmd_SaberAttackCycle_f(void) { + if (!&g_entities[0] || !g_entities[0].client) { return; } gentity_t *self = G_GetSelfForPlayerCmd(); - if ( self->s.weapon != WP_SABER ) - {// saberAttackCycle button also switches to saber - gi.SendConsoleCommand("weapon 1" ); + if (self->s.weapon != WP_SABER) { // saberAttackCycle button also switches to saber + gi.SendConsoleCommand("weapon 1"); return; } - if ( self->client->ps.dualSabers ) - {//can't cycle styles with dualSabers, so just toggle second saber on/off - if ( WP_SaberCanTurnOffSomeBlades( &self->client->ps.saber[1] ) ) - {//can turn second saber off - if ( self->client->ps.saber[1].ActiveManualOnly() ) - {//turn it off + if (self->client->ps.dualSabers) { // can't cycle styles with dualSabers, so just toggle second saber on/off + if (WP_SaberCanTurnOffSomeBlades(&self->client->ps.saber[1])) { // can turn second saber off + if (self->client->ps.saber[1].ActiveManualOnly()) { // turn it off qboolean skipThisBlade; - for ( int bladeNum = 0; bladeNum < self->client->ps.saber[1].numBlades; bladeNum++ ) - { + for (int bladeNum = 0; bladeNum < self->client->ps.saber[1].numBlades; bladeNum++) { skipThisBlade = qfalse; - if ( WP_SaberBladeUseSecondBladeStyle( &self->client->ps.saber[1], bladeNum ) ) - {//check to see if we should check the secondary style's flags - if ( (self->client->ps.saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE2) ) - { + if (WP_SaberBladeUseSecondBladeStyle(&self->client->ps.saber[1], bladeNum)) { // check to see if we should check the secondary style's flags + if ((self->client->ps.saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) { skipThisBlade = qtrue; } - } - else - {//use the primary style's flags - if ( (self->client->ps.saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) ) - { + } else { // use the primary style's flags + if ((self->client->ps.saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) { skipThisBlade = qtrue; } } - if ( !skipThisBlade ) - { - self->client->ps.saber[1].BladeActivate( bladeNum, qfalse ); - G_SoundIndexOnEnt( self, CHAN_WEAPON, self->client->ps.saber[1].soundOff ); + if (!skipThisBlade) { + self->client->ps.saber[1].BladeActivate(bladeNum, qfalse); + G_SoundIndexOnEnt(self, CHAN_WEAPON, self->client->ps.saber[1].soundOff); } } - } - else if ( !self->client->ps.saber[0].ActiveManualOnly() ) - {//first one is off, too, so just turn that one on - if ( !self->client->ps.saberInFlight ) - {//but only if it's in your hand! + } else if (!self->client->ps.saber[0].ActiveManualOnly()) { // first one is off, too, so just turn that one on + if (!self->client->ps.saberInFlight) { // but only if it's in your hand! self->client->ps.saber[0].Activate(); } - } - else - {//turn on the second one + } else { // turn on the second one self->client->ps.saber[1].Activate(); } return; } - } - else if ( self->client->ps.saber[0].numBlades > 1 - && WP_SaberCanTurnOffSomeBlades( &self->client->ps.saber[0] ) )//self->client->ps.saber[0].type == SABER_STAFF ) - {//can't cycle styles with saberstaff, so just toggles saber blades on/off - if ( self->client->ps.saberInFlight ) - {//can't turn second blade back on if it's in the air, you naughty boy! + } else if (self->client->ps.saber[0].numBlades > 1 && + WP_SaberCanTurnOffSomeBlades(&self->client->ps.saber[0])) // self->client->ps.saber[0].type == SABER_STAFF ) + { // can't cycle styles with saberstaff, so just toggles saber blades on/off + if (self->client->ps.saberInFlight) { // can't turn second blade back on if it's in the air, you naughty boy! return; } /* @@ -434,43 +365,31 @@ void Svcmd_SaberAttackCycle_f( void ) } */ qboolean playedSound = qfalse; - if ( !self->client->ps.saber[0].blade[0].active ) - {//first one is not even on - //turn only it on - self->client->ps.SaberBladeActivate( 0, 0, qtrue ); + if (!self->client->ps.saber[0].blade[0].active) { // first one is not even on + // turn only it on + self->client->ps.SaberBladeActivate(0, 0, qtrue); return; } qboolean skipThisBlade; - for ( int bladeNum = 1; bladeNum < self->client->ps.saber[0].numBlades; bladeNum++ ) - { - if ( !self->client->ps.saber[0].blade[bladeNum].active ) - {//extra is off, turn it on - self->client->ps.saber[0].BladeActivate( bladeNum, qtrue ); - } - else - {//turn extra off + for (int bladeNum = 1; bladeNum < self->client->ps.saber[0].numBlades; bladeNum++) { + if (!self->client->ps.saber[0].blade[bladeNum].active) { // extra is off, turn it on + self->client->ps.saber[0].BladeActivate(bladeNum, qtrue); + } else { // turn extra off skipThisBlade = qfalse; - if ( WP_SaberBladeUseSecondBladeStyle( &self->client->ps.saber[1], bladeNum ) ) - {//check to see if we should check the secondary style's flags - if ( (self->client->ps.saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE2) ) - { + if (WP_SaberBladeUseSecondBladeStyle(&self->client->ps.saber[1], bladeNum)) { // check to see if we should check the secondary style's flags + if ((self->client->ps.saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) { skipThisBlade = qtrue; } - } - else - {//use the primary style's flags - if ( (self->client->ps.saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) ) - { + } else { // use the primary style's flags + if ((self->client->ps.saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) { skipThisBlade = qtrue; } } - if ( !skipThisBlade ) - { - self->client->ps.saber[0].BladeActivate( bladeNum, qfalse ); - if ( !playedSound ) - { - G_SoundIndexOnEnt( self, CHAN_WEAPON, self->client->ps.saber[0].soundOff ); + if (!skipThisBlade) { + self->client->ps.saber[0].BladeActivate(bladeNum, qfalse); + if (!playedSound) { + G_SoundIndexOnEnt(self, CHAN_WEAPON, self->client->ps.saber[0].soundOff); playedSound = qtrue; } } @@ -480,118 +399,95 @@ void Svcmd_SaberAttackCycle_f( void ) } int allowedStyles = self->client->ps.saberStylesKnown; - if ( self->client->ps.dualSabers - && self->client->ps.saber[0].Active() - && self->client->ps.saber[1].Active() ) - { - allowedStyles |= (1<client->ps.saber[0].stylesLearned&(1<client->ps.saber[1].stylesLearned&(1<client->ps.saber[0].stylesForbidden&(1<client->ps.saber[1].stylesForbidden&(1<client->ps.saber[0].stylesForbidden&(1<client->ps.saber[1].stylesForbidden&(1<client->ps.dualSabers && self->client->ps.saber[0].Active() && self->client->ps.saber[1].Active()) { + allowedStyles |= (1 << SS_DUAL); + for (int styleNum = SS_NONE + 1; styleNum < SS_NUM_SABER_STYLES; styleNum++) { + if (styleNum == SS_TAVION && + ((self->client->ps.saber[0].stylesLearned & (1 << SS_TAVION)) || + (self->client->ps.saber[1].stylesLearned & (1 << SS_TAVION))) // was given this style by one of my sabers + && !(self->client->ps.saber[0].stylesForbidden & (1 << SS_TAVION)) && + !(self->client->ps.saber[1].stylesForbidden & (1 << SS_TAVION))) { // if have both sabers on, allow tavion only if one of our sabers + // specifically wanted to use it... (unless specifically forbidden) + } else if (styleNum == SS_DUAL && !(self->client->ps.saber[0].stylesForbidden & (1 << SS_DUAL)) && + !(self->client->ps.saber[1].stylesForbidden & + (1 << SS_DUAL))) { // if have both sabers on, only dual style is allowed (unless specifically forbidden) + } else { + allowedStyles &= ~(1 << styleNum); } } } - if ( !allowedStyles ) - { + if (!allowedStyles) { return; } - int saberAnimLevel; - if ( !self->s.number ) - { + int saberAnimLevel; + if (!self->s.number) { saberAnimLevel = cg.saberAnimLevelPending; - } - else - { + } else { saberAnimLevel = self->client->ps.saberAnimLevel; } saberAnimLevel++; int sanityCheck = 0; - while ( self->client->ps.saberAnimLevel != saberAnimLevel - && !(allowedStyles&(1<client->ps.saberAnimLevel != saberAnimLevel && !(allowedStyles & (1 << saberAnimLevel)) && sanityCheck < SS_NUM_SABER_STYLES + 1) { saberAnimLevel++; - if ( saberAnimLevel > SS_STAFF ) - { + if (saberAnimLevel > SS_STAFF) { saberAnimLevel = SS_FAST; } sanityCheck++; } - if ( !(allowedStyles&(1<s.number ) - { + WP_UseFirstValidSaberStyle(self, &saberAnimLevel); + if (!self->s.number) { cg.saberAnimLevelPending = saberAnimLevel; - } - else - { + } else { self->client->ps.saberAnimLevel = saberAnimLevel; } #ifndef FINAL_BUILD - switch ( saberAnimLevel ) - { + switch (saberAnimLevel) { case SS_FAST: - gi.Printf( S_COLOR_BLUE "Lightsaber Combat Style: Fast\n" ); - //LIGHTSABERCOMBATSTYLE_FAST + gi.Printf(S_COLOR_BLUE "Lightsaber Combat Style: Fast\n"); + // LIGHTSABERCOMBATSTYLE_FAST break; case SS_MEDIUM: - gi.Printf( S_COLOR_YELLOW "Lightsaber Combat Style: Medium\n" ); - //LIGHTSABERCOMBATSTYLE_MEDIUM + gi.Printf(S_COLOR_YELLOW "Lightsaber Combat Style: Medium\n"); + // LIGHTSABERCOMBATSTYLE_MEDIUM break; case SS_STRONG: - gi.Printf( S_COLOR_RED "Lightsaber Combat Style: Strong\n" ); - //LIGHTSABERCOMBATSTYLE_STRONG + gi.Printf(S_COLOR_RED "Lightsaber Combat Style: Strong\n"); + // LIGHTSABERCOMBATSTYLE_STRONG break; case SS_DESANN: - gi.Printf( S_COLOR_CYAN "Lightsaber Combat Style: Desann\n" ); - //LIGHTSABERCOMBATSTYLE_DESANN + gi.Printf(S_COLOR_CYAN "Lightsaber Combat Style: Desann\n"); + // LIGHTSABERCOMBATSTYLE_DESANN break; case SS_TAVION: - gi.Printf( S_COLOR_MAGENTA "Lightsaber Combat Style: Tavion\n" ); - //LIGHTSABERCOMBATSTYLE_TAVION + gi.Printf(S_COLOR_MAGENTA "Lightsaber Combat Style: Tavion\n"); + // LIGHTSABERCOMBATSTYLE_TAVION break; case SS_DUAL: - gi.Printf( S_COLOR_MAGENTA "Lightsaber Combat Style: Dual\n" ); - //LIGHTSABERCOMBATSTYLE_TAVION + gi.Printf(S_COLOR_MAGENTA "Lightsaber Combat Style: Dual\n"); + // LIGHTSABERCOMBATSTYLE_TAVION break; case SS_STAFF: - gi.Printf( S_COLOR_MAGENTA "Lightsaber Combat Style: Staff\n" ); - //LIGHTSABERCOMBATSTYLE_TAVION + gi.Printf(S_COLOR_MAGENTA "Lightsaber Combat Style: Staff\n"); + // LIGHTSABERCOMBATSTYLE_TAVION break; } - //gi.Printf("\n"); + // gi.Printf("\n"); #endif } -qboolean G_ReleaseEntity( gentity_t *grabber ) -{ - if ( grabber && grabber->client && grabber->client->ps.heldClient < ENTITYNUM_WORLD ) - { +qboolean G_ReleaseEntity(gentity_t *grabber) { + if (grabber && grabber->client && grabber->client->ps.heldClient < ENTITYNUM_WORLD) { gentity_t *heldClient = &g_entities[grabber->client->ps.heldClient]; grabber->client->ps.heldClient = ENTITYNUM_NONE; - if ( heldClient && heldClient->client ) - { + if (heldClient && heldClient->client) { heldClient->client->ps.heldByClient = ENTITYNUM_NONE; heldClient->owner = NULL; @@ -601,15 +497,13 @@ qboolean G_ReleaseEntity( gentity_t *grabber ) return qfalse; } -void G_GrabEntity( gentity_t *grabber, const char *target ) -{ - if ( !grabber || !grabber->client ) - { +void G_GrabEntity(gentity_t *grabber, const char *target) { + if (!grabber || !grabber->client) { return; } - gentity_t *heldClient = G_Find( NULL, FOFS(targetname), (char *)target ); - if ( heldClient && heldClient->client && heldClient != grabber )//don't grab yourself, it's not polite - {//found him + gentity_t *heldClient = G_Find(NULL, FOFS(targetname), (char *)target); + if (heldClient && heldClient->client && heldClient != grabber) // don't grab yourself, it's not polite + { // found him grabber->client->ps.heldClient = heldClient->s.number; heldClient->client->ps.heldByClient = grabber->s.number; @@ -617,222 +511,159 @@ void G_GrabEntity( gentity_t *grabber, const char *target ) } } -static void Svcmd_ICARUS_f( void ) -{ - Quake3Game()->Svcmd(); -} +static void Svcmd_ICARUS_f(void) { Quake3Game()->Svcmd(); } -template -static void Svcmd_ForceSetLevel_f(void) -{ - Svcmd_ForceSetLevel_f(power); -} +template static void Svcmd_ForceSetLevel_f(void) { Svcmd_ForceSetLevel_f(power); } -static void Svcmd_SetForceAll_f(void) -{ - for ( int i = FP_HEAL; i < NUM_FORCE_POWERS; i++ ) - { - Svcmd_ForceSetLevel_f( i ); +static void Svcmd_SetForceAll_f(void) { + for (int i = FP_HEAL; i < NUM_FORCE_POWERS; i++) { + Svcmd_ForceSetLevel_f(i); } - if( gi.argc() > 1 ) - { - for ( int i = SS_NONE+1; i < SS_NUM_SABER_STYLES; i++ ) - { - g_entities[0].client->ps.saberStylesKnown |= (1< 1) { + for (int i = SS_NONE + 1; i < SS_NUM_SABER_STYLES; i++) { + g_entities[0].client->ps.saberStylesKnown |= (1 << i); } } } -static void Svcmd_SetSaberAll_f(void) -{ - Svcmd_ForceSetLevel_f( FP_SABERTHROW ); - Svcmd_ForceSetLevel_f( FP_SABER_DEFENSE ); - Svcmd_ForceSetLevel_f( FP_SABER_OFFENSE ); - for ( int i = SS_NONE+1; i < SS_NUM_SABER_STYLES; i++ ) - { - g_entities[0].client->ps.saberStylesKnown |= (1<ps.saberStylesKnown |= (1 << i); } } -static void Svcmd_RunScript_f(void) -{ +static void Svcmd_RunScript_f(void) { const char *cmd2 = gi.argv(1); - if ( cmd2 && cmd2[0] ) - { + if (cmd2 && cmd2[0]) { const char *cmd3 = gi.argv(2); - if ( cmd3 && cmd3[0] ) - { + if (cmd3 && cmd3[0]) { gentity_t *found = NULL; - if ( (found = G_Find(NULL, FOFS(targetname), cmd2 ) ) != NULL ) - { - Quake3Game()->RunScript( found, cmd3 ); - } - else - { - //can't find cmd2 - gi.Printf( S_COLOR_RED "runscript: can't find targetname %s\n", cmd2 ); + if ((found = G_Find(NULL, FOFS(targetname), cmd2)) != NULL) { + Quake3Game()->RunScript(found, cmd3); + } else { + // can't find cmd2 + gi.Printf(S_COLOR_RED "runscript: can't find targetname %s\n", cmd2); } + } else { + Quake3Game()->RunScript(&g_entities[0], cmd2); } - else - { - Quake3Game()->RunScript( &g_entities[0], cmd2 ); - } - } - else - { - gi.Printf( S_COLOR_RED "usage: runscript scriptname\n" ); + } else { + gi.Printf(S_COLOR_RED "usage: runscript scriptname\n"); } } -static void Svcmd_PlayerTeam_f(void) -{ +static void Svcmd_PlayerTeam_f(void) { const char *cmd2 = gi.argv(1); - if ( !*cmd2 || !cmd2[0] ) - { - gi.Printf( S_COLOR_RED "'playerteam' - change player team, requires a team name!\n" ); - gi.Printf( S_COLOR_RED "Current team is: %s\n", GetStringForID( TeamTable, g_entities[0].client->playerTeam ) ); - gi.Printf( S_COLOR_RED "Valid team names are:\n"); - for ( int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED "%s\n", GetStringForID( TeamTable, n ) ); + if (!*cmd2 || !cmd2[0]) { + gi.Printf(S_COLOR_RED "'playerteam' - change player team, requires a team name!\n"); + gi.Printf(S_COLOR_RED "Current team is: %s\n", GetStringForID(TeamTable, g_entities[0].client->playerTeam)); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", GetStringForID(TeamTable, n)); } - } - else - { - team_t team; - - team = (team_t)GetIDForString( TeamTable, cmd2 ); - if ( team == (team_t)-1 ) - { - gi.Printf( S_COLOR_RED "'playerteam' unrecognized team name %s!\n", cmd2 ); - gi.Printf( S_COLOR_RED "Current team is: %s\n", GetStringForID( TeamTable, g_entities[0].client->playerTeam ) ); - gi.Printf( S_COLOR_RED "Valid team names are:\n"); - for ( int n = TEAM_FREE; n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED "%s\n", GetStringForID( TeamTable, n ) ); + } else { + team_t team; + + team = (team_t)GetIDForString(TeamTable, cmd2); + if (team == (team_t)-1) { + gi.Printf(S_COLOR_RED "'playerteam' unrecognized team name %s!\n", cmd2); + gi.Printf(S_COLOR_RED "Current team is: %s\n", GetStringForID(TeamTable, g_entities[0].client->playerTeam)); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (int n = TEAM_FREE; n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", GetStringForID(TeamTable, n)); } - } - else - { + } else { g_entities[0].client->playerTeam = team; - //FIXME: convert Imperial, Malon, Hirogen and Klingon to Scavenger? + // FIXME: convert Imperial, Malon, Hirogen and Klingon to Scavenger? } } } -static void Svcmd_Control_f(void) -{ - const char *cmd2 = gi.argv(1); - if ( !*cmd2 || !cmd2[0] ) - { - if ( !G_ClearViewEntity( &g_entities[0] ) ) - { - gi.Printf( S_COLOR_RED "control \n", cmd2 ); +static void Svcmd_Control_f(void) { + const char *cmd2 = gi.argv(1); + if (!*cmd2 || !cmd2[0]) { + if (!G_ClearViewEntity(&g_entities[0])) { + gi.Printf(S_COLOR_RED "control \n", cmd2); } - } - else - { - Q3_SetViewEntity( 0, cmd2 ); + } else { + Q3_SetViewEntity(0, cmd2); } } -static void Svcmd_Grab_f(void) -{ - const char *cmd2 = gi.argv(1); - if ( !*cmd2 || !cmd2[0] ) - { - if ( !G_ReleaseEntity( &g_entities[0] ) ) - { - gi.Printf( S_COLOR_RED "grab \n", cmd2 ); +static void Svcmd_Grab_f(void) { + const char *cmd2 = gi.argv(1); + if (!*cmd2 || !cmd2[0]) { + if (!G_ReleaseEntity(&g_entities[0])) { + gi.Printf(S_COLOR_RED "grab \n", cmd2); } + } else { + G_GrabEntity(&g_entities[0], cmd2); } - else - { - G_GrabEntity( &g_entities[0], cmd2 ); - } -} - -static void Svcmd_Knockdown_f(void) -{ - G_Knockdown( &g_entities[0], &g_entities[0], vec3_origin, 300, qtrue ); } -static void Svcmd_PlayerModel_f(void) -{ - if ( gi.argc() == 1 ) - { - gi.Printf( S_COLOR_RED "USAGE: playerModel \n playerModel \n playerModel player (builds player from customized menu settings)" S_COLOR_WHITE "\n" ); - gi.Printf( "playerModel = %s ", va("%s %s %s %s\n", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string ) ); - } - else if ( gi.argc() == 2 ) - { - G_ChangePlayerModel( &g_entities[0], gi.argv(1) ); - } - else if ( gi.argc() == 5 ) - { - //instead of setting it directly via a command, we now store it in cvars - //G_ChangePlayerModel( &g_entities[0], va("%s|%s|%s|%s", gi.argv(1), gi.argv(2), gi.argv(3), gi.argv(4)) ); - gi.cvar_set("g_char_model", gi.argv(1) ); - gi.cvar_set("g_char_skin_head", gi.argv(2) ); - gi.cvar_set("g_char_skin_torso", gi.argv(3) ); - gi.cvar_set("g_char_skin_legs", gi.argv(4) ); - G_InitPlayerFromCvars( &g_entities[0] ); +static void Svcmd_Knockdown_f(void) { G_Knockdown(&g_entities[0], &g_entities[0], vec3_origin, 300, qtrue); } + +static void Svcmd_PlayerModel_f(void) { + if (gi.argc() == 1) { + gi.Printf(S_COLOR_RED "USAGE: playerModel \n playerModel \n playerModel player " + "(builds player from customized menu settings)" S_COLOR_WHITE "\n"); + gi.Printf("playerModel = %s ", + va("%s %s %s %s\n", g_char_model->string, g_char_skin_head->string, g_char_skin_torso->string, g_char_skin_legs->string)); + } else if (gi.argc() == 2) { + G_ChangePlayerModel(&g_entities[0], gi.argv(1)); + } else if (gi.argc() == 5) { + // instead of setting it directly via a command, we now store it in cvars + // G_ChangePlayerModel( &g_entities[0], va("%s|%s|%s|%s", gi.argv(1), gi.argv(2), gi.argv(3), gi.argv(4)) ); + gi.cvar_set("g_char_model", gi.argv(1)); + gi.cvar_set("g_char_skin_head", gi.argv(2)); + gi.cvar_set("g_char_skin_torso", gi.argv(3)); + gi.cvar_set("g_char_skin_legs", gi.argv(4)); + G_InitPlayerFromCvars(&g_entities[0]); } } -static void Svcmd_PlayerTint_f(void) -{ - if ( gi.argc() == 4 ) - { +static void Svcmd_PlayerTint_f(void) { + if (gi.argc() == 4) { g_entities[0].client->renderInfo.customRGBA[0] = atoi(gi.argv(1)); g_entities[0].client->renderInfo.customRGBA[1] = atoi(gi.argv(2)); g_entities[0].client->renderInfo.customRGBA[2] = atoi(gi.argv(3)); - gi.cvar_set("g_char_color_red", gi.argv(1) ); - gi.cvar_set("g_char_color_green", gi.argv(2) ); - gi.cvar_set("g_char_color_blue", gi.argv(3) ); - } - else - { - gi.Printf( S_COLOR_RED "USAGE: playerTint \n" ); - gi.Printf( "playerTint = %s\n", va("%d %d %d", g_char_color_red->integer, g_char_color_green->integer, g_char_color_blue->integer ) ); + gi.cvar_set("g_char_color_red", gi.argv(1)); + gi.cvar_set("g_char_color_green", gi.argv(2)); + gi.cvar_set("g_char_color_blue", gi.argv(3)); + } else { + gi.Printf(S_COLOR_RED "USAGE: playerTint \n"); + gi.Printf("playerTint = %s\n", va("%d %d %d", g_char_color_red->integer, g_char_color_green->integer, g_char_color_blue->integer)); } } -static void Svcmd_IKnowKungfu_f(void) -{ - gi.cvar_set( "g_debugMelee", "1" ); - G_SetWeapon( &g_entities[0], WP_MELEE ); - for ( int i = FP_FIRST; i < NUM_FORCE_POWERS; i++ ) - { - g_entities[0].client->ps.forcePowersKnown |= ( 1 << i ); - if ( i == FP_TELEPATHY ) - { +static void Svcmd_IKnowKungfu_f(void) { + gi.cvar_set("g_debugMelee", "1"); + G_SetWeapon(&g_entities[0], WP_MELEE); + for (int i = FP_FIRST; i < NUM_FORCE_POWERS; i++) { + g_entities[0].client->ps.forcePowersKnown |= (1 << i); + if (i == FP_TELEPATHY) { g_entities[0].client->ps.forcePowerLevel[i] = FORCE_LEVEL_4; - } - else - { + } else { g_entities[0].client->ps.forcePowerLevel[i] = FORCE_LEVEL_3; } } } -static void Svcmd_Secrets_f(void) -{ +static void Svcmd_Secrets_f(void) { const gentity_t *pl = &g_entities[0]; - if(pl->client->sess.missionStats.totalSecrets < 1) - { - gi.Printf( "There are" S_COLOR_RED " NO " S_COLOR_WHITE "secrets on this map!\n" ); - } - else if(pl->client->sess.missionStats.secretsFound == pl->client->sess.missionStats.totalSecrets) - { - gi.Printf( "You've found all " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets on this map!\n", pl->client->sess.missionStats.secretsFound ); - } - else - { - gi.Printf( "You've found " S_COLOR_GREEN "%i" S_COLOR_WHITE " out of " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets!\n", pl->client->sess.missionStats.secretsFound, pl->client->sess.missionStats.totalSecrets ); + if (pl->client->sess.missionStats.totalSecrets < 1) { + gi.Printf("There are" S_COLOR_RED " NO " S_COLOR_WHITE "secrets on this map!\n"); + } else if (pl->client->sess.missionStats.secretsFound == pl->client->sess.missionStats.totalSecrets) { + gi.Printf("You've found all " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets on this map!\n", pl->client->sess.missionStats.secretsFound); + } else { + gi.Printf("You've found " S_COLOR_GREEN "%i" S_COLOR_WHITE " out of " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets!\n", + pl->client->sess.missionStats.secretsFound, pl->client->sess.missionStats.totalSecrets); } } @@ -842,145 +673,122 @@ static void Svcmd_Secrets_f(void) // JEDI MASTER - g_spskill 2 + cg_crosshairForceHint 0 + handicap 50 extern cvar_t *g_spskill; -static void Svcmd_Difficulty_f(void) -{ - if(gi.argc() == 1) - { - if(g_spskill->integer == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Padawan" S_COLOR_WHITE "\n" ); - } - else if(g_spskill->integer == 1) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi" S_COLOR_WHITE "\n" ); - } - else if(g_spskill->integer == 2) - { +static void Svcmd_Difficulty_f(void) { + if (gi.argc() == 1) { + if (g_spskill->integer == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Padawan" S_COLOR_WHITE "\n"); + } else if (g_spskill->integer == 1) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi" S_COLOR_WHITE "\n"); + } else if (g_spskill->integer == 2) { int crosshairHint = gi.Cvar_VariableIntegerValue("cg_crosshairForceHint"); int handicap = gi.Cvar_VariableIntegerValue("handicap"); - if(handicap == 100 && crosshairHint == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Knight" S_COLOR_WHITE "\n" ); - } - else if(handicap == 50 && crosshairHint == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Master" S_COLOR_WHITE "\n" ); + if (handicap == 100 && crosshairHint == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Knight" S_COLOR_WHITE "\n"); + } else if (handicap == 50 && crosshairHint == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Master" S_COLOR_WHITE "\n"); + } else { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Knight (Custom)" S_COLOR_WHITE "\n"); + gi.Printf(S_COLOR_GREEN "Crosshair Force Hint: %i" S_COLOR_WHITE "\n", crosshairHint != 0 ? 1 : 0); + gi.Printf(S_COLOR_GREEN "Handicap: %i" S_COLOR_WHITE "\n", handicap); } - else - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Knight (Custom)" S_COLOR_WHITE "\n" ); - gi.Printf( S_COLOR_GREEN "Crosshair Force Hint: %i" S_COLOR_WHITE "\n", crosshairHint != 0 ? 1 : 0 ); - gi.Printf( S_COLOR_GREEN "Handicap: %i" S_COLOR_WHITE "\n", handicap ); - } - } - else - { - gi.Printf( S_COLOR_RED "Invalid difficulty cvar set! g_spskill (%i) [0-2] is valid range only" S_COLOR_WHITE "\n", g_spskill->integer ); + } else { + gi.Printf(S_COLOR_RED "Invalid difficulty cvar set! g_spskill (%i) [0-2] is valid range only" S_COLOR_WHITE "\n", g_spskill->integer); } } } -#define CMD_NONE (0x00000000u) -#define CMD_CHEAT (0x00000001u) -#define CMD_ALIVE (0x00000002u) +#define CMD_NONE (0x00000000u) +#define CMD_CHEAT (0x00000001u) +#define CMD_ALIVE (0x00000002u) typedef struct svcmd_s { - const char *name; - void (*func)(void); - uint32_t flags; + const char *name; + void (*func)(void); + uint32_t flags; } svcmd_t; -static int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((svcmd_t*)b)->name ); -} +static int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((svcmd_t *)b)->name); } // FIXME some of these should be made CMD_ALIVE too! static svcmd_t svcmds[] = { - { "entitylist", Svcmd_EntityList_f, CMD_NONE }, - { "game_memory", Svcmd_GameMem_f, CMD_NONE }, - - { "nav", Svcmd_Nav_f, CMD_CHEAT }, - { "npc", Svcmd_NPC_f, CMD_CHEAT }, - { "use", Svcmd_Use_f, CMD_CHEAT }, - { "ICARUS", Svcmd_ICARUS_f, CMD_CHEAT }, - - { "saberColor", Svcmd_SaberColor_f, CMD_CHEAT }, - { "saber", Svcmd_Saber_f, CMD_CHEAT }, - { "saberBlade", Svcmd_SaberBlade_f, CMD_CHEAT }, - - { "setForceJump", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberThrow", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceHeal", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForcePush", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForcePull", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceSpeed", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceGrip", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceLightning", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setMindTrick", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberDefense", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberOffense", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceRage", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceDrain", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceProtect", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceAbsorb", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceSight", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceAll", Svcmd_SetForceAll_f, CMD_CHEAT }, - { "setSaberAll", Svcmd_SetSaberAll_f, CMD_CHEAT }, - - { "saberAttackCycle", Svcmd_SaberAttackCycle_f, CMD_NONE }, - - { "runscript", Svcmd_RunScript_f, CMD_CHEAT }, - - { "playerTeam", Svcmd_PlayerTeam_f, CMD_CHEAT }, - - { "control", Svcmd_Control_f, CMD_CHEAT }, - { "grab", Svcmd_Grab_f, CMD_CHEAT }, - { "knockdown", Svcmd_Knockdown_f, CMD_CHEAT }, - - { "playerModel", Svcmd_PlayerModel_f, CMD_NONE }, - { "playerTint", Svcmd_PlayerTint_f, CMD_NONE }, - - { "nexttestaxes", G_NextTestAxes, CMD_NONE }, - - { "exitview", Svcmd_ExitView_f, CMD_NONE }, - - { "iknowkungfu", Svcmd_IKnowKungfu_f, CMD_CHEAT }, - - { "secrets", Svcmd_Secrets_f, CMD_NONE }, - { "difficulty", Svcmd_Difficulty_f, CMD_NONE }, - + {"entitylist", Svcmd_EntityList_f, CMD_NONE}, + {"game_memory", Svcmd_GameMem_f, CMD_NONE}, + + {"nav", Svcmd_Nav_f, CMD_CHEAT}, + {"npc", Svcmd_NPC_f, CMD_CHEAT}, + {"use", Svcmd_Use_f, CMD_CHEAT}, + {"ICARUS", Svcmd_ICARUS_f, CMD_CHEAT}, + + {"saberColor", Svcmd_SaberColor_f, CMD_CHEAT}, + {"saber", Svcmd_Saber_f, CMD_CHEAT}, + {"saberBlade", Svcmd_SaberBlade_f, CMD_CHEAT}, + + {"setForceJump", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberThrow", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceHeal", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForcePush", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForcePull", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceSpeed", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceGrip", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceLightning", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setMindTrick", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberDefense", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberOffense", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceRage", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceDrain", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceProtect", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceAbsorb", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceSight", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceAll", Svcmd_SetForceAll_f, CMD_CHEAT}, + {"setSaberAll", Svcmd_SetSaberAll_f, CMD_CHEAT}, + + {"saberAttackCycle", Svcmd_SaberAttackCycle_f, CMD_NONE}, + + {"runscript", Svcmd_RunScript_f, CMD_CHEAT}, + + {"playerTeam", Svcmd_PlayerTeam_f, CMD_CHEAT}, + + {"control", Svcmd_Control_f, CMD_CHEAT}, + {"grab", Svcmd_Grab_f, CMD_CHEAT}, + {"knockdown", Svcmd_Knockdown_f, CMD_CHEAT}, + + {"playerModel", Svcmd_PlayerModel_f, CMD_NONE}, + {"playerTint", Svcmd_PlayerTint_f, CMD_NONE}, + + {"nexttestaxes", G_NextTestAxes, CMD_NONE}, + + {"exitview", Svcmd_ExitView_f, CMD_NONE}, + + {"iknowkungfu", Svcmd_IKnowKungfu_f, CMD_CHEAT}, + + {"secrets", Svcmd_Secrets_f, CMD_NONE}, + {"difficulty", Svcmd_Difficulty_f, CMD_NONE}, + //{ "say", Svcmd_Say_f, qtrue }, //{ "toggleallowvote", Svcmd_ToggleAllowVote_f, qfalse }, //{ "toggleuserinfovalidation", Svcmd_ToggleUserinfoValidation_f, qfalse }, }; -static const size_t numsvcmds = ARRAY_LEN( svcmds ); +static const size_t numsvcmds = ARRAY_LEN(svcmds); /* ================= ConsoleCommand ================= */ -qboolean ConsoleCommand( void ) { +qboolean ConsoleCommand(void) { const char *cmd = gi.argv(0); - const svcmd_t *command = (const svcmd_t *)Q_LinearSearch( cmd, svcmds, numsvcmds, sizeof( svcmds[0] ), svcmdcmp ); + const svcmd_t *command = (const svcmd_t *)Q_LinearSearch(cmd, svcmds, numsvcmds, sizeof(svcmds[0]), svcmdcmp); - if ( !command ) + if (!command) return qfalse; - - if ( (command->flags & CMD_CHEAT) - && !g_cheats->integer ) - { - gi.Printf( "Cheats are not enabled on this server.\n" ); + + if ((command->flags & CMD_CHEAT) && !g_cheats->integer) { + gi.Printf("Cheats are not enabled on this server.\n"); return qtrue; - } - else if ( (command->flags & CMD_ALIVE) - && (g_entities[0].health <= 0) ) - { - gi.Printf( "You must be alive to use this command.\n" ); + } else if ((command->flags & CMD_ALIVE) && (g_entities[0].health <= 0)) { + gi.Printf("You must be alive to use this command.\n"); return qtrue; - } - else + } else command->func(); return qtrue; } - diff --git a/code/game/g_target.cpp b/code/game/g_target.cpp index 9d18d77706..14bd8f9013 100644 --- a/code/game/g_target.cpp +++ b/code/game/g_target.cpp @@ -25,44 +25,42 @@ along with this program; if not, see . #include "Q3_Interface.h" #include "g_local.h" #include "g_functions.h" -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); //========================================================== /*QUAKED target_give (1 0 0) (-8 -8 -8) (8 8 8) Gives the activator all the items pointed to. */ -void Use_Target_Give( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - gentity_t *t; - trace_t trace; +void Use_Target_Give(gentity_t *ent, gentity_t *other, gentity_t *activator) { + gentity_t *t; + trace_t trace; - if ( !activator->client ) { + if (!activator->client) { return; } - if ( !ent->target ) { + if (!ent->target) { return; } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - memset( &trace, 0, sizeof( trace ) ); + memset(&trace, 0, sizeof(trace)); t = NULL; - while ( (t = G_Find (t, FOFS(targetname), ent->target)) != NULL ) { - if ( !t->item ) { + while ((t = G_Find(t, FOFS(targetname), ent->target)) != NULL) { + if (!t->item) { continue; } - Touch_Item( t, activator, &trace ); + Touch_Item(t, activator, &trace); // make sure it isn't going to respawn or show any events t->nextthink = 0; - gi.unlinkentity( t ); + gi.unlinkentity(t); } } -void SP_target_give( gentity_t *ent ) { - ent->e_UseFunc = useF_Use_Target_Give; -} +void SP_target_give(gentity_t *ent) { ent->e_UseFunc = useF_Use_Target_Give; } //========================================================== @@ -70,37 +68,29 @@ void SP_target_give( gentity_t *ent ) { "wait" seconds to pause before firing targets. "random" delay variance, total delay = delay +/- random seconds */ -void Think_Target_Delay( gentity_t *ent ) -{ - G_UseTargets( ent, ent->activator ); -} +void Think_Target_Delay(gentity_t *ent) { G_UseTargets(ent, ent->activator); } -void Use_Target_Delay( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Delay(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->e_ThinkFunc = thinkF_Think_Target_Delay; ent->activator = activator; } -void SP_target_delay( gentity_t *ent ) -{ +void SP_target_delay(gentity_t *ent) { // check delay for backwards compatability - if ( !G_SpawnFloat( "delay", "0", &ent->wait ) ) - { - G_SpawnFloat( "wait", "1", &ent->wait ); + if (!G_SpawnFloat("delay", "0", &ent->wait)) { + G_SpawnFloat("wait", "1", &ent->wait); } - if ( !ent->wait ) - { + if (!ent->wait) { ent->wait = 1; } ent->e_UseFunc = useF_Use_Target_Delay; } - //========================================================== /*QUAKED target_score (1 0 0) (-8 -8 -8) (8 8 8) @@ -108,49 +98,42 @@ void SP_target_delay( gentity_t *ent ) The activator is given this many points. */ -void Use_Target_Score (gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Score(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - AddScore( activator, ent->count ); + AddScore(activator, ent->count); } -void SP_target_score( gentity_t *ent ) { - if ( !ent->count ) { +void SP_target_score(gentity_t *ent) { + if (!ent->count) { ent->count = 1; } ent->e_UseFunc = useF_Use_Target_Score; } - //========================================================== /*QUAKED target_print (1 0 0) (-8 -8 -8) (8 8 8) "message" text to print If "private", only the activator gets the message. If no checks, all clients get the message. */ -void Use_Target_Print (gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Print(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - if ( activator->client ) { - gi.SendServerCommand( activator-g_entities, "cp \"%s\"", ent->message ); + if (activator->client) { + gi.SendServerCommand(activator - g_entities, "cp \"%s\"", ent->message); } } -void SP_target_print( gentity_t *ent ) { - ent->e_UseFunc = useF_Use_Target_Print; -} - +void SP_target_print(gentity_t *ent) { ent->e_UseFunc = useF_Use_Target_Print; } //========================================================== - /*QUAKED target_speaker (1 0 0) (-8 -8 -8) (8 8 8) looped-on looped-off global activator "noise" wav file to play -"sounds" va() min max, so if your sound string is borgtalk%d.wav, and you set a "sounds" value of 4, it will randomly play borgtalk1.wav - borgtalk4.wav when triggered -to use this, you must store the wav name in "soundGroup", NOT "noise" +"sounds" va() min max, so if your sound string is borgtalk%d.wav, and you set a "sounds" value of 4, it will randomly play borgtalk1.wav - borgtalk4.wav when +triggered to use this, you must store the wav name in "soundGroup", NOT "noise" A global sound will play full volume throughout the level. Activator sounds will play on the player that activated the target. @@ -161,78 +144,68 @@ Multiple identical looping sounds will just increase volume without any speed co "wait" : Seconds between triggerings, 0 = don't auto trigger "random" wait variance, default is 0 */ -void Use_Target_Speaker (gentity_t *ent, gentity_t *other, gentity_t *activator) { - if(ent->painDebounceTime > level.time) - { +void Use_Target_Speaker(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (ent->painDebounceTime > level.time) { return; } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - if ( ent->sounds ) - { - ent->noise_index = G_SoundIndex( va( ent->paintarget, Q_irand(1, ent->sounds ) ) ); + if (ent->sounds) { + ent->noise_index = G_SoundIndex(va(ent->paintarget, Q_irand(1, ent->sounds))); } - if (ent->spawnflags & 3) { // looping sound toggles + if (ent->spawnflags & 3) { // looping sound toggles gentity_t *looper = ent; - if ( ent->spawnflags & 8 ) { + if (ent->spawnflags & 8) { looper = activator; } if (looper->s.loopSound) - looper->s.loopSound = 0; // turn it off + looper->s.loopSound = 0; // turn it off else - looper->s.loopSound = ent->noise_index; // start it - }else { // normal sound - if ( ent->spawnflags & 8 ) { - G_AddEvent( activator, EV_GENERAL_SOUND, ent->noise_index ); + looper->s.loopSound = ent->noise_index; // start it + } else { // normal sound + if (ent->spawnflags & 8) { + G_AddEvent(activator, EV_GENERAL_SOUND, ent->noise_index); } else if (ent->spawnflags & 4) { - G_AddEvent( ent, EV_GLOBAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GLOBAL_SOUND, ent->noise_index); } else { - G_AddEvent( ent, EV_GENERAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GENERAL_SOUND, ent->noise_index); } } - if(ent->wait < 0) - {//BYE! + if (ent->wait < 0) { // BYE! ent->e_UseFunc = useF_NULL; - } - else - { + } else { ent->painDebounceTime = level.time + ent->wait; } } -void SP_target_speaker( gentity_t *ent ) { - char buffer[MAX_QPATH]; - char *s; - int i; +void SP_target_speaker(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + int i; - if ( VALIDSTRING( ent->soundSet ) ) - { - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - gi.linkentity (ent); + if (VALIDSTRING(ent->soundSet)) { + VectorCopy(ent->s.origin, ent->s.pos.trBase); + gi.linkentity(ent); return; } - G_SpawnFloat( "wait", "0", &ent->wait ); - G_SpawnFloat( "random", "0", &ent->random ); + G_SpawnFloat("wait", "0", &ent->wait); + G_SpawnFloat("random", "0", &ent->random); - if(!ent->sounds) - { - if ( !G_SpawnString( "noise", "*NOSOUND*", &s ) ) { - G_Error( "target_speaker without a noise key at %s", vtos( ent->s.origin ) ); + if (!ent->sounds) { + if (!G_SpawnString("noise", "*NOSOUND*", &s)) { + G_Error("target_speaker without a noise key at %s", vtos(ent->s.origin)); } - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); - } - else - {//Precache all possible sounds - for( i = 0; i < ent->sounds; i++ ) - { - ent->noise_index = G_SoundIndex( va( ent->paintarget, i+1 ) ); + } else { // Precache all possible sounds + for (i = 0; i < ent->sounds; i++) { + ent->noise_index = G_SoundIndex(va(ent->paintarget, i + 1)); } } @@ -245,7 +218,7 @@ void SP_target_speaker( gentity_t *ent ) { ent->wait *= 1000; // check for prestarted looping sound - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.loopSound = ent->noise_index; } @@ -255,134 +228,125 @@ void SP_target_speaker( gentity_t *ent ) { ent->svFlags |= SVF_BROADCAST; } - VectorCopy( ent->s.origin, ent->s.pos.trBase ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); // must link the entity so we get areas and clusters so // the server can determine who to send updates to - gi.linkentity (ent); + gi.linkentity(ent); } - - //========================================================== /*QUAKED target_laser (0 .5 .8) (-8 -8 -8) (8 8 8) START_ON When triggered, fires a laser. You can either set a target or a direction. */ -void target_laser_think (gentity_t *self) { - vec3_t end; - trace_t tr; - vec3_t point; +void target_laser_think(gentity_t *self) { + vec3_t end; + trace_t tr; + vec3_t point; // if pointed at another entity, set movedir to point at it - if ( self->enemy ) { - VectorMA (self->enemy->s.origin, 0.5, self->enemy->mins, point); - VectorMA (point, 0.5, self->enemy->maxs, point); - VectorSubtract (point, self->s.origin, self->movedir); - VectorNormalize (self->movedir); + if (self->enemy) { + VectorMA(self->enemy->s.origin, 0.5, self->enemy->mins, point); + VectorMA(point, 0.5, self->enemy->maxs, point); + VectorSubtract(point, self->s.origin, self->movedir); + VectorNormalize(self->movedir); } // fire forward and see what we hit - VectorMA (self->s.origin, 2048, self->movedir, end); + VectorMA(self->s.origin, 2048, self->movedir, end); - gi.trace( &tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE, (EG2_Collision)0, 0); + gi.trace(&tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_CORPSE, (EG2_Collision)0, 0); - if ( tr.entityNum ) { + if (tr.entityNum) { // hurt it if we can - G_Damage ( &g_entities[tr.entityNum], self, self->activator, self->movedir, - tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_ENERGY ); + G_Damage(&g_entities[tr.entityNum], self, self->activator, self->movedir, tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_ENERGY); } - VectorCopy (tr.endpos, self->s.origin2); + VectorCopy(tr.endpos, self->s.origin2); - gi.linkentity( self ); + gi.linkentity(self); self->nextthink = level.time + FRAMETIME; } -void target_laser_on (gentity_t *self) -{ +void target_laser_on(gentity_t *self) { if (!self->activator) self->activator = self; - target_laser_think (self); + target_laser_think(self); } -void target_laser_off (gentity_t *self) -{ - gi.unlinkentity( self ); +void target_laser_off(gentity_t *self) { + gi.unlinkentity(self); self->nextthink = 0; } -void target_laser_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_laser_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); self->activator = activator; - if ( self->nextthink > 0 ) - target_laser_off (self); + if (self->nextthink > 0) + target_laser_off(self); else - target_laser_on (self); + target_laser_on(self); } -void target_laser_start (gentity_t *self) -{ +void target_laser_start(gentity_t *self) { gentity_t *ent; self->s.eType = ET_BEAM; if (self->target) { - ent = G_Find (NULL, FOFS(targetname), self->target); + ent = G_Find(NULL, FOFS(targetname), self->target); if (!ent) { - gi.Printf ("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); + gi.Printf("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); } - G_SetEnemy( self, ent ); + G_SetEnemy(self, ent); } else { - G_SetMovedir (self->s.angles, self->movedir); + G_SetMovedir(self->s.angles, self->movedir); } - self->e_UseFunc = useF_target_laser_use; + self->e_UseFunc = useF_target_laser_use; self->e_ThinkFunc = thinkF_target_laser_think; - if ( !self->damage ) { + if (!self->damage) { self->damage = 1; } if (self->spawnflags & 1) - target_laser_on (self); + target_laser_on(self); else - target_laser_off (self); + target_laser_off(self); } -void SP_target_laser (gentity_t *self) -{ +void SP_target_laser(gentity_t *self) { // let everything else get spawned before we start firing self->e_ThinkFunc = thinkF_target_laser_start; self->nextthink = level.time + START_TIME_LINK_ENTS; } - //========================================================== -void target_teleporter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { - gentity_t *dest; +void target_teleporter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + gentity_t *dest; if (!activator->client) return; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - gi.Printf ("Couldn't find teleporter destination\n"); + gi.Printf("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( activator, dest->s.origin, dest->s.angles ); + TeleportPlayer(activator, dest->s.origin, dest->s.angles); } /*QUAK-ED target_teleporter (1 0 0) (-8 -8 -8) (8 8 8) The activator will be teleported away. */ -void SP_target_teleporter( gentity_t *self ) { +void SP_target_teleporter(gentity_t *self) { if (!self->targetname) gi.Printf("untargeted %s at %s\n", self->classname, vtos(self->s.origin)); @@ -391,7 +355,6 @@ void SP_target_teleporter( gentity_t *self ) { //========================================================== - /*QUAKED target_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) RED_ONLY BLUE_ONLY RANDOM x x x x INACTIVE This doesn't perform any actions except fire its targets. The activator can be forced to be from a certain team. @@ -402,132 +365,105 @@ INACTIVE Can't be used until activated "delay" - Will actually fire this many seconds after being used "wait" - Cannot be fired again until this many seconds after the last time it was used */ -void target_relay_use_go (gentity_t *self ) -{ - G_ActivateBehavior( self, BSET_USE ); +void target_relay_use_go(gentity_t *self) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 4 ) - { - gentity_t *ent; + if (self->spawnflags & 4) { + gentity_t *ent; - ent = G_PickTarget( self->target ); - if ( ent && (ent->e_UseFunc != useF_NULL) ) - { // e_UseFunc check can be omitted - GEntity_UseFunc( ent, self, self->activator ); + ent = G_PickTarget(self->target); + if (ent && (ent->e_UseFunc != useF_NULL)) { // e_UseFunc check can be omitted + GEntity_UseFunc(ent, self, self->activator); } return; } - G_UseTargets( self, self->activator ); + G_UseTargets(self, self->activator); } -void target_relay_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( ( self->spawnflags & 1 ) && activator->client ) - {//&& activator->client->ps.persistant[PERS_TEAM] != TEAM_RED ) { +void target_relay_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if ((self->spawnflags & 1) && activator->client) { //&& activator->client->ps.persistant[PERS_TEAM] != TEAM_RED ) { return; } - if ( ( self->spawnflags & 2 ) && activator->client ) - {//&& activator->client->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { + if ((self->spawnflags & 2) && activator->client) { //&& activator->client->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { return; } - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if ( self->painDebounceTime > level.time ) - { + if (self->painDebounceTime > level.time) { return; } - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->activator = activator; - if ( self->delay ) - { + if (self->delay) { self->e_ThinkFunc = thinkF_target_relay_use_go; self->nextthink = level.time + self->delay; return; } - target_relay_use_go( self ); + target_relay_use_go(self); - if ( self->wait < 0 ) - { + if (self->wait < 0) { self->e_UseFunc = useF_NULL; - } - else - { + } else { self->painDebounceTime = level.time + self->wait; } } -void SP_target_relay (gentity_t *self) -{ +void SP_target_relay(gentity_t *self) { self->e_UseFunc = useF_target_relay_use; self->wait *= 1000; self->delay *= 1000; - if ( self->spawnflags&128 ) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } } - //========================================================== /*QUAKED target_kill (.5 .5 .5) (-8 -8 -8) (8 8 8) FALLING ELECTRICAL Kills the activator. */ -void target_kill_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void target_kill_use(gentity_t *self, gentity_t *other, gentity_t *activator) { - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 1 ) - {//falling death - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_FALLING ); - if ( !activator->s.number && activator->health <= 0 && 1 ) - { - extern void CGCam_Fade( vec4_t source, vec4_t dest, float duration ); - float src[4] = {0,0,0,0},dst[4]={0,0,0,1}; - CGCam_Fade( src, dst, 10000 ); + if (self->spawnflags & 1) { // falling death + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_FALLING); + if (!activator->s.number && activator->health <= 0 && 1) { + extern void CGCam_Fade(vec4_t source, vec4_t dest, float duration); + float src[4] = {0, 0, 0, 0}, dst[4] = {0, 0, 0, 1}; + CGCam_Fade(src, dst, 10000); } - } - else if ( self->spawnflags & 2 ) // electrical + } else if (self->spawnflags & 2) // electrical { - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_ELECTROCUTE ); + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_ELECTROCUTE); - if ( activator->client ) - { - activator->s.powerups |= ( 1 << PW_SHOCKED ); + if (activator->client) { + activator->s.powerups |= (1 << PW_SHOCKED); activator->client->ps.powerups[PW_SHOCKED] = level.time + 4000; } - } - else - { - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); + } else { + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } } -void SP_target_kill( gentity_t *self ) -{ - self->e_UseFunc = useF_target_kill_use; -} +void SP_target_kill(gentity_t *self) { self->e_UseFunc = useF_target_kill_use; } /*QUAKED target_position (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. info_notnull does the same thing */ -void SP_target_position( gentity_t *self ){ - G_SetOrigin( self, self->s.origin ); -} +void SP_target_position(gentity_t *self) { G_SetOrigin(self, self->s.origin); } -//static -slc -void target_location_linkup(gentity_t *ent) -{ +// static -slc +void target_location_linkup(gentity_t *ent) { int i; if (level.locationLinked) @@ -555,11 +491,11 @@ Set "count" to 0-7 for color. Closest target_location in sight used for the location, if none in site, closest in distance */ -void SP_target_location( gentity_t *self ){ +void SP_target_location(gentity_t *self) { self->e_ThinkFunc = thinkF_target_location_linkup; - self->nextthink = level.time + 1000; // Let them all spawn first + self->nextthink = level.time + 1000; // Let them all spawn first - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); } //===NEW=================================================================== @@ -576,64 +512,54 @@ After the counter has been triggered "count" times (default 2), it will fire all bounceCount - number of times the counter should reset to it's full count when it's done */ -void target_counter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->count == 0 ) - { +void target_counter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->count == 0) { return; } - //gi.Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + // gi.Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); self->count--; - if ( activator ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, (self->max_health-self->count), self->max_health ); + if (activator) { + Quake3Game()->DebugPrint(IGameInterface::WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, + (self->max_health - self->count), self->max_health); } - if ( self->count ) - { - if ( self->target2 ) - { - //gi.Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); - G_UseTargets2( self, activator, self->target2 ); + if (self->count) { + if (self->target2) { + // gi.Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + G_UseTargets2(self, activator, self->target2); } return; } - G_ActivateBehavior( self,BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 128 ) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } self->activator = activator; - G_UseTargets( self, activator ); + G_UseTargets(self, activator); - if ( self->count == 0 ) - { - if ( self->bounceCount == 0 ) - { + if (self->count == 0) { + if (self->bounceCount == 0) { return; } self->count = self->max_health; - if ( self->bounceCount > 0 ) - {//-1 means bounce back forever + if (self->bounceCount > 0) { //-1 means bounce back forever self->bounceCount--; } } } -void SP_target_counter (gentity_t *self) -{ +void SP_target_counter(gentity_t *self) { self->wait = -1; - if (!self->count) - { + if (!self->count) { self->count = 2; } - //if ( self->bounceCount > 0 )//let's always set this anyway - {//we will reset when we use up our count, remember our initial count + // if ( self->bounceCount > 0 )//let's always set this anyway + { // we will reset when we use up our count, remember our initial count self->max_health = self->count; } @@ -646,81 +572,63 @@ Randomly fires off only one of it's targets each time used USEONCE set to never fire again */ -void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int t_count = 0, pick; - gentity_t *t = NULL; +void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int t_count = 0, pick; + gentity_t *t = NULL; - //gi.Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); - G_ActivateBehavior(self,BSET_USE); + // gi.Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); + G_ActivateBehavior(self, BSET_USE); - if(self->spawnflags & 1) - { + if (self->spawnflags & 1) { self->e_UseFunc = useF_NULL; } - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; } } - if(!t_count) - { + if (!t_count) { return; } - if(t_count == 1) - { - G_UseTargets (self, activator); + if (t_count == 1) { + G_UseTargets(self, activator); return; } - //FIXME: need a seed + // FIXME: need a seed pick = Q_irand(1, t_count); t_count = 0; - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; - } - else - { + } else { continue; } - if (t == self) - { -// gi.Printf ("WARNING: Entity used itself.\n"); - } - else if(t_count == pick) - { - if (t->e_UseFunc != useF_NULL) // check can be omitted + if (t == self) { + // gi.Printf ("WARNING: Entity used itself.\n"); + } else if (t_count == pick) { + if (t->e_UseFunc != useF_NULL) // check can be omitted { GEntity_UseFunc(t, self, activator); return; } } - if (!self->inuse) - { + if (!self->inuse) { gi.Printf("entity was removed while using targets\n"); return; } } } -void SP_target_random (gentity_t *self) -{ - self->e_UseFunc = useF_target_random_use; -} +void SP_target_random(gentity_t *self) { self->e_UseFunc = useF_target_random_use; } -int numNewICARUSEnts = 0; -void scriptrunner_run (gentity_t *self) -{ +int numNewICARUSEnts = 0; +void scriptrunner_run(gentity_t *self) { /* if (self->behaviorSet[BSET_USE]) { @@ -732,86 +640,66 @@ void scriptrunner_run (gentity_t *self) } */ - if ( self->count != -1 ) - { - if ( self->count <= 0 ) - { + if (self->count != -1) { + if (self->count <= 0) { self->e_UseFunc = useF_NULL; self->behaviorSet[BSET_USE] = NULL; return; - } - else - { + } else { --self->count; } } - if (self->behaviorSet[BSET_USE]) - { - if ( self->spawnflags & 1 ) - { - if ( !self->activator ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "target_scriptrunner tried to run on invalid entity!\n"); + if (self->behaviorSet[BSET_USE]) { + if (self->spawnflags & 1) { + if (!self->activator) { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "target_scriptrunner tried to run on invalid entity!\n"); return; } - if ( self->activator->m_iIcarusID == IIcarusInterface::ICARUS_INVALID ) - {//Need to be initialized through ICARUS - if ( !self->activator->script_targetname || !self->activator->script_targetname[0] ) - { - //We don't have a script_targetname, so create a new one - self->activator->script_targetname = va( "newICARUSEnt%d", numNewICARUSEnts++ ); + if (self->activator->m_iIcarusID == IIcarusInterface::ICARUS_INVALID) { // Need to be initialized through ICARUS + if (!self->activator->script_targetname || !self->activator->script_targetname[0]) { + // We don't have a script_targetname, so create a new one + self->activator->script_targetname = va("newICARUSEnt%d", numNewICARUSEnts++); } - if ( Quake3Game()->ValidEntity( self->activator ) ) - { - Quake3Game()->InitEntity( self->activator ); - } - else - { - Quake3Game()->DebugPrint( IGameInterface::WL_ERROR, "target_scriptrunner tried to run on invalid ICARUS activator!\n"); + if (Quake3Game()->ValidEntity(self->activator)) { + Quake3Game()->InitEntity(self->activator); + } else { + Quake3Game()->DebugPrint(IGameInterface::WL_ERROR, "target_scriptrunner tried to run on invalid ICARUS activator!\n"); return; } } - Quake3Game()->DebugPrint( IGameInterface::WL_VERBOSE, "target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], self->activator->targetname ); + Quake3Game()->DebugPrint(IGameInterface::WL_VERBOSE, "target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], + self->activator->targetname); - Quake3Game()->RunScript( self->activator, self->behaviorSet[BSET_USE] ); - } - else - { - if ( self->activator ) - { - Quake3Game()->DebugPrint( IGameInterface::WL_VERBOSE, "target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname ); + Quake3Game()->RunScript(self->activator, self->behaviorSet[BSET_USE]); + } else { + if (self->activator) { + Quake3Game()->DebugPrint(IGameInterface::WL_VERBOSE, "target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname); } - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); } } - if ( self->wait ) - { + if (self->wait) { self->nextthink = level.time + self->wait; } } -void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->nextthink > level.time ) - { +void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->nextthink > level.time) { return; } self->activator = activator; - G_SetEnemy( self, other ); - if ( self->delay ) - {//delay before firing scriptrunner + G_SetEnemy(self, other); + if (self->delay) { // delay before firing scriptrunner self->e_ThinkFunc = thinkF_scriptrunner_run; self->nextthink = level.time + self->delay; - } - else - { - scriptrunner_run (self); + } else { + scriptrunner_run(self); } } @@ -827,20 +715,16 @@ wait - can't be used again in this amount of seconds (Default is 1 second if it' delay - how long to wait after use to run script */ -void SP_target_scriptrunner( gentity_t *self ) -{ - if (!self->behaviorSet[BSET_USE]) - { - gi.Printf(S_COLOR_RED "SP_target_scriptrunner %s has no USESCRIPT\n", self->targetname ); +void SP_target_scriptrunner(gentity_t *self) { + if (!self->behaviorSet[BSET_USE]) { + gi.Printf(S_COLOR_RED "SP_target_scriptrunner %s has no USESCRIPT\n", self->targetname); } - if ( self->spawnflags & 128 ) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } - if ( !self->count ) - { - self->count = 1;//default 1 use only + if (!self->count) { + self->count = 1; // default 1 use only } /* else if ( !self->wait ) @@ -848,28 +732,25 @@ void SP_target_scriptrunner( gentity_t *self ) self->wait = 1;//default wait of 1 sec } */ - // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be able to set less than a second delays - // no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next project + // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be + // able to set less than a second delays no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next + // project self->radius = 0.0f; - G_SpawnFloat( "delay", "0", &self->radius ); - self->delay = self->radius * 1000;//sec to ms - self->wait *= 1000;//sec to ms + G_SpawnFloat("delay", "0", &self->radius); + self->delay = self->radius * 1000; // sec to ms + self->wait *= 1000; // sec to ms - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_scriptrunner_use; } -void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { gi.cvar_set("g_gravity", va("%f", self->speed)); - } - else if ( activator->client ) - { - int grav = floor(self->speed); + } else if (activator->client) { + int grav = floor(self->speed); /* if ( activator->client->ps.gravity != grav ) { @@ -878,7 +759,7 @@ void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *act */ activator->client->ps.gravity = grav; activator->svFlags |= SVF_CUSTOM_GRAVITY; - //FIXME: need a way to set this back to normal? + // FIXME: need a way to set this back to normal? } } @@ -888,23 +769,18 @@ void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *act GLOBAL - Apply to entire world, not just the activator */ -void SP_target_gravity_change( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); - G_SpawnFloat( "gravity", "0", &self->speed ); +void SP_target_gravity_change(gentity_t *self) { + G_SetOrigin(self, self->s.origin); + G_SpawnFloat("gravity", "0", &self->speed); self->e_UseFunc = useF_target_gravity_change_use; } -void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if(self->spawnflags & 1) - {//FIXME - make a global? - //gi.Cvar_Set("g_friction", va("%d", self->health)); - } - else if(activator->client) - { + if (self->spawnflags & 1) { // FIXME - make a global? + // gi.Cvar_Set("g_friction", va("%d", self->health)); + } else if (activator->client) { activator->client->ps.friction = self->health; } } @@ -914,134 +790,112 @@ void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *ac "friction" Normal = 6, Valid range 0 - 10 */ -void SP_target_friction_change( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_friction_change(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_friction_change_use; } -void set_mission_stats_cvars( void ) -{ - char text[1024]={0}; +void set_mission_stats_cvars(void) { + char text[1024] = {0}; - //we'll assume that the activator is the player - gclient_t* const client = &level.clients[0]; + // we'll assume that the activator is the player + gclient_t *const client = &level.clients[0]; - if (!client) - { + if (!client) { return; } - gi.cvar_set("ui_stats_enemieskilled", va("%d",client->sess.missionStats.enemiesKilled)); //pass this on to the menu + gi.cvar_set("ui_stats_enemieskilled", va("%d", client->sess.missionStats.enemiesKilled)); // pass this on to the menu - if (cg_entities[0].gent->client->sess.missionStats.totalSecrets) - { - cgi_SP_GetStringTextString( "SP_INGAME_SECRETAREAS_OF", text, sizeof(text) ); - gi.cvar_set("ui_stats_secretsfound", va("%d %s %d", - cg_entities[0].gent->client->sess.missionStats.secretsFound, - text, - cg_entities[0].gent->client->sess.missionStats.totalSecrets)); - } - else // Setting ui_stats_secretsfound to 0 will hide the text on screen + if (cg_entities[0].gent->client->sess.missionStats.totalSecrets) { + cgi_SP_GetStringTextString("SP_INGAME_SECRETAREAS_OF", text, sizeof(text)); + gi.cvar_set("ui_stats_secretsfound", va("%d %s %d", cg_entities[0].gent->client->sess.missionStats.secretsFound, text, + cg_entities[0].gent->client->sess.missionStats.totalSecrets)); + } else // Setting ui_stats_secretsfound to 0 will hide the text on screen { gi.cvar_set("ui_stats_secretsfound", "0"); } // Find the favorite weapon - int wpn=0,i; + int wpn = 0, i; int max_wpn = cg_entities[0].gent->client->sess.missionStats.weaponUsed[0]; - for (i = 1; iclient->sess.missionStats.weaponUsed[i] > max_wpn) - { + for (i = 1; i < WP_NUM_WEAPONS; i++) { + if (cg_entities[0].gent->client->sess.missionStats.weaponUsed[i] > max_wpn) { max_wpn = cg_entities[0].gent->client->sess.missionStats.weaponUsed[i]; wpn = i; } } - if ( wpn ) - { - gitem_t *wItem= FindItemForWeapon( (weapon_t)wpn); - cgi_SP_GetStringTextString( va("SP_INGAME_%s",wItem->classname ), text, sizeof( text )); - gi.cvar_set("ui_stats_fave", va("%s",text)); //pass this on to the menu + if (wpn) { + gitem_t *wItem = FindItemForWeapon((weapon_t)wpn); + cgi_SP_GetStringTextString(va("SP_INGAME_%s", wItem->classname), text, sizeof(text)); + gi.cvar_set("ui_stats_fave", va("%s", text)); // pass this on to the menu } - gi.cvar_set("ui_stats_shots", va("%d",client->sess.missionStats.shotsFired)); //pass this on to the menu - - gi.cvar_set("ui_stats_hits", va("%d",client->sess.missionStats.hits)); //pass this on to the menu + gi.cvar_set("ui_stats_shots", va("%d", client->sess.missionStats.shotsFired)); // pass this on to the menu - const float percent = cg_entities[0].gent->client->sess.missionStats.shotsFired? 100.0f * (float)cg_entities[0].gent->client->sess.missionStats.hits / cg_entities[0].gent->client->sess.missionStats.shotsFired : 0; - gi.cvar_set("ui_stats_accuracy", va("%.2f%%",percent)); //pass this on to the menu + gi.cvar_set("ui_stats_hits", va("%d", client->sess.missionStats.hits)); // pass this on to the menu - gi.cvar_set("ui_stats_thrown", va("%d",client->sess.missionStats.saberThrownCnt)); //pass this on to the menu + const float percent = cg_entities[0].gent->client->sess.missionStats.shotsFired + ? 100.0f * (float)cg_entities[0].gent->client->sess.missionStats.hits / cg_entities[0].gent->client->sess.missionStats.shotsFired + : 0; + gi.cvar_set("ui_stats_accuracy", va("%.2f%%", percent)); // pass this on to the menu - gi.cvar_set("ui_stats_blocks", va("%d",client->sess.missionStats.saberBlocksCnt)); - gi.cvar_set("ui_stats_legattacks", va("%d",client->sess.missionStats.legAttacksCnt)); - gi.cvar_set("ui_stats_armattacks", va("%d",client->sess.missionStats.armAttacksCnt)); - gi.cvar_set("ui_stats_bodyattacks", va("%d",client->sess.missionStats.torsoAttacksCnt)); + gi.cvar_set("ui_stats_thrown", va("%d", client->sess.missionStats.saberThrownCnt)); // pass this on to the menu - gi.cvar_set("ui_stats_absorb", va("%d",client->sess.missionStats.forceUsed[FP_ABSORB])); - gi.cvar_set("ui_stats_heal", va("%d",client->sess.missionStats.forceUsed[FP_HEAL])); - gi.cvar_set("ui_stats_mindtrick", va("%d",client->sess.missionStats.forceUsed[FP_TELEPATHY])); - gi.cvar_set("ui_stats_protect", va("%d",client->sess.missionStats.forceUsed[FP_PROTECT])); + gi.cvar_set("ui_stats_blocks", va("%d", client->sess.missionStats.saberBlocksCnt)); + gi.cvar_set("ui_stats_legattacks", va("%d", client->sess.missionStats.legAttacksCnt)); + gi.cvar_set("ui_stats_armattacks", va("%d", client->sess.missionStats.armAttacksCnt)); + gi.cvar_set("ui_stats_bodyattacks", va("%d", client->sess.missionStats.torsoAttacksCnt)); - gi.cvar_set("ui_stats_jump", va("%d",client->sess.missionStats.forceUsed[FP_LEVITATION])); - gi.cvar_set("ui_stats_pull", va("%d",client->sess.missionStats.forceUsed[FP_PULL])); - gi.cvar_set("ui_stats_push", va("%d",client->sess.missionStats.forceUsed[FP_PUSH])); - gi.cvar_set("ui_stats_sense", va("%d",client->sess.missionStats.forceUsed[FP_SEE])); - gi.cvar_set("ui_stats_speed", va("%d",client->sess.missionStats.forceUsed[FP_SPEED])); - gi.cvar_set("ui_stats_defense", va("%d",client->sess.missionStats.forceUsed[FP_SABER_DEFENSE])); - gi.cvar_set("ui_stats_offense", va("%d",client->sess.missionStats.forceUsed[FP_SABER_OFFENSE])); - gi.cvar_set("ui_stats_throw", va("%d",client->sess.missionStats.forceUsed[FP_SABERTHROW])); + gi.cvar_set("ui_stats_absorb", va("%d", client->sess.missionStats.forceUsed[FP_ABSORB])); + gi.cvar_set("ui_stats_heal", va("%d", client->sess.missionStats.forceUsed[FP_HEAL])); + gi.cvar_set("ui_stats_mindtrick", va("%d", client->sess.missionStats.forceUsed[FP_TELEPATHY])); + gi.cvar_set("ui_stats_protect", va("%d", client->sess.missionStats.forceUsed[FP_PROTECT])); - gi.cvar_set("ui_stats_drain", va("%d",client->sess.missionStats.forceUsed[FP_DRAIN])); - gi.cvar_set("ui_stats_grip", va("%d",client->sess.missionStats.forceUsed[FP_GRIP])); - gi.cvar_set("ui_stats_lightning", va("%d",client->sess.missionStats.forceUsed[FP_LIGHTNING])); - gi.cvar_set("ui_stats_rage", va("%d",client->sess.missionStats.forceUsed[FP_RAGE])); + gi.cvar_set("ui_stats_jump", va("%d", client->sess.missionStats.forceUsed[FP_LEVITATION])); + gi.cvar_set("ui_stats_pull", va("%d", client->sess.missionStats.forceUsed[FP_PULL])); + gi.cvar_set("ui_stats_push", va("%d", client->sess.missionStats.forceUsed[FP_PUSH])); + gi.cvar_set("ui_stats_sense", va("%d", client->sess.missionStats.forceUsed[FP_SEE])); + gi.cvar_set("ui_stats_speed", va("%d", client->sess.missionStats.forceUsed[FP_SPEED])); + gi.cvar_set("ui_stats_defense", va("%d", client->sess.missionStats.forceUsed[FP_SABER_DEFENSE])); + gi.cvar_set("ui_stats_offense", va("%d", client->sess.missionStats.forceUsed[FP_SABER_OFFENSE])); + gi.cvar_set("ui_stats_throw", va("%d", client->sess.missionStats.forceUsed[FP_SABERTHROW])); + gi.cvar_set("ui_stats_drain", va("%d", client->sess.missionStats.forceUsed[FP_DRAIN])); + gi.cvar_set("ui_stats_grip", va("%d", client->sess.missionStats.forceUsed[FP_GRIP])); + gi.cvar_set("ui_stats_lightning", va("%d", client->sess.missionStats.forceUsed[FP_LIGHTNING])); + gi.cvar_set("ui_stats_rage", va("%d", client->sess.missionStats.forceUsed[FP_RAGE])); } -#include "../cgame/cg_media.h" //access to cgs -extern void G_ChangeMap (const char *mapname, const char *spawntarget, qboolean hub); //g_utils -void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +#include "../cgame/cg_media.h" //access to cgs +extern void G_ChangeMap(const char *mapname, const char *spawntarget, qboolean hub); // g_utils +void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if( self->message && !Q_stricmp( "disconnect", self->message ) ) - { - gi.SendConsoleCommand( "disconnect\n"); - } - else - { - G_ChangeMap( self->message, self->target, (qboolean)((self->spawnflags&1) != 0) ); + if (self->message && !Q_stricmp("disconnect", self->message)) { + gi.SendConsoleCommand("disconnect\n"); + } else { + G_ChangeMap(self->message, self->target, (qboolean)((self->spawnflags & 1) != 0)); } - if (self->count>=0) - { - gi.cvar_set("tier_storyinfo", va("%i",self->count)); - if (level.mapname[0] == 't' && level.mapname[2] == '_' - && ( level.mapname[1] == '1' || level.mapname[1] == '2' || level.mapname[1] == '3' ) - ) - { + if (self->count >= 0) { + gi.cvar_set("tier_storyinfo", va("%i", self->count)); + if (level.mapname[0] == 't' && level.mapname[2] == '_' && (level.mapname[1] == '1' || level.mapname[1] == '2' || level.mapname[1] == '3')) { char s[2048]; - gi.Cvar_VariableStringBuffer("tiers_complete", s, sizeof(s)); //get the current list - if (*s) - { - gi.cvar_set("tiers_complete", va("%s %s", s, level.mapname)); //strcat this level into the existing list - } - else - { - gi.cvar_set("tiers_complete", level.mapname); //set this level into the list + gi.Cvar_VariableStringBuffer("tiers_complete", s, sizeof(s)); // get the current list + if (*s) { + gi.cvar_set("tiers_complete", va("%s %s", s, level.mapname)); // strcat this level into the existing list + } else { + gi.cvar_set("tiers_complete", level.mapname); // set this level into the list } } - if (self->noise_index) - { + if (self->noise_index) { cgi_S_StopSounds(); - cgi_S_StartSound( NULL, 0, CHAN_VOICE, cgs.sound_precache[ self->noise_index ] ); + cgi_S_StartSound(NULL, 0, CHAN_VOICE, cgs.sound_precache[self->noise_index]); } } set_mission_stats_cvars(); - } /*QUAKED target_level_change (1 0 0) (-4 -4 -4) (4 4 4) HUB NO_STORYSOUND @@ -1055,56 +909,42 @@ NO_STORYSOUND - will not play storyinfo wav file, even if you '++' or set tier_s "saber_menu" - integer to set cvar for menu "weapon_menu" - integer to set cvar for ingame weapon menu */ -void SP_target_level_change( gentity_t *self ) -{ - if ( !self->message ) - { - G_Error( "target_level_change with no mapname!\n"); +void SP_target_level_change(gentity_t *self) { + if (!self->message) { + G_Error("target_level_change with no mapname!\n"); return; } char *s; - if (G_SpawnString( "tier_storyinfo", "", &s )) - { - if (*s == '+') - { - self->noise_index = G_SoundIndex(va("sound/chars/tiervictory/%s.mp3",level.mapname) ); - self->count = gi.Cvar_VariableIntegerValue("tier_storyinfo")+1; - G_SoundIndex(va("sound/chars/storyinfo/%d.mp3",self->count)); //cache for menu - } - else - { + if (G_SpawnString("tier_storyinfo", "", &s)) { + if (*s == '+') { + self->noise_index = G_SoundIndex(va("sound/chars/tiervictory/%s.mp3", level.mapname)); + self->count = gi.Cvar_VariableIntegerValue("tier_storyinfo") + 1; + G_SoundIndex(va("sound/chars/storyinfo/%d.mp3", self->count)); // cache for menu + } else { self->count = atoi(s); - if( !(self->spawnflags & 2) ) - { - self->noise_index = G_SoundIndex(va("sound/chars/storyinfo/%d.mp3",self->count) ); + if (!(self->spawnflags & 2)) { + self->noise_index = G_SoundIndex(va("sound/chars/storyinfo/%d.mp3", self->count)); } } - if (G_SpawnString( "storyhead", "", &s )) - { //[luke, kyle, or prot] - gi.cvar_set("storyhead", s); //pass this on to the menu - } - else - { //show head based on mapname - gi.cvar_set("storyhead", level.mapname); //pass this on to the menu + if (G_SpawnString("storyhead", "", &s)) { //[luke, kyle, or prot] + gi.cvar_set("storyhead", s); // pass this on to the menu + } else { // show head based on mapname + gi.cvar_set("storyhead", level.mapname); // pass this on to the menu } } - if (G_SpawnString( "saber_menu", "", &s )) - { - gi.cvar_set("saber_menu", s); //pass this on to the menu + if (G_SpawnString("saber_menu", "", &s)) { + gi.cvar_set("saber_menu", s); // pass this on to the menu } - if (G_SpawnString( "weapon_menu", "1", &s )) - { - gi.cvar_set("weapon_menu", s); //pass this on to the menu - } - else - { - gi.cvar_set("weapon_menu", "0"); //pass this on to the menu + if (G_SpawnString("weapon_menu", "1", &s)) { + gi.cvar_set("weapon_menu", s); // pass this on to the menu + } else { + gi.cvar_set("weapon_menu", "0"); // pass this on to the menu } - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_level_change_use; } @@ -1127,41 +967,33 @@ parm14 parm15 parm16 */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue); -void target_change_parm_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( !activator || !self ) - { +void Q3_SetParm(int entID, int parmNum, const char *parmValue); +void target_change_parm_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || !self) { return; } - //FIXME: call capyparms - if ( self->parms ) - { - for ( int parmNum = 0; parmNum < MAX_PARMS; parmNum++ ) - { - if ( self->parms->parm[parmNum] && self->parms->parm[parmNum][0] ) - { - Q3_SetParm( activator->s.number, parmNum, self->parms->parm[parmNum] ); + // FIXME: call capyparms + if (self->parms) { + for (int parmNum = 0; parmNum < MAX_PARMS; parmNum++) { + if (self->parms->parm[parmNum] && self->parms->parm[parmNum][0]) { + Q3_SetParm(activator->s.number, parmNum, self->parms->parm[parmNum]); } } } } -void SP_target_change_parm( gentity_t *self ) -{ - if ( !self->parms ) - {//ERROR! +void SP_target_change_parm(gentity_t *self) { + if (!self->parms) { // ERROR! return; } - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_change_parm_use; } -void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - gi.SetConfigstring( CS_MUSIC, self->message ); +void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + gi.SetConfigstring(CS_MUSIC, self->message); } /*QUAKED target_play_music (1 0 0) (-4 -4 -4) (4 4 4) @@ -1175,81 +1007,72 @@ If an intro file and loop file are specified, the intro plays first, then the lo portion will start and loop indefinetly. If no introfile is entered, only the loopfile will play. */ -void SP_target_play_music( gentity_t *self ) -{ +void SP_target_play_music(gentity_t *self) { char *s; - G_SetOrigin( self, self->s.origin ); - if (!G_SpawnString( "music", "", &s )) { - G_Error( "target_play_music without a music key at %s", vtos( self->s.origin ) ); + G_SetOrigin(self, self->s.origin); + if (!G_SpawnString("music", "", &s)) { + G_Error("target_play_music without a music key at %s", vtos(self->s.origin)); } - self->message = G_NewString (s); + self->message = G_NewString(s); self->e_UseFunc = useF_target_play_music_use; -extern cvar_t *com_buildScript; - //Precache! - if (com_buildScript->integer) {//copy this puppy over + extern cvar_t *com_buildScript; + // Precache! + if (com_buildScript->integer) { // copy this puppy over char buffer[MAX_QPATH]; - fileHandle_t hFile; + fileHandle_t hFile; - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".mp3"); + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".mp3"); gi.FS_FOpenFile(buffer, &hFile, FS_READ); if (hFile) { - gi.FS_FCloseFile( hFile ); + gi.FS_FCloseFile(hFile); } } } -void target_autosave_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - //gi.SendServerCommand( NULL, "cp @SP_INGAME_CHECKPOINT" ); - CG_CenterPrint( "@SP_INGAME_CHECKPOINT", SCREEN_HEIGHT * 0.25 ); //jump the network +void target_autosave_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + // gi.SendServerCommand( NULL, "cp @SP_INGAME_CHECKPOINT" ); + CG_CenterPrint("@SP_INGAME_CHECKPOINT", SCREEN_HEIGHT * 0.25); // jump the network - gi.SendConsoleCommand( "wait 2;save auto\n" ); + gi.SendConsoleCommand("wait 2;save auto\n"); } /*QUAKED target_autosave (1 0 0) (-4 -4 -4) (4 4 4) Auto save the game in two frames. Make sure it won't trigger during dialogue or cinematic or it will stutter! */ -void SP_target_autosave( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_autosave(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_autosave_use; } -void target_secret_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - //we'll assume that the activator is the player - gclient_t* const client = &level.clients[0]; +void target_secret_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + // we'll assume that the activator is the player + gclient_t *const client = &level.clients[0]; client->sess.missionStats.secretsFound++; - if ( activator ) - { - G_Sound( activator, self->noise_index ); - } - else - { - G_Sound( self, self->noise_index ); + if (activator) { + G_Sound(activator, self->noise_index); + } else { + G_Sound(self, self->noise_index); } - gi.SendServerCommand( 0, "cp @SP_INGAME_SECRET_AREA" ); - if( client->sess.missionStats.secretsFound > client->sess.missionStats.totalSecrets ) + gi.SendServerCommand(0, "cp @SP_INGAME_SECRET_AREA"); + if (client->sess.missionStats.secretsFound > client->sess.missionStats.totalSecrets) client->sess.missionStats.totalSecrets++; - //assert(client->sess.missionStats.totalSecrets); + // assert(client->sess.missionStats.totalSecrets); } /*QUAKED target_secret (1 0 1) (-4 -4 -4) (4 4 4) You found a Secret! "count" - how many secrets on this level, - if more than one on a level, be sure they all have the same count! + if more than one on a level, be sure they all have the same count! */ -void SP_target_secret( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_secret(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_secret_use; self->noise_index = G_SoundIndex("sound/interface/secret_area"); - if (self->count) - { - gi.cvar_set("newTotalSecrets", va("%i",self->count)); + if (self->count) { + gi.cvar_set("newTotalSecrets", va("%i", self->count)); } } diff --git a/code/game/g_trigger.cpp b/code/game/g_trigger.cpp index f1118c96bf..323810b482 100644 --- a/code/game/g_trigger.cpp +++ b/code/game/g_trigger.cpp @@ -27,350 +27,275 @@ along with this program; if not, see . #include "anims.h" #include "../cgame/cg_local.h" -#define ENTDIST_PLAYER 1 -#define ENTDIST_NPC 2 - -extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); -extern qboolean G_ClearTrace( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -extern qboolean PM_CrouchAnim( int anim ); -extern void Boba_FlyStart( gentity_t *self ); -extern qboolean Boba_Flying( gentity_t *self ); - -void InitTrigger( gentity_t *self ) { - if (!VectorCompare (self->s.angles, vec3_origin)) - G_SetMovedir (self->s.angles, self->movedir); - - gi.SetBrushModel( self, self->model ); - self->contents = CONTENTS_TRIGGER; // replaces the -1 from gi.SetBrushModel +#define ENTDIST_PLAYER 1 +#define ENTDIST_NPC 2 + +extern qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs); +extern qboolean G_ClearTrace(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +extern qboolean PM_CrouchAnim(int anim); +extern void Boba_FlyStart(gentity_t *self); +extern qboolean Boba_Flying(gentity_t *self); + +void InitTrigger(gentity_t *self) { + if (!VectorCompare(self->s.angles, vec3_origin)) + G_SetMovedir(self->s.angles, self->movedir); + + gi.SetBrushModel(self, self->model); + self->contents = CONTENTS_TRIGGER; // replaces the -1 from gi.SetBrushModel self->svFlags = SVF_NOCLIENT; - if(self->spawnflags & 128) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } } - // the wait time has passed, so set back up for another activation -void multi_wait( gentity_t *ent ) { - ent->nextthink = 0; -} - +void multi_wait(gentity_t *ent) { ent->nextthink = 0; } // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing -void multi_trigger_run( gentity_t *ent ) -{ +void multi_trigger_run(gentity_t *ent) { ent->e_ThinkFunc = thinkF_NULL; - G_ActivateBehavior( ent, BSET_USE ); + G_ActivateBehavior(ent, BSET_USE); - if ( ent->soundSet && ent->soundSet[0] ) - { - gi.SetConfigstring( CS_AMBIENT_SET, ent->soundSet ); + if (ent->soundSet && ent->soundSet[0]) { + gi.SetConfigstring(CS_AMBIENT_SET, ent->soundSet); } - G_UseTargets (ent, ent->activator); - if ( ent->noise_index ) - { - G_Sound( ent->activator, ent->noise_index ); + G_UseTargets(ent, ent->activator); + if (ent->noise_index) { + G_Sound(ent->activator, ent->noise_index); } - if ( ent->target2 && ent->target2[0] && ent->wait >= 0 ) - { + if (ent->target2 && ent->target2[0] && ent->wait >= 0) { ent->e_ThinkFunc = thinkF_trigger_cleared_fire; ent->nextthink = level.time + ent->speed; - } - else if ( ent->wait > 0 ) - { - if ( ent->painDebounceTime != level.time ) - {//first ent to touch it this frame - //ent->e_ThinkFunc = thinkF_multi_wait; - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + } else if (ent->wait > 0) { + if (ent->painDebounceTime != level.time) { // first ent to touch it this frame + // ent->e_ThinkFunc = thinkF_multi_wait; + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->painDebounceTime = level.time; } - } - else if ( ent->wait < 0 ) - { + } else if (ent->wait < 0) { // we can't just remove (self) here, because this is a touch function // called while looping through area links... - ent->contents &= ~CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + ent->contents &= ~CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me ent->e_TouchFunc = touchF_NULL; ent->e_UseFunc = useF_NULL; - //Don't remove, Icarus may barf? - //ent->nextthink = level.time + FRAMETIME; - //ent->think = G_FreeEntity; + // Don't remove, Icarus may barf? + // ent->nextthink = level.time + FRAMETIME; + // ent->think = G_FreeEntity; } - if( ent->activator && ent->activator->s.number == 0 ) - { // mark the trigger as being touched by the player + if (ent->activator && ent->activator->s.number == 0) { // mark the trigger as being touched by the player ent->aimDebounceTime = level.time; } } - -void multi_trigger( gentity_t *ent, gentity_t *activator ) -{ - if ( ent->e_ThinkFunc == thinkF_multi_trigger_run ) - {//already triggered, just waiting to run +void multi_trigger(gentity_t *ent, gentity_t *activator) { + if (ent->e_ThinkFunc == thinkF_multi_trigger_run) { // already triggered, just waiting to run return; } - if ( ent->nextthink > level.time ) - { - if( ent->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in a single frame + if (ent->nextthink > level.time) { + if (ent->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in a single frame { - if ( ent->painDebounceTime && ent->painDebounceTime != level.time ) - {//this should still allow subsequent ents to fire this trigger in the current frame - return; // can't retrigger until the wait is over + if (ent->painDebounceTime && + ent->painDebounceTime != level.time) { // this should still allow subsequent ents to fire this trigger in the current frame + return; // can't retrigger until the wait is over } - } - else - { + } else { return; } - } - if ( ent->spawnflags & 32) - { + if (ent->spawnflags & 32) { ent->nextthink = level.time + ent->delay; - // trace_t viewTrace; - // gi.trace(&viewTrace, ent->currentOrigin, 0, 0, activator->currentOrigin, ent->s.number, MASK_SHOT); - // if ((viewTrace.allsolid) || (viewTrace.startsolid) || (viewTrace.entityNum!=activator->s.number)) - // { - // return; - // } + // trace_t viewTrace; + // gi.trace(&viewTrace, ent->currentOrigin, 0, 0, activator->currentOrigin, ent->s.number, MASK_SHOT); + // if ((viewTrace.allsolid) || (viewTrace.startsolid) || (viewTrace.entityNum!=activator->s.number)) + // { + // return; + // } } - // if the player has already activated this trigger this frame - if( activator && !activator->s.number && ent->aimDebounceTime == level.time ) - { + if (activator && !activator->s.number && ent->aimDebounceTime == level.time) { return; } - if ( ent->svFlags & SVF_INACTIVE ) - {//Not active at this time + if (ent->svFlags & SVF_INACTIVE) { // Not active at this time return; } ent->activator = activator; - if(ent->delay && ent->painDebounceTime < (level.time + ent->delay) ) - {//delay before firing trigger + if (ent->delay && ent->painDebounceTime < (level.time + ent->delay)) { // delay before firing trigger ent->e_ThinkFunc = thinkF_multi_trigger_run; ent->nextthink = level.time + ent->delay; ent->painDebounceTime = level.time; - } - else - { - multi_trigger_run (ent); + } else { + multi_trigger_run(ent); } } -void Use_Multi( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - multi_trigger( ent, activator ); -} +void Use_Multi(gentity_t *ent, gentity_t *other, gentity_t *activator) { multi_trigger(ent, activator); } -extern int Pilot_ActivePilotCount(void); +extern int Pilot_ActivePilotCount(void); -void Touch_Multi( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if( !other->client ) - { +void Touch_Multi(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if( self->noDamageTeam ) - { - if ( other->client->playerTeam != self->noDamageTeam ) - { + if (self->noDamageTeam) { + if (other->client->playerTeam != self->noDamageTeam) { return; } } -// moved to just above multi_trigger because up here it just checks if the trigger is not being touched -// we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" -// if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) -// {//We're waiting to fire our target2 first -// self->nextthink = level.time + self->speed; -// return; -// } + // moved to just above multi_trigger because up here it just checks if the trigger is not being touched + // we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" + // if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) + // {//We're waiting to fire our target2 first + // self->nextthink = level.time + self->speed; + // return; + // } - if ( self->spawnflags & 1 ) - { - if ( other->s.number != 0 ) - { + if (self->spawnflags & 1) { + if (other->s.number != 0) { return; } - } - else - { - if ( self->spawnflags & 16 ) - {//NPCONLY - if ( other->NPC == NULL ) - { + } else { + if (self->spawnflags & 16) { // NPCONLY + if (other->NPC == NULL) { return; } } - if ( self->NPC_targetname && self->NPC_targetname[0] ) - { - if ( other->script_targetname && other->script_targetname[0] ) - { - if ( Q_stricmp( self->NPC_targetname, other->script_targetname ) != 0 ) - {//not the right guy to fire me off + if (self->NPC_targetname && self->NPC_targetname[0]) { + if (other->script_targetname && other->script_targetname[0]) { + if (Q_stricmp(self->NPC_targetname, other->script_targetname) != 0) { // not the right guy to fire me off return; } - } - else - { + } else { return; } } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - if ( !other->client ) - { + if (self->spawnflags & 4) { // USE_BUTTON + if (!other->client) { return; } - if( !( other->client->usercmd.buttons & BUTTON_USE ) ) - {//not pressing use button + if (!(other->client->usercmd.buttons & BUTTON_USE)) { // not pressing use button return; } } - if ( self->spawnflags & 2 ) - {//FACING - vec3_t forward; + if (self->spawnflags & 2) { // FACING + vec3_t forward; - if ( other->client ) - { - AngleVectors( other->client->ps.viewangles, forward, NULL, NULL ); - } - else - { - AngleVectors( other->currentAngles, forward, NULL, NULL ); + if (other->client) { + AngleVectors(other->client->ps.viewangles, forward, NULL, NULL); + } else { + AngleVectors(other->currentAngles, forward, NULL, NULL); } - if ( DotProduct( self->movedir, forward ) < 0.5 ) - {//Not Within 45 degrees + if (DotProduct(self->movedir, forward) < 0.5) { // Not Within 45 degrees return; } } - if ( self->spawnflags & 8 ) - {//FIRE_BUTTON - if ( !other->client ) - { + if (self->spawnflags & 8) { // FIRE_BUTTON + if (!other->client) { return; } - if( !( other->client->ps.eFlags & EF_FIRING /*usercmd.buttons & BUTTON_ATTACK*/ ) && - !( other->client->ps.eFlags & EF_ALT_FIRING/*usercmd.buttons & BUTTON_ALT_ATTACK*/ ) ) - {//not pressing fire button or altfire button + if (!(other->client->ps.eFlags & EF_FIRING /*usercmd.buttons & BUTTON_ATTACK*/) && + !(other->client->ps.eFlags & EF_ALT_FIRING /*usercmd.buttons & BUTTON_ALT_ATTACK*/)) { // not pressing fire button or altfire button return; } - //FIXME: do we care about the sniper rifle or not? + // FIXME: do we care about the sniper rifle or not? - if( other->s.number == 0 && ( other->client->ps.weapon > MAX_PLAYER_WEAPONS || other->client->ps.weapon <= WP_NONE ) ) - {//don't care about non-player weapons if this is the player + if (other->s.number == 0 && (other->client->ps.weapon > MAX_PLAYER_WEAPONS || + other->client->ps.weapon <= WP_NONE)) { // don't care about non-player weapons if this is the player return; } } - if ( other->client && self->radius ) - { - vec3_t eyeSpot; + if (other->client && self->radius) { + vec3_t eyeSpot; - //Only works if your head is in it, but we allow leaning out - //NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this - //to be reliant on the physical model the player uses. + // Only works if your head is in it, but we allow leaning out + // NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this + // to be reliant on the physical model the player uses. VectorCopy(other->currentOrigin, eyeSpot); eyeSpot[2] += other->client->ps.viewheight; - if ( G_PointInBounds( eyeSpot, self->absmin, self->absmax ) ) - { - if( !( other->client->ps.eFlags & EF_FIRING ) && - !( other->client->ps.eFlags & EF_ALT_FIRING ) ) - {//not attacking, so hiding bonus - //FIXME: should really have sound events clear the hiddenDist + if (G_PointInBounds(eyeSpot, self->absmin, self->absmax)) { + if (!(other->client->ps.eFlags & EF_FIRING) && !(other->client->ps.eFlags & EF_ALT_FIRING)) { // not attacking, so hiding bonus + // FIXME: should really have sound events clear the hiddenDist other->client->hiddenDist = self->radius; - //NOTE: movedir HAS to be normalized! - if ( VectorLength( self->movedir ) ) - {//They can only be hidden from enemies looking in this direction - VectorCopy( self->movedir, other->client->hiddenDir ); - } - else - { - VectorClear( other->client->hiddenDir ); + // NOTE: movedir HAS to be normalized! + if (VectorLength(self->movedir)) { // They can only be hidden from enemies looking in this direction + VectorCopy(self->movedir, other->client->hiddenDir); + } else { + VectorClear(other->client->hiddenDir); } } } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - NPC_SetAnim( other, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->spawnflags & 4) { // USE_BUTTON + NPC_SetAnim(other, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); /* if ( !VectorLengthSquared( other->client->ps.velocity ) && !PM_CrouchAnim( other->client->ps.legsAnim ) ) { NPC_SetAnim( other, SETANIM_LEGS, BOTH_BUTTON_HOLD, SETANIM_FLAG_NORMAL|SETANIM_FLAG_HOLD ); } */ - //other->client->ps.weaponTime = other->client->ps.torsoAnimTimer; + // other->client->ps.weaponTime = other->client->ps.torsoAnimTimer; } - if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) - {//We're waiting to fire our target2 first + if (self->e_ThinkFunc == thinkF_trigger_cleared_fire) { // We're waiting to fire our target2 first self->nextthink = level.time + self->speed; return; } - if ( self->spawnflags & 32) - { - if (Pilot_ActivePilotCount()>=self->lastInAirTime) - { + if (self->spawnflags & 32) { + if (Pilot_ActivePilotCount() >= self->lastInAirTime) { return; } } - multi_trigger( self, other ); + multi_trigger(self, other); } -void trigger_cleared_fire (gentity_t *self) -{ - G_UseTargets2( self, self->activator, self->target2 ); +void trigger_cleared_fire(gentity_t *self) { + G_UseTargets2(self, self->activator, self->target2); self->e_ThinkFunc = thinkF_NULL; // should start the wait timer now, because the trigger's just been cleared, so we must "wait" from this point - if ( self->wait > 0 ) - { - self->nextthink = level.time + ( self->wait + self->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + if (self->wait > 0) { + self->nextthink = level.time + (self->wait + self->random * Q_flrand(-1.0f, 1.0f)) * 1000; } } -qboolean G_TriggerActive( gentity_t *self ) -{ - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +qboolean G_TriggerActive(gentity_t *self) { + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return qfalse; } - if ( self->spawnflags & 1 ) - {//player only + if (self->spawnflags & 1) { // player only return qfalse; } @@ -414,8 +339,10 @@ MULTIPLE - multiple entities can touch this trigger in a single frame *and* if n "wait" Seconds between triggerings, 0 default, number < 0 means one time only. "random" wait variance, default is 0 "delay" how many seconds to wait to fire targets after tripped -"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but not standing should be 48 tall. -"target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') +"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from +enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but +not standing should be 48 tall. "target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the +conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') "speed" How many seconds to wait to fire the target2, default is 1 "noise" Sound to play when the trigger fires (plays at activator's origin) "max_pilots" Number of pilots this spawner will allow @@ -432,48 +359,41 @@ so, the basic time between firing is a random time between "soundSet" Ambient sound set to play when this trigger is activated */ -void SP_trigger_multiple( gentity_t *ent ) -{ - char buffer[MAX_QPATH]; - char *s; - if ( G_SpawnString( "noise", "*NOSOUND*", &s ) ) - { - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); +void SP_trigger_multiple(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + if (G_SpawnString("noise", "*NOSOUND*", &s)) { + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); } - G_SpawnFloat( "wait", "0", &ent->wait );//was 0.5 ... but that means wait can never be zero... we should probably put it back to 0.5, though... - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnInt( "max_pilots", "2", &ent->lastInAirTime ); - + G_SpawnFloat("wait", "0", &ent->wait); // was 0.5 ... but that means wait can never be zero... we should probably put it back to 0.5, though... + G_SpawnFloat("random", "0", &ent->random); + G_SpawnInt("max_pilots", "2", &ent->lastInAirTime); - if ( (ent->wait > 0) && (ent->random >= ent->wait) ) { + if ((ent->wait > 0) && (ent->random >= ent->wait)) { ent->random = ent->wait - FRAMETIME; - gi.Printf(S_COLOR_YELLOW"trigger_multiple has random >= wait\n"); + gi.Printf(S_COLOR_YELLOW "trigger_multiple has random >= wait\n"); } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec - if ( !ent->speed && ent->target2 && ent->target2[0] ) - { + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec + if (!ent->speed && ent->target2 && ent->target2[0]) { ent->speed = 1000; - } - else - { + } else { ent->speed *= 1000; } ent->e_TouchFunc = touchF_Touch_Multi; - ent->e_UseFunc = useF_Use_Multi; + ent->e_UseFunc = useF_Use_Multi; - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = (team_t)GetIDForString( TeamTable, ent->team ); + if (ent->team && ent->team[0]) { + ent->noDamageTeam = (team_t)GetIDForString(TeamTable, ent->team); ent->team = NULL; } - InitTrigger( ent ); - gi.linkentity (ent); + InitTrigger(ent); + gi.linkentity(ent); } /*QUAKED trigger_once (.5 1 .5) ? PLAYERONLY FACING USE_BUTTON FIRE_BUTTON NPCONLY x x INACTIVE MULTIPLE @@ -500,35 +420,31 @@ so, the basic time between firing is a random time between "soundSet" Ambient sound set to play when this trigger is activated */ -void SP_trigger_once( gentity_t *ent ) -{ - char buffer[MAX_QPATH]; - char *s; - if ( G_SpawnString( "noise", "*NOSOUND*", &s ) ) - { - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); +void SP_trigger_once(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + if (G_SpawnString("noise", "*NOSOUND*", &s)) { + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); } ent->wait = -1; ent->e_TouchFunc = touchF_Touch_Multi; - ent->e_UseFunc = useF_Use_Multi; + ent->e_UseFunc = useF_Use_Multi; - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = (team_t)GetIDForString( TeamTable, ent->team ); + if (ent->team && ent->team[0]) { + ent->noDamageTeam = (team_t)GetIDForString(TeamTable, ent->team); ent->team = NULL; } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - InitTrigger( ent ); - gi.linkentity (ent); + InitTrigger(ent); + gi.linkentity(ent); } - /*QUAKED trigger_bidirectional (.1 .5 .1) ? PLAYER_ONLY x x x x x x INACTIVE NOT IMPLEMENTED INACTIVE - Start off, has to be activated to be touchable/usable @@ -544,21 +460,20 @@ Fires "backwardstarget" when someone moves through it in the opposite direction TODO: count */ -void SP_trigger_bidirectional( gentity_t *ent ) -{ +void SP_trigger_bidirectional(gentity_t *ent) { G_FreeEntity(ent); - //FIXME: Implement -/* if(!ent->wait) - { - ent->wait = -1; - } + // FIXME: Implement + /* if(!ent->wait) + { + ent->wait = -1; + } - ent->touch = Touch_Multi; - ent->use = Use_Multi; + ent->touch = Touch_Multi; + ent->use = Use_Multi; - InitTrigger( ent ); - gi.linkentity (ent); -*/ + InitTrigger( ent ); + gi.linkentity (ent); + */ } /*QUAKED trigger_location (.1 .5 .1) ? @@ -567,18 +482,15 @@ When an ent is asked for it's location, it will return this ent's "message" fiel NOTE: always rectangular */ -char *G_GetLocationForEnt( gentity_t *ent ) -{ - vec3_t mins, maxs; - gentity_t *found = NULL; +char *G_GetLocationForEnt(gentity_t *ent) { + vec3_t mins, maxs; + gentity_t *found = NULL; - VectorAdd( ent->currentOrigin, ent->mins, mins ); - VectorAdd( ent->currentOrigin, ent->maxs, maxs ); + VectorAdd(ent->currentOrigin, ent->mins, mins); + VectorAdd(ent->currentOrigin, ent->maxs, maxs); - while( (found = G_Find(found, FOFS(classname), "trigger_location")) != NULL ) - { - if ( gi.EntityContact( mins, maxs, found ) ) - { + while ((found = G_Find(found, FOFS(classname), "trigger_location")) != NULL) { + if (gi.EntityContact(mins, maxs, found)) { return found->message; } } @@ -586,20 +498,18 @@ char *G_GetLocationForEnt( gentity_t *ent ) return NULL; } -void SP_trigger_location( gentity_t *ent ) -{ - if ( !ent->message || !ent->message[0] ) - { +void SP_trigger_location(gentity_t *ent) { + if (!ent->message || !ent->message[0]) { gi.Printf("WARNING: trigger_location with no message!\n"); G_FreeEntity(ent); return; } - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); ent->contents = 0; ent->svFlags = SVF_NOCLIENT; - gi.linkentity (ent); + gi.linkentity(ent); } /* ============================================================================== @@ -609,21 +519,20 @@ trigger_always ============================================================================== */ -void trigger_always_think( gentity_t *ent ) { +void trigger_always_think(gentity_t *ent) { G_UseTargets(ent, ent); - G_FreeEntity( ent ); + G_FreeEntity(ent); } /*QUAKED trigger_always (.1 .5 .1) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ -void SP_trigger_always (gentity_t *ent) { +void SP_trigger_always(gentity_t *ent) { // we must have some delay to make sure our use targets are present ent->nextthink = level.time + 300; ent->e_ThinkFunc = thinkF_trigger_always_think; } - /* ============================================================================== @@ -632,110 +541,87 @@ trigger_push ============================================================================== */ #define PUSH_CONVEYOR 32 -void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +void trigger_push_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if( level.time < self->painDebounceTime + self->wait ) // normal 'wait' check + if (level.time < self->painDebounceTime + self->wait) // normal 'wait' check { - if( self->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in one frame + if (self->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in one frame { - if ( self->painDebounceTime && level.time > self->painDebounceTime ) // if we haven't reached the next frame continue to let ents touch the trigger + if (self->painDebounceTime && level.time > self->painDebounceTime) // if we haven't reached the next frame continue to let ents touch the trigger { return; } - } - else // only allowing one ent per frame to touch trigger + } else // only allowing one ent per frame to touch trigger { return; } } // if the player has already activated this trigger this frame - if( other && !other->s.number && self->aimDebounceTime == level.time ) - { + if (other && !other->s.number && self->aimDebounceTime == level.time) { return; } - - if( self->spawnflags & PUSH_CONVEYOR ) - { // only push player if he's on the ground - if( other->s.groundEntityNum == ENTITYNUM_NONE ) - { + if (self->spawnflags & PUSH_CONVEYOR) { // only push player if he's on the ground + if (other->s.groundEntityNum == ENTITYNUM_NONE) { return; } } - if ( self->spawnflags & 1 ) - {//PLAYERONLY - if ( other->s.number != 0 ) - { + if (self->spawnflags & 1) { // PLAYERONLY + if (other->s.number != 0) { return; } - } - else - { - if ( self->spawnflags & 8 ) - {//NPCONLY - if ( other->NPC == NULL ) - { + } else { + if (self->spawnflags & 8) { // NPCONLY + if (other->NPC == NULL) { return; } } } - if ( !other->client ) { - if ( other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && VectorLengthSquared( other->s.pos.trDelta ) ) - {//already moving - VectorCopy( other->currentOrigin, other->s.pos.trBase ); - VectorCopy( self->s.origin2, other->s.pos.trDelta ); + if (!other->client) { + if (other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && + VectorLengthSquared(other->s.pos.trDelta)) { // already moving + VectorCopy(other->currentOrigin, other->s.pos.trBase); + VectorCopy(self->s.origin2, other->s.pos.trDelta); other->s.pos.trTime = level.time; } return; } - if ( other->client->ps.pm_type != PM_NORMAL ) { + if (other->client->ps.pm_type != PM_NORMAL) { return; } - if ( (self->spawnflags&16) ) - {//relative, dir to it * speed + if ((self->spawnflags & 16)) { // relative, dir to it * speed vec3_t dir; - VectorSubtract( self->s.origin2, other->currentOrigin, dir ); - if ( self->speed ) - { - VectorNormalize( dir ); - VectorScale( dir, self->speed, dir ); + VectorSubtract(self->s.origin2, other->currentOrigin, dir); + if (self->speed) { + VectorNormalize(dir); + VectorScale(dir, self->speed, dir); } - VectorCopy( dir, other->client->ps.velocity ); - } - else if ( (self->spawnflags&4) ) - {//linear dir * speed - VectorScale( self->s.origin2, self->speed, other->client->ps.velocity ); - } - else - { - VectorCopy( self->s.origin2, other->client->ps.velocity ); + VectorCopy(dir, other->client->ps.velocity); + } else if ((self->spawnflags & 4)) { // linear dir * speed + VectorScale(self->s.origin2, self->speed, other->client->ps.velocity); + } else { + VectorCopy(self->s.origin2, other->client->ps.velocity); } - //so we don't take damage unless we land lower than we start here... + // so we don't take damage unless we land lower than we start here... other->client->ps.forceJumpZStart = 0; - other->client->ps.pm_flags |= PMF_TRIGGER_PUSHED;//pushed by a trigger + other->client->ps.pm_flags |= PMF_TRIGGER_PUSHED; // pushed by a trigger other->client->ps.jumpZStart = other->client->ps.origin[2]; - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->e_TouchFunc = touchF_NULL; - } - else if ( self->wait > 0 ) - { + } else if (self->wait > 0) { self->painDebounceTime = level.time; - } - if( other && !other->s.number ) - { // mark that the player has activated this trigger this frame - self->aimDebounceTime =level.time; + if (other && !other->s.number) { // mark that the player has activated this trigger this frame + self->aimDebounceTime = level.time; } } @@ -748,105 +634,90 @@ AimAtTarget Calculate origin2 so the target apogee will be hit ================= */ -void AimAtTarget( gentity_t *self ) -{ - gentity_t *ent; - vec3_t origin; - float height, gravity, time, forward; - float dist; - - VectorAdd( self->absmin, self->absmax, origin ); - VectorScale ( origin, 0.5, origin ); - - ent = G_PickTarget( self->target ); - if ( !ent ) - { - G_FreeEntity( self ); +void AimAtTarget(gentity_t *self) { + gentity_t *ent; + vec3_t origin; + float height, gravity, time, forward; + float dist; + + VectorAdd(self->absmin, self->absmax, origin); + VectorScale(origin, 0.5, origin); + + ent = G_PickTarget(self->target); + if (!ent) { + G_FreeEntity(self); return; } - if ( self->classname && !Q_stricmp( "trigger_push", self->classname ) ) - { - if ( (self->spawnflags&2) ) - {//check once a second to see if we should activate or deactivate ourselves + if (self->classname && !Q_stricmp("trigger_push", self->classname)) { + if ((self->spawnflags & 2)) { // check once a second to see if we should activate or deactivate ourselves self->e_ThinkFunc = thinkF_trigger_push_checkclear; self->nextthink = level.time + FRAMETIME; } - if ( (self->spawnflags&16) ) - {//relative, not an arc or linear - VectorCopy( ent->currentOrigin, self->s.origin2 ); + if ((self->spawnflags & 16)) { // relative, not an arc or linear + VectorCopy(ent->currentOrigin, self->s.origin2); return; - } - else if ( (self->spawnflags&4) ) - {//linear, not an arc - VectorSubtract( ent->currentOrigin, origin, self->s.origin2 ); - VectorNormalize( self->s.origin2 ); + } else if ((self->spawnflags & 4)) { // linear, not an arc + VectorSubtract(ent->currentOrigin, origin, self->s.origin2); + VectorNormalize(self->s.origin2); return; } } - if ( self->classname && !Q_stricmp( "target_push", self->classname ) ) - { - if( self->spawnflags & PUSH_CONSTANT ) - { - VectorSubtract ( ent->s.origin, self->s.origin, self->s.origin2 ); - VectorNormalize( self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + if (self->classname && !Q_stricmp("target_push", self->classname)) { + if (self->spawnflags & PUSH_CONSTANT) { + VectorSubtract(ent->s.origin, self->s.origin, self->s.origin2); + VectorNormalize(self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); return; } } height = ent->s.origin[2] - origin[2]; - if ( height < 0 ) - {//sqrt of negative is bad! + if (height < 0) { // sqrt of negative is bad! height = 0; } gravity = g_gravity->value; - if ( gravity < 0 ) - { + if (gravity < 0) { gravity = 0; } - time = sqrt( height / ( .5 * gravity ) ); - if ( !time ) { - G_FreeEntity( self ); + time = sqrt(height / (.5 * gravity)); + if (!time) { + G_FreeEntity(self); return; } // set s.origin2 to the push velocity - VectorSubtract ( ent->s.origin, origin, self->s.origin2 ); + VectorSubtract(ent->s.origin, origin, self->s.origin2); self->s.origin2[2] = 0; - dist = VectorNormalize( self->s.origin2); + dist = VectorNormalize(self->s.origin2); forward = dist / time; - VectorScale( self->s.origin2, forward, self->s.origin2 ); + VectorScale(self->s.origin2, forward, self->s.origin2); self->s.origin2[2] = time * gravity; } -void trigger_push_checkclear( gentity_t *self ) -{ - trace_t trace; - vec3_t center; +void trigger_push_checkclear(gentity_t *self) { + trace_t trace; + vec3_t center; self->nextthink = level.time + 500; - VectorAdd( self->absmin, self->absmax, center ); - VectorScale( center, 0.5, center ); + VectorAdd(self->absmin, self->absmax, center); + VectorScale(center, 0.5, center); - gentity_t *target = G_Find( NULL, FOFS(targetname), self->target ); - gi.trace( &trace, center, vec3_origin, vec3_origin, target->currentOrigin, ENTITYNUM_NONE, CONTENTS_SOLID, (EG2_Collision)0, 0 ); + gentity_t *target = G_Find(NULL, FOFS(targetname), self->target); + gi.trace(&trace, center, vec3_origin, vec3_origin, target->currentOrigin, ENTITYNUM_NONE, CONTENTS_SOLID, (EG2_Collision)0, 0); - if ( trace.fraction >= 1.0f ) - {//can trace, turn on - self->contents |= CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + if (trace.fraction >= 1.0f) { // can trace, turn on + self->contents |= CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me self->e_TouchFunc = touchF_trigger_push_touch; - gi.linkentity( self ); - } - else - {//no trace, turn off - self->contents &= ~CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + gi.linkentity(self); + } else { // no trace, turn off + self->contents &= ~CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me self->e_TouchFunc = touchF_NULL; - gi.unlinkentity( self ); + gi.unlinkentity(self); } } /*QUAKED trigger_push (.1 .5 .1) ? PLAYERONLY CHECKCLEAR LINEAR NPCONLY RELATIVE CONVEYOR x INACTIVE MULTIPLE @@ -854,21 +725,20 @@ Must point at a target_position, which will be the apex of the leap. This will be client side predicted, unlike target_push PLAYERONLY - only the player is affected LINEAR - Instead of tossing the client at the target_position, it will push them towards it. Must set a "speed" (see below) -CHECKCLEAR - Every 1 second, it will check to see if it can trace to the target_position, if it can, the trigger is touchable, if it can't, the trigger is not touchable -NPCONLY - only NPCs are affected -RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the target_position, it pushes *you* toward the target position, relative to your current location (can use with "speed"... if don't set a speed, it will use the distance from you to the target_position) -CONVEYOR - acts like a conveyor belt, will only push if player is on the ground ( should probably use RELATIVE also, if you want a true conveyor belt ) -INACTIVE - not active until targeted by a target_activate -MULTIPLE - multiple entities can touch this trigger in a single frame *and* if needed, the trigger can have a wait of > 0 +CHECKCLEAR - Every 1 second, it will check to see if it can trace to the target_position, if it can, the trigger is touchable, if it can't, the trigger is not +touchable NPCONLY - only NPCs are affected RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the +target_position, it pushes *you* toward the target position, relative to your current location (can use with "speed"... if don't set a speed, it will use the +distance from you to the target_position) CONVEYOR - acts like a conveyor belt, will only push if player is on the ground ( should probably use RELATIVE also, +if you want a true conveyor belt ) INACTIVE - not active until targeted by a target_activate MULTIPLE - multiple entities can touch this trigger in a single +frame *and* if needed, the trigger can have a wait of > 0 wait - how long to wait between pushes: -1 = push only once speed - when used with the LINEAR spawnflag, pushes the client toward the position at a constant speed (default is 1000) */ -void SP_trigger_push( gentity_t *self ) { - InitTrigger (self); +void SP_trigger_push(gentity_t *self) { + InitTrigger(self); - if ( self->wait > 0 ) - { + if (self->wait > 0) { self->wait *= 1000; } @@ -876,50 +746,47 @@ void SP_trigger_push( gentity_t *self ) { self->svFlags &= ~SVF_NOCLIENT; self->s.eType = ET_PUSH_TRIGGER; - if ( !(self->spawnflags&2) ) - {//start on + if (!(self->spawnflags & 2)) { // start on self->e_TouchFunc = touchF_trigger_push_touch; } - if ( self->spawnflags & 4 ) - {//linear + if (self->spawnflags & 4) { // linear self->speed = 1000; } self->e_ThinkFunc = thinkF_AimAtTarget; self->nextthink = level.time + START_TIME_LINK_ENTS; - gi.linkentity (self); + gi.linkentity(self); } -void Use_target_push( gentity_t *self, gentity_t *other, gentity_t *activator ) { - if ( !activator->client ) { +void Use_target_push(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator->client) { return; } - if ( activator->client->ps.pm_type != PM_NORMAL ) { + if (activator->client->ps.pm_type != PM_NORMAL) { return; } - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - VectorCopy( self->s.origin2, activator->client->ps.velocity ); + VectorCopy(self->s.origin2, activator->client->ps.velocity); - if( self->spawnflags & 4 ) // lower + if (self->spawnflags & 4) // lower { // reset this so I don't take falling damage when I land activator->client->ps.jumpZStart = activator->currentOrigin[2]; } - //so we don't take damage unless we land lower than we start here... + // so we don't take damage unless we land lower than we start here... activator->client->ps.forceJumpZStart = 0; - activator->client->ps.pm_flags |= PMF_TRIGGER_PUSHED;//pushed by a trigger + activator->client->ps.pm_flags |= PMF_TRIGGER_PUSHED; // pushed by a trigger // play fly sound every 1.5 seconds - if ( self->noise_index && activator->fly_sound_debounce_time < level.time ) { + if (self->noise_index && activator->fly_sound_debounce_time < level.time) { activator->fly_sound_debounce_time = level.time + 1500; - G_Sound( activator, self->noise_index ); + G_Sound(activator, self->noise_index); } } - /*QUAKED target_push (.5 .5 .5) (-8 -8 -8) (8 8 8) ENERGYNOISE CONSTANT NO_DAMAGE When triggered, pushes the activator in the direction of angles "speed" defaults to 1000 @@ -927,25 +794,23 @@ ENERGYNOISE plays energy noise CONSTANT will push activator in direction of 'target' at constant 'speed' NO_DAMAGE the activator won't take falling damage after being pushed */ -void SP_target_push( gentity_t *self ) { - +void SP_target_push(gentity_t *self) { if (!self->speed) { self->speed = 1000; } - G_SetMovedir (self->s.angles, self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + G_SetMovedir(self->s.angles, self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); - if ( self->spawnflags & 1 ) { - //self->noise_index = G_SoundIndex("sound/ambience/forge/antigrav.wav"); + if (self->spawnflags & 1) { + // self->noise_index = G_SoundIndex("sound/ambience/forge/antigrav.wav"); } - if ( self->target ) { + if (self->target) { - VectorCopy( self->s.origin, self->absmin ); - VectorCopy( self->s.origin, self->absmax ); + VectorCopy(self->s.origin, self->absmin); + VectorCopy(self->s.origin, self->absmax); self->e_ThinkFunc = thinkF_AimAtTarget; self->nextthink = level.time + START_TIME_LINK_ENTS; - } self->e_UseFunc = useF_Use_target_push; } @@ -959,91 +824,76 @@ trigger_teleport */ #define SNAP_ANGLES 1 #define NO_MISSILES 2 -#define NO_NPCS 4 -#define TTSF_STASIS 8 -#define TTSF_DEAD_OK 16 -void TeleportMover( gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle ); -void trigger_teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace ) -{ - gentity_t *dest; - - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +#define NO_NPCS 4 +#define TTSF_STASIS 8 +#define TTSF_DEAD_OK 16 +void TeleportMover(gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle); +void trigger_teleporter_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *dest; + + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - dest = G_PickTarget( self->target ); - if (!dest) - { - gi.Printf ("Couldn't find teleporter destination\n"); + dest = G_PickTarget(self->target); + if (!dest) { + gi.Printf("Couldn't find teleporter destination\n"); return; } - if ( other->client ) - { - if ( other->client->ps.pm_type == PM_DEAD ) - { - if ( !(self->spawnflags&TTSF_DEAD_OK) ) - {//dead men can't teleport + if (other->client) { + if (other->client->ps.pm_type == PM_DEAD) { + if (!(self->spawnflags & TTSF_DEAD_OK)) { // dead men can't teleport return; } } - if ( other->NPC ) - { - if ( self->spawnflags & NO_NPCS ) - { + if (other->NPC) { + if (self->spawnflags & NO_NPCS) { return; } } - if ( other->client->playerTeam != TEAM_FREE && SpotWouldTelefrag2( other, dest->currentOrigin ) )//SpotWouldTelefrag( dest, other->client->playerTeam ) ) - {//Don't go through if something blocking on the other side + if (other->client->playerTeam != TEAM_FREE && SpotWouldTelefrag2(other, dest->currentOrigin)) // SpotWouldTelefrag( dest, other->client->playerTeam ) ) + { // Don't go through if something blocking on the other side return; } - TeleportPlayer( other, dest->s.origin, dest->s.angles ); + TeleportPlayer(other, dest->s.origin, dest->s.angles); } - //FIXME: check for SVF_NO_TELEPORT - else if ( !(self->svFlags & SVF_NO_TELEPORT) && !(self->spawnflags & NO_MISSILES) && VectorLengthSquared( other->s.pos.trDelta ) ) - {//It's a mover of some sort and is currently moving - vec3_t diffAngles = {0, 0, 0}; - qboolean snap = qfalse; + // FIXME: check for SVF_NO_TELEPORT + else if (!(self->svFlags & SVF_NO_TELEPORT) && !(self->spawnflags & NO_MISSILES) && + VectorLengthSquared(other->s.pos.trDelta)) { // It's a mover of some sort and is currently moving + vec3_t diffAngles = {0, 0, 0}; + qboolean snap = qfalse; - if ( self->lastEnemy ) - { - VectorSubtract( dest->s.angles, self->lastEnemy->s.angles, diffAngles ); - } - else - {//snaps to angle - VectorSubtract( dest->s.angles, other->currentAngles, diffAngles ); + if (self->lastEnemy) { + VectorSubtract(dest->s.angles, self->lastEnemy->s.angles, diffAngles); + } else { // snaps to angle + VectorSubtract(dest->s.angles, other->currentAngles, diffAngles); snap = qtrue; } - TeleportMover( other, dest->s.origin, diffAngles, snap ); + TeleportMover(other, dest->s.origin, diffAngles, snap); } } -void trigger_teleporter_find_closest_portal( gentity_t *self ) -{ +void trigger_teleporter_find_closest_portal(gentity_t *self) { gentity_t *found = NULL; - vec3_t org, vec; - float dist, bestDist = 64*64; - - VectorAdd( self->mins, self->maxs, org ); - VectorScale( org, 0.5, org ); - while ( (found = G_Find( found, FOFS(classname), "misc_portal_surface" )) != NULL ) - { - VectorSubtract( found->currentOrigin, org, vec ); - dist = VectorLengthSquared( vec ); - if ( dist < bestDist ) - { + vec3_t org, vec; + float dist, bestDist = 64 * 64; + + VectorAdd(self->mins, self->maxs, org); + VectorScale(org, 0.5, org); + while ((found = G_Find(found, FOFS(classname), "misc_portal_surface")) != NULL) { + VectorSubtract(found->currentOrigin, org, vec); + dist = VectorLengthSquared(vec); + if (dist < bestDist) { self->lastEnemy = found; bestDist = dist; } } - if ( self->lastEnemy ) - { + if (self->lastEnemy) { gi.Printf("trigger_teleporter found misc_portal_surface\n"); } self->e_ThinkFunc = thinkF_NULL; @@ -1059,9 +909,8 @@ NO_NPCS - NPCs cannot pass through STASIS - will play stasis teleport sound and fx instead of starfleet DEAD_OK - even if dead, you will teleport */ -void SP_trigger_teleport( gentity_t *self ) -{ - InitTrigger (self); +void SP_trigger_teleport(gentity_t *self) { + InitTrigger(self); // unlike other triggers, we need to send this one to the client self->svFlags &= ~SVF_NOCLIENT; @@ -1072,11 +921,9 @@ void SP_trigger_teleport( gentity_t *self ) self->e_ThinkFunc = thinkF_trigger_teleporter_find_closest_portal; self->nextthink = level.time + START_TIME_LINK_ENTS; - gi.linkentity (self); + gi.linkentity(self); } - - /* ============================================================================== @@ -1105,192 +952,158 @@ MULTIPLE multiple entities can touch this trigger in a single frame *and* "NPC_targetname" - If set, only an NPC with a matching NPC_targetname will trip this trigger "noise" sound to play when it hurts something ( default: "sound/world/electro" ) */ -void hurt_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void hurt_use(gentity_t *self, gentity_t *other, gentity_t *activator) { - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - //FIXME: Targeting the trigger will toggle its on / off state??? - if ( self->linked ) { - gi.unlinkentity( self ); + // FIXME: Targeting the trigger will toggle its on / off state??? + if (self->linked) { + gi.unlinkentity(self); } else { - gi.linkentity( self ); + gi.linkentity(self); } } -void trigger_hurt_reset (gentity_t *self) -{ +void trigger_hurt_reset(gentity_t *self) { self->attackDebounceTime = 0; self->e_ThinkFunc = thinkF_NULL; } -extern void JET_FlyStart(gentity_t* actor); -void hurt_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - int dflags; - int actualDmg = self->damage; - - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +extern void JET_FlyStart(gentity_t *actor); +void hurt_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + int dflags; + int actualDmg = self->damage; + + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if ( !other->takedamage ) - { + if (!other->takedamage) { return; } - if( level.time < self->painDebounceTime + self->wait ) // normal 'wait' check + if (level.time < self->painDebounceTime + self->wait) // normal 'wait' check { - if( self->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in one frame + if (self->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in one frame { - if ( self->painDebounceTime && level.time > self->painDebounceTime ) // if we haven't reached the next frame continue to let ents touch the trigger + if (self->painDebounceTime && level.time > self->painDebounceTime) // if we haven't reached the next frame continue to let ents touch the trigger { return; } - } - else // only allowing one ent per frame to touch trigger + } else // only allowing one ent per frame to touch trigger { return; } } // if the player has already activated this trigger this frame - if( other && !other->s.number && self->aimDebounceTime == level.time ) - { + if (other && !other->s.number && self->aimDebounceTime == level.time) { return; } - - if ( self->spawnflags & 2 ) - {//player only - if ( other->s.number ) - { + if (self->spawnflags & 2) { // player only + if (other->s.number) { return; } } - if ( self->NPC_targetname && self->NPC_targetname[0] ) - {//I am for you, Kirk - if ( other->script_targetname && other->script_targetname[0] ) - {//must have a name - if ( Q_stricmp( self->NPC_targetname, other->script_targetname ) != 0 ) - {//not the right guy to fire me off + if (self->NPC_targetname && self->NPC_targetname[0]) { // I am for you, Kirk + if (other->script_targetname && other->script_targetname[0]) { // must have a name + if (Q_stricmp(self->NPC_targetname, other->script_targetname) != 0) { // not the right guy to fire me off return; } - } - else - {//no name? No trigger. + } else { // no name? No trigger. return; } } // play sound - if ( !(self->spawnflags & 4) ) - { - G_Sound( other, self->noise_index ); + if (!(self->spawnflags & 4)) { + G_Sound(other, self->noise_index); } - if ( self->spawnflags & 8 ) - { + if (self->spawnflags & 8) { dflags = DAMAGE_NO_PROTECTION; - } - else - { + } else { dflags = 0; } - if ( self->delay ) - {//Increase dmg over time - if ( self->attackDebounceTime < self->delay ) - {//FIXME: this is for the entire trigger, not per person, so if someone else jumped in after you were in it for 5 seconds, they'd get damaged faster - actualDmg = floor( (float)(self->damage * self->attackDebounceTime / self->delay) ); + if (self->delay) { // Increase dmg over time + if (self->attackDebounceTime < self->delay) { // FIXME: this is for the entire trigger, not per person, so if someone else jumped in after you were in + // it for 5 seconds, they'd get damaged faster + actualDmg = floor((float)(self->damage * self->attackDebounceTime / self->delay)); } self->attackDebounceTime += FRAMETIME; self->e_ThinkFunc = thinkF_trigger_hurt_reset; - self->nextthink = level.time + FRAMETIME*2; + self->nextthink = level.time + FRAMETIME * 2; } - if ( actualDmg ) - { - if (( self->spawnflags & 64 ) && other->client )//electrical damage + if (actualDmg) { + if ((self->spawnflags & 64) && other->client) // electrical damage { // zap effect - other->s.powerups |= ( 1 << PW_SHOCKED ); + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = level.time + 1000; } - if ( self->spawnflags & 32 ) - {//falling death - if ( other->NPC && other->client && - (other->client->NPC_class == CLASS_BOBAFETT || other->client->NPC_class == CLASS_ROCKETTROOPER )) - {//boba never falls to his death! - //FIXME: fall through if jetpack broken? + if (self->spawnflags & 32) { // falling death + if (other->NPC && other->client && + (other->client->NPC_class == CLASS_BOBAFETT || other->client->NPC_class == CLASS_ROCKETTROOPER)) { // boba never falls to his death! + // FIXME: fall through if jetpack broken? JET_FlyStart(other); - } - else - { - G_Damage (other, self, self, NULL, NULL, actualDmg, dflags|DAMAGE_NO_ARMOR, MOD_FALLING); + } else { + G_Damage(other, self, self, NULL, NULL, actualDmg, dflags | DAMAGE_NO_ARMOR, MOD_FALLING); // G_Damage will free this ent, which makes it s.number 0, so we must check inuse... - if ( !other->s.number && other->health <= 0 ) - { - if ( self->count ) - { - extern void CGCam_Fade( vec4_t source, vec4_t dest, float duration ); - float src[4] = {0,0,0,0},dst[4]={0,0,0,1}; - CGCam_Fade( src, dst, self->count ); + if (!other->s.number && other->health <= 0) { + if (self->count) { + extern void CGCam_Fade(vec4_t source, vec4_t dest, float duration); + float src[4] = {0, 0, 0, 0}, dst[4] = {0, 0, 0, 1}; + CGCam_Fade(src, dst, self->count); } - if ( self->spawnflags & 16 ) - {//lock cam + if (self->spawnflags & 16) { // lock cam cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_CDP; cg.overrides.thirdPersonCameraDamp = 0; } - if ( other->client ) - { + if (other->client) { other->client->ps.pm_flags |= PMF_SLOW_MO_FALL; } - //G_SoundOnEnt( other, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN? + // G_SoundOnEnt( other, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN? } } + } else { + G_Damage(other, self, self, NULL, NULL, actualDmg, dflags, MOD_TRIGGER_HURT); } - else - { - G_Damage (other, self, self, NULL, NULL, actualDmg, dflags, MOD_TRIGGER_HURT); - } - if( other && !other->s.number ) - { + if (other && !other->s.number) { self->aimDebounceTime = level.time; } - if (( self->spawnflags & 64 ) && other->client && other->health <= 0 )//electrical damage - {//just killed them, make the effect last longer since dead clients don't touch triggers + if ((self->spawnflags & 64) && other->client && other->health <= 0) // electrical damage + { // just killed them, make the effect last longer since dead clients don't touch triggers other->client->ps.powerups[PW_SHOCKED] = level.time + 10000; } self->painDebounceTime = level.time; } - if ( self->wait < 0 ) - { + if (self->wait < 0) { self->e_TouchFunc = touchF_NULL; } } -void SP_trigger_hurt( gentity_t *self ) -{ - char buffer[MAX_QPATH]; - char *s; +void SP_trigger_hurt(gentity_t *self) { + char buffer[MAX_QPATH]; + char *s; - InitTrigger (self); + InitTrigger(self); - if ( !( self->spawnflags & 4 )) - { - G_SpawnString( "noise", "sound/world/electro", &s ); + if (!(self->spawnflags & 4)) { + G_SpawnString("noise", "sound/world/electro", &s); - Q_strncpyz( buffer, s, sizeof(buffer) ); + Q_strncpyz(buffer, s, sizeof(buffer)); self->noise_index = G_SoundIndex(buffer); } self->e_TouchFunc = touchF_hurt_touch; - if ( !self->damage ) { + if (!self->damage) { self->damage = 5; } @@ -1299,51 +1112,42 @@ void SP_trigger_hurt( gentity_t *self ) self->contents = CONTENTS_TRIGGER; - if ( self->targetname ) {//NOTE: for some reason, this used to be: if(self->spawnflags&2) + if (self->targetname) { // NOTE: for some reason, this used to be: if(self->spawnflags&2) self->e_UseFunc = useF_hurt_use; } // link in to the world if starting active - if ( !(self->spawnflags & 1) ) - { - gi.linkentity (self); - } - else // triggers automatically get linked into the world by SetBrushModel, so we have to unlink it here + if (!(self->spawnflags & 1)) { + gi.linkentity(self); + } else // triggers automatically get linked into the world by SetBrushModel, so we have to unlink it here { gi.unlinkentity(self); } } -#define INITIAL_SUFFOCATION_DELAY 5000 //5 seconds -void space_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if (!other || !other->inuse || !other->client ) - //NOTE: we need vehicles to know this, too... - //|| other->s.number >= MAX_CLIENTS) +#define INITIAL_SUFFOCATION_DELAY 5000 // 5 seconds +void space_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other || !other->inuse || !other->client) + // NOTE: we need vehicles to know this, too... + //|| other->s.number >= MAX_CLIENTS) { return; } - if (other->s.m_iVehicleNum - && other->s.m_iVehicleNum <= MAX_CLIENTS ) - {//a player client inside a vehicle + if (other->s.m_iVehicleNum && other->s.m_iVehicleNum <= MAX_CLIENTS) { // a player client inside a vehicle gentity_t *veh = &g_entities[other->s.m_iVehicleNum]; if (veh->inuse && veh->client && veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->hideRider) - { //if they are "inside" a vehicle, then let that protect them from THE HORRORS OF SPACE. + veh->m_pVehicle->m_pVehicleInfo->hideRider) { // if they are "inside" a vehicle, then let that protect them from THE HORRORS OF SPACE. return; } } - if (!G_PointInBounds(other->client->ps.origin, self->absmin, self->absmax)) - { //his origin must be inside the trigger + if (!G_PointInBounds(other->client->ps.origin, self->absmin, self->absmax)) { // his origin must be inside the trigger return; } - if (!other->client->inSpaceIndex || - other->client->inSpaceIndex == ENTITYNUM_NONE) - { //freshly entering space + if (!other->client->inSpaceIndex || other->client->inSpaceIndex == ENTITYNUM_NONE) { // freshly entering space other->client->inSpaceSuffocation = level.time + INITIAL_SUFFOCATION_DELAY; } @@ -1354,37 +1158,31 @@ void space_touch( gentity_t *self, gentity_t *other, trace_t *trace ) causes human clients to suffocate and have no gravity. */ -void SP_trigger_space(gentity_t *self) -{ +void SP_trigger_space(gentity_t *self) { InitTrigger(self); self->contents = CONTENTS_TRIGGER; - //FIXME: implement!!! - //self->e_TouchFunc = touchF_space_touch; + // FIXME: implement!!! + // self->e_TouchFunc = touchF_space_touch; - gi.linkentity(self); + gi.linkentity(self); } -void shipboundary_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void shipboundary_touch(gentity_t *self, gentity_t *other, trace_t *trace) { gentity_t *ent; - if (!other || !other->inuse || !other->client || - other->s.number < MAX_CLIENTS || - !other->m_pVehicle) - { //only let vehicles touch + if (!other || !other->inuse || !other->client || other->s.number < MAX_CLIENTS || !other->m_pVehicle) { // only let vehicles touch return; } - ent = G_Find (NULL, FOFS(targetname), self->target); - if (!ent || !ent->inuse) - { //this is bad + ent = G_Find(NULL, FOFS(targetname), self->target); + if (!ent || !ent->inuse) { // this is bad G_Error("trigger_shipboundary has invalid target '%s'\n", self->target); return; } - if (!other->s.m_iVehicleNum || other->m_pVehicle->m_iRemovedSurfaces) - { //if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up + if (!other->s.m_iVehicleNum || + other->m_pVehicle->m_iRemovedSurfaces) { // if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up G_Damage(other, other, other, NULL, other->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); return; } @@ -1400,26 +1198,23 @@ causes vehicle to turn toward target and travel in that direction for a set time "traveltime" time to travel in this direction */ -void SP_trigger_shipboundary(gentity_t *self) -{ +void SP_trigger_shipboundary(gentity_t *self) { InitTrigger(self); self->contents = CONTENTS_TRIGGER; - if (!self->target || !self->target[0]) - { + if (!self->target || !self->target[0]) { G_Error("trigger_shipboundary without a target."); } G_SpawnInt("traveltime", "0", &self->count); - if (!self->count) - { + if (!self->count) { G_Error("trigger_shipboundary without traveltime."); } - //FIXME: implement! - //self->e_TouchFunc = touchF_shipboundary_touch; + // FIXME: implement! + // self->e_TouchFunc = touchF_shipboundary_touch; - gi.linkentity(self); + gi.linkentity(self); } /* ============================================================================== @@ -1429,7 +1224,6 @@ timer ============================================================================== */ - /*QUAKED func_timer (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) START_ON This should be renamed trigger_timer... Repeatedly fires its targets. @@ -1441,41 +1235,40 @@ so, the basic time between firing is a random time between (wait - random) and (wait + random) */ -void func_timer_think( gentity_t *self ) { - G_UseTargets (self, self->activator); +void func_timer_think(gentity_t *self) { + G_UseTargets(self, self->activator); // set time before next firing - self->nextthink = level.time + 1000 * ( self->wait + Q_flrand(-1.0f, 1.0f) * self->random ); + self->nextthink = level.time + 1000 * (self->wait + Q_flrand(-1.0f, 1.0f) * self->random); } -void func_timer_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void func_timer_use(gentity_t *self, gentity_t *other, gentity_t *activator) { self->activator = activator; - G_ActivateBehavior(self,BSET_USE); - + G_ActivateBehavior(self, BSET_USE); // if on, turn it off - if ( self->nextthink ) { + if (self->nextthink) { self->nextthink = 0; return; } // turn it on - func_timer_think (self); + func_timer_think(self); } -void SP_func_timer( gentity_t *self ) { - G_SpawnFloat( "random", "1", &self->random); - G_SpawnFloat( "wait", "1", &self->wait ); +void SP_func_timer(gentity_t *self) { + G_SpawnFloat("random", "1", &self->random); + G_SpawnFloat("wait", "1", &self->wait); - self->e_UseFunc = useF_func_timer_use; + self->e_UseFunc = useF_func_timer_use; self->e_ThinkFunc = thinkF_func_timer_think; - if ( self->random >= self->wait ) { - self->random = self->wait - 1;//NOTE: was - FRAMETIME, but FRAMETIME is in msec (100) and these numbers are in *seconds*! - gi.Printf( "func_timer at %s has random >= wait\n", vtos( self->s.origin ) ); + if (self->random >= self->wait) { + self->random = self->wait - 1; // NOTE: was - FRAMETIME, but FRAMETIME is in msec (100) and these numbers are in *seconds*! + gi.Printf("func_timer at %s has random >= wait\n", vtos(self->s.origin)); } - if ( self->spawnflags & 1 ) { + if (self->spawnflags & 1) { self->nextthink = level.time + FRAMETIME; self->activator = self; } @@ -1491,7 +1284,6 @@ timer ============================================================================== */ - /*QUAKED trigger_entdist (.1 .5 .1) (-8 -8 -8) (8 8 8) PLAYER NPC fires if the given entity is within the given distance. Sets itself inactive after one use. ----- KEYS ----- @@ -1510,26 +1302,23 @@ if it finds either of these within distance it will fire. add LOS to it??? */ -void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - vec3_t diff; - gentity_t *found = NULL; - gentity_t *owner = NULL; - qboolean useflag; - const char *token, *holdString; +void trigger_entdist_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + vec3_t diff; + gentity_t *found = NULL; + gentity_t *owner = NULL; + qboolean useflag; + const char *token, *holdString; - if ( self->svFlags & SVF_INACTIVE ) // Don't use INACTIVE + if (self->svFlags & SVF_INACTIVE) // Don't use INACTIVE return; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if(self->ownername && self->ownername[0]) - { + if (self->ownername && self->ownername[0]) { owner = G_Find(NULL, FOFS(targetname), self->ownername); } - if(owner == NULL) - { + if (owner == NULL) { owner = self; } @@ -1537,39 +1326,35 @@ void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activato useflag = qfalse; - self->svFlags |= SVF_INACTIVE; // Make it inactive after one use + self->svFlags |= SVF_INACTIVE; // Make it inactive after one use - if (self->spawnflags & ENTDIST_PLAYER) // Look for player??? + if (self->spawnflags & ENTDIST_PLAYER) // Look for player??? { found = &g_entities[0]; - if (found) - { + if (found) { VectorSubtract(owner->currentOrigin, found->currentOrigin, diff); - if(VectorLength(diff) < self->count) - { + if (VectorLength(diff) < self->count) { useflag = qtrue; } } } - if ((self->spawnflags & ENTDIST_NPC) && (!useflag)) - { + if ((self->spawnflags & ENTDIST_NPC) && (!useflag)) { holdString = self->NPC_target; - while (holdString) - { - token = COM_Parse( &holdString); - if ( !token ) // Nothing left to look at + while (holdString) { + token = COM_Parse(&holdString); + if (!token) // Nothing left to look at { break; } - found = G_Find(found, FOFS(targetname), token); // Look for the specified NPC - if (found) //Found??? + found = G_Find(found, FOFS(targetname), token); // Look for the specified NPC + if (found) // Found??? { VectorSubtract(owner->currentOrigin, found->currentOrigin, diff); - if(VectorLength(diff) < self->count) // Within distance + if (VectorLength(diff) < self->count) // Within distance { useflag = qtrue; break; @@ -1578,89 +1363,72 @@ void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activato } } - if (useflag) - { - G_UseTargets2 (self, self->activator, self->target); - } - else if (self->target2) - { + if (useflag) { + G_UseTargets2(self, self->activator, self->target); + } else if (self->target2) { // This is the negative target - G_UseTargets2 (self, self->activator, self->target2); + G_UseTargets2(self, self->activator, self->target2); } - - } -void SP_trigger_entdist( gentity_t *self ) -{ - G_SpawnInt( "distance", "0", &self->count); +void SP_trigger_entdist(gentity_t *self) { + G_SpawnInt("distance", "0", &self->count); self->e_UseFunc = useF_trigger_entdist_use; - } // spawnflag -#define TRIGGERVISIBLE_FORCESIGHT 2 +#define TRIGGERVISIBLE_FORCESIGHT 2 -void trigger_visible_check_player_visibility( gentity_t *self ) -{ - //Check every FRAMETIME*2 - self->nextthink = level.time + FRAMETIME*2; +void trigger_visible_check_player_visibility(gentity_t *self) { + // Check every FRAMETIME*2 + self->nextthink = level.time + FRAMETIME * 2; - if ( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; } - vec3_t dir; - float dist; - gentity_t *player = &g_entities[0]; + vec3_t dir; + float dist; + gentity_t *player = &g_entities[0]; - if (!player || !player->client ) - { + if (!player || !player->client) { return; } // Added 01/20/03 by AReis // If this trigger can only be used if the players force sight is on... - if ( self->spawnflags & TRIGGERVISIBLE_FORCESIGHT ) - { + if (self->spawnflags & TRIGGERVISIBLE_FORCESIGHT) { // If their force sight is not on, leave... - if ( !( player->client->ps.forcePowersActive & (1 << FP_SEE) ) ) - { + if (!(player->client->ps.forcePowersActive & (1 << FP_SEE))) { return; } } - //1: see if player is within 512*512 range - VectorSubtract( self->currentOrigin, player->client->renderInfo.eyePoint, dir ); - dist = VectorNormalize( dir ); - if ( dist < self->radius ) - {//Within range - vec3_t forward; - float dot; - //2: see if dot to us and player viewangles is > 0.7 - AngleVectors( player->client->renderInfo.eyeAngles, forward, NULL, NULL ); - dot = DotProduct( forward, dir ); - if ( dot > self->random ) - {//Within the desired FOV - //3: see if player is in PVS - if ( gi.inPVS( self->currentOrigin, player->client->renderInfo.eyePoint ) ) - { - vec3_t mins = {-1, -1, -1}; - vec3_t maxs = {1, 1, 1}; - //4: If needbe, trace to see if there is clear LOS from player viewpos - if ( (self->spawnflags&1) || G_ClearTrace( player->client->renderInfo.eyePoint, mins, maxs, self->currentOrigin, 0, MASK_OPAQUE ) ) - { - //5: Fire! - G_UseTargets( self, player ); - //6: Remove yourself - G_FreeEntity( self ); + // 1: see if player is within 512*512 range + VectorSubtract(self->currentOrigin, player->client->renderInfo.eyePoint, dir); + dist = VectorNormalize(dir); + if (dist < self->radius) { // Within range + vec3_t forward; + float dot; + // 2: see if dot to us and player viewangles is > 0.7 + AngleVectors(player->client->renderInfo.eyeAngles, forward, NULL, NULL); + dot = DotProduct(forward, dir); + if (dot > self->random) { // Within the desired FOV + // 3: see if player is in PVS + if (gi.inPVS(self->currentOrigin, player->client->renderInfo.eyePoint)) { + vec3_t mins = {-1, -1, -1}; + vec3_t maxs = {1, 1, 1}; + // 4: If needbe, trace to see if there is clear LOS from player viewpos + if ((self->spawnflags & 1) || G_ClearTrace(player->client->renderInfo.eyePoint, mins, maxs, self->currentOrigin, 0, MASK_OPAQUE)) { + // 5: Fire! + G_UseTargets(self, player); + // 6: Remove yourself + G_FreeEntity(self); } } } } - } /*QUAKED trigger_visible (.1 .5 .1) (-8 -8 -8) (8 8 8) NOTRACE FORCESIGHT x x x x x INACTIVE @@ -1672,34 +1440,29 @@ void trigger_visible_check_player_visibility( gentity_t *self ) INACTIVE - won't check for player visibility until activated radius - how far this ent can be from player's eyes, max, and still be considered "seen" - FOV - how far off to the side of the player's field of view this can be, max, and still be considered "seen". Player FOV is 80, so the default for this value is 30. + FOV - how far off to the side of the player's field of view this can be, max, and still be considered "seen". Player FOV is 80, so the default for this value + is 30. "target" - What to use when it fires. */ -void SP_trigger_visible( gentity_t *self ) -{ - if ( self->radius <= 0 ) - { +void SP_trigger_visible(gentity_t *self) { + if (self->radius <= 0) { self->radius = 512; } - if ( self->random <= 0 ) - {//about 30 degrees + if (self->random <= 0) { // about 30 degrees self->random = 0.7f; - } - else - {//convert from FOV degrees to number meaningful for dot products - self->random = 1.0f - (self->random/90.0f); + } else { // convert from FOV degrees to number meaningful for dot products + self->random = 1.0f - (self->random / 90.0f); } - if ( self->spawnflags & 128 ) - {// Make it inactive + if (self->spawnflags & 128) { // Make it inactive self->svFlags |= SVF_INACTIVE; } - G_SetOrigin( self, self->s.origin ); - gi.linkentity( self ); + G_SetOrigin(self, self->s.origin); + gi.linkentity(self); self->e_ThinkFunc = thinkF_trigger_visible_check_player_visibility; - self->nextthink = level.time + FRAMETIME*2; + self->nextthink = level.time + FRAMETIME * 2; } diff --git a/code/game/g_turret.cpp b/code/game/g_turret.cpp index d7f90afa61..f45f26b899 100644 --- a/code/game/g_turret.cpp +++ b/code/game/g_turret.cpp @@ -25,185 +25,159 @@ along with this program; if not, see . #include "b_local.h" #include "../cgame/cg_local.h" -extern cvar_t *g_spskill; +extern cvar_t *g_spskill; -void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -void finish_spawning_turret( gentity_t *base ); -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ); -//special routine for tracking angles between client and server -rww +void G_SetEnemy(gentity_t *self, gentity_t *enemy); +void finish_spawning_turret(gentity_t *base); +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath); +// special routine for tracking angles between client and server -rww void turret_SetBoneAngles(gentity_t *ent, const char *bone, const vec3_t angles); -#define ARM_ANGLE_RANGE 60 -#define HEAD_ANGLE_RANGE 90 +#define ARM_ANGLE_RANGE 60 +#define HEAD_ANGLE_RANGE 90 -#define SPF_TURRETG2_TURBO 4 -#define SPF_TURRETG2_LEAD_ENEMY 8 +#define SPF_TURRETG2_TURBO 4 +#define SPF_TURRETG2_LEAD_ENEMY 8 #define name "models/map_objects/imp_mine/turret_canon.glm" #define name2 "models/map_objects/imp_mine/turret_damage.md3" #define name3 "models/map_objects/wedge/laser_cannon_model.glm" //------------------------------------------------------------------------------------------------------------ -void TurretPain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc ) +void TurretPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) //------------------------------------------------------------------------------------------------------------ { vec3_t dir; - VectorSubtract( point, self->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(point, self->currentOrigin, dir); + VectorNormalize(dir); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { // DEMP2 makes the turret stop shooting for a bit..and does extra feedback self->attackDebounceTime = level.time + 800 + Q_flrand(0.0f, 1.0f) * 500; - G_PlayEffect( "sparks/spark_exp_nosnd", point, dir ); + G_PlayEffect("sparks/spark_exp_nosnd", point, dir); } - if ( !self->enemy ) - {//react to being hit - G_SetEnemy( self, attacker ); + if (!self->enemy) { // react to being hit + G_SetEnemy(self, attacker); } - G_PlayEffect( "sparks/spark_exp_nosnd", point, dir ); + G_PlayEffect("sparks/spark_exp_nosnd", point, dir); } //------------------------------------------------------------------------------------------------------------ -void turret_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) +void turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) //------------------------------------------------------------------------------------------------------------ { - vec3_t forward = { 0,0,-1 }, pos; + vec3_t forward = {0, 0, -1}, pos; // Turn off the thinking of the base & use it's targets self->e_ThinkFunc = thinkF_NULL; self->e_UseFunc = useF_NULL; // clear my data - self->e_DieFunc = dieF_NULL; + self->e_DieFunc = dieF_NULL; self->takedamage = qfalse; self->health = 0; self->s.loopSound = 0; // hack the effect angle so that explode death can orient the effect properly - if ( self->spawnflags & 2 ) - { - VectorSet( forward, 0, 0, 1 ); + if (self->spawnflags & 2) { + VectorSet(forward, 0, 0, 1); } -// VectorCopy( self->currentOrigin, self->s.pos.trBase ); + // VectorCopy( self->currentOrigin, self->s.pos.trBase ); - if ( self->spawnflags & SPF_TURRETG2_TURBO ) - { - G_PlayEffect( G_EffectIndex( "explosions/fighter_explosion2" ), self->currentOrigin, self->currentAngles ); - } - else - { - if ( self->fxID > 0 ) - { - VectorMA( self->currentOrigin, 12, forward, pos ); - G_PlayEffect( self->fxID, pos, forward ); + if (self->spawnflags & SPF_TURRETG2_TURBO) { + G_PlayEffect(G_EffectIndex("explosions/fighter_explosion2"), self->currentOrigin, self->currentAngles); + } else { + if (self->fxID > 0) { + VectorMA(self->currentOrigin, 12, forward, pos); + G_PlayEffect(self->fxID, pos, forward); } } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 1; // black } self->s.weapon = 0; // crosshair code uses this to mark crosshair red - if ( self->s.modelindex2 ) - { + if (self->s.modelindex2) { // switch to damage model if we should self->s.modelindex = self->s.modelindex2; - VectorCopy( self->currentAngles, self->s.apos.trBase ); - VectorClear( self->s.apos.trDelta ); + VectorCopy(self->currentAngles, self->s.apos.trBase); + VectorClear(self->s.apos.trDelta); - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - } - else - { - ObjectDie( self, inflictor, attacker, damage, meansOfDeath ); + } else { + ObjectDie(self, inflictor, attacker, damage, meansOfDeath); } } -//start an animation on model_root both server side and client side -void TurboLaser_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) -{ - //set info on the entity so it knows to start the anim on the client next snapshot. - //eweb->s.eFlags |= EF_G2ANIMATING; +// start an animation on model_root both server side and client side +void TurboLaser_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) { + // set info on the entity so it knows to start the anim on the client next snapshot. + // eweb->s.eFlags |= EF_G2ANIMATING; - if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) - { //already playing this anim, let's flag it to restart - //eweb->s.torsoFlip = !eweb->s.torsoFlip; - } - else - { + if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) { // already playing this anim, let's flag it to restart + // eweb->s.torsoFlip = !eweb->s.torsoFlip; + } else { eweb->s.torsoAnim = startFrame; eweb->s.legsAnim = endFrame; } - //now set the animation on the server ghoul2 instance. + // now set the animation on the server ghoul2 instance. assert(&eweb->ghoul2[0]); - gi.G2API_SetBoneAnim(&eweb->ghoul2[0], "model_root", startFrame, endFrame, - (BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); + gi.G2API_SetBoneAnim(&eweb->ghoul2[0], "model_root", startFrame, endFrame, (BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); } #define START_DIS 15 -extern void WP_FireTurboLaserMissile( gentity_t *ent, vec3_t start, vec3_t dir ); +extern void WP_FireTurboLaserMissile(gentity_t *ent, vec3_t start, vec3_t dir); //---------------------------------------------------------------- -static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) +static void turret_fire(gentity_t *ent, vec3_t start, vec3_t dir) //---------------------------------------------------------------- { - vec3_t org, ang; - gentity_t *bolt; + vec3_t org, ang; + gentity_t *bolt; - if ( (gi.pointcontents( start, ent->s.number )&MASK_SHOT) ) - { + if ((gi.pointcontents(start, ent->s.number) & MASK_SHOT)) { return; } - VectorMA( start, -START_DIS, dir, org ); // dumb.... + VectorMA(start, -START_DIS, dir, org); // dumb.... - if ( ent->random ) - { - vectoangles( dir, ang ); - ang[PITCH] += Q_flrand( -ent->random, ent->random ); - ang[YAW] += Q_flrand( -ent->random, ent->random ); - AngleVectors( ang, dir, NULL, NULL ); + if (ent->random) { + vectoangles(dir, ang); + ang[PITCH] += Q_flrand(-ent->random, ent->random); + ang[YAW] += Q_flrand(-ent->random, ent->random); + AngleVectors(ang, dir, NULL, NULL); } vectoangles(dir, ang); - if ( (ent->spawnflags&SPF_TURRETG2_TURBO) ) - { - //muzzle flash - G_PlayEffect( G_EffectIndex( "turret/turb_muzzle_flash" ), org, ang ); - G_SoundOnEnt( ent, CHAN_LESS_ATTEN, "sound/vehicles/weapons/turbolaser/fire1" ); + if ((ent->spawnflags & SPF_TURRETG2_TURBO)) { + // muzzle flash + G_PlayEffect(G_EffectIndex("turret/turb_muzzle_flash"), org, ang); + G_SoundOnEnt(ent, CHAN_LESS_ATTEN, "sound/vehicles/weapons/turbolaser/fire1"); - WP_FireTurboLaserMissile( ent, start, dir ); - if ( ent->alt_fire ) - { - TurboLaser_SetBoneAnim( ent, 2, 3 ); + WP_FireTurboLaserMissile(ent, start, dir); + if (ent->alt_fire) { + TurboLaser_SetBoneAnim(ent, 2, 3); + } else { + TurboLaser_SetBoneAnim(ent, 0, 1); } - else - { - TurboLaser_SetBoneAnim( ent, 0, 1 ); - } - } - else - { - G_PlayEffect( "blaster/muzzle_flash", org, dir ); + } else { + G_PlayEffect("blaster/muzzle_flash", org, dir); bolt = G_Spawn(); @@ -214,218 +188,175 @@ static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) bolt->s.weapon = WP_BLASTER; bolt->owner = ent; bolt->damage = ent->damage; - bolt->dflags = DAMAGE_NO_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; bolt->methodOfDeath = MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - bolt->trigger_formation = qfalse; // don't draw tail on first frame + bolt->trigger_formation = qfalse; // don't draw tail on first frame - VectorSet( bolt->maxs, 1.5, 1.5, 1.5 ); - VectorScale( bolt->maxs, -1, bolt->mins ); + VectorSet(bolt->maxs, 1.5, 1.5, 1.5); + VectorScale(bolt->maxs, -1, bolt->mins); bolt->s.pos.trType = TR_LINEAR; bolt->s.pos.trTime = level.time; - VectorCopy( start, bolt->s.pos.trBase ); - VectorScale( dir, 1100, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( start, bolt->currentOrigin); + VectorCopy(start, bolt->s.pos.trBase); + VectorScale(dir, 1100, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->currentOrigin); } } //----------------------------------------------------- -void turret_head_think( gentity_t *self ) +void turret_head_think(gentity_t *self) //----------------------------------------------------- { // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time - if ( self->enemy && self->pushDebounceTime < level.time && self->attackDebounceTime < level.time ) - { + if (self->enemy && self->pushDebounceTime < level.time && self->attackDebounceTime < level.time) { // set up our next fire time self->pushDebounceTime = level.time + self->wait; - vec3_t fwd, org; - mdxaBone_t boltMatrix; + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( self->ghoul2, - 0, - (self->spawnflags&SPF_TURRETG2_TURBO) ? ( (self->alt_fire ? gi.G2API_AddBolt( &self->ghoul2[0], "*muzzle2" ) : gi.G2API_AddBolt( &self->ghoul2[0], "*muzzle1" )) ) : gi.G2API_AddBolt( &self->ghoul2[0], "*flash03" ), - &boltMatrix, - self->currentAngles, - self->currentOrigin, - level.time, - NULL, - self->modelScale ); - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { + gi.G2API_GetBoltMatrix(self->ghoul2, 0, + (self->spawnflags & SPF_TURRETG2_TURBO) + ? ((self->alt_fire ? gi.G2API_AddBolt(&self->ghoul2[0], "*muzzle2") : gi.G2API_AddBolt(&self->ghoul2[0], "*muzzle1"))) + : gi.G2API_AddBolt(&self->ghoul2[0], "*flash03"), + &boltMatrix, self->currentAngles, self->currentOrigin, level.time, NULL, self->modelScale); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { self->alt_fire = (qboolean)!self->alt_fire; } - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, fwd ); - } - else - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, fwd); + } else { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); } - VectorMA( org, START_DIS, fwd, org ); + VectorMA(org, START_DIS, fwd, org); - turret_fire( self, org, fwd ); - self->fly_sound_debounce_time = level.time;//used as lastShotTime + turret_fire(self, org, fwd); + self->fly_sound_debounce_time = level.time; // used as lastShotTime } } //----------------------------------------------------- -static void turret_aim( gentity_t *self ) +static void turret_aim(gentity_t *self) //----------------------------------------------------- { - vec3_t enemyDir, org, org2; - vec3_t desiredAngles, setAngle; - float diffYaw = 0.0f, diffPitch = 0.0f; - float maxYawSpeed = ( self->spawnflags & SPF_TURRETG2_TURBO ) ? 30.0f : 14.0f; - float maxPitchSpeed = ( self->spawnflags & SPF_TURRETG2_TURBO ) ? 15.0f : 3.0f; + vec3_t enemyDir, org, org2; + vec3_t desiredAngles, setAngle; + float diffYaw = 0.0f, diffPitch = 0.0f; + float maxYawSpeed = (self->spawnflags & SPF_TURRETG2_TURBO) ? 30.0f : 14.0f; + float maxPitchSpeed = (self->spawnflags & SPF_TURRETG2_TURBO) ? 15.0f : 3.0f; // move our gun base yaw to where we should be at this time.... - EvaluateTrajectory( &self->s.apos, level.time, self->currentAngles ); - self->currentAngles[YAW] = AngleNormalize360( self->currentAngles[YAW] ); - self->speed = AngleNormalize360( self->speed ); + EvaluateTrajectory(&self->s.apos, level.time, self->currentAngles); + self->currentAngles[YAW] = AngleNormalize360(self->currentAngles[YAW]); + self->speed = AngleNormalize360(self->speed); - if ( self->enemy ) - { + if (self->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->currentOrigin, org); } - else - { - VectorCopy( self->enemy->currentOrigin, org ); - } - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] -= 5; } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Getting the "eye" here - gi.G2API_GetBoltMatrix( self->ghoul2, - 0, - (self->spawnflags&SPF_TURRETG2_TURBO) ? ( (self->alt_fire ? gi.G2API_AddBolt( &self->ghoul2[0], "*muzzle2" ) : gi.G2API_AddBolt( &self->ghoul2[0], "*muzzle1" )) ) : gi.G2API_AddBolt( &self->ghoul2[0], "*flash03" ), - &boltMatrix, - self->currentAngles, - self->s.origin, - level.time, - NULL, - self->modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, 0, + (self->spawnflags & SPF_TURRETG2_TURBO) + ? ((self->alt_fire ? gi.G2API_AddBolt(&self->ghoul2[0], "*muzzle2") : gi.G2API_AddBolt(&self->ghoul2[0], "*muzzle1"))) + : gi.G2API_AddBolt(&self->ghoul2[0], "*flash03"), + &boltMatrix, self->currentAngles, self->s.origin, level.time, NULL, self->modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - VectorSubtract( org, org2, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, org2, enemyDir); + vectoangles(enemyDir, desiredAngles); - diffYaw = AngleSubtract( self->currentAngles[YAW], desiredAngles[YAW] ); - diffPitch = AngleSubtract( self->speed, desiredAngles[PITCH] ); - } - else - { + diffYaw = AngleSubtract(self->currentAngles[YAW], desiredAngles[YAW]); + diffPitch = AngleSubtract(self->speed, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one -// diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. + // diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. } - if ( diffYaw ) - { + if (diffYaw) { // cap max speed.... - if ( fabs(diffYaw) > maxYawSpeed ) - { - diffYaw = ( diffYaw >= 0 ? maxYawSpeed : -maxYawSpeed ); + if (fabs(diffYaw) > maxYawSpeed) { + diffYaw = (diffYaw >= 0 ? maxYawSpeed : -maxYawSpeed); } // ...then set up our desired yaw - VectorSet( setAngle, 0.0f, diffYaw, 0.0f ); + VectorSet(setAngle, 0.0f, diffYaw, 0.0f); - VectorCopy( self->currentAngles, self->s.apos.trBase ); - VectorScale( setAngle,- 5, self->s.apos.trDelta ); + VectorCopy(self->currentAngles, self->s.apos.trBase); + VectorScale(setAngle, -5, self->s.apos.trDelta); self->s.apos.trTime = level.time; self->s.apos.trType = TR_LINEAR; } - if ( diffPitch ) - { - if ( fabs(diffPitch) > maxPitchSpeed ) - { + if (diffPitch) { + if (fabs(diffPitch) > maxPitchSpeed) { // cap max speed self->speed += (diffPitch > 0.0f) ? -maxPitchSpeed : maxPitchSpeed; - } - else - { + } else { // small enough, so just add half the diff so we smooth out the stopping - self->speed -= ( diffPitch );//desiredAngles[PITCH]; + self->speed -= (diffPitch); // desiredAngles[PITCH]; } // Note that this is NOT interpolated, so it will be less smooth...On the other hand, it does use Ghoul2 to blend, so it may smooth it out a bit? - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - if ( self->spawnflags & 2 ) - { - VectorSet( desiredAngles, 0.0f, 0.0f, -self->speed ); - } - else - { - VectorSet( desiredAngles, 0.0f, 0.0f, self->speed ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + if (self->spawnflags & 2) { + VectorSet(desiredAngles, 0.0f, 0.0f, -self->speed); + } else { + VectorSet(desiredAngles, 0.0f, 0.0f, self->speed); } turret_SetBoneAngles(self, "pitch", desiredAngles); - } - else - { + } else { // Note that this is NOT interpolated, so it will be less smooth...On the other hand, it does use Ghoul2 to blend, so it may smooth it out a bit? - if ( self->spawnflags & 2 ) - { - VectorSet( desiredAngles, self->speed, 0.0f, 0.0f ); + if (self->spawnflags & 2) { + VectorSet(desiredAngles, self->speed, 0.0f, 0.0f); + } else { + VectorSet(desiredAngles, -self->speed, 0.0f, 0.0f); } - else - { - VectorSet( desiredAngles, -self->speed, 0.0f, 0.0f ); - } - gi.G2API_SetBoneAngles( &self->ghoul2[0], "Bone_body", desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time ); + gi.G2API_SetBoneAngles(&self->ghoul2[0], "Bone_body", desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time); } } - if ( diffYaw || diffPitch ) - { - self->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); - } - else - { + if (diffYaw || diffPitch) { + self->s.loopSound = G_SoundIndex("sound/chars/turret/move.wav"); + } else { self->s.loopSound = 0; } } //----------------------------------------------------- -static void turret_turnoff( gentity_t *self ) +static void turret_turnoff(gentity_t *self) //----------------------------------------------------- { - if ( self->enemy == NULL ) - { + if (self->enemy == NULL) { // we don't need to turnoff return; } - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - TurboLaser_SetBoneAnim( self, 4, 5 ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + TurboLaser_SetBoneAnim(self, 4, 5); } // shut-down sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/shutdown.wav")); // make turret play ping sound for 5 seconds self->aimDebounceTime = level.time + 5000; @@ -435,91 +366,77 @@ static void turret_turnoff( gentity_t *self ) } //----------------------------------------------------- -static qboolean turret_find_enemies( gentity_t *self ) +static qboolean turret_find_enemies(gentity_t *self) //----------------------------------------------------- { // HACK for t2_wedge!!! - if ( self->spawnflags & SPF_TURRETG2_TURBO ) + if (self->spawnflags & SPF_TURRETG2_TURBO) return qfalse; - qboolean found = qfalse; - int count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; + qboolean found = qfalse; + int count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - G_Sound(self, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + G_Sound(self, G_SoundIndex("sound/chars/turret/ping.wav")); self->painDebounceTime = level.time + 1000; } } - VectorCopy( self->currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 20; - } - else - { + } else { org2[2] -= 20; } - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { // only attack clients continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client->playerTeam == self->noDamageTeam ) - { + if (target->client->playerTeam == self->noDamageTeam) { // A bot we don't want to shoot continue; } - if ( !gi.inPVS( org2, target->currentOrigin )) - { + if (!gi.inPVS(org2, target->currentOrigin)) { continue; } - VectorCopy( target->client->renderInfo.eyePoint, org ); + VectorCopy(target->client->renderInfo.eyePoint, org); - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] += 5; } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist )// all things equal, keep current + if (enemyDist < bestDist) // all things equal, keep current { - if ( self->attackDebounceTime < level.time ) - { + if (self->attackDebounceTime < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/startup.wav")); // Wind up turrets for a bit self->attackDebounceTime = level.time + 1400; @@ -532,17 +449,14 @@ static qboolean turret_find_enemies( gentity_t *self ) } } - if ( found ) - { - if ( !self->enemy ) - {//just aquired one - AddSoundEvent( bestTarget, self->currentOrigin, 256, AEL_DISCOVERED ); - AddSightEvent( bestTarget, self->currentOrigin, 512, AEL_DISCOVERED, 20 ); + if (found) { + if (!self->enemy) { // just aquired one + AddSoundEvent(bestTarget, self->currentOrigin, 256, AEL_DISCOVERED); + AddSightEvent(bestTarget, self->currentOrigin, 512, AEL_DISCOVERED, 20); } - G_SetEnemy( self, bestTarget ); - if ( VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + G_SetEnemy(self, bestTarget); + if (VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } } @@ -550,120 +464,97 @@ static qboolean turret_find_enemies( gentity_t *self ) } //----------------------------------------------------- -void turret_base_think( gentity_t *self ) +void turret_base_think(gentity_t *self) //----------------------------------------------------- { - qboolean turnOff = qtrue; - float enemyDist; - vec3_t enemyDir, org, org2; + qboolean turnOff = qtrue; + float enemyDist; + vec3_t enemyDir, org, org2; self->nextthink = level.time + FRAMETIME; - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { // not turned on - turret_turnoff( self ); - turret_aim( self ); + turret_turnoff(self); + turret_aim(self); // No target self->flags |= FL_NOTARGET; return; - } - else - { + } else { // I'm all hot and bothered self->flags &= ~FL_NOTARGET; } - if ( !self->enemy ) - { - if ( turret_find_enemies( self )) - { + if (!self->enemy) { + if (turret_find_enemies(self)) { turnOff = qfalse; } - } - else - { - if ( self->enemy->health > 0 ) - { + } else { + if (self->enemy->health > 0) { // enemy is alive - VectorSubtract( self->enemy->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(self->enemy->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < self->radius * self->radius ) - { + if (enemyDist < self->radius * self->radius) { // was in valid radius - if ( gi.inPVS( self->currentOrigin, self->enemy->currentOrigin ) ) - { + if (gi.inPVS(self->currentOrigin, self->enemy->currentOrigin)) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->currentOrigin, org); } - else - { - VectorCopy( self->enemy->currentOrigin, org ); - } - VectorCopy( self->currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 10; - } - else - { + } else { org2[2] -= 10; } - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( self->spawnflags & SPF_TURRETG2_TURBO || ( !tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number ) ) - { - turnOff = qfalse; // Can see our enemy + if (self->spawnflags & SPF_TURRETG2_TURBO || (!tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number)) { + turnOff = qfalse; // Can see our enemy } } } } - turret_head_think( self ); + turret_head_think(self); } - if ( turnOff ) - { - if ( self->bounceCount < level.time ) // bounceCount is used to keep the thing from ping-ponging from on to off + if (turnOff) { + if (self->bounceCount < level.time) // bounceCount is used to keep the thing from ping-ponging from on to off { - turret_turnoff( self ); + turret_turnoff(self); } - } - else - { + } else { // keep our enemy for a minimum of 2 seconds from now self->bounceCount = level.time + 2000 + Q_flrand(0.0f, 1.0f) * 150; } - turret_aim( self ); + turret_aim(self); } //----------------------------------------------------------------------------- -void turret_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void turret_base_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); - if (( self->s.eFlags & EF_SHADER_ANIM ) && ( self->spawnflags & 1 )) // Start_Off + if ((self->s.eFlags & EF_SHADER_ANIM) && (self->spawnflags & 1)) // Start_Off { self->s.frame = 1; // black - } - else - { + } else { self->s.frame = 0; // glow } } -//special routine for tracking angles between client and server -rww -void turret_SetBoneAngles(gentity_t *ent, const char *bone, const vec3_t angles) -{ +// special routine for tracking angles between client and server -rww +void turret_SetBoneAngles(gentity_t *ent, const char *bone, const vec3_t angles) { /* int *thebone = &ent->s.boneIndex1; int *firstFree = NULL; @@ -732,10 +623,9 @@ void turret_SetBoneAngles(gentity_t *ent, const char *bone, const vec3_t angles) //to set the bone angles on the client. VectorCopy(angles, *boneVector); */ - //Now set the angles on our server instance if we have one. + // Now set the angles on our server instance if we have one. - if ( !ent->ghoul2.size() ) - { + if (!ent->ghoul2.size()) { return; } @@ -745,24 +635,20 @@ void turret_SetBoneAngles(gentity_t *ent, const char *bone, const vec3_t angles) right = NEGATIVE_Z; forward = NEGATIVE_X; - //first 3 bits is forward, second 3 bits is right, third 3 bits is up - //ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); + // first 3 bits is forward, second 3 bits is right, third 3 bits is up + // ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); - gi.G2API_SetBoneAngles( &ent->ghoul2[0], bone, angles, flags, up, - right, forward, NULL, 100, level.time ); + gi.G2API_SetBoneAngles(&ent->ghoul2[0], bone, angles, flags, up, right, forward, NULL, 100, level.time); } -void turret_set_models( gentity_t *self, qboolean dying ) -{ - if ( dying ) - { - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - self->s.modelindex = G_ModelIndex( name2 ); - self->s.modelindex2 = G_ModelIndex( name ); +void turret_set_models(gentity_t *self, qboolean dying) { + if (dying) { + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + self->s.modelindex = G_ModelIndex(name2); + self->s.modelindex2 = G_ModelIndex(name); } - gi.G2API_RemoveGhoul2Model( self->ghoul2, 0 ); + gi.G2API_RemoveGhoul2Model(self->ghoul2, 0); /*G_KillG2Queue( self->s.number ); self->s.modelGhoul2 = 0; @@ -777,39 +663,26 @@ void turret_set_models( gentity_t *self, qboolean dying ) 0, 0); */ - } - else - { - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - self->s.modelindex = G_ModelIndex( name ); - self->s.modelindex2 = G_ModelIndex( name2 ); - //set the new onw - gi.G2API_InitGhoul2Model( self->ghoul2, - name, - 0, //base->s.modelindex, - //note, this is not the same kind of index - this one's referring to the actual - //index of the model in the g2 instance, whereas modelindex is the index of a - //configstring -rww - 0, - 0, - 0, - 0); - } - else - { - self->s.modelindex = G_ModelIndex( name3 ); - //set the new onw - gi.G2API_InitGhoul2Model( self->ghoul2, - name3, - 0, //base->s.modelindex, - //note, this is not the same kind of index - this one's referring to the actual - //index of the model in the g2 instance, whereas modelindex is the index of a - //configstring -rww - 0, - 0, - 0, - 0); + } else { + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + self->s.modelindex = G_ModelIndex(name); + self->s.modelindex2 = G_ModelIndex(name2); + // set the new onw + gi.G2API_InitGhoul2Model(self->ghoul2, name, + 0, // base->s.modelindex, + // note, this is not the same kind of index - this one's referring to the actual + // index of the model in the g2 instance, whereas modelindex is the index of a + // configstring -rww + 0, 0, 0, 0); + } else { + self->s.modelindex = G_ModelIndex(name3); + // set the new onw + gi.G2API_InitGhoul2Model(self->ghoul2, name3, + 0, // base->s.modelindex, + // note, this is not the same kind of index - this one's referring to the actual + // index of the model in the g2 instance, whereas modelindex is the index of a + // configstring -rww + 0, 0, 0, 0); } /*self->s.modelGhoul2 = 1; @@ -822,16 +695,13 @@ void turret_set_models( gentity_t *self, qboolean dying ) self->s.g2radius = 80; }*/ - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - {//different pitch bone and muzzle flash points + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { // different pitch bone and muzzle flash points turret_SetBoneAngles(self, "pitch", vec3_origin); - //self->genericValue11 = gi.G2API_AddBolt( self->ghoul2, 0, "*muzzle1" ); - //self->genericValue12 = gi.G2API_AddBolt( self->ghoul2, 0, "*muzzle2" ); - } - else - { + // self->genericValue11 = gi.G2API_AddBolt( self->ghoul2, 0, "*muzzle1" ); + // self->genericValue12 = gi.G2API_AddBolt( self->ghoul2, 0, "*muzzle2" ); + } else { turret_SetBoneAngles(self, "Bone_body", vec3_origin); - //self->genericValue11 = gi.G2API_AddBolt( self->ghoul2, 0, "*flash03" ); + // self->genericValue11 = gi.G2API_AddBolt( self->ghoul2, 0, "*flash03" ); } } } @@ -862,44 +732,40 @@ Turret that hangs from the ceiling, will aim and shoot at enemies "neutral" */ //----------------------------------------------------- -void SP_misc_turret( gentity_t *base ) +void SP_misc_turret(gentity_t *base) //----------------------------------------------------- { /*base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/turret_canon.glm" ); base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/turret_damage.md3" ); base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/turret_canon.glm", base->s.modelindex ); base->s.radius = 80.0f;*/ - turret_set_models( base, qfalse ); + turret_set_models(base, qfalse); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash03" ); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash03"); - finish_spawning_turret( base ); + finish_spawning_turret(base); - if (( base->spawnflags & 1 )) // Start_Off + if ((base->spawnflags & 1)) // Start_Off { base->s.frame = 1; // black - } - else - { + } else { base->s.frame = 0; // glow } base->s.eFlags |= EF_SHADER_ANIM; } //----------------------------------------------------- -void finish_spawning_turret( gentity_t *base ) -{ - vec3_t fwd; +void finish_spawning_turret(gentity_t *base) { + vec3_t fwd; - if ( base->spawnflags & 2 ) - { + if (base->spawnflags & 2) { base->s.angles[ROLL] += 180; base->s.origin[2] -= 22.0f; } - G_SetAngles( base, base->s.angles ); - AngleVectors( base->currentAngles, fwd, NULL, NULL ); + G_SetAngles(base, base->s.angles); + AngleVectors(base->currentAngles, fwd, NULL, NULL); G_SetOrigin(base, base->s.origin); @@ -907,15 +773,14 @@ void finish_spawning_turret( gentity_t *base ) base->s.eType = ET_GENERAL; - if ( base->team && base->team[0] ) - { - base->noDamageTeam = (team_t)GetIDForString( TeamTable, base->team ); + if (base->team && base->team[0]) { + base->noDamageTeam = (team_t)GetIDForString(TeamTable, base->team); base->team = NULL; } // Set up our explosion effect for the ExplodeDeath code.... - base->fxID = G_EffectIndex( "turret/explode" ); - G_EffectIndex( "sparks/spark_exp_nosnd" ); + base->fxID = G_EffectIndex("turret/explode"); + G_EffectIndex("sparks/spark_exp_nosnd"); base->e_UseFunc = useF_turret_base_use; base->e_PainFunc = painF_TurretPain; @@ -927,166 +792,140 @@ void finish_spawning_turret( gentity_t *base ) // this is really the pitch angle..... base->speed = 0; - G_SpawnFloat( "shotspeed", "0", &base->mass ); - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - if ( !base->random ) - {//error worked into projectile direction + G_SpawnFloat("shotspeed", "0", &base->mass); + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + if (!base->random) { // error worked into projectile direction base->random = 2.0f; } - if ( !base->mass ) - {//misnomer: speed of projectile + if (!base->mass) { // misnomer: speed of projectile base->mass = 4000; } - if ( !base->health ) - { + if (!base->health) { base->health = 2000; } // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 32768; } // How quickly to fire - if ( !base->wait ) - { - base->wait = 500;// + Q_flrand(0.0f, 1.0f) * 500; + if (!base->wait) { + base->wait = 500; // + Q_flrand(0.0f, 1.0f) * 500; } - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 200; } - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 500; } // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 10; } - VectorSet( base->s.modelScale, 2.0f, 2.0f, 2.0f ); - VectorSet( base->maxs, 128.0f, 128.0f, 120.0f ); - VectorSet( base->mins, -128.0f, -128.0f, -120.0f ); + VectorSet(base->s.modelScale, 2.0f, 2.0f, 2.0f); + VectorSet(base->maxs, 128.0f, 128.0f, 120.0f); + VectorSet(base->mins, -128.0f, -128.0f, -120.0f); // Cull Radius. base->s.radius = 256; - //start in "off" anim - TurboLaser_SetBoneAnim( base, 4, 5 ); + // start in "off" anim + TurboLaser_SetBoneAnim(base, 4, 5); // Make sure it doesn't do sparks and such when saber contacts with it. base->flags = FL_DMG_BY_HEAVY_WEAP_ONLY; base->takedamage = qfalse; - base->contents = CONTENTS_BODY|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_SHOTCLIP; + base->contents = CONTENTS_BODY | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_SHOTCLIP; base->noDamageTeam = TEAM_NEUTRAL; base->team = NULL; - } - else - { + } else { // this is a random time offset for the no-enemy-search-around-mode base->count = Q_flrand(0.0f, 1.0f) * 9000; - if ( !base->health ) - { + if (!base->health) { base->health = 100; } // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 512; } // How quickly to fire - if ( !base->wait ) - { + if (!base->wait) { base->wait = 150 + Q_flrand(0.0f, 1.0f) * 55; } - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 10; } - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 25; } // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 5; } - if ( base->spawnflags & 2 ) - {//upside-down, invert mins and maxe - VectorSet( base->maxs, 10.0f, 10.0f, 30.0f ); - VectorSet( base->mins, -10.0f, -10.0f, 0.0f ); - } - else - { - VectorSet( base->maxs, 10.0f, 10.0f, 0.0f ); - VectorSet( base->mins, -10.0f, -10.0f, -30.0f ); + if (base->spawnflags & 2) { // upside-down, invert mins and maxe + VectorSet(base->maxs, 10.0f, 10.0f, 30.0f); + VectorSet(base->mins, -10.0f, -10.0f, 0.0f); + } else { + VectorSet(base->maxs, 10.0f, 10.0f, 0.0f); + VectorSet(base->mins, -10.0f, -10.0f, -30.0f); } base->takedamage = qtrue; - base->contents = CONTENTS_BODY|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_SHOTCLIP; + base->contents = CONTENTS_BODY | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_SHOTCLIP; } // Precache special FX and moving sounds - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - G_EffectIndex( "turret/turb_muzzle_flash" ); - G_EffectIndex( "turret/turb_shot" ); - G_EffectIndex( "turret/turb_impact" ); - //FIXME: Turbo Laser Cannon sounds! - G_SoundIndex( "sound/vehicles/weapons/turbolaser/turn.wav" ); - G_EffectIndex( "explosions/fighter_explosion2" ); - RegisterItem( FindItemForWeapon( WP_TIE_FIGHTER )); - } - else - { + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + G_EffectIndex("turret/turb_muzzle_flash"); + G_EffectIndex("turret/turb_shot"); + G_EffectIndex("turret/turb_impact"); + // FIXME: Turbo Laser Cannon sounds! + G_SoundIndex("sound/vehicles/weapons/turbolaser/turn.wav"); + G_EffectIndex("explosions/fighter_explosion2"); + RegisterItem(FindItemForWeapon(WP_TIE_FIGHTER)); + } else { // Precache moving sounds - G_SoundIndex( "sound/chars/turret/startup.wav" ); - G_SoundIndex( "sound/chars/turret/shutdown.wav" ); - G_SoundIndex( "sound/chars/turret/ping.wav" ); - G_SoundIndex( "sound/chars/turret/move.wav" ); + G_SoundIndex("sound/chars/turret/startup.wav"); + G_SoundIndex("sound/chars/turret/shutdown.wav"); + G_SoundIndex("sound/chars/turret/ping.wav"); + G_SoundIndex("sound/chars/turret/move.wav"); } base->max_health = base->health; - base->e_DieFunc = dieF_turret_die; + base->e_DieFunc = dieF_turret_die; base->material = MAT_METAL; - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - RegisterItem( FindItemForWeapon( WP_TURRET )); + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + RegisterItem(FindItemForWeapon(WP_TURRET)); - base->svFlags |= SVF_NO_TELEPORT|SVF_SELF_ANIMATING; - } - else - { + base->svFlags |= SVF_NO_TELEPORT | SVF_SELF_ANIMATING; + } else { // Register this so that we can use it for the missile effect - RegisterItem( FindItemForWeapon( WP_BLASTER )); + RegisterItem(FindItemForWeapon(WP_BLASTER)); - base->svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; + base->svFlags |= SVF_NO_TELEPORT | SVF_NONNPC_ENEMY | SVF_SELF_ANIMATING; } // But set us as a turret so that we can be identified as a turret base->s.weapon = WP_TURRET; - gi.linkentity( base ); + gi.linkentity(base); } /*QUAKED misc_ns_turret (1 0 0) (-8 -8 -32) (8 8 29) START_OFF @@ -1112,132 +951,121 @@ NS turret that only hangs from the ceiling, will aim and shoot at enemies "neutral" */ //----------------------------------------------------- -void SP_misc_ns_turret( gentity_t *base ) +void SP_misc_ns_turret(gentity_t *base) //----------------------------------------------------- { - base->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/turret/turret.glm" ); - base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/turret_damage.md3" ); // FIXME! - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/nar_shaddar/turret/turret.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/turret/turret.glm"); + base->s.modelindex2 = G_ModelIndex("models/map_objects/imp_mine/turret_damage.md3"); // FIXME! + base->playerModel = + gi.G2API_InitGhoul2Model(base->ghoul2, "models/map_objects/nar_shaddar/turret/turret.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 80.0f; - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); - finish_spawning_turret( base ); + finish_spawning_turret(base); } //-------------------------------------- -void laser_arm_fire (gentity_t *ent) -{ - vec3_t start, end, fwd, rt, up; - trace_t trace; +void laser_arm_fire(gentity_t *ent) { + vec3_t start, end, fwd, rt, up; + trace_t trace; - if ( ent->attackDebounceTime < level.time && ent->alt_fire ) - { + if (ent->attackDebounceTime < level.time && ent->alt_fire) { // If I'm firing the laser and it's time to quit....then quit! ent->alt_fire = qfalse; -// ent->e_ThinkFunc = thinkF_NULL; -// return; + // ent->e_ThinkFunc = thinkF_NULL; + // return; } ent->nextthink = level.time + FRAMETIME; // If a fool gets in the laser path, fry 'em - AngleVectors( ent->currentAngles, fwd, rt, up ); + AngleVectors(ent->currentAngles, fwd, rt, up); - VectorMA( ent->currentOrigin, 20, fwd, start ); - //VectorMA( start, -6, rt, start ); - //VectorMA( start, -3, up, start ); - VectorMA( start, 4096, fwd, end ); + VectorMA(ent->currentOrigin, 20, fwd, start); + // VectorMA( start, -6, rt, start ); + // VectorMA( start, -3, up, start ); + VectorMA(start, 4096, fwd, end); - gi.trace( &trace, start, NULL, NULL, end, ENTITYNUM_NONE, MASK_SHOT, (EG2_Collision)0, 0 );//ignore - ent->fly_sound_debounce_time = level.time;//used as lastShotTime + gi.trace(&trace, start, NULL, NULL, end, ENTITYNUM_NONE, MASK_SHOT, (EG2_Collision)0, 0); // ignore + ent->fly_sound_debounce_time = level.time; // used as lastShotTime // Only deal damage when in alt-fire mode - if ( trace.fraction < 1.0 && ent->alt_fire ) - { - if ( trace.entityNum < ENTITYNUM_WORLD ) - { + if (trace.fraction < 1.0 && ent->alt_fire) { + if (trace.entityNum < ENTITYNUM_WORLD) { gentity_t *hapless_victim = &g_entities[trace.entityNum]; - if ( hapless_victim && hapless_victim->takedamage && ent->damage ) - { - G_Damage( hapless_victim, ent, ent->nextTrain->activator, fwd, trace.endpos, ent->damage, DAMAGE_IGNORE_TEAM, MOD_UNKNOWN ); + if (hapless_victim && hapless_victim->takedamage && ent->damage) { + G_Damage(hapless_victim, ent, ent->nextTrain->activator, fwd, trace.endpos, ent->damage, DAMAGE_IGNORE_TEAM, MOD_UNKNOWN); } } } - if ( ent->alt_fire ) - { -// CG_FireLaser( start, trace.endpos, trace.plane.normal, ent->nextTrain->startRGBA, qfalse ); - } - else - { -// CG_AimLaser( start, trace.endpos, trace.plane.normal ); + if (ent->alt_fire) { + // CG_FireLaser( start, trace.endpos, trace.plane.normal, ent->nextTrain->startRGBA, qfalse ); + } else { + // CG_AimLaser( start, trace.endpos, trace.plane.normal ); } } -void laser_arm_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - vec3_t newAngles; +void laser_arm_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + vec3_t newAngles; self->activator = activator; - switch( self->count ) - { + switch (self->count) { case 0: default: - //Fire - //gi.Printf("FIRE!\n"); -// self->lastEnemy->lastEnemy->e_ThinkFunc = thinkF_laser_arm_fire; -// self->lastEnemy->lastEnemy->nextthink = level.time + FRAMETIME; - //For 3 seconds + // Fire + // gi.Printf("FIRE!\n"); + // self->lastEnemy->lastEnemy->e_ThinkFunc = thinkF_laser_arm_fire; + // self->lastEnemy->lastEnemy->nextthink = level.time + FRAMETIME; + // For 3 seconds self->lastEnemy->lastEnemy->alt_fire = qtrue; // Let 'er rip! self->lastEnemy->lastEnemy->attackDebounceTime = level.time + self->lastEnemy->lastEnemy->wait; G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/fire.wav")); break; case 1: - //Yaw left - //gi.Printf("LEFT...\n"); - VectorCopy( self->lastEnemy->currentAngles, newAngles ); + // Yaw left + // gi.Printf("LEFT...\n"); + VectorCopy(self->lastEnemy->currentAngles, newAngles); newAngles[1] += self->speed; - G_SetAngles( self->lastEnemy, newAngles ); -// bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); - G_Sound( self->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy, newAngles); + // bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_Sound(self->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 2: - //Yaw right - //gi.Printf("RIGHT...\n"); - VectorCopy( self->lastEnemy->currentAngles, newAngles ); + // Yaw right + // gi.Printf("RIGHT...\n"); + VectorCopy(self->lastEnemy->currentAngles, newAngles); newAngles[1] -= self->speed; - G_SetAngles( self->lastEnemy, newAngles ); -// bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); - G_Sound( self->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy, newAngles); + // bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_Sound(self->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 3: - //pitch up - //gi.Printf("UP...\n"); - //FIXME: Clamp - VectorCopy( self->lastEnemy->lastEnemy->currentAngles, newAngles ); + // pitch up + // gi.Printf("UP...\n"); + // FIXME: Clamp + VectorCopy(self->lastEnemy->lastEnemy->currentAngles, newAngles); newAngles[0] -= self->speed; - if ( newAngles[0] < -45 ) - { + if (newAngles[0] < -45) { newAngles[0] = -45; } - G_SetAngles( self->lastEnemy->lastEnemy, newAngles ); - G_Sound( self->lastEnemy->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy->lastEnemy, newAngles); + G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 4: - //pitch down - //gi.Printf("DOWN...\n"); - //FIXME: Clamp - VectorCopy( self->lastEnemy->lastEnemy->currentAngles, newAngles ); + // pitch down + // gi.Printf("DOWN...\n"); + // FIXME: Clamp + VectorCopy(self->lastEnemy->lastEnemy->currentAngles, newAngles); newAngles[0] += self->speed; - if ( newAngles[0] > 90 ) - { + if (newAngles[0] > 90) { newAngles[0] = 90; } - G_SetAngles( self->lastEnemy->lastEnemy, newAngles ); - G_Sound( self->lastEnemy->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy->lastEnemy, newAngles); + G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; } } @@ -1260,114 +1088,97 @@ What it does when used depends on it's "count" (can be set by a script) "startRGBA" - laser color, Red Green Blue Alpha, range 0 to 1 (default 1.0 0.85 0.15 0.75 = Yellow-Orange) */ -void laser_arm_start (gentity_t *base) -{ - vec3_t armAngles; - vec3_t headAngles; +void laser_arm_start(gentity_t *base) { + vec3_t armAngles; + vec3_t headAngles; base->e_ThinkFunc = thinkF_NULL; - //We're the base, spawn the arm and head + // We're the base, spawn the arm and head gentity_t *arm = G_Spawn(); gentity_t *head = G_Spawn(); - VectorCopy( base->s.angles, armAngles ); - VectorCopy( base->s.angles, headAngles ); - if ( base->target && base->target[0] ) - {//Start out pointing at something - gentity_t *targ = G_Find( NULL, FOFS(targetname), base->target ); - if ( !targ ) - {//couldn't find it! + VectorCopy(base->s.angles, armAngles); + VectorCopy(base->s.angles, headAngles); + if (base->target && base->target[0]) { // Start out pointing at something + gentity_t *targ = G_Find(NULL, FOFS(targetname), base->target); + if (!targ) { // couldn't find it! Com_Printf(S_COLOR_RED "ERROR : laser_arm can't find target %s!\n", base->target); - } - else - {//point at it - vec3_t dir, angles; + } else { // point at it + vec3_t dir, angles; - VectorSubtract(targ->currentOrigin, base->s.origin, dir ); - vectoangles( dir, angles ); + VectorSubtract(targ->currentOrigin, base->s.origin, dir); + vectoangles(dir, angles); armAngles[1] = angles[1]; headAngles[0] = angles[0]; headAngles[1] = angles[1]; } } - //Base - //Base does the looking for enemies and pointing the arm and head - G_SetAngles( base, base->s.angles ); - //base->s.origin[2] += 4; + // Base + // Base does the looking for enemies and pointing the arm and head + G_SetAngles(base, base->s.angles); + // base->s.origin[2] += 4; G_SetOrigin(base, base->s.origin); gi.linkentity(base); - //FIXME: need an actual model + // FIXME: need an actual model base->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_base.md3"); base->s.eType = ET_GENERAL; - G_SpawnVector4( "startRGBA", "1.0 0.85 0.15 0.75", (float *)&base->startRGBA ); - //anglespeed - how fast it can track the player, entered in degrees per second, so we divide by FRAMETIME/1000 - if ( !base->speed ) - { + G_SpawnVector4("startRGBA", "1.0 0.85 0.15 0.75", (float *)&base->startRGBA); + // anglespeed - how fast it can track the player, entered in degrees per second, so we divide by FRAMETIME/1000 + if (!base->speed) { base->speed = 3.0f; - } - else - { - base->speed *= FRAMETIME/1000.0f; + } else { + base->speed *= FRAMETIME / 1000.0f; } base->e_UseFunc = useF_laser_arm_use; base->nextthink = level.time + FRAMETIME; - //Arm - //Does nothing, not solid, gets removed when head explodes - G_SetOrigin( arm, base->s.origin ); + // Arm + // Does nothing, not solid, gets removed when head explodes + G_SetOrigin(arm, base->s.origin); gi.linkentity(arm); - G_SetAngles( arm, armAngles ); -// bolt_head_to_arm( arm, head, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_SetAngles(arm, armAngles); + // bolt_head_to_arm( arm, head, LARM_FOFS, LARM_ROFS, LARM_UOFS ); arm->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_arm.md3"); - //Head - //Fires when enemy detected, animates, can be blown up - //Need to normalize the headAngles pitch for the clamping later - if ( headAngles[0] < -180 ) - { + // Head + // Fires when enemy detected, animates, can be blown up + // Need to normalize the headAngles pitch for the clamping later + if (headAngles[0] < -180) { headAngles[0] += 360; - } - else if ( headAngles[0] > 180 ) - { + } else if (headAngles[0] > 180) { headAngles[0] -= 360; } - G_SetAngles( head, headAngles ); + G_SetAngles(head, headAngles); head->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_head.md3"); head->s.eType = ET_GENERAL; -// head->svFlags |= SVF_BROADCAST;// Broadcast to all clients - VectorSet( head->mins, -8, -8, -8 ); - VectorSet( head->maxs, 8, 8, 8 ); + // head->svFlags |= SVF_BROADCAST;// Broadcast to all clients + VectorSet(head->mins, -8, -8, -8); + VectorSet(head->maxs, 8, 8, 8); head->contents = CONTENTS_BODY; gi.linkentity(head); - //dmg - if ( !base->damage ) - { + // dmg + if (!base->damage) { head->damage = 5; - } - else - { + } else { head->damage = base->damage; } base->damage = 0; - //lifespan of beam - if ( !base->wait ) - { + // lifespan of beam + if (!base->wait) { head->wait = 3000; - } - else - { + } else { head->wait = base->wait * 1000; } base->wait = 0; - //Precache firing and explode sounds + // Precache firing and explode sounds G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); G_SoundIndex("sound/chars/l_arm/fire.wav"); G_SoundIndex("sound/chars/l_arm/move.wav"); - //Link them up + // Link them up base->lastEnemy = arm; arm->lastEnemy = head; head->owner = arm; @@ -1379,8 +1190,7 @@ void laser_arm_start (gentity_t *base) head->alt_fire = qfalse; // Don't do damage until told to } -void SP_laser_arm (gentity_t *base) -{ +void SP_laser_arm(gentity_t *base) { base->e_ThinkFunc = thinkF_laser_arm_start; base->nextthink = level.time + START_TIME_LINK_ENTS; } @@ -1389,46 +1199,41 @@ void SP_laser_arm (gentity_t *base) // PERSONAL ASSAULT SENTRY //-------------------------- -#define PAS_DAMAGE 2 +#define PAS_DAMAGE 2 //----------------------------------------------------------------------------- -void pas_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void pas_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { self->nextthink = 0; // turn off and do nothing self->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { self->nextthink = level.time + 50; self->e_ThinkFunc = thinkF_pas_think; } } //---------------------------------------------------------------- -void pas_fire( gentity_t *ent ) +void pas_fire(gentity_t *ent) //---------------------------------------------------------------- { - vec3_t fwd, org; - mdxaBone_t boltMatrix; + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->torsoBolt, - &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->torsoBolt, &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); - G_PlayEffect( "turret/muzzle_flash", org, fwd ); + G_PlayEffect("turret/muzzle_flash", org, fwd); - gentity_t *bolt; + gentity_t *bolt; bolt = G_Spawn(); @@ -1439,181 +1244,157 @@ void pas_fire( gentity_t *ent ) bolt->s.weapon = WP_TURRET; bolt->owner = ent; bolt->damage = PAS_DAMAGE; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; bolt->methodOfDeath = MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - VectorSet( bolt->maxs, 1, 1, 1 ); - VectorScale( bolt->maxs, -1, bolt->mins ); + VectorSet(bolt->maxs, 1, 1, 1); + VectorScale(bolt->maxs, -1, bolt->mins); bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( org, bolt->s.pos.trBase ); - VectorScale( fwd, 900, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( org, bolt->currentOrigin); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(org, bolt->s.pos.trBase); + VectorScale(fwd, 900, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(org, bolt->currentOrigin); } //----------------------------------------------------- -static qboolean pas_find_enemies( gentity_t *self ) +static qboolean pas_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target; - - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + qboolean found = qfalse; + int count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target; + + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - G_Sound(self, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + G_Sound(self, G_SoundIndex("sound/chars/turret/ping.wav")); self->painDebounceTime = level.time + 1000; } } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Getting the "eye" here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->currentAngles, self->s.origin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->currentAngles, self->s.origin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client->playerTeam == self->noDamageTeam ) - { + if (target->client->playerTeam == self->noDamageTeam) { // A bot we don't want to shoot continue; } - if ( !gi.inPVS( org2, target->currentOrigin )) - { + if (!gi.inPVS(org2, target->currentOrigin)) { continue; } - if ( target->client ) - { - VectorCopy( target->client->renderInfo.eyePoint, org ); + if (target->client) { + VectorCopy(target->client->renderInfo.eyePoint, org); org[2] -= 15; - } - else - { - VectorCopy( target->currentOrigin, org ); + } else { + VectorCopy(target->currentOrigin, org); } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( target->s.number ) // don't do this for the player + if (target->s.number) // don't do this for the player { - G_StartFlee( target, self, self->currentOrigin, AEL_DANGER, 3000, 5000 ); + G_StartFlee(target, self, self->currentOrigin, AEL_DANGER, 3000, 5000); } - if ( enemyDist < bestDist )// all things equal, keep current + if (enemyDist < bestDist) // all things equal, keep current { - if ( self->attackDebounceTime + 2000 < level.time ) - { + if (self->attackDebounceTime + 2000 < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/startup.wav")); // Wind up turrets for a bit self->attackDebounceTime = level.time + 900 + Q_flrand(0.0f, 1.0f) * 200; } - G_SetEnemy( self, target ); + G_SetEnemy(self, target); bestDist = enemyDist; found = qtrue; } } } - if ( found && VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + if (found && VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } return found; } //--------------------------------- -void pas_adjust_enemy( gentity_t *ent ) +void pas_adjust_enemy(gentity_t *ent) //--------------------------------- { qboolean keep = qtrue; - if ( ent->enemy->health <= 0 ) - { + if (ent->enemy->health <= 0) { keep = qfalse; - } - else// if ( Q_flrand(0.0f, 1.0f) > 0.5f ) + } else // if ( Q_flrand(0.0f, 1.0f) > 0.5f ) { // do a trace every now and then. - mdxaBone_t boltMatrix; - vec3_t org, org2; + mdxaBone_t boltMatrix; + vec3_t org, org2; // Getting the "eye" here - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->torsoBolt, - &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->torsoBolt, &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->renderInfo.eyePoint, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->renderInfo.eyePoint, org); org[2] -= 15; - } - else - { - VectorCopy( ent->enemy->currentOrigin, org ); + } else { + VectorCopy(ent->enemy->currentOrigin, org); } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( tr.allsolid || tr.startsolid || tr.entityNum != ent->enemy->s.number ) - { + if (tr.allsolid || tr.startsolid || tr.entityNum != ent->enemy->s.number) { // trace failed keep = qfalse; } } - if ( keep ) - { + if (keep) { ent->bounceCount = level.time + 500 + Q_flrand(0.0f, 1.0f) * 150; - } - else if ( ent->bounceCount < level.time ) // don't ping pong on and off + } else if (ent->bounceCount < level.time) // don't ping pong on and off { ent->enemy = NULL; // shut-down sound - G_Sound( ent, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(ent, G_SoundIndex("sound/chars/turret/shutdown.wav")); // make turret play ping sound for 5 seconds ent->aimDebounceTime = level.time + 5000; @@ -1621,138 +1402,112 @@ void pas_adjust_enemy( gentity_t *ent ) } //--------------------------------- -void pas_think( gentity_t *ent ) +void pas_think(gentity_t *ent) //--------------------------------- { - if ( !ent->damage ) - { + if (!ent->damage) { // let us do our animation, then we are good to go in terms of pounding the crap out of enemies. ent->damage = 1; - gi.G2API_SetBoneAnimIndex( &ent->ghoul2[ent->playerModel], ent->rootBone, 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&ent->ghoul2[ent->playerModel], ent->rootBone, 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, -1, -1); ent->nextthink = level.time + 1200; return; } - if ( !ent->count ) - { + if (!ent->count) { // turrets that have no ammo may as well do nothing return; } ent->nextthink = level.time + FRAMETIME; - if ( ent->enemy ) - { + if (ent->enemy) { // make sure that the enemy is still valid - pas_adjust_enemy( ent ); + pas_adjust_enemy(ent); } - if ( !ent->enemy ) - { - pas_find_enemies( ent ); + if (!ent->enemy) { + pas_find_enemies(ent); } - qboolean moved = qfalse; - float diffYaw = 0.0f, diffPitch = 0.0f; - vec3_t enemyDir, org; - vec3_t frontAngles, backAngles; - vec3_t desiredAngles; + qboolean moved = qfalse; + float diffYaw = 0.0f, diffPitch = 0.0f; + vec3_t enemyDir, org; + vec3_t frontAngles, backAngles; + vec3_t desiredAngles; - ent->speed = AngleNormalize360( ent->speed ); - ent->random = AngleNormalize360( ent->random ); + ent->speed = AngleNormalize360(ent->speed); + ent->random = AngleNormalize360(ent->random); - if ( ent->enemy ) - { + if (ent->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->renderInfo.eyePoint, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->renderInfo.eyePoint, org); org[2] -= 40; - } - else - { - VectorCopy( ent->enemy->currentOrigin, org ); + } else { + VectorCopy(ent->enemy->currentOrigin, org); } - VectorSubtract( org, ent->currentOrigin, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, ent->currentOrigin, enemyDir); + vectoangles(enemyDir, desiredAngles); - diffYaw = AngleSubtract( ent->speed, desiredAngles[YAW] ); - diffPitch = AngleSubtract( ent->random, desiredAngles[PITCH] ); - } - else - { + diffYaw = AngleSubtract(ent->speed, desiredAngles[YAW]); + diffPitch = AngleSubtract(ent->random, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one - diffYaw = sin( level.time * 0.0001f + ent->count ) * 2.0f; + diffYaw = sin(level.time * 0.0001f + ent->count) * 2.0f; } - if ( fabs(diffYaw) > 0.25f ) - { + if (fabs(diffYaw) > 0.25f) { moved = qtrue; - if ( fabs(diffYaw) > 10.0f ) - { + if (fabs(diffYaw) > 10.0f) { // cap max speed ent->speed += (diffYaw > 0.0f) ? -10.0f : 10.0f; - } - else - { + } else { // small enough ent->speed -= diffYaw; } } - - if ( fabs(diffPitch) > 0.25f ) - { + if (fabs(diffPitch) > 0.25f) { moved = qtrue; - if ( fabs(diffPitch) > 4.0f ) - { + if (fabs(diffPitch) > 4.0f) { // cap max speed ent->random += (diffPitch > 0.0f) ? -4.0f : 4.0f; - } - else - { + } else { // small enough ent->random -= diffPitch; } } // the bone axes are messed up, so hence some dumbness here - VectorSet( frontAngles, -ent->random, 0.0f, 0.0f ); - VectorSet( backAngles, 0.0f, 0.0f, ent->speed - ent->s.angles[YAW] ); - - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_barrel", frontAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL,100,cg.time); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_gback", frontAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL,100,cg.time); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_hinge", backAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL,100,cg.time); - - if ( moved ) - { - //ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); - } - else - { + VectorSet(frontAngles, -ent->random, 0.0f, 0.0f); + VectorSet(backAngles, 0.0f, 0.0f, ent->speed - ent->s.angles[YAW]); + + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_barrel", frontAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL, 100, + cg.time); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_gback", frontAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL, 100, + cg.time); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_hinge", backAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, + cg.time); + + if (moved) { + // ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); + } else { ent->s.loopSound = 0; } - if ( ent->enemy && ent->attackDebounceTime < level.time && Q_flrand(0.0f, 1.0f) > 0.3f ) - { + if (ent->enemy && ent->attackDebounceTime < level.time && Q_flrand(0.0f, 1.0f) > 0.3f) { ent->count--; - if ( ent->count ) - { - pas_fire( ent ); - ent->fly_sound_debounce_time = level.time;//used as lastShotTime - } - else - { + if (ent->count) { + pas_fire(ent); + ent->fly_sound_debounce_time = level.time; // used as lastShotTime + } else { ent->nextthink = 0; - G_Sound( ent, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(ent, G_SoundIndex("sound/chars/turret/shutdown.wav")); } } } @@ -1781,36 +1536,34 @@ personal assault sentry, like the ones you can carry in your inventory */ //--------------------------------- -void SP_PAS( gentity_t *base ) +void SP_PAS(gentity_t *base) //--------------------------------- { base->classname = "PAS"; - G_SetOrigin( base, base->s.origin ); - G_SetAngles( base, base->s.angles ); + G_SetOrigin(base, base->s.origin); + G_SetAngles(base, base->s.angles); base->speed = base->s.angles[YAW]; - base->s.modelindex = G_ModelIndex( "models/items/psgun.glm" ); - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/items/psgun.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/items/psgun.glm"); + base->playerModel = gi.G2API_InitGhoul2Model(base->ghoul2, "models/items/psgun.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 30.0f; - VectorSet( base->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(base->s.modelScale, 1.0f, 1.0f, 1.0f); - base->rootBone = gi.G2API_GetBoneIndex( &base->ghoul2[base->playerModel], "model_root", qtrue ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); + base->rootBone = gi.G2API_GetBoneIndex(&base->ghoul2[base->playerModel], "model_root", qtrue); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); base->s.eType = ET_GENERAL; - if ( !base->radius ) - { + if (!base->radius) { base->radius = 512; } - if ( base->count == 0 ) - { + if (base->count == 0) { // give ammo base->count = 150; } @@ -1819,29 +1572,28 @@ void SP_PAS( gentity_t *base ) base->damage = 0; // start animation flag - base->contents = CONTENTS_SHOTCLIP|CONTENTS_CORPSE;//for certain traces - VectorSet( base->mins, -8, -8, 0 ); - VectorSet( base->maxs, 8, 8, 18 ); + base->contents = CONTENTS_SHOTCLIP | CONTENTS_CORPSE; // for certain traces + VectorSet(base->mins, -8, -8, 0); + VectorSet(base->maxs, 8, 8, 18); - if ( !(base->spawnflags & 1 )) // START_OFF + if (!(base->spawnflags & 1)) // START_OFF { base->nextthink = level.time + 1000; // we aren't starting off, so start working right away base->e_ThinkFunc = thinkF_pas_think; } // Set up our explosion effect for the ExplodeDeath code.... - base->fxID = G_EffectIndex( "turret/explode" ); - G_EffectIndex( "sparks/spark_exp_nosnd" ); + base->fxID = G_EffectIndex("turret/explode"); + G_EffectIndex("sparks/spark_exp_nosnd"); - if ( !base->health ) - { + if (!base->health) { base->health = 50; } base->max_health = base->health; base->takedamage = qtrue; base->e_PainFunc = painF_TurretPain; - base->e_DieFunc = dieF_turret_die; + base->e_DieFunc = dieF_turret_die; // hack this flag on so that when it calls the turret die code, it will orient the effect up // HACK @@ -1849,70 +1601,66 @@ void SP_PAS( gentity_t *base ) base->spawnflags |= 2; // Use this for our missile effect - RegisterItem( FindItemForWeapon( WP_TURRET )); + RegisterItem(FindItemForWeapon(WP_TURRET)); base->s.weapon = WP_TURRET; base->svFlags |= SVF_NONNPC_ENEMY; base->noDamageTeam = TEAM_NEUTRAL; - if ( base->team && base->team[0] ) - { - base->noDamageTeam = (team_t)GetIDForString( TeamTable, base->team ); + if (base->team && base->team[0]) { + base->noDamageTeam = (team_t)GetIDForString(TeamTable, base->team); base->team = NULL; } - gi.linkentity( base ); + gi.linkentity(base); } //------------------------------------------------------------------------ -qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t angs ) +qboolean place_portable_assault_sentry(gentity_t *self, vec3_t origin, vec3_t angs) //------------------------------------------------------------------------ { - vec3_t fwd, pos; - vec3_t mins, maxs; - trace_t tr; - gentity_t *pas; + vec3_t fwd, pos; + vec3_t mins, maxs; + trace_t tr; + gentity_t *pas; - VectorSet( maxs, 9, 9, 0 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 9, 9, 0); + VectorScale(maxs, -1, mins); angs[PITCH] = 0; angs[ROLL] = 0; - AngleVectors( angs, fwd, NULL, NULL ); + AngleVectors(angs, fwd, NULL, NULL); // and move a consistent distance away from us so we don't have the dumb thing spawning inside of us. - VectorMA( origin, 30, fwd, pos ); - gi.trace( &tr, origin, NULL, NULL, pos, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + VectorMA(origin, 30, fwd, pos); + gi.trace(&tr, origin, NULL, NULL, pos, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); // find the ground tr.endpos[2] += 20; - VectorCopy( tr.endpos, pos ); + VectorCopy(tr.endpos, pos); pos[2] -= 64; - gi.trace( &tr, tr.endpos, mins, maxs, pos, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, tr.endpos, mins, maxs, pos, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); // check for a decent surface, meaning mostly flat...should probably also check surface parms so we don't set us down on lava or something. - if ( !tr.startsolid && !tr.allsolid && tr.fraction < 1.0f && tr.plane.normal[2] > 0.9f && tr.entityNum >= ENTITYNUM_WORLD ) - { + if (!tr.startsolid && !tr.allsolid && tr.fraction < 1.0f && tr.plane.normal[2] > 0.9f && tr.entityNum >= ENTITYNUM_WORLD) { // Then spawn us if it seems cool. pas = G_Spawn(); - if ( pas ) - { - VectorCopy( tr.endpos, pas->s.origin ); - SP_PAS( pas ); + if (pas) { + VectorCopy(tr.endpos, pas->s.origin); + SP_PAS(pas); pas->contents |= CONTENTS_PLAYERCLIP; // player placed ones can block players but not npcs pas->e_UseFunc = useF_NULL; // placeable ones never need to be used // we don't hurt us or anyone who belongs to the same team as us. - if ( self->client ) - { + if (self->client) { pas->noDamageTeam = self->client->playerTeam; } - G_Sound( self, G_SoundIndex( "sound/player/use_sentry" )); + G_Sound(self, G_SoundIndex("sound/player/use_sentry")); pas->activator = self; return qtrue; } @@ -1920,123 +1668,106 @@ qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t a return qfalse; } - //------------- // ION CANNON //------------- - //---------------------------------------- -void ion_cannon_think( gentity_t *self ) +void ion_cannon_think(gentity_t *self) //---------------------------------------- { - if ( self->spawnflags & 2 ) - { - if ( self->count ) - { + if (self->spawnflags & 2) { + if (self->count) { // still have bursts left, so keep going self->count--; - } - else - { + } else { // done with burst, so wait delay amount, plus a random bit - self->nextthink = level.time + ( self->delay + Q_flrand(-1.0f, 1.0f) * self->random ); - self->count = Q_irand(0,5); // 0-5 bursts + self->nextthink = level.time + (self->delay + Q_flrand(-1.0f, 1.0f) * self->random); + self->count = Q_irand(0, 5); // 0-5 bursts // Not firing this time return; } } - if ( self->fxID ) - { - vec3_t fwd, org; - mdxaBone_t boltMatrix; + if (self->fxID) { + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->s.angles, self->s.origin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->s.angles, self->s.origin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); - G_PlayEffect( self->fxID, org, fwd ); + G_PlayEffect(self->fxID, org, fwd); } - if ( self->target2 ) - { + if (self->target2) { // If we have a target2 fire it off in sync with our gun firing - G_UseTargets2( self, self, self->target2 ); + G_UseTargets2(self, self, self->target2); } - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 0, 8, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 0, 8, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1); self->nextthink = level.time + self->wait + Q_flrand(-1.0f, 1.0f) * self->random; } //---------------------------------------------------------------------------------------------- -void ion_cannon_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) +void ion_cannon_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) //---------------------------------------------------------------------------------------------- { vec3_t org; // dead, so nuke the ghoul model and put in the damage md3 version - if ( self->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->playerModel ); + if (self->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->playerModel); } self->s.modelindex = self->s.modelindex2; self->s.modelindex2 = 0; - // Turn off the thinking of the base & use it's targets + // Turn off the thinking of the base & use it's targets self->e_ThinkFunc = thinkF_NULL; self->e_UseFunc = useF_NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } // clear my data - self->e_DieFunc = dieF_NULL; + self->e_DieFunc = dieF_NULL; self->takedamage = qfalse; self->health = 0; - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops self->s.loopSound = 0; // not solid anymore self->contents = 0; - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 20; - G_PlayEffect( "env/ion_cannon_explosion", org ); + G_PlayEffect("env/ion_cannon_explosion", org); - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, - attacker, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - gi.linkentity( self ); + gi.linkentity(self); } //---------------------------------------------------------------------------- -void ion_cannon_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void ion_cannon_use(gentity_t *self, gentity_t *other, gentity_t *activator) //---------------------------------------------------------------------------- { // toggle - if ( self->e_ThinkFunc == thinkF_NULL ) - { + if (self->e_ThinkFunc == thinkF_NULL) { // start thinking now self->e_ThinkFunc = thinkF_ion_cannon_think; self->nextthink = level.time + FRAMETIME; // fires right on being used - } - else - { + } else { self->e_ThinkFunc = thinkF_NULL; } } @@ -2061,141 +1792,122 @@ Huge ion cannon, like the ones at the rebel base on Hoth. target2 - What to use when it fires a shot. */ //----------------------------------------------------- -void SP_misc_ion_cannon( gentity_t *base ) +void SP_misc_ion_cannon(gentity_t *base) //----------------------------------------------------- { - G_SetAngles( base, base->s.angles ); + G_SetAngles(base, base->s.angles); G_SetOrigin(base, base->s.origin); - base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/ion_cannon.glm" ); - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/ion_cannon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/ion_cannon.glm"); + base->playerModel = + gi.G2API_InitGhoul2Model(base->ghoul2, "models/map_objects/imp_mine/ion_cannon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 320.0f; - VectorSet( base->s.modelScale, 2.0f, 2.0f, 2.0f ); + VectorSet(base->s.modelScale, 2.0f, 2.0f, 2.0f); - base->rootBone = gi.G2API_GetBoneIndex( &base->ghoul2[base->playerModel], "model_root", qtrue ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + base->rootBone = gi.G2API_GetBoneIndex(&base->ghoul2[base->playerModel], "model_root", qtrue); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); // register damage model - base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/ion_cannon_damage.md3" ); + base->s.modelindex2 = G_ModelIndex("models/map_objects/imp_mine/ion_cannon_damage.md3"); base->e_UseFunc = useF_ion_cannon_use; // How quickly to fire - if ( base->wait == 0.0f ) - { + if (base->wait == 0.0f) { base->wait = 1500.0f; - } - else if ( base->wait < 500.0f ) - { + } else if (base->wait < 500.0f) { base->wait = 500.0f; } - if ( base->random == 0.0f ) - { + if (base->random == 0.0f) { base->random = 400.0f; } - if ( base->delay == 0 ) - { + if (base->delay == 0) { base->delay = 6000; - } - else if ( base->delay < 1000 ) - { + } else if (base->delay < 1000) { base->delay = 1000; } // we only take damage from a heavy weapon class missile base->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; - if ( base->spawnflags & 4 )//shielded + if (base->spawnflags & 4) // shielded { - base->flags |= FL_SHIELDED; //technically, this would only take damage from a lightsaber, but the other flag just above would cancel that out too. + base->flags |= FL_SHIELDED; // technically, this would only take damage from a lightsaber, but the other flag just above would cancel that out too. } - G_SpawnInt( "health", "2000", &base->health ); + G_SpawnInt("health", "2000", &base->health); base->e_DieFunc = dieF_ion_cannon_die; base->takedamage = qtrue; // Start Off? - if ( base->spawnflags & 1 ) - { + if (base->spawnflags & 1) { base->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { // start thinking now, otherwise, we'll wait until we are used base->e_ThinkFunc = thinkF_ion_cannon_think; base->nextthink = level.time + base->wait + Q_flrand(-1.0f, 1.0f) * base->random; } // Bursts? - if ( base->spawnflags & 2 ) - { - base->count = Q_irand(0,5); // 0-5 bursts + if (base->spawnflags & 2) { + base->count = Q_irand(0, 5); // 0-5 bursts } // precache - base->fxID = G_EffectIndex( "env/ion_cannon" ); + base->fxID = G_EffectIndex("env/ion_cannon"); // Set up our explosion effect for the ExplodeDeath code.... - G_EffectIndex( "env/ion_cannon_explosion" ); + G_EffectIndex("env/ion_cannon_explosion"); base->contents = CONTENTS_BODY; - VectorSet( base->mins, -141.0f, -148.0f, 0.0f ); - VectorSet( base->maxs, 142.0f, 135.0f, 245.0f ); + VectorSet(base->mins, -141.0f, -148.0f, 0.0f); + VectorSet(base->maxs, 142.0f, 135.0f, 245.0f); - gi.linkentity( base ); + gi.linkentity(base); } - //----------------------------------------------------- -void spotlight_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->e_ThinkFunc == thinkF_NULL ) - { +void spotlight_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->e_ThinkFunc == thinkF_NULL) { // start thinking now, otherwise, we'll wait until we are used self->e_ThinkFunc = thinkF_spotlight_think; self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->e_ThinkFunc = thinkF_NULL; self->s.eFlags &= ~EF_ALT_FIRING; } } //----------------------------------------------------- -void spotlight_think( gentity_t *ent ) -{ - vec3_t dir, end; - trace_t tr; +void spotlight_think(gentity_t *ent) { + vec3_t dir, end; + trace_t tr; // dumb hack flag so that we can draw an interpolated light cone cgame side. ent->s.eFlags |= EF_ALT_FIRING; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.apos.trBase ); + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.apos.trBase); ent->s.apos.trType = TR_INTERPOLATE; - VectorMA( ent->currentOrigin, 2048, dir, end ); // just pick some max trace distance - gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID, (EG2_Collision)0, 0 ); + VectorMA(ent->currentOrigin, 2048, dir, end); // just pick some max trace distance + gi.trace(&tr, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID, (EG2_Collision)0, 0); ent->radius = tr.fraction * 2048.0f; - if ( tr.fraction < 1 ) - { - if ( DistanceSquared( tr.endpos, g_entities[0].currentOrigin ) < 140 * 140 ) - { + if (tr.fraction < 1) { + if (DistanceSquared(tr.endpos, g_entities[0].currentOrigin) < 140 * 140) { // hit player--use target2 - G_UseTargets2( ent, &g_entities[0], ent->target2 ); + G_UseTargets2(ent, &g_entities[0], ent->target2); #ifndef FINAL_BUILD - if ( g_developer->integer == PRINT_DEVELOPER ) - { - Com_Printf( S_COLOR_MAGENTA "Spotlight hit player at time: %d!!!\n", level.time ); + if (g_developer->integer == PRINT_DEVELOPER) { + Com_Printf(S_COLOR_MAGENTA "Spotlight hit player at time: %d!!!\n", level.time); } #endif } @@ -2205,29 +1917,24 @@ void spotlight_think( gentity_t *ent ) } //----------------------------------------------------- -void spotlight_link( gentity_t *ent ) -{ +void spotlight_link(gentity_t *ent) { gentity_t *target = 0; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - Com_Printf( S_COLOR_RED "ERROR: spotlight_link: bogus target %s\n", ent->target ); - G_FreeEntity( ent ); + if (!target) { + Com_Printf(S_COLOR_RED "ERROR: spotlight_link: bogus target %s\n", ent->target); + G_FreeEntity(ent); return; } ent->enemy = target; // Start Off? - if ( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { ent->e_ThinkFunc = thinkF_NULL; ent->s.eFlags &= ~EF_ALT_FIRING; - } - else - { + } else { // start thinking now, otherwise, we'll wait until we are used ent->e_ThinkFunc = thinkF_spotlight_think; ent->nextthink = level.time + FRAMETIME; @@ -2247,25 +1954,24 @@ Uses its target2 when it detects the player */ //----------------------------------------------------- -void SP_misc_spotlight( gentity_t *base ) +void SP_misc_spotlight(gentity_t *base) //----------------------------------------------------- { - if ( !base->target ) - { - Com_Printf( S_COLOR_RED "ERROR: misc_spotlight must have a target\n" ); - G_FreeEntity( base ); + if (!base->target) { + Com_Printf(S_COLOR_RED "ERROR: misc_spotlight must have a target\n"); + G_FreeEntity(base); return; } - G_SetAngles( base, base->s.angles ); - G_SetOrigin( base, base->s.origin ); + G_SetAngles(base, base->s.angles); + G_SetOrigin(base, base->s.origin); - base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/spotlight.md3" ); + base->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/spotlight.md3"); - G_SpawnInt( "health", "300", &base->health ); + G_SpawnInt("health", "300", &base->health); // Set up our lightcone effect, though we will have it draw cgame side so it looks better - G_EffectIndex( "env/light_cone" ); + G_EffectIndex("env/light_cone"); base->contents = CONTENTS_BODY; base->e_UseFunc = useF_spotlight_use; @@ -2274,7 +1980,7 @@ void SP_misc_spotlight( gentity_t *base ) base->e_ThinkFunc = thinkF_spotlight_link; base->nextthink = level.time + 100; - gi.linkentity( base ); + gi.linkentity(base); } /*QUAKED misc_panel_turret (0 0 1) (-8 -8 -12) (8 8 16) HEALTH @@ -2295,20 +2001,19 @@ Creates a turret that, when the player uses a panel, takes control of this turre heatlh - how much heatlh the thing has, (default 200) only works if HEALTH is checked, otherwise it can't be destroyed. */ -extern gentity_t *player; -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +extern gentity_t *player; +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void panel_turret_shoot( gentity_t *self, vec3_t org, vec3_t dir) -{ - gentity_t *missile = CreateMissile( org, dir, self->speed, 10000, self ); +void panel_turret_shoot(gentity_t *self, vec3_t org, vec3_t dir) { + gentity_t *missile = CreateMissile(org, dir, self->speed, 10000, self); missile->classname = "b_proj"; missile->s.weapon = WP_TIE_FIGHTER; - VectorSet( missile->maxs, 9, 9, 9 ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, 9, 9, 9); + VectorScale(missile->maxs, -1, missile->mins); missile->bounceCount = 0; @@ -2317,105 +2022,92 @@ void panel_turret_shoot( gentity_t *self, vec3_t org, vec3_t dir) missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - G_SoundOnEnt( self, CHAN_AUTO, "sound/movers/objects/ladygun_fire" ); + G_SoundOnEnt(self, CHAN_AUTO, "sound/movers/objects/ladygun_fire"); - VectorMA( org, 32, dir, org ); + VectorMA(org, 32, dir, org); org[2] -= 4; - G_PlayEffect( "ships/imp_blastermuzzleflash", org, dir ); + G_PlayEffect("ships/imp_blastermuzzleflash", org, dir); } //----------------------------------------- -void misc_panel_turret_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - if ( self->target3 ) - { - G_UseTargets2( self, player, self->target3 ); +void misc_panel_turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (self->target3) { + G_UseTargets2(self, player, self->target3); } // FIXME: might need some other kind of logic or functionality in here?? - G_UseTargets2( self, player, self->target2 ); - G_ClearViewEntity( player ); + G_UseTargets2(self, player, self->target2); + G_ClearViewEntity(player); cg.overrides.active &= ~CG_OVERRIDE_FOV; cg.overrides.fov = 0; } //----------------------------------------- -void panel_turret_think( gentity_t *self ) -{ +void panel_turret_think(gentity_t *self) { // Ensure that I am the viewEntity - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - { + if (player && player->client && player->client->ps.viewEntity == self->s.number) { usercmd_t *ucmd = &player->client->usercmd; // We are the viewEnt so update our new viewangles based on the sum of our start angles and the ucmd angles - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { // convert our base angle to a short, add with the usercmd.angle ( a short ), then switch use back to a real angle - self->s.apos.trBase[i] = AngleNormalize180( SHORT2ANGLE( ucmd->angles[i] + ANGLE2SHORT( self->s.angles[i] ) + self->pos3[i] )); + self->s.apos.trBase[i] = AngleNormalize180(SHORT2ANGLE(ucmd->angles[i] + ANGLE2SHORT(self->s.angles[i]) + self->pos3[i])); } // Only clamp if we have a PITCH clamp - if ( self->random != 0.0f ) + if (self->random != 0.0f) // Angle clamping -- PITCH { - if ( self->s.apos.trBase[PITCH] > self->random ) // random is PITCH + if (self->s.apos.trBase[PITCH] > self->random) // random is PITCH { - self->pos3[PITCH] += ANGLE2SHORT( AngleNormalize180( self->random - self->s.apos.trBase[PITCH])); + self->pos3[PITCH] += ANGLE2SHORT(AngleNormalize180(self->random - self->s.apos.trBase[PITCH])); self->s.apos.trBase[PITCH] = self->random; - } - else if ( self->s.apos.trBase[PITCH] < -self->random ) - { - self->pos3[PITCH] -= ANGLE2SHORT( AngleNormalize180( self->random + self->s.apos.trBase[PITCH])); + } else if (self->s.apos.trBase[PITCH] < -self->random) { + self->pos3[PITCH] -= ANGLE2SHORT(AngleNormalize180(self->random + self->s.apos.trBase[PITCH])); self->s.apos.trBase[PITCH] = -self->random; } } // Only clamp if we have a YAW clamp - if ( self->radius != 0.0f ) - { - float yawDif = AngleSubtract( self->s.apos.trBase[YAW], self->s.angles[YAW] ); + if (self->radius != 0.0f) { + float yawDif = AngleSubtract(self->s.apos.trBase[YAW], self->s.angles[YAW]); // Angle clamping -- YAW - if ( yawDif > self->radius ) // radius is YAW + if (yawDif > self->radius) // radius is YAW { - self->pos3[YAW] += ANGLE2SHORT( self->radius - yawDif ); - self->s.apos.trBase[YAW] = AngleNormalize180( self->s.angles[YAW] + self->radius ); - } - else if ( yawDif < -self->radius ) // radius is YAW + self->pos3[YAW] += ANGLE2SHORT(self->radius - yawDif); + self->s.apos.trBase[YAW] = AngleNormalize180(self->s.angles[YAW] + self->radius); + } else if (yawDif < -self->radius) // radius is YAW { - self->pos3[YAW] -= ANGLE2SHORT( self->radius + yawDif ); - self->s.apos.trBase[YAW] = AngleNormalize180( self->s.angles[YAW] - self->radius ); + self->pos3[YAW] -= ANGLE2SHORT(self->radius + yawDif); + self->s.apos.trBase[YAW] = AngleNormalize180(self->s.angles[YAW] - self->radius); } } // Let cgame interpolation smooth out the angle changes self->s.apos.trType = TR_INTERPOLATE; - self->s.pos.trType = TR_INTERPOLATE; // not really moving, but this fixes an interpolation bug in cg_ents. + self->s.pos.trType = TR_INTERPOLATE; // not really moving, but this fixes an interpolation bug in cg_ents. // Check for backing out of turret - if ( ( self->useDebounceTime < level.time ) && ((ucmd->buttons & BUTTON_USE) || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove) ) - { + if ((self->useDebounceTime < level.time) && ((ucmd->buttons & BUTTON_USE) || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove)) { self->useDebounceTime = level.time + 200; - G_UseTargets2( self, player, self->target2 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); + G_UseTargets2(self, player, self->target2); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); cg.overrides.active &= ~CG_OVERRIDE_FOV; cg.overrides.fov = 0; - if ( ucmd->upmove > 0 ) - {//stop player from doing anything for a half second after + if (ucmd->upmove > 0) { // stop player from doing anything for a half second after player->aimDebounceTime = level.time + 500; } // can be drawn -// self->s.eFlags &= ~EF_NODRAW; - } - else - { + // self->s.eFlags &= ~EF_NODRAW; + } else { // don't draw me when being looked through -// self->s.eFlags |= EF_NODRAW; -// self->s.modelindex = 0; + // self->s.eFlags |= EF_NODRAW; + // self->s.modelindex = 0; // we only need to think when we are being used self->nextthink = level.time + 50; @@ -2424,17 +2116,15 @@ void panel_turret_think( gentity_t *self ) cg.overrides.fov = 90; } - if ( ucmd->buttons & BUTTON_ATTACK || ucmd->buttons & BUTTON_ALT_ATTACK ) - { - if ( self->attackDebounceTime < level.time ) - { + if (ucmd->buttons & BUTTON_ATTACK || ucmd->buttons & BUTTON_ALT_ATTACK) { + if (self->attackDebounceTime < level.time) { vec3_t dir, pt; - AngleVectors( self->s.apos.trBase, dir, NULL, NULL ); + AngleVectors(self->s.apos.trBase, dir, NULL, NULL); - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] -= 4; - panel_turret_shoot( self, pt, dir ); + panel_turret_shoot(self, pt, dir); self->attackDebounceTime = level.time + self->delay; } @@ -2443,84 +2133,80 @@ void panel_turret_think( gentity_t *self ) } //----------------------------------------- -void panel_turret_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void panel_turret_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // really only usable by the player - if ( !activator || !activator->client || activator->s.number ) - { + if (!activator || !activator->client || activator->s.number) { return; } - if ( self->useDebounceTime > level.time ) - { + if (self->useDebounceTime > level.time) { // can't use it again right away. return; } - if ( self->spawnflags & 1 ) // health...presumably the lady luck gun + if (self->spawnflags & 1) // health...presumably the lady luck gun { - G_Sound( self, G_SoundIndex( "sound/movers/objects/ladygun_on" )); + G_Sound(self, G_SoundIndex("sound/movers/objects/ladygun_on")); } self->useDebounceTime = level.time + 200; // Compensating for the difference between the players view at the time of use and the start angles that the gun object has - self->pos3[PITCH] = -activator->client->usercmd.angles[PITCH]; - self->pos3[YAW] = -activator->client->usercmd.angles[YAW]; - self->pos3[ROLL] = 0; + self->pos3[PITCH] = -activator->client->usercmd.angles[PITCH]; + self->pos3[YAW] = -activator->client->usercmd.angles[YAW]; + self->pos3[ROLL] = 0; // set me as view entity - G_UseTargets2( self, activator, self->target ); - G_SetViewEntity( activator, self ); + G_UseTargets2(self, activator, self->target); + G_SetViewEntity(activator, self); - G_Sound( activator, self->soundPos1 ); + G_Sound(activator, self->soundPos1); self->e_ThinkFunc = thinkF_panel_turret_think; -// panel_turret_think( self ); + // panel_turret_think( self ); self->nextthink = level.time + 150; } //----------------------------------------- -void SP_misc_panel_turret( gentity_t *self ) -{ - G_SpawnFloat( "radius", "90", &self->radius ); // yaw - G_SpawnFloat( "random", "60", &self->random ); // pitch - G_SpawnFloat( "speed" , "3000", &self->speed ); - G_SpawnInt( "delay", "200", &self->delay ); - G_SpawnInt( "damage", "50", &self->damage ); +void SP_misc_panel_turret(gentity_t *self) { + G_SpawnFloat("radius", "90", &self->radius); // yaw + G_SpawnFloat("random", "60", &self->random); // pitch + G_SpawnFloat("speed", "3000", &self->speed); + G_SpawnInt("delay", "200", &self->delay); + G_SpawnInt("damage", "50", &self->damage); - VectorSet( self->pos3, 0.0f, 0.0f, 0.0f ); + VectorSet(self->pos3, 0.0f, 0.0f, 0.0f); - if ( self->spawnflags & 1 ) // heatlh + if (self->spawnflags & 1) // heatlh { self->takedamage = qtrue; self->contents = CONTENTS_SHOTCLIP; - G_SpawnInt( "health", "200", &self->health ); + G_SpawnInt("health", "200", &self->health); self->max_health = self->health; self->dflags |= DAMAGE_CUSTOM_HUD; // dumb, but we draw a custom hud - G_SoundIndex( "sound/movers/objects/ladygun_on" ); + G_SoundIndex("sound/movers/objects/ladygun_on"); } - self->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/ladyluck_gun.md3" ); + self->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/ladyluck_gun.md3"); - self->soundPos1 = G_SoundIndex( "sound/movers/camera_on.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/camera_off.mp3" ); + self->soundPos1 = G_SoundIndex("sound/movers/camera_on.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/camera_off.mp3"); - G_SoundIndex( "sound/movers/objects/ladygun_fire" ); + G_SoundIndex("sound/movers/objects/ladygun_fire"); G_EffectIndex("ships/imp_blastermuzzleflash"); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); - VectorSet( self->mins, -8, -8, -12 ); - VectorSet( self->maxs, 8, 8, 0 ); + VectorSet(self->mins, -8, -8, -12); + VectorSet(self->maxs, 8, 8, 0); self->contents = CONTENTS_SOLID; self->s.weapon = WP_TURRET; - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); - gi.linkentity( self ); + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); + gi.linkentity(self); self->e_UseFunc = useF_panel_turret_use; self->e_DieFunc = dieF_misc_panel_turret_die; diff --git a/code/game/g_usable.cpp b/code/game/g_usable.cpp index 318b2464a4..90f92a2590 100644 --- a/code/game/g_usable.cpp +++ b/code/game/g_usable.cpp @@ -23,132 +23,105 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" -extern void InitMover( gentity_t *ent ); - -extern gentity_t *G_TestEntityPosition( gentity_t *ent ); -void func_wait_return_solid( gentity_t *self ) -{ - //once a frame, see if it's clear. - self->clipmask = CONTENTS_BODY;//|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; - if ( !(self->spawnflags&16) || G_TestEntityPosition( self ) == NULL ) - { - gi.SetBrushModel( self, self->model ); - VectorCopy( self->currentOrigin, self->pos1 ); - InitMover( self ); +extern void InitMover(gentity_t *ent); + +extern gentity_t *G_TestEntityPosition(gentity_t *ent); +void func_wait_return_solid(gentity_t *self) { + // once a frame, see if it's clear. + self->clipmask = CONTENTS_BODY; //|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + if (!(self->spawnflags & 16) || G_TestEntityPosition(self) == NULL) { + gi.SetBrushModel(self, self->model); + VectorCopy(self->currentOrigin, self->pos1); + InitMover(self); /* VectorCopy( self->s.origin, self->s.pos.trBase ); VectorCopy( self->s.origin, self->currentOrigin ); */ - //if we moved, we want the *current* origin, not our start origin! - VectorCopy( self->currentOrigin, self->s.pos.trBase ); - gi.linkentity( self ); + // if we moved, we want the *current* origin, not our start origin! + VectorCopy(self->currentOrigin, self->s.pos.trBase); + gi.linkentity(self); self->svFlags &= ~SVF_NOCLIENT; self->s.eFlags &= ~EF_NODRAW; self->e_UseFunc = useF_func_usable_use; self->clipmask = 0; - if ( self->target2 && self->target2[0] ) - { - G_UseTargets2( self, self->activator, self->target2 ); + if (self->target2 && self->target2[0]) { + G_UseTargets2(self, self->activator, self->target2); } - if ( self->s.eFlags & EF_ANIM_ONCE ) - {//Start our anim + if (self->s.eFlags & EF_ANIM_ONCE) { // Start our anim self->s.frame = 0; } - //NOTE: be sure to reset the brushmodel before doing this or else CONTENTS_OPAQUE may not be on when you call this - if ( !(self->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( self, qfalse ); + // NOTE: be sure to reset the brushmodel before doing this or else CONTENTS_OPAQUE may not be on when you call this + if (!(self->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(self, qfalse); } - } - else - { + } else { self->clipmask = 0; self->e_ThinkFunc = thinkF_func_wait_return_solid; self->nextthink = level.time + FRAMETIME; } } -void func_usable_think( gentity_t *self ) -{ - if ( self->spawnflags & 8 ) - { - self->svFlags |= SVF_PLAYER_USABLE; //Replace the usable flag +void func_usable_think(gentity_t *self) { + if (self->spawnflags & 8) { + self->svFlags |= SVF_PLAYER_USABLE; // Replace the usable flag self->e_UseFunc = useF_func_usable_use; self->e_ThinkFunc = thinkF_NULL; } } -qboolean G_EntIsRemovableUsable( int entNum ) -{ +qboolean G_EntIsRemovableUsable(int entNum) { gentity_t *ent = &g_entities[entNum]; - if ( ent->classname && !Q_stricmp( "func_usable", ent->classname ) ) - { - if ( !(ent->s.eFlags&EF_SHADER_ANIM) && !(ent->spawnflags&8) && ent->targetname ) - {//not just a shader-animator and not ALWAYS_ON, so it must be removable somehow + if (ent->classname && !Q_stricmp("func_usable", ent->classname)) { + if (!(ent->s.eFlags & EF_SHADER_ANIM) && !(ent->spawnflags & 8) && + ent->targetname) { // not just a shader-animator and not ALWAYS_ON, so it must be removable somehow return qtrue; } } return qfalse; } -void func_usable_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{//Toggle on and off - if ( other == activator ) - {//directly used by use button trace - if ( (self->spawnflags&32) ) - {//only usable by NPCs - if ( activator->NPC == NULL ) - {//Not an NPC +void func_usable_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle on and off + if (other == activator) { // directly used by use button trace + if ((self->spawnflags & 32)) { // only usable by NPCs + if (activator->NPC == NULL) { // Not an NPC return; } } } - G_ActivateBehavior( self, BSET_USE ); - if ( self->s.eFlags & EF_SHADER_ANIM ) - {//animate shader when used - self->s.frame++;//inc frame - if ( self->s.frame > self->endFrame ) - {//wrap around + G_ActivateBehavior(self, BSET_USE); + if (self->s.eFlags & EF_SHADER_ANIM) { // animate shader when used + self->s.frame++; // inc frame + if (self->s.frame > self->endFrame) { // wrap around self->s.frame = 0; } - if ( self->target && self->target[0] ) - { - G_UseTargets( self, activator ); + if (self->target && self->target[0]) { + G_UseTargets(self, activator); } - } - else if ( self->spawnflags & 8 ) - {//ALWAYS_ON - //Remove the ability to use the entity directly + } else if (self->spawnflags & 8) { // ALWAYS_ON + // Remove the ability to use the entity directly self->svFlags &= ~SVF_PLAYER_USABLE; - //also remove ability to call any use func at all! + // also remove ability to call any use func at all! self->e_UseFunc = useF_NULL; - if(self->target && self->target[0]) - { + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - if ( self->wait ) - { + if (self->wait) { self->e_ThinkFunc = thinkF_func_usable_think; - self->nextthink = level.time + ( self->wait * 1000 ); + self->nextthink = level.time + (self->wait * 1000); } return; - } - else if ( !self->count ) - {//become solid again + } else if (!self->count) { // become solid again self->count = 1; self->activator = activator; - func_wait_return_solid( self ); - } - else - { - //NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! - if ( !(self->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( self, qtrue ); + func_wait_return_solid(self); + } else { + // NOTE: MUST do this BEFORE clearing contents, or you may not open the area portal!!! + if (!(self->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(self, qtrue); } self->s.solid = 0; self->contents = 0; @@ -157,8 +130,7 @@ void func_usable_use( gentity_t *self, gentity_t *other, gentity_t *activator ) self->s.eFlags |= EF_NODRAW; self->count = 0; - if(self->target && self->target[0]) - { + if (self->target && self->target[0]) { G_UseTargets(self, activator); } self->e_ThinkFunc = thinkF_NULL; @@ -166,22 +138,17 @@ void func_usable_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } } -void func_usable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod,int hitLoc) -{ - if ( self->paintarget ) - { - G_UseTargets2 (self, self->activator, self->paintarget); - } - else - { - GEntity_UseFunc( self, attacker, attacker ); +void func_usable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, const vec3_t point, int damage, int mod, int hitLoc) { + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); + } else { + GEntity_UseFunc(self, attacker, attacker); } } -void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc) -{ +void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { self->takedamage = qfalse; - GEntity_UseFunc( self, inflictor, attacker ); + GEntity_UseFunc(self, inflictor, attacker); } /*QUAKED func_usable (0 .5 .8) ? STARTOFF AUTOANIMATE ANIM_ONCE ALWAYS_ON BLOCKCHECK NPC_USE PLAYER_USE INACTIVE @@ -209,18 +176,16 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls "forcevisible" - When you turn on force sight (any level), you can see these draw through the entire level... */ -void SP_func_usable( gentity_t *self ) -{ - gi.SetBrushModel( self, self->model ); - InitMover( self ); - VectorCopy( self->s.origin, self->s.pos.trBase ); - VectorCopy( self->s.origin, self->currentOrigin ); - VectorCopy( self->s.origin, self->pos1 ); +void SP_func_usable(gentity_t *self) { + gi.SetBrushModel(self, self->model); + InitMover(self); + VectorCopy(self->s.origin, self->s.pos.trBase); + VectorCopy(self->s.origin, self->currentOrigin); + VectorCopy(self->s.origin, self->pos1); self->count = 1; - if (self->spawnflags & 1) - { - self->spawnContents = self->contents; // It Navs can temporarly turn it "on" + if (self->spawnflags & 1) { + self->spawnContents = self->contents; // It Navs can temporarly turn it "on" self->s.solid = 0; self->contents = 0; self->clipmask = 0; @@ -229,39 +194,33 @@ void SP_func_usable( gentity_t *self ) self->count = 0; } - if (self->spawnflags & 2) - { + if (self->spawnflags & 2) { self->s.eFlags |= EF_ANIM_ALLFAST; } - if (self->spawnflags & 4) - {//FIXME: need to be able to do change to something when it's done? Or not be usable until it's done? + if (self->spawnflags & 4) { // FIXME: need to be able to do change to something when it's done? Or not be usable until it's done? self->s.eFlags |= EF_ANIM_ONCE; } self->e_UseFunc = useF_func_usable_use; - if ( self->health ) - { + if (self->health) { self->takedamage = qtrue; self->e_DieFunc = dieF_func_usable_die; self->e_PainFunc = painF_func_usable_pain; } - if ( self->endFrame > 0 ) - { + if (self->endFrame > 0) { self->s.frame = self->startFrame = 0; self->s.eFlags |= EF_SHADER_ANIM; } - gi.linkentity (self); + gi.linkentity(self); int forceVisible = 0; - G_SpawnInt( "forcevisible", "0", &forceVisible ); - if ( forceVisible ) - {//can see these through walls with force sight, so must be broadcast - if ( VectorCompare( self->s.origin, vec3_origin ) ) - {//no origin brush + G_SpawnInt("forcevisible", "0", &forceVisible); + if (forceVisible) { // can see these through walls with force sight, so must be broadcast + if (VectorCompare(self->s.origin, vec3_origin)) { // no origin brush self->svFlags |= SVF_BROADCAST; } self->s.eFlags |= EF_FORCE_VISIBLE; diff --git a/code/game/g_utils.cpp b/code/game/g_utils.cpp index 9273fad527..efb1986f5a 100644 --- a/code/game/g_utils.cpp +++ b/code/game/g_utils.cpp @@ -31,10 +31,10 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -#define ACT_ACTIVE qtrue -#define ACT_INACTIVE qfalse -extern void NPC_UseResponse ( gentity_t *self, gentity_t *user, qboolean useWhenDone ); -extern qboolean PM_CrouchAnim( int anim ); +#define ACT_ACTIVE qtrue +#define ACT_INACTIVE qfalse +extern void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone); +extern qboolean PM_CrouchAnim(int anim); /* ========================================================================= @@ -49,34 +49,34 @@ G_FindConfigstringIndex ================ */ -extern void ForceTelepathy( gentity_t *self ); -int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ) { - int i; - char s[MAX_STRING_CHARS]; +extern void ForceTelepathy(gentity_t *self); +int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create) { + int i; + char s[MAX_STRING_CHARS]; - if ( !name || !name[0] ) { + if (!name || !name[0]) { return 0; } - for ( i=1 ; is.eventParm = fxID; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); - VectorCopy( fwd, tent->pos3 ); + VectorCopy(fwd, tent->pos3); // Assume angles, we'll do a cross product on the other end to finish up - MakeNormalVectors( fwd, tent->pos4, temp ); - gi.linkentity( tent ); + MakeNormalVectors(fwd, tent->pos4, temp); + gi.linkentity(tent); } // Play an effect at the origin of the specified entity //---------------------------- -void G_PlayEffect( int fxID, int entNum, const vec3_t fwd ) -{ - gentity_t *tent; - vec3_t temp; +void G_PlayEffect(int fxID, int entNum, const vec3_t fwd) { + gentity_t *tent; + vec3_t temp; - tent = G_TempEntity( g_entities[entNum].currentOrigin, EV_PLAY_EFFECT ); + tent = G_TempEntity(g_entities[entNum].currentOrigin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; tent->s.otherEntityNum = entNum; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); - VectorCopy( fwd, tent->pos3 ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); + VectorCopy(fwd, tent->pos3); // Assume angles, we'll do a cross product on the other end to finish up - MakeNormalVectors( fwd, tent->pos4, temp ); + MakeNormalVectors(fwd, tent->pos4, temp); } // Play an effect bolted onto the muzzle of the specified client //---------------------------- -void G_PlayEffect( const char *name, int clientNum ) -{ - gentity_t *tent; +void G_PlayEffect(const char *name, int clientNum) { + gentity_t *tent; - tent = G_TempEntity( g_entities[clientNum].currentOrigin, EV_PLAY_MUZZLE_EFFECT ); - tent->s.eventParm = G_EffectIndex( name ); + tent = G_TempEntity(g_entities[clientNum].currentOrigin, EV_PLAY_MUZZLE_EFFECT); + tent->s.eventParm = G_EffectIndex(name); tent->s.otherEntityNum = clientNum; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); } //----------------------------- -void G_PlayEffect( int fxID, const vec3_t origin, const vec3_t axis[3] ) -{ - gentity_t *tent; +void G_PlayEffect(int fxID, const vec3_t origin, const vec3_t axis[3]) { + gentity_t *tent; - tent = G_TempEntity( origin, EV_PLAY_EFFECT ); + tent = G_TempEntity(origin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); // We can just assume axis[2] from doing a cross product on these. - VectorCopy( axis[0], tent->pos3 ); - VectorCopy( axis[1], tent->pos4 ); + VectorCopy(axis[0], tent->pos3); + VectorCopy(axis[1], tent->pos4); } // Effect playing utilities - bolt an effect to a ghoul2 models bolton point //----------------------------- -void G_PlayEffect( int fxID, const int modelIndex, const int boltIndex, const int entNum, const vec3_t origin, int iLoopTime, qboolean isRelative )//iLoopTime 0 = not looping, 1 for infinite, else duration +void G_PlayEffect(int fxID, const int modelIndex, const int boltIndex, const int entNum, const vec3_t origin, int iLoopTime, + qboolean isRelative) // iLoopTime 0 = not looping, 1 for infinite, else duration { - gentity_t *tent; + gentity_t *tent; - tent = G_TempEntity( origin, EV_PLAY_EFFECT ); + tent = G_TempEntity(origin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; tent->s.loopSound = iLoopTime; tent->s.weapon = isRelative; - tent->svFlags |=SVF_BROADCAST; + tent->svFlags |= SVF_BROADCAST; gi.G2API_AttachEnt(&tent->s.boltInfo, &g_entities[entNum].ghoul2[modelIndex], boltIndex, entNum, modelIndex); } //----------------------------- -void G_PlayEffect( const char *name, const vec3_t origin ) -{ - vec3_t up = {0, 0, 1}; +void G_PlayEffect(const char *name, const vec3_t origin) { + vec3_t up = {0, 0, 1}; - G_PlayEffect( G_EffectIndex( name ), origin, up ); + G_PlayEffect(G_EffectIndex(name), origin, up); } -void G_PlayEffect( int fxID, const vec3_t origin ) -{ - vec3_t up = {0, 0, 1}; +void G_PlayEffect(int fxID, const vec3_t origin) { + vec3_t up = {0, 0, 1}; - G_PlayEffect( fxID, origin, up ); + G_PlayEffect(fxID, origin, up); } //----------------------------- -void G_PlayEffect( const char *name, const vec3_t origin, const vec3_t fwd ) -{ - G_PlayEffect( G_EffectIndex( name ), origin, fwd ); -} +void G_PlayEffect(const char *name, const vec3_t origin, const vec3_t fwd) { G_PlayEffect(G_EffectIndex(name), origin, fwd); } //----------------------------- -void G_PlayEffect( const char *name, const vec3_t origin, const vec3_t axis[3] ) -{ - G_PlayEffect( G_EffectIndex( name ), origin, axis ); -} +void G_PlayEffect(const char *name, const vec3_t origin, const vec3_t axis[3]) { G_PlayEffect(G_EffectIndex(name), origin, axis); } -void G_StopEffect( int fxID, const int modelIndex, const int boltIndex, const int entNum ) -{ - gentity_t *tent; +void G_StopEffect(int fxID, const int modelIndex, const int boltIndex, const int entNum) { + gentity_t *tent; - tent = G_TempEntity( g_entities[entNum].currentOrigin, EV_STOP_EFFECT ); + tent = G_TempEntity(g_entities[entNum].currentOrigin, EV_STOP_EFFECT); tent->s.eventParm = fxID; tent->svFlags |= SVF_BROADCAST; - gi.G2API_AttachEnt( &tent->s.boltInfo, &g_entities[entNum].ghoul2[modelIndex], boltIndex, entNum, modelIndex ); + gi.G2API_AttachEnt(&tent->s.boltInfo, &g_entities[entNum].ghoul2[modelIndex], boltIndex, entNum, modelIndex); } -void G_StopEffect(const char *name, const int modelIndex, const int boltIndex, const int entNum ) -{ - G_StopEffect( G_EffectIndex( name ), modelIndex, boltIndex, entNum ); +void G_StopEffect(const char *name, const int modelIndex, const int boltIndex, const int entNum) { + G_StopEffect(G_EffectIndex(name), modelIndex, boltIndex, entNum); } //===Bypass network for sounds on specific channels==================== -extern void cgi_S_StartSound( const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); -#include "../cgame/cg_media.h" //access to cgs -extern qboolean CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ); +extern void cgi_S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); +#include "../cgame/cg_media.h" //access to cgs +extern qboolean CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet); extern cvar_t *g_timescale; -//NOTE: Do NOT Try to use this before the cgame DLL is valid, it will NOT work! -void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ) -{ - int index = G_SoundIndex( (char *)soundPath ); +// NOTE: Do NOT Try to use this before the cgame DLL is valid, it will NOT work! +void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath) { + int index = G_SoundIndex((char *)soundPath); - if ( !ent ) - { + if (!ent) { return; } - if ( g_timescale->integer > 50 ) - {//Skip the sound! + if (g_timescale->integer > 50) { // Skip the sound! return; } - cgi_S_UpdateEntityPosition( ent->s.number, ent->currentOrigin ); - if ( cgs.sound_precache[ index ] ) - { - cgi_S_StartSound( NULL, ent->s.number, channel, cgs.sound_precache[ index ] ); - } - else - { - CG_TryPlayCustomSound( NULL, ent->s.number, channel, soundPath, -1 ); + cgi_S_UpdateEntityPosition(ent->s.number, ent->currentOrigin); + if (cgs.sound_precache[index]) { + cgi_S_StartSound(NULL, ent->s.number, channel, cgs.sound_precache[index]); + } else { + CG_TryPlayCustomSound(NULL, ent->s.number, channel, soundPath, -1); } } -void G_SoundIndexOnEnt( gentity_t *ent, soundChannel_t channel, int index ) -{ - if ( !ent ) - { +void G_SoundIndexOnEnt(gentity_t *ent, soundChannel_t channel, int index) { + if (!ent) { return; } - cgi_S_UpdateEntityPosition( ent->s.number, ent->currentOrigin ); - if ( cgs.sound_precache[ index ] ) - { - cgi_S_StartSound( NULL, ent->s.number, channel, cgs.sound_precache[ index ] ); + cgi_S_UpdateEntityPosition(ent->s.number, ent->currentOrigin); + if (cgs.sound_precache[index]) { + cgi_S_StartSound(NULL, ent->s.number, channel, cgs.sound_precache[index]); } } -extern cvar_t *g_skippingcin; -void G_SpeechEvent( gentity_t *self, int event ) -{ - if ( in_camera - && g_skippingcin - && g_skippingcin->integer ) - {//Skipping a cinematic, so skip NPC voice sounds... +extern cvar_t *g_skippingcin; +void G_SpeechEvent(gentity_t *self, int event) { + if (in_camera && g_skippingcin && g_skippingcin->integer) { // Skipping a cinematic, so skip NPC voice sounds... return; } - //update entity pos, too - cgi_S_UpdateEntityPosition( self->s.number, self->currentOrigin ); - switch ( event ) - { - case EV_ANGER1: //Say when acquire an enemy when didn't have one before + // update entity pos, too + cgi_S_UpdateEntityPosition(self->s.number, self->currentOrigin); + switch (event) { + case EV_ANGER1: // Say when acquire an enemy when didn't have one before case EV_ANGER2: case EV_ANGER3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT); break; - case EV_VICTORY1: //Say when killed an enemy + case EV_VICTORY1: // Say when killed an enemy case EV_VICTORY2: case EV_VICTORY3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT); break; - case EV_CONFUSE1: //Say when confused + case EV_CONFUSE1: // Say when confused case EV_CONFUSE2: case EV_CONFUSE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT); break; - case EV_PUSHED1: //Say when pushed + case EV_PUSHED1: // Say when pushed case EV_PUSHED2: case EV_PUSHED3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT); break; - case EV_CHOKE1: //Say when choking + case EV_CHOKE1: // Say when choking case EV_CHOKE2: case EV_CHOKE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT); break; - case EV_FFWARN: //Warn ally to stop shooting you - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT ); + case EV_FFWARN: // Warn ally to stop shooting you + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT); break; - case EV_FFTURN: //Turn on ally after being shot by them - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT ); + case EV_FFTURN: // Turn on ally after being shot by them + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT); break; - //extra sounds for ST + // extra sounds for ST case EV_CHASE1: case EV_CHASE2: case EV_CHASE3: - if ( !CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA ) ) - { - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", Q_irand(1,3)), CS_COMBAT ); + if (!CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA)) { + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", Q_irand(1, 3)), CS_COMBAT); } break; case EV_COVER1: @@ -352,99 +316,97 @@ void G_SpeechEvent( gentity_t *self, int event ) case EV_COVER3: case EV_COVER4: case EV_COVER5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA); break; case EV_DETECTED1: case EV_DETECTED2: case EV_DETECTED3: case EV_DETECTED4: case EV_DETECTED5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA); break; case EV_GIVEUP1: case EV_GIVEUP2: case EV_GIVEUP3: case EV_GIVEUP4: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA); break; case EV_LOOK1: case EV_LOOK2: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA); break; case EV_LOST1: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*lost1.wav", CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*lost1.wav", CS_EXTRA); break; case EV_OUTFLANK1: case EV_OUTFLANK2: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA); break; case EV_ESCAPING1: case EV_ESCAPING2: case EV_ESCAPING3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA); break; case EV_SIGHT1: case EV_SIGHT2: case EV_SIGHT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA); break; case EV_SOUND1: case EV_SOUND2: case EV_SOUND3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA); break; case EV_SUSPICIOUS1: case EV_SUSPICIOUS2: case EV_SUSPICIOUS3: case EV_SUSPICIOUS4: case EV_SUSPICIOUS5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA); break; - //extra sounds for Jedi + // extra sounds for Jedi case EV_COMBAT1: case EV_COMBAT2: case EV_COMBAT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI); break; case EV_JDETECTED1: case EV_JDETECTED2: case EV_JDETECTED3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI); break; case EV_TAUNT1: case EV_TAUNT2: case EV_TAUNT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI); break; case EV_JCHASE1: case EV_JCHASE2: case EV_JCHASE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI); break; case EV_JLOST1: case EV_JLOST2: case EV_JLOST3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI); break; case EV_DEFLECT1: case EV_DEFLECT2: case EV_DEFLECT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI); break; case EV_GLOAT1: case EV_GLOAT2: case EV_GLOAT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI); break; case EV_PUSHFAIL: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*pushfail.wav", CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*pushfail.wav", CS_JEDI); break; } } //===================================================================== - - /* ============= G_Find @@ -457,12 +419,10 @@ NULL will be returned if the end of the list is reached. ============= */ -gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match) -{ - char *s; +gentity_t *G_Find(gentity_t *from, int fieldofs, const char *match) { + char *s; - if(!match || !match[0]) - { + if (!match || !match[0]) { return NULL; } @@ -471,93 +431,80 @@ gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match) else from++; -// for ( ; from < &g_entities[globals.num_entities] ; from++) - int i=from-g_entities; - for ( ; i < globals.num_entities ; i++) - { -// if (!from->inuse) - if(!PInUse(i)) + // for ( ; from < &g_entities[globals.num_entities] ; from++) + int i = from - g_entities; + for (; i < globals.num_entities; i++) { + // if (!from->inuse) + if (!PInUse(i)) continue; - from=&g_entities[i]; - s = *(char **) ((byte *)from + fieldofs); + from = &g_entities[i]; + s = *(char **)((byte *)from + fieldofs); if (!s) continue; - if (!Q_stricmp (s, match)) + if (!Q_stricmp(s, match)) return from; } return NULL; } - /* ============ G_RadiusList - given an origin and a radius, return all entities that are in use that are within the list ============ */ -int G_RadiusList ( vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) -{ - float dist; - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - - if ( radius < 1 ) - { +int G_RadiusList(vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) { + float dist; + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); - radius *= radius; //square for the length squared below - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); + radius *= radius; // square for the length squared below + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if ((ent == ignore) || !(ent->inuse) || ent->takedamage != takeDamage) continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( origin[i] < ent->absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - origin[i]; - } else if ( origin[i] > ent->absmax[i] ) - { + } else if (origin[i] > ent->absmax[i]) { v[i] = origin[i] - ent->absmax[i]; - } else - { + } else { v[i] = 0; } } - dist = VectorLengthSquared( v ); - if ( dist >= radius ) - { + dist = VectorLengthSquared(v); + if (dist >= radius) { continue; } // ok, we are within the radius, add us to the incoming list ent_list[ent_count] = ent; ent_count++; - } // we are done, return how many we found - return(ent_count); + return (ent_count); } - /* ============= G_PickTarget @@ -565,23 +512,20 @@ G_PickTarget Selects a random entity from among the targets ============= */ -#define MAXCHOICES 32 +#define MAXCHOICES 32 -gentity_t *G_PickTarget (char *targetname) -{ - gentity_t *ent = NULL; - int num_choices = 0; - gentity_t *choice[MAXCHOICES]; +gentity_t *G_PickTarget(char *targetname) { + gentity_t *ent = NULL; + int num_choices = 0; + gentity_t *choice[MAXCHOICES]; - if (!targetname) - { + if (!targetname) { gi.Printf("G_PickTarget called with NULL targetname\n"); return NULL; } - while(1) - { - ent = G_Find (ent, FOFS(targetname), targetname); + while (1) { + ent = G_Find(ent, FOFS(targetname), targetname); if (!ent) break; choice[num_choices++] = ent; @@ -589,8 +533,7 @@ gentity_t *G_PickTarget (char *targetname) break; } - if (!num_choices) - { + if (!num_choices) { gi.Printf("G_PickTarget: target %s not found\n", targetname); return NULL; } @@ -598,45 +541,36 @@ gentity_t *G_PickTarget (char *targetname) return choice[rand() % num_choices]; } -void G_UseTargets2 (gentity_t *ent, gentity_t *activator, const char *string) -{ - gentity_t *t; +void G_UseTargets2(gentity_t *ent, gentity_t *activator, const char *string) { + gentity_t *t; -// -// fire targets -// - if (string) - { - if( !Q_stricmp( string, "self") ) - { + // + // fire targets + // + if (string) { + if (!Q_stricmp(string, "self")) { t = ent; - if (t->e_UseFunc != useF_NULL) // check can be omitted + if (t->e_UseFunc != useF_NULL) // check can be omitted { GEntity_UseFunc(t, ent, activator); } - if (!ent->inuse) - { + if (!ent->inuse) { gi.Printf("entity was removed while using targets\n"); return; } - } - else - { + } else { t = NULL; - while ( (t = G_Find (t, FOFS(targetname), (char *) string)) != NULL ) - { - if (t == ent) - { - // gi.Printf ("WARNING: Entity used itself.\n"); + while ((t = G_Find(t, FOFS(targetname), (char *)string)) != NULL) { + if (t == ent) { + // gi.Printf ("WARNING: Entity used itself.\n"); } - if (t->e_UseFunc != useF_NULL) // check can be omitted + if (t->e_UseFunc != useF_NULL) // check can be omitted { GEntity_UseFunc(t, ent, activator); } - if (!ent->inuse) - { + if (!ent->inuse) { gi.Printf("entity was removed while using targets\n"); return; } @@ -656,12 +590,11 @@ match (string)self.target and call their .use function ============================== */ -void G_UseTargets (gentity_t *ent, gentity_t *activator) -{ -// -// fire targets -// - G_UseTargets2 (ent, activator, ent->target); +void G_UseTargets(gentity_t *ent, gentity_t *activator) { + // + // fire targets + // + G_UseTargets2(ent, activator, ent->target); } /* @@ -672,21 +605,20 @@ This is just a convenience function for printing vectors ============= */ -char *vtos( const vec3_t v ) { - static int index; - static char str[8][32]; - char *s; +char *vtos(const vec3_t v) { + static int index; + static char str[8][32]; + char *s; // use an array so that multiple vtos won't collide s = str[index]; - index = (index + 1)&7; + index = (index + 1) & 7; - Com_sprintf (s, 32, "(%4.2f %4.2f %4.2f)", v[0], v[1], v[2]); + Com_sprintf(s, 32, "(%4.2f %4.2f %4.2f)", v[0], v[1], v[2]); return s; } - /* =============== G_SetMovedir @@ -697,31 +629,30 @@ Angles will be cleared, because it is being used to represent a direction instead of an orientation. =============== */ -void G_SetMovedir( vec3_t angles, vec3_t movedir ) { - static vec3_t VEC_UP = {0, -1, 0}; - static vec3_t MOVEDIR_UP = {0, 0, 1}; - static vec3_t VEC_DOWN = {0, -2, 0}; - static vec3_t MOVEDIR_DOWN = {0, 0, -1}; - - if ( VectorCompare (angles, VEC_UP) ) { - VectorCopy (MOVEDIR_UP, movedir); - } else if ( VectorCompare (angles, VEC_DOWN) ) { - VectorCopy (MOVEDIR_DOWN, movedir); +void G_SetMovedir(vec3_t angles, vec3_t movedir) { + static vec3_t VEC_UP = {0, -1, 0}; + static vec3_t MOVEDIR_UP = {0, 0, 1}; + static vec3_t VEC_DOWN = {0, -2, 0}; + static vec3_t MOVEDIR_DOWN = {0, 0, -1}; + + if (VectorCompare(angles, VEC_UP)) { + VectorCopy(MOVEDIR_UP, movedir); + } else if (VectorCompare(angles, VEC_DOWN)) { + VectorCopy(MOVEDIR_DOWN, movedir); } else { - AngleVectors (angles, movedir, NULL, NULL); + AngleVectors(angles, movedir, NULL, NULL); } - VectorClear( angles ); + VectorClear(angles); } - -float vectoyaw( const vec3_t vec ) { - float yaw; +float vectoyaw(const vec3_t vec) { + float yaw; if (vec[YAW] == 0 && vec[PITCH] == 0) { yaw = 0; } else { if (vec[PITCH]) { - yaw = ( atan2( vec[YAW], vec[PITCH]) * 180 / M_PI ); + yaw = (atan2(vec[YAW], vec[PITCH]) * 180 / M_PI); } else if (vec[YAW] > 0) { yaw = 90; } else { @@ -735,9 +666,7 @@ float vectoyaw( const vec3_t vec ) { return yaw; } - -void G_InitGentity( gentity_t *e, qboolean bFreeG2 ) -{ +void G_InitGentity(gentity_t *e, qboolean bFreeG2) { e->inuse = qtrue; SetInUse(e); e->m_iIcarusID = IIcarusInterface::ICARUS_INVALID; @@ -745,13 +674,12 @@ void G_InitGentity( gentity_t *e, qboolean bFreeG2 ) e->s.number = e - g_entities; // remove any ghoul2 models here in case we're reusing - if (bFreeG2 && e->ghoul2.IsValid()) - { + if (bFreeG2 && e->ghoul2.IsValid()) { gi.G2API_CleanGhoul2Models(e->ghoul2); } - //Navigational setups - e->waypoint = WAYPOINT_NONE; - e->lastWaypoint = WAYPOINT_NONE; + // Navigational setups + e->waypoint = WAYPOINT_NONE; + e->lastWaypoint = WAYPOINT_NONE; } /* @@ -769,91 +697,83 @@ instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ -gentity_t *G_Spawn( void ) -{ - int i, force; - gentity_t *e; +gentity_t *G_Spawn(void) { + int i, force; + gentity_t *e; - e = NULL; // shut up warning - i = 0; // shut up warning - for ( force = 0 ; force < 2 ; force++ ) - { + e = NULL; // shut up warning + i = 0; // shut up warning + for (force = 0; force < 2; force++) { // if we go through all entities and can't find one to free, // override the normal minimum times before use e = &g_entities[MAX_CLIENTS]; -// for ( i = MAX_CLIENTS ; iinuse ) -// { -// continue; -// } - for ( i = MAX_CLIENTS ; iinuse ) + // { + // continue; + // } + for (i = MAX_CLIENTS; i < globals.num_entities; i++) { + if (PInUse(i)) { continue; } - e=&g_entities[i]; + e = &g_entities[i]; // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy - if ( !force && e->freetime > 2000 && level.time - e->freetime < 1000 ) { + if (!force && e->freetime > 2000 && level.time - e->freetime < 1000) { continue; } // reuse this slot - G_InitGentity( e, qtrue ); + G_InitGentity(e, qtrue); return e; } - e=&g_entities[i]; - if ( i != ENTITYNUM_MAX_NORMAL ) - { + e = &g_entities[i]; + if (i != ENTITYNUM_MAX_NORMAL) { break; } } - if ( i == ENTITYNUM_MAX_NORMAL ) - { + if (i == ENTITYNUM_MAX_NORMAL) { -//#ifndef FINAL_BUILD + //#ifndef FINAL_BUILD e = &g_entities[0]; -//--------------Use this to dump directly to a file + //--------------Use this to dump directly to a file char buff[256]; FILE *fp; - fp = fopen( "c:/nofreeentities.txt", "w" ); - for ( i = 0 ; iclassname ) - { - sprintf( buff, "%d: %s\n", i, e->classname ); + fp = fopen("c:/nofreeentities.txt", "w"); + for (i = 0; i < globals.num_entities; i++, e++) { + if (e->classname) { + sprintf(buff, "%d: %s\n", i, e->classname); } - fputs( buff, fp ); + fputs(buff, fp); } - fclose( fp ); -/* -//---------------Or use this to dump to the console -- beware though, the console will fill quickly and you probably won't see the full list - for ( i = 0 ; iclassname ) - { - Com_Printf( "%d: %s\n", i, e->classname ); + fclose(fp); + /* + //---------------Or use this to dump to the console -- beware though, the console will fill quickly and you probably won't see the full list + for ( i = 0 ; iclassname ) + { + Com_Printf( "%d: %s\n", i, e->classname ); - } - } -*/ -//FINAL_BUILD - G_Error( "G_Spawn: no free entities" ); + } + } + */ + // FINAL_BUILD + G_Error("G_Spawn: no free entities"); } // open up a new slot globals.num_entities++; - G_InitGentity( e, qtrue ); + G_InitGentity(e, qtrue); return e; } -extern void Vehicle_Remove(gentity_t *ent); +extern void Vehicle_Remove(gentity_t *ent); /* ================= @@ -862,66 +782,61 @@ G_FreeEntity Marks the entity as free ================= */ -void G_FreeEntity( gentity_t *ed ) { - gi.unlinkentity (ed); // unlink from world +void G_FreeEntity(gentity_t *ed) { + gi.unlinkentity(ed); // unlink from world // Free the Game Element (the entity) and delete the Icarus ID. - Quake3Game()->FreeEntity( ed ); + Quake3Game()->FreeEntity(ed); /*if ( ed->neverFree ) { return; }*/ - if (ed->wayedge!=0) - { + if (ed->wayedge != 0) { NAV::WayEdgesNowClear(ed); } - // remove any ghoul2 models here gi.G2API_CleanGhoul2Models(ed->ghoul2); - if (ed->client && ed->client->NPC_class == CLASS_VEHICLE) - { + if (ed->client && ed->client->NPC_class == CLASS_VEHICLE) { Vehicle_Remove(ed); - if ( ed->m_pVehicle ) - { - gi.Free( ed->m_pVehicle ); + if (ed->m_pVehicle) { + gi.Free(ed->m_pVehicle); } - //CVehicleNPC *pVeh = static_cast< CVehicleNPC * >( ed->NPC ); - //delete pVeh; - //gi.Free((char*)ed->NPC-4);//crazy hack for class vtables + // CVehicleNPC *pVeh = static_cast< CVehicleNPC * >( ed->NPC ); + // delete pVeh; + // gi.Free((char*)ed->NPC-4);//crazy hack for class vtables } - //free this stuff now, rather than waiting until the level ends. - if (ed->NPC) - { + // free this stuff now, rather than waiting until the level ends. + if (ed->NPC) { gi.Free(ed->NPC); - if(ed->client->clientInfo.customBasicSoundDir && gi.bIsFromZone(ed->client->clientInfo.customBasicSoundDir, TAG_G_ALLOC)) { + if (ed->client->clientInfo.customBasicSoundDir && gi.bIsFromZone(ed->client->clientInfo.customBasicSoundDir, TAG_G_ALLOC)) { gi.Free(ed->client->clientInfo.customBasicSoundDir); } - if(ed->client->clientInfo.customCombatSoundDir) { + if (ed->client->clientInfo.customCombatSoundDir) { gi.Free(ed->client->clientInfo.customCombatSoundDir); } - if(ed->client->clientInfo.customExtraSoundDir) { + if (ed->client->clientInfo.customExtraSoundDir) { gi.Free(ed->client->clientInfo.customExtraSoundDir); } - if(ed->client->clientInfo.customJediSoundDir) { + if (ed->client->clientInfo.customJediSoundDir) { gi.Free(ed->client->clientInfo.customJediSoundDir); } - if(ed->client->ps.saber[0].name && gi.bIsFromZone(ed->client->ps.saber[0].name, TAG_G_ALLOC) ) { + if (ed->client->ps.saber[0].name && gi.bIsFromZone(ed->client->ps.saber[0].name, TAG_G_ALLOC)) { gi.Free(ed->client->ps.saber[0].name); } - if(ed->client->ps.saber[0].model && gi.bIsFromZone(ed->client->ps.saber[0].model, TAG_G_ALLOC) ) { + if (ed->client->ps.saber[0].model && gi.bIsFromZone(ed->client->ps.saber[0].model, TAG_G_ALLOC)) { gi.Free(ed->client->ps.saber[0].model); } - if(ed->client->ps.saber[1].name && gi.bIsFromZone(ed->client->ps.saber[1].name, TAG_G_ALLOC) ) { + if (ed->client->ps.saber[1].name && gi.bIsFromZone(ed->client->ps.saber[1].name, TAG_G_ALLOC)) { gi.Free(ed->client->ps.saber[1].name); } - if(ed->client->ps.saber[1].model && gi.bIsFromZone(ed->client->ps.saber[1].model, TAG_G_ALLOC) ) { - gi.Free(ed->client->ps.saber[1].model); + if (ed->client->ps.saber[1].model && gi.bIsFromZone(ed->client->ps.saber[1].model, TAG_G_ALLOC)) { + gi.Free(ed->client->ps.saber[1].model); } gi.Free(ed->client); @@ -940,7 +855,7 @@ void G_FreeEntity( gentity_t *ed ) { gi.Free(ed->NPC_type); } if (ed->classname && gi.bIsFromZone(ed->classname, TAG_G_ALLOC)) { - gi.Free(ed->classname ); + gi.Free(ed->classname); } if (ed->message && gi.bIsFromZone(ed->message, TAG_G_ALLOC)) { gi.Free(ed->message); @@ -949,7 +864,7 @@ void G_FreeEntity( gentity_t *ed ) { gi.Free(ed->model); } -//scripting + // scripting if (ed->script_targetname && gi.bIsFromZone(ed->script_targetname, TAG_G_ALLOC)) { gi.Free(ed->script_targetname); } @@ -959,21 +874,21 @@ void G_FreeEntity( gentity_t *ed ) { if (ed->paintarget && gi.bIsFromZone(ed->paintarget, TAG_G_ALLOC)) { gi.Free(ed->paintarget); } - if(ed->parms) { + if (ed->parms) { gi.Free(ed->parms); } -//Limbs - if (ed->target && gi.bIsFromZone(ed->target , TAG_G_ALLOC)) { + // Limbs + if (ed->target && gi.bIsFromZone(ed->target, TAG_G_ALLOC)) { gi.Free(ed->target); } - if (ed->target2 && gi.bIsFromZone(ed->target2 , TAG_G_ALLOC)) { + if (ed->target2 && gi.bIsFromZone(ed->target2, TAG_G_ALLOC)) { gi.Free(ed->target2); } - if (ed->target3 && gi.bIsFromZone(ed->target3 , TAG_G_ALLOC)) { + if (ed->target3 && gi.bIsFromZone(ed->target3, TAG_G_ALLOC)) { gi.Free(ed->target3); } - if (ed->target4 && gi.bIsFromZone(ed->target4 , TAG_G_ALLOC)) { + if (ed->target4 && gi.bIsFromZone(ed->target4, TAG_G_ALLOC)) { gi.Free(ed->target4); } if (ed->opentarget) { @@ -985,7 +900,7 @@ void G_FreeEntity( gentity_t *ed ) { // Free any associated timers TIMER_Clear(ed->s.number); - memset (ed, 0, sizeof(*ed)); + memset(ed, 0, sizeof(*ed)); ed->s.number = ENTITYNUM_NONE; ed->classname = "freed"; ed->freetime = level.time; @@ -1002,9 +917,9 @@ The origin will be snapped to save net bandwidth, so care must be taken if the origin is right on a surface (snap towards start vector first) ================= */ -gentity_t *G_TempEntity( const vec3_t origin, int event ) { - gentity_t *e; - vec3_t snapped; +gentity_t *G_TempEntity(const vec3_t origin, int event) { + gentity_t *e; + vec3_t snapped; e = G_Spawn(); e->s.eType = ET_EVENTS + event; @@ -1013,18 +928,16 @@ gentity_t *G_TempEntity( const vec3_t origin, int event ) { e->eventTime = level.time; e->freeAfterEvent = qtrue; - VectorCopy( origin, snapped ); - SnapVector( snapped ); // save network bandwidth - G_SetOrigin( e, snapped ); + VectorCopy(origin, snapped); + SnapVector(snapped); // save network bandwidth + G_SetOrigin(e, snapped); // find cluster for PVS - gi.linkentity( e ); + gi.linkentity(e); return e; } - - /* ============================================================================== @@ -1041,52 +954,43 @@ Kills all entities that would touch the proposed new positioning of ent. Ent should be unlinked before calling this! ================= */ -void G_KillBox (gentity_t *ent) { - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +void G_KillBox(gentity_t *ent) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; - VectorAdd( ent->client->ps.origin, ent->mins, mins ); - VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(ent->client->ps.origin, ent->mins, mins); + VectorAdd(ent->client->ps.origin, ent->maxs, maxs); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient ) { + if (!hit->client) { continue; } - if ( hit == ent ) { + if (hit == ent) { continue; } - if ( ent->s.number && hit->client->ps.stats[STAT_HEALTH] <= 0 ) - {//NPC + if (ent->s.number && hit->client->ps.stats[STAT_HEALTH] <= 0) { // NPC continue; } - if ( ent->s.number ) - {//NPC - if ( !(hit->contents&CONTENTS_BODY) ) - { + if (ent->s.number) { // NPC + if (!(hit->contents & CONTENTS_BODY)) { continue; } - } - else - {//player - if ( !(hit->contents & ent->contents) ) - { + } else { // player + if (!(hit->contents & ent->contents)) { continue; } } // nail it - G_Damage ( hit, ent, ent, NULL, NULL, - 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); + G_Damage(hit, ent, ent, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } - } //============================================================================== - /* =============== G_AddEvent @@ -1094,11 +998,11 @@ G_AddEvent Adds an event+parm and twiddles the event counter =============== */ -void G_AddEvent( gentity_t *ent, int event, int eventParm ) { - int bits; +void G_AddEvent(gentity_t *ent, int event, int eventParm) { + int bits; - if ( !event ) { - gi.Printf( "G_AddEvent: zero event added for entity %i\n", ent->s.number ); + if (!event) { + gi.Printf("G_AddEvent: zero event added for entity %i\n", ent->s.number); return; } @@ -1123,7 +1027,7 @@ void G_AddEvent( gentity_t *ent, int event, int eventParm ) { #endif // clients need to add the event in playerState_t instead of entityState_t - if ( !ent->s.number ) //only one client + if (!ent->s.number) // only one client { #if 0 bits = ent->client->ps.externalEvent & EV_EVENT_BITS; @@ -1132,38 +1036,32 @@ void G_AddEvent( gentity_t *ent, int event, int eventParm ) { ent->client->ps.externalEventParm = eventParm; ent->client->ps.externalEventTime = level.time; #endif - if ( eventParm > 255 ) - { - if ( event == EV_PAIN ) - {//must have cheated, in undying? + if (eventParm > 255) { + if (event == EV_PAIN) { // must have cheated, in undying? eventParm = 255; - } - else - { - assert( eventParm < 256 ); + } else { + assert(eventParm < 256); } } - AddEventToPlayerstate( event, eventParm, &ent->client->ps ); + AddEventToPlayerstate(event, eventParm, &ent->client->ps); } else { bits = ent->s.event & EV_EVENT_BITS; - bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS; + bits = (bits + EV_EVENT_BIT1) & EV_EVENT_BITS; ent->s.event = event | bits; ent->s.eventParm = eventParm; } ent->eventTime = level.time; } - /* ============= G_Sound ============= */ -void G_Sound( gentity_t *ent, int soundIndex ) -{ - gentity_t *te; +void G_Sound(gentity_t *ent, int soundIndex) { + gentity_t *te; - te = G_TempEntity( ent->currentOrigin, EV_GENERAL_SOUND ); + te = G_TempEntity(ent->currentOrigin, EV_GENERAL_SOUND); te->s.eventParm = soundIndex; } @@ -1172,14 +1070,12 @@ void G_Sound( gentity_t *ent, int soundIndex ) G_Sound ============= */ -void G_SoundAtSpot( vec3_t org, int soundIndex, qboolean broadcast ) -{ - gentity_t *te; +void G_SoundAtSpot(vec3_t org, int soundIndex, qboolean broadcast) { + gentity_t *te; - te = G_TempEntity( org, EV_GENERAL_SOUND ); + te = G_TempEntity(org, EV_GENERAL_SOUND); te->s.eventParm = soundIndex; - if ( broadcast ) - { + if (broadcast) { te->svFlags |= SVF_BROADCAST; } } @@ -1191,11 +1087,10 @@ G_SoundBroadcast Plays sound that can permeate PVS blockage ============= */ -void G_SoundBroadcast( gentity_t *ent, int soundIndex ) -{ - gentity_t *te; +void G_SoundBroadcast(gentity_t *ent, int soundIndex) { + gentity_t *te; - te = G_TempEntity( ent->currentOrigin, EV_GLOBAL_SOUND ); //full volume + te = G_TempEntity(ent->currentOrigin, EV_GLOBAL_SOUND); // full volume te->s.eventParm = soundIndex; te->svFlags |= SVF_BROADCAST; } @@ -1209,41 +1104,33 @@ G_SetOrigin Sets the pos trajectory for a fixed position ================ */ -void G_SetOrigin( gentity_t *ent, const vec3_t origin ) -{ - VectorCopy( origin, ent->s.pos.trBase ); - if(ent->client) - { - VectorCopy( origin, ent->client->ps.origin ); - VectorCopy( origin, ent->s.origin ); - } - else - { +void G_SetOrigin(gentity_t *ent, const vec3_t origin) { + VectorCopy(origin, ent->s.pos.trBase); + if (ent->client) { + VectorCopy(origin, ent->client->ps.origin); + VectorCopy(origin, ent->s.origin); + } else { ent->s.pos.trType = TR_STATIONARY; } ent->s.pos.trTime = 0; ent->s.pos.trDuration = 0; - VectorClear( ent->s.pos.trDelta ); + VectorClear(ent->s.pos.trDelta); - VectorCopy( origin, ent->currentOrigin ); + VectorCopy(origin, ent->currentOrigin); // clear waypoints - if( ent->client && ent->NPC ) - { + if (ent->client && ent->NPC) { ent->waypoint = 0; ent->lastWaypoint = 0; - if( NAV::HasPath( ent ) ) - { - NAV::ClearPath( ent ); + if (NAV::HasPath(ent)) { + NAV::ClearPath(ent); } } - } -qboolean G_CheckInSolidTeleport (const vec3_t& teleportPos, gentity_t *self) -{ - trace_t trace; - vec3_t end, mins; +qboolean G_CheckInSolidTeleport(const vec3_t &teleportPos, gentity_t *self) { + trace_t trace; + vec3_t end, mins; VectorCopy(teleportPos, end); end[2] += self->mins[2]; @@ -1251,18 +1138,16 @@ qboolean G_CheckInSolidTeleport (const vec3_t& teleportPos, gentity_t *self) mins[2] = 0; gi.trace(&trace, teleportPos, mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0); - if(trace.allsolid || trace.startsolid) - { + if (trace.allsolid || trace.startsolid) { return qtrue; } return qfalse; } //=============================================================================== -qboolean G_CheckInSolid (gentity_t *self, qboolean fix) -{ - trace_t trace; - vec3_t end, mins; +qboolean G_CheckInSolid(gentity_t *self, qboolean fix) { + trace_t trace; + vec3_t end, mins; VectorCopy(self->currentOrigin, end); end[2] += self->mins[2]; @@ -1270,20 +1155,18 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) mins[2] = 0; gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, self->clipmask, (EG2_Collision)0, 0); - if(trace.allsolid || trace.startsolid) - { + if (trace.allsolid || trace.startsolid) { return qtrue; } #ifdef _DEBUG - if(trace.fraction < 0.99999713) + if (trace.fraction < 0.99999713) #else - if(trace.fraction < 1.0) + if (trace.fraction < 1.0) #endif { - if(fix) - {//Put them at end of trace and check again - vec3_t neworg; + if (fix) { // Put them at end of trace and check again + vec3_t neworg; VectorCopy(trace.endpos, neworg); neworg[2] -= self->mins[2]; @@ -1291,9 +1174,7 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) gi.linkentity(self); return G_CheckInSolid(self, qfalse); - } - else - { + } else { return qtrue; } } @@ -1301,10 +1182,9 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) return qfalse; } -qboolean infront(gentity_t *from, gentity_t *to) -{ - vec3_t angles, dir, forward; - float dot; +qboolean infront(gentity_t *from, gentity_t *to) { + vec3_t angles, dir, forward; + float dot; angles[PITCH] = angles[ROLL] = 0; angles[YAW] = from->s.angles[YAW]; @@ -1314,105 +1194,84 @@ qboolean infront(gentity_t *from, gentity_t *to) VectorNormalize(dir); dot = DotProduct(forward, dir); - if(dot < 0.0f) - { + if (dot < 0.0f) { return qfalse; } return qtrue; } -void Svcmd_Use_f( void ) -{ - const char *cmd1 = gi.argv(1); +void Svcmd_Use_f(void) { + const char *cmd1 = gi.argv(1); - if ( !cmd1 || !cmd1[0] ) - { - //FIXME: warning message - gi.Printf( "'use' takes targetname of ent or 'list' (lists all usable ents)\n" ); + if (!cmd1 || !cmd1[0]) { + // FIXME: warning message + gi.Printf("'use' takes targetname of ent or 'list' (lists all usable ents)\n"); return; - } - else if ( !Q_stricmp("list", cmd1) ) - { - gentity_t *ent; + } else if (!Q_stricmp("list", cmd1)) { + gentity_t *ent; gi.Printf("Listing all usable entities:\n"); - for ( int i = 1; i < ENTITYNUM_WORLD; i++ ) - { - ent = &g_entities[i]; - if ( ent ) - { - if ( ent->targetname && ent->targetname[0] ) - { - if ( ent->e_UseFunc != useF_NULL ) - { - if ( ent->NPC ) - { - gi.Printf( "%s (NPC)\n", ent->targetname ); - } - else - { - gi.Printf( "%s\n", ent->targetname ); - } - } - } - } + for (int i = 1; i < ENTITYNUM_WORLD; i++) { + ent = &g_entities[i]; + if (ent) { + if (ent->targetname && ent->targetname[0]) { + if (ent->e_UseFunc != useF_NULL) { + if (ent->NPC) { + gi.Printf("%s (NPC)\n", ent->targetname); + } else { + gi.Printf("%s\n", ent->targetname); + } + } + } + } } gi.Printf("End of list.\n"); - } - else - { - G_UseTargets2( &g_entities[0], &g_entities[0], cmd1 ); + } else { + G_UseTargets2(&g_entities[0], &g_entities[0], cmd1); } } //====================================================== -void G_SetActiveState(char *targetstring, qboolean actState) -{ - gentity_t *target = NULL; - while( NULL != (target = G_Find(target, FOFS(targetname), targetstring)) ) - { - target->svFlags = actState ? (target->svFlags&~SVF_INACTIVE) : (target->svFlags|SVF_INACTIVE); +void G_SetActiveState(char *targetstring, qboolean actState) { + gentity_t *target = NULL; + while (NULL != (target = G_Find(target, FOFS(targetname), targetstring))) { + target->svFlags = actState ? (target->svFlags & ~SVF_INACTIVE) : (target->svFlags | SVF_INACTIVE); } } -void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_ACTIVE); } -void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_INACTIVE); } -//FIXME: make these apply to doors, etc too? +// FIXME: make these apply to doors, etc too? /*QUAKED target_activate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be usable/triggerable */ -void SP_target_activate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_activate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_activate_use; } /*QUAKED target_deactivate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be non-usable/triggerable */ -void SP_target_deactivate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_deactivate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_deactivate_use; } - //====================================================== /* @@ -1422,61 +1281,52 @@ ValidUseTarget Returns whether or not the targeted entity is useable ============== */ -qboolean ValidUseTarget( gentity_t *ent ) -{ - if ( ent->e_UseFunc == useF_NULL ) - { +qboolean ValidUseTarget(gentity_t *ent) { + if (ent->e_UseFunc == useF_NULL) { return qfalse; } - if ( ent->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (ent->svFlags & SVF_INACTIVE) { // set by target_deactivate return qfalse; } - if ( !(ent->svFlags & SVF_PLAYER_USABLE) ) - {//Check for flag that denotes BUTTON_USE useability + if (!(ent->svFlags & SVF_PLAYER_USABLE)) { // Check for flag that denotes BUTTON_USE useability return qfalse; } - //FIXME: This is only a temp fix.. - if ( !Q_strncmp( ent->classname, "trigger", 7) ) - { + // FIXME: This is only a temp fix.. + if (!Q_strncmp(ent->classname, "trigger", 7)) { return qfalse; } return qtrue; } -static void DebugTraceForNPC(gentity_t *ent) -{ - trace_t trace; - vec3_t src, dest, vf; +static void DebugTraceForNPC(gentity_t *ent) { + trace_t trace; + vec3_t src, dest, vf; - VectorCopy( ent->client->renderInfo.eyePoint, src ); + VectorCopy(ent->client->renderInfo.eyePoint, src); - AngleVectors( ent->client->ps.viewangles, vf, NULL, NULL );//ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically - //extend to find end of use trace - VectorMA( src, 4096, vf, dest ); + AngleVectors(ent->client->ps.viewangles, vf, NULL, NULL); // ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically + // extend to find end of use trace + VectorMA(src, 4096, vf, dest); - //Trace ahead to find a valid target - gi.trace( &trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, (EG2_Collision)0, 0 ); + // Trace ahead to find a valid target + gi.trace(&trace, src, vec3_origin, vec3_origin, dest, ent->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, (EG2_Collision)0, 0); - if (trace.fraction < 0.99f) - { - gentity_t *found = &g_entities[trace.entityNum]; + if (trace.fraction < 0.99f) { + gentity_t *found = &g_entities[trace.entityNum]; - if (found) - { + if (found) { const char *targetName = found->targetname; const char *className = found->classname; - if (targetName == 0) - { + if (targetName == 0) { targetName = ""; } - if (className == 0) - { + if (className == 0) { className = ""; } Com_Printf("found targetname '%s', classname '%s'\n", targetName, className); @@ -1484,83 +1334,59 @@ static void DebugTraceForNPC(gentity_t *ent) } } -static qboolean G_ValidActivateBehavior (gentity_t* self, int bset) -{ - if ( !self ) - { +static qboolean G_ValidActivateBehavior(gentity_t *self, int bset) { + if (!self) { return qfalse; } const char *bs_name = self->behaviorSet[bset]; - if( !(VALIDSTRING( bs_name )) ) - { + if (!(VALIDSTRING(bs_name))) { return qfalse; } return qtrue; } -static qboolean G_IsTriggerUsable(gentity_t* self, gentity_t* other) -{ - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +static qboolean G_IsTriggerUsable(gentity_t *self, gentity_t *other) { + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return qfalse; } - if( self->noDamageTeam ) - { - if ( other->client->playerTeam != self->noDamageTeam ) - { + if (self->noDamageTeam) { + if (other->client->playerTeam != self->noDamageTeam) { return qfalse; } } - - if ( self->spawnflags & 4 ) - {//USE_BUTTON - if ( !other->client ) - { + if (self->spawnflags & 4) { // USE_BUTTON + if (!other->client) { return qfalse; } - } - else - { + } else { return qfalse; } - if ( self->spawnflags & 2 ) - {//FACING - vec3_t forward; + if (self->spawnflags & 2) { // FACING + vec3_t forward; - if ( other->client ) - { - AngleVectors( other->client->ps.viewangles, forward, NULL, NULL ); - } - else - { - AngleVectors( other->currentAngles, forward, NULL, NULL ); + if (other->client) { + AngleVectors(other->client->ps.viewangles, forward, NULL, NULL); + } else { + AngleVectors(other->currentAngles, forward, NULL, NULL); } - if ( DotProduct( self->movedir, forward ) < 0.5 ) - {//Not Within 45 degrees + if (DotProduct(self->movedir, forward) < 0.5) { // Not Within 45 degrees return qfalse; } } - if ((!G_ValidActivateBehavior (self, BSET_USE) && !self->target) || - (self->target && - (Q_stricmp(self->target, "n") == 0 || - (Q_stricmp(self->target, "neveropen") == 0 || - (Q_stricmp(self->target, "run_gran_drop") == 0) || - (Q_stricmp(self->target, "speaker") == 0) || - (Q_stricmp(self->target, "locked") == 0) - )))) - { + if ((!G_ValidActivateBehavior(self, BSET_USE) && !self->target) || + (self->target && (Q_stricmp(self->target, "n") == 0 || (Q_stricmp(self->target, "neveropen") == 0 || (Q_stricmp(self->target, "run_gran_drop") == 0) || + (Q_stricmp(self->target, "speaker") == 0) || (Q_stricmp(self->target, "locked") == 0))))) { return qfalse; } - /* //NOTE: This doesn't stop you from using it, just delays the use action! if(self->delay && self->painDebounceTime < (level.time + self->delay) ) @@ -1572,46 +1398,44 @@ static qboolean G_IsTriggerUsable(gentity_t* self, gentity_t* other) return qtrue; } -static qboolean CanUseInfrontOfPartOfLevel(gentity_t* ent ) //originally from VV +static qboolean CanUseInfrontOfPartOfLevel(gentity_t *ent) // originally from VV { - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; - const vec3_t range = { 40, 40, 52 }; + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; + const vec3_t range = {40, 40, 52}; - if ( !ent->client ) { + if (!ent->client) { return qfalse; } - VectorSubtract( ent->client->ps.origin, range, mins ); - VectorAdd( ent->client->ps.origin, range, maxs ); + VectorSubtract(ent->client->ps.origin, range, mins); + VectorAdd(ent->client->ps.origin, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( ent->client->ps.origin, ent->mins, mins ); - VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); + VectorAdd(ent->client->ps.origin, ent->mins, mins); + VectorAdd(ent->client->ps.origin, ent->maxs, maxs); - for ( i=0 ; ie_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { + if ((hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL)) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } - if ( !gi.EntityContact( mins, maxs, hit ) ) { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } - if ( hit->e_TouchFunc != touchF_NULL ) { - switch (hit->e_TouchFunc ) - { + if (hit->e_TouchFunc != touchF_NULL) { + switch (hit->e_TouchFunc) { case touchF_Touch_Multi: - if (G_IsTriggerUsable(hit, ent)) - { + if (G_IsTriggerUsable(hit, ent)) { return qtrue; } continue; @@ -1624,118 +1448,91 @@ static qboolean CanUseInfrontOfPartOfLevel(gentity_t* ent ) //originally from VV return qfalse; } -#define USE_DISTANCE 64.0f -extern qboolean eweb_can_be_used( gentity_t *self, gentity_t *other, gentity_t *activator ); -qboolean CanUseInfrontOf(gentity_t *ent) -{ - gentity_t *target; - trace_t trace; - vec3_t src, dest, vf; +#define USE_DISTANCE 64.0f +extern qboolean eweb_can_be_used(gentity_t *self, gentity_t *other, gentity_t *activator); +qboolean CanUseInfrontOf(gentity_t *ent) { + gentity_t *target; + trace_t trace; + vec3_t src, dest, vf; - if ( ent->s.number && ent->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST -// GEntity_UseFunc( ent->activator, ent, ent ); + if (ent->s.number && ent->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + // GEntity_UseFunc( ent->activator, ent, ent ); return qfalse; } - if (ent->client->ps.viewEntity != ent->s.number) - { + if (ent->client->ps.viewEntity != ent->s.number) { ent = &g_entities[ent->client->ps.viewEntity]; - if ( !Q_stricmp( "misc_camera", ent->classname ) ) - { // we are in a camera + if (!Q_stricmp("misc_camera", ent->classname)) { // we are in a camera gentity_t *next = 0; - if ( ent->target2 != NULL ) - { - next = G_Find( NULL, FOFS(targetname), ent->target2 ); + if (ent->target2 != NULL) { + next = G_Find(NULL, FOFS(targetname), ent->target2); } - if ( next ) - {//found another one - if ( !Q_stricmp( "misc_camera", next->classname ) ) - {//make sure it's another camera + if (next) { // found another one + if (!Q_stricmp("misc_camera", next->classname)) { // make sure it's another camera return qtrue; } - } - else //if ( ent->health > 0 ) - {//I was the last (only?) one, clear out the viewentity + } else // if ( ent->health > 0 ) + { // I was the last (only?) one, clear out the viewentity return qfalse; } } } - if ( !ent->client ) { + if (!ent->client) { return qfalse; } + // FIXME: this does not match where the new accurate crosshair aims... + // cg.refdef.vieworg, basically + VectorCopy(ent->client->renderInfo.eyePoint, src); - //FIXME: this does not match where the new accurate crosshair aims... - //cg.refdef.vieworg, basically - VectorCopy( ent->client->renderInfo.eyePoint, src ); - - AngleVectors( ent->client->ps.viewangles, vf, NULL, NULL ); - //extend to find end of use trace - VectorMA( src, USE_DISTANCE, vf, dest ); + AngleVectors(ent->client->ps.viewangles, vf, NULL, NULL); + // extend to find end of use trace + VectorMA(src, USE_DISTANCE, vf, dest); - //Trace ahead to find a valid target - gi.trace( &trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE , G2_NOCOLLIDE, 10); + // Trace ahead to find a valid target + gi.trace(&trace, src, vec3_origin, vec3_origin, dest, ent->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, G2_NOCOLLIDE, 10); - if ( trace.fraction == 1.0f || trace.entityNum >= ENTITYNUM_WORLD ) - { + if (trace.fraction == 1.0f || trace.entityNum >= ENTITYNUM_WORLD) { return (CanUseInfrontOfPartOfLevel(ent)); } target = &g_entities[trace.entityNum]; - if ( target && target->client && target->client->NPC_class == CLASS_VEHICLE ) - { + if (target && target->client && target->client->NPC_class == CLASS_VEHICLE) { // Attempt to board this vehicle. return qtrue; } - //Check for a use command - if (ValidUseTarget( target )) { - if ( target->s.eType == ET_ITEM ) - {//item, see if we could actually pick it up - if ( (target->spawnflags&128/*ITMSF_USEPICKUP*/) ) - {//player has to be touching me and hit use to pick it up, so don't allow this - if ( !G_BoundsOverlap( target->absmin, target->absmax, ent->absmin, ent->absmax ) ) - {//not touching + // Check for a use command + if (ValidUseTarget(target)) { + if (target->s.eType == ET_ITEM) { // item, see if we could actually pick it up + if ((target->spawnflags & 128 /*ITMSF_USEPICKUP*/)) { // player has to be touching me and hit use to pick it up, so don't allow this + if (!G_BoundsOverlap(target->absmin, target->absmax, ent->absmin, ent->absmax)) { // not touching return qfalse; } } - if ( !BG_CanItemBeGrabbed( &target->s, &ent->client->ps ) ) - {//nope, so don't indicate that we can use it + if (!BG_CanItemBeGrabbed(&target->s, &ent->client->ps)) { // nope, so don't indicate that we can use it return qfalse; } - } - else if ( target->e_UseFunc == useF_misc_atst_use ) - {//drivable AT-ST from JK2 - if ( ent->client->ps.groundEntityNum != target->s.number ) - {//must be standing on it to use it + } else if (target->e_UseFunc == useF_misc_atst_use) { // drivable AT-ST from JK2 + if (ent->client->ps.groundEntityNum != target->s.number) { // must be standing on it to use it return qfalse; } - } - else if ( target->NPC!=NULL && target->health<=0 ) - { + } else if (target->NPC != NULL && target->health <= 0) { return qfalse; - } - else if ( target->e_UseFunc == useF_eweb_use ) - { - if ( !eweb_can_be_used( target, ent, ent ) ) - { + } else if (target->e_UseFunc == useF_eweb_use) { + if (!eweb_can_be_used(target, ent, ent)) { return qfalse; } } return qtrue; } - if ( target->client - && target->client->ps.pm_type < PM_DEAD - && target->NPC!=NULL - && target->client->playerTeam - && (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) - && !(target->NPC->scriptFlags&SCF_NO_RESPONSE) - && G_ValidActivateBehavior (target, BSET_USE)) - { + if (target->client && target->client->ps.pm_type < PM_DEAD && target->NPC != NULL && target->client->playerTeam && + (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) && + !(target->NPC->scriptFlags & SCF_NO_RESPONSE) && G_ValidActivateBehavior(target, BSET_USE)) { return qtrue; } @@ -1754,44 +1551,40 @@ Try and use an entity in the world, directly ahead of us ============== */ +void TryUse(gentity_t *ent) { + gentity_t *target; + trace_t trace; + vec3_t src, dest, vf; -void TryUse( gentity_t *ent ) -{ - gentity_t *target; - trace_t trace; - vec3_t src, dest, vf; - - if (ent->s.number == 0 && g_npcdebug->integer == 1) - { + if (ent->s.number == 0 && g_npcdebug->integer == 1) { DebugTraceForNPC(ent); } - if ( ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST - GEntity_UseFunc( ent->activator, ent, ent ); + if (ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + GEntity_UseFunc(ent->activator, ent, ent); return; } // TODO: turo-boost. -/* if ( ent->client->ps.vehicleIndex != VEHICLE_NONE ) - {//in a vehicle, use key makes you turbo-boost - return; - }*/ + /* if ( ent->client->ps.vehicleIndex != VEHICLE_NONE ) + {//in a vehicle, use key makes you turbo-boost + return; + }*/ - //FIXME: this does not match where the new accurate crosshair aims... - //cg.refdef.vieworg, basically - VectorCopy( ent->client->renderInfo.eyePoint, src ); + // FIXME: this does not match where the new accurate crosshair aims... + // cg.refdef.vieworg, basically + VectorCopy(ent->client->renderInfo.eyePoint, src); - AngleVectors( ent->client->ps.viewangles, vf, NULL, NULL );//ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically - //extend to find end of use trace - VectorMA( src, USE_DISTANCE, vf, dest ); + AngleVectors(ent->client->ps.viewangles, vf, NULL, NULL); // ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically + // extend to find end of use trace + VectorMA(src, USE_DISTANCE, vf, dest); - //Trace ahead to find a valid target - gi.trace( &trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_TERRAIN|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE , G2_NOCOLLIDE, 10); + // Trace ahead to find a valid target + gi.trace(&trace, src, vec3_origin, vec3_origin, dest, ent->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_TERRAIN | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, G2_NOCOLLIDE, 10); - if ( trace.fraction == 1.0f || trace.entityNum >= ENTITYNUM_WORLD ) - { - //TODO: Play a failure sound + if (trace.fraction == 1.0f || trace.entityNum >= ENTITYNUM_WORLD) { + // TODO: Play a failure sound /* if ( ent->s.number == 0 ) {//if nothing else, try the force telepathy power @@ -1803,36 +1596,29 @@ void TryUse( gentity_t *ent ) target = &g_entities[trace.entityNum]; - if ( target && target->client && target->client->NPC_class == CLASS_VEHICLE ) - { + if (target && target->client && target->client->NPC_class == CLASS_VEHICLE) { // Attempt to board this vehicle. - target->m_pVehicle->m_pVehicleInfo->Board( target->m_pVehicle, ent ); + target->m_pVehicle->m_pVehicleInfo->Board(target->m_pVehicle, ent); return; } - //Check for a use command - if ( ValidUseTarget( target ) ) - { - NPC_SetAnim( ent, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // Check for a use command + if (ValidUseTarget(target)) { + NPC_SetAnim(ent, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); /* if ( !VectorLengthSquared( ent->client->ps.velocity ) && !PM_CrouchAnim( ent->client->ps.legsAnim ) ) { NPC_SetAnim( ent, SETANIM_LEGS, BOTH_BUTTON_HOLD, SETANIM_FLAG_NORMAL|SETANIM_FLAG_HOLD ); } */ - //ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; - GEntity_UseFunc( target, ent, ent ); + // ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; + GEntity_UseFunc(target, ent, ent); return; - } - else if ( target->client - && target->client->ps.pm_type < PM_DEAD - && target->NPC!=NULL - && target->client->playerTeam - && (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) - && !(target->NPC->scriptFlags&SCF_NO_RESPONSE) ) - { - NPC_UseResponse ( target, ent, qfalse ); + } else if (target->client && target->client->ps.pm_type < PM_DEAD && target->NPC != NULL && target->client->playerTeam && + (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) && + !(target->NPC->scriptFlags & SCF_NO_RESPONSE)) { + NPC_UseResponse(target, ent, qfalse); return; } /* @@ -1844,48 +1630,39 @@ void TryUse( gentity_t *ent ) } extern int killPlayerTimer; -void G_ChangeMap (const char *mapname, const char *spawntarget, qboolean hub) -{ -// gi.Printf("Loading..."); - //ignore if player is dead +void G_ChangeMap(const char *mapname, const char *spawntarget, qboolean hub) { + // gi.Printf("Loading..."); + // ignore if player is dead if (g_entities[0].client->ps.pm_type == PM_DEAD) return; - if ( killPlayerTimer ) - {//can't go to next map if your allies have turned on you + if (killPlayerTimer) { // can't go to next map if your allies have turned on you return; } - if (mapname[0] == '+') //fire up the menu instead + if (mapname[0] == '+') // fire up the menu instead { - gi.SendConsoleCommand( va("uimenu %s\n", mapname+1) ); + gi.SendConsoleCommand(va("uimenu %s\n", mapname + 1)); gi.cvar_set("skippingCinematic", "0"); gi.cvar_set("timescale", "1"); return; } - if ( spawntarget == NULL ) { - spawntarget = ""; //prevent it from becoming "(null)" - } - if ( hub == qtrue ) - { - gi.SendConsoleCommand( va("loadtransition %s %s\n", mapname, spawntarget) ); + if (spawntarget == NULL) { + spawntarget = ""; // prevent it from becoming "(null)" } - else - { - gi.SendConsoleCommand( va("maptransition %s %s\n", mapname, spawntarget) ); + if (hub == qtrue) { + gi.SendConsoleCommand(va("loadtransition %s %s\n", mapname, spawntarget)); + } else { + gi.SendConsoleCommand(va("maptransition %s %s\n", mapname, spawntarget)); } } -qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ) -{ - for(int i = 0; i < 3; i++ ) - { - if ( point[i] < mins[i] ) - { +qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs) { + for (int i = 0; i < 3; i++) { + if (point[i] < mins[i]) { return qfalse; } - if ( point[i] > maxs[i] ) - { + if (point[i] > maxs[i]) { return qfalse; } } @@ -1893,61 +1670,55 @@ qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t ma return qtrue; } -qboolean G_BoxInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs, const vec3_t boundsMins, const vec3_t boundsMaxs ) -{ +qboolean G_BoxInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs, const vec3_t boundsMins, const vec3_t boundsMaxs) { vec3_t boxMins; vec3_t boxMaxs; - VectorAdd( point, mins, boxMins ); - VectorAdd( point, maxs, boxMaxs ); + VectorAdd(point, mins, boxMins); + VectorAdd(point, maxs, boxMaxs); - if(boxMaxs[0]>boundsMaxs[0]) + if (boxMaxs[0] > boundsMaxs[0]) return qfalse; - if(boxMaxs[1]>boundsMaxs[1]) + if (boxMaxs[1] > boundsMaxs[1]) return qfalse; - if(boxMaxs[2]>boundsMaxs[2]) + if (boxMaxs[2] > boundsMaxs[2]) return qfalse; - if(boxMins[0]currentAngles ); - VectorCopy( angles, ent->s.angles ); - VectorCopy( angles, ent->s.apos.trBase ); +void G_SetAngles(gentity_t *ent, const vec3_t angles) { + VectorCopy(angles, ent->currentAngles); + VectorCopy(angles, ent->s.angles); + VectorCopy(angles, ent->s.apos.trBase); } -qboolean G_ClearTrace( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask ) -{ - static trace_t tr; +qboolean G_ClearTrace(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask) { + static trace_t tr; - gi.trace( &tr, start, mins, maxs, end, ignore, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&tr, start, mins, maxs, end, ignore, clipmask, (EG2_Collision)0, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 1.0 ) - { + if (tr.allsolid || tr.startsolid || tr.fraction < 1.0) { return qfalse; } return qtrue; } -extern void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int radius); -void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteornot) -{ +extern void CG_TestLine(vec3_t start, vec3_t end, int time, unsigned int color, int radius); +void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteornot) { /* gentity_t *tent = G_TempEntity( A, EV_DEBUG_LINE ); VectorCopy(B, tent->s.origin2 ); @@ -1957,70 +1728,59 @@ void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteorn tent->freeAfterEvent = deleteornot; */ - CG_TestLine( A, B, duration, color, 1 ); + CG_TestLine(A, B, duration, color, 1); } -qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ) -{ - trace_t tr; - vec3_t start, end; +qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask) { + trace_t tr; + vec3_t start, end; - VectorCopy( point, start ); + VectorCopy(point, start); - for ( int i = 0; i < 3; i++ ) - { - VectorCopy( start, end ); + for (int i = 0; i < 3; i++) { + VectorCopy(start, end); end[i] += mins[i]; - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { - VectorCopy( start, end ); - end[i] += maxs[i]-(mins[i]*tr.fraction); - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + if (tr.fraction < 1.0) { + VectorCopy(start, end); + end[i] += maxs[i] - (mins[i] * tr.fraction); + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { + if (tr.fraction < 1.0) { return qfalse; } - VectorCopy( end, start ); + VectorCopy(end, start); } } - //expanded it, now see if it's all clear - gi.trace( &tr, start, mins, maxs, start, ignore, clipmask, (EG2_Collision)0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + // expanded it, now see if it's all clear + gi.trace(&tr, start, mins, maxs, start, ignore, clipmask, (EG2_Collision)0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - VectorCopy( start, point ); + VectorCopy(start, point); return qtrue; } /* Ghoul2 Insert Start */ -void removeBoltSurface( gentity_t *ent) -{ - gentity_t *hitEnt = &g_entities[ent->cantHitEnemyCounter]; +void removeBoltSurface(gentity_t *ent) { + gentity_t *hitEnt = &g_entities[ent->cantHitEnemyCounter]; // check first to be sure the bolt is still there on the model - if ((hitEnt->ghoul2.size() > ent->damage) && - (hitEnt->ghoul2[ent->damage].mModelindex != -1) && + if ((hitEnt->ghoul2.size() > ent->damage) && (hitEnt->ghoul2[ent->damage].mModelindex != -1) && (hitEnt->ghoul2[ent->damage].mSlist.size() > (unsigned int)ent->aimDebounceTime) && (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].surface != -1) && - (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].offFlags == G2SURFACEFLAG_GENERATED)) - { + (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].offFlags == G2SURFACEFLAG_GENERATED)) { // remove the bolt gi.G2API_RemoveBolt(&hitEnt->ghoul2[ent->damage], ent->attackDebounceTime); // now remove a surface if there is one - if (ent->aimDebounceTime != -1) - { + if (ent->aimDebounceTime != -1) { gi.G2API_RemoveSurface(&hitEnt->ghoul2[ent->damage], ent->aimDebounceTime); } } @@ -2028,9 +1788,9 @@ void removeBoltSurface( gentity_t *ent) G_FreeEntity(ent); } -void G_SetBoltSurfaceRemoval( const int entNum, const int modelIndex, const int boltIndex, const int surfaceIndex , float duration ) { - gentity_t *e; - vec3_t snapped = {0,0,0}; +void G_SetBoltSurfaceRemoval(const int entNum, const int modelIndex, const int boltIndex, const int surfaceIndex, float duration) { + gentity_t *e; + vec3_t snapped = {0, 0, 0}; e = G_Spawn(); @@ -2040,17 +1800,15 @@ void G_SetBoltSurfaceRemoval( const int entNum, const int modelIndex, const int e->attackDebounceTime = boltIndex; e->aimDebounceTime = surfaceIndex; - G_SetOrigin( e, snapped ); + G_SetOrigin(e, snapped); // find cluster for PVS - gi.linkentity( e ); + gi.linkentity(e); e->nextthink = level.time + duration; e->e_ThinkFunc = thinkF_removeBoltSurface; - } /* Ghoul2 Insert End */ - diff --git a/code/game/g_vehicleLoad.cpp b/code/game/g_vehicleLoad.cpp index 4af1336a20..0613bb2f5c 100644 --- a/code/game/g_vehicleLoad.cpp +++ b/code/game/g_vehicleLoad.cpp @@ -1,319 +1,303 @@ -//g_vehicleLoad.cpp -// leave this line at the top for all NPC_xxxx.cpp files... +// g_vehicleLoad.cpp +// leave this line at the top for all NPC_xxxx.cpp files... #include "g_headers.h" #include "../qcommon/q_shared.h" #include "anims.h" #include "g_vehicles.h" -extern qboolean G_ParseLiteral( const char **data, const char *string ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); +extern qboolean G_ParseLiteral(const char **data, const char *string); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); vehicleInfo_t g_vehicleInfo[MAX_VEHICLES]; -int numVehicles = 1;//first one is null/default +int numVehicles = 1; // first one is null/default typedef enum { VF_INT, VF_FLOAT, - VF_LSTRING, // string on disk, pointer in memory, TAG_LEVEL + VF_LSTRING, // string on disk, pointer in memory, TAG_LEVEL VF_VECTOR, VF_BOOL, VF_VEHTYPE, VF_ANIM } vehFieldType_t; -typedef struct -{ - char *name; - int ofs; - vehFieldType_t type; +typedef struct { + char *name; + int ofs; + vehFieldType_t type; } vehField_t; -vehField_t vehFields[VEH_PARM_MAX] = -{ - {"name", VFOFS(name), VF_LSTRING}, //unique name of the vehicle - - //general data - {"type", VFOFS(type), VF_VEHTYPE}, //what kind of vehicle - - {"numHands", VFOFS(numHands), VF_INT}, //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, //How far you can look up and down off the forward of the vehicle - {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, //How far you can look left and right off the forward of the vehicle - {"length", VFOFS(length), VF_FLOAT}, //how long it is - used for body length traces when turning/moving? - {"width", VFOFS(width), VF_FLOAT}, //how wide it is - used for body length traces when turning/moving? - {"height", VFOFS(height), VF_FLOAT}, //how tall it is - used for body length traces when turning/moving? - {"centerOfGravity", VFOFS(centerOfGravity), VF_VECTOR},//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - {"speedMax", VFOFS(speedMax), VF_FLOAT}, //top speed - {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, //turbo speed - {"speedMin", VFOFS(speedMin), VF_FLOAT}, //if < 0, can go in reverse - {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, //what speed it drifts to when no accel/decel input is given - {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, //if speedIdle > 0, how quickly it goes up to that speed - {"acceleration", VFOFS(acceleration), VF_FLOAT}, //when pressing on accelerator - {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, //when giving no input, how quickly it drops to speedIdle - {"strafePerc", VFOFS(strafePerc), VF_FLOAT}, //multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, //how quickly it pitches and rolls (not under player control) - {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, //how far it can roll forward or backward - {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, //how far it can roll to either side - {"braking", VFOFS(braking), VF_FLOAT}, //when pressing on decelerator - {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, //how quickly you can turn - {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL},//whether or not you can turn when not moving - {"traction", VFOFS(traction), VF_FLOAT}, //how much your command input affects velocity - {"friction", VFOFS(friction), VF_FLOAT}, //how much velocity is cut on its own - {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, //the max slope that it can go up with control - - //durability stats - {"mass", VFOFS(mass), VF_INT}, //for momentum and impact force (player mass is 10) - {"armor", VFOFS(armor), VF_INT}, //total points of damage it can take - {"toughness", VFOFS(toughness), VF_FLOAT}, //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT},//when armor drops to or below this point, start malfunctioning - - //visuals & sounds - {"model", VFOFS(model), VF_LSTRING}, //what model to use - if make it an NPC's primary model, don't need this? - {"skin", VFOFS(skin), VF_LSTRING}, //what skin to use - if make it an NPC's primary model, don't need this? - {"riderAnim", VFOFS(riderAnim), VF_ANIM}, //what animation the rider uses - {"gunswivelBone", VFOFS(gunswivelBone), VF_LSTRING},//gun swivel bones - {"lFinBone", VFOFS(lFinBone), VF_LSTRING}, //left fin bone - {"rFinBone", VFOFS(rFinBone), VF_LSTRING}, //right fin bone - {"lExhaustTag", VFOFS(lExhaustTag), VF_LSTRING}, //left exhaust tag - {"rExhaustTag", VFOFS(rExhaustTag), VF_LSTRING}, //right exhaust tag - - {"soundOn", VFOFS(soundOn), VF_LSTRING}, //sound to play when get on it - {"soundLoop", VFOFS(soundLoop), VF_LSTRING}, //sound to loop while riding it - {"soundOff", VFOFS(soundOff), VF_LSTRING}, //sound to play when get off - {"exhaustFX", VFOFS(exhaustFX), VF_LSTRING}, //exhaust effect, played from "*exhaust" bolt(s) - {"trailFX", VFOFS(trailFX), VF_LSTRING}, //trail effect, played from "*trail" bolt(s) - {"impactFX", VFOFS(impactFX), VF_LSTRING}, //impact effect, for when it bumps into something - {"explodeFX", VFOFS(explodeFX), VF_LSTRING}, //explosion effect, for when it blows up (should have the sound built into explosion effect) - {"wakeFX", VFOFS(wakeFX), VF_LSTRING}, //effect it makes when going across water - - //other misc stats - {"gravity", VFOFS(gravity), VF_INT}, //normal is 800 - {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, //if 0, it's a ground vehicle - {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, //how hard it pushes off ground when less than hover height... causes "bounce", like shocks - {"waterProof", VFOFS(waterProof), VF_BOOL}, //can drive underwater if it has to - {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, //when in water, how high it floats (1 is neutral bouyancy) - {"fuelMax", VFOFS(fuelMax), VF_INT}, //how much fuel it can hold (capacity) - {"fuelRate", VFOFS(fuelRate), VF_INT}, //how quickly is uses up fuel - {"visibility", VFOFS(visibility), VF_INT}, //for sight alerts - {"loudness", VFOFS(loudness), VF_INT}, //for sound alerts - {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT},//range of explosion - {"explosionDamage", VFOFS(explosionDamage), VF_INT},//damage of explosion - - //new stuff - {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). - {"hideRider", VFOFS(hideRider), VF_BOOL }, // rider (and passengers?) should not be drawn - {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL },//if rider is on vehicle when it dies, they should die - {"flammable", VFOFS(flammable), VF_BOOL }, //whether or not the vehicle should catch on fire before it explodes - {"explosionDelay", VFOFS(explosionDelay), VF_INT}, //how long the vehicle should be on fire/dying before it explodes - //camera stuff - {"cameraOverride", VFOFS(cameraOverride), VF_BOOL }, //override the third person camera with the below values - normal is 0 (off) - {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, //how far back the camera should be - normal is 80 - {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT},//how high over the vehicle origin the camera should be - normal is 16 - {"cameraHorzOffset", VFOFS(cameraHorzOffset), VF_FLOAT},//how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT},//a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, //third person camera FOV, default is 80 - {"cameraAlpha", VFOFS(cameraAlpha), VF_BOOL }, //fade out the vehicle if it's in the way of the crosshair +vehField_t vehFields[VEH_PARM_MAX] = { + {"name", VFOFS(name), VF_LSTRING}, // unique name of the vehicle + + // general data + {"type", VFOFS(type), VF_VEHTYPE}, // what kind of vehicle + + {"numHands", VFOFS(numHands), VF_INT}, // if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, // How far you can look up and down off the forward of the vehicle + {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, // How far you can look left and right off the forward of the vehicle + {"length", VFOFS(length), VF_FLOAT}, // how long it is - used for body length traces when turning/moving? + {"width", VFOFS(width), VF_FLOAT}, // how wide it is - used for body length traces when turning/moving? + {"height", VFOFS(height), VF_FLOAT}, // how tall it is - used for body length traces when turning/moving? + {"centerOfGravity", VFOFS(centerOfGravity), + VF_VECTOR}, // offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) + + // speed stats + {"speedMax", VFOFS(speedMax), VF_FLOAT}, // top speed + {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, // turbo speed + {"speedMin", VFOFS(speedMin), VF_FLOAT}, // if < 0, can go in reverse + {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, // what speed it drifts to when no accel/decel input is given + {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, // if speedIdle > 0, how quickly it goes up to that speed + {"acceleration", VFOFS(acceleration), VF_FLOAT}, // when pressing on accelerator + {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, // when giving no input, how quickly it drops to speedIdle + {"strafePerc", VFOFS(strafePerc), + VF_FLOAT}, // multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing + + // handling stats + {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, // how quickly it pitches and rolls (not under player control) + {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, // how far it can roll forward or backward + {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, // how far it can roll to either side + {"braking", VFOFS(braking), VF_FLOAT}, // when pressing on decelerator + {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, // how quickly you can turn + {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL}, // whether or not you can turn when not moving + {"traction", VFOFS(traction), VF_FLOAT}, // how much your command input affects velocity + {"friction", VFOFS(friction), VF_FLOAT}, // how much velocity is cut on its own + {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, // the max slope that it can go up with control + + // durability stats + {"mass", VFOFS(mass), VF_INT}, // for momentum and impact force (player mass is 10) + {"armor", VFOFS(armor), VF_INT}, // total points of damage it can take + {"toughness", VFOFS(toughness), + VF_FLOAT}, // modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction + {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT}, // when armor drops to or below this point, start malfunctioning + + // visuals & sounds + {"model", VFOFS(model), VF_LSTRING}, // what model to use - if make it an NPC's primary model, don't need this? + {"skin", VFOFS(skin), VF_LSTRING}, // what skin to use - if make it an NPC's primary model, don't need this? + {"riderAnim", VFOFS(riderAnim), VF_ANIM}, // what animation the rider uses + {"gunswivelBone", VFOFS(gunswivelBone), VF_LSTRING}, // gun swivel bones + {"lFinBone", VFOFS(lFinBone), VF_LSTRING}, // left fin bone + {"rFinBone", VFOFS(rFinBone), VF_LSTRING}, // right fin bone + {"lExhaustTag", VFOFS(lExhaustTag), VF_LSTRING}, // left exhaust tag + {"rExhaustTag", VFOFS(rExhaustTag), VF_LSTRING}, // right exhaust tag + + {"soundOn", VFOFS(soundOn), VF_LSTRING}, // sound to play when get on it + {"soundLoop", VFOFS(soundLoop), VF_LSTRING}, // sound to loop while riding it + {"soundOff", VFOFS(soundOff), VF_LSTRING}, // sound to play when get off + {"exhaustFX", VFOFS(exhaustFX), VF_LSTRING}, // exhaust effect, played from "*exhaust" bolt(s) + {"trailFX", VFOFS(trailFX), VF_LSTRING}, // trail effect, played from "*trail" bolt(s) + {"impactFX", VFOFS(impactFX), VF_LSTRING}, // impact effect, for when it bumps into something + {"explodeFX", VFOFS(explodeFX), VF_LSTRING}, // explosion effect, for when it blows up (should have the sound built into explosion effect) + {"wakeFX", VFOFS(wakeFX), VF_LSTRING}, // effect it makes when going across water + + // other misc stats + {"gravity", VFOFS(gravity), VF_INT}, // normal is 800 + {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, // if 0, it's a ground vehicle + {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, // how hard it pushes off ground when less than hover height... causes "bounce", like shocks + {"waterProof", VFOFS(waterProof), VF_BOOL}, // can drive underwater if it has to + {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, // when in water, how high it floats (1 is neutral bouyancy) + {"fuelMax", VFOFS(fuelMax), VF_INT}, // how much fuel it can hold (capacity) + {"fuelRate", VFOFS(fuelRate), VF_INT}, // how quickly is uses up fuel + {"visibility", VFOFS(visibility), VF_INT}, // for sight alerts + {"loudness", VFOFS(loudness), VF_INT}, // for sound alerts + {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT}, // range of explosion + {"explosionDamage", VFOFS(explosionDamage), VF_INT}, // damage of explosion + + // new stuff + {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). + {"hideRider", VFOFS(hideRider), VF_BOOL}, // rider (and passengers?) should not be drawn + {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL}, // if rider is on vehicle when it dies, they should die + {"flammable", VFOFS(flammable), VF_BOOL}, // whether or not the vehicle should catch on fire before it explodes + {"explosionDelay", VFOFS(explosionDelay), VF_INT}, // how long the vehicle should be on fire/dying before it explodes + // camera stuff + {"cameraOverride", VFOFS(cameraOverride), VF_BOOL}, // override the third person camera with the below values - normal is 0 (off) + {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, // how far back the camera should be - normal is 80 + {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT}, // how high over the vehicle origin the camera should be - normal is 16 + {"cameraHorzOffset", VFOFS(cameraHorzOffset), + VF_FLOAT}, // how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 + {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT}, // a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 + {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, // third person camera FOV, default is 80 + {"cameraAlpha", VFOFS(cameraAlpha), VF_BOOL}, // fade out the vehicle if it's in the way of the crosshair }; -stringID_table_t VehicleTable[VH_NUM_VEHICLES+1] = -{ - ENUM2STRING(VH_WALKER), //something you ride inside of, it walks like you, like an AT-ST - ENUM2STRING(VH_FIGHTER), //something you fly inside of, like an X-Wing or TIE fighter - ENUM2STRING(VH_SPEEDER), //something you ride on that hovers, like a speeder or swoop - ENUM2STRING(VH_ANIMAL), //animal you ride on top of that walks, like a tauntaun - ENUM2STRING(VH_FLIER), //animal you ride on top of that flies, like a giant mynoc? - "", -1 -}; - -void G_VehicleSetDefaults( vehicleInfo_t *vehicle ) -{ - vehicle->name = "default"; //unique name of the vehicle -/* - //general data - vehicle->type = VH_SPEEDER; //what kind of vehicle - //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player - vehicle->numHands = 2; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - vehicle->lookPitch = 35; //How far you can look up and down off the forward of the vehicle - vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle - vehicle->length = 0; //how long it is - used for body length traces when turning/moving? - vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? - vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? - VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - note: these are DESIRED speed, not actual current speed/velocity - vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed - vehicle->turboSpeed = 0; //turboBoost - vehicle->speedMin = 0; //if < 0, can go in reverse - vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given - vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed - vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) - vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle - vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) - vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side - vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward - vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) - vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn - vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving - vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity - vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own - vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control - - //durability stats - vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) - vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take - vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning - - //visuals & sounds - vehicle->model = "swoop"; //what model to use - if make it an NPC's primary model, don't need this? - vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level - vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? - vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses - vehicle->gunswivelBone = NULL; //gun swivel bones - vehicle->lFinBone = NULL; //left fin bone - vehicle->rFinBone = NULL; //right fin bone - vehicle->lExhaustTag = NULL; //left exhaust tag - vehicle->rExhaustTag = NULL; //right exhaust tag - - vehicle->soundOn = NULL; //sound to play when get on it - vehicle->soundLoop = NULL; //sound to loop while riding it - vehicle->soundOff = NULL; //sound to play when get off - vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) - vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) - vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->wakeFX = NULL; //effect itmakes when going across water - - //other misc stats - vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 - vehicle->hoverHeight = 0; //if 0, it's a ground vehicle - vehicle->hoverStrength = 0;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks - vehicle->waterProof = qtrue; //can drive underwater if it has to - vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) - vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) - vehicle->fuelRate = 1; //how quickly is uses up fuel - vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts - vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts - vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; - vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; - - //new stuff - vehicle->maxPassengers = 0; - vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn - vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die - vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes - vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes - //camera stuff - vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values - vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 - vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 - vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80 - vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair -*/ +stringID_table_t VehicleTable[VH_NUM_VEHICLES + 1] = {ENUM2STRING(VH_WALKER), // something you ride inside of, it walks like you, like an AT-ST + ENUM2STRING(VH_FIGHTER), // something you fly inside of, like an X-Wing or TIE fighter + ENUM2STRING(VH_SPEEDER), // something you ride on that hovers, like a speeder or swoop + ENUM2STRING(VH_ANIMAL), // animal you ride on top of that walks, like a tauntaun + ENUM2STRING(VH_FLIER), // animal you ride on top of that flies, like a giant mynoc? + "", + -1}; + +void G_VehicleSetDefaults(vehicleInfo_t *vehicle) { + vehicle->name = "default"; // unique name of the vehicle + /* + //general data + vehicle->type = VH_SPEEDER; //what kind of vehicle + //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player + vehicle->numHands = 2; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + vehicle->lookPitch = 35; //How far you can look up and down off the forward of the vehicle + vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle + vehicle->length = 0; //how long it is - used for body length traces when turning/moving? + vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? + vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? + VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is + all the way forward) + + //speed stats - note: these are DESIRED speed, not actual current speed/velocity + vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed + vehicle->turboSpeed = 0; //turboBoost + vehicle->speedMin = 0; //if < 0, can go in reverse + vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given + vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed + vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) + vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle + vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going + forward, 0.5 is half, 0 is no strafing + + //handling stats + vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) + vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side + vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward + vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) + vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn + vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving + vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity + vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own + vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control + + //durability stats + vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) + vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take + vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher + materials/construction vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning + + //visuals & sounds + vehicle->model = "swoop"; //what model to use - if make it an NPC's primary model, don't need this? + vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level + vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? + vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses + vehicle->gunswivelBone = NULL; //gun swivel bones + vehicle->lFinBone = NULL; //left fin bone + vehicle->rFinBone = NULL; //right fin bone + vehicle->lExhaustTag = NULL; //left exhaust tag + vehicle->rExhaustTag = NULL; //right exhaust tag + + vehicle->soundOn = NULL; //sound to play when get on it + vehicle->soundLoop = NULL; //sound to loop while riding it + vehicle->soundOff = NULL; //sound to play when get off + vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) + vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) + vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->wakeFX = NULL; //effect itmakes when going across water + + //other misc stats + vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 + vehicle->hoverHeight = 0; //if 0, it's a ground vehicle + vehicle->hoverStrength = 0;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks + vehicle->waterProof = qtrue; //can drive underwater if it has to + vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) + vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) + vehicle->fuelRate = 1; //how quickly is uses up fuel + vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts + vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts + vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; + vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; + + //new stuff + vehicle->maxPassengers = 0; + vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn + vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die + vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes + vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes + //camera stuff + vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values + vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 + vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 + vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal + is 0 vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 + vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80 + vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair + */ } -void G_VehicleClampData( vehicleInfo_t *vehicle ) -{//sanity check and clamp the vehicle's data - int i; +void G_VehicleClampData(vehicleInfo_t *vehicle) { // sanity check and clamp the vehicle's data + int i; - for ( i = 0; i < 3; i++ ) - { - if ( vehicle->centerOfGravity[i] > 1.0f ) - { + for (i = 0; i < 3; i++) { + if (vehicle->centerOfGravity[i] > 1.0f) { vehicle->centerOfGravity[i] = 1.0f; - } - else if ( vehicle->centerOfGravity[i] < -1.0f ) - { + } else if (vehicle->centerOfGravity[i] < -1.0f) { vehicle->centerOfGravity[i] = -1.0f; } } // Validate passenger max. - if ( vehicle->maxPassengers > VEH_MAX_PASSENGERS ) - { + if (vehicle->maxPassengers > VEH_MAX_PASSENGERS) { vehicle->maxPassengers = VEH_MAX_PASSENGERS; - } - else if ( vehicle->maxPassengers < 0 ) - { + } else if (vehicle->maxPassengers < 0) { vehicle->maxPassengers = 0; } } - -static void G_ParseVehicleParms( vehicleInfo_t *vehicle, const char **holdBuf ) -{ - const char *token; - const char *value; - int i; - vec3_t vec; - byte *b = (byte *)vehicle; - int _iFieldsRead = 0; +static void G_ParseVehicleParms(vehicleInfo_t *vehicle, const char **holdBuf) { + const char *token; + const char *value; + int i; + vec3_t vec; + byte *b = (byte *)vehicle; + int _iFieldsRead = 0; vehicleType_t vehType; - while ( holdBuf ) - { - token = COM_ParseExt( holdBuf, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing vehicles!\n" ); + while (holdBuf) { + token = COM_ParseExt(holdBuf, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing vehicles!\n"); return; } - if ( !Q_stricmp( token, "}" ) ) // End of data for this vehicle + if (!Q_stricmp(token, "}")) // End of data for this vehicle { break; } // Loop through possible parameters - for ( i = 0; i < VEH_PARM_MAX; i++ ) - { - if ( vehFields[i].name && !Q_stricmp( vehFields[i].name, token ) ) - { + for (i = 0; i < VEH_PARM_MAX; i++) { + if (vehFields[i].name && !Q_stricmp(vehFields[i].name, token)) { // found it - if ( COM_ParseString( holdBuf, &value ) ) - { + if (COM_ParseString(holdBuf, &value)) { continue; } - switch( vehFields[i].type ) - { + switch (vehFields[i].type) { case VF_INT: - *(int *)(b+vehFields[i].ofs) = atoi(value); + *(int *)(b + vehFields[i].ofs) = atoi(value); break; case VF_FLOAT: - *(float *)(b+vehFields[i].ofs) = atof(value); + *(float *)(b + vehFields[i].ofs) = atof(value); break; - case VF_LSTRING: // string on disk, pointer in memory, TAG_LEVEL - *(char **)(b+vehFields[i].ofs) = G_NewString( value ); + case VF_LSTRING: // string on disk, pointer in memory, TAG_LEVEL + *(char **)(b + vehFields[i].ofs) = G_NewString(value); break; case VF_VECTOR: - _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - assert(_iFieldsRead==3 ); - if (_iFieldsRead!=3) - { - gi.Printf (S_COLOR_YELLOW"G_ParseVehicleParms: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + assert(_iFieldsRead == 3); + if (_iFieldsRead != 3) { + gi.Printf(S_COLOR_YELLOW "G_ParseVehicleParms: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); } - ((float *)(b+vehFields[i].ofs))[0] = vec[0]; - ((float *)(b+vehFields[i].ofs))[1] = vec[1]; - ((float *)(b+vehFields[i].ofs))[2] = vec[2]; + ((float *)(b + vehFields[i].ofs))[0] = vec[0]; + ((float *)(b + vehFields[i].ofs))[1] = vec[1]; + ((float *)(b + vehFields[i].ofs))[2] = vec[2]; break; case VF_BOOL: - *(qboolean *)(b+vehFields[i].ofs) = (atof(value)!=0); + *(qboolean *)(b + vehFields[i].ofs) = (atof(value) != 0); break; case VF_VEHTYPE: - vehType = (vehicleType_t)GetIDForString( VehicleTable, value ); - *(vehicleType_t *)(b+vehFields[i].ofs) = vehType; + vehType = (vehicleType_t)GetIDForString(VehicleTable, value); + *(vehicleType_t *)(b + vehFields[i].ofs) = vehType; break; case VF_ANIM: - int anim = GetIDForString( animTable, value ); - *(int *)(b+vehFields[i].ofs) = anim; + int anim = GetIDForString(animTable, value); + *(int *)(b + vehFields[i].ofs) = anim; break; } break; @@ -322,107 +306,95 @@ static void G_ParseVehicleParms( vehicleInfo_t *vehicle, const char **holdBuf ) } } -static void G_VehicleStoreParms( const char *p ) -{//load up all into a table: g_vehicleInfo - const char *token; - vehicleInfo_t *vehicle; +static void G_VehicleStoreParms(const char *p) { // load up all into a table: g_vehicleInfo + const char *token; + vehicleInfo_t *vehicle; ////////////////// HERE ////////////////////// // The first vehicle just contains all the base level (not 'overridden') function calls. - G_SetSharedVehicleFunctions( &g_vehicleInfo[0] ); + G_SetSharedVehicleFunctions(&g_vehicleInfo[0]); numVehicles = 1; - //try to parse data out + // try to parse data out COM_BeginParseSession(); - //look for an open brace - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//barf + // look for an open brace + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // barf return; } - if ( !Q_stricmp( token, "{" ) ) - {//found one, parse out the goodies - if ( numVehicles >= MAX_VEHICLES ) - {//sorry, no more vehicle slots! - gi.Printf( S_COLOR_RED"Too many vehicles in *.veh (limit %d)\n", MAX_VEHICLES ); + if (!Q_stricmp(token, "{")) { // found one, parse out the goodies + if (numVehicles >= MAX_VEHICLES) { // sorry, no more vehicle slots! + gi.Printf(S_COLOR_RED "Too many vehicles in *.veh (limit %d)\n", MAX_VEHICLES); break; } - //token = token; + // token = token; vehicle = &g_vehicleInfo[numVehicles++]; - G_VehicleSetDefaults( vehicle ); - G_ParseVehicleParms( vehicle, &p ); - //sanity check and clamp the vehicle's data - G_VehicleClampData( vehicle ); - ////////////////// HERE ////////////////////// + G_VehicleSetDefaults(vehicle); + G_ParseVehicleParms(vehicle, &p); + // sanity check and clamp the vehicle's data + G_VehicleClampData(vehicle); + ////////////////// HERE ////////////////////// // Setup the shared function pointers. - G_SetSharedVehicleFunctions( vehicle ); - switch( vehicle->type ) - { - case VH_SPEEDER: - G_SetSpeederVehicleFunctions( vehicle ); - break; - case VH_ANIMAL: - G_SetAnimalVehicleFunctions( vehicle ); - break; - case VH_FIGHTER: - G_SetFighterVehicleFunctions( vehicle ); - break; - case VH_WALKER: - G_SetAnimalVehicleFunctions( vehicle ); - break; + G_SetSharedVehicleFunctions(vehicle); + switch (vehicle->type) { + case VH_SPEEDER: + G_SetSpeederVehicleFunctions(vehicle); + break; + case VH_ANIMAL: + G_SetAnimalVehicleFunctions(vehicle); + break; + case VH_FIGHTER: + G_SetFighterVehicleFunctions(vehicle); + break; + case VH_WALKER: + G_SetAnimalVehicleFunctions(vehicle); + break; } } } } -void G_VehicleLoadParms( void ) -{//HMM... only do this if there's a vehicle on the level? - int len, totallen, vehExtFNLen, fileCnt, i; - char *buffer, *holdChar, *marker; - char vehExtensionListBuf[2048]; // The list of file names read in +void G_VehicleLoadParms(void) { // HMM... only do this if there's a vehicle on the level? + int len, totallen, vehExtFNLen, fileCnt, i; + char *buffer, *holdChar, *marker; + char vehExtensionListBuf[2048]; // The list of file names read in - #define MAX_VEHICLE_DATA_SIZE 0x20000 - char VehicleParms[MAX_VEHICLE_DATA_SIZE]={0}; +#define MAX_VEHICLE_DATA_SIZE 0x20000 + char VehicleParms[MAX_VEHICLE_DATA_SIZE] = {0}; // gi.Printf( "Parsing *.veh vehicle definitions\n" ); - //set where to store the first one + // set where to store the first one totallen = 0; marker = VehicleParms; - //now load in the .veh vehicle definitions - fileCnt = gi.FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf) ); + // now load in the .veh vehicle definitions + fileCnt = gi.FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf)); holdChar = vehExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 ) - { - vehExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1) { + vehExtFNLen = strlen(holdChar); - //gi.Printf( "Parsing %s\n", holdChar ); + // gi.Printf( "Parsing %s\n", holdChar ); - len = gi.FS_ReadFile( va( "ext_data/vehicles/%s", holdChar), (void **) &buffer ); + len = gi.FS_ReadFile(va("ext_data/vehicles/%s", holdChar), (void **)&buffer); - if ( len == -1 ) - { - gi.Printf( "G_VehicleLoadParms: error reading file %s\n", holdChar ); - } - else - { - if ( totallen && *(marker-1) == '}' ) - {//don't let it end on a } because that should be a stand-alone token - strcat( marker, " " ); + if (len == -1) { + gi.Printf("G_VehicleLoadParms: error reading file %s\n", holdChar); + } else { + if (totallen && *(marker - 1) == '}') { // don't let it end on a } because that should be a stand-alone token + strcat(marker, " "); totallen++; marker++; } - if ( totallen + len >= MAX_VEHICLE_DATA_SIZE ) { - G_Error( "G_VehicleLoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar ); + if (totallen + len >= MAX_VEHICLE_DATA_SIZE) { + G_Error("G_VehicleLoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar); } - strcat( marker, buffer ); - gi.FS_FreeFile( buffer ); + strcat(marker, buffer); + gi.FS_FreeFile(buffer); totallen += len; marker += len; diff --git a/code/game/g_vehicles.cpp b/code/game/g_vehicles.cpp index 2db37c0065..24471905bc 100644 --- a/code/game/g_vehicles.cpp +++ b/code/game/g_vehicles.cpp @@ -23,7 +23,7 @@ along with this program; if not, see . #include "../qcommon/q_shared.h" #include "g_local.h" -#ifdef _JK2 //SP does not have this preprocessor for game like MP does +#ifdef _JK2 // SP does not have this preprocessor for game like MP does #ifndef _JK2MP #define _JK2MP #endif @@ -38,8 +38,8 @@ along with this program; if not, see . #endif #ifdef _JK2MP -//this is really horrible, but it works! just be sure not to use any locals or anything -//with these names (exluding bool, false, true). -rww +// this is really horrible, but it works! just be sure not to use any locals or anything +// with these names (exluding bool, false, true). -rww #define currentAngles r.currentAngles #define currentOrigin r.currentOrigin #define mins r.mins @@ -60,51 +60,50 @@ along with this program; if not, see . #endif #ifdef _JK2MP -extern gentity_t *NPC_Spawn_Do( gentity_t *ent ); -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags); +extern gentity_t *NPC_Spawn_Do(gentity_t *ent); +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags); #else -extern gentity_t *NPC_Spawn_Do( gentity_t *pEnt, qboolean fullSpawnNow ); +extern gentity_t *NPC_Spawn_Do(gentity_t *pEnt, qboolean fullSpawnNow); extern qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask); -extern qboolean G_SetG2PlayerModelInfo( gentity_t *pEnt, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ); -extern void G_RemovePlayerModel( gentity_t *pEnt ); -extern void G_ChangePlayerModel( gentity_t *pEnt, const char *newModel ); -extern void G_RemoveWeaponModels( gentity_t *pEnt ); -extern void CG_ChangeWeapon( int num ); -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern void SetClientViewAngle( gentity_t *ent, vec3_t angle ); +extern qboolean G_SetG2PlayerModelInfo(gentity_t *pEnt, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn); +extern void G_RemovePlayerModel(gentity_t *pEnt); +extern void G_ChangePlayerModel(gentity_t *pEnt, const char *newModel); +extern void G_RemoveWeaponModels(gentity_t *pEnt); +extern void CG_ChangeWeapon(int num); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern void SetClientViewAngle(gentity_t *ent, vec3_t angle); -extern vmCvar_t cg_thirdPersonAlpha; +extern vmCvar_t cg_thirdPersonAlpha; extern vec3_t playerMins; extern vec3_t playerMaxs; -extern cvar_t *g_speederControlScheme; +extern cvar_t *g_speederControlScheme; extern cvar_t *in_joystick; -extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); +extern void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); #endif #ifdef _JK2MP #include "../namespace_begin.h" -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern void BG_SetLegsAnimTimer(playerState_t *ps, int time ); -extern void BG_SetTorsoAnimTimer(playerState_t *ps, int time ); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern void BG_SetLegsAnimTimer(playerState_t *ps, int time); +extern void BG_SetTorsoAnimTimer(playerState_t *ps, int time); #include "../namespace_end.h" -void G_VehUpdateShields( gentity_t *targ ); +void G_VehUpdateShields(gentity_t *targ); #ifdef QAGAME -extern void VEH_TurretThink( Vehicle_t *pVeh, gentity_t *parent, int turretNum ); +extern void VEH_TurretThink(Vehicle_t *pVeh, gentity_t *parent, int turretNum); #endif #else -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); #endif -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); -void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend) -{ +void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend) { #ifdef _JK2MP assert(ent->client); BG_SetAnim(&ent->client->ps, bgAllAnims[ent->localAnimIndex].anims, setAnimParts, anim, setAnimFlags, iBlend); @@ -114,172 +113,148 @@ void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, #endif } -void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ) -{ +void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask) { #ifdef _JK2MP trap_Trace(results, start, tMins, tMaxs, end, passEntityNum, contentmask); #else - gi.trace( results, start, tMins, tMaxs, end, passEntityNum, contentmask, (EG2_Collision)0, 0 ); + gi.trace(results, start, tMins, tMaxs, end, passEntityNum, contentmask, (EG2_Collision)0, 0); #endif } -Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ) -{ +Vehicle_t *G_IsRidingVehicle(gentity_t *pEnt) { gentity_t *ent = (gentity_t *)pEnt; - if ( ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && ent->s.m_iVehicleNum != 0 ) //ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) + if (ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && + ent->s.m_iVehicleNum != 0) // ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) { return g_entities[ent->s.m_iVehicleNum].m_pVehicle; } return NULL; } -bool G_IsRidingTurboVehicle( gentity_t *pEnt ) -{ +bool G_IsRidingTurboVehicle(gentity_t *pEnt) { gentity_t *ent = (gentity_t *)pEnt; - if ( ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && ent->s.m_iVehicleNum != 0 ) //ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) + if (ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && + ent->s.m_iVehicleNum != 0) // ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) { - return (level.times.m_iVehicleNum].m_pVehicle->m_iTurboTime); + return (level.time < g_entities[ent->s.m_iVehicleNum].m_pVehicle->m_iTurboTime); } return false; } - - -float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ +float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUcmd) { #ifndef _JK2MP - gentity_t* rider = pVeh->m_pPilot; + gentity_t *rider = pVeh->m_pPilot; // If There Is An Enemy And We Are At The Same Z Height //------------------------------------------------------ - if (rider && - rider->enemy && - pUcmd->rightmove && - fabsf(rider->enemy->currentOrigin[2] - rider->currentOrigin[2])<50.0f) - { - if (level.timem_safeJumpMountTime) - { + if (rider && rider->enemy && pUcmd->rightmove && fabsf(rider->enemy->currentOrigin[2] - rider->currentOrigin[2]) < 50.0f) { + if (level.time < pVeh->m_safeJumpMountTime) { return pVeh->m_safeJumpMountRightDot; } - // If The Enemy Is Riding Another Vehicle //---------------------------------------- - Vehicle_t* enemyVeh = G_IsRidingVehicle(rider->enemy); - if (enemyVeh) - { - vec3_t enemyFwd; - vec3_t toEnemy; - float toEnemyDistance; - vec3_t riderFwd; - vec3_t riderRight; - float riderRightDot; + Vehicle_t *enemyVeh = G_IsRidingVehicle(rider->enemy); + if (enemyVeh) { + vec3_t enemyFwd; + vec3_t toEnemy; + float toEnemyDistance; + vec3_t riderFwd; + vec3_t riderRight; + float riderRightDot; // If He Is Close Enough And Going The Same Speed //------------------------------------------------ VectorSubtract(rider->enemy->currentOrigin, rider->currentOrigin, toEnemy); - toEnemyDistance = VectorNormalize(toEnemy); - if (toEnemyDistance<70.0f && - pVeh->m_pParentEntity->resultspeed>100.0f && - fabsf(pVeh->m_pParentEntity->resultspeed - enemyVeh->m_pParentEntity->resultspeed)<100.0f) - { + toEnemyDistance = VectorNormalize(toEnemy); + if (toEnemyDistance < 70.0f && pVeh->m_pParentEntity->resultspeed > 100.0f && + fabsf(pVeh->m_pParentEntity->resultspeed - enemyVeh->m_pParentEntity->resultspeed) < 100.0f) { // If He Is Either To The Left Or Right Of Me //-------------------------------------------- AngleVectors(rider->currentAngles, riderFwd, riderRight, 0); riderRightDot = DotProduct(riderRight, toEnemy); - if ((pUcmd->rightmove>0 && riderRightDot>0.2) || (pUcmd->rightmove<0 &&riderRightDot<-0.2)) - { + if ((pUcmd->rightmove > 0 && riderRightDot > 0.2) || (pUcmd->rightmove < 0 && riderRightDot < -0.2)) { // If We Are Both Going About The Same Direction //----------------------------------------------- AngleVectors(rider->enemy->currentAngles, enemyFwd, 0, 0); - if (DotProduct(enemyFwd, riderFwd)>0.2f) - { - pVeh->m_safeJumpMountTime = level.time + Q_irand(3000, 4000); // Ok, now you get a 3 sec window + if (DotProduct(enemyFwd, riderFwd) > 0.2f) { + pVeh->m_safeJumpMountTime = level.time + Q_irand(3000, 4000); // Ok, now you get a 3 sec window pVeh->m_safeJumpMountRightDot = riderRightDot; return riderRightDot; - }// Same Direction? - }// To Left Or Right? - }// Close Enough & Same Speed? - }// Enemy Riding A Vehicle? - }// Has Enemy And On Same Z-Height + } // Same Direction? + } // To Left Or Right? + } // Close Enough & Same Speed? + } // Enemy Riding A Vehicle? + } // Has Enemy And On Same Z-Height #endif return 0.0f; } // Spawn this vehicle into the world. -void G_VehicleSpawn( gentity_t *self ) -{ +void G_VehicleSpawn(gentity_t *self) { float yaw; gentity_t *vehEnt; - VectorCopy( self->currentOrigin, self->s.origin ); + VectorCopy(self->currentOrigin, self->s.origin); #ifdef _JK2MP - trap_LinkEntity( self ); + trap_LinkEntity(self); #else - gi.linkentity( self ); + gi.linkentity(self); #endif - if ( !self->count ) - { + if (!self->count) { self->count = 1; } - //save this because self gets removed in next func + // save this because self gets removed in next func yaw = self->s.angles[YAW]; #ifdef _JK2MP - vehEnt = NPC_Spawn_Do( self ); + vehEnt = NPC_Spawn_Do(self); #else - vehEnt = NPC_Spawn_Do( self, qtrue ); + vehEnt = NPC_Spawn_Do(self, qtrue); #endif - if ( !vehEnt ) - { - return;//return NULL; + if (!vehEnt) { + return; // return NULL; } vehEnt->s.angles[YAW] = yaw; - if ( vehEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - { + if (vehEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { vehEnt->NPC->behaviorState = BS_CINEMATIC; } -#ifdef _JK2MP //special check in case someone disconnects/dies while boarding - if (vehEnt->spawnflags & 1) - { //die without pilot - if (!vehEnt->damage) - { //default 10 sec +#ifdef _JK2MP // special check in case someone disconnects/dies while boarding + if (vehEnt->spawnflags & 1) { // die without pilot + if (!vehEnt->damage) { // default 10 sec vehEnt->damage = 10000; } - if (!vehEnt->speed) - { //default 512 units + if (!vehEnt->speed) { // default 512 units vehEnt->speed = 512.0f; } vehEnt->m_pVehicle->m_iPilotTime = level.time + vehEnt->damage; } #else - if (vehEnt->spawnflags & 1) - { //die without pilot + if (vehEnt->spawnflags & 1) { // die without pilot vehEnt->m_pVehicle->m_iPilotTime = level.time + vehEnt->endFrame; } #endif - //return vehEnt; + // return vehEnt; } // Attachs an entity to the vehicle it's riding (it's owner). -void G_AttachToVehicle( gentity_t *pEnt, usercmd_t **ucmd ) -{ - gentity_t *vehEnt; - mdxaBone_t boltMatrix; - gentity_t *ent; +void G_AttachToVehicle(gentity_t *pEnt, usercmd_t **ucmd) { + gentity_t *vehEnt; + mdxaBone_t boltMatrix; + gentity_t *ent; #ifdef _JK2MP - int crotchBolt; + int crotchBolt; #endif - if ( !pEnt || !ucmd ) + if (!pEnt || !ucmd) return; ent = (gentity_t *)pEnt; @@ -291,244 +266,202 @@ void G_AttachToVehicle( gentity_t *pEnt, usercmd_t **ucmd ) #endif ent->waypoint = vehEnt->waypoint; // take the veh's waypoint as your own - if ( !vehEnt->m_pVehicle ) + if (!vehEnt->m_pVehicle) return; #ifdef _JK2MP crotchBolt = trap_G2API_AddBolt(vehEnt->ghoul2, 0, "*driver"); // Get the driver tag. - trap_G2API_GetBoltMatrix( vehEnt->ghoul2, 0, crotchBolt, &boltMatrix, - vehEnt->m_pVehicle->m_vOrientation, vehEnt->currentOrigin, - level.time, NULL, vehEnt->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, ent->client->ps.origin ); + trap_G2API_GetBoltMatrix(vehEnt->ghoul2, 0, crotchBolt, &boltMatrix, vehEnt->m_pVehicle->m_vOrientation, vehEnt->currentOrigin, level.time, NULL, + vehEnt->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, ent->client->ps.origin); G_SetOrigin(ent, ent->client->ps.origin); - trap_LinkEntity( ent ); + trap_LinkEntity(ent); #else // Get the driver tag. - gi.G2API_GetBoltMatrix( vehEnt->ghoul2, vehEnt->playerModel, vehEnt->crotchBolt, &boltMatrix, - vehEnt->m_pVehicle->m_vOrientation, vehEnt->currentOrigin, - (cg.time?cg.time:level.time), NULL, vehEnt->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->ps.origin ); - gi.linkentity( ent ); + gi.G2API_GetBoltMatrix(vehEnt->ghoul2, vehEnt->playerModel, vehEnt->crotchBolt, &boltMatrix, vehEnt->m_pVehicle->m_vOrientation, vehEnt->currentOrigin, + (cg.time ? cg.time : level.time), NULL, vehEnt->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->ps.origin); + gi.linkentity(ent); #endif } #ifndef _JK2MP -void G_KnockOffVehicle( gentity_t *pRider, gentity_t *self, qboolean bPull ) -{ +void G_KnockOffVehicle(gentity_t *pRider, gentity_t *self, qboolean bPull) { Vehicle_t *pVeh = NULL; vec3_t riderAngles, fDir, rDir, dir2Me; - float fDot, rDot; + float fDot, rDot; - if ( !pRider || !pRider->client ) - { + if (!pRider || !pRider->client) { return; } - pVeh = G_IsRidingVehicle( pRider ); + pVeh = G_IsRidingVehicle(pRider); - if ( !pVeh || !pVeh->m_pVehicleInfo ) - { + if (!pVeh || !pVeh->m_pVehicleInfo) { return; } - VectorCopy( pRider->currentAngles, riderAngles ); + VectorCopy(pRider->currentAngles, riderAngles); riderAngles[0] = 0; - AngleVectors( riderAngles, fDir, rDir, NULL ); - VectorSubtract( self->currentOrigin, pRider->currentOrigin, dir2Me ); + AngleVectors(riderAngles, fDir, rDir, NULL); + VectorSubtract(self->currentOrigin, pRider->currentOrigin, dir2Me); dir2Me[2] = 0; - VectorNormalize( dir2Me ); - fDot = DotProduct( fDir, dir2Me ); - if ( fDot >= 0.5f ) - {//I'm in front of them - if ( bPull ) - {//pull them foward + VectorNormalize(dir2Me); + fDot = DotProduct(fDir, dir2Me); + if (fDot >= 0.5f) { // I'm in front of them + if (bPull) { // pull them foward pVeh->m_EjectDir = VEH_EJECT_FRONT; - } - else - {//push them back + } else { // push them back pVeh->m_EjectDir = VEH_EJECT_REAR; } - } - else if ( fDot <= -0.5f ) - {//I'm behind them - if ( bPull ) - {//pull them back + } else if (fDot <= -0.5f) { // I'm behind them + if (bPull) { // pull them back pVeh->m_EjectDir = VEH_EJECT_REAR; - } - else - {//push them forward + } else { // push them forward pVeh->m_EjectDir = VEH_EJECT_FRONT; } - } - else - {//to the side of them - rDot = DotProduct( fDir, dir2Me ); - if ( rDot >= 0.0f ) - {//to the right - if ( bPull ) - {//pull them right + } else { // to the side of them + rDot = DotProduct(fDir, dir2Me); + if (rDot >= 0.0f) { // to the right + if (bPull) { // pull them right pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else - {//push them left + } else { // push them left pVeh->m_EjectDir = VEH_EJECT_LEFT; } - } - else - {//to the left - if ( bPull ) - {//pull them left + } else { // to the left + if (bPull) { // pull them left pVeh->m_EjectDir = VEH_EJECT_LEFT; - } - else - {//push them right + } else { // push them right pVeh->m_EjectDir = VEH_EJECT_RIGHT; } } } - //now forcibly eject them - pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qtrue ); + // now forcibly eject them + pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qtrue); } #endif -#ifndef _JK2MP //don't want this in mp at least for now -void G_DrivableATSTDie( gentity_t *self ) -{ -} +#ifndef _JK2MP // don't want this in mp at least for now +void G_DrivableATSTDie(gentity_t *self) {} -void G_DriveATST( gentity_t *pEnt, gentity_t *atst ) -{ - if ( pEnt->NPC_type && pEnt->client && (pEnt->client->NPC_class == CLASS_ATST) ) - {//already an atst, switch back - //open hatch - G_RemovePlayerModel( pEnt ); +void G_DriveATST(gentity_t *pEnt, gentity_t *atst) { + if (pEnt->NPC_type && pEnt->client && (pEnt->client->NPC_class == CLASS_ATST)) { // already an atst, switch back + // open hatch + G_RemovePlayerModel(pEnt); pEnt->NPC_type = "player"; pEnt->client->NPC_class = CLASS_PLAYER; pEnt->flags &= ~FL_SHIELDED; pEnt->client->ps.eFlags &= ~EF_IN_ATST; - //size - VectorCopy( playerMins, pEnt->mins ); - VectorCopy( playerMaxs, pEnt->maxs ); + // size + VectorCopy(playerMins, pEnt->mins); + VectorCopy(playerMaxs, pEnt->maxs); pEnt->client->crouchheight = CROUCH_MAXS_2; pEnt->client->standheight = DEFAULT_MAXS_2; - pEnt->s.radius = 0;//clear it so the G2-model-setting stuff will recalc it - G_ChangePlayerModel( pEnt, pEnt->NPC_type ); - //G_SetG2PlayerModel( pEnt, pEnt->NPC_type, NULL, NULL, NULL ); + pEnt->s.radius = 0; // clear it so the G2-model-setting stuff will recalc it + G_ChangePlayerModel(pEnt, pEnt->NPC_type); + // G_SetG2PlayerModel( pEnt, pEnt->NPC_type, NULL, NULL, NULL ); - //FIXME: reset/4 their weapon - pEnt->client->ps.stats[STAT_WEAPONS] &= ~(( 1 << WP_ATST_MAIN )|( 1 << WP_ATST_SIDE )); + // FIXME: reset/4 their weapon + pEnt->client->ps.stats[STAT_WEAPONS] &= ~((1 << WP_ATST_MAIN) | (1 << WP_ATST_SIDE)); pEnt->client->ps.ammo[weaponData[WP_ATST_MAIN].ammoIndex] = 0; pEnt->client->ps.ammo[weaponData[WP_ATST_SIDE].ammoIndex] = 0; - if ( pEnt->client->ps.stats[STAT_WEAPONS] & (1<client->ps.stats[STAT_WEAPONS] & (1 << WP_BLASTER)) { + CG_ChangeWeapon(WP_BLASTER); + // camera + if (cg_gunAutoFirst.integer) { // go back to first person + gi.cvar_set("cg_thirdperson", "0"); } + } else { + CG_ChangeWeapon(WP_NONE); } - else - { - CG_ChangeWeapon( WP_NONE ); - } - cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_VOF|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_APH); + cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_VOF | CG_OVERRIDE_3RD_PERSON_POF | CG_OVERRIDE_3RD_PERSON_APH); cg.overrides.thirdPersonRange = cg.overrides.thirdPersonVertOffset = cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonAlpha = cg_thirdPersonAlpha.value; pEnt->client->ps.viewheight = pEnt->maxs[2] + STANDARD_VIEWHEIGHT_OFFSET; - //pEnt->mass = 10; - } - else - {//become an atst + // pEnt->mass = 10; + } else { // become an atst pEnt->NPC_type = "atst"; pEnt->client->NPC_class = CLASS_ATST; pEnt->client->ps.eFlags |= EF_IN_ATST; pEnt->flags |= FL_SHIELDED; - //size - VectorSet( pEnt->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2 ); - VectorSet( pEnt->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2 ); + // size + VectorSet(pEnt->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2); + VectorSet(pEnt->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2); pEnt->client->crouchheight = ATST_MAXS2; pEnt->client->standheight = ATST_MAXS2; - if ( !atst ) - {//no pEnt to copy from - G_ChangePlayerModel( pEnt, "atst" ); - //G_SetG2PlayerModel( pEnt, "atst", NULL, NULL, NULL ); - NPC_SetAnim( pEnt, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE, 200 ); - } - else - { - G_RemovePlayerModel( pEnt ); - G_RemoveWeaponModels( pEnt ); - gi.G2API_CopyGhoul2Instance( atst->ghoul2, pEnt->ghoul2, -1 ); + if (!atst) { // no pEnt to copy from + G_ChangePlayerModel(pEnt, "atst"); + // G_SetG2PlayerModel( pEnt, "atst", NULL, NULL, NULL ); + NPC_SetAnim(pEnt, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE, 200); + } else { + G_RemovePlayerModel(pEnt); + G_RemoveWeaponModels(pEnt); + gi.G2API_CopyGhoul2Instance(atst->ghoul2, pEnt->ghoul2, -1); pEnt->playerModel = 0; - G_SetG2PlayerModelInfo( pEnt, "atst", NULL, NULL, NULL ); - //turn off hatch underside - gi.G2API_SetSurfaceOnOff( &pEnt->ghoul2[pEnt->playerModel], "head_hatchcover", 0x00000002/*G2SURFACEFLAG_OFF*/ ); - G_Sound( pEnt, G_SoundIndex( "sound/chars/atst/atst_hatch_close" )); + G_SetG2PlayerModelInfo(pEnt, "atst", NULL, NULL, NULL); + // turn off hatch underside + gi.G2API_SetSurfaceOnOff(&pEnt->ghoul2[pEnt->playerModel], "head_hatchcover", 0x00000002 /*G2SURFACEFLAG_OFF*/); + G_Sound(pEnt, G_SoundIndex("sound/chars/atst/atst_hatch_close")); } pEnt->s.radius = 320; - //weapon - gitem_t *item = FindItemForWeapon( WP_ATST_MAIN ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_ATST_SIDE ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - pEnt->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_ATST_MAIN )|( 1 << WP_ATST_SIDE ); + // weapon + gitem_t *item = FindItemForWeapon(WP_ATST_MAIN); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_ATST_SIDE); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + pEnt->client->ps.stats[STAT_WEAPONS] |= (1 << WP_ATST_MAIN) | (1 << WP_ATST_SIDE); pEnt->client->ps.ammo[weaponData[WP_ATST_MAIN].ammoIndex] = ammoData[weaponData[WP_ATST_MAIN].ammoIndex].max; pEnt->client->ps.ammo[weaponData[WP_ATST_SIDE].ammoIndex] = ammoData[weaponData[WP_ATST_SIDE].ammoIndex].max; - CG_ChangeWeapon( WP_ATST_MAIN ); - //HACKHACKHACKTEMP - item = FindItemForWeapon( WP_EMPLACED_GUN ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_ROCKET_LAUNCHER ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_BOWCASTER ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - //HACKHACKHACKTEMP - //FIXME: these get lost in load/save! Must use variables that are set every frame or saved/loaded - //camera - gi.cvar_set( "cg_thirdperson", "1" ); + CG_ChangeWeapon(WP_ATST_MAIN); + // HACKHACKHACKTEMP + item = FindItemForWeapon(WP_EMPLACED_GUN); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_ROCKET_LAUNCHER); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_BOWCASTER); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + // HACKHACKHACKTEMP + // FIXME: these get lost in load/save! Must use variables that are set every frame or saved/loaded + // camera + gi.cvar_set("cg_thirdperson", "1"); cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = 240; - //cg.overrides.thirdPersonVertOffset = 100; - //cg.overrides.thirdPersonPitchOffset = -30; - //FIXME: this gets stomped in pmove? + // cg.overrides.thirdPersonVertOffset = 100; + // cg.overrides.thirdPersonPitchOffset = -30; + // FIXME: this gets stomped in pmove? pEnt->client->ps.viewheight = 120; - //FIXME: setting these broke things very badly...? - //pEnt->client->standheight = 200; - //pEnt->client->crouchheight = 200; - //pEnt->mass = 300; - //movement - //pEnt->client->ps.speed = 0;//FIXME: override speed? - //FIXME: slow turn turning/can't turn if not moving? + // FIXME: setting these broke things very badly...? + // pEnt->client->standheight = 200; + // pEnt->client->crouchheight = 200; + // pEnt->mass = 300; + // movement + // pEnt->client->ps.speed = 0;//FIXME: override speed? + // FIXME: slow turn turning/can't turn if not moving? } } #endif //_JK2MP // Animate the vehicle and it's riders. -void Animate( Vehicle_t *pVeh ) -{ +void Animate(Vehicle_t *pVeh) { // Validate a pilot rider. - if ( pVeh->m_pPilot ) - { - if (pVeh->m_pVehicleInfo->AnimateRiders) - { - pVeh->m_pVehicleInfo->AnimateRiders( pVeh ); + if (pVeh->m_pPilot) { + if (pVeh->m_pVehicleInfo->AnimateRiders) { + pVeh->m_pVehicleInfo->AnimateRiders(pVeh); } } - pVeh->m_pVehicleInfo->AnimateVehicle( pVeh ); + pVeh->m_pVehicleInfo->AnimateVehicle(pVeh); } // Determine whether this entity is able to board this vehicle or not. -bool ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +bool ValidateBoard(Vehicle_t *pVeh, bgEntity_t *pEnt) { // Determine where the entity is entering the vehicle from (left, right, or back). vec3_t vVehToEnt; vec3_t vVehDir; @@ -537,39 +470,29 @@ bool ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) vec3_t vVehAngles; float fDot; - if ( pVeh->m_iDieTime>0) - { + if (pVeh->m_iDieTime > 0) { return false; } - if ( ent->health <= 0 ) - {//dead men can't ride vehicles + if (ent->health <= 0) { // dead men can't ride vehicles return false; } - if ( pVeh->m_pPilot != NULL ) - {//already have a driver! - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - {//I know, I know, this should by in the fighters's validateboard() - //can never steal a fighter from it's pilot + if (pVeh->m_pPilot != NULL) { // already have a driver! + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // I know, I know, this should by in the fighters's validateboard() + // can never steal a fighter from it's pilot return false; - } - else if ( pVeh->m_pVehicleInfo->type == VH_WALKER ) - {//I know, I know, this should by in the walker's validateboard() - if ( !ent->client || ent->client->ps.groundEntityNum != parent->s.number ) - {//can only steal an occupied AT-ST if you're on top (by the hatch) + } else if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // I know, I know, this should by in the walker's validateboard() + if (!ent->client || ent->client->ps.groundEntityNum != parent->s.number) { // can only steal an occupied AT-ST if you're on top (by the hatch) return false; } - } - else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) - {//you can only steal the bike from the driver if you landed on the driver or bike - return (pVeh->m_iBoarding==VEH_MOUNT_THROW_LEFT || pVeh->m_iBoarding==VEH_MOUNT_THROW_RIGHT); + } else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // you can only steal the bike from the driver if you landed on the driver or bike + return (pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT || pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT); } } // Yes, you shouldn't have put this here (you 'should' have made an 'overriden' ValidateBoard func), but in this // instance it's more than adequate (which is why I do it too :-). Making a whole other function for this is silly. - else if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { + else if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // If you're a fighter, you allow everyone to enter you from all directions. return true; } @@ -578,40 +501,36 @@ bool ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) VectorSet(vVehAngles, 0, parent->currentAngles[YAW], 0); // Vector from Entity to Vehicle. - VectorSubtract( ent->currentOrigin, parent->currentOrigin, vVehToEnt ); + VectorSubtract(ent->currentOrigin, parent->currentOrigin, vVehToEnt); vVehToEnt[2] = 0; - VectorNormalize( vVehToEnt ); + VectorNormalize(vVehToEnt); // Get the right vector. - AngleVectors( vVehAngles, NULL, vVehDir, NULL ); - VectorNormalize( vVehDir ); + AngleVectors(vVehAngles, NULL, vVehDir, NULL); + VectorNormalize(vVehDir); // Find the angle between the vehicle right vector and the vehicle to entity vector. - fDot = DotProduct( vVehToEnt, vVehDir ); + fDot = DotProduct(vVehToEnt, vVehDir); // If the entity is within a certain angle to the left of the vehicle... - if ( fDot >= 0.5f ) - { + if (fDot >= 0.5f) { // Right board. pVeh->m_iBoarding = -2; - } - else if ( fDot <= -0.5f ) - { + } else if (fDot <= -0.5f) { // Left board. pVeh->m_iBoarding = -1; } // Maybe they're trying to board from the back... - else - { + else { // The forward vector of the vehicle. - // AngleVectors( vVehAngles, vVehDir, NULL, NULL ); - // VectorNormalize( vVehDir ); + // AngleVectors( vVehAngles, vVehDir, NULL, NULL ); + // VectorNormalize( vVehDir ); // Find the angle between the vehicle forward and the vehicle to entity vector. - // fDot = DotProduct( vVehToEnt, vVehDir ); + // fDot = DotProduct( vVehToEnt, vVehDir ); // If the entity is within a certain angle behind the vehicle... - //if ( fDot <= -0.85f ) + // if ( fDot <= -0.85f ) { // Jump board. pVeh->m_iBoarding = -3; @@ -619,15 +538,14 @@ bool ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) } // If for some reason we couldn't board, leave... - if ( pVeh->m_iBoarding > -1 ) + if (pVeh->m_iBoarding > -1) return false; return true; } // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +bool Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { vec3_t vPlayerDir; gentity_t *ent = (gentity_t *)pEnt; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; @@ -635,20 +553,20 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) // If it's not a valid entity, OR if the vehicle is blowing up (it's dead), OR it's not // empty, OR we're already being boarded, OR the person trying to get on us is already // in a vehicle (that was a fun bug :-), leave! - if ( !ent || parent->health <= 0 /*|| !( parent->client->ps.eFlags & EF_EMPTY_VEHICLE )*/ || (pVeh->m_iBoarding > 0) || + if (!ent || parent->health <= 0 /*|| !( parent->client->ps.eFlags & EF_EMPTY_VEHICLE )*/ || (pVeh->m_iBoarding > 0) || #ifdef _JK2MP - ( ent->client->ps.m_iVehicleNum ) ) + (ent->client->ps.m_iVehicleNum)) #else - ( ent->s.m_iVehicleNum != 0 ) ) + (ent->s.m_iVehicleNum != 0)) #endif return false; // Bucking so we can't do anything (NOTE: Should probably be a better name since fighters don't buck...). - if ( pVeh->m_ulFlags & VEH_BUCKING ) + if (pVeh->m_ulFlags & VEH_BUCKING) return false; // Validate the entity's ability to board this vehicle. - if ( !pVeh->m_pVehicleInfo->ValidateBoard( pVeh, pEnt ) ) + if (!pVeh->m_pVehicleInfo->ValidateBoard(pVeh, pEnt)) return false; // FIXME FIXME!!! Ask Mike monday where ent->client->ps.eFlags might be getting changed!!! It is always 0 (when it should @@ -656,31 +574,24 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) // Tell everybody their status. // ALWAYS let the player be the pilot. - if ( ent->s.number < MAX_CLIENTS ) - { + if (ent->s.number < MAX_CLIENTS) { pVeh->m_pOldPilot = pVeh->m_pPilot; - #ifdef _JK2MP - if ( !pVeh->m_pPilot ) - { //become the pilot, if there isn't one now - pVeh->m_pVehicleInfo->SetPilot( pVeh, (bgEntity_t *)ent ); + if (!pVeh->m_pPilot) { // become the pilot, if there isn't one now + pVeh->m_pVehicleInfo->SetPilot(pVeh, (bgEntity_t *)ent); } // If we're not yet full... - else if ( pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers ) - { + else if (pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers) { int i; // Find an empty slot and put that passenger here. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] == NULL ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i] == NULL) { pVeh->m_ppPassengers[i] = (bgEntity_t *)ent; #ifdef QAGAME - //Server just needs to tell client which passengernum he is - if ( ent->client ) - { - ent->client->ps.generic1 = i+1; + // Server just needs to tell client which passengernum he is + if (ent->client) { + ent->client->ps.generic1 = i + 1; } #endif break; @@ -689,22 +600,19 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) pVeh->m_iNumPassengers++; } // We're full, sorry... - else - { + else { return false; } ent->s.m_iVehicleNum = parent->s.number; - if (ent->client) - { + if (ent->client) { ent->client->ps.m_iVehicleNum = ent->s.m_iVehicleNum; } - if ( pVeh->m_pPilot == (bgEntity_t *)ent ) - { + if (pVeh->m_pPilot == (bgEntity_t *)ent) { parent->r.ownerNum = ent->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction } #else - pVeh->m_pVehicleInfo->SetPilot( pVeh, ent ); + pVeh->m_pVehicleInfo->SetPilot(pVeh, ent); ent->s.m_iVehicleNum = parent->s.number; parent->owner = ent; #endif @@ -712,13 +620,11 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) #ifdef QAGAME { gentity_t *gParent = (gentity_t *)parent; - if ( (gParent->spawnflags&2) ) - {//was being suspended - gParent->spawnflags &= ~2;//SUSPENDED - clear this spawnflag, no longer docked, okay to free-fall if not in space - //gParent->client->ps.eFlags &= ~EF_RADAROBJECT; - G_Sound( gParent, CHAN_AUTO, G_SoundIndex( "sound/vehicles/common/release.wav" ) ); - if ( gParent->fly_sound_debounce_time ) - {//we should drop like a rock for a few seconds + if ((gParent->spawnflags & 2)) { // was being suspended + gParent->spawnflags &= ~2; // SUSPENDED - clear this spawnflag, no longer docked, okay to free-fall if not in space + // gParent->client->ps.eFlags &= ~EF_RADAROBJECT; + G_Sound(gParent, CHAN_AUTO, G_SoundIndex("sound/vehicles/common/release.wav")); + if (gParent->fly_sound_debounce_time) { // we should drop like a rock for a few seconds pVeh->m_iDropTime = level.time + gParent->fly_sound_debounce_time; } } @@ -726,12 +632,12 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) #endif #ifndef _JK2MP - gi.cvar_set( "cg_thirdperson", "1" ); //go to third person - CG_CenterPrint( "@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.86 ); //tell them how to get out! + gi.cvar_set("cg_thirdperson", "1"); // go to third person + CG_CenterPrint("@SP_INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.86); // tell them how to get out! #endif - //FIXME: rider needs to look in vehicle's direction when he gets in - // Clear these since they're used to turn the vehicle now. + // FIXME: rider needs to look in vehicle's direction when he gets in + // Clear these since they're used to turn the vehicle now. /*SetClientViewAngle( ent, pVeh->m_vOrientation ); memset( &parent->client->usercmd, 0, sizeof( usercmd_t ) ); memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); @@ -739,33 +645,28 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) VectorClear( parent->client->ps.delta_angles );*/ // Set the looping sound only when there is a pilot (when the vehicle is "on"). - if ( pVeh->m_pVehicleInfo->soundLoop ) - { + if (pVeh->m_pVehicleInfo->soundLoop) { #ifdef _JK2MP parent->client->ps.loopSound = parent->s.loopSound = pVeh->m_pVehicleInfo->soundLoop; #else parent->s.loopSound = pVeh->m_pVehicleInfo->soundLoop; #endif } - } - else - { + } else { // If there's no pilot, try to drive this vehicle. - if ( pVeh->m_pPilot == NULL ) - { + if (pVeh->m_pPilot == NULL) { #ifdef _JK2MP - pVeh->m_pVehicleInfo->SetPilot( pVeh, (bgEntity_t *)ent ); + pVeh->m_pVehicleInfo->SetPilot(pVeh, (bgEntity_t *)ent); // TODO: Set pilot should do all this stuff.... parent->r.ownerNum = ent->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction #else - pVeh->m_pVehicleInfo->SetPilot( pVeh, ent ); + pVeh->m_pVehicleInfo->SetPilot(pVeh, ent); // TODO: Set pilot should do all this stuff.... parent->owner = ent; #endif // Set the looping sound only when there is a pilot (when the vehicle is "on"). - if ( pVeh->m_pVehicleInfo->soundLoop ) - { + if (pVeh->m_pVehicleInfo->soundLoop) { #ifdef _JK2MP parent->client->ps.loopSound = parent->s.loopSound = pVeh->m_pVehicleInfo->soundLoop; #else @@ -774,11 +675,10 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) } parent->client->ps.speed = 0; - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); } // We're full, sorry... - else - { + else { return false; } } @@ -787,113 +687,100 @@ bool Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) #ifdef _JK2MP ent->client->ps.m_iVehicleNum = parent->s.number; ent->r.ownerNum = parent->s.number; - ent->s.owner = ent->r.ownerNum; //for prediction - if (pVeh->m_pPilot == (bgEntity_t *)ent) - { - parent->client->ps.m_iVehicleNum = ent->s.number+1; //always gonna be under MAX_CLIENTS so no worries about 1 byte overflow + ent->s.owner = ent->r.ownerNum; // for prediction + if (pVeh->m_pPilot == (bgEntity_t *)ent) { + parent->client->ps.m_iVehicleNum = ent->s.number + 1; // always gonna be under MAX_CLIENTS so no worries about 1 byte overflow } #else ent->s.m_iVehicleNum = parent->s.number; ent->owner = parent; - parent->s.m_iVehicleNum = ent->s.number+1; + parent->s.m_iVehicleNum = ent->s.number + 1; #endif - //memset( &ent->client->usercmd, 0, sizeof( usercmd_t ) ); + // memset( &ent->client->usercmd, 0, sizeof( usercmd_t ) ); - //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player - if ( pVeh->m_pVehicleInfo->numHands == 2 ) - {//switch to vehicle weapon -#ifndef _JK2MP //rwwFIXMEFIXMEFIXME - if (ent->s.numberclient->ps.stats[ STAT_WEAPONS ] |= (1<m_pVehicleInfo->numHands == 2) { // switch to vehicle weapon +#ifndef _JK2MP // rwwFIXMEFIXMEFIXME + if (ent->s.number < MAX_CLIENTS) { // Riding means you get WP_NONE + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_NONE); } - if ( (ent->client->ps.weapon != WP_SABER - && ent->client->ps.weapon != WP_BLASTER) || !(pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_SPEEDER)) - {//switch to weapon none? - if (ent->s.numberclient->ps.weapon != WP_SABER && ent->client->ps.weapon != WP_BLASTER) || + !(pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_SPEEDER)) { // switch to weapon none? + if (ent->s.number < MAX_CLIENTS) { CG_ChangeWeapon(WP_NONE); } ent->client->ps.weapon = WP_NONE; - G_RemoveWeaponModels( ent ); + G_RemoveWeaponModels(ent); } #endif } - if ( pVeh->m_pVehicleInfo->hideRider ) - {//hide the rider - pVeh->m_pVehicleInfo->Ghost( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pVehicleInfo->hideRider) { // hide the rider + pVeh->m_pVehicleInfo->Ghost(pVeh, (bgEntity_t *)ent); } // Play the start sounds - if ( pVeh->m_pVehicleInfo->soundOn ) - { + if (pVeh->m_pVehicleInfo->soundOn) { #ifdef _JK2MP - G_Sound( parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn ); + G_Sound(parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn); #else // NOTE: Use this type so it's spatialized and updates play origin as bike moves - MCG - G_SoundIndexOnEnt( parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn ); + G_SoundIndexOnEnt(parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn); #endif } - VectorCopy( pVeh->m_vOrientation, vPlayerDir ); + VectorCopy(pVeh->m_vOrientation, vPlayerDir); vPlayerDir[ROLL] = 0; - SetClientViewAngle( ent, vPlayerDir ); + SetClientViewAngle(ent, vPlayerDir); return true; } -bool VEH_TryEject( Vehicle_t *pVeh, - gentity_t *parent, - gentity_t *ent, - int ejectDir, - vec3_t vExitPos ) -{ - float fBias; - float fVehDiag; - float fEntDiag; - vec3_t vEntMins, vEntMaxs, vVehLeaveDir, vVehAngles; - trace_t m_ExitTrace; +bool VEH_TryEject(Vehicle_t *pVeh, gentity_t *parent, gentity_t *ent, int ejectDir, vec3_t vExitPos) { + float fBias; + float fVehDiag; + float fEntDiag; + vec3_t vEntMins, vEntMaxs, vVehLeaveDir, vVehAngles; + trace_t m_ExitTrace; // Make sure that the entity is not 'stuck' inside the vehicle (since their bboxes will now intersect). // This makes the entity leave the vehicle from the right side. VectorSet(vVehAngles, 0, parent->currentAngles[YAW], 0); - switch ( ejectDir ) - { - // Left. - case VEH_EJECT_LEFT: - AngleVectors( vVehAngles, NULL, vVehLeaveDir, NULL ); - vVehLeaveDir[0] = -vVehLeaveDir[0]; - vVehLeaveDir[1] = -vVehLeaveDir[1]; - vVehLeaveDir[2] = -vVehLeaveDir[2]; - break; - // Right. - case VEH_EJECT_RIGHT: - AngleVectors( vVehAngles, NULL, vVehLeaveDir, NULL ); - break; - // Front. - case VEH_EJECT_FRONT: - AngleVectors( vVehAngles, vVehLeaveDir, NULL, NULL ); - break; - // Rear. - case VEH_EJECT_REAR: - AngleVectors( vVehAngles, vVehLeaveDir, NULL, NULL ); - vVehLeaveDir[0] = -vVehLeaveDir[0]; - vVehLeaveDir[1] = -vVehLeaveDir[1]; - vVehLeaveDir[2] = -vVehLeaveDir[2]; - break; - // Top. - case VEH_EJECT_TOP: - AngleVectors( vVehAngles, NULL, NULL, vVehLeaveDir ); - break; - // Bottom?. - case VEH_EJECT_BOTTOM: - break; + switch (ejectDir) { + // Left. + case VEH_EJECT_LEFT: + AngleVectors(vVehAngles, NULL, vVehLeaveDir, NULL); + vVehLeaveDir[0] = -vVehLeaveDir[0]; + vVehLeaveDir[1] = -vVehLeaveDir[1]; + vVehLeaveDir[2] = -vVehLeaveDir[2]; + break; + // Right. + case VEH_EJECT_RIGHT: + AngleVectors(vVehAngles, NULL, vVehLeaveDir, NULL); + break; + // Front. + case VEH_EJECT_FRONT: + AngleVectors(vVehAngles, vVehLeaveDir, NULL, NULL); + break; + // Rear. + case VEH_EJECT_REAR: + AngleVectors(vVehAngles, vVehLeaveDir, NULL, NULL); + vVehLeaveDir[0] = -vVehLeaveDir[0]; + vVehLeaveDir[1] = -vVehLeaveDir[1]; + vVehLeaveDir[2] = -vVehLeaveDir[2]; + break; + // Top. + case VEH_EJECT_TOP: + AngleVectors(vVehAngles, NULL, NULL, vVehLeaveDir); + break; + // Bottom?. + case VEH_EJECT_BOTTOM: + break; } - VectorNormalize( vVehLeaveDir ); - //NOTE: not sure why following line was needed - MCG - //pVeh->m_EjectDir = VEH_EJECT_LEFT; + VectorNormalize(vVehLeaveDir); + // NOTE: not sure why following line was needed - MCG + // pVeh->m_EjectDir = VEH_EJECT_LEFT; // Since (as of this time) the collidable geometry of the entity is just an axis // aligned box, we need to get the diagonal length of it in case we come out on that side. @@ -902,28 +789,27 @@ bool VEH_TryEject( Vehicle_t *pVeh, // TODO: DO diagonal for entity. fBias = 1.0f; - if (pVeh->m_pVehicleInfo->type == VH_WALKER) - { //hacktastic! + if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // hacktastic! fBias += 0.2f; } - VectorCopy( ent->currentOrigin, vExitPos ); - fVehDiag = sqrtf( ( parent->maxs[0] * parent->maxs[0] ) + ( parent->maxs[1] * parent->maxs[1] ) ); - VectorCopy( ent->maxs, vEntMaxs ); + VectorCopy(ent->currentOrigin, vExitPos); + fVehDiag = sqrtf((parent->maxs[0] * parent->maxs[0]) + (parent->maxs[1] * parent->maxs[1])); + VectorCopy(ent->maxs, vEntMaxs); #ifdef _JK2MP - if ( ent->s.number < MAX_CLIENTS ) - {//for some reason, in MP, player client mins and maxs are never stored permanently, just set to these hardcoded numbers in PMove + if (ent->s.number < + MAX_CLIENTS) { // for some reason, in MP, player client mins and maxs are never stored permanently, just set to these hardcoded numbers in PMove vEntMaxs[0] = 15; vEntMaxs[1] = 15; } #endif - fEntDiag = sqrtf( ( vEntMaxs[0] * vEntMaxs[0] ) + ( vEntMaxs[1] * vEntMaxs[1] ) ); - vVehLeaveDir[0] *= ( fVehDiag + fEntDiag ) * fBias; // x - vVehLeaveDir[1] *= ( fVehDiag + fEntDiag ) * fBias; // y - vVehLeaveDir[2] *= ( fVehDiag + fEntDiag ) * fBias; - VectorAdd( vExitPos, vVehLeaveDir, vExitPos ); + fEntDiag = sqrtf((vEntMaxs[0] * vEntMaxs[0]) + (vEntMaxs[1] * vEntMaxs[1])); + vVehLeaveDir[0] *= (fVehDiag + fEntDiag) * fBias; // x + vVehLeaveDir[1] *= (fVehDiag + fEntDiag) * fBias; // y + vVehLeaveDir[2] *= (fVehDiag + fEntDiag) * fBias; + VectorAdd(vExitPos, vVehLeaveDir, vExitPos); - //we actually could end up *not* getting off if the trace fails... - // Check to see if this new position is a valid place for our entity to go. + // we actually could end up *not* getting off if the trace fails... + // Check to see if this new position is a valid place for our entity to go. #ifdef _JK2MP VectorSet(vEntMins, -15.0f, -15.0f, DEFAULT_MINS_2); VectorSet(vEntMaxs, 15.0f, 15.0f, DEFAULT_MAXS_2); @@ -931,32 +817,29 @@ bool VEH_TryEject( Vehicle_t *pVeh, VectorCopy(ent->mins, vEntMins); VectorCopy(ent->maxs, vEntMaxs); #endif - G_VehicleTrace( &m_ExitTrace, ent->currentOrigin, vEntMins, vEntMaxs, vExitPos, ent->s.number, ent->clipmask ); + G_VehicleTrace(&m_ExitTrace, ent->currentOrigin, vEntMins, vEntMaxs, vExitPos, ent->s.number, ent->clipmask); - if ( m_ExitTrace.allsolid//in solid - || m_ExitTrace.startsolid) - { + if (m_ExitTrace.allsolid // in solid + || m_ExitTrace.startsolid) { return false; } // If the trace hit something, we can't go there! - if ( m_ExitTrace.fraction < 1.0f ) - {//not totally clear + if (m_ExitTrace.fraction < 1.0f) { // not totally clear #ifdef _JK2MP - if ( (parent->clipmask&ent->r.contents) )//vehicle could actually get stuck on body + if ((parent->clipmask & ent->r.contents)) // vehicle could actually get stuck on body #else - if ( (parent->clipmask&ent->contents) )//vehicle could actually get stuck on body + if ((parent->clipmask & ent->contents)) // vehicle could actually get stuck on body #endif - {//the trace hit the vehicle, don't let them get out, just in case + { // the trace hit the vehicle, don't let them get out, just in case return false; } - //otherwise, use the trace.endpos - VectorCopy( m_ExitTrace.endpos, vExitPos ); + // otherwise, use the trace.endpos + VectorCopy(m_ExitTrace.endpos, vExitPos); } return true; } -void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) -{ +void G_EjectDroidUnit(Vehicle_t *pVeh, qboolean kill) { pVeh->m_pDroidUnit->s.m_iVehicleNum = ENTITYNUM_NONE; #ifdef _JK2MP pVeh->m_pDroidUnit->s.owner = ENTITYNUM_NONE; @@ -969,15 +852,13 @@ void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) gentity_t *droidEnt = (gentity_t *)pVeh->m_pDroidUnit; droidEnt->flags &= ~FL_UNDYING; droidEnt->r.ownerNum = ENTITYNUM_NONE; - if ( droidEnt->client ) - { + if (droidEnt->client) { droidEnt->client->ps.m_iVehicleNum = ENTITYNUM_NONE; } - if ( kill ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (kill) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(droidEnt->s.number, CHAN_VOICE); - G_Damage( droidEnt, NULL, NULL, NULL, droidEnt->s.origin, 10000, 0, MOD_SUICIDE );//FIXME: proper MOD? Get from vehicle? + G_Damage(droidEnt, NULL, NULL, NULL, droidEnt->s.origin, 10000, 0, MOD_SUICIDE); // FIXME: proper MOD? Get from vehicle? } } #endif @@ -985,51 +866,42 @@ void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) } // Eject the pilot from the vehicle. -bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) -{ - gentity_t *parent; - vec3_t vExitPos; +bool Eject(Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject) { + gentity_t *parent; + vec3_t vExitPos; #ifndef _JK2MP - vec3_t vPlayerDir; + vec3_t vPlayerDir; #endif - gentity_t *ent = (gentity_t *)pEnt; - int firstEjectDir; + gentity_t *ent = (gentity_t *)pEnt; + int firstEjectDir; #ifdef _JK2MP - qboolean taintedRider = qfalse; - qboolean deadRider = qfalse; + qboolean taintedRider = qfalse; + qboolean deadRider = qfalse; - if ( pEnt == pVeh->m_pDroidUnit ) - { - G_EjectDroidUnit( pVeh, qfalse ); + if (pEnt == pVeh->m_pDroidUnit) { + G_EjectDroidUnit(pVeh, qfalse); return true; } - if (ent) - { - if (!ent->inuse || !ent->client || ent->client->pers.connected != CON_CONNECTED) - { + if (ent) { + if (!ent->inuse || !ent->client || ent->client->pers.connected != CON_CONNECTED) { taintedRider = qtrue; parent = (gentity_t *)pVeh->m_pParentEntity; goto getItOutOfMe; - } - else if (ent->health < 1) - { + } else if (ent->health < 1) { deadRider = qtrue; } } #endif // Validate. - if ( !ent ) - { + if (!ent) { return false; } - if ( !forceEject ) - { - if ( !( pVeh->m_iBoarding == 0 || pVeh->m_iBoarding == -999 || ( pVeh->m_iBoarding < -3 && pVeh->m_iBoarding >= -9 ) ) ) - { -#ifdef _JK2MP //I don't care, if he's dead get him off even if he died while boarding + if (!forceEject) { + if (!(pVeh->m_iBoarding == 0 || pVeh->m_iBoarding == -999 || (pVeh->m_iBoarding < -3 && pVeh->m_iBoarding >= -9))) { +#ifdef _JK2MP // I don't care, if he's dead get him off even if he died while boarding deadRider = qtrue; pVeh->m_iBoarding = 0; pVeh->m_bWasBoarding = false; @@ -1039,66 +911,55 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } } -/*#ifndef _JK2MP //rwwFIXMEFIXMEFIXME - if (ent->s.numberclient->ps.weapon = WP_NONE; - G_RemoveWeaponModels( ent ); -#endif*/ + /*#ifndef _JK2MP //rwwFIXMEFIXMEFIXME + if (ent->s.numberclient->ps.weapon = WP_NONE; + G_RemoveWeaponModels( ent ); + #endif*/ parent = (gentity_t *)pVeh->m_pParentEntity; - //Try ejecting in every direction - if ( pVeh->m_EjectDir < VEH_EJECT_LEFT ) - { + // Try ejecting in every direction + if (pVeh->m_EjectDir < VEH_EJECT_LEFT) { pVeh->m_EjectDir = VEH_EJECT_LEFT; - } - else if ( pVeh->m_EjectDir > VEH_EJECT_BOTTOM ) - { + } else if (pVeh->m_EjectDir > VEH_EJECT_BOTTOM) { pVeh->m_EjectDir = VEH_EJECT_BOTTOM; } firstEjectDir = pVeh->m_EjectDir; - while ( !VEH_TryEject( pVeh, parent, ent, pVeh->m_EjectDir, vExitPos ) ) - { + while (!VEH_TryEject(pVeh, parent, ent, pVeh->m_EjectDir, vExitPos)) { pVeh->m_EjectDir++; - if ( pVeh->m_EjectDir > VEH_EJECT_BOTTOM ) - { + if (pVeh->m_EjectDir > VEH_EJECT_BOTTOM) { pVeh->m_EjectDir = VEH_EJECT_LEFT; } - if ( pVeh->m_EjectDir == firstEjectDir ) - {//they all failed + if (pVeh->m_EjectDir == firstEjectDir) { // they all failed #ifdef _JK2MP - if (!deadRider) - { //if he's dead.. just shove him in solid, who cares. + if (!deadRider) { // if he's dead.. just shove him in solid, who cares. return false; } #endif - if ( forceEject ) - {//we want to always get out, just eject him here - VectorCopy( ent->currentOrigin, vExitPos ); + if (forceEject) { // we want to always get out, just eject him here + VectorCopy(ent->currentOrigin, vExitPos); break; - } - else - {//can't eject + } else { // can't eject return false; } } } // Move them to the exit position. - G_SetOrigin( ent, vExitPos ); + G_SetOrigin(ent, vExitPos); #ifdef _JK2MP VectorCopy(ent->currentOrigin, ent->client->ps.origin); - trap_LinkEntity( ent ); + trap_LinkEntity(ent); #else - gi.linkentity( ent ); + gi.linkentity(ent); #endif // If it's the player, stop overrides. - if ( ent->s.number < MAX_CLIENTS ) - { + if (ent->s.number < MAX_CLIENTS) { #ifndef _JK2MP cg.overrides.active = 0; #else @@ -1106,13 +967,12 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) #endif } -#ifdef _JK2MP //in MP if someone disconnects on us, we still have to clear our owner +#ifdef _JK2MP // in MP if someone disconnects on us, we still have to clear our owner getItOutOfMe: #endif // If he's the pilot... - if ( (gentity_t *)pVeh->m_pPilot == ent ) - { + if ((gentity_t *)pVeh->m_pPilot == ent) { #ifdef _JK2MP int j = 0; #endif @@ -1120,51 +980,45 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) pVeh->m_pPilot = NULL; #ifdef _JK2MP parent->r.ownerNum = ENTITYNUM_NONE; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction - //keep these current angles - //SetClientViewAngle( parent, pVeh->m_vOrientation ); - memset( &parent->client->pers.cmd, 0, sizeof( usercmd_t ) ); + // keep these current angles + // SetClientViewAngle( parent, pVeh->m_vOrientation ); + memset(&parent->client->pers.cmd, 0, sizeof(usercmd_t)); #else parent->owner = NULL; - //keep these current angles - //SetClientViewAngle( parent, pVeh->m_vOrientation ); - memset( &parent->client->usercmd, 0, sizeof( usercmd_t ) ); + // keep these current angles + // SetClientViewAngle( parent, pVeh->m_vOrientation ); + memset(&parent->client->usercmd, 0, sizeof(usercmd_t)); #endif - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); -#ifdef _JK2MP //if there are some passengers, promote the first passenger to pilot - while (j < pVeh->m_iNumPassengers) - { - if (pVeh->m_ppPassengers[j]) - { +#ifdef _JK2MP // if there are some passengers, promote the first passenger to pilot + while (j < pVeh->m_iNumPassengers) { + if (pVeh->m_ppPassengers[j]) { int k = 1; - pVeh->m_pVehicleInfo->SetPilot( pVeh, pVeh->m_ppPassengers[j] ); + pVeh->m_pVehicleInfo->SetPilot(pVeh, pVeh->m_ppPassengers[j]); parent->r.ownerNum = pVeh->m_ppPassengers[j]->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction - parent->client->ps.m_iVehicleNum = pVeh->m_ppPassengers[j]->s.number+1; + parent->s.owner = parent->r.ownerNum; // for prediction + parent->client->ps.m_iVehicleNum = pVeh->m_ppPassengers[j]->s.number + 1; - //rearrange the passenger slots now.. + // rearrange the passenger slots now.. #ifdef QAGAME - //Server just needs to tell client he's not a passenger anymore - if ( ((gentity_t *)pVeh->m_ppPassengers[j])->client ) - { + // Server just needs to tell client he's not a passenger anymore + if (((gentity_t *)pVeh->m_ppPassengers[j])->client) { ((gentity_t *)pVeh->m_ppPassengers[j])->client->ps.generic1 = 0; } #endif pVeh->m_ppPassengers[j] = NULL; - while (k < pVeh->m_iNumPassengers) - { - if (!pVeh->m_ppPassengers[k-1]) - { //move down - pVeh->m_ppPassengers[k-1] = pVeh->m_ppPassengers[k]; + while (k < pVeh->m_iNumPassengers) { + if (!pVeh->m_ppPassengers[k - 1]) { // move down + pVeh->m_ppPassengers[k - 1] = pVeh->m_ppPassengers[k]; pVeh->m_ppPassengers[k] = NULL; #ifdef QAGAME - //Server just needs to tell client which passenger he is - if ( ((gentity_t *)pVeh->m_ppPassengers[k-1])->client ) - { - ((gentity_t *)pVeh->m_ppPassengers[k-1])->client->ps.generic1 = k; + // Server just needs to tell client which passenger he is + if (((gentity_t *)pVeh->m_ppPassengers[k - 1])->client) { + ((gentity_t *)pVeh->m_ppPassengers[k - 1])->client->ps.generic1 = k; } #endif } @@ -1177,27 +1031,22 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) j++; } #endif - } - else if (ent==(gentity_t *)pVeh->m_pOldPilot) - { + } else if (ent == (gentity_t *)pVeh->m_pOldPilot) { pVeh->m_pOldPilot = 0; } -#ifdef _JK2MP //I hate adding these! - if (!taintedRider) - { +#ifdef _JK2MP // I hate adding these! + if (!taintedRider) { #endif - if ( pVeh->m_pVehicleInfo->hideRider ) - { - pVeh->m_pVehicleInfo->UnGhost( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pVehicleInfo->hideRider) { + pVeh->m_pVehicleInfo->UnGhost(pVeh, (bgEntity_t *)ent); } #ifdef _JK2MP } #endif // If the vehicle now has no pilot... - if ( pVeh->m_pPilot == NULL ) - { + if (pVeh->m_pPilot == NULL) { #ifdef _JK2MP parent->client->ps.loopSound = parent->s.loopSound = 0; #else @@ -1212,8 +1061,7 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } #ifdef _JK2MP - if (taintedRider) - { //you can go now + if (taintedRider) { // you can go now pVeh->m_iBoarding = level.time + 1000; return true; } @@ -1223,15 +1071,14 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) #ifdef _JK2MP ent->client->ps.m_iVehicleNum = 0; ent->r.ownerNum = ENTITYNUM_NONE; - ent->s.owner = ent->r.ownerNum; //for prediction + ent->s.owner = ent->r.ownerNum; // for prediction ent->client->ps.viewangles[PITCH] = 0.0f; ent->client->ps.viewangles[ROLL] = 0.0f; ent->client->ps.viewangles[YAW] = pVeh->m_vOrientation[YAW]; SetClientViewAngle(ent, ent->client->ps.viewangles); - if (ent->client->solidHack) - { + if (ent->client->solidHack) { ent->client->solidHack = 0; ent->r.contents = CONTENTS_BODY; } @@ -1241,55 +1088,52 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) ent->s.m_iVehicleNum = 0; // Jump out. -/* if ( ent->client->ps.velocity[2] < JUMP_VELOCITY ) - { - ent->client->ps.velocity[2] = JUMP_VELOCITY; - } - else - { - ent->client->ps.velocity[2] += JUMP_VELOCITY; - }*/ + /* if ( ent->client->ps.velocity[2] < JUMP_VELOCITY ) + { + ent->client->ps.velocity[2] = JUMP_VELOCITY; + } + else + { + ent->client->ps.velocity[2] += JUMP_VELOCITY; + }*/ // Make sure entity is facing the direction it got off at. #ifndef _JK2MP - VectorCopy( pVeh->m_vOrientation, vPlayerDir ); + VectorCopy(pVeh->m_vOrientation, vPlayerDir); vPlayerDir[ROLL] = 0; - SetClientViewAngle( ent, vPlayerDir ); + SetClientViewAngle(ent, vPlayerDir); #endif - //if was using vehicle weapon, remove it and switch to normal weapon when hop out... - if ( ent->client->ps.weapon == WP_NONE ) - {//FIXME: check against this vehicle's gun from the g_vehicleInfo table - //remove the vehicle's weapon from me - //ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_EMPLACED_GUN ); - //ent->client->ps.ammo[weaponData[WP_EMPLACED_GUN].ammoIndex] = 0;//maybe store this ammo on the vehicle before clearing it? - //switch back to a normal weapon we're carrying + // if was using vehicle weapon, remove it and switch to normal weapon when hop out... + if (ent->client->ps.weapon == WP_NONE) { // FIXME: check against this vehicle's gun from the g_vehicleInfo table + // remove the vehicle's weapon from me + // ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_EMPLACED_GUN ); + // ent->client->ps.ammo[weaponData[WP_EMPLACED_GUN].ammoIndex] = 0;//maybe store this ammo on the vehicle before + // clearing it? switch back to a normal weapon we're carrying - //FIXME: store the weapon we were using when we got on and restore that when hop off -/* if ( (ent->client->ps.stats[STAT_WEAPONS]&(1< WP_NONE; checkWp-- ) - { - if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<client->ps.stats[STAT_WEAPONS]&(1< WP_NONE; checkWp-- ) + { + if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<s.number && ent->client->ps.weapon != WP_SABER @@ -1298,11 +1142,11 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) gi.cvar_set( "cg_thirdperson", "0" ); }*/ #ifdef _JK2MP - BG_SetLegsAnimTimer( &ent->client->ps, 0 ); - BG_SetTorsoAnimTimer( &ent->client->ps, 0 ); + BG_SetLegsAnimTimer(&ent->client->ps, 0); + BG_SetTorsoAnimTimer(&ent->client->ps, 0); #else - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, 0 ); + PM_SetLegsAnimTimer(ent, &ent->client->ps.legsAnimTimer, 0); + PM_SetTorsoAnimTimer(ent, &ent->client->ps.torsoAnimTimer, 0); #endif // Set how long until this vehicle can be boarded again. @@ -1312,8 +1156,7 @@ bool Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } // Eject all the inhabitants of this vehicle. -bool EjectAll( Vehicle_t *pVeh ) -{ +bool EjectAll(Vehicle_t *pVeh) { // TODO: Setup a default escape for ever vehicle type. pVeh->m_EjectDir = VEH_EJECT_TOP; @@ -1322,117 +1165,96 @@ bool EjectAll( Vehicle_t *pVeh ) pVeh->m_bWasBoarding = false; // Throw them off. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { #ifdef QAGAME - gentity_t *pilot = (gentity_t*)pVeh->m_pPilot; + gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; #endif - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); #ifdef QAGAME - if ( pVeh->m_pVehicleInfo->killRiderOnDeath && pilot ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (pVeh->m_pVehicleInfo->killRiderOnDeath && pilot) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(pilot->s.number, CHAN_VOICE); - G_Damage( pilot, player, player, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE ); + G_Damage(pilot, player, player, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE); } #endif } - if ( pVeh->m_pOldPilot ) - { + if (pVeh->m_pOldPilot) { #ifdef QAGAME - gentity_t *pilot = (gentity_t*)pVeh->m_pOldPilot; + gentity_t *pilot = (gentity_t *)pVeh->m_pOldPilot; #endif - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pOldPilot, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pOldPilot, qtrue); #ifdef QAGAME - if ( pVeh->m_pVehicleInfo->killRiderOnDeath && pilot ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (pVeh->m_pVehicleInfo->killRiderOnDeath && pilot) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(pilot->s.number, CHAN_VOICE); - G_Damage( pilot, player, player, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE ); + G_Damage(pilot, player, player, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE); } #endif } - if ( pVeh->m_pDroidUnit ) - { - G_EjectDroidUnit( pVeh, pVeh->m_pVehicleInfo->killRiderOnDeath ); + if (pVeh->m_pDroidUnit) { + G_EjectDroidUnit(pVeh, pVeh->m_pVehicleInfo->killRiderOnDeath); } return true; } // Start a delay until the vehicle explodes. -static void StartDeathDelay( Vehicle_t *pVeh, int iDelayTimeOverride ) -{ +static void StartDeathDelay(Vehicle_t *pVeh, int iDelayTimeOverride) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if ( iDelayTimeOverride ) - { + if (iDelayTimeOverride) { pVeh->m_iDieTime = level.time + iDelayTimeOverride; - } - else - { + } else { pVeh->m_iDieTime = level.time + pVeh->m_pVehicleInfo->explosionDelay; } #ifdef _JK2MP - if ( pVeh->m_pVehicleInfo->flammable ) - { - parent->client->ps.loopSound = parent->s.loopSound = G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); + if (pVeh->m_pVehicleInfo->flammable) { + parent->client->ps.loopSound = parent->s.loopSound = G_SoundIndex("sound/vehicles/common/fire_lp.wav"); } #else // Armor Gone Effects (Fire) //--------------------------- - if (pVeh->m_pVehicleInfo->iArmorGoneFX) - { - if (!(pVeh->m_ulFlags&VEH_ARMORGONE) && (pVeh->m_iArmor <= 0)) - { + if (pVeh->m_pVehicleInfo->iArmorGoneFX) { + if (!(pVeh->m_ulFlags & VEH_ARMORGONE) && (pVeh->m_iArmor <= 0)) { pVeh->m_ulFlags |= VEH_ARMORGONE; G_PlayEffect(pVeh->m_pVehicleInfo->iArmorGoneFX, parent->playerModel, parent->crotchBolt, parent->s.number, parent->currentOrigin, 1, qtrue); - parent->s.loopSound = G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); + parent->s.loopSound = G_SoundIndex("sound/vehicles/common/fire_lp.wav"); } } #endif } // Decide whether to explode the vehicle or not. -static void DeathUpdate( Vehicle_t *pVeh ) -{ +static void DeathUpdate(Vehicle_t *pVeh) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if ( level.time >= pVeh->m_iDieTime ) - { + if (level.time >= pVeh->m_iDieTime) { // If the vehicle is not empty. - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { #ifndef _JK2MP - if (pVeh->m_pPilot) - { - pVeh->m_pPilot->client->noRagTime = -1; // no ragdoll for you + if (pVeh->m_pPilot) { + pVeh->m_pPilot->client->noRagTime = -1; // no ragdoll for you } #endif - pVeh->m_pVehicleInfo->EjectAll( pVeh ); + pVeh->m_pVehicleInfo->EjectAll(pVeh); #ifdef _JK2MP - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { //if we've still got people in us, just kill the bastards - if ( pVeh->m_pPilot ) - { - //FIXME: does this give proper credit to the enemy who shot you down? - G_Damage((gentity_t *)pVeh->m_pPilot, (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, - NULL, pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_EXPLOSIVE); + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { // if we've still got people in us, just kill the bastards + if (pVeh->m_pPilot) { + // FIXME: does this give proper credit to the enemy who shot you down? + G_Damage((gentity_t *)pVeh->m_pPilot, (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, NULL, + pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_EXPLOSIVE); } - if ( pVeh->m_iNumPassengers ) - { + if (pVeh->m_iNumPassengers) { int i; - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] ) - { - //FIXME: does this give proper credit to the enemy who shot you down? - G_Damage((gentity_t *)pVeh->m_ppPassengers[i], (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, - NULL, pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_EXPLOSIVE); + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i]) { + // FIXME: does this give proper credit to the enemy who shot you down? + G_Damage((gentity_t *)pVeh->m_ppPassengers[i], (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, NULL, + pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_EXPLOSIVE); } } } @@ -1440,67 +1262,60 @@ static void DeathUpdate( Vehicle_t *pVeh ) #endif } - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { //explode now as long as we managed to kick everyone out - vec3_t lMins, lMaxs, bottom; - trace_t trace; - + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh)) { // explode now as long as we managed to kick everyone out + vec3_t lMins, lMaxs, bottom; + trace_t trace; #ifndef _JK2MP // Kill All Client Side Looping Effects //-------------------------------------- - if (pVeh->m_pVehicleInfo->iExhaustFX) - { - for (int i=0; (im_iExhaustTag[i]!=-1); i++) - { + if (pVeh->m_pVehicleInfo->iExhaustFX) { + for (int i = 0; (i < MAX_VEHICLE_EXHAUSTS && pVeh->m_iExhaustTag[i] != -1); i++) { G_StopEffect(pVeh->m_pVehicleInfo->iExhaustFX, parent->playerModel, pVeh->m_iExhaustTag[i], parent->s.number); } } - if (pVeh->m_pVehicleInfo->iArmorLowFX) - { - G_StopEffect(pVeh->m_pVehicleInfo->iArmorLowFX, parent->playerModel, parent->crotchBolt, parent->s.number); + if (pVeh->m_pVehicleInfo->iArmorLowFX) { + G_StopEffect(pVeh->m_pVehicleInfo->iArmorLowFX, parent->playerModel, parent->crotchBolt, parent->s.number); } - if (pVeh->m_pVehicleInfo->iArmorGoneFX) - { + if (pVeh->m_pVehicleInfo->iArmorGoneFX) { G_StopEffect(pVeh->m_pVehicleInfo->iArmorGoneFX, parent->playerModel, parent->crotchBolt, parent->s.number); } //-------------------------------------- #endif - if ( pVeh->m_pVehicleInfo->iExplodeFX ) - { - vec3_t fxAng = { 0.0f, -1.0f, 0.0f }; - G_PlayEffect( pVeh->m_pVehicleInfo->iExplodeFX, parent->currentOrigin, fxAng ); + if (pVeh->m_pVehicleInfo->iExplodeFX) { + vec3_t fxAng = {0.0f, -1.0f, 0.0f}; + G_PlayEffect(pVeh->m_pVehicleInfo->iExplodeFX, parent->currentOrigin, fxAng); - //trace down and place mark - VectorCopy( parent->currentOrigin, bottom ); + // trace down and place mark + VectorCopy(parent->currentOrigin, bottom); bottom[2] -= 80; - G_VehicleTrace( &trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); - if ( trace.fraction < 1.0f ) - { - VectorCopy( trace.endpos, bottom ); + G_VehicleTrace(&trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID); + if (trace.fraction < 1.0f) { + VectorCopy(trace.endpos, bottom); bottom[2] += 2; #ifdef _JK2MP VectorSet(fxAng, -90.0f, 0.0f, 0.0f); - G_PlayEffectID( G_EffectIndex("ships/ship_explosion_mark"), trace.endpos, fxAng ); + G_PlayEffectID(G_EffectIndex("ships/ship_explosion_mark"), trace.endpos, fxAng); #else - G_PlayEffect( "ships/ship_explosion_mark", trace.endpos ); + G_PlayEffect("ships/ship_explosion_mark", trace.endpos); #endif } } - parent->takedamage = qfalse;//so we don't recursively damage ourselves - if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) - { - VectorCopy( parent->mins, lMins ); - lMins[2] = -4;//to keep it off the ground a *little* - VectorCopy( parent->maxs, lMaxs ); - VectorCopy( parent->currentOrigin, bottom ); + parent->takedamage = qfalse; // so we don't recursively damage ourselves + if (pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0) { + VectorCopy(parent->mins, lMins); + lMins[2] = -4; // to keep it off the ground a *little* + VectorCopy(parent->maxs, lMaxs); + VectorCopy(parent->currentOrigin, bottom); bottom[2] += parent->mins[2] - 32; - G_VehicleTrace( &trace, parent->currentOrigin, lMins, lMaxs, bottom, parent->s.number, CONTENTS_SOLID ); + G_VehicleTrace(&trace, parent->currentOrigin, lMins, lMaxs, bottom, parent->s.number, CONTENTS_SOLID); #ifdef _JK2MP - G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, NULL, MOD_EXPLOSIVE );//FIXME: extern damage and radius or base on fuel + G_RadiusDamage(trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, NULL, + MOD_EXPLOSIVE); // FIXME: extern damage and radius or base on fuel #else - G_RadiusDamage( trace.endpos, player, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, MOD_EXPLOSIVE );//FIXME: extern damage and radius or base on fuel + G_RadiusDamage(trace.endpos, player, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, + MOD_EXPLOSIVE); // FIXME: extern damage and radius or base on fuel #endif } @@ -1513,31 +1328,26 @@ static void DeathUpdate( Vehicle_t *pVeh ) } } #ifndef _JK2MP - else - {//let everyone around me know I'm gonna blow! - if ( !Q_irand( 0, 10 ) ) - {//not so often... - AddSoundEvent( parent, parent->currentOrigin, 512, AEL_DANGER ); - AddSightEvent( parent, parent->currentOrigin, 512, AEL_DANGER, 100 ); + else { // let everyone around me know I'm gonna blow! + if (!Q_irand(0, 10)) { // not so often... + AddSoundEvent(parent, parent->currentOrigin, 512, AEL_DANGER); + AddSightEvent(parent, parent->currentOrigin, 512, AEL_DANGER, 100); } } #endif } // Register all the assets used by this vehicle. -void RegisterAssets( Vehicle_t *pVeh ) -{ -} +void RegisterAssets(Vehicle_t *pVeh) {} -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); // Initialize the vehicle. -bool Initialize( Vehicle_t *pVeh ) -{ +bool Initialize(Vehicle_t *pVeh) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; int i = 0; - if ( !parent || !parent->client ) + if (!parent || !parent->client) return false; #ifdef _JK2MP @@ -1545,49 +1355,42 @@ bool Initialize( Vehicle_t *pVeh ) #endif parent->s.m_iVehicleNum = 0; { - pVeh->m_iArmor = pVeh->m_pVehicleInfo->armor; - parent->client->pers.maxHealth = parent->client->ps.stats[STAT_MAX_HEALTH] = parent->NPC->stats.health = parent->health = parent->client->ps.stats[STAT_HEALTH] = pVeh->m_iArmor; - pVeh->m_iShields = pVeh->m_pVehicleInfo->shields; + pVeh->m_iArmor = pVeh->m_pVehicleInfo->armor; + parent->client->pers.maxHealth = parent->client->ps.stats[STAT_MAX_HEALTH] = parent->NPC->stats.health = parent->health = + parent->client->ps.stats[STAT_HEALTH] = pVeh->m_iArmor; + pVeh->m_iShields = pVeh->m_pVehicleInfo->shields; #ifdef _JK2MP - G_VehUpdateShields( parent ); + G_VehUpdateShields(parent); #endif - parent->client->ps.stats[STAT_ARMOR] = pVeh->m_iShields; + parent->client->ps.stats[STAT_ARMOR] = pVeh->m_iShields; } parent->mass = pVeh->m_pVehicleInfo->mass; - //initialize the ammo to max - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - { + // initialize the ammo to max + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { parent->client->ps.ammo[i] = pVeh->weaponStatus[i].ammo = pVeh->m_pVehicleInfo->weapon[i].ammoMax; } - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - pVeh->turretStatus[i].nextMuzzle = (pVeh->m_pVehicleInfo->turret[i].iMuzzle[i]-1); - parent->client->ps.ammo[MAX_VEHICLE_WEAPONS+i] = pVeh->turretStatus[i].ammo = pVeh->m_pVehicleInfo->turret[i].iAmmoMax; - if ( pVeh->m_pVehicleInfo->turret[i].bAI ) - {//they're going to be finding enemies, init this to NONE + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + pVeh->turretStatus[i].nextMuzzle = (pVeh->m_pVehicleInfo->turret[i].iMuzzle[i] - 1); + parent->client->ps.ammo[MAX_VEHICLE_WEAPONS + i] = pVeh->turretStatus[i].ammo = pVeh->m_pVehicleInfo->turret[i].iAmmoMax; + if (pVeh->m_pVehicleInfo->turret[i].bAI) { // they're going to be finding enemies, init this to NONE pVeh->turretStatus[i].enemyEntNum = ENTITYNUM_NONE; } } - //begin stopped...? + // begin stopped...? parent->client->ps.speed = 0; - VectorClear( pVeh->m_vOrientation ); + VectorClear(pVeh->m_vOrientation); pVeh->m_vOrientation[YAW] = parent->s.angles[YAW]; #ifdef _JK2MP - if ( pVeh->m_pVehicleInfo->gravity && - pVeh->m_pVehicleInfo->gravity != g_gravity.value ) - {//not normal gravity - if ( parent->NPC ) - { + if (pVeh->m_pVehicleInfo->gravity && pVeh->m_pVehicleInfo->gravity != g_gravity.value) { // not normal gravity + if (parent->NPC) { parent->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; } parent->client->ps.gravity = pVeh->m_pVehicleInfo->gravity; } #else - if ( pVeh->m_pVehicleInfo->gravity && - pVeh->m_pVehicleInfo->gravity != g_gravity->value ) - {//not normal gravity + if (pVeh->m_pVehicleInfo->gravity && pVeh->m_pVehicleInfo->gravity != g_gravity->value) { // not normal gravity parent->svFlags |= SVF_CUSTOM_GRAVITY; parent->client->ps.gravity = pVeh->m_pVehicleInfo->gravity; } @@ -1600,177 +1403,159 @@ bool Initialize( Vehicle_t *pVeh ) } else */ - //why?! -rww - { - pVeh->m_ulFlags = 0; - } + // why?! -rww + { pVeh->m_ulFlags = 0; } pVeh->m_fTimeModifier = 1.0f; pVeh->m_iBoarding = 0; pVeh->m_bWasBoarding = false; pVeh->m_pOldPilot = NULL; VectorClear(pVeh->m_vBoardingVelocity); pVeh->m_pPilot = NULL; - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); pVeh->m_iDieTime = 0; pVeh->m_EjectDir = VEH_EJECT_LEFT; - //pVeh->m_iDriverTag = -1; - //pVeh->m_iLeftExhaustTag = -1; - //pVeh->m_iRightExhaustTag = -1; - //pVeh->m_iGun1Tag = -1; - //pVeh->m_iGun1Bone = -1; - //pVeh->m_iLeftWingBone = -1; - //pVeh->m_iRightWingBone = -1; - memset( pVeh->m_iExhaustTag, -1, sizeof( int ) * MAX_VEHICLE_EXHAUSTS ); - memset( pVeh->m_iMuzzleTag, -1, sizeof( int ) * MAX_VEHICLE_MUZZLES ); + // pVeh->m_iDriverTag = -1; + // pVeh->m_iLeftExhaustTag = -1; + // pVeh->m_iRightExhaustTag = -1; + // pVeh->m_iGun1Tag = -1; + // pVeh->m_iGun1Bone = -1; + // pVeh->m_iLeftWingBone = -1; + // pVeh->m_iRightWingBone = -1; + memset(pVeh->m_iExhaustTag, -1, sizeof(int) * MAX_VEHICLE_EXHAUSTS); + memset(pVeh->m_iMuzzleTag, -1, sizeof(int) * MAX_VEHICLE_MUZZLES); // FIXME! Use external values read from the vehicle data file! -#ifndef _JK2MP //blargh, fixme - memset( pVeh->m_Muzzles, 0, sizeof( Muzzle ) * MAX_VEHICLE_MUZZLES ); +#ifndef _JK2MP // blargh, fixme + memset(pVeh->m_Muzzles, 0, sizeof(Muzzle) * MAX_VEHICLE_MUZZLES); #endif pVeh->m_iDroidUnitTag = -1; - //initialize to blaster, just since it's a basic weapon and there's no lightsaber crap...? + // initialize to blaster, just since it's a basic weapon and there's no lightsaber crap...? parent->client->ps.weapon = WP_BLASTER; parent->client->ps.weaponstate = WEAPON_READY; - parent->client->ps.stats[STAT_WEAPONS] |= (1<client->ps.stats[STAT_WEAPONS] |= (1 << WP_BLASTER); - //Initialize to landed (wings closed, gears down) animation + // Initialize to landed (wings closed, gears down) animation { int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; #ifdef _JK2MP pVeh->m_ulFlags |= VEH_GEARSOPEN; - BG_SetAnim(pVeh->m_pParentEntity->playerState, - bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, - SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend); + BG_SetAnim(pVeh->m_pParentEntity->playerState, bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend); #else - NPC_SetAnim( pVeh->m_pParentEntity, SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend ); + NPC_SetAnim(pVeh->m_pParentEntity, SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend); #endif } return true; } - - // Like a think or move command, this updates various vehicle properties. #ifdef _JK2MP -void G_VehicleDamageBoxSizing(Vehicle_t *pVeh); //declared below +void G_VehicleDamageBoxSizing(Vehicle_t *pVeh); // declared below #endif -static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) -{ +static bool Update(Vehicle_t *pVeh, const usercmd_t *pUmcd) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilotEnt; - //static float fMod = 1000.0f / 60.0f; + // static float fMod = 1000.0f / 60.0f; vec3_t vVehAngles; int i; - int prevSpeed; - int nextSpeed; - int curTime; + int prevSpeed; + int nextSpeed; + int curTime; int halfMaxSpeed; playerState_t *parentPS; qboolean linkHeld = qfalse; - #ifdef _JK2MP - parentPS = pVeh->m_pParentEntity->playerState; + parentPS = pVeh->m_pParentEntity->playerState; #else parentPS = &pVeh->m_pParentEntity->client->ps; #endif -#ifndef _JK2MP//SP +#ifndef _JK2MP // SP curTime = level.time; -#elif QAGAME//MP GAME +#elif QAGAME // MP GAME curTime = level.time; -#elif CGAME//MP CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... +#elif CGAME // MP CGAME + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif - //increment the ammo for all rechargeable weapons - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapon[i].ID > VEH_WEAPON_BASE//have a weapon in this slot - && pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS//its ammo is rechargable - && pVeh->weaponStatus[i].ammo < pVeh->m_pVehicleInfo->weapon[i].ammoMax//its ammo is below max - && pUmcd->serverTime-pVeh->weaponStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS )//enough time has passed - {//add 1 to the ammo + // increment the ammo for all rechargeable weapons + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { + if (pVeh->m_pVehicleInfo->weapon[i].ID > VEH_WEAPON_BASE // have a weapon in this slot + && pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS // its ammo is rechargable + && pVeh->weaponStatus[i].ammo < pVeh->m_pVehicleInfo->weapon[i].ammoMax // its ammo is below max + && pUmcd->serverTime - pVeh->weaponStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS) // enough time has passed + { // add 1 to the ammo pVeh->weaponStatus[i].lastAmmoInc = pUmcd->serverTime; pVeh->weaponStatus[i].ammo++; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( parent && parent->client ) - { + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo + // array + if (parent && parent->client) { parent->client->ps.ammo[i] = pVeh->weaponStatus[i].ammo; } } } - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - if ( pVeh->m_pVehicleInfo->turret[i].iWeapon > VEH_WEAPON_BASE//have a weapon in this slot - && pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS//its ammo is rechargable - && pVeh->turretStatus[i].ammo < pVeh->m_pVehicleInfo->turret[i].iAmmoMax//its ammo is below max - && pUmcd->serverTime-pVeh->turretStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS )//enough time has passed - {//add 1 to the ammo + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + if (pVeh->m_pVehicleInfo->turret[i].iWeapon > VEH_WEAPON_BASE // have a weapon in this slot + && pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS // its ammo is rechargable + && pVeh->turretStatus[i].ammo < pVeh->m_pVehicleInfo->turret[i].iAmmoMax // its ammo is below max + && pUmcd->serverTime - pVeh->turretStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS) // enough time has passed + { // add 1 to the ammo pVeh->turretStatus[i].lastAmmoInc = pUmcd->serverTime; pVeh->turretStatus[i].ammo++; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( parent && parent->client ) - { - parent->client->ps.ammo[MAX_VEHICLE_WEAPONS+i] = pVeh->turretStatus[i].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo + // array + if (parent && parent->client) { + parent->client->ps.ammo[MAX_VEHICLE_WEAPONS + i] = pVeh->turretStatus[i].ammo; } } } - //increment shields for rechargable shields - if ( pVeh->m_pVehicleInfo->shieldRechargeMS - && parentPS->stats[STAT_ARMOR] > 0 //still have some shields left - && parentPS->stats[STAT_ARMOR] < pVeh->m_pVehicleInfo->shields//its below max - && pUmcd->serverTime-pVeh->lastShieldInc >= pVeh->m_pVehicleInfo->shieldRechargeMS )//enough time has passed + // increment shields for rechargable shields + if (pVeh->m_pVehicleInfo->shieldRechargeMS && parentPS->stats[STAT_ARMOR] > 0 // still have some shields left + && parentPS->stats[STAT_ARMOR] < pVeh->m_pVehicleInfo->shields // its below max + && pUmcd->serverTime - pVeh->lastShieldInc >= pVeh->m_pVehicleInfo->shieldRechargeMS) // enough time has passed { parentPS->stats[STAT_ARMOR]++; - if ( parentPS->stats[STAT_ARMOR] > pVeh->m_pVehicleInfo->shields ) - { + if (parentPS->stats[STAT_ARMOR] > pVeh->m_pVehicleInfo->shields) { parentPS->stats[STAT_ARMOR] = pVeh->m_pVehicleInfo->shields; } pVeh->m_iShields = parentPS->stats[STAT_ARMOR]; #ifdef _JK2MP - G_VehUpdateShields( parent ); + G_VehUpdateShields(parent); #endif } -#ifdef _JK2MP //sometimes this gets out of whack, probably init'ing - if (parent && parent->r.ownerNum != parent->s.owner) - { +#ifdef _JK2MP // sometimes this gets out of whack, probably init'ing + if (parent && parent->r.ownerNum != parent->s.owner) { parent->s.owner = parent->r.ownerNum; } - //keep the PS value in sync. set it up here in case we return below at some point. - if (pVeh->m_iBoarding) - { + // keep the PS value in sync. set it up here in case we return below at some point. + if (pVeh->m_iBoarding) { parent->client->ps.vehBoarding = qtrue; - } - else - { + } else { parent->client->ps.vehBoarding = qfalse; } #endif // See whether this vehicle should be dieing or dead. - if ( pVeh->m_iDieTime != 0 -#ifndef _JK2MP //sometimes this gets out of whack, probably init'ing + if (pVeh->m_iDieTime != 0 +#ifndef _JK2MP // sometimes this gets out of whack, probably init'ing || (parent->health <= 0) #endif - ) - {//NOTE!!!: This HAS to be consistent with cgame!!! + ) { // NOTE!!!: This HAS to be consistent with cgame!!! // Keep track of the old orientation. - VectorCopy( pVeh->m_vOrientation, pVeh->m_vPrevOrientation ); + VectorCopy(pVeh->m_vOrientation, pVeh->m_vPrevOrientation); // Process the orient commands. - pVeh->m_pVehicleInfo->ProcessOrientCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessOrientCommands(pVeh); // Need to copy orientation to our entity's viewangles so that it renders at the proper angle and currentAngles is correct. - SetClientViewAngle( parent, pVeh->m_vOrientation ); - if ( pVeh->m_pPilot ) - { - SetClientViewAngle( (gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation ); + SetClientViewAngle(parent, pVeh->m_vOrientation); + if (pVeh->m_pPilot) { + SetClientViewAngle((gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation); } /* for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) @@ -1783,74 +1568,54 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) */ // Process the move commands. - pVeh->m_pVehicleInfo->ProcessMoveCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessMoveCommands(pVeh); // Setup the move direction. - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { - AngleVectors( pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL ); - } - else - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + AngleVectors(pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL); + } else { VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); } - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); return false; } // Vehicle dead! #ifdef _JK2MP - else if ( parent->health <= 0 ) - { + else if (parent->health <= 0) { // Instant kill. - if (pVeh->m_pVehicleInfo->type == VH_FIGHTER && - pVeh->m_iLastImpactDmg > 500) - { //explode instantly in inferno-y death - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, -1/* -1 causes instant death */); + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER && pVeh->m_iLastImpactDmg > 500) { // explode instantly in inferno-y death + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, -1 /* -1 causes instant death */); + } else { + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 0); } - else - { - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, 0 ); - } - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); return false; } #endif -#ifdef _JK2MP //special check in case someone disconnects/dies while boarding +#ifdef _JK2MP // special check in case someone disconnects/dies while boarding #ifdef QAGAME - if (parent->spawnflags & 1) - { - if (pVeh->m_pPilot || !pVeh->m_bHasHadPilot) - { - if (pVeh->m_pPilot && !pVeh->m_bHasHadPilot) - { + if (parent->spawnflags & 1) { + if (pVeh->m_pPilot || !pVeh->m_bHasHadPilot) { + if (pVeh->m_pPilot && !pVeh->m_bHasHadPilot) { pVeh->m_bHasHadPilot = qtrue; pVeh->m_iPilotLastIndex = pVeh->m_pPilot->s.number; } pVeh->m_iPilotTime = level.time + parent->damage; - } - else if (pVeh->m_iPilotTime) - { //die + } else if (pVeh->m_iPilotTime) { // die gentity_t *oldPilot = &g_entities[pVeh->m_iPilotLastIndex]; - if (!oldPilot->inuse || !oldPilot->client || - oldPilot->client->pers.connected != CON_CONNECTED) - { //no longer in the game? + if (!oldPilot->inuse || !oldPilot->client || oldPilot->client->pers.connected != CON_CONNECTED) { // no longer in the game? G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); - } - else - { + } else { vec3_t v; VectorSubtract(parent->client->ps.origin, oldPilot->client->ps.origin, v); - if (VectorLength(v) < parent->speed) - { //they are still within the minimum distance to their vehicle + if (VectorLength(v) < parent->speed) { // they are still within the minimum distance to their vehicle pVeh->m_iPilotTime = level.time + parent->damage; - } - else if (pVeh->m_iPilotTime < level.time) - { //dying time + } else if (pVeh->m_iPilotTime < level.time) { // dying time G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } @@ -1858,67 +1623,53 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) } #endif #else - if (parent->spawnflags & 1) - {//NOTE: in SP, this actually just checks LOS to the Player - if (pVeh->m_iPilotTime < level.time) - {//do another check? - if ( !player || G_ClearLineOfSight(pVeh->m_pParentEntity->currentOrigin, player->currentOrigin, pVeh->m_pParentEntity->s.number, MASK_OPAQUE ) ) - { + if (parent->spawnflags & 1) { // NOTE: in SP, this actually just checks LOS to the Player + if (pVeh->m_iPilotTime < level.time) { // do another check? + if (!player || G_ClearLineOfSight(pVeh->m_pParentEntity->currentOrigin, player->currentOrigin, pVeh->m_pParentEntity->s.number, MASK_OPAQUE)) { pVeh->m_iPilotTime = level.time + pVeh->m_pParentEntity->endFrame; } } - if (pVeh->m_iPilotTime && pVeh->m_iPilotTime < level.time) - { //die - //FIXME: does this give proper credit to the enemy who shot you down? - G_Damage(parent, player, player, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); + if (pVeh->m_iPilotTime && pVeh->m_iPilotTime < level.time) { // die + // FIXME: does this give proper credit to the enemy who shot you down? + G_Damage(parent, player, player, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } #endif #ifndef _JK2MP -// if (level.timem_iTurboTime || pVeh->m_pVehicleInfo->type==VH_ANIMAL) + // if (level.timem_iTurboTime || pVeh->m_pVehicleInfo->type==VH_ANIMAL) // always knock guys around now... { - vec3_t dir; - vec3_t projectedPosition; + vec3_t dir; + vec3_t projectedPosition; VectorCopy(parent->client->ps.velocity, dir); VectorMA(parent->currentOrigin, 0.1f, dir, projectedPosition); - float force = VectorNormalize(dir); + float force = VectorNormalize(dir); force /= 10.0f; - if (force>30.0f) - { - trace_t tr; + if (force > 30.0f) { + trace_t tr; G_VehicleTrace(&tr, parent->currentOrigin, parent->mins, parent->maxs, projectedPosition, parent->s.number, CONTENTS_BODY); - if (tr.fraction<1.0f && - !tr.allsolid && - !tr.startsolid && - tr.entityNum!=ENTITYNUM_NONE && - tr.entityNum!=ENTITYNUM_WORLD && - (level.timem_iTurboTime || Q_irand(0,3)==0)) - { - gentity_t* other = &g_entities[tr.entityNum]; - if (other && other->client && !other->s.m_iVehicleNum) - { - G_Throw( other, dir, force/10.0f ); - G_Knockdown( other, parent, dir, force, qtrue ); - G_Damage( other, player, player, parent->client->ps.velocity, parent->currentOrigin, force, DAMAGE_NO_ARMOR|DAMAGE_EXTRA_KNOCKBACK, MOD_IMPACT); + if (tr.fraction < 1.0f && !tr.allsolid && !tr.startsolid && tr.entityNum != ENTITYNUM_NONE && tr.entityNum != ENTITYNUM_WORLD && + (level.time < pVeh->m_iTurboTime || Q_irand(0, 3) == 0)) { + gentity_t *other = &g_entities[tr.entityNum]; + if (other && other->client && !other->s.m_iVehicleNum) { + G_Throw(other, dir, force / 10.0f); + G_Knockdown(other, parent, dir, force, qtrue); + G_Damage(other, player, player, parent->client->ps.velocity, parent->currentOrigin, force, DAMAGE_NO_ARMOR | DAMAGE_EXTRA_KNOCKBACK, + MOD_IMPACT); } } } } #endif -#ifdef _JK2MP //special check in case someone disconnects/dies while boarding - if (pVeh->m_iBoarding != 0) - { +#ifdef _JK2MP // special check in case someone disconnects/dies while boarding + if (pVeh->m_iBoarding != 0) { pilotEnt = (gentity_t *)pVeh->m_pPilot; - if (pilotEnt) - { - if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || - pilotEnt->client->pers.connected != CON_CONNECTED) - { - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + if (pilotEnt) { + if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || pilotEnt->client->pers.connected != CON_CONNECTED) { + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); return false; } } @@ -1926,22 +1677,17 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) #endif // If we're not done mounting, can't do anything. - if ( pVeh->m_iBoarding != 0 ) - { - if (!pVeh->m_bWasBoarding) - { + if (pVeh->m_iBoarding != 0) { + if (!pVeh->m_bWasBoarding) { VectorCopy(parentPS->velocity, pVeh->m_vBoardingVelocity); pVeh->m_bWasBoarding = true; } // See if we're done boarding. - if ( pVeh->m_iBoarding > -1 && pVeh->m_iBoarding <= level.time ) - { + if (pVeh->m_iBoarding > -1 && pVeh->m_iBoarding <= level.time) { pVeh->m_bWasBoarding = false; pVeh->m_iBoarding = 0; - } - else - { + } else { #ifdef _JK2MP goto maintainSelfDuringBoarding; #else @@ -1953,33 +1699,31 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) parent = (gentity_t *)pVeh->m_pParentEntity; // Validate vehicle. - if ( !parent || !parent->client || parent->health <= 0 ) + if (!parent || !parent->client || parent->health <= 0) return false; // See if any of the riders are dead and if so kick em off. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { pilotEnt = (gentity_t *)pVeh->m_pPilot; #ifdef _JK2MP - if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || - pilotEnt->client->pers.connected != CON_CONNECTED) + if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || pilotEnt->client->pers.connected != CON_CONNECTED) #else if (pilotEnt->health <= 0) #endif { - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); } } #ifdef _JK2MP // Copy over the commands for local storage. - memcpy( &parent->client->pers.cmd, &pVeh->m_ucmd, sizeof( usercmd_t ) ); - pVeh->m_ucmd.buttons &= ~(BUTTON_TALK);//|BUTTON_GESTURE); //don't want some of these buttons + memcpy(&parent->client->pers.cmd, &pVeh->m_ucmd, sizeof(usercmd_t)); + pVeh->m_ucmd.buttons &= ~(BUTTON_TALK); //|BUTTON_GESTURE); //don't want some of these buttons #else // Copy over the commands for local storage. - memcpy( &pVeh->m_ucmd, pUmcd, sizeof( usercmd_t ) ); - memcpy( &parent->client->pers.lastCommand, pUmcd, sizeof( usercmd_t ) ); + memcpy(&pVeh->m_ucmd, pUmcd, sizeof(usercmd_t)); + memcpy(&parent->client->pers.lastCommand, pUmcd, sizeof(usercmd_t)); #endif /* @@ -1998,82 +1742,70 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) pVeh->m_fTimeModifier = pVeh->m_fTimeModifier / fMod; */ - //check for weapon linking/unlinking command - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - if ( pVeh->m_pVehicleInfo->weapon[i].linkable == 2 ) - {//always linked - //FIXME: just set this once, on Initialize...? - if ( !pVeh->weaponStatus[i].linked ) - { + // check for weapon linking/unlinking command + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + if (pVeh->m_pVehicleInfo->weapon[i].linkable == 2) { // always linked + // FIXME: just set this once, on Initialize...? + if (!pVeh->weaponStatus[i].linked) { pVeh->weaponStatus[i].linked = qtrue; } } #ifdef _JK2MP - else if ( (pVeh->m_ucmd.buttons&BUTTON_USE_HOLDABLE) ) + else if ((pVeh->m_ucmd.buttons & BUTTON_USE_HOLDABLE)) #else - //FIXME: implement... just a console command bound to a key? - else if ( 0 ) + // FIXME: implement... just a console command bound to a key? + else if (0) #endif - {//pilot pressed the "weapon link" toggle button - //playerState_t *pilotPS; + { // pilot pressed the "weapon link" toggle button + // playerState_t *pilotPS; #ifdef _JK2MP bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } - //pilotPS = rider->playerState; + // pilotPS = rider->playerState; #else - //gentity_t *rider = parent->owner; - //pilotPS = &rider->client->ps; + // gentity_t *rider = parent->owner; + // pilotPS = &rider->client->ps; #endif - if ( !pVeh->linkWeaponToggleHeld )//so we don't hold it down and toggle it back and forth - {//okay to toggle - if ( pVeh->m_pVehicleInfo->weapon[i].linkable == 1 ) - {//link-toggleable + if (!pVeh->linkWeaponToggleHeld) // so we don't hold it down and toggle it back and forth + { // okay to toggle + if (pVeh->m_pVehicleInfo->weapon[i].linkable == 1) { // link-toggleable pVeh->weaponStatus[i].linked = (qboolean)!pVeh->weaponStatus[i].linked; } } linkHeld = qtrue; } } - if ( linkHeld ) - { - //so we don't hold it down and toggle it back and forth + if (linkHeld) { + // so we don't hold it down and toggle it back and forth pVeh->linkWeaponToggleHeld = qtrue; - } - else - { - //so we don't hold it down and toggle it back and forth + } else { + // so we don't hold it down and toggle it back and forth pVeh->linkWeaponToggleHeld = qfalse; } #ifdef _JK2MP - //now pass it over the network so cgame knows about it - //NOTE: SP can just cheat and check directly + // now pass it over the network so cgame knows about it + // NOTE: SP can just cheat and check directly parentPS->vehWeaponsLinked = qfalse; - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - if ( pVeh->weaponStatus[i].linked ) - { + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + if (pVeh->weaponStatus[i].linked) { parentPS->vehWeaponsLinked = qtrue; } } #endif #ifdef QAGAME - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - VEH_TurretThink( pVeh, parent, i ); + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + VEH_TurretThink(pVeh, parent, i); } #endif #ifdef _JK2MP maintainSelfDuringBoarding: - if (pVeh->m_pPilot && pVeh->m_pPilot->playerState && pVeh->m_iBoarding != 0) - { - VectorCopy(pVeh->m_vOrientation, pVeh->m_pPilot->playerState->viewangles); + if (pVeh->m_pPilot && pVeh->m_pPilot->playerState && pVeh->m_iBoarding != 0) { + VectorCopy(pVeh->m_vOrientation, pVeh->m_pPilot->playerState->viewangles); pVeh->m_ucmd.buttons = 0; pVeh->m_ucmd.forwardmove = 0; pVeh->m_ucmd.rightmove = 0; @@ -2082,27 +1814,24 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) #endif // Keep track of the old orientation. - VectorCopy( pVeh->m_vOrientation, pVeh->m_vPrevOrientation ); + VectorCopy(pVeh->m_vOrientation, pVeh->m_vPrevOrientation); // Process the orient commands. - pVeh->m_pVehicleInfo->ProcessOrientCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessOrientCommands(pVeh); // Need to copy orientation to our entity's viewangles so that it renders at the proper angle and currentAngles is correct. - SetClientViewAngle( parent, pVeh->m_vOrientation ); - if ( pVeh->m_pPilot ) - { + SetClientViewAngle(parent, pVeh->m_vOrientation); + if (pVeh->m_pPilot) { #ifdef _JK2MP - if ( !BG_UnrestrainedPitchRoll( pVeh->m_pPilot->playerState, pVeh ) ) - { + if (!BG_UnrestrainedPitchRoll(pVeh->m_pPilot->playerState, pVeh)) { vec3_t newVAngle; newVAngle[PITCH] = pVeh->m_pPilot->playerState->viewangles[PITCH]; newVAngle[YAW] = pVeh->m_pPilot->playerState->viewangles[YAW]; newVAngle[ROLL] = pVeh->m_vOrientation[ROLL]; - SetClientViewAngle( (gentity_t *)pVeh->m_pPilot, newVAngle ); + SetClientViewAngle((gentity_t *)pVeh->m_pPilot, newVAngle); } #else - if ( !BG_UnrestrainedPitchRoll( &pVeh->m_pPilot->client->ps, pVeh ) ) - { - SetClientViewAngle( (gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation ); + if (!BG_UnrestrainedPitchRoll(&pVeh->m_pPilot->client->ps, pVeh)) { + SetClientViewAngle((gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation); } #endif } @@ -2118,190 +1847,159 @@ static bool Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) // Process the move commands. prevSpeed = parentPS->speed; - pVeh->m_pVehicleInfo->ProcessMoveCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessMoveCommands(pVeh); nextSpeed = parentPS->speed; - halfMaxSpeed = pVeh->m_pVehicleInfo->speedMax*0.5f; - - -// Shifting Sounds -//===================================================================== - if (pVeh->m_iTurboTimem_iSoundDebounceTimerprevSpeed && nextSpeed>halfMaxSpeed && prevSpeedhalfMaxSpeed && !Q_irand(0,1000))) - ) - { - int shiftSound = Q_irand(1,4); - switch (shiftSound) - { - case 1: shiftSound=pVeh->m_pVehicleInfo->soundShift1; break; - case 2: shiftSound=pVeh->m_pVehicleInfo->soundShift2; break; - case 3: shiftSound=pVeh->m_pVehicleInfo->soundShift3; break; - case 4: shiftSound=pVeh->m_pVehicleInfo->soundShift4; break; + halfMaxSpeed = pVeh->m_pVehicleInfo->speedMax * 0.5f; + + // Shifting Sounds + //===================================================================== + if (pVeh->m_iTurboTime < curTime && pVeh->m_iSoundDebounceTimer < curTime && + ((nextSpeed > prevSpeed && nextSpeed > halfMaxSpeed && prevSpeed < halfMaxSpeed) || (nextSpeed > halfMaxSpeed && !Q_irand(0, 1000)))) { + int shiftSound = Q_irand(1, 4); + switch (shiftSound) { + case 1: + shiftSound = pVeh->m_pVehicleInfo->soundShift1; + break; + case 2: + shiftSound = pVeh->m_pVehicleInfo->soundShift2; + break; + case 3: + shiftSound = pVeh->m_pVehicleInfo->soundShift3; + break; + case 4: + shiftSound = pVeh->m_pVehicleInfo->soundShift4; + break; } - if (shiftSound) - { + if (shiftSound) { pVeh->m_iSoundDebounceTimer = curTime + Q_irand(1000, 4000); #ifdef _JK2MP // TODO: MP Shift Sound Playback #else // NOTE: Use this type so it's spatialized and updates play origin as bike moves - MCG - G_SoundIndexOnEnt( pVeh->m_pParentEntity, CHAN_AUTO, shiftSound); + G_SoundIndexOnEnt(pVeh->m_pParentEntity, CHAN_AUTO, shiftSound); #endif } } -//===================================================================== - + //===================================================================== // Setup the move direction. - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { - AngleVectors( pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL ); - } - else - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + AngleVectors(pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL); + } else { VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); } #ifdef _JK2MP - if (pVeh->m_pVehicleInfo->surfDestruction) - { - if (pVeh->m_iRemovedSurfaces) - { + if (pVeh->m_pVehicleInfo->surfDestruction) { + if (pVeh->m_iRemovedSurfaces) { gentity_t *killer = parent; G_VehicleDamageBoxSizing(pVeh); - //damage him constantly if any chunks are currently taken off - if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && - parent->client->ps.otherKillerTime > level.time) - { + // damage him constantly if any chunks are currently taken off + if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && parent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[parent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } - //FIXME: aside from bypassing shields, maybe set m_iShields to 0, too... ? - G_Damage(parent, killer, killer, NULL, parent->client->ps.origin, Q_irand(2, 5), DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR, MOD_SUICIDE); + // FIXME: aside from bypassing shields, maybe set m_iShields to 0, too... ? + G_Damage(parent, killer, killer, NULL, parent->client->ps.origin, Q_irand(2, 5), DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR, MOD_SUICIDE); } - //make sure playerstate value stays in sync + // make sure playerstate value stays in sync parent->client->ps.vehSurfaces = pVeh->m_iRemovedSurfaces; } #endif #ifdef _JK2MP - //keep the PS value in sync - if (pVeh->m_iBoarding) - { + // keep the PS value in sync + if (pVeh->m_iBoarding) { parent->client->ps.vehBoarding = qtrue; - } - else - { + } else { parent->client->ps.vehBoarding = qfalse; } #endif #ifndef _JK2MP // Make sure the vehicle takes on the enemy of it's rider (for homing missles for instance). - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { parent->enemy = pVeh->m_pPilot->enemy; } #endif - return true; } - // Update the properties of a Rider (that may reflect what happens to the vehicle). -static bool UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd ) -{ +static bool UpdateRider(Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd) { gentity_t *parent; gentity_t *rider; - if ( pVeh->m_iBoarding != 0 && pVeh->m_iDieTime==0) + if (pVeh->m_iBoarding != 0 && pVeh->m_iDieTime == 0) return true; parent = (gentity_t *)pVeh->m_pParentEntity; rider = (gentity_t *)pRider; #ifdef _JK2MP - //MG FIXME !! Single player needs update! - if ( rider && rider->client - && parent && parent->client ) - {//so they know who we're locking onto with our rockets, if anyone + // MG FIXME !! Single player needs update! + if (rider && rider->client && parent && parent->client) { // so they know who we're locking onto with our rockets, if anyone rider->client->ps.rocketLockIndex = parent->client->ps.rocketLockIndex; rider->client->ps.rocketLockTime = parent->client->ps.rocketLockTime; rider->client->ps.rocketTargetTime = parent->client->ps.rocketTargetTime; } #endif // Regular exit. - if ( pUmcd->buttons & BUTTON_USE && pVeh->m_pVehicleInfo->type!=VH_SPEEDER) - { - if ( pVeh->m_pVehicleInfo->type == VH_WALKER ) - {//just get the fuck out + if (pUmcd->buttons & BUTTON_USE && pVeh->m_pVehicleInfo->type != VH_SPEEDER) { + if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // just get the fuck out pVeh->m_EjectDir = VEH_EJECT_REAR; - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) return false; - } - else if ( !(pVeh->m_ulFlags & VEH_FLYING)) - { + } else if (!(pVeh->m_ulFlags & VEH_FLYING)) { // If going too fast, roll off. - if ((parent->client->ps.speed<=600) && pUmcd->rightmove!=0) - { - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if ((parent->client->ps.speed <= 600) && pUmcd->rightmove != 0) { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { animNumber_t Anim; int iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, iBlend = 300; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_ROLL_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else - { + } else { Anim = BOTH_ROLL_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; } - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); #if 1 - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, iFlags, iBlend); #else #endif - //PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - rider->client->ps.weaponTime = rider->client->ps.torsoAnimTimer - 200;//just to make sure it's cleared when roll is done - G_AddEvent( rider, EV_ROLL, 0 ); + // PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); + rider->client->ps.weaponTime = rider->client->ps.torsoAnimTimer - 200; // just to make sure it's cleared when roll is done + G_AddEvent(rider, EV_ROLL, 0); return false; } - } - else - { + } else { // FIXME: Check trace to see if we should start playing the animation. animNumber_t Anim; int iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, iBlend = 500; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_VS_DISMOUNT_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else - { + } else { Anim = BOTH_VS_DISMOUNT_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; } - if ( pVeh->m_iBoarding <= 1 ) - { + if (pVeh->m_iBoarding <= 1) { int iAnimLen; // NOTE: I know I shouldn't reuse pVeh->m_iBoarding so many times for so many different // purposes, but it's not used anywhere else right here so why waste memory??? #ifdef _JK2MP - iAnimLen = BG_AnimLength( rider->localAnimIndex, Anim ); + iAnimLen = BG_AnimLength(rider->localAnimIndex, Anim); #else - iAnimLen = PM_AnimLength( pRider->client->clientInfo.animFileIndex, Anim ); + iAnimLen = PM_AnimLength(pRider->client->clientInfo.animFileIndex, Anim); #endif pVeh->m_iBoarding = level.time + iAnimLen; // Weird huh? Well I wanted to reuse flags and this should never be set in an @@ -2316,103 +2014,93 @@ static bool UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd ) rider->client->ps.weaponTime = iAnimLen; } - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, iFlags, iBlend); } } // Flying, so just fall off. - else - { + else { pVeh->m_EjectDir = VEH_EJECT_LEFT; - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) return false; } } // Getting off animation complete (if we had one going)? #ifdef _JK2MP - if ( pVeh->m_iBoarding < level.time && (rider->flags & FL_VEH_BOARDING) ) - { + if (pVeh->m_iBoarding < level.time && (rider->flags & FL_VEH_BOARDING)) { rider->flags &= ~FL_VEH_BOARDING; #else - if ( pVeh->m_iBoarding < level.time && (rider->client->ps.eFlags & EF_VEH_BOARDING) ) - { + if (pVeh->m_iBoarding < level.time && (rider->client->ps.eFlags & EF_VEH_BOARDING)) { rider->client->ps.eFlags &= ~EF_VEH_BOARDING; #endif // Eject this guy now. - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { return false; } } - if ( pVeh->m_pVehicleInfo->type != VH_FIGHTER - && pVeh->m_pVehicleInfo->type != VH_WALKER ) - { + if (pVeh->m_pVehicleInfo->type != VH_FIGHTER && pVeh->m_pVehicleInfo->type != VH_WALKER) { // Jump off. - if ( pUmcd->upmove > 0 ) - { + if (pUmcd->upmove > 0) { // NOT IN MULTI PLAYER! //=================================================================== #ifndef _JK2MP float riderRightDot = G_CanJumpToEnemyVeh(pVeh, pUmcd); - if (riderRightDot!=0.0f) - { + if (riderRightDot != 0.0f) { // Eject Player From Current Vehicle //----------------------------------- pVeh->m_EjectDir = VEH_EJECT_TOP; - pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qtrue); // Send Current Vehicle Spinning Out Of Control //---------------------------------------------- pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 10000); pVeh->m_ulFlags |= (VEH_OUTOFCONTROL); - VectorScale(pVeh->m_pParentEntity->client->ps.velocity, 1.0f, pVeh->m_pParentEntity->pos3); + VectorScale(pVeh->m_pParentEntity->client->ps.velocity, 1.0f, pVeh->m_pParentEntity->pos3); // Todo: Throw Old Vehicle Away From The New Vehicle Some //------------------------------------------------------- - vec3_t toEnemy; + vec3_t toEnemy; VectorSubtract(pVeh->m_pParentEntity->currentOrigin, rider->enemy->currentOrigin, toEnemy); VectorNormalize(toEnemy); G_Throw(pVeh->m_pParentEntity, toEnemy, 50); // Start Boarding On Enemy's Vehicle //----------------------------------- - Vehicle_t* enemyVeh = G_IsRidingVehicle(rider->enemy); - enemyVeh->m_iBoarding = (riderRightDot>0)?(VEH_MOUNT_THROW_RIGHT):(VEH_MOUNT_THROW_LEFT); + Vehicle_t *enemyVeh = G_IsRidingVehicle(rider->enemy); + enemyVeh->m_iBoarding = (riderRightDot > 0) ? (VEH_MOUNT_THROW_RIGHT) : (VEH_MOUNT_THROW_LEFT); enemyVeh->m_pVehicleInfo->Board(enemyVeh, rider); } // Don't Jump Off If Holding Strafe Key and Moving Fast - else if (pUmcd->rightmove && (parent->client->ps.speed>=10)) - { + else if (pUmcd->rightmove && (parent->client->ps.speed >= 10)) { return true; } #endif -//=================================================================== + //=================================================================== - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { // Allow them to force jump off. - VectorScale( parent->client->ps.velocity, 0.5f, rider->client->ps.velocity ); + VectorScale(parent->client->ps.velocity, 0.5f, rider->client->ps.velocity); rider->client->ps.velocity[2] += JUMP_VELOCITY; #ifdef _JK2MP rider->client->ps.fd.forceJumpZStart = rider->client->ps.origin[2]; if (!trap_ICARUS_TaskIDPending(rider, TID_CHAN_VOICE)) #else - rider->client->ps.pm_flags |= ( PMF_JUMPING | PMF_JUMP_HELD ); + rider->client->ps.pm_flags |= (PMF_JUMPING | PMF_JUMP_HELD); rider->client->ps.forceJumpZStart = rider->client->ps.origin[2]; - if ( !Q3_TaskIDPending( rider, TID_CHAN_VOICE ) ) + if (!Q3_TaskIDPending(rider, TID_CHAN_VOICE)) #endif { - G_AddEvent( rider, EV_JUMP, 0 ); + G_AddEvent(rider, EV_JUMP, 0); } #if 1 - Vehicle_SetAnim( rider, SETANIM_BOTH, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 300 ); + Vehicle_SetAnim(rider, SETANIM_BOTH, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 300); #else #endif @@ -2422,48 +2110,37 @@ static bool UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd ) // Roll off. #ifdef _JK2MP - if ( pUmcd->upmove < 0 ) - { + if (pUmcd->upmove < 0) { animNumber_t Anim = BOTH_ROLL_B; pVeh->m_EjectDir = VEH_EJECT_REAR; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_ROLL_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else if ( pUmcd->rightmove < 0 ) - { + } else if (pUmcd->rightmove < 0) { Anim = BOTH_ROLL_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; - } - else if ( pUmcd->forwardmove < 0 ) - { + } else if (pUmcd->forwardmove < 0) { Anim = BOTH_ROLL_B; pVeh->m_EjectDir = VEH_EJECT_REAR; - } - else if ( pUmcd->forwardmove > 0 ) - { + } else if (pUmcd->forwardmove > 0) { Anim = BOTH_ROLL_F; pVeh->m_EjectDir = VEH_EJECT_FRONT; } - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { - if ( !(pVeh->m_ulFlags & VEH_FLYING) ) - { - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { + if (!(pVeh->m_ulFlags & VEH_FLYING)) { + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); #if 1 - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 300 ); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 300); #else #endif - //PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - rider->client->ps.weaponTime = rider->client->ps.torsoAnimTimer - 200;//just to make sure it's cleared when roll is done - G_AddEvent( rider, EV_ROLL, 0 ); + // PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); + rider->client->ps.weaponTime = rider->client->ps.torsoAnimTimer - 200; // just to make sure it's cleared when roll is done + G_AddEvent(rider, EV_ROLL, 0); } return false; } - } #endif } @@ -2471,50 +2148,45 @@ static bool UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd ) return true; } -#ifdef _JK2MP //we want access to this one clientside, but it's the only -//generic vehicle function we care about over there +#ifdef _JK2MP // we want access to this one clientside, but it's the only +// generic vehicle function we care about over there #include "../namespace_begin.h" -extern void AttachRidersGeneric( Vehicle_t *pVeh ); +extern void AttachRidersGeneric(Vehicle_t *pVeh); #include "../namespace_end.h" #endif // Attachs all the riders of this vehicle to their appropriate tag (*driver, *pass1, *pass2, whatever...). -static void AttachRiders( Vehicle_t *pVeh ) -{ +static void AttachRiders(Vehicle_t *pVeh) { #ifdef _JK2MP int i = 0; AttachRidersGeneric(pVeh); - if (pVeh->m_pPilot) - { + if (pVeh->m_pPilot) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; pilot->waypoint = parent->waypoint; // take the veh's waypoint as your own - //assuming we updated him relative to the bolt in AttachRidersGeneric - G_SetOrigin( pilot, pilot->client->ps.origin ); - trap_LinkEntity( pilot ); + // assuming we updated him relative to the bolt in AttachRidersGeneric + G_SetOrigin(pilot, pilot->client->ps.origin); + trap_LinkEntity(pilot); } - if (pVeh->m_pOldPilot) - { + if (pVeh->m_pOldPilot) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *oldpilot = (gentity_t *)pVeh->m_pOldPilot; oldpilot->waypoint = parent->waypoint; // take the veh's waypoint as your own - //assuming we updated him relative to the bolt in AttachRidersGeneric - G_SetOrigin( oldpilot, oldpilot->client->ps.origin ); - trap_LinkEntity( oldpilot ); + // assuming we updated him relative to the bolt in AttachRidersGeneric + G_SetOrigin(oldpilot, oldpilot->client->ps.origin); + trap_LinkEntity(oldpilot); } - //attach passengers - while (i < pVeh->m_iNumPassengers) - { - if (pVeh->m_ppPassengers[i]) - { + // attach passengers + while (i < pVeh->m_iNumPassengers) { + if (pVeh->m_ppPassengers[i]) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles; + vec3_t yawOnlyAngles; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilot = (gentity_t *)pVeh->m_ppPassengers[i]; int crotchBolt; @@ -2527,50 +2199,44 @@ static void AttachRiders( Vehicle_t *pVeh ) VectorSet(yawOnlyAngles, 0, parent->client->ps.viewangles[YAW], 0); // Get the driver tag. - trap_G2API_GetBoltMatrix( parent->ghoul2, 0, crotchBolt, &boltMatrix, - yawOnlyAngles, parent->client->ps.origin, - level.time, NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, pilot->client->ps.origin ); + trap_G2API_GetBoltMatrix(parent->ghoul2, 0, crotchBolt, &boltMatrix, yawOnlyAngles, parent->client->ps.origin, level.time, NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pilot->client->ps.origin); - G_SetOrigin( pilot, pilot->client->ps.origin ); - trap_LinkEntity( pilot ); + G_SetOrigin(pilot, pilot->client->ps.origin); + trap_LinkEntity(pilot); } i++; } - //attach droid - if (pVeh->m_pDroidUnit - && pVeh->m_iDroidUnitTag != -1) - { + // attach droid + if (pVeh->m_pDroidUnit && pVeh->m_iDroidUnitTag != -1) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles, fwd; + vec3_t yawOnlyAngles, fwd; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *droid = (gentity_t *)pVeh->m_pDroidUnit; assert(parent->ghoul2); assert(parent->client); - //assert(droid->client); + // assert(droid->client); - if ( droid->client ) - { + if (droid->client) { VectorSet(yawOnlyAngles, 0, parent->client->ps.viewangles[YAW], 0); // Get the droid tag. - trap_G2API_GetBoltMatrix( parent->ghoul2, 0, pVeh->m_iDroidUnitTag, &boltMatrix, - yawOnlyAngles, parent->currentOrigin, - level.time, NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, droid->client->ps.origin ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, fwd ); - vectoangles( fwd, droid->client->ps.viewangles ); - - G_SetOrigin( droid, droid->client->ps.origin ); - G_SetAngles( droid, droid->client->ps.viewangles); - SetClientViewAngle( droid, droid->client->ps.viewangles ); - trap_LinkEntity( droid ); - - if ( droid->NPC ) - { - NPC_SetAnim( droid, SETANIM_BOTH, BOTH_STAND2, (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD) ); + trap_G2API_GetBoltMatrix(parent->ghoul2, 0, pVeh->m_iDroidUnitTag, &boltMatrix, yawOnlyAngles, parent->currentOrigin, level.time, NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droid->client->ps.origin); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd); + vectoangles(fwd, droid->client->ps.viewangles); + + G_SetOrigin(droid, droid->client->ps.origin); + G_SetAngles(droid, droid->client->ps.viewangles); + SetClientViewAngle(droid, droid->client->ps.viewangles); + trap_LinkEntity(droid); + + if (droid->NPC) { + NPC_SetAnim(droid, SETANIM_BOTH, BOTH_STAND2, (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD)); droid->client->ps.legsTimer = 500; droid->client->ps.torsoTimer = 500; } @@ -2578,55 +2244,49 @@ static void AttachRiders( Vehicle_t *pVeh ) } #else // If we have a pilot, attach him to the driver tag. - if ( pVeh->m_pPilot ) - { - gentity_t * const parent = pVeh->m_pParentEntity; - gentity_t * const pilot = pVeh->m_pPilot; - mdxaBone_t boltMatrix; + if (pVeh->m_pPilot) { + gentity_t *const parent = pVeh->m_pParentEntity; + gentity_t *const pilot = pVeh->m_pPilot; + mdxaBone_t boltMatrix; pilot->waypoint = parent->waypoint; // take the veh's waypoint as your own // Get the driver tag. - gi.G2API_GetBoltMatrix( parent->ghoul2, parent->playerModel, parent->crotchBolt, &boltMatrix, - pVeh->m_vOrientation, parent->currentOrigin, - (cg.time?cg.time:level.time), NULL, parent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pilot->client->ps.origin ); - G_SetOrigin( pilot, pilot->client->ps.origin ); - gi.linkentity( pilot ); + gi.G2API_GetBoltMatrix(parent->ghoul2, parent->playerModel, parent->crotchBolt, &boltMatrix, pVeh->m_vOrientation, parent->currentOrigin, + (cg.time ? cg.time : level.time), NULL, parent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pilot->client->ps.origin); + G_SetOrigin(pilot, pilot->client->ps.origin); + gi.linkentity(pilot); } // If we have a pilot, attach him to the driver tag. - if ( pVeh->m_pOldPilot ) - { - gentity_t * const parent = pVeh->m_pParentEntity; - gentity_t * const pilot = pVeh->m_pOldPilot; - mdxaBone_t boltMatrix; + if (pVeh->m_pOldPilot) { + gentity_t *const parent = pVeh->m_pParentEntity; + gentity_t *const pilot = pVeh->m_pOldPilot; + mdxaBone_t boltMatrix; pilot->waypoint = parent->waypoint; // take the veh's waypoint as your own // Get the driver tag. - gi.G2API_GetBoltMatrix( parent->ghoul2, parent->playerModel, parent->crotchBolt, &boltMatrix, - pVeh->m_vOrientation, parent->currentOrigin, - (cg.time?cg.time:level.time), NULL, parent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pilot->client->ps.origin ); - G_SetOrigin( pilot, pilot->client->ps.origin ); - gi.linkentity( pilot ); + gi.G2API_GetBoltMatrix(parent->ghoul2, parent->playerModel, parent->crotchBolt, &boltMatrix, pVeh->m_vOrientation, parent->currentOrigin, + (cg.time ? cg.time : level.time), NULL, parent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pilot->client->ps.origin); + G_SetOrigin(pilot, pilot->client->ps.origin); + gi.linkentity(pilot); } #endif } // Make someone invisible and un-collidable. -static void Ghost( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +static void Ghost(Vehicle_t *pVeh, bgEntity_t *pEnt) { gentity_t *ent; - if ( !pEnt ) + if (!pEnt) return; ent = (gentity_t *)pEnt; ent->s.eFlags |= EF_NODRAW; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.eFlags |= EF_NODRAW; } #ifdef _JK2MP @@ -2637,18 +2297,16 @@ static void Ghost( Vehicle_t *pVeh, bgEntity_t *pEnt ) } // Make someone visible and collidable. -static void UnGhost( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +static void UnGhost(Vehicle_t *pVeh, bgEntity_t *pEnt) { gentity_t *ent; - if ( !pEnt ) + if (!pEnt) return; ent = (gentity_t *)pEnt; ent->s.eFlags &= ~EF_NODRAW; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.eFlags &= ~EF_NODRAW; } #ifdef _JK2MP @@ -2659,67 +2317,58 @@ static void UnGhost( Vehicle_t *pVeh, bgEntity_t *pEnt ) } #ifdef _JK2MP -//try to resize the bounding box around a torn apart ship -void G_VehicleDamageBoxSizing(Vehicle_t *pVeh) -{ +// try to resize the bounding box around a torn apart ship +void G_VehicleDamageBoxSizing(Vehicle_t *pVeh) { vec3_t fwd, right, up; - vec3_t nose; //maxs - vec3_t back; //mins + vec3_t nose; // maxs + vec3_t back; // mins trace_t trace; - const float fDist = 256.0f; //estimated distance to nose from origin - const float bDist = 256.0f; //estimated distance to back from origin - const float wDist = 32.0f; //width on each side from origin - const float hDist = 32.0f; //height on each side from origin + const float fDist = 256.0f; // estimated distance to nose from origin + const float bDist = 256.0f; // estimated distance to back from origin + const float wDist = 32.0f; // width on each side from origin + const float hDist = 32.0f; // height on each side from origin gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if (!parent->ghoul2 || !parent->m_pVehicle || !parent->client) - { //shouldn't have gotten in here then + if (!parent->ghoul2 || !parent->m_pVehicle || !parent->client) { // shouldn't have gotten in here then return; } - //for now, let's only do anything if all wings are stripped off. - //this is because I want to be able to tear my wings off and fling - //myself down narrow hallways to my death. Because it's fun! -rww - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) ) - { + // for now, let's only do anything if all wings are stripped off. + // this is because I want to be able to tear my wings off and fling + // myself down narrow hallways to my death. Because it's fun! -rww + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || + !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { return; } - //get directions based on orientation + // get directions based on orientation AngleVectors(pVeh->m_vOrientation, fwd, right, up); - //get the nose and back positions (relative to 0, they're gonna be mins/maxs) + // get the nose and back positions (relative to 0, they're gonna be mins/maxs) VectorMA(vec3_origin, fDist, fwd, nose); VectorMA(vec3_origin, -bDist, fwd, back); - //move the nose and back to opposite right/left, they will end up as our relative mins and maxs + // move the nose and back to opposite right/left, they will end up as our relative mins and maxs VectorMA(nose, wDist, right, nose); VectorMA(nose, -wDist, right, back); - //use the same concept for up/down now + // use the same concept for up/down now VectorMA(nose, hDist, up, nose); VectorMA(nose, -hDist, up, back); - //and now, let's trace and see if our new mins/maxs are safe.. + // and now, let's trace and see if our new mins/maxs are safe.. trap_Trace(&trace, parent->client->ps.origin, back, nose, parent->client->ps.origin, parent->s.number, parent->clipmask); - if (!trace.allsolid && !trace.startsolid && trace.fraction == 1.0f) - { //all clear! + if (!trace.allsolid && !trace.startsolid && trace.fraction == 1.0f) { // all clear! VectorCopy(nose, parent->maxs); VectorCopy(back, parent->mins); - } - else - { //oh well, DIE! - //FIXME: does this give proper credit to the enemy who shot you down? + } else { // oh well, DIE! + // FIXME: does this give proper credit to the enemy who shot you down? G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } -//get one of 4 possible impact locations based on the trace direction -int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) -{ +// get one of 4 possible impact locations based on the trace direction +int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) { float impactAngle; float relativeAngle; trace_t localTrace; @@ -2730,8 +2379,7 @@ int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) Vehicle_t *pVeh = veh->m_pVehicle; qboolean noseClear = qfalse; - if (!trace || !pVeh || !veh->client) - { + if (!trace || !pVeh || !veh->client) { return -1; } @@ -2739,194 +2387,151 @@ int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) VectorSet(testMins, -24.0f, -24.0f, -24.0f); VectorSet(testMaxs, 24.0f, 24.0f, 24.0f); - //do a trace to determine if the nose is clear + // do a trace to determine if the nose is clear VectorMA(veh->client->ps.origin, 256.0f, fwd, fPos); trap_Trace(&localTrace, veh->client->ps.origin, testMins, testMaxs, fPos, veh->s.number, veh->clipmask); - if (!localTrace.startsolid && !localTrace.allsolid && localTrace.fraction == 1.0f) - { //otherwise I guess it's not clear.. + if (!localTrace.startsolid && !localTrace.allsolid && localTrace.fraction == 1.0f) { // otherwise I guess it's not clear.. noseClear = qtrue; } - if (noseClear) - { //if nose is clear check for tearing the wings off - //sadly, the trace endpos given always matches the vehicle origin, so we - //can't get a real impact direction. First we'll trace forward and see if the wings are colliding - //with anything, and if not, we'll fall back to checking the trace plane normal. + if (noseClear) { // if nose is clear check for tearing the wings off + // sadly, the trace endpos given always matches the vehicle origin, so we + // can't get a real impact direction. First we'll trace forward and see if the wings are colliding + // with anything, and if not, we'll fall back to checking the trace plane normal. VectorMA(veh->client->ps.origin, 128.0f, right, rWing); VectorMA(veh->client->ps.origin, -128.0f, right, lWing); - //test the right wing - unless it's already removed - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { + // test the right wing - unless it's already removed + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { VectorMA(rWing, 256.0f, fwd, fPos); trap_Trace(&localTrace, rWing, testMins, testMaxs, fPos, veh->s.number, veh->clipmask); - if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) - { //impact + if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) { // impact return SHIPSURF_RIGHT; } } - //test the left wing - unless it's already removed - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { + // test the left wing - unless it's already removed + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { VectorMA(lWing, 256.0f, fwd, fPos); trap_Trace(&localTrace, lWing, testMins, testMaxs, fPos, veh->s.number, veh->clipmask); - if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) - { //impact + if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) { // impact return SHIPSURF_LEFT; } } } - //try to use the trace plane normal + // try to use the trace plane normal impactAngle = vectoyaw(trace->plane.normal); relativeAngle = AngleSubtract(impactAngle, veh->client->ps.viewangles[YAW]); - if (relativeAngle > 130 || - relativeAngle < -130) - { //consider this front + if (relativeAngle > 130 || relativeAngle < -130) { // consider this front return SHIPSURF_FRONT; - } - else if (relativeAngle > 0) - { + } else if (relativeAngle > 0) { return SHIPSURF_RIGHT; - } - else if (relativeAngle < 0) - { + } else if (relativeAngle < 0) { return SHIPSURF_LEFT; } return SHIPSURF_BACK; } -//try to break surfaces off the ship on impact -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 -extern void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags); //NPC_utils.c -int G_ShipSurfaceForSurfName( const char *surfaceName ) -{ - if ( !surfaceName ) - { +// try to break surfaces off the ship on impact +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 +extern void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags); // NPC_utils.c +int G_ShipSurfaceForSurfName(const char *surfaceName) { + if (!surfaceName) { return -1; } - if ( !Q_strncmp( "nose", surfaceName, 4 ) - || !Q_strncmp( "f_gear", surfaceName, 6 ) - || !Q_strncmp( "glass", surfaceName, 5 ) ) - { + if (!Q_strncmp("nose", surfaceName, 4) || !Q_strncmp("f_gear", surfaceName, 6) || !Q_strncmp("glass", surfaceName, 5)) { return SHIPSURF_FRONT; } - if ( !Q_strncmp( "body", surfaceName, 4 ) ) - { + if (!Q_strncmp("body", surfaceName, 4)) { return SHIPSURF_BACK; } - if ( !Q_strncmp( "r_wing1", surfaceName, 7 ) - || !Q_strncmp( "r_wing2", surfaceName, 7 ) - || !Q_strncmp( "r_gear", surfaceName, 6 ) ) - { + if (!Q_strncmp("r_wing1", surfaceName, 7) || !Q_strncmp("r_wing2", surfaceName, 7) || !Q_strncmp("r_gear", surfaceName, 6)) { return SHIPSURF_RIGHT; } - if ( !Q_strncmp( "l_wing1", surfaceName, 7 ) - || !Q_strncmp( "l_wing2", surfaceName, 7 ) - || !Q_strncmp( "l_gear", surfaceName, 6 ) ) - { + if (!Q_strncmp("l_wing1", surfaceName, 7) || !Q_strncmp("l_wing2", surfaceName, 7) || !Q_strncmp("l_gear", surfaceName, 6)) { return SHIPSURF_LEFT; } return -1; } -void G_SetVehDamageFlags( gentity_t *veh, int shipSurf, int damageLevel ) -{ +void G_SetVehDamageFlags(gentity_t *veh, int shipSurf, int damageLevel) { int dmgFlag; - switch ( damageLevel ) - { - case 3://destroyed - //add both flags so cgame side knows this surf is GONE - //add heavy - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs |= (1<client->ps.brokenLimbs |= (1 << dmgFlag); + // add light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs |= (1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; - //check droid - if ( shipSurf == SHIPSURF_BACK ) - {//destroy the droid if we have one - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pDroidUnit ) - {//we have one + // check droid + if (shipSurf == SHIPSURF_BACK) { // destroy the droid if we have one + if (veh->m_pVehicle && veh->m_pVehicle->m_pDroidUnit) { // we have one gentity_t *droidEnt = (gentity_t *)veh->m_pVehicle->m_pDroidUnit; - if ( droidEnt - && ((droidEnt->flags&FL_UNDYING) || droidEnt->health > 0) ) - {//boom - //make it vulnerable + if (droidEnt && ((droidEnt->flags & FL_UNDYING) || droidEnt->health > 0)) { // boom + // make it vulnerable droidEnt->flags &= ~FL_UNDYING; - //blow it up - G_Damage( droidEnt, veh->enemy, veh->enemy, NULL, NULL, 99999, 0, MOD_UNKNOWN ); + // blow it up + G_Damage(droidEnt, veh->enemy, veh->enemy, NULL, NULL, 99999, 0, MOD_UNKNOWN); } } } break; - case 2://heavy only - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs |= (1 << dmgFlag); + // remove light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; - //check droid - if ( shipSurf == SHIPSURF_BACK ) - {//make the droid vulnerable if we have one - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pDroidUnit ) - {//we have one + // check droid + if (shipSurf == SHIPSURF_BACK) { // make the droid vulnerable if we have one + if (veh->m_pVehicle && veh->m_pVehicle->m_pDroidUnit) { // we have one gentity_t *droidEnt = (gentity_t *)veh->m_pVehicle->m_pDroidUnit; - if ( droidEnt - && (droidEnt->flags&FL_UNDYING) ) - {//make it vulnerab;e + if (droidEnt && (droidEnt->flags & FL_UNDYING)) { // make it vulnerab;e droidEnt->flags &= ~FL_UNDYING; } } } break; - case 1://light only - //add light - dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs |= (1 << dmgFlag); + // remove heavy (shouldn't have to do this, but... + dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; break; - case 0://no damage + case 0: // no damage default: - //remove heavy - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs &= ~(1 << dmgFlag); + // remove light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; break; } } -void G_VehicleSetDamageLocFlags( gentity_t *veh, int impactDir, int deathPoint ) -{ - if ( !veh->client ) - { +void G_VehicleSetDamageLocFlags(gentity_t *veh, int impactDir, int deathPoint) { + if (!veh->client) { return; - } - else - { - int deathPoint, heavyDamagePoint, lightDamagePoint; - switch(impactDir) - { + } else { + int deathPoint, heavyDamagePoint, lightDamagePoint; + switch (impactDir) { case SHIPSURF_FRONT: deathPoint = veh->m_pVehicle->m_pVehicleInfo->health_front; break; @@ -2943,91 +2548,77 @@ void G_VehicleSetDamageLocFlags( gentity_t *veh, int impactDir, int deathPoint ) return; break; } - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pVehicleInfo - && veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel - && veh->m_pVehicle->m_pVehicleInfo->armor ) - { - float perc = ((float)veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel/(float)veh->m_pVehicle->m_pVehicleInfo->armor); - if ( perc > 0.99f ) - { + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel && + veh->m_pVehicle->m_pVehicleInfo->armor) { + float perc = ((float)veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel / (float)veh->m_pVehicle->m_pVehicleInfo->armor); + if (perc > 0.99f) { perc = 0.99f; } - heavyDamagePoint = ceil( deathPoint*perc*0.25f ); - lightDamagePoint = ceil( deathPoint*perc ); - } - else - { - heavyDamagePoint = ceil( deathPoint*0.66f ); - lightDamagePoint = ceil( deathPoint*0.14f ); + heavyDamagePoint = ceil(deathPoint * perc * 0.25f); + lightDamagePoint = ceil(deathPoint * perc); + } else { + heavyDamagePoint = ceil(deathPoint * 0.66f); + lightDamagePoint = ceil(deathPoint * 0.14f); } - if ( veh->locationDamage[impactDir] >= deathPoint) - {//destroyed - G_SetVehDamageFlags( veh, impactDir, 3 ); - } - else if ( veh->locationDamage[impactDir] <= heavyDamagePoint ) - {//heavy only - G_SetVehDamageFlags( veh, impactDir, 2 ); - } - else if ( veh->locationDamage[impactDir] <= lightDamagePoint ) - {//light only - G_SetVehDamageFlags( veh, impactDir, 1 ); + if (veh->locationDamage[impactDir] >= deathPoint) { // destroyed + G_SetVehDamageFlags(veh, impactDir, 3); + } else if (veh->locationDamage[impactDir] <= heavyDamagePoint) { // heavy only + G_SetVehDamageFlags(veh, impactDir, 2); + } else if (veh->locationDamage[impactDir] <= lightDamagePoint) { // light only + G_SetVehDamageFlags(veh, impactDir, 1); } } } -qboolean G_FlyVehicleDestroySurface( gentity_t *veh, int surface ) -{ - char *surfName[4]; //up to 4 surfs at once +qboolean G_FlyVehicleDestroySurface(gentity_t *veh, int surface) { + char *surfName[4]; // up to 4 surfs at once int numSurfs = 0; int smashedBits = 0; - if (surface == -1) - { //not valid? + if (surface == -1) { // not valid? return qfalse; } - switch(surface) - { - case SHIPSURF_FRONT: //break the nose off + switch (surface) { + case SHIPSURF_FRONT: // break the nose off surfName[0] = "nose"; smashedBits = (SHIPSURF_BROKEN_G); numSurfs = 1; break; - case SHIPSURF_BACK: //break both the bottom wings off for a backward impact I guess + case SHIPSURF_BACK: // break both the bottom wings off for a backward impact I guess surfName[0] = "r_wing2"; surfName[1] = "l_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "r_gear"; surfName[3] = "l_gear"; - smashedBits = (SHIPSURF_BROKEN_A|SHIPSURF_BROKEN_B|SHIPSURF_BROKEN_D|SHIPSURF_BROKEN_F); + smashedBits = (SHIPSURF_BROKEN_A | SHIPSURF_BROKEN_B | SHIPSURF_BROKEN_D | SHIPSURF_BROKEN_F); numSurfs = 4; break; - case SHIPSURF_RIGHT: //break both right wings off + case SHIPSURF_RIGHT: // break both right wings off surfName[0] = "r_wing1"; surfName[1] = "r_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "r_gear"; - smashedBits = (SHIPSURF_BROKEN_B|SHIPSURF_BROKEN_E|SHIPSURF_BROKEN_F); + smashedBits = (SHIPSURF_BROKEN_B | SHIPSURF_BROKEN_E | SHIPSURF_BROKEN_F); numSurfs = 3; break; - case SHIPSURF_LEFT: //break both left wings off + case SHIPSURF_LEFT: // break both left wings off surfName[0] = "l_wing1"; surfName[1] = "l_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "l_gear"; - smashedBits = (SHIPSURF_BROKEN_A|SHIPSURF_BROKEN_C|SHIPSURF_BROKEN_D); + smashedBits = (SHIPSURF_BROKEN_A | SHIPSURF_BROKEN_C | SHIPSURF_BROKEN_D); numSurfs = 3; break; @@ -3035,60 +2626,52 @@ qboolean G_FlyVehicleDestroySurface( gentity_t *veh, int surface ) break; } - if (numSurfs < 1) - { //didn't get any valid surfs.. + if (numSurfs < 1) { // didn't get any valid surfs.. return qfalse; } - while (numSurfs > 0) - { //use my silly system of automatically managing surf status on both client and server + while (numSurfs > 0) { // use my silly system of automatically managing surf status on both client and server numSurfs--; NPC_SetSurfaceOnOff(veh, surfName[numSurfs], TURN_OFF); } - if ( !veh->m_pVehicle->m_iRemovedSurfaces ) - {//first time something got blown off - if ( veh->m_pVehicle->m_pPilot ) - {//make the pilot scream to his death - G_EntitySound((gentity_t*)veh->m_pVehicle->m_pPilot, CHAN_VOICE, G_SoundIndex("*falling1.wav")); + if (!veh->m_pVehicle->m_iRemovedSurfaces) { // first time something got blown off + if (veh->m_pVehicle->m_pPilot) { // make the pilot scream to his death + G_EntitySound((gentity_t *)veh->m_pVehicle->m_pPilot, CHAN_VOICE, G_SoundIndex("*falling1.wav")); } } - //so we can check what's broken + // so we can check what's broken veh->m_pVehicle->m_iRemovedSurfaces |= smashedBits; - //do some explosive damage, but don't damage this ship with it + // do some explosive damage, but don't damage this ship with it G_RadiusDamage(veh->client->ps.origin, veh, 100, 500, veh, NULL, MOD_SUICIDE); - //when spiraling to your death, do the electical shader + // when spiraling to your death, do the electical shader veh->client->ps.electrifyTime = level.time + 10000; return qtrue; } -void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force) -{ +void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force) { int impactDir; int secondImpact; int deathPoint = -1; qboolean alreadyRebroken = qfalse; - if (!veh->ghoul2 || !veh->m_pVehicle) - { //no g2 instance.. or no vehicle instance + if (!veh->ghoul2 || !veh->m_pVehicle) { // no g2 instance.. or no vehicle instance return; } - impactDir = G_FlyVehicleImpactDir(veh, trace); + impactDir = G_FlyVehicleImpactDir(veh, trace); anotherImpact: - if (impactDir == -1) - { //not valid? + if (impactDir == -1) { // not valid? return; } - veh->locationDamage[impactDir] += magnitude*7; + veh->locationDamage[impactDir] += magnitude * 7; - switch(impactDir) - { + switch (impactDir) { case SHIPSURF_FRONT: deathPoint = veh->m_pVehicle->m_pVehicleInfo->health_front; break; @@ -3105,30 +2688,22 @@ void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitud break; } - if ( deathPoint != -1 ) - {//got a valid health value - if ( force && veh->locationDamage[impactDir] < deathPoint ) - {//force that surf to be destroyed + if (deathPoint != -1) { // got a valid health value + if (force && veh->locationDamage[impactDir] < deathPoint) { // force that surf to be destroyed veh->locationDamage[impactDir] = deathPoint; } - if ( veh->locationDamage[impactDir] >= deathPoint) - { //do it - if ( G_FlyVehicleDestroySurface( veh, impactDir ) ) - {//actually took off a surface - G_VehicleSetDamageLocFlags( veh, impactDir, deathPoint ); + if (veh->locationDamage[impactDir] >= deathPoint) { // do it + if (G_FlyVehicleDestroySurface(veh, impactDir)) { // actually took off a surface + G_VehicleSetDamageLocFlags(veh, impactDir, deathPoint); } - } - else - { - G_VehicleSetDamageLocFlags( veh, impactDir, deathPoint ); + } else { + G_VehicleSetDamageLocFlags(veh, impactDir, deathPoint); } } - if (!alreadyRebroken) - { + if (!alreadyRebroken) { secondImpact = G_FlyVehicleImpactDir(veh, trace); - if (impactDir != secondImpact) - { //can break off another piece in this same impact.. but only break off up to 2 at once + if (impactDir != secondImpact) { // can break off another piece in this same impact.. but only break off up to 2 at once alreadyRebroken = qtrue; impactDir = secondImpact; goto anotherImpact; @@ -3136,63 +2711,57 @@ void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitud } } -void G_VehUpdateShields( gentity_t *targ ) -{ - if ( !targ || !targ->client - || !targ->m_pVehicle || !targ->m_pVehicle->m_pVehicleInfo ) - { +void G_VehUpdateShields(gentity_t *targ) { + if (!targ || !targ->client || !targ->m_pVehicle || !targ->m_pVehicle->m_pVehicleInfo) { return; } - if ( targ->m_pVehicle->m_pVehicleInfo->shields <= 0 ) - {//doesn't have shields, so don't have to send it + if (targ->m_pVehicle->m_pVehicleInfo->shields <= 0) { // doesn't have shields, so don't have to send it return; } - targ->client->ps.activeForcePass = floor(((float)targ->m_pVehicle->m_iShields/(float)targ->m_pVehicle->m_pVehicleInfo->shields)*10.0f); + targ->client->ps.activeForcePass = floor(((float)targ->m_pVehicle->m_iShields / (float)targ->m_pVehicle->m_pVehicleInfo->shields) * 10.0f); } #endif // Set the parent entity of this Vehicle NPC. -void SetParent( Vehicle_t *pVeh, bgEntity_t *pParentEntity ) { pVeh->m_pParentEntity = pParentEntity; } +void SetParent(Vehicle_t *pVeh, bgEntity_t *pParentEntity) { pVeh->m_pParentEntity = pParentEntity; } // Add a pilot to the vehicle. -void SetPilot( Vehicle_t *pVeh, bgEntity_t *pPilot ) { pVeh->m_pPilot = pPilot; } +void SetPilot(Vehicle_t *pVeh, bgEntity_t *pPilot) { pVeh->m_pPilot = pPilot; } // Add a passenger to the vehicle (false if we're full). -bool AddPassenger( Vehicle_t *pVeh ) { return false; } +bool AddPassenger(Vehicle_t *pVeh) { return false; } // Whether this vehicle is currently inhabited (by anyone) or not. -bool Inhabited( Vehicle_t *pVeh ) { return ( pVeh->m_pPilot ) ? true : false; } - +bool Inhabited(Vehicle_t *pVeh) { return (pVeh->m_pPilot) ? true : false; } // Setup the shared functions (one's that all vehicles would generally use). -void G_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ -// pVehInfo->AnimateVehicle = AnimateVehicle; -// pVehInfo->AnimateRiders = AnimateRiders; - pVehInfo->ValidateBoard = ValidateBoard; - pVehInfo->SetParent = SetParent; - pVehInfo->SetPilot = SetPilot; - pVehInfo->AddPassenger = AddPassenger; - pVehInfo->Animate = Animate; - pVehInfo->Board = Board; - pVehInfo->Eject = Eject; - pVehInfo->EjectAll = EjectAll; - pVehInfo->StartDeathDelay = StartDeathDelay; - pVehInfo->DeathUpdate = DeathUpdate; - pVehInfo->RegisterAssets = RegisterAssets; - pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; - pVehInfo->UpdateRider = UpdateRider; -// pVehInfo->ProcessMoveCommands = ProcessMoveCommands; -// pVehInfo->ProcessOrientCommands = ProcessOrientCommands; - pVehInfo->AttachRiders = AttachRiders; - pVehInfo->Ghost = Ghost; - pVehInfo->UnGhost = UnGhost; - pVehInfo->Inhabited = Inhabited; +void G_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo) { + // pVehInfo->AnimateVehicle = AnimateVehicle; + // pVehInfo->AnimateRiders = AnimateRiders; + pVehInfo->ValidateBoard = ValidateBoard; + pVehInfo->SetParent = SetParent; + pVehInfo->SetPilot = SetPilot; + pVehInfo->AddPassenger = AddPassenger; + pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + pVehInfo->Eject = Eject; + pVehInfo->EjectAll = EjectAll; + pVehInfo->StartDeathDelay = StartDeathDelay; + pVehInfo->DeathUpdate = DeathUpdate; + pVehInfo->RegisterAssets = RegisterAssets; + pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; + pVehInfo->UpdateRider = UpdateRider; + // pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + // pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + pVehInfo->AttachRiders = AttachRiders; + pVehInfo->Ghost = Ghost; + pVehInfo->UnGhost = UnGhost; + pVehInfo->Inhabited = Inhabited; } #ifdef _JK2MP -//get rid of all the crazy defs we added for this file +// get rid of all the crazy defs we added for this file #undef currentAngles #undef currentOrigin #undef mins diff --git a/code/game/g_weapon.cpp b/code/game/g_weapon.cpp index a5979e7c71..469a1546d0 100644 --- a/code/game/g_weapon.cpp +++ b/code/game/g_weapon.cpp @@ -33,100 +33,94 @@ along with this program; if not, see . #include "w_local.h" #include "../cgame/cg_local.h" -vec3_t forwardVec, vrightVec, up; -vec3_t muzzle; +vec3_t forwardVec, vrightVec, up; +vec3_t muzzle; gentity_t *ent_list[MAX_GENTITIES]; -extern cvar_t *g_debugMelee; +extern cvar_t *g_debugMelee; // some naughty little things that are used cg side int g_rocketLockEntNum = ENTITYNUM_NONE; int g_rocketLockTime = 0; -int g_rocketSlackTime = 0; +int g_rocketSlackTime = 0; // Weapon Helper Functions -float weaponSpeed[WP_NUM_WEAPONS][2] = -{ - { 0,0 },//WP_NONE, - { 0,0 },//WP_SABER, // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. - { BRYAR_PISTOL_VEL,BRYAR_PISTOL_VEL },//WP_BLASTER_PISTOL, - { BLASTER_VELOCITY,BLASTER_VELOCITY },//WP_BLASTER, - { Q3_INFINITE,Q3_INFINITE },//WP_DISRUPTOR, - { BOWCASTER_VELOCITY,BOWCASTER_VELOCITY },//WP_BOWCASTER, - { REPEATER_VELOCITY,REPEATER_ALT_VELOCITY },//WP_REPEATER, - { DEMP2_VELOCITY,DEMP2_ALT_RANGE },//WP_DEMP2, - { FLECHETTE_VEL,FLECHETTE_MINE_VEL },//WP_FLECHETTE, - { ROCKET_VELOCITY,ROCKET_ALT_VELOCITY },//WP_ROCKET_LAUNCHER, - { TD_VELOCITY,TD_ALT_VELOCITY },//WP_THERMAL, - { 0,0 },//WP_TRIP_MINE, - { 0,0 },//WP_DET_PACK, - { CONC_VELOCITY,Q3_INFINITE },//WP_CONCUSSION, - { 0,0 },//WP_MELEE, // Any ol' melee attack - { 0,0 },//WP_STUN_BATON, - { BRYAR_PISTOL_VEL,BRYAR_PISTOL_VEL },//WP_BRYAR_PISTOL, - { EMPLACED_VEL,EMPLACED_VEL },//WP_EMPLACED_GUN, - { BRYAR_PISTOL_VEL,BRYAR_PISTOL_VEL },//WP_BOT_LASER, // Probe droid - Laser blast - { 0,0 },//WP_TURRET, // turret guns - { ATST_MAIN_VEL,ATST_MAIN_VEL },//WP_ATST_MAIN, - { ATST_SIDE_MAIN_VELOCITY,ATST_SIDE_ALT_NPC_VELOCITY },//WP_ATST_SIDE, - { EMPLACED_VEL,EMPLACED_VEL },//WP_TIE_FIGHTER, - { EMPLACED_VEL,REPEATER_ALT_VELOCITY },//WP_RAPID_FIRE_CONC, - { 0,0 },//WP_JAWA, - { TUSKEN_RIFLE_VEL,TUSKEN_RIFLE_VEL },//WP_TUSKEN_RIFLE, - { 0,0 },//WP_TUSKEN_STAFF, - { 0,0 },//WP_SCEPTER, - { 0,0 },//WP_NOGHRI_STICK, +float weaponSpeed[WP_NUM_WEAPONS][2] = { + {0, 0}, // WP_NONE, + {0, 0}, // WP_SABER, // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. + {BRYAR_PISTOL_VEL, BRYAR_PISTOL_VEL}, // WP_BLASTER_PISTOL, + {BLASTER_VELOCITY, BLASTER_VELOCITY}, // WP_BLASTER, + {Q3_INFINITE, Q3_INFINITE}, // WP_DISRUPTOR, + {BOWCASTER_VELOCITY, BOWCASTER_VELOCITY}, // WP_BOWCASTER, + {REPEATER_VELOCITY, REPEATER_ALT_VELOCITY}, // WP_REPEATER, + {DEMP2_VELOCITY, DEMP2_ALT_RANGE}, // WP_DEMP2, + {FLECHETTE_VEL, FLECHETTE_MINE_VEL}, // WP_FLECHETTE, + {ROCKET_VELOCITY, ROCKET_ALT_VELOCITY}, // WP_ROCKET_LAUNCHER, + {TD_VELOCITY, TD_ALT_VELOCITY}, // WP_THERMAL, + {0, 0}, // WP_TRIP_MINE, + {0, 0}, // WP_DET_PACK, + {CONC_VELOCITY, Q3_INFINITE}, // WP_CONCUSSION, + {0, 0}, // WP_MELEE, // Any ol' melee attack + {0, 0}, // WP_STUN_BATON, + {BRYAR_PISTOL_VEL, BRYAR_PISTOL_VEL}, // WP_BRYAR_PISTOL, + {EMPLACED_VEL, EMPLACED_VEL}, // WP_EMPLACED_GUN, + {BRYAR_PISTOL_VEL, BRYAR_PISTOL_VEL}, // WP_BOT_LASER, // Probe droid - Laser blast + {0, 0}, // WP_TURRET, // turret guns + {ATST_MAIN_VEL, ATST_MAIN_VEL}, // WP_ATST_MAIN, + {ATST_SIDE_MAIN_VELOCITY, ATST_SIDE_ALT_NPC_VELOCITY}, // WP_ATST_SIDE, + {EMPLACED_VEL, EMPLACED_VEL}, // WP_TIE_FIGHTER, + {EMPLACED_VEL, REPEATER_ALT_VELOCITY}, // WP_RAPID_FIRE_CONC, + {0, 0}, // WP_JAWA, + {TUSKEN_RIFLE_VEL, TUSKEN_RIFLE_VEL}, // WP_TUSKEN_RIFLE, + {0, 0}, // WP_TUSKEN_STAFF, + {0, 0}, // WP_SCEPTER, + {0, 0}, // WP_NOGHRI_STICK, }; -float WP_SpeedOfMissileForWeapon( int wp, qboolean alt_fire ) -{ - if ( alt_fire ) - { +float WP_SpeedOfMissileForWeapon(int wp, qboolean alt_fire) { + if (alt_fire) { return weaponSpeed[wp][1]; } return weaponSpeed[wp][0]; } //----------------------------------------------------------------------------- -void WP_TraceSetStart( const gentity_t *ent, vec3_t start, const vec3_t mins, const vec3_t maxs ) +void WP_TraceSetStart(const gentity_t *ent, vec3_t start, const vec3_t mins, const vec3_t maxs) //----------------------------------------------------------------------------- { - //make sure our start point isn't on the other side of a wall - trace_t tr; - vec3_t entMins, newstart; - vec3_t entMaxs; + // make sure our start point isn't on the other side of a wall + trace_t tr; + vec3_t entMins, newstart; + vec3_t entMaxs; - VectorSet( entMaxs, 5, 5, 5 ); - VectorScale( entMaxs, -1, entMins ); + VectorSet(entMaxs, 5, 5, 5); + VectorScale(entMaxs, -1, entMins); - if ( !ent->client ) - { + if (!ent->client) { return; } - VectorCopy( ent->currentOrigin, newstart ); + VectorCopy(ent->currentOrigin, newstart); newstart[2] = start[2]; // force newstart to be on the same plane as the muzzle ( start ) - gi.trace( &tr, newstart, entMins, entMaxs, start, ent->s.number, MASK_SOLID|CONTENTS_SHOTCLIP, (EG2_Collision)0, 0 ); + gi.trace(&tr, newstart, entMins, entMaxs, start, ent->s.number, MASK_SOLID | CONTENTS_SHOTCLIP, (EG2_Collision)0, 0); - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { // there is a problem here.. return; } - if ( tr.fraction < 1.0f ) - { - VectorCopy( tr.endpos, start ); + if (tr.fraction < 1.0f) { + VectorCopy(tr.endpos, start); } } -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); //----------------------------------------------------------------------------- -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire ) +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire) //----------------------------------------------------------------------------- { - gentity_t *missile; + gentity_t *missile; missile = G_Spawn(); @@ -135,95 +129,86 @@ gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t missile->s.eType = ET_MISSILE; missile->owner = owner; - Vehicle_t* pVeh = G_IsRidingVehicle(owner); + Vehicle_t *pVeh = G_IsRidingVehicle(owner); missile->alt_fire = altFire; missile->s.pos.trType = TR_LINEAR; - missile->s.pos.trTime = level.time;// - 10; // move a bit on the very first frame - VectorCopy( org, missile->s.pos.trBase ); - VectorScale( dir, vel, missile->s.pos.trDelta ); - if (pVeh) - { - missile->s.eFlags |= EF_USE_ANGLEDELTA; - vectoangles(missile->s.pos.trDelta, missile->s.angles); - VectorMA(missile->s.pos.trDelta, 2.0f, pVeh->m_pParentEntity->client->ps.velocity, missile->s.pos.trDelta); + missile->s.pos.trTime = level.time; // - 10; // move a bit on the very first frame + VectorCopy(org, missile->s.pos.trBase); + VectorScale(dir, vel, missile->s.pos.trDelta); + if (pVeh) { + missile->s.eFlags |= EF_USE_ANGLEDELTA; + vectoangles(missile->s.pos.trDelta, missile->s.angles); + VectorMA(missile->s.pos.trDelta, 2.0f, pVeh->m_pParentEntity->client->ps.velocity, missile->s.pos.trDelta); } - VectorCopy( org, missile->currentOrigin); - gi.linkentity( missile ); + VectorCopy(org, missile->currentOrigin); + gi.linkentity(missile); return missile; } - //----------------------------------------------------------------------------- -void WP_Stick( gentity_t *missile, trace_t *trace, float fudge_distance ) +void WP_Stick(gentity_t *missile, trace_t *trace, float fudge_distance) //----------------------------------------------------------------------------- { vec3_t org, ang; // not moving or rotating missile->s.pos.trType = TR_STATIONARY; - VectorClear( missile->s.pos.trDelta ); - VectorClear( missile->s.apos.trDelta ); + VectorClear(missile->s.pos.trDelta); + VectorClear(missile->s.apos.trDelta); // so we don't stick into the wall - VectorMA( trace->endpos, fudge_distance, trace->plane.normal, org ); - G_SetOrigin( missile, org ); + VectorMA(trace->endpos, fudge_distance, trace->plane.normal, org); + G_SetOrigin(missile, org); - vectoangles( trace->plane.normal, ang ); - G_SetAngles( missile, ang ); + vectoangles(trace->plane.normal, ang); + G_SetAngles(missile, ang); // I guess explode death wants me as the normal? -// VectorCopy( trace->plane.normal, missile->pos1 ); - gi.linkentity( missile ); + // VectorCopy( trace->plane.normal, missile->pos1 ); + gi.linkentity(missile); } // This version shares is in the thinkFunc format //----------------------------------------------------------------------------- -void WP_Explode( gentity_t *self ) +void WP_Explode(gentity_t *self) //----------------------------------------------------------------------------- { - gentity_t *attacker = self; - vec3_t forwardVec={0,0,1}; + gentity_t *attacker = self; + vec3_t forwardVec = {0, 0, 1}; // stop chain reaction runaway loops self->takedamage = qfalse; self->s.loopSound = 0; -// VectorCopy( self->currentOrigin, self->s.pos.trBase ); - if ( !self->client ) - { - AngleVectors( self->s.angles, forwardVec, NULL, NULL ); + // VectorCopy( self->currentOrigin, self->s.pos.trBase ); + if (!self->client) { + AngleVectors(self->s.angles, forwardVec, NULL, NULL); } - if ( self->fxID > 0 ) - { - G_PlayEffect( self->fxID, self->currentOrigin, forwardVec ); + if (self->fxID > 0) { + G_PlayEffect(self->fxID, self->currentOrigin, forwardVec); } - if ( self->owner ) - { + if (self->owner) { attacker = self->owner; - } - else if ( self->activator ) - { + } else if (self->activator) { attacker = self->activator; } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, 0/*don't ignore attacker*/, MOD_EXPLOSIVE_SPLASH ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, 0 /*don't ignore attacker*/, MOD_EXPLOSIVE_SPLASH); } - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_SetOrigin( self, self->currentOrigin ); + G_SetOrigin(self, self->currentOrigin); self->nextthink = level.time + 50; self->e_ThinkFunc = thinkF_G_FreeEntity; @@ -231,13 +216,12 @@ void WP_Explode( gentity_t *self ) // We need to have a dieFunc, otherwise G_Damage won't actually make us die. I could modify G_Damage, but that entails too many changes //----------------------------------------------------------------------------- -void WP_ExplosiveDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) +void WP_ExplosiveDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) //----------------------------------------------------------------------------- { self->enemy = attacker; - if ( attacker && !attacker->s.number ) - { + if (attacker && !attacker->s.number) { // less damage when shot by player self->splashDamage /= 3; self->splashRadius /= 3; @@ -245,29 +229,24 @@ void WP_ExplosiveDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker self->s.eFlags &= ~EF_FIRING; // don't draw beam if we are dead - WP_Explode( self ); + WP_Explode(self); } -bool WP_MissileTargetHint(gentity_t* shooter, vec3_t start, vec3_t out) -{ - return false; -} +bool WP_MissileTargetHint(gentity_t *shooter, vec3_t start, vec3_t out) { return false; } -int G_GetHitLocFromTrace( trace_t *trace, int mod ) -{ +int G_GetHitLocFromTrace(trace_t *trace, int mod) { int hitLoc = HL_NONE; - for (int i=0; i < MAX_G2_COLLISIONS; i++) - { - if ( trace->G2CollisionMap[i].mEntityNum == -1 ) - { + for (int i = 0; i < MAX_G2_COLLISIONS; i++) { + if (trace->G2CollisionMap[i].mEntityNum == -1) { break; } CCollisionRecord &coll = trace->G2CollisionMap[i]; - if ( (coll.mFlags & G2_FRONTFACE) ) - { - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &hitLoc, coll.mCollisionPosition, NULL, NULL, mod ); - //we only want the first "entrance wound", so break + if ((coll.mFlags & G2_FRONTFACE)) { + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &hitLoc, + coll.mCollisionPosition, NULL, NULL, mod); + // we only want the first "entrance wound", so break break; } } @@ -278,12 +257,10 @@ int G_GetHitLocFromTrace( trace_t *trace, int mod ) void AddLeanOfs(const gentity_t *const ent, vec3_t point) //--------------------------------------------------------- { - if(ent->client) - { - if(ent->client->ps.leanofs) - { - vec3_t right; - //add leaning offset + if (ent->client) { + if (ent->client->ps.leanofs) { + vec3_t right; + // add leaning offset AngleVectors(ent->client->ps.viewangles, NULL, right, NULL); VectorMA(point, (float)ent->client->ps.leanofs, right, point); } @@ -294,14 +271,12 @@ void AddLeanOfs(const gentity_t *const ent, vec3_t point) void SubtractLeanOfs(const gentity_t *const ent, vec3_t point) //--------------------------------------------------------- { - if(ent->client) - { - if(ent->client->ps.leanofs) - { - vec3_t right; - //add leaning offset - AngleVectors( ent->client->ps.viewangles, NULL, right, NULL ); - VectorMA( point, ent->client->ps.leanofs*-1, right, point ); + if (ent->client) { + if (ent->client->ps.leanofs) { + vec3_t right; + // add leaning offset + AngleVectors(ent->client->ps.viewangles, NULL, right, NULL); + VectorMA(point, ent->client->ps.leanofs * -1, right, point); } } } @@ -310,38 +285,32 @@ void SubtractLeanOfs(const gentity_t *const ent, vec3_t point) void ViewHeightFix(const gentity_t *const ent) //--------------------------------------------------------- { - //FIXME: this is hacky and doesn't need to be here. Was only put here to make up - //for the times a crouch anim would be used but not actually crouching. - //When we start calcing eyepos (SPOT_HEAD) from the tag_eyes, we won't need - //this (or viewheight at all?) - if ( !ent ) + // FIXME: this is hacky and doesn't need to be here. Was only put here to make up + // for the times a crouch anim would be used but not actually crouching. + // When we start calcing eyepos (SPOT_HEAD) from the tag_eyes, we won't need + // this (or viewheight at all?) + if (!ent) return; - if ( !ent->client || !ent->NPC ) + if (!ent->client || !ent->NPC) return; - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) - return;//dead + if (ent->client->ps.stats[STAT_HEALTH] <= 0) + return; // dead - if ( ent->client->ps.legsAnim == BOTH_CROUCH1IDLE || ent->client->ps.legsAnim == BOTH_CROUCH1 || ent->client->ps.legsAnim == BOTH_CROUCH1WALK ) - { - if ( ent->client->ps.viewheight!=ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET ) + if (ent->client->ps.legsAnim == BOTH_CROUCH1IDLE || ent->client->ps.legsAnim == BOTH_CROUCH1 || ent->client->ps.legsAnim == BOTH_CROUCH1WALK) { + if (ent->client->ps.viewheight != ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET) ent->client->ps.viewheight = ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET; - } - else - { - if ( ent->client->ps.viewheight!=ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET ) + } else { + if (ent->client->ps.viewheight != ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET) ent->client->ps.viewheight = ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET; } } -qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) -{ - if ( mod != MOD_UNKNOWN ) - { - switch( mod ) - { - //standard weapons +qboolean W_AccuracyLoggableWeapon(int weapon, qboolean alt_fire, int mod) { + if (mod != MOD_UNKNOWN) { + switch (mod) { + // standard weapons case MOD_BRYAR: case MOD_BRYAR_ALT: case MOD_BLASTER: @@ -356,30 +325,26 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) case MOD_CONC_ALT: return qtrue; break; - //non-alt standard + // non-alt standard case MOD_REPEATER: case MOD_DEMP2: case MOD_FLECHETTE: return qtrue; break; - //emplaced gun + // emplaced gun case MOD_EMPLACED: return qtrue; break; - //atst + // atst case MOD_ENERGY: case MOD_EXPLOSIVE: - if ( weapon == WP_ATST_MAIN || weapon == WP_ATST_SIDE ) - { + if (weapon == WP_ATST_MAIN || weapon == WP_ATST_SIDE) { return qtrue; } break; } - } - else if ( weapon != WP_NONE ) - { - switch( weapon ) - { + } else if (weapon != WP_NONE) { + switch (weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: case WP_BLASTER: @@ -389,20 +354,19 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) case WP_CONCUSSION: return qtrue; break; - //non-alt standard + // non-alt standard case WP_REPEATER: case WP_DEMP2: case WP_FLECHETTE: - if ( !alt_fire ) - { + if (!alt_fire) { return qtrue; } break; - //emplaced gun + // emplaced gun case WP_EMPLACED_GUN: return qtrue; break; - //atst + // atst case WP_ATST_MAIN: case WP_ATST_SIDE: return qtrue; @@ -417,28 +381,28 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) LogAccuracyHit =============== */ -qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) { - if( !target->takedamage ) { +qboolean LogAccuracyHit(gentity_t *target, gentity_t *attacker) { + if (!target->takedamage) { return qfalse; } - if ( target == attacker ) { + if (target == attacker) { return qfalse; } - if( !target->client ) { + if (!target->client) { return qfalse; } - if( !attacker->client ) { + if (!attacker->client) { return qfalse; } - if( target->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (target->client->ps.stats[STAT_HEALTH] <= 0) { return qfalse; } - if ( OnSameTeam( target, attacker ) ) { + if (OnSameTeam(target, attacker)) { return qfalse; } @@ -446,98 +410,85 @@ qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) { } //--------------------------------------------------------- -void CalcMuzzlePoint( gentity_t *const ent, vec3_t forwardVec, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in ) +void CalcMuzzlePoint(gentity_t *const ent, vec3_t forwardVec, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in) //--------------------------------------------------------- { - vec3_t org; - mdxaBone_t boltMatrix; + vec3_t org; + mdxaBone_t boltMatrix; - if( !lead_in ) //&& ent->s.number != 0 - {//Not players or melee - if( ent->client ) - { - if ( ent->client->renderInfo.mPCalcTime >= level.time - FRAMETIME*2 ) - {//Our muzz point was calced no more than 2 frames ago + if (!lead_in) //&& ent->s.number != 0 + { // Not players or melee + if (ent->client) { + if (ent->client->renderInfo.mPCalcTime >= level.time - FRAMETIME * 2) { // Our muzz point was calced no more than 2 frames ago VectorCopy(ent->client->renderInfo.muzzlePoint, muzzlePoint); return; } } } - VectorCopy( ent->currentOrigin, muzzlePoint ); + VectorCopy(ent->currentOrigin, muzzlePoint); - switch( ent->s.weapon ) - { + switch (ent->s.weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 16; - VectorMA( muzzlePoint, 28, forwardVec, muzzlePoint ); - VectorMA( muzzlePoint, 6, vrightVec, muzzlePoint ); + VectorMA(muzzlePoint, 28, forwardVec, muzzlePoint); + VectorMA(muzzlePoint, 6, vrightVec, muzzlePoint); break; case WP_ROCKET_LAUNCHER: case WP_CONCUSSION: case WP_THERMAL: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 2; break; case WP_BLASTER: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 1; - if ( ent->s.number == 0 ) - VectorMA( muzzlePoint, 12, forwardVec, muzzlePoint ); // player, don't set this any lower otherwise the projectile will impact immediately when your back is to a wall + if (ent->s.number == 0) + VectorMA(muzzlePoint, 12, forwardVec, + muzzlePoint); // player, don't set this any lower otherwise the projectile will impact immediately when your back is to a wall else - VectorMA( muzzlePoint, 2, forwardVec, muzzlePoint ); // NPC, don't set too far forwardVec otherwise the projectile can go through doors + VectorMA(muzzlePoint, 2, forwardVec, muzzlePoint); // NPC, don't set too far forwardVec otherwise the projectile can go through doors - VectorMA( muzzlePoint, 1, vrightVec, muzzlePoint ); + VectorMA(muzzlePoint, 1, vrightVec, muzzlePoint); break; case WP_SABER: - if(ent->NPC!=NULL && - (ent->client->ps.torsoAnim == TORSO_WEAPONREADY2 || - ent->client->ps.torsoAnim == BOTH_ATTACK2))//Sniper pose + if (ent->NPC != NULL && (ent->client->ps.torsoAnim == TORSO_WEAPONREADY2 || ent->client->ps.torsoAnim == BOTH_ATTACK2)) // Sniper pose { ViewHeightFix(ent); - muzzle[2] += ent->client->ps.viewheight;//By eyes - } - else - { + muzzle[2] += ent->client->ps.viewheight; // By eyes + } else { muzzlePoint[2] += 16; } - VectorMA( muzzlePoint, 8, forwardVec, muzzlePoint ); - VectorMA( muzzlePoint, 16, vrightVec, muzzlePoint ); + VectorMA(muzzlePoint, 8, forwardVec, muzzlePoint); + VectorMA(muzzlePoint, 16, vrightVec, muzzlePoint); break; case WP_BOT_LASER: - muzzlePoint[2] -= 16; // + muzzlePoint[2] -= 16; // break; case WP_ATST_MAIN: - if (ent->count > 0) - { + if (ent->count > 0) { ent->count = 0; - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->handLBolt, - &boltMatrix, ent->s.angles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); - } - else - { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handLBolt, &boltMatrix, ent->s.angles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); + } else { ent->count = 1; - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->handRBolt, - &boltMatrix, ent->s.angles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handRBolt, &boltMatrix, ent->s.angles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); } - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); - VectorCopy(org,muzzlePoint); + VectorCopy(org, muzzlePoint); break; } @@ -546,126 +497,104 @@ void CalcMuzzlePoint( gentity_t *const ent, vec3_t forwardVec, vec3_t right, vec } // Muzzle point table... -vec3_t WP_MuzzlePoint[WP_NUM_WEAPONS] = -{// Fwd, right, up. - {0, 0, 0 }, // WP_NONE, - {8 , 16, 0 }, // WP_SABER, - {12, 6, -6 }, // WP_BLASTER_PISTOL, - {12, 6, -6 }, // WP_BLASTER, - {12, 6, -6 }, // WP_DISRUPTOR, - {12, 2, -6 }, // WP_BOWCASTER, - {12, 4.5, -6 }, // WP_REPEATER, - {12, 6, -6 }, // WP_DEMP2, - {12, 6, -6 }, // WP_FLECHETTE, - {12, 8, -4 }, // WP_ROCKET_LAUNCHER, - {12, 0, -4 }, // WP_THERMAL, - {12, 0, -10 }, // WP_TRIP_MINE, - {12, 0, -4 }, // WP_DET_PACK, - {12, 8, -4 }, // WP_CONCUSSION, - {0 , 8, 0 }, // WP_MELEE, - {0, 0, 0 }, // WP_ATST_MAIN, - {0, 0, 0 }, // WP_ATST_SIDE, - {0 , 8, 0 }, // WP_STUN_BATON, - {12, 6, -6 }, // WP_BRYAR_PISTOL, +vec3_t WP_MuzzlePoint[WP_NUM_WEAPONS] = { + // Fwd, right, up. + {0, 0, 0}, // WP_NONE, + {8, 16, 0}, // WP_SABER, + {12, 6, -6}, // WP_BLASTER_PISTOL, + {12, 6, -6}, // WP_BLASTER, + {12, 6, -6}, // WP_DISRUPTOR, + {12, 2, -6}, // WP_BOWCASTER, + {12, 4.5, -6}, // WP_REPEATER, + {12, 6, -6}, // WP_DEMP2, + {12, 6, -6}, // WP_FLECHETTE, + {12, 8, -4}, // WP_ROCKET_LAUNCHER, + {12, 0, -4}, // WP_THERMAL, + {12, 0, -10}, // WP_TRIP_MINE, + {12, 0, -4}, // WP_DET_PACK, + {12, 8, -4}, // WP_CONCUSSION, + {0, 8, 0}, // WP_MELEE, + {0, 0, 0}, // WP_ATST_MAIN, + {0, 0, 0}, // WP_ATST_SIDE, + {0, 8, 0}, // WP_STUN_BATON, + {12, 6, -6}, // WP_BRYAR_PISTOL, }; -void WP_RocketLock( gentity_t *ent, float lockDist ) -{ +void WP_RocketLock(gentity_t *ent, float lockDist) { // Not really a charge weapon, but we still want to delay fire until the button comes up so that we can // implement our alt-fire locking stuff - vec3_t ang; - trace_t tr; + vec3_t ang; + trace_t tr; vec3_t muzzleOffPoint, muzzlePoint, forwardVec, right, up; - AngleVectors( ent->client->ps.viewangles, forwardVec, right, up ); + AngleVectors(ent->client->ps.viewangles, forwardVec, right, up); AngleVectors(ent->client->ps.viewangles, ang, NULL, NULL); - VectorCopy( ent->client->ps.origin, muzzlePoint ); + VectorCopy(ent->client->ps.origin, muzzlePoint); VectorCopy(WP_MuzzlePoint[WP_ROCKET_LAUNCHER], muzzleOffPoint); VectorMA(muzzlePoint, muzzleOffPoint[0], forwardVec, muzzlePoint); VectorMA(muzzlePoint, muzzleOffPoint[1], right, muzzlePoint); muzzlePoint[2] += ent->client->ps.viewheight + muzzleOffPoint[2]; - ang[0] = muzzlePoint[0] + ang[0]*lockDist; - ang[1] = muzzlePoint[1] + ang[1]*lockDist; - ang[2] = muzzlePoint[2] + ang[2]*lockDist; + ang[0] = muzzlePoint[0] + ang[0] * lockDist; + ang[1] = muzzlePoint[1] + ang[1] * lockDist; + ang[2] = muzzlePoint[2] + ang[2] * lockDist; gi.trace(&tr, muzzlePoint, NULL, NULL, ang, ent->client->ps.clientNum, MASK_PLAYERSOLID, (EG2_Collision)0, 0); - if (tr.fraction != 1 && tr.entityNum < ENTITYNUM_NONE && tr.entityNum != ent->client->ps.clientNum) - { + if (tr.fraction != 1 && tr.entityNum < ENTITYNUM_NONE && tr.entityNum != ent->client->ps.clientNum) { gentity_t *bgEnt = &g_entities[tr.entityNum]; - if ( bgEnt && (bgEnt->s.powerups&PW_CLOAKED) ) - { + if (bgEnt && (bgEnt->s.powerups & PW_CLOAKED)) { ent->client->rocketLockIndex = ENTITYNUM_NONE; ent->client->rocketLockTime = 0; - } - else if (bgEnt && bgEnt->s.eType == ET_PLAYER ) - { - if (ent->client->rocketLockIndex == ENTITYNUM_NONE) - { + } else if (bgEnt && bgEnt->s.eType == ET_PLAYER) { + if (ent->client->rocketLockIndex == ENTITYNUM_NONE) { ent->client->rocketLockIndex = tr.entityNum; ent->client->rocketLockTime = level.time; - } - else if (ent->client->rocketLockIndex != tr.entityNum && ent->client->rocketTargetTime < level.time) - { + } else if (ent->client->rocketLockIndex != tr.entityNum && ent->client->rocketTargetTime < level.time) { ent->client->rocketLockIndex = tr.entityNum; ent->client->rocketLockTime = level.time; - } - else if (ent->client->rocketLockIndex == tr.entityNum) - { - if (ent->client->rocketLockTime == -1) - { + } else if (ent->client->rocketLockIndex == tr.entityNum) { + if (ent->client->rocketLockTime == -1) { ent->client->rocketLockTime = ent->client->rocketLastValidTime; } } - if (ent->client->rocketLockIndex == tr.entityNum) - { + if (ent->client->rocketLockIndex == tr.entityNum) { ent->client->rocketTargetTime = level.time + 500; } } - } - else if (ent->client->rocketTargetTime < level.time) - { + } else if (ent->client->rocketTargetTime < level.time) { ent->client->rocketLockIndex = ENTITYNUM_NONE; ent->client->rocketLockTime = 0; - } - else - { - if (ent->client->rocketLockTime != -1) - { + } else { + if (ent->client->rocketLockTime != -1) { ent->client->rocketLastValidTime = ent->client->rocketLockTime; } ent->client->rocketLockTime = -1; } } -#define VEH_HOMING_MISSILE_THINK_TIME 100 -void WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon ) -{ - if ( !vehWeapon ) - {//invalid vehicle weapon +#define VEH_HOMING_MISSILE_THINK_TIME 100 +void WP_FireVehicleWeapon(gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon) { + if (!vehWeapon) { // invalid vehicle weapon return; - } - else if ( vehWeapon->bIsProjectile ) - {//projectile entity - gentity_t *missile; - vec3_t mins, maxs; + } else if (vehWeapon->bIsProjectile) { // projectile entity + gentity_t *missile; + vec3_t mins, maxs; - VectorSet( maxs, vehWeapon->fWidth/2.0f,vehWeapon->fWidth/2.0f,vehWeapon->fHeight/2.0f ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, vehWeapon->fWidth / 2.0f, vehWeapon->fWidth / 2.0f, vehWeapon->fHeight / 2.0f); + VectorScale(maxs, -1, mins); - //make sure our start point isn't on the other side of a wall - WP_TraceSetStart( ent, start, mins, maxs ); + // make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, mins, maxs); - //QUERY: alt_fire true or not? Does it matter? - missile = CreateMissile( start, dir, vehWeapon->fSpeed, 10000, ent, qfalse ); - if ( vehWeapon->bHasGravity ) - {//TESTME: is this all we need to do? + // QUERY: alt_fire true or not? Does it matter? + missile = CreateMissile(start, dir, vehWeapon->fSpeed, 10000, ent, qfalse); + if (vehWeapon->bHasGravity) { // TESTME: is this all we need to do? missile->s.pos.trType = TR_GRAVITY; } @@ -676,23 +605,20 @@ void WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponIn missile->splashRadius = vehWeapon->fSplashRadius; // HUGE HORRIBLE HACK - if (ent->owner && ent->owner->s.number==0) - { - //Should only be for speeders - mainly for t2_trip - if (ent->m_pVehicle->m_pVehicleInfo && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) - { - missile->damage *= 20.0f; - missile->splashDamage *= 20.0f; - missile->splashRadius *= 20.0f; + if (ent->owner && ent->owner->s.number == 0) { + // Should only be for speeders - mainly for t2_trip + if (ent->m_pVehicle->m_pVehicleInfo && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) { + missile->damage *= 20.0f; + missile->splashDamage *= 20.0f; + missile->splashRadius *= 20.0f; } } - //FIXME: externalize some of these properties? + // FIXME: externalize some of these properties? missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->clipmask = MASK_SHOT; - //Maybe by checking flags...? - if ( vehWeapon->bSaberBlockable ) - { + // Maybe by checking flags...? + if (vehWeapon->bSaberBlockable) { missile->clipmask |= CONTENTS_LIGHTSABER; } /* @@ -709,112 +635,93 @@ void WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponIn missile->s.eFlags |= EF_RADAROBJECT; } */ - missile->s.weapon = WP_BLASTER;//does this really matter? + missile->s.weapon = WP_BLASTER; // does this really matter? // Make it easier to hit things - VectorCopy( mins, missile->mins ); - VectorCopy( maxs, missile->maxs ); - //some slightly different stuff for things with bboxes - if ( vehWeapon->fWidth || vehWeapon->fHeight ) - {//we assume it's a rocket-like thing + VectorCopy(mins, missile->mins); + VectorCopy(maxs, missile->maxs); + // some slightly different stuff for things with bboxes + if (vehWeapon->fWidth || vehWeapon->fHeight) { // we assume it's a rocket-like thing missile->methodOfDeath = MOD_ROCKET; - missile->splashMethodOfDeath = MOD_ROCKET;// ?SPLASH; + missile->splashMethodOfDeath = MOD_ROCKET; // ?SPLASH; // we don't want it to ever bounce missile->bounceCount = 0; missile->mass = 10; - } - else - {//a blaster-laser-like thing - missile->s.weapon = WP_BLASTER;//does this really matter? - missile->methodOfDeath = MOD_EMPLACED;//MOD_TURBLAST; //count as a heavy weap - missile->splashMethodOfDeath = MOD_EMPLACED;//MOD_TURBLAST;// ?SPLASH; + } else { // a blaster-laser-like thing + missile->s.weapon = WP_BLASTER; // does this really matter? + missile->methodOfDeath = MOD_EMPLACED; // MOD_TURBLAST; //count as a heavy weap + missile->splashMethodOfDeath = MOD_EMPLACED; // MOD_TURBLAST;// ?SPLASH; // we don't want it to bounce forever missile->bounceCount = 8; } - if ( vehWeapon->iHealth ) - {//the missile can take damage + if (vehWeapon->iHealth) { // the missile can take damage missile->health = vehWeapon->iHealth; missile->takedamage = qtrue; missile->contents = MASK_SHOT; - missile->e_DieFunc = dieF_WP_ExplosiveDie;//dieF_RocketDie; + missile->e_DieFunc = dieF_WP_ExplosiveDie; // dieF_RocketDie; } - //set veh as cgame side owner for purpose of fx overrides - if (ent->m_pVehicle && ent->m_pVehicle->m_pPilot) - { + // set veh as cgame side owner for purpose of fx overrides + if (ent->m_pVehicle && ent->m_pVehicle->m_pPilot) { missile->owner = ent->m_pVehicle->m_pPilot; - } - else - { + } else { missile->owner = ent; } missile->s.otherEntityNum = ent->s.number; - missile->s.otherEntityNum2 = (vehWeapon-&g_vehWeaponInfo[0]); + missile->s.otherEntityNum2 = (vehWeapon - &g_vehWeaponInfo[0]); - if ( vehWeapon->iLifeTime ) - {//expire after a time - if ( vehWeapon->bExplodeOnExpire ) - {//blow up when your lifetime is up - missile->e_ThinkFunc = thinkF_WP_Explode;//FIXME: custom func? - } - else - {//just remove yourself - missile->e_ThinkFunc = thinkF_G_FreeEntity;//FIXME: custom func? + if (vehWeapon->iLifeTime) { // expire after a time + if (vehWeapon->bExplodeOnExpire) { // blow up when your lifetime is up + missile->e_ThinkFunc = thinkF_WP_Explode; // FIXME: custom func? + } else { // just remove yourself + missile->e_ThinkFunc = thinkF_G_FreeEntity; // FIXME: custom func? } missile->nextthink = level.time + vehWeapon->iLifeTime; } - if ( vehWeapon->fHoming ) - {//homing missile - //crap, we need to set up the homing stuff like it is in MP... - WP_RocketLock( ent, 16384 ); - if ( ent->client && ent->client->rocketLockIndex != ENTITYNUM_NONE ) - { + if (vehWeapon->fHoming) { // homing missile + // crap, we need to set up the homing stuff like it is in MP... + WP_RocketLock(ent, 16384); + if (ent->client && ent->client->rocketLockIndex != ENTITYNUM_NONE) { int dif = 0; float rTime; rTime = ent->client->rocketLockTime; - if (rTime == -1) - { + if (rTime == -1) { rTime = ent->client->rocketLastValidTime; } - if ( !vehWeapon->iLockOnTime ) - {//no minimum lock-on time - dif = 10;//guaranteed lock-on - } - else - { - float lockTimeInterval = vehWeapon->iLockOnTime/16.0f; - dif = ( level.time - rTime ) / lockTimeInterval; + if (!vehWeapon->iLockOnTime) { // no minimum lock-on time + dif = 10; // guaranteed lock-on + } else { + float lockTimeInterval = vehWeapon->iLockOnTime / 16.0f; + dif = (level.time - rTime) / lockTimeInterval; } - if (dif < 0) - { + if (dif < 0) { dif = 0; } - //It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in time between server and client - if ( dif >= 10 && rTime != -1 ) - { + // It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in + // time between server and client + if (dif >= 10 && rTime != -1) { missile->enemy = &g_entities[ent->client->rocketLockIndex]; - if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && !OnSameTeam(ent, missile->enemy)) - { //if enemy became invalid, died, or is on the same team, then don't seek it - missile->spawnflags |= 1;//just to let it know it should be faster... FIXME: EXTERNALIZE + if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && + !OnSameTeam(ent, missile->enemy)) { // if enemy became invalid, died, or is on the same team, then don't seek it + missile->spawnflags |= 1; // just to let it know it should be faster... FIXME: EXTERNALIZE missile->speed = vehWeapon->fSpeed; missile->angle = vehWeapon->fHoming; - if ( vehWeapon->iLifeTime ) - {//expire after a time + if (vehWeapon->iLifeTime) { // expire after a time missile->disconnectDebounceTime = level.time + vehWeapon->iLifeTime; missile->lockCount = (int)(vehWeapon->bExplodeOnExpire); } missile->e_ThinkFunc = thinkF_rocketThink; missile->nextthink = level.time + VEH_HOMING_MISSILE_THINK_TIME; - //FIXME: implement radar in SP? - //missile->s.eFlags |= EF_RADAROBJECT; + // FIXME: implement radar in SP? + // missile->s.eFlags |= EF_RADAROBJECT; } } @@ -822,47 +729,39 @@ void WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponIn ent->client->rocketLockTime = 0; ent->client->rocketTargetTime = 0; - VectorCopy( dir, missile->movedir ); - missile->random = 1.0f;//FIXME: externalize? + VectorCopy(dir, missile->movedir); + missile->random = 1.0f; // FIXME: externalize? } } - } - else - {//traceline - //FIXME: implement + } else { // traceline + // FIXME: implement } } -void WP_VehLeadCrosshairVeh( gentity_t *camTraceEnt, vec3_t newEnd, const vec3_t dir, const vec3_t shotStart, vec3_t shotDir ) -{ - //FIXME: implement from MP? +void WP_VehLeadCrosshairVeh(gentity_t *camTraceEnt, vec3_t newEnd, const vec3_t dir, const vec3_t shotStart, vec3_t shotDir) { + // FIXME: implement from MP? } -qboolean WP_VehCheckTraceFromCamPos( gentity_t *ent, const vec3_t shotStart, vec3_t shotDir ) -{ - //FIXME: implement from MP? +qboolean WP_VehCheckTraceFromCamPos(gentity_t *ent, const vec3_t shotStart, vec3_t shotDir) { + // FIXME: implement from MP? return qfalse; } //--------------------------------------------------------- -void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) +void FireVehicleWeapon(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { Vehicle_t *pVeh = ent->m_pVehicle; - if ( !pVeh ) - { + if (!pVeh) { return; } - if (pVeh->m_iRemovedSurfaces) - { //can't fire when the thing is breaking apart + if (pVeh->m_iRemovedSurfaces) { // can't fire when the thing is breaking apart return; } - - if (ent->owner && ent->owner->client && ent->owner->client->ps.weapon!=WP_NONE) - { + if (ent->owner && ent->owner->client && ent->owner->client->ps.weapon != WP_NONE) { return; } @@ -871,41 +770,32 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) // would actually have to press the 2 key or something like that (I doubt I'd get a graphic for it anyways though). -AReis // If this is not the alternate fire, fire a normal blaster shot... - if ( pVeh->m_pVehicleInfo && - (pVeh->m_pVehicleInfo->type != VH_FIGHTER || (pVeh->m_ulFlags&VEH_WINGSOPEN)) ) // NOTE: Wings open also denotes that it has already launched. - {//fighters can only fire when wings are open - int weaponNum = 0, vehWeaponIndex = VEH_WEAPON_NONE; - int delay = 1000; + if (pVeh->m_pVehicleInfo && + (pVeh->m_pVehicleInfo->type != VH_FIGHTER || (pVeh->m_ulFlags & VEH_WINGSOPEN))) // NOTE: Wings open also denotes that it has already launched. + { // fighters can only fire when wings are open + int weaponNum = 0, vehWeaponIndex = VEH_WEAPON_NONE; + int delay = 1000; qboolean aimCorrect = qfalse; qboolean linkedFiring = qfalse; - if ( !alt_fire ) - { + if (!alt_fire) { weaponNum = 0; - } - else - { + } else { weaponNum = 1; } vehWeaponIndex = pVeh->m_pVehicleInfo->weapon[weaponNum].ID; - if ( pVeh->weaponStatus[weaponNum].ammo <= 0 ) - {//no ammo for this weapon - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo + if (pVeh->weaponStatus[weaponNum].ammo <= 0) { // no ammo for this weapon + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo int i; - //but only if one of the vehicle muzzles is actually ready to fire this weapon - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + // but only if one of the vehicle muzzles is actually ready to fire this weapon + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( pVeh->m_iMuzzleTag[i] != -1 - && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time ) - {//this one would have fired, send the no ammo message - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time) { // this one would have fired, send the no ammo message + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); break; } } @@ -915,208 +805,166 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) delay = pVeh->m_pVehicleInfo->weapon[weaponNum].delay; aimCorrect = pVeh->m_pVehicleInfo->weapon[weaponNum].aimCorrect; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2//always linked - || ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 1//optionally linkable - && pVeh->weaponStatus[weaponNum].linked ) )//linked - {//we're linking the primary or alternate weapons, so we'll do *all* the muzzles + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2 // always linked + || (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 1 // optionally linkable + && pVeh->weaponStatus[weaponNum].linked)) // linked + { // we're linking the primary or alternate weapons, so we'll do *all* the muzzles linkedFiring = qtrue; } - if ( vehWeaponIndex <= VEH_WEAPON_BASE || vehWeaponIndex >= MAX_VEH_WEAPONS ) - {//invalid vehicle weapon + if (vehWeaponIndex <= VEH_WEAPON_BASE || vehWeaponIndex >= MAX_VEH_WEAPONS) { // invalid vehicle weapon return; - } - else - { + } else { int i, numMuzzles = 0, numMuzzlesReady = 0, cumulativeDelay = 0, cumulativeAmmo = 0; qboolean sentAmmoWarning = qfalse; vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[vehWeaponIndex]; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2 ) - {//always linked weapons don't accumulate delay, just use specified delay + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2) { // always linked weapons don't accumulate delay, just use specified delay cumulativeDelay = delay; } - //find out how many we've got for this weapon - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + // find out how many we've got for this weapon + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time ) - { + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time) { numMuzzlesReady++; } - if ( pVeh->m_pVehicleInfo->weapMuzzle[pVeh->weaponStatus[weaponNum].nextMuzzle] != vehWeaponIndex ) - {//Our designated next muzzle for this weapon isn't valid for this weapon (happens when ships fire for the first time) - //set the next to this one + if (pVeh->m_pVehicleInfo->weapMuzzle[pVeh->weaponStatus[weaponNum].nextMuzzle] != + vehWeaponIndex) { // Our designated next muzzle for this weapon isn't valid for this weapon (happens when ships fire for the first time) + // set the next to this one pVeh->weaponStatus[weaponNum].nextMuzzle = i; } - if ( linkedFiring ) - { + if (linkedFiring) { cumulativeAmmo += vehWeapon->iAmmoPerShot; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable != 2 ) - {//always linked weapons don't accumulate delay, just use specified delay + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable != 2) { // always linked weapons don't accumulate delay, just use specified delay cumulativeDelay += delay; } } numMuzzles++; } - if ( linkedFiring ) - {//firing all muzzles at once - if ( numMuzzlesReady != numMuzzles ) - {//can't fire all linked muzzles yet + if (linkedFiring) { // firing all muzzles at once + if (numMuzzlesReady != numMuzzles) { // can't fire all linked muzzles yet return; - } - else - {//can fire all linked muzzles, check ammo - if ( pVeh->weaponStatus[weaponNum].ammo < cumulativeAmmo ) - {//can't fire, not enough ammo - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + } else { // can fire all linked muzzles, check ammo + if (pVeh->weaponStatus[weaponNum].ammo < cumulativeAmmo) { // can't fire, not enough ammo + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); } return; } } } - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( !linkedFiring - && i != pVeh->weaponStatus[weaponNum].nextMuzzle ) - {//we're only firing one muzzle and this isn't it + if (!linkedFiring && i != pVeh->weaponStatus[weaponNum].nextMuzzle) { // we're only firing one muzzle and this isn't it continue; } // Fire this muzzle. - if ( pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time ) - { - vec3_t start, dir; + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_Muzzles[i].m_iMuzzleWait < level.time) { + vec3_t start, dir; - if ( pVeh->weaponStatus[weaponNum].ammo < vehWeapon->iAmmoPerShot ) - {//out of ammo! - if ( !sentAmmoWarning ) - { + if (pVeh->weaponStatus[weaponNum].ammo < vehWeapon->iAmmoPerShot) { // out of ammo! + if (!sentAmmoWarning) { sentAmmoWarning = qtrue; - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); } } - } - else - {//have enough ammo to shoot - //do the firing - //WP_CalcVehMuzzle(ent, i); - VectorCopy( pVeh->m_Muzzles[i].m_vMuzzlePos, start ); - VectorCopy( pVeh->m_Muzzles[i].m_vMuzzleDir, dir ); - if ( WP_VehCheckTraceFromCamPos( ent, start, dir ) ) - {//auto-aim at whatever crosshair would be over from camera's point of view (if closer) - } - else if ( aimCorrect ) - {//auto-aim the missile at the crosshair if there's anything there + } else { // have enough ammo to shoot + // do the firing + // WP_CalcVehMuzzle(ent, i); + VectorCopy(pVeh->m_Muzzles[i].m_vMuzzlePos, start); + VectorCopy(pVeh->m_Muzzles[i].m_vMuzzleDir, dir); + if (WP_VehCheckTraceFromCamPos(ent, start, + dir)) { // auto-aim at whatever crosshair would be over from camera's point of view (if closer) + } else if (aimCorrect) { // auto-aim the missile at the crosshair if there's anything there trace_t trace; - vec3_t end; - vec3_t ang; - vec3_t fixedDir; + vec3_t end; + vec3_t ang; + vec3_t fixedDir; - if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) - { + if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { VectorSet(ang, 0.0f, pVeh->m_vOrientation[1], 0.0f); - } - else - { + } else { VectorCopy(pVeh->m_vOrientation, ang); } - AngleVectors( ang, fixedDir, NULL, NULL ); - //VectorMA( ent->currentOrigin, 32768, dir, end ); - VectorMA( ent->currentOrigin, 8192, dir, end ); - gi.trace( &trace, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( trace.fraction < 1.0f && !trace.allsolid && !trace.startsolid ) - { + AngleVectors(ang, fixedDir, NULL, NULL); + // VectorMA( ent->currentOrigin, 32768, dir, end ); + VectorMA(ent->currentOrigin, 8192, dir, end); + gi.trace(&trace, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (trace.fraction < 1.0f && !trace.allsolid && !trace.startsolid) { vec3_t newEnd; - VectorCopy( trace.endpos, newEnd ); - WP_VehLeadCrosshairVeh( &g_entities[trace.entityNum], newEnd, fixedDir, start, dir ); + VectorCopy(trace.endpos, newEnd); + WP_VehLeadCrosshairVeh(&g_entities[trace.entityNum], newEnd, fixedDir, start, dir); } } - //play the weapon's muzzle effect if we have one - if ( vehWeapon->iMuzzleFX ) - { - G_PlayEffect( vehWeapon->iMuzzleFX, pVeh->m_Muzzles[i].m_vMuzzlePos, pVeh->m_Muzzles[i].m_vMuzzleDir ); + // play the weapon's muzzle effect if we have one + if (vehWeapon->iMuzzleFX) { + G_PlayEffect(vehWeapon->iMuzzleFX, pVeh->m_Muzzles[i].m_vMuzzlePos, pVeh->m_Muzzles[i].m_vMuzzleDir); } - WP_FireVehicleWeapon( ent, start, dir, vehWeapon ); + WP_FireVehicleWeapon(ent, start, dir, vehWeapon); } - if ( linkedFiring ) - {//we're linking the weapon, so continue on and fire all appropriate muzzles + if (linkedFiring) { // we're linking the weapon, so continue on and fire all appropriate muzzles continue; } - //else just firing one - //take the ammo, set the next muzzle and set the delay on it - if ( numMuzzles > 1 ) - {//more than one, look for it + // else just firing one + // take the ammo, set the next muzzle and set the delay on it + if (numMuzzles > 1) { // more than one, look for it int nextMuzzle = pVeh->weaponStatus[weaponNum].nextMuzzle; - while ( 1 ) - { + while (1) { nextMuzzle++; - if ( nextMuzzle >= MAX_VEHICLE_MUZZLES ) - { + if (nextMuzzle >= MAX_VEHICLE_MUZZLES) { nextMuzzle = 0; } - if ( nextMuzzle == pVeh->weaponStatus[weaponNum].nextMuzzle ) - {//WTF? Wrapped without finding another valid one! + if (nextMuzzle == pVeh->weaponStatus[weaponNum].nextMuzzle) { // WTF? Wrapped without finding another valid one! break; } - if ( pVeh->m_pVehicleInfo->weapMuzzle[nextMuzzle] == vehWeaponIndex ) - {//this is the next muzzle for this weapon + if (pVeh->m_pVehicleInfo->weapMuzzle[nextMuzzle] == vehWeaponIndex) { // this is the next muzzle for this weapon pVeh->weaponStatus[weaponNum].nextMuzzle = nextMuzzle; break; } } - }//else, just stay on the one we just fired - //set the delay on the next muzzle + } // else, just stay on the one we just fired + // set the delay on the next muzzle pVeh->m_Muzzles[pVeh->weaponStatus[weaponNum].nextMuzzle].m_iMuzzleWait = level.time + delay; - //take away the ammo + // take away the ammo pVeh->weaponStatus[weaponNum].ammo -= vehWeapon->iAmmoPerShot; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( pVeh->m_pParentEntity && ((gentity_t*)(pVeh->m_pParentEntity))->client ) - { - ((gentity_t*)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's + // client->ps.ammo array + if (pVeh->m_pParentEntity && ((gentity_t *)(pVeh->m_pParentEntity))->client) { + ((gentity_t *)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; } - //done! - //we'll get in here again next frame and try the next muzzle... - //return; + // done! + // we'll get in here again next frame and try the next muzzle... + // return; return; } } - //we went through all the muzzles, so apply the cumulative delay and ammo cost - if ( cumulativeAmmo ) - {//taking ammo one shot at a time - //take the ammo + // we went through all the muzzles, so apply the cumulative delay and ammo cost + if (cumulativeAmmo) { // taking ammo one shot at a time + // take the ammo pVeh->weaponStatus[weaponNum].ammo -= cumulativeAmmo; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( pVeh->m_pParentEntity && ((gentity_t*)(pVeh->m_pParentEntity))->client ) - { - ((gentity_t*)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's + // client->ps.ammo array + if (pVeh->m_pParentEntity && ((gentity_t *)(pVeh->m_pParentEntity))->client) { + ((gentity_t *)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; } } - if ( cumulativeDelay ) - {//we linked muzzles so we need to apply the cumulative delay now, to each of the linked muzzles - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + if (cumulativeDelay) { // we linked muzzles so we need to apply the cumulative delay now, to each of the linked muzzles + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - //apply the cumulative delay + // apply the cumulative delay pVeh->m_Muzzles[i].m_iMuzzleWait = level.time + cumulativeDelay; } } @@ -1124,47 +972,41 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) } } -void WP_FireScepter( gentity_t *ent, qboolean alt_fire ) -{//just a straight beam - int damage = 1; - vec3_t start, end; - trace_t tr; - gentity_t *traceEnt = NULL, *tent; - float shotRange = 8192; - qboolean render_impact = qtrue; +void WP_FireScepter(gentity_t *ent, qboolean alt_fire) { // just a straight beam + int damage = 1; + vec3_t start, end; + trace_t tr; + gentity_t *traceEnt = NULL, *tent; + float shotRange = 8192; + qboolean render_impact = qtrue; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); WP_MissileTargetHint(ent, start, forwardVec); - VectorMA( start, shotRange, forwardVec, end ); + VectorMA(start, shotRange, forwardVec, end); - gi.trace( &tr, start, NULL, NULL, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); + gi.trace(&tr, start, NULL, NULL, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 10); traceEnt = &g_entities[tr.entityNum]; - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_MAIN_SHOT ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_MAIN_SHOT); tent->svFlags |= SVF_BROADCAST; - VectorCopy( muzzle, tent->s.origin2 ); + VectorCopy(muzzle, tent->s.origin2); - if ( render_impact ) - { - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { + if (render_impact) { + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "disruptor/flesh_impact" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("disruptor/flesh_impact"), tr.endpos, tr.plane.normal); - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_DISRUPTOR ); - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_EXTRA_KNOCKBACK, MOD_DISRUPTOR, hitLoc ); - } - else - { - G_PlayEffect( G_EffectIndex( "disruptor/wall_impact" ), tr.endpos, tr.plane.normal ); + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_DISRUPTOR); + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_EXTRA_KNOCKBACK, MOD_DISRUPTOR, hitLoc); + } else { + G_PlayEffect(G_EffectIndex("disruptor/wall_impact"), tr.endpos, tr.plane.normal); } } @@ -1182,9 +1024,9 @@ void WP_FireScepter( gentity_t *ent, qboolean alt_fire ) */ } -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); //--------------------------------------------------------- -void FireWeapon( gentity_t *ent, qboolean alt_fire ) +void FireWeapon(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { float alert = 256; @@ -1194,59 +1036,42 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) ent->client->ps.persistant[PERS_ACCURACY_SHOTS]++; // If this is a vehicle, fire it's weapon and we're done. - if ( ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { - FireVehicleWeapon( ent, alt_fire ); + if (ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE) { + FireVehicleWeapon(ent, alt_fire); return; } // set aiming directions - if ( ent->s.weapon == WP_DISRUPTOR && alt_fire ) - { - if ( ent->NPC ) - { - //snipers must use the angles they actually did their shot trace with - AngleVectors( ent->lastAngles, forwardVec, vrightVec, up ); + if (ent->s.weapon == WP_DISRUPTOR && alt_fire) { + if (ent->NPC) { + // snipers must use the angles they actually did their shot trace with + AngleVectors(ent->lastAngles, forwardVec, vrightVec, up); } - } - else if ( ent->s.weapon == WP_ATST_SIDE || ent->s.weapon == WP_ATST_MAIN ) - { - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; + } else if (ent->s.weapon == WP_ATST_SIDE || ent->s.weapon == WP_ATST_MAIN) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; - VectorCopy( ent->client->renderInfo.muzzlePoint, muzzle1 ); + VectorCopy(ent->client->renderInfo.muzzlePoint, muzzle1); - if ( !ent->s.number ) - {//player driving an AT-ST - //SIGH... because we can't anticipate alt-fire, must calc muzzle here and now - mdxaBone_t boltMatrix; - int bolt; + if (!ent->s.number) { // player driving an AT-ST + // SIGH... because we can't anticipate alt-fire, must calc muzzle here and now + mdxaBone_t boltMatrix; + int bolt; - if ( ent->client->ps.weapon == WP_ATST_MAIN ) - {//FIXME: alt_fire should fire both barrels, but slower? - if ( ent->alt_fire ) - { + if (ent->client->ps.weapon == WP_ATST_MAIN) { // FIXME: alt_fire should fire both barrels, but slower? + if (ent->alt_fire) { bolt = ent->handRBolt; - } - else - { + } else { bolt = ent->handLBolt; } - } - else - {// ATST SIDE weapons - if ( ent->alt_fire ) - { - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], "head_light_blaster_cann" ) ) - {//don't have it! + } else { // ATST SIDE weapons + if (ent->alt_fire) { + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], "head_light_blaster_cann")) { // don't have it! return; } bolt = ent->genericBolt2; - } - else - { - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], "head_concussion_charger" ) ) - {//don't have it! + } else { + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], "head_concussion_charger")) { // don't have it! return; } bolt = ent->genericBolt1; @@ -1254,135 +1079,111 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) } vec3_t yawOnlyAngles = {0, ent->currentAngles[YAW], 0}; - if ( ent->currentAngles[YAW] != ent->client->ps.legsYaw ) - { + if (ent->currentAngles[YAW] != ent->client->ps.legsYaw) { yawOnlyAngles[YAW] = ent->client->ps.legsYaw; } - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, bolt, &boltMatrix, yawOnlyAngles, ent->currentOrigin, (cg.time?cg.time:level.time), NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, bolt, &boltMatrix, yawOnlyAngles, ent->currentOrigin, (cg.time ? cg.time : level.time), NULL, + ent->s.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent->client->renderInfo.muzzleDir); ent->client->renderInfo.mPCalcTime = level.time; - AngleVectors( ent->client->ps.viewangles, forwardVec, vrightVec, up ); - //CalcMuzzlePoint( ent, forwardVec, vrightVec, up, muzzle, 0 ); - } - else if ( !ent->enemy ) - {//an NPC with no enemy to auto-aim at - VectorCopy( ent->client->renderInfo.muzzleDir, forwardVec ); - } - else - {//NPC, auto-aim at enemy - CalcEntitySpot( ent->enemy, SPOT_HEAD, enemy_org1 ); + AngleVectors(ent->client->ps.viewangles, forwardVec, vrightVec, up); + // CalcMuzzlePoint( ent, forwardVec, vrightVec, up, muzzle, 0 ); + } else if (!ent->enemy) { // an NPC with no enemy to auto-aim at + VectorCopy(ent->client->renderInfo.muzzleDir, forwardVec); + } else { // NPC, auto-aim at enemy + CalcEntitySpot(ent->enemy, SPOT_HEAD, enemy_org1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forwardVec, vrightVec, up); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forwardVec, vrightVec, up); } - } - else if ( ent->s.weapon == WP_BOT_LASER && ent->enemy ) - { - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; + } else if (ent->s.weapon == WP_BOT_LASER && ent->enemy) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; - CalcEntitySpot( ent->enemy, SPOT_HEAD, enemy_org1 ); - CalcEntitySpot( ent, SPOT_WEAPON, muzzle1 ); + CalcEntitySpot(ent->enemy, SPOT_HEAD, enemy_org1); + CalcEntitySpot(ent, SPOT_WEAPON, muzzle1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forwardVec, vrightVec, up); - } - else - { - if ( (pVeh = G_IsRidingVehicle( ent )) != NULL) //riding a vehicle - {//use our muzzleDir, can't use viewangles or vehicle m_vOrientation because we may be animated to shoot left or right... - if ((ent->s.eFlags&EF_NODRAW))//we're inside it + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forwardVec, vrightVec, up); + } else { + if ((pVeh = G_IsRidingVehicle(ent)) != NULL) // riding a vehicle + { // use our muzzleDir, can't use viewangles or vehicle m_vOrientation because we may be animated to shoot left or right... + if ((ent->s.eFlags & EF_NODRAW)) // we're inside it { - vec3_t aimAngles; - VectorCopy( ent->client->renderInfo.muzzleDir, forwardVec ); - vectoangles( forwardVec, aimAngles ); - //we're only keeping the yaw + vec3_t aimAngles; + VectorCopy(ent->client->renderInfo.muzzleDir, forwardVec); + vectoangles(forwardVec, aimAngles); + // we're only keeping the yaw aimAngles[PITCH] = ent->client->ps.viewangles[PITCH]; aimAngles[ROLL] = 0; - AngleVectors( aimAngles, forwardVec, vrightVec, up ); - } - else - { - vec3_t actorRight; - vec3_t actorFwd; + AngleVectors(aimAngles, forwardVec, vrightVec, up); + } else { + vec3_t actorRight; + vec3_t actorFwd; - VectorCopy( ent->client->renderInfo.muzzlePoint, muzzle ); + VectorCopy(ent->client->renderInfo.muzzlePoint, muzzle); AngleVectors(ent->currentAngles, actorFwd, actorRight, 0); // Aiming Left //------------- - if (ent->client->ps.torsoAnim==BOTH_VT_ATL_G || ent->client->ps.torsoAnim==BOTH_VS_ATL_G) - { - VectorScale(actorRight, -1.0f, forwardVec); + if (ent->client->ps.torsoAnim == BOTH_VT_ATL_G || ent->client->ps.torsoAnim == BOTH_VS_ATL_G) { + VectorScale(actorRight, -1.0f, forwardVec); } // Aiming Right //-------------- - else if (ent->client->ps.torsoAnim==BOTH_VT_ATR_G || ent->client->ps.torsoAnim==BOTH_VS_ATR_G) - { - VectorCopy(actorRight, forwardVec); + else if (ent->client->ps.torsoAnim == BOTH_VT_ATR_G || ent->client->ps.torsoAnim == BOTH_VS_ATR_G) { + VectorCopy(actorRight, forwardVec); } // Aiming Forward //---------------- - else - { - VectorCopy(actorFwd, forwardVec); + else { + VectorCopy(actorFwd, forwardVec); } // If We Have An Enemy, Fudge The Aim To Hit The Enemy - if (ent->enemy) - { - vec3_t toEnemy; + if (ent->enemy) { + vec3_t toEnemy; VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, toEnemy); VectorNormalize(toEnemy); - if (DotProduct(toEnemy, forwardVec)>0.75f && - ((ent->s.number==0 && !Q_irand(0,2)) || // the player has a 1 in 3 chance - (ent->s.number!=0 && !Q_irand(0,5)))) // other guys have a 1 in 6 chance + if (DotProduct(toEnemy, forwardVec) > 0.75f && ((ent->s.number == 0 && !Q_irand(0, 2)) || // the player has a 1 in 3 chance + (ent->s.number != 0 && !Q_irand(0, 5)))) // other guys have a 1 in 6 chance { VectorCopy(toEnemy, forwardVec); - } - else - { + } else { forwardVec[0] += Q_flrand(-0.1f, 0.1f); forwardVec[1] += Q_flrand(-0.1f, 0.1f); forwardVec[2] += Q_flrand(-0.1f, 0.1f); } } } - } - else - { - AngleVectors( ent->client->ps.viewangles, forwardVec, vrightVec, up ); + } else { + AngleVectors(ent->client->ps.viewangles, forwardVec, vrightVec, up); } } ent->alt_fire = alt_fire; - if (!pVeh) - { - if (ent->NPC && (ent->NPC->scriptFlags&SCF_FIRE_WEAPON_NO_ANIM)) - { - VectorCopy( ent->client->renderInfo.muzzlePoint, muzzle ); - VectorCopy( ent->client->renderInfo.muzzleDir, forwardVec ); + if (!pVeh) { + if (ent->NPC && (ent->NPC->scriptFlags & SCF_FIRE_WEAPON_NO_ANIM)) { + VectorCopy(ent->client->renderInfo.muzzlePoint, muzzle); + VectorCopy(ent->client->renderInfo.muzzleDir, forwardVec); MakeNormalVectors(forwardVec, vrightVec, up); - } - else - { - CalcMuzzlePoint ( ent, forwardVec, vrightVec, up, muzzle , 0); + } else { + CalcMuzzlePoint(ent, forwardVec, vrightVec, up, muzzle, 0); } } // fire the specific weapon - switch( ent->s.weapon ) - { + switch (ent->s.weapon) { // Player weapons //----------------- case WP_SABER: @@ -1391,148 +1192,135 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: - WP_FireBryarPistol( ent, alt_fire ); + WP_FireBryarPistol(ent, alt_fire); break; case WP_BLASTER: - WP_FireBlaster( ent, alt_fire ); + WP_FireBlaster(ent, alt_fire); break; case WP_TUSKEN_RIFLE: - if ( alt_fire ) - { - WP_FireTuskenRifle( ent ); - } - else - { - WP_Melee( ent ); + if (alt_fire) { + WP_FireTuskenRifle(ent); + } else { + WP_Melee(ent); } break; case WP_DISRUPTOR: alert = 50; // if you want it to alert enemies, remove this - WP_FireDisruptor( ent, alt_fire ); + WP_FireDisruptor(ent, alt_fire); break; case WP_BOWCASTER: - WP_FireBowcaster( ent, alt_fire ); + WP_FireBowcaster(ent, alt_fire); break; case WP_REPEATER: - WP_FireRepeater( ent, alt_fire ); + WP_FireRepeater(ent, alt_fire); break; case WP_DEMP2: - WP_FireDEMP2( ent, alt_fire ); + WP_FireDEMP2(ent, alt_fire); break; case WP_FLECHETTE: - WP_FireFlechette( ent, alt_fire ); + WP_FireFlechette(ent, alt_fire); break; case WP_ROCKET_LAUNCHER: - WP_FireRocket( ent, alt_fire ); + WP_FireRocket(ent, alt_fire); break; case WP_CONCUSSION: - WP_Concussion( ent, alt_fire ); + WP_Concussion(ent, alt_fire); break; case WP_THERMAL: - WP_FireThermalDetonator( ent, alt_fire ); + WP_FireThermalDetonator(ent, alt_fire); break; case WP_TRIP_MINE: alert = 0; // if you want it to alert enemies, remove this - WP_PlaceLaserTrap( ent, alt_fire ); + WP_PlaceLaserTrap(ent, alt_fire); break; case WP_DET_PACK: alert = 0; // if you want it to alert enemies, remove this - WP_FireDetPack( ent, alt_fire ); + WP_FireDetPack(ent, alt_fire); break; case WP_BOT_LASER: - WP_BotLaser( ent ); + WP_BotLaser(ent); break; case WP_EMPLACED_GUN: // doesn't care about whether it's alt-fire or not. We can do an alt-fire if needed - WP_EmplacedFire( ent ); + WP_EmplacedFire(ent); break; case WP_MELEE: alert = 0; // if you want it to alert enemies, remove this - if ( !alt_fire || !g_debugMelee->integer ) - { - WP_Melee( ent ); + if (!alt_fire || !g_debugMelee->integer) { + WP_Melee(ent); } break; case WP_ATST_MAIN: - WP_ATSTMainFire( ent ); + WP_ATSTMainFire(ent); break; case WP_ATST_SIDE: // TEMP - if ( alt_fire ) - { -// WP_FireRocket( ent, qfalse ); + if (alt_fire) { + // WP_FireRocket( ent, qfalse ); WP_ATSTSideAltFire(ent); - } - else - { + } else { // FIXME! - /* if ( ent->s.number == 0 - && ent->client->NPC_class == CLASS_VEHICLE - && vehicleData[((CVehicleNPC *)ent->NPC)->m_iVehicleTypeID].type == VH_FIGHTER ) - { - WP_ATSTMainFire( ent ); - } - else*/ - { - WP_ATSTSideFire(ent); - } + /* if ( ent->s.number == 0 + && ent->client->NPC_class == CLASS_VEHICLE + && vehicleData[((CVehicleNPC *)ent->NPC)->m_iVehicleTypeID].type == VH_FIGHTER ) + { + WP_ATSTMainFire( ent ); + } + else*/ + { WP_ATSTSideFire(ent); } } break; case WP_TIE_FIGHTER: // TEMP - WP_EmplacedFire( ent ); + WP_EmplacedFire(ent); break; case WP_RAPID_FIRE_CONC: // TEMP - if ( alt_fire ) - { - WP_FireRepeater( ent, alt_fire ); - } - else - { - WP_EmplacedFire( ent ); + if (alt_fire) { + WP_FireRepeater(ent, alt_fire); + } else { + WP_EmplacedFire(ent); } break; case WP_STUN_BATON: - WP_FireStunBaton( ent, alt_fire ); + WP_FireStunBaton(ent, alt_fire); break; -// case WP_BLASTER_PISTOL: + // case WP_BLASTER_PISTOL: case WP_JAWA: - WP_FireBryarPistol( ent, qfalse ); // never an alt-fire? + WP_FireBryarPistol(ent, qfalse); // never an alt-fire? break; case WP_SCEPTER: - WP_FireScepter( ent, alt_fire ); + WP_FireScepter(ent, alt_fire); break; case WP_NOGHRI_STICK: - if ( !alt_fire ) - { - WP_FireNoghriStick( ent ); + if (!alt_fire) { + WP_FireNoghriStick(ent); } - //else does melee attack/damage/func + // else does melee attack/damage/func break; case WP_TUSKEN_STAFF: @@ -1541,38 +1329,27 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) break; } - if ( !ent->s.number ) - { - if ( ent->s.weapon == WP_FLECHETTE || (ent->s.weapon == WP_BOWCASTER && !alt_fire) ) - {//these can fire multiple shots, count them individually within the firing functions - } - else if ( W_AccuracyLoggableWeapon( ent->s.weapon, alt_fire, MOD_UNKNOWN ) ) - { + if (!ent->s.number) { + if (ent->s.weapon == WP_FLECHETTE || + (ent->s.weapon == WP_BOWCASTER && !alt_fire)) { // these can fire multiple shots, count them individually within the firing functions + } else if (W_AccuracyLoggableWeapon(ent->s.weapon, alt_fire, MOD_UNKNOWN)) { ent->client->sess.missionStats.shotsFired++; } } // We should probably just use this as a default behavior, in special cases, just set alert to false. - if ( ent->s.number == 0 && alert > 0 ) - { - if ( ent->client->ps.groundEntityNum == ENTITYNUM_WORLD//FIXME: check for sand contents type? - && ent->s.weapon != WP_STUN_BATON - && ent->s.weapon != WP_MELEE - && ent->s.weapon != WP_TUSKEN_STAFF - && ent->s.weapon != WP_THERMAL - && ent->s.weapon != WP_TRIP_MINE - && ent->s.weapon != WP_DET_PACK ) - {//the vibration of the shot carries through your feet into the ground - AddSoundEvent( ent, muzzle, alert, AEL_DISCOVERED, qfalse, qtrue ); + if (ent->s.number == 0 && alert > 0) { + if (ent->client->ps.groundEntityNum == ENTITYNUM_WORLD // FIXME: check for sand contents type? + && ent->s.weapon != WP_STUN_BATON && ent->s.weapon != WP_MELEE && ent->s.weapon != WP_TUSKEN_STAFF && ent->s.weapon != WP_THERMAL && + ent->s.weapon != WP_TRIP_MINE && ent->s.weapon != WP_DET_PACK) { // the vibration of the shot carries through your feet into the ground + AddSoundEvent(ent, muzzle, alert, AEL_DISCOVERED, qfalse, qtrue); + } else { // an in-air alert + AddSoundEvent(ent, muzzle, alert, AEL_DISCOVERED); } - else - {//an in-air alert - AddSoundEvent( ent, muzzle, alert, AEL_DISCOVERED ); - } - AddSightEvent( ent, muzzle, alert*2, AEL_DISCOVERED, 20 ); + AddSightEvent(ent, muzzle, alert * 2, AEL_DISCOVERED, 20); } } -//NOTE: Emplaced gun moved to g_emplaced.cpp +// NOTE: Emplaced gun moved to g_emplaced.cpp /*QUAKED misc_weapon_shooter (1 0 0) (-8 -8 -8) (8 8 8) ALTFIRE TOGGLE ALTFIRE - fire the alt-fire of the chosen weapon @@ -1607,93 +1384,75 @@ TOGGLE - keep firing until used again (fires at intervals of "wait") WP_RAPID_FIRE_CONC WP_BLASTER_PISTOL */ -void misc_weapon_shooter_fire( gentity_t *self ) -{ - FireWeapon( self, (qboolean)((self->spawnflags&1) != 0) ); - if ( (self->spawnflags&2) ) - {//repeat +void misc_weapon_shooter_fire(gentity_t *self) { + FireWeapon(self, (qboolean)((self->spawnflags & 1) != 0)); + if ((self->spawnflags & 2)) { // repeat self->e_ThinkFunc = thinkF_misc_weapon_shooter_fire; - if (self->random) - { - self->nextthink = level.time + self->wait + (int)(Q_flrand(0.0f, 1.0f)*self->random); - } - else - { + if (self->random) { + self->nextthink = level.time + self->wait + (int)(Q_flrand(0.0f, 1.0f) * self->random); + } else { self->nextthink = level.time + self->wait; } } } -void misc_weapon_shooter_use ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->e_ThinkFunc == thinkF_misc_weapon_shooter_fire ) - {//repeating fire, stop +void misc_weapon_shooter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->e_ThinkFunc == thinkF_misc_weapon_shooter_fire) { // repeating fire, stop self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; return; } - //otherwise, fire - misc_weapon_shooter_fire( self ); + // otherwise, fire + misc_weapon_shooter_fire(self); } -void misc_weapon_shooter_aim( gentity_t *self ) -{ - //update my aim - if ( self->target ) - { - gentity_t *targ = G_Find( NULL, FOFS(targetname), self->target ); - if ( targ ) - { +void misc_weapon_shooter_aim(gentity_t *self) { + // update my aim + if (self->target) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), self->target); + if (targ) { self->enemy = targ; - VectorSubtract( targ->currentOrigin, self->currentOrigin, self->client->renderInfo.muzzleDir ); - VectorCopy( targ->currentOrigin, self->pos1 ); - vectoangles( self->client->renderInfo.muzzleDir, self->client->ps.viewangles ); - SetClientViewAngle( self, self->client->ps.viewangles ); - //FIXME: don't keep doing this unless target is a moving target? + VectorSubtract(targ->currentOrigin, self->currentOrigin, self->client->renderInfo.muzzleDir); + VectorCopy(targ->currentOrigin, self->pos1); + vectoangles(self->client->renderInfo.muzzleDir, self->client->ps.viewangles); + SetClientViewAngle(self, self->client->ps.viewangles); + // FIXME: don't keep doing this unless target is a moving target? self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->enemy = NULL; } } } extern stringID_table_t WPTable[]; -void SP_misc_weapon_shooter( gentity_t *self ) -{ - //alloc a client just for the weapon code to use +void SP_misc_weapon_shooter(gentity_t *self) { + // alloc a client just for the weapon code to use self->client = (gclient_t *)gi.Malloc(sizeof(gclient_t), TAG_G_ALLOC, qtrue); - //set weapon + // set weapon self->s.weapon = self->client->ps.weapon = WP_BLASTER; - if ( self->paintarget ) - {//use a different weapon - self->s.weapon = self->client->ps.weapon = GetIDForString( WPTable, self->paintarget ); + if (self->paintarget) { // use a different weapon + self->s.weapon = self->client->ps.weapon = GetIDForString(WPTable, self->paintarget); } - //set where our muzzle is - VectorCopy( self->s.origin, self->client->renderInfo.muzzlePoint ); - //permanently updated + // set where our muzzle is + VectorCopy(self->s.origin, self->client->renderInfo.muzzlePoint); + // permanently updated self->client->renderInfo.mPCalcTime = Q3_INFINITE; - //set up to link - if ( self->target ) - { - self->e_ThinkFunc = thinkF_misc_weapon_shooter_aim; + // set up to link + if (self->target) { + self->e_ThinkFunc = thinkF_misc_weapon_shooter_aim; self->nextthink = level.time + START_TIME_LINK_ENTS; - } - else - {//just set aim angles - VectorCopy( self->s.angles, self->client->ps.viewangles ); - AngleVectors( self->s.angles, self->client->renderInfo.muzzleDir, NULL, NULL ); + } else { // just set aim angles + VectorCopy(self->s.angles, self->client->ps.viewangles); + AngleVectors(self->s.angles, self->client->renderInfo.muzzleDir, NULL, NULL); } - //set up to fire when used - self->e_UseFunc = useF_misc_weapon_shooter_use; + // set up to fire when used + self->e_UseFunc = useF_misc_weapon_shooter_use; - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; } } diff --git a/code/game/g_weaponLoad.cpp b/code/game/g_weaponLoad.cpp index 75f1e82c69..76ba0da524 100644 --- a/code/game/g_weaponLoad.cpp +++ b/code/game/g_weaponLoad.cpp @@ -27,116 +27,113 @@ along with this program; if not, see . #include "g_local.h" typedef struct { - const char *name; - void (*func)(centity_t *cent, const struct weaponInfo_s *weapon ); + const char *name; + void (*func)(centity_t *cent, const struct weaponInfo_s *weapon); } func_t; // Bryar -void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BryarProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_BryarAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Blaster -void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BlasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_BlasterAltFireThink(centity_t *cent, const struct weaponInfo_s *weapon); // Bowcaster -void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BowcasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Heavy Repeater -void FX_RepeaterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_RepeaterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_RepeaterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_RepeaterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // DEMP2 -void FX_DEMP2_ProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_DEMP2_AltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_DEMP2_ProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_DEMP2_AltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Golan Arms Flechette -void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_FlechetteAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_FlechetteProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_FlechetteAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Personal Rocket Launcher -void FX_RocketProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_RocketAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_RocketProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_RocketAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Concussion Rifle -void FX_ConcProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_ConcProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Emplaced weapon -void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_EmplacedProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Turret weapon -void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_TurretProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // ATST Main weapon -void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_ATSTMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // ATST Side weapons -void FX_ATSTSideMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_ATSTSideMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_ATSTSideAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); -//Tusken projectile -void FX_TuskenShotProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +// Tusken projectile +void FX_TuskenShotProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); -//Noghri projectile -void FX_NoghriShotProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +// Noghri projectile +void FX_NoghriShotProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Table used to attach an extern missile function string to the actual cgame function -func_t funcs[] = { - {"bryar_func", FX_BryarProjectileThink}, - {"bryar_alt_func", FX_BryarAltProjectileThink}, - {"blaster_func", FX_BlasterProjectileThink}, - {"blaster_alt_func", FX_BlasterAltFireThink}, - {"bowcaster_func", FX_BowcasterProjectileThink}, - {"repeater_func", FX_RepeaterProjectileThink}, - {"repeater_alt_func", FX_RepeaterAltProjectileThink}, - {"demp2_func", FX_DEMP2_ProjectileThink}, - {"demp2_alt_func", FX_DEMP2_AltProjectileThink}, - {"flechette_func", FX_FlechetteProjectileThink}, - {"flechette_alt_func", FX_FlechetteAltProjectileThink}, - {"rocket_func", FX_RocketProjectileThink}, - {"rocket_alt_func", FX_RocketAltProjectileThink}, - {"conc_func", FX_ConcProjectileThink}, - {"emplaced_func", FX_EmplacedProjectileThink}, - {"turret_func", FX_TurretProjectileThink}, - {"atstmain_func", FX_ATSTMainProjectileThink}, - {"atst_side_alt_func", FX_ATSTSideAltProjectileThink}, - {"atst_side_main_func", FX_ATSTSideMainProjectileThink}, - {"tusk_shot_func", FX_TuskenShotProjectileThink}, - {"noghri_shot_func", FX_NoghriShotProjectileThink}, - {NULL, NULL} -}; - -//qboolean COM_ParseInt( char **data, int *i ); -//qboolean COM_ParseString( char **data, char **s ); -//qboolean COM_ParseFloat( char **data, float *f ); - -struct wpnParms_s -{ - int weaponNum; // Current weapon number - int ammoNum; +func_t funcs[] = {{"bryar_func", FX_BryarProjectileThink}, + {"bryar_alt_func", FX_BryarAltProjectileThink}, + {"blaster_func", FX_BlasterProjectileThink}, + {"blaster_alt_func", FX_BlasterAltFireThink}, + {"bowcaster_func", FX_BowcasterProjectileThink}, + {"repeater_func", FX_RepeaterProjectileThink}, + {"repeater_alt_func", FX_RepeaterAltProjectileThink}, + {"demp2_func", FX_DEMP2_ProjectileThink}, + {"demp2_alt_func", FX_DEMP2_AltProjectileThink}, + {"flechette_func", FX_FlechetteProjectileThink}, + {"flechette_alt_func", FX_FlechetteAltProjectileThink}, + {"rocket_func", FX_RocketProjectileThink}, + {"rocket_alt_func", FX_RocketAltProjectileThink}, + {"conc_func", FX_ConcProjectileThink}, + {"emplaced_func", FX_EmplacedProjectileThink}, + {"turret_func", FX_TurretProjectileThink}, + {"atstmain_func", FX_ATSTMainProjectileThink}, + {"atst_side_alt_func", FX_ATSTSideAltProjectileThink}, + {"atst_side_main_func", FX_ATSTSideMainProjectileThink}, + {"tusk_shot_func", FX_TuskenShotProjectileThink}, + {"noghri_shot_func", FX_NoghriShotProjectileThink}, + {NULL, NULL}}; + +// qboolean COM_ParseInt( char **data, int *i ); +// qboolean COM_ParseString( char **data, char **s ); +// qboolean COM_ParseFloat( char **data, float *f ); + +struct wpnParms_s { + int weaponNum; // Current weapon number + int ammoNum; } wpnParms; -void WPN_Ammo (const char **holdBuf); -void WPN_AmmoIcon (const char **holdBuf); -void WPN_AmmoMax (const char **holdBuf); -void WPN_AmmoLowCnt (const char **holdBuf); -void WPN_AmmoType (const char **holdBuf); -void WPN_EnergyPerShot (const char **holdBuf); -void WPN_FireTime (const char **holdBuf); -void WPN_FiringSnd (const char **holdBuf); -void WPN_AltFiringSnd(const char **holdBuf ); -void WPN_StopSnd( const char **holdBuf ); -void WPN_ChargeSnd (const char **holdBuf); -void WPN_AltChargeSnd (const char **holdBuf); -void WPN_SelectSnd (const char **holdBuf); -void WPN_Range (const char **holdBuf); -void WPN_WeaponClass ( const char **holdBuf); -void WPN_WeaponIcon (const char **holdBuf); -void WPN_WeaponModel (const char **holdBuf); -void WPN_WeaponType (const char **holdBuf); -void WPN_AltEnergyPerShot (const char **holdBuf); -void WPN_AltFireTime (const char **holdBuf); -void WPN_AltRange (const char **holdBuf); +void WPN_Ammo(const char **holdBuf); +void WPN_AmmoIcon(const char **holdBuf); +void WPN_AmmoMax(const char **holdBuf); +void WPN_AmmoLowCnt(const char **holdBuf); +void WPN_AmmoType(const char **holdBuf); +void WPN_EnergyPerShot(const char **holdBuf); +void WPN_FireTime(const char **holdBuf); +void WPN_FiringSnd(const char **holdBuf); +void WPN_AltFiringSnd(const char **holdBuf); +void WPN_StopSnd(const char **holdBuf); +void WPN_ChargeSnd(const char **holdBuf); +void WPN_AltChargeSnd(const char **holdBuf); +void WPN_SelectSnd(const char **holdBuf); +void WPN_Range(const char **holdBuf); +void WPN_WeaponClass(const char **holdBuf); +void WPN_WeaponIcon(const char **holdBuf); +void WPN_WeaponModel(const char **holdBuf); +void WPN_WeaponType(const char **holdBuf); +void WPN_AltEnergyPerShot(const char **holdBuf); +void WPN_AltFireTime(const char **holdBuf); +void WPN_AltRange(const char **holdBuf); void WPN_BarrelCount(const char **holdBuf); void WPN_MissileName(const char **holdBuf); void WPN_AltMissileName(const char **holdBuf); @@ -165,456 +162,435 @@ void WPN_AltSplashRadius(const char **holdBuf); // Legacy weapons.dat force fields void WPN_FuncSkip(const char **holdBuf); -typedef struct -{ - const char *parmName; - void (*func)(const char **holdBuf); +typedef struct { + const char *parmName; + void (*func)(const char **holdBuf); } wpnParms_t; // This is used as a fallback for each new field, in case they're using base files --eez const int defaultDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - BRYAR_PISTOL_DAMAGE, // WP_BLASTER_PISTOL - BLASTER_DAMAGE, // WP_BLASTER - DISRUPTOR_MAIN_DAMAGE, // WP_DISRUPTOR - BOWCASTER_DAMAGE, // WP_BOWCASTER - REPEATER_DAMAGE, // WP_REPEATER - DEMP2_DAMAGE, // WP_DEMP2 - FLECHETTE_DAMAGE, // WP_FLECHETTE - ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER - TD_DAMAGE, // WP_THERMAL - LT_DAMAGE, // WP_TRIP_MINE - FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - CONC_DAMAGE, // WP_CONCUSSION - - 0, // WP_MELEE // handled by the melee attack function - - ATST_MAIN_DAMAGE, // WP_ATST_MAIN - ATST_SIDE_MAIN_DAMAGE, // WP_ATST_SIDE - - STUN_BATON_DAMAGE, // WP_STUN_BATON - - BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL - EMPLACED_DAMAGE, // WP_EMPLACED_GUN - BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - EMPLACED_DAMAGE, // WP_TIE_FIGHTER - EMPLACED_DAMAGE, // WP_RAPID_FIRE_CONC, - - BRYAR_PISTOL_DAMAGE, // WP_JAWA - 0, // WP_TUSKEN_RIFLE - 0, // WP_TUSKEN_STAFF - 0, // WP_SCEPTER - 0, // WP_NOGHRI_STICK + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + BRYAR_PISTOL_DAMAGE, // WP_BLASTER_PISTOL + BLASTER_DAMAGE, // WP_BLASTER + DISRUPTOR_MAIN_DAMAGE, // WP_DISRUPTOR + BOWCASTER_DAMAGE, // WP_BOWCASTER + REPEATER_DAMAGE, // WP_REPEATER + DEMP2_DAMAGE, // WP_DEMP2 + FLECHETTE_DAMAGE, // WP_FLECHETTE + ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER + TD_DAMAGE, // WP_THERMAL + LT_DAMAGE, // WP_TRIP_MINE + FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + CONC_DAMAGE, // WP_CONCUSSION + + 0, // WP_MELEE // handled by the melee attack function + + ATST_MAIN_DAMAGE, // WP_ATST_MAIN + ATST_SIDE_MAIN_DAMAGE, // WP_ATST_SIDE + + STUN_BATON_DAMAGE, // WP_STUN_BATON + + BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL + EMPLACED_DAMAGE, // WP_EMPLACED_GUN + BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + EMPLACED_DAMAGE, // WP_TIE_FIGHTER + EMPLACED_DAMAGE, // WP_RAPID_FIRE_CONC, + + BRYAR_PISTOL_DAMAGE, // WP_JAWA + 0, // WP_TUSKEN_RIFLE + 0, // WP_TUSKEN_STAFF + 0, // WP_SCEPTER + 0, // WP_NOGHRI_STICK }; const int defaultAltDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - BRYAR_PISTOL_DAMAGE, // WP_BLASTER_PISTOL - BLASTER_DAMAGE, // WP_BLASTER - DISRUPTOR_ALT_DAMAGE, // WP_DISRUPTOR - BOWCASTER_DAMAGE, // WP_BOWCASTER - REPEATER_ALT_DAMAGE, // WP_REPEATER - DEMP2_ALT_DAMAGE, // WP_DEMP2 - FLECHETTE_ALT_DAMAGE, // WP_FLECHETTE - ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER - TD_ALT_DAMAGE, // WP_THERMAL - LT_DAMAGE, // WP_TRIP_MINE - FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - CONC_ALT_DAMAGE, // WP_CONCUSION - - 0, // WP_MELEE // handled by the melee attack function - - ATST_MAIN_DAMAGE, // WP_ATST_MAIN - ATST_SIDE_ALT_DAMAGE, // WP_ATST_SIDE - - STUN_BATON_ALT_DAMAGE, // WP_STUN_BATON - - BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL - EMPLACED_DAMAGE, // WP_EMPLACED_GUN - BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - EMPLACED_DAMAGE, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC // repeater alt damage is used instead - - BRYAR_PISTOL_DAMAGE, // WP_JAWA - 0, // WP_TUSKEN_RIFLE - 0, // WP_TUSKEN_STAFF - 0, // WP_SCEPTER - 0, // WP_NOGHRI_STICK + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + BRYAR_PISTOL_DAMAGE, // WP_BLASTER_PISTOL + BLASTER_DAMAGE, // WP_BLASTER + DISRUPTOR_ALT_DAMAGE, // WP_DISRUPTOR + BOWCASTER_DAMAGE, // WP_BOWCASTER + REPEATER_ALT_DAMAGE, // WP_REPEATER + DEMP2_ALT_DAMAGE, // WP_DEMP2 + FLECHETTE_ALT_DAMAGE, // WP_FLECHETTE + ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER + TD_ALT_DAMAGE, // WP_THERMAL + LT_DAMAGE, // WP_TRIP_MINE + FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + CONC_ALT_DAMAGE, // WP_CONCUSION + + 0, // WP_MELEE // handled by the melee attack function + + ATST_MAIN_DAMAGE, // WP_ATST_MAIN + ATST_SIDE_ALT_DAMAGE, // WP_ATST_SIDE + + STUN_BATON_ALT_DAMAGE, // WP_STUN_BATON + + BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL + EMPLACED_DAMAGE, // WP_EMPLACED_GUN + BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + EMPLACED_DAMAGE, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC // repeater alt damage is used instead + + BRYAR_PISTOL_DAMAGE, // WP_JAWA + 0, // WP_TUSKEN_RIFLE + 0, // WP_TUSKEN_STAFF + 0, // WP_SCEPTER + 0, // WP_NOGHRI_STICK }; const int defaultSplashDamage[] = { - 0, // WP_NONE - 0, // WP_SABER - 0, // WP_BLASTER_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER - 0, // WP_REPEATER - 0, // WP_DEMP2 - 0, // WP_FLECHETTE - ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER - TD_SPLASH_DAM, // WP_THERMAL - LT_SPLASH_DAM, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - CONC_SPLASH_DAMAGE, // WP_CONCUSSION - - 0, // WP_MELEE - - 0, // WP_ATST_MAIN - ATST_SIDE_MAIN_SPLASH_DAMAGE, // WP_ATST_SIDE - - 0, // WP_STUN_BATON - - 0, // WP_BRYAR_PISTOL - 0, // WP_EMPLACED_GUN - 0, // WP_BOT_LASER - 0, // WP_TURRET - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - - 0, // WP_JAWA - 0, // WP_TUSKEN_RIFLE - 0, // WP_TUSKEN_STAFF - 0, // WP_SCEPTER - 0, // WP_NOGHRI_STICK + 0, // WP_NONE + 0, // WP_SABER + 0, // WP_BLASTER_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER + 0, // WP_REPEATER + 0, // WP_DEMP2 + 0, // WP_FLECHETTE + ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER + TD_SPLASH_DAM, // WP_THERMAL + LT_SPLASH_DAM, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + CONC_SPLASH_DAMAGE, // WP_CONCUSSION + + 0, // WP_MELEE + + 0, // WP_ATST_MAIN + ATST_SIDE_MAIN_SPLASH_DAMAGE, // WP_ATST_SIDE + + 0, // WP_STUN_BATON + + 0, // WP_BRYAR_PISTOL + 0, // WP_EMPLACED_GUN + 0, // WP_BOT_LASER + 0, // WP_TURRET + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + + 0, // WP_JAWA + 0, // WP_TUSKEN_RIFLE + 0, // WP_TUSKEN_STAFF + 0, // WP_SCEPTER + 0, // WP_NOGHRI_STICK }; const float defaultSplashRadius[] = { - 0.0f, // WP_NONE - 0.0f, // WP_SABER - 0.0f, // WP_BLASTER_PISTOL - 0.0f, // WP_BLASTER - 0.0f, // WP_DISRUPTOR - BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER - 0.0f, // WP_REPEATER - 0.0f, // WP_DEMP2 - 0.0f, // WP_FLECHETTE - ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER - TD_SPLASH_RAD, // WP_THERMAL - LT_SPLASH_RAD, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_RADIUS, // WP_DET_PACK // HACK, this is what the code sez. - CONC_SPLASH_RADIUS, // WP_CONCUSSION - - 0.0f, // WP_MELEE - - 0.0f, // WP_ATST_MAIN - ATST_SIDE_MAIN_SPLASH_RADIUS, // WP_ATST_SIDE - - 0.0f, // WP_STUN_BATON - - 0.0f, // WP_BRYAR_PISTOL - 0.0f, // WP_EMPLACED_GUN - 0.0f, // WP_BOT_LASER - 0.0f, // WP_TURRET - 0.0f, // WP_TIE_FIGHTER - 0.0f, // WP_RAPID_FIRE_CONC - - 0.0f, // WP_JAWA - 0.0f, // WP_TUSKEN_RIFLE - 0.0f, // WP_TUSKEN_STAFF - 0.0f, // WP_SCEPTER - 0.0f, // WP_NOGHRI_STICK + 0.0f, // WP_NONE + 0.0f, // WP_SABER + 0.0f, // WP_BLASTER_PISTOL + 0.0f, // WP_BLASTER + 0.0f, // WP_DISRUPTOR + BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER + 0.0f, // WP_REPEATER + 0.0f, // WP_DEMP2 + 0.0f, // WP_FLECHETTE + ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER + TD_SPLASH_RAD, // WP_THERMAL + LT_SPLASH_RAD, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_RADIUS, // WP_DET_PACK // HACK, this is what the code sez. + CONC_SPLASH_RADIUS, // WP_CONCUSSION + + 0.0f, // WP_MELEE + + 0.0f, // WP_ATST_MAIN + ATST_SIDE_MAIN_SPLASH_RADIUS, // WP_ATST_SIDE + + 0.0f, // WP_STUN_BATON + + 0.0f, // WP_BRYAR_PISTOL + 0.0f, // WP_EMPLACED_GUN + 0.0f, // WP_BOT_LASER + 0.0f, // WP_TURRET + 0.0f, // WP_TIE_FIGHTER + 0.0f, // WP_RAPID_FIRE_CONC + + 0.0f, // WP_JAWA + 0.0f, // WP_TUSKEN_RIFLE + 0.0f, // WP_TUSKEN_STAFF + 0.0f, // WP_SCEPTER + 0.0f, // WP_NOGHRI_STICK }; const int defaultAltSplashDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - 0, // WP_BLASTER_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER - REPEATER_ALT_SPLASH_DAMAGE, // WP_REPEATER - DEMP2_ALT_DAMAGE, // WP_DEMP2 - FLECHETTE_ALT_SPLASH_DAM, // WP_FLECHETTE - ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER - TD_ALT_SPLASH_DAM, // WP_THERMAL - TD_ALT_SPLASH_DAM, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - 0, // WP_CONCUSSION - - 0, // WP_MELEE // handled by the melee attack function - - 0, // WP_ATST_MAIN - ATST_SIDE_ALT_SPLASH_DAMAGE, // WP_ATST_SIDE - - 0, // WP_STUN_BATON - - 0, // WP_BRYAR_PISTOL - 0, // WP_EMPLACED_GUN - 0, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - - 0, // WP_JAWA - 0, // WP_TUSKEN_RIFLE - 0, // WP_TUSKEN_STAFF - 0, // WP_SCEPTER - 0, // WP_NOGHRI_STICK + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + 0, // WP_BLASTER_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER + REPEATER_ALT_SPLASH_DAMAGE, // WP_REPEATER + DEMP2_ALT_DAMAGE, // WP_DEMP2 + FLECHETTE_ALT_SPLASH_DAM, // WP_FLECHETTE + ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER + TD_ALT_SPLASH_DAM, // WP_THERMAL + TD_ALT_SPLASH_DAM, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + 0, // WP_CONCUSSION + + 0, // WP_MELEE // handled by the melee attack function + + 0, // WP_ATST_MAIN + ATST_SIDE_ALT_SPLASH_DAMAGE, // WP_ATST_SIDE + + 0, // WP_STUN_BATON + + 0, // WP_BRYAR_PISTOL + 0, // WP_EMPLACED_GUN + 0, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + + 0, // WP_JAWA + 0, // WP_TUSKEN_RIFLE + 0, // WP_TUSKEN_STAFF + 0, // WP_SCEPTER + 0, // WP_NOGHRI_STICK }; const float defaultAltSplashRadius[] = { - 0.0f, // WP_NONE - 0.0f, // WP_SABER // handled elsewhere - 0.0f, // WP_BLASTER_PISTOL - 0.0f, // WP_BLASTER - 0.0f, // WP_DISRUPTOR - BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER - REPEATER_ALT_SPLASH_RADIUS, // WP_REPEATER - DEMP2_ALT_SPLASHRADIUS, // WP_DEMP2 - FLECHETTE_ALT_SPLASH_RAD, // WP_FLECHETTE - ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER - TD_ALT_SPLASH_RAD, // WP_THERMAL - LT_SPLASH_RAD, // WP_TRIP_MINE - FLECHETTE_ALT_SPLASH_RAD, // WP_DET_PACK // HACK, this is what the code sez. - 0.0f, // WP_CONCUSSION - - 0.0f, // WP_MELEE // handled by the melee attack function - - 0.0f, // WP_ATST_MAIN - ATST_SIDE_ALT_SPLASH_RADIUS, // WP_ATST_SIDE - - 0.0f, // WP_STUN_BATON - - 0.0f, // WP_BRYAR_PISTOL - 0.0f, // WP_EMPLACED_GUN - 0.0f, // WP_BOT_LASER - 0.0f, // WP_TURRET // handled elsewhere - 0.0f, // WP_TIE_FIGHTER - 0.0f, // WP_RAPID_FIRE_CONC - - 0.0f, // WP_JAWA - 0.0f, // WP_TUSKEN_RIFLE - 0.0f, // WP_TUSKEN_STAFF - 0.0f, // WP_SCEPTER - 0.0f, // WP_NOGHRI_STICK + 0.0f, // WP_NONE + 0.0f, // WP_SABER // handled elsewhere + 0.0f, // WP_BLASTER_PISTOL + 0.0f, // WP_BLASTER + 0.0f, // WP_DISRUPTOR + BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER + REPEATER_ALT_SPLASH_RADIUS, // WP_REPEATER + DEMP2_ALT_SPLASHRADIUS, // WP_DEMP2 + FLECHETTE_ALT_SPLASH_RAD, // WP_FLECHETTE + ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER + TD_ALT_SPLASH_RAD, // WP_THERMAL + LT_SPLASH_RAD, // WP_TRIP_MINE + FLECHETTE_ALT_SPLASH_RAD, // WP_DET_PACK // HACK, this is what the code sez. + 0.0f, // WP_CONCUSSION + + 0.0f, // WP_MELEE // handled by the melee attack function + + 0.0f, // WP_ATST_MAIN + ATST_SIDE_ALT_SPLASH_RADIUS, // WP_ATST_SIDE + + 0.0f, // WP_STUN_BATON + + 0.0f, // WP_BRYAR_PISTOL + 0.0f, // WP_EMPLACED_GUN + 0.0f, // WP_BOT_LASER + 0.0f, // WP_TURRET // handled elsewhere + 0.0f, // WP_TIE_FIGHTER + 0.0f, // WP_RAPID_FIRE_CONC + + 0.0f, // WP_JAWA + 0.0f, // WP_TUSKEN_RIFLE + 0.0f, // WP_TUSKEN_STAFF + 0.0f, // WP_SCEPTER + 0.0f, // WP_NOGHRI_STICK }; -wpnParms_t WpnParms[] = -{ - { "ammo", WPN_Ammo }, //ammo - { "ammoicon", WPN_AmmoIcon }, - { "ammomax", WPN_AmmoMax }, - { "ammolowcount", WPN_AmmoLowCnt }, //weapons - { "ammotype", WPN_AmmoType }, - { "energypershot", WPN_EnergyPerShot }, - { "fireTime", WPN_FireTime }, - { "firingsound", WPN_FiringSnd }, - { "altfiringsound", WPN_AltFiringSnd }, -// { "flashsound", WPN_FlashSnd }, -// { "altflashsound", WPN_AltFlashSnd }, - { "stopsound", WPN_StopSnd }, - { "chargesound", WPN_ChargeSnd }, - { "altchargesound", WPN_AltChargeSnd }, - { "selectsound", WPN_SelectSnd }, - { "range", WPN_Range }, - { "weaponclass", WPN_WeaponClass }, - { "weaponicon", WPN_WeaponIcon }, - { "weaponmodel", WPN_WeaponModel }, - { "weapontype", WPN_WeaponType }, - { "altenergypershot", WPN_AltEnergyPerShot }, - { "altfireTime", WPN_AltFireTime }, - { "altrange", WPN_AltRange }, - { "barrelcount", WPN_BarrelCount }, - { "missileModel", WPN_MissileName }, - { "altmissileModel", WPN_AltMissileName }, - { "missileSound", WPN_MissileSound }, - { "altmissileSound", WPN_AltMissileSound }, - { "missileLight", WPN_MissileLight }, - { "altmissileLight", WPN_AltMissileLight }, - { "missileLightColor",WPN_MissileLightColor }, - { "altmissileLightColor", WPN_AltMissileLightColor }, - { "missileFuncName", WPN_FuncName }, - { "altmissileFuncName", WPN_AltFuncName }, - { "missileHitSound", WPN_MissileHitSound }, - { "altmissileHitSound", WPN_AltMissileHitSound }, - { "muzzleEffect", WPN_MuzzleEffect }, - { "altmuzzleEffect", WPN_AltMuzzleEffect }, +wpnParms_t WpnParms[] = { + {"ammo", WPN_Ammo}, // ammo + {"ammoicon", WPN_AmmoIcon}, + {"ammomax", WPN_AmmoMax}, + {"ammolowcount", WPN_AmmoLowCnt}, // weapons + {"ammotype", WPN_AmmoType}, + {"energypershot", WPN_EnergyPerShot}, + {"fireTime", WPN_FireTime}, + {"firingsound", WPN_FiringSnd}, + {"altfiringsound", WPN_AltFiringSnd}, + // { "flashsound", WPN_FlashSnd }, + // { "altflashsound", WPN_AltFlashSnd }, + {"stopsound", WPN_StopSnd}, + {"chargesound", WPN_ChargeSnd}, + {"altchargesound", WPN_AltChargeSnd}, + {"selectsound", WPN_SelectSnd}, + {"range", WPN_Range}, + {"weaponclass", WPN_WeaponClass}, + {"weaponicon", WPN_WeaponIcon}, + {"weaponmodel", WPN_WeaponModel}, + {"weapontype", WPN_WeaponType}, + {"altenergypershot", WPN_AltEnergyPerShot}, + {"altfireTime", WPN_AltFireTime}, + {"altrange", WPN_AltRange}, + {"barrelcount", WPN_BarrelCount}, + {"missileModel", WPN_MissileName}, + {"altmissileModel", WPN_AltMissileName}, + {"missileSound", WPN_MissileSound}, + {"altmissileSound", WPN_AltMissileSound}, + {"missileLight", WPN_MissileLight}, + {"altmissileLight", WPN_AltMissileLight}, + {"missileLightColor", WPN_MissileLightColor}, + {"altmissileLightColor", WPN_AltMissileLightColor}, + {"missileFuncName", WPN_FuncName}, + {"altmissileFuncName", WPN_AltFuncName}, + {"missileHitSound", WPN_MissileHitSound}, + {"altmissileHitSound", WPN_AltMissileHitSound}, + {"muzzleEffect", WPN_MuzzleEffect}, + {"altmuzzleEffect", WPN_AltMuzzleEffect}, // OPENJK NEW FIELDS - { "damage", WPN_Damage }, - { "altdamage", WPN_AltDamage }, - { "splashDamage", WPN_SplashDamage }, - { "splashRadius", WPN_SplashRadius }, - { "altSplashDamage", WPN_AltSplashDamage }, - { "altSplashRadius", WPN_AltSplashRadius }, + {"damage", WPN_Damage}, + {"altdamage", WPN_AltDamage}, + {"splashDamage", WPN_SplashDamage}, + {"splashRadius", WPN_SplashRadius}, + {"altSplashDamage", WPN_AltSplashDamage}, + {"altSplashRadius", WPN_AltSplashRadius}, // Old legacy files contain these, so we skip them to shut up warnings - { "firingforce", WPN_FuncSkip }, - { "chargeforce", WPN_FuncSkip }, - { "altchargeforce", WPN_FuncSkip }, - { "selectforce", WPN_FuncSkip }, + {"firingforce", WPN_FuncSkip}, + {"chargeforce", WPN_FuncSkip}, + {"altchargeforce", WPN_FuncSkip}, + {"selectforce", WPN_FuncSkip}, }; static const size_t numWpnParms = ARRAY_LEN(WpnParms); -void WPN_FuncSkip( const char **holdBuf) -{ - SkipRestOfLine(holdBuf); -} +void WPN_FuncSkip(const char **holdBuf) { SkipRestOfLine(holdBuf); } -void WPN_WeaponType( const char **holdBuf) -{ +void WPN_WeaponType(const char **holdBuf) { int weaponNum; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } // FIXME : put this in an array (maybe a weaponDataInternal array???) - if (!Q_stricmp(tokenStr,"WP_NONE")) + if (!Q_stricmp(tokenStr, "WP_NONE")) weaponNum = WP_NONE; - else if (!Q_stricmp(tokenStr,"WP_SABER")) + else if (!Q_stricmp(tokenStr, "WP_SABER")) weaponNum = WP_SABER; - else if (!Q_stricmp(tokenStr,"WP_BLASTER_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER_PISTOL")) weaponNum = WP_BLASTER_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_BRYAR_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BRYAR_PISTOL")) weaponNum = WP_BRYAR_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_BLASTER")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER")) weaponNum = WP_BLASTER; - else if (!Q_stricmp(tokenStr,"WP_DISRUPTOR")) + else if (!Q_stricmp(tokenStr, "WP_DISRUPTOR")) weaponNum = WP_DISRUPTOR; - else if (!Q_stricmp(tokenStr,"WP_BOWCASTER")) + else if (!Q_stricmp(tokenStr, "WP_BOWCASTER")) weaponNum = WP_BOWCASTER; - else if (!Q_stricmp(tokenStr,"WP_REPEATER")) + else if (!Q_stricmp(tokenStr, "WP_REPEATER")) weaponNum = WP_REPEATER; - else if (!Q_stricmp(tokenStr,"WP_DEMP2")) + else if (!Q_stricmp(tokenStr, "WP_DEMP2")) weaponNum = WP_DEMP2; - else if (!Q_stricmp(tokenStr,"WP_FLECHETTE")) + else if (!Q_stricmp(tokenStr, "WP_FLECHETTE")) weaponNum = WP_FLECHETTE; - else if (!Q_stricmp(tokenStr,"WP_ROCKET_LAUNCHER")) + else if (!Q_stricmp(tokenStr, "WP_ROCKET_LAUNCHER")) weaponNum = WP_ROCKET_LAUNCHER; - else if (!Q_stricmp(tokenStr,"WP_CONCUSSION")) + else if (!Q_stricmp(tokenStr, "WP_CONCUSSION")) weaponNum = WP_CONCUSSION; - else if (!Q_stricmp(tokenStr,"WP_THERMAL")) + else if (!Q_stricmp(tokenStr, "WP_THERMAL")) weaponNum = WP_THERMAL; - else if (!Q_stricmp(tokenStr,"WP_TRIP_MINE")) + else if (!Q_stricmp(tokenStr, "WP_TRIP_MINE")) weaponNum = WP_TRIP_MINE; - else if (!Q_stricmp(tokenStr,"WP_DET_PACK")) + else if (!Q_stricmp(tokenStr, "WP_DET_PACK")) weaponNum = WP_DET_PACK; - else if (!Q_stricmp(tokenStr,"WP_STUN_BATON")) + else if (!Q_stricmp(tokenStr, "WP_STUN_BATON")) weaponNum = WP_STUN_BATON; - else if (!Q_stricmp(tokenStr,"WP_BOT_LASER")) + else if (!Q_stricmp(tokenStr, "WP_BOT_LASER")) weaponNum = WP_BOT_LASER; - else if (!Q_stricmp(tokenStr,"WP_EMPLACED_GUN")) + else if (!Q_stricmp(tokenStr, "WP_EMPLACED_GUN")) weaponNum = WP_EMPLACED_GUN; - else if (!Q_stricmp(tokenStr,"WP_MELEE")) + else if (!Q_stricmp(tokenStr, "WP_MELEE")) weaponNum = WP_MELEE; - else if (!Q_stricmp(tokenStr,"WP_TURRET")) + else if (!Q_stricmp(tokenStr, "WP_TURRET")) weaponNum = WP_TURRET; - else if (!Q_stricmp(tokenStr,"WP_ATST_MAIN")) + else if (!Q_stricmp(tokenStr, "WP_ATST_MAIN")) weaponNum = WP_ATST_MAIN; - else if (!Q_stricmp(tokenStr,"WP_ATST_SIDE")) + else if (!Q_stricmp(tokenStr, "WP_ATST_SIDE")) weaponNum = WP_ATST_SIDE; - else if (!Q_stricmp(tokenStr,"WP_TIE_FIGHTER")) + else if (!Q_stricmp(tokenStr, "WP_TIE_FIGHTER")) weaponNum = WP_TIE_FIGHTER; - else if (!Q_stricmp(tokenStr,"WP_RAPID_FIRE_CONC")) + else if (!Q_stricmp(tokenStr, "WP_RAPID_FIRE_CONC")) weaponNum = WP_RAPID_FIRE_CONC; - else if (!Q_stricmp(tokenStr,"WP_JAWA")) + else if (!Q_stricmp(tokenStr, "WP_JAWA")) weaponNum = WP_JAWA; - else if (!Q_stricmp(tokenStr,"WP_TUSKEN_RIFLE")) + else if (!Q_stricmp(tokenStr, "WP_TUSKEN_RIFLE")) weaponNum = WP_TUSKEN_RIFLE; - else if (!Q_stricmp(tokenStr,"WP_TUSKEN_STAFF")) + else if (!Q_stricmp(tokenStr, "WP_TUSKEN_STAFF")) weaponNum = WP_TUSKEN_STAFF; - else if (!Q_stricmp(tokenStr,"WP_SCEPTER")) + else if (!Q_stricmp(tokenStr, "WP_SCEPTER")) weaponNum = WP_SCEPTER; - else if (!Q_stricmp(tokenStr,"WP_NOGHRI_STICK")) + else if (!Q_stricmp(tokenStr, "WP_NOGHRI_STICK")) weaponNum = WP_NOGHRI_STICK; - else - { + else { weaponNum = 0; - gi.Printf(S_COLOR_YELLOW"WARNING: bad weapontype in external weapon data '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: bad weapontype in external weapon data '%s'\n", tokenStr); } wpnParms.weaponNum = weaponNum; } //-------------------------------------------- -void WPN_WeaponClass(const char **holdBuf) -{ +void WPN_WeaponClass(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 32) - { + if (len > 32) { len = 32; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponclass too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponclass too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].classname,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].classname, tokenStr, len); } - //-------------------------------------------- -void WPN_WeaponModel(const char **holdBuf) -{ +void WPN_WeaponModel(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponMdl too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponMdl too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].weaponMdl,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].weaponMdl, tokenStr, len); } //-------------------------------------------- -void WPN_WeaponIcon(const char **holdBuf) -{ +void WPN_WeaponIcon(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponIcon too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponIcon too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].weaponIcon,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].weaponIcon, tokenStr, len); } //-------------------------------------------- -void WPN_AmmoType(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoType(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < AMMO_NONE ) || (tokenInt >= AMMO_MAX )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammotype in external weapon data '%d'\n", tokenInt); + if ((tokenInt < AMMO_NONE) || (tokenInt >= AMMO_MAX)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammotype in external weapon data '%d'\n", tokenInt); return; } @@ -622,19 +598,17 @@ void WPN_AmmoType(const char **holdBuf) } //-------------------------------------------- -void WPN_AmmoLowCnt(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoLowCnt(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 200 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 200)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammolowcount in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammolowcount in external weapon data '%d'\n", tokenInt); return; } @@ -642,171 +616,149 @@ void WPN_AmmoLowCnt(const char **holdBuf) } //-------------------------------------------- -void WPN_FiringSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_FiringSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: firingSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: firingSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].firingSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].firingSnd, tokenStr, len); } //-------------------------------------------- -void WPN_AltFiringSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_AltFiringSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: altFiringSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: altFiringSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altFiringSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altFiringSnd, tokenStr, len); } //-------------------------------------------- -void WPN_StopSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_StopSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: stopSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: stopSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].stopSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].stopSnd, tokenStr, len); } //-------------------------------------------- -void WPN_ChargeSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_ChargeSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: chargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: chargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].chargeSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].chargeSnd, tokenStr, len); } //-------------------------------------------- -void WPN_AltChargeSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_AltChargeSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: altChargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: altChargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altChargeSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altChargeSnd, tokenStr, len); } //-------------------------------------------- -void WPN_SelectSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_SelectSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString( holdBuf,&tokenStr )) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ); + len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: selectSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: selectSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz( weaponData[wpnParms.weaponNum].selectSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].selectSnd, tokenStr, len); } //-------------------------------------------- -void WPN_FireTime(const char **holdBuf) -{ - int tokenInt; +void WPN_FireTime(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Firetime in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Firetime in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].fireTime = tokenInt; } //-------------------------------------------- -void WPN_Range(const char **holdBuf) -{ - int tokenInt; +void WPN_Range(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Range in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Range in external weapon data '%d'\n", tokenInt); return; } @@ -814,57 +766,51 @@ void WPN_Range(const char **holdBuf) } //-------------------------------------------- -void WPN_EnergyPerShot(const char **holdBuf) -{ - int tokenInt; +void WPN_EnergyPerShot(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 1000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad EnergyPerShot in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad EnergyPerShot in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].energyPerShot = tokenInt; } //-------------------------------------------- -void WPN_AltFireTime(const char **holdBuf) -{ - int tokenInt; +void WPN_AltFireTime(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altFireTime in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad altFireTime in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].altFireTime = tokenInt; } //-------------------------------------------- -void WPN_AltRange(const char **holdBuf) -{ - int tokenInt; +void WPN_AltRange(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad AltRange in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad AltRange in external weapon data '%d'\n", tokenInt); return; } @@ -872,148 +818,128 @@ void WPN_AltRange(const char **holdBuf) } //-------------------------------------------- -void WPN_AltEnergyPerShot(const char **holdBuf) -{ - int tokenInt; +void WPN_AltEnergyPerShot(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 1000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad AltEnergyPerShot in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad AltEnergyPerShot in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].altEnergyPerShot = tokenInt; } //-------------------------------------------- -void WPN_Ammo(const char **holdBuf) -{ - const char *tokenStr; +void WPN_Ammo(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if (!Q_stricmp(tokenStr,"AMMO_NONE")) + if (!Q_stricmp(tokenStr, "AMMO_NONE")) wpnParms.ammoNum = AMMO_NONE; - else if (!Q_stricmp(tokenStr,"AMMO_FORCE")) + else if (!Q_stricmp(tokenStr, "AMMO_FORCE")) wpnParms.ammoNum = AMMO_FORCE; - else if (!Q_stricmp(tokenStr,"AMMO_BLASTER")) + else if (!Q_stricmp(tokenStr, "AMMO_BLASTER")) wpnParms.ammoNum = AMMO_BLASTER; - else if (!Q_stricmp(tokenStr,"AMMO_POWERCELL")) + else if (!Q_stricmp(tokenStr, "AMMO_POWERCELL")) wpnParms.ammoNum = AMMO_POWERCELL; - else if (!Q_stricmp(tokenStr,"AMMO_METAL_BOLTS")) + else if (!Q_stricmp(tokenStr, "AMMO_METAL_BOLTS")) wpnParms.ammoNum = AMMO_METAL_BOLTS; - else if (!Q_stricmp(tokenStr,"AMMO_ROCKETS")) + else if (!Q_stricmp(tokenStr, "AMMO_ROCKETS")) wpnParms.ammoNum = AMMO_ROCKETS; - else if (!Q_stricmp(tokenStr,"AMMO_EMPLACED")) + else if (!Q_stricmp(tokenStr, "AMMO_EMPLACED")) wpnParms.ammoNum = AMMO_EMPLACED; - else if (!Q_stricmp(tokenStr,"AMMO_THERMAL")) + else if (!Q_stricmp(tokenStr, "AMMO_THERMAL")) wpnParms.ammoNum = AMMO_THERMAL; - else if (!Q_stricmp(tokenStr,"AMMO_TRIPMINE")) + else if (!Q_stricmp(tokenStr, "AMMO_TRIPMINE")) wpnParms.ammoNum = AMMO_TRIPMINE; - else if (!Q_stricmp(tokenStr,"AMMO_DETPACK")) + else if (!Q_stricmp(tokenStr, "AMMO_DETPACK")) wpnParms.ammoNum = AMMO_DETPACK; - else - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad ammotype in external weapon data '%s'\n", tokenStr); + else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad ammotype in external weapon data '%s'\n", tokenStr); wpnParms.ammoNum = 0; } } //-------------------------------------------- -void WPN_AmmoIcon(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_AmmoIcon(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: ammoicon too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: ammoicon too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(ammoData[wpnParms.ammoNum].icon,tokenStr,len); - + Q_strncpyz(ammoData[wpnParms.ammoNum].icon, tokenStr, len); } //-------------------------------------------- -void WPN_AmmoMax(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoMax(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammo Max in external weapon data '%d'\n", tokenInt); + if ((tokenInt < 0) || (tokenInt > 1000)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammo Max in external weapon data '%d'\n", tokenInt); return; } ammoData[wpnParms.ammoNum].max = tokenInt; } //-------------------------------------------- -void WPN_BarrelCount(const char **holdBuf) -{ - int tokenInt; +void WPN_BarrelCount(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 4 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Range in external weapon data '%d'\n", tokenInt); + if ((tokenInt < 0) || (tokenInt > 4)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Range in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].numBarrels = tokenInt; } - //-------------------------------------------- -static void WP_ParseWeaponParms(const char **holdBuf) -{ - const char *token; - size_t i; +static void WP_ParseWeaponParms(const char **holdBuf) { + const char *token; + size_t i; - while (holdBuf) - { - token = COM_ParseExt( holdBuf, qtrue ); + while (holdBuf) { + token = COM_ParseExt(holdBuf, qtrue); - if (!Q_stricmp( token, "}" )) // End of data for this weapon + if (!Q_stricmp(token, "}")) // End of data for this weapon break; // Loop through possible parameters - for (i=0;i 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileMdl,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].missileMdl, tokenStr, len); } //-------------------------------------------- -void WPN_AltMissileName(const char **holdBuf) -{ +void WPN_AltMissileName(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileMdl,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileMdl, tokenStr, len); } - //-------------------------------------------- -void WPN_MissileHitSound(const char **holdBuf) -{ +void WPN_MissileHitSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileHitSound,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].missileHitSound, tokenStr, len); } //-------------------------------------------- -void WPN_AltMissileHitSound(const char **holdBuf) -{ +void WPN_AltMissileHitSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altmissileHitSound,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altmissileHitSound, tokenStr, len); } //-------------------------------------------- -void WPN_MissileSound(const char **holdBuf) -{ +void WPN_MissileSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileSound,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].missileSound, tokenStr, len); } - //-------------------------------------------- -void WPN_AltMissileSound(const char **holdBuf) -{ +void WPN_AltMissileSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileSound,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileSound, tokenStr, len); } //-------------------------------------------- -void WPN_MissileLightColor(const char **holdBuf) -{ +void WPN_MissileLightColor(const char **holdBuf) { int i; - float tokenFlt; + float tokenFlt; - for (i=0;i<3;++i) - { - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); continue; } - if ((tokenFlt < 0) || (tokenFlt > 1 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad missilelightcolor in external weapon data '%f'\n", tokenFlt); + if ((tokenFlt < 0) || (tokenFlt > 1)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad missilelightcolor in external weapon data '%f'\n", tokenFlt); continue; } weaponData[wpnParms.weaponNum].missileDlightColor[i] = tokenFlt; } - } //-------------------------------------------- -void WPN_AltMissileLightColor(const char **holdBuf) -{ +void WPN_AltMissileLightColor(const char **holdBuf) { int i; - float tokenFlt; + float tokenFlt; - for (i=0;i<3;++i) - { - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); continue; } - if ((tokenFlt < 0) || (tokenFlt > 1 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altmissilelightcolor in external weapon data '%f'\n", tokenFlt); + if ((tokenFlt < 0) || (tokenFlt > 1)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad altmissilelightcolor in external weapon data '%f'\n", tokenFlt); continue; } weaponData[wpnParms.weaponNum].alt_missileDlightColor[i] = tokenFlt; } - } - //-------------------------------------------- -void WPN_MissileLight(const char **holdBuf) -{ - float tokenFlt; +void WPN_MissileLight(const char **holdBuf) { + float tokenFlt; - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); } - if ((tokenFlt < 0) || (tokenFlt > 255 )) // FIXME :What are the right values? + if ((tokenFlt < 0) || (tokenFlt > 255)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad missilelight in external weapon data '%f'\n", tokenFlt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad missilelight in external weapon data '%f'\n", tokenFlt); } weaponData[wpnParms.weaponNum].missileDlight = tokenFlt; } //-------------------------------------------- -void WPN_AltMissileLight(const char **holdBuf) -{ - float tokenFlt; +void WPN_AltMissileLight(const char **holdBuf) { + float tokenFlt; - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); } - if ((tokenFlt < 0) || (tokenFlt > 255 )) // FIXME :What are the right values? + if ((tokenFlt < 0) || (tokenFlt > 255)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altmissilelight in external weapon data '%f'\n", tokenFlt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad altmissilelight in external weapon data '%f'\n", tokenFlt); } weaponData[wpnParms.weaponNum].alt_missileDlight = tokenFlt; } - //-------------------------------------------- -void WPN_FuncName(const char **holdBuf) -{ - const char *tokenStr; +void WPN_FuncName(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: FuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: FuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); } - for ( func_t* s=funcs ; s->name ; s++ ) { - if ( !Q_stricmp(s->name, tokenStr) ) { + for (func_t *s = funcs; s->name; s++) { + if (!Q_stricmp(s->name, tokenStr)) { // found it - weaponData[wpnParms.weaponNum].func = (void*)s->func; + weaponData[wpnParms.weaponNum].func = (void *)s->func; return; } } - gi.Printf(S_COLOR_YELLOW"WARNING: FuncName '%s' in external WEAPONS.DAT does not exist\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: FuncName '%s' in external WEAPONS.DAT does not exist\n", tokenStr); } - //-------------------------------------------- -void WPN_AltFuncName(const char **holdBuf) -{ - const char *tokenStr; +void WPN_AltFuncName(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltFuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltFuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); } - for ( func_t* s=funcs ; s->name ; s++ ) { - if ( !Q_stricmp(s->name, tokenStr) ) { + for (func_t *s = funcs; s->name; s++) { + if (!Q_stricmp(s->name, tokenStr)) { // found it - weaponData[wpnParms.weaponNum].altfunc = (void*)s->func; + weaponData[wpnParms.weaponNum].altfunc = (void *)s->func; return; } } - gi.Printf(S_COLOR_YELLOW"WARNING: AltFuncName %s in external WEAPONS.DAT does not exist\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltFuncName %s in external WEAPONS.DAT does not exist\n", tokenStr); } //-------------------------------------------- -void WPN_MuzzleEffect(const char **holdBuf) -{ - const char *tokenStr; +void WPN_MuzzleEffect(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - size_t len = strlen( tokenStr ); + size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); } - G_EffectIndex( tokenStr ); - Q_strncpyz(weaponData[wpnParms.weaponNum].mMuzzleEffect,tokenStr,len); + G_EffectIndex(tokenStr); + Q_strncpyz(weaponData[wpnParms.weaponNum].mMuzzleEffect, tokenStr, len); } //-------------------------------------------- -void WPN_AltMuzzleEffect(const char **holdBuf) -{ - const char *tokenStr; +void WPN_AltMuzzleEffect(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - size_t len = strlen( tokenStr ); + size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); } - G_EffectIndex( tokenStr ); - Q_strncpyz(weaponData[wpnParms.weaponNum].mAltMuzzleEffect,tokenStr,len); + G_EffectIndex(tokenStr); + Q_strncpyz(weaponData[wpnParms.weaponNum].mAltMuzzleEffect, tokenStr, len); } //-------------------------------------------- -void WPN_Damage(const char **holdBuf) -{ - int tokenInt; +void WPN_Damage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1361,12 +1232,10 @@ void WPN_Damage(const char **holdBuf) //-------------------------------------------- -void WPN_AltDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_AltDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1376,12 +1245,10 @@ void WPN_AltDamage(const char **holdBuf) //-------------------------------------------- -void WPN_SplashDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_SplashDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1391,12 +1258,10 @@ void WPN_SplashDamage(const char **holdBuf) //-------------------------------------------- -void WPN_SplashRadius(const char **holdBuf) -{ - float tokenFlt; +void WPN_SplashRadius(const char **holdBuf) { + float tokenFlt; - if( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); return; } @@ -1406,12 +1271,10 @@ void WPN_SplashRadius(const char **holdBuf) //-------------------------------------------- -void WPN_AltSplashDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_AltSplashDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1421,12 +1284,10 @@ void WPN_AltSplashDamage(const char **holdBuf) //-------------------------------------------- -void WPN_AltSplashRadius(const char **holdBuf) -{ - float tokenFlt; +void WPN_AltSplashRadius(const char **holdBuf) { + float tokenFlt; - if( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); return; } @@ -1435,48 +1296,40 @@ void WPN_AltSplashRadius(const char **holdBuf) } //-------------------------------------------- -static void WP_ParseParms(const char *buffer) -{ - const char *holdBuf; - const char *token; +static void WP_ParseParms(const char *buffer) { + const char *holdBuf; + const char *token; holdBuf = buffer; COM_BeginParseSession(); - while ( holdBuf ) - { - token = COM_ParseExt( &holdBuf, qtrue ); + while (holdBuf) { + token = COM_ParseExt(&holdBuf, qtrue); - if ( !Q_stricmp( token, "{" ) ) - { + if (!Q_stricmp(token, "{")) { WP_ParseWeaponParms(&holdBuf); } - } - COM_EndParseSession( ); - + COM_EndParseSession(); } //-------------------------------------------- -void WP_LoadWeaponParms (void) -{ +void WP_LoadWeaponParms(void) { char *buffer; int len; - len = gi.FS_ReadFile("ext_data/weapons.dat",(void **) &buffer); + len = gi.FS_ReadFile("ext_data/weapons.dat", (void **)&buffer); - if (len == -1) - { - Com_Error(ERR_FATAL,"Cannot find ext_data/weapons.dat!\n"); + if (len == -1) { + Com_Error(ERR_FATAL, "Cannot find ext_data/weapons.dat!\n"); } // initialise the data area memset(weaponData, 0, sizeof(weaponData)); // put in the default values, because backwards compatibility is awesome! - for(int i = 0; i < WP_NUM_WEAPONS; i++) - { + for (int i = 0; i < WP_NUM_WEAPONS; i++) { weaponData[i].damage = defaultDamage[i]; weaponData[i].altDamage = defaultAltDamage[i]; weaponData[i].splashDamage = defaultSplashDamage[i]; @@ -1487,5 +1340,5 @@ void WP_LoadWeaponParms (void) WP_ParseParms(buffer); - gi.FS_FreeFile( buffer ); //let go of the buffer + gi.FS_FreeFile(buffer); // let go of the buffer } diff --git a/code/game/genericparser2.cpp b/code/game/genericparser2.cpp index ad825ce1a8..c7b6119d40 100644 --- a/code/game/genericparser2.cpp +++ b/code/game/genericparser2.cpp @@ -32,53 +32,42 @@ along with this program; if not, see . #include #include - -static void skipWhitespace( gsl::cstring_span& text, const bool allowLineBreaks ) -{ +static void skipWhitespace(gsl::cstring_span &text, const bool allowLineBreaks) { gsl::cstring_span::iterator whitespaceEnd = text.begin(); - while( whitespaceEnd != text.end() // No EOF - && std::isspace( *whitespaceEnd ) // No End of Whitespace - && ( allowLineBreaks || *whitespaceEnd != '\n' ) ) // No unwanted newline + while (whitespaceEnd != text.end() // No EOF + && std::isspace(*whitespaceEnd) // No End of Whitespace + && (allowLineBreaks || *whitespaceEnd != '\n')) // No unwanted newline { ++whitespaceEnd; } - text = { whitespaceEnd, text.end() }; + text = {whitespaceEnd, text.end()}; } -static void skipWhitespaceAndComments( gsl::cstring_span& text, const bool allowLineBreaks ) -{ - skipWhitespace( text, allowLineBreaks ); +static void skipWhitespaceAndComments(gsl::cstring_span &text, const bool allowLineBreaks) { + skipWhitespace(text, allowLineBreaks); // skip single line comment - if( text.size() >= 2 && text[ 0 ] == '/' && text[ 1 ] == '/' ) - { - auto commentEnd = std::find( text.begin() + 2, text.end(), '\n' ); - if( commentEnd == text.end() ) - { - text = { text.end(), text.end() }; + if (text.size() >= 2 && text[0] == '/' && text[1] == '/') { + auto commentEnd = std::find(text.begin() + 2, text.end(), '\n'); + if (commentEnd == text.end()) { + text = {text.end(), text.end()}; return; - } - else - { - text = { commentEnd, text.end() }; - skipWhitespaceAndComments( text, allowLineBreaks ); + } else { + text = {commentEnd, text.end()}; + skipWhitespaceAndComments(text, allowLineBreaks); return; } } // skip multi line comments - if( text.size() >= 2 && text[ 0 ] == '/' && text[ 1 ] == '*' ) - { - static const std::array< char, 2 > endStr{ '*', '/' }; - auto commentEnd = std::search( text.begin(), text.end(), endStr.begin(), endStr.end() ); - if( commentEnd == text.end() ) - { - text = { text.end(), text.end() }; + if (text.size() >= 2 && text[0] == '/' && text[1] == '*') { + static const std::array endStr{'*', '/'}; + auto commentEnd = std::search(text.begin(), text.end(), endStr.begin(), endStr.end()); + if (commentEnd == text.end()) { + text = {text.end(), text.end()}; return; - } - else - { - text = { commentEnd + endStr.size(), text.end() }; - skipWhitespace( text, allowLineBreaks ); + } else { + text = {commentEnd + endStr.size(), text.end()}; + skipWhitespace(text, allowLineBreaks); return; } } @@ -87,15 +76,10 @@ static void skipWhitespaceAndComments( gsl::cstring_span& text, const bool allow return; } -static gsl::cstring_span removeTrailingWhitespace( const gsl::cstring_span& text ) -{ - return{ - text.begin(), - std::find_if_not( - std::reverse_iterator< const char *>( text.end() ), std::reverse_iterator< const char* >( text.begin() ), - static_cast< int( *)( int ) >( std::isspace ) - ).base() - }; +static gsl::cstring_span removeTrailingWhitespace(const gsl::cstring_span &text) { + return {text.begin(), std::find_if_not(std::reverse_iterator(text.end()), std::reverse_iterator(text.begin()), + static_cast(std::isspace)) + .base()}; } /** @@ -106,130 +90,71 @@ A token can be: - EOL- or comment-delimited (if readToEOL == true); i.e. reads to end of line or the first // or /* @param text adjusted to start beyond the read token */ -static gsl::cstring_span GetToken( gsl::cstring_span& text, bool allowLineBreaks, bool readToEOL = false ) -{ - skipWhitespaceAndComments( text, allowLineBreaks ); +static gsl::cstring_span GetToken(gsl::cstring_span &text, bool allowLineBreaks, bool readToEOL = false) { + skipWhitespaceAndComments(text, allowLineBreaks); // EOF - if( text.empty() ) - { - return{}; + if (text.empty()) { + return {}; } // string. ignores readToEOL. - if( text[ 0 ] == '"' ) - { + if (text[0] == '"') { // there are no escapes, string just ends at the next " - auto tokenEnd = std::find( text.begin() + 1, text.end(), '"' ); - if( tokenEnd == text.end() ) - { - gsl::cstring_span token = { text.begin() + 1, text.end() }; - text = { text.end(), text.end() }; + auto tokenEnd = std::find(text.begin() + 1, text.end(), '"'); + if (tokenEnd == text.end()) { + gsl::cstring_span token = {text.begin() + 1, text.end()}; + text = {text.end(), text.end()}; return token; - } - else - { - gsl::cstring_span token = { text.begin() + 1, tokenEnd }; - text = { tokenEnd + 1, text.end() }; + } else { + gsl::cstring_span token = {text.begin() + 1, tokenEnd}; + text = {tokenEnd + 1, text.end()}; return token; } - } - else if( readToEOL ) - { + } else if (readToEOL) { // find the first of '\n', "//" or "/*"; that's end of token - auto tokenEnd = std::find( text.begin(), text.end(), '\n' ); - static const std::array< char, 2 > commentPatterns[]{ - { { '/', '*' } }, - { { '/', '/' } } - }; - for( auto& pattern : commentPatterns ) - { - tokenEnd = std::min( - tokenEnd, - std::search( - text.begin(), tokenEnd, - pattern.begin(), pattern.end() - ) - ); + auto tokenEnd = std::find(text.begin(), text.end(), '\n'); + static const std::array commentPatterns[]{{{'/', '*'}}, {{'/', '/'}}}; + for (auto &pattern : commentPatterns) { + tokenEnd = std::min(tokenEnd, std::search(text.begin(), tokenEnd, pattern.begin(), pattern.end())); } - gsl::cstring_span token{ text.begin(), tokenEnd }; - text = { tokenEnd, text.end() }; - return removeTrailingWhitespace( token ); - } - else - { + gsl::cstring_span token{text.begin(), tokenEnd}; + text = {tokenEnd, text.end()}; + return removeTrailingWhitespace(token); + } else { // consume until first whitespace (if allowLineBreaks == false, that may be text.begin(); in that case token is empty.) - auto tokenEnd = std::find_if( text.begin(), text.end(), static_cast< int( *)( int ) >( std::isspace ) ); - gsl::cstring_span token{ text.begin(), tokenEnd }; - text = { tokenEnd, text.end() }; + auto tokenEnd = std::find_if(text.begin(), text.end(), static_cast(std::isspace)); + gsl::cstring_span token{text.begin(), tokenEnd}; + text = {tokenEnd, text.end()}; return token; } } - - - - -CGPProperty::CGPProperty( gsl::cstring_span initKey, gsl::cstring_span initValue ) - : mKey( initKey ) -{ - if( !initValue.empty() ) - { - mValues.push_back( initValue ); +CGPProperty::CGPProperty(gsl::cstring_span initKey, gsl::cstring_span initValue) : mKey(initKey) { + if (!initValue.empty()) { + mValues.push_back(initValue); } } -void CGPProperty::AddValue( gsl::cstring_span newValue ) -{ - mValues.push_back( newValue ); -} - - - - - - - - - - - +void CGPProperty::AddValue(gsl::cstring_span newValue) { mValues.push_back(newValue); } +CGPGroup::CGPGroup(const gsl::cstring_span &initName) : mName(initName) {} +bool CGPGroup::Parse(gsl::cstring_span &data, const bool topLevel) { + while (true) { + gsl::cstring_span token = GetToken(data, true); - - -CGPGroup::CGPGroup( const gsl::cstring_span& initName ) - : mName( initName ) -{ -} - -bool CGPGroup::Parse( gsl::cstring_span& data, const bool topLevel ) -{ - while( true ) - { - gsl::cstring_span token = GetToken( data, true ); - - if( token.empty() ) - { - if ( topLevel ) - { + if (token.empty()) { + if (topLevel) { // top level parse; there was no opening "{", so there should be no closing one either. return true; - } - else - { + } else { // end of data - error! return false; } - } - else if( token == CSTRING_VIEW( "}" ) ) - { - if( topLevel ) - { + } else if (token == CSTRING_VIEW("}")) { + if (topLevel) { // top-level group; there was no opening "{" so there should be no closing one, either. return false; - } - else - { + } else { // ending brace for this group return true; } @@ -237,74 +162,44 @@ bool CGPGroup::Parse( gsl::cstring_span& data, const bool topLevel ) gsl::cstring_span lastToken = token; // read ahead to see what we are doing - token = GetToken( data, true, true ); - if( token == CSTRING_VIEW( "{" ) ) - { + token = GetToken(data, true, true); + if (token == CSTRING_VIEW("{")) { // new sub group - mSubGroups.emplace_back( lastToken ); - if( !mSubGroups.back().Parse( data, false ) ) - { + mSubGroups.emplace_back(lastToken); + if (!mSubGroups.back().Parse(data, false)) { return false; } - } - else if( token == CSTRING_VIEW( "[" ) ) - { + } else if (token == CSTRING_VIEW("[")) { // new list - mProperties.emplace_back( lastToken ); - CGPProperty& list = mProperties.back(); - while( true ) - { - token = GetToken( data, true, true ); - if( token.empty() ) - { + mProperties.emplace_back(lastToken); + CGPProperty &list = mProperties.back(); + while (true) { + token = GetToken(data, true, true); + if (token.empty()) { return false; } - if( token == CSTRING_VIEW( "]" ) ) - { + if (token == CSTRING_VIEW("]")) { break; } - list.AddValue( token ); + list.AddValue(token); } - } - else - { + } else { // new value - mProperties.emplace_back( lastToken, token ); + mProperties.emplace_back(lastToken, token); } } } - - - - - - - - - - - - - -bool CGenericParser2::Parse( gsl::czstring filename ) -{ +bool CGenericParser2::Parse(gsl::czstring filename) { Clear(); - mFileContent = FS::ReadFile( filename ); - if( !mFileContent.valid() ) - { + mFileContent = FS::ReadFile(filename); + if (!mFileContent.valid()) { return false; } auto view = mFileContent.view(); - return mTopLevel.Parse( view ); + return mTopLevel.Parse(view); } -void CGenericParser2::Clear() NOEXCEPT -{ - mTopLevel.Clear(); -} - - +void CGenericParser2::Clear() NOEXCEPT { mTopLevel.Clear(); } //////////////////// eof ///////////////////// - diff --git a/code/game/wp_atst.cpp b/code/game/wp_atst.cpp index 2ec17bbbe4..debdd92722 100644 --- a/code/game/wp_atst.cpp +++ b/code/game/wp_atst.cpp @@ -27,55 +27,52 @@ along with this program; if not, see . // ATST Main //--------------------------------------------------------- -void WP_ATSTMainFire( gentity_t *ent ) +void WP_ATSTMainFire(gentity_t *ent) //--------------------------------------------------------- { float vel = ATST_MAIN_VEL; -// if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) -// { -// vel = 4500.0f; -// } + // if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) + // { + // vel = 4500.0f; + // } - if ( !ent->s.number ) - { + if (!ent->s.number) { // player shoots faster vel *= 1.6f; } WP_MissileTargetHint(ent, muzzle, forwardVec); - gentity_t *missile = CreateMissile( muzzle, forwardVec, vel, 10000, ent ); + gentity_t *missile = CreateMissile(muzzle, forwardVec, vel, 10000, ent); missile->classname = "atst_main_proj"; missile->s.weapon = WP_ATST_MAIN; missile->damage = weaponData[WP_ATST_MAIN].damage; - missile->dflags = DAMAGE_DEATH_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS; + missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->owner = ent; - VectorSet( missile->maxs, ATST_MAIN_SIZE, ATST_MAIN_SIZE, ATST_MAIN_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); - + VectorSet(missile->maxs, ATST_MAIN_SIZE, ATST_MAIN_SIZE, ATST_MAIN_SIZE); + VectorScale(missile->maxs, -1, missile->mins); } // ATST Alt Side //--------------------------------------------------------- -void WP_ATSTSideAltFire( gentity_t *ent ) +void WP_ATSTSideAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_ATST_SIDE].altDamage; - float vel = ATST_SIDE_ALT_NPC_VELOCITY; + int damage = weaponData[WP_ATST_SIDE].altDamage; + float vel = ATST_SIDE_ALT_NPC_VELOCITY; - if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) - { + if (ent->client && (ent->client->ps.eFlags & EF_IN_ATST)) { vel = ATST_SIDE_ALT_VELOCITY; } - gentity_t *missile = CreateMissile( muzzle, forwardVec, vel, 10000, ent, qtrue ); + gentity_t *missile = CreateMissile(muzzle, forwardVec, vel, 10000, ent, qtrue); missile->classname = "atst_rocket"; missile->s.weapon = WP_ATST_SIDE; @@ -83,27 +80,21 @@ void WP_ATSTSideAltFire( gentity_t *ent ) missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_HARD; } } - VectorCopy( forwardVec, missile->movedir ); + VectorCopy(forwardVec, missile->movedir); // Make it easier to hit things - VectorSet( missile->maxs, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; @@ -112,7 +103,7 @@ void WP_ATSTSideAltFire( gentity_t *ent ) missile->clipmask = MASK_SHOT; // Scale damage down a bit if it is coming from an NPC - missile->splashDamage = weaponData[WP_ATST_SIDE].altSplashDamage * ( ent->s.number == 0 ? 1.0f : ATST_SIDE_ALT_ROCKET_SPLASH_SCALE ); + missile->splashDamage = weaponData[WP_ATST_SIDE].altSplashDamage * (ent->s.number == 0 ? 1.0f : ATST_SIDE_ALT_ROCKET_SPLASH_SCALE); missile->splashRadius = weaponData[WP_ATST_SIDE].altSplashRadius; // we don't want it to ever bounce @@ -121,42 +112,36 @@ void WP_ATSTSideAltFire( gentity_t *ent ) // ATST Side //--------------------------------------------------------- -void WP_ATSTSideFire( gentity_t *ent ) +void WP_ATSTSideFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_ATST_SIDE].damage; + int damage = weaponData[WP_ATST_SIDE].damage; - gentity_t *missile = CreateMissile( muzzle, forwardVec, ATST_SIDE_MAIN_VELOCITY, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(muzzle, forwardVec, ATST_SIDE_MAIN_VELOCITY, 10000, ent, qfalse); missile->classname = "atst_side_proj"; missile->s.weapon = WP_ATST_SIDE; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ATST_SIDE_MAIN_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ATST_SIDE_MAIN_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ATST_SIDE_MAIN_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; - missile->dflags = DAMAGE_DEATH_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS; + missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - missile->splashDamage = weaponData[WP_REPEATER].splashDamage * ( ent->s.number == 0 ? 1.0f : 0.6f ); + missile->splashDamage = weaponData[WP_REPEATER].splashDamage * (ent->s.number == 0 ? 1.0f : 0.6f); missile->splashRadius = weaponData[WP_REPEATER].splashRadius; // we don't want it to bounce diff --git a/code/game/wp_blaster_pistol.cpp b/code/game/wp_blaster_pistol.cpp index cede5bbd16..f6c36258f8 100644 --- a/code/game/wp_blaster_pistol.cpp +++ b/code/game/wp_blaster_pistol.cpp @@ -25,71 +25,56 @@ along with this program; if not, see . #include "wp_saber.h" #include "w_local.h" - //--------------- // Bryar Pistol //--------------- //--------------------------------------------------------- -void WP_FireBryarPistol( gentity_t *ent, qboolean alt_fire ) +void WP_FireBryarPistol(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - int damage = !alt_fire ? weaponData[WP_BRYAR_PISTOL].damage : weaponData[WP_BRYAR_PISTOL].altDamage; - - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall - - if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - if ( ent->NPC && ent->NPC->currentAim < 5 ) - { - vec3_t angs; - - vectoangles( forwardVec, angs ); - - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - {//*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - } - else - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); + vec3_t start; + int damage = !alt_fire ? weaponData[WP_BRYAR_PISTOL].damage : weaponData[WP_BRYAR_PISTOL].altDamage; + + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall + + if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + if (ent->NPC && ent->NPC->currentAim < 5) { + vec3_t angs; + + vectoangles(forwardVec, angs); + + if (ent->client->NPC_class == CLASS_IMPWORKER) { //*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + } else { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); } - AngleVectors( angs, forwardVec, NULL, NULL ); + AngleVectors(angs, forwardVec, NULL, NULL); } } WP_MissileTargetHint(ent, start, forwardVec); - gentity_t *missile = CreateMissile( start, forwardVec, BRYAR_PISTOL_VEL, 10000, ent, alt_fire ); + gentity_t *missile = CreateMissile(start, forwardVec, BRYAR_PISTOL_VEL, 10000, ent, alt_fire); missile->classname = "bryar_proj"; - if ( ent->s.weapon == WP_BLASTER_PISTOL - || ent->s.weapon == WP_JAWA ) - {//*SIGH*... I hate our weapon system... + if (ent->s.weapon == WP_BLASTER_PISTOL || ent->s.weapon == WP_JAWA) { //*SIGH*... I hate our weapon system... missile->s.weapon = ent->s.weapon; - } - else - { + } else { missile->s.weapon = WP_BRYAR_PISTOL; } - if ( alt_fire ) - { - int count = ( level.time - ent->client->ps.weaponChargeTime ) / BRYAR_CHARGE_UNIT; + if (alt_fire) { + int count = (level.time - ent->client->ps.weaponChargeTime) / BRYAR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } @@ -97,22 +82,19 @@ void WP_FireBryarPistol( gentity_t *ent, qboolean alt_fire ) missile->count = count; // this will get used in the projectile rendering code to make a beefier effect } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( alt_fire ) - { + if (alt_fire) { missile->methodOfDeath = MOD_BRYAR_ALT; - } - else - { + } else { missile->methodOfDeath = MOD_BRYAR; } @@ -121,8 +103,7 @@ void WP_FireBryarPistol( gentity_t *ent, qboolean alt_fire ) // we don't want it to bounce forever missile->bounceCount = 8; - if ( ent->weaponModel[1] > 0 ) - {//dual pistols, toggle the muzzle point back and forth between the two pistols each time he fires - ent->count = (ent->count)?0:1; + if (ent->weaponModel[1] > 0) { // dual pistols, toggle the muzzle point back and forth between the two pistols each time he fires + ent->count = (ent->count) ? 0 : 1; } } \ No newline at end of file diff --git a/code/game/wp_blaster_rifle.cpp b/code/game/wp_blaster_rifle.cpp index 87545617c9..cab463e28c 100644 --- a/code/game/wp_blaster_rifle.cpp +++ b/code/game/wp_blaster_rifle.cpp @@ -26,83 +26,66 @@ along with this program; if not, see . #include "wp_saber.h" #include "w_local.h" - //--------------- // Blaster //--------------- //--------------------------------------------------------- -void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire ) +void WP_FireBlasterMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire) //--------------------------------------------------------- { - int velocity = BLASTER_VELOCITY; - int damage = altFire ? weaponData[WP_BLASTER].altDamage : weaponData[WP_BLASTER].damage; + int velocity = BLASTER_VELOCITY; + int damage = altFire ? weaponData[WP_BLASTER].altDamage : weaponData[WP_BLASTER].damage; - if ( ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE) { damage *= 3; velocity = ATST_MAIN_VEL + ent->client->ps.speed; - } - else - { + } else { // If an enemy is shooting at us, lower the velocity so you have a chance to evade - if ( ent->client && ent->client->ps.clientNum != 0 && ent->client->NPC_class != CLASS_BOBAFETT ) - { - if ( g_spskill->integer < 2 ) - { + if (ent->client && ent->client->ps.clientNum != 0 && ent->client->NPC_class != CLASS_BOBAFETT) { + if (g_spskill->integer < 2) { velocity *= BLASTER_NPC_VEL_CUT; - } - else - { + } else { velocity *= BLASTER_NPC_HARD_VEL_CUT; } } } - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall WP_MissileTargetHint(ent, start, dir); - gentity_t *missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + gentity_t *missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "blaster_proj"; missile->s.weapon = WP_BLASTER; // Do the damages - if ( ent->s.number != 0 && ent->client->NPC_class != CLASS_BOBAFETT ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0 && ent->client->NPC_class != CLASS_BOBAFETT) { + if (g_spskill->integer == 0) { damage = BLASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BLASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BLASTER_NPC_DAMAGE_HARD; } } -// if ( ent->client ) -// { -// if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } -// } + // if ( ent->client ) + // { + // if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( altFire ) - { + if (altFire) { missile->methodOfDeath = MOD_BLASTER_ALT; - } - else - { + } else { missile->methodOfDeath = MOD_BLASTER; } missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; @@ -112,48 +95,37 @@ void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean a } //--------------------------------------------------------- -void WP_FireBlaster( gentity_t *ent, qboolean alt_fire ) +void WP_FireBlaster(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( forwardVec, angs ); + vectoangles(forwardVec, angs); - if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - {//no inherent aim screw up - } - else if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - if ( alt_fire ) - { + if (ent->client && ent->client->NPC_class == CLASS_VEHICLE) { // no inherent aim screw up + } else if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || + ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + if (alt_fire) { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; - } - else - { + angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; + } else { // Troopers use their aim values as well as the gun's inherent inaccuracy // so check for all classes of stormtroopers and anyone else that has aim error - if ( ent->client && ent->NPC && - ( ent->client->NPC_class == CLASS_STORMTROOPER || - ent->client->NPC_class == CLASS_SWAMPTROOPER ) ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - } - else - { + if (ent->client && ent->NPC && (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER)) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + } else { // add some slop to the main-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; } } } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - WP_FireBlasterMissile( ent, muzzle, dir, alt_fire ); + WP_FireBlasterMissile(ent, muzzle, dir, alt_fire); } \ No newline at end of file diff --git a/code/game/wp_bot_laser.cpp b/code/game/wp_bot_laser.cpp index d37df25cba..e8ac6c9e96 100644 --- a/code/game/wp_bot_laser.cpp +++ b/code/game/wp_bot_laser.cpp @@ -25,10 +25,10 @@ along with this program; if not, see . // Bot Laser //--------------------------------------------------------- -void WP_BotLaser( gentity_t *ent ) +void WP_BotLaser(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *missile = CreateMissile( muzzle, forwardVec, BRYAR_PISTOL_VEL, 10000, ent ); + gentity_t *missile = CreateMissile(muzzle, forwardVec, BRYAR_PISTOL_VEL, 10000, ent); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; diff --git a/code/game/wp_bowcaster.cpp b/code/game/wp_bowcaster.cpp index f0b6680244..dac993029c 100644 --- a/code/game/wp_bowcaster.cpp +++ b/code/game/wp_bowcaster.cpp @@ -31,93 +31,80 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_BowcasterMainFire( gentity_t *ent ) +static void WP_BowcasterMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_BOWCASTER].damage, count; - float vel; - vec3_t angs, dir, start; - gentity_t *missile; + int damage = weaponData[WP_BOWCASTER].damage, count; + float vel; + vec3_t angs, dir, start; + gentity_t *missile; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = BOWCASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BOWCASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BOWCASTER_NPC_DAMAGE_HARD; } } - count = ( level.time - ent->client->ps.weaponChargeTime ) / BOWCASTER_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / BOWCASTER_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if ( !(count & 1 )) - { + if (!(count & 1)) { // if we aren't odd, knock us down a level count--; } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } WP_MissileTargetHint(ent, start, forwardVec); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { // create a range of different velocities - vel = BOWCASTER_VELOCITY * ( Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f ); + vel = BOWCASTER_VELOCITY * (Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f); - vectoangles( forwardVec, angs ); + vectoangles(forwardVec, angs); - if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - // add some slop to the fire direction + if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || + ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + // add some slop to the fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BOWCASTER_ALT_SPREAD * 0.2f; - angs[YAW] += ((i+0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD ); - if ( ent->NPC ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); + angs[YAW] += ((i + 0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD); + if (ent->NPC) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); } } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); - missile = CreateMissile( start, dir, vel, 10000, ent ); + missile = CreateMissile(start, dir, vel, 10000, ent); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// missile->flags |= FL_OVERCHARGED; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // missile->flags |= FL_OVERCHARGED; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -133,48 +120,42 @@ static void WP_BowcasterMainFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_BowcasterAltFire( gentity_t *ent ) +static void WP_BowcasterAltFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_BOWCASTER].altDamage; + vec3_t start; + int damage = weaponData[WP_BOWCASTER].altDamage; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall WP_MissileTargetHint(ent, start, forwardVec); - gentity_t *missile = CreateMissile( start, forwardVec, BOWCASTER_VELOCITY, 10000, ent, qtrue ); + gentity_t *missile = CreateMissile(start, forwardVec, BOWCASTER_VELOCITY, 10000, ent, qtrue); missile->classname = "bowcaster_alt_proj"; missile->s.weapon = WP_BOWCASTER; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = BOWCASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BOWCASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BOWCASTER_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->s.eFlags |= EF_BOUNCE; missile->bounceCount = 3; @@ -188,15 +169,12 @@ static void WP_BowcasterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireBowcaster( gentity_t *ent, qboolean alt_fire ) +void WP_FireBowcaster(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_BowcasterAltFire( ent ); - } - else - { - WP_BowcasterMainFire( ent ); + if (alt_fire) { + WP_BowcasterAltFire(ent); + } else { + WP_BowcasterMainFire(ent); } } \ No newline at end of file diff --git a/code/game/wp_concussion.cpp b/code/game/wp_concussion.cpp index eb200888d0..b089a99e01 100644 --- a/code/game/wp_concussion.cpp +++ b/code/game/wp_concussion.cpp @@ -27,48 +27,41 @@ along with this program; if not, see . #include "w_local.h" #include "../cgame/cg_local.h" -static void WP_FireConcussionAlt( gentity_t *ent ) -{//a rail-gun-like beam - int damage = weaponData[WP_CONCUSSION].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; - qboolean render_impact = qtrue; - vec3_t start, end; - vec3_t muzzle2, spot, dir; - trace_t tr; - gentity_t *traceEnt, *tent; - float dist, shotDist, shotRange = 8192; - qboolean hitDodged = qfalse; - - if (ent->s.number >= MAX_CLIENTS) - { +static void WP_FireConcussionAlt(gentity_t *ent) { // a rail-gun-like beam + int damage = weaponData[WP_CONCUSSION].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; + qboolean render_impact = qtrue; + vec3_t start, end; + vec3_t muzzle2, spot, dir; + trace_t tr; + gentity_t *traceEnt, *tent; + float dist, shotDist, shotRange = 8192; + qboolean hitDodged = qfalse; + + if (ent->s.number >= MAX_CLIENTS) { vec3_t angles; vectoangles(forwardVec, angles); - angles[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angles[YAW] += ( Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f + angles[PITCH] += (Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angles[YAW] += (Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f AngleVectors(angles, forwardVec, vrightVec, up); } - //Shove us backwards for half a second - VectorMA( ent->client->ps.velocity, -200, forwardVec, ent->client->ps.velocity ); + // Shove us backwards for half a second + VectorMA(ent->client->ps.velocity, -200, forwardVec, ent->client->ps.velocity); ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( (ent->client->ps.pm_flags&PMF_DUCKED) ) - {//hunkered down + if ((ent->client->ps.pm_flags & PMF_DUCKED)) { // hunkered down ent->client->ps.pm_time = 100; - } - else - { + } else { ent->client->ps.pm_time = 250; } - ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK|PMF_TIME_NOFRICTION; - //FIXME: only if on ground? So no "rocket jump"? Or: (see next FIXME) - //FIXME: instead, set a forced ucmd backmove instead of this sliding + ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK | PMF_TIME_NOFRICTION; + // FIXME: only if on ground? So no "rocket jump"? Or: (see next FIXME) + // FIXME: instead, set a forced ucmd backmove instead of this sliding - VectorCopy( muzzle, muzzle2 ); // making a backup copy + VectorCopy(muzzle, muzzle2); // making a backup copy // The trace start will originate at the eye so we can ensure that it hits the crosshair. - if ( ent->NPC ) - { - switch ( g_spskill->integer ) - { + if (ent->NPC) { + switch (g_spskill->integer) { case 0: damage = CONC_ALT_NPC_DAMAGE_EASY; break; @@ -81,230 +74,203 @@ static void WP_FireConcussionAlt( gentity_t *ent ) break; } } - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); skip = ent->s.number; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - //Make it a little easier to hit guys at long range + // Make it a little easier to hit guys at long range vec3_t shot_mins, shot_maxs; - VectorSet( shot_mins, -1, -1, -1 ); - VectorSet( shot_maxs, 1, 1, 1 ); + VectorSet(shot_mins, -1, -1, -1); + VectorSet(shot_maxs, 1, 1, 1); - for ( int i = 0; i < traces; i++ ) - { - VectorMA( start, shotRange, forwardVec, end ); + for (int i = 0; i < traces; i++) { + VectorMA(start, shotRange, forwardVec, end); - //NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" - //alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter - //gi.trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); - gi.trace( &tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); + // NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" + // alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter + // gi.trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); + gi.trace(&tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, G2_COLLIDE, 10); // G2_RETURNONHIT, 0 ); - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } - if ( tr.entityNum == ent->s.number ) - { + if (tr.entityNum == ent->s.number) { // should never happen, but basically we don't want to consider a hit to ourselves? // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; #ifdef _DEBUG - gi.Printf( "BAD! Concussion gun shot somehow traced back and hit the owner!\n" ); + gi.Printf("BAD! Concussion gun shot somehow traced back and hit the owner!\n"); #endif continue; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - //NOTE: let's just draw one beam at the end - //tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); - //tent->svFlags |= SVF_BROADCAST; + // NOTE: let's just draw one beam at the end + // tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); + // tent->svFlags |= SVF_BROADCAST; - //VectorCopy( muzzle2, tent->s.origin2 ); + // VectorCopy( muzzle2, tent->s.origin2 ); - if ( tr.fraction >= 1.0f ) - { + if (tr.fraction >= 1.0f) { // draw the beam but don't do anything else break; } traceEnt = &g_entities[tr.entityNum]; - if ( traceEnt //&& traceEnt->NPC - && ( traceEnt->s.weapon == WP_SABER || (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT||traceEnt->client->NPC_class == CLASS_REBORN) ) ) ) - {//FIXME: need a more reliable way to know we hit a jedi? - hitDodged = Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ); - //acts like we didn't even hit him + if (traceEnt //&& traceEnt->NPC + && (traceEnt->s.weapon == WP_SABER || + (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT || + traceEnt->client->NPC_class == CLASS_REBORN)))) { // FIXME: need a more reliable way to know we hit a jedi? + hitDodged = Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE); + // acts like we didn't even hit him } - if ( !hitDodged ) - { - if ( render_impact ) - { - if (( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - || !Q_stricmp( traceEnt->classname, "misc_model_breakable" ) - || traceEnt->s.eType == ET_MOVER ) - { + if (!hitDodged) { + if (render_impact) { + if ((tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) || !Q_stricmp(traceEnt->classname, "misc_model_breakable") || + traceEnt->s.eType == ET_MOVER) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "concussion/alt_hit" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("concussion/alt_hit"), tr.endpos, tr.plane.normal); - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - {//NOTE: hitting multiple ents can still get you over 100% accuracy + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { // NOTE: hitting multiple ents can still get you over 100% accuracy ent->client->ps.persistant[PERS_ACCURACY_HITS]++; } - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_CONC_ALT ); - qboolean noKnockBack = (qboolean)((traceEnt->flags&FL_NO_KNOCKBACK) != 0);//will be set if they die, I want to know if it was on *before* they died - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, 10, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_CONC_ALT, hitLoc ); + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_CONC_ALT); + qboolean noKnockBack = + (qboolean)((traceEnt->flags & FL_NO_KNOCKBACK) != 0); // will be set if they die, I want to know if it was on *before* they died + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, 10, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_CONC_ALT, hitLoc); break; } - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_CONC_ALT, hitLoc ); + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_CONC_ALT, hitLoc); - //do knockback and knockdown manually - if ( traceEnt->client ) - {//only if we hit a client + // do knockback and knockdown manually + if (traceEnt->client) { // only if we hit a client vec3_t pushDir; - VectorCopy( forwardVec, pushDir ); - if ( pushDir[2] < 0.2f ) - { + VectorCopy(forwardVec, pushDir); + if (pushDir[2] < 0.2f) { pushDir[2] = 0.2f; - }//hmm, re-normalize? nah... - //if ( traceEnt->NPC || Q_irand(0,g_spskill->integer+1) ) + } // hmm, re-normalize? nah... + // if ( traceEnt->NPC || Q_irand(0,g_spskill->integer+1) ) { - if ( !noKnockBack ) - {//knock-backable - G_Throw( traceEnt, pushDir, 200 ); - if ( traceEnt->client->NPC_class == CLASS_ROCKETTROOPER ) - { - traceEnt->client->ps.pm_time = Q_irand( 1500, 3000 ); + if (!noKnockBack) { // knock-backable + G_Throw(traceEnt, pushDir, 200); + if (traceEnt->client->NPC_class == CLASS_ROCKETTROOPER) { + traceEnt->client->ps.pm_time = Q_irand(1500, 3000); } } - if ( traceEnt->health > 0 ) - {//alive - if ( G_HasKnockdownAnims( traceEnt ) ) - {//knock-downable - G_Knockdown( traceEnt, ent, pushDir, 400, qtrue ); + if (traceEnt->health > 0) { // alive + if (G_HasKnockdownAnims(traceEnt)) { // knock-downable + G_Knockdown(traceEnt, ent, pushDir, 400, qtrue); } } } } - if ( traceEnt->s.eType == ET_MOVER ) - {//stop the traces on any mover + if (traceEnt->s.eType == ET_MOVER) { // stop the traces on any mover break; } - } - else - { - // we only make this mark on things that can't break or move - tent = G_TempEntity( tr.endpos, EV_CONC_ALT_MISS ); + } else { + // we only make this mark on things that can't break or move + tent = G_TempEntity(tr.endpos, EV_CONC_ALT_MISS); tent->svFlags |= SVF_BROADCAST; - VectorCopy( tr.plane.normal, tent->pos1 ); + VectorCopy(tr.plane.normal, tent->pos1); break; // hit solid, but doesn't take damage, so stop the shot...we _could_ allow it to shoot through walls, might be cool? } - } - else // not rendering impact, must be a skybox or other similar thing? + } else // not rendering impact, must be a skybox or other similar thing? { break; // don't try anymore traces } } // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; hitDodged = qfalse; } - //just draw one beam all the way to the end - tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); + // just draw one beam all the way to the end + tent = G_TempEntity(tr.endpos, EV_CONC_ALT_SHOT); tent->svFlags |= SVF_BROADCAST; - VectorCopy( muzzle, tent->s.origin2 ); + VectorCopy(muzzle, tent->s.origin2); // now go along the trail and make sight events - VectorSubtract( tr.endpos, muzzle, dir ); - - shotDist = VectorNormalize( dir ); - - //FIXME: if shoot *really* close to someone, the alert could be way out of their FOV - for ( dist = 0; dist < shotDist; dist += 64 ) - { - //FIXME: on a really long shot, this could make a LOT of alerts in one frame... - VectorMA( muzzle, dist, dir, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); - //FIXME: creates *way* too many effects, make it one effect somehow? - G_PlayEffect( G_EffectIndex( "concussion/alt_ring" ), spot, forwardVec ); + VectorSubtract(tr.endpos, muzzle, dir); + + shotDist = VectorNormalize(dir); + + // FIXME: if shoot *really* close to someone, the alert could be way out of their FOV + for (dist = 0; dist < shotDist; dist += 64) { + // FIXME: on a really long shot, this could make a LOT of alerts in one frame... + VectorMA(muzzle, dist, dir, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); + // FIXME: creates *way* too many effects, make it one effect somehow? + G_PlayEffect(G_EffectIndex("concussion/alt_ring"), spot, forwardVec); } - //FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? - VectorMA( start, shotDist-4, forwardVec, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + // FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? + VectorMA(start, shotDist - 4, forwardVec, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); - G_PlayEffect( G_EffectIndex( "concussion/altmuzzle_flash" ), muzzle, forwardVec ); + G_PlayEffect(G_EffectIndex("concussion/altmuzzle_flash"), muzzle, forwardVec); } -static void WP_FireConcussion( gentity_t *ent ) -{//a fast rocket-like projectile - vec3_t start; - int damage = weaponData[WP_CONCUSSION].damage; - float vel = CONC_VELOCITY; +static void WP_FireConcussion(gentity_t *ent) { // a fast rocket-like projectile + vec3_t start; + int damage = weaponData[WP_CONCUSSION].damage; + float vel = CONC_VELOCITY; - if (ent->s.number >= MAX_CLIENTS) - { + if (ent->s.number >= MAX_CLIENTS) { vec3_t angles; vectoangles(forwardVec, angles); - angles[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angles[YAW] += ( Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f + angles[PITCH] += (Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angles[YAW] += (Q_flrand(-1.0f, 1.0f) * (CONC_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f AngleVectors(angles, forwardVec, vrightVec, up); } - //hold us still for a bit + // hold us still for a bit ent->client->ps.pm_time = 300; ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //add viewkick - if ( ent->s.number < MAX_CLIENTS//player only - && !cg.renderingThirdPerson )//gives an advantage to being in 3rd person, but would look silly otherwise - {//kick the view back - cg.kick_angles[PITCH] = Q_flrand( -10, -15 ); + // add viewkick + if (ent->s.number < MAX_CLIENTS // player only + && !cg.renderingThirdPerson) // gives an advantage to being in 3rd person, but would look silly otherwise + { // kick the view back + cg.kick_angles[PITCH] = Q_flrand(-10, -15); cg.kick_time = level.time; } - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, forwardVec, vel, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(start, forwardVec, vel, 10000, ent, qfalse); missile->classname = "conc_proj"; missile->s.weapon = WP_CONCUSSION; missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = CONC_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = CONC_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = CONC_NPC_DAMAGE_HARD; } } // Make it easier to hit things - VectorSet( missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_EXTRA_KNOCKBACK; @@ -320,14 +286,10 @@ static void WP_FireConcussion( gentity_t *ent ) missile->bounceCount = 0; } -void WP_Concussion( gentity_t *ent, qboolean alt_fire ) -{ - if(alt_fire) - { +void WP_Concussion(gentity_t *ent, qboolean alt_fire) { + if (alt_fire) { WP_FireConcussionAlt(ent); - } - else - { + } else { WP_FireConcussion(ent); } } \ No newline at end of file diff --git a/code/game/wp_demp2.cpp b/code/game/wp_demp2.cpp index f28ebf2899..a043f4a681 100644 --- a/code/game/wp_demp2.cpp +++ b/code/game/wp_demp2.cpp @@ -31,48 +31,42 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_DEMP2_MainFire( gentity_t *ent ) +static void WP_DEMP2_MainFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_DEMP2].damage; + vec3_t start; + int damage = weaponData[WP_DEMP2].damage; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall WP_MissileTargetHint(ent, start, forwardVec); - gentity_t *missile = CreateMissile( start, forwardVec, DEMP2_VELOCITY, 10000, ent ); + gentity_t *missile = CreateMissile(start, forwardVec, DEMP2_VELOCITY, 10000, ent); missile->classname = "demp2_proj"; missile->s.weapon = WP_DEMP2; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = DEMP2_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = DEMP2_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = DEMP2_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -85,50 +79,40 @@ static void WP_DEMP2_MainFire( gentity_t *ent ) // NOTE: this is 100% for the demp2 alt-fire effect, so changes to the visual effect will affect game side demp2 code //-------------------------------------------------- -void DEMP2_AltRadiusDamage( gentity_t *ent ) -{ - float frac = ( level.time - ent->fx_time ) / 1300.0f; // synchronize with demp2 effect - float dist, radius; - gentity_t *gent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities, i, e; - vec3_t mins, maxs; - vec3_t v, dir; +void DEMP2_AltRadiusDamage(gentity_t *ent) { + float frac = (level.time - ent->fx_time) / 1300.0f; // synchronize with demp2 effect + float dist, radius; + gentity_t *gent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities, i, e; + vec3_t mins, maxs; + vec3_t v, dir; frac *= frac * frac; // yes, this is completely ridiculous...but it causes the shell to grow slowly then "explode" at the end radius = frac * 200.0f; // 200 is max radius...the model is aprox. 100 units tall...the fx draw code mults. this by 2. - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = ent->currentOrigin[i] - radius; maxs[i] = ent->currentOrigin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - gent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + gent = entityList[e]; - if ( !gent->takedamage || !gent->contents ) - { + if (!gent->takedamage || !gent->contents) { continue; } // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( ent->currentOrigin[i] < gent->absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (ent->currentOrigin[i] < gent->absmin[i]) { v[i] = gent->absmin[i] - ent->currentOrigin[i]; - } - else if ( ent->currentOrigin[i] > gent->absmax[i] ) - { + } else if (ent->currentOrigin[i] > gent->absmax[i]) { v[i] = ent->currentOrigin[i] - gent->absmax[i]; - } - else - { + } else { v[i] = 0; } } @@ -136,55 +120,52 @@ void DEMP2_AltRadiusDamage( gentity_t *ent ) // shape is an ellipsoid, so cut vertical distance in half` v[2] *= 0.5f; - dist = VectorLength( v ); + dist = VectorLength(v); - if ( dist >= radius ) - { + if (dist >= radius) { // shockwave hasn't hit them yet continue; } - if ( dist < ent->radius ) - { + if (dist < ent->radius) { // shockwave has already hit this thing... continue; } - VectorCopy( gent->currentOrigin, v ); - VectorSubtract( v, ent->currentOrigin, dir); + VectorCopy(gent->currentOrigin, v); + VectorSubtract(v, ent->currentOrigin, dir); // push the center of mass higher than the origin so players get knocked into the air more dir[2] += 12; - G_Damage( gent, ent, ent->owner, dir, ent->currentOrigin, weaponData[WP_DEMP2].altDamage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath ); - if ( gent->takedamage && gent->client ) - { - gent->s.powerups |= ( 1 << PW_SHOCKED ); + G_Damage(gent, ent, ent->owner, dir, ent->currentOrigin, weaponData[WP_DEMP2].altDamage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath); + if (gent->takedamage && gent->client) { + gent->s.powerups |= (1 << PW_SHOCKED); gent->client->ps.powerups[PW_SHOCKED] = level.time + 2000; - Saboteur_Decloak( gent, Q_irand( 3000, 10000 ) ); + Saboteur_Decloak(gent, Q_irand(3000, 10000)); } } - // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge is + // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge + // is ent->radius = radius; - if ( frac < 1.0f ) - { + if (frac < 1.0f) { // shock is still happening so continue letting it expand ent->nextthink = level.time + 50; } } - //--------------------------------------------------------- -void DEMP2_AltDetonate( gentity_t *ent ) +void DEMP2_AltDetonate(gentity_t *ent) //--------------------------------------------------------- { - G_SetOrigin( ent, ent->currentOrigin ); + G_SetOrigin(ent, ent->currentOrigin); - // start the effects, unfortunately, I wanted to do some custom things that I couldn't easily do with the fx system, so part of it uses an event and localEntities - G_PlayEffect( "demp2/altDetonate", ent->currentOrigin, ent->pos1 ); - G_AddEvent( ent, EV_DEMP2_ALT_IMPACT, ent->count * 2 ); + // start the effects, unfortunately, I wanted to do some custom things that I couldn't easily do with the fx system, so part of it uses an event and + // localEntities + G_PlayEffect("demp2/altDetonate", ent->currentOrigin, ent->pos1); + G_AddEvent(ent, EV_DEMP2_ALT_IMPACT, ent->count * 2); ent->fx_time = level.time; ent->radius = 0; @@ -194,39 +175,36 @@ void DEMP2_AltDetonate( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_DEMP2_AltFire( gentity_t *ent ) +static void WP_DEMP2_AltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_REPEATER].altDamage; - int count; - vec3_t start; - trace_t tr; + int damage = weaponData[WP_REPEATER].altDamage; + int count; + vec3_t start; + trace_t tr; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - count = ( level.time - ent->client->ps.weaponChargeTime ) / DEMP2_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / DEMP2_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 3 ) - { + } else if (count > 3) { count = 3; } - damage *= ( 1 + ( count * ( count - 1 )));// yields damage of 12,36,84...gives a higher bonus for longer charge + damage *= (1 + (count * (count - 1))); // yields damage of 12,36,84...gives a higher bonus for longer charge // the shot can travel a whopping 4096 units in 1 second. Note that the shot will auto-detonate at 4096 units...we'll see if this looks cool or not WP_MissileTargetHint(ent, start, forwardVec); - gentity_t *missile = CreateMissile( start, forwardVec, DEMP2_ALT_RANGE, 1000, ent, qtrue ); + gentity_t *missile = CreateMissile(start, forwardVec, DEMP2_ALT_RANGE, 1000, ent, qtrue); // letting it know what the charge size is. missile->count = count; -// missile->speed = missile->nextthink; - VectorCopy( tr.plane.normal, missile->pos1 ); + // missile->speed = missile->nextthink; + VectorCopy(tr.plane.normal, missile->pos1); missile->classname = "demp2_alt_proj"; missile->s.weapon = WP_DEMP2; @@ -245,15 +223,12 @@ static void WP_DEMP2_AltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireDEMP2( gentity_t *ent, qboolean alt_fire ) +void WP_FireDEMP2(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_DEMP2_AltFire( ent ); - } - else - { - WP_DEMP2_MainFire( ent ); + if (alt_fire) { + WP_DEMP2_AltFire(ent); + } else { + WP_DEMP2_MainFire(ent); } } \ No newline at end of file diff --git a/code/game/wp_det_pack.cpp b/code/game/wp_det_pack.cpp index 8a481db678..bb4341076a 100644 --- a/code/game/wp_det_pack.cpp +++ b/code/game/wp_det_pack.cpp @@ -31,7 +31,7 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) +void charge_stick(gentity_t *self, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { self->s.eType = ET_GENERAL; @@ -44,8 +44,8 @@ void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->e_DieFunc = dieF_WP_ExplosiveDie; - VectorSet( self->maxs, 10, 10, 10 ); - VectorScale( self->maxs, -1, self->mins ); + VectorSet(self->maxs, 10, 10, 10); + VectorScale(self->maxs, -1, self->mins); self->activator = self->owner; self->owner = NULL; @@ -54,25 +54,25 @@ void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - WP_Stick( self, trace, 1.0f ); + WP_Stick(self, trace, 1.0f); } //--------------------------------------------------------- -static void WP_DropDetPack( gentity_t *self, vec3_t start, vec3_t dir ) +static void WP_DropDetPack(gentity_t *self, vec3_t start, vec3_t dir) //--------------------------------------------------------- { // Chucking a new one - AngleVectors( self->client->ps.viewangles, forwardVec, vrightVec, up ); - CalcMuzzlePoint( self, forwardVec, vrightVec, up, muzzle, 0 ); - VectorNormalize( forwardVec ); - VectorMA( muzzle, -4, forwardVec, muzzle ); + AngleVectors(self->client->ps.viewangles, forwardVec, vrightVec, up); + CalcMuzzlePoint(self, forwardVec, vrightVec, up, muzzle, 0); + VectorNormalize(forwardVec); + VectorMA(muzzle, -4, forwardVec, muzzle); - VectorCopy( muzzle, start ); - WP_TraceSetStart( self, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(self, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, forwardVec, 300, 10000, self, qfalse ); + gentity_t *missile = CreateMissile(start, forwardVec, 300, 10000, self, qfalse); - missile->fxID = G_EffectIndex( "detpack/explosion" ); // if we set an explosion effect, explode death can use that instead + missile->fxID = G_EffectIndex("detpack/explosion"); // if we set an explosion effect, explode death can use that instead missile->classname = "detpack"; missile->s.weapon = WP_DET_PACK; @@ -87,59 +87,52 @@ static void WP_DropDetPack( gentity_t *self, vec3_t start, vec3_t dir ) missile->splashDamage = weaponData[WP_DET_PACK].splashDamage; missile->splashRadius = weaponData[WP_DET_PACK].splashRadius; - missile->splashMethodOfDeath = MOD_DETPACK;// ?SPLASH; + missile->splashMethodOfDeath = MOD_DETPACK; // ?SPLASH; - missile->clipmask = (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP);//MASK_SHOT; + missile->clipmask = (CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP); // MASK_SHOT; // we don't want it to ever bounce missile->bounceCount = 0; missile->s.radius = 30; - VectorSet( missile->s.modelScale, 1.0f, 1.0f, 1.0f ); - gi.G2API_InitGhoul2Model( missile->ghoul2, weaponData[WP_DET_PACK].missileMdl, G_ModelIndex( weaponData[WP_DET_PACK].missileMdl ), - NULL_HANDLE, NULL_HANDLE, 0, 0); + VectorSet(missile->s.modelScale, 1.0f, 1.0f, 1.0f); + gi.G2API_InitGhoul2Model(missile->ghoul2, weaponData[WP_DET_PACK].missileMdl, G_ModelIndex(weaponData[WP_DET_PACK].missileMdl), NULL_HANDLE, NULL_HANDLE, 0, + 0); - AddSoundEvent( NULL, missile->currentOrigin, 128, AEL_MINOR, qtrue ); - AddSightEvent( NULL, missile->currentOrigin, 128, AEL_SUSPICIOUS, 10 ); + AddSoundEvent(NULL, missile->currentOrigin, 128, AEL_MINOR, qtrue); + AddSightEvent(NULL, missile->currentOrigin, 128, AEL_SUSPICIOUS, 10); } //--------------------------------------------------------- -void WP_FireDetPack( gentity_t *ent, qboolean alt_fire ) +void WP_FireDetPack(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - if ( alt_fire ) - { - if ( ent->client->ps.eFlags & EF_PLANTED_CHARGE ) - { + if (alt_fire) { + if (ent->client->ps.eFlags & EF_PLANTED_CHARGE) { gentity_t *found = NULL; // loop through all ents and blow the crap out of them! - while (( found = G_Find( found, FOFS( classname ), "detpack" )) != NULL ) - { - if ( found->activator == ent ) - { - VectorCopy( found->currentOrigin, found->s.origin ); + while ((found = G_Find(found, FOFS(classname), "detpack")) != NULL) { + if (found->activator == ent) { + VectorCopy(found->currentOrigin, found->s.origin); found->e_ThinkFunc = thinkF_WP_Explode; found->nextthink = level.time + 100 + Q_flrand(0.0f, 1.0f) * 100; - G_Sound( found, G_SoundIndex( "sound/weapons/detpack/warning.wav" )); + G_Sound(found, G_SoundIndex("sound/weapons/detpack/warning.wav")); // would be nice if this actually worked? - AddSoundEvent( NULL, found->currentOrigin, found->splashRadius*2, AEL_DANGER, qfalse, qtrue );//FIXME: are we on ground or not? - AddSightEvent( NULL, found->currentOrigin, found->splashRadius*2, AEL_DISCOVERED, 100 ); + AddSoundEvent(NULL, found->currentOrigin, found->splashRadius * 2, AEL_DANGER, qfalse, qtrue); // FIXME: are we on ground or not? + AddSightEvent(NULL, found->currentOrigin, found->splashRadius * 2, AEL_DISCOVERED, 100); } } ent->client->ps.eFlags &= ~EF_PLANTED_CHARGE; } - } - else - { - WP_DropDetPack( ent, muzzle, forwardVec ); + } else { + WP_DropDetPack(ent, muzzle, forwardVec); ent->client->ps.eFlags |= EF_PLANTED_CHARGE; } diff --git a/code/game/wp_disruptor.cpp b/code/game/wp_disruptor.cpp index 6cebd8de6f..e1e3929651 100644 --- a/code/game/wp_disruptor.cpp +++ b/code/game/wp_disruptor.cpp @@ -31,20 +31,18 @@ along with this program; if not, see . //--------------------- //--------------------------------------------------------- -static void WP_DisruptorMainFire( gentity_t *ent ) +static void WP_DisruptorMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_DISRUPTOR].damage; - qboolean render_impact = qtrue; - vec3_t start, end, spot; - trace_t tr; - gentity_t *traceEnt = NULL, *tent; - float dist, shotDist, shotRange = 8192; - - if ( ent->NPC ) - { - switch ( g_spskill->integer ) - { + int damage = weaponData[WP_DISRUPTOR].damage; + qboolean render_impact = qtrue; + vec3_t start, end, spot; + trace_t tr; + gentity_t *traceEnt = NULL, *tent; + float dist, shotDist, shotRange = 8192; + + if (ent->NPC) { + switch (g_spskill->integer) { case 0: damage = DISRUPTOR_NPC_MAIN_DAMAGE_EASY; break; @@ -58,110 +56,96 @@ static void WP_DisruptorMainFire( gentity_t *ent ) } } - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } WP_MissileTargetHint(ent, start, forwardVec); - VectorMA( start, shotRange, forwardVec, end ); + VectorMA(start, shotRange, forwardVec, end); int ignore = ent->s.number; int traces = 0; - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - gi.trace( &tr, start, NULL, NULL, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0 ); + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + gi.trace(&tr, start, NULL, NULL, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0); traceEnt = &g_entities[tr.entityNum]; - if ( traceEnt - && ( traceEnt->s.weapon == WP_SABER || (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT||traceEnt->client->NPC_class == CLASS_REBORN) ) ) ) - {//FIXME: need a more reliable way to know we hit a jedi? - if ( Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + if (traceEnt && (traceEnt->s.weapon == WP_SABER || + (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT || + traceEnt->client->NPC_class == CLASS_REBORN)))) { // FIXME: need a more reliable way to know we hit a jedi? + if (Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE)) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_MAIN_SHOT ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_MAIN_SHOT); tent->svFlags |= SVF_BROADCAST; - VectorCopy( muzzle, tent->s.origin2 ); + VectorCopy(muzzle, tent->s.origin2); - if ( render_impact ) - { - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { + if (render_impact) { + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "disruptor/flesh_impact" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("disruptor/flesh_impact"), tr.endpos, tr.plane.normal); - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - { + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { ent->client->ps.persistant[PERS_ACCURACY_HITS]++; } - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_DISRUPTOR ); - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, 3, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc ); - } - else - { - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc ); + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_DISRUPTOR); + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, 3, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc); + } else { + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc); } - } - else - { - G_PlayEffect( G_EffectIndex( "disruptor/wall_impact" ), tr.endpos, tr.plane.normal ); + } else { + G_PlayEffect(G_EffectIndex("disruptor/wall_impact"), tr.endpos, tr.plane.normal); } } shotDist = shotRange * tr.fraction; - for ( dist = 0; dist < shotDist; dist += 64 ) - { - //FIXME: on a really long shot, this could make a LOT of alerts in one frame... - VectorMA( start, dist, forwardVec, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + for (dist = 0; dist < shotDist; dist += 64) { + // FIXME: on a really long shot, this could make a LOT of alerts in one frame... + VectorMA(start, dist, forwardVec, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } - VectorMA( start, shotDist-4, forwardVec, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + VectorMA(start, shotDist - 4, forwardVec, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } //--------------------------------------------------------- -void WP_DisruptorAltFire( gentity_t *ent ) +void WP_DisruptorAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_DISRUPTOR].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; - qboolean render_impact = qtrue; - vec3_t start, end; - vec3_t muzzle2, spot, dir; - trace_t tr; - gentity_t *traceEnt, *tent; - float dist, shotDist, shotRange = 8192; - qboolean hitDodged = qfalse, fullCharge = qfalse; + int damage = weaponData[WP_DISRUPTOR].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; + qboolean render_impact = qtrue; + vec3_t start, end; + vec3_t muzzle2, spot, dir; + trace_t tr; + gentity_t *traceEnt, *tent; + float dist, shotDist, shotRange = 8192; + qboolean hitDodged = qfalse, fullCharge = qfalse; - VectorCopy( muzzle, muzzle2 ); // making a backup copy + VectorCopy(muzzle, muzzle2); // making a backup copy // The trace start will originate at the eye so we can ensure that it hits the crosshair. - if ( ent->NPC ) - { - switch ( g_spskill->integer ) - { + if (ent->NPC) { + switch (g_spskill->integer) { case 0: damage = DISRUPTOR_NPC_ALT_DAMAGE_EASY; break; @@ -173,181 +157,158 @@ void WP_DisruptorAltFire( gentity_t *ent ) damage = DISRUPTOR_NPC_ALT_DAMAGE_HARD; break; } - VectorCopy( muzzle, start ); + VectorCopy(muzzle, start); fullCharge = qtrue; - } - else - { - VectorCopy( ent->client->renderInfo.eyePoint, start ); - AngleVectors( ent->client->renderInfo.eyeAngles, forwardVec, NULL, NULL ); + } else { + VectorCopy(ent->client->renderInfo.eyePoint, start); + AngleVectors(ent->client->renderInfo.eyeAngles, forwardVec, NULL, NULL); // don't let NPC's do charging - int count = ( level.time - ent->client->ps.weaponChargeTime - 50 ) / DISRUPTOR_CHARGE_UNIT; + int count = (level.time - ent->client->ps.weaponChargeTime - 50) / DISRUPTOR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count >= 10 ) - { + } else if (count >= 10) { count = 10; fullCharge = qtrue; } // more powerful charges go through more things - if ( count < 3 ) - { + if (count < 3) { traces = 1; - } - else if ( count < 6 ) - { + } else if (count < 6) { traces = 2; } - //else do full traces + // else do full traces damage = damage * count + weaponData[WP_DISRUPTOR].damage * 0.5f; // give a boost to low charge shots } skip = ent->s.number; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - for ( int i = 0; i < traces; i++ ) - { - VectorMA( start, shotRange, forwardVec, end ); + for (int i = 0; i < traces; i++) { + VectorMA(start, shotRange, forwardVec, end); - //NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" - //alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter - gi.trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); + // NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" + // alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter + gi.trace(&tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10); // G2_RETURNONHIT, 0 ); - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } - if ( tr.entityNum == ent->s.number ) - { + if (tr.entityNum == ent->s.number) { // should never happen, but basically we don't want to consider a hit to ourselves? // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; #ifdef _DEBUG - gi.Printf( "BAD! Disruptor gun shot somehow traced back and hit the owner!\n" ); + gi.Printf("BAD! Disruptor gun shot somehow traced back and hit the owner!\n"); #endif continue; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - //NOTE: let's just draw one beam, at the end - //tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); - //tent->svFlags |= SVF_BROADCAST; - //tent->alt_fire = fullCharge; // mark us so we can alter the effect + // NOTE: let's just draw one beam, at the end + // tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); + // tent->svFlags |= SVF_BROADCAST; + // tent->alt_fire = fullCharge; // mark us so we can alter the effect - //VectorCopy( muzzle2, tent->s.origin2 ); + // VectorCopy( muzzle2, tent->s.origin2 ); - if ( tr.fraction >= 1.0f ) - { + if (tr.fraction >= 1.0f) { // draw the beam but don't do anything else break; } traceEnt = &g_entities[tr.entityNum]; - if ( traceEnt //&& traceEnt->NPC - && ( traceEnt->s.weapon == WP_SABER || (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT||traceEnt->client->NPC_class == CLASS_REBORN) ) ) ) - {//FIXME: need a more reliable way to know we hit a jedi? - hitDodged = Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ); - //acts like we didn't even hit him + if (traceEnt //&& traceEnt->NPC + && (traceEnt->s.weapon == WP_SABER || + (traceEnt->client && (traceEnt->client->NPC_class == CLASS_BOBAFETT || + traceEnt->client->NPC_class == CLASS_REBORN)))) { // FIXME: need a more reliable way to know we hit a jedi? + hitDodged = Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE); + // acts like we didn't even hit him } - if ( !hitDodged ) - { - if ( render_impact ) - { - if (( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - || !Q_stricmp( traceEnt->classname, "misc_model_breakable" ) - || traceEnt->s.eType == ET_MOVER ) - { + if (!hitDodged) { + if (render_impact) { + if ((tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) || !Q_stricmp(traceEnt->classname, "misc_model_breakable") || + traceEnt->s.eType == ET_MOVER) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "disruptor/alt_hit" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("disruptor/alt_hit"), tr.endpos, tr.plane.normal); - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - {//NOTE: hitting multiple ents can still get you over 100% accuracy + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { // NOTE: hitting multiple ents can still get you over 100% accuracy ent->client->ps.persistant[PERS_ACCURACY_HITS]++; } - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_DISRUPTOR ); - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, 10, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc ); + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_DISRUPTOR); + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, 10, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, + fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc); break; } - G_Damage( traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc ); - if ( traceEnt->s.eType == ET_MOVER ) - {//stop the traces on any mover + G_Damage(traceEnt, ent, ent, forwardVec, tr.endpos, damage, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, + fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc); + if (traceEnt->s.eType == ET_MOVER) { // stop the traces on any mover break; } - } - else - { - // we only make this mark on things that can't break or move - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_MISS ); + } else { + // we only make this mark on things that can't break or move + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_MISS); tent->svFlags |= SVF_BROADCAST; - VectorCopy( tr.plane.normal, tent->pos1 ); + VectorCopy(tr.plane.normal, tent->pos1); break; // hit solid, but doesn't take damage, so stop the shot...we _could_ allow it to shoot through walls, might be cool? } - } - else // not rendering impact, must be a skybox or other similar thing? + } else // not rendering impact, must be a skybox or other similar thing? { break; // don't try anymore traces } } // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; hitDodged = qfalse; } - //just draw one solid beam all the way to the end... - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); + // just draw one solid beam all the way to the end... + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_SHOT); tent->svFlags |= SVF_BROADCAST; tent->alt_fire = fullCharge; // mark us so we can alter the effect - VectorCopy( muzzle, tent->s.origin2 ); + VectorCopy(muzzle, tent->s.origin2); // now go along the trail and make sight events - VectorSubtract( tr.endpos, muzzle, dir ); + VectorSubtract(tr.endpos, muzzle, dir); - shotDist = VectorNormalize( dir ); + shotDist = VectorNormalize(dir); - //FIXME: if shoot *really* close to someone, the alert could be way out of their FOV - for ( dist = 0; dist < shotDist; dist += 64 ) - { - //FIXME: on a really long shot, this could make a LOT of alerts in one frame... - VectorMA( muzzle, dist, dir, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + // FIXME: if shoot *really* close to someone, the alert could be way out of their FOV + for (dist = 0; dist < shotDist; dist += 64) { + // FIXME: on a really long shot, this could make a LOT of alerts in one frame... + VectorMA(muzzle, dist, dir, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } - //FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? - VectorMA( start, shotDist-4, forwardVec, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + // FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? + VectorMA(start, shotDist - 4, forwardVec, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } //--------------------------------------------------------- -void WP_FireDisruptor( gentity_t *ent, qboolean alt_fire ) +void WP_FireDisruptor(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_DisruptorAltFire( ent ); - } - else - { - WP_DisruptorMainFire( ent ); + if (alt_fire) { + WP_DisruptorAltFire(ent); + } else { + WP_DisruptorMainFire(ent); } - G_PlayEffect( G_EffectIndex( "disruptor/line_cap" ), muzzle, forwardVec ); + G_PlayEffect(G_EffectIndex("disruptor/line_cap"), muzzle, forwardVec); } \ No newline at end of file diff --git a/code/game/wp_emplaced_gun.cpp b/code/game/wp_emplaced_gun.cpp index a28de484b7..708b39c582 100644 --- a/code/game/wp_emplaced_gun.cpp +++ b/code/game/wp_emplaced_gun.cpp @@ -27,52 +27,52 @@ along with this program; if not, see . #include "w_local.h" //--------------------------------------------------------- -void WP_FireTurboLaserMissile( gentity_t *ent, vec3_t start, vec3_t dir ) +void WP_FireTurboLaserMissile(gentity_t *ent, vec3_t start, vec3_t dir) //--------------------------------------------------------- { - int velocity = ent->mass; //FIXME: externalize + int velocity = ent->mass; // FIXME: externalize gentity_t *missile; - missile = CreateMissile( start, dir, velocity, 10000, ent, qfalse ); + missile = CreateMissile(start, dir, velocity, 10000, ent, qfalse); - //use a custom shot effect - //missile->s.otherEntityNum2 = G_EffectIndex( "turret/turb_shot" ); - //use a custom impact effect - //missile->s.emplacedOwner = G_EffectIndex( "turret/turb_impact" ); + // use a custom shot effect + // missile->s.otherEntityNum2 = G_EffectIndex( "turret/turb_shot" ); + // use a custom impact effect + // missile->s.emplacedOwner = G_EffectIndex( "turret/turb_impact" ); missile->classname = "turbo_proj"; missile->s.weapon = WP_TIE_FIGHTER; - missile->damage = ent->damage; //FIXME: externalize - missile->splashDamage = ent->splashDamage; //FIXME: externalize - missile->splashRadius = ent->splashRadius; //FIXME: externalize + missile->damage = ent->damage; // FIXME: externalize + missile->splashDamage = ent->splashDamage; // FIXME: externalize + missile->splashRadius = ent->splashRadius; // FIXME: externalize missile->dflags = DAMAGE_DEATH_KNOCKBACK; - missile->methodOfDeath = MOD_EMPLACED; //MOD_TURBLAST; //count as a heavy weap - missile->splashMethodOfDeath = MOD_EMPLACED; //MOD_TURBLAST;// ?SPLASH; + missile->methodOfDeath = MOD_EMPLACED; // MOD_TURBLAST; //count as a heavy weap + missile->splashMethodOfDeath = MOD_EMPLACED; // MOD_TURBLAST;// ?SPLASH; missile->clipmask = MASK_SHOT; // we don't want it to bounce forever missile->bounceCount = 8; - //set veh as cgame side owner for purpose of fx overrides - //missile->s.owner = ent->s.number; + // set veh as cgame side owner for purpose of fx overrides + // missile->s.owner = ent->s.number; - //don't let them last forever + // don't let them last forever missile->e_ThinkFunc = thinkF_G_FreeEntity; - missile->nextthink = level.time + 10000;//at 20000 speed, that should be more than enough + missile->nextthink = level.time + 10000; // at 20000 speed, that should be more than enough } // Emplaced Gun //--------------------------------------------------------- -void WP_EmplacedFire( gentity_t *ent ) +void WP_EmplacedFire(gentity_t *ent) //--------------------------------------------------------- { - float damage = weaponData[WP_EMPLACED_GUN].damage * ( ent->NPC ? 0.1f : 1.0f ); - float vel = EMPLACED_VEL * ( ent->NPC ? 0.4f : 1.0f ); + float damage = weaponData[WP_EMPLACED_GUN].damage * (ent->NPC ? 0.1f : 1.0f); + float vel = EMPLACED_VEL * (ent->NPC ? 0.4f : 1.0f); WP_MissileTargetHint(ent, muzzle, forwardVec); - gentity_t *missile = CreateMissile( muzzle, forwardVec, vel, 10000, ent ); + gentity_t *missile = CreateMissile(muzzle, forwardVec, vel, 10000, ent); missile->classname = "emplaced_proj"; missile->s.weapon = WP_EMPLACED_GUN; @@ -83,22 +83,18 @@ void WP_EmplacedFire( gentity_t *ent ) missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // do some weird switchery on who the real owner is, we do this so the projectiles don't hit the gun object - if ( ent && ent->client && !(ent->client->ps.eFlags&EF_LOCKED_TO_WEAPON) ) - { + if (ent && ent->client && !(ent->client->ps.eFlags & EF_LOCKED_TO_WEAPON)) { missile->owner = ent; - } - else - { + } else { missile->owner = ent->owner; } - if ( missile->owner->e_UseFunc == useF_eweb_use ) - { + if (missile->owner->e_UseFunc == useF_eweb_use) { missile->alt_fire = qtrue; } - VectorSet( missile->maxs, EMPLACED_SIZE, EMPLACED_SIZE, EMPLACED_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, EMPLACED_SIZE, EMPLACED_SIZE, EMPLACED_SIZE); + VectorScale(missile->maxs, -1, missile->mins); // alternate muzzles ent->fxID = !ent->fxID; diff --git a/code/game/wp_flechette.cpp b/code/game/wp_flechette.cpp index 2f240c8f42..9ba76203b5 100644 --- a/code/game/wp_flechette.cpp +++ b/code/game/wp_flechette.cpp @@ -31,69 +31,64 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -static void WP_FlechetteMainFire( gentity_t *ent ) +static void WP_FlechetteMainFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t fwd, angs, start; - gentity_t *missile; - float damage = weaponData[WP_FLECHETTE].damage, vel = FLECHETTE_VEL; + vec3_t fwd, angs, start; + gentity_t *missile; + float damage = weaponData[WP_FLECHETTE].damage, vel = FLECHETTE_VEL; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall // If we aren't the player, we will cut the velocity and damage of the shots - if ( ent->s.number ) - { + if (ent->s.number) { damage *= 0.75f; vel *= 0.5f; } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - for ( int i = 0; i < FLECHETTE_SHOTS; i++ ) - { - vectoangles( forwardVec, angs ); + for (int i = 0; i < FLECHETTE_SHOTS; i++) { + vectoangles(forwardVec, angs); - if ( i == 0 && ent->s.number == 0 ) - { + if (i == 0 && ent->s.number == 0) { // do nothing on the first shot for the player, this one will hit the crosshairs - } - else - { + } else { angs[PITCH] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; } - AngleVectors( angs, fwd, NULL, NULL ); + AngleVectors(angs, fwd, NULL, NULL); WP_MissileTargetHint(ent, start, fwd); - missile = CreateMissile( start, fwd, vel, 10000, ent ); + missile = CreateMissile(start, fwd, vel, 10000, ent); missile->classname = "flech_proj"; missile->s.weapon = WP_FLECHETTE; - VectorSet( missile->maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// missile->flags |= FL_OVERCHARGED; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // missile->flags |= FL_OVERCHARGED; + // } - missile->dflags = (DAMAGE_DEATH_KNOCKBACK|DAMAGE_EXTRA_KNOCKBACK); + missile->dflags = (DAMAGE_DEATH_KNOCKBACK | DAMAGE_EXTRA_KNOCKBACK); missile->methodOfDeath = MOD_FLECHETTE; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // we don't want it to bounce forever - missile->bounceCount = Q_irand(1,2); + missile->bounceCount = Q_irand(1, 2); missile->s.eFlags |= EF_BOUNCE_SHRAPNEL; ent->client->sess.missionStats.shotsFired++; @@ -101,47 +96,39 @@ static void WP_FlechetteMainFire( gentity_t *ent ) } //--------------------------------------------------------- -void prox_mine_think( gentity_t *ent ) +void prox_mine_think(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // if it isn't time to auto-explode, do a small proximity check - if ( ent->delay > level.time ) - { - count = G_RadiusList( ent->currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list ); - - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number ) - { + if (ent->delay > level.time) { + count = G_RadiusList(ent->currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list); + + for (int i = 0; i < count; i++) { + if (ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number) { blow = qtrue; break; } } - } - else - { + } else { // well, we must die now blow = qtrue; } - if ( blow ) - { -// G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); + if (blow) { + // G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); ent->e_ThinkFunc = thinkF_WP_Explode; ent->nextthink = level.time + 200; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + 500; } } //--------------------------------------------------------- -void prox_mine_stick( gentity_t *self, gentity_t *other, trace_t *trace ) +void prox_mine_stick(gentity_t *self, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { // turn us into a generic entity so we aren't running missile code @@ -155,13 +142,13 @@ void prox_mine_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->health = 5; self->e_DieFunc = dieF_WP_ExplosiveDie; - VectorSet( self->maxs, 5, 5, 5 ); - VectorScale( self->maxs, -1, self->mins ); + VectorSet(self->maxs, 5, 5, 5); + VectorScale(self->maxs, -1, self->mins); self->activator = self->owner; self->owner = NULL; - WP_Stick( self, trace ); + WP_Stick(self, trace); self->e_ThinkFunc = thinkF_prox_mine_think; self->nextthink = level.time + 450; @@ -169,7 +156,7 @@ void prox_mine_stick( gentity_t *self, gentity_t *other, trace_t *trace ) // sticks for twenty seconds, then auto blows. self->delay = level.time + 20000; - gi.linkentity( self ); + gi.linkentity(self); } /* Old Flechette alt-fire code.... //--------------------------------------------------------- @@ -202,22 +189,22 @@ static void WP_FlechetteProxMine( gentity_t *ent ) } */ //---------------------------------------------- -void WP_flechette_alt_blow( gentity_t *ent ) +void WP_flechette_alt_blow(gentity_t *ent) //---------------------------------------------- { - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); // Not sure if this is even necessary, but correct origins are cool? + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); // Not sure if this is even necessary, but correct origins are cool? - G_RadiusDamage( ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, MOD_EXPLOSIVE_SPLASH ); - G_PlayEffect( "flechette/alt_blow", ent->currentOrigin ); + G_RadiusDamage(ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, MOD_EXPLOSIVE_SPLASH); + G_PlayEffect("flechette/alt_blow", ent->currentOrigin); - G_FreeEntity( ent ); + G_FreeEntity(ent); } //------------------------------------------------------------------------------ -static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t *self ) +static void WP_CreateFlechetteBouncyThing(vec3_t start, vec3_t fwd, gentity_t *self) //------------------------------------------------------------------------------ { - gentity_t *missile = CreateMissile( start, fwd, 950 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue ); + gentity_t *missile = CreateMissile(start, fwd, 950 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue); missile->e_ThinkFunc = thinkF_WP_flechette_alt_blow; @@ -226,8 +213,8 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->mass = 4; // How 'bout we give this thing a size... - VectorSet( missile->mins, -3.0f, -3.0f, -3.0f ); - VectorSet( missile->maxs, 3.0f, 3.0f, 3.0f ); + VectorSet(missile->mins, -3.0f, -3.0f, -3.0f); + VectorSet(missile->maxs, 3.0f, 3.0f, 3.0f); missile->clipmask = MASK_SHOT; missile->clipmask &= ~CONTENTS_CORPSE; @@ -246,43 +233,39 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->methodOfDeath = MOD_FLECHETTE_ALT; missile->splashMethodOfDeath = MOD_FLECHETTE_ALT; - VectorCopy( start, missile->pos2 ); + VectorCopy(start, missile->pos2); } //--------------------------------------------------------- -static void WP_FlechetteAltFire( gentity_t *self ) +static void WP_FlechetteAltFire(gentity_t *self) //--------------------------------------------------------- { - vec3_t dir, fwd, start, angs; + vec3_t dir, fwd, start, angs; - vectoangles( forwardVec, angs ); - VectorCopy( muzzle, start ); + vectoangles(forwardVec, angs); + VectorCopy(muzzle, start); - WP_TraceSetStart( self, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(self, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - for ( int i = 0; i < 2; i++ ) - { - VectorCopy( angs, dir ); + for (int i = 0; i < 2; i++) { + VectorCopy(angs, dir); dir[PITCH] -= Q_flrand(0.0f, 1.0f) * 4 + 8; // make it fly upwards dir[YAW] += Q_flrand(-1.0f, 1.0f) * 2; - AngleVectors( dir, fwd, NULL, NULL ); + AngleVectors(dir, fwd, NULL, NULL); - WP_CreateFlechetteBouncyThing( start, fwd, self ); + WP_CreateFlechetteBouncyThing(start, fwd, self); self->client->sess.missionStats.shotsFired++; } } //--------------------------------------------------------- -void WP_FireFlechette( gentity_t *ent, qboolean alt_fire ) +void WP_FireFlechette(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_FlechetteAltFire( ent ); - } - else - { - WP_FlechetteMainFire( ent ); + if (alt_fire) { + WP_FlechetteAltFire(ent); + } else { + WP_FlechetteMainFire(ent); } } \ No newline at end of file diff --git a/code/game/wp_melee.cpp b/code/game/wp_melee.cpp index a010be95c6..d2abcac910 100644 --- a/code/game/wp_melee.cpp +++ b/code/game/wp_melee.cpp @@ -26,57 +26,49 @@ along with this program; if not, see . #include "wp_saber.h" #include "w_local.h" -void WP_Melee( gentity_t *ent ) +void WP_Melee(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end; - int damage = ent->s.number ? (g_spskill->integer*2)+1 : 3; - float range = ent->s.number ? 64 : 32; + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end; + int damage = ent->s.number ? (g_spskill->integer * 2) + 1 : 3; + float range = ent->s.number ? 64 : 32; - VectorMA( muzzle, range, forwardVec, end ); + VectorMA(muzzle, range, forwardVec, end); - VectorSet( maxs, 6, 6, 6 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 6, 6, 6); + VectorScale(maxs, -1, mins); - gi.trace ( &tr, muzzle, mins, maxs, end, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); + gi.trace(&tr, muzzle, mins, maxs, end, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0); - if ( tr.entityNum >= ENTITYNUM_WORLD ) - { - if ( tr.entityNum == ENTITYNUM_WORLD ) - { - G_PlayEffect( G_EffectIndex( "melee/punch_impact" ), tr.endpos, forwardVec ); + if (tr.entityNum >= ENTITYNUM_WORLD) { + if (tr.entityNum == ENTITYNUM_WORLD) { + G_PlayEffect(G_EffectIndex("melee/punch_impact"), tr.endpos, forwardVec); } return; } tr_ent = &g_entities[tr.entityNum]; - if ( ent->client && !PM_DroidMelee( ent->client->NPC_class ) ) - { - if ( ent->s.number || ent->alt_fire ) - { - damage *= Q_irand( 2, 3 ); - } - else - { - damage *= Q_irand( 1, 2 ); + if (ent->client && !PM_DroidMelee(ent->client->NPC_class)) { + if (ent->s.number || ent->alt_fire) { + damage *= Q_irand(2, 3); + } else { + damage *= Q_irand(1, 2); } } - if ( tr_ent && tr_ent->takedamage ) - { + if (tr_ent && tr_ent->takedamage) { int dflags = DAMAGE_NO_KNOCKBACK; - G_PlayEffect( G_EffectIndex( "melee/punch_impact" ), tr.endpos, forwardVec ); - //G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); - if ( ent->NPC && (ent->NPC->aiFlags&NPCAI_HEAVY_MELEE) ) - { //4x damage for heavy melee class + G_PlayEffect(G_EffectIndex("melee/punch_impact"), tr.endpos, forwardVec); + // G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + if (ent->NPC && (ent->NPC->aiFlags & NPCAI_HEAVY_MELEE)) { // 4x damage for heavy melee class damage *= 4; dflags &= ~DAMAGE_NO_KNOCKBACK; dflags |= DAMAGE_DISMEMBER; } - G_Damage( tr_ent, ent, ent, forwardVec, tr.endpos, damage, dflags, MOD_MELEE ); + G_Damage(tr_ent, ent, ent, forwardVec, tr.endpos, damage, dflags, MOD_MELEE); } } \ No newline at end of file diff --git a/code/game/wp_noghri_stick.cpp b/code/game/wp_noghri_stick.cpp index a96aac6064..3219b532ad 100644 --- a/code/game/wp_noghri_stick.cpp +++ b/code/game/wp_noghri_stick.cpp @@ -26,62 +26,54 @@ along with this program; if not, see . #include "w_local.h" //--------------------------------------------------------- -void WP_FireNoghriStick( gentity_t *ent ) +void WP_FireNoghriStick(gentity_t *ent) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( forwardVec, angs ); + vectoangles(forwardVec, angs); - if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - // add some slop to the main-fire direction - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f + if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + // add some slop to the main-fire direction + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - int velocity = 1200; + int velocity = 1200; - WP_TraceSetStart( ent, muzzle, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, muzzle, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall WP_MissileTargetHint(ent, muzzle, dir); - gentity_t *missile = CreateMissile( muzzle, dir, velocity, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(muzzle, dir, velocity, 10000, ent, qfalse); missile->classname = "noghri_proj"; missile->s.weapon = WP_NOGHRI_STICK; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { missile->damage = 1; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { missile->damage = 5; - } - else - { + } else { missile->damage = 10; } } -// if ( ent->client ) -// { -// if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } -// } + // if ( ent->client ) + // { + // if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } + // } missile->dflags = DAMAGE_NO_KNOCKBACK; missile->methodOfDeath = MOD_BLASTER; @@ -90,5 +82,5 @@ void WP_FireNoghriStick( gentity_t *ent ) missile->splashRadius = 100; missile->splashMethodOfDeath = MOD_GAS; - //Hmm: maybe spew gas on impact? + // Hmm: maybe spew gas on impact? } \ No newline at end of file diff --git a/code/game/wp_repeater.cpp b/code/game/wp_repeater.cpp index 792732978b..43d1cf5999 100644 --- a/code/game/wp_repeater.cpp +++ b/code/game/wp_repeater.cpp @@ -31,45 +31,39 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) +static void WP_RepeaterMainFire(gentity_t *ent, vec3_t dir) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_REPEATER].damage; + vec3_t start; + int damage = weaponData[WP_REPEATER].damage; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall WP_MissileTargetHint(ent, start, dir); - gentity_t *missile = CreateMissile( start, dir, REPEATER_VELOCITY, 10000, ent ); + gentity_t *missile = CreateMissile(start, dir, REPEATER_VELOCITY, 10000, ent); missile->classname = "repeater_proj"; missile->s.weapon = WP_REPEATER; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = REPEATER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = REPEATER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = REPEATER_NPC_DAMAGE_HARD; } } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -81,24 +75,21 @@ static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) } //--------------------------------------------------------- -static void WP_RepeaterAltFire( gentity_t *ent ) +static void WP_RepeaterAltFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_REPEATER].altDamage; + vec3_t start; + int damage = weaponData[WP_REPEATER].altDamage; gentity_t *missile = NULL; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - if ( ent->client && ent->client->NPC_class == CLASS_GALAKMECH ) - { - missile = CreateMissile( start, ent->client->hiddenDir, ent->client->hiddenDist, 10000, ent, qtrue ); - } - else - { + if (ent->client && ent->client->NPC_class == CLASS_GALAKMECH) { + missile = CreateMissile(start, ent->client->hiddenDir, ent->client->hiddenDist, 10000, ent, qtrue); + } else { WP_MissileTargetHint(ent, start, forwardVec); - missile = CreateMissile( start, forwardVec, REPEATER_ALT_VELOCITY, 10000, ent, qtrue ); + missile = CreateMissile(start, forwardVec, REPEATER_ALT_VELOCITY, 10000, ent, qtrue); } missile->classname = "repeater_alt_proj"; @@ -106,33 +97,27 @@ static void WP_RepeaterAltFire( gentity_t *ent ) missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = REPEATER_ALT_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = REPEATER_ALT_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = REPEATER_ALT_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->s.pos.trType = TR_GRAVITY; - missile->s.pos.trDelta[2] += 40.0f; //give a slight boost in the upward direction + missile->s.pos.trDelta[2] += 40.0f; // give a slight boost in the upward direction -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -147,44 +132,36 @@ static void WP_RepeaterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireRepeater( gentity_t *ent, qboolean alt_fire ) +void WP_FireRepeater(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t dir, angs; - - vectoangles( forwardVec, angs ); - - if ( alt_fire ) - { - WP_RepeaterAltFire( ent ); - } - else - { - if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - // Troopers use their aim values as well as the gun's inherent inaccuracy - // so check for all classes of stormtroopers and anyone else that has aim error - if ( ent->client && ent->NPC && - ( ent->client->NPC_class == CLASS_STORMTROOPER || - ent->client->NPC_class == CLASS_SWAMPTROOPER || - ent->client->NPC_class == CLASS_SHADOWTROOPER ) ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - } - else - { + vec3_t dir, angs; + + vectoangles(forwardVec, angs); + + if (alt_fire) { + WP_RepeaterAltFire(ent); + } else { + if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || + ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + // Troopers use their aim values as well as the gun's inherent inaccuracy + // so check for all classes of stormtroopers and anyone else that has aim error + if (ent->client && ent->NPC && + (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || + ent->client->NPC_class == CLASS_SHADOWTROOPER)) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + } else { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; } } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - WP_RepeaterMainFire( ent, dir ); + WP_RepeaterMainFire(ent, dir); } } \ No newline at end of file diff --git a/code/game/wp_rocket_launcher.cpp b/code/game/wp_rocket_launcher.cpp index 9d19bf1807..4b54bdaf24 100644 --- a/code/game/wp_rocket_launcher.cpp +++ b/code/game/wp_rocket_launcher.cpp @@ -31,50 +31,39 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -void rocketThink( gentity_t *ent ) +void rocketThink(gentity_t *ent) //--------------------------------------------------------- { - vec3_t newdir, targetdir, - up={0,0,1}, right; - vec3_t org; + vec3_t newdir, targetdir, up = {0, 0, 1}, right; + vec3_t org; float dot, dot2; - if ( ent->disconnectDebounceTime && ent->disconnectDebounceTime < level.time ) - {//time's up, we're done, remove us - if ( ent->lockCount ) - {//explode when die - WP_ExplosiveDie( ent, ent->owner, ent->owner, 0, MOD_UNKNOWN, 0, HL_NONE ); - } - else - {//just remove when die - G_FreeEntity( ent ); + if (ent->disconnectDebounceTime && ent->disconnectDebounceTime < level.time) { // time's up, we're done, remove us + if (ent->lockCount) { // explode when die + WP_ExplosiveDie(ent, ent->owner, ent->owner, 0, MOD_UNKNOWN, 0, HL_NONE); + } else { // just remove when die + G_FreeEntity(ent); } return; } - if ( ent->enemy && ent->enemy->inuse ) - { - float vel = (ent->spawnflags&1)?ent->speed:ROCKET_VELOCITY; - float newDirMult = ent->angle?ent->angle*2.0f:1.0f; - float oldDirMult = ent->angle?(1.0f-ent->angle)*2.0f:1.0f; - - if ( (ent->spawnflags&1) ) - {//vehicle rocket - if ( ent->enemy->client && ent->enemy->client->NPC_class == CLASS_VEHICLE ) - {//tracking another vehicle - if ( ent->enemy->client->ps.speed+ent->speed > vel ) - { - vel = ent->enemy->client->ps.speed+ent->speed; + if (ent->enemy && ent->enemy->inuse) { + float vel = (ent->spawnflags & 1) ? ent->speed : ROCKET_VELOCITY; + float newDirMult = ent->angle ? ent->angle * 2.0f : 1.0f; + float oldDirMult = ent->angle ? (1.0f - ent->angle) * 2.0f : 1.0f; + + if ((ent->spawnflags & 1)) { // vehicle rocket + if (ent->enemy->client && ent->enemy->client->NPC_class == CLASS_VEHICLE) { // tracking another vehicle + if (ent->enemy->client->ps.speed + ent->speed > vel) { + vel = ent->enemy->client->ps.speed + ent->speed; } } } - VectorCopy( ent->enemy->currentOrigin, org ); + VectorCopy(ent->enemy->currentOrigin, org); org[2] += (ent->enemy->mins[2] + ent->enemy->maxs[2]) * 0.5f; - if ( ent->enemy->client ) - { - switch( ent->enemy->client->NPC_class ) - { + if (ent->enemy->client) { + switch (ent->enemy->client->NPC_class) { case CLASS_ATST: org[2] += 80; break; @@ -87,187 +76,152 @@ void rocketThink( gentity_t *ent ) default: break; } - if ( !TIMER_Done( ent->enemy, "flee" ) ) - { - TIMER_Set( ent->enemy, "rocketChasing", 500 ); + if (!TIMER_Done(ent->enemy, "flee")) { + TIMER_Set(ent->enemy, "rocketChasing", 500); } } - VectorSubtract( org, ent->currentOrigin, targetdir ); - VectorNormalize( targetdir ); + VectorSubtract(org, ent->currentOrigin, targetdir); + VectorNormalize(targetdir); // Now the rocket can't do a 180 in space, so we'll limit the turn to about 45 degrees. - dot = DotProduct( targetdir, ent->movedir ); + dot = DotProduct(targetdir, ent->movedir); // a dot of 1.0 means right-on-target. - if ( dot < 0.0f ) - { + if (dot < 0.0f) { // Go in the direction opposite, start a 180. - CrossProduct( ent->movedir, up, right ); - dot2 = DotProduct( targetdir, right ); + CrossProduct(ent->movedir, up, right); + dot2 = DotProduct(targetdir, right); - if ( dot2 > 0 ) - { + if (dot2 > 0) { // Turn 45 degrees right. - VectorMA( ent->movedir, 0.3f*newDirMult, right, newdir ); - } - else - { + VectorMA(ent->movedir, 0.3f * newDirMult, right, newdir); + } else { // Turn 45 degrees left. - VectorMA(ent->movedir, -0.3f*newDirMult, right, newdir); + VectorMA(ent->movedir, -0.3f * newDirMult, right, newdir); } // Yeah we've adjusted horizontally, but let's split the difference vertically, so we kinda try to move towards it. - newdir[2] = ( (targetdir[2]*newDirMult) + (ent->movedir[2]*oldDirMult) ) * 0.5; + newdir[2] = ((targetdir[2] * newDirMult) + (ent->movedir[2] * oldDirMult)) * 0.5; // slowing down coupled with fairly tight turns can lead us to orbit an enemy..looks bad so don't do it! -// vel *= 0.5f; - } - else if ( dot < 0.70f ) - { + // vel *= 0.5f; + } else if (dot < 0.70f) { // Still a bit off, so we turn a bit softer - VectorMA( ent->movedir, 0.5f*newDirMult, targetdir, newdir ); - } - else - { + VectorMA(ent->movedir, 0.5f * newDirMult, targetdir, newdir); + } else { // getting close, so turn a bit harder - VectorMA( ent->movedir, 0.9f*newDirMult, targetdir, newdir ); + VectorMA(ent->movedir, 0.9f * newDirMult, targetdir, newdir); } // add crazy drunkenness - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { newdir[i] += Q_flrand(-1.0f, 1.0f) * ent->random * 0.25f; } // decay the randomness ent->random *= 0.9f; - if ( ent->enemy->client - && ent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//tracking a client who's on the ground, aim at the floor...? + if (ent->enemy->client && ent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // tracking a client who's on the ground, aim at the floor...? // Try to crash into the ground if we get close enough to do splash damage - float dis = Distance( ent->currentOrigin, org ); + float dis = Distance(ent->currentOrigin, org); - if ( dis < 128 ) - { + if (dis < 128) { // the closer we get, the more we push the rocket down, heh heh. newdir[2] -= (1.0f - (dis / 128.0f)) * 0.6f; } } - VectorNormalize( newdir ); + VectorNormalize(newdir); - VectorScale( newdir, vel * 0.5f, ent->s.pos.trDelta ); - VectorCopy( newdir, ent->movedir ); - SnapVector( ent->s.pos.trDelta ); // save net bandwidth - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(newdir, vel * 0.5f, ent->s.pos.trDelta); + VectorCopy(newdir, ent->movedir); + SnapVector(ent->s.pos.trDelta); // save net bandwidth + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } - ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. + ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. return; } //--------------------------------------------------------- -void WP_FireRocket( gentity_t *ent, qboolean alt_fire ) +void WP_FireRocket(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_ROCKET_LAUNCHER].damage; - float vel = ROCKET_VELOCITY; + vec3_t start; + int damage = weaponData[WP_ROCKET_LAUNCHER].damage; + float vel = ROCKET_VELOCITY; - if ( alt_fire ) - { + if (alt_fire) { vel *= 0.5f; } - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, forwardVec, vel, 10000, ent, alt_fire ); + gentity_t *missile = CreateMissile(start, forwardVec, vel, 10000, ent, alt_fire); missile->classname = "rocket_proj"; missile->s.weapon = WP_ROCKET_LAUNCHER; missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ROCKET_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ROCKET_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ROCKET_NPC_DAMAGE_HARD; } - if (ent->client && ent->client->NPC_class==CLASS_BOBAFETT) - { - damage = damage/2; + if (ent->client && ent->client->NPC_class == CLASS_BOBAFETT) { + damage = damage / 2; } } - if ( alt_fire ) - { - int lockEntNum, lockTime; - if ( ent->NPC && ent->enemy ) - { + if (alt_fire) { + int lockEntNum, lockTime; + if (ent->NPC && ent->enemy) { lockEntNum = ent->enemy->s.number; - lockTime = Q_irand( 600, 1200 ); - } - else - { + lockTime = Q_irand(600, 1200); + } else { lockEntNum = g_rocketLockEntNum; lockTime = g_rocketLockTime; } // we'll consider attempting to lock this little poochie onto some baddie. - if ( (lockEntNum > 0 || (ent->NPC && lockEntNum >= 0)) && lockEntNum < ENTITYNUM_WORLD && lockTime > 0 ) - { + if ((lockEntNum > 0 || (ent->NPC && lockEntNum >= 0)) && lockEntNum < ENTITYNUM_WORLD && lockTime > 0) { // take our current lock time and divide that by 8 wedge slices to get the current lock amount - int dif = ( level.time - lockTime ) / ( 1200.0f / 8.0f ); + int dif = (level.time - lockTime) / (1200.0f / 8.0f); - if ( dif < 0 ) - { + if (dif < 0) { dif = 0; - } - else if ( dif > 8 ) - { + } else if (dif > 8) { dif = 8; } // if we are fully locked, always take on the enemy. // Also give a slight advantage to higher, but not quite full charges. // Finally, just give any amount of charge a very slight random chance of locking. - if ( dif == 8 || Q_flrand(0.0f, 1.0f) * dif > 2 || Q_flrand(0.0f, 1.0f) > 0.97f ) - { + if (dif == 8 || Q_flrand(0.0f, 1.0f) * dif > 2 || Q_flrand(0.0f, 1.0f) > 0.97f) { missile->enemy = &g_entities[lockEntNum]; - if ( missile->enemy - && missile->enemy->inuse )//&& DistanceSquared( missile->currentOrigin, missile->enemy->currentOrigin ) < 262144 && InFOV( missile->currentOrigin, missile->enemy->currentOrigin, missile->enemy->client->ps.viewangles, 45, 45 ) ) + if (missile->enemy && + missile->enemy->inuse) //&& DistanceSquared( missile->currentOrigin, missile->enemy->currentOrigin ) < 262144 && InFOV( + //missile->currentOrigin, missile->enemy->currentOrigin, missile->enemy->client->ps.viewangles, 45, 45 ) ) { - if ( missile->enemy->client - && (missile->enemy->client->ps.forcePowersKnown&(1<enemy->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_0 ) - {//have force push, don't flee from homing rockets - } - else - { + if (missile->enemy->client && (missile->enemy->client->ps.forcePowersKnown & (1 << FP_PUSH)) && + missile->enemy->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_0) { // have force push, don't flee from homing rockets + } else { vec3_t dir, dir2; - AngleVectors( missile->enemy->currentAngles, dir, NULL, NULL ); - AngleVectors( ent->client->renderInfo.eyeAngles, dir2, NULL, NULL ); + AngleVectors(missile->enemy->currentAngles, dir, NULL, NULL); + AngleVectors(ent->client->renderInfo.eyeAngles, dir2, NULL, NULL); - if ( DotProduct( dir, dir2 ) < 0.0f ) - { - G_StartFlee( missile->enemy, ent, missile->enemy->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - if ( !TIMER_Done( missile->enemy, "flee" ) ) - { - TIMER_Set( missile->enemy, "rocketChasing", 500 ); + if (DotProduct(dir, dir2) < 0.0f) { + G_StartFlee(missile->enemy, ent, missile->enemy->currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + if (!TIMER_Done(missile->enemy, "flee")) { + TIMER_Set(missile->enemy, "rocketChasing", 500); } } } @@ -275,7 +229,7 @@ void WP_FireRocket( gentity_t *ent, qboolean alt_fire ) } } - VectorCopy( forwardVec, missile->movedir ); + VectorCopy(forwardVec, missile->movedir); missile->e_ThinkFunc = thinkF_rocketThink; missile->random = 1.0f; @@ -283,21 +237,18 @@ void WP_FireRocket( gentity_t *ent, qboolean alt_fire ) } // Make it easier to hit things - VectorSet( missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( alt_fire ) - { + if (alt_fire) { missile->methodOfDeath = MOD_ROCKET_ALT; - missile->splashMethodOfDeath = MOD_ROCKET_ALT;// ?SPLASH; - } - else - { + missile->splashMethodOfDeath = MOD_ROCKET_ALT; // ?SPLASH; + } else { missile->methodOfDeath = MOD_ROCKET; - missile->splashMethodOfDeath = MOD_ROCKET;// ?SPLASH; + missile->splashMethodOfDeath = MOD_ROCKET; // ?SPLASH; } missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; diff --git a/code/game/wp_saber.cpp b/code/game/wp_saber.cpp index ae6985decf..5ad39dccb1 100644 --- a/code/game/wp_saber.cpp +++ b/code/game/wp_saber.cpp @@ -33,510 +33,395 @@ along with this program; if not, see . #define JK2_RAGDOLL_GRIPNOHEALTH #define MAX_SABER_VICTIMS 16 -static int victimEntityNum[MAX_SABER_VICTIMS]; -static float totalDmg[MAX_SABER_VICTIMS]; -static vec3_t dmgDir[MAX_SABER_VICTIMS]; -static vec3_t dmgNormal[MAX_SABER_VICTIMS]; -static vec3_t dmgBladeVec[MAX_SABER_VICTIMS]; -static vec3_t dmgSpot[MAX_SABER_VICTIMS]; -static float dmgFraction[MAX_SABER_VICTIMS]; -static int hitLoc[MAX_SABER_VICTIMS]; -static qboolean hitDismember[MAX_SABER_VICTIMS]; -static int hitDismemberLoc[MAX_SABER_VICTIMS]; -static vec3_t saberHitLocation, saberHitNormal={0,0,1.0}; -static float saberHitFraction; -static float sabersCrossed; -static int saberHitEntity; -static int numVictims = 0; - -extern cvar_t *g_sex; -extern cvar_t *g_timescale; -extern cvar_t *g_dismemberment; -extern cvar_t *g_debugSaberLock; -extern cvar_t *g_saberLockRandomNess; -extern cvar_t *d_slowmodeath; -extern cvar_t *g_cheats; -extern cvar_t *g_debugMelee; -extern cvar_t *g_saberRestrictForce; -extern cvar_t *g_saberPickuppableDroppedSabers; -extern cvar_t *debug_subdivision; - - -extern qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); -extern qboolean WP_SaberBladeDoTransitionDamage( saberInfo_t *saber, int bladeNum ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern qboolean G_ControlledByPlayer( gentity_t *self ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void CG_ChangeWeapon( int num ); -extern void CG_SaberDoWeaponHitMarks( gclient_t *client, gentity_t *saberEnt, gentity_t *hitEnt, int saberNum, int bladeNum, vec3_t hitPos, vec3_t hitDir, vec3_t uaxis, vec3_t splashBackDir, float sizeTimeScale ); -extern void G_AngerAlert( gentity_t *self ); -extern void G_ReflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ); -extern int G_CheckLedgeDive( gentity_t *self, float checkDist, const vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp ); -extern void G_BounceMissile( gentity_t *ent, trace_t *trace ); -extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); -extern void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ); -extern void WP_FireDreadnoughtBeam( gentity_t *ent ); -extern void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc=HL_NONE ); -extern evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f ); -extern void Jedi_RageStop( gentity_t *self ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern void NPC_SetPainEvent( gentity_t *self ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInAttackPure( int move ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInReturn( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern saberMoveName_t PM_SaberBounceForAttack( int move ); -extern saberMoveName_t PM_BrokenParryForAttack( int move ); -extern saberMoveName_t PM_KnockawayForParry( int move ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_ForceUsingSaberAnim( int anim ); -extern qboolean PM_SuperBreakLoseAnim( int anim ); -extern qboolean PM_SuperBreakWinAnim( int anim ); -extern qboolean PM_SaberLockBreakAnim( int anim ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern qboolean PM_KnockDownAnim( int anim ); -extern qboolean PM_SaberInKata( saberMoveName_t saberMove ); -extern qboolean PM_StabDownAnim( int anim ); -extern int PM_PowerLevelForSaberAnim( playerState_t *ps, int saberNum = 0 ); -extern void PM_VelocityForSaberMove( playerState_t *ps, vec3_t throwDir ); -extern qboolean PM_VelocityForBlockedMove( playerState_t *ps, vec3_t throwDir ); -extern qboolean PM_SaberCanInterruptMove( int move, int anim ); -extern int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ); -extern qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ); -extern void Jedi_PlayDeflectSound( gentity_t *self ); -extern void Jedi_PlayBlockedPushSound( gentity_t *self ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern void Jedi_Ambush( gentity_t *self ); -extern qboolean Jedi_SaberBusy( gentity_t *self ); -extern qboolean Jedi_CultistDestroyer( gentity_t *self ); -extern qboolean Boba_Flying( gentity_t *self ); -extern void JET_FlyStart( gentity_t *self ); -extern void Boba_DoFlameThrower( gentity_t *self ); -extern void Boba_StopFlameThrower( gentity_t *self ); - -extern Vehicle_t *G_IsRidingVehicle( gentity_t *ent ); -extern int SaberDroid_PowerLevelForSaberAnim( gentity_t *self ); -extern qboolean G_ValidEnemy( gentity_t *self, gentity_t *enemy ); -extern void G_StartMatrixEffect( gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0 ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_KnockOffVehicle( gentity_t *pRider, gentity_t *self, qboolean bPull ); -extern qboolean PM_LockedAnim( int anim ); -extern qboolean Rosh_BeingHealed( gentity_t *self ); -extern qboolean G_OkayToLean( playerState_t *ps, usercmd_t *cmd, qboolean interruptOkay ); +static int victimEntityNum[MAX_SABER_VICTIMS]; +static float totalDmg[MAX_SABER_VICTIMS]; +static vec3_t dmgDir[MAX_SABER_VICTIMS]; +static vec3_t dmgNormal[MAX_SABER_VICTIMS]; +static vec3_t dmgBladeVec[MAX_SABER_VICTIMS]; +static vec3_t dmgSpot[MAX_SABER_VICTIMS]; +static float dmgFraction[MAX_SABER_VICTIMS]; +static int hitLoc[MAX_SABER_VICTIMS]; +static qboolean hitDismember[MAX_SABER_VICTIMS]; +static int hitDismemberLoc[MAX_SABER_VICTIMS]; +static vec3_t saberHitLocation, saberHitNormal = {0, 0, 1.0}; +static float saberHitFraction; +static float sabersCrossed; +static int saberHitEntity; +static int numVictims = 0; + +extern cvar_t *g_sex; +extern cvar_t *g_timescale; +extern cvar_t *g_dismemberment; +extern cvar_t *g_debugSaberLock; +extern cvar_t *g_saberLockRandomNess; +extern cvar_t *d_slowmodeath; +extern cvar_t *g_cheats; +extern cvar_t *g_debugMelee; +extern cvar_t *g_saberRestrictForce; +extern cvar_t *g_saberPickuppableDroppedSabers; +extern cvar_t *debug_subdivision; + +extern qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); +extern qboolean WP_SaberBladeDoTransitionDamage(saberInfo_t *saber, int bladeNum); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern qboolean G_ControlledByPlayer(gentity_t *self); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void CG_ChangeWeapon(int num); +extern void CG_SaberDoWeaponHitMarks(gclient_t *client, gentity_t *saberEnt, gentity_t *hitEnt, int saberNum, int bladeNum, vec3_t hitPos, vec3_t hitDir, + vec3_t uaxis, vec3_t splashBackDir, float sizeTimeScale); +extern void G_AngerAlert(gentity_t *self); +extern void G_ReflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward); +extern int G_CheckLedgeDive(gentity_t *self, float checkDist, const vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp); +extern void G_BounceMissile(gentity_t *ent, trace_t *trace); +extern qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs); +extern void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone); +extern void WP_FireDreadnoughtBeam(gentity_t *ent); +extern void G_MissileImpacted(gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc = HL_NONE); +extern evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f); +extern void Jedi_RageStop(gentity_t *self); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern void NPC_SetPainEvent(gentity_t *self); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInAttackPure(int move); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInReturn(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SpinningSaberAnim(int anim); +extern saberMoveName_t PM_SaberBounceForAttack(int move); +extern saberMoveName_t PM_BrokenParryForAttack(int move); +extern saberMoveName_t PM_KnockawayForParry(int move); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_ForceUsingSaberAnim(int anim); +extern qboolean PM_SuperBreakLoseAnim(int anim); +extern qboolean PM_SuperBreakWinAnim(int anim); +extern qboolean PM_SaberLockBreakAnim(int anim); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern qboolean PM_KnockDownAnim(int anim); +extern qboolean PM_SaberInKata(saberMoveName_t saberMove); +extern qboolean PM_StabDownAnim(int anim); +extern int PM_PowerLevelForSaberAnim(playerState_t *ps, int saberNum = 0); +extern void PM_VelocityForSaberMove(playerState_t *ps, vec3_t throwDir); +extern qboolean PM_VelocityForBlockedMove(playerState_t *ps, vec3_t throwDir); +extern qboolean PM_SaberCanInterruptMove(int move, int anim); +extern int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType); +extern qboolean Jedi_DodgeEvasion(gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc); +extern void Jedi_PlayDeflectSound(gentity_t *self); +extern void Jedi_PlayBlockedPushSound(gentity_t *self); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern void Jedi_Ambush(gentity_t *self); +extern qboolean Jedi_SaberBusy(gentity_t *self); +extern qboolean Jedi_CultistDestroyer(gentity_t *self); +extern qboolean Boba_Flying(gentity_t *self); +extern void JET_FlyStart(gentity_t *self); +extern void Boba_DoFlameThrower(gentity_t *self); +extern void Boba_StopFlameThrower(gentity_t *self); + +extern Vehicle_t *G_IsRidingVehicle(gentity_t *ent); +extern int SaberDroid_PowerLevelForSaberAnim(gentity_t *self); +extern qboolean G_ValidEnemy(gentity_t *self, gentity_t *enemy); +extern void G_StartMatrixEffect(gentity_t *ent, int meFlags = 0, int length = 1000, float timeScale = 0.0f, int spinTime = 0); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_KnockOffVehicle(gentity_t *pRider, gentity_t *self, qboolean bPull); +extern qboolean PM_LockedAnim(int anim); +extern qboolean Rosh_BeingHealed(gentity_t *self); +extern qboolean G_OkayToLean(playerState_t *ps, usercmd_t *cmd, qboolean interruptOkay); int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacker, int atPower, int atPowerLevel, int atForceSpent); -void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_SaberInFlightReflectCheck( gentity_t *self, usercmd_t *ucmd ); - -void WP_SaberDrop( gentity_t *self, gentity_t *saber ); -qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -void WP_SaberReturn( gentity_t *self, gentity_t *saber ); -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ); -qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_DeactivateSaber( gentity_t *self, qboolean clearLength = qfalse ); -qboolean FP_ForceDrainGrippableEnt( gentity_t *victim ); - -extern cvar_t *g_saberAutoBlocking; -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *g_saberDamageCapping; -extern cvar_t *g_saberNewControlScheme; +void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_SaberInFlightReflectCheck(gentity_t *self, usercmd_t *ucmd); + +void WP_SaberDrop(gentity_t *self, gentity_t *saber); +qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +void WP_SaberReturn(gentity_t *self, gentity_t *saber); +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock); +qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_DeactivateSaber(gentity_t *self, qboolean clearLength = qfalse); +qboolean FP_ForceDrainGrippableEnt(gentity_t *victim); + +extern cvar_t *g_saberAutoBlocking; +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *g_saberDamageCapping; +extern cvar_t *g_saberNewControlScheme; extern int g_crosshairEntNum; qboolean g_saberNoEffects = qfalse; qboolean g_noClashFlare = qfalse; -int g_saberFlashTime = 0; -vec3_t g_saberFlashPos = {0,0,0}; - -int forcePowerDarkLight[NUM_FORCE_POWERS] = //0 == neutral -{ //nothing should be usable at rank 0.. - FORCE_LIGHTSIDE,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - FORCE_LIGHTSIDE,//FP_TELEPATHY,//instant - FORCE_DARKSIDE,//FP_GRIP,//hold/duration - FORCE_DARKSIDE,//FP_LIGHTNING,//hold/duration - 0,//FP_SABERATTACK, - 0,//FP_SABERDEFEND, - 0,//FP_SABERTHROW, - //new Jedi Academy powers - FORCE_DARKSIDE,//FP_RAGE,//duration - FORCE_LIGHTSIDE,//FP_PROTECT,//duration - FORCE_LIGHTSIDE,//FP_ABSORB,//duration - FORCE_DARKSIDE,//FP_DRAIN,//hold/duration - 0,//FP_SEE,//duration - //NUM_FORCE_POWERS +int g_saberFlashTime = 0; +vec3_t g_saberFlashPos = {0, 0, 0}; + +int forcePowerDarkLight[NUM_FORCE_POWERS] = // 0 == neutral + { + // nothing should be usable at rank 0.. + FORCE_LIGHTSIDE, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + FORCE_LIGHTSIDE, // FP_TELEPATHY,//instant + FORCE_DARKSIDE, // FP_GRIP,//hold/duration + FORCE_DARKSIDE, // FP_LIGHTNING,//hold/duration + 0, // FP_SABERATTACK, + 0, // FP_SABERDEFEND, + 0, // FP_SABERTHROW, + // new Jedi Academy powers + FORCE_DARKSIDE, // FP_RAGE,//duration + FORCE_LIGHTSIDE, // FP_PROTECT,//duration + FORCE_LIGHTSIDE, // FP_ABSORB,//duration + FORCE_DARKSIDE, // FP_DRAIN,//hold/duration + 0, // FP_SEE,//duration + // NUM_FORCE_POWERS }; -int forcePowerNeeded[NUM_FORCE_POWERS] = -{ - 0,//FP_HEAL,//instant - 10,//FP_LEVITATION,//hold/duration - 50,//FP_SPEED,//duration - 15,//FP_PUSH,//hold/duration - 15,//FP_PULL,//hold/duration - 20,//FP_TELEPATHY,//instant - 1,//FP_GRIP,//hold/duration - FIXME: 30? - 1,//FP_LIGHTNING,//hold/duration - 20,//FP_SABERTHROW, - 1,//FP_SABER_DEFENSE, - 0,//FP_SABER_OFFENSE, - //new Jedi Academy powers - 50,//FP_RAGE,//duration - speed, invincibility and extra damage for short period, drains your health and leaves you weak and slow afterwards. - 30,//FP_PROTECT,//duration - protect against physical/energy (level 1 stops blaster/energy bolts, level 2 stops projectiles, level 3 protects against explosions) - 30,//FP_ABSORB,//duration - protect against dark force powers (grip, lightning, drain) - 1,//FP_DRAIN,//hold/duration - drain force power for health - 20//FP_SEE,//duration - detect/see hidden enemies - //NUM_FORCE_POWERS +int forcePowerNeeded[NUM_FORCE_POWERS] = { + 0, // FP_HEAL,//instant + 10, // FP_LEVITATION,//hold/duration + 50, // FP_SPEED,//duration + 15, // FP_PUSH,//hold/duration + 15, // FP_PULL,//hold/duration + 20, // FP_TELEPATHY,//instant + 1, // FP_GRIP,//hold/duration - FIXME: 30? + 1, // FP_LIGHTNING,//hold/duration + 20, // FP_SABERTHROW, + 1, // FP_SABER_DEFENSE, + 0, // FP_SABER_OFFENSE, + // new Jedi Academy powers + 50, // FP_RAGE,//duration - speed, invincibility and extra damage for short period, drains your health and leaves you weak and slow afterwards. + 30, // FP_PROTECT,//duration - protect against physical/energy (level 1 stops blaster/energy bolts, level 2 stops projectiles, level 3 protects against + // explosions) + 30, // FP_ABSORB,//duration - protect against dark force powers (grip, lightning, drain) + 1, // FP_DRAIN,//hold/duration - drain force power for health + 20 // FP_SEE,//duration - detect/see hidden enemies + // NUM_FORCE_POWERS }; -float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = -{ - JUMP_VELOCITY,//normal jump - 420, - 590, - 840 -}; +float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = {JUMP_VELOCITY, // normal jump + 420, 590, 840}; -float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = -{ - 32,//normal jump (+stepheight+crouchdiff = 66) - 96,//(+stepheight+crouchdiff = 130) - 192,//(+stepheight+crouchdiff = 226) - 384//(+stepheight+crouchdiff = 418) +float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = { + 32, // normal jump (+stepheight+crouchdiff = 66) + 96, //(+stepheight+crouchdiff = 130) + 192, //(+stepheight+crouchdiff = 226) + 384 //(+stepheight+crouchdiff = 418) }; -float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = -{ - 66,//normal jump (32+stepheight(18)+crouchdiff(24) = 74) - 130,//(96+stepheight(18)+crouchdiff(24) = 138) - 226,//(192+stepheight(18)+crouchdiff(24) = 234) - 418//(384+stepheight(18)+crouchdiff(24) = 426) +float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = { + 66, // normal jump (32+stepheight(18)+crouchdiff(24) = 74) + 130, //(96+stepheight(18)+crouchdiff(24) = 138) + 226, //(192+stepheight(18)+crouchdiff(24) = 234) + 418 //(384+stepheight(18)+crouchdiff(24) = 426) }; -float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 384,//256, - 448,//384, - 512 -}; +float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = {0, // none + 384, // 256, + 448, // 384, + 512}; -float forcePushCone[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 1.0f, - 0.8f, - 0.6f -}; +float forcePushCone[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 1.0f, 0.8f, 0.6f}; -float forcePullCone[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 1.0f, - 1.0f, - 0.8f -}; +float forcePullCone[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 1.0f, 1.0f, 0.8f}; -float forceSpeedValue[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 0.75f, - 0.5f, - 0.25f -}; +float forceSpeedValue[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 0.75f, 0.5f, 0.25f}; -float forceSpeedRangeMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//none - 30.0f, - 45.0f, - 60.0f -}; +float forceSpeedRangeMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // none + 30.0f, 45.0f, 60.0f}; -float forceSpeedFOVMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//none - 20.0f, - 30.0f, - 40.0f -}; +float forceSpeedFOVMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // none + 20.0f, 30.0f, 40.0f}; -int forceGripDamage[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 0, - 6, - 9 -}; +int forceGripDamage[NUM_FORCE_POWER_LEVELS] = {0, // none + 0, 6, 9}; -int mindTrickTime[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 10000,//5000, - 15000,//10000, - 30000//15000 +int mindTrickTime[NUM_FORCE_POWER_LEVELS] = { + 0, // none + 10000, // 5000, + 15000, // 10000, + 30000 // 15000 }; -//NOTE: keep in synch with table below!!! -int saberThrowDist[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 256, - 400, - 400 -}; +// NOTE: keep in synch with table below!!! +int saberThrowDist[NUM_FORCE_POWER_LEVELS] = {0, // none + 256, 400, 400}; -//NOTE: keep in synch with table above!!! -int saberThrowDistSquared[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 65536, - 160000, - 160000 -}; +// NOTE: keep in synch with table above!!! +int saberThrowDistSquared[NUM_FORCE_POWER_LEVELS] = {0, // none + 65536, 160000, 160000}; -int parryDebounce[NUM_FORCE_POWER_LEVELS] = -{ - 500,//if don't even have defense, can't use defense! - 300, - 150, - 50 -}; +int parryDebounce[NUM_FORCE_POWER_LEVELS] = {500, // if don't even have defense, can't use defense! + 300, 150, 50}; -float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//if don't even have offense, can't use offense! - 0.75f, - 1.0f, - 2.0f -}; +float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // if don't even have offense, can't use offense! + 0.75f, 1.0f, 2.0f}; -stringID_table_t SaberStyleTable[] = -{ - { "NULL",SS_NONE }, - ENUM2STRING(SS_FAST), - { "fast",SS_FAST }, - ENUM2STRING(SS_MEDIUM), - { "medium",SS_MEDIUM }, - ENUM2STRING(SS_STRONG), - { "strong",SS_STRONG }, - ENUM2STRING(SS_DESANN), - { "desann",SS_DESANN }, - ENUM2STRING(SS_TAVION), - { "tavion",SS_TAVION }, - ENUM2STRING(SS_DUAL), - { "dual",SS_DUAL }, - ENUM2STRING(SS_STAFF), - { "staff",SS_STAFF }, - { "", 0 }, +stringID_table_t SaberStyleTable[] = { + {"NULL", SS_NONE}, ENUM2STRING(SS_FAST), {"fast", SS_FAST}, ENUM2STRING(SS_MEDIUM), + {"medium", SS_MEDIUM}, ENUM2STRING(SS_STRONG), {"strong", SS_STRONG}, ENUM2STRING(SS_DESANN), + {"desann", SS_DESANN}, ENUM2STRING(SS_TAVION), {"tavion", SS_TAVION}, ENUM2STRING(SS_DUAL), + {"dual", SS_DUAL}, ENUM2STRING(SS_STAFF), {"staff", SS_STAFF}, {"", 0}, }; -//SABER INITIALIZATION====================================================================== +// SABER INITIALIZATION====================================================================== -void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *psWeaponModel, int boltNum, int weaponNum ) -{ - if (!psWeaponModel) - { - assert (psWeaponModel); +void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *psWeaponModel, int boltNum, int weaponNum) { + if (!psWeaponModel) { + assert(psWeaponModel); return; } - if ( ent->playerModel == -1 ) - { + if (ent->playerModel == -1) { return; } - if ( boltNum == -1 ) - { + if (boltNum == -1) { return; } - if ( ent && ent->client && ent->client->NPC_class == CLASS_GALAKMECH ) - {//hack for galakmech, no weaponmodel + if (ent && ent->client && ent->client->NPC_class == CLASS_GALAKMECH) { // hack for galakmech, no weaponmodel ent->weaponModel[0] = ent->weaponModel[1] = -1; return; } - if ( weaponNum < 0 || weaponNum >= MAX_INHAND_WEAPONS ) - { + if (weaponNum < 0 || weaponNum >= MAX_INHAND_WEAPONS) { return; } char weaponModel[64]; - strcpy (weaponModel, psWeaponModel); - if (char *spot = strstr(weaponModel, ".md3") ) { + strcpy(weaponModel, psWeaponModel); + if (char *spot = strstr(weaponModel, ".md3")) { *spot = 0; - spot = strstr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on - if (!spot&&!strstr(weaponModel, "noweap")) - { - strcat (weaponModel, "_w"); + spot = strstr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on + if (!spot && !strstr(weaponModel, "noweap")) { + strcat(weaponModel, "_w"); } - strcat (weaponModel, ".glm"); //and change to ghoul2 + strcat(weaponModel, ".glm"); // and change to ghoul2 } // give us a saber model - int wModelIndex = G_ModelIndex( weaponModel ); - if ( wModelIndex ) - { - ent->weaponModel[weaponNum] = gi.G2API_InitGhoul2Model(ent->ghoul2, weaponModel, wModelIndex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - if ( ent->weaponModel[weaponNum] != -1 ) - { + int wModelIndex = G_ModelIndex(weaponModel); + if (wModelIndex) { + ent->weaponModel[weaponNum] = gi.G2API_InitGhoul2Model(ent->ghoul2, weaponModel, wModelIndex, NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->weaponModel[weaponNum] != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->weaponModel[weaponNum]], &ent->ghoul2[ent->playerModel], - boltNum, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->weaponModel[weaponNum]], &ent->ghoul2[ent->playerModel], boltNum, ent->playerModel); // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 gi.G2API_AddBolt(&ent->ghoul2[ent->weaponModel[weaponNum]], "*flash"); - //gi.G2API_SetLodBias( &ent->ghoul2[ent->weaponModel[weaponNum]], 0 ); + // gi.G2API_SetLodBias( &ent->ghoul2[ent->weaponModel[weaponNum]], 0 ); } } - } -void WP_SaberAddG2SaberModels( gentity_t *ent, int specificSaberNum ) -{ +void WP_SaberAddG2SaberModels(gentity_t *ent, int specificSaberNum) { int saberNum = 0, maxSaber = 1; - if ( specificSaberNum != -1 && specificSaberNum <= maxSaber ) - { + if (specificSaberNum != -1 && specificSaberNum <= maxSaber) { saberNum = maxSaber = specificSaberNum; } - for ( ; saberNum <= maxSaber; saberNum++ ) - { - if ( ent->weaponModel[saberNum] > 0 ) - {//we already have a weapon model in this slot - //remove it - gi.G2API_SetSkin( &ent->ghoul2[ent->weaponModel[saberNum]], -1, 0 ); - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[saberNum] ); + for (; saberNum <= maxSaber; saberNum++) { + if (ent->weaponModel[saberNum] > 0) { // we already have a weapon model in this slot + // remove it + gi.G2API_SetSkin(&ent->ghoul2[ent->weaponModel[saberNum]], -1, 0); + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[saberNum]); ent->weaponModel[saberNum] = -1; } - if ( saberNum > 0 ) - {//second saber - if ( !ent->client->ps.dualSabers - || G_IsRidingVehicle( ent ) ) - {//only have one saber or riding a vehicle and can only use one saber + if (saberNum > 0) { // second saber + if (!ent->client->ps.dualSabers || G_IsRidingVehicle(ent)) { // only have one saber or riding a vehicle and can only use one saber return; } - } - else if ( saberNum == 0 ) - {//first saber - if ( ent->client->ps.saberInFlight ) - {//it's still out there somewhere, don't add it - //FIXME: call it back? + } else if (saberNum == 0) { // first saber + if (ent->client->ps.saberInFlight) { // it's still out there somewhere, don't add it + // FIXME: call it back? continue; } } int handBolt = ((saberNum == 0) ? ent->handRBolt : ent->handLBolt); - if ( (ent->client->ps.saber[saberNum].saberFlags&SFL_BOLT_TO_WRIST) ) - {//special case, bolt to forearm - if ( saberNum == 0 ) - { - handBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*r_hand_cap_r_arm" ); - } - else - { - handBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], "*l_hand_cap_l_arm" ); + if ((ent->client->ps.saber[saberNum].saberFlags & SFL_BOLT_TO_WRIST)) { // special case, bolt to forearm + if (saberNum == 0) { + handBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_hand_cap_r_arm"); + } else { + handBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_hand_cap_l_arm"); } } - G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[saberNum].model, handBolt, saberNum ); + G_CreateG2AttachedWeaponModel(ent, ent->client->ps.saber[saberNum].model, handBolt, saberNum); - if ( ent->client->ps.saber[saberNum].skin != NULL ) - {//if this saber has a customSkin, use it + if (ent->client->ps.saber[saberNum].skin != NULL) { // if this saber has a customSkin, use it // lets see if it's out there - int saberSkin = gi.RE_RegisterSkin( ent->client->ps.saber[saberNum].skin ); - if ( saberSkin ) - { + int saberSkin = gi.RE_RegisterSkin(ent->client->ps.saber[saberNum].skin); + if (saberSkin) { // put it in the config strings // and set the ghoul2 model to use it - gi.G2API_SetSkin( &ent->ghoul2[ent->weaponModel[saberNum]], G_SkinIndex( ent->client->ps.saber[saberNum].skin ), saberSkin ); + gi.G2API_SetSkin(&ent->ghoul2[ent->weaponModel[saberNum]], G_SkinIndex(ent->client->ps.saber[saberNum].skin), saberSkin); } } } } //---------------------------------------------------------- -void G_Throw( gentity_t *targ, const vec3_t newDir, float push ) +void G_Throw(gentity_t *targ, const vec3_t newDir, float push) //---------------------------------------------------------- { - vec3_t kvel; - float mass; + vec3_t kvel; + float mass; - if ( targ - && targ->client - && ( targ->client->NPC_class == CLASS_ATST - || targ->client->NPC_class == CLASS_RANCOR - || targ->client->NPC_class == CLASS_SAND_CREATURE ) ) - {//much to large to *ever* throw + if (targ && targ->client && + (targ->client->NPC_class == CLASS_ATST || targ->client->NPC_class == CLASS_RANCOR || + targ->client->NPC_class == CLASS_SAND_CREATURE)) { // much to large to *ever* throw return; } - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass { mass = targ->physicsBounce; - } - else - { + } else { mass = 200; } - if ( g_gravity->value > 0 ) - { - VectorScale( newDir, g_knockback->value * (float)push / mass * 0.8, kvel ); - if ( !targ->client || targ->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//give them some z lift to get them off the ground + if (g_gravity->value > 0) { + VectorScale(newDir, g_knockback->value * (float)push / mass * 0.8, kvel); + if (!targ->client || targ->client->ps.groundEntityNum != ENTITYNUM_NONE) { // give them some z lift to get them off the ground kvel[2] = newDir[2] * g_knockback->value * (float)push / mass * 1.5; } - } - else - { - VectorScale( newDir, g_knockback->value * (float)push / mass, kvel ); + } else { + VectorScale(newDir, g_knockback->value * (float)push / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = push * 2; - if ( t < 50 ) - { + if (t < 50) { t = 50; } - if ( t > 200 ) - { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -544,332 +429,227 @@ void G_Throw( gentity_t *targ, const vec3_t newDir, float push ) } } -int WP_SetSaberModel( gclient_t *client, class_t npcClass ) -{//FIXME: read from NPCs.cfg - if ( client ) - { - switch ( npcClass ) - { - case CLASS_DESANN://Desann +int WP_SetSaberModel(gclient_t *client, class_t npcClass) { // FIXME: read from NPCs.cfg + if (client) { + switch (npcClass) { + case CLASS_DESANN: // Desann client->ps.saber[0].model = "models/weapons2/saber_desann/saber_w.glm"; break; - case CLASS_LUKE://Luke + case CLASS_LUKE: // Luke client->ps.saber[0].model = "models/weapons2/saber_luke/saber_w.glm"; break; - case CLASS_PLAYER://Kyle NPC and player - case CLASS_KYLE://Kyle NPC and player + case CLASS_PLAYER: // Kyle NPC and player + case CLASS_KYLE: // Kyle NPC and player client->ps.saber[0].model = "models/weapons2/saber/saber_w.glm"; break; - default://reborn and tavion and everyone else + default: // reborn and tavion and everyone else client->ps.saber[0].model = "models/weapons2/saber_reborn/saber_w.glm"; break; } - return ( G_ModelIndex( client->ps.saber[0].model ) ); - } - else - { - switch ( npcClass ) - { - case CLASS_DESANN://Desann - return ( G_ModelIndex( "models/weapons2/saber_desann/saber_w.glm" ) ); + return (G_ModelIndex(client->ps.saber[0].model)); + } else { + switch (npcClass) { + case CLASS_DESANN: // Desann + return (G_ModelIndex("models/weapons2/saber_desann/saber_w.glm")); break; - case CLASS_LUKE://Luke - return ( G_ModelIndex( "models/weapons2/saber_luke/saber_w.glm" ) ); + case CLASS_LUKE: // Luke + return (G_ModelIndex("models/weapons2/saber_luke/saber_w.glm")); break; - case CLASS_PLAYER://Kyle NPC and player - case CLASS_KYLE://Kyle NPC and player - return ( G_ModelIndex( "models/weapons2/saber/saber_w.glm" ) ); + case CLASS_PLAYER: // Kyle NPC and player + case CLASS_KYLE: // Kyle NPC and player + return (G_ModelIndex("models/weapons2/saber/saber_w.glm")); break; - default://reborn and tavion and everyone else - return ( G_ModelIndex( "models/weapons2/saber_reborn/saber_w.glm" ) ); + default: // reborn and tavion and everyone else + return (G_ModelIndex("models/weapons2/saber_reborn/saber_w.glm")); break; } } } -void WP_SetSaberEntModelSkin( gentity_t *ent, gentity_t *saberent ) -{ - int saberModel = 0; - qboolean newModel = qfalse; - //FIXME: get saberModel from NPCs.cfg - if ( !ent->client->ps.saber[0].model ) - { - saberModel = WP_SetSaberModel( ent->client, ent->client->NPC_class ); - } - else - { - //got saberModel from NPCs.cfg - saberModel = G_ModelIndex( ent->client->ps.saber[0].model ); - } - if ( saberModel && saberent->s.modelindex != saberModel ) - { - if ( saberent->playerModel >= 0 ) - {//remove the old one, if there is one - gi.G2API_RemoveGhoul2Model( saberent->ghoul2, saberent->playerModel ); - } - //add the new one - saberent->playerModel = gi.G2API_InitGhoul2Model( saberent->ghoul2, ent->client->ps.saber[0].model, saberModel, NULL_HANDLE, NULL_HANDLE, 0, 0); +void WP_SetSaberEntModelSkin(gentity_t *ent, gentity_t *saberent) { + int saberModel = 0; + qboolean newModel = qfalse; + // FIXME: get saberModel from NPCs.cfg + if (!ent->client->ps.saber[0].model) { + saberModel = WP_SetSaberModel(ent->client, ent->client->NPC_class); + } else { + // got saberModel from NPCs.cfg + saberModel = G_ModelIndex(ent->client->ps.saber[0].model); + } + if (saberModel && saberent->s.modelindex != saberModel) { + if (saberent->playerModel >= 0) { // remove the old one, if there is one + gi.G2API_RemoveGhoul2Model(saberent->ghoul2, saberent->playerModel); + } + // add the new one + saberent->playerModel = gi.G2API_InitGhoul2Model(saberent->ghoul2, ent->client->ps.saber[0].model, saberModel, NULL_HANDLE, NULL_HANDLE, 0, 0); saberent->s.modelindex = saberModel; newModel = qtrue; } - //set skin, too - if ( ent->client->ps.saber[0].skin == NULL ) - { - gi.G2API_SetSkin( &saberent->ghoul2[0], -1, 0 ); - } - else - {//if this saber has a customSkin, use it + // set skin, too + if (ent->client->ps.saber[0].skin == NULL) { + gi.G2API_SetSkin(&saberent->ghoul2[0], -1, 0); + } else { // if this saber has a customSkin, use it // lets see if it's out there - int saberSkin = gi.RE_RegisterSkin( ent->client->ps.saber[0].skin ); - if ( saberSkin && (newModel || saberent->s.modelindex2 != saberSkin) ) - { + int saberSkin = gi.RE_RegisterSkin(ent->client->ps.saber[0].skin); + if (saberSkin && (newModel || saberent->s.modelindex2 != saberSkin)) { // put it in the config strings // and set the ghoul2 model to use it - gi.G2API_SetSkin( &saberent->ghoul2[0], G_SkinIndex( ent->client->ps.saber[0].skin ), saberSkin ); + gi.G2API_SetSkin(&saberent->ghoul2[0], G_SkinIndex(ent->client->ps.saber[0].skin), saberSkin); saberent->s.modelindex2 = saberSkin; } } } -void WP_SaberFallSound( gentity_t *owner, gentity_t *saber ) -{ - if ( !saber ) - { +void WP_SaberFallSound(gentity_t *owner, gentity_t *saber) { + if (!saber) { return; } - if ( owner && owner->client ) - {//have an owner, use their data (assume saberNum is 0 because only the 0 saber can be thrown) - if ( owner->client->ps.saber[0].fallSound[0] ) - {//have an override - G_Sound( saber, owner->client->ps.saber[0].fallSound[Q_irand( 0, 2 )] ); - } - else if ( owner->client->ps.saber[0].type == SABER_SITH_SWORD ) - {//is a sith sword - G_Sound( saber, G_SoundIndex( va( "sound/weapons/sword/fall%d.wav", Q_irand( 1, 7 ) ) ) ); - } - else - {//normal saber - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); + if (owner && owner->client) { // have an owner, use their data (assume saberNum is 0 because only the 0 saber can be thrown) + if (owner->client->ps.saber[0].fallSound[0]) { // have an override + G_Sound(saber, owner->client->ps.saber[0].fallSound[Q_irand(0, 2)]); + } else if (owner->client->ps.saber[0].type == SABER_SITH_SWORD) { // is a sith sword + G_Sound(saber, G_SoundIndex(va("sound/weapons/sword/fall%d.wav", Q_irand(1, 7)))); + } else { // normal saber + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); } - } - else if ( saber->NPC_type && saber->NPC_type[0] ) - {//have a saber name to look up + } else if (saber->NPC_type && saber->NPC_type[0]) { // have a saber name to look up saberInfo_t saberInfo; - if ( WP_SaberParseParms( saber->NPC_type, &saberInfo ) ) - {//found it - if ( saberInfo.fallSound[0] ) - {//have an override sound - G_Sound( saber, saberInfo.fallSound[Q_irand( 0, 2 )] ); - } - else if ( saberInfo.type == SABER_SITH_SWORD ) - {//is a sith sword - G_Sound( saber, G_SoundIndex( va( "sound/weapons/sword/fall%d.wav", Q_irand( 1, 7 ) ) ) ); - } - else - {//normal saber - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); + if (WP_SaberParseParms(saber->NPC_type, &saberInfo)) { // found it + if (saberInfo.fallSound[0]) { // have an override sound + G_Sound(saber, saberInfo.fallSound[Q_irand(0, 2)]); + } else if (saberInfo.type == SABER_SITH_SWORD) { // is a sith sword + G_Sound(saber, G_SoundIndex(va("sound/weapons/sword/fall%d.wav", Q_irand(1, 7)))); + } else { // normal saber + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); } + } else { // can't find it + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); } - else - {//can't find it - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); - } - } - else - {//no saber name specified - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); + } else { // no saber name specified + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); } } -void WP_SaberSwingSound( gentity_t *ent, int saberNum, swingType_t swingType ) -{ +void WP_SaberSwingSound(gentity_t *ent, int saberNum, swingType_t swingType) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - if ( swingType == SWING_FAST ) - { - index = Q_irand( 1, 3 ); - } - else if ( swingType == SWING_MEDIUM ) - { - index = Q_irand( 4, 6 ); - } - else if ( swingType == SWING_STRONG ) - { - index = Q_irand( 7, 9 ); + if (swingType == SWING_FAST) { + index = Q_irand(1, 3); + } else if (swingType == SWING_MEDIUM) { + index = Q_irand(4, 6); + } else if (swingType == SWING_STRONG) { + index = Q_irand(7, 9); } - if ( ent->client->ps.saber[saberNum].swingSound[0] ) - { - G_SoundIndexOnEnt( ent, CHAN_WEAPON, ent->client->ps.saber[saberNum].swingSound[Q_irand( 0, 2 )] ); - } - else if ( ent->client->ps.saber[saberNum].type == SABER_SITH_SWORD ) - { - G_SoundOnEnt( ent, CHAN_WEAPON, va( "sound/weapons/sword/swing%d.wav", Q_irand( 1, 4 ) ) ); - } - else - { - G_SoundOnEnt( ent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", index ) ); + if (ent->client->ps.saber[saberNum].swingSound[0]) { + G_SoundIndexOnEnt(ent, CHAN_WEAPON, ent->client->ps.saber[saberNum].swingSound[Q_irand(0, 2)]); + } else if (ent->client->ps.saber[saberNum].type == SABER_SITH_SWORD) { + G_SoundOnEnt(ent, CHAN_WEAPON, va("sound/weapons/sword/swing%d.wav", Q_irand(1, 4))); + } else { + G_SoundOnEnt(ent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", index)); } } -void WP_SaberHitSound( gentity_t *ent, int saberNum, int bladeNum ) -{ +void WP_SaberHitSound(gentity_t *ent, int saberNum, int bladeNum) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - index = Q_irand( 1, 3 ); + index = Q_irand(1, 3); - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hitSound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].hitSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hit2Sound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].hit2Sound[Q_irand( 0, 2 )] ); - } - else if ( ent->client->ps.saber[saberNum].type == SABER_SITH_SWORD ) - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/sword/stab%d.wav", Q_irand( 1, 4 ) ) ) ); - } - else - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberhit%d.wav", index ) ) ); + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].hitSound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].hitSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].hit2Sound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].hit2Sound[Q_irand(0, 2)]); + } else if (ent->client->ps.saber[saberNum].type == SABER_SITH_SWORD) { + G_Sound(ent, G_SoundIndex(va("sound/weapons/sword/stab%d.wav", Q_irand(1, 4)))); + } else { + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberhit%d.wav", index))); } } -void WP_SaberBlockSound( gentity_t *ent, gentity_t *hitEnt, int saberNum, int bladeNum ) -{ +void WP_SaberBlockSound(gentity_t *ent, gentity_t *hitEnt, int saberNum, int bladeNum) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - index = Q_irand( 1, 9 ); + index = Q_irand(1, 9); - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].blockSound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].blockSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].block2Sound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].block2Sound[Q_irand( 0, 2 )] ); - } - else - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", index ) ) ); + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].blockSound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].blockSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].block2Sound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].block2Sound[Q_irand(0, 2)]); + } else { + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", index))); } } - -void WP_SaberBounceOnWallSound( gentity_t *ent, int saberNum, int bladeNum ) -{ +void WP_SaberBounceOnWallSound(gentity_t *ent, int saberNum, int bladeNum) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - index = Q_irand( 1, 9 ); + index = Q_irand(1, 9); - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].bounceSound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].bounceSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].bounce2Sound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].bounce2Sound[Q_irand( 0, 2 )] ); - } - else if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].blockSound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].blockSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].block2Sound[0] ) - { - G_Sound( ent, ent->client->ps.saber[saberNum].block2Sound[Q_irand( 0, 2 )] ); - } - else - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", index ) ) ); + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].bounceSound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].bounceSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].bounce2Sound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].bounce2Sound[Q_irand(0, 2)]); + } else if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].blockSound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].blockSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].block2Sound[0]) { + G_Sound(ent, ent->client->ps.saber[saberNum].block2Sound[Q_irand(0, 2)]); + } else { + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", index))); } } -void WP_SaberBounceSound( gentity_t *ent, gentity_t *hitEnt, gentity_t *playOnEnt, int saberNum, int bladeNum, qboolean doForce ) -{ +void WP_SaberBounceSound(gentity_t *ent, gentity_t *hitEnt, gentity_t *playOnEnt, int saberNum, int bladeNum, qboolean doForce) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - index = Q_irand( 1, 3 ); + index = Q_irand(1, 3); - if ( !playOnEnt ) - { + if (!playOnEnt) { playOnEnt = ent; } - //NOTE: we don't allow overriding of the saberbounce sound, but since it's just a variant on the saberblock sound, we use that as the override - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].blockSound[0] ) - { - G_Sound( playOnEnt, ent->client->ps.saber[saberNum].blockSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].block2Sound[0] ) - { - G_Sound( playOnEnt, ent->client->ps.saber[saberNum].block2Sound[Q_irand( 0, 2 )] ); - } - else - { - G_Sound( playOnEnt, G_SoundIndex( va( "sound/weapons/saber/saberbounce%d.wav", index ) ) ); + // NOTE: we don't allow overriding of the saberbounce sound, but since it's just a variant on the saberblock sound, we use that as the override + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].blockSound[0]) { + G_Sound(playOnEnt, ent->client->ps.saber[saberNum].blockSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].block2Sound[0]) { + G_Sound(playOnEnt, ent->client->ps.saber[saberNum].block2Sound[Q_irand(0, 2)]); + } else { + G_Sound(playOnEnt, G_SoundIndex(va("sound/weapons/saber/saberbounce%d.wav", index))); } } -int WP_SaberInitBladeData( gentity_t *ent ) -{ - if ( !ent->client ) - { +int WP_SaberInitBladeData(gentity_t *ent) { + if (!ent->client) { return 0; } - if ( 1 ) - { - VectorClear( ent->client->renderInfo.muzzlePoint ); - VectorClear( ent->client->renderInfo.muzzlePointOld ); - //VectorClear( ent->client->renderInfo.muzzlePointNext ); - VectorClear( ent->client->renderInfo.muzzleDir ); - VectorClear( ent->client->renderInfo.muzzleDirOld ); - //VectorClear( ent->client->renderInfo.muzzleDirNext ); - for ( int saberNum = 0; saberNum < MAX_SABERS; saberNum++ ) - { - for ( int bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++ ) - { - VectorClear( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint ); - VectorClear( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld ); - VectorClear( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir ); - VectorClear( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld ); + if (1) { + VectorClear(ent->client->renderInfo.muzzlePoint); + VectorClear(ent->client->renderInfo.muzzlePointOld); + // VectorClear( ent->client->renderInfo.muzzlePointNext ); + VectorClear(ent->client->renderInfo.muzzleDir); + VectorClear(ent->client->renderInfo.muzzleDirOld); + // VectorClear( ent->client->renderInfo.muzzleDirNext ); + for (int saberNum = 0; saberNum < MAX_SABERS; saberNum++) { + for (int bladeNum = 0; bladeNum < MAX_BLADES; bladeNum++) { + VectorClear(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint); + VectorClear(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld); + VectorClear(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir); + VectorClear(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld); ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld = ent->client->ps.saber[saberNum].blade[bladeNum].length = 0; - if ( !ent->client->ps.saber[saberNum].blade[bladeNum].lengthMax ) - { - if ( ent->client->NPC_class == CLASS_DESANN ) - {//longer saber + if (!ent->client->ps.saber[saberNum].blade[bladeNum].lengthMax) { + if (ent->client->NPC_class == CLASS_DESANN) { // longer saber ent->client->ps.saber[saberNum].blade[bladeNum].lengthMax = 48; - } - else if ( ent->client->NPC_class == CLASS_REBORN ) - {//shorter saber + } else if (ent->client->NPC_class == CLASS_REBORN) { // shorter saber ent->client->ps.saber[saberNum].blade[bladeNum].lengthMax = 32; - } - else - {//standard saber length + } else { // standard saber length ent->client->ps.saber[saberNum].blade[bladeNum].lengthMax = 40; } } @@ -877,95 +657,64 @@ int WP_SaberInitBladeData( gentity_t *ent ) } ent->client->ps.saberLockEnemy = ENTITYNUM_NONE; ent->client->ps.saberLockTime = 0; - if ( ent->s.number ) - { - if ( !ent->client->ps.saberAnimLevel ) - { - if ( ent->client->NPC_class == CLASS_DESANN ) - { + if (ent->s.number) { + if (!ent->client->ps.saberAnimLevel) { + if (ent->client->NPC_class == CLASS_DESANN) { ent->client->ps.saberAnimLevel = SS_DESANN; - } - else if ( ent->client->NPC_class == CLASS_TAVION ) - { + } else if (ent->client->NPC_class == CLASS_TAVION) { ent->client->ps.saberAnimLevel = SS_TAVION; - } - else if ( ent->client->NPC_class == CLASS_ALORA ) - { + } else if (ent->client->NPC_class == CLASS_ALORA) { ent->client->ps.saberAnimLevel = SS_DUAL; } - //FIXME: CLASS_CULTIST instead of this Q_stricmpn? - else if ( !Q_stricmpn( "cultist", ent->NPC_type, 7 ) ) - {//should already be set in the .npc file - ent->client->ps.saberAnimLevel = Q_irand( SS_FAST, SS_STRONG ); - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && (ent->NPC->rank == RANK_CIVILIAN || ent->NPC->rank == RANK_LT_JG) ) - {//grunt and fencer always uses quick attacks + // FIXME: CLASS_CULTIST instead of this Q_stricmpn? + else if (!Q_stricmpn("cultist", ent->NPC_type, 7)) { // should already be set in the .npc file + ent->client->ps.saberAnimLevel = Q_irand(SS_FAST, SS_STRONG); + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && + (ent->NPC->rank == RANK_CIVILIAN || ent->NPC->rank == RANK_LT_JG)) { // grunt and fencer always uses quick attacks ent->client->ps.saberAnimLevel = SS_FAST; - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && (ent->NPC->rank == RANK_CREWMAN || ent->NPC->rank == RANK_ENSIGN) ) - {//acrobat & force-users always use medium attacks + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && + (ent->NPC->rank == RANK_CREWMAN || ent->NPC->rank == RANK_ENSIGN)) { // acrobat & force-users always use medium attacks ent->client->ps.saberAnimLevel = SS_MEDIUM; - } - else if ( ent->client->playerTeam == TEAM_ENEMY && ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//shadowtroopers - ent->client->ps.saberAnimLevel = Q_irand( SS_FAST, SS_STRONG ); - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && ent->NPC->rank == RANK_LT ) - {//boss always starts with strong attacks + } else if (ent->client->playerTeam == TEAM_ENEMY && ent->client->NPC_class == CLASS_SHADOWTROOPER) { // shadowtroopers + ent->client->ps.saberAnimLevel = Q_irand(SS_FAST, SS_STRONG); + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && ent->NPC->rank == RANK_LT) { // boss always starts with strong attacks ent->client->ps.saberAnimLevel = SS_STRONG; - } - else if ( ent->client->NPC_class == CLASS_PLAYER ) - { + } else if (ent->client->NPC_class == CLASS_PLAYER) { ent->client->ps.saberAnimLevel = g_entities[0].client->ps.saberAnimLevel; - } - else - {//? - ent->client->ps.saberAnimLevel = Q_irand( SS_FAST, SS_STRONG ); + } else { //? + ent->client->ps.saberAnimLevel = Q_irand(SS_FAST, SS_STRONG); } } - } - else - { - if ( !ent->client->ps.saberAnimLevel ) - {//initialize, but don't reset - if (ent->s.number < MAX_CLIENTS) - { - if (!ent->client->ps.saberStylesKnown) - { - ent->client->ps.saberStylesKnown = (1<client->ps.saberAnimLevel) { // initialize, but don't reset + if (ent->s.number < MAX_CLIENTS) { + if (!ent->client->ps.saberStylesKnown) { + ent->client->ps.saberStylesKnown = (1 << SS_MEDIUM); } - - if (ent->client->ps.saberStylesKnown & (1<client->ps.saberStylesKnown & (1 << SS_FAST)) { ent->client->ps.saberAnimLevel = SS_FAST; - } - else if (ent->client->ps.saberStylesKnown & (1<client->ps.saberStylesKnown & (1 << SS_STRONG)) { ent->client->ps.saberAnimLevel = SS_STRONG; - } - else - { + } else { ent->client->ps.saberAnimLevel = SS_MEDIUM; } - } - else - { + } else { ent->client->ps.saberAnimLevel = SS_MEDIUM; } } cg.saberAnimLevelPending = ent->client->ps.saberAnimLevel; - if ( ent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0 ) - {//let missionStats know that we actually do have the saber, even if we never use it + if (ent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0) { // let missionStats know that we actually do have the saber, even if we never use it ent->client->sess.missionStats.weaponUsed[WP_SABER] = 1; } } ent->client->ps.saberAttackChainCount = 0; - if ( ent->client->ps.saberEntityNum <= 0 || ent->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//FIXME: if you do have a saber already, be sure to re-set the model if it's changed (say, via a script). + if (ent->client->ps.saberEntityNum <= 0 || + ent->client->ps.saberEntityNum >= + ENTITYNUM_WORLD) { // FIXME: if you do have a saber already, be sure to re-set the model if it's changed (say, via a script). gentity_t *saberent = G_Spawn(); ent->client->ps.saberEntityNum = saberent->s.number; saberent->classname = "lightsaber"; @@ -975,40 +724,39 @@ int WP_SaberInitBladeData( gentity_t *ent ) saberent->s.weapon = WP_SABER; saberent->owner = ent; saberent->s.otherEntityNum = ent->s.number; - //clear the enemy + // clear the enemy saberent->enemy = NULL; saberent->clipmask = MASK_SOLID | CONTENTS_LIGHTSABER; - saberent->contents = CONTENTS_LIGHTSABER;//|CONTENTS_SHOTCLIP; + saberent->contents = CONTENTS_LIGHTSABER; //|CONTENTS_SHOTCLIP; - VectorSet( saberent->mins, -3.0f, -3.0f, -3.0f ); - VectorSet( saberent->maxs, 3.0f, 3.0f, 3.0f ); - saberent->mass = 10;//necc? + VectorSet(saberent->mins, -3.0f, -3.0f, -3.0f); + VectorSet(saberent->maxs, 3.0f, 3.0f, 3.0f); + saberent->mass = 10; // necc? saberent->s.eFlags |= EF_NODRAW; saberent->svFlags |= SVF_NOCLIENT; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ saberent->playerModel = -1; - WP_SetSaberEntModelSkin( ent, saberent ); + WP_SetSaberEntModelSkin(ent, saberent); // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 - gi.G2API_AddBolt( &saberent->ghoul2[0], "*flash" ); - //gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); - if ( ent->client->ps.dualSabers ) - { - //int saber2 = - G_ModelIndex( ent->client->ps.saber[1].model ); - //gi.G2API_InitGhoul2Model( saberent->ghoul2, ent->client->ps.saber[1].model, saber2 ); - // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 - //gi.G2API_AddBolt( &saberent->ghoul2[0], "*flash" ); - //gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); + gi.G2API_AddBolt(&saberent->ghoul2[0], "*flash"); + // gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); + if (ent->client->ps.dualSabers) { + // int saber2 = + G_ModelIndex(ent->client->ps.saber[1].model); + // gi.G2API_InitGhoul2Model( saberent->ghoul2, ent->client->ps.saber[1].model, saber2 ); + // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 + // gi.G2API_AddBolt( &saberent->ghoul2[0], "*flash" ); + // gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ ent->client->ps.saberInFlight = qfalse; ent->client->ps.saberEntityDist = 0; @@ -1016,55 +764,43 @@ Ghoul2 Insert End ent->client->ps.saberMove = ent->client->ps.saberMoveNext = LS_NONE; - //FIXME: need a think function to create alerts when turned on or is on, etc. + // FIXME: need a think function to create alerts when turned on or is on, etc. + } else { // already have one, might just be changing sabers, register the model and skin and use them if different from what we're using now. + WP_SetSaberEntModelSkin(ent, &g_entities[ent->client->ps.saberEntityNum]); } - else - {//already have one, might just be changing sabers, register the model and skin and use them if different from what we're using now. - WP_SetSaberEntModelSkin( ent, &g_entities[ent->client->ps.saberEntityNum] ); - } - } - else - { + } else { ent->client->ps.saberEntityNum = ENTITYNUM_NONE; ent->client->ps.saberInFlight = qfalse; ent->client->ps.saberEntityDist = 0; ent->client->ps.saberEntityState = SES_LEAVING; } - if ( ent->client->ps.dualSabers ) - { + if (ent->client->ps.dualSabers) { return 2; } return 1; } -void WP_SaberUpdateOldBladeData( gentity_t *ent ) -{ - if ( ent->client ) - { +void WP_SaberUpdateOldBladeData(gentity_t *ent) { + if (ent->client) { qboolean didEvent = qfalse; - for ( int saberNum = 0; saberNum < 2; saberNum++ ) - { - for ( int bladeNum = 0; bladeNum < ent->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld ); - if ( !didEvent ) - { - if ( ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld <= 0 && ent->client->ps.saber[saberNum].blade[bladeNum].length > 0 ) - {//just turned on - //do sound event - vec3_t saberOrg; - VectorCopy( g_entities[ent->client->ps.saberEntityNum].currentOrigin, saberOrg ); - if ( (!ent->client->ps.saberInFlight && ent->client->ps.groundEntityNum == ENTITYNUM_WORLD)//holding saber and on ground - || g_entities[ent->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY )//saber out there somewhere and on ground - {//a ground alert - AddSoundEvent( ent, saberOrg, 256, AEL_SUSPICIOUS, qfalse, qtrue ); - } - else - {//an in-air alert - AddSoundEvent( ent, saberOrg, 256, AEL_SUSPICIOUS ); + for (int saberNum = 0; saberNum < 2; saberNum++) { + for (int bladeNum = 0; bladeNum < ent->client->ps.saber[saberNum].numBlades; bladeNum++) { + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld); + if (!didEvent) { + if (ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld <= 0 && + ent->client->ps.saber[saberNum].blade[bladeNum].length > 0) { // just turned on + // do sound event + vec3_t saberOrg; + VectorCopy(g_entities[ent->client->ps.saberEntityNum].currentOrigin, saberOrg); + if ((!ent->client->ps.saberInFlight && ent->client->ps.groundEntityNum == ENTITYNUM_WORLD) // holding saber and on ground + || g_entities[ent->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) // saber out there somewhere and on ground + { // a ground alert + AddSoundEvent(ent, saberOrg, 256, AEL_SUSPICIOUS, qfalse, qtrue); + } else { // an in-air alert + AddSoundEvent(ent, saberOrg, 256, AEL_SUSPICIOUS); } didEvent = qtrue; } @@ -1072,502 +808,374 @@ void WP_SaberUpdateOldBladeData( gentity_t *ent ) ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld = ent->client->ps.saber[saberNum].blade[bladeNum].length; } } - VectorCopy( ent->client->renderInfo.muzzlePoint, ent->client->renderInfo.muzzlePointOld ); - VectorCopy( ent->client->renderInfo.muzzleDir, ent->client->renderInfo.muzzleDirOld ); + VectorCopy(ent->client->renderInfo.muzzlePoint, ent->client->renderInfo.muzzlePointOld); + VectorCopy(ent->client->renderInfo.muzzleDir, ent->client->renderInfo.muzzleDirOld); } } - - -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -int WPDEBUG_SaberColor( saber_colors_t saberColor ) -{ - switch( (int)(saberColor) ) - { - case SABER_RED: - return 0x000000ff; - break; - case SABER_ORANGE: - return 0x000088ff; - break; - case SABER_YELLOW: - return 0x0000ffff; - break; - case SABER_GREEN: - return 0x0000ff00; - break; - case SABER_BLUE: - return 0x00ff0000; - break; - case SABER_PURPLE: - return 0x00ff00ff; - break; - default: - return 0x00ffffff;//white - break; +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +int WPDEBUG_SaberColor(saber_colors_t saberColor) { + switch ((int)(saberColor)) { + case SABER_RED: + return 0x000000ff; + break; + case SABER_ORANGE: + return 0x000088ff; + break; + case SABER_YELLOW: + return 0x0000ffff; + break; + case SABER_GREEN: + return 0x0000ff00; + break; + case SABER_BLUE: + return 0x00ff0000; + break; + case SABER_PURPLE: + return 0x00ff00ff; + break; + default: + return 0x00ffffff; // white + break; } } -qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity_t *defender ) -{ - vec3_t temp, att_SaberBase, att_StartPos, saberMidNext, att_HitDir, att_HitPos, def_BladeDir; - float att_SaberHitLength, hitDot; +qboolean WP_GetSaberDeflectionAngle(gentity_t *attacker, gentity_t *defender) { + vec3_t temp, att_SaberBase, att_StartPos, saberMidNext, att_HitDir, att_HitPos, def_BladeDir; + float att_SaberHitLength, hitDot; - if ( !attacker || !attacker->client || attacker->client->ps.saberInFlight || attacker->client->ps.SaberLength() <= 0 ) - { + if (!attacker || !attacker->client || attacker->client->ps.saberInFlight || attacker->client->ps.SaberLength() <= 0) { return qfalse; } - if ( !defender || !defender->client || defender->client->ps.saberInFlight || defender->client->ps.SaberLength() <= 0 ) - { + if (!defender || !defender->client || defender->client->ps.saberInFlight || defender->client->ps.SaberLength() <= 0) { return qfalse; } - if ( PM_SuperBreakLoseAnim( attacker->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( attacker->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(attacker->client->ps.torsoAnim) || PM_SuperBreakWinAnim(attacker->client->ps.torsoAnim)) { return qfalse; } attacker->client->ps.saberBounceMove = LS_NONE; - //get the attacker's saber base pos at time of impact - VectorSubtract( attacker->client->renderInfo.muzzlePoint, attacker->client->renderInfo.muzzlePointOld, temp ); - VectorMA( attacker->client->renderInfo.muzzlePointOld, saberHitFraction, temp, att_SaberBase ); - - //get the position along the length of the blade where the hit occured - att_SaberHitLength = Distance( saberHitLocation, att_SaberBase )/attacker->client->ps.SaberLength(); - - //now get the start of that midpoint in the swing and the actual impact point in the swing (shouldn't the latter just be saberHitLocation?) - VectorMA( attacker->client->renderInfo.muzzlePointOld, att_SaberHitLength, attacker->client->renderInfo.muzzleDirOld, att_StartPos ); - VectorMA( attacker->client->renderInfo.muzzlePoint, att_SaberHitLength, attacker->client->renderInfo.muzzleDir, saberMidNext ); - VectorSubtract( saberMidNext, att_StartPos, att_HitDir ); - VectorMA( att_StartPos, saberHitFraction, att_HitDir, att_HitPos ); - VectorNormalize( att_HitDir ); - - //get the defender's saber dir at time of impact - VectorSubtract( defender->client->renderInfo.muzzleDirOld, defender->client->renderInfo.muzzleDir, temp ); - VectorMA( defender->client->renderInfo.muzzleDirOld, saberHitFraction, temp, def_BladeDir ); - - //now compare - hitDot = DotProduct( att_HitDir, def_BladeDir ); - if ( hitDot < 0.25f && hitDot > -0.25f ) - {//hit pretty much perpendicular, pop straight back - attacker->client->ps.saberBounceMove = PM_SaberBounceForAttack( attacker->client->ps.saberMove ); + // get the attacker's saber base pos at time of impact + VectorSubtract(attacker->client->renderInfo.muzzlePoint, attacker->client->renderInfo.muzzlePointOld, temp); + VectorMA(attacker->client->renderInfo.muzzlePointOld, saberHitFraction, temp, att_SaberBase); + + // get the position along the length of the blade where the hit occured + att_SaberHitLength = Distance(saberHitLocation, att_SaberBase) / attacker->client->ps.SaberLength(); + + // now get the start of that midpoint in the swing and the actual impact point in the swing (shouldn't the latter just be saberHitLocation?) + VectorMA(attacker->client->renderInfo.muzzlePointOld, att_SaberHitLength, attacker->client->renderInfo.muzzleDirOld, att_StartPos); + VectorMA(attacker->client->renderInfo.muzzlePoint, att_SaberHitLength, attacker->client->renderInfo.muzzleDir, saberMidNext); + VectorSubtract(saberMidNext, att_StartPos, att_HitDir); + VectorMA(att_StartPos, saberHitFraction, att_HitDir, att_HitPos); + VectorNormalize(att_HitDir); + + // get the defender's saber dir at time of impact + VectorSubtract(defender->client->renderInfo.muzzleDirOld, defender->client->renderInfo.muzzleDir, temp); + VectorMA(defender->client->renderInfo.muzzleDirOld, saberHitFraction, temp, def_BladeDir); + + // now compare + hitDot = DotProduct(att_HitDir, def_BladeDir); + if (hitDot < 0.25f && hitDot > -0.25f) { // hit pretty much perpendicular, pop straight back + attacker->client->ps.saberBounceMove = PM_SaberBounceForAttack(attacker->client->ps.saberMove); return qfalse; - } - else - {//a deflection - vec3_t att_Right, att_Up, att_DeflectionDir; - float swingRDot, swingUDot; - - //get the direction of the deflection - VectorScale( def_BladeDir, hitDot, att_DeflectionDir ); - //get our bounce straight back direction - VectorScale( att_HitDir, -1.0f, temp ); - //add the bounce back and deflection - VectorAdd( att_DeflectionDir, temp, att_DeflectionDir ); - //normalize the result to determine what direction our saber should bounce back toward - VectorNormalize( att_DeflectionDir ); - - //need to know the direction of the deflectoin relative to the attacker's facing - VectorSet( temp, 0, attacker->client->ps.viewangles[YAW], 0 );//presumes no pitch! - AngleVectors( temp, NULL, att_Right, att_Up ); - swingRDot = DotProduct( att_Right, att_DeflectionDir ); - swingUDot = DotProduct( att_Up, att_DeflectionDir ); - - if ( swingRDot > 0.25f ) - {//deflect to right - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // a deflection + vec3_t att_Right, att_Up, att_DeflectionDir; + float swingRDot, swingUDot; + + // get the direction of the deflection + VectorScale(def_BladeDir, hitDot, att_DeflectionDir); + // get our bounce straight back direction + VectorScale(att_HitDir, -1.0f, temp); + // add the bounce back and deflection + VectorAdd(att_DeflectionDir, temp, att_DeflectionDir); + // normalize the result to determine what direction our saber should bounce back toward + VectorNormalize(att_DeflectionDir); + + // need to know the direction of the deflectoin relative to the attacker's facing + VectorSet(temp, 0, attacker->client->ps.viewangles[YAW], 0); // presumes no pitch! + AngleVectors(temp, NULL, att_Right, att_Up); + swingRDot = DotProduct(att_Right, att_DeflectionDir); + swingUDot = DotProduct(att_Up, att_DeflectionDir); + + if (swingRDot > 0.25f) { // deflect to right + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_TR; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_BR; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberBounceMove = LS_D1__R; } - } - else if ( swingRDot < -0.25f ) - {//deflect to left - if ( swingUDot > 0.25f ) - {//deflect to top + } else if (swingRDot < -0.25f) { // deflect to left + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_TL; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_BL; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberBounceMove = LS_D1__L; } - } - else - {//deflect in middle - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // deflect in middle + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_T_; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_B_; - } - else - {//deflect horizontally? Well, no such thing as straight back in my face, so use top - if ( swingRDot > 0 ) - { + } else { // deflect horizontally? Well, no such thing as straight back in my face, so use top + if (swingRDot > 0) { attacker->client->ps.saberBounceMove = LS_D1_TR; - } - else if ( swingRDot < 0 ) - { + } else if (swingRDot < 0) { attacker->client->ps.saberBounceMove = LS_D1_TL; - } - else - { + } else { attacker->client->ps.saberBounceMove = LS_D1_T_; } } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_BLUE"%s deflected from %s to %s\n", attacker->targetname, saberMoveData[attacker->client->ps.saberMove].name, saberMoveData[attacker->client->ps.saberBounceMove].name ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_BLUE "%s deflected from %s to %s\n", attacker->targetname, saberMoveData[attacker->client->ps.saberMove].name, + saberMoveData[attacker->client->ps.saberBounceMove].name); } #endif return qtrue; } } - -void WP_SaberClearDamageForEntNum( gentity_t *attacker, int entityNum, int saberNum, int bladeNum ) -{ +void WP_SaberClearDamageForEntNum(gentity_t *attacker, int entityNum, int saberNum, int bladeNum) { #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( entityNum ) - { - Com_Printf( "clearing damage for entnum %d\n", entityNum ); + if (d_saberCombat->integer) { + if (entityNum) { + Com_Printf("clearing damage for entnum %d\n", entityNum); } } -#endif// FINAL_BUILD - if ( g_saberRealisticCombat->integer > 1 ) - { +#endif // FINAL_BUILD + if (g_saberRealisticCombat->integer > 1) { return; } - //FIXME: if hit their saber in WP_SaberDamageForTrace, need to still do knockback on them... + // FIXME: if hit their saber in WP_SaberDamageForTrace, need to still do knockback on them... float knockBackScale = 0.0f; - if ( attacker && attacker->client ) - { - if ( !WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].knockbackScale > 0.0f ) - { + if (attacker && attacker->client) { + if (!WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && attacker->client->ps.saber[saberNum].knockbackScale > 0.0f) { knockBackScale = attacker->client->ps.saber[saberNum].knockbackScale; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].knockbackScale2 > 0.0f ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + attacker->client->ps.saber[saberNum].knockbackScale2 > 0.0f) { knockBackScale = attacker->client->ps.saber[saberNum].knockbackScale2; } } - for ( int i = 0; i < numVictims; i++ ) - { - if ( victimEntityNum[i] == entityNum ) - { - //hold on a sec, let's still do any accumulated knockback - if ( knockBackScale ) - { + for (int i = 0; i < numVictims; i++) { + if (victimEntityNum[i] == entityNum) { + // hold on a sec, let's still do any accumulated knockback + if (knockBackScale) { gentity_t *victim = &g_entities[victimEntityNum[i]]; - if ( victim && victim->client ) - { + if (victim && victim->client) { vec3_t center, dirToCenter; - float knockDownThreshHold, knockback = knockBackScale * totalDmg[i] * 0.5f; - - VectorAdd( victim->absmin, victim->absmax, center ); - VectorScale( center, 0.5, center ); - VectorSubtract( victim->currentOrigin, saberHitLocation, dirToCenter ); - VectorNormalize( dirToCenter ); - G_Throw( victim, dirToCenter, knockback ); - if ( victim->client->ps.groundEntityNum != ENTITYNUM_NONE - && dirToCenter[2] <= 0 ) - {//hit downward on someone who is standing on firm ground, so more likely to knock them down - knockDownThreshHold = Q_irand( 25, 50 ); - } - else - { - knockDownThreshHold = Q_irand( 75, 125 ); + float knockDownThreshHold, knockback = knockBackScale * totalDmg[i] * 0.5f; + + VectorAdd(victim->absmin, victim->absmax, center); + VectorScale(center, 0.5, center); + VectorSubtract(victim->currentOrigin, saberHitLocation, dirToCenter); + VectorNormalize(dirToCenter); + G_Throw(victim, dirToCenter, knockback); + if (victim->client->ps.groundEntityNum != ENTITYNUM_NONE && + dirToCenter[2] <= 0) { // hit downward on someone who is standing on firm ground, so more likely to knock them down + knockDownThreshHold = Q_irand(25, 50); + } else { + knockDownThreshHold = Q_irand(75, 125); } - if ( knockback > knockDownThreshHold ) - { - G_Knockdown( victim, attacker, dirToCenter, 350, qtrue ); + if (knockback > knockDownThreshHold) { + G_Knockdown(victim, attacker, dirToCenter, 350, qtrue); } } } - //now clear everything - totalDmg[i] = 0;//no damage + // now clear everything + totalDmg[i] = 0; // no damage hitLoc[i] = HL_NONE; hitDismemberLoc[i] = HL_NONE; hitDismember[i] = qfalse; - victimEntityNum[i] = ENTITYNUM_NONE;//like we never hit him + victimEntityNum[i] = ENTITYNUM_NONE; // like we never hit him } } } extern float damageModifier[]; extern float hitLocHealthPercentage[]; -qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, - qboolean brokenParry, int saberNum, int bladeNum, qboolean thrownSaber ) -{ - qboolean didDamage = qfalse; - gentity_t *victim; - int dFlags = baseDFlags; - float maxDmg; +qboolean WP_SaberApplyDamage(gentity_t *ent, float baseDamage, int baseDFlags, qboolean brokenParry, int saberNum, int bladeNum, qboolean thrownSaber) { + qboolean didDamage = qfalse; + gentity_t *victim; + int dFlags = baseDFlags; + float maxDmg; saberType_t saberType = ent->client->ps.saber[saberNum].type; - if ( !numVictims ) - { + if (!numVictims) { return qfalse; } - for ( int i = 0; i < numVictims; i++ ) - { - dFlags = baseDFlags|DAMAGE_DEATH_KNOCKBACK|DAMAGE_NO_HIT_LOC; - if ( victimEntityNum[i] != ENTITYNUM_NONE && &g_entities[victimEntityNum[i]] != NULL ) - { // Don't bother with this damage if the fraction is higher than the saber's fraction - if ( dmgFraction[i] < saberHitFraction || brokenParry ) - { + for (int i = 0; i < numVictims; i++) { + dFlags = baseDFlags | DAMAGE_DEATH_KNOCKBACK | DAMAGE_NO_HIT_LOC; + if (victimEntityNum[i] != ENTITYNUM_NONE && + &g_entities[victimEntityNum[i]] != NULL) { // Don't bother with this damage if the fraction is higher than the saber's fraction + if (dmgFraction[i] < saberHitFraction || brokenParry) { victim = &g_entities[victimEntityNum[i]]; - if ( !victim ) - { + if (!victim) { continue; } - if ( victim->e_DieFunc == dieF_maglock_die ) - {//*sigh*, special check for maglocks + if (victim->e_DieFunc == dieF_maglock_die) { //*sigh*, special check for maglocks vec3_t testFrom; - if ( ent->client->ps.saberInFlight ) - { - VectorCopy( g_entities[ent->client->ps.saberEntityNum].currentOrigin, testFrom ); - } - else - { - VectorCopy( ent->currentOrigin, testFrom ); + if (ent->client->ps.saberInFlight) { + VectorCopy(g_entities[ent->client->ps.saberEntityNum].currentOrigin, testFrom); + } else { + VectorCopy(ent->currentOrigin, testFrom); } testFrom[2] = victim->currentOrigin[2]; trace_t testTrace; - gi.trace( &testTrace, testFrom, vec3_origin, vec3_origin, victim->currentOrigin, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( testTrace.entityNum != victim->s.number ) - {//can only damage maglocks if have a clear trace to the thing's origin + gi.trace(&testTrace, testFrom, vec3_origin, vec3_origin, victim->currentOrigin, ent->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (testTrace.entityNum != victim->s.number) { // can only damage maglocks if have a clear trace to the thing's origin continue; } } - if ( totalDmg[i] > 0 ) - {//actually want to do *some* damage here - if ( victim->client - && victim->client->NPC_class==CLASS_WAMPA - && victim->activator == ent ) - { - } - else if ( PM_SuperBreakWinAnim( ent->client->ps.torsoAnim ) - || PM_StabDownAnim( ent->client->ps.torsoAnim ) ) - {//never cap the superbreak wins - } - else - { - if ( victim->client - && (victim->s.weapon == WP_SABER || (victim->client->NPC_class==CLASS_REBORN) || (victim->client->NPC_class==CLASS_WAMPA)) - && !g_saberRealisticCombat->integer ) - {//dmg vs other saber fighters is modded by hitloc and capped + if (totalDmg[i] > 0) { // actually want to do *some* damage here + if (victim->client && victim->client->NPC_class == CLASS_WAMPA && victim->activator == ent) { + } else if (PM_SuperBreakWinAnim(ent->client->ps.torsoAnim) || PM_StabDownAnim(ent->client->ps.torsoAnim)) { // never cap the superbreak wins + } else { + if (victim->client && + (victim->s.weapon == WP_SABER || (victim->client->NPC_class == CLASS_REBORN) || (victim->client->NPC_class == CLASS_WAMPA)) && + !g_saberRealisticCombat->integer) { // dmg vs other saber fighters is modded by hitloc and capped totalDmg[i] *= damageModifier[hitLoc[i]]; - if ( hitLoc[i] == HL_NONE ) - { - maxDmg = 33*baseDamage; + if (hitLoc[i] == HL_NONE) { + maxDmg = 33 * baseDamage; + } else { + maxDmg = 50 * hitLocHealthPercentage[hitLoc[i]] * baseDamage; //*victim->client->ps.stats[STAT_MAX_HEALTH]*2.0f; } - else - { - maxDmg = 50*hitLocHealthPercentage[hitLoc[i]]*baseDamage;//*victim->client->ps.stats[STAT_MAX_HEALTH]*2.0f; - } - if ( maxDmg < totalDmg[i] ) - { + if (maxDmg < totalDmg[i]) { totalDmg[i] = maxDmg; } - //dFlags |= DAMAGE_NO_HIT_LOC; + // dFlags |= DAMAGE_NO_HIT_LOC; } - //clamp the dmg - if ( victim->s.weapon != WP_SABER ) - {//clamp the dmg between 25 and maxhealth + // clamp the dmg + if (victim->s.weapon != WP_SABER) { // clamp the dmg between 25 and maxhealth /* if ( totalDmg[i] > victim->max_health ) { totalDmg[i] = victim->max_health; } - else */if ( totalDmg[i] < 25 ) - { + else */ + if (totalDmg[i] < 25) { totalDmg[i] = 25; } - if ( totalDmg[i] > 100 )//+(50*g_spskill->integer) ) - {//clamp using same adjustment as in NPC_Begin - totalDmg[i] = 100;//+(50*g_spskill->integer); + if (totalDmg[i] > 100) //+(50*g_spskill->integer) ) + { // clamp using same adjustment as in NPC_Begin + totalDmg[i] = 100; //+(50*g_spskill->integer); } - } - else - {//clamp the dmg between 5 and 100 - if ( !victim->s.number && totalDmg[i] > 50 ) - {//never do more than half full health damage to player - //prevents one-hit kills + } else { // clamp the dmg between 5 and 100 + if (!victim->s.number && totalDmg[i] > 50) { // never do more than half full health damage to player + // prevents one-hit kills totalDmg[i] = 50; - } - else if ( totalDmg[i] > 100 ) - { + } else if (totalDmg[i] > 100) { totalDmg[i] = 100; - } - else - { - if ( totalDmg[i] < 5 ) - { + } else { + if (totalDmg[i] < 5) { totalDmg[i] = 5; } } } } - if ( totalDmg[i] > 0 ) - { + if (totalDmg[i] > 0) { gentity_t *inflictor = ent; didDamage = qtrue; qboolean vicWasDismembered = qtrue; - qboolean vicWasAlive = (qboolean)(victim->health>0); + qboolean vicWasAlive = (qboolean)(victim->health > 0); - if ( baseDamage <= 0.1f ) - {//just get their attention? + if (baseDamage <= 0.1f) { // just get their attention? dFlags |= DAMAGE_NO_DAMAGE; } - if( victim->client ) - { - if ( victim->client->ps.pm_time > 0 && victim->client->ps.pm_flags & PMF_TIME_KNOCKBACK && victim->client->ps.velocity[2] > 0 ) - {//already being knocked around + if (victim->client) { + if (victim->client->ps.pm_time > 0 && victim->client->ps.pm_flags & PMF_TIME_KNOCKBACK && + victim->client->ps.velocity[2] > 0) { // already being knocked around dFlags |= DAMAGE_NO_KNOCKBACK; } - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_DISMEMBERMENT) ) - {//no dismemberment! (blunt/stabbing weapon?) - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_DISMEMBERMENT2) ) - {//no dismemberment! (blunt/stabbing weapon?) - } - else - { - if ( debug_subdivision->integer || g_saberRealisticCombat->integer ) - { + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_DISMEMBERMENT)) { // no dismemberment! (blunt/stabbing weapon?) + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_DISMEMBERMENT2)) { // no dismemberment! (blunt/stabbing weapon?) + } else { + if (debug_subdivision->integer || g_saberRealisticCombat->integer) { dFlags |= DAMAGE_DISMEMBER; - if ( hitDismember[i] ) - { + if (hitDismember[i]) { victim->client->dismembered = false; } - } - else if ( hitDismember[i] ) - { + } else if (hitDismember[i]) { dFlags |= DAMAGE_DISMEMBER; } - if ( !victim->client->dismembered ) - { + if (!victim->client->dismembered) { vicWasDismembered = qfalse; } } - if ( baseDamage <= 1.0f ) - {//very mild damage - if ( victim->s.number == 0 || victim->client->ps.weapon == WP_SABER || victim->client->NPC_class == CLASS_GALAKMECH ) - {//if it's the player or a saber-user, don't kill them with this blow + if (baseDamage <= 1.0f) { // very mild damage + if (victim->s.number == 0 || victim->client->ps.weapon == WP_SABER || + victim->client->NPC_class == CLASS_GALAKMECH) { // if it's the player or a saber-user, don't kill them with this blow dFlags |= DAMAGE_NO_KILL; } } - } - else - { - if ( victim->takedamage ) - {//some other breakable thing - //create a flash here - if ( !g_noClashFlare ) - { - g_saberFlashTime = level.time-50; - VectorCopy( dmgSpot[i], g_saberFlashPos ); + } else { + if (victim->takedamage) { // some other breakable thing + // create a flash here + if (!g_noClashFlare) { + g_saberFlashTime = level.time - 50; + VectorCopy(dmgSpot[i], g_saberFlashPos); } } } - if ( !PM_SuperBreakWinAnim( ent->client->ps.torsoAnim ) - && !PM_StabDownAnim( ent->client->ps.torsoAnim ) - && !g_saberRealisticCombat->integer - && g_saberDamageCapping->integer ) - {//never cap the superbreak wins - if ( victim->client - && victim->s.number >= MAX_CLIENTS ) - { - if ( victim->client->NPC_class == CLASS_SHADOWTROOPER - || ( victim->NPC && (victim->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) ) - {//hit a boss character - int maxDmg = ((3-g_spskill->integer)*5)+10; - if ( totalDmg[i] > maxDmg ) - { + if (!PM_SuperBreakWinAnim(ent->client->ps.torsoAnim) && !PM_StabDownAnim(ent->client->ps.torsoAnim) && + !g_saberRealisticCombat->integer && g_saberDamageCapping->integer) { // never cap the superbreak wins + if (victim->client && victim->s.number >= MAX_CLIENTS) { + if (victim->client->NPC_class == CLASS_SHADOWTROOPER || + (victim->NPC && (victim->NPC->aiFlags & NPCAI_BOSS_CHARACTER))) { // hit a boss character + int maxDmg = ((3 - g_spskill->integer) * 5) + 10; + if (totalDmg[i] > maxDmg) { totalDmg[i] = maxDmg; } - } - else if ( victim->client->ps.weapon == WP_SABER - || victim->client->NPC_class == CLASS_REBORN - || victim->client->NPC_class == CLASS_JEDI ) - {//hit a non-boss saber-user - int maxDmg = ((3-g_spskill->integer)*15)+30; - if ( totalDmg[i] > maxDmg ) - { + } else if (victim->client->ps.weapon == WP_SABER || victim->client->NPC_class == CLASS_REBORN || + victim->client->NPC_class == CLASS_JEDI) { // hit a non-boss saber-user + int maxDmg = ((3 - g_spskill->integer) * 15) + 30; + if (totalDmg[i] > maxDmg) { totalDmg[i] = maxDmg; } } } - if ( victim->s.number < MAX_CLIENTS - && ent->NPC ) - { - if ( (ent->NPC->aiFlags&NPCAI_BOSS_CHARACTER) - || (ent->NPC->aiFlags&NPCAI_SUBBOSS_CHARACTER) - || ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//player hit by a boss character - int maxDmg = ((g_spskill->integer+1)*4)+3; - if ( totalDmg[i] > maxDmg ) - { + if (victim->s.number < MAX_CLIENTS && ent->NPC) { + if ((ent->NPC->aiFlags & NPCAI_BOSS_CHARACTER) || (ent->NPC->aiFlags & NPCAI_SUBBOSS_CHARACTER) || + ent->client->NPC_class == CLASS_SHADOWTROOPER) { // player hit by a boss character + int maxDmg = ((g_spskill->integer + 1) * 4) + 3; + if (totalDmg[i] > maxDmg) { totalDmg[i] = maxDmg; } - } - else if ( g_spskill->integer < 3 ) //was < 2 - {//player hit by any enemy //on easy or medium? - int maxDmg = ((g_spskill->integer+1)*10)+20; - if ( totalDmg[i] > maxDmg ) - { + } else if (g_spskill->integer < 3) // was < 2 + { // player hit by any enemy //on easy or medium? + int maxDmg = ((g_spskill->integer + 1) * 10) + 20; + if (totalDmg[i] > maxDmg) { totalDmg[i] = maxDmg; } } } } - //victim->hitLoc = hitLoc[i]; + // victim->hitLoc = hitLoc[i]; - dFlags |= DAMAGE_NO_KNOCKBACK;//okay, let's try no knockback whatsoever... + dFlags |= DAMAGE_NO_KNOCKBACK; // okay, let's try no knockback whatsoever... dFlags &= ~DAMAGE_DEATH_KNOCKBACK; - if ( g_saberRealisticCombat->integer ) - { + if (g_saberRealisticCombat->integer) { dFlags |= DAMAGE_NO_KNOCKBACK; dFlags &= ~DAMAGE_DEATH_KNOCKBACK; dFlags &= ~DAMAGE_NO_KILL; } - if ( ent->client && !ent->s.number ) - { - switch( hitLoc[i] ) - { + if (ent->client && !ent->s.number) { + switch (hitLoc[i]) { case HL_FOOT_RT: case HL_FOOT_LT: case HL_LEG_RT: @@ -1595,110 +1203,71 @@ qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, } } - if ( saberType == SABER_SITH_SWORD ) - {//do knockback - dFlags &= ~(DAMAGE_NO_KNOCKBACK|DAMAGE_DEATH_KNOCKBACK); + if (saberType == SABER_SITH_SWORD) { // do knockback + dFlags &= ~(DAMAGE_NO_KNOCKBACK | DAMAGE_DEATH_KNOCKBACK); } - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].knockbackScale > 0.0f ) - { - dFlags &= ~(DAMAGE_NO_KNOCKBACK|DAMAGE_DEATH_KNOCKBACK); - if ( saberNum < 1 ) - { + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + ent->client->ps.saber[saberNum].knockbackScale > 0.0f) { + dFlags &= ~(DAMAGE_NO_KNOCKBACK | DAMAGE_DEATH_KNOCKBACK); + if (saberNum < 1) { dFlags |= DAMAGE_SABER_KNOCKBACK1; - } - else - { + } else { dFlags |= DAMAGE_SABER_KNOCKBACK2; } - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].knockbackScale2 > 0.0f ) - { - dFlags &= ~(DAMAGE_NO_KNOCKBACK|DAMAGE_DEATH_KNOCKBACK); - if ( saberNum < 1 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + ent->client->ps.saber[saberNum].knockbackScale2 > 0.0f) { + dFlags &= ~(DAMAGE_NO_KNOCKBACK | DAMAGE_DEATH_KNOCKBACK); + if (saberNum < 1) { dFlags |= DAMAGE_SABER_KNOCKBACK1_B2; - } - else - { + } else { dFlags |= DAMAGE_SABER_KNOCKBACK2_B2; } } - if ( thrownSaber ) - { + if (thrownSaber) { inflictor = &g_entities[ent->client->ps.saberEntityNum]; } int damage = 0; - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].damageScale != 1.0f ) - { - damage = ceil(totalDmg[i]*ent->client->ps.saber[saberNum].damageScale); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].damageScale2 != 1.0f ) - { - damage = ceil(totalDmg[i]*ent->client->ps.saber[saberNum].damageScale2); - } - else - { + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + ent->client->ps.saber[saberNum].damageScale != 1.0f) { + damage = ceil(totalDmg[i] * ent->client->ps.saber[saberNum].damageScale); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + ent->client->ps.saber[saberNum].damageScale2 != 1.0f) { + damage = ceil(totalDmg[i] * ent->client->ps.saber[saberNum].damageScale2); + } else { damage = ceil(totalDmg[i]); } - G_Damage( victim, inflictor, ent, dmgDir[i], dmgSpot[i], damage, dFlags, MOD_SABER, hitDismemberLoc[i] ); - if ( damage > 0 && cg.time ) - { + G_Damage(victim, inflictor, ent, dmgDir[i], dmgSpot[i], damage, dFlags, MOD_SABER, hitDismemberLoc[i]); + if (damage > 0 && cg.time) { float sizeTimeScale = 1.0f; - if ( (vicWasAlive - && victim->health <= 0 ) - || (!vicWasDismembered - && victim->client->dismembered - && hitDismemberLoc[i] != HL_NONE - && hitDismember[i]) ) - { + if ((vicWasAlive && victim->health <= 0) || + (!vicWasDismembered && victim->client->dismembered && hitDismemberLoc[i] != HL_NONE && hitDismember[i])) { sizeTimeScale = 3.0f; } - //FIXME: if not hitting the first model on the enemy, don't do this! - CG_SaberDoWeaponHitMarks( ent->client, - (ent->client->ps.saberInFlight?&g_entities[ent->client->ps.saberEntityNum]:NULL), - victim, - saberNum, - bladeNum, - dmgSpot[i], - dmgDir[i], - dmgBladeVec[i], - dmgNormal[i], - sizeTimeScale ); - } -#ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( (dFlags&DAMAGE_NO_DAMAGE) ) - { - gi.Printf( S_COLOR_RED"damage: fake, hitLoc %d\n", hitLoc[i] ); - } - else - { - gi.Printf( S_COLOR_RED"damage: %4.2f, hitLoc %d\n", totalDmg[i], hitLoc[i] ); + // FIXME: if not hitting the first model on the enemy, don't do this! + CG_SaberDoWeaponHitMarks(ent->client, (ent->client->ps.saberInFlight ? &g_entities[ent->client->ps.saberEntityNum] : NULL), victim, + saberNum, bladeNum, dmgSpot[i], dmgDir[i], dmgBladeVec[i], dmgNormal[i], sizeTimeScale); + } +#ifndef FINAL_BUILD + if (d_saberCombat->integer) { + if ((dFlags & DAMAGE_NO_DAMAGE)) { + gi.Printf(S_COLOR_RED "damage: fake, hitLoc %d\n", hitLoc[i]); + } else { + gi.Printf(S_COLOR_RED "damage: %4.2f, hitLoc %d\n", totalDmg[i], hitLoc[i]); } } #endif - //do the effect - //vec3_t splashBackDir; - //VectorScale( dmgNormal[i], -1, splashBackDir ); - //G_PlayEffect( G_EffectIndex( "blood_sparks" ), dmgSpot[i], splashBackDir ); - if ( ent->s.number == 0 ) - { - AddSoundEvent( victim->owner, dmgSpot[i], 256, AEL_DISCOVERED ); - AddSightEvent( victim->owner, dmgSpot[i], 512, AEL_DISCOVERED, 50 ); - } - if ( ent->client ) - { - if ( ent->enemy && ent->enemy == victim ) - {//just so Jedi knows that he hit his enemy + // do the effect + // vec3_t splashBackDir; + // VectorScale( dmgNormal[i], -1, splashBackDir ); + // G_PlayEffect( G_EffectIndex( "blood_sparks" ), dmgSpot[i], splashBackDir ); + if (ent->s.number == 0) { + AddSoundEvent(victim->owner, dmgSpot[i], 256, AEL_DISCOVERED); + AddSightEvent(victim->owner, dmgSpot[i], 512, AEL_DISCOVERED, 50); + } + if (ent->client) { + if (ent->enemy && ent->enemy == victim) { // just so Jedi knows that he hit his enemy ent->client->ps.saberEventFlags |= SEF_HITENEMY; - } - else - { + } else { ent->client->ps.saberEventFlags |= SEF_HITOBJECT; } } @@ -1710,75 +1279,64 @@ qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, return didDamage; } -void WP_SaberDamageAdd( float trDmg, int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgBladeVec, vec3_t trDmgNormal, vec3_t trDmgSpot, float dmg, float fraction, int trHitLoc, qboolean trDismember, int trDismemberLoc ) -{ +void WP_SaberDamageAdd(float trDmg, int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgBladeVec, vec3_t trDmgNormal, vec3_t trDmgSpot, float dmg, + float fraction, int trHitLoc, qboolean trDismember, int trDismemberLoc) { int curVictim = 0; int i; - if ( trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD ) - { + if (trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD) { return; } - if ( trDmg * dmg < 10.0f ) - {//too piddly an amount of damage to really count? - //FIXME: but already did the effect, didn't we... sigh... - //return; + if (trDmg * dmg < 10.0f) { // too piddly an amount of damage to really count? + // FIXME: but already did the effect, didn't we... sigh... + // return; } - if ( trDmg ) - {//did some damage to something - for ( i = 0; i < numVictims; i++ ) - { - if ( victimEntityNum[i] == trVictimEntityNum ) - {//already hit this guy before + if (trDmg) { // did some damage to something + for (i = 0; i < numVictims; i++) { + if (victimEntityNum[i] == trVictimEntityNum) { // already hit this guy before curVictim = i; break; } } - if ( i == numVictims ) - {//haven't hit his guy before - if ( numVictims + 1 >= MAX_SABER_VICTIMS ) - {//can't add another victim at this time + if (i == numVictims) { // haven't hit his guy before + if (numVictims + 1 >= MAX_SABER_VICTIMS) { // can't add another victim at this time return; } - //add a new victim to the list + // add a new victim to the list curVictim = numVictims; victimEntityNum[numVictims++] = trVictimEntityNum; } - float addDmg = trDmg*dmg; - if ( trHitLoc!=HL_NONE && (hitLoc[curVictim]==HL_NONE||hitLocHealthPercentage[trHitLoc]>hitLocHealthPercentage[hitLoc[curVictim]]) ) - {//this hitLoc is more critical than the previous one this frame + float addDmg = trDmg * dmg; + if (trHitLoc != HL_NONE && + (hitLoc[curVictim] == HL_NONE || + hitLocHealthPercentage[trHitLoc] > hitLocHealthPercentage[hitLoc[curVictim]])) { // this hitLoc is more critical than the previous one this frame hitLoc[curVictim] = trHitLoc; } totalDmg[curVictim] += addDmg; - if ( !VectorLengthSquared( dmgDir[curVictim] ) ) - { - VectorCopy( trDmgDir, dmgDir[curVictim] ); + if (!VectorLengthSquared(dmgDir[curVictim])) { + VectorCopy(trDmgDir, dmgDir[curVictim]); } - if ( !VectorLengthSquared( dmgBladeVec[curVictim] ) ) - { - VectorCopy( trDmgBladeVec, dmgBladeVec[curVictim] ); + if (!VectorLengthSquared(dmgBladeVec[curVictim])) { + VectorCopy(trDmgBladeVec, dmgBladeVec[curVictim]); } - if ( !VectorLengthSquared( dmgNormal[curVictim] ) ) - { - VectorCopy( trDmgNormal, dmgNormal[curVictim] ); + if (!VectorLengthSquared(dmgNormal[curVictim])) { + VectorCopy(trDmgNormal, dmgNormal[curVictim]); } - if ( !VectorLengthSquared( dmgSpot[curVictim] ) ) - { - VectorCopy( trDmgSpot, dmgSpot[curVictim] ); + if (!VectorLengthSquared(dmgSpot[curVictim])) { + VectorCopy(trDmgSpot, dmgSpot[curVictim]); } // Make sure we keep track of the fraction. Why? // Well, if the saber hits something that stops it, the damage isn't done past that point. dmgFraction[curVictim] = fraction; - if ( (trDismemberLoc != HL_NONE && hitDismemberLoc[curVictim] == HL_NONE) - || (!hitDismember[curVictim] && trDismember) ) - {//either this is the first dismember loc we got or we got a loc before, but it wasn't a dismember loc, so take the new one + if ((trDismemberLoc != HL_NONE && hitDismemberLoc[curVictim] == HL_NONE) || + (!hitDismember[curVictim] && + trDismember)) { // either this is the first dismember loc we got or we got a loc before, but it wasn't a dismember loc, so take the new one hitDismemberLoc[curVictim] = trDismemberLoc; } - if ( trDismember ) - {//we scored a dismemberment hit... + if (trDismember) { // we scored a dismemberment hit... hitDismember[curVictim] = trDismember; } } @@ -1790,15 +1348,15 @@ WP_SabersIntersect Breaks the two saber paths into 2 tris each and tests each tri for the first saber path against each of the other saber path's tris FIXME: subdivide the arc into a consistant increment -FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different times)? +FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different +times)? */ -extern qboolean tri_tri_intersect(vec3_t V0,vec3_t V1,vec3_t V2,vec3_t U0,vec3_t U1,vec3_t U2); -qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum, gentity_t *ent2, qboolean checkDir ) -{ - vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; - vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; - int ent2SaberNum = 0, ent2BladeNum = 0; - vec3_t dir; +extern qboolean tri_tri_intersect(vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2); +qboolean WP_SabersIntersect(gentity_t *ent1, int ent1SaberNum, int ent1BladeNum, gentity_t *ent2, qboolean checkDir) { + vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; + vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; + int ent2SaberNum = 0, ent2BladeNum = 0; + vec3_t dir; /* #ifndef FINAL_BUILD @@ -1809,111 +1367,109 @@ qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum #endif */ - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0 ) - { + if (ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0) { return qfalse; } - for ( ent2SaberNum = 0; ent2SaberNum < MAX_SABERS; ent2SaberNum++ ) - { - for ( ent2BladeNum = 0; ent2BladeNum < ent2->client->ps.saber[ent2SaberNum].numBlades; ent2BladeNum++ ) - { - if ( ent2->client->ps.saber[ent2SaberNum].type != SABER_NONE - && ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length > 0 ) - {//valid saber and this blade is on - //if ( ent1->client->ps.saberInFlight ) + for (ent2SaberNum = 0; ent2SaberNum < MAX_SABERS; ent2SaberNum++) { + for (ent2BladeNum = 0; ent2BladeNum < ent2->client->ps.saber[ent2SaberNum].numBlades; ent2BladeNum++) { + if (ent2->client->ps.saber[ent2SaberNum].type != SABER_NONE && + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length > 0) { // valid saber and this blade is on + // if ( ent1->client->ps.saberInFlight ) { - VectorCopy( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, saberBase1 ); - VectorCopy( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBaseNext1 ); + VectorCopy(ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, saberBase1); + VectorCopy(ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBaseNext1); - VectorSubtract( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1 ); + VectorSubtract(ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, + ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1); - VectorMA( saberBase1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirOld, saberTip1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTipNext1 ); + VectorMA(saberBase1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, + ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirOld, saberTip1); + VectorMA(saberBaseNext1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, + ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTipNext1); - VectorSubtract( saberTipNext1, saberTip1, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1 ); + VectorSubtract(saberTipNext1, saberTip1, dir); + VectorNormalize(dir); + VectorMA(saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1); } /* else { VectorCopy( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBase1 ); VectorCopy( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointNext, saberBaseNext1 ); - VectorMA( saberBase1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTip1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirNext, saberTipNext1 ); + VectorMA( saberBase1, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, + ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTip1 ); VectorMA( saberBaseNext1, + ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].length, ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirNext, + saberTipNext1 ); } */ - //if ( ent2->client->ps.saberInFlight ) + // if ( ent2->client->ps.saberInFlight ) { - VectorCopy( ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, saberBase2 ); - VectorCopy( ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBaseNext2 ); + VectorCopy(ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, saberBase2); + VectorCopy(ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBaseNext2); - VectorSubtract( ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2 ); + VectorSubtract(ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2); - VectorMA( saberBase2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirOld, saberTip2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTipNext2 ); + VectorMA(saberBase2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirOld, saberTip2); + VectorMA(saberBaseNext2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTipNext2); - VectorSubtract( saberTipNext2, saberTip2, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2 ); + VectorSubtract(saberTipNext2, saberTip2, dir); + VectorNormalize(dir); + VectorMA(saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2); } /* else { VectorCopy( ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBase2 ); VectorCopy( ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointNext, saberBaseNext2 ); - VectorMA( saberBase2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTip2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirNext, saberTipNext2 ); + VectorMA( saberBase2, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTip2 ); VectorMA( saberBaseNext2, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].length, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirNext, + saberTipNext2 ); } */ - if ( checkDir ) - {//check the direction of the two swings to make sure the sabers are swinging towards each other + if (checkDir) { // check the direction of the two swings to make sure the sabers are swinging towards each other vec3_t saberDir1, saberDir2; - VectorSubtract( saberTipNext1, saberTip1, saberDir1 ); - VectorSubtract( saberTipNext2, saberTip2, saberDir2 ); - VectorNormalize( saberDir1 ); - VectorNormalize( saberDir2 ); - if ( DotProduct( saberDir1, saberDir2 ) > 0.6f ) - {//sabers moving in same dir, probably didn't actually hit + VectorSubtract(saberTipNext1, saberTip1, saberDir1); + VectorSubtract(saberTipNext2, saberTip2, saberDir2); + VectorNormalize(saberDir1); + VectorNormalize(saberDir2); + if (DotProduct(saberDir1, saberDir2) > 0.6f) { // sabers moving in same dir, probably didn't actually hit continue; } - //now check orientation of sabers, make sure they're not parallel or close to it - float dot = DotProduct( ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir ); - if ( dot > 0.9f || dot < -0.9f ) - {//too parallel to really block effectively? + // now check orientation of sabers, make sure they're not parallel or close to it + float dot = DotProduct(ent1->client->ps.saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, + ent2->client->ps.saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir); + if (dot > 0.9f || dot < -0.9f) { // too parallel to really block effectively? continue; } } - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } } @@ -1922,10 +1478,9 @@ qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum return qfalse; } -float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) -{ - vec3_t saberBaseNext1, saberTipNext1, saberPoint1; - vec3_t saberBaseNext2, saberTipNext2, saberPoint2; +float WP_SabersDistance(gentity_t *ent1, gentity_t *ent2) { + vec3_t saberBaseNext1, saberTipNext1, saberPoint1; + vec3_t saberBaseNext2, saberTipNext2, saberPoint2; /* #ifndef FINAL_BUILD @@ -1936,25 +1491,22 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) #endif */ - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0 ) - { + if (ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0) { return qfalse; } - //FIXME: UGH, how do we make this work for multiply-bladed sabers? + // FIXME: UGH, how do we make this work for multiply-bladed sabers? - //if ( ent1->client->ps.saberInFlight ) + // if ( ent1->client->ps.saberInFlight ) { - VectorCopy( ent1->client->ps.saber[0].blade[0].muzzlePoint, saberBaseNext1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saber[0].blade[0].length, ent1->client->ps.saber[0].blade[0].muzzleDir, saberTipNext1 ); + VectorCopy(ent1->client->ps.saber[0].blade[0].muzzlePoint, saberBaseNext1); + VectorMA(saberBaseNext1, ent1->client->ps.saber[0].blade[0].length, ent1->client->ps.saber[0].blade[0].muzzleDir, saberTipNext1); } /* else @@ -1964,10 +1516,10 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) } */ - //if ( ent2->client->ps.saberInFlight ) + // if ( ent2->client->ps.saberInFlight ) { - VectorCopy( ent2->client->ps.saber[0].blade[0].muzzlePoint, saberBaseNext2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saber[0].blade[0].length, ent2->client->ps.saber[0].blade[0].muzzleDir, saberTipNext2 ); + VectorCopy(ent2->client->ps.saber[0].blade[0].muzzlePoint, saberBaseNext2); + VectorMA(saberBaseNext2, ent2->client->ps.saber[0].blade[0].length, ent2->client->ps.saber[0].blade[0].muzzleDir, saberTipNext2); } /* else @@ -1977,9 +1529,9 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) } */ - float sabersDist = ShortestLineSegBewteen2LineSegs( saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2 ); + float sabersDist = ShortestLineSegBewteen2LineSegs(saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2); - //okay, this is a super hack, but makes saber collisions look better from the player point of view + // okay, this is a super hack, but makes saber collisions look better from the player point of view /* if ( sabersDist < 16.0f ) { @@ -2000,61 +1552,52 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) */ #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 2 ) - { - G_DebugLine( saberPoint1, saberPoint2, FRAMETIME, 0x00ffffff, qtrue ); + if (d_saberCombat->integer > 2) { + G_DebugLine(saberPoint1, saberPoint2, FRAMETIME, 0x00ffffff, qtrue); } #endif return sabersDist; } -qboolean WP_SabersIntersection( gentity_t *ent1, gentity_t *ent2, vec3_t intersect ) -{ - vec3_t saberBaseNext1, saberTipNext1, saberPoint1; - vec3_t saberBaseNext2, saberTipNext2, saberPoint2; - int saberNum1, saberNum2, bladeNum1, bladeNum2; - float lineSegLength, bestLineSegLength = Q3_INFINITE; +qboolean WP_SabersIntersection(gentity_t *ent1, gentity_t *ent2, vec3_t intersect) { + vec3_t saberBaseNext1, saberTipNext1, saberPoint1; + vec3_t saberBaseNext2, saberTipNext2, saberPoint2; + int saberNum1, saberNum2, bladeNum1, bladeNum2; + float lineSegLength, bestLineSegLength = Q3_INFINITE; - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0 ) - { + if (ent1->client->ps.SaberLength() <= 0 || ent2->client->ps.SaberLength() <= 0) { return qfalse; } - //UGH, had to make this work for multiply-bladed sabers - for ( saberNum1 = 0; saberNum1 < MAX_SABERS; saberNum1++ ) - { - for ( bladeNum1 = 0; bladeNum1 < ent1->client->ps.saber[saberNum1].numBlades; bladeNum1++ ) - { - if ( ent1->client->ps.saber[saberNum1].type != SABER_NONE - && ent1->client->ps.saber[saberNum1].blade[bladeNum1].length > 0 ) - {//valid saber and this blade is on - for ( saberNum2 = 0; saberNum2 < MAX_SABERS; saberNum2++ ) - { - for ( bladeNum2 = 0; bladeNum2 < ent2->client->ps.saber[saberNum2].numBlades; bladeNum2++ ) - { - if ( ent2->client->ps.saber[saberNum2].type != SABER_NONE - && ent2->client->ps.saber[saberNum2].blade[bladeNum2].length > 0 ) - {//valid saber and this blade is on - VectorCopy( ent1->client->ps.saber[saberNum1].blade[bladeNum1].muzzlePoint, saberBaseNext1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saber[saberNum1].blade[bladeNum1].length, ent1->client->ps.saber[saberNum1].blade[bladeNum1].muzzleDir, saberTipNext1 ); - - VectorCopy( ent2->client->ps.saber[saberNum2].blade[bladeNum2].muzzlePoint, saberBaseNext2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saber[saberNum2].blade[bladeNum2].length, ent2->client->ps.saber[saberNum2].blade[bladeNum2].muzzleDir, saberTipNext2 ); - - lineSegLength = ShortestLineSegBewteen2LineSegs( saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2 ); - if ( lineSegLength < bestLineSegLength ) - { + // UGH, had to make this work for multiply-bladed sabers + for (saberNum1 = 0; saberNum1 < MAX_SABERS; saberNum1++) { + for (bladeNum1 = 0; bladeNum1 < ent1->client->ps.saber[saberNum1].numBlades; bladeNum1++) { + if (ent1->client->ps.saber[saberNum1].type != SABER_NONE && + ent1->client->ps.saber[saberNum1].blade[bladeNum1].length > 0) { // valid saber and this blade is on + for (saberNum2 = 0; saberNum2 < MAX_SABERS; saberNum2++) { + for (bladeNum2 = 0; bladeNum2 < ent2->client->ps.saber[saberNum2].numBlades; bladeNum2++) { + if (ent2->client->ps.saber[saberNum2].type != SABER_NONE && + ent2->client->ps.saber[saberNum2].blade[bladeNum2].length > 0) { // valid saber and this blade is on + VectorCopy(ent1->client->ps.saber[saberNum1].blade[bladeNum1].muzzlePoint, saberBaseNext1); + VectorMA(saberBaseNext1, ent1->client->ps.saber[saberNum1].blade[bladeNum1].length, + ent1->client->ps.saber[saberNum1].blade[bladeNum1].muzzleDir, saberTipNext1); + + VectorCopy(ent2->client->ps.saber[saberNum2].blade[bladeNum2].muzzlePoint, saberBaseNext2); + VectorMA(saberBaseNext2, ent2->client->ps.saber[saberNum2].blade[bladeNum2].length, + ent2->client->ps.saber[saberNum2].blade[bladeNum2].muzzleDir, saberTipNext2); + + lineSegLength = + ShortestLineSegBewteen2LineSegs(saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2); + if (lineSegLength < bestLineSegLength) { bestLineSegLength = lineSegLength; - VectorAdd( saberPoint1, saberPoint2, intersect ); - VectorScale( intersect, 0.5, intersect ); + VectorAdd(saberPoint1, saberPoint2, intersect); + VectorScale(intersect, 0.5, intersect); } } } @@ -2065,46 +1608,45 @@ qboolean WP_SabersIntersection( gentity_t *ent1, gentity_t *ent2, vec3_t interse return qtrue; } -const char *hit_blood_sparks = "sparks/blood_sparks2"; // could have changed this effect directly, but this is just safer in case anyone anywhere else is using the old one for something? +const char *hit_blood_sparks = + "sparks/blood_sparks2"; // could have changed this effect directly, but this is just safer in case anyone anywhere else is using the old one for something? const char *hit_sparks = "saber/saber_cut"; -qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, float dmg, vec3_t dmgDir, vec3_t bladeVec, int enemyTeam, saberType_t saberType, saberInfo_t *saber, int bladeNum ) -{ +qboolean WP_SaberDamageEffects(trace_t *tr, const vec3_t start, float length, float dmg, vec3_t dmgDir, vec3_t bladeVec, int enemyTeam, saberType_t saberType, + saberInfo_t *saber, int bladeNum) { - int hitEntNum[MAX_G2_COLLISIONS]; - for ( int hen = 0; hen < MAX_G2_COLLISIONS; hen++ ) - { + int hitEntNum[MAX_G2_COLLISIONS]; + for (int hen = 0; hen < MAX_G2_COLLISIONS; hen++) { hitEntNum[hen] = ENTITYNUM_NONE; } - //NOTE: = {0} does NOT work on anything but bytes? - float hitEntDmgAdd[MAX_G2_COLLISIONS] = {0}; - float hitEntDmgSub[MAX_G2_COLLISIONS] = {0}; - vec3_t hitEntPoint[MAX_G2_COLLISIONS]; - vec3_t hitEntNormal[MAX_G2_COLLISIONS]; - vec3_t bladeDir; - float hitEntStartFrac[MAX_G2_COLLISIONS] = {0}; - int trHitLoc[MAX_G2_COLLISIONS] = {HL_NONE};//same as 0 - int trDismemberLoc[MAX_G2_COLLISIONS] = {HL_NONE};//same as 0 - qboolean trDismember[MAX_G2_COLLISIONS] = {qfalse};//same as 0 - int i,z; - int numHitEnts = 0; - float distFromStart,doDmg; - int hitEffect = 0; - const char *trSurfName; - gentity_t *hitEnt; - - VectorNormalize2( bladeVec, bladeDir ); - - for (z=0; z < MAX_G2_COLLISIONS; z++) - { - if ( tr->G2CollisionMap[z].mEntityNum == -1 ) - {//actually, completely break out of this for loop since nothing after this in the aray should ever be valid either - continue;//break;// - } - - CCollisionRecord &coll = tr->G2CollisionMap[z]; - //distFromStart = Distance( start, coll.mCollisionPosition ); - distFromStart = coll.mDistance; + // NOTE: = {0} does NOT work on anything but bytes? + float hitEntDmgAdd[MAX_G2_COLLISIONS] = {0}; + float hitEntDmgSub[MAX_G2_COLLISIONS] = {0}; + vec3_t hitEntPoint[MAX_G2_COLLISIONS]; + vec3_t hitEntNormal[MAX_G2_COLLISIONS]; + vec3_t bladeDir; + float hitEntStartFrac[MAX_G2_COLLISIONS] = {0}; + int trHitLoc[MAX_G2_COLLISIONS] = {HL_NONE}; // same as 0 + int trDismemberLoc[MAX_G2_COLLISIONS] = {HL_NONE}; // same as 0 + qboolean trDismember[MAX_G2_COLLISIONS] = {qfalse}; // same as 0 + int i, z; + int numHitEnts = 0; + float distFromStart, doDmg; + int hitEffect = 0; + const char *trSurfName; + gentity_t *hitEnt; + + VectorNormalize2(bladeVec, bladeDir); + + for (z = 0; z < MAX_G2_COLLISIONS; z++) { + if (tr->G2CollisionMap[z].mEntityNum == + -1) { // actually, completely break out of this for loop since nothing after this in the aray should ever be valid either + continue; // break;// + } + + CCollisionRecord &coll = tr->G2CollisionMap[z]; + // distFromStart = Distance( start, coll.mCollisionPosition ); + distFromStart = coll.mDistance; /* //FIXME: (distFromStart/length) is not guaranteed to be from 0 to 1... *sigh*... @@ -2120,142 +1662,88 @@ qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, f } */ - for ( i = 0; i < numHitEnts; i++ ) - { - if ( hitEntNum[i] == coll.mEntityNum ) - {//we hit this ent before - //we'll want to add this dist + for (i = 0; i < numHitEnts; i++) { + if (hitEntNum[i] == coll.mEntityNum) { // we hit this ent before + // we'll want to add this dist hitEntDmgAdd[i] = distFromStart; break; } } - if ( i == numHitEnts ) - {//first time we hit this ent - if ( numHitEnts == MAX_G2_COLLISIONS ) - {//hit too many damn ents! + if (i == numHitEnts) { // first time we hit this ent + if (numHitEnts == MAX_G2_COLLISIONS) { // hit too many damn ents! continue; } hitEntNum[numHitEnts] = coll.mEntityNum; - if ( !coll.mFlags ) - {//hmm, we came out first, so we must have started inside - //we'll want to subtract this dist + if (!coll.mFlags) { // hmm, we came out first, so we must have started inside + // we'll want to subtract this dist hitEntDmgAdd[numHitEnts] = distFromStart; - } - else - {//we're entering the model - //we'll want to subtract this dist + } else { // we're entering the model + // we'll want to subtract this dist hitEntDmgSub[numHitEnts] = distFromStart; } - //keep track of how far in the damage was done - hitEntStartFrac[numHitEnts] = hitEntDmgSub[numHitEnts]/length; - //remember the entrance point - VectorCopy( coll.mCollisionPosition, hitEntPoint[numHitEnts] ); - //remember the normal of the face we hit - VectorCopy( coll.mCollisionNormal, hitEntNormal[numHitEnts] ); - VectorNormalize( hitEntNormal[numHitEnts] ); + // keep track of how far in the damage was done + hitEntStartFrac[numHitEnts] = hitEntDmgSub[numHitEnts] / length; + // remember the entrance point + VectorCopy(coll.mCollisionPosition, hitEntPoint[numHitEnts]); + // remember the normal of the face we hit + VectorCopy(coll.mCollisionNormal, hitEntNormal[numHitEnts]); + VectorNormalize(hitEntNormal[numHitEnts]); - //do the effect + // do the effect - //FIXME: check material rather than team? + // FIXME: check material rather than team? hitEnt = &g_entities[hitEntNum[numHitEnts]]; - if ( hitEnt - && hitEnt->client - && coll.mModelIndex > 0 ) - {//hit a submodel on the enemy, not their actual body! - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect ) - { + if (hitEnt && hitEnt->client && coll.mModelIndex > 0) { // hit a submodel on the enemy, not their actual body! + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect) { hitEffect = saber->hitOtherEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect2) { hitEffect = saber->hitOtherEffect2; + } else { + hitEffect = G_EffectIndex(hit_sparks); } - else - { - hitEffect = G_EffectIndex( hit_sparks ); - } - } - else - { - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitPersonEffect ) - { + } else { + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitPersonEffect) { hitEffect = saber->hitPersonEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitPersonEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitPersonEffect2) { hitEffect = saber->hitPersonEffect2; - } - else - { - hitEffect = G_EffectIndex( hit_blood_sparks ); + } else { + hitEffect = G_EffectIndex(hit_blood_sparks); } } - if ( hitEnt != NULL ) - { - if ( hitEnt->client ) - { + if (hitEnt != NULL) { + if (hitEnt->client) { class_t npc_class = hitEnt->client->NPC_class; - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || + npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || + npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || + npc_class == CLASS_SENTRY) { + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect) { hitEffect = saber->hitOtherEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect2) { hitEffect = saber->hitOtherEffect2; - } - else - { - hitEffect = G_EffectIndex( hit_sparks ); + } else { + hitEffect = G_EffectIndex(hit_sparks); } } - } - else - { + } else { // So sue me, this is the easiest way to check to see if this is the turbo laser from t2_wedge, // in which case I don't want the saber effects goin off on it. - if ( (hitEnt->flags&FL_DMG_BY_HEAVY_WEAP_ONLY) - && hitEnt->takedamage == qfalse - && Q_stricmp( hitEnt->classname, "misc_turret" ) == 0 ) - { + if ((hitEnt->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) && hitEnt->takedamage == qfalse && Q_stricmp(hitEnt->classname, "misc_turret") == 0) { continue; - } - else - { - if ( dmg ) - {//only do these effects if actually trying to damage the thing... - if ( (hitEnt->svFlags&SVF_BBRUSH)//a breakable brush - && ( (hitEnt->spawnflags&1)//INVINCIBLE - ||(hitEnt->flags&FL_DMG_BY_HEAVY_WEAP_ONLY) )//HEAVY weapon damage only - ) - {//no hit effect (besides regular client-side one) + } else { + if (dmg) { // only do these effects if actually trying to damage the thing... + if ((hitEnt->svFlags & SVF_BBRUSH) // a breakable brush + && ((hitEnt->spawnflags & 1) // INVINCIBLE + || (hitEnt->flags & FL_DMG_BY_HEAVY_WEAP_ONLY)) // HEAVY weapon damage only + ) { // no hit effect (besides regular client-side one) hitEffect = 0; - } - else - { - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect ) - { + } else { + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect) { hitEffect = saber->hitOtherEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->hitOtherEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->hitOtherEffect2) { hitEffect = saber->hitOtherEffect2; - } - else - { - hitEffect = G_EffectIndex( hit_sparks ); + } else { + hitEffect = G_EffectIndex(hit_sparks); } } } @@ -2263,27 +1751,25 @@ qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, f } } - //FIXME: play less if damage is less? - if ( !g_saberNoEffects ) - { - if ( hitEffect != 0 ) - { - //FIXME: when you have multiple blades hitting someone for many sequential server frames, this can get a bit chuggy! - G_PlayEffect( hitEffect, coll.mCollisionPosition, coll.mCollisionNormal ); + // FIXME: play less if damage is less? + if (!g_saberNoEffects) { + if (hitEffect != 0) { + // FIXME: when you have multiple blades hitting someone for many sequential server frames, this can get a bit chuggy! + G_PlayEffect(hitEffect, coll.mCollisionPosition, coll.mCollisionNormal); } } - //Get the hit location based on surface name - if ( (hitLoc[numHitEnts] == HL_NONE && trHitLoc[numHitEnts] == HL_NONE) - || (hitDismemberLoc[numHitEnts] == HL_NONE && trDismemberLoc[numHitEnts] == HL_NONE) - || (!hitDismember[numHitEnts] && !trDismember[numHitEnts]) ) - {//no hit loc set for this ent this damage cycle yet - //FIXME: find closest impact surf *first* (per ent), then call G_GetHitLocFromSurfName? - //FIXED: if hit multiple ents in this collision record, these trSurfName, trDismember and trDismemberLoc will get stomped/confused over the multiple ents I hit - trSurfName = gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ); - trDismember[numHitEnts] = G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], trSurfName, &trHitLoc[numHitEnts], coll.mCollisionPosition, dmgDir, bladeDir, MOD_SABER, saberType ); - if ( trDismember[numHitEnts] ) - { + // Get the hit location based on surface name + if ((hitLoc[numHitEnts] == HL_NONE && trHitLoc[numHitEnts] == HL_NONE) || + (hitDismemberLoc[numHitEnts] == HL_NONE && trDismemberLoc[numHitEnts] == HL_NONE) || + (!hitDismember[numHitEnts] && !trDismember[numHitEnts])) { // no hit loc set for this ent this damage cycle yet + // FIXME: find closest impact surf *first* (per ent), then call G_GetHitLocFromSurfName? + // FIXED: if hit multiple ents in this collision record, these trSurfName, trDismember and trDismemberLoc will get stomped/confused over the + // multiple ents I hit + trSurfName = gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex); + trDismember[numHitEnts] = G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], trSurfName, &trHitLoc[numHitEnts], coll.mCollisionPosition, + dmgDir, bladeDir, MOD_SABER, saberType); + if (trDismember[numHitEnts]) { trDismemberLoc[numHitEnts] = trHitLoc[numHitEnts]; } /* @@ -2301,209 +1787,152 @@ qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, f } } - //now go through all the ents we hit and do the damage - for ( i = 0; i < numHitEnts; i++ ) - { + // now go through all the ents we hit and do the damage + for (i = 0; i < numHitEnts; i++) { doDmg = dmg; - if ( hitEntNum[i] != ENTITYNUM_NONE ) - { - if ( doDmg < 10 ) - {//base damage is less than 10 - if ( hitEntNum[i] != 0 ) - {//not the player + if (hitEntNum[i] != ENTITYNUM_NONE) { + if (doDmg < 10) { // base damage is less than 10 + if (hitEntNum[i] != 0) { // not the player hitEnt = &g_entities[hitEntNum[i]]; - if ( !hitEnt->client || (hitEnt->client->ps.weapon!=WP_SABER&&hitEnt->client->NPC_class!=CLASS_GALAKMECH&&hitEnt->client->playerTeam==enemyTeam) ) - {//did *not* hit a jedi and did *not* hit the player - //make sure the base damage is high against non-jedi, feels better + if (!hitEnt->client || (hitEnt->client->ps.weapon != WP_SABER && hitEnt->client->NPC_class != CLASS_GALAKMECH && + hitEnt->client->playerTeam == enemyTeam)) { // did *not* hit a jedi and did *not* hit the player + // make sure the base damage is high against non-jedi, feels better doDmg = 10; } } } - if ( !hitEntDmgAdd[i] && !hitEntDmgSub[i] ) - {//spent entire time in model - //NOTE: will we even get a collision then? + if (!hitEntDmgAdd[i] && !hitEntDmgSub[i]) { // spent entire time in model + // NOTE: will we even get a collision then? doDmg *= length; - } - else if ( hitEntDmgAdd[i] && hitEntDmgSub[i] ) - {//we did enter and exit + } else if (hitEntDmgAdd[i] && hitEntDmgSub[i]) { // we did enter and exit doDmg *= hitEntDmgAdd[i] - hitEntDmgSub[i]; - } - else if ( !hitEntDmgAdd[i] ) - {//we didn't exit, just entered + } else if (!hitEntDmgAdd[i]) { // we didn't exit, just entered doDmg *= length - hitEntDmgSub[i]; - } - else if ( !hitEntDmgSub[i] ) - {//we didn't enter, only exited + } else if (!hitEntDmgSub[i]) { // we didn't enter, only exited doDmg *= hitEntDmgAdd[i]; } - if ( doDmg > 0 ) - { - WP_SaberDamageAdd( 1.0, hitEntNum[i], dmgDir, bladeVec, hitEntNormal[i], hitEntPoint[i], ceil(doDmg), hitEntStartFrac[i], trHitLoc[i], trDismember[i], trDismemberLoc[i] ); + if (doDmg > 0) { + WP_SaberDamageAdd(1.0, hitEntNum[i], dmgDir, bladeVec, hitEntNormal[i], hitEntPoint[i], ceil(doDmg), hitEntStartFrac[i], trHitLoc[i], + trDismember[i], trDismemberLoc[i]); } } } - return (qboolean)(numHitEnts>0); + return (qboolean)(numHitEnts > 0); } -void WP_SaberBlockEffect( gentity_t *attacker, int saberNum, int bladeNum, vec3_t position, vec3_t normal, qboolean cutNotBlock ) -{ +void WP_SaberBlockEffect(gentity_t *attacker, int saberNum, int bladeNum, vec3_t position, vec3_t normal, qboolean cutNotBlock) { saberInfo_t *saber = NULL; - if ( attacker && attacker->client ) - { + if (attacker && attacker->client) { saber = &attacker->client->ps.saber[saberNum]; } - if ( saber - && !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->blockEffect ) - { - if ( normal ) - { - G_PlayEffect( saber->blockEffect, position, normal ); + if (saber && !WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->blockEffect) { + if (normal) { + G_PlayEffect(saber->blockEffect, position, normal); + } else { + G_PlayEffect(saber->blockEffect, position); } - else - { - G_PlayEffect( saber->blockEffect, position ); - } - } - else if ( saber - && WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) - && saber->blockEffect2 ) - { - if ( normal ) - { - G_PlayEffect( saber->blockEffect2, position, normal ); - } - else - { - G_PlayEffect( saber->blockEffect2, position ); - } - } - else if ( cutNotBlock ) - { - if ( normal ) - { - G_PlayEffect( "saber/saber_cut", position, normal ); + } else if (saber && WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && saber->blockEffect2) { + if (normal) { + G_PlayEffect(saber->blockEffect2, position, normal); + } else { + G_PlayEffect(saber->blockEffect2, position); } - else - { - G_PlayEffect( "saber/saber_cut", position ); + } else if (cutNotBlock) { + if (normal) { + G_PlayEffect("saber/saber_cut", position, normal); + } else { + G_PlayEffect("saber/saber_cut", position); } - } - else - { + } else { - if ( normal ) - { - G_PlayEffect( "saber/saber_block", position, normal ); - } - else - { - G_PlayEffect( "saber/saber_block", position ); + if (normal) { + G_PlayEffect("saber/saber_block", position, normal); + } else { + G_PlayEffect("saber/saber_block", position); } } } -void WP_SaberKnockaway( gentity_t *attacker, trace_t *tr ) -{ - WP_SaberDrop( attacker, &g_entities[attacker->client->ps.saberEntityNum] ); - WP_SaberBlockSound( attacker, NULL, 0, 0 ); - //G_Sound( &g_entities[attacker->client->ps.saberEntityNum], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - WP_SaberBlockEffect( attacker, 0, 0, tr->endpos, NULL, qfalse ); +void WP_SaberKnockaway(gentity_t *attacker, trace_t *tr) { + WP_SaberDrop(attacker, &g_entities[attacker->client->ps.saberEntityNum]); + WP_SaberBlockSound(attacker, NULL, 0, 0); + // G_Sound( &g_entities[attacker->client->ps.saberEntityNum], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + WP_SaberBlockEffect(attacker, 0, 0, tr->endpos, NULL, qfalse); saberHitFraction = tr->fraction; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_MAGENTA"WP_SaberKnockaway: saberHitFraction %4.2f\n", saberHitFraction ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_MAGENTA "WP_SaberKnockaway: saberHitFraction %4.2f\n", saberHitFraction); } #endif - VectorCopy( tr->endpos, saberHitLocation ); + VectorCopy(tr->endpos, saberHitLocation); saberHitEntity = tr->entityNum; - if ( !g_noClashFlare ) - { - g_saberFlashTime = level.time-50; - VectorCopy( saberHitLocation, g_saberFlashPos ); + if (!g_noClashFlare) { + g_saberFlashTime = level.time - 50; + VectorCopy(saberHitLocation, g_saberFlashPos); } - //FIXME: make hitEnt play an attack anim or some other special anim when this happens - //gentity_t *hitEnt = &g_entities[tr->entityNum]; - //NPC_SetAnim( hitEnt, SETANIM_BOTH, BOTH_KNOCKSABER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // FIXME: make hitEnt play an attack anim or some other special anim when this happens + // gentity_t *hitEnt = &g_entities[tr->entityNum]; + // NPC_SetAnim( hitEnt, SETANIM_BOTH, BOTH_KNOCKSABER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } -qboolean G_InCinematicSaberAnim( gentity_t *self ) -{ - if ( self->NPC - && self->NPC->behaviorState == BS_CINEMATIC - && (self->client->ps.torsoAnim == BOTH_CIN_16 ||self->client->ps.torsoAnim == BOTH_CIN_17) ) - { +qboolean G_InCinematicSaberAnim(gentity_t *self) { + if (self->NPC && self->NPC->behaviorState == BS_CINEMATIC && (self->client->ps.torsoAnim == BOTH_CIN_16 || self->client->ps.torsoAnim == BOTH_CIN_17)) { return qtrue; } return qfalse; } -#define SABER_COLLISION_DIST 6//was 2//was 4//was 8//was 16 -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg, - vec3_t bladeDir, qboolean noGhoul, int attackStrength, - saberType_t saberType, qboolean extrapolate, - int saberNum, int bladeNum ) -{ - trace_t tr; - vec3_t dir; - int mask = (MASK_SHOT|CONTENTS_LIGHTSABER); - gentity_t *attacker = &g_entities[ignore]; - - vec3_t end2; - VectorCopy( end, end2 ); - if ( extrapolate ) - { - //NOTE: since we can no longer use the predicted point, extrapolate the trace some. +#define SABER_COLLISION_DIST 6 // was 2//was 4//was 8//was 16 +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +qboolean WP_SaberDamageForTrace(int ignore, vec3_t start, vec3_t end, float dmg, vec3_t bladeDir, qboolean noGhoul, int attackStrength, saberType_t saberType, + qboolean extrapolate, int saberNum, int bladeNum) { + trace_t tr; + vec3_t dir; + int mask = (MASK_SHOT | CONTENTS_LIGHTSABER); + gentity_t *attacker = &g_entities[ignore]; + + vec3_t end2; + VectorCopy(end, end2); + if (extrapolate) { + // NOTE: since we can no longer use the predicted point, extrapolate the trace some. // this may allow saber hits that aren't actually hits, but it doesn't look too bad vec3_t diff; - VectorSubtract( end, start, diff ); - VectorNormalize( diff ); - VectorMA( end2, SABER_EXTRAPOLATE_DIST, diff, end2 ); + VectorSubtract(end, start, diff); + VectorNormalize(diff); + VectorMA(end2, SABER_EXTRAPOLATE_DIST, diff, end2); } - if ( !noGhoul ) - { + if (!noGhoul) { float useRadiusForDamage = 0; - if ( attacker - && attacker->client ) - {//see if we're not drawing the blade, if so, do a trace based on radius of blade (because the radius is being used to simulate a larger/smaller piece of a solid weapon)... - if ( !WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && (attacker->client->ps.saber[saberNum].saberFlags2&SFL2_NO_BLADE) ) - {//not drawing blade + if (attacker && attacker->client) { // see if we're not drawing the blade, if so, do a trace based on radius of blade (because the radius is being used + // to simulate a larger/smaller piece of a solid weapon)... + if (!WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + (attacker->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_BLADE)) { // not drawing blade useRadiusForDamage = attacker->client->ps.saber[saberNum].blade[bladeNum].radius; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && (attacker->client->ps.saber[saberNum].saberFlags2&SFL2_NO_BLADE2) ) - {//not drawing blade + } else if (WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + (attacker->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_BLADE2)) { // not drawing blade useRadiusForDamage = attacker->client->ps.saber[saberNum].blade[bladeNum].radius; } } - if ( !useRadiusForDamage ) - {//do normal check for larger-size saber traces - if ( !attacker->s.number - || (attacker->client - && (attacker->client->playerTeam==TEAM_PLAYER - || attacker->client->NPC_class==CLASS_SHADOWTROOPER - || attacker->client->NPC_class==CLASS_ALORA - || (attacker->NPC && (attacker->NPC->aiFlags&NPCAI_BOSS_CHARACTER)) - ) - ) - )//&&attackStrength==FORCE_LEVEL_3) + if (!useRadiusForDamage) { // do normal check for larger-size saber traces + if (!attacker->s.number || + (attacker->client && (attacker->client->playerTeam == TEAM_PLAYER || attacker->client->NPC_class == CLASS_SHADOWTROOPER || + attacker->client->NPC_class == CLASS_ALORA || + (attacker->NPC && (attacker->NPC->aiFlags & NPCAI_BOSS_CHARACTER))))) //&&attackStrength==FORCE_LEVEL_3) { useRadiusForDamage = 2; } } - if ( useRadiusForDamage > 0 )//&&attackStrength==FORCE_LEVEL_3) - {//player,. player allies, shadowtroopers, tavion and desann use larger traces - vec3_t traceMins = {-useRadiusForDamage,-useRadiusForDamage,-useRadiusForDamage}, traceMaxs = {useRadiusForDamage,useRadiusForDamage,useRadiusForDamage}; - gi.trace( &tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX + if (useRadiusForDamage > 0) //&&attackStrength==FORCE_LEVEL_3) + { // player,. player allies, shadowtroopers, tavion and desann use larger traces + vec3_t traceMins = {-useRadiusForDamage, -useRadiusForDamage, -useRadiusForDamage}, + traceMaxs = {useRadiusForDamage, useRadiusForDamage, useRadiusForDamage}; + gi.trace(&tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10); // G2_SUPERSIZEDBBOX } /* else if ( !attacker->s.number ) @@ -2512,131 +1941,100 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg gi.trace( &tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX } */ - else - {//reborn use smaller traces - gi.trace( &tr, start, NULL, NULL, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX + else { // reborn use smaller traces + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask, G2_COLLIDE, 10); // G2_SUPERSIZEDBBOX } + } else { + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask, G2_NOCOLLIDE, 10); } - else - { - gi.trace( &tr, start, NULL, NULL, end2, ignore, mask, G2_NOCOLLIDE, 10 ); - } - #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( attacker != NULL && attacker->client != NULL ) - { - G_DebugLine(start, end2, FRAMETIME, WPDEBUG_SaberColor( attacker->client->ps.saber[0].blade[0].color ), qtrue); + if (d_saberCombat->integer > 1) { + if (attacker != NULL && attacker->client != NULL) { + G_DebugLine(start, end2, FRAMETIME, WPDEBUG_SaberColor(attacker->client->ps.saber[0].blade[0].color), qtrue); } } #endif - if ( tr.entityNum == ENTITYNUM_NONE ) - { + if (tr.entityNum == ENTITYNUM_NONE) { return qfalse; } - if ( tr.entityNum == ENTITYNUM_WORLD ) - { - if ( attacker && attacker->client && (attacker->client->ps.saber[saberNum].saberFlags&SFL_BOUNCE_ON_WALLS) ) - { - VectorCopy( tr.endpos, saberHitLocation ); - VectorCopy( tr.plane.normal, saberHitNormal ); + if (tr.entityNum == ENTITYNUM_WORLD) { + if (attacker && attacker->client && (attacker->client->ps.saber[saberNum].saberFlags & SFL_BOUNCE_ON_WALLS)) { + VectorCopy(tr.endpos, saberHitLocation); + VectorCopy(tr.plane.normal, saberHitNormal); } return qtrue; } - if ( &g_entities[tr.entityNum] ) - { + if (&g_entities[tr.entityNum]) { gentity_t *hitEnt = &g_entities[tr.entityNum]; gentity_t *owner = g_entities[tr.entityNum].owner; - if ( hitEnt->contents & CONTENTS_LIGHTSABER ) - { - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - {//thrown saber hit something - if ( owner - && owner->s.number - && owner->client - && owner->NPC - && owner->health > 0 ) - { - if ( owner->client->NPC_class == CLASS_ALORA ) - {//alora takes less damage + if (hitEnt->contents & CONTENTS_LIGHTSABER) { + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { // thrown saber hit something + if (owner && owner->s.number && owner->client && owner->NPC && owner->health > 0) { + if (owner->client->NPC_class == CLASS_ALORA) { // alora takes less damage dmg *= 0.25f; - } + } else if ( owner->client->NPC_class == CLASS_TAVION /*|| (owner->client->NPC_class == CLASS_SHADOWTROOPER && !Q_irand( 0, g_spskill->integer*3 )) || (Q_irand( -5, owner->NPC->rank ) > RANK_CIVILIAN && !Q_irand( 0, g_spskill->integer*3 ))*/ ) {//Tavion can toss a blocked thrown saber aside - WP_SaberKnockaway( attacker, &tr ); - Jedi_PlayDeflectSound( owner ); + WP_SaberKnockaway(attacker, &tr); + Jedi_PlayDeflectSound(owner); return qfalse; } } } - //FIXME: take target FP_SABER_DEFENSE and attacker FP_SABER_OFFENSE into account here somehow? - qboolean sabersIntersect = WP_SabersIntersect( attacker, saberNum, bladeNum, owner, qfalse );//qtrue ); + // FIXME: take target FP_SABER_DEFENSE and attacker FP_SABER_OFFENSE into account here somehow? + qboolean sabersIntersect = WP_SabersIntersect(attacker, saberNum, bladeNum, owner, qfalse); // qtrue ); float sabersDist; - if ( attacker && attacker->client && attacker->client->ps.saberInFlight - && owner && owner->s.number == 0 && (g_saberAutoBlocking->integer||attacker->client->ps.saberBlockingTime>level.time) )//NPC flying saber hit player's saber bounding box - {//players have g_saberAutoBlocking, do the more generous check against flying sabers - //FIXME: instead of hitting the player's saber bounding box - //and picking an anim afterwards, have him use AI similar - //to the AI the jedi use for picking a saber melee block...? + if (attacker && attacker->client && attacker->client->ps.saberInFlight && owner && owner->s.number == 0 && + (g_saberAutoBlocking->integer || attacker->client->ps.saberBlockingTime > level.time)) // NPC flying saber hit player's saber bounding box + { // players have g_saberAutoBlocking, do the more generous check against flying sabers + // FIXME: instead of hitting the player's saber bounding box + // and picking an anim afterwards, have him use AI similar + // to the AI the jedi use for picking a saber melee block...? sabersDist = 0; - } - else - {//sabers must actually collide with the attacking saber - sabersDist = WP_SabersDistance( attacker, owner ); - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - { + } else { // sabers must actually collide with the attacking saber + sabersDist = WP_SabersDistance(attacker, owner); + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { sabersDist /= 2.0f; - if ( sabersDist <= 16.0f ) - { + if (sabersDist <= 16.0f) { sabersIntersect = qtrue; } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - gi.Printf( "sabersDist: %4.2f\n", sabersDist ); + if (d_saberCombat->integer > 1) { + gi.Printf("sabersDist: %4.2f\n", sabersDist); } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } - if ( sabersCrossed == -1 || sabersCrossed > sabersDist ) - { + if (sabersCrossed == -1 || sabersCrossed > sabersDist) { sabersCrossed = sabersDist; } - float collisionDist; - if ( g_saberRealisticCombat->integer ) - { + float collisionDist; + if (g_saberRealisticCombat->integer) { collisionDist = SABER_COLLISION_DIST; + } else { + collisionDist = SABER_COLLISION_DIST + 6 + g_spskill->integer * 4; } - else { - collisionDist = SABER_COLLISION_DIST+6+g_spskill->integer*4; - } - { - if ( G_InCinematicSaberAnim( owner ) - && G_InCinematicSaberAnim( attacker ) ) - { - sabersIntersect = qtrue; - } + if (G_InCinematicSaberAnim(owner) && G_InCinematicSaberAnim(attacker)) { + sabersIntersect = qtrue; + } } - if ( owner && owner->client && (attacker != NULL) - && (sabersDist > collisionDist )//|| !InFront( attacker->currentOrigin, owner->currentOrigin, owner->client->ps.viewangles, 0.35f )) - && !sabersIntersect )//was qtrue, but missed too much? - {//swing came from behind and/or was not stopped by a lightsaber - //re-try the trace without checking for lightsabers - gi.trace ( &tr, start, NULL, NULL, end2, ignore, mask&~CONTENTS_LIGHTSABER, G2_NOCOLLIDE, 10 ); - if ( tr.entityNum == ENTITYNUM_WORLD ) - { - return qtrue; + if (owner && owner->client && (attacker != NULL) && + (sabersDist > collisionDist) //|| !InFront( attacker->currentOrigin, owner->currentOrigin, owner->client->ps.viewangles, 0.35f )) + && !sabersIntersect) // was qtrue, but missed too much? + { // swing came from behind and/or was not stopped by a lightsaber + // re-try the trace without checking for lightsabers + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask & ~CONTENTS_LIGHTSABER, G2_NOCOLLIDE, 10); + if (tr.entityNum == ENTITYNUM_WORLD) { + return qtrue; } - if ( tr.entityNum == ENTITYNUM_NONE || &g_entities[tr.entityNum] == NULL ) - {//didn't hit the owner + if (tr.entityNum == ENTITYNUM_NONE || &g_entities[tr.entityNum] == NULL) { // didn't hit the owner /* if ( attacker && attacker->client @@ -2662,74 +2060,57 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg } } */ - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_MAGENTA"%d saber hit owner through saber %4.2f, dist = %4.2f\n", level.time, saberHitFraction, sabersDist ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_MAGENTA "%d saber hit owner through saber %4.2f, dist = %4.2f\n", level.time, saberHitFraction, sabersDist); } } -#endif//FINAL_BUILD +#endif // FINAL_BUILD hitEnt = &g_entities[tr.entityNum]; owner = g_entities[tr.entityNum].owner; - } - else - {//hit a lightsaber - if ( (tr.fraction < saberHitFraction || tr.startsolid) - && sabersDist < (8.0f+g_spskill->value)*4.0f// 50.0f//16.0f - && (sabersIntersect || sabersDist < (4.0f+g_spskill->value)*2.0f) )//32.0f) ) - { // This saber hit closer than the last one. - if ( (tr.allsolid || tr.startsolid) && owner && owner->client ) - {//tr.fraction will be 0, unreliable... so calculate actual - float dist = Distance( start, end2 ); - if ( dist ) - { - float hitFrac = WP_SabersDistance( attacker, owner )/dist; - if ( hitFrac > 1.0f ) - {//umm... minimum distance between sabers was longer than trace...? + } else { // hit a lightsaber + if ((tr.fraction < saberHitFraction || tr.startsolid) && sabersDist < (8.0f + g_spskill->value) * 4.0f // 50.0f//16.0f + && (sabersIntersect || sabersDist < (4.0f + g_spskill->value) * 2.0f)) // 32.0f) ) + { // This saber hit closer than the last one. + if ((tr.allsolid || tr.startsolid) && owner && owner->client) { // tr.fraction will be 0, unreliable... so calculate actual + float dist = Distance(start, end2); + if (dist) { + float hitFrac = WP_SabersDistance(attacker, owner) / dist; + if (hitFrac > 1.0f) { // umm... minimum distance between sabers was longer than trace...? hitFrac = 1.0f; } - if ( hitFrac < saberHitFraction ) - { + if (hitFrac < saberHitFraction) { saberHitFraction = hitFrac; } - } - else - { + } else { saberHitFraction = 0.0f; } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_GREEN"%d saber hit saber dist %4.2f allsolid %4.2f\n", level.time, sabersDist, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_GREEN "%d saber hit saber dist %4.2f allsolid %4.2f\n", level.time, sabersDist, saberHitFraction); } } -#endif//FINAL_BUILD - } - else - { +#endif // FINAL_BUILD + } else { #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_BLUE"%d saber hit saber dist %4.2f, frac %4.2f\n", level.time, sabersDist, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_BLUE "%d saber hit saber dist %4.2f, frac %4.2f\n", level.time, sabersDist, saberHitFraction); } saberHitFraction = tr.fraction; } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_MAGENTA"hit saber: saberHitFraction %4.2f, allsolid %d, startsolid %d\n", saberHitFraction, tr.allsolid, tr.startsolid ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_MAGENTA "hit saber: saberHitFraction %4.2f, allsolid %d, startsolid %d\n", saberHitFraction, tr.allsolid, + tr.startsolid); } -#endif//FINAL_BUILD +#endif // FINAL_BUILD VectorCopy(tr.endpos, saberHitLocation); saberHitEntity = tr.entityNum; } @@ -2760,174 +2141,133 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg } } */ - //FIXME: check to see if we broke the saber + // FIXME: check to see if we broke the saber // go through the impacted surfaces and call WP_BreakSaber // PROBLEM: saberEnt doesn't actually have a saber g2 model // and/or isn't in same location as saber model attached // to the client. We'd have to fake it somehow... - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } - } - else - { + } else { #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_RED"%d saber hit owner directly %4.2f\n", level.time, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_RED "%d saber hit owner directly %4.2f\n", level.time, saberHitFraction); } } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - {//thrown saber hit something - if ( ( hitEnt && hitEnt->client && hitEnt->health > 0 && ( hitEnt->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",hitEnt->NPC_type) || hitEnt->client->NPC_class == CLASS_LUKE || hitEnt->client->NPC_class == CLASS_BOBAFETT || (hitEnt->client->ps.powerups[PW_GALAK_SHIELD] > 0) ) ) || - ( owner && owner->client && owner->health > 0 && ( owner->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",owner->NPC_type) || owner->client->NPC_class == CLASS_LUKE || (owner->client->ps.powerups[PW_GALAK_SHIELD] > 0) ) ) ) - {//Luke and Desann slap thrown sabers aside - //FIXME: control the direction of the thrown saber... if hit Galak's shield, bounce directly away from his origin? - WP_SaberKnockaway( attacker, &tr ); - if ( hitEnt->client ) - { - Jedi_PlayDeflectSound( hitEnt ); + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { // thrown saber hit something + if ((hitEnt && hitEnt->client && hitEnt->health > 0 && + (hitEnt->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", hitEnt->NPC_type) || hitEnt->client->NPC_class == CLASS_LUKE || + hitEnt->client->NPC_class == CLASS_BOBAFETT || (hitEnt->client->ps.powerups[PW_GALAK_SHIELD] > 0))) || + (owner && owner->client && owner->health > 0 && + (owner->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", owner->NPC_type) || owner->client->NPC_class == CLASS_LUKE || + (owner->client->ps.powerups[PW_GALAK_SHIELD] > 0)))) { // Luke and Desann slap thrown sabers aside + // FIXME: control the direction of the thrown saber... if hit Galak's shield, bounce directly away from his origin? + WP_SaberKnockaway(attacker, &tr); + if (hitEnt->client) { + Jedi_PlayDeflectSound(hitEnt); + } else { + Jedi_PlayDeflectSound(owner); } - else - { - Jedi_PlayDeflectSound( owner ); - } - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } } - if ( hitEnt->takedamage ) - { - //no team damage: if ( !hitEnt->client || attacker == NULL || !attacker->client || (hitEnt->client->playerTeam != attacker->client->playerTeam) ) + if (hitEnt->takedamage) { + // no team damage: if ( !hitEnt->client || attacker == NULL || !attacker->client || (hitEnt->client->playerTeam != attacker->client->playerTeam) ) { - vec3_t bladeVec={0}; - if ( attacker && attacker->client ) - { - VectorScale( bladeDir, attacker->client->ps.saber[saberNum].blade[bladeNum].length, bladeVec ); + vec3_t bladeVec = {0}; + if (attacker && attacker->client) { + VectorScale(bladeDir, attacker->client->ps.saber[saberNum].blade[bladeNum].length, bladeVec); } - //multiply the damage by the total distance of the swipe - VectorSubtract( end2, start, dir ); - float len = VectorNormalize( dir );//VectorLength( dir ); - if ( noGhoul || !hitEnt->ghoul2.size() ) - {//we weren't doing a ghoul trace + // multiply the damage by the total distance of the swipe + VectorSubtract(end2, start, dir); + float len = VectorNormalize(dir); // VectorLength( dir ); + if (noGhoul || !hitEnt->ghoul2.size()) { // we weren't doing a ghoul trace int hitEffect = 0; - if ( dmg >= 1.0 && hitEnt->bmodel ) - { + if (dmg >= 1.0 && hitEnt->bmodel) { dmg = 1.0; } - if ( len > 1 ) - { + if (len > 1) { dmg *= len; } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !(hitEnt->contents & CONTENTS_LIGHTSABER) ) - { - gi.Printf( S_COLOR_GREEN"Hit ent, but no ghoul collisions\n" ); + if (d_saberCombat->integer > 1) { + if (!(hitEnt->contents & CONTENTS_LIGHTSABER)) { + gi.Printf(S_COLOR_GREEN "Hit ent, but no ghoul collisions\n"); } } #endif - float trFrac, dmgFrac; - if ( tr.allsolid ) - {//totally inside them + float trFrac, dmgFrac; + if (tr.allsolid) { // totally inside them trFrac = 1.0; dmgFrac = 0.0; - } - else if ( tr.startsolid ) - {//started inside them - //we don't know how much was inside, we know it's less than all, so use half? + } else if (tr.startsolid) { // started inside them + // we don't know how much was inside, we know it's less than all, so use half? trFrac = 0.5; dmgFrac = 0.0; - } - else - {//started outside them and hit them - //yeah. this doesn't account for coming out the other wide, but we can worry about that later (use ghoul2) + } else { // started outside them and hit them + // yeah. this doesn't account for coming out the other wide, but we can worry about that later (use ghoul2) trFrac = (1.0f - tr.fraction); dmgFrac = tr.fraction; } vec3_t backdir; - VectorScale( dir, -1, backdir ); - WP_SaberDamageAdd( trFrac, tr.entityNum, dir, bladeVec, backdir, tr.endpos, dmg, dmgFrac, HL_NONE, qfalse, HL_NONE ); - if ( !tr.allsolid && !tr.startsolid ) - { - VectorScale( dir, -1, dir ); - } - if ( hitEnt != NULL ) - { - if ( hitEnt->client ) - { - //don't do blood sparks on non-living things + VectorScale(dir, -1, backdir); + WP_SaberDamageAdd(trFrac, tr.entityNum, dir, bladeVec, backdir, tr.endpos, dmg, dmgFrac, HL_NONE, qfalse, HL_NONE); + if (!tr.allsolid && !tr.startsolid) { + VectorScale(dir, -1, dir); + } + if (hitEnt != NULL) { + if (hitEnt->client) { + // don't do blood sparks on non-living things class_t npc_class = hitEnt->client->NPC_class; - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { - if ( !WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].hitOtherEffect ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || npc_class == CLASS_PROTOCOL || + npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || + npc_class == CLASS_SENTRY) { + if (!WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + attacker->client->ps.saber[saberNum].hitOtherEffect) { hitEffect = attacker->client->ps.saber[saberNum].hitOtherEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].hitOtherEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + attacker->client->ps.saber[saberNum].hitOtherEffect2) { hitEffect = attacker->client->ps.saber[saberNum].hitOtherEffect2; - } - else - { - hitEffect = G_EffectIndex( hit_sparks ); + } else { + hitEffect = G_EffectIndex(hit_sparks); } } - } - else - { - if ( dmg ) - {//only do these effects if actually trying to damage the thing... - if ( (hitEnt->svFlags&SVF_BBRUSH)//a breakable brush - && ( (hitEnt->spawnflags&1)//INVINCIBLE - ||(hitEnt->flags&FL_DMG_BY_HEAVY_WEAP_ONLY)//HEAVY weapon damage only - ||(hitEnt->NPC_targetname&&attacker&&attacker->targetname&&Q_stricmp(attacker->targetname,hitEnt->NPC_targetname)) ) )//only breakable by an entity who is not the attacker - {//no hit effect (besides regular client-side one) - } - else - { - if ( !WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].hitOtherEffect ) - { + } else { + if (dmg) { // only do these effects if actually trying to damage the thing... + if ((hitEnt->svFlags & SVF_BBRUSH) // a breakable brush + && ((hitEnt->spawnflags & 1) // INVINCIBLE + || (hitEnt->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) // HEAVY weapon damage only + || (hitEnt->NPC_targetname && attacker && attacker->targetname && + Q_stricmp(attacker->targetname, hitEnt->NPC_targetname)))) // only breakable by an entity who is not the attacker + { // no hit effect (besides regular client-side one) + } else { + if (!WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + attacker->client->ps.saber[saberNum].hitOtherEffect) { hitEffect = attacker->client->ps.saber[saberNum].hitOtherEffect; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &attacker->client->ps.saber[saberNum], bladeNum ) - && attacker->client->ps.saber[saberNum].hitOtherEffect2 ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(&attacker->client->ps.saber[saberNum], bladeNum) && + attacker->client->ps.saber[saberNum].hitOtherEffect2) { hitEffect = attacker->client->ps.saber[saberNum].hitOtherEffect2; - } - else - { - hitEffect = G_EffectIndex( hit_sparks ); + } else { + hitEffect = G_EffectIndex(hit_sparks); } } } } } - if ( !g_saberNoEffects && hitEffect != 0 ) - { - G_PlayEffect( hitEffect, tr.endpos, dir );//"saber_cut" + if (!g_saberNoEffects && hitEffect != 0) { + G_PlayEffect(hitEffect, tr.endpos, dir); //"saber_cut" } - } - else - {//we were doing a ghoul trace - if ( !attacker - || !attacker->client - || attacker->client->ps.saberLockTime < level.time ) - { - if ( !WP_SaberDamageEffects( &tr, start, len, dmg, dir, bladeVec, attacker->client->enemyTeam, saberType, &attacker->client->ps.saber[saberNum], bladeNum ) ) - {//didn't hit a ghoul ent + } else { // we were doing a ghoul trace + if (!attacker || !attacker->client || attacker->client->ps.saberLockTime < level.time) { + if (!WP_SaberDamageEffects(&tr, start, len, dmg, dir, bladeVec, attacker->client->enemyTeam, saberType, + &attacker->client->ps.saber[saberNum], bladeNum)) { // didn't hit a ghoul ent /* if ( && hitEnt->ghoul2.size() ) {//it was a ghoul2 model so we should have hit it @@ -2946,48 +2286,34 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg #define LOCK_IDEAL_DIST_TOP 32.0f #define LOCK_IDEAL_DIST_CIRCLE 48.0f -#define LOCK_IDEAL_DIST_JKA 46.0f//all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN -extern void PM_SetAnimFrame( gentity_t *gent, int frame, qboolean torso, qboolean legs ); -extern qboolean ValidAnimFileIndex ( int index ); -int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSide, int lockOrBreakOrSuperBreak, int winOrLose ) -{ +#define LOCK_IDEAL_DIST_JKA 46.0f // all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN +extern void PM_SetAnimFrame(gentity_t *gent, int frame, qboolean torso, qboolean legs); +extern qboolean ValidAnimFileIndex(int index); +int G_SaberLockAnim(int attackerSaberStyle, int defenderSaberStyle, int topOrSide, int lockOrBreakOrSuperBreak, int winOrLose) { int baseAnim = -1; - if ( lockOrBreakOrSuperBreak == SABERLOCK_LOCK ) - {//special case: if we're using the same style and locking - if ( attackerSaberStyle == defenderSaberStyle - || (attackerSaberStyle>=SS_FAST&&attackerSaberStyle<=SS_TAVION&&defenderSaberStyle>=SS_FAST&&defenderSaberStyle<=SS_TAVION) ) - {//using same style - if ( winOrLose == SABERLOCK_LOSE ) - {//you want the defender's stance... - switch ( defenderSaberStyle ) - { + if (lockOrBreakOrSuperBreak == SABERLOCK_LOCK) { // special case: if we're using the same style and locking + if (attackerSaberStyle == defenderSaberStyle || (attackerSaberStyle >= SS_FAST && attackerSaberStyle <= SS_TAVION && defenderSaberStyle >= SS_FAST && + defenderSaberStyle <= SS_TAVION)) { // using same style + if (winOrLose == SABERLOCK_LOSE) { // you want the defender's stance... + switch (defenderSaberStyle) { case SS_DUAL: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_DL_DL_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_DL_DL_S_L_2; } break; case SS_STAFF: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_ST_ST_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_ST_ST_S_L_2; } break; default: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_S_S_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_S_S_S_L_2; } break; @@ -2995,72 +2321,61 @@ int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSi } } } - if ( baseAnim == -1 ) - { - switch ( attackerSaberStyle ) - { + if (baseAnim == -1) { + switch (attackerSaberStyle) { case SS_DUAL: - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_DL_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_DL_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_DL_S_S_B_1_L; - break; + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_DL_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_DL_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_DL_S_S_B_1_L; + break; } break; case SS_STAFF: - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_ST_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_ST_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_ST_S_S_B_1_L; - break; + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_ST_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_ST_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_ST_S_S_B_1_L; + break; } break; - default://single - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_S_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_S_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_S_S_S_B_1_L; - break; + default: // single + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_S_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_S_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_S_S_S_B_1_L; + break; } break; } - //side lock or top lock? - if ( topOrSide == SABERLOCK_TOP ) - { + // side lock or top lock? + if (topOrSide == SABERLOCK_TOP) { baseAnim += 5; } - //lock, break or superbreak? - if ( lockOrBreakOrSuperBreak == SABERLOCK_LOCK ) - { + // lock, break or superbreak? + if (lockOrBreakOrSuperBreak == SABERLOCK_LOCK) { baseAnim += 2; - } - else - {//a break or superbreak - if ( lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK ) - { + } else { // a break or superbreak + if (lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK) { baseAnim += 3; } - //winner or loser? - if ( winOrLose == SABERLOCK_WIN ) - { + // winner or loser? + if (winOrLose == SABERLOCK_WIN) { baseAnim += 1; } } @@ -3068,85 +2383,72 @@ int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSi return baseAnim; } -qboolean G_CheckIncrementLockAnim( int anim, int winOrLose ) -{ - qboolean increment = qfalse;//??? - //RULE: if you are the first style in the lock anim, you advance from LOSING position to WINNING position +qboolean G_CheckIncrementLockAnim(int anim, int winOrLose) { + qboolean increment = qfalse; //??? + // RULE: if you are the first style in the lock anim, you advance from LOSING position to WINNING position // if you are the second style in the lock anim, you advance from WINNING position to LOSING position - switch ( anim ) - { - //increment to win: - case BOTH_LK_DL_DL_S_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_S_L_2: //lock if I'm using dual vs. dual and other initiated - case BOTH_LK_DL_DL_T_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_T_L_2: //lock if I'm using dual vs. dual and other initiated - case BOTH_LK_DL_S_S_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_S_T_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_ST_S_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_ST_T_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_S_S_S_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_S_T_L_2: //lock if I'm using single vs. a single and other initiated - case BOTH_LK_ST_S_S_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_S_T_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_ST_T_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_T_L_2: //lock if I'm using staff vs. a staff and other initiated - if ( winOrLose == SABERLOCK_WIN ) - { + switch (anim) { + // increment to win: + case BOTH_LK_DL_DL_S_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_S_L_2: // lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_T_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_T_L_2: // lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_S_S_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_S_T_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_ST_S_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_ST_T_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_S_S_S_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_S_T_L_2: // lock if I'm using single vs. a single and other initiated + case BOTH_LK_ST_S_S_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_S_T_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_ST_T_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_T_L_2: // lock if I'm using staff vs. a staff and other initiated + if (winOrLose == SABERLOCK_WIN) { increment = qtrue; - } - else - { + } else { increment = qfalse; } break; - //decrement to win: - case BOTH_LK_S_DL_S_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_DL_T_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_S_S_L_2: //lock if I'm using single vs. a single and other intitiated - case BOTH_LK_S_S_T_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_ST_S_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_ST_T_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_ST_DL_S_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_DL_T_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_ST_S_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_S_L_2: //lock if I'm using staff vs. a staff and other initiated - if ( winOrLose == SABERLOCK_WIN ) - { + // decrement to win: + case BOTH_LK_S_DL_S_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_DL_T_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_S_S_L_2: // lock if I'm using single vs. a single and other intitiated + case BOTH_LK_S_S_T_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_ST_S_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_ST_T_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_ST_DL_S_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_DL_T_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_ST_S_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_S_L_2: // lock if I'm using staff vs. a staff and other initiated + if (winOrLose == SABERLOCK_WIN) { increment = qfalse; - } - else - { + } else { increment = qtrue; } break; default: #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: unknown Saber Lock Anim: %s!!!\n", animTable[anim].name ); + Com_Printf(S_COLOR_RED "ERROR: unknown Saber Lock Anim: %s!!!\n", animTable[anim].name); #endif break; } return increment; } -qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ) -{ +qboolean WP_SabersCheckLock2(gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode) { animation_t *anim; - int attAnim, defAnim, advance = 0; - float attStart = 0.5f, defStart = 0.5f; - float idealDist = 48.0f; - //FIXME: this distances need to be modified by the lengths of the sabers involved... - //MATCH ANIMS - if ( lockMode == LOCK_KYLE_GRAB1 - || lockMode == LOCK_KYLE_GRAB2 - || lockMode == LOCK_KYLE_GRAB3 ) - { - float numSpins = 1.0f; - idealDist = 46.0f;//42.0f; + int attAnim, defAnim, advance = 0; + float attStart = 0.5f, defStart = 0.5f; + float idealDist = 48.0f; + // FIXME: this distances need to be modified by the lengths of the sabers involved... + // MATCH ANIMS + if (lockMode == LOCK_KYLE_GRAB1 || lockMode == LOCK_KYLE_GRAB2 || lockMode == LOCK_KYLE_GRAB3) { + float numSpins = 1.0f; + idealDist = 46.0f; // 42.0f; attStart = defStart = 0.0f; - switch ( lockMode ) - { + switch (lockMode) { default: case LOCK_KYLE_GRAB1: attAnim = BOTH_KYLE_PA_1; @@ -3161,202 +2463,172 @@ qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLo case LOCK_KYLE_GRAB3: attAnim = BOTH_KYLE_PA_2; defAnim = BOTH_PLAYER_PA_2; - defender->forcePushTime = level.time + PM_AnimLength( defender->client->clientInfo.animFileIndex, BOTH_PLAYER_PA_2 ); + defender->forcePushTime = level.time + PM_AnimLength(defender->client->clientInfo.animFileIndex, BOTH_PLAYER_PA_2); numSpins = 3.0f; break; } attacker->client->ps.SaberDeactivate(); defender->client->ps.SaberDeactivate(); - if ( d_slowmodeath->integer > 3 - && ( defender->s.number < MAX_CLIENTS - || attacker->s.number < MAX_CLIENTS ) ) - { - if( ValidAnimFileIndex( attacker->client->clientInfo.animFileIndex ) ) - { - int effectTime = PM_AnimLength( attacker->client->clientInfo.animFileIndex, (animNumber_t)attAnim ); - int spinTime = floor((float)effectTime/numSpins); - int meFlags = (MEF_MULTI_SPIN);//MEF_NO_TIMESCALE|MEF_NO_VERTBOB| - if ( Q_irand( 0, 1 ) ) - { + if (d_slowmodeath->integer > 3 && (defender->s.number < MAX_CLIENTS || attacker->s.number < MAX_CLIENTS)) { + if (ValidAnimFileIndex(attacker->client->clientInfo.animFileIndex)) { + int effectTime = PM_AnimLength(attacker->client->clientInfo.animFileIndex, (animNumber_t)attAnim); + int spinTime = floor((float)effectTime / numSpins); + int meFlags = (MEF_MULTI_SPIN); // MEF_NO_TIMESCALE|MEF_NO_VERTBOB| + if (Q_irand(0, 1)) { meFlags |= MEF_REVERSE_SPIN; } - G_StartMatrixEffect( attacker, meFlags, effectTime, 0.75f, spinTime ); + G_StartMatrixEffect(attacker, meFlags, effectTime, 0.75f, spinTime); } } - } - else if ( lockMode == LOCK_FORCE_DRAIN ) - { - idealDist = 46.0f;//42.0f; + } else if (lockMode == LOCK_FORCE_DRAIN) { + idealDist = 46.0f; // 42.0f; attStart = defStart = 0.0f; attAnim = BOTH_FORCE_DRAIN_GRAB_START; defAnim = BOTH_FORCE_DRAIN_GRABBED; attacker->client->ps.SaberDeactivate(); defender->client->ps.SaberDeactivate(); - } - else - { - if ( lockMode == LOCK_RANDOM ) - { - lockMode = (sabersLockMode_t)Q_irand( (int)LOCK_FIRST, (int)(LOCK_RANDOM)-1 ); - } - //FIXME: attStart% and idealDist will change per saber lock anim pairing... do we need a big table like in bg_panimate.cpp? - if ( attacker->client->ps.saberAnimLevel >= SS_FAST - && attacker->client->ps.saberAnimLevel <= SS_TAVION - && defender->client->ps.saberAnimLevel >= SS_FAST - && defender->client->ps.saberAnimLevel <= SS_TAVION ) - {//2 single sabers? Just do it the old way... - switch ( lockMode ) - { + } else { + if (lockMode == LOCK_RANDOM) { + lockMode = (sabersLockMode_t)Q_irand((int)LOCK_FIRST, (int)(LOCK_RANDOM)-1); + } + // FIXME: attStart% and idealDist will change per saber lock anim pairing... do we need a big table like in bg_panimate.cpp? + if (attacker->client->ps.saberAnimLevel >= SS_FAST && attacker->client->ps.saberAnimLevel <= SS_TAVION && + defender->client->ps.saberAnimLevel >= SS_FAST && defender->client->ps.saberAnimLevel <= SS_TAVION) { // 2 single sabers? Just do it the old way... + switch (lockMode) { case LOCK_TOP: - attAnim = BOTH_BF2LOCK;// - starts in middle - defAnim = BOTH_BF1LOCK;// - starts in middle + attAnim = BOTH_BF2LOCK; // - starts in middle + defAnim = BOTH_BF1LOCK; // - starts in middle attStart = defStart = 0.5f; idealDist = LOCK_IDEAL_DIST_TOP; break; case LOCK_DIAG_TR: attAnim = BOTH_CCWCIRCLELOCK; //- starts in middle - defAnim = BOTH_CWCIRCLELOCK;// - starts in middle + defAnim = BOTH_CWCIRCLELOCK; // - starts in middle attStart = defStart = 0.5f; idealDist = LOCK_IDEAL_DIST_CIRCLE; break; case LOCK_DIAG_TL: - attAnim = BOTH_CWCIRCLELOCK;// - starts in middle - defAnim = BOTH_CCWCIRCLELOCK;// - starts in middle + attAnim = BOTH_CWCIRCLELOCK; // - starts in middle + defAnim = BOTH_CCWCIRCLELOCK; // - starts in middle attStart = defStart = 0.5f; idealDist = LOCK_IDEAL_DIST_CIRCLE; break; case LOCK_DIAG_BR: - attAnim = BOTH_CWCIRCLELOCK;// - starts on left, to right - defAnim = BOTH_CCWCIRCLELOCK;// - starts on right, to left - attStart = defStart = 0.85f;//move to end of anim + attAnim = BOTH_CWCIRCLELOCK; // - starts on left, to right + defAnim = BOTH_CCWCIRCLELOCK; // - starts on right, to left + attStart = defStart = 0.85f; // move to end of anim idealDist = LOCK_IDEAL_DIST_CIRCLE; break; case LOCK_DIAG_BL: - attAnim = BOTH_CCWCIRCLELOCK;// - starts on right, to left - defAnim = BOTH_CWCIRCLELOCK;// - starts on left, to right - attStart = defStart = 0.85f;//move to end of anim + attAnim = BOTH_CCWCIRCLELOCK; // - starts on right, to left + defAnim = BOTH_CWCIRCLELOCK; // - starts on left, to right + attStart = defStart = 0.85f; // move to end of anim idealDist = LOCK_IDEAL_DIST_CIRCLE; break; case LOCK_R: - attAnim = BOTH_CWCIRCLELOCK;// - starts on left, to right - defAnim = BOTH_CCWCIRCLELOCK;// - starts on right, to left - attStart = defStart = 0.75f;//move to end of anim + attAnim = BOTH_CWCIRCLELOCK; // - starts on left, to right + defAnim = BOTH_CCWCIRCLELOCK; // - starts on right, to left + attStart = defStart = 0.75f; // move to end of anim idealDist = LOCK_IDEAL_DIST_CIRCLE; break; case LOCK_L: - attAnim = BOTH_CCWCIRCLELOCK;// - starts on right, to left - defAnim = BOTH_CWCIRCLELOCK;// - starts on left, to right - attStart = defStart = 0.75f;//move to end of anim + attAnim = BOTH_CCWCIRCLELOCK; // - starts on right, to left + defAnim = BOTH_CWCIRCLELOCK; // - starts on left, to right + attStart = defStart = 0.75f; // move to end of anim idealDist = LOCK_IDEAL_DIST_CIRCLE; break; default: return qfalse; break; } - } - else - {//use the new system - idealDist = LOCK_IDEAL_DIST_JKA;//all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN - if ( lockMode == LOCK_TOP ) - {//top lock - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_LOSE ); + } else { // use the new system + idealDist = LOCK_IDEAL_DIST_JKA; // all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN + if (lockMode == LOCK_TOP) { // top lock + attAnim = + G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_WIN); + defAnim = + G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_LOSE); attStart = defStart = 0.5f; - } - else - {//side lock - switch ( lockMode ) - { + } else { // side lock + switch (lockMode) { case LOCK_DIAG_TR: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); attStart = defStart = 0.5f; break; case LOCK_DIAG_TL: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); attStart = defStart = 0.5f; break; case LOCK_DIAG_BR: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - if ( G_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.85f;//move to end of anim - } - else - { - attStart = 0.15f;//start at beginning of anim - } - if ( G_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.85f;//start at end of anim - } - else - { - defStart = 0.15f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + if (G_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.85f; // move to end of anim + } else { + attStart = 0.15f; // start at beginning of anim + } + if (G_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.85f; // start at end of anim + } else { + defStart = 0.15f; // start at beginning of anim } break; case LOCK_DIAG_BL: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - if ( G_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.85f;//move to end of anim - } - else - { - attStart = 0.15f;//start at beginning of anim - } - if ( G_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.85f;//start at end of anim - } - else - { - defStart = 0.15f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + if (G_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.85f; // move to end of anim + } else { + attStart = 0.15f; // start at beginning of anim + } + if (G_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.85f; // start at end of anim + } else { + defStart = 0.15f; // start at beginning of anim } break; case LOCK_R: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - if ( G_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.75f;//move to end of anim - } - else - { - attStart = 0.25f;//start at beginning of anim - } - if ( G_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.75f;//start at end of anim - } - else - { - defStart = 0.25f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + if (G_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.75f; // move to end of anim + } else { + attStart = 0.25f; // start at beginning of anim + } + if (G_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.75f; // start at end of anim + } else { + defStart = 0.25f; // start at beginning of anim } break; case LOCK_L: - attAnim = G_SaberLockAnim( attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - //attacker starts with advantage - if ( G_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.75f;//move to end of anim - } - else - { - attStart = 0.25f;//start at beginning of anim - } - if ( G_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.75f;//start at end of anim - } - else - { - defStart = 0.25f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.saberAnimLevel, defender->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.saberAnimLevel, attacker->client->ps.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + // attacker starts with advantage + if (G_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.75f; // move to end of anim + } else { + attStart = 0.25f; // start at beginning of anim + } + if (G_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.75f; // start at end of anim + } else { + defStart = 0.25f; // start at beginning of anim } break; default: @@ -3366,330 +2638,243 @@ qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLo } } } - //set the proper anims - NPC_SetAnim( attacker, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC_SetAnim( defender, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't let them store a kick for the whole saberlock.... + // set the proper anims + NPC_SetAnim(attacker, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC_SetAnim(defender, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't let them store a kick for the whole saberlock.... attacker->client->ps.saberMoveNext = defender->client->ps.saberMoveNext = LS_NONE; // - if ( attStart > 0.0f ) - { - if( ValidAnimFileIndex( attacker->client->clientInfo.animFileIndex ) ) - { + if (attStart > 0.0f) { + if (ValidAnimFileIndex(attacker->client->clientInfo.animFileIndex)) { anim = &level.knownAnimFileSets[attacker->client->clientInfo.animFileIndex].animations[attAnim]; - advance = floor( anim->numFrames*attStart ); - PM_SetAnimFrame( attacker, anim->firstFrame + advance, qtrue, qtrue ); + advance = floor(anim->numFrames * attStart); + PM_SetAnimFrame(attacker, anim->firstFrame + advance, qtrue, qtrue); #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - Com_Printf( "%s starting saber lock, anim = %s, %d frames to go!\n", attacker->NPC_type, animTable[attAnim].name, anim->numFrames-advance ); + if (d_saberCombat->integer) { + Com_Printf("%s starting saber lock, anim = %s, %d frames to go!\n", attacker->NPC_type, animTable[attAnim].name, anim->numFrames - advance); } #endif } } - if ( defStart > 0.0f ) - { - if( ValidAnimFileIndex( defender->client->clientInfo.animFileIndex ) ) - { + if (defStart > 0.0f) { + if (ValidAnimFileIndex(defender->client->clientInfo.animFileIndex)) { anim = &level.knownAnimFileSets[defender->client->clientInfo.animFileIndex].animations[defAnim]; - advance = ceil( anim->numFrames*defStart ); - PM_SetAnimFrame( defender, anim->firstFrame + advance, qtrue, qtrue );//was anim->firstFrame + anim->numFrames - advance, but that's wrong since they are matched anims + advance = ceil(anim->numFrames * defStart); + PM_SetAnimFrame(defender, anim->firstFrame + advance, qtrue, + qtrue); // was anim->firstFrame + anim->numFrames - advance, but that's wrong since they are matched anims #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - Com_Printf( "%s starting saber lock, anim = %s, %d frames to go!\n", defender->NPC_type, animTable[defAnim].name, advance ); + if (d_saberCombat->integer) { + Com_Printf("%s starting saber lock, anim = %s, %d frames to go!\n", defender->NPC_type, animTable[defAnim].name, advance); } #endif } } - VectorClear( attacker->client->ps.velocity ); - VectorClear( attacker->client->ps.moveDir ); - VectorClear( defender->client->ps.velocity ); - VectorClear( defender->client->ps.moveDir ); - if ( lockMode == LOCK_KYLE_GRAB1 - || lockMode == LOCK_KYLE_GRAB2 - || lockMode == LOCK_KYLE_GRAB3 - || lockMode == LOCK_FORCE_DRAIN ) - {//not a real lock, just freeze them both in place - //can't move or attack + VectorClear(attacker->client->ps.velocity); + VectorClear(attacker->client->ps.moveDir); + VectorClear(defender->client->ps.velocity); + VectorClear(defender->client->ps.moveDir); + if (lockMode == LOCK_KYLE_GRAB1 || lockMode == LOCK_KYLE_GRAB2 || lockMode == LOCK_KYLE_GRAB3 || + lockMode == LOCK_FORCE_DRAIN) { // not a real lock, just freeze them both in place + // can't move or attack attacker->client->ps.pm_time = attacker->client->ps.weaponTime = attacker->client->ps.legsAnimTimer; attacker->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; attacker->painDebounceTime = level.time + attacker->client->ps.pm_time; - if ( lockMode != LOCK_FORCE_DRAIN ) - { + if (lockMode != LOCK_FORCE_DRAIN) { defender->client->ps.torsoAnimTimer += 200; defender->client->ps.legsAnimTimer += 200; } defender->client->ps.pm_time = defender->client->ps.weaponTime = defender->client->ps.legsAnimTimer; defender->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( lockMode != LOCK_FORCE_DRAIN ) - { + if (lockMode != LOCK_FORCE_DRAIN) { attacker->aimDebounceTime = level.time + attacker->client->ps.pm_time; } - } - else - { + } else { attacker->client->ps.saberLockTime = defender->client->ps.saberLockTime = level.time + SABER_LOCK_TIME; - attacker->client->ps.legsAnimTimer = attacker->client->ps.torsoAnimTimer = defender->client->ps.legsAnimTimer = defender->client->ps.torsoAnimTimer = SABER_LOCK_TIME; - //attacker->client->ps.weaponTime = defender->client->ps.weaponTime = SABER_LOCK_TIME; + attacker->client->ps.legsAnimTimer = attacker->client->ps.torsoAnimTimer = defender->client->ps.legsAnimTimer = defender->client->ps.torsoAnimTimer = + SABER_LOCK_TIME; + // attacker->client->ps.weaponTime = defender->client->ps.weaponTime = SABER_LOCK_TIME; attacker->client->ps.saberLockEnemy = defender->s.number; defender->client->ps.saberLockEnemy = attacker->s.number; } - //MATCH ANGLES - if ( lockMode == LOCK_KYLE_GRAB1 - || lockMode == LOCK_KYLE_GRAB2 - || lockMode == LOCK_KYLE_GRAB3 ) - {//not a real lock, just set pitch to 0 + // MATCH ANGLES + if (lockMode == LOCK_KYLE_GRAB1 || lockMode == LOCK_KYLE_GRAB2 || lockMode == LOCK_KYLE_GRAB3) { // not a real lock, just set pitch to 0 attacker->client->ps.viewangles[PITCH] = defender->client->ps.viewangles[PITCH] = 0; - } - else - { - //FIXME: if zDiff in elevation, make lower look up and upper look down and move them closer? - float defPitchAdd = 0, zDiff = ((attacker->currentOrigin[2]+attacker->client->standheight)-(defender->currentOrigin[2]+defender->client->standheight)); - if ( zDiff > 24 ) - { + } else { + // FIXME: if zDiff in elevation, make lower look up and upper look down and move them closer? + float defPitchAdd = 0, + zDiff = ((attacker->currentOrigin[2] + attacker->client->standheight) - (defender->currentOrigin[2] + defender->client->standheight)); + if (zDiff > 24) { defPitchAdd = -30; - } - else if ( zDiff < -24 ) - { + } else if (zDiff < -24) { defPitchAdd = 30; + } else { + defPitchAdd = zDiff / 24.0f * -30.0f; } - else - { - defPitchAdd = zDiff/24.0f*-30.0f; - } - if ( attacker->NPC && defender->NPC ) - {//if 2 NPCs, just set pitch to 0 + if (attacker->NPC && defender->NPC) { // if 2 NPCs, just set pitch to 0 attacker->client->ps.viewangles[PITCH] = -defPitchAdd; defender->client->ps.viewangles[PITCH] = defPitchAdd; - } - else - {//if a player is involved, clamp player's pitch and match NPC's to player - if ( !attacker->s.number ) - { - //clamp to defPitch - if ( attacker->client->ps.viewangles[PITCH] > -defPitchAdd + 10 ) - { + } else { // if a player is involved, clamp player's pitch and match NPC's to player + if (!attacker->s.number) { + // clamp to defPitch + if (attacker->client->ps.viewangles[PITCH] > -defPitchAdd + 10) { attacker->client->ps.viewangles[PITCH] = -defPitchAdd + 10; + } else if (attacker->client->ps.viewangles[PITCH] < -defPitchAdd - 10) { + attacker->client->ps.viewangles[PITCH] = -defPitchAdd - 10; } - else if ( attacker->client->ps.viewangles[PITCH] < -defPitchAdd-10 ) - { - attacker->client->ps.viewangles[PITCH] = -defPitchAdd-10; - } - //clamp to sane numbers - if ( attacker->client->ps.viewangles[PITCH] > 50 ) - { + // clamp to sane numbers + if (attacker->client->ps.viewangles[PITCH] > 50) { attacker->client->ps.viewangles[PITCH] = 50; - } - else if ( attacker->client->ps.viewangles[PITCH] < -50 ) - { + } else if (attacker->client->ps.viewangles[PITCH] < -50) { attacker->client->ps.viewangles[PITCH] = -50; } - defender->client->ps.viewangles[PITCH] = attacker->client->ps.viewangles[PITCH]*-1; + defender->client->ps.viewangles[PITCH] = attacker->client->ps.viewangles[PITCH] * -1; defPitchAdd = defender->client->ps.viewangles[PITCH]; - } - else if ( !defender->s.number ) - { - //clamp to defPitch - if ( defender->client->ps.viewangles[PITCH] > defPitchAdd + 10 ) - { + } else if (!defender->s.number) { + // clamp to defPitch + if (defender->client->ps.viewangles[PITCH] > defPitchAdd + 10) { defender->client->ps.viewangles[PITCH] = defPitchAdd + 10; + } else if (defender->client->ps.viewangles[PITCH] < defPitchAdd - 10) { + defender->client->ps.viewangles[PITCH] = defPitchAdd - 10; } - else if ( defender->client->ps.viewangles[PITCH] < defPitchAdd-10 ) - { - defender->client->ps.viewangles[PITCH] = defPitchAdd-10; - } - //clamp to sane numbers - if ( defender->client->ps.viewangles[PITCH] > 50 ) - { + // clamp to sane numbers + if (defender->client->ps.viewangles[PITCH] > 50) { defender->client->ps.viewangles[PITCH] = 50; - } - else if ( defender->client->ps.viewangles[PITCH] < -50 ) - { + } else if (defender->client->ps.viewangles[PITCH] < -50) { defender->client->ps.viewangles[PITCH] = -50; } defPitchAdd = defender->client->ps.viewangles[PITCH]; - attacker->client->ps.viewangles[PITCH] = defender->client->ps.viewangles[PITCH]*-1; + attacker->client->ps.viewangles[PITCH] = defender->client->ps.viewangles[PITCH] * -1; } } } - vec3_t attAngles, defAngles, defDir; - VectorSubtract( defender->currentOrigin, attacker->currentOrigin, defDir ); - VectorCopy( attacker->client->ps.viewangles, attAngles ); - attAngles[YAW] = vectoyaw( defDir ); - SetClientViewAngle( attacker, attAngles ); - defAngles[PITCH] = attAngles[PITCH]*-1; - defAngles[YAW] = AngleNormalize180( attAngles[YAW] + 180); + vec3_t attAngles, defAngles, defDir; + VectorSubtract(defender->currentOrigin, attacker->currentOrigin, defDir); + VectorCopy(attacker->client->ps.viewangles, attAngles); + attAngles[YAW] = vectoyaw(defDir); + SetClientViewAngle(attacker, attAngles); + defAngles[PITCH] = attAngles[PITCH] * -1; + defAngles[YAW] = AngleNormalize180(attAngles[YAW] + 180); defAngles[ROLL] = 0; - SetClientViewAngle( defender, defAngles ); + SetClientViewAngle(defender, defAngles); - //MATCH POSITIONS - vec3_t newOrg; + // MATCH POSITIONS + vec3_t newOrg; /* idealDist -= fabs(defPitchAdd)/8.0f; */ - float scale = (attacker->s.modelScale[0]+attacker->s.modelScale[1])*0.5f; - if ( scale && scale != 1.0f ) - { - idealDist += 8*(scale-1.0f); - } - scale = (defender->s.modelScale[0]+defender->s.modelScale[1])*0.5f; - if ( scale && scale != 1.0f ) - { - idealDist += 8*(scale-1.0f); - } - - float diff = VectorNormalize( defDir ) - idealDist;//diff will be the total error in dist - //try to move attacker half the diff towards the defender - VectorMA( attacker->currentOrigin, diff*0.5f, defDir, newOrg ); - trace_t trace; - gi.trace( &trace, attacker->currentOrigin, attacker->mins, attacker->maxs, newOrg, attacker->s.number, attacker->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - G_SetOrigin( attacker, trace.endpos ); - gi.linkentity( attacker ); - } - //now get the defender's dist and do it for him too - vec3_t attDir; - VectorSubtract( attacker->currentOrigin, defender->currentOrigin, attDir ); - diff = VectorNormalize( attDir ) - idealDist;//diff will be the total error in dist - //try to move defender all of the remaining diff towards the attacker - VectorMA( defender->currentOrigin, diff, attDir, newOrg ); - gi.trace( &trace, defender->currentOrigin, defender->mins, defender->maxs, newOrg, defender->s.number, defender->clipmask, (EG2_Collision)0, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - G_SetOrigin( defender, trace.endpos ); - gi.linkentity( defender ); - } - - //DONE! + float scale = (attacker->s.modelScale[0] + attacker->s.modelScale[1]) * 0.5f; + if (scale && scale != 1.0f) { + idealDist += 8 * (scale - 1.0f); + } + scale = (defender->s.modelScale[0] + defender->s.modelScale[1]) * 0.5f; + if (scale && scale != 1.0f) { + idealDist += 8 * (scale - 1.0f); + } + + float diff = VectorNormalize(defDir) - idealDist; // diff will be the total error in dist + // try to move attacker half the diff towards the defender + VectorMA(attacker->currentOrigin, diff * 0.5f, defDir, newOrg); + trace_t trace; + gi.trace(&trace, attacker->currentOrigin, attacker->mins, attacker->maxs, newOrg, attacker->s.number, attacker->clipmask, (EG2_Collision)0, 0); + if (!trace.startsolid && !trace.allsolid) { + G_SetOrigin(attacker, trace.endpos); + gi.linkentity(attacker); + } + // now get the defender's dist and do it for him too + vec3_t attDir; + VectorSubtract(attacker->currentOrigin, defender->currentOrigin, attDir); + diff = VectorNormalize(attDir) - idealDist; // diff will be the total error in dist + // try to move defender all of the remaining diff towards the attacker + VectorMA(defender->currentOrigin, diff, attDir, newOrg); + gi.trace(&trace, defender->currentOrigin, defender->mins, defender->maxs, newOrg, defender->s.number, defender->clipmask, (EG2_Collision)0, 0); + if (!trace.startsolid && !trace.allsolid) { + G_SetOrigin(defender, trace.endpos); + gi.linkentity(defender); + } + + // DONE! return qtrue; } -qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) -{ - if ( ent1->client->playerTeam == ent2->client->playerTeam ) - { +qboolean WP_SabersCheckLock(gentity_t *ent1, gentity_t *ent2) { + if (ent1->client->playerTeam == ent2->client->playerTeam) { return qfalse; } - if ( ent1->client->NPC_class == CLASS_SABER_DROID - || ent2->client->NPC_class == CLASS_SABER_DROID ) - {//they don't have saberlock anims + if (ent1->client->NPC_class == CLASS_SABER_DROID || ent2->client->NPC_class == CLASS_SABER_DROID) { // they don't have saberlock anims return qfalse; } - if ( ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || - ent2->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + if (ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || ent2->client->ps.groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - if ( (ent1->client->ps.saber[0].saberFlags&SFL_NOT_LOCKABLE) - || (ent2->client->ps.saber[0].saberFlags&SFL_NOT_LOCKABLE) ) - {//one of these sabers cannot lock (like a lance) + if ((ent1->client->ps.saber[0].saberFlags & SFL_NOT_LOCKABLE) || + (ent2->client->ps.saber[0].saberFlags & SFL_NOT_LOCKABLE)) { // one of these sabers cannot lock (like a lance) return qfalse; } - if ( ent1->client->ps.dualSabers - && ent1->client->ps.saber[1].Active() - && (ent1->client->ps.saber[1].saberFlags&SFL_NOT_LOCKABLE) ) - {//one of these sabers cannot lock (like a lance) + if (ent1->client->ps.dualSabers && ent1->client->ps.saber[1].Active() && + (ent1->client->ps.saber[1].saberFlags & SFL_NOT_LOCKABLE)) { // one of these sabers cannot lock (like a lance) return qfalse; } - if ( ent2->client->ps.dualSabers - && ent2->client->ps.saber[1].Active() - && (ent2->client->ps.saber[1].saberFlags&SFL_NOT_LOCKABLE) ) - {//one of these sabers cannot lock (like a lance) + if (ent2->client->ps.dualSabers && ent2->client->ps.saber[1].Active() && + (ent2->client->ps.saber[1].saberFlags & SFL_NOT_LOCKABLE)) { // one of these sabers cannot lock (like a lance) return qfalse; } - if ( ent1->painDebounceTime > level.time-1000 || ent2->painDebounceTime > level.time-1000 ) - {//can't saberlock if you're not ready + if (ent1->painDebounceTime > level.time - 1000 || ent2->painDebounceTime > level.time - 1000) { // can't saberlock if you're not ready return qfalse; } - if ( fabs( ent1->currentOrigin[2]-ent2->currentOrigin[2]) > 18 ) - { + if (fabs(ent1->currentOrigin[2] - ent2->currentOrigin[2]) > 18) { return qfalse; } - float dist = DistanceSquared(ent1->currentOrigin,ent2->currentOrigin); - if ( dist < 64 || dist > 6400 )//( dist < 128 || dist > 2304 ) - {//between 8 and 80 from each other//was 16 and 48 + float dist = DistanceSquared(ent1->currentOrigin, ent2->currentOrigin); + if (dist < 64 || dist > 6400) //( dist < 128 || dist > 2304 ) + { // between 8 and 80 from each other//was 16 and 48 return qfalse; } - if ( !InFOV( ent1, ent2, 40, 180 ) || !InFOV( ent2, ent1, 40, 180 ) ) - { + if (!InFOV(ent1, ent2, 40, 180) || !InFOV(ent2, ent1, 40, 180)) { return qfalse; } - //Check for certain anims that *cannot* lock - //FIXME: there should probably be a whole *list* of these, but I'll put them in as they come up - if ( ent1->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent1->client->ps.torsoAnimTimer > 300 ) - {//can't lock when saber is behind you + // Check for certain anims that *cannot* lock + // FIXME: there should probably be a whole *list* of these, but I'll put them in as they come up + if (ent1->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent1->client->ps.torsoAnimTimer > 300) { // can't lock when saber is behind you return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent2->client->ps.torsoAnimTimer > 300 ) - {//can't lock when saber is behind you + if (ent2->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent2->client->ps.torsoAnimTimer > 300) { // can't lock when saber is behind you return qfalse; } - if ( PM_LockedAnim( ent1->client->ps.torsoAnim ) - || PM_LockedAnim( ent2->client->ps.torsoAnim ) ) - {//stuck doing something else + if (PM_LockedAnim(ent1->client->ps.torsoAnim) || PM_LockedAnim(ent2->client->ps.torsoAnim)) { // stuck doing something else return qfalse; } - if ( PM_SaberLockBreakAnim( ent1->client->ps.torsoAnim ) - || PM_SaberLockBreakAnim( ent2->client->ps.torsoAnim ) ) - {//still finishing the last lock break! + if (PM_SaberLockBreakAnim(ent1->client->ps.torsoAnim) || PM_SaberLockBreakAnim(ent2->client->ps.torsoAnim)) { // still finishing the last lock break! return qfalse; } - //BR to TL lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A5_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A6_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A7_BR_TL ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BR ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A5_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A6_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A7_BR_TL ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BR ); - } - //BL to TR lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A5_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A6_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A7_BL_TR ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BL ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A5_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A6_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A7_BL_TR ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BL ); - } - //L to R lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__L__R || - ent1->client->ps.torsoAnim == BOTH_A2__L__R || - ent1->client->ps.torsoAnim == BOTH_A3__L__R || - ent1->client->ps.torsoAnim == BOTH_A4__L__R || - ent1->client->ps.torsoAnim == BOTH_A5__L__R || - ent1->client->ps.torsoAnim == BOTH_A6__L__R || - ent1->client->ps.torsoAnim == BOTH_A7__L__R ) - {//ent1 is attacking l to r - return WP_SabersCheckLock2( ent1, ent2, LOCK_L ); + // BR to TL lock + if (ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || ent1->client->ps.torsoAnim == BOTH_A5_BR_TL || ent1->client->ps.torsoAnim == BOTH_A6_BR_TL || + ent1->client->ps.torsoAnim == BOTH_A7_BR_TL) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BR); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || ent2->client->ps.torsoAnim == BOTH_A5_BR_TL || ent2->client->ps.torsoAnim == BOTH_A6_BR_TL || + ent2->client->ps.torsoAnim == BOTH_A7_BR_TL) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BR); + } + // BL to TR lock + if (ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || ent1->client->ps.torsoAnim == BOTH_A5_BL_TR || ent1->client->ps.torsoAnim == BOTH_A6_BL_TR || + ent1->client->ps.torsoAnim == BOTH_A7_BL_TR) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BL); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || ent2->client->ps.torsoAnim == BOTH_A5_BL_TR || ent2->client->ps.torsoAnim == BOTH_A6_BL_TR || + ent2->client->ps.torsoAnim == BOTH_A7_BL_TR) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BL); + } + // L to R lock + if (ent1->client->ps.torsoAnim == BOTH_A1__L__R || ent1->client->ps.torsoAnim == BOTH_A2__L__R || ent1->client->ps.torsoAnim == BOTH_A3__L__R || + ent1->client->ps.torsoAnim == BOTH_A4__L__R || ent1->client->ps.torsoAnim == BOTH_A5__L__R || ent1->client->ps.torsoAnim == BOTH_A6__L__R || + ent1->client->ps.torsoAnim == BOTH_A7__L__R) { // ent1 is attacking l to r + return WP_SabersCheckLock2(ent1, ent2, LOCK_L); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -3713,15 +2898,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1__L__R || - ent2->client->ps.torsoAnim == BOTH_A2__L__R || - ent2->client->ps.torsoAnim == BOTH_A3__L__R || - ent2->client->ps.torsoAnim == BOTH_A4__L__R || - ent2->client->ps.torsoAnim == BOTH_A5__L__R || - ent2->client->ps.torsoAnim == BOTH_A6__L__R || - ent2->client->ps.torsoAnim == BOTH_A7__L__R ) - {//ent2 is attacking l to r - return WP_SabersCheckLock2( ent2, ent1, LOCK_L ); + if (ent2->client->ps.torsoAnim == BOTH_A1__L__R || ent2->client->ps.torsoAnim == BOTH_A2__L__R || ent2->client->ps.torsoAnim == BOTH_A3__L__R || + ent2->client->ps.torsoAnim == BOTH_A4__L__R || ent2->client->ps.torsoAnim == BOTH_A5__L__R || ent2->client->ps.torsoAnim == BOTH_A6__L__R || + ent2->client->ps.torsoAnim == BOTH_A7__L__R) { // ent2 is attacking l to r + return WP_SabersCheckLock2(ent2, ent1, LOCK_L); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -3745,16 +2925,11 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //R to L lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__R__L || - ent1->client->ps.torsoAnim == BOTH_A2__R__L || - ent1->client->ps.torsoAnim == BOTH_A3__R__L || - ent1->client->ps.torsoAnim == BOTH_A4__R__L || - ent1->client->ps.torsoAnim == BOTH_A5__R__L || - ent1->client->ps.torsoAnim == BOTH_A6__R__L || - ent1->client->ps.torsoAnim == BOTH_A7__R__L ) - {//ent1 is attacking r to l - return WP_SabersCheckLock2( ent1, ent2, LOCK_R ); + // R to L lock + if (ent1->client->ps.torsoAnim == BOTH_A1__R__L || ent1->client->ps.torsoAnim == BOTH_A2__R__L || ent1->client->ps.torsoAnim == BOTH_A3__R__L || + ent1->client->ps.torsoAnim == BOTH_A4__R__L || ent1->client->ps.torsoAnim == BOTH_A5__R__L || ent1->client->ps.torsoAnim == BOTH_A6__R__L || + ent1->client->ps.torsoAnim == BOTH_A7__R__L) { // ent1 is attacking r to l + return WP_SabersCheckLock2(ent1, ent2, LOCK_R); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -3778,15 +2953,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1__R__L || - ent2->client->ps.torsoAnim == BOTH_A2__R__L || - ent2->client->ps.torsoAnim == BOTH_A3__R__L || - ent2->client->ps.torsoAnim == BOTH_A4__R__L || - ent2->client->ps.torsoAnim == BOTH_A5__R__L || - ent2->client->ps.torsoAnim == BOTH_A6__R__L || - ent2->client->ps.torsoAnim == BOTH_A7__R__L ) - {//ent2 is attacking r to l - return WP_SabersCheckLock2( ent2, ent1, LOCK_R ); + if (ent2->client->ps.torsoAnim == BOTH_A1__R__L || ent2->client->ps.torsoAnim == BOTH_A2__R__L || ent2->client->ps.torsoAnim == BOTH_A3__R__L || + ent2->client->ps.torsoAnim == BOTH_A4__R__L || ent2->client->ps.torsoAnim == BOTH_A5__R__L || ent2->client->ps.torsoAnim == BOTH_A6__R__L || + ent2->client->ps.torsoAnim == BOTH_A7__R__L) { // ent2 is attacking r to l + return WP_SabersCheckLock2(ent2, ent1, LOCK_R); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -3810,16 +2980,11 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //TR to BL lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A7_TR_BL ) - {//ent1 is attacking diagonally - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TR ); + // TR to BL lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A7_TR_BL) { // ent1 is attacking diagonally + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TR); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -3854,15 +3019,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A7_TR_BL ) - {//ent2 is attacking diagonally - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TR ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A7_TR_BL) { // ent2 is attacking diagonally + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TR); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -3897,16 +3057,11 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - //TL to BR lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A7_TL_BR ) - {//ent1 is attacking diagonally - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TL ); + // TL to BR lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A7_TL_BR) { // ent1 is attacking diagonally + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TL); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -3941,15 +3096,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A7_TL_BR ) - {//ent2 is attacking diagonally - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TL ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A7_TL_BR) { // ent2 is attacking diagonally + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TL); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -3983,38 +3133,28 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //T to B lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A5_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A6_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A7_T__B_ ) - {//ent1 is attacking top-down + // T to B lock + if (ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || ent1->client->ps.torsoAnim == BOTH_A5_T__B_ || ent1->client->ps.torsoAnim == BOTH_A6_T__B_ || + ent1->client->ps.torsoAnim == BOTH_A7_T__B_) { // ent1 is attacking top-down /* if ( ent2->client->ps.torsoAnim == BOTH_P1_S1_T_ || ent2->client->ps.torsoAnim == BOTH_K1_S1_T_ ) */ - {//ent2 is blocking at top - return WP_SabersCheckLock2( ent1, ent2, LOCK_TOP ); + { // ent2 is blocking at top + return WP_SabersCheckLock2(ent1, ent2, LOCK_TOP); } } - if ( ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A5_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A6_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A7_T__B_ ) - {//ent2 is attacking top-down + if (ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || ent2->client->ps.torsoAnim == BOTH_A5_T__B_ || ent2->client->ps.torsoAnim == BOTH_A6_T__B_ || + ent2->client->ps.torsoAnim == BOTH_A7_T__B_) { // ent2 is attacking top-down /* if ( ent1->client->ps.torsoAnim == BOTH_P1_S1_T_ || ent1->client->ps.torsoAnim == BOTH_K1_S1_T_ ) */ - {//ent1 is blocking at top - return WP_SabersCheckLock2( ent2, ent1, LOCK_TOP ); + { // ent1 is blocking at top + return WP_SabersCheckLock2(ent2, ent1, LOCK_TOP); } } /* @@ -4026,101 +3166,74 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) return qfalse; } -qboolean WP_SaberParry( gentity_t *victim, gentity_t *attacker, int saberNum, int bladeNum ) -{ - if ( !victim || !victim->client || !attacker ) - { +qboolean WP_SaberParry(gentity_t *victim, gentity_t *attacker, int saberNum, int bladeNum) { + if (!victim || !victim->client || !attacker) { return qfalse; } - if ( Rosh_BeingHealed( victim ) ) - { + if (Rosh_BeingHealed(victim)) { return qfalse; } - if ( G_InCinematicSaberAnim( victim ) ) - { + if (G_InCinematicSaberAnim(victim)) { return qfalse; } - if ( PM_SuperBreakLoseAnim( victim->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( victim->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(victim->client->ps.torsoAnim) || PM_SuperBreakWinAnim(victim->client->ps.torsoAnim)) { return qfalse; } - if ( victim->s.number || g_saberAutoBlocking->integer || victim->client->ps.saberBlockingTime > level.time ) - {//either an NPC or a player who is blocking - if ( !PM_SaberInTransitionAny( victim->client->ps.saberMove ) - && !PM_SaberInBounce( victim->client->ps.saberMove ) - && !PM_SaberInKnockaway( victim->client->ps.saberMove ) ) - {//I'm not attacking, in transition or in a bounce or knockaway, so play a parry - WP_SaberBlockNonRandom( victim, saberHitLocation, qfalse ); + if (victim->s.number || g_saberAutoBlocking->integer || victim->client->ps.saberBlockingTime > level.time) { // either an NPC or a player who is blocking + if (!PM_SaberInTransitionAny(victim->client->ps.saberMove) && !PM_SaberInBounce(victim->client->ps.saberMove) && + !PM_SaberInKnockaway(victim->client->ps.saberMove)) { // I'm not attacking, in transition or in a bounce or knockaway, so play a parry + WP_SaberBlockNonRandom(victim, saberHitLocation, qfalse); } victim->client->ps.saberEventFlags |= SEF_PARRIED; - //since it was parried, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( attacker, victim->s.number, saberNum, bladeNum ); + // since it was parried, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(attacker, victim->s.number, saberNum, bladeNum); - //tell the victim to get mad at me - if ( victim->enemy != attacker && victim->client->playerTeam != attacker->client->playerTeam ) - {//they're not mad at me and they're not on my team - G_ClearEnemy( victim ); - G_SetEnemy( victim, attacker ); + // tell the victim to get mad at me + if (victim->enemy != attacker && victim->client->playerTeam != attacker->client->playerTeam) { // they're not mad at me and they're not on my team + G_ClearEnemy(victim); + G_SetEnemy(victim, attacker); } return qtrue; } return qfalse; } -qboolean WP_BrokenParryKnockDown( gentity_t *victim ) -{ - if ( !victim || !victim->client ) - { +qboolean WP_BrokenParryKnockDown(gentity_t *victim) { + if (!victim || !victim->client) { return qfalse; } - if ( PM_SuperBreakLoseAnim( victim->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( victim->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(victim->client->ps.torsoAnim) || PM_SuperBreakWinAnim(victim->client->ps.torsoAnim)) { return qfalse; } - if ( victim->client->ps.saberMove == LS_PARRY_UP - || victim->client->ps.saberMove == LS_PARRY_UR - || victim->client->ps.saberMove == LS_PARRY_UL - || victim->client->ps.saberMove == LS_H1_BR - || victim->client->ps.saberMove == LS_H1_B_ - || victim->client->ps.saberMove == LS_H1_BL ) - {//knock their asses down! + if (victim->client->ps.saberMove == LS_PARRY_UP || victim->client->ps.saberMove == LS_PARRY_UR || victim->client->ps.saberMove == LS_PARRY_UL || + victim->client->ps.saberMove == LS_H1_BR || victim->client->ps.saberMove == LS_H1_B_ || + victim->client->ps.saberMove == LS_H1_BL) { // knock their asses down! int knockAnim = BOTH_KNOCKDOWN1; - if ( PM_CrouchAnim( victim->client->ps.legsAnim ) ) - { + if (PM_CrouchAnim(victim->client->ps.legsAnim)) { knockAnim = BOTH_KNOCKDOWN4; } - NPC_SetAnim( victim, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_AddEvent( victim, EV_PAIN, victim->health ); + NPC_SetAnim(victim, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(victim, EV_PAIN, victim->health); return qtrue; } return qfalse; } -qboolean G_TryingKataAttack( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingKataAttack(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else //if ( self && self->client ) - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ALT_ATTACK) ) - {//pressing alt-attack - //if ( !(self->client->ps.pm_flags&PMF_ALT_ATTACK_HELD) ) - {//haven't been holding alt-attack - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack + } else // if ( self && self->client ) + { // use the old control scheme + if ((cmd->buttons & BUTTON_ALT_ATTACK)) { // pressing alt-attack + // if ( !(self->client->ps.pm_flags&PMF_ALT_ATTACK_HELD) ) + { // haven't been holding alt-attack + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack return qtrue; } } @@ -4129,42 +3242,28 @@ qboolean G_TryingKataAttack( gentity_t *self, usercmd_t *cmd ) return qfalse; } -qboolean G_TryingPullAttack( gentity_t *self, usercmd_t *cmd, qboolean amPulling ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { - if ( self && self->client ) - { - if ( self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 ) - {//force pull 3 - if ( amPulling - || (self->client->ps.forcePowersActive&(1<client->ps.forcePowerDebounce[FP_PULL] > level.time ) //force-pulling - {//pulling +qboolean G_TryingPullAttack(gentity_t *self, usercmd_t *cmd, qboolean amPulling) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { + if (self && self->client) { + if (self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3) { // force pull 3 + if (amPulling || (self->client->ps.forcePowersActive & (1 << FP_PULL)) || + self->client->ps.forcePowerDebounce[FP_PULL] > level.time) // force-pulling + { // pulling return qtrue; } } } - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack - if ( self && self->client ) - { - if ( self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 ) - {//force pull 3 - if ( amPulling - || (self->client->ps.forcePowersActive&(1<client->ps.forcePowerDebounce[FP_PULL] > level.time ) //force-pulling - {//pulling + } else { // use the old control scheme + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack + if (self && self->client) { + if (self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3) { // force pull 3 + if (amPulling || (self->client->ps.forcePowersActive & (1 << FP_PULL)) || + self->client->ps.forcePowerDebounce[FP_PULL] > level.time) // force-pulling + { // pulling return qtrue; } } @@ -4174,38 +3273,24 @@ qboolean G_TryingPullAttack( gentity_t *self, usercmd_t *cmd, qboolean amPulling return qfalse; } -qboolean G_TryingCartwheel( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingCartwheel(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack - if ( cmd->rightmove ) - { - if ( self && self->client ) - { - if ( cmd->upmove>0 //) - && self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on ground, pressing jump + } else { // use the old control scheme + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack + if (cmd->rightmove) { + if (self && self->client) { + if (cmd->upmove > 0 //) + && self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on ground, pressing jump return qtrue; - } - else - {//just jumped? - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE - && level.time - self->client->ps.lastOnGround <= 50//250 - && (self->client->ps.pm_flags&PMF_JUMPING) )//jumping - {//just jumped this or last frame + } else { // just jumped? + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE && level.time - self->client->ps.lastOnGround <= 50 // 250 + && (self->client->ps.pm_flags & PMF_JUMPING)) // jumping + { // just jumped this or last frame return qtrue; } } @@ -4216,52 +3301,33 @@ qboolean G_TryingCartwheel( gentity_t *self, usercmd_t *cmd ) return qfalse; } -qboolean G_TryingSpecial( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingSpecial(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme + } else { // use the old control scheme return qfalse; } } -qboolean G_TryingJumpAttack( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingJumpAttack(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack - if ( cmd->upmove>0 ) - {//pressing jump + } else { // use the old control scheme + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack + if (cmd->upmove > 0) { // pressing jump return qtrue; - } - else if ( self && self->client ) - {//just jumped? - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE - && level.time - self->client->ps.lastOnGround <= 250 - && (self->client->ps.pm_flags&PMF_JUMPING) )//jumping - {//jumped within the last quarter second + } else if (self && self->client) { // just jumped? + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE && level.time - self->client->ps.lastOnGround <= 250 && + (self->client->ps.pm_flags & PMF_JUMPING)) // jumping + { // jumped within the last quarter second return qtrue; } } @@ -4270,38 +3336,23 @@ qboolean G_TryingJumpAttack( gentity_t *self, usercmd_t *cmd ) return qfalse; } -qboolean G_TryingJumpForwardAttack( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingJumpForwardAttack(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack - if ( cmd->forwardmove > 0 ) - {//moving forward - if ( self && self->client ) - { - if ( cmd->upmove>0 - && self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//pressing jump + } else { // use the old control scheme + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack + if (cmd->forwardmove > 0) { // moving forward + if (self && self->client) { + if (cmd->upmove > 0 && self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // pressing jump return qtrue; - } - else - {//no slop on forward jumps - must be precise! - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE - && level.time - self->client->ps.lastOnGround <= 50 - && (self->client->ps.pm_flags&PMF_JUMPING) )//jumping - {//just jumped this or last frame + } else { // no slop on forward jumps - must be precise! + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE && level.time - self->client->ps.lastOnGround <= 50 && + (self->client->ps.pm_flags & PMF_JUMPING)) // jumping + { // just jumped this or last frame return qtrue; } } @@ -4312,31 +3363,19 @@ qboolean G_TryingJumpForwardAttack( gentity_t *self, usercmd_t *cmd ) return qfalse; } -qboolean G_TryingLungeAttack( gentity_t *self, usercmd_t *cmd ) -{ - if ( g_saberNewControlScheme->integer ) - {//use the new control scheme: force focus button - if ( (cmd->buttons&BUTTON_FORCE_FOCUS) ) - { +qboolean G_TryingLungeAttack(gentity_t *self, usercmd_t *cmd) { + if (g_saberNewControlScheme->integer) { // use the new control scheme: force focus button + if ((cmd->buttons & BUTTON_FORCE_FOCUS)) { return qtrue; - } - else - { + } else { return qfalse; } - } - else - {//use the old control scheme - if ( (cmd->buttons&BUTTON_ATTACK) ) - {//pressing attack - if ( cmd->upmove<0 ) - {//pressing crouch + } else { // use the old control scheme + if ((cmd->buttons & BUTTON_ATTACK)) { // pressing attack + if (cmd->upmove < 0) { // pressing crouch return qtrue; - } - else if ( self && self->client ) - {//just unducked? - if ( (self->client->ps.pm_flags&PMF_DUCKED) ) - {//just unducking + } else if (self && self->client) { // just unducked? + if ((self->client->ps.pm_flags & PMF_DUCKED)) { // just unducking return qtrue; } } @@ -4345,138 +3384,99 @@ qboolean G_TryingLungeAttack( gentity_t *self, usercmd_t *cmd ) return qfalse; } - -//FIXME: for these below funcs, maybe in the old control scheme some moves should still cost power... if so, pass in the saberMove and use a switch statement -qboolean G_EnoughPowerForSpecialMove( int forcePower, int cost, qboolean kataMove ) -{ - if ( g_saberNewControlScheme->integer || kataMove ) - {//special moves cost power - if ( forcePower >= cost ) - { +// FIXME: for these below funcs, maybe in the old control scheme some moves should still cost power... if so, pass in the saberMove and use a switch statement +qboolean G_EnoughPowerForSpecialMove(int forcePower, int cost, qboolean kataMove) { + if (g_saberNewControlScheme->integer || kataMove) { // special moves cost power + if (forcePower >= cost) { return qtrue; - } - else - { + } else { cg.forceHUDTotalFlashTime = level.time + 1000; return qfalse; } - } - else - {//old control scheme: uses no power, so just do it + } else { // old control scheme: uses no power, so just do it return qtrue; } } -void G_DrainPowerForSpecialMove( gentity_t *self, forcePowers_t fp, int cost, qboolean kataMove ) -{ - if ( !self || !self->client || self->s.number >= MAX_CLIENTS ) - { +void G_DrainPowerForSpecialMove(gentity_t *self, forcePowers_t fp, int cost, qboolean kataMove) { + if (!self || !self->client || self->s.number >= MAX_CLIENTS) { return; } - if ( g_saberNewControlScheme->integer || kataMove ) - {//special moves cost power - WP_ForcePowerDrain( self, fp, cost );//drain the required force power - } - else - {//old control scheme: uses no power, so just do it + if (g_saberNewControlScheme->integer || kataMove) { // special moves cost power + WP_ForcePowerDrain(self, fp, cost); // drain the required force power + } else { // old control scheme: uses no power, so just do it } } -int G_CostForSpecialMove( int cost, qboolean kataMove ) -{ - if ( g_saberNewControlScheme->integer || kataMove ) - {//special moves cost power +int G_CostForSpecialMove(int cost, qboolean kataMove) { + if (g_saberNewControlScheme->integer || kataMove) { // special moves cost power return cost; - } - else - {//old control scheme: uses no power, so just do it + } else { // old control scheme: uses no power, so just do it return 0; } } -extern qboolean G_EntIsBreakable( int entityNum, gentity_t *breaker ); -void WP_SaberRadiusDamage( gentity_t *ent, vec3_t point, float radius, int damage, float knockBack ) -{ - if ( !ent || !ent->client ) - { +extern qboolean G_EntIsBreakable(int entityNum, gentity_t *breaker); +void WP_SaberRadiusDamage(gentity_t *ent, vec3_t point, float radius, int damage, float knockBack) { + if (!ent || !ent->client) { return; - } - else if ( radius <= 0.0f || (damage <= 0 && knockBack <= 0) ) - { + } else if (radius <= 0.0f || (damage <= 0 && knockBack <= 0)) { return; - } - else - { - vec3_t mins, maxs, entDir; - gentity_t *radiusEnts[128]; - int numEnts, i; - float dist; + } else { + vec3_t mins, maxs, entDir; + gentity_t *radiusEnts[128]; + int numEnts, i; + float dist; - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = point[i] - radius; maxs[i] = point[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - for ( i = 0; i < numEnts; i++ ) - { - if ( !radiusEnts[i]->inuse ) - { + for (i = 0; i < numEnts; i++) { + if (!radiusEnts[i]->inuse) { continue; } - if ( radiusEnts[i] == ent ) - {//Skip myself + if (radiusEnts[i] == ent) { // Skip myself continue; } - if ( radiusEnts[i]->client == NULL ) - {//must be a client - if ( G_EntIsBreakable( radiusEnts[i]->s.number, ent ) ) - {//damage breakables within range, but not as much - G_Damage( radiusEnts[i], ent, ent, vec3_origin, radiusEnts[i]->currentOrigin, 10, 0, MOD_EXPLOSIVE_SPLASH ); + if (radiusEnts[i]->client == NULL) { // must be a client + if (G_EntIsBreakable(radiusEnts[i]->s.number, ent)) { // damage breakables within range, but not as much + G_Damage(radiusEnts[i], ent, ent, vec3_origin, radiusEnts[i]->currentOrigin, 10, 0, MOD_EXPLOSIVE_SPLASH); } continue; } - if ( (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_RANCOR) - || (radiusEnts[i]->client->ps.eFlags&EF_HELD_BY_WAMPA) ) - {//can't be one being held + if ((radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_RANCOR) || (radiusEnts[i]->client->ps.eFlags & EF_HELD_BY_WAMPA)) { // can't be one being held continue; } - VectorSubtract( radiusEnts[i]->currentOrigin, point, entDir ); - dist = VectorNormalize( entDir ); - if ( dist <= radius ) - {//in range - if ( damage > 0 ) - {//do damage - int points = ceil((float)damage*dist/radius); - G_Damage( radiusEnts[i], ent, ent, vec3_origin, radiusEnts[i]->currentOrigin, points, DAMAGE_NO_KNOCKBACK, MOD_EXPLOSIVE_SPLASH ); - } - if ( knockBack > 0 ) - {//do knockback - if ( radiusEnts[i]->client - && radiusEnts[i]->client->NPC_class != CLASS_RANCOR - && radiusEnts[i]->client->NPC_class != CLASS_ATST - && !(radiusEnts[i]->flags&FL_NO_KNOCKBACK) )//don't throw them back + VectorSubtract(radiusEnts[i]->currentOrigin, point, entDir); + dist = VectorNormalize(entDir); + if (dist <= radius) { // in range + if (damage > 0) { // do damage + int points = ceil((float)damage * dist / radius); + G_Damage(radiusEnts[i], ent, ent, vec3_origin, radiusEnts[i]->currentOrigin, points, DAMAGE_NO_KNOCKBACK, MOD_EXPLOSIVE_SPLASH); + } + if (knockBack > 0) { // do knockback + if (radiusEnts[i]->client && radiusEnts[i]->client->NPC_class != CLASS_RANCOR && radiusEnts[i]->client->NPC_class != CLASS_ATST && + !(radiusEnts[i]->flags & FL_NO_KNOCKBACK)) // don't throw them back { - float knockbackStr = knockBack*dist/radius; + float knockbackStr = knockBack * dist / radius; entDir[2] += 0.1f; - VectorNormalize( entDir ); - G_Throw( radiusEnts[i], entDir, knockbackStr ); - if ( radiusEnts[i]->health > 0 ) - {//still alive - if ( knockbackStr > 50 ) - {//close enough and knockback high enough to possibly knock down - if ( dist < (radius*0.5f) - || radiusEnts[i]->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//within range of my fist or within ground-shaking range and not in the air - G_Knockdown( radiusEnts[i], ent, entDir, 500, qtrue ); + VectorNormalize(entDir); + G_Throw(radiusEnts[i], entDir, knockbackStr); + if (radiusEnts[i]->health > 0) { // still alive + if (knockbackStr > 50) { // close enough and knockback high enough to possibly knock down + if (dist < (radius * 0.5f) || radiusEnts[i]->client->ps.groundEntityNum != + ENTITYNUM_NONE) { // within range of my fist or within ground-shaking range and not in the air + G_Knockdown(radiusEnts[i], ent, entDir, 500, qtrue); } } } @@ -4496,236 +3496,177 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) --------------------------------------------------------- */ #define MAX_SABER_SWING_INC 0.33f -void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) -{ - vec3_t mp1, mp2, md1, md2, baseOld, baseNew, baseDiff, endOld, endNew, bladePointOld, bladePointNew; - float tipDmgMod = 1.0f; - float baseDamage; - int baseDFlags = 0; - qboolean hit_wall = qfalse; - qboolean brokenParry = qfalse; - - for ( int ven = 0; ven < MAX_SABER_VICTIMS; ven++ ) - { +void WP_SaberDamageTrace(gentity_t *ent, int saberNum, int bladeNum) { + vec3_t mp1, mp2, md1, md2, baseOld, baseNew, baseDiff, endOld, endNew, bladePointOld, bladePointNew; + float tipDmgMod = 1.0f; + float baseDamage; + int baseDFlags = 0; + qboolean hit_wall = qfalse; + qboolean brokenParry = qfalse; + + for (int ven = 0; ven < MAX_SABER_VICTIMS; ven++) { victimEntityNum[ven] = ENTITYNUM_NONE; } - memset( totalDmg, 0, sizeof( totalDmg) ); - memset( dmgDir, 0, sizeof( dmgDir ) ); - memset( dmgNormal, 0, sizeof( dmgNormal ) ); - memset( dmgSpot, 0, sizeof( dmgSpot ) ); - memset( dmgFraction, 0, sizeof( dmgFraction ) ); - memset( hitLoc, HL_NONE, sizeof( hitLoc ) ); - memset( hitDismemberLoc, HL_NONE, sizeof( hitDismemberLoc ) ); - memset( hitDismember, qfalse, sizeof( hitDismember ) ); + memset(totalDmg, 0, sizeof(totalDmg)); + memset(dmgDir, 0, sizeof(dmgDir)); + memset(dmgNormal, 0, sizeof(dmgNormal)); + memset(dmgSpot, 0, sizeof(dmgSpot)); + memset(dmgFraction, 0, sizeof(dmgFraction)); + memset(hitLoc, HL_NONE, sizeof(hitLoc)); + memset(hitDismemberLoc, HL_NONE, sizeof(hitDismemberLoc)); + memset(hitDismember, qfalse, sizeof(hitDismember)); numVictims = 0; VectorClear(saberHitLocation); VectorClear(saberHitNormal); - saberHitFraction = 1.0; // Closest saber hit. The saber can do no damage past this point. + saberHitFraction = 1.0; // Closest saber hit. The saber can do no damage past this point. saberHitEntity = ENTITYNUM_NONE; sabersCrossed = -1; - if ( !ent->client ) - { + if (!ent->client) { return; } - if ( !ent->s.number ) - {//player never uses these + if (!ent->s.number) { // player never uses these ent->client->ps.saberEventFlags &= ~SEF_EVENTS; } - if ( ent->client->ps.saber[saberNum].blade[bladeNum].length <= 1 )//cen get down to 1 when in a wall - {//saber is not on + if (ent->client->ps.saber[saberNum].blade[bladeNum].length <= 1) // cen get down to 1 when in a wall + { // saber is not on return; } - if ( VectorCompare( ent->client->renderInfo.muzzlePointOld, vec3_origin ) || VectorCompare( ent->client->renderInfo.muzzleDirOld, vec3_origin ) ) - { - //just started up the saber? + if (VectorCompare(ent->client->renderInfo.muzzlePointOld, vec3_origin) || VectorCompare(ent->client->renderInfo.muzzleDirOld, vec3_origin)) { + // just started up the saber? return; } int saberContents = 0; - if ( !(ent->client->ps.saber[saberNum].saberFlags&SFL_ON_IN_WATER) ) - {//saber can't stay on underwater - saberContents = gi.pointcontents( ent->client->renderInfo.muzzlePoint, ent->client->ps.saberEntityNum ); - } - if ( (saberContents&CONTENTS_WATER)|| - (saberContents&CONTENTS_SLIME)|| - (saberContents&CONTENTS_LAVA) ) - {//um... turn off? Or just set length to 1? - //FIXME: short-out effect/sound? + if (!(ent->client->ps.saber[saberNum].saberFlags & SFL_ON_IN_WATER)) { // saber can't stay on underwater + saberContents = gi.pointcontents(ent->client->renderInfo.muzzlePoint, ent->client->ps.saberEntityNum); + } + if ((saberContents & CONTENTS_WATER) || (saberContents & CONTENTS_SLIME) || (saberContents & CONTENTS_LAVA)) { // um... turn off? Or just set length to 1? + // FIXME: short-out effect/sound? ent->client->ps.saber[saberNum].blade[bladeNum].active = qfalse; return; - } - else if (!g_saberNoEffects && gi.WE_IsOutside(ent->client->renderInfo.muzzlePoint)) - { + } else if (!g_saberNoEffects && gi.WE_IsOutside(ent->client->renderInfo.muzzlePoint)) { float chanceOfFizz = gi.WE_GetChanceOfSaberFizz(); - if (chanceOfFizz>0 && Q_flrand(0.0f, 1.0f)client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].length*Q_flrand(0, 1), ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, end ); - G_PlayEffect( "saber/fizz", end ); + if (chanceOfFizz > 0 && Q_flrand(0.0f, 1.0f) < chanceOfFizz) { + vec3_t end; /*normal = {0,0,1};//FIXME: opposite of rain angles?*/ + VectorMA(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].length * Q_flrand(0, 1), + ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, end); + G_PlayEffect("saber/fizz", end); } } - //FIXMEFIXMEFIXME: When in force speed (esp. lvl 3), need to interpolate this because + // FIXMEFIXMEFIXME: When in force speed (esp. lvl 3), need to interpolate this because // we animate so much faster that the arc is pretty much flat... int entPowerLevel = 0; - if ( ent->client->NPC_class == CLASS_SABER_DROID ) - { - entPowerLevel = SaberDroid_PowerLevelForSaberAnim( ent ); - } - else if ( !ent->s.number && (ent->client->ps.forcePowersActive&(1<client->NPC_class == CLASS_SABER_DROID) { + entPowerLevel = SaberDroid_PowerLevelForSaberAnim(ent); + } else if (!ent->s.number && (ent->client->ps.forcePowersActive & (1 << FP_SPEED))) { entPowerLevel = FORCE_LEVEL_3; - } - else - { - entPowerLevel = PM_PowerLevelForSaberAnim( &ent->client->ps, saberNum ); + } else { + entPowerLevel = PM_PowerLevelForSaberAnim(&ent->client->ps, saberNum); } - if ( entPowerLevel ) - { - if ( ent->client->ps.forceRageRecoveryTime > level.time ) - { + if (entPowerLevel) { + if (ent->client->ps.forceRageRecoveryTime > level.time) { entPowerLevel = FORCE_LEVEL_1; - } - else if ( ent->client->ps.forcePowersActive & (1 << FP_RAGE) ) - { + } else if (ent->client->ps.forcePowersActive & (1 << FP_RAGE)) { entPowerLevel += ent->client->ps.forcePowerLevel[FP_RAGE]; } } - if ( ent->client->ps.saberInFlight ) - {//flying sabers are much more deadly - //unless you're dead - if ( ent->health <= 0 && g_saberRealisticCombat->integer < 2 ) - {//so enemies don't keep trying to block it - //FIXME: still do damage, just not to humanoid clients who should try to avoid it - //baseDamage = 0.0f; + if (ent->client->ps.saberInFlight) { // flying sabers are much more deadly + // unless you're dead + if (ent->health <= 0 && g_saberRealisticCombat->integer < 2) { // so enemies don't keep trying to block it + // FIXME: still do damage, just not to humanoid clients who should try to avoid it + // baseDamage = 0.0f; return; } - //or unless returning - else if ( ent->client->ps.saberEntityState == SES_RETURNING - && !(ent->client->ps.saber[0].saberFlags&SFL_RETURN_DAMAGE) )//type != SABER_STAR ) - {//special case, since we're returning, chances are if we hit something - //it's going to be butt-first. So do less damage. + // or unless returning + else if (ent->client->ps.saberEntityState == SES_RETURNING && !(ent->client->ps.saber[0].saberFlags & SFL_RETURN_DAMAGE)) // type != SABER_STAR ) + { // special case, since we're returning, chances are if we hit something + // it's going to be butt-first. So do less damage. baseDamage = 0.1f; - } - else - { - if ( !ent->s.number ) - {//cheat for player + } else { + if (!ent->s.number) { // cheat for player baseDamage = 10.0f; - } - else - { + } else { baseDamage = 2.5f; } } - //Use old to current since can't predict it - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, mp1 ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, md1 ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, mp2 ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, md2 ); - } - else - { - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - {//no effects, no damage + // Use old to current since can't predict it + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, mp1); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, md1); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, mp2); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, md2); + } else { + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { // no effects, no damage return; - } - else if ( G_InCinematicSaberAnim( ent ) ) - { + } else if (G_InCinematicSaberAnim(ent)) { baseDFlags = DAMAGE_NO_KILL; baseDamage = 0.1f; - } - else if ( ent->client->ps.saberMove == LS_READY - && !PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) ) - {//just do effects - if ( g_saberRealisticCombat->integer < 2 ) - {//don't kill with this hit + } else if (ent->client->ps.saberMove == LS_READY && !PM_SaberInSpecialAttack(ent->client->ps.torsoAnim)) { // just do effects + if (g_saberRealisticCombat->integer < 2) { // don't kill with this hit baseDFlags = DAMAGE_NO_KILL; } - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT2) ) - ) - {//do nothing at all when idle + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT2))) { // do nothing at all when idle return; } baseDamage = 0; - } - else if ( ent->client->ps.saberLockTime > level.time ) - {//just do effects - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT2) ) - ) - {//do nothing at all when idle + } else if (ent->client->ps.saberLockTime > level.time) { // just do effects + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT2))) { // do nothing at all when idle return; } baseDamage = 0; - } - else if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].damageScale <= 0.0f - && ent->client->ps.saber[saberNum].knockbackScale <= 0.0f ) - {//this blade does no damage and no knockback (only for blocking?) + } else if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].damageScale <= 0.0f && + ent->client->ps.saber[saberNum].knockbackScale <= 0.0f) { // this blade does no damage and no knockback (only for blocking?) baseDamage = 0; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].damageScale2 <= 0.0f - && ent->client->ps.saber[saberNum].knockbackScale2 <= 0.0f ) - {//this blade does no damage and no knockback (only for blocking?) + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].damageScale2 <= 0.0f && + ent->client->ps.saber[saberNum].knockbackScale2 <= 0.0f) { // this blade does no damage and no knockback (only for blocking?) baseDamage = 0; - } - else if ( ent->client->ps.saberBlocked > BLOCKED_NONE - || ( !PM_SaberInAttack( ent->client->ps.saberMove ) - && !PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - && !PM_SaberInTransitionAny( ent->client->ps.saberMove ) - ) - ) - {//don't do damage if parrying/reflecting/bouncing/deflecting or not actually attacking or in a transition to/from/between attacks - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT2) ) - ) - {//do nothing at all when idle + } else if (ent->client->ps.saberBlocked > BLOCKED_NONE || + (!PM_SaberInAttack(ent->client->ps.saberMove) && !PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) && + !PM_SaberInTransitionAny(ent->client->ps.saberMove))) { // don't do damage if parrying/reflecting/bouncing/deflecting or not actually + // attacking or in a transition to/from/between attacks + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT2))) { // do nothing at all when idle return; } baseDamage = 0; - } - else - {//okay, in a saberMove that does damage - //make sure we're in the right anim - if ( !PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - && !PM_InAnimForSaberMove( ent->client->ps.torsoAnim, ent->client->ps.saberMove ) ) - {//forced into some other animation somehow, like a pain or death? - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && (ent->client->ps.saber[saberNum].saberFlags2&SFL2_NO_IDLE_EFFECT2) ) - ) - {//do nothing at all when idle + } else { // okay, in a saberMove that does damage + // make sure we're in the right anim + if (!PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) && + !PM_InAnimForSaberMove(ent->client->ps.torsoAnim, + ent->client->ps.saberMove)) { // forced into some other animation somehow, like a pain or death? + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + (ent->client->ps.saber[saberNum].saberFlags2 & SFL2_NO_IDLE_EFFECT2))) { // do nothing at all when idle return; } baseDamage = 0; - } - else if ( ent->client->ps.weaponstate == WEAPON_FIRING && ent->client->ps.saberBlocked == BLOCKED_NONE && - ( PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) || PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || entPowerLevel > FORCE_LEVEL_2 || (WP_SaberBladeDoTransitionDamage( &ent->client->ps.saber[saberNum], bladeNum )&&PM_SaberInTransitionAny(ent->client->ps.saberMove)) ) )// || ent->client->ps.saberAnimLevel == SS_STAFF ) ) - {//normal attack swing swinging/spinning (or if using strong set), do normal damage //FIXME: or if using staff? - //FIXME: more damage for higher attack power levels? + } else if (ent->client->ps.weaponstate == WEAPON_FIRING && ent->client->ps.saberBlocked == BLOCKED_NONE && + (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || entPowerLevel > FORCE_LEVEL_2 || + (WP_SaberBladeDoTransitionDamage(&ent->client->ps.saber[saberNum], bladeNum) && + PM_SaberInTransitionAny(ent->client->ps.saberMove)))) // || ent->client->ps.saberAnimLevel == SS_STAFF ) ) + { // normal attack swing swinging/spinning (or if using strong set), do normal damage //FIXME: or if using staff? + // FIXME: more damage for higher attack power levels? // More damage based on length/color of saber? - //FIXME: Desann does double damage? - if ( g_saberRealisticCombat->integer ) - { - switch ( entPowerLevel ) - { + // FIXME: Desann does double damage? + if (g_saberRealisticCombat->integer) { + switch (entPowerLevel) { default: case FORCE_LEVEL_3: baseDamage = 10.0f; @@ -4738,33 +3679,21 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) baseDamage = 2.5f; break; } - } - else - { - if ( g_spskill->integer > 0 - && ent->s.number < MAX_CLIENTS - && ( ent->client->ps.torsoAnim == BOTH_ROLL_STAB - || ent->client->ps.torsoAnim == BOTH_SPINATTACK6 - || ent->client->ps.torsoAnim == BOTH_SPINATTACK7 - || ent->client->ps.torsoAnim == BOTH_LUNGE2_B__T_ ) ) - {//*sigh*, these anim do less damage since they're so easy to do - baseDamage = 2.5f; - } - else - { + } else { + if (g_spskill->integer > 0 && ent->s.number < MAX_CLIENTS && + (ent->client->ps.torsoAnim == BOTH_ROLL_STAB || ent->client->ps.torsoAnim == BOTH_SPINATTACK6 || + ent->client->ps.torsoAnim == BOTH_SPINATTACK7 || + ent->client->ps.torsoAnim == BOTH_LUNGE2_B__T_)) { //*sigh*, these anim do less damage since they're so easy to do + baseDamage = 2.5f; + } else { baseDamage = 2.5f * (float)entPowerLevel; } } - } - else - {//saber is transitioning, defending or idle, don't do as much damage - //FIXME: strong attacks and returns should do damage and be unblockable - if ( g_timescale->value < 1.0 ) - {//in slow mo or force speed, we need to do damage during the transitions - if ( g_saberRealisticCombat->integer ) - { - switch ( entPowerLevel ) - { + } else { // saber is transitioning, defending or idle, don't do as much damage + // FIXME: strong attacks and returns should do damage and be unblockable + if (g_timescale->value < 1.0) { // in slow mo or force speed, we need to do damage during the transitions + if (g_saberRealisticCombat->integer) { + switch (entPowerLevel) { case FORCE_LEVEL_3: baseDamage = 10.0f; break; @@ -4776,14 +3705,11 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) baseDamage = 2.5f; break; } - } - else - { + } else { baseDamage = 2.5f * (float)entPowerLevel; } - } - else// if ( !ent->s.number ) - {//I have to do *some* damage in transitions or else you feel like a total gimp + } else // if ( !ent->s.number ) + { // I have to do *some* damage in transitions or else you feel like a total gimp baseDamage = 0.1f; } /* @@ -4795,75 +3721,62 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) } } - //Use current to next since can predict it - //FIXME: if they're closer than the saber blade start, we don't want the + // Use current to next since can predict it + // FIXME: if they're closer than the saber blade start, we don't want the // arm to pass through them without any damage... so check the radius // and push them away (do pain & knockback) - //FIXME: if going into/coming from a parry/reflection or going into a deflection, don't use old mp & dir? Otherwise, deflections will cut through? - //VectorCopy( ent->client->renderInfo.muzzlePoint, mp1 ); - //VectorCopy( ent->client->renderInfo.muzzleDir, md1 ); - //VectorCopy( ent->client->renderInfo.muzzlePointNext, mp2 ); - //VectorCopy( ent->client->renderInfo.muzzleDirNext, md2 ); - //prediction was causing gaps in swing (G2 problem) so *don't* predict - if ( ent->client->ps.saberDamageDebounceTime > level.time ) - {//really only used when a saber attack start anim starts, not actually for stopping damage - //we just want to not use the old position to trace the attack from... - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld ); - } - //do the damage trace from the last position... - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, mp1 ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, md1 ); + // FIXME: if going into/coming from a parry/reflection or going into a deflection, don't use old mp & dir? Otherwise, deflections will cut through? + // VectorCopy( ent->client->renderInfo.muzzlePoint, mp1 ); + // VectorCopy( ent->client->renderInfo.muzzleDir, md1 ); + // VectorCopy( ent->client->renderInfo.muzzlePointNext, mp2 ); + // VectorCopy( ent->client->renderInfo.muzzleDirNext, md2 ); + // prediction was causing gaps in swing (G2 problem) so *don't* predict + if (ent->client->ps.saberDamageDebounceTime > level.time) { // really only used when a saber attack start anim starts, not actually for stopping damage + // we just want to not use the old position to trace the attack from... + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld); + } + // do the damage trace from the last position... + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePointOld, mp1); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDirOld, md1); //...to the current one. - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, mp2 ); - VectorCopy( ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, md2 ); - - //NOTE: this is a test, may not be necc, as I can still swing right through someone without hitting them, somehow... - //see if anyone is so close that they're within the dist from my origin to the start of the saber - if ( ent->health > 0 && !ent->client->ps.saberLockTime && saberNum == 0 && bladeNum == 0 - && !G_InCinematicSaberAnim( ent ) ) - {//only do once - for first blade + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, mp2); + VectorCopy(ent->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, md2); + + // NOTE: this is a test, may not be necc, as I can still swing right through someone without hitting them, somehow... + // see if anyone is so close that they're within the dist from my origin to the start of the saber + if (ent->health > 0 && !ent->client->ps.saberLockTime && saberNum == 0 && bladeNum == 0 && + !G_InCinematicSaberAnim(ent)) { // only do once - for first blade trace_t trace; - gi.trace( &trace, ent->currentOrigin, vec3_origin, vec3_origin, mp1, ent->s.number, (MASK_SHOT&~(CONTENTS_CORPSE|CONTENTS_ITEM)), (EG2_Collision)0, 0 ); - if ( trace.entityNum < ENTITYNUM_WORLD && (trace.entityNum > 0||ent->client->NPC_class == CLASS_DESANN) )//NPCs don't push player away, unless it's Desann - {//a valid ent + gi.trace(&trace, ent->currentOrigin, vec3_origin, vec3_origin, mp1, ent->s.number, (MASK_SHOT & ~(CONTENTS_CORPSE | CONTENTS_ITEM)), + (EG2_Collision)0, 0); + if (trace.entityNum < ENTITYNUM_WORLD && + (trace.entityNum > 0 || ent->client->NPC_class == CLASS_DESANN)) // NPCs don't push player away, unless it's Desann + { // a valid ent gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt - && traceEnt->client - && traceEnt->client->NPC_class != CLASS_RANCOR - && traceEnt->client->NPC_class != CLASS_ATST - && traceEnt->client->NPC_class != CLASS_WAMPA - && traceEnt->client->NPC_class != CLASS_SAND_CREATURE - && traceEnt->health > 0 - && traceEnt->client->playerTeam != ent->client->playerTeam - && !PM_SuperBreakLoseAnim( traceEnt->client->ps.legsAnim ) - && !PM_SuperBreakLoseAnim( traceEnt->client->ps.torsoAnim ) - && !PM_SuperBreakWinAnim( traceEnt->client->ps.legsAnim ) - && !PM_SuperBreakWinAnim( traceEnt->client->ps.torsoAnim ) - && !PM_InKnockDown( &traceEnt->client->ps ) - && !PM_LockedAnim( traceEnt->client->ps.legsAnim ) - && !PM_LockedAnim( traceEnt->client->ps.torsoAnim ) - && !G_InCinematicSaberAnim( traceEnt )) - {//enemy client, push them away - if ( !traceEnt->client->ps.saberLockTime - && !traceEnt->message - && !(traceEnt->flags&FL_NO_KNOCKBACK) - && (!traceEnt->NPC||traceEnt->NPC->jumpState!=JS_JUMPING) ) - {//don't push people in saberlock or with security keys or who are in BS_JUMP + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class != CLASS_RANCOR && traceEnt->client->NPC_class != CLASS_ATST && + traceEnt->client->NPC_class != CLASS_WAMPA && traceEnt->client->NPC_class != CLASS_SAND_CREATURE && traceEnt->health > 0 && + traceEnt->client->playerTeam != ent->client->playerTeam && !PM_SuperBreakLoseAnim(traceEnt->client->ps.legsAnim) && + !PM_SuperBreakLoseAnim(traceEnt->client->ps.torsoAnim) && !PM_SuperBreakWinAnim(traceEnt->client->ps.legsAnim) && + !PM_SuperBreakWinAnim(traceEnt->client->ps.torsoAnim) && !PM_InKnockDown(&traceEnt->client->ps) && + !PM_LockedAnim(traceEnt->client->ps.legsAnim) && !PM_LockedAnim(traceEnt->client->ps.torsoAnim) && + !G_InCinematicSaberAnim(traceEnt)) { // enemy client, push them away + if (!traceEnt->client->ps.saberLockTime && !traceEnt->message && !(traceEnt->flags & FL_NO_KNOCKBACK) && + (!traceEnt->NPC || + traceEnt->NPC->jumpState != JS_JUMPING)) { // don't push people in saberlock or with security keys or who are in BS_JUMP vec3_t hitDir; - VectorSubtract( trace.endpos, ent->currentOrigin, hitDir ); - float totalDist = Distance( mp1, ent->currentOrigin ); - float knockback = (totalDist-VectorNormalize( hitDir ))/totalDist * 200.0f; + VectorSubtract(trace.endpos, ent->currentOrigin, hitDir); + float totalDist = Distance(mp1, ent->currentOrigin); + float knockback = (totalDist - VectorNormalize(hitDir)) / totalDist * 200.0f; hitDir[2] = 0; - //FIXME: do we need to call G_Throw? Seems unfair to put actual knockback on them, stops the attack - //G_Throw( traceEnt, hitDir, knockback ); - VectorMA( traceEnt->client->ps.velocity, knockback, hitDir, traceEnt->client->ps.velocity ); + // FIXME: do we need to call G_Throw? Seems unfair to put actual knockback on them, stops the attack + // G_Throw( traceEnt, hitDir, knockback ); + VectorMA(traceEnt->client->ps.velocity, knockback, hitDir, traceEnt->client->ps.velocity); traceEnt->client->ps.pm_time = 200; traceEnt->client->ps.pm_flags |= PMF_TIME_NOFRICTION; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( "%s pushing away %s at %s\n", ent->NPC_type, traceEnt->NPC_type, vtos( traceEnt->client->ps.velocity ) ); + if (d_saberCombat->integer) { + gi.Printf("%s pushing away %s at %s\n", ent->NPC_type, traceEnt->NPC_type, vtos(traceEnt->client->ps.velocity)); } #endif } @@ -4872,207 +3785,166 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) } } - //the thicker the blade, the more damage... the thinner, the less damage - baseDamage *= ent->client->ps.saber[saberNum].blade[bladeNum].radius/SABER_RADIUS_STANDARD; + // the thicker the blade, the more damage... the thinner, the less damage + baseDamage *= ent->client->ps.saber[saberNum].blade[bladeNum].radius / SABER_RADIUS_STANDARD; - if ( g_saberRealisticCombat->integer > 1 ) - {//always do damage, and lots of it - if ( g_saberRealisticCombat->integer > 2 ) - {//always do damage, and lots of it + if (g_saberRealisticCombat->integer > 1) { // always do damage, and lots of it + if (g_saberRealisticCombat->integer > 2) { // always do damage, and lots of it baseDamage = 25.0f; - } - else if ( baseDamage > 0.1f ) - {//only do super damage if we would have done damage according to normal rules + } else if (baseDamage > 0.1f) { // only do super damage if we would have done damage according to normal rules baseDamage = 25.0f; } + } else if (((!ent->s.number && ent->client->ps.forcePowersActive & (1 << FP_SPEED)) || ent->client->ps.forcePowersActive & (1 << FP_RAGE)) && + g_timescale->value < 1.0f) { + baseDamage *= (1.0f - g_timescale->value); } - else if ( ((!ent->s.number&&ent->client->ps.forcePowersActive&(1<client->ps.forcePowersActive&(1<value < 1.0f ) - { - baseDamage *= (1.0f-g_timescale->value); - } - if ( baseDamage > 0.1f ) - { - if ( (ent->client->ps.forcePowersActive&(1< 0.1f) { + if ((ent->client->ps.forcePowersActive & (1 << FP_RAGE))) { // add some damage if raged baseDamage += ent->client->ps.forcePowerLevel[FP_RAGE] * 5.0f; - } - else if ( ent->client->ps.forceRageRecoveryTime ) - {//halve it if recovering + } else if (ent->client->ps.forceRageRecoveryTime) { // halve it if recovering baseDamage *= 0.5f; } } // Get the old state of the blade - VectorCopy( mp1, baseOld ); - VectorMA( baseOld, ent->client->ps.saber[saberNum].blade[bladeNum].length, md1, endOld ); + VectorCopy(mp1, baseOld); + VectorMA(baseOld, ent->client->ps.saber[saberNum].blade[bladeNum].length, md1, endOld); // Get the future state of the blade - VectorCopy( mp2, baseNew ); - VectorMA( baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, md2, endNew ); + VectorCopy(mp2, baseNew); + VectorMA(baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, md2, endNew); sabersCrossed = -1; - if ( VectorCompare2( baseOld, baseNew ) && VectorCompare2( endOld, endNew ) ) - { - hit_wall = WP_SaberDamageForTrace( ent->s.number, mp2, endNew, baseDamage*4, md2, - qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qfalse, - saberNum, bladeNum ); - } - else - { + if (VectorCompare2(baseOld, baseNew) && VectorCompare2(endOld, endNew)) { + hit_wall = WP_SaberDamageForTrace(ent->s.number, mp2, endNew, baseDamage * 4, md2, qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qfalse, + saberNum, bladeNum); + } else { float aveLength, step = 8, stepsize = 8; - vec3_t ma1, ma2, md2ang, curBase1, curBase2; - int xx; - //do the trace at the base first - hit_wall = WP_SaberDamageForTrace( ent->s.number, baseOld, baseNew, baseDamage, md2, - qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qtrue, - saberNum, bladeNum ); - - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0 ) - { - //adjust muzzleDir... + vec3_t ma1, ma2, md2ang, curBase1, curBase2; + int xx; + // do the trace at the base first + hit_wall = WP_SaberDamageForTrace(ent->s.number, baseOld, baseNew, baseDamage, md2, qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qtrue, + saberNum, bladeNum); + + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0) { + // adjust muzzleDir... vec3_t ma1, ma2; - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], saberHitFraction ); + vectoangles(md1, ma1); + vectoangles(md2, ma2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], saberHitFraction); } - AngleVectors( md2ang, md2, NULL, NULL ); - //shorten the base pos - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, md2, endNew ); + AngleVectors(md2ang, md2, NULL, NULL); + // shorten the base pos + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, md2, endNew); } - //If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc + // If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc float dirInc, curDirFrac; - if ( PM_SaberInAttack( ent->client->ps.saberMove ) - || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - || PM_SpinningSaberAnim( ent->client->ps.torsoAnim ) - || PM_InSpecialJump( ent->client->ps.torsoAnim ) - || (g_timescale->value<1.0f&&PM_SaberInTransitionAny( ent->client->ps.saberMove )) ) - { - curDirFrac = DotProduct( md1, md2 ); - } - else - { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || PM_InSpecialJump(ent->client->ps.torsoAnim) || + (g_timescale->value < 1.0f && PM_SaberInTransitionAny(ent->client->ps.saberMove))) { + curDirFrac = DotProduct(md1, md2); + } else { curDirFrac = 1.0f; } - //NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! - if ( fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC ) - {//the saber blade spun more than 33 degrees since the last damage trace - curDirFrac = dirInc = 1.0f/((1.0f - curDirFrac)/MAX_SABER_SWING_INC); - } - else - { + // NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! + if (fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC) { // the saber blade spun more than 33 degrees since the last damage trace + curDirFrac = dirInc = 1.0f / ((1.0f - curDirFrac) / MAX_SABER_SWING_INC); + } else { curDirFrac = 1.0f; dirInc = 0.0f; } qboolean hit_saber = qfalse; - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); - - vec3_t curMD1, curMD2;//, mdDiff, dirDiff; - //VectorSubtract( md2, md1, mdDiff ); - VectorCopy( md1, curMD2 ); - VectorCopy( baseOld, curBase2 ); - - while ( 1 ) - { - VectorCopy( curMD2, curMD1 ); - VectorCopy( curBase2, curBase1 ); - if ( curDirFrac >= 1.0f ) - { - VectorCopy( md2, curMD2 ); - VectorCopy( baseNew, curBase2 ); - } - else - { - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], curDirFrac ); - } - AngleVectors( md2ang, curMD2, NULL, NULL ); - //VectorMA( md1, curDirFrac, mdDiff, curMD2 ); - VectorSubtract( baseNew, baseOld, baseDiff ); - VectorMA( baseOld, curDirFrac, baseDiff, curBase2 ); + vectoangles(md1, ma1); + vectoangles(md2, ma2); + + vec3_t curMD1, curMD2; //, mdDiff, dirDiff; + // VectorSubtract( md2, md1, mdDiff ); + VectorCopy(md1, curMD2); + VectorCopy(baseOld, curBase2); + + while (1) { + VectorCopy(curMD2, curMD1); + VectorCopy(curBase2, curBase1); + if (curDirFrac >= 1.0f) { + VectorCopy(md2, curMD2); + VectorCopy(baseNew, curBase2); + } else { + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], curDirFrac); + } + AngleVectors(md2ang, curMD2, NULL, NULL); + // VectorMA( md1, curDirFrac, mdDiff, curMD2 ); + VectorSubtract(baseNew, baseOld, baseDiff); + VectorMA(baseOld, curDirFrac, baseDiff, curBase2); } // Move up the blade in intervals of stepsize - for ( step = stepsize; step < ent->client->ps.saber[saberNum].blade[bladeNum].length && step < ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld; step+=12 ) - { - VectorMA( curBase1, step, curMD1, bladePointOld ); - VectorMA( curBase2, step, curMD2, bladePointNew ); - if ( WP_SaberDamageForTrace( ent->s.number, bladePointOld, bladePointNew, baseDamage, curMD2, - qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qtrue, - saberNum, bladeNum ) ) - { + for (step = stepsize; + step < ent->client->ps.saber[saberNum].blade[bladeNum].length && step < ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld; + step += 12) { + VectorMA(curBase1, step, curMD1, bladePointOld); + VectorMA(curBase2, step, curMD2, bladePointNew); + if (WP_SaberDamageForTrace(ent->s.number, bladePointOld, bladePointNew, baseDamage, curMD2, qfalse, entPowerLevel, + ent->client->ps.saber[saberNum].type, qtrue, saberNum, bladeNum)) { hit_wall = qtrue; } - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0 ) - { - //adjust muzzle endpoint - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, curMD2, endNew ); - //adjust muzzleDir... + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0) { + // adjust muzzle endpoint + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, ent->client->ps.saber[saberNum].blade[bladeNum].length, curMD2, endNew); + // adjust muzzleDir... vec3_t curMA1, curMA2; - vectoangles( curMD1, curMA1 ); - vectoangles( curMD2, curMA2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( curMA1[xx], curMA2[xx], saberHitFraction ); + vectoangles(curMD1, curMA1); + vectoangles(curMD2, curMA2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(curMA1[xx], curMA2[xx], saberHitFraction); } - AngleVectors( md2ang, curMD2, NULL, NULL ); + AngleVectors(md2ang, curMD2, NULL, NULL); /* VectorSubtract( curMD2, curMD1, dirDiff ); VectorMA( curMD1, saberHitFraction, dirDiff, curMD2 ); */ hit_saber = qtrue; } - if (hit_wall) - { + if (hit_wall) { break; } } - if ( hit_wall || hit_saber ) - { + if (hit_wall || hit_saber) { break; } - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { break; - } - else - { + } else { curDirFrac += dirInc; - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { curDirFrac = 1.0f; } } } - //do the trace at the end last - //Special check- adjust for length of blade not being a multiple of 12 - aveLength = (ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld + ent->client->ps.saber[saberNum].blade[bladeNum].length)/2; - if ( step > aveLength ) - {//less dmg if the last interval was not stepsize - tipDmgMod = (stepsize-(step-aveLength))/stepsize; + // do the trace at the end last + // Special check- adjust for length of blade not being a multiple of 12 + aveLength = (ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld + ent->client->ps.saber[saberNum].blade[bladeNum].length) / 2; + if (step > aveLength) { // less dmg if the last interval was not stepsize + tipDmgMod = (stepsize - (step - aveLength)) / stepsize; } - //NOTE: since this is the tip, we do not extrapolate the extra 16 - if ( WP_SaberDamageForTrace( ent->s.number, endOld, endNew, tipDmgMod*baseDamage, md2, - qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qfalse, - saberNum, bladeNum ) ) - { + // NOTE: since this is the tip, we do not extrapolate the extra 16 + if (WP_SaberDamageForTrace(ent->s.number, endOld, endNew, tipDmgMod * baseDamage, md2, qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, + qfalse, saberNum, bladeNum)) { hit_wall = qtrue; } } - if ( (saberHitFraction < 1.0f||(sabersCrossed>=0&&sabersCrossed<=32.0f)) && (ent->client->ps.weaponstate == WEAPON_FIRING || ent->client->ps.saberInFlight || G_InCinematicSaberAnim( ent ) ) ) - {// The saber (in-hand) hit another saber, mano. + if ((saberHitFraction < 1.0f || (sabersCrossed >= 0 && sabersCrossed <= 32.0f)) && + (ent->client->ps.weaponstate == WEAPON_FIRING || ent->client->ps.saberInFlight || + G_InCinematicSaberAnim(ent))) { // The saber (in-hand) hit another saber, mano. qboolean inFlightSaberBlocked = qfalse; qboolean collisionResolved = qfalse; qboolean deflected = qfalse; @@ -5081,13 +3953,11 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) gentity_t *hitOwner = NULL; int hitOwnerPowerLevel = FORCE_LEVEL_0; - if ( hitEnt ) - { + if (hitEnt) { hitOwner = hitEnt->owner; } - if ( hitOwner && hitOwner->client ) - { - hitOwnerPowerLevel = PM_PowerLevelForSaberAnim( &hitOwner->client->ps ); + if (hitOwner && hitOwner->client) { + hitOwnerPowerLevel = PM_PowerLevelForSaberAnim(&hitOwner->client->ps); /* if ( entPowerLevel >= FORCE_LEVEL_3 && PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) ) @@ -5102,322 +3972,265 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) */ } - //FIXME: check for certain anims, facing, etc, to make them lock into a sabers-locked pose - //SEF_LOCKED + // FIXME: check for certain anims, facing, etc, to make them lock into a sabers-locked pose + // SEF_LOCKED - if ( ent->client->ps.saberInFlight && saberNum == 0 && - ent->client->ps.saber[saberNum].blade[bladeNum].active && - ent->client->ps.saberEntityNum != ENTITYNUM_NONE && - ent->client->ps.saberEntityState != SES_RETURNING ) - {//saber was blocked, return it + if (ent->client->ps.saberInFlight && saberNum == 0 && ent->client->ps.saber[saberNum].blade[bladeNum].active && + ent->client->ps.saberEntityNum != ENTITYNUM_NONE && ent->client->ps.saberEntityState != SES_RETURNING) { // saber was blocked, return it inFlightSaberBlocked = qtrue; } - //FIXME: based on strength, position and angle of attack & defense, decide if: + // FIXME: based on strength, position and angle of attack & defense, decide if: // defender and attacker lock sabers // *defender's parry should hold and attack bounces (or deflects, based on angle of sabers) // *defender's parry is somewhat broken and both bounce (or deflect) // *defender's parry is broken and they bounce while attacker's attack deflects or carries through (especially if they're dead) // defender is knocked down and attack goes through - //Check deflections and broken parries - if ( hitOwner && hitOwner->health > 0 && ent->health > 0 //both are alive - && !inFlightSaberBlocked && hitOwner->client && !hitOwner->client->ps.saberInFlight && !ent->client->ps.saberInFlight//both have sabers in-hand - && ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN - && ent->client->ps.saberLockTime < level.time - && hitOwner->client->ps.saberLockTime < level.time ) - {//2 in-hand sabers hit - //FIXME: defender should not parry or block at all if not in a saber anim... like, if in a roll or knockdown... - if ( baseDamage ) - {//there is damage involved, not just effects + // Check deflections and broken parries + if (hitOwner && hitOwner->health > 0 && ent->health > 0 // both are alive + && !inFlightSaberBlocked && hitOwner->client && !hitOwner->client->ps.saberInFlight && !ent->client->ps.saberInFlight // both have sabers in-hand + && ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN && ent->client->ps.saberLockTime < level.time && + hitOwner->client->ps.saberLockTime < level.time) { // 2 in-hand sabers hit + // FIXME: defender should not parry or block at all if not in a saber anim... like, if in a roll or knockdown... + if (baseDamage) { // there is damage involved, not just effects qboolean entAttacking = qfalse; qboolean hitOwnerAttacking = qfalse; qboolean entDefending = qfalse; qboolean hitOwnerDefending = qfalse; qboolean forceLock = qfalse; - if ( (ent->client->NPC_class == CLASS_KYLE && (ent->spawnflags&1) && hitOwner->s.number < MAX_CLIENTS ) - || (hitOwner->client->NPC_class == CLASS_KYLE && (hitOwner->spawnflags&1) && ent->s.number < MAX_CLIENTS ) ) - {//Player vs. Kyle Boss == lots of saberlocks - if ( !Q_irand( 0, 2 ) ) - { + if ((ent->client->NPC_class == CLASS_KYLE && (ent->spawnflags & 1) && hitOwner->s.number < MAX_CLIENTS) || + (hitOwner->client->NPC_class == CLASS_KYLE && (hitOwner->spawnflags & 1) && + ent->s.number < MAX_CLIENTS)) { // Player vs. Kyle Boss == lots of saberlocks + if (!Q_irand(0, 2)) { forceLock = qtrue; } } - if ( PM_SaberInAttack( ent->client->ps.saberMove ) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) ) - { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim)) { entAttacking = qtrue; - } - else if ( entPowerLevel > FORCE_LEVEL_2 ) - {//stronger styles count as attacking even if in a transition - if ( PM_SaberInTransitionAny( ent->client->ps.saberMove ) ) - { + } else if (entPowerLevel > FORCE_LEVEL_2) { // stronger styles count as attacking even if in a transition + if (PM_SaberInTransitionAny(ent->client->ps.saberMove)) { entAttacking = qtrue; } } - if ( PM_SaberInParry( ent->client->ps.saberMove ) - || ent->client->ps.saberMove == LS_READY ) - { + if (PM_SaberInParry(ent->client->ps.saberMove) || ent->client->ps.saberMove == LS_READY) { entDefending = qtrue; } - if ( ent->client->ps.torsoAnim == BOTH_A1_SPECIAL - || ent->client->ps.torsoAnim == BOTH_A2_SPECIAL - || ent->client->ps.torsoAnim == BOTH_A3_SPECIAL ) - {//parry/block/break-parry bonus for single-style kata moves + if (ent->client->ps.torsoAnim == BOTH_A1_SPECIAL || ent->client->ps.torsoAnim == BOTH_A2_SPECIAL || + ent->client->ps.torsoAnim == BOTH_A3_SPECIAL) { // parry/block/break-parry bonus for single-style kata moves entPowerLevel++; } - if ( entAttacking ) - {//add twoHanded bonus and breakParryBonus to entPowerLevel here - //This makes staff too powerful - if ( (ent->client->ps.saber[saberNum].saberFlags&SFL_TWO_HANDED) ) - { + if (entAttacking) { // add twoHanded bonus and breakParryBonus to entPowerLevel here + // This makes staff too powerful + if ((ent->client->ps.saber[saberNum].saberFlags & SFL_TWO_HANDED)) { entPowerLevel++; } - //FIXME: what if dualSabers && both sabers are hitting at same time? - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) ) - { + // FIXME: what if dualSabers && both sabers are hitting at same time? + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum)) { entPowerLevel += ent->client->ps.saber[saberNum].breakParryBonus; - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) ) - { + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum)) { entPowerLevel += ent->client->ps.saber[saberNum].breakParryBonus2; } - } - else if ( entDefending ) - {//add twoHanded bonus and dualSaber bonus and parryBonus to entPowerLevel here - if ( (ent->client->ps.saber[saberNum].saberFlags&SFL_TWO_HANDED) - || (ent->client->ps.dualSabers && ent->client->ps.saber[1].Active()) ) - { + } else if (entDefending) { // add twoHanded bonus and dualSaber bonus and parryBonus to entPowerLevel here + if ((ent->client->ps.saber[saberNum].saberFlags & SFL_TWO_HANDED) || (ent->client->ps.dualSabers && ent->client->ps.saber[1].Active())) { entPowerLevel++; } - //FIXME: what about second saber if dualSabers? + // FIXME: what about second saber if dualSabers? entPowerLevel += ent->client->ps.saber[saberNum].parryBonus; } - if ( PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) ) - { + if (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim)) { hitOwnerAttacking = qtrue; - } - else if ( hitOwnerPowerLevel > FORCE_LEVEL_2 ) - {//stronger styles count as attacking even if in a transition - if ( PM_SaberInTransitionAny( hitOwner->client->ps.saberMove ) ) - { + } else if (hitOwnerPowerLevel > FORCE_LEVEL_2) { // stronger styles count as attacking even if in a transition + if (PM_SaberInTransitionAny(hitOwner->client->ps.saberMove)) { hitOwnerAttacking = qtrue; } } - if ( PM_SaberInParry( hitOwner->client->ps.saberMove ) - || hitOwner->client->ps.saberMove == LS_READY ) - { + if (PM_SaberInParry(hitOwner->client->ps.saberMove) || hitOwner->client->ps.saberMove == LS_READY) { hitOwnerDefending = qtrue; } - if ( hitOwner->client->ps.torsoAnim == BOTH_A1_SPECIAL - || hitOwner->client->ps.torsoAnim == BOTH_A2_SPECIAL - || hitOwner->client->ps.torsoAnim == BOTH_A3_SPECIAL ) - {//parry/block/break-parry bonus for single-style kata moves + if (hitOwner->client->ps.torsoAnim == BOTH_A1_SPECIAL || hitOwner->client->ps.torsoAnim == BOTH_A2_SPECIAL || + hitOwner->client->ps.torsoAnim == BOTH_A3_SPECIAL) { // parry/block/break-parry bonus for single-style kata moves hitOwnerPowerLevel++; } - if ( hitOwnerAttacking ) - {//add twoHanded bonus and breakParryBonus to entPowerLevel here - if ( (hitOwner->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - { + if (hitOwnerAttacking) { // add twoHanded bonus and breakParryBonus to entPowerLevel here + if ((hitOwner->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { hitOwnerPowerLevel++; } hitOwnerPowerLevel += hitOwner->client->ps.saber[0].breakParryBonus; - if ( hitOwner->client->ps.dualSabers && Q_irand( 0, 1 ) ) - {//FIXME: assumes both sabers are hitting at same time...? + if (hitOwner->client->ps.dualSabers && Q_irand(0, 1)) { // FIXME: assumes both sabers are hitting at same time...? hitOwnerPowerLevel += 1 + hitOwner->client->ps.saber[1].breakParryBonus; } - } - else if ( hitOwnerDefending ) - {//add twoHanded bonus and dualSaber bonus and parryBonus to entPowerLevel here - if ( (hitOwner->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) - || (hitOwner->client->ps.dualSabers && hitOwner->client->ps.saber[1].Active()) ) - { + } else if (hitOwnerDefending) { // add twoHanded bonus and dualSaber bonus and parryBonus to entPowerLevel here + if ((hitOwner->client->ps.saber[0].saberFlags & SFL_TWO_HANDED) || + (hitOwner->client->ps.dualSabers && hitOwner->client->ps.saber[1].Active())) { hitOwnerPowerLevel++; } hitOwnerPowerLevel += hitOwner->client->ps.saber[0].parryBonus; - if ( hitOwner->client->ps.dualSabers && Q_irand( 0, 1 ) ) - {//FIXME: assumes both sabers are defending at same time...? + if (hitOwner->client->ps.dualSabers && Q_irand(0, 1)) { // FIXME: assumes both sabers are defending at same time...? hitOwnerPowerLevel += 1 + hitOwner->client->ps.saber[1].parryBonus; } } - if ( PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( ent->client->ps.torsoAnim ) - || PM_SuperBreakLoseAnim( hitOwner->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( hitOwner->client->ps.torsoAnim ) ) - {//don't mess with this + if (PM_SuperBreakLoseAnim(ent->client->ps.torsoAnim) || PM_SuperBreakWinAnim(ent->client->ps.torsoAnim) || + PM_SuperBreakLoseAnim(hitOwner->client->ps.torsoAnim) || PM_SuperBreakWinAnim(hitOwner->client->ps.torsoAnim)) { // don't mess with this collisionResolved = qtrue; - } - else if ( entAttacking - && hitOwnerAttacking - && !Q_irand( 0, g_saberLockRandomNess->integer ) - && ( g_debugSaberLock->integer || forceLock - || entPowerLevel == hitOwnerPowerLevel - || (entPowerLevel > FORCE_LEVEL_2 && hitOwnerPowerLevel > FORCE_LEVEL_2 ) - || (entPowerLevel < FORCE_LEVEL_3 && hitOwnerPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && Q_irand( 0, 3 )) - || (entPowerLevel < FORCE_LEVEL_2 && hitOwnerPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && Q_irand( 0, 2 )) - || (hitOwnerPowerLevel < FORCE_LEVEL_3 && entPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && !Q_irand( 0, 1 )) - || (hitOwnerPowerLevel < FORCE_LEVEL_2 && entPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && !Q_irand( 0, 1 ))) - && WP_SabersCheckLock( ent, hitOwner ) ) - { + } else if (entAttacking && hitOwnerAttacking && !Q_irand(0, g_saberLockRandomNess->integer) && + (g_debugSaberLock->integer || forceLock || entPowerLevel == hitOwnerPowerLevel || + (entPowerLevel > FORCE_LEVEL_2 && hitOwnerPowerLevel > FORCE_LEVEL_2) || + (entPowerLevel < FORCE_LEVEL_3 && hitOwnerPowerLevel < FORCE_LEVEL_3 && + hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && Q_irand(0, 3)) || + (entPowerLevel < FORCE_LEVEL_2 && hitOwnerPowerLevel < FORCE_LEVEL_3 && + hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && Q_irand(0, 2)) || + (hitOwnerPowerLevel < FORCE_LEVEL_3 && entPowerLevel < FORCE_LEVEL_3 && + ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && !Q_irand(0, 1)) || + (hitOwnerPowerLevel < FORCE_LEVEL_2 && entPowerLevel < FORCE_LEVEL_3 && + ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && !Q_irand(0, 1))) && + WP_SabersCheckLock(ent, hitOwner)) { collisionResolved = qtrue; - } - else if ( hitOwnerAttacking - && entDefending - && !Q_irand( 0, g_saberLockRandomNess->integer*3 ) - && (g_debugSaberLock->integer || forceLock || - ((ent->client->ps.saberMove != LS_READY || (hitOwnerPowerLevel-ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand( -6, 0 ) ) - && ((hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 )|| - (hitOwnerPowerLevel < FORCE_LEVEL_2 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 )|| - (hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && !Q_irand( 0, (hitOwnerPowerLevel-ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]+1)*2 ))) )) - && WP_SabersCheckLock( hitOwner, ent ) ) - { + } else if (hitOwnerAttacking && entDefending && !Q_irand(0, g_saberLockRandomNess->integer * 3) && + (g_debugSaberLock->integer || forceLock || + ((ent->client->ps.saberMove != LS_READY || + (hitOwnerPowerLevel - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand(-6, 0)) && + ((hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2) || + (hitOwnerPowerLevel < FORCE_LEVEL_2 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1) || + (hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && + !Q_irand(0, (hitOwnerPowerLevel - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] + 1) * 2))))) && + WP_SabersCheckLock(hitOwner, ent)) { collisionResolved = qtrue; - } - else if ( entAttacking && hitOwnerDefending ) - {//I'm attacking hit, they're parrying - qboolean activeDefense = (qboolean)(hitOwner->s.number||g_saberAutoBlocking->integer||hitOwner->client->ps.saberBlockingTime > level.time); - if ( !Q_irand( 0, g_saberLockRandomNess->integer*3 ) - && activeDefense - && (g_debugSaberLock->integer || forceLock || - ((hitOwner->client->ps.saberMove != LS_READY || (entPowerLevel-hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand( -6, 0 ) ) - && ( ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 ) - || ( entPowerLevel < FORCE_LEVEL_2 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 ) - || ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && !Q_irand( 0, (entPowerLevel-hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]+1)*2 )) ) )) - && WP_SabersCheckLock( ent, hitOwner ) ) - { + } else if (entAttacking && hitOwnerDefending) { // I'm attacking hit, they're parrying + qboolean activeDefense = + (qboolean)(hitOwner->s.number || g_saberAutoBlocking->integer || hitOwner->client->ps.saberBlockingTime > level.time); + if (!Q_irand(0, g_saberLockRandomNess->integer * 3) && activeDefense && + (g_debugSaberLock->integer || forceLock || + ((hitOwner->client->ps.saberMove != LS_READY || + (entPowerLevel - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand(-6, 0)) && + ((entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2) || + (entPowerLevel < FORCE_LEVEL_2 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1) || + (entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && + !Q_irand(0, (entPowerLevel - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] + 1) * 2))))) && + WP_SabersCheckLock(ent, hitOwner)) { collisionResolved = qtrue; - } - else if ( saberHitFraction < 1.0f ) - {//an actual collision - if ( entPowerLevel < FORCE_LEVEL_3 && activeDefense ) - {//strong attacks cannot be deflected - //based on angle of attack & angle of defensive saber, see if I should deflect off in another dir rather than bounce back - deflected = WP_GetSaberDeflectionAngle( ent, hitOwner ); - //just so Jedi knows that he was blocked + } else if (saberHitFraction < 1.0f) { // an actual collision + if (entPowerLevel < FORCE_LEVEL_3 && activeDefense) { // strong attacks cannot be deflected + // based on angle of attack & angle of defensive saber, see if I should deflect off in another dir rather than bounce back + deflected = WP_GetSaberDeflectionAngle(ent, hitOwner); + // just so Jedi knows that he was blocked ent->client->ps.saberEventFlags |= SEF_BLOCKED; } - //base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE - if ( entPowerLevel < FORCE_LEVEL_3 - //&& ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_3//if you have high saber offense, you cannot have your attack knocked away, regardless of what style you're using? + // base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE + if (entPowerLevel < FORCE_LEVEL_3 + //&& ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_3//if you have high saber offense, you cannot have your attack + //knocked away, regardless of what style you're using? //&& hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 - && activeDefense - && (hitOwnerPowerLevel > FORCE_LEVEL_2||(hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_2&&Q_irand(0,hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE]))) ) - {//knockaways can make fast-attacker go into a broken parry anim if the ent is using fast or med (but not Tavion) - //make me parry - WP_SaberParry( hitOwner, ent, saberNum, bladeNum ); - //turn the parry into a knockaway - hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry( hitOwner->client->ps.saberBlocked ); - //make them go into a broken parry - ent->client->ps.saberBounceMove = PM_BrokenParryForAttack( ent->client->ps.saberMove ); + && activeDefense && + (hitOwnerPowerLevel > FORCE_LEVEL_2 || + (hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 && + Q_irand(0, + hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE])))) { // knockaways can make fast-attacker go into a broken parry + // anim if the ent is using fast or med (but not Tavion) + // make me parry + WP_SaberParry(hitOwner, ent, saberNum, bladeNum); + // turn the parry into a knockaway + hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry(hitOwner->client->ps.saberBlocked); + // make them go into a broken parry + ent->client->ps.saberBounceMove = PM_BrokenParryForAttack(ent->client->ps.saberMove); ent->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; - if ( saberNum == 0 ) - {//FIXME: can only lose right-hand saber for now - if ( !(ent->client->ps.saber[saberNum].saberFlags&SFL_NOT_DISARMABLE) - && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 + if (saberNum == 0) { // FIXME: can only lose right-hand saber for now + if (!(ent->client->ps.saber[saberNum].saberFlags & SFL_NOT_DISARMABLE) && + ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 //&& (ent->s.number||g_saberRealisticCombat->integer) - && Q_irand( 0, hitOwner->client->ps.SaberDisarmBonus( 0 ) ) > 0 - && (hitOwner->s.number || g_saberAutoBlocking->integer || !Q_irand( 0, 2 )) )//if player defending and autoblocking is on, this is less likely to happen, so don't do the random check - {//knocked the saber right out of his hand! (never happens to player) - //Get a good velocity to send the saber in based on my parry move - vec3_t throwDir; - if ( !PM_VelocityForBlockedMove( &hitOwner->client->ps, throwDir ) ) - { - PM_VelocityForSaberMove( &ent->client->ps, throwDir ); + && Q_irand(0, hitOwner->client->ps.SaberDisarmBonus(0)) > 0 && + (hitOwner->s.number || g_saberAutoBlocking->integer || + !Q_irand(0, 2))) // if player defending and autoblocking is on, this is less likely to happen, so don't do the random check + { // knocked the saber right out of his hand! (never happens to player) + // Get a good velocity to send the saber in based on my parry move + vec3_t throwDir; + if (!PM_VelocityForBlockedMove(&hitOwner->client->ps, throwDir)) { + PM_VelocityForSaberMove(&ent->client->ps, throwDir); } - WP_SaberLose( ent, throwDir ); + WP_SaberLose(ent, throwDir); } } - //just so Jedi knows that he was blocked + // just so Jedi knows that he was blocked ent->client->ps.saberEventFlags |= SEF_BLOCKED; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_RED"%s knockaway %s's attack, new move = %s, anim = %s\n", hitOwner->NPC_type, ent->NPC_type, saberMoveData[ent->client->ps.saberBounceMove].name, animTable[saberMoveData[ent->client->ps.saberBounceMove].animToUse].name ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_RED "%s knockaway %s's attack, new move = %s, anim = %s\n", hitOwner->NPC_type, ent->NPC_type, + saberMoveData[ent->client->ps.saberBounceMove].name, + animTable[saberMoveData[ent->client->ps.saberBounceMove].animToUse].name); } #endif - } - else if ( !activeDefense//they're not defending - || (entPowerLevel > FORCE_LEVEL_2 //I hit hard - && hitOwnerPowerLevel < entPowerLevel)//they are defending, but their defense strength is lower than my attack... - || (!deflected && Q_irand( 0, Q_max(0, PM_PowerLevelForSaberAnim( &ent->client->ps, saberNum ) - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE])/*PM_PowerLevelForSaberAnim( &hitOwner->client->ps )*/ ) > 0 ) ) - {//broke their parry altogether - if ( entPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, Q_max(0, ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) ) ) - {//chance of continuing with the attack (not bouncing back) + } else if (!activeDefense // they're not defending + || (entPowerLevel > FORCE_LEVEL_2 // I hit hard + && hitOwnerPowerLevel < entPowerLevel) // they are defending, but their defense strength is lower than my attack... + || (!deflected && + Q_irand(0, Q_max(0, PM_PowerLevelForSaberAnim(&ent->client->ps, saberNum) - + hitOwner->client->ps + .forcePowerLevel[FP_SABER_DEFENSE]) /*PM_PowerLevelForSaberAnim( &hitOwner->client->ps )*/) > + 0)) { // broke their parry altogether + if (entPowerLevel > FORCE_LEVEL_2 || + Q_irand(0, Q_max(0, ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - + hitOwner->client->ps + .forcePowerLevel[FP_SABER_DEFENSE]))) { // chance of continuing with the attack (not bouncing back) ent->client->ps.saberEventFlags &= ~SEF_BLOCKED; ent->client->ps.saberBounceMove = LS_NONE; brokenParry = qtrue; } - //do some time-consuming saber-knocked-aside broken parry anim + // do some time-consuming saber-knocked-aside broken parry anim hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; hitOwner->client->ps.saberBounceMove = LS_NONE; - //FIXME: for now, you always disarm the right-hand saber - if ( !(hitOwner->client->ps.saber[0].saberFlags&SFL_NOT_DISARMABLE) - && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 + // FIXME: for now, you always disarm the right-hand saber + if (!(hitOwner->client->ps.saber[0].saberFlags & SFL_NOT_DISARMABLE) && + hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 //&& (ent->s.number||g_saberRealisticCombat->integer) - && Q_irand( 0, 2-ent->client->ps.SaberDisarmBonus( bladeNum ) ) <= 0 ) - {//knocked the saber right out of his hand! - //get the right velocity for my attack direction - vec3_t throwDir; - PM_VelocityForSaberMove( &ent->client->ps, throwDir ); - WP_SaberLose( hitOwner, throwDir ); - if ( (ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0,3) ) - || ( ent->client->ps.saberAnimLevel==SS_DESANN&&!Q_irand(0,1) ) ) - {// a strong attack - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + && Q_irand(0, 2 - ent->client->ps.SaberDisarmBonus(bladeNum)) <= 0) { // knocked the saber right out of his hand! + // get the right velocity for my attack direction + vec3_t throwDir; + PM_VelocityForSaberMove(&ent->client->ps, throwDir); + WP_SaberLose(hitOwner, throwDir); + if ((ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0, 3)) || + (ent->client->ps.saberAnimLevel == SS_DESANN && !Q_irand(0, 1))) { // a strong attack + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } } - } - else - { - if ( (ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0,5) ) - || ( ent->client->ps.saberAnimLevel==SS_DESANN&&!Q_irand(0,3) ) ) - {// a strong attack - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + } else { + if ((ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0, 5)) || + (ent->client->ps.saberAnimLevel == SS_DESANN && !Q_irand(0, 3))) { // a strong attack + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( ent->client->ps.saberEventFlags&SEF_BLOCKED ) - { - gi.Printf( S_COLOR_RED"%s parry broken (bounce/deflect)!\n", hitOwner->targetname ); - } - else - { - gi.Printf( S_COLOR_RED"%s parry broken (follow-through)!\n", hitOwner->targetname ); + if (d_saberCombat->integer) { + if (ent->client->ps.saberEventFlags & SEF_BLOCKED) { + gi.Printf(S_COLOR_RED "%s parry broken (bounce/deflect)!\n", hitOwner->targetname); + } else { + gi.Printf(S_COLOR_RED "%s parry broken (follow-through)!\n", hitOwner->targetname); } } #endif - } - else - {//just a parry, possibly the hitOwner can knockaway the ent - WP_SaberParry( hitOwner, ent, saberNum, bladeNum ); - if ( PM_SaberInBounce( ent->client->ps.saberMove ) //FIXME: saberMove not set until pmove! - && activeDefense - && hitOwner->client->ps.saberAnimLevel != SS_FAST //&& hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 - && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 ) - {//attacker bounced off, and defender has ability to do knockaways, so do one unless we're using fast attacks - //turn the parry into a knockaway - hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry( hitOwner->client->ps.saberBlocked ); - } - else if ( (ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0,6) ) - || ( ent->client->ps.saberAnimLevel==SS_DESANN && !Q_irand(0,3) ) ) - {// a strong attack can sometimes do a knockdown - //HMM... maybe only if they're moving backwards? - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + } else { // just a parry, possibly the hitOwner can knockaway the ent + WP_SaberParry(hitOwner, ent, saberNum, bladeNum); + if (PM_SaberInBounce(ent->client->ps.saberMove) // FIXME: saberMove not set until pmove! + && activeDefense && hitOwner->client->ps.saberAnimLevel != SS_FAST //&& hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 + && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > + FORCE_LEVEL_2) { // attacker bounced off, and defender has ability to do knockaways, so do one unless we're using fast + // attacks + // turn the parry into a knockaway + hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry(hitOwner->client->ps.saberBlocked); + } else if ((ent->client->ps.saberAnimLevel == SS_STRONG && !Q_irand(0, 6)) || + (ent->client->ps.saberAnimLevel == SS_DESANN && !Q_irand(0, 3))) { // a strong attack can sometimes do a knockdown + // HMM... maybe only if they're moving backwards? + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } @@ -5437,9 +4250,11 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) hitOwner->client->ps.saberEventFlags |= SEF_BLOCKED; } //FIXME: base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || (!deflected && Q_irand( 0, PM_PowerLevelForSaberAnim( &hitOwner->client->ps ) - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) > 0 ) ) + if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || (!deflected && Q_irand( 0, PM_PowerLevelForSaberAnim( &hitOwner->client->ps ) - +ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) > 0 ) ) {//broke my parry altogether - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) ) + if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - +ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) ) {//chance of continuing with the attack (not bouncing back) hitOwner->client->ps.saberEventFlags &= ~SEF_BLOCKED; hitOwner->client->ps.saberBounceMove = LS_NONE; @@ -5467,42 +4282,31 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) collisionResolved = qtrue; } */ - else - {//some other kind of in-hand saber collision + else { // some other kind of in-hand saber collision } } - } - else - {//some kind of in-flight collision + } else { // some kind of in-flight collision } - if ( saberHitFraction < 1.0f ) - { - if ( !collisionResolved && baseDamage ) - {//some other kind of in-hand saber collision - //handle my reaction - if ( !ent->client->ps.saberInFlight - && ent->client->ps.saberLockTime < level.time ) - {//my saber is in hand - if ( ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { - if ( PM_SaberInAttack( ent->client->ps.saberMove ) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) || - (entPowerLevel > FORCE_LEVEL_2&&!PM_SaberInIdle(ent->client->ps.saberMove)&&!PM_SaberInParry(ent->client->ps.saberMove)&&!PM_SaberInReflect(ent->client->ps.saberMove)) ) - {//in the middle of attacking - if ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->health > 0 ) - {//don't deflect/bounce in strong attack or when enemy is dead - WP_GetSaberDeflectionAngle( ent, hitOwner ); + if (saberHitFraction < 1.0f) { + if (!collisionResolved && baseDamage) { // some other kind of in-hand saber collision + // handle my reaction + if (!ent->client->ps.saberInFlight && ent->client->ps.saberLockTime < level.time) { // my saber is in hand + if (ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + (entPowerLevel > FORCE_LEVEL_2 && !PM_SaberInIdle(ent->client->ps.saberMove) && !PM_SaberInParry(ent->client->ps.saberMove) && + !PM_SaberInReflect(ent->client->ps.saberMove))) { // in the middle of attacking + if (entPowerLevel < FORCE_LEVEL_3 && hitOwner->health > 0) { // don't deflect/bounce in strong attack or when enemy is dead + WP_GetSaberDeflectionAngle(ent, hitOwner); ent->client->ps.saberEventFlags |= SEF_BLOCKED; - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( ent, hitOwner->s.number, saberNum, bladeNum ); + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(ent, hitOwner->s.number, saberNum, bladeNum); } - } - else - {//saber collided when not attacking, parry it - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( ent, hitOwner->s.number, saberNum, bladeNum ); + } else { // saber collided when not attacking, parry it + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(ent, hitOwner->s.number, saberNum, bladeNum); /* if ( ent->s.number || g_saberAutoBlocking->integer || ent->client->ps.saberBlockingTime > level.time ) {//either an NPC or a player who has blocking @@ -5515,27 +4319,20 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) } */ } + } else { + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(ent, hitOwner->s.number, saberNum, bladeNum); } - else - { - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( ent, hitOwner->s.number, saberNum, bladeNum ); - } + } else { // nothing happens to *me* when my inFlight saber hits something } - else - {//nothing happens to *me* when my inFlight saber hits something - } - //handle their reaction - if ( hitOwner - && hitOwner->health > 0 - && hitOwner->client - && !hitOwner->client->ps.saberInFlight - && hitOwner->client->ps.saberLockTime < level.time ) - {//their saber is in hand - if ( PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) || - (hitOwner->client->ps.saberAnimLevel > SS_MEDIUM&&!PM_SaberInIdle(hitOwner->client->ps.saberMove)&&!PM_SaberInParry(hitOwner->client->ps.saberMove)&&!PM_SaberInReflect(hitOwner->client->ps.saberMove)) ) - {//in the middle of attacking + // handle their reaction + if (hitOwner && hitOwner->health > 0 && hitOwner->client && !hitOwner->client->ps.saberInFlight && + hitOwner->client->ps.saberLockTime < level.time) { // their saber is in hand + if (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim) || + (hitOwner->client->ps.saberAnimLevel > SS_MEDIUM && !PM_SaberInIdle(hitOwner->client->ps.saberMove) && + !PM_SaberInParry(hitOwner->client->ps.saberMove) && + !PM_SaberInReflect(hitOwner->client->ps.saberMove))) { // in the middle of attacking /* if ( hitOwner->client->ps.saberAnimLevel < SS_STRONG ) {//don't deflect/bounce in strong attack @@ -5543,29 +4340,22 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) hitOwner->client->ps.saberEventFlags |= SEF_BLOCKED; } */ - } - else - {//saber collided when not attacking, parry it - if ( !PM_SaberInBrokenParry( hitOwner->client->ps.saberMove ) ) - {//not currently in a broken parry - if ( !WP_SaberParry( hitOwner, ent, saberNum, bladeNum ) ) - {//FIXME: hitOwner can't parry, do some time-consuming saber-knocked-aside broken parry anim? - //hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; + } else { // saber collided when not attacking, parry it + if (!PM_SaberInBrokenParry(hitOwner->client->ps.saberMove)) { // not currently in a broken parry + if (!WP_SaberParry(hitOwner, ent, saberNum, + bladeNum)) { // FIXME: hitOwner can't parry, do some time-consuming saber-knocked-aside broken parry anim? + // hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; } } } - } - else - {//nothing happens to *hitOwner* when their inFlight saber hits something + } else { // nothing happens to *hitOwner* when their inFlight saber hits something } } - //collision must have been handled by now - //Set the blocked attack bounce value in saberBlocked so we actually play our saberBounceMove anim - if ( ent->client->ps.saberEventFlags & SEF_BLOCKED ) - { - if ( ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { + // collision must have been handled by now + // Set the blocked attack bounce value in saberBlocked so we actually play our saberBounceMove anim + if (ent->client->ps.saberEventFlags & SEF_BLOCKED) { + if (ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { ent->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; } } @@ -5577,278 +4367,207 @@ void WP_SaberDamageTrace( gentity_t *ent, int saberNum, int bladeNum ) */ } - if ( saberHitFraction < 1.0f || collisionResolved ) - {//either actually hit or locked - if ( ent->client->ps.saberLockTime < level.time ) - { - if ( inFlightSaberBlocked ) - {//FIXME: never hear this sound - WP_SaberBounceSound( ent, hitOwner, &g_entities[ent->client->ps.saberEntityNum], 0, 0, qfalse ); - } - else - { - if ( deflected ) - { - WP_SaberBounceSound( ent, hitOwner, NULL, saberNum, bladeNum, qtrue ); - } - else - { - WP_SaberBlockSound( ent, hitOwner, saberNum, bladeNum ); + if (saberHitFraction < 1.0f || collisionResolved) { // either actually hit or locked + if (ent->client->ps.saberLockTime < level.time) { + if (inFlightSaberBlocked) { // FIXME: never hear this sound + WP_SaberBounceSound(ent, hitOwner, &g_entities[ent->client->ps.saberEntityNum], 0, 0, qfalse); + } else { + if (deflected) { + WP_SaberBounceSound(ent, hitOwner, NULL, saberNum, bladeNum, qtrue); + } else { + WP_SaberBlockSound(ent, hitOwner, saberNum, bladeNum); } } - if ( !g_saberNoEffects ) - { - WP_SaberBlockEffect( ent, saberNum, bladeNum, saberHitLocation, saberHitNormal, qfalse ); + if (!g_saberNoEffects) { + WP_SaberBlockEffect(ent, saberNum, bladeNum, saberHitLocation, saberHitNormal, qfalse); } } // Set the little screen flash - only when an attack is blocked - if ( !g_noClashFlare ) - { - g_saberFlashTime = level.time-50; - VectorCopy( saberHitLocation, g_saberFlashPos ); + if (!g_noClashFlare) { + g_saberFlashTime = level.time - 50; + VectorCopy(saberHitLocation, g_saberFlashPos); } } - if ( saberHitFraction < 1.0f ) - { - if ( inFlightSaberBlocked ) - {//we threw a saber and it was blocked, do any effects, etc. - int knockAway = 5; - if ( hitEnt - && hitOwner - && hitOwner->client - && (PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) || PM_SpinningSaberAnim( hitOwner->client->ps.torsoAnim )) ) - {//if hit someone who was in an attack or spin anim, more likely to have in-flight saber knocked away - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 ) - {//strong attacks almost always knock it aside! + if (saberHitFraction < 1.0f) { + if (inFlightSaberBlocked) { // we threw a saber and it was blocked, do any effects, etc. + int knockAway = 5; + if (hitEnt && hitOwner && hitOwner->client && + (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim) || + PM_SpinningSaberAnim(hitOwner->client->ps.torsoAnim))) { // if hit someone who was in an attack or spin anim, more likely to have in-flight + // saber knocked away + if (hitOwnerPowerLevel > FORCE_LEVEL_2) { // strong attacks almost always knock it aside! knockAway = 1; - } - else - {//33% chance + } else { // 33% chance knockAway = 2; } - knockAway -= hitOwner->client->ps.SaberDisarmBonus( 0 ); - } - if ( Q_irand( 0, knockAway ) <= 0 || //random - ( hitOwner - && hitOwner->client - && hitOwner->NPC - && (hitOwner->NPC->aiFlags&NPCAI_BOSS_CHARACTER) - ) //or if blocked by a Boss character FIXME: or base on defense level? - )//FIXME: player should not auto-block a flying saber, let him override the parry with an attack to knock the saber from the air, rather than this random chance - {//knock it aside and turn it off - if ( !g_saberNoEffects ) - { - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hitOtherEffect ) - { - G_PlayEffect( ent->client->ps.saber[saberNum].hitOtherEffect, saberHitLocation, saberHitNormal ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hitOtherEffect2 ) - { - G_PlayEffect( ent->client->ps.saber[saberNum].hitOtherEffect2, saberHitLocation, saberHitNormal ); - } - else - { - G_PlayEffect( "saber/saber_cut", saberHitLocation, saberHitNormal ); - } - } - if ( hitEnt ) - { + knockAway -= hitOwner->client->ps.SaberDisarmBonus(0); + } + if (Q_irand(0, knockAway) <= 0 || // random + (hitOwner && hitOwner->client && hitOwner->NPC && + (hitOwner->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) // or if blocked by a Boss character FIXME: or base on defense level? + ) // FIXME: player should not auto-block a flying saber, let him override the parry with an attack to knock the saber from the air, rather + // than this random chance + { // knock it aside and turn it off + if (!g_saberNoEffects) { + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].hitOtherEffect) { + G_PlayEffect(ent->client->ps.saber[saberNum].hitOtherEffect, saberHitLocation, saberHitNormal); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && + ent->client->ps.saber[saberNum].hitOtherEffect2) { + G_PlayEffect(ent->client->ps.saber[saberNum].hitOtherEffect2, saberHitLocation, saberHitNormal); + } else { + G_PlayEffect("saber/saber_cut", saberHitLocation, saberHitNormal); + } + } + if (hitEnt) { vec3_t newDir; - VectorSubtract( g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir ); - VectorNormalize( newDir ); - G_ReflectMissile( ent, &g_entities[ent->client->ps.saberEntityNum], newDir ); + VectorSubtract(g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir); + VectorNormalize(newDir); + G_ReflectMissile(ent, &g_entities[ent->client->ps.saberEntityNum], newDir); } - Jedi_PlayDeflectSound( hitOwner ); - WP_SaberDrop( ent, &g_entities[ent->client->ps.saberEntityNum] ); - } - else - { - if ( !Q_irand( 0, 2 ) && hitEnt ) - { + Jedi_PlayDeflectSound(hitOwner); + WP_SaberDrop(ent, &g_entities[ent->client->ps.saberEntityNum]); + } else { + if (!Q_irand(0, 2) && hitEnt) { vec3_t newDir; - VectorSubtract( g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir ); - VectorNormalize( newDir ); - G_ReflectMissile( ent, &g_entities[ent->client->ps.saberEntityNum], newDir ); + VectorSubtract(g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir); + VectorNormalize(newDir); + G_ReflectMissile(ent, &g_entities[ent->client->ps.saberEntityNum], newDir); } - WP_SaberReturn( ent, &g_entities[ent->client->ps.saberEntityNum] ); + WP_SaberReturn(ent, &g_entities[ent->client->ps.saberEntityNum]); } } } } - if ( ent->client->ps.saberLockTime > level.time ) - { - if ( ent->s.number < ent->client->ps.saberLockEnemy - && !Q_irand( 0, 3 ) ) - {//need to make some kind of effect - vec3_t hitNorm = {0,0,1}; - if ( WP_SabersIntersection( ent, &g_entities[ent->client->ps.saberLockEnemy], g_saberFlashPos ) ) - { - if ( Q_irand( 0, 10 ) ) - { - if ( !g_saberNoEffects ) - { - WP_SaberBlockEffect( ent, saberNum, bladeNum, g_saberFlashPos, hitNorm, qfalse ); + if (ent->client->ps.saberLockTime > level.time) { + if (ent->s.number < ent->client->ps.saberLockEnemy && !Q_irand(0, 3)) { // need to make some kind of effect + vec3_t hitNorm = {0, 0, 1}; + if (WP_SabersIntersection(ent, &g_entities[ent->client->ps.saberLockEnemy], g_saberFlashPos)) { + if (Q_irand(0, 10)) { + if (!g_saberNoEffects) { + WP_SaberBlockEffect(ent, saberNum, bladeNum, g_saberFlashPos, hitNorm, qfalse); } - } - else - { - if ( !g_noClashFlare ) - { - g_saberFlashTime = level.time-50; + } else { + if (!g_noClashFlare) { + g_saberFlashTime = level.time - 50; } - if ( !g_saberNoEffects ) - { - WP_SaberBlockEffect( ent, saberNum, bladeNum, g_saberFlashPos, hitNorm, qtrue ); + if (!g_saberNoEffects) { + WP_SaberBlockEffect(ent, saberNum, bladeNum, g_saberFlashPos, hitNorm, qtrue); } } - WP_SaberBlockSound( ent, &g_entities[ent->client->ps.saberLockEnemy], 0, 0 ); + WP_SaberBlockSound(ent, &g_entities[ent->client->ps.saberLockEnemy], 0, 0); } } - } - else - { - if ( hit_wall - && (ent->client->ps.saber[saberNum].saberFlags&SFL_BOUNCE_ON_WALLS) - && (PM_SaberInAttackPure( ent->client->ps.saberMove ) //only in a normal attack anim - || ent->client->ps.saberMove == LS_A_JUMP_T__B_ ) //or in the strong jump-fwd-attack "death from above" move - ) - {//bounce off walls - //do anim + } else { + if (hit_wall && (ent->client->ps.saber[saberNum].saberFlags & SFL_BOUNCE_ON_WALLS) && + (PM_SaberInAttackPure(ent->client->ps.saberMove) // only in a normal attack anim + || ent->client->ps.saberMove == LS_A_JUMP_T__B_) // or in the strong jump-fwd-attack "death from above" move + ) { // bounce off walls + // do anim ent->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; - ent->client->ps.saberBounceMove = LS_D1_BR+(saberMoveData[ent->client->ps.saberMove].startQuad-Q_BR); - //do bounce sound & force feedback - WP_SaberBounceOnWallSound( ent, saberNum, bladeNum ); - //do hit effect - if ( !g_saberNoEffects ) - { - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hitOtherEffect ) - { - G_PlayEffect( ent->client->ps.saber[saberNum].hitOtherEffect, saberHitLocation, saberHitNormal ); + ent->client->ps.saberBounceMove = LS_D1_BR + (saberMoveData[ent->client->ps.saberMove].startQuad - Q_BR); + // do bounce sound & force feedback + WP_SaberBounceOnWallSound(ent, saberNum, bladeNum); + // do hit effect + if (!g_saberNoEffects) { + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].hitOtherEffect) { + G_PlayEffect(ent->client->ps.saber[saberNum].hitOtherEffect, saberHitLocation, saberHitNormal); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum) && ent->client->ps.saber[saberNum].hitOtherEffect2) { + G_PlayEffect(ent->client->ps.saber[saberNum].hitOtherEffect2, saberHitLocation, saberHitNormal); + } else { + G_PlayEffect("saber/saber_cut", saberHitLocation, saberHitNormal); } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) - && ent->client->ps.saber[saberNum].hitOtherEffect2 ) - { - G_PlayEffect( ent->client->ps.saber[saberNum].hitOtherEffect2, saberHitLocation, saberHitNormal ); - } - else - { - G_PlayEffect( "saber/saber_cut", saberHitLocation, saberHitNormal ); - } - } - //do radius damage/knockback, if any - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[saberNum], bladeNum ) ) - { - WP_SaberRadiusDamage( ent, saberHitLocation, ent->client->ps.saber[saberNum].splashRadius, ent->client->ps.saber[saberNum].splashDamage, ent->client->ps.saber[saberNum].splashKnockback ); } - else - { - WP_SaberRadiusDamage( ent, saberHitLocation, ent->client->ps.saber[saberNum].splashRadius2, ent->client->ps.saber[saberNum].splashDamage2, ent->client->ps.saber[saberNum].splashKnockback2 ); + // do radius damage/knockback, if any + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[saberNum], bladeNum)) { + WP_SaberRadiusDamage(ent, saberHitLocation, ent->client->ps.saber[saberNum].splashRadius, ent->client->ps.saber[saberNum].splashDamage, + ent->client->ps.saber[saberNum].splashKnockback); + } else { + WP_SaberRadiusDamage(ent, saberHitLocation, ent->client->ps.saber[saberNum].splashRadius2, ent->client->ps.saber[saberNum].splashDamage2, + ent->client->ps.saber[saberNum].splashKnockback2); } } } - if ( WP_SaberApplyDamage( ent, baseDamage, baseDFlags, brokenParry, saberNum, bladeNum, (qboolean)(saberNum==0&&ent->client->ps.saberInFlight) ) ) - {//actually did damage to something + if (WP_SaberApplyDamage(ent, baseDamage, baseDFlags, brokenParry, saberNum, bladeNum, + (qboolean)(saberNum == 0 && ent->client->ps.saberInFlight))) { // actually did damage to something #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( "base damage was %4.2f\n", baseDamage ); + if (d_saberCombat->integer) { + gi.Printf("base damage was %4.2f\n", baseDamage); } #endif - WP_SaberHitSound( ent, saberNum, bladeNum ); + WP_SaberHitSound(ent, saberNum, bladeNum); } - if ( hit_wall ) - { - //just so Jedi knows that he hit a wall + if (hit_wall) { + // just so Jedi knows that he hit a wall ent->client->ps.saberEventFlags |= SEF_HITWALL; - if ( ent->s.number == 0 ) - { - AddSoundEvent( ent, ent->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue );//FIXME: is this impact on ground or not? - AddSightEvent( ent, ent->currentOrigin, 256, AEL_DISCOVERED, 50 ); + if (ent->s.number == 0) { + AddSoundEvent(ent, ent->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue); // FIXME: is this impact on ground or not? + AddSightEvent(ent, ent->currentOrigin, 256, AEL_DISCOVERED, 50); } } } -void WP_SabersDamageTrace( gentity_t *ent, qboolean noEffects ) -{ - if ( !ent->client ) - { +void WP_SabersDamageTrace(gentity_t *ent, qboolean noEffects) { + if (!ent->client) { return; } - if ( PM_SuperBreakLoseAnim( ent->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(ent->client->ps.torsoAnim)) { return; } // Saber 1. g_saberNoEffects = noEffects; - for ( int i = 0; i < ent->client->ps.saber[0].numBlades; i++ ) - { + for (int i = 0; i < ent->client->ps.saber[0].numBlades; i++) { // If the Blade is not active and the length is 0, don't trace it, try the next blade... - if ( !ent->client->ps.saber[0].blade[i].active && ent->client->ps.saber[0].blade[i].length == 0 ) + if (!ent->client->ps.saber[0].blade[i].active && ent->client->ps.saber[0].blade[i].length == 0) continue; - if ( i != 0 ) - {//not first blade - if ( ent->client->ps.saber[0].type == SABER_BROAD || - ent->client->ps.saber[0].type == SABER_SAI || - ent->client->ps.saber[0].type == SABER_CLAW ) - { + if (i != 0) { // not first blade + if (ent->client->ps.saber[0].type == SABER_BROAD || ent->client->ps.saber[0].type == SABER_SAI || ent->client->ps.saber[0].type == SABER_CLAW) { g_saberNoEffects = qtrue; } } g_noClashFlare = qfalse; - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[0], i ) && (ent->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[0], i ) && (ent->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE2) ) ) - { + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[0], i) && (ent->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[0], i) && (ent->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE2))) { g_noClashFlare = qtrue; } - WP_SaberDamageTrace( ent, 0, i ); + WP_SaberDamageTrace(ent, 0, i); } // Saber 2. g_saberNoEffects = noEffects; - if ( ent->client->ps.dualSabers ) - { - for ( int i = 0; i < ent->client->ps.saber[1].numBlades; i++ ) - { + if (ent->client->ps.dualSabers) { + for (int i = 0; i < ent->client->ps.saber[1].numBlades; i++) { // If the Blade is not active and the length is 0, don't trace it, try the next blade... - if ( !ent->client->ps.saber[1].blade[i].active && ent->client->ps.saber[1].blade[i].length == 0 ) + if (!ent->client->ps.saber[1].blade[i].active && ent->client->ps.saber[1].blade[i].length == 0) continue; - if ( i != 0 ) - {//not first blade - if ( ent->client->ps.saber[1].type == SABER_BROAD || - ent->client->ps.saber[1].type == SABER_SAI || - ent->client->ps.saber[1].type == SABER_CLAW ) - { + if (i != 0) { // not first blade + if (ent->client->ps.saber[1].type == SABER_BROAD || ent->client->ps.saber[1].type == SABER_SAI || ent->client->ps.saber[1].type == SABER_CLAW) { g_saberNoEffects = qtrue; } } g_noClashFlare = qfalse; - if ( (!WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[1], i ) && (ent->client->ps.saber[1].saberFlags2&SFL2_NO_CLASH_FLARE) ) - || ( WP_SaberBladeUseSecondBladeStyle( &ent->client->ps.saber[1], i ) && (ent->client->ps.saber[1].saberFlags2&SFL2_NO_CLASH_FLARE2) ) ) - { + if ((!WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[1], i) && (ent->client->ps.saber[1].saberFlags2 & SFL2_NO_CLASH_FLARE)) || + (WP_SaberBladeUseSecondBladeStyle(&ent->client->ps.saber[1], i) && (ent->client->ps.saber[1].saberFlags2 & SFL2_NO_CLASH_FLARE2))) { g_noClashFlare = qtrue; } - WP_SaberDamageTrace( ent, 1, i ); + WP_SaberDamageTrace(ent, 1, i); } } g_saberNoEffects = qfalse; g_noClashFlare = qfalse; } -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ /* ================ @@ -5856,414 +4575,336 @@ WP_SaberImpact ================ */ -void WP_SaberImpact( gentity_t *owner, gentity_t *saber, trace_t *trace ) -{ - gentity_t *other; +void WP_SaberImpact(gentity_t *owner, gentity_t *saber, trace_t *trace) { + gentity_t *other; other = &g_entities[trace->entityNum]; - if ( other->takedamage && (other->svFlags&SVF_BBRUSH) ) - {//a breakable brush? break it! - if ( (other->spawnflags&1)//INVINCIBLE - ||(other->flags&FL_DMG_BY_HEAVY_WEAP_ONLY) )//HEAVY weapon damage only - {//can't actually break it - //no hit effect (besides regular client-side one) - } - else if ( other->NPC_targetname && - (!owner||!owner->targetname||Q_stricmp(owner->targetname,other->NPC_targetname)) ) - {//only breakable by an entity who is not the attacker - //no hit effect (besides regular client-side one) - } - else - { + if (other->takedamage && (other->svFlags & SVF_BBRUSH)) { // a breakable brush? break it! + if ((other->spawnflags & 1) // INVINCIBLE + || (other->flags & FL_DMG_BY_HEAVY_WEAP_ONLY)) // HEAVY weapon damage only + { // can't actually break it + // no hit effect (besides regular client-side one) + } else if (other->NPC_targetname && (!owner || !owner->targetname || + Q_stricmp(owner->targetname, other->NPC_targetname))) { // only breakable by an entity who is not the attacker + // no hit effect (besides regular client-side one) + } else { vec3_t dir; - VectorCopy( saber->s.pos.trDelta, dir ); - VectorNormalize( dir ); + VectorCopy(saber->s.pos.trDelta, dir); + VectorNormalize(dir); - int dmg = other->health*2; - if ( other->health > 50 && dmg > 20 && !(other->svFlags&SVF_GLASS_BRUSH) ) - { + int dmg = other->health * 2; + if (other->health > 50 && dmg > 20 && !(other->svFlags & SVF_GLASS_BRUSH)) { dmg = 20; } - G_Damage( other, saber, owner, dir, trace->endpos, dmg, 0, MOD_SABER ); - if ( owner - && owner->client - && owner->client->ps.saber[0].hitOtherEffect ) - { - G_PlayEffect( owner->client->ps.saber[0].hitOtherEffect, trace->endpos, dir ); - } - else - { - G_PlayEffect( "saber/saber_cut", trace->endpos, dir ); + G_Damage(other, saber, owner, dir, trace->endpos, dmg, 0, MOD_SABER); + if (owner && owner->client && owner->client->ps.saber[0].hitOtherEffect) { + G_PlayEffect(owner->client->ps.saber[0].hitOtherEffect, trace->endpos, dir); + } else { + G_PlayEffect("saber/saber_cut", trace->endpos, dir); } - if ( owner->s.number == 0 ) - { - AddSoundEvent( owner, trace->endpos, 256, AEL_DISCOVERED ); - AddSightEvent( owner, trace->endpos, 512, AEL_DISCOVERED, 50 ); + if (owner->s.number == 0) { + AddSoundEvent(owner, trace->endpos, 256, AEL_DISCOVERED); + AddSightEvent(owner, trace->endpos, 512, AEL_DISCOVERED, 50); } return; } } - if ( saber->s.pos.trType == TR_LINEAR ) - { - //hit a wall? send it back - WP_SaberReturn( saber->owner, saber ); - } - - if ( other && !other->client && (other->contents&CONTENTS_LIGHTSABER) )//&& other->s.weapon == WP_SABER ) - {//2 in-flight sabers collided! - //Big flash - //FIXME: bigger effect/sound? - //FIXME: STILL DOESNT WORK!!! - WP_SaberBlockSound( saber->owner, NULL, 0, 0 ); - //G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - WP_SaberBlockEffect( saber->owner, 0, 0, trace->endpos, NULL, qfalse); + if (saber->s.pos.trType == TR_LINEAR) { + // hit a wall? send it back + WP_SaberReturn(saber->owner, saber); + } + + if (other && !other->client && (other->contents & CONTENTS_LIGHTSABER)) //&& other->s.weapon == WP_SABER ) + { // 2 in-flight sabers collided! + // Big flash + // FIXME: bigger effect/sound? + // FIXME: STILL DOESNT WORK!!! + WP_SaberBlockSound(saber->owner, NULL, 0, 0); + // G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + WP_SaberBlockEffect(saber->owner, 0, 0, trace->endpos, NULL, qfalse); qboolean noFlare = qfalse; - if ( saber->owner - && saber->owner->client - && (saber->owner->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) ) - { + if (saber->owner && saber->owner->client && (saber->owner->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE)) { noFlare = qtrue; } - if ( !noFlare ) - { - g_saberFlashTime = level.time-50; - VectorCopy( trace->endpos, g_saberFlashPos ); + if (!noFlare) { + g_saberFlashTime = level.time - 50; + VectorCopy(trace->endpos, g_saberFlashPos); } } - if ( owner && owner->s.number == 0 && owner->client ) - { - //Add the event - if ( owner->client->ps.SaberLength() > 0 ) - {//saber is on, very suspicious - if ( (!owner->client->ps.saberInFlight && owner->client->ps.groundEntityNum == ENTITYNUM_WORLD)//holding saber and on ground - || saber->s.pos.trType == TR_STATIONARY )//saber out there somewhere and on ground - {//an on-ground alert - AddSoundEvent( owner, saber->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue ); - } - else - {//an in-air alert - AddSoundEvent( owner, saber->currentOrigin, 128, AEL_DISCOVERED ); + if (owner && owner->s.number == 0 && owner->client) { + // Add the event + if (owner->client->ps.SaberLength() > 0) { // saber is on, very suspicious + if ((!owner->client->ps.saberInFlight && owner->client->ps.groundEntityNum == ENTITYNUM_WORLD) // holding saber and on ground + || saber->s.pos.trType == TR_STATIONARY) // saber out there somewhere and on ground + { // an on-ground alert + AddSoundEvent(owner, saber->currentOrigin, 128, AEL_DISCOVERED, qfalse, qtrue); + } else { // an in-air alert + AddSoundEvent(owner, saber->currentOrigin, 128, AEL_DISCOVERED); } - AddSightEvent( owner, saber->currentOrigin, 256, AEL_DISCOVERED, 50 ); - } - else - {//saber is off, not as suspicious - AddSoundEvent( owner, saber->currentOrigin, 128, AEL_SUSPICIOUS ); - AddSightEvent( owner, saber->currentOrigin, 256, AEL_SUSPICIOUS ); + AddSightEvent(owner, saber->currentOrigin, 256, AEL_DISCOVERED, 50); + } else { // saber is off, not as suspicious + AddSoundEvent(owner, saber->currentOrigin, 128, AEL_SUSPICIOUS); + AddSightEvent(owner, saber->currentOrigin, 256, AEL_SUSPICIOUS); } } // check for bounce - if ( !other->takedamage && ( saber->s.eFlags & ( EF_BOUNCE | EF_BOUNCE_HALF ) ) ) - { + if (!other->takedamage && (saber->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF))) { // Check to see if there is a bounce count - if ( saber->bounceCount ) { + if (saber->bounceCount) { // decrement number of bounces and then see if it should be done bouncing - if ( --saber->bounceCount <= 0 ) { + if (--saber->bounceCount <= 0) { // He (or she) will bounce no more (after this current bounce, that is). - saber->s.eFlags &= ~( EF_BOUNCE | EF_BOUNCE_HALF ); - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - { - WP_SaberDrop( saber->owner, saber ); + saber->s.eFlags &= ~(EF_BOUNCE | EF_BOUNCE_HALF); + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING) { + WP_SaberDrop(saber->owner, saber); } return; - } - else - {//bounced and still have bounces left - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - {//under telekinetic control - if ( !gi.inPVS( saber->currentOrigin, owner->client->renderInfo.handRPoint ) ) - {//not in the PVS of my master + } else { // bounced and still have bounces left + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && + owner->client->ps.saberEntityState == SES_RETURNING) { // under telekinetic control + if (!gi.inPVS(saber->currentOrigin, owner->client->renderInfo.handRPoint)) { // not in the PVS of my master saber->bounceCount -= 25; } } } } - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - { - //don't home for a few frames so we can get around this thing - trace_t bounceTr; - vec3_t end; - float owner_dist = Distance( owner->client->renderInfo.handRPoint, saber->currentOrigin ); - - VectorMA( saber->currentOrigin, 10, trace->plane.normal, end ); - gi.trace( &bounceTr, saber->currentOrigin, saber->mins, saber->maxs, end, owner->s.number, saber->clipmask, (EG2_Collision)0, 0 ); - VectorCopy( bounceTr.endpos, saber->currentOrigin ); - if ( owner_dist > 0 ) - { - if ( owner_dist > 50 ) - { - owner->client->ps.saberEntityDist = owner_dist-50; - } - else - { + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING) { + // don't home for a few frames so we can get around this thing + trace_t bounceTr; + vec3_t end; + float owner_dist = Distance(owner->client->renderInfo.handRPoint, saber->currentOrigin); + + VectorMA(saber->currentOrigin, 10, trace->plane.normal, end); + gi.trace(&bounceTr, saber->currentOrigin, saber->mins, saber->maxs, end, owner->s.number, saber->clipmask, (EG2_Collision)0, 0); + VectorCopy(bounceTr.endpos, saber->currentOrigin); + if (owner_dist > 0) { + if (owner_dist > 50) { + owner->client->ps.saberEntityDist = owner_dist - 50; + } else { owner->client->ps.saberEntityDist = 0; } } return; } - G_BounceMissile( saber, trace ); + G_BounceMissile(saber, trace); - if ( saber->s.pos.trType == TR_GRAVITY ) - {//bounced - //play a bounce sound - WP_SaberFallSound( owner, saber ); - //change rotation - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); + if (saber->s.pos.trType == TR_GRAVITY) { // bounced + // play a bounce sound + WP_SaberFallSound(owner, saber); + // change rotation + VectorCopy(saber->currentAngles, saber->s.apos.trBase); saber->s.apos.trType = TR_LINEAR; saber->s.apos.trTime = level.time; - VectorSet( saber->s.apos.trDelta, Q_irand( -300, 300 ), Q_irand( -300, 300 ), Q_irand( -300, 300 ) ); - } - //see if we stopped - else if ( saber->s.pos.trType == TR_STATIONARY ) - {//stopped - //play a bounce sound - WP_SaberFallSound( owner, saber ); - //stop rotation - VectorClear( saber->s.apos.trDelta ); - pitch_roll_for_slope( saber, trace->plane.normal, saber->currentAngles ); + VectorSet(saber->s.apos.trDelta, Q_irand(-300, 300), Q_irand(-300, 300), Q_irand(-300, 300)); + } + // see if we stopped + else if (saber->s.pos.trType == TR_STATIONARY) { // stopped + // play a bounce sound + WP_SaberFallSound(owner, saber); + // stop rotation + VectorClear(saber->s.apos.trDelta); + pitch_roll_for_slope(saber, trace->plane.normal, saber->currentAngles); saber->currentAngles[0] += SABER_PITCH_HACK; - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); - //remember when it fell so it can return automagically + VectorCopy(saber->currentAngles, saber->s.apos.trBase); + // remember when it fell so it can return automagically saber->aimDebounceTime = level.time; } - } - else if ( other->client && other->health > 0 - && ( (other->NPC && (other->NPC->aiFlags&NPCAI_BOSS_CHARACTER)) - //|| other->client->NPC_class == CLASS_ALORA - || other->client->NPC_class == CLASS_BOBAFETT - || ( other->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) ) ) - {//Luke, Desann and Tavion slap thrown sabers aside - WP_SaberDrop( owner, saber ); - WP_SaberBlockSound( owner, other, 0, 0 ); - //G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - WP_SaberBlockEffect( owner, 0, 0, trace->endpos, NULL, qfalse ); + } else if (other->client && other->health > 0 && + ((other->NPC && (other->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) + //|| other->client->NPC_class == CLASS_ALORA + || other->client->NPC_class == CLASS_BOBAFETT || + (other->client->ps.powerups[PW_GALAK_SHIELD] > 0))) { // Luke, Desann and Tavion slap thrown sabers aside + WP_SaberDrop(owner, saber); + WP_SaberBlockSound(owner, other, 0, 0); + // G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + WP_SaberBlockEffect(owner, 0, 0, trace->endpos, NULL, qfalse); qboolean noFlare = qfalse; - if ( owner - && owner->client - && (owner->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) ) - { + if (owner && owner->client && (owner->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE)) { noFlare = qtrue; } - if ( !noFlare ) - { - g_saberFlashTime = level.time-50; - VectorCopy( trace->endpos, g_saberFlashPos ); + if (!noFlare) { + g_saberFlashTime = level.time - 50; + VectorCopy(trace->endpos, g_saberFlashPos); } - //FIXME: make Luke/Desann/Tavion play an attack anim or some other special anim when this happens - Jedi_PlayDeflectSound( other ); + // FIXME: make Luke/Desann/Tavion play an attack anim or some other special anim when this happens + Jedi_PlayDeflectSound(other); } } -extern float G_PointDistFromLineSegment( const vec3_t start, const vec3_t end, const vec3_t from ); -void WP_SaberInFlightReflectCheck( gentity_t *self, usercmd_t *ucmd ) -{ - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *missile_list[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - int i, e, numSabers; - int ent_count = 0; - int radius = 180; - vec3_t center; - vec3_t tip; - vec3_t up = {0,0,1}; - qboolean willHit = qfalse; - - if ( self->NPC && (self->NPC->scriptFlags&SCF_IGNORE_ALERTS) ) - {//don't react to things flying at me... - return; - } - //sanity checks: make sure we actually have a saberent - if ( self->client->ps.weapon != WP_SABER ) - { +extern float G_PointDistFromLineSegment(const vec3_t start, const vec3_t end, const vec3_t from); +void WP_SaberInFlightReflectCheck(gentity_t *self, usercmd_t *ucmd) { + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *missile_list[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + int i, e, numSabers; + int ent_count = 0; + int radius = 180; + vec3_t center; + vec3_t tip; + vec3_t up = {0, 0, 1}; + qboolean willHit = qfalse; + + if (self->NPC && (self->NPC->scriptFlags & SCF_IGNORE_ALERTS)) { // don't react to things flying at me... return; } - if ( !self->client->ps.saberInFlight ) - { + // sanity checks: make sure we actually have a saberent + if (self->client->ps.weapon != WP_SABER) { return; } - if ( !self->client->ps.SaberLength() ) - { + if (!self->client->ps.saberInFlight) { return; } - if ( self->client->ps.saberEntityNum == ENTITYNUM_NONE ) - { + if (!self->client->ps.SaberLength()) { + return; + } + if (self->client->ps.saberEntityNum == ENTITYNUM_NONE) { return; } gentity_t *saberent = &g_entities[self->client->ps.saberEntityNum]; - if ( !saberent ) - { + if (!saberent) { return; } - //okay, enough damn sanity checks + // okay, enough damn sanity checks - VectorCopy( saberent->currentOrigin, center ); + VectorCopy(saberent->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - //FIXME: check visibility? - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + // FIXME: check visibility? + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType != ET_MISSILE ) - { - if ( ent->client || ent->s.weapon != WP_SABER ) - {//FIXME: wake up bad guys? + if (ent->s.eType != ET_MISSILE) { + if (ent->client || ent->s.weapon != WP_SABER) { // FIXME: wake up bad guys? continue; } - if ( ent->s.eFlags & EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber continue; } - } - else - {//FIXME: make exploding missiles explode? - if ( ent->s.pos.trType == TR_STATIONARY ) - {//nothing you can do with a stationary missile + } else { // FIXME: make exploding missiles explode? + if (ent->s.pos.trType == TR_STATIONARY) { // nothing you can do with a stationary missile continue; } - if ( ent->splashDamage || ent->splashRadius ) - {//can't deflect exploding missiles - if ( DistanceSquared( ent->currentOrigin, center ) < 256 )//16 squared + if (ent->splashDamage || ent->splashRadius) { // can't deflect exploding missiles + if (DistanceSquared(ent->currentOrigin, center) < 256) // 16 squared { - G_MissileImpacted( ent, saberent, ent->currentOrigin, up ); + G_MissileImpacted(ent, saberent, ent->currentOrigin, up); } continue; } } - //don't deflect it if it's not within 16 units of the blade - //do this for all blades + // don't deflect it if it's not within 16 units of the blade + // do this for all blades willHit = qfalse; numSabers = 1; - if ( self->client->ps.dualSabers ) - { + if (self->client->ps.dualSabers) { numSabers = 2; } - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - for ( int bladeNum = 0; bladeNum < self->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - VectorMA( self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, self->client->ps.saber[saberNum].blade[bladeNum].length, self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, tip ); + for (int saberNum = 0; saberNum < numSabers; saberNum++) { + for (int bladeNum = 0; bladeNum < self->client->ps.saber[saberNum].numBlades; bladeNum++) { + VectorMA(self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, self->client->ps.saber[saberNum].blade[bladeNum].length, + self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, tip); - if( G_PointDistFromLineSegment( self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, tip, ent->currentOrigin ) <= 32 ) - { + if (G_PointDistFromLineSegment(self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, tip, ent->currentOrigin) <= 32) { willHit = qtrue; break; } } - if ( willHit ) - { + if (willHit) { break; } } - if ( !willHit ) - { + if (!willHit) { continue; } // ok, we are within the radius, add us to the incoming list missile_list[ent_count] = ent; ent_count++; - } - if ( ent_count ) - { - vec3_t fx_dir; + if (ent_count) { + vec3_t fx_dir; // we are done, do we have any to deflect? - if ( ent_count ) - { - for ( int x = 0; x < ent_count; x++ ) - { - if ( missile_list[x]->s.weapon == WP_SABER ) - {//just send it back - if ( missile_list[x]->owner && missile_list[x]->owner->client && missile_list[x]->owner->client->ps.saber[0].Active() && missile_list[x]->s.pos.trType == TR_LINEAR && missile_list[x]->owner->client->ps.saberEntityState != SES_RETURNING ) - {//it's on and being controlled - //FIXME: prevent it from damaging me? - WP_SaberReturn( missile_list[x]->owner, missile_list[x] ); - VectorNormalize2( missile_list[x]->s.pos.trDelta, fx_dir ); - WP_SaberBlockEffect( self, 0, 0, missile_list[x]->currentOrigin, fx_dir, qfalse ); - if ( missile_list[x]->owner->client->ps.saberInFlight && self->client->ps.saberInFlight ) - { - WP_SaberBlockSound( self, missile_list[x]->owner, 0, 0 ); - //G_Sound( missile_list[x], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + if (ent_count) { + for (int x = 0; x < ent_count; x++) { + if (missile_list[x]->s.weapon == WP_SABER) { // just send it back + if (missile_list[x]->owner && missile_list[x]->owner->client && missile_list[x]->owner->client->ps.saber[0].Active() && + missile_list[x]->s.pos.trType == TR_LINEAR && + missile_list[x]->owner->client->ps.saberEntityState != SES_RETURNING) { // it's on and being controlled + // FIXME: prevent it from damaging me? + WP_SaberReturn(missile_list[x]->owner, missile_list[x]); + VectorNormalize2(missile_list[x]->s.pos.trDelta, fx_dir); + WP_SaberBlockEffect(self, 0, 0, missile_list[x]->currentOrigin, fx_dir, qfalse); + if (missile_list[x]->owner->client->ps.saberInFlight && self->client->ps.saberInFlight) { + WP_SaberBlockSound(self, missile_list[x]->owner, 0, 0); + // G_Sound( missile_list[x], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); qboolean noFlare = qfalse; - if ( (missile_list[x]->owner->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) - && (self->client->ps.saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) ) - { + if ((missile_list[x]->owner->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE) && + (self->client->ps.saber[0].saberFlags2 & SFL2_NO_CLASH_FLARE)) { noFlare = qtrue; } - if ( !noFlare ) - { - g_saberFlashTime = level.time-50; + if (!noFlare) { + g_saberFlashTime = level.time - 50; gentity_t *saber = &g_entities[self->client->ps.saberEntityNum]; - vec3_t org; - VectorSubtract( missile_list[x]->currentOrigin, saber->currentOrigin, org ); - VectorMA( saber->currentOrigin, 0.5, org, org ); - VectorCopy( org, g_saberFlashPos ); + vec3_t org; + VectorSubtract(missile_list[x]->currentOrigin, saber->currentOrigin, org); + VectorMA(saber->currentOrigin, 0.5, org, org); + VectorCopy(org, g_saberFlashPos); } } } - } - else - {//bounce it - vec3_t reflectAngle, forward; - if ( self->client && !self->s.number ) - { + } else { // bounce it + vec3_t reflectAngle, forward; + if (self->client && !self->s.number) { self->client->sess.missionStats.saberBlocksCnt++; } - VectorCopy( saberent->s.apos.trBase, reflectAngle ); - reflectAngle[PITCH] = Q_flrand( -90, 90 ); - AngleVectors( reflectAngle, forward, NULL, NULL ); + VectorCopy(saberent->s.apos.trBase, reflectAngle); + reflectAngle[PITCH] = Q_flrand(-90, 90); + AngleVectors(reflectAngle, forward, NULL, NULL); - G_ReflectMissile( self, missile_list[x], forward ); - //do an effect - VectorNormalize2( missile_list[x]->s.pos.trDelta, fx_dir ); - G_PlayEffect( "blaster/deflect", missile_list[x]->currentOrigin, fx_dir ); + G_ReflectMissile(self, missile_list[x], forward); + // do an effect + VectorNormalize2(missile_list[x]->s.pos.trDelta, fx_dir); + G_PlayEffect("blaster/deflect", missile_list[x]->currentOrigin, fx_dir); } } } } } -qboolean WP_SaberValidateEnemy( gentity_t *self, gentity_t *enemy ) -{ - if ( !enemy ) - { +qboolean WP_SaberValidateEnemy(gentity_t *self, gentity_t *enemy) { + if (!enemy) { return qfalse; } - if ( !enemy || enemy == self || !enemy->inuse || !enemy->client ) - {//not valid + if (!enemy || enemy == self || !enemy->inuse || !enemy->client) { // not valid return qfalse; } - if ( enemy->health <= 0 ) - {//corpse + if (enemy->health <= 0) { // corpse return qfalse; } @@ -6274,93 +4915,81 @@ qboolean WP_SaberValidateEnemy( gentity_t *self, gentity_t *enemy ) return qfalse; } */ - if ( enemy->s.number >= MAX_CLIENTS ) - {//NPCs can cheat and use the homing saber throw 3 on the player - if ( enemy->client->ps.forcePowersKnown ) - {//not other jedi? + if (enemy->s.number >= MAX_CLIENTS) { // NPCs can cheat and use the homing saber throw 3 on the player + if (enemy->client->ps.forcePowersKnown) { // not other jedi? return qfalse; } } - if ( DistanceSquared( self->client->renderInfo.handRPoint, enemy->currentOrigin ) > saberThrowDistSquared[self->client->ps.forcePowerLevel[FP_SABERTHROW]] ) - {//too far + if (DistanceSquared(self->client->renderInfo.handRPoint, enemy->currentOrigin) > + saberThrowDistSquared[self->client->ps.forcePowerLevel[FP_SABERTHROW]]) { // too far return qfalse; } - if ( (!InFront( enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || !G_ClearLOS( self, self->client->renderInfo.eyePoint, enemy ) ) - && ( DistanceHorizontalSquared( enemy->currentOrigin, self->currentOrigin ) > 65536 || fabs(enemy->currentOrigin[2]-self->currentOrigin[2]) > 384 ) ) - {//(not in front or not clear LOS) & greater than 256 away + if ((!InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || + !G_ClearLOS(self, self->client->renderInfo.eyePoint, enemy)) && + (DistanceHorizontalSquared(enemy->currentOrigin, self->currentOrigin) > 65536 || + fabs(enemy->currentOrigin[2] - self->currentOrigin[2]) > 384)) { //(not in front or not clear LOS) & greater than 256 away return qfalse; } - if ( enemy->client->playerTeam == self->client->playerTeam ) - {//on same team + if (enemy->client->playerTeam == self->client->playerTeam) { // on same team return qfalse; } - //LOS? + // LOS? return qtrue; } -float WP_SaberRateEnemy( gentity_t *enemy, vec3_t center, vec3_t forward, float radius ) -{ +float WP_SaberRateEnemy(gentity_t *enemy, vec3_t center, vec3_t forward, float radius) { float rating; - vec3_t dir; + vec3_t dir; - VectorSubtract( enemy->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir ); + VectorSubtract(enemy->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir); return rating; } -gentity_t *WP_SaberFindEnemy( gentity_t *self, gentity_t *saber ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent, *bestEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward; - int i, e; - float radius = 400; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? +gentity_t *WP_SaberFindEnemy(gentity_t *self, gentity_t *saber) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent, *bestEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward; + int i, e; + float radius = 400; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( saber->currentOrigin, center ); + VectorCopy(saber->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - //if the saber has an enemy from the last time it looked, init to that one - if ( WP_SaberValidateEnemy( self, saber->enemy ) ) - { - if ( gi.inPVS( self->currentOrigin, saber->enemy->currentOrigin ) ) - {//potentially visible - if ( G_ClearLOS( self, self->client->renderInfo.eyePoint, saber->enemy ) ) - {//can see him + // if the saber has an enemy from the last time it looked, init to that one + if (WP_SaberValidateEnemy(self, saber->enemy)) { + if (gi.inPVS(self->currentOrigin, saber->enemy->currentOrigin)) { // potentially visible + if (G_ClearLOS(self, self->client->renderInfo.eyePoint, saber->enemy)) { // can see him bestEnt = saber->enemy; - bestRating = WP_SaberRateEnemy( bestEnt, center, forward, radius ); + bestRating = WP_SaberRateEnemy(bestEnt, center, forward, radius); } } } - //If I have an enemy, see if that's even better - if ( WP_SaberValidateEnemy( self, self->enemy ) ) - { - float myEnemyRating = WP_SaberRateEnemy( self->enemy, center, forward, radius ); - if ( myEnemyRating > bestRating ) - { - if ( gi.inPVS( self->currentOrigin, self->enemy->currentOrigin ) ) - {//potentially visible - if ( G_ClearLOS( self, self->client->renderInfo.eyePoint, self->enemy ) ) - {//can see him + // If I have an enemy, see if that's even better + if (WP_SaberValidateEnemy(self, self->enemy)) { + float myEnemyRating = WP_SaberRateEnemy(self->enemy, center, forward, radius); + if (myEnemyRating > bestRating) { + if (gi.inPVS(self->currentOrigin, self->enemy->currentOrigin)) { // potentially visible + if (G_ClearLOS(self, self->client->renderInfo.eyePoint, self->enemy)) { // can see him bestEnt = self->enemy; bestRating = myEnemyRating; } @@ -6368,37 +4997,31 @@ gentity_t *WP_SaberFindEnemy( gentity_t *self, gentity_t *saber ) } } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - if ( !numListedEntities ) - {//should we clear the enemy? + if (!numListedEntities) { // should we clear the enemy? return bestEnt; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( ent == self || ent == saber || ent == bestEnt ) - { + if (ent == self || ent == saber || ent == bestEnt) { continue; } - if ( !WP_SaberValidateEnemy( self, ent ) ) - {//doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call + if (!WP_SaberValidateEnemy( + self, ent)) { // doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call continue; } - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - //rate him based on how close & how in front he is - rating = WP_SaberRateEnemy( ent, center, forward, radius ); - if ( rating > bestRating ) - { + // rate him based on how close & how in front he is + rating = WP_SaberRateEnemy(ent, center, forward, radius); + if (rating > bestRating) { bestEnt = ent; bestRating = rating; } @@ -6406,131 +5029,102 @@ gentity_t *WP_SaberFindEnemy( gentity_t *self, gentity_t *saber ) return bestEnt; } -void WP_RunSaber( gentity_t *self, gentity_t *saber ) -{ - vec3_t origin, oldOrg; - trace_t tr; +void WP_RunSaber(gentity_t *self, gentity_t *saber) { + vec3_t origin, oldOrg; + trace_t tr; - VectorCopy( saber->currentOrigin, oldOrg ); + VectorCopy(saber->currentOrigin, oldOrg); // get current position - EvaluateTrajectory( &saber->s.pos, level.time, origin ); + EvaluateTrajectory(&saber->s.pos, level.time, origin); // get current angles - EvaluateTrajectory( &saber->s.apos, level.time, saber->currentAngles ); + EvaluateTrajectory(&saber->s.apos, level.time, saber->currentAngles); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner int clipmask = saber->clipmask; - if ( !self || !self->client || self->client->ps.SaberLength() <= 0 ) - {//don't keep hitting other sabers when turned off + if (!self || !self->client || self->client->ps.SaberLength() <= 0) { // don't keep hitting other sabers when turned off clipmask &= ~CONTENTS_LIGHTSABER; } - gi.trace( &tr, saber->currentOrigin, saber->mins, saber->maxs, origin, - saber->owner ? saber->owner->s.number : ENTITYNUM_NONE, clipmask, (EG2_Collision)0, 0 ); + gi.trace(&tr, saber->currentOrigin, saber->mins, saber->maxs, origin, saber->owner ? saber->owner->s.number : ENTITYNUM_NONE, clipmask, (EG2_Collision)0, + 0); - VectorCopy( tr.endpos, saber->currentOrigin ); + VectorCopy(tr.endpos, saber->currentOrigin); - if ( self->client->ps.SaberActive() ) - { - if ( self->client->ps.saberInFlight || (self->client->ps.weaponTime&&!Q_irand( 0, 100 )) ) - {//make enemies run from a lit saber in flight or from me when I'm attacking - if ( !Q_irand( 0, 10 ) ) - {//not so often... - AddSightEvent( self, saber->currentOrigin, self->client->ps.SaberLength()*3, AEL_DANGER, 100 ); + if (self->client->ps.SaberActive()) { + if (self->client->ps.saberInFlight || + (self->client->ps.weaponTime && !Q_irand(0, 100))) { // make enemies run from a lit saber in flight or from me when I'm attacking + if (!Q_irand(0, 10)) { // not so often... + AddSightEvent(self, saber->currentOrigin, self->client->ps.SaberLength() * 3, AEL_DANGER, 100); } } } - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( saber ); + gi.linkentity(saber); - //touch push triggers? + // touch push triggers? - if ( tr.fraction != 1 ) - { - WP_SaberImpact( self, saber, &tr ); + if (tr.fraction != 1) { + WP_SaberImpact(self, saber, &tr); } - if ( saber->s.pos.trType == TR_LINEAR ) - {//home - //figure out where saber should be - vec3_t forward, saberHome, saberDest, fwdangles = {0}; + if (saber->s.pos.trType == TR_LINEAR) { // home + // figure out where saber should be + vec3_t forward, saberHome, saberDest, fwdangles = {0}; - VectorCopy( self->client->ps.viewangles, fwdangles ); - if ( self->s.number ) - { + VectorCopy(self->client->ps.viewangles, fwdangles); + if (self->s.number) { fwdangles[0] -= 8; - } - else if ( cg.renderingThirdPerson ) - { + } else if (cg.renderingThirdPerson) { fwdangles[0] -= 5; } - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 - || self->client->ps.saberEntityState == SES_RETURNING - || VectorCompare( saber->s.pos.trDelta, vec3_origin ) ) - {//control if it's returning or just starting - float saberSpeed = 500;//FIXME: based on force level? - float dist; + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 || self->client->ps.saberEntityState == SES_RETURNING || + VectorCompare(saber->s.pos.trDelta, vec3_origin)) { // control if it's returning or just starting + float saberSpeed = 500; // FIXME: based on force level? + float dist; gentity_t *enemy = NULL; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - if ( self->client->ps.saberEntityDist < 100 ) - {//make the saber head to my hand- the bolt it was attached to - VectorCopy( self->client->renderInfo.handRPoint, saberHome ); + if (self->client->ps.saberEntityDist < 100) { // make the saber head to my hand- the bolt it was attached to + VectorCopy(self->client->renderInfo.handRPoint, saberHome); + } else { // aim saber from eyes + VectorCopy(self->client->renderInfo.eyePoint, saberHome); } - else - {//aim saber from eyes - VectorCopy( self->client->renderInfo.eyePoint, saberHome ); - } - VectorMA( saberHome, self->client->ps.saberEntityDist, forward, saberDest ); + VectorMA(saberHome, self->client->ps.saberEntityDist, forward, saberDest); - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 - && self->client->ps.saberEntityState == SES_LEAVING ) - {//max level - if ( self->enemy && - !WP_SaberValidateEnemy( self, self->enemy ) ) - {//if my enemy isn't valid to auto-aim at, don't autoaim - } - else - { - //pick an enemy - enemy = WP_SaberFindEnemy( self, saber ); - if ( enemy ) - {//home in on enemy - float enemyDist = Distance( self->client->renderInfo.handRPoint, enemy->currentOrigin ); - VectorCopy( enemy->currentOrigin, saberDest ); - saberDest[2] += enemy->maxs[2]/2.0f;//FIXME: when in a knockdown anim, the saber float above them... do we care? + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING) { // max level + if (self->enemy && !WP_SaberValidateEnemy(self, self->enemy)) { // if my enemy isn't valid to auto-aim at, don't autoaim + } else { + // pick an enemy + enemy = WP_SaberFindEnemy(self, saber); + if (enemy) { // home in on enemy + float enemyDist = Distance(self->client->renderInfo.handRPoint, enemy->currentOrigin); + VectorCopy(enemy->currentOrigin, saberDest); + saberDest[2] += enemy->maxs[2] / 2.0f; // FIXME: when in a knockdown anim, the saber float above them... do we care? self->client->ps.saberEntityDist = enemyDist; - //once you pick an enemy, stay with it! + // once you pick an enemy, stay with it! saber->enemy = enemy; - //FIXME: lock onto that enemy for a minimum amount of time (unless they become invalid?) + // FIXME: lock onto that enemy for a minimum amount of time (unless they become invalid?) } } } - - //Make the saber head there - VectorSubtract( saberDest, saber->currentOrigin, saber->s.pos.trDelta ); - dist = VectorNormalize( saber->s.pos.trDelta ); - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING && !enemy ) - { - if ( dist < 200 ) - { - saberSpeed = 400 - (dist*2); + // Make the saber head there + VectorSubtract(saberDest, saber->currentOrigin, saber->s.pos.trDelta); + dist = VectorNormalize(saber->s.pos.trDelta); + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING && !enemy) { + if (dist < 200) { + saberSpeed = 400 - (dist * 2); } - } - else if ( self->client->ps.saberEntityState == SES_LEAVING && dist < 50 ) - { + } else if (self->client->ps.saberEntityState == SES_LEAVING && dist < 50) { saberSpeed = dist * 2 + 30; - if ( (enemy && dist > enemy->maxs[0]) || (!enemy && dist > 24) ) - {//auto-tracking an enemy and we can't hit him - if ( saberSpeed < 120 ) - {//clamp to a minimum speed + if ((enemy && dist > enemy->maxs[0]) || (!enemy && dist > 24)) { // auto-tracking an enemy and we can't hit him + if (saberSpeed < 120) { // clamp to a minimum speed saberSpeed = 120; } } @@ -6545,129 +5139,106 @@ void WP_RunSaber( gentity_t *self, gentity_t *saber ) } } */ - VectorScale( saber->s.pos.trDelta, saberSpeed, saber->s.pos.trDelta ); - //SnapVector( saber->s.pos.trDelta ); // save net bandwidth - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + VectorScale(saber->s.pos.trDelta, saberSpeed, saber->s.pos.trDelta); + // SnapVector( saber->s.pos.trDelta ); // save net bandwidth + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; - } - else - { - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + } else { + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; } - //if it's heading back, point it's base at us - if ( self->client->ps.saberEntityState == SES_RETURNING - && !(self->client->ps.saber[0].saberFlags&SFL_RETURN_DAMAGE) )//type != SABER_STAR ) + // if it's heading back, point it's base at us + if (self->client->ps.saberEntityState == SES_RETURNING && !(self->client->ps.saber[0].saberFlags & SFL_RETURN_DAMAGE)) // type != SABER_STAR ) { fwdangles[0] += SABER_PITCH_HACK; - VectorCopy( fwdangles, saber->s.apos.trBase ); + VectorCopy(fwdangles, saber->s.apos.trBase); saber->s.apos.trTime = level.time; saber->s.apos.trType = TR_INTERPOLATE; - VectorClear( saber->s.apos.trDelta ); + VectorClear(saber->s.apos.trDelta); } } } +qboolean WP_SaberLaunch(gentity_t *self, gentity_t *saber, qboolean thrown, qboolean noFail = qfalse) { // FIXME: probably need a debounce time + vec3_t saberMins = {-3.0f, -3.0f, -3.0f}; + vec3_t saberMaxs = {3.0f, 3.0f, 3.0f}; + trace_t trace; -qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown, qboolean noFail = qfalse ) -{//FIXME: probably need a debounce time - vec3_t saberMins={-3.0f,-3.0f,-3.0f}; - vec3_t saberMaxs={3.0f,3.0f,3.0f}; - trace_t trace; - - if ( self->client->NPC_class == CLASS_SABER_DROID ) - {//saber droids can't drop their saber + if (self->client->NPC_class == CLASS_SABER_DROID) { // saber droids can't drop their saber return qfalse; } - if ( !noFail ) - { - if ( thrown ) - {//this is a regular throw, so see if it's legal - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - { - if ( !WP_ForcePowerUsable( self, FP_SABERTHROW, 20 ) ) - { + if (!noFail) { + if (thrown) { // this is a regular throw, so see if it's legal + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { + if (!WP_ForcePowerUsable(self, FP_SABERTHROW, 20)) { return qfalse; } - } - else - { - if ( !WP_ForcePowerUsable( self, FP_SABERTHROW, 0 ) ) - { + } else { + if (!WP_ForcePowerUsable(self, FP_SABERTHROW, 0)) { return qfalse; } } } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't saber throw when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't saber throw when zoomed in or in cinematic return qfalse; } - //make sure it won't start in solid - gi.trace( &trace, self->client->renderInfo.handRPoint, saberMins, saberMaxs, self->client->renderInfo.handRPoint, saber->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); - if ( trace.startsolid || trace.allsolid ) - { + // make sure it won't start in solid + gi.trace(&trace, self->client->renderInfo.handRPoint, saberMins, saberMaxs, self->client->renderInfo.handRPoint, saber->s.number, MASK_SOLID, + (EG2_Collision)0, 0); + if (trace.startsolid || trace.allsolid) { return qfalse; } - //make sure I'm not throwing it on the other side of a door or wall or whatever - gi.trace( &trace, self->currentOrigin, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); - if ( trace.startsolid || trace.allsolid || trace.fraction < 1.0f ) - { + // make sure I'm not throwing it on the other side of a door or wall or whatever + gi.trace(&trace, self->currentOrigin, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, (EG2_Collision)0, 0); + if (trace.startsolid || trace.allsolid || trace.fraction < 1.0f) { return qfalse; } - if ( thrown ) - {//this is a regular throw, so take force power - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - {//at max skill, the cost increases as keep it out - WP_ForcePowerStart( self, FP_SABERTHROW, 10 ); - } - else - { - WP_ForcePowerStart( self, FP_SABERTHROW, 0 ); + if (thrown) { // this is a regular throw, so take force power + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { // at max skill, the cost increases as keep it out + WP_ForcePowerStart(self, FP_SABERTHROW, 10); + } else { + WP_ForcePowerStart(self, FP_SABERTHROW, 0); } } } - //clear the enemy + // clear the enemy saber->enemy = NULL; -//===FIXME!!!============================================================================================== - //We should copy the right-hand saber's g2 instance to the thrown saber - //Then back again when you catch it!!! -//===FIXME!!!============================================================================================== + //===FIXME!!!============================================================================================== + // We should copy the right-hand saber's g2 instance to the thrown saber + // Then back again when you catch it!!! + //===FIXME!!!============================================================================================== - //draw it + // draw it saber->s.eFlags &= ~EF_NODRAW; saber->svFlags |= SVF_BROADCAST; saber->svFlags &= ~SVF_NOCLIENT; - //place it - VectorCopy( self->client->renderInfo.handRPoint, saber->currentOrigin );//muzzlePoint - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + // place it + VectorCopy(self->client->renderInfo.handRPoint, saber->currentOrigin); // muzzlePoint + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; - VectorClear( saber->s.pos.trDelta ); - gi.linkentity( saber ); + VectorClear(saber->s.pos.trDelta); + gi.linkentity(saber); - //spin it - VectorClear( saber->s.apos.trBase ); + // spin it + VectorClear(saber->s.apos.trBase); saber->s.apos.trTime = level.time; saber->s.apos.trType = TR_LINEAR; - if ( self->health > 0 && thrown ) - {//throwing it + if (self->health > 0 && thrown) { // throwing it saber->s.apos.trBase[1] = self->client->ps.viewangles[1]; saber->s.apos.trBase[0] = SABER_PITCH_HACK; + } else { // dropping it + vectoangles(self->client->renderInfo.muzzleDir, saber->s.apos.trBase); } - else - {//dropping it - vectoangles( self->client->renderInfo.muzzleDir, saber->s.apos.trBase ); - } - VectorClear( saber->s.apos.trDelta ); + VectorClear(saber->s.apos.trDelta); - switch ( self->client->ps.forcePowerLevel[FP_SABERTHROW] ) - {//FIXME: make a table? + switch (self->client->ps.forcePowerLevel[FP_SABERTHROW]) { // FIXME: make a table? default: case FORCE_LEVEL_1: saber->s.apos.trDelta[1] = 600; @@ -6680,51 +5251,44 @@ qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown, qbo break; } - //Take it out of my hand + // Take it out of my hand self->client->ps.saberInFlight = qtrue; self->client->ps.saberEntityState = SES_LEAVING; self->client->ps.saberEntityDist = saberThrowDist[self->client->ps.forcePowerLevel[FP_SABERTHROW]]; self->client->ps.saberThrowTime = level.time; - //if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) + // if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) { - self->client->ps.forcePowerDebounce[FP_SABERTHROW] = level.time + 1000;//so we can keep it out for a minimum amount of time + self->client->ps.forcePowerDebounce[FP_SABERTHROW] = level.time + 1000; // so we can keep it out for a minimum amount of time } - if ( thrown ) - {//this is a regular throw, so turn the saber on - //turn saber on - if ( (self->client->ps.saber[0].saberFlags&SFL_SINGLE_BLADE_THROWABLE) )//SaberStaff() ) - {//only first blade can be on - if ( !self->client->ps.saber[0].blade[0].active ) - {//turn on first one - self->client->ps.SaberBladeActivate( 0, 0 ); + if (thrown) { // this is a regular throw, so turn the saber on + // turn saber on + if ((self->client->ps.saber[0].saberFlags & SFL_SINGLE_BLADE_THROWABLE)) // SaberStaff() ) + { // only first blade can be on + if (!self->client->ps.saber[0].blade[0].active) { // turn on first one + self->client->ps.SaberBladeActivate(0, 0); } - for ( int i = 1; i < self->client->ps.saber[0].numBlades; i++ ) - {//turn off all others - if ( self->client->ps.saber[0].blade[i].active ) - { - self->client->ps.SaberBladeActivate( 0, i, qfalse ); + for (int i = 1; i < self->client->ps.saber[0].numBlades; i++) { // turn off all others + if (self->client->ps.saber[0].blade[i].active) { + self->client->ps.SaberBladeActivate(0, i, qfalse); } } - } - else - {//turn the sabers, all blades...? + } else { // turn the sabers, all blades...? self->client->ps.saber[0].Activate(); - //self->client->ps.SaberActivate(); + // self->client->ps.SaberActivate(); } - //turn on the saber trail - self->client->ps.saber[0].ActivateTrail( 150 ); + // turn on the saber trail + self->client->ps.saber[0].ActivateTrail(150); } - //reset the mins - VectorCopy( saberMins, saber->mins ); - VectorCopy( saberMaxs, saber->maxs ); - saber->contents = 0;//CONTENTS_LIGHTSABER; + // reset the mins + VectorCopy(saberMins, saber->mins); + VectorCopy(saberMaxs, saber->maxs); + saber->contents = 0; // CONTENTS_LIGHTSABER; saber->clipmask = MASK_SOLID | CONTENTS_LIGHTSABER; // remove the ghoul2 right-hand saber model on the player - if ( self->weaponModel[0] > 0 ) - { + if (self->weaponModel[0] > 0) { gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel[0]); self->weaponModel[0] = -1; } @@ -6732,19 +5296,15 @@ qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown, qbo return qtrue; } -qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ) -{ - if ( !self || !self->client || self->client->ps.saberEntityNum <= 0 ) - {//WTF?!! We lost it already? +qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir) { + if (!self || !self->client || self->client->ps.saberEntityNum <= 0) { // WTF?!! We lost it already? return qfalse; } - if ( self->client->NPC_class == CLASS_SABER_DROID ) - {//saber droids can't drop their saber + if (self->client->NPC_class == CLASS_SABER_DROID) { // saber droids can't drop their saber return qfalse; } gentity_t *dropped = &g_entities[self->client->ps.saberEntityNum]; - if ( !self->client->ps.saberInFlight ) - {//not alreay in air + if (!self->client->ps.saberInFlight) { // not alreay in air /* qboolean noForceThrow = qfalse; //make it so we can throw it @@ -6755,9 +5315,8 @@ qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ) self->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_1; } */ - //throw it - if ( !WP_SaberLaunch( self, dropped, qfalse ) ) - {//couldn't throw it + // throw it + if (!WP_SaberLaunch(self, dropped, qfalse)) { // couldn't throw it return qfalse; } /* @@ -6767,126 +5326,104 @@ qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ) } */ } - if ( self->client->ps.saber[0].Active() ) - {//on - //drop it instantly - WP_SaberDrop( self, dropped ); + if (self->client->ps.saber[0].Active()) { // on + // drop it instantly + WP_SaberDrop(self, dropped); } - //optionally give it some thrown velocity - if ( throwDir && !VectorCompare( throwDir, vec3_origin ) ) - { - VectorCopy( throwDir, dropped->s.pos.trDelta ); + // optionally give it some thrown velocity + if (throwDir && !VectorCompare(throwDir, vec3_origin)) { + VectorCopy(throwDir, dropped->s.pos.trDelta); } - //don't pull it back on the next frame - if ( self->NPC ) - { + // don't pull it back on the next frame + if (self->NPC) { self->NPC->last_ucmd.buttons &= ~BUTTON_ATTACK; } return qtrue; } -void WP_SetSaberOrigin( gentity_t *self, vec3_t newOrg ) -{ - if ( !self || !self->client ) - { +void WP_SetSaberOrigin(gentity_t *self, vec3_t newOrg) { + if (!self || !self->client) { return; } - if ( self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//no saber ent to reposition + if (self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { // no saber ent to reposition return; } - if ( self->client->NPC_class == CLASS_SABER_DROID ) - {//saber droids can't drop their saber + if (self->client->NPC_class == CLASS_SABER_DROID) { // saber droids can't drop their saber return; } gentity_t *dropped = &g_entities[self->client->ps.saberEntityNum]; - if ( !self->client->ps.saberInFlight ) - {//not already in air + if (!self->client->ps.saberInFlight) { // not already in air qboolean noForceThrow = qfalse; - //make it so we can throw it - self->client->ps.forcePowersKnown |= (1<client->ps.forcePowerLevel[FP_SABERTHROW] < FORCE_LEVEL_1 ) - { + // make it so we can throw it + self->client->ps.forcePowersKnown |= (1 << FP_SABERTHROW); + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] < FORCE_LEVEL_1) { noForceThrow = qtrue; self->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_1; } - //throw it - if ( !WP_SaberLaunch( self, dropped, qfalse, qtrue ) ) - {//couldn't throw it + // throw it + if (!WP_SaberLaunch(self, dropped, qfalse, qtrue)) { // couldn't throw it return; } - if ( noForceThrow ) - { + if (noForceThrow) { self->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_0; } } - VectorCopy( newOrg, dropped->s.origin ); - VectorCopy( newOrg, dropped->currentOrigin ); - VectorCopy( newOrg, dropped->s.pos.trBase ); - //drop it instantly - WP_SaberDrop( self, dropped ); - //don't pull it back on the next frame - if ( self->NPC ) - { + VectorCopy(newOrg, dropped->s.origin); + VectorCopy(newOrg, dropped->currentOrigin); + VectorCopy(newOrg, dropped->s.pos.trBase); + // drop it instantly + WP_SaberDrop(self, dropped); + // don't pull it back on the next frame + if (self->NPC) { self->NPC->last_ucmd.buttons &= ~BUTTON_ATTACK; } } -void WP_SaberCatch( gentity_t *self, gentity_t *saber, qboolean switchToSaber ) -{//FIXME: probably need a debounce time - if ( self->health > 0 && !PM_SaberInBrokenParry( self->client->ps.saberMove ) && self->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { - //clear the enemy +void WP_SaberCatch(gentity_t *self, gentity_t *saber, qboolean switchToSaber) { // FIXME: probably need a debounce time + if (self->health > 0 && !PM_SaberInBrokenParry(self->client->ps.saberMove) && self->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { + // clear the enemy saber->enemy = NULL; -//===FIXME!!!============================================================================================== - //We should copy the thrown saber's g2 instance to the right-hand saber - //When you catch it, and vice-versa when you throw it!!! -//===FIXME!!!============================================================================================== - //don't draw it + //===FIXME!!!============================================================================================== + // We should copy the thrown saber's g2 instance to the right-hand saber + // When you catch it, and vice-versa when you throw it!!! + //===FIXME!!!============================================================================================== + // don't draw it saber->s.eFlags |= EF_NODRAW; saber->svFlags &= SVF_BROADCAST; saber->svFlags |= SVF_NOCLIENT; - //take off any gravity stuff if we'd dropped it + // take off any gravity stuff if we'd dropped it saber->s.pos.trType = TR_LINEAR; saber->s.eFlags &= ~EF_BOUNCE_HALF; - //Put it in my hand + // Put it in my hand self->client->ps.saberInFlight = qfalse; self->client->ps.saberEntityState = SES_LEAVING; - //turn off the saber trail - self->client->ps.saber[0].DeactivateTrail( 75 ); + // turn off the saber trail + self->client->ps.saber[0].DeactivateTrail(75); - //reset its contents/clipmask - saber->contents = CONTENTS_LIGHTSABER;// | CONTENTS_SHOTCLIP; + // reset its contents/clipmask + saber->contents = CONTENTS_LIGHTSABER; // | CONTENTS_SHOTCLIP; saber->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - //play catch sound - G_Sound( saber, G_SoundIndex( "sound/weapons/saber/saber_catch.wav" ) ); - //FIXME: if an NPC, don't turn it back on if no enemy or enemy is dead... - //if it's not our current weapon, make it our current weapon - if ( self->client->ps.weapon == WP_SABER ) - {//only do the first saber since we only throw the first one - WP_SaberAddG2SaberModels( self, qfalse ); - } - if ( switchToSaber ) - { - if ( self->client->ps.weapon != WP_SABER ) - { - CG_ChangeWeapon( WP_SABER ); - } - else - {//if it's not active, turn it on - if ( (self->client->ps.saber[0].saberFlags&SFL_SINGLE_BLADE_THROWABLE) )//SaberStaff() ) - {//only first blade can be on - if ( !self->client->ps.saber[0].blade[0].active ) - {//only turn it on if first blade is off, otherwise, leave as-is + // play catch sound + G_Sound(saber, G_SoundIndex("sound/weapons/saber/saber_catch.wav")); + // FIXME: if an NPC, don't turn it back on if no enemy or enemy is dead... + // if it's not our current weapon, make it our current weapon + if (self->client->ps.weapon == WP_SABER) { // only do the first saber since we only throw the first one + WP_SaberAddG2SaberModels(self, qfalse); + } + if (switchToSaber) { + if (self->client->ps.weapon != WP_SABER) { + CG_ChangeWeapon(WP_SABER); + } else { // if it's not active, turn it on + if ((self->client->ps.saber[0].saberFlags & SFL_SINGLE_BLADE_THROWABLE)) // SaberStaff() ) + { // only first blade can be on + if (!self->client->ps.saber[0].blade[0].active) { // only turn it on if first blade is off, otherwise, leave as-is self->client->ps.saber[0].Activate(); } - } - else - {//turn all blades on + } else { // turn all blades on self->client->ps.saber[0].Activate(); } } @@ -6894,357 +5431,276 @@ void WP_SaberCatch( gentity_t *self, gentity_t *saber, qboolean switchToSaber ) } } - -void WP_SaberReturn( gentity_t *self, gentity_t *saber ) -{ - if ( PM_SaberInBrokenParry( self->client->ps.saberMove ) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { +void WP_SaberReturn(gentity_t *self, gentity_t *saber) { + if (PM_SaberInBrokenParry(self->client->ps.saberMove) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { return; } - if ( self && self->client ) - {//still alive and stuff - //FIXME: when it's returning, flies butt first, but seems to do a lot of damage when going through people... hmm... + if (self && self->client) { // still alive and stuff + // FIXME: when it's returning, flies butt first, but seems to do a lot of damage when going through people... hmm... self->client->ps.saberEntityState = SES_RETURNING; - //turn down the saber trail - if ( !(self->client->ps.saber[0].saberFlags&SFL_RETURN_DAMAGE) )//type != SABER_STAR ) + // turn down the saber trail + if (!(self->client->ps.saber[0].saberFlags & SFL_RETURN_DAMAGE)) // type != SABER_STAR ) { - self->client->ps.saber[0].DeactivateTrail( 75 ); + self->client->ps.saber[0].DeactivateTrail(75); } } - if ( !(saber->s.eFlags&EF_BOUNCE) ) - { + if (!(saber->s.eFlags & EF_BOUNCE)) { saber->s.eFlags |= EF_BOUNCE; saber->bounceCount = 300; } } - -void WP_SaberDrop( gentity_t *self, gentity_t *saber ) -{ - //clear the enemy +void WP_SaberDrop(gentity_t *self, gentity_t *saber) { + // clear the enemy saber->enemy = NULL; saber->s.eFlags &= ~EF_BOUNCE; saber->bounceCount = 0; - //make it fall + // make it fall saber->s.pos.trType = TR_GRAVITY; - //make it bounce some + // make it bounce some saber->s.eFlags |= EF_BOUNCE_HALF; - //make it spin - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); + // make it spin + VectorCopy(saber->currentAngles, saber->s.apos.trBase); saber->s.apos.trType = TR_LINEAR; saber->s.apos.trTime = level.time; - VectorSet( saber->s.apos.trDelta, Q_irand( -300, 300 ), saber->s.apos.trDelta[1], Q_irand( -300, 300 ) ); - if ( !saber->s.apos.trDelta[1] ) - { - saber->s.apos.trDelta[1] = Q_irand( -300, 300 ); + VectorSet(saber->s.apos.trDelta, Q_irand(-300, 300), saber->s.apos.trDelta[1], Q_irand(-300, 300)); + if (!saber->s.apos.trDelta[1]) { + saber->s.apos.trDelta[1] = Q_irand(-300, 300); } - //force it to be ready to return + // force it to be ready to return self->client->ps.saberEntityDist = 0; self->client->ps.saberEntityState = SES_RETURNING; - //turn it off + // turn it off self->client->ps.saber[0].Deactivate(); - //turn off the saber trail - self->client->ps.saber[0].DeactivateTrail( 75 ); - //play the saber turning off sound - G_SoundIndexOnEnt( saber, CHAN_AUTO, self->client->ps.saber[0].soundOff ); + // turn off the saber trail + self->client->ps.saber[0].DeactivateTrail(75); + // play the saber turning off sound + G_SoundIndexOnEnt(saber, CHAN_AUTO, self->client->ps.saber[0].soundOff); - if ( self->health <= 0 ) - {//owner is dead! - saber->s.time = level.time;//will make us free ourselves after a time + if (self->health <= 0) { // owner is dead! + saber->s.time = level.time; // will make us free ourselves after a time } } - -void WP_SaberPull( gentity_t *self, gentity_t *saber ) -{ - if ( PM_SaberInBrokenParry( self->client->ps.saberMove ) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { +void WP_SaberPull(gentity_t *self, gentity_t *saber) { + if (PM_SaberInBrokenParry(self->client->ps.saberMove) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { return; } - if ( self->health > 0 ) - { - //take off gravity + if (self->health > 0) { + // take off gravity saber->s.pos.trType = TR_LINEAR; - //take off bounce + // take off bounce saber->s.eFlags &= EF_BOUNCE_HALF; - //play sound - G_Sound( self, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); + // play sound + G_Sound(self, G_SoundIndex("sound/weapons/force/pull.wav")); } } -const char *saberColorStringForColor[SABER_PURPLE+1] = -{ - "red",//SABER_RED - "orange",//SABER_ORANGE - "yellow",//SABER_YELLOW - "green",//SABER_GREEN - "blue",//SABER_BLUE - "purple"//SABER_PURPLE +const char *saberColorStringForColor[SABER_PURPLE + 1] = { + "red", // SABER_RED + "orange", // SABER_ORANGE + "yellow", // SABER_YELLOW + "green", // SABER_GREEN + "blue", // SABER_BLUE + "purple" // SABER_PURPLE }; // Check if we are throwing it, launch it if needed, update position if needed. -void WP_SaberThrow( gentity_t *self, usercmd_t *ucmd ) -{ - vec3_t saberDiff; - trace_t tr; - //static float SABER_SPEED = 10; +void WP_SaberThrow(gentity_t *self, usercmd_t *ucmd) { + vec3_t saberDiff; + trace_t tr; + // static float SABER_SPEED = 10; gentity_t *saberent; - if ( self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//WTF?!! We lost it? + if (self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { // WTF?!! We lost it? return; } - if ( self->client->ps.torsoAnim == BOTH_LOSE_SABER ) - {//can't catch it while it's being yanked from your hand! + if (self->client->ps.torsoAnim == BOTH_LOSE_SABER) { // can't catch it while it's being yanked from your hand! return; } - if ( !g_saberNewControlScheme->integer ) - { - if ( PM_SaberInKata( (saberMoveName_t)self->client->ps.saberMove ) ) - {//don't throw saber when in special attack (alt+attack) + if (!g_saberNewControlScheme->integer) { + if (PM_SaberInKata((saberMoveName_t)self->client->ps.saberMove)) { // don't throw saber when in special attack (alt+attack) return; } - if ( (ucmd->buttons&BUTTON_ATTACK) - && (ucmd->buttons&BUTTON_ALT_ATTACK) - && !self->client->ps.saberInFlight ) - {//trying to do special attack, don't throw it + if ((ucmd->buttons & BUTTON_ATTACK) && (ucmd->buttons & BUTTON_ALT_ATTACK) && + !self->client->ps.saberInFlight) { // trying to do special attack, don't throw it return; - } - else if ( self->client->ps.torsoAnim == BOTH_A1_SPECIAL - || self->client->ps.torsoAnim == BOTH_A2_SPECIAL - || self->client->ps.torsoAnim == BOTH_A3_SPECIAL ) - {//don't throw in these anims! + } else if (self->client->ps.torsoAnim == BOTH_A1_SPECIAL || self->client->ps.torsoAnim == BOTH_A2_SPECIAL || + self->client->ps.torsoAnim == BOTH_A3_SPECIAL) { // don't throw in these anims! return; } } saberent = &g_entities[self->client->ps.saberEntityNum]; - VectorSubtract( self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff ); + VectorSubtract(self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff); - //is our saber in flight? - if ( !self->client->ps.saberInFlight ) - {//saber is not in flight right now - if ( self->client->ps.weapon != WP_SABER ) - {//don't even have it out + // is our saber in flight? + if (!self->client->ps.saberInFlight) { // saber is not in flight right now + if (self->client->ps.weapon != WP_SABER) { // don't even have it out return; - } - else if ( (ucmd->buttons&BUTTON_ALT_ATTACK) && !(self->client->ps.pm_flags&PMF_ALT_ATTACK_HELD) ) - {//still holding it, not still holding attack from a previous throw, so throw it. - if ( !(self->client->ps.saberEventFlags&SEF_INWATER) && WP_SaberLaunch( self, saberent, qtrue ) ) - { - if ( self->client && !self->s.number ) - { + } else if ((ucmd->buttons & BUTTON_ALT_ATTACK) && + !(self->client->ps.pm_flags & PMF_ALT_ATTACK_HELD)) { // still holding it, not still holding attack from a previous throw, so throw it. + if (!(self->client->ps.saberEventFlags & SEF_INWATER) && WP_SaberLaunch(self, saberent, qtrue)) { + if (self->client && !self->s.number) { self->client->sess.missionStats.saberThrownCnt++; } - //need to recalc this because we just moved it - VectorSubtract( self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff ); - } - else - {//couldn't throw it + // need to recalc this because we just moved it + VectorSubtract(self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff); + } else { // couldn't throw it return; } - } - else - {//holding it, don't want to throw it, go away. + } else { // holding it, don't want to throw it, go away. return; } - } - else - {//inflight - //is our saber currently on it's way back to us? - if ( self->client->ps.saberEntityState == SES_RETURNING ) - {//see if we're close enough to pick it up - if ( VectorLengthSquared( saberDiff ) <= 256 )//16 squared//G_BoundsOverlap( self->absmin, self->absmax, saberent->absmin, saberent->absmax ) )// - {//caught it - vec3_t axisPoint; - trace_t trace; - VectorCopy( self->currentOrigin, axisPoint ); + } else { // inflight + // is our saber currently on it's way back to us? + if (self->client->ps.saberEntityState == SES_RETURNING) { // see if we're close enough to pick it up + if (VectorLengthSquared(saberDiff) <= 256) // 16 squared//G_BoundsOverlap( self->absmin, self->absmax, saberent->absmin, saberent->absmax ) )// + { // caught it + vec3_t axisPoint; + trace_t trace; + VectorCopy(self->currentOrigin, axisPoint); axisPoint[2] = self->client->renderInfo.handRPoint[2]; - gi.trace( &trace, axisPoint, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); - if ( !trace.startsolid && trace.fraction >= 1.0f ) - {//our hand isn't through a wall - WP_SaberCatch( self, saberent, qtrue ); - //NPC_SetAnim( self, SETANIM_TORSO, TORSO_HANDRETRACT1, SETANIM_FLAG_OVERRIDE ); + gi.trace(&trace, axisPoint, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, (EG2_Collision)0, 0); + if (!trace.startsolid && trace.fraction >= 1.0f) { // our hand isn't through a wall + WP_SaberCatch(self, saberent, qtrue); + // NPC_SetAnim( self, SETANIM_TORSO, TORSO_HANDRETRACT1, SETANIM_FLAG_OVERRIDE ); } return; } } - if ( saberent->s.pos.trType != TR_STATIONARY ) - {//saber is in flight, lerp it - if ( self->health <= 0 )//&& level.time > saberent->s.time + 5000 ) - {//make us free ourselves after a time - if ( g_saberPickuppableDroppedSabers->integer - && G_DropSaberItem( self->client->ps.saber[0].name, self->client->ps.saber[0].blade[0].color, saberent->currentOrigin, saberent->s.pos.trDelta, saberent->currentAngles ) != NULL ) - {//dropped it - //free it - G_FreeEntity( saberent ); - //forget it + if (saberent->s.pos.trType != TR_STATIONARY) { // saber is in flight, lerp it + if (self->health <= 0) //&& level.time > saberent->s.time + 5000 ) + { // make us free ourselves after a time + if (g_saberPickuppableDroppedSabers->integer && + G_DropSaberItem(self->client->ps.saber[0].name, self->client->ps.saber[0].blade[0].color, saberent->currentOrigin, saberent->s.pos.trDelta, + saberent->currentAngles) != NULL) { // dropped it + // free it + G_FreeEntity(saberent); + // forget it self->client->ps.saberEntityNum = ENTITYNUM_NONE; return; } } - WP_RunSaber( self, saberent ); - } - else - {//it fell on the ground - if ( self->health <= 0 )//&& level.time > saberent->s.time + 5000 ) - {//make us free ourselves after a time - if ( g_saberPickuppableDroppedSabers->integer ) - {//spawn an item - G_DropSaberItem( self->client->ps.saber[0].name, self->client->ps.saber[0].blade[0].color, saberent->currentOrigin, saberent->s.pos.trDelta, saberent->currentAngles ); - } - //free it - G_FreeEntity( saberent ); - //forget it + WP_RunSaber(self, saberent); + } else { // it fell on the ground + if (self->health <= 0) //&& level.time > saberent->s.time + 5000 ) + { // make us free ourselves after a time + if (g_saberPickuppableDroppedSabers->integer) { // spawn an item + G_DropSaberItem(self->client->ps.saber[0].name, self->client->ps.saber[0].blade[0].color, saberent->currentOrigin, saberent->s.pos.trDelta, + saberent->currentAngles); + } + // free it + G_FreeEntity(saberent); + // forget it self->client->ps.saberEntityNum = ENTITYNUM_NONE; return; } - if ( (!self->s.number && level.time - saberent->aimDebounceTime > 15000) - || (self->s.number && level.time - saberent->aimDebounceTime > 5000) ) - {//(only for player) been missing for 15 seconds, automagicially return - WP_SaberCatch( self, saberent, qfalse ); + if ((!self->s.number && level.time - saberent->aimDebounceTime > 15000) || + (self->s.number && level.time - saberent->aimDebounceTime > 5000)) { //(only for player) been missing for 15 seconds, automagicially return + WP_SaberCatch(self, saberent, qfalse); return; } } } - //are we still trying to use the saber? - if ( self->client->ps.weapon != WP_SABER ) - {//switched away - if ( !self->client->ps.saberInFlight ) - {//wasn't throwing saber + // are we still trying to use the saber? + if (self->client->ps.weapon != WP_SABER) { // switched away + if (!self->client->ps.saberInFlight) { // wasn't throwing saber return; - } - else if ( saberent->s.pos.trType == TR_LINEAR ) - {//switched away while controlling it, just drop the saber - WP_SaberDrop( self, saberent ); + } else if (saberent->s.pos.trType == TR_LINEAR) { // switched away while controlling it, just drop the saber + WP_SaberDrop(self, saberent); return; - } - else - {//it's on the ground, see if it's inside us (touching) - if ( G_PointInBounds( saberent->currentOrigin, self->absmin, self->absmax ) ) - {//it's in us, pick it up automatically - WP_SaberPull( self, saberent ); + } else { // it's on the ground, see if it's inside us (touching) + if (G_PointInBounds(saberent->currentOrigin, self->absmin, self->absmax)) { // it's in us, pick it up automatically + WP_SaberPull(self, saberent); } } - } - else if ( saberent->s.pos.trType != TR_LINEAR ) - {//weapon is saber and not flying - if ( self->client->ps.saberInFlight ) - {//we dropped it - if ( ucmd->buttons & BUTTON_ATTACK )//|| self->client->ps.weaponstate == WEAPON_RAISING )//ucmd->buttons & BUTTON_ALT_ATTACK || - {//we actively want to pick it up or we just switched to it, so pull it back - gi.trace( &tr, saberent->currentOrigin, saberent->mins, saberent->maxs, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, (EG2_Collision)0, 0 ); + } else if (saberent->s.pos.trType != TR_LINEAR) { // weapon is saber and not flying + if (self->client->ps.saberInFlight) { // we dropped it + if (ucmd->buttons & BUTTON_ATTACK) //|| self->client->ps.weaponstate == WEAPON_RAISING )//ucmd->buttons & BUTTON_ALT_ATTACK || + { // we actively want to pick it up or we just switched to it, so pull it back + gi.trace(&tr, saberent->currentOrigin, saberent->mins, saberent->maxs, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, + (EG2_Collision)0, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 1.0f ) - {//can't pick it up yet, no LOS + if (tr.allsolid || tr.startsolid || tr.fraction < 1.0f) { // can't pick it up yet, no LOS return; } - //clear LOS, pick it up - WP_SaberPull( self, saberent ); - } - else - {//see if it's inside us (touching) - if ( G_PointInBounds( saberent->currentOrigin, self->absmin, self->absmax ) ) - {//it's in us, pick it up automatically - WP_SaberPull( self, saberent ); + // clear LOS, pick it up + WP_SaberPull(self, saberent); + } else { // see if it's inside us (touching) + if (G_PointInBounds(saberent->currentOrigin, self->absmin, self->absmax)) { // it's in us, pick it up automatically + WP_SaberPull(self, saberent); } } } - } - else if ( self->health <= 0 && self->client->ps.saberInFlight ) - {//we died, drop it - WP_SaberDrop( self, saberent ); + } else if (self->health <= 0 && self->client->ps.saberInFlight) { // we died, drop it + WP_SaberDrop(self, saberent); return; - } - else if ( !self->client->ps.saber[0].Active() && self->client->ps.saberEntityState != SES_RETURNING ) - {//we turned it off, drop it - WP_SaberDrop( self, saberent ); + } else if (!self->client->ps.saber[0].Active() && self->client->ps.saberEntityState != SES_RETURNING) { // we turned it off, drop it + WP_SaberDrop(self, saberent); return; } - //TODO: if deactivate saber in flight, should it drop? + // TODO: if deactivate saber in flight, should it drop? - if ( saberent->s.pos.trType != TR_LINEAR ) - {//don't home + if (saberent->s.pos.trType != TR_LINEAR) { // don't home return; } - float saberDist = VectorLength( saberDiff ); - if ( self->client->ps.saberEntityState == SES_LEAVING ) - {//saber still flying forward - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - {//still holding it out - if ( !(ucmd->buttons&BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time ) - {//done throwing, return to me - if ( self->client->ps.saber[0].Active() ) - {//still on - WP_SaberReturn( self, saberent ); + float saberDist = VectorLength(saberDiff); + if (self->client->ps.saberEntityState == SES_LEAVING) { // saber still flying forward + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { // still holding it out + if (!(ucmd->buttons & BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time) { // done throwing, return to me + if (self->client->ps.saber[0].Active()) { // still on + WP_SaberReturn(self, saberent); } - } - else if ( level.time - self->client->ps.saberThrowTime >= 100 ) - { - if ( WP_ForcePowerAvailable( self, FP_SABERTHROW, 1 ) ) - { - WP_ForcePowerDrain( self, FP_SABERTHROW, 1 ); + } else if (level.time - self->client->ps.saberThrowTime >= 100) { + if (WP_ForcePowerAvailable(self, FP_SABERTHROW, 1)) { + WP_ForcePowerDrain(self, FP_SABERTHROW, 1); self->client->ps.saberThrowTime = level.time; - } - else - {//out of force power, return to me - WP_SaberReturn( self, saberent ); + } else { // out of force power, return to me + WP_SaberReturn(self, saberent); } } - } - else - { - if ( !(ucmd->buttons&BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time ) - {//not holding button and has been out at least 1 second, return to me - if ( self->client->ps.saber[0].Active() ) - {//still on - WP_SaberReturn( self, saberent ); + } else { + if (!(ucmd->buttons & BUTTON_ALT_ATTACK) && + self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time) { // not holding button and has been out at least 1 second, return to me + if (self->client->ps.saber[0].Active()) { // still on + WP_SaberReturn(self, saberent); } - } - else if ( level.time - self->client->ps.saberThrowTime > 3000 - || (self->client->ps.forcePowerLevel[FP_SABERTHROW]==FORCE_LEVEL_1&&saberDist>=self->client->ps.saberEntityDist) ) - {//been out too long, or saber throw 1 went too far, return to me - if ( self->client->ps.saber[0].Active() ) - {//still on - WP_SaberReturn( self, saberent ); + } else if (level.time - self->client->ps.saberThrowTime > 3000 || + (self->client->ps.forcePowerLevel[FP_SABERTHROW] == FORCE_LEVEL_1 && + saberDist >= self->client->ps.saberEntityDist)) { // been out too long, or saber throw 1 went too far, return to me + if (self->client->ps.saber[0].Active()) { // still on + WP_SaberReturn(self, saberent); } } } } - if ( self->client->ps.saberEntityState == SES_RETURNING ) - { - if ( self->client->ps.saberEntityDist > 0 ) - { + if (self->client->ps.saberEntityState == SES_RETURNING) { + if (self->client->ps.saberEntityDist > 0) { self->client->ps.saberEntityDist -= 25; } - if ( self->client->ps.saberEntityDist < 0 ) - { + if (self->client->ps.saberEntityDist < 0) { self->client->ps.saberEntityDist = 0; - } - else if ( saberDist < self->client->ps.saberEntityDist ) - {//if it's coming back to me, never push it away + } else if (saberDist < self->client->ps.saberEntityDist) { // if it's coming back to me, never push it away self->client->ps.saberEntityDist = saberDist; } } } - -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -int WP_MissileBlockForBlock( int saberBlock ) -{ - switch( saberBlock ) - { +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +int WP_MissileBlockForBlock(int saberBlock) { + switch (saberBlock) { case BLOCKED_UPPER_RIGHT: return BLOCKED_UPPER_RIGHT_PROJ; break; @@ -7264,108 +5720,83 @@ int WP_MissileBlockForBlock( int saberBlock ) return saberBlock; } -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ) -{ - vec3_t diff, fwdangles={0,0,0}, right; +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock) { + vec3_t diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - if ( self->client->ps.weaponstate == WEAPON_DROPPING || - self->client->ps.weaponstate == WEAPON_RAISING ) - {//don't block while changing weapons + if (self->client->ps.weaponstate == WEAPON_DROPPING || self->client->ps.weaponstate == WEAPON_RAISING) { // don't block while changing weapons return; } - if ( PM_SuperBreakLoseAnim( self->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( self->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(self->client->ps.torsoAnim) || PM_SuperBreakWinAnim(self->client->ps.torsoAnim)) { return; } - //NPCs don't auto-block - if ( !missileBlock && self->s.number != 0 && self->client->ps.saberBlocked != BLOCKED_NONE ) - { + // NPCs don't auto-block + if (!missileBlock && self->s.number != 0 && self->client->ps.saberBlocked != BLOCKED_NONE) { return; } - VectorSubtract( hitloc, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(hitloc, self->client->renderInfo.eyePoint, diff); diff[2] = 0; - VectorNormalize( diff ); + VectorNormalize(diff); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); rightdot = DotProduct(right, diff); zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2]; - //FIXME: take torsoAngles into account? - if ( zdiff > -5 )//0 )//40 ) + // FIXME: take torsoAngles into account? + if (zdiff > -5) // 0 )//40 ) { - if ( rightdot > 0.3 ) - { + if (rightdot > 0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.3 ) - { + } else if (rightdot < -0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else if ( zdiff > -22 )//-20 )//20 ) + } else if (zdiff > -22) //-20 )//20 ) { - if ( zdiff < -10 )//30 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - //NPC should duck, but NPC should never get here + if (zdiff < -10) // 30 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck + // NPC should duck, but NPC should never get here } - if ( rightdot > 0.1 ) - { + if (rightdot > 0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.1 ) - { + } else if (rightdot < -0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - {//FIXME: this looks really weird if the shot is too low! + } else { // FIXME: this looks really weird if the shot is too low! self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else - { - if ( rightdot >= 0 ) - { + } else { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( !self->s.number ) - { - gi.Printf( "EyeZ: %4.2f HitZ: %4.2f zdiff: %4.2f rdot: %4.2f\n", self->client->renderInfo.eyePoint[2], hitloc[2], zdiff, rightdot ); - switch ( self->client->ps.saberBlocked ) - { + if (d_saberCombat->integer) { + if (!self->s.number) { + gi.Printf("EyeZ: %4.2f HitZ: %4.2f zdiff: %4.2f rdot: %4.2f\n", self->client->renderInfo.eyePoint[2], hitloc[2], zdiff, rightdot); + switch (self->client->ps.saberBlocked) { case BLOCKED_TOP: - gi.Printf( "BLOCKED_TOP\n" ); + gi.Printf("BLOCKED_TOP\n"); break; case BLOCKED_UPPER_RIGHT: - gi.Printf( "BLOCKED_UPPER_RIGHT\n" ); + gi.Printf("BLOCKED_UPPER_RIGHT\n"); break; case BLOCKED_UPPER_LEFT: - gi.Printf( "BLOCKED_UPPER_LEFT\n" ); + gi.Printf("BLOCKED_UPPER_LEFT\n"); break; case BLOCKED_LOWER_RIGHT: - gi.Printf( "BLOCKED_LOWER_RIGHT\n" ); + gi.Printf("BLOCKED_LOWER_RIGHT\n"); break; case BLOCKED_LOWER_LEFT: - gi.Printf( "BLOCKED_LOWER_LEFT\n" ); + gi.Printf("BLOCKED_LOWER_LEFT\n"); break; default: break; @@ -7374,299 +5805,222 @@ void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlo } #endif - if ( missileBlock ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (missileBlock) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } - if ( self->client->ps.saberBlocked != BLOCKED_NONE ) - { - int parryReCalcTime = Jedi_ReCalcParryTime( self, EVASION_PARRY ); - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + if (self->client->ps.saberBlocked != BLOCKED_NONE) { + int parryReCalcTime = Jedi_ReCalcParryTime(self, EVASION_PARRY); + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } } } -void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) -{ - float dist; - gentity_t *ent, *incoming = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - int i, e; - float closestDist, radius = 256; - vec3_t forward, dir, missile_dir, fwdangles = {0}; - trace_t trace; - vec3_t traceTo, entDir; - qboolean dodgeOnlySabers = qfalse; - +void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd) { + float dist; + gentity_t *ent, *incoming = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + int i, e; + float closestDist, radius = 256; + vec3_t forward, dir, missile_dir, fwdangles = {0}; + trace_t trace; + vec3_t traceTo, entDir; + qboolean dodgeOnlySabers = qfalse; - if ( self->NPC && (self->NPC->scriptFlags&SCF_IGNORE_ALERTS) ) - {//don't react to things flying at me... + if (self->NPC && (self->NPC->scriptFlags & SCF_IGNORE_ALERTS)) { // don't react to things flying at me... return; } - if ( self->health <= 0 ) - {//dead don't try to block (NOTE: actual deflection happens in missile code) + if (self->health <= 0) { // dead don't try to block (NOTE: actual deflection happens in missile code) return; } - if ( PM_InKnockDown( &self->client->ps ) ) - {//can't block when knocked down + if (PM_InKnockDown(&self->client->ps)) { // can't block when knocked down return; } - if ( PM_SuperBreakLoseAnim( self->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( self->client->ps.torsoAnim ) ) - {//can't block while in break anim + if (PM_SuperBreakLoseAnim(self->client->ps.torsoAnim) || PM_SuperBreakWinAnim(self->client->ps.torsoAnim)) { // can't block while in break anim return; } - if ( Rosh_BeingHealed( self ) ) - { + if (Rosh_BeingHealed(self)) { return; } - if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - {//rockettrooper - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//must be in air + if (self->client->NPC_class == CLASS_ROCKETTROOPER) { // rockettrooper + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // must be in air return; } - if ( Q_irand( 0, 4-(g_spskill->integer*2) ) ) - {//easier level guys do this less + if (Q_irand(0, 4 - (g_spskill->integer * 2))) { // easier level guys do this less return; } - if ( Q_irand( 0, 3 ) ) - {//base level: 25% chance of looking for something to dodge - if ( Q_irand( 0, 1 ) ) - {//dodge sabers twice as frequently as other projectiles + if (Q_irand(0, 3)) { // base level: 25% chance of looking for something to dodge + if (Q_irand(0, 1)) { // dodge sabers twice as frequently as other projectiles dodgeOnlySabers = qtrue; - } - else - { + } else { return; } } } - if ( self->client->NPC_class == CLASS_BOBAFETT ) - {//Boba doesn't dodge quite as much - if ( Q_irand( 0, 2-g_spskill->integer) ) - {//easier level guys do this less + if (self->client->NPC_class == CLASS_BOBAFETT) { // Boba doesn't dodge quite as much + if (Q_irand(0, 2 - g_spskill->integer)) { // easier level guys do this less return; } } - if ( self->client->NPC_class != CLASS_BOBAFETT - && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) - && (self->client->NPC_class != CLASS_ROCKETTROOPER||!self->NPC||self->NPC->rankinteger - && (ucmd->buttons & BUTTON_USE) - && cg.renderingThirdPerson - && G_OkayToLean( &self->client->ps, ucmd, qfalse ) - && (self->client->ps.forcePowersActive&(1<client->ps.weapon != WP_SABER ) - { + if (self->client->NPC_class != CLASS_BOBAFETT && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) && + (self->client->NPC_class != CLASS_ROCKETTROOPER || !self->NPC || + self->NPC->rank < RANK_LT) // if a rockettrooper, but not an officer, do these normal checks + ) { + if (g_debugMelee->integer && (ucmd->buttons & BUTTON_USE) && cg.renderingThirdPerson && G_OkayToLean(&self->client->ps, ucmd, qfalse) && + (self->client->ps.forcePowersActive & (1 << FP_SPEED))) { + } else { + if (self->client->ps.weapon != WP_SABER) { return; } - if ( self->client->ps.saberInFlight ) - { + if (self->client->ps.saberInFlight) { return; } - if ( self->s.number < MAX_CLIENTS ) - { - if ( !self->client->ps.SaberLength() ) - {//player doesn't auto-activate + if (self->s.number < MAX_CLIENTS) { + if (!self->client->ps.SaberLength()) { // player doesn't auto-activate return; } - if ( !g_saberAutoBlocking->integer && self->client->ps.saberBlockingTimeinteger && self->client->ps.saberBlockingTime < level.time) { return; } } - if ( (self->client->ps.saber[0].saberFlags&SFL_NOT_ACTIVE_BLOCKING) ) - {//can't actively block with this saber type + if ((self->client->ps.saber[0].saberFlags & SFL_NOT_ACTIVE_BLOCKING)) { // can't actively block with this saber type return; } } - if ( !self->s.number ) - {//don't do this if already attacking! - if ( ucmd->buttons & BUTTON_ATTACK - || PM_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || PM_SaberInTransitionAny( self->client->ps.saberMove )) - { + if (!self->s.number) { // don't do this if already attacking! + if (ucmd->buttons & BUTTON_ATTACK || PM_SaberInAttack(self->client->ps.saberMove) || PM_SaberInSpecialAttack(self->client->ps.torsoAnim) || + PM_SaberInTransitionAny(self->client->ps.saberMove)) { return; } } - if ( self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1 ) - {//you have not the SKILLZ + if (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1) { // you have not the SKILLZ return; } - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't block while already blocking + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time) { // can't block while already blocking return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // can't block while zapping return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_DRAIN)) { // can't block while draining return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_PUSH)) { // can't block while shoving return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & + (1 << FP_GRIP)) { // can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) return; } } fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = self->currentOrigin[i] - radius; maxs[i] = self->currentOrigin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); closestDist = radius; - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( dodgeOnlySabers ) - {//only care about thrown sabers - if ( ent->client - || ent->s.weapon != WP_SABER - || !ent->classname - || !ent->classname[0] - || Q_stricmp( "lightsaber", ent->classname ) ) - {//not a lightsaber, ignore it + if (dodgeOnlySabers) { // only care about thrown sabers + if (ent->client || ent->s.weapon != WP_SABER || !ent->classname || !ent->classname[0] || + Q_stricmp("lightsaber", ent->classname)) { // not a lightsaber, ignore it continue; } } - if ( ent->s.eType != ET_MISSILE && !(ent->s.eFlags&EF_MISSILE_STICK) ) - {//not a normal projectile - if ( ent->client || ent->s.weapon != WP_SABER ) - {//FIXME: wake up bad guys? + if (ent->s.eType != ET_MISSILE && !(ent->s.eFlags & EF_MISSILE_STICK)) { // not a normal projectile + if (ent->client || ent->s.weapon != WP_SABER) { // FIXME: wake up bad guys? continue; } - if ( ent->s.eFlags & EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber - //FIXME: what about general objects that are small in size- like rocks, etc... + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber + // FIXME: what about general objects that are small in size- like rocks, etc... continue; } - //a lightsaber.. make sure it's on and inFlight - if ( !ent->owner || !ent->owner->client ) - { + // a lightsaber.. make sure it's on and inFlight + if (!ent->owner || !ent->owner->client) { continue; } - if ( !ent->owner->client->ps.saberInFlight ) - {//not in flight + if (!ent->owner->client->ps.saberInFlight) { // not in flight continue; } - if ( ent->owner->client->ps.SaberLength() <= 0 ) - {//not on + if (ent->owner->client->ps.SaberLength() <= 0) { // not on continue; } - if ( ent->owner->health <= 0 && g_saberRealisticCombat->integer < 2 ) - {//it's not doing damage, so ignore it + if (ent->owner->health <= 0 && g_saberRealisticCombat->integer < 2) { // it's not doing damage, so ignore it continue; } - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && !self->s.number ) - {//nothing you can do with a stationary missile if you're the player + } else { + if (ent->s.pos.trType == TR_STATIONARY && !self->s.number) { // nothing you can do with a stationary missile if you're the player continue; } } - float dot1, dot2; - //see if they're in front of me - VectorSubtract( ent->currentOrigin, self->currentOrigin, dir ); - dist = VectorNormalize( dir ); - //FIXME: handle detpacks, proximity mines and tripmines - if ( ent->s.weapon == WP_THERMAL ) - {//thermal detonator! - if ( self->NPC && dist < ent->splashRadius ) - { - if ( dist < ent->splashRadius && - ent->nextthink < level.time + 600 && - ent->count && - self->client->ps.groundEntityNum != ENTITYNUM_NONE && - (ent->s.pos.trType == TR_STATIONARY|| - ent->s.pos.trType == TR_INTERPOLATE|| - (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE|| - !WP_ForcePowerUsable( self, FP_PUSH, 0 )) ) - {//TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and about to blow up, or I don't have force-push so force-jump! - //FIXME: sometimes this might make me just jump into it...? + float dot1, dot2; + // see if they're in front of me + VectorSubtract(ent->currentOrigin, self->currentOrigin, dir); + dist = VectorNormalize(dir); + // FIXME: handle detpacks, proximity mines and tripmines + if (ent->s.weapon == WP_THERMAL) { // thermal detonator! + if (self->NPC && dist < ent->splashRadius) { + if (dist < ent->splashRadius && ent->nextthink < level.time + 600 && ent->count && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (ent->s.pos.trType == TR_STATIONARY || ent->s.pos.trType == TR_INTERPOLATE || + (dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE || + !WP_ForcePowerUsable(self, FP_PUSH, 0))) { // TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and + // about to blow up, or I don't have force-push so force-jump! + // FIXME: sometimes this might make me just jump into it...? self->client->ps.forceJumpCharge = 480; - } - else if ( self->client->NPC_class != CLASS_BOBAFETT - && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) - && self->client->NPC_class != CLASS_ROCKETTROOPER ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - if ( !ent->owner || !OnSameTeam( self, ent->owner ) ) - { - ForceThrow( self, qfalse ); + } else if (self->client->NPC_class != CLASS_BOBAFETT && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) && + self->client->NPC_class != CLASS_ROCKETTROOPER) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + if (!ent->owner || !OnSameTeam(self, ent->owner)) { + ForceThrow(self, qfalse); } } } continue; - } - else if ( ent->splashDamage && ent->splashRadius ) - {//exploding missile - //FIXME: handle tripmines and detpacks somehow... + } else if (ent->splashDamage && ent->splashRadius) { // exploding missile + // FIXME: handle tripmines and detpacks somehow... // maybe do a force-gesture that makes them explode? // But what if we're within it's splashradius? - if ( !self->s.number ) - {//players don't auto-handle these at all + if (!self->s.number) { // players don't auto-handle these at all continue; - } - else - { - if ( self->client->NPC_class == CLASS_BOBAFETT - || self->client->NPC_class == CLASS_ROCKETTROOPER ) - { + } else { + if (self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) { /* if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) {//sorry, you're scrooged here @@ -7675,363 +6029,293 @@ void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) } //else it's a rocket, try to evade it */ - //HMM... let's see what happens if these guys try to avoid tripmines and detpacks, too...? - } - else - {//normal Jedi - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) - && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) ) - {//a placed explosive like a tripmine or detpack - if ( InFOV( ent->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90 ) ) - {//in front of me - if ( G_ClearLOS( self, ent ) ) - {//can see it + // HMM... let's see what happens if these guys try to avoid tripmines and detpacks, too...? + } else { // normal Jedi + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK) && + (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER)) { // a placed explosive like a tripmine or detpack + if (InFOV(ent->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90)) { // in front of me + if (G_ClearLOS(self, ent)) { // can see it vec3_t throwDir; - //make the gesture - ForceThrow( self, qfalse ); - //take it off the wall and toss it + // make the gesture + ForceThrow(self, qfalse); + // take it off the wall and toss it ent->s.pos.trType = TR_GRAVITY; ent->s.eType = ET_MISSILE; ent->s.eFlags &= ~EF_MISSILE_STICK; ent->s.eFlags |= EF_BOUNCE_HALF; - AngleVectors( ent->currentAngles, throwDir, NULL, NULL ); - VectorMA( ent->currentOrigin, ent->maxs[0]+4, throwDir, ent->currentOrigin ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorScale( throwDir, 300, ent->s.pos.trDelta ); + AngleVectors(ent->currentAngles, throwDir, NULL, NULL); + VectorMA(ent->currentOrigin, ent->maxs[0] + 4, throwDir, ent->currentOrigin); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorScale(throwDir, 300, ent->s.pos.trDelta); ent->s.pos.trDelta[2] += 150; - VectorMA( ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta ); - ent->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorMA(ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta); + ent->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->owner = self; // make it explode, but with less damage ent->splashDamage /= 3; ent->splashRadius /= 3; ent->e_ThinkFunc = thinkF_WP_Explode; - ent->nextthink = level.time + Q_irand( 500, 3000 ); + ent->nextthink = level.time + Q_irand(500, 3000); } } - } - else if ( dist < ent->splashRadius - && self->client->ps.groundEntityNum != ENTITYNUM_NONE - && ( DotProduct( dir, forward ) < SABER_REFLECT_MISSILE_CONE - || !WP_ForcePowerUsable( self, FP_PUSH, 0 ) ) ) - {//NPCs try to evade it + } else if (dist < ent->splashRadius && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (DotProduct(dir, forward) < SABER_REFLECT_MISSILE_CONE || !WP_ForcePowerUsable(self, FP_PUSH, 0))) { // NPCs try to evade it self->client->ps.forceJumpCharge = 480; - } - else if ( (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) ) - {//else, try to force-throw it away - if ( !ent->owner || !OnSameTeam( self, ent->owner ) ) - { - //FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( self, qfalse ); + } else if ((self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER)) { // else, try to force-throw it away + if (!ent->owner || !OnSameTeam(self, ent->owner)) { + // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(self, qfalse); } } - //otherwise, can't block it, so we're screwed + // otherwise, can't block it, so we're screwed continue; } } } - if ( ent->s.weapon != WP_SABER ) - {//only block shots coming from behind - if ( (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE ) + if (ent->s.weapon != WP_SABER) { // only block shots coming from behind + if ((dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE) continue; - } - else if ( !self->s.number ) - {//player never auto-blocks thrown sabers + } else if (!self->s.number) { // player never auto-blocks thrown sabers continue; - }//NPCs always try to block sabers coming from behind! + } // NPCs always try to block sabers coming from behind! - //see if they're heading towards me - VectorCopy( ent->s.pos.trDelta, missile_dir ); - VectorNormalize( missile_dir ); - if ( (dot2 = DotProduct( dir, missile_dir )) > 0 ) + // see if they're heading towards me + VectorCopy(ent->s.pos.trDelta, missile_dir); + VectorNormalize(missile_dir); + if ((dot2 = DotProduct(dir, missile_dir)) > 0) continue; - //FIXME: must have a clear trace to me, too... - if ( dist < closestDist ) - { - VectorCopy( self->currentOrigin, traceTo ); + // FIXME: must have a clear trace to me, too... + if (dist < closestDist) { + VectorCopy(self->currentOrigin, traceTo); traceTo[2] = self->absmax[2] - 4; - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//okay, try one more check - VectorNormalize2( ent->s.pos.trDelta, entDir ); - VectorMA( ent->currentOrigin, radius, entDir, traceTo ); - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//can't hit me, ignore it + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // okay, try one more check + VectorNormalize2(ent->s.pos.trDelta, entDir); + VectorMA(ent->currentOrigin, radius, entDir, traceTo); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, (EG2_Collision)0, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // can't hit me, ignore it continue; } } - if ( self->s.number != 0 ) - {//An NPC - if ( self->NPC && !self->enemy && ent->owner ) - { - if ( ent->owner->health >= 0 && (!ent->owner->client || ent->owner->client->playerTeam != self->client->playerTeam) ) - { - G_SetEnemy( self, ent->owner ); + if (self->s.number != 0) { // An NPC + if (self->NPC && !self->enemy && ent->owner) { + if (ent->owner->health >= 0 && (!ent->owner->client || ent->owner->client->playerTeam != self->client->playerTeam)) { + G_SetEnemy(self, ent->owner); } } } - //FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box (+/-saberLength?), don't try to deflect unless it does? + // FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box + // (+/-saberLength?), don't try to deflect unless it does? closestDist = dist; incoming = ent; } } - if ( incoming ) - { - if ( self->NPC && !G_ControlledByPlayer( self ) ) - { - if ( Jedi_WaitingAmbush( self ) ) - { - Jedi_Ambush( self ); - } - if ( ( self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER ) - && self->client->moveType == MT_FLYSWIM - && incoming->methodOfDeath != MOD_ROCKET_ALT ) - {//a hovering Boba Fett, not a tracking rocket - if ( !Q_irand( 0, 1 ) ) - {//strafe + if (incoming) { + if (self->NPC && !G_ControlledByPlayer(self)) { + if (Jedi_WaitingAmbush(self)) { + Jedi_Ambush(self); + } + if ((self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->moveType == MT_FLYSWIM && + incoming->methodOfDeath != MOD_ROCKET_ALT) { // a hovering Boba Fett, not a tracking rocket + if (!Q_irand(0, 1)) { // strafe self->NPC->standTime = 0; - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand( 1000, 2000 ); + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand(1000, 2000); } - if ( !Q_irand( 0, 1 ) ) - {//go up/down - TIMER_Set( self, "heightChange", Q_irand( 1000, 3000 ) ); - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand( 1000, 2000 ); + if (!Q_irand(0, 1)) { // go up/down + TIMER_Set(self, "heightChange", Q_irand(1000, 3000)); + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand(1000, 2000); } - } - else if ( self->client->NPC_class != CLASS_ROCKETTROOPER - && Jedi_SaberBlockGo( self, &self->NPC->last_ucmd, NULL, NULL, incoming ) != EVASION_NONE ) - {//make sure to turn on your saber if it's not on - if ( self->client->NPC_class != CLASS_BOBAFETT - && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER) ) - { + } else if (self->client->NPC_class != CLASS_ROCKETTROOPER && + Jedi_SaberBlockGo(self, &self->NPC->last_ucmd, NULL, NULL, incoming) != EVASION_NONE) { // make sure to turn on your saber if it's not on + if (self->client->NPC_class != CLASS_BOBAFETT && (self->client->NPC_class != CLASS_REBORN || self->s.weapon == WP_SABER)) { self->client->ps.SaberActivate(); } } - } - else//player + } else // player { - if ( !(ucmd->buttons & BUTTON_USE) )//self->s.weapon == WP_SABER && self->client->ps.SaberActive() ) - { - WP_SaberBlockNonRandom( self, incoming->currentOrigin, qtrue ); - } - else + if (!(ucmd->buttons & BUTTON_USE)) // self->s.weapon == WP_SABER && self->client->ps.SaberActive() ) { + WP_SaberBlockNonRandom(self, incoming->currentOrigin, qtrue); + } else { vec3_t diff, start, end; float dist; - VectorSubtract( incoming->currentOrigin, self->currentOrigin, diff ); - dist = VectorLength( diff ); - VectorNormalize2( incoming->s.pos.trDelta, entDir ); - VectorMA( incoming->currentOrigin, dist, entDir, start ); - VectorCopy( self->currentOrigin, end ); - end[2] += self->maxs[2]*0.75f; - gi.trace( &trace, start, incoming->mins, incoming->maxs, end, incoming->s.number, MASK_SHOT, G2_COLLIDE, 10 ); + VectorSubtract(incoming->currentOrigin, self->currentOrigin, diff); + dist = VectorLength(diff); + VectorNormalize2(incoming->s.pos.trDelta, entDir); + VectorMA(incoming->currentOrigin, dist, entDir, start); + VectorCopy(self->currentOrigin, end); + end[2] += self->maxs[2] * 0.75f; + gi.trace(&trace, start, incoming->mins, incoming->maxs, end, incoming->s.number, MASK_SHOT, G2_COLLIDE, 10); - Jedi_DodgeEvasion( self, incoming->owner, &trace, HL_NONE ); + Jedi_DodgeEvasion(self, incoming->owner, &trace, HL_NONE); } - if ( incoming->owner && incoming->owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER) )//keep enemy jedi over shooters + if (incoming->owner && incoming->owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER)) // keep enemy jedi over shooters { self->enemy = incoming->owner; - NPC_SetLookTarget( self, incoming->owner->s.number, level.time+1000 ); + NPC_SetLookTarget(self, incoming->owner->s.number, level.time + 1000); } } } } +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ - -void WP_SetSaberMove(gentity_t *self, short blocked) -{ - self->client->ps.saberBlocked = blocked; -} +void WP_SetSaberMove(gentity_t *self, short blocked) { self->client->ps.saberBlocked = blocked; } -extern void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ); -void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ) -{ - //float swap; - float minsize = 16; +extern void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha); +void WP_SaberUpdate(gentity_t *self, usercmd_t *ucmd) { + // float swap; + float minsize = 16; - if(0)// if ( self->s.number != 0 ) - {//for now only the player can do this // not anymore + if (0) // if ( self->s.number != 0 ) + { // for now only the player can do this // not anymore return; } - if ( !self->client ) - { + if (!self->client) { return; } - if ( self->client->ps.saberEntityNum < 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//never got one + if (self->client->ps.saberEntityNum < 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { // never got one return; } // Check if we are throwing it, launch it if needed, update position if needed. WP_SaberThrow(self, ucmd); - - //vec3_t saberloc; - //vec3_t sabermins={-8,-8,-8}, sabermaxs={8,8,8}; + // vec3_t saberloc; + // vec3_t sabermins={-8,-8,-8}, sabermaxs={8,8,8}; gentity_t *saberent; - if (self->client->ps.saberEntityNum <= 0) - {//WTF?!! We lost it? + if (self->client->ps.saberEntityNum <= 0) { // WTF?!! We lost it? return; } saberent = &g_entities[self->client->ps.saberEntityNum]; - //FIXME: Based on difficulty level/jedi saber combat skill, make this bounding box fatter/smaller - if ( self->client->ps.saberBlocked != BLOCKED_NONE ) - {//we're blocking, increase min size + // FIXME: Based on difficulty level/jedi saber combat skill, make this bounding box fatter/smaller + if (self->client->ps.saberBlocked != BLOCKED_NONE) { // we're blocking, increase min size minsize = 32; } - if ( G_InCinematicSaberAnim( self ) ) - {//fake some blocking + if (G_InCinematicSaberAnim(self)) { // fake some blocking self->client->ps.saberBlocking = BLK_TIGHT; - if ( self->client->ps.saber[0].Active() ) - { - self->client->ps.saber[0].ActivateTrail( 150 ); + if (self->client->ps.saber[0].Active()) { + self->client->ps.saber[0].ActivateTrail(150); } - if ( self->client->ps.saber[1].Active() ) - { - self->client->ps.saber[1].ActivateTrail( 150 ); + if (self->client->ps.saber[1].Active()) { + self->client->ps.saber[1].ActivateTrail(150); } } - //is our saber in flight? - if ( !self->client->ps.saberInFlight ) - { // It isn't, which means we can update its position as we will. + // is our saber in flight? + if (!self->client->ps.saberInFlight) { // It isn't, which means we can update its position as we will. qboolean alwaysBlock[MAX_SABERS][MAX_BLADES]; qboolean forceBlock = qfalse; qboolean noBlocking = qfalse; - //clear out last frame's numbers + // clear out last frame's numbers VectorClear(saberent->mins); VectorClear(saberent->maxs); - Vehicle_t *pVeh = G_IsRidingVehicle( self ); - if ( !self->client->ps.SaberActive() - || !self->client->ps.saberBlocking - || PM_InKnockDown( &self->client->ps ) - || PM_SuperBreakLoseAnim( self->client->ps.torsoAnim ) - || (pVeh && pVeh->m_pVehicleInfo && pVeh->m_pVehicleInfo->type != VH_ANIMAL && pVeh->m_pVehicleInfo->type != VH_FLIER) )//riding a vehicle that you cannot block shots on - {//can't block if saber isn't on + Vehicle_t *pVeh = G_IsRidingVehicle(self); + if (!self->client->ps.SaberActive() || !self->client->ps.saberBlocking || PM_InKnockDown(&self->client->ps) || + PM_SuperBreakLoseAnim(self->client->ps.torsoAnim) || + (pVeh && pVeh->m_pVehicleInfo && pVeh->m_pVehicleInfo->type != VH_ANIMAL && + pVeh->m_pVehicleInfo->type != VH_FLIER)) // riding a vehicle that you cannot block shots on + { // can't block if saber isn't on int i, j; - for ( i = 0; i < MAX_SABERS; i++ ) - { - //initialize to not blocking - for ( j = 0; j < MAX_BLADES; j++ ) - { + for (i = 0; i < MAX_SABERS; i++) { + // initialize to not blocking + for (j = 0; j < MAX_BLADES; j++) { alwaysBlock[i][j] = qfalse; } - if ( i > 0 && !self->client->ps.dualSabers ) - {//not using a second saber, leave it not blocking - } - else - { - if ( (self->client->ps.saber[i].saberFlags2&SFL2_ALWAYS_BLOCK) ) - { - for ( j = 0; j < self->client->ps.saber[i].numBlades; j++ ) - { + if (i > 0 && !self->client->ps.dualSabers) { // not using a second saber, leave it not blocking + } else { + if ((self->client->ps.saber[i].saberFlags2 & SFL2_ALWAYS_BLOCK)) { + for (j = 0; j < self->client->ps.saber[i].numBlades; j++) { alwaysBlock[i][j] = qtrue; forceBlock = qtrue; } } - if ( self->client->ps.saber[i].bladeStyle2Start > 0 ) - { - for ( j = self->client->ps.saber[i].bladeStyle2Start; j < self->client->ps.saber[i].numBlades; j++ ) - { - if ( (self->client->ps.saber[i].saberFlags2&SFL2_ALWAYS_BLOCK2) ) - { + if (self->client->ps.saber[i].bladeStyle2Start > 0) { + for (j = self->client->ps.saber[i].bladeStyle2Start; j < self->client->ps.saber[i].numBlades; j++) { + if ((self->client->ps.saber[i].saberFlags2 & SFL2_ALWAYS_BLOCK2)) { alwaysBlock[i][j] = qtrue; forceBlock = qtrue; - } - else - { + } else { alwaysBlock[i][j] = qfalse; } } } } } - if ( !forceBlock ) - { + if (!forceBlock) { noBlocking = qtrue; - } - else if ( !self->client->ps.saberBlocking ) - {//turn blocking on! + } else if (!self->client->ps.saberBlocking) { // turn blocking on! self->client->ps.saberBlocking = BLK_TIGHT; } } - if ( noBlocking ) - { - //VectorClear(saberent->mins); - //VectorClear(saberent->maxs); + if (noBlocking) { + // VectorClear(saberent->mins); + // VectorClear(saberent->maxs); G_SetOrigin(saberent, self->currentOrigin); - } - else if ( self->client->ps.saberBlocking == BLK_TIGHT - || self->client->ps.saberBlocking == BLK_WIDE ) - {//FIXME: keep bbox in front of player, even when wide? - vec3_t saberOrg; - if ( !forceBlock - && ( (self->s.number&&!Jedi_SaberBusy(self)&&!g_saberRealisticCombat->integer) || (self->s.number == 0 && self->client->ps.saberBlocking == BLK_WIDE && (g_saberAutoBlocking->integer||self->client->ps.saberBlockingTime>level.time)) ) - && self->client->ps.weaponTime <= 0 - && !G_InCinematicSaberAnim( self ) ) - {//full-size blocking for non-attacking player with g_saberAutoBlocking on - vec3_t saberang={0,0,0}, fwd, sabermins={-8,-8,-8}, sabermaxs={8,8,8}; + } else if (self->client->ps.saberBlocking == BLK_TIGHT || + self->client->ps.saberBlocking == BLK_WIDE) { // FIXME: keep bbox in front of player, even when wide? + vec3_t saberOrg; + if (!forceBlock && + ((self->s.number && !Jedi_SaberBusy(self) && !g_saberRealisticCombat->integer) || + (self->s.number == 0 && self->client->ps.saberBlocking == BLK_WIDE && + (g_saberAutoBlocking->integer || self->client->ps.saberBlockingTime > level.time))) && + self->client->ps.weaponTime <= 0 && !G_InCinematicSaberAnim(self)) { // full-size blocking for non-attacking player with g_saberAutoBlocking on + vec3_t saberang = {0, 0, 0}, fwd, sabermins = {-8, -8, -8}, sabermaxs = {8, 8, 8}; saberang[YAW] = self->client->ps.viewangles[YAW]; - AngleVectors( saberang, fwd, NULL, NULL ); + AngleVectors(saberang, fwd, NULL, NULL); - VectorMA( self->currentOrigin, 12, fwd, saberOrg ); + VectorMA(self->currentOrigin, 12, fwd, saberOrg); - VectorAdd( self->mins, sabermins, saberent->mins ); - VectorAdd( self->maxs, sabermaxs, saberent->maxs ); + VectorAdd(self->mins, sabermins, saberent->mins); + VectorAdd(self->maxs, sabermaxs, saberent->maxs); saberent->contents = CONTENTS_LIGHTSABER; - G_SetOrigin( saberent, saberOrg ); - } - else - { - vec3_t saberBase, saberTip; + G_SetOrigin(saberent, saberOrg); + } else { + vec3_t saberBase, saberTip; int numSabers = 1; - if ( self->client->ps.dualSabers ) - { + if (self->client->ps.dualSabers) { numSabers = 2; } - for ( int saberNum = 0; saberNum < numSabers; saberNum++ ) - { - for ( int bladeNum = 0; bladeNum < self->client->ps.saber[saberNum].numBlades; bladeNum++ ) - { - if ( self->client->ps.saber[saberNum].blade[bladeNum].length <= 0.0f ) - {//don't include blades that are not on... + for (int saberNum = 0; saberNum < numSabers; saberNum++) { + for (int bladeNum = 0; bladeNum < self->client->ps.saber[saberNum].numBlades; bladeNum++) { + if (self->client->ps.saber[saberNum].blade[bladeNum].length <= 0.0f) { // don't include blades that are not on... continue; } - if ( forceBlock ) - {//doing blade-specific bbox-sizing only, see if this blade should be counted - if ( !alwaysBlock[saberNum][bladeNum] ) - {//this blade doesn't count right now + if (forceBlock) { // doing blade-specific bbox-sizing only, see if this blade should be counted + if (!alwaysBlock[saberNum][bladeNum]) { // this blade doesn't count right now continue; } } - VectorCopy( self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, saberBase ); - VectorMA( saberBase, self->client->ps.saber[saberNum].blade[bladeNum].length, self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, saberTip ); - VectorMA( saberBase, self->client->ps.saber[saberNum].blade[bladeNum].length*0.5, self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, saberOrg ); - for ( int i = 0; i < 3; i++ ) - { + VectorCopy(self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint, saberBase); + VectorMA(saberBase, self->client->ps.saber[saberNum].blade[bladeNum].length, self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, + saberTip); + VectorMA(saberBase, self->client->ps.saber[saberNum].blade[bladeNum].length * 0.5, + self->client->ps.saber[saberNum].blade[bladeNum].muzzleDir, saberOrg); + for (int i = 0; i < 3; i++) { /* if ( saberTip[i] > self->client->ps.saber[saberNum].blade[bladeNum].muzzlePoint[i] ) { @@ -8045,50 +6329,39 @@ void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ) } */ float newSizeTip = (saberTip[i] - saberOrg[i]); - newSizeTip += (newSizeTip>=0)?8:-8; + newSizeTip += (newSizeTip >= 0) ? 8 : -8; float newSizeBase = (saberBase[i] - saberOrg[i]); - newSizeBase += (newSizeBase>=0)?8:-8; - if ( newSizeTip > saberent->maxs[i] ) - { + newSizeBase += (newSizeBase >= 0) ? 8 : -8; + if (newSizeTip > saberent->maxs[i]) { saberent->maxs[i] = newSizeTip; } - if ( newSizeBase > saberent->maxs[i] ) - { + if (newSizeBase > saberent->maxs[i]) { saberent->maxs[i] = newSizeBase; } - if ( newSizeTip < saberent->mins[i] ) - { + if (newSizeTip < saberent->mins[i]) { saberent->mins[i] = newSizeTip; } - if ( newSizeBase < saberent->mins[i] ) - { + if (newSizeBase < saberent->mins[i]) { saberent->mins[i] = newSizeBase; } } } } - if ( !forceBlock ) - {//not doing special "alwaysBlock" bbox - if ( self->client->ps.weaponTime > 0 - || self->s.number - || g_saberAutoBlocking->integer - || self->client->ps.saberBlockingTime > level.time ) - {//if attacking or blocking (or an NPC), inflate to a minimum size - for ( int i = 0; i < 3; i++ ) - { - if ( saberent->maxs[i] < minsize ) - { + if (!forceBlock) { // not doing special "alwaysBlock" bbox + if (self->client->ps.weaponTime > 0 || self->s.number || g_saberAutoBlocking->integer || + self->client->ps.saberBlockingTime > level.time) { // if attacking or blocking (or an NPC), inflate to a minimum size + for (int i = 0; i < 3; i++) { + if (saberent->maxs[i] < minsize) { saberent->maxs[i] = minsize; } - if ( saberent->mins[i] > -minsize ) - { + if (saberent->mins[i] > -minsize) { saberent->mins[i] = -minsize; } } } } saberent->contents = CONTENTS_LIGHTSABER; - G_SetOrigin( saberent, saberOrg ); + G_SetOrigin(saberent, saberOrg); } } /* @@ -8147,507 +6420,391 @@ void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ) G_SetOrigin( saberent, saberloc); } */ - else - { // Otherwise there is no blocking possible. - //VectorClear(saberent->mins); - //VectorClear(saberent->maxs); + else { // Otherwise there is no blocking possible. + // VectorClear(saberent->mins); + // VectorClear(saberent->maxs); G_SetOrigin(saberent, self->currentOrigin); } saberent->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; gi.linkentity(saberent); - } - else - { - WP_SaberInFlightReflectCheck( self, ucmd ); + } else { + WP_SaberInFlightReflectCheck(self, ucmd); } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 2 ) - { - CG_CubeOutline( saberent->absmin, saberent->absmax, 50, WPDEBUG_SaberColor( self->client->ps.saber[0].blade[0].color ), 1 ); + if (d_saberCombat->integer > 2) { + CG_CubeOutline(saberent->absmin, saberent->absmax, 50, WPDEBUG_SaberColor(self->client->ps.saber[0].blade[0].color), 1); } #endif } -#define MAX_RADIUS_ENTS 256 //NOTE: This can cause entities to be lost -qboolean G_CheckEnemyPresence( gentity_t *ent, int dir, float radius, float tolerance ) -{ - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; - vec3_t mins, maxs; - int numEnts; - vec3_t checkDir, dir2checkEnt; - float dist; - int i; - - switch( dir ) - { +#define MAX_RADIUS_ENTS 256 // NOTE: This can cause entities to be lost +qboolean G_CheckEnemyPresence(gentity_t *ent, int dir, float radius, float tolerance) { + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; + vec3_t mins, maxs; + int numEnts; + vec3_t checkDir, dir2checkEnt; + float dist; + int i; + + switch (dir) { case DIR_RIGHT: - AngleVectors( ent->currentAngles, NULL, checkDir, NULL ); + AngleVectors(ent->currentAngles, NULL, checkDir, NULL); break; case DIR_LEFT: - AngleVectors( ent->currentAngles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(ent->currentAngles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); break; case DIR_FRONT: - AngleVectors( ent->currentAngles, checkDir, NULL, NULL ); + AngleVectors(ent->currentAngles, checkDir, NULL, NULL); break; case DIR_BACK: - AngleVectors( ent->currentAngles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(ent->currentAngles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); break; } - //Get all ents in range, see if they're living clients and enemies, then check dot to them... + // Get all ents in range, see if they're living clients and enemies, then check dot to them... - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = ent->currentOrigin[i] - radius; maxs[i] = ent->currentOrigin[i] + radius; } - //Get a number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get a number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - for ( i = 0; i < numEnts; i++ ) - { - //Don't consider self - if ( radiusEnts[i] == ent ) + for (i = 0; i < numEnts; i++) { + // Don't consider self + if (radiusEnts[i] == ent) continue; - //Must be valid - if ( G_ValidEnemy( ent, radiusEnts[i] ) == qfalse ) + // Must be valid + if (G_ValidEnemy(ent, radiusEnts[i]) == qfalse) continue; - VectorSubtract( radiusEnts[i]->currentOrigin, ent->currentOrigin, dir2checkEnt ); - dist = VectorNormalize( dir2checkEnt ); - if ( dist <= radius - && DotProduct( dir2checkEnt, checkDir ) >= tolerance ) - { - //stop on the first one + VectorSubtract(radiusEnts[i]->currentOrigin, ent->currentOrigin, dir2checkEnt); + dist = VectorNormalize(dir2checkEnt); + if (dist <= radius && DotProduct(dir2checkEnt, checkDir) >= tolerance) { + // stop on the first one return qtrue; } } return qfalse; } -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -extern gentity_t *TossClientItems( gentity_t *self ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -void WP_DropWeapon( gentity_t *dropper, vec3_t velocity ) -{ - if ( !dropper || !dropper->client ) - { - return; - } - int replaceWeap = WP_NONE; +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +extern gentity_t *TossClientItems(gentity_t *self); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +void WP_DropWeapon(gentity_t *dropper, vec3_t velocity) { + if (!dropper || !dropper->client) { + return; + } + int replaceWeap = WP_NONE; int oldWeap = dropper->s.weapon; - gentity_t *weapon = TossClientItems( dropper ); - if ( oldWeap == WP_THERMAL && dropper->NPC ) - {//Hmm, maybe all NPCs should go into melee? Not too many, though, or they mob you and look silly + gentity_t *weapon = TossClientItems(dropper); + if (oldWeap == WP_THERMAL && dropper->NPC) { // Hmm, maybe all NPCs should go into melee? Not too many, though, or they mob you and look silly replaceWeap = WP_MELEE; } - if ( dropper->ghoul2.IsValid() ) - { - if ( dropper->weaponModel[0] > 0 ) - {//NOTE: guess you never drop the left-hand weapon, eh? - gi.G2API_RemoveGhoul2Model( dropper->ghoul2, dropper->weaponModel[0] ); + if (dropper->ghoul2.IsValid()) { + if (dropper->weaponModel[0] > 0) { // NOTE: guess you never drop the left-hand weapon, eh? + gi.G2API_RemoveGhoul2Model(dropper->ghoul2, dropper->weaponModel[0]); dropper->weaponModel[0] = -1; } } - //FIXME: does this work on the player? - dropper->client->ps.stats[STAT_WEAPONS] |= ( 1 << replaceWeap ); - if ( !dropper->s.number ) - { - if ( oldWeap == WP_THERMAL ) - { + // FIXME: does this work on the player? + dropper->client->ps.stats[STAT_WEAPONS] |= (1 << replaceWeap); + if (!dropper->s.number) { + if (oldWeap == WP_THERMAL) { dropper->client->ps.ammo[weaponData[oldWeap].ammoIndex] -= weaponData[oldWeap].energyPerShot; + } else { + dropper->client->ps.stats[STAT_WEAPONS] &= ~(1 << oldWeap); } - else - { - dropper->client->ps.stats[STAT_WEAPONS] &= ~( 1 << oldWeap ); - } - CG_ChangeWeapon( replaceWeap ); - } - else - { - dropper->client->ps.stats[STAT_WEAPONS] &= ~( 1 << oldWeap ); + CG_ChangeWeapon(replaceWeap); + } else { + dropper->client->ps.stats[STAT_WEAPONS] &= ~(1 << oldWeap); } - ChangeWeapon( dropper, replaceWeap ); + ChangeWeapon(dropper, replaceWeap); dropper->s.weapon = replaceWeap; - if ( dropper->NPC ) - { + if (dropper->NPC) { dropper->NPC->last_ucmd.weapon = replaceWeap; } - if ( weapon != NULL && velocity && !VectorCompare( velocity, vec3_origin ) ) - {//weapon should have a direction to it's throw - VectorScale( velocity, 3, weapon->s.pos.trDelta );//NOTE: Presumes it is moving already...? - if ( weapon->s.pos.trDelta[2] < 150 ) - {//this is presuming you don't want them to drop the weapon down on you... + if (weapon != NULL && velocity && !VectorCompare(velocity, vec3_origin)) { // weapon should have a direction to it's throw + VectorScale(velocity, 3, weapon->s.pos.trDelta); // NOTE: Presumes it is moving already...? + if (weapon->s.pos.trDelta[2] < 150) { // this is presuming you don't want them to drop the weapon down on you... weapon->s.pos.trDelta[2] = 150; } - //FIXME: gets stuck inside it's former owner... + // FIXME: gets stuck inside it's former owner... weapon->forcePushTime = level.time + 600; // let the push effect last for 600 ms } } -void WP_KnockdownTurret( gentity_t *self, gentity_t *pas ) -{ - //knock it over - VectorCopy( pas->currentOrigin, pas->s.pos.trBase ); +void WP_KnockdownTurret(gentity_t *self, gentity_t *pas) { + // knock it over + VectorCopy(pas->currentOrigin, pas->s.pos.trBase); pas->s.pos.trType = TR_LINEAR_STOP; pas->s.pos.trDuration = 250; pas->s.pos.trTime = level.time; - pas->s.pos.trDelta[2] = ( 12.0f / ( pas->s.pos.trDuration * 0.001f ) ); + pas->s.pos.trDelta[2] = (12.0f / (pas->s.pos.trDuration * 0.001f)); - VectorCopy( pas->currentAngles, pas->s.apos.trBase ); + VectorCopy(pas->currentAngles, pas->s.apos.trBase); pas->s.apos.trType = TR_LINEAR_STOP; pas->s.apos.trDuration = 250; pas->s.apos.trTime = level.time; - //FIXME: pick pitch/roll that always tilts it directly away from pusher - pas->s.apos.trDelta[PITCH] = ( 100.0f / ( pas->s.apos.trDuration * 0.001f ) ); + // FIXME: pick pitch/roll that always tilts it directly away from pusher + pas->s.apos.trDelta[PITCH] = (100.0f / (pas->s.apos.trDuration * 0.001f)); - //kill it + // kill it pas->count = 0; pas->nextthink = -1; - G_Sound( pas, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); - //push effect? + G_Sound(pas, G_SoundIndex("sound/chars/turret/shutdown.wav")); + // push effect? pas->forcePushTime = level.time + 600; // let the push effect last for 600 ms } -void WP_ForceThrowHazardTrooper( gentity_t *self, gentity_t *trooper, qboolean pull ) -{ - if ( !self || !self->client ) - { +void WP_ForceThrowHazardTrooper(gentity_t *self, gentity_t *trooper, qboolean pull) { + if (!self || !self->client) { return; } - if ( !trooper || !trooper->client ) - { + if (!trooper || !trooper->client) { return; } - //all levels: see effect on them, they notice us + // all levels: see effect on them, they notice us trooper->forcePushTime = level.time + 600; // let the push effect last for 600 ms - if ( (pull&&self->client->ps.forcePowerLevel[FP_PULL]>FORCE_LEVEL_1) - || (!pull&&self->client->ps.forcePowerLevel[FP_PUSH]>FORCE_LEVEL_1) ) - {//level 2: they stop for a couple seconds and make a sound - trooper->painDebounceTime = level.time + Q_irand( 1500, 2500 ); - G_AddVoiceEvent( trooper, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand( 1000, 3000 ) ); - GEntity_PainFunc( trooper, self, self, trooper->currentOrigin, 0, MOD_MELEE ); - - if ( (pull&&self->client->ps.forcePowerLevel[FP_PULL]>FORCE_LEVEL_2) - || (!pull&&self->client->ps.forcePowerLevel[FP_PUSH]>FORCE_LEVEL_2) ) - {//level 3: they actually play a pushed anim and stumble a bit - vec3_t hazAngles = {0,trooper->currentAngles[YAW],0}; + if ((pull && self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1) || + (!pull && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1)) { // level 2: they stop for a couple seconds and make a sound + trooper->painDebounceTime = level.time + Q_irand(1500, 2500); + G_AddVoiceEvent(trooper, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand(1000, 3000)); + GEntity_PainFunc(trooper, self, self, trooper->currentOrigin, 0, MOD_MELEE); + + if ((pull && self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_2) || + (!pull && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2)) { // level 3: they actually play a pushed anim and stumble a bit + vec3_t hazAngles = {0, trooper->currentAngles[YAW], 0}; int anim = -1; - if ( InFront( self->currentOrigin, trooper->currentOrigin, hazAngles ) ) - {//I'm on front of him - if ( pull ) - { + if (InFront(self->currentOrigin, trooper->currentOrigin, hazAngles)) { // I'm on front of him + if (pull) { anim = BOTH_PAIN4; - } - else - { + } else { anim = BOTH_PAIN1; } - } - else - {//I'm behind him - if ( pull ) - { + } else { // I'm behind him + if (pull) { anim = BOTH_PAIN1; - } - else - { + } else { anim = BOTH_PAIN4; } } - if ( anim != -1 ) - { - if ( anim == BOTH_PAIN1 ) - {//make them take a couple steps back - AngleVectors( hazAngles, trooper->client->ps.velocity, NULL, NULL ); - VectorScale( trooper->client->ps.velocity, -40.0f, trooper->client->ps.velocity ); + if (anim != -1) { + if (anim == BOTH_PAIN1) { // make them take a couple steps back + AngleVectors(hazAngles, trooper->client->ps.velocity, NULL, NULL); + VectorScale(trooper->client->ps.velocity, -40.0f, trooper->client->ps.velocity); trooper->client->ps.pm_flags |= PMF_TIME_NOFRICTION; - } - else if ( anim == BOTH_PAIN4 ) - {//make them stumble forward - AngleVectors( hazAngles, trooper->client->ps.velocity, NULL, NULL ); - VectorScale( trooper->client->ps.velocity, 80.0f, trooper->client->ps.velocity ); + } else if (anim == BOTH_PAIN4) { // make them stumble forward + AngleVectors(hazAngles, trooper->client->ps.velocity, NULL, NULL); + VectorScale(trooper->client->ps.velocity, 80.0f, trooper->client->ps.velocity); trooper->client->ps.pm_flags |= PMF_TIME_NOFRICTION; } - NPC_SetAnim( trooper, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(trooper, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); trooper->painDebounceTime += trooper->client->ps.torsoAnimTimer; trooper->client->ps.pm_time = trooper->client->ps.torsoAnimTimer; } } - if ( trooper->NPC ) - { - if ( trooper->NPC->shotTime < trooper->painDebounceTime ) - { + if (trooper->NPC) { + if (trooper->NPC->shotTime < trooper->painDebounceTime) { trooper->NPC->shotTime = trooper->painDebounceTime; } } - trooper->client->ps.weaponTime = trooper->painDebounceTime-level.time; - } - else - {//level 1: no pain reaction, but they should still notice - if ( trooper->enemy == NULL//not mad at anyone - && trooper->client->playerTeam != self->client->playerTeam//not on our team - && !(trooper->svFlags&SVF_LOCKEDENEMY)//not locked on an enemy - && !(trooper->svFlags&SVF_IGNORE_ENEMIES)//not ignoring enemie - && !(self->flags&FL_NOTARGET) )//I'm not in notarget - {//not already mad at them and can get mad at them, do so - G_SetEnemy( trooper, self ); + trooper->client->ps.weaponTime = trooper->painDebounceTime - level.time; + } else { // level 1: no pain reaction, but they should still notice + if (trooper->enemy == NULL // not mad at anyone + && trooper->client->playerTeam != self->client->playerTeam // not on our team + && !(trooper->svFlags & SVF_LOCKEDENEMY) // not locked on an enemy + && !(trooper->svFlags & SVF_IGNORE_ENEMIES) // not ignoring enemie + && !(self->flags & FL_NOTARGET)) // I'm not in notarget + { // not already mad at them and can get mad at them, do so + G_SetEnemy(trooper, self); } } } -void WP_ResistForcePush( gentity_t *self, gentity_t *pusher, qboolean noPenalty ) -{ +void WP_ResistForcePush(gentity_t *self, gentity_t *pusher, qboolean noPenalty) { int parts; qboolean runningResist = qfalse; - if ( !self || self->health <= 0 || !self->client || !pusher || !pusher->client ) - { + if (!self || self->health <= 0 || !self->client || !pusher || !pusher->client) { return; } - //NOTE: don't interrupt big anims with this! - if ( !PM_SaberCanInterruptMove( self->client->ps.saberMove, self->client->ps.torsoAnim ) ) - {//can't interrupt my current torso anim/sabermove with this, so ignore it entirely! + // NOTE: don't interrupt big anims with this! + if (!PM_SaberCanInterruptMove(self->client->ps.saberMove, + self->client->ps.torsoAnim)) { // can't interrupt my current torso anim/sabermove with this, so ignore it entirely! return; } - if ( (!self->s.number - ||( self->NPC && (self->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) - ||( self->client && self->client->NPC_class == CLASS_SHADOWTROOPER ) - /* - || self->client->NPC_class == CLASS_DESANN - || !Q_stricmp("Yoda",self->NPC_type) - || self->client->NPC_class == CLASS_LUKE*/ - ) - && (VectorLengthSquared( self->client->ps.velocity ) > 10000 || self->client->ps.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 ) ) - { + if ((!self->s.number || (self->NPC && (self->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) || (self->client && self->client->NPC_class == CLASS_SHADOWTROOPER) + /* + || self->client->NPC_class == CLASS_DESANN + || !Q_stricmp("Yoda",self->NPC_type) + || self->client->NPC_class == CLASS_LUKE*/ + ) && + (VectorLengthSquared(self->client->ps.velocity) > 10000 || self->client->ps.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || + self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3)) { runningResist = qtrue; } - if ( !runningResist - && self->client->ps.groundEntityNum != ENTITYNUM_NONE - && !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_CrouchAnim( self->client->ps.legsAnim )) - {//if on a surface and not in a spin or flip, play full body resist + if (!runningResist && self->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && !PM_InKnockDown(&self->client->ps) && + !PM_CrouchAnim(self->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body resist parts = SETANIM_BOTH; - } - else - {//play resist just in torso + } else { // play resist just in torso parts = SETANIM_TORSO; } - NPC_SetAnim( self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( !noPenalty ) - { - if ( !runningResist ) - { - VectorClear( self->client->ps.velocity ); - //still stop them from attacking or moving for a bit, though - //FIXME: maybe push just a little (like, slide)? + if (!noPenalty) { + if (!runningResist) { + VectorClear(self->client->ps.velocity); + // still stop them from attacking or moving for a bit, though + // FIXME: maybe push just a little (like, slide)? self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } self->client->ps.pm_time = self->client->ps.weaponTime; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //play the full body push effect on me + // play the full body push effect on me self->forcePushTime = level.time + 600; // let the push effect last for 600 ms - } - else - { + } else { self->client->ps.weaponTime = 600; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } } - //play my force push effect on my hand - //self->client->ps.powerups[PW_FORCE_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; + // play my force push effect on my hand + // self->client->ps.powerups[PW_FORCE_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; - //reset to 0 in case it's still > 0 from a previous push - //self->client->pushEffectFadeTime = 0; - if ( !pusher //??? - || pusher == self->enemy//my enemy tried to push me - || (pusher->client && pusher->client->playerTeam != self->client->playerTeam) )//someone not on my team tried to push me + // reset to 0 in case it's still > 0 from a previous push + // self->client->pushEffectFadeTime = 0; + if (!pusher //??? + || pusher == self->enemy // my enemy tried to push me + || (pusher->client && pusher->client->playerTeam != self->client->playerTeam)) // someone not on my team tried to push me { - Jedi_PlayBlockedPushSound( self ); + Jedi_PlayBlockedPushSound(self); } } -extern qboolean Boba_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown ); -extern qboolean Jedi_StopKnockdown( gentity_t *self, gentity_t *pusher, const vec3_t pushDir ); -void WP_ForceKnockdown( gentity_t *self, gentity_t *pusher, qboolean pull, qboolean strongKnockdown, qboolean breakSaberLock ) -{ - if ( !self || !self->client || !pusher || !pusher->client ) - { +extern qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir, qboolean forceKnockdown); +extern qboolean Jedi_StopKnockdown(gentity_t *self, gentity_t *pusher, const vec3_t pushDir); +void WP_ForceKnockdown(gentity_t *self, gentity_t *pusher, qboolean pull, qboolean strongKnockdown, qboolean breakSaberLock) { + if (!self || !self->client || !pusher || !pusher->client) { return; } - if ( self->client->NPC_class == CLASS_ROCKETTROOPER ) - { + if (self->client->NPC_class == CLASS_ROCKETTROOPER) { return; - } - else if ( PM_LockedAnim( self->client->ps.legsAnim ) ) - {//stuck doing something else + } else if (PM_LockedAnim(self->client->ps.legsAnim)) { // stuck doing something else return; - } - else if ( Rosh_BeingHealed( self ) ) - { + } else if (Rosh_BeingHealed(self)) { return; } - //break out of a saberLock? - if ( self->client->ps.saberLockTime > level.time ) - { - if ( breakSaberLock - || (pusher && self->client->ps.saberLockEnemy == pusher->s.number) ) - { + // break out of a saberLock? + if (self->client->ps.saberLockTime > level.time) { + if (breakSaberLock || (pusher && self->client->ps.saberLockEnemy == pusher->s.number)) { self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; - } - else - { + } else { return; } } - if ( self->health > 0 ) - { - if ( !self->s.number ) - { - NPC_SetPainEvent( self ); - } - else - { - GEntity_PainFunc( self, pusher, pusher, self->currentOrigin, 0, MOD_MELEE ); + if (self->health > 0) { + if (!self->s.number) { + NPC_SetPainEvent(self); + } else { + GEntity_PainFunc(self, pusher, pusher, self->currentOrigin, 0, MOD_MELEE); } - vec3_t pushDir; - if ( pull ) - { - VectorSubtract( pusher->currentOrigin, self->currentOrigin, pushDir ); - } - else - { - VectorSubtract( self->currentOrigin, pusher->currentOrigin, pushDir ); + vec3_t pushDir; + if (pull) { + VectorSubtract(pusher->currentOrigin, self->currentOrigin, pushDir); + } else { + VectorSubtract(self->currentOrigin, pusher->currentOrigin, pushDir); } - //FIXME: sometimes do this for some NPC force-users, too! - if ( Boba_StopKnockdown( self, pusher, pushDir, qtrue ) ) - {//He can backflip instead of be knocked down + // FIXME: sometimes do this for some NPC force-users, too! + if (Boba_StopKnockdown(self, pusher, pushDir, qtrue)) { // He can backflip instead of be knocked down return; - } - else if ( Jedi_StopKnockdown( self, pusher, pushDir ) ) - {//They can backflip instead of be knocked down + } else if (Jedi_StopKnockdown(self, pusher, pushDir)) { // They can backflip instead of be knocked down return; } - G_CheckLedgeDive( self, 72, pushDir, qfalse, qfalse ); + G_CheckLedgeDive(self, 72, pushDir, qfalse, qfalse); - if ( !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - { - int knockAnim = BOTH_KNOCKDOWN1;//default knockdown - if ( pusher->client->NPC_class == CLASS_DESANN && self->client->NPC_class != CLASS_LUKE ) - {//desann always knocks down, unless you're Luke + if (!PM_SpinningSaberAnim(self->client->ps.legsAnim) && !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && + !PM_InKnockDown(&self->client->ps)) { + int knockAnim = BOTH_KNOCKDOWN1; // default knockdown + if (pusher->client->NPC_class == CLASS_DESANN && self->client->NPC_class != CLASS_LUKE) { // desann always knocks down, unless you're Luke strongKnockdown = qtrue; } - if ( !self->s.number - && !strongKnockdown - && ( (!pull&&(self->client->ps.forcePowerLevel[FP_PUSH]>FORCE_LEVEL_1||!g_spskill->integer)) || (pull&&(self->client->ps.forcePowerLevel[FP_PULL]>FORCE_LEVEL_1||!g_spskill->integer)) ) ) - {//player only knocked down if pushed *hard* - if ( self->s.weapon == WP_SABER ) - {//temp HACK: these are the only 2 pain anims that look good when holding a saber - knockAnim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); - } - else - { - knockAnim = PM_PickAnim( self, BOTH_PAIN1, BOTH_PAIN18 ); + if (!self->s.number && !strongKnockdown && + ((!pull && (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1 || !g_spskill->integer)) || + (pull && (self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 || !g_spskill->integer)))) { // player only knocked down if pushed *hard* + if (self->s.weapon == WP_SABER) { // temp HACK: these are the only 2 pain anims that look good when holding a saber + knockAnim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else { + knockAnim = PM_PickAnim(self, BOTH_PAIN1, BOTH_PAIN18); } - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - {//crouched knockdown + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { // crouched knockdown knockAnim = BOTH_KNOCKDOWN4; - } - else - {//plain old knockdown - vec3_t pLFwd, pLAngles = {0,self->client->ps.viewangles[YAW],0}; - vec3_t sFwd, sAngles = {0,pusher->client->ps.viewangles[YAW],0}; - AngleVectors( pLAngles, pLFwd, NULL, NULL ); - AngleVectors( sAngles, sFwd, NULL, NULL ); - if ( DotProduct( sFwd, pLFwd ) > 0.2f ) - {//pushing him from behind - //FIXME: check to see if we're aiming below or above the waist? - if ( pull ) - { + } else { // plain old knockdown + vec3_t pLFwd, pLAngles = {0, self->client->ps.viewangles[YAW], 0}; + vec3_t sFwd, sAngles = {0, pusher->client->ps.viewangles[YAW], 0}; + AngleVectors(pLAngles, pLFwd, NULL, NULL); + AngleVectors(sAngles, sFwd, NULL, NULL); + if (DotProduct(sFwd, pLFwd) > 0.2f) { // pushing him from behind + // FIXME: check to see if we're aiming below or above the waist? + if (pull) { knockAnim = BOTH_KNOCKDOWN1; - } - else - { + } else { knockAnim = BOTH_KNOCKDOWN3; } - } - else - {//pushing him from front - if ( pull ) - { + } else { // pushing him from front + if (pull) { knockAnim = BOTH_KNOCKDOWN3; - } - else - { + } else { knockAnim = BOTH_KNOCKDOWN1; } } } - if ( knockAnim == BOTH_KNOCKDOWN1 && strongKnockdown ) - {//push *hard* + if (knockAnim == BOTH_KNOCKDOWN1 && strongKnockdown) { // push *hard* knockAnim = BOTH_KNOCKDOWN2; } - NPC_SetAnim( self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->s.number >= MAX_CLIENTS ) - {//randomize getup times - but not for boba + NPC_SetAnim(self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (self->s.number >= MAX_CLIENTS) { // randomize getup times - but not for boba int addTime; - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - addTime = Q_irand( -500, 0 ); - } - else - { - addTime = Q_irand( -300, 300 ); + if (self->client->NPC_class == CLASS_BOBAFETT) { + addTime = Q_irand(-500, 0); + } else { + addTime = Q_irand(-300, 300); } self->client->ps.legsAnimTimer += addTime; self->client->ps.torsoAnimTimer += addTime; - } - else - {//player holds extra long so you have more time to decide to do the quick getup - if ( PM_KnockDownAnim( self->client->ps.legsAnim ) ) - { + } else { // player holds extra long so you have more time to decide to do the quick getup + if (PM_KnockDownAnim(self->client->ps.legsAnim)) { self->client->ps.legsAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; self->client->ps.torsoAnimTimer += PLAYER_KNOCKDOWN_HOLD_EXTRA_TIME; } } // - if ( pusher->NPC && pusher->enemy == self ) - {//pushed pushed down his enemy - G_AddVoiceEvent( pusher, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 3000 ); + if (pusher->NPC && pusher->enemy == self) { // pushed pushed down his enemy + G_AddVoiceEvent(pusher, Q_irand(EV_GLOAT1, EV_GLOAT3), 3000); pusher->NPC->blockedSpeechDebounceTime = level.time + 3000; } } @@ -8655,163 +6812,110 @@ void WP_ForceKnockdown( gentity_t *self, gentity_t *pusher, qboolean pull, qbool self->forcePushTime = level.time + 600; // let the push effect last for 600 ms } -qboolean WP_ForceThrowable( gentity_t *ent, gentity_t *forwardEnt, gentity_t *self, qboolean pull, float cone, float radius, vec3_t forward ) -{ +qboolean WP_ForceThrowable(gentity_t *ent, gentity_t *forwardEnt, gentity_t *self, qboolean pull, float cone, float radius, vec3_t forward) { if (ent == self) return qfalse; - if ( ent->owner == self && ent->s.weapon != WP_THERMAL )//can push your own thermals + if (ent->owner == self && ent->s.weapon != WP_THERMAL) // can push your own thermals return qfalse; - if ( !(ent->inuse) ) + if (!(ent->inuse)) return qfalse; - if ( ent->NPC && ent->NPC->scriptFlags & SCF_NO_FORCE ) - { - if ( ent->s.weapon == WP_SABER ) - {//Hmm, should jedi do the resist behavior? If this is on, perhaps it's because of a cinematic? - WP_ResistForcePush( ent, self, qtrue ); + if (ent->NPC && ent->NPC->scriptFlags & SCF_NO_FORCE) { + if (ent->s.weapon == WP_SABER) { // Hmm, should jedi do the resist behavior? If this is on, perhaps it's because of a cinematic? + WP_ResistForcePush(ent, self, qtrue); } return qfalse; } - if ( (ent->flags&FL_FORCE_PULLABLE_ONLY) && !pull ) - {//simple HACK: cannot force-push ammo rack items (because they may start in solid) + if ((ent->flags & FL_FORCE_PULLABLE_ONLY) && !pull) { // simple HACK: cannot force-push ammo rack items (because they may start in solid) return qfalse; } - //FIXME: don't push it if I already pushed it a little while ago - if ( ent->s.eType != ET_MISSILE ) - { - if ( ent->client ) - { - if ( ent->client->ps.pullAttackTime > level.time ) - { + // FIXME: don't push it if I already pushed it a little while ago + if (ent->s.eType != ET_MISSILE) { + if (ent->client) { + if (ent->client->ps.pullAttackTime > level.time) { return qfalse; } } - if ( cone >= 1.0f ) - {//must be pointing right at them - if ( ent != forwardEnt ) - {//must be the person I'm looking right at - if ( ent->client && !pull - && ent->client->ps.forceGripEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_GRIPPED) ) - {//this is the guy that's force-gripping me, use a wider cone regardless of force power level - } - else - { - if ( ent->client && !pull - && ent->client->ps.forceDrainEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_DRAINED) ) - {//this is the guy that's force-draining me, use a wider cone regardless of force power level - } - else - { + if (cone >= 1.0f) { // must be pointing right at them + if (ent != forwardEnt) { // must be the person I'm looking right at + if (ent->client && !pull && ent->client->ps.forceGripEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_GRIPPED)) { // this is the guy that's force-gripping me, use a wider cone regardless of force power level + } else { + if (ent->client && !pull && ent->client->ps.forceDrainEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_DRAINED)) { // this is the guy that's force-draining me, use a wider cone regardless of force power level + } else { return qfalse; } } } } - if ( ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject )//|| !(ent->flags&FL_DROPPED_ITEM) )//was only dropped items + if (ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject) //|| !(ent->flags&FL_DROPPED_ITEM) )//was only dropped items { - //FIXME: need pushable objects - if ( ent->s.eFlags & EF_NODRAW ) - { + // FIXME: need pushable objects + if (ent->s.eFlags & EF_NODRAW) { return qfalse; } - if ( !ent->client ) - { - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber - if ( !(ent->svFlags&SVF_GLASS_BRUSH) ) - {//and not glass - if ( Q_stricmp( "func_door", ent->classname ) != 0 || !(ent->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/) ) - {//not a force-usable door - if ( Q_stricmp( "func_static", ent->classname ) != 0 || (!(ent->spawnflags&1/*F_PUSH*/)&&!(ent->spawnflags&2/*F_PULL*/)) || (ent->spawnflags&32/*SOLITARY*/) ) - {//not a force-usable func_static or, it is one, but it's solitary, so you only press it when looking right at it - if ( Q_stricmp( "limb", ent->classname ) ) - {//not a limb - if ( ent->s.weapon == WP_TURRET && !Q_stricmp( "PAS", ent->classname ) && ent->s.apos.trType == TR_STATIONARY ) - {//can knock over placed turrets - if ( !self->s.number || self->enemy != ent ) - {//only NPCs who are actively mad at this turret can push it over + if (!ent->client) { + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber + if (!(ent->svFlags & SVF_GLASS_BRUSH)) { // and not glass + if (Q_stricmp("func_door", ent->classname) != 0 || !(ent->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/)) { // not a force-usable door + if (Q_stricmp("func_static", ent->classname) != 0 || (!(ent->spawnflags & 1 /*F_PUSH*/) && !(ent->spawnflags & 2 /*F_PULL*/)) || + (ent->spawnflags & 32 /*SOLITARY*/)) { // not a force-usable func_static or, it is one, but it's solitary, so you only press it + // when looking right at it + if (Q_stricmp("limb", ent->classname)) { // not a limb + if (ent->s.weapon == WP_TURRET && !Q_stricmp("PAS", ent->classname) && + ent->s.apos.trType == TR_STATIONARY) { // can knock over placed turrets + if (!self->s.number || self->enemy != ent) { // only NPCs who are actively mad at this turret can push it over return qfalse; } - } - else - { + } else { return qfalse; } } } - } - else if ( ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2 ) - {//not at rest + } else if (ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2) { // not at rest return qfalse; } } } - //return qfalse; - } - else if ( ent->client->NPC_class == CLASS_MARK1 ) - {//can't push Mark1 unless push 3 - if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - { + // return qfalse; + } else if (ent->client->NPC_class == CLASS_MARK1) { // can't push Mark1 unless push 3 + if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3) { return qfalse; } - } - else if ( ent->client->NPC_class == CLASS_GALAKMECH - || ent->client->NPC_class == CLASS_ATST - || ent->client->NPC_class == CLASS_RANCOR - || ent->client->NPC_class == CLASS_WAMPA - || ent->client->NPC_class == CLASS_SAND_CREATURE ) - {//can't push ATST or Galak or Rancor or Wampa + } else if (ent->client->NPC_class == CLASS_GALAKMECH || ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_RANCOR || + ent->client->NPC_class == CLASS_WAMPA || ent->client->NPC_class == CLASS_SAND_CREATURE) { // can't push ATST or Galak or Rancor or Wampa return qfalse; - } - else if ( ent->s.weapon == WP_EMPLACED_GUN ) - {//FIXME: maybe can pull them out? + } else if (ent->s.weapon == WP_EMPLACED_GUN) { // FIXME: maybe can pull them out? return qfalse; - } - else if ( ent->client->playerTeam == self->client->playerTeam && self->enemy && self->enemy != ent ) - {//can't accidently push a teammate while in combat + } else if (ent->client->playerTeam == self->client->playerTeam && self->enemy && + self->enemy != ent) { // can't accidently push a teammate while in combat return qfalse; - } - else if ( G_IsRidingVehicle( ent ) - && (ent->s.eFlags&EF_NODRAW) ) - {//can't push/pull anyone riding *inside* vehicle + } else if (G_IsRidingVehicle(ent) && (ent->s.eFlags & EF_NODRAW)) { // can't push/pull anyone riding *inside* vehicle return qfalse; } - } - else if ( ent->s.eType == ET_ITEM ) - { - if ( (ent->flags&FL_NO_KNOCKBACK) ) - { + } else if (ent->s.eType == ET_ITEM) { + if ((ent->flags & FL_NO_KNOCKBACK)) { return qfalse; } - if ( ent->item - && ent->item->giType == IT_HOLDABLE - && ent->item->giTag == INV_SECURITY_KEY ) - //&& (ent->flags&FL_DROPPED_ITEM) ??? - {//dropped security keys can't be pushed? But placed ones can...? does this make any sense? - if ( !pull || self->s.number ) - {//can't push, NPC's can't do anything to it + if (ent->item && ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY) + //&& (ent->flags&FL_DROPPED_ITEM) ??? + { // dropped security keys can't be pushed? But placed ones can...? does this make any sense? + if (!pull || self->s.number) { // can't push, NPC's can't do anything to it return qfalse; - } - else - { - if ( g_crosshairEntNum != ent->s.number ) - {//player can pull it if looking *right* at it - if ( cone >= 1.0f ) - {//we did a forwardEnt trace - if ( forwardEnt != ent ) - {//must be pointing right at them + } else { + if (g_crosshairEntNum != ent->s.number) { // player can pull it if looking *right* at it + if (cone >= 1.0f) { // we did a forwardEnt trace + if (forwardEnt != ent) { // must be pointing right at them return qfalse; } - } - else if ( forward ) - {//do a forwardEnt trace + } else if (forward) { // do a forwardEnt trace trace_t tr; vec3_t end; - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, (EG2_Collision)0, 0 );//was MASK_SHOT, changed to match crosshair trace - if ( tr.entityNum != ent->s.number ) - {//last chance + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, (EG2_Collision)0, + 0); // was MASK_SHOT, changed to match crosshair trace + if (tr.entityNum != ent->s.number) { // last chance return qfalse; } } @@ -8819,11 +6923,8 @@ qboolean WP_ForceThrowable( gentity_t *ent, gentity_t *forwardEnt, gentity_t *se } } } - } - else - { - switch ( ent->s.weapon ) - {//only missiles with mass are force-pushable + } else { + switch (ent->s.weapon) { // only missiles with mass are force-pushable case WP_SABER: case WP_FLECHETTE: case WP_ROCKET_LAUNCHER: @@ -8832,17 +6933,15 @@ qboolean WP_ForceThrowable( gentity_t *ent, gentity_t *forwardEnt, gentity_t *se case WP_TRIP_MINE: case WP_DET_PACK: break; - //only alt-fire of this weapon is force-pushable + // only alt-fire of this weapon is force-pushable case WP_REPEATER: - if ( ent->methodOfDeath != MOD_REPEATER_ALT ) - {//not an alt-fire missile + if (ent->methodOfDeath != MOD_REPEATER_ALT) { // not an alt-fire missile return qfalse; } break; - //everything else cannot be pushed + // everything else cannot be pushed case WP_ATST_SIDE: - if ( ent->methodOfDeath != MOD_EXPLOSIVE ) - {//not a rocket + if (ent->methodOfDeath != MOD_EXPLOSIVE) { // not a rocket return qfalse; } break; @@ -8851,76 +6950,62 @@ qboolean WP_ForceThrowable( gentity_t *ent, gentity_t *forwardEnt, gentity_t *se break; } - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//can't force-push/pull stuck missiles (detpacks, tripmines) + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // can't force-push/pull stuck missiles (detpacks, tripmines) return qfalse; } - if ( ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL ) - {//only thermal detonators can be pushed once stopped + if (ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL) { // only thermal detonators can be pushed once stopped return qfalse; } } return qtrue; } -static qboolean ShouldPlayerResistForceThrow( gentity_t *player, gentity_t *attacker, qboolean pull ) -{ - if ( player->health <= 0 ) - { +static qboolean ShouldPlayerResistForceThrow(gentity_t *player, gentity_t *attacker, qboolean pull) { + if (player->health <= 0) { return qfalse; } - if ( !player->client ) - { + if (!player->client) { return qfalse; } - if ( player->client->ps.forceRageRecoveryTime >= level.time ) - { + if (player->client->ps.forceRageRecoveryTime >= level.time) { return qfalse; } - //wasn't trying to grip/drain anyone - if ( player->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD || - player->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || - player->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) - { + // wasn't trying to grip/drain anyone + if (player->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD || player->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || + player->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD) { return qfalse; } - //only 30% chance of resisting a Desann or yoda push - if ( (attacker->client->NPC_class == CLASS_DESANN || Q_stricmp("Yoda",attacker->NPC_type) == 0) && Q_irand( 0, 2 ) > 0 ) - { + // only 30% chance of resisting a Desann or yoda push + if ((attacker->client->NPC_class == CLASS_DESANN || Q_stricmp("Yoda", attacker->NPC_type) == 0) && Q_irand(0, 2) > 0) { return qfalse; } - //on the ground - if ( player->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + // on the ground + if (player->client->ps.groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - //not knocked down already - if ( PM_InKnockDown( &player->client->ps ) ) - { + // not knocked down already + if (PM_InKnockDown(&player->client->ps)) { return qfalse; } - //not involved in a saberLock - if ( player->client->ps.saberLockTime >= level.time ) - { + // not involved in a saberLock + if (player->client->ps.saberLockTime >= level.time) { return qfalse; } - //not attacking or otherwise busy - if ( player->client->ps.weaponTime >= level.time ) - { + // not attacking or otherwise busy + if (player->client->ps.weaponTime >= level.time) { return qfalse; } - //using saber or fists - if ( player->client->ps.weapon != WP_SABER && player->client->ps.weapon != WP_MELEE ) - { + // using saber or fists + if (player->client->ps.weapon != WP_SABER && player->client->ps.weapon != WP_MELEE) { return qfalse; } @@ -8928,13 +7013,10 @@ static qboolean ShouldPlayerResistForceThrow( gentity_t *player, gentity_t *atta int attackingForceLevel = attacker->client->ps.forcePowerLevel[forcePower]; int defendingForceLevel = player->client->ps.forcePowerLevel[forcePower]; - if ( player->client->ps.powerups[PW_FORCE_PUSH] > level.time || - Q_irand( 0, Q_max(0, defendingForceLevel - attackingForceLevel)*2 + 1 ) > 0 ) - { + if (player->client->ps.powerups[PW_FORCE_PUSH] > level.time || Q_irand(0, Q_max(0, defendingForceLevel - attackingForceLevel) * 2 + 1) > 0) { // player was pushing, or player's force push/pull is high enough to try to stop me - if ( InFront( attacker->currentOrigin, player->client->renderInfo.eyePoint, player->client->ps.viewangles, 0.3f ) ) - { - //I'm in front of player + if (InFront(attacker->currentOrigin, player->client->renderInfo.eyePoint, player->client->ps.viewangles, 0.3f)) { + // I'm in front of player return qtrue; } } @@ -8942,175 +7024,142 @@ static qboolean ShouldPlayerResistForceThrow( gentity_t *player, gentity_t *atta return qfalse; } -void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) -{//FIXME: pass in a target ent so we (an NPC) can push/pull just one targeted ent. - //shove things in front of you away - float dist; - gentity_t *ent, *forwardEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *push_list[MAX_GENTITIES]; - int numListedEntities = 0; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - int radius; - vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; - float dot1, cone; - trace_t tr; - int anim, hold, soundIndex, cost, actualCost; - qboolean noResist = qfalse; - - if ( self->health <= 0 ) - { +void ForceThrow(gentity_t *self, qboolean pull, qboolean fake) { // FIXME: pass in a target ent so we (an NPC) can push/pull just one targeted ent. + // shove things in front of you away + float dist; + gentity_t *ent, *forwardEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *push_list[MAX_GENTITIES]; + int numListedEntities = 0; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + int radius; + vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; + float dot1, cone; + trace_t tr; + int anim, hold, soundIndex, cost, actualCost; + qboolean noResist = qfalse; + + if (self->health <= 0) { return; } - if ( self->client->ps.leanofs ) - {//can't force-throw while leaning + if (self->client->ps.leanofs) { // can't force-throw while leaning return; } - if ( self->client->ps.forcePowerDebounce[FP_PUSH] > level.time ) - {//already pushing- now you can't haul someone across the room, sorry + if (self->client->ps.forcePowerDebounce[FP_PUSH] > level.time) { // already pushing- now you can't haul someone across the room, sorry return; } - if ( self->client->ps.forcePowerDebounce[FP_PULL] > level.time ) - {//already pulling- now you can't haul someone across the room, sorry + if (self->client->ps.forcePowerDebounce[FP_PULL] > level.time) { // already pulling- now you can't haul someone across the room, sorry return; } - if ( self->client->ps.pullAttackTime > level.time ) - {//already pull-attacking + if (self->client->ps.pullAttackTime > level.time) { // already pull-attacking return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force throw/pull when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force throw/pull when zoomed in or in cinematic return; } - if ( self->client->ps.saberLockTime > level.time ) - { - if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - {//this can be a way to break out + if (self->client->ps.saberLockTime > level.time) { + if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3) { // this can be a way to break out return; } - //else, I'm breaking my half of the saberlock + // else, I'm breaking my half of the saberlock self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; } - if ( self->client->ps.legsAnim == BOTH_KNOCKDOWN3 - || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F1 && self->client->ps.torsoAnimTimer > 400) - || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F2 && self->client->ps.torsoAnimTimer > 900) - || (self->client->ps.torsoAnim == BOTH_GETUP3 && self->client->ps.torsoAnimTimer > 500) - || (self->client->ps.torsoAnim == BOTH_GETUP4 && self->client->ps.torsoAnimTimer > 300) - || (self->client->ps.torsoAnim == BOTH_GETUP5 && self->client->ps.torsoAnimTimer > 500) ) - {//we're face-down, so we'd only be force-push/pulling the floor + if (self->client->ps.legsAnim == BOTH_KNOCKDOWN3 || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F1 && self->client->ps.torsoAnimTimer > 400) || + (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F2 && self->client->ps.torsoAnimTimer > 900) || + (self->client->ps.torsoAnim == BOTH_GETUP3 && self->client->ps.torsoAnimTimer > 500) || + (self->client->ps.torsoAnim == BOTH_GETUP4 && self->client->ps.torsoAnimTimer > 300) || + (self->client->ps.torsoAnim == BOTH_GETUP5 && self->client->ps.torsoAnimTimer > 500)) { // we're face-down, so we'd only be force-push/pulling the floor return; } - if ( pull ) - { + if (pull) { radius = forcePushPullRadius[self->client->ps.forcePowerLevel[FP_PULL]]; - } - else - { + } else { radius = forcePushPullRadius[self->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( !radius ) - {//no ability to do this yet + if (!radius) { // no ability to do this yet return; } - if ( pull ) - { + if (pull) { cost = forcePowerNeeded[FP_PULL]; - if ( !WP_ForcePowerUsable( self, FP_PULL, cost ) ) - { + if (!WP_ForcePowerUsable(self, FP_PULL, cost)) { return; } - //make sure this plays and that you cannot press fire for about 200ms after this + // make sure this plays and that you cannot press fire for about 200ms after this anim = BOTH_FORCEPULL; - soundIndex = G_SoundIndex( "sound/weapons/force/pull.wav" ); + soundIndex = G_SoundIndex("sound/weapons/force/pull.wav"); hold = 200; - } - else - { + } else { cost = forcePowerNeeded[FP_PUSH]; - if ( !WP_ForcePowerUsable( self, FP_PUSH, cost ) ) - { + if (!WP_ForcePowerUsable(self, FP_PUSH, cost)) { return; } - //make sure this plays and that you cannot press fire for about 1 second after this + // make sure this plays and that you cannot press fire for about 1 second after this anim = BOTH_FORCEPUSH; - soundIndex = G_SoundIndex( "sound/weapons/force/push.wav" ); + soundIndex = G_SoundIndex("sound/weapons/force/push.wav"); hold = 650; } int parts = SETANIM_TORSO; - if ( !PM_InKnockDown( &self->client->ps ) ) - { - if ( self->client->ps.saberLockTime > level.time ) - { + if (!PM_InKnockDown(&self->client->ps)) { + if (self->client->ps.saberLockTime > level.time) { self->client->ps.saberLockTime = 0; self->painDebounceTime = level.time + 2000; hold += 1000; parts = SETANIM_BOTH; - } - else if ( !VectorLengthSquared( self->client->ps.velocity ) && !(self->client->ps.pm_flags&PMF_DUCKED)) - { + } else if (!VectorLengthSquared(self->client->ps.velocity) && !(self->client->ps.pm_flags & PMF_DUCKED)) { parts = SETANIM_BOTH; } } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - if ( self->client->ps.forcePowersActive&(1<value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + hold = floor(hold * g_timescale->value); } - self->client->ps.weaponTime = hold;//was 1000, but want to swing sooner - //do effect... FIXME: build-up or delay this until in proper part of anim + self->client->ps.weaponTime = hold; // was 1000, but want to swing sooner + // do effect... FIXME: build-up or delay this until in proper part of anim self->client->ps.powerups[PW_FORCE_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; - //reset to 0 in case it's still > 0 from a previous push + // reset to 0 in case it's still > 0 from a previous push self->client->pushEffectFadeTime = 0; - G_Sound( self, soundIndex ); + G_Sound(self, soundIndex); - if ( (!pull && self->client->ps.forcePowersForced&(1<client->ps.forcePowersForced&(1<client->NPC_class==CLASS_KYLE&&(self->spawnflags&1)&&TIMER_Done( self, "kyleTakesSaber" )) ) - { + if ((!pull && self->client->ps.forcePowersForced & (1 << FP_PUSH)) || (pull && self->client->ps.forcePowersForced & (1 << FP_PULL)) || + (pull && self->client->NPC_class == CLASS_KYLE && (self->spawnflags & 1) && TIMER_Done(self, "kyleTakesSaber"))) { noResist = qtrue; } - VectorCopy( self->client->ps.viewangles, fwdangles ); - //fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, right, NULL ); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->client->ps.viewangles, fwdangles); + // fwdangles[1] = self->client->ps.viewangles[1]; + AngleVectors(fwdangles, forward, right, NULL); + VectorCopy(self->currentOrigin, center); - if ( pull ) - { + if (pull) { cone = forcePullCone[self->client->ps.forcePowerLevel[FP_PULL]]; - } - else - { + } else { cone = forcePushCone[self->client->ps.forcePowerLevel[FP_PUSH]]; } // if ( cone >= 1.0f ) - {//must be pointing right at them - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, (EG2_Collision)0, 0 );//was MASK_SHOT, changed to match crosshair trace - if ( tr.entityNum < ENTITYNUM_WORLD ) - {//found something right in front of self, + { // must be pointing right at them + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, (EG2_Collision)0, + 0); // was MASK_SHOT, changed to match crosshair trace + if (tr.entityNum < ENTITYNUM_WORLD) { // found something right in front of self, forwardEnt = &g_entities[tr.entityNum]; - if ( !forwardEnt->client && !Q_stricmp( "func_static", forwardEnt->classname ) ) - { - if ( (forwardEnt->spawnflags&1/*F_PUSH*/)||(forwardEnt->spawnflags&2/*F_PULL*/) ) - {//push/pullable - if ( (forwardEnt->spawnflags&32/*SOLITARY*/) ) - {//can only push/pull ME, ignore all others - if ( forwardEnt->NPC_targetname == NULL - || (self->targetname&&Q_stricmp( forwardEnt->NPC_targetname, self->targetname ) == 0) ) - {//anyone can push it or only 1 person can push it and it's me + if (!forwardEnt->client && !Q_stricmp("func_static", forwardEnt->classname)) { + if ((forwardEnt->spawnflags & 1 /*F_PUSH*/) || (forwardEnt->spawnflags & 2 /*F_PULL*/)) { // push/pullable + if ((forwardEnt->spawnflags & 32 /*SOLITARY*/)) { // can only push/pull ME, ignore all others + if (forwardEnt->NPC_targetname == NULL || (self->targetname && Q_stricmp(forwardEnt->NPC_targetname, self->targetname) == + 0)) { // anyone can push it or only 1 person can push it and it's me push_list[0] = forwardEnt; ent_count = numListedEntities = 1; } @@ -9120,124 +7169,96 @@ void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) } } - if ( forwardEnt ) - { - if ( G_TryingPullAttack( self, &self->client->usercmd, qtrue ) ) - {//we're going to try to do a pull attack on our forwardEnt - if ( WP_ForceThrowable( forwardEnt, forwardEnt, self, pull, cone, radius, forward ) ) - {//we will actually pull-attack him, so don't pull him or anything else here - //activate the power, here, though, so the later check that actually does the pull attack knows we tried to pull - self->client->ps.forcePowersActive |= (1<client->ps.forcePowerDebounce[FP_PULL] = level.time + 100; //force-pulling + if (forwardEnt) { + if (G_TryingPullAttack(self, &self->client->usercmd, qtrue)) { // we're going to try to do a pull attack on our forwardEnt + if (WP_ForceThrowable(forwardEnt, forwardEnt, self, pull, cone, radius, + forward)) { // we will actually pull-attack him, so don't pull him or anything else here + // activate the power, here, though, so the later check that actually does the pull attack knows we tried to pull + self->client->ps.forcePowersActive |= (1 << FP_PULL); + self->client->ps.forcePowerDebounce[FP_PULL] = level.time + 100; // force-pulling return; } } } - if ( !numListedEntities ) - { - for ( i = 0 ; i < 3 ; i++ ) - { + if (!numListedEntities) { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( !WP_ForceThrowable( ent, forwardEnt, self, pull, cone, radius, forward ) ) - { + if (!WP_ForceThrowable(ent, forwardEnt, self, pull, cone, radius, forward)) { continue; } - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < ent->absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - center[i]; - } else if ( center[i] > ent->absmax[i] ) - { + } else if (center[i] > ent->absmax[i]) { v[i] = center[i] - ent->absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( ent->absmax, ent->absmin, size ); - VectorMA( ent->absmin, 0.5, size, ent_org ); + VectorSubtract(ent->absmax, ent->absmin, size); + VectorMA(ent->absmin, 0.5, size, ent_org); - //see if they're in front of me - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( cone < 1.0f ) - {//must be within the forward cone - if ( ent->client && !pull - && ent->client->ps.forceGripEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_GRIPPED) ) - {//this is the guy that's force-gripping me, use a wider cone regardless of force power level - if ( (dot1 = DotProduct( dir, forward )) < cone-0.3f ) + // see if they're in front of me + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if (cone < 1.0f) { // must be within the forward cone + if (ent->client && !pull && ent->client->ps.forceGripEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_GRIPPED)) { // this is the guy that's force-gripping me, use a wider cone regardless of force power level + if ((dot1 = DotProduct(dir, forward)) < cone - 0.3f) continue; - } - else if ( ent->client && !pull - && ent->client->ps.forceDrainEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_DRAINED) ) - {//this is the guy that's force-draining me, use a wider cone regardless of force power level - if ( (dot1 = DotProduct( dir, forward )) < cone-0.3f ) + } else if (ent->client && !pull && ent->client->ps.forceDrainEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_DRAINED)) { // this is the guy that's force-draining me, use a wider cone regardless of force power level + if ((dot1 = DotProduct(dir, forward)) < cone - 0.3f) continue; - } - else if ( ent->s.eType == ET_MISSILE )//&& ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject ) - {//missiles are easier to force-push, never require direct trace (FIXME: maybe also items and general physics objects) - if ( (dot1 = DotProduct( dir, forward )) < cone-0.3f ) + } else if (ent->s.eType == ET_MISSILE) //&& ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject ) + { // missiles are easier to force-push, never require direct trace (FIXME: maybe also items and general physics objects) + if ((dot1 = DotProduct(dir, forward)) < cone - 0.3f) continue; - } - else if ( (dot1 = DotProduct( dir, forward )) < cone ) - { + } else if ((dot1 = DotProduct(dir, forward)) < cone) { continue; } - } - else if ( ent->s.eType == ET_MISSILE ) - {//a missile and we're at force level 1... just use a small cone, but not ridiculously small - if ( (dot1 = DotProduct( dir, forward )) < 0.75f ) - { + } else if (ent->s.eType == ET_MISSILE) { // a missile and we're at force level 1... just use a small cone, but not ridiculously small + if ((dot1 = DotProduct(dir, forward)) < 0.75f) { continue; } - }//else is an NPC or brush entity that our forward trace would have to hit + } // else is an NPC or brush entity that our forward trace would have to hit - dist = VectorLength( v ); + dist = VectorLength(v); - //Now check and see if we can actually deflect it - //method1 - //if within a certain range, deflect it - if ( ent->s.eType == ET_MISSILE && cone >= 1.0f ) - {//smaller radius on missile checks at force push 1 - if ( dist >= 192 ) - { + // Now check and see if we can actually deflect it + // method1 + // if within a certain range, deflect it + if (ent->s.eType == ET_MISSILE && cone >= 1.0f) { // smaller radius on missile checks at force push 1 + if (dist >= 192) { continue; } - } - else if ( dist >= radius ) - { + } else if (dist >= radius) { continue; } - //in PVS? - if ( !ent->bmodel && !gi.inPVS( ent_org, self->client->renderInfo.eyePoint ) ) - {//must be in PVS + // in PVS? + if (!ent->bmodel && !gi.inPVS(ent_org, self->client->renderInfo.eyePoint)) { // must be in PVS continue; } - if ( ent != forwardEnt ) - {//don't need to trace against forwardEnt again - //really should have a clear LOS to this thing... - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_FORCE_PUSH, (EG2_Collision)0, 0 );//was MASK_SHOT, but changed to match above trace and crosshair trace - if ( tr.fraction < 1.0f && tr.entityNum != ent->s.number ) - {//must have clear LOS + if (ent != forwardEnt) { // don't need to trace against forwardEnt again + // really should have a clear LOS to this thing... + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_FORCE_PUSH, (EG2_Collision)0, + 0); // was MASK_SHOT, but changed to match above trace and crosshair trace + if (tr.fraction < 1.0f && tr.entityNum != ent->s.number) { // must have clear LOS continue; } } @@ -9248,417 +7269,316 @@ void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) } } - if ( ent_count ) - { - for ( int x = 0; x < ent_count; x++ ) - { - if ( push_list[x]->client ) - { - vec3_t pushDir; - float knockback = pull?0:200; + if (ent_count) { + for (int x = 0; x < ent_count; x++) { + if (push_list[x]->client) { + vec3_t pushDir; + float knockback = pull ? 0 : 200; - //SIGH band-aid... - if ( push_list[x]->s.number >= MAX_CLIENTS - && self->s.number < MAX_CLIENTS ) - { - if ( (push_list[x]->client->ps.forcePowersActive&(1<s.number >= MAX_CLIENTS && self->s.number < MAX_CLIENTS) { + if ((push_list[x]->client->ps.forcePowersActive & (1 << FP_GRIP)) //&& push_list[x]->client->ps.forcePowerDebounce[FP_GRIP] < level.time - && push_list[x]->client->ps.forceGripEntityNum == self->s.number ) - { - WP_ForcePowerStop( push_list[x], FP_GRIP ); + && push_list[x]->client->ps.forceGripEntityNum == self->s.number) { + WP_ForcePowerStop(push_list[x], FP_GRIP); } - if ( (push_list[x]->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_DRAIN)) //&& push_list[x]->client->ps.forcePowerDebounce[FP_DRAIN] < level.time - && push_list[x]->client->ps.forceDrainEntityNum == self->s.number ) - { - WP_ForcePowerStop( push_list[x], FP_DRAIN ); + && push_list[x]->client->ps.forceDrainEntityNum == self->s.number) { + WP_ForcePowerStop(push_list[x], FP_DRAIN); } } - if ( Rosh_BeingHealed( push_list[x] ) ) - { + if (Rosh_BeingHealed(push_list[x])) { continue; } - if ( push_list[x]->client->NPC_class == CLASS_HAZARD_TROOPER - && push_list[x]->health > 0 ) - {//living hazard troopers resist push/pull - WP_ForceThrowHazardTrooper( self, push_list[x], pull ); + if (push_list[x]->client->NPC_class == CLASS_HAZARD_TROOPER && push_list[x]->health > 0) { // living hazard troopers resist push/pull + WP_ForceThrowHazardTrooper(self, push_list[x], pull); continue; } - if ( fake ) - {//always resist - WP_ResistForcePush( push_list[x], self, qfalse ); + if (fake) { // always resist + WP_ResistForcePush(push_list[x], self, qfalse); continue; } -//FIXMEFIXMEFIXMEFIXMEFIXME: extern a lot of this common code when I have the time!!! + // FIXMEFIXMEFIXMEFIXMEFIXME: extern a lot of this common code when I have the time!!! int powerLevel, powerUse; - if (pull) - { + if (pull) { powerLevel = self->client->ps.forcePowerLevel[FP_PULL]; powerUse = FP_PULL; - } - else - { + } else { powerLevel = self->client->ps.forcePowerLevel[FP_PUSH]; powerUse = FP_PUSH; } - int modPowerLevel = WP_AbsorbConversion( push_list[x], push_list[x]->client->ps.forcePowerLevel[FP_ABSORB], self, powerUse, powerLevel, forcePowerNeeded[self->client->ps.forcePowerLevel[powerUse]] ); - if (push_list[x]->client->NPC_class==CLASS_ASSASSIN_DROID || - push_list[x]->client->NPC_class==CLASS_HAZARD_TROOPER) - { - modPowerLevel = 0; // devides throw by 10 - } - - //First, if this is the player we're push/pulling, see if he can counter it - if ( modPowerLevel != -1 - && !noResist - && InFront( self->currentOrigin, push_list[x]->client->renderInfo.eyePoint, push_list[x]->client->ps.viewangles, 0.3f ) ) - {//absorbed and I'm in front of them - //counter it - if ( push_list[x]->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_2 ) - {//no reaction at all - } - else - { - WP_ResistForcePush( push_list[x], self, qfalse ); - push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + int modPowerLevel = WP_AbsorbConversion(push_list[x], push_list[x]->client->ps.forcePowerLevel[FP_ABSORB], self, powerUse, powerLevel, + forcePowerNeeded[self->client->ps.forcePowerLevel[powerUse]]); + if (push_list[x]->client->NPC_class == CLASS_ASSASSIN_DROID || push_list[x]->client->NPC_class == CLASS_HAZARD_TROOPER) { + modPowerLevel = 0; // devides throw by 10 + } + + // First, if this is the player we're push/pulling, see if he can counter it + if (modPowerLevel != -1 && !noResist && + InFront(self->currentOrigin, push_list[x]->client->renderInfo.eyePoint, push_list[x]->client->ps.viewangles, + 0.3f)) { // absorbed and I'm in front of them + // counter it + if (push_list[x]->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_2) { // no reaction at all + } else { + WP_ResistForcePush(push_list[x], self, qfalse); + push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = + LS_READY; // don't finish whatever saber anim you may have been in push_list[x]->client->ps.saberBlocked = BLOCKED_NONE; } continue; - } - else if ( !push_list[x]->s.number ) - {//player - if ( !noResist && ShouldPlayerResistForceThrow(push_list[x], self, pull) ) - { - WP_ResistForcePush( push_list[x], self, qfalse ); - push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + } else if (!push_list[x]->s.number) { // player + if (!noResist && ShouldPlayerResistForceThrow(push_list[x], self, pull)) { + WP_ResistForcePush(push_list[x], self, qfalse); + push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = + LS_READY; // don't finish whatever saber anim you may have been in push_list[x]->client->ps.saberBlocked = BLOCKED_NONE; continue; } - } - else if ( push_list[x]->client && Jedi_WaitingAmbush( push_list[x] ) ) - { - WP_ForceKnockdown( push_list[x], self, pull, qtrue, qfalse ); + } else if (push_list[x]->client && Jedi_WaitingAmbush(push_list[x])) { + WP_ForceKnockdown(push_list[x], self, pull, qtrue, qfalse); continue; } - G_KnockOffVehicle( push_list[x], self, pull ); - - if ( !pull - && push_list[x]->client->ps.forceDrainEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_DRAINED) ) - {//stop them from draining me now, dammit! - WP_ForcePowerStop( push_list[x], FP_DRAIN ); - } - - //okay, everyone else (or player who couldn't resist it)... - if ( ((self->s.number == 0 && Q_irand( 0, 2 ) ) || Q_irand( 0, 2 ) ) && push_list[x]->client && push_list[x]->health > 0 //a living client - && push_list[x]->client->ps.weapon == WP_SABER //Jedi - && push_list[x]->health > 0 //alive - && push_list[x]->client->ps.forceRageRecoveryTime < level.time //not recobering from rage - && ((self->client->NPC_class != CLASS_DESANN&&Q_stricmp("Yoda",self->NPC_type)) || !Q_irand( 0, 2 ) )//only 30% chance of resisting a Desann push - && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE //on the ground - && InFront( self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.3f ) //I'm in front of him - && ( push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time ||//he's pushing too - (push_list[x]->s.number != 0 && push_list[x]->client->ps.weaponTime < level.time)//not the player and not attacking (NPC jedi auto-defend against pushes) - ) - ) - {//Jedi don't get pushed, they resist as long as they aren't already attacking and are on the ground - if ( push_list[x]->client->ps.saberLockTime > level.time ) - {//they're in a lock - if ( push_list[x]->client->ps.saberLockEnemy != self->s.number ) - {//they're not in a lock with me + G_KnockOffVehicle(push_list[x], self, pull); + + if (!pull && push_list[x]->client->ps.forceDrainEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_DRAINED)) { // stop them from draining me now, dammit! + WP_ForcePowerStop(push_list[x], FP_DRAIN); + } + + // okay, everyone else (or player who couldn't resist it)... + if (((self->s.number == 0 && Q_irand(0, 2)) || Q_irand(0, 2)) && push_list[x]->client && push_list[x]->health > 0 // a living client + && push_list[x]->client->ps.weapon == WP_SABER // Jedi + && push_list[x]->health > 0 // alive + && push_list[x]->client->ps.forceRageRecoveryTime < level.time // not recobering from rage + && ((self->client->NPC_class != CLASS_DESANN && Q_stricmp("Yoda", self->NPC_type)) || + !Q_irand(0, 2)) // only 30% chance of resisting a Desann push + && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE // on the ground + && InFront(self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.3f) // I'm in front of him + && (push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time || // he's pushing too + (push_list[x]->s.number != 0 && + push_list[x]->client->ps.weaponTime < level.time) // not the player and not attacking (NPC jedi auto-defend against pushes) + )) { // Jedi don't get pushed, they resist as long as they aren't already attacking and are on the ground + if (push_list[x]->client->ps.saberLockTime > level.time) { // they're in a lock + if (push_list[x]->client->ps.saberLockEnemy != self->s.number) { // they're not in a lock with me continue; - } - else if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 || - push_list[x]->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//they're in a lock with me, but my push is too weak + } else if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 || + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // they're in a lock with me, but my push is too weak continue; - } - else - {//we will knock them down + } else { // we will knock them down self->painDebounceTime = 0; self->client->ps.weaponTime = 500; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } } int resistChance = Q_irand(0, 2); - if ( push_list[x]->s.number >= MAX_CLIENTS ) - {//NPC - if ( g_spskill->integer == 1 ) - {//stupid tweak for graham + if (push_list[x]->s.number >= MAX_CLIENTS) { // NPC + if (g_spskill->integer == 1) { // stupid tweak for graham resistChance = Q_irand(0, 3); } } - if ( noResist || - ( !pull - && modPowerLevel == -1 - && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 - && !resistChance - && push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - ) - {//a level 3 push can even knock down a jedi - if ( PM_InKnockDown( &push_list[x]->client->ps ) ) - {//can't knock them down again + if (noResist || (!pull && modPowerLevel == -1 && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && !resistChance && + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3)) { // a level 3 push can even knock down a jedi + if (PM_InKnockDown(&push_list[x]->client->ps)) { // can't knock them down again continue; } - WP_ForceKnockdown( push_list[x], self, pull, qfalse, qtrue ); - } - else - { - WP_ResistForcePush( push_list[x], self, qfalse ); + WP_ForceKnockdown(push_list[x], self, pull, qfalse, qtrue); + } else { + WP_ResistForcePush(push_list[x], self, qfalse); } - } - else - { - //UGH: FIXME: for enemy jedi, they should probably always do force pull 3, and not your weapon (if player?)! - //shove them - if ( push_list[x]->NPC - && push_list[x]->NPC->jumpState == JS_JUMPING ) - {//don't interrupt a scripted jump - //WP_ResistForcePush( push_list[x], self, qfalse ); + } else { + // UGH: FIXME: for enemy jedi, they should probably always do force pull 3, and not your weapon (if player?)! + // shove them + if (push_list[x]->NPC && push_list[x]->NPC->jumpState == JS_JUMPING) { // don't interrupt a scripted jump + // WP_ResistForcePush( push_list[x], self, qfalse ); push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms continue; } - if ( push_list[x]->s.number - && (push_list[x]->message || (push_list[x]->flags&FL_NO_KNOCKBACK)) ) - {//an NPC who has a key - //don't push me... FIXME: maybe can pull the key off me? - WP_ForceKnockdown( push_list[x], self, pull, qfalse, qfalse ); + if (push_list[x]->s.number && (push_list[x]->message || (push_list[x]->flags & FL_NO_KNOCKBACK))) { // an NPC who has a key + // don't push me... FIXME: maybe can pull the key off me? + WP_ForceKnockdown(push_list[x], self, pull, qfalse, qfalse); continue; } - if ( pull ) - { - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, pushDir ); - if ( self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 - && self->client->NPC_class == CLASS_KYLE - && (self->spawnflags&1) - && TIMER_Done( self, "kyleTakesSaber" ) - && push_list[x]->client - && push_list[x]->client->ps.weapon == WP_SABER - && !push_list[x]->client->ps.saberInFlight - && push_list[x]->client->ps.saberEntityNum < ENTITYNUM_WORLD - && !PM_InOnGroundAnim( &push_list[x]->client->ps ) ) - { + if (pull) { + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, pushDir); + if (self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 && self->client->NPC_class == CLASS_KYLE && (self->spawnflags & 1) && + TIMER_Done(self, "kyleTakesSaber") && push_list[x]->client && push_list[x]->client->ps.weapon == WP_SABER && + !push_list[x]->client->ps.saberInFlight && push_list[x]->client->ps.saberEntityNum < ENTITYNUM_WORLD && + !PM_InOnGroundAnim(&push_list[x]->client->ps)) { vec3_t throwVec; - VectorScale( pushDir, 10.0f, throwVec ); - WP_SaberLose( push_list[x], throwVec ); - NPC_SetAnim( push_list[x], SETANIM_BOTH, BOTH_LOSE_SABER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + VectorScale(pushDir, 10.0f, throwVec); + WP_SaberLose(push_list[x], throwVec); + NPC_SetAnim(push_list[x], SETANIM_BOTH, BOTH_LOSE_SABER, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); push_list[x]->client->ps.torsoAnimTimer += 500; push_list[x]->client->ps.pm_time = push_list[x]->client->ps.weaponTime = push_list[x]->client->ps.torsoAnimTimer; push_list[x]->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; push_list[x]->client->ps.saberMove = LS_NONE; push_list[x]->aimDebounceTime = level.time + push_list[x]->client->ps.torsoAnimTimer; - VectorClear( push_list[x]->client->ps.velocity ); - VectorClear( push_list[x]->client->ps.moveDir ); - //Kyle will stand around for a bit, too... + VectorClear(push_list[x]->client->ps.velocity); + VectorClear(push_list[x]->client->ps.moveDir); + // Kyle will stand around for a bit, too... self->client->ps.pm_time = self->client->ps.weaponTime = 2000; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; self->painDebounceTime = level.time + self->client->ps.weaponTime; - TIMER_Set( self, "kyleTakesSaber", Q_irand( 60000, 180000 ) );//don't do this again for a while - G_AddVoiceEvent( self, Q_irand(EV_TAUNT1,EV_TAUNT3), Q_irand( 4000, 6000 ) ); - VectorClear( self->client->ps.velocity ); - VectorClear( self->client->ps.moveDir ); + TIMER_Set(self, "kyleTakesSaber", Q_irand(60000, 180000)); // don't do this again for a while + G_AddVoiceEvent(self, Q_irand(EV_TAUNT1, EV_TAUNT3), Q_irand(4000, 6000)); + VectorClear(self->client->ps.velocity); + VectorClear(self->client->ps.moveDir); continue; - } - else if ( push_list[x]->NPC - && (push_list[x]->NPC->scriptFlags&SCF_DONT_FLEE) ) - {//*SIGH*... if an NPC can't flee, they can't run after and pick up their weapon, do don't drop it - } - else if ( self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 - && push_list[x]->client->NPC_class != CLASS_ROCKETTROOPER//rockettroopers never drop their weapon - && push_list[x]->client->NPC_class != CLASS_VEHICLE - && push_list[x]->client->NPC_class != CLASS_BOBAFETT - && push_list[x]->client->NPC_class != CLASS_TUSKEN - && push_list[x]->client->NPC_class != CLASS_HAZARD_TROOPER - && push_list[x]->client->NPC_class != CLASS_ASSASSIN_DROID - && push_list[x]->s.weapon != WP_SABER - && push_list[x]->s.weapon != WP_MELEE - && push_list[x]->s.weapon != WP_THERMAL - && push_list[x]->s.weapon != WP_CONCUSSION // so rax can't drop his - ) - {//yank the weapon - NOTE: level 1 just knocks them down, not take weapon - //FIXME: weapon yank anim if not a knockdown? - if ( InFront( self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.0f ) ) - {//enemy has to be facing me, too... - WP_DropWeapon( push_list[x], pushDir ); + } else if (push_list[x]->NPC && + (push_list[x]->NPC->scriptFlags & + SCF_DONT_FLEE)) { //*SIGH*... if an NPC can't flee, they can't run after and pick up their weapon, do don't drop it + } else if (self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 && + push_list[x]->client->NPC_class != CLASS_ROCKETTROOPER // rockettroopers never drop their weapon + && push_list[x]->client->NPC_class != CLASS_VEHICLE && push_list[x]->client->NPC_class != CLASS_BOBAFETT && + push_list[x]->client->NPC_class != CLASS_TUSKEN && push_list[x]->client->NPC_class != CLASS_HAZARD_TROOPER && + push_list[x]->client->NPC_class != CLASS_ASSASSIN_DROID && push_list[x]->s.weapon != WP_SABER && + push_list[x]->s.weapon != WP_MELEE && push_list[x]->s.weapon != WP_THERMAL && + push_list[x]->s.weapon != WP_CONCUSSION // so rax can't drop his + ) { // yank the weapon - NOTE: level 1 just knocks them down, not take weapon + // FIXME: weapon yank anim if not a knockdown? + if (InFront(self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, + 0.0f)) { // enemy has to be facing me, too... + WP_DropWeapon(push_list[x], pushDir); } } - knockback += VectorNormalize( pushDir ); - if ( knockback > 200 ) - { + knockback += VectorNormalize(pushDir); + if (knockback > 200) { knockback = 200; } - if ( self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_3 ) - {//maybe just knock them down + if (self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_3) { // maybe just knock them down knockback /= 3; } - } - else - { - VectorSubtract( push_list[x]->currentOrigin, self->currentOrigin, pushDir ); - knockback -= VectorNormalize( pushDir ); - if ( knockback < 100 ) - { + } else { + VectorSubtract(push_list[x]->currentOrigin, self->currentOrigin, pushDir); + knockback -= VectorNormalize(pushDir); + if (knockback < 100) { knockback = 100; } - //scale for push level - if ( self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 ) - {//maybe just knock them down + // scale for push level + if (self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2) { // maybe just knock them down knockback /= 3; - } - else if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//super-hard push - //Hmm, maybe in this case can even nudge/knockdown a jedi? Especially if close? - //knockback *= 5; + } else if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // super-hard push + // Hmm, maybe in this case can even nudge/knockdown a jedi? + // Especially if close? knockback *= 5; } } - if ( modPowerLevel != -1 ) - { - if ( !modPowerLevel ) - { + if (modPowerLevel != -1) { + if (!modPowerLevel) { knockback /= 10.0f; - } - else if ( modPowerLevel == 1 ) - { + } else if (modPowerLevel == 1) { knockback /= 6.0f; - } - else// if ( modPowerLevel == 2 ) + } else // if ( modPowerLevel == 2 ) { knockback /= 2.0f; } } - //actually push/pull the enemy - G_Throw( push_list[x], pushDir, knockback ); - //make it so they don't actually hurt me when pulled at me... + // actually push/pull the enemy + G_Throw(push_list[x], pushDir, knockback); + // make it so they don't actually hurt me when pulled at me... push_list[x]->forcePuller = self->s.number; - if ( push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//if on the ground, make sure they get shoved up some - if ( push_list[x]->client->ps.velocity[2] < knockback ) - { + if (push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE) { // if on the ground, make sure they get shoved up some + if (push_list[x]->client->ps.velocity[2] < knockback) { push_list[x]->client->ps.velocity[2] = knockback; } } - if ( push_list[x]->health > 0 ) - {//target is still alive - if ( (push_list[x]->s.number||(cg.renderingThirdPerson&&!cg.zoomMode)) //NPC or 3rd person player - && ((!pull&&self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 && push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) //level 1 push - || (pull && self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_2 && push_list[x]->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_1)) )//level 1 pull - {//NPC or third person player (without force push/pull skill), and force push/pull level is at 1 - WP_ForceKnockdown( push_list[x], self, pull, (qboolean)(!pull&&knockback>150), qfalse ); - } - else if ( !push_list[x]->s.number ) - {//player, have to force an anim on him - WP_ForceKnockdown( push_list[x], self, pull, (qboolean)(!pull&&knockback>150), qfalse ); - } - else - {//NPC and force-push/pull at level 2 or higher - WP_ForceKnockdown( push_list[x], self, pull, (qboolean)(!pull&&knockback>100), qfalse ); + if (push_list[x]->health > 0) { // target is still alive + if ((push_list[x]->s.number || (cg.renderingThirdPerson && !cg.zoomMode)) // NPC or 3rd person player + && ((!pull && self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 && + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) // level 1 push + || (pull && self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_2 && + push_list[x]->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_1))) // level 1 pull + { // NPC or third person player (without force push/pull skill), and force push/pull level is at 1 + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 150), qfalse); + } else if (!push_list[x]->s.number) { // player, have to force an anim on him + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 150), qfalse); + } else { // NPC and force-push/pull at level 2 or higher + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 100), qfalse); } } push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms } - } - else if ( !fake ) - {//not a fake push/pull - if ( push_list[x]->s.weapon == WP_SABER && (push_list[x]->contents&CONTENTS_LIGHTSABER) ) - {//a thrown saber, just send it back + } else if (!fake) { // not a fake push/pull + if (push_list[x]->s.weapon == WP_SABER && (push_list[x]->contents & CONTENTS_LIGHTSABER)) { // a thrown saber, just send it back /* if ( pull ) {//steal it? } - else */if ( push_list[x]->owner && push_list[x]->owner->client && push_list[x]->owner->client->ps.SaberActive() && push_list[x]->s.pos.trType == TR_LINEAR && push_list[x]->owner->client->ps.saberEntityState != SES_RETURNING ) - {//it's on and being controlled - //FIXME: prevent it from damaging me? - if ( self->s.number == 0 || Q_irand( 0, 2 ) ) - {//certain chance of throwing it aside and turning it off? - //give it some velocity away from me - //FIXME: maybe actually push or pull it? - if ( Q_irand( 0, 1 ) ) - { - VectorScale( right, -1, right ); + else */ + if (push_list[x]->owner && push_list[x]->owner->client && push_list[x]->owner->client->ps.SaberActive() && + push_list[x]->s.pos.trType == TR_LINEAR && + push_list[x]->owner->client->ps.saberEntityState != SES_RETURNING) { // it's on and being controlled + // FIXME: prevent it from damaging me? + if (self->s.number == 0 || Q_irand(0, 2)) { // certain chance of throwing it aside and turning it off? + // give it some velocity away from me + // FIXME: maybe actually push or pull it? + if (Q_irand(0, 1)) { + VectorScale(right, -1, right); } - G_ReflectMissile( self, push_list[x], right ); - //FIXME: isn't turning off!!! - WP_SaberDrop( push_list[x]->owner, push_list[x] ); + G_ReflectMissile(self, push_list[x], right); + // FIXME: isn't turning off!!! + WP_SaberDrop(push_list[x]->owner, push_list[x]); + } else { + WP_SaberReturn(push_list[x]->owner, push_list[x]); } - else - { - WP_SaberReturn( push_list[x]->owner, push_list[x] ); - } - //different effect? + // different effect? } - } - else if ( push_list[x]->s.eType == ET_MISSILE - && push_list[x]->s.pos.trType != TR_STATIONARY - && (push_list[x]->s.pos.trType != TR_INTERPOLATE||push_list[x]->s.weapon != WP_THERMAL) )//rolling and stationary thermal detonators are dealt with below + } else if (push_list[x]->s.eType == ET_MISSILE && push_list[x]->s.pos.trType != TR_STATIONARY && + (push_list[x]->s.pos.trType != TR_INTERPOLATE || + push_list[x]->s.weapon != WP_THERMAL)) // rolling and stationary thermal detonators are dealt with below { vec3_t dir2Me; - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, dir2Me ); - float dot = DotProduct( push_list[x]->s.pos.trDelta, dir2Me ); - if ( pull ) - {//deflect rather than reflect? - } - else - { - if ( push_list[x]->s.eFlags&EF_MISSILE_STICK ) - {//caught a sticky in-air + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, dir2Me); + float dot = DotProduct(push_list[x]->s.pos.trDelta, dir2Me); + if (pull) { // deflect rather than reflect? + } else { + if (push_list[x]->s.eFlags & EF_MISSILE_STICK) { // caught a sticky in-air push_list[x]->s.eType = ET_MISSILE; push_list[x]->s.eFlags &= ~EF_MISSILE_STICK; push_list[x]->s.eFlags |= EF_BOUNCE_HALF; push_list[x]->splashDamage /= 3; push_list[x]->splashRadius /= 3; push_list[x]->e_ThinkFunc = thinkF_WP_Explode; - push_list[x]->nextthink = level.time + Q_irand( 500, 3000 ); - } - if ( dot >= 0 ) - {//it's heading towards me - G_ReflectMissile( self, push_list[x], forward ); + push_list[x]->nextthink = level.time + Q_irand(500, 3000); } - else - { - VectorScale( push_list[x]->s.pos.trDelta, 1.25f, push_list[x]->s.pos.trDelta ); + if (dot >= 0) { // it's heading towards me + G_ReflectMissile(self, push_list[x], forward); + } else { + VectorScale(push_list[x]->s.pos.trDelta, 1.25f, push_list[x]->s.pos.trDelta); } - //deflect sound - //G_Sound( push_list[x], G_SoundIndex( va("sound/weapons/blaster/reflect%d.wav", Q_irand( 1, 3 ) ) ) ); - //push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms - } - if ( push_list[x]->s.eType == ET_MISSILE - && push_list[x]->s.weapon == WP_ROCKET_LAUNCHER - && push_list[x]->damage < 60 ) - {//pushing away a rocket raises it's damage to the max for NPCs + // deflect sound + // G_Sound( push_list[x], G_SoundIndex( va("sound/weapons/blaster/reflect%d.wav", Q_irand( 1, 3 ) ) ) ); + // push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms + } + if (push_list[x]->s.eType == ET_MISSILE && push_list[x]->s.weapon == WP_ROCKET_LAUNCHER && + push_list[x]->damage < 60) { // pushing away a rocket raises it's damage to the max for NPCs push_list[x]->damage = 60; } - } - else if ( push_list[x]->svFlags & SVF_GLASS_BRUSH ) - {//break the glass + } else if (push_list[x]->svFlags & SVF_GLASS_BRUSH) { // break the glass trace_t tr; - vec3_t pushDir; - float damage = 800; - - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - {//must be pointing right at it + vec3_t pushDir; + float damage = 800; + + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { // must be pointing right at it continue; } - if ( pull ) - { - VectorSubtract( self->client->renderInfo.eyePoint, tr.endpos, pushDir ); - } - else - { - VectorSubtract( tr.endpos, self->client->renderInfo.eyePoint, pushDir ); + if (pull) { + VectorSubtract(self->client->renderInfo.eyePoint, tr.endpos, pushDir); + } else { + VectorSubtract(tr.endpos, self->client->renderInfo.eyePoint, pushDir); } /* VectorSubtract( push_list[x]->absmax, push_list[x]->absmin, size ); @@ -9672,133 +7592,107 @@ void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) VectorSubtract( center, self->client->renderInfo.eyePoint, pushDir ); } */ - damage -= VectorNormalize( pushDir ); - if ( damage < 200 ) - { + damage -= VectorNormalize(pushDir); + if (damage < 200) { damage = 200; } - VectorScale( pushDir, damage, pushDir ); + VectorScale(pushDir, damage, pushDir); - G_Damage( push_list[x], self, self, pushDir, tr.endpos, damage, 0, MOD_UNKNOWN ); - } - else if ( !Q_stricmp( "func_static", push_list[x]->classname ) ) - {//force-usable func_static - if ( !pull && (push_list[x]->spawnflags&1/*F_PUSH*/) ) - { - if ( push_list[x]->NPC_targetname == NULL - || (self->targetname&&Q_stricmp( push_list[x]->NPC_targetname, self->targetname ) == 0) ) - {//anyone can pull it or only 1 person can push it and it's me - GEntity_UseFunc( push_list[x], self, self ); + G_Damage(push_list[x], self, self, pushDir, tr.endpos, damage, 0, MOD_UNKNOWN); + } else if (!Q_stricmp("func_static", push_list[x]->classname)) { // force-usable func_static + if (!pull && (push_list[x]->spawnflags & 1 /*F_PUSH*/)) { + if (push_list[x]->NPC_targetname == NULL || + (self->targetname && + Q_stricmp(push_list[x]->NPC_targetname, self->targetname) == 0)) { // anyone can pull it or only 1 person can push it and it's me + GEntity_UseFunc(push_list[x], self, self); } - } - else if ( pull && (push_list[x]->spawnflags&2/*F_PULL*/) ) - { - if ( push_list[x]->NPC_targetname == NULL - || (self->targetname&&Q_stricmp( push_list[x]->NPC_targetname, self->NPC_targetname ) == 0) ) - {//anyone can push it or only 1 person can push it and it's me - GEntity_UseFunc( push_list[x], self, self ); + } else if (pull && (push_list[x]->spawnflags & 2 /*F_PULL*/)) { + if (push_list[x]->NPC_targetname == NULL || + (self->targetname && Q_stricmp(push_list[x]->NPC_targetname, self->NPC_targetname) == + 0)) { // anyone can push it or only 1 person can push it and it's me + GEntity_UseFunc(push_list[x], self, self); } } - } - else if ( !Q_stricmp( "func_door", push_list[x]->classname ) && (push_list[x]->spawnflags&2/*MOVER_FORCE_ACTIVATE*/) ) - {//push/pull the door - vec3_t pos1, pos2; + } else if (!Q_stricmp("func_door", push_list[x]->classname) && (push_list[x]->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/)) { // push/pull the door + vec3_t pos1, pos2; - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - {//must be pointing right at it + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { // must be pointing right at it continue; } - if ( VectorCompare( vec3_origin, push_list[x]->s.origin ) ) - {//does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center - VectorSubtract( push_list[x]->absmax, push_list[x]->absmin, size ); - VectorMA( push_list[x]->absmin, 0.5, size, center ); - if ( (push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS1 ) - {//if at pos1 and started open, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos1, center ); - } - else if ( !(push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS2 ) - {//if at pos2, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos2, center ); - } - VectorAdd( center, push_list[x]->pos1, pos1 ); - VectorAdd( center, push_list[x]->pos2, pos2 ); - } - else - {//actually has an origin, pos1 and pos2 are absolute - VectorCopy( push_list[x]->currentOrigin, center ); - VectorCopy( push_list[x]->pos1, pos1 ); - VectorCopy( push_list[x]->pos2, pos2 ); - } - - if ( Distance( pos1, self->client->renderInfo.eyePoint ) < Distance( pos2, self->client->renderInfo.eyePoint ) ) - {//pos1 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + if (VectorCompare( + vec3_origin, + push_list[x]->s.origin)) { // does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center + VectorSubtract(push_list[x]->absmax, push_list[x]->absmin, size); + VectorMA(push_list[x]->absmin, 0.5, size, center); + if ((push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS1) { // if at pos1 and started open, make sure we get the center where it *started* because + // we're going to add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos1, center); + } else if (!(push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS2) { // if at pos2, make sure we get the center where it *started* because we're going + // to add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos2, center); + } + VectorAdd(center, push_list[x]->pos1, pos1); + VectorAdd(center, push_list[x]->pos2, pos2); + } else { // actually has an origin, pos1 and pos2 are absolute + VectorCopy(push_list[x]->currentOrigin, center); + VectorCopy(push_list[x]->pos1, pos1); + VectorCopy(push_list[x]->pos2, pos2); + } + + if (Distance(pos1, self->client->renderInfo.eyePoint) < Distance(pos2, self->client->renderInfo.eyePoint)) { // pos1 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } } - } - else - {//pos2 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else { // pos2 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } } } - GEntity_UseFunc( push_list[x], self, self ); - } - else if ( push_list[x]->s.eType == ET_MISSILE/*thermal resting on ground*/ - || push_list[x]->s.eType == ET_ITEM - || push_list[x]->e_ThinkFunc == thinkF_G_RunObject || Q_stricmp( "limb", push_list[x]->classname ) == 0 ) - {//general object, toss it - vec3_t pushDir, kvel; - float knockback = pull?0:200; - float mass = 200; - - if ( pull ) - { - if ( push_list[x]->s.eType == ET_ITEM ) - {//pull it to a little higher point - vec3_t adjustedOrg; - VectorCopy( self->currentOrigin, adjustedOrg ); - adjustedOrg[2] += self->maxs[2]/3; - VectorSubtract( adjustedOrg, push_list[x]->currentOrigin, pushDir ); - } - else if ( self->enemy //I have an enemy - //&& push_list[x]->s.eType != ET_ITEM //not an item - && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 //have push 3 or greater - && InFront(push_list[x]->currentOrigin, self->currentOrigin, self->currentAngles, 0.25f)//object is generally in front of me - && InFront(self->enemy->currentOrigin, self->currentOrigin, self->currentAngles, 0.75f)//enemy is pretty much right in front of me - && !InFront(push_list[x]->currentOrigin, self->enemy->currentOrigin, self->enemy->currentAngles, -0.25f)//object is generally behind enemy - //FIXME: check dist to enemy and clear LOS to enemy and clear Path between object and enemy? - && ( (self->NPC&&(noResist||Q_irand(0,RANK_CAPTAIN)NPC->rank) )//NPC with enough skill - ||( self->s.numbers.eType == ET_MISSILE /*thermal resting on ground*/ + || push_list[x]->s.eType == ET_ITEM || push_list[x]->e_ThinkFunc == thinkF_G_RunObject || + Q_stricmp("limb", push_list[x]->classname) == 0) { // general object, toss it + vec3_t pushDir, kvel; + float knockback = pull ? 0 : 200; + float mass = 200; + + if (pull) { + if (push_list[x]->s.eType == ET_ITEM) { // pull it to a little higher point + vec3_t adjustedOrg; + VectorCopy(self->currentOrigin, adjustedOrg); + adjustedOrg[2] += self->maxs[2] / 3; + VectorSubtract(adjustedOrg, push_list[x]->currentOrigin, pushDir); + } else if (self->enemy // I have an enemy + //&& push_list[x]->s.eType != ET_ITEM //not an item + && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 // have push 3 or greater + && + InFront(push_list[x]->currentOrigin, self->currentOrigin, self->currentAngles, 0.25f) // object is generally in front of me + && InFront(self->enemy->currentOrigin, self->currentOrigin, self->currentAngles, + 0.75f) // enemy is pretty much right in front of me + && !InFront(push_list[x]->currentOrigin, self->enemy->currentOrigin, self->enemy->currentAngles, + -0.25f) // object is generally behind enemy + // FIXME: check dist to enemy and clear LOS to enemy and clear Path between object and enemy? + && ((self->NPC && (noResist || Q_irand(0, RANK_CAPTAIN) < self->NPC->rank)) // NPC with enough skill + || (self->s.number < MAX_CLIENTS))) { // if I have an auto-enemy & he's in front of me, push it toward him! /* if ( targetedObjectMassTotal + push_list[x]->mass > TARGETED_OBJECT_PUSH_MASS_MAX ) {//already pushed too many things @@ -9807,45 +7701,33 @@ void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) } targetedObjectMassTotal += push_list[x]->mass; */ - VectorSubtract( self->enemy->currentOrigin, push_list[x]->currentOrigin, pushDir ); - } - else - { - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, pushDir ); + VectorSubtract(self->enemy->currentOrigin, push_list[x]->currentOrigin, pushDir); + } else { + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, pushDir); } - knockback += VectorNormalize( pushDir ); - if ( knockback > 200 ) - { + knockback += VectorNormalize(pushDir); + if (knockback > 200) { knockback = 200; } - if ( push_list[x]->s.eType == ET_ITEM - && push_list[x]->item - && push_list[x]->item->giType == IT_HOLDABLE - && push_list[x]->item->giTag == INV_SECURITY_KEY ) - {//security keys are pulled with less enthusiasm - if ( knockback > 100 ) - { + if (push_list[x]->s.eType == ET_ITEM && push_list[x]->item && push_list[x]->item->giType == IT_HOLDABLE && + push_list[x]->item->giTag == INV_SECURITY_KEY) { // security keys are pulled with less enthusiasm + if (knockback > 100) { knockback = 100; } - } - else if ( knockback > 200 ) - { + } else if (knockback > 200) { knockback = 200; } - } - else - { - if ( self->enemy //I have an enemy - && push_list[x]->s.eType != ET_ITEM //not an item - && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 //have push 3 or greater - && InFront(push_list[x]->currentOrigin, self->currentOrigin, self->currentAngles, 0.25f)//object is generally in front of me - && InFront(self->enemy->currentOrigin, self->currentOrigin, self->currentAngles, 0.75f)//enemy is pretty much right in front of me - && InFront(push_list[x]->currentOrigin, self->enemy->currentOrigin, self->enemy->currentAngles, 0.25f)//object is generally in front of enemy - //FIXME: check dist to enemy and clear LOS to enemy and clear Path between object and enemy? - && ( (self->NPC&&(noResist||Q_irand(0,RANK_CAPTAIN)NPC->rank) )//NPC with enough skill - ||( self->s.numberenemy // I have an enemy + && push_list[x]->s.eType != ET_ITEM // not an item + && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 // have push 3 or greater + && InFront(push_list[x]->currentOrigin, self->currentOrigin, self->currentAngles, 0.25f) // object is generally in front of me + && InFront(self->enemy->currentOrigin, self->currentOrigin, self->currentAngles, 0.75f) // enemy is pretty much right in front of me + && InFront(push_list[x]->currentOrigin, self->enemy->currentOrigin, self->enemy->currentAngles, + 0.25f) // object is generally in front of enemy + // FIXME: check dist to enemy and clear LOS to enemy and clear Path between object and enemy? + && ((self->NPC && (noResist || Q_irand(0, RANK_CAPTAIN) < self->NPC->rank)) // NPC with enough skill + || (self->s.number < MAX_CLIENTS))) { // if I have an auto-enemy & he's in front of me, push it toward him! /* if ( targetedObjectMassTotal + push_list[x]->mass > TARGETED_OBJECT_PUSH_MASS_MAX ) {//already pushed too many things @@ -9854,236 +7736,167 @@ void ForceThrow( gentity_t *self, qboolean pull, qboolean fake ) } targetedObjectMassTotal += push_list[x]->mass; */ - VectorSubtract( self->enemy->currentOrigin, push_list[x]->currentOrigin, pushDir ); + VectorSubtract(self->enemy->currentOrigin, push_list[x]->currentOrigin, pushDir); + } else { + VectorSubtract(push_list[x]->currentOrigin, self->currentOrigin, pushDir); } - else - { - VectorSubtract( push_list[x]->currentOrigin, self->currentOrigin, pushDir ); - } - knockback -= VectorNormalize( pushDir ); - if ( knockback < 100 ) - { + knockback -= VectorNormalize(pushDir); + if (knockback < 100) { knockback = 100; } } - //FIXME: if pull a FL_FORCE_PULLABLE_ONLY, clear the flag, assuming it's no longer in solid? or check? - VectorCopy( push_list[x]->currentOrigin, push_list[x]->s.pos.trBase ); - push_list[x]->s.pos.trTime = level.time; // move a bit on the very first frame - if ( push_list[x]->s.pos.trType != TR_INTERPOLATE ) - {//don't do this to rolling missiles + // FIXME: if pull a FL_FORCE_PULLABLE_ONLY, clear the flag, assuming it's no longer in solid? or check? + VectorCopy(push_list[x]->currentOrigin, push_list[x]->s.pos.trBase); + push_list[x]->s.pos.trTime = level.time; // move a bit on the very first frame + if (push_list[x]->s.pos.trType != TR_INTERPOLATE) { // don't do this to rolling missiles push_list[x]->s.pos.trType = TR_GRAVITY; } - if ( push_list[x]->e_ThinkFunc == thinkF_G_RunObject && push_list[x]->physicsBounce ) - {//it's a pushable misc_model_breakable, use it's mass instead of our one-size-fits-all mass - mass = push_list[x]->physicsBounce;//same as push_list[x]->mass, right? + if (push_list[x]->e_ThinkFunc == thinkF_G_RunObject && + push_list[x]->physicsBounce) { // it's a pushable misc_model_breakable, use it's mass instead of our one-size-fits-all mass + mass = push_list[x]->physicsBounce; // same as push_list[x]->mass, right? } - if ( mass < 50 ) - {//??? + if (mass < 50) { //??? mass = 50; } - if ( g_gravity->value > 0 ) - { - VectorScale( pushDir, g_knockback->value * knockback / mass * 0.8, kvel ); + if (g_gravity->value > 0) { + VectorScale(pushDir, g_knockback->value * knockback / mass * 0.8, kvel); kvel[2] = pushDir[2] * g_knockback->value * knockback / mass * 1.5; + } else { + VectorScale(pushDir, g_knockback->value * knockback / mass, kvel); } - else - { - VectorScale( pushDir, g_knockback->value * knockback / mass, kvel ); - } - VectorAdd( push_list[x]->s.pos.trDelta, kvel, push_list[x]->s.pos.trDelta ); - if ( g_gravity->value > 0 ) - { - if ( push_list[x]->s.pos.trDelta[2] < knockback ) - { + VectorAdd(push_list[x]->s.pos.trDelta, kvel, push_list[x]->s.pos.trDelta); + if (g_gravity->value > 0) { + if (push_list[x]->s.pos.trDelta[2] < knockback) { push_list[x]->s.pos.trDelta[2] = knockback; } } - //no trDuration? - if ( push_list[x]->e_ThinkFunc != thinkF_G_RunObject ) - {//objects spin themselves? - //spin it - //FIXME: messing with roll ruins the rotational center??? + // no trDuration? + if (push_list[x]->e_ThinkFunc != thinkF_G_RunObject) { // objects spin themselves? + // spin it + // FIXME: messing with roll ruins the rotational center??? push_list[x]->s.apos.trTime = level.time; push_list[x]->s.apos.trType = TR_LINEAR; - VectorClear( push_list[x]->s.apos.trDelta ); - push_list[x]->s.apos.trDelta[1] = Q_irand( -800, 800 ); + VectorClear(push_list[x]->s.apos.trDelta); + push_list[x]->s.apos.trDelta[1] = Q_irand(-800, 800); } - if ( Q_stricmp( "limb", push_list[x]->classname ) == 0 ) - {//make sure it runs it's physics + if (Q_stricmp("limb", push_list[x]->classname) == 0) { // make sure it runs it's physics push_list[x]->e_ThinkFunc = thinkF_LimbThink; push_list[x]->nextthink = level.time + FRAMETIME; } push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms - push_list[x]->forcePuller = self->s.number;//remember this regardless - if ( push_list[x]->item && push_list[x]->item->giTag == INV_SECURITY_KEY ) - { - AddSightEvent( player, push_list[x]->currentOrigin, 128, AEL_DISCOVERED );//security keys are more important - } - else - { - AddSightEvent( player, push_list[x]->currentOrigin, 128, AEL_SUSPICIOUS );//hmm... or should this always be discovered? - } - } - else if ( push_list[x]->s.weapon == WP_TURRET - && !Q_stricmp( "PAS", push_list[x]->classname ) - && push_list[x]->s.apos.trType == TR_STATIONARY ) - {//a portable turret - WP_KnockdownTurret( self, push_list[x] ); - } - } - } - if ( pull ) - { - if ( self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_2 ) - {//at level 3, can pull multiple, so it costs more - actualCost = forcePowerNeeded[FP_PULL]*ent_count; - if ( actualCost > 50 ) - { - actualCost = 50; - } - else if ( actualCost < cost ) - { - actualCost = cost; + push_list[x]->forcePuller = self->s.number; // remember this regardless + if (push_list[x]->item && push_list[x]->item->giTag == INV_SECURITY_KEY) { + AddSightEvent(player, push_list[x]->currentOrigin, 128, AEL_DISCOVERED); // security keys are more important + } else { + AddSightEvent(player, push_list[x]->currentOrigin, 128, AEL_SUSPICIOUS); // hmm... or should this always be discovered? + } + } else if (push_list[x]->s.weapon == WP_TURRET && !Q_stricmp("PAS", push_list[x]->classname) && + push_list[x]->s.apos.trType == TR_STATIONARY) { // a portable turret + WP_KnockdownTurret(self, push_list[x]); } } - else - { - actualCost = cost; - } - WP_ForcePowerStart( self, FP_PULL, actualCost ); } - else - { - if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//at level 3, can push multiple, so costs more - actualCost = forcePowerNeeded[FP_PUSH]*ent_count; - if ( actualCost > 50 ) - { + if (pull) { + if (self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_2) { // at level 3, can pull multiple, so it costs more + actualCost = forcePowerNeeded[FP_PULL] * ent_count; + if (actualCost > 50) { actualCost = 50; - } - else if ( actualCost < cost ) - { + } else if (actualCost < cost) { actualCost = cost; } + } else { + actualCost = cost; } - else if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1 ) - {//at level 2, can push multiple, so costs more - actualCost = floor(forcePowerNeeded[FP_PUSH]*ent_count/1.5f); - if ( actualCost > 50 ) - { + WP_ForcePowerStart(self, FP_PULL, actualCost); + } else { + if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // at level 3, can push multiple, so costs more + actualCost = forcePowerNeeded[FP_PUSH] * ent_count; + if (actualCost > 50) { actualCost = 50; + } else if (actualCost < cost) { + actualCost = cost; } - else if ( actualCost < cost ) - { + } else if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1) { // at level 2, can push multiple, so costs more + actualCost = floor(forcePowerNeeded[FP_PUSH] * ent_count / 1.5f); + if (actualCost > 50) { + actualCost = 50; + } else if (actualCost < cost) { actualCost = cost; } - } - else - { + } else { actualCost = cost; } - WP_ForcePowerStart( self, FP_PUSH, actualCost ); + WP_ForcePowerStart(self, FP_PUSH, actualCost); } - } - else - {//didn't push or pull anything? don't penalize them too much - if ( pull ) - { - WP_ForcePowerStart( self, FP_PULL, 5 ); - } - else - { - WP_ForcePowerStart( self, FP_PUSH, 5 ); + } else { // didn't push or pull anything? don't penalize them too much + if (pull) { + WP_ForcePowerStart(self, FP_PULL, 5); + } else { + WP_ForcePowerStart(self, FP_PUSH, 5); } } - if ( pull ) - { - if ( self->NPC ) - {//NPCs can push more often - //FIXME: vary by rank and game skill? + if (pull) { + if (self->NPC) { // NPCs can push more often + // FIXME: vary by rank and game skill? self->client->ps.forcePowerDebounce[FP_PULL] = level.time + 200; - } - else - { + } else { self->client->ps.forcePowerDebounce[FP_PULL] = level.time + self->client->ps.torsoAnimTimer + 500; } - } - else - { - if ( self->NPC ) - {//NPCs can push more often - //FIXME: vary by rank and game skill? + } else { + if (self->NPC) { // NPCs can push more often + // FIXME: vary by rank and game skill? self->client->ps.forcePowerDebounce[FP_PUSH] = level.time + 200; - } - else - { + } else { self->client->ps.forcePowerDebounce[FP_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; } } } -void WP_DebounceForceDeactivateTime( gentity_t *self ) -{ - //FIXME: if these are interruptable, should they also drain power at a constant rate +void WP_DebounceForceDeactivateTime(gentity_t *self) { + // FIXME: if these are interruptable, should they also drain power at a constant rate // rather than just taking one lump sum of force power upfront? - if ( self && self->client ) - { - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersActive&(1<client->ps.forcePowersActive&(1<client) { + if (self->client->ps.forcePowersActive & (1 << FP_SPEED) || self->client->ps.forcePowersActive & (1 << FP_PROTECT) || + self->client->ps.forcePowersActive & (1 << FP_ABSORB) || self->client->ps.forcePowersActive & (1 << FP_RAGE) || + self->client->ps.forcePowersActive & (1 << FP_SEE)) { // already running another power that can be manually, stopped don't debounce so long self->client->ps.forceAllowDeactivateTime = level.time + 500; - } - else - {//not running one of the interruptable powers - //FIXME: this should be shorter for force speed and rage (because of timescaling) + } else { // not running one of the interruptable powers + // FIXME: this should be shorter for force speed and rage (because of timescaling) self->client->ps.forceAllowDeactivateTime = level.time + 1500; } } } -void ForceSpeed( gentity_t *self, int duration ) -{ - if ( self->health <= 0 ) - { +void ForceSpeed(gentity_t *self, int duration) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.forcePowersActive & (1 << FP_SPEED)) ) - {//stop using it - WP_ForcePowerStop( self, FP_SPEED ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.forcePowersActive & (1 << FP_SPEED))) { // stop using it + WP_ForcePowerStop(self, FP_SPEED); return; } - if ( !WP_ForcePowerUsable( self, FP_SPEED, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_SPEED, 0)) { return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - WP_DebounceForceDeactivateTime( self ); + WP_DebounceForceDeactivateTime(self); - WP_ForcePowerStart( self, FP_SPEED, 0 ); - if ( duration ) - { + WP_ForcePowerStart(self, FP_SPEED, 0); + if (duration) { self->client->ps.forcePowerDuration[FP_SPEED] = level.time + duration; } - G_Sound( self, G_SoundIndex( "sound/weapons/force/speed.wav" ) ); + G_Sound(self, G_SoundIndex("sound/weapons/force/speed.wav")); } -void WP_StartForceHealEffects( gentity_t *self ) -{ - if ( self->ghoul2.size() ) - { - if ( self->chestBolt != -1 ) - { - G_PlayEffect( G_EffectIndex( "force/heal2" ), self->playerModel, self->chestBolt, self->s.number, self->currentOrigin, 3000, qtrue ); +void WP_StartForceHealEffects(gentity_t *self) { + if (self->ghoul2.size()) { + if (self->chestBolt != -1) { + G_PlayEffect(G_EffectIndex("force/heal2"), self->playerModel, self->chestBolt, self->s.number, self->currentOrigin, 3000, qtrue); } /* if ( self->headBolt != -1 ) @@ -10122,13 +7935,10 @@ void WP_StartForceHealEffects( gentity_t *self ) } } -void WP_StopForceHealEffects( gentity_t *self ) -{ - if ( self->ghoul2.size() ) - { - if ( self->chestBolt != -1 ) - { - G_StopEffect( G_EffectIndex( "force/heal2" ), self->playerModel, self->chestBolt, self->s.number ); +void WP_StopForceHealEffects(gentity_t *self) { + if (self->ghoul2.size()) { + if (self->chestBolt != -1) { + G_StopEffect(G_EffectIndex("force/heal2"), self->playerModel, self->chestBolt, self->s.number); } /* if ( self->headBolt != -1 ) @@ -10167,51 +7977,41 @@ void WP_StopForceHealEffects( gentity_t *self ) } } -int FP_MaxForceHeal( gentity_t *self ) -{ - if ( self->s.number >= MAX_CLIENTS ) - { +int FP_MaxForceHeal(gentity_t *self) { + if (self->s.number >= MAX_CLIENTS) { return MAX_FORCE_HEAL_HARD; } - switch ( g_spskill->integer ) - { - case 0://easy + switch (g_spskill->integer) { + case 0: // easy return MAX_FORCE_HEAL_EASY; break; - case 1://medium + case 1: // medium return MAX_FORCE_HEAL_MEDIUM; break; - case 2://hard + case 2: // hard default: return MAX_FORCE_HEAL_HARD; break; } } -int FP_ForceHealInterval( gentity_t *self ) -{ - return (self->client->ps.forcePowerLevel[FP_HEAL]>FORCE_LEVEL_2)?50:FORCE_HEAL_INTERVAL; -} +int FP_ForceHealInterval(gentity_t *self) { return (self->client->ps.forcePowerLevel[FP_HEAL] > FORCE_LEVEL_2) ? 50 : FORCE_HEAL_INTERVAL; } -void ForceHeal( gentity_t *self ) -{ - if ( self->health <= 0 || self->client->ps.stats[STAT_MAX_HEALTH] <= self->health ) - { +void ForceHeal(gentity_t *self) { + if (self->health <= 0 || self->client->ps.stats[STAT_MAX_HEALTH] <= self->health) { return; } - if ( !WP_ForcePowerUsable( self, FP_HEAL, 20 ) ) - {//must have enough force power for at least 5 points of health + if (!WP_ForcePowerUsable(self, FP_HEAL, 20)) { // must have enough force power for at least 5 points of health return; } - if ( self->painDebounceTime > level.time || (self->client->ps.weaponTime&&self->client->ps.weapon!=WP_NONE) ) - {//can't initiate a heal while taking pain or attacking + if (self->painDebounceTime > level.time || + (self->client->ps.weaponTime && self->client->ps.weapon != WP_NONE)) { // can't initiate a heal while taking pain or attacking return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } /* @@ -10234,21 +8034,18 @@ void ForceHeal( gentity_t *self ) else */ { - //start health going up - //NPC_SetAnim( self, SETANIM_TORSO, ?, SETANIM_FLAG_OVERRIDE ); - WP_ForcePowerStart( self, FP_HEAL, 0 ); - if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 ) - {//must meditate - //FIXME: holster weapon (select WP_NONE?) - //FIXME: BOTH_FORCEHEAL_START - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // start health going up + // NPC_SetAnim( self, SETANIM_TORSO, ?, SETANIM_FLAG_OVERRIDE ); + WP_ForcePowerStart(self, FP_HEAL, 0); + if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2) { // must meditate + // FIXME: holster weapon (select WP_NONE?) + // FIXME: BOTH_FORCEHEAL_START + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - self->client->ps.torsoAnimTimer = self->client->ps.legsAnimTimer = FP_ForceHealInterval(self)*FP_MaxForceHeal(self) + 2000;//??? - WP_DeactivateSaber( self );//turn off saber when meditating - } - else - {//just a quick gesture + self->client->ps.torsoAnimTimer = self->client->ps.legsAnimTimer = FP_ForceHealInterval(self) * FP_MaxForceHeal(self) + 2000; //??? + WP_DeactivateSaber(self); // turn off saber when meditating + } else { // just a quick gesture /* //Can't get an anim that looks good... NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEHEAL_QUICK, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); @@ -10258,45 +8055,34 @@ void ForceHeal( gentity_t *self ) } } - //FIXME: always play healing effect - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/heal.mp3" ); + // FIXME: always play healing effect + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/heal.mp3"); } -extern void NPC_PlayConfusionSound( gentity_t *self ); -extern void NPC_Jedi_PlayConfusionSound( gentity_t *self ); -qboolean WP_CheckBreakControl( gentity_t *self ) -{ - if ( !self ) - { +extern void NPC_PlayConfusionSound(gentity_t *self); +extern void NPC_Jedi_PlayConfusionSound(gentity_t *self); +qboolean WP_CheckBreakControl(gentity_t *self) { + if (!self) { return qfalse; } - if ( !self->s.number ) - {//player - if ( self->client && self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control-level - if ( self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//we are in a viewentity + if (!self->s.number) { // player + if (self->client && self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control-level + if (self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD) { // we are in a viewentity gentity_t *controlled = &g_entities[self->client->ps.viewEntity]; - if ( controlled->NPC && controlled->NPC->controlledTime > level.time ) - {//it is an NPC we controlled - //clear it and return - G_ClearViewEntity( self ); + if (controlled->NPC && controlled->NPC->controlledTime > level.time) { // it is an NPC we controlled + // clear it and return + G_ClearViewEntity(self); return qtrue; } } } - } - else - {//NPC - if ( self->NPC && self->NPC->controlledTime > level.time ) - {//being controlled + } else { // NPC + if (self->NPC && self->NPC->controlledTime > level.time) { // being controlled gentity_t *controller = &g_entities[0]; - if ( controller->client && controller->client->ps.viewEntity == self->s.number ) - {//we are being controlled by player - if ( controller->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control-level mind trick - //clear the control and return - G_ClearViewEntity( controller ); + if (controller->client && controller->client->ps.viewEntity == self->s.number) { // we are being controlled by player + if (controller->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control-level mind trick + // clear the control and return + G_ClearViewEntity(controller); return qtrue; } } @@ -10304,63 +8090,53 @@ qboolean WP_CheckBreakControl( gentity_t *self ) } return qfalse; } -extern bool Pilot_AnyVehiclesRegistered(); +extern bool Pilot_AnyVehiclesRegistered(); -void ForceTelepathy( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; - qboolean targetLive = qfalse; +void ForceTelepathy(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; + qboolean targetLive = qfalse; - if ( WP_CheckBreakControl( self ) ) - { + if (WP_CheckBreakControl(self)) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - //FIXME: if mind trick 3 and aiming at an enemy need more force power - if ( !WP_ForcePowerUsable( self, FP_TELEPATHY, 0 ) ) - { + // FIXME: if mind trick 3 and aiming at an enemy need more force power + if (!WP_ForcePowerUsable(self, FP_TELEPATHY, 0)) { return; } - if ( self->client->ps.weaponTime >= 800 ) - {//just did one! + if (self->client->ps.weaponTime >= 800) { // just did one! return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, 2048, forward, end ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, 2048, forward, end); - //Cause a distraction if enemy is not fighting - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_BODY, (EG2_Collision)0, 0 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + // Cause a distraction if enemy is not fighting + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE | CONTENTS_BODY, (EG2_Collision)0, 0); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; - if( traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE ) - { + if (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) { return; } - if ( traceEnt && traceEnt->client ) - { - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grip him, he's in armor - case CLASS_ATST://much too big to grip! - //no droids either + if (traceEnt && traceEnt->client) { + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grip him, he's in armor + case CLASS_ATST: // much too big to grip! + // no droids either case CLASS_PROBE: case CLASS_GONK: case CLASS_R2D2: @@ -10376,8 +8152,7 @@ void ForceTelepathy( gentity_t *self ) case CLASS_BOBAFETT: break; case CLASS_RANCOR: - if ( !(traceEnt->spawnflags&1) ) - { + if (!(traceEnt->spawnflags & 1)) { targetLive = qtrue; } break; @@ -10386,219 +8161,175 @@ void ForceTelepathy( gentity_t *self ) break; } } - if ( targetLive - && traceEnt->NPC - && traceEnt->health > 0 ) - {//hit an organic non-player - if ( G_ActivateBehavior( traceEnt, BSET_MINDTRICK ) ) - {//activated a script on him - //FIXME: do the visual sparkles effect on their heads, still? - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); - } - else if ( traceEnt->client->playerTeam != self->client->playerTeam ) - {//an enemy + if (targetLive && traceEnt->NPC && traceEnt->health > 0) { // hit an organic non-player + if (G_ActivateBehavior(traceEnt, BSET_MINDTRICK)) { // activated a script on him + // FIXME: do the visual sparkles effect on their heads, still? + WP_ForcePowerStart(self, FP_TELEPATHY, 0); + } else if (traceEnt->client->playerTeam != self->client->playerTeam) { // an enemy int override = 0; - if ( (traceEnt->NPC->scriptFlags&SCF_NO_MIND_TRICK) ) - { - if ( traceEnt->client->NPC_class == CLASS_GALAKMECH ) - { - G_AddVoiceEvent( traceEnt, Q_irand( EV_CONFUSE1, EV_CONFUSE3 ), Q_irand( 3000, 5000 ) ); + if ((traceEnt->NPC->scriptFlags & SCF_NO_MIND_TRICK)) { + if (traceEnt->client->NPC_class == CLASS_GALAKMECH) { + G_AddVoiceEvent(traceEnt, Q_irand(EV_CONFUSE1, EV_CONFUSE3), Q_irand(3000, 5000)); } - } - else if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control them, even jedi - G_SetViewEntity( self, traceEnt ); + } else if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control them, even jedi + G_SetViewEntity(self, traceEnt); traceEnt->NPC->controlledTime = level.time + 30000; - } - else if ( traceEnt->s.weapon != WP_SABER - && traceEnt->client->NPC_class != CLASS_REBORN ) - {//haha! Jedi aren't easily confused! - if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2 - && traceEnt->s.weapon != WP_NONE //don't charm people who aren't capable of fighting... like ugnaughts and droids, just confuse them - && traceEnt->client->NPC_class != CLASS_TUSKEN//don't charm them, just confuse them - && traceEnt->client->NPC_class != CLASS_NOGHRI//don't charm them, just confuse them - && !Pilot_AnyVehiclesRegistered() //also, don't charm guys when bikes are near - ) - {//turn them to our side - //if mind trick 3 and aiming at an enemy need more force power + } else if (traceEnt->s.weapon != WP_SABER && traceEnt->client->NPC_class != CLASS_REBORN) { // haha! Jedi aren't easily confused! + if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2 && + traceEnt->s.weapon != WP_NONE // don't charm people who aren't capable of fighting... like ugnaughts and droids, just confuse them + && traceEnt->client->NPC_class != CLASS_TUSKEN // don't charm them, just confuse them + && traceEnt->client->NPC_class != CLASS_NOGHRI // don't charm them, just confuse them + && !Pilot_AnyVehiclesRegistered() // also, don't charm guys when bikes are near + ) { // turn them to our side + // if mind trick 3 and aiming at an enemy need more force power override = 50; - if ( self->client->ps.forcePower < 50 ) - { + if (self->client->ps.forcePower < 50) { return; } - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); } - if ( traceEnt->NPC ) - { - //traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; + if (traceEnt->NPC) { + // traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; traceEnt->client->leader = self; } - //FIXME: maybe pick an enemy right here? - //FIXME: does nothing to TEAM_FREE and TEAM_NEUTRALs!!! - team_t saveTeam = traceEnt->client->enemyTeam; + // FIXME: maybe pick an enemy right here? + // FIXME: does nothing to TEAM_FREE and TEAM_NEUTRALs!!! + team_t saveTeam = traceEnt->client->enemyTeam; traceEnt->client->enemyTeam = traceEnt->client->playerTeam; traceEnt->client->playerTeam = saveTeam; - //FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when done? + // FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when done? traceEnt->NPC->charmedTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]]; - if ( traceEnt->ghoul2.size() && traceEnt->headBolt != -1 ) - {//FIXME: what if already playing effect? - G_PlayEffect( G_EffectIndex( "force/confusion" ), traceEnt->playerModel, traceEnt->headBolt, traceEnt->s.number, traceEnt->currentOrigin, mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]], qtrue ); - } - } - else - {//just confuse them - //somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them pick one up for a while unless shot? - traceEnt->NPC->confusionTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]];//confused for about 10 seconds - if ( traceEnt->ghoul2.size() && traceEnt->headBolt != -1 ) - {//FIXME: what if already playing effect? - G_PlayEffect( G_EffectIndex( "force/confusion" ), traceEnt->playerModel, traceEnt->headBolt, traceEnt->s.number, traceEnt->currentOrigin, mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]], qtrue ); - } - NPC_PlayConfusionSound( traceEnt ); - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); - } - } - } - else - { - NPC_Jedi_PlayConfusionSound( traceEnt ); - } - WP_ForcePowerStart( self, FP_TELEPATHY, override ); - } - else if ( traceEnt->client->playerTeam == self->client->playerTeam ) - {//an ally - //maybe just have him look at you? Respond? Take your enemy? - if ( traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC!=NULL && !(traceEnt->NPC->scriptFlags&SCF_NO_RESPONSE) ) - { - NPC_UseResponse( traceEnt, self, qfalse ); - WP_ForcePowerStart( self, FP_TELEPATHY, 1 ); - } - }//NOTE: no effect on TEAM_NEUTRAL? - vec3_t eyeDir; - AngleVectors( traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL ); - VectorNormalize( eyeDir ); - G_PlayEffect( "force/force_touch", traceEnt->client->renderInfo.eyePoint, eyeDir ); - - //make sure this plays and that you cannot press fire for about 1 second after this - //FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT - NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); - //FIXME: build-up or delay this until in proper part of anim - } - else - { - if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && tr.fraction * 2048 > 64 ) - {//don't create a diversion less than 64 from you of if at power level 1 - //use distraction anim instead - G_PlayEffect( G_EffectIndex( "force/force_touch" ), tr.endpos, tr.plane.normal ); - //FIXME: these events don't seem to always be picked up...? - AddSoundEvent( self, tr.endpos, 512, AEL_SUSPICIOUS, qtrue, qtrue ); - AddSightEvent( self, tr.endpos, 512, AEL_SUSPICIOUS, 50 ); - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); - } - NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); - } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + if (traceEnt->ghoul2.size() && traceEnt->headBolt != -1) { // FIXME: what if already playing effect? + G_PlayEffect(G_EffectIndex("force/confusion"), traceEnt->playerModel, traceEnt->headBolt, traceEnt->s.number, traceEnt->currentOrigin, + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]], qtrue); + } + } else { // just confuse them + // somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them + // pick one up for a while unless shot? + traceEnt->NPC->confusionTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]]; // confused for about 10 seconds + if (traceEnt->ghoul2.size() && traceEnt->headBolt != -1) { // FIXME: what if already playing effect? + G_PlayEffect(G_EffectIndex("force/confusion"), traceEnt->playerModel, traceEnt->headBolt, traceEnt->s.number, traceEnt->currentOrigin, + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]], qtrue); + } + NPC_PlayConfusionSound(traceEnt); + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); + } + } + } else { + NPC_Jedi_PlayConfusionSound(traceEnt); + } + WP_ForcePowerStart(self, FP_TELEPATHY, override); + } else if (traceEnt->client->playerTeam == self->client->playerTeam) { // an ally + // maybe just have him look at you? Respond? Take your enemy? + if (traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC != NULL && !(traceEnt->NPC->scriptFlags & SCF_NO_RESPONSE)) { + NPC_UseResponse(traceEnt, self, qfalse); + WP_ForcePowerStart(self, FP_TELEPATHY, 1); + } + } // NOTE: no effect on TEAM_NEUTRAL? + vec3_t eyeDir; + AngleVectors(traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL); + VectorNormalize(eyeDir); + G_PlayEffect("force/force_touch", traceEnt->client->renderInfo.eyePoint, eyeDir); + + // make sure this plays and that you cannot press fire for about 1 second after this + // FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT + NPC_SetAnim(self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + // FIXME: build-up or delay this until in proper part of anim + } else { + if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && + tr.fraction * 2048 > 64) { // don't create a diversion less than 64 from you of if at power level 1 + // use distraction anim instead + G_PlayEffect(G_EffectIndex("force/force_touch"), tr.endpos, tr.plane.normal); + // FIXME: these events don't seem to always be picked up...? + AddSoundEvent(self, tr.endpos, 512, AEL_SUSPICIOUS, qtrue, qtrue); + AddSightEvent(self, tr.endpos, 512, AEL_SUSPICIOUS, 50); + WP_ForcePowerStart(self, FP_TELEPATHY, 0); + } + NPC_SetAnim(self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN //#define JK2_RAGDOLL_GRIPNOHEALTH -//rww - RAGDOLL_END +// rww - RAGDOLL_END -void ForceGrip( gentity_t *self ) -{//FIXME: make enemy Jedi able to use this - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt = NULL; +void ForceGrip(gentity_t *self) { // FIXME: make enemy Jedi able to use this + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt = NULL; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force grip when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force grip when zoomed in or in cinematic return; } - if ( self->client->ps.leanofs ) - {//can't force-grip while leaning + if (self->client->ps.leanofs) { // can't force-grip while leaning return; } - if ( self->client->ps.forceGripEntityNum <= ENTITYNUM_WORLD ) - {//already gripping - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - { + if (self->client->ps.forceGripEntityNum <= ENTITYNUM_WORLD) { // already gripping + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { self->client->ps.forcePowerDuration[FP_GRIP] = level.time + 100; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } return; } - if ( !WP_ForcePowerUsable( self, FP_GRIP, 0 ) ) - {//can't use it right now + if (!WP_ForcePowerUsable(self, FP_GRIP, 0)) { // can't use it right now return; } - if ( self->client->ps.forcePower < 26 ) - {//need 20 to start, 6 to hold it for any decent amount of time... + if (self->client->ps.forcePower < 26) { // need 20 to start, 6 to hold it for any decent amount of time... return; } - if ( self->client->ps.weaponTime ) - {//busy + if (self->client->ps.weaponTime) { // busy return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - //Cause choking anim + health drain in ent in front of me - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // Cause choking anim + health drain in ent in front of me + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.handLPoint, FORCE_GRIP_DIST, forward, end ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.handLPoint, FORCE_GRIP_DIST, forward, end); - if ( self->enemy ) - {//I have an enemy - if ( !self->enemy->message - && !(self->flags&FL_NO_KNOCKBACK) ) - {//don't auto-pickup guys with keys - if ( DistanceSquared( self->enemy->currentOrigin, self->currentOrigin ) < FORCE_GRIP_DIST_SQUARED ) - {//close enough to grab + if (self->enemy) { // I have an enemy + if (!self->enemy->message && !(self->flags & FL_NO_KNOCKBACK)) { // don't auto-pickup guys with keys + if (DistanceSquared(self->enemy->currentOrigin, self->currentOrigin) < FORCE_GRIP_DIST_SQUARED) { // close enough to grab float minDot = 0.5f; - if ( self->s.number < MAX_CLIENTS ) - {//player needs to be facing more directly + if (self->s.number < MAX_CLIENTS) { // player needs to be facing more directly minDot = 0.2f; } - if ( InFront( self->enemy->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, minDot ) ) //self->s.number || //NPCs can always lift enemy since we assume they're looking at them...? - {//need to be facing the enemy - if ( gi.inPVS( self->enemy->currentOrigin, self->client->renderInfo.eyePoint ) ) - {//must be in PVS - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, self->enemy->currentOrigin, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.fraction == 1.0f || tr.entityNum == self->enemy->s.number ) - {//must have clear LOS + if (InFront(self->enemy->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, + minDot)) // self->s.number || //NPCs can always lift enemy since we assume they're looking at them...? + { // need to be facing the enemy + if (gi.inPVS(self->enemy->currentOrigin, self->client->renderInfo.eyePoint)) { // must be in PVS + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, self->enemy->currentOrigin, self->s.number, MASK_SHOT, + (EG2_Collision)0, 0); + if (tr.fraction == 1.0f || tr.entityNum == self->enemy->s.number) { // must have clear LOS traceEnt = self->enemy; } } @@ -10606,95 +8337,80 @@ void ForceGrip( gentity_t *self ) } } } - if ( !traceEnt ) - {//okay, trace straight ahead and see what's there - gi.trace( &tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + if (!traceEnt) { // okay, trace straight ahead and see what's there + gi.trace(&tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef JK2_RAGDOLL_GRIPNOHEALTH - if ( !traceEnt || traceEnt == self/*???*/ || traceEnt->bmodel || (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) ) - { + if (!traceEnt || traceEnt == self /*???*/ || traceEnt->bmodel || (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE)) { return; } #else -//rww - RAGDOLL_END - if ( !traceEnt || traceEnt == self/*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) ) - { + // rww - RAGDOLL_END + if (!traceEnt || traceEnt == self /*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || + (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE)) { return; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #endif -//rww - RAGDOLL_END - - if ( traceEnt->m_pVehicle != NULL ) - {//is it a vehicle - //grab pilot if there is one - if ( traceEnt->m_pVehicle->m_pPilot != NULL - && traceEnt->m_pVehicle->m_pPilot->client != NULL ) - {//grip the pilot + // rww - RAGDOLL_END + + if (traceEnt->m_pVehicle != NULL) { // is it a vehicle + // grab pilot if there is one + if (traceEnt->m_pVehicle->m_pPilot != NULL && traceEnt->m_pVehicle->m_pPilot->client != NULL) { // grip the pilot traceEnt = traceEnt->m_pVehicle->m_pPilot; - } - else - {//can't grip a vehicle + } else { // can't grip a vehicle return; } } - if ( traceEnt->client ) - { - if ( traceEnt->client->ps.forceJumpZStart ) - {//can't catch them in mid force jump - FIXME: maybe base it on velocity? + if (traceEnt->client) { + if (traceEnt->client->ps.forceJumpZStart) { // can't catch them in mid force jump - FIXME: maybe base it on velocity? return; } - if ( traceEnt->client->ps.pullAttackTime > level.time ) - {//can't grip someone who is being pull-attacked or is pull-attacking + if (traceEnt->client->ps.pullAttackTime > level.time) { // can't grip someone who is being pull-attacked or is pull-attacking return; } - if ( !Q_stricmp("Yoda",traceEnt->NPC_type) ) - { - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + if (!Q_stricmp("Yoda", traceEnt->NPC_type)) { + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return; } - if ( G_IsRidingVehicle( traceEnt ) - && (traceEnt->s.eFlags&EF_NODRAW) ) - {//riding *inside* vehicle + if (G_IsRidingVehicle(traceEnt) && (traceEnt->s.eFlags & EF_NODRAW)) { // riding *inside* vehicle return; } - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grip him, he's in armor - G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand( 3000, 5000 ) ); + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grip him, he's in armor + G_AddVoiceEvent(traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand(3000, 5000)); return; break; - case CLASS_HAZARD_TROOPER://cant grip him, he's in armor + case CLASS_HAZARD_TROOPER: // cant grip him, he's in armor return; break; - case CLASS_ATST://much too big to grip! - case CLASS_RANCOR://much too big to grip! - case CLASS_WAMPA://much too big to grip! - case CLASS_SAND_CREATURE://much too big to grip! + case CLASS_ATST: // much too big to grip! + case CLASS_RANCOR: // much too big to grip! + case CLASS_WAMPA: // much too big to grip! + case CLASS_SAND_CREATURE: // much too big to grip! return; break; - //no droids either...? + // no droids either...? case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: case CLASS_MARK1: case CLASS_MARK2: - case CLASS_MOUSE://? + case CLASS_MOUSE: //? case CLASS_PROTOCOL: //*sigh*... in JK3, you'll be able to grab and move *anything*... return; break; - //not even combat droids? (No animation for being gripped...) + // not even combat droids? (No animation for being gripped...) case CLASS_SABER_DROID: case CLASS_ASSASSIN_DROID: //*sigh*... in JK3, you'll be able to grab and move *anything*... @@ -10708,139 +8424,107 @@ void ForceGrip( gentity_t *self ) //*sigh*... in JK3, you'll be able to grab and move *anything*... return; break; - case CLASS_DESANN://Desann cannot be gripped, he just pushes you back instantly + case CLASS_DESANN: // Desann cannot be gripped, he just pushes you back instantly case CLASS_KYLE: case CLASS_TAVION: case CLASS_LUKE: - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return; break; case CLASS_REBORN: case CLASS_SHADOWTROOPER: case CLASS_ALORA: case CLASS_JEDI: - if ( traceEnt->NPC && traceEnt->NPC->rank > RANK_CIVILIAN && self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - { - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + if (traceEnt->NPC && traceEnt->NPC->rank > RANK_CIVILIAN && self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return; } break; default: break; } - if ( traceEnt->s.weapon == WP_EMPLACED_GUN ) - {//FIXME: maybe can pull them out? - return; - } - if ( self->enemy && traceEnt != self->enemy && traceEnt->client->playerTeam == self->client->playerTeam ) - {//can't accidently grip your teammate in combat + if (traceEnt->s.weapon == WP_EMPLACED_GUN) { // FIXME: maybe can pull them out? return; } -//=CHECKABSORB=== - if ( -1 != WP_AbsorbConversion( traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_GRIP, self->client->ps.forcePowerLevel[FP_GRIP], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_GRIP]]) ) - { - //WP_ForcePowerStop( self, FP_GRIP ); + if (self->enemy && traceEnt != self->enemy && + traceEnt->client->playerTeam == self->client->playerTeam) { // can't accidently grip your teammate in combat return; } -//=============== - } - else - {//can't grip non-clients... right? - //FIXME: Make it so objects flagged as "grabbable" are let through - //if ( Q_stricmp( "misc_model_breakable", traceEnt->classname ) || !(traceEnt->s.eFlags&EF_BOUNCE_HALF) || !traceEnt->physicsBounce ) - { + //=CHECKABSORB=== + if (-1 != WP_AbsorbConversion(traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_GRIP, self->client->ps.forcePowerLevel[FP_GRIP], + forcePowerNeeded[self->client->ps.forcePowerLevel[FP_GRIP]])) { + // WP_ForcePowerStop( self, FP_GRIP ); return; } + //=============== + } else { // can't grip non-clients... right? + // FIXME: Make it so objects flagged as "grabbable" are let through + // if ( Q_stricmp( "misc_model_breakable", traceEnt->classname ) || !(traceEnt->s.eFlags&EF_BOUNCE_HALF) || !traceEnt->physicsBounce ) + { return; } } // Make sure to turn off Force Protection and Force Absorb. - if (self->client->ps.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); } - if (self->client->ps.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); } - WP_ForcePowerStart( self, FP_GRIP, 20 ); - //FIXME: rule out other things? - //FIXME: Jedi resist, like the push and pull? + WP_ForcePowerStart(self, FP_GRIP, 20); + // FIXME: rule out other things? + // FIXME: Jedi resist, like the push and pull? self->client->ps.forceGripEntityNum = traceEnt->s.number; - if ( traceEnt->client ) - { + if (traceEnt->client) { Vehicle_t *pVeh; - if ( ( pVeh = G_IsRidingVehicle( traceEnt ) ) != NULL ) - {//riding vehicle? pull him off! - //FIXME: if in an AT-ST or X-Wing, shouldn't do this... :) - //pull him off of it + if ((pVeh = G_IsRidingVehicle(traceEnt)) != NULL) { // riding vehicle? pull him off! + // FIXME: if in an AT-ST or X-Wing, shouldn't do this... :) + // pull him off of it //((CVehicleNPC *)traceEnt->NPC)->Eject( traceEnt ); - pVeh->m_pVehicleInfo->Eject( pVeh, traceEnt, qtrue ); - //G_DriveVehicle( traceEnt, NULL, NULL ); - } - G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 || traceEnt->s.weapon == WP_SABER ) - {//if we pick up & carry, drop their weap - if ( traceEnt->s.weapon - && traceEnt->client->NPC_class != CLASS_ROCKETTROOPER - && traceEnt->client->NPC_class != CLASS_VEHICLE - && traceEnt->client->NPC_class != CLASS_HAZARD_TROOPER - && traceEnt->client->NPC_class != CLASS_TUSKEN - && traceEnt->client->NPC_class != CLASS_BOBAFETT - && traceEnt->client->NPC_class != CLASS_ASSASSIN_DROID - && traceEnt->s.weapon != WP_CONCUSSION // so rax can't drop his - ) - { - if ( traceEnt->client->NPC_class == CLASS_BOBAFETT ) - {//he doesn't drop them, just puts it away - ChangeWeapon( traceEnt, WP_MELEE ); - } - else if ( traceEnt->s.weapon == WP_MELEE ) - {//they can't take that away from me, oh no... - } - else if ( traceEnt->NPC - && (traceEnt->NPC->scriptFlags&SCF_DONT_FLEE) ) - {//*SIGH*... if an NPC can't flee, they can't run after and pick up their weapon, do don't drop it - } - else if ( traceEnt->s.weapon != WP_SABER ) - { - WP_DropWeapon( traceEnt, NULL ); - } - else - { - //turn it off? + pVeh->m_pVehicleInfo->Eject(pVeh, traceEnt, qtrue); + // G_DriveVehicle( traceEnt, NULL, NULL ); + } + G_AddVoiceEvent(traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 || traceEnt->s.weapon == WP_SABER) { // if we pick up & carry, drop their weap + if (traceEnt->s.weapon && traceEnt->client->NPC_class != CLASS_ROCKETTROOPER && traceEnt->client->NPC_class != CLASS_VEHICLE && + traceEnt->client->NPC_class != CLASS_HAZARD_TROOPER && traceEnt->client->NPC_class != CLASS_TUSKEN && + traceEnt->client->NPC_class != CLASS_BOBAFETT && traceEnt->client->NPC_class != CLASS_ASSASSIN_DROID && + traceEnt->s.weapon != WP_CONCUSSION // so rax can't drop his + ) { + if (traceEnt->client->NPC_class == CLASS_BOBAFETT) { // he doesn't drop them, just puts it away + ChangeWeapon(traceEnt, WP_MELEE); + } else if (traceEnt->s.weapon == WP_MELEE) { // they can't take that away from me, oh no... + } else if (traceEnt->NPC && (traceEnt->NPC->scriptFlags & + SCF_DONT_FLEE)) { //*SIGH*... if an NPC can't flee, they can't run after and pick up their weapon, do don't drop it + } else if (traceEnt->s.weapon != WP_SABER) { + WP_DropWeapon(traceEnt, NULL); + } else { + // turn it off? traceEnt->client->ps.SaberDeactivate(); - G_SoundOnEnt( traceEnt, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav" ); + G_SoundOnEnt(traceEnt, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav"); } } } - //else FIXME: need a one-armed choke if we're not on a high enough level to make them drop their gun - VectorCopy( traceEnt->client->renderInfo.headPoint, self->client->ps.forceGripOrg ); - } - else - { - VectorCopy( traceEnt->currentOrigin, self->client->ps.forceGripOrg ); + // else FIXME: need a one-armed choke if we're not on a high enough level to make them drop their gun + VectorCopy(traceEnt->client->renderInfo.headPoint, self->client->ps.forceGripOrg); + } else { + VectorCopy(traceEnt->currentOrigin, self->client->ps.forceGripOrg); } - self->client->ps.forceGripOrg[2] += 48;//FIXME: define? - if ( self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//just a duration + self->client->ps.forceGripOrg[2] += 48; // FIXME: define? + if (self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // just a duration self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 250; self->client->ps.forcePowerDuration[FP_GRIP] = level.time + 5000; - if ( self->m_pVehicle && self->m_pVehicle->m_pVehicleInfo->Inhabited( self->m_pVehicle ) ) - {//empty vehicles don't make gripped noise - traceEnt->s.loopSound = G_SoundIndex( "sound/weapons/force/grip.mp3" ); + if (self->m_pVehicle && self->m_pVehicle->m_pVehicleInfo->Inhabited(self->m_pVehicle)) { // empty vehicles don't make gripped noise + traceEnt->s.loopSound = G_SoundIndex("sound/weapons/force/grip.mp3"); } - } - else - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 ) - {//lifting sound? or always? + } else { + if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2) { // lifting sound? or always? } - //if ( traceEnt->s.number ) - {//picks them up for a second first + // if ( traceEnt->s.number ) + { // picks them up for a second first self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 1000; } /* @@ -10849,108 +8533,81 @@ void ForceGrip( gentity_t *self ) self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 250; } */ - // force grip sound should only play when the target is alive? - // if (traceEnt->health>0) - // { - self->s.loopSound = G_SoundIndex( "sound/weapons/force/grip.mp3" ); - // } + // force grip sound should only play when the target is alive? + // if (traceEnt->health>0) + // { + self->s.loopSound = G_SoundIndex("sound/weapons/force/grip.mp3"); + // } } } -qboolean ForceLightningCheck2Handed( gentity_t *self ) -{ - if ( self && self->client ) - { - if ( self->s.weapon == WP_NONE - || self->s.weapon == WP_MELEE - || (self->s.weapon == WP_SABER && !self->client->ps.SaberActive()) ) - { +qboolean ForceLightningCheck2Handed(gentity_t *self) { + if (self && self->client) { + if (self->s.weapon == WP_NONE || self->s.weapon == WP_MELEE || (self->s.weapon == WP_SABER && !self->client->ps.SaberActive())) { return qtrue; } } return qfalse; } -void ForceLightningAnim( gentity_t *self ) -{ - if ( !self || !self->client ) - { +void ForceLightningAnim(gentity_t *self) { + if (!self || !self->client) { return; } - //one-handed lightning 2 and above + // one-handed lightning 2 and above int startAnim = BOTH_FORCELIGHTNING_START; int holdAnim = BOTH_FORCELIGHTNING_HOLD; - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] >= FORCE_LEVEL_3 - && ForceLightningCheck2Handed( self ) ) - {//empty handed lightning 3 + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] >= FORCE_LEVEL_3 && ForceLightningCheck2Handed(self)) { // empty handed lightning 3 startAnim = BOTH_FORCE_2HANDEDLIGHTNING_START; holdAnim = BOTH_FORCE_2HANDEDLIGHTNING_HOLD; } - //FIXME: if standing still, play on whole body? Especially 2-handed version - if ( self->client->ps.torsoAnim == startAnim ) - { - if ( !self->client->ps.torsoAnimTimer ) - { - NPC_SetAnim( self, SETANIM_TORSO, holdAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, startAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // FIXME: if standing still, play on whole body? Especially 2-handed version + if (self->client->ps.torsoAnim == startAnim) { + if (!self->client->ps.torsoAnimTimer) { + NPC_SetAnim(self, SETANIM_TORSO, holdAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_TORSO, startAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, holdAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(self, SETANIM_TORSO, holdAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } -void ForceLightning( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceLightning(gentity_t *self) { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force lightning when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force lightning when zoomed in or in cinematic return; } - if ( self->client->ps.leanofs ) - {//can't force-lightning while leaning + if (self->client->ps.leanofs) { // can't force-lightning while leaning return; } - if ( self->client->ps.forcePower < 25 || !WP_ForcePowerUsable( self, FP_LIGHTNING, 0 ) ) - { + if (self->client->ps.forcePower < 25 || !WP_ForcePowerUsable(self, FP_LIGHTNING, 0)) { return; } - if ( self->client->ps.forcePowerDebounce[FP_LIGHTNING] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.forcePowerDebounce[FP_LIGHTNING] > level.time) { // stops it while using it and also after using it, up to 3 second delay return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } // Make sure to turn off Force Protection and Force Absorb. - if (self->client->ps.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); - } - if (self->client->ps.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); - } - //Shoot lightning from hand - //make sure this plays and that you cannot press fire for about 1 second after this - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - ForceLightningAnim( self ); + if (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); + } + if (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); + } + // Shoot lightning from hand + // make sure this plays and that you cannot press fire for about 1 second after this + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + ForceLightningAnim(self); /* if ( ForceLightningCheck2Handed( self ) ) {//empty handed lightning 3 @@ -10962,189 +8619,141 @@ void ForceLightning( gentity_t *self ) } */ } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - {//short burst - //G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); - } - else - {//holding it - self->s.loopSound = G_SoundIndex( "sound/weapons/force/lightning2.wav" ); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/lightning.wav"); + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2) { // short burst + // G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); + } else { // holding it + self->s.loopSound = G_SoundIndex("sound/weapons/force/lightning2.wav"); } - //FIXME: build-up or delay this until in proper part of anim + // FIXME: build-up or delay this until in proper part of anim self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - WP_ForcePowerStart( self, FP_LIGHTNING, self->client->ps.torsoAnimTimer ); + WP_ForcePowerStart(self, FP_LIGHTNING, self->client->ps.torsoAnimTimer); } -void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, float dist, float dot, vec3_t impactPoint ) -{ - if( traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE ) - { +void ForceLightningDamage(gentity_t *self, gentity_t *traceEnt, vec3_t dir, float dist, float dot, vec3_t impactPoint) { + if (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) { return; } - if ( traceEnt && traceEnt->takedamage ) - { - if ( !traceEnt->client || traceEnt->client->playerTeam != self->client->playerTeam || self->enemy == traceEnt || traceEnt->enemy == self ) - {//an enemy or object - int dmg; - //FIXME: check for client using FP_ABSORB - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//more damage if closer and more in front + if (traceEnt && traceEnt->takedamage) { + if (!traceEnt->client || traceEnt->client->playerTeam != self->client->playerTeam || self->enemy == traceEnt || + traceEnt->enemy == self) { // an enemy or object + int dmg; + // FIXME: check for client using FP_ABSORB + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // more damage if closer and more in front dmg = 1; - if ( self->client->NPC_class == CLASS_REBORN - && self->client->ps.weapon == WP_NONE ) - {//Cultist: looks fancy, but does less damage - } - else - { - if ( dist < 100 ) - { + if (self->client->NPC_class == CLASS_REBORN && self->client->ps.weapon == WP_NONE) { // Cultist: looks fancy, but does less damage + } else { + if (dist < 100) { dmg += 2; - } - else if ( dist < 200 ) - { + } else if (dist < 200) { dmg += 1; } - if ( dot > 0.9f ) - { + if (dot > 0.9f) { dmg += 2; - } - else if ( dot > 0.7f ) - { + } else if (dot > 0.7f) { dmg += 1; } } - if ( self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE ) - {//jackin' 'em up, Palpatine-style + if (self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START || + self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD || + self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE) { // jackin' 'em up, Palpatine-style dmg *= 2; } - } - else - { - dmg = Q_irand( 1, 3 );//*self->client->ps.forcePowerLevel[FP_LIGHTNING]; + } else { + dmg = Q_irand(1, 3); //*self->client->ps.forcePowerLevel[FP_LIGHTNING]; } - if ( traceEnt->client - && traceEnt->health > 0 - && traceEnt->NPC - && (traceEnt->NPC->aiFlags&NPCAI_BOSS_CHARACTER) ) - {//Luke, Desann Tavion and Kyle can shield themselves from the attack - //FIXME: shield effect or something? + if (traceEnt->client && traceEnt->health > 0 && traceEnt->NPC && + (traceEnt->NPC->aiFlags & NPCAI_BOSS_CHARACTER)) { // Luke, Desann Tavion and Kyle can shield themselves from the attack + // FIXME: shield effect or something? int parts; - if ( traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim( traceEnt->client->ps.legsAnim ) && !PM_FlippingAnim( traceEnt->client->ps.legsAnim ) && !PM_RollingAnim( traceEnt->client->ps.legsAnim ) ) - {//if on a surface and not in a spin or flip, play full body resist + if (traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(traceEnt->client->ps.legsAnim) && + !PM_FlippingAnim(traceEnt->client->ps.legsAnim) && + !PM_RollingAnim(traceEnt->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body resist parts = SETANIM_BOTH; - } - else - {//play resist just in torso + } else { // play resist just in torso parts = SETANIM_TORSO; } - //FIXME: don't interrupt big anims with this! - NPC_SetAnim( traceEnt, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - Jedi_PlayDeflectSound( traceEnt ); - dmg = Q_irand(0,1); - } - else if ( traceEnt->s.weapon == WP_SABER ) - {//saber can block lightning - if ( traceEnt->client //a client - && !traceEnt->client->ps.saberInFlight//saber in hand - && ( traceEnt->client->ps.saberMove == LS_READY || PM_SaberInParry( traceEnt->client->ps.saberMove ) || PM_SaberInReturn( traceEnt->client->ps.saberMove ) )//not attacking with saber - && InFOV( self->currentOrigin, traceEnt->currentOrigin, traceEnt->client->ps.viewangles, 20, 35 ) //I'm in front of them - && !PM_InKnockDown( &traceEnt->client->ps ) //they're not in a knockdown - && !PM_SuperBreakLoseAnim( traceEnt->client->ps.torsoAnim ) - && !PM_SuperBreakWinAnim( traceEnt->client->ps.torsoAnim ) - && !PM_SaberInSpecialAttack( traceEnt->client->ps.torsoAnim ) - && !PM_InSpecialJump( traceEnt->client->ps.torsoAnim ) - && (!traceEnt->s.number||(traceEnt->NPC&&traceEnt->NPC->rank>=RANK_LT_COMM)) )//the player or a tough jedi/reborn - { - if ( Q_irand( 0, traceEnt->client->ps.forcePowerLevel[FP_SABER_DEFENSE]*3 ) > 0 )//more of a chance of defending if saber defense is high + // FIXME: don't interrupt big anims with this! + NPC_SetAnim(traceEnt, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + Jedi_PlayDeflectSound(traceEnt); + dmg = Q_irand(0, 1); + } else if (traceEnt->s.weapon == WP_SABER) { // saber can block lightning + if (traceEnt->client // a client + && !traceEnt->client->ps.saberInFlight // saber in hand + && (traceEnt->client->ps.saberMove == LS_READY || PM_SaberInParry(traceEnt->client->ps.saberMove) || + PM_SaberInReturn(traceEnt->client->ps.saberMove)) // not attacking with saber + && InFOV(self->currentOrigin, traceEnt->currentOrigin, traceEnt->client->ps.viewangles, 20, 35) // I'm in front of them + && !PM_InKnockDown(&traceEnt->client->ps) // they're not in a knockdown + && !PM_SuperBreakLoseAnim(traceEnt->client->ps.torsoAnim) && !PM_SuperBreakWinAnim(traceEnt->client->ps.torsoAnim) && + !PM_SaberInSpecialAttack(traceEnt->client->ps.torsoAnim) && !PM_InSpecialJump(traceEnt->client->ps.torsoAnim) && + (!traceEnt->s.number || (traceEnt->NPC && traceEnt->NPC->rank >= RANK_LT_COMM))) // the player or a tough jedi/reborn + { + if (Q_irand(0, traceEnt->client->ps.forcePowerLevel[FP_SABER_DEFENSE] * 3) > 0) // more of a chance of defending if saber defense is high { dmg = 0; } - if ( (traceEnt->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_2 ) - {//no parry, just absorb - } - else - { - //make them do a parry + if ((traceEnt->client->ps.forcePowersActive & (1 << FP_ABSORB)) && + traceEnt->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_2) { // no parry, just absorb + } else { + // make them do a parry traceEnt->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - int parryReCalcTime = Jedi_ReCalcParryTime( traceEnt, EVASION_PARRY ); - if ( traceEnt->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + int parryReCalcTime = Jedi_ReCalcParryTime(traceEnt, EVASION_PARRY); + if (traceEnt->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { traceEnt->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } - traceEnt->client->ps.weaponTime = Q_irand( 100, 300 );//hold this move - can't attack! - FIXME: unless dual sabers? + traceEnt->client->ps.weaponTime = Q_irand(100, 300); // hold this move - can't attack! - FIXME: unless dual sabers? } - } - else if ( Q_irand( 0, 1 ) ) - {//jedi less likely to be damaged + } else if (Q_irand(0, 1)) { // jedi less likely to be damaged dmg = 0; - } - else - { + } else { dmg = 1; } } - if ( traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_GALAK_SHIELD] ) - { - //has shield up + if (traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_GALAK_SHIELD]) { + // has shield up dmg = 0; } int modPowerLevel = -1; - if (traceEnt->client) - { - modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_LIGHTNING, self->client->ps.forcePowerLevel[FP_LIGHTNING], 1); + if (traceEnt->client) { + modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_LIGHTNING, + self->client->ps.forcePowerLevel[FP_LIGHTNING], 1); } - if (modPowerLevel != -1) - { - if ( !modPowerLevel ) - { + if (modPowerLevel != -1) { + if (!modPowerLevel) { dmg = 0; - } - else if ( modPowerLevel == 1 ) - { - dmg = floor((float)dmg/4.0f); - } - else if ( modPowerLevel == 2 ) - { - dmg = floor((float)dmg/2.0f); + } else if (modPowerLevel == 1) { + dmg = floor((float)dmg / 4.0f); + } else if (modPowerLevel == 2) { + dmg = floor((float)dmg / 2.0f); } } - //FIXME: if ForceDrain, sap force power and add health to self, use different sound & effects - if ( dmg ) - { - G_Damage( traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_LIGHTNING ); + // FIXME: if ForceDrain, sap force power and add health to self, use different sound & effects + if (dmg) { + G_Damage(traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_LIGHTNING); } - if ( traceEnt->client ) - { - if ( !Q_irand( 0, 2 ) ) - { - G_Sound( traceEnt, G_SoundIndex( va( "sound/weapons/force/lightninghit%d.wav", Q_irand( 1, 3 ) ) ) ); + if (traceEnt->client) { + if (!Q_irand(0, 2)) { + G_Sound(traceEnt, G_SoundIndex(va("sound/weapons/force/lightninghit%d.wav", Q_irand(1, 3)))); } - traceEnt->s.powerups |= ( 1 << PW_SHOCKED ); + traceEnt->s.powerups |= (1 << PW_SHOCKED); // If we are dead or we are a bot, we can do the full version class_t npc_class = traceEnt->client->NPC_class; - if ( traceEnt->health <= 0 || ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || - npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || - npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST ) || - npc_class == CLASS_SENTRY ) - { + if (traceEnt->health <= 0 || + (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_REMOTE || npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || + npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST) || + npc_class == CLASS_SENTRY) { traceEnt->client->ps.powerups[PW_SHOCKED] = level.time + 4000; - } - else //short version + } else // short version { traceEnt->client->ps.powerups[PW_SHOCKED] = level.time + 500; } @@ -11153,205 +8762,175 @@ void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, flo } } -void ForceShootLightning( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; +void ForceShootLightning(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && cg.zoomMode ) - {//can't force lightning when zoomed in + if (!self->s.number && cg.zoomMode) { // can't force lightning when zoomed in return; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); - //FIXME: if lightning hits water, do water-only-flagged radius damage from that point - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t center, mins, maxs, dir, ent_org, size, v; - float radius = 512, dot, dist; - gentity_t *entityList[MAX_GENTITIES]; - int e, numListedEntities, i; + // FIXME: if lightning hits water, do water-only-flagged radius damage from that point + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t center, mins, maxs, dir, ent_org, size, v; + float radius = 512, dot, dist; + gentity_t *entityList[MAX_GENTITIES]; + int e, numListedEntities, i; - VectorCopy( self->currentOrigin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + VectorCopy(self->currentOrigin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { traceEnt = entityList[e]; - if ( !traceEnt ) + if (!traceEnt) continue; - if ( traceEnt == self ) + if (traceEnt == self) continue; - if ( traceEnt->owner == self && traceEnt->s.weapon != WP_THERMAL )//can push your own thermals + if (traceEnt->owner == self && traceEnt->s.weapon != WP_THERMAL) // can push your own thermals continue; - if ( !traceEnt->inuse ) + if (!traceEnt->inuse) continue; - if ( !traceEnt->takedamage ) + if (!traceEnt->takedamage) continue; /* if ( traceEnt->health <= 0 )//no torturing corpses continue; */ - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < traceEnt->absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < traceEnt->absmin[i]) { v[i] = traceEnt->absmin[i] - center[i]; - } else if ( center[i] > traceEnt->absmax[i] ) - { + } else if (center[i] > traceEnt->absmax[i]) { v[i] = center[i] - traceEnt->absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( traceEnt->absmax, traceEnt->absmin, size ); - VectorMA( traceEnt->absmin, 0.5, size, ent_org ); + VectorSubtract(traceEnt->absmax, traceEnt->absmin, size); + VectorMA(traceEnt->absmin, 0.5, size, ent_org); - //see if they're in front of me - //must be within the forward cone - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot = DotProduct( dir, forward )) < 0.5 ) + // see if they're in front of me + // must be within the forward cone + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot = DotProduct(dir, forward)) < 0.5) continue; - //must be close enough - dist = VectorLength( v ); - if ( dist >= radius ) - { + // must be close enough + dist = VectorLength(v); + if (dist >= radius) { continue; } - //in PVS? - if ( !traceEnt->bmodel && !gi.inPVS( ent_org, self->client->renderInfo.handLPoint ) ) - {//must be in PVS + // in PVS? + if (!traceEnt->bmodel && !gi.inPVS(ent_org, self->client->renderInfo.handLPoint)) { // must be in PVS continue; } - //Now check and see if we can actually hit it - gi.trace( &tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number ) - {//must have clear LOS + // Now check and see if we can actually hit it + gi.trace(&tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number) { // must have clear LOS continue; } // ok, we are within the radius, add us to the incoming list - //FIXME: maybe add up the ents and do more damage the less ents there are + // FIXME: maybe add up the ents and do more damage the less ents there are // as if we're spreading out the damage? - ForceLightningDamage( self, traceEnt, dir, dist, dot, ent_org ); + ForceLightningDamage(self, traceEnt, dir, dist, dot, ent_org); } - } - else - {//trace-line + } else { // trace-line int ignore = self->s.number; int traces = 0; - vec3_t start; + vec3_t start; - VectorCopy( self->client->renderInfo.handLPoint, start ); - VectorMA( self->client->renderInfo.handLPoint, 2048, forward, end ); + VectorCopy(self->client->renderInfo.handLPoint, start); + VectorMA(self->client->renderInfo.handLPoint, 2048, forward, end); - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 10); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; - //NOTE: only NPCs do this auto-dodge - if ( traceEnt - && traceEnt->s.number >= MAX_CLIENTS - && traceEnt->client - && traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 )//&& traceEnt->NPC - {//FIXME: need a more reliable way to know we hit a jedi? - if ( !Jedi_DodgeEvasion( traceEnt, self, &tr, HL_NONE ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + // NOTE: only NPCs do this auto-dodge + if (traceEnt && traceEnt->s.number >= MAX_CLIENTS && traceEnt->client && + traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) //&& traceEnt->NPC + { // FIXME: need a more reliable way to know we hit a jedi? + if (!Jedi_DodgeEvasion(traceEnt, self, &tr, HL_NONE)) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } traceEnt = &g_entities[tr.entityNum]; - ForceLightningDamage( self, traceEnt, forward, 0, 0, tr.endpos ); + ForceLightningDamage(self, traceEnt, forward, 0, 0, tr.endpos); } } -void WP_DeactivateSaber( gentity_t *self, qboolean clearLength ) -{ - if ( !self || !self->client ) - { +void WP_DeactivateSaber(gentity_t *self, qboolean clearLength) { + if (!self || !self->client) { return; } - //keep my saber off! - if ( self->client->ps.SaberActive() ) - { + // keep my saber off! + if (self->client->ps.SaberActive()) { self->client->ps.SaberDeactivate(); - if ( clearLength ) - { - self->client->ps.SetSaberLength( 0 ); + if (clearLength) { + self->client->ps.SetSaberLength(0); } - G_SoundIndexOnEnt( self, CHAN_WEAPON, self->client->ps.saber[0].soundOff ); + G_SoundIndexOnEnt(self, CHAN_WEAPON, self->client->ps.saber[0].soundOff); } } -static void ForceShootDrain( gentity_t *self ); +static void ForceShootDrain(gentity_t *self); -void ForceDrainGrabStart( gentity_t *self ) -{ - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in +void ForceDrainGrabStart(gentity_t *self) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } - //actually grabbing someone, so turn off the saber! - WP_DeactivateSaber( self, qtrue ); + // actually grabbing someone, so turn off the saber! + WP_DeactivateSaber(self, qtrue); } -qboolean ForceDrain2( gentity_t *self ) -{//FIXME: make enemy Jedi able to use this - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt = NULL; +qboolean ForceDrain2(gentity_t *self) { // FIXME: make enemy Jedi able to use this + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt = NULL; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return qtrue; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force grip when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force grip when zoomed in or in cinematic return qtrue; } - if ( self->client->ps.leanofs ) - {//can't force-drain while leaning + if (self->client->ps.leanofs) { // can't force-drain while leaning return qtrue; } @@ -11362,95 +8941,81 @@ qboolean ForceDrain2( gentity_t *self ) } */ - if ( self->client->ps.forceDrainEntityNum <= ENTITYNUM_WORLD ) - {//already draining - //keep my saber off! - WP_DeactivateSaber( self, qtrue ); - if ( self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 ) - { + if (self->client->ps.forceDrainEntityNum <= ENTITYNUM_WORLD) { // already draining + // keep my saber off! + WP_DeactivateSaber(self, qtrue); + if (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1) { self->client->ps.forcePowerDuration[FP_DRAIN] = level.time + 100; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } return qtrue; } - if ( self->client->ps.forcePowerDebounce[FP_DRAIN] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.forcePowerDebounce[FP_DRAIN] > level.time) { // stops it while using it and also after using it, up to 3 second delay return qtrue; } - if ( self->client->ps.weaponTime > 0 ) - {//busy + if (self->client->ps.weaponTime > 0) { // busy return qtrue; } - if ( self->client->ps.forcePower < 25 || !WP_ForcePowerUsable( self, FP_DRAIN, 0 ) ) - { + if (self->client->ps.forcePower < 25 || !WP_ForcePowerUsable(self, FP_DRAIN, 0)) { return qtrue; } - if ( self->client->ps.saberLockTime > level.time ) - {//in saberlock + if (self->client->ps.saberLockTime > level.time) { // in saberlock return qtrue; } - //NOTE: from here on, if it fails, it's okay to try a normal drain, so return qfalse - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//in air + // NOTE: from here on, if it fails, it's okay to try a normal drain, so return qfalse + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // in air return qfalse; } - //Cause choking anim + health drain in ent in front of me - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, FORCE_DRAIN_DIST, forward, end ); + // Cause choking anim + health drain in ent in front of me + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, FORCE_DRAIN_DIST, forward, end); - //okay, trace straight ahead and see what's there - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0 ); - if ( tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + // okay, trace straight ahead and see what's there + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, (EG2_Collision)0, 0); + if (tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return qfalse; } traceEnt = &g_entities[tr.entityNum]; - if ( !traceEnt || traceEnt == self/*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) ) - { + if (!traceEnt || traceEnt == self /*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || + (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE)) { return qfalse; } - if ( traceEnt->client ) - { - if ( traceEnt->client->ps.forceJumpZStart ) - {//can't catch them in mid force jump - FIXME: maybe base it on velocity? + if (traceEnt->client) { + if (traceEnt->client->ps.forceJumpZStart) { // can't catch them in mid force jump - FIXME: maybe base it on velocity? return qfalse; } - if ( traceEnt->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//can't catch them in mid air + if (traceEnt->client->ps.groundEntityNum == ENTITYNUM_NONE) { // can't catch them in mid air return qfalse; } - if ( !Q_stricmp("Yoda",traceEnt->NPC_type) ) - { - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + if (!Q_stricmp("Yoda", traceEnt->NPC_type)) { + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return qtrue; } - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grab him, he's in armor - G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand( 3000, 5000 ) ); + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grab him, he's in armor + G_AddVoiceEvent(traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand(3000, 5000)); return qfalse; break; - case CLASS_ROCKETTROOPER://cant grab him, he's in armor - case CLASS_HAZARD_TROOPER://cant grab him, he's in armor + case CLASS_ROCKETTROOPER: // cant grab him, he's in armor + case CLASS_HAZARD_TROOPER: // cant grab him, he's in armor return qfalse; break; - case CLASS_ATST://much too big to grab! + case CLASS_ATST: // much too big to grab! return qfalse; break; - //no droids either + // no droids either case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: @@ -11469,69 +9034,61 @@ qboolean ForceDrain2( gentity_t *self ) case CLASS_INTERROGATOR: return qfalse; break; - case CLASS_DESANN://Desann cannot be gripped, he just pushes you back instantly + case CLASS_DESANN: // Desann cannot be gripped, he just pushes you back instantly case CLASS_KYLE: case CLASS_TAVION: case CLASS_LUKE: - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return qtrue; break; case CLASS_REBORN: case CLASS_SHADOWTROOPER: - //case CLASS_ALORA: + // case CLASS_ALORA: case CLASS_JEDI: - if ( traceEnt->NPC - && traceEnt->NPC->rank > RANK_CIVILIAN - && self->client->ps.forcePowerLevel[FP_DRAIN] < FORCE_LEVEL_2 - && traceEnt->client->ps.weaponTime <= 0 ) - { - ForceDrainGrabStart( self ); - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + if (traceEnt->NPC && traceEnt->NPC->rank > RANK_CIVILIAN && self->client->ps.forcePowerLevel[FP_DRAIN] < FORCE_LEVEL_2 && + traceEnt->client->ps.weaponTime <= 0) { + ForceDrainGrabStart(self); + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return qtrue; } break; default: break; } - if ( traceEnt->s.weapon == WP_EMPLACED_GUN ) - {//FIXME: maybe can pull them out? + if (traceEnt->s.weapon == WP_EMPLACED_GUN) { // FIXME: maybe can pull them out? return qfalse; } - if ( traceEnt != self->enemy && OnSameTeam(self, traceEnt) ) - {//can't accidently grip-drain your teammate + if (traceEnt != self->enemy && OnSameTeam(self, traceEnt)) { // can't accidently grip-drain your teammate return qfalse; } -//=CHECKABSORB=== + //=CHECKABSORB=== /* - if ( -1 != WP_AbsorbConversion( traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.forcePowerLevel[FP_DRAIN], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]]) ) + if ( -1 != WP_AbsorbConversion( traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.forcePowerLevel[FP_DRAIN], + forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]]) ) { //WP_ForcePowerStop( self, FP_DRAIN ); return; } */ -//=============== - if ( !FP_ForceDrainGrippableEnt( traceEnt ) ) - { + //=============== + if (!FP_ForceDrainGrippableEnt(traceEnt)) { return qfalse; } - } - else - {//can't drain non-clients + } else { // can't drain non-clients return qfalse; } - ForceDrainGrabStart( self ); + ForceDrainGrabStart(self); - WP_ForcePowerStart( self, FP_DRAIN, 10 ); + WP_ForcePowerStart(self, FP_DRAIN, 10); self->client->ps.forceDrainEntityNum = traceEnt->s.number; -// G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); - G_AddVoiceEvent( traceEnt, Q_irand(EV_CHOKE1, EV_CHOKE3), 2000 ); - if ( /*self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ||*/ traceEnt->s.weapon == WP_SABER ) - {//if we pick up, turn off their weapon - WP_DeactivateSaber( traceEnt, qtrue ); + // G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + G_AddVoiceEvent(traceEnt, Q_irand(EV_CHOKE1, EV_CHOKE3), 2000); + if (/*self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ||*/ traceEnt->s.weapon == WP_SABER) { // if we pick up, turn off their weapon + WP_DeactivateSaber(traceEnt, qtrue); } /* @@ -11542,81 +9099,69 @@ qboolean ForceDrain2( gentity_t *self ) } */ - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/drain.mp3" ); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/drain.mp3"); -// NPC_SetAnim( traceEnt, SETANIM_BOTH, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC_SetAnim( traceEnt, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRABBED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // NPC_SetAnim( traceEnt, SETANIM_BOTH, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(traceEnt, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRABBED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - WP_SabersCheckLock2( self, traceEnt, LOCK_FORCE_DRAIN ); + WP_SabersCheckLock2(self, traceEnt, LOCK_FORCE_DRAIN); return qtrue; } -void ForceDrain( gentity_t *self, qboolean triedDrain2 ) -{ - if ( self->health <= 0 ) - { +void ForceDrain(gentity_t *self, qboolean triedDrain2) { + if (self->health <= 0) { return; } - if ( !triedDrain2 && self->client->ps.weaponTime > 0 ) - { + if (!triedDrain2 && self->client->ps.weaponTime > 0) { return; } - if ( self->client->ps.forcePower < 25 || !WP_ForcePowerUsable( self, FP_DRAIN, 0 ) ) - { + if (self->client->ps.forcePower < 25 || !WP_ForcePowerUsable(self, FP_DRAIN, 0)) { return; } - if ( self->client->ps.forcePowerDebounce[FP_DRAIN] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.forcePowerDebounce[FP_DRAIN] > level.time) { // stops it while using it and also after using it, up to 3 second delay return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } // Make sure to turn off Force Protection and Force Absorb. - if ( self->client->ps.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); } - if ( self->client->ps.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); } - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/drain.mp3" ); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/drain.mp3"); - WP_ForcePowerStart( self, FP_DRAIN, 0 ); + WP_ForcePowerStart(self, FP_DRAIN, 0); } - -qboolean FP_ForceDrainableEnt( gentity_t *victim ) -{ - if ( !victim || !victim->client ) - { +qboolean FP_ForceDrainableEnt(gentity_t *victim) { + if (!victim || !victim->client) { return qfalse; } - switch ( victim->client->NPC_class ) - { - case CLASS_SAND_CREATURE://?? - case CLASS_ATST: // technically droid... - case CLASS_GONK: // droid - case CLASS_INTERROGATOR: // droid - case CLASS_MARK1: // droid - case CLASS_MARK2: // droid - case CLASS_GALAKMECH: // droid + switch (victim->client->NPC_class) { + case CLASS_SAND_CREATURE: //?? + case CLASS_ATST: // technically droid... + case CLASS_GONK: // droid + case CLASS_INTERROGATOR: // droid + case CLASS_MARK1: // droid + case CLASS_MARK2: // droid + case CLASS_GALAKMECH: // droid case CLASS_MINEMONSTER: - case CLASS_MOUSE: // droid - case CLASS_PROBE: // droid - case CLASS_PROTOCOL: // droid - case CLASS_R2D2: // droid - case CLASS_R5D2: // droid + case CLASS_MOUSE: // droid + case CLASS_PROBE: // droid + case CLASS_PROTOCOL: // droid + case CLASS_R2D2: // droid + case CLASS_R5D2: // droid case CLASS_REMOTE: - case CLASS_SEEKER: // droid + case CLASS_SEEKER: // droid case CLASS_SENTRY: case CLASS_SABER_DROID: case CLASS_ASSASSIN_DROID: @@ -11628,18 +9173,14 @@ qboolean FP_ForceDrainableEnt( gentity_t *victim ) return qtrue; } -qboolean FP_ForceDrainGrippableEnt( gentity_t *victim ) -{ - if ( !victim || !victim->client ) - { +qboolean FP_ForceDrainGrippableEnt(gentity_t *victim) { + if (!victim || !victim->client) { return qfalse; } - if ( !FP_ForceDrainableEnt( victim ) ) - { + if (!FP_ForceDrainableEnt(victim)) { return qfalse; } - switch ( victim->client->NPC_class ) - { + switch (victim->client->NPC_class) { case CLASS_RANCOR: case CLASS_SAND_CREATURE: case CLASS_WAMPA: @@ -11656,63 +9197,44 @@ qboolean FP_ForceDrainGrippableEnt( gentity_t *victim ) return qtrue; } -void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint ) -{ - if ( traceEnt - && traceEnt->health > 0 - && traceEnt->takedamage - && FP_ForceDrainableEnt( traceEnt ) ) - { - if ( traceEnt->client - && (!OnSameTeam(self, traceEnt)||self->enemy==traceEnt)//don't drain an ally unless that is actually my current enemy - && self->client->ps.forceDrainTime < level.time ) - {//an enemy or object +void ForceDrainDamage(gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint) { + if (traceEnt && traceEnt->health > 0 && traceEnt->takedamage && FP_ForceDrainableEnt(traceEnt)) { + if (traceEnt->client && (!OnSameTeam(self, traceEnt) || self->enemy == traceEnt) // don't drain an ally unless that is actually my current enemy + && self->client->ps.forceDrainTime < level.time) { // an enemy or object int modPowerLevel = -1; - int dmg = self->client->ps.forcePowerLevel[FP_DRAIN] + 1; - int dflags = (DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC);//|DAMAGE_NO_KILL); - if ( traceEnt->s.number == self->client->ps.forceDrainEntityNum ) - {//grabbing hold of them does more damage/drains more, and can actually kill them + int dmg = self->client->ps.forcePowerLevel[FP_DRAIN] + 1; + int dflags = (DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC); //|DAMAGE_NO_KILL); + if (traceEnt->s.number == self->client->ps.forceDrainEntityNum) { // grabbing hold of them does more damage/drains more, and can actually kill them dmg += 3; dflags |= DAMAGE_IGNORE_TEAM; - //dflags &= ~DAMAGE_NO_KILL; + // dflags &= ~DAMAGE_NO_KILL; } - if (traceEnt->client) - { - //check for client using FP_ABSORB - modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.forcePowerLevel[FP_DRAIN], 0); - //Since this is drain, don't absorb any power, but nullify the affect it has + if (traceEnt->client) { + // check for client using FP_ABSORB + modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, + self->client->ps.forcePowerLevel[FP_DRAIN], 0); + // Since this is drain, don't absorb any power, but nullify the affect it has } - if ( modPowerLevel != -1 ) - { - if ( !modPowerLevel ) - { + if (modPowerLevel != -1) { + if (!modPowerLevel) { dmg = 0; - } - else if ( modPowerLevel == 1 ) - { + } else if (modPowerLevel == 1) { dmg = 1; - } - else if ( modPowerLevel == 2 ) - { + } else if (modPowerLevel == 2) { dmg = 2; } } - if ( dmg ) - { - int drain = 0; - if ( traceEnt->client->ps.forcePower ) - { - if ( dmg > traceEnt->client->ps.forcePower ) - { + if (dmg) { + int drain = 0; + if (traceEnt->client->ps.forcePower) { + if (dmg > traceEnt->client->ps.forcePower) { drain = traceEnt->client->ps.forcePower; dmg -= drain; traceEnt->client->ps.forcePower = 0; - } - else - { + } else { drain = dmg; traceEnt->client->ps.forcePower -= (dmg); dmg = 0; @@ -11734,37 +9256,29 @@ void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t */ int maxHealth = self->client->ps.stats[STAT_MAX_HEALTH]; - if ( self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//overcharge health - maxHealth = floor( (float)self->client->ps.stats[STAT_MAX_HEALTH] * 1.25f ); + if (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // overcharge health + maxHealth = floor((float)self->client->ps.stats[STAT_MAX_HEALTH] * 1.25f); } - if (self->client->ps.stats[STAT_HEALTH] < maxHealth && - self->health > 0 && self->client->ps.stats[STAT_HEALTH] > 0) - { - self->health += (drain+dmg); - if (self->health > maxHealth ) - { + if (self->client->ps.stats[STAT_HEALTH] < maxHealth && self->health > 0 && self->client->ps.stats[STAT_HEALTH] > 0) { + self->health += (drain + dmg); + if (self->health > maxHealth) { self->health = maxHealth; } self->client->ps.stats[STAT_HEALTH] = self->health; - if ( self->health > self->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { self->flags |= FL_OVERCHARGED_HEALTH; } } - if ( dmg ) - {//do damage, too - G_Damage( traceEnt, self, self, dir, impactPoint, dmg, dflags, MOD_FORCE_DRAIN ); - } - else if ( drain ) - { + if (dmg) { // do damage, too + G_Damage(traceEnt, self, self, dir, impactPoint, dmg, dflags, MOD_FORCE_DRAIN); + } else if (drain) { /* if ( traceEnt->s.number == self->client->ps.forceDrainEntityNum || traceEnt->s.number < MAX_CLIENTS ) {//grip-draining (or player - only does sound) */ - NPC_SetPainEvent( traceEnt ); + NPC_SetPainEvent(traceEnt); /* } else @@ -11774,423 +9288,345 @@ void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t */ } - if ( !Q_irand( 0, 2 ) ) - { - G_Sound( traceEnt, G_SoundIndex( "sound/weapons/force/drained.mp3" ) ); + if (!Q_irand(0, 2)) { + G_Sound(traceEnt, G_SoundIndex("sound/weapons/force/drained.mp3")); } - traceEnt->client->ps.forcePowerRegenDebounceTime = level.time + 800; //don't let the client being drained get force power back right away + traceEnt->client->ps.forcePowerRegenDebounceTime = level.time + 800; // don't let the client being drained get force power back right away } } } } -qboolean WP_CheckForceDraineeStopMe( gentity_t *self, gentity_t *drainee ) -{ - if ( drainee->NPC - && drainee->client - && (drainee->client->ps.forcePowersKnown&(1<client->ps.forcePowerDebounce[FP_DRAIN]>self->client->ps.forcePowerLevel[FP_DRAIN]*500)//at level 1, I always get at least 500ms of drain, at level 3 I get 1500ms - && !Q_irand( 0, 100-(drainee->NPC->stats.evasion*10)-(g_spskill->integer*12) ) ) - {//a jedi who broke free - ForceThrow( drainee, qfalse ); - //FIXME: I need to go into some pushed back anim... - WP_ForcePowerStop( self, FP_DRAIN ); - //can't drain again for 2 seconds +qboolean WP_CheckForceDraineeStopMe(gentity_t *self, gentity_t *drainee) { + if (drainee->NPC && drainee->client && (drainee->client->ps.forcePowersKnown & (1 << FP_PUSH)) && + level.time - (self->client->ps.forcePowerDebounce[FP_DRAIN] > + self->client->ps.forcePowerLevel[FP_DRAIN] * 500) // at level 1, I always get at least 500ms of drain, at level 3 I get 1500ms + && !Q_irand(0, 100 - (drainee->NPC->stats.evasion * 10) - (g_spskill->integer * 12))) { // a jedi who broke free + ForceThrow(drainee, qfalse); + // FIXME: I need to go into some pushed back anim... + WP_ForcePowerStop(self, FP_DRAIN); + // can't drain again for 2 seconds self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 4000; return qtrue; } return qfalse; } -void ForceShootDrain( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; - int numDrained = 0; +void ForceShootDrain(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; + int numDrained = 0; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( self->client->ps.forcePowerDebounce[FP_DRAIN] <= level.time ) - { - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - - if ( self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//arc - vec3_t center, mins, maxs, dir, ent_org, size, v; - float radius = MAX_DRAIN_DISTANCE, dot, dist; - gentity_t *entityList[MAX_GENTITIES]; - int e, numListedEntities, i; - - VectorCopy( self->client->ps.origin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + if (self->client->ps.forcePowerDebounce[FP_DRAIN] <= level.time) { + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + + if (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // arc + vec3_t center, mins, maxs, dir, ent_org, size, v; + float radius = MAX_DRAIN_DISTANCE, dot, dist; + gentity_t *entityList[MAX_GENTITIES]; + int e, numListedEntities, i; + + VectorCopy(self->client->ps.origin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { traceEnt = entityList[e]; - if ( !traceEnt ) + if (!traceEnt) continue; - if ( traceEnt == self ) + if (traceEnt == self) continue; - if ( !traceEnt->inuse ) + if (!traceEnt->inuse) continue; - if ( !traceEnt->takedamage ) + if (!traceEnt->takedamage) continue; - if ( traceEnt->health <= 0 )//no torturing corpses + if (traceEnt->health <= 0) // no torturing corpses continue; - if ( !traceEnt->client ) + if (!traceEnt->client) continue; /* if ( !traceEnt->client->ps.forcePower ) continue; */ - // if (traceEnt->client->ps.forceSide == FORCE_DARKSIDE) // We no longer care if the victim is dark or light - // continue; - if (self->enemy != traceEnt//not my enemy - && OnSameTeam(self, traceEnt))//on my team + // if (traceEnt->client->ps.forceSide == FORCE_DARKSIDE) // We no longer care if the victim is dark or light + // continue; + if (self->enemy != traceEnt // not my enemy + && OnSameTeam(self, traceEnt)) // on my team continue; - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < traceEnt->absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < traceEnt->absmin[i]) { v[i] = traceEnt->absmin[i] - center[i]; - } else if ( center[i] > traceEnt->absmax[i] ) - { + } else if (center[i] > traceEnt->absmax[i]) { v[i] = center[i] - traceEnt->absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( traceEnt->absmax, traceEnt->absmin, size ); - VectorMA( traceEnt->absmin, 0.5, size, ent_org ); + VectorSubtract(traceEnt->absmax, traceEnt->absmin, size); + VectorMA(traceEnt->absmin, 0.5, size, ent_org); - //see if they're in front of me - //must be within the forward cone - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot = DotProduct( dir, forward )) < 0.5 ) + // see if they're in front of me + // must be within the forward cone + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot = DotProduct(dir, forward)) < 0.5) continue; - //must be close enough - dist = VectorLength( v ); - if ( dist >= radius ) - { + // must be close enough + dist = VectorLength(v); + if (dist >= radius) { continue; } - //in PVS? - if ( !traceEnt->bmodel && !gi.inPVS( ent_org, self->client->renderInfo.handLPoint ) ) - {//must be in PVS + // in PVS? + if (!traceEnt->bmodel && !gi.inPVS(ent_org, self->client->renderInfo.handLPoint)) { // must be in PVS continue; } - //Now check and see if we can actually hit it - gi.trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number ) - {//must have clear LOS + // Now check and see if we can actually hit it + gi.trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, G2_RETURNONHIT, 10); + if (tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number) { // must have clear LOS continue; } - if ( traceEnt - && traceEnt->s.number >= MAX_CLIENTS - && traceEnt->client - && traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 )//&& traceEnt->NPC + if (traceEnt && traceEnt->s.number >= MAX_CLIENTS && traceEnt->client && + traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) //&& traceEnt->NPC { - if ( !Q_irand( 0, 4 ) && !Jedi_DodgeEvasion( traceEnt, self, &tr, HL_NONE ) ) - {//act like we didn't even hit him + if (!Q_irand(0, 4) && !Jedi_DodgeEvasion(traceEnt, self, &tr, HL_NONE)) { // act like we didn't even hit him continue; } } // ok, we are within the radius, add us to the incoming list - if ( WP_CheckForceDraineeStopMe( self, traceEnt ) ) - { + if (WP_CheckForceDraineeStopMe(self, traceEnt)) { continue; } - ForceDrainDamage( self, traceEnt, dir, ent_org ); + ForceDrainDamage(self, traceEnt, dir, ent_org); numDrained++; } - } - else - {//trace-line + } else { // trace-line int ignore = self->s.number; int traces = 0; - vec3_t start; + vec3_t start; - VectorCopy( self->client->renderInfo.handLPoint, start ); - VectorMA( start, MAX_DRAIN_DISTANCE, forward, end ); + VectorCopy(self->client->renderInfo.handLPoint, start); + VectorMA(start, MAX_DRAIN_DISTANCE, forward, end); - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 10 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { - //always take 1 force point per frame that we're shooting this - WP_ForcePowerDrain( self, FP_DRAIN, 1 ); + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 10); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { + // always take 1 force point per frame that we're shooting this + WP_ForcePowerDrain(self, FP_DRAIN, 1); return; } traceEnt = &g_entities[tr.entityNum]; - //NOTE: only NPCs do this auto-dodge - if ( traceEnt - && traceEnt->s.number >= MAX_CLIENTS - && traceEnt->client - && traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 )//&& traceEnt->NPC + // NOTE: only NPCs do this auto-dodge + if (traceEnt && traceEnt->s.number >= MAX_CLIENTS && traceEnt->client && + traceEnt->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) //&& traceEnt->NPC { - if ( !Q_irand( 0, 2 ) && !Jedi_DodgeEvasion( traceEnt, self, &tr, HL_NONE ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + if (!Q_irand(0, 2) && !Jedi_DodgeEvasion(traceEnt, self, &tr, HL_NONE)) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } traceEnt = &g_entities[tr.entityNum]; - if ( !WP_CheckForceDraineeStopMe( self, traceEnt ) ) - { - ForceDrainDamage( self, traceEnt, forward, tr.endpos ); + if (!WP_CheckForceDraineeStopMe(self, traceEnt)) { + ForceDrainDamage(self, traceEnt, forward, tr.endpos); } numDrained = 1; } - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 200;//so we don't drain so damn fast! + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 200; // so we don't drain so damn fast! } self->client->ps.forcePowerRegenDebounceTime = level.time + 500; - if ( !numDrained ) - {//always take 1 force point per frame that we're shooting this - WP_ForcePowerDrain( self, FP_DRAIN, 1 ); - } - else - { - WP_ForcePowerDrain( self, FP_DRAIN, numDrained );//was 2, but... + if (!numDrained) { // always take 1 force point per frame that we're shooting this + WP_ForcePowerDrain(self, FP_DRAIN, 1); + } else { + WP_ForcePowerDrain(self, FP_DRAIN, numDrained); // was 2, but... } return; } -void ForceDrainEnt( gentity_t *self, gentity_t *drainEnt ) -{ - if ( self->health <= 0 ) - { +void ForceDrainEnt(gentity_t *self, gentity_t *drainEnt) { + if (self->health <= 0) { return; } - if ( self->client->ps.forcePowerDebounce[FP_DRAIN] <= level.time ) - { - if ( !drainEnt ) + if (self->client->ps.forcePowerDebounce[FP_DRAIN] <= level.time) { + if (!drainEnt) return; - if ( drainEnt == self ) + if (drainEnt == self) return; - if ( !drainEnt->inuse ) + if (!drainEnt->inuse) return; - if ( !drainEnt->takedamage ) + if (!drainEnt->takedamage) return; - if ( drainEnt->health <= 0 )//no torturing corpses + if (drainEnt->health <= 0) // no torturing corpses return; - if ( !drainEnt->client ) + if (!drainEnt->client) return; if (OnSameTeam(self, drainEnt)) return; vec3_t fwd; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); drainEnt->painDebounceTime = 0; - ForceDrainDamage( self, drainEnt, fwd, drainEnt->currentOrigin ); + ForceDrainDamage(self, drainEnt, fwd, drainEnt->currentOrigin); drainEnt->painDebounceTime = level.time + 2000; - if ( drainEnt->s.number ) - { - if ( self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//do damage faster at level 3 - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand( 100, 500 ); - } - else - { - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand( 200, 800 ); + if (drainEnt->s.number) { + if (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // do damage faster at level 3 + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand(100, 500); + } else { + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand(200, 800); } - } - else - {//player takes damage faster - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand( 100, 500 ); + } else { // player takes damage faster + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + Q_irand(100, 500); } } self->client->ps.forcePowerRegenDebounceTime = level.time + 500; } -void ForceSeeing( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceSeeing(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.forcePowersActive & (1 << FP_SEE)) ) - { - WP_ForcePowerStop( self, FP_SEE ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.forcePowersActive & (1 << FP_SEE))) { + WP_ForcePowerStop(self, FP_SEE); return; } - if ( !WP_ForcePowerUsable( self, FP_SEE, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_SEE, 0)) { return; } - WP_DebounceForceDeactivateTime( self ); + WP_DebounceForceDeactivateTime(self); - WP_ForcePowerStart( self, FP_SEE, 0 ); + WP_ForcePowerStart(self, FP_SEE, 0); - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/see.wav" ); + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/see.wav"); } -void ForceProtect( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceProtect(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.forcePowersActive & (1 << FP_PROTECT))) { + WP_ForcePowerStop(self, FP_PROTECT); return; } - if ( !WP_ForcePowerUsable( self, FP_PROTECT, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_PROTECT, 0)) { return; } // Make sure to turn off Force Rage and Force Absorb. - if (self->client->ps.forcePowersActive & (1 << FP_RAGE) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.forcePowersActive & (1 << FP_RAGE)) { + WP_ForcePowerStop(self, FP_RAGE); } - WP_DebounceForceDeactivateTime( self ); + WP_DebounceForceDeactivateTime(self); - WP_ForcePowerStart( self, FP_PROTECT, 0 ); + WP_ForcePowerStart(self, FP_PROTECT, 0); - if ( self->client->ps.saberLockTime < level.time ) - { - if ( self->client->ps.forcePowerLevel[FP_PROTECT] < FORCE_LEVEL_3 ) - {//animate + if (self->client->ps.saberLockTime < level.time) { + if (self->client->ps.forcePowerLevel[FP_PROTECT] < FORCE_LEVEL_3) { // animate int parts = SETANIM_BOTH; int anim = BOTH_FORCE_PROTECT; - if ( self->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1 ) - {//level 2 only does it on torso (can keep running) + if (self->client->ps.forcePowerLevel[FP_PROTECT] > FORCE_LEVEL_1) { // level 2 only does it on torso (can keep running) parts = SETANIM_TORSO; anim = BOTH_FORCE_PROTECT_FAST; - } - else - { - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - VectorClear( self->client->ps.velocity ); + } else { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + VectorClear(self->client->ps.velocity); } - if ( self->NPC ) - { - VectorClear( self->client->ps.moveDir ); + if (self->NPC) { + VectorClear(self->client->ps.moveDir); self->client->ps.speed = 0; } - //FIXME: what if in air? + // FIXME: what if in air? } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't move or attack during this anim - if ( self->client->ps.forcePowerLevel[FP_PROTECT] < FORCE_LEVEL_2 ) - { + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't move or attack during this anim + if (self->client->ps.forcePowerLevel[FP_PROTECT] < FORCE_LEVEL_2) { self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; self->client->ps.pm_time = self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - if ( self->s.number ) - {//NPC + if (self->s.number) { // NPC self->painDebounceTime = level.time + self->client->ps.torsoAnimTimer; - } - else - {//player + } else { // player self->aimDebounceTime = level.time + self->client->ps.torsoAnimTimer; } - } - else - { + } else { self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; } } } } -void ForceAbsorb( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceAbsorb(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.forcePowersActive & (1 << FP_ABSORB))) { + WP_ForcePowerStop(self, FP_ABSORB); return; } - if ( !WP_ForcePowerUsable( self, FP_ABSORB, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_ABSORB, 0)) { return; } // Make sure to turn off Force Rage and Force Protection. - if (self->client->ps.forcePowersActive & (1 << FP_RAGE) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.forcePowersActive & (1 << FP_RAGE)) { + WP_ForcePowerStop(self, FP_RAGE); } - WP_DebounceForceDeactivateTime( self ); + WP_DebounceForceDeactivateTime(self); - WP_ForcePowerStart( self, FP_ABSORB, 0 ); + WP_ForcePowerStart(self, FP_ABSORB, 0); - if ( self->client->ps.saberLockTime < level.time ) - { - if ( self->client->ps.forcePowerLevel[FP_ABSORB] < FORCE_LEVEL_3 ) - {//must animate + if (self->client->ps.saberLockTime < level.time) { + if (self->client->ps.forcePowerLevel[FP_ABSORB] < FORCE_LEVEL_3) { // must animate int parts = SETANIM_BOTH; - if ( self->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1 ) - {//level 2 only does it on torso (can keep running) + if (self->client->ps.forcePowerLevel[FP_ABSORB] > FORCE_LEVEL_1) { // level 2 only does it on torso (can keep running) parts = SETANIM_TORSO; - } - else - { - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - VectorClear( self->client->ps.velocity ); + } else { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + VectorClear(self->client->ps.velocity); } - if ( self->NPC ) - { - VectorClear( self->client->ps.moveDir ); + if (self->NPC) { + VectorClear(self->client->ps.moveDir); self->client->ps.speed = 0; } - //FIXME: what if in air? + // FIXME: what if in air? } /* //if in air, only do on torso - NOTE: or moving? @@ -12199,338 +9635,242 @@ void ForceAbsorb( gentity_t *self ) parts = SETANIM_TORSO; } */ - NPC_SetAnim( self, parts, BOTH_FORCE_ABSORB, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, parts, BOTH_FORCE_ABSORB, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - if ( parts == SETANIM_BOTH ) - {//can't move + if (parts == SETANIM_BOTH) { // can't move self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - self->client->ps.pm_time = self->client->ps.legsAnimTimer = self->client->ps.torsoAnimTimer;// = self->client->ps.forcePowerDuration[FP_ABSORB]; - if ( self->s.number ) - {//NPC - self->painDebounceTime = level.time + self->client->ps.pm_time;//self->client->ps.forcePowerDuration[FP_ABSORB]; - } - else - {//player - self->aimDebounceTime = level.time + self->client->ps.pm_time;//self->client->ps.forcePowerDuration[FP_ABSORB]; + self->client->ps.pm_time = self->client->ps.legsAnimTimer = + self->client->ps.torsoAnimTimer; // = self->client->ps.forcePowerDuration[FP_ABSORB]; + if (self->s.number) { // NPC + self->painDebounceTime = level.time + self->client->ps.pm_time; // self->client->ps.forcePowerDuration[FP_ABSORB]; + } else { // player + self->aimDebounceTime = level.time + self->client->ps.pm_time; // self->client->ps.forcePowerDuration[FP_ABSORB]; } } - //stop saber - //WP_DeactivateSaber( self );//turn off saber when meditating - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // stop saber + // WP_DeactivateSaber( self );//turn off saber when meditating + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; } } } -void ForceRage( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceRage(gentity_t *self) { + if (self->health <= 0) { return; } - //FIXME: prevent them from using any other force powers when raging? + // FIXME: prevent them from using any other force powers when raging? - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.forcePowersActive & (1 << FP_RAGE)) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.forcePowersActive & (1 << FP_RAGE))) { + WP_ForcePowerStop(self, FP_RAGE); return; } - if ( !WP_ForcePowerUsable( self, FP_RAGE, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_RAGE, 0)) { return; } - if (self->client->ps.forceRageRecoveryTime >= level.time) - { + if (self->client->ps.forceRageRecoveryTime >= level.time) { return; } - if ( self->s.number < MAX_CLIENTS - && self->health < 25 ) - {//have to have at least 25 health to start it + if (self->s.number < MAX_CLIENTS && self->health < 25) { // have to have at least 25 health to start it return; } - if (self->health < 10) - { + if (self->health < 10) { return; } // Make sure to turn off Force Protection and Force Absorb. - if (self->client->ps.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); } - if (self->client->ps.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); } - WP_DebounceForceDeactivateTime( self ); + WP_DebounceForceDeactivateTime(self); - WP_ForcePowerStart( self, FP_RAGE, 0 ); + WP_ForcePowerStart(self, FP_RAGE, 0); - if ( self->client->ps.saberLockTime < level.time ) - { - if ( self->client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_3 ) - {//must animate - if ( self->client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_2 ) - {//have to stand still for whole length of anim - //FIXME: if in air, only do on torso? - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't attack during this anim + if (self->client->ps.saberLockTime < level.time) { + if (self->client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_3) { // must animate + if (self->client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_2) { // have to stand still for whole length of anim + // FIXME: if in air, only do on torso? + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't attack during this anim self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; self->client->ps.pm_time = self->client->ps.torsoAnimTimer; - if ( self->s.number ) - {//NPC + if (self->s.number) { // NPC self->painDebounceTime = level.time + self->client->ps.torsoAnimTimer; - } - else - {//player + } else { // player self->aimDebounceTime = level.time + self->client->ps.torsoAnimTimer; } - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_RAGE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't attack during this anim + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_RAGE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't attack during this anim self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; } - //stop saber - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // stop saber + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; } } } -void ForceJumpCharge( gentity_t *self, usercmd_t *ucmd ) -{ - float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME/FRAMETIME); +void ForceJumpCharge(gentity_t *self, usercmd_t *ucmd) { + float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && cg.zoomMode ) - {//can't force jump when zoomed in + if (!self->s.number && cg.zoomMode) { // can't force jump when zoomed in return; } - //need to play sound - if ( !self->client->ps.forceJumpCharge ) - {//FIXME: this should last only as long as the actual charge-up - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jumpbuild.wav" ); + // need to play sound + if (!self->client->ps.forceJumpCharge) { // FIXME: this should last only as long as the actual charge-up + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jumpbuild.wav"); } - //Increment + // Increment self->client->ps.forceJumpCharge += forceJumpChargeInterval; - //clamp to max strength for current level - if ( self->client->ps.forceJumpCharge > forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]] ) - { + // clamp to max strength for current level + if (self->client->ps.forceJumpCharge > forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]) { self->client->ps.forceJumpCharge = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]; } - //clamp to max available force power - if ( self->client->ps.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[FP_LEVITATION] > self->client->ps.forcePower ) - {//can't use more than you have - self->client->ps.forceJumpCharge = self->client->ps.forcePower*forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + // clamp to max available force power + if (self->client->ps.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * forcePowerNeeded[FP_LEVITATION] > + self->client->ps.forcePower) { // can't use more than you have + self->client->ps.forceJumpCharge = self->client->ps.forcePower * forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); } - //FIXME: a simple tap should always do at least a normal height's jump? + // FIXME: a simple tap should always do at least a normal height's jump? } -int WP_GetVelocityForForceJump( gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd ) -{ +int WP_GetVelocityForForceJump(gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd) { float pushFwd = 0, pushRt = 0; - vec3_t view, forward, right; - VectorCopy( self->client->ps.viewangles, view ); + vec3_t view, forward, right; + VectorCopy(self->client->ps.viewangles, view); view[0] = 0; - AngleVectors( view, forward, right, NULL ); - if ( ucmd->forwardmove && ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + AngleVectors(view, forward, right, NULL); + if (ucmd->forwardmove && ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 50; - } - else - { + } else { pushFwd = -50; } - if ( ucmd->rightmove > 0 ) - { + if (ucmd->rightmove > 0) { pushRt = 50; - } - else - { + } else { pushRt = -50; } - } - else if ( ucmd->forwardmove || ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + } else if (ucmd->forwardmove || ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 100; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { pushFwd = -100; - } - else if ( ucmd->rightmove > 0 ) - { + } else if (ucmd->rightmove > 0) { pushRt = 100; - } - else if ( ucmd->rightmove < 0 ) - { + } else if (ucmd->rightmove < 0) { pushRt = -100; } } - VectorMA( self->client->ps.velocity, pushFwd, forward, jumpVel ); - VectorMA( self->client->ps.velocity, pushRt, right, jumpVel ); - jumpVel[2] += self->client->ps.forceJumpCharge;//forceJumpStrength; - if ( pushFwd > 0 && self->client->ps.forceJumpCharge > 200 ) - { + VectorMA(self->client->ps.velocity, pushFwd, forward, jumpVel); + VectorMA(self->client->ps.velocity, pushRt, right, jumpVel); + jumpVel[2] += self->client->ps.forceJumpCharge; // forceJumpStrength; + if (pushFwd > 0 && self->client->ps.forceJumpCharge > 200) { return FJ_FORWARD; - } - else if ( pushFwd < 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushFwd < 0 && self->client->ps.forceJumpCharge > 200) { return FJ_BACKWARD; - } - else if ( pushRt > 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushRt > 0 && self->client->ps.forceJumpCharge > 200) { return FJ_RIGHT; - } - else if ( pushRt < 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushRt < 0 && self->client->ps.forceJumpCharge > 200) { return FJ_LEFT; - } - else - {//FIXME: jump straight up anim + } else { // FIXME: jump straight up anim return FJ_UP; } } -void ForceJump( gentity_t *self, usercmd_t *ucmd ) -{ - if ( self->client->ps.forcePowerDuration[FP_LEVITATION] > level.time ) - { +void ForceJump(gentity_t *self, usercmd_t *ucmd) { + if (self->client->ps.forcePowerDuration[FP_LEVITATION] > level.time) { return; } - if ( !WP_ForcePowerUsable( self, FP_LEVITATION, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_LEVITATION, 0)) { return; } - if ( self->s.groundEntityNum == ENTITYNUM_NONE ) - { + if (self->s.groundEntityNum == ENTITYNUM_NONE) { return; } - if ( self->client->ps.pm_flags&PMF_JUMP_HELD ) - { + if (self->client->ps.pm_flags & PMF_JUMP_HELD) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force jump when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force jump when zoomed in or in cinematic return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - if ( self->client->NPC_class == CLASS_BOBAFETT - || self->client->NPC_class == CLASS_ROCKETTROOPER ) - { - if ( self->client->ps.forceJumpCharge > 300 ) - { + if (self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) { + if (self->client->ps.forceJumpCharge > 300) { JET_FlyStart(NPC); + } else { + G_AddEvent(self, EV_JUMP, 0); } - else - { - G_AddEvent( self, EV_JUMP, 0 ); - } - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } - float forceJumpChargeInterval = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + float forceJumpChargeInterval = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); int anim; - vec3_t jumpVel; + vec3_t jumpVel; - switch( WP_GetVelocityForForceJump( self, jumpVel, ucmd ) ) - { + switch (WP_GetVelocityForForceJump(self, jumpVel, ucmd)) { case FJ_FORWARD: - if ( ((self->client->NPC_class == CLASS_BOBAFETT||self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300 ) - || (self->client->ps.saber[0].saberFlags&SFL_NO_FLIPS) - || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags&SFL_NO_FLIPS) ) - || ( self->NPC && - self->NPC->rank != RANK_CREWMAN && - self->NPC->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + if (((self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300) || + (self->client->ps.saber[0].saberFlags & SFL_NO_FLIPS) || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_FLIPS)) || + (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG)) { // can't do acrobatics anim = BOTH_FORCEJUMP1; - } - else - { - if ( self->client->NPC_class == CLASS_ALORA && Q_irand( 0, 3 ) ) - { - anim = Q_irand( BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3 ); - } - else - { + } else { + if (self->client->NPC_class == CLASS_ALORA && Q_irand(0, 3)) { + anim = Q_irand(BOTH_ALORA_FLIP_1, BOTH_ALORA_FLIP_3); + } else { anim = BOTH_FLIP_F; } } break; case FJ_BACKWARD: - if ( ((self->client->NPC_class == CLASS_BOBAFETT||self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300 ) - || (self->client->ps.saber[0].saberFlags&SFL_NO_FLIPS) - || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags&SFL_NO_FLIPS) ) - || ( self->NPC && - self->NPC->rank != RANK_CREWMAN && - self->NPC->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + if (((self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300) || + (self->client->ps.saber[0].saberFlags & SFL_NO_FLIPS) || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_FLIPS)) || + (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG)) { // can't do acrobatics anim = BOTH_FORCEJUMPBACK1; - } - else - { + } else { anim = BOTH_FLIP_B; } break; case FJ_RIGHT: - if ( ((self->client->NPC_class == CLASS_BOBAFETT||self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300 ) - || (self->client->ps.saber[0].saberFlags&SFL_NO_FLIPS) - || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags&SFL_NO_FLIPS) ) - || ( self->NPC && - self->NPC->rank != RANK_CREWMAN && - self->NPC->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + if (((self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300) || + (self->client->ps.saber[0].saberFlags & SFL_NO_FLIPS) || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_FLIPS)) || + (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG)) { // can't do acrobatics anim = BOTH_FORCEJUMPRIGHT1; - } - else - { + } else { anim = BOTH_FLIP_R; } break; case FJ_LEFT: - if ( ((self->client->NPC_class == CLASS_BOBAFETT||self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300 ) - || (self->client->ps.saber[0].saberFlags&SFL_NO_FLIPS) - || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags&SFL_NO_FLIPS) ) - || ( self->NPC && - self->NPC->rank != RANK_CREWMAN && - self->NPC->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + if (((self->client->NPC_class == CLASS_BOBAFETT || self->client->NPC_class == CLASS_ROCKETTROOPER) && self->client->ps.forceJumpCharge > 300) || + (self->client->ps.saber[0].saberFlags & SFL_NO_FLIPS) || (self->client->ps.dualSabers && (self->client->ps.saber[1].saberFlags & SFL_NO_FLIPS)) || + (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG)) { // can't do acrobatics anim = BOTH_FORCEJUMPLEFT1; - } - else - { + } else { anim = BOTH_FLIP_L; } break; @@ -12540,200 +9880,173 @@ void ForceJump( gentity_t *self, usercmd_t *ucmd ) break; } - int parts = SETANIM_BOTH; - if ( self->client->ps.weaponTime ) - {//FIXME: really only care if we're in a saber attack anim.. maybe trail length? + int parts = SETANIM_BOTH; + if (self->client->ps.weaponTime) { // FIXME: really only care if we're in a saber attack anim.. maybe trail length? parts = SETANIM_LEGS; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - //FIXME: sound effect - self->client->ps.forceJumpZStart = self->currentOrigin[2];//remember this for when we land - VectorCopy( jumpVel, self->client->ps.velocity ); - //wasn't allowing them to attack when jumping, but that was annoying - //self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; + // FIXME: sound effect + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // remember this for when we land + VectorCopy(jumpVel, self->client->ps.velocity); + // wasn't allowing them to attack when jumping, but that was annoying + // self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - WP_ForcePowerStart( self, FP_LEVITATION, self->client->ps.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[FP_LEVITATION] ); - //self->client->ps.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; + WP_ForcePowerStart(self, FP_LEVITATION, + self->client->ps.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * forcePowerNeeded[FP_LEVITATION]); + // self->client->ps.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; self->client->ps.forceJumpCharge = 0; } -int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacker, int atPower, int atPowerLevel, int atForceSpent) -{ +int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacker, int atPower, int atPowerLevel, int atForceSpent) { int getLevel = 0; int addTot = 0; - if (atPower != FP_LIGHTNING && - atPower != FP_DRAIN && - atPower != FP_GRIP && - atPower != FP_PUSH && - atPower != FP_PULL) - { //Only these powers can be absorbed + if (atPower != FP_LIGHTNING && atPower != FP_DRAIN && atPower != FP_GRIP && atPower != FP_PUSH && atPower != FP_PULL) { // Only these powers can be absorbed return -1; } - if (!atdAbsLevel) - { //looks like attacker doesn't have any absorb power + if (!atdAbsLevel) { // looks like attacker doesn't have any absorb power return -1; } - if (!(attacked->client->ps.forcePowersActive & (1 << FP_ABSORB))) - { //absorb is not active + if (!(attacked->client->ps.forcePowersActive & (1 << FP_ABSORB))) { // absorb is not active return -1; } - //Subtract absorb power level from the offensive force power + // Subtract absorb power level from the offensive force power getLevel = atPowerLevel; getLevel -= atdAbsLevel; - if (getLevel < 0) - { + if (getLevel < 0) { getLevel = 0; } - //let the attacker absorb an amount of force used in this attack based on his level of absorb - addTot = (atForceSpent/3)*attacked->client->ps.forcePowerLevel[FP_ABSORB]; + // let the attacker absorb an amount of force used in this attack based on his level of absorb + addTot = (atForceSpent / 3) * attacked->client->ps.forcePowerLevel[FP_ABSORB]; - if (addTot < 1 && atForceSpent >= 1) - { + if (addTot < 1 && atForceSpent >= 1) { addTot = 1; } attacked->client->ps.forcePower += addTot; - if (attacked->client->ps.forcePower > attacked->client->ps.forcePowerMax) - { + if (attacked->client->ps.forcePower > attacked->client->ps.forcePowerMax) { attacked->client->ps.forcePower = attacked->client->ps.forcePowerMax; } - G_SoundOnEnt( attacked, CHAN_ITEM, "sound/weapons/force/absorbhit.wav" ); + G_SoundOnEnt(attacked, CHAN_ITEM, "sound/weapons/force/absorbhit.wav"); return getLevel; } -void WP_ForcePowerRegenerate( gentity_t *self, int overrideAmt ) -{ - if ( !self->client ) - { +void WP_ForcePowerRegenerate(gentity_t *self, int overrideAmt) { + if (!self->client) { return; } - if ( self->client->ps.forcePower < self->client->ps.forcePowerMax ) - { - if ( overrideAmt ) - { + if (self->client->ps.forcePower < self->client->ps.forcePowerMax) { + if (overrideAmt) { self->client->ps.forcePower += overrideAmt; - } - else - { + } else { self->client->ps.forcePower++; } - if ( self->client->ps.forcePower > self->client->ps.forcePowerMax ) - { + if (self->client->ps.forcePower > self->client->ps.forcePowerMax) { self->client->ps.forcePower = self->client->ps.forcePowerMax; } } } -void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - if ( self->NPC ) - {//For now, NPCs have infinite force power +void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + if (self->NPC) { // For now, NPCs have infinite force power return; } - //take away the power - int drain = overrideAmt; - if ( !drain ) - { + // take away the power + int drain = overrideAmt; + if (!drain) { drain = forcePowerNeeded[forcePower]; } - if ( !drain ) - { + if (!drain) { return; } self->client->ps.forcePower -= drain; - if ( self->client->ps.forcePower < 0 ) - { + if (self->client->ps.forcePower < 0) { self->client->ps.forcePower = 0; } } -void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - int duration = 0; +void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + int duration = 0; - //FIXME: debounce some of these? + // FIXME: debounce some of these? self->client->ps.forcePowerDebounce[forcePower] = 0; - //and it in - //set up duration time - switch( (int)forcePower ) - { + // and it in + // set up duration time + switch ((int)forcePower) { case FP_HEAL: - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); self->client->ps.forceHealCount = 0; - WP_StartForceHealEffects( self ); + WP_StartForceHealEffects(self); break; case FP_LEVITATION: - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; case FP_SPEED: - //duration is always 5 seconds, player time - duration = ceil(FORCE_SPEED_DURATION*forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]);//FIXME: because the timescale scales down (not instant), this doesn't end up being exactly right... - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/speedloop.wav" ); - if ( self->client->ps.forcePowerLevel[FP_SPEED] > FORCE_LEVEL_2 ) - {//HACK: just using this as a timestamp for when the power started, setting debounce to current time shouldn't adversely affect anything else + // duration is always 5 seconds, player time + duration = + ceil(FORCE_SPEED_DURATION * forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]); // FIXME: because the timescale scales down (not instant), + // this doesn't end up being exactly right... + self->client->ps.forcePowersActive |= (1 << forcePower); + self->s.loopSound = G_SoundIndex("sound/weapons/force/speedloop.wav"); + if (self->client->ps.forcePowerLevel[FP_SPEED] > FORCE_LEVEL_2) { // HACK: just using this as a timestamp for when the power started, setting debounce + // to current time shouldn't adversely affect anything else self->client->ps.forcePowerDebounce[FP_SPEED] = level.time; } break; case FP_PUSH: break; case FP_PULL: - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; case FP_TELEPATHY: break; case FP_GRIP: duration = 1000; - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - //HACK: just using this as a timestamp for when the power started, setting debounce to current time shouldn't adversely affect anything else - //self->client->ps.forcePowerDebounce[forcePower] = level.time; + self->client->ps.forcePowersActive |= (1 << forcePower); + // HACK: just using this as a timestamp for when the power started, setting debounce to current time shouldn't adversely affect anything else + // self->client->ps.forcePowerDebounce[forcePower] = level.time; break; case FP_LIGHTNING: duration = overrideAmt; overrideAmt = 0; - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; - //new Jedi Academy force powers + // new Jedi Academy force powers case FP_RAGE: - //duration is always 5 seconds, player time - duration = ceil(FORCE_RAGE_DURATION*forceSpeedValue[self->client->ps.forcePowerLevel[FP_RAGE]-1]);//FIXME: because the timescale scales down (not instant), this doesn't end up being exactly right... - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/rage.mp3" ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/rageloop.wav" ); - if ( self->chestBolt != -1 ) - { - G_PlayEffect( G_EffectIndex( "force/rage2" ), self->playerModel, self->chestBolt, self->s.number, self->currentOrigin, duration, qtrue ); + // duration is always 5 seconds, player time + duration = + ceil(FORCE_RAGE_DURATION * forceSpeedValue[self->client->ps.forcePowerLevel[FP_RAGE] - 1]); // FIXME: because the timescale scales down (not + // instant), this doesn't end up being exactly right... + self->client->ps.forcePowersActive |= (1 << forcePower); + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/rage.mp3"); + self->s.loopSound = G_SoundIndex("sound/weapons/force/rageloop.wav"); + if (self->chestBolt != -1) { + G_PlayEffect(G_EffectIndex("force/rage2"), self->playerModel, self->chestBolt, self->s.number, self->currentOrigin, duration, qtrue); } break; case FP_DRAIN: - if ( self->client->ps.forcePowerLevel[forcePower] > FORCE_LEVEL_1 - && self->client->ps.forceDrainEntityNum >= ENTITYNUM_WORLD ) - { + if (self->client->ps.forcePowerLevel[forcePower] > FORCE_LEVEL_1 && self->client->ps.forceDrainEntityNum >= ENTITYNUM_WORLD) { duration = overrideAmt; overrideAmt = 0; - //HACK: just using this as a timestamp for when the power started, setting debounce to current time shouldn't adversely affect anything else + // HACK: just using this as a timestamp for when the power started, setting debounce to current time shouldn't adversely affect anything else self->client->ps.forcePowerDebounce[forcePower] = level.time; - } - else - { + } else { duration = 1000; } - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; case FP_PROTECT: - switch ( self->client->ps.forcePowerLevel[FP_PROTECT] ) - { + switch (self->client->ps.forcePowerLevel[FP_PROTECT]) { case FORCE_LEVEL_3: duration = 20000; break; @@ -12746,123 +10059,98 @@ void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int override duration = 10000; break; } - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/protect.mp3" ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/protectloop.wav" ); + self->client->ps.forcePowersActive |= (1 << forcePower); + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/protect.mp3"); + self->s.loopSound = G_SoundIndex("sound/weapons/force/protectloop.wav"); break; case FP_ABSORB: duration = 20000; - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/absorb.mp3" ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/absorbloop.wav" ); + self->client->ps.forcePowersActive |= (1 << forcePower); + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/absorb.mp3"); + self->s.loopSound = G_SoundIndex("sound/weapons/force/absorbloop.wav"); break; case FP_SEE: - if ( self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_1 ) - { + if (self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_1) { duration = 5000; - } - else if ( self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_2 ) - { + } else if (self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_2) { duration = 10000; - } - else// if ( self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_3 ) + } else // if ( self->client->ps.forcePowerLevel[FP_SEE] == FORCE_LEVEL_3 ) { duration = 20000; } - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/see.mp3" ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/seeloop.wav" ); + self->client->ps.forcePowersActive |= (1 << forcePower); + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/see.mp3"); + self->s.loopSound = G_SoundIndex("sound/weapons/force/seeloop.wav"); break; default: break; } - if ( duration ) - { + if (duration) { self->client->ps.forcePowerDuration[forcePower] = level.time + duration; - } - else - { + } else { self->client->ps.forcePowerDuration[forcePower] = 0; } - WP_ForcePowerDrain( self, forcePower, overrideAmt ); + WP_ForcePowerDrain(self, forcePower, overrideAmt); - if ( !self->s.number ) - { + if (!self->s.number) { self->client->sess.missionStats.forceUsed[(int)forcePower]++; } } -qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - if ( forcePower == FP_LEVITATION ) - { +qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + if (forcePower == FP_LEVITATION) { return qtrue; } - int drain = overrideAmt?overrideAmt:forcePowerNeeded[forcePower]; - if ( !drain ) - { + int drain = overrideAmt ? overrideAmt : forcePowerNeeded[forcePower]; + if (!drain) { return qtrue; } - if ( self->client->ps.forcePower < drain ) - { - //G_AddEvent( self, EV_NOAMMO, 0 ); + if (self->client->ps.forcePower < drain) { + // G_AddEvent( self, EV_NOAMMO, 0 ); return qfalse; } return qtrue; } -extern void CG_PlayerLockedWeaponSpeech( int jumping ); -extern qboolean Rosh_TwinNearBy( gentity_t *self ); -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - if ( !(self->client->ps.forcePowersKnown & ( 1 << forcePower )) ) - {//don't know this power +extern void CG_PlayerLockedWeaponSpeech(int jumping); +extern qboolean Rosh_TwinNearBy(gentity_t *self); +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + if (!(self->client->ps.forcePowersKnown & (1 << forcePower))) { // don't know this power return qfalse; - } - else if ( self->NPC && (self->NPC->aiFlags&NPCAI_ROSH) ) - { - if ( ((1<NPC && (self->NPC->aiFlags & NPCAI_ROSH)) { + if (((1 << forcePower) & FORCE_POWERS_ROSH_FROM_TWINS)) { // this is a force power we can only use when a twin is near us + if (!Rosh_TwinNearBy(self)) { return qfalse; } } } - if ( self->client->ps.forcePowerLevel[forcePower] <= 0 ) - {//can't use this power + if (self->client->ps.forcePowerLevel[forcePower] <= 0) { // can't use this power return qfalse; } - if( (self->flags&FL_LOCK_PLAYER_WEAPONS) ) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + if ((self->flags & FL_LOCK_PLAYER_WEAPONS)) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one { - if ( self->s.number < MAX_CLIENTS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (self->s.number < MAX_CLIENTS) { + CG_PlayerLockedWeaponSpeech(qfalse); } return qfalse; } - if ( in_camera && self->s.number < MAX_CLIENTS ) - {//player can't turn on force powers duing cinematics + if (in_camera && self->s.number < MAX_CLIENTS) { // player can't turn on force powers duing cinematics return qfalse; } - if ( PM_LockedAnim( self->client->ps.torsoAnim ) && self->client->ps.torsoAnimTimer ) - {//no force powers during these special anims + if (PM_LockedAnim(self->client->ps.torsoAnim) && self->client->ps.torsoAnimTimer) { // no force powers during these special anims return qfalse; } - if ( PM_SuperBreakLoseAnim( self->client->ps.torsoAnim ) - || PM_SuperBreakWinAnim( self->client->ps.torsoAnim ) ) - { + if (PM_SuperBreakLoseAnim(self->client->ps.torsoAnim) || PM_SuperBreakWinAnim(self->client->ps.torsoAnim)) { return qfalse; } - if ( (self->client->ps.forcePowersActive & ( 1 << forcePower )) ) - {//already using this power + if ((self->client->ps.forcePowersActive & (1 << forcePower))) { // already using this power return qfalse; } /* @@ -12871,48 +10159,36 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int ove return qfalse; } */ - if ( self->client->NPC_class == CLASS_ATST ) - {//Doh! No force powers in an AT-ST! + if (self->client->NPC_class == CLASS_ATST) { // Doh! No force powers in an AT-ST! return qfalse; } Vehicle_t *pVeh = NULL; - if ( (pVeh = G_IsRidingVehicle( self )) != NULL ) - {//Doh! No force powers when flying a vehicle! - if ( pVeh->m_pVehicleInfo->numHands > 1 ) - {//if in a two-handed vehicle + if ((pVeh = G_IsRidingVehicle(self)) != NULL) { // Doh! No force powers when flying a vehicle! + if (pVeh->m_pVehicleInfo->numHands > 1) { // if in a two-handed vehicle return qfalse; } } - if ( self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//Doh! No force powers when controlling an NPC + if (self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD) { // Doh! No force powers when controlling an NPC return qfalse; } - if ( self->client->ps.eFlags & EF_LOCKED_TO_WEAPON ) - {//Doh! No force powers when in an emplaced gun! + if (self->client->ps.eFlags & EF_LOCKED_TO_WEAPON) { // Doh! No force powers when in an emplaced gun! return qfalse; } - if ( (self->client->ps.saber[0].saberFlags&SFL_SINGLE_BLADE_THROWABLE)//SaberStaff() //using staff - && !self->client->ps.dualSabers //only 1, in right hand - && !self->client->ps.saber[0].blade[1].active )//only first blade is on - {//allow power - //FIXME: externalize this condition seperately? - } - else - { - if ( forcePower == FP_SABERTHROW && (self->client->ps.saber[0].saberFlags&SFL_NOT_THROWABLE) ) - {//cannot throw this kind of saber + if ((self->client->ps.saber[0].saberFlags & SFL_SINGLE_BLADE_THROWABLE) // SaberStaff() //using staff + && !self->client->ps.dualSabers // only 1, in right hand + && !self->client->ps.saber[0].blade[1].active) // only first blade is on + { // allow power + // FIXME: externalize this condition seperately? + } else { + if (forcePower == FP_SABERTHROW && (self->client->ps.saber[0].saberFlags & SFL_NOT_THROWABLE)) { // cannot throw this kind of saber return qfalse; } - if ( self->client->ps.saber[0].Active() ) - { - if ( (self->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) ) - { - if ( g_saberRestrictForce->integer ) - { - switch ( forcePower ) - { + if (self->client->ps.saber[0].Active()) { + if ((self->client->ps.saber[0].saberFlags & SFL_TWO_HANDED)) { + if (g_saberRestrictForce->integer) { + switch (forcePower) { case FP_PUSH: case FP_PULL: case FP_TELEPATHY: @@ -12925,21 +10201,17 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int ove } } } - if ( (self->client->ps.saber[0].saberFlags&SFL_TWO_HANDED) - || (self->client->ps.dualSabers && self->client->ps.saber[1].Active()) ) - {//this saber requires the use of two hands OR our other hand is using an active saber too - if ( (self->client->ps.saber[0].forceRestrictions&(1<client->ps.saber[0].saberFlags & SFL_TWO_HANDED) || + (self->client->ps.dualSabers && + self->client->ps.saber[1].Active())) { // this saber requires the use of two hands OR our other hand is using an active saber too + if ((self->client->ps.saber[0].forceRestrictions & (1 << forcePower))) { // this power is verboten when using this saber return qfalse; } } } - if ( self->client->ps.dualSabers && self->client->ps.saber[1].Active() ) - { - if ( g_saberRestrictForce->integer ) - { - switch ( forcePower ) - { + if (self->client->ps.dualSabers && self->client->ps.saber[1].Active()) { + if (g_saberRestrictForce->integer) { + switch (forcePower) { case FP_PUSH: case FP_PULL: case FP_TELEPATHY: @@ -12951,51 +10223,43 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int ove break; } } - if ( (self->client->ps.saber[1].forceRestrictions&(1<client->ps.saber[1].forceRestrictions & (1 << forcePower))) { // this power is verboten when using this saber return qfalse; } } } - return WP_ForcePowerAvailable( self, forcePower, overrideAmt ); + return WP_ForcePowerAvailable(self, forcePower, overrideAmt); } -void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) -{ - gentity_t *gripEnt; - gentity_t *drainEnt; +void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower) { + gentity_t *gripEnt; + gentity_t *drainEnt; - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << forcePower))) { // umm, wasn't doing it, so... return; } - self->client->ps.forcePowersActive &= ~( 1 << forcePower ); + self->client->ps.forcePowersActive &= ~(1 << forcePower); - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: - //if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 ) - {//wasn't an instant heal and heal is now done - if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 ) - {//if in meditation pose, must come out of it - //FIXME: BOTH_FORCEHEAL_STOP - if ( self->client->ps.legsAnim == BOTH_FORCEHEAL_START ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 ) + { // wasn't an instant heal and heal is now done + if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2) { // if in meditation pose, must come out of it + // FIXME: BOTH_FORCEHEAL_STOP + if (self->client->ps.legsAnim == BOTH_FORCEHEAL_START) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_FORCEHEAL_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCEHEAL_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; } } - WP_StopForceHealEffects( self ); - if (self->health >= self->client->ps.stats[STAT_MAX_HEALTH]/3) - { + WP_StopForceHealEffects(self); + if (self->health >= self->client->ps.stats[STAT_MAX_HEALTH] / 3) { gi.G2API_ClearSkinGore(self->ghoul2); } break; @@ -13003,17 +10267,15 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->client->ps.forcePowerDebounce[FP_LEVITATION] = 0; break; case FP_SPEED: - if ( !self->s.number ) - {//player using force speed - if ( g_timescale->value != 1.0 ) - { - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_2 ) - {//not slowed down because of force rage + if (!self->s.number) { // player using force speed + if (g_timescale->value != 1.0) { + if (!(self->client->ps.forcePowersActive & (1 << FP_RAGE)) || + self->client->ps.forcePowerLevel[FP_RAGE] < FORCE_LEVEL_2) { // not slowed down because of force rage gi.cvar_set("timescale", "1"); } } } - //FIXME: reset my current anim, keeping current frame, but with proper anim speed + // FIXME: reset my current anim, keeping current frame, but with proper anim speed // otherwise, the anim will continue playing at high speed self->s.loopSound = 0; break; @@ -13024,117 +10286,87 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) case FP_TELEPATHY: break; case FP_GRIP: - if ( self->NPC ) - { - TIMER_Set( self, "gripping", -level.time ); + if (self->NPC) { + TIMER_Set(self, "gripping", -level.time); } - if ( self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD ) - { + if (self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD) { gripEnt = &g_entities[self->client->ps.forceGripEntityNum]; - if ( gripEnt ) - { + if (gripEnt) { gripEnt->s.loopSound = 0; - if ( gripEnt->client ) - { + if (gripEnt->client) { gripEnt->client->ps.eFlags &= ~EF_FORCE_GRIPPED; - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//sanity-cap the velocity - float gripVel = VectorNormalize( gripEnt->client->ps.velocity ); - if ( gripVel > 500.0f ) - { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // sanity-cap the velocity + float gripVel = VectorNormalize(gripEnt->client->ps.velocity); + if (gripVel > 500.0f) { gripVel = 500.0f; } - VectorScale( gripEnt->client->ps.velocity, gripVel, gripEnt->client->ps.velocity ); + VectorScale(gripEnt->client->ps.velocity, gripVel, gripEnt->client->ps.velocity); } - //FIXME: they probably dropped their weapon, should we make them flee? Or should AI handle no-weapon behavior? -//rww - RAGDOLL_BEGIN + // FIXME: they probably dropped their weapon, should we make them flee? Or should AI handle no-weapon behavior? +// rww - RAGDOLL_BEGIN #ifndef JK2_RAGDOLL_GRIPNOHEALTH -//rww - RAGDOLL_END - if ( gripEnt->health > 0 ) -//rww - RAGDOLL_BEGIN + // rww - RAGDOLL_END + if (gripEnt->health > 0) +// rww - RAGDOLL_BEGIN #endif -//rww - RAGDOLL_END + // rww - RAGDOLL_END { - int holdTime = 500; - if ( gripEnt->health > 0 ) - { - G_AddEvent( gripEnt, EV_WATER_CLEAR, 0 ); + int holdTime = 500; + if (gripEnt->health > 0) { + G_AddEvent(gripEnt, EV_WATER_CLEAR, 0); } - if ( gripEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time ) - {//they probably pushed out of it + if (gripEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time) { // they probably pushed out of it holdTime = 0; - } - else if ( gripEnt->s.weapon == WP_SABER ) - {//jedi recover faster - holdTime = self->client->ps.forcePowerLevel[FP_GRIP]*200; - } - else - { - holdTime = self->client->ps.forcePowerLevel[FP_GRIP]*500; - } - //stop the anims soon, keep them locked in place for a bit - if ( gripEnt->client->ps.torsoAnim == BOTH_CHOKE1 || gripEnt->client->ps.torsoAnim == BOTH_CHOKE3 ) - {//stop choking anim on torso - if ( gripEnt->client->ps.torsoAnimTimer > holdTime ) - { + } else if (gripEnt->s.weapon == WP_SABER) { // jedi recover faster + holdTime = self->client->ps.forcePowerLevel[FP_GRIP] * 200; + } else { + holdTime = self->client->ps.forcePowerLevel[FP_GRIP] * 500; + } + // stop the anims soon, keep them locked in place for a bit + if (gripEnt->client->ps.torsoAnim == BOTH_CHOKE1 || gripEnt->client->ps.torsoAnim == BOTH_CHOKE3) { // stop choking anim on torso + if (gripEnt->client->ps.torsoAnimTimer > holdTime) { gripEnt->client->ps.torsoAnimTimer = holdTime; } } - if ( gripEnt->client->ps.legsAnim == BOTH_CHOKE1 || gripEnt->client->ps.legsAnim == BOTH_CHOKE3 ) - {//stop choking anim on legs + if (gripEnt->client->ps.legsAnim == BOTH_CHOKE1 || gripEnt->client->ps.legsAnim == BOTH_CHOKE3) { // stop choking anim on legs gripEnt->client->ps.legsAnimTimer = 0; - if ( holdTime ) - { - //lock them in place for a bit + if (holdTime) { + // lock them in place for a bit gripEnt->client->ps.pm_time = gripEnt->client->ps.torsoAnimTimer; gripEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( gripEnt->s.number ) - {//NPC + if (gripEnt->s.number) { // NPC gripEnt->painDebounceTime = level.time + gripEnt->client->ps.torsoAnimTimer; - } - else - {//player + } else { // player gripEnt->aimDebounceTime = level.time + gripEnt->client->ps.torsoAnimTimer; } } } - if ( gripEnt->NPC ) - { - if ( !(gripEnt->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//not falling to their death + if (gripEnt->NPC) { + if (!(gripEnt->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // not falling to their death gripEnt->NPC->nextBStateThink = level.time + holdTime; } - //if still alive after stopped gripping, let them wake others up - if ( gripEnt->health > 0 ) - { - G_AngerAlert( gripEnt ); + // if still alive after stopped gripping, let them wake others up + if (gripEnt->health > 0) { + G_AngerAlert(gripEnt); } } } - } - else - { + } else { gripEnt->s.eFlags &= ~EF_FORCE_GRIPPED; - if ( gripEnt->s.eType == ET_MISSILE ) - {//continue normal movement - if ( gripEnt->s.weapon == WP_THERMAL ) - { + if (gripEnt->s.eType == ET_MISSILE) { // continue normal movement + if (gripEnt->s.weapon == WP_THERMAL) { gripEnt->s.pos.trType = TR_INTERPOLATE; + } else { + gripEnt->s.pos.trType = TR_LINEAR; // FIXME: what about gravity-effected projectiles? } - else - { - gripEnt->s.pos.trType = TR_LINEAR;//FIXME: what about gravity-effected projectiles? - } - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); gripEnt->s.pos.trTime = level.time; - } - else - {//drop it + } else { // drop it gripEnt->e_ThinkFunc = thinkF_G_RunObject; gripEnt->nextthink = level.time + FRAMETIME; gripEnt->s.pos.trType = TR_GRAVITY; - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); gripEnt->s.pos.trTime = level.time; } } @@ -13142,130 +10374,95 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->s.loopSound = 0; self->client->ps.forceGripEntityNum = ENTITYNUM_NONE; } - if ( self->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCEGRIP_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCEGRIP_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } break; case FP_LIGHTNING: - if ( self->NPC ) - { - TIMER_Set( self, "holdLightning", -level.time ); - } - if ( self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_HOLD - || self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_2HANDEDLIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - {//don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) - self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 3000;//FIXME: define? - } - else - {//stop the looping sound - self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 1000;//FIXME: define? + if (self->NPC) { + TIMER_Set(self, "holdLightning", -level.time); + } + if (self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_HOLD || self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_2HANDEDLIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < + FORCE_LEVEL_2) { // don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) + self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 3000; // FIXME: define? + } else { // stop the looping sound + self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 1000; // FIXME: define? self->s.loopSound = 0; } break; case FP_RAGE: - self->client->ps.forceRageRecoveryTime = level.time + 10000;//recover for 10 seconds - if ( self->client->ps.forcePowerDuration[FP_RAGE] > level.time ) - {//still had time left, we cut it short - self->client->ps.forceRageRecoveryTime -= (self->client->ps.forcePowerDuration[FP_RAGE] - level.time);//minus however much time you had left when you cut it short - } - if ( !self->s.number ) - {//player using force speed - if ( g_timescale->value != 1.0 ) - { - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forceRageRecoveryTime = level.time + 10000; // recover for 10 seconds + if (self->client->ps.forcePowerDuration[FP_RAGE] > level.time) { // still had time left, we cut it short + self->client->ps.forceRageRecoveryTime -= + (self->client->ps.forcePowerDuration[FP_RAGE] - level.time); // minus however much time you had left when you cut it short + } + if (!self->s.number) { // player using force speed + if (g_timescale->value != 1.0) { + if (!(self->client->ps.forcePowersActive & (1 << FP_SPEED))) { // not slowed down because of force speed gi.cvar_set("timescale", "1"); } } } - //FIXME: reset my current anim, keeping current frame, but with proper anim speed + // FIXME: reset my current anim, keeping current frame, but with proper anim speed // otherwise, the anim will continue playing at high speed self->s.loopSound = 0; - if ( self->NPC ) - { - Jedi_RageStop( self ); + if (self->NPC) { + Jedi_RageStop(self); } - if ( self->chestBolt != -1 ) - { - G_StopEffect("force/rage2", self->playerModel, self->chestBolt, self->s.number ); + if (self->chestBolt != -1) { + G_StopEffect("force/rage2", self->playerModel, self->chestBolt, self->s.number); } break; case FP_DRAIN: - if ( self->NPC ) - { - TIMER_Set( self, "draining", -level.time ); - } - if ( self->client->ps.forcePowerLevel[FP_DRAIN] < FORCE_LEVEL_2 ) - {//don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 3000;//FIXME: define? - } - else - {//stop the looping sound - self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 1000;//FIXME: define? + if (self->NPC) { + TIMER_Set(self, "draining", -level.time); + } + if (self->client->ps.forcePowerLevel[FP_DRAIN] < + FORCE_LEVEL_2) { // don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 3000; // FIXME: define? + } else { // stop the looping sound + self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 1000; // FIXME: define? self->s.loopSound = 0; } - //drop them - if ( self->client->ps.forceDrainEntityNum < ENTITYNUM_WORLD ) - { + // drop them + if (self->client->ps.forceDrainEntityNum < ENTITYNUM_WORLD) { drainEnt = &g_entities[self->client->ps.forceDrainEntityNum]; - if ( drainEnt ) - { - if ( drainEnt->client ) - { + if (drainEnt) { + if (drainEnt->client) { drainEnt->client->ps.eFlags &= ~EF_FORCE_DRAINED; - //VectorClear( drainEnt->client->ps.velocity ); - if ( drainEnt->health > 0 ) - { - if ( drainEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time ) - {//they probably pushed out of it - } - else - { - //NPC_SetAnim( drainEnt, SETANIM_BOTH, BOTH_HUGGEESTOP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( drainEnt->client->ps.torsoAnim != BOTH_FORCEPUSH ) - {//don't stop the push + // VectorClear( drainEnt->client->ps.velocity ); + if (drainEnt->health > 0) { + if (drainEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time) { // they probably pushed out of it + } else { + // NPC_SetAnim( drainEnt, SETANIM_BOTH, BOTH_HUGGEESTOP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (drainEnt->client->ps.torsoAnim != BOTH_FORCEPUSH) { // don't stop the push drainEnt->client->ps.torsoAnimTimer = 0; } drainEnt->client->ps.legsAnimTimer = 0; } - if ( drainEnt->NPC ) - {//if still alive after stopped draining, let them wake others up - G_AngerAlert( drainEnt ); + if (drainEnt->NPC) { // if still alive after stopped draining, let them wake others up + G_AngerAlert(drainEnt); } - } - else - {//leave the effect playing on them for a few seconds - //drainEnt->client->ps.eFlags |= EF_FORCE_DRAINED; - drainEnt->s.powerups |= ( 1 << PW_DRAINED ); - drainEnt->client->ps.powerups[PW_DRAINED] = level.time + Q_irand( 1000, 4000 ); + } else { // leave the effect playing on them for a few seconds + // drainEnt->client->ps.eFlags |= EF_FORCE_DRAINED; + drainEnt->s.powerups |= (1 << PW_DRAINED); + drainEnt->client->ps.powerups[PW_DRAINED] = level.time + Q_irand(1000, 4000); } } } - self->client->ps.forceDrainEntityNum = ENTITYNUM_NONE; - } - if ( self->client->ps.torsoAnim == BOTH_HUGGER1 ) - {//old anim - NPC_SetAnim( self, SETANIM_BOTH, BOTH_HUGGERSTOP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START - || self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) - {//new anim - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + self->client->ps.forceDrainEntityNum = ENTITYNUM_NONE; } - else if ( self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_HOLD - || self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_DRAIN_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_HUGGER1) { // old anim + NPC_SetAnim(self, SETANIM_BOTH, BOTH_HUGGERSTOP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD) { // new anim + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_HOLD || self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_DRAIN_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } break; case FP_PROTECT: @@ -13273,25 +10470,19 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) break; case FP_ABSORB: self->s.loopSound = 0; - if ( self->client->ps.legsAnim == BOTH_FORCE_ABSORB_START ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_FORCE_ABSORB_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.legsAnim == BOTH_FORCE_ABSORB_START) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_FORCE_ABSORB_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_FORCE_ABSORB_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_ABSORB_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCE_ABSORB_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_ABSORB_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.forcePowerLevel[FP_ABSORB] < FORCE_LEVEL_2 ) - {//was stuck, free us in case we interrupted it or something + if (self->client->ps.forcePowerLevel[FP_ABSORB] < FORCE_LEVEL_2) { // was stuck, free us in case we interrupted it or something self->client->ps.weaponTime = 0; self->client->ps.pm_flags &= ~PMF_TIME_KNOCKBACK; self->client->ps.pm_time = 0; - if ( self->s.number ) - {//NPC + if (self->s.number) { // NPC self->painDebounceTime = 0; - } - else - {//player + } else { // player self->aimDebounceTime = 0; } } @@ -13304,176 +10495,131 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) } } -void WP_ForceForceThrow( gentity_t *thrower ) -{ - if ( !thrower || !thrower->client ) - { +void WP_ForceForceThrow(gentity_t *thrower) { + if (!thrower || !thrower->client) { return; } qboolean relock = qfalse; - if ( !(thrower->client->ps.forcePowersKnown&(1<client->ps.forcePowersKnown |= (1<client->ps.forcePowersKnown & (1 << FP_PUSH))) { // give them push just for this specific purpose + thrower->client->ps.forcePowersKnown |= (1 << FP_PUSH); thrower->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_1; } - if ( thrower->NPC - && (thrower->NPC->aiFlags&NPCAI_HEAL_ROSH) - && (thrower->flags&FL_LOCK_PLAYER_WEAPONS) ) - { + if (thrower->NPC && (thrower->NPC->aiFlags & NPCAI_HEAL_ROSH) && (thrower->flags & FL_LOCK_PLAYER_WEAPONS)) { thrower->flags &= ~FL_LOCK_PLAYER_WEAPONS; relock = qtrue; } - ForceThrow( thrower, qfalse ); + ForceThrow(thrower, qfalse); - if ( relock ) - { + if (relock) { thrower->flags |= FL_LOCK_PLAYER_WEAPONS; } - if ( thrower ) - {//take it back off - thrower->client->ps.forcePowersKnown &= ~(1<client->ps.forcePowersKnown &= ~(1 << FP_PUSH); thrower->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_0; } } -extern qboolean PM_ForceJumpingUp( gentity_t *gent ); -static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd ) -{ - float speed, newSpeed; - gentity_t *gripEnt, *drainEnt; - vec3_t angles, dir, gripOrg, gripEntOrg; - float dist; - extern usercmd_t ucmd; +extern qboolean PM_ForceJumpingUp(gentity_t *gent); +static void WP_ForcePowerRun(gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd) { + float speed, newSpeed; + gentity_t *gripEnt, *drainEnt; + vec3_t angles, dir, gripOrg, gripEntOrg; + float dist; + extern usercmd_t ucmd; - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: - if ( self->client->ps.forceHealCount >= FP_MaxForceHeal(self) || self->health >= self->client->ps.stats[STAT_MAX_HEALTH] ) - {//fully healed or used up all 25 - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - int index = Q_irand( 1, 4 ); - if ( self->s.number < MAX_CLIENTS ) - { - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/force/heal%d_%c.mp3", index, g_sex->string[0] ) ); - } - else if ( self->NPC ) - { - if ( self->NPC->blockedSpeechDebounceTime <= level.time ) - {//enough time has passed since our last speech - if ( Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - {//not playing a scripted line - //say "Ahhh...." - if ( self->NPC->stats.sex == SEX_MALE - || self->NPC->stats.sex == SEX_NEUTRAL ) - { - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/force/heal%d_m.mp3", index ) ); - } - else//all other sexes use female sounds + if (self->client->ps.forceHealCount >= FP_MaxForceHeal(self) || + self->health >= self->client->ps.stats[STAT_MAX_HEALTH]) { // fully healed or used up all 25 + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + int index = Q_irand(1, 4); + if (self->s.number < MAX_CLIENTS) { + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/force/heal%d_%c.mp3", index, g_sex->string[0])); + } else if (self->NPC) { + if (self->NPC->blockedSpeechDebounceTime <= level.time) { // enough time has passed since our last speech + if (Q3_TaskIDPending(self, TID_CHAN_VOICE)) { // not playing a scripted line + // say "Ahhh...." + if (self->NPC->stats.sex == SEX_MALE || self->NPC->stats.sex == SEX_NEUTRAL) { + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/force/heal%d_m.mp3", index)); + } else // all other sexes use female sounds { - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/force/heal%d_f.mp3", index ) ); + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/force/heal%d_f.mp3", index)); } } } } } - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 && ( (cmd->buttons&BUTTON_ATTACK) || (cmd->buttons&BUTTON_ALT_ATTACK) || self->painDebounceTime > level.time || (self->client->ps.weaponTime&&self->client->ps.weapon!=WP_NONE) ) ) - {//attacked or was hit while healing... - //stop healing - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 && ( cmd->rightmove || cmd->forwardmove || cmd->upmove > 0 ) ) - {//moved while healing... FIXME: also, in WP_ForcePowerStart, stop healing if any other force power is used - //stop healing - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerDebounce[FP_HEAL] < level.time ) - {//time to heal again - if ( WP_ForcePowerAvailable( self, forcePower, 4 ) ) - {//have available power - int healInterval = FP_ForceHealInterval( self ); - int healAmount = 1;//hard, normal healing rate - if ( self->s.number < MAX_CLIENTS ) - { - if ( g_spskill->integer == 1 ) - {//medium, heal twice as fast + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 && + ((cmd->buttons & BUTTON_ATTACK) || (cmd->buttons & BUTTON_ALT_ATTACK) || self->painDebounceTime > level.time || + (self->client->ps.weaponTime && self->client->ps.weapon != WP_NONE))) { // attacked or was hit while healing... + // stop healing + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 && + (cmd->rightmove || cmd->forwardmove || + cmd->upmove > 0)) { // moved while healing... FIXME: also, in WP_ForcePowerStart, stop healing if any other force power is used + // stop healing + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerDebounce[FP_HEAL] < level.time) { // time to heal again + if (WP_ForcePowerAvailable(self, forcePower, 4)) { // have available power + int healInterval = FP_ForceHealInterval(self); + int healAmount = 1; // hard, normal healing rate + if (self->s.number < MAX_CLIENTS) { + if (g_spskill->integer == 1) { // medium, heal twice as fast healAmount *= 2; - } - else if ( g_spskill->integer == 0 ) - {//easy, heal 3 times as fast... + } else if (g_spskill->integer == 0) { // easy, heal 3 times as fast... healAmount *= 3; } } - if ( self->health + healAmount > self->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (self->health + healAmount > self->client->ps.stats[STAT_MAX_HEALTH]) { healAmount = self->client->ps.stats[STAT_MAX_HEALTH] - self->health; } self->health += healAmount; self->client->ps.forceHealCount += healAmount; self->client->ps.forcePowerDebounce[FP_HEAL] = level.time + healInterval; - WP_ForcePowerDrain( self, forcePower, 4 ); - } - else - {//stop - WP_ForcePowerStop( self, forcePower ); + WP_ForcePowerDrain(self, forcePower, 4); + } else { // stop + WP_ForcePowerStop(self, forcePower); } } break; case FP_LEVITATION: - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceJumpZStart ) - {//done with jump - WP_ForcePowerStop( self, forcePower ); - } - else - { - if ( PM_ForceJumpingUp( self ) ) - {//holding jump in air - if ( cmd->upmove > 10 ) - {//still trying to go up - if ( WP_ForcePowerAvailable( self, FP_LEVITATION, 1 ) ) - { - if ( self->client->ps.forcePowerDebounce[FP_LEVITATION] < level.time ) - { - WP_ForcePowerDrain( self, FP_LEVITATION, 5 ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceJumpZStart) { // done with jump + WP_ForcePowerStop(self, forcePower); + } else { + if (PM_ForceJumpingUp(self)) { // holding jump in air + if (cmd->upmove > 10) { // still trying to go up + if (WP_ForcePowerAvailable(self, FP_LEVITATION, 1)) { + if (self->client->ps.forcePowerDebounce[FP_LEVITATION] < level.time) { + WP_ForcePowerDrain(self, FP_LEVITATION, 5); self->client->ps.forcePowerDebounce[FP_LEVITATION] = level.time + 100; } - self->client->ps.forcePowersActive |= ( 1 << FP_LEVITATION ); - self->client->ps.forceJumpCharge = 1;//just used as a flag for the player, cleared when he lands - } - else - {//cut the jump short - WP_ForcePowerStop( self, forcePower ); + self->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + self->client->ps.forceJumpCharge = 1; // just used as a flag for the player, cleared when he lands + } else { // cut the jump short + WP_ForcePowerStop(self, forcePower); } + } else { // cut the jump short + WP_ForcePowerStop(self, forcePower); } - else - {//cut the jump short - WP_ForcePowerStop( self, forcePower ); - } - } - else - { - WP_ForcePowerStop( self, forcePower ); + } else { + WP_ForcePowerStop(self, forcePower); } } break; case FP_SPEED: speed = forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]; - if ( !self->s.number ) - {//player using force speed - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SPEED] >= self->client->ps.forcePowerLevel[FP_RAGE] ) - {//either not using rage or rage is at a lower level than speed + if (!self->s.number) { // player using force speed + if (!(self->client->ps.forcePowersActive & (1 << FP_RAGE)) || + self->client->ps.forcePowerLevel[FP_SPEED] >= + self->client->ps.forcePowerLevel[FP_RAGE]) { // either not using rage or rage is at a lower level than speed gi.cvar_set("timescale", va("%4.2f", speed)); - if ( g_timescale->value > speed ) - { + if (g_timescale->value > speed) { newSpeed = g_timescale->value - 0.05; - if ( newSpeed < speed ) - { + if (newSpeed < speed) { newSpeed = speed; } gi.cvar_set("timescale", va("%4.2f", newSpeed)); @@ -13488,439 +10634,329 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd case FP_TELEPATHY: break; case FP_GRIP: - if ( !WP_ForcePowerAvailable( self, FP_GRIP, 0 ) - || (self->client->ps.forcePowerLevel[FP_GRIP]>FORCE_LEVEL_1&&!self->s.number&&!(cmd->buttons&BUTTON_FORCEGRIP)) ) - { - WP_ForcePowerStop( self, FP_GRIP ); + if (!WP_ForcePowerAvailable(self, FP_GRIP, 0) || + (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 && !self->s.number && !(cmd->buttons & BUTTON_FORCEGRIP))) { + WP_ForcePowerStop(self, FP_GRIP); return; - } - else if ( self->client->ps.forceGripEntityNum >= 0 && self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD ) - { + } else if (self->client->ps.forceGripEntityNum >= 0 && self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD) { gripEnt = &g_entities[self->client->ps.forceGripEntityNum]; - if ( !gripEnt || !gripEnt->inuse ) - {//invalid or freed ent - WP_ForcePowerStop( self, FP_GRIP ); + if (!gripEnt || !gripEnt->inuse) { // invalid or freed ent + WP_ForcePowerStop(self, FP_GRIP); return; - } - else -//rww - RAGDOLL_BEGIN + } else +// rww - RAGDOLL_BEGIN #ifndef JK2_RAGDOLL_GRIPNOHEALTH -//rww - RAGDOLL_END - if ( gripEnt->health <= 0 && gripEnt->takedamage )//FIXME: what about things that never had health or lose takedamage when they die? - {//either invalid ent, or dead ent - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else -//rww - RAGDOLL_BEGIN -#endif -//rww - RAGDOLL_END - if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_1 - && gripEnt->client - && gripEnt->client->ps.groundEntityNum == ENTITYNUM_NONE - && gripEnt->client->moveType != MT_FLYSWIM ) - { - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else if ( gripEnt->client && gripEnt->client->moveType == MT_FLYSWIM && VectorLengthSquared( gripEnt->client->ps.velocity ) > (300*300) ) - {//flying creature broke free - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else if ( gripEnt->client - && gripEnt->health>0 //dead dudes don't fly - && (gripEnt->client->NPC_class == CLASS_BOBAFETT || gripEnt->client->NPC_class == CLASS_ROCKETTROOPER) - && self->client->ps.forcePowerDebounce[FP_GRIP] < level.time - && !Q_irand( 0, 3 ) - ) - {//boba fett - fly away! - gripEnt->client->ps.forceJumpCharge = 0;//so we don't play the force flip anim - gripEnt->client->ps.velocity[2] = 250; - gripEnt->client->ps.forceJumpZStart = gripEnt->currentOrigin[2];//so we don't take damage if we land at same height - gripEnt->client->ps.pm_flags |= PMF_JUMPING; - G_AddEvent( gripEnt, EV_JUMP, 0 ); - JET_FlyStart( gripEnt ); - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else if ( gripEnt->NPC - && gripEnt->client - && gripEnt->client->ps.forcePowersKnown - && (gripEnt->client->NPC_class==CLASS_REBORN||gripEnt->client->ps.weapon==WP_SABER) - && !Jedi_CultistDestroyer(gripEnt) - && !Q_irand( 0, 100-(gripEnt->NPC->stats.evasion*8)-(g_spskill->integer*20) ) ) - {//a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? - WP_ForceForceThrow( gripEnt ); - //FIXME: I need to go into some pushed back anim... - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else if ( PM_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInStart( self->client->ps.saberMove ) ) - {//started an attack - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - else - { - int gripLevel = self->client->ps.forcePowerLevel[FP_GRIP]; - if ( gripEnt->client ) - { - gripLevel = WP_AbsorbConversion( gripEnt, gripEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_GRIP, self->client->ps.forcePowerLevel[FP_GRIP], forcePowerNeeded[gripLevel] ); - } - if ( !gripLevel ) - { - WP_ForcePowerStop( self, forcePower ); + // rww - RAGDOLL_END + if (gripEnt->health <= 0 && gripEnt->takedamage) // FIXME: what about things that never had health or lose takedamage when they die? + { // either invalid ent, or dead ent + WP_ForcePowerStop(self, FP_GRIP); return; - } - - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding it - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->client->ps.torsoAnimTimer < 100 ){//we were already playing this anim, we didn't want to restart it, but we want to hold it for at least 100ms, sooo.... - - self->client->ps.torsoAnimTimer = 100; - } - } - //get their org - VectorCopy( self->client->ps.viewangles, angles ); - angles[0] -= 10; - AngleVectors( angles, dir, NULL, NULL ); - if ( gripEnt->client ) - {//move - VectorCopy( gripEnt->client->renderInfo.headPoint, gripEntOrg ); - } - else - { - VectorCopy( gripEnt->currentOrigin, gripEntOrg ); - } + } else +// rww - RAGDOLL_BEGIN +#endif + // rww - RAGDOLL_END + if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_1 && gripEnt->client && + gripEnt->client->ps.groundEntityNum == ENTITYNUM_NONE && gripEnt->client->moveType != MT_FLYSWIM) { + WP_ForcePowerStop(self, FP_GRIP); + return; + } else if (gripEnt->client && gripEnt->client->moveType == MT_FLYSWIM && + VectorLengthSquared(gripEnt->client->ps.velocity) > (300 * 300)) { // flying creature broke free + WP_ForcePowerStop(self, FP_GRIP); + return; + } else if (gripEnt->client && gripEnt->health > 0 // dead dudes don't fly + && (gripEnt->client->NPC_class == CLASS_BOBAFETT || gripEnt->client->NPC_class == CLASS_ROCKETTROOPER) && + self->client->ps.forcePowerDebounce[FP_GRIP] < level.time && !Q_irand(0, 3)) { // boba fett - fly away! + gripEnt->client->ps.forceJumpCharge = 0; // so we don't play the force flip anim + gripEnt->client->ps.velocity[2] = 250; + gripEnt->client->ps.forceJumpZStart = gripEnt->currentOrigin[2]; // so we don't take damage if we land at same height + gripEnt->client->ps.pm_flags |= PMF_JUMPING; + G_AddEvent(gripEnt, EV_JUMP, 0); + JET_FlyStart(gripEnt); + WP_ForcePowerStop(self, FP_GRIP); + return; + } else if (gripEnt->NPC && gripEnt->client && gripEnt->client->ps.forcePowersKnown && + (gripEnt->client->NPC_class == CLASS_REBORN || gripEnt->client->ps.weapon == WP_SABER) && !Jedi_CultistDestroyer(gripEnt) && + !Q_irand(0, + 100 - (gripEnt->NPC->stats.evasion * 8) - + (g_spskill->integer * 20))) { // a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? + WP_ForceForceThrow(gripEnt); + // FIXME: I need to go into some pushed back anim... + WP_ForcePowerStop(self, FP_GRIP); + return; + } else if (PM_SaberInAttack(self->client->ps.saberMove) || PM_SaberInStart(self->client->ps.saberMove)) { // started an attack + WP_ForcePowerStop(self, FP_GRIP); + return; + } else { + int gripLevel = self->client->ps.forcePowerLevel[FP_GRIP]; + if (gripEnt->client) { + gripLevel = WP_AbsorbConversion(gripEnt, gripEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_GRIP, + self->client->ps.forcePowerLevel[FP_GRIP], forcePowerNeeded[gripLevel]); + } + if (!gripLevel) { + WP_ForcePowerStop(self, forcePower); + return; + } - //how far are they - dist = Distance( self->client->renderInfo.handLPoint, gripEntOrg ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 && - (!InFront( gripEntOrg, self->client->renderInfo.handLPoint, self->client->ps.viewangles, 0.3f ) || - DistanceSquared( gripEntOrg, self->client->renderInfo.handLPoint ) > FORCE_GRIP_DIST_SQUARED)) - {//must face them - WP_ForcePowerStop( self, FP_GRIP ); - return; - } + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding it + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (self->client->ps.torsoAnimTimer < + 100) { // we were already playing this anim, we didn't want to restart it, but we want to hold it for at least 100ms, sooo.... - //check for lift or carry - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 - && (!gripEnt->client || (!gripEnt->message&&!(gripEnt->flags&FL_NO_KNOCKBACK))) ) - {//carry - //cap dist - if ( dist > FORCE_GRIP_3_MAX_DIST ) - { - dist = FORCE_GRIP_3_MAX_DIST; - } - else if ( dist < FORCE_GRIP_3_MIN_DIST ) - { - dist = FORCE_GRIP_3_MIN_DIST; - } - VectorMA( self->client->renderInfo.handLPoint, dist, dir, gripOrg ); - } - else if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//just lift - VectorCopy( self->client->ps.forceGripOrg, gripOrg ); - } - else - { - VectorCopy( gripEnt->currentOrigin, gripOrg ); - } - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//if holding him, make sure there's a clear LOS between my hand and him - trace_t gripTrace; - gi.trace( &gripTrace, self->client->renderInfo.handLPoint, NULL, NULL, gripEntOrg, ENTITYNUM_NONE, MASK_FORCE_PUSH, (EG2_Collision)0, 0 ); - if ( gripTrace.startsolid - || gripTrace.allsolid - || gripTrace.fraction < 1.0f ) - {//no clear trace, drop them - WP_ForcePowerStop( self, FP_GRIP ); - return; - } - } - //now move them - if ( gripEnt->client ) - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - VectorSubtract( gripOrg, gripEntOrg, gripEnt->client->ps.velocity ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 - && (!gripEnt->client || (!gripEnt->message&&!(gripEnt->flags&FL_NO_KNOCKBACK)) ) ) - {//level 2 just lifts them - float gripDist = VectorNormalize( gripEnt->client->ps.velocity )/3.0f; - if ( gripDist < 20.0f ) - { - if (gripDist<2.0f) - { - VectorClear(gripEnt->client->ps.velocity); + self->client->ps.torsoAnimTimer = 100; + } + } + // get their org + VectorCopy(self->client->ps.viewangles, angles); + angles[0] -= 10; + AngleVectors(angles, dir, NULL, NULL); + if (gripEnt->client) { // move + VectorCopy(gripEnt->client->renderInfo.headPoint, gripEntOrg); + } else { + VectorCopy(gripEnt->currentOrigin, gripEntOrg); + } + + // how far are they + dist = Distance(self->client->renderInfo.handLPoint, gripEntOrg); + if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 && + (!InFront(gripEntOrg, self->client->renderInfo.handLPoint, self->client->ps.viewangles, 0.3f) || + DistanceSquared(gripEntOrg, self->client->renderInfo.handLPoint) > FORCE_GRIP_DIST_SQUARED)) { // must face them + WP_ForcePowerStop(self, FP_GRIP); + return; + } + + // check for lift or carry + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 && + (!gripEnt->client || (!gripEnt->message && !(gripEnt->flags & FL_NO_KNOCKBACK)))) { // carry + // cap dist + if (dist > FORCE_GRIP_3_MAX_DIST) { + dist = FORCE_GRIP_3_MAX_DIST; + } else if (dist < FORCE_GRIP_3_MIN_DIST) { + dist = FORCE_GRIP_3_MIN_DIST; + } + VectorMA(self->client->renderInfo.handLPoint, dist, dir, gripOrg); + } else if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // just lift + VectorCopy(self->client->ps.forceGripOrg, gripOrg); + } else { + VectorCopy(gripEnt->currentOrigin, gripOrg); + } + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // if holding him, make sure there's a clear LOS between my hand and + // him + trace_t gripTrace; + gi.trace(&gripTrace, self->client->renderInfo.handLPoint, NULL, NULL, gripEntOrg, ENTITYNUM_NONE, MASK_FORCE_PUSH, (EG2_Collision)0, + 0); + if (gripTrace.startsolid || gripTrace.allsolid || gripTrace.fraction < 1.0f) { // no clear trace, drop them + WP_ForcePowerStop(self, FP_GRIP); + return; + } + } + // now move them + if (gripEnt->client) { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + VectorSubtract(gripOrg, gripEntOrg, gripEnt->client->ps.velocity); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 && + (!gripEnt->client || (!gripEnt->message && !(gripEnt->flags & FL_NO_KNOCKBACK)))) { // level 2 just lifts them + float gripDist = VectorNormalize(gripEnt->client->ps.velocity) / 3.0f; + if (gripDist < 20.0f) { + if (gripDist < 2.0f) { + VectorClear(gripEnt->client->ps.velocity); + } else { + VectorScale(gripEnt->client->ps.velocity, (gripDist * gripDist), gripEnt->client->ps.velocity); + } + } else { + VectorScale(gripEnt->client->ps.velocity, (gripDist * gripDist), gripEnt->client->ps.velocity); + } + } + } + // stop them from thinking + gripEnt->client->ps.pm_time = 2000; + gripEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; + if (gripEnt->NPC) { + if (!(gripEnt->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // not falling to their death + gripEnt->NPC->nextBStateThink = level.time + 2000; } - else - { - VectorScale( gripEnt->client->ps.velocity, (gripDist*gripDist), gripEnt->client->ps.velocity ); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + vectoangles(dir, angles); + gripEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW] + 180); + gripEnt->NPC->desiredPitch = -angles[PITCH]; + SaveNPCGlobals(); + SetNPCGlobals(gripEnt); + NPC_UpdateAngles(qtrue, qtrue); + gripEnt->NPC->last_ucmd.angles[0] = ucmd.angles[0]; + gripEnt->NPC->last_ucmd.angles[1] = ucmd.angles[1]; + gripEnt->NPC->last_ucmd.angles[2] = ucmd.angles[2]; + RestoreNPCGlobals(); + // FIXME: why does he turn back to his original angles once he dies or is let go? } + } else if (!gripEnt->s.number) { + // vectoangles( dir, angles ); + // gripEnt->client->ps.viewangles[0] = -angles[0]; + // gripEnt->client->ps.viewangles[1] = AngleNormalize180(angles[YAW]+180); + gripEnt->enemy = self; + NPC_SetLookTarget(gripEnt, self->s.number, level.time + 1000); } - else - { - VectorScale( gripEnt->client->ps.velocity, (gripDist*gripDist), gripEnt->client->ps.velocity ); + + gripEnt->client->ps.eFlags |= EF_FORCE_GRIPPED; + // dammit! Make sure that saber stays off! + WP_DeactivateSaber(gripEnt); + } else { // move + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); + VectorSubtract(gripOrg, gripEntOrg, gripEnt->s.pos.trDelta); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 && + (!gripEnt->client || (!gripEnt->message && !(gripEnt->flags & FL_NO_KNOCKBACK)))) { // level 2 just lifts them + VectorScale(gripEnt->s.pos.trDelta, 10, gripEnt->s.pos.trDelta); + } + gripEnt->s.pos.trType = TR_LINEAR; + gripEnt->s.pos.trTime = level.time; } - } - } - //stop them from thinking - gripEnt->client->ps.pm_time = 2000; - gripEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( gripEnt->NPC ) - { - if ( !(gripEnt->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//not falling to their death - gripEnt->NPC->nextBStateThink = level.time + 2000; - } - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - vectoangles( dir, angles ); - gripEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW]+180); - gripEnt->NPC->desiredPitch = -angles[PITCH]; - SaveNPCGlobals(); - SetNPCGlobals( gripEnt ); - NPC_UpdateAngles( qtrue, qtrue ); - gripEnt->NPC->last_ucmd.angles[0] = ucmd.angles[0]; - gripEnt->NPC->last_ucmd.angles[1] = ucmd.angles[1]; - gripEnt->NPC->last_ucmd.angles[2] = ucmd.angles[2]; - RestoreNPCGlobals(); - //FIXME: why does he turn back to his original angles once he dies or is let go? - } - } - else if ( !gripEnt->s.number ) - { - //vectoangles( dir, angles ); - //gripEnt->client->ps.viewangles[0] = -angles[0]; - //gripEnt->client->ps.viewangles[1] = AngleNormalize180(angles[YAW]+180); - gripEnt->enemy = self; - NPC_SetLookTarget( gripEnt, self->s.number, level.time+1000 ); - } - gripEnt->client->ps.eFlags |= EF_FORCE_GRIPPED; - //dammit! Make sure that saber stays off! - WP_DeactivateSaber( gripEnt ); - } - else - {//move - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); - VectorSubtract( gripOrg, gripEntOrg, gripEnt->s.pos.trDelta ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 - && (!gripEnt->client || (!gripEnt->message&&!(gripEnt->flags&FL_NO_KNOCKBACK))) ) - {//level 2 just lifts them - VectorScale( gripEnt->s.pos.trDelta, 10, gripEnt->s.pos.trDelta ); + gripEnt->s.eFlags |= EF_FORCE_GRIPPED; } - gripEnt->s.pos.trType = TR_LINEAR; - gripEnt->s.pos.trTime = level.time; - } - - gripEnt->s.eFlags |= EF_FORCE_GRIPPED; - } - //Shouldn't this be discovered? - //AddSightEvent( self, gripOrg, 128, AEL_DANGER, 20 ); - AddSightEvent( self, gripOrg, 128, AEL_DISCOVERED, 20 ); + // Shouldn't this be discovered? + // AddSightEvent( self, gripOrg, 128, AEL_DANGER, 20 ); + AddSightEvent(self, gripOrg, 128, AEL_DISCOVERED, 20); - if ( self->client->ps.forcePowerDebounce[FP_GRIP] < level.time ) - { - //GEntity_PainFunc( gripEnt, self, self, gripOrg, 0, MOD_CRUSH ); - if ( !gripEnt->client - || gripEnt->client->NPC_class != CLASS_VEHICLE - || (gripEnt->m_pVehicle - && gripEnt->m_pVehicle->m_pVehicleInfo - && gripEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) ) - {//we don't damage the empty vehicle - gripEnt->painDebounceTime = 0; - int gripDmg = forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]]; - if ( gripLevel != -1 ) - { - if ( gripLevel == 1 ) - { - gripDmg = floor((float)gripDmg/3.0f); + if (self->client->ps.forcePowerDebounce[FP_GRIP] < level.time) { + // GEntity_PainFunc( gripEnt, self, self, gripOrg, 0, MOD_CRUSH ); + if (!gripEnt->client || gripEnt->client->NPC_class != CLASS_VEHICLE || + (gripEnt->m_pVehicle && gripEnt->m_pVehicle->m_pVehicleInfo && + gripEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)) { // we don't damage the empty vehicle + gripEnt->painDebounceTime = 0; + int gripDmg = forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]]; + if (gripLevel != -1) { + if (gripLevel == 1) { + gripDmg = floor((float)gripDmg / 3.0f); + } else // if ( gripLevel == 2 ) + { + gripDmg = floor((float)gripDmg / 1.5f); + } + } + G_Damage(gripEnt, self, self, dir, gripOrg, gripDmg, DAMAGE_NO_ARMOR, MOD_CRUSH); // MOD_??? } - else //if ( gripLevel == 2 ) - { - gripDmg = floor((float)gripDmg/1.5f); + if (gripEnt->s.number) { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2) { // do damage faster at level 3 + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(150, 750); + } else { + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(250, 1000); + } + } else { // player takes damage faster + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(100, 600); } - } - G_Damage( gripEnt, self, self, dir, gripOrg, gripDmg, DAMAGE_NO_ARMOR, MOD_CRUSH );//MOD_??? - } - if ( gripEnt->s.number ) - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 ) - {//do damage faster at level 3 - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 150, 750 ); - } - else - { - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 250, 1000 ); - } - } - else - {//player takes damage faster - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 100, 600 ); - } - if ( forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]] > 0 ) - {//no damage at level 1 - WP_ForcePowerDrain( self, FP_GRIP, 3 ); - } - if ( self->client->NPC_class == CLASS_KYLE - && (self->spawnflags&1) ) - {//"Boss" Kyle - if ( gripEnt->client ) - { - if ( !Q_irand( 0, 2 ) ) - {//toss him aside! - vec3_t vRt; - AngleVectors( self->currentAngles, NULL, vRt, NULL ); - //stop gripping - TIMER_Set( self, "gripping", -level.time ); - WP_ForcePowerStop( self, FP_GRIP ); - //now toss him - if ( Q_irand( 0, 1 ) ) - {//throw him to my left - NPC_SetAnim( self, SETANIM_BOTH, BOTH_TOSS1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - VectorScale( vRt, -1500.0f, gripEnt->client->ps.velocity ); - G_Knockdown( gripEnt, self, vRt, 500, qfalse ); + if (forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]] > 0) { // no damage at level 1 + WP_ForcePowerDrain(self, FP_GRIP, 3); + } + if (self->client->NPC_class == CLASS_KYLE && (self->spawnflags & 1)) { //"Boss" Kyle + if (gripEnt->client) { + if (!Q_irand(0, 2)) { // toss him aside! + vec3_t vRt; + AngleVectors(self->currentAngles, NULL, vRt, NULL); + // stop gripping + TIMER_Set(self, "gripping", -level.time); + WP_ForcePowerStop(self, FP_GRIP); + // now toss him + if (Q_irand(0, 1)) { // throw him to my left + NPC_SetAnim(self, SETANIM_BOTH, BOTH_TOSS1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + VectorScale(vRt, -1500.0f, gripEnt->client->ps.velocity); + G_Knockdown(gripEnt, self, vRt, 500, qfalse); + } else { // throw him to my right + NPC_SetAnim(self, SETANIM_BOTH, BOTH_TOSS2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + VectorScale(vRt, 1500.0f, gripEnt->client->ps.velocity); + G_Knockdown(gripEnt, self, vRt, 500, qfalse); + } + // don't do anything for a couple seconds + self->client->ps.weaponTime = self->client->ps.torsoAnimTimer + 2000; + self->painDebounceTime = level.time + self->client->ps.weaponTime; + // stop moving + VectorClear(self->client->ps.velocity); + VectorClear(self->client->ps.moveDir); + return; + } } - else - {//throw him to my right - NPC_SetAnim( self, SETANIM_BOTH, BOTH_TOSS2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - VectorScale( vRt, 1500.0f, gripEnt->client->ps.velocity ); - G_Knockdown( gripEnt, self, vRt, 500, qfalse ); + } + } else { + // WP_ForcePowerDrain( self, FP_GRIP, 0 ); + if (!gripEnt->enemy) { + if (gripEnt->client && gripEnt->client->playerTeam == TEAM_PLAYER && self->s.number < MAX_CLIENTS && self->client && + self->client->playerTeam == TEAM_PLAYER) { // this shouldn't make allies instantly turn on you, let the damage->pain routine + // determine how allies should react to this + } else { + G_SetEnemy(gripEnt, self); } - //don't do anything for a couple seconds - self->client->ps.weaponTime = self->client->ps.torsoAnimTimer + 2000; - self->painDebounceTime = level.time + self->client->ps.weaponTime; - //stop moving - VectorClear( self->client->ps.velocity ); - VectorClear( self->client->ps.moveDir ); - return; } } - } - } - else - { - //WP_ForcePowerDrain( self, FP_GRIP, 0 ); - if ( !gripEnt->enemy ) - { - if ( gripEnt->client - && gripEnt->client->playerTeam == TEAM_PLAYER - && self->s.number < MAX_CLIENTS - && self->client - && self->client->playerTeam == TEAM_PLAYER ) - {//this shouldn't make allies instantly turn on you, let the damage->pain routine determine how allies should react to this - } - else - { - G_SetEnemy( gripEnt, self ); + if (gripEnt->client && gripEnt->health > 0) { + int anim = BOTH_CHOKE3; // left-handed choke + if (gripEnt->client->ps.weapon == WP_NONE || gripEnt->client->ps.weapon == WP_MELEE) { + anim = BOTH_CHOKE1; // two-handed choke + } + if (self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // still on ground, only set anim on torso + NPC_SetAnim(gripEnt, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // in air, set on whole body + NPC_SetAnim(gripEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + gripEnt->painDebounceTime = level.time + 2000; } } - } - if ( gripEnt->client && gripEnt->health > 0 ) - { - int anim = BOTH_CHOKE3; //left-handed choke - if ( gripEnt->client->ps.weapon == WP_NONE || gripEnt->client->ps.weapon == WP_MELEE ) - { - anim = BOTH_CHOKE1; //two-handed choke - } - if ( self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//still on ground, only set anim on torso - NPC_SetAnim( gripEnt, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//in air, set on whole body - NPC_SetAnim( gripEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - gripEnt->painDebounceTime = level.time + 2000; - } - } } break; case FP_LIGHTNING: - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//higher than level 1 - if ( cmd->buttons & BUTTON_FORCE_LIGHTNING ) - {//holding it keeps it going + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // higher than level 1 + if (cmd->buttons & BUTTON_FORCE_LIGHTNING) { // holding it keeps it going self->client->ps.forcePowerDuration[FP_LIGHTNING] = level.time + 500; - ForceLightningAnim( self ); + ForceLightningAnim(self); } } - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) ) - { - WP_ForcePowerStop( self, forcePower ); - } - else - { - ForceShootLightning( self ); - if ( self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD - || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE ) - {//jackin' 'em up, Palpatine-style - //extra cost - WP_ForcePowerDrain( self, forcePower, 0 ); + if (!WP_ForcePowerAvailable(self, forcePower, 0)) { + WP_ForcePowerStop(self, forcePower); + } else { + ForceShootLightning(self); + if (self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING || self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_START || + self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD || + self->client->ps.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_RELEASE) { // jackin' 'em up, Palpatine-style + // extra cost + WP_ForcePowerDrain(self, forcePower, 0); } - WP_ForcePowerDrain( self, forcePower, 0 ); + WP_ForcePowerDrain(self, forcePower, 0); } break; - //new Jedi Academy force powers + // new Jedi Academy force powers case FP_RAGE: - if (self->health < 1) - { + if (self->health < 1) { WP_ForcePowerStop(self, forcePower); break; } - if (self->client->ps.forceRageDrainTime < level.time) - { + if (self->client->ps.forceRageDrainTime < level.time) { int addTime = 400; self->health -= 2; - if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) - { + if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) { addTime = 100; - } - else if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) - { + } else if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) { addTime = 250; - } - else if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) - { + } else if (self->client->ps.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) { addTime = 500; } self->client->ps.forceRageDrainTime = level.time + addTime; } - if ( self->health < 1 ) - { + if (self->health < 1) { self->health = 1; - //WP_ForcePowerStop( self, forcePower ); - } - else - { + // WP_ForcePowerStop( self, forcePower ); + } else { self->client->ps.stats[STAT_HEALTH] = self->health; - speed = forceSpeedValue[self->client->ps.forcePowerLevel[FP_RAGE]-1]; - if ( !self->s.number ) - {//player using force rage - if ( !(self->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_RAGE] > self->client->ps.forcePowerLevel[FP_SPEED]+1 ) - {//either not using speed or speed is at a lower level than rage + speed = forceSpeedValue[self->client->ps.forcePowerLevel[FP_RAGE] - 1]; + if (!self->s.number) { // player using force rage + if (!(self->client->ps.forcePowersActive & (1 << FP_SPEED)) || + self->client->ps.forcePowerLevel[FP_RAGE] > + self->client->ps.forcePowerLevel[FP_SPEED] + 1) { // either not using speed or speed is at a lower level than rage gi.cvar_set("timescale", va("%4.2f", speed)); - if ( g_timescale->value > speed ) - { + if (g_timescale->value > speed) { newSpeed = g_timescale->value - 0.05; - if ( newSpeed < speed ) - { + if (newSpeed < speed) { newSpeed = speed; } gi.cvar_set("timescale", va("%4.2f", newSpeed)); @@ -13930,121 +10966,96 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } break; case FP_DRAIN: - if ( cmd->buttons & BUTTON_FORCE_DRAIN ) - {//holding it keeps it going + if (cmd->buttons & BUTTON_FORCE_DRAIN) { // holding it keeps it going self->client->ps.forcePowerDuration[FP_DRAIN] = level.time + 500; } - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) ) - {//no more force power, stop - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forceDrainEntityNum >= 0 && self->client->ps.forceDrainEntityNum < ENTITYNUM_WORLD ) - {//holding someone - if ( !WP_ForcePowerAvailable( self, FP_DRAIN, 0 ) - || (self->client->ps.forcePowerLevel[FP_DRAIN]>FORCE_LEVEL_1 - && !self->s.number - && !(cmd->buttons&BUTTON_FORCE_DRAIN) - && self->client->ps.forcePowerDuration[FP_DRAIN]client->ps.forceDrainEntityNum >= 0 && self->client->ps.forceDrainEntityNum < ENTITYNUM_WORLD) { // holding someone + if (!WP_ForcePowerAvailable(self, FP_DRAIN, 0) || + (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 && !self->s.number && !(cmd->buttons & BUTTON_FORCE_DRAIN) && + self->client->ps.forcePowerDuration[FP_DRAIN] < level.time)) { + WP_ForcePowerStop(self, FP_DRAIN); return; - } - else - { + } else { drainEnt = &g_entities[self->client->ps.forceDrainEntityNum]; - if ( !drainEnt ) - {//invalid ent - WP_ForcePowerStop( self, FP_DRAIN ); + if (!drainEnt) { // invalid ent + WP_ForcePowerStop(self, FP_DRAIN); return; - } - else if ( (drainEnt->health <= 0&&drainEnt->takedamage) )//FIXME: what about things that never had health or lose takedamage when they die? - {//dead ent - WP_ForcePowerStop( self, FP_DRAIN ); + } else if ((drainEnt->health <= 0 && drainEnt->takedamage)) // FIXME: what about things that never had health or lose takedamage when they die? + { // dead ent + WP_ForcePowerStop(self, FP_DRAIN); return; - } - else if ( drainEnt->client && drainEnt->client->moveType == MT_FLYSWIM && VectorLengthSquared( NPC->client->ps.velocity ) > (300*300) ) - {//flying creature broke free - WP_ForcePowerStop( self, FP_DRAIN ); + } else if (drainEnt->client && drainEnt->client->moveType == MT_FLYSWIM && + VectorLengthSquared(NPC->client->ps.velocity) > (300 * 300)) { // flying creature broke free + WP_ForcePowerStop(self, FP_DRAIN); return; - } - else if ( drainEnt->client - && drainEnt->health>0 //dead dudes don't fly - && (drainEnt->client->NPC_class == CLASS_BOBAFETT || drainEnt->client->NPC_class == CLASS_ROCKETTROOPER) - && self->client->ps.forcePowerDebounce[FP_DRAIN] < level.time - && !Q_irand( 0, 10 ) ) - {//boba fett - fly away! - drainEnt->client->ps.forceJumpCharge = 0;//so we don't play the force flip anim + } else if (drainEnt->client && drainEnt->health > 0 // dead dudes don't fly + && (drainEnt->client->NPC_class == CLASS_BOBAFETT || drainEnt->client->NPC_class == CLASS_ROCKETTROOPER) && + self->client->ps.forcePowerDebounce[FP_DRAIN] < level.time && !Q_irand(0, 10)) { // boba fett - fly away! + drainEnt->client->ps.forceJumpCharge = 0; // so we don't play the force flip anim drainEnt->client->ps.velocity[2] = 250; - drainEnt->client->ps.forceJumpZStart = drainEnt->currentOrigin[2];//so we don't take damage if we land at same height + drainEnt->client->ps.forceJumpZStart = drainEnt->currentOrigin[2]; // so we don't take damage if we land at same height drainEnt->client->ps.pm_flags |= PMF_JUMPING; - G_AddEvent( drainEnt, EV_JUMP, 0 ); - JET_FlyStart( drainEnt ); - WP_ForcePowerStop( self, FP_DRAIN ); + G_AddEvent(drainEnt, EV_JUMP, 0); + JET_FlyStart(drainEnt); + WP_ForcePowerStop(self, FP_DRAIN); return; - } - else if ( drainEnt->NPC - && drainEnt->client - && drainEnt->client->ps.forcePowersKnown - && (drainEnt->client->NPC_class==CLASS_REBORN||drainEnt->client->ps.weapon==WP_SABER) - && !Jedi_CultistDestroyer(drainEnt) - && level.time-(self->client->ps.forcePowerDebounce[FP_DRAIN]>self->client->ps.forcePowerLevel[FP_DRAIN]*500)//at level 1, I always get at least 500ms of drain, at level 3 I get 1500ms - && !Q_irand( 0, 100-(drainEnt->NPC->stats.evasion*8)-(g_spskill->integer*15) ) ) - {//a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? - WP_ForceForceThrow( drainEnt ); - //FIXME: I need to go into some pushed back anim... - WP_ForcePowerStop( self, FP_DRAIN ); - //can't drain again for 2 seconds + } else if (drainEnt->NPC && drainEnt->client && drainEnt->client->ps.forcePowersKnown && + (drainEnt->client->NPC_class == CLASS_REBORN || drainEnt->client->ps.weapon == WP_SABER) && !Jedi_CultistDestroyer(drainEnt) && + level.time - + (self->client->ps.forcePowerDebounce[FP_DRAIN] > + self->client->ps.forcePowerLevel[FP_DRAIN] * 500) // at level 1, I always get at least 500ms of drain, at level 3 I get 1500ms + && + !Q_irand(0, 100 - (drainEnt->NPC->stats.evasion * 8) - + (g_spskill->integer * 15))) { // a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? + WP_ForceForceThrow(drainEnt); + // FIXME: I need to go into some pushed back anim... + WP_ForcePowerStop(self, FP_DRAIN); + // can't drain again for 2 seconds self->client->ps.forcePowerDebounce[FP_DRAIN] = level.time + 4000; return; - } - else - { + } else { /* - int drainLevel = WP_AbsorbConversion( drainEnt, drainEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.forcePowerLevel[FP_DRAIN], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]] ); - if ( !drainLevel ) + int drainLevel = WP_AbsorbConversion( drainEnt, drainEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, + self->client->ps.forcePowerLevel[FP_DRAIN], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]] ); if ( !drainLevel ) { WP_ForcePowerStop( self, forcePower ); return; } */ - //NPC_SetAnim( self, SETANIM_BOTH, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->client->ps.torsoAnim != BOTH_FORCE_DRAIN_GRAB_START - || !self->client->ps.torsoAnimTimer ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // NPC_SetAnim( self, SETANIM_BOTH, BOTH_HUGGER1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim != BOTH_FORCE_DRAIN_GRAB_START || !self->client->ps.torsoAnimTimer) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRAB_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->handLBolt != -1 ) - { - G_PlayEffect( G_EffectIndex( "force/drain_hand" ), self->playerModel, self->handLBolt, self->s.number, self->currentOrigin, 200, qtrue ); + if (self->handLBolt != -1) { + G_PlayEffect(G_EffectIndex("force/drain_hand"), self->playerModel, self->handLBolt, self->s.number, self->currentOrigin, 200, qtrue); } - if ( self->handRBolt != -1 ) - { - G_PlayEffect( G_EffectIndex( "force/drain_hand" ), self->playerModel, self->handRBolt, self->s.number, self->currentOrigin, 200, qtrue ); + if (self->handRBolt != -1) { + G_PlayEffect(G_EffectIndex("force/drain_hand"), self->playerModel, self->handRBolt, self->s.number, self->currentOrigin, 200, qtrue); } - //how far are they - dist = Distance( self->client->renderInfo.eyePoint, drainEnt->currentOrigin ); - if ( DistanceSquared( drainEnt->currentOrigin, self->currentOrigin ) > FORCE_DRAIN_DIST_SQUARED ) - {//must be close, got away somehow! - WP_ForcePowerStop( self, FP_DRAIN ); + // how far are they + dist = Distance(self->client->renderInfo.eyePoint, drainEnt->currentOrigin); + if (DistanceSquared(drainEnt->currentOrigin, self->currentOrigin) > FORCE_DRAIN_DIST_SQUARED) { // must be close, got away somehow! + WP_ForcePowerStop(self, FP_DRAIN); return; } - //keep my saber off! - WP_DeactivateSaber( self, qtrue ); - if ( drainEnt->client ) - { - //now move them - VectorCopy( self->client->ps.viewangles, angles ); + // keep my saber off! + WP_DeactivateSaber(self, qtrue); + if (drainEnt->client) { + // now move them + VectorCopy(self->client->ps.viewangles, angles); angles[0] = 0; - AngleVectors( angles, dir, NULL, NULL ); + AngleVectors(angles, dir, NULL, NULL); /* VectorMA( self->currentOrigin, self->maxs[0], dir, drainEnt->client->ps.forceDrainOrg ); trace_t trace; - gi.trace( &trace, drainEnt->currentOrigin, drainEnt->mins, drainEnt->maxs, drainEnt->client->ps.forceDrainOrg, drainEnt->s.number, drainEnt->clipmask ); - if ( !trace.startsolid && !trace.allsolid ) + gi.trace( &trace, drainEnt->currentOrigin, drainEnt->mins, drainEnt->maxs, drainEnt->client->ps.forceDrainOrg, drainEnt->s.number, + drainEnt->clipmask ); if ( !trace.startsolid && !trace.allsolid ) { G_SetOrigin( drainEnt, trace.endpos ); gi.linkentity( drainEnt ); @@ -14052,97 +11063,75 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } VectorMA( self->currentOrigin, self->maxs[0]*0.5f, dir, drainEnt->client->ps.forceDrainOrg ); */ - //stop them from thinking + // stop them from thinking drainEnt->client->ps.pm_time = 2000; drainEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( drainEnt->NPC ) - { - if ( !(drainEnt->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//not falling to their death + if (drainEnt->NPC) { + if (!(drainEnt->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // not falling to their death drainEnt->NPC->nextBStateThink = level.time + 2000; } - vectoangles( dir, angles ); - drainEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW]+180); + vectoangles(dir, angles); + drainEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW] + 180); drainEnt->NPC->desiredPitch = -angles[PITCH]; SaveNPCGlobals(); - SetNPCGlobals( drainEnt ); - NPC_UpdateAngles( qtrue, qtrue ); + SetNPCGlobals(drainEnt); + NPC_UpdateAngles(qtrue, qtrue); drainEnt->NPC->last_ucmd.angles[0] = ucmd.angles[0]; drainEnt->NPC->last_ucmd.angles[1] = ucmd.angles[1]; drainEnt->NPC->last_ucmd.angles[2] = ucmd.angles[2]; RestoreNPCGlobals(); - //FIXME: why does he turn back to his original angles once he dies or is let go? - } - else if ( !drainEnt->s.number ) - { + // FIXME: why does he turn back to his original angles once he dies or is let go? + } else if (!drainEnt->s.number) { drainEnt->enemy = self; - NPC_SetLookTarget( drainEnt, self->s.number, level.time+1000 ); + NPC_SetLookTarget(drainEnt, self->s.number, level.time + 1000); } drainEnt->client->ps.eFlags |= EF_FORCE_DRAINED; - //dammit! Make sure that saber stays off! - WP_DeactivateSaber( drainEnt, qtrue ); + // dammit! Make sure that saber stays off! + WP_DeactivateSaber(drainEnt, qtrue); } - //Shouldn't this be discovered? - AddSightEvent( self, drainEnt->currentOrigin, 128, AEL_DISCOVERED, 20 ); + // Shouldn't this be discovered? + AddSightEvent(self, drainEnt->currentOrigin, 128, AEL_DISCOVERED, 20); - if ( self->client->ps.forcePowerDebounce[FP_DRAIN] < level.time ) - { - int drainLevel = WP_AbsorbConversion( drainEnt, drainEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.forcePowerLevel[FP_DRAIN], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]] ); - if ( (drainLevel && drainLevel == -1) - || Q_irand( drainLevel, 3 ) < 3 ) - {//the drain is being absorbed - ForceDrainEnt( self, drainEnt ); + if (self->client->ps.forcePowerDebounce[FP_DRAIN] < level.time) { + int drainLevel = + WP_AbsorbConversion(drainEnt, drainEnt->client->ps.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, + self->client->ps.forcePowerLevel[FP_DRAIN], forcePowerNeeded[self->client->ps.forcePowerLevel[FP_DRAIN]]); + if ((drainLevel && drainLevel == -1) || Q_irand(drainLevel, 3) < 3) { // the drain is being absorbed + ForceDrainEnt(self, drainEnt); } - WP_ForcePowerDrain( self, FP_DRAIN, 3 ); - } - else - { - if ( !Q_irand( 0, 4 ) ) - { - WP_ForcePowerDrain( self, FP_DRAIN, 1 ); + WP_ForcePowerDrain(self, FP_DRAIN, 3); + } else { + if (!Q_irand(0, 4)) { + WP_ForcePowerDrain(self, FP_DRAIN, 1); } - if ( !drainEnt->enemy ) - { - G_SetEnemy( drainEnt, self ); + if (!drainEnt->enemy) { + G_SetEnemy(drainEnt, self); } } - if ( drainEnt->health > 0 ) - {//still alive - //NPC_SetAnim( drainEnt, SETANIM_BOTH, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC_SetAnim( drainEnt, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRABBED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (drainEnt->health > 0) { // still alive + // NPC_SetAnim( drainEnt, SETANIM_BOTH, BOTH_HUGGEE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(drainEnt, SETANIM_BOTH, BOTH_FORCE_DRAIN_GRABBED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } - } - else if ( self->client->ps.forcePowerLevel[forcePower] > FORCE_LEVEL_1 ) - {//regular distance-drain - if ( cmd->buttons & BUTTON_FORCE_DRAIN ) - {//holding it keeps it going + } else if (self->client->ps.forcePowerLevel[forcePower] > FORCE_LEVEL_1) { // regular distance-drain + if (cmd->buttons & BUTTON_FORCE_DRAIN) { // holding it keeps it going self->client->ps.forcePowerDuration[FP_DRAIN] = level.time + 500; - if ( self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_START ) - { - if ( !self->client->ps.torsoAnimTimer ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_DRAIN_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_DRAIN_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCE_DRAIN_START) { + if (!self->client->ps.torsoAnimTimer) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_DRAIN_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_DRAIN_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCE_DRAIN_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCE_DRAIN_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) ) - { - WP_ForcePowerStop( self, forcePower ); - } - else - { - ForceShootDrain( self ); + if (!WP_ForcePowerAvailable(self, forcePower, 0)) { + WP_ForcePowerStop(self, forcePower); + } else { + ForceShootDrain(self); } } break; @@ -14157,245 +11146,204 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } } -void WP_CheckForcedPowers( gentity_t *self, usercmd_t *ucmd ) -{ - for ( int forcePower = FP_FIRST; forcePower < NUM_FORCE_POWERS; forcePower++ ) - { - if ( (self->client->ps.forcePowersForced&(1<client->ps.forcePowersForced & (1 << forcePower))) { + switch (forcePower) { case FP_HEAL: - ForceHeal( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_LEVITATION: - //nothing + // nothing break; case FP_SPEED: - ForceSpeed( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_PUSH: - ForceThrow( self, qfalse ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_PULL: - ForceThrow( self, qtrue ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_TELEPATHY: - //FIXME: target at enemy? - ForceTelepathy( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_GRIP: - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS|BUTTON_FORCE_DRAIN|BUTTON_FORCE_LIGHTNING); + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS | BUTTON_FORCE_DRAIN | BUTTON_FORCE_LIGHTNING); ucmd->buttons |= BUTTON_FORCEGRIP; - //holds until cleared + // holds until cleared break; case FP_LIGHTNING: - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS|BUTTON_FORCEGRIP|BUTTON_FORCE_DRAIN); + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS | BUTTON_FORCEGRIP | BUTTON_FORCE_DRAIN); ucmd->buttons |= BUTTON_FORCE_LIGHTNING; - //holds until cleared + // holds until cleared break; case FP_SABERTHROW: - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_FORCE_FOCUS|BUTTON_FORCEGRIP|BUTTON_FORCE_DRAIN|BUTTON_FORCE_LIGHTNING); + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_FORCE_FOCUS | BUTTON_FORCEGRIP | BUTTON_FORCE_DRAIN | BUTTON_FORCE_LIGHTNING); ucmd->buttons |= BUTTON_ALT_ATTACK; - //holds until cleared? + // holds until cleared? break; case FP_SABER_DEFENSE: - //nothing + // nothing break; case FP_SABER_OFFENSE: - //nothing + // nothing break; case FP_RAGE: - ForceRage( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_PROTECT: - ForceProtect( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_ABSORB: - ForceAbsorb( self ); - //do only once - self->client->ps.forcePowersForced &= ~(1<client->ps.forcePowersForced &= ~(1 << forcePower); break; case FP_DRAIN: - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK|BUTTON_FORCE_FOCUS|BUTTON_FORCEGRIP|BUTTON_FORCE_LIGHTNING); + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK | BUTTON_FORCE_FOCUS | BUTTON_FORCEGRIP | BUTTON_FORCE_LIGHTNING); ucmd->buttons |= BUTTON_FORCE_DRAIN; - //holds until cleared + // holds until cleared break; case FP_SEE: - //nothing + // nothing break; } } } } -void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) -{ - qboolean usingForce = qfalse; - int i; - //see if any force powers are running - if ( !self ) - { +void WP_ForcePowersUpdate(gentity_t *self, usercmd_t *ucmd) { + qboolean usingForce = qfalse; + int i; + // see if any force powers are running + if (!self) { return; } - if ( !self->client ) - { + if (!self->client) { return; } - if ( self->health <= 0 ) - {//if dead, deactivate any active force powers - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.forcePowerDuration[i] || (self->client->ps.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerStop( self, (forcePowers_t)i ); + if (self->health <= 0) { // if dead, deactivate any active force powers + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.forcePowerDuration[i] || (self->client->ps.forcePowersActive & (1 << i))) { + WP_ForcePowerStop(self, (forcePowers_t)i); self->client->ps.forcePowerDuration[i] = 0; } } return; } - WP_CheckForcedPowers( self, ucmd ); + WP_CheckForcedPowers(self, ucmd); - if ( !self->s.number ) - {//player uses different kind of force-jump - } - else - { + if (!self->s.number) { // player uses different kind of force-jump + } else { /* if ( ucmd->buttons & BUTTON_FORCEJUMP ) {//just charging up ForceJumpCharge( self, ucmd ); } else */ - if ( self->client->ps.forceJumpCharge ) - {//let go of charge button, have charge - //if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE - && !PM_SwimmingAnim( self->client->ps.legsAnim ) ) - {//FIXME: stop sound? - //self->client->ps.forceJumpCharge = 0; - //FIXME: actually, we want this to still be cleared... don't clear it if the button isn't being pressed, but clear it if not holding button and not on ground. - } - else - {//still on ground, so jump - ForceJump( self, ucmd ); + if (self->client->ps.forceJumpCharge) { // let go of charge button, have charge + // if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE && + !PM_SwimmingAnim(self->client->ps.legsAnim)) { // FIXME: stop sound? + // self->client->ps.forceJumpCharge = 0; + // FIXME: actually, we want this to still be cleared... don't clear it if the button isn't being + // pressed, but clear it if not holding button and not on ground. + } else { // still on ground, so jump + ForceJump(self, ucmd); return; } } } - if ( ucmd->buttons & BUTTON_FORCEGRIP ) - { - ForceGrip( self ); + if (ucmd->buttons & BUTTON_FORCEGRIP) { + ForceGrip(self); } - if ( !self->s.number - && self->client->NPC_class == CLASS_BOBAFETT ) - {//Boba Fett - if ( ucmd->buttons & BUTTON_FORCE_LIGHTNING ) - {//start flamethrower - Boba_DoFlameThrower( self ); + if (!self->s.number && self->client->NPC_class == CLASS_BOBAFETT) { // Boba Fett + if (ucmd->buttons & BUTTON_FORCE_LIGHTNING) { // start flamethrower + Boba_DoFlameThrower(self); return; - } - else if ( self->client->ps.forcePowerDuration[FP_LIGHTNING] ) - { + } else if (self->client->ps.forcePowerDuration[FP_LIGHTNING]) { self->client->ps.forcePowerDuration[FP_LIGHTNING] = 0; - Boba_StopFlameThrower( self ); + Boba_StopFlameThrower(self); return; } - } - else if ( ucmd->buttons & BUTTON_FORCE_LIGHTNING ) - { - ForceLightning( self ); + } else if (ucmd->buttons & BUTTON_FORCE_LIGHTNING) { + ForceLightning(self); } - if ( ucmd->buttons & BUTTON_FORCE_DRAIN ) - { - if ( !ForceDrain2( self ) ) - {//can't drain-grip someone right in front - if ( self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 ) - {//try ranged - ForceDrain( self, qtrue ); + if (ucmd->buttons & BUTTON_FORCE_DRAIN) { + if (!ForceDrain2(self)) { // can't drain-grip someone right in front + if (self->client->ps.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1) { // try ranged + ForceDrain(self, qtrue); } } } - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.forcePowerDuration[i] ) - { - if ( self->client->ps.forcePowerDuration[i] < level.time ) - { - if ( (self->client->ps.forcePowersActive&( 1 << i )) ) - {//turn it off - WP_ForcePowerStop( self, (forcePowers_t)i ); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.forcePowerDuration[i]) { + if (self->client->ps.forcePowerDuration[i] < level.time) { + if ((self->client->ps.forcePowersActive & (1 << i))) { // turn it off + WP_ForcePowerStop(self, (forcePowers_t)i); } self->client->ps.forcePowerDuration[i] = 0; } } - if ( (self->client->ps.forcePowersActive&( 1 << i )) ) - { + if ((self->client->ps.forcePowersActive & (1 << i))) { usingForce = qtrue; - WP_ForcePowerRun( self, (forcePowers_t)i, ucmd ); + WP_ForcePowerRun(self, (forcePowers_t)i, ucmd); } } - if ( self->client->ps.saberInFlight ) - {//don't regen force power while throwing saber - if ( self->client->ps.saberEntityNum < ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[self->client->ps.saberEntityNum] != NULL && g_entities[self->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR ) - {//fell to the ground and we're trying to pull it back + if (self->client->ps.saberInFlight) { // don't regen force power while throwing saber + if (self->client->ps.saberEntityNum < ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0) // player is 0 + { // + if (&g_entities[self->client->ps.saberEntityNum] != NULL && + g_entities[self->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR) { // fell to the ground and we're trying to pull it back usingForce = qtrue; } } } - if ( PM_ForceUsingSaberAnim( self->client->ps.torsoAnim ) ) - { + if (PM_ForceUsingSaberAnim(self->client->ps.torsoAnim)) { usingForce = qtrue; } - if ( !usingForce ) - {//when not using the force, regenerate at 10 points per second - if ( self->client->ps.forcePowerRegenDebounceTime < level.time ) - { - WP_ForcePowerRegenerate( self, self->client->ps.forcePowerRegenAmount ); + if (!usingForce) { // when not using the force, regenerate at 10 points per second + if (self->client->ps.forcePowerRegenDebounceTime < level.time) { + WP_ForcePowerRegenerate(self, self->client->ps.forcePowerRegenAmount); self->client->ps.forcePowerRegenDebounceTime = level.time + self->client->ps.forcePowerRegenRate; - if ( self->client->ps.forceRageRecoveryTime >= level.time ) - {//regen half as fast + if (self->client->ps.forceRageRecoveryTime >= level.time) { // regen half as fast self->client->ps.forcePowerRegenDebounceTime += self->client->ps.forcePowerRegenRate; } } } } -void WP_InitForcePowers( gentity_t *ent ) -{ - if ( !ent || !ent->client ) - { +void WP_InitForcePowers(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if ( !ent->client->ps.forcePowerMax ) - { + if (!ent->client->ps.forcePowerMax) { ent->client->ps.forcePowerMax = FORCE_POWER_MAX; } - if ( !ent->client->ps.forcePowerRegenRate ) - { + if (!ent->client->ps.forcePowerRegenRate) { ent->client->ps.forcePowerRegenRate = 100; } ent->client->ps.forcePower = ent->client->ps.forcePowerMax; @@ -14406,16 +11354,15 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forceDrainTime = 0; ent->client->ps.pullAttackTime = 0; - if ( ent->s.number < MAX_CLIENTS ) - {//player - if ( !g_cheats->integer )//devmaps give you all the FP + if (ent->s.number < MAX_CLIENTS) { // player + if (!g_cheats->integer) // devmaps give you all the FP { ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; - } - else - { - ent->client->ps.forcePowersKnown = ( 1 << FP_HEAL )|( 1 << FP_LEVITATION )|( 1 << FP_SPEED )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_TELEPATHY )|( 1 << FP_GRIP )|( 1 << FP_LIGHTNING)|( 1 << FP_SABERTHROW)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE )|( 1<< FP_RAGE )|( 1<< FP_DRAIN )|( 1<< FP_PROTECT )|( 1<< FP_ABSORB )|( 1<< FP_SEE ); + } else { + ent->client->ps.forcePowersKnown = (1 << FP_HEAL) | (1 << FP_LEVITATION) | (1 << FP_SPEED) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_TELEPATHY) | + (1 << FP_GRIP) | (1 << FP_LIGHTNING) | (1 << FP_SABERTHROW) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE) | + (1 << FP_RAGE) | (1 << FP_DRAIN) | (1 << FP_PROTECT) | (1 << FP_ABSORB) | (1 << FP_SEE); ent->client->ps.forcePowerLevel[FP_HEAL] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_1; @@ -14438,15 +11385,12 @@ void WP_InitForcePowers( gentity_t *ent ) } } -bool WP_DoingMoronicForcedAnimationForForcePowers(gentity_t *ent) -{ +bool WP_DoingMoronicForcedAnimationForForcePowers(gentity_t *ent) { // :P --eez - if( !ent->client ) return false; - if( ent->client->ps.legsAnim == BOTH_FORCE_ABSORB_START || - ent->client->ps.legsAnim == BOTH_FORCE_ABSORB_END || - ent->client->ps.legsAnim == BOTH_FORCE_ABSORB || - ent->client->ps.torsoAnim == BOTH_FORCE_RAGE || - ent->client->ps.legsAnim == BOTH_FORCE_PROTECT ) + if (!ent->client) + return false; + if (ent->client->ps.legsAnim == BOTH_FORCE_ABSORB_START || ent->client->ps.legsAnim == BOTH_FORCE_ABSORB_END || + ent->client->ps.legsAnim == BOTH_FORCE_ABSORB || ent->client->ps.torsoAnim == BOTH_FORCE_RAGE || ent->client->ps.legsAnim == BOTH_FORCE_PROTECT) return true; return false; } diff --git a/code/game/wp_saberLoad.cpp b/code/game/wp_saberLoad.cpp index 1b89f34b8f..2b8cc80875 100644 --- a/code/game/wp_saberLoad.cpp +++ b/code/game/wp_saberLoad.cpp @@ -20,38 +20,34 @@ along with this program; if not, see . =========================================================================== */ -//wp_saberLoad.cpp +// wp_saberLoad.cpp #include "../qcommon/q_shared.h" #include "g_local.h" #include "wp_saber.h" #include "../cgame/cg_local.h" -extern qboolean G_ParseLiteral( const char **data, const char *string ); -extern saber_colors_t TranslateSaberColor( const char *name ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInAttack( int move ); +extern qboolean G_ParseLiteral(const char **data, const char *string); +extern saber_colors_t TranslateSaberColor(const char *name); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInAttack(int move); extern stringID_table_t FPTable[]; -#define MAX_SABER_DATA_SIZE (1024*1024) // 1mb, was 512kb -char SaberParms[MAX_SABER_DATA_SIZE]; +#define MAX_SABER_DATA_SIZE (1024 * 1024) // 1mb, was 512kb +char SaberParms[MAX_SABER_DATA_SIZE]; -void Saber_SithSwordPrecache( void ) -{//*SIGH* special sounds used by the sith sword +void Saber_SithSwordPrecache(void) { //*SIGH* special sounds used by the sith sword int i; - for ( i = 1; i < 5; i++ ) - { - G_SoundIndex( va( "sound/weapons/sword/stab%d.wav", i ) ); + for (i = 1; i < 5; i++) { + G_SoundIndex(va("sound/weapons/sword/stab%d.wav", i)); } - for ( i = 1; i < 5; i++ ) - { - G_SoundIndex( va( "sound/weapons/sword/swing%d.wav", i ) ); + for (i = 1; i < 5; i++) { + G_SoundIndex(va("sound/weapons/sword/swing%d.wav", i)); } - for ( i = 1; i < 7; i++ ) - { - G_SoundIndex( va( "sound/weapons/sword/fall%d.wav", i ) ); + for (i = 1; i < 7; i++) { + G_SoundIndex(va("sound/weapons/sword/fall%d.wav", i)); } /* for ( i = 1; i < 4; i++ ) @@ -61,203 +57,177 @@ void Saber_SithSwordPrecache( void ) */ } -stringID_table_t SaberTable[] = -{ - ENUM2STRING(SABER_NONE), - ENUM2STRING(SABER_SINGLE), - ENUM2STRING(SABER_STAFF), - ENUM2STRING(SABER_BROAD), - ENUM2STRING(SABER_PRONG), - ENUM2STRING(SABER_DAGGER), - ENUM2STRING(SABER_ARC), - ENUM2STRING(SABER_SAI), - ENUM2STRING(SABER_CLAW), - ENUM2STRING(SABER_LANCE), - ENUM2STRING(SABER_STAR), - ENUM2STRING(SABER_TRIDENT), - ENUM2STRING(SABER_SITH_SWORD), - { "", -1 } -}; - -stringID_table_t SaberMoveTable[] = -{ - ENUM2STRING(LS_NONE), - // Attacks - ENUM2STRING(LS_A_TL2BR), - ENUM2STRING(LS_A_L2R), - ENUM2STRING(LS_A_BL2TR), - ENUM2STRING(LS_A_BR2TL), - ENUM2STRING(LS_A_R2L), - ENUM2STRING(LS_A_TR2BL), - ENUM2STRING(LS_A_T2B), - ENUM2STRING(LS_A_BACKSTAB), - ENUM2STRING(LS_A_BACK), - ENUM2STRING(LS_A_BACK_CR), - ENUM2STRING(LS_ROLL_STAB), - ENUM2STRING(LS_A_LUNGE), - ENUM2STRING(LS_A_JUMP_T__B_), - ENUM2STRING(LS_A_FLIP_STAB), - ENUM2STRING(LS_A_FLIP_SLASH), - ENUM2STRING(LS_JUMPATTACK_DUAL), - ENUM2STRING(LS_JUMPATTACK_ARIAL_LEFT), - ENUM2STRING(LS_JUMPATTACK_ARIAL_RIGHT), - ENUM2STRING(LS_JUMPATTACK_CART_LEFT), - ENUM2STRING(LS_JUMPATTACK_CART_RIGHT), - ENUM2STRING(LS_JUMPATTACK_STAFF_LEFT), - ENUM2STRING(LS_JUMPATTACK_STAFF_RIGHT), - ENUM2STRING(LS_BUTTERFLY_LEFT), - ENUM2STRING(LS_BUTTERFLY_RIGHT), - ENUM2STRING(LS_A_BACKFLIP_ATK), - ENUM2STRING(LS_SPINATTACK_DUAL), - ENUM2STRING(LS_SPINATTACK), - ENUM2STRING(LS_LEAP_ATTACK), - ENUM2STRING(LS_SWOOP_ATTACK_RIGHT), - ENUM2STRING(LS_SWOOP_ATTACK_LEFT), - ENUM2STRING(LS_TAUNTAUN_ATTACK_RIGHT), - ENUM2STRING(LS_TAUNTAUN_ATTACK_LEFT), - ENUM2STRING(LS_KICK_F), - ENUM2STRING(LS_KICK_B), - ENUM2STRING(LS_KICK_R), - ENUM2STRING(LS_KICK_L), - ENUM2STRING(LS_KICK_S), - ENUM2STRING(LS_KICK_BF), - ENUM2STRING(LS_KICK_RL), - ENUM2STRING(LS_KICK_F_AIR), - ENUM2STRING(LS_KICK_B_AIR), - ENUM2STRING(LS_KICK_R_AIR), - ENUM2STRING(LS_KICK_L_AIR), - ENUM2STRING(LS_STABDOWN), - ENUM2STRING(LS_STABDOWN_STAFF), - ENUM2STRING(LS_STABDOWN_DUAL), - ENUM2STRING(LS_DUAL_SPIN_PROTECT), - ENUM2STRING(LS_STAFF_SOULCAL), - ENUM2STRING(LS_A1_SPECIAL), - ENUM2STRING(LS_A2_SPECIAL), - ENUM2STRING(LS_A3_SPECIAL), - ENUM2STRING(LS_UPSIDE_DOWN_ATTACK), - ENUM2STRING(LS_PULL_ATTACK_STAB), - ENUM2STRING(LS_PULL_ATTACK_SWING), - ENUM2STRING(LS_SPINATTACK_ALORA), - ENUM2STRING(LS_DUAL_FB), - ENUM2STRING(LS_DUAL_LR), - ENUM2STRING(LS_HILT_BASH), - { "", -1 } -}; - - -saber_styles_t TranslateSaberStyle( const char *name ) { - if ( !Q_stricmp( name, "fast" ) ) return SS_FAST; - if ( !Q_stricmp( name, "medium" ) ) return SS_MEDIUM; - if ( !Q_stricmp( name, "strong" ) ) return SS_STRONG; - if ( !Q_stricmp( name, "desann" ) ) return SS_DESANN; - if ( !Q_stricmp( name, "tavion" ) ) return SS_TAVION; - if ( !Q_stricmp( name, "dual" ) ) return SS_DUAL; - if ( !Q_stricmp( name, "staff" ) ) return SS_STAFF; +stringID_table_t SaberTable[] = {ENUM2STRING(SABER_NONE), ENUM2STRING(SABER_SINGLE), + ENUM2STRING(SABER_STAFF), ENUM2STRING(SABER_BROAD), + ENUM2STRING(SABER_PRONG), ENUM2STRING(SABER_DAGGER), + ENUM2STRING(SABER_ARC), ENUM2STRING(SABER_SAI), + ENUM2STRING(SABER_CLAW), ENUM2STRING(SABER_LANCE), + ENUM2STRING(SABER_STAR), ENUM2STRING(SABER_TRIDENT), + ENUM2STRING(SABER_SITH_SWORD), {"", -1}}; + +stringID_table_t SaberMoveTable[] = {ENUM2STRING(LS_NONE), + // Attacks + ENUM2STRING(LS_A_TL2BR), + ENUM2STRING(LS_A_L2R), + ENUM2STRING(LS_A_BL2TR), + ENUM2STRING(LS_A_BR2TL), + ENUM2STRING(LS_A_R2L), + ENUM2STRING(LS_A_TR2BL), + ENUM2STRING(LS_A_T2B), + ENUM2STRING(LS_A_BACKSTAB), + ENUM2STRING(LS_A_BACK), + ENUM2STRING(LS_A_BACK_CR), + ENUM2STRING(LS_ROLL_STAB), + ENUM2STRING(LS_A_LUNGE), + ENUM2STRING(LS_A_JUMP_T__B_), + ENUM2STRING(LS_A_FLIP_STAB), + ENUM2STRING(LS_A_FLIP_SLASH), + ENUM2STRING(LS_JUMPATTACK_DUAL), + ENUM2STRING(LS_JUMPATTACK_ARIAL_LEFT), + ENUM2STRING(LS_JUMPATTACK_ARIAL_RIGHT), + ENUM2STRING(LS_JUMPATTACK_CART_LEFT), + ENUM2STRING(LS_JUMPATTACK_CART_RIGHT), + ENUM2STRING(LS_JUMPATTACK_STAFF_LEFT), + ENUM2STRING(LS_JUMPATTACK_STAFF_RIGHT), + ENUM2STRING(LS_BUTTERFLY_LEFT), + ENUM2STRING(LS_BUTTERFLY_RIGHT), + ENUM2STRING(LS_A_BACKFLIP_ATK), + ENUM2STRING(LS_SPINATTACK_DUAL), + ENUM2STRING(LS_SPINATTACK), + ENUM2STRING(LS_LEAP_ATTACK), + ENUM2STRING(LS_SWOOP_ATTACK_RIGHT), + ENUM2STRING(LS_SWOOP_ATTACK_LEFT), + ENUM2STRING(LS_TAUNTAUN_ATTACK_RIGHT), + ENUM2STRING(LS_TAUNTAUN_ATTACK_LEFT), + ENUM2STRING(LS_KICK_F), + ENUM2STRING(LS_KICK_B), + ENUM2STRING(LS_KICK_R), + ENUM2STRING(LS_KICK_L), + ENUM2STRING(LS_KICK_S), + ENUM2STRING(LS_KICK_BF), + ENUM2STRING(LS_KICK_RL), + ENUM2STRING(LS_KICK_F_AIR), + ENUM2STRING(LS_KICK_B_AIR), + ENUM2STRING(LS_KICK_R_AIR), + ENUM2STRING(LS_KICK_L_AIR), + ENUM2STRING(LS_STABDOWN), + ENUM2STRING(LS_STABDOWN_STAFF), + ENUM2STRING(LS_STABDOWN_DUAL), + ENUM2STRING(LS_DUAL_SPIN_PROTECT), + ENUM2STRING(LS_STAFF_SOULCAL), + ENUM2STRING(LS_A1_SPECIAL), + ENUM2STRING(LS_A2_SPECIAL), + ENUM2STRING(LS_A3_SPECIAL), + ENUM2STRING(LS_UPSIDE_DOWN_ATTACK), + ENUM2STRING(LS_PULL_ATTACK_STAB), + ENUM2STRING(LS_PULL_ATTACK_SWING), + ENUM2STRING(LS_SPINATTACK_ALORA), + ENUM2STRING(LS_DUAL_FB), + ENUM2STRING(LS_DUAL_LR), + ENUM2STRING(LS_HILT_BASH), + {"", -1}}; + +saber_styles_t TranslateSaberStyle(const char *name) { + if (!Q_stricmp(name, "fast")) + return SS_FAST; + if (!Q_stricmp(name, "medium")) + return SS_MEDIUM; + if (!Q_stricmp(name, "strong")) + return SS_STRONG; + if (!Q_stricmp(name, "desann")) + return SS_DESANN; + if (!Q_stricmp(name, "tavion")) + return SS_TAVION; + if (!Q_stricmp(name, "dual")) + return SS_DUAL; + if (!Q_stricmp(name, "staff")) + return SS_STAFF; return SS_NONE; } -void WP_SaberFreeStrings( saberInfo_t &saber ) { - if ( saber.name && gi.bIsFromZone( saber.name, TAG_G_ALLOC ) ) { - gi.Free( saber.name ); +void WP_SaberFreeStrings(saberInfo_t &saber) { + if (saber.name && gi.bIsFromZone(saber.name, TAG_G_ALLOC)) { + gi.Free(saber.name); saber.name = NULL; } - if ( saber.fullName && gi.bIsFromZone( saber.fullName, TAG_G_ALLOC ) ) { - gi.Free( saber.fullName ); + if (saber.fullName && gi.bIsFromZone(saber.fullName, TAG_G_ALLOC)) { + gi.Free(saber.fullName); saber.fullName = NULL; } - if ( saber.model && gi.bIsFromZone( saber.model, TAG_G_ALLOC ) ) { - gi.Free( saber.model ); + if (saber.model && gi.bIsFromZone(saber.model, TAG_G_ALLOC)) { + gi.Free(saber.model); saber.model = NULL; } - if ( saber.skin && gi.bIsFromZone( saber.skin, TAG_G_ALLOC ) ) { - gi.Free( saber.skin ); + if (saber.skin && gi.bIsFromZone(saber.skin, TAG_G_ALLOC)) { + gi.Free(saber.skin); saber.skin = NULL; } - if ( saber.brokenSaber1 && gi.bIsFromZone( saber.brokenSaber1, TAG_G_ALLOC ) ) { - gi.Free( saber.brokenSaber1 ); + if (saber.brokenSaber1 && gi.bIsFromZone(saber.brokenSaber1, TAG_G_ALLOC)) { + gi.Free(saber.brokenSaber1); saber.brokenSaber1 = NULL; } - if ( saber.brokenSaber2 && gi.bIsFromZone( saber.brokenSaber2, TAG_G_ALLOC ) ) { - gi.Free( saber.brokenSaber2 ); + if (saber.brokenSaber2 && gi.bIsFromZone(saber.brokenSaber2, TAG_G_ALLOC)) { + gi.Free(saber.brokenSaber2); saber.brokenSaber2 = NULL; } } -qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ) { - if ( saber - && saber->bladeStyle2Start > 0 - && bladeNum >= saber->bladeStyle2Start ) +qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum) { + if (saber && saber->bladeStyle2Start > 0 && bladeNum >= saber->bladeStyle2Start) return qtrue; return qfalse; } -qboolean WP_SaberBladeDoTransitionDamage( saberInfo_t *saber, int bladeNum ) { - //use first blade style for this blade - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE) ) +qboolean WP_SaberBladeDoTransitionDamage(saberInfo_t *saber, int bladeNum) { + // use first blade style for this blade + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE)) return qtrue; - //use second blade style for this blade - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE2) ) + // use second blade style for this blade + else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE2)) return qtrue; return qfalse; } -qboolean WP_UseFirstValidSaberStyle( gentity_t *ent, int *saberAnimLevel ) -{ - if ( ent && ent->client ) - { +qboolean WP_UseFirstValidSaberStyle(gentity_t *ent, int *saberAnimLevel) { + if (ent && ent->client) { qboolean styleInvalid = qfalse; - int validStyles = 0, styleNum; + int validStyles = 0, styleNum; - //initially, all styles are valid - for ( styleNum = SS_NONE+1; styleNum < SS_NUM_SABER_STYLES; styleNum++ ) - { - validStyles |= (1<client->ps.saber[0].Active() - && ent->client->ps.saber[0].stylesForbidden ) - { - if ( (ent->client->ps.saber[0].stylesForbidden&(1<<*saberAnimLevel)) ) - {//not a valid style for first saber! + if (ent->client->ps.saber[0].Active() && ent->client->ps.saber[0].stylesForbidden) { + if ((ent->client->ps.saber[0].stylesForbidden & (1 << *saberAnimLevel))) { // not a valid style for first saber! styleInvalid = qtrue; validStyles &= ~ent->client->ps.saber[0].stylesForbidden; } } - if ( ent->client->ps.dualSabers ) - {//check second saber, too - if ( ent->client->ps.saber[1].Active() - && ent->client->ps.saber[1].stylesForbidden ) - { - if ( (ent->client->ps.saber[1].stylesForbidden&(1<<*saberAnimLevel)) ) - {//not a valid style for second saber! + if (ent->client->ps.dualSabers) { // check second saber, too + if (ent->client->ps.saber[1].Active() && ent->client->ps.saber[1].stylesForbidden) { + if ((ent->client->ps.saber[1].stylesForbidden & (1 << *saberAnimLevel))) { // not a valid style for second saber! styleInvalid = qtrue; - //only the ones both sabers allow is valid + // only the ones both sabers allow is valid validStyles &= ~ent->client->ps.saber[1].stylesForbidden; } + } else { // can't use dual style if not using 2 sabers + validStyles &= ~(1 << SS_DUAL); } - else - {//can't use dual style if not using 2 sabers - validStyles &= ~(1<client ) - { - if ( ent->client->ps.saber[0].Active() - && ent->client->ps.saber[0].stylesForbidden ) - { - if ( (ent->client->ps.saber[0].stylesForbidden&(1<client) { + if (ent->client->ps.saber[0].Active() && ent->client->ps.saber[0].stylesForbidden) { + if ((ent->client->ps.saber[0].stylesForbidden & (1 << saberAnimLevel))) { // not a valid style for first saber! return qfalse; } } - if ( ent->client->ps.dualSabers ) - {//check second saber, too - if ( ent->client->ps.saber[1].Active() ) - { - if ( ent->client->ps.saber[1].stylesForbidden ) - { - if ( (ent->client->ps.saber[1].stylesForbidden&(1<client->ps.dualSabers) { // check second saber, too + if (ent->client->ps.saber[1].Active()) { + if (ent->client->ps.saber[1].stylesForbidden) { + if ((ent->client->ps.saber[1].stylesForbidden & (1 << saberAnimLevel))) { // not a valid style for second saber! return qfalse; } } - //now: if using dual sabers, only dual and tavion (if given with this saber) are allowed - if ( saberAnimLevel != SS_DUAL ) - {//dual is okay - if ( saberAnimLevel != SS_TAVION ) - {//tavion might be okay, all others are not + // now: if using dual sabers, only dual and tavion (if given with this saber) are allowed + if (saberAnimLevel != SS_DUAL) { // dual is okay + if (saberAnimLevel != SS_TAVION) { // tavion might be okay, all others are not return qfalse; - } - else - {//see if "tavion" style is okay - if ( ent->client->ps.saber[0].Active() - && (ent->client->ps.saber[0].stylesLearned&(1<client->ps.saber[1].stylesLearned&(1<client->ps.saber[0].Active() && + (ent->client->ps.saber[0].stylesLearned & (1 << SS_TAVION))) { // okay to use tavion style, first saber gave it to us + } else if ((ent->client->ps.saber[1].stylesLearned & (1 << SS_TAVION))) { // okay to use tavion style, second saber gave it to us + } else { // tavion style is not allowed because neither of the sabers we're using gave it to us (I know, doesn't quite make sense, + // but...) return qfalse; } } } - } - else if ( saberAnimLevel == SS_DUAL ) - {//can't use dual style if not using dualSabers + } else if (saberAnimLevel == SS_DUAL) { // can't use dual style if not using dualSabers return qfalse; } - } - else if ( saberAnimLevel == SS_DUAL ) - {//can't use dual style if not using dualSabers + } else if (saberAnimLevel == SS_DUAL) { // can't use dual style if not using dualSabers return qfalse; } } return qtrue; } -qboolean WP_SaberCanTurnOffSomeBlades( saberInfo_t *saber ) -{ - if ( saber->bladeStyle2Start > 0 - && saber->numBlades > saber->bladeStyle2Start ) - { - if ( (saber->saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) - && (saber->saberFlags2&SFL2_NO_MANUAL_DEACTIVATE2) ) - {//all blades are always on +qboolean WP_SaberCanTurnOffSomeBlades(saberInfo_t *saber) { + if (saber->bladeStyle2Start > 0 && saber->numBlades > saber->bladeStyle2Start) { + if ((saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE) && (saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) { // all blades are always on return qfalse; } - } - else - { - if ( (saber->saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) ) - {//all blades are always on + } else { + if ((saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) { // all blades are always on return qfalse; } } - //you can turn some off + // you can turn some off return qtrue; } -void WP_SaberSetDefaults( saberInfo_t *saber, qboolean setColors = qtrue ) -{ - //Set defaults so that, if it fails, there's at least something there +void WP_SaberSetDefaults(saberInfo_t *saber, qboolean setColors = qtrue) { + // Set defaults so that, if it fails, there's at least something there saber->name = NULL; saber->fullName = NULL; - for ( int i = 0; i < MAX_BLADES; i++ ) - { - if ( setColors ) - { + for (int i = 0; i < MAX_BLADES; i++) { + if (setColors) { saber->blade[i].color = SABER_RED; } saber->blade[i].radius = SABER_RADIUS_STANDARD; @@ -365,14 +303,14 @@ void WP_SaberSetDefaults( saberInfo_t *saber, qboolean setColors = qtrue ) } saber->model = "models/weapons2/saber_reborn/saber_w.glm"; saber->skin = NULL; - saber->soundOn = G_SoundIndex( "sound/weapons/saber/enemy_saber_on.wav" ); - saber->soundLoop = G_SoundIndex( "sound/weapons/saber/saberhum3.wav" ); - saber->soundOff = G_SoundIndex( "sound/weapons/saber/enemy_saber_off.wav" ); + saber->soundOn = G_SoundIndex("sound/weapons/saber/enemy_saber_on.wav"); + saber->soundLoop = G_SoundIndex("sound/weapons/saber/saberhum3.wav"); + saber->soundOff = G_SoundIndex("sound/weapons/saber/enemy_saber_off.wav"); saber->numBlades = 1; saber->type = SABER_SINGLE; saber->stylesLearned = 0; saber->stylesForbidden = 0; - saber->maxChain = 0;//0 = use default behavior + saber->maxChain = 0; // 0 = use default behavior saber->forceRestrictions = 0; saber->lockBonus = 0; saber->parryBonus = 0; @@ -380,1393 +318,1402 @@ void WP_SaberSetDefaults( saberInfo_t *saber, qboolean setColors = qtrue ) saber->breakParryBonus2 = 0; saber->disarmBonus = 0; saber->disarmBonus2 = 0; - saber->singleBladeStyle = SS_NONE;//makes it so that you use a different style if you only have the first blade active - saber->brokenSaber1 = NULL;//if saber is actually hit by another saber, it can be cut in half/broken and will be replaced with this saber in your right hand - saber->brokenSaber2 = NULL;//if saber is actually hit by another saber, it can be cut in half/broken and will be replaced with this saber in your left hand -//===NEW======================================================================================== - //these values are global to the saber, like all of the ones above - saber->saberFlags = 0; //see all the SFL_ flags - saber->saberFlags2 = 0; //see all the SFL2_ flags - saber->spinSound = 0; //none - if set, plays this sound as it spins when thrown - saber->swingSound[0] = 0; //none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - saber->swingSound[1] = 0; //none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - saber->swingSound[2] = 0; //none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - saber->fallSound[0] = 0; //none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! - saber->fallSound[1] = 0; //none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! - saber->fallSound[2] = 0; //none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! - - //done in game (server-side code) - saber->moveSpeedScale = 1.0f; //1.0 - you move faster/slower when using this saber - saber->animSpeedScale = 1.0f; //1.0 - plays normal attack animations faster/slower - - saber->kataMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time - saber->lungeAtkMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they crouch+fwd+attack - saber->jumpAtkUpMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they jump+attack - saber->jumpAtkFwdMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they jump+fwd+attack - saber->jumpAtkBackMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they jump+back+attack - saber->jumpAtkRightMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they jump+rightattack - saber->jumpAtkLeftMove = LS_INVALID; //LS_INVALID - if set, player will execute this move when they jump+left+attack - saber->readyAnim = -1; //-1 - anim to use when standing idle - saber->drawAnim = -1; //-1 - anim to use when drawing weapon - saber->putawayAnim = -1; //-1 - anim to use when putting weapon away - saber->tauntAnim = -1; //-1 - anim to use when hit "taunt" - saber->bowAnim = -1; //-1 - anim to use when hit "bow" - saber->meditateAnim = -1; //-1 - anim to use when hit "meditate" - saber->flourishAnim = -1; //-1 - anim to use when hit "flourish" - saber->gloatAnim = -1; //-1 - anim to use when hit "gloat" - - //***NOTE: you can only have a maximum of 2 "styles" of blades, so this next value, "bladeStyle2Start" is the number of the first blade to use these value on... all blades before this use the normal values above, all blades at and after this number use the secondary values below*** - saber->bladeStyle2Start = 0; //0 - if set, blades from this number and higher use the following values (otherwise, they use the normal values already set) + saber->singleBladeStyle = SS_NONE; // makes it so that you use a different style if you only have the first blade active + saber->brokenSaber1 = + NULL; // if saber is actually hit by another saber, it can be cut in half/broken and will be replaced with this saber in your right hand + saber->brokenSaber2 = NULL; // if saber is actually hit by another saber, it can be cut in half/broken and will be replaced with this saber in your left + // hand + //===NEW======================================================================================== + // these values are global to the saber, like all of the ones above + saber->saberFlags = 0; // see all the SFL_ flags + saber->saberFlags2 = 0; // see all the SFL2_ flags + saber->spinSound = 0; // none - if set, plays this sound as it spins when thrown + saber->swingSound[0] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + saber->swingSound[1] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + saber->swingSound[2] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + saber->fallSound[0] = 0; // none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! + saber->fallSound[1] = 0; // none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! + saber->fallSound[2] = 0; // none - if set, plays one of these 3 sounds when weapon falls to the ground - NOTE: must provide all 3!!! + + // done in game (server-side code) + saber->moveSpeedScale = 1.0f; // 1.0 - you move faster/slower when using this saber + saber->animSpeedScale = 1.0f; // 1.0 - plays normal attack animations faster/slower + + saber->kataMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time + saber->lungeAtkMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they crouch+fwd+attack + saber->jumpAtkUpMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+attack + saber->jumpAtkFwdMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+fwd+attack + saber->jumpAtkBackMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+back+attack + saber->jumpAtkRightMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+rightattack + saber->jumpAtkLeftMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+left+attack + saber->readyAnim = -1; //-1 - anim to use when standing idle + saber->drawAnim = -1; //-1 - anim to use when drawing weapon + saber->putawayAnim = -1; //-1 - anim to use when putting weapon away + saber->tauntAnim = -1; //-1 - anim to use when hit "taunt" + saber->bowAnim = -1; //-1 - anim to use when hit "bow" + saber->meditateAnim = -1; //-1 - anim to use when hit "meditate" + saber->flourishAnim = -1; //-1 - anim to use when hit "flourish" + saber->gloatAnim = -1; //-1 - anim to use when hit "gloat" + + //***NOTE: you can only have a maximum of 2 "styles" of blades, so this next value, "bladeStyle2Start" is the number of the first blade to use these value + //on... all blades before this use the normal values above, all blades at and after this number use the secondary values below*** + saber->bladeStyle2Start = 0; // 0 - if set, blades from this number and higher use the following values (otherwise, they use the normal values already set) //***The following can be different for the extra blades - not setting them individually defaults them to the value for the whole saber (and first blade)*** //===PRIMARY BLADES===================== - //done in cgame (client-side code) - saber->trailStyle = 0; //0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) - saber->g2MarksShader[0]=0; //none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->g2WeaponMarkShader[0]=0; //none - if set, the game will ry to project this shader onto the weapon when it damages a person (good for a blood splatter on the weapon) - //saber->bladeShader = 0; //none - if set, overrides the shader used for the saber blade? - //saber->trailShader = 0; //none - if set, overrides the shader used for the saber trail? - saber->hitSound[0] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hitSound[1] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hitSound[2] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->blockSound[0] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->blockSound[1] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->blockSound[2] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->bounceSound[0] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounceSound[1] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounceSound[2] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->blockEffect = 0; //none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") - saber->hitPersonEffect = 0; //none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") - saber->hitOtherEffect = 0; //none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") - saber->bladeEffect = 0; //none - if set, plays this effect at the blade tag - - //done in game (server-side code) - saber->knockbackScale = 0; //0 - if non-zero, uses damage done to calculate an appropriate amount of knockback - saber->damageScale = 1.0f; //1 - scale up or down the damage done by the saber - saber->splashRadius = 0.0f; //0 - radius of splashDamage - saber->splashDamage = 0; //0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius - saber->splashKnockback = 0.0f; //0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius + // done in cgame (client-side code) + saber->trailStyle = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) + saber->g2MarksShader[0] = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->g2WeaponMarkShader[0] = + 0; // none - if set, the game will ry to project this shader onto the weapon when it damages a person (good for a blood splatter on the weapon) + // saber->bladeShader = 0; //none - if set, overrides the shader used for the saber blade? + // saber->trailShader = 0; //none - if set, overrides the shader used for the saber trail? + saber->hitSound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hitSound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hitSound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->blockSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->blockSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->blockSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->bounceSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounceSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounceSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->blockEffect = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") + saber->hitPersonEffect = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") + saber->hitOtherEffect = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") + saber->bladeEffect = 0; // none - if set, plays this effect at the blade tag + + // done in game (server-side code) + saber->knockbackScale = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback + saber->damageScale = 1.0f; // 1 - scale up or down the damage done by the saber + saber->splashRadius = 0.0f; // 0 - radius of splashDamage + saber->splashDamage = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius + saber->splashKnockback = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius //===SECONDARY BLADES=================== - //done in cgame (client-side code) - saber->trailStyle2 = 0; //0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) - saber->g2MarksShader2[0]=0; //none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->g2WeaponMarkShader2[0]=0; //none - if set, the game will ry to project this shader onto the weapon when it damages a person (good for a blood splatter on the weapon) - //saber->bladeShader = 0; //none - if set, overrides the shader used for the saber blade? - //saber->trailShader = 0; //none - if set, overrides the shader used for the saber trail? - saber->hit2Sound[0] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hit2Sound[1] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hit2Sound[2] = 0; //none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->block2Sound[0] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->block2Sound[1] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->block2Sound[2] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->bounce2Sound[0] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounce2Sound[1] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounce2Sound[2] = 0; //none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->blockEffect2 = 0; //none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") - saber->hitPersonEffect2 = 0; //none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") - saber->hitOtherEffect2 = 0; //none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") - saber->bladeEffect2 = 0; //none - if set, plays this effect at the blade tag - - //done in game (server-side code) - saber->knockbackScale2 = 0; //0 - if non-zero, uses damage done to calculate an appropriate amount of knockback - saber->damageScale2 = 1.0f; //1 - scale up or down the damage done by the saber - saber->splashRadius2 = 0.0f; //0 - radius of splashDamage - saber->splashDamage2 = 0; //0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius - saber->splashKnockback2 = 0.0f; //0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius -//========================================================================================================================================= -} - -static void Saber_ParseName( saberInfo_t *saber, const char **p ) { - const char *value; - if ( COM_ParseString( p, &value ) ) - return; - saber->fullName = G_NewString( value ); -} -static void Saber_ParseSaberType( saberInfo_t *saber, const char **p ) { + // done in cgame (client-side code) + saber->trailStyle2 = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) + saber->g2MarksShader2[0] = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->g2WeaponMarkShader2[0] = + 0; // none - if set, the game will ry to project this shader onto the weapon when it damages a person (good for a blood splatter on the weapon) + // saber->bladeShader = 0; //none - if set, overrides the shader used for the saber blade? + // saber->trailShader = 0; //none - if set, overrides the shader used for the saber trail? + saber->hit2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hit2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hit2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->block2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->block2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->block2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->bounce2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounce2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounce2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->blockEffect2 = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") + saber->hitPersonEffect2 = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") + saber->hitOtherEffect2 = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") + saber->bladeEffect2 = 0; // none - if set, plays this effect at the blade tag + + // done in game (server-side code) + saber->knockbackScale2 = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback + saber->damageScale2 = 1.0f; // 1 - scale up or down the damage done by the saber + saber->splashRadius2 = 0.0f; // 0 - radius of splashDamage + saber->splashDamage2 = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius + saber->splashKnockback2 = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius + //========================================================================================================================================= +} + +static void Saber_ParseName(saberInfo_t *saber, const char **p) { + const char *value; + if (COM_ParseString(p, &value)) + return; + saber->fullName = G_NewString(value); +} +static void Saber_ParseSaberType(saberInfo_t *saber, const char **p) { const char *value; int saberType; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberType = GetIDForString( SaberTable, value ); - if ( saberType >= SABER_SINGLE && saberType <= NUM_SABERS ) + saberType = GetIDForString(SaberTable, value); + if (saberType >= SABER_SINGLE && saberType <= NUM_SABERS) saber->type = (saberType_t)saberType; } -static void Saber_ParseSaberModel( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberModel(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->model = G_NewString( value ); + saber->model = G_NewString(value); } -static void Saber_ParseCustomSkin( saberInfo_t *saber, const char **p ) { +static void Saber_ParseCustomSkin(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->skin = G_NewString( value ); + saber->skin = G_NewString(value); } -static void Saber_ParseSoundOn( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundOn(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundOn = G_SoundIndex( value ); + saber->soundOn = G_SoundIndex(value); } -static void Saber_ParseSoundLoop( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundLoop(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundLoop = G_SoundIndex( value ); + saber->soundLoop = G_SoundIndex(value); } -static void Saber_ParseSoundOff( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundOff(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundOff = G_SoundIndex( value ); + saber->soundOff = G_SoundIndex(value); } -static void Saber_ParseNumBlades( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNumBlades(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n < 1 || n > MAX_BLADES ) { - Com_Error( ERR_DROP, "WP_SaberParseParms: saber %s has illegal number of blades (%d) max: %d", saber->name, n, MAX_BLADES ); + if (n < 1 || n > MAX_BLADES) { + Com_Error(ERR_DROP, "WP_SaberParseParms: saber %s has illegal number of blades (%d) max: %d", saber->name, n, MAX_BLADES); return; } saber->numBlades = n; } qboolean Saber_SetColor = qtrue; -static void Saber_ParseSaberColor( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor(saberInfo_t *saber, const char **p) { const char *value; - int i=0; + int i = 0; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); - for ( i=0; iblade[i].color = color; } -static void Saber_ParseSaberColor2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor2(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[1].color = color; } -static void Saber_ParseSaberColor3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor3(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[2].color = color; } -static void Saber_ParseSaberColor4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor4(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[3].color = color; } -static void Saber_ParseSaberColor5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor5(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[4].color = color; } -static void Saber_ParseSaberColor6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor6(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[5].color = color; } -static void Saber_ParseSaberColor7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor7(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; // don't actually want to set the colors // read the color out anyway just to advance the *p pointer - if ( !Saber_SetColor ) + if (!Saber_SetColor) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[6].color = color; } -static void Saber_ParseSaberLength( saberInfo_t *saber, const char **p ) { - int i=0; +static void Saber_ParseSaberLength(saberInfo_t *saber, const char **p) { + int i = 0; float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; - for ( i=0; iblade[i].lengthMax = f; } -static void Saber_ParseSaberLength2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[1].lengthMax = f; } -static void Saber_ParseSaberLength3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength3(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[2].lengthMax = f; } -static void Saber_ParseSaberLength4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength4(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[3].lengthMax = f; } -static void Saber_ParseSaberLength5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength5(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[4].lengthMax = f; } -static void Saber_ParseSaberLength6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength6(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[5].lengthMax = f; } -static void Saber_ParseSaberLength7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength7(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[6].lengthMax = f; } -static void Saber_ParseSaberRadius( saberInfo_t *saber, const char **p ) { - int i=0; +static void Saber_ParseSaberRadius(saberInfo_t *saber, const char **p) { + int i = 0; float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; - for ( i=0; iblade[i].radius = f; } -static void Saber_ParseSaberRadius2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[1].radius = f; } -static void Saber_ParseSaberRadius3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius3(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[2].radius = f; } -static void Saber_ParseSaberRadius4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius4(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[3].radius = f; } -static void Saber_ParseSaberRadius5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius5(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[4].radius = f; } -static void Saber_ParseSaberRadius6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius6(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[5].radius = f; } -static void Saber_ParseSaberRadius7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius7(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[6].radius = f; } -static void Saber_ParseSaberStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyle(saberInfo_t *saber, const char **p) { const char *value; int style, styleNum; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - //OLD WAY: only allowed ONE style - style = TranslateSaberStyle( value ); - //learn only this style - saber->stylesLearned = (1<stylesLearned = (1 << style); + // forbid all other styles saber->stylesForbidden = 0; - for ( styleNum=SS_NONE+1; styleNumstylesForbidden |= (1<stylesForbidden |= (1 << styleNum); } } -static void Saber_ParseSaberStyleLearned( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyleLearned(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->stylesLearned |= (1<stylesLearned |= (1 << TranslateSaberStyle(value)); } -static void Saber_ParseSaberStyleForbidden( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyleForbidden(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->stylesForbidden |= (1<stylesForbidden |= (1 << TranslateSaberStyle(value)); } -static void Saber_ParseMaxChain( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMaxChain(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->maxChain = n; } -static void Saber_ParseLockable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLockable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_LOCKABLE; } -static void Saber_ParseThrowable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseThrowable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_THROWABLE; } -static void Saber_ParseDisarmable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_DISARMABLE; } -static void Saber_ParseBlocking( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlocking(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_ACTIVE_BLOCKING; } -static void Saber_ParseTwoHanded( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTwoHanded(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_TWO_HANDED; } -static void Saber_ParseForceRestrict( saberInfo_t *saber, const char **p ) { +static void Saber_ParseForceRestrict(saberInfo_t *saber, const char **p) { const char *value; int fp; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - fp = GetIDForString( FPTable, value ); - if ( fp >= FP_FIRST && fp < NUM_FORCE_POWERS ) - saber->forceRestrictions |= (1<= FP_FIRST && fp < NUM_FORCE_POWERS) + saber->forceRestrictions |= (1 << fp); } -static void Saber_ParseLockBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLockBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->lockBonus = n; } -static void Saber_ParseParryBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseParryBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->parryBonus = n; } -static void Saber_ParseBreakParryBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBreakParryBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->breakParryBonus = n; } -static void Saber_ParseBreakParryBonus2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBreakParryBonus2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->breakParryBonus2 = n; } -static void Saber_ParseDisarmBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->disarmBonus = n; } -static void Saber_ParseDisarmBonus2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmBonus2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->disarmBonus2 = n; } -static void Saber_ParseSingleBladeStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSingleBladeStyle(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->singleBladeStyle = TranslateSaberStyle( value ); + saber->singleBladeStyle = TranslateSaberStyle(value); } -static void Saber_ParseSingleBladeThrowable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSingleBladeThrowable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_SINGLE_BLADE_THROWABLE; } -static void Saber_ParseBrokenSaber1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBrokenSaber1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->brokenSaber1 = G_NewString( value ); + saber->brokenSaber1 = G_NewString(value); } -static void Saber_ParseBrokenSaber2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBrokenSaber2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->brokenSaber2 = G_NewString( value ); + saber->brokenSaber2 = G_NewString(value); } -static void Saber_ParseReturnDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseReturnDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_RETURN_DAMAGE; } -static void Saber_ParseSpinSound( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSpinSound(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->spinSound = G_SoundIndex( value ); + saber->spinSound = G_SoundIndex(value); } -static void Saber_ParseSwingSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[0] = G_SoundIndex( value ); + saber->swingSound[0] = G_SoundIndex(value); } -static void Saber_ParseSwingSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[1] = G_SoundIndex( value ); + saber->swingSound[1] = G_SoundIndex(value); } -static void Saber_ParseSwingSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[2] = G_SoundIndex( value ); + saber->swingSound[2] = G_SoundIndex(value); } -static void Saber_ParseFallSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseFallSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->fallSound[0] = G_SoundIndex( value ); + saber->fallSound[0] = G_SoundIndex(value); } -static void Saber_ParseFallSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseFallSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->fallSound[1] = G_SoundIndex( value ); + saber->fallSound[1] = G_SoundIndex(value); } -static void Saber_ParseFallSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseFallSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->fallSound[2] = G_SoundIndex( value ); + saber->fallSound[2] = G_SoundIndex(value); } -static void Saber_ParseMoveSpeedScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMoveSpeedScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->moveSpeedScale = f; } -static void Saber_ParseAnimSpeedScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAnimSpeedScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->animSpeedScale = f; } -static void Saber_ParseOnInWater( saberInfo_t *saber, const char **p ) { +static void Saber_ParseOnInWater(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_ON_IN_WATER; } -static void Saber_ParseBounceOnWalls( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceOnWalls(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_BOUNCE_ON_WALLS; } -static void Saber_ParseBoltToWrist( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBoltToWrist(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_BOLT_TO_WRIST; } -static void Saber_ParseKataMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKataMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) - saber->kataMove = saberMove; //LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) + saber->kataMove = saberMove; // LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time } -static void Saber_ParseLungeAtkMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLungeAtkMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->lungeAtkMove = saberMove; } -static void Saber_ParseJumpAtkUpMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkUpMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkUpMove = saberMove; } -static void Saber_ParseJumpAtkFwdMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkFwdMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkFwdMove = saberMove; } -static void Saber_ParseJumpAtkBackMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkBackMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkBackMove = saberMove; } -static void Saber_ParseJumpAtkRightMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkRightMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkRightMove = saberMove; } -static void Saber_ParseJumpAtkLeftMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkLeftMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( SaberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(SaberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkLeftMove = saberMove; } -static void Saber_ParseReadyAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseReadyAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->readyAnim = anim; } -static void Saber_ParseDrawAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDrawAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->drawAnim = anim; } -static void Saber_ParsePutawayAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParsePutawayAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->putawayAnim = anim; } -static void Saber_ParseTauntAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTauntAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->tauntAnim = anim; } -static void Saber_ParseBowAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBowAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->bowAnim = anim; } -static void Saber_ParseMeditateAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMeditateAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->meditateAnim = anim; } -static void Saber_ParseFlourishAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseFlourishAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->flourishAnim = anim; } -static void Saber_ParseGloatAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseGloatAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->gloatAnim = anim; } -static void Saber_ParseNoRollStab( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoRollStab(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_ROLL_STAB; } -static void Saber_ParseNoPullAttack( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoPullAttack(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_PULL_ATTACK; } -static void Saber_ParseNoBackAttack( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBackAttack(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_BACK_ATTACK; } -static void Saber_ParseNoStabDown( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoStabDown(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_STABDOWN; } -static void Saber_ParseNoWallRuns( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallRuns(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_RUNS; } -static void Saber_ParseNoWallFlips( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallFlips(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_FLIPS; } -static void Saber_ParseNoWallGrab( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallGrab(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_GRAB; } -static void Saber_ParseNoRolls( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoRolls(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_ROLLS; } -static void Saber_ParseNoFlips( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoFlips(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_FLIPS; } -static void Saber_ParseNoCartwheels( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoCartwheels(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_CARTWHEELS; } -static void Saber_ParseNoKicks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoKicks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_KICKS; } -static void Saber_ParseNoMirrorAttacks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoMirrorAttacks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_MIRROR_ATTACKS; } -static void Saber_ParseNotInMP( saberInfo_t *saber, const char **p ) { - SkipRestOfLine( p ); -} -static void Saber_ParseBladeStyle2Start( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNotInMP(saberInfo_t *saber, const char **p) { SkipRestOfLine(p); } +static void Saber_ParseBladeStyle2Start(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->bladeStyle2Start = n; } -static void Saber_ParseNoWallMarks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallMarks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_WALL_MARKS; } -static void Saber_ParseNoDLight( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDLight(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DLIGHT; } -static void Saber_ParseNoBlade( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBlade(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_BLADE; } -static void Saber_ParseTrailStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTrailStyle(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->trailStyle = n; } -static void Saber_ParseG2MarksShader( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2MarksShader(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } - Q_strncpyz( saber->g2MarksShader, value, sizeof( saber->g2MarksShader ) ); - //NOTE: registers this on cgame side where it registers all client assets + Q_strncpyz(saber->g2MarksShader, value, sizeof(saber->g2MarksShader)); + // NOTE: registers this on cgame side where it registers all client assets } -static void Saber_ParseG2WeaponMarkShader( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2WeaponMarkShader(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } - Q_strncpyz( saber->g2WeaponMarkShader, value, sizeof( saber->g2WeaponMarkShader ) ); - //NOTE: registers this on cgame side where it registers all client assets + Q_strncpyz(saber->g2WeaponMarkShader, value, sizeof(saber->g2WeaponMarkShader)); + // NOTE: registers this on cgame side where it registers all client assets } -static void Saber_ParseKnockbackScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKnockbackScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->knockbackScale = f; } -static void Saber_ParseDamageScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDamageScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->damageScale = f; } -static void Saber_ParseNoDismemberment( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDismemberment(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DISMEMBERMENT; } -static void Saber_ParseNoIdleEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoIdleEffect(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_IDLE_EFFECT; } -static void Saber_ParseAlwaysBlock( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAlwaysBlock(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_ALWAYS_BLOCK; } -static void Saber_ParseNoManualDeactivate( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoManualDeactivate(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_MANUAL_DEACTIVATE; } -static void Saber_ParseTransitionDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTransitionDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_TRANSITION_DAMAGE; } -static void Saber_ParseSplashRadius( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashRadius(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashRadius = f; } -static void Saber_ParseSplashDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->splashDamage = n; } -static void Saber_ParseSplashKnockback( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashKnockback(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashKnockback = f; } -static void Saber_ParseHitSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[0] = G_SoundIndex( value ); + saber->hitSound[0] = G_SoundIndex(value); } -static void Saber_ParseHitSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[1] = G_SoundIndex( value ); + saber->hitSound[1] = G_SoundIndex(value); } -static void Saber_ParseHitSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[2] = G_SoundIndex( value ); + saber->hitSound[2] = G_SoundIndex(value); } -static void Saber_ParseBlockSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[0] = G_SoundIndex( value ); + saber->blockSound[0] = G_SoundIndex(value); } -static void Saber_ParseBlockSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[1] = G_SoundIndex( value ); + saber->blockSound[1] = G_SoundIndex(value); } -static void Saber_ParseBlockSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[2] = G_SoundIndex( value ); + saber->blockSound[2] = G_SoundIndex(value); } -static void Saber_ParseBounceSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[0] = G_SoundIndex( value ); + saber->bounceSound[0] = G_SoundIndex(value); } -static void Saber_ParseBounceSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[1] = G_SoundIndex( value ); + saber->bounceSound[1] = G_SoundIndex(value); } -static void Saber_ParseBounceSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[2] = G_SoundIndex( value ); + saber->bounceSound[2] = G_SoundIndex(value); } -static void Saber_ParseBlockEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockEffect = G_EffectIndex( value ); + saber->blockEffect = G_EffectIndex(value); } -static void Saber_ParseHitPersonEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitPersonEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitPersonEffect = G_EffectIndex( value ); + saber->hitPersonEffect = G_EffectIndex(value); } -static void Saber_ParseHitOtherEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitOtherEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitOtherEffect = G_EffectIndex( value ); + saber->hitOtherEffect = G_EffectIndex(value); } -static void Saber_ParseBladeEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBladeEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bladeEffect = G_EffectIndex( value ); + saber->bladeEffect = G_EffectIndex(value); } -static void Saber_ParseNoClashFlare( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoClashFlare(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_CLASH_FLARE; } -static void Saber_ParseNoWallMarks2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallMarks2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_WALL_MARKS2; } -static void Saber_ParseNoDLight2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDLight2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DLIGHT2; } -static void Saber_ParseNoBlade2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBlade2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_BLADE2; } -static void Saber_ParseTrailStyle2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTrailStyle2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->trailStyle2 = n; } -static void Saber_ParseG2MarksShader2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2MarksShader2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } - Q_strncpyz( saber->g2MarksShader2, value, sizeof(saber->g2MarksShader2) ); - //NOTE: registers this on cgame side where it registers all client assets + Q_strncpyz(saber->g2MarksShader2, value, sizeof(saber->g2MarksShader2)); + // NOTE: registers this on cgame side where it registers all client assets } -static void Saber_ParseG2WeaponMarkShader2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2WeaponMarkShader2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } - Q_strncpyz( saber->g2WeaponMarkShader2, value, sizeof(saber->g2WeaponMarkShader2) ); - //NOTE: registers this on cgame side where it registers all client assets + Q_strncpyz(saber->g2WeaponMarkShader2, value, sizeof(saber->g2WeaponMarkShader2)); + // NOTE: registers this on cgame side where it registers all client assets } -static void Saber_ParseKnockbackScale2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKnockbackScale2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->knockbackScale2 = f; } -static void Saber_ParseDamageScale2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDamageScale2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->damageScale2 = f; } -static void Saber_ParseNoDismemberment2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDismemberment2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DISMEMBERMENT2; } -static void Saber_ParseNoIdleEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoIdleEffect2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_IDLE_EFFECT2; } -static void Saber_ParseAlwaysBlock2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAlwaysBlock2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_ALWAYS_BLOCK2; } -static void Saber_ParseNoManualDeactivate2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoManualDeactivate2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_MANUAL_DEACTIVATE2; } -static void Saber_ParseTransitionDamage2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTransitionDamage2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_TRANSITION_DAMAGE2; } -static void Saber_ParseSplashRadius2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashRadius2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashRadius2 = f; } -static void Saber_ParseSplashDamage2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashDamage2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->splashDamage2 = n; } -static void Saber_ParseSplashKnockback2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashKnockback2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashKnockback2 = f; } -static void Saber_ParseHit2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[0] = G_SoundIndex( value ); + saber->hit2Sound[0] = G_SoundIndex(value); } -static void Saber_ParseHit2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[1] = G_SoundIndex( value ); + saber->hit2Sound[1] = G_SoundIndex(value); } -static void Saber_ParseHit2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[2] = G_SoundIndex( value ); + saber->hit2Sound[2] = G_SoundIndex(value); } -static void Saber_ParseBlock2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[0] = G_SoundIndex( value ); + saber->block2Sound[0] = G_SoundIndex(value); } -static void Saber_ParseBlock2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[1] = G_SoundIndex( value ); + saber->block2Sound[1] = G_SoundIndex(value); } -static void Saber_ParseBlock2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[2] = G_SoundIndex( value ); + saber->block2Sound[2] = G_SoundIndex(value); } -static void Saber_ParseBounce2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[0] = G_SoundIndex( value ); + saber->bounce2Sound[0] = G_SoundIndex(value); } -static void Saber_ParseBounce2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[1] = G_SoundIndex( value ); + saber->bounce2Sound[1] = G_SoundIndex(value); } -static void Saber_ParseBounce2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[2] = G_SoundIndex( value ); + saber->bounce2Sound[2] = G_SoundIndex(value); } -static void Saber_ParseBlockEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockEffect2 = G_EffectIndex( value ); + saber->blockEffect2 = G_EffectIndex(value); } -static void Saber_ParseHitPersonEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitPersonEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitPersonEffect2 = G_EffectIndex( value ); + saber->hitPersonEffect2 = G_EffectIndex(value); } -static void Saber_ParseHitOtherEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitOtherEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitOtherEffect2 = G_EffectIndex( value ); + saber->hitOtherEffect2 = G_EffectIndex(value); } -static void Saber_ParseBladeEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBladeEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bladeEffect2 = G_EffectIndex( (char *)value ); + saber->bladeEffect2 = G_EffectIndex((char *)value); } -static void Saber_ParseNoClashFlare2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoClashFlare2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_CLASH_FLARE2; } @@ -1779,317 +1726,305 @@ Keyword Hash #define KEYWORDHASH_SIZE (512) typedef struct keywordHash_s { - char *keyword; - void (*func)(saberInfo_t *saber, const char **p); + char *keyword; + void (*func)(saberInfo_t *saber, const char **p); struct keywordHash_s *next; } keywordHash_t; -static int KeywordHash_Key( const char *keyword ) { +static int KeywordHash_Key(const char *keyword) { int hash, i; hash = 0; - for ( i=0; keyword[i]; i++ ) { - if ( keyword[i] >= 'A' && keyword[i] <= 'Z' ) - hash += (keyword[i] + ('a'-'A')) * (119 + i); + for (i = 0; keyword[i]; i++) { + if (keyword[i] >= 'A' && keyword[i] <= 'Z') + hash += (keyword[i] + ('a' - 'A')) * (119 + i); else hash += keyword[i] * (119 + i); } - hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE-1); + hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE - 1); return hash; } -static void KeywordHash_Add( keywordHash_t *table[], keywordHash_t *key ) { - int hash = KeywordHash_Key( key->keyword ); +static void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) { + int hash = KeywordHash_Key(key->keyword); key->next = table[hash]; table[hash] = key; } -static keywordHash_t *KeywordHash_Find( keywordHash_t *table[], const char *keyword ) { +static keywordHash_t *KeywordHash_Find(keywordHash_t *table[], const char *keyword) { keywordHash_t *key; int hash = KeywordHash_Key(keyword); - for ( key=table[hash]; key; key=key->next ) { - if ( !Q_stricmp( key->keyword, keyword ) ) + for (key = table[hash]; key; key = key->next) { + if (!Q_stricmp(key->keyword, keyword)) return key; } return NULL; } -static keywordHash_t saberParseKeywords[] = { - { "name", Saber_ParseName, NULL }, - { "saberType", Saber_ParseSaberType, NULL }, - { "saberModel", Saber_ParseSaberModel, NULL }, - { "customSkin", Saber_ParseCustomSkin, NULL }, - { "soundOn", Saber_ParseSoundOn, NULL }, - { "soundLoop", Saber_ParseSoundLoop, NULL }, - { "soundOff", Saber_ParseSoundOff, NULL }, - { "numBlades", Saber_ParseNumBlades, NULL }, - { "saberColor", Saber_ParseSaberColor, NULL }, - { "saberColor2", Saber_ParseSaberColor2, NULL }, - { "saberColor3", Saber_ParseSaberColor3, NULL }, - { "saberColor4", Saber_ParseSaberColor4, NULL }, - { "saberColor5", Saber_ParseSaberColor5, NULL }, - { "saberColor6", Saber_ParseSaberColor6, NULL }, - { "saberColor7", Saber_ParseSaberColor7, NULL }, - { "saberLength", Saber_ParseSaberLength, NULL }, - { "saberLength2", Saber_ParseSaberLength2, NULL }, - { "saberLength3", Saber_ParseSaberLength3, NULL }, - { "saberLength4", Saber_ParseSaberLength4, NULL }, - { "saberLength5", Saber_ParseSaberLength5, NULL }, - { "saberLength6", Saber_ParseSaberLength6, NULL }, - { "saberLength7", Saber_ParseSaberLength7, NULL }, - { "saberRadius", Saber_ParseSaberRadius, NULL }, - { "saberRadius2", Saber_ParseSaberRadius2, NULL }, - { "saberRadius3", Saber_ParseSaberRadius3, NULL }, - { "saberRadius4", Saber_ParseSaberRadius4, NULL }, - { "saberRadius5", Saber_ParseSaberRadius5, NULL }, - { "saberRadius6", Saber_ParseSaberRadius6, NULL }, - { "saberRadius7", Saber_ParseSaberRadius7, NULL }, - { "saberStyle", Saber_ParseSaberStyle, NULL }, - { "saberStyleLearned", Saber_ParseSaberStyleLearned, NULL }, - { "saberStyleForbidden", Saber_ParseSaberStyleForbidden, NULL }, - { "maxChain", Saber_ParseMaxChain, NULL }, - { "lockable", Saber_ParseLockable, NULL }, - { "throwable", Saber_ParseThrowable, NULL }, - { "disarmable", Saber_ParseDisarmable, NULL }, - { "blocking", Saber_ParseBlocking, NULL }, - { "twoHanded", Saber_ParseTwoHanded, NULL }, - { "forceRestrict", Saber_ParseForceRestrict, NULL }, - { "lockBonus", Saber_ParseLockBonus, NULL }, - { "parryBonus", Saber_ParseParryBonus, NULL }, - { "breakParryBonus", Saber_ParseBreakParryBonus, NULL }, - { "breakParryBonus2", Saber_ParseBreakParryBonus2, NULL }, - { "disarmBonus", Saber_ParseDisarmBonus, NULL }, - { "disarmBonus2", Saber_ParseDisarmBonus2, NULL }, - { "singleBladeStyle", Saber_ParseSingleBladeStyle, NULL }, - { "singleBladeThrowable", Saber_ParseSingleBladeThrowable,NULL }, - { "brokenSaber1", Saber_ParseBrokenSaber1, NULL }, - { "brokenSaber2", Saber_ParseBrokenSaber2, NULL }, - { "returnDamage", Saber_ParseReturnDamage, NULL }, - { "spinSound", Saber_ParseSpinSound, NULL }, - { "swingSound1", Saber_ParseSwingSound1, NULL }, - { "swingSound2", Saber_ParseSwingSound2, NULL }, - { "swingSound3", Saber_ParseSwingSound3, NULL }, - { "fallSound1", Saber_ParseFallSound1, NULL }, - { "fallSound2", Saber_ParseFallSound2, NULL }, - { "fallSound3", Saber_ParseFallSound3, NULL }, - { "moveSpeedScale", Saber_ParseMoveSpeedScale, NULL }, - { "animSpeedScale", Saber_ParseAnimSpeedScale, NULL }, - { "onInWater", Saber_ParseOnInWater, NULL }, - { "bounceOnWalls", Saber_ParseBounceOnWalls, NULL }, - { "boltToWrist", Saber_ParseBoltToWrist, NULL }, - { "kataMove", Saber_ParseKataMove, NULL }, - { "lungeAtkMove", Saber_ParseLungeAtkMove, NULL }, - { "jumpAtkUpMove", Saber_ParseJumpAtkUpMove, NULL }, - { "jumpAtkFwdMove", Saber_ParseJumpAtkFwdMove, NULL }, - { "jumpAtkBackMove", Saber_ParseJumpAtkBackMove, NULL }, - { "jumpAtkRightMove", Saber_ParseJumpAtkRightMove, NULL }, - { "jumpAtkLeftMove", Saber_ParseJumpAtkLeftMove, NULL }, - { "readyAnim", Saber_ParseReadyAnim, NULL }, - { "drawAnim", Saber_ParseDrawAnim, NULL }, - { "putawayAnim", Saber_ParsePutawayAnim, NULL }, - { "tauntAnim", Saber_ParseTauntAnim, NULL }, - { "bowAnim", Saber_ParseBowAnim, NULL }, - { "meditateAnim", Saber_ParseMeditateAnim, NULL }, - { "flourishAnim", Saber_ParseFlourishAnim, NULL }, - { "gloatAnim", Saber_ParseGloatAnim, NULL }, - { "noRollStab", Saber_ParseNoRollStab, NULL }, - { "noPullAttack", Saber_ParseNoPullAttack, NULL }, - { "noBackAttack", Saber_ParseNoBackAttack, NULL }, - { "noStabDown", Saber_ParseNoStabDown, NULL }, - { "noWallRuns", Saber_ParseNoWallRuns, NULL }, - { "noWallFlips", Saber_ParseNoWallFlips, NULL }, - { "noWallGrab", Saber_ParseNoWallGrab, NULL }, - { "noRolls", Saber_ParseNoRolls, NULL }, - { "noFlips", Saber_ParseNoFlips, NULL }, - { "noCartwheels", Saber_ParseNoCartwheels, NULL }, - { "noKicks", Saber_ParseNoKicks, NULL }, - { "noMirrorAttacks", Saber_ParseNoMirrorAttacks, NULL }, - { "notInMP", Saber_ParseNotInMP, NULL }, - { "bladeStyle2Start", Saber_ParseBladeStyle2Start, NULL }, - { "noWallMarks", Saber_ParseNoWallMarks, NULL }, - { "noWallMarks2", Saber_ParseNoWallMarks2, NULL }, - { "noDlight", Saber_ParseNoDLight, NULL }, - { "noDlight2", Saber_ParseNoDLight2, NULL }, - { "noBlade", Saber_ParseNoBlade, NULL }, - { "noBlade2", Saber_ParseNoBlade2, NULL }, - { "trailStyle", Saber_ParseTrailStyle, NULL }, - { "trailStyle2", Saber_ParseTrailStyle2, NULL }, - { "g2MarksShader", Saber_ParseG2MarksShader, NULL }, - { "g2MarksShader2", Saber_ParseG2MarksShader2, NULL }, - { "g2WeaponMarkShader", Saber_ParseG2WeaponMarkShader, NULL }, - { "g2WeaponMarkShader2", Saber_ParseG2WeaponMarkShader2, NULL }, - { "knockbackScale", Saber_ParseKnockbackScale, NULL }, - { "knockbackScale2", Saber_ParseKnockbackScale2, NULL }, - { "damageScale", Saber_ParseDamageScale, NULL }, - { "damageScale2", Saber_ParseDamageScale2, NULL }, - { "noDismemberment", Saber_ParseNoDismemberment, NULL }, - { "noDismemberment2", Saber_ParseNoDismemberment2, NULL }, - { "noIdleEffect", Saber_ParseNoIdleEffect, NULL }, - { "noIdleEffect2", Saber_ParseNoIdleEffect2, NULL }, - { "alwaysBlock", Saber_ParseAlwaysBlock, NULL }, - { "alwaysBlock2", Saber_ParseAlwaysBlock2, NULL }, - { "noManualDeactivate", Saber_ParseNoManualDeactivate, NULL }, - { "noManualDeactivate2", Saber_ParseNoManualDeactivate2, NULL }, - { "transitionDamage", Saber_ParseTransitionDamage, NULL }, - { "transitionDamage2", Saber_ParseTransitionDamage2, NULL }, - { "splashRadius", Saber_ParseSplashRadius, NULL }, - { "splashRadius2", Saber_ParseSplashRadius2, NULL }, - { "splashDamage", Saber_ParseSplashDamage, NULL }, - { "splashDamage2", Saber_ParseSplashDamage2, NULL }, - { "splashKnockback", Saber_ParseSplashKnockback, NULL }, - { "splashKnockback2", Saber_ParseSplashKnockback2, NULL }, - { "hitSound1", Saber_ParseHitSound1, NULL }, - { "hit2Sound1", Saber_ParseHit2Sound1, NULL }, - { "hitSound2", Saber_ParseHitSound2, NULL }, - { "hit2Sound2", Saber_ParseHit2Sound2, NULL }, - { "hitSound3", Saber_ParseHitSound3, NULL }, - { "hit2Sound3", Saber_ParseHit2Sound3, NULL }, - { "blockSound1", Saber_ParseBlockSound1, NULL }, - { "block2Sound1", Saber_ParseBlock2Sound1, NULL }, - { "blockSound2", Saber_ParseBlockSound2, NULL }, - { "block2Sound2", Saber_ParseBlock2Sound2, NULL }, - { "blockSound3", Saber_ParseBlockSound3, NULL }, - { "block2Sound3", Saber_ParseBlock2Sound3, NULL }, - { "bounceSound1", Saber_ParseBounceSound1, NULL }, - { "bounce2Sound1", Saber_ParseBounce2Sound1, NULL }, - { "bounceSound2", Saber_ParseBounceSound2, NULL }, - { "bounce2Sound2", Saber_ParseBounce2Sound2, NULL }, - { "bounceSound3", Saber_ParseBounceSound3, NULL }, - { "bounce2Sound3", Saber_ParseBounce2Sound3, NULL }, - { "blockEffect", Saber_ParseBlockEffect, NULL }, - { "blockEffect2", Saber_ParseBlockEffect2, NULL }, - { "hitPersonEffect", Saber_ParseHitPersonEffect, NULL }, - { "hitPersonEffect2", Saber_ParseHitPersonEffect2, NULL }, - { "hitOtherEffect", Saber_ParseHitOtherEffect, NULL }, - { "hitOtherEffect2", Saber_ParseHitOtherEffect2, NULL }, - { "bladeEffect", Saber_ParseBladeEffect, NULL }, - { "bladeEffect2", Saber_ParseBladeEffect2, NULL }, - { "noClashFlare", Saber_ParseNoClashFlare, NULL }, - { "noClashFlare2", Saber_ParseNoClashFlare2, NULL }, - { NULL, NULL, NULL } -}; +static keywordHash_t saberParseKeywords[] = {{"name", Saber_ParseName, NULL}, + {"saberType", Saber_ParseSaberType, NULL}, + {"saberModel", Saber_ParseSaberModel, NULL}, + {"customSkin", Saber_ParseCustomSkin, NULL}, + {"soundOn", Saber_ParseSoundOn, NULL}, + {"soundLoop", Saber_ParseSoundLoop, NULL}, + {"soundOff", Saber_ParseSoundOff, NULL}, + {"numBlades", Saber_ParseNumBlades, NULL}, + {"saberColor", Saber_ParseSaberColor, NULL}, + {"saberColor2", Saber_ParseSaberColor2, NULL}, + {"saberColor3", Saber_ParseSaberColor3, NULL}, + {"saberColor4", Saber_ParseSaberColor4, NULL}, + {"saberColor5", Saber_ParseSaberColor5, NULL}, + {"saberColor6", Saber_ParseSaberColor6, NULL}, + {"saberColor7", Saber_ParseSaberColor7, NULL}, + {"saberLength", Saber_ParseSaberLength, NULL}, + {"saberLength2", Saber_ParseSaberLength2, NULL}, + {"saberLength3", Saber_ParseSaberLength3, NULL}, + {"saberLength4", Saber_ParseSaberLength4, NULL}, + {"saberLength5", Saber_ParseSaberLength5, NULL}, + {"saberLength6", Saber_ParseSaberLength6, NULL}, + {"saberLength7", Saber_ParseSaberLength7, NULL}, + {"saberRadius", Saber_ParseSaberRadius, NULL}, + {"saberRadius2", Saber_ParseSaberRadius2, NULL}, + {"saberRadius3", Saber_ParseSaberRadius3, NULL}, + {"saberRadius4", Saber_ParseSaberRadius4, NULL}, + {"saberRadius5", Saber_ParseSaberRadius5, NULL}, + {"saberRadius6", Saber_ParseSaberRadius6, NULL}, + {"saberRadius7", Saber_ParseSaberRadius7, NULL}, + {"saberStyle", Saber_ParseSaberStyle, NULL}, + {"saberStyleLearned", Saber_ParseSaberStyleLearned, NULL}, + {"saberStyleForbidden", Saber_ParseSaberStyleForbidden, NULL}, + {"maxChain", Saber_ParseMaxChain, NULL}, + {"lockable", Saber_ParseLockable, NULL}, + {"throwable", Saber_ParseThrowable, NULL}, + {"disarmable", Saber_ParseDisarmable, NULL}, + {"blocking", Saber_ParseBlocking, NULL}, + {"twoHanded", Saber_ParseTwoHanded, NULL}, + {"forceRestrict", Saber_ParseForceRestrict, NULL}, + {"lockBonus", Saber_ParseLockBonus, NULL}, + {"parryBonus", Saber_ParseParryBonus, NULL}, + {"breakParryBonus", Saber_ParseBreakParryBonus, NULL}, + {"breakParryBonus2", Saber_ParseBreakParryBonus2, NULL}, + {"disarmBonus", Saber_ParseDisarmBonus, NULL}, + {"disarmBonus2", Saber_ParseDisarmBonus2, NULL}, + {"singleBladeStyle", Saber_ParseSingleBladeStyle, NULL}, + {"singleBladeThrowable", Saber_ParseSingleBladeThrowable, NULL}, + {"brokenSaber1", Saber_ParseBrokenSaber1, NULL}, + {"brokenSaber2", Saber_ParseBrokenSaber2, NULL}, + {"returnDamage", Saber_ParseReturnDamage, NULL}, + {"spinSound", Saber_ParseSpinSound, NULL}, + {"swingSound1", Saber_ParseSwingSound1, NULL}, + {"swingSound2", Saber_ParseSwingSound2, NULL}, + {"swingSound3", Saber_ParseSwingSound3, NULL}, + {"fallSound1", Saber_ParseFallSound1, NULL}, + {"fallSound2", Saber_ParseFallSound2, NULL}, + {"fallSound3", Saber_ParseFallSound3, NULL}, + {"moveSpeedScale", Saber_ParseMoveSpeedScale, NULL}, + {"animSpeedScale", Saber_ParseAnimSpeedScale, NULL}, + {"onInWater", Saber_ParseOnInWater, NULL}, + {"bounceOnWalls", Saber_ParseBounceOnWalls, NULL}, + {"boltToWrist", Saber_ParseBoltToWrist, NULL}, + {"kataMove", Saber_ParseKataMove, NULL}, + {"lungeAtkMove", Saber_ParseLungeAtkMove, NULL}, + {"jumpAtkUpMove", Saber_ParseJumpAtkUpMove, NULL}, + {"jumpAtkFwdMove", Saber_ParseJumpAtkFwdMove, NULL}, + {"jumpAtkBackMove", Saber_ParseJumpAtkBackMove, NULL}, + {"jumpAtkRightMove", Saber_ParseJumpAtkRightMove, NULL}, + {"jumpAtkLeftMove", Saber_ParseJumpAtkLeftMove, NULL}, + {"readyAnim", Saber_ParseReadyAnim, NULL}, + {"drawAnim", Saber_ParseDrawAnim, NULL}, + {"putawayAnim", Saber_ParsePutawayAnim, NULL}, + {"tauntAnim", Saber_ParseTauntAnim, NULL}, + {"bowAnim", Saber_ParseBowAnim, NULL}, + {"meditateAnim", Saber_ParseMeditateAnim, NULL}, + {"flourishAnim", Saber_ParseFlourishAnim, NULL}, + {"gloatAnim", Saber_ParseGloatAnim, NULL}, + {"noRollStab", Saber_ParseNoRollStab, NULL}, + {"noPullAttack", Saber_ParseNoPullAttack, NULL}, + {"noBackAttack", Saber_ParseNoBackAttack, NULL}, + {"noStabDown", Saber_ParseNoStabDown, NULL}, + {"noWallRuns", Saber_ParseNoWallRuns, NULL}, + {"noWallFlips", Saber_ParseNoWallFlips, NULL}, + {"noWallGrab", Saber_ParseNoWallGrab, NULL}, + {"noRolls", Saber_ParseNoRolls, NULL}, + {"noFlips", Saber_ParseNoFlips, NULL}, + {"noCartwheels", Saber_ParseNoCartwheels, NULL}, + {"noKicks", Saber_ParseNoKicks, NULL}, + {"noMirrorAttacks", Saber_ParseNoMirrorAttacks, NULL}, + {"notInMP", Saber_ParseNotInMP, NULL}, + {"bladeStyle2Start", Saber_ParseBladeStyle2Start, NULL}, + {"noWallMarks", Saber_ParseNoWallMarks, NULL}, + {"noWallMarks2", Saber_ParseNoWallMarks2, NULL}, + {"noDlight", Saber_ParseNoDLight, NULL}, + {"noDlight2", Saber_ParseNoDLight2, NULL}, + {"noBlade", Saber_ParseNoBlade, NULL}, + {"noBlade2", Saber_ParseNoBlade2, NULL}, + {"trailStyle", Saber_ParseTrailStyle, NULL}, + {"trailStyle2", Saber_ParseTrailStyle2, NULL}, + {"g2MarksShader", Saber_ParseG2MarksShader, NULL}, + {"g2MarksShader2", Saber_ParseG2MarksShader2, NULL}, + {"g2WeaponMarkShader", Saber_ParseG2WeaponMarkShader, NULL}, + {"g2WeaponMarkShader2", Saber_ParseG2WeaponMarkShader2, NULL}, + {"knockbackScale", Saber_ParseKnockbackScale, NULL}, + {"knockbackScale2", Saber_ParseKnockbackScale2, NULL}, + {"damageScale", Saber_ParseDamageScale, NULL}, + {"damageScale2", Saber_ParseDamageScale2, NULL}, + {"noDismemberment", Saber_ParseNoDismemberment, NULL}, + {"noDismemberment2", Saber_ParseNoDismemberment2, NULL}, + {"noIdleEffect", Saber_ParseNoIdleEffect, NULL}, + {"noIdleEffect2", Saber_ParseNoIdleEffect2, NULL}, + {"alwaysBlock", Saber_ParseAlwaysBlock, NULL}, + {"alwaysBlock2", Saber_ParseAlwaysBlock2, NULL}, + {"noManualDeactivate", Saber_ParseNoManualDeactivate, NULL}, + {"noManualDeactivate2", Saber_ParseNoManualDeactivate2, NULL}, + {"transitionDamage", Saber_ParseTransitionDamage, NULL}, + {"transitionDamage2", Saber_ParseTransitionDamage2, NULL}, + {"splashRadius", Saber_ParseSplashRadius, NULL}, + {"splashRadius2", Saber_ParseSplashRadius2, NULL}, + {"splashDamage", Saber_ParseSplashDamage, NULL}, + {"splashDamage2", Saber_ParseSplashDamage2, NULL}, + {"splashKnockback", Saber_ParseSplashKnockback, NULL}, + {"splashKnockback2", Saber_ParseSplashKnockback2, NULL}, + {"hitSound1", Saber_ParseHitSound1, NULL}, + {"hit2Sound1", Saber_ParseHit2Sound1, NULL}, + {"hitSound2", Saber_ParseHitSound2, NULL}, + {"hit2Sound2", Saber_ParseHit2Sound2, NULL}, + {"hitSound3", Saber_ParseHitSound3, NULL}, + {"hit2Sound3", Saber_ParseHit2Sound3, NULL}, + {"blockSound1", Saber_ParseBlockSound1, NULL}, + {"block2Sound1", Saber_ParseBlock2Sound1, NULL}, + {"blockSound2", Saber_ParseBlockSound2, NULL}, + {"block2Sound2", Saber_ParseBlock2Sound2, NULL}, + {"blockSound3", Saber_ParseBlockSound3, NULL}, + {"block2Sound3", Saber_ParseBlock2Sound3, NULL}, + {"bounceSound1", Saber_ParseBounceSound1, NULL}, + {"bounce2Sound1", Saber_ParseBounce2Sound1, NULL}, + {"bounceSound2", Saber_ParseBounceSound2, NULL}, + {"bounce2Sound2", Saber_ParseBounce2Sound2, NULL}, + {"bounceSound3", Saber_ParseBounceSound3, NULL}, + {"bounce2Sound3", Saber_ParseBounce2Sound3, NULL}, + {"blockEffect", Saber_ParseBlockEffect, NULL}, + {"blockEffect2", Saber_ParseBlockEffect2, NULL}, + {"hitPersonEffect", Saber_ParseHitPersonEffect, NULL}, + {"hitPersonEffect2", Saber_ParseHitPersonEffect2, NULL}, + {"hitOtherEffect", Saber_ParseHitOtherEffect, NULL}, + {"hitOtherEffect2", Saber_ParseHitOtherEffect2, NULL}, + {"bladeEffect", Saber_ParseBladeEffect, NULL}, + {"bladeEffect2", Saber_ParseBladeEffect2, NULL}, + {"noClashFlare", Saber_ParseNoClashFlare, NULL}, + {"noClashFlare2", Saber_ParseNoClashFlare2, NULL}, + {NULL, NULL, NULL}}; static keywordHash_t *saberParseKeywordHash[KEYWORDHASH_SIZE]; static qboolean hashSetup = qfalse; -static void WP_SaberSetupKeywordHash( void ) { +static void WP_SaberSetupKeywordHash(void) { int i; - memset( saberParseKeywordHash, 0, sizeof( saberParseKeywordHash ) ); - for ( i=0; saberParseKeywords[i].keyword; i++ ) - KeywordHash_Add( saberParseKeywordHash, &saberParseKeywords[i] ); + memset(saberParseKeywordHash, 0, sizeof(saberParseKeywordHash)); + for (i = 0; saberParseKeywords[i].keyword; i++) + KeywordHash_Add(saberParseKeywordHash, &saberParseKeywords[i]); hashSetup = qtrue; } -qboolean WP_SaberParseParms( const char *SaberName, saberInfo_t *saber, qboolean setColors ) -{ - const char *token; - const char *p; +qboolean WP_SaberParseParms(const char *SaberName, saberInfo_t *saber, qboolean setColors) { + const char *token; + const char *p; keywordHash_t *key; // make sure the hash table has been setup - if ( !hashSetup ) + if (!hashSetup) WP_SaberSetupKeywordHash(); - if ( !saber ) + if (!saber) return qfalse; - //Set defaults so that, if it fails, there's at least something there - WP_SaberSetDefaults( saber, setColors ); + // Set defaults so that, if it fails, there's at least something there + WP_SaberSetDefaults(saber, setColors); - if ( !VALIDSTRING( SaberName ) ) + if (!VALIDSTRING(SaberName)) return qfalse; - //check if we want to set the sabercolors or not (for if we're loading a savegame) + // check if we want to set the sabercolors or not (for if we're loading a savegame) Saber_SetColor = setColors; - //try to parse it out + // try to parse it out p = SaberParms; COM_ParseSession ps; // look for the right saber - while ( p ) { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) + while (p) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) return qfalse; - if ( !Q_stricmp( token, SaberName ) ) + if (!Q_stricmp(token, SaberName)) break; - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) + if (!p) return qfalse; - saber->name = G_NewString( SaberName ); + saber->name = G_NewString(SaberName); - if ( G_ParseLiteral( &p, "{" ) ) + if (G_ParseLiteral(&p, "{")) return qfalse; // parse the saber info block - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s' (WP_SaberParseParms)\n", SaberName ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s' (WP_SaberParseParms)\n", SaberName); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) + if (!Q_stricmp(token, "}")) break; - key = KeywordHash_Find( saberParseKeywordHash, token ); - if ( key ) { - key->func( saber, &p ); + key = KeywordHash_Find(saberParseKeywordHash, token); + if (key) { + key->func(saber, &p); continue; } - gi.Printf( "WARNING: unknown keyword '%s' while parsing '%s'\n", token, SaberName ); - SkipRestOfLine( &p ); + gi.Printf("WARNING: unknown keyword '%s' while parsing '%s'\n", token, SaberName); + SkipRestOfLine(&p); } - //FIXME: precache the saberModel(s)? + // FIXME: precache the saberModel(s)? - if ( saber->type == SABER_SITH_SWORD ) - {//precache all the sith sword sounds + if (saber->type == SABER_SITH_SWORD) { // precache all the sith sword sounds Saber_SithSwordPrecache(); } return qtrue; } -void WP_RemoveSaber( gentity_t *ent, int saberNum ) -{ - if ( !ent || !ent->client ) - { +void WP_RemoveSaber(gentity_t *ent, int saberNum) { + if (!ent || !ent->client) { return; } - //reset everything for this saber just in case - WP_SaberSetDefaults( &ent->client->ps.saber[saberNum] ); + // reset everything for this saber just in case + WP_SaberSetDefaults(&ent->client->ps.saber[saberNum]); ent->client->ps.dualSabers = qfalse; ent->client->ps.saber[saberNum].Deactivate(); - ent->client->ps.saber[saberNum].SetLength( 0.0f ); - if ( ent->weaponModel[saberNum] > 0 ) - { - gi.G2API_SetSkin( &ent->ghoul2[ent->weaponModel[saberNum]], -1, 0 ); - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[saberNum] ); + ent->client->ps.saber[saberNum].SetLength(0.0f); + if (ent->weaponModel[saberNum] > 0) { + gi.G2API_SetSkin(&ent->ghoul2[ent->weaponModel[saberNum]], -1, 0); + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[saberNum]); ent->weaponModel[saberNum] = -1; } - if ( ent->client->ps.saberAnimLevel == SS_DUAL - || ent->client->ps.saberAnimLevel == SS_STAFF ) - {//change to the style to the default - for ( int i = SS_NONE+1; i < SS_NUM_SABER_STYLES; i++ ) - { - if ( (ent->client->ps.saberStylesKnown&(1<client->ps.saberAnimLevel == SS_DUAL || ent->client->ps.saberAnimLevel == SS_STAFF) { // change to the style to the default + for (int i = SS_NONE + 1; i < SS_NUM_SABER_STYLES; i++) { + if ((ent->client->ps.saberStylesKnown & (1 << i))) { ent->client->ps.saberAnimLevel = i; - if ( ent->s.number < MAX_CLIENTS ) - { + if (ent->s.number < MAX_CLIENTS) { cg.saberAnimLevelPending = ent->client->ps.saberAnimLevel; } break; @@ -2098,40 +2033,32 @@ void WP_RemoveSaber( gentity_t *ent, int saberNum ) } } -void WP_SetSaber( gentity_t *ent, int saberNum, const char *saberName ) -{ - if ( !ent || !ent->client ) - { +void WP_SetSaber(gentity_t *ent, int saberNum, const char *saberName) { + if (!ent || !ent->client) { return; } - if ( Q_stricmp( "none", saberName ) == 0 || Q_stricmp( "remove", saberName ) == 0 ) - { - WP_RemoveSaber( ent, saberNum ); + if (Q_stricmp("none", saberName) == 0 || Q_stricmp("remove", saberName) == 0) { + WP_RemoveSaber(ent, saberNum); return; } - if ( ent->weaponModel[saberNum] > 0 ) - { + if (ent->weaponModel[saberNum] > 0) { gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel[saberNum]); ent->weaponModel[saberNum] = -1; } - WP_SaberParseParms( saberName, &ent->client->ps.saber[saberNum] );//get saber info - if ( ent->client->ps.saber[saberNum].stylesLearned ) - { + WP_SaberParseParms(saberName, &ent->client->ps.saber[saberNum]); // get saber info + if (ent->client->ps.saber[saberNum].stylesLearned) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[saberNum].stylesLearned; } - if ( ent->client->ps.saber[saberNum].singleBladeStyle ) - { + if (ent->client->ps.saber[saberNum].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[saberNum].singleBladeStyle; } - if ( saberNum == 1 && (ent->client->ps.saber[1].saberFlags&SFL_TWO_HANDED) ) - {//not allowed to use a 2-handed saber as second saber - WP_RemoveSaber( ent, saberNum ); + if (saberNum == 1 && (ent->client->ps.saber[1].saberFlags & SFL_TWO_HANDED)) { // not allowed to use a 2-handed saber as second saber + WP_RemoveSaber(ent, saberNum); return; } - G_ModelIndex( ent->client->ps.saber[saberNum].model ); - WP_SaberInitBladeData( ent ); - if ( saberNum == 1 ) - {//now have 2 sabers + G_ModelIndex(ent->client->ps.saber[saberNum].model); + WP_SaberInitBladeData(ent); + if (saberNum == 1) { // now have 2 sabers ent->client->ps.dualSabers = qtrue; } /* @@ -2143,138 +2070,117 @@ void WP_SetSaber( gentity_t *ent, int saberNum, const char *saberName ) } } */ - WP_SaberAddG2SaberModels( ent, saberNum ); - ent->client->ps.saber[saberNum].SetLength( 0.0f ); + WP_SaberAddG2SaberModels(ent, saberNum); + ent->client->ps.saber[saberNum].SetLength(0.0f); ent->client->ps.saber[saberNum].Activate(); - if ( ent->client->ps.saber[saberNum].stylesLearned ) - {//change to the style we're supposed to be using + if (ent->client->ps.saber[saberNum].stylesLearned) { // change to the style we're supposed to be using ent->client->ps.saberStylesKnown |= ent->client->ps.saber[saberNum].stylesLearned; } - if ( ent->client->ps.saber[saberNum].singleBladeStyle ) - { + if (ent->client->ps.saber[saberNum].singleBladeStyle) { ent->client->ps.saberStylesKnown |= ent->client->ps.saber[saberNum].singleBladeStyle; } - WP_UseFirstValidSaberStyle( ent, &ent->client->ps.saberAnimLevel ); - if ( ent->s.number < MAX_CLIENTS ) - { + WP_UseFirstValidSaberStyle(ent, &ent->client->ps.saberAnimLevel); + if (ent->s.number < MAX_CLIENTS) { cg.saberAnimLevelPending = ent->client->ps.saberAnimLevel; } } -void WP_SaberSetColor( gentity_t *ent, int saberNum, int bladeNum, char *colorName ) -{ - if ( !ent || !ent->client ) - { +void WP_SaberSetColor(gentity_t *ent, int saberNum, int bladeNum, char *colorName) { + if (!ent || !ent->client) { return; } - ent->client->ps.saber[saberNum].blade[bladeNum].color = TranslateSaberColor( colorName ); + ent->client->ps.saber[saberNum].blade[bladeNum].color = TranslateSaberColor(colorName); } -extern void WP_SetSaberEntModelSkin( gentity_t *ent, gentity_t *saberent ); -qboolean WP_BreakSaber( gentity_t *ent, const char *surfName, saberType_t saberType ) -{//Make sure there *is* one specified and not using dualSabers - if ( ent == NULL || ent->client == NULL ) - {//invalid ent or client +extern void WP_SetSaberEntModelSkin(gentity_t *ent, gentity_t *saberent); +qboolean WP_BreakSaber(gentity_t *ent, const char *surfName, saberType_t saberType) { // Make sure there *is* one specified and not using dualSabers + if (ent == NULL || ent->client == NULL) { // invalid ent or client return qfalse; } - if ( ent->s.number < MAX_CLIENTS ) - {//player - //if ( g_spskill->integer < 3 ) - {//only on the hardest level? - //FIXME: add a cvar? + if (ent->s.number < MAX_CLIENTS) { // player + // if ( g_spskill->integer < 3 ) + { // only on the hardest level? + // FIXME: add a cvar? return qfalse; } } - if ( ent->health <= 0 ) - {//not if they're dead + if (ent->health <= 0) { // not if they're dead return qfalse; } - if ( ent->client->ps.weapon != WP_SABER ) - {//not holding saber + if (ent->client->ps.weapon != WP_SABER) { // not holding saber return qfalse; } - if ( ent->client->ps.dualSabers ) - {//FIXME: handle this? + if (ent->client->ps.dualSabers) { // FIXME: handle this? return qfalse; } - if ( !ent->client->ps.saber[0].brokenSaber1 ) - {//not breakable into another type of saber + if (!ent->client->ps.saber[0].brokenSaber1) { // not breakable into another type of saber return qfalse; } - if ( PM_SaberInStart( ent->client->ps.saberMove ) //in a start - || PM_SaberInTransition( ent->client->ps.saberMove ) //in a transition - || PM_SaberInAttack( ent->client->ps.saberMove ) )//in an attack - {//don't break when in the middle of an attack + if (PM_SaberInStart(ent->client->ps.saberMove) // in a start + || PM_SaberInTransition(ent->client->ps.saberMove) // in a transition + || PM_SaberInAttack(ent->client->ps.saberMove)) // in an attack + { // don't break when in the middle of an attack return qfalse; } - if ( Q_stricmpn( "w_", surfName, 2 ) - && Q_stricmpn( "saber", surfName, 5 ) //hack because using mod-community made saber - && Q_stricmp( "cylinder01", surfName ) )//hack because using mod-community made saber - {//didn't hit my weapon + if (Q_stricmpn("w_", surfName, 2) && Q_stricmpn("saber", surfName, 5) // hack because using mod-community made saber + && Q_stricmp("cylinder01", surfName)) // hack because using mod-community made saber + { // didn't hit my weapon return qfalse; } - //Sith Sword should ALWAYS do this - if ( saberType != SABER_SITH_SWORD && Q_irand( 0, 50 ) )//&& Q_irand( 0, 10 ) ) - {//10% chance - FIXME: extern this, too? + // Sith Sword should ALWAYS do this + if (saberType != SABER_SITH_SWORD && Q_irand(0, 50)) //&& Q_irand( 0, 10 ) ) + { // 10% chance - FIXME: extern this, too? return qfalse; } - //break it - char *replacementSaber1 = G_NewString( ent->client->ps.saber[0].brokenSaber1 ); - char *replacementSaber2 = G_NewString( ent->client->ps.saber[0].brokenSaber2 ); - int i, originalNumBlades = ent->client->ps.saber[0].numBlades; - qboolean broken = qfalse; - saber_colors_t colors[MAX_BLADES]; + // break it + char *replacementSaber1 = G_NewString(ent->client->ps.saber[0].brokenSaber1); + char *replacementSaber2 = G_NewString(ent->client->ps.saber[0].brokenSaber2); + int i, originalNumBlades = ent->client->ps.saber[0].numBlades; + qboolean broken = qfalse; + saber_colors_t colors[MAX_BLADES]; - //store the colors - for ( i = 0; i < MAX_BLADES; i++ ) - { + // store the colors + for (i = 0; i < MAX_BLADES; i++) { colors[i] = ent->client->ps.saber[0].blade[i].color; } - //FIXME: chance of dropping the right-hand one? Based on damage, or...? - //FIXME: sound & effect when this happens, and send them into a broken parry? + // FIXME: chance of dropping the right-hand one? Based on damage, or...? + // FIXME: sound & effect when this happens, and send them into a broken parry? - //remove saber[0], replace with replacementSaber1 - if ( replacementSaber1 ) - { - WP_RemoveSaber( ent, 0 ); - WP_SetSaber( ent, 0, replacementSaber1 ); - for ( i = 0; i < ent->client->ps.saber[0].numBlades; i++ ) - { + // remove saber[0], replace with replacementSaber1 + if (replacementSaber1) { + WP_RemoveSaber(ent, 0); + WP_SetSaber(ent, 0, replacementSaber1); + for (i = 0; i < ent->client->ps.saber[0].numBlades; i++) { ent->client->ps.saber[0].blade[i].color = colors[i]; } broken = qtrue; - //change my saberent's model and skin to match my new right-hand saber - WP_SetSaberEntModelSkin( ent, &g_entities[ent->client->ps.saberEntityNum] ); - } - - if ( originalNumBlades <= 1 ) - {//nothing to split off - //FIXME: handle this? - } - else - { - //remove saber[1], replace with replacementSaber2 - if ( replacementSaber2 ) - {//FIXME: 25% chance that it just breaks - just spawn the second saber piece and toss it away immediately, can't be picked up. - //shouldn't be one in this hand, but just in case, remove it - WP_RemoveSaber( ent, 1 ); - WP_SetSaber( ent, 1, replacementSaber2 ); - - //put the remainder of the original saber's blade colors onto this saber's blade(s) - for ( i = ent->client->ps.saber[0].numBlades; i < MAX_BLADES; i++ ) - { - ent->client->ps.saber[1].blade[i-ent->client->ps.saber[0].numBlades].color = colors[i]; + // change my saberent's model and skin to match my new right-hand saber + WP_SetSaberEntModelSkin(ent, &g_entities[ent->client->ps.saberEntityNum]); + } + + if (originalNumBlades <= 1) { // nothing to split off + // FIXME: handle this? + } else { + // remove saber[1], replace with replacementSaber2 + if (replacementSaber2) { // FIXME: 25% chance that it just breaks - just spawn the second saber piece and toss it away immediately, can't be picked up. + // shouldn't be one in this hand, but just in case, remove it + WP_RemoveSaber(ent, 1); + WP_SetSaber(ent, 1, replacementSaber2); + + // put the remainder of the original saber's blade colors onto this saber's blade(s) + for (i = ent->client->ps.saber[0].numBlades; i < MAX_BLADES; i++) { + ent->client->ps.saber[1].blade[i - ent->client->ps.saber[0].numBlades].color = colors[i]; } broken = qtrue; } @@ -2282,48 +2188,42 @@ qboolean WP_BreakSaber( gentity_t *ent, const char *surfName, saberType_t saberT return broken; } -void WP_SaberLoadParms( void ) -{ - int len, totallen, saberExtFNLen, fileCnt, i; - char *buffer, *holdChar, *marker; - char saberExtensionListBuf[2048]; // The list of file names read in +void WP_SaberLoadParms(void) { + int len, totallen, saberExtFNLen, fileCnt, i; + char *buffer, *holdChar, *marker; + char saberExtensionListBuf[2048]; // The list of file names read in - //gi.Printf( "Parsing *.sab saber definitions\n" ); + // gi.Printf( "Parsing *.sab saber definitions\n" ); - //set where to store the first one + // set where to store the first one totallen = 0; marker = SaberParms; marker[0] = '\0'; - //now load in the .sab definitions - fileCnt = gi.FS_GetFileList("ext_data/sabers", ".sab", saberExtensionListBuf, sizeof(saberExtensionListBuf) ); + // now load in the .sab definitions + fileCnt = gi.FS_GetFileList("ext_data/sabers", ".sab", saberExtensionListBuf, sizeof(saberExtensionListBuf)); holdChar = saberExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += saberExtFNLen + 1 ) - { - saberExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += saberExtFNLen + 1) { + saberExtFNLen = strlen(holdChar); - len = gi.FS_ReadFile( va( "ext_data/sabers/%s", holdChar), (void **) &buffer ); + len = gi.FS_ReadFile(va("ext_data/sabers/%s", holdChar), (void **)&buffer); - if ( len == -1 ) - { - gi.Printf( "WP_SaberLoadParms: error reading %s\n", holdChar ); - } - else - { - if ( totallen && *(marker-1) == '}' ) - {//don't let it end on a } because that should be a stand-alone token - strcat( marker, " " ); + if (len == -1) { + gi.Printf("WP_SaberLoadParms: error reading %s\n", holdChar); + } else { + if (totallen && *(marker - 1) == '}') { // don't let it end on a } because that should be a stand-alone token + strcat(marker, " "); totallen++; marker++; } - len = COM_Compress( buffer ); + len = COM_Compress(buffer); - if ( totallen + len >= MAX_SABER_DATA_SIZE ) { - G_Error( "WP_SaberLoadParms: ran out of space before reading %s\n(you must make the .sab files smaller)", holdChar ); + if (totallen + len >= MAX_SABER_DATA_SIZE) { + G_Error("WP_SaberLoadParms: ran out of space before reading %s\n(you must make the .sab files smaller)", holdChar); } - strcat( marker, buffer ); - gi.FS_FreeFile( buffer ); + strcat(marker, buffer); + gi.FS_FreeFile(buffer); totallen += len; marker += len; diff --git a/code/game/wp_stun_baton.cpp b/code/game/wp_stun_baton.cpp index 8c2273d8e3..44260f7388 100644 --- a/code/game/wp_stun_baton.cpp +++ b/code/game/wp_stun_baton.cpp @@ -27,43 +27,39 @@ along with this program; if not, see . #include "w_local.h" //--------------------------------------------------------- -void WP_FireStunBaton( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end, start; +void WP_FireStunBaton(gentity_t *ent, qboolean alt_fire) { + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end, start; - G_Sound( ent, G_SoundIndex( "sound/weapons/baton/fire" )); + G_Sound(ent, G_SoundIndex("sound/weapons/baton/fire")); - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); - VectorMA( start, STUN_BATON_RANGE, forwardVec, end ); + VectorMA(start, STUN_BATON_RANGE, forwardVec, end); - VectorSet( maxs, 5, 5, 5 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 5, 5, 5); + VectorScale(maxs, -1, mins); - gi.trace ( &tr, start, mins, maxs, end, ent->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP, (EG2_Collision)0, 0 ); + gi.trace(&tr, start, mins, maxs, end, ent->s.number, CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP, (EG2_Collision)0, 0); - if ( tr.entityNum >= ENTITYNUM_WORLD || tr.entityNum < 0 ) - { + if (tr.entityNum >= ENTITYNUM_WORLD || tr.entityNum < 0) { return; } tr_ent = &g_entities[tr.entityNum]; - if ( tr_ent && tr_ent->takedamage && tr_ent->client ) - { - G_PlayEffect( "stunBaton/flesh_impact", tr.endpos, tr.plane.normal ); + if (tr_ent && tr_ent->takedamage && tr_ent->client) { + G_PlayEffect("stunBaton/flesh_impact", tr.endpos, tr.plane.normal); // TEMP! -// G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + // G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); tr_ent->client->ps.powerups[PW_SHOCKED] = level.time + 1500; - G_Damage( tr_ent, ent, ent, forwardVec, tr.endpos, weaponData[WP_STUN_BATON].damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else if ( tr_ent->svFlags & SVF_GLASS_BRUSH || ( tr_ent->svFlags & SVF_BBRUSH && tr_ent->material == 12 )) // material grate...we are breaking a grate! + G_Damage(tr_ent, ent, ent, forwardVec, tr.endpos, weaponData[WP_STUN_BATON].damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else if (tr_ent->svFlags & SVF_GLASS_BRUSH || (tr_ent->svFlags & SVF_BBRUSH && tr_ent->material == 12)) // material grate...we are breaking a grate! { - G_Damage( tr_ent, ent, ent, forwardVec, tr.endpos, 999, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); // smash that puppy + G_Damage(tr_ent, ent, ent, forwardVec, tr.endpos, 999, DAMAGE_NO_KNOCKBACK, MOD_MELEE); // smash that puppy } } \ No newline at end of file diff --git a/code/game/wp_thermal.cpp b/code/game/wp_thermal.cpp index 928df9fd7e..0b63e68bd2 100644 --- a/code/game/wp_thermal.cpp +++ b/code/game/wp_thermal.cpp @@ -31,300 +31,243 @@ along with this program; if not, see . //--------------------- //--------------------------------------------------------- -void thermalDetonatorExplode( gentity_t *ent ) +void thermalDetonatorExplode(gentity_t *ent) //--------------------------------------------------------- { - if ( (ent->s.eFlags&EF_HELD_BY_SAND_CREATURE) ) - { + if ((ent->s.eFlags & EF_HELD_BY_SAND_CREATURE)) { ent->takedamage = qfalse; // don't allow double deaths! - G_Damage( ent->activator, ent, ent->owner, vec3_origin, ent->currentOrigin, weaponData[WP_THERMAL].altDamage, 0, MOD_EXPLOSIVE ); - G_PlayEffect( "thermal/explosion", ent->currentOrigin ); - G_PlayEffect( "thermal/shockwave", ent->currentOrigin ); + G_Damage(ent->activator, ent, ent->owner, vec3_origin, ent->currentOrigin, weaponData[WP_THERMAL].altDamage, 0, MOD_EXPLOSIVE); + G_PlayEffect("thermal/explosion", ent->currentOrigin); + G_PlayEffect("thermal/shockwave", ent->currentOrigin); - G_FreeEntity( ent ); - } - else if ( !ent->count ) - { - G_Sound( ent, G_SoundIndex( "sound/weapons/thermal/warning.wav" ) ); + G_FreeEntity(ent); + } else if (!ent->count) { + G_Sound(ent, G_SoundIndex("sound/weapons/thermal/warning.wav")); ent->count = 1; ent->nextthink = level.time + 800; - ent->svFlags |= SVF_BROADCAST;//so everyone hears/sees the explosion? - } - else - { - vec3_t pos; + ent->svFlags |= SVF_BROADCAST; // so everyone hears/sees the explosion? + } else { + vec3_t pos; - VectorSet( pos, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + 8 ); + VectorSet(pos, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + 8); ent->takedamage = qfalse; // don't allow double deaths! - G_RadiusDamage( ent->currentOrigin, ent->owner, weaponData[WP_THERMAL].splashDamage, weaponData[WP_THERMAL].splashRadius, NULL, MOD_EXPLOSIVE_SPLASH ); + G_RadiusDamage(ent->currentOrigin, ent->owner, weaponData[WP_THERMAL].splashDamage, weaponData[WP_THERMAL].splashRadius, NULL, MOD_EXPLOSIVE_SPLASH); - G_PlayEffect( "thermal/explosion", ent->currentOrigin ); - G_PlayEffect( "thermal/shockwave", ent->currentOrigin ); + G_PlayEffect("thermal/explosion", ent->currentOrigin); + G_PlayEffect("thermal/shockwave", ent->currentOrigin); - G_FreeEntity( ent ); + G_FreeEntity(ent); } } //------------------------------------------------------------------------------------------------------------- -void thermal_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) +void thermal_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) //------------------------------------------------------------------------------------------------------------- { - thermalDetonatorExplode( self ); + thermalDetonatorExplode(self); } //--------------------------------------------------------- -qboolean WP_LobFire( gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, - vec3_t velocity, qboolean tracePath, int ignoreEntNum, int enemyNum, - float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit ) +qboolean WP_LobFire(gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, vec3_t velocity, qboolean tracePath, int ignoreEntNum, + int enemyNum, float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit) //--------------------------------------------------------- { - float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, - vec3_t targetDir, shotVel, failCase = { 0.0f }; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; - vec3_t lastPos, testPos; - gentity_t *traceEnt; - - if ( !idealSpeed ) - { + float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, + vec3_t targetDir, shotVel, failCase = {0.0f}; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; + vec3_t lastPos, testPos; + gentity_t *traceEnt; + + if (!idealSpeed) { idealSpeed = 300; - } - else if ( idealSpeed < speedInc ) - { + } else if (idealSpeed < speedInc) { idealSpeed = speedInc; } shotSpeed = idealSpeed; - skipNum = (idealSpeed-speedInc)/speedInc; - if ( !minSpeed ) - { + skipNum = (idealSpeed - speedInc) / speedInc; + if (!minSpeed) { minSpeed = 100; } - if ( !maxSpeed ) - { + if (!maxSpeed) { maxSpeed = 900; } - while ( hitCount < maxHits ) - { - VectorSubtract( target, start, targetDir ); - targetDist = VectorNormalize( targetDir ); + while (hitCount < maxHits) { + VectorSubtract(target, start, targetDir); + targetDist = VectorNormalize(targetDir); - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * g_gravity->value; - if ( !hitCount ) - {//save the first (ideal) one as the failCase (fallback value) - if ( !mustHit ) - {//default is fine as a return value - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first (ideal) one as the failCase (fallback value) + if (!mustHit) { // default is fine as a return value + VectorCopy(shotVel, failCase); } } - if ( tracePath ) - {//do a rough trace of the path + if (tracePath) { // do a rough trace of the path blocked = qfalse; - VectorCopy( start, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(start, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( start, lastPos ); - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); + VectorCopy(start, lastPos); + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace + // just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - gi.trace( &trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, (EG2_Collision)0, 0 ); + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + gi.trace(&trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, (EG2_Collision)0, 0); - if ( trace.allsolid || trace.startsolid ) - { + if (trace.allsolid || trace.startsolid) { blocked = qtrue; break; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.entityNum == enemyNum ) - {//hit the enemy, that's perfect! + if (trace.fraction < 1.0f) { // hit something + if (trace.entityNum == enemyNum) { // hit the enemy, that's perfect! break; - } - else if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, target ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + } else if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, target) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, target ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, target); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; - //see if we should store this as the failCase - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit an ent + // see if we should store this as the failCase + if (trace.entityNum < ENTITYNUM_WORLD) { // hit an ent traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && traceEnt->takedamage && !OnSameTeam( self, traceEnt ) ) - {//hit something breakable, so that's okay - //we haven't found a clear shot yet so use this as the failcase - VectorCopy( shotVel, failCase ); + if (traceEnt && traceEnt->takedamage && !OnSameTeam(self, traceEnt)) { // hit something breakable, so that's okay + // we haven't found a clear shot yet so use this as the failcase + VectorCopy(shotVel, failCase); } } break; } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear + if (elapsedTime == floor(travelTime)) { // reached end, all clear break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - shotSpeed = idealSpeed + ((hitCount-skipNum) * speedInc);//from min to max (skipping ideal) - if ( hitCount >= skipNum ) - {//skip ideal since that was the first value we tested + shotSpeed = idealSpeed + ((hitCount - skipNum) * speedInc); // from min to max (skipping ideal) + if (hitCount >= skipNum) { // skip ideal since that was the first value we tested shotSpeed += speedInc; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) - assert( (failCase[0] + failCase[1] + failCase[2]) > 0.0f ); - VectorCopy( failCase, velocity ); + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + assert((failCase[0] + failCase[1] + failCase[2]) > 0.0f); + VectorCopy(failCase, velocity); return qfalse; } - VectorCopy( shotVel, velocity ); + VectorCopy(shotVel, velocity); return qtrue; } //--------------------------------------------------------- -void WP_ThermalThink( gentity_t *ent ) +void WP_ThermalThink(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // Thermal detonators for the player do occasional radius checks and blow up if there are entities in the blast radius // This is done so that the main fire is actually useful as an attack. We explode anyway after delay expires. - if ( (ent->s.eFlags&EF_HELD_BY_SAND_CREATURE) ) - {//blow once creature is underground (done with anim) - //FIXME: chance of being spit out? Especially if lots of delay left... - ent->e_TouchFunc = touchF_NULL;//don't impact on anything - if ( !ent->activator - || !ent->activator->client - || !ent->activator->client->ps.legsAnimTimer ) - {//either something happened to the sand creature or it's done with it's attack anim - //blow! + if ((ent->s.eFlags & EF_HELD_BY_SAND_CREATURE)) { // blow once creature is underground (done with anim) + // FIXME: chance of being spit out? Especially if lots of delay left... + ent->e_TouchFunc = touchF_NULL; // don't impact on anything + if (!ent->activator || !ent->activator->client || + !ent->activator->client->ps.legsAnimTimer) { // either something happened to the sand creature or it's done with it's attack anim + // blow! ent->e_ThinkFunc = thinkF_thermalDetonatorExplode; - ent->nextthink = level.time + Q_irand( 50, 2000 ); - } - else - {//keep checking + ent->nextthink = level.time + Q_irand(50, 2000); + } else { // keep checking ent->nextthink = level.time + TD_THINK_TIME; } return; - } - else if ( ent->delay > level.time ) - { + } else if (ent->delay > level.time) { // Finally, we force it to bounce at least once before doing the special checks, otherwise it's just too easy for the player? - if ( ent->has_bounced ) - { - count = G_RadiusList( ent->currentOrigin, TD_TEST_RAD, ent, qtrue, ent_list ); - - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->s.number == 0 ) - { + if (ent->has_bounced) { + count = G_RadiusList(ent->currentOrigin, TD_TEST_RAD, ent, qtrue, ent_list); + + for (int i = 0; i < count; i++) { + if (ent_list[i]->s.number == 0) { // avoid deliberately blowing up next to the player, no matter how close any enemy is.. // ...if the delay time expires though, there is no saving the player...muwhaaa haa ha blow = qfalse; break; - } - else if ( ent_list[i]->client - && ent_list[i]->client->NPC_class != CLASS_SAND_CREATURE//ignore sand creatures - && ent_list[i]->health > 0 ) - { - //FIXME! sometimes the ent_list order changes, so we should make sure that the player isn't anywhere in this list + } else if (ent_list[i]->client && ent_list[i]->client->NPC_class != CLASS_SAND_CREATURE // ignore sand creatures + && ent_list[i]->health > 0) { + // FIXME! sometimes the ent_list order changes, so we should make sure that the player isn't anywhere in this list blow = qtrue; } } } - } - else - { + } else { // our death time has arrived, even if nothing is near us blow = qtrue; } - if ( blow ) - { + if (blow) { ent->e_ThinkFunc = thinkF_thermalDetonatorExplode; ent->nextthink = level.time + 50; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + TD_THINK_TIME; } } //--------------------------------------------------------- -gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) +gentity_t *WP_FireThermalDetonator(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - gentity_t *bolt; - vec3_t dir, start; - float damageScale = 1.0f; + gentity_t *bolt; + vec3_t dir, start; + float damageScale = 1.0f; - VectorCopy( forwardVec, dir ); - VectorCopy( muzzle, start ); + VectorCopy(forwardVec, dir); + VectorCopy(muzzle, start); bolt = G_Spawn(); bolt->classname = "thermal_detonator"; - if ( ent->s.number != 0 ) - { + if (ent->s.number != 0) { // If not the player, cut the damage a bit so we don't get pounded on so much damageScale = TD_NPC_DAMAGE_CUT; } - if ( !alt_fire && ent->s.number == 0 ) - { + if (!alt_fire && ent->s.number == 0) { // Main fires for the players do a little bit of extra thinking bolt->e_ThinkFunc = thinkF_WP_ThermalThink; bolt->nextthink = level.time + TD_THINK_TIME; bolt->delay = level.time + TD_TIME; // How long 'til she blows - } - else - { + } else { bolt->e_ThinkFunc = thinkF_thermalDetonatorExplode; bolt->nextthink = level.time + TD_TIME; // How long 'til she blows } @@ -332,8 +275,8 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->mass = 10; // How 'bout we give this thing a size... - VectorSet( bolt->mins, -4.0f, -4.0f, -4.0f ); - VectorSet( bolt->maxs, 4.0f, 4.0f, 4.0f ); + VectorSet(bolt->mins, -4.0f, -4.0f, -4.0f); + VectorSet(bolt->maxs, 4.0f, 4.0f, 4.0f); bolt->clipmask = MASK_SHOT; bolt->clipmask &= ~CONTENTS_CORPSE; bolt->contents = CONTENTS_SHOTCLIP; @@ -341,34 +284,28 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->health = 15; bolt->e_DieFunc = dieF_thermal_die; - WP_TraceSetStart( ent, start, bolt->mins, bolt->maxs );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, bolt->mins, bolt->maxs); // make sure our start point isn't on the other side of a wall float chargeAmount = 1.0f; // default of full charge - if ( ent->client ) - { + if (ent->client) { chargeAmount = level.time - ent->client->ps.weaponChargeTime; } // get charge amount chargeAmount = chargeAmount / (float)TD_VELOCITY; - if ( chargeAmount > 1.0f ) - { + if (chargeAmount > 1.0f) { chargeAmount = 1.0f; - } - else if ( chargeAmount < TD_MIN_CHARGE ) - { + } else if (chargeAmount < TD_MIN_CHARGE) { chargeAmount = TD_MIN_CHARGE; } - float thrownSpeed = TD_VELOCITY; - const qboolean thisIsAShooter = (qboolean)!Q_stricmp( "misc_weapon_shooter", ent->classname); + float thrownSpeed = TD_VELOCITY; + const qboolean thisIsAShooter = (qboolean)!Q_stricmp("misc_weapon_shooter", ent->classname); - if (thisIsAShooter) - { - if (ent->delay != 0) - { + if (thisIsAShooter) { + if (ent->delay != 0) { thrownSpeed = ent->delay; } } @@ -376,49 +313,40 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) // normal ones bounce, alt ones explode on impact bolt->s.pos.trType = TR_GRAVITY; bolt->owner = ent; - VectorScale( dir, thrownSpeed * chargeAmount, bolt->s.pos.trDelta ); + VectorScale(dir, thrownSpeed * chargeAmount, bolt->s.pos.trDelta); - if ( ent->health > 0 ) - { + if (ent->health > 0) { bolt->s.pos.trDelta[2] += 120; - if ( (ent->NPC || (ent->s.number && thisIsAShooter) ) - && ent->enemy ) - {//NPC or misc_weapon_shooter - //FIXME: we're assuming he's actually facing this direction... - vec3_t target; - - VectorCopy( ent->enemy->currentOrigin, target ); - if ( target[2] <= start[2] ) - { - vec3_t vec; - VectorSubtract( target, start, vec ); - VectorNormalize( vec ); - VectorMA( target, Q_flrand( 0, -32 ), vec, target );//throw a little short + if ((ent->NPC || (ent->s.number && thisIsAShooter)) && ent->enemy) { // NPC or misc_weapon_shooter + // FIXME: we're assuming he's actually facing this direction... + vec3_t target; + + VectorCopy(ent->enemy->currentOrigin, target); + if (target[2] <= start[2]) { + vec3_t vec; + VectorSubtract(target, start, vec); + VectorNormalize(vec); + VectorMA(target, Q_flrand(0, -32), vec, target); // throw a little short } - target[0] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); - target[1] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); - target[2] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); + target[0] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); + target[1] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); + target[2] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); - WP_LobFire( ent, start, target, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number ); - } - else if ( thisIsAShooter && ent->target && !VectorCompare( ent->pos1, vec3_origin ) ) - {//misc_weapon_shooter firing at a position - WP_LobFire( ent, start, ent->pos1, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number ); + WP_LobFire(ent, start, target, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number); + } else if (thisIsAShooter && ent->target && !VectorCompare(ent->pos1, vec3_origin)) { // misc_weapon_shooter firing at a position + WP_LobFire(ent, start, ent->pos1, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number); } } - if ( alt_fire ) - { + if (alt_fire) { bolt->alt_fire = qtrue; - } - else - { + } else { bolt->s.eFlags |= EF_BOUNCE_HALF; } - bolt->s.loopSound = G_SoundIndex( "sound/weapons/thermal/thermloop.wav" ); + bolt->s.loopSound = G_SoundIndex("sound/weapons/thermal/thermloop.wav"); bolt->damage = weaponData[WP_THERMAL].damage * damageScale; bolt->dflags = 0; @@ -429,33 +357,30 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->svFlags = SVF_USE_CURRENT_ORIGIN; bolt->s.weapon = WP_THERMAL; - if ( alt_fire ) - { + if (alt_fire) { bolt->methodOfDeath = MOD_THERMAL_ALT; - bolt->splashMethodOfDeath = MOD_THERMAL_ALT;//? SPLASH; - } - else - { + bolt->splashMethodOfDeath = MOD_THERMAL_ALT; //? SPLASH; + } else { bolt->methodOfDeath = MOD_THERMAL; - bolt->splashMethodOfDeath = MOD_THERMAL;//? SPLASH; + bolt->splashMethodOfDeath = MOD_THERMAL; //? SPLASH; } - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, bolt->s.pos.trBase ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, bolt->s.pos.trBase); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy (start, bolt->currentOrigin); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->currentOrigin); - VectorCopy( start, bolt->pos2 ); + VectorCopy(start, bolt->pos2); return bolt; } //--------------------------------------------------------- -gentity_t *WP_DropThermal( gentity_t *ent ) +gentity_t *WP_DropThermal(gentity_t *ent) //--------------------------------------------------------- { - AngleVectors( ent->client->ps.viewangles, forwardVec, vrightVec, up ); - CalcEntitySpot( ent, SPOT_WEAPON, muzzle ); - return (WP_FireThermalDetonator( ent, qfalse )); + AngleVectors(ent->client->ps.viewangles, forwardVec, vrightVec, up); + CalcEntitySpot(ent, SPOT_WEAPON, muzzle); + return (WP_FireThermalDetonator(ent, qfalse)); } diff --git a/code/game/wp_trip_mine.cpp b/code/game/wp_trip_mine.cpp index db9d5fc0d9..d5c3baa06e 100644 --- a/code/game/wp_trip_mine.cpp +++ b/code/game/wp_trip_mine.cpp @@ -31,20 +31,20 @@ along with this program; if not, see . //----------------------- #define PROXIMITY_STYLE 1 -#define TRIPWIRE_STYLE 2 +#define TRIPWIRE_STYLE 2 //--------------------------------------------------------- -void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) +void touchLaserTrap(gentity_t *ent, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { ent->s.eType = ET_GENERAL; // a tripwire so add draw line flag - VectorCopy( trace->plane.normal, ent->movedir ); + VectorCopy(trace->plane.normal, ent->movedir); // make it shootable - VectorSet( ent->mins, -4, -4, -4 ); - VectorSet( ent->maxs, 4, 4, 4 ); + VectorSet(ent->mins, -4, -4, -4); + VectorSet(ent->maxs, 4, 4, 4); ent->clipmask = MASK_SHOT; ent->contents = CONTENTS_SHOTCLIP; @@ -58,20 +58,17 @@ void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) ent->activator = ent->owner; ent->owner = NULL; - WP_Stick( ent, trace ); + WP_Stick(ent, trace); - if ( ent->count == TRIPWIRE_STYLE ) - { - vec3_t mins = {-4,-4,-4}, maxs = {4,4,4};//FIXME: global these - trace_t tr; - VectorMA( ent->currentOrigin, 32, ent->movedir, ent->s.origin2 ); - gi.trace( &tr, ent->s.origin2, mins, maxs, ent->currentOrigin, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); - VectorCopy( tr.endpos, ent->s.origin2 ); + if (ent->count == TRIPWIRE_STYLE) { + vec3_t mins = {-4, -4, -4}, maxs = {4, 4, 4}; // FIXME: global these + trace_t tr; + VectorMA(ent->currentOrigin, 32, ent->movedir, ent->s.origin2); + gi.trace(&tr, ent->s.origin2, mins, maxs, ent->currentOrigin, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0); + VectorCopy(tr.endpos, ent->s.origin2); ent->e_ThinkFunc = thinkF_laserTrapThink; - } - else - { + } else { ent->e_ThinkFunc = thinkF_WP_prox_mine_think; } @@ -80,68 +77,58 @@ void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) // copied from flechette prox above...which will not be used if this gets approved //--------------------------------------------------------- -void WP_prox_mine_think( gentity_t *ent ) +void WP_prox_mine_think(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // first time through? - if ( ent->count ) - { + if (ent->count) { // play activated warning ent->count = 0; ent->s.eFlags |= EF_PROX_TRIP; - G_Sound( ent, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" )); + G_Sound(ent, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); } // if it isn't time to auto-explode, do a small proximity check - if ( ent->delay > level.time ) - { - count = G_RadiusList( ent->currentOrigin, PROX_MINE_RADIUS_CHECK, ent, qtrue, ent_list ); + if (ent->delay > level.time) { + count = G_RadiusList(ent->currentOrigin, PROX_MINE_RADIUS_CHECK, ent, qtrue, ent_list); - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number ) - { + for (int i = 0; i < count; i++) { + if (ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number) { blow = qtrue; break; } } - } - else - { + } else { // well, we must die now blow = qtrue; } - if ( blow ) - { -// G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); + if (blow) { + // G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); ent->e_ThinkFunc = thinkF_WP_Explode; ent->nextthink = level.time + 200; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + 500; } } //--------------------------------------------------------- -void laserTrapThink( gentity_t *ent ) +void laserTrapThink(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *traceEnt; - vec3_t end, mins = {-4,-4,-4}, maxs = {4,4,4}; - trace_t tr; + gentity_t *traceEnt; + vec3_t end, mins = {-4, -4, -4}, maxs = {4, 4, 4}; + trace_t tr; // turn on the beam effect - if ( !(ent->s.eFlags & EF_FIRING )) - { + if (!(ent->s.eFlags & EF_FIRING)) { // arm me - G_Sound( ent, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" )); - ent->s.loopSound = G_SoundIndex( "sound/weapons/laser_trap/hum_loop.wav" ); + G_Sound(ent, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); + ent->s.loopSound = G_SoundIndex("sound/weapons/laser_trap/hum_loop.wav"); ent->s.eFlags |= EF_FIRING; } @@ -149,22 +136,19 @@ void laserTrapThink( gentity_t *ent ) ent->nextthink = level.time + FRAMETIME; // Find the main impact point - VectorMA( ent->s.pos.trBase, 2048, ent->movedir, end ); - gi.trace( &tr, ent->s.origin2, mins, maxs, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); + VectorMA(ent->s.pos.trBase, 2048, ent->movedir, end); + gi.trace(&tr, ent->s.origin2, mins, maxs, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0); - traceEnt = &g_entities[ tr.entityNum ]; + traceEnt = &g_entities[tr.entityNum]; // Adjust this so that the effect has a relatively fresh endpoint - VectorCopy( tr.endpos, ent->pos4 ); + VectorCopy(tr.endpos, ent->pos4); - if ( traceEnt->client || tr.startsolid ) - { + if (traceEnt->client || tr.startsolid) { // go boom - WP_Explode( ent ); + WP_Explode(ent); ent->s.eFlags &= ~EF_FIRING; // don't draw beam if we are dead - } - else - { + } else { /* // FIXME: they need to avoid the beam! AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); @@ -174,11 +158,10 @@ void laserTrapThink( gentity_t *ent ) } //--------------------------------------------------------- -void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) +void CreateLaserTrap(gentity_t *laserTrap, vec3_t start, gentity_t *owner) //--------------------------------------------------------- { - if ( !VALIDSTRING( laserTrap->classname )) - { + if (!VALIDSTRING(laserTrap->classname)) { // since we may be coming from a map placed trip mine, we don't want to override that class name.... // That would be bad because the player drop code tries to limit number of placed items...so it would have removed map placed ones as well. laserTrap->classname = "tripmine"; @@ -188,47 +171,46 @@ void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) laserTrap->splashRadius = weaponData[WP_TRIP_MINE].splashRadius; laserTrap->damage = weaponData[WP_TRIP_MINE].damage; laserTrap->methodOfDeath = MOD_LASERTRIP; - laserTrap->splashMethodOfDeath = MOD_LASERTRIP;//? SPLASH; + laserTrap->splashMethodOfDeath = MOD_LASERTRIP; //? SPLASH; laserTrap->s.eType = ET_MISSILE; laserTrap->svFlags = SVF_USE_CURRENT_ORIGIN; laserTrap->s.weapon = WP_TRIP_MINE; laserTrap->owner = owner; -// VectorSet( laserTrap->mins, -LT_SIZE, -LT_SIZE, -LT_SIZE ); -// VectorSet( laserTrap->maxs, LT_SIZE, LT_SIZE, LT_SIZE ); - laserTrap->clipmask = (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP);//MASK_SHOT; + // VectorSet( laserTrap->mins, -LT_SIZE, -LT_SIZE, -LT_SIZE ); + // VectorSet( laserTrap->maxs, LT_SIZE, LT_SIZE, LT_SIZE ); + laserTrap->clipmask = (CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP); // MASK_SHOT; - laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, laserTrap->s.pos.trBase ); - VectorCopy( start, laserTrap->currentOrigin); + laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, laserTrap->s.pos.trBase); + VectorCopy(start, laserTrap->currentOrigin); - VectorCopy( start, laserTrap->pos2 ); // ?? wtf ? + VectorCopy(start, laserTrap->pos2); // ?? wtf ? - laserTrap->fxID = G_EffectIndex( "tripMine/explosion" ); + laserTrap->fxID = G_EffectIndex("tripMine/explosion"); laserTrap->e_TouchFunc = touchF_touchLaserTrap; laserTrap->s.radius = 60; - VectorSet( laserTrap->s.modelScale, 1.0f, 1.0f, 1.0f ); - gi.G2API_InitGhoul2Model( laserTrap->ghoul2, weaponData[WP_TRIP_MINE].missileMdl, G_ModelIndex( weaponData[WP_TRIP_MINE].missileMdl ), - NULL_HANDLE, NULL_HANDLE, 0, 0); + VectorSet(laserTrap->s.modelScale, 1.0f, 1.0f, 1.0f); + gi.G2API_InitGhoul2Model(laserTrap->ghoul2, weaponData[WP_TRIP_MINE].missileMdl, G_ModelIndex(weaponData[WP_TRIP_MINE].missileMdl), NULL_HANDLE, + NULL_HANDLE, 0, 0); } //--------------------------------------------------------- -static void WP_RemoveOldTraps( gentity_t *ent ) +static void WP_RemoveOldTraps(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *found = NULL; - int trapcount = 0, i; - int foundLaserTraps[MAX_GENTITIES] = {ENTITYNUM_NONE}; - int trapcount_org, lowestTimeStamp; - int removeMe; + gentity_t *found = NULL; + int trapcount = 0, i; + int foundLaserTraps[MAX_GENTITIES] = {ENTITYNUM_NONE}; + int trapcount_org, lowestTimeStamp; + int removeMe; // see how many there are now - while (( found = G_Find( found, FOFS(classname), "tripmine" )) != NULL ) - { - if ( found->activator != ent ) // activator is really the owner? + while ((found = G_Find(found, FOFS(classname), "tripmine")) != NULL) { + if (found->activator != ent) // activator is really the owner? { continue; } @@ -240,80 +222,66 @@ static void WP_RemoveOldTraps( gentity_t *ent ) trapcount_org = trapcount; lowestTimeStamp = level.time; - while ( trapcount > 9 ) - { + while (trapcount > 9) { removeMe = -1; - for ( i = 0; i < trapcount_org; i++ ) - { - if ( foundLaserTraps[i] == ENTITYNUM_NONE ) - { + for (i = 0; i < trapcount_org; i++) { + if (foundLaserTraps[i] == ENTITYNUM_NONE) { continue; } found = &g_entities[foundLaserTraps[i]]; - if ( found->setTime < lowestTimeStamp ) - { + if (found->setTime < lowestTimeStamp) { removeMe = i; lowestTimeStamp = found->setTime; } } - if ( removeMe != -1 ) - { - //remove it... or blow it? - if ( &g_entities[foundLaserTraps[removeMe]] == NULL ) - { + if (removeMe != -1) { + // remove it... or blow it? + if (&g_entities[foundLaserTraps[removeMe]] == NULL) { break; - } - else - { - G_FreeEntity( &g_entities[foundLaserTraps[removeMe]] ); + } else { + G_FreeEntity(&g_entities[foundLaserTraps[removeMe]]); } foundLaserTraps[removeMe] = ENTITYNUM_NONE; trapcount--; - } - else - { + } else { break; } } } //--------------------------------------------------------- -void WP_PlaceLaserTrap( gentity_t *ent, qboolean alt_fire ) +void WP_PlaceLaserTrap(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - gentity_t *laserTrap; + vec3_t start; + gentity_t *laserTrap; // limit to 10 placed at any one time - WP_RemoveOldTraps( ent ); + WP_RemoveOldTraps(ent); - //FIXME: surface must be within 64 + // FIXME: surface must be within 64 laserTrap = G_Spawn(); - if ( laserTrap ) - { + if (laserTrap) { // now make the new one - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - CreateLaserTrap( laserTrap, start, ent ); + CreateLaserTrap(laserTrap, start, ent); // set player-created-specific fields - laserTrap->setTime = level.time;//remember when we placed it + laserTrap->setTime = level.time; // remember when we placed it laserTrap->s.eFlags |= EF_MISSILE_STICK; laserTrap->s.pos.trType = TR_GRAVITY; - VectorScale( forwardVec, LT_VELOCITY, laserTrap->s.pos.trDelta ); + VectorScale(forwardVec, LT_VELOCITY, laserTrap->s.pos.trDelta); - if ( alt_fire ) - { + if (alt_fire) { laserTrap->count = PROXIMITY_STYLE; laserTrap->delay = level.time + 40000; // will auto-blow in 40 seconds. laserTrap->methodOfDeath = MOD_LASERTRIP_ALT; - laserTrap->splashMethodOfDeath = MOD_LASERTRIP_ALT;//? SPLASH; - } - else - { + laserTrap->splashMethodOfDeath = MOD_LASERTRIP_ALT; //? SPLASH; + } else { laserTrap->count = TRIPWIRE_STYLE; } } diff --git a/code/game/wp_tusken.cpp b/code/game/wp_tusken.cpp index 10c5817fdc..68fc1786e8 100644 --- a/code/game/wp_tusken.cpp +++ b/code/game/wp_tusken.cpp @@ -27,61 +27,50 @@ along with this program; if not, see . #include "w_local.h" //--------------------------------------------------------- -void WP_FireTuskenRifle( gentity_t *ent ) +void WP_FireTuskenRifle(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; + vec3_t start; - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - if ( !(ent->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2 ) - {//force sight 2+ gives perfect aim - //FIXME: maybe force sight level 3 autoaims some? - if ( ent->NPC && ent->NPC->currentAim < 5 ) - { - vec3_t angs; + if (!(ent->client->ps.forcePowersActive & (1 << FP_SEE)) || ent->client->ps.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // force sight 2+ gives perfect aim + // FIXME: maybe force sight level 3 autoaims some? + if (ent->NPC && ent->NPC->currentAim < 5) { + vec3_t angs; - vectoangles( forwardVec, angs ); + vectoangles(forwardVec, angs); - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - {//*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - } - else - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { //*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + } else { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); } - AngleVectors( angs, forwardVec, NULL, NULL ); + AngleVectors(angs, forwardVec, NULL, NULL); } } WP_MissileTargetHint(ent, start, forwardVec); - gentity_t *missile = CreateMissile( start, forwardVec, TUSKEN_RIFLE_VEL, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(start, forwardVec, TUSKEN_RIFLE_VEL, 10000, ent, qfalse); missile->classname = "trifle_proj"; missile->s.weapon = WP_TUSKEN_RIFLE; - if ( ent->s.number < MAX_CLIENTS || g_spskill->integer >= 2 ) - { + if (ent->s.number < MAX_CLIENTS || g_spskill->integer >= 2) { missile->damage = TUSKEN_RIFLE_DAMAGE_HARD; - } - else if ( g_spskill->integer > 0 ) - { + } else if (g_spskill->integer > 0) { missile->damage = TUSKEN_RIFLE_DAMAGE_MEDIUM; - } - else - { + } else { missile->damage = TUSKEN_RIFLE_DAMAGE_EASY; } missile->dflags = DAMAGE_DEATH_KNOCKBACK; - missile->methodOfDeath = MOD_BRYAR;//??? + missile->methodOfDeath = MOD_BRYAR; //??? missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; diff --git a/code/icarus/BlockStream.cpp b/code/icarus/BlockStream.cpp index 3e94244c4e..76f0e23077 100644 --- a/code/icarus/BlockStream.cpp +++ b/code/icarus/BlockStream.cpp @@ -44,16 +44,13 @@ along with this program; if not, see . =================================================================================================== */ -inline CBlockMember::CBlockMember( void ) -{ +inline CBlockMember::CBlockMember(void) { m_id = -1; m_size = -1; m_data = NULL; } -inline CBlockMember::~CBlockMember( void ) -{ -} +inline CBlockMember::~CBlockMember(void) {} /* ------------------------- @@ -61,11 +58,9 @@ Free ------------------------- */ -void CBlockMember::Free(IGameInterface* game) -{ - if ( m_data != NULL ) - { - game->Free ( m_data ); +void CBlockMember::Free(IGameInterface *game) { + if (m_data != NULL) { + game->Free(m_data); m_data = NULL; m_id = m_size = -1; @@ -79,8 +74,7 @@ GetInfo ------------------------- */ -void CBlockMember::GetInfo( int *id, int *size, void **data ) -{ +void CBlockMember::GetInfo(int *id, int *size, void **data) { *id = m_id; *size = m_size; *data = m_data; @@ -92,24 +86,17 @@ SetData overloads ------------------------- */ -void CBlockMember::SetData( const char *data , CIcarus* icarus) -{ - WriteDataPointer( data, strlen(data)+1, icarus ); -} +void CBlockMember::SetData(const char *data, CIcarus *icarus) { WriteDataPointer(data, strlen(data) + 1, icarus); } -void CBlockMember::SetData( vec3_t data , CIcarus* icarus) -{ - WriteDataPointer( data, 3 , icarus); -} +void CBlockMember::SetData(vec3_t data, CIcarus *icarus) { WriteDataPointer(data, 3, icarus); } -void CBlockMember::SetData( void *data, int size, CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - if ( m_data ) - game->Free( m_data ); +void CBlockMember::SetData(void *data, int size, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + if (m_data) + game->Free(m_data); - m_data = game->Malloc( size ); - memcpy( m_data, data, size ); + m_data = game->Malloc(size); + memcpy(m_data, data, size); m_size = size; } @@ -121,26 +108,23 @@ ReadMember ------------------------- */ -int CBlockMember::ReadMember( char **stream, long *streamPos, CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); - m_id = LittleLong(*(int *) (*stream + *streamPos)); - *streamPos += sizeof( int ); - - if ( m_id == CIcarus::ID_RANDOM ) - {//special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time random is checked when inside a wait - m_size = sizeof( float ); - *streamPos += sizeof( int ); - m_data = game->Malloc( m_size ); +int CBlockMember::ReadMember(char **stream, long *streamPos, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + m_id = LittleLong(*(int *)(*stream + *streamPos)); + *streamPos += sizeof(int); + + if (m_id == CIcarus::ID_RANDOM) { // special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time + // random is checked when inside a wait + m_size = sizeof(float); + *streamPos += sizeof(int); + m_data = game->Malloc(m_size); float infinite = game->MaxFloat(); - memcpy( m_data, &infinite, m_size ); - } - else - { - m_size = LittleLong(*(int *) (*stream + *streamPos)); - *streamPos += sizeof( int ); - m_data = game->Malloc( m_size ); - memcpy( m_data, (*stream + *streamPos), m_size ); + memcpy(m_data, &infinite, m_size); + } else { + m_size = LittleLong(*(int *)(*stream + *streamPos)); + *streamPos += sizeof(int); + m_data = game->Malloc(m_size); + memcpy(m_data, (*stream + *streamPos), m_size); #ifdef Q3_BIG_ENDIAN // only TK_INT, TK_VECTOR and TK_FLOAT has to be swapped, but just in case if (m_size == 4 && m_id != CIcarus::TK_STRING && m_id != CIcarus::TK_IDENTIFIER && m_id != CIcarus::TK_CHAR) @@ -158,11 +142,10 @@ WriteMember ------------------------- */ -int CBlockMember::WriteMember( FILE *m_fileHandle ) -{ - fwrite( &m_id, sizeof(m_id), 1, m_fileHandle ); - fwrite( &m_size, sizeof(m_size), 1, m_fileHandle ); - fwrite( m_data, m_size, 1, m_fileHandle ); +int CBlockMember::WriteMember(FILE *m_fileHandle) { + fwrite(&m_id, sizeof(m_id), 1, m_fileHandle); + fwrite(&m_size, sizeof(m_size), 1, m_fileHandle); + fwrite(m_data, m_size, 1, m_fileHandle); return true; } @@ -173,16 +156,15 @@ Duplicate ------------------------- */ -CBlockMember *CBlockMember::Duplicate( CIcarus* icarus ) -{ - CBlockMember *newblock = new CBlockMember; +CBlockMember *CBlockMember::Duplicate(CIcarus *icarus) { + CBlockMember *newblock = new CBlockMember; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->SetData( m_data, m_size, icarus ); - newblock->SetSize( m_size ); - newblock->SetID( m_id ); + newblock->SetData(m_data, m_size, icarus); + newblock->SetSize(m_size); + newblock->SetID(m_id); return newblock; } @@ -195,17 +177,15 @@ CBlockMember *CBlockMember::Duplicate( CIcarus* icarus ) =================================================================================================== */ - /* ------------------------- Init ------------------------- */ -int CBlock::Init( void ) -{ - m_flags = 0; - m_id = 0; +int CBlock::Init(void) { + m_flags = 0; + m_id = 0; return true; } @@ -216,8 +196,7 @@ Create ------------------------- */ -int CBlock::Create( int block_id ) -{ +int CBlock::Create(int block_id) { Init(); m_id = block_id; @@ -231,15 +210,13 @@ Free ------------------------- */ -int CBlock::Free( CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); - int numMembers = GetNumMembers(); - CBlockMember *bMember; +int CBlock::Free(CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + int numMembers = GetNumMembers(); + CBlockMember *bMember; - while ( numMembers-- ) - { - bMember = GetMember( numMembers ); + while (numMembers--) { + bMember = GetMember(numMembers); if (!bMember) return false; @@ -247,7 +224,7 @@ int CBlock::Free( CIcarus* icarus ) bMember->Free(game); } - m_members.clear(); //List of all CBlockMembers owned by this list + m_members.clear(); // List of all CBlockMembers owned by this list return true; } @@ -260,67 +237,61 @@ Write ------------------------- */ -int CBlock::Write( int member_id, const char *member_data, CIcarus* icarus ) -{ +int CBlock::Write(int member_id, const char *member_data, CIcarus *icarus) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); + bMember->SetID(member_id); - bMember->SetData( member_data, icarus ); - bMember->SetSize( strlen(member_data) + 1 ); + bMember->SetData(member_data, icarus); + bMember->SetSize(strlen(member_data) + 1); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, vec3_t member_data, CIcarus* icarus ) -{ +int CBlock::Write(int member_id, vec3_t member_data, CIcarus *icarus) { CBlockMember *bMember; bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->SetData( member_data, icarus ); - bMember->SetSize( sizeof(vec3_t) ); + bMember->SetID(member_id); + bMember->SetData(member_data, icarus); + bMember->SetSize(sizeof(vec3_t)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, float member_data, CIcarus* icarus ) -{ +int CBlock::Write(int member_id, float member_data, CIcarus *icarus) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data, icarus ); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data, icarus); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, int member_data, CIcarus* icarus ) -{ +int CBlock::Write(int member_id, int member_data, CIcarus *icarus) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data , icarus); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data, icarus); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } +int CBlock::Write(CBlockMember *bMember, CIcarus *) { + // findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); -int CBlock::Write( CBlockMember *bMember, CIcarus* ) -{ -// findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); - - AddMember( bMember ); + AddMember(bMember); return true; } @@ -333,9 +304,8 @@ AddMember ------------------------- */ -int CBlock::AddMember( CBlockMember *member ) -{ - m_members.insert( m_members.end(), member ); +int CBlock::AddMember(CBlockMember *member) { + m_members.insert(m_members.end(), member); return true; } @@ -345,13 +315,11 @@ GetMember ------------------------- */ -CBlockMember *CBlock::GetMember( int memberNum ) -{ - if ( memberNum >= GetNumMembers() ) - { +CBlockMember *CBlock::GetMember(int memberNum) { + if (memberNum >= GetNumMembers()) { return NULL; } - return m_members[ memberNum ]; + return m_members[memberNum]; } /* @@ -360,13 +328,11 @@ GetMemberData ------------------------- */ -void *CBlock::GetMemberData( int memberNum ) -{ - if ( memberNum >= GetNumMembers() ) - { +void *CBlock::GetMemberData(int memberNum) { + if (memberNum >= GetNumMembers()) { return NULL; } - return (void *) ((GetMember( memberNum ))->GetData()); + return (void *)((GetMember(memberNum))->GetData()); } /* @@ -375,22 +341,20 @@ Duplicate ------------------------- */ -CBlock *CBlock::Duplicate( CIcarus* icarus ) -{ - blockMember_v::iterator mi; - CBlock *newblock; +CBlock *CBlock::Duplicate(CIcarus *icarus) { + blockMember_v::iterator mi; + CBlock *newblock; newblock = new CBlock; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->Create( m_id ); + newblock->Create(m_id); - //Duplicate entire block and return the cc - for ( mi = m_members.begin(); mi != m_members.end(); ++mi ) - { - newblock->AddMember( (*mi)->Duplicate(icarus) ); + // Duplicate entire block and return the cc + for (mi = m_members.begin(); mi != m_members.end(); ++mi) { + newblock->AddMember((*mi)->Duplicate(icarus)); } return newblock; @@ -404,11 +368,10 @@ CBlock *CBlock::Duplicate( CIcarus* icarus ) =================================================================================================== */ -const int IBI_HEADER_ID_LENGTH = 4; // Length of s_IBI_HEADER_ID + 1 (for null terminating byte) -char* CBlockStream::s_IBI_EXT = ".IBI"; //(I)nterpreted (B)lock (I)nstructions -char* CBlockStream::s_IBI_HEADER_ID = "IBI"; -const float CBlockStream::s_IBI_VERSION = 1.57f; - +const int IBI_HEADER_ID_LENGTH = 4; // Length of s_IBI_HEADER_ID + 1 (for null terminating byte) +char *CBlockStream::s_IBI_EXT = ".IBI"; //(I)nterpreted (B)lock (I)nstructions +char *CBlockStream::s_IBI_HEADER_ID = "IBI"; +const float CBlockStream::s_IBI_VERSION = 1.57f; /* ------------------------- @@ -416,9 +379,8 @@ Free ------------------------- */ -int CBlockStream::Free( void ) -{ - //NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call +int CBlockStream::Free(void) { + // NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call // That's why this doesn't free the memory, it only clears its internal pointer m_stream = NULL; @@ -433,19 +395,17 @@ Create ------------------------- */ -int CBlockStream::Create( char *filename ) -{ - //Strip the extension and add the BLOCK_EXT extension - COM_StripExtension( filename, m_fileName, sizeof(m_fileName) ); - COM_DefaultExtension( m_fileName, sizeof(m_fileName), s_IBI_EXT ); +int CBlockStream::Create(char *filename) { + // Strip the extension and add the BLOCK_EXT extension + COM_StripExtension(filename, m_fileName, sizeof(m_fileName)); + COM_DefaultExtension(m_fileName, sizeof(m_fileName), s_IBI_EXT); - if ( (m_fileHandle = fopen(m_fileName, "wb")) == NULL ) - { + if ((m_fileHandle = fopen(m_fileName, "wb")) == NULL) { return false; } - fwrite( s_IBI_HEADER_ID, 1, sizeof(s_IBI_HEADER_ID), m_fileHandle ); - fwrite( &s_IBI_VERSION, 1, sizeof(s_IBI_VERSION), m_fileHandle ); + fwrite(s_IBI_HEADER_ID, 1, sizeof(s_IBI_HEADER_ID), m_fileHandle); + fwrite(&s_IBI_VERSION, 1, sizeof(s_IBI_VERSION), m_fileHandle); return true; } @@ -456,8 +416,7 @@ Init ------------------------- */ -int CBlockStream::Init( void ) -{ +int CBlockStream::Init(void) { m_fileHandle = NULL; memset(m_fileName, 0, sizeof(m_fileName)); @@ -475,21 +434,19 @@ WriteBlock ------------------------- */ -int CBlockStream::WriteBlock( CBlock *block, CIcarus* icarus ) -{ - CBlockMember *bMember; - int id = block->GetBlockID(); - int numMembers = block->GetNumMembers(); - unsigned char flags = block->GetFlags(); - - fwrite ( &id, sizeof(id), 1, m_fileHandle ); - fwrite ( &numMembers, sizeof(numMembers), 1, m_fileHandle ); - fwrite ( &flags, sizeof( flags ), 1, m_fileHandle ); - - for ( int i = 0; i < numMembers; i++ ) - { - bMember = block->GetMember( i ); - bMember->WriteMember( m_fileHandle ); +int CBlockStream::WriteBlock(CBlock *block, CIcarus *icarus) { + CBlockMember *bMember; + int id = block->GetBlockID(); + int numMembers = block->GetNumMembers(); + unsigned char flags = block->GetFlags(); + + fwrite(&id, sizeof(id), 1, m_fileHandle); + fwrite(&numMembers, sizeof(numMembers), 1, m_fileHandle); + fwrite(&flags, sizeof(flags), 1, m_fileHandle); + + for (int i = 0; i < numMembers; i++) { + bMember = block->GetMember(i); + bMember->WriteMember(m_fileHandle); } block->Free(icarus); @@ -503,9 +460,8 @@ BlockAvailable ------------------------- */ -int CBlockStream::BlockAvailable( void ) -{ - if ( m_streamPos >= m_fileSize ) +int CBlockStream::BlockAvailable(void) { + if (m_streamPos >= m_fileSize) return false; return true; @@ -517,35 +473,33 @@ ReadBlock ------------------------- */ -int CBlockStream::ReadBlock( CBlock *get, CIcarus* icarus ) -{ - CBlockMember *bMember; - int b_id, numMembers; - unsigned char flags; +int CBlockStream::ReadBlock(CBlock *get, CIcarus *icarus) { + CBlockMember *bMember; + int b_id, numMembers; + unsigned char flags; if (!BlockAvailable()) return false; - b_id = LittleLong(*(int *) (m_stream + m_streamPos)); - m_streamPos += sizeof( b_id ); + b_id = LittleLong(*(int *)(m_stream + m_streamPos)); + m_streamPos += sizeof(b_id); - numMembers = LittleLong(*(int *) (m_stream + m_streamPos)); - m_streamPos += sizeof( numMembers ); + numMembers = LittleLong(*(int *)(m_stream + m_streamPos)); + m_streamPos += sizeof(numMembers); - flags = *(unsigned char*) (m_stream + m_streamPos); - m_streamPos += sizeof( flags ); + flags = *(unsigned char *)(m_stream + m_streamPos); + m_streamPos += sizeof(flags); if (numMembers < 0) return false; - get->Create( b_id ); - get->SetFlags( flags ); + get->Create(b_id); + get->SetFlags(flags); - while ( numMembers-- > 0) - { + while (numMembers-- > 0) { bMember = new CBlockMember; - bMember->ReadMember( &m_stream, &m_streamPos, icarus ); - get->AddMember( bMember ); + bMember->ReadMember(&m_stream, &m_streamPos, icarus); + get->AddMember(bMember); } return true; @@ -557,10 +511,9 @@ Open ------------------------- */ -int CBlockStream::Open( char *buffer, long size ) -{ - char id_header[IBI_HEADER_ID_LENGTH]; - float version; +int CBlockStream::Open(char *buffer, long size) { + char id_header[IBI_HEADER_ID_LENGTH]; + float version; Init(); @@ -568,24 +521,21 @@ int CBlockStream::Open( char *buffer, long size ) m_stream = buffer; - for ( size_t i = 0; i < sizeof( id_header ); i++ ) - { + for (size_t i = 0; i < sizeof(id_header); i++) { id_header[i] = *(m_stream + m_streamPos++); } - version = LittleFloat(*(float *) (m_stream + m_streamPos)); - m_streamPos += sizeof( version ); + version = LittleFloat(*(float *)(m_stream + m_streamPos)); + m_streamPos += sizeof(version); - //Check for valid header - if ( strcmp( id_header, s_IBI_HEADER_ID ) ) - { + // Check for valid header + if (strcmp(id_header, s_IBI_HEADER_ID)) { Free(); return false; } - //Check for valid version - if ( version != s_IBI_VERSION ) - { + // Check for valid version + if (version != s_IBI_VERSION) { Free(); return false; } diff --git a/code/icarus/IcarusImplementation.cpp b/code/icarus/IcarusImplementation.cpp index ba17235ca1..29bf09aa61 100644 --- a/code/icarus/IcarusImplementation.cpp +++ b/code/icarus/IcarusImplementation.cpp @@ -36,43 +36,34 @@ along with this program; if not, see . #include "../qcommon/qcommon.h" #include "qcommon/ojk_saved_game_helper.h" -#define STL_ITERATE( a, b ) for ( a = b.begin(); a != b.end(); ++a ) -#define STL_INSERT( a, b ) a.insert( a.end(), b ); - - +#define STL_ITERATE(a, b) for (a = b.begin(); a != b.end(); ++a) +#define STL_INSERT(a, b) a.insert(a.end(), b); ////////////////////////////////////////////////////////////////////////////////////////////////////////// // // required implementation of CIcarusInterface -IIcarusInterface* IIcarusInterface::GetIcarus(int flavor,bool constructIfNecessary) -{ - if(!CIcarus::s_instances && constructIfNecessary) - { +IIcarusInterface *IIcarusInterface::GetIcarus(int flavor, bool constructIfNecessary) { + if (!CIcarus::s_instances && constructIfNecessary) { CIcarus::s_flavorsAvailable = IGameInterface::s_IcarusFlavorsNeeded; - if (!CIcarus::s_flavorsAvailable) - { + if (!CIcarus::s_flavorsAvailable) { return NULL; } - CIcarus::s_instances = new CIcarus*[CIcarus::s_flavorsAvailable]; - for (int index = 0; index < CIcarus::s_flavorsAvailable; index++) - { + CIcarus::s_instances = new CIcarus *[CIcarus::s_flavorsAvailable]; + for (int index = 0; index < CIcarus::s_flavorsAvailable; index++) { CIcarus::s_instances[index] = new CIcarus(index); - //OutputDebugString( "ICARUS flavor successfully created\n" ); + // OutputDebugString( "ICARUS flavor successfully created\n" ); } } - if(flavor >= CIcarus::s_flavorsAvailable || !CIcarus::s_instances ) - { + if (flavor >= CIcarus::s_flavorsAvailable || !CIcarus::s_instances) { return NULL; } return CIcarus::s_instances[flavor]; } -void IIcarusInterface::DestroyIcarus() -{ - for(int index = 0; index < CIcarus::s_flavorsAvailable; index++) - { +void IIcarusInterface::DestroyIcarus() { + for (int index = 0; index < CIcarus::s_flavorsAvailable; index++) { delete CIcarus::s_instances[index]; } delete[] CIcarus::s_instances; @@ -80,9 +71,7 @@ void IIcarusInterface::DestroyIcarus() CIcarus::s_flavorsAvailable = 0; } -IIcarusInterface::~IIcarusInterface() -{ -} +IIcarusInterface::~IIcarusInterface() {} ///////////////////////////////////////////////////////////////////////////////////////////////////////// // @@ -92,23 +81,21 @@ double CIcarus::ICARUS_VERSION = 1.40; int CIcarus::s_flavorsAvailable = 0; -CIcarus** CIcarus::s_instances = NULL; +CIcarus **CIcarus::s_instances = NULL; -CIcarus::CIcarus(int flavor) : - m_flavor(flavor), m_nextSequencerID(0) -{ +CIcarus::CIcarus(int flavor) : m_flavor(flavor), m_nextSequencerID(0) { m_GUID = 0; #ifdef _DEBUG - m_DEBUG_NumSequencerAlloc = 0; - m_DEBUG_NumSequencerFreed = 0; - m_DEBUG_NumSequencerResidual = 0; + m_DEBUG_NumSequencerAlloc = 0; + m_DEBUG_NumSequencerFreed = 0; + m_DEBUG_NumSequencerResidual = 0; - m_DEBUG_NumSequenceAlloc = 0; - m_DEBUG_NumSequenceFreed = 0; - m_DEBUG_NumSequenceResidual = 0; + m_DEBUG_NumSequenceAlloc = 0; + m_DEBUG_NumSequenceFreed = 0; + m_DEBUG_NumSequenceResidual = 0; #endif @@ -117,59 +104,46 @@ CIcarus::CIcarus(int flavor) : m_byBuffer = NULL; } -CIcarus::~CIcarus() -{ - Delete(); -} +CIcarus::~CIcarus() { Delete(); } -void CIcarus::Delete( void ) -{ +void CIcarus::Delete(void) { Free(); #ifdef _DEBUG - Com_Printf( "ICARUS Instance Debug Info:\n" ); - Com_Printf( "---------------------------\n" ); - Com_Printf( "Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc ); - Com_Printf( "Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed ); - Com_Printf( "Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual ); - Com_Printf( "Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc ); - Com_Printf( "Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed ); - Com_Printf( "Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual ); + Com_Printf("ICARUS Instance Debug Info:\n"); + Com_Printf("---------------------------\n"); + Com_Printf("Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc); + Com_Printf("Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed); + Com_Printf("Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual); + Com_Printf("Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc); + Com_Printf("Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed); + Com_Printf("Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual); #endif } -void CIcarus::Signal( const char *identifier ) -{ - m_signals[ identifier ] = 1; -} +void CIcarus::Signal(const char *identifier) { m_signals[identifier] = 1; } -bool CIcarus::CheckSignal( const char *identifier ) -{ - signal_m::iterator smi; +bool CIcarus::CheckSignal(const char *identifier) { + signal_m::iterator smi; - smi = m_signals.find( identifier ); + smi = m_signals.find(identifier); - if ( smi == m_signals.end() ) + if (smi == m_signals.end()) return false; return true; } -void CIcarus::ClearSignal( const char *identifier ) -{ - m_signals.erase( identifier ); -} +void CIcarus::ClearSignal(const char *identifier) { m_signals.erase(identifier); } -void CIcarus::Free( void ) -{ - sequencer_l::iterator sri; +void CIcarus::Free(void) { + sequencer_l::iterator sri; - //Delete any residual sequencers - STL_ITERATE( sri, m_sequencers ) - { + // Delete any residual sequencers + STL_ITERATE(sri, m_sequencers) { (*sri)->Free(this); #ifdef _DEBUG @@ -177,17 +151,15 @@ void CIcarus::Free( void ) m_DEBUG_NumSequencerResidual++; #endif - } m_sequencers.clear(); m_signals.clear(); - sequence_l::iterator si; + sequence_l::iterator si; - //Delete any residual sequences - STL_ITERATE( si, m_sequences ) - { + // Delete any residual sequences + STL_ITERATE(si, m_sequences) { (*si)->Delete(this); delete (*si); @@ -196,7 +168,6 @@ void CIcarus::Free( void ) m_DEBUG_NumSequenceResidual++; #endif - } m_sequences.clear(); @@ -204,16 +175,15 @@ void CIcarus::Free( void ) m_sequencerMap.clear(); } -int CIcarus::GetIcarusID( int gameID ) -{ - CSequencer *sequencer = CSequencer::Create(); - CTaskManager *taskManager = CTaskManager::Create(); +int CIcarus::GetIcarusID(int gameID) { + CSequencer *sequencer = CSequencer::Create(); + CTaskManager *taskManager = CTaskManager::Create(); - sequencer->Init( gameID, taskManager ); + sequencer->Init(gameID, taskManager); - taskManager->Init( sequencer ); + taskManager->Init(sequencer); - STL_INSERT( m_sequencers, sequencer ); + STL_INSERT(m_sequencers, sequencer); m_sequencerMap[sequencer->GetID()] = sequencer; @@ -226,19 +196,16 @@ int CIcarus::GetIcarusID( int gameID ) return sequencer->GetID(); } -void CIcarus::DeleteIcarusID( int& icarusID ) -{ - CSequencer* sequencer = FindSequencer(icarusID); - if(!sequencer) - { +void CIcarus::DeleteIcarusID(int &icarusID) { + CSequencer *sequencer = FindSequencer(icarusID); + if (!sequencer) { icarusID = -1; return; } - CTaskManager *taskManager = sequencer->GetTaskManager(); - if (taskManager->IsResident()) - { - IGameInterface::GetGame()->DebugPrint( IGameInterface::WL_ERROR, "Refusing DeleteIcarusID(%d) because it is running!\n", icarusID); + CTaskManager *taskManager = sequencer->GetTaskManager(); + if (taskManager->IsResident()) { + IGameInterface::GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Refusing DeleteIcarusID(%d) because it is running!\n", icarusID); assert(0); return; } @@ -248,14 +215,12 @@ void CIcarus::DeleteIcarusID( int& icarusID ) // added 2/12/2 to properly delete blocks that were passed to the task manager sequencer->Recall(this); - - if ( taskManager ) - { + if (taskManager) { taskManager->Free(); delete taskManager; } - m_sequencers.remove( sequencer ); + m_sequencers.remove(sequencer); sequencer->Free(this); @@ -267,14 +232,13 @@ void CIcarus::DeleteIcarusID( int& icarusID ) icarusID = -1; } -CSequence *CIcarus::GetSequence( void ) -{ - CSequence *sequence = CSequence::Create(); +CSequence *CIcarus::GetSequence(void) { + CSequence *sequence = CSequence::Create(); - //Assign the GUID - sequence->SetID( m_GUID++ ); + // Assign the GUID + sequence->SetID(m_GUID++); - STL_INSERT( m_sequences, sequence ); + STL_INSERT(m_sequences, sequence); #ifdef _DEBUG @@ -285,21 +249,18 @@ CSequence *CIcarus::GetSequence( void ) return sequence; } -CSequence *CIcarus::GetSequence( int id ) -{ - sequence_l::iterator si; - STL_ITERATE( si, m_sequences ) - { - if ( (*si)->GetID() == id ) +CSequence *CIcarus::GetSequence(int id) { + sequence_l::iterator si; + STL_ITERATE(si, m_sequences) { + if ((*si)->GetID() == id) return (*si); } return NULL; } -void CIcarus::DeleteSequence( CSequence *sequence ) -{ - m_sequences.remove( sequence ); +void CIcarus::DeleteSequence(CSequence *sequence) { + m_sequences.remove(sequence); sequence->Delete(this); delete sequence; @@ -311,97 +272,88 @@ void CIcarus::DeleteSequence( CSequence *sequence ) #endif } -int CIcarus::AllocateSequences( int numSequences, int *idTable ) -{ - CSequence *sequence; +int CIcarus::AllocateSequences(int numSequences, int *idTable) { + CSequence *sequence; - for ( int i = 0; i < numSequences; i++ ) - { - //If the GUID of this sequence is higher than the current, take this a the "current" GUID - if ( idTable[i] > m_GUID ) + for (int i = 0; i < numSequences; i++) { + // If the GUID of this sequence is higher than the current, take this a the "current" GUID + if (idTable[i] > m_GUID) m_GUID = idTable[i]; - //Allocate the container sequence - if ( ( sequence = GetSequence() ) == NULL ) + // Allocate the container sequence + if ((sequence = GetSequence()) == NULL) return false; - //Override the given GUID with the real one - sequence->SetID( idTable[i] ); + // Override the given GUID with the real one + sequence->SetID(idTable[i]); } return true; } -void CIcarus::Precache(char* buffer, long length) -{ - IGameInterface* game = IGameInterface::GetGame(m_flavor); - CBlockStream stream; - CBlockMember *blockMember; - CBlock block; +void CIcarus::Precache(char *buffer, long length) { + IGameInterface *game = IGameInterface::GetGame(m_flavor); + CBlockStream stream; + CBlockMember *blockMember; + CBlock block; - if ( stream.Open( buffer, length ) == 0 ) + if (stream.Open(buffer, length) == 0) return; - const char *sVal1, *sVal2; + const char *sVal1, *sVal2; - //Now iterate through all blocks of the script, searching for keywords - while ( stream.BlockAvailable() ) - { - //Get a block - if ( stream.ReadBlock( &block, this ) == 0 ) + // Now iterate through all blocks of the script, searching for keywords + while (stream.BlockAvailable()) { + // Get a block + if (stream.ReadBlock(&block, this) == 0) return; - //Determine what type of block this is - switch( block.GetBlockID() ) + // Determine what type of block this is + switch (block.GetBlockID()) { + case ID_CAMERA: // to cache ROFF files { - case ID_CAMERA: // to cache ROFF files - { - float f = *(float *) block.GetMemberData( 0 ); + float f = *(float *)block.GetMemberData(0); - if (f == TYPE_PATH) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (f == TYPE_PATH) { + sVal1 = (const char *)block.GetMemberData(1); - game->PrecacheRoff(sVal1); - } + game->PrecacheRoff(sVal1); } - break; + } break; - case ID_PLAY: // to cache ROFF files + case ID_PLAY: // to cache ROFF files - sVal1 = (const char *) block.GetMemberData( 0 ); + sVal1 = (const char *)block.GetMemberData(0); - if (!Q_stricmp(sVal1,"PLAY_ROFF")) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (!Q_stricmp(sVal1, "PLAY_ROFF")) { + sVal1 = (const char *)block.GetMemberData(1); game->PrecacheRoff(sVal1); } break; - //Run commands + // Run commands case ID_RUN: - sVal1 = (const char *) block.GetMemberData( 0 ); - game->PrecacheScript( sVal1 ); + sVal1 = (const char *)block.GetMemberData(0); + game->PrecacheScript(sVal1); break; case ID_SOUND: - sVal1 = (const char *) block.GetMemberData( 1 ); //0 is channel, 1 is filename + sVal1 = (const char *)block.GetMemberData(1); // 0 is channel, 1 is filename game->PrecacheSound(sVal1); break; case ID_SET: - blockMember = block.GetMember( 0 ); + blockMember = block.GetMember(0); - //NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) + // NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) - //Make sure we're testing against strings - if ( blockMember->GetID() == TK_STRING ) - { - sVal1 = (const char *) block.GetMemberData( 0 ); - sVal2 = (const char *) block.GetMemberData( 1 ); + // Make sure we're testing against strings + if (blockMember->GetID() == TK_STRING) { + sVal1 = (const char *)block.GetMemberData(0); + sVal2 = (const char *)block.GetMemberData(1); - game->PrecacheFromSet( sVal1 , sVal2); + game->PrecacheFromSet(sVal1, sVal2); } break; @@ -409,173 +361,145 @@ void CIcarus::Precache(char* buffer, long length) break; } - //Clean out the block for the next pass + // Clean out the block for the next pass block.Free(this); } - //All done + // All done stream.Free(); } -CSequencer* CIcarus::FindSequencer(int sequencerID) -{ - sequencer_m::iterator mi = m_sequencerMap.find( sequencerID ); +CSequencer *CIcarus::FindSequencer(int sequencerID) { + sequencer_m::iterator mi = m_sequencerMap.find(sequencerID); - if ( mi == m_sequencerMap.end() ) + if (mi == m_sequencerMap.end()) return NULL; return (*mi).second; } -int CIcarus::Run(int icarusID, char* buffer, long length) -{ - CSequencer* sequencer = FindSequencer(icarusID); - if(sequencer) - { +int CIcarus::Run(int icarusID, char *buffer, long length) { + CSequencer *sequencer = FindSequencer(icarusID); + if (sequencer) { return sequencer->Run(buffer, length, this); } return ICARUS_INVALID; } -int CIcarus::SaveSequenceIDTable() -{ - //Save out the number of sequences to follow - int numSequences = m_sequences.size(); +int CIcarus::SaveSequenceIDTable() { + // Save out the number of sequences to follow + int numSequences = m_sequences.size(); - BufferWrite( &numSequences, sizeof( numSequences ) ); + BufferWrite(&numSequences, sizeof(numSequences)); - //Sequences are saved first, by ID and information - sequence_l::iterator sqi; + // Sequences are saved first, by ID and information + sequence_l::iterator sqi; - //First pass, save all sequences ID for reconstruction - int *idTable = new int[ numSequences ]; - int itr = 0; + // First pass, save all sequences ID for reconstruction + int *idTable = new int[numSequences]; + int itr = 0; - if ( idTable == NULL ) + if (idTable == NULL) return false; - STL_ITERATE( sqi, m_sequences ) - { - idTable[itr++] = (*sqi)->GetID(); - } + STL_ITERATE(sqi, m_sequences) { idTable[itr++] = (*sqi)->GetID(); } - //game->WriteSaveData( INT_ID('S','Q','T','B'), idTable, sizeof( int ) * numSequences ); - BufferWrite( idTable, sizeof( int ) * numSequences ); + // game->WriteSaveData( INT_ID('S','Q','T','B'), idTable, sizeof( int ) * numSequences ); + BufferWrite(idTable, sizeof(int) * numSequences); delete[] idTable; return true; } -int CIcarus::SaveSequences() -{ - //Save out a listing of all the used sequences by ID +int CIcarus::SaveSequences() { + // Save out a listing of all the used sequences by ID SaveSequenceIDTable(); - //Save all the information in order - sequence_l::iterator sqi; - STL_ITERATE( sqi, m_sequences ) - { - (*sqi)->Save(); - } + // Save all the information in order + sequence_l::iterator sqi; + STL_ITERATE(sqi, m_sequences) { (*sqi)->Save(); } return true; } -int CIcarus::SaveSequencers() -{ - //Save out the number of sequences to follow - int numSequencers = m_sequencers.size(); - BufferWrite( &numSequencers, sizeof( numSequencers ) ); +int CIcarus::SaveSequencers() { + // Save out the number of sequences to follow + int numSequencers = m_sequencers.size(); + BufferWrite(&numSequencers, sizeof(numSequencers)); - //The sequencers are then saved + // The sequencers are then saved int sequencessaved = 0; - sequencer_l::iterator si; - STL_ITERATE( si, m_sequencers ) - { + sequencer_l::iterator si; + STL_ITERATE(si, m_sequencers) { (*si)->Save(); sequencessaved++; } - assert( sequencessaved == numSequencers ); + assert(sequencessaved == numSequencers); return true; } -int CIcarus::SaveSignals() -{ - int numSignals = m_signals.size(); +int CIcarus::SaveSignals() { + int numSignals = m_signals.size(); - //game->WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); - BufferWrite( &numSignals, sizeof( numSignals ) ); + // game->WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); + BufferWrite(&numSignals, sizeof(numSignals)); - signal_m::iterator si; - STL_ITERATE( si, m_signals ) - { - //game->WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); + signal_m::iterator si; + STL_ITERATE(si, m_signals) { + // game->WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); const char *name = ((*si).first).c_str(); - int length = strlen( name ) + 1; + int length = strlen(name) + 1; - //Save out the string size - BufferWrite( &length, sizeof( length ) ); + // Save out the string size + BufferWrite(&length, sizeof(length)); - //Write out the string - BufferWrite( (void *) name, length ); + // Write out the string + BufferWrite((void *)name, length); } return true; } // Get the current Game flavor. -int CIcarus::GetFlavor() -{ - return m_flavor; -} +int CIcarus::GetFlavor() { return m_flavor; } -int CIcarus::Save() -{ +int CIcarus::Save() { // Allocate the temporary buffer. CreateBuffer(); - IGameInterface* game = IGameInterface::GetGame(m_flavor); + IGameInterface *game = IGameInterface::GetGame(m_flavor); - ojk::SavedGameHelper saved_game( - game->get_saved_game_file()); + ojk::SavedGameHelper saved_game(game->get_saved_game_file()); - //Save out a ICARUS save block header with the ICARUS version - double version = ICARUS_VERSION; + // Save out a ICARUS save block header with the ICARUS version + double version = ICARUS_VERSION; - saved_game.write_chunk( - INT_ID('I', 'C', 'A', 'R'), - version); + saved_game.write_chunk(INT_ID('I', 'C', 'A', 'R'), version); - //Save out the signals - if ( SaveSignals() == false ) - { + // Save out the signals + if (SaveSignals() == false) { DestroyBuffer(); return false; } - //Save out the sequences - if ( SaveSequences() == false ) - { + // Save out the sequences + if (SaveSequences() == false) { DestroyBuffer(); return false; } - //Save out the sequencers - if ( SaveSequencers() == false ) - { + // Save out the sequencers + if (SaveSequencers() == false) { DestroyBuffer(); return false; } // Write out the buffer with all our collected data. - saved_game.write_chunk( - INT_ID('I', 'S', 'E', 'Q'), - m_byBuffer, - static_cast(m_ulBufferCurPos)); + saved_game.write_chunk(INT_ID('I', 'S', 'E', 'Q'), m_byBuffer, static_cast(m_ulBufferCurPos)); // De-allocate the temporary buffer. DestroyBuffer(); @@ -583,175 +507,154 @@ int CIcarus::Save() return true; } -int CIcarus::LoadSignals() -{ +int CIcarus::LoadSignals() { int numSignals; - BufferRead( &numSignals, sizeof( numSignals ) ); + BufferRead(&numSignals, sizeof(numSignals)); - for ( int i = 0; i < numSignals; i++ ) - { - char buffer[1024]; - int length = 0; + for (int i = 0; i < numSignals; i++) { + char buffer[1024]; + int length = 0; - //Get the size of the string - BufferRead( &length, sizeof( length ) ); + // Get the size of the string + BufferRead(&length, sizeof(length)); - //Get the string - BufferRead( &buffer, length ); + // Get the string + BufferRead(&buffer, length); - //Turn it on and add it to the system - Signal( (const char *) &buffer ); + // Turn it on and add it to the system + Signal((const char *)&buffer); } return true; } -int CIcarus::LoadSequence() -{ - CSequence *sequence = GetSequence(); +int CIcarus::LoadSequence() { + CSequence *sequence = GetSequence(); - //Load the sequence back in + // Load the sequence back in sequence->Load(this); - //If this sequence had a higher GUID than the current, save it - if ( sequence->GetID() > m_GUID ) + // If this sequence had a higher GUID than the current, save it + if (sequence->GetID() > m_GUID) m_GUID = sequence->GetID(); return true; } -int CIcarus::LoadSequences() -{ - CSequence *sequence; - int numSequences; +int CIcarus::LoadSequences() { + CSequence *sequence; + int numSequences; - //Get the number of sequences to read in - BufferRead( &numSequences, sizeof( numSequences ) ); + // Get the number of sequences to read in + BufferRead(&numSequences, sizeof(numSequences)); - int *idTable = new int[ numSequences ]; + int *idTable = new int[numSequences]; - if ( idTable == NULL ) + if (idTable == NULL) return false; - //Load the sequencer ID table - BufferRead( idTable, sizeof( int ) * numSequences ); + // Load the sequencer ID table + BufferRead(idTable, sizeof(int) * numSequences); - //First pass, allocate all container sequences and give them their proper IDs - if ( AllocateSequences( numSequences, idTable ) == false ) + // First pass, allocate all container sequences and give them their proper IDs + if (AllocateSequences(numSequences, idTable) == false) return false; - //Second pass, load all sequences - for ( int i = 0; i < numSequences; i++ ) - { - //Get the proper sequence for this load - if ( ( sequence = GetSequence( idTable[i] ) ) == NULL ) + // Second pass, load all sequences + for (int i = 0; i < numSequences; i++) { + // Get the proper sequence for this load + if ((sequence = GetSequence(idTable[i])) == NULL) return false; - //Load the sequence - if ( ( sequence->Load(this) ) == false ) + // Load the sequence + if ((sequence->Load(this)) == false) return false; } - //Free the idTable + // Free the idTable delete[] idTable; return true; } -int CIcarus::LoadSequencers() -{ - CSequencer *sequencer; - int numSequencers; - IGameInterface* game = IGameInterface::GetGame(m_flavor); +int CIcarus::LoadSequencers() { + CSequencer *sequencer; + int numSequencers; + IGameInterface *game = IGameInterface::GetGame(m_flavor); - //Get the number of sequencers to load - BufferRead( &numSequencers, sizeof( numSequencers ) ); + // Get the number of sequencers to load + BufferRead(&numSequencers, sizeof(numSequencers)); - //Load all sequencers - for ( int i = 0; i < numSequencers; i++ ) - { - //NOTENOTE: The ownerID will be replaced in the loading process + // Load all sequencers + for (int i = 0; i < numSequencers; i++) { + // NOTENOTE: The ownerID will be replaced in the loading process int sequencerID = GetIcarusID(-1); - if ( ( sequencer = FindSequencer(sequencerID) ) == NULL ) + if ((sequencer = FindSequencer(sequencerID)) == NULL) return false; - if ( sequencer->Load(this, game) == false ) + if (sequencer->Load(this, game) == false) return false; } return true; } -int CIcarus::Load() -{ +int CIcarus::Load() { CreateBuffer(); - IGameInterface* game = IGameInterface::GetGame(m_flavor); + IGameInterface *game = IGameInterface::GetGame(m_flavor); - ojk::SavedGameHelper saved_game( - game->get_saved_game_file()); + ojk::SavedGameHelper saved_game(game->get_saved_game_file()); - //Clear out any old information + // Clear out any old information Free(); - //Check to make sure we're at the ICARUS save block - double version = 0.0; + // Check to make sure we're at the ICARUS save block + double version = 0.0; - saved_game.read_chunk( - INT_ID('I', 'C', 'A', 'R'), - version); + saved_game.read_chunk(INT_ID('I', 'C', 'A', 'R'), version); - //Versions must match! - if ( version != ICARUS_VERSION ) - { + // Versions must match! + if (version != ICARUS_VERSION) { DestroyBuffer(); - game->DebugPrint( IGameInterface::WL_ERROR, "save game data contains outdated ICARUS version information!\n"); + game->DebugPrint(IGameInterface::WL_ERROR, "save game data contains outdated ICARUS version information!\n"); return false; } // Read into the buffer all our data. - saved_game.read_chunk( - INT_ID('I','S','E','Q')); + saved_game.read_chunk(INT_ID('I', 'S', 'E', 'Q')); - const unsigned char* sg_buffer_data = static_cast( - saved_game.get_buffer_data()); + const unsigned char *sg_buffer_data = static_cast(saved_game.get_buffer_data()); int sg_buffer_size = saved_game.get_buffer_size(); - if (sg_buffer_size < 0 || static_cast(sg_buffer_size) > MAX_BUFFER_SIZE) - { + if (sg_buffer_size < 0 || static_cast(sg_buffer_size) > MAX_BUFFER_SIZE) { DestroyBuffer(); - game->DebugPrint( IGameInterface::WL_ERROR, "invalid ISEQ length: %d bytes\n", sg_buffer_size); + game->DebugPrint(IGameInterface::WL_ERROR, "invalid ISEQ length: %d bytes\n", sg_buffer_size); return false; } - std::uninitialized_copy_n( - sg_buffer_data, - sg_buffer_size, - m_byBuffer); + std::uninitialized_copy_n(sg_buffer_data, sg_buffer_size, m_byBuffer); - //Load all signals - if ( LoadSignals() == false ) - { + // Load all signals + if (LoadSignals() == false) { DestroyBuffer(); - game->DebugPrint( IGameInterface::WL_ERROR, "failed to load signals from save game!\n"); + game->DebugPrint(IGameInterface::WL_ERROR, "failed to load signals from save game!\n"); return false; } - //Load in all sequences - if ( LoadSequences() == false ) - { + // Load in all sequences + if (LoadSequences() == false) { DestroyBuffer(); - game->DebugPrint( IGameInterface::WL_ERROR, "failed to load sequences from save game!\n"); + game->DebugPrint(IGameInterface::WL_ERROR, "failed to load sequences from save game!\n"); return false; } - //Load in all sequencers - if ( LoadSequencers() == false ) - { + // Load in all sequencers + if (LoadSequencers() == false) { DestroyBuffer(); - game->DebugPrint( IGameInterface::WL_ERROR, "failed to load sequencers from save game!\n"); + game->DebugPrint(IGameInterface::WL_ERROR, "failed to load sequencers from save game!\n"); return false; } @@ -760,122 +663,98 @@ int CIcarus::Load() return true; } -int CIcarus::Update(int icarusID) -{ - CSequencer* sequencer = FindSequencer(icarusID); - if(sequencer) - { +int CIcarus::Update(int icarusID) { + CSequencer *sequencer = FindSequencer(icarusID); + if (sequencer) { return sequencer->GetTaskManager()->Update(this); } return -1; } -int CIcarus::IsRunning(int icarusID) -{ - CSequencer* sequencer = FindSequencer(icarusID); - if(sequencer) - { +int CIcarus::IsRunning(int icarusID) { + CSequencer *sequencer = FindSequencer(icarusID); + if (sequencer) { return sequencer->GetTaskManager()->IsRunning(); } return false; } -void CIcarus::Completed( int icarusID, int taskID ) -{ - CSequencer* sequencer = FindSequencer(icarusID); - if(sequencer) - { +void CIcarus::Completed(int icarusID, int taskID) { + CSequencer *sequencer = FindSequencer(icarusID); + if (sequencer) { sequencer->GetTaskManager()->Completed(taskID); } } // Destroy the File Buffer. -void CIcarus::DestroyBuffer() -{ - if ( m_byBuffer ) - { - IGameInterface::GetGame()->Free( m_byBuffer ); +void CIcarus::DestroyBuffer() { + if (m_byBuffer) { + IGameInterface::GetGame()->Free(m_byBuffer); m_byBuffer = NULL; } } // Create the File Buffer. -void CIcarus::CreateBuffer() -{ +void CIcarus::CreateBuffer() { DestroyBuffer(); - m_byBuffer = (unsigned char *)IGameInterface::GetGame()->Malloc( MAX_BUFFER_SIZE ); + m_byBuffer = (unsigned char *)IGameInterface::GetGame()->Malloc(MAX_BUFFER_SIZE); m_ulBufferCurPos = 0; } // Write to a buffer. -void CIcarus::BufferWrite( void *pSrcData, unsigned long ulNumBytesToWrite ) -{ - if ( !pSrcData ) +void CIcarus::BufferWrite(void *pSrcData, unsigned long ulNumBytesToWrite) { + if (!pSrcData) return; // Make sure we have enough space in the buffer to write to. - if ( MAX_BUFFER_SIZE - m_ulBufferCurPos < ulNumBytesToWrite ) - { // Write out the buffer with all our collected data so far... - IGameInterface::GetGame()->DebugPrint( IGameInterface::WL_ERROR, "BufferWrite: Out of buffer space, Flushing." ); + if (MAX_BUFFER_SIZE - m_ulBufferCurPos < ulNumBytesToWrite) { // Write out the buffer with all our collected data so far... + IGameInterface::GetGame()->DebugPrint(IGameInterface::WL_ERROR, "BufferWrite: Out of buffer space, Flushing."); - ojk::SavedGameHelper saved_game( - IGameInterface::GetGame()->get_saved_game_file()); + ojk::SavedGameHelper saved_game(IGameInterface::GetGame()->get_saved_game_file()); - saved_game.write_chunk( - INT_ID('I', 'S', 'E', 'Q'), - m_byBuffer, - static_cast(m_ulBufferCurPos)); + saved_game.write_chunk(INT_ID('I', 'S', 'E', 'Q'), m_byBuffer, static_cast(m_ulBufferCurPos)); - m_ulBufferCurPos = 0; //reset buffer + m_ulBufferCurPos = 0; // reset buffer } - assert( MAX_BUFFER_SIZE - m_ulBufferCurPos >= ulNumBytesToWrite ); + assert(MAX_BUFFER_SIZE - m_ulBufferCurPos >= ulNumBytesToWrite); { - memcpy( m_byBuffer + m_ulBufferCurPos, pSrcData, ulNumBytesToWrite ); + memcpy(m_byBuffer + m_ulBufferCurPos, pSrcData, ulNumBytesToWrite); m_ulBufferCurPos += ulNumBytesToWrite; } } // Read from a buffer. -void CIcarus::BufferRead( void *pDstBuff, unsigned long ulNumBytesToRead ) -{ - if ( !pDstBuff ) +void CIcarus::BufferRead(void *pDstBuff, unsigned long ulNumBytesToRead) { + if (!pDstBuff) return; // If we can read this data... - if ( m_ulBytesRead + ulNumBytesToRead > MAX_BUFFER_SIZE ) - {// We've tried to read past the buffer... - IGameInterface::GetGame()->DebugPrint( IGameInterface::WL_ERROR, "BufferRead: Buffer underflow, Looking for new block." ); + if (m_ulBytesRead + ulNumBytesToRead > MAX_BUFFER_SIZE) { // We've tried to read past the buffer... + IGameInterface::GetGame()->DebugPrint(IGameInterface::WL_ERROR, "BufferRead: Buffer underflow, Looking for new block."); // Read in the next block. - ojk::SavedGameHelper saved_game( - IGameInterface::GetGame()->get_saved_game_file()); + ojk::SavedGameHelper saved_game(IGameInterface::GetGame()->get_saved_game_file()); - saved_game.read_chunk( - INT_ID('I', 'S', 'E', 'Q')); + saved_game.read_chunk(INT_ID('I', 'S', 'E', 'Q')); - const unsigned char* sg_buffer_data = static_cast( - saved_game.get_buffer_data()); + const unsigned char *sg_buffer_data = static_cast(saved_game.get_buffer_data()); int sg_buffer_size = saved_game.get_buffer_size(); - if (sg_buffer_size < 0 || static_cast(sg_buffer_size) > MAX_BUFFER_SIZE) - { - IGameInterface::GetGame()->DebugPrint( IGameInterface::WL_ERROR, "invalid ISEQ length: %d bytes\n", sg_buffer_size); + if (sg_buffer_size < 0 || static_cast(sg_buffer_size) > MAX_BUFFER_SIZE) { + IGameInterface::GetGame()->DebugPrint(IGameInterface::WL_ERROR, "invalid ISEQ length: %d bytes\n", sg_buffer_size); return; } - std::uninitialized_copy_n( - sg_buffer_data, - sg_buffer_size, - m_byBuffer); + std::uninitialized_copy_n(sg_buffer_data, sg_buffer_size, m_byBuffer); - m_ulBytesRead = 0; //reset buffer + m_ulBytesRead = 0; // reset buffer } assert(m_ulBytesRead + ulNumBytesToRead <= MAX_BUFFER_SIZE); { - memcpy( pDstBuff, m_byBuffer + m_ulBytesRead, ulNumBytesToRead ); + memcpy(pDstBuff, m_byBuffer + m_ulBytesRead, ulNumBytesToRead); m_ulBytesRead += ulNumBytesToRead; } } diff --git a/code/icarus/Sequence.cpp b/code/icarus/Sequence.cpp index bdfa249dc8..29fd4f8971 100644 --- a/code/icarus/Sequence.cpp +++ b/code/icarus/Sequence.cpp @@ -31,25 +31,22 @@ along with this program; if not, see . #include "blockstream.h" #include "sequence.h" -#define STL_ITERATE( a, b ) for ( a = b.begin(); a != b.end(); ++a ) -#define STL_INSERT( a, b ) a.insert( a.end(), b ); +#define STL_ITERATE(a, b) for (a = b.begin(); a != b.end(); ++a) +#define STL_INSERT(a, b) a.insert(a.end(), b); +inline CSequence::CSequence(void) { + m_numCommands = 0; + // m_numChildren = 0; + m_flags = 0; + m_iterations = 1; -inline CSequence::CSequence( void ) -{ - m_numCommands = 0; -// m_numChildren = 0; - m_flags = 0; - m_iterations = 1; - - m_parent = NULL; - m_return = NULL; + m_parent = NULL; + m_return = NULL; } -CSequence::~CSequence( void ) -{ +CSequence::~CSequence(void) { assert(!m_commands.size()); - //assert(!m_numChildren); + // assert(!m_numChildren); } /* @@ -58,16 +55,15 @@ Create ------------------------- */ -CSequence *CSequence::Create( void ) -{ +CSequence *CSequence::Create(void) { CSequence *seq = new CSequence; - //TODO: Emit warning + // TODO: Emit warning assert(seq); - if ( seq == NULL ) + if (seq == NULL) return NULL; - seq->SetFlag( SQ_COMMON ); + seq->SetFlag(SQ_COMMON); return seq; } @@ -78,60 +74,52 @@ Delete ------------------------- */ -void CSequence::Delete( CIcarus* icarus ) -{ - block_l::iterator bi; +void CSequence::Delete(CIcarus *icarus) { + block_l::iterator bi; sequence_l::iterator si; - //Notify the parent of the deletion - if ( m_parent ) - { - m_parent->RemoveChild( this ); + // Notify the parent of the deletion + if (m_parent) { + m_parent->RemoveChild(this); } - //Clear all children - if ( m_children.size() > 0 ) - { + // Clear all children + if (m_children.size() > 0) { /*for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) { (*iterSeq).second->SetParent( NULL ); }*/ - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->SetParent( NULL ); + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->SetParent(NULL); } } m_children.clear(); - //m_childrenMap.clear(); + // m_childrenMap.clear(); - //Clear all held commands - for ( bi = m_commands.begin(); bi != m_commands.end(); ++bi ) - { + // Clear all held commands + for (bi = m_commands.begin(); bi != m_commands.end(); ++bi) { (*bi)->Free(icarus); - delete (*bi); //Free() handled internally -- not any more!! + delete (*bi); // Free() handled internally -- not any more!! } m_commands.clear(); - } - /* ------------------------- AddChild ------------------------- */ -void CSequence::AddChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::AddChild(CSequence *child) { + assert(child); + if (child == NULL) return; - m_children.insert( m_children.end(), child ); -// m_childrenMap[ m_numChildren ] = child; -// m_numChildren++; + m_children.insert(m_children.end(), child); + // m_childrenMap[ m_numChildren ] = child; + // m_numChildren++; } /* @@ -140,22 +128,21 @@ RemoveChild ------------------------- */ -void CSequence::RemoveChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::RemoveChild(CSequence *child) { + assert(child); + if (child == NULL) return; - m_children.remove( child ); + m_children.remove(child); - //Remove the child -/* sequenceID_m::iterator iterSeq = m_childrenMap.find( child->GetID() ); - if ( iterSeq != m_childrenMap.end() ) - { - m_childrenMap.erase( iterSeq ); - } + // Remove the child + /* sequenceID_m::iterator iterSeq = m_childrenMap.find( child->GetID() ); + if ( iterSeq != m_childrenMap.end() ) + { + m_childrenMap.erase( iterSeq ); + } - m_numChildren--;*/ + m_numChildren--;*/ } /* @@ -164,28 +151,26 @@ HasChild ------------------------- */ -bool CSequence::HasChild( CSequence *sequence ) -{ - sequence_l::iterator ci; +bool CSequence::HasChild(CSequence *sequence) { + sequence_l::iterator ci; - for ( ci = m_children.begin(); ci != m_children.end(); ci++ ) - { - if ( (*ci) == sequence ) + for (ci = m_children.begin(); ci != m_children.end(); ci++) { + if ((*ci) == sequence) return true; - if ( (*ci)->HasChild( sequence ) ) + if ((*ci)->HasChild(sequence)) return true; } -/* sequenceID_m::iterator iterSeq = NULL; - for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) - { - if ( ((*iterSeq).second) == sequence ) - return true; + /* sequenceID_m::iterator iterSeq = NULL; + for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) + { + if ( ((*iterSeq).second) == sequence ) + return true; - if ( (*iterSeq).second->HasChild( sequence ) ) - return true; - }*/ + if ( (*iterSeq).second->HasChild( sequence ) ) + return true; + }*/ return false; } @@ -196,18 +181,17 @@ SetParent ------------------------- */ -void CSequence::SetParent( CSequence *parent ) -{ +void CSequence::SetParent(CSequence *parent) { m_parent = parent; - if ( parent == NULL ) + if (parent == NULL) return; - //Inherit the parent's properties (this avoids messy tree walks later on) - if ( parent->m_flags & SQ_RETAIN ) + // Inherit the parent's properties (this avoids messy tree walks later on) + if (parent->m_flags & SQ_RETAIN) m_flags |= SQ_RETAIN; - if ( parent->m_flags & SQ_PENDING ) + if (parent->m_flags & SQ_PENDING) m_flags |= SQ_PENDING; } @@ -217,18 +201,16 @@ PopCommand ------------------------- */ -CBlock *CSequence::PopCommand( int type ) -{ - CBlock *command = NULL; +CBlock *CSequence::PopCommand(int type) { + CBlock *command = NULL; - //Make sure everything is ok - assert( (type == POP_FRONT) || (type == POP_BACK) ); + // Make sure everything is ok + assert((type == POP_FRONT) || (type == POP_BACK)); - if ( m_commands.empty() ) + if (m_commands.empty()) return NULL; - switch ( type ) - { + switch (type) { case POP_FRONT: command = m_commands.front(); @@ -248,7 +230,7 @@ CBlock *CSequence::PopCommand( int type ) break; } - //Invalid flag + // Invalid flag return NULL; } @@ -258,17 +240,15 @@ PushCommand ------------------------- */ -int CSequence::PushCommand( CBlock *block, int type ) -{ - //Make sure everything is ok - assert( (type == PUSH_FRONT) || (type == PUSH_BACK) ); - assert( block ); +int CSequence::PushCommand(CBlock *block, int type) { + // Make sure everything is ok + assert((type == PUSH_FRONT) || (type == PUSH_BACK)); + assert(block); - switch ( type ) - { + switch (type) { case PUSH_FRONT: - m_commands.push_front( block ); + m_commands.push_front(block); m_numCommands++; return true; @@ -276,14 +256,14 @@ int CSequence::PushCommand( CBlock *block, int type ) case PUSH_BACK: - m_commands.push_back( block ); + m_commands.push_back(block); m_numCommands++; return true; break; } - //Invalid flag + // Invalid flag return false; } @@ -293,10 +273,7 @@ SetFlag ------------------------- */ -void CSequence::SetFlag( int flag ) -{ - m_flags |= flag; -} +void CSequence::SetFlag(int flag) { m_flags |= flag; } /* ------------------------- @@ -304,22 +281,19 @@ RemoveFlag ------------------------- */ -void CSequence::RemoveFlag( int flag, bool children ) -{ +void CSequence::RemoveFlag(int flag, bool children) { m_flags &= ~flag; - if ( children ) - { -/* sequenceID_m::iterator iterSeq = NULL; - for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) - { - (*iterSeq).second->RemoveFlag( flag, true ); - }*/ + if (children) { + /* sequenceID_m::iterator iterSeq = NULL; + for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) + { + (*iterSeq).second->RemoveFlag( flag, true ); + }*/ - sequence_l::iterator si; - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->RemoveFlag( flag, true ); + sequence_l::iterator si; + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->RemoveFlag(flag, true); } } } @@ -330,10 +304,7 @@ HasFlag ------------------------- */ -int CSequence::HasFlag( int flag ) -{ - return (m_flags & flag); -} +int CSequence::HasFlag(int flag) { return (m_flags & flag); } /* ------------------------- @@ -341,9 +312,8 @@ SetReturn ------------------------- */ -void CSequence::SetReturn ( CSequence *sequence ) -{ - assert( sequence != this ); +void CSequence::SetReturn(CSequence *sequence) { + assert(sequence != this); m_return = sequence; } @@ -353,23 +323,21 @@ GetChildByID ------------------------- */ -CSequence *CSequence::GetChildByID( int id ) -{ - if ( id < 0 ) +CSequence *CSequence::GetChildByID(int id) { + if (id < 0) return NULL; - //NOTENOTE: Done for safety reasons, I don't know what this template will return on underflow ( sigh... ) -/* sequenceID_m::iterator mi = m_childrenMap.find( id ); + // NOTENOTE: Done for safety reasons, I don't know what this template will return on underflow ( sigh... ) + /* sequenceID_m::iterator mi = m_childrenMap.find( id ); - if ( mi == m_childrenMap.end() ) - return NULL; + if ( mi == m_childrenMap.end() ) + return NULL; - return (*mi).second;*/ + return (*mi).second;*/ sequence_l::iterator iterSeq; - STL_ITERATE( iterSeq, m_children ) - { - if ( (*iterSeq)->GetID() == id ) + STL_ITERATE(iterSeq, m_children) { + if ((*iterSeq)->GetID() == id) return (*iterSeq); } @@ -382,14 +350,12 @@ GetChildByIndex ------------------------- */ -CSequence *CSequence::GetChildByIndex( int iIndex ) -{ - if ( iIndex < 0 || iIndex >= (int)m_children.size() ) +CSequence *CSequence::GetChildByIndex(int iIndex) { + if (iIndex < 0 || iIndex >= (int)m_children.size()) return NULL; sequence_l::iterator iterSeq = m_children.begin(); - for ( int i = 0; i < iIndex; i++ ) - { + for (int i = 0; i < iIndex; i++) { ++iterSeq; } return (*iterSeq); @@ -401,13 +367,12 @@ SaveCommand ------------------------- */ -int CSequence::SaveCommand( CBlock *block ) -{ +int CSequence::SaveCommand(CBlock *block) { CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; // Data saved here (IBLK): // Block ID. @@ -418,44 +383,42 @@ int CSequence::SaveCommand( CBlock *block ) // - Block Data Size. // - Block (Raw) Data. - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - pIcarus->BufferWrite( &bID, sizeof ( bID ) ); + pIcarus->BufferWrite(&bID, sizeof(bID)); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - pIcarus->BufferWrite( &flags, sizeof ( flags ) ); + pIcarus->BufferWrite(&flags, sizeof(flags)); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - pIcarus->BufferWrite( &numMembers, sizeof ( numMembers ) ); + pIcarus->BufferWrite(&numMembers, sizeof(numMembers)); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - pIcarus->BufferWrite( &bID, sizeof ( bID ) ); + pIcarus->BufferWrite(&bID, sizeof(bID)); - //Save out the data size + // Save out the data size size = bm->GetSize(); - pIcarus->BufferWrite( &size, sizeof ( size ) ); + pIcarus->BufferWrite(&size, sizeof(size)); - //Save out the raw data - pIcarus->BufferWrite( bm->GetData(), size ); + // Save out the raw data + pIcarus->BufferWrite(bm->GetData(), size); } return true; } -int CSequence::LoadCommand( CBlock *block, CIcarus *icarus ) -{ - IGameInterface* game = icarus->GetGame(); - int bID, bSize; - void *bData; - unsigned char flags; - int id, numMembers; +int CSequence::LoadCommand(CBlock *block, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + int bID, bSize; + void *bData; + unsigned char flags; + int id, numMembers; // Data expected/loaded here (IBLK) (with the size as : 'IBSZ' ). // Block ID. @@ -466,75 +429,71 @@ int CSequence::LoadCommand( CBlock *block, CIcarus *icarus ) // - Block Data Size. // - Block (Raw) Data. - //Get the block ID. - icarus->BufferRead( &id, sizeof( id ) ); - block->Create( id ); + // Get the block ID. + icarus->BufferRead(&id, sizeof(id)); + block->Create(id); - //Read the block's flags - icarus->BufferRead( &flags, sizeof( flags ) ); - block->SetFlags( flags ); + // Read the block's flags + icarus->BufferRead(&flags, sizeof(flags)); + block->SetFlags(flags); - //Get the number of block members - icarus->BufferRead( &numMembers, sizeof( numMembers ) ); + // Get the number of block members + icarus->BufferRead(&numMembers, sizeof(numMembers)); - for ( int j = 0; j < numMembers; j++ ) - { - //Get the member ID - icarus->BufferRead( &bID, sizeof( bID ) ); + for (int j = 0; j < numMembers; j++) { + // Get the member ID + icarus->BufferRead(&bID, sizeof(bID)); - //Get the member size - icarus->BufferRead( &bSize, sizeof( bSize ) ); + // Get the member size + icarus->BufferRead(&bSize, sizeof(bSize)); - //Get the member's data - if ( ( bData = game->Malloc( bSize ) ) == NULL ) + // Get the member's data + if ((bData = game->Malloc(bSize)) == NULL) return false; - //Get the actual raw data - icarus->BufferRead( bData, bSize ); + // Get the actual raw data + icarus->BufferRead(bData, bSize); - //Write out the correct type - switch ( bID ) - { - case CIcarus::TK_INT: - { - assert(0); - int data = *(int *) bData; - block->Write( CIcarus::TK_FLOAT, (float) data, icarus ); - } - break; + // Write out the correct type + switch (bID) { + case CIcarus::TK_INT: { + assert(0); + int data = *(int *)bData; + block->Write(CIcarus::TK_FLOAT, (float)data, icarus); + } break; case CIcarus::TK_FLOAT: - block->Write( CIcarus::TK_FLOAT, *(float *) bData, icarus ); + block->Write(CIcarus::TK_FLOAT, *(float *)bData, icarus); break; case CIcarus::TK_STRING: case CIcarus::TK_IDENTIFIER: case CIcarus::TK_CHAR: - block->Write( CIcarus::TK_STRING, (char *) bData, icarus ); + block->Write(CIcarus::TK_STRING, (char *)bData, icarus); break; case CIcarus::TK_VECTOR: case CIcarus::TK_VECTOR_START: - block->Write( CIcarus::TK_VECTOR, *(vec3_t *) bData, icarus ); + block->Write(CIcarus::TK_VECTOR, *(vec3_t *)bData, icarus); break; case CIcarus::ID_TAG: - block->Write( CIcarus::ID_TAG, (float) CIcarus::ID_TAG, icarus ); + block->Write(CIcarus::ID_TAG, (float)CIcarus::ID_TAG, icarus); break; case CIcarus::ID_GET: - block->Write( CIcarus::ID_GET, (float) CIcarus::ID_GET, icarus ); + block->Write(CIcarus::ID_GET, (float)CIcarus::ID_GET, icarus); break; case CIcarus::ID_RANDOM: - block->Write( CIcarus::ID_RANDOM, *(float *) bData, icarus );//(float) ID_RANDOM ); + block->Write(CIcarus::ID_RANDOM, *(float *)bData, icarus); //(float) ID_RANDOM ); break; case CIcarus::TK_EQUALS: case CIcarus::TK_GREATER_THAN: case CIcarus::TK_LESS_THAN: case CIcarus::TK_NOT: - block->Write( bID, 0, icarus ); + block->Write(bID, 0, icarus); break; default: @@ -543,8 +502,8 @@ int CSequence::LoadCommand( CBlock *block, CIcarus *icarus ) break; } - //Get rid of the temp memory - game->Free( bData ); + // Get rid of the temp memory + game->Free(bData); } return true; @@ -556,8 +515,7 @@ Save ------------------------- */ -int CSequence::Save() -{ +int CSequence::Save() { // Data saved here. // Parent ID. // Return ID. @@ -571,48 +529,44 @@ int CSequence::Save() CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - block_l::iterator bi; - int id; + block_l::iterator bi; + int id; // Save the parent (by GUID). - id = ( m_parent != NULL ) ? m_parent->GetID() : -1; - pIcarus->BufferWrite( &id, sizeof( id ) ); + id = (m_parent != NULL) ? m_parent->GetID() : -1; + pIcarus->BufferWrite(&id, sizeof(id)); - //Save the return (by GUID) - id = ( m_return != NULL ) ? m_return->GetID() : -1; - pIcarus->BufferWrite( &id, sizeof( id ) ); + // Save the return (by GUID) + id = (m_return != NULL) ? m_return->GetID() : -1; + pIcarus->BufferWrite(&id, sizeof(id)); - //Save the number of children + // Save the number of children int iNumChildren = m_children.size(); - pIcarus->BufferWrite( &iNumChildren, sizeof( iNumChildren ) ); + pIcarus->BufferWrite(&iNumChildren, sizeof(iNumChildren)); - //Save out the children (only by GUID) + // Save out the children (only by GUID) /*STL_ITERATE( iterSeq, m_childrenMap ) { id = (*iterSeq).second->GetID(); pIcarus->BufferWrite( &id, sizeof( id ) ); }*/ sequence_l::iterator iterSeq; - STL_ITERATE( iterSeq, m_children ) - { + STL_ITERATE(iterSeq, m_children) { id = (*iterSeq)->GetID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); } - //Save flags - pIcarus->BufferWrite( &m_flags, sizeof( m_flags ) ); + // Save flags + pIcarus->BufferWrite(&m_flags, sizeof(m_flags)); - //Save iterations - pIcarus->BufferWrite( &m_iterations, sizeof( m_iterations ) ); + // Save iterations + pIcarus->BufferWrite(&m_iterations, sizeof(m_iterations)); - //Save the number of commands - pIcarus->BufferWrite( &m_numCommands, sizeof( m_numCommands ) ); + // Save the number of commands + pIcarus->BufferWrite(&m_numCommands, sizeof(m_numCommands)); - //Save the commands - STL_ITERATE( bi, m_commands ) - { - SaveCommand( (*bi) ); - } + // Save the commands + STL_ITERATE(bi, m_commands) { SaveCommand((*bi)); } return true; } @@ -623,11 +577,10 @@ Load ------------------------- */ -int CSequence::Load( CIcarus* icarus ) -{ - CSequence *sequence; - CBlock *block; - int id; +int CSequence::Load(CIcarus *icarus) { + CSequence *sequence; + CBlock *block; + int id; // Data expected/loaded here (ISEQ) (with the size as : 'ISSZ' ). // Parent ID. @@ -640,56 +593,53 @@ int CSequence::Load( CIcarus* icarus ) // Number of Commands // - Commands (raw) data. - //Get the parent sequence - icarus->BufferRead( &id, sizeof( id ) ); - m_parent = ( id != -1 ) ? icarus->GetSequence( id ) : NULL; + // Get the parent sequence + icarus->BufferRead(&id, sizeof(id)); + m_parent = (id != -1) ? icarus->GetSequence(id) : NULL; - //Get the return sequence - icarus->BufferRead( &id, sizeof( id ) ); - m_return = ( id != -1 ) ? icarus->GetSequence( id ) : NULL; + // Get the return sequence + icarus->BufferRead(&id, sizeof(id)); + m_return = (id != -1) ? icarus->GetSequence(id) : NULL; - //Get the number of children + // Get the number of children int iNumChildren = 0; - icarus->BufferRead( &iNumChildren, sizeof( iNumChildren ) ); + icarus->BufferRead(&iNumChildren, sizeof(iNumChildren)); - //Reload all children - for ( int i = 0; i < iNumChildren; i++ ) - { - //Get the child sequence ID - icarus->BufferRead( &id, sizeof( id ) ); + // Reload all children + for (int i = 0; i < iNumChildren; i++) { + // Get the child sequence ID + icarus->BufferRead(&id, sizeof(id)); - //Get the desired sequence - if ( ( sequence = icarus->GetSequence( id ) ) == NULL ) + // Get the desired sequence + if ((sequence = icarus->GetSequence(id)) == NULL) return false; - //Insert this into the list - STL_INSERT( m_children, sequence ); + // Insert this into the list + STL_INSERT(m_children, sequence); - //Restore the connection in the child / ID map -// m_childrenMap[ i ] = sequence; + // Restore the connection in the child / ID map + // m_childrenMap[ i ] = sequence; } + // Get the sequence flags + icarus->BufferRead(&m_flags, sizeof(m_flags)); - //Get the sequence flags - icarus->BufferRead( &m_flags, sizeof( m_flags ) ); + // Get the number of iterations + icarus->BufferRead(&m_iterations, sizeof(m_iterations)); - //Get the number of iterations - icarus->BufferRead( &m_iterations, sizeof( m_iterations ) ); + int numCommands; - int numCommands; + // Get the number of commands + icarus->BufferRead(&numCommands, sizeof(numCommands)); - //Get the number of commands - icarus->BufferRead( &numCommands, sizeof( numCommands ) ); - - //Get all the commands - for ( int i = 0; i < numCommands; i++ ) - { + // Get all the commands + for (int i = 0; i < numCommands; i++) { block = new CBlock; - LoadCommand( block, icarus ); + LoadCommand(block, icarus); - //Save the block - //STL_INSERT( m_commands, block ); - PushCommand( block, PUSH_BACK ); + // Save the block + // STL_INSERT( m_commands, block ); + PushCommand(block, PUSH_BACK); } return true; diff --git a/code/icarus/Sequencer.cpp b/code/icarus/Sequencer.cpp index 91e506f62e..d1d7db1d79 100644 --- a/code/icarus/Sequencer.cpp +++ b/code/icarus/Sequencer.cpp @@ -33,11 +33,10 @@ along with this program; if not, see . #include "taskmanager.h" #include "sequencer.h" -#define S_FAILED(a) (a!=SEQ_OK) - -#define STL_ITERATE( a, b ) for ( a = b.begin(); a != b.end(); ++a ) -#define STL_INSERT( a, b ) a.insert( a.end(), b ); +#define S_FAILED(a) (a != SEQ_OK) +#define STL_ITERATE(a, b) for (a = b.begin(); a != b.end(); ++a) +#define STL_INSERT(a, b) a.insert(a.end(), b); // Save/Load restructuring. // Date: 10/29/02 @@ -46,18 +45,16 @@ along with this program; if not, see . // using a chunks for EVERYTHING is vastly inefficient and wasteful. Thus, the saving // is now primary focused on saving large chunks with *expected* data read from there. - // Sequencer -CSequencer::CSequencer( void ) -{ +CSequencer::CSequencer(void) { static int uniqueID = 1; m_id = uniqueID++; - m_numCommands = 0; + m_numCommands = 0; - m_curStream = NULL; - m_curSequence = NULL; + m_curStream = NULL; + m_curSequence = NULL; m_elseValid = 0; m_elseOwner = NULL; @@ -65,9 +62,7 @@ CSequencer::CSequencer( void ) m_curGroup = NULL; } -CSequencer::~CSequencer( void ) -{ -} +CSequencer::~CSequencer(void) {} /* ======================== @@ -77,8 +72,7 @@ Static creation function ======================== */ -CSequencer *CSequencer::Create ( void ) -{ +CSequencer *CSequencer::Create(void) { CSequencer *sequencer = new CSequencer; return sequencer; @@ -91,10 +85,9 @@ Init Initializes the sequencer ======================== */ -int CSequencer::Init( int ownerID, CTaskManager *taskManager ) -{ - m_ownerID = ownerID; - m_taskManager = taskManager; +int CSequencer::Init(int ownerID, CTaskManager *taskManager) { + m_ownerID = ownerID; + m_taskManager = taskManager; return SEQ_OK; } @@ -106,33 +99,30 @@ Free Releases all resources and re-inits the sequencer ======================== */ -void CSequencer::Free( CIcarus* icarus ) -{ - //Flush the sequences -/* sequenceID_m::iterator iterSeq = NULL; - for ( iterSeq = m_sequenceMap.begin(); iterSeq != m_sequenceMap.end(); iterSeq++ ) - { - icarus->DeleteSequence( (*iterSeq).second ); - } - m_sequenceMap.clear();*/ +void CSequencer::Free(CIcarus *icarus) { + // Flush the sequences + /* sequenceID_m::iterator iterSeq = NULL; + for ( iterSeq = m_sequenceMap.begin(); iterSeq != m_sequenceMap.end(); iterSeq++ ) + { + icarus->DeleteSequence( (*iterSeq).second ); + } + m_sequenceMap.clear();*/ // OLD STUFF! - sequence_l::iterator sli; - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ++sli ) - { - icarus->DeleteSequence( (*sli) ); + sequence_l::iterator sli; + for (sli = m_sequences.begin(); sli != m_sequences.end(); ++sli) { + icarus->DeleteSequence((*sli)); } m_sequences.clear(); m_taskSequences.clear(); - //Clean up any other info + // Clean up any other info m_numCommands = 0; m_curSequence = NULL; bstream_t *streamToDel; - while(!m_streamsCreated.empty()) - { + while (!m_streamsCreated.empty()) { streamToDel = m_streamsCreated.back(); DeleteStream(streamToDel); } @@ -146,59 +136,55 @@ Flush ------------------------- */ -int CSequencer::Flush( CSequence *owner, CIcarus* icarus ) -{ - if ( owner == NULL ) +int CSequencer::Flush(CSequence *owner, CIcarus *icarus) { + if (owner == NULL) return SEQ_FAILED; Recall(icarus); - - //Flush the sequences -/* sequenceID_m::iterator iterSeq = NULL; - for ( iterSeq = m_sequenceMap.begin(); iterSeq != m_sequenceMap.end(); ) - { - if ( ( (*iterSeq).second == owner ) || ( owner->HasChild( (*iterSeq).second ) ) || ( (*iterSeq).second->HasFlag( CSequence::SQ_PENDING ) ) || ( (*iterSeq).second->HasFlag( CSequence::SQ_TASK ) ) ) + // Flush the sequences + /* sequenceID_m::iterator iterSeq = NULL; + for ( iterSeq = m_sequenceMap.begin(); iterSeq != m_sequenceMap.end(); ) { - iterSeq++; - continue; - } - - //Delete it, and remove all references - RemoveSequence( (*iterSeq).second, icarus ); - icarus->DeleteSequence( (*iterSeq).second ); + if ( ( (*iterSeq).second == owner ) || ( owner->HasChild( (*iterSeq).second ) ) || ( (*iterSeq).second->HasFlag( CSequence::SQ_PENDING ) ) || ( + (*iterSeq).second->HasFlag( CSequence::SQ_TASK ) ) ) + { + iterSeq++; + continue; + } - //Remove it from the map - //Delete from the sequence list and move on - iterSeq = m_sequenceMap.erase( iterSeq ); - }*/ + //Delete it, and remove all references + RemoveSequence( (*iterSeq).second, icarus ); + icarus->DeleteSequence( (*iterSeq).second ); + //Remove it from the map + //Delete from the sequence list and move on + iterSeq = m_sequenceMap.erase( iterSeq ); + }*/ // OLD STUFF! - //Flush the sequences + // Flush the sequences sequence_l::iterator sli; - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ) - { - if ( ( (*sli) == owner ) || ( owner->HasChild( (*sli) ) ) || ( (*sli)->HasFlag( CSequence::SQ_PENDING ) ) || ( (*sli)->HasFlag( CSequence::SQ_TASK ) ) ) - { + for (sli = m_sequences.begin(); sli != m_sequences.end();) { + if (((*sli) == owner) || (owner->HasChild((*sli))) || ((*sli)->HasFlag(CSequence::SQ_PENDING)) || ((*sli)->HasFlag(CSequence::SQ_TASK))) { ++sli; continue; } - //Remove it from the map - //m_sequenceMap.erase( (*sli)->GetID() ); + // Remove it from the map + // m_sequenceMap.erase( (*sli)->GetID() ); - //Delete it, and remove all references - RemoveSequence( (*sli), icarus ); - icarus->DeleteSequence( (*sli) ); + // Delete it, and remove all references + RemoveSequence((*sli), icarus); + icarus->DeleteSequence((*sli)); - //Delete from the sequence list and move on - sli = m_sequences.erase( sli ); + // Delete from the sequence list and move on + sli = m_sequences.erase(sli); } - //Make sure this owner knows it's now the root sequence - owner->SetParent( NULL ); - owner->SetReturn( NULL ); + // Make sure this owner knows it's now the root sequence + owner->SetParent(NULL); + owner->SetReturn(NULL); return SEQ_OK; } @@ -211,12 +197,11 @@ Creates a stream for parsing ======================== */ -bstream_t *CSequencer::AddStream( void ) -{ - bstream_t *stream; +bstream_t *CSequencer::AddStream(void) { + bstream_t *stream; - stream = new bstream_t; //deleted in Route() - stream->stream = new CBlockStream; //deleted in Route() + stream = new bstream_t; // deleted in Route() + stream->stream = new CBlockStream; // deleted in Route() stream->last = m_curStream; m_streamsCreated.push_back(stream); @@ -231,11 +216,9 @@ DeleteStream Deletes parsing stream ======================== */ -void CSequencer::DeleteStream( bstream_t *bstream ) -{ - std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); - if(finder != m_streamsCreated.end()) - { +void CSequencer::DeleteStream(bstream_t *bstream) { + std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); + if (finder != m_streamsCreated.end()) { m_streamsCreated.erase(finder); } @@ -253,10 +236,7 @@ AddTaskSequence ------------------------- */ -void CSequencer::AddTaskSequence( CSequence *sequence, CTaskGroup *group ) -{ - m_taskSequences[ group ] = sequence; -} +void CSequencer::AddTaskSequence(CSequence *sequence, CTaskGroup *group) { m_taskSequences[group] = sequence; } /* ------------------------- @@ -264,13 +244,12 @@ GetTaskSequence ------------------------- */ -CSequence *CSequencer::GetTaskSequence( CTaskGroup *group ) -{ - taskSequence_m::iterator tsi; +CSequence *CSequencer::GetTaskSequence(CTaskGroup *group) { + taskSequence_m::iterator tsi; - tsi = m_taskSequences.find( group ); + tsi = m_taskSequences.find(group); - if ( tsi == m_taskSequences.end() ) + if (tsi == m_taskSequences.end()) return NULL; return (*tsi).second; @@ -284,45 +263,43 @@ Creates and adds a sequence to the sequencer ======================== */ -CSequence *CSequencer::AddSequence( CIcarus* icarus ) -{ - CSequence *sequence = (CSequence*)icarus->GetSequence(); +CSequence *CSequencer::AddSequence(CIcarus *icarus) { + CSequence *sequence = (CSequence *)icarus->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //The rest is handled internally to the class - //m_sequenceMap[ sequence->GetID() ] = sequence; + // The rest is handled internally to the class + // m_sequenceMap[ sequence->GetID() ] = sequence; // OLD STUFF! - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); - //FIXME: Temp fix - sequence->SetFlag( CSequence::SQ_PENDING ); + // FIXME: Temp fix + sequence->SetFlag(CSequence::SQ_PENDING); return sequence; } -CSequence *CSequencer::AddSequence( CSequence *parent, CSequence *returnSeq, int flags, CIcarus* icarus ) -{ - CSequence *sequence = (CSequence*)icarus->GetSequence(); +CSequence *CSequencer::AddSequence(CSequence *parent, CSequence *returnSeq, int flags, CIcarus *icarus) { + CSequence *sequence = (CSequence *)icarus->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //The rest is handled internally to the class -// m_sequenceMap[ sequence->GetID() ] = sequence; + // The rest is handled internally to the class + // m_sequenceMap[ sequence->GetID() ] = sequence; // OLD STUFF! - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); - sequence->SetFlags( flags ); - sequence->SetParent( parent ); - sequence->SetReturn( returnSeq ); + sequence->SetFlags(flags); + sequence->SetParent(parent); + sequence->SetReturn(returnSeq); return sequence; } @@ -335,21 +312,19 @@ Retrieves a sequence by its ID ======================== */ -CSequence *CSequencer::GetSequence( int id ) -{ -/* sequenceID_m::iterator mi; +CSequence *CSequencer::GetSequence(int id) { + /* sequenceID_m::iterator mi; - mi = m_sequenceMap.find( id ); + mi = m_sequenceMap.find( id ); - if ( mi == m_sequenceMap.end() ) - return NULL; + if ( mi == m_sequenceMap.end() ) + return NULL; - return (*mi).second;*/ + return (*mi).second;*/ sequence_l::iterator iterSeq; - STL_ITERATE( iterSeq, m_sequences ) - { - if ( (*iterSeq)->GetID() == id ) + STL_ITERATE(iterSeq, m_sequences) { + if ((*iterSeq)->GetID() == id) return (*iterSeq); } @@ -362,15 +337,14 @@ Interrupt ------------------------- */ -void CSequencer::Interrupt( void ) -{ - CBlock *command = m_taskManager->GetCurrentTask(); +void CSequencer::Interrupt(void) { + CBlock *command = m_taskManager->GetCurrentTask(); - if ( command == NULL ) + if (command == NULL) return; - //Save it - PushCommand( command, CSequence::PUSH_BACK ); + // Save it + PushCommand(command, CSequence::PUSH_BACK); } /* @@ -380,30 +354,27 @@ Run Runs a script ======================== */ -int CSequencer::Run( char *buffer, long size, CIcarus* icarus ) -{ - bstream_t *blockStream; +int CSequencer::Run(char *buffer, long size, CIcarus *icarus) { + bstream_t *blockStream; - IGameInterface* game = icarus->GetGame(); + IGameInterface *game = icarus->GetGame(); Recall(icarus); - //Create a new stream + // Create a new stream blockStream = AddStream(); - //Open the stream as an IBI stream - if (!blockStream->stream->Open( buffer, size )) - { - game->DebugPrint(IGameInterface::WL_ERROR, "invalid stream" ); + // Open the stream as an IBI stream + if (!blockStream->stream->Open(buffer, size)) { + game->DebugPrint(IGameInterface::WL_ERROR, "invalid stream"); return SEQ_FAILED; } - CSequence *sequence = AddSequence( NULL, m_curSequence, CSequence::SQ_COMMON, icarus ); + CSequence *sequence = AddSequence(NULL, m_curSequence, CSequence::SQ_COMMON, icarus); // Interpret the command blocks and route them properly - if ( S_FAILED( Route( sequence, blockStream, icarus )) ) - { - //Error code is set inside of Route() + if (S_FAILED(Route(sequence, blockStream, icarus))) { + // Error code is set inside of Route() return SEQ_FAILED; } @@ -418,52 +389,48 @@ Parses a user triggered run command ======================== */ -int CSequencer::ParseRun( CBlock *block , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CSequence *new_sequence; - bstream_t *new_stream; - char *buffer; - char newname[ CIcarus::MAX_STRING_SIZE ]; - int buffer_size; +int CSequencer::ParseRun(CBlock *block, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequence *new_sequence; + bstream_t *new_stream; + char *buffer; + char newname[CIcarus::MAX_STRING_SIZE]; + int buffer_size; - //Get the name and format it - COM_StripExtension( (char*) block->GetMemberData( 0 ), (char *) newname, sizeof(newname) ); + // Get the name and format it + COM_StripExtension((char *)block->GetMemberData(0), (char *)newname, sizeof(newname)); - //Get the file from the game engine - buffer_size = game->LoadFile( newname, (void **) &buffer ); + // Get the file from the game engine + buffer_size = game->LoadFile(newname, (void **)&buffer); - if ( buffer_size <= 0 ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "'%s' : could not open file\n", (char*) block->GetMemberData( 0 )); + if (buffer_size <= 0) { + game->DebugPrint(IGameInterface::WL_ERROR, "'%s' : could not open file\n", (char *)block->GetMemberData(0)); block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - //Create a new stream for this file + // Create a new stream for this file new_stream = AddStream(); - //Begin streaming the file - if (!new_stream->stream->Open( buffer, buffer_size )) - { - game->DebugPrint(IGameInterface::WL_ERROR, "invalid stream" ); + // Begin streaming the file + if (!new_stream->stream->Open(buffer, buffer_size)) { + game->DebugPrint(IGameInterface::WL_ERROR, "invalid stream"); block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - //Create a new sequence - new_sequence = AddSequence( m_curSequence, m_curSequence, ( CSequence::SQ_RUN | CSequence::SQ_PENDING ), icarus ); + // Create a new sequence + new_sequence = AddSequence(m_curSequence, m_curSequence, (CSequence::SQ_RUN | CSequence::SQ_PENDING), icarus); - m_curSequence->AddChild( new_sequence ); + m_curSequence->AddChild(new_sequence); // Interpret the command blocks and route them properly - if ( S_FAILED( Route( new_sequence, new_stream, icarus )) ) - { - //Error code is set inside of Route() + if (S_FAILED(Route(new_sequence, new_stream, icarus))) { + // Error code is set inside of Route() block->Free(icarus); delete block; block = NULL; @@ -472,10 +439,10 @@ int CSequencer::ParseRun( CBlock *block , CIcarus* icarus) m_curSequence = m_curSequence->GetReturn(); - assert( m_curSequence ); + assert(m_curSequence); - block->Write( CIcarus::TK_FLOAT, (float) new_sequence->GetID() , icarus); - PushCommand( block, CSequence::PUSH_FRONT ); + block->Write(CIcarus::TK_FLOAT, (float)new_sequence->GetID(), icarus); + PushCommand(block, CSequence::PUSH_FRONT); return SEQ_OK; } @@ -488,34 +455,32 @@ Parses an if statement ======================== */ -int CSequencer::ParseIf( CBlock *block, bstream_t *bstream , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CSequence *sequence; +int CSequencer::ParseIf(CBlock *block, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequence *sequence; - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, CSequence::SQ_CONDITIONAL, icarus); + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, CSequence::SQ_CONDITIONAL, icarus); - assert( sequence ); - if ( sequence == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "ParseIf: failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "ParseIf: failed to allocate container sequence"); block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Add a unique conditional identifier to the block for reference later - block->Write( CIcarus::TK_FLOAT, (float) sequence->GetID(), icarus ); + // Add a unique conditional identifier to the block for reference later + block->Write(CIcarus::TK_FLOAT, (float)sequence->GetID(), icarus); - //Push this onto the stack to mark the conditional entrance - PushCommand( block, CSequence::PUSH_FRONT ); + // Push this onto the stack to mark the conditional entrance + PushCommand(block, CSequence::PUSH_FRONT); - //Recursively obtain the conditional body - Route( sequence, bstream, icarus ); + // Recursively obtain the conditional body + Route(sequence, bstream, icarus); m_elseValid = 2; m_elseOwner = block; @@ -531,42 +496,39 @@ Parses an else statement ======================== */ -int CSequencer::ParseElse( CBlock *block, bstream_t *bstream , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - //The else is not retained +int CSequencer::ParseElse(CBlock *block, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + // The else is not retained block->Free(icarus); delete block; block = NULL; - CSequence *sequence; + CSequence *sequence; - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, CSequence::SQ_CONDITIONAL, icarus ); + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, CSequence::SQ_CONDITIONAL, icarus); - assert( sequence ); - if ( sequence == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "ParseIf: failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "ParseIf: failed to allocate container sequence"); return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Add a unique conditional identifier to the block for reference later - //TODO: Emit warning - if ( m_elseOwner == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid 'else' found!\n" ); + // Add a unique conditional identifier to the block for reference later + // TODO: Emit warning + if (m_elseOwner == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - m_elseOwner->Write( CIcarus::TK_FLOAT, (float) sequence->GetID(), icarus ); + m_elseOwner->Write(CIcarus::TK_FLOAT, (float)sequence->GetID(), icarus); - m_elseOwner->SetFlag( BF_ELSE ); + m_elseOwner->SetFlag(BF_ELSE); - //Recursively obtain the conditional body - Route( sequence, bstream, icarus ); + // Recursively obtain the conditional body + Route(sequence, bstream, icarus); m_elseValid = 0; m_elseOwner = NULL; @@ -582,56 +544,51 @@ Parses a loop command ======================== */ -int CSequencer::ParseLoop( CBlock *block, bstream_t *bstream , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CSequence *sequence; - CBlockMember *bm; - float min, max; - int rIter; - int memberNum = 0; +int CSequencer::ParseLoop(CBlock *block, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequence *sequence; + CBlockMember *bm; + float min, max; + int rIter; + int memberNum = 0; - //Set the parent - sequence = AddSequence( m_curSequence, m_curSequence, ( CSequence::SQ_LOOP | CSequence::SQ_RETAIN ), icarus ); + // Set the parent + sequence = AddSequence(m_curSequence, m_curSequence, (CSequence::SQ_LOOP | CSequence::SQ_RETAIN), icarus); - assert( sequence ); - if ( sequence == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "ParseLoop : failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "ParseLoop : failed to allocate container sequence"); block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Set the number of iterations of this sequence + // Set the number of iterations of this sequence - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); - if ( bm->GetID() == CIcarus::ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + if (bm->GetID() == CIcarus::ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - rIter = (int) game->Random( min, max ); - sequence->SetIterations( rIter ); - } - else - { - sequence->SetIterations ( (int) (*(float *) bm->GetData()) ); + rIter = (int)game->Random(min, max); + sequence->SetIterations(rIter); + } else { + sequence->SetIterations((int)(*(float *)bm->GetData())); } - //Add a unique loop identifier to the block for reference later - block->Write( CIcarus::TK_FLOAT, (float) sequence->GetID(), icarus ); + // Add a unique loop identifier to the block for reference later + block->Write(CIcarus::TK_FLOAT, (float)sequence->GetID(), icarus); - //Push this onto the stack to mark the loop entrance - PushCommand( block, CSequence::PUSH_FRONT ); + // Push this onto the stack to mark the loop entrance + PushCommand(block, CSequence::PUSH_FRONT); - //Recursively obtain the loop - Route( sequence, bstream , icarus); + // Recursively obtain the loop + Route(sequence, bstream, icarus); return SEQ_OK; } @@ -644,31 +601,29 @@ Adds a sequence that is saved until the affect is called by the parent ======================== */ -int CSequencer::AddAffect( bstream_t *bstream, int retain, int *id, CIcarus* icarus ) -{ - CSequence *sequence = AddSequence(icarus); - bstream_t new_stream; +int CSequencer::AddAffect(bstream_t *bstream, int retain, int *id, CIcarus *icarus) { + CSequence *sequence = AddSequence(icarus); + bstream_t new_stream; - sequence->SetFlag( CSequence::SQ_AFFECT | CSequence::SQ_PENDING ); + sequence->SetFlag(CSequence::SQ_AFFECT | CSequence::SQ_PENDING); - if ( retain ) - sequence->SetFlag( CSequence::SQ_RETAIN ); + if (retain) + sequence->SetFlag(CSequence::SQ_RETAIN); - //This will be replaced once it's actually used, but this will restore the route state properly - sequence->SetReturn( m_curSequence ); + // This will be replaced once it's actually used, but this will restore the route state properly + sequence->SetReturn(m_curSequence); - //We need this as a temp holder + // We need this as a temp holder new_stream.last = m_curStream; new_stream.stream = bstream->stream; - if S_FAILED( Route( sequence, &new_stream , icarus) ) - { + if S_FAILED (Route(sequence, &new_stream, icarus)) { return SEQ_FAILED; } *id = sequence->GetID(); - sequence->SetReturn( NULL ); + sequence->SetReturn(NULL); return SEQ_OK; } @@ -681,112 +636,104 @@ Parses an affect command ======================== */ -int CSequencer::ParseAffect( CBlock *block, bstream_t *bstream, CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); - CSequencer *stream_sequencer = NULL; - char *entname = NULL; - int ret; - int ent = -1; +int CSequencer::ParseAffect(CBlock *block, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequencer *stream_sequencer = NULL; + char *entname = NULL; + int ret; + int ent = -1; - entname = (char*) block->GetMemberData( 0 ); - ent = game->GetByName( entname ); + entname = (char *)block->GetMemberData(0); + ent = game->GetByName(entname); - if( ent < 0 ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (ent < 0) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' + // try to parse a 'get' command that is embeded in this 'affect' - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - switch ( id ) - { + switch (id) { // these 3 cases probably aren't necessary case CIcarus::TK_STRING: case CIcarus::TK_IDENTIFIER: case CIcarus::TK_CHAR: - p1 = (char *) bm->GetData(); + p1 = (char *)bm->GetData(); break; - case CIcarus::ID_GET: - { - int type; + case CIcarus::ID_GET: { + int type; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( 1 )); - name = (char *) block->GetMemberData( 2 ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(1)); + name = (char *)block->GetMemberData(2); - switch ( type ) // what type are they attempting to get - { + switch (type) // what type are they attempting to get + { - case CIcarus::TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( game->GetString( m_ownerID, name, &p1 ) == false) - { - block->Free(icarus); - delete block; - block = NULL; - return false; - } - break; - default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _1" ); - block->Free(icarus); - delete block; - block = NULL; - return false; - break; + case CIcarus::TK_STRING: + // only string is acceptable for affect, store result in p1 + if (game->GetString(m_ownerID, name, &p1) == false) { + block->Free(icarus); + delete block; + block = NULL; + return false; } - break; - } - default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _1"); block->Free(icarus); delete block; block = NULL; return false; break; - }//end id switch + } - if(p1) - { - ent = game->GetByName( p1 ); + break; + } + + default: + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _2"); + block->Free(icarus); + delete block; + block = NULL; + return false; + break; + } // end id switch + + if (p1) { + ent = game->GetByName(p1); } - if(ent < 0) - { // a valid entity name was not returned from the get command + if (ent < 0) { // a valid entity name was not returned from the get command game->DebugPrint(IGameInterface::WL_WARNING, "'%s' : invalid affect() target\n"); } } // end if(!ent) - if( ent >= 0 ) - { + if (ent >= 0) { int sequencerID = game->CreateIcarus(ent); stream_sequencer = icarus->FindSequencer(sequencerID); } - if (stream_sequencer == NULL) - { - game->DebugPrint(IGameInterface::WL_WARNING, "'%s' : invalid affect() target\n", entname ); + if (stream_sequencer == NULL) { + game->DebugPrint(IGameInterface::WL_WARNING, "'%s' : invalid affect() target\n", entname); - //Fast-forward out of this affect block onto the next valid code + // Fast-forward out of this affect block onto the next valid code CSequence *backSeq = m_curSequence; - CSequence *trashSeq = (CSequence*)icarus->GetSequence(); - Route( trashSeq, bstream , icarus); + CSequence *trashSeq = (CSequence *)icarus->GetSequence(); + Route(trashSeq, bstream, icarus); Recall(icarus); - DestroySequence( trashSeq, icarus ); + DestroySequence(trashSeq, icarus); m_curSequence = backSeq; block->Free(icarus); delete block; @@ -794,20 +741,19 @@ int CSequencer::ParseAffect( CBlock *block, bstream_t *bstream, CIcarus* icarus return SEQ_OK; } - if S_FAILED ( stream_sequencer->AddAffect( bstream, (int) m_curSequence->HasFlag( CSequence::SQ_RETAIN ), &ret, icarus) ) - { + if S_FAILED (stream_sequencer->AddAffect(bstream, (int)m_curSequence->HasFlag(CSequence::SQ_RETAIN), &ret, icarus)) { block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - //Hold onto the id for later use - //FIXME: If the target sequence is freed, what then? (!suspect!) + // Hold onto the id for later use + // FIXME: If the target sequence is freed, what then? (!suspect!) - block->Write( CIcarus::TK_FLOAT, (float) ret, icarus ); + block->Write(CIcarus::TK_FLOAT, (float)ret, icarus); - PushCommand( block, CSequence::PUSH_FRONT ); + PushCommand(block, CSequence::PUSH_FRONT); /* //Don't actually do these right now, we're just pre-processing (parsing) the affect if( ent ) @@ -825,46 +771,44 @@ ParseTask ------------------------- */ -int CSequencer::ParseTask( CBlock *block, bstream_t *bstream , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CSequence *sequence; - CTaskGroup *group; - const char *taskName; +int CSequencer::ParseTask(CBlock *block, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequence *sequence; + CTaskGroup *group; + const char *taskName; - //Setup the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, CSequence::SQ_TASK | CSequence::SQ_RETAIN, icarus); - m_curSequence->AddChild( sequence ); + // Setup the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, CSequence::SQ_TASK | CSequence::SQ_RETAIN, icarus); + m_curSequence->AddChild(sequence); - //Get the name of this task for reference later - taskName = (const char *) block->GetMemberData( 0 ); + // Get the name of this task for reference later + taskName = (const char *)block->GetMemberData(0); - //Get a new task group from the task manager - group = m_taskManager->AddTaskGroup( taskName, icarus ); + // Get a new task group from the task manager + group = m_taskManager->AddTaskGroup(taskName, icarus); - if ( group == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "error : unable to allocate a new task group" ); + if (group == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "error : unable to allocate a new task group"); block->Free(icarus); delete block; block = NULL; return SEQ_FAILED; } - //The current group is set to this group, all subsequent commands (until a block end) will fall into this task group - group->SetParent( m_curGroup ); + // The current group is set to this group, all subsequent commands (until a block end) will fall into this task group + group->SetParent(m_curGroup); m_curGroup = group; - //Keep an association between this task and the container sequence - AddTaskSequence( sequence, group ); + // Keep an association between this task and the container sequence + AddTaskSequence(sequence, group); - //PushCommand( block, PUSH_FRONT ); + // PushCommand( block, PUSH_FRONT ); block->Free(icarus); delete block; block = NULL; - //Recursively obtain the loop - Route( sequence, bstream, icarus ); + // Recursively obtain the loop + Route(sequence, bstream, icarus); return SEQ_OK; } @@ -877,49 +821,44 @@ Properly handles and routes commands to the sequencer ======================== */ -//FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently +// FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently -//FIXME: A sequencer cannot properly affect itself +// FIXME: A sequencer cannot properly affect itself -int CSequencer::Route( CSequence *sequence, bstream_t *bstream , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CBlockStream *stream; - CBlock *block; +int CSequencer::Route(CSequence *sequence, bstream_t *bstream, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlockStream *stream; + CBlock *block; - //Take the stream as the current stream + // Take the stream as the current stream m_curStream = bstream; stream = bstream->stream; m_curSequence = sequence; - //Obtain all blocks - while ( stream->BlockAvailable() ) - { - block = new CBlock; //deleted in Free() - stream->ReadBlock( block , icarus); + // Obtain all blocks + while (stream->BlockAvailable()) { + block = new CBlock; // deleted in Free() + stream->ReadBlock(block, icarus); - //TEMP: HACK! - if ( m_elseValid ) + // TEMP: HACK! + if (m_elseValid) m_elseValid--; - switch( block->GetBlockID() ) - { - //Marks the end of a blocked section + switch (block->GetBlockID()) { + // Marks the end of a blocked section case CIcarus::ID_BLOCK_END: - //Save this as a pre-process marker - PushCommand( block, CSequence::PUSH_FRONT ); + // Save this as a pre-process marker + PushCommand(block, CSequence::PUSH_FRONT); - if ( m_curSequence->HasFlag( CSequence::SQ_RUN ) || m_curSequence->HasFlag( CSequence::SQ_AFFECT ) ) - { - //Go back to the last stream + if (m_curSequence->HasFlag(CSequence::SQ_RUN) || m_curSequence->HasFlag(CSequence::SQ_AFFECT)) { + // Go back to the last stream m_curStream = bstream->last; } - if ( m_curSequence->HasFlag( CSequence::SQ_TASK ) ) - { - //Go back to the last stream + if (m_curSequence->HasFlag(CSequence::SQ_TASK)) { + // Go back to the last stream m_curStream = bstream->last; m_curGroup = m_curGroup->GetParent(); } @@ -929,60 +868,59 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream , CIcarus* icarus return SEQ_OK; break; - //Affect pre-processor + // Affect pre-processor case CIcarus::ID_AFFECT: - if S_FAILED( ParseAffect( block, bstream, icarus ) ) + if S_FAILED (ParseAffect(block, bstream, icarus)) return SEQ_FAILED; break; - //Run pre-processor + // Run pre-processor case CIcarus::ID_RUN: - if S_FAILED( ParseRun( block, icarus ) ) + if S_FAILED (ParseRun(block, icarus)) return SEQ_FAILED; break; - //Loop pre-processor + // Loop pre-processor case CIcarus::ID_LOOP: - if S_FAILED( ParseLoop( block, bstream, icarus ) ) + if S_FAILED (ParseLoop(block, bstream, icarus)) return SEQ_FAILED; break; - //Conditional pre-processor + // Conditional pre-processor case CIcarus::ID_IF: - if S_FAILED( ParseIf( block, bstream, icarus ) ) + if S_FAILED (ParseIf(block, bstream, icarus)) return SEQ_FAILED; break; case CIcarus::ID_ELSE: - //TODO: Emit warning - if ( m_elseValid == 0 ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid 'else' found!\n" ); + // TODO: Emit warning + if (m_elseValid == 0) { + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - if S_FAILED( ParseElse( block, bstream, icarus ) ) + if S_FAILED (ParseElse(block, bstream, icarus)) return SEQ_FAILED; break; case CIcarus::ID_TASK: - if S_FAILED( ParseTask( block, bstream, icarus ) ) + if S_FAILED (ParseTask(block, bstream, icarus)) return SEQ_FAILED; break; - //FIXME: For now this is to catch problems, but can ultimately be removed + // FIXME: For now this is to catch problems, but can ultimately be removed case CIcarus::ID_WAIT: case CIcarus::ID_PRINT: case CIcarus::ID_SOUND: @@ -1001,26 +939,25 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream , CIcarus* icarus case CIcarus::ID_WAITSIGNAL: case CIcarus::ID_PLAY: - //Commands go directly into the sequence without pre-process - PushCommand( block, CSequence::PUSH_FRONT ); + // Commands go directly into the sequence without pre-process + PushCommand(block, CSequence::PUSH_FRONT); break; - //Error + // Error default: - game->DebugPrint(IGameInterface::WL_ERROR, "'%d' : invalid block ID", block->GetBlockID() ); + game->DebugPrint(IGameInterface::WL_ERROR, "'%d' : invalid block ID", block->GetBlockID()); return SEQ_FAILED; break; } } - //Check for a run sequence, it must be marked - if ( m_curSequence->HasFlag( CSequence::SQ_RUN ) ) - { + // Check for a run sequence, it must be marked + if (m_curSequence->HasFlag(CSequence::SQ_RUN)) { block = new CBlock; - block->Create( CIcarus::ID_BLOCK_END ); - PushCommand( block, CSequence::PUSH_FRONT ); //mark the end of the run + block->Create(CIcarus::ID_BLOCK_END); + PushCommand(block, CSequence::PUSH_FRONT); // mark the end of the run /* //Free the stream @@ -1031,17 +968,16 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream , CIcarus* icarus return SEQ_OK; } - //Check to start the communication - if ( ( bstream->last == NULL ) && ( m_numCommands > 0 ) ) - { - //Everything is routed, so get it all rolling - Prime( m_taskManager, PopCommand( CSequence::POP_BACK ), icarus ); + // Check to start the communication + if ((bstream->last == NULL) && (m_numCommands > 0)) { + // Everything is routed, so get it all rolling + Prime(m_taskManager, PopCommand(CSequence::POP_BACK), icarus); } m_curStream = bstream->last; - //Free the stream - DeleteStream( bstream ); + // Free the stream + DeleteStream(bstream); return SEQ_OK; } @@ -1054,29 +990,24 @@ Checks for run command pre-processing ======================== */ -//Directly changes the parameter to avoid excess push/pop +// Directly changes the parameter to avoid excess push/pop -void CSequencer::CheckRun( CBlock **command , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CBlock *block = *command; +void CSequencer::CheckRun(CBlock **command, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - //Check for a run command - if ( block->GetBlockID() == CIcarus::ID_RUN ) - { - int id = (int) (*(float *) block->GetMemberData( 1 )); + // Check for a run command + if (block->GetBlockID() == CIcarus::ID_RUN) { + int id = (int)(*(float *)block->GetMemberData(1)); - game->DebugPrint(IGameInterface::WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *) block->GetMemberData(0), game->GetTime() ); + game->DebugPrint(IGameInterface::WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *)block->GetMemberData(0), game->GetTime()); - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; @@ -1084,54 +1015,47 @@ void CSequencer::CheckRun( CBlock **command , CIcarus* icarus) *command = NULL; } - m_curSequence = GetSequence( id ); + m_curSequence = GetSequence(id); - //TODO: Emit warning - assert( m_curSequence ); - if ( m_curSequence == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find 'run' sequence!\n" ); + // TODO: Emit warning + assert(m_curSequence); + if (m_curSequence == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find 'run' sequence!\n"); *command = NULL; return; } - if ( m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( CSequence::POP_BACK ); + if (m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(CSequence::POP_BACK); - Prep( command , icarus); //Account for any other pre-processes + Prep(command, icarus); // Account for any other pre-processes return; } return; } - //Check for the end of a run - if ( ( block->GetBlockID() == CIcarus::ID_BLOCK_END ) && ( m_curSequence->HasFlag( CSequence::SQ_RUN ) ) ) - { - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Check for the end of a run + if ((block->GetBlockID() == CIcarus::ID_BLOCK_END) && (m_curSequence->HasFlag(CSequence::SQ_RUN))) { + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - m_curSequence = ReturnSequence( m_curSequence ); + m_curSequence = ReturnSequence(m_curSequence); - if ( m_curSequence && m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( CSequence::POP_BACK ); + if (m_curSequence && m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(CSequence::POP_BACK); - Prep( command, icarus ); //Account for any other pre-processes + Prep(command, icarus); // Account for any other pre-processes return; } - //FIXME: Check this... + // FIXME: Check this... } } @@ -1141,46 +1065,43 @@ EvaluateConditional ------------------------- */ -//FIXME: This function will be written better later once the functionality of the ideas here are tested +// FIXME: This function will be written better later once the functionality of the ideas here are tested -int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CBlockMember *bm; - char tempString1[128], tempString2[128]; - vec3_t vec; - int id, i, oper, memberNum = 0; - char *p1 = NULL, *p2 = NULL; - int t1, t2; +int CSequencer::EvaluateConditional(CBlock *block, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlockMember *bm; + char tempString1[128], tempString2[128]; + vec3_t vec; + int id, i, oper, memberNum = 0; + char *p1 = NULL, *p2 = NULL; + int t1, t2; // // Get the first parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t1 = id; - switch ( id ) - { + switch (id) { case CIcarus::TK_FLOAT: - sprintf( (char *) tempString1, "%.3f", *(float *) bm->GetData() ); - p1 = (char *) tempString1; + sprintf((char *)tempString1, "%.3f", *(float *)bm->GetData()); + p1 = (char *)tempString1; break; case CIcarus::TK_VECTOR: tempString1[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - sprintf( (char *) tempString1, "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + sprintf((char *)tempString1, "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; break; @@ -1188,115 +1109,106 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) case CIcarus::TK_IDENTIFIER: case CIcarus::TK_CHAR: - p1 = (char *) bm->GetData(); + p1 = (char *)bm->GetData(); break; - case CIcarus::ID_GET: - { - int type; - char *name; + case CIcarus::ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t1 = type; + // Get the type returned and hold onto it + t1 = type; - switch ( type ) - { - case CIcarus::TK_FLOAT: - { - float fVal; + switch (type) { + case CIcarus::TK_FLOAT: { + float fVal; - if ( game->GetFloat( m_ownerID, name, &fVal ) == false) - return false; + if (game->GetFloat(m_ownerID, name, &fVal) == false) + return false; - sprintf( (char *) tempString1, "%.3f", fVal ); - p1 = (char *) tempString1; - } + sprintf((char *)tempString1, "%.3f", fVal); + p1 = (char *)tempString1; + } - break; + break; - case CIcarus::TK_INT: - { - float fVal; + case CIcarus::TK_INT: { + float fVal; - if ( game->GetFloat( m_ownerID, name, &fVal ) == false) - return false; + if (game->GetFloat(m_ownerID, name, &fVal) == false) + return false; - sprintf( (char *) tempString1, "%d", (int) fVal ); - p1 = (char *) tempString1; - } - break; + sprintf((char *)tempString1, "%d", (int)fVal); + p1 = (char *)tempString1; + } break; - case CIcarus::TK_STRING: + case CIcarus::TK_STRING: - if ( game->GetString( m_ownerID, name, &p1 ) == false) - return false; + if (game->GetString(m_ownerID, name, &p1) == false) + return false; - break; + break; - case CIcarus::TK_VECTOR: - { - vec3_t vVal; + case CIcarus::TK_VECTOR: { + vec3_t vVal; - if ( game->GetVector( m_ownerID, name, vVal ) == false) - return false; + if (game->GetVector(m_ownerID, name, vVal) == false) + return false; - sprintf( (char *) tempString1, "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p1 = (char *) tempString1; - } + sprintf((char *)tempString1, "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p1 = (char *)tempString1; + } - break; + break; } break; } - case CIcarus::ID_RANDOM: - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements + case CIcarus::ID_RANDOM: { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - //A float value is returned from the function - t1 = CIcarus::TK_FLOAT; + // A float value is returned from the function + t1 = CIcarus::TK_FLOAT; - sprintf( (char *) tempString1, "%.3f", game->Random( min, max ) ); - p1 = (char *) tempString1; - } + sprintf((char *)tempString1, "%.3f", game->Random(min, max)); + p1 = (char *)tempString1; + } - break; + break; - case CIcarus::ID_TAG: - { - char *name; - float type; + case CIcarus::ID_TAG: { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t1 = CIcarus::TK_VECTOR; + t1 = CIcarus::TK_VECTOR; - //TODO: Emit warning - if ( game->GetTag( m_ownerID, name, (int) type, vec ) == false) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (game->GetTag(m_ownerID, name, (int)type, vec) == false) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - sprintf( (char *) tempString1, "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + sprintf((char *)tempString1, "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on conditional"); return false; break; } @@ -1305,11 +1217,10 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) // Get the comparison operator // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); - switch ( id ) - { + switch (id) { case CIcarus::TK_EQUALS: case CIcarus::TK_GREATER_THAN: case CIcarus::TK_LESS_THAN: @@ -1318,8 +1229,8 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) break; default: - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid operator type found on conditional!\n" ); - return false; //FIXME: Emit warning + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid operator type found on conditional!\n"); + return false; // FIXME: Emit warning break; } @@ -1327,30 +1238,28 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) // Get the second parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t2 = id; - switch ( id ) - { + switch (id) { case CIcarus::TK_FLOAT: - sprintf( (char *) tempString2, "%.3f", *(float *) bm->GetData() ); - p2 = (char *) tempString2; + sprintf((char *)tempString2, "%.3f", *(float *)bm->GetData()); + p2 = (char *)tempString2; break; case CIcarus::TK_VECTOR: tempString2[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - sprintf( (char *) tempString2, "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + sprintf((char *)tempString2, "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; break; @@ -1358,67 +1267,61 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) case CIcarus::TK_IDENTIFIER: case CIcarus::TK_CHAR: - p2 = (char *) bm->GetData(); + p2 = (char *)bm->GetData(); break; - case CIcarus::ID_GET: - { - int type; - char *name; + case CIcarus::ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t2 = type; + // Get the type returned and hold onto it + t2 = type; - switch ( type ) - { - case CIcarus::TK_FLOAT: - { - float fVal; + switch (type) { + case CIcarus::TK_FLOAT: { + float fVal; - if ( game->GetFloat( m_ownerID, name, &fVal ) == false) - return false; + if (game->GetFloat(m_ownerID, name, &fVal) == false) + return false; - sprintf( (char *) tempString2, "%.3f", fVal ); - p2 = (char *) tempString2; - } + sprintf((char *)tempString2, "%.3f", fVal); + p2 = (char *)tempString2; + } - break; + break; - case CIcarus::TK_INT: - { - float fVal; + case CIcarus::TK_INT: { + float fVal; - if ( game->GetFloat( m_ownerID, name, &fVal ) == false) - return false; + if (game->GetFloat(m_ownerID, name, &fVal) == false) + return false; - sprintf( (char *) tempString2, "%d", (int) fVal ); - p2 = (char *) tempString2; - } - break; + sprintf((char *)tempString2, "%d", (int)fVal); + p2 = (char *)tempString2; + } break; - case CIcarus::TK_STRING: + case CIcarus::TK_STRING: - if ( game->GetString( m_ownerID, name, &p2 ) == false) - return false; + if (game->GetString(m_ownerID, name, &p2) == false) + return false; - break; + break; - case CIcarus::TK_VECTOR: - { - vec3_t vVal; + case CIcarus::TK_VECTOR: { + vec3_t vVal; - if ( game->GetVector( m_ownerID, name, vVal ) == false) - return false; + if (game->GetVector(m_ownerID, name, vVal) == false) + return false; - sprintf( (char *) tempString2, "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p2 = (char *) tempString2; - } + sprintf((char *)tempString2, "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p2 = (char *)tempString2; + } - break; + break; } break; @@ -1426,54 +1329,53 @@ int CSequencer::EvaluateConditional( CBlock *block , CIcarus* icarus) case CIcarus::ID_RANDOM: - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements + { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - //A float value is returned from the function - t2 = CIcarus::TK_FLOAT; + // A float value is returned from the function + t2 = CIcarus::TK_FLOAT; - sprintf( (char *) tempString2, "%.3f", game->Random( min, max ) ); - p2 = (char *) tempString2; - } + sprintf((char *)tempString2, "%.3f", game->Random(min, max)); + p2 = (char *)tempString2; + } - break; + break; case CIcarus::ID_TAG: - { - char *name; - float type; + { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t2 = CIcarus::TK_VECTOR; + t2 = CIcarus::TK_VECTOR; - //TODO: Emit warning - if ( game->GetTag( m_ownerID, name, (int) type, vec ) == false) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (game->GetTag(m_ownerID, name, (int)type, vec) == false) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - sprintf( (char *) tempString2, "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + sprintf((char *)tempString2, "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on conditional"); return false; break; } - return game->Evaluate( t1, p1, t2, p2, oper ); + return game->Evaluate(t1, p1, t2, p2, oper); } /* @@ -1484,49 +1386,39 @@ Checks for if statement pre-processing ======================== */ -void CSequencer::CheckIf( CBlock **command , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CBlock *block = *command; - int successID, failureID; - CSequence *successSeq, *failureSeq; +void CSequencer::CheckIf(CBlock **command, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlock *block = *command; + int successID, failureID; + CSequence *successSeq, *failureSeq; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == CIcarus::ID_IF ) - { - int ret = EvaluateConditional( block, icarus ); + if (block->GetBlockID() == CIcarus::ID_IF) { + int ret = EvaluateConditional(block, icarus); - if ( ret /*TRUE*/ ) - { - if ( block->HasFlag( BF_ELSE ) ) - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 2 )); - } - else - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); + if (ret /*TRUE*/) { + if (block->HasFlag(BF_ELSE)) { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 2)); + } else { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); } - successSeq = GetSequence( successID ); + successSeq = GetSequence(successID); - //TODO: Emit warning - assert( successSeq ); - if ( successSeq == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find conditional success sequence!\n" ); + // TODO: Emit warning + assert(successSeq); + if (successSeq == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find conditional success sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; @@ -1535,34 +1427,29 @@ void CSequencer::CheckIf( CBlock **command , CIcarus* icarus) m_curSequence = successSeq; - //Recursively work out any other pre-processors - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // Recursively work out any other pre-processors + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - if ( ( ret == false ) && ( block->HasFlag( BF_ELSE ) ) ) - { - failureID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); - failureSeq = GetSequence( failureID ); + if ((ret == false) && (block->HasFlag(BF_ELSE))) { + failureID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); + failureSeq = GetSequence(failureID); - //TODO: Emit warning - assert( failureSeq ); - if ( failureSeq == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find conditional failure sequence!\n" ); + // TODO: Emit warning + assert(failureSeq); + if (failureSeq == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find conditional failure sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; @@ -1571,67 +1458,58 @@ void CSequencer::CheckIf( CBlock **command , CIcarus* icarus) m_curSequence = failureSeq; - //Recursively work out any other pre-processors - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // Recursively work out any other pre-processors + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - //Conditional failed, just move on to the next command - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // Conditional failed, just move on to the next command + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - if ( ( block->GetBlockID() == CIcarus::ID_BLOCK_END ) && ( m_curSequence->HasFlag( CSequence::SQ_CONDITIONAL ) ) ) - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + if ((block->GetBlockID() == CIcarus::ID_BLOCK_END) && (m_curSequence->HasFlag(CSequence::SQ_CONDITIONAL))) { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - //Back out of the conditional and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); + // Back out of the conditional and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); - //This can safely happen - if ( m_curSequence == NULL ) - { + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); } } @@ -1643,68 +1521,58 @@ Checks for loop command pre-processing ======================== */ -void CSequencer::CheckLoop( CBlock **command , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); - CBlockMember *bm; - CBlock *block = *command; - float min, max; - int iterations; - int loopID; - int memberNum = 0; - - if ( block == NULL ) +void CSequencer::CheckLoop(CBlock **command, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlockMember *bm; + CBlock *block = *command; + float min, max; + int iterations; + int loopID; + int memberNum = 0; + + if (block == NULL) return; - //Check for a loop - if ( block->GetBlockID() == CIcarus::ID_LOOP ) - { - //Get the loop ID - bm = block->GetMember( memberNum++ ); + // Check for a loop + if (block->GetBlockID() == CIcarus::ID_LOOP) { + // Get the loop ID + bm = block->GetMember(memberNum++); - if ( bm->GetID() == CIcarus::ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + if (bm->GetID() == CIcarus::ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - iterations = (int) game->Random( min, max ); - } - else - { - iterations = (int) (*(float *) bm->GetData()); + iterations = (int)game->Random(min, max); + } else { + iterations = (int)(*(float *)bm->GetData()); } - loopID = (int) (*(float *) block->GetMemberData( memberNum++ )); + loopID = (int)(*(float *)block->GetMemberData(memberNum++)); - CSequence *loop = GetSequence( loopID ); + CSequence *loop = GetSequence(loopID); - //TODO: Emit warning - assert( loop ); - if ( loop == NULL ) - { - game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find 'loop' sequence!\n" ); + // TODO: Emit warning + assert(loop); + if (loop == NULL) { + game->DebugPrint(IGameInterface::WL_ERROR, "Unable to find 'loop' sequence!\n"); *command = NULL; return; } - assert( loop->GetParent() ); - if ( loop->GetParent() == NULL ) - { + assert(loop->GetParent()); + if (loop->GetParent() == NULL) { *command = NULL; return; } - //Restore the count if it has been lost - loop->SetIterations( iterations ); + // Restore the count if it has been lost + loop->SetIterations(iterations); - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; @@ -1713,65 +1581,56 @@ void CSequencer::CheckLoop( CBlock **command , CIcarus* icarus) m_curSequence = loop; - //Recursively work out any other pre-processors - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // Recursively work out any other pre-processors + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - //Check for the end of the loop - if ( ( block->GetBlockID() == CIcarus::ID_BLOCK_END ) && ( m_curSequence->HasFlag( CSequence::SQ_LOOP ) ) ) - { - //We don't want to decrement -1 - if ( m_curSequence->GetIterations() > 0 ) - m_curSequence->SetIterations( m_curSequence->GetIterations()-1 ); //Nice, eh? + // Check for the end of the loop + if ((block->GetBlockID() == CIcarus::ID_BLOCK_END) && (m_curSequence->HasFlag(CSequence::SQ_LOOP))) { + // We don't want to decrement -1 + if (m_curSequence->GetIterations() > 0) + m_curSequence->SetIterations(m_curSequence->GetIterations() - 1); // Nice, eh? - //Either there's another iteration, or it's infinite - if ( m_curSequence->GetIterations() != 0 ) - { - //Another iteration is going to happen, so this will need to be considered again - PushCommand( block, CSequence::PUSH_FRONT ); + // Either there's another iteration, or it's infinite + if (m_curSequence->GetIterations() != 0) { + // Another iteration is going to happen, so this will need to be considered again + PushCommand(block, CSequence::PUSH_FRONT); - *command = PopCommand( CSequence::POP_BACK ); - Prep( command, icarus ); + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; - } - else - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + } else { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - //Back out of the loop and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); + // Back out of the loop and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); - //This can safely happen - if ( m_curSequence == NULL ) - { + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( CSequence::POP_BACK ); - Prep( command, icarus); + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); } } } @@ -1784,33 +1643,28 @@ Checks for flush command pre-processing ======================== */ -void CSequencer::CheckFlush( CBlock **command, CIcarus* icarus) -{ - CBlock *block = *command; +void CSequencer::CheckFlush(CBlock **command, CIcarus *icarus) { + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == CIcarus::ID_FLUSH ) - { - //Flush the sequence - Flush( m_curSequence, icarus ); + if (block->GetBlockID() == CIcarus::ID_FLUSH) { + // Flush the sequence + Flush(m_curSequence, icarus); - //Check to retain it - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } @@ -1824,137 +1678,121 @@ Checks for affect command pre-processing ======================== */ -void CSequencer::CheckAffect( CBlock **command , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); +void CSequencer::CheckAffect(CBlock **command, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); CBlock *block = *command; - int ent = -1; - char *entname = NULL; - int memberNum = 0; + int ent = -1; + char *entname = NULL; + int memberNum = 0; - if ( block == NULL ) - { + if (block == NULL) { return; } - if ( block->GetBlockID() == CIcarus::ID_AFFECT ) - { - CSequencer *sequencer = NULL; - entname = (char*) block->GetMemberData( memberNum++ ); - ent = game->GetByName( entname ); + if (block->GetBlockID() == CIcarus::ID_AFFECT) { + CSequencer *sequencer = NULL; + entname = (char *)block->GetMemberData(memberNum++); + ent = game->GetByName(entname); - if( ent < 0 ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (ent < 0) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' + // try to parse a 'get' command that is embeded in this 'affect' - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - switch ( id ) - { - // these 3 cases probably aren't necessary - case CIcarus::TK_STRING: - case CIcarus::TK_IDENTIFIER: - case CIcarus::TK_CHAR: - p1 = (char *) bm->GetData(); + switch (id) { + // these 3 cases probably aren't necessary + case CIcarus::TK_STRING: + case CIcarus::TK_IDENTIFIER: + case CIcarus::TK_CHAR: + p1 = (char *)bm->GetData(); break; - case CIcarus::ID_GET: + case CIcarus::ID_GET: { + int type; + + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); + + switch (type) // what type are they attempting to get { - int type; - - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); - - switch ( type ) // what type are they attempting to get - { - - case CIcarus::TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( game->GetString( m_ownerID, name, &p1 ) == false) - { - return; - } - break; - default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _1" ); - return; - break; - } + case CIcarus::TK_STRING: + // only string is acceptable for affect, store result in p1 + if (game->GetString(m_ownerID, name, &p1) == false) { + return; + } break; - } - default: - //FIXME: Make an enum id for the error... - game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _1"); return; break; - }//end id switch + } - if(p1) - { - ent = game->GetByName( p1 ); + break; + } + + default: + // FIXME: Make an enum id for the error... + game->DebugPrint(IGameInterface::WL_ERROR, "Invalid parameter type on affect _2"); + return; + break; + } // end id switch + + if (p1) { + ent = game->GetByName(p1); } - if(ent < 0) - { // a valid entity name was not returned from the get command + if (ent < 0) { // a valid entity name was not returned from the get command game->DebugPrint(IGameInterface::WL_WARNING, "'%s' : invalid affect() target\n"); } } // end if(!ent) - if( ent >= 0) - { + if (ent >= 0) { int sequencerID = game->CreateIcarus(ent); sequencer = icarus->FindSequencer(sequencerID); } - if(memberNum == 0) - { //there was no get, increment manually before next step + if (memberNum == 0) { // there was no get, increment manually before next step memberNum++; } - int type = (int) (*(float *) block->GetMemberData( memberNum )); - int id = (int) (*(float *) block->GetMemberData( memberNum+1 )); + int type = (int)(*(float *)block->GetMemberData(memberNum)); + int id = (int)(*(float *)block->GetMemberData(memberNum + 1)); - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - //NOTENOTE: If this isn't found, continue on to the next command - if ( sequencer == NULL ) - { - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // NOTENOTE: If this isn't found, continue on to the next command + if (sequencer == NULL) { + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - sequencer->Affect( id, type , icarus); + sequencer->Affect(id, type, icarus); - *command = PopCommand( CSequence::POP_BACK ); - Prep( command, icarus ); - if( ent >= 0 ) - { // ents need to update upon being affected + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); + if (ent >= 0) { // ents need to update upon being affected int sequencerID = game->CreateIcarus(ent); - CSequencer* entsequencer = icarus->FindSequencer(sequencerID); - CTaskManager* taskmanager = entsequencer->GetTaskManager(); - if(taskmanager) - { + CSequencer *entsequencer = icarus->FindSequencer(sequencerID); + CTaskManager *taskmanager = entsequencer->GetTaskManager(); + if (taskmanager) { taskmanager->Update(icarus); } } @@ -1962,41 +1800,33 @@ void CSequencer::CheckAffect( CBlock **command , CIcarus* icarus) return; } - if ( ( block->GetBlockID() == CIcarus::ID_BLOCK_END ) && ( m_curSequence->HasFlag( CSequence::SQ_AFFECT ) ) ) - { - if ( m_curSequence->HasFlag(CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == CIcarus::ID_BLOCK_END) && (m_curSequence->HasFlag(CSequence::SQ_AFFECT))) { + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - m_curSequence = ReturnSequence( m_curSequence ); + m_curSequence = ReturnSequence(m_curSequence); - if ( m_curSequence == NULL ) - { + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); - if( ent >= 0) - { // ents need to update upon being affected + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); + if (ent >= 0) { // ents need to update upon being affected int sequencerID = game->CreateIcarus(ent); - CSequencer* entsequencer = icarus->FindSequencer(sequencerID); - CTaskManager* taskmanager = entsequencer->GetTaskManager(); - if(taskmanager) - { + CSequencer *entsequencer = icarus->FindSequencer(sequencerID); + CTaskManager *taskmanager = entsequencer->GetTaskManager(); + if (taskmanager) { taskmanager->Update(icarus); } } - } } @@ -2006,100 +1836,88 @@ CheckDo ------------------------- */ -void CSequencer::CheckDo( CBlock **command , CIcarus* icarus) -{ - IGameInterface* game = icarus->GetGame(); +void CSequencer::CheckDo(CBlock **command, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == CIcarus::ID_DO ) - { - //Get the sequence - const char *groupName = (const char *) block->GetMemberData( 0 ); - CTaskGroup *group = m_taskManager->GetTaskGroup( groupName, icarus ); - CSequence *sequence = GetTaskSequence( group ); - - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - game->DebugPrint(IGameInterface::WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName ); + if (block->GetBlockID() == CIcarus::ID_DO) { + // Get the sequence + const char *groupName = (const char *)block->GetMemberData(0); + CTaskGroup *group = m_taskManager->GetTaskGroup(groupName, icarus); + CSequence *sequence = GetTaskSequence(group); + + // TODO: Emit warning + assert(group); + if (group == NULL) { + // TODO: Give name/number of entity trying to execute, too + game->DebugPrint(IGameInterface::WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName); *command = NULL; return; } - //TODO: Emit warning - assert( sequence ); - if ( sequence == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - game->DebugPrint(IGameInterface::WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName ); + // TODO: Emit warning + assert(sequence); + if (sequence == NULL) { + // TODO: Give name/number of entity trying to execute, too + game->DebugPrint(IGameInterface::WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName); *command = NULL; return; } - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - //Set this to our current sequence - sequence->SetReturn( m_curSequence ); + // Set this to our current sequence + sequence->SetReturn(m_curSequence); m_curSequence = sequence; - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - //Mark all the following commands as being in the task - m_taskManager->MarkTask( group->GetGUID(), TASK_START, icarus ); + // Mark all the following commands as being in the task + m_taskManager->MarkTask(group->GetGUID(), TASK_START, icarus); - //Recursively work out any other pre-processors - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + // Recursively work out any other pre-processors + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); return; } - if ( ( block->GetBlockID() == CIcarus::ID_BLOCK_END ) && ( m_curSequence->HasFlag( CSequence::SQ_TASK ) ) ) - { - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == CIcarus::ID_BLOCK_END) && (m_curSequence->HasFlag(CSequence::SQ_TASK))) { + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; *command = NULL; } - m_taskManager->MarkTask( m_curGroup->GetGUID(), TASK_END, icarus ); + m_taskManager->MarkTask(m_curGroup->GetGUID(), TASK_END, icarus); m_curGroup = m_curGroup->GetParent(); - CSequence *returnSeq = ReturnSequence( m_curSequence ); - m_curSequence->SetReturn( NULL ); + CSequence *returnSeq = ReturnSequence(m_curSequence); + m_curSequence->SetReturn(NULL); m_curSequence = returnSeq; - if ( m_curSequence == NULL ) - { + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( CSequence::POP_BACK ); - Prep( command , icarus); + *command = PopCommand(CSequence::POP_BACK); + Prep(command, icarus); } } @@ -2111,15 +1929,14 @@ Handles internal sequencer maintenance ======================== */ -void CSequencer::Prep( CBlock **command , CIcarus* icarus) -{ - //Check all pre-processes - CheckAffect( command , icarus); - CheckFlush( command , icarus); - CheckLoop( command , icarus); - CheckRun( command , icarus); - CheckIf( command , icarus); - CheckDo( command , icarus); +void CSequencer::Prep(CBlock **command, CIcarus *icarus) { + // Check all pre-processes + CheckAffect(command, icarus); + CheckFlush(command, icarus); + CheckLoop(command, icarus); + CheckRun(command, icarus); + CheckIf(command, icarus); + CheckDo(command, icarus); } /* @@ -2130,13 +1947,11 @@ Starts communication between the task manager and this sequencer ======================== */ -int CSequencer::Prime( CTaskManager *taskManager, CBlock *command , CIcarus* icarus) -{ - Prep( &command , icarus); +int CSequencer::Prime(CTaskManager *taskManager, CBlock *command, CIcarus *icarus) { + Prep(&command, icarus); - if ( command ) - { - taskManager->SetCommand( command, CSequence::PUSH_BACK, icarus ); + if (command) { + taskManager->SetCommand(command, CSequence::PUSH_BACK, icarus); } return SEQ_OK; @@ -2150,54 +1965,48 @@ Handles a completed task and returns a new task to be completed ======================== */ -int CSequencer::Callback( CTaskManager *taskManager, CBlock *block, int returnCode, CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); - CBlock *command; +int CSequencer::Callback(CTaskManager *taskManager, CBlock *block, int returnCode, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CBlock *command; - if (returnCode == TASK_RETURN_COMPLETE) - { - //There are no more pending commands - if ( m_curSequence == NULL ) - { + if (returnCode == TASK_RETURN_COMPLETE) { + // There are no more pending commands + if (m_curSequence == NULL) { block->Free(icarus); delete block; block = NULL; return SEQ_OK; } - //Check to retain the command - if ( m_curSequence->HasFlag( CSequence::SQ_RETAIN ) ) //This isn't true for affect sequences...? - { - PushCommand( block, CSequence::PUSH_FRONT ); - } - else + // Check to retain the command + if (m_curSequence->HasFlag(CSequence::SQ_RETAIN)) // This isn't true for affect sequences...? { + PushCommand(block, CSequence::PUSH_FRONT); + } else { block->Free(icarus); delete block; block = NULL; } - //Check for pending commands - if ( m_curSequence->GetNumCommands() <= 0 ) - { - if ( m_curSequence->GetReturn() == NULL) + // Check for pending commands + if (m_curSequence->GetNumCommands() <= 0) { + if (m_curSequence->GetReturn() == NULL) return SEQ_OK; m_curSequence = m_curSequence->GetReturn(); } - command = PopCommand( CSequence::POP_BACK ); - Prep( &command , icarus); + command = PopCommand(CSequence::POP_BACK); + Prep(&command, icarus); - if ( command ) - taskManager->SetCommand( command, CSequence::PUSH_FRONT, icarus ); + if (command) + taskManager->SetCommand(command, CSequence::PUSH_FRONT, icarus); return SEQ_OK; } - //FIXME: This could be more descriptive - game->DebugPrint(IGameInterface::WL_ERROR, "command could not be called back\n" ); + // FIXME: This could be more descriptive + game->DebugPrint(IGameInterface::WL_ERROR, "command could not be called back\n"); assert(0); return SEQ_FAILED; @@ -2209,18 +2018,13 @@ Recall ------------------------- */ -int CSequencer::Recall( CIcarus* icarus ) -{ - CBlock *block = NULL; +int CSequencer::Recall(CIcarus *icarus) { + CBlock *block = NULL; - while ( ( block = m_taskManager->RecallTask() ) != NULL ) - { - if (m_curSequence) - { - PushCommand( block, CSequence::PUSH_BACK ); - } - else - { + while ((block = m_taskManager->RecallTask()) != NULL) { + if (m_curSequence) { + PushCommand(block, CSequence::PUSH_BACK); + } else { block->Free(icarus); delete block; block = NULL; @@ -2236,29 +2040,26 @@ Affect ------------------------- */ -int CSequencer::Affect( int id, int type, CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); - CSequence *sequence = GetSequence( id ); +int CSequencer::Affect(int id, int type, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); + CSequence *sequence = GetSequence(id); - if ( sequence == NULL ) - { + if (sequence == NULL) { return SEQ_FAILED; } - switch ( type ) - { + switch (type) { case CIcarus::TYPE_FLUSH: - //Get rid of all old code - Flush( sequence, icarus ); + // Get rid of all old code + Flush(sequence, icarus); - sequence->RemoveFlag( CSequence::SQ_PENDING, true ); + sequence->RemoveFlag(CSequence::SQ_PENDING, true); m_curSequence = sequence; - Prime( m_taskManager, PopCommand( CSequence::POP_BACK ), icarus ); + Prime(m_taskManager, PopCommand(CSequence::POP_BACK), icarus); break; @@ -2266,19 +2067,18 @@ int CSequencer::Affect( int id, int type, CIcarus* icarus ) Recall(icarus); - sequence->SetReturn( m_curSequence ); + sequence->SetReturn(m_curSequence); - sequence->RemoveFlag( CSequence::SQ_PENDING, true ); + sequence->RemoveFlag(CSequence::SQ_PENDING, true); m_curSequence = sequence; - Prime( m_taskManager, PopCommand( CSequence::POP_BACK ), icarus ); + Prime(m_taskManager, PopCommand(CSequence::POP_BACK), icarus); break; - default: - game->DebugPrint(IGameInterface::WL_ERROR, "unknown affect type found" ); + game->DebugPrint(IGameInterface::WL_ERROR, "unknown affect type found"); break; } @@ -2293,17 +2093,16 @@ Pushes a commands onto the current sequence ======================== */ -int CSequencer::PushCommand( CBlock *command, int flag ) -{ - //Make sure everything is ok - assert( m_curSequence ); - if ( m_curSequence == NULL ) +int CSequencer::PushCommand(CBlock *command, int flag) { + // Make sure everything is ok + assert(m_curSequence); + if (m_curSequence == NULL) return SEQ_FAILED; - m_curSequence->PushCommand( command, flag ); + m_curSequence->PushCommand(command, flag); m_numCommands++; - //Invalid flag + // Invalid flag return SEQ_OK; } @@ -2315,15 +2114,14 @@ Pops a command off the current sequence ======================== */ -CBlock *CSequencer::PopCommand( int flag ) -{ - //Make sure everything is ok - if ( m_curSequence == NULL ) +CBlock *CSequencer::PopCommand(int flag) { + // Make sure everything is ok + if (m_curSequence == NULL) return NULL; - CBlock *block = m_curSequence->PopCommand( flag ); + CBlock *block = m_curSequence->PopCommand(flag); - if ( block != NULL ) + if (block != NULL) m_numCommands--; return block; @@ -2335,79 +2133,66 @@ RemoveSequence ------------------------- */ -//NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) +// NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) -int CSequencer::RemoveSequence( CSequence *sequence, CIcarus* icarus ) -{ - IGameInterface* game = icarus->GetGame(); +int CSequencer::RemoveSequence(CSequence *sequence, CIcarus *icarus) { + IGameInterface *game = icarus->GetGame(); CSequence *temp; int numChildren = sequence->GetNumChildren(); - //Add all the children - for ( int i = 0; i < numChildren; i++ ) - { - temp = sequence->GetChildByIndex( i ); + // Add all the children + for (int i = 0; i < numChildren; i++) { + temp = sequence->GetChildByIndex(i); - //TODO: Emit warning - assert( temp ); - if ( temp == NULL ) - { - game->DebugPrint(IGameInterface::WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n" ); + // TODO: Emit warning + assert(temp); + if (temp == NULL) { + game->DebugPrint(IGameInterface::WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n"); continue; } - //Remove the references to this sequence - temp->SetParent( NULL ); - temp->SetReturn( NULL ); - + // Remove the references to this sequence + temp->SetParent(NULL); + temp->SetReturn(NULL); } return SEQ_OK; } -int CSequencer::DestroySequence( CSequence *sequence, CIcarus* icarus ) -{ - if ( !sequence || !icarus ) +int CSequencer::DestroySequence(CSequence *sequence, CIcarus *icarus) { + if (!sequence || !icarus) return SEQ_FAILED; - //m_sequenceMap.erase( sequence->GetID() ); - m_sequences.remove( sequence ); + // m_sequenceMap.erase( sequence->GetID() ); + m_sequences.remove(sequence); - taskSequence_m::iterator tsi; - for ( tsi = m_taskSequences.begin(); tsi != m_taskSequences.end(); ) - { - if((*tsi).second == sequence) - { + taskSequence_m::iterator tsi; + for (tsi = m_taskSequences.begin(); tsi != m_taskSequences.end();) { + if ((*tsi).second == sequence) { m_taskSequences.erase(tsi++); - } - else - { + } else { ++tsi; } } // Remove this guy from his parents list. - CSequence* parent = sequence->GetParent(); - if ( parent ) - { - parent->RemoveChild( sequence ); + CSequence *parent = sequence->GetParent(); + if (parent) { + parent->RemoveChild(sequence); parent = NULL; } int curChild = sequence->GetNumChildren(); - while( curChild ) - { + while (curChild) { // Stop if we're about to go negative (invalid index!). - if ( curChild > 0 ) - { - DestroySequence( sequence->GetChildByIndex( --curChild ), icarus); - } - else + if (curChild > 0) { + DestroySequence(sequence->GetChildByIndex(--curChild), icarus); + } else break; } - icarus->DeleteSequence( sequence ); + icarus->DeleteSequence(sequence); return SEQ_OK; } @@ -2418,23 +2203,21 @@ ReturnSequence ------------------------- */ -inline CSequence *CSequencer::ReturnSequence( CSequence *sequence ) -{ - while ( sequence->GetReturn() ) - { - assert(sequence != sequence->GetReturn() ); - if ( sequence == sequence->GetReturn() ) +inline CSequence *CSequencer::ReturnSequence(CSequence *sequence) { + while (sequence->GetReturn()) { + assert(sequence != sequence->GetReturn()); + if (sequence == sequence->GetReturn()) return NULL; sequence = sequence->GetReturn(); - if ( sequence->GetNumCommands() > 0 ) + if (sequence->GetNumCommands() > 0) return sequence; } return NULL; } -//Save / Load +// Save / Load /* ------------------------- @@ -2442,10 +2225,9 @@ Save ------------------------- */ -int CSequencer::Save() -{ - taskSequence_m::iterator ti; - int numSequences = 0, id, numTasks; +int CSequencer::Save() { + taskSequence_m::iterator ti; + int numSequences = 0, id, numTasks; // Data saved here. // Owner Sequence. @@ -2462,52 +2244,50 @@ int CSequencer::Save() CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - //Get the number of sequences to save out + // Get the number of sequences to save out numSequences = /*m_sequenceMap.size();*/ m_sequences.size(); - //Save out the owner sequence - pIcarus->BufferWrite( &m_ownerID, sizeof( m_ownerID ) ); + // Save out the owner sequence + pIcarus->BufferWrite(&m_ownerID, sizeof(m_ownerID)); - //Write out the number of sequences we need to read - pIcarus->BufferWrite( &numSequences, sizeof( numSequences ) ); + // Write out the number of sequences we need to read + pIcarus->BufferWrite(&numSequences, sizeof(numSequences)); - //Second pass, save out all sequences, in order + // Second pass, save out all sequences, in order sequence_l::iterator iterSeq = m_sequences.end(); - STL_ITERATE( iterSeq, m_sequences ) - { + STL_ITERATE(iterSeq, m_sequences) { id = (*iterSeq)->GetID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); } - //Save out the taskManager + // Save out the taskManager m_taskManager->Save(); - //Save out the task sequences mapping the name to the GUIDs + // Save out the task sequences mapping the name to the GUIDs numTasks = m_taskSequences.size(); - pIcarus->BufferWrite( &numTasks, sizeof( numTasks ) ); + pIcarus->BufferWrite(&numTasks, sizeof(numTasks)); - STL_ITERATE( ti, m_taskSequences ) - { - //Save the task group's ID + STL_ITERATE(ti, m_taskSequences) { + // Save the task group's ID id = ((*ti).first)->GetGUID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); - //Save the sequence's ID + // Save the sequence's ID id = ((*ti).second)->GetID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); } - int curGroupID = ( m_curGroup == NULL ) ? -1 : m_curGroup->GetGUID(); + int curGroupID = (m_curGroup == NULL) ? -1 : m_curGroup->GetGUID(); // Right the group ID. - pIcarus->BufferWrite( &curGroupID, sizeof( curGroupID ) ); + pIcarus->BufferWrite(&curGroupID, sizeof(curGroupID)); - //Output the number of commands - pIcarus->BufferWrite( &m_numCommands, sizeof( m_numCommands ) ); + // Output the number of commands + pIcarus->BufferWrite(&m_numCommands, sizeof(m_numCommands)); - //Output the ID of the current sequence - id = ( m_curSequence != NULL ) ? m_curSequence->GetID() : -1; - pIcarus->BufferWrite( &id, sizeof( id ) ); + // Output the ID of the current sequence + id = (m_curSequence != NULL) ? m_curSequence->GetID() : -1; + pIcarus->BufferWrite(&id, sizeof(id)); return true; } @@ -2518,8 +2298,7 @@ Load ------------------------- */ -int CSequencer::Load( CIcarus* icarus, IGameInterface* game ) -{ +int CSequencer::Load(CIcarus *icarus, IGameInterface *game) { // Data expected/loaded here. // Owner Sequence. // Number of Sequences. @@ -2535,76 +2314,74 @@ int CSequencer::Load( CIcarus* icarus, IGameInterface* game ) CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - //Get the owner of this sequencer - pIcarus->BufferRead( &m_ownerID, sizeof( m_ownerID ) ); + // Get the owner of this sequencer + pIcarus->BufferRead(&m_ownerID, sizeof(m_ownerID)); - //Link the entity back to the sequencer - game->LinkGame( m_ownerID, m_id ); + // Link the entity back to the sequencer + game->LinkGame(m_ownerID, m_id); - CTaskGroup *taskGroup; - CSequence *seq; - int numSequences, seqID, taskID, numTasks; + CTaskGroup *taskGroup; + CSequence *seq; + int numSequences, seqID, taskID, numTasks; - //Get the number of sequences to read - pIcarus->BufferRead( &numSequences, sizeof( numSequences ) ); + // Get the number of sequences to read + pIcarus->BufferRead(&numSequences, sizeof(numSequences)); - //Read in all the sequences - for ( int i = 0; i < numSequences; i++ ) - { - pIcarus->BufferRead( &seqID, sizeof( seqID ) ); + // Read in all the sequences + for (int i = 0; i < numSequences; i++) { + pIcarus->BufferRead(&seqID, sizeof(seqID)); - seq = (CSequence*)icarus->GetSequence( seqID ); + seq = (CSequence *)icarus->GetSequence(seqID); - assert( seq ); + assert(seq); - STL_INSERT( m_sequences, seq ); - //m_sequenceMap[ seqID ] = seq; + STL_INSERT(m_sequences, seq); + // m_sequenceMap[ seqID ] = seq; } - //Setup the task manager - m_taskManager->Init( this ); + // Setup the task manager + m_taskManager->Init(this); - //Load the task manager + // Load the task manager m_taskManager->Load(icarus); - //Get the number of tasks in the map - pIcarus->BufferRead( &numTasks, sizeof( numTasks ) ); + // Get the number of tasks in the map + pIcarus->BufferRead(&numTasks, sizeof(numTasks)); - //Read in, and reassociate the tasks to the sequences - for ( int i = 0; i < numTasks; i++ ) - { - //Read in the task's ID - pIcarus->BufferRead( &taskID, sizeof( taskID ) ); + // Read in, and reassociate the tasks to the sequences + for (int i = 0; i < numTasks; i++) { + // Read in the task's ID + pIcarus->BufferRead(&taskID, sizeof(taskID)); - //Read in the sequence's ID - pIcarus->BufferRead( &seqID, sizeof( seqID ) ); + // Read in the sequence's ID + pIcarus->BufferRead(&seqID, sizeof(seqID)); - taskGroup = m_taskManager->GetTaskGroup( taskID , icarus); + taskGroup = m_taskManager->GetTaskGroup(taskID, icarus); - assert( taskGroup ); + assert(taskGroup); - seq = icarus->GetSequence( seqID ); + seq = icarus->GetSequence(seqID); - assert( seq ); + assert(seq); - //Associate the values - m_taskSequences[ taskGroup ] = seq; + // Associate the values + m_taskSequences[taskGroup] = seq; } - int curGroupID; + int curGroupID; - //Get the current task group - pIcarus->BufferRead( &curGroupID, sizeof( curGroupID ) ); + // Get the current task group + pIcarus->BufferRead(&curGroupID, sizeof(curGroupID)); - m_curGroup = ( curGroupID == -1 ) ? NULL : m_taskManager->GetTaskGroup( curGroupID , icarus); + m_curGroup = (curGroupID == -1) ? NULL : m_taskManager->GetTaskGroup(curGroupID, icarus); - //Get the number of commands - pIcarus->BufferRead( &m_numCommands, sizeof( m_numCommands ) ); + // Get the number of commands + pIcarus->BufferRead(&m_numCommands, sizeof(m_numCommands)); - //Get the current sequence - pIcarus->BufferRead( &seqID, sizeof( seqID ) ); + // Get the current sequence + pIcarus->BufferRead(&seqID, sizeof(seqID)); - m_curSequence = ( seqID != -1 ) ? (CSequence*)icarus->GetSequence( seqID ) : NULL; + m_curSequence = (seqID != -1) ? (CSequence *)icarus->GetSequence(seqID) : NULL; return true; } diff --git a/code/icarus/TaskManager.cpp b/code/icarus/TaskManager.cpp index 74f0b0494d..434b7ef3a5 100644 --- a/code/icarus/TaskManager.cpp +++ b/code/icarus/TaskManager.cpp @@ -24,7 +24,6 @@ along with this program; if not, see . // // -- jweier - // this include must remain at the top of every Icarus CPP file #include "StdAfx.h" #include "IcarusImplementation.h" @@ -34,10 +33,12 @@ along with this program; if not, see . #include "taskmanager.h" #include "sequencer.h" -#define ICARUS_VALIDATE(a) if ( a == false ) return TASK_FAILED; +#define ICARUS_VALIDATE(a) \ + if (a == false) \ + return TASK_FAILED; -#define STL_ITERATE( a, b ) for ( a = b.begin(); a != b.end(); ++a ) -#define STL_INSERT( a, b ) a.insert( a.end(), b ); +#define STL_ITERATE(a, b) for (a = b.begin(); a != b.end(); ++a) +#define STL_INSERT(a, b) a.insert(a.end(), b); /* ================================================= @@ -47,25 +48,20 @@ CTask ================================================= */ -CTask::CTask( void ) -{ -} +CTask::CTask(void) {} -CTask::~CTask( void ) -{ -} +CTask::~CTask(void) {} -CTask *CTask::Create( int GUID, CBlock *block ) -{ +CTask *CTask::Create(int GUID, CBlock *block) { CTask *task = new CTask; - //TODO: Emit warning - if ( task == NULL ) + // TODO: Emit warning + if (task == NULL) return NULL; - task->SetTimeStamp( 0 ); - task->SetBlock( block ); - task->SetGUID( GUID ); + task->SetTimeStamp(0); + task->SetBlock(block); + task->SetGUID(GUID); return task; } @@ -76,9 +72,8 @@ Free ------------------------- */ -void CTask::Free( void ) -{ - //NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up +void CTask::Free(void) { + // NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up delete this; } @@ -90,18 +85,14 @@ CTaskGroup ================================================= */ -CTaskGroup::CTaskGroup( void ) -{ +CTaskGroup::CTaskGroup(void) { Init(); - m_GUID = 0; - m_parent = NULL; + m_GUID = 0; + m_parent = NULL; } -CTaskGroup::~CTaskGroup( void ) -{ - m_completedTasks.clear(); -} +CTaskGroup::~CTaskGroup(void) { m_completedTasks.clear(); } /* ------------------------- @@ -109,10 +100,7 @@ SetGUID ------------------------- */ -void CTaskGroup::SetGUID( int GUID ) -{ - m_GUID = GUID; -} +void CTaskGroup::SetGUID(int GUID) { m_GUID = GUID; } /* ------------------------- @@ -120,12 +108,11 @@ Init ------------------------- */ -void CTaskGroup::Init( void ) -{ +void CTaskGroup::Init(void) { m_completedTasks.clear(); - m_numCompleted = 0; - m_parent = NULL; + m_numCompleted = 0; + m_parent = NULL; } /* @@ -134,9 +121,8 @@ Add ------------------------- */ -int CTaskGroup::Add( CTask *task ) -{ - m_completedTasks[ task->GetGUID() ] = false; +int CTaskGroup::Add(CTask *task) { + m_completedTasks[task->GetGUID()] = false; return TASK_OK; } @@ -146,11 +132,9 @@ MarkTaskComplete ------------------------- */ -bool CTaskGroup::MarkTaskComplete( int id ) -{ - if ( (m_completedTasks.find( id )) != m_completedTasks.end() ) - { - m_completedTasks[ id ] = true; +bool CTaskGroup::MarkTaskComplete(int id) { + if ((m_completedTasks.find(id)) != m_completedTasks.end()) { + m_completedTasks[id] = true; m_numCompleted++; return true; @@ -167,15 +151,12 @@ CTaskManager ================================================= */ -CTaskManager::CTaskManager( void ) -{ +CTaskManager::CTaskManager(void) { static int uniqueID = 0; m_id = uniqueID++; } -CTaskManager::~CTaskManager( void ) -{ -} +CTaskManager::~CTaskManager(void) {} /* ------------------------- @@ -183,10 +164,7 @@ Create ------------------------- */ -CTaskManager *CTaskManager::Create( void ) -{ - return new CTaskManager; -} +CTaskManager *CTaskManager::Create(void) { return new CTaskManager; } /* ------------------------- @@ -194,18 +172,17 @@ Init ------------------------- */ -int CTaskManager::Init( CSequencer *owner ) -{ - //TODO: Emit warning - if ( owner == NULL ) +int CTaskManager::Init(CSequencer *owner) { + // TODO: Emit warning + if (owner == NULL) return TASK_FAILED; m_tasks.clear(); - m_owner = owner; - m_ownerID = owner->GetOwnerID(); - m_curGroup = NULL; - m_GUID = 0; - m_resident = false; + m_owner = owner; + m_ownerID = owner->GetOwnerID(); + m_curGroup = NULL; + m_GUID = 0; + m_resident = false; return TASK_OK; } @@ -215,23 +192,20 @@ int CTaskManager::Init( CSequencer *owner ) Free ------------------------- */ -int CTaskManager::Free( void ) -{ - taskGroup_v::iterator gi; - tasks_l::iterator ti; - - assert(!m_resident); //don't free me, i'm currently running! - //Clear out all pending tasks - for ( ti = m_tasks.begin(); ti != m_tasks.end(); ++ti ) - { +int CTaskManager::Free(void) { + taskGroup_v::iterator gi; + tasks_l::iterator ti; + + assert(!m_resident); // don't free me, i'm currently running! + // Clear out all pending tasks + for (ti = m_tasks.begin(); ti != m_tasks.end(); ++ti) { (*ti)->Free(); } m_tasks.clear(); - //Clear out all taskGroups - for ( gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi ) - { + // Clear out all taskGroups + for (gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi) { delete (*gi); } @@ -248,9 +222,8 @@ Flush ------------------------- */ -int CTaskManager::Flush( void ) -{ - //FIXME: Rewrite +int CTaskManager::Flush(void) { + // FIXME: Rewrite return true; } @@ -261,42 +234,39 @@ AddTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::AddTaskGroup( const char *name, CIcarus* icarus ) -{ +CTaskGroup *CTaskManager::AddTaskGroup(const char *name, CIcarus *icarus) { CTaskGroup *group; - //Collect any garbage - taskGroupName_m::iterator tgni; - tgni = m_taskGroupNameMap.find( name ); + // Collect any garbage + taskGroupName_m::iterator tgni; + tgni = m_taskGroupNameMap.find(name); - if ( tgni != m_taskGroupNameMap.end() ) - { + if (tgni != m_taskGroupNameMap.end()) { group = (*tgni).second; - //Clear it and just move on + // Clear it and just move on group->Init(); return group; } - //Allocate a new one + // Allocate a new one group = new CTaskGroup; - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to allocate task group \"%s\"\n", name ); + // TODO: Emit warning + assert(group); + if (group == NULL) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to allocate task group \"%s\"\n", name); return NULL; } - //Setup the internal information - group->SetGUID( m_GUID++ ); + // Setup the internal information + group->SetGUID(m_GUID++); - //Add it to the list and associate it for retrieval later - m_taskGroups.insert( m_taskGroups.end(), group ); - m_taskGroupNameMap[ name ] = group; - m_taskGroupIDMap[ group->GetGUID() ] = group; + // Add it to the list and associate it for retrieval later + m_taskGroups.insert(m_taskGroups.end(), group); + m_taskGroupNameMap[name] = group; + m_taskGroupIDMap[group->GetGUID()] = group; return group; } @@ -307,30 +277,26 @@ GetTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::GetTaskGroup( const char *name, CIcarus* icarus ) -{ - taskGroupName_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(const char *name, CIcarus *icarus) { + taskGroupName_m::iterator tgi; - tgi = m_taskGroupNameMap.find( name ); + tgi = m_taskGroupNameMap.find(name); - if ( tgi == m_taskGroupNameMap.end() ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Could not find task group \"%s\"\n", name ); + if (tgi == m_taskGroupNameMap.end()) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Could not find task group \"%s\"\n", name); return NULL; } return (*tgi).second; } -CTaskGroup *CTaskManager::GetTaskGroup( int id, CIcarus* icarus ) -{ - taskGroupID_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(int id, CIcarus *icarus) { + taskGroupID_m::iterator tgi; - tgi = m_taskGroupIDMap.find( id ); + tgi = m_taskGroupIDMap.find(id); - if ( tgi == m_taskGroupIDMap.end() ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Could not find task group \"%d\"\n", id ); + if (tgi == m_taskGroupIDMap.end()) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Could not find task group \"%d\"\n", id); return NULL; } @@ -343,13 +309,11 @@ Update ------------------------- */ -int CTaskManager::Update( CIcarus* icarus ) -{ - if ( icarus->GetGame()->IsFrozen(m_ownerID) ) - { +int CTaskManager::Update(CIcarus *icarus) { + if (icarus->GetGame()->IsFrozen(m_ownerID)) { return TASK_FAILED; } - m_count = 0; //Needed for runaway init + m_count = 0; // Needed for runaway init m_resident = true; int returnVal = Go(icarus); @@ -365,9 +329,8 @@ Check ------------------------- */ -inline bool CTaskManager::Check( int targetID, CBlock *block, int memberNum ) const -{ - if ( (block->GetMember( memberNum ))->GetID() == targetID ) +inline bool CTaskManager::Check(int targetID, CBlock *block, int memberNum) const { + if ((block->GetMember(memberNum))->GetID() == targetID) return true; return false; @@ -379,67 +342,57 @@ GetFloat ------------------------- */ -int CTaskManager::GetFloat( int entID, CBlock *block, int &memberNum, float &value, CIcarus* icarus ) -{ - char *name; - int type; +int CTaskManager::GetFloat(int entID, CBlock *block, int &memberNum, float &value, CIcarus *icarus) { + char *name; + int type; - //See if this is a get() command replacement - if ( Check( CIcarus::ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(CIcarus::ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != CIcarus::TK_FLOAT ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n" ); + // TODO: Emit warning + if (type != CIcarus::TK_FLOAT) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n"); return false; } - return icarus->GetGame()->GetFloat( entID, name, &value ); + return icarus->GetGame()->GetFloat(entID, name, &value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( CIcarus::ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(CIcarus::ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - value = icarus->GetGame()->Random( min, max ); + value = icarus->GetGame()->Random(min, max); return true; } - //Look for a tag() inline call - if ( Check( CIcarus::ID_TAG, block, memberNum ) ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n" ); + // Look for a tag() inline call + if (Check(CIcarus::ID_TAG, block, memberNum)) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n"); return false; } - CBlockMember *bm = block->GetMember( memberNum ); + CBlockMember *bm = block->GetMember(memberNum); - if ( bm->GetID() == CIcarus::TK_INT ) - { - value = (float) (*(int *) block->GetMemberData( memberNum++ )); - } - else if ( bm->GetID() == CIcarus::TK_FLOAT ) - { - value = *(float *) block->GetMemberData( memberNum++ ); - } - else - { + if (bm->GetID() == CIcarus::TK_INT) { + value = (float)(*(int *)block->GetMemberData(memberNum++)); + } else if (bm->GetID() == CIcarus::TK_FLOAT) { + value = *(float *)block->GetMemberData(memberNum++); + } else { assert(0); - icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Unexpected value; expected type FLOAT\n" ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Unexpected value; expected type FLOAT\n"); return false; } @@ -452,82 +405,73 @@ GetVector ------------------------- */ -int CTaskManager::GetVector( int entID, CBlock *block, int &memberNum, vec3_t &value, CIcarus* icarus ) -{ - char *name; - int type, i; +int CTaskManager::GetVector(int entID, CBlock *block, int &memberNum, vec3_t &value, CIcarus *icarus) { + char *name; + int type, i; - //See if this is a get() command replacement - if ( Check( CIcarus::ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(CIcarus::ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != CIcarus::TK_VECTOR ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n" ); + // TODO: Emit warning + if (type != CIcarus::TK_VECTOR) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n"); } - return icarus->GetGame()->GetVector( entID, name, value ); + return icarus->GetGame()->GetVector(entID, name, value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( CIcarus::ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(CIcarus::ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - for ( i = 0; i < 3; i++ ) - { - value[i] = (float) icarus->GetGame()->Random( min, max ); //FIXME: Just truncating it for now.. should be fine though + for (i = 0; i < 3; i++) { + value[i] = (float)icarus->GetGame()->Random(min, max); // FIXME: Just truncating it for now.. should be fine though } return true; } - //Look for a tag() inline call - if ( Check( CIcarus::ID_TAG, block, memberNum ) ) - { - char *tagName; - float tagLookup; + // Look for a tag() inline call + if (Check(CIcarus::ID_TAG, block, memberNum)) { + char *tagName; + float tagLookup; memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName, icarus ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup, icarus ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName, icarus)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup, icarus)); - if ( icarus->GetGame()->GetTag( entID, tagName, (int) tagLookup, value ) == false) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); - assert(0&&"Unable to find tag"); + if (icarus->GetGame()->GetTag(entID, tagName, (int)tagLookup, value) == false) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); + assert(0 && "Unable to find tag"); return TASK_FAILED; } return true; } - //Check for a real vector here - type = (int) (*(float *) block->GetMemberData( memberNum )); + // Check for a real vector here + type = (int)(*(float *)block->GetMemberData(memberNum)); - if ( type != CIcarus::TK_VECTOR ) - { -// icarus->GetGame()->DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); + if (type != CIcarus::TK_VECTOR) { + // icarus->GetGame()->DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); return false; } memberNum++; - for ( i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, value[i], icarus ) == false ) + for (i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, value[i], icarus) == false) return false; } @@ -540,170 +484,148 @@ Get ------------------------- */ -int CTaskManager::GetID() -{ - return m_id; -} +int CTaskManager::GetID() { return m_id; } -int CTaskManager::Get( int entID, CBlock *block, int &memberNum, char **value, CIcarus* icarus ) -{ - static char tempBuffer[128]; //FIXME: EEEK! - vec3_t vector; - char *name, *tagName; - float tagLookup; - int type; +int CTaskManager::Get(int entID, CBlock *block, int &memberNum, char **value, CIcarus *icarus) { + static char tempBuffer[128]; // FIXME: EEEK! + vec3_t vector; + char *name, *tagName; + float tagLookup; + int type; - //Look for a get() inline call - if ( Check( CIcarus::ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // Look for a get() inline call + if (Check(CIcarus::ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Format the return properly - //FIXME: This is probably doing double formatting in certain cases... - //FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! - switch ( type ) - { + // Format the return properly + // FIXME: This is probably doing double formatting in certain cases... + // FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! + switch (type) { case CIcarus::TK_STRING: - if ( icarus->GetGame()->GetString( entID, name, value ) == false ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); + if (icarus->GetGame()->GetString(entID, name, value) == false) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); return false; } return true; break; - case CIcarus::TK_FLOAT: - { - float temp; - - if ( icarus->GetGame()->GetFloat( entID, name, &temp ) == false ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case CIcarus::TK_FLOAT: { + float temp; - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", temp ); - *value = (char *) tempBuffer; + if (icarus->GetGame()->GetFloat(entID, name, &temp) == false) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", temp); + *value = (char *)tempBuffer; + } + return true; break; - case CIcarus::TK_VECTOR: - { - vec3_t vval; - - if ( icarus->GetGame()->GetVector( entID, name, vval ) == false ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case CIcarus::TK_VECTOR: { + vec3_t vval; - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + if (icarus->GetGame()->GetVector(entID, name, vval) == false) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; + } + return true; break; default: - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return an unknown type!\n" ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Get() call tried to return an unknown type!\n"); return false; break; } } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( CIcarus::ID_RANDOM, block, memberNum ) ) - { - float min, max, ret; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(CIcarus::ID_RANDOM, block, memberNum)) { + float min, max, ret; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - ret = icarus->GetGame()->Random( min, max ); + ret = icarus->GetGame()->Random(min, max); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", ret ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", ret); + *value = (char *)tempBuffer; return true; } - //Look for a tag() inline call - if ( Check( CIcarus::ID_TAG, block, memberNum ) ) - { + // Look for a tag() inline call + if (Check(CIcarus::ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName, icarus ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup, icarus ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName, icarus)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup, icarus)); - if (icarus->GetGame()->GetTag( entID, tagName, (int) tagLookup, vector ) == false) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if (icarus->GetGame()->GetTag(entID, tagName, (int)tagLookup, vector) == false) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0 && "Unable to find tag"); return false; } - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vector[0], vector[1], vector[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vector[0], vector[1], vector[2]); + *value = (char *)tempBuffer; return true; } - //Get an actual piece of data + // Get an actual piece of data - CBlockMember *bm = block->GetMember( memberNum ); + CBlockMember *bm = block->GetMember(memberNum); - if ( bm->GetID() == CIcarus::TK_INT ) - { - float fval = (float) (*(int *) block->GetMemberData( memberNum++ )); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", fval ); - *value = (char *) tempBuffer; + if (bm->GetID() == CIcarus::TK_INT) { + float fval = (float)(*(int *)block->GetMemberData(memberNum++)); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == CIcarus::TK_FLOAT ) - { - float fval = *(float *) block->GetMemberData( memberNum++ ); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", fval ); - *value = (char *) tempBuffer; + } else if (bm->GetID() == CIcarus::TK_FLOAT) { + float fval = *(float *)block->GetMemberData(memberNum++); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == CIcarus::TK_VECTOR ) - { - vec3_t vval; + } else if (bm->GetID() == CIcarus::TK_VECTOR) { + vec3_t vval; memberNum++; - for ( int i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, vval[i], icarus ) == false ) + for (int i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, vval[i], icarus) == false) return false; } - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; return true; - } - else if ( ( bm->GetID() == CIcarus::TK_STRING ) || ( bm->GetID() == CIcarus::TK_IDENTIFIER ) ) - { - *value = (char *) block->GetMemberData( memberNum++ ); + } else if ((bm->GetID() == CIcarus::TK_STRING) || (bm->GetID() == CIcarus::TK_IDENTIFIER)) { + *value = (char *)block->GetMemberData(memberNum++); return true; } - //TODO: Emit warning - assert( 0 ); - icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Unexpected value; expected type STRING\n" ); + // TODO: Emit warning + assert(0); + icarus->GetGame()->DebugPrint(IGameInterface::WL_WARNING, "Unexpected value; expected type STRING\n"); return false; } @@ -714,136 +636,129 @@ Go ------------------------- */ -int CTaskManager::Go( CIcarus* icarus ) -{ - CTask *task = NULL; - bool completed = false; +int CTaskManager::Go(CIcarus *icarus) { + CTask *task = NULL; + bool completed = false; - //Check for run away scripts - if ( m_count++ > RUNAWAY_LIMIT ) - { + // Check for run away scripts + if (m_count++ > RUNAWAY_LIMIT) { assert(0); - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Runaway loop detected!\n" ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Runaway loop detected!\n"); return TASK_FAILED; } - //If there are tasks to complete, do so - if ( m_tasks.empty() == false ) - { - //Get the next task - task = PopTask( CSequence::POP_BACK ); + // If there are tasks to complete, do so + if (m_tasks.empty() == false) { + // Get the next task + task = PopTask(CSequence::POP_BACK); - assert( task ); - if ( task == NULL ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Invalid task found in Go()!\n" ); + assert(task); + if (task == NULL) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Invalid task found in Go()!\n"); return TASK_FAILED; } - //If this hasn't been stamped, do so - if ( task->GetTimeStamp() == 0 ) - task->SetTimeStamp( icarus->GetGame()->GetTime() ); + // If this hasn't been stamped, do so + if (task->GetTimeStamp() == 0) + task->SetTimeStamp(icarus->GetGame()->GetTime()); - //Switch and call the proper function - switch( task->GetID() ) - { + // Switch and call the proper function + switch (task->GetID()) { case CIcarus::ID_WAIT: - Wait( task, completed, icarus ); + Wait(task, completed, icarus); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, CSequence::PUSH_BACK ); + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, CSequence::PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; case CIcarus::ID_WAITSIGNAL: - WaitSignal( task, completed , icarus); + WaitSignal(task, completed, icarus); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, CSequence::PUSH_BACK ); + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, CSequence::PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; - case CIcarus::ID_PRINT: //print( STRING ) - Print( task, icarus ); + case CIcarus::ID_PRINT: // print( STRING ) + Print(task, icarus); break; - case CIcarus::ID_SOUND: //sound( name ) - Sound( task, icarus ); + case CIcarus::ID_SOUND: // sound( name ) + Sound(task, icarus); break; - case CIcarus::ID_MOVE: //move ( ORIGIN, ANGLES, DURATION ) - Move( task, icarus ); + case CIcarus::ID_MOVE: // move ( ORIGIN, ANGLES, DURATION ) + Move(task, icarus); break; - case CIcarus::ID_ROTATE: //rotate( ANGLES, DURATION ) - Rotate( task, icarus ); + case CIcarus::ID_ROTATE: // rotate( ANGLES, DURATION ) + Rotate(task, icarus); break; - case CIcarus::ID_KILL: //kill( NAME ) - Kill( task, icarus ); + case CIcarus::ID_KILL: // kill( NAME ) + Kill(task, icarus); break; - case CIcarus::ID_REMOVE: //remove( NAME ) - Remove( task, icarus ); + case CIcarus::ID_REMOVE: // remove( NAME ) + Remove(task, icarus); break; - case CIcarus::ID_CAMERA: //camera( ? ) - Camera( task, icarus ); + case CIcarus::ID_CAMERA: // camera( ? ) + Camera(task, icarus); break; - case CIcarus::ID_SET: //set( NAME, ? ) - Set( task, icarus ); + case CIcarus::ID_SET: // set( NAME, ? ) + Set(task, icarus); break; - case CIcarus::ID_USE: //use( NAME ) - Use( task, icarus ); + case CIcarus::ID_USE: // use( NAME ) + Use(task, icarus); break; - case CIcarus::ID_DECLARE://declare( TYPE, NAME ) - DeclareVariable( task, icarus ); + case CIcarus::ID_DECLARE: // declare( TYPE, NAME ) + DeclareVariable(task, icarus); break; - case CIcarus::ID_FREE: //free( NAME ) - FreeVariable( task, icarus ); + case CIcarus::ID_FREE: // free( NAME ) + FreeVariable(task, icarus); break; - case CIcarus::ID_SIGNAL: //signal( NAME ) - Signal( task, icarus ); + case CIcarus::ID_SIGNAL: // signal( NAME ) + Signal(task, icarus); break; - case CIcarus::ID_PLAY: //play ( NAME ) - Play( task, icarus ); + case CIcarus::ID_PLAY: // play ( NAME ) + Play(task, icarus); break; default: assert(0); task->Free(); - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Found unknown task type!\n" ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Found unknown task type!\n"); return TASK_FAILED; break; } - //Pump the sequencer for another task - CallbackCommand( task, TASK_RETURN_COMPLETE , icarus); + // Pump the sequencer for another task + CallbackCommand(task, TASK_RETURN_COMPLETE, icarus); task->Free(); } - //FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't + // FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't // execute too many commands in one cycle. This may, however, cause timing errors to surface. return TASK_OK; } @@ -854,25 +769,22 @@ SetCommand ------------------------- */ -int CTaskManager::SetCommand( CBlock *command, int type, CIcarus* icarus ) -{ - CTask *task = CTask::Create( m_GUID++, command ); +int CTaskManager::SetCommand(CBlock *command, int type, CIcarus *icarus) { + CTask *task = CTask::Create(m_GUID++, command); - //If this is part of a task group, add it in - if ( m_curGroup ) - { - m_curGroup->Add( task ); + // If this is part of a task group, add it in + if (m_curGroup) { + m_curGroup->Add(task); } - //TODO: Emit warning - assert( task ); - if ( task == NULL ) - { - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to allocate new task!\n" ); + // TODO: Emit warning + assert(task); + if (task == NULL) { + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to allocate new task!\n"); return TASK_FAILED; } - PushTask( task, type ); + PushTask(task, type); return TASK_OK; } @@ -883,35 +795,30 @@ MarkTask ------------------------- */ -int CTaskManager::MarkTask( int id, int operation, CIcarus* icarus ) -{ - CTaskGroup *group = GetTaskGroup( id, icarus ); +int CTaskManager::MarkTask(int id, int operation, CIcarus *icarus) { + CTaskGroup *group = GetTaskGroup(id, icarus); - assert( group ); + assert(group); - if ( group == NULL ) + if (group == NULL) return TASK_FAILED; - if ( operation == TASK_START ) - { - //Reset all the completion information + if (operation == TASK_START) { + // Reset all the completion information group->Init(); - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - } - else if ( operation == TASK_END ) - { - assert( m_curGroup ); - if ( m_curGroup == NULL ) + } else if (operation == TASK_END) { + assert(m_curGroup); + if (m_curGroup == NULL) return TASK_FAILED; m_curGroup = m_curGroup->GetParent(); } #ifdef _DEBUG - else - { + else { assert(0); } #endif @@ -925,15 +832,13 @@ Completed ------------------------- */ -int CTaskManager::Completed( int id ) -{ - taskGroup_v::iterator tgi; +int CTaskManager::Completed(int id) { + taskGroup_v::iterator tgi; - //Mark the task as completed - for ( tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi ) - { - //If this returns true, then the task was marked properly - if ( (*tgi)->MarkTaskComplete( id ) ) + // Mark the task as completed + for (tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi) { + // If this returns true, then the task was marked properly + if ((*tgi)->MarkTaskComplete(id)) break; } @@ -946,14 +851,13 @@ CallbackCommand ------------------------- */ -int CTaskManager::CallbackCommand( CTask *task, int returnCode, CIcarus* icarus ) -{ - if ( m_owner->Callback( this, task->GetBlock(), returnCode, icarus ) == CSequencer::SEQ_OK ) +int CTaskManager::CallbackCommand(CTask *task, int returnCode, CIcarus *icarus) { + if (m_owner->Callback(this, task->GetBlock(), returnCode, icarus) == CSequencer::SEQ_OK) return Go(icarus); assert(0); - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Command callback failure!\n" ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Command callback failure!\n"); return TASK_FAILED; } @@ -963,20 +867,18 @@ RecallTask ------------------------- */ -CBlock *CTaskManager::RecallTask( void ) -{ - CTask *task; +CBlock *CTaskManager::RecallTask(void) { + CTask *task; - task = PopTask( CSequence::POP_BACK ); + task = PopTask(CSequence::POP_BACK); - if ( task ) - { - // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) - CBlock* retBlock = task->GetBlock(); + if (task) { + // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; - // return task->GetBlock(); + // return task->GetBlock(); } return NULL; @@ -988,12 +890,10 @@ PushTask ------------------------- */ -int CTaskManager::PushTask( CTask *task, int flag ) -{ - assert( (flag == CSequence::PUSH_FRONT) || (flag == CSequence::PUSH_BACK) ); +int CTaskManager::PushTask(CTask *task, int flag) { + assert((flag == CSequence::PUSH_FRONT) || (flag == CSequence::PUSH_BACK)); - switch ( flag ) - { + switch (flag) { case CSequence::PUSH_FRONT: m_tasks.insert(m_tasks.begin(), task); @@ -1007,7 +907,7 @@ int CTaskManager::PushTask( CTask *task, int flag ) break; } - //Invalid flag + // Invalid flag return CSequencer::SEQ_FAILED; } @@ -1017,17 +917,15 @@ PopTask ------------------------- */ -CTask *CTaskManager::PopTask( int flag ) -{ - CTask *task; +CTask *CTaskManager::PopTask(int flag) { + CTask *task; - assert( (flag == CSequence::POP_FRONT) || (flag == CSequence::POP_BACK) ); + assert((flag == CSequence::POP_FRONT) || (flag == CSequence::POP_BACK)); - if ( m_tasks.empty() ) + if (m_tasks.empty()) return NULL; - switch ( flag ) - { + switch (flag) { case CSequence::POP_FRONT: task = m_tasks.front(); m_tasks.pop_front(); @@ -1043,7 +941,7 @@ CTask *CTaskManager::PopTask( int flag ) break; } - //Invalid flag + // Invalid flag return NULL; } @@ -1053,18 +951,17 @@ GetCurrentTask ------------------------- */ -CBlock *CTaskManager::GetCurrentTask( void ) -{ - CTask *task = PopTask( CSequence::POP_BACK ); +CBlock *CTaskManager::GetCurrentTask(void) { + CTask *task = PopTask(CSequence::POP_BACK); - if ( task == NULL ) + if (task == NULL) return NULL; -// fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) - CBlock* retBlock = task->GetBlock(); + // fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; -// return task->GetBlock(); + // return task->GetBlock(); } /* @@ -1075,77 +972,65 @@ CBlock *CTaskManager::GetCurrentTask( void ) ================================================= */ -int CTaskManager::Wait( CTask *task, bool &completed , CIcarus* icarus ) -{ - CBlockMember *bm; - CBlock *block = task->GetBlock(); - char *sVal; - float dwtime; - int memberNum = 0; +int CTaskManager::Wait(CTask *task, bool &completed, CIcarus *icarus) { + CBlockMember *bm; + CBlock *block = task->GetBlock(); + char *sVal; + float dwtime; + int memberNum = 0; completed = false; - bm = block->GetMember( 0 ); + bm = block->GetMember(0); - //Check if this is a task completion wait - if ( bm->GetID() == CIcarus::TK_STRING ) - { - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + // Check if this is a task completion wait + if (bm->GetID() == CIcarus::TK_STRING) { + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - if ( task->GetTimeStamp() == icarus->GetGame()->GetTime() ) - { - //Print out the debug info - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == icarus->GetGame()->GetTime()) { + // Print out the debug info + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - CTaskGroup *group = GetTaskGroup( sVal , icarus); + CTaskGroup *group = GetTaskGroup(sVal, icarus); - if ( group == NULL ) - { - //TODO: Emit warning + if (group == NULL) { + // TODO: Emit warning completed = false; return TASK_FAILED; } completed = group->Complete(); - } - else //Otherwise it's a time completion wait + } else // Otherwise it's a time completion wait { - if ( Check( CIcarus::ID_RANDOM, block, memberNum ) ) - {//get it random only the first time - float min, max; + if (Check(CIcarus::ID_RANDOM, block, memberNum)) { // get it random only the first time + float min, max; - dwtime = *(float *) block->GetMemberData( memberNum++ ); - if ( dwtime == icarus->GetGame()->MaxFloat() ) - {//we have not evaluated this random yet - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + dwtime = *(float *)block->GetMemberData(memberNum++); + if (dwtime == icarus->GetGame()->MaxFloat()) { // we have not evaluated this random yet + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - dwtime = icarus->GetGame()->Random( min, max ); + dwtime = icarus->GetGame()->Random(min, max); - //store the result in the first member - bm->SetData( &dwtime, sizeof( dwtime ) , icarus); + // store the result in the first member + bm->SetData(&dwtime, sizeof(dwtime), icarus); } - } - else - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, dwtime, icarus ) ); + } else { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, dwtime, icarus)); } - if ( task->GetTimeStamp() == icarus->GetGame()->GetTime() ) - { - //Print out the debug info - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int) dwtime, task->GetTimeStamp() ); + if (task->GetTimeStamp() == icarus->GetGame()->GetTime()) { + // Print out the debug info + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int)dwtime, task->GetTimeStamp()); } - if ( (task->GetTimeStamp() + dwtime) < (icarus->GetGame()->GetTime()) ) - { + if ((task->GetTimeStamp() + dwtime) < (icarus->GetGame()->GetTime())) { completed = true; memberNum = 0; - if ( Check( CIcarus::ID_RANDOM, block, memberNum ) ) - {//set the data back to 0 so it will be re-randomized next time + if (Check(CIcarus::ID_RANDOM, block, memberNum)) { // set the data back to 0 so it will be re-randomized next time dwtime = icarus->GetGame()->MaxFloat(); - bm->SetData( &dwtime, sizeof( dwtime ), icarus ); + bm->SetData(&dwtime, sizeof(dwtime), icarus); } } } @@ -1159,26 +1044,23 @@ WaitSignal ------------------------- */ -int CTaskManager::WaitSignal( CTask *task, bool &completed , CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::WaitSignal(CTask *task, bool &completed, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; completed = false; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal , icarus) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - if ( task->GetTimeStamp() == icarus->GetGame()->GetTime() ) - { - //Print out the debug info - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == icarus->GetGame()->GetTime()) { + // Print out the debug info + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - if ( icarus->CheckSignal( sVal ) ) - { + if (icarus->CheckSignal(sVal)) { completed = true; - icarus->ClearSignal( sVal ); + icarus->ClearSignal(sVal); } return TASK_OK; @@ -1190,19 +1072,18 @@ Print ------------------------- */ -int CTaskManager::Print( CTask *task , CIcarus* icarus) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Print(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); - icarus->GetGame()->CenterPrint( sVal ); + icarus->GetGame()->CenterPrint(sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1213,20 +1094,19 @@ Sound ------------------------- */ -int CTaskManager::Sound( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Sound(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); - //Only instantly complete if the user has requested it - if( icarus->GetGame()->PlayIcarusSound( task->GetGUID(), m_ownerID, sVal2, sVal ) ) - Completed( task->GetGUID() ); + // Only instantly complete if the user has requested it + if (icarus->GetGame()->PlayIcarusSound(task->GetGUID(), m_ownerID, sVal2, sVal)) + Completed(task->GetGUID()); return TASK_OK; } @@ -1237,41 +1117,37 @@ Rotate ------------------------- */ -int CTaskManager::Rotate( CTask *task , CIcarus* icarus) -{ - vec3_t vector; - CBlock *block = task->GetBlock(); - char *tagName; - float tagLookup, duration; - int memberNum = 0; +int CTaskManager::Rotate(CTask *task, CIcarus *icarus) { + vec3_t vector; + CBlock *block = task->GetBlock(); + char *tagName; + float tagLookup, duration; + int memberNum = 0; - //Check for a tag reference - if ( Check( CIcarus::ID_TAG, block, memberNum ) ) - { + // Check for a tag reference + if (Check(CIcarus::ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &tagName, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, tagLookup, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &tagName, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, tagLookup, icarus)); - if ( icarus->GetGame()->GetTag( m_ownerID, tagName, (int) tagLookup, vector ) == false ) - { - //TODO: Emit warning - icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if (icarus->GetGame()->GetTag(m_ownerID, tagName, (int)tagLookup, vector) == false) { + // TODO: Emit warning + icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0); return TASK_FAILED; } - } - else - { - //Get a normal vector - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector, icarus ) ); + } else { + // Get a normal vector + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector, icarus)); } - //Find the duration - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration, icarus ) ); + // Find the duration + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int) duration, task->GetTimeStamp() ); - icarus->GetGame()->Lerp2Angles( task->GetGUID(), m_ownerID, vector, duration ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int)duration, + task->GetTimeStamp()); + icarus->GetGame()->Lerp2Angles(task->GetGUID(), m_ownerID, vector, duration); return TASK_OK; } @@ -1282,18 +1158,17 @@ Remove ------------------------- */ -int CTaskManager::Remove( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Remove(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->GetGame()->Remove( m_ownerID, sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->GetGame()->Remove(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1304,129 +1179,131 @@ Camera ------------------------- */ -int CTaskManager::Camera( CTask *task , CIcarus* icarus) -{ - CBlock *block = task->GetBlock(); - vec3_t vector, vector2; - float type, fVal, fVal2, fVal3; - char *sVal; - int memberNum = 0; +int CTaskManager::Camera(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + vec3_t vector, vector2; + float type, fVal, fVal2, fVal3; + char *sVal; + int memberNum = 0; - //Get the camera function type - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, type, icarus ) ); + // Get the camera function type + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, type, icarus)); - switch ( (int) type ) - { + switch ((int)type) { case CIcarus::TYPE_PAN: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector, icarus ) ); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2, icarus ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector, icarus)); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2, icarus)); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], fVal, task->GetTimeStamp() ); - icarus->GetGame()->CameraPan( vector, vector2, fVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], + vector[2], vector2[0], vector2[1], vector2[2], fVal, task->GetTimeStamp()); + icarus->GetGame()->CameraPan(vector, vector2, fVal); break; case CIcarus::TYPE_ZOOM: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraZoom( fVal, fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + icarus->GetGame()->CameraZoom(fVal, fVal2); break; case CIcarus::TYPE_MOVE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp() ); - icarus->GetGame()->CameraMove( vector, fVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, + task->GetTimeStamp()); + icarus->GetGame()->CameraMove(vector, fVal); break; case CIcarus::TYPE_ROLL: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraRoll( fVal, fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + icarus->GetGame()->CameraRoll(fVal, fVal2); break; case CIcarus::TYPE_FOLLOW: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraFollow( (const char *) sVal, fVal, fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, + task->GetTimeStamp()); + icarus->GetGame()->CameraFollow((const char *)sVal, fVal, fVal2); break; case CIcarus::TYPE_TRACK: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraTrack( (const char *) sVal, fVal, fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp()); + icarus->GetGame()->CameraTrack((const char *)sVal, fVal, fVal2); break; case CIcarus::TYPE_DISTANCE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraDistance( fVal, fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + icarus->GetGame()->CameraDistance(fVal, fVal2); break; case CIcarus::TYPE_FADE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal3, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal3, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp() ); - icarus->GetGame()->CameraFade( vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], + vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp()); + icarus->GetGame()->CameraFade(vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3); break; case CIcarus::TYPE_PATH: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->GetGame()->CameraPath( sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->GetGame()->CameraPath(sVal); break; case CIcarus::TYPE_ENABLE: - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp()); icarus->GetGame()->CameraEnable(); break; case CIcarus::TYPE_DISABLE: - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp()); icarus->GetGame()->CameraDisable(); break; case CIcarus::TYPE_SHAKE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - icarus->GetGame()->CameraShake( fVal, (int) fVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + icarus->GetGame()->CameraShake(fVal, (int)fVal2); break; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1437,33 +1314,32 @@ Move ------------------------- */ -int CTaskManager::Move( CTask *task, CIcarus* icarus ) -{ - vec3_t vector, vector2; - CBlock *block = task->GetBlock(); - float duration; - int memberNum = 0; +int CTaskManager::Move(CTask *task, CIcarus *icarus) { + vec3_t vector, vector2; + CBlock *block = task->GetBlock(); + float duration; + int memberNum = 0; - //Get the goal position - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector, icarus ) ); + // Get the goal position + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector, icarus)); - //Check for possible angles field - if ( GetVector( m_ownerID, block, memberNum, vector2, icarus ) == false ) - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration, icarus ) ); + // Check for possible angles field + if (GetVector(m_ownerID, block, memberNum, vector2, icarus) == false) { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration, icarus)); - - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp() ); - icarus->GetGame()->Lerp2Pos( task->GetGUID(), m_ownerID, vector, NULL, duration ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, + task->GetTimeStamp()); + icarus->GetGame()->Lerp2Pos(task->GetGUID(), m_ownerID, vector, NULL, duration); return TASK_OK; } - //Get the duration and make the call - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration, icarus ) ); + // Get the duration and make the call + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], duration, task->GetTimeStamp() ); - icarus->GetGame()->Lerp2Pos( task->GetGUID(), m_ownerID, vector, vector2, duration ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], + vector2[0], vector2[1], vector2[2], duration, task->GetTimeStamp()); + icarus->GetGame()->Lerp2Pos(task->GetGUID(), m_ownerID, vector, vector2, duration); return TASK_OK; } @@ -1474,18 +1350,17 @@ Kill ------------------------- */ -int CTaskManager::Kill( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Kill(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->GetGame()->Kill( m_ownerID, sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->GetGame()->Kill(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1496,17 +1371,16 @@ Set ------------------------- */ -int CTaskManager::Set( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Set(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - icarus->GetGame()->Set( task->GetGUID(), m_ownerID, sVal, sVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + icarus->GetGame()->Set(task->GetGUID(), m_ownerID, sVal, sVal2); return TASK_OK; } @@ -1517,18 +1391,17 @@ Use ------------------------- */ -int CTaskManager::Use( CTask *task , CIcarus* icarus) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Use(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->GetGame()->Use( m_ownerID, sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->GetGame()->Use(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1539,23 +1412,21 @@ DeclareVariable ------------------------- */ -int CTaskManager::DeclareVariable( CTask *task , CIcarus* icarus) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; - float fVal; +int CTaskManager::DeclareVariable(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; + float fVal; - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal, icarus ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal, icarus)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int) fVal, sVal, task->GetTimeStamp() ); - icarus->GetGame()->DeclareVariable( (int) fVal, sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int)fVal, sVal, task->GetTimeStamp()); + icarus->GetGame()->DeclareVariable((int)fVal, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1564,21 +1435,19 @@ FreeVariable ------------------------- */ -int CTaskManager::FreeVariable( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::FreeVariable(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->GetGame()->FreeVariable( sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->GetGame()->FreeVariable(sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1587,18 +1456,17 @@ Signal ------------------------- */ -int CTaskManager::Signal( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Signal(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - icarus->Signal( (const char *) sVal ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + icarus->Signal((const char *)sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1609,17 +1477,16 @@ Play ------------------------- */ -int CTaskManager::Play( CTask *task, CIcarus* icarus ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Play(CTask *task, CIcarus *icarus) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal, icarus ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2, icarus ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal, icarus)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2, icarus)); - icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - icarus->GetGame()->Play( task->GetGUID(), m_ownerID, (const char *) sVal, (const char *) sVal2 ); + icarus->GetGame()->DebugPrint(IGameInterface::WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + icarus->GetGame()->Play(task->GetGUID(), m_ownerID, (const char *)sVal, (const char *)sVal2); return TASK_OK; } @@ -1630,42 +1497,40 @@ SaveCommand ------------------------- */ -//FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... +// FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... -int CTaskManager::SaveCommand( CBlock *block ) -{ +int CTaskManager::SaveCommand(CBlock *block) { CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - pIcarus->BufferWrite( &bID, sizeof( bID ) ); + pIcarus->BufferWrite(&bID, sizeof(bID)); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - pIcarus->BufferWrite( &flags, sizeof( flags ) ); + pIcarus->BufferWrite(&flags, sizeof(flags)); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - pIcarus->BufferWrite( &numMembers, sizeof( numMembers ) ); + pIcarus->BufferWrite(&numMembers, sizeof(numMembers)); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - pIcarus->BufferWrite( &bID, sizeof( bID ) ); + pIcarus->BufferWrite(&bID, sizeof(bID)); - //Save out the data size + // Save out the data size size = bm->GetSize(); - pIcarus->BufferWrite( &size, sizeof( size ) ); + pIcarus->BufferWrite(&size, sizeof(size)); - //Save out the raw data - pIcarus->BufferWrite( bm->GetData(), size ); + // Save out the raw data + pIcarus->BufferWrite(bm->GetData(), size); } return true; @@ -1677,15 +1542,14 @@ Save ------------------------- */ -void CTaskManager::Save() -{ - CTaskGroup *taskGroup; - const char *name; - CBlock *block; - unsigned int timeStamp; - bool completed; - int id, numCommands; - int numWritten; +void CTaskManager::Save() { + CTaskGroup *taskGroup; + const char *name; + CBlock *block; + unsigned int timeStamp; + bool completed; + int id, numCommands; + int numWritten; // Data saved here. // Taskmanager GUID. @@ -1711,115 +1575,109 @@ void CTaskManager::Save() CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - //Save the taskmanager's GUID - pIcarus->BufferWrite( &m_GUID, sizeof( m_GUID ) ); + // Save the taskmanager's GUID + pIcarus->BufferWrite(&m_GUID, sizeof(m_GUID)); - //Save out the number of tasks that will follow + // Save out the number of tasks that will follow int iNumTasks = m_tasks.size(); - pIcarus->BufferWrite( &iNumTasks, sizeof( iNumTasks ) ); + pIcarus->BufferWrite(&iNumTasks, sizeof(iNumTasks)); - //Save out all the tasks - tasks_l::iterator ti; + // Save out all the tasks + tasks_l::iterator ti; - STL_ITERATE( ti, m_tasks ) - { - //Save the GUID + STL_ITERATE(ti, m_tasks) { + // Save the GUID id = (*ti)->GetGUID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); - //Save the timeStamp (FIXME: Although, this is going to be worthless if time is not consistent...) + // Save the timeStamp (FIXME: Although, this is going to be worthless if time is not consistent...) timeStamp = (*ti)->GetTimeStamp(); - pIcarus->BufferWrite( &timeStamp, sizeof( timeStamp ) ); + pIcarus->BufferWrite(&timeStamp, sizeof(timeStamp)); - //Save out the block + // Save out the block block = (*ti)->GetBlock(); - SaveCommand( block ); + SaveCommand(block); } - //Save out the number of task groups + // Save out the number of task groups int numTaskGroups = m_taskGroups.size(); - pIcarus->BufferWrite( &numTaskGroups, sizeof( numTaskGroups ) ); + pIcarus->BufferWrite(&numTaskGroups, sizeof(numTaskGroups)); - //Save out the IDs of all the task groups + // Save out the IDs of all the task groups numWritten = 0; - taskGroup_v::iterator tgi; - STL_ITERATE( tgi, m_taskGroups ) - { + taskGroup_v::iterator tgi; + STL_ITERATE(tgi, m_taskGroups) { id = (*tgi)->GetGUID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); - //Save out the task groups + // Save out the task groups numWritten = 0; - STL_ITERATE( tgi, m_taskGroups ) - { - //Save out the parent - id = ( (*tgi)->GetParent() == NULL ) ? -1 : ((*tgi)->GetParent())->GetGUID(); - pIcarus->BufferWrite( &id, sizeof( id ) ); + STL_ITERATE(tgi, m_taskGroups) { + // Save out the parent + id = ((*tgi)->GetParent() == NULL) ? -1 : ((*tgi)->GetParent())->GetGUID(); + pIcarus->BufferWrite(&id, sizeof(id)); - //Save out the number of commands + // Save out the number of commands numCommands = (*tgi)->m_completedTasks.size(); - pIcarus->BufferWrite( &numCommands, sizeof( numCommands ) ); + pIcarus->BufferWrite(&numCommands, sizeof(numCommands)); - //Save out the command map - CTaskGroup::taskCallback_m::iterator tci; + // Save out the command map + CTaskGroup::taskCallback_m::iterator tci; - STL_ITERATE( tci, (*tgi)->m_completedTasks ) - { - //Write out the ID + STL_ITERATE(tci, (*tgi)->m_completedTasks) { + // Write out the ID id = (*tci).first; - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); - //Write out the state of completion + // Write out the state of completion completed = (*tci).second; - pIcarus->BufferWrite( &completed, sizeof( completed ) ); + pIcarus->BufferWrite(&completed, sizeof(completed)); } - //Save out the number of completed commands + // Save out the number of completed commands id = (*tgi)->m_numCompleted; - pIcarus->BufferWrite( &id, sizeof( id ) ); + pIcarus->BufferWrite(&id, sizeof(id)); numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); - //Only bother if we've got tasks present - if ( m_taskGroups.size() ) - { - //Save out the currently active group - int curGroupID = ( m_curGroup == NULL ) ? -1 : m_curGroup->GetGUID(); - pIcarus->BufferWrite( &curGroupID, sizeof( curGroupID ) ); + // Only bother if we've got tasks present + if (m_taskGroups.size()) { + // Save out the currently active group + int curGroupID = (m_curGroup == NULL) ? -1 : m_curGroup->GetGUID(); + pIcarus->BufferWrite(&curGroupID, sizeof(curGroupID)); } - //Save out the task group name maps - taskGroupName_m::iterator tmi; + // Save out the task group name maps + taskGroupName_m::iterator tmi; numWritten = 0; - STL_ITERATE( tmi, m_taskGroupNameMap ) - { + STL_ITERATE(tmi, m_taskGroupNameMap) { name = ((*tmi).first).c_str(); - //Make sure this is a valid string - assert( ( name != NULL ) && ( name[0] != '\0' ) ); + // Make sure this is a valid string + assert((name != NULL) && (name[0] != '\0')); - int length = strlen( name ) + 1; + int length = strlen(name) + 1; - //Save out the string size - //icarus->GetGame()->WriteSaveData( 'TGNL', &length, sizeof ( length ) ); - pIcarus->BufferWrite( &length, sizeof( length ) ); + // Save out the string size + // icarus->GetGame()->WriteSaveData( 'TGNL', &length, sizeof ( length ) ); + pIcarus->BufferWrite(&length, sizeof(length)); - //Write out the string - pIcarus->BufferWrite( (void *) name, length ); + // Write out the string + pIcarus->BufferWrite((void *)name, length); taskGroup = (*tmi).second; id = taskGroup->GetGUID(); - //Write out the ID - pIcarus->BufferWrite( &id, sizeof( id ) ); + // Write out the ID + pIcarus->BufferWrite(&id, sizeof(id)); numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); } /* @@ -1828,17 +1686,16 @@ Load ------------------------- */ -void CTaskManager::Load( CIcarus* icarus ) -{ - unsigned char flags; - CTaskGroup *taskGroup; - CBlock *block; - CTask *task; - unsigned int timeStamp; - bool completed; - void *bData; - int id, numTasks, numMembers; - int bID, bSize; +void CTaskManager::Load(CIcarus *icarus) { + unsigned char flags; + CTaskGroup *taskGroup; + CBlock *block; + CTask *task; + unsigned int timeStamp; + bool completed; + void *bData; + int id, numTasks, numMembers; + int bID, bSize; // Data expected/loaded here. // Taskmanager GUID. @@ -1864,195 +1721,187 @@ void CTaskManager::Load( CIcarus* icarus ) CIcarus *pIcarus = (CIcarus *)IIcarusInterface::GetIcarus(); - //Get the GUID - pIcarus->BufferRead( &m_GUID, sizeof( m_GUID ) ); + // Get the GUID + pIcarus->BufferRead(&m_GUID, sizeof(m_GUID)); - //Get the number of tasks to follow - pIcarus->BufferRead( &numTasks, sizeof( numTasks ) ); + // Get the number of tasks to follow + pIcarus->BufferRead(&numTasks, sizeof(numTasks)); - //Reload all the tasks - for ( int i = 0; i < numTasks; i++ ) - { + // Reload all the tasks + for (int i = 0; i < numTasks; i++) { task = new CTask; - assert( task ); + assert(task); - //Get the GUID - pIcarus->BufferRead( &id, sizeof( id ) ); - task->SetGUID( id ); + // Get the GUID + pIcarus->BufferRead(&id, sizeof(id)); + task->SetGUID(id); - //Get the time stamp - pIcarus->BufferRead( &timeStamp, sizeof( timeStamp ) ); - task->SetTimeStamp( timeStamp ); + // Get the time stamp + pIcarus->BufferRead(&timeStamp, sizeof(timeStamp)); + task->SetTimeStamp(timeStamp); // // BLOCK LOADING // - //Get the block ID and create a new container - pIcarus->BufferRead( &id, sizeof( id ) ); + // Get the block ID and create a new container + pIcarus->BufferRead(&id, sizeof(id)); block = new CBlock; - block->Create( id ); + block->Create(id); - //Read the block's flags - pIcarus->BufferRead( &flags, sizeof( flags ) ); - block->SetFlags( flags ); + // Read the block's flags + pIcarus->BufferRead(&flags, sizeof(flags)); + block->SetFlags(flags); - //Get the number of block members - pIcarus->BufferRead( &numMembers, sizeof( numMembers ) ); + // Get the number of block members + pIcarus->BufferRead(&numMembers, sizeof(numMembers)); - for ( int j = 0; j < numMembers; j++ ) - { - //Get the member ID - pIcarus->BufferRead( &bID, sizeof( bID ) ); + for (int j = 0; j < numMembers; j++) { + // Get the member ID + pIcarus->BufferRead(&bID, sizeof(bID)); - //Get the member size - pIcarus->BufferRead( &bSize, sizeof( bSize ) ); + // Get the member size + pIcarus->BufferRead(&bSize, sizeof(bSize)); - //Get the member's data - if ( ( bData = icarus->GetGame()->Malloc( bSize ) ) == NULL ) - { - assert( 0 ); + // Get the member's data + if ((bData = icarus->GetGame()->Malloc(bSize)) == NULL) { + assert(0); return; } - //Get the actual raw data - pIcarus->BufferRead( bData, bSize ); + // Get the actual raw data + pIcarus->BufferRead(bData, bSize); - //Write out the correct type - switch ( bID ) - { + // Write out the correct type + switch (bID) { case CIcarus::TK_FLOAT: - block->Write( CIcarus::TK_FLOAT, *(float *) bData, icarus ); + block->Write(CIcarus::TK_FLOAT, *(float *)bData, icarus); break; case CIcarus::TK_IDENTIFIER: - block->Write( CIcarus::TK_IDENTIFIER, (char *) bData , icarus); + block->Write(CIcarus::TK_IDENTIFIER, (char *)bData, icarus); break; case CIcarus::TK_STRING: - block->Write( CIcarus::TK_STRING, (char *) bData , icarus); + block->Write(CIcarus::TK_STRING, (char *)bData, icarus); break; case CIcarus::TK_VECTOR: - block->Write( CIcarus::TK_VECTOR, *(vec3_t *) bData, icarus ); + block->Write(CIcarus::TK_VECTOR, *(vec3_t *)bData, icarus); break; case CIcarus::ID_RANDOM: - block->Write( CIcarus::ID_RANDOM, *(float *) bData, icarus );//ID_RANDOM ); + block->Write(CIcarus::ID_RANDOM, *(float *)bData, icarus); // ID_RANDOM ); break; case CIcarus::ID_TAG: - block->Write( CIcarus::ID_TAG, (float) CIcarus::ID_TAG , icarus); + block->Write(CIcarus::ID_TAG, (float)CIcarus::ID_TAG, icarus); break; case CIcarus::ID_GET: - block->Write( CIcarus::ID_GET, (float) CIcarus::ID_GET , icarus); + block->Write(CIcarus::ID_GET, (float)CIcarus::ID_GET, icarus); break; default: icarus->GetGame()->DebugPrint(IGameInterface::WL_ERROR, "Invalid Block id %d\n", bID); - assert( 0 ); + assert(0); break; } - //Get rid of the temp memory - icarus->GetGame()->Free( bData ); + // Get rid of the temp memory + icarus->GetGame()->Free(bData); } - task->SetBlock( block ); + task->SetBlock(block); - STL_INSERT( m_tasks, task ); + STL_INSERT(m_tasks, task); } - //Load the task groups + // Load the task groups int numTaskGroups; - //icarus->GetGame()->ReadSaveData( 'TG#G', &numTaskGroups, sizeof( numTaskGroups ) ); - pIcarus->BufferRead( &numTaskGroups, sizeof( numTaskGroups ) ); + // icarus->GetGame()->ReadSaveData( 'TG#G', &numTaskGroups, sizeof( numTaskGroups ) ); + pIcarus->BufferRead(&numTaskGroups, sizeof(numTaskGroups)); - if ( numTaskGroups == 0 ) + if (numTaskGroups == 0) return; - int *taskIDs = new int[ numTaskGroups ]; + int *taskIDs = new int[numTaskGroups]; - //Get the task group IDs - for ( int i = 0; i < numTaskGroups; i++ ) - { - //Creat a new task group + // Get the task group IDs + for (int i = 0; i < numTaskGroups; i++) { + // Creat a new task group taskGroup = new CTaskGroup; - assert( taskGroup ); + assert(taskGroup); - //Get this task group's ID - pIcarus->BufferRead( &taskIDs[i], sizeof( taskIDs[i] ) ); + // Get this task group's ID + pIcarus->BufferRead(&taskIDs[i], sizeof(taskIDs[i])); taskGroup->m_GUID = taskIDs[i]; - m_taskGroupIDMap[ taskIDs[i] ] = taskGroup; + m_taskGroupIDMap[taskIDs[i]] = taskGroup; - STL_INSERT( m_taskGroups, taskGroup ); + STL_INSERT(m_taskGroups, taskGroup); } - //Recreate and load the task groups - for ( int i = 0; i < numTaskGroups; i++ ) - { - taskGroup = GetTaskGroup( taskIDs[i], icarus ); - assert( taskGroup ); + // Recreate and load the task groups + for (int i = 0; i < numTaskGroups; i++) { + taskGroup = GetTaskGroup(taskIDs[i], icarus); + assert(taskGroup); - //Load the parent ID - pIcarus->BufferRead( &id, sizeof( id ) ); + // Load the parent ID + pIcarus->BufferRead(&id, sizeof(id)); - if ( id != -1 ) - taskGroup->m_parent = ( GetTaskGroup( id, icarus ) != NULL ) ? GetTaskGroup( id, icarus ) : NULL; + if (id != -1) + taskGroup->m_parent = (GetTaskGroup(id, icarus) != NULL) ? GetTaskGroup(id, icarus) : NULL; - //Get the number of commands in this group - pIcarus->BufferRead( &numMembers, sizeof( numMembers ) ); + // Get the number of commands in this group + pIcarus->BufferRead(&numMembers, sizeof(numMembers)); - //Get each command and its completion state - for ( int j = 0; j < numMembers; j++ ) - { - //Get the ID - pIcarus->BufferRead( &id, sizeof( id ) ); + // Get each command and its completion state + for (int j = 0; j < numMembers; j++) { + // Get the ID + pIcarus->BufferRead(&id, sizeof(id)); - //Write out the state of completion - pIcarus->BufferRead( &completed, sizeof( completed ) ); + // Write out the state of completion + pIcarus->BufferRead(&completed, sizeof(completed)); - //Save it out - taskGroup->m_completedTasks[ id ] = completed; + // Save it out + taskGroup->m_completedTasks[id] = completed; } - //Get the number of completed tasks - pIcarus->BufferRead( &taskGroup->m_numCompleted, sizeof( taskGroup->m_numCompleted ) ); + // Get the number of completed tasks + pIcarus->BufferRead(&taskGroup->m_numCompleted, sizeof(taskGroup->m_numCompleted)); } - //Reload the currently active group + // Reload the currently active group int curGroupID; - pIcarus->BufferRead( &curGroupID, sizeof( curGroupID ) ); + pIcarus->BufferRead(&curGroupID, sizeof(curGroupID)); - //Reload the map entries - for ( int i = 0; i < numTaskGroups; i++ ) - { - char name[1024]; - int length; + // Reload the map entries + for (int i = 0; i < numTaskGroups; i++) { + char name[1024]; + int length; - //Get the size of the string - pIcarus->BufferRead( &length, sizeof( length ) ); + // Get the size of the string + pIcarus->BufferRead(&length, sizeof(length)); - //Get the string - pIcarus->BufferRead( &name, length ); + // Get the string + pIcarus->BufferRead(&name, length); - //Get the id - pIcarus->BufferRead( &id, sizeof( id ) ); + // Get the id + pIcarus->BufferRead(&id, sizeof(id)); - taskGroup = GetTaskGroup( id, icarus ); - assert( taskGroup ); + taskGroup = GetTaskGroup(id, icarus); + assert(taskGroup); - m_taskGroupNameMap[ name ] = taskGroup; - m_taskGroupIDMap[ taskGroup->GetGUID() ] = taskGroup; + m_taskGroupNameMap[name] = taskGroup; + m_taskGroupIDMap[taskGroup->GetGUID()] = taskGroup; } - m_curGroup = ( curGroupID == -1 ) ? NULL : m_taskGroupIDMap[curGroupID]; + m_curGroup = (curGroupID == -1) ? NULL : m_taskGroupIDMap[curGroupID]; delete[] taskIDs; } diff --git a/code/mp3code/cdct.c b/code/mp3code/cdct.c index 7afb95f608..80cc841ae9 100644 --- a/code/mp3code/cdct.c +++ b/code/mp3code/cdct.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -40,279 +40,252 @@ portable C #include #include -float coef32[31]; /* 32 pt dct coefs */ // !!!!!!!!!!!!!!!!!! (only generated once (always to same value) +float coef32[31]; /* 32 pt dct coefs */ // !!!!!!!!!!!!!!!!!! (only generated once (always to same value) /*------------------------------------------------------------*/ -float *dct_coef_addr() -{ - return coef32; -} +float *dct_coef_addr() { return coef32; } /*------------------------------------------------------------*/ -static void forward_bf(int m, int n, float x[], float f[], float coef[]) -{ - int i, j, n2; - int p, q, p0, k; +static void forward_bf(int m, int n, float x[], float f[], float coef[]) { + int i, j, n2; + int p, q, p0, k; - p0 = 0; - n2 = n >> 1; - for (i = 0; i < m; i++, p0 += n) - { - k = 0; - p = p0; - q = p + n - 1; - for (j = 0; j < n2; j++, p++, q--, k++) - { - f[p] = x[p] + x[q]; - f[n2 + p] = coef[k] * (x[p] - x[q]); - } - } + p0 = 0; + n2 = n >> 1; + for (i = 0; i < m; i++, p0 += n) { + k = 0; + p = p0; + q = p + n - 1; + for (j = 0; j < n2; j++, p++, q--, k++) { + f[p] = x[p] + x[q]; + f[n2 + p] = coef[k] * (x[p] - x[q]); + } + } } /*------------------------------------------------------------*/ -static void back_bf(int m, int n, float x[], float f[]) -{ - int i, j, n2, n21; - int p, q, p0; +static void back_bf(int m, int n, float x[], float f[]) { + int i, j, n2, n21; + int p, q, p0; - p0 = 0; - n2 = n >> 1; - n21 = n2 - 1; - for (i = 0; i < m; i++, p0 += n) - { - p = p0; - q = p0; - for (j = 0; j < n2; j++, p += 2, q++) - f[p] = x[q]; - p = p0 + 1; - for (j = 0; j < n21; j++, p += 2, q++) - f[p] = x[q] + x[q + 1]; - f[p] = x[q]; - } + p0 = 0; + n2 = n >> 1; + n21 = n2 - 1; + for (i = 0; i < m; i++, p0 += n) { + p = p0; + q = p0; + for (j = 0; j < n2; j++, p += 2, q++) + f[p] = x[q]; + p = p0 + 1; + for (j = 0; j < n21; j++, p += 2, q++) + f[p] = x[q] + x[q + 1]; + f[p] = x[q]; + } } /*------------------------------------------------------------*/ +void fdct32(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + int p, q; -void fdct32(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - int p, q; - - float *src = x; + float *src = x; -/* special first stage */ - for (p = 0, q = 31; p < 16; p++, q--) - { - a[p] = src[p] + src[q]; - a[16 + p] = coef32[p] * (src[p] - src[q]); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage */ + for (p = 0, q = 31; p < 16; p++, q--) { + a[p] = src[p] + src[q]; + a[16 + p] = coef32[p] * (src[p] - src[q]); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*------------------------------------------------------------*/ -void fdct32_dual(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - int p, pp, qq; +void fdct32_dual(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + int p, pp, qq; -/* special first stage for dual chan (interleaved x) */ - pp = 0; - qq = 2 * 31; - for (p = 0; p < 16; p++, pp += 2, qq -= 2) - { - a[p] = x[pp] + x[qq]; - a[16 + p] = coef32[p] * (x[pp] - x[qq]); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage for dual chan (interleaved x) */ + pp = 0; + qq = 2 * 31; + for (p = 0; p < 16; p++, pp += 2, qq -= 2) { + a[p] = x[pp] + x[qq]; + a[16 + p] = coef32[p] * (x[pp] - x[qq]); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*---------------convert dual to mono------------------------------*/ -void fdct32_dual_mono(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - float t1, t2; - int p, pp, qq; +void fdct32_dual_mono(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - pp = 0; - qq = 2 * 31; - for (p = 0; p < 16; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - a[p] = t1 + t2; - a[16 + p] = coef32[p] * (t1 - t2); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage */ + pp = 0; + qq = 2 * 31; + for (p = 0; p < 16; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + a[p] = t1 + t2; + a[16 + p] = coef32[p] * (t1 - t2); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct -------------------------------*/ -void fdct16(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - int p, q; +void fdct16(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + int p, q; -/* special first stage (drop highest sb) */ - a[0] = x[0]; - a[8] = coef32[16] * x[0]; - for (p = 1, q = 14; p < 8; p++, q--) - { - a[p] = x[p] + x[q]; - a[8 + p] = coef32[16 + p] * (x[p] - x[q]); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage (drop highest sb) */ + a[0] = x[0]; + a[8] = coef32[16] * x[0]; + for (p = 1, q = 14; p < 8; p++, q--) { + a[p] = x[p] + x[q]; + a[8 + p] = coef32[16 + p] * (x[p] - x[q]); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual chan---------------------*/ -void fdct16_dual(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - int p, pp, qq; +void fdct16_dual(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + int p, pp, qq; -/* special first stage for interleaved input */ - a[0] = x[0]; - a[8] = coef32[16] * x[0]; - pp = 2; - qq = 2 * 14; - for (p = 1; p < 8; p++, pp += 2, qq -= 2) - { - a[p] = x[pp] + x[qq]; - a[8 + p] = coef32[16 + p] * (x[pp] - x[qq]); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage for interleaved input */ + a[0] = x[0]; + a[8] = coef32[16] * x[0]; + pp = 2; + qq = 2 * 14; + for (p = 1; p < 8; p++, pp += 2, qq -= 2) { + a[p] = x[pp] + x[qq]; + a[8 + p] = coef32[16 + p] * (x[pp] - x[qq]); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual to mono-------------------*/ -void fdct16_dual_mono(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - float t1, t2; - int p, pp, qq; +void fdct16_dual_mono(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - a[0] = 0.5F * (x[0] + x[1]); - a[8] = coef32[16] * a[0]; - pp = 2; - qq = 2 * 14; - for (p = 1; p < 8; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - a[p] = t1 + t2; - a[8 + p] = coef32[16 + p] * (t1 - t2); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage */ + a[0] = 0.5F * (x[0] + x[1]); + a[8] = coef32[16] * a[0]; + pp = 2; + qq = 2 * 14; + for (p = 1; p < 8; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + a[p] = t1 + t2; + a[8 + p] = coef32[16 + p] * (t1 - t2); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct -------------------------------*/ -void fdct8(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - int p, q; +void fdct8(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + int p, q; -/* special first stage */ + /* special first stage */ - b[0] = x[0] + x[7]; - b[4] = coef32[16 + 8] * (x[0] - x[7]); - for (p = 1, q = 6; p < 4; p++, q--) - { - b[p] = x[p] + x[q]; - b[4 + p] = coef32[16 + 8 + p] * (x[p] - x[q]); - } + b[0] = x[0] + x[7]; + b[4] = coef32[16 + 8] * (x[0] - x[7]); + for (p = 1, q = 6; p < 4; p++, q--) { + b[p] = x[p] + x[q]; + b[4 + p] = coef32[16 + 8 + p] * (x[p] - x[q]); + } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual chan---------------------*/ -void fdct8_dual(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - int p, pp, qq; +void fdct8_dual(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + int p, pp, qq; -/* special first stage for interleaved input */ - b[0] = x[0] + x[14]; - b[4] = coef32[16 + 8] * (x[0] - x[14]); - pp = 2; - qq = 2 * 6; - for (p = 1; p < 4; p++, pp += 2, qq -= 2) - { - b[p] = x[pp] + x[qq]; - b[4 + p] = coef32[16 + 8 + p] * (x[pp] - x[qq]); - } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + /* special first stage for interleaved input */ + b[0] = x[0] + x[14]; + b[4] = coef32[16 + 8] * (x[0] - x[14]); + pp = 2; + qq = 2 * 6; + for (p = 1; p < 4; p++, pp += 2, qq -= 2) { + b[p] = x[pp] + x[qq]; + b[4 + p] = coef32[16 + 8 + p] * (x[pp] - x[qq]); + } + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual to mono---------------------*/ -void fdct8_dual_mono(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - float t1, t2; - int p, pp, qq; +void fdct8_dual_mono(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - t1 = 0.5F * (x[0] + x[1]); - t2 = 0.5F * (x[14] + x[15]); - b[0] = t1 + t2; - b[4] = coef32[16 + 8] * (t1 - t2); - pp = 2; - qq = 2 * 6; - for (p = 1; p < 4; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - b[p] = t1 + t2; - b[4 + p] = coef32[16 + 8 + p] * (t1 - t2); - } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + /* special first stage */ + t1 = 0.5F * (x[0] + x[1]); + t2 = 0.5F * (x[14] + x[15]); + b[0] = t1 + t2; + b[4] = coef32[16 + 8] * (t1 - t2); + pp = 2; + qq = 2 * 6; + for (p = 1; p < 4; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + b[p] = t1 + t2; + b[4 + p] = coef32[16 + 8 + p] * (t1 - t2); + } + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ diff --git a/code/mp3code/csbt.c b/code/mp3code/csbt.c index b264317528..bff51cfeac 100644 --- a/code/mp3code/csbt.c +++ b/code/mp3code/csbt.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -66,290 +66,246 @@ void window8_dual(float *vbuf, int vb_ptr, short *pcm); float *dct_coef_addr(); /*======================================================================*/ -static void gencoef() /* gen coef for N=32 (31 coefs) */ +static void gencoef() /* gen coef for N=32 (31 coefs) */ { static int iOnceOnly = 0; - int p, n, i, k; - double t, pi; - float *coef32; - - if (!iOnceOnly++) - { - coef32 = dct_coef_addr(); - - pi = 4.0 * atan(1.0); - n = 16; - k = 0; - for (i = 0; i < 5; i++, n = n / 2) - { - - for (p = 0; p < n; p++, k++) - { - t = (pi / (4 * n)) * (2 * p + 1); - coef32[k] = (float) (0.50 / cos(t)); - } - } - } + int p, n, i, k; + double t, pi; + float *coef32; + + if (!iOnceOnly++) { + coef32 = dct_coef_addr(); + + pi = 4.0 * atan(1.0); + n = 16; + k = 0; + for (i = 0; i < 5; i++, n = n / 2) { + + for (p = 0; p < n; p++, k++) { + t = (pi / (4 * n)) * (2 * p + 1); + coef32[k] = (float)(0.50 / cos(t)); + } + } + } } /*------------------------------------------------------------*/ -void sbt_init() -{ - int i; - static int first_pass = 1; - - if (first_pass) - { - gencoef(); - first_pass = 0; - } - -/* clear window pMP3Stream->vbuf */ - for (i = 0; i < 512; i++) - { - pMP3Stream->vbuf[i] = 0.0F; - pMP3Stream->vbuf2[i] = 0.0F; - } - pMP3Stream->vb2_ptr = pMP3Stream->vb_ptr = 0; - +void sbt_init() { + int i; + static int first_pass = 1; + + if (first_pass) { + gencoef(); + first_pass = 0; + } + + /* clear window pMP3Stream->vbuf */ + for (i = 0; i < 512; i++) { + pMP3Stream->vbuf[i] = 0.0F; + pMP3Stream->vbuf2[i] = 0.0F; + } + pMP3Stream->vb2_ptr = pMP3Stream->vb_ptr = 0; } /*============================================================*/ /*============================================================*/ /*============================================================*/ -void sbt_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbt_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbt_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 64; - } - - +void sbt_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 64; + } } /*------------------------------------------------------------*/ /* convert dual to mono */ -void sbt_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbt_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to left */ -void sbt_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbt_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to right */ -void sbt_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; /* point to right chan */ - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbt_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; /* point to right chan */ + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt16_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } - - +void sbt16_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } +void sbt16_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbt16_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt8_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } - +void sbt8_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 16; - } +void sbt8_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt8_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ #define COMPILE_ME -#include "csbtb.c" /* 8 bit output */ -#include "csbtl3.c" /* Layer III */ +#include "csbtb.c" /* 8 bit output */ +#include "csbtl3.c" /* Layer III */ /*------------------------------------------------------------*/ diff --git a/code/mp3code/csbtb.c b/code/mp3code/csbtb.c index dfb401171c..1e1e30e43d 100644 --- a/code/mp3code/csbtb.c +++ b/code/mp3code/csbtb.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -42,237 +42,200 @@ void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm); void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm); /*============================================================*/ -void sbtB_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbtB_mono(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbtB_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 64; - } - - +void sbtB_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 64; + } } /*------------------------------------------------------------*/ /* convert dual to mono */ -void sbtB_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbtB_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to left */ -void sbtB_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbtB_dual_left(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to right */ -void sbtB_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; /* point to right chan */ - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbtB_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; /* point to right chan */ + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB16_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } - +void sbtB16_mono(float *sample, unsigned char *pcm, int n) { + int i; + for (i = 0; i < n; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } +void sbtB16_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB16_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } + for (i = 0; i < n; i++) { + fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB16_dual_left(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbtB16_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB8_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbtB8_mono(float *sample, unsigned char *pcm, int n) { + int i; + for (i = 0; i < n; i++) { + fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 16; - } +void sbtB8_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } + for (i = 0; i < n; i++) { + fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB8_dual_left(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbtB8_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/csbtl3.c b/code/mp3code/csbtl3.c index e63995c08e..9d59ea8e94 100644 --- a/code/mp3code/csbtl3.c +++ b/code/mp3code/csbtl3.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -35,13 +35,11 @@ layer III /*============================================================*/ /*============ Layer III =====================================*/ /*============================================================*/ -void sbt_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -50,25 +48,19 @@ void sbt_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt_dual_L3(float *sample, short *pcm, int ch) -{ +void sbt_dual_L3(float *sample, short *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; pcm += 64; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); window_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -81,13 +73,11 @@ void sbt_dual_L3(float *sample, short *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt16_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt16_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -96,43 +86,35 @@ void sbt16_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt16_dual_L3(float *sample, short *pcm, int ch) -{ - int i; +void sbt16_dual_L3(float *sample, short *pcm, int ch) { + int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 32; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } - } - else - { - for (i = 0; i < 18; i++) - { - fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); - window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); - sample += 32; - pMP3Stream->vb2_ptr = (pMP3Stream->vb2_ptr - 16) & 255; - pcm += 32; - } - } + if (ch == 0) { + for (i = 0; i < 18; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 32; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } + } else { + for (i = 0; i < 18; i++) { + fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); + window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); + sample += 32; + pMP3Stream->vb2_ptr = (pMP3Stream->vb2_ptr - 16) & 255; + pcm += 32; + } + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt8_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt8_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -141,25 +123,19 @@ void sbt8_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt8_dual_L3(float *sample, short *pcm, int ch) -{ +void sbt8_dual_L3(float *sample, short *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; pcm += 16; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -171,13 +147,11 @@ void sbt8_dual_L3(float *sample, short *pcm, int ch) /*------------------------------------------------------------*/ /*------- 8 bit output ---------------------------------------*/ /*------------------------------------------------------------*/ -void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -186,25 +160,19 @@ void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; pcm += 64; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -217,13 +185,11 @@ void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 16 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -232,25 +198,19 @@ void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; pcm += 32; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -262,13 +222,11 @@ void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 8 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -277,25 +235,19 @@ void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; pcm += 16; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -305,4 +257,4 @@ void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/cup.c b/code/mp3code/cup.c index 7fbb73c098..516faa76a7 100644 --- a/code/mp3code/cup.c +++ b/code/mp3code/cup.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,43 +37,43 @@ mods 11/15/95 for Layer I ******************************************************************/ /****************************************************************** - MPEG audio software decoder portable ANSI c. - Decodes all Layer I/II to 16 bit linear pcm. - Optional stereo to mono conversion. Optional - output sample rate conversion to half or quarter of - native mpeg rate. dec8.c adds oupuut conversion features. + MPEG audio software decoder portable ANSI c. + Decodes all Layer I/II to 16 bit linear pcm. + Optional stereo to mono conversion. Optional + output sample rate conversion to half or quarter of + native mpeg rate. dec8.c adds oupuut conversion features. ------------------------------------- int audio_decode_init(MPEG_HEAD *h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) + int reduction_code, int transform_code, int convert_code, + int freq_limit) initilize decoder: - return 0 = fail, not 0 = success + return 0 = fail, not 0 = success MPEG_HEAD *h input, mpeg header info (returned by call to head_info) pMP3Stream->framebytes input, mpeg frame size (returned by call to head_info) reduction_code input, sample rate reduction code - 0 = full rate - 1 = half rate - 2 = quarter rate + 0 = full rate + 1 = half rate + 2 = quarter rate transform_code input, ignored convert_code input, channel conversion - convert_code: 0 = two chan output - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan + convert_code: 0 = two chan output + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan freq_limit input, limits bandwidth of pcm output to specified - frequency. Special use. Set to 24000 for normal use. + frequency. Special use. Set to 24000 for normal use. --------------------------------- void audio_decode_info( DEC_INFO *info) information return: - Call after audio_decode_init. See mhead.h for - information returned in DEC_INFO structure. + Call after audio_decode_init. See mhead.h for + information returned in DEC_INFO structure. --------------------------------- @@ -81,23 +81,22 @@ IN_OUT audio_decode(unsigned char *bs, void *pcmbuf) decode one mpeg audio frame: bs input, mpeg bitstream, must start with - sync word. Caution: may read up to 3 bytes - beyond end of frame. + sync word. Caution: may read up to 3 bytes + beyond end of frame. pcmbuf output, pcm samples. IN_OUT structure returns: - Number bytes conceptually removed from mpeg bitstream. - Returns 0 if sync loss. - Number bytes of pcm output. + Number bytes conceptually removed from mpeg bitstream. + Returns 0 if sync loss. + Number bytes of pcm output. *******************************************************************/ - #include #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ #include "mp3struct.h" @@ -110,22 +109,22 @@ not cause a memory access violation (protection fault) /*====================================================================*/ /*----------------*/ //@@@@ This next one (decinfo) is ok: -DEC_INFO decinfo; /* global for Layer III */ // only written into by decode init funcs, then copied to stack struct higher up +DEC_INFO decinfo; /* global for Layer III */ // only written into by decode init funcs, then copied to stack struct higher up /*----------------*/ -static float look_c_value[18]; /* built by init */ // effectively constant +static float look_c_value[18]; /* built by init */ // effectively constant /*----------------*/ ////@@@@static int pMP3Stream->outbytes; // !!!!!!!!!!!!!!? ////@@@@static int pMP3Stream->framebytes; // !!!!!!!!!!!!!!!! ////@@@@static int pMP3Stream->outvalues; // !!!!!!!!!!!!? ////@@@@static int pad; -static const int look_joint[16] = -{ /* lookup stereo sb's by mode+ext */ - 64, 64, 64, 64, /* stereo */ - 2 * 4, 2 * 8, 2 * 12, 2 * 16, /* joint */ - 64, 64, 64, 64, /* dual */ - 32, 32, 32, 32, /* mono */ +static const int look_joint[16] = { + /* lookup stereo sb's by mode+ext */ + 64, 64, 64, 64, /* stereo */ + 2 * 4, 2 * 8, 2 * 12, 2 * 16, /* joint */ + 64, 64, 64, 64, /* dual */ + 32, 32, 32, 32, /* mono */ }; /*----------------*/ @@ -135,28 +134,26 @@ static const int look_joint[16] = /*----------------*/ ////@@@@static int pMP3Stream->nsb_limit = 6; ////@@@@static int bit_skip; -static const int bat_bit_master[] = -{ - 0, 5, 7, 9, 10, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}; +static const int bat_bit_master[] = {0, 5, 7, 9, 10, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}; /*----------------*/ ////@@@@static int nbat[4] = {3, 8, 12, 7}; // !!!!!!!!!!!!! not constant!!!! ////@@@@static int bat[4][16]; // built as constant, but built according to header type (sigh) -static int ballo[64]; /* set by unpack_ba */ // scratchpad -static unsigned int samp_dispatch[66]; /* set by unpack_ba */ // scratchpad? -static float c_value[64]; /* set by unpack_ba */ // scratchpad +static int ballo[64]; /* set by unpack_ba */ // scratchpad +static unsigned int samp_dispatch[66]; /* set by unpack_ba */ // scratchpad? +static float c_value[64]; /* set by unpack_ba */ // scratchpad /*----------------*/ -static unsigned int sf_dispatch[66]; /* set by unpack_ba */ // scratchpad? -static float sf_table[64]; // effectively constant +static unsigned int sf_dispatch[66]; /* set by unpack_ba */ // scratchpad? +static float sf_table[64]; // effectively constant ////@@@@ static float cs_factor[3][64]; /*----------------*/ ////@@@@FINDME - groan.... (I shoved a *2 in just in case it needed it for stereo. This whole thing is crap now -float sample[2304*2]; /* global for use by Later 3 */ // !!!!!!!!!!!!!!!!!!!!!! // scratchpad? -static signed char group3_table[32][3]; // effectively constant -static signed char group5_table[128][3]; // effectively constant -static signed short group9_table[1024][3]; // effectively constant +float sample[2304 * 2]; /* global for use by Later 3 */ // !!!!!!!!!!!!!!!!!!!!!! // scratchpad? +static signed char group3_table[32][3]; // effectively constant +static signed char group5_table[128][3]; // effectively constant +static signed short group9_table[1024][3]; // effectively constant /*----------------*/ @@ -165,8 +162,7 @@ void sbt_mono(float *sample, short *pcm, int n); void sbt_dual(float *sample, short *pcm, int n); ////@@@@static SBT_FUNCTION sbt = sbt_mono; - -typedef IN_OUT(*AUDIO_DECODE_ROUTINE) (unsigned char *bs, signed short *pcm); +typedef IN_OUT (*AUDIO_DECODE_ROUTINE)(unsigned char *bs, signed short *pcm); IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm); static AUDIO_DECODE_ROUTINE audio_decode_routine = L2audio_decode; @@ -180,361 +176,343 @@ static int bits; static long bitval; /*------------- initialize bit getter -------------*/ -static void load_init(unsigned char *buf) -{ - bs_ptr = buf; - bits = 0; - bitbuf = 0; +static void load_init(unsigned char *buf) { + bs_ptr = buf; + bits = 0; + bitbuf = 0; } /*------------- get n bits from bitstream -------------*/ -static long load(int n) -{ - unsigned long x; - - if (bits < n) - { /* refill bit buf if necessary */ - while (bits <= 24) - { - bitbuf = (bitbuf << 8) | *bs_ptr++; - bits += 8; - } - } - bits -= n; - x = bitbuf >> bits; - bitbuf -= x << bits; - return x; +static long load(int n) { + unsigned long x; + + if (bits < n) { /* refill bit buf if necessary */ + while (bits <= 24) { + bitbuf = (bitbuf << 8) | *bs_ptr++; + bits += 8; + } + } + bits -= n; + x = bitbuf >> bits; + bitbuf -= x << bits; + return x; } /*------------- skip over n bits in bitstream -------------*/ -static void skip(int n) -{ - int k; - - if (bits < n) - { - n -= bits; - k = n >> 3; -/*--- bytes = n/8 --*/ - bs_ptr += k; - n -= k << 3; - bitbuf = *bs_ptr++; - bits = 8; - } - bits -= n; - bitbuf -= (bitbuf >> bits) << bits; +static void skip(int n) { + int k; + + if (bits < n) { + n -= bits; + k = n >> 3; + /*--- bytes = n/8 --*/ + bs_ptr += k; + n -= k << 3; + bitbuf = *bs_ptr++; + bits = 8; + } + bits -= n; + bitbuf -= (bitbuf >> bits) << bits; } /*--------------------------------------------------------------*/ -#define mac_load_check(n) if( bits < (n) ) { \ - while( bits <= 24 ) { \ - bitbuf = (bitbuf << 8) | *bs_ptr++; \ - bits += 8; \ - } \ - } +#define mac_load_check(n) \ + if (bits < (n)) { \ + while (bits <= 24) { \ + bitbuf = (bitbuf << 8) | *bs_ptr++; \ + bits += 8; \ + } \ + } /*--------------------------------------------------------------*/ -#define mac_load(n) ( bits -= n, \ - bitval = bitbuf >> bits, \ - bitbuf -= bitval << bits, \ - bitval ) +#define mac_load(n) (bits -= n, bitval = bitbuf >> bits, bitbuf -= bitval << bits, bitval) /*======================================================================*/ -static void unpack_ba() -{ - int i, j, k; - static int nbit[4] = - {4, 4, 3, 2}; - int nstereo; - - pMP3Stream->bit_skip = 0; - nstereo = pMP3Stream->stereo_sb; - k = 0; - for (i = 0; i < 4; i++) - { - for (j = 0; j < pMP3Stream->nbat[i]; j++, k++) - { - mac_load_check(4); - ballo[k] = samp_dispatch[k] = pMP3Stream->bat[i][mac_load(nbit[i])]; - if (k >= pMP3Stream->nsb_limit) - pMP3Stream->bit_skip += bat_bit_master[samp_dispatch[k]]; - c_value[k] = look_c_value[samp_dispatch[k]]; - if (--nstereo < 0) - { - ballo[k + 1] = ballo[k]; - samp_dispatch[k] += 18; /* flag as joint */ - samp_dispatch[k + 1] = samp_dispatch[k]; /* flag for sf */ - c_value[k + 1] = c_value[k]; - k++; - j++; - } - } - } - samp_dispatch[pMP3Stream->nsb_limit] = 37; /* terminate the dispatcher with skip */ - samp_dispatch[k] = 36; /* terminate the dispatcher */ - +static void unpack_ba() { + int i, j, k; + static int nbit[4] = {4, 4, 3, 2}; + int nstereo; + + pMP3Stream->bit_skip = 0; + nstereo = pMP3Stream->stereo_sb; + k = 0; + for (i = 0; i < 4; i++) { + for (j = 0; j < pMP3Stream->nbat[i]; j++, k++) { + mac_load_check(4); + ballo[k] = samp_dispatch[k] = pMP3Stream->bat[i][mac_load(nbit[i])]; + if (k >= pMP3Stream->nsb_limit) + pMP3Stream->bit_skip += bat_bit_master[samp_dispatch[k]]; + c_value[k] = look_c_value[samp_dispatch[k]]; + if (--nstereo < 0) { + ballo[k + 1] = ballo[k]; + samp_dispatch[k] += 18; /* flag as joint */ + samp_dispatch[k + 1] = samp_dispatch[k]; /* flag for sf */ + c_value[k + 1] = c_value[k]; + k++; + j++; + } + } + } + samp_dispatch[pMP3Stream->nsb_limit] = 37; /* terminate the dispatcher with skip */ + samp_dispatch[k] = 36; /* terminate the dispatcher */ } /*-------------------------------------------------------------------------*/ -static void unpack_sfs() /* unpack scale factor selectors */ +static void unpack_sfs() /* unpack scale factor selectors */ { - int i; - - for (i = 0; i < pMP3Stream->max_sb; i++) - { - mac_load_check(2); - if (ballo[i]) - sf_dispatch[i] = mac_load(2); - else - sf_dispatch[i] = 4; /* no allo */ - } - sf_dispatch[i] = 5; /* terminate dispatcher */ + int i; + + for (i = 0; i < pMP3Stream->max_sb; i++) { + mac_load_check(2); + if (ballo[i]) + sf_dispatch[i] = mac_load(2); + else + sf_dispatch[i] = 4; /* no allo */ + } + sf_dispatch[i] = 5; /* terminate dispatcher */ } /*-------------------------------------------------------------------------*/ -static void unpack_sf() /* unpack scale factor */ -{ /* combine dequant and scale factors */ - int i; - - i = -1; - dispatch:switch (sf_dispatch[++i]) - { - case 0: /* 3 factors 012 */ - mac_load_check(18); - pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 1: /* 2 factors 002 */ - mac_load_check(12); - pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 2: /* 1 factor 000 */ - mac_load_check(6); - pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = - c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 3: /* 2 factors 022 */ - mac_load_check(12); - pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 4: /* no allo */ -/*-- pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = 0.0; --*/ - goto dispatch; - case 5: /* all done */ - ; - } /* end switch */ +static void unpack_sf() /* unpack scale factor */ +{ /* combine dequant and scale factors */ + int i; + + i = -1; +dispatch: + switch (sf_dispatch[++i]) { + case 0: /* 3 factors 012 */ + mac_load_check(18); + pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 1: /* 2 factors 002 */ + mac_load_check(12); + pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 2: /* 1 factor 000 */ + mac_load_check(6); + pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 3: /* 2 factors 022 */ + mac_load_check(12); + pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 4: /* no allo */ + /*-- pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = 0.0; --*/ + goto dispatch; + case 5: /* all done */ + ; + } /* end switch */ } /*-------------------------------------------------------------------------*/ -#define UNPACK_N(n) s[k] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACK_N2(n) mac_load_check(3*n); \ - s[k] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACK_N3(n) mac_load_check(2*n); \ - s[k] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - mac_load_check(n); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACKJ_N(n) tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+64+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+128+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - k++; /* skip right chan dispatch */ \ - goto dispatch; +#define UNPACK_N(n) \ + s[k] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACK_N2(n) \ + mac_load_check(3 * n); \ + s[k] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACK_N3(n) \ + mac_load_check(2 * n); \ + s[k] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + mac_load_check(n); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACKJ_N(n) \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + k++; /* skip right chan dispatch */ \ + goto dispatch; /*-------------------------------------------------------------------------*/ -static void unpack_samp() /* unpack samples */ +static void unpack_samp() /* unpack samples */ { - int i, j, k; - float *s; - int n; - long tmp; - - s = sample; - for (i = 0; i < 3; i++) - { /* 3 groups of scale factors */ - for (j = 0; j < 4; j++) - { - k = -1; - dispatch:switch (samp_dispatch[++k]) - { - case 0: - s[k + 128] = s[k + 64] = s[k] = 0.0F; - goto dispatch; - case 1: /* 3 levels grouped 5 bits */ - mac_load_check(5); - n = mac_load(5); - s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; - goto dispatch; - case 2: /* 5 levels grouped 7 bits */ - mac_load_check(7); - n = mac_load(7); - s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; - goto dispatch; - case 3: - UNPACK_N2(3) /* 7 levels */ - case 4: /* 9 levels grouped 10 bits */ - mac_load_check(10); - n = mac_load(10); - s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; - goto dispatch; - case 5: - UNPACK_N2(4) /* 15 levels */ - case 6: - UNPACK_N2(5) /* 31 levels */ - case 7: - UNPACK_N2(6) /* 63 levels */ - case 8: - UNPACK_N2(7) /* 127 levels */ - case 9: - UNPACK_N2(8) /* 255 levels */ - case 10: - UNPACK_N3(9) /* 511 levels */ - case 11: - UNPACK_N3(10) /* 1023 levels */ - case 12: - UNPACK_N3(11) /* 2047 levels */ - case 13: - UNPACK_N3(12) /* 4095 levels */ - case 14: - UNPACK_N(13) /* 8191 levels */ - case 15: - UNPACK_N(14) /* 16383 levels */ - case 16: - UNPACK_N(15) /* 32767 levels */ - case 17: - UNPACK_N(16) /* 65535 levels */ -/* -- joint ---- */ - case 18 + 0: - s[k + 128 + 1] = s[k + 128] = s[k + 64 + 1] = s[k + 64] = s[k + 1] = s[k] = 0.0F; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 1: /* 3 levels grouped 5 bits */ - n = load(5); - s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 2: /* 5 levels grouped 7 bits */ - n = load(7); - s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 3: - UNPACKJ_N(3) /* 7 levels */ - case 18 + 4: /* 9 levels grouped 10 bits */ - n = load(10); - s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 5: - UNPACKJ_N(4) /* 15 levels */ - case 18 + 6: - UNPACKJ_N(5) /* 31 levels */ - case 18 + 7: - UNPACKJ_N(6) /* 63 levels */ - case 18 + 8: - UNPACKJ_N(7) /* 127 levels */ - case 18 + 9: - UNPACKJ_N(8) /* 255 levels */ - case 18 + 10: - UNPACKJ_N(9) /* 511 levels */ - case 18 + 11: - UNPACKJ_N(10) /* 1023 levels */ - case 18 + 12: - UNPACKJ_N(11) /* 2047 levels */ - case 18 + 13: - UNPACKJ_N(12) /* 4095 levels */ - case 18 + 14: - UNPACKJ_N(13) /* 8191 levels */ - case 18 + 15: - UNPACKJ_N(14) /* 16383 levels */ - case 18 + 16: - UNPACKJ_N(15) /* 32767 levels */ - case 18 + 17: - UNPACKJ_N(16) /* 65535 levels */ -/* -- end of dispatch -- */ - case 37: - skip(pMP3Stream->bit_skip); - case 36: - s += 3 * 64; - } /* end switch */ - } /* end j loop */ - } /* end i loop */ - - + int i, j, k; + float *s; + int n; + long tmp; + + s = sample; + for (i = 0; i < 3; i++) { /* 3 groups of scale factors */ + for (j = 0; j < 4; j++) { + k = -1; + dispatch: + switch (samp_dispatch[++k]) { + case 0: + s[k + 128] = s[k + 64] = s[k] = 0.0F; + goto dispatch; + case 1: /* 3 levels grouped 5 bits */ + mac_load_check(5); + n = mac_load(5); + s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; + goto dispatch; + case 2: /* 5 levels grouped 7 bits */ + mac_load_check(7); + n = mac_load(7); + s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; + goto dispatch; + case 3: + UNPACK_N2(3) /* 7 levels */ + case 4: /* 9 levels grouped 10 bits */ + mac_load_check(10); + n = mac_load(10); + s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; + goto dispatch; + case 5: + UNPACK_N2(4) /* 15 levels */ + case 6: + UNPACK_N2(5) /* 31 levels */ + case 7: + UNPACK_N2(6) /* 63 levels */ + case 8: + UNPACK_N2(7) /* 127 levels */ + case 9: + UNPACK_N2(8) /* 255 levels */ + case 10: + UNPACK_N3(9) /* 511 levels */ + case 11: + UNPACK_N3(10) /* 1023 levels */ + case 12: + UNPACK_N3(11) /* 2047 levels */ + case 13: + UNPACK_N3(12) /* 4095 levels */ + case 14: + UNPACK_N(13) /* 8191 levels */ + case 15: + UNPACK_N(14) /* 16383 levels */ + case 16: + UNPACK_N(15) /* 32767 levels */ + case 17: + UNPACK_N(16) /* 65535 levels */ + /* -- joint ---- */ + case 18 + 0: + s[k + 128 + 1] = s[k + 128] = s[k + 64 + 1] = s[k + 64] = s[k + 1] = s[k] = 0.0F; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 1: /* 3 levels grouped 5 bits */ + n = load(5); + s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 2: /* 5 levels grouped 7 bits */ + n = load(7); + s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 3: + UNPACKJ_N(3) /* 7 levels */ + case 18 + 4: /* 9 levels grouped 10 bits */ + n = load(10); + s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 5: + UNPACKJ_N(4) /* 15 levels */ + case 18 + 6: + UNPACKJ_N(5) /* 31 levels */ + case 18 + 7: + UNPACKJ_N(6) /* 63 levels */ + case 18 + 8: + UNPACKJ_N(7) /* 127 levels */ + case 18 + 9: + UNPACKJ_N(8) /* 255 levels */ + case 18 + 10: + UNPACKJ_N(9) /* 511 levels */ + case 18 + 11: + UNPACKJ_N(10) /* 1023 levels */ + case 18 + 12: + UNPACKJ_N(11) /* 2047 levels */ + case 18 + 13: + UNPACKJ_N(12) /* 4095 levels */ + case 18 + 14: + UNPACKJ_N(13) /* 8191 levels */ + case 18 + 15: + UNPACKJ_N(14) /* 16383 levels */ + case 18 + 16: + UNPACKJ_N(15) /* 32767 levels */ + case 18 + 17: + UNPACKJ_N(16) /* 65535 levels */ + /* -- end of dispatch -- */ + case 37: + skip(pMP3Stream->bit_skip); + case 36: + s += 3 * 64; + } /* end switch */ + } /* end j loop */ + } /* end i loop */ } /*-------------------------------------------------------------------------*/ unsigned char *gpNextByteAfterData = NULL; -IN_OUT audio_decode(unsigned char *bs, signed short *pcm, unsigned char *pNextByteAfterData) -{ - gpNextByteAfterData = pNextByteAfterData; // sigh.... - return audio_decode_routine(bs, pcm); +IN_OUT audio_decode(unsigned char *bs, signed short *pcm, unsigned char *pNextByteAfterData) { + gpNextByteAfterData = pNextByteAfterData; // sigh.... + return audio_decode_routine(bs, pcm); } /*-------------------------------------------------------------------------*/ -IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm) -{ - int sync, prot; - IN_OUT in_out; - - load_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = load(12); - if (sync != 0xFFF) - return in_out; /* sync fail */ - - load(3); /* skip id and option (checked by init) */ - prot = load(1); /* load prot bit */ - load(6); /* skip to pad */ - pMP3Stream->pad = load(1); - load(1); /* skip to mode */ - pMP3Stream->stereo_sb = look_joint[load(4)]; - if (prot) - load(4); /* skip to data */ - else - load(20); /* skip crc */ - - unpack_ba(); /* unpack bit allocation */ - unpack_sfs(); /* unpack scale factor selectors */ - unpack_sf(); /* unpack scale factor */ - unpack_samp(); /* unpack samples */ - - pMP3Stream->sbt(sample, pcm, 36); -/*-----------*/ - in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.out_bytes = pMP3Stream->outbytes; - - return in_out; +IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm) { + int sync, prot; + IN_OUT in_out; + + load_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = load(12); + if (sync != 0xFFF) + return in_out; /* sync fail */ + + load(3); /* skip id and option (checked by init) */ + prot = load(1); /* load prot bit */ + load(6); /* skip to pad */ + pMP3Stream->pad = load(1); + load(1); /* skip to mode */ + pMP3Stream->stereo_sb = look_joint[load(4)]; + if (prot) + load(4); /* skip to data */ + else + load(20); /* skip crc */ + + unpack_ba(); /* unpack bit allocation */ + unpack_sfs(); /* unpack scale factor selectors */ + unpack_sf(); /* unpack scale factor */ + unpack_samp(); /* unpack samples */ + + pMP3Stream->sbt(sample, pcm, 36); + /*-----------*/ + in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.out_bytes = pMP3Stream->outbytes; + + return in_out; } /*-------------------------------------------------------------------------*/ #define COMPILE_ME -#include "cupini.c" /* initialization */ -#include "cupl1.c" /* Layer I */ +#include "cupini.c" /* initialization */ +#include "cupl1.c" /* Layer I */ /*-------------------------------------------------------------------------*/ diff --git a/code/mp3code/cupini.c b/code/mp3code/cupini.c index 5a317adced..b1ebc34a84 100644 --- a/code/mp3code/cupini.c +++ b/code/mp3code/cupini.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -34,89 +34,75 @@ mod 8/6/96 add 8 bit output mod 5/10/95 add quick (low precision) window mod 5/16/95 sb limit for reduced samprate output - changed from 94% to 100% of Nyquist sb + changed from 94% to 100% of Nyquist sb mod 11/15/95 for Layer I =========================================================*/ -static const long steps[18] = -{ - 0, 3, 5, 7, 9, 15, 31, 63, 127, - 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; - +static const long steps[18] = {0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; /* ABCD_INDEX = lookqt[mode][sr_index][br_index] */ /* -1 = invalid */ -static const signed char lookqt[4][3][16] = -{ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ -// mono extended beyond legal br index -// 1,2,2,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 44ks single chan */ -// 0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,-1, /* 48ks */ -// 1,3,3,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 32ks */ -// legal mono - {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ - {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ - {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ +static const signed char lookqt[4][3][16] = { + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + // mono extended beyond legal br index + // 1,2,2,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 44ks single chan */ + // 0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,-1, /* 48ks */ + // 1,3,3,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 32ks */ + // legal mono + {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ + {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ + {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ }; -static const long sr_table[8] = -{22050L, 24000L, 16000L, 1L, - 44100L, 48000L, 32000L, 1L}; +static const long sr_table[8] = {22050L, 24000L, 16000L, 1L, 44100L, 48000L, 32000L, 1L}; /* bit allocation table look up */ /* table per mpeg spec tables 3b2a/b/c/d /e is mpeg2 */ /* look_bat[abcd_index][4][16] */ -static const unsigned char look_bat[5][4][16] = -{ -/* LOOK_BATA */ - {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, - {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATB */ - {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, - {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATC */ - {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATD */ - {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATE */ - {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, +static const unsigned char look_bat[5][4][16] = { + /* LOOK_BATA */ + {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, + {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATB */ + {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, + {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATC */ + {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATD */ + {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATE */ + {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, }; /* look_nbat[abcd_index]][4] */ -static const unsigned char look_nbat[5][4] = -{ - {3, 8, 12, 4}, - {3, 8, 12, 7}, - {2, 0, 6, 0}, - {2, 0, 10, 0}, - {4, 0, 7, 19}, +static const unsigned char look_nbat[5][4] = { + {3, 8, 12, 4}, {3, 8, 12, 7}, {2, 0, 6, 0}, {2, 0, 10, 0}, {4, 0, 7, 19}, }; - void sbt_mono(float *sample, short *pcm, int n); void sbt_dual(float *sample, short *pcm, int n); void sbt_dual_mono(float *sample, short *pcm, int n); @@ -150,243 +136,191 @@ void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n); void sbtB8_dual_left(float *sample, unsigned char *pcm, int n); void sbtB8_dual_right(float *sample, unsigned char *pcm, int n); - -static const SBT_FUNCTION sbt_table[2][3][5] = -{ - {{sbt_mono, sbt_dual, sbt_dual_mono, sbt_dual_left, sbt_dual_right}, - {sbt16_mono, sbt16_dual, sbt16_dual_mono, sbt16_dual_left, sbt16_dual_right}, - {sbt8_mono, sbt8_dual, sbt8_dual_mono, sbt8_dual_left, sbt8_dual_right}}, - {{(SBT_FUNCTION) sbtB_mono, - (SBT_FUNCTION) sbtB_dual, - (SBT_FUNCTION) sbtB_dual_mono, - (SBT_FUNCTION) sbtB_dual_left, - (SBT_FUNCTION) sbtB_dual_right}, - {(SBT_FUNCTION) sbtB16_mono, - (SBT_FUNCTION) sbtB16_dual, - (SBT_FUNCTION) sbtB16_dual_mono, - (SBT_FUNCTION) sbtB16_dual_left, - (SBT_FUNCTION) sbtB16_dual_right}, - {(SBT_FUNCTION) sbtB8_mono, - (SBT_FUNCTION) sbtB8_dual, - (SBT_FUNCTION) sbtB8_dual_mono, - (SBT_FUNCTION) sbtB8_dual_left, - (SBT_FUNCTION) sbtB8_dual_right}}, +static const SBT_FUNCTION sbt_table[2][3][5] = { + {{sbt_mono, sbt_dual, sbt_dual_mono, sbt_dual_left, sbt_dual_right}, + {sbt16_mono, sbt16_dual, sbt16_dual_mono, sbt16_dual_left, sbt16_dual_right}, + {sbt8_mono, sbt8_dual, sbt8_dual_mono, sbt8_dual_left, sbt8_dual_right}}, + {{(SBT_FUNCTION)sbtB_mono, (SBT_FUNCTION)sbtB_dual, (SBT_FUNCTION)sbtB_dual_mono, (SBT_FUNCTION)sbtB_dual_left, (SBT_FUNCTION)sbtB_dual_right}, + {(SBT_FUNCTION)sbtB16_mono, (SBT_FUNCTION)sbtB16_dual, (SBT_FUNCTION)sbtB16_dual_mono, (SBT_FUNCTION)sbtB16_dual_left, (SBT_FUNCTION)sbtB16_dual_right}, + {(SBT_FUNCTION)sbtB8_mono, (SBT_FUNCTION)sbtB8_dual, (SBT_FUNCTION)sbtB8_dual_mono, (SBT_FUNCTION)sbtB8_dual_left, (SBT_FUNCTION)sbtB8_dual_right}}, }; -static const int out_chans[5] = -{1, 2, 1, 1, 1}; +static const int out_chans[5] = {1, 2, 1, 1, 1}; - -int audio_decode_initL1(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); +int audio_decode_initL1(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void sbt_init(); - IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm); IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm); IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm); -static const AUDIO_DECODE_ROUTINE decode_routine_table[4] = -{ - L2audio_decode, - (AUDIO_DECODE_ROUTINE)L3audio_decode, - L2audio_decode, - L1audio_decode,}; +static const AUDIO_DECODE_ROUTINE decode_routine_table[4] = { + L2audio_decode, + (AUDIO_DECODE_ROUTINE)L3audio_decode, + L2audio_decode, + L1audio_decode, +}; /*---------------------------------------------------------*/ -static void table_init() -{ - int i, j; - int code; - static int iOnceOnly=0; - - if (!iOnceOnly++) - { - /*-- c_values (dequant) --*/ - for (i = 1; i < 18; i++) - look_c_value[i] = 2.0F / steps[i]; - - /*-- scale factor table, scale by 32768 for 16 pcm output --*/ - for (i = 0; i < 64; i++) - sf_table[i] = (float) (32768.0 * 2.0 * pow(2.0, -i / 3.0)); - - /*-- grouped 3 level lookup table 5 bit token --*/ - for (i = 0; i < 32; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group3_table[i][j] = (char) ((code % 3) - 1); - code /= 3; - } - } - - /*-- grouped 5 level lookup table 7 bit token --*/ - for (i = 0; i < 128; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group5_table[i][j] = (char) ((code % 5) - 2); - code /= 5; - } - } - - /*-- grouped 9 level lookup table 10 bit token --*/ - for (i = 0; i < 1024; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group9_table[i][j] = (short) ((code % 9) - 4); - code /= 9; - } - } - } +static void table_init() { + int i, j; + int code; + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*-- c_values (dequant) --*/ + for (i = 1; i < 18; i++) + look_c_value[i] = 2.0F / steps[i]; + + /*-- scale factor table, scale by 32768 for 16 pcm output --*/ + for (i = 0; i < 64; i++) + sf_table[i] = (float)(32768.0 * 2.0 * pow(2.0, -i / 3.0)); + + /*-- grouped 3 level lookup table 5 bit token --*/ + for (i = 0; i < 32; i++) { + code = i; + for (j = 0; j < 3; j++) { + group3_table[i][j] = (char)((code % 3) - 1); + code /= 3; + } + } + + /*-- grouped 5 level lookup table 7 bit token --*/ + for (i = 0; i < 128; i++) { + code = i; + for (j = 0; j < 3; j++) { + group5_table[i][j] = (char)((code % 5) - 2); + code /= 5; + } + } + + /*-- grouped 9 level lookup table 10 bit token --*/ + for (i = 0; i < 1024; i++) { + code = i; + for (j = 0; j < 3; j++) { + group9_table[i][j] = (short)((code % 9) - 4); + code /= 9; + } + } + } } /*---------------------------------------------------------*/ -int L1audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); -int L3audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); +int L1audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); +int L3audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pad */ -int audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, j, k; - static int first_pass = 1; - int abcd_index; - long samprate; - int limit; - int bit_code; - - if (first_pass) - { - table_init(); - first_pass = 0; - } - -/* select decoder routine Layer I,II,III */ - audio_decode_routine = decode_routine_table[h->option & 3]; - - - if (h->option == 3) /* layer I */ - return L1audio_decode_init(h, framebytes_arg, - reduction_code, transform_code, convert_code, freq_limit); - - if (h->option == 1) /* layer III */ - return L3audio_decode_init(h, framebytes_arg, - reduction_code, transform_code, convert_code, freq_limit); - - - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - pMP3Stream->framebytes = framebytes_arg; -/* check if code handles */ - if (h->option != 2) - return 0; /* layer II only */ - if (h->sr_index == 3) - return 0; /* reserved */ - -/* compute abcd index for bit allo table selection */ - if (h->id) /* mpeg 1 */ - abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; - else - abcd_index = 4; /* mpeg 2 */ - - if (abcd_index < 0) - return 0; // fail invalid Layer II bit rate index - - for (i = 0; i < 4; i++) - for (j = 0; j < 16; j++) - pMP3Stream->bat[i][j] = look_bat[abcd_index][i][j]; - for (i = 0; i < 4; i++) - pMP3Stream->nbat[i] = look_nbat[abcd_index][i]; - pMP3Stream->max_sb = pMP3Stream->nbat[0] + pMP3Stream->nbat[1] + pMP3Stream->nbat[2] + pMP3Stream->nbat[3]; -/*----- compute pMP3Stream->nsb_limit --------*/ - samprate = sr_table[4 * h->id + h->sr_index]; - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ -/*---- limit = 0.94*(32>>reduction_code); ----*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) - pMP3Stream->nsb_limit = pMP3Stream->max_sb; - - pMP3Stream->outvalues = 1152 >> reduction_code; - if (h->mode != 3) - { /* adjust for 2 channel modes */ - for (i = 0; i < 4; i++) - pMP3Stream->nbat[i] *= 2; - pMP3Stream->max_sb *= 2; - pMP3Stream->nsb_limit *= 2; - } - -/* set sbt function */ - k = 1 + convert_code; - if (h->mode == 3) - { - k = 0; - } - pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; - pMP3Stream->outvalues *= out_chans[k]; - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - decinfo.channels = out_chans[k]; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - - -/* clear sample buffer, unused sub bands must be 0 */ - for (i = 0; i < 2304*2; i++) // the *2 here was inserted by me just in case, since the array is now *2, because of stereo files unpacking at 4608 bytes per frame (which may or may not be relevant, but in any case I don't think we use the L1 versions of MP3 now anyway - sample[i] = 0.0F; - - -/* init sub-band transform */ - sbt_init(); - - return 1; +int audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, j, k; + static int first_pass = 1; + int abcd_index; + long samprate; + int limit; + int bit_code; + + if (first_pass) { + table_init(); + first_pass = 0; + } + + /* select decoder routine Layer I,II,III */ + audio_decode_routine = decode_routine_table[h->option & 3]; + + if (h->option == 3) /* layer I */ + return L1audio_decode_init(h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); + + if (h->option == 1) /* layer III */ + return L3audio_decode_init(h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + pMP3Stream->framebytes = framebytes_arg; + /* check if code handles */ + if (h->option != 2) + return 0; /* layer II only */ + if (h->sr_index == 3) + return 0; /* reserved */ + + /* compute abcd index for bit allo table selection */ + if (h->id) /* mpeg 1 */ + abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; + else + abcd_index = 4; /* mpeg 2 */ + + if (abcd_index < 0) + return 0; // fail invalid Layer II bit rate index + + for (i = 0; i < 4; i++) + for (j = 0; j < 16; j++) + pMP3Stream->bat[i][j] = look_bat[abcd_index][i][j]; + for (i = 0; i < 4; i++) + pMP3Stream->nbat[i] = look_nbat[abcd_index][i]; + pMP3Stream->max_sb = pMP3Stream->nbat[0] + pMP3Stream->nbat[1] + pMP3Stream->nbat[2] + pMP3Stream->nbat[3]; + /*----- compute pMP3Stream->nsb_limit --------*/ + samprate = sr_table[4 * h->id + h->sr_index]; + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + /*---- limit = 0.94*(32>>reduction_code); ----*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) + pMP3Stream->nsb_limit = pMP3Stream->max_sb; + + pMP3Stream->outvalues = 1152 >> reduction_code; + if (h->mode != 3) { /* adjust for 2 channel modes */ + for (i = 0; i < 4; i++) + pMP3Stream->nbat[i] *= 2; + pMP3Stream->max_sb *= 2; + pMP3Stream->nsb_limit *= 2; + } + + /* set sbt function */ + k = 1 + convert_code; + if (h->mode == 3) { + k = 0; + } + pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; + pMP3Stream->outvalues *= out_chans[k]; + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + decinfo.channels = out_chans[k]; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + /* clear sample buffer, unused sub bands must be 0 */ + for (i = 0; i < 2304 * 2; i++) // the *2 here was inserted by me just in case, since the array is now *2, because of stereo files unpacking at 4608 bytes + // per frame (which may or may not be relevant, but in any case I don't think we use the L1 versions of MP3 now anyway + sample[i] = 0.0F; + + /* init sub-band transform */ + sbt_init(); + + return 1; } /*---------------------------------------------------------*/ -void audio_decode_info(DEC_INFO * info) -{ - *info = decinfo; /* info return, call after init */ -} +void audio_decode_info(DEC_INFO *info) { *info = decinfo; /* info return, call after init */ } /*---------------------------------------------------------*/ -void decode_table_init() -{ -/* dummy for asm version compatability */ -} +void decode_table_init() { /* dummy for asm version compatability */ } /*---------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME - +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/cupl1.c b/code/mp3code/cupl1.c index 8d095e22b0..06ebb94568 100644 --- a/code/mp3code/cupl1.c +++ b/code/mp3code/cupl1.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -34,288 +34,270 @@ include to clup.c ******************************************************************/ /*======================================================================*/ -static const int bat_bit_masterL1[] = -{ - 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 -}; +static const int bat_bit_masterL1[] = {0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; ////@@@@static float *pMP3Stream->cs_factorL1 = &pMP3Stream->cs_factor[0]; // !!!!!!!!!!!!!!!! -static float look_c_valueL1[16]; // effectively constant +static float look_c_valueL1[16]; // effectively constant ////@@@@static int nbatL1 = 32; /*======================================================================*/ -static void unpack_baL1() -{ - int j; - int nstereo; - - pMP3Stream->bit_skip = 0; - nstereo = pMP3Stream->stereo_sb; - - for (j = 0; j < pMP3Stream->nbatL1; j++) - { - mac_load_check(4); - ballo[j] = samp_dispatch[j] = mac_load(4); - if (j >= pMP3Stream->nsb_limit) - pMP3Stream->bit_skip += bat_bit_masterL1[samp_dispatch[j]]; - c_value[j] = look_c_valueL1[samp_dispatch[j]]; - if (--nstereo < 0) - { - ballo[j + 1] = ballo[j]; - samp_dispatch[j] += 15; /* flag as joint */ - samp_dispatch[j + 1] = samp_dispatch[j]; /* flag for sf */ - c_value[j + 1] = c_value[j]; - j++; - } - } -/*-- terminate with bit skip and end --*/ - samp_dispatch[pMP3Stream->nsb_limit] = 31; - samp_dispatch[j] = 30; +static void unpack_baL1() { + int j; + int nstereo; + + pMP3Stream->bit_skip = 0; + nstereo = pMP3Stream->stereo_sb; + + for (j = 0; j < pMP3Stream->nbatL1; j++) { + mac_load_check(4); + ballo[j] = samp_dispatch[j] = mac_load(4); + if (j >= pMP3Stream->nsb_limit) + pMP3Stream->bit_skip += bat_bit_masterL1[samp_dispatch[j]]; + c_value[j] = look_c_valueL1[samp_dispatch[j]]; + if (--nstereo < 0) { + ballo[j + 1] = ballo[j]; + samp_dispatch[j] += 15; /* flag as joint */ + samp_dispatch[j + 1] = samp_dispatch[j]; /* flag for sf */ + c_value[j + 1] = c_value[j]; + j++; + } + } + /*-- terminate with bit skip and end --*/ + samp_dispatch[pMP3Stream->nsb_limit] = 31; + samp_dispatch[j] = 30; } /*-------------------------------------------------------------------------*/ -static void unpack_sfL1(void) /* unpack scale factor */ -{ /* combine dequant and scale factors */ - int i; - - for (i = 0; i < pMP3Stream->nbatL1; i++) - { - if (ballo[i]) - { - mac_load_check(6); - pMP3Stream->cs_factorL1[i] = c_value[i] * sf_table[mac_load(6)]; - } - } -/*-- done --*/ +static void unpack_sfL1(void) /* unpack scale factor */ +{ /* combine dequant and scale factors */ + int i; + + for (i = 0; i < pMP3Stream->nbatL1; i++) { + if (ballo[i]) { + mac_load_check(6); + pMP3Stream->cs_factorL1[i] = c_value[i] * sf_table[mac_load(6)]; + } + } + /*-- done --*/ } /*-------------------------------------------------------------------------*/ -#define UNPACKL1_N(n) s[k] = pMP3Stream->cs_factorL1[k]*(load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACKL1J_N(n) tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k] = pMP3Stream->cs_factorL1[k]*tmp; \ - s[k+1] = pMP3Stream->cs_factorL1[k+1]*tmp; \ - k++; \ - goto dispatch; +#define UNPACKL1_N(n) \ + s[k] = pMP3Stream->cs_factorL1[k] * (load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACKL1J_N(n) \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k] = pMP3Stream->cs_factorL1[k] * tmp; \ + s[k + 1] = pMP3Stream->cs_factorL1[k + 1] * tmp; \ + k++; \ + goto dispatch; /*-------------------------------------------------------------------------*/ -static void unpack_sampL1() /* unpack samples */ +static void unpack_sampL1() /* unpack samples */ { - int j, k; - float *s; - long tmp; - - s = sample; - for (j = 0; j < 12; j++) - { - k = -1; - dispatch:switch (samp_dispatch[++k]) - { - case 0: - s[k] = 0.0F; - goto dispatch; - case 1: - UNPACKL1_N(2) /* 3 levels */ - case 2: - UNPACKL1_N(3) /* 7 levels */ - case 3: - UNPACKL1_N(4) /* 15 levels */ - case 4: - UNPACKL1_N(5) /* 31 levels */ - case 5: - UNPACKL1_N(6) /* 63 levels */ - case 6: - UNPACKL1_N(7) /* 127 levels */ - case 7: - UNPACKL1_N(8) /* 255 levels */ - case 8: - UNPACKL1_N(9) /* 511 levels */ - case 9: - UNPACKL1_N(10) /* 1023 levels */ - case 10: - UNPACKL1_N(11) /* 2047 levels */ - case 11: - UNPACKL1_N(12) /* 4095 levels */ - case 12: - UNPACKL1_N(13) /* 8191 levels */ - case 13: - UNPACKL1_N(14) /* 16383 levels */ - case 14: - UNPACKL1_N(15) /* 32767 levels */ -/* -- joint ---- */ - case 15 + 0: - s[k + 1] = s[k] = 0.0F; - k++; /* skip right chan dispatch */ - goto dispatch; -/* -- joint ---- */ - case 15 + 1: - UNPACKL1J_N(2) /* 3 levels */ - case 15 + 2: - UNPACKL1J_N(3) /* 7 levels */ - case 15 + 3: - UNPACKL1J_N(4) /* 15 levels */ - case 15 + 4: - UNPACKL1J_N(5) /* 31 levels */ - case 15 + 5: - UNPACKL1J_N(6) /* 63 levels */ - case 15 + 6: - UNPACKL1J_N(7) /* 127 levels */ - case 15 + 7: - UNPACKL1J_N(8) /* 255 levels */ - case 15 + 8: - UNPACKL1J_N(9) /* 511 levels */ - case 15 + 9: - UNPACKL1J_N(10) /* 1023 levels */ - case 15 + 10: - UNPACKL1J_N(11) /* 2047 levels */ - case 15 + 11: - UNPACKL1J_N(12) /* 4095 levels */ - case 15 + 12: - UNPACKL1J_N(13) /* 8191 levels */ - case 15 + 13: - UNPACKL1J_N(14) /* 16383 levels */ - case 15 + 14: - UNPACKL1J_N(15) /* 32767 levels */ - -/* -- end of dispatch -- */ - case 31: - skip(pMP3Stream->bit_skip); - case 30: - s += 64; - } /* end switch */ - } /* end j loop */ - -/*-- done --*/ + int j, k; + float *s; + long tmp; + + s = sample; + for (j = 0; j < 12; j++) { + k = -1; + dispatch: + switch (samp_dispatch[++k]) { + case 0: + s[k] = 0.0F; + goto dispatch; + case 1: + UNPACKL1_N(2) /* 3 levels */ + case 2: + UNPACKL1_N(3) /* 7 levels */ + case 3: + UNPACKL1_N(4) /* 15 levels */ + case 4: + UNPACKL1_N(5) /* 31 levels */ + case 5: + UNPACKL1_N(6) /* 63 levels */ + case 6: + UNPACKL1_N(7) /* 127 levels */ + case 7: + UNPACKL1_N(8) /* 255 levels */ + case 8: + UNPACKL1_N(9) /* 511 levels */ + case 9: + UNPACKL1_N(10) /* 1023 levels */ + case 10: + UNPACKL1_N(11) /* 2047 levels */ + case 11: + UNPACKL1_N(12) /* 4095 levels */ + case 12: + UNPACKL1_N(13) /* 8191 levels */ + case 13: + UNPACKL1_N(14) /* 16383 levels */ + case 14: + UNPACKL1_N(15) /* 32767 levels */ + /* -- joint ---- */ + case 15 + 0: + s[k + 1] = s[k] = 0.0F; + k++; /* skip right chan dispatch */ + goto dispatch; + /* -- joint ---- */ + case 15 + 1: + UNPACKL1J_N(2) /* 3 levels */ + case 15 + 2: + UNPACKL1J_N(3) /* 7 levels */ + case 15 + 3: + UNPACKL1J_N(4) /* 15 levels */ + case 15 + 4: + UNPACKL1J_N(5) /* 31 levels */ + case 15 + 5: + UNPACKL1J_N(6) /* 63 levels */ + case 15 + 6: + UNPACKL1J_N(7) /* 127 levels */ + case 15 + 7: + UNPACKL1J_N(8) /* 255 levels */ + case 15 + 8: + UNPACKL1J_N(9) /* 511 levels */ + case 15 + 9: + UNPACKL1J_N(10) /* 1023 levels */ + case 15 + 10: + UNPACKL1J_N(11) /* 2047 levels */ + case 15 + 11: + UNPACKL1J_N(12) /* 4095 levels */ + case 15 + 12: + UNPACKL1J_N(13) /* 8191 levels */ + case 15 + 13: + UNPACKL1J_N(14) /* 16383 levels */ + case 15 + 14: + UNPACKL1J_N(15) /* 32767 levels */ + + /* -- end of dispatch -- */ + case 31: + skip(pMP3Stream->bit_skip); + case 30: + s += 64; + } /* end switch */ + } /* end j loop */ + + /*-- done --*/ } /*-------------------------------------------------------------------*/ -IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm) -{ - int sync, prot; - IN_OUT in_out; - - load_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = load(12); - if (sync != 0xFFF) - return in_out; /* sync fail */ - - - load(3); /* skip id and option (checked by init) */ - prot = load(1); /* load prot bit */ - load(6); /* skip to pad */ - pMP3Stream->pad = (load(1)) << 2; - load(1); /* skip to mode */ - pMP3Stream->stereo_sb = look_joint[load(4)]; - if (prot) - load(4); /* skip to data */ - else - load(20); /* skip crc */ - - unpack_baL1(); /* unpack bit allocation */ - unpack_sfL1(); /* unpack scale factor */ - unpack_sampL1(); /* unpack samples */ - - pMP3Stream->sbt(sample, pcm, 12); -/*-----------*/ - in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.out_bytes = pMP3Stream->outbytes; - - return in_out; +IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm) { + int sync, prot; + IN_OUT in_out; + + load_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = load(12); + if (sync != 0xFFF) + return in_out; /* sync fail */ + + load(3); /* skip id and option (checked by init) */ + prot = load(1); /* load prot bit */ + load(6); /* skip to pad */ + pMP3Stream->pad = (load(1)) << 2; + load(1); /* skip to mode */ + pMP3Stream->stereo_sb = look_joint[load(4)]; + if (prot) + load(4); /* skip to data */ + else + load(20); /* skip crc */ + + unpack_baL1(); /* unpack bit allocation */ + unpack_sfL1(); /* unpack scale factor */ + unpack_sampL1(); /* unpack samples */ + + pMP3Stream->sbt(sample, pcm, 12); + /*-----------*/ + in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.out_bytes = pMP3Stream->outbytes; + + return in_out; } /*-------------------------------------------------------------------------*/ -int L1audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, k; - static int first_pass = 1; - long samprate; - int limit; - long step; - int bit_code; - -/*--- sf init done by layer II init ---*/ - if (first_pass) - { - for (step = 4, i = 1; i < 16; i++, step <<= 1) - look_c_valueL1[i] = (float) (2.0 / (step - 1)); - first_pass = 0; - } - pMP3Stream->cs_factorL1 = pMP3Stream->cs_factor[0]; - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - pMP3Stream->framebytes = framebytes_arg; -/* check if code handles */ - if (h->option != 3) - return 0; /* layer I only */ - - pMP3Stream->nbatL1 = 32; - pMP3Stream->max_sb = pMP3Stream->nbatL1; -/*----- compute pMP3Stream->nsb_limit --------*/ - samprate = sr_table[4 * h->id + h->sr_index]; - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ -/*---- limit = 0.94*(32>>reduction_code); ----*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) - pMP3Stream->nsb_limit = pMP3Stream->max_sb; - - pMP3Stream->outvalues = 384 >> reduction_code; - if (h->mode != 3) - { /* adjust for 2 channel modes */ - pMP3Stream->nbatL1 *= 2; - pMP3Stream->max_sb *= 2; - pMP3Stream->nsb_limit *= 2; - } - -/* set sbt function */ - k = 1 + convert_code; - if (h->mode == 3) - { - k = 0; - } - pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; - pMP3Stream->outvalues *= out_chans[k]; - - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - decinfo.channels = out_chans[k]; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - -/* clear sample buffer, unused sub bands must be 0 */ - for (i = 0; i < 768; i++) - sample[i] = 0.0F; - - -/* init sub-band transform */ - sbt_init(); - - return 1; +int L1audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, k; + static int first_pass = 1; + long samprate; + int limit; + long step; + int bit_code; + + /*--- sf init done by layer II init ---*/ + if (first_pass) { + for (step = 4, i = 1; i < 16; i++, step <<= 1) + look_c_valueL1[i] = (float)(2.0 / (step - 1)); + first_pass = 0; + } + pMP3Stream->cs_factorL1 = pMP3Stream->cs_factor[0]; + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + pMP3Stream->framebytes = framebytes_arg; + /* check if code handles */ + if (h->option != 3) + return 0; /* layer I only */ + + pMP3Stream->nbatL1 = 32; + pMP3Stream->max_sb = pMP3Stream->nbatL1; + /*----- compute pMP3Stream->nsb_limit --------*/ + samprate = sr_table[4 * h->id + h->sr_index]; + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + /*---- limit = 0.94*(32>>reduction_code); ----*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) + pMP3Stream->nsb_limit = pMP3Stream->max_sb; + + pMP3Stream->outvalues = 384 >> reduction_code; + if (h->mode != 3) { /* adjust for 2 channel modes */ + pMP3Stream->nbatL1 *= 2; + pMP3Stream->max_sb *= 2; + pMP3Stream->nsb_limit *= 2; + } + + /* set sbt function */ + k = 1 + convert_code; + if (h->mode == 3) { + k = 0; + } + pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; + pMP3Stream->outvalues *= out_chans[k]; + + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + decinfo.channels = out_chans[k]; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + /* clear sample buffer, unused sub bands must be 0 */ + for (i = 0; i < 768; i++) + sample[i] = 0.0F; + + /* init sub-band transform */ + sbt_init(); + + return 1; } /*---------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/cupl3.c b/code/mp3code/cupl3.c index d3562f9eb4..30d04100f5 100644 --- a/code/mp3code/cupl3.c +++ b/code/mp3code/cupl3.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -53,22 +53,20 @@ TO DO: Test mixed blocks (mixed long/short) #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ #include "l3.h" #include "jdw.h" #include "mp3struct.h" #if !defined(min) -# define min(a, b) ((a) < (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) #endif /*====================================================================*/ -static const int mp_sr20_table[2][4] = -{{441, 480, 320, -999}, {882, 960, 640, -999}}; -static const int mp_br_tableL3[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ - {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; +static const int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; +static const int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ + {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; /*====================================================================*/ @@ -80,12 +78,12 @@ static const int mp_br_tableL3[2][16] = /*====================================================================*/ /*----------------*/ -extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then chucked. +extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then chucked. /*----------------*/ ////@@@@static int pMP3Stream->mpeg25_flag; // L3 only -//int iframe; +// int iframe; /*-------*/ ////@@@@static int pMP3Stream->band_limit = (576); // L3 only @@ -105,18 +103,18 @@ extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then ////@@@@static int pMP3Stream->half_outbytes; // L3 only ////@@@@static int pMP3Stream->framebytes; // -//static int padframebytes; +// static int padframebytes; ////@@@@static int pMP3Stream->crcbytes; // L3 only ////@@@@static int pMP3Stream->pad; // -//static int stereo_flag; // only written to +// static int stereo_flag; // only written to ////@@@@static int pMP3Stream->nchan; // L3 only ////@@@@static int pMP3Stream->ms_mode; // L3 only (99%) ////@@@@static int pMP3Stream->is_mode; // L3 only ////@@@@static unsigned int pMP3Stream->zero_level_pcm = 0; // L3 only /* cb_info[igr][ch], compute by dequant, used by joint */ -static CB_INFO cb_info[2][2]; // L3 only ############ I think this is ok, only a scratchpad? -static IS_SF_INFO is_sf_info; /* MPEG-2 intensity stereo */ // L3 only ############## scratchpad? +static CB_INFO cb_info[2][2]; // L3 only ############ I think this is ok, only a scratchpad? +static IS_SF_INFO is_sf_info; /* MPEG-2 intensity stereo */ // L3 only ############## scratchpad? /*---------------------------------*/ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -130,17 +128,17 @@ static int buf_ptr1 = 0; // !!!!!!!!!!! static int main_pos_bit; */ /*---------------------------------*/ -static SIDE_INFO side_info; // ####### scratchpad? +static SIDE_INFO side_info; // ####### scratchpad? -static SCALEFACT sf[2][2]; /* [gr][ch] */ // ########## scratchpad? +static SCALEFACT sf[2][2]; /* [gr][ch] */ // ########## scratchpad? -static int nsamp[2][2]; /* must start = 0, for nsamp[igr_prev] */ // ########## scratchpad? +static int nsamp[2][2]; /* must start = 0, for nsamp[igr_prev] */ // ########## scratchpad? /*- sample union of int/float sample[ch][gr][576] */ /* static SAMPLE sample[2][2][576]; */ // @@@@FINDME ////@@@@extern SAMPLE sample[2][2][576]; ////////////????? suspicious, mainly used in decode loop, but zeroed init code -static float yout[576]; /* hybrid out, sbt in */ //////////// scratchpad +static float yout[576]; /* hybrid out, sbt in */ //////////// scratchpad ////@@@@typedef void (*SBT_FUNCTION) (float *sample, short *pcm, int ch); void sbt_dual_L3(float *sample, short *pcm, int n); @@ -155,906 +153,696 @@ IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm); ////@@@@typedef IN_OUT(*DECODE_FUNCTION) (unsigned char *bs, unsigned char *pcm); ////@@@@static DECODE_FUNCTION decode_function = L3audio_decode_MPEG1; <------------------ needs streaming, ditto above!!! - /*====================================================================*/ -int hybrid(void *xin, void *xprev, float *y, - int btype, int nlong, int ntot, int nprev); -int hybrid_sum(void *xin, void *xin_left, float *y, - int btype, int nlong, int ntot); +int hybrid(void *xin, void *xprev, float *y, int btype, int nlong, int ntot, int nprev); +int hybrid_sum(void *xin, void *xin_left, float *y, int btype, int nlong, int ntot); void sum_f_bands(void *a, void *b, int n); void FreqInvert(float *y, int n); void antialias(void *x, int n); -void ms_process(void *x, int n); /* sum-difference stereo */ -void is_process_MPEG1(void *x, /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - int nsamp, int ms_mode); -void is_process_MPEG2(void *x, /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - IS_SF_INFO * is_sf_info, - int nsamp, int ms_mode); +void ms_process(void *x, int n); /* sum-difference stereo */ +void is_process_MPEG1(void *x, /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + int nsamp, int ms_mode); +void is_process_MPEG2(void *x, /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + IS_SF_INFO *is_sf_info, int nsamp, int ms_mode); void unpack_huff(void *xy, int n, int ntable); int unpack_huff_quad(void *vwxy, int n, int nbits, int ntable); -void dequant(SAMPLE sample[], int *nsamp, - SCALEFACT * sf, - GR * gr, - CB_INFO * cb_info, int ncbl_mixed); -void unpack_sf_sub_MPEG1(SCALEFACT * scalefac, GR * gr, - int scfsi, /* bit flag */ - int igr); -void unpack_sf_sub_MPEG2(SCALEFACT sf[], /* return intensity scale */ - GR * grdat, - int is_and_ch, IS_SF_INFO * is_sf_info); +void dequant(SAMPLE sample[], int *nsamp, SCALEFACT *sf, GR *gr, CB_INFO *cb_info, int ncbl_mixed); +void unpack_sf_sub_MPEG1(SCALEFACT *scalefac, GR *gr, int scfsi, /* bit flag */ + int igr); +void unpack_sf_sub_MPEG2(SCALEFACT sf[], /* return intensity scale */ + GR *grdat, int is_and_ch, IS_SF_INFO *is_sf_info); /*====================================================================*/ /* get bits from bitstream in endian independent way */ -BITDAT bitdat; /* global for inline use by Huff */ // !!!!!!!!!!!!!!!!!!! +BITDAT bitdat; /* global for inline use by Huff */ // !!!!!!!!!!!!!!!!!!! /*------------- initialize bit getter -------------*/ -static void bitget_init(unsigned char *buf) -{ - bitdat.bs_ptr0 = bitdat.bs_ptr = buf; - bitdat.bits = 0; - bitdat.bitbuf = 0; +static void bitget_init(unsigned char *buf) { + bitdat.bs_ptr0 = bitdat.bs_ptr = buf; + bitdat.bits = 0; + bitdat.bitbuf = 0; } /*------------- initialize bit getter -------------*/ -static void bitget_init_end(unsigned char *buf_end) -{ - bitdat.bs_ptr_end = buf_end; -} +static void bitget_init_end(unsigned char *buf_end) { bitdat.bs_ptr_end = buf_end; } /*------------- get n bits from bitstream -------------*/ -int bitget_bits_used() -{ - int n; /* compute bits used from last init call */ +int bitget_bits_used() { + int n; /* compute bits used from last init call */ - n = ((bitdat.bs_ptr - bitdat.bs_ptr0) << 3) - bitdat.bits; - return n; + n = ((bitdat.bs_ptr - bitdat.bs_ptr0) << 3) - bitdat.bits; + return n; } /*------------- check for n bits in bitbuf -------------*/ -void bitget_check(int n) -{ - if (bitdat.bits < n) - { - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } +void bitget_check(int n) { + if (bitdat.bits < n) { + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } } /*------------- get n bits from bitstream -------------*/ -unsigned int bitget(int n) -{ - unsigned int x; - - if (bitdat.bits < n) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits -= n; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +unsigned int bitget(int n) { + unsigned int x; + + if (bitdat.bits < n) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits -= n; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } /*------------- get 1 bit from bitstream -------------*/ -unsigned int bitget_1bit() -{ - unsigned int x; - - if (bitdat.bits <= 0) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits--; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +unsigned int bitget_1bit() { + unsigned int x; + + if (bitdat.bits <= 0) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits--; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } /*====================================================================*/ -static void Xform_mono(void *pcm, int igr) -{ - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - n1 = n2 = nsamp[igr][0]; /* total number bands */ - if (side_info.gr[igr][0].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][0].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - igr_prev = igr ^ 1; - - nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); - FreqInvert(yout, nsamp[igr][0]); - pMP3Stream->sbt_L3(yout, pcm, 0); - +static void Xform_mono(void *pcm, int igr) { + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + n1 = n2 = nsamp[igr][0]; /* total number bands */ + if (side_info.gr[igr][0].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][0].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + igr_prev = igr ^ 1; + + nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + FreqInvert(yout, nsamp[igr][0]); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ -static void Xform_dual_right(void *pcm, int igr) -{ - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - n1 = n2 = nsamp[igr][1]; /* total number bands */ - if (side_info.gr[igr][1].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][1].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - igr_prev = igr ^ 1; - nsamp[igr][1] = hybrid(pMP3Stream->sample[1][igr], pMP3Stream->sample[1][igr_prev], - yout, side_info.gr[igr][1].block_type, n1, n2, nsamp[igr_prev][1]); - FreqInvert(yout, nsamp[igr][1]); - pMP3Stream->sbt_L3(yout, pcm, 0); - +static void Xform_dual_right(void *pcm, int igr) { + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + n1 = n2 = nsamp[igr][1]; /* total number bands */ + if (side_info.gr[igr][1].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][1].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + igr_prev = igr ^ 1; + nsamp[igr][1] = hybrid(pMP3Stream->sample[1][igr], pMP3Stream->sample[1][igr_prev], yout, side_info.gr[igr][1].block_type, n1, n2, nsamp[igr_prev][1]); + FreqInvert(yout, nsamp[igr][1]); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ -static void Xform_dual(void *pcm, int igr) -{ - int ch; - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - igr_prev = igr ^ 1; - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - n1 = n2 = nsamp[igr][ch]; /* total number bands */ - if (side_info.gr[igr][ch].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][ch].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - nsamp[igr][ch] = hybrid(pMP3Stream->sample[ch][igr], pMP3Stream->sample[ch][igr_prev], - yout, side_info.gr[igr][ch].block_type, n1, n2, nsamp[igr_prev][ch]); - FreqInvert(yout, nsamp[igr][ch]); - pMP3Stream->sbt_L3(yout, pcm, ch); - } - +static void Xform_dual(void *pcm, int igr) { + int ch; + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + igr_prev = igr ^ 1; + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + n1 = n2 = nsamp[igr][ch]; /* total number bands */ + if (side_info.gr[igr][ch].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][ch].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + nsamp[igr][ch] = + hybrid(pMP3Stream->sample[ch][igr], pMP3Stream->sample[ch][igr_prev], yout, side_info.gr[igr][ch].block_type, n1, n2, nsamp[igr_prev][ch]); + FreqInvert(yout, nsamp[igr][ch]); + pMP3Stream->sbt_L3(yout, pcm, ch); + } } /*--------------------------------------------------------------------*/ -static void Xform_dual_mono(void *pcm, int igr) -{ - int igr_prev, n1, n2, n3; - -/*--- hybrid + sbt ---*/ - igr_prev = igr ^ 1; - if ((side_info.gr[igr][0].block_type == side_info.gr[igr][1].block_type) - && (side_info.gr[igr][0].mixed_block_flag == 0) - && (side_info.gr[igr][1].mixed_block_flag == 0)) - { - - n2 = nsamp[igr][0]; /* total number bands max of L R */ - if (n2 < nsamp[igr][1]) - n2 = nsamp[igr][1]; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - n1 = n2; /* n1 = number long bands */ - if (side_info.gr[igr][0].block_type == 2) - n1 = 0; - sum_f_bands(pMP3Stream->sample[0][igr], pMP3Stream->sample[1][igr], n2); - n3 = nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); - } - else - { /* transform and then sum (not tested - never happens in test) */ -/*-- left chan --*/ - n1 = n2 = nsamp[igr][0]; /* total number bands */ - if (side_info.gr[igr][0].block_type == 2) - { - n1 = 0; /* long bands */ - if (side_info.gr[igr][0].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - n3 = nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); -/*-- right chan --*/ - n1 = n2 = nsamp[igr][1]; /* total number bands */ - if (side_info.gr[igr][1].block_type == 2) - { - n1 = 0; /* long bands */ - if (side_info.gr[igr][1].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - nsamp[igr][1] = hybrid_sum(pMP3Stream->sample[1][igr], pMP3Stream->sample[0][igr], - yout, side_info.gr[igr][1].block_type, n1, n2); - if (n3 < nsamp[igr][1]) - n1 = nsamp[igr][1]; - } - -/*--------*/ - FreqInvert(yout, n3); - pMP3Stream->sbt_L3(yout, pcm, 0); +static void Xform_dual_mono(void *pcm, int igr) { + int igr_prev, n1, n2, n3; + + /*--- hybrid + sbt ---*/ + igr_prev = igr ^ 1; + if ((side_info.gr[igr][0].block_type == side_info.gr[igr][1].block_type) && (side_info.gr[igr][0].mixed_block_flag == 0) && + (side_info.gr[igr][1].mixed_block_flag == 0)) { + + n2 = nsamp[igr][0]; /* total number bands max of L R */ + if (n2 < nsamp[igr][1]) + n2 = nsamp[igr][1]; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + n1 = n2; /* n1 = number long bands */ + if (side_info.gr[igr][0].block_type == 2) + n1 = 0; + sum_f_bands(pMP3Stream->sample[0][igr], pMP3Stream->sample[1][igr], n2); + n3 = nsamp[igr][0] = + hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + } else { /* transform and then sum (not tested - never happens in test) */ + /*-- left chan --*/ + n1 = n2 = nsamp[igr][0]; /* total number bands */ + if (side_info.gr[igr][0].block_type == 2) { + n1 = 0; /* long bands */ + if (side_info.gr[igr][0].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + n3 = nsamp[igr][0] = + hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + /*-- right chan --*/ + n1 = n2 = nsamp[igr][1]; /* total number bands */ + if (side_info.gr[igr][1].block_type == 2) { + n1 = 0; /* long bands */ + if (side_info.gr[igr][1].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + nsamp[igr][1] = hybrid_sum(pMP3Stream->sample[1][igr], pMP3Stream->sample[0][igr], yout, side_info.gr[igr][1].block_type, n1, n2); + if (n3 < nsamp[igr][1]) + n1 = nsamp[igr][1]; + } + /*--------*/ + FreqInvert(yout, n3); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ /*====================================================================*/ -static int unpack_side_MPEG1() -{ - int prot; - int br_index; - int igr, ch; - int side_bytes; - -/* decode partial header plus initial side info */ -/* at entry bit getter points at id, sync skipped by caller */ - - pMP3Stream->id = bitget(1); /* id */ - bitget(2); /* skip layer */ - prot = bitget(1); /* bitget prot bit */ - br_index = bitget(4); - pMP3Stream->sr_index = bitget(2); - pMP3Stream->pad = bitget(1); - bitget(1); /* skip to mode */ - side_info.mode = bitget(2); /* mode */ - side_info.mode_ext = bitget(2); /* mode ext */ - - if (side_info.mode != 1) - side_info.mode_ext = 0; - -/* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ - pMP3Stream->ms_mode = side_info.mode_ext >> 1; - pMP3Stream->is_mode = side_info.mode_ext & 1; - - - pMP3Stream->crcbytes = 0; - if (prot) - bitget(4); /* skip to data */ - else - { - bitget(20); /* skip crc */ - pMP3Stream->crcbytes = 2; - } - - if (br_index > 0) /* pMP3Stream->framebytes fixed for free format */ +static int unpack_side_MPEG1() { + int prot; + int br_index; + int igr, ch; + int side_bytes; + + /* decode partial header plus initial side info */ + /* at entry bit getter points at id, sync skipped by caller */ + + pMP3Stream->id = bitget(1); /* id */ + bitget(2); /* skip layer */ + prot = bitget(1); /* bitget prot bit */ + br_index = bitget(4); + pMP3Stream->sr_index = bitget(2); + pMP3Stream->pad = bitget(1); + bitget(1); /* skip to mode */ + side_info.mode = bitget(2); /* mode */ + side_info.mode_ext = bitget(2); /* mode ext */ + + if (side_info.mode != 1) + side_info.mode_ext = 0; + + /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ + pMP3Stream->ms_mode = side_info.mode_ext >> 1; + pMP3Stream->is_mode = side_info.mode_ext & 1; + + pMP3Stream->crcbytes = 0; + if (prot) + bitget(4); /* skip to data */ + else { + bitget(20); /* skip crc */ + pMP3Stream->crcbytes = 2; + } + + if (br_index > 0) /* pMP3Stream->framebytes fixed for free format */ { - pMP3Stream->framebytes = - 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - } - - side_info.main_data_begin = bitget(9); - if (side_info.mode == 3) - { - side_info.private_bits = bitget(5); - pMP3Stream->nchan = 1; -// stereo_flag = 0; - side_bytes = (4 + 17); -/*-- with header --*/ - } - else - { - side_info.private_bits = bitget(3); - pMP3Stream->nchan = 2; -// stereo_flag = 1; - side_bytes = (4 + 32); -/*-- with header --*/ - } - for (ch = 0; ch < pMP3Stream->nchan; ch++) - side_info.scfsi[ch] = bitget(4); -/* this always 0 (both igr) for short blocks */ - - for (igr = 0; igr < 2; igr++) - { - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - side_info.gr[igr][ch].part2_3_length = bitget(12); - side_info.gr[igr][ch].big_values = bitget(9); - side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; - if (pMP3Stream->ms_mode) - side_info.gr[igr][ch].global_gain -= 2; - side_info.gr[igr][ch].scalefac_compress = bitget(4); - side_info.gr[igr][ch].window_switching_flag = bitget(1); - if (side_info.gr[igr][ch].window_switching_flag) - { - side_info.gr[igr][ch].block_type = bitget(2); - side_info.gr[igr][ch].mixed_block_flag = bitget(1); - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].subblock_gain[0] = bitget(3); - side_info.gr[igr][ch].subblock_gain[1] = bitget(3); - side_info.gr[igr][ch].subblock_gain[2] = bitget(3); - /* region count set in terms of long block cb's/bands */ - /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ - /* if(window_switching_flag) always 36 samples in region0 */ - side_info.gr[igr][ch].region0_count = (8 - 1); /* 36 samples */ - side_info.gr[igr][ch].region1_count = 20 - (8 - 1); - } - else - { - side_info.gr[igr][ch].mixed_block_flag = 0; - side_info.gr[igr][ch].block_type = 0; - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].table_select[2] = bitget(5); - side_info.gr[igr][ch].region0_count = bitget(4); - side_info.gr[igr][ch].region1_count = bitget(3); - } - side_info.gr[igr][ch].preflag = bitget(1); - side_info.gr[igr][ch].scalefac_scale = bitget(1); - side_info.gr[igr][ch].count1table_select = bitget(1); - } - } - - - -/* return bytes in header + side info */ - return side_bytes; + pMP3Stream->framebytes = 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + } + + side_info.main_data_begin = bitget(9); + if (side_info.mode == 3) { + side_info.private_bits = bitget(5); + pMP3Stream->nchan = 1; + // stereo_flag = 0; + side_bytes = (4 + 17); + /*-- with header --*/ + } else { + side_info.private_bits = bitget(3); + pMP3Stream->nchan = 2; + // stereo_flag = 1; + side_bytes = (4 + 32); + /*-- with header --*/ + } + for (ch = 0; ch < pMP3Stream->nchan; ch++) + side_info.scfsi[ch] = bitget(4); + /* this always 0 (both igr) for short blocks */ + + for (igr = 0; igr < 2; igr++) { + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + side_info.gr[igr][ch].part2_3_length = bitget(12); + side_info.gr[igr][ch].big_values = bitget(9); + side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; + if (pMP3Stream->ms_mode) + side_info.gr[igr][ch].global_gain -= 2; + side_info.gr[igr][ch].scalefac_compress = bitget(4); + side_info.gr[igr][ch].window_switching_flag = bitget(1); + if (side_info.gr[igr][ch].window_switching_flag) { + side_info.gr[igr][ch].block_type = bitget(2); + side_info.gr[igr][ch].mixed_block_flag = bitget(1); + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].subblock_gain[0] = bitget(3); + side_info.gr[igr][ch].subblock_gain[1] = bitget(3); + side_info.gr[igr][ch].subblock_gain[2] = bitget(3); + /* region count set in terms of long block cb's/bands */ + /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ + /* if(window_switching_flag) always 36 samples in region0 */ + side_info.gr[igr][ch].region0_count = (8 - 1); /* 36 samples */ + side_info.gr[igr][ch].region1_count = 20 - (8 - 1); + } else { + side_info.gr[igr][ch].mixed_block_flag = 0; + side_info.gr[igr][ch].block_type = 0; + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].table_select[2] = bitget(5); + side_info.gr[igr][ch].region0_count = bitget(4); + side_info.gr[igr][ch].region1_count = bitget(3); + } + side_info.gr[igr][ch].preflag = bitget(1); + side_info.gr[igr][ch].scalefac_scale = bitget(1); + side_info.gr[igr][ch].count1table_select = bitget(1); + } + } + + /* return bytes in header + side info */ + return side_bytes; } /*====================================================================*/ -static int unpack_side_MPEG2(int igr) -{ - int prot; - int br_index; - int ch; - int side_bytes; - -/* decode partial header plus initial side info */ -/* at entry bit getter points at id, sync skipped by caller */ - - pMP3Stream->id = bitget(1); /* id */ - bitget(2); /* skip layer */ - prot = bitget(1); /* bitget prot bit */ - br_index = bitget(4); - pMP3Stream->sr_index = bitget(2); - pMP3Stream->pad = bitget(1); - bitget(1); /* skip to mode */ - side_info.mode = bitget(2); /* mode */ - side_info.mode_ext = bitget(2); /* mode ext */ - - if (side_info.mode != 1) - side_info.mode_ext = 0; - -/* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ - pMP3Stream->ms_mode = side_info.mode_ext >> 1; - pMP3Stream->is_mode = side_info.mode_ext & 1; - - pMP3Stream->crcbytes = 0; - if (prot) - bitget(4); /* skip to data */ - else - { - bitget(20); /* skip crc */ - pMP3Stream->crcbytes = 2; - } - - if (br_index > 0) - { /* pMP3Stream->framebytes fixed for free format */ - if (pMP3Stream->mpeg25_flag == 0) - { - pMP3Stream->framebytes = - 1440 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - } - else - { - pMP3Stream->framebytes = - 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - //if( pMP3Stream->sr_index == 2 ) return 0; // fail mpeg25 8khz - } - } - side_info.main_data_begin = bitget(8); - if (side_info.mode == 3) - { - side_info.private_bits = bitget(1); - pMP3Stream->nchan = 1; -// stereo_flag = 0; - side_bytes = (4 + 9); -/*-- with header --*/ - } - else - { - side_info.private_bits = bitget(2); - pMP3Stream->nchan = 2; -// stereo_flag = 1; - side_bytes = (4 + 17); -/*-- with header --*/ - } - side_info.scfsi[1] = side_info.scfsi[0] = 0; - - - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - side_info.gr[igr][ch].part2_3_length = bitget(12); - side_info.gr[igr][ch].big_values = bitget(9); - side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; - if (pMP3Stream->ms_mode) - side_info.gr[igr][ch].global_gain -= 2; - side_info.gr[igr][ch].scalefac_compress = bitget(9); - side_info.gr[igr][ch].window_switching_flag = bitget(1); - if (side_info.gr[igr][ch].window_switching_flag) - { - side_info.gr[igr][ch].block_type = bitget(2); - side_info.gr[igr][ch].mixed_block_flag = bitget(1); - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].subblock_gain[0] = bitget(3); - side_info.gr[igr][ch].subblock_gain[1] = bitget(3); - side_info.gr[igr][ch].subblock_gain[2] = bitget(3); - /* region count set in terms of long block cb's/bands */ - /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ - /* bt=1 or 3 54 samples */ - /* bt=2 mixed=0 36 samples */ - /* bt=2 mixed=1 54 (8 long sf) samples? or maybe 36 */ - /* region0 discussion says 54 but this would mix long */ - /* and short in region0 if scale factors switch */ - /* at band 36 (6 long scale factors) */ - if (side_info.gr[igr][ch].block_type == 2) - { - side_info.gr[igr][ch].region0_count = (6 - 1); /* 36 samples */ - side_info.gr[igr][ch].region1_count = 20 - (6 - 1); - } - else - { /* long block type 1 or 3 */ - side_info.gr[igr][ch].region0_count = (8 - 1); /* 54 samples */ - side_info.gr[igr][ch].region1_count = 20 - (8 - 1); - } - } - else - { - side_info.gr[igr][ch].mixed_block_flag = 0; - side_info.gr[igr][ch].block_type = 0; - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].table_select[2] = bitget(5); - side_info.gr[igr][ch].region0_count = bitget(4); - side_info.gr[igr][ch].region1_count = bitget(3); - } - side_info.gr[igr][ch].preflag = 0; - side_info.gr[igr][ch].scalefac_scale = bitget(1); - side_info.gr[igr][ch].count1table_select = bitget(1); - } - -/* return bytes in header + side info */ - return side_bytes; +static int unpack_side_MPEG2(int igr) { + int prot; + int br_index; + int ch; + int side_bytes; + + /* decode partial header plus initial side info */ + /* at entry bit getter points at id, sync skipped by caller */ + + pMP3Stream->id = bitget(1); /* id */ + bitget(2); /* skip layer */ + prot = bitget(1); /* bitget prot bit */ + br_index = bitget(4); + pMP3Stream->sr_index = bitget(2); + pMP3Stream->pad = bitget(1); + bitget(1); /* skip to mode */ + side_info.mode = bitget(2); /* mode */ + side_info.mode_ext = bitget(2); /* mode ext */ + + if (side_info.mode != 1) + side_info.mode_ext = 0; + + /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ + pMP3Stream->ms_mode = side_info.mode_ext >> 1; + pMP3Stream->is_mode = side_info.mode_ext & 1; + + pMP3Stream->crcbytes = 0; + if (prot) + bitget(4); /* skip to data */ + else { + bitget(20); /* skip crc */ + pMP3Stream->crcbytes = 2; + } + + if (br_index > 0) { /* pMP3Stream->framebytes fixed for free format */ + if (pMP3Stream->mpeg25_flag == 0) { + pMP3Stream->framebytes = 1440 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + } else { + pMP3Stream->framebytes = 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + // if( pMP3Stream->sr_index == 2 ) return 0; // fail mpeg25 8khz + } + } + side_info.main_data_begin = bitget(8); + if (side_info.mode == 3) { + side_info.private_bits = bitget(1); + pMP3Stream->nchan = 1; + // stereo_flag = 0; + side_bytes = (4 + 9); + /*-- with header --*/ + } else { + side_info.private_bits = bitget(2); + pMP3Stream->nchan = 2; + // stereo_flag = 1; + side_bytes = (4 + 17); + /*-- with header --*/ + } + side_info.scfsi[1] = side_info.scfsi[0] = 0; + + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + side_info.gr[igr][ch].part2_3_length = bitget(12); + side_info.gr[igr][ch].big_values = bitget(9); + side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; + if (pMP3Stream->ms_mode) + side_info.gr[igr][ch].global_gain -= 2; + side_info.gr[igr][ch].scalefac_compress = bitget(9); + side_info.gr[igr][ch].window_switching_flag = bitget(1); + if (side_info.gr[igr][ch].window_switching_flag) { + side_info.gr[igr][ch].block_type = bitget(2); + side_info.gr[igr][ch].mixed_block_flag = bitget(1); + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].subblock_gain[0] = bitget(3); + side_info.gr[igr][ch].subblock_gain[1] = bitget(3); + side_info.gr[igr][ch].subblock_gain[2] = bitget(3); + /* region count set in terms of long block cb's/bands */ + /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ + /* bt=1 or 3 54 samples */ + /* bt=2 mixed=0 36 samples */ + /* bt=2 mixed=1 54 (8 long sf) samples? or maybe 36 */ + /* region0 discussion says 54 but this would mix long */ + /* and short in region0 if scale factors switch */ + /* at band 36 (6 long scale factors) */ + if (side_info.gr[igr][ch].block_type == 2) { + side_info.gr[igr][ch].region0_count = (6 - 1); /* 36 samples */ + side_info.gr[igr][ch].region1_count = 20 - (6 - 1); + } else { /* long block type 1 or 3 */ + side_info.gr[igr][ch].region0_count = (8 - 1); /* 54 samples */ + side_info.gr[igr][ch].region1_count = 20 - (8 - 1); + } + } else { + side_info.gr[igr][ch].mixed_block_flag = 0; + side_info.gr[igr][ch].block_type = 0; + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].table_select[2] = bitget(5); + side_info.gr[igr][ch].region0_count = bitget(4); + side_info.gr[igr][ch].region1_count = bitget(3); + } + side_info.gr[igr][ch].preflag = 0; + side_info.gr[igr][ch].scalefac_scale = bitget(1); + side_info.gr[igr][ch].count1table_select = bitget(1); + } + + /* return bytes in header + side info */ + return side_bytes; } /*-----------------------------------------------------------------*/ -static void unpack_main(unsigned char *pcm, int igr) -{ - int ch; - int bit0; - int n1, n2, n3, n4, nn2, nn3; - int nn4; - int qbits; - int m0; - - - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - bitget_init(pMP3Stream->buf + (pMP3Stream->main_pos_bit >> 3)); - bit0 = (pMP3Stream->main_pos_bit & 7); - if (bit0) - bitget(bit0); - pMP3Stream->main_pos_bit += side_info.gr[igr][ch].part2_3_length; - bitget_init_end(pMP3Stream->buf + ((pMP3Stream->main_pos_bit + 39) >> 3)); -/*-- scale factors --*/ - if (pMP3Stream->id) - unpack_sf_sub_MPEG1(&sf[igr][ch], - &side_info.gr[igr][ch], side_info.scfsi[ch], igr); - else - unpack_sf_sub_MPEG2(&sf[igr][ch], - &side_info.gr[igr][ch], pMP3Stream->is_mode & ch, &is_sf_info); -/*--- huff data ---*/ - n1 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count]; - n2 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count - + side_info.gr[igr][ch].region1_count + 1]; - n3 = side_info.gr[igr][ch].big_values; - n3 = n3 + n3; - - - if (n3 > pMP3Stream->band_limit) - n3 = pMP3Stream->band_limit; - if (n2 > n3) - n2 = n3; - if (n1 > n3) - n1 = n3; - nn3 = n3 - n2; - nn2 = n2 - n1; - unpack_huff(pMP3Stream->sample[ch][igr], n1, side_info.gr[igr][ch].table_select[0]); - unpack_huff(pMP3Stream->sample[ch][igr] + n1, nn2, side_info.gr[igr][ch].table_select[1]); - unpack_huff(pMP3Stream->sample[ch][igr] + n2, nn3, side_info.gr[igr][ch].table_select[2]); - qbits = side_info.gr[igr][ch].part2_3_length - (bitget_bits_used() - bit0); - nn4 = unpack_huff_quad(pMP3Stream->sample[ch][igr] + n3, pMP3Stream->band_limit - n3, qbits, - side_info.gr[igr][ch].count1table_select); - n4 = n3 + nn4; - nsamp[igr][ch] = n4; - //limit n4 or allow deqaunt to sf band 22 - if (side_info.gr[igr][ch].block_type == 2) - n4 = min(n4, pMP3Stream->band_limit12); - else - n4 = min(n4, pMP3Stream->band_limit21); - if (n4 < 576) - memset(pMP3Stream->sample[ch][igr] + n4, 0, sizeof(SAMPLE) * (576 - n4)); - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - { // bad data overrun - - memset(pMP3Stream->sample[ch][igr], 0, sizeof(SAMPLE) * (576)); - } - } - - - -/*--- dequant ---*/ - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - dequant(pMP3Stream->sample[ch][igr], - &nsamp[igr][ch], /* nsamp updated for shorts */ - &sf[igr][ch], &side_info.gr[igr][ch], - &cb_info[igr][ch], pMP3Stream->ncbl_mixed); - } - -/*--- ms stereo processing ---*/ - if (pMP3Stream->ms_mode) - { - if (pMP3Stream->is_mode == 0) - { - m0 = nsamp[igr][0]; /* process to longer of left/right */ - if (m0 < nsamp[igr][1]) - m0 = nsamp[igr][1]; - } - else - { /* process to last cb in right */ - m0 = pMP3Stream->sfBandIndex[cb_info[igr][1].cbtype][cb_info[igr][1].cbmax]; - } - ms_process(pMP3Stream->sample[0][igr], m0); - } - -/*--- is stereo processing ---*/ - if (pMP3Stream->is_mode) - { - if (pMP3Stream->id) - is_process_MPEG1(pMP3Stream->sample[0][igr], &sf[igr][1], - cb_info[igr], nsamp[igr][0], pMP3Stream->ms_mode); - else - is_process_MPEG2(pMP3Stream->sample[0][igr], &sf[igr][1], - cb_info[igr], &is_sf_info, - nsamp[igr][0], pMP3Stream->ms_mode); - } - -/*-- adjust ms and is modes to max of left/right */ - if (side_info.mode_ext) - { - if (nsamp[igr][0] < nsamp[igr][1]) - nsamp[igr][0] = nsamp[igr][1]; - else - nsamp[igr][1] = nsamp[igr][0]; - } - -/*--- antialias ---*/ - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - if (cb_info[igr][ch].ncbl == 0) - continue; /* have no long blocks */ - if (side_info.gr[igr][ch].mixed_block_flag) - n1 = 1; /* 1 -> 36 samples */ - else - n1 = (nsamp[igr][ch] + 7) / 18; - if (n1 > 31) - n1 = 31; - antialias(pMP3Stream->sample[ch][igr], n1); - n1 = 18 * n1 + 8; /* update number of samples */ - if (n1 > nsamp[igr][ch]) - nsamp[igr][ch] = n1; - } - - - -/*--- hybrid + sbt ---*/ - pMP3Stream->Xform(pcm, igr); - - -/*-- done --*/ +static void unpack_main(unsigned char *pcm, int igr) { + int ch; + int bit0; + int n1, n2, n3, n4, nn2, nn3; + int nn4; + int qbits; + int m0; + + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + bitget_init(pMP3Stream->buf + (pMP3Stream->main_pos_bit >> 3)); + bit0 = (pMP3Stream->main_pos_bit & 7); + if (bit0) + bitget(bit0); + pMP3Stream->main_pos_bit += side_info.gr[igr][ch].part2_3_length; + bitget_init_end(pMP3Stream->buf + ((pMP3Stream->main_pos_bit + 39) >> 3)); + /*-- scale factors --*/ + if (pMP3Stream->id) + unpack_sf_sub_MPEG1(&sf[igr][ch], &side_info.gr[igr][ch], side_info.scfsi[ch], igr); + else + unpack_sf_sub_MPEG2(&sf[igr][ch], &side_info.gr[igr][ch], pMP3Stream->is_mode & ch, &is_sf_info); + /*--- huff data ---*/ + n1 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count]; + n2 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count + side_info.gr[igr][ch].region1_count + 1]; + n3 = side_info.gr[igr][ch].big_values; + n3 = n3 + n3; + + if (n3 > pMP3Stream->band_limit) + n3 = pMP3Stream->band_limit; + if (n2 > n3) + n2 = n3; + if (n1 > n3) + n1 = n3; + nn3 = n3 - n2; + nn2 = n2 - n1; + unpack_huff(pMP3Stream->sample[ch][igr], n1, side_info.gr[igr][ch].table_select[0]); + unpack_huff(pMP3Stream->sample[ch][igr] + n1, nn2, side_info.gr[igr][ch].table_select[1]); + unpack_huff(pMP3Stream->sample[ch][igr] + n2, nn3, side_info.gr[igr][ch].table_select[2]); + qbits = side_info.gr[igr][ch].part2_3_length - (bitget_bits_used() - bit0); + nn4 = unpack_huff_quad(pMP3Stream->sample[ch][igr] + n3, pMP3Stream->band_limit - n3, qbits, side_info.gr[igr][ch].count1table_select); + n4 = n3 + nn4; + nsamp[igr][ch] = n4; + // limit n4 or allow deqaunt to sf band 22 + if (side_info.gr[igr][ch].block_type == 2) + n4 = min(n4, pMP3Stream->band_limit12); + else + n4 = min(n4, pMP3Stream->band_limit21); + if (n4 < 576) + memset(pMP3Stream->sample[ch][igr] + n4, 0, sizeof(SAMPLE) * (576 - n4)); + if (bitdat.bs_ptr > bitdat.bs_ptr_end) { // bad data overrun + + memset(pMP3Stream->sample[ch][igr], 0, sizeof(SAMPLE) * (576)); + } + } + + /*--- dequant ---*/ + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + dequant(pMP3Stream->sample[ch][igr], &nsamp[igr][ch], /* nsamp updated for shorts */ + &sf[igr][ch], &side_info.gr[igr][ch], &cb_info[igr][ch], pMP3Stream->ncbl_mixed); + } + + /*--- ms stereo processing ---*/ + if (pMP3Stream->ms_mode) { + if (pMP3Stream->is_mode == 0) { + m0 = nsamp[igr][0]; /* process to longer of left/right */ + if (m0 < nsamp[igr][1]) + m0 = nsamp[igr][1]; + } else { /* process to last cb in right */ + m0 = pMP3Stream->sfBandIndex[cb_info[igr][1].cbtype][cb_info[igr][1].cbmax]; + } + ms_process(pMP3Stream->sample[0][igr], m0); + } + + /*--- is stereo processing ---*/ + if (pMP3Stream->is_mode) { + if (pMP3Stream->id) + is_process_MPEG1(pMP3Stream->sample[0][igr], &sf[igr][1], cb_info[igr], nsamp[igr][0], pMP3Stream->ms_mode); + else + is_process_MPEG2(pMP3Stream->sample[0][igr], &sf[igr][1], cb_info[igr], &is_sf_info, nsamp[igr][0], pMP3Stream->ms_mode); + } + + /*-- adjust ms and is modes to max of left/right */ + if (side_info.mode_ext) { + if (nsamp[igr][0] < nsamp[igr][1]) + nsamp[igr][0] = nsamp[igr][1]; + else + nsamp[igr][1] = nsamp[igr][0]; + } + + /*--- antialias ---*/ + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + if (cb_info[igr][ch].ncbl == 0) + continue; /* have no long blocks */ + if (side_info.gr[igr][ch].mixed_block_flag) + n1 = 1; /* 1 -> 36 samples */ + else + n1 = (nsamp[igr][ch] + 7) / 18; + if (n1 > 31) + n1 = 31; + antialias(pMP3Stream->sample[ch][igr], n1); + n1 = 18 * n1 + 8; /* update number of samples */ + if (n1 > nsamp[igr][ch]) + nsamp[igr][ch] = n1; + } + + /*--- hybrid + sbt ---*/ + pMP3Stream->Xform(pcm, igr); + + /*-- done --*/ } /*--------------------------------------------------------------------*/ /*-----------------------------------------------------------------*/ -IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm) -{ - return pMP3Stream->decode_function(bs, pcm); -} +IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm) { return pMP3Stream->decode_function(bs, pcm); } /*--------------------------------------------------------------------*/ extern unsigned char *gpNextByteAfterData; -IN_OUT L3audio_decode_MPEG1(unsigned char *bs, unsigned char *pcm) -{ - int sync; - IN_OUT in_out; - int side_bytes; - int nbytes; - - int padframebytes; ////@@@@ - -// iframe++; - - bitget_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = bitget(12); - - if (sync != 0xFFF) - return in_out; /* sync fail */ -/*-----------*/ - -/*-- unpack side info --*/ - side_bytes = unpack_side_MPEG1(); - padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; - - if (bs + padframebytes > gpNextByteAfterData) - return in_out; // error check if we're about to read off the end of the legal memory (caused by certain MP3 writers' goofy comment formats) -ste. - in_out.in_bytes = padframebytes; - -/*-- load main data and update buf pointer --*/ -/*------------------------------------------- - if start point < 0, must just cycle decoder - if jumping into middle of stream, -w---------------------------------------------*/ - pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ - if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) - { /* shift buffer */ - memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = side_info.main_data_begin; - } - nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - - // RAK: This is no bueno. :-( - if (nbytes < 0 || nbytes > NBUF) - { - in_out.in_bytes = 0; - return in_out; - } +IN_OUT L3audio_decode_MPEG1(unsigned char *bs, unsigned char *pcm) { + int sync; + IN_OUT in_out; + int side_bytes; + int nbytes; + + int padframebytes; ////@@@@ + + // iframe++; + + bitget_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = bitget(12); + + if (sync != 0xFFF) + return in_out; /* sync fail */ + /*-----------*/ + + /*-- unpack side info --*/ + side_bytes = unpack_side_MPEG1(); + padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; + + if (bs + padframebytes > gpNextByteAfterData) + return in_out; // error check if we're about to read off the end of the legal memory (caused by certain MP3 writers' goofy comment formats) -ste. + in_out.in_bytes = padframebytes; + + /*-- load main data and update buf pointer --*/ + /*------------------------------------------- + if start point < 0, must just cycle decoder + if jumping into middle of stream, + w---------------------------------------------*/ + pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ + if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ + memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = side_info.main_data_begin; + } + nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - if (bFastEstimateOnly) - { + // RAK: This is no bueno. :-( + if (nbytes < 0 || nbytes > NBUF) { + in_out.in_bytes = 0; + return in_out; + } + + if (bFastEstimateOnly) { in_out.out_bytes = pMP3Stream->outbytes; return in_out; } - memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); - pMP3Stream->buf_ptr1 += nbytes; -/*-----------------------*/ - - if (pMP3Stream->buf_ptr0 >= 0) - { -// dump_frame(buf+buf_ptr0, 64); - pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; - unpack_main(pcm, 0); - unpack_main(pcm + pMP3Stream->half_outbytes, 1); - in_out.out_bytes = pMP3Stream->outbytes; - } - else - { - memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ - in_out.out_bytes = pMP3Stream->outbytes; -/* iframe--; in_out.out_bytes = 0; // test test */ - } - - return in_out; + memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); + pMP3Stream->buf_ptr1 += nbytes; + /*-----------------------*/ + + if (pMP3Stream->buf_ptr0 >= 0) { + // dump_frame(buf+buf_ptr0, 64); + pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; + unpack_main(pcm, 0); + unpack_main(pcm + pMP3Stream->half_outbytes, 1); + in_out.out_bytes = pMP3Stream->outbytes; + } else { + memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ + in_out.out_bytes = pMP3Stream->outbytes; + /* iframe--; in_out.out_bytes = 0; // test test */ + } + + return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm) -{ - int sync; - IN_OUT in_out; - int side_bytes; - int nbytes; - static int igr = 0; - - int padframebytes; ////@@@@ - -// iframe++; - - - bitget_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = bitget(12); - -// if( sync != 0xFFF ) return in_out; /* sync fail */ - - pMP3Stream->mpeg25_flag = 0; - if (sync != 0xFFF) - { - pMP3Stream->mpeg25_flag = 1; /* mpeg 2.5 sync */ - if (sync != 0xFFE) - return in_out; /* sync fail */ - } -/*-----------*/ - - -/*-- unpack side info --*/ - side_bytes = unpack_side_MPEG2(igr); - padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.in_bytes = padframebytes; - - pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ - if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) - { /* shift buffer */ - memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = side_info.main_data_begin; - } - nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - // RAK: This is no bueno. :-( - if (nbytes < 0 || nbytes > NBUF) - { - in_out.in_bytes = 0; - return in_out; - } +IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm) { + int sync; + IN_OUT in_out; + int side_bytes; + int nbytes; + static int igr = 0; + + int padframebytes; ////@@@@ + + // iframe++; + + bitget_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = bitget(12); + + // if( sync != 0xFFF ) return in_out; /* sync fail */ + + pMP3Stream->mpeg25_flag = 0; + if (sync != 0xFFF) { + pMP3Stream->mpeg25_flag = 1; /* mpeg 2.5 sync */ + if (sync != 0xFFE) + return in_out; /* sync fail */ + } + /*-----------*/ + + /*-- unpack side info --*/ + side_bytes = unpack_side_MPEG2(igr); + padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.in_bytes = padframebytes; + + pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ + if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ + memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = side_info.main_data_begin; + } + nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; + // RAK: This is no bueno. :-( + if (nbytes < 0 || nbytes > NBUF) { + in_out.in_bytes = 0; + return in_out; + } - if (bFastEstimateOnly) - { + if (bFastEstimateOnly) { in_out.out_bytes = pMP3Stream->outbytes; return in_out; } - memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); - pMP3Stream->buf_ptr1 += nbytes; -/*-----------------------*/ - - if (pMP3Stream->buf_ptr0 >= 0) - { - pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; - unpack_main(pcm, igr); - in_out.out_bytes = pMP3Stream->outbytes; - } - else - { - memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ - in_out.out_bytes = pMP3Stream->outbytes; -// iframe--; in_out.out_bytes = 0; return in_out;// test test */ - } - + memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); + pMP3Stream->buf_ptr1 += nbytes; + /*-----------------------*/ + if (pMP3Stream->buf_ptr0 >= 0) { + pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; + unpack_main(pcm, igr); + in_out.out_bytes = pMP3Stream->outbytes; + } else { + memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ + in_out.out_bytes = pMP3Stream->outbytes; + // iframe--; in_out.out_bytes = 0; return in_out;// test test */ + } - igr = igr ^ 1; - return in_out; + igr = igr ^ 1; + return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -static const int sr_table[8] = -{22050, 24000, 16000, 1, - 44100, 48000, 32000, 1}; - -static const struct -{ - int l[23]; - int s[14]; -} -sfBandIndexTable[3][3] = -{ -/* mpeg-2 */ - { - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , - } - , -/* mpeg-1 */ - { - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192 - } - } - , - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192 - } - } - , - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192 - } - } - } - , - -/* mpeg-2.5, 11 & 12 KHz seem ok, 8 ok */ - { - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , -// this 8khz table, and only 8khz, from mpeg123) - { - { - 0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576 - } - , - { - 0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192 - } - } - , - } - , -}; +static const int sr_table[8] = {22050, 24000, 16000, 1, 44100, 48000, 32000, 1}; +static const struct { + int l[23]; + int s[14]; +} sfBandIndexTable[3][3] = { + /* mpeg-2 */ + { + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + }, + /* mpeg-1 */ + {{{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576}, + {0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192}}, + {{0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576}, + {0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192}}, + {{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576}, + {0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192}}}, + + /* mpeg-2.5, 11 & 12 KHz seem ok, 8 ok */ + { + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + // this 8khz table, and only 8khz, from mpeg123) + {{0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576}, + {0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192}}, + }, +}; void sbt_mono_L3(float *sample, signed short *pcm, int ch); void sbt_dual_L3(float *sample, signed short *pcm, int ch); @@ -1070,38 +858,22 @@ void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch); void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch); void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch); - - -static const SBT_FUNCTION sbt_table[2][3][2] = -{ -{{ (SBT_FUNCTION) sbt_mono_L3, - (SBT_FUNCTION) sbt_dual_L3 } , - { (SBT_FUNCTION) sbt16_mono_L3, - (SBT_FUNCTION) sbt16_dual_L3 } , - { (SBT_FUNCTION) sbt8_mono_L3, - (SBT_FUNCTION) sbt8_dual_L3 }} , -/*-- 8 bit output -*/ -{{ (SBT_FUNCTION) sbtB_mono_L3, - (SBT_FUNCTION) sbtB_dual_L3 }, - { (SBT_FUNCTION) sbtB16_mono_L3, - (SBT_FUNCTION) sbtB16_dual_L3 }, - { (SBT_FUNCTION) sbtB8_mono_L3, - (SBT_FUNCTION) sbtB8_dual_L3 }} -}; - +static const SBT_FUNCTION sbt_table[2][3][2] = {{{(SBT_FUNCTION)sbt_mono_L3, (SBT_FUNCTION)sbt_dual_L3}, + {(SBT_FUNCTION)sbt16_mono_L3, (SBT_FUNCTION)sbt16_dual_L3}, + {(SBT_FUNCTION)sbt8_mono_L3, (SBT_FUNCTION)sbt8_dual_L3}}, + /*-- 8 bit output -*/ + {{(SBT_FUNCTION)sbtB_mono_L3, (SBT_FUNCTION)sbtB_dual_L3}, + {(SBT_FUNCTION)sbtB16_mono_L3, (SBT_FUNCTION)sbtB16_dual_L3}, + {(SBT_FUNCTION)sbtB8_mono_L3, (SBT_FUNCTION)sbtB8_dual_L3}}}; void Xform_mono(void *pcm, int igr); void Xform_dual(void *pcm, int igr); void Xform_dual_mono(void *pcm, int igr); void Xform_dual_right(void *pcm, int igr); -static XFORM_FUNCTION xform_table[5] = -{ - Xform_mono, - Xform_dual, - Xform_dual_mono, - Xform_mono, /* left */ - Xform_dual_right, +static XFORM_FUNCTION xform_table[5] = { + Xform_mono, Xform_dual, Xform_dual_mono, Xform_mono, /* left */ + Xform_dual_right, }; int L3table_init(); void msis_init(); @@ -1113,178 +885,161 @@ iARRAY22 *msis_init_band_addr(); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pMP3Stream->pad */ ////@@@@INIT -int L3audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, j, k; - // static int first_pass = 1; - int samprate; - int limit; - int bit_code; - int out_chans; - - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = 0; - -/* check if code handles */ - if (h->option != 1) - return 0; /* layer III only */ - - if (h->id) - pMP3Stream->ncbl_mixed = 8; /* mpeg-1 */ - else - pMP3Stream->ncbl_mixed = 6; /* mpeg-2 */ - - pMP3Stream->framebytes = framebytes_arg; - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - samprate = sr_table[4 * h->id + h->sr_index]; - if ((h->sync & 1) == 0) - samprate = samprate / 2; // mpeg 2.5 -/*----- compute pMP3Stream->nsb_limit --------*/ - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - limit = 18 * pMP3Stream->nsb_limit; - - k = h->id; - if ((h->sync & 1) == 0) - k = 2; // mpeg 2.5 - - if (k == 1) - { - pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[13]; - pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[22]; - } - else - { - pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[12]; - pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[21]; - } - pMP3Stream->band_limit += 8; /* allow for antialias */ - if (pMP3Stream->band_limit > limit) - pMP3Stream->band_limit = limit; - - if (pMP3Stream->band_limit21 > pMP3Stream->band_limit) - pMP3Stream->band_limit21 = pMP3Stream->band_limit; - if (pMP3Stream->band_limit12 > pMP3Stream->band_limit) - pMP3Stream->band_limit12 = pMP3Stream->band_limit; - - - pMP3Stream->band_limit_nsb = (pMP3Stream->band_limit + 17) / 18; /* limit nsb's rounded up */ -/*----------------------------------------------*/ - pMP3Stream->gain_adjust = 0; /* adjust gain e.g. cvt to mono sum channel */ - if ((h->mode != 3) && (convert_code == 1)) - pMP3Stream->gain_adjust = -4; - - pMP3Stream->outvalues = 1152 >> reduction_code; - if (h->id == 0) - pMP3Stream->outvalues /= 2; - - out_chans = 2; - if (h->mode == 3) - out_chans = 1; - if (convert_code) - out_chans = 1; - - pMP3Stream->sbt_L3 = sbt_table[bit_code][reduction_code][out_chans - 1]; - k = 1 + convert_code; - if (h->mode == 3) - k = 0; - pMP3Stream->Xform = xform_table[k]; - - - pMP3Stream->outvalues *= out_chans; - - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - if (bit_code) - pMP3Stream->zero_level_pcm = 128; /* 8 bit output */ - else - pMP3Stream->zero_level_pcm = 0; - - - decinfo.channels = out_chans; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - pMP3Stream->half_outbytes = pMP3Stream->outbytes / 2; -/*------------------------------------------*/ - -/*- init band tables --*/ - - - k = h->id; - if ((h->sync & 1) == 0) - k = 2; // mpeg 2.5 - - for (i = 0; i < 22; i++) - pMP3Stream->sfBandIndex[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1]; - for (i = 0; i < 13; i++) - pMP3Stream->sfBandIndex[1][i] = 3 * sfBandIndexTable[k][h->sr_index].s[i + 1]; - for (i = 0; i < 22; i++) - pMP3Stream->nBand[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1] - sfBandIndexTable[k][h->sr_index].l[i]; - for (i = 0; i < 13; i++) - pMP3Stream->nBand[1][i] = sfBandIndexTable[k][h->sr_index].s[i + 1] - sfBandIndexTable[k][h->sr_index].s[i]; - - -/* init tables */ - L3table_init(); -/* init ms and is stereo modes */ - msis_init(); - -/*----- init sbt ---*/ - sbt_init(); - - - -/*--- clear buffers --*/ - for (i = 0; i < 576; i++) - yout[i] = 0.0f; - for (j = 0; j < 2; j++) - { - for (k = 0; k < 2; k++) - { - for (i = 0; i < 576; i++) - { - pMP3Stream->sample[j][k][i].x = 0.0f; - pMP3Stream->sample[j][k][i].s = 0; - } - } - } +int L3audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, j, k; + // static int first_pass = 1; + int samprate; + int limit; + int bit_code; + int out_chans; + + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = 0; + + /* check if code handles */ + if (h->option != 1) + return 0; /* layer III only */ + + if (h->id) + pMP3Stream->ncbl_mixed = 8; /* mpeg-1 */ + else + pMP3Stream->ncbl_mixed = 6; /* mpeg-2 */ + + pMP3Stream->framebytes = framebytes_arg; + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + samprate = sr_table[4 * h->id + h->sr_index]; + if ((h->sync & 1) == 0) + samprate = samprate / 2; // mpeg 2.5 + /*----- compute pMP3Stream->nsb_limit --------*/ + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + limit = 18 * pMP3Stream->nsb_limit; + + k = h->id; + if ((h->sync & 1) == 0) + k = 2; // mpeg 2.5 + + if (k == 1) { + pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[13]; + pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[22]; + } else { + pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[12]; + pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[21]; + } + pMP3Stream->band_limit += 8; /* allow for antialias */ + if (pMP3Stream->band_limit > limit) + pMP3Stream->band_limit = limit; + + if (pMP3Stream->band_limit21 > pMP3Stream->band_limit) + pMP3Stream->band_limit21 = pMP3Stream->band_limit; + if (pMP3Stream->band_limit12 > pMP3Stream->band_limit) + pMP3Stream->band_limit12 = pMP3Stream->band_limit; + + pMP3Stream->band_limit_nsb = (pMP3Stream->band_limit + 17) / 18; /* limit nsb's rounded up */ + /*----------------------------------------------*/ + pMP3Stream->gain_adjust = 0; /* adjust gain e.g. cvt to mono sum channel */ + if ((h->mode != 3) && (convert_code == 1)) + pMP3Stream->gain_adjust = -4; + + pMP3Stream->outvalues = 1152 >> reduction_code; + if (h->id == 0) + pMP3Stream->outvalues /= 2; + + out_chans = 2; + if (h->mode == 3) + out_chans = 1; + if (convert_code) + out_chans = 1; + + pMP3Stream->sbt_L3 = sbt_table[bit_code][reduction_code][out_chans - 1]; + k = 1 + convert_code; + if (h->mode == 3) + k = 0; + pMP3Stream->Xform = xform_table[k]; + + pMP3Stream->outvalues *= out_chans; + + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + if (bit_code) + pMP3Stream->zero_level_pcm = 128; /* 8 bit output */ + else + pMP3Stream->zero_level_pcm = 0; + + decinfo.channels = out_chans; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + pMP3Stream->half_outbytes = pMP3Stream->outbytes / 2; + /*------------------------------------------*/ + + /*- init band tables --*/ + + k = h->id; + if ((h->sync & 1) == 0) + k = 2; // mpeg 2.5 + + for (i = 0; i < 22; i++) + pMP3Stream->sfBandIndex[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1]; + for (i = 0; i < 13; i++) + pMP3Stream->sfBandIndex[1][i] = 3 * sfBandIndexTable[k][h->sr_index].s[i + 1]; + for (i = 0; i < 22; i++) + pMP3Stream->nBand[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1] - sfBandIndexTable[k][h->sr_index].l[i]; + for (i = 0; i < 13; i++) + pMP3Stream->nBand[1][i] = sfBandIndexTable[k][h->sr_index].s[i + 1] - sfBandIndexTable[k][h->sr_index].s[i]; + + /* init tables */ + L3table_init(); + /* init ms and is stereo modes */ + msis_init(); + + /*----- init sbt ---*/ + sbt_init(); + + /*--- clear buffers --*/ + for (i = 0; i < 576; i++) + yout[i] = 0.0f; + for (j = 0; j < 2; j++) { + for (k = 0; k < 2; k++) { + for (i = 0; i < 576; i++) { + pMP3Stream->sample[j][k][i].x = 0.0f; + pMP3Stream->sample[j][k][i].s = 0; + } + } + } - if (h->id == 1) - pMP3Stream->decode_function = L3audio_decode_MPEG1; - else - pMP3Stream->decode_function = L3audio_decode_MPEG2; + if (h->id == 1) + pMP3Stream->decode_function = L3audio_decode_MPEG1; + else + pMP3Stream->decode_function = L3audio_decode_MPEG2; - return 1; + return 1; } /*---------------------------------------------------------*/ /*==========================================================*/ diff --git a/code/mp3code/cwin.c b/code/mp3code/cwin.c index b1714055de..633fb9b2f6 100644 --- a/code/mp3code/cwin.c +++ b/code/mp3code/cwin.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,433 +37,395 @@ portable C #include "config.h" /*-------------------------------------------------------------------------*/ -void window(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } - - /*------------------------------------------------------------*/ -void window_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; /* dual window interleaves output */ - int si, bx; - const float *coef; - float sum; - long tmp; +void window_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; /* dual window interleaves output */ + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ -void window16(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void window16(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ -void window16_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void window16_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------- 8 pt window ------------------------------*/ -void window8(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window8(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } /*--------------- 8 pt dual window (interleaved output) -----------------*/ -void window8_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window8_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/cwinb.c b/code/mp3code/cwinb.c index 2b78f1e43b..a4604401ce 100644 --- a/code/mp3code/cwinb.c +++ b/code/mp3code/cwinb.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -35,430 +35,394 @@ portable C ******************************************************************/ /*-------------------------------------------------------------------------*/ -void windowB(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*------------------------------------------------------------*/ -void windowB_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; /* dual window interleaves output */ - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; /* dual window interleaves output */ + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ -void windowB16(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void windowB16(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ -void windowB16_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void windowB16_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------- 8 pt window ------------------------------*/ -void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*--------------- 8 pt dual window (interleaved output) -----------------*/ -void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/code/mp3code/cwinm.c b/code/mp3code/cwinm.c index d1a292e11f..345003bdb0 100644 --- a/code/mp3code/cwinm.c +++ b/code/mp3code/cwinm.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,8 +37,8 @@ portable C #include #include -const float wincoef[264] = -{ /* window coefs */ +const float wincoef[264] = { + /* window coefs */ #include "tableawd.h" }; diff --git a/code/mp3code/hwin.c b/code/mp3code/hwin.c index 8f04280c15..f0fb8e18e7 100644 --- a/code/mp3code/hwin.c +++ b/code/mp3code/hwin.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -42,223 +42,188 @@ hybrid window/filter typedef float ARRAY36[36]; /*-- windows by block type --*/ -static float win[4][36]; // effectively a constant - +static float win[4][36]; // effectively a constant /*====================================================================*/ -void imdct18(float f[]); /* 18 point */ -void imdct6_3(float f[]); /* 6 point */ +void imdct18(float f[]); /* 18 point */ +void imdct6_3(float f[]); /* 6 point */ /*====================================================================*/ -ARRAY36 *hwin_init_addr() -{ - return win; -} - +ARRAY36 *hwin_init_addr() { return win; } /*====================================================================*/ -int hybrid(float xin[], float xprev[], float y[18][32], - int btype, int nlong, int ntot, int nprev) -{ - int i, j; - float *x, *x0; - float xa, xb; - int n; - int nout; - - - - if (btype == 2) - btype = 0; - x = xin; - x0 = xprev; - -/*-- do long blocks (if any) --*/ - n = (nlong + 17) / 18; /* number of dct's to do */ - for (i = 0; i < n; i++) - { - imdct18(x); - for (j = 0; j < 9; j++) - { - y[j][i] = x0[j] + win[btype][j] * x[9 + j]; - y[9 + j][i] = x0[9 + j] + win[btype][9 + j] * x[17 - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 4; j++) - { - xa = x[j]; - xb = x[8 - j]; - x[j] = win[btype][18 + j] * xb; - x[8 - j] = win[btype][(18 + 8) - j] * xa; - x[9 + j] = win[btype][(18 + 9) + j] * xa; - x[17 - j] = win[btype][(18 + 17) - j] * xb; - } - xa = x[j]; - x[j] = win[btype][18 + j] * xa; - x[9 + j] = win[btype][(18 + 9) + j] * xa; - - x += 18; - x0 += 18; - } - -/*-- do short blocks (if any) --*/ - n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ - for (; i < n; i++) - { - imdct6_3(x); - for (j = 0; j < 3; j++) - { - y[j][i] = x0[j]; - y[3 + j][i] = x0[3 + j]; - - y[6 + j][i] = x0[6 + j] + win[2][j] * x[3 + j]; - y[9 + j][i] = x0[9 + j] + win[2][3 + j] * x[5 - j]; - - y[12 + j][i] = x0[12 + j] + win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; - y[15 + j][i] = x0[15 + j] + win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 3; j++) - { - x[j] = win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; - x[3 + j] = win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; - } - for (j = 0; j < 3; j++) - { - x[6 + j] = win[2][6 + j] * x[(12 + 2) - j]; - x[9 + j] = win[2][9 + j] * x[12 + j]; - } - for (j = 0; j < 3; j++) - { - x[12 + j] = 0.0f; - x[15 + j] = 0.0f; - } - x += 18; - x0 += 18; - } - -/*--- overlap prev if prev longer that current --*/ - n = (nprev + 17) / 18; - for (; i < n; i++) - { - for (j = 0; j < 18; j++) - y[j][i] = x0[j]; - x0 += 18; - } - nout = 18 * i; - -/*--- clear remaining only to band limit --*/ - for (; i < pMP3Stream->band_limit_nsb; i++) - { - for (j = 0; j < 18; j++) - y[j][i] = 0.0f; - } - - return nout; +int hybrid(float xin[], float xprev[], float y[18][32], int btype, int nlong, int ntot, int nprev) { + int i, j; + float *x, *x0; + float xa, xb; + int n; + int nout; + + if (btype == 2) + btype = 0; + x = xin; + x0 = xprev; + + /*-- do long blocks (if any) --*/ + n = (nlong + 17) / 18; /* number of dct's to do */ + for (i = 0; i < n; i++) { + imdct18(x); + for (j = 0; j < 9; j++) { + y[j][i] = x0[j] + win[btype][j] * x[9 + j]; + y[9 + j][i] = x0[9 + j] + win[btype][9 + j] * x[17 - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 4; j++) { + xa = x[j]; + xb = x[8 - j]; + x[j] = win[btype][18 + j] * xb; + x[8 - j] = win[btype][(18 + 8) - j] * xa; + x[9 + j] = win[btype][(18 + 9) + j] * xa; + x[17 - j] = win[btype][(18 + 17) - j] * xb; + } + xa = x[j]; + x[j] = win[btype][18 + j] * xa; + x[9 + j] = win[btype][(18 + 9) + j] * xa; + + x += 18; + x0 += 18; + } + + /*-- do short blocks (if any) --*/ + n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ + for (; i < n; i++) { + imdct6_3(x); + for (j = 0; j < 3; j++) { + y[j][i] = x0[j]; + y[3 + j][i] = x0[3 + j]; + + y[6 + j][i] = x0[6 + j] + win[2][j] * x[3 + j]; + y[9 + j][i] = x0[9 + j] + win[2][3 + j] * x[5 - j]; + + y[12 + j][i] = x0[12 + j] + win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; + y[15 + j][i] = x0[15 + j] + win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 3; j++) { + x[j] = win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; + x[3 + j] = win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; + } + for (j = 0; j < 3; j++) { + x[6 + j] = win[2][6 + j] * x[(12 + 2) - j]; + x[9 + j] = win[2][9 + j] * x[12 + j]; + } + for (j = 0; j < 3; j++) { + x[12 + j] = 0.0f; + x[15 + j] = 0.0f; + } + x += 18; + x0 += 18; + } + + /*--- overlap prev if prev longer that current --*/ + n = (nprev + 17) / 18; + for (; i < n; i++) { + for (j = 0; j < 18; j++) + y[j][i] = x0[j]; + x0 += 18; + } + nout = 18 * i; + + /*--- clear remaining only to band limit --*/ + for (; i < pMP3Stream->band_limit_nsb; i++) { + for (j = 0; j < 18; j++) + y[j][i] = 0.0f; + } + + return nout; } - /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*-- convert to mono, add curr result to y, - window and add next time to current left */ -int hybrid_sum(float xin[], float xin_left[], float y[18][32], - int btype, int nlong, int ntot) -{ - int i, j; - float *x, *x0; - float xa, xb; - int n; - int nout; - - - - if (btype == 2) - btype = 0; - x = xin; - x0 = xin_left; - -/*-- do long blocks (if any) --*/ - n = (nlong + 17) / 18; /* number of dct's to do */ - for (i = 0; i < n; i++) - { - imdct18(x); - for (j = 0; j < 9; j++) - { - y[j][i] += win[btype][j] * x[9 + j]; - y[9 + j][i] += win[btype][9 + j] * x[17 - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 4; j++) - { - xa = x[j]; - xb = x[8 - j]; - x0[j] += win[btype][18 + j] * xb; - x0[8 - j] += win[btype][(18 + 8) - j] * xa; - x0[9 + j] += win[btype][(18 + 9) + j] * xa; - x0[17 - j] += win[btype][(18 + 17) - j] * xb; - } - xa = x[j]; - x0[j] += win[btype][18 + j] * xa; - x0[9 + j] += win[btype][(18 + 9) + j] * xa; - - x += 18; - x0 += 18; - } - -/*-- do short blocks (if any) --*/ - n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ - for (; i < n; i++) - { - imdct6_3(x); - for (j = 0; j < 3; j++) - { - y[6 + j][i] += win[2][j] * x[3 + j]; - y[9 + j][i] += win[2][3 + j] * x[5 - j]; - - y[12 + j][i] += win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; - y[15 + j][i] += win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; - } - /* window x for next time */ - for (j = 0; j < 3; j++) - { - x0[j] += win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; - x0[3 + j] += win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; - } - for (j = 0; j < 3; j++) - { - x0[6 + j] += win[2][6 + j] * x[(12 + 2) - j]; - x0[9 + j] += win[2][9 + j] * x[12 + j]; - } - x += 18; - x0 += 18; - } - - nout = 18 * i; - - return nout; + window and add next time to current left */ +int hybrid_sum(float xin[], float xin_left[], float y[18][32], int btype, int nlong, int ntot) { + int i, j; + float *x, *x0; + float xa, xb; + int n; + int nout; + + if (btype == 2) + btype = 0; + x = xin; + x0 = xin_left; + + /*-- do long blocks (if any) --*/ + n = (nlong + 17) / 18; /* number of dct's to do */ + for (i = 0; i < n; i++) { + imdct18(x); + for (j = 0; j < 9; j++) { + y[j][i] += win[btype][j] * x[9 + j]; + y[9 + j][i] += win[btype][9 + j] * x[17 - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 4; j++) { + xa = x[j]; + xb = x[8 - j]; + x0[j] += win[btype][18 + j] * xb; + x0[8 - j] += win[btype][(18 + 8) - j] * xa; + x0[9 + j] += win[btype][(18 + 9) + j] * xa; + x0[17 - j] += win[btype][(18 + 17) - j] * xb; + } + xa = x[j]; + x0[j] += win[btype][18 + j] * xa; + x0[9 + j] += win[btype][(18 + 9) + j] * xa; + + x += 18; + x0 += 18; + } + + /*-- do short blocks (if any) --*/ + n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ + for (; i < n; i++) { + imdct6_3(x); + for (j = 0; j < 3; j++) { + y[6 + j][i] += win[2][j] * x[3 + j]; + y[9 + j][i] += win[2][3 + j] * x[5 - j]; + + y[12 + j][i] += win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; + y[15 + j][i] += win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; + } + /* window x for next time */ + for (j = 0; j < 3; j++) { + x0[j] += win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; + x0[3 + j] += win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; + } + for (j = 0; j < 3; j++) { + x0[6 + j] += win[2][6 + j] * x[(12 + 2) - j]; + x0[9 + j] += win[2][9 + j] * x[12 + j]; + } + x += 18; + x0 += 18; + } + + nout = 18 * i; + + return nout; } /*--------------------------------------------------------------------*/ -void sum_f_bands(float a[], float b[], int n) -{ - int i; +void sum_f_bands(float a[], float b[], int n) { + int i; - for (i = 0; i < n; i++) - a[i] += b[i]; + for (i = 0; i < n; i++) + a[i] += b[i]; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -void FreqInvert(float y[18][32], int n) -{ - int i, j; - - n = (n + 17) / 18; - for (j = 0; j < 18; j += 2) - { - for (i = 0; i < n; i += 2) - { - y[1 + j][1 + i] = -y[1 + j][1 + i]; - } - } +void FreqInvert(float y[18][32], int n) { + int i, j; + + n = (n + 17) / 18; + for (j = 0; j < 18; j += 2) { + for (i = 0; i < n; i += 2) { + y[1 + j][1 + i] = -y[1 + j][1 + i]; + } + } } /*--------------------------------------------------------------------*/ diff --git a/code/mp3code/l3dq.c b/code/mp3code/l3dq.c index a5a56d3bc6..a616650d36 100644 --- a/code/mp3code/l3dq.c +++ b/code/mp3code/l3dq.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -55,200 +55,166 @@ int s[14];} sfBandTable[3] = ----------*/ /*--------------------------------*/ -static const int pretab[2][22] = -{ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 2, 2, 3, 3, 3, 2, 0}, +static const int pretab[2][22] = { + {0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 2, 2, 3, 3, 3, 2, 0}, }; - ////@@@@extern int nBand[2][22]; /* long = nBand[0][i], short = nBand[1][i] */ /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ /* two extra slots to do 1/sqrt(2) scaling for ms */ /* 4 extra slots to do 1/2 scaling for cvt to mono */ -static float look_global[256 + 2 + 4]; // effectively constant +static float look_global[256 + 2 + 4]; // effectively constant /*-------- scaling lookup x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) look_scale[scalefact_scale][preemp][scalefac] -----------------------*/ -static float look_scale[2][4][32]; // effectively constant +static float look_scale[2][4][32]; // effectively constant typedef float LS[4][32]; - /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ #define ISMAX 32 -static float look_pow[2 * ISMAX]; // effectively constant +static float look_pow[2 * ISMAX]; // effectively constant /*-- pow(2.0, -0.25*8.0*subblock_gain) --*/ -static float look_subblock[8]; // effectively constant +static float look_subblock[8]; // effectively constant /*-- reorder buffer ---*/ -static float re_buf[192][3]; // used by dequant() below, but only during func (as workspace) +static float re_buf[192][3]; // used by dequant() below, but only during func (as workspace) typedef float ARRAY3[3]; - /*=============================================================*/ -float *quant_init_global_addr() -{ - return look_global; -} +float *quant_init_global_addr() { return look_global; } /*-------------------------------------------------------------*/ -LS *quant_init_scale_addr() -{ - return look_scale; -} +LS *quant_init_scale_addr() { return look_scale; } /*-------------------------------------------------------------*/ -float *quant_init_pow_addr() -{ - return look_pow; -} +float *quant_init_pow_addr() { return look_pow; } /*-------------------------------------------------------------*/ -float *quant_init_subblock_addr() -{ - return look_subblock; -} +float *quant_init_subblock_addr() { return look_subblock; } /*=============================================================*/ -void dequant(SAMPLE Sample[], int *nsamp, - SCALEFACT * sf, - GR * gr, - CB_INFO * cb_info, int ncbl_mixed) -{ - int i, j; - int cb, n, w; - float x0, xs; - float xsb[3]; - double tmp; - int ncbl; - int cbs0; - ARRAY3 *buf; /* short block reorder */ - int nbands; - int i0; - int non_zero; - int cbmax[3]; - - nbands = *nsamp; - - - ncbl = 22; /* long block cb end */ - cbs0 = 12; /* short block cb start */ -/* ncbl_mixed = 8 or 6 mpeg1 or 2 */ - if (gr->block_type == 2) - { - ncbl = 0; - cbs0 = 0; - if (gr->mixed_block_flag) - { - ncbl = ncbl_mixed; - cbs0 = 3; - } - } -/* fill in cb_info -- */ - /* This doesn't seem used anywhere... - cb_info->lb_type = gr->block_type; - if (gr->block_type == 2) - cb_info->lb_type; - */ - cb_info->cbs0 = cbs0; - cb_info->ncbl = ncbl; - - cbmax[2] = cbmax[1] = cbmax[0] = 0; -/* global gain pre-adjusted by 2 if ms_mode, 0 otherwise */ - x0 = look_global[(2 + 4) + gr->global_gain]; - i = 0; -/*----- long blocks ---*/ - for (cb = 0; cb < ncbl; cb++) - { - non_zero = 0; - xs = x0 * look_scale[gr->scalefac_scale][pretab[gr->preflag][cb]][sf->l[cb]]; - n = pMP3Stream->nBand[0][cb]; - for (j = 0; j < n; j++, i++) - { - if (Sample[i].s == 0) - Sample[i].x = 0.0F; - else - { - non_zero = 1; - if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) - Sample[i].x = xs * look_pow[ISMAX + Sample[i].s]; - else - { - float tmpConst = (float)(1.0/3.0); - tmp = (double) Sample[i].s; - Sample[i].x = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); - } - } - } - if (non_zero) - cbmax[0] = cb; - if (i >= nbands) - break; - } - - cb_info->cbmax = cbmax[0]; - cb_info->cbtype = 0; // type = long - - if (cbs0 >= 12) - return; -/*--------------------------- -block type = 2 short blocks -----------------------------*/ - cbmax[2] = cbmax[1] = cbmax[0] = cbs0; - i0 = i; /* save for reorder */ - buf = re_buf; - for (w = 0; w < 3; w++) - xsb[w] = x0 * look_subblock[gr->subblock_gain[w]]; - for (cb = cbs0; cb < 13; cb++) - { - n = pMP3Stream->nBand[1][cb]; - for (w = 0; w < 3; w++) - { - non_zero = 0; - xs = xsb[w] * look_scale[gr->scalefac_scale][0][sf->s[w][cb]]; - for (j = 0; j < n; j++, i++) - { - if (Sample[i].s == 0) - buf[j][w] = 0.0F; - else - { - non_zero = 1; - if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) - buf[j][w] = xs * look_pow[ISMAX + Sample[i].s]; - else - { - float tmpConst = (float)(1.0/3.0); - tmp = (double) Sample[i].s; - buf[j][w] = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); - } - } - } - if (non_zero) - cbmax[w] = cb; - } - if (i >= nbands) - break; - buf += n; - } - - - memmove(&Sample[i0].x, &re_buf[0][0], sizeof(float) * (i - i0)); - - *nsamp = i; /* update nsamp */ - cb_info->cbmax_s[0] = cbmax[0]; - cb_info->cbmax_s[1] = cbmax[1]; - cb_info->cbmax_s[2] = cbmax[2]; - if (cbmax[1] > cbmax[0]) - cbmax[0] = cbmax[1]; - if (cbmax[2] > cbmax[0]) - cbmax[0] = cbmax[2]; - - cb_info->cbmax = cbmax[0]; - cb_info->cbtype = 1; /* type = short */ - - - return; +void dequant(SAMPLE Sample[], int *nsamp, SCALEFACT *sf, GR *gr, CB_INFO *cb_info, int ncbl_mixed) { + int i, j; + int cb, n, w; + float x0, xs; + float xsb[3]; + double tmp; + int ncbl; + int cbs0; + ARRAY3 *buf; /* short block reorder */ + int nbands; + int i0; + int non_zero; + int cbmax[3]; + + nbands = *nsamp; + + ncbl = 22; /* long block cb end */ + cbs0 = 12; /* short block cb start */ + /* ncbl_mixed = 8 or 6 mpeg1 or 2 */ + if (gr->block_type == 2) { + ncbl = 0; + cbs0 = 0; + if (gr->mixed_block_flag) { + ncbl = ncbl_mixed; + cbs0 = 3; + } + } + /* fill in cb_info -- */ + /* This doesn't seem used anywhere... + cb_info->lb_type = gr->block_type; + if (gr->block_type == 2) + cb_info->lb_type; + */ + cb_info->cbs0 = cbs0; + cb_info->ncbl = ncbl; + + cbmax[2] = cbmax[1] = cbmax[0] = 0; + /* global gain pre-adjusted by 2 if ms_mode, 0 otherwise */ + x0 = look_global[(2 + 4) + gr->global_gain]; + i = 0; + /*----- long blocks ---*/ + for (cb = 0; cb < ncbl; cb++) { + non_zero = 0; + xs = x0 * look_scale[gr->scalefac_scale][pretab[gr->preflag][cb]][sf->l[cb]]; + n = pMP3Stream->nBand[0][cb]; + for (j = 0; j < n; j++, i++) { + if (Sample[i].s == 0) + Sample[i].x = 0.0F; + else { + non_zero = 1; + if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) + Sample[i].x = xs * look_pow[ISMAX + Sample[i].s]; + else { + float tmpConst = (float)(1.0 / 3.0); + tmp = (double)Sample[i].s; + Sample[i].x = (float)(xs * tmp * pow(fabs(tmp), tmpConst)); + } + } + } + if (non_zero) + cbmax[0] = cb; + if (i >= nbands) + break; + } + + cb_info->cbmax = cbmax[0]; + cb_info->cbtype = 0; // type = long + + if (cbs0 >= 12) + return; + /*--------------------------- + block type = 2 short blocks + ----------------------------*/ + cbmax[2] = cbmax[1] = cbmax[0] = cbs0; + i0 = i; /* save for reorder */ + buf = re_buf; + for (w = 0; w < 3; w++) + xsb[w] = x0 * look_subblock[gr->subblock_gain[w]]; + for (cb = cbs0; cb < 13; cb++) { + n = pMP3Stream->nBand[1][cb]; + for (w = 0; w < 3; w++) { + non_zero = 0; + xs = xsb[w] * look_scale[gr->scalefac_scale][0][sf->s[w][cb]]; + for (j = 0; j < n; j++, i++) { + if (Sample[i].s == 0) + buf[j][w] = 0.0F; + else { + non_zero = 1; + if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) + buf[j][w] = xs * look_pow[ISMAX + Sample[i].s]; + else { + float tmpConst = (float)(1.0 / 3.0); + tmp = (double)Sample[i].s; + buf[j][w] = (float)(xs * tmp * pow(fabs(tmp), tmpConst)); + } + } + } + if (non_zero) + cbmax[w] = cb; + } + if (i >= nbands) + break; + buf += n; + } + + memmove(&Sample[i0].x, &re_buf[0][0], sizeof(float) * (i - i0)); + + *nsamp = i; /* update nsamp */ + cb_info->cbmax_s[0] = cbmax[0]; + cb_info->cbmax_s[1] = cbmax[1]; + cb_info->cbmax_s[2] = cbmax[2]; + if (cbmax[1] > cbmax[0]) + cbmax[0] = cbmax[1]; + if (cbmax[2] > cbmax[0]) + cbmax[0] = cbmax[2]; + + cb_info->cbmax = cbmax[0]; + cb_info->cbtype = 1; /* type = short */ + + return; } /*-------------------------------------------------------------*/ diff --git a/code/mp3code/l3init.c b/code/mp3code/l3init.c index 174bb39deb..3a6af45a92 100644 --- a/code/mp3code/l3init.c +++ b/code/mp3code/l3init.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -40,12 +40,10 @@ ____________________________________________________________________________*/ /* 8 bit lookup x = pow(2.0, 0.25*(global_gain-210)) */ float *quant_init_global_addr(); - /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ typedef float LS[4][32]; LS *quant_init_scale_addr(); - float *quant_init_pow_addr(); float *quant_init_subblock_addr(); @@ -56,169 +54,148 @@ iARRAY22 *quant_init_band_addr(); typedef float PAIR[2]; PAIR *alias_init_addr(); -static const float Ci[8] = -{ - -0.6f, -0.535f, -0.33f, -0.185f, -0.095f, -0.041f, -0.0142f, -0.0037f}; - +static const float Ci[8] = {-0.6f, -0.535f, -0.33f, -0.185f, -0.095f, -0.041f, -0.0142f, -0.0037f}; -void hwin_init(); /* hybrid windows -- */ +void hwin_init(); /* hybrid windows -- */ void imdct_init(); -typedef struct -{ - float *w; - float *w2; - void *coef; -} -IMDCT_INIT_BLOCK; +typedef struct { + float *w; + float *w2; + void *coef; +} IMDCT_INIT_BLOCK; void msis_init(); void msis_init_MPEG2(); /*=============================================================*/ -int L3table_init() -{ - int i; - float *x; - LS *ls; - int scalefact_scale, preemp, scalefac; - double tmp; - PAIR *csa; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { -/*================ quant ===============================*/ - - /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ - /* extra 2 for ms scaling by 1/sqrt(2) */ - /* extra 4 for cvt to mono scaling by 1/2 */ - x = quant_init_global_addr(); - for (i = 0; i < 256 + 2 + 4; i++) - x[i] = (float) pow(2.0, 0.25 * ((i - (2 + 4)) - 210 + GLOBAL_GAIN_SCALE)); - - - - /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ - ls = quant_init_scale_addr(); - for (scalefact_scale = 0; scalefact_scale < 2; scalefact_scale++) - { - for (preemp = 0; preemp < 4; preemp++) - { - for (scalefac = 0; scalefac < 32; scalefac++) - { - ls[scalefact_scale][preemp][scalefac] = - (float) pow(2.0, -0.5 * (1 + scalefact_scale) * (scalefac + preemp)); - } - } - } - - /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ - x = quant_init_pow_addr(); - for (i = 0; i < 64; i++) - { - tmp = i - 32; - x[i] = (float) (tmp * pow(fabs(tmp), (1.0 / 3.0))); - } - - - /*-- pow(2.0, -0.25*8.0*subblock_gain) 3 bits --*/ - x = quant_init_subblock_addr(); - for (i = 0; i < 8; i++) - { - x[i] = (float) pow(2.0, 0.25 * -8.0 * i); - } - - /*-------------------------*/ - // quant_init_sf_band(sr_index); replaced by code in sup.c - - -/*================ antialias ===============================*/ - // onceonly!!!!!!!!!!!!!!!!!!!!! - csa = alias_init_addr(); - for (i = 0; i < 8; i++) - { - csa[i][0] = (float) (1.0 / sqrt(1.0 + Ci[i] * Ci[i])); - csa[i][1] = (float) (Ci[i] / sqrt(1.0 + Ci[i] * Ci[i])); - } - } - - // these 4 are iOnceOnly-protected inside... - -/*================ msis ===============================*/ - msis_init(); - msis_init_MPEG2(); - -/*================ imdct ===============================*/ - imdct_init(); - -/*--- hybrid windows ------------*/ - hwin_init(); - - return 0; +int L3table_init() { + int i; + float *x; + LS *ls; + int scalefact_scale, preemp, scalefac; + double tmp; + PAIR *csa; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*================ quant ===============================*/ + + /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ + /* extra 2 for ms scaling by 1/sqrt(2) */ + /* extra 4 for cvt to mono scaling by 1/2 */ + x = quant_init_global_addr(); + for (i = 0; i < 256 + 2 + 4; i++) + x[i] = (float)pow(2.0, 0.25 * ((i - (2 + 4)) - 210 + GLOBAL_GAIN_SCALE)); + + /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ + ls = quant_init_scale_addr(); + for (scalefact_scale = 0; scalefact_scale < 2; scalefact_scale++) { + for (preemp = 0; preemp < 4; preemp++) { + for (scalefac = 0; scalefac < 32; scalefac++) { + ls[scalefact_scale][preemp][scalefac] = (float)pow(2.0, -0.5 * (1 + scalefact_scale) * (scalefac + preemp)); + } + } + } + + /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ + x = quant_init_pow_addr(); + for (i = 0; i < 64; i++) { + tmp = i - 32; + x[i] = (float)(tmp * pow(fabs(tmp), (1.0 / 3.0))); + } + + /*-- pow(2.0, -0.25*8.0*subblock_gain) 3 bits --*/ + x = quant_init_subblock_addr(); + for (i = 0; i < 8; i++) { + x[i] = (float)pow(2.0, 0.25 * -8.0 * i); + } + + /*-------------------------*/ + // quant_init_sf_band(sr_index); replaced by code in sup.c + + /*================ antialias ===============================*/ + // onceonly!!!!!!!!!!!!!!!!!!!!! + csa = alias_init_addr(); + for (i = 0; i < 8; i++) { + csa[i][0] = (float)(1.0 / sqrt(1.0 + Ci[i] * Ci[i])); + csa[i][1] = (float)(Ci[i] / sqrt(1.0 + Ci[i] * Ci[i])); + } + } + + // these 4 are iOnceOnly-protected inside... + + /*================ msis ===============================*/ + msis_init(); + msis_init_MPEG2(); + + /*================ imdct ===============================*/ + imdct_init(); + + /*--- hybrid windows ------------*/ + hwin_init(); + + return 0; } /*====================================================================*/ typedef float ARRAY36[36]; ARRAY36 *hwin_init_addr(); /*--------------------------------------------------------------------*/ -void hwin_init() -{ - int i, j; - double pi; - ARRAY36 *win; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - win = hwin_init_addr(); - - pi = 4.0 * atan(1.0); - - /* type 0 */ - for (i = 0; i < 36; i++) - win[0][i] = (float) sin(pi / 36 * (i + 0.5)); - - /* type 1 */ - for (i = 0; i < 18; i++) - win[1][i] = (float) sin(pi / 36 * (i + 0.5)); - for (i = 18; i < 24; i++) - win[1][i] = 1.0F; - for (i = 24; i < 30; i++) - win[1][i] = (float) sin(pi / 12 * (i + 0.5 - 18)); - for (i = 30; i < 36; i++) - win[1][i] = 0.0F; - - /* type 3 */ - for (i = 0; i < 6; i++) - win[3][i] = 0.0F; - for (i = 6; i < 12; i++) - win[3][i] = (float) sin(pi / 12 * (i + 0.5 - 6)); - for (i = 12; i < 18; i++) - win[3][i] = 1.0F; - for (i = 18; i < 36; i++) - win[3][i] = (float) sin(pi / 36 * (i + 0.5)); - - /* type 2 */ - for (i = 0; i < 12; i++) - win[2][i] = (float) sin(pi / 12 * (i + 0.5)); - for (i = 12; i < 36; i++) - win[2][i] = 0.0F; - - /*--- invert signs by region to match mdct 18pt --> 36pt mapping */ - for (j = 0; j < 4; j++) - { - if (j == 2) - continue; - for (i = 9; i < 36; i++) - win[j][i] = -win[j][i]; - } - - /*-- invert signs for short blocks --*/ - for (i = 3; i < 12; i++) - win[2][i] = -win[2][i]; - } +void hwin_init() { + int i, j; + double pi; + ARRAY36 *win; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + win = hwin_init_addr(); + + pi = 4.0 * atan(1.0); + + /* type 0 */ + for (i = 0; i < 36; i++) + win[0][i] = (float)sin(pi / 36 * (i + 0.5)); + + /* type 1 */ + for (i = 0; i < 18; i++) + win[1][i] = (float)sin(pi / 36 * (i + 0.5)); + for (i = 18; i < 24; i++) + win[1][i] = 1.0F; + for (i = 24; i < 30; i++) + win[1][i] = (float)sin(pi / 12 * (i + 0.5 - 18)); + for (i = 30; i < 36; i++) + win[1][i] = 0.0F; + + /* type 3 */ + for (i = 0; i < 6; i++) + win[3][i] = 0.0F; + for (i = 6; i < 12; i++) + win[3][i] = (float)sin(pi / 12 * (i + 0.5 - 6)); + for (i = 12; i < 18; i++) + win[3][i] = 1.0F; + for (i = 18; i < 36; i++) + win[3][i] = (float)sin(pi / 36 * (i + 0.5)); + + /* type 2 */ + for (i = 0; i < 12; i++) + win[2][i] = (float)sin(pi / 12 * (i + 0.5)); + for (i = 12; i < 36; i++) + win[2][i] = 0.0F; + + /*--- invert signs by region to match mdct 18pt --> 36pt mapping */ + for (j = 0; j < 4; j++) { + if (j == 2) + continue; + for (i = 9; i < 36; i++) + win[j][i] = -win[j][i]; + } + + /*-- invert signs for short blocks --*/ + for (i = 3; i < 12; i++) + win[2][i] = -win[2][i]; + } } /*=============================================================*/ typedef float ARRAY4[4]; @@ -226,115 +203,106 @@ const IMDCT_INIT_BLOCK *imdct_init_addr_18(); const IMDCT_INIT_BLOCK *imdct_init_addr_6(); /*-------------------------------------------------------------*/ -void imdct_init() -{ - int k, p, n; - double t, pi; - const IMDCT_INIT_BLOCK *addr; - float *w, *w2; - float *v, *v2, *coef87; - ARRAY4 *coef; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - /*--- 18 point --*/ - addr = imdct_init_addr_18(); - w = addr->w; - w2 = addr->w2; - coef = addr->coef; - /*----*/ - n = 18; - pi = 4.0 * atan(1.0); - t = pi / (4 * n); - for (p = 0; p < n; p++) - w[p] = (float) (2.0 * cos(t * (2 * p + 1))); - for (p = 0; p < 9; p++) - w2[p] = (float) (2.0 *cos(2 * t * (2 * p + 1))); - - t = pi / (2 * n); - for (k = 0; k < 9; k++) - { - for (p = 0; p < 4; p++) - coef[k][p] = (float) cos(t * (2 * k) * (2 * p + 1)); - } - - /*--- 6 point */ - addr = imdct_init_addr_6(); - v = addr->w; - v2 = addr->w2; - coef87 = addr->coef; - /*----*/ - n = 6; - pi = 4.0 * atan(1.0); - t = pi / (4 * n); - for (p = 0; p < n; p++) - v[p] = (float) (2.0 *cos(t * (2 * p + 1))); - - for (p = 0; p < 3; p++) - v2[p] = (float) (2.0 *cos(2 * t * (2 * p + 1))); - - t = pi / (2 * n); - k = 1; - p = 0; - *coef87 = (float) cos(t * (2 * k) * (2 * p + 1)); - /* adjust scaling to save a few mults */ - for (p = 0; p < 6; p++) - v[p] = v[p] / 2.0f; - *coef87 = (float) (2.0 *(*coef87)); - - } +void imdct_init() { + int k, p, n; + double t, pi; + const IMDCT_INIT_BLOCK *addr; + float *w, *w2; + float *v, *v2, *coef87; + ARRAY4 *coef; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*--- 18 point --*/ + addr = imdct_init_addr_18(); + w = addr->w; + w2 = addr->w2; + coef = addr->coef; + /*----*/ + n = 18; + pi = 4.0 * atan(1.0); + t = pi / (4 * n); + for (p = 0; p < n; p++) + w[p] = (float)(2.0 * cos(t * (2 * p + 1))); + for (p = 0; p < 9; p++) + w2[p] = (float)(2.0 * cos(2 * t * (2 * p + 1))); + + t = pi / (2 * n); + for (k = 0; k < 9; k++) { + for (p = 0; p < 4; p++) + coef[k][p] = (float)cos(t * (2 * k) * (2 * p + 1)); + } + + /*--- 6 point */ + addr = imdct_init_addr_6(); + v = addr->w; + v2 = addr->w2; + coef87 = addr->coef; + /*----*/ + n = 6; + pi = 4.0 * atan(1.0); + t = pi / (4 * n); + for (p = 0; p < n; p++) + v[p] = (float)(2.0 * cos(t * (2 * p + 1))); + + for (p = 0; p < 3; p++) + v2[p] = (float)(2.0 * cos(2 * t * (2 * p + 1))); + + t = pi / (2 * n); + k = 1; + p = 0; + *coef87 = (float)cos(t * (2 * k) * (2 * p + 1)); + /* adjust scaling to save a few mults */ + for (p = 0; p < 6; p++) + v[p] = v[p] / 2.0f; + *coef87 = (float)(2.0 * (*coef87)); + } } /*===============================================================*/ typedef float ARRAY8_2[8][2]; ARRAY8_2 *msis_init_addr(); /*-------------------------------------------------------------*/ -void msis_init() -{ - int i; - double s, c; - double pi; - double t; - ARRAY8_2 *lr; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - lr = msis_init_addr(); - - - pi = 4.0 * atan(1.0); - t = pi / 12.0; - for (i = 0; i < 7; i++) - { - s = sin(i * t); - c = cos(i * t); +void msis_init() { + int i; + double s, c; + double pi; + double t; + ARRAY8_2 *lr; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + lr = msis_init_addr(); + + pi = 4.0 * atan(1.0); + t = pi / 12.0; + for (i = 0; i < 7; i++) { + s = sin(i * t); + c = cos(i * t); + /* ms_mode = 0 */ + lr[0][i][0] = (float)(s / (s + c)); + lr[0][i][1] = (float)(c / (s + c)); + /* ms_mode = 1 */ + lr[1][i][0] = (float)(sqrt(2.0) * (s / (s + c))); + lr[1][i][1] = (float)(sqrt(2.0) * (c / (s + c))); + } + /* sf = 7 */ /* ms_mode = 0 */ - lr[0][i][0] = (float) (s / (s + c)); - lr[0][i][1] = (float) (c / (s + c)); - /* ms_mode = 1 */ - lr[1][i][0] = (float) (sqrt(2.0) * (s / (s + c))); - lr[1][i][1] = (float) (sqrt(2.0) * (c / (s + c))); - } - /* sf = 7 */ - /* ms_mode = 0 */ - lr[0][i][0] = 1.0f; - lr[0][i][1] = 0.0f; - /* ms_mode = 1, in is bands is routine does ms processing */ - lr[1][i][0] = 1.0f; - lr[1][i][1] = 1.0f; - - - /*------- - for(i=0;i<21;i++) nBand[0][i] = - sfBandTable[sr_index].l[i+1] - sfBandTable[sr_index].l[i]; - for(i=0;i<12;i++) nBand[1][i] = - sfBandTable[sr_index].s[i+1] - sfBandTable[sr_index].s[i]; - -------------*/ - } + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + /* ms_mode = 1, in is bands is routine does ms processing */ + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; + + /*------- + for(i=0;i<21;i++) nBand[0][i] = + sfBandTable[sr_index].l[i+1] - sfBandTable[sr_index].l[i]; + for(i=0;i<12;i++) nBand[1][i] = + sfBandTable[sr_index].s[i+1] - sfBandTable[sr_index].s[i]; + -------------*/ + } } /*-------------------------------------------------------------*/ /*===============================================================*/ @@ -342,75 +310,58 @@ typedef float ARRAY2_64_2[2][64][2]; ARRAY2_64_2 *msis_init_addr_MPEG2(); /*-------------------------------------------------------------*/ -void msis_init_MPEG2() -{ - int k, n; - double t; - ARRAY2_64_2 *lr2; - int intensity_scale, ms_mode, sf, sflen; - float ms_factor[2]; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - ms_factor[0] = 1.0; - ms_factor[1] = (float) sqrt(2.0); - - lr2 = msis_init_addr_MPEG2(); - - /* intensity stereo MPEG2 */ - /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ - - for (intensity_scale = 0; intensity_scale < 2; intensity_scale++) - { - t = pow(2.0, -0.25 * (1 + intensity_scale)); - for (ms_mode = 0; ms_mode < 2; ms_mode++) - { - - n = 1; - k = 0; - for (sflen = 0; sflen < 6; sflen++) - { - for (sf = 0; sf < (n - 1); sf++, k++) - { - if (sf == 0) - { - lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; - lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; - } - else if ((sf & 1)) - { - lr2[intensity_scale][ms_mode][k][0] = - (float) (ms_factor[ms_mode] * pow(t, (sf + 1) / 2)); - lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; - } - else - { - lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; - lr2[intensity_scale][ms_mode][k][1] = - (float) (ms_factor[ms_mode] * pow(t, sf / 2)); - } +void msis_init_MPEG2() { + int k, n; + double t; + ARRAY2_64_2 *lr2; + int intensity_scale, ms_mode, sf, sflen; + float ms_factor[2]; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + ms_factor[0] = 1.0; + ms_factor[1] = (float)sqrt(2.0); + + lr2 = msis_init_addr_MPEG2(); + + /* intensity stereo MPEG2 */ + /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ + + for (intensity_scale = 0; intensity_scale < 2; intensity_scale++) { + t = pow(2.0, -0.25 * (1 + intensity_scale)); + for (ms_mode = 0; ms_mode < 2; ms_mode++) { + + n = 1; + k = 0; + for (sflen = 0; sflen < 6; sflen++) { + for (sf = 0; sf < (n - 1); sf++, k++) { + if (sf == 0) { + lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; + lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; + } else if ((sf & 1)) { + lr2[intensity_scale][ms_mode][k][0] = (float)(ms_factor[ms_mode] * pow(t, (sf + 1) / 2)); + lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; + } else { + lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; + lr2[intensity_scale][ms_mode][k][1] = (float)(ms_factor[ms_mode] * pow(t, sf / 2)); + } + } + + /* illegal is_pos used to do ms processing */ + if (ms_mode == 0) { /* ms_mode = 0 */ + lr2[intensity_scale][ms_mode][k][0] = 1.0f; + lr2[intensity_scale][ms_mode][k][1] = 0.0f; + } else { + /* ms_mode = 1, in is bands is routine does ms processing */ + lr2[intensity_scale][ms_mode][k][0] = 1.0f; + lr2[intensity_scale][ms_mode][k][1] = 1.0f; + } + k++; + n = n + n; + } } - - /* illegal is_pos used to do ms processing */ - if (ms_mode == 0) - { /* ms_mode = 0 */ - lr2[intensity_scale][ms_mode][k][0] = 1.0f; - lr2[intensity_scale][ms_mode][k][1] = 0.0f; - } - else - { - /* ms_mode = 1, in is bands is routine does ms processing */ - lr2[intensity_scale][ms_mode][k][0] = 1.0f; - lr2[intensity_scale][ms_mode][k][1] = 1.0f; - } - k++; - n = n + n; - } - } - } - } - + } + } } /*-------------------------------------------------------------*/ diff --git a/code/mp3code/mdct.c b/code/mp3code/mdct.c index 59b5d19bc9..e66e7303ce 100644 --- a/code/mp3code/mdct.c +++ b/code/mp3code/mdct.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -31,7 +31,7 @@ Layer III cos transform for n=18, n=6 computes c[k] = Sum( cos((pi/4*n)*(2*k+1)*(2*p+1))*f[p] ) - k = 0, ...n-1, p = 0...n-1 + k = 0, ...n-1, p = 0...n-1 inplace ok. @@ -43,187 +43,156 @@ inplace ok. #include #include - /*------ 18 point xform -------*/ -float mdct18w[18]; // effectively constant -float mdct18w2[9]; // " " -float coef[9][4]; // " " - -float mdct6_3v[6]; // " " -float mdct6_3v2[3]; // " " -float coef87; // " " - -typedef struct -{ - float *w; - float *w2; - void *coef; -} -IMDCT_INIT_BLOCK; +float mdct18w[18]; // effectively constant +float mdct18w2[9]; // " " +float coef[9][4]; // " " -static const IMDCT_INIT_BLOCK imdct_info_18 = -{mdct18w, mdct18w2, coef}; -static const IMDCT_INIT_BLOCK imdct_info_6 = -{mdct6_3v, mdct6_3v2, &coef87}; +float mdct6_3v[6]; // " " +float mdct6_3v2[3]; // " " +float coef87; // " " +typedef struct { + float *w; + float *w2; + void *coef; +} IMDCT_INIT_BLOCK; +static const IMDCT_INIT_BLOCK imdct_info_18 = {mdct18w, mdct18w2, coef}; +static const IMDCT_INIT_BLOCK imdct_info_6 = {mdct6_3v, mdct6_3v2, &coef87}; /*====================================================================*/ -const IMDCT_INIT_BLOCK *imdct_init_addr_18() -{ - return &imdct_info_18; -} -const IMDCT_INIT_BLOCK *imdct_init_addr_6() -{ - return &imdct_info_6; -} +const IMDCT_INIT_BLOCK *imdct_init_addr_18() { return &imdct_info_18; } +const IMDCT_INIT_BLOCK *imdct_init_addr_6() { return &imdct_info_6; } /*--------------------------------------------------------------------*/ -void imdct18(float f[18]) /* 18 point */ +void imdct18(float f[18]) /* 18 point */ { - int p; - float a[9], b[9]; - float ap, bp, a8p, b8p; - float g1, g2; - - - for (p = 0; p < 4; p++) - { - g1 = mdct18w[p] * f[p]; - g2 = mdct18w[17 - p] * f[17 - p]; - ap = g1 + g2; // a[p] - - bp = mdct18w2[p] * (g1 - g2); // b[p] - - g1 = mdct18w[8 - p] * f[8 - p]; - g2 = mdct18w[9 + p] * f[9 + p]; - a8p = g1 + g2; // a[8-p] - - b8p = mdct18w2[8 - p] * (g1 - g2); // b[8-p] - - a[p] = ap + a8p; - a[5 + p] = ap - a8p; - b[p] = bp + b8p; - b[5 + p] = bp - b8p; - } - g1 = mdct18w[p] * f[p]; - g2 = mdct18w[17 - p] * f[17 - p]; - a[p] = g1 + g2; - b[p] = mdct18w2[p] * (g1 - g2); - - - f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); - f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); - - f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] - + coef[1][3] * a[8]; - f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] - + coef[1][3] * b[8] - f[1]; - f[1] = f[1] - f[0]; - f[2] = f[2] - f[1]; - - f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] - + coef[2][3] * a[3] - a[4]; - f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] - + coef[2][3] * b[3] - b[4] - f[3]; - f[3] = f[3] - f[2]; - f[4] = f[4] - f[3]; - - f[6] = coef[3][0] * (a[5] - a[7] - a[8]); - f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; - f[5] = f[5] - f[4]; - f[6] = f[6] - f[5]; - - f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] - + coef[4][3] * a[3] + a[4]; - f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] - + coef[4][3] * b[3] + b[4] - f[7]; - f[7] = f[7] - f[6]; - f[8] = f[8] - f[7]; - - f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] - + coef[5][3] * a[8]; - f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] - + coef[5][3] * b[8] - f[9]; - f[9] = f[9] - f[8]; - f[10] = f[10] - f[9]; - - f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; - f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; - f[11] = f[11] - f[10]; - f[12] = f[12] - f[11]; - - f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] - + coef[7][3] * a[8]; - f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] - + coef[7][3] * b[8] - f[13]; - f[13] = f[13] - f[12]; - f[14] = f[14] - f[13]; - - f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] - + coef[8][3] * a[3] + a[4]; - f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] - + coef[8][3] * b[3] + b[4] - f[15]; - f[15] = f[15] - f[14]; - f[16] = f[16] - f[15]; - f[17] = f[17] - f[16]; - - - return; + int p; + float a[9], b[9]; + float ap, bp, a8p, b8p; + float g1, g2; + + for (p = 0; p < 4; p++) { + g1 = mdct18w[p] * f[p]; + g2 = mdct18w[17 - p] * f[17 - p]; + ap = g1 + g2; // a[p] + + bp = mdct18w2[p] * (g1 - g2); // b[p] + + g1 = mdct18w[8 - p] * f[8 - p]; + g2 = mdct18w[9 + p] * f[9 + p]; + a8p = g1 + g2; // a[8-p] + + b8p = mdct18w2[8 - p] * (g1 - g2); // b[8-p] + + a[p] = ap + a8p; + a[5 + p] = ap - a8p; + b[p] = bp + b8p; + b[5 + p] = bp - b8p; + } + g1 = mdct18w[p] * f[p]; + g2 = mdct18w[17 - p] * f[17 - p]; + a[p] = g1 + g2; + b[p] = mdct18w2[p] * (g1 - g2); + + f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); + f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); + + f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] + coef[1][3] * a[8]; + f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] + coef[1][3] * b[8] - f[1]; + f[1] = f[1] - f[0]; + f[2] = f[2] - f[1]; + + f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] + coef[2][3] * a[3] - a[4]; + f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] + coef[2][3] * b[3] - b[4] - f[3]; + f[3] = f[3] - f[2]; + f[4] = f[4] - f[3]; + + f[6] = coef[3][0] * (a[5] - a[7] - a[8]); + f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; + f[5] = f[5] - f[4]; + f[6] = f[6] - f[5]; + + f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] + coef[4][3] * a[3] + a[4]; + f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] + coef[4][3] * b[3] + b[4] - f[7]; + f[7] = f[7] - f[6]; + f[8] = f[8] - f[7]; + + f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] + coef[5][3] * a[8]; + f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] + coef[5][3] * b[8] - f[9]; + f[9] = f[9] - f[8]; + f[10] = f[10] - f[9]; + + f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; + f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; + f[11] = f[11] - f[10]; + f[12] = f[12] - f[11]; + + f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] + coef[7][3] * a[8]; + f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] + coef[7][3] * b[8] - f[13]; + f[13] = f[13] - f[12]; + f[14] = f[14] - f[13]; + + f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] + coef[8][3] * a[3] + a[4]; + f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] + coef[8][3] * b[3] + b[4] - f[15]; + f[15] = f[15] - f[14]; + f[16] = f[16] - f[15]; + f[17] = f[17] - f[16]; + + return; } /*--------------------------------------------------------------------*/ /* does 3, 6 pt dct. changes order from f[i][window] c[window][i] */ -void imdct6_3(float f[]) /* 6 point */ +void imdct6_3(float f[]) /* 6 point */ { - int w; - float buf[18]; - float *a, *c; // b[i] = a[3+i] - - float g1, g2; - float a02, b02; - - c = f; - a = buf; - for (w = 0; w < 3; w++) - { - g1 = mdct6_3v[0] * f[3 * 0]; - g2 = mdct6_3v[5] * f[3 * 5]; - a[0] = g1 + g2; - a[3 + 0] = mdct6_3v2[0] * (g1 - g2); - - g1 = mdct6_3v[1] * f[3 * 1]; - g2 = mdct6_3v[4] * f[3 * 4]; - a[1] = g1 + g2; - a[3 + 1] = mdct6_3v2[1] * (g1 - g2); - - g1 = mdct6_3v[2] * f[3 * 2]; - g2 = mdct6_3v[3] * f[3 * 3]; - a[2] = g1 + g2; - a[3 + 2] = mdct6_3v2[2] * (g1 - g2); - - a += 6; - f++; - } - - a = buf; - for (w = 0; w < 3; w++) - { - a02 = (a[0] + a[2]); - b02 = (a[3 + 0] + a[3 + 2]); - c[0] = a02 + a[1]; - c[1] = b02 + a[3 + 1]; - c[2] = coef87 * (a[0] - a[2]); - c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; - c[1] = c[1] - c[0]; - c[2] = c[2] - c[1]; - c[4] = a02 - a[1] - a[1]; - c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; - c[3] = c[3] - c[2]; - c[4] = c[4] - c[3]; - c[5] = c[5] - c[4]; - a += 6; - c += 6; - } - - return; + int w; + float buf[18]; + float *a, *c; // b[i] = a[3+i] + + float g1, g2; + float a02, b02; + + c = f; + a = buf; + for (w = 0; w < 3; w++) { + g1 = mdct6_3v[0] * f[3 * 0]; + g2 = mdct6_3v[5] * f[3 * 5]; + a[0] = g1 + g2; + a[3 + 0] = mdct6_3v2[0] * (g1 - g2); + + g1 = mdct6_3v[1] * f[3 * 1]; + g2 = mdct6_3v[4] * f[3 * 4]; + a[1] = g1 + g2; + a[3 + 1] = mdct6_3v2[1] * (g1 - g2); + + g1 = mdct6_3v[2] * f[3 * 2]; + g2 = mdct6_3v[3] * f[3 * 3]; + a[2] = g1 + g2; + a[3 + 2] = mdct6_3v2[2] * (g1 - g2); + + a += 6; + f++; + } + + a = buf; + for (w = 0; w < 3; w++) { + a02 = (a[0] + a[2]); + b02 = (a[3 + 0] + a[3 + 2]); + c[0] = a02 + a[1]; + c[1] = b02 + a[3 + 1]; + c[2] = coef87 * (a[0] - a[2]); + c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; + c[1] = c[1] - c[0]; + c[2] = c[2] - c[1]; + c[4] = a02 - a[1] - a[1]; + c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; + c[3] = c[3] - c[2]; + c[4] = c[4] - c[3]; + c[5] = c[5] - c[4]; + a += 6; + c += 6; + } + + return; } /*--------------------------------------------------------------------*/ diff --git a/code/mp3code/mhead.c b/code/mp3code/mhead.c index 61340a93e8..4920f2a8ea 100644 --- a/code/mp3code/mhead.c +++ b/code/mp3code/mhead.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -40,155 +40,114 @@ ____________________________________________________________________________*/ #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ -static const int mp_br_table[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, - {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0}}; -static const int mp_sr20_table[2][4] = -{{441, 480, 320, -999}, {882, 960, 640, -999}}; - -static const int mp_br_tableL1[2][16] = -{{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0},/* mpeg2 */ - {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0}}; - -static const int mp_br_tableL3[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ - {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; +static const int mp_br_table[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, + {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0}}; +static const int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; +static const int mp_br_tableL1[2][16] = {{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0}, /* mpeg2 */ + {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0}}; +static const int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ + {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; static int find_sync(unsigned char *buf, int n); static int sync_scan(unsigned char *buf, int n, int i0); static int sync_test(unsigned char *buf, int n, int isync, int padbytes); - /*--------------------------------------------------------------*/ -int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD * h) -{ - int framebytes; - int mpeg25_flag; - - if (n > 10000) - n = 10000; /* limit scan for free format */ - - - - h->sync = 0; - //if ((buf[0] == 0xFF) && ((buf[1] & 0xF0) == 0xF0)) - if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xF0)) - { - mpeg25_flag = 0; // mpeg 1 & 2 - - } - else if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xE0)) - { - mpeg25_flag = 1; // mpeg 2.5 - - } - else - return 0; // sync fail - - h->sync = 1; - if (mpeg25_flag) - h->sync = 2; //low bit clear signals mpeg25 (as in 0xFFE) - - h->id = (buf[0+1] & 0x08) >> 3; - h->option = (buf[0+1] & 0x06) >> 1; - h->prot = (buf[0+1] & 0x01); - - h->br_index = (buf[0+2] & 0xf0) >> 4; - h->sr_index = (buf[0+2] & 0x0c) >> 2; - h->pad = (buf[0+2] & 0x02) >> 1; - h->private_bit = (buf[0+2] & 0x01); - h->mode = (buf[0+3] & 0xc0) >> 6; - h->mode_ext = (buf[0+3] & 0x30) >> 4; - h->cr = (buf[0+3] & 0x08) >> 3; - h->original = (buf[0+3] & 0x04) >> 2; - h->emphasis = (buf[0+3] & 0x03); - - -// if( mpeg25_flag ) { - // if( h->sr_index == 2 ) return 0; // fail 8khz - //} - - -/* compute framebytes for Layer I, II, III */ - if (h->option < 1) - return 0; - if (h->option > 3) - return 0; - - framebytes = 0; - - if (h->br_index > 0) - { - if (h->option == 3) - { /* layer I */ - framebytes = - 240 * mp_br_tableL1[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - framebytes = 4 * framebytes; - } - else if (h->option == 2) - { /* layer II */ - framebytes = - 2880 * mp_br_table[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else if (h->option == 1) - { /* layer III */ - if (h->id) - { // mpeg1 - - framebytes = - 2880 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else - { // mpeg2 - - if (mpeg25_flag) - { // mpeg2.2 - - framebytes = - 2880 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else - { - framebytes = - 1440 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - } - } - } - else - framebytes = find_sync(buf, n); /* free format */ - - return framebytes; +int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD *h) { + int framebytes; + int mpeg25_flag; + + if (n > 10000) + n = 10000; /* limit scan for free format */ + + h->sync = 0; + // if ((buf[0] == 0xFF) && ((buf[1] & 0xF0) == 0xF0)) + if ((buf[0] == 0xFF) && ((buf[0 + 1] & 0xF0) == 0xF0)) { + mpeg25_flag = 0; // mpeg 1 & 2 + + } else if ((buf[0] == 0xFF) && ((buf[0 + 1] & 0xF0) == 0xE0)) { + mpeg25_flag = 1; // mpeg 2.5 + + } else + return 0; // sync fail + + h->sync = 1; + if (mpeg25_flag) + h->sync = 2; // low bit clear signals mpeg25 (as in 0xFFE) + + h->id = (buf[0 + 1] & 0x08) >> 3; + h->option = (buf[0 + 1] & 0x06) >> 1; + h->prot = (buf[0 + 1] & 0x01); + + h->br_index = (buf[0 + 2] & 0xf0) >> 4; + h->sr_index = (buf[0 + 2] & 0x0c) >> 2; + h->pad = (buf[0 + 2] & 0x02) >> 1; + h->private_bit = (buf[0 + 2] & 0x01); + h->mode = (buf[0 + 3] & 0xc0) >> 6; + h->mode_ext = (buf[0 + 3] & 0x30) >> 4; + h->cr = (buf[0 + 3] & 0x08) >> 3; + h->original = (buf[0 + 3] & 0x04) >> 2; + h->emphasis = (buf[0 + 3] & 0x03); + + // if( mpeg25_flag ) { + // if( h->sr_index == 2 ) return 0; // fail 8khz + //} + + /* compute framebytes for Layer I, II, III */ + if (h->option < 1) + return 0; + if (h->option > 3) + return 0; + + framebytes = 0; + + if (h->br_index > 0) { + if (h->option == 3) { /* layer I */ + framebytes = 240 * mp_br_tableL1[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + framebytes = 4 * framebytes; + } else if (h->option == 2) { /* layer II */ + framebytes = 2880 * mp_br_table[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else if (h->option == 1) { /* layer III */ + if (h->id) { // mpeg1 + + framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else { // mpeg2 + + if (mpeg25_flag) { // mpeg2.2 + + framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else { + framebytes = 1440 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } + } + } + } else + framebytes = find_sync(buf, n); /* free format */ + + return framebytes; } int head_info3(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int *br, unsigned int *searchForward) { unsigned int pBuf = 0; // jdw insertion... - while ((pBuf < n) && !((buf[pBuf] == 0xFF) && - ((buf[pBuf+1] & 0xF0) == 0xF0 || (buf[pBuf+1] & 0xF0) == 0xE0))) - { + while ((pBuf < n) && !((buf[pBuf] == 0xFF) && ((buf[pBuf + 1] & 0xF0) == 0xF0 || (buf[pBuf + 1] & 0xF0) == 0xE0))) { pBuf++; - } + } - if (pBuf == n) return 0; + if (pBuf == n) + return 0; - *searchForward = pBuf; - return head_info2(&(buf[pBuf]),n,h,br); + *searchForward = pBuf; + return head_info2(&(buf[pBuf]), n, h, br); } /*--------------------------------------------------------------*/ -int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br) -{ +int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int *br) { int framebytes; /*--- return br (in bits/sec) in addition to frame bytes ---*/ @@ -200,129 +159,115 @@ int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br) if (framebytes == 0) return 0; - switch (h->option) + switch (h->option) { + case 1: /* layer III */ { - case 1: /* layer III */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_tableL3[h->id][h->br_index]; - else - { - if (h->id) // mpeg1 - - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); - else - { // mpeg2 + if (h->br_index > 0) + *br = 1000 * mp_br_tableL3[h->id][h->br_index]; + else { + if (h->id) // mpeg1 - if ((h->sync & 1) == 0) // flags mpeg25 + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); + else { // mpeg2 - *br = 500 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); - } + if ((h->sync & 1) == 0) // flags mpeg25 + + *br = 500 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); } } - break; - - case 2: /* layer II */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_table[h->id][h->br_index]; - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); - } - break; - - case 3: /* layer I */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_tableL1[h->id][h->br_index]; - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (48 * 20); - } - break; + } break; - default: + case 2: /* layer II */ + { + if (h->br_index > 0) + *br = 1000 * mp_br_table[h->id][h->br_index]; + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); + } break; - return 0; // fuck knows what this is, but it ain't one of ours... - } + case 3: /* layer I */ + { + if (h->br_index > 0) + *br = 1000 * mp_br_tableL1[h->id][h->br_index]; + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (48 * 20); + } break; + default: + + return 0; // fuck knows what this is, but it ain't one of ours... + } return framebytes; } /*--------------------------------------------------------------*/ -static int compare(unsigned char *buf, unsigned char *buf2) -{ - if (buf[0] != buf2[0]) - return 0; - if (buf[1] != buf2[1]) - return 0; - return 1; +static int compare(unsigned char *buf, unsigned char *buf2) { + if (buf[0] != buf2[0]) + return 0; + if (buf[1] != buf2[1]) + return 0; + return 1; } /*----------------------------------------------------------*/ /*-- does not scan for initial sync, initial sync assumed --*/ -static int find_sync(unsigned char *buf, int n) -{ - int i0, isync, nmatch, pad; - int padbytes, option; - -/* mod 4/12/95 i0 change from 72, allows as low as 8kbits for mpeg1 */ - i0 = 24; - padbytes = 1; - option = (buf[1] & 0x06) >> 1; - if (option == 3) - { - padbytes = 4; - i0 = 24; /* for shorter layer I frames */ - } - - pad = (buf[2] & 0x02) >> 1; - - n -= 3; /* need 3 bytes of header */ - - while (i0 < 2000) - { - isync = sync_scan(buf, n, i0); - i0 = isync + 1; - isync -= pad; - if (isync <= 0) - return 0; - nmatch = sync_test(buf, n, isync, padbytes); - if (nmatch > 0) - return isync; - } - - return 0; +static int find_sync(unsigned char *buf, int n) { + int i0, isync, nmatch, pad; + int padbytes, option; + + /* mod 4/12/95 i0 change from 72, allows as low as 8kbits for mpeg1 */ + i0 = 24; + padbytes = 1; + option = (buf[1] & 0x06) >> 1; + if (option == 3) { + padbytes = 4; + i0 = 24; /* for shorter layer I frames */ + } + + pad = (buf[2] & 0x02) >> 1; + + n -= 3; /* need 3 bytes of header */ + + while (i0 < 2000) { + isync = sync_scan(buf, n, i0); + i0 = isync + 1; + isync -= pad; + if (isync <= 0) + return 0; + nmatch = sync_test(buf, n, isync, padbytes); + if (nmatch > 0) + return isync; + } + + return 0; } /*------------------------------------------------------*/ /*---- scan for next sync, assume start is valid -------*/ /*---- return number bytes to next sync ----------------*/ -static int sync_scan(unsigned char *buf, int n, int i0) -{ - int i; +static int sync_scan(unsigned char *buf, int n, int i0) { + int i; - for (i = i0; i < n; i++) - if (compare(buf, buf + i)) - return i; + for (i = i0; i < n; i++) + if (compare(buf, buf + i)) + return i; - return 0; + return 0; } /*------------------------------------------------------*/ /*- test consecutative syncs, input isync without pad --*/ -static int sync_test(unsigned char *buf, int n, int isync, int padbytes) -{ - int i, nmatch, pad; - - nmatch = 0; - for (i = 0;;) - { - pad = padbytes * ((buf[i + 2] & 0x02) >> 1); - i += (pad + isync); - if (i > n) - break; - if (!compare(buf, buf + i)) - return -nmatch; - nmatch++; - } - return nmatch; +static int sync_test(unsigned char *buf, int n, int isync, int padbytes) { + int i, nmatch, pad; + + nmatch = 0; + for (i = 0;;) { + pad = padbytes * ((buf[i + 2] & 0x02) >> 1); + i += (pad + isync); + if (i > n) + break; + if (!compare(buf, buf + i)) + return -nmatch; + nmatch++; + } + return nmatch; } diff --git a/code/mp3code/msis.c b/code/mp3code/msis.c index f0e11f51a7..770ccafae2 100644 --- a/code/mp3code/msis.c +++ b/code/mp3code/msis.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -29,15 +29,15 @@ ____________________________________________________________________________*/ antialias, ms and is stereo precessing **** is_process assumes never switch - from short to long in is region ***** + from short to long in is region ***** is_process does ms or stereo in "forbidded sf regions" - //ms_mode = 0 - lr[0][i][0] = 1.0f; - lr[0][i][1] = 0.0f; - // ms_mode = 1, in is bands is routine does ms processing - lr[1][i][0] = 1.0f; - lr[1][i][1] = 1.0f; + //ms_mode = 0 + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + // ms_mode = 1, in is bands is routine does ms processing + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; ******************************************************************/ @@ -52,7 +52,7 @@ is_process does ms or stereo in "forbidded sf regions" typedef float ARRAY2[2]; typedef float ARRAY8_2[8][2]; -float csa[8][2]; /* antialias */ // effectively constant +float csa[8][2]; /* antialias */ // effectively constant /* pMP3Stream->nBand[0] = long, pMP3Stream->nBand[1] = short */ ////@@@@extern int pMP3Stream->nBand[2][22]; @@ -61,236 +61,204 @@ float csa[8][2]; /* antialias */ // effectively constant /* intensity stereo */ /* if ms mode quant pre-scales all values by 1.0/sqrt(2.0) ms_mode in table compensates */ -static float lr[2][8][2]; /* [ms_mode 0/1][sf][left/right] */ // effectively constant - +static float lr[2][8][2]; /* [ms_mode 0/1][sf][left/right] */ // effectively constant /* intensity stereo MPEG2 */ /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ typedef float ARRAY2_64_2[2][64][2]; typedef float ARRAY64_2[64][2]; -static float lr2[2][2][64][2]; // effectively constant - +static float lr2[2][2][64][2]; // effectively constant /*===============================================================*/ -ARRAY2 *alias_init_addr() -{ - return csa; -} +ARRAY2 *alias_init_addr() { return csa; } /*-----------------------------------------------------------*/ -ARRAY8_2 *msis_init_addr() -{ -/*------- -pi = 4.0*atan(1.0); -t = pi/12.0; -for(i=0;i<7;i++) { - s = sin(i*t); - c = cos(i*t); - // ms_mode = 0 - lr[0][i][0] = (float)(s/(s+c)); - lr[0][i][1] = (float)(c/(s+c)); - // ms_mode = 1 - lr[1][i][0] = (float)(sqrt(2.0)*(s/(s+c))); - lr[1][i][1] = (float)(sqrt(2.0)*(c/(s+c))); -} -//sf = 7 -//ms_mode = 0 -lr[0][i][0] = 1.0f; -lr[0][i][1] = 0.0f; -// ms_mode = 1, in is bands is routine does ms processing -lr[1][i][0] = 1.0f; -lr[1][i][1] = 1.0f; -------------*/ - - return lr; +ARRAY8_2 *msis_init_addr() { + /*------- + pi = 4.0*atan(1.0); + t = pi/12.0; + for(i=0;i<7;i++) { + s = sin(i*t); + c = cos(i*t); + // ms_mode = 0 + lr[0][i][0] = (float)(s/(s+c)); + lr[0][i][1] = (float)(c/(s+c)); + // ms_mode = 1 + lr[1][i][0] = (float)(sqrt(2.0)*(s/(s+c))); + lr[1][i][1] = (float)(sqrt(2.0)*(c/(s+c))); + } + //sf = 7 + //ms_mode = 0 + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + // ms_mode = 1, in is bands is routine does ms processing + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; + ------------*/ + + return lr; } /*-------------------------------------------------------------*/ -ARRAY2_64_2 *msis_init_addr_MPEG2() -{ - return lr2; -} +ARRAY2_64_2 *msis_init_addr_MPEG2() { return lr2; } /*===============================================================*/ -void antialias(float x[], int n) -{ - int i, k; - float a, b; - - for (k = 0; k < n; k++) - { - for (i = 0; i < 8; i++) - { - a = x[17 - i]; - b = x[18 + i]; - x[17 - i] = a * csa[i][0] - b * csa[i][1]; - x[18 + i] = b * csa[i][0] + a * csa[i][1]; - } - x += 18; - } +void antialias(float x[], int n) { + int i, k; + float a, b; + + for (k = 0; k < n; k++) { + for (i = 0; i < 8; i++) { + a = x[17 - i]; + b = x[18 + i]; + x[17 - i] = a * csa[i][0] - b * csa[i][1]; + x[18 + i] = b * csa[i][0] + a * csa[i][1]; + } + x += 18; + } } /*===============================================================*/ -void ms_process(float x[][1152], int n) /* sum-difference stereo */ +void ms_process(float x[][1152], int n) /* sum-difference stereo */ { - int i; - float xl, xr; - -/*-- note: sqrt(2) done scaling by dequant ---*/ - for (i = 0; i < n; i++) - { - xl = x[0][i] + x[1][i]; - xr = x[0][i] - x[1][i]; - x[0][i] = xl; - x[1][i] = xr; - } - return; + int i; + float xl, xr; + + /*-- note: sqrt(2) done scaling by dequant ---*/ + for (i = 0; i < n; i++) { + xl = x[0][i] + x[1][i]; + xr = x[0][i] - x[1][i]; + x[0][i] = xl; + x[1][i] = xr; + } + return; } /*===============================================================*/ -void is_process_MPEG1(float x[][1152], /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - int nsamp, int ms_mode) -{ - int i, j, n, cb, w; - float fl, fr; - int m; - int isf; - float fls[3], frs[3]; - int cb0; - - - cb0 = cb_info[1].cbmax; /* start at end of right */ - i = pMP3Stream->sfBandIndex[cb_info[1].cbtype][cb0]; - cb0++; - m = nsamp - i; /* process to len of left */ - - if (cb_info[1].cbtype) - goto short_blocks; -/*------------------------*/ -/* long_blocks: */ - for (cb = cb0; cb < 21; cb++) - { - isf = sf->l[cb]; - n = pMP3Stream->nBand[0][cb]; - fl = lr[ms_mode][isf][0]; - fr = lr[ms_mode][isf][1]; - for (j = 0; j < n; j++, i++) - { - if (--m < 0) - goto exit; - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - } - } - return; -/*------------------------*/ - short_blocks: - for (cb = cb0; cb < 12; cb++) - { - for (w = 0; w < 3; w++) - { - isf = sf->s[w][cb]; - fls[w] = lr[ms_mode][isf][0]; - frs[w] = lr[ms_mode][isf][1]; - } - n = pMP3Stream->nBand[1][cb]; - for (j = 0; j < n; j++) - { - m -= 3; - if (m < 0) - goto exit; - x[1][i] = frs[0] * x[0][i]; - x[0][i] = fls[0] * x[0][i]; - x[1][1 + i] = frs[1] * x[0][1 + i]; - x[0][1 + i] = fls[1] * x[0][1 + i]; - x[1][2 + i] = frs[2] * x[0][2 + i]; - x[0][2 + i] = fls[2] * x[0][2 + i]; - i += 3; - } - } - - exit: - return; +void is_process_MPEG1(float x[][1152], /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + int nsamp, int ms_mode) { + int i, j, n, cb, w; + float fl, fr; + int m; + int isf; + float fls[3], frs[3]; + int cb0; + + cb0 = cb_info[1].cbmax; /* start at end of right */ + i = pMP3Stream->sfBandIndex[cb_info[1].cbtype][cb0]; + cb0++; + m = nsamp - i; /* process to len of left */ + + if (cb_info[1].cbtype) + goto short_blocks; + /*------------------------*/ + /* long_blocks: */ + for (cb = cb0; cb < 21; cb++) { + isf = sf->l[cb]; + n = pMP3Stream->nBand[0][cb]; + fl = lr[ms_mode][isf][0]; + fr = lr[ms_mode][isf][1]; + for (j = 0; j < n; j++, i++) { + if (--m < 0) + goto exit; + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + } + } + return; + /*------------------------*/ +short_blocks: + for (cb = cb0; cb < 12; cb++) { + for (w = 0; w < 3; w++) { + isf = sf->s[w][cb]; + fls[w] = lr[ms_mode][isf][0]; + frs[w] = lr[ms_mode][isf][1]; + } + n = pMP3Stream->nBand[1][cb]; + for (j = 0; j < n; j++) { + m -= 3; + if (m < 0) + goto exit; + x[1][i] = frs[0] * x[0][i]; + x[0][i] = fls[0] * x[0][i]; + x[1][1 + i] = frs[1] * x[0][1 + i]; + x[0][1 + i] = fls[1] * x[0][1 + i]; + x[1][2 + i] = frs[2] * x[0][2 + i]; + x[0][2 + i] = fls[2] * x[0][2 + i]; + i += 3; + } + } + +exit: + return; } /*===============================================================*/ -void is_process_MPEG2(float x[][1152], /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - IS_SF_INFO * is_sf_info, - int nsamp, int ms_mode) -{ - int i, j, k, n, cb, w; - float fl, fr; - int m; - int isf; - int il[21]; - int tmp; - int r; - ARRAY2 *lr; - int cb0, cb1; - - lr = lr2[is_sf_info->intensity_scale][ms_mode]; - - if (cb_info[1].cbtype) - goto short_blocks; - -/*------------------------*/ -/* long_blocks: */ - cb0 = cb_info[1].cbmax; /* start at end of right */ - i = pMP3Stream->sfBandIndex[0][cb0]; - m = nsamp - i; /* process to len of left */ -/* gen sf info */ - for (k = r = 0; r < 3; r++) - { - tmp = (1 << is_sf_info->slen[r]) - 1; - for (j = 0; j < is_sf_info->nr[r]; j++, k++) - il[k] = tmp; - } - for (cb = cb0 + 1; cb < 21; cb++) - { - isf = il[cb] + sf->l[cb]; - fl = lr[isf][0]; - fr = lr[isf][1]; - n = pMP3Stream->nBand[0][cb]; - for (j = 0; j < n; j++, i++) - { - if (--m < 0) - goto exit; - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - } - } - return; -/*------------------------*/ - short_blocks: - - for (k = r = 0; r < 3; r++) - { - tmp = (1 << is_sf_info->slen[r]) - 1; - for (j = 0; j < is_sf_info->nr[r]; j++, k++) - il[k] = tmp; - } - - for (w = 0; w < 3; w++) - { - cb0 = cb_info[1].cbmax_s[w]; /* start at end of right */ - i = pMP3Stream->sfBandIndex[1][cb0] + w; - cb1 = cb_info[0].cbmax_s[w]; /* process to end of left */ - - for (cb = cb0 + 1; cb <= cb1; cb++) - { - isf = il[cb] + sf->s[w][cb]; - fl = lr[isf][0]; - fr = lr[isf][1]; - n = pMP3Stream->nBand[1][cb]; - for (j = 0; j < n; j++) - { - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - i += 3; - } - } - - } - - exit: - return; +void is_process_MPEG2(float x[][1152], /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + IS_SF_INFO *is_sf_info, int nsamp, int ms_mode) { + int i, j, k, n, cb, w; + float fl, fr; + int m; + int isf; + int il[21]; + int tmp; + int r; + ARRAY2 *lr; + int cb0, cb1; + + lr = lr2[is_sf_info->intensity_scale][ms_mode]; + + if (cb_info[1].cbtype) + goto short_blocks; + + /*------------------------*/ + /* long_blocks: */ + cb0 = cb_info[1].cbmax; /* start at end of right */ + i = pMP3Stream->sfBandIndex[0][cb0]; + m = nsamp - i; /* process to len of left */ + /* gen sf info */ + for (k = r = 0; r < 3; r++) { + tmp = (1 << is_sf_info->slen[r]) - 1; + for (j = 0; j < is_sf_info->nr[r]; j++, k++) + il[k] = tmp; + } + for (cb = cb0 + 1; cb < 21; cb++) { + isf = il[cb] + sf->l[cb]; + fl = lr[isf][0]; + fr = lr[isf][1]; + n = pMP3Stream->nBand[0][cb]; + for (j = 0; j < n; j++, i++) { + if (--m < 0) + goto exit; + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + } + } + return; + /*------------------------*/ +short_blocks: + + for (k = r = 0; r < 3; r++) { + tmp = (1 << is_sf_info->slen[r]) - 1; + for (j = 0; j < is_sf_info->nr[r]; j++, k++) + il[k] = tmp; + } + + for (w = 0; w < 3; w++) { + cb0 = cb_info[1].cbmax_s[w]; /* start at end of right */ + i = pMP3Stream->sfBandIndex[1][cb0] + w; + cb1 = cb_info[0].cbmax_s[w]; /* process to end of left */ + + for (cb = cb0 + 1; cb <= cb1; cb++) { + isf = il[cb] + sf->s[w][cb]; + fl = lr[isf][0]; + fr = lr[isf][1]; + n = pMP3Stream->nBand[1][cb]; + for (j = 0; j < n; j++) { + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + i += 3; + } + } + } + +exit: + return; } /*===============================================================*/ diff --git a/code/mp3code/towave.c b/code/mp3code/towave.c index ff83a00229..d31eafd2b9 100644 --- a/code/mp3code/towave.c +++ b/code/mp3code/towave.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -26,13 +26,13 @@ ____________________________________________________________________________*/ /* ------------------------------------------------------------------------ - NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE - This file exists for reference only. It is not actually used - in the FreeAmp project. There is no need to mess with this - file. There is no need to flatten the beavers, either. + This file exists for reference only. It is not actually used + in the FreeAmp project. There is no need to mess with this + file. There is no need to flatten the beavers, either. - NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE ----- towave.c -------------------------------------------- 32 bit version only @@ -45,7 +45,7 @@ mod 8/19/98 decode 22 sf bands mod 5/14/98 allow mpeg25 (dec8 not supported for mpeg25 samp rate) mod 3/4/98 bs_trigger bs_bufbytes made signed, unsigned may - not terminate properly. Also extra test in bs_fill. + not terminate properly. Also extra test in bs_fill. mod 8/6/96 add 8 bit output to standard decoder @@ -54,9 +54,9 @@ ver 1.4 mods 7/18/96 32 bit and add asm option mods 6/29/95 allow MS wave file for u-law. bugfix u-law table dec8.c mods 2/95 add sample rate reduction, freq_limit and conversions. - add _decode8 for 8Ks output, 16bit 8bit, u-law output. - add additional control parameters to init. - add _info function + add _decode8 for 8Ks output, 16bit 8bit, u-law output. + add additional control parameters to init. + add _info function mod 5/12/95 add quick window cwinq.c @@ -68,11 +68,11 @@ mod 1/5/95 integer overflow mod iup.c ver 1.3 mod 2/5/96 portability mods - drop Tom and Gloria pcm file types + drop Tom and Gloria pcm file types ver 2.0 mod 1/7/97 Layer 3 (float mpeg-1 only) - 2/6/97 Layer 3 MPEG-2 + 2/6/97 Layer 3 MPEG-2 ver 3.01 Layer III bugfix crc problem 8/18/97 ver 3.02 Layer III fix wannabe.mp3 problem 10/9/97 @@ -102,26 +102,26 @@ mod 8/6/96 standard decoder adds 8 bit output decode8 (8Ks output) convert_code: convert_code = 4*bit_code + chan_code - bit_code: 1 = 16 bit linear pcm - 2 = 8 bit (unsigned) linear pcm - 3 = u-law (8 bits unsigned) - chan_code: 0 = convert two chan to mono - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan + bit_code: 1 = 16 bit linear pcm + 2 = 8 bit (unsigned) linear pcm + 3 = u-law (8 bits unsigned) + chan_code: 0 = convert two chan to mono + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan decode (standard decoder) convert_code: - 0 = two chan output - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan - or with 8 = 8 bit output - (other bits ignored) + 0 = two chan output + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan + or with 8 = 8 bit output + (other bits ignored) decode (standard decoder) reduction_code: - 0 = full sample rate output - 1 = half rate - 2 = quarter rate + 0 = full sample rate output + 1 = half rate + 2 = quarter rate -----------------------------------------------------------*/ #include @@ -132,10 +132,10 @@ decode (standard decoder) reduction_code: #ifdef WIN32 #include #endif -#include /* file open flags */ -#include /* someone wants for port */ -#include /* forward slash for portability */ -#include "mhead.h" /* mpeg header structure, decode protos */ +#include /* file open flags */ +#include /* someone wants for port */ +#include /* forward slash for portability */ +#include "mhead.h" /* mpeg header structure, decode protos */ #include "port.h" @@ -151,53 +151,41 @@ decode (standard decoder) reduction_code: #include "mp3struct.h" #include - -#if !defined(byte) && !defined(MACOS_X) && !defined (__linux__) +#if !defined(byte) && !defined(MACOS_X) && !defined(__linux__) typedef unsigned char byte; #endif - - typedef struct id3v1_1 { - char id[3]; - char title[30]; // - char artist[30]; // "Raven Software" - char album[30]; // "#UNCOMP %d" // needed - char year[4]; // "2000" - char comment[28]; // "#MAXVOL %g" // needed - char zero; - char track; - char genre; -} id3v1_1; // 128 bytes in size + char id[3]; + char title[30]; // + char artist[30]; // "Raven Software" + char album[30]; // "#UNCOMP %d" // needed + char year[4]; // "2000" + char comment[28]; // "#MAXVOL %g" // needed + char zero; + char track; + char genre; +} id3v1_1; // 128 bytes in size id3v1_1 *gpTAG; -#define BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(_pvData, _iBytesRemaining) \ - \ - /* account for trailing ID3 tag in _iBytesRemaining */ \ - gpTAG = (id3v1_1*) (((byte *)_pvData + _iBytesRemaining)-sizeof(id3v1_1)); /* sizeof = 128 */ \ - if (!strncmp(gpTAG->id, "TAG", 3)) \ - { \ - _iBytesRemaining -= sizeof(id3v1_1); \ +#define BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(_pvData, _iBytesRemaining) \ + \ + /* account for trailing ID3 tag in _iBytesRemaining */ \ + gpTAG = (id3v1_1 *)(((byte *)_pvData + _iBytesRemaining) - sizeof(id3v1_1)); /* sizeof = 128 */ \ + if (!strncmp(gpTAG->id, "TAG", 3)) { \ + _iBytesRemaining -= sizeof(id3v1_1); \ } - - - - /******** pcm buffer ********/ -#define PCM_BUFBYTES 60000U // more than enough to cover the largest that one packet will ever expand to -char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mallocs in this module (MAC reasons) +#define PCM_BUFBYTES 60000U // more than enough to cover the largest that one packet will ever expand to +char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mallocs in this module (MAC reasons) - typedef struct - { - int (*decode_init) (MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, - int convert_code, int freq_limit); - void (*decode_info) (DEC_INFO * info); - IN_OUT(*decode) (unsigned char *bs, short *pcm, unsigned char *pNextByteAfterData); - } - AUDIO; +typedef struct { + int (*decode_init)(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); + void (*decode_info)(DEC_INFO *info); + IN_OUT (*decode)(unsigned char *bs, short *pcm, unsigned char *pNextByteAfterData); +} AUDIO; #if 0 // fuck this... @@ -226,31 +214,28 @@ char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mall }; #endif - static const AUDIO audio = {audio_decode_init, audio_decode_info, audio_decode}; //audio_table[0][0]; - +static const AUDIO audio = {audio_decode_init, audio_decode_info, audio_decode}; // audio_table[0][0]; // Do NOT change these, ever!!!!!!!!!!!!!!!!!! // -const int reduction_code = 0; // unpack at full sample rate output -const int convert_code_mono = 1; +const int reduction_code = 0; // unpack at full sample rate output +const int convert_code_mono = 1; const int convert_code_stereo = 0; -const int freq_limit = 24000; // no idea what this is about, but it's always this value so... +const int freq_limit = 24000; // no idea what this is about, but it's always this value so... // the entire decode mechanism uses this now... // MP3STREAM _MP3Stream; LP_MP3STREAM pMP3Stream = &_MP3Stream; -int bFastEstimateOnly = 0; // MUST DEFAULT TO THIS VALUE!!!!!!!!! - +int bFastEstimateOnly = 0; // MUST DEFAULT TO THIS VALUE!!!!!!!!! // char *return is NZ for any errors (no trailing CR!) // -char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) -{ -// char sTemp[1024]; ///////////////////////////////////////////////// +char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) { + // char sTemp[1024]; ///////////////////////////////////////////////// unsigned int iRealDataStart; MPEG_HEAD head; - DEC_INFO decinfo; + DEC_INFO decinfo; int iBitRate; int iFrameBytes; @@ -260,11 +245,10 @@ char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) // iBitRate = iIgnoreThisForNowIJustNeedItToBreakpointOnToReadAValue; // get rid of unused-variable warning #endif - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - iFrameBytes = head_info3( pvData, iDataLen/2, &head, &iBitRate, &iRealDataStart); - if (iFrameBytes == 0) - { + iFrameBytes = head_info3(pvData, iDataLen / 2, &head, &iBitRate, &iRealDataStart); + if (iFrameBytes == 0) { return "MP3ERR: Bad or unsupported file!"; } @@ -273,42 +257,31 @@ char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) // although the decoder can convert stereo to mono (apparently), we want to know about stereo files // because they're a waste of source space... (all FX are mono, and moved via panning) // - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { - if (bStereoDesired) - { - if (pMP3Stream->outbytes > 4608) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { + if (bStereoDesired) { + if (pMP3Stream->outbytes > 4608) { return "MP3ERR: Source file has output packet size > 2304 (*2 for stereo) bytes!"; } - } - else - { - if (pMP3Stream->outbytes > 2304) - { + } else { + if (pMP3Stream->outbytes > 2304) { return "MP3ERR: Source file has output packet size > 2304 bytes!"; } } audio.decode_info(&decinfo); - if (decinfo.bits != 16) - { - return "MP3ERR: Source file is not 16bit!"; // will this ever happen? oh well... + if (decinfo.bits != 16) { + return "MP3ERR: Source file is not 16bit!"; // will this ever happen? oh well... } - if (decinfo.samprate != 44100) - { + if (decinfo.samprate != 44100) { return "MP3ERR: Source file is not sampled @ 44100!"; } - if (bStereoDesired && decinfo.channels != 2) - { - return "MP3ERR: Source file is not stereo!"; // sod it, I'm going to count this as an error now + if (bStereoDesired && decinfo.channels != 2) { + return "MP3ERR: Source file is not stereo!"; // sod it, I'm going to count this as an error now } - } - else - { + } else { return "MP3ERR: Decoder failed to initialise"; } @@ -317,37 +290,30 @@ char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) return NULL; } - - // char *return is NZ for any errors (no trailing CR!) // -char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, int *piChannels, int bStereoDesired) -{ +char *C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, int *piChannels, int bStereoDesired) { unsigned int iRealDataStart; MPEG_HEAD head; - DEC_INFO decinfo; + DEC_INFO decinfo; int iBitRate; int iFrameBytes; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - iFrameBytes = head_info3( pvData, iDataLen/2, &head, &iBitRate, &iRealDataStart); - if (iFrameBytes == 0) - { + iFrameBytes = head_info3(pvData, iDataLen / 2, &head, &iBitRate, &iRealDataStart); + if (iFrameBytes == 0) { return "MP3ERR: Bad or unsupported file!"; } - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); - *piRate = decinfo.samprate; // rate (eg 22050, 44100 etc) - *piWidth = decinfo.bits/8; // 1 for 8bit, 2 for 16 bit - *piChannels = decinfo.channels; // 1 for mono, 2 for stereo - } - else - { + *piRate = decinfo.samprate; // rate (eg 22050, 44100 etc) + *piWidth = decinfo.bits / 8; // 1 for 8bit, 2 for 16 bit + *piChannels = decinfo.channels; // 1 for mono, 2 for stereo + } else { return "MP3ERR: Decoder failed to initialise"; } @@ -356,9 +322,6 @@ char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, return NULL; } - - - // this duplicates work done in C_MP3_IsValid(), but it avoids global structs, and means that you can call this anytime // if you just want info for some reason // @@ -366,8 +329,7 @@ char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, // // char *return is NZ for any errors (no trailing CR!) // -char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, int bStereoDesired ) -{ +char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, int bStereoDesired) { int iReadLimit; unsigned int iRealDataStart; MPEG_HEAD head; @@ -375,177 +337,155 @@ char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpa char *pPCM_Buffer = PCM_Buffer; char *psReturn = NULL; -// int iSourceReadIndex = 0; - int iDestWriteIndex = 0; + // int iSourceReadIndex = 0; + int iDestWriteIndex = 0; int iFrameBytes; int iFrameCounter; DEC_INFO decinfo; - IN_OUT x; + IN_OUT x; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); #define iSourceReadIndex iRealDataStart -// iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); - iFrameBytes = head_info3( pvData, iSourceBytesRemaining/2, &head, &iBitRate, &iRealDataStart); + // iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); + iFrameBytes = head_info3(pvData, iSourceBytesRemaining / 2, &head, &iBitRate, &iRealDataStart); BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvData, iSourceBytesRemaining) iSourceBytesRemaining -= iRealDataStart; iReadLimit = iSourceReadIndex + iSourceBytesRemaining; - if (iFrameBytes) - { - //pPCM_Buffer = Z_Malloc(PCM_BUFBYTES); + if (iFrameBytes) { + // pPCM_Buffer = Z_Malloc(PCM_BUFBYTES); - //if (pPCM_Buffer) + // if (pPCM_Buffer) { // init decoder... - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); // decode... // - for (iFrameCounter = 0;;iFrameCounter++) - { - if ( iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) - break; // end of file + for (iFrameCounter = 0;; iFrameCounter++) { + if (iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) + break; // end of file - bFastEstimateOnly = 1; /////////////////////////////// + bFastEstimateOnly = 1; /////////////////////////////// - x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *) ((char *)pPCM_Buffer - //+ iDestWriteIndex // keep decoding over the same spot since we're only counting bytes in this function - ), - (unsigned char *)pvData + iReadLimit - ); + x = audio.decode((unsigned char *)pvData + iSourceReadIndex, + (short *)((char *)pPCM_Buffer + //+ iDestWriteIndex // keep decoding over the same spot since we're only counting bytes in this function + ), + (unsigned char *)pvData + iReadLimit); - bFastEstimateOnly = 0; /////////////////////////////// + bFastEstimateOnly = 0; /////////////////////////////// - iSourceReadIndex += x.in_bytes; - iSourceBytesRemaining -= x.in_bytes; - iDestWriteIndex += x.out_bytes; + iSourceReadIndex += x.in_bytes; + iSourceBytesRemaining -= x.in_bytes; + iDestWriteIndex += x.out_bytes; - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; break; } } - *piUnpackedSize = iDestWriteIndex; // yeeehaaa! - } - else - { + *piUnpackedSize = iDestWriteIndex; // yeeehaaa! + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } } -// else -// { -// psReturn = "MP3ERR: Unable to alloc temp decomp buffer"; -// } - } - else - { + // else + // { + // psReturn = "MP3ERR: Unable to alloc temp decomp buffer"; + // } + } else { psReturn = "MP3ERR: Bad or Unsupported MP3 file!"; } - -// if (pPCM_Buffer) -// { -// Z_Free(pPCM_Buffer); -// pPCM_Buffer = NULL; // I know, I know... -// } + // if (pPCM_Buffer) + // { + // Z_Free(pPCM_Buffer); + // pPCM_Buffer = NULL; // I know, I know... + // } return psReturn; #undef iSourceReadIndex } - - - -char *C_MP3_UnpackRawPCM( void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, void *pbUnpackBuffer, int bStereoDesired) -{ +char *C_MP3_UnpackRawPCM(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, void *pbUnpackBuffer, int bStereoDesired) { int iReadLimit; unsigned int iRealDataStart; MPEG_HEAD head; int iBitRate; char *psReturn = NULL; -// int iSourceReadIndex = 0; - int iDestWriteIndex = 0; + // int iSourceReadIndex = 0; + int iDestWriteIndex = 0; int iFrameBytes; int iFrameCounter; DEC_INFO decinfo; - IN_OUT x; + IN_OUT x; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); #define iSourceReadIndex iRealDataStart -// iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); - iFrameBytes = head_info3( pvData, iSourceBytesRemaining/2, &head, &iBitRate, &iRealDataStart); + // iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); + iFrameBytes = head_info3(pvData, iSourceBytesRemaining / 2, &head, &iBitRate, &iRealDataStart); BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvData, iSourceBytesRemaining) iSourceBytesRemaining -= iRealDataStart; iReadLimit = iSourceReadIndex + iSourceBytesRemaining; - if (iFrameBytes) - { -// if (1)////////////////////////pPCM_Buffer) + if (iFrameBytes) { + // if (1)////////////////////////pPCM_Buffer) { // init decoder... - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); -// printf("\n output samprate = %6ld",decinfo.samprate); -// printf("\n output channels = %6d", decinfo.channels); -// printf("\n output bits = %6d", decinfo.bits); -// printf("\n output type = %6d", decinfo.type); + // printf("\n output samprate = %6ld",decinfo.samprate); + // printf("\n output channels = %6d", decinfo.channels); + // printf("\n output bits = %6d", decinfo.bits); + // printf("\n output type = %6d", decinfo.type); -//=============== + //=============== // decode... // - for (iFrameCounter = 0;;iFrameCounter++) - { - if ( iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) - break; // end of file - - x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *) ((char *)pbUnpackBuffer + iDestWriteIndex), - (unsigned char *)pvData + iReadLimit - ); - - iSourceReadIndex += x.in_bytes; - iSourceBytesRemaining -= x.in_bytes; - iDestWriteIndex += x.out_bytes; - - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; + for (iFrameCounter = 0;; iFrameCounter++) { + if (iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) + break; // end of file + + x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *)((char *)pbUnpackBuffer + iDestWriteIndex), + (unsigned char *)pvData + iReadLimit); + + iSourceReadIndex += x.in_bytes; + iSourceBytesRemaining -= x.in_bytes; + iDestWriteIndex += x.out_bytes; + + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; break; } } - *piUnpackedSize = iDestWriteIndex; // yeeehaaa! - } - else - { + *piUnpackedSize = iDestWriteIndex; // yeeehaaa! + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } } - } - else - { + } else { psReturn = "MP3ERR: Bad or Unsupported MP3 file!"; } @@ -554,101 +494,90 @@ char *C_MP3_UnpackRawPCM( void *pvData, int iSourceBytesRemaining, int *piUnpack #undef iSourceReadIndex } - // called once, after we've decided to keep something as MP3. This just sets up the decoder for subsequent stream-calls. // // (the struct pSFX_MP3Stream is cleared internally, so pass as args anything you want stored in it) // // char * return is NULL for ok, else error string // -char *C_MP3Stream_DecodeInit( LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, int iSourceBytesRemaining, - int iGameAudioSampleRate, int iGameAudioSampleBits, int bStereoDesired ) -{ - char *psReturn = NULL; - MPEG_HEAD head; // only relevant within this function during init - DEC_INFO decinfo; // " " - int iBitRate; // not used after being filled in by head_info3() +char *C_MP3Stream_DecodeInit(LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, int iSourceBytesRemaining, int iGameAudioSampleRate, int iGameAudioSampleBits, + int bStereoDesired) { + char *psReturn = NULL; + MPEG_HEAD head; // only relevant within this function during init + DEC_INFO decinfo; // " " + int iBitRate; // not used after being filled in by head_info3() pMP3Stream = pSFX_MP3Stream; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - pMP3Stream->pbSourceData = (byte *) pvSourceData; - pMP3Stream->iSourceBytesRemaining = iSourceBytesRemaining; - pMP3Stream->iSourceFrameBytes = head_info3( (byte *) pvSourceData, iSourceBytesRemaining/2, &head, &iBitRate, (unsigned int*)&pMP3Stream->iSourceReadIndex ); + pMP3Stream->pbSourceData = (byte *)pvSourceData; + pMP3Stream->iSourceBytesRemaining = iSourceBytesRemaining; + pMP3Stream->iSourceFrameBytes = + head_info3((byte *)pvSourceData, iSourceBytesRemaining / 2, &head, &iBitRate, (unsigned int *)&pMP3Stream->iSourceReadIndex); // hack, do NOT do this for stereo, since music files are now streamed and therefore the data isn't actually fully // loaded at this point, only about 4k or so for the header is actually in memory!!!... // - if (!bStereoDesired) - { + if (!bStereoDesired) { BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvSourceData, pMP3Stream->iSourceBytesRemaining); - pMP3Stream->iSourceBytesRemaining -= pMP3Stream->iSourceReadIndex; + pMP3Stream->iSourceBytesRemaining -= pMP3Stream->iSourceReadIndex; } // backup a couple of fields so we can play this again later... // - pMP3Stream->iRewind_SourceReadIndex = pMP3Stream->iSourceReadIndex; - pMP3Stream->iRewind_SourceBytesRemaining= pMP3Stream->iSourceBytesRemaining; + pMP3Stream->iRewind_SourceReadIndex = pMP3Stream->iSourceReadIndex; + pMP3Stream->iRewind_SourceBytesRemaining = pMP3Stream->iSourceBytesRemaining; assert(pMP3Stream->iSourceFrameBytes); - if (pMP3Stream->iSourceFrameBytes) - { - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, reduction_code, pMP3Stream->iSourceReadIndex, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { - pMP3Stream->iRewind_FinalReductionCode = reduction_code; // default = 0 (no reduction), 1=half, 2 = quarter + if (pMP3Stream->iSourceFrameBytes) { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, reduction_code, pMP3Stream->iSourceReadIndex, + bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { + pMP3Stream->iRewind_FinalReductionCode = reduction_code; // default = 0 (no reduction), 1=half, 2 = quarter - pMP3Stream->iRewind_FinalConvertCode = bStereoDesired?convert_code_stereo:convert_code_mono; - // default = 1 (mono), OR with 8 for 8-bit output + pMP3Stream->iRewind_FinalConvertCode = bStereoDesired ? convert_code_stereo : convert_code_mono; + // default = 1 (mono), OR with 8 for 8-bit output // only now can we ask what kind of properties this file has, and then adjust to fit what the game wants... // audio.decode_info(&decinfo); -// printf("\n output samprate = %6ld",decinfo.samprate); -// printf("\n output channels = %6d", decinfo.channels); -// printf("\n output bits = %6d", decinfo.bits); -// printf("\n output type = %6d", decinfo.type); + // printf("\n output samprate = %6ld",decinfo.samprate); + // printf("\n output channels = %6d", decinfo.channels); + // printf("\n output bits = %6d", decinfo.bits); + // printf("\n output type = %6d", decinfo.type); // decoder offers half or quarter rate adjustement only... // - if (iGameAudioSampleRate == decinfo.samprate>>1) + if (iGameAudioSampleRate == decinfo.samprate >> 1) pMP3Stream->iRewind_FinalReductionCode = 1; - else - if (iGameAudioSampleRate == decinfo.samprate>>2) + else if (iGameAudioSampleRate == decinfo.samprate >> 2) pMP3Stream->iRewind_FinalReductionCode = 2; - if (iGameAudioSampleBits == decinfo.bits>>1) // if game wants 8 bit sounds, then setup for that + if (iGameAudioSampleBits == decinfo.bits >> 1) // if game wants 8 bit sounds, then setup for that pMP3Stream->iRewind_FinalConvertCode |= 8; - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, pMP3Stream->iRewind_FinalConvertCode, freq_limit)) - { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, + pMP3Stream->iRewind_FinalConvertCode, freq_limit)) { audio.decode_info(&decinfo); #ifdef _DEBUG - assert( iGameAudioSampleRate == decinfo.samprate ); - assert( iGameAudioSampleBits == decinfo.bits ); + assert(iGameAudioSampleRate == decinfo.samprate); + assert(iGameAudioSampleBits == decinfo.bits); #endif // sod it, no harm in one last check... (should never happen) // - if ( iGameAudioSampleRate != decinfo.samprate || iGameAudioSampleBits != decinfo.bits ) - { + if (iGameAudioSampleRate != decinfo.samprate || iGameAudioSampleBits != decinfo.bits) { psReturn = "MP3ERR: Decoder unable to convert to current game audio settings"; } - } - else - { + } else { psReturn = "MP3ERR: Decoder failed to initialise for pass 2 sample adjust"; } - } - else - { + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } - } - else - { - psReturn = "MP3ERR: Errr.... something's broken with this MP3 file"; // should never happen by this point + } else { + psReturn = "MP3ERR: Errr.... something's broken with this MP3 file"; // should never happen by this point } // restore global stream ptr before returning to normal functions (so the rest of the MP3 code still works)... @@ -660,48 +589,41 @@ char *C_MP3Stream_DecodeInit( LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, i // return value is decoded bytes for this packet, which is effectively a BOOL, NZ for not finished decoding yet... // -unsigned int C_MP3Stream_Decode( LP_MP3STREAM pSFX_MP3Stream, int bFastForwarding ) -{ - unsigned int uiDecoded = 0; // default to "finished" - IN_OUT x; +unsigned int C_MP3Stream_Decode(LP_MP3STREAM pSFX_MP3Stream, int bFastForwarding) { + unsigned int uiDecoded = 0; // default to "finished" + IN_OUT x; pMP3Stream = pSFX_MP3Stream; - if ( pSFX_MP3Stream->iSourceBytesRemaining == 0 )//|| pSFX_MP3Stream->iSourceBytesRemaining < pSFX_MP3Stream->iSourceFrameBytes) + if (pSFX_MP3Stream->iSourceBytesRemaining == 0) //|| pSFX_MP3Stream->iSourceBytesRemaining < pSFX_MP3Stream->iSourceFrameBytes) { - uiDecoded = 0; // finished + uiDecoded = 0; // finished pMP3Stream = &_MP3Stream; return uiDecoded; } + bFastEstimateOnly = bFastForwarding; /////////////////////////////// + x = audio.decode(pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iSourceReadIndex, (short *)(pSFX_MP3Stream->bDecodeBuffer), + pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iRewind_SourceReadIndex + pSFX_MP3Stream->iRewind_SourceBytesRemaining); - bFastEstimateOnly = bFastForwarding; /////////////////////////////// - - x = audio.decode(pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iSourceReadIndex, (short *) (pSFX_MP3Stream->bDecodeBuffer), - pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iRewind_SourceReadIndex + pSFX_MP3Stream->iRewind_SourceBytesRemaining - ); - - bFastEstimateOnly = 0; /////////////////////////////// - - + bFastEstimateOnly = 0; /////////////////////////////// #ifdef _DEBUG pSFX_MP3Stream->iSourceFrameCounter++; #endif - pSFX_MP3Stream->iSourceReadIndex += x.in_bytes; - pSFX_MP3Stream->iSourceBytesRemaining -= x.in_bytes; - pSFX_MP3Stream->iBytesDecodedTotal += x.out_bytes; - pSFX_MP3Stream->iBytesDecodedThisPacket = x.out_bytes; + pSFX_MP3Stream->iSourceReadIndex += x.in_bytes; + pSFX_MP3Stream->iSourceBytesRemaining -= x.in_bytes; + pSFX_MP3Stream->iBytesDecodedTotal += x.out_bytes; + pSFX_MP3Stream->iBytesDecodedThisPacket = x.out_bytes; uiDecoded = x.out_bytes; - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; - uiDecoded= 0; // finished + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; + uiDecoded = 0; // finished pMP3Stream = &_MP3Stream; return uiDecoded; @@ -714,37 +636,31 @@ unsigned int C_MP3Stream_Decode( LP_MP3STREAM pSFX_MP3Stream, int bFastForwardin return uiDecoded; } - // ret is char* errstring, else NULL for ok // -char *C_MP3Stream_Rewind( LP_MP3STREAM pSFX_MP3Stream ) -{ - char* psReturn = NULL; - MPEG_HEAD head; // only relevant within this function during init - int iBitRate; // ditto - int iNULL; +char *C_MP3Stream_Rewind(LP_MP3STREAM pSFX_MP3Stream) { + char *psReturn = NULL; + MPEG_HEAD head; // only relevant within this function during init + int iBitRate; // ditto + int iNULL; pMP3Stream = pSFX_MP3Stream; - pMP3Stream->iSourceReadIndex = pMP3Stream->iRewind_SourceReadIndex; - pMP3Stream->iSourceBytesRemaining = pMP3Stream->iRewind_SourceBytesRemaining; // already adjusted for tags etc + pMP3Stream->iSourceReadIndex = pMP3Stream->iRewind_SourceReadIndex; + pMP3Stream->iSourceBytesRemaining = pMP3Stream->iRewind_SourceBytesRemaining; // already adjusted for tags etc // I'm not sure that this is needed, but where else does decode_init get passed useful data ptrs?... // - if (pMP3Stream->iSourceFrameBytes == head_info3( pMP3Stream->pbSourceData, pMP3Stream->iSourceBytesRemaining/2, &head, &iBitRate, (unsigned int*)&iNULL ) ) - { - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, pMP3Stream->iRewind_FinalConvertCode, freq_limit)) - { + if (pMP3Stream->iSourceFrameBytes == + head_info3(pMP3Stream->pbSourceData, pMP3Stream->iSourceBytesRemaining / 2, &head, &iBitRate, (unsigned int *)&iNULL)) { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, + pMP3Stream->iRewind_FinalConvertCode, freq_limit)) { // we should always get here... // - } - else - { + } else { psReturn = "MP3ERR: Failed to re-init decoder for rewind!"; } - } - else - { + } else { psReturn = "MP3ERR: Frame bytes mismatch during rewind header-read!"; } @@ -754,4 +670,3 @@ char *C_MP3Stream_Rewind( LP_MP3STREAM pSFX_MP3Stream ) return psReturn; } - diff --git a/code/mp3code/uph.c b/code/mp3code/uph.c index 55f1a4dce2..ec3eee4ae0 100644 --- a/code/mp3code/uph.c +++ b/code/mp3code/uph.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -44,79 +44,41 @@ Layer 3 audio /* quad required 10 bit w/signs must have (MAXBITS+2) >= 10 */ #define MAXBITS 9 -static const HUFF_ELEMENT huff_table_0[4] = -{{0}, {0}, {0}, {64}}; /* dummy must not use */ +static const HUFF_ELEMENT huff_table_0[4] = {{0}, {0}, {0}, {64}}; /* dummy must not use */ #include "htable.h" /*-- 6 bit lookup (purgebits, value) --*/ -static const unsigned char quad_table_a[][2] = -{ - {6, 11}, {6, 15}, {6, 13}, {6, 14}, {6, 7}, {6, 5}, {5, 9}, - {5, 9}, {5, 6}, {5, 6}, {5, 3}, {5, 3}, {5, 10}, {5, 10}, - {5, 12}, {5, 12}, {4, 2}, {4, 2}, {4, 2}, {4, 2}, {4, 1}, - {4, 1}, {4, 1}, {4, 1}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, - {4, 8}, {4, 8}, {4, 8}, {4, 8}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, +static const unsigned char quad_table_a[][2] = { + {6, 11}, {6, 15}, {6, 13}, {6, 14}, {6, 7}, {6, 5}, {5, 9}, {5, 9}, {5, 6}, {5, 6}, {5, 3}, {5, 3}, {5, 10}, {5, 10}, {5, 12}, {5, 12}, + {4, 2}, {4, 2}, {4, 2}, {4, 2}, {4, 1}, {4, 1}, {4, 1}, {4, 1}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 8}, {4, 8}, {4, 8}, {4, 8}, + {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, + {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, }; - -typedef struct -{ - const HUFF_ELEMENT *table; - int linbits; - int ncase; -} -HUFF_SETUP; - -#define no_bits 0 -#define one_shot 1 -#define no_linbits 2 -#define have_linbits 3 -#define quad_a 4 -#define quad_b 5 - - -static const HUFF_SETUP table_look[] = -{ - {huff_table_0, 0, no_bits}, - {huff_table_1, 0, one_shot}, - {huff_table_2, 0, one_shot}, - {huff_table_3, 0, one_shot}, - {huff_table_0, 0, no_bits}, - {huff_table_5, 0, one_shot}, - {huff_table_6, 0, one_shot}, - {huff_table_7, 0, no_linbits}, - {huff_table_8, 0, no_linbits}, - {huff_table_9, 0, no_linbits}, - {huff_table_10, 0, no_linbits}, - {huff_table_11, 0, no_linbits}, - {huff_table_12, 0, no_linbits}, - {huff_table_13, 0, no_linbits}, - {huff_table_0, 0, no_bits}, - {huff_table_15, 0, no_linbits}, - {huff_table_16, 1, have_linbits}, - {huff_table_16, 2, have_linbits}, - {huff_table_16, 3, have_linbits}, - {huff_table_16, 4, have_linbits}, - {huff_table_16, 6, have_linbits}, - {huff_table_16, 8, have_linbits}, - {huff_table_16, 10, have_linbits}, - {huff_table_16, 13, have_linbits}, - {huff_table_24, 4, have_linbits}, - {huff_table_24, 5, have_linbits}, - {huff_table_24, 6, have_linbits}, - {huff_table_24, 7, have_linbits}, - {huff_table_24, 8, have_linbits}, - {huff_table_24, 9, have_linbits}, - {huff_table_24, 11, have_linbits}, - {huff_table_24, 13, have_linbits}, - {huff_table_0, 0, quad_a}, - {huff_table_0, 0, quad_b}, +typedef struct { + const HUFF_ELEMENT *table; + int linbits; + int ncase; +} HUFF_SETUP; + +#define no_bits 0 +#define one_shot 1 +#define no_linbits 2 +#define have_linbits 3 +#define quad_a 4 +#define quad_b 5 + +static const HUFF_SETUP table_look[] = { + {huff_table_0, 0, no_bits}, {huff_table_1, 0, one_shot}, {huff_table_2, 0, one_shot}, {huff_table_3, 0, one_shot}, + {huff_table_0, 0, no_bits}, {huff_table_5, 0, one_shot}, {huff_table_6, 0, one_shot}, {huff_table_7, 0, no_linbits}, + {huff_table_8, 0, no_linbits}, {huff_table_9, 0, no_linbits}, {huff_table_10, 0, no_linbits}, {huff_table_11, 0, no_linbits}, + {huff_table_12, 0, no_linbits}, {huff_table_13, 0, no_linbits}, {huff_table_0, 0, no_bits}, {huff_table_15, 0, no_linbits}, + {huff_table_16, 1, have_linbits}, {huff_table_16, 2, have_linbits}, {huff_table_16, 3, have_linbits}, {huff_table_16, 4, have_linbits}, + {huff_table_16, 6, have_linbits}, {huff_table_16, 8, have_linbits}, {huff_table_16, 10, have_linbits}, {huff_table_16, 13, have_linbits}, + {huff_table_24, 4, have_linbits}, {huff_table_24, 5, have_linbits}, {huff_table_24, 6, have_linbits}, {huff_table_24, 7, have_linbits}, + {huff_table_24, 8, have_linbits}, {huff_table_24, 9, have_linbits}, {huff_table_24, 11, have_linbits}, {huff_table_24, 13, have_linbits}, + {huff_table_0, 0, quad_a}, {huff_table_0, 0, quad_b}, }; /*========================================================*/ @@ -131,10 +93,10 @@ static unsigned int bitget(int n) if (bitdat.bits < n) { */ /* refill bit buf if necessary */ /* while (bitdat.bits <= 24) - { + { bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; bitdat.bits += 8; - } + } } bitdat.bits -= n; x = bitdat.bitbuf >> bitdat.bits; @@ -143,42 +105,33 @@ static unsigned int bitget(int n) } */ /*----- get n bits - checks for n+2 avail bits (linbits+sign) -----*/ -static unsigned int bitget_lb(int n) -{ - unsigned int x; - - if (bitdat.bits < (n + 2)) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits -= n; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +static unsigned int bitget_lb(int n) { + unsigned int x; + + if (bitdat.bits < (n + 2)) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits -= n; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } - - - /*------------- get n bits but DO NOT remove from bitstream --*/ -static unsigned int bitget2(int n) -{ - unsigned int x; - - if (bitdat.bits < (MAXBITS + 2)) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - x = bitdat.bitbuf >> (bitdat.bits - n); - return x; +static unsigned int bitget2(int n) { + unsigned int x; + + if (bitdat.bits < (MAXBITS + 2)) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + x = bitdat.bitbuf >> (bitdat.bits - n); + return x; } /*------------- remove n bits from bitstream ---------*/ /* unused @@ -202,299 +155,263 @@ static unsigned int bitget_1bit() */ /*========================================================*/ /*========================================================*/ -#define mac_bitget_check(n) if( bitdat.bits < (n) ) { \ - while( bitdat.bits <= 24 ) { \ - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; \ - bitdat.bits += 8; \ - } \ -} +#define mac_bitget_check(n) \ + if (bitdat.bits < (n)) { \ + while (bitdat.bits <= 24) { \ + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; \ + bitdat.bits += 8; \ + } \ + } /*---------------------------------------------------------*/ -#define mac_bitget2(n) (bitdat.bitbuf >> (bitdat.bits-n)); +#define mac_bitget2(n) (bitdat.bitbuf >> (bitdat.bits - n)); /*---------------------------------------------------------*/ -#define mac_bitget(n) ( bitdat.bits -= n, \ - code = bitdat.bitbuf >> bitdat.bits, \ - bitdat.bitbuf -= code << bitdat.bits, \ - code ) +#define mac_bitget(n) (bitdat.bits -= n, code = bitdat.bitbuf >> bitdat.bits, bitdat.bitbuf -= code << bitdat.bits, code) /*---------------------------------------------------------*/ -#define mac_bitget_purge(n) bitdat.bits -= n, \ - bitdat.bitbuf -= (bitdat.bitbuf >> bitdat.bits) << bitdat.bits; +#define mac_bitget_purge(n) bitdat.bits -= n, bitdat.bitbuf -= (bitdat.bitbuf >> bitdat.bits) << bitdat.bits; /*---------------------------------------------------------*/ -#define mac_bitget_1bit() ( bitdat.bits--, \ - code = bitdat.bitbuf >> bitdat.bits, \ - bitdat.bitbuf -= code << bitdat.bits, \ - code ) +#define mac_bitget_1bit() (bitdat.bits--, code = bitdat.bitbuf >> bitdat.bits, bitdat.bitbuf -= code << bitdat.bits, code) /*========================================================*/ /*========================================================*/ -void unpack_huff(int xy[][2], int n, int ntable) -{ - int i; - const HUFF_ELEMENT *t; - const HUFF_ELEMENT *t0; - int linbits; - int bits; - int code; - int x, y; - - if (n <= 0) - return; - n = n >> 1; /* huff in pairs */ -/*-------------*/ - t0 = table_look[ntable].table; - linbits = table_look[ntable].linbits; - switch (table_look[ntable].ncase) - { - default: -/*------------------------------------------*/ - case no_bits: -/*- table 0, no data, x=y=0--*/ - for (i = 0; i < n; i++) - { - xy[i][0] = 0; - xy[i][1] = 0; - } - return; -/*------------------------------------------*/ - case one_shot: -/*- single lookup, no escapes -*/ - for (i = 0; i < n; i++) - { - mac_bitget_check((MAXBITS + 2)); - bits = t0[0].b.signbits; - code = mac_bitget2(bits); - mac_bitget_purge(t0[1 + code].b.purgebits); - x = t0[1 + code].b.x; - y = t0[1 + code].b.y; - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; -/*------------------------------------------*/ - case no_linbits: - for (i = 0; i < n; i++) - { - t = t0; - for (;;) - { - mac_bitget_check((MAXBITS + 2)); - bits = t[0].b.signbits; - code = mac_bitget2(bits); - if (t[1 + code].b.purgebits) - break; - t += t[1 + code].ptr; /* ptr include 1+code */ - mac_bitget_purge(bits); - } - mac_bitget_purge(t[1 + code].b.purgebits); - x = t[1 + code].b.x; - y = t[1 + code].b.y; - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; -/*------------------------------------------*/ - case have_linbits: - for (i = 0; i < n; i++) - { - t = t0; - for (;;) - { - bits = t[0].b.signbits; - code = bitget2(bits); - if (t[1 + code].b.purgebits) - break; - t += t[1 + code].ptr; /* ptr includes 1+code */ - mac_bitget_purge(bits); - } - mac_bitget_purge(t[1 + code].b.purgebits); - x = t[1 + code].b.x; - y = t[1 + code].b.y; - if (x == 15) - x += bitget_lb(linbits); - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y == 15) - y += bitget_lb(linbits); - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; - } -/*--- end switch ---*/ - +void unpack_huff(int xy[][2], int n, int ntable) { + int i; + const HUFF_ELEMENT *t; + const HUFF_ELEMENT *t0; + int linbits; + int bits; + int code; + int x, y; + + if (n <= 0) + return; + n = n >> 1; /* huff in pairs */ + /*-------------*/ + t0 = table_look[ntable].table; + linbits = table_look[ntable].linbits; + switch (table_look[ntable].ncase) { + default: + /*------------------------------------------*/ + case no_bits: + /*- table 0, no data, x=y=0--*/ + for (i = 0; i < n; i++) { + xy[i][0] = 0; + xy[i][1] = 0; + } + return; + /*------------------------------------------*/ + case one_shot: + /*- single lookup, no escapes -*/ + for (i = 0; i < n; i++) { + mac_bitget_check((MAXBITS + 2)); + bits = t0[0].b.signbits; + code = mac_bitget2(bits); + mac_bitget_purge(t0[1 + code].b.purgebits); + x = t0[1 + code].b.x; + y = t0[1 + code].b.y; + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + /*------------------------------------------*/ + case no_linbits: + for (i = 0; i < n; i++) { + t = t0; + for (;;) { + mac_bitget_check((MAXBITS + 2)); + bits = t[0].b.signbits; + code = mac_bitget2(bits); + if (t[1 + code].b.purgebits) + break; + t += t[1 + code].ptr; /* ptr include 1+code */ + mac_bitget_purge(bits); + } + mac_bitget_purge(t[1 + code].b.purgebits); + x = t[1 + code].b.x; + y = t[1 + code].b.y; + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + /*------------------------------------------*/ + case have_linbits: + for (i = 0; i < n; i++) { + t = t0; + for (;;) { + bits = t[0].b.signbits; + code = bitget2(bits); + if (t[1 + code].b.purgebits) + break; + t += t[1 + code].ptr; /* ptr includes 1+code */ + mac_bitget_purge(bits); + } + mac_bitget_purge(t[1 + code].b.purgebits); + x = t[1 + code].b.x; + y = t[1 + code].b.y; + if (x == 15) + x += bitget_lb(linbits); + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y == 15) + y += bitget_lb(linbits); + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + } + /*--- end switch ---*/ } /*==========================================================*/ -int unpack_huff_quad(int vwxy[][4], int n, int nbits, int ntable) -{ - int i; - int code; - int x, y, v, w; - int tmp; - int i_non_zero, tmp_nz; - - tmp_nz = 15; - i_non_zero = -1; - - n = n >> 2; /* huff in quads */ - - if (ntable) - goto case_quad_b; - -/* case_quad_a: */ - for (i = 0; i < n; i++) - { - if (nbits <= 0) - break; - mac_bitget_check(10); - code = mac_bitget2(6); - nbits -= quad_table_a[code][0]; - mac_bitget_purge(quad_table_a[code][0]); - tmp = quad_table_a[code][1]; - if (tmp) - { - i_non_zero = i; - tmp_nz = tmp; - } - v = (tmp >> 3) & 1; - w = (tmp >> 2) & 1; - x = (tmp >> 1) & 1; - y = tmp & 1; - if (v) - { - if (mac_bitget_1bit()) - v = -v; - nbits--; - } - if (w) - { - if (mac_bitget_1bit()) - w = -w; - nbits--; - } - if (x) - { - if (mac_bitget_1bit()) - x = -x; - nbits--; - } - if (y) - { - if (mac_bitget_1bit()) - y = -y; - nbits--; - } - vwxy[i][0] = v; - vwxy[i][1] = w; - vwxy[i][2] = x; - vwxy[i][3] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - if (i && nbits < 0) - { - i--; - vwxy[i][0] = 0; - vwxy[i][1] = 0; - vwxy[i][2] = 0; - vwxy[i][3] = 0; - } - - i_non_zero = (i_non_zero + 1) << 2; - - if ((tmp_nz & 3) == 0) - i_non_zero -= 2; - - return i_non_zero; - -/*--------------------*/ - case_quad_b: - for (i = 0; i < n; i++) - { - if (nbits < 4) - break; - nbits -= 4; - mac_bitget_check(8); - tmp = mac_bitget(4) ^ 15; /* one's complement of bitstream */ - if (tmp) - { - i_non_zero = i; - tmp_nz = tmp; - } - v = (tmp >> 3) & 1; - w = (tmp >> 2) & 1; - x = (tmp >> 1) & 1; - y = tmp & 1; - if (v) - { - if (mac_bitget_1bit()) - v = -v; - nbits--; - } - if (w) - { - if (mac_bitget_1bit()) - w = -w; - nbits--; - } - if (x) - { - if (mac_bitget_1bit()) - x = -x; - nbits--; - } - if (y) - { - if (mac_bitget_1bit()) - y = -y; - nbits--; - } - vwxy[i][0] = v; - vwxy[i][1] = w; - vwxy[i][2] = x; - vwxy[i][3] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - if (nbits < 0) - { - i--; - vwxy[i][0] = 0; - vwxy[i][1] = 0; - vwxy[i][2] = 0; - vwxy[i][3] = 0; - } - - i_non_zero = (i_non_zero + 1) << 2; - - if ((tmp_nz & 3) == 0) - i_non_zero -= 2; - - return i_non_zero; /* return non-zero sample (to nearest pair) */ - +int unpack_huff_quad(int vwxy[][4], int n, int nbits, int ntable) { + int i; + int code; + int x, y, v, w; + int tmp; + int i_non_zero, tmp_nz; + + tmp_nz = 15; + i_non_zero = -1; + + n = n >> 2; /* huff in quads */ + + if (ntable) + goto case_quad_b; + + /* case_quad_a: */ + for (i = 0; i < n; i++) { + if (nbits <= 0) + break; + mac_bitget_check(10); + code = mac_bitget2(6); + nbits -= quad_table_a[code][0]; + mac_bitget_purge(quad_table_a[code][0]); + tmp = quad_table_a[code][1]; + if (tmp) { + i_non_zero = i; + tmp_nz = tmp; + } + v = (tmp >> 3) & 1; + w = (tmp >> 2) & 1; + x = (tmp >> 1) & 1; + y = tmp & 1; + if (v) { + if (mac_bitget_1bit()) + v = -v; + nbits--; + } + if (w) { + if (mac_bitget_1bit()) + w = -w; + nbits--; + } + if (x) { + if (mac_bitget_1bit()) + x = -x; + nbits--; + } + if (y) { + if (mac_bitget_1bit()) + y = -y; + nbits--; + } + vwxy[i][0] = v; + vwxy[i][1] = w; + vwxy[i][2] = x; + vwxy[i][3] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + if (i && nbits < 0) { + i--; + vwxy[i][0] = 0; + vwxy[i][1] = 0; + vwxy[i][2] = 0; + vwxy[i][3] = 0; + } + + i_non_zero = (i_non_zero + 1) << 2; + + if ((tmp_nz & 3) == 0) + i_non_zero -= 2; + + return i_non_zero; + + /*--------------------*/ +case_quad_b: + for (i = 0; i < n; i++) { + if (nbits < 4) + break; + nbits -= 4; + mac_bitget_check(8); + tmp = mac_bitget(4) ^ 15; /* one's complement of bitstream */ + if (tmp) { + i_non_zero = i; + tmp_nz = tmp; + } + v = (tmp >> 3) & 1; + w = (tmp >> 2) & 1; + x = (tmp >> 1) & 1; + y = tmp & 1; + if (v) { + if (mac_bitget_1bit()) + v = -v; + nbits--; + } + if (w) { + if (mac_bitget_1bit()) + w = -w; + nbits--; + } + if (x) { + if (mac_bitget_1bit()) + x = -x; + nbits--; + } + if (y) { + if (mac_bitget_1bit()) + y = -y; + nbits--; + } + vwxy[i][0] = v; + vwxy[i][1] = w; + vwxy[i][2] = x; + vwxy[i][3] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + if (nbits < 0) { + i--; + vwxy[i][0] = 0; + vwxy[i][1] = 0; + vwxy[i][2] = 0; + vwxy[i][3] = 0; + } + + i_non_zero = (i_non_zero + 1) << 2; + + if ((tmp_nz & 3) == 0) + i_non_zero -= 2; + + return i_non_zero; /* return non-zero sample (to nearest pair) */ } /*-----------------------------------------------------*/ diff --git a/code/mp3code/upsf.c b/code/mp3code/upsf.c index da3d311ae4..4e05115667 100644 --- a/code/mp3code/upsf.c +++ b/code/mp3code/upsf.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -27,7 +27,7 @@ ____________________________________________________________________________*/ /**** upsf.c *************************************************** Layer III - unpack scale factors + unpack scale factors @@ -42,361 +42,292 @@ Layer III unsigned int bitget(int n); /*------------------------------------------------------------*/ -static const int slen_table[16][2] = -{ - {0, 0}, {0, 1}, - {0, 2}, {0, 3}, - {3, 0}, {1, 1}, - {1, 2}, {1, 3}, - {2, 1}, {2, 2}, - {2, 3}, {3, 1}, - {3, 2}, {3, 3}, - {4, 2}, {4, 3}, +static const int slen_table[16][2] = { + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {3, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 2}, {4, 3}, }; /* nr_table[size+3*is_right][block type 0,1,3 2, 2+mixed][4] */ /* for bt=2 nr is count for group of 3 */ -static const int nr_table[6][3][4] = -{ - {{6, 5, 5, 5}, - {3, 3, 3, 3}, - {6, 3, 3, 3}}, - - {{6, 5, 7, 3}, - {3, 3, 4, 2}, - {6, 3, 4, 2}}, - - {{11, 10, 0, 0}, - {6, 6, 0, 0}, - {6, 3, 6, 0}}, /* adjusted *//* 15, 18, 0, 0, */ -/*-intensity stereo right chan--*/ - {{7, 7, 7, 0}, - {4, 4, 4, 0}, - {6, 5, 4, 0}}, - - {{6, 6, 6, 3}, - {4, 3, 3, 2}, - {6, 4, 3, 2}}, - - {{8, 8, 5, 0}, - {5, 4, 3, 0}, - {6, 6, 3, 0}}, +static const int nr_table[6][3][4] = { + {{6, 5, 5, 5}, {3, 3, 3, 3}, {6, 3, 3, 3}}, + + {{6, 5, 7, 3}, {3, 3, 4, 2}, {6, 3, 4, 2}}, + + {{11, 10, 0, 0}, {6, 6, 0, 0}, {6, 3, 6, 0}}, + /* adjusted */ /* 15, 18, 0, 0, */ + /*-intensity stereo right chan--*/ + {{7, 7, 7, 0}, {4, 4, 4, 0}, {6, 5, 4, 0}}, + + {{6, 6, 6, 3}, {4, 3, 3, 2}, {6, 4, 3, 2}}, + + {{8, 8, 5, 0}, {5, 4, 3, 0}, {6, 6, 3, 0}}, }; /*=============================================================*/ -void unpack_sf_sub_MPEG1(SCALEFACT sf[], - GR * grdat, - int scfsi, /* bit flag */ - int gr) -{ - int sfb; - int slen0, slen1; - int block_type, mixed_block_flag, scalefac_compress; - - - block_type = grdat->block_type; - mixed_block_flag = grdat->mixed_block_flag; - scalefac_compress = grdat->scalefac_compress; - - slen0 = slen_table[scalefac_compress][0]; - slen1 = slen_table[scalefac_compress][1]; - - - if (block_type == 2) - { - if (mixed_block_flag) - { /* mixed */ - for (sfb = 0; sfb < 8; sfb++) - sf[0].l[sfb] = bitget(slen0); - for (sfb = 3; sfb < 6; sfb++) - { - sf[0].s[0][sfb] = bitget(slen0); - sf[0].s[1][sfb] = bitget(slen0); - sf[0].s[2][sfb] = bitget(slen0); - } - for (sfb = 6; sfb < 12; sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - return; - } - for (sfb = 0; sfb < 6; sfb++) - { - sf[0].s[0][sfb] = bitget(slen0); - sf[0].s[1][sfb] = bitget(slen0); - sf[0].s[2][sfb] = bitget(slen0); - } - for (; sfb < 12; sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - return; - } - -/* long blocks types 0 1 3, first granule */ - if (gr == 0) - { - for (sfb = 0; sfb < 11; sfb++) - sf[0].l[sfb] = bitget(slen0); - for (; sfb < 21; sfb++) - sf[0].l[sfb] = bitget(slen1); - return; - } - -/* long blocks 0, 1, 3, second granule */ - sfb = 0; - if (scfsi & 8) - for (; sfb < 6; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 6; sfb++) - sf[0].l[sfb] = bitget(slen0); - if (scfsi & 4) - for (; sfb < 11; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 11; sfb++) - sf[0].l[sfb] = bitget(slen0); - if (scfsi & 2) - for (; sfb < 16; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 16; sfb++) - sf[0].l[sfb] = bitget(slen1); - if (scfsi & 1) - for (; sfb < 21; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 21; sfb++) - sf[0].l[sfb] = bitget(slen1); - - - - return; +void unpack_sf_sub_MPEG1(SCALEFACT sf[], GR *grdat, int scfsi, /* bit flag */ + int gr) { + int sfb; + int slen0, slen1; + int block_type, mixed_block_flag, scalefac_compress; + + block_type = grdat->block_type; + mixed_block_flag = grdat->mixed_block_flag; + scalefac_compress = grdat->scalefac_compress; + + slen0 = slen_table[scalefac_compress][0]; + slen1 = slen_table[scalefac_compress][1]; + + if (block_type == 2) { + if (mixed_block_flag) { /* mixed */ + for (sfb = 0; sfb < 8; sfb++) + sf[0].l[sfb] = bitget(slen0); + for (sfb = 3; sfb < 6; sfb++) { + sf[0].s[0][sfb] = bitget(slen0); + sf[0].s[1][sfb] = bitget(slen0); + sf[0].s[2][sfb] = bitget(slen0); + } + for (sfb = 6; sfb < 12; sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + return; + } + for (sfb = 0; sfb < 6; sfb++) { + sf[0].s[0][sfb] = bitget(slen0); + sf[0].s[1][sfb] = bitget(slen0); + sf[0].s[2][sfb] = bitget(slen0); + } + for (; sfb < 12; sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + return; + } + + /* long blocks types 0 1 3, first granule */ + if (gr == 0) { + for (sfb = 0; sfb < 11; sfb++) + sf[0].l[sfb] = bitget(slen0); + for (; sfb < 21; sfb++) + sf[0].l[sfb] = bitget(slen1); + return; + } + + /* long blocks 0, 1, 3, second granule */ + sfb = 0; + if (scfsi & 8) + for (; sfb < 6; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 6; sfb++) + sf[0].l[sfb] = bitget(slen0); + if (scfsi & 4) + for (; sfb < 11; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 11; sfb++) + sf[0].l[sfb] = bitget(slen0); + if (scfsi & 2) + for (; sfb < 16; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 16; sfb++) + sf[0].l[sfb] = bitget(slen1); + if (scfsi & 1) + for (; sfb < 21; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 21; sfb++) + sf[0].l[sfb] = bitget(slen1); + + return; } /*=============================================================*/ -void unpack_sf_sub_MPEG2(SCALEFACT sf[], - GR * grdat, - int is_and_ch, IS_SF_INFO * sf_info) -{ - int sfb; - int slen1, slen2, slen3, slen4; - int nr1, nr2, nr3, nr4; - int i, k; - int preflag, intensity_scale; - int block_type, mixed_block_flag, scalefac_compress; - - - block_type = grdat->block_type; - mixed_block_flag = grdat->mixed_block_flag; - scalefac_compress = grdat->scalefac_compress; - - preflag = 0; - intensity_scale = 0; /* to avoid compiler warning */ - if (is_and_ch == 0) - { - if (scalefac_compress < 400) - { - slen2 = scalefac_compress >> 4; - slen1 = slen2 / 5; - slen2 = slen2 % 5; - slen4 = scalefac_compress & 15; - slen3 = slen4 >> 2; - slen4 = slen4 & 3; - k = 0; - } - else if (scalefac_compress < 500) - { - scalefac_compress -= 400; - slen2 = scalefac_compress >> 2; - slen1 = slen2 / 5; - slen2 = slen2 % 5; - slen3 = scalefac_compress & 3; - slen4 = 0; - k = 1; - } - else - { - scalefac_compress -= 500; - slen1 = scalefac_compress / 3; - slen2 = scalefac_compress % 3; - slen3 = slen4 = 0; - if (mixed_block_flag) - { - slen3 = slen2; /* adjust for long/short mix logic */ - slen2 = slen1; - } - preflag = 1; - k = 2; - } - } - else - { /* intensity stereo ch = 1 (right) */ - intensity_scale = scalefac_compress & 1; - scalefac_compress >>= 1; - if (scalefac_compress < 180) - { - slen1 = scalefac_compress / 36; - slen2 = scalefac_compress % 36; - slen3 = slen2 % 6; - slen2 = slen2 / 6; - slen4 = 0; - k = 3 + 0; - } - else if (scalefac_compress < 244) - { - scalefac_compress -= 180; - slen3 = scalefac_compress & 3; - scalefac_compress >>= 2; - slen2 = scalefac_compress & 3; - slen1 = scalefac_compress >> 2; - slen4 = 0; - k = 3 + 1; - } - else - { - scalefac_compress -= 244; - slen1 = scalefac_compress / 3; - slen2 = scalefac_compress % 3; - slen3 = slen4 = 0; - k = 3 + 2; - } - } - - i = 0; - if (block_type == 2) - i = (mixed_block_flag & 1) + 1; - nr1 = nr_table[k][i][0]; - nr2 = nr_table[k][i][1]; - nr3 = nr_table[k][i][2]; - nr4 = nr_table[k][i][3]; - - -/* return is scale factor info (for right chan is mode) */ - if (is_and_ch) - { - sf_info->nr[0] = nr1; - sf_info->nr[1] = nr2; - sf_info->nr[2] = nr3; - sf_info->slen[0] = slen1; - sf_info->slen[1] = slen2; - sf_info->slen[2] = slen3; - sf_info->intensity_scale = intensity_scale; - } - grdat->preflag = preflag; /* return preflag */ - -/*--------------------------------------*/ - if (block_type == 2) - { - if (mixed_block_flag) - { /* mixed */ - if (slen1 != 0) /* long block portion */ - for (sfb = 0; sfb < 6; sfb++) - sf[0].l[sfb] = bitget(slen1); - else - for (sfb = 0; sfb < 6; sfb++) - sf[0].l[sfb] = 0; - sfb = 3; /* start sfb for short */ - } - else - { /* all short, initial short blocks */ - sfb = 0; - if (slen1 != 0) - for (i = 0; i < nr1; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - else - for (i = 0; i < nr1; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - } -/* remaining short blocks */ - if (slen2 != 0) - for (i = 0; i < nr2; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen2); - sf[0].s[1][sfb] = bitget(slen2); - sf[0].s[2][sfb] = bitget(slen2); - } - else - for (i = 0; i < nr2; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - if (slen3 != 0) - for (i = 0; i < nr3; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen3); - sf[0].s[1][sfb] = bitget(slen3); - sf[0].s[2][sfb] = bitget(slen3); - } - else - for (i = 0; i < nr3; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - if (slen4 != 0) - for (i = 0; i < nr4; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen4); - sf[0].s[1][sfb] = bitget(slen4); - sf[0].s[2][sfb] = bitget(slen4); - } - else - for (i = 0; i < nr4; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - return; - } - - -/* long blocks types 0 1 3 */ - sfb = 0; - if (slen1 != 0) - for (i = 0; i < nr1; i++, sfb++) - sf[0].l[sfb] = bitget(slen1); - else - for (i = 0; i < nr1; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen2 != 0) - for (i = 0; i < nr2; i++, sfb++) - sf[0].l[sfb] = bitget(slen2); - else - for (i = 0; i < nr2; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen3 != 0) - for (i = 0; i < nr3; i++, sfb++) - sf[0].l[sfb] = bitget(slen3); - else - for (i = 0; i < nr3; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen4 != 0) - for (i = 0; i < nr4; i++, sfb++) - sf[0].l[sfb] = bitget(slen4); - else - for (i = 0; i < nr4; i++, sfb++) - sf[0].l[sfb] = 0; - - +void unpack_sf_sub_MPEG2(SCALEFACT sf[], GR *grdat, int is_and_ch, IS_SF_INFO *sf_info) { + int sfb; + int slen1, slen2, slen3, slen4; + int nr1, nr2, nr3, nr4; + int i, k; + int preflag, intensity_scale; + int block_type, mixed_block_flag, scalefac_compress; + + block_type = grdat->block_type; + mixed_block_flag = grdat->mixed_block_flag; + scalefac_compress = grdat->scalefac_compress; + + preflag = 0; + intensity_scale = 0; /* to avoid compiler warning */ + if (is_and_ch == 0) { + if (scalefac_compress < 400) { + slen2 = scalefac_compress >> 4; + slen1 = slen2 / 5; + slen2 = slen2 % 5; + slen4 = scalefac_compress & 15; + slen3 = slen4 >> 2; + slen4 = slen4 & 3; + k = 0; + } else if (scalefac_compress < 500) { + scalefac_compress -= 400; + slen2 = scalefac_compress >> 2; + slen1 = slen2 / 5; + slen2 = slen2 % 5; + slen3 = scalefac_compress & 3; + slen4 = 0; + k = 1; + } else { + scalefac_compress -= 500; + slen1 = scalefac_compress / 3; + slen2 = scalefac_compress % 3; + slen3 = slen4 = 0; + if (mixed_block_flag) { + slen3 = slen2; /* adjust for long/short mix logic */ + slen2 = slen1; + } + preflag = 1; + k = 2; + } + } else { /* intensity stereo ch = 1 (right) */ + intensity_scale = scalefac_compress & 1; + scalefac_compress >>= 1; + if (scalefac_compress < 180) { + slen1 = scalefac_compress / 36; + slen2 = scalefac_compress % 36; + slen3 = slen2 % 6; + slen2 = slen2 / 6; + slen4 = 0; + k = 3 + 0; + } else if (scalefac_compress < 244) { + scalefac_compress -= 180; + slen3 = scalefac_compress & 3; + scalefac_compress >>= 2; + slen2 = scalefac_compress & 3; + slen1 = scalefac_compress >> 2; + slen4 = 0; + k = 3 + 1; + } else { + scalefac_compress -= 244; + slen1 = scalefac_compress / 3; + slen2 = scalefac_compress % 3; + slen3 = slen4 = 0; + k = 3 + 2; + } + } + + i = 0; + if (block_type == 2) + i = (mixed_block_flag & 1) + 1; + nr1 = nr_table[k][i][0]; + nr2 = nr_table[k][i][1]; + nr3 = nr_table[k][i][2]; + nr4 = nr_table[k][i][3]; + + /* return is scale factor info (for right chan is mode) */ + if (is_and_ch) { + sf_info->nr[0] = nr1; + sf_info->nr[1] = nr2; + sf_info->nr[2] = nr3; + sf_info->slen[0] = slen1; + sf_info->slen[1] = slen2; + sf_info->slen[2] = slen3; + sf_info->intensity_scale = intensity_scale; + } + grdat->preflag = preflag; /* return preflag */ + + /*--------------------------------------*/ + if (block_type == 2) { + if (mixed_block_flag) { /* mixed */ + if (slen1 != 0) /* long block portion */ + for (sfb = 0; sfb < 6; sfb++) + sf[0].l[sfb] = bitget(slen1); + else + for (sfb = 0; sfb < 6; sfb++) + sf[0].l[sfb] = 0; + sfb = 3; /* start sfb for short */ + } else { /* all short, initial short blocks */ + sfb = 0; + if (slen1 != 0) + for (i = 0; i < nr1; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + else + for (i = 0; i < nr1; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + } + /* remaining short blocks */ + if (slen2 != 0) + for (i = 0; i < nr2; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen2); + sf[0].s[1][sfb] = bitget(slen2); + sf[0].s[2][sfb] = bitget(slen2); + } + else + for (i = 0; i < nr2; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + if (slen3 != 0) + for (i = 0; i < nr3; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen3); + sf[0].s[1][sfb] = bitget(slen3); + sf[0].s[2][sfb] = bitget(slen3); + } + else + for (i = 0; i < nr3; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + if (slen4 != 0) + for (i = 0; i < nr4; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen4); + sf[0].s[1][sfb] = bitget(slen4); + sf[0].s[2][sfb] = bitget(slen4); + } + else + for (i = 0; i < nr4; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + return; + } + + /* long blocks types 0 1 3 */ + sfb = 0; + if (slen1 != 0) + for (i = 0; i < nr1; i++, sfb++) + sf[0].l[sfb] = bitget(slen1); + else + for (i = 0; i < nr1; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen2 != 0) + for (i = 0; i < nr2; i++, sfb++) + sf[0].l[sfb] = bitget(slen2); + else + for (i = 0; i < nr2; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen3 != 0) + for (i = 0; i < nr3; i++, sfb++) + sf[0].l[sfb] = bitget(slen3); + else + for (i = 0; i < nr3; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen4 != 0) + for (i = 0; i < nr4; i++, sfb++) + sf[0].l[sfb] = bitget(slen4); + else + for (i = 0; i < nr4; i++, sfb++) + sf[0].l[sfb] = 0; } /*-------------------------------------------------*/ diff --git a/code/qcommon/cm_load.cpp b/code/qcommon/cm_load.cpp index 5407ffb0f3..a820807b30 100644 --- a/code/qcommon/cm_load.cpp +++ b/code/qcommon/cm_load.cpp @@ -28,55 +28,52 @@ along with this program; if not, see . #include "qcommon/ojk_saved_game_helper.h" #ifdef BSPC -void SetPlaneSignbits (cplane_t *out) { - int bits, j; +void SetPlaneSignbits(cplane_t *out) { + int bits, j; // for fast box on planeside test bits = 0; - for (j=0 ; j<3 ; j++) { + for (j = 0; j < 3; j++) { if (out->normal[j] < 0) { - bits |= 1<signbits = bits; } -#endif //BSPC +#endif // BSPC // to allow boxes to be treated as brush models, we allocate // some extra indexes along with those needed by the map -#define BOX_BRUSHES 1 -#define BOX_SIDES 6 -#define BOX_LEAFS 2 -#define BOX_PLANES 12 +#define BOX_BRUSHES 1 +#define BOX_SIDES 6 +#define BOX_LEAFS 2 +#define BOX_PLANES 12 -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) +clipMap_t cmg; +int c_pointcontents; +int c_traces, c_brush_traces, c_patch_traces; -clipMap_t cmg; -int c_pointcontents; -int c_traces, c_brush_traces, c_patch_traces; - - -byte *cmod_base; +byte *cmod_base; #ifndef BSPC -cvar_t *cm_noAreas; -cvar_t *cm_noCurves; -cvar_t *cm_playerCurveClip; +cvar_t *cm_noAreas; +cvar_t *cm_noCurves; +cvar_t *cm_playerCurveClip; #endif -cmodel_t box_model; -cplane_t *box_planes; -cbrush_t *box_brush; +cmodel_t box_model; +cplane_t *box_planes; +cbrush_t *box_brush; -int CM_OrOfAllContentsFlagsInMap; +int CM_OrOfAllContentsFlagsInMap; +void CM_InitBoxHull(void); +void CM_FloodAreaConnections(clipMap_t &cm); -void CM_InitBoxHull (void); -void CM_FloodAreaConnections (clipMap_t &cm); - -clipMap_t SubBSP[MAX_SUB_BSP]; -int NumSubBSP = 0, TotalSubModels = 0; +clipMap_t SubBSP[MAX_SUB_BSP]; +int NumSubBSP = 0, TotalSubModels = 0; /* =============================================================================== @@ -91,133 +88,124 @@ int NumSubBSP = 0, TotalSubModels = 0; CMod_LoadShaders ================= */ -void CMod_LoadShaders( lump_t *l, clipMap_t &cm ) -{ - dshader_t *in; - int i, count; - CCMShader *out; +void CMod_LoadShaders(lump_t *l, clipMap_t &cm) { + dshader_t *in; + int i, count; + CCMShader *out; in = (dshader_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) { - Com_Error (ERR_DROP, "CMod_LoadShaders: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadShaders: funny lump size"); } count = l->filelen / sizeof(*in); if (count < 1) { - Com_Error (ERR_DROP, "Map with no shaders"); + Com_Error(ERR_DROP, "Map with no shaders"); } - cm.shaders = (CCMShader *)Z_Malloc( (1 + count) * sizeof( *cm.shaders ), TAG_BSP, qtrue ); //+1 for the BOX_SIDES to point at + cm.shaders = (CCMShader *)Z_Malloc((1 + count) * sizeof(*cm.shaders), TAG_BSP, qtrue); //+1 for the BOX_SIDES to point at cm.numShaders = count; out = cm.shaders; - for ( i = 0; i < count; i++, in++, out++ ) - { + for (i = 0; i < count; i++, in++, out++) { Q_strncpyz(out->shader, in->shader, MAX_QPATH); - out->contentFlags = LittleLong( in->contentFlags ); - out->surfaceFlags = LittleLong( in->surfaceFlags ); + out->contentFlags = LittleLong(in->contentFlags); + out->surfaceFlags = LittleLong(in->surfaceFlags); } } - /* ================= CMod_LoadSubmodels ================= */ -void CMod_LoadSubmodels( lump_t *l, clipMap_t &cm ) { - dmodel_t *in; - cmodel_t *out; - int i, j, count; - int *indexes; +void CMod_LoadSubmodels(lump_t *l, clipMap_t &cm) { + dmodel_t *in; + cmodel_t *out; + int i, j, count; + int *indexes; in = (dmodel_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadSubmodels: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadSubmodels: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) { - Com_Error (ERR_DROP, "Map with no models"); + Com_Error(ERR_DROP, "Map with no models"); } - //FIXME: note that MAX_SUBMODELS - 1 is used for BOX_MODEL_HANDLE, if that slot gets used, that would be bad, no? - if ( count > MAX_SUBMODELS ) { - Com_Error( ERR_DROP, "MAX_SUBMODELS (%d) exceeded by %d", MAX_SUBMODELS, count-MAX_SUBMODELS ); + // FIXME: note that MAX_SUBMODELS - 1 is used for BOX_MODEL_HANDLE, if that slot gets used, that would be bad, no? + if (count > MAX_SUBMODELS) { + Com_Error(ERR_DROP, "MAX_SUBMODELS (%d) exceeded by %d", MAX_SUBMODELS, count - MAX_SUBMODELS); } - cm.cmodels = (struct cmodel_s *) Z_Malloc( count * sizeof( *cm.cmodels ), TAG_BSP, qtrue ); + cm.cmodels = (struct cmodel_s *)Z_Malloc(count * sizeof(*cm.cmodels), TAG_BSP, qtrue); cm.numSubModels = count; - for ( i=0 ; imins[j] = LittleFloat (in->mins[j]) - 1; - out->maxs[j] = LittleFloat (in->maxs[j]) + 1; + for (j = 0; j < 3; j++) { // spread the mins / maxs by a pixel + out->mins[j] = LittleFloat(in->mins[j]) - 1; + out->maxs[j] = LittleFloat(in->maxs[j]) + 1; } - //rww - I changed this to do the &cm == &cmg check. sof2 does not have to do this, - //but I think they have a different tracing system that allows it to catch subbsp - //stuff without extra leaf data. The reason we have to do this for subbsp instances - //is that they often are compiled in a sort of "prefab" form, so the first model isn't - //necessarily the world model. - if ( i == 0 && &cm == &cmg ) { - continue; // world model doesn't need other info + // rww - I changed this to do the &cm == &cmg check. sof2 does not have to do this, + // but I think they have a different tracing system that allows it to catch subbsp + // stuff without extra leaf data. The reason we have to do this for subbsp instances + // is that they often are compiled in a sort of "prefab" form, so the first model isn't + // necessarily the world model. + if (i == 0 && &cm == &cmg) { + continue; // world model doesn't need other info } // make a "leaf" just to hold the model's brushes and surfaces - out->leaf.numLeafBrushes = LittleLong( in->numBrushes ); - indexes = (int *) Z_Malloc( out->leaf.numLeafBrushes * 4, TAG_BSP, qfalse); + out->leaf.numLeafBrushes = LittleLong(in->numBrushes); + indexes = (int *)Z_Malloc(out->leaf.numLeafBrushes * 4, TAG_BSP, qfalse); out->leaf.firstLeafBrush = indexes - cm.leafbrushes; - for ( j = 0 ; j < out->leaf.numLeafBrushes ; j++ ) { - indexes[j] = LittleLong( in->firstBrush ) + j; + for (j = 0; j < out->leaf.numLeafBrushes; j++) { + indexes[j] = LittleLong(in->firstBrush) + j; } - out->leaf.numLeafSurfaces = LittleLong( in->numSurfaces ); - indexes = (int *) Z_Malloc( out->leaf.numLeafSurfaces * 4, TAG_BSP, qfalse); + out->leaf.numLeafSurfaces = LittleLong(in->numSurfaces); + indexes = (int *)Z_Malloc(out->leaf.numLeafSurfaces * 4, TAG_BSP, qfalse); out->leaf.firstLeafSurface = indexes - cm.leafsurfaces; - for ( j = 0 ; j < out->leaf.numLeafSurfaces ; j++ ) { - indexes[j] = LittleLong( in->firstSurface ) + j; + for (j = 0; j < out->leaf.numLeafSurfaces; j++) { + indexes[j] = LittleLong(in->firstSurface) + j; } } } - /* ================= CMod_LoadNodes ================= */ -void CMod_LoadNodes( lump_t *l, clipMap_t &cm ) { - dnode_t *in; - int child; - cNode_t *out; - int i, j, count; +void CMod_LoadNodes(lump_t *l, clipMap_t &cm) { + dnode_t *in; + int child; + cNode_t *out; + int i, j, count; in = (dnode_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map has no nodes"); - cm.nodes = (cNode_t *) Z_Malloc( count * sizeof( *cm.nodes ), TAG_BSP, qfalse); + Com_Error(ERR_DROP, "Map has no nodes"); + cm.nodes = (cNode_t *)Z_Malloc(count * sizeof(*cm.nodes), TAG_BSP, qfalse); cm.numNodes = count; out = cm.nodes; - for (i=0 ; iplane = cm.planes + LittleLong( in->planeNum ); - for (j=0 ; j<2 ; j++) - { - child = LittleLong (in->children[j]); + for (i = 0; i < count; i++, out++, in++) { + out->plane = cm.planes + LittleLong(in->planeNum); + for (j = 0; j < 2; j++) { + child = LittleLong(in->children[j]); out->children[j] = child; } } - } /* @@ -226,7 +214,7 @@ CM_BoundBrush ================= */ -void CM_BoundBrush( cbrush_t *b ) { +void CM_BoundBrush(cbrush_t *b) { b->bounds[0][0] = -b->sides[0].plane->dist; b->bounds[1][0] = b->sides[1].plane->dist; @@ -237,51 +225,48 @@ void CM_BoundBrush( cbrush_t *b ) { b->bounds[1][2] = b->sides[5].plane->dist; } - /* ================= CMod_LoadBrushes ================= */ -void CMod_LoadBrushes( lump_t *l, clipMap_t &cm ) { - dbrush_t *in; - cbrush_t *out; - int i, count; +void CMod_LoadBrushes(lump_t *l, clipMap_t &cm) { + dbrush_t *in; + cbrush_t *out; + int i, count; in = (dbrush_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) { - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); } count = l->filelen / sizeof(*in); - cm.brushes = (cbrush_t *) Z_Malloc( ( BOX_BRUSHES + count ) * sizeof( *cm.brushes ), TAG_BSP, qfalse); + cm.brushes = (cbrush_t *)Z_Malloc((BOX_BRUSHES + count) * sizeof(*cm.brushes), TAG_BSP, qfalse); cm.numBrushes = count; out = cm.brushes; - for ( i=0 ; isides = cm.brushsides + LittleLong(in->firstSide); out->numsides = LittleLong(in->numSides); - out->shaderNum = LittleLong( in->shaderNum ); - if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) { - Com_Error( ERR_DROP, "CMod_LoadBrushes: bad shaderNum: %i", out->shaderNum ); + out->shaderNum = LittleLong(in->shaderNum); + if (out->shaderNum < 0 || out->shaderNum >= cm.numShaders) { + Com_Error(ERR_DROP, "CMod_LoadBrushes: bad shaderNum: %i", out->shaderNum); } out->contents = cm.shaders[out->shaderNum].contentFlags; #ifdef JK2_MODE - //JK2 HACK: for water that cuts vis but is not solid!!! (used on yavin swamp) - if ( cm.shaders[out->shaderNum].surfaceFlags & SURF_SLICK ) - { + // JK2 HACK: for water that cuts vis but is not solid!!! (used on yavin swamp) + if (cm.shaders[out->shaderNum].surfaceFlags & SURF_SLICK) { out->contents &= ~CONTENTS_SOLID; } #endif CM_OrOfAllContentsFlagsInMap |= out->contents; - out->checkcount=0; + out->checkcount = 0; - CM_BoundBrush( out ); + CM_BoundBrush(out); } - } /* @@ -289,33 +274,31 @@ void CMod_LoadBrushes( lump_t *l, clipMap_t &cm ) { CMod_LoadLeafs ================= */ -void CMod_LoadLeafs (lump_t *l, clipMap_t &cm) -{ - int i; - cLeaf_t *out; - dleaf_t *in; - int count; +void CMod_LoadLeafs(lump_t *l, clipMap_t &cm) { + int i; + cLeaf_t *out; + dleaf_t *in; + int count; in = (dleaf_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map with no leafs"); + Com_Error(ERR_DROP, "Map with no leafs"); - cm.leafs = (cLeaf_t *) Z_Malloc( ( BOX_LEAFS + count ) * sizeof( *cm.leafs ), TAG_BSP, qfalse); + cm.leafs = (cLeaf_t *)Z_Malloc((BOX_LEAFS + count) * sizeof(*cm.leafs), TAG_BSP, qfalse); cm.numLeafs = count; out = cm.leafs; - for ( i=0 ; icluster = LittleLong (in->cluster); - out->area = LittleLong (in->area); - out->firstLeafBrush = LittleLong (in->firstLeafBrush); - out->numLeafBrushes = LittleLong (in->numLeafBrushes); - out->firstLeafSurface = LittleLong (in->firstLeafSurface); - out->numLeafSurfaces = LittleLong (in->numLeafSurfaces); + for (i = 0; i < count; i++, in++, out++) { + out->cluster = LittleLong(in->cluster); + out->area = LittleLong(in->area); + out->firstLeafBrush = LittleLong(in->firstLeafBrush); + out->numLeafBrushes = LittleLong(in->numLeafBrushes); + out->firstLeafSurface = LittleLong(in->firstLeafSurface); + out->numLeafSurfaces = LittleLong(in->numLeafSurfaces); if (out->cluster >= cm.numClusters) cm.numClusters = out->cluster + 1; @@ -323,8 +306,8 @@ void CMod_LoadLeafs (lump_t *l, clipMap_t &cm) cm.numAreas = out->area + 1; } - cm.areas = (cArea_t *) Z_Malloc( cm.numAreas * sizeof( *cm.areas ), TAG_BSP, qtrue ); - cm.areaPortals = (int *) Z_Malloc( cm.numAreas * cm.numAreas * sizeof( *cm.areaPortals ), TAG_BSP, qtrue ); + cm.areas = (cArea_t *)Z_Malloc(cm.numAreas * sizeof(*cm.areas), TAG_BSP, qtrue); + cm.areaPortals = (int *)Z_Malloc(cm.numAreas * cm.numAreas * sizeof(*cm.areaPortals), TAG_BSP, qtrue); } /* @@ -332,38 +315,35 @@ void CMod_LoadLeafs (lump_t *l, clipMap_t &cm) CMod_LoadPlanes ================= */ -void CMod_LoadPlanes (lump_t *l, clipMap_t &cm) -{ - int i, j; - cplane_t *out; - dplane_t *in; - int count; - int bits; +void CMod_LoadPlanes(lump_t *l, clipMap_t &cm) { + int i, j; + cplane_t *out; + dplane_t *in; + int count; + int bits; in = (dplane_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map with no planes"); - cm.planes = (struct cplane_s *) Z_Malloc( ( BOX_PLANES + count ) * sizeof( *cm.planes ), TAG_BSP, qfalse); + Com_Error(ERR_DROP, "Map with no planes"); + cm.planes = (struct cplane_s *)Z_Malloc((BOX_PLANES + count) * sizeof(*cm.planes), TAG_BSP, qfalse); cm.numPlanes = count; out = cm.planes; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + for (j = 0; j < 3; j++) { + out->normal[j] = LittleFloat(in->normal[j]); if (out->normal[j] < 0) - bits |= 1<dist = LittleFloat (in->dist); - out->type = PlaneTypeForNormal( out->normal ); + out->dist = LittleFloat(in->dist); + out->type = PlaneTypeForNormal(out->normal); out->signbits = bits; } } @@ -373,25 +353,24 @@ void CMod_LoadPlanes (lump_t *l, clipMap_t &cm) CMod_LoadLeafBrushes ================= */ -void CMod_LoadLeafBrushes (lump_t *l, clipMap_t &cm) -{ - int i; - int *out; - int *in; - int count; +void CMod_LoadLeafBrushes(lump_t *l, clipMap_t &cm) { + int i; + int *out; + int *in; + int count; in = (int *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); count = l->filelen / sizeof(*in); - cm.leafbrushes = (int *) Z_Malloc( ( BOX_BRUSHES + count ) * sizeof( *cm.leafbrushes ), TAG_BSP, qfalse); + cm.leafbrushes = (int *)Z_Malloc((BOX_BRUSHES + count) * sizeof(*cm.leafbrushes), TAG_BSP, qfalse); cm.numLeafBrushes = count; out = cm.leafbrushes; - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); count = l->filelen / sizeof(*in); - cm.leafsurfaces = (int *) Z_Malloc( count * sizeof( *cm.leafsurfaces ), TAG_BSP, qfalse); + cm.leafsurfaces = (int *)Z_Malloc(count * sizeof(*cm.leafsurfaces), TAG_BSP, qfalse); cm.numLeafSurfaces = count; out = cm.leafsurfaces; - for ( i=0 ; ifileofs); - if ( l->filelen % sizeof(*in) ) { - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + if (l->filelen % sizeof(*in)) { + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); } count = l->filelen / sizeof(*in); - cm.brushsides = (cbrushside_t *) Z_Malloc( ( BOX_SIDES + count ) * sizeof( *cm.brushsides ), TAG_BSP, qfalse); + cm.brushsides = (cbrushside_t *)Z_Malloc((BOX_SIDES + count) * sizeof(*cm.brushsides), TAG_BSP, qfalse); cm.numBrushSides = count; out = cm.brushsides; - for ( i=0 ; iplaneNum ); + for (i = 0; i < count; i++, in++, out++) { + num = LittleLong(in->planeNum); out->plane = &cm.planes[num]; - out->shaderNum = LittleLong( in->shaderNum ); - if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) { - Com_Error( ERR_DROP, "CMod_LoadBrushSides: bad shaderNum: %i", out->shaderNum ); + out->shaderNum = LittleLong(in->shaderNum); + if (out->shaderNum < 0 || out->shaderNum >= cm.numShaders) { + Com_Error(ERR_DROP, "CMod_LoadBrushSides: bad shaderNum: %i", out->shaderNum); } -// out->surfaceFlags = cm.shaders[out->shaderNum].surfaceFlags; + // out->surfaceFlags = cm.shaders[out->shaderNum].surfaceFlags; } } - /* ================= CMod_LoadEntityString ================= */ -void CMod_LoadEntityString( lump_t *l, clipMap_t &cm, const char* name ) { +void CMod_LoadEntityString(lump_t *l, clipMap_t &cm, const char *name) { fileHandle_t h; char entName[MAX_QPATH]; @@ -474,9 +450,8 @@ void CMod_LoadEntityString( lump_t *l, clipMap_t &cm, const char* name ) { entName[entNameLen - 2] = 'n'; entName[entNameLen - 1] = 't'; const int iEntityFileLen = FS_FOpenFileRead(entName, &h, qfalse); - if (h) - { - cm.entityString = (char *) Z_Malloc( iEntityFileLen + 1, TAG_BSP, qfalse ); + if (h) { + cm.entityString = (char *)Z_Malloc(iEntityFileLen + 1, TAG_BSP, qfalse); cm.numEntityChars = iEntityFileLen + 1; FS_Read(cm.entityString, iEntityFileLen, h); FS_FCloseFile(h); @@ -485,9 +460,9 @@ void CMod_LoadEntityString( lump_t *l, clipMap_t &cm, const char* name ) { return; } - cm.entityString = (char *) Z_Malloc( l->filelen, TAG_BSP, qfalse); + cm.entityString = (char *)Z_Malloc(l->filelen, TAG_BSP, qfalse); cm.numEntityChars = l->filelen; - memcpy (cm.entityString, cmod_base + l->fileofs, l->filelen); + memcpy(cm.entityString, cmod_base + l->fileofs, l->filelen); } /* @@ -495,90 +470,89 @@ void CMod_LoadEntityString( lump_t *l, clipMap_t &cm, const char* name ) { CMod_LoadVisibility ================= */ -#define VIS_HEADER 8 -void CMod_LoadVisibility( lump_t *l, clipMap_t &cm ) { - int len; - byte *buf; - - len = l->filelen; - if ( !len ) { - cm.clusterBytes = ( cm.numClusters + 31 ) & ~31; - cm.visibility = (unsigned char *) Z_Malloc( cm.clusterBytes, TAG_BSP, qfalse); - memset( cm.visibility, 255, cm.clusterBytes ); +#define VIS_HEADER 8 +void CMod_LoadVisibility(lump_t *l, clipMap_t &cm) { + int len; + byte *buf; + + len = l->filelen; + if (!len) { + cm.clusterBytes = (cm.numClusters + 31) & ~31; + cm.visibility = (unsigned char *)Z_Malloc(cm.clusterBytes, TAG_BSP, qfalse); + memset(cm.visibility, 255, cm.clusterBytes); return; } buf = cmod_base + l->fileofs; cm.vised = qtrue; - cm.visibility = (unsigned char *) Z_Malloc( len, TAG_BSP, qtrue ); - cm.numClusters = LittleLong( ((int *)buf)[0] ); - cm.clusterBytes = LittleLong( ((int *)buf)[1] ); - memcpy (cm.visibility, buf + VIS_HEADER, len - VIS_HEADER ); + cm.visibility = (unsigned char *)Z_Malloc(len, TAG_BSP, qtrue); + cm.numClusters = LittleLong(((int *)buf)[0]); + cm.clusterBytes = LittleLong(((int *)buf)[1]); + memcpy(cm.visibility, buf + VIS_HEADER, len - VIS_HEADER); } //================================================================== - /* ================= CMod_LoadPatches ================= */ -#define MAX_PATCH_VERTS 1024 -void CMod_LoadPatches( lump_t *surfs, lump_t *verts, clipMap_t &cm ) { - mapVert_t *dv, *dv_p; - dsurface_t *in; - int count; - int i, j; - int c; - cPatch_t *patch; - vec3_t points[MAX_PATCH_VERTS]; - int width, height; - int shaderNum; +#define MAX_PATCH_VERTS 1024 +void CMod_LoadPatches(lump_t *surfs, lump_t *verts, clipMap_t &cm) { + mapVert_t *dv, *dv_p; + dsurface_t *in; + int count; + int i, j; + int c; + cPatch_t *patch; + vec3_t points[MAX_PATCH_VERTS]; + int width, height; + int shaderNum; in = (dsurface_t *)(cmod_base + surfs->fileofs); if (surfs->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); cm.numSurfaces = count = surfs->filelen / sizeof(*in); - cm.surfaces = (cPatch_t **) Z_Malloc( cm.numSurfaces * sizeof( cm.surfaces[0] ), TAG_BSP, qtrue ); + cm.surfaces = (cPatch_t **)Z_Malloc(cm.numSurfaces * sizeof(cm.surfaces[0]), TAG_BSP, qtrue); dv = (mapVert_t *)(cmod_base + verts->fileofs); if (verts->filelen % sizeof(*dv)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); // scan through all the surfaces, but only load patches, // not planar faces - for ( i = 0 ; i < count ; i++, in++ ) { - if ( LittleLong( in->surfaceType ) != MST_PATCH ) { - continue; // ignore other surfaces + for (i = 0; i < count; i++, in++) { + if (LittleLong(in->surfaceType) != MST_PATCH) { + continue; // ignore other surfaces } // FIXME: check for non-colliding patches - cm.surfaces[ i ] = patch = (cPatch_t *) Z_Malloc( sizeof( *patch ), TAG_BSP, qtrue ); + cm.surfaces[i] = patch = (cPatch_t *)Z_Malloc(sizeof(*patch), TAG_BSP, qtrue); // load the full drawverts onto the stack - width = LittleLong( in->patchWidth ); - height = LittleLong( in->patchHeight ); + width = LittleLong(in->patchWidth); + height = LittleLong(in->patchHeight); c = width * height; - if ( c > MAX_PATCH_VERTS ) { - Com_Error( ERR_DROP, "ParseMesh: MAX_PATCH_VERTS" ); + if (c > MAX_PATCH_VERTS) { + Com_Error(ERR_DROP, "ParseMesh: MAX_PATCH_VERTS"); } - dv_p = dv + LittleLong( in->firstVert ); - for ( j = 0 ; j < c ; j++, dv_p++ ) { - points[j][0] = LittleFloat( dv_p->xyz[0] ); - points[j][1] = LittleFloat( dv_p->xyz[1] ); - points[j][2] = LittleFloat( dv_p->xyz[2] ); + dv_p = dv + LittleLong(in->firstVert); + for (j = 0; j < c; j++, dv_p++) { + points[j][0] = LittleFloat(dv_p->xyz[0]); + points[j][1] = LittleFloat(dv_p->xyz[1]); + points[j][2] = LittleFloat(dv_p->xyz[2]); } - shaderNum = LittleLong( in->shaderNum ); + shaderNum = LittleLong(in->shaderNum); patch->contents = cm.shaders[shaderNum].contentFlags; CM_OrOfAllContentsFlagsInMap |= patch->contents; patch->surfaceFlags = cm.shaders[shaderNum].surfaceFlags; // create the internal facet structure - patch->pc = CM_GeneratePatchCollide( width, height, points ); + patch->pc = CM_GeneratePatchCollide(width, height, points); } } @@ -593,11 +567,11 @@ Free any loaded map and all submodels ================== */ void CM_FreeMap(void) { - memset( &cm, 0, sizeof( cm ) ); + memset(&cm, 0, sizeof(cm)); Hunk_ClearHigh(); CM_ClearLevelPatches(); } -#endif //BSPC +#endif // BSPC /* ================== @@ -607,25 +581,22 @@ Loads in the map and all submodels ================== */ void *gpvCachedMapDiskImage = NULL; -char gsCachedMapDiskImage[MAX_QPATH]; -qboolean gbUsingCachedMapDataRightNow = qfalse; // if true, signifies that you can't delete this at the moment!! (used during z_malloc()-fail recovery attempt) +char gsCachedMapDiskImage[MAX_QPATH]; +qboolean gbUsingCachedMapDataRightNow = qfalse; // if true, signifies that you can't delete this at the moment!! (used during z_malloc()-fail recovery attempt) // called in response to a "devmapbsp blah" or "devmapall blah" command, do NOT use inside CM_Load unless you pass in qtrue // // new bool return used to see if anything was freed, used during z_malloc failure re-try // -qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) -{ +qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) { qboolean bActuallyFreedSomething = qfalse; - if (bGuaranteedOkToDelete || !gbUsingCachedMapDataRightNow) - { + if (bGuaranteedOkToDelete || !gbUsingCachedMapDataRightNow) { // dump cached disk image... // - if (gpvCachedMapDiskImage) - { - Z_Free( gpvCachedMapDiskImage ); - gpvCachedMapDiskImage = NULL; + if (gpvCachedMapDiskImage) { + Z_Free(gpvCachedMapDiskImage); + gpvCachedMapDiskImage = NULL; bActuallyFreedSomething = qtrue; } @@ -639,80 +610,72 @@ qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) return bActuallyFreedSomething; } -static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *checksum, clipMap_t &cm ) { - const int *buf; - size_t i; - dheader_t header; - static unsigned last_checksum; - void *subBSPData = NULL; +static void CM_LoadMap_Actual(const char *name, qboolean clientload, int *checksum, clipMap_t &cm) { + const int *buf; + size_t i; + dheader_t header; + static unsigned last_checksum; + void *subBSPData = NULL; - if ( !name || !name[0] ) { - Com_Error( ERR_DROP, "CM_LoadMap: NULL name" ); + if (!name || !name[0]) { + Com_Error(ERR_DROP, "CM_LoadMap: NULL name"); } #ifndef BSPC - cm_noAreas = Cvar_Get ("cm_noAreas", "0", CVAR_CHEAT); - cm_noCurves = Cvar_Get ("cm_noCurves", "0", CVAR_CHEAT); - cm_playerCurveClip = Cvar_Get ("cm_playerCurveClip", "1", CVAR_ARCHIVE_ND|CVAR_CHEAT ); + cm_noAreas = Cvar_Get("cm_noAreas", "0", CVAR_CHEAT); + cm_noCurves = Cvar_Get("cm_noCurves", "0", CVAR_CHEAT); + cm_playerCurveClip = Cvar_Get("cm_playerCurveClip", "1", CVAR_ARCHIVE_ND | CVAR_CHEAT); #endif - Com_DPrintf( "CM_LoadMap( %s, %i )\n", name, clientload ); + Com_DPrintf("CM_LoadMap( %s, %i )\n", name, clientload); - if ( !strcmp( cm.name, name ) && clientload ) { + if (!strcmp(cm.name, name) && clientload) { *checksum = last_checksum; return; } - if (&cm == &cmg) - { + if (&cm == &cmg) { // if there was a cached disk image but the name was empty (ie ERR_DROP happened) or just doesn't match // the current name, then ditch it... // - if (gpvCachedMapDiskImage && - (gsCachedMapDiskImage[0] == '\0' || strcmp( gsCachedMapDiskImage, name )) - ) - { + if (gpvCachedMapDiskImage && (gsCachedMapDiskImage[0] == '\0' || strcmp(gsCachedMapDiskImage, name))) { Z_Free(gpvCachedMapDiskImage); - gpvCachedMapDiskImage = NULL; - gsCachedMapDiskImage[0] = '\0'; + gpvCachedMapDiskImage = NULL; + gsCachedMapDiskImage[0] = '\0'; - CM_ClearMap(); + CM_ClearMap(); } } // if there's a valid map name, and it's the same as last time (respawn?), and it's the server-load, // then keep the data from last time... // - if (name[0] && !strcmp( cm.name, name ) && !clientload && &cm == &cmg ) - { + if (name[0] && !strcmp(cm.name, name) && !clientload && &cm == &cmg) { // clear some stuff that needs zeroing... // cm.floodvalid = 0; - //NO... don't reset this because the brush checkcounts are cached, - //so when you load up, brush checkcounts equal the cm.checkcount - //and the trace will be skipped (because everything loads and - //traces in the same exact order ever time you load the map) - cm.checkcount++;// = 0; - memset(cm.areas, 0, cm.numAreas * sizeof( *cm.areas )); - memset(cm.areaPortals, 0, cm.numAreas * cm.numAreas * sizeof( *cm.areaPortals )); - } - else - { + // NO... don't reset this because the brush checkcounts are cached, + // so when you load up, brush checkcounts equal the cm.checkcount + // and the trace will be skipped (because everything loads and + // traces in the same exact order ever time you load the map) + cm.checkcount++; // = 0; + memset(cm.areas, 0, cm.numAreas * sizeof(*cm.areas)); + memset(cm.areaPortals, 0, cm.numAreas * cm.numAreas * sizeof(*cm.areaPortals)); + } else { // ... else load map from scratch... // - if (&cm == &cmg) - { - assert(!clientload); // logic check. I'm assuming that a client load doesn't get this far? + if (&cm == &cmg) { + assert(!clientload); // logic check. I'm assuming that a client load doesn't get this far? // free old stuff - memset( &cm, 0, sizeof( cm ) ); + memset(&cm, 0, sizeof(cm)); CM_ClearLevelPatches(); Z_TagFree(TAG_BSP); - if ( !name[0] ) { + if (!name[0]) { cm.numLeafs = 1; cm.numClusters = 1; cm.numAreas = 1; - cm.cmodels = (struct cmodel_s *) Z_Malloc( sizeof( *cm.cmodels ), TAG_BSP, qtrue ); + cm.cmodels = (struct cmodel_s *)Z_Malloc(sizeof(*cm.cmodels), TAG_BSP, qtrue); *checksum = 0; return; } @@ -722,99 +685,88 @@ static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *check // then keep it long enough to save the renderer re-loading it, then discard it after that. // fileHandle_t h; - const int iBSPLen = FS_FOpenFileRead( name, &h, qfalse ); - if(!h) - { - Com_Error (ERR_DROP, "Couldn't load %s", name); + const int iBSPLen = FS_FOpenFileRead(name, &h, qfalse); + if (!h) { + Com_Error(ERR_DROP, "Couldn't load %s", name); return; } - //rww - only do this when not loading a sub-bsp! - if (&cm == &cmg) - { - if (gpvCachedMapDiskImage && gsCachedMapDiskImage[0]) - { //didn't get cleared elsewhere so free it before we allocate the pointer again - //Maps with terrain will allow this to happen because they want everything to be cleared out (going between terrain and no-terrain is messy) + // rww - only do this when not loading a sub-bsp! + if (&cm == &cmg) { + if (gpvCachedMapDiskImage && gsCachedMapDiskImage[0]) { // didn't get cleared elsewhere so free it before we allocate the pointer again + // Maps with terrain will allow this to happen because they want everything to be cleared + // out (going between terrain and no-terrain is messy) Z_Free(gpvCachedMapDiskImage); } - gsCachedMapDiskImage[0] = '\0'; // flag that map isn't valid, until name is filled in - gpvCachedMapDiskImage = Z_Malloc( iBSPLen, TAG_BSP_DISKIMAGE, qfalse); + gsCachedMapDiskImage[0] = '\0'; // flag that map isn't valid, until name is filled in + gpvCachedMapDiskImage = Z_Malloc(iBSPLen, TAG_BSP_DISKIMAGE, qfalse); FS_Read(gpvCachedMapDiskImage, iBSPLen, h); - FS_FCloseFile( h ); + FS_FCloseFile(h); - buf = (int*) gpvCachedMapDiskImage; // so the rest of the code works as normal - } - else - { //otherwise, read straight in.. - subBSPData = Z_Malloc( iBSPLen, TAG_BSP_DISKIMAGE, qfalse); + buf = (int *)gpvCachedMapDiskImage; // so the rest of the code works as normal + } else { // otherwise, read straight in.. + subBSPData = Z_Malloc(iBSPLen, TAG_BSP_DISKIMAGE, qfalse); FS_Read(subBSPData, iBSPLen, h); - FS_FCloseFile( h ); + FS_FCloseFile(h); - buf = (int*)subBSPData; + buf = (int *)subBSPData; } // carry on as before... - last_checksum = LittleLong (Com_BlockChecksum (buf, iBSPLen)); + last_checksum = LittleLong(Com_BlockChecksum(buf, iBSPLen)); header = *(dheader_t *)buf; - for (i=0 ; i, if we've got enough ram to keep it for the renderer's disk-load... // extern qboolean Sys_LowPhysicalMemory(); if (Sys_LowPhysicalMemory() //|| com_dedicated->integer // no need to check for dedicated in single-player codebase - ) - { - Z_Free( gpvCachedMapDiskImage ); - gpvCachedMapDiskImage = NULL; - } - else - { + ) { + Z_Free(gpvCachedMapDiskImage); + gpvCachedMapDiskImage = NULL; + } else { // ... do nothing, and let the renderer free it after it's finished playing with it... // } - if (subBSPData) - { + if (subBSPData) { Z_Free(subBSPData); } - if (&cm == &cmg) - { - CM_InitBoxHull (); + if (&cm == &cmg) { + CM_InitBoxHull(); - Q_strncpyz( gsCachedMapDiskImage, name, sizeof(gsCachedMapDiskImage) ); // so the renderer can check it + Q_strncpyz(gsCachedMapDiskImage, name, sizeof(gsCachedMapDiskImage)); // so the renderer can check it } } @@ -822,32 +774,28 @@ static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *check // do this whether or not the map was cached from last load... // - CM_FloodAreaConnections (cm); + CM_FloodAreaConnections(cm); // allow this to be cached if it is loaded by the server - if ( !clientload ) { - Q_strncpyz( cm.name, name, sizeof( cm.name ) ); + if (!clientload) { + Q_strncpyz(cm.name, name, sizeof(cm.name)); } CM_CleanLeafCache(); } // need a wrapper function around this because of multiple returns, need to ensure bool is correct... // -void CM_LoadMap( const char *name, qboolean clientload, int *checksum, qboolean subBSP ) -{ - if (subBSP) - { +void CM_LoadMap(const char *name, qboolean clientload, int *checksum, qboolean subBSP) { + if (subBSP) { Com_DPrintf("^5CM_LoadMap->CMLoadSubBSP(%s, %i)\n", name, qfalse); CM_LoadSubBSP(va("maps/%s.bsp", ((const char *)name) + 1), qfalse); - //CM_LoadMap_Actual( name, clientload, checksum, cmg ); - } - else - { - gbUsingCachedMapDataRightNow = qtrue; // !!!!!!!!!!!!!!!!!! + // CM_LoadMap_Actual( name, clientload, checksum, cmg ); + } else { + gbUsingCachedMapDataRightNow = qtrue; // !!!!!!!!!!!!!!!!!! - CM_LoadMap_Actual( name, clientload, checksum, cmg ); + CM_LoadMap_Actual(name, clientload, checksum, cmg); - gbUsingCachedMapDataRightNow = qfalse; // !!!!!!!!!!!!!!!!!! + gbUsingCachedMapDataRightNow = qfalse; // !!!!!!!!!!!!!!!!!! } /* gbUsingCachedMapDataRightNow = qtrue; // !!!!!!!!!!!!!!!!!! @@ -858,15 +806,12 @@ void CM_LoadMap( const char *name, qboolean clientload, int *checksum, qboolean */ } -qboolean CM_SameMap(const char *server) -{ - if (!cmg.name[0] || !server || !server[0]) - { +qboolean CM_SameMap(const char *server) { + if (!cmg.name[0] || !server || !server[0]) { return qfalse; } - if (Q_stricmp(cmg.name, va("maps/%s.bsp", server))) - { + if (Q_stricmp(cmg.name, va("maps/%s.bsp", server))) { return qfalse; } @@ -878,66 +823,52 @@ qboolean CM_SameMap(const char *server) CM_ClearMap ================== */ -void CM_ClearMap( void ) -{ - int i; +void CM_ClearMap(void) { + int i; CM_OrOfAllContentsFlagsInMap = CONTENTS_BODY; - memset( &cmg, 0, sizeof( cmg ) ); + memset(&cmg, 0, sizeof(cmg)); CM_ClearLevelPatches(); - for(i = 0; i < NumSubBSP; i++) - { + for (i = 0; i < NumSubBSP; i++) { memset(&SubBSP[i], 0, sizeof(SubBSP[0])); } NumSubBSP = 0; TotalSubModels = 0; } -int CM_TotalMapContents() -{ - return CM_OrOfAllContentsFlagsInMap; -} +int CM_TotalMapContents() { return CM_OrOfAllContentsFlagsInMap; } /* ================== CM_ClipHandleToModel ================== */ -cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) -{ - int i; - int count; - - if ( handle < 0 ) - { - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle ); +cmodel_t *CM_ClipHandleToModel(clipHandle_t handle, clipMap_t **clipMap) { + int i; + int count; + + if (handle < 0) { + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle); } - if ( handle < cmg.numSubModels ) - { - if (clipMap) - { + if (handle < cmg.numSubModels) { + if (clipMap) { *clipMap = &cmg; } return &cmg.cmodels[handle]; } - if ( handle == BOX_MODEL_HANDLE ) - { - if (clipMap) - { + if (handle == BOX_MODEL_HANDLE) { + if (clipMap) { *clipMap = &cmg; } return &box_model; } count = cmg.numSubModels; - for(i = 0; i < NumSubBSP; i++) - { - if (handle < count + SubBSP[i].numSubModels) - { - if (clipMap) - { + for (i = 0; i < NumSubBSP; i++) { + if (handle < count + SubBSP[i].numSubModels) { + if (clipMap) { *clipMap = &SubBSP[i]; } return &SubBSP[i].cmodels[handle - count]; @@ -945,12 +876,10 @@ cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) count += SubBSP[i].numSubModels; } - if ( handle < MAX_SUBMODELS ) - { - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i < %i < %i", - cmg.numSubModels, handle, MAX_SUBMODELS ); + if (handle < MAX_SUBMODELS) { + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle %i < %i < %i", cmg.numSubModels, handle, MAX_SUBMODELS); } - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle + MAX_SUBMODELS ); + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle + MAX_SUBMODELS); return NULL; } @@ -960,43 +889,35 @@ cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) CM_InlineModel ================== */ -clipHandle_t CM_InlineModel( int index ) { - if ( index < 0 || index >= TotalSubModels ) { - Com_Error( ERR_DROP, "CM_InlineModel: bad number: %d >= %d (may need to re-BSP map?)", index, TotalSubModels ); +clipHandle_t CM_InlineModel(int index) { + if (index < 0 || index >= TotalSubModels) { + Com_Error(ERR_DROP, "CM_InlineModel: bad number: %d >= %d (may need to re-BSP map?)", index, TotalSubModels); } return index; } -int CM_NumInlineModels( void ) { - return cmg.numSubModels; -} +int CM_NumInlineModels(void) { return cmg.numSubModels; } -char *CM_EntityString( void ) { - return cmg.entityString; -} +char *CM_EntityString(void) { return cmg.entityString; } -char *CM_SubBSPEntityString( int index ) -{ - return SubBSP[index].entityString; -} +char *CM_SubBSPEntityString(int index) { return SubBSP[index].entityString; } -int CM_LeafCluster( int leafnum ) { +int CM_LeafCluster(int leafnum) { if (leafnum < 0 || leafnum >= cmg.numLeafs) { - Com_Error (ERR_DROP, "CM_LeafCluster: bad number"); + Com_Error(ERR_DROP, "CM_LeafCluster: bad number"); } return cmg.leafs[leafnum].cluster; } -int CM_LeafArea( int leafnum ) { - if ( leafnum < 0 || leafnum >= cmg.numLeafs ) { - Com_Error (ERR_DROP, "CM_LeafArea: bad number"); +int CM_LeafArea(int leafnum) { + if (leafnum < 0 || leafnum >= cmg.numLeafs) { + Com_Error(ERR_DROP, "CM_LeafArea: bad number"); } return cmg.leafs[leafnum].area; } //======================================================================= - /* =================== CM_InitBoxHull @@ -1005,12 +926,11 @@ Set up the planes and nodes so that the six floats of a bounding box can just be stored out and get a proper clipping hull structure. =================== */ -void CM_InitBoxHull (void) -{ - int i; - int side; - cplane_t *p; - cbrushside_t *s; +void CM_InitBoxHull(void) { + int i; + int side; + cplane_t *p; + cbrushside_t *s; box_planes = &cmg.planes[cmg.numPlanes]; @@ -1020,38 +940,35 @@ void CM_InitBoxHull (void) box_brush->contents = CONTENTS_BODY; box_model.leaf.numLeafBrushes = 1; -// box_model.leaf.firstLeafBrush = cmg.numBrushes; + // box_model.leaf.firstLeafBrush = cmg.numBrushes; box_model.leaf.firstLeafBrush = cmg.numLeafBrushes; cmg.leafbrushes[cmg.numLeafBrushes] = cmg.numBrushes; - for (i=0 ; i<6 ; i++) - { - side = i&1; + for (i = 0; i < 6; i++) { + side = i & 1; // brush sides - s = &cmg.brushsides[cmg.numBrushSides+i]; - s->plane = cmg.planes + (cmg.numPlanes+i*2+side); - s->shaderNum = cmg.numShaders; //not storing flags directly anymore, so be sure to point @ a valid shader + s = &cmg.brushsides[cmg.numBrushSides + i]; + s->plane = cmg.planes + (cmg.numPlanes + i * 2 + side); + s->shaderNum = cmg.numShaders; // not storing flags directly anymore, so be sure to point @ a valid shader // planes - p = &box_planes[i*2]; - p->type = i>>1; + p = &box_planes[i * 2]; + p->type = i >> 1; p->signbits = 0; - VectorClear (p->normal); - p->normal[i>>1] = 1; + VectorClear(p->normal); + p->normal[i >> 1] = 1; - p = &box_planes[i*2+1]; - p->type = 3 + (i>>1); + p = &box_planes[i * 2 + 1]; + p->type = 3 + (i >> 1); p->signbits = 0; - VectorClear (p->normal); - p->normal[i>>1] = -1; + VectorClear(p->normal); + p->normal[i >> 1] = -1; - SetPlaneSignbits( p ); + SetPlaneSignbits(p); } } - - /* =================== CM_HeadnodeForBox @@ -1060,7 +977,7 @@ To keep everything totally uniform, bounding boxes are turned into small BSP trees instead of being compared directly. =================== */ -clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs) {//, const int contents ) { +clipHandle_t CM_TempBoxModel(const vec3_t mins, const vec3_t maxs) { //, const int contents ) { box_planes[0].dist = maxs[0]; box_planes[1].dist = -maxs[0]; box_planes[2].dist = mins[0]; @@ -1074,103 +991,91 @@ clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs) {//, const i box_planes[10].dist = mins[2]; box_planes[11].dist = -mins[2]; - VectorCopy( mins, box_brush->bounds[0] ); - VectorCopy( maxs, box_brush->bounds[1] ); + VectorCopy(mins, box_brush->bounds[0]); + VectorCopy(maxs, box_brush->bounds[1]); - //FIXME: this is the "correct" way, but not the way JK2 was designed around... fix for further projects - //box_brush->contents = contents; + // FIXME: this is the "correct" way, but not the way JK2 was designed around... fix for further projects + // box_brush->contents = contents; return BOX_MODEL_HANDLE; } - /* =================== CM_ModelBounds =================== */ -void CM_ModelBounds( clipMap_t &cm, clipHandle_t model, vec3_t mins, vec3_t maxs ) -{ - cmodel_t *cmod; +void CM_ModelBounds(clipMap_t &cm, clipHandle_t model, vec3_t mins, vec3_t maxs) { + cmodel_t *cmod; - cmod = CM_ClipHandleToModel( model ); - VectorCopy( cmod->mins, mins ); - VectorCopy( cmod->maxs, maxs ); + cmod = CM_ClipHandleToModel(model); + VectorCopy(cmod->mins, mins); + VectorCopy(cmod->maxs, maxs); } -int CM_LoadSubBSP(const char *name, qboolean clientload) -{ - int i; - int checksum; - int count; +int CM_LoadSubBSP(const char *name, qboolean clientload) { + int i; + int checksum; + int count; count = cmg.numSubModels; - for(i = 0; i < NumSubBSP; i++) - { - if (!Q_stricmp(name, SubBSP[i].name)) - { + for (i = 0; i < NumSubBSP; i++) { + if (!Q_stricmp(name, SubBSP[i].name)) { return count; } count += SubBSP[i].numSubModels; } - if (NumSubBSP == MAX_SUB_BSP) - { - Com_Error (ERR_DROP, "CM_LoadSubBSP: too many unique sub BSPs"); + if (NumSubBSP == MAX_SUB_BSP) { + Com_Error(ERR_DROP, "CM_LoadSubBSP: too many unique sub BSPs"); } Com_DPrintf("CM_LoadSubBSP(%s, %i)\n", name, clientload); - CM_LoadMap_Actual( name, clientload, &checksum, SubBSP[NumSubBSP] ); + CM_LoadMap_Actual(name, clientload, &checksum, SubBSP[NumSubBSP]); NumSubBSP++; return count; } -int CM_FindSubBSP(int modelIndex) -{ - int i; - int count; +int CM_FindSubBSP(int modelIndex) { + int i; + int count; count = cmg.numSubModels; - if (modelIndex < count) - { // belongs to the main bsp + if (modelIndex < count) { // belongs to the main bsp return -1; } - for(i = 0; i < NumSubBSP; i++) - { + for (i = 0; i < NumSubBSP; i++) { count += SubBSP[i].numSubModels; - if (modelIndex < count) - { + if (modelIndex < count) { return i; } } return -1; } -void CM_GetWorldBounds ( vec3_t mins, vec3_t maxs ) -{ - VectorCopy ( cmg.cmodels[0].mins, mins ); - VectorCopy ( cmg.cmodels[0].maxs, maxs ); +void CM_GetWorldBounds(vec3_t mins, vec3_t maxs) { + VectorCopy(cmg.cmodels[0].mins, mins); + VectorCopy(cmg.cmodels[0].maxs, maxs); } -int CM_ModelContents_Actual( clipHandle_t model, clipMap_t *cm ) -{ - if ( !cm ) { +int CM_ModelContents_Actual(clipHandle_t model, clipMap_t *cm) { + if (!cm) { cm = &cmg; } int contents = 0; - const cmodel_t *cmod = CM_ClipHandleToModel( model, &cm ); - for ( int i = 0; i < cmod->leaf.numLeafBrushes; i++ ) { + const cmodel_t *cmod = CM_ClipHandleToModel(model, &cm); + for (int i = 0; i < cmod->leaf.numLeafBrushes; i++) { int brushNum = cm->leafbrushes[cmod->leaf.firstLeafBrush + i]; contents |= cm->brushes[brushNum].contents; } - for ( int i = 0; i < cmod->leaf.numLeafSurfaces; i++ ) { + for (int i = 0; i < cmod->leaf.numLeafSurfaces; i++) { int surfaceNum = cm->leafsurfaces[cmod->leaf.firstLeafSurface + i]; - if ( cm->surfaces[surfaceNum] ) { + if (cm->surfaces[surfaceNum]) { // HERNH? How could we have a null surf within our cmod->leaf.numLeafSurfaces? contents |= cm->surfaces[surfaceNum]->contents; } @@ -1179,17 +1084,15 @@ int CM_ModelContents_Actual( clipHandle_t model, clipMap_t *cm ) return contents; } -int CM_ModelContents( clipHandle_t model, int subBSPIndex ) -{ - if (subBSPIndex < 0) - { +int CM_ModelContents(clipHandle_t model, int subBSPIndex) { + if (subBSPIndex < 0) { return CM_ModelContents_Actual(model, NULL); } return CM_ModelContents_Actual(model, &SubBSP[subBSPIndex]); } -//support for save/load games +// support for save/load games /* =================== CM_WritePortalState @@ -1201,15 +1104,10 @@ Writes the portal state to a savegame file qboolean SG_Append(unsigned int chid, const void *data, int length); int SG_Read(unsigned int chid, void *pvAddress, int iLength, void **ppvAddressPtr = NULL); -void CM_WritePortalState() -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +void CM_WritePortalState() { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - saved_game.write_chunk( - INT_ID('P', 'R', 'T', 'S'), - ::cmg.areaPortals, - ::cmg.numAreas * ::cmg.numAreas); + saved_game.write_chunk(INT_ID('P', 'R', 'T', 'S'), ::cmg.areaPortals, ::cmg.numAreas * ::cmg.numAreas); } /* @@ -1220,15 +1118,10 @@ Reads the portal state from a savegame file and recalculates the area connections =================== */ -void CM_ReadPortalState() -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +void CM_ReadPortalState() { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - saved_game.read_chunk( - INT_ID('P', 'R', 'T', 'S'), - ::cmg.areaPortals, - ::cmg.numAreas * ::cmg.numAreas); + saved_game.read_chunk(INT_ID('P', 'R', 'T', 'S'), ::cmg.areaPortals, ::cmg.numAreas * ::cmg.numAreas); - CM_FloodAreaConnections (cmg); + CM_FloodAreaConnections(cmg); } diff --git a/code/qcommon/cm_patch.cpp b/code/qcommon/cm_patch.cpp index dbaa19ddf2..c202291f9e 100644 --- a/code/qcommon/cm_patch.cpp +++ b/code/qcommon/cm_patch.cpp @@ -106,21 +106,21 @@ typedef struct { #define ADDBEVELS -int c_totalPatchBlocks; -int c_totalPatchSurfaces; -int c_totalPatchEdges; +int c_totalPatchBlocks; +int c_totalPatchSurfaces; +int c_totalPatchEdges; -static const patchCollide_t *debugPatchCollide; -static const facet_t *debugFacet; -static qboolean debugBlock; -static vec3_t debugBlockPoints[4]; +static const patchCollide_t *debugPatchCollide; +static const facet_t *debugFacet; +static qboolean debugBlock; +static vec3_t debugBlockPoints[4]; /* ================= CM_ClearLevelPatches ================= */ -void CM_ClearLevelPatches( void ) { +void CM_ClearLevelPatches(void) { debugPatchCollide = NULL; debugFacet = NULL; } @@ -130,13 +130,13 @@ void CM_ClearLevelPatches( void ) { CM_SignbitsForNormal ================= */ -static int CM_SignbitsForNormal( vec3_t normal ) { - int bits, j; +static int CM_SignbitsForNormal(vec3_t normal) { + int bits, j; bits = 0; - for (j=0 ; j<3 ; j++) { - if ( normal[j] < 0 ) { - bits |= 1<= (SUBDIVIDE_DISTANCE * SUBDIVIDE_DISTANCE)); } @@ -213,10 +212,10 @@ a, b, and c are control points. the subdivided sequence will be: a, out1, out2, out3, c =============== */ -static void CM_Subdivide( vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3 ) { - int i; +static void CM_Subdivide(vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { out1[i] = 0.5 * (a[i] + b[i]); out3[i] = 0.5 * (b[i] + c[i]); out2[i] = 0.5 * (out1[i] + out3[i]); @@ -230,36 +229,36 @@ CM_TransposeGrid Swaps the rows and columns in place ================= */ -static void CM_TransposeGrid( cGrid_t *grid ) { - int i, j, l; - vec3_t temp; - qboolean tempWrap; - - if ( grid->width > grid->height ) { - for ( i = 0 ; i < grid->height ; i++ ) { - for ( j = i + 1 ; j < grid->width ; j++ ) { - if ( j < grid->height ) { +static void CM_TransposeGrid(cGrid_t *grid) { + int i, j, l; + vec3_t temp; + qboolean tempWrap; + + if (grid->width > grid->height) { + for (i = 0; i < grid->height; i++) { + for (j = i + 1; j < grid->width; j++) { + if (j < grid->height) { // swap the value - VectorCopy( grid->points[i][j], temp ); - VectorCopy( grid->points[j][i], grid->points[i][j] ); - VectorCopy( temp, grid->points[j][i] ); + VectorCopy(grid->points[i][j], temp); + VectorCopy(grid->points[j][i], grid->points[i][j]); + VectorCopy(temp, grid->points[j][i]); } else { // just copy - VectorCopy( grid->points[j][i], grid->points[i][j] ); + VectorCopy(grid->points[j][i], grid->points[i][j]); } } } } else { - for ( i = 0 ; i < grid->width ; i++ ) { - for ( j = i + 1 ; j < grid->height ; j++ ) { - if ( j < grid->width ) { + for (i = 0; i < grid->width; i++) { + for (j = i + 1; j < grid->height; j++) { + if (j < grid->width) { // swap the value - VectorCopy( grid->points[j][i], temp ); - VectorCopy( grid->points[i][j], grid->points[j][i] ); - VectorCopy( temp, grid->points[i][j] ); + VectorCopy(grid->points[j][i], temp); + VectorCopy(grid->points[i][j], grid->points[j][i]); + VectorCopy(temp, grid->points[i][j]); } else { // just copy - VectorCopy( grid->points[i][j], grid->points[j][i] ); + VectorCopy(grid->points[i][j], grid->points[j][i]); } } } @@ -281,29 +280,28 @@ CM_SetGridWrapWidth If the left and right columns are exactly equal, set grid->wrapWidth qtrue =================== */ -static void CM_SetGridWrapWidth( cGrid_t *grid ) { - int i, j; - float d; - - for ( i = 0 ; i < grid->height ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - d = grid->points[0][i][j] - grid->points[grid->width-1][i][j]; - if ( d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON ) { +static void CM_SetGridWrapWidth(cGrid_t *grid) { + int i, j; + float d; + + for (i = 0; i < grid->height; i++) { + for (j = 0; j < 3; j++) { + d = grid->points[0][i][j] - grid->points[grid->width - 1][i][j]; + if (d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON) { break; } } - if ( j != 3 ) { + if (j != 3) { break; } } - if ( i == grid->height ) { + if (i == grid->height) { grid->wrapWidth = qtrue; } else { grid->wrapWidth = qfalse; } } - /* ================= CM_SubdivideGridColumns @@ -313,10 +311,10 @@ all the aproximating points are within SUBDIVIDE_DISTANCE from the true curve ================= */ -static void CM_SubdivideGridColumns( cGrid_t *grid ) { - int i, j, k; +static void CM_SubdivideGridColumns(cGrid_t *grid) { + int i, j, k; - for ( i = 0 ; i < grid->width - 2 ; ) { + for (i = 0; i < grid->width - 2;) { // grid->points[i][x] is an interpolating control point // grid->points[i+1][x] is an aproximating control point // grid->points[i+2][x] is an interpolating control point @@ -324,18 +322,18 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { // // first see if we can collapse the aproximating collumn away // - for ( j = 0 ; j < grid->height ; j++ ) { - if ( CM_NeedsSubdivision( grid->points[i][j], grid->points[i+1][j], grid->points[i+2][j] ) ) { + for (j = 0; j < grid->height; j++) { + if (CM_NeedsSubdivision(grid->points[i][j], grid->points[i + 1][j], grid->points[i + 2][j])) { break; } } - if ( j == grid->height ) { + if (j == grid->height) { // all of the points were close enough to the linear midpoints // that we can collapse the entire column away - for ( j = 0 ; j < grid->height ; j++ ) { + for (j = 0; j < grid->height; j++) { // remove the column - for ( k = i + 2 ; k < grid->width ; k++ ) { - VectorCopy( grid->points[k][j], grid->points[k-1][j] ); + for (k = i + 2; k < grid->width; k++) { + VectorCopy(grid->points[k][j], grid->points[k - 1][j]); } } @@ -349,23 +347,23 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { // // we need to subdivide the curve // - for ( j = 0 ; j < grid->height ; j++ ) { - vec3_t prev, mid, next; + for (j = 0; j < grid->height; j++) { + vec3_t prev, mid, next; // save the control points now - VectorCopy( grid->points[i][j], prev ); - VectorCopy( grid->points[i+1][j], mid ); - VectorCopy( grid->points[i+2][j], next ); + VectorCopy(grid->points[i][j], prev); + VectorCopy(grid->points[i + 1][j], mid); + VectorCopy(grid->points[i + 2][j], next); // make room for two additional columns in the grid // columns i+1 will be replaced, column i+2 will become i+4 // i+1, i+2, and i+3 will be generated - for ( k = grid->width - 1 ; k > i + 1 ; k-- ) { - VectorCopy( grid->points[k][j], grid->points[k+2][j] ); + for (k = grid->width - 1; k > i + 1; k--) { + VectorCopy(grid->points[k][j], grid->points[k + 2][j]); } // generate the subdivided points - CM_Subdivide( prev, mid, next, grid->points[i+1][j], grid->points[i+2][j], grid->points[i+3][j] ); + CM_Subdivide(prev, mid, next, grid->points[i + 1][j], grid->points[i + 2][j], grid->points[i + 3][j]); } grid->width += 2; @@ -375,26 +373,25 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { } } - -#define POINT_EPSILON 0.1 +#define POINT_EPSILON 0.1 /* ====================== CM_ComparePoints ====================== */ -static qboolean CM_ComparePoints( float *a, float *b ) { - float d; +static qboolean CM_ComparePoints(float *a, float *b) { + float d; d = a[0] - b[0]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } d = a[1] - b[1]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } d = a[2] - b[2]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } return qtrue; @@ -407,24 +404,24 @@ CM_RemoveDegenerateColumns If there are any identical columns, remove them ================= */ -static void CM_RemoveDegenerateColumns( cGrid_t *grid ) { - int i, j, k; +static void CM_RemoveDegenerateColumns(cGrid_t *grid) { + int i, j, k; - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height ; j++ ) { - if ( !CM_ComparePoints( grid->points[i][j], grid->points[i+1][j] ) ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height; j++) { + if (!CM_ComparePoints(grid->points[i][j], grid->points[i + 1][j])) { break; } } - if ( j != grid->height ) { - continue; // not degenerate + if (j != grid->height) { + continue; // not degenerate } - for ( j = 0 ; j < grid->height ; j++ ) { + for (j = 0; j < grid->height; j++) { // remove the column - for ( k = i + 2 ; k < grid->width ; k++ ) { - VectorCopy( grid->points[k][j], grid->points[k-1][j] ); + for (k = i + 2; k < grid->width; k++) { + VectorCopy(grid->points[k][j], grid->points[k - 1][j]); } } grid->width--; @@ -442,26 +439,22 @@ PATCH COLLIDE GENERATION ================================================================================ */ -static int numPlanes; -static patchPlane_t planes[MAX_PATCH_PLANES]; +static int numPlanes; +static patchPlane_t planes[MAX_PATCH_PLANES]; -//static int numFacets; -// static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ?? -//static facet_t facets[MAX_FACETS]; // Switched to MAX_FACETS = VV_FIXME, allocate these only during use -static facet_t *facets = NULL; +// static int numFacets; +// static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ?? +// static facet_t facets[MAX_FACETS]; // Switched to MAX_FACETS = VV_FIXME, allocate these only during use +static facet_t *facets = NULL; -#define NORMAL_EPSILON 0.00015 -#define DIST_EPSILON 0.0235 +#define NORMAL_EPSILON 0.00015 +#define DIST_EPSILON 0.0235 int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { float invplane[4]; - if ( - Q_fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON - && Q_fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON - && Q_fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON - && Q_fabs(p->plane[3] - plane[3]) < DIST_EPSILON ) - { + if (Q_fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON && Q_fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON && + Q_fabs(p->plane[3] - plane[3]) < DIST_EPSILON) { *flipped = qfalse; return qtrue; } @@ -469,12 +462,8 @@ int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { VectorNegate(plane, invplane); invplane[3] = -plane[3]; - if ( - Q_fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON - && Q_fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON - && Q_fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON - && Q_fabs(p->plane[3] - invplane[3]) < DIST_EPSILON ) - { + if (Q_fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON && + Q_fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON && Q_fabs(p->plane[3] - invplane[3]) < DIST_EPSILON) { *flipped = qtrue; return qtrue; } @@ -483,19 +472,16 @@ int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { } void CM_SnapVector(vec3_t normal) { - int i; + int i; - for (i=0 ; i<3 ; i++) - { - if ( Q_fabs(normal[i] - 1) < NORMAL_EPSILON ) - { - VectorClear (normal); + for (i = 0; i < 3; i++) { + if (Q_fabs(normal[i] - 1) < NORMAL_EPSILON) { + VectorClear(normal); normal[i] = 1; break; } - if ( Q_fabs(normal[i] - -1) < NORMAL_EPSILON ) - { - VectorClear (normal); + if (Q_fabs(normal[i] - -1) < NORMAL_EPSILON) { + VectorClear(normal); normal[i] = -1; break; } @@ -506,23 +492,24 @@ int CM_FindPlane2(float plane[4], int *flipped) { int i; // see if the points are close enough to an existing plane - for ( i = 0 ; i < numPlanes ; i++ ) { - if (CM_PlaneEqual(&planes[i], plane, flipped)) return i; + for (i = 0; i < numPlanes; i++) { + if (CM_PlaneEqual(&planes[i], plane, flipped)) + return i; } // add a new plane - if ( numPlanes == MAX_PATCH_PLANES ) { - Com_Error( ERR_DROP, "MAX_PATCH_PLANES reached (%d)", MAX_PATCH_PLANES ); + if (numPlanes == MAX_PATCH_PLANES) { + Com_Error(ERR_DROP, "MAX_PATCH_PLANES reached (%d)", MAX_PATCH_PLANES); } - VectorCopy4( plane, planes[numPlanes].plane ); - planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); + VectorCopy4(plane, planes[numPlanes].plane); + planes[numPlanes].signbits = CM_SignbitsForNormal(plane); numPlanes++; *flipped = qfalse; - return numPlanes-1; + return numPlanes - 1; } /* @@ -530,33 +517,33 @@ int CM_FindPlane2(float plane[4], int *flipped) { CM_FindPlane ================== */ -static int CM_FindPlane( float *p1, float *p2, float *p3 ) { - float plane[4]; - int i; - float d; +static int CM_FindPlane(float *p1, float *p2, float *p3) { + float plane[4]; + int i; + float d; - if ( !CM_PlaneFromPoints( plane, p1, p2, p3 ) ) { + if (!CM_PlaneFromPoints(plane, p1, p2, p3)) { return -1; } // see if the points are close enough to an existing plane - for ( i = 0 ; i < numPlanes ; i++ ) { - if ( DotProduct( plane, planes[i].plane ) < 0 ) { - continue; // allow backwards planes? + for (i = 0; i < numPlanes; i++) { + if (DotProduct(plane, planes[i].plane) < 0) { + continue; // allow backwards planes? } - d = DotProduct( p1, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p1, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } - d = DotProduct( p2, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p2, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } - d = DotProduct( p3, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p3, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } @@ -565,61 +552,59 @@ static int CM_FindPlane( float *p1, float *p2, float *p3 ) { } // add a new plane - if ( numPlanes == MAX_PATCH_PLANES ) { - Com_Error( ERR_DROP, "MAX_PATCH_PLANES" ); + if (numPlanes == MAX_PATCH_PLANES) { + Com_Error(ERR_DROP, "MAX_PATCH_PLANES"); } - VectorCopy4( plane, planes[numPlanes].plane ); - planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); + VectorCopy4(plane, planes[numPlanes].plane); + planes[numPlanes].signbits = CM_SignbitsForNormal(plane); numPlanes++; - return numPlanes-1; + return numPlanes - 1; } - /* ================== CM_PointOnPlaneSide ================== */ -static int CM_PointOnPlaneSide( float *p, int planeNum ) { - float *plane; - float d; +static int CM_PointOnPlaneSide(float *p, int planeNum) { + float *plane; + float d; - if ( planeNum == -1 ) { + if (planeNum == -1) { return SIDE_ON; } - plane = planes[ planeNum ].plane; + plane = planes[planeNum].plane; - d = DotProduct( p, plane ) - plane[3]; + d = DotProduct(p, plane) - plane[3]; - if ( d > PLANE_TRI_EPSILON ) { + if (d > PLANE_TRI_EPSILON) { return SIDE_FRONT; } - if ( d < -PLANE_TRI_EPSILON ) { + if (d < -PLANE_TRI_EPSILON) { return SIDE_BACK; } return SIDE_ON; } - -static int CM_GridPlane( int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int tri ) { - int p; +static int CM_GridPlane(int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int tri) { + int p; p = gridPlanes[i][j][tri]; - if ( p != -1 ) { + if (p != -1) { return p; } p = gridPlanes[i][j][!tri]; - if ( p != -1 ) { + if (p != -1) { return p; } // should never happen - Com_Printf( "WARNING: CM_GridPlane unresolvable\n" ); + Com_Printf("WARNING: CM_GridPlane unresolvable\n"); return -1; } @@ -628,75 +613,74 @@ static int CM_GridPlane( int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], CM_EdgePlaneNum ================== */ -static int CM_EdgePlaneNum( cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int k ) { - float *p1, *p2; - vec3_t up; - int p; +static int CM_EdgePlaneNum(cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int k) { + float *p1, *p2; + vec3_t up; + int p; - switch ( k ) { - case 0: // top border + switch (k) { + case 0: // top border p1 = grid->points[i][j]; - p2 = grid->points[i+1][j]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + p2 = grid->points[i + 1][j]; + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); - - case 2: // bottom border - p1 = grid->points[i][j+1]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); + + case 2: // bottom border + p1 = grid->points[i][j + 1]; + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p2, p1, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p2, p1, up); case 3: // left border p1 = grid->points[i][j]; - p2 = grid->points[i][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + p2 = grid->points[i][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p2, p1, up ); - - case 1: // right border - p1 = grid->points[i+1][j]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p2, p1, up); + + case 1: // right border + p1 = grid->points[i + 1][j]; + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); - case 4: // diagonal out of triangle 0 - p1 = grid->points[i+1][j+1]; + case 4: // diagonal out of triangle 0 + p1 = grid->points[i + 1][j + 1]; p2 = grid->points[i][j]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); - case 5: // diagonal out of triangle 1 + case 5: // diagonal out of triangle 1 p1 = grid->points[i][j]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); - + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); } - Com_Error( ERR_DROP, "CM_EdgePlaneNum: bad k" ); + Com_Error(ERR_DROP, "CM_EdgePlaneNum: bad k"); return -1; } @@ -705,72 +689,72 @@ static int CM_EdgePlaneNum( cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_M CM_SetBorderInward =================== */ -static void CM_SetBorderInward( facet_t *facet, cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], - int i, int j, int which ) { - int k, l; - float *points[4]; - int numPoints; +static void CM_SetBorderInward(facet_t *facet, cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int which) { + int k, l; + float *points[4]; + int numPoints; - switch ( which ) { + switch (which) { case -1: points[0] = grid->points[i][j]; - points[1] = grid->points[i+1][j]; - points[2] = grid->points[i+1][j+1]; - points[3] = grid->points[i][j+1]; + points[1] = grid->points[i + 1][j]; + points[2] = grid->points[i + 1][j + 1]; + points[3] = grid->points[i][j + 1]; numPoints = 4; break; case 0: points[0] = grid->points[i][j]; - points[1] = grid->points[i+1][j]; - points[2] = grid->points[i+1][j+1]; + points[1] = grid->points[i + 1][j]; + points[2] = grid->points[i + 1][j + 1]; numPoints = 3; break; case 1: - points[0] = grid->points[i+1][j+1]; - points[1] = grid->points[i][j+1]; + points[0] = grid->points[i + 1][j + 1]; + points[1] = grid->points[i][j + 1]; points[2] = grid->points[i][j]; numPoints = 3; break; default: - Com_Error( ERR_FATAL, "CM_SetBorderInward: bad parameter" ); + Com_Error(ERR_FATAL, "CM_SetBorderInward: bad parameter"); numPoints = 0; break; } - for ( k = 0 ; k < facet->numBorders ; k++ ) { - int front, back; + for (k = 0; k < facet->numBorders; k++) { + int front, back; front = 0; back = 0; - for ( l = 0 ; l < numPoints ; l++ ) { - int side; + for (l = 0; l < numPoints; l++) { + int side; - side = CM_PointOnPlaneSide( points[l], facet->borderPlanes[k] ); - if ( side == SIDE_FRONT ) { + side = CM_PointOnPlaneSide(points[l], facet->borderPlanes[k]); + if (side == SIDE_FRONT) { front++; - } if ( side == SIDE_BACK ) { + } + if (side == SIDE_BACK) { back++; } } - if ( front && !back ) { + if (front && !back) { facet->borderInward[k] = qtrue; - } else if ( back && !front ) { + } else if (back && !front) { facet->borderInward[k] = qfalse; - } else if ( !front && !back ) { + } else if (!front && !back) { // flat side border facet->borderPlanes[k] = -1; } else { // bisecting side border - Com_DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" ); + Com_DPrintf("WARNING: CM_SetBorderInward: mixed plane sides\n"); facet->borderInward[k] = qfalse; - if ( !debugBlock ) { + if (!debugBlock) { debugBlock = qtrue; - VectorCopy( grid->points[i][j], debugBlockPoints[0] ); - VectorCopy( grid->points[i+1][j], debugBlockPoints[1] ); - VectorCopy( grid->points[i+1][j+1], debugBlockPoints[2] ); - VectorCopy( grid->points[i][j+1], debugBlockPoints[3] ); + VectorCopy(grid->points[i][j], debugBlockPoints[0]); + VectorCopy(grid->points[i + 1][j], debugBlockPoints[1]); + VectorCopy(grid->points[i + 1][j + 1], debugBlockPoints[2]); + VectorCopy(grid->points[i][j + 1], debugBlockPoints[3]); } } } @@ -783,51 +767,51 @@ CM_ValidateFacet If the facet isn't bounded by its borders, we screwed up. ================== */ -static qboolean CM_ValidateFacet( facet_t *facet ) { - float plane[4]; - int j; - winding_t *w; - vec3_t bounds[2]; +static qboolean CM_ValidateFacet(facet_t *facet) { + float plane[4]; + int j; + winding_t *w; + vec3_t bounds[2]; - if ( facet->surfacePlane == -1 ) { + if (facet->surfacePlane == -1) { return qfalse; } - VectorCopy4( planes[ facet->surfacePlane ].plane, plane ); - w = BaseWindingForPlane( plane, plane[3] ); - for ( j = 0 ; j < facet->numBorders && w ; j++ ) { - if ( facet->borderPlanes[j] == -1 ) { + VectorCopy4(planes[facet->surfacePlane].plane, plane); + w = BaseWindingForPlane(plane, plane[3]); + for (j = 0; j < facet->numBorders && w; j++) { + if (facet->borderPlanes[j] == -1) { FreeWinding(w); return qfalse; } - VectorCopy4( planes[ facet->borderPlanes[j] ].plane, plane ); - if ( !facet->borderInward[j] ) { - VectorSubtract( vec3_origin, plane, plane ); + VectorCopy4(planes[facet->borderPlanes[j]].plane, plane); + if (!facet->borderInward[j]) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } - ChopWindingInPlace( &w, plane, plane[3], 0.1f ); + ChopWindingInPlace(&w, plane, plane[3], 0.1f); } - if ( !w ) { - return qfalse; // winding was completely chopped away + if (!w) { + return qfalse; // winding was completely chopped away } // see if the facet is unreasonably large - WindingBounds( w, bounds[0], bounds[1] ); - FreeWinding( w ); + WindingBounds(w, bounds[0], bounds[1]); + FreeWinding(w); - for ( j = 0 ; j < 3 ; j++ ) { - if ( bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS ) { - return qfalse; // we must be missing a plane + for (j = 0; j < 3; j++) { + if (bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS) { + return qfalse; // we must be missing a plane } - if ( bounds[0][j] >= MAX_MAP_BOUNDS ) { + if (bounds[0][j] >= MAX_MAP_BOUNDS) { return qfalse; } - if ( bounds[1][j] <= -MAX_MAP_BOUNDS ) { + if (bounds[1][j] <= -MAX_MAP_BOUNDS) { return qfalse; } } - return qtrue; // winding is fine + return qtrue; // winding is fine } /* @@ -835,7 +819,7 @@ static qboolean CM_ValidateFacet( facet_t *facet ) { CM_AddFacetBevels ================== */ -void CM_AddFacetBevels( facet_t *facet ) { +void CM_AddFacetBevels(facet_t *facet) { int i, j, k, l; int axis, dir, order, flipped; @@ -847,21 +831,22 @@ void CM_AddFacetBevels( facet_t *facet ) { return; #endif - VectorCopy4( planes[ facet->surfacePlane ].plane, plane ); + VectorCopy4(planes[facet->surfacePlane].plane, plane); - w = BaseWindingForPlane( plane, plane[3] ); - for ( j = 0 ; j < facet->numBorders && w ; j++ ) { - if (facet->borderPlanes[j] == facet->surfacePlane) continue; - VectorCopy4( planes[ facet->borderPlanes[j] ].plane, plane ); + w = BaseWindingForPlane(plane, plane[3]); + for (j = 0; j < facet->numBorders && w; j++) { + if (facet->borderPlanes[j] == facet->surfacePlane) + continue; + VectorCopy4(planes[facet->borderPlanes[j]].plane, plane); - if ( !facet->borderInward[j] ) { - VectorSubtract( vec3_origin, plane, plane ); + if (!facet->borderInward[j]) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } - ChopWindingInPlace( &w, plane, plane[3], 0.1f ); + ChopWindingInPlace(&w, plane, plane[3], 0.1f); } - if ( !w ) { + if (!w) { return; } @@ -869,30 +854,28 @@ void CM_AddFacetBevels( facet_t *facet ) { // add the axial planes order = 0; - for ( axis = 0 ; axis < 3 ; axis++ ) - { - for ( dir = -1 ; dir <= 1 ; dir += 2, order++ ) - { + for (axis = 0; axis < 3; axis++) { + for (dir = -1; dir <= 1; dir += 2, order++) { VectorClear(plane); plane[axis] = dir; if (dir == 1) { plane[3] = maxs[axis]; - } - else { + } else { plane[3] = -mins[axis]; } - //if it's the surface plane + // if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present - for ( i = 0 ; i < facet->numBorders ; i++ ) { + for (i = 0; i < facet->numBorders; i++) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) break; } - if ( i == facet->numBorders ) { - if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); + if (i == facet->numBorders) { + if (facet->numBorders > 4 + 6 + 16) + Com_Printf(S_COLOR_RED "ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); facet->borderNoAdjust[facet->numBorders] = qfalse; facet->borderInward[facet->numBorders] = flipped; @@ -904,62 +887,59 @@ void CM_AddFacetBevels( facet_t *facet ) { // add the edge bevels // // test the non-axial plane edges - for ( j = 0 ; j < w->numpoints ; j++ ) - { - k = (j+1)%w->numpoints; - VectorSubtract (w->p[j], w->p[k], vec); - //if it's a degenerate edge - if (VectorNormalize (vec) < 0.5) + for (j = 0; j < w->numpoints; j++) { + k = (j + 1) % w->numpoints; + VectorSubtract(w->p[j], w->p[k], vec); + // if it's a degenerate edge + if (VectorNormalize(vec) < 0.5) continue; CM_SnapVector(vec); - for ( k = 0; k < 3 ; k++ ) - if ( vec[k] == -1 || vec[k] == 1 ) - break; // axial - if ( k < 3 ) - continue; // only test non-axial edges + for (k = 0; k < 3; k++) + if (vec[k] == -1 || vec[k] == 1) + break; // axial + if (k < 3) + continue; // only test non-axial edges // try the six possible slanted axials from this edge - for ( axis = 0 ; axis < 3 ; axis++ ) - { - for ( dir = -1 ; dir <= 1 ; dir += 2 ) - { + for (axis = 0; axis < 3; axis++) { + for (dir = -1; dir <= 1; dir += 2) { // construct a plane - VectorClear (vec2); + VectorClear(vec2); vec2[axis] = dir; - CrossProduct (vec, vec2, plane); - if (VectorNormalize (plane) < 0.5) + CrossProduct(vec, vec2, plane); + if (VectorNormalize(plane) < 0.5) continue; - plane[3] = DotProduct (w->p[j], plane); + plane[3] = DotProduct(w->p[j], plane); // if all the points of the facet winding are // behind this plane, it is a proper edge bevel - for ( l = 0 ; l < w->numpoints ; l++ ) - { - d = DotProduct (w->p[l], plane) - plane[3]; + for (l = 0; l < w->numpoints; l++) { + d = DotProduct(w->p[l], plane) - plane[3]; if (d > 0.1) - break; // point in front + break; // point in front } - if ( l < w->numpoints ) + if (l < w->numpoints) continue; - //if it's the surface plane + // if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present - for ( i = 0 ; i < facet->numBorders ; i++ ) { + for (i = 0; i < facet->numBorders; i++) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) { - break; + break; } } - if ( i == facet->numBorders ) { - if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); + if (i == facet->numBorders) { + if (facet->numBorders > 4 + 6 + 16) + Com_Printf(S_COLOR_RED "ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); - for ( k = 0 ; k < facet->numBorders ; k++ ) { - if (facet->borderPlanes[facet->numBorders] == - facet->borderPlanes[k]) Com_Printf("WARNING: bevel plane already used\n"); + for (k = 0; k < facet->numBorders; k++) { + if (facet->borderPlanes[facet->numBorders] == facet->borderPlanes[k]) + Com_Printf("WARNING: bevel plane already used\n"); } facet->borderNoAdjust[facet->numBorders] = qfalse; @@ -967,139 +947,129 @@ void CM_AddFacetBevels( facet_t *facet ) { // w2 = CopyWinding(w); VectorCopy4(planes[facet->borderPlanes[facet->numBorders]].plane, newplane); - if (!facet->borderInward[facet->numBorders]) - { + if (!facet->borderInward[facet->numBorders]) { VectorNegate(newplane, newplane); newplane[3] = -newplane[3]; - } //end if - ChopWindingInPlace( &w2, newplane, newplane[3], 0.1f ); + } // end if + ChopWindingInPlace(&w2, newplane, newplane[3], 0.1f); if (!w2) { Com_DPrintf("WARNING: CM_AddFacetBevels... invalid bevel\n"); continue; - } - else { + } else { FreeWinding(w2); } // facet->numBorders++; - //already got a bevel -// break; + // already got a bevel + // break; } } } } - FreeWinding( w ); + FreeWinding(w); #ifndef BSPC - //add opposite plane + // add opposite plane facet->borderPlanes[facet->numBorders] = facet->surfacePlane; facet->borderNoAdjust[facet->numBorders] = qfalse; facet->borderInward[facet->numBorders] = qtrue; facet->numBorders++; -#endif //BSPC - +#endif // BSPC } - -typedef enum { - EN_TOP, - EN_RIGHT, - EN_BOTTOM, - EN_LEFT -} edgeName_t; - +typedef enum { EN_TOP, EN_RIGHT, EN_BOTTOM, EN_LEFT } edgeName_t; /* ================== CM_PatchCollideFromGrid ================== */ -static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { - int i, j; - float *p1, *p2, *p3; - int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2]; - facet_t *facet; - int borders[4]; - qboolean noAdjust[4]; +static void CM_PatchCollideFromGrid(cGrid_t *grid, patchCollide_t *pf) { + int i, j; + float *p1, *p2, *p3; + int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2]; + facet_t *facet; + int borders[4]; + qboolean noAdjust[4]; int numFacets; - facets = (facet_t*) Z_Malloc(MAX_FACETS*sizeof(facet_t), TAG_TEMP_WORKSPACE, qfalse); + facets = (facet_t *)Z_Malloc(MAX_FACETS * sizeof(facet_t), TAG_TEMP_WORKSPACE, qfalse); numPlanes = 0; numFacets = 0; // find the planes for each triangle of the grid - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height - 1 ; j++ ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height - 1; j++) { p1 = grid->points[i][j]; - p2 = grid->points[i+1][j]; - p3 = grid->points[i+1][j+1]; - gridPlanes[i][j][0] = CM_FindPlane( p1, p2, p3 ); + p2 = grid->points[i + 1][j]; + p3 = grid->points[i + 1][j + 1]; + gridPlanes[i][j][0] = CM_FindPlane(p1, p2, p3); - p1 = grid->points[i+1][j+1]; - p2 = grid->points[i][j+1]; + p1 = grid->points[i + 1][j + 1]; + p2 = grid->points[i][j + 1]; p3 = grid->points[i][j]; - gridPlanes[i][j][1] = CM_FindPlane( p1, p2, p3 ); + gridPlanes[i][j][1] = CM_FindPlane(p1, p2, p3); } } // create the borders for each facet - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height - 1 ; j++ ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height - 1; j++) { borders[EN_TOP] = -1; - if ( j > 0 ) { - borders[EN_TOP] = gridPlanes[i][j-1][1]; - } else if ( grid->wrapHeight ) { - borders[EN_TOP] = gridPlanes[i][grid->height-2][1]; + if (j > 0) { + borders[EN_TOP] = gridPlanes[i][j - 1][1]; + } else if (grid->wrapHeight) { + borders[EN_TOP] = gridPlanes[i][grid->height - 2][1]; } - noAdjust[EN_TOP] = (qboolean)( borders[EN_TOP] == gridPlanes[i][j][0] ); - if ( borders[EN_TOP] == -1 || noAdjust[EN_TOP] ) { - borders[EN_TOP] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 0 ); + noAdjust[EN_TOP] = (qboolean)(borders[EN_TOP] == gridPlanes[i][j][0]); + if (borders[EN_TOP] == -1 || noAdjust[EN_TOP]) { + borders[EN_TOP] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 0); } borders[EN_BOTTOM] = -1; - if ( j < grid->height - 2 ) { - borders[EN_BOTTOM] = gridPlanes[i][j+1][0]; - } else if ( grid->wrapHeight ) { + if (j < grid->height - 2) { + borders[EN_BOTTOM] = gridPlanes[i][j + 1][0]; + } else if (grid->wrapHeight) { borders[EN_BOTTOM] = gridPlanes[i][0][0]; } - noAdjust[EN_BOTTOM] = (qboolean)( borders[EN_BOTTOM] == gridPlanes[i][j][1] ); - if ( borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM] ) { - borders[EN_BOTTOM] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 2 ); + noAdjust[EN_BOTTOM] = (qboolean)(borders[EN_BOTTOM] == gridPlanes[i][j][1]); + if (borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM]) { + borders[EN_BOTTOM] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 2); } borders[EN_LEFT] = -1; - if ( i > 0 ) { - borders[EN_LEFT] = gridPlanes[i-1][j][0]; - } else if ( grid->wrapWidth ) { - borders[EN_LEFT] = gridPlanes[grid->width-2][j][0]; + if (i > 0) { + borders[EN_LEFT] = gridPlanes[i - 1][j][0]; + } else if (grid->wrapWidth) { + borders[EN_LEFT] = gridPlanes[grid->width - 2][j][0]; } - noAdjust[EN_LEFT] = (qboolean)( borders[EN_LEFT] == gridPlanes[i][j][1] ); - if ( borders[EN_LEFT] == -1 || noAdjust[EN_LEFT] ) { - borders[EN_LEFT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 3 ); + noAdjust[EN_LEFT] = (qboolean)(borders[EN_LEFT] == gridPlanes[i][j][1]); + if (borders[EN_LEFT] == -1 || noAdjust[EN_LEFT]) { + borders[EN_LEFT] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 3); } borders[EN_RIGHT] = -1; - if ( i < grid->width - 2 ) { - borders[EN_RIGHT] = gridPlanes[i+1][j][1]; - } else if ( grid->wrapWidth ) { + if (i < grid->width - 2) { + borders[EN_RIGHT] = gridPlanes[i + 1][j][1]; + } else if (grid->wrapWidth) { borders[EN_RIGHT] = gridPlanes[0][j][1]; } - noAdjust[EN_RIGHT] = (qboolean)( borders[EN_RIGHT] == gridPlanes[i][j][0] ); - if ( borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT] ) { - borders[EN_RIGHT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 1 ); + noAdjust[EN_RIGHT] = (qboolean)(borders[EN_RIGHT] == gridPlanes[i][j][0]); + if (borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT]) { + borders[EN_RIGHT] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 1); } - if ( numFacets == MAX_FACETS ) { - Com_Error( ERR_DROP, "MAX_FACETS" ); + if (numFacets == MAX_FACETS) { + Com_Error(ERR_DROP, "MAX_FACETS"); } facet = &facets[numFacets]; - memset( facet, 0, sizeof( *facet ) ); + memset(facet, 0, sizeof(*facet)); - if ( gridPlanes[i][j][0] == gridPlanes[i][j][1] ) { - if ( gridPlanes[i][j][0] == -1 ) { - continue; // degenrate + if (gridPlanes[i][j][0] == gridPlanes[i][j][1]) { + if (gridPlanes[i][j][0] == -1) { + continue; // degenrate } facet->surfacePlane = gridPlanes[i][j][0]; facet->numBorders = 4; @@ -1111,9 +1081,9 @@ static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { facet->borderNoAdjust[2] = noAdjust[EN_BOTTOM]; facet->borderPlanes[3] = borders[EN_LEFT]; facet->borderNoAdjust[3] = noAdjust[EN_LEFT]; - CM_SetBorderInward( facet, grid, gridPlanes, i, j, -1 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, -1); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } } else { @@ -1125,23 +1095,23 @@ static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { facet->borderPlanes[1] = borders[EN_RIGHT]; facet->borderNoAdjust[1] = noAdjust[EN_RIGHT]; facet->borderPlanes[2] = gridPlanes[i][j][1]; - if ( facet->borderPlanes[2] == -1 ) { + if (facet->borderPlanes[2] == -1) { facet->borderPlanes[2] = borders[EN_BOTTOM]; - if ( facet->borderPlanes[2] == -1 ) { - facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 4 ); + if (facet->borderPlanes[2] == -1) { + facet->borderPlanes[2] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 4); } } - CM_SetBorderInward( facet, grid, gridPlanes, i, j, 0 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, 0); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } - if ( numFacets == MAX_FACETS ) { - Com_Error( ERR_DROP, "MAX_FACETS" ); + if (numFacets == MAX_FACETS) { + Com_Error(ERR_DROP, "MAX_FACETS"); } facet = &facets[numFacets]; - memset( facet, 0, sizeof( *facet ) ); + memset(facet, 0, sizeof(*facet)); facet->surfacePlane = gridPlanes[i][j][1]; facet->numBorders = 3; @@ -1150,15 +1120,15 @@ static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { facet->borderPlanes[1] = borders[EN_LEFT]; facet->borderNoAdjust[1] = noAdjust[EN_LEFT]; facet->borderPlanes[2] = gridPlanes[i][j][0]; - if ( facet->borderPlanes[2] == -1 ) { + if (facet->borderPlanes[2] == -1) { facet->borderPlanes[2] = borders[EN_TOP]; - if ( facet->borderPlanes[2] == -1 ) { - facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 5 ); + if (facet->borderPlanes[2] == -1) { + facet->borderPlanes[2] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 5); } } - CM_SetBorderInward( facet, grid, gridPlanes, i, j, 1 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, 1); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } } @@ -1168,36 +1138,29 @@ static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { // copy the results out pf->numPlanes = numPlanes; pf->numFacets = numFacets; - if (numFacets) - { - pf->facets = (facet_t *) Z_Malloc( numFacets * sizeof( *pf->facets ), TAG_BSP, qfalse); - memcpy( pf->facets, facets, numFacets * sizeof( *pf->facets ) ); - } - else - { + if (numFacets) { + pf->facets = (facet_t *)Z_Malloc(numFacets * sizeof(*pf->facets), TAG_BSP, qfalse); + memcpy(pf->facets, facets, numFacets * sizeof(*pf->facets)); + } else { pf->facets = 0; } - pf->planes = (patchPlane_t *) Z_Malloc( numPlanes * sizeof( *pf->planes ), TAG_BSP, qfalse); - memcpy( pf->planes, planes, numPlanes * sizeof( *pf->planes ) ); + pf->planes = (patchPlane_t *)Z_Malloc(numPlanes * sizeof(*pf->planes), TAG_BSP, qfalse); + memcpy(pf->planes, planes, numPlanes * sizeof(*pf->planes)); Z_Free(facets); } static patchCollide_t *pfScratch = 0; -void CM_PreparePatchCollide(int num) -{ - pfScratch = (patchCollide_t *) Z_Malloc( sizeof( *pfScratch ) * num, TAG_BSP, qfalse ); -} +void CM_PreparePatchCollide(int num) { pfScratch = (patchCollide_t *)Z_Malloc(sizeof(*pfScratch) * num, TAG_BSP, qfalse); } cGrid_t *cm_grid = 0; -void CM_GridAlloc() -{ - if (cm_grid) return; - cm_grid = (cGrid_t*)Z_Malloc(sizeof(cGrid_t), TAG_TEMP_WORKSPACE, qfalse); +void CM_GridAlloc() { + if (cm_grid) + return; + cm_grid = (cGrid_t *)Z_Malloc(sizeof(cGrid_t), TAG_TEMP_WORKSPACE, qfalse); } -void CM_GridDealloc() -{ +void CM_GridDealloc() { Z_Free(cm_grid); cm_grid = 0; } @@ -1212,22 +1175,21 @@ collision detection with a patch mesh. Points is packed as concatenated rows. =================== */ -struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points ) { - patchCollide_t *pf; - cGrid_t grid; - int i, j; - - if ( width <= 2 || height <= 2 || !points ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", - width, height, points ); +struct patchCollide_s *CM_GeneratePatchCollide(int width, int height, vec3_t *points) { + patchCollide_t *pf; + cGrid_t grid; + int i, j; + + if (width <= 2 || height <= 2 || !points) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", width, height, points); } - if ( !(width & 1) || !(height & 1) ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" ); + if (!(width & 1) || !(height & 1)) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes"); } - if ( width > CM_MAX_GRID_SIZE || height > CM_MAX_GRID_SIZE ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: source is > CM_MAX_GRID_SIZE" ); + if (width > CM_MAX_GRID_SIZE || height > CM_MAX_GRID_SIZE) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: source is > CM_MAX_GRID_SIZE"); } // build a grid @@ -1235,38 +1197,38 @@ struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *p grid.height = height; grid.wrapWidth = qfalse; grid.wrapHeight = qfalse; - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - VectorCopy( points[j*width + i], grid.points[i][j] ); + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + VectorCopy(points[j * width + i], grid.points[i][j]); } } // subdivide the grid - CM_SetGridWrapWidth( &grid ); - CM_SubdivideGridColumns( &grid ); - CM_RemoveDegenerateColumns( &grid ); + CM_SetGridWrapWidth(&grid); + CM_SubdivideGridColumns(&grid); + CM_RemoveDegenerateColumns(&grid); - CM_TransposeGrid( &grid ); + CM_TransposeGrid(&grid); - CM_SetGridWrapWidth( &grid ); - CM_SubdivideGridColumns( &grid ); - CM_RemoveDegenerateColumns( &grid ); + CM_SetGridWrapWidth(&grid); + CM_SubdivideGridColumns(&grid); + CM_RemoveDegenerateColumns(&grid); // we now have a grid of points exactly on the curve // the aproximate surface defined by these points will be // collided against - pf = (patchCollide_t *) Z_Malloc( sizeof( *pf ), TAG_BSP, qfalse ); - ClearBounds( pf->bounds[0], pf->bounds[1] ); - for ( i = 0 ; i < grid.width ; i++ ) { - for ( j = 0 ; j < grid.height ; j++ ) { - AddPointToBounds( grid.points[i][j], pf->bounds[0], pf->bounds[1] ); + pf = (patchCollide_t *)Z_Malloc(sizeof(*pf), TAG_BSP, qfalse); + ClearBounds(pf->bounds[0], pf->bounds[1]); + for (i = 0; i < grid.width; i++) { + for (j = 0; j < grid.height; j++) { + AddPointToBounds(grid.points[i][j], pf->bounds[0], pf->bounds[1]); } } - c_totalPatchBlocks += ( grid.width - 1 ) * ( grid.height - 1 ); + c_totalPatchBlocks += (grid.width - 1) * (grid.height - 1); // generate a bsp tree for the surface - CM_PatchCollideFromGrid( &grid, pf ); + CM_PatchCollideFromGrid(&grid, pf); // expand by one unit for epsilon purposes pf->bounds[0][0] -= 1; @@ -1394,100 +1356,98 @@ CM_TracePointThroughPatchCollide special case for point traces because the patch collide "brushes" have no volume ==================== */ -void CM_TracePointThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { - qboolean frontFacing[MAX_PATCH_PLANES]; - float intersection[MAX_PATCH_PLANES]; - float intersect; - const patchPlane_t *planes; - const facet_t *facet; - int i, j, k; - float offset; - float d1, d2; +void CM_TracePointThroughPatchCollide(traceWork_t *tw, const struct patchCollide_s *pc) { + qboolean frontFacing[MAX_PATCH_PLANES]; + float intersection[MAX_PATCH_PLANES]; + float intersect; + const patchPlane_t *planes; + const facet_t *facet; + int i, j, k; + float offset; + float d1, d2; #ifndef BSPC static cvar_t *cv; -#endif //BSPC +#endif // BSPC #ifndef BSPC - if ( !cm_playerCurveClip->integer && !tw->isPoint ) { - return; // FIXME: until I get player sized clipping working right + if (!cm_playerCurveClip->integer && !tw->isPoint) { + return; // FIXME: until I get player sized clipping working right } #endif - if (!pc->numFacets) - { //not gonna do anything anyhow? + if (!pc->numFacets) { // not gonna do anything anyhow? return; } // determine the trace's relationship to all planes planes = pc->planes; - for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { - offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); - d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; - d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; - if ( d1 <= 0 ) { + for (i = 0; i < pc->numPlanes; i++, planes++) { + offset = DotProduct(tw->offsets[planes->signbits], planes->plane); + d1 = DotProduct(tw->start, planes->plane) - planes->plane[3] + offset; + d2 = DotProduct(tw->end, planes->plane) - planes->plane[3] + offset; + if (d1 <= 0) { frontFacing[i] = qfalse; } else { frontFacing[i] = qtrue; } - if ( d1 == d2 ) { + if (d1 == d2) { intersection[i] = WORLD_SIZE; } else { - intersection[i] = d1 / ( d1 - d2 ); - if ( intersection[i] <= 0 ) { + intersection[i] = d1 / (d1 - d2); + if (intersection[i] <= 0) { intersection[i] = WORLD_SIZE; } } } - // see if any of the surface planes are intersected facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { - if ( !frontFacing[facet->surfacePlane] ) { + for (i = 0; i < pc->numFacets; i++, facet++) { + if (!frontFacing[facet->surfacePlane]) { continue; } intersect = intersection[facet->surfacePlane]; - if ( intersect < 0 ) { - continue; // surface is behind the starting point + if (intersect < 0) { + continue; // surface is behind the starting point } - if ( intersect > tw->trace.fraction ) { - continue; // already hit something closer + if (intersect > tw->trace.fraction) { + continue; // already hit something closer } - for ( j = 0 ; j < facet->numBorders ; j++ ) { + for (j = 0; j < facet->numBorders; j++) { k = facet->borderPlanes[j]; - if ( frontFacing[k] ^ facet->borderInward[j] ) { - if ( intersection[k] > intersect ) { + if (frontFacing[k] ^ facet->borderInward[j]) { + if (intersection[k] > intersect) { break; } } else { - if ( intersection[k] < intersect ) { + if (intersection[k] < intersect) { break; } } } - if ( j == facet->numBorders ) { + if (j == facet->numBorders) { // we hit this facet #ifndef BSPC if (!cv) { - cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); + cv = Cvar_Get("r_debugSurfaceUpdate", "1", 0); } if (cv->integer) { debugPatchCollide = pc; debugFacet = facet; } -#endif //BSPC +#endif // BSPC planes = &pc->planes[facet->surfacePlane]; // calculate intersection with a slight pushoff - offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); - d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; - d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; - tw->trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); + offset = DotProduct(tw->offsets[planes->signbits], planes->plane); + d1 = DotProduct(tw->start, planes->plane) - planes->plane[3] + offset; + d2 = DotProduct(tw->end, planes->plane) - planes->plane[3] + offset; + tw->trace.fraction = (d1 - SURFACE_CLIP_EPSILON) / (d1 - d2); - if ( tw->trace.fraction < 0 ) { + if (tw->trace.fraction < 0) { tw->trace.fraction = 0; } - VectorCopy( planes->plane, tw->trace.plane.normal ); + VectorCopy(planes->plane, tw->trace.plane.normal); tw->trace.plane.dist = planes->plane[3]; } } @@ -1503,33 +1463,33 @@ int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, float *enterFrac, *hit = qfalse; - d1 = DotProduct( start, plane ) - plane[3]; - d2 = DotProduct( end, plane ) - plane[3]; + d1 = DotProduct(start, plane) - plane[3]; + d2 = DotProduct(end, plane) - plane[3]; // if completely in front of face, no intersection with the entire facet - if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { + if (d1 > 0 && (d2 >= SURFACE_CLIP_EPSILON || d2 >= d1)) { return qfalse; } // if it doesn't cross the plane, the plane isn't relevent - if (d1 <= 0 && d2 <= 0 ) { + if (d1 <= 0 && d2 <= 0) { return qtrue; } // crosses face - if (d1 > d2) { // enter - f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f < 0 ) { + if (d1 > d2) { // enter + f = (d1 - SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f < 0) { f = 0; } - //always favor previous plane hits and thus also the surface plane hit + // always favor previous plane hits and thus also the surface plane hit if (f > *enterFrac) { *enterFrac = f; *hit = qtrue; } - } else { // leave - f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f > 1 ) { + } else { // leave + f = (d1 + SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f > 1) { f = 1; } if (f < *leaveFrac) { @@ -1544,58 +1504,53 @@ int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, float *enterFrac, CM_TraceThroughPatchCollide ==================== */ -void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) -{ +void CM_TraceThroughPatchCollide(traceWork_t *tw, const struct patchCollide_s *pc) { int i, j, hit, hitnum; float offset, enterFrac, leaveFrac, t; patchPlane_t *planes; - facet_t *facet; - float plane[4] = { 0.0f }, bestplane[4] = { 0.0f }; + facet_t *facet; + float plane[4] = {0.0f}, bestplane[4] = {0.0f}; vec3_t startp, endp; #ifndef BSPC static cvar_t *cv; -#endif //BSPC +#endif // BSPC if (tw->isPoint) { - CM_TracePointThroughPatchCollide( tw, pc ); + CM_TracePointThroughPatchCollide(tw, pc); return; } #ifndef ADDBEVELS - CM_TracePointThroughPatchCollide( tw, pc ); + CM_TracePointThroughPatchCollide(tw, pc); return; #endif // facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { + for (i = 0; i < pc->numFacets; i++, facet++) { enterFrac = -1.0; leaveFrac = 1.0; hitnum = -1; // - planes = &pc->planes[ facet->surfacePlane ]; + planes = &pc->planes[facet->surfacePlane]; VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0.0f ) - { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - VectorSubtract( tw->end, tw->sphere.offset, endp ); - } - else - { - VectorAdd( tw->start, tw->sphere.offset, startp ); - VectorAdd( tw->end, tw->sphere.offset, endp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0.0f) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + VectorSubtract(tw->end, tw->sphere.offset, endp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); + VectorAdd(tw->end, tw->sphere.offset, endp); } - } - else { - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + } else { + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] -= offset; - VectorCopy( tw->start, startp ); - VectorCopy( tw->end, endp ); + VectorCopy(tw->start, startp); + VectorCopy(tw->end, endp); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { continue; @@ -1603,39 +1558,34 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s * if (hit) { VectorCopy4(plane, bestplane); } - for ( j = 0 ; j < facet->numBorders ; j++ ) { - planes = &pc->planes[ facet->borderPlanes[j] ]; + for (j = 0; j < facet->numBorders; j++) { + planes = &pc->planes[facet->borderPlanes[j]]; if (facet->borderInward[j]) { VectorNegate(planes->plane, plane); plane[3] = -planes->plane[3]; - } - else { + } else { VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; } - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0.0f ) - { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - VectorSubtract( tw->end, tw->sphere.offset, endp ); - } - else - { - VectorAdd( tw->start, tw->sphere.offset, startp ); - VectorAdd( tw->end, tw->sphere.offset, endp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0.0f) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + VectorSubtract(tw->end, tw->sphere.offset, endp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); + VectorAdd(tw->end, tw->sphere.offset, endp); } - } - else { + } else { // NOTE: this works even though the plane might be flipped because the bbox is centered - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] += fabs(offset); - VectorCopy( tw->start, startp ); - VectorCopy( tw->end, endp ); + VectorCopy(tw->start, startp); + VectorCopy(tw->end, endp); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { break; @@ -1645,9 +1595,11 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s * VectorCopy4(plane, bestplane); } } - if (j < facet->numBorders) continue; - //never clip against the back side - if (hitnum == facet->numBorders - 1) continue; + if (j < facet->numBorders) + continue; + // never clip against the back side + if (hitnum == facet->numBorders - 1) + continue; if (enterFrac < leaveFrac && enterFrac >= 0) { if (enterFrac < tw->trace.fraction) { if (enterFrac < 0) { @@ -1655,7 +1607,7 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s * } #ifndef BSPC if (!cv) { - cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); + cv = Cvar_Get("r_debugSurfaceUpdate", "1", 0); } if (cv && cv->integer) { debugPatchCollide = pc; @@ -1664,7 +1616,7 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s * #endif // BSPC tw->trace.fraction = enterFrac; - VectorCopy( bestplane, tw->trace.plane.normal ); + VectorCopy(bestplane, tw->trace.plane.normal); tw->trace.plane.dist = bestplane[3]; } } @@ -1679,9 +1631,9 @@ POSITION TEST ======================================================================= */ -#define BOX_FRONT 0 -#define BOX_BACK 1 -#define BOX_CROSS 2 +#define BOX_FRONT 0 +#define BOX_BACK 1 +#define BOX_CROSS 2 /* ==================== @@ -1690,20 +1642,19 @@ CM_PositionTestInPatchCollide Modifies tr->tr if any of the facets effect the trace ==================== */ -qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { - int cross[MAX_PATCH_PLANES]; - const patchPlane_t *planes; - const facet_t *facet; - int i, j, k; - float offset; - float d; +qboolean CM_PositionTestInPatchCollide(traceWork_t *tw, const struct patchCollide_s *pc) { + int cross[MAX_PATCH_PLANES]; + const patchPlane_t *planes; + const facet_t *facet; + int i, j, k; + float offset; + float d; -//return qfalse; + // return qfalse; #ifndef CULL_BBOX - for ( i = 0 ; i < 3 ; i++ ) { - if ( tw->bounds[0][i] > pc->bounds[1][i] - || tw->bounds[1][i] < pc->bounds[0][i] ) { + for (i = 0; i < 3; i++) { + if (tw->bounds[0][i] > pc->bounds[1][i] || tw->bounds[1][i] < pc->bounds[0][i]) { return qfalse; } } @@ -1711,38 +1662,37 @@ qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchColli // determine if the box is in front, behind, or crossing each plane planes = pc->planes; - for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { - d = DotProduct( tw->start, planes->plane ) - planes->plane[3]; - offset = fabs( DotProduct( tw->offsets[ planes->signbits ], planes->plane ) ); - if ( d < -offset ) { + for (i = 0; i < pc->numPlanes; i++, planes++) { + d = DotProduct(tw->start, planes->plane) - planes->plane[3]; + offset = fabs(DotProduct(tw->offsets[planes->signbits], planes->plane)); + if (d < -offset) { cross[i] = BOX_FRONT; - } else if ( d > offset ) { + } else if (d > offset) { cross[i] = BOX_BACK; } else { cross[i] = BOX_CROSS; } } - // see if any of the surface planes are intersected facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { + for (i = 0; i < pc->numFacets; i++, facet++) { // the facet plane must be in a cross state - if ( cross[facet->surfacePlane] != BOX_CROSS ) { + if (cross[facet->surfacePlane] != BOX_CROSS) { continue; } // all of the boundaries must be either cross or back - for ( j = 0 ; j < facet->numBorders ; j++ ) { + for (j = 0; j < facet->numBorders; j++) { k = facet->borderPlanes[j]; - if ( cross[ k ] == BOX_CROSS ) { + if (cross[k] == BOX_CROSS) { continue; } - if ( cross[k] ^ facet->borderInward[j] ) { + if (cross[k] ^ facet->borderInward[j]) { break; } } // if we passed all borders, we are definately in this facet - if ( j == facet->numBorders ) { + if (j == facet->numBorders) { return qtrue; } } @@ -1758,7 +1708,6 @@ DEBUGGING ======================================================================= */ - /* ================== CM_DrawDebugSurface @@ -1770,8 +1719,4 @@ Called from the renderer void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *points), int value); #endif -void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *points) ) { - -} - - +void CM_DrawDebugSurface(void (*drawPoly)(int color, int numPoints, float *points)) {} diff --git a/code/qcommon/cm_polylib.cpp b/code/qcommon/cm_polylib.cpp index 95d4b6a1ca..db6a7ffe71 100644 --- a/code/qcommon/cm_polylib.cpp +++ b/code/qcommon/cm_polylib.cpp @@ -27,28 +27,25 @@ along with this program; if not, see . // counters are only bumped when running single threaded, // because they are an awefull coherence problem -int c_active_windings; -int c_peak_windings; -int c_winding_allocs; -int c_winding_points; - -void pw(winding_t *w) -{ - int i; - for (i=0 ; inumpoints ; i++) - printf ("(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2]); +int c_active_windings; +int c_peak_windings; +int c_winding_allocs; +int c_winding_points; + +void pw(winding_t *w) { + int i; + for (i = 0; i < w->numpoints; i++) + printf("(%5.1f, %5.1f, %5.1f)\n", w->p[i][0], w->p[i][1], w->p[i][2]); } - /* ============= AllocWinding ============= */ -winding_t *AllocWinding (int points) -{ - winding_t *w; - int s; +winding_t *AllocWinding(int points) { + winding_t *w; + int s; c_winding_allocs++; c_winding_points += points; @@ -56,34 +53,30 @@ winding_t *AllocWinding (int points) if (c_active_windings > c_peak_windings) c_peak_windings = c_active_windings; - s = sizeof(vec_t)*3*points + sizeof(int); - w = (winding_t *) Z_Malloc (s,TAG_BSP, qtrue);//TAG_WINDING); -// memset (w, 0, s); // qtrue above does this + s = sizeof(vec_t) * 3 * points + sizeof(int); + w = (winding_t *)Z_Malloc(s, TAG_BSP, qtrue); // TAG_WINDING); + // memset (w, 0, s); // qtrue above does this return w; } -void FreeWinding (winding_t *w) -{ +void FreeWinding(winding_t *w) { if (*(unsigned *)w == 0xdeaddead) - Com_Error (ERR_FATAL, "FreeWinding: freed a freed winding"); + Com_Error(ERR_FATAL, "FreeWinding: freed a freed winding"); *(unsigned *)w = 0xdeaddead; c_active_windings--; - Z_Free (w); + Z_Free(w); } -void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs) -{ - vec_t v; - int i,j; +void WindingBounds(winding_t *w, vec3_t mins, vec3_t maxs) { + vec_t v; + int i, j; - mins[0] = mins[1] = mins[2] = WORLD_SIZE; // 99999; // WORLD_SIZE instead of MAX_WORLD_COORD so that... - maxs[0] = maxs[1] = maxs[2] = -WORLD_SIZE; //-99999; // ... it's guaranteed to be outide of legal + mins[0] = mins[1] = mins[2] = WORLD_SIZE; // 99999; // WORLD_SIZE instead of MAX_WORLD_COORD so that... + maxs[0] = maxs[1] = maxs[2] = -WORLD_SIZE; //-99999; // ... it's guaranteed to be outide of legal - for (i=0 ; inumpoints ; i++) - { - for (j=0 ; j<3 ; j++) - { + for (i = 0; i < w->numpoints; i++) { + for (j = 0; j < 3; j++) { v = w->p[i][j]; if (v < mins[j]) mins[j] = v; @@ -98,32 +91,28 @@ void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs) BaseWindingForPlane ================= */ -winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist) -{ - int i, x; - vec_t max, v; - vec3_t org, vright, vup; - winding_t *w; +winding_t *BaseWindingForPlane(vec3_t normal, vec_t dist) { + int i, x; + vec_t max, v; + vec3_t org, vright, vup; + winding_t *w; -// find the major axis + // find the major axis max = -MAX_MAP_BOUNDS; x = -1; - for (i=0 ; i<3; i++) - { + for (i = 0; i < 3; i++) { v = fabs(normal[i]); - if (v > max) - { + if (v > max) { x = i; max = v; } } - if (x==-1) - Com_Error (ERR_DROP, "BaseWindingForPlane: no axis found"); + if (x == -1) + Com_Error(ERR_DROP, "BaseWindingForPlane: no axis found"); - VectorCopy (vec3_origin, vup); - switch (x) - { + VectorCopy(vec3_origin, vup); + switch (x) { case 0: case 1: vup[2] = 1; @@ -133,31 +122,31 @@ winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist) break; } - v = DotProduct (vup, normal); - VectorMA (vup, -v, normal, vup); + v = DotProduct(vup, normal); + VectorMA(vup, -v, normal, vup); VectorNormalize2(vup, vup); - VectorScale (normal, dist, org); + VectorScale(normal, dist, org); - CrossProduct (vup, normal, vright); + CrossProduct(vup, normal, vright); - VectorScale (vup, MAX_MAP_BOUNDS, vup); - VectorScale (vright, MAX_MAP_BOUNDS, vright); + VectorScale(vup, MAX_MAP_BOUNDS, vup); + VectorScale(vright, MAX_MAP_BOUNDS, vright); -// project a really big axis aligned box onto the plane - w = AllocWinding (4); + // project a really big axis aligned box onto the plane + w = AllocWinding(4); - VectorSubtract (org, vright, w->p[0]); - VectorAdd (w->p[0], vup, w->p[0]); + VectorSubtract(org, vright, w->p[0]); + VectorAdd(w->p[0], vup, w->p[0]); - VectorAdd (org, vright, w->p[1]); - VectorAdd (w->p[1], vup, w->p[1]); + VectorAdd(org, vright, w->p[1]); + VectorAdd(w->p[1], vup, w->p[1]); - VectorAdd (org, vright, w->p[2]); - VectorSubtract (w->p[2], vup, w->p[2]); + VectorAdd(org, vright, w->p[2]); + VectorSubtract(w->p[2], vup, w->p[2]); - VectorSubtract (org, vright, w->p[3]); - VectorSubtract (w->p[3], vup, w->p[3]); + VectorSubtract(org, vright, w->p[3]); + VectorSubtract(w->p[3], vup, w->p[3]); w->numpoints = 4; @@ -169,14 +158,13 @@ winding_t *BaseWindingForPlane (vec3_t normal, vec_t dist) CopyWinding ================== */ -winding_t *CopyWinding (winding_t *w) -{ - intptr_t size; - winding_t *c; +winding_t *CopyWinding(winding_t *w) { + intptr_t size; + winding_t *c; - c = AllocWinding (w->numpoints); + c = AllocWinding(w->numpoints); size = (intptr_t)((winding_t *)0)->p[w->numpoints]; - memcpy (c, w, size); + memcpy(c, w, size); return c; } @@ -185,34 +173,31 @@ winding_t *CopyWinding (winding_t *w) ChopWindingInPlace ============= */ -void ChopWindingInPlace (winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon) -{ - winding_t *in; - float dists[MAX_POINTS_ON_WINDING+4] = { 0 }; - int sides[MAX_POINTS_ON_WINDING+4] = { 0 }; - int counts[3]; - static float dot; // VC 4.2 optimizer bug if not static - int i, j; - float *p1, *p2; - vec3_t mid; - winding_t *f; - int maxpts; +void ChopWindingInPlace(winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon) { + winding_t *in; + float dists[MAX_POINTS_ON_WINDING + 4] = {0}; + int sides[MAX_POINTS_ON_WINDING + 4] = {0}; + int counts[3]; + static float dot; // VC 4.2 optimizer bug if not static + int i, j; + float *p1, *p2; + vec3_t mid; + winding_t *f; + int maxpts; in = *inout; counts[0] = counts[1] = counts[2] = 0; -// determine sides for each point - for (i=0 ; inumpoints ; i++) - { - dot = DotProduct (in->p[i], normal); + // determine sides for each point + for (i = 0; i < in->numpoints; i++) { + dot = DotProduct(in->p[i], normal); dot -= dist; dists[i] = dot; if (dot > epsilon) sides[i] = SIDE_FRONT; else if (dot < -epsilon) sides[i] = SIDE_BACK; - else - { + else { sides[i] = SIDE_ON; } counts[sides[i]]++; @@ -220,63 +205,58 @@ void ChopWindingInPlace (winding_t **inout, vec3_t normal, vec_t dist, vec_t eps sides[i] = sides[0]; dists[i] = dists[0]; - if (!counts[0]) - { - FreeWinding (in); + if (!counts[0]) { + FreeWinding(in); *inout = NULL; return; } if (!counts[1]) - return; // inout stays the same + return; // inout stays the same - maxpts = in->numpoints+4; // cant use counts[0]+2 because + maxpts = in->numpoints + 4; // cant use counts[0]+2 because // of fp grouping errors - f = AllocWinding (maxpts); + f = AllocWinding(maxpts); - for (i=0 ; inumpoints ; i++) - { + for (i = 0; i < in->numpoints; i++) { p1 = in->p[i]; - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, f->p[f->numpoints]); + if (sides[i] == SIDE_ON) { + VectorCopy(p1, f->p[f->numpoints]); f->numpoints++; continue; } - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, f->p[f->numpoints]); + if (sides[i] == SIDE_FRONT) { + VectorCopy(p1, f->p[f->numpoints]); f->numpoints++; } - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) continue; - // generate a split point - p2 = in->p[(i+1)%in->numpoints]; + // generate a split point + p2 = in->p[(i + 1) % in->numpoints]; - dot = dists[i] / (dists[i]-dists[i+1]); - for (j=0 ; j<3 ; j++) - { // avoid round off error when possible + dot = dists[i] / (dists[i] - dists[i + 1]); + for (j = 0; j < 3; j++) { // avoid round off error when possible if (normal[j] == 1) mid[j] = dist; else if (normal[j] == -1) mid[j] = -dist; else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + mid[j] = p1[j] + dot * (p2[j] - p1[j]); } - VectorCopy (mid, f->p[f->numpoints]); + VectorCopy(mid, f->p[f->numpoints]); f->numpoints++; } if (f->numpoints > maxpts) - Com_Error (ERR_DROP, "ClipWinding: points exceeded estimate"); + Com_Error(ERR_DROP, "ClipWinding: points exceeded estimate"); if (f->numpoints > MAX_POINTS_ON_WINDING) - Com_Error (ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING"); + Com_Error(ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING"); - FreeWinding (in); + FreeWinding(in); *inout = f; } diff --git a/code/qcommon/cm_test.cpp b/code/qcommon/cm_test.cpp index 77a2265f81..b1c6a3d5bd 100644 --- a/code/qcommon/cm_test.cpp +++ b/code/qcommon/cm_test.cpp @@ -23,17 +23,11 @@ along with this program; if not, see . #include "cm_local.h" -class CPoint -{ -public: - float x,y,z; - CPoint(float _x,float _y,float _z): - x(_x), - y(_y), - z(_z) - { - } - bool operator== (const CPoint& P) const {return((x==P.x)&&(y==P.y)&&(z==P.z));} +class CPoint { + public: + float x, y, z; + CPoint(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} + bool operator==(const CPoint &P) const { return ((x == P.x) && (y == P.y) && (z == P.z)); } }; /* class CPointComparator @@ -45,13 +39,12 @@ class CPointComparator // Fixed memory version of pointToLeaf that doesn't use STL // cuts down on memory fragmentation -struct PointAndLeaf -{ +struct PointAndLeaf { // Default constructor for array construction below - PointAndLeaf() : point(0, 0, 0), leaf(0) { } + PointAndLeaf() : point(0, 0, 0), leaf(0) {} - CPoint point; - int leaf; + CPoint point; + int leaf; }; // I think it is a patholoically bad idea to do a 64 item linear search for a cache, @@ -59,16 +52,15 @@ struct PointAndLeaf // hopefully getting rid of water checks on maps with no water will leave us less // reliant on this cache. -gwg -#define MAX_POINTS_TO_LEAVES 16 +#define MAX_POINTS_TO_LEAVES 16 -static PointAndLeaf pointToLeaf[MAX_POINTS_TO_LEAVES]; -static int oldestPointToLeaf = 0, sizePointToLeaf = 0; +static PointAndLeaf pointToLeaf[MAX_POINTS_TO_LEAVES]; +static int oldestPointToLeaf = 0, sizePointToLeaf = 0; -//static hlist > pointToLeaf; -//static hlist > pointToContents; +// static hlist > pointToLeaf; +// static hlist > pointToContents; -void CM_CleanLeafCache(void) -{ +void CM_CleanLeafCache(void) { oldestPointToLeaf = sizePointToLeaf = 0; // pointToLeaf.clear(); #if 0 // VVFIXME @@ -78,12 +70,12 @@ void CM_CleanLeafCache(void) pointToLeaf.erase(l); } #endif -/* - for(l=pointToContents.begin();l!=pointToContents.end();l++) - { - pointToContents.erase(l); - } -*/ + /* + for(l=pointToContents.begin();l!=pointToContents.end();l++) + { + pointToContents.erase(l); + } + */ } /* @@ -92,39 +84,37 @@ CM_PointLeafnum_r ================== */ -int CM_PointLeafnum_r( const vec3_t p, int num, clipMap_t *local ) { - float d; - cNode_t *node; - cplane_t *plane; +int CM_PointLeafnum_r(const vec3_t p, int num, clipMap_t *local) { + float d; + cNode_t *node; + cplane_t *plane; - while (num >= 0) - { + while (num >= 0) { node = local->nodes + num; plane = node->plane; if (plane->type < 3) d = p[plane->type] - plane->dist; else - d = DotProduct (plane->normal, p) - plane->dist; + d = DotProduct(plane->normal, p) - plane->dist; if (d < 0) num = node->children[1]; else num = node->children[0]; } - c_pointcontents++; // optimize counter + c_pointcontents++; // optimize counter return -1 - num; } -int CM_PointLeafnum( const vec3_t p ) { - if ( !cmg.numNodes ) { // map not loaded +int CM_PointLeafnum(const vec3_t p) { + if (!cmg.numNodes) { // map not loaded return 0; } - return CM_PointLeafnum_r (p, 0, &cmg); + return CM_PointLeafnum_r(p, 0, &cmg); } - /* ====================================================================== @@ -133,55 +123,54 @@ LEAF LISTING ====================================================================== */ - -void CM_StoreLeafs( leafList_t *ll, int nodenum ) { - int leafNum; +void CM_StoreLeafs(leafList_t *ll, int nodenum) { + int leafNum; leafNum = -1 - nodenum; // store the lastLeaf even if the list is overflowed - if ( cmg.leafs[ leafNum ].cluster != -1 ) { + if (cmg.leafs[leafNum].cluster != -1) { ll->lastLeaf = leafNum; } - if ( ll->count >= ll->maxcount) { + if (ll->count >= ll->maxcount) { ll->overflowed = qtrue; return; } - ll->list[ ll->count++ ] = leafNum; + ll->list[ll->count++] = leafNum; } -void CM_StoreBrushes( leafList_t *ll, int nodenum ) { - int i, k; - int leafnum; - int brushnum; - cLeaf_t *leaf; - cbrush_t *b; +void CM_StoreBrushes(leafList_t *ll, int nodenum) { + int i, k; + int leafnum; + int brushnum; + cLeaf_t *leaf; + cbrush_t *b; leafnum = -1 - nodenum; leaf = &cmg.leafs[leafnum]; - for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) { - brushnum = cmg.leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = cmg.leafbrushes[leaf->firstLeafBrush + k]; b = &cmg.brushes[brushnum]; - if ( b->checkcount == cmg.checkcount ) { - continue; // already checked this brush in another leaf + if (b->checkcount == cmg.checkcount) { + continue; // already checked this brush in another leaf } b->checkcount = cmg.checkcount; - for ( i = 0 ; i < 3 ; i++ ) { - if ( b->bounds[0][i] >= ll->bounds[1][i] || b->bounds[1][i] <= ll->bounds[0][i] ) { + for (i = 0; i < 3; i++) { + if (b->bounds[0][i] >= ll->bounds[1][i] || b->bounds[1][i] <= ll->bounds[0][i]) { break; } } - if ( i != 3 ) { + if (i != 3) { continue; } - if ( ll->count >= ll->maxcount) { + if (ll->count >= ll->maxcount) { ll->overflowed = qtrue; return; } - ((cbrush_t **)ll->list)[ ll->count++ ] = b; + ((cbrush_t **)ll->list)[ll->count++] = b; } #if 0 // store patches? @@ -201,31 +190,30 @@ CM_BoxLeafnums Fills in a list of all the leafs touched ============= */ -void CM_BoxLeafnums_r( leafList_t *ll, int nodenum ) { - cplane_t *plane; - cNode_t *node; - int s; +void CM_BoxLeafnums_r(leafList_t *ll, int nodenum) { + cplane_t *plane; + cNode_t *node; + int s; while (1) { if (nodenum < 0) { - ll->storeLeafs( ll, nodenum ); + ll->storeLeafs(ll, nodenum); return; } node = &cmg.nodes[nodenum]; plane = node->plane; - s = BoxOnPlaneSide( ll->bounds[0], ll->bounds[1], plane ); + s = BoxOnPlaneSide(ll->bounds[0], ll->bounds[1], plane); if (s == 1) { nodenum = node->children[0]; } else if (s == 2) { nodenum = node->children[1]; } else { // go down both - CM_BoxLeafnums_r( ll, node->children[0] ); + CM_BoxLeafnums_r(ll, node->children[0]); nodenum = node->children[1]; } - } } @@ -234,13 +222,13 @@ void CM_BoxLeafnums_r( leafList_t *ll, int nodenum ) { CM_BoxLeafnums ================== */ -int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *boxList, int listsize, int *lastLeaf) { - leafList_t ll; +int CM_BoxLeafnums(const vec3_t mins, const vec3_t maxs, int *boxList, int listsize, int *lastLeaf) { + leafList_t ll; cmg.checkcount++; - VectorCopy( mins, ll.bounds[0] ); - VectorCopy( maxs, ll.bounds[1] ); + VectorCopy(mins, ll.bounds[0]); + VectorCopy(maxs, ll.bounds[1]); ll.count = 0; ll.maxcount = listsize; ll.list = boxList; @@ -248,16 +236,14 @@ int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *boxList, int list ll.lastLeaf = 0; ll.overflowed = qfalse; - CM_BoxLeafnums_r( &ll, 0 ); + CM_BoxLeafnums_r(&ll, 0); *lastLeaf = ll.lastLeaf; return ll.count; } - //==================================================================== - /* ================== CM_PointContents @@ -267,65 +253,57 @@ CM_PointContents #if 1 -int CM_PointContents( const vec3_t p, clipHandle_t model ) { - int leafnum=0; - int i, k; - int brushnum; - cLeaf_t *leaf; - cbrush_t *b; - int contents; - float d; - cmodel_t *clipm; - clipMap_t *local; - - if (!cmg.numNodes) { // map not loaded +int CM_PointContents(const vec3_t p, clipHandle_t model) { + int leafnum = 0; + int i, k; + int brushnum; + cLeaf_t *leaf; + cbrush_t *b; + int contents; + float d; + cmodel_t *clipm; + clipMap_t *local; + + if (!cmg.numNodes) { // map not loaded return 0; } - if ( model ) { - clipm = CM_ClipHandleToModel( model, &local ); + if (model) { + clipm = CM_ClipHandleToModel(model, &local); leaf = &clipm->leaf; - } - else - { + } else { local = &cmg; - CPoint pt(p[0],p[1],p[2]); -/* map::iterator l=pointToLeaf.find(pt); - if(l!=pointToLeaf.end()) - { - leafnum=(*l).second; - } - else - { - if(pointToLeaf.size()>=64) - { - pointToLeaf.clear(); - Com_Printf("Cleared cache\n"); - } - leafnum=CM_PointLeafnum_r(p, 0); - pointToLeaf[pt]=leafnum; - }*/ + CPoint pt(p[0], p[1], p[2]); + /* map::iterator l=pointToLeaf.find(pt); + if(l!=pointToLeaf.end()) + { + leafnum=(*l).second; + } + else + { + if(pointToLeaf.size()>=64) + { + pointToLeaf.clear(); + Com_Printf("Cleared cache\n"); + } + leafnum=CM_PointLeafnum_r(p, 0); + pointToLeaf[pt]=leafnum; + }*/ int l = 0; - for ( ; l < sizePointToLeaf; ++l) - { - if (pointToLeaf[l].point == pt) - { + for (; l < sizePointToLeaf; ++l) { + if (pointToLeaf[l].point == pt) { leafnum = pointToLeaf[l].leaf; break; } } - if (l == sizePointToLeaf) - { // Didn't find it - if (sizePointToLeaf < MAX_POINTS_TO_LEAVES) - { // We're adding a new one, rather than replacing + if (l == sizePointToLeaf) { // Didn't find it + if (sizePointToLeaf < MAX_POINTS_TO_LEAVES) { // We're adding a new one, rather than replacing sizePointToLeaf++; - } - else - { // Put it in the "oldest" slot + } else { // Put it in the "oldest" slot l = oldestPointToLeaf++; - oldestPointToLeaf &= (MAX_POINTS_TO_LEAVES-1); + oldestPointToLeaf &= (MAX_POINTS_TO_LEAVES - 1); } leafnum = CM_PointLeafnum_r(p, 0, local); @@ -357,22 +335,22 @@ int CM_PointContents( const vec3_t p, clipHandle_t model ) { } contents = 0; - for (k=0 ; knumLeafBrushes ; k++) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; // see if the point is in the brush - for ( i = 0 ; i < b->numsides ; i++ ) { - d = DotProduct( p, b->sides[i].plane->normal ); + for (i = 0; i < b->numsides; i++) { + d = DotProduct(p, b->sides[i].plane->normal); -// FIXME test for Cash -// if ( d >= b->sides[i].plane->dist ) { - if ( d > b->sides[i].plane->dist ) { + // FIXME test for Cash + // if ( d >= b->sides[i].plane->dist ) { + if (d > b->sides[i].plane->dist) { break; } } - if ( i == b->numsides ) { + if (i == b->numsides) { contents |= b->contents; } } @@ -382,74 +360,63 @@ int CM_PointContents( const vec3_t p, clipHandle_t model ) { #else -int CM_PointContents( const vec3_t p, clipHandle_t model ) { - int leafnum=0; - int i, k; - int brushnum; - cLeaf_t *leaf; - cbrush_t *b; - int contents; - float d; - cmodel_t *clipm; - - if (!cmg.numNodes) { // map not loaded +int CM_PointContents(const vec3_t p, clipHandle_t model) { + int leafnum = 0; + int i, k; + int brushnum; + cLeaf_t *leaf; + cbrush_t *b; + int contents; + float d; + cmodel_t *clipm; + + if (!cmg.numNodes) { // map not loaded return 0; } - CPoint pt(p[0],p[1],p[2]); - if ( model ) - { - clipm = CM_ClipHandleToModel( model ); + CPoint pt(p[0], p[1], p[2]); + if (model) { + clipm = CM_ClipHandleToModel(model); leaf = &clipm->leaf; - } - else - { - hlist >::iterator l; - for(l=pointToContents.begin();l!=pointToContents.end();l++) - { - if((*l).first==pt) - { + } else { + hlist>::iterator l; + for (l = pointToContents.begin(); l != pointToContents.end(); l++) { + if ((*l).first == pt) { // Breakout early. - return((*l).second); + return ((*l).second); } } - leafnum=CM_PointLeafnum_r(p, 0); + leafnum = CM_PointLeafnum_r(p, 0); leaf = &cmg.leafs[leafnum]; } contents = 0; - for (k=0 ; knumLeafBrushes ; k++) - { - brushnum = cmg.leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = cmg.leafbrushes[leaf->firstLeafBrush + k]; b = &cmg.brushes[brushnum]; // see if the point is in the brush - for ( i = 0 ; i < b->numsides ; i++ ) - { - d = DotProduct( p, b->sides[i].plane->normal ); + for (i = 0; i < b->numsides; i++) { + d = DotProduct(p, b->sides[i].plane->normal); // FIXME test for Cash -// if ( d >= b->sides[i].plane->dist ) { - if ( d > b->sides[i].plane->dist ) - { + // if ( d >= b->sides[i].plane->dist ) { + if (d > b->sides[i].plane->dist) { break; } } - if ( i == b->numsides ) - { + if (i == b->numsides) { contents |= b->contents; } } // Cache the result for next time. - if(!model) - { - if(pointToContents.size()>=64) - { + if (!model) { + if (pointToContents.size() >= 64) { pointToContents.pop_back(); } - pointToContents.push_front(pair(pt,contents)); + pointToContents.push_front(pair(pt, contents)); } return contents; @@ -464,31 +431,27 @@ Handles offseting and rotation of the end points for moving and rotating entities ================== */ -int CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { - vec3_t p_l; - vec3_t temp; - vec3_t forward, right, up; +int CM_TransformedPointContents(const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { + vec3_t p_l; + vec3_t temp; + vec3_t forward, right, up; // subtract origin offset - VectorSubtract (p, origin, p_l); + VectorSubtract(p, origin, p_l); // rotate start and end into the models frame of reference - if ( model != BOX_MODEL_HANDLE && - (angles[0] || angles[1] || angles[2]) ) - { - AngleVectors (angles, forward, right, up); + if (model != BOX_MODEL_HANDLE && (angles[0] || angles[1] || angles[2])) { + AngleVectors(angles, forward, right, up); - VectorCopy (p_l, temp); - p_l[0] = DotProduct (temp, forward); - p_l[1] = -DotProduct (temp, right); - p_l[2] = DotProduct (temp, up); + VectorCopy(p_l, temp); + p_l[0] = DotProduct(temp, forward); + p_l[1] = -DotProduct(temp, right); + p_l[2] = DotProduct(temp, up); } - return CM_PointContents( p_l, model ); + return CM_PointContents(p_l, model); } - - /* =============================================================================== @@ -497,8 +460,8 @@ PVS =============================================================================== */ -byte *CM_ClusterPVS (int cluster) { - if (cluster < 0 || cluster >= cmg.numClusters || !cmg.vised ) { +byte *CM_ClusterPVS(int cluster) { + if (cluster < 0 || cluster >= cmg.numClusters || !cmg.vised) { return cmg.visibility; } @@ -513,25 +476,25 @@ AREAPORTALS =============================================================================== */ -void CM_FloodArea_r( int areaNum, int floodnum, clipMap_t &cm) { - int i; +void CM_FloodArea_r(int areaNum, int floodnum, clipMap_t &cm) { + int i; cArea_t *area; - int *con; + int *con; - area = &cmg.areas[ areaNum ]; + area = &cmg.areas[areaNum]; - if ( area->floodvalid == cmg.floodvalid ) { + if (area->floodvalid == cmg.floodvalid) { if (area->floodnum == floodnum) return; - Com_Error (ERR_DROP, "FloodArea_r: reflooded"); + Com_Error(ERR_DROP, "FloodArea_r: reflooded"); } area->floodnum = floodnum; area->floodvalid = cmg.floodvalid; con = cmg.areaPortals + areaNum * cmg.numAreas; - for ( i=0 ; i < cmg.numAreas ; i++ ) { - if ( con[i] > 0 ) { - CM_FloodArea_r( i, floodnum, cm ); + for (i = 0; i < cmg.numAreas; i++) { + if (con[i] > 0) { + CM_FloodArea_r(i, floodnum, cm); } } } @@ -542,24 +505,23 @@ CM_FloodAreaConnections ==================== */ -void CM_FloodAreaConnections( clipMap_t &cm ) { - int i; - cArea_t *area; - int floodnum; +void CM_FloodAreaConnections(clipMap_t &cm) { + int i; + cArea_t *area; + int floodnum; // all current floods are now invalid cmg.floodvalid++; floodnum = 0; - for (i = 0 ; i < cmg.numAreas ; i++) { + for (i = 0; i < cmg.numAreas; i++) { area = &cmg.areas[i]; if (area->floodvalid == cmg.floodvalid) { - continue; // already flooded into + continue; // already flooded into } floodnum++; - CM_FloodArea_r (i, floodnum, cm); + CM_FloodArea_r(i, floodnum, cm); } - } /* @@ -568,27 +530,27 @@ CM_AdjustAreaPortalState ==================== */ -void CM_AdjustAreaPortalState( int area1, int area2, qboolean open ) { - if ( area1 < 0 || area2 < 0 ) { +void CM_AdjustAreaPortalState(int area1, int area2, qboolean open) { + if (area1 < 0 || area2 < 0) { return; } - if ( area1 >= cmg.numAreas || area2 >= cmg.numAreas ) { - Com_Error (ERR_DROP, "CM_ChangeAreaPortalState: bad area number"); + if (area1 >= cmg.numAreas || area2 >= cmg.numAreas) { + Com_Error(ERR_DROP, "CM_ChangeAreaPortalState: bad area number"); } - if ( open ) { - cmg.areaPortals[ area1 * cmg.numAreas + area2 ]++; - cmg.areaPortals[ area2 * cmg.numAreas + area1 ]++; + if (open) { + cmg.areaPortals[area1 * cmg.numAreas + area2]++; + cmg.areaPortals[area2 * cmg.numAreas + area1]++; } else { - cmg.areaPortals[ area1 * cmg.numAreas + area2 ]--; - cmg.areaPortals[ area2 * cmg.numAreas + area1 ]--; - if ( cmg.areaPortals[ area2 * cmg.numAreas + area1 ] < 0 ) { - Com_Error (ERR_DROP, "CM_AdjustAreaPortalState: negative reference count"); + cmg.areaPortals[area1 * cmg.numAreas + area2]--; + cmg.areaPortals[area2 * cmg.numAreas + area1]--; + if (cmg.areaPortals[area2 * cmg.numAreas + area1] < 0) { + Com_Error(ERR_DROP, "CM_AdjustAreaPortalState: negative reference count"); } } - CM_FloodAreaConnections (cmg); + CM_FloodAreaConnections(cmg); } /* @@ -597,19 +559,19 @@ CM_AreasConnected ==================== */ -qboolean CM_AreasConnected( int area1, int area2 ) { +qboolean CM_AreasConnected(int area1, int area2) { #ifndef BSPC - if ( cm_noAreas->integer ) { + if (cm_noAreas->integer) { return qtrue; } #endif - if ( area1 < 0 || area2 < 0 ) { + if (area1 < 0 || area2 < 0) { return qfalse; } if (area1 >= cmg.numAreas || area2 >= cmg.numAreas) { - Com_Error (ERR_DROP, "area >= cmg.numAreas"); + Com_Error(ERR_DROP, "area >= cmg.numAreas"); } if (cmg.areas[area1].floodnum == cmg.areas[area2].floodnum) { @@ -618,7 +580,6 @@ qboolean CM_AreasConnected( int area1, int area2 ) { return qfalse; } - /* ================= CM_WriteAreaBits @@ -633,51 +594,43 @@ viewpoints and get the union of all visible areas. This is used to cull non-visible entities from snapshots ================= */ -int CM_WriteAreaBits (byte *buffer, int area) -{ - int i; - int floodnum; - int bytes; +int CM_WriteAreaBits(byte *buffer, int area) { + int i; + int floodnum; + int bytes; - bytes = (cmg.numAreas+7)>>3; + bytes = (cmg.numAreas + 7) >> 3; #ifndef BSPC if (cm_noAreas->integer || area == -1) #else - if ( area == -1) + if (area == -1) #endif - { // for debugging, send everything - memset (buffer, 255, bytes); - } - else - { + { // for debugging, send everything + memset(buffer, 255, bytes); + } else { floodnum = cmg.areas[area].floodnum; - for (i=0 ; i>3] |= 1<<(i&7); + buffer[i >> 3] |= 1 << (i & 7); } } return bytes; } -void CM_SnapPVS(vec3_t origin,byte *buffer) -{ - int clientarea; - int leafnum; - int i; +void CM_SnapPVS(vec3_t origin, byte *buffer) { + int clientarea; + int leafnum; + int i; - leafnum = CM_PointLeafnum (origin); - clientarea = CM_LeafArea (leafnum); + leafnum = CM_PointLeafnum(origin); + clientarea = CM_LeafArea(leafnum); // calculate the visible areas - memset(buffer,0,MAX_MAP_AREA_BYTES); - CM_WriteAreaBits(buffer,clientarea); - for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) { + memset(buffer, 0, MAX_MAP_AREA_BYTES); + CM_WriteAreaBits(buffer, clientarea); + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { ((int *)buffer)[i] = ((int *)buffer)[i] ^ -1; } - } - - diff --git a/code/qcommon/cm_trace.cpp b/code/qcommon/cm_trace.cpp index 7f60532462..099969baad 100644 --- a/code/qcommon/cm_trace.cpp +++ b/code/qcommon/cm_trace.cpp @@ -36,41 +36,36 @@ POSITION TESTING CM_TestBoxInBrush ================ */ -void CM_TestBoxInBrush( traceWork_t *tw, cbrush_t *brush ) { - int i; - cplane_t *plane; - float dist; - float d1; - cbrushside_t *side; +void CM_TestBoxInBrush(traceWork_t *tw, cbrush_t *brush) { + int i; + cplane_t *plane; + float dist; + float d1; + cbrushside_t *side; if (!brush->numsides) { return; } // special test for axial - if ( tw->bounds[0][0] > brush->bounds[1][0] - || tw->bounds[0][1] > brush->bounds[1][1] - || tw->bounds[0][2] > brush->bounds[1][2] - || tw->bounds[1][0] < brush->bounds[0][0] - || tw->bounds[1][1] < brush->bounds[0][1] - || tw->bounds[1][2] < brush->bounds[0][2] - ) { + if (tw->bounds[0][0] > brush->bounds[1][0] || tw->bounds[0][1] > brush->bounds[1][1] || tw->bounds[0][2] > brush->bounds[1][2] || + tw->bounds[1][0] < brush->bounds[0][0] || tw->bounds[1][1] < brush->bounds[0][1] || tw->bounds[1][2] < brush->bounds[0][2]) { return; } // the first six planes are the axial planes, so we only // need to test the remainder - for ( i = 6 ; i < brush->numsides ; i++ ) { + for (i = 6; i < brush->numsides; i++) { side = brush->sides + i; plane = side->plane; // adjust the plane distance apropriately for mins/maxs - dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal ); + dist = plane->dist - DotProduct(tw->offsets[plane->signbits], plane->normal); - d1 = DotProduct( tw->start, plane->normal ) - dist; + d1 = DotProduct(tw->start, plane->normal) - dist; // if completely in front of face, no intersection - if ( d1 > 0 ) { + if (d1 > 0) { return; } } @@ -89,78 +84,62 @@ CM_PlaneCollision ================ */ -bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) -{ - float dist, f; - float d1, d2; - cplane_t *plane = side->plane; +bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) { + float dist, f; + float d1, d2; + cplane_t *plane = side->plane; // adjust the plane distance apropriately for mins/maxs - dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal ); + dist = plane->dist - DotProduct(tw->offsets[plane->signbits], plane->normal); - d1 = DotProduct( tw->start, plane->normal ) - dist; - d2 = DotProduct( tw->end, plane->normal ) - dist; + d1 = DotProduct(tw->start, plane->normal) - dist; + d2 = DotProduct(tw->end, plane->normal) - dist; - if (d2 > 0.0f) - { + if (d2 > 0.0f) { // endpoint is not in solid tw->getout = true; } - if (d1 > 0.0f) - { + if (d1 > 0.0f) { // startpoint is not in solid tw->startout = true; } // if completely in front of face, no intersection with the entire brush - if ((d1 > 0.0f) && ( (d2 >= SURFACE_CLIP_EPSILON) || (d2 >= d1) ) ) - { - return(false); + if ((d1 > 0.0f) && ((d2 >= SURFACE_CLIP_EPSILON) || (d2 >= d1))) { + return (false); } // if it doesn't cross the plane, the plane isn't relevent - if ((d1 <= 0.0f) && (d2 <= 0.0f)) - { - return(true); + if ((d1 <= 0.0f) && (d2 <= 0.0f)) { + return (true); } // crosses face - if (d1 > d2) - { // enter + if (d1 > d2) { // enter f = (d1 - SURFACE_CLIP_EPSILON); - if ( f < 0.0f ) - { + if (f < 0.0f) { f = 0.0f; - if (f > tw->enterFrac) - { + if (f > tw->enterFrac) { tw->enterFrac = f; tw->clipplane = plane; tw->leadside = side; } - } - else if (f > tw->enterFrac * (d1 - d2) ) - { + } else if (f > tw->enterFrac * (d1 - d2)) { tw->enterFrac = f / (d1 - d2); tw->clipplane = plane; tw->leadside = side; } - } - else - { // leave + } else { // leave f = (d1 + SURFACE_CLIP_EPSILON); - if ( f < (d1 - d2) ) - { + if (f < (d1 - d2)) { f = 1.0f; - if (f < tw->leaveFrac) - { + if (f < tw->leaveFrac) { tw->leaveFrac = f; } - } - else if (f > tw->leaveFrac * (d1 - d2) ) - { + } else if (f > tw->leaveFrac * (d1 - d2)) { tw->leaveFrac = f / (d1 - d2); } } - return(true); + return (true); } /* @@ -168,17 +147,15 @@ bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) CM_TraceThroughBrush ================ */ -void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, bool infoOnly ) -{ - int i; - cbrushside_t *side; +void CM_TraceThroughBrush(traceWork_t *tw, trace_t &trace, cbrush_t *brush, bool infoOnly) { + int i; + cbrushside_t *side; tw->enterFrac = -1.0f; tw->leaveFrac = 1.0f; tw->clipplane = NULL; - if ( !brush->numsides ) - { + if (!brush->numsides) { return; } @@ -191,12 +168,10 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo // find the latest time the trace crosses a plane towards the interior // and the earliest time the trace crosses a plane towards the exterior // - for (i = 0; i < brush->numsides; i++) - { + for (i = 0; i < brush->numsides; i++) { side = brush->sides + i; - if(!CM_PlaneCollision(tw, side)) - { + if (!CM_PlaneCollision(tw, side)) { return; } } @@ -205,14 +180,11 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo // all planes have been checked, and the trace was not // completely outside the brush // - if (!tw->startout) - { - if(!infoOnly) - { + if (!tw->startout) { + if (!infoOnly) { // original point was inside brush trace.startsolid = qtrue; - if (!tw->getout) - { + if (!tw->getout) { trace.allsolid = qtrue; trace.fraction = 0.0f; } @@ -221,20 +193,16 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo return; } - if (tw->enterFrac < tw->leaveFrac) - { - if ((tw->enterFrac > -1.0f) && (tw->enterFrac < trace.fraction)) - { - if (tw->enterFrac < 0.0f) - { + if (tw->enterFrac < tw->leaveFrac) { + if ((tw->enterFrac > -1.0f) && (tw->enterFrac < trace.fraction)) { + if (tw->enterFrac < 0.0f) { tw->enterFrac = 0.0f; } - if(!infoOnly) - { + if (!infoOnly) { trace.fraction = tw->enterFrac; trace.plane = *tw->clipplane; trace.surfaceFlags = cmg.shaders[tw->leadside->shaderNum].surfaceFlags; -// tw->trace.sideNum = tw->leadside - cmg.brushsides; + // tw->trace.sideNum = tw->leadside - cmg.brushsides; trace.contents = brush->contents; } } @@ -246,27 +214,27 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo CM_TestInLeaf ================ */ -void CM_TestInLeaf( traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local ) { - int k; - int brushnum; - cbrush_t *b; - cPatch_t *patch; +void CM_TestInLeaf(traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local) { + int k; + int brushnum; + cbrush_t *b; + cPatch_t *patch; // test box position against all brushes in the leaf - for (k=0 ; knumLeafBrushes ; k++) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; if (b->checkcount == local->checkcount) { - continue; // already checked this brush in another leaf + continue; // already checked this brush in another leaf } b->checkcount = local->checkcount; - if ( !(b->contents & tw->contents)) { + if (!(b->contents & tw->contents)) { continue; } - CM_TestBoxInBrush( tw, b ); - if ( tw->trace.allsolid ) { + CM_TestBoxInBrush(tw, b); + if (tw->trace.allsolid) { return; } } @@ -275,24 +243,24 @@ void CM_TestInLeaf( traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local ) { #ifdef BSPC if (1) { #else - if ( !cm_noCurves->integer ) { -#endif //BSPC - for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) { - patch = local->surfaces[ local->leafsurfaces[ leaf->firstLeafSurface + k ] ]; + if (!cm_noCurves->integer) { +#endif // BSPC + for (k = 0; k < leaf->numLeafSurfaces; k++) { + patch = local->surfaces[local->leafsurfaces[leaf->firstLeafSurface + k]]; - if ( !patch ) { + if (!patch) { continue; } - if ( patch->checkcount == local->checkcount ) { - continue; // already checked this brush in another leaf + if (patch->checkcount == local->checkcount) { + continue; // already checked this brush in another leaf } patch->checkcount = local->checkcount; - if ( !(patch->contents & tw->contents)) { + if (!(patch->contents & tw->contents)) { continue; } - if ( CM_PositionTestInPatchCollide( tw, patch->pc ) ) { + if (CM_PositionTestInPatchCollide(tw, patch->pc)) { tw->trace.startsolid = tw->trace.allsolid = qtrue; tw->trace.fraction = 0; tw->trace.contents = patch->contents; @@ -307,17 +275,17 @@ void CM_TestInLeaf( traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local ) { CM_PositionTest ================== */ -#define MAX_POSITION_LEAFS 1024 -void CM_PositionTest( traceWork_t *tw ) { - int leafs[MAX_POSITION_LEAFS]; - int i; - leafList_t ll; +#define MAX_POSITION_LEAFS 1024 +void CM_PositionTest(traceWork_t *tw) { + int leafs[MAX_POSITION_LEAFS]; + int i; + leafList_t ll; // identify the leafs we are touching - VectorAdd( tw->start, tw->size[0], ll.bounds[0] ); - VectorAdd( tw->start, tw->size[1], ll.bounds[1] ); + VectorAdd(tw->start, tw->size[0], ll.bounds[0]); + VectorAdd(tw->start, tw->size[1], ll.bounds[1]); - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { ll.bounds[0][i] -= 1; ll.bounds[1][i] += 1; } @@ -331,15 +299,14 @@ void CM_PositionTest( traceWork_t *tw ) { cmg.checkcount++; - CM_BoxLeafnums_r( &ll, 0 ); - + CM_BoxLeafnums_r(&ll, 0); cmg.checkcount++; // test the contents of the leafs - for (i=0 ; i < ll.count ; i++) { - CM_TestInLeaf( tw, &cmg.leafs[leafs[i]], &cmg ); - if ( tw->trace.allsolid ) { + for (i = 0; i < ll.count; i++) { + CM_TestInLeaf(tw, &cmg.leafs[leafs[i]], &cmg); + if (tw->trace.allsolid) { break; } } @@ -353,62 +320,55 @@ BOX TRACING =============================================================================== */ - /* ================ CM_TraceThroughPatch ================ */ -void CM_TraceThroughPatch( traceWork_t *tw, cPatch_t *patch ) { - float oldFrac; +void CM_TraceThroughPatch(traceWork_t *tw, cPatch_t *patch) { + float oldFrac; c_patch_traces++; oldFrac = tw->trace.fraction; - CM_TraceThroughPatchCollide( tw, patch->pc ); + CM_TraceThroughPatchCollide(tw, patch->pc); - if ( tw->trace.fraction < oldFrac ) { + if (tw->trace.fraction < oldFrac) { tw->trace.surfaceFlags = patch->surfaceFlags; tw->trace.contents = patch->contents; } } - /* ================ CM_TraceThroughBrush ================ */ -void CM_TraceThroughBrush( traceWork_t *tw, cbrush_t *brush ) { - int i; - cplane_t *plane, *clipplane; - float dist; - float enterFrac, leaveFrac; - float d1, d2; - qboolean getout, startout; - float f; - cbrushside_t *side, *leadside; +void CM_TraceThroughBrush(traceWork_t *tw, cbrush_t *brush) { + int i; + cplane_t *plane, *clipplane; + float dist; + float enterFrac, leaveFrac; + float d1, d2; + qboolean getout, startout; + float f; + cbrushside_t *side, *leadside; enterFrac = -1.0; leaveFrac = 1.0; clipplane = NULL; - if ( !brush->numsides ) { + if (!brush->numsides) { return; } // I'm not sure if test is strictly correct. Are all // bboxes axis aligned? Do I care? It seems to work // good enough... - if ( tw->bounds[0][0] > brush->bounds[1][0] - || tw->bounds[0][1] > brush->bounds[1][1] - || tw->bounds[0][2] > brush->bounds[1][2] - || tw->bounds[1][0] < brush->bounds[0][0] - || tw->bounds[1][1] < brush->bounds[0][1] - || tw->bounds[1][2] < brush->bounds[0][2] - ) { + if (tw->bounds[0][0] > brush->bounds[1][0] || tw->bounds[0][1] > brush->bounds[1][1] || tw->bounds[0][2] > brush->bounds[1][2] || + tw->bounds[1][0] < brush->bounds[0][0] || tw->bounds[1][1] < brush->bounds[0][1] || tw->bounds[1][2] < brush->bounds[0][2]) { return; } @@ -424,37 +384,37 @@ void CM_TraceThroughBrush( traceWork_t *tw, cbrush_t *brush ) { // find the latest time the trace crosses a plane towards the interior // and the earliest time the trace crosses a plane towards the exterior // - for (i=0 ; inumsides ; i++) { + for (i = 0; i < brush->numsides; i++) { side = brush->sides + i; plane = side->plane; // adjust the plane distance apropriately for mins/maxs - dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal ); + dist = plane->dist - DotProduct(tw->offsets[plane->signbits], plane->normal); - d1 = DotProduct( tw->start, plane->normal ) - dist; - d2 = DotProduct( tw->end, plane->normal ) - dist; + d1 = DotProduct(tw->start, plane->normal) - dist; + d2 = DotProduct(tw->end, plane->normal) - dist; if (d2 > 0) { - getout = qtrue; // endpoint is not in solid + getout = qtrue; // endpoint is not in solid } if (d1 > 0) { startout = qtrue; } // if completely in front of face, no intersection with the entire brush - if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { + if (d1 > 0 && (d2 >= SURFACE_CLIP_EPSILON || d2 >= d1)) { return; } // if it doesn't cross the plane, the plane isn't relevent - if (d1 <= 0 && d2 <= 0 ) { + if (d1 <= 0 && d2 <= 0) { continue; } // crosses face - if (d1 > d2) { // enter - f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f < 0 ) { + if (d1 > d2) { // enter + f = (d1 - SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f < 0) { f = 0; } if (f > enterFrac) { @@ -462,9 +422,9 @@ void CM_TraceThroughBrush( traceWork_t *tw, cbrush_t *brush ) { clipplane = plane; leadside = side; } - } else { // leave - f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f > 1 ) { + } else { // leave + f = (d1 + SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f > 1) { f = 1; } if (f < leaveFrac) { @@ -477,11 +437,10 @@ void CM_TraceThroughBrush( traceWork_t *tw, cbrush_t *brush ) { // all planes have been checked, and the trace was not // completely outside the brush // - if (!startout) { // original point was inside brush + if (!startout) { // original point was inside brush tw->trace.startsolid = qtrue; - tw->trace.contents |= brush->contents; //note, we always want to know the contents of something we're inside of - if (!getout) - { //endpoint was inside brush + tw->trace.contents |= brush->contents; // note, we always want to know the contents of something we're inside of + if (!getout) { // endpoint was inside brush tw->trace.allsolid = qtrue; tw->trace.fraction = 0; } @@ -507,23 +466,19 @@ CM_GenericBoxCollide ================ */ -bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) -{ - int i; +bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) { + int i; // Check for completely no intersection - for(i = 0; i < 3; i++) - { - if(abounds[1][i] < bbounds[0][i]) - { - return(false); + for (i = 0; i < 3; i++) { + if (abounds[1][i] < bbounds[0][i]) { + return (false); } - if(abounds[0][i] > bbounds[1][i]) - { - return(false); + if (abounds[0][i] > bbounds[1][i]) { + return (false); } } - return(true); + return (true); } /* @@ -531,30 +486,30 @@ bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) CM_TraceToLeaf ================ */ -void CM_TraceToLeaf( traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local ) { - int k; - int brushnum; - cbrush_t *b; - cPatch_t *patch; +void CM_TraceToLeaf(traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local) { + int k; + int brushnum; + cbrush_t *b; + cPatch_t *patch; // trace line against all brushes in the leaf - for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; - if ( b->checkcount == local->checkcount ) { - continue; // already checked this brush in another leaf + if (b->checkcount == local->checkcount) { + continue; // already checked this brush in another leaf } b->checkcount = local->checkcount; - if ( !(b->contents & tw->contents) ) { + if (!(b->contents & tw->contents)) { continue; } - //if (b->contents & CONTENTS_PLAYERCLIP) continue; + // if (b->contents & CONTENTS_PLAYERCLIP) continue; - CM_TraceThroughBrush( tw, b ); - if ( !tw->trace.fraction ) { + CM_TraceThroughBrush(tw, b); + if (!tw->trace.fraction) { return; } } @@ -563,24 +518,24 @@ void CM_TraceToLeaf( traceWork_t *tw, cLeaf_t *leaf, clipMap_t *local ) { #ifdef BSPC if (1) { #else - if ( !cm_noCurves->integer ) { + if (!cm_noCurves->integer) { #endif - for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) { - patch = local->surfaces[ local->leafsurfaces[ leaf->firstLeafSurface + k ] ]; - if ( !patch ) { + for (k = 0; k < leaf->numLeafSurfaces; k++) { + patch = local->surfaces[local->leafsurfaces[leaf->firstLeafSurface + k]]; + if (!patch) { continue; } - if ( patch->checkcount == local->checkcount ) { - continue; // already checked this patch in another leaf + if (patch->checkcount == local->checkcount) { + continue; // already checked this patch in another leaf } patch->checkcount = local->checkcount; - if ( !(patch->contents & tw->contents) ) { + if (!(patch->contents & tw->contents)) { continue; } - CM_TraceThroughPatch( tw, patch ); - if ( !tw->trace.fraction ) { + CM_TraceThroughPatch(tw, patch); + if (!tw->trace.fraction) { return; } } @@ -599,23 +554,23 @@ trace volumes it is possible to hit something in a later leaf with a smaller intercept fraction. ================== */ -void CM_TraceThroughTree( traceWork_t *tw, clipMap_t *local, int num, float p1f, float p2f, vec3_t p1, vec3_t p2) { - cNode_t *node; - cplane_t *plane; - float t1, t2, offset; - float frac, frac2; - float idist; - vec3_t mid; - int side; - float midf; +void CM_TraceThroughTree(traceWork_t *tw, clipMap_t *local, int num, float p1f, float p2f, vec3_t p1, vec3_t p2) { + cNode_t *node; + cplane_t *plane; + float t1, t2, offset; + float frac, frac2; + float idist; + vec3_t mid; + int side; + float midf; if (tw->trace.fraction <= p1f) { - return; // already hit something nearer + return; // already hit something nearer } // if < 0, we are in a leaf node if (num < 0) { - CM_TraceToLeaf( tw, &local->leafs[-1-num], local ); + CM_TraceToLeaf(tw, &local->leafs[-1 - num], local); return; } @@ -634,22 +589,20 @@ return; #endif // adjust the plane distance apropriately for mins/maxs - if ( plane->type < 3 ) { + if (plane->type < 3) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; offset = tw->extents[plane->type]; } else { - t1 = DotProduct (plane->normal, p1) - plane->dist; - t2 = DotProduct (plane->normal, p2) - plane->dist; - if ( tw->isPoint ) { + t1 = DotProduct(plane->normal, p1) - plane->dist; + t2 = DotProduct(plane->normal, p2) - plane->dist; + if (tw->isPoint) { offset = 0; } else { // an axial brush right behind a slanted bsp plane // will poke through when expanded, so adjust // by sqrt(3) - offset = fabs(tw->extents[0]*plane->normal[0]) + - fabs(tw->extents[1]*plane->normal[1]) + - fabs(tw->extents[2]*plane->normal[2]); + offset = fabs(tw->extents[0] * plane->normal[0]) + fabs(tw->extents[1] * plane->normal[1]) + fabs(tw->extents[2] * plane->normal[2]); offset *= 2; #if 0 @@ -663,26 +616,26 @@ return; } // see which sides we need to consider - if ( t1 >= offset + 1 && t2 >= offset + 1 ) { - CM_TraceThroughTree( tw, local, node->children[0], p1f, p2f, p1, p2 ); + if (t1 >= offset + 1 && t2 >= offset + 1) { + CM_TraceThroughTree(tw, local, node->children[0], p1f, p2f, p1, p2); return; } - if ( t1 < -offset - 1 && t2 < -offset - 1 ) { - CM_TraceThroughTree( tw, local, node->children[1], p1f, p2f, p1, p2 ); + if (t1 < -offset - 1 && t2 < -offset - 1) { + CM_TraceThroughTree(tw, local, node->children[1], p1f, p2f, p1, p2); return; } // put the crosspoint SURFACE_CLIP_EPSILON pixels on the near side - if ( t1 < t2 ) { - idist = 1.0/(t1-t2); + if (t1 < t2) { + idist = 1.0 / (t1 - t2); side = 1; - frac2 = (t1 + offset + SURFACE_CLIP_EPSILON)*idist; - frac = (t1 - offset + SURFACE_CLIP_EPSILON)*idist; + frac2 = (t1 + offset + SURFACE_CLIP_EPSILON) * idist; + frac = (t1 - offset + SURFACE_CLIP_EPSILON) * idist; } else if (t1 > t2) { - idist = 1.0/(t1-t2); + idist = 1.0 / (t1 - t2); side = 0; - frac2 = (t1 - offset - SURFACE_CLIP_EPSILON)*idist; - frac = (t1 + offset + SURFACE_CLIP_EPSILON)*idist; + frac2 = (t1 - offset - SURFACE_CLIP_EPSILON) * idist; + frac = (t1 + offset + SURFACE_CLIP_EPSILON) * idist; } else { side = 0; frac = 1; @@ -690,52 +643,46 @@ return; } // move up to the node - if ( frac < 0 ) { + if (frac < 0) { frac = 0; } - if ( frac > 1 ) { + if (frac > 1) { frac = 1; } - midf = p1f + (p2f - p1f)*frac; + midf = p1f + (p2f - p1f) * frac; - mid[0] = p1[0] + frac*(p2[0] - p1[0]); - mid[1] = p1[1] + frac*(p2[1] - p1[1]); - mid[2] = p1[2] + frac*(p2[2] - p1[2]); - - CM_TraceThroughTree( tw, local, node->children[side], p1f, midf, p1, mid ); + mid[0] = p1[0] + frac * (p2[0] - p1[0]); + mid[1] = p1[1] + frac * (p2[1] - p1[1]); + mid[2] = p1[2] + frac * (p2[2] - p1[2]); + CM_TraceThroughTree(tw, local, node->children[side], p1f, midf, p1, mid); // go past the node - if ( frac2 < 0 ) { + if (frac2 < 0) { frac2 = 0; } - if ( frac2 > 1 ) { + if (frac2 > 1) { frac2 = 1; } - midf = p1f + (p2f - p1f)*frac2; + midf = p1f + (p2f - p1f) * frac2; - mid[0] = p1[0] + frac2*(p2[0] - p1[0]); - mid[1] = p1[1] + frac2*(p2[1] - p1[1]); - mid[2] = p1[2] + frac2*(p2[2] - p1[2]); + mid[0] = p1[0] + frac2 * (p2[0] - p1[0]); + mid[1] = p1[1] + frac2 * (p2[1] - p1[1]); + mid[2] = p1[2] + frac2 * (p2[2] - p1[2]); - CM_TraceThroughTree( tw, local, node->children[side^1], midf, p2f, mid, p2 ); + CM_TraceThroughTree(tw, local, node->children[side ^ 1], midf, p2f, mid, p2); } -void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, vec3pair_t bounds) -{ - int i; +void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, vec3pair_t bounds) { + int i; - for ( i = 0 ; i < 3 ; i++ ) - { - if ( start[i] < end[i] ) - { + for (i = 0; i < 3; i++) { + if (start[i] < end[i]) { bounds[0][i] = start[i] + tw->size[0][i]; bounds[1][i] = end[i] + tw->size[1][i]; - } - else - { + } else { bounds[0][i] = end[i] + tw->size[0][i]; bounds[1][i] = start[i] + tw->size[1][i]; } @@ -749,35 +696,33 @@ void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, CM_BoxTrace ================== */ -void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask) { - int i; - traceWork_t tw; - vec3_t offset; - cmodel_t *cmod; - clipMap_t *local = 0; +void CM_BoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask) { + int i; + traceWork_t tw; + vec3_t offset; + cmodel_t *cmod; + clipMap_t *local = 0; - cmod = CM_ClipHandleToModel( model, &local ); + cmod = CM_ClipHandleToModel(model, &local); - local->checkcount++; // for multi-check avoidance + local->checkcount++; // for multi-check avoidance - c_traces++; // for statistics, may be zeroed + c_traces++; // for statistics, may be zeroed // fill in a default trace - memset( &tw, 0, sizeof(tw) - sizeof(tw.trace.G2CollisionMap)); - tw.trace.fraction = 1; // assume it goes the entire distance until shown otherwise + memset(&tw, 0, sizeof(tw) - sizeof(tw.trace.G2CollisionMap)); + tw.trace.fraction = 1; // assume it goes the entire distance until shown otherwise if (!local->numNodes) { *results = tw.trace; - return; // map not loaded, shouldn't happen + return; // map not loaded, shouldn't happen } // allow NULL to be passed in for 0,0,0 - if ( !mins ) { + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } @@ -787,8 +732,8 @@ void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, // adjust so that mins and maxs are always symetric, which // avoids some complications with plane expanding of rotated // bmodels - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; tw.size[0][i] = mins[i] - offset[i]; tw.size[1][i] = maxs[i] - offset[i]; tw.start[i] = start[i] + offset[i]; @@ -830,12 +775,11 @@ void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, tw.offsets[7][1] = tw.size[1][1]; tw.offsets[7][2] = tw.size[1][2]; - // // calculate bounds // - for ( i = 0 ; i < 3 ; i++ ) { - if ( tw.start[i] < tw.end[i] ) { + for (i = 0; i < 3; i++) { + if (tw.start[i] < tw.end[i]) { tw.bounds[0][i] = tw.start[i] + tw.size[0][i]; tw.bounds[1][i] = tw.end[i] + tw.size[1][i]; } else { @@ -848,18 +792,18 @@ void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, // check for position test special case // if (start[0] == end[0] && start[1] == end[1] && start[2] == end[2]) { - if ( model ) { - CM_TestInLeaf( &tw, &cmod->leaf, local ); + if (model) { + CM_TestInLeaf(&tw, &cmod->leaf, local); } else { - CM_PositionTest( &tw ); + CM_PositionTest(&tw); } } else { // // check for point special case // - if ( tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0 ) { + if (tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0) { tw.isPoint = qtrue; - VectorClear( tw.extents ); + VectorClear(tw.extents); } else { tw.isPoint = qfalse; tw.extents[0] = tw.size[1][0]; @@ -870,18 +814,18 @@ void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, // // general sweeping through world // - if ( model ) { - CM_TraceToLeaf( &tw, &cmod->leaf, local ); + if (model) { + CM_TraceToLeaf(&tw, &cmod->leaf, local); } else { - CM_TraceThroughTree( &tw, local, 0, 0, 1, tw.start, tw.end ); + CM_TraceThroughTree(&tw, local, 0, 0, 1, tw.start, tw.end); } } // generate endpos from the original, unmodified start/end - if ( tw.trace.fraction == 1 ) { - VectorCopy (end, tw.trace.endpos); + if (tw.trace.fraction == 1) { + VectorCopy(end, tw.trace.endpos); } else { - for ( i=0 ; i<3 ; i++ ) { + for (i = 0; i < 3; i++) { tw.trace.endpos[i] = start[i] + tw.trace.fraction * (end[i] - start[i]); } } @@ -889,7 +833,6 @@ void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, *results = tw.trace; } - /* ================== CM_TransformedBoxTrace @@ -898,32 +841,30 @@ Handles offseting and rotation of the end points for moving and rotating entities ================== */ -void CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask, - const vec3_t origin, const vec3_t angles) { - trace_t trace; - vec3_t start_l, end_l; - vec3_t a; - vec3_t forward, right, up; - vec3_t temp; - qboolean rotated; - vec3_t offset; - vec3_t symetricSize[2]; - int i; - - if ( !mins ) { +void CM_TransformedBoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, + const vec3_t origin, const vec3_t angles) { + trace_t trace; + vec3_t start_l, end_l; + vec3_t a; + vec3_t forward, right, up; + vec3_t temp; + qboolean rotated; + vec3_t offset; + vec3_t symetricSize[2]; + int i; + + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } // adjust so that mins and maxs are always symetric, which // avoids some complications with plane expanding of rotated // bmodels - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; symetricSize[0][i] = mins[i] - offset[i]; symetricSize[1][i] = maxs[i] - offset[i]; start_l[i] = start[i] + offset[i]; @@ -931,43 +872,42 @@ void CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t } // subtract origin offset - VectorSubtract( start_l, origin, start_l ); - VectorSubtract( end_l, origin, end_l ); + VectorSubtract(start_l, origin, start_l); + VectorSubtract(end_l, origin, end_l); // rotate start and end into the models frame of reference - if ( model != BOX_MODEL_HANDLE && - (angles[0] || angles[1] || angles[2]) ) { + if (model != BOX_MODEL_HANDLE && (angles[0] || angles[1] || angles[2])) { rotated = qtrue; } else { rotated = qfalse; } if (rotated) { - AngleVectors (angles, forward, right, up); + AngleVectors(angles, forward, right, up); - VectorCopy (start_l, temp); - start_l[0] = DotProduct (temp, forward); - start_l[1] = -DotProduct (temp, right); - start_l[2] = DotProduct (temp, up); + VectorCopy(start_l, temp); + start_l[0] = DotProduct(temp, forward); + start_l[1] = -DotProduct(temp, right); + start_l[2] = DotProduct(temp, up); - VectorCopy (end_l, temp); - end_l[0] = DotProduct (temp, forward); - end_l[1] = -DotProduct (temp, right); - end_l[2] = DotProduct (temp, up); + VectorCopy(end_l, temp); + end_l[0] = DotProduct(temp, forward); + end_l[1] = -DotProduct(temp, right); + end_l[2] = DotProduct(temp, up); } // sweep the box through the model - CM_BoxTrace( &trace, start_l, end_l, symetricSize[0], symetricSize[1], model, brushmask); + CM_BoxTrace(&trace, start_l, end_l, symetricSize[0], symetricSize[1], model, brushmask); - if ( rotated && trace.fraction != 1.0 ) { + if (rotated && trace.fraction != 1.0) { // FIXME: figure out how to do this with existing angles - VectorNegate (angles, a); - AngleVectors (a, forward, right, up); + VectorNegate(angles, a); + AngleVectors(a, forward, right, up); - VectorCopy (trace.plane.normal, temp); - trace.plane.normal[0] = DotProduct (temp, forward); - trace.plane.normal[1] = -DotProduct (temp, right); - trace.plane.normal[2] = DotProduct (temp, up); + VectorCopy(trace.plane.normal, temp); + trace.plane.normal[0] = DotProduct(temp, forward); + trace.plane.normal[1] = -DotProduct(temp, right); + trace.plane.normal[2] = DotProduct(temp, up); } trace.endpos[0] = start[0] + trace.fraction * (end[0] - start[0]); @@ -985,24 +925,19 @@ Returns true if culled out ================= */ -bool CM_CullBox(const cplane_t *frustum, const vec3_t transformed[8]) -{ - int i, j; - const cplane_t *frust; +bool CM_CullBox(const cplane_t *frustum, const vec3_t transformed[8]) { + int i, j; + const cplane_t *frust; // check against frustum planes - for (i=0, frust=frustum; i<4 ; i++, frust++) - { - for (j=0 ; j<8 ; j++) - { - if (DotProduct(transformed[j], frust->normal) > frust->dist) - { // a point is in front + for (i = 0, frust = frustum; i < 4; i++, frust++) { + for (j = 0; j < 8; j++) { + if (DotProduct(transformed[j], frust->normal) > frust->dist) { // a point is in front break; } } - if (j == 8) - { // all points were behind one of the planes + if (j == 8) { // all points were behind one of the planes return true; } } @@ -1017,18 +952,16 @@ Returns true if culled out ================= */ -bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds) -{ - int i; - vec3_t transformed[8]; +bool CM_CullWorldBox(const cplane_t *frustum, const vec3pair_t bounds) { + int i; + vec3_t transformed[8]; - for (i = 0 ; i < 8 ; i++) - { + for (i = 0; i < 8; i++) { transformed[i][0] = bounds[i & 1][0]; transformed[i][1] = bounds[(i >> 1) & 1][1]; transformed[i][2] = bounds[(i >> 2) & 1][2]; } - //rwwFIXMEFIXME: Was not ! before. But that seems the way it should be and it works that way. Why? - return(!CM_CullBox(frustum, transformed)); + // rwwFIXMEFIXME: Was not ! before. But that seems the way it should be and it works that way. Why? + return (!CM_CullBox(frustum, transformed)); } diff --git a/code/qcommon/cmd.cpp b/code/qcommon/cmd.cpp index a918cd2633..06a0535bb9 100644 --- a/code/qcommon/cmd.cpp +++ b/code/qcommon/cmd.cpp @@ -27,18 +27,18 @@ along with this program; if not, see . #include "q_shared.h" #include "qcommon.h" -#define MAX_CMD_BUFFER 128*1024 -#define MAX_CMD_LINE 1024 +#define MAX_CMD_BUFFER 128 * 1024 +#define MAX_CMD_LINE 1024 typedef struct cmd_s { - byte *data; - int maxsize; - int cursize; + byte *data; + int maxsize; + int cursize; } cmd_t; -int cmd_wait; -cmd_t cmd_text; -byte cmd_text_buf[MAX_CMD_BUFFER]; +int cmd_wait; +cmd_t cmd_text; +byte cmd_text_buf[MAX_CMD_BUFFER]; //============================================================================= @@ -51,17 +51,16 @@ next frame. This allows commands like: bind g "cmd use rocket ; +attack ; wait ; -attack ; cmd use blaster" ============ */ -void Cmd_Wait_f( void ) { - if ( Cmd_Argc() == 2 ) { - cmd_wait = atoi( Cmd_Argv( 1 ) ); - if ( cmd_wait < 0 ) +void Cmd_Wait_f(void) { + if (Cmd_Argc() == 2) { + cmd_wait = atoi(Cmd_Argv(1)); + if (cmd_wait < 0) cmd_wait = 1; // ignore the argument } else { cmd_wait = 1; } } - /* ============================================================================= @@ -75,8 +74,7 @@ void Cmd_Wait_f( void ) { Cbuf_Init ============ */ -void Cbuf_Init (void) -{ +void Cbuf_Init(void) { cmd_text.data = cmd_text_buf; cmd_text.maxsize = MAX_CMD_BUFFER; cmd_text.cursize = 0; @@ -89,21 +87,19 @@ Cbuf_AddText Adds command text at the end of the buffer, does NOT add a final \n ============ */ -void Cbuf_AddText( const char *text ) { - int l; +void Cbuf_AddText(const char *text) { + int l; - l = strlen (text); + l = strlen(text); - if (cmd_text.cursize + l >= cmd_text.maxsize) - { - Com_Printf ("Cbuf_AddText: overflow\n"); + if (cmd_text.cursize + l >= cmd_text.maxsize) { + Com_Printf("Cbuf_AddText: overflow\n"); return; } Com_Memcpy(&cmd_text.data[cmd_text.cursize], text, l); cmd_text.cursize += l; } - /* ============ Cbuf_InsertText @@ -112,57 +108,54 @@ Adds command text immediately after the current command Adds a \n to the text ============ */ -void Cbuf_InsertText( const char *text ) { - int len; - int i; +void Cbuf_InsertText(const char *text) { + int len; + int i; - len = strlen( text ) + 1; - if ( len + cmd_text.cursize > cmd_text.maxsize ) { - Com_Printf( "Cbuf_InsertText overflowed\n" ); + len = strlen(text) + 1; + if (len + cmd_text.cursize > cmd_text.maxsize) { + Com_Printf("Cbuf_InsertText overflowed\n"); return; } // move the existing command text - for ( i = cmd_text.cursize - 1 ; i >= 0 ; i-- ) { - cmd_text.data[ i + len ] = cmd_text.data[ i ]; + for (i = cmd_text.cursize - 1; i >= 0; i--) { + cmd_text.data[i + len] = cmd_text.data[i]; } // copy the new text in - Com_Memcpy( cmd_text.data, text, len - 1 ); + Com_Memcpy(cmd_text.data, text, len - 1); // add a \n - cmd_text.data[ len - 1 ] = '\n'; + cmd_text.data[len - 1] = '\n'; cmd_text.cursize += len; } - /* ============ Cbuf_ExecuteText ============ */ -void Cbuf_ExecuteText (int exec_when, const char *text) -{ - switch (exec_when) - { +void Cbuf_ExecuteText(int exec_when, const char *text) { + switch (exec_when) { case EXEC_NOW: if (text && strlen(text) > 0) { Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", text); - Cmd_ExecuteString (text); + Cmd_ExecuteString(text); } else { Cbuf_Execute(); Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", cmd_text.data); } break; case EXEC_INSERT: - Cbuf_InsertText (text); + Cbuf_InsertText(text); break; case EXEC_APPEND: - Cbuf_AddText (text); + Cbuf_AddText(text); break; default: - Com_Error (ERR_FATAL, "Cbuf_ExecuteText: bad exec_when"); + Com_Error(ERR_FATAL, "Cbuf_ExecuteText: bad exec_when"); } } @@ -171,12 +164,11 @@ void Cbuf_ExecuteText (int exec_when, const char *text) Cbuf_Execute ============ */ -void Cbuf_Execute (void) -{ - int i; - char *text; - char line[MAX_CMD_LINE]; - int quotes; +void Cbuf_Execute(void) { + int i; + char *text; + char line[MAX_CMD_LINE]; + int quotes; // This will keep // style comments all on one line by not breaking on // a semicolon. It will keep /* ... */ style comments all on one line by not @@ -184,9 +176,8 @@ void Cbuf_Execute (void) qboolean in_star_comment = qfalse; qboolean in_slash_comment = qfalse; - while (cmd_text.cursize) - { - if ( cmd_wait > 0 ) { + while (cmd_text.cursize) { + if (cmd_wait > 0) { // skip out while text still remains in buffer, leaving it // for next frame cmd_wait--; @@ -197,18 +188,17 @@ void Cbuf_Execute (void) text = (char *)cmd_text.data; quotes = 0; - for (i=0 ; i< cmd_text.cursize ; i++) - { + for (i = 0; i < cmd_text.cursize; i++) { if (text[i] == '"') quotes++; - if ( !(quotes&1)) { + if (!(quotes & 1)) { if (i < cmd_text.cursize - 1) { - if (! in_star_comment && text[i] == '/' && text[i+1] == '/') + if (!in_star_comment && text[i] == '/' && text[i + 1] == '/') in_slash_comment = qtrue; - else if (! in_slash_comment && text[i] == '/' && text[i+1] == '*') + else if (!in_slash_comment && text[i] == '/' && text[i + 1] == '*') in_star_comment = qtrue; - else if (in_star_comment && text[i] == '*' && text[i+1] == '/') { + else if (in_star_comment && text[i] == '*' && text[i + 1] == '/') { in_star_comment = qfalse; // If we are in a star comment, then the part after it is valid // Note: This will cause it to NUL out the terminating '/' @@ -217,42 +207,40 @@ void Cbuf_Execute (void) break; } } - if (! in_slash_comment && ! in_star_comment && text[i] == ';') + if (!in_slash_comment && !in_star_comment && text[i] == ';') break; } - if (! in_star_comment && (text[i] == '\n' || text[i] == '\r')) { + if (!in_star_comment && (text[i] == '\n' || text[i] == '\r')) { in_slash_comment = qfalse; break; } } - if( i >= (MAX_CMD_LINE - 1)) { + if (i >= (MAX_CMD_LINE - 1)) { i = MAX_CMD_LINE - 1; } - Com_Memcpy (line, text, i); + Com_Memcpy(line, text, i); line[i] = 0; -// delete the text from the command buffer and move remaining commands down -// this is necessary because commands (exec) can insert data at the -// beginning of the text buffer + // delete the text from the command buffer and move remaining commands down + // this is necessary because commands (exec) can insert data at the + // beginning of the text buffer if (i == cmd_text.cursize) cmd_text.cursize = 0; - else - { + else { i++; cmd_text.cursize -= i; - memmove (text, text+i, cmd_text.cursize); + memmove(text, text + i, cmd_text.cursize); } -// execute the command line + // execute the command line - Cmd_ExecuteString (line); + Cmd_ExecuteString(line); } } - /* ============================================================================== @@ -261,44 +249,41 @@ void Cbuf_Execute (void) ============================================================================== */ - /* =============== Cmd_Exec_f =============== */ -void Cmd_Exec_f( void ) { +void Cmd_Exec_f(void) { bool quiet; union { - char *c; - void *v; + char *c; + void *v; } f; - char filename[MAX_QPATH]; + char filename[MAX_QPATH]; quiet = !Q_stricmp(Cmd_Argv(0), "execq"); - if (Cmd_Argc () != 2) { - Com_Printf ("exec%s : execute a script file%s\n", - quiet ? "q" : "", quiet ? " without notification" : ""); + if (Cmd_Argc() != 2) { + Com_Printf("exec%s : execute a script file%s\n", quiet ? "q" : "", quiet ? " without notification" : ""); return; } - Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); - FS_ReadFile( filename, &f.v); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".cfg"); + FS_ReadFile(filename, &f.v); if (!f.c) { - Com_Printf ("couldn't exec %s\n", filename); + Com_Printf("couldn't exec %s\n", filename); return; } if (!quiet) - Com_Printf ("execing %s\n", filename); + Com_Printf("execing %s\n", filename); - Cbuf_InsertText (f.c); + Cbuf_InsertText(f.c); - FS_FreeFile (f.v); + FS_FreeFile(f.v); } - /* =============== Cmd_Vstr_f @@ -306,19 +291,18 @@ Cmd_Vstr_f Inserts the current value of a variable as command text =============== */ -void Cmd_Vstr_f( void ) { - const char *v; +void Cmd_Vstr_f(void) { + const char *v; - if (Cmd_Argc () != 2) { - Com_Printf ("vstr : execute a variable command\n"); + if (Cmd_Argc() != 2) { + Com_Printf("vstr : execute a variable command\n"); return; } - v = Cvar_VariableString( Cmd_Argv( 1 ) ); - Cbuf_InsertText( va("%s\n", v ) ); + v = Cvar_VariableString(Cmd_Argv(1)); + Cbuf_InsertText(va("%s\n", v)); } - /* =============== Cmd_Echo_f @@ -326,11 +310,7 @@ Cmd_Echo_f Just prints the rest of the line to the console =============== */ -void Cmd_Echo_f (void) -{ - Com_Printf ("%s\n", Cmd_Args()); -} - +void Cmd_Echo_f(void) { Com_Printf("%s\n", Cmd_Args()); } /* ============================================================================= @@ -340,32 +320,29 @@ void Cmd_Echo_f (void) ============================================================================= */ -typedef struct cmd_function_s -{ - struct cmd_function_s *next; - char *name; - xcommand_t function; - completionFunc_t complete; +typedef struct cmd_function_s { + struct cmd_function_s *next; + char *name; + xcommand_t function; + completionFunc_t complete; } cmd_function_t; +static int cmd_argc; +static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized +static char cmd_tokenized[BIG_INFO_STRING + MAX_STRING_TOKENS]; // will have 0 bytes inserted +static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing) -static int cmd_argc; -static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized -static char cmd_tokenized[BIG_INFO_STRING+MAX_STRING_TOKENS]; // will have 0 bytes inserted -static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing) - -static cmd_function_t *cmd_functions; // possible commands to execute +static cmd_function_t *cmd_functions; // possible commands to execute /* ============ Cmd_FindCommand ============ */ -cmd_function_t *Cmd_FindCommand( const char *cmd_name ) -{ +cmd_function_t *Cmd_FindCommand(const char *cmd_name) { cmd_function_t *cmd; - for( cmd = cmd_functions; cmd; cmd = cmd->next ) - if( !Q_stricmp( cmd_name, cmd->name ) ) + for (cmd = cmd_functions; cmd; cmd = cmd->next) + if (!Q_stricmp(cmd_name, cmd->name)) return cmd; return NULL; } @@ -375,17 +352,15 @@ cmd_function_t *Cmd_FindCommand( const char *cmd_name ) Cmd_Argc ============ */ -int Cmd_Argc( void ) { - return cmd_argc; -} +int Cmd_Argc(void) { return cmd_argc; } /* ============ Cmd_Argv ============ */ -char *Cmd_Argv( int arg ) { - if ( (unsigned)arg >= (unsigned)cmd_argc ) +char *Cmd_Argv(int arg) { + if ((unsigned)arg >= (unsigned)cmd_argc) return ""; return cmd_argv[arg]; @@ -399,9 +374,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_Argv( arg ), bufferLength ); -} +void Cmd_ArgvBuffer(int arg, char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_Argv(arg), bufferLength); } /* ============ @@ -410,17 +383,17 @@ Cmd_ArgsFrom Returns a single string containing argv(arg) to argv(argc()-1) ============ */ -char *Cmd_ArgsFrom( int arg ) { - static char cmd_args[BIG_INFO_STRING]; - int i; +char *Cmd_ArgsFrom(int arg) { + static char cmd_args[BIG_INFO_STRING]; + int i; cmd_args[0] = '\0'; if (arg < 0) arg = 0; - for ( i = arg ; i < cmd_argc ; i++ ) { - Q_strcat( cmd_args, sizeof( cmd_args ), cmd_argv[i] ); - if ( i != cmd_argc-1 ) { - Q_strcat( cmd_args, sizeof( cmd_args ), " " ); + for (i = arg; i < cmd_argc; i++) { + Q_strcat(cmd_args, sizeof(cmd_args), cmd_argv[i]); + if (i != cmd_argc - 1) { + Q_strcat(cmd_args, sizeof(cmd_args), " "); } } @@ -434,9 +407,7 @@ Cmd_Args Returns a single string containing argv(1) to argv(argc()-1) ============ */ -char *Cmd_Args( void ) { - return Cmd_ArgsFrom( 1 ); -} +char *Cmd_Args(void) { return Cmd_ArgsFrom(1); } /* ============ @@ -446,9 +417,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgsBuffer( char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_ArgsFrom( 1 ), bufferLength ); -} +void Cmd_ArgsBuffer(char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_ArgsFrom(1), bufferLength); } /* ============ @@ -458,9 +427,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgsFromBuffer( int arg, char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_Args( ), bufferLength ); -} +void Cmd_ArgsFromBuffer(int arg, char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_Args(), bufferLength); } /* ============ @@ -471,10 +438,7 @@ For rcon use when you want to transmit without altering quoting https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543 ============ */ -char *Cmd_Cmd(void) -{ - return cmd_cmd; -} +char *Cmd_Cmd(void) { return cmd_cmd; } /* ============ @@ -486,67 +450,67 @@ are inserted in the apropriate place, The argv array will point into this temporary buffer. ============ */ -static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { - const char *text; - char *textOut; +static void Cmd_TokenizeString2(const char *text_in, qboolean ignoreQuotes) { + const char *text; + char *textOut; // clear previous args cmd_argc = 0; - if ( !text_in ) { + if (!text_in) { return; } - Q_strncpyz( cmd_cmd, text_in, sizeof(cmd_cmd) ); + Q_strncpyz(cmd_cmd, text_in, sizeof(cmd_cmd)); text = text_in; textOut = cmd_tokenized; - while ( 1 ) { - if ( cmd_argc == MAX_STRING_TOKENS ) { - return; // this is usually something malicious + while (1) { + if (cmd_argc == MAX_STRING_TOKENS) { + return; // this is usually something malicious } - while ( 1 ) { + while (1) { // skip whitespace - while ( *text && *(const unsigned char* /*eurofix*/)text <= ' ' ) { + while (*text && *(const unsigned char * /*eurofix*/)text <= ' ') { text++; } - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } // skip // comments - if ( text[0] == '/' && text[1] == '/' ) { - return; // all tokens parsed + if (text[0] == '/' && text[1] == '/') { + return; // all tokens parsed } // skip /* */ comments - if ( text[0] == '/' && text[1] =='*' ) { - while ( *text && ( text[0] != '*' || text[1] != '/' ) ) { + if (text[0] == '/' && text[1] == '*') { + while (*text && (text[0] != '*' || text[1] != '/')) { text++; } - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } text += 2; } else { - break; // we are ready to parse a token + break; // we are ready to parse a token } } // handle quoted strings - // NOTE TTimo this doesn't handle \" escaping - if ( !ignoreQuotes && *text == '"' ) { + // NOTE TTimo this doesn't handle \" escaping + if (!ignoreQuotes && *text == '"') { cmd_argv[cmd_argc] = textOut; cmd_argc++; text++; - while ( *text && *text != '"' ) { + while (*text && *text != '"') { *textOut++ = *text++; } *textOut++ = 0; - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } text++; continue; @@ -557,17 +521,17 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { cmd_argc++; // skip until whitespace, quote, or command - while ( *(const unsigned char* /*eurofix*/)text > ' ' ) { - if ( !ignoreQuotes && text[0] == '"' ) { + while (*(const unsigned char * /*eurofix*/)text > ' ') { + if (!ignoreQuotes && text[0] == '"') { break; } - if ( text[0] == '/' && text[1] == '/' ) { + if (text[0] == '/' && text[1] == '/') { break; } // skip /* */ comments - if ( text[0] == '/' && text[1] =='*' ) { + if (text[0] == '/' && text[1] == '*') { break; } @@ -576,11 +540,10 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { *textOut++ = 0; - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } } - } /* @@ -588,40 +551,35 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { Cmd_TokenizeString ============ */ -void Cmd_TokenizeString( const char *text_in ) { - Cmd_TokenizeString2( text_in, qfalse ); -} +void Cmd_TokenizeString(const char *text_in) { Cmd_TokenizeString2(text_in, qfalse); } /* ============ Cmd_TokenizeStringIgnoreQuotes ============ */ -void Cmd_TokenizeStringIgnoreQuotes( const char *text_in ) { - Cmd_TokenizeString2( text_in, qtrue ); -} +void Cmd_TokenizeStringIgnoreQuotes(const char *text_in) { Cmd_TokenizeString2(text_in, qtrue); } /* ============ Cmd_AddCommand ============ */ -void Cmd_AddCommand( const char *cmd_name, xcommand_t function ) { - cmd_function_t *cmd; +void Cmd_AddCommand(const char *cmd_name, xcommand_t function) { + cmd_function_t *cmd; // fail if the command already exists - if( Cmd_FindCommand( cmd_name ) ) - { + if (Cmd_FindCommand(cmd_name)) { // allow completion-only commands to be silently doubled - if ( function != NULL ) { - Com_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name); + if (function != NULL) { + Com_Printf("Cmd_AddCommand: %s already defined\n", cmd_name); } return; } // use a small malloc to avoid zone fragmentation - cmd = (struct cmd_function_s *)S_Malloc (sizeof(cmd_function_t)); - cmd->name = CopyString( cmd_name ); + cmd = (struct cmd_function_s *)S_Malloc(sizeof(cmd_function_t)); + cmd->name = CopyString(cmd_name); cmd->function = function; cmd->complete = NULL; cmd->next = cmd_functions; @@ -633,9 +591,9 @@ void Cmd_AddCommand( const char *cmd_name, xcommand_t function ) { Cmd_SetCommandCompletionFunc ============ */ -void Cmd_SetCommandCompletionFunc( const char *command, completionFunc_t complete ) { - for ( cmd_function_t *cmd=cmd_functions; cmd; cmd=cmd->next ) { - if ( !Q_stricmp( command, cmd->name ) ) +void Cmd_SetCommandCompletionFunc(const char *command, completionFunc_t complete) { + for (cmd_function_t *cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!Q_stricmp(command, cmd->name)) cmd->complete = complete; } } @@ -645,22 +603,22 @@ void Cmd_SetCommandCompletionFunc( const char *command, completionFunc_t complet Cmd_RemoveCommand ============ */ -void Cmd_RemoveCommand( const char *cmd_name ) { - cmd_function_t *cmd, **back; +void Cmd_RemoveCommand(const char *cmd_name) { + cmd_function_t *cmd, **back; back = &cmd_functions; - while( 1 ) { + while (1) { cmd = *back; - if ( !cmd ) { + if (!cmd) { // command wasn't active return; } - if ( !strcmp( cmd_name, cmd->name ) ) { + if (!strcmp(cmd_name, cmd->name)) { *back = cmd->next; if (cmd->name) { Z_Free(cmd->name); } - Z_Free (cmd); + Z_Free(cmd); return; } back = &cmd->next; @@ -672,11 +630,11 @@ void Cmd_RemoveCommand( const char *cmd_name ) { Cmd_CommandCompletion ============ */ -void Cmd_CommandCompletion( callbackFunc_t callback ) { - cmd_function_t *cmd; +void Cmd_CommandCompletion(callbackFunc_t callback) { + cmd_function_t *cmd; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) { - callback( cmd->name ); + for (cmd = cmd_functions; cmd; cmd = cmd->next) { + callback(cmd->name); } } @@ -685,10 +643,10 @@ void Cmd_CommandCompletion( callbackFunc_t callback ) { Cmd_CompleteArgument ============ */ -void Cmd_CompleteArgument( const char *command, char *args, int argNum ) { - for ( cmd_function_t *cmd=cmd_functions; cmd; cmd=cmd->next ) { - if ( !Q_stricmp( command, cmd->name ) && cmd->complete ) - cmd->complete( args, argNum ); +void Cmd_CompleteArgument(const char *command, char *args, int argNum) { + for (cmd_function_t *cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!Q_stricmp(command, cmd->name) && cmd->complete) + cmd->complete(args, argNum); } } @@ -699,19 +657,19 @@ Cmd_ExecuteString A complete command line has been parsed, so try to execute it ============ */ -void Cmd_ExecuteString( const char *text ) { - cmd_function_t *cmd, **prev; +void Cmd_ExecuteString(const char *text) { + cmd_function_t *cmd, **prev; // execute the command line - Cmd_TokenizeString( text ); - if ( !Cmd_Argc() ) { - return; // no tokens + Cmd_TokenizeString(text); + if (!Cmd_Argc()) { + return; // no tokens } // check registered command functions - for ( prev = &cmd_functions ; *prev ; prev = &cmd->next ) { + for (prev = &cmd_functions; *prev; prev = &cmd->next) { cmd = *prev; - if ( !Q_stricmp( Cmd_Argv(0), cmd->name ) ) { + if (!Q_stricmp(Cmd_Argv(0), cmd->name)) { // rearrange the links so that the command will be // near the head of the list next time it is used *prev = cmd->next; @@ -719,39 +677,39 @@ void Cmd_ExecuteString( const char *text ) { cmd_functions = cmd; // perform the action - if ( !cmd->function ) { + if (!cmd->function) { // let the cgame or game handle it break; } else { - cmd->function (); + cmd->function(); } return; } } // check cvars - if ( Cvar_Command() ) { + if (Cvar_Command()) { return; } // check client game commands - if ( com_cl_running && com_cl_running->integer && CL_GameCommand() ) { + if (com_cl_running && com_cl_running->integer && CL_GameCommand()) { return; } // check server game commands - if ( com_sv_running && com_sv_running->integer && SV_GameCommand() ) { + if (com_sv_running && com_sv_running->integer && SV_GameCommand()) { return; } // check ui commands - if ( com_cl_running && com_cl_running->integer && UI_GameCommand() ) { + if (com_cl_running && com_cl_running->integer && UI_GameCommand()) { return; } // send it as a server command if we are connected // this will usually result in a chat message - CL_ForwardCommandToServer (); + CL_ForwardCommandToServer(); } /* @@ -759,30 +717,26 @@ void Cmd_ExecuteString( const char *text ) { Cmd_List_f ============ */ -void Cmd_List_f (void) -{ - cmd_function_t *cmd = NULL; - int i, j; - char *match = NULL; +void Cmd_List_f(void) { + cmd_function_t *cmd = NULL; + int i, j; + char *match = NULL; - if ( Cmd_Argc() > 1 ) { - match = Cmd_Argv( 1 ); + if (Cmd_Argc() > 1) { + match = Cmd_Argv(1); } - for ( cmd=cmd_functions, i=0, j=0; - cmd; - cmd=cmd->next, i++ ) - { - if ( !cmd->name || (match && !Com_Filter( match, cmd->name, qfalse )) ) + for (cmd = cmd_functions, i = 0, j = 0; cmd; cmd = cmd->next, i++) { + if (!cmd->name || (match && !Com_Filter(match, cmd->name, qfalse))) continue; - Com_Printf (" %s\n", cmd->name); + Com_Printf(" %s\n", cmd->name); j++; } - Com_Printf ("\n%i total commands\n", i); - if ( i != j ) - Com_Printf( "%i matching commands\n", j ); + Com_Printf("\n%i total commands\n", i); + if (i != j) + Com_Printf("%i matching commands\n", j); } /* @@ -790,9 +744,9 @@ void Cmd_List_f (void) Cmd_CompleteCfgName ================== */ -void Cmd_CompleteCfgName( char *args, int argNum ) { - if( argNum == 2 ) { - Field_CompleteFilename( "", "cfg", qfalse, qtrue ); +void Cmd_CompleteCfgName(char *args, int argNum) { + if (argNum == 2) { + Field_CompleteFilename("", "cfg", qfalse, qtrue); } } @@ -801,14 +755,14 @@ void Cmd_CompleteCfgName( char *args, int argNum ) { Cmd_Init ============ */ -void Cmd_Init (void) { - Cmd_AddCommand ("cmdlist",Cmd_List_f); - Cmd_AddCommand ("exec",Cmd_Exec_f); - Cmd_AddCommand ("execq",Cmd_Exec_f); - Cmd_SetCommandCompletionFunc( "exec", Cmd_CompleteCfgName ); - Cmd_SetCommandCompletionFunc( "execq", Cmd_CompleteCfgName ); - Cmd_AddCommand ("vstr",Cmd_Vstr_f); - Cmd_SetCommandCompletionFunc( "vstr", Cvar_CompleteCvarName ); - Cmd_AddCommand ("echo",Cmd_Echo_f); - Cmd_AddCommand ("wait", Cmd_Wait_f); +void Cmd_Init(void) { + Cmd_AddCommand("cmdlist", Cmd_List_f); + Cmd_AddCommand("exec", Cmd_Exec_f); + Cmd_AddCommand("execq", Cmd_Exec_f); + Cmd_SetCommandCompletionFunc("exec", Cmd_CompleteCfgName); + Cmd_SetCommandCompletionFunc("execq", Cmd_CompleteCfgName); + Cmd_AddCommand("vstr", Cmd_Vstr_f); + Cmd_SetCommandCompletionFunc("vstr", Cvar_CompleteCvarName); + Cmd_AddCommand("echo", Cmd_Echo_f); + Cmd_AddCommand("wait", Cmd_Wait_f); } diff --git a/code/qcommon/common.cpp b/code/qcommon/common.cpp index 41f2da9e55..54376968b6 100644 --- a/code/qcommon/common.cpp +++ b/code/qcommon/common.cpp @@ -27,7 +27,7 @@ along with this program; if not, see . #include "q_shared.h" #include "qcommon.h" #include "qcommon/q_version.h" -#include "sstring.h" // to get Gil's string class, because MS's doesn't compile properly in here +#include "sstring.h" // to get Gil's string class, because MS's doesn't compile properly in here #include "stringed_ingame.h" #include "stv_version.h" #include "../shared/sys/sys_local.h" @@ -40,69 +40,68 @@ along with this program; if not, see . #include "../rd-common/tr_public.h" extern refexport_t re; -static fileHandle_t logfile; -static fileHandle_t speedslog; -static fileHandle_t camerafile; -fileHandle_t com_journalFile; -fileHandle_t com_journalDataFile; // config files are written here - -cvar_t *com_speeds; -cvar_t *com_developer; -cvar_t *com_timescale; -cvar_t *com_fixedtime; -cvar_t *com_sv_running; -cvar_t *com_cl_running; -cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print -cvar_t *com_showtrace; -cvar_t *com_version; -cvar_t *com_buildScript; // for automated data building scripts -cvar_t *com_bootlogo; -cvar_t *cl_paused; -cvar_t *sv_paused; -cvar_t *com_skippingcin; -cvar_t *com_speedslog; // 1 = buffer log, 2 = flush after each print -cvar_t *com_homepath; +static fileHandle_t logfile; +static fileHandle_t speedslog; +static fileHandle_t camerafile; +fileHandle_t com_journalFile; +fileHandle_t com_journalDataFile; // config files are written here + +cvar_t *com_speeds; +cvar_t *com_developer; +cvar_t *com_timescale; +cvar_t *com_fixedtime; +cvar_t *com_sv_running; +cvar_t *com_cl_running; +cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print +cvar_t *com_showtrace; +cvar_t *com_version; +cvar_t *com_buildScript; // for automated data building scripts +cvar_t *com_bootlogo; +cvar_t *cl_paused; +cvar_t *sv_paused; +cvar_t *com_skippingcin; +cvar_t *com_speedslog; // 1 = buffer log, 2 = flush after each print +cvar_t *com_homepath; #ifndef _WIN32 -cvar_t *com_ansiColor = NULL; +cvar_t *com_ansiColor = NULL; #endif -cvar_t *com_busyWait; +cvar_t *com_busyWait; #ifdef G2_PERFORMANCE_ANALYSIS -cvar_t *com_G2Report; +cvar_t *com_G2Report; #endif cvar_t *com_affinity; -cvar_t *com_timestamps; +cvar_t *com_timestamps; // com_speeds times -int time_game; -int time_frontend; // renderer frontend time -int time_backend; // renderer backend time +int time_game; +int time_frontend; // renderer frontend time +int time_backend; // renderer backend time -int timeInTrace; -int timeInPVSCheck; -int numTraces; +int timeInTrace; +int timeInPVSCheck; +int numTraces; -int com_frameTime; -int com_frameNumber = 0; +int com_frameTime; +int com_frameNumber = 0; -qboolean com_errorEntered = qfalse; -qboolean com_fullyInitialized = qfalse; +qboolean com_errorEntered = qfalse; +qboolean com_fullyInitialized = qfalse; -char com_errorMessage[MAXPRINTMSG] = {0}; +char com_errorMessage[MAXPRINTMSG] = {0}; -void Com_WriteConfig_f( void ); -//JLF +void Com_WriteConfig_f(void); +// JLF //============================================================================ -static char *rd_buffer; -static int rd_buffersize; -static void (*rd_flush)( char *buffer ); +static char *rd_buffer; +static int rd_buffersize; +static void (*rd_flush)(char *buffer); -void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) ) -{ +void Com_BeginRedirect(char *buffer, int buffersize, void (*flush)(char *)) { if (!buffer || !buffersize || !flush) return; rd_buffer = buffer; @@ -112,9 +111,8 @@ void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) ) *rd_buffer = 0; } -void Com_EndRedirect (void) -{ - if ( rd_flush ) { +void Com_EndRedirect(void) { + if (rd_flush) { rd_flush(rd_buffer); } @@ -136,37 +134,37 @@ to the apropriate place. A raw string should NEVER be passed as fmt, because of "%f" type crashers. ============= */ -void QDECL Com_Printf( const char *fmt, ... ) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL Com_Printf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; const char *p; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - if ( rd_buffer ) { - if ((strlen (msg) + strlen(rd_buffer)) > (unsigned)(rd_buffersize - 1)) { + if (rd_buffer) { + if ((strlen(msg) + strlen(rd_buffer)) > (unsigned)(rd_buffersize - 1)) { rd_flush(rd_buffer); *rd_buffer = 0; } - Q_strcat (rd_buffer, strlen(rd_buffer), msg); + Q_strcat(rd_buffer, strlen(rd_buffer), msg); return; } - CL_ConsolePrint( msg ); + CL_ConsolePrint(msg); p = msg; while (*p) { - static qboolean newLine = qtrue; - char line[MAXPRINTMSG]; - size_t lineLen; + static qboolean newLine = qtrue; + char line[MAXPRINTMSG]; + size_t lineLen; if (newLine && com_timestamps && com_timestamps->integer) { - time_t t = time( NULL ); - struct tm *tms = localtime( &t ); - Com_sprintf(line, sizeof(line), "%04i-%02i-%02i %02i:%02i:%02i ", - 1900 + tms->tm_year, 1 + tms->tm_mon, tms->tm_mday, tms->tm_hour, tms->tm_min, tms->tm_sec); + time_t t = time(NULL); + struct tm *tms = localtime(&t); + Com_sprintf(line, sizeof(line), "%04i-%02i-%02i %02i:%02i:%02i ", 1900 + tms->tm_year, 1 + tms->tm_mon, tms->tm_mday, tms->tm_hour, tms->tm_min, + tms->tm_sec); lineLen = strlen(line); newLine = qfalse; } else { @@ -183,31 +181,29 @@ void QDECL Com_Printf( const char *fmt, ... ) { } // echo to dedicated console and early console - Sys_Print( line ); - + Sys_Print(line); #ifdef OUTPUT_TO_BUILD_WINDOW OutputDebugString(line); #endif // logfile - if ( com_logfile && com_logfile->integer ) { - if ( !logfile && FS_Initialized() ) { - logfile = FS_FOpenFileWrite( "qconsole.log" ); - if ( com_logfile->integer > 1 ) { + if (com_logfile && com_logfile->integer) { + if (!logfile && FS_Initialized()) { + logfile = FS_FOpenFileWrite("qconsole.log"); + if (com_logfile->integer > 1) { // force it to not buffer so we get valid // data even if we are crashing FS_ForceFlush(logfile); } } - if ( logfile ) { + if (logfile) { FS_Write(line, strlen(line), logfile); } } } } - /* ================ Com_DPrintf @@ -215,57 +211,52 @@ Com_DPrintf A Com_Printf that only shows up if the "developer" cvar is set ================ */ -void QDECL Com_DPrintf( const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL Com_DPrintf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - if ( !com_developer || !com_developer->integer ) { - return; // don't confuse non-developers with techie stuff... + if (!com_developer || !com_developer->integer) { + return; // don't confuse non-developers with techie stuff... } - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Com_Printf ("%s", msg); + Com_Printf("%s", msg); } -void Com_WriteCam ( const char *text ) -{ - static char mapname[MAX_QPATH]; +void Com_WriteCam(const char *text) { + static char mapname[MAX_QPATH]; // camerafile - if ( !camerafile ) - { - extern cvar_t *sv_mapname; + if (!camerafile) { + extern cvar_t *sv_mapname; - //NOTE: always saves in working dir if using one... - Com_sprintf( mapname, MAX_QPATH, "maps/%s_cam.map", sv_mapname->string ); - camerafile = FS_FOpenFileWrite( mapname ); + // NOTE: always saves in working dir if using one... + Com_sprintf(mapname, MAX_QPATH, "maps/%s_cam.map", sv_mapname->string); + camerafile = FS_FOpenFileWrite(mapname); } - if ( camerafile ) - { - FS_Printf( camerafile, "%s", text ); + if (camerafile) { + FS_Printf(camerafile, "%s", text); } - Com_Printf( "%s\n", mapname ); + Com_Printf("%s\n", mapname); } -void Com_FlushCamFile() -{ - if (!camerafile) - { +void Com_FlushCamFile() { + if (!camerafile) { // nothing to flush, right? Com_Printf("No cam file available\n"); return; } FS_ForceFlush(camerafile); - FS_FCloseFile (camerafile); + FS_FCloseFile(camerafile); camerafile = 0; - static char flushedMapname[MAX_QPATH]; - extern cvar_t *sv_mapname; - Com_sprintf( flushedMapname, MAX_QPATH, "maps/%s_cam.map", sv_mapname->string ); + static char flushedMapname[MAX_QPATH]; + extern cvar_t *sv_mapname; + Com_sprintf(flushedMapname, MAX_QPATH, "maps/%s_cam.map", sv_mapname->string); Com_Printf("flushed all cams to %s\n", flushedMapname); } @@ -281,27 +272,27 @@ void SG_Shutdown(); #ifdef JK2_MODE extern void SCR_UnprecacheScreenshot(); #endif -void NORETURN QDECL Com_Error( int code, const char *fmt, ... ) { - va_list argptr; - static int lastErrorTime; - static int errorCount; - int currentTime; - - if ( com_errorEntered ) { - Sys_Error( "recursive error after: %s", com_errorMessage ); +void NORETURN QDECL Com_Error(int code, const char *fmt, ...) { + va_list argptr; + static int lastErrorTime; + static int errorCount; + int currentTime; + + if (com_errorEntered) { + Sys_Error("recursive error after: %s", com_errorMessage); } com_errorEntered = qtrue; // when we are running automated scripts, make sure we // know if anything failed - if ( com_buildScript && com_buildScript->integer ) { + if (com_buildScript && com_buildScript->integer) { code = ERR_FATAL; } // if we are getting a solid stream of ERR_DROP, do an ERR_FATAL currentTime = Sys_Milliseconds(); - if ( currentTime - lastErrorTime < 100 ) { - if ( ++errorCount > 3 ) { + if (currentTime - lastErrorTime < 100) { + if (++errorCount > 3) { code = ERR_FATAL; } } else { @@ -313,29 +304,28 @@ void NORETURN QDECL Com_Error( int code, const char *fmt, ... ) { SCR_UnprecacheScreenshot(); #endif - va_start (argptr,fmt); - Q_vsnprintf (com_errorMessage, sizeof(com_errorMessage), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(com_errorMessage, sizeof(com_errorMessage), fmt, argptr); + va_end(argptr); - if ( code != ERR_DISCONNECT ) { - Cvar_Get("com_errorMessage", "", CVAR_ROM); //give com_errorMessage a default so it won't come back to life after a resetDefaults + if (code != ERR_DISCONNECT) { + Cvar_Get("com_errorMessage", "", CVAR_ROM); // give com_errorMessage a default so it won't come back to life after a resetDefaults Cvar_Set("com_errorMessage", com_errorMessage); } - SG_Shutdown(); // close any file pointers - if ( code == ERR_DISCONNECT || code == ERR_DROP ) { + SG_Shutdown(); // close any file pointers + if (code == ERR_DISCONNECT || code == ERR_DROP) { throw code; } else { - SV_Shutdown (va("Server fatal crashed: %s\n", com_errorMessage)); - CL_Shutdown (); + SV_Shutdown(va("Server fatal crashed: %s\n", com_errorMessage)); + CL_Shutdown(); } - Com_Shutdown (); + Com_Shutdown(); - Sys_Error ("%s", com_errorMessage); + Sys_Error("%s", com_errorMessage); } - /* ============= Com_Quit_f @@ -344,19 +334,17 @@ Both client and server can use this, and it will do the apropriate things. ============= */ -void NORETURN Com_Quit_f( void ) { +void NORETURN Com_Quit_f(void) { // don't try to shutdown if we are in a recursive error - if ( !com_errorEntered ) { - SV_Shutdown ("Server quit\n"); - CL_Shutdown (); - Com_Shutdown (); + if (!com_errorEntered) { + SV_Shutdown("Server quit\n"); + CL_Shutdown(); + Com_Shutdown(); FS_Shutdown(); } - Sys_Quit (); + Sys_Quit(); } - - /* ============================================================================ @@ -374,9 +362,9 @@ quake3 set test blah + map test ============================================================================ */ -#define MAX_CONSOLE_LINES 32 -int com_numConsoleLines; -char *com_consoleLines[MAX_CONSOLE_LINES]; +#define MAX_CONSOLE_LINES 32 +int com_numConsoleLines; +char *com_consoleLines[MAX_CONSOLE_LINES]; /* ================== @@ -385,19 +373,19 @@ Com_ParseCommandLine Break it up into multiple console lines ================== */ -void Com_ParseCommandLine( char *commandLine ) { +void Com_ParseCommandLine(char *commandLine) { int inq = 0; com_consoleLines[0] = commandLine; com_numConsoleLines = 1; - while ( *commandLine ) { + while (*commandLine) { if (*commandLine == '"') { inq = !inq; } // look for a + separating character // if commandLine came from a file, we might have real line seperators - if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) { - if ( com_numConsoleLines == MAX_CONSOLE_LINES ) { + if ((*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r') { + if (com_numConsoleLines == MAX_CONSOLE_LINES) { return; } com_consoleLines[com_numConsoleLines] = commandLine + 1; @@ -408,7 +396,6 @@ void Com_ParseCommandLine( char *commandLine ) { } } - /* =================== Com_SafeMode @@ -417,13 +404,12 @@ Check for "safe" on the command line, which will skip loading of openjk_sp.cfg =================== */ -qboolean Com_SafeMode( void ) { - int i; +qboolean Com_SafeMode(void) { + int i; - for ( i = 0 ; i < com_numConsoleLines ; i++ ) { - Cmd_TokenizeString( com_consoleLines[i] ); - if ( !Q_stricmp( Cmd_Argv(0), "safe" ) - || !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) { + for (i = 0; i < com_numConsoleLines; i++) { + Cmd_TokenizeString(com_consoleLines[i]); + if (!Q_stricmp(Cmd_Argv(0), "safe") || !Q_stricmp(Cmd_Argv(0), "cvar_restart")) { com_consoleLines[i][0] = 0; return qtrue; } @@ -431,7 +417,6 @@ qboolean Com_SafeMode( void ) { return qfalse; } - /* =============== Com_StartupVariable @@ -443,20 +428,19 @@ before the filesystem is started, but all other sets should be after execing the config and default. =============== */ -void Com_StartupVariable( const char *match ) { - char *s; +void Com_StartupVariable(const char *match) { + char *s; - for (int i=0 ; i < com_numConsoleLines ; i++) { - Cmd_TokenizeString( com_consoleLines[i] ); - if ( strcmp( Cmd_Argv(0), "set" ) ) { + for (int i = 0; i < com_numConsoleLines; i++) { + Cmd_TokenizeString(com_consoleLines[i]); + if (strcmp(Cmd_Argv(0), "set")) { continue; } s = Cmd_Argv(1); - if(!match || !strcmp(s, match)) - { - if((unsigned)Cvar_Flags(s) == CVAR_NONEXISTENT) + if (!match || !strcmp(s, match)) { + if ((unsigned)Cvar_Flags(s) == CVAR_NONEXISTENT) Cvar_Get(s, Cmd_ArgsFrom(2), CVAR_USER_CREATED); else Cvar_Set2(s, Cmd_ArgsFrom(2), qfalse); @@ -464,7 +448,6 @@ void Com_StartupVariable( const char *match ) { } } - /* ================= Com_AddStartupCommands @@ -476,59 +459,53 @@ Returns qtrue if any late commands were added, which will keep the demoloop from immediately starting ================= */ -qboolean Com_AddStartupCommands( void ) { - int i; - qboolean added; +qboolean Com_AddStartupCommands(void) { + int i; + qboolean added; added = qfalse; // quote every token, so args with semicolons can work - for (i=0 ; i < com_numConsoleLines ; i++) { - if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) { + for (i = 0; i < com_numConsoleLines; i++) { + if (!com_consoleLines[i] || !com_consoleLines[i][0]) { continue; } // set commands won't override menu startup - if ( Q_stricmpn( com_consoleLines[i], "set", 3 ) ) { + if (Q_stricmpn(com_consoleLines[i], "set", 3)) { added = qtrue; } - Cbuf_AddText( com_consoleLines[i] ); - Cbuf_AddText( "\n" ); + Cbuf_AddText(com_consoleLines[i]); + Cbuf_AddText("\n"); } return added; } - //============================================================================ - -void Info_Print( const char *s ) { - char key[512]; - char value[512]; - char *o; - int l; +void Info_Print(const char *s) { + char key[512]; + char value[512]; + char *o; + int l; if (*s == '\\') s++; - while (*s) - { + while (*s) { o = key; while (*s && *s != '\\') *o++ = *s++; l = o - key; - if (l < 20) - { - memset (o, ' ', 20-l); + if (l < 20) { + memset(o, ' ', 20 - l); key[20] = 0; - } - else + } else *o = 0; - Com_Printf ("%s", key); + Com_Printf("%s", key); - if (!*s) - { - Com_Printf ("MISSING VALUE\n"); + if (!*s) { + Com_Printf("MISSING VALUE\n"); return; } @@ -540,7 +517,7 @@ void Info_Print( const char *s ) { if (*s) s++; - Com_Printf ("%s\n", value); + Com_Printf("%s\n", value); } } @@ -559,8 +536,7 @@ const char *Com_StringContains(const char *str1, const char *str2, int casesensi if (str1[j] != str2[j]) { break; } - } - else { + } else { if (toupper(str1[j]) != toupper(str2[j])) { break; } @@ -583,67 +559,69 @@ int Com_Filter(const char *filter, const char *name, int casesensitive) { const char *ptr; int i, found; - while(*filter) { + while (*filter) { if (*filter == '*') { filter++; for (i = 0; *filter; i++) { - if (*filter == '*' || *filter == '?') break; + if (*filter == '*' || *filter == '?') + break; buf[i] = *filter; filter++; } buf[i] = '\0'; if (strlen(buf)) { ptr = Com_StringContains(name, buf, casesensitive); - if (!ptr) return qfalse; + if (!ptr) + return qfalse; name = ptr + strlen(buf); } - } - else if (*filter == '?') { + } else if (*filter == '?') { filter++; name++; - } - else if (*filter == '[' && *(filter+1) == '[') { + } else if (*filter == '[' && *(filter + 1) == '[') { filter++; - } - else if (*filter == '[') { + } else if (*filter == '[') { filter++; found = qfalse; - while(*filter && !found) { - if (*filter == ']' && *(filter+1) != ']') break; - if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) { + while (*filter && !found) { + if (*filter == ']' && *(filter + 1) != ']') + break; + if (*(filter + 1) == '-' && *(filter + 2) && (*(filter + 2) != ']' || *(filter + 3) == ']')) { if (casesensitive) { - if (*name >= *filter && *name <= *(filter+2)) found = qtrue; - } - else { - if (toupper(*name) >= toupper(*filter) && - toupper(*name) <= toupper(*(filter+2))) found = qtrue; + if (*name >= *filter && *name <= *(filter + 2)) + found = qtrue; + } else { + if (toupper(*name) >= toupper(*filter) && toupper(*name) <= toupper(*(filter + 2))) + found = qtrue; } filter += 3; - } - else { + } else { if (casesensitive) { - if (*filter == *name) found = qtrue; - } - else { - if (toupper(*filter) == toupper(*name)) found = qtrue; + if (*filter == *name) + found = qtrue; + } else { + if (toupper(*filter) == toupper(*name)) + found = qtrue; } filter++; } } - if (!found) return qfalse; - while(*filter) { - if (*filter == ']' && *(filter+1) != ']') break; + if (!found) + return qfalse; + while (*filter) { + if (*filter == ']' && *(filter + 1) != ']') + break; filter++; } filter++; name++; - } - else { + } else { if (casesensitive) { - if (*filter != *name) return qfalse; - } - else { - if (toupper(*filter) != toupper(*name)) return qfalse; + if (*filter != *name) + return qfalse; + } else { + if (toupper(*filter) != toupper(*name)) + return qfalse; } filter++; name++; @@ -657,26 +635,23 @@ int Com_Filter(const char *filter, const char *name, int casesensitive) { Com_FilterPath ============ */ -int Com_FilterPath(const char *filter, const char *name, int casesensitive) -{ +int Com_FilterPath(const char *filter, const char *name, int casesensitive) { int i; char new_filter[MAX_QPATH]; char new_name[MAX_QPATH]; - for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) { - if ( filter[i] == '\\' || filter[i] == ':' ) { + for (i = 0; i < MAX_QPATH - 1 && filter[i]; i++) { + if (filter[i] == '\\' || filter[i] == ':') { new_filter[i] = '/'; - } - else { + } else { new_filter[i] = filter[i]; } } new_filter[i] = '\0'; - for (i = 0; i < MAX_QPATH-1 && name[i]; i++) { - if ( name[i] == '\\' || name[i] == ':' ) { + for (i = 0; i < MAX_QPATH - 1 && name[i]; i++) { + if (name[i] == '\\' || name[i] == ':') { new_name[i] = '/'; - } - else { + } else { new_name[i] = name[i]; } } @@ -684,26 +659,20 @@ int Com_FilterPath(const char *filter, const char *name, int casesensitive) return Com_Filter(new_filter, new_name, casesensitive); } - - /* ================= Com_InitHunkMemory ================= */ -void Com_InitHunkMemory( void ) -{ +void Com_InitHunkMemory(void) { Hunk_Clear(); -// Cmd_AddCommand( "meminfo", Z_Details_f ); + // Cmd_AddCommand( "meminfo", Z_Details_f ); } // I'm leaving this in just in case we ever need to remember where's a good place to hook something like this in. // -void Com_ShutdownHunkMemory(void) -{ -} - +void Com_ShutdownHunkMemory(void) {} /* =================== @@ -712,11 +681,7 @@ Hunk_SetMark The server calls this after the level and game VM have been loaded =================== */ -void Hunk_SetMark( void ) -{ -} - - +void Hunk_SetMark(void) {} /* ================= @@ -725,14 +690,11 @@ Hunk_ClearToMark The client calls this before starting a vid_restart or snd_restart ================= */ -void Hunk_ClearToMark( void ) -{ +void Hunk_ClearToMark(void) { Z_TagFree(TAG_HUNKALLOC); Z_TagFree(TAG_HUNKMISCMODELS); } - - /* ================= Hunk_Clear @@ -740,23 +702,17 @@ Hunk_Clear The server calls this before shutting down or loading a new map ================= */ -void Hunk_Clear( void ) -{ +void Hunk_Clear(void) { Z_TagFree(TAG_HUNKALLOC); Z_TagFree(TAG_HUNKMISCMODELS); -extern void CIN_CloseAllVideos(); + extern void CIN_CloseAllVideos(); CIN_CloseAllVideos(); - if(re.R_ClearStuffToStopGhoul2CrashingThings) + if (re.R_ClearStuffToStopGhoul2CrashingThings) re.R_ClearStuffToStopGhoul2CrashingThings(); } - - - - - /* =================================================================== @@ -767,20 +723,20 @@ journaled file =================================================================== */ -#define MAX_PUSHED_EVENTS 64 -int com_pushedEventsHead, com_pushedEventsTail; -sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS]; +#define MAX_PUSHED_EVENTS 64 +int com_pushedEventsHead, com_pushedEventsTail; +sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS]; /* ================= Com_GetRealEvent ================= */ -sysEvent_t Com_GetRealEvent( void ) { - sysEvent_t ev; +sysEvent_t Com_GetRealEvent(void) { + sysEvent_t ev; // get an event from the system - ev = Sys_GetEvent(); + ev = Sys_GetEvent(); return ev; } @@ -790,22 +746,22 @@ sysEvent_t Com_GetRealEvent( void ) { Com_PushEvent ================= */ -void Com_PushEvent( sysEvent_t *event ) { - sysEvent_t *ev; - static int printedWarning; +void Com_PushEvent(sysEvent_t *event) { + sysEvent_t *ev; + static int printedWarning; - ev = &com_pushedEvents[ com_pushedEventsHead & (MAX_PUSHED_EVENTS-1) ]; + ev = &com_pushedEvents[com_pushedEventsHead & (MAX_PUSHED_EVENTS - 1)]; - if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) { + if (com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS) { // don't print the warning constantly, or it can give time for more... - if ( !printedWarning ) { + if (!printedWarning) { printedWarning = qtrue; - Com_Printf( "WARNING: Com_PushEvent overflow\n" ); + Com_Printf("WARNING: Com_PushEvent overflow\n"); } - if ( ev->evPtr ) { - Z_Free( ev->evPtr ); + if (ev->evPtr) { + Z_Free(ev->evPtr); } com_pushedEventsTail++; } else { @@ -821,10 +777,10 @@ void Com_PushEvent( sysEvent_t *event ) { Com_GetEvent ================= */ -sysEvent_t Com_GetEvent( void ) { - if ( com_pushedEventsHead > com_pushedEventsTail ) { +sysEvent_t Com_GetEvent(void) { + if (com_pushedEventsHead > com_pushedEventsTail) { com_pushedEventsTail++; - return com_pushedEvents[ (com_pushedEventsTail-1) & (MAX_PUSHED_EVENTS-1) ]; + return com_pushedEvents[(com_pushedEventsTail - 1) & (MAX_PUSHED_EVENTS - 1)]; } return Com_GetRealEvent(); } @@ -834,22 +790,22 @@ sysEvent_t Com_GetEvent( void ) { Com_RunAndTimeServerPacket ================= */ -void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) { - int t1, t2, msec; +void Com_RunAndTimeServerPacket(netadr_t *evFrom, msg_t *buf) { + int t1, t2, msec; t1 = 0; - if ( com_speeds->integer ) { - t1 = Sys_Milliseconds (); + if (com_speeds->integer) { + t1 = Sys_Milliseconds(); } - SV_PacketEvent( *evFrom, buf ); + SV_PacketEvent(*evFrom, buf); - if ( com_speeds->integer ) { - t2 = Sys_Milliseconds (); + if (com_speeds->integer) { + t2 = Sys_Milliseconds(); msec = t2 - t1; - if ( com_speeds->integer == 3 ) { - Com_Printf( "SV_PacketEvent time: %i\n", msec ); + if (com_speeds->integer == 3) { + Com_Printf("SV_PacketEvent time: %i\n", msec); } } } @@ -861,62 +817,61 @@ Com_EventLoop Returns last event time ================= */ -int Com_EventLoop( void ) { - sysEvent_t ev; - netadr_t evFrom; - byte bufData[MAX_MSGLEN]; - msg_t buf; +int Com_EventLoop(void) { + sysEvent_t ev; + netadr_t evFrom; + byte bufData[MAX_MSGLEN]; + msg_t buf; - MSG_Init( &buf, bufData, sizeof( bufData ) ); + MSG_Init(&buf, bufData, sizeof(bufData)); - while ( 1 ) { + while (1) { ev = Com_GetEvent(); // if no more events are available - if ( ev.evType == SE_NONE ) { + if (ev.evType == SE_NONE) { // manually send packet events for the loopback channel - while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) { - CL_PacketEvent( evFrom, &buf ); + while (NET_GetLoopPacket(NS_CLIENT, &evFrom, &buf)) { + CL_PacketEvent(evFrom, &buf); } - while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) { + while (NET_GetLoopPacket(NS_SERVER, &evFrom, &buf)) { // if the server just shut down, flush the events - if ( com_sv_running->integer ) { - Com_RunAndTimeServerPacket( &evFrom, &buf ); + if (com_sv_running->integer) { + Com_RunAndTimeServerPacket(&evFrom, &buf); } } return ev.evTime; } - - switch ( ev.evType ) { + switch (ev.evType) { default: - Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType ); + Com_Error(ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType); + break; + case SE_NONE: break; - case SE_NONE: - break; case SE_KEY: - CL_KeyEvent( ev.evValue, (qboolean)ev.evValue2, ev.evTime ); + CL_KeyEvent(ev.evValue, (qboolean)ev.evValue2, ev.evTime); break; case SE_CHAR: - CL_CharEvent( ev.evValue ); + CL_CharEvent(ev.evValue); break; case SE_MOUSE: - CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime ); + CL_MouseEvent(ev.evValue, ev.evValue2, ev.evTime); break; case SE_JOYSTICK_AXIS: - CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime ); + CL_JoystickEvent(ev.evValue, ev.evValue2, ev.evTime); break; case SE_CONSOLE: - Cbuf_AddText( (char *)ev.evPtr ); - Cbuf_AddText( "\n" ); + Cbuf_AddText((char *)ev.evPtr); + Cbuf_AddText("\n"); break; } // free any block data - if ( ev.evPtr ) { - Z_Free( ev.evPtr ); + if (ev.evPtr) { + Z_Free(ev.evPtr); } } } @@ -928,17 +883,17 @@ Com_Milliseconds Can be used for profiling, but will be journaled accurately ================ */ -int Com_Milliseconds (void) { - sysEvent_t ev; +int Com_Milliseconds(void) { + sysEvent_t ev; // get events and push them until we get a null event with the current time do { ev = Com_GetRealEvent(); - if ( ev.evType != SE_NONE ) { - Com_PushEvent( &ev ); + if (ev.evType != SE_NONE) { + Com_PushEvent(&ev); } - } while ( ev.evType != SE_NONE ); + } while (ev.evType != SE_NONE); return ev.evTime; } @@ -953,15 +908,14 @@ Just throw a fatal error to test error shutdown procedures ============= */ -static void NORETURN Com_Error_f (void) { - if ( Cmd_Argc() > 1 ) { - Com_Error( ERR_DROP, "Testing drop error" ); +static void NORETURN Com_Error_f(void) { + if (Cmd_Argc() > 1) { + Com_Error(ERR_DROP, "Testing drop error"); } else { - Com_Error( ERR_FATAL, "Testing fatal error" ); + Com_Error(ERR_FATAL, "Testing fatal error"); } } - /* ============= Com_Freeze_f @@ -970,21 +924,21 @@ Just freeze in place for a given number of seconds to test error recovery ============= */ -static void Com_Freeze_f (void) { - float s; - int start, now; +static void Com_Freeze_f(void) { + float s; + int start, now; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "freeze \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("freeze \n"); return; } - s = atof( Cmd_Argv(1) ); + s = atof(Cmd_Argv(1)); start = Com_Milliseconds(); - while ( 1 ) { + while (1) { now = Com_Milliseconds(); - if ( ( now - start ) * 0.001 > s ) { + if ((now - start) * 0.001 > s) { break; } } @@ -997,8 +951,8 @@ Com_Crash_f A way to force a bus error for development reasons ================= */ -static void NORETURN Com_Crash_f( void ) { - * ( volatile int * ) 0 = 0x12345678; +static void NORETURN Com_Crash_f(void) { + *(volatile int *)0 = 0x12345678; /* that should crash already, but to reassure the compiler: */ abort(); } @@ -1009,13 +963,11 @@ Com_ExecuteCfg ================== */ -void Com_ExecuteCfg(void) -{ +void Com_ExecuteCfg(void) { Cbuf_ExecuteText(EXEC_NOW, "exec default.cfg\n"); Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing - if(!Com_SafeMode()) - { + if (!Com_SafeMode()) { // skip the q3config.cfg and autoexec.cfg if "safe" is on the command line Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_NAME "\n"); Cbuf_Execute(); @@ -1030,18 +982,16 @@ Com_ErrorString Error string for the given error code (from Com_Error). ================= */ -static const char *Com_ErrorString ( int code ) -{ - switch ( code ) - { - case ERR_DISCONNECT: - return "DISCONNECTED"; +static const char *Com_ErrorString(int code) { + switch (code) { + case ERR_DISCONNECT: + return "DISCONNECTED"; - case ERR_DROP: - return "DROPPED"; + case ERR_DROP: + return "DROPPED"; - default: - return "UNKNOWN"; + default: + return "UNKNOWN"; } } @@ -1051,24 +1001,24 @@ Com_CatchError Handles freeing up of resources when Com_Error is called. ================= */ -void SG_WipeSavegame(const char *name); // pretty sucky, but that's how SoF did it... -static void Com_CatchError ( int code ) -{ - if ( code == ERR_DISCONNECT ) { - SV_Shutdown( "Server disconnected" ); - CL_Disconnect( ); - CL_FlushMemory( ); +void SG_WipeSavegame(const char *name); // pretty sucky, but that's how SoF did it... +static void Com_CatchError(int code) { + if (code == ERR_DISCONNECT) { + SV_Shutdown("Server disconnected"); + CL_Disconnect(); + CL_FlushMemory(); com_errorEntered = qfalse; - } else if ( code == ERR_DROP ) { + } else if (code == ERR_DROP) { // If loading/saving caused the crash/error - delete the temp file - SG_WipeSavegame("current"); // delete file - - Com_Printf ("********************\n" - "ERROR: %s\n" - "********************\n", com_errorMessage); - SV_Shutdown (va("Server crashed: %s\n", com_errorMessage)); - CL_Disconnect( ); - CL_FlushMemory( ); + SG_WipeSavegame("current"); // delete file + + Com_Printf("********************\n" + "ERROR: %s\n" + "********************\n", + com_errorMessage); + SV_Shutdown(va("Server crashed: %s\n", com_errorMessage)); + CL_Disconnect(); + CL_FlushMemory(); com_errorEntered = qfalse; } } @@ -1078,40 +1028,40 @@ static void Com_CatchError ( int code ) Com_Init ================= */ -void Com_Init( char *commandLine ) { - char *s; +void Com_Init(char *commandLine) { + char *s; - Com_Printf( "%s %s %s\n", Q3_VERSION, PLATFORM_STRING, SOURCE_DATE ); + Com_Printf("%s %s %s\n", Q3_VERSION, PLATFORM_STRING, SOURCE_DATE); try { Com_InitZoneMemory(); - Cvar_Init (); + Cvar_Init(); // prepare enough of the subsystems to handle // cvar and command buffer management - Com_ParseCommandLine( commandLine ); + Com_ParseCommandLine(commandLine); - //Swap_Init (); - Cbuf_Init (); + // Swap_Init (); + Cbuf_Init(); Com_InitZoneMemoryVars(); - Cmd_Init (); + Cmd_Init(); // override anything from the config files with command line args - Com_StartupVariable( NULL ); + Com_StartupVariable(NULL); // done early so bind command exists CL_InitKeyCommands(); com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT); - FS_InitFilesystem (); //uses z_malloc - //re.R_InitWorldEffects(); // this doesn't do much but I want to be sure certain variables are intialized. + FS_InitFilesystem(); // uses z_malloc + // re.R_InitWorldEffects(); // this doesn't do much but I want to be sure certain variables are intialized. Com_ExecuteCfg(); // override anything from the config files with command line args - Com_StartupVariable( NULL ); + Com_StartupVariable(NULL); // allocate the stack based hunk allocator Com_InitHunkMemory(); @@ -1123,59 +1073,59 @@ void Com_Init( char *commandLine ) { // // init commands and vars // - Cmd_AddCommand ("quit", Com_Quit_f); - Cmd_AddCommand ("writeconfig", Com_WriteConfig_f ); + Cmd_AddCommand("quit", Com_Quit_f); + Cmd_AddCommand("writeconfig", Com_WriteConfig_f); - com_developer = Cvar_Get ("developer", "0", CVAR_TEMP ); - com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP ); - com_speedslog = Cvar_Get ("speedslog", "0", CVAR_TEMP ); + com_developer = Cvar_Get("developer", "0", CVAR_TEMP); + com_logfile = Cvar_Get("logfile", "0", CVAR_TEMP); + com_speedslog = Cvar_Get("speedslog", "0", CVAR_TEMP); - com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT ); - com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT); - com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT); - com_speeds = Cvar_Get ("com_speeds", "0", 0); + com_timescale = Cvar_Get("timescale", "1", CVAR_CHEAT); + com_fixedtime = Cvar_Get("fixedtime", "0", CVAR_CHEAT); + com_showtrace = Cvar_Get("com_showtrace", "0", CVAR_CHEAT); + com_speeds = Cvar_Get("com_speeds", "0", 0); #ifdef G2_PERFORMANCE_ANALYSIS com_G2Report = Cvar_Get("com_G2Report", "0", 0); #endif - cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM); - sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM); - com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM); - com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM); - com_skippingcin = Cvar_Get ("skippingCinematic", "0", CVAR_ROM); - com_buildScript = Cvar_Get( "com_buildScript", "0", 0 ); + cl_paused = Cvar_Get("cl_paused", "0", CVAR_ROM); + sv_paused = Cvar_Get("sv_paused", "0", CVAR_ROM); + com_sv_running = Cvar_Get("sv_running", "0", CVAR_ROM); + com_cl_running = Cvar_Get("cl_running", "0", CVAR_ROM); + com_skippingcin = Cvar_Get("skippingCinematic", "0", CVAR_ROM); + com_buildScript = Cvar_Get("com_buildScript", "0", 0); - com_affinity = Cvar_Get( "com_affinity", "0", CVAR_ARCHIVE_ND ); - com_busyWait = Cvar_Get( "com_busyWait", "0", CVAR_ARCHIVE_ND ); + com_affinity = Cvar_Get("com_affinity", "0", CVAR_ARCHIVE_ND); + com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE_ND); - com_bootlogo = Cvar_Get( "com_bootlogo", "1", CVAR_ARCHIVE_ND ); + com_bootlogo = Cvar_Get("com_bootlogo", "1", CVAR_ARCHIVE_ND); - com_timestamps = Cvar_Get( "com_timestamps", "1", CVAR_ARCHIVE_ND ); + com_timestamps = Cvar_Get("com_timestamps", "1", CVAR_ARCHIVE_ND); - if ( com_developer && com_developer->integer ) { - Cmd_AddCommand ("error", Com_Error_f); - Cmd_AddCommand ("crash", Com_Crash_f ); - Cmd_AddCommand ("freeze", Com_Freeze_f); + if (com_developer && com_developer->integer) { + Cmd_AddCommand("error", Com_Error_f); + Cmd_AddCommand("crash", Com_Crash_f); + Cmd_AddCommand("freeze", Com_Freeze_f); } - s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, SOURCE_DATE ); - com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO ); + s = va("%s %s %s", Q3_VERSION, PLATFORM_STRING, SOURCE_DATE); + com_version = Cvar_Get("version", s, CVAR_ROM | CVAR_SERVERINFO); #ifdef JK2_MODE JK2SP_Init(); Com_Printf("Running Jedi Outcast Mode\n"); #else - SE_Init(); // Initialize StringEd + SE_Init(); // Initialize StringEd Com_Printf("Running Jedi Academy Mode\n"); #endif - Sys_Init(); // this also detects CPU type, so I can now do this CPU check below... + Sys_Init(); // this also detects CPU type, so I can now do this CPU check below... Sys_SetProcessorAffinity(); - Netchan_Init( Com_Milliseconds() & 0xffff ); // pick a port value that should be nice and random -// VM_Init(); + Netchan_Init(Com_Milliseconds() & 0xffff); // pick a port value that should be nice and random + // VM_Init(); SV_Init(); CL_Init(); @@ -1186,18 +1136,17 @@ void Com_Init( char *commandLine ) { com_frameTime = Com_Milliseconds(); // add + commands from command line - if ( !Com_AddStartupCommands() ) { + if (!Com_AddStartupCommands()) { // if the user didn't give any commands, run default action - if ( com_bootlogo->integer ) - { - Cbuf_AddText ("cinematic openinglogos\n"); + if (com_bootlogo->integer) { + Cbuf_AddText("cinematic openinglogos\n"); } } com_fullyInitialized = qtrue; - Com_Printf ("--- Common Initialization Complete ---\n"); + Com_Printf("--- Common Initialization Complete ---\n"); -//HACKERY FOR THE DEUTSCH - //if ( (Cvar_VariableIntegerValue("ui_iscensored") == 1) //if this was on before, set it again so it gets its flags + // HACKERY FOR THE DEUTSCH + // if ( (Cvar_VariableIntegerValue("ui_iscensored") == 1) //if this was on before, set it again so it gets its flags // ) //{ // Cvar_Get( "ui_iscensored", "1", CVAR_ARCHIVE|CVAR_ROM|CVAR_INIT|CVAR_CHEAT|CVAR_NORESTART); @@ -1205,33 +1154,30 @@ void Com_Init( char *commandLine ) { // // NOTE : I also create this in UI_Init() // Cvar_Get( "g_dismemberment", "0", CVAR_ARCHIVE|CVAR_ROM|CVAR_INIT|CVAR_CHEAT); // Cvar_Set( "g_dismemberment", "0"); //just in case it was archived - //} - } - catch ( int code ) - { - Com_CatchError (code); - Sys_Error ("Error during initialization %s", Com_ErrorString (code)); + // } + } catch (int code) { + Com_CatchError(code); + Sys_Error("Error during initialization %s", Com_ErrorString(code)); } } //================================================================== -void Com_WriteConfigToFile( const char *filename ) { - fileHandle_t f; +void Com_WriteConfigToFile(const char *filename) { + fileHandle_t f; - f = FS_FOpenFileWrite( filename ); - if ( !f ) { - Com_Printf ("Couldn't write %s.\n", filename ); + f = FS_FOpenFileWrite(filename); + if (!f) { + Com_Printf("Couldn't write %s.\n", filename); return; } - FS_Printf (f, "// generated by OpenJK SP, do not modify\n"); - Key_WriteBindings (f); - Cvar_WriteVariables (f); - FS_FCloseFile( f ); + FS_Printf(f, "// generated by OpenJK SP, do not modify\n"); + Key_WriteBindings(f); + Cvar_WriteVariables(f); + FS_FCloseFile(f); } - /* =============== Com_WriteConfiguration @@ -1239,22 +1185,21 @@ Com_WriteConfiguration Writes key bindings and archived cvars to config file if modified =============== */ -void Com_WriteConfiguration( void ) { +void Com_WriteConfiguration(void) { // if we are quiting without fully initializing, make sure // we don't write out anything - if ( !com_fullyInitialized ) { + if (!com_fullyInitialized) { return; } - if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) { + if (!(cvar_modifiedFlags & CVAR_ARCHIVE)) { return; } cvar_modifiedFlags &= ~CVAR_ARCHIVE; - Com_WriteConfigToFile( Q3CONFIG_NAME ); + Com_WriteConfigToFile(Q3CONFIG_NAME); } - /* =============== Com_WriteConfig_f @@ -1262,31 +1207,29 @@ Com_WriteConfig_f Write the config file to a specific name =============== */ -void Com_WriteConfig_f( void ) { - char filename[MAX_QPATH]; +void Com_WriteConfig_f(void) { + char filename[MAX_QPATH]; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "Usage: writeconfig \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: writeconfig \n"); return; } - Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".cfg"); - if(!COM_CompareExtension(filename, ".cfg")) - { - Com_Printf( "Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n" ); + if (!COM_CompareExtension(filename, ".cfg")) { + Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n"); return; } - if(!FS_FilenameCompare(filename, "mpdefault.cfg") || !FS_FilenameCompare(filename, "default.cfg")) - { - Com_Printf( S_COLOR_YELLOW "Com_WriteConfig_f: The filename \"%s\" is reserved! Please choose another name.\n", filename ); + if (!FS_FilenameCompare(filename, "mpdefault.cfg") || !FS_FilenameCompare(filename, "default.cfg")) { + Com_Printf(S_COLOR_YELLOW "Com_WriteConfig_f: The filename \"%s\" is reserved! Please choose another name.\n", filename); return; } - Com_Printf( "Writing %s.\n", filename ); - Com_WriteConfigToFile( filename ); + Com_Printf("Writing %s.\n", filename); + Com_WriteConfigToFile(filename); } /* @@ -1295,36 +1238,30 @@ Com_ModifyMsec ================ */ +int Com_ModifyMsec(int msec, float &fraction) { + int clampTime; -int Com_ModifyMsec( int msec, float &fraction ) -{ - int clampTime; - - fraction=0.0f; + fraction = 0.0f; // // modify time for debugging values // - if ( com_fixedtime->integer ) - { + if (com_fixedtime->integer) { msec = com_fixedtime->integer; - } - else if ( com_timescale->value ) - { - fraction=(float)msec; - fraction*=com_timescale->value; - msec=(int)floor(fraction); - fraction-=(float)msec; + } else if (com_timescale->value) { + fraction = (float)msec; + fraction *= com_timescale->value; + msec = (int)floor(fraction); + fraction -= (float)msec; } // don't let it scale below 1 msec - if ( msec < 1 ) - { + if (msec < 1) { msec = 1; - fraction=0.0f; + fraction = 0.0f; } - if ( com_skippingcin->integer ) { + if (com_skippingcin->integer) { // we're skipping ahead so let it go a bit faster clampTime = 500; } else { @@ -1334,9 +1271,9 @@ int Com_ModifyMsec( int msec, float &fraction ) clampTime = 200; } - if ( msec > clampTime ) { + if (msec > clampTime) { msec = clampTime; - fraction=0.0f; + fraction = 0.0f; } return msec; @@ -1348,13 +1285,12 @@ Com_TimeVal ================= */ -int Com_TimeVal(int minMsec) -{ +int Com_TimeVal(int minMsec) { int timeVal; timeVal = Sys_Milliseconds() - com_frameTime; - if(timeVal >= minMsec) + if (timeVal >= minMsec) timeVal = 0; else timeVal = minMsec - timeVal; @@ -1370,10 +1306,9 @@ Com_Frame static vec3_t corg; static vec3_t cangles; static bool bComma; -void Com_SetOrgAngles(vec3_t org,vec3_t angles) -{ - VectorCopy(org,corg); - VectorCopy(angles,cangles); +void Com_SetOrgAngles(vec3_t org, vec3_t angles) { + VectorCopy(org, corg); + VectorCopy(angles, cangles); } #ifdef G2_PERFORMANCE_ANALYSIS @@ -1381,13 +1316,12 @@ void G2Time_ResetTimers(void); void G2Time_ReportTimers(void); #endif -void Com_Frame( void ) { - try - { - int timeBeforeFirstEvents = 0, timeBeforeServer = 0, timeBeforeEvents = 0, timeBeforeClient = 0, timeAfter = 0; - int msec, minMsec; - int timeVal; - static int lastTime = 0, bias = 0; +void Com_Frame(void) { + try { + int timeBeforeFirstEvents = 0, timeBeforeServer = 0, timeBeforeEvents = 0, timeBeforeClient = 0, timeAfter = 0; + int msec, minMsec; + int timeVal; + static int lastTime = 0, bias = 0; // write config file if anything changed Com_WriteConfiguration(); @@ -1395,16 +1329,16 @@ void Com_Frame( void ) { // // main event loop // - if ( com_speeds->integer ) { - timeBeforeFirstEvents = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeFirstEvents = Sys_Milliseconds(); } // Figure out how much time we have - if(com_minimized->integer && com_maxfpsMinimized->integer > 0) + if (com_minimized->integer && com_maxfpsMinimized->integer > 0) minMsec = 1000 / com_maxfpsMinimized->integer; - else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0) + else if (com_unfocused->integer && com_maxfpsUnfocused->integer > 0) minMsec = 1000 / com_maxfpsUnfocused->integer; - else if(com_maxfps->integer > 0) + else if (com_maxfps->integer > 0) minMsec = 1000 / com_maxfps->integer; else minMsec = 1; @@ -1422,11 +1356,11 @@ void Com_Frame( void ) { timeVal = Com_TimeVal(minMsec); do { // Busy sleep the last millisecond for better timeout precision - if(com_busyWait->integer || timeVal < 1) + if (com_busyWait->integer || timeVal < 1) Sys_Sleep(0); else Sys_Sleep(timeVal - 1); - } while( (timeVal = Com_TimeVal(minMsec)) != 0 ); + } while ((timeVal = Com_TimeVal(minMsec)) != 0); IN_Frame(); lastTime = com_frameTime; @@ -1434,60 +1368,56 @@ void Com_Frame( void ) { msec = com_frameTime - lastTime; - Cbuf_Execute (); + Cbuf_Execute(); // mess with msec if needed - float fractionMsec=0.0f; - msec = Com_ModifyMsec( msec, fractionMsec); + float fractionMsec = 0.0f; + msec = Com_ModifyMsec(msec, fractionMsec); // // server side // - if ( com_speeds->integer ) { - timeBeforeServer = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeServer = Sys_Milliseconds(); } - SV_Frame (msec, fractionMsec); - + SV_Frame(msec, fractionMsec); // // client system // - - // if ( !com_dedicated->integer ) + // if ( !com_dedicated->integer ) { // // run event loop a second time to get server to client packets // without a frame of latency // - if ( com_speeds->integer ) { - timeBeforeEvents = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeEvents = Sys_Milliseconds(); } Com_EventLoop(); - Cbuf_Execute (); - + Cbuf_Execute(); // // client side // - if ( com_speeds->integer ) { - timeBeforeClient = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeClient = Sys_Milliseconds(); } - CL_Frame (msec, fractionMsec); + CL_Frame(msec, fractionMsec); - if ( com_speeds->integer ) { - timeAfter = Sys_Milliseconds (); + if (com_speeds->integer) { + timeAfter = Sys_Milliseconds(); } } - // // report timing information // - if ( com_speeds->integer ) { - int all, sv, ev, cl; + if (com_speeds->integer) { + int all, sv, ev, cl; all = timeAfter - timeBeforeServer; sv = timeBeforeEvents - timeBeforeServer; @@ -1496,42 +1426,35 @@ void Com_Frame( void ) { sv -= time_game; cl -= time_frontend + time_backend; - Com_Printf("fr:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i tr:%3i pvs:%3i rf:%3i bk:%3i\n", - com_frameNumber, all, sv, ev, cl, time_game, timeInTrace, timeInPVSCheck, time_frontend, time_backend); + Com_Printf("fr:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i tr:%3i pvs:%3i rf:%3i bk:%3i\n", com_frameNumber, all, sv, ev, cl, time_game, timeInTrace, + timeInPVSCheck, time_frontend, time_backend); // speedslog - if ( com_speedslog && com_speedslog->integer ) - { - if(!speedslog) - { + if (com_speedslog && com_speedslog->integer) { + if (!speedslog) { speedslog = FS_FOpenFileWrite("speeds.log"); FS_Write("data={\n", strlen("data={\n"), speedslog); - bComma=false; - if ( com_speedslog->integer > 1 ) - { + bComma = false; + if (com_speedslog->integer > 1) { // force it to not buffer so we get valid // data even if we are crashing FS_ForceFlush(logfile); } } - if (speedslog) - { - char msg[MAXPRINTMSG]; + if (speedslog) { + char msg[MAXPRINTMSG]; - if(bComma) - { + if (bComma) { FS_Write(",\n", strlen(",\n"), speedslog); - bComma=false; + bComma = false; } FS_Write("{", strlen("{"), speedslog); - Com_sprintf(msg,sizeof(msg), - "%8.4f,%8.4f,%8.4f,%8.4f,%8.4f,%8.4f,",corg[0],corg[1],corg[2],cangles[0],cangles[1],cangles[2]); + Com_sprintf(msg, sizeof(msg), "%8.4f,%8.4f,%8.4f,%8.4f,%8.4f,%8.4f,", corg[0], corg[1], corg[2], cangles[0], cangles[1], cangles[2]); FS_Write(msg, strlen(msg), speedslog); - Com_sprintf(msg,sizeof(msg), - "%i,%3i,%3i,%3i,%3i,%3i,%3i,%3i,%3i,%3i}", - com_frameNumber, all, sv, ev, cl, time_game, timeInTrace, timeInPVSCheck, time_frontend, time_backend); + Com_sprintf(msg, sizeof(msg), "%i,%3i,%3i,%3i,%3i,%3i,%3i,%3i,%3i,%3i}", com_frameNumber, all, sv, ev, cl, time_game, timeInTrace, + timeInPVSCheck, time_frontend, time_backend); FS_Write(msg, strlen(msg), speedslog); - bComma=true; + bComma = true; } } @@ -1541,42 +1464,36 @@ void Com_Frame( void ) { // // trace optimization tracking // - if ( com_showtrace->integer ) { - extern int c_traces, c_brush_traces, c_patch_traces; - extern int c_pointcontents; + if (com_showtrace->integer) { + extern int c_traces, c_brush_traces, c_patch_traces; + extern int c_pointcontents; /* - Com_Printf( "%4i non-sv_traces, %4i sv_traces, %4i ms, ave %4.2f ms\n", c_traces - numTraces, numTraces, timeInTrace, (float)timeInTrace/(float)numTraces ); - timeInTrace = numTraces = 0; - c_traces = 0; + Com_Printf( "%4i non-sv_traces, %4i sv_traces, %4i ms, ave %4.2f ms\n", c_traces - numTraces, numTraces, timeInTrace, + (float)timeInTrace/(float)numTraces ); timeInTrace = numTraces = 0; c_traces = 0; */ - Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces, - c_brush_traces, c_patch_traces, c_pointcontents); + Com_Printf("%4i traces (%ib %ip) %4i points\n", c_traces, c_brush_traces, c_patch_traces, c_pointcontents); c_traces = 0; c_brush_traces = 0; c_patch_traces = 0; c_pointcontents = 0; } - if ( com_affinity->modified ) - { + if (com_affinity->modified) { com_affinity->modified = qfalse; Sys_SetProcessorAffinity(); } com_frameNumber++; - } - catch ( int code ) - { - Com_CatchError (code); - Com_Printf ("%s\n", Com_ErrorString (code)); + } catch (int code) { + Com_CatchError(code); + Com_Printf("%s\n", Com_ErrorString(code)); return; } #ifdef G2_PERFORMANCE_ANALYSIS - if (com_G2Report && com_G2Report->integer) - { + if (com_G2Report && com_G2Report->integer) { re.G2Time_ReportTimers(); } @@ -1589,34 +1506,34 @@ void Com_Frame( void ) { Com_Shutdown ================= */ -void Com_Shutdown (void) { +void Com_Shutdown(void) { CM_ClearMap(); if (logfile) { - FS_FCloseFile (logfile); + FS_FCloseFile(logfile); logfile = 0; } if (speedslog) { FS_Write("\n};", strlen("\n};"), speedslog); - FS_FCloseFile (speedslog); + FS_FCloseFile(speedslog); speedslog = 0; } if (camerafile) { - FS_FCloseFile (camerafile); + FS_FCloseFile(camerafile); camerafile = 0; } - if ( com_journalFile ) { - FS_FCloseFile( com_journalFile ); + if (com_journalFile) { + FS_FCloseFile(com_journalFile); com_journalFile = 0; } #ifdef JK2_MODE JK2SP_Shutdown(); #else - SE_ShutDown();//close the string packages + SE_ShutDown(); // close the string packages #endif extern void Netchan_Shutdown(); @@ -1628,7 +1545,7 @@ void Com_Shutdown (void) { Field_Clear ================== */ -void Field_Clear( field_t *edit ) { +void Field_Clear(field_t *edit) { memset(edit->buffer, 0, MAX_EDIT_LINE); edit->cursor = 0; edit->scroll = 0; @@ -1644,7 +1561,7 @@ CONSOLE LINE EDITING static const char *completionString; static char shortestMatch[MAX_TOKEN_CHARS]; -static int matchCount; +static int matchCount; // field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance) static field_t *completionField; @@ -1654,27 +1571,26 @@ FindMatches =============== */ -static void FindMatches( const char *s ) { - int i; +static void FindMatches(const char *s) { + int i; - if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) { + if (Q_stricmpn(s, completionString, strlen(completionString))) { return; } matchCount++; - if ( matchCount == 1 ) { - Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) ); + if (matchCount == 1) { + Q_strncpyz(shortestMatch, s, sizeof(shortestMatch)); return; } // cut shortestMatch to the amount common with s - for ( i = 0 ; s[i] ; i++ ) { - if ( tolower(shortestMatch[i]) != tolower(s[i]) ) { + for (i = 0; s[i]; i++) { + if (tolower(shortestMatch[i]) != tolower(s[i])) { shortestMatch[i] = 0; break; } } - if (!s[i]) - { + if (!s[i]) { shortestMatch[i] = 0; } } @@ -1685,9 +1601,9 @@ PrintMatches =============== */ -static void PrintMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) { - Com_Printf( S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s\n", s ); +static void PrintMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, strlen(shortestMatch))) { + Com_Printf(S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s\n", s); } } @@ -1712,9 +1628,9 @@ PrintKeyMatches =============== */ -static void PrintKeyMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) { - Com_Printf( S_COLOR_GREY "Key " S_COLOR_WHITE "%s\n", s ); +static void PrintKeyMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, strlen(shortestMatch))) { + Com_Printf(S_COLOR_GREY "Key " S_COLOR_WHITE "%s\n", s); } } @@ -1724,9 +1640,9 @@ PrintFileMatches =============== */ -static void PrintFileMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) { - Com_Printf( S_COLOR_GREY "File " S_COLOR_WHITE "%s\n", s ); +static void PrintFileMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, strlen(shortestMatch))) { + Com_Printf(S_COLOR_GREY "File " S_COLOR_WHITE "%s\n", s); } } @@ -1736,12 +1652,12 @@ PrintCvarMatches =============== */ -static void PrintCvarMatches( const char *s ) { +static void PrintCvarMatches(const char *s) { char value[TRUNCATE_LENGTH] = {0}; - if ( !Q_stricmpn( s, shortestMatch, (int)strlen( shortestMatch ) ) ) { - Com_TruncateLongString( value, Cvar_VariableString( s ) ); - Com_Printf( S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", s, value ); + if (!Q_stricmpn(s, shortestMatch, (int)strlen(shortestMatch))) { + Com_TruncateLongString(value, Cvar_VariableString(s)); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", s, value); } } @@ -1750,10 +1666,10 @@ static void PrintCvarMatches( const char *s ) { Field_FindFirstSeparator =============== */ -static char *Field_FindFirstSeparator( char *s ) { - for ( size_t i=0; ibuffer ) - strlen( completionString ); + completionOffset = strlen(completionField->buffer) - strlen(completionString); - Q_strncpyz( &completionField->buffer[completionOffset], shortestMatch, sizeof( completionField->buffer ) - completionOffset ); + Q_strncpyz(&completionField->buffer[completionOffset], shortestMatch, sizeof(completionField->buffer) - completionOffset); - completionField->cursor = strlen( completionField->buffer ); + completionField->cursor = strlen(completionField->buffer); - if ( matchCount == 1 ) { - Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " ); + if (matchCount == 1) { + Q_strcat(completionField->buffer, sizeof(completionField->buffer), " "); completionField->cursor++; return qtrue; } - Com_Printf( "%c%s\n", CONSOLE_PROMPT_CHAR, completionField->buffer ); + Com_Printf("%c%s\n", CONSOLE_PROMPT_CHAR, completionField->buffer); return qfalse; } @@ -1792,15 +1708,14 @@ static qboolean Field_Complete( void ) { Field_CompleteKeyname =============== */ -void Field_CompleteKeyname( void ) -{ +void Field_CompleteKeyname(void) { matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - Key_KeynameCompletion( FindMatches ); + Key_KeynameCompletion(FindMatches); - if( !Field_Complete( ) ) - Key_KeynameCompletion( PrintKeyMatches ); + if (!Field_Complete()) + Key_KeynameCompletion(PrintKeyMatches); } /* @@ -1808,15 +1723,14 @@ void Field_CompleteKeyname( void ) Field_CompleteFilename =============== */ -void Field_CompleteFilename( const char *dir, const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk ) -{ +void Field_CompleteFilename(const char *dir, const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk) { matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk ); + FS_FilenameCompletion(dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk); - if ( !Field_Complete() ) - FS_FilenameCompletion( dir, ext, stripExt, PrintFileMatches, allowNonPureFilesOnDisk ); + if (!Field_Complete()) + FS_FilenameCompletion(dir, ext, stripExt, PrintFileMatches, allowNonPureFilesOnDisk); } /* @@ -1824,59 +1738,56 @@ void Field_CompleteFilename( const char *dir, const char *ext, qboolean stripExt Field_CompleteCommand =============== */ -void Field_CompleteCommand( char *cmd, qboolean doCommands, qboolean doCvars ) -{ +void Field_CompleteCommand(char *cmd, qboolean doCommands, qboolean doCvars) { int completionArgument = 0; // Skip leading whitespace and quotes - cmd = Com_SkipCharset( cmd, " \"" ); + cmd = Com_SkipCharset(cmd, " \""); - Cmd_TokenizeStringIgnoreQuotes( cmd ); + Cmd_TokenizeStringIgnoreQuotes(cmd); completionArgument = Cmd_Argc(); // If there is trailing whitespace on the cmd - if ( *(cmd + strlen( cmd )-1) == ' ' ) { + if (*(cmd + strlen(cmd) - 1) == ' ') { completionString = ""; completionArgument++; - } - else - completionString = Cmd_Argv( completionArgument - 1 ); + } else + completionString = Cmd_Argv(completionArgument - 1); - if ( completionArgument > 1 ) { - const char *baseCmd = Cmd_Argv( 0 ); + if (completionArgument > 1) { + const char *baseCmd = Cmd_Argv(0); char *p; - if ( baseCmd[0] == '\\' || baseCmd[0] == '/' ) + if (baseCmd[0] == '\\' || baseCmd[0] == '/') baseCmd++; - if( ( p = Field_FindFirstSeparator( cmd ) ) ) - Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command + if ((p = Field_FindFirstSeparator(cmd))) + Field_CompleteCommand(p + 1, qtrue, qtrue); // Compound command else - Cmd_CompleteArgument( baseCmd, cmd, completionArgument ); - } - else { - if ( completionString[0] == '\\' || completionString[0] == '/' ) + Cmd_CompleteArgument(baseCmd, cmd, completionArgument); + } else { + if (completionString[0] == '\\' || completionString[0] == '/') completionString++; matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - if ( strlen( completionString ) == 0 ) + if (strlen(completionString) == 0) return; - if ( doCommands ) - Cmd_CommandCompletion( FindMatches ); + if (doCommands) + Cmd_CommandCompletion(FindMatches); - if ( doCvars ) - Cvar_CommandCompletion( FindMatches ); + if (doCvars) + Cvar_CommandCompletion(FindMatches); - if ( !Field_Complete() ) { + if (!Field_Complete()) { // run through again, printing matches - if ( doCommands ) - Cmd_CommandCompletion( PrintMatches ); + if (doCommands) + Cmd_CommandCompletion(PrintMatches); - if ( doCvars ) - Cvar_CommandCompletion( PrintCvarMatches ); + if (doCvars) + Cvar_CommandCompletion(PrintCvarMatches); } } } @@ -1888,49 +1799,43 @@ Field_AutoComplete Perform Tab expansion =============== */ -void Field_AutoComplete( field_t *field ) { - if ( !field || !field->buffer[0] ) +void Field_AutoComplete(field_t *field) { + if (!field || !field->buffer[0]) return; completionField = field; - Field_CompleteCommand( completionField->buffer, qtrue, qtrue ); + Field_CompleteCommand(completionField->buffer, qtrue, qtrue); } - /* =============== Converts a UTF-8 character to UTF-32. =============== */ -uint32_t ConvertUTF8ToUTF32( char *utf8CurrentChar, char **utf8NextChar ) -{ +uint32_t ConvertUTF8ToUTF32(char *utf8CurrentChar, char **utf8NextChar) { uint32_t utf32 = 0; char *c = utf8CurrentChar; - if( ( *c & 0x80 ) == 0 ) + if ((*c & 0x80) == 0) utf32 = *c++; - else if( ( *c & 0xE0 ) == 0xC0 ) // 110x xxxx + else if ((*c & 0xE0) == 0xC0) // 110x xxxx { - utf32 |= ( *c++ & 0x1F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else if( ( *c & 0xF0 ) == 0xE0 ) // 1110 xxxx - { - utf32 |= ( *c++ & 0x0F ) << 12; - utf32 |= ( *c++ & 0x3F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else if( ( *c & 0xF8 ) == 0xF0 ) // 1111 0xxx + utf32 |= (*c++ & 0x1F) << 6; + utf32 |= (*c++ & 0x3F); + } else if ((*c & 0xF0) == 0xE0) // 1110 xxxx { - utf32 |= ( *c++ & 0x07 ) << 18; - utf32 |= ( *c++ & 0x3F ) << 12; - utf32 |= ( *c++ & 0x3F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else + utf32 |= (*c++ & 0x0F) << 12; + utf32 |= (*c++ & 0x3F) << 6; + utf32 |= (*c++ & 0x3F); + } else if ((*c & 0xF8) == 0xF0) // 1111 0xxx { - Com_DPrintf( "Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c ); + utf32 |= (*c++ & 0x07) << 18; + utf32 |= (*c++ & 0x3F) << 12; + utf32 |= (*c++ & 0x3F) << 6; + utf32 |= (*c++ & 0x3F); + } else { + Com_DPrintf("Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c); c++; } diff --git a/code/qcommon/cvar.cpp b/code/qcommon/cvar.cpp index 77d8e4b4a7..7c47a5a594 100644 --- a/code/qcommon/cvar.cpp +++ b/code/qcommon/cvar.cpp @@ -27,28 +27,25 @@ along with this program; if not, see . #include "q_shared.h" #include "qcommon.h" -cvar_t *cvar_vars = NULL; -cvar_t *cvar_cheats; -int cvar_modifiedFlags; +cvar_t *cvar_vars = NULL; +cvar_t *cvar_cheats; +int cvar_modifiedFlags; -#define MAX_CVARS 8192 -cvar_t cvar_indexes[MAX_CVARS]; -int cvar_numIndexes; +#define MAX_CVARS 8192 +cvar_t cvar_indexes[MAX_CVARS]; +int cvar_numIndexes; -#define FILE_HASH_SIZE 512 -static cvar_t* hashTable[FILE_HASH_SIZE]; -static qboolean cvar_sort = qfalse; +#define FILE_HASH_SIZE 512 +static cvar_t *hashTable[FILE_HASH_SIZE]; +static qboolean cvar_sort = qfalse; static char *lastMemPool = NULL; static int memPoolSize; - -//If the string came from the memory pool, don't really free it. The entire -//memory pool will be wiped during the next level load. -static void Cvar_FreeString(char *string) -{ - if(!lastMemPool || string < lastMemPool || - string >= lastMemPool + memPoolSize) { +// If the string came from the memory pool, don't really free it. The entire +// memory pool will be wiped during the next level load. +static void Cvar_FreeString(char *string) { + if (!lastMemPool || string < lastMemPool || string >= lastMemPool + memPoolSize) { Z_Free(string); } } @@ -58,19 +55,19 @@ static void Cvar_FreeString(char *string) return a hash value for the filename ================ */ -static long generateHashValue( const char *fname ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - hash+=(long)(letter)*(i+119); + hash += (long)(letter) * (i + 119); i++; } - hash &= (FILE_HASH_SIZE-1); + hash &= (FILE_HASH_SIZE - 1); return hash; } @@ -79,17 +76,17 @@ static long generateHashValue( const char *fname ) { Cvar_ValidateString ============ */ -static qboolean Cvar_ValidateString( const char *s ) { - if ( !s ) { +static qboolean Cvar_ValidateString(const char *s) { + if (!s) { return qfalse; } - if ( strchr( s, '\\' ) ) { + if (strchr(s, '\\')) { return qfalse; } - if ( strchr( s, '\"' ) ) { + if (strchr(s, '\"')) { return qfalse; } - if ( strchr( s, ';' ) ) { + if (strchr(s, ';')) { return qfalse; } return qtrue; @@ -100,13 +97,13 @@ static qboolean Cvar_ValidateString( const char *s ) { Cvar_FindVar ============ */ -static cvar_t *Cvar_FindVar( const char *var_name ) { - cvar_t *var; +static cvar_t *Cvar_FindVar(const char *var_name) { + cvar_t *var; long hash; hash = generateHashValue(var_name); - for (var=hashTable[hash] ; var ; var=var->hashNext) { + for (var = hashTable[hash]; var; var = var->hashNext) { if (!Q_stricmp(var_name, var->name)) { return var; } @@ -120,60 +117,56 @@ static cvar_t *Cvar_FindVar( const char *var_name ) { Cvar_VariableValue ============ */ -float Cvar_VariableValue( const char *var_name ) { - cvar_t *var; +float Cvar_VariableValue(const char *var_name) { + cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return 0; return var->value; } - /* ============ Cvar_VariableIntegerValue ============ */ -int Cvar_VariableIntegerValue( const char *var_name ) { - cvar_t *var; +int Cvar_VariableIntegerValue(const char *var_name) { + cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return 0; return var->integer; } - /* ============ Cvar_VariableString ============ */ -char *Cvar_VariableString( const char *var_name ) { +char *Cvar_VariableString(const char *var_name) { cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return ""; return var->string; } - /* ============ Cvar_VariableStringBuffer ============ */ -void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { +void Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize) { cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) { *buffer = 0; - } - else { - Q_strncpyz( buffer, var->string, bufsize ); + } else { + Q_strncpyz(buffer, var->string, bufsize); } } @@ -182,14 +175,13 @@ void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize Cvar_Flags ============ */ -int Cvar_Flags( const char *var_name ) { +int Cvar_Flags(const char *var_name) { cvar_t *var; - if(!(var = Cvar_FindVar(var_name))) + if (!(var = Cvar_FindVar(var_name))) return CVAR_NONEXISTENT; - else - { - if(var->modified) + else { + if (var->modified) return var->flags | CVAR_MODIFIED; else return var->flags; @@ -201,15 +193,14 @@ int Cvar_Flags( const char *var_name ) { Cvar_CommandCompletion ============ */ -void Cvar_CommandCompletion( callbackFunc_t callback ) { - cvar_t *cvar; +void Cvar_CommandCompletion(callbackFunc_t callback) { + cvar_t *cvar; - for ( cvar = cvar_vars ; cvar ; cvar = cvar->next ) { - if ( (cvar->flags & CVAR_CHEAT) && !cvar_cheats->integer ) - { + for (cvar = cvar_vars; cvar; cvar = cvar->next) { + if ((cvar->flags & CVAR_CHEAT) && !cvar_cheats->integer) { continue; } - callback( cvar->name ); + callback(cvar->name); } } @@ -218,100 +209,84 @@ void Cvar_CommandCompletion( callbackFunc_t callback ) { Cvar_Validate ============ */ -static const char *Cvar_Validate( cvar_t *var, const char *value, qboolean warn ) -{ +static const char *Cvar_Validate(cvar_t *var, const char *value, qboolean warn) { static char s[MAX_CVAR_VALUE_STRING]; float valuef; qboolean changed = qfalse; - if( !var->validate ) + if (!var->validate) return value; - if( !value ) + if (!value) return value; - if( Q_isanumber( value ) ) - { - valuef = atof( value ); + if (Q_isanumber(value)) { + valuef = atof(value); - if( var->integral ) - { - if( !Q_isintegral( valuef ) ) - { - if( warn ) - Com_Printf( "WARNING: cvar '%s' must be integral", var->name ); + if (var->integral) { + if (!Q_isintegral(valuef)) { + if (warn) + Com_Printf("WARNING: cvar '%s' must be integral", var->name); valuef = (int)valuef; changed = qtrue; } } - } - else - { - if( warn ) - Com_Printf( "WARNING: cvar '%s' must be numeric", var->name ); + } else { + if (warn) + Com_Printf("WARNING: cvar '%s' must be numeric", var->name); - valuef = atof( var->resetString ); + valuef = atof(var->resetString); changed = qtrue; } - if( valuef < var->min ) - { - if( warn ) - { - if( changed ) - Com_Printf( " and is" ); + if (valuef < var->min) { + if (warn) { + if (changed) + Com_Printf(" and is"); else - Com_Printf( "WARNING: cvar '%s'", var->name ); + Com_Printf("WARNING: cvar '%s'", var->name); - if( Q_isintegral( var->min ) ) - Com_Printf( " out of range (min %d)", (int)var->min ); + if (Q_isintegral(var->min)) + Com_Printf(" out of range (min %d)", (int)var->min); else - Com_Printf( " out of range (min %f)", var->min ); + Com_Printf(" out of range (min %f)", var->min); } valuef = var->min; changed = qtrue; - } - else if( valuef > var->max ) - { - if( warn ) - { - if( changed ) - Com_Printf( " and is" ); + } else if (valuef > var->max) { + if (warn) { + if (changed) + Com_Printf(" and is"); else - Com_Printf( "WARNING: cvar '%s'", var->name ); + Com_Printf("WARNING: cvar '%s'", var->name); - if( Q_isintegral( var->max ) ) - Com_Printf( " out of range (max %d)", (int)var->max ); + if (Q_isintegral(var->max)) + Com_Printf(" out of range (max %d)", (int)var->max); else - Com_Printf( " out of range (max %f)", var->max ); + Com_Printf(" out of range (max %f)", var->max); } valuef = var->max; changed = qtrue; } - if( changed ) - { - if( Q_isintegral( valuef ) ) - { - Com_sprintf( s, sizeof( s ), "%d", (int)valuef ); + if (changed) { + if (Q_isintegral(valuef)) { + Com_sprintf(s, sizeof(s), "%d", (int)valuef); - if( warn ) - Com_Printf( ", setting to %d\n", (int)valuef ); - } - else - { - Com_sprintf( s, sizeof( s ), "%f", valuef ); + if (warn) + Com_Printf(", setting to %d\n", (int)valuef); + } else { + Com_sprintf(s, sizeof(s), "%f", valuef); - if( warn ) - Com_Printf( ", setting to %f\n", valuef ); + if (warn) + Com_Printf(", setting to %f\n", valuef); } return s; - } - else + } else return value; } @@ -323,57 +298,52 @@ If the variable already exists, the value will not be set unless CVAR_ROM The flags will be or'ed in if the variable exists. ============ */ -cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { - cvar_t *var; - long hash; - int index; +cvar_t *Cvar_Get(const char *var_name, const char *var_value, int flags) { + cvar_t *var; + long hash; + int index; - if ( !var_name || ! var_value ) { - Com_Error( ERR_FATAL, "Cvar_Get: NULL parameter" ); - } + if (!var_name || !var_value) { + Com_Error(ERR_FATAL, "Cvar_Get: NULL parameter"); + } - if ( !Cvar_ValidateString( var_name ) ) { - Com_Printf("invalid cvar name string: %s\n", var_name ); + if (!Cvar_ValidateString(var_name)) { + Com_Printf("invalid cvar name string: %s\n", var_name); var_name = "BADNAME"; } -#if 0 // FIXME: values with backslash happen +#if 0 // FIXME: values with backslash happen if ( !Cvar_ValidateString( var_value ) ) { Com_Printf("invalid cvar value string: %s\n", var_value ); var_value = "BADVALUE"; } #endif - var = Cvar_FindVar (var_name); - if ( var ) { + var = Cvar_FindVar(var_name); + if (var) { var_value = Cvar_Validate(var, var_value, qfalse); // Make sure the game code cannot mark engine-added variables as gamecode vars - if(var->flags & CVAR_VM_CREATED) - { - if(!(flags & CVAR_VM_CREATED)) + if (var->flags & CVAR_VM_CREATED) { + if (!(flags & CVAR_VM_CREATED)) var->flags &= ~CVAR_VM_CREATED; - } - else if (!(var->flags & CVAR_USER_CREATED)) - { - if(flags & CVAR_VM_CREATED) + } else if (!(var->flags & CVAR_USER_CREATED)) { + if (flags & CVAR_VM_CREATED) flags &= ~CVAR_VM_CREATED; } // if the C code is now specifying a variable that the user already // set a value for, take the new value as the reset value - if ( var->flags & CVAR_USER_CREATED ) - { + if (var->flags & CVAR_USER_CREATED) { var->flags &= ~CVAR_USER_CREATED; - Cvar_FreeString( var->resetString ); - var->resetString = CopyString( var_value ); + Cvar_FreeString(var->resetString); + var->resetString = CopyString(var_value); - if(flags & CVAR_ROM) - { + if (flags & CVAR_ROM) { // this variable was set by the user, // so force it to value given by the engine. - if(var->latchedString) + if (var->latchedString) Cvar_FreeString(var->latchedString); var->latchedString = CopyString(var_value); @@ -381,36 +351,32 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { } // Make sure servers cannot mark engine-added variables as SERVER_CREATED - if(var->flags & CVAR_SERVER_CREATED) - { - if(!(flags & CVAR_SERVER_CREATED)) + if (var->flags & CVAR_SERVER_CREATED) { + if (!(flags & CVAR_SERVER_CREATED)) var->flags &= ~CVAR_SERVER_CREATED; - } - else - { - if(flags & CVAR_SERVER_CREATED) + } else { + if (flags & CVAR_SERVER_CREATED) flags &= ~CVAR_SERVER_CREATED; } var->flags |= flags; // only allow one non-empty reset string without a warning - if ( !var->resetString[0] ) { + if (!var->resetString[0]) { // we don't have a reset string yet - Cvar_FreeString( var->resetString ); - var->resetString = CopyString( var_value ); - } else if ( var_value[0] && strcmp( var->resetString, var_value ) ) { - Com_DPrintf( S_COLOR_YELLOW "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n", - var_name, var->resetString, var_value ); + Cvar_FreeString(var->resetString); + var->resetString = CopyString(var_value); + } else if (var_value[0] && strcmp(var->resetString, var_value)) { + Com_DPrintf(S_COLOR_YELLOW "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n", var_name, var->resetString, var_value); } // if we have a latched string, take that value now - if ( var->latchedString ) { + if (var->latchedString) { char *s; s = var->latchedString; - var->latchedString = NULL; // otherwise cvar_set2 would free it - Cvar_Set2( var_name, s, qtrue ); - Cvar_FreeString( s ); + var->latchedString = NULL; // otherwise cvar_set2 would free it + Cvar_Set2(var_name, s, qtrue); + Cvar_FreeString(s); } // ZOID--needs to be set so that cvars the game sets as @@ -425,15 +391,13 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { // // find a free cvar - for(index = 0; index < MAX_CVARS; index++) - { - if(!cvar_indexes[index].name) + for (index = 0; index < MAX_CVARS; index++) { + if (!cvar_indexes[index].name) break; } - if(index >= MAX_CVARS) - { - if(!com_errorEntered) + if (index >= MAX_CVARS) { + if (!com_errorEntered) Com_Error(ERR_FATAL, "Error: Too many cvars, cannot create a new one!"); return NULL; @@ -441,21 +405,21 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { var = &cvar_indexes[index]; - if(index >= cvar_numIndexes) + if (index >= cvar_numIndexes) cvar_numIndexes = index + 1; - var->name = CopyString (var_name); - var->string = CopyString (var_value); + var->name = CopyString(var_name); + var->string = CopyString(var_value); var->modified = qtrue; var->modificationCount = 1; - var->value = atof (var->string); + var->value = atof(var->string); var->integer = atoi(var->string); - var->resetString = CopyString( var_value ); + var->resetString = CopyString(var_value); var->validate = qfalse; // link the variable in var->next = cvar_vars; - if(cvar_vars) + if (cvar_vars) cvar_vars->prev = var; var->prev = NULL; @@ -469,7 +433,7 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { var->hashIndex = hash; var->hashNext = hashTable[hash]; - if(hashTable[hash]) + if (hashTable[hash]) hashTable[hash]->hashPrev = var; var->hashPrev = NULL; @@ -481,63 +445,64 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, int flags ) { return var; } -static void Cvar_QSortByName( cvar_t **a, int n ) -{ +static void Cvar_QSortByName(cvar_t **a, int n) { cvar_t *temp; cvar_t *m; - int i, j; + int i, j; i = 0; j = n; - m = a[ n>>1 ]; + m = a[n >> 1]; do { // sort in descending order - while ( strcmp( a[i]->name, m->name ) > 0 ) i++; - while ( strcmp( a[j]->name, m->name ) < 0 ) j--; + while (strcmp(a[i]->name, m->name) > 0) + i++; + while (strcmp(a[j]->name, m->name) < 0) + j--; - if ( i <= j ) { - temp = a[i]; - a[i] = a[j]; + if (i <= j) { + temp = a[i]; + a[i] = a[j]; a[j] = temp; - i++; + i++; j--; } - } while ( i <= j ); + } while (i <= j); - if ( j > 0 ) Cvar_QSortByName( a, j ); - if ( n > i ) Cvar_QSortByName( a+i, n-i ); + if (j > 0) + Cvar_QSortByName(a, j); + if (n > i) + Cvar_QSortByName(a + i, n - i); } - -static void Cvar_Sort( void ) -{ - cvar_t *list[ MAX_CVARS ], *var; +static void Cvar_Sort(void) { + cvar_t *list[MAX_CVARS], *var; int count; int i; - for ( count = 0, var = cvar_vars; var; var = var->next ) { - if ( var->name ) { - list[ count++ ] = var; + for (count = 0, var = cvar_vars; var; var = var->next) { + if (var->name) { + list[count++] = var; } else { - Com_Error( ERR_FATAL, "Cvar_Sort: NULL cvar name" ); + Com_Error(ERR_FATAL, "Cvar_Sort: NULL cvar name"); } } - if ( count < 2 ) { + if (count < 2) { return; // nothing to sort } - Cvar_QSortByName( &list[0], count-1 ); - + Cvar_QSortByName(&list[0], count - 1); + cvar_vars = NULL; // relink cvars - for ( i = 0; i < count; i++ ) { - var = list[ i ]; + for (i = 0; i < count; i++) { + var = list[i]; // link the variable in var->next = cvar_vars; - if ( cvar_vars ) + if (cvar_vars) cvar_vars->prev = var; var->prev = NULL; cvar_vars = var; @@ -551,20 +516,20 @@ Cvar_Print Prints the value, default, and latched string of the given variable ============ */ -void Cvar_Print( cvar_t *v ) { - Com_Printf( S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->name, v->string ); +void Cvar_Print(cvar_t *v) { + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->name, v->string); - if ( !(v->flags & CVAR_ROM) ) { - if ( !Q_stricmp( v->string, v->resetString ) ) - Com_Printf( ", " S_COLOR_WHITE "the default" ); + if (!(v->flags & CVAR_ROM)) { + if (!Q_stricmp(v->string, v->resetString)) + Com_Printf(", " S_COLOR_WHITE "the default"); else - Com_Printf( ", " S_COLOR_WHITE "default = " S_COLOR_GREY"\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->resetString ); + Com_Printf(", " S_COLOR_WHITE "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->resetString); } - Com_Printf( "\n" ); + Com_Printf("\n"); - if ( v->latchedString ) - Com_Printf( " latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"\n", v->latchedString ); + if (v->latchedString) + Com_Printf(" latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"\n", v->latchedString); } /* @@ -572,121 +537,107 @@ void Cvar_Print( cvar_t *v ) { Cvar_Set2 ============ */ -cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force ) { - cvar_t *var; +cvar_t *Cvar_Set2(const char *var_name, const char *value, qboolean force) { + cvar_t *var; - //Com_DPrintf( "Cvar_Set2: %s %s\n", var_name, value ); + // Com_DPrintf( "Cvar_Set2: %s %s\n", var_name, value ); - if ( !Cvar_ValidateString( var_name ) ) { - Com_Printf("invalid cvar name string: %s\n", var_name ); + if (!Cvar_ValidateString(var_name)) { + Com_Printf("invalid cvar name string: %s\n", var_name); var_name = "BADNAME"; } -#if 0 // FIXME +#if 0 // FIXME if ( value && !Cvar_ValidateString( value ) ) { Com_Printf("invalid cvar value string: %s\n", value ); var_value = "BADVALUE"; } #endif - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) { - if ( !value ) { + if (!value) { return NULL; } // create it - if ( !force ) { - return Cvar_Get( var_name, value, CVAR_USER_CREATED ); + if (!force) { + return Cvar_Get(var_name, value, CVAR_USER_CREATED); } else { - return Cvar_Get (var_name, value, 0); + return Cvar_Get(var_name, value, 0); } } - if (!value ) { + if (!value) { value = var->resetString; } value = Cvar_Validate(var, value, qtrue); - if((var->flags & CVAR_LATCH) && var->latchedString) - { - if(!strcmp(value, var->string)) - { + if ((var->flags & CVAR_LATCH) && var->latchedString) { + if (!strcmp(value, var->string)) { Cvar_FreeString(var->latchedString); var->latchedString = NULL; return var; } - if(!strcmp(value, var->latchedString)) + if (!strcmp(value, var->latchedString)) return var; - } - else if(!strcmp(value, var->string)) + } else if (!strcmp(value, var->string)) return var; // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) cvar_modifiedFlags |= var->flags; - if (!force) - { - if (var->flags & CVAR_ROM) - { - Com_Printf ("%s is read only.\n", var_name); + if (!force) { + if (var->flags & CVAR_ROM) { + Com_Printf("%s is read only.\n", var_name); return var; } - if (var->flags & CVAR_INIT) - { - Com_Printf ("%s is write protected.\n", var_name); + if (var->flags & CVAR_INIT) { + Com_Printf("%s is write protected.\n", var_name); return var; } - if (var->flags & CVAR_LATCH) - { - if (var->latchedString) - { + if (var->flags & CVAR_LATCH) { + if (var->latchedString) { if (strcmp(value, var->latchedString) == 0) return var; - Cvar_FreeString (var->latchedString); - } - else - { + Cvar_FreeString(var->latchedString); + } else { if (strcmp(value, var->string) == 0) return var; } - Com_Printf ("%s will be changed upon restarting.\n", var_name); + Com_Printf("%s will be changed upon restarting.\n", var_name); var->latchedString = CopyString(value); var->modified = qtrue; var->modificationCount++; return var; } - if ( (var->flags & CVAR_CHEAT) && !cvar_cheats->integer ) - { - Com_Printf ("%s is cheat protected.\n", var_name); + if ((var->flags & CVAR_CHEAT) && !cvar_cheats->integer) { + Com_Printf("%s is cheat protected.\n", var_name); return var; } - } - else - { - if (var->latchedString) - { - Cvar_FreeString (var->latchedString); + } else { + if (var->latchedString) { + Cvar_FreeString(var->latchedString); var->latchedString = NULL; } } if (!strcmp(value, var->string)) - return var; // not changed + return var; // not changed var->modified = qtrue; var->modificationCount++; - Cvar_FreeString (var->string); // free the old value string + Cvar_FreeString(var->string); // free the old value string var->string = CopyString(value); - var->value = atof (var->string); - var->integer = atoi (var->string); + var->value = atof(var->string); + var->integer = atoi(var->string); return var; } @@ -696,24 +647,22 @@ cvar_t *Cvar_Set2( const char *var_name, const char *value, qboolean force ) { Cvar_Set ============ */ -void Cvar_Set( const char *var_name, const char *value) { - Cvar_Set2 (var_name, value, qtrue); -} +void Cvar_Set(const char *var_name, const char *value) { Cvar_Set2(var_name, value, qtrue); } /* ============ Cvar_SetValue ============ */ -void Cvar_SetValue( const char *var_name, float value) { - char val[32]; +void Cvar_SetValue(const char *var_name, float value) { + char val[32]; - if ( value == (int)value ) { - Com_sprintf (val, sizeof(val), "%i",(int)value); + if (value == (int)value) { + Com_sprintf(val, sizeof(val), "%i", (int)value); } else { - Com_sprintf (val, sizeof(val), "%f",value); + Com_sprintf(val, sizeof(val), "%f", value); } - Cvar_Set (var_name, val); + Cvar_Set(var_name, val); } /* @@ -721,15 +670,14 @@ void Cvar_SetValue( const char *var_name, float value) { Cvar_SetValue2 ============ */ -void Cvar_SetValue2( const char *var_name, float value, qboolean force ) -{ - char val[32]; +void Cvar_SetValue2(const char *var_name, float value, qboolean force) { + char val[32]; - if( Q_isintegral( value ) ) - Com_sprintf( val, sizeof(val), "%i", (int)value ); + if (Q_isintegral(value)) + Com_sprintf(val, sizeof(val), "%i", (int)value); else - Com_sprintf( val, sizeof(val), "%f", value ); - Cvar_Set2( var_name, val, force ); + Com_sprintf(val, sizeof(val), "%f", value); + Cvar_Set2(var_name, val, force); } /* @@ -737,20 +685,14 @@ void Cvar_SetValue2( const char *var_name, float value, qboolean force ) Cvar_Reset ============ */ -void Cvar_Reset( const char *var_name ) { - Cvar_Set2( var_name, NULL, qfalse ); -} +void Cvar_Reset(const char *var_name) { Cvar_Set2(var_name, NULL, qfalse); } /* ============ Cvar_ForceReset ============ */ -void Cvar_ForceReset(const char *var_name) -{ - Cvar_Set2(var_name, NULL, qtrue); -} - +void Cvar_ForceReset(const char *var_name) { Cvar_Set2(var_name, NULL, qtrue); } /* ============ @@ -759,21 +701,20 @@ Cvar_SetCheatState Any testing variables will be reset to the safe values ============ */ -void Cvar_SetCheatState( void ) { - cvar_t *var; +void Cvar_SetCheatState(void) { + cvar_t *var; // set all default vars to the safe value - for ( var = cvar_vars ; var ; var = var->next ) { - if ( var->flags & CVAR_CHEAT ) { + for (var = cvar_vars; var; var = var->next) { + if (var->flags & CVAR_CHEAT) { // the CVAR_LATCHED|CVAR_CHEAT vars might escape the reset here // because of a different var->latchedString - if (var->latchedString) - { + if (var->latchedString) { Cvar_FreeString(var->latchedString); var->latchedString = NULL; } - if (strcmp(var->resetString,var->string)) { - Cvar_Set( var->name, var->resetString ); + if (strcmp(var->resetString, var->string)) { + Cvar_Set(var->name, var->resetString); } } } @@ -786,31 +727,30 @@ Cvar_Command Handles variable inspection and changing from the console ============ */ -qboolean Cvar_Command( void ) { - cvar_t *v; +qboolean Cvar_Command(void) { + cvar_t *v; // check variables - v = Cvar_FindVar (Cmd_Argv(0)); + v = Cvar_FindVar(Cmd_Argv(0)); if (!v) { return qfalse; } // perform a variable print or set - if ( Cmd_Argc() == 1 ) { - Cvar_Print( v ); + if (Cmd_Argc() == 1) { + Cvar_Print(v); return qtrue; } // toggle - if( !strcmp( Cmd_Argv(1), "!" ) ) - { + if (!strcmp(Cmd_Argv(1), "!")) { // Swap the value if our command has ! in it (bind p "cg_thirdPeson !") - Cvar_SetValue2( v->name, !v->value, qfalse ); + Cvar_SetValue2(v->name, !v->value, qfalse); return qtrue; } // set the value if forcing isn't required - Cvar_Set2 (v->name, Cmd_Args(), qfalse); + Cvar_Set2(v->name, Cmd_Args(), qfalse); return qtrue; } @@ -823,14 +763,12 @@ Prints the contents of a cvar (preferred over Cvar_Command where cvar names and commands conflict) ============ */ -void Cvar_Print_f(void) -{ +void Cvar_Print_f(void) { char *name; cvar_t *cv; - if(Cmd_Argc() != 2) - { - Com_Printf ("usage: print \n"); + if (Cmd_Argc() != 2) { + Com_Printf("usage: print \n"); return; } @@ -838,10 +776,10 @@ void Cvar_Print_f(void) cv = Cvar_FindVar(name); - if(cv) + if (cv) Cvar_Print(cv); else - Com_Printf ("Cvar %s does not exist.\n", name); + Com_Printf("Cvar %s does not exist.\n", name); } /* @@ -852,23 +790,21 @@ Toggles a cvar for easy single key binding, optionally through a list of given values ============ */ -void Cvar_Toggle_f( void ) { - int i, c = Cmd_Argc(); - char *curval; +void Cvar_Toggle_f(void) { + int i, c = Cmd_Argc(); + char *curval; - if(c < 2) { + if (c < 2) { Com_Printf("usage: toggle [value1, value2, ...]\n"); return; } - if(c == 2) { - Cvar_Set2(Cmd_Argv(1), va("%d", - !Cvar_VariableValue(Cmd_Argv(1))), - qfalse); + if (c == 2) { + Cvar_Set2(Cmd_Argv(1), va("%d", !Cvar_VariableValue(Cmd_Argv(1))), qfalse); return; } - if(c == 3) { + if (c == 3) { Com_Printf("toggle: nothing to toggle to\n"); return; } @@ -877,8 +813,8 @@ void Cvar_Toggle_f( void ) { // don't bother checking the last arg for a match since the desired // behaviour is the same as no match (set to the first argument) - for(i = 2; i + 1 < c; i++) { - if(strcmp(curval, Cmd_Argv(i)) == 0) { + for (i = 2; i + 1 < c; i++) { + if (strcmp(curval, Cmd_Argv(i)) == 0) { Cvar_Set2(Cmd_Argv(1), Cmd_Argv(i + 1), qfalse); return; } @@ -896,46 +832,46 @@ Allows setting and defining of arbitrary cvars from console, even if they weren't declared in C code. ============ */ -void Cvar_Set_f( void ) { - int c; - char *cmd; - cvar_t *v; +void Cvar_Set_f(void) { + int c; + char *cmd; + cvar_t *v; c = Cmd_Argc(); cmd = Cmd_Argv(0); - if ( c < 2 ) { - Com_Printf ("usage: %s \n", cmd); + if (c < 2) { + Com_Printf("usage: %s \n", cmd); return; } - if ( c == 2 ) { + if (c == 2) { Cvar_Print_f(); return; } - v = Cvar_Set2 (Cmd_Argv(1), Cmd_ArgsFrom(2), qfalse); - if( !v ) { + v = Cvar_Set2(Cmd_Argv(1), Cmd_ArgsFrom(2), qfalse); + if (!v) { return; } - switch( cmd[3] ) { - case 'a': - if( !( v->flags & CVAR_ARCHIVE ) ) { - v->flags |= CVAR_ARCHIVE; - cvar_modifiedFlags |= CVAR_ARCHIVE; - } - break; - case 'u': - if( !( v->flags & CVAR_USERINFO ) ) { - v->flags |= CVAR_USERINFO; - cvar_modifiedFlags |= CVAR_USERINFO; - } - break; - case 's': - if( !( v->flags & CVAR_SERVERINFO ) ) { - v->flags |= CVAR_SERVERINFO; - cvar_modifiedFlags |= CVAR_SERVERINFO; - } - break; + switch (cmd[3]) { + case 'a': + if (!(v->flags & CVAR_ARCHIVE)) { + v->flags |= CVAR_ARCHIVE; + cvar_modifiedFlags |= CVAR_ARCHIVE; + } + break; + case 'u': + if (!(v->flags & CVAR_USERINFO)) { + v->flags |= CVAR_USERINFO; + cvar_modifiedFlags |= CVAR_USERINFO; + } + break; + case 's': + if (!(v->flags & CVAR_SERVERINFO)) { + v->flags |= CVAR_SERVERINFO; + cvar_modifiedFlags |= CVAR_SERVERINFO; + } + break; } } @@ -944,12 +880,12 @@ void Cvar_Set_f( void ) { Cvar_Reset_f ============ */ -void Cvar_Reset_f( void ) { - if ( Cmd_Argc() != 2 ) { - Com_Printf ("usage: reset \n"); +void Cvar_Reset_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf("usage: reset \n"); return; } - Cvar_Reset( Cmd_Argv( 1 ) ); + Cvar_Reset(Cmd_Argv(1)); } /* @@ -960,45 +896,46 @@ Appends lines containing "set variable value" for all variables with the archive flag set to qtrue. ============ */ -void Cvar_WriteVariables( fileHandle_t f ) { - cvar_t *var; +void Cvar_WriteVariables(fileHandle_t f) { + cvar_t *var; char buffer[1024]; - if ( cvar_sort ) { - Com_DPrintf( "Cvar_Sort: sort cvars\n" ); + if (cvar_sort) { + Com_DPrintf("Cvar_Sort: sort cvars\n"); cvar_sort = qfalse; Cvar_Sort(); } - for ( var = cvar_vars; var; var = var->next ) - { - if ( !var->name || Q_stricmp( var->name, "cl_cdkey" ) == 0 ) + for (var = cvar_vars; var; var = var->next) { + if (!var->name || Q_stricmp(var->name, "cl_cdkey") == 0) continue; - if ( var->flags & CVAR_ARCHIVE ) { + if (var->flags & CVAR_ARCHIVE) { // write the latched value, even if it hasn't taken effect yet - if ( var->latchedString ) { - if( strlen( var->name ) + strlen( var->latchedString ) + 10 > sizeof( buffer ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: value of variable " - "\"%s\" too long to write to file\n", var->name ); + if (var->latchedString) { + if (strlen(var->name) + strlen(var->latchedString) + 10 > sizeof(buffer)) { + Com_Printf(S_COLOR_YELLOW "WARNING: value of variable " + "\"%s\" too long to write to file\n", + var->name); continue; } - if ( (var->flags & CVAR_NODEFAULT) && !strcmp( var->latchedString, var->resetString ) ) { + if ((var->flags & CVAR_NODEFAULT) && !strcmp(var->latchedString, var->resetString)) { continue; } - Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString); + Com_sprintf(buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString); } else { - if( strlen( var->name ) + strlen( var->string ) + 10 > sizeof( buffer ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: value of variable " - "\"%s\" too long to write to file\n", var->name ); + if (strlen(var->name) + strlen(var->string) + 10 > sizeof(buffer)) { + Com_Printf(S_COLOR_YELLOW "WARNING: value of variable " + "\"%s\" too long to write to file\n", + var->name); continue; } - if ( (var->flags & CVAR_NODEFAULT) && !strcmp( var->string, var->resetString ) ) { + if ((var->flags & CVAR_NODEFAULT) && !strcmp(var->string, var->resetString)) { continue; } - Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string); + Com_sprintf(buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string); } - FS_Write( buffer, strlen( buffer ), f ); + FS_Write(buffer, strlen(buffer), f); } } } @@ -1008,84 +945,99 @@ void Cvar_WriteVariables( fileHandle_t f ) { Cvar_List_f ============ */ -void Cvar_List_f( void ) { +void Cvar_List_f(void) { cvar_t *var = NULL; int i = 0; char *match = NULL; - if ( Cmd_Argc() > 1 ) - match = Cmd_Argv( 1 ); + if (Cmd_Argc() > 1) + match = Cmd_Argv(1); - for ( var=cvar_vars, i=0; - var; - var=var->next, i++ ) - { - if ( !var->name || (match && !Com_Filter( match, var->name, qfalse )) ) + for (var = cvar_vars, i = 0; var; var = var->next, i++) { + if (!var->name || (match && !Com_Filter(match, var->name, qfalse))) continue; - if (var->flags & CVAR_SERVERINFO) Com_Printf( "S" ); else Com_Printf( " " ); - if (var->flags & CVAR_SYSTEMINFO) Com_Printf( "s" ); else Com_Printf( " " ); - if (var->flags & CVAR_USERINFO) Com_Printf( "U" ); else Com_Printf( " " ); - if (var->flags & CVAR_ROM) Com_Printf( "R" ); else Com_Printf( " " ); - if (var->flags & CVAR_INIT) Com_Printf( "I" ); else Com_Printf( " " ); - if (var->flags & CVAR_ARCHIVE) Com_Printf( "A" ); else Com_Printf( " " ); - if (var->flags & CVAR_LATCH) Com_Printf( "L" ); else Com_Printf( " " ); - if (var->flags & CVAR_CHEAT) Com_Printf( "C" ); else Com_Printf( " " ); - if (var->flags & CVAR_USER_CREATED) Com_Printf( "?" ); else Com_Printf( " " ); - - Com_Printf( S_COLOR_WHITE " %s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->name, var->string ); - if ( var->latchedString ) - Com_Printf( ", latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->latchedString ); - Com_Printf( "\n" ); + if (var->flags & CVAR_SERVERINFO) + Com_Printf("S"); + else + Com_Printf(" "); + if (var->flags & CVAR_SYSTEMINFO) + Com_Printf("s"); + else + Com_Printf(" "); + if (var->flags & CVAR_USERINFO) + Com_Printf("U"); + else + Com_Printf(" "); + if (var->flags & CVAR_ROM) + Com_Printf("R"); + else + Com_Printf(" "); + if (var->flags & CVAR_INIT) + Com_Printf("I"); + else + Com_Printf(" "); + if (var->flags & CVAR_ARCHIVE) + Com_Printf("A"); + else + Com_Printf(" "); + if (var->flags & CVAR_LATCH) + Com_Printf("L"); + else + Com_Printf(" "); + if (var->flags & CVAR_CHEAT) + Com_Printf("C"); + else + Com_Printf(" "); + if (var->flags & CVAR_USER_CREATED) + Com_Printf("?"); + else + Com_Printf(" "); + + Com_Printf(S_COLOR_WHITE " %s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->name, var->string); + if (var->latchedString) + Com_Printf(", latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->latchedString); + Com_Printf("\n"); } - Com_Printf( "\n%i total cvars\n", i ); - if ( i != cvar_numIndexes ) - Com_Printf( "%i cvar indexes\n", cvar_numIndexes ); + Com_Printf("\n%i total cvars\n", i); + if (i != cvar_numIndexes) + Com_Printf("%i cvar indexes\n", cvar_numIndexes); } -void Cvar_ListModified_f( void ) { +void Cvar_ListModified_f(void) { cvar_t *var = NULL; // build a list of cvars that are modified - for ( var=cvar_vars; - var; - var=var->next ) - { + for (var = cvar_vars; var; var = var->next) { char *value = var->latchedString ? var->latchedString : var->string; - if ( !var->name || !var->modificationCount || !strcmp( value, var->resetString ) ) + if (!var->name || !var->modificationCount || !strcmp(value, var->resetString)) continue; - Com_Printf( S_COLOR_GREY "Cvar " - S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE ", " - S_COLOR_WHITE "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", - var->name, value, var->resetString ); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE ", " S_COLOR_WHITE + "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", + var->name, value, var->resetString); } } -void Cvar_ListUserCreated_f( void ) { +void Cvar_ListUserCreated_f(void) { cvar_t *var = NULL; uint32_t count = 0; // build a list of cvars that are modified - for ( var=cvar_vars; - var; - var=var->next ) - { + for (var = cvar_vars; var; var = var->next) { char *value = var->latchedString ? var->latchedString : var->string; - if ( !(var->flags & CVAR_USER_CREATED) ) + if (!(var->flags & CVAR_USER_CREATED)) continue; - Com_Printf( S_COLOR_GREY "Cvar " - S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", - var->name, value ); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", var->name, value); count++; } - if ( count > 0 ) - Com_Printf( S_COLOR_GREY "Showing " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count ); + if (count > 0) + Com_Printf(S_COLOR_GREY "Showing " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count); else - Com_Printf( S_COLOR_GREY "No user created cvars" S_COLOR_WHITE "\n" ); + Com_Printf(S_COLOR_GREY "No user created cvars" S_COLOR_WHITE "\n"); } /* @@ -1096,34 +1048,33 @@ Unsets a cvar ============ */ -cvar_t *Cvar_Unset(cvar_t *cv) -{ +cvar_t *Cvar_Unset(cvar_t *cv) { cvar_t *next = cv->next; // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) cvar_modifiedFlags |= cv->flags; - if(cv->name) + if (cv->name) Cvar_FreeString(cv->name); - if(cv->string) + if (cv->string) Cvar_FreeString(cv->string); - if(cv->latchedString) + if (cv->latchedString) Cvar_FreeString(cv->latchedString); - if(cv->resetString) + if (cv->resetString) Cvar_FreeString(cv->resetString); - if(cv->prev) + if (cv->prev) cv->prev->next = cv->next; else cvar_vars = cv->next; - if(cv->next) + if (cv->next) cv->next->prev = cv->prev; - if(cv->hashPrev) + if (cv->hashPrev) cv->hashPrev->hashNext = cv->hashNext; else hashTable[cv->hashIndex] = cv->hashNext; - if(cv->hashNext) + if (cv->hashNext) cv->hashNext->hashPrev = cv->hashPrev; memset(cv, 0, sizeof(*cv)); @@ -1139,48 +1090,43 @@ Unsets a userdefined cvar ============ */ -void Cvar_Unset_f(void) -{ +void Cvar_Unset_f(void) { cvar_t *cv; - if(Cmd_Argc() != 2) - { + if (Cmd_Argc() != 2) { Com_Printf("Usage: %s \n", Cmd_Argv(0)); return; } cv = Cvar_FindVar(Cmd_Argv(1)); - if(!cv) + if (!cv) return; - if(cv->flags & CVAR_USER_CREATED) + if (cv->flags & CVAR_USER_CREATED) Cvar_Unset(cv); else Com_Printf("Error: %s: Variable %s is not user created.\n", Cmd_Argv(0), cv->name); } -void Cvar_UnsetUserCreated_f(void) -{ - cvar_t *curvar = cvar_vars; +void Cvar_UnsetUserCreated_f(void) { + cvar_t *curvar = cvar_vars; uint32_t count = 0; - while ( curvar ) - { - if ( ( curvar->flags & CVAR_USER_CREATED ) ) - { + while (curvar) { + if ((curvar->flags & CVAR_USER_CREATED)) { // throw out any variables the user created - curvar = Cvar_Unset( curvar ); + curvar = Cvar_Unset(curvar); count++; continue; } curvar = curvar->next; } - if ( count > 0 ) - Com_Printf( S_COLOR_GREY "Removed " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count ); + if (count > 0) + Com_Printf(S_COLOR_GREY "Removed " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count); else - Com_Printf( S_COLOR_GREY "No user created cvars to remove" S_COLOR_WHITE "\n" ); + Com_Printf(S_COLOR_GREY "No user created cvars to remove" S_COLOR_WHITE "\n"); } /* @@ -1192,24 +1138,19 @@ and variables added via the VMs if requested. ============ */ -void Cvar_Restart(qboolean unsetVM) -{ - cvar_t *curvar; +void Cvar_Restart(qboolean unsetVM) { + cvar_t *curvar; curvar = cvar_vars; - while(curvar) - { - if((curvar->flags & CVAR_USER_CREATED) || - (unsetVM && (curvar->flags & CVAR_VM_CREATED))) - { + while (curvar) { + if ((curvar->flags & CVAR_USER_CREATED) || (unsetVM && (curvar->flags & CVAR_VM_CREATED))) { // throw out any variables the user/vm created curvar = Cvar_Unset(curvar); continue; } - if(!(curvar->flags & (CVAR_ROM | CVAR_INIT | CVAR_NORESTART))) - { + if (!(curvar->flags & (CVAR_ROM | CVAR_INIT | CVAR_NORESTART))) { // Just reset the rest to their default values. Cvar_Set2(curvar->name, curvar->resetString, qfalse); } @@ -1225,24 +1166,22 @@ Cvar_Restart_f Resets all cvars to their hardcoded values ============ */ -void Cvar_Restart_f( void ) { - Cvar_Restart(qfalse); -} +void Cvar_Restart_f(void) { Cvar_Restart(qfalse); } /* ===================== Cvar_InfoString ===================== */ -char *Cvar_InfoString( int bit ) { - static char info[MAX_INFO_STRING]; - cvar_t *var; +char *Cvar_InfoString(int bit) { + static char info[MAX_INFO_STRING]; + cvar_t *var; info[0] = 0; - for (var = cvar_vars ; var ; var = var->next) { + for (var = cvar_vars; var; var = var->next) { if (var->name && (var->flags & bit)) { - Info_SetValueForKey (info, var->name, var->string); + Info_SetValueForKey(info, var->name, var->string); } } return info; @@ -1253,24 +1192,21 @@ char *Cvar_InfoString( int bit ) { Cvar_InfoStringBuffer ===================== */ -void Cvar_InfoStringBuffer( int bit, char* buff, int buffsize ) { - Q_strncpyz(buff,Cvar_InfoString(bit),buffsize); -} +void Cvar_InfoStringBuffer(int bit, char *buff, int buffsize) { Q_strncpyz(buff, Cvar_InfoString(bit), buffsize); } /* ===================== Cvar_CheckRange ===================== */ -void Cvar_CheckRange( cvar_t *var, float min, float max, qboolean integral ) -{ +void Cvar_CheckRange(cvar_t *var, float min, float max, qboolean integral) { var->validate = qtrue; var->min = min; var->max = max; var->integral = integral; // Force an initial range check - Cvar_Set( var->name, var->string ); + Cvar_Set(var->name, var->string); } /* @@ -1280,29 +1216,29 @@ Cvar_Register basically a slightly modified Cvar_Get for the interpreted modules ===================== */ -void Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) { - cvar_t *cv; +void Cvar_Register(vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags) { + cvar_t *cv; // There is code in Cvar_Get to prevent CVAR_ROM cvars being changed by the // user. In other words CVAR_ARCHIVE and CVAR_ROM are mutually exclusive // flags. Unfortunately some historical game code (including single player // baseq3) sets both flags. We unset CVAR_ROM for such cvars. if ((flags & (CVAR_ARCHIVE | CVAR_ROM)) == (CVAR_ARCHIVE | CVAR_ROM)) { - Com_DPrintf( S_COLOR_YELLOW "WARNING: Unsetting CVAR_ROM cvar '%s', " - "since it is also CVAR_ARCHIVE\n", varName ); + Com_DPrintf(S_COLOR_YELLOW "WARNING: Unsetting CVAR_ROM cvar '%s', " + "since it is also CVAR_ARCHIVE\n", + varName); flags &= ~CVAR_ROM; } - cv = Cvar_Get( varName, defaultValue, flags | CVAR_VM_CREATED ); - if ( !vmCvar ) { + cv = Cvar_Get(varName, defaultValue, flags | CVAR_VM_CREATED); + if (!vmCvar) { return; } vmCvar->handle = cv - cvar_indexes; vmCvar->modificationCount = -1; - Cvar_Update( vmCvar ); + Cvar_Update(vmCvar); } - /* ===================== Cvar_Update @@ -1310,28 +1246,26 @@ Cvar_Update updates an interpreted modules' version of a cvar ===================== */ -void Cvar_Update( vmCvar_t *vmCvar ) { - cvar_t *cv = NULL; +void Cvar_Update(vmCvar_t *vmCvar) { + cvar_t *cv = NULL; assert(vmCvar); - if ( (unsigned)vmCvar->handle >= (unsigned)cvar_numIndexes ) { - Com_Error( ERR_DROP, "Cvar_Update: handle %u out of range", (unsigned)vmCvar->handle ); + if ((unsigned)vmCvar->handle >= (unsigned)cvar_numIndexes) { + Com_Error(ERR_DROP, "Cvar_Update: handle %u out of range", (unsigned)vmCvar->handle); } cv = cvar_indexes + vmCvar->handle; - if ( cv->modificationCount == vmCvar->modificationCount ) { + if (cv->modificationCount == vmCvar->modificationCount) { return; } - if ( !cv->string ) { - return; // variable might have been cleared by a cvar_restart + if (!cv->string) { + return; // variable might have been cleared by a cvar_restart } vmCvar->modificationCount = cv->modificationCount; - if ( strlen(cv->string)+1 > MAX_CVAR_VALUE_STRING ) - Com_Error( ERR_DROP, "Cvar_Update: src %s length %u exceeds MAX_CVAR_VALUE_STRING", - cv->string, - (unsigned int) strlen(cv->string)); - Q_strncpyz( vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING ); + if (strlen(cv->string) + 1 > MAX_CVAR_VALUE_STRING) + Com_Error(ERR_DROP, "Cvar_Update: src %s length %u exceeds MAX_CVAR_VALUE_STRING", cv->string, (unsigned int)strlen(cv->string)); + Q_strncpyz(vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING); vmCvar->value = cv->value; vmCvar->integer = cv->integer; } @@ -1341,15 +1275,13 @@ void Cvar_Update( vmCvar_t *vmCvar ) { Cvar_CompleteCvarName ================== */ -void Cvar_CompleteCvarName( char *args, int argNum ) -{ - if( argNum == 2 ) - { +void Cvar_CompleteCvarName(char *args, int argNum) { + if (argNum == 2) { // Skip " " - char *p = Com_SkipTokens( args, 1, " " ); + char *p = Com_SkipTokens(args, 1, " "); - if( p > args ) - Field_CompleteCommand( p, qfalse, qtrue ); + if (p > args) + Field_CompleteCommand(p, qfalse, qtrue); } } @@ -1360,40 +1292,37 @@ Cvar_Init Reads in all archived cvars ============ */ -void Cvar_Init (void) { - memset( cvar_indexes, 0, sizeof( cvar_indexes ) ); - memset( hashTable, 0, sizeof( hashTable ) ); - - cvar_cheats = Cvar_Get("helpUsObi", "0", CVAR_SYSTEMINFO ); - - Cmd_AddCommand( "print", Cvar_Print_f ); - Cmd_SetCommandCompletionFunc( "print", Cvar_CompleteCvarName ); - Cmd_AddCommand( "toggle", Cvar_Toggle_f ); - Cmd_SetCommandCompletionFunc( "toggle", Cvar_CompleteCvarName ); - Cmd_AddCommand( "set", Cvar_Set_f ); - Cmd_SetCommandCompletionFunc( "set", Cvar_CompleteCvarName ); - Cmd_AddCommand( "sets", Cvar_Set_f ); - Cmd_SetCommandCompletionFunc( "sets", Cvar_CompleteCvarName ); - Cmd_AddCommand( "setu", Cvar_Set_f ); - Cmd_SetCommandCompletionFunc( "setu", Cvar_CompleteCvarName ); - Cmd_AddCommand( "seta", Cvar_Set_f ); - Cmd_SetCommandCompletionFunc( "seta", Cvar_CompleteCvarName ); - Cmd_AddCommand( "reset", Cvar_Reset_f ); - Cmd_SetCommandCompletionFunc( "reset", Cvar_CompleteCvarName ); - Cmd_AddCommand( "unset", Cvar_Unset_f ); - Cmd_SetCommandCompletionFunc( "unset", Cvar_CompleteCvarName ); - Cmd_AddCommand( "unset_usercreated", Cvar_UnsetUserCreated_f ); - Cmd_AddCommand( "cvarlist", Cvar_List_f ); - Cmd_AddCommand( "cvar_usercreated", Cvar_ListUserCreated_f ); - Cmd_AddCommand( "cvar_modified", Cvar_ListModified_f ); - Cmd_AddCommand( "cvar_restart", Cvar_Restart_f ); +void Cvar_Init(void) { + memset(cvar_indexes, 0, sizeof(cvar_indexes)); + memset(hashTable, 0, sizeof(hashTable)); + + cvar_cheats = Cvar_Get("helpUsObi", "0", CVAR_SYSTEMINFO); + + Cmd_AddCommand("print", Cvar_Print_f); + Cmd_SetCommandCompletionFunc("print", Cvar_CompleteCvarName); + Cmd_AddCommand("toggle", Cvar_Toggle_f); + Cmd_SetCommandCompletionFunc("toggle", Cvar_CompleteCvarName); + Cmd_AddCommand("set", Cvar_Set_f); + Cmd_SetCommandCompletionFunc("set", Cvar_CompleteCvarName); + Cmd_AddCommand("sets", Cvar_Set_f); + Cmd_SetCommandCompletionFunc("sets", Cvar_CompleteCvarName); + Cmd_AddCommand("setu", Cvar_Set_f); + Cmd_SetCommandCompletionFunc("setu", Cvar_CompleteCvarName); + Cmd_AddCommand("seta", Cvar_Set_f); + Cmd_SetCommandCompletionFunc("seta", Cvar_CompleteCvarName); + Cmd_AddCommand("reset", Cvar_Reset_f); + Cmd_SetCommandCompletionFunc("reset", Cvar_CompleteCvarName); + Cmd_AddCommand("unset", Cvar_Unset_f); + Cmd_SetCommandCompletionFunc("unset", Cvar_CompleteCvarName); + Cmd_AddCommand("unset_usercreated", Cvar_UnsetUserCreated_f); + Cmd_AddCommand("cvarlist", Cvar_List_f); + Cmd_AddCommand("cvar_usercreated", Cvar_ListUserCreated_f); + Cmd_AddCommand("cvar_modified", Cvar_ListModified_f); + Cmd_AddCommand("cvar_restart", Cvar_Restart_f); } - -static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) -{ - if(string && *string) - { +static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) { + if (string && *string) { char *temp = memPool + memPoolUsed; strcpy(temp, *string); memPoolUsed += strlen(*string) + 1; @@ -1402,16 +1331,13 @@ static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) } } - -//Turns many small allocation blocks into one big one. -void Cvar_Defrag(void) -{ - cvar_t *var; +// Turns many small allocation blocks into one big one. +void Cvar_Defrag(void) { + cvar_t *var; int totalMem = 0; int nextMemPoolSize; - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { if (var->name) { totalMem += strlen(var->name) + 1; } @@ -1426,22 +1352,20 @@ void Cvar_Defrag(void) } } - char *mem = (char*)Z_Malloc(totalMem, TAG_SMALL, qfalse); + char *mem = (char *)Z_Malloc(totalMem, TAG_SMALL, qfalse); nextMemPoolSize = totalMem; totalMem = 0; - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { Cvar_Realloc(&var->name, mem, totalMem); Cvar_Realloc(&var->string, mem, totalMem); Cvar_Realloc(&var->resetString, mem, totalMem); Cvar_Realloc(&var->latchedString, mem, totalMem); } - if(lastMemPool) { + if (lastMemPool) { Z_Free(lastMemPool); } lastMemPool = mem; memPoolSize = nextMemPoolSize; } - diff --git a/code/qcommon/files.cpp b/code/qcommon/files.cpp index c35d0e00f5..1945979dfc 100644 --- a/code/qcommon/files.cpp +++ b/code/qcommon/files.cpp @@ -38,10 +38,10 @@ along with this program; if not, see . #include // for rmdir -#if defined (_MSC_VER) - #include +#if defined(_MSC_VER) +#include #else - #include +#include #endif #if defined(_WIN32) @@ -193,84 +193,84 @@ or configs will never get loaded from disk! static const uint32_t bonuspak_checksum = 0u;*/ -#define MAX_ZPATH 256 -#define MAX_SEARCH_PATHS 4096 -#define MAX_FILEHASH_SIZE 1024 +#define MAX_ZPATH 256 +#define MAX_SEARCH_PATHS 4096 +#define MAX_FILEHASH_SIZE 1024 typedef struct fileInPack_s { - char *name; // name of the file - unsigned long pos; // file info position in zip - unsigned long len; // uncompress file size - struct fileInPack_s* next; // next file in the hash + char *name; // name of the file + unsigned long pos; // file info position in zip + unsigned long len; // uncompress file size + struct fileInPack_s *next; // next file in the hash } fileInPack_t; typedef struct pack_s { - char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base - char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3 - char pakBasename[MAX_OSPATH]; // assets0 - char pakGamename[MAX_OSPATH]; // base - unzFile handle; // handle to zip file - int checksum; // regular checksum - int numfiles; // number of files in pk3 - int hashSize; // hash table size (power of 2) - fileInPack_t* *hashTable; // hash table - fileInPack_t* buildBuffer; // buffer with the filenames etc. + char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base + char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3 + char pakBasename[MAX_OSPATH]; // assets0 + char pakGamename[MAX_OSPATH]; // base + unzFile handle; // handle to zip file + int checksum; // regular checksum + int numfiles; // number of files in pk3 + int hashSize; // hash table size (power of 2) + fileInPack_t **hashTable; // hash table + fileInPack_t *buildBuffer; // buffer with the filenames etc. } pack_t; typedef struct directory_s { - char path[MAX_OSPATH]; // c:\jediacademy\gamedata - char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base - char gamedir[MAX_OSPATH]; // base + char path[MAX_OSPATH]; // c:\jediacademy\gamedata + char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base + char gamedir[MAX_OSPATH]; // base } directory_t; typedef struct searchpath_s { struct searchpath_s *next; - pack_t *pack; // only one of pack / dir will be non NULL - directory_t *dir; + pack_t *pack; // only one of pack / dir will be non NULL + directory_t *dir; } searchpath_t; -static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators -static cvar_t *fs_debug; -static cvar_t *fs_homepath; +static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators +static cvar_t *fs_debug; +static cvar_t *fs_homepath; #ifdef MACOS_X // Also search the .app bundle for .pk3 files -static cvar_t *fs_apppath; +static cvar_t *fs_apppath; #endif -static cvar_t *fs_basepath; -static cvar_t *fs_basegame; -static cvar_t *fs_cdpath; -static cvar_t *fs_copyfiles; -static cvar_t *fs_gamedirvar; -static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them -static searchpath_t *fs_searchpaths; -static int fs_readCount; // total bytes read -static int fs_loadCount; // total files read -static int fs_packFiles = 0; // total number of files in packs +static cvar_t *fs_basepath; +static cvar_t *fs_basegame; +static cvar_t *fs_cdpath; +static cvar_t *fs_copyfiles; +static cvar_t *fs_gamedirvar; +static cvar_t *fs_dirbeforepak; // rww - when building search path, keep directories at top and insert pk3's under them +static searchpath_t *fs_searchpaths; +static int fs_readCount; // total bytes read +static int fs_loadCount; // total files read +static int fs_packFiles = 0; // total number of files in packs typedef union qfile_gus { - FILE* o; - unzFile z; + FILE *o; + unzFile z; } qfile_gut; typedef struct qfile_us { - qfile_gut file; - qboolean unique; + qfile_gut file; + qboolean unique; } qfile_ut; typedef struct fileHandleData_s { - qfile_ut handleFiles; - qboolean handleSync; - int fileSize; - int zipFilePos; - int zipFileLen; - qboolean zipFile; - char name[MAX_ZPATH]; + qfile_ut handleFiles; + qboolean handleSync; + int fileSize; + int zipFilePos; + int zipFileLen; + qboolean zipFile; + char name[MAX_ZPATH]; } fileHandleData_t; -static fileHandleData_t fsh[MAX_FILE_HANDLES]; +static fileHandleData_t fsh[MAX_FILE_HANDLES]; // last valid game folder used char lastValidBase[MAX_OSPATH]; @@ -278,11 +278,11 @@ char lastValidGame[MAX_OSPATH]; /* C99 defines __func__ */ #if __STDC_VERSION__ < 199901L -# if __GNUC__ >= 2 || _MSC_VER >= 1300 -# define __func__ __FUNCTION__ -# else -# define __func__ "(unknown)" -# endif +#if __GNUC__ >= 2 || _MSC_VER >= 1300 +#define __func__ __FUNCTION__ +#else +#define __func__ "(unknown)" +#endif #endif /* @@ -291,13 +291,11 @@ FS_Initialized ============== */ -qboolean FS_Initialized( void ) { - return (qboolean)(fs_searchpaths != NULL); -} +qboolean FS_Initialized(void) { return (qboolean)(fs_searchpaths != NULL); } -static void FS_AssertInitialised( void ) { - if ( !fs_searchpaths ) { - Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" ); +static void FS_AssertInitialised(void) { + if (!fs_searchpaths) { + Com_Error(ERR_FATAL, "Filesystem call made without initialization\n"); } } @@ -306,62 +304,65 @@ static void FS_AssertInitialised( void ) { return a hash value for the filename ================ */ -static long FS_HashFileName( const char *fname, int hashSize ) { - int i; - long hash; - char letter; +static long FS_HashFileName(const char *fname, int hashSize) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); - hash &= (hashSize-1); + hash &= (hashSize - 1); return hash; } static fileHandle_t FS_HandleForFile(void) { - int i; + int i; - for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { - if ( fsh[i].handleFiles.file.o == NULL ) { + for (i = 1; i < MAX_FILE_HANDLES; i++) { + if (fsh[i].handleFiles.file.o == NULL) { return i; } } - Com_Printf( "FS_HandleForFile: all handles taken:\n" ); - for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { - Com_Printf( "%d. %s\n", i, fsh[i].name); + Com_Printf("FS_HandleForFile: all handles taken:\n"); + for (i = 1; i < MAX_FILE_HANDLES; i++) { + Com_Printf("%d. %s\n", i, fsh[i].name); } - Com_Error( ERR_DROP, "FS_HandleForFile: none free" ); + Com_Error(ERR_DROP, "FS_HandleForFile: none free"); return 0; } -static FILE *FS_FileForHandle( fileHandle_t f ) { - if ( f < 1 || f >= MAX_FILE_HANDLES ) { - Com_Error( ERR_DROP, "FS_FileForHandle: out of range" ); +static FILE *FS_FileForHandle(fileHandle_t f) { + if (f < 1 || f >= MAX_FILE_HANDLES) { + Com_Error(ERR_DROP, "FS_FileForHandle: out of range"); } if (fsh[f].zipFile == qtrue) { - Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" ); + Com_Error(ERR_DROP, "FS_FileForHandle: can't get FILE on zip file"); } - if ( ! fsh[f].handleFiles.file.o ) { - Com_Error( ERR_DROP, "FS_FileForHandle: NULL" ); + if (!fsh[f].handleFiles.file.o) { + Com_Error(ERR_DROP, "FS_FileForHandle: NULL"); } return fsh[f].handleFiles.file.o; } -void FS_ForceFlush( fileHandle_t f ) { +void FS_ForceFlush(fileHandle_t f) { FILE *file; file = FS_FileForHandle(f); - setvbuf( file, NULL, _IONBF, 0 ); + setvbuf(file, NULL, _IONBF, 0); } /* @@ -370,13 +371,12 @@ FS_fplength ================ */ -long FS_fplength(FILE *h) -{ - long pos; - long end; +long FS_fplength(FILE *h) { + long pos; + long end; pos = ftell(h); - if ( pos == EOF ) + if (pos == EOF) return EOF; fseek(h, 0, SEEK_END); @@ -395,12 +395,12 @@ it will return the size of the pak file, not the expected size of the file. ================ */ -int FS_filelength( fileHandle_t f ) { - FILE *h; +int FS_filelength(fileHandle_t f) { + FILE *h; h = FS_FileForHandle(f); - if(h == NULL) + if (h == NULL) return EOF; else return FS_fplength(h); @@ -413,17 +413,17 @@ FS_ReplaceSeparators Fix things up differently for win/unix/mac ==================== */ -void FS_ReplaceSeparators( char *path ) { - char *s; +void FS_ReplaceSeparators(char *path) { + char *s; qboolean lastCharWasSep = qfalse; - for ( s = path ; *s ; s++ ) { - if ( *s == '/' || *s == '\\' ) { - if ( !lastCharWasSep ) { + for (s = path; *s; s++) { + if (*s == '/' || *s == '\\') { + if (!lastCharWasSep) { *s = PATH_SEP; lastCharWasSep = qtrue; } else { - memmove (s, s + 1, strlen (s)); + memmove(s, s + 1, strlen(s)); } } else { lastCharWasSep = qfalse; @@ -438,40 +438,40 @@ FS_BuildOSPath Qpath may have either forward or backwards slashes =================== */ -char *FS_BuildOSPath( const char *qpath ) { - char temp[MAX_OSPATH]; +char *FS_BuildOSPath(const char *qpath) { + char temp[MAX_OSPATH]; static char ospath[4][MAX_OSPATH]; static int toggle; - int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) + int nextToggle = (toggle + 1) & 3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) toggle = nextToggle; // Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo) if (qpath[0] == '\\' || qpath[0] == '/') qpath++; - Com_sprintf( temp, sizeof(temp), "/base/%s", qpath ); // FIXME SP used fs_gamedir here as well (not sure if this func is even used) - FS_ReplaceSeparators( temp ); - Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp ); + Com_sprintf(temp, sizeof(temp), "/base/%s", qpath); // FIXME SP used fs_gamedir here as well (not sure if this func is even used) + FS_ReplaceSeparators(temp); + Com_sprintf(ospath[toggle], sizeof(ospath[0]), "%s%s", fs_basepath->string, temp); return ospath[toggle]; } -char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) { - char temp[MAX_OSPATH]; +char *FS_BuildOSPath(const char *base, const char *game, const char *qpath) { + char temp[MAX_OSPATH]; static char ospath[4][MAX_OSPATH]; static int toggle; - int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) + int nextToggle = (toggle + 1) & 3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) toggle = nextToggle; - if( !game || !game[0] ) { + if (!game || !game[0]) { game = fs_gamedir; } - Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath ); - FS_ReplaceSeparators( temp ); - Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp ); + Com_sprintf(temp, sizeof(temp), "/%s/%s", game, qpath); + FS_ReplaceSeparators(temp); + Com_sprintf(ospath[toggle], sizeof(ospath[0]), "%s%s", base, temp); return ospath[toggle]; } @@ -483,33 +483,32 @@ FS_CreatePath Creates any directories needed to store the given filename ============ */ -qboolean FS_CreatePath (char *OSPath) { - char *ofs; - char path[MAX_OSPATH]; +qboolean FS_CreatePath(char *OSPath) { + char *ofs; + char path[MAX_OSPATH]; // make absolutely sure that it can't back up the path // FIXME: is c: allowed??? - if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) { - Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath ); + if (strstr(OSPath, "..") || strstr(OSPath, "::")) { + Com_Printf("WARNING: refusing to create relative path \"%s\"\n", OSPath); return qtrue; } - Q_strncpyz( path, OSPath, sizeof( path ) ); - FS_ReplaceSeparators( path ); + Q_strncpyz(path, OSPath, sizeof(path)); + FS_ReplaceSeparators(path); // Skip creation of the root directory as it will always be there - ofs = strchr( path, PATH_SEP ); - if ( ofs ) { + ofs = strchr(path, PATH_SEP); + if (ofs) { ofs++; } - for (; ofs != NULL && *ofs ; ofs++) { + for (; ofs != NULL && *ofs; ofs++) { if (*ofs == PATH_SEP) { // create the directory *ofs = 0; - if (!Sys_Mkdir (path)) { - Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", - path ); + if (!Sys_Mkdir(path)) { + Com_Error(ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", path); } *ofs = PATH_SEP; } @@ -524,14 +523,13 @@ FS_CheckFilenameIsMutable ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension ================= */ -static void FS_CheckFilenameIsMutable( const char *filename, const char *function ) -{ +static void FS_CheckFilenameIsMutable(const char *filename, const char *function) { // Check if the filename ends with the library, or pk3 extension - if( COM_CompareExtension( filename, DLL_EXT ) - || COM_CompareExtension( filename, ".pk3" ) ) - { - Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due " - "to %s extension", function, filename, COM_GetExtension( filename ) ); + if (COM_CompareExtension(filename, DLL_EXT) || COM_CompareExtension(filename, ".pk3")) { + Com_Error(ERR_FATAL, + "%s: Not allowed to manipulate '%s' due " + "to %s extension", + function, filename, COM_GetExtension(filename)); } } @@ -543,66 +541,63 @@ Copy a fully specified file from one place to another ================= */ // added extra param so behind-the-scenes copying in savegames doesn't clutter up the screen -slc -void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent = qfalse ); -void FS_CopyFile( char *fromOSPath, char *toOSPath, qboolean qbSilent ) { - FILE *f; - int len; - byte *buf; +void FS_CopyFile(char *fromOSPath, char *toOSPath, qboolean qbSilent = qfalse); +void FS_CopyFile(char *fromOSPath, char *toOSPath, qboolean qbSilent) { + FILE *f; + int len; + byte *buf; - FS_CheckFilenameIsMutable( fromOSPath, __func__ ); + FS_CheckFilenameIsMutable(fromOSPath, __func__); - if ( !qbSilent ) - Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath ); + if (!qbSilent) + Com_Printf("copy %s to %s\n", fromOSPath, toOSPath); - f = fopen( fromOSPath, "rb" ); - if ( !f ) { + f = fopen(fromOSPath, "rb"); + if (!f) { return; } - fseek (f, 0, SEEK_END); - len = ftell (f); - fseek (f, 0, SEEK_SET); + fseek(f, 0, SEEK_END); + len = ftell(f); + fseek(f, 0, SEEK_SET); - if ( len == EOF ) - { - fclose( f ); - if ( qbSilent ) + if (len == EOF) { + fclose(f); + if (qbSilent) return; - Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" ); + Com_Error(ERR_FATAL, "Bad file length in FS_CopyFile()"); } // we are using direct malloc instead of Z_Malloc here, so it // probably won't work on a mac... Its only for developers anyway... - buf = (unsigned char *)malloc( len ); - if (fread( buf, 1, len, f ) != (size_t)len) - { - fclose( f ); - free ( buf ); - if ( qbSilent ) + buf = (unsigned char *)malloc(len); + if (fread(buf, 1, len, f) != (size_t)len) { + fclose(f); + free(buf); + if (qbSilent) return; - Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" ); + Com_Error(ERR_FATAL, "Short read in FS_Copyfiles()\n"); } - fclose( f ); + fclose(f); - if( FS_CreatePath( toOSPath ) ) { - free ( buf ); + if (FS_CreatePath(toOSPath)) { + free(buf); return; } - f = fopen( toOSPath, "wb" ); - if ( !f ) { - free ( buf ); + f = fopen(toOSPath, "wb"); + if (!f) { + free(buf); return; } - if (fwrite( buf, 1, len, f ) != (size_t)len) - { - fclose( f ); - free ( buf ); - if ( qbSilent ) + if (fwrite(buf, 1, len, f) != (size_t)len) { + fclose(f); + free(buf); + if (qbSilent) return; - Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" ); + Com_Error(ERR_FATAL, "Short write in FS_Copyfiles()\n"); } - fclose( f ); - free( buf ); + fclose(f); + free(buf); } /* @@ -611,10 +606,10 @@ FS_Remove =========== */ -void FS_Remove( const char *osPath ) { - FS_CheckFilenameIsMutable( osPath, __func__ ); +void FS_Remove(const char *osPath) { + FS_CheckFilenameIsMutable(osPath, __func__); - remove( osPath ); + remove(osPath); } /* @@ -623,11 +618,10 @@ FS_HomeRemove =========== */ -void FS_HomeRemove( const char *homePath ) { - FS_CheckFilenameIsMutable( homePath, __func__ ); +void FS_HomeRemove(const char *homePath) { + FS_CheckFilenameIsMutable(homePath, __func__); - remove( FS_BuildOSPath( fs_homepath->string, - fs_gamedir, homePath ) ); + remove(FS_BuildOSPath(fs_homepath->string, fs_gamedir, homePath)); } // The following functions with "UserGen" in them were added for savegame handling, @@ -635,33 +629,31 @@ void FS_HomeRemove( const char *homePath ) { // "filename" is local to the current gamedir (eg "saves/blah.sav") // -void FS_DeleteUserGenFile( const char *filename ) { - FS_HomeRemove( filename ); -} +void FS_DeleteUserGenFile(const char *filename) { FS_HomeRemove(filename); } // filenames are local (eg "saves/blah.sav") // // return: qtrue = OK // -qboolean FS_MoveUserGenFile( const char *filename_src, const char *filename_dst ) { - char *from_ospath, *to_ospath; +qboolean FS_MoveUserGenFile(const char *filename_src, const char *filename_dst) { + char *from_ospath, *to_ospath; FS_AssertInitialised(); // don't let sound stutter S_ClearSoundBuffer(); - from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_src ); - to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename_dst ); + from_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename_src); + to_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename_dst); - if ( fs_debug->integer ) { - Com_Printf( "FS_MoveUserGenFile: %s --> %s\n", from_ospath, to_ospath ); + if (fs_debug->integer) { + Com_Printf("FS_MoveUserGenFile: %s --> %s\n", from_ospath, to_ospath); } - FS_CheckFilenameIsMutable( to_ospath, __func__ ); + FS_CheckFilenameIsMutable(to_ospath, __func__); - remove( to_ospath ); - return (qboolean)!rename( from_ospath, to_ospath ); + remove(to_ospath); + return (qboolean)!rename(from_ospath, to_ospath); } /* @@ -671,33 +663,33 @@ FS_Rmdir Removes a directory, optionally deleting all files under it =========== */ -void FS_Rmdir( const char *osPath, qboolean recursive ) { - FS_CheckFilenameIsMutable( osPath, __func__ ); +void FS_Rmdir(const char *osPath, qboolean recursive) { + FS_CheckFilenameIsMutable(osPath, __func__); - if ( recursive ) { + if (recursive) { int numfiles; int i; - char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse ); - for ( i = 0; i < numfiles; i++ ) { + char **filesToRemove = Sys_ListFiles(osPath, "", NULL, &numfiles, qfalse); + for (i = 0; i < numfiles; i++) { char fileOsPath[MAX_OSPATH]; - Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] ); - FS_Remove( fileOsPath ); + Com_sprintf(fileOsPath, sizeof(fileOsPath), "%s/%s", osPath, filesToRemove[i]); + FS_Remove(fileOsPath); } - FS_FreeFileList( filesToRemove ); + FS_FreeFileList(filesToRemove); - char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse ); - for ( i = 0; i < numfiles; i++ ) { - if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) { + char **directoriesToRemove = Sys_ListFiles(osPath, "/", NULL, &numfiles, qfalse); + for (i = 0; i < numfiles; i++) { + if (!Q_stricmp(directoriesToRemove[i], ".") || !Q_stricmp(directoriesToRemove[i], "..")) { continue; } char directoryOsPath[MAX_OSPATH]; - Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] ); - FS_Rmdir( directoryOsPath, qtrue ); + Com_sprintf(directoryOsPath, sizeof(directoryOsPath), "%s/%s", osPath, directoriesToRemove[i]); + FS_Rmdir(directoryOsPath, qtrue); } - FS_FreeFileList( directoriesToRemove ); + FS_FreeFileList(directoriesToRemove); } - rmdir( osPath ); + rmdir(osPath); } /* @@ -707,11 +699,10 @@ FS_HomeRmdir Removes a directory, optionally deleting all files under it =========== */ -void FS_HomeRmdir( const char *homePath, qboolean recursive ) { - FS_CheckFilenameIsMutable( homePath, __func__ ); +void FS_HomeRmdir(const char *homePath, qboolean recursive) { + FS_CheckFilenameIsMutable(homePath, __func__); - FS_Rmdir( FS_BuildOSPath( fs_homepath->string, - fs_gamedir, homePath ), recursive ); + FS_Rmdir(FS_BuildOSPath(fs_homepath->string, fs_gamedir, homePath), recursive); } /* @@ -721,14 +712,12 @@ FS_FileInPathExists Tests if path and file exists ================ */ -qboolean FS_FileInPathExists(const char *testpath) -{ +qboolean FS_FileInPathExists(const char *testpath) { FILE *filep; filep = fopen(testpath, "rb"); - if(filep) - { + if (filep) { fclose(filep); return qtrue; } @@ -746,10 +735,7 @@ search the paths. This is to determine if opening a file to write NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards ================ */ -qboolean FS_FileExists( const char *file ) -{ - return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file)); -} +qboolean FS_FileExists(const char *file) { return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file)); } /* ================ @@ -758,12 +744,11 @@ FS_SV_FileExists Tests if the file exists ================ */ -qboolean FS_SV_FileExists( const char *file ) -{ +qboolean FS_SV_FileExists(const char *file) { char *testpath; - testpath = FS_BuildOSPath( fs_homepath->string, file, ""); - testpath[strlen(testpath)-1] = '\0'; + testpath = FS_BuildOSPath(fs_homepath->string, file, ""); + testpath[strlen(testpath) - 1] = '\0'; return FS_FileInPathExists(testpath); } @@ -774,32 +759,32 @@ FS_SV_FOpenFileWrite =========== */ -fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) { +fileHandle_t FS_SV_FOpenFileWrite(const char *filename) { char *ospath; - fileHandle_t f; + fileHandle_t f; FS_AssertInitialised(); - ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_homepath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileWrite: %s\n", ospath); } - FS_CheckFilenameIsMutable( ospath, __func__ ); + FS_CheckFilenameIsMutable(ospath, __func__); - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } - Com_DPrintf( "writing to: %s\n", ospath ); - fsh[f].handleFiles.file.o = fopen( ospath, "wb" ); + Com_DPrintf("writing to: %s\n", ospath); + fsh[f].handleFiles.file.o = fopen(ospath, "wb"); - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { @@ -815,71 +800,64 @@ search for a file somewhere below the home path, base path or cd path we search in that order, matching FS_SV_FOpenFileRead order =========== */ -int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) { +int FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp) { char *ospath; - fileHandle_t f = 0; + fileHandle_t f = 0; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); // don't let sound stutter S_ClearSoundBuffer(); // search homepath - ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); + ospath = FS_BuildOSPath(fs_homepath->string, filename, ""); // remove trailing slash - ospath[strlen(ospath)-1] = '\0'; + ospath[strlen(ospath) - 1] = '\0'; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; - if (!fsh[f].handleFiles.file.o) - { + if (!fsh[f].handleFiles.file.o) { // NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid - if (Q_stricmp(fs_homepath->string,fs_basepath->string)) - { + if (Q_stricmp(fs_homepath->string, fs_basepath->string)) { // search basepath - ospath = FS_BuildOSPath( fs_basepath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_basepath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; - if ( fs_debug->integer ) - { - Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; } - if ( !fsh[f].handleFiles.file.o ) - { + if (!fsh[f].handleFiles.file.o) { f = 0; } } - if (!fsh[f].handleFiles.file.o) - { + if (!fsh[f].handleFiles.file.o) { // search cd path - ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_cdpath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; - if (fs_debug->integer) - { - Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; - if ( !fsh[f].handleFiles.file.o ) - { + if (!fsh[f].handleFiles.file.o) { f = 0; } } @@ -897,31 +875,31 @@ FS_SV_Rename =========== */ -void FS_SV_Rename( const char *from, const char *to, qboolean safe ) { - char *from_ospath, *to_ospath; +void FS_SV_Rename(const char *from, const char *to, qboolean safe) { + char *from_ospath, *to_ospath; FS_AssertInitialised(); // don't let sound stutter S_ClearSoundBuffer(); - from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" ); - to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" ); - from_ospath[strlen(from_ospath)-1] = '\0'; - to_ospath[strlen(to_ospath)-1] = '\0'; + from_ospath = FS_BuildOSPath(fs_homepath->string, from, ""); + to_ospath = FS_BuildOSPath(fs_homepath->string, to, ""); + from_ospath[strlen(from_ospath) - 1] = '\0'; + to_ospath[strlen(to_ospath) - 1] = '\0'; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath); } - if ( safe ) { - FS_CheckFilenameIsMutable( to_ospath, __func__ ); + if (safe) { + FS_CheckFilenameIsMutable(to_ospath, __func__); } - if (rename( from_ospath, to_ospath )) { + if (rename(from_ospath, to_ospath)) { // Failed, try copying it and deleting the original - FS_CopyFile ( from_ospath, to_ospath ); - FS_Remove ( from_ospath ); + FS_CopyFile(from_ospath, to_ospath); + FS_Remove(from_ospath); } } @@ -931,27 +909,27 @@ FS_Rename =========== */ -void FS_Rename( const char *from, const char *to ) { - char *from_ospath, *to_ospath; +void FS_Rename(const char *from, const char *to) { + char *from_ospath, *to_ospath; FS_AssertInitialised(); // don't let sound stutter S_ClearSoundBuffer(); - from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from ); - to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to ); + from_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, from); + to_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, to); - if ( fs_debug->integer ) { - Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath ); + if (fs_debug->integer) { + Com_Printf("FS_Rename: %s --> %s\n", from_ospath, to_ospath); } - FS_CheckFilenameIsMutable( to_ospath, __func__ ); + FS_CheckFilenameIsMutable(to_ospath, __func__); - if (rename( from_ospath, to_ospath )) { + if (rename(from_ospath, to_ospath)) { // Failed, try copying it and deleting the original - FS_CopyFile ( from_ospath, to_ospath ); - FS_Remove ( from_ospath ); + FS_CopyFile(from_ospath, to_ospath); + FS_Remove(from_ospath); } } @@ -966,31 +944,31 @@ There are three cases handled: * normal file: closed with fclose. * file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the - minizip handle to the pak3 remains open. + minizip handle to the pak3 remains open. * file in pak3 archive, opened with "unique" flag: This file did not use - the system minizip handle to the pak3 file, but its own dedicated one. - The dedicated handle is closed with unzClose. + the system minizip handle to the pak3 file, but its own dedicated one. + The dedicated handle is closed with unzClose. =========== */ -void FS_FCloseFile( fileHandle_t f ) { +void FS_FCloseFile(fileHandle_t f) { FS_AssertInitialised(); if (fsh[f].zipFile == qtrue) { - unzCloseCurrentFile( fsh[f].handleFiles.file.z ); - if ( fsh[f].handleFiles.unique ) { - unzClose( fsh[f].handleFiles.file.z ); + unzCloseCurrentFile(fsh[f].handleFiles.file.z); + if (fsh[f].handleFiles.unique) { + unzClose(fsh[f].handleFiles.file.z); } - Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); + Com_Memset(&fsh[f], 0, sizeof(fsh[f])); return; } // we didn't find it as a pak, so close it as a unique file if (fsh[f].handleFiles.file.o) { - fclose (fsh[f].handleFiles.file.o); + fclose(fsh[f].handleFiles.file.o); } - Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); + Com_Memset(&fsh[f], 0, sizeof(fsh[f])); } /* @@ -999,35 +977,35 @@ FS_FOpenFileWrite =========== */ -fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) { - char *ospath; - fileHandle_t f; +fileHandle_t FS_FOpenFileWrite(const char *filename, qboolean safe) { + char *ospath; + fileHandle_t f; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); + ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename); - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileWrite: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileWrite: %s\n", ospath); } - if ( safe ) { - FS_CheckFilenameIsMutable( ospath, __func__ ); + if (safe) { + FS_CheckFilenameIsMutable(ospath, __func__); } - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } // enabling the following line causes a recursive function call loop // when running with +set logfile 1 +set developer 1 - //Com_DPrintf( "writing to: %s\n", ospath ); - fsh[f].handleFiles.file.o = fopen( ospath, "wb" ); + // Com_DPrintf( "writing to: %s\n", ospath ); + fsh[f].handleFiles.file.o = fopen(ospath, "wb"); - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { @@ -1042,33 +1020,33 @@ FS_FOpenFileAppend =========== */ -fileHandle_t FS_FOpenFileAppend( const char *filename ) { - char *ospath; - fileHandle_t f; +fileHandle_t FS_FOpenFileAppend(const char *filename) { + char *ospath; + fileHandle_t f; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); // don't let sound stutter S_ClearSoundBuffer(); - ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); + ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename); - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileAppend: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileAppend: %s\n", ospath); } - FS_CheckFilenameIsMutable( ospath, __func__ ); + FS_CheckFilenameIsMutable(ospath, __func__); - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } - fsh[f].handleFiles.file.o = fopen( ospath, "ab" ); + fsh[f].handleFiles.file.o = fopen(ospath, "ab"); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { f = 0; @@ -1083,8 +1061,8 @@ FS_FilenameCompare Ignore case and separator char distinctions =========== */ -qboolean FS_FilenameCompare( const char *s1, const char *s2 ) { - int c1, c2; +qboolean FS_FilenameCompare(const char *s1, const char *s2) { + int c1, c2; do { c1 = *s1++; @@ -1097,19 +1075,19 @@ qboolean FS_FilenameCompare( const char *s1, const char *s2 ) { c2 -= ('a' - 'A'); } - if ( c1 == '\\' || c1 == ':' ) { + if (c1 == '\\' || c1 == ':') { c1 = '/'; } - if ( c2 == '\\' || c2 == ':' ) { + if (c2 == '\\' || c2 == ':') { c2 = '/'; } if (c1 != c2) { - return qtrue; // strings not equal + return qtrue; // strings not equal } } while (c1); - return qfalse; // strings are equal + return qfalse; // strings are equal } /* @@ -1120,13 +1098,12 @@ Return qtrue if ext matches file extension filename =========== */ -qboolean FS_IsExt(const char *filename, const char *ext, int namelen) -{ +qboolean FS_IsExt(const char *filename, const char *ext, int namelen) { int extlen; extlen = strlen(ext); - if(extlen > namelen) + if (extlen > namelen) return qfalse; filename += namelen - extlen; @@ -1143,16 +1120,14 @@ Return qtrue if filename has a demo extension */ #define DEMO_EXTENSION "dm_" -qboolean FS_IsDemoExt(const char *filename, int namelen) -{ +qboolean FS_IsDemoExt(const char *filename, int namelen) { const char *ext_test; ext_test = strrchr(filename, '.'); - if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1)) - { + if (ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1)) { int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION)); - if(protocol == PROTOCOL_VERSION) + if (protocol == PROTOCOL_VERSION) return qtrue; } @@ -1161,29 +1136,25 @@ qboolean FS_IsDemoExt(const char *filename, int namelen) #ifdef _WIN32 -bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) -{ +bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) { bool bSuccess = false; HANDLE hFile = INVALID_HANDLE_VALUE; - hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file - GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode - FILE_SHARE_READ, // DWORD dwShareMode, // share mode - NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes - OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create - FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes - NULL // HANDLE hTemplateFile // handle to file with attributes to - ); - - if (hFile != INVALID_HANDLE_VALUE) - { - if (GetFileTime(hFile, // handle to file - NULL, // LPFILETIME lpCreationTime - NULL, // LPFILETIME lpLastAccessTime - &ft // LPFILETIME lpLastWriteTime - ) - ) - { + hFile = CreateFile(psFileName, // LPCTSTR lpFileName, // pointer to name of the file + GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode + FILE_SHARE_READ, // DWORD dwShareMode, // share mode + NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes + OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create + FILE_FLAG_NO_BUFFERING, // DWORD dwFlagsAndAttributes, // file attributes + NULL // HANDLE hTemplateFile // handle to file with attributes to + ); + + if (hFile != INVALID_HANDLE_VALUE) { + if (GetFileTime(hFile, // handle to file + NULL, // LPFILETIME lpCreationTime + NULL, // LPFILETIME lpLastAccessTime + &ft // LPFILETIME lpLastWriteTime + )) { bSuccess = true; } @@ -1193,32 +1164,24 @@ bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) return bSuccess; } -bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ ) -{ +bool Sys_FileOutOfDate(LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */) { FILETIME ftFinalFile, ftDataFile; - if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile)) - { + if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile)) { // timer res only accurate to within 2 seconds on FAT, so can't do exact compare... // - //LONG l = CompareFileTime( &ftFinalFile, &ftDataFile ); - if ( (abs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) && - ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime - ) - { - return false; // file not out of date, ie use it. + // LONG l = CompareFileTime( &ftFinalFile, &ftDataFile ); + if ((abs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000) && ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime) { + return false; // file not out of date, ie use it. } - return true; // flag return code to copy over a replacement version of this file + return true; // flag return code to copy over a replacement version of this file } - // extra error check, report as suspicious if you find a file locally but not out on the net.,. // - if (com_developer->integer) - { - if (!Sys_GetFileTime(psDataFileName, ftDataFile)) - { - Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName); + if (com_developer->integer) { + if (!Sys_GetFileTime(psDataFileName, ftDataFile)) { + Com_Printf("Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName); } } @@ -1227,14 +1190,12 @@ bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName #endif // _WIN32 -bool FS_FileCacheable(const char* const filename) -{ - extern cvar_t *com_buildScript; - if (com_buildScript && com_buildScript->integer) - { +bool FS_FileCacheable(const char *const filename) { + extern cvar_t *com_buildScript; + if (com_buildScript && com_buildScript->integer) { return true; } - return( strchr(filename, '/') != 0 ); + return (strchr(filename, '/') != 0); } /* @@ -1247,52 +1208,52 @@ Used for streaming data out of either a separate file or a ZIP file. =========== */ -extern qboolean com_fullyInitialized; - -long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) { - searchpath_t *search; - char *netpath; - pack_t *pak; - fileInPack_t *pakFile; - directory_t *dir; - long hash; - //unz_s *zfi; - //void *temp; - bool isUserConfig = false; +extern qboolean com_fullyInitialized; + +long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { + searchpath_t *search; + char *netpath; + pack_t *pak; + fileInPack_t *pakFile; + directory_t *dir; + long hash; + // unz_s *zfi; + // void *temp; + bool isUserConfig = false; hash = 0; FS_AssertInitialised(); - if ( file == NULL ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" ); + if (file == NULL) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n"); } - if ( !filename ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" ); + if (!filename) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n"); } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { *file = 0; return -1; } // make sure the q3key file is only readable by the quake3.exe at initialization // any other time the key should only be accessed in memory using the provided functions - if( com_fullyInitialized && strstr( filename, "q3key" ) ) { + if (com_fullyInitialized && strstr(filename, "q3key")) { *file = 0; return -1; } - isUserConfig = !Q_stricmp( filename, "autoexec_sp.cfg" ) || !Q_stricmp( filename, Q3CONFIG_NAME ); + isUserConfig = !Q_stricmp(filename, "autoexec_sp.cfg") || !Q_stricmp(filename, Q3CONFIG_NAME); // // search through the path, one element at a time @@ -1308,19 +1269,18 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // qboolean bFasterToReOpenUsingNewLocalFile = qfalse; - do - { + do { bFasterToReOpenUsingNewLocalFile = qfalse; - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // - if ( search->pack ) { + if (search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); } // is the element a pak file? - if ( search->pack && search->pack->hashTable[hash] ) { + if (search->pack && search->pack->hashTable[hash]) { // autoexec_sp.cfg and openjk_sp.cfg can only be loaded outside of pk3 files. - if ( isUserConfig ) { + if (isUserConfig) { continue; } @@ -1329,19 +1289,19 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { // found it! - if ( uniqueFILE ) { + if (uniqueFILE) { // open a new file on the pakfile - fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename); + fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename); if (fsh[*file].handleFiles.file.z == NULL) { - Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename); + Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename); } } else { fsh[*file].handleFiles.file.z = pak->handle; } - Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) ); + Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qtrue; // set the file position in the zip file (also sets the current file info) @@ -1366,22 +1326,21 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique fsh[*file].zipFilePos = pakFile->pos; fsh[*file].zipFileLen = pakFile->len; - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n", - filename, pak->pakFilename ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n", filename, pak->pakFilename); } return pakFile->len; } pakFile = pakFile->next; - } while(pakFile != NULL); - } else if ( search->dir ) { + } while (pakFile != NULL); + } else if (search->dir) { // check a file in the directory tree dir = search->dir; - netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename ); - fsh[*file].handleFiles.file.o = fopen (netpath, "rb"); - if ( !fsh[*file].handleFiles.file.o ) { + netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); + fsh[*file].handleFiles.file.o = fopen(netpath, "rb"); + if (!fsh[*file].handleFiles.file.o) { continue; } @@ -1390,85 +1349,71 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // if the time/date stamp != the network version (so it'll loop round again and use the network path, // which comes later in the search order) // - if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string ) - && FS_FileCacheable(filename) ) - { - if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) )) - { + if (fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp(dir->path, fs_basepath->string) && FS_FileCacheable(filename)) { + if (Sys_FileOutOfDate(netpath, FS_BuildOSPath(fs_cdpath->string, dir->gamedir, filename))) { fclose(fsh[*file].handleFiles.file.o); fsh[*file].handleFiles.file.o = 0; - continue; //carry on to find the cdpath version. + continue; // carry on to find the cdpath version. } } #endif - Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) ); + Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qfalse; - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename, - dir->path, PATH_SEP, dir->gamedir ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename, dir->path, PATH_SEP, dir->gamedir); } #ifdef _WIN32 // if we are getting it from the cdpath, optionally copy it // to the basepath - if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) { - char *copypath; - - copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename ); - switch ( fs_copyfiles->integer ) - { - default: - case 1: - { - FS_CopyFile( netpath, copypath ); - } - break; - - case 2: - { + if (fs_copyfiles->integer && !Q_stricmp(dir->path, fs_cdpath->string)) { + char *copypath; + + copypath = FS_BuildOSPath(fs_basepath->string, dir->gamedir, filename); + switch (fs_copyfiles->integer) { + default: + case 1: { + FS_CopyFile(netpath, copypath); + } break; + + case 2: { + + if (FS_FileCacheable(filename)) { + // maybe change this to Com_DPrintf? On the other hand... + // + Com_Printf("fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath); + + FS_CreatePath(copypath); + + bool bOk = true; + if (!CopyFile(netpath, copypath, FALSE)) { + DWORD dwAttrs = GetFileAttributes(copypath); + SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY); + bOk = !!CopyFile(netpath, copypath, FALSE); + } - if (FS_FileCacheable(filename) ) - { - // maybe change this to Com_DPrintf? On the other hand... + if (bOk) { + // clear this handle and setup for re-opening of the new local copy... // - Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath ); - - FS_CreatePath( copypath ); - - bool bOk = true; - if (!CopyFile( netpath, copypath, FALSE )) - { - DWORD dwAttrs = GetFileAttributes(copypath); - SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY); - bOk = !!CopyFile( netpath, copypath, FALSE ); - } - - if (bOk) - { - // clear this handle and setup for re-opening of the new local copy... - // - bFasterToReOpenUsingNewLocalFile = qtrue; - fclose(fsh[*file].handleFiles.file.o); - fsh[*file].handleFiles.file.o = NULL; - } + bFasterToReOpenUsingNewLocalFile = qtrue; + fclose(fsh[*file].handleFiles.file.o); + fsh[*file].handleFiles.file.o = NULL; } } - break; + } break; } } #endif - if (bFasterToReOpenUsingNewLocalFile) - { - break; // and re-read the local copy, not the net version + if (bFasterToReOpenUsingNewLocalFile) { + break; // and re-read the local copy, not the net version } return FS_fplength(fsh[*file].handleFiles.file.o); } } - } - while ( bFasterToReOpenUsingNewLocalFile ); + } while (bFasterToReOpenUsingNewLocalFile); - Com_DPrintf ("Can't find %s\n", filename); + Com_DPrintf("Can't find %s\n", filename); *file = 0; return -1; } @@ -1480,15 +1425,15 @@ FS_Read Properly handles partial reads ================= */ -int FS_Read( void *buffer, int len, fileHandle_t f ) { - int block, remaining; - int read; - byte *buf; - int tries; +int FS_Read(void *buffer, int len, fileHandle_t f) { + int block, remaining; + int read; + byte *buf; + int tries; FS_AssertInitialised(); - if ( !f ) { + if (!f) { return 0; } @@ -1500,19 +1445,19 @@ int FS_Read( void *buffer, int len, fileHandle_t f ) { tries = 0; while (remaining) { block = remaining; - read = fread (buf, 1, block, fsh[f].handleFiles.file.o); + read = fread(buf, 1, block, fsh[f].handleFiles.file.o); if (read == 0) { // we might have been trying to read from a CD, which // sometimes returns a 0 read on windows if (!tries) { tries = 1; } else { - return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read"); + return len - remaining; // Com_Error (ERR_FATAL, "FS_Read: 0 bytes read"); } } if (read == -1) { - Com_Error (ERR_FATAL, "FS_Read: -1 bytes read"); + Com_Error(ERR_FATAL, "FS_Read: -1 bytes read"); } remaining -= read; @@ -1531,16 +1476,16 @@ FS_Write Properly handles partial writes ================= */ -int FS_Write( const void *buffer, int len, fileHandle_t h ) { - int block, remaining; - int written; - byte *buf; - int tries; - FILE *f; +int FS_Write(const void *buffer, int len, fileHandle_t h) { + int block, remaining; + int written; + byte *buf; + int tries; + FILE *f; FS_AssertInitialised(); - if ( !h ) { + if (!h) { return 0; } @@ -1551,38 +1496,38 @@ int FS_Write( const void *buffer, int len, fileHandle_t h ) { tries = 0; while (remaining) { block = remaining; - written = fwrite (buf, 1, block, f); + written = fwrite(buf, 1, block, f); if (written == 0) { if (!tries) { tries = 1; } else { - Com_Printf( "FS_Write: 0 bytes written\n" ); + Com_Printf("FS_Write: 0 bytes written\n"); return 0; } } if (written == -1) { - Com_Printf( "FS_Write: -1 bytes written\n" ); + Com_Printf("FS_Write: -1 bytes written\n"); return 0; } remaining -= written; buf += written; } - if ( fsh[h].handleSync ) { - fflush( f ); + if (fsh[h].handleSync) { + fflush(f); } return len; } -#define MAXPRINTMSG 4096 -void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) { - va_list argptr; - char msg[MAXPRINTMSG]; +#define MAXPRINTMSG 4096 +void QDECL FS_Printf(fileHandle_t h, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); FS_Write(msg, strlen(msg), h); } @@ -1594,74 +1539,74 @@ FS_Seek ================= */ -int FS_Seek( fileHandle_t f, long offset, int origin ) { - int _origin; +int FS_Seek(fileHandle_t f, long offset, int origin) { + int _origin; FS_AssertInitialised(); if (fsh[f].zipFile == qtrue) { - //FIXME: this is really, really crappy + // FIXME: this is really, really crappy //(but better than what was here before) - byte buffer[PK3_SEEK_BUFFER_SIZE]; - int remainder; - int currentPosition = FS_FTell( f ); + byte buffer[PK3_SEEK_BUFFER_SIZE]; + int remainder; + int currentPosition = FS_FTell(f); // change negative offsets into FS_SEEK_SET - if ( offset < 0 ) { - switch( origin ) { - case FS_SEEK_END: - remainder = fsh[f].zipFileLen + offset; - break; + if (offset < 0) { + switch (origin) { + case FS_SEEK_END: + remainder = fsh[f].zipFileLen + offset; + break; - case FS_SEEK_CUR: - remainder = currentPosition + offset; - break; + case FS_SEEK_CUR: + remainder = currentPosition + offset; + break; - case FS_SEEK_SET: - default: - remainder = 0; - break; + case FS_SEEK_SET: + default: + remainder = 0; + break; } - if ( remainder < 0 ) { + if (remainder < 0) { remainder = 0; } origin = FS_SEEK_SET; } else { - if ( origin == FS_SEEK_END ) { + if (origin == FS_SEEK_END) { remainder = fsh[f].zipFileLen - currentPosition + offset; } else { remainder = offset; } } - switch( origin ) { - case FS_SEEK_SET: - if ( remainder == currentPosition ) { - return offset; - } - unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos); - unzOpenCurrentFile(fsh[f].handleFiles.file.z); - //fallthrough - - case FS_SEEK_END: - case FS_SEEK_CUR: - while( remainder > PK3_SEEK_BUFFER_SIZE ) { - FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f ); - remainder -= PK3_SEEK_BUFFER_SIZE; - } - FS_Read( buffer, remainder, f ); + switch (origin) { + case FS_SEEK_SET: + if (remainder == currentPosition) { return offset; + } + unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos); + unzOpenCurrentFile(fsh[f].handleFiles.file.z); + // fallthrough - default: - Com_Error( ERR_FATAL, "Bad origin in FS_Seek" ); - return -1; + case FS_SEEK_END: + case FS_SEEK_CUR: + while (remainder > PK3_SEEK_BUFFER_SIZE) { + FS_Read(buffer, PK3_SEEK_BUFFER_SIZE, f); + remainder -= PK3_SEEK_BUFFER_SIZE; + } + FS_Read(buffer, remainder, f); + return offset; + + default: + Com_Error(ERR_FATAL, "Bad origin in FS_Seek"); + return -1; } } else { FILE *file; file = FS_FileForHandle(f); - switch( origin ) { + switch (origin) { case FS_SEEK_CUR: _origin = SEEK_CUR; break; @@ -1673,11 +1618,11 @@ int FS_Seek( fileHandle_t f, long offset, int origin ) { break; default: _origin = SEEK_CUR; - Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" ); + Com_Error(ERR_FATAL, "Bad origin in FS_Seek\n"); break; } - return fseek( file, offset, _origin ); + return fseek(file, offset, _origin); } } @@ -1689,27 +1634,27 @@ CONVENIENCE FUNCTIONS FOR ENTIRE FILES ====================================================================================== */ -int FS_FileIsInPAK(const char *filename ) { - searchpath_t *search; - pack_t *pak; - fileInPack_t *pakFile; - long hash = 0; +int FS_FileIsInPAK(const char *filename) { + searchpath_t *search; + pack_t *pak; + fileInPack_t *pakFile; + long hash = 0; FS_AssertInitialised(); - if ( !filename ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" ); + if (!filename) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n"); } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { return -1; } @@ -1717,23 +1662,23 @@ int FS_FileIsInPAK(const char *filename ) { // search through the path, one element at a time // - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // if (search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); } // is the element a pak file? - if ( search->pack && search->pack->hashTable[hash] ) { + if (search->pack && search->pack->hashTable[hash]) { // look through all the pak file elements pak = search->pack; pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { return 1; } pakFile = pakFile->next; - } while(pakFile != NULL); + } while (pakFile != NULL); } } return -1; @@ -1747,58 +1692,58 @@ Filename are relative to the quake search path a null buffer will just return the file length without loading ============ */ -long FS_ReadFile( const char *qpath, void **buffer ) { - fileHandle_t h; - byte* buf; - long len; +long FS_ReadFile(const char *qpath, void **buffer) { + fileHandle_t h; + byte *buf; + long len; FS_AssertInitialised(); - if ( !qpath || !qpath[0] ) { - Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" ); + if (!qpath || !qpath[0]) { + Com_Error(ERR_FATAL, "FS_ReadFile with empty name\n"); } // stop sounds from repeating S_ClearSoundBuffer(); - buf = NULL; // quiet compiler warning + buf = NULL; // quiet compiler warning // look for it in the filesystem or pack files - len = FS_FOpenFileRead( qpath, &h, qfalse ); - if ( h == 0 ) { - if ( buffer ) { + len = FS_FOpenFileRead(qpath, &h, qfalse); + if (h == 0) { + if (buffer) { *buffer = NULL; } return -1; } - if ( !buffer ) { - FS_FCloseFile( h); + if (!buffer) { + FS_FCloseFile(h); return len; } fs_loadCount++; - buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse); - buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool + buf = (byte *)Z_Malloc(len + 1, TAG_FILESYS, qfalse); + buf[len] = '\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool *buffer = buf; Z_Label(buf, qpath); // PRECACE CHECKER! #ifndef FINAL_BUILD - if (com_sv_running && com_sv_running->integer && cls.state >= CA_ACTIVE) { //com_cl_running - if (strncmp(qpath,"menu/",5) ) { - Com_DPrintf( S_COLOR_MAGENTA"FS_ReadFile: %s NOT PRECACHED!\n", qpath ); + if (com_sv_running && com_sv_running->integer && cls.state >= CA_ACTIVE) { // com_cl_running + if (strncmp(qpath, "menu/", 5)) { + Com_DPrintf(S_COLOR_MAGENTA "FS_ReadFile: %s NOT PRECACHED!\n", qpath); } } #endif - FS_Read (buf, len, h); + FS_Read(buf, len, h); // guarantee that it will have a trailing 0 for string operations buf[len] = 0; - FS_FCloseFile( h ); + FS_FCloseFile(h); return len; } @@ -1807,13 +1752,13 @@ long FS_ReadFile( const char *qpath, void **buffer ) { FS_FreeFile ============= */ -void FS_FreeFile( void *buffer ) { +void FS_FreeFile(void *buffer) { FS_AssertInitialised(); - if ( !buffer ) { - Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" ); + if (!buffer) { + Com_Error(ERR_FATAL, "FS_FreeFile( NULL )"); } - Z_Free( buffer ); + Z_Free(buffer); } /* @@ -1823,24 +1768,24 @@ FS_WriteFile Filename are reletive to the quake search path ============ */ -void FS_WriteFile( const char *qpath, const void *buffer, int size ) { +void FS_WriteFile(const char *qpath, const void *buffer, int size) { fileHandle_t f; FS_AssertInitialised(); - if ( !qpath || !buffer ) { - Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" ); + if (!qpath || !buffer) { + Com_Error(ERR_FATAL, "FS_WriteFile: NULL parameter"); } - f = FS_FOpenFileWrite( qpath ); - if ( !f ) { - Com_Printf( "Failed to open %s\n", qpath ); + f = FS_FOpenFileWrite(qpath); + if (!f) { + Com_Printf("Failed to open %s\n", qpath); return; } - FS_Write( buffer, size, f ); + FS_Write(buffer, size, f); - FS_FCloseFile( f ); + FS_FCloseFile(f); } /* @@ -1859,34 +1804,32 @@ Creates a new pak_t in the search chain for the contents of a zip file. ================= */ -static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) -{ - fileInPack_t *buildBuffer; - pack_t *pack; - unzFile uf; - int err; +static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename) { + fileInPack_t *buildBuffer; + pack_t *pack; + unzFile uf; + int err; unz_global_info gi; - char filename_inzip[MAX_ZPATH]; - unz_file_info file_info; - int len; - size_t i; - long hash; - int fs_numHeaderLongs; - int *fs_headerLongs; - char *namePtr; + char filename_inzip[MAX_ZPATH]; + unz_file_info file_info; + int len; + size_t i; + long hash; + int fs_numHeaderLongs; + int *fs_headerLongs; + char *namePtr; fs_numHeaderLongs = 0; uf = unzOpen(zipfile); - err = unzGetGlobalInfo (uf,&gi); + err = unzGetGlobalInfo(uf, &gi); if (err != UNZ_OK) return NULL; len = 0; unzGoToFirstFile(uf); - for (i = 0; i < gi.number_entry; i++) - { + for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; @@ -1895,9 +1838,9 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) unzGoToNextFile(uf); } - buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue ); - namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t ); - fs_headerLongs = (int *)Z_Malloc( gi.number_entry * sizeof(int), TAG_FILESYS, qtrue ); + buildBuffer = (struct fileInPack_s *)Z_Malloc((gi.number_entry * sizeof(fileInPack_t)) + len, TAG_FILESYS, qtrue); + namePtr = ((char *)buildBuffer) + gi.number_entry * sizeof(fileInPack_t); + fs_headerLongs = (int *)Z_Malloc(gi.number_entry * sizeof(int), TAG_FILESYS, qtrue); // get the hash table size from the number of files in the zip // because lots of custom pk3 files have less than 32 or 64 files @@ -1907,27 +1850,26 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) } } - pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue ); + pack = (pack_t *)Z_Malloc(sizeof(pack_t) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue); pack->hashSize = i; - pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t )); - for(int j = 0; j < pack->hashSize; j++) { + pack->hashTable = (fileInPack_t **)(((char *)pack) + sizeof(pack_t)); + for (int j = 0; j < pack->hashSize; j++) { pack->hashTable[j] = NULL; } - Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) ); - Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) ); + Q_strncpyz(pack->pakFilename, zipfile, sizeof(pack->pakFilename)); + Q_strncpyz(pack->pakBasename, basename, sizeof(pack->pakBasename)); // strip .pk3 if needed - if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) { - pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0; + if (strlen(pack->pakBasename) > 4 && !Q_stricmp(pack->pakBasename + strlen(pack->pakBasename) - 4, ".pk3")) { + pack->pakBasename[strlen(pack->pakBasename) - 4] = 0; } pack->handle = uf; pack->numfiles = gi.number_entry; unzGoToFirstFile(uf); - for (i = 0; i < gi.number_entry; i++) - { + for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; @@ -1935,10 +1877,10 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) if (file_info.uncompressed_size > 0) { fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc); } - Q_strlwr( filename_inzip ); + Q_strlwr(filename_inzip); hash = FS_HashFileName(filename_inzip, pack->hashSize); buildBuffer[i].name = namePtr; - strcpy( buildBuffer[i].name, filename_inzip ); + strcpy(buildBuffer[i].name, filename_inzip); namePtr += strlen(filename_inzip) + 1; // store the file position in the zip buildBuffer[i].pos = unzGetOffset(uf); @@ -1948,8 +1890,8 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) unzGoToNextFile(uf); } - pack->checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs ); - pack->checksum = LittleLong( pack->checksum ); + pack->checksum = Com_BlockChecksum(fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs); + pack->checksum = LittleLong(pack->checksum); Z_Free(fs_headerLongs); @@ -1965,8 +1907,7 @@ Frees a pak structure and releases all associated resources ================= */ -void FS_FreePak(pack_t *thepak) -{ +void FS_FreePak(pack_t *thepak) { unzClose(thepak->handle); Z_Free(thepak->buildBuffer); Z_Free(thepak); @@ -1980,9 +1921,9 @@ DIRECTORY SCANNING FUNCTIONS ================================================================================= */ -#define MAX_FOUND_FILES 0x1000 +#define MAX_FOUND_FILES 0x1000 -static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { +static int FS_ReturnPath(const char *zname, char *zpath, int *depth) { int len, at, newdep; newdep = 0; @@ -1990,9 +1931,8 @@ static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { len = 0; at = 0; - while(zname[at] != 0) - { - if (zname[at]=='/' || zname[at]=='\\') { + while (zname[at] != 0) { + if (zname[at] == '/' || zname[at] == '\\') { len = at; newdep++; } @@ -2010,18 +1950,18 @@ static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { FS_AddFileToList ================== */ -static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) { - int i; +static int FS_AddFileToList(char *name, char *list[MAX_FOUND_FILES], int nfiles) { + int i; - if ( nfiles == MAX_FOUND_FILES - 1 ) { + if (nfiles == MAX_FOUND_FILES - 1) { return nfiles; } - for ( i = 0 ; i < nfiles ; i++ ) { - if ( !Q_stricmp( name, list[i] ) ) { - return nfiles; // allready in list + for (i = 0; i < nfiles; i++) { + if (!Q_stricmp(name, list[i])) { + return nfiles; // allready in list } } - list[nfiles] = CopyString( name ); + list[nfiles] = CopyString(name); nfiles++; return nfiles; @@ -2035,112 +1975,111 @@ Returns a uniqued list of files that match the given criteria from all search paths =============== */ -char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) { - int nfiles; - char **listCopy; - char *list[MAX_FOUND_FILES]; - searchpath_t *search; - int i; - int pathLength; - int extensionLength; - int length, pathDepth, temp; - pack_t *pak; - fileInPack_t *buildBuffer; - char zpath[MAX_ZPATH]; +char **FS_ListFilteredFiles(const char *path, const char *extension, char *filter, int *numfiles) { + int nfiles; + char **listCopy; + char *list[MAX_FOUND_FILES]; + searchpath_t *search; + int i; + int pathLength; + int extensionLength; + int length, pathDepth, temp; + pack_t *pak; + fileInPack_t *buildBuffer; + char zpath[MAX_ZPATH]; FS_AssertInitialised(); - if ( !path ) { + if (!path) { *numfiles = 0; return NULL; } - if ( !extension ) { + if (!extension) { extension = ""; } - pathLength = strlen( path ); - if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) { + pathLength = strlen(path); + if (path[pathLength - 1] == '\\' || path[pathLength - 1] == '/') { pathLength--; } - extensionLength = strlen( extension ); + extensionLength = strlen(extension); nfiles = 0; FS_ReturnPath(path, zpath, &pathDepth); // // search through the path, one element at a time, adding to list // - for (search = fs_searchpaths ; search ; search = search->next) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? if (search->pack) { // look through all the pak file elements pak = search->pack; buildBuffer = pak->buildBuffer; for (i = 0; i < pak->numfiles; i++) { - char *name; - int zpathLen, depth; + char *name; + int zpathLen, depth; // check for directory match name = buildBuffer[i].name; // if (filter) { // case insensitive - if (!Com_FilterPath( filter, name, qfalse )) + if (!Com_FilterPath(filter, name, qfalse)) continue; // unique the match - nfiles = FS_AddFileToList( name, list, nfiles ); - } - else { + nfiles = FS_AddFileToList(name, list, nfiles); + } else { zpathLen = FS_ReturnPath(name, zpath, &depth); - if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) { + if ((depth - pathDepth) > 2 || pathLength > zpathLen || Q_stricmpn(name, path, pathLength)) { continue; } // check for extension match - length = strlen( name ); - if ( length < extensionLength ) { + length = strlen(name); + if (length < extensionLength) { continue; } - if ( Q_stricmp( name + length - extensionLength, extension ) ) { + if (Q_stricmp(name + length - extensionLength, extension)) { continue; } // unique the match temp = pathLength; if (pathLength) { - temp++; // include the '/' + temp++; // include the '/' } - nfiles = FS_AddFileToList( name + temp, list, nfiles ); + nfiles = FS_AddFileToList(name + temp, list, nfiles); } } } else if (search->dir) { // scan for files in the filesystem - char *netpath; - int numSysFiles; - char **sysFiles; - char *name; - - netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path ); - sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse ); - for ( i = 0 ; i < numSysFiles ; i++ ) { + char *netpath; + int numSysFiles; + char **sysFiles; + char *name; + + netpath = FS_BuildOSPath(search->dir->path, search->dir->gamedir, path); + sysFiles = Sys_ListFiles(netpath, extension, filter, &numSysFiles, qfalse); + for (i = 0; i < numSysFiles; i++) { // unique the match name = sysFiles[i]; - nfiles = FS_AddFileToList( name, list, nfiles ); + nfiles = FS_AddFileToList(name, list, nfiles); } - Sys_FreeFileList( sysFiles ); + Sys_FreeFileList(sysFiles); } } // return a copy of the list *numfiles = nfiles; - if ( !nfiles ) { + if (!nfiles) { return NULL; } - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS, qfalse ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_FILESYS, qfalse); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; @@ -2153,40 +2092,37 @@ char **FS_ListFilteredFiles( const char *path, const char *extension, char *filt FS_ListFiles ================= */ -char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) { - return FS_ListFilteredFiles( path, extension, NULL, numfiles ); -} +char **FS_ListFiles(const char *path, const char *extension, int *numfiles) { return FS_ListFilteredFiles(path, extension, NULL, numfiles); } /* ================= FS_FreeFileList ================= */ -void FS_FreeFileList( char **fileList ) { - //rwwRMG - changed to fileList to not conflict with list type - int i; +void FS_FreeFileList(char **fileList) { + // rwwRMG - changed to fileList to not conflict with list type + int i; FS_AssertInitialised(); - if ( !fileList ) { + if (!fileList) { return; } - for ( i = 0 ; fileList[i] ; i++ ) { - Z_Free( fileList[i] ); + for (i = 0; fileList[i]; i++) { + Z_Free(fileList[i]); } - Z_Free( fileList ); + Z_Free(fileList); } - /* ================ FS_GetFileList ================ */ -int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { - int nFiles, i, nTotal, nLen; +int FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize) { + int nFiles, i, nTotal, nLen; char **pFiles = NULL; *listbuf = 0; @@ -2199,14 +2135,13 @@ int FS_GetFileList( const char *path, const char *extension, char *listbuf, int pFiles = FS_ListFiles(path, extension, &nFiles); - for (i =0; i < nFiles; i++) { + for (i = 0; i < nFiles; i++) { nLen = strlen(pFiles[i]) + 1; if (nTotal + nLen + 1 < bufsize) { strcpy(listbuf, pFiles[i]); listbuf += nLen; nTotal += nLen; - } - else { + } else { nFiles = i; break; } @@ -2222,20 +2157,17 @@ int FS_GetFileList( const char *path, const char *extension, char *listbuf, int Sys_ConcatenateFileLists mkv: Naive implementation. Concatenates three lists into a - new list, and frees the old lists from the heap. + new list, and frees the old lists from the heap. bk001129 - from cvs1.17 (mkv) FIXME TTimo those two should move to common.c next to Sys_ListFiles ======================= */ -static unsigned int Sys_CountFileList(char **fileList) -{ +static unsigned int Sys_CountFileList(char **fileList) { int i = 0; - if (fileList) - { - while (*fileList) - { + if (fileList) { + while (*fileList) { fileList++; i++; } @@ -2243,17 +2175,16 @@ static unsigned int Sys_CountFileList(char **fileList) return i; } -static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 ) -{ +static char **Sys_ConcatenateFileLists(char **list0, char **list1, char **list2) { int totalLength = 0; - char** cat = NULL, **dst, **src; + char **cat = NULL, **dst, **src; totalLength += Sys_CountFileList(list0); totalLength += Sys_CountFileList(list1); totalLength += Sys_CountFileList(list2); /* Create new list. */ - dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue ); + dst = cat = (char **)Z_Malloc((totalLength + 1) * sizeof(char *), TAG_FILESYS, qtrue); /* Copy over lists. */ if (list0) { @@ -2274,16 +2205,19 @@ static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 // Free our old lists. // NOTE: not freeing their content, it's been merged in dst and still being used - if (list0) Z_Free( list0 ); - if (list1) Z_Free( list1 ); - if (list2) Z_Free( list2 ); + if (list0) + Z_Free(list0); + if (list1) + Z_Free(list1); + if (list2) + Z_Free(list2); return cat; } //#endif // For base game mod listing -const char *SE_GetString( const char *psPackageAndStringReference ); +const char *SE_GetString(const char *psPackageAndStringReference); /* ================ @@ -2294,8 +2228,8 @@ A mod directory is a peer to base with a pk3 in it The directories are searched in base path, cd path and home path ================ */ -int FS_GetModList( char *listbuf, int bufsize ) { - int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen; +int FS_GetModList(char *listbuf, int bufsize) { + int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen; char **pFiles = NULL; char **pPaks = NULL; char *name, *path; @@ -2311,23 +2245,22 @@ int FS_GetModList( char *listbuf, int bufsize ) { *listbuf = 0; nMods = nPotential = nTotal = 0; - pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue ); - pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue ); - pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue ); + pFiles0 = Sys_ListFiles(fs_homepath->string, NULL, NULL, &dummy, qtrue); + pFiles1 = Sys_ListFiles(fs_basepath->string, NULL, NULL, &dummy, qtrue); + pFiles2 = Sys_ListFiles(fs_cdpath->string, NULL, NULL, &dummy, qtrue); // we searched for mods in the three paths // it is likely that we have duplicate names now, which we will cleanup below - pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 ); + pFiles = Sys_ConcatenateFileLists(pFiles0, pFiles1, pFiles2); nPotential = Sys_CountFileList(pFiles); - for ( i = 0 ; i < nPotential ; i++ ) { + for (i = 0; i < nPotential; i++) { name = pFiles[i]; // NOTE: cleaner would involve more changes // ignore duplicate mod directories - if (i!=0) { + if (i != 0) { bDrop = qfalse; - for(j=0; jstring, name, "" ); + path = FS_BuildOSPath(fs_basepath->string, name, ""); nPaks = 0; pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); - Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present + Sys_FreeFileList(pPaks); // we only use Sys_ListFiles to check wether .pk3 files are present /* Try on cd path */ - if( nPaks <= 0 ) { - path = FS_BuildOSPath( fs_cdpath->string, name, "" ); + if (nPaks <= 0) { + path = FS_BuildOSPath(fs_cdpath->string, name, ""); nPaks = 0; - pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse ); - Sys_FreeFileList( pPaks ); + pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); + Sys_FreeFileList(pPaks); } /* try on home path */ - if ( nPaks <= 0 ) - { - path = FS_BuildOSPath( fs_homepath->string, name, "" ); + if (nPaks <= 0) { + path = FS_BuildOSPath(fs_homepath->string, name, ""); nPaks = 0; - pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse ); - Sys_FreeFileList( pPaks ); + pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); + Sys_FreeFileList(pPaks); } if (nPaks > 0) { - bool isBase = !Q_stricmp( name, BASEGAME ); + bool isBase = !Q_stricmp(name, BASEGAME); nLen = isBase ? 1 : strlen(name) + 1; // nLen is the length of the mod path // we need to see if there is a description available descPath[0] = '\0'; strcpy(descPath, name); strcat(descPath, "/description.txt"); - nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle ); - if ( nDescLen > 0 && descHandle) { + nDescLen = FS_SV_FOpenFileRead(descPath, &descHandle); + if (nDescLen > 0 && descHandle) { FILE *file; file = FS_FileForHandle(descHandle); - Com_Memset( descPath, 0, sizeof( descPath ) ); + Com_Memset(descPath, 0, sizeof(descPath)); nDescLen = fread(descPath, 1, 48, file); if (nDescLen >= 0) { descPath[nDescLen] = '\0'; } FS_FCloseFile(descHandle); - } else if ( isBase ) { + } else if (isBase) { strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY")); } else { strcpy(descPath, name); @@ -2392,7 +2324,7 @@ int FS_GetModList( char *listbuf, int bufsize ) { nDescLen = strlen(descPath) + 1; if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) { - if ( isBase ) + if (isBase) strcpy(listbuf, ""); else strcpy(listbuf, name); @@ -2401,14 +2333,13 @@ int FS_GetModList( char *listbuf, int bufsize ) { listbuf += nDescLen; nTotal += nLen + nDescLen; nMods++; - } - else { + } else { break; } } } } - Sys_FreeFileList( pFiles ); + Sys_FreeFileList(pFiles); return nMods; } @@ -2420,35 +2351,35 @@ int FS_GetModList( char *listbuf, int bufsize ) { FS_Dir_f ================ */ -void FS_Dir_f( void ) { - char *path; - char *extension; - char **dirnames; - int ndirs; - int i; - - if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) { - Com_Printf( "usage: dir [extension]\n" ); +void FS_Dir_f(void) { + char *path; + char *extension; + char **dirnames; + int ndirs; + int i; + + if (Cmd_Argc() < 2 || Cmd_Argc() > 3) { + Com_Printf("usage: dir [extension]\n"); return; } - if ( Cmd_Argc() == 2 ) { - path = Cmd_Argv( 1 ); + if (Cmd_Argc() == 2) { + path = Cmd_Argv(1); extension = ""; } else { - path = Cmd_Argv( 1 ); - extension = Cmd_Argv( 2 ); + path = Cmd_Argv(1); + extension = Cmd_Argv(2); } - Com_Printf( "Directory of %s %s\n", path, extension ); - Com_Printf( "---------------\n" ); + Com_Printf("Directory of %s %s\n", path, extension); + Com_Printf("---------------\n"); - dirnames = FS_ListFiles( path, extension, &ndirs ); + dirnames = FS_ListFiles(path, extension, &ndirs); - for ( i = 0; i < ndirs; i++ ) { - Com_Printf( "%s\n", dirnames[i] ); + for (i = 0; i < ndirs; i++) { + Com_Printf("%s\n", dirnames[i]); } - FS_FreeFileList( dirnames ); + FS_FreeFileList(dirnames); } /* @@ -2456,9 +2387,9 @@ void FS_Dir_f( void ) { FS_ConvertPath =========== */ -void FS_ConvertPath( char *s ) { +void FS_ConvertPath(char *s) { while (*s) { - if ( *s == '\\' || *s == ':' ) { + if (*s == '\\' || *s == ':') { *s = '/'; } s++; @@ -2472,8 +2403,8 @@ FS_PathCmp Ignore case and separator char distinctions =========== */ -int FS_PathCmp( const char *s1, const char *s2 ) { - int c1, c2; +int FS_PathCmp(const char *s1, const char *s2) { + int c1, c2; do { c1 = *s1++; @@ -2486,22 +2417,22 @@ int FS_PathCmp( const char *s1, const char *s2 ) { c2 -= ('a' - 'A'); } - if ( c1 == '\\' || c1 == ':' ) { + if (c1 == '\\' || c1 == ':') { c1 = '/'; } - if ( c2 == '\\' || c2 == ':' ) { + if (c2 == '\\' || c2 == ':') { c2 = '/'; } if (c1 < c2) { - return -1; // strings not equal + return -1; // strings not equal } if (c1 > c2) { return 1; } } while (c1); - return 0; // strings are equal + return 0; // strings are equal } /* @@ -2513,7 +2444,7 @@ void FS_SortFileList(char **filelist, int numfiles) { int i, j, k, numsortedfiles; char **sortedlist; - sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue ); + sortedlist = (char **)Z_Malloc((numfiles + 1) * sizeof(*sortedlist), TAG_FILESYS, qtrue); sortedlist[0] = NULL; numsortedfiles = 0; for (i = 0; i < numfiles; i++) { @@ -2523,12 +2454,12 @@ void FS_SortFileList(char **filelist, int numfiles) { } } for (k = numsortedfiles; k > j; k--) { - sortedlist[k] = sortedlist[k-1]; + sortedlist[k] = sortedlist[k - 1]; } sortedlist[j] = filelist[i]; numsortedfiles++; } - Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) ); + Com_Memcpy(filelist, sortedlist, numfiles * sizeof(*filelist)); Z_Free(sortedlist); } @@ -2537,32 +2468,32 @@ void FS_SortFileList(char **filelist, int numfiles) { FS_NewDir_f ================ */ -void FS_NewDir_f( void ) { - char *filter; - char **dirnames; - int ndirs; - int i; - - if ( Cmd_Argc() < 2 ) { - Com_Printf( "usage: fdir \n" ); - Com_Printf( "example: fdir *t1*.bsp\n"); +void FS_NewDir_f(void) { + char *filter; + char **dirnames; + int ndirs; + int i; + + if (Cmd_Argc() < 2) { + Com_Printf("usage: fdir \n"); + Com_Printf("example: fdir *t1*.bsp\n"); return; } - filter = Cmd_Argv( 1 ); + filter = Cmd_Argv(1); - Com_Printf( "---------------\n" ); + Com_Printf("---------------\n"); - dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs ); + dirnames = FS_ListFilteredFiles("", "", filter, &ndirs); FS_SortFileList(dirnames, ndirs); - for ( i = 0; i < ndirs; i++ ) { + for (i = 0; i < ndirs; i++) { FS_ConvertPath(dirnames[i]); - Com_Printf( "%s\n", dirnames[i] ); + Com_Printf("%s\n", dirnames[i]); } - Com_Printf( "%d files listed\n", ndirs ); - FS_FreeFileList( dirnames ); + Com_Printf("%d files listed\n", ndirs); + FS_FreeFileList(dirnames); } /* @@ -2571,23 +2502,23 @@ FS_Path_f ============ */ -void FS_Path_f( void ) { - searchpath_t *s; - int i; +void FS_Path_f(void) { + searchpath_t *s; + int i; - Com_Printf ("Current search path:\n"); + Com_Printf("Current search path:\n"); for (s = fs_searchpaths; s; s = s->next) { if (s->pack) { - Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles); + Com_Printf("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles); } else { - Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir ); + Com_Printf("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir); } } - Com_Printf( "\n" ); - for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { - if ( fsh[i].handleFiles.file.o ) { - Com_Printf( "handle %i: %s\n", i, fsh[i].name ); + Com_Printf("\n"); + for (i = 1; i < MAX_FILE_HANDLES; i++) { + if (fsh[i].handleFiles.file.o) { + Com_Printf("handle %i: %s\n", i, fsh[i].name); } } } @@ -2600,17 +2531,17 @@ The only purpose of this function is to allow game script files to copy arbitrary files furing an "fs_copyfiles 1" run. ============ */ -void FS_TouchFile_f( void ) { - fileHandle_t f; +void FS_TouchFile_f(void) { + fileHandle_t f; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "Usage: touchFile \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: touchFile \n"); return; } - FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse ); - if ( f ) { - FS_FCloseFile( f ); + FS_FOpenFileRead(Cmd_Argv(1), &f, qfalse); + if (f) { + FS_FCloseFile(f); } } @@ -2619,81 +2550,81 @@ void FS_TouchFile_f( void ) { FS_Which_f ============ */ -void FS_Which_f( void ) { - searchpath_t *search; - char *filename; +void FS_Which_f(void) { + searchpath_t *search; + char *filename; filename = Cmd_Argv(1); - if ( !filename[0] ) { - Com_Printf( "Usage: which \n" ); + if (!filename[0]) { + Com_Printf("Usage: which \n"); return; } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { return; } // just wants to see if file is there - for ( search=fs_searchpaths; search; search=search->next ) { - if ( search->pack ) { - long hash = FS_HashFileName( filename, search->pack->hashSize ); + for (search = fs_searchpaths; search; search = search->next) { + if (search->pack) { + long hash = FS_HashFileName(filename, search->pack->hashSize); // is the element a pak file? - if ( search->pack->hashTable[hash]) { + if (search->pack->hashTable[hash]) { // look through all the pak file elements - pack_t* pak = search->pack; - fileInPack_t* pakFile = pak->hashTable[hash]; + pack_t *pak = search->pack; + fileInPack_t *pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { // found it! - Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename ); + Com_Printf("File \"%s\" found in \"%s\"\n", filename, pak->pakFilename); return; } pakFile = pakFile->next; - } while ( pakFile != NULL ); + } while (pakFile != NULL); } } else if (search->dir) { - directory_t* dir = search->dir; + directory_t *dir = search->dir; - char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename ); - FILE* filep = fopen(netpath, "rb"); + char *netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); + FILE *filep = fopen(netpath, "rb"); - if ( filep ) { - fclose( filep ); + if (filep) { + fclose(filep); char buf[MAX_OSPATH]; - Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir ); - FS_ReplaceSeparators( buf ); - Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf ); + Com_sprintf(buf, sizeof(buf), "%s%c%s", dir->path, PATH_SEP, dir->gamedir); + FS_ReplaceSeparators(buf); + Com_Printf("File \"%s\" found at \"%s\"\n", filename, buf); return; } } } - Com_Printf( "File not found: \"%s\"\n", filename ); + Com_Printf("File not found: \"%s\"\n", filename); } //=========================================================================== -static int QDECL paksort( const void *a, const void *b ) { - char *aa, *bb; +static int QDECL paksort(const void *a, const void *b) { + char *aa, *bb; aa = *(char **)a; bb = *(char **)b; - return FS_PathCmp( aa, bb ); + return FS_PathCmp(aa, bb); } /* @@ -2704,64 +2635,64 @@ Sets fs_gamedir, adds the directory to the head of the path, then loads the zip headers ================ */ -#define MAX_PAKFILES 1024 -static void FS_AddGameDirectory( const char *path, const char *dir ) { - searchpath_t *sp; - int i; - searchpath_t *search; - searchpath_t *thedir; - pack_t *pak; - char curpath[MAX_OSPATH + 1], *pakfile; - int numfiles; - char **pakfiles; - char *sorted[MAX_PAKFILES]; +#define MAX_PAKFILES 1024 +static void FS_AddGameDirectory(const char *path, const char *dir) { + searchpath_t *sp; + int i; + searchpath_t *search; + searchpath_t *thedir; + pack_t *pak; + char curpath[MAX_OSPATH + 1], *pakfile; + int numfiles; + char **pakfiles; + char *sorted[MAX_PAKFILES]; // this fixes the case where fs_basepath is the same as fs_cdpath // which happens on full installs - for ( sp = fs_searchpaths ; sp ; sp = sp->next ) { + for (sp = fs_searchpaths; sp; sp = sp->next) { // TODO Sys_PathCmp SDL-Port will contain this for SP as well // Should be Sys_PathCmp(sp->dir->path, path) - if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) { - return; // we've already got this one + if (sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) { + return; // we've already got this one } } - Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) ); + Q_strncpyz(fs_gamedir, dir, sizeof(fs_gamedir)); // find all pak files in this directory Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath)); - curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash + curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash // // add the directory to the search path // - search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue); - search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue ); + search = (struct searchpath_s *)Z_Malloc(sizeof(searchpath_t), TAG_FILESYS, qtrue); + search->dir = (directory_t *)Z_Malloc(sizeof(*search->dir), TAG_FILESYS, qtrue); - Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) ); - Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) ); - Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) ); + Q_strncpyz(search->dir->path, path, sizeof(search->dir->path)); + Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath)); + Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir)); search->next = fs_searchpaths; fs_searchpaths = search; thedir = search; - pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse ); + pakfiles = Sys_ListFiles(curpath, ".pk3", NULL, &numfiles, qfalse); // sort them so that later alphabetic matches override // earlier ones. This makes pak1.pk3 override pak0.pk3 - if ( numfiles > MAX_PAKFILES ) { + if (numfiles > MAX_PAKFILES) { numfiles = MAX_PAKFILES; } - for ( i = 0 ; i < numfiles ; i++ ) { + for (i = 0; i < numfiles; i++) { sorted[i] = pakfiles[i]; } - qsort( sorted, numfiles, sizeof(char*), paksort ); + qsort(sorted, numfiles, sizeof(char *), paksort); - for ( i = 0 ; i < numfiles ; i++ ) { - pakfile = FS_BuildOSPath( path, dir, sorted[i] ); - if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) + for (i = 0; i < numfiles; i++) { + pakfile = FS_BuildOSPath(path, dir, sorted[i]); + if ((pak = FS_LoadZipFile(pakfile, sorted[i])) == 0) continue; Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname)); // store the game name for downloading @@ -2769,30 +2700,26 @@ static void FS_AddGameDirectory( const char *path, const char *dir ) { fs_packFiles += pak->numfiles; - search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue); + search = (searchpath_s *)Z_Malloc(sizeof(searchpath_t), TAG_FILESYS, qtrue); search->pack = pak; - if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir) - { + if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir) { searchpath_t *oldnext = thedir->next; thedir->next = search; - while (oldnext) - { + while (oldnext) { search->next = oldnext; search = search->next; oldnext = oldnext->next; } - } - else - { + } else { search->next = fs_searchpaths; fs_searchpaths = search; } } // done - Sys_FreeFileList( pakfiles ); + Sys_FreeFileList(pakfiles); } /* @@ -2804,9 +2731,8 @@ and return qtrue if it does. ================ */ -qboolean FS_CheckDirTraversal(const char *checkdir) -{ - if(strstr(checkdir, "../") || strstr(checkdir, "..\\")) +qboolean FS_CheckDirTraversal(const char *checkdir) { + if (strstr(checkdir, "../") || strstr(checkdir, "..\\")) return qtrue; return qfalse; @@ -2819,37 +2745,37 @@ FS_Shutdown Frees all resources and closes all files ================ */ -void FS_Shutdown( void ) { - searchpath_t *p, *next; - int i; +void FS_Shutdown(void) { + searchpath_t *p, *next; + int i; - for(i = 0; i < MAX_FILE_HANDLES; i++) { + for (i = 0; i < MAX_FILE_HANDLES; i++) { if (fsh[i].fileSize) { FS_FCloseFile(i); } } // free everything - for ( p = fs_searchpaths ; p ; p = next ) { + for (p = fs_searchpaths; p; p = next) { next = p->next; - if ( p->pack ) { - FS_FreePak( p->pack ); + if (p->pack) { + FS_FreePak(p->pack); } - if ( p->dir ) { - Z_Free( p->dir ); + if (p->dir) { + Z_Free(p->dir); } - Z_Free( p ); + Z_Free(p); } // any FS_ calls will now be an error until reinitialized fs_searchpaths = NULL; - Cmd_RemoveCommand( "path" ); - Cmd_RemoveCommand( "dir" ); - Cmd_RemoveCommand( "fdir" ); - Cmd_RemoveCommand( "touchFile" ); - Cmd_RemoveCommand( "which" ); + Cmd_RemoveCommand("path"); + Cmd_RemoveCommand("dir"); + Cmd_RemoveCommand("fdir"); + Cmd_RemoveCommand("touchFile"); + Cmd_RemoveCommand("which"); } /* @@ -2857,40 +2783,40 @@ void FS_Shutdown( void ) { FS_Startup ================ */ -void FS_Startup( const char *gameName ) { +void FS_Startup(const char *gameName) { const char *homePath; - Com_Printf( "----- FS_Startup -----\n" ); + Com_Printf("----- FS_Startup -----\n"); fs_packFiles = 0; - fs_debug = Cvar_Get( "fs_debug", "0", 0 ); - fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT ); - fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED ); - fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED ); - fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT ); + fs_debug = Cvar_Get("fs_debug", "0", 0); + fs_copyfiles = Cvar_Get("fs_copyfiles", "0", CVAR_INIT); + fs_cdpath = Cvar_Get("fs_cdpath", "", CVAR_INIT | CVAR_PROTECTED); + fs_basepath = Cvar_Get("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT | CVAR_PROTECTED); + fs_basegame = Cvar_Get("fs_basegame", "", CVAR_INIT); homePath = Sys_DefaultHomePath(); if (!homePath || !homePath[0]) { homePath = fs_basepath->string; } - fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED ); - fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO ); + fs_homepath = Cvar_Get("fs_homepath", homePath, CVAR_INIT | CVAR_PROTECTED); + fs_gamedirvar = Cvar_Get("fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO); - fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED); + fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT | CVAR_PROTECTED); // add search path elements in reverse priority order if (fs_cdpath->string[0]) { - FS_AddGameDirectory( fs_cdpath->string, gameName ); + FS_AddGameDirectory(fs_cdpath->string, gameName); } if (fs_basepath->string[0]) { - FS_AddGameDirectory( fs_basepath->string, gameName ); + FS_AddGameDirectory(fs_basepath->string, gameName); } #ifdef MACOS_X - fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED ); + fs_apppath = Cvar_Get("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT | CVAR_PROTECTED); // Make MacOSX also include the base path included with the .app bundle if (fs_apppath->string[0]) { - FS_AddGameDirectory( fs_apppath->string, gameName ); + FS_AddGameDirectory(fs_apppath->string, gameName); } #endif @@ -2899,12 +2825,12 @@ void FS_Startup( const char *gameName ) { // TODO Sys_PathCmp see previous comment for why // !Sys_PathCmp(fs_homepath->string, fs_basepath->string) if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string)) { - FS_CreatePath ( fs_homepath->string ); - FS_AddGameDirectory ( fs_homepath->string, gameName ); + FS_CreatePath(fs_homepath->string); + FS_AddGameDirectory(fs_homepath->string, gameName); } // check for additional base game so mods can be based upon other mods - if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) { + if (fs_basegame->string[0] && Q_stricmp(fs_basegame->string, gameName)) { if (fs_cdpath->string[0]) { FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string); } @@ -2917,7 +2843,7 @@ void FS_Startup( const char *gameName ) { } // check for additional game folder for mods - if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) { + if (fs_gamedirvar->string[0] && Q_stricmp(fs_gamedirvar->string, gameName)) { if (fs_cdpath->string[0]) { FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string); } @@ -2930,19 +2856,19 @@ void FS_Startup( const char *gameName ) { } // add our commands - Cmd_AddCommand ("path", FS_Path_f); - Cmd_AddCommand ("dir", FS_Dir_f ); - Cmd_AddCommand ("fdir", FS_NewDir_f ); - Cmd_AddCommand ("touchFile", FS_TouchFile_f ); - Cmd_AddCommand ("which", FS_Which_f ); + Cmd_AddCommand("path", FS_Path_f); + Cmd_AddCommand("dir", FS_Dir_f); + Cmd_AddCommand("fdir", FS_NewDir_f); + Cmd_AddCommand("touchFile", FS_TouchFile_f); + Cmd_AddCommand("which", FS_Which_f); // print the current search paths FS_Path_f(); fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified - Com_Printf( "----------------------\n" ); - Com_Printf( "%d files in pk3 files\n", fs_packFiles ); + Com_Printf("----------------------\n"); + Com_Printf("%d files in pk3 files\n", fs_packFiles); } /* @@ -2953,44 +2879,44 @@ Called only at inital startup, not when the filesystem is resetting due to a game change ================ */ -void FS_InitFilesystem( void ) { +void FS_InitFilesystem(void) { // allow command line parms to override our defaults // we have to specially handle this, because normal command // line variable sets don't happen until after the filesystem // has already been initialized - Com_StartupVariable( "fs_cdpath" ); - Com_StartupVariable( "fs_basepath" ); - Com_StartupVariable( "fs_homepath" ); - Com_StartupVariable( "fs_game" ); - Com_StartupVariable( "fs_copyfiles" ); - Com_StartupVariable( "fs_dirbeforepak" ); + Com_StartupVariable("fs_cdpath"); + Com_StartupVariable("fs_basepath"); + Com_StartupVariable("fs_homepath"); + Com_StartupVariable("fs_game"); + Com_StartupVariable("fs_copyfiles"); + Com_StartupVariable("fs_dirbeforepak"); #ifdef MACOS_X - Com_StartupVariable( "fs_apppath" ); + Com_StartupVariable("fs_apppath"); #endif const char *gamedir = Cvar_VariableString("fs_game"); bool requestbase = false; - if ( !FS_FilenameCompare( gamedir, BASEGAME ) ) + if (!FS_FilenameCompare(gamedir, BASEGAME)) requestbase = true; - if ( requestbase ) - Cvar_Set2( "fs_game", "", qtrue ); + if (requestbase) + Cvar_Set2("fs_game", "", qtrue); // try to start up normally - FS_Startup( BASEGAME ); + FS_Startup(BASEGAME); // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load - if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) { - Com_Error( ERR_FATAL, "Couldn't load default.cfg" ); + if (FS_ReadFile("default.cfg", NULL) <= 0) { + Com_Error(ERR_FATAL, "Couldn't load default.cfg"); // bk001208 - SafeMode see below, FIXME? } Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase)); Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame)); - // bk001208 - SafeMode see below, FIXME? + // bk001208 - SafeMode see below, FIXME? } /* @@ -2998,18 +2924,18 @@ void FS_InitFilesystem( void ) { FS_Restart ================ */ -void FS_Restart( void ) { +void FS_Restart(void) { // free anything we currently have loaded FS_Shutdown(); // try to start up normally - FS_Startup( BASEGAME ); + FS_Startup(BASEGAME); // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load - if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) { + if (FS_ReadFile("default.cfg", NULL) <= 0) { // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3 // (for instance a TA demo server) if (lastValidBase[0]) { @@ -3018,22 +2944,21 @@ void FS_Restart( void ) { lastValidBase[0] = '\0'; lastValidGame[0] = '\0'; FS_Restart(); - Com_Error( ERR_DROP, "Invalid game folder" ); + Com_Error(ERR_DROP, "Invalid game folder"); return; } - Com_Error( ERR_FATAL, "Couldn't load default.cfg" ); + Com_Error(ERR_FATAL, "Couldn't load default.cfg"); } - if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) { + if (Q_stricmp(fs_gamedirvar->string, lastValidGame)) { // skip the jaconfig.cfg if "safe" is on the command line - if ( !Com_SafeMode() ) { - Cbuf_AddText ("exec " Q3CONFIG_NAME "\n"); + if (!Com_SafeMode()) { + Cbuf_AddText("exec " Q3CONFIG_NAME "\n"); } } Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase)); Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame)); - } /* @@ -3043,8 +2968,8 @@ FS_ConditionalRestart Restart if necessary ================= */ -qboolean FS_ConditionalRestart( void ) { - if(fs_gamedirvar->modified) { +qboolean FS_ConditionalRestart(void) { + if (fs_gamedirvar->modified) { FS_Restart(); return qtrue; } @@ -3059,18 +2984,18 @@ Handle based file calls for virtual machines ======================================================================================== */ -int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - int r; - qboolean sync; +int FS_FOpenFileByMode(const char *qpath, fileHandle_t *f, fsMode_t mode) { + int r; + qboolean sync; sync = qfalse; - switch( mode ) { + switch (mode) { case FS_READ: - r = FS_FOpenFileRead( qpath, f, qtrue ); + r = FS_FOpenFileRead(qpath, f, qtrue); break; case FS_WRITE: - *f = FS_FOpenFileWrite( qpath ); + *f = FS_FOpenFileWrite(qpath); r = 0; if (*f == 0) { r = -1; @@ -3079,14 +3004,14 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { case FS_APPEND_SYNC: sync = qtrue; case FS_APPEND: - *f = FS_FOpenFileAppend( qpath ); + *f = FS_FOpenFileAppend(qpath); r = 0; if (*f == 0) { r = -1; } break; default: - Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" ); + Com_Error(ERR_FATAL, "FSH_FOpenFile: bad mode"); return -1; } @@ -3094,7 +3019,7 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { return r; } - if ( *f ) { + if (*f) { fsh[*f].fileSize = r; } fsh[*f].handleSync = sync; @@ -3102,7 +3027,7 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { return r; } -int FS_FTell( fileHandle_t f ) { +int FS_FTell(fileHandle_t f) { int pos; if (fsh[f].zipFile == qtrue) { pos = unztell(fsh[f].handleFiles.file.z); @@ -3112,41 +3037,37 @@ int FS_FTell( fileHandle_t f ) { return pos; } -void FS_Flush( fileHandle_t f ) { - fflush(fsh[f].handleFiles.file.o); -} +void FS_Flush(fileHandle_t f) { fflush(fsh[f].handleFiles.file.o); } -void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) { +void FS_FilenameCompletion(const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk) { int nfiles; char **filenames, filename[MAX_STRING_CHARS]; - filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles ); + filenames = FS_ListFilteredFiles(dir, ext, NULL, &nfiles); - FS_SortFileList( filenames, nfiles ); + FS_SortFileList(filenames, nfiles); // pass all the files to callback (FindMatches) - for ( int i=0; istring[0]) +const char *FS_GetCurrentGameDir(bool emptybase) { + if (fs_gamedirvar->string[0]) return fs_gamedirvar->string; return emptybase ? "" : BASEGAME; } -qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath ) -{ +qboolean FS_WriteToTemporaryFile(const void *data, size_t dataLength, char **tempFilePath) { // SP doesn't need to do this. return qfalse; } diff --git a/code/qcommon/hstring.cpp b/code/qcommon/hstring.cpp index f2b1cb6b91..7975a243f7 100644 --- a/code/qcommon/hstring.cpp +++ b/code/qcommon/hstring.cpp @@ -1,203 +1,174 @@ #include "cm_local.h" #include "hstring.h" -#if defined (_DEBUG) && defined (_WIN32) +#if defined(_DEBUG) && defined(_WIN32) #define WIN32_LEAN_AND_MEAN 1 //#include // for Sleep for Z_Malloc recovery attempy #include "platform.h" #endif // mapPoolBlockCount is defined differently in the executable (sv_main.cpp) and the game dll (g_main.cpp) cuz -//we likely don't need as many blocks in the executable as we do in the game -extern int mapPoolBlockCount; +// we likely don't need as many blocks in the executable as we do in the game +extern int mapPoolBlockCount; // Used to fool optimizer during compilation of mem touch routines. -int HaHaOptimizer2=0; +int HaHaOptimizer2 = 0; - -CMapPoolLow &GetMapPool() -{ +CMapPoolLow &GetMapPool() { // this may need to be ifdefed to be different for different modules static CMapPoolLow thePool; return thePool; } -#define MAPBLOCK_SIZE_NODES (1024) -#define MAPNODE_FREE (0xa1) -#define MAPNODE_INUSE (0x94) +#define MAPBLOCK_SIZE_NODES (1024) +#define MAPNODE_FREE (0xa1) +#define MAPNODE_INUSE (0x94) -struct SMapNode -{ - unsigned char mData[MAP_NODE_SIZE-2]; +struct SMapNode { + unsigned char mData[MAP_NODE_SIZE - 2]; unsigned char mMapBlockNum; unsigned char mTag; }; -class CMapBlock -{ - int mId; - char mRaw[(MAPBLOCK_SIZE_NODES+1)*MAP_NODE_SIZE]; - SMapNode *mNodes; - int mLastNode; - -public: - CMapBlock(int id,vector &freeList) : - mLastNode(0) - { +class CMapBlock { + int mId; + char mRaw[(MAPBLOCK_SIZE_NODES + 1) * MAP_NODE_SIZE]; + SMapNode *mNodes; + int mLastNode; + + public: + CMapBlock(int id, vector &freeList) : mLastNode(0) { // Alloc node storage for MAPBLOCK_SIZE_NODES worth of nodes. - mNodes=(SMapNode *)((((unsigned long)mRaw)+MAP_NODE_SIZE)&~(unsigned long)0x1f); + mNodes = (SMapNode *)((((unsigned long)mRaw) + MAP_NODE_SIZE) & ~(unsigned long)0x1f); // Set all nodes to initially be free. int i; - for(i=0;i=&mNodes[0])&&(((SMapNode *)node)<&mNodes[MAPBLOCK_SIZE_NODES])); - } + bool bOwnsNode(void *node) { return ((((SMapNode *)node) >= &mNodes[0]) && (((SMapNode *)node) < &mNodes[MAPBLOCK_SIZE_NODES])); } }; -CMapPoolLow::CMapPoolLow() -{ - mLastBlockNum=-1; -} +CMapPoolLow::CMapPoolLow() { mLastBlockNum = -1; } -CMapPoolLow::~CMapPoolLow() -{ +CMapPoolLow::~CMapPoolLow() { #if _DEBUG char mess[1000]; #if _GAME - if(mFreeList.size()mTag==MAPNODE_FREE); - assert((((SMapNode *)node)->mMapBlockNum)>=0); - assert((((SMapNode *)node)->mMapBlockNum)<256); - assert((((SMapNode *)node)->mMapBlockNum)<=mLastBlockNum); + assert(((SMapNode *)node)->mTag == MAPNODE_FREE); + assert((((SMapNode *)node)->mMapBlockNum) >= 0); + assert((((SMapNode *)node)->mMapBlockNum) < 256); + assert((((SMapNode *)node)->mMapBlockNum) <= mLastBlockNum); assert(mMapBlocks[((SMapNode *)node)->mMapBlockNum]->bOwnsNode(node)); // Ok, mark the node as in use. - ((SMapNode *)node)->mTag=MAPNODE_INUSE; + ((SMapNode *)node)->mTag = MAPNODE_INUSE; - return(node); + return (node); } -void CMapPoolLow::Free(void *p) -{ +void CMapPoolLow::Free(void *p) { // Validate that someone isn't trying to double free this node and also // that the end marker is intact. - assert(((SMapNode *)p)->mTag==MAPNODE_INUSE); - assert((((SMapNode *)p)->mMapBlockNum)>=0); - assert((((SMapNode *)p)->mMapBlockNum)<256); - assert((((SMapNode *)p)->mMapBlockNum)<=mLastBlockNum); + assert(((SMapNode *)p)->mTag == MAPNODE_INUSE); + assert((((SMapNode *)p)->mMapBlockNum) >= 0); + assert((((SMapNode *)p)->mMapBlockNum) < 256); + assert((((SMapNode *)p)->mMapBlockNum) <= mLastBlockNum); assert(mMapBlocks[((SMapNode *)p)->mMapBlockNum]->bOwnsNode(p)); // Ok, mark the the node as free. - ((SMapNode *)p)->mTag=MAPNODE_FREE; + ((SMapNode *)p)->mTag = MAPNODE_FREE; // Add a new freelist entry to point at this node. mFreeList.push_back(p); } -void CMapPoolLow::TouchMem() -{ - int i,j; - unsigned char *memory; - int totSize=0; - for(i=0;i=0&&hash= 0 && hash < MAX_HASH); assert(value); // 0 is the empty marker - int i=hash; - while (mHashes[i]) - { - assert(mHashes[i]!=value); //please don't insert things twice - i=(i+1)&(MAX_HASH-1); - assert(i!=hash); //hash table is full? + int i = hash; + while (mHashes[i]) { + assert(mHashes[i] != value); // please don't insert things twice + i = (i + 1) & (MAX_HASH - 1); + assert(i != hash); // hash table is full? } - mHashes[i]=value; + mHashes[i] = value; } - int FindFirst(int hash) - { - mFindPtr=hash; - mFindPtrStart=hash; + int FindFirst(int hash) { + mFindPtr = hash; + mFindPtrStart = hash; return FindNext(); } - int FindNext() - { - assert(mFindPtr>=0&&mFindPtr= 0 && mFindPtr < MAX_HASH); + int val = mHashes[mFindPtr]; + mFindPtr = (mFindPtr + 1) & (MAX_HASH - 1); + assert(mFindPtr != mFindPtrStart); // hash table full? return val; } - void TouchMem() - { - int i; - for(i=0;i(BLOCK_SIZE-mBytesUsed)) - { - return(0); + if (sizeBytes > (BLOCK_SIZE - mBytesUsed)) { + return (0); } // Return the pointer to the start of allocated space. - char *ret=&mRaw[mBytesUsed]; - mBytesUsed+=sizeBytes; + char *ret = &mRaw[mBytesUsed]; + mBytesUsed += sizeBytes; return ret; } - bool operator== (const CHSBlock &block) const - { - if(!memcmp(mRaw,block.mRaw,BLOCK_SIZE)) - { - return(true); + bool operator==(const CHSBlock &block) const { + if (!memcmp(mRaw, block.mRaw, BLOCK_SIZE)) { + return (true); } - return(false); + return (false); } }; -class CPool -{ - vector mBlockVec; +class CPool { + vector mBlockVec; -public: - int mNextStringId; - int mLastBlockNum; + public: + int mNextStringId; + int mLastBlockNum; - CPool(void) : - mNextStringId(1), - mLastBlockNum(-1) - { - memset(gCharPtrs,0,MAX_HSTRINGS*4); - } + CPool(void) : mNextStringId(1), mLastBlockNum(-1) { memset(gCharPtrs, 0, MAX_HSTRINGS * 4); } - ~CPool(void) - { + ~CPool(void) { int i; - for (i=0;i=0) - { + assert(mNextStringId < MAX_HSTRINGS); + char *raw = 0; + if (mLastBlockNum >= 0) { // Get the pointer to the start of allocated space in the current block. - raw=mBlockVec[mLastBlockNum]->Alloc(sizeBytes); + raw = mBlockVec[mLastBlockNum]->Alloc(sizeBytes); } - if(!raw) - { + if (!raw) { // Ok, make a new empty block and append it. - CHSBlock *block=new(CHSBlock); + CHSBlock *block = new (CHSBlock); mBlockVec.push_back(block); mLastBlockNum++; - raw=mBlockVec[mLastBlockNum]->Alloc(sizeBytes); + raw = mBlockVec[mLastBlockNum]->Alloc(sizeBytes); } // Should never really happen!! assert(raw); - id=mNextStringId; - gCharPtrs[mNextStringId]=raw; + id = mNextStringId; + gCharPtrs[mNextStringId] = raw; mNextStringId++; - return(raw); + return (raw); } - bool operator== (const CPool &pool) const - { + bool operator==(const CPool &pool) const { int i; - for(i=0;i0&&id 0 && id < ThePool().mNextStringId); + if (!strcmp(str, gCharPtrs[id])) { + mId = id; return; } - id=HashHelper().FindNext(); + id = HashHelper().FindNext(); } - char *raw=ThePool().Alloc(strlen(str),mId); - strcpy(raw,str); - HashHelper().Add(hash,mId); + char *raw = ThePool().Alloc(strlen(str), mId); + strcpy(raw, str); + HashHelper().Add(hash, mId); #ifdef _DEBUG int test; - raw=TheDebugPool().Alloc(strlen(str),test); - assert(test==mId); - strcpy(raw,str); + raw = TheDebugPool().Alloc(strlen(str), test); + assert(test == mId); + strcpy(raw, str); #endif - } -const char *hstring::c_str(void) const -{ - if(!mId) - { - return(""); +const char *hstring::c_str(void) const { + if (!mId) { + return (""); } - assert(mId>0&&mId 0 && mId < ThePool().mNextStringId); + return (gCharPtrs[mId]); } -string hstring::str(void) const -{ - if(!mId) - { - return(string()); +string hstring::str(void) const { + if (!mId) { + return (string()); } - assert(mId>0&&mId 0 && mId < ThePool().mNextStringId); return string(gCharPtrs[mId]); } - diff --git a/code/qcommon/matcomp.cpp b/code/qcommon/matcomp.cpp index 0be0fdb478..35772c7f96 100644 --- a/code/qcommon/matcomp.cpp +++ b/code/qcommon/matcomp.cpp @@ -25,175 +25,174 @@ along with this program; if not, see . #include #include #include -#include // for memcpy +#include // for memcpy -#define MC_MASK_X ((1<<(MC_BITS_X))-1) -#define MC_MASK_Y ((1<<(MC_BITS_Y))-1) -#define MC_MASK_Z ((1<<(MC_BITS_Z))-1) -#define MC_MASK_VECT ((1<<(MC_BITS_VECT))-1) +#define MC_MASK_X ((1 << (MC_BITS_X)) - 1) +#define MC_MASK_Y ((1 << (MC_BITS_Y)) - 1) +#define MC_MASK_Z ((1 << (MC_BITS_Z)) - 1) +#define MC_MASK_VECT ((1 << (MC_BITS_VECT)) - 1) -#define MC_SCALE_VECT (1.0f/(float)((1<<(MC_BITS_VECT-1))-2)) +#define MC_SCALE_VECT (1.0f / (float)((1 << (MC_BITS_VECT - 1)) - 2)) #define MC_POS_X (0) #define MC_SHIFT_X (0) -#define MC_POS_Y ((((MC_BITS_X))/8)) -#define MC_SHIFT_Y ((((MC_BITS_X)%8))) +#define MC_POS_Y ((((MC_BITS_X)) / 8)) +#define MC_SHIFT_Y ((((MC_BITS_X) % 8))) -#define MC_POS_Z ((((MC_BITS_X+MC_BITS_Y))/8)) -#define MC_SHIFT_Z ((((MC_BITS_X+MC_BITS_Y)%8))) +#define MC_POS_Z ((((MC_BITS_X + MC_BITS_Y)) / 8)) +#define MC_SHIFT_Z ((((MC_BITS_X + MC_BITS_Y) % 8))) -#define MC_POS_V11 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z))/8)) -#define MC_SHIFT_V11 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z)%8))) +#define MC_POS_V11 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z)) / 8)) +#define MC_SHIFT_V11 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z) % 8))) -#define MC_POS_V12 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT))/8)) -#define MC_SHIFT_V12 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT)%8))) +#define MC_POS_V12 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT)) / 8)) +#define MC_SHIFT_V12 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT) % 8))) -#define MC_POS_V13 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*2))/8)) -#define MC_SHIFT_V13 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*2)%8))) +#define MC_POS_V13 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 2)) / 8)) +#define MC_SHIFT_V13 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 2) % 8))) -#define MC_POS_V21 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*3))/8)) -#define MC_SHIFT_V21 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*3)%8))) +#define MC_POS_V21 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 3)) / 8)) +#define MC_SHIFT_V21 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 3) % 8))) -#define MC_POS_V22 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*4))/8)) -#define MC_SHIFT_V22 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*4)%8))) +#define MC_POS_V22 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 4)) / 8)) +#define MC_SHIFT_V22 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 4) % 8))) -#define MC_POS_V23 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*5))/8)) -#define MC_SHIFT_V23 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*5)%8))) +#define MC_POS_V23 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 5)) / 8)) +#define MC_SHIFT_V23 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 5) % 8))) -#define MC_POS_V31 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*6))/8)) -#define MC_SHIFT_V31 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*6)%8))) +#define MC_POS_V31 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 6)) / 8)) +#define MC_SHIFT_V31 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 6) % 8))) -#define MC_POS_V32 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*7))/8)) -#define MC_SHIFT_V32 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*7)%8))) +#define MC_POS_V32 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 7)) / 8)) +#define MC_SHIFT_V32 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 7) % 8))) -#define MC_POS_V33 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*8))/8)) -#define MC_SHIFT_V33 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*8)%8))) +#define MC_POS_V33 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 8)) / 8)) +#define MC_SHIFT_V33 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 8) % 8))) -void MC_Compress(const float mat[3][4],unsigned char * _comp) -{ - char comp[MC_COMP_BYTES*2]; +void MC_Compress(const float mat[3][4], unsigned char *_comp) { + char comp[MC_COMP_BYTES * 2]; - int i,val; - for (i=0;i=(1<= (1 << MC_BITS_X)) + val = (1 << MC_BITS_X) - 1; + if (val < 0) + val = 0; byteAlias_t *ba = (byteAlias_t *)&comp[MC_POS_X]; ba->ui |= ((uint32_t)val) << MC_SHIFT_X; - val=(int)(mat[1][3]/MC_SCALE_Y); - val+=1<<(MC_BITS_Y-1); - if (val>=(1<= (1 << MC_BITS_Y)) + val = (1 << MC_BITS_Y) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_Y]; ba->ui |= ((uint32_t)val) << MC_SHIFT_Y; - val=(int)(mat[2][3]/MC_SCALE_Z); - val+=1<<(MC_BITS_Z-1); - if (val>=(1<= (1 << MC_BITS_Z)) + val = (1 << MC_BITS_Z) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_Z]; ba->ui |= ((uint32_t)val) << MC_SHIFT_Z; - val=(int)(mat[0][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V11]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V11; - val=(int)(mat[0][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V12]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V12; - val=(int)(mat[0][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V13]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V13; - val=(int)(mat[1][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V21]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V21; - val=(int)(mat[1][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V22]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V22; - val=(int)(mat[1][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V23]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V23; - val=(int)(mat[2][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V31]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V31; - val=(int)(mat[2][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V32]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V32; - val=(int)(mat[2][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V33]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V33; @@ -202,137 +201,130 @@ void MC_Compress(const float mat[3][4],unsigned char * _comp) // technically is writing beyond the 24th byte of the output array. This *should* be harmless if the OR'd-in value // doesn't change those bytes, but BoundsChecker says that it's accessing undefined memory (which it does, // sometimes). This is probably bad, so... - memcpy(_comp,comp,MC_COMP_BYTES); + memcpy(_comp, comp, MC_COMP_BYTES); } -void MC_UnCompress(float mat[3][4],const unsigned char * comp) -{ +void MC_UnCompress(float mat[3][4], const unsigned char *comp) { int val; - val=(int)((unsigned short *)(comp))[0]; - val-=1<<(MC_BITS_X-1); - mat[0][3]=((float)(val))*MC_SCALE_X; + val = (int)((unsigned short *)(comp))[0]; + val -= 1 << (MC_BITS_X - 1); + mat[0][3] = ((float)(val)) * MC_SCALE_X; - val=(int)((unsigned short *)(comp))[1]; - val-=1<<(MC_BITS_Y-1); - mat[1][3]=((float)(val))*MC_SCALE_Y; + val = (int)((unsigned short *)(comp))[1]; + val -= 1 << (MC_BITS_Y - 1); + mat[1][3] = ((float)(val)) * MC_SCALE_Y; - val=(int)((unsigned short *)(comp))[2]; - val-=1<<(MC_BITS_Z-1); - mat[2][3]=((float)(val))*MC_SCALE_Z; + val = (int)((unsigned short *)(comp))[2]; + val -= 1 << (MC_BITS_Z - 1); + mat[2][3] = ((float)(val)) * MC_SCALE_Z; - val=(int)((unsigned short *)(comp))[3]; - val-=1<<(MC_BITS_VECT-1); - mat[0][0]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[3]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][0] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[4]; - val-=1<<(MC_BITS_VECT-1); - mat[0][1]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[4]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[5]; - val-=1<<(MC_BITS_VECT-1); - mat[0][2]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[5]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][2] = ((float)(val)) * MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[6]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][0] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[6]; - val-=1<<(MC_BITS_VECT-1); - mat[1][0]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[7]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[7]; - val-=1<<(MC_BITS_VECT-1); - mat[1][1]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[8]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][2] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[8]; - val-=1<<(MC_BITS_VECT-1); - mat[1][2]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[9]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][0] = ((float)(val)) * MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[10]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[9]; - val-=1<<(MC_BITS_VECT-1); - mat[2][0]=((float)(val))*MC_SCALE_VECT; - - val=(int)((unsigned short *)(comp))[10]; - val-=1<<(MC_BITS_VECT-1); - mat[2][1]=((float)(val))*MC_SCALE_VECT; - - val=(int)((unsigned short *)(comp))[11]; - val-=1<<(MC_BITS_VECT-1); - mat[2][2]=((float)(val))*MC_SCALE_VECT; - + val = (int)((unsigned short *)(comp))[11]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][2] = ((float)(val)) * MC_SCALE_VECT; } -void MC_UnCompressQuat(float mat[3][4],const unsigned char * comp) -{ - float w,x,y,z,f; - float fTx; - float fTy; - float fTz; - float fTwx; - float fTwy; - float fTwz; - float fTxx; - float fTxy; - float fTxz; - float fTyy; - float fTyz; - float fTzz; - - const unsigned short *pwIn = (unsigned short *) comp; +void MC_UnCompressQuat(float mat[3][4], const unsigned char *comp) { + float w, x, y, z, f; + float fTx; + float fTy; + float fTz; + float fTwx; + float fTwy; + float fTwz; + float fTxx; + float fTxy; + float fTxz; + float fTyy; + float fTyz; + float fTzz; + + const unsigned short *pwIn = (unsigned short *)comp; w = *pwIn++; - w/=16383.0f; - w-=2.0f; + w /= 16383.0f; + w -= 2.0f; x = *pwIn++; - x/=16383.0f; - x-=2.0f; + x /= 16383.0f; + x -= 2.0f; y = *pwIn++; - y/=16383.0f; - y-=2.0f; + y /= 16383.0f; + y -= 2.0f; z = *pwIn++; - z/=16383.0f; - z-=2.0f; - - fTx = 2.0f*x; - fTy = 2.0f*y; - fTz = 2.0f*z; - fTwx = fTx*w; - fTwy = fTy*w; - fTwz = fTz*w; - fTxx = fTx*x; - fTxy = fTy*x; - fTxz = fTz*x; - fTyy = fTy*y; - fTyz = fTz*y; - fTzz = fTz*z; + z /= 16383.0f; + z -= 2.0f; + + fTx = 2.0f * x; + fTy = 2.0f * y; + fTz = 2.0f * z; + fTwx = fTx * w; + fTwy = fTy * w; + fTwz = fTz * w; + fTxx = fTx * x; + fTxy = fTy * x; + fTxz = fTz * x; + fTyy = fTy * y; + fTyz = fTz * y; + fTzz = fTz * z; // rot... // - mat[0][0] = 1.0f-(fTyy+fTzz); - mat[0][1] = fTxy-fTwz; - mat[0][2] = fTxz+fTwy; - mat[1][0] = fTxy+fTwz; - mat[1][1] = 1.0f-(fTxx+fTzz); - mat[1][2] = fTyz-fTwx; - mat[2][0] = fTxz-fTwy; - mat[2][1] = fTyz+fTwx; - mat[2][2] = 1.0f-(fTxx+fTyy); + mat[0][0] = 1.0f - (fTyy + fTzz); + mat[0][1] = fTxy - fTwz; + mat[0][2] = fTxz + fTwy; + mat[1][0] = fTxy + fTwz; + mat[1][1] = 1.0f - (fTxx + fTzz); + mat[1][2] = fTyz - fTwx; + mat[2][0] = fTxz - fTwy; + mat[2][1] = fTyz + fTwx; + mat[2][2] = 1.0f - (fTxx + fTyy); // xlat... // f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[0][3] = f; f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[1][3] = f; f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[2][3] = f; } - - diff --git a/code/qcommon/md4.cpp b/code/qcommon/md4.cpp index 23851d5867..8b41ea7b86 100644 --- a/code/qcommon/md4.cpp +++ b/code/qcommon/md4.cpp @@ -30,97 +30,126 @@ Boston, MA 02111-1307, USA #include "q_shared.h" #include "qcommon.h" -typedef struct mdfour_s -{ +typedef struct mdfour_s { uint32_t A, B, C, D; uint32_t totalN; } mdfour_ctx; - /* NOTE: This code makes no attempt to be fast! It assumes that an int is at least 32 bits long */ -static mdfour_ctx *m; +static mdfour_ctx *m; -#define F(X,Y,Z) (((X)&(Y)) | ((~(X))&(Z))) -#define G(X,Y,Z) (((X)&(Y)) | ((X)&(Z)) | ((Y)&(Z))) -#define H(X,Y,Z) ((X)^(Y)^(Z)) -#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) +#define F(X, Y, Z) (((X) & (Y)) | ((~(X)) & (Z))) +#define G(X, Y, Z) (((X) & (Y)) | ((X) & (Z)) | ((Y) & (Z))) +#define H(X, Y, Z) ((X) ^ (Y) ^ (Z)) +#define lshift(x, s) (((x) << (s)) | ((x) >> (32 - (s)))) -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) +#define ROUND1(a, b, c, d, k, s) a = lshift(a + F(b, c, d) + X[k], s) +#define ROUND2(a, b, c, d, k, s) a = lshift(a + G(b, c, d) + X[k] + 0x5A827999, s) +#define ROUND3(a, b, c, d, k, s) a = lshift(a + H(b, c, d) + X[k] + 0x6ED9EBA1, s) /* this applies md4 to 64 byte chunks */ -static void mdfour64( uint32_t *M ) -{ +static void mdfour64(uint32_t *M) { int j; uint32_t AA, BB, CC, DD; uint32_t X[16]; uint32_t A, B, C, D; - for ( j = 0; j<16; j++ ) + for (j = 0; j < 16; j++) X[j] = M[j]; - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; - - ROUND1( A, B, C, D, 0, 3 ); ROUND1( D, A, B, C, 1, 7 ); - ROUND1( C, D, A, B, 2, 11 ); ROUND1( B, C, D, A, 3, 19 ); - ROUND1( A, B, C, D, 4, 3 ); ROUND1( D, A, B, C, 5, 7 ); - ROUND1( C, D, A, B, 6, 11 ); ROUND1( B, C, D, A, 7, 19 ); - ROUND1( A, B, C, D, 8, 3 ); ROUND1( D, A, B, C, 9, 7 ); - ROUND1( C, D, A, B, 10, 11 ); ROUND1( B, C, D, A, 11, 19 ); - ROUND1( A, B, C, D, 12, 3 ); ROUND1( D, A, B, C, 13, 7 ); - ROUND1( C, D, A, B, 14, 11 ); ROUND1( B, C, D, A, 15, 19 ); - - ROUND2( A, B, C, D, 0, 3 ); ROUND2( D, A, B, C, 4, 5 ); - ROUND2( C, D, A, B, 8, 9 ); ROUND2( B, C, D, A, 12, 13 ); - ROUND2( A, B, C, D, 1, 3 ); ROUND2( D, A, B, C, 5, 5 ); - ROUND2( C, D, A, B, 9, 9 ); ROUND2( B, C, D, A, 13, 13 ); - ROUND2( A, B, C, D, 2, 3 ); ROUND2( D, A, B, C, 6, 5 ); - ROUND2( C, D, A, B, 10, 9 ); ROUND2( B, C, D, A, 14, 13 ); - ROUND2( A, B, C, D, 3, 3 ); ROUND2( D, A, B, C, 7, 5 ); - ROUND2( C, D, A, B, 11, 9 ); ROUND2( B, C, D, A, 15, 13 ); - - ROUND3( A, B, C, D, 0, 3 ); ROUND3( D, A, B, C, 8, 9 ); - ROUND3( C, D, A, B, 4, 11 ); ROUND3( B, C, D, A, 12, 15 ); - ROUND3( A, B, C, D, 2, 3 ); ROUND3( D, A, B, C, 10, 9 ); - ROUND3( C, D, A, B, 6, 11 ); ROUND3( B, C, D, A, 14, 15 ); - ROUND3( A, B, C, D, 1, 3 ); ROUND3( D, A, B, C, 9, 9 ); - ROUND3( C, D, A, B, 5, 11 ); ROUND3( B, C, D, A, 13, 15 ); - ROUND3( A, B, C, D, 3, 3 ); ROUND3( D, A, B, C, 11, 9 ); - ROUND3( C, D, A, B, 7, 11 ); ROUND3( B, C, D, A, 15, 15 ); - - A += AA; B += BB; C += CC; D += DD; - - for ( j = 0; j<16; j++ ) + A = m->A; + B = m->B; + C = m->C; + D = m->D; + AA = A; + BB = B; + CC = C; + DD = D; + + ROUND1(A, B, C, D, 0, 3); + ROUND1(D, A, B, C, 1, 7); + ROUND1(C, D, A, B, 2, 11); + ROUND1(B, C, D, A, 3, 19); + ROUND1(A, B, C, D, 4, 3); + ROUND1(D, A, B, C, 5, 7); + ROUND1(C, D, A, B, 6, 11); + ROUND1(B, C, D, A, 7, 19); + ROUND1(A, B, C, D, 8, 3); + ROUND1(D, A, B, C, 9, 7); + ROUND1(C, D, A, B, 10, 11); + ROUND1(B, C, D, A, 11, 19); + ROUND1(A, B, C, D, 12, 3); + ROUND1(D, A, B, C, 13, 7); + ROUND1(C, D, A, B, 14, 11); + ROUND1(B, C, D, A, 15, 19); + + ROUND2(A, B, C, D, 0, 3); + ROUND2(D, A, B, C, 4, 5); + ROUND2(C, D, A, B, 8, 9); + ROUND2(B, C, D, A, 12, 13); + ROUND2(A, B, C, D, 1, 3); + ROUND2(D, A, B, C, 5, 5); + ROUND2(C, D, A, B, 9, 9); + ROUND2(B, C, D, A, 13, 13); + ROUND2(A, B, C, D, 2, 3); + ROUND2(D, A, B, C, 6, 5); + ROUND2(C, D, A, B, 10, 9); + ROUND2(B, C, D, A, 14, 13); + ROUND2(A, B, C, D, 3, 3); + ROUND2(D, A, B, C, 7, 5); + ROUND2(C, D, A, B, 11, 9); + ROUND2(B, C, D, A, 15, 13); + + ROUND3(A, B, C, D, 0, 3); + ROUND3(D, A, B, C, 8, 9); + ROUND3(C, D, A, B, 4, 11); + ROUND3(B, C, D, A, 12, 15); + ROUND3(A, B, C, D, 2, 3); + ROUND3(D, A, B, C, 10, 9); + ROUND3(C, D, A, B, 6, 11); + ROUND3(B, C, D, A, 14, 15); + ROUND3(A, B, C, D, 1, 3); + ROUND3(D, A, B, C, 9, 9); + ROUND3(C, D, A, B, 5, 11); + ROUND3(B, C, D, A, 13, 15); + ROUND3(A, B, C, D, 3, 3); + ROUND3(D, A, B, C, 11, 9); + ROUND3(C, D, A, B, 7, 11); + ROUND3(B, C, D, A, 15, 15); + + A += AA; + B += BB; + C += CC; + D += DD; + + for (j = 0; j < 16; j++) X[j] = 0; - m->A = A; m->B = B; m->C = C; m->D = D; + m->A = A; + m->B = B; + m->C = C; + m->D = D; } -static void copy64( uint32_t *M, byte *in ) -{ +static void copy64(uint32_t *M, byte *in) { int i; - for ( i = 0; i<16; i++ ) - M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | - (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); + for (i = 0; i < 16; i++) + M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); } -static void copy4( byte *out, uint32_t x ) -{ +static void copy4(byte *out, uint32_t x) { out[0] = x & 0xFF; out[1] = (x >> 8) & 0xFF; out[2] = (x >> 16) & 0xFF; out[3] = (x >> 24) & 0xFF; } -void mdfour_begin( mdfour_ctx *md ) -{ +void mdfour_begin(mdfour_ctx *md) { md->A = 0x67452301; md->B = 0xefcdab89; md->C = 0x98badcfe; @@ -128,9 +157,7 @@ void mdfour_begin( mdfour_ctx *md ) md->totalN = 0; } - -static void mdfour_tail( byte *in, int n ) -{ +static void mdfour_tail(byte *in, int n) { byte buf[128]; uint32_t M[16]; uint32_t b; @@ -139,73 +166,66 @@ static void mdfour_tail( byte *in, int n ) b = m->totalN * 8; - Com_Memset( buf, 0, 128 ); - if ( n ) Com_Memcpy( buf, in, n ); + Com_Memset(buf, 0, 128); + if (n) + Com_Memcpy(buf, in, n); buf[n] = 0x80; - if ( n <= 55 ) - { - copy4( buf + 56, b ); - copy64( M, buf ); - mdfour64( M ); - } - else - { - copy4( buf + 120, b ); - copy64( M, buf ); - mdfour64( M ); - copy64( M, buf + 64 ); - mdfour64( M ); + if (n <= 55) { + copy4(buf + 56, b); + copy64(M, buf); + mdfour64(M); + } else { + copy4(buf + 120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf + 64); + mdfour64(M); } } -static void mdfour_update( mdfour_ctx *md, byte *in, int n ) -{ +static void mdfour_update(mdfour_ctx *md, byte *in, int n) { uint32_t M[16]; m = md; - if ( n == 0 ) mdfour_tail( in, n ); + if (n == 0) + mdfour_tail(in, n); - while ( n >= 64 ) - { - copy64( M, in ); - mdfour64( M ); + while (n >= 64) { + copy64(M, in); + mdfour64(M); in += 64; n -= 64; m->totalN += 64; } - mdfour_tail( in, n ); + mdfour_tail(in, n); } - -static void mdfour_result( mdfour_ctx *md, byte *out ) -{ +static void mdfour_result(mdfour_ctx *md, byte *out) { m = md; - copy4( out, m->A ); - copy4( out + 4, m->B ); - copy4( out + 8, m->C ); - copy4( out + 12, m->D ); + copy4(out, m->A); + copy4(out + 4, m->B); + copy4(out + 8, m->C); + copy4(out + 12, m->D); } -static void mdfour( byte *out, byte *in, int n ) -{ +static void mdfour(byte *out, byte *in, int n) { mdfour_ctx md; - mdfour_begin( &md ); - mdfour_update( &md, in, n ); - mdfour_result( &md, out ); + mdfour_begin(&md); + mdfour_update(&md, in, n); + mdfour_result(&md, out); } //=================================================================== -uint32_t Com_BlockChecksum( const void *buffer, int length ) -{ - int digest[4]; - uint32_t val; +uint32_t Com_BlockChecksum(const void *buffer, int length) { + int digest[4]; + uint32_t val; - mdfour( (byte *)digest, (byte *)buffer, length ); + mdfour((byte *)digest, (byte *)buffer, length); val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; diff --git a/code/qcommon/msg.cpp b/code/qcommon/msg.cpp index 8740abe380..98a58d57ac 100644 --- a/code/qcommon/msg.cpp +++ b/code/qcommon/msg.cpp @@ -34,52 +34,49 @@ Handles byte ordering and avoids alignment errors ============================================================================== */ - -void MSG_Init( msg_t *buf, byte *data, int length ) { - memset (buf, 0, sizeof(*buf)); +void MSG_Init(msg_t *buf, byte *data, int length) { + memset(buf, 0, sizeof(*buf)); buf->data = data; buf->maxsize = length; } -void MSG_Clear( msg_t *buf ) { +void MSG_Clear(msg_t *buf) { buf->cursize = 0; buf->overflowed = qfalse; buf->bit = 0; } - -void MSG_BeginReading( msg_t *msg ) { +void MSG_BeginReading(msg_t *msg) { msg->readcount = 0; msg->bit = 0; } - -void MSG_ReadByteAlign( msg_t *buf ) { +void MSG_ReadByteAlign(msg_t *buf) { // round up to the next byte - if ( buf->bit ) { + if (buf->bit) { buf->bit = 0; buf->readcount++; } } -void *MSG_GetSpace( msg_t *buf, int length ) { - void *data; +void *MSG_GetSpace(msg_t *buf, int length) { + void *data; // round up to the next byte - if ( buf->bit ) { + if (buf->bit) { buf->bit = 0; buf->cursize++; } - if ( buf->cursize + length > buf->maxsize ) { - if ( !buf->allowoverflow ) { - Com_Error (ERR_FATAL, "MSG_GetSpace: overflow without allowoverflow set"); + if (buf->cursize + length > buf->maxsize) { + if (!buf->allowoverflow) { + Com_Error(ERR_FATAL, "MSG_GetSpace: overflow without allowoverflow set"); } - if ( length > buf->maxsize ) { - Com_Error (ERR_FATAL, "MSG_GetSpace: %i is > full buffer size", length); + if (length > buf->maxsize) { + Com_Error(ERR_FATAL, "MSG_GetSpace: %i is > full buffer size", length); } - Com_Printf ("MSG_GetSpace: overflow\n"); - MSG_Clear (buf); + Com_Printf("MSG_GetSpace: overflow\n"); + MSG_Clear(buf); buf->overflowed = qtrue; } @@ -89,10 +86,7 @@ void *MSG_GetSpace( msg_t *buf, int length ) { return data; } -void MSG_WriteData( msg_t *buf, const void *data, int length ) { - memcpy (MSG_GetSpace(buf,length),data,length); -} - +void MSG_WriteData(msg_t *buf, const void *data, int length) { memcpy(MSG_GetSpace(buf, length), data, length); } /* ============================================================================= @@ -102,179 +96,171 @@ bit functions ============================================================================= */ -int overflows; +int overflows; // negative bit values include signs -void MSG_WriteBits( msg_t *msg, int value, int bits ) { - int put; - int fraction; +void MSG_WriteBits(msg_t *msg, int value, int bits) { + int put; + int fraction; // this isn't an exact overflow check, but close enough - if ( msg->maxsize - msg->cursize < 4 ) { + if (msg->maxsize - msg->cursize < 4) { msg->overflowed = qtrue; #ifndef FINAL_BUILD - Com_Printf (S_COLOR_RED"MSG_WriteBits: buffer Full writing %d in %d bits\n", value, bits); + Com_Printf(S_COLOR_RED "MSG_WriteBits: buffer Full writing %d in %d bits\n", value, bits); #endif return; } - if ( bits == 0 || bits < -31 || bits > 32 ) { - Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); + if (bits == 0 || bits < -31 || bits > 32) { + Com_Error(ERR_DROP, "MSG_WriteBits: bad bits %i", bits); } // check for overflows - if ( bits != 32 ) { - if ( bits > 0 ) { - if ( value > ( ( 1 << bits ) - 1 ) || value < 0 ) { + if (bits != 32) { + if (bits > 0) { + if (value > ((1 << bits) - 1) || value < 0) { overflows++; #ifndef FINAL_BUILD #ifdef _DEBUG - Com_Printf (S_COLOR_RED"MSG_WriteBits: overflow writing %d in %d bits\n", value, bits); + Com_Printf(S_COLOR_RED "MSG_WriteBits: overflow writing %d in %d bits\n", value, bits); #endif #endif } } else { - int r; + int r; - r = 1 << (bits-1); + r = 1 << (bits - 1); - if ( value > r - 1 || value < -r ) { + if (value > r - 1 || value < -r) { overflows++; #ifndef FINAL_BUILD #ifdef _DEBUG - Com_Printf (S_COLOR_RED"MSG_WriteBits: overflow writing %d in %d bits\n", value, bits); + Com_Printf(S_COLOR_RED "MSG_WriteBits: overflow writing %d in %d bits\n", value, bits); #endif #endif } } } - if ( bits < 0 ) { + if (bits < 0) { bits = -bits; } - while ( bits ) { - if ( msg->bit == 0 ) { + while (bits) { + if (msg->bit == 0) { msg->data[msg->cursize] = 0; msg->cursize++; } put = 8 - msg->bit; - if ( put > bits ) { + if (put > bits) { put = bits; } - fraction = value & ( ( 1 << put ) - 1 ); + fraction = value & ((1 << put) - 1); msg->data[msg->cursize - 1] |= fraction << msg->bit; bits -= put; value >>= put; - msg->bit = ( msg->bit + put ) & 7; + msg->bit = (msg->bit + put) & 7; } } -int MSG_ReadBits( msg_t *msg, int bits ) { - int value; - int valueBits; - int get; - int fraction; - qboolean sgn; +int MSG_ReadBits(msg_t *msg, int bits) { + int value; + int valueBits; + int get; + int fraction; + qboolean sgn; value = 0; valueBits = 0; - if ( bits < 0 ) { + if (bits < 0) { bits = -bits; sgn = qtrue; } else { sgn = qfalse; } - while ( valueBits < bits ) { - if ( msg->bit == 0 ) { + while (valueBits < bits) { + if (msg->bit == 0) { msg->readcount++; - assert (msg->readcount <= msg->cursize); + assert(msg->readcount <= msg->cursize); } get = 8 - msg->bit; - if ( get > (bits - valueBits) ) { + if (get > (bits - valueBits)) { get = (bits - valueBits); } fraction = msg->data[msg->readcount - 1]; fraction >>= msg->bit; - fraction &= ( 1 << get ) - 1; + fraction &= (1 << get) - 1; value |= fraction << valueBits; valueBits += get; - msg->bit = ( msg->bit + get ) & 7; + msg->bit = (msg->bit + get) & 7; } - if ( sgn ) { - if ( value & ( 1 << ( bits - 1 ) ) ) { - value |= -1 ^ ( ( 1 << bits ) - 1 ); + if (sgn) { + if (value & (1 << (bits - 1))) { + value |= -1 ^ ((1 << bits) - 1); } } return value; } - - //================================================================================ // // writing functions // -void MSG_WriteByte( msg_t *sb, int c ) { +void MSG_WriteByte(msg_t *sb, int c) { #ifdef PARANOID if (c < 0 || c > 255) - Com_Error (ERR_FATAL, "MSG_WriteByte: range error"); + Com_Error(ERR_FATAL, "MSG_WriteByte: range error"); #endif - MSG_WriteBits( sb, c, 8 ); + MSG_WriteBits(sb, c, 8); } -void MSG_WriteShort( msg_t *sb, int c ) { +void MSG_WriteShort(msg_t *sb, int c) { #ifdef PARANOID if (c < ((short)0x8000) || c > (short)0x7fff) - Com_Error (ERR_FATAL, "MSG_WriteShort: range error"); + Com_Error(ERR_FATAL, "MSG_WriteShort: range error"); #endif - MSG_WriteBits( sb, c, 16 ); + MSG_WriteBits(sb, c, 16); } -static void MSG_WriteSShort( msg_t *sb, int c ) { - MSG_WriteBits( sb, c, -16 ); -} +static void MSG_WriteSShort(msg_t *sb, int c) { MSG_WriteBits(sb, c, -16); } -void MSG_WriteLong( msg_t *sb, int c ) { - MSG_WriteBits( sb, c, 32 ); -} +void MSG_WriteLong(msg_t *sb, int c) { MSG_WriteBits(sb, c, 32); } -void MSG_WriteString( msg_t *sb, const char *s ) { - if ( !s ) { - MSG_WriteData (sb, "", 1); +void MSG_WriteString(msg_t *sb, const char *s) { + if (!s) { + MSG_WriteData(sb, "", 1); } else { - int l, i; - char string[MAX_STRING_CHARS]; + int l, i; + char string[MAX_STRING_CHARS]; - l = strlen( s ); - if ( l >= MAX_STRING_CHARS ) { - Com_Printf( "MSG_WriteString: MAX_STRING_CHARS" ); - MSG_WriteData (sb, "", 1); + l = strlen(s); + if (l >= MAX_STRING_CHARS) { + Com_Printf("MSG_WriteString: MAX_STRING_CHARS"); + MSG_WriteData(sb, "", 1); return; } - Q_strncpyz( string, s, sizeof( string ) ); + Q_strncpyz(string, s, sizeof(string)); // get rid of 0xff chars, because old clients don't like them - for ( i = 0 ; i < l ; i++ ) { - if ( ((byte *)string)[i] > 127 ) { + for (i = 0; i < l; i++) { + if (((byte *)string)[i] > 127) { string[i] = '.'; } } - MSG_WriteData (sb, string, l+1); + MSG_WriteData(sb, string, l + 1); } } - - //============================================================ // @@ -282,68 +268,68 @@ void MSG_WriteString( msg_t *sb, const char *s ) { // // returns -1 if no more characters are available -int MSG_ReadByte( msg_t *msg ) { - int c; +int MSG_ReadByte(msg_t *msg) { + int c; - if ( msg->readcount+1 > msg->cursize ) { + if (msg->readcount + 1 > msg->cursize) { c = -1; } else { - c = (unsigned char)MSG_ReadBits( msg, 8 ); + c = (unsigned char)MSG_ReadBits(msg, 8); } return c; } -int MSG_ReadShort( msg_t *msg ) { - int c; +int MSG_ReadShort(msg_t *msg) { + int c; - if ( msg->readcount+2 > msg->cursize ) { + if (msg->readcount + 2 > msg->cursize) { c = -1; } else { - c = MSG_ReadBits( msg, 16 ); + c = MSG_ReadBits(msg, 16); } return c; } -static int MSG_ReadSShort( msg_t *msg ) { - int c; +static int MSG_ReadSShort(msg_t *msg) { + int c; - if ( msg->readcount+2 > msg->cursize ) { + if (msg->readcount + 2 > msg->cursize) { c = -1; } else { - c = MSG_ReadBits( msg, -16 ); + c = MSG_ReadBits(msg, -16); } return c; } -int MSG_ReadLong( msg_t *msg ) { - int c; +int MSG_ReadLong(msg_t *msg) { + int c; - if ( msg->readcount+4 > msg->cursize ) { + if (msg->readcount + 4 > msg->cursize) { c = -1; } else { - c = MSG_ReadBits( msg, 32 ); + c = MSG_ReadBits(msg, 32); } return c; } -char *MSG_ReadString( msg_t *msg ) { +char *MSG_ReadString(msg_t *msg) { static const int STRING_SIZE = MAX_STRING_CHARS; - static char string[STRING_SIZE]; - int l,c; + static char string[STRING_SIZE]; + int l, c; - MSG_ReadByteAlign( msg ); + MSG_ReadByteAlign(msg); l = 0; do { - c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds - if ( c == -1 || c == 0 ) { + c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds + if (c == -1 || c == 0) { break; } // translate all fmt spec to avoid crash bugs - if ( c == '%' ) { + if (c == '%') { c = '.'; } @@ -356,20 +342,20 @@ char *MSG_ReadString( msg_t *msg ) { return string; } -char *MSG_ReadStringLine( msg_t *msg ) { +char *MSG_ReadStringLine(msg_t *msg) { static const int STRING_SIZE = MAX_STRING_CHARS; - static char string[STRING_SIZE]; - int l,c; + static char string[STRING_SIZE]; + int l, c; - MSG_ReadByteAlign( msg ); + MSG_ReadByteAlign(msg); l = 0; do { - c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds + c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds if (c == -1 || c == 0 || c == '\n') { break; } // translate all fmt spec to avoid crash bugs - if ( c == '%' ) { + if (c == '%') { c = '.'; } string[l] = c; @@ -381,17 +367,15 @@ char *MSG_ReadStringLine( msg_t *msg ) { return string; } +void MSG_ReadData(msg_t *msg, void *data, int len) { + int i; -void MSG_ReadData( msg_t *msg, void *data, int len ) { - int i; - - MSG_ReadByteAlign( msg ); - for (i=0 ; iinteger == 4 ) { Com_Printf("%s ", x ); }; +#define LOG(x) \ + if (cl_shownet->integer == 4) { \ + Com_Printf("%s ", x); \ + }; -void MSG_WriteDelta( msg_t *msg, int oldV, int newV, int bits ) { - if ( oldV == newV ) { - MSG_WriteBits( msg, 0, 1 ); +void MSG_WriteDelta(msg_t *msg, int oldV, int newV, int bits) { + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, newV, bits ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, newV, bits); } -int MSG_ReadDelta( msg_t *msg, int oldV, int bits ) { - if ( MSG_ReadBits( msg, 1 ) ) { - return MSG_ReadBits( msg, bits ); +int MSG_ReadDelta(msg_t *msg, int oldV, int bits) { + if (MSG_ReadBits(msg, 1)) { + return MSG_ReadBits(msg, bits); } return oldV; } -void MSG_WriteDeltaFloat( msg_t *msg, float oldV, float newV ) { +void MSG_WriteDeltaFloat(msg_t *msg, float oldV, float newV) { byteAlias_t fi; - if ( oldV == newV ) { - MSG_WriteBits( msg, 0, 1 ); + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } fi.f = newV; - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, fi.i, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, fi.i, 32); } -float MSG_ReadDeltaFloat( msg_t *msg, float oldV ) { - if ( MSG_ReadBits( msg, 1 ) ) { +float MSG_ReadDeltaFloat(msg_t *msg, float oldV) { + if (MSG_ReadBits(msg, 1)) { byteAlias_t fi; - fi.i = MSG_ReadBits( msg, 32 ); + fi.i = MSG_ReadBits(msg, 32); return fi.f; } return oldV; } - /* ============================================================================ @@ -451,50 +437,49 @@ usercmd_t communication */ // ms is allways sent, the others are optional -#define CM_ANGLE1 (1<<0) -#define CM_ANGLE2 (1<<1) -#define CM_ANGLE3 (1<<2) -#define CM_FORWARD (1<<3) -#define CM_SIDE (1<<4) -#define CM_UP (1<<5) -#define CM_BUTTONS (1<<6) -#define CM_WEAPON (1<<7) +#define CM_ANGLE1 (1 << 0) +#define CM_ANGLE2 (1 << 1) +#define CM_ANGLE3 (1 << 2) +#define CM_FORWARD (1 << 3) +#define CM_SIDE (1 << 4) +#define CM_UP (1 << 5) +#define CM_BUTTONS (1 << 6) +#define CM_WEAPON (1 << 7) /* ===================== MSG_WriteDeltaUsercmd ===================== */ -void MSG_WriteDeltaUsercmd( msg_t *msg, usercmd_t *from, usercmd_t *to ) { - MSG_WriteDelta( msg, from->serverTime, to->serverTime, 32 ); - MSG_WriteDelta( msg, from->angles[0], to->angles[0], 16 ); - MSG_WriteDelta( msg, from->angles[1], to->angles[1], 16 ); - MSG_WriteDelta( msg, from->angles[2], to->angles[2], 16 ); - MSG_WriteDelta( msg, from->forwardmove, to->forwardmove, -8 ); - MSG_WriteDelta( msg, from->rightmove, to->rightmove, -8 ); - MSG_WriteDelta( msg, from->upmove, to->upmove, -8 ); - MSG_WriteDelta( msg, from->buttons, to->buttons, 16 );//FIXME: We're only really using 9 bits...can this be changed to that? - MSG_WriteDelta( msg, from->weapon, to->weapon, 8 ); - MSG_WriteDelta( msg, from->generic_cmd, to->generic_cmd, 8 ); +void MSG_WriteDeltaUsercmd(msg_t *msg, usercmd_t *from, usercmd_t *to) { + MSG_WriteDelta(msg, from->serverTime, to->serverTime, 32); + MSG_WriteDelta(msg, from->angles[0], to->angles[0], 16); + MSG_WriteDelta(msg, from->angles[1], to->angles[1], 16); + MSG_WriteDelta(msg, from->angles[2], to->angles[2], 16); + MSG_WriteDelta(msg, from->forwardmove, to->forwardmove, -8); + MSG_WriteDelta(msg, from->rightmove, to->rightmove, -8); + MSG_WriteDelta(msg, from->upmove, to->upmove, -8); + MSG_WriteDelta(msg, from->buttons, to->buttons, 16); // FIXME: We're only really using 9 bits...can this be changed to that? + MSG_WriteDelta(msg, from->weapon, to->weapon, 8); + MSG_WriteDelta(msg, from->generic_cmd, to->generic_cmd, 8); } - /* ===================== MSG_ReadDeltaUsercmd ===================== */ -void MSG_ReadDeltaUsercmd( msg_t *msg, usercmd_t *from, usercmd_t *to ) { - to->serverTime = MSG_ReadDelta( msg, from->serverTime, 32); - to->angles[0] = MSG_ReadDelta( msg, from->angles[0], 16); - to->angles[1] = MSG_ReadDelta( msg, from->angles[1], 16); - to->angles[2] = MSG_ReadDelta( msg, from->angles[2], 16); - to->forwardmove = MSG_ReadDelta( msg, from->forwardmove, -8); - to->rightmove = MSG_ReadDelta( msg, from->rightmove, -8); - to->upmove = MSG_ReadDelta( msg, from->upmove, -8); - to->buttons = MSG_ReadDelta( msg, from->buttons, 16);//FIXME: We're only really using 9 bits...can this be changed to that? - to->weapon = MSG_ReadDelta( msg, from->weapon, 8); - to->generic_cmd = MSG_ReadDelta( msg, from->generic_cmd, 8); +void MSG_ReadDeltaUsercmd(msg_t *msg, usercmd_t *from, usercmd_t *to) { + to->serverTime = MSG_ReadDelta(msg, from->serverTime, 32); + to->angles[0] = MSG_ReadDelta(msg, from->angles[0], 16); + to->angles[1] = MSG_ReadDelta(msg, from->angles[1], 16); + to->angles[2] = MSG_ReadDelta(msg, from->angles[2], 16); + to->forwardmove = MSG_ReadDelta(msg, from->forwardmove, -8); + to->rightmove = MSG_ReadDelta(msg, from->rightmove, -8); + to->upmove = MSG_ReadDelta(msg, from->upmove, -8); + to->buttons = MSG_ReadDelta(msg, from->buttons, 16); // FIXME: We're only really using 9 bits...can this be changed to that? + to->weapon = MSG_ReadDelta(msg, from->weapon, 8); + to->generic_cmd = MSG_ReadDelta(msg, from->generic_cmd, 8); } /* @@ -506,15 +491,15 @@ entityState_t communication */ typedef struct { - const char *name; - size_t offset; - int bits; // 0 = float + const char *name; + size_t offset; + int bits; // 0 = float } netField_t; // using the stringizing operator to save typing... -#define NETF(x) #x,offsetof(entityState_t, x) +#define NETF(x) #x, offsetof(entityState_t, x) -#if 0 // Removed by BTO (VV) +#if 0 // Removed by BTO (VV) const netField_t entityStateFields[] = { { NETF(eType), 8 }, @@ -607,100 +592,89 @@ Ghoul2 Insert Start }; #endif - // if (int)f == f and (int)f + ( 1<<(FLOAT_INT_BITS-1) ) < ( 1 << FLOAT_INT_BITS ) // the float will be sent with FLOAT_INT_BITS, otherwise all 32 bits will be sent -#define FLOAT_INT_BITS 13 -#define FLOAT_INT_BIAS (1<<(FLOAT_INT_BITS-1)) +#define FLOAT_INT_BITS 13 +#define FLOAT_INT_BIAS (1 << (FLOAT_INT_BITS - 1)) -void MSG_WriteField (msg_t *msg, const int *toF, const netField_t *field) -{ - int trunc; - float fullFloat; +void MSG_WriteField(msg_t *msg, const int *toF, const netField_t *field) { + int trunc; + float fullFloat; - if ( field->bits == -1) - { // a -1 in the bits field means it's a float that's always between -1 and 1 + if (field->bits == -1) { // a -1 in the bits field means it's a float that's always between -1 and 1 int temp = *(float *)toF * 32767; - MSG_WriteBits( msg, temp, -16 ); - } - else - if ( field->bits == 0 ) { - // float - fullFloat = *(float *)toF; - trunc = (int)fullFloat; + MSG_WriteBits(msg, temp, -16); + } else if (field->bits == 0) { + // float + fullFloat = *(float *)toF; + trunc = (int)fullFloat; if (fullFloat == 0.0f) { - MSG_WriteBits( msg, 0, 1 ); //it's a zero + MSG_WriteBits(msg, 0, 1); // it's a zero } else { - MSG_WriteBits( msg, 1, 1 ); //not a zero - if ( trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && - trunc + FLOAT_INT_BIAS < ( 1 << FLOAT_INT_BITS ) ) { + MSG_WriteBits(msg, 1, 1); // not a zero + if (trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && trunc + FLOAT_INT_BIAS < (1 << FLOAT_INT_BITS)) { // send as small integer - MSG_WriteBits( msg, 0, 1 ); - MSG_WriteBits( msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS ); + MSG_WriteBits(msg, 0, 1); + MSG_WriteBits(msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS); } else { // send as full floating point value - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, *toF, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, *toF, 32); } } - } else { + } else { if (*toF == 0) { - MSG_WriteBits( msg, 0, 1 ); //it's a zero + MSG_WriteBits(msg, 0, 1); // it's a zero } else { - MSG_WriteBits( msg, 1, 1 ); //not a zero + MSG_WriteBits(msg, 1, 1); // not a zero // integer - MSG_WriteBits( msg, *toF, field->bits ); + MSG_WriteBits(msg, *toF, field->bits); } - } + } } -void MSG_ReadField (msg_t *msg, int *toF, const netField_t *field, int print) -{ - int trunc; +void MSG_ReadField(msg_t *msg, int *toF, const netField_t *field, int print) { + int trunc; - if ( field->bits == -1) - { // a -1 in the bits field means it's a float that's always between -1 and 1 - int temp = MSG_ReadBits( msg, -16); + if (field->bits == -1) { // a -1 in the bits field means it's a float that's always between -1 and 1 + int temp = MSG_ReadBits(msg, -16); *(float *)toF = (float)temp / 32767; - } - else - if ( field->bits == 0 ) { - // float - if ( MSG_ReadBits( msg, 1 ) == 0 ) { - *(float *)toF = 0.0f; + } else if (field->bits == 0) { + // float + if (MSG_ReadBits(msg, 1) == 0) { + *(float *)toF = 0.0f; } else { - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { // integral float - trunc = MSG_ReadBits( msg, FLOAT_INT_BITS ); + trunc = MSG_ReadBits(msg, FLOAT_INT_BITS); // bias to allow equal parts positive and negative trunc -= FLOAT_INT_BIAS; *(float *)toF = trunc; - if ( print ) { - Com_Printf( "%s:%i ", field->name, trunc ); + if (print) { + Com_Printf("%s:%i ", field->name, trunc); } } else { // full floating point value - *toF = MSG_ReadBits( msg, 32 ); - if ( print ) { - Com_Printf( "%s:%f ", field->name, *(float *)toF ); + *toF = MSG_ReadBits(msg, 32); + if (print) { + Com_Printf("%s:%f ", field->name, *(float *)toF); } } } } else { - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { *toF = 0; } else { // integer - *toF = MSG_ReadBits( msg, field->bits ); - if ( print ) { - Com_Printf( "%s:%i ", field->name, *toF ); + *toF = MSG_ReadBits(msg, field->bits); + if (print) { + Com_Printf("%s:%i ", field->name, *toF); } } } } - /* ================== MSG_WriteDeltaEntity @@ -803,33 +777,30 @@ void MSG_WriteDeltaEntity( msg_t *msg, struct entityState_s *from, struct entity } #endif - extern serverStatic_t svs; -void MSG_WriteEntity( msg_t *msg, struct entityState_s *to, int removeNum) -{ +void MSG_WriteEntity(msg_t *msg, struct entityState_s *to, int removeNum) { - if ( to == NULL ) { + if (to == NULL) { MSG_WriteBits(msg, removeNum, GENTITYNUM_BITS); - MSG_WriteBits(msg, 1, 1); //removed + MSG_WriteBits(msg, 1, 1); // removed return; } else { MSG_WriteBits(msg, to->number, GENTITYNUM_BITS); - MSG_WriteBits(msg, 0, 1); //not removed + MSG_WriteBits(msg, 0, 1); // not removed } - assert(( to - svs.snapshotEntities ) >= 0 && ( to - svs.snapshotEntities ) < 512); + assert((to - svs.snapshotEntities) >= 0 && (to - svs.snapshotEntities) < 512); MSG_WriteLong(msg, to - svs.snapshotEntities); } -void MSG_ReadEntity( msg_t *msg, entityState_t *to) -{ +void MSG_ReadEntity(msg_t *msg, entityState_t *to) { // check for a remove - if ( MSG_ReadBits( msg, 1 ) == 1 ) { - memset( to, 0, sizeof( *to ) ); + if (MSG_ReadBits(msg, 1) == 1) { + memset(to, 0, sizeof(*to)); to->number = MAX_GENTITIES - 1; return; } - //No remove, read data + // No remove, read data int index; index = MSG_ReadLong(msg); assert(index >= 0 && index < svs.numSnapshotEntities); @@ -848,7 +819,7 @@ If the delta removes the entity, entityState_t->number will be set to MAX_GENTIT Can go from either a baseline or a previous packet_entity ================== */ -extern cvar_t *cl_shownet; +extern cvar_t *cl_shownet; #if 0 // Removed by BTO (VV) void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to, int number) @@ -946,86 +917,85 @@ plyer_state_t communication */ // using the stringizing operator to save typing... -#define PSF(x) #x,offsetof(playerState_t, x) +#define PSF(x) #x, offsetof(playerState_t, x) -static const netField_t playerStateFields[] = -{ -{ PSF(commandTime), 32 }, -{ PSF(pm_type), 8 }, -{ PSF(bobCycle), 8 }, +static const netField_t playerStateFields[] = { + {PSF(commandTime), 32}, + {PSF(pm_type), 8}, + {PSF(bobCycle), 8}, #ifdef JK2_MODE -{ PSF(pm_flags), 17 }, + {PSF(pm_flags), 17}, #else -{ PSF(pm_flags), 32 }, + {PSF(pm_flags), 32}, #endif // JK2_MODE -{ PSF(pm_time), -16 }, -{ PSF(origin[0]), 0 }, -{ PSF(origin[1]), 0 }, -{ PSF(origin[2]), 0 }, -{ PSF(velocity[0]), 0 }, -{ PSF(velocity[1]), 0 }, -{ PSF(velocity[2]), 0 }, -{ PSF(weaponTime), -16 }, -{ PSF(weaponChargeTime), 32 }, //? really need 32 bits?? -{ PSF(gravity), 16 }, -{ PSF(leanofs), -8 }, -{ PSF(friction), 16 }, -{ PSF(speed), 16 }, -{ PSF(delta_angles[0]), 16 }, -{ PSF(delta_angles[1]), 16 }, -{ PSF(delta_angles[2]), 16 }, -{ PSF(groundEntityNum), GENTITYNUM_BITS }, -//{ PSF(animationTimer), 16 }, -{ PSF(legsAnim), 16 }, -{ PSF(torsoAnim), 16 }, -{ PSF(movementDir), 4 }, -{ PSF(eFlags), 32 }, -{ PSF(eventSequence), 16 }, -{ PSF(events[0]), 8 }, -{ PSF(events[1]), 8 }, -{ PSF(eventParms[0]), -9 }, -{ PSF(eventParms[1]), -9 }, -{ PSF(externalEvent), 8 }, -{ PSF(externalEventParm), 8 }, -{ PSF(clientNum), 32 }, -{ PSF(weapon), 5 }, -{ PSF(weaponstate), 4 }, -{ PSF(batteryCharge), 16 }, -{ PSF(viewangles[0]), 0 }, -{ PSF(viewangles[1]), 0 }, -{ PSF(viewangles[2]), 0 }, -{ PSF(viewheight), -8 }, -{ PSF(damageEvent), 8 }, -{ PSF(damageYaw), 8 }, -{ PSF(damagePitch), -8 }, -{ PSF(damageCount), 8 }, + {PSF(pm_time), -16}, + {PSF(origin[0]), 0}, + {PSF(origin[1]), 0}, + {PSF(origin[2]), 0}, + {PSF(velocity[0]), 0}, + {PSF(velocity[1]), 0}, + {PSF(velocity[2]), 0}, + {PSF(weaponTime), -16}, + {PSF(weaponChargeTime), 32}, //? really need 32 bits?? + {PSF(gravity), 16}, + {PSF(leanofs), -8}, + {PSF(friction), 16}, + {PSF(speed), 16}, + {PSF(delta_angles[0]), 16}, + {PSF(delta_angles[1]), 16}, + {PSF(delta_angles[2]), 16}, + {PSF(groundEntityNum), GENTITYNUM_BITS}, + //{ PSF(animationTimer), 16 }, + {PSF(legsAnim), 16}, + {PSF(torsoAnim), 16}, + {PSF(movementDir), 4}, + {PSF(eFlags), 32}, + {PSF(eventSequence), 16}, + {PSF(events[0]), 8}, + {PSF(events[1]), 8}, + {PSF(eventParms[0]), -9}, + {PSF(eventParms[1]), -9}, + {PSF(externalEvent), 8}, + {PSF(externalEventParm), 8}, + {PSF(clientNum), 32}, + {PSF(weapon), 5}, + {PSF(weaponstate), 4}, + {PSF(batteryCharge), 16}, + {PSF(viewangles[0]), 0}, + {PSF(viewangles[1]), 0}, + {PSF(viewangles[2]), 0}, + {PSF(viewheight), -8}, + {PSF(damageEvent), 8}, + {PSF(damageYaw), 8}, + {PSF(damagePitch), -8}, + {PSF(damageCount), 8}, #ifdef JK2_MODE -{ PSF(saberColor), 8 }, -{ PSF(saberActive), 8 }, -{ PSF(saberLength), 32 }, -{ PSF(saberLengthMax), 32 }, + {PSF(saberColor), 8}, + {PSF(saberActive), 8}, + {PSF(saberLength), 32}, + {PSF(saberLengthMax), 32}, #endif -{ PSF(forcePowersActive), 32}, -{ PSF(saberInFlight), 8 }, + {PSF(forcePowersActive), 32}, + {PSF(saberInFlight), 8}, #ifdef JK2_MODE -{ PSF(vehicleModel), 32 }, + {PSF(vehicleModel), 32}, #endif -/*{ PSF(vehicleIndex), 32 }, // WOAH, what do we do with this stuff??? -{ PSF(vehicleArmor), 32 }, -{ PSF(vehicleAngles[0]), 0 }, -{ PSF(vehicleAngles[1]), 0 }, -{ PSF(vehicleAngles[2]), 0 },*/ + /*{ PSF(vehicleIndex), 32 }, // WOAH, what do we do with this stuff??? + { PSF(vehicleArmor), 32 }, + { PSF(vehicleAngles[0]), 0 }, + { PSF(vehicleAngles[1]), 0 }, + { PSF(vehicleAngles[2]), 0 },*/ -{ PSF(viewEntity), 32 }, -{ PSF(serverViewOrg[0]), 0 }, -{ PSF(serverViewOrg[1]), 0 }, -{ PSF(serverViewOrg[2]), 0 }, + {PSF(viewEntity), 32}, + {PSF(serverViewOrg[0]), 0}, + {PSF(serverViewOrg[1]), 0}, + {PSF(serverViewOrg[2]), 0}, #ifndef JK2_MODE -{ PSF(forceRageRecoveryTime), 32 }, + {PSF(forceRageRecoveryTime), 32}, #endif // !JK2_MODE }; @@ -1035,253 +1005,240 @@ MSG_WriteDeltaPlayerstate ============= */ -void MSG_WriteDeltaPlayerstate( msg_t *msg, playerState_t *from, playerState_t *to ) { - int i; - playerState_t dummy; - int statsbits; - int persistantbits; - int ammobits; - int powerupbits; - int numFields; - int c; - const netField_t *field; - int *fromF, *toF; +void MSG_WriteDeltaPlayerstate(msg_t *msg, playerState_t *from, playerState_t *to) { + int i; + playerState_t dummy; + int statsbits; + int persistantbits; + int ammobits; + int powerupbits; + int numFields; + int c; + const netField_t *field; + int *fromF, *toF; if (!from) { from = &dummy; - memset (&dummy, 0, sizeof(dummy)); + memset(&dummy, 0, sizeof(dummy)); } c = msg->cursize; - numFields = sizeof( playerStateFields ) / sizeof( playerStateFields[0] ); - for ( i = 0, field = playerStateFields ; i < numFields ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + numFields = sizeof(playerStateFields) / sizeof(playerStateFields[0]); + for (i = 0, field = playerStateFields; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); - if ( *fromF == *toF ) { - MSG_WriteBits( msg, 0, 1 ); // no change + if (*fromF == *toF) { + MSG_WriteBits(msg, 0, 1); // no change continue; } - MSG_WriteBits( msg, 1, 1 ); // changed - MSG_WriteField (msg, toF, field); + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteField(msg, toF, field); } c = msg->cursize - c; - // // send the arrays // statsbits = 0; - for (i=0 ; istats[i] != from->stats[i]) { - statsbits |= 1<stats[i], 32); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - persistantbits = 0; - for (i=0 ; ipersistant[i] != from->persistant[i]) { - persistantbits |= 1<persistant[i]); + if (persistantbits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteShort(msg, persistantbits); + for (i = 0; i < MAX_PERSISTANT; i++) + if (persistantbits & (1 << i)) + MSG_WriteSShort(msg, to->persistant[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - ammobits = 0; - for (i=0 ; iammo[i] != from->ammo[i]) { - ammobits |= 1<ammo[i]); + if (ammobits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteShort(msg, ammobits); + for (i = 0; i < MAX_AMMO; i++) + if (ammobits & (1 << i)) + MSG_WriteSShort(msg, to->ammo[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } powerupbits = 0; - for (i=0 ; ipowerups[i] != from->powerups[i]) { - powerupbits |= 1<powerups[i] ); + if (powerupbits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteShort(msg, powerupbits); + for (i = 0; i < MAX_POWERUPS; i++) + if (powerupbits & (1 << i)) + MSG_WriteLong(msg, to->powerups[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - statsbits = 0; - for (i=0 ; iinventory[i] != from->inventory[i]) - { - statsbits |= 1<inventory[i] != from->inventory[i]) { + statsbits |= 1 << i; } } - if ( statsbits ) - { - MSG_WriteBits( msg, 1, 1 ); // changed - MSG_WriteShort( msg, statsbits ); - for (i=0 ; iinventory[i]); + if (statsbits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteShort(msg, statsbits); + for (i = 0; i < MAX_INVENTORY; i++) { + if (statsbits & (1 << i)) { + MSG_WriteShort(msg, to->inventory[i]); } } - } - else - { - MSG_WriteBits( msg, 0, 1 ); // no change + } else { + MSG_WriteBits(msg, 0, 1); // no change } } - /* =================== MSG_ReadDeltaPlayerstate =================== */ -void MSG_ReadDeltaPlayerstate (msg_t *msg, playerState_t *from, playerState_t *to ) { - int i; - int bits; - const netField_t *field; - int numFields; - int startBit, endBit; - int print; - int *fromF, *toF; - playerState_t dummy; +void MSG_ReadDeltaPlayerstate(msg_t *msg, playerState_t *from, playerState_t *to) { + int i; + int bits; + const netField_t *field; + int numFields; + int startBit, endBit; + int print; + int *fromF, *toF; + playerState_t dummy; - if ( !from ) { + if (!from) { from = &dummy; - memset( &dummy, 0, sizeof( dummy ) ); + memset(&dummy, 0, sizeof(dummy)); } *to = *from; - if ( msg->bit == 0 ) { + if (msg->bit == 0) { startBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - startBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + startBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } // shownet 2/3 will interleave with other printed info, -2 will // just print the delta records - if ( cl_shownet->integer >= 2 || cl_shownet->integer == -2 ) { + if (cl_shownet->integer >= 2 || cl_shownet->integer == -2) { print = 1; - Com_Printf( "%3i: playerstate ", msg->readcount ); + Com_Printf("%3i: playerstate ", msg->readcount); } else { print = 0; } - numFields = sizeof( playerStateFields ) / sizeof( playerStateFields[0] ); - for ( i = 0, field = playerStateFields ; i < numFields ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + numFields = sizeof(playerStateFields) / sizeof(playerStateFields[0]); + for (i = 0, field = playerStateFields; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); - if ( ! MSG_ReadBits( msg, 1 ) ) { + if (!MSG_ReadBits(msg, 1)) { // no change *toF = *fromF; } else { - MSG_ReadField( msg, toF, field, print); + MSG_ReadField(msg, toF, field, print); } } // read the arrays // parse stats - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_STATS"); - bits = MSG_ReadShort (msg); - for (i=0 ; istats[i] = MSG_ReadBits(msg,32); + bits = MSG_ReadShort(msg); + for (i = 0; i < MAX_STATS; i++) { + if (bits & (1 << i)) { + to->stats[i] = MSG_ReadBits(msg, 32); } } } // parse persistant stats - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_PERSISTANT"); - bits = MSG_ReadShort (msg); - for (i=0 ; ipersistant[i] = MSG_ReadSShort(msg); } } } // parse ammo - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_AMMO"); - bits = MSG_ReadShort (msg); - for (i=0 ; iammo[i] = MSG_ReadSShort(msg); } } } // parse powerups - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_POWERUPS"); - bits = MSG_ReadShort (msg); - for (i=0 ; ipowerups[i] = MSG_ReadLong(msg); } } } // parse inventory - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_INVENTORY"); - bits = MSG_ReadShort (msg); - for (i=0 ; iinventory[i] = MSG_ReadShort(msg); } } } - if ( print ) { - if ( msg->bit == 0 ) { + if (print) { + if (msg->bit == 0) { endBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - endBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + endBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } - Com_Printf( " (%i bits)\n", endBit - startBit ); + Com_Printf(" (%i bits)\n", endBit - startBit); } } - //=========================================================================== diff --git a/code/qcommon/net_chan.cpp b/code/qcommon/net_chan.cpp index 79bc3336ea..b24c49fc48 100644 --- a/code/qcommon/net_chan.cpp +++ b/code/qcommon/net_chan.cpp @@ -48,9 +48,8 @@ to the new value before sending out any replies. */ - -#define MAX_PACKETLEN (MAX_MSGLEN) //(1400) // max size of a network packet -#define MAX_LOOPDATA 16 * 1024 +#define MAX_PACKETLEN (MAX_MSGLEN) //(1400) // max size of a network packet +#define MAX_LOOPDATA 16 * 1024 #if (MAX_PACKETLEN > MAX_MSGLEN) #error MAX_PACKETLEN must be <= MAX_MSGLEN @@ -59,27 +58,23 @@ to the new value before sending out any replies. #error MAX_LOOPDATA must be <= MAX_MSGLEN #endif -#define FRAGMENT_SIZE (MAX_PACKETLEN - 100) -#define PACKET_HEADER 10 // two ints and a short +#define FRAGMENT_SIZE (MAX_PACKETLEN - 100) +#define PACKET_HEADER 10 // two ints and a short -#define FRAGMENT_BIT (1<<31) +#define FRAGMENT_BIT (1 << 31) -cvar_t *showpackets; -cvar_t *showdrop; -cvar_t *qport; +cvar_t *showpackets; +cvar_t *showdrop; +cvar_t *qport; -static const char *netsrcString[2] = { - "client", - "server" -}; +static const char *netsrcString[2] = {"client", "server"}; typedef struct { char loopData[MAX_LOOPDATA]; - int get, send; + int get, send; } loopback_t; -static loopback_t *loopbacks = NULL; - +static loopback_t *loopbacks = NULL; /* =============== @@ -87,22 +82,19 @@ Netchan_Init =============== */ -void Netchan_Init( int port ) { - if (!loopbacks) - { - loopbacks = (loopback_t*) Z_Malloc(sizeof(loopback_t) * 2, TAG_NEWDEL, qtrue); +void Netchan_Init(int port) { + if (!loopbacks) { + loopbacks = (loopback_t *)Z_Malloc(sizeof(loopback_t) * 2, TAG_NEWDEL, qtrue); } port &= 0xffff; - showpackets = Cvar_Get ("showpackets", "0", CVAR_TEMP ); - showdrop = Cvar_Get ("showdrop", "0", CVAR_TEMP ); - qport = Cvar_Get ("net_qport", va("%i", port), CVAR_INIT ); + showpackets = Cvar_Get("showpackets", "0", CVAR_TEMP); + showdrop = Cvar_Get("showdrop", "0", CVAR_TEMP); + qport = Cvar_Get("net_qport", va("%i", port), CVAR_INIT); } -void Netchan_Shutdown() -{ - if (loopbacks) - { +void Netchan_Shutdown() { + if (loopbacks) { Z_Free(loopbacks); loopbacks = 0; } @@ -115,8 +107,8 @@ Netchan_Setup called to open a channel to a remote system ============== */ -void Netchan_Setup( netsrc_t sock, netchan_t *chan, netadr_t adr, int qport ) { - memset (chan, 0, sizeof(*chan)); +void Netchan_Setup(netsrc_t sock, netchan_t *chan, netadr_t adr, int qport) { + memset(chan, 0, sizeof(*chan)); chan->sock = sock; chan->remoteAddress = adr; @@ -133,49 +125,45 @@ Sends a message to a connection, fragmenting if necessary A 0 length will still generate a packet. ================ */ -void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) { - msg_t send; - byte send_buf[MAX_PACKETLEN]; - int fragmentStart, fragmentLength; +void Netchan_Transmit(netchan_t *chan, int length, const byte *data) { + msg_t send; + byte send_buf[MAX_PACKETLEN]; + int fragmentStart, fragmentLength; - fragmentStart = 0; // stop warning message + fragmentStart = 0; // stop warning message fragmentLength = 0; // fragment large reliable messages - if ( length >= FRAGMENT_SIZE ) { + if (length >= FRAGMENT_SIZE) { fragmentStart = 0; do { // write the packet header - MSG_Init (&send, send_buf, sizeof(send_buf)); + MSG_Init(&send, send_buf, sizeof(send_buf)); - MSG_WriteLong( &send, chan->outgoingSequence | FRAGMENT_BIT ); - MSG_WriteLong( &send, chan->incomingSequence ); + MSG_WriteLong(&send, chan->outgoingSequence | FRAGMENT_BIT); + MSG_WriteLong(&send, chan->incomingSequence); // send the qport if we are a client - if ( chan->sock == NS_CLIENT ) { - MSG_WriteShort( &send, qport->integer ); + if (chan->sock == NS_CLIENT) { + MSG_WriteShort(&send, qport->integer); } // copy the reliable message to the packet first fragmentLength = FRAGMENT_SIZE; - if ( fragmentStart + fragmentLength > length ) { + if (fragmentStart + fragmentLength > length) { fragmentLength = length - fragmentStart; } - MSG_WriteShort( &send, fragmentStart ); - MSG_WriteShort( &send, fragmentLength ); - MSG_WriteData( &send, data + fragmentStart, fragmentLength ); + MSG_WriteShort(&send, fragmentStart); + MSG_WriteShort(&send, fragmentLength); + MSG_WriteData(&send, data + fragmentStart, fragmentLength); // send the datagram - NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress ); - - if ( showpackets->integer ) { - Com_Printf ("%s send %4i : s=%i ack=%i fragment=%i,%i\n" - , netsrcString[ chan->sock ] - , send.cursize - , chan->outgoingSequence - 1 - , chan->incomingSequence - , fragmentStart, fragmentLength); + NET_SendPacket(chan->sock, send.cursize, send.data, chan->remoteAddress); + + if (showpackets->integer) { + Com_Printf("%s send %4i : s=%i ack=%i fragment=%i,%i\n", netsrcString[chan->sock], send.cursize, chan->outgoingSequence - 1, + chan->incomingSequence, fragmentStart, fragmentLength); } fragmentStart += fragmentLength; @@ -183,35 +171,31 @@ void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) { // that is exactly the fragment length still needs to send // a second packet of zero length so that the other side // can tell there aren't more to follow - } while ( fragmentStart != length || fragmentLength == FRAGMENT_SIZE ); + } while (fragmentStart != length || fragmentLength == FRAGMENT_SIZE); chan->outgoingSequence++; return; } // write the packet header - MSG_Init (&send, send_buf, sizeof(send_buf)); + MSG_Init(&send, send_buf, sizeof(send_buf)); - MSG_WriteLong( &send, chan->outgoingSequence ); - MSG_WriteLong( &send, chan->incomingSequence ); + MSG_WriteLong(&send, chan->outgoingSequence); + MSG_WriteLong(&send, chan->incomingSequence); chan->outgoingSequence++; // send the qport if we are a client - if ( chan->sock == NS_CLIENT ) { - MSG_WriteShort( &send, qport->integer ); + if (chan->sock == NS_CLIENT) { + MSG_WriteShort(&send, qport->integer); } - MSG_WriteData( &send, data, length ); + MSG_WriteData(&send, data, length); // send the datagram - NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress ); - - if ( showpackets->integer ) { - Com_Printf( "%s send %4i : s=%i ack=%i\n" - , netsrcString[ chan->sock ] - , send.cursize - , chan->outgoingSequence - 1 - , chan->incomingSequence ); + NET_SendPacket(chan->sock, send.cursize, send.data, chan->remoteAddress); + + if (showpackets->integer) { + Com_Printf("%s send %4i : s=%i ack=%i\n", netsrcString[chan->sock], send.cursize, chan->outgoingSequence - 1, chan->incomingSequence); } } @@ -227,19 +211,19 @@ final fragment of a multi-part message, the entire thing will be copied out. ================= */ -qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { - int sequence, sequence_ack; - //int qport; - int fragmentStart, fragmentLength; - qboolean fragmented; +qboolean Netchan_Process(netchan_t *chan, msg_t *msg) { + int sequence, sequence_ack; + // int qport; + int fragmentStart, fragmentLength; + qboolean fragmented; // get sequence numbers - MSG_BeginReading( msg ); - sequence = MSG_ReadLong( msg ); - sequence_ack = MSG_ReadLong( msg ); + MSG_BeginReading(msg); + sequence = MSG_ReadLong(msg); + sequence_ack = MSG_ReadLong(msg); // check for fragment information - if ( sequence & FRAGMENT_BIT ) { + if (sequence & FRAGMENT_BIT) { sequence &= ~FRAGMENT_BIT; fragmented = qtrue; } else { @@ -247,45 +231,34 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { } // read the qport if we are a server - if ( chan->sock == NS_SERVER ) { - /*qport = */MSG_ReadShort( msg ); + if (chan->sock == NS_SERVER) { + /*qport = */ MSG_ReadShort(msg); } // read the fragment information - if ( fragmented ) { - fragmentStart = MSG_ReadShort( msg ); - fragmentLength = MSG_ReadShort( msg ); + if (fragmented) { + fragmentStart = MSG_ReadShort(msg); + fragmentLength = MSG_ReadShort(msg); } else { - fragmentStart = 0; // stop warning message + fragmentStart = 0; // stop warning message fragmentLength = 0; } - if ( showpackets->integer ) { - if ( fragmented ) { - Com_Printf( "%s recv %4i : s=%i ack=%i fragment=%i,%i\n" - , netsrcString[ chan->sock ] - , msg->cursize - , sequence - , sequence_ack - , fragmentStart, fragmentLength ); + if (showpackets->integer) { + if (fragmented) { + Com_Printf("%s recv %4i : s=%i ack=%i fragment=%i,%i\n", netsrcString[chan->sock], msg->cursize, sequence, sequence_ack, fragmentStart, + fragmentLength); } else { - Com_Printf( "%s recv %4i : s=%i ack=%i\n" - , netsrcString[ chan->sock ] - , msg->cursize - , sequence - , sequence_ack ); + Com_Printf("%s recv %4i : s=%i ack=%i\n", netsrcString[chan->sock], msg->cursize, sequence, sequence_ack); } } // // discard out of order or duplicated packets // - if ( sequence <= chan->incomingSequence ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Out of order packet %i at %i\n" - , NET_AdrToString( chan->remoteAddress ) - , sequence - , chan->incomingSequence ); + if (sequence <= chan->incomingSequence) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Out of order packet %i at %i\n", NET_AdrToString(chan->remoteAddress), sequence, chan->incomingSequence); } return qfalse; } @@ -293,34 +266,28 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { // // dropped packets don't keep the message from being used // - chan->dropped = sequence - (chan->incomingSequence+1); - if ( chan->dropped > 0 ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Dropped %i packets at %i\n" - , NET_AdrToString( chan->remoteAddress ) - , chan->dropped - , sequence ); + chan->dropped = sequence - (chan->incomingSequence + 1); + if (chan->dropped > 0) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Dropped %i packets at %i\n", NET_AdrToString(chan->remoteAddress), chan->dropped, sequence); } } - // // if this is the final framgent of a reliable message, // bump incoming_reliable_sequence // - if ( fragmented ) { + if (fragmented) { // make sure we - if ( sequence != chan->fragmentSequence ) { + if (sequence != chan->fragmentSequence) { chan->fragmentSequence = sequence; chan->fragmentLength = 0; } // if we missed a fragment, dump the message - if ( fragmentStart != chan->fragmentLength ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Dropped a message fragment\n" - , NET_AdrToString( chan->remoteAddress ) - , sequence); + if (fragmentStart != chan->fragmentLength) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Dropped a message fragment\n", NET_AdrToString(chan->remoteAddress), sequence); } // we can still keep the part that we have so far, // so we don't need to clear chan->fragmentLength @@ -328,41 +295,36 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { } // copy the fragment to the fragment buffer - if ( fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize || - chan->fragmentLength + fragmentLength > (int)sizeof( chan->fragmentBuffer ) ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf ("%s:illegal fragment length\n" - , NET_AdrToString (chan->remoteAddress ) ); + if (fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize || chan->fragmentLength + fragmentLength > (int)sizeof(chan->fragmentBuffer)) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:illegal fragment length\n", NET_AdrToString(chan->remoteAddress)); } return qfalse; } - memcpy( chan->fragmentBuffer + chan->fragmentLength, - msg->data + msg->readcount, fragmentLength ); + memcpy(chan->fragmentBuffer + chan->fragmentLength, msg->data + msg->readcount, fragmentLength); chan->fragmentLength += fragmentLength; // if this wasn't the last fragment, don't process anything - if ( fragmentLength == FRAGMENT_SIZE ) { + if (fragmentLength == FRAGMENT_SIZE) { return qfalse; } - if ( chan->fragmentLength > msg->maxsize ) { - Com_Printf( "%s:fragmentLength %i > msg->maxsize\n" - , NET_AdrToString (chan->remoteAddress ), - chan->fragmentLength ); + if (chan->fragmentLength > msg->maxsize) { + Com_Printf("%s:fragmentLength %i > msg->maxsize\n", NET_AdrToString(chan->remoteAddress), chan->fragmentLength); return qfalse; } // copy the full message over the partial fragment // make sure the sequence number is still there - *(int *)msg->data = LittleLong( sequence ); + *(int *)msg->data = LittleLong(sequence); - memcpy( msg->data + 4, chan->fragmentBuffer, chan->fragmentLength ); + memcpy(msg->data + 4, chan->fragmentBuffer, chan->fragmentLength); msg->cursize = chan->fragmentLength + 4; chan->fragmentLength = 0; - msg->readcount = 4; // past the sequence number + msg->readcount = 4; // past the sequence number return qtrue; } @@ -376,7 +338,6 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { return qtrue; } - //============================================================================== /* @@ -386,48 +347,39 @@ NET_CompareBaseAdr Compares without the port =================== */ -qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b) -{ +qboolean NET_CompareBaseAdr(netadr_t a, netadr_t b) { if (a.type != b.type) return qfalse; if (a.type == NA_LOOPBACK) return qtrue; - Com_Printf ("NET_CompareBaseAdr: bad address type\n"); + Com_Printf("NET_CompareBaseAdr: bad address type\n"); return qfalse; } -const char *NET_AdrToString (netadr_t a) -{ - static char s[64]; +const char *NET_AdrToString(netadr_t a) { + static char s[64]; if (a.type == NA_LOOPBACK) { - Com_sprintf (s, sizeof(s), "loopback"); + Com_sprintf(s, sizeof(s), "loopback"); } return s; } - -qboolean NET_CompareAdr (netadr_t a, netadr_t b) -{ +qboolean NET_CompareAdr(netadr_t a, netadr_t b) { if (a.type != b.type) return qfalse; if (a.type == NA_LOOPBACK) return qtrue; - Com_Printf ("NET_CompareAdr: bad address type\n"); + Com_Printf("NET_CompareAdr: bad address type\n"); return qfalse; } - -qboolean NET_IsLocalAddress( netadr_t adr ) { - return (qboolean)(adr.type == NA_LOOPBACK); -} - - +qboolean NET_IsLocalAddress(netadr_t adr) { return (qboolean)(adr.type == NA_LOOPBACK); } /* ============================================================================= @@ -437,63 +389,59 @@ LOOPBACK BUFFERS FOR LOCAL PLAYER ============================================================================= */ -qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message) -{ - int i; - loopback_t *loop; +qboolean NET_GetLoopPacket(netsrc_t sock, netadr_t *net_from, msg_t *net_message) { + int i; + loopback_t *loop; loop = &loopbacks[sock]; - //If read and write positions are the same, nothing left to read. + // If read and write positions are the same, nothing left to read. if (loop->get == loop->send) return qfalse; - //Get read position. Wrap if too close to end. + // Get read position. Wrap if too close to end. i = loop->get; - if(i > MAX_LOOPDATA - 4) { + if (i > MAX_LOOPDATA - 4) { i = 0; } - //Get length of packet. + // Get length of packet. byteAlias_t *ba = (byteAlias_t *)&loop->loopData[i]; const int length = ba->i; i += 4; - //See if entire packet is at end of buffer or part is at the beginning. - if(i + length <= MAX_LOOPDATA) { - //Everything fits, full copy. - memcpy (net_message->data, loop->loopData + i, length); + // See if entire packet is at end of buffer or part is at the beginning. + if (i + length <= MAX_LOOPDATA) { + // Everything fits, full copy. + memcpy(net_message->data, loop->loopData + i, length); net_message->cursize = length; i += length; loop->get = i; } else { - //Doesn't all fit, partial copy + // Doesn't all fit, partial copy const int copyToEnd = MAX_LOOPDATA - i; - memcpy (net_message->data, loop->loopData + i, copyToEnd); - memcpy ((char*)net_message->data + copyToEnd, - loop->loopData, length - copyToEnd); + memcpy(net_message->data, loop->loopData + i, copyToEnd); + memcpy((char *)net_message->data + copyToEnd, loop->loopData, length - copyToEnd); net_message->cursize = length; loop->get = length - copyToEnd; } - memset (net_from, 0, sizeof(*net_from)); + memset(net_from, 0, sizeof(*net_from)); net_from->type = NA_LOOPBACK; return qtrue; } +void NET_SendLoopPacket(netsrc_t sock, int length, const void *data, netadr_t to) { + int i; + loopback_t *loop; -void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t to) -{ - int i; - loopback_t *loop; - - loop = &loopbacks[sock^1]; + loop = &loopbacks[sock ^ 1]; - //Make sure there is enough free space in the buffer. + // Make sure there is enough free space in the buffer. #ifdef _DEBUG int freeSpace; - if(loop->send >= loop->get) { + if (loop->send >= loop->get) { freeSpace = MAX_LOOPDATA - (loop->send - loop->get); } else { freeSpace = loop->get - loop->send; @@ -502,45 +450,44 @@ void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t t assert(freeSpace > length); #endif // _DEBUG - //Get write position. Wrap around if too close to end. + // Get write position. Wrap around if too close to end. i = loop->send; - if(i > MAX_LOOPDATA - 4) { + if (i > MAX_LOOPDATA - 4) { i = 0; } - //Write length of packet. + // Write length of packet. byteAlias_t *ba = (byteAlias_t *)&loop->loopData[i]; ba->i = length; i += 4; - //See if the whole packet will fit on the end of the buffer or if we - //need to write part of it back at the beginning. - if(i + length <= MAX_LOOPDATA) { - //Everything fits, full copy. - memcpy (loop->loopData + i, data, length); + // See if the whole packet will fit on the end of the buffer or if we + // need to write part of it back at the beginning. + if (i + length <= MAX_LOOPDATA) { + // Everything fits, full copy. + memcpy(loop->loopData + i, data, length); i += length; loop->send = i; } else { - //Doesn't all fit, partial copy + // Doesn't all fit, partial copy int copyToEnd = MAX_LOOPDATA - i; memcpy(loop->loopData + i, data, copyToEnd); - memcpy(loop->loopData, (char*)data + copyToEnd, length - copyToEnd); + memcpy(loop->loopData, (char *)data + copyToEnd, length - copyToEnd); loop->send = length - copyToEnd; } } //============================================================================= - -void NET_SendPacket( netsrc_t sock, int length, const void *data, netadr_t to ) { +void NET_SendPacket(netsrc_t sock, int length, const void *data, netadr_t to) { // sequenced packets are shown in netchan, so just show oob - if ( showpackets->integer && *(int *)data == -1 ) { - Com_Printf ("send packet %4i\n", length); + if (showpackets->integer && *(int *)data == -1) { + Com_Printf("send packet %4i\n", length); } - if ( to.type == NA_LOOPBACK ) { - NET_SendLoopPacket (sock, length, data, to); + if (to.type == NA_LOOPBACK) { + NET_SendLoopPacket(sock, length, data, to); return; } } @@ -552,26 +499,24 @@ NET_OutOfBandPrint Sends a text message in an out-of-band datagram ================ */ -void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, ... ) { - va_list argptr; - char string[MAX_MSGLEN]; +void QDECL NET_OutOfBandPrint(netsrc_t sock, netadr_t adr, const char *format, ...) { + va_list argptr; + char string[MAX_MSGLEN]; // set the header - string[0] = (char) 0xff; - string[1] = (char) 0xff; - string[2] = (char) 0xff; - string[3] = (char) 0xff; + string[0] = (char)0xff; + string[1] = (char)0xff; + string[2] = (char)0xff; + string[3] = (char)0xff; - va_start( argptr, format ); - Q_vsnprintf( string+4, sizeof(string)-4, format, argptr ); - va_end( argptr ); + va_start(argptr, format); + Q_vsnprintf(string + 4, sizeof(string) - 4, format, argptr); + va_end(argptr); // send the datagram - NET_SendPacket( sock, strlen( string ), string, adr ); + NET_SendPacket(sock, strlen(string), string, adr); } - - /* ============= NET_StringToAdr @@ -579,9 +524,9 @@ NET_StringToAdr Traps "localhost" for loopback, passes everything else to system ============= */ -qboolean NET_StringToAdr( const char *s, netadr_t *a ) { - if (!strcmp (s, "localhost")) { - memset (a, 0, sizeof(*a)); +qboolean NET_StringToAdr(const char *s, netadr_t *a) { + if (!strcmp(s, "localhost")) { + memset(a, 0, sizeof(*a)); a->type = NA_LOOPBACK; return qtrue; } @@ -589,4 +534,3 @@ qboolean NET_StringToAdr( const char *s, netadr_t *a ) { a->type = NA_BAD; return qfalse; } - diff --git a/code/qcommon/ojk_saved_game.cpp b/code/qcommon/ojk_saved_game.cpp index d58e23221a..df08259681 100644 --- a/code/qcommon/ojk_saved_game.cpp +++ b/code/qcommon/ojk_saved_game.cpp @@ -2,7 +2,6 @@ // Saved game. // - #include "ojk_saved_game.h" #include #include @@ -10,145 +9,86 @@ #include "qcommon/qcommon.h" #include "server/server.h" +namespace ojk { -namespace ojk -{ - - -SavedGame::SavedGame() : - error_message_(), - file_handle_(), - io_buffer_(), - saved_io_buffer_(), - io_buffer_offset_(), - saved_io_buffer_offset_(), - rle_buffer_(), - is_readable_(), - is_writable_(), - is_failed_() -{ -} +SavedGame::SavedGame() + : error_message_(), file_handle_(), io_buffer_(), saved_io_buffer_(), io_buffer_offset_(), saved_io_buffer_offset_(), rle_buffer_(), is_readable_(), + is_writable_(), is_failed_() {} -SavedGame::~SavedGame() -{ - close(); -} +SavedGame::~SavedGame() { close(); } -bool SavedGame::open( - const std::string& base_file_name) -{ +bool SavedGame::open(const std::string &base_file_name) { close(); - - const std::string file_path = generate_path( - base_file_name); + const std::string file_path = generate_path(base_file_name); bool is_succeed = true; - static_cast(::FS_FOpenFileRead( - file_path.c_str(), - &file_handle_, - qtrue)); + static_cast(::FS_FOpenFileRead(file_path.c_str(), &file_handle_, qtrue)); - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_succeed = false; - error_message_ = - S_COLOR_RED "Failed to open a saved game file: \"" + - file_path + "\"."; + error_message_ = S_COLOR_RED "Failed to open a saved game file: \"" + file_path + "\"."; - ::Com_DPrintf( - "%s\n", - error_message_.c_str()); + ::Com_DPrintf("%s\n", error_message_.c_str()); } - if (is_succeed) - { + if (is_succeed) { is_readable_ = true; } - - if (is_succeed) - { - SavedGameHelper saved_game( - this); + if (is_succeed) { + SavedGameHelper saved_game(this); int sg_version = -1; - if (saved_game.try_read_chunk( - INT_ID('_', 'V', 'E', 'R'), - sg_version)) - { - if (sg_version != iSAVEGAME_VERSION) - { + if (saved_game.try_read_chunk(INT_ID('_', 'V', 'E', 'R'), sg_version)) { + if (sg_version != iSAVEGAME_VERSION) { is_succeed = false; - ::Com_Printf( - S_COLOR_RED "File \"%s\" has version # %d (expecting %d)\n", - base_file_name.c_str(), - sg_version, - iSAVEGAME_VERSION); + ::Com_Printf(S_COLOR_RED "File \"%s\" has version # %d (expecting %d)\n", base_file_name.c_str(), sg_version, iSAVEGAME_VERSION); } - } - else - { + } else { is_succeed = false; - ::Com_Printf( - S_COLOR_RED "Failed to read a version.\n"); + ::Com_Printf(S_COLOR_RED "Failed to read a version.\n"); } } - if (!is_succeed) - { + if (!is_succeed) { close(); } return is_succeed; } -bool SavedGame::create( - const std::string& base_file_name) -{ +bool SavedGame::create(const std::string &base_file_name) { close(); + remove(base_file_name); - remove( - base_file_name); + const std::string file_path = generate_path(base_file_name); - const std::string file_path = generate_path( - base_file_name); + file_handle_ = ::FS_FOpenFileWrite(file_path.c_str()); - file_handle_ = ::FS_FOpenFileWrite( - file_path.c_str()); + if (file_handle_ == 0) { + const std::string error_message = S_COLOR_RED "Failed to create a saved game file: \"" + file_path + "\"."; - if (file_handle_ == 0) - { - const std::string error_message = - S_COLOR_RED "Failed to create a saved game file: \"" + - file_path + "\"."; - - ::Com_Printf( - "%s\n", - error_message.c_str()); + ::Com_Printf("%s\n", error_message.c_str()); return false; } - is_writable_ = true; const int sg_version = iSAVEGAME_VERSION; SavedGameHelper sgsh(this); - sgsh.write_chunk( - INT_ID('_', 'V', 'E', 'R'), - sg_version); + sgsh.write_chunk(INT_ID('_', 'V', 'E', 'R'), sg_version); - if (is_failed()) - { + if (is_failed()) { close(); return false; } @@ -156,10 +96,8 @@ bool SavedGame::create( return true; } -void SavedGame::close() -{ - if (file_handle_ != 0) - { +void SavedGame::close() { + if (file_handle_ != 0) { ::FS_FCloseFile(file_handle_); file_handle_ = 0; } @@ -176,16 +114,12 @@ void SavedGame::close() is_writable_ = false; } -bool SavedGame::read_chunk( - const uint32_t chunk_id) -{ - if (is_failed_) - { +bool SavedGame::read_chunk(const uint32_t chunk_id) { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_failed_ = true; error_message_ = "Not open or created."; return false; @@ -193,48 +127,31 @@ bool SavedGame::read_chunk( io_buffer_offset_ = 0; - const std::string chunk_id_string = get_chunk_id_string( - chunk_id); + const std::string chunk_id_string = get_chunk_id_string(chunk_id); - ::Com_DPrintf( - "Attempting read of chunk %s\n", - chunk_id_string.c_str()); + ::Com_DPrintf("Attempting read of chunk %s\n", chunk_id_string.c_str()); uint32_t loaded_chunk_id = 0; uint32_t loaded_data_size = 0; - int loaded_chunk_size = ::FS_Read( - &loaded_chunk_id, - static_cast(sizeof(loaded_chunk_id)), - file_handle_); + int loaded_chunk_size = ::FS_Read(&loaded_chunk_id, static_cast(sizeof(loaded_chunk_id)), file_handle_); - loaded_chunk_size += ::FS_Read( - &loaded_data_size, - static_cast(sizeof(loaded_data_size)), - file_handle_); + loaded_chunk_size += ::FS_Read(&loaded_data_size, static_cast(sizeof(loaded_data_size)), file_handle_); const bool is_compressed = (static_cast(loaded_data_size) < 0); - if (is_compressed) - { + if (is_compressed) { loaded_data_size = -static_cast(loaded_data_size); } // Make sure we are loading the correct chunk... // - if (loaded_chunk_id != chunk_id) - { + if (loaded_chunk_id != chunk_id) { is_failed_ = true; - const std::string loaded_chunk_id_string = get_chunk_id_string( - loaded_chunk_id); + const std::string loaded_chunk_id_string = get_chunk_id_string(loaded_chunk_id); - error_message_ = - "Loaded chunk ID (" + - loaded_chunk_id_string + - ") does not match requested chunk ID (" + - chunk_id_string + - ")."; + error_message_ = "Loaded chunk ID (" + loaded_chunk_id_string + ") does not match requested chunk ID (" + chunk_id_string + ")."; return false; } @@ -244,109 +161,71 @@ bool SavedGame::read_chunk( #ifdef JK2_MODE // Get checksum... // - loaded_chunk_size += ::FS_Read( - &loaded_checksum, - static_cast(sizeof(loaded_checksum)), - file_handle_); + loaded_chunk_size += ::FS_Read(&loaded_checksum, static_cast(sizeof(loaded_checksum)), file_handle_); #endif // JK2_MODE // Load in data and magic number... // uint32_t compressed_size = 0; - if (is_compressed) - { - loaded_chunk_size += ::FS_Read( - &compressed_size, - static_cast(sizeof(compressed_size)), - file_handle_); + if (is_compressed) { + loaded_chunk_size += ::FS_Read(&compressed_size, static_cast(sizeof(compressed_size)), file_handle_); - rle_buffer_.resize( - compressed_size); + rle_buffer_.resize(compressed_size); - loaded_chunk_size += ::FS_Read( - rle_buffer_.data(), - compressed_size, - file_handle_); + loaded_chunk_size += ::FS_Read(rle_buffer_.data(), compressed_size, file_handle_); - io_buffer_.resize( - loaded_data_size); + io_buffer_.resize(loaded_data_size); - decompress( - rle_buffer_, - io_buffer_); - } - else - { - io_buffer_.resize( - loaded_data_size); + decompress(rle_buffer_, io_buffer_); + } else { + io_buffer_.resize(loaded_data_size); - loaded_chunk_size += ::FS_Read( - io_buffer_.data(), - loaded_data_size, - file_handle_); + loaded_chunk_size += ::FS_Read(io_buffer_.data(), loaded_data_size, file_handle_); } #ifdef JK2_MODE uint32_t loaded_magic_value = 0; - loaded_chunk_size += ::FS_Read( - &loaded_magic_value, - static_cast(sizeof(loaded_magic_value)), - file_handle_); + loaded_chunk_size += ::FS_Read(&loaded_magic_value, static_cast(sizeof(loaded_magic_value)), file_handle_); - if (loaded_magic_value != get_jo_magic_value()) - { + if (loaded_magic_value != get_jo_magic_value()) { is_failed_ = true; - error_message_ = - "Bad saved game magic for chunk " + chunk_id_string + "."; + error_message_ = "Bad saved game magic for chunk " + chunk_id_string + "."; return false; } #else // Get checksum... // - loaded_chunk_size += ::FS_Read( - &loaded_checksum, - static_cast(sizeof(loaded_checksum)), - file_handle_); + loaded_chunk_size += ::FS_Read(&loaded_checksum, static_cast(sizeof(loaded_checksum)), file_handle_); #endif // JK2_MODE // Make sure the checksums match... // - const uint32_t checksum = ::Com_BlockChecksum( - io_buffer_.data(), - static_cast(io_buffer_.size())); + const uint32_t checksum = ::Com_BlockChecksum(io_buffer_.data(), static_cast(io_buffer_.size())); - if (loaded_checksum != checksum) - { + if (loaded_checksum != checksum) { is_failed_ = true; - error_message_ = - "Failed checksum check for chunk " + chunk_id_string + "."; + error_message_ = "Failed checksum check for chunk " + chunk_id_string + "."; return false; } // Make sure we didn't encounter any read errors... - std::size_t ref_chunk_size = - sizeof(loaded_chunk_id) + - sizeof(loaded_data_size) + - sizeof(loaded_checksum) + - (is_compressed ? sizeof(compressed_size) : 0) + - (is_compressed ? compressed_size : io_buffer_.size()); + std::size_t ref_chunk_size = sizeof(loaded_chunk_id) + sizeof(loaded_data_size) + sizeof(loaded_checksum) + (is_compressed ? sizeof(compressed_size) : 0) + + (is_compressed ? compressed_size : io_buffer_.size()); #ifdef JK2_MODE ref_chunk_size += sizeof(loaded_magic_value); #endif - if (loaded_chunk_size != static_cast(ref_chunk_size)) - { + if (loaded_chunk_size != static_cast(ref_chunk_size)) { is_failed_ = true; - error_message_ = - "Error during loading chunk " + chunk_id_string + "."; + error_message_ = "Error during loading chunk " + chunk_id_string + "."; return false; } @@ -354,80 +233,57 @@ bool SavedGame::read_chunk( return true; } -bool SavedGame::is_all_data_read() const -{ - if (is_failed_) - { +bool SavedGame::is_all_data_read() const { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { return false; } return io_buffer_.size() == io_buffer_offset_; } -void SavedGame::ensure_all_data_read() -{ - if (!is_all_data_read()) - { +void SavedGame::ensure_all_data_read() { + if (!is_all_data_read()) { error_message_ = "Not all expected data read."; throw_error(); } } -bool SavedGame::write_chunk( - const uint32_t chunk_id) -{ - if (is_failed_) - { +bool SavedGame::write_chunk(const uint32_t chunk_id) { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_failed_ = true; error_message_ = "Not open or created."; return false; } + const std::string chunk_id_string = get_chunk_id_string(chunk_id); - const std::string chunk_id_string = get_chunk_id_string( - chunk_id); + ::Com_DPrintf("Attempting write of chunk %s\n", chunk_id_string.c_str()); - ::Com_DPrintf( - "Attempting write of chunk %s\n", - chunk_id_string.c_str()); - - if (::sv_testsave->integer != 0) - { + if (::sv_testsave->integer != 0) { return true; } const int src_size = static_cast(io_buffer_.size()); - const uint32_t checksum = Com_BlockChecksum( - io_buffer_.data(), - src_size); + const uint32_t checksum = Com_BlockChecksum(io_buffer_.data(), src_size); - uint32_t saved_chunk_size = ::FS_Write( - &chunk_id, - static_cast(sizeof(chunk_id)), - file_handle_); + uint32_t saved_chunk_size = ::FS_Write(&chunk_id, static_cast(sizeof(chunk_id)), file_handle_); int compressed_size = -1; - if (::sv_compress_saved_games->integer != 0) - { - compress( - io_buffer_, - rle_buffer_); + if (::sv_compress_saved_games->integer != 0) { + compress(io_buffer_, rle_buffer_); - if (rle_buffer_.size() < io_buffer_.size()) - { + if (rle_buffer_.size() < io_buffer_.size()) { compressed_size = static_cast(rle_buffer_.size()); } } @@ -436,122 +292,69 @@ bool SavedGame::write_chunk( const uint32_t magic_value = get_jo_magic_value(); #endif // JK2_MODE - if (compressed_size > 0) - { + if (compressed_size > 0) { const int size = -static_cast(io_buffer_.size()); - saved_chunk_size += ::FS_Write( - &size, - static_cast(sizeof(size)), - file_handle_); + saved_chunk_size += ::FS_Write(&size, static_cast(sizeof(size)), file_handle_); #ifdef JK2_MODE - saved_chunk_size += ::FS_Write( - &checksum, - static_cast(sizeof(checksum)), - file_handle_); + saved_chunk_size += ::FS_Write(&checksum, static_cast(sizeof(checksum)), file_handle_); #endif // JK2_MODE - saved_chunk_size += ::FS_Write( - &compressed_size, - static_cast(sizeof(compressed_size)), - file_handle_); + saved_chunk_size += ::FS_Write(&compressed_size, static_cast(sizeof(compressed_size)), file_handle_); - saved_chunk_size += ::FS_Write( - rle_buffer_.data(), - compressed_size, - file_handle_); + saved_chunk_size += ::FS_Write(rle_buffer_.data(), compressed_size, file_handle_); #ifdef JK2_MODE - saved_chunk_size += ::FS_Write( - &magic_value, - static_cast(sizeof(magic_value)), - file_handle_); + saved_chunk_size += ::FS_Write(&magic_value, static_cast(sizeof(magic_value)), file_handle_); #else - saved_chunk_size += ::FS_Write( - &checksum, - static_cast(sizeof(checksum)), - file_handle_); + saved_chunk_size += ::FS_Write(&checksum, static_cast(sizeof(checksum)), file_handle_); #endif // JK2_MODE - std::size_t ref_chunk_size = - sizeof(chunk_id) + - sizeof(size) + - sizeof(checksum) + - sizeof(compressed_size) + - compressed_size; + std::size_t ref_chunk_size = sizeof(chunk_id) + sizeof(size) + sizeof(checksum) + sizeof(compressed_size) + compressed_size; #ifdef JK2_MODE ref_chunk_size += sizeof(magic_value); #endif // JK2_MODE - if (saved_chunk_size != ref_chunk_size) - { + if (saved_chunk_size != ref_chunk_size) { is_failed_ = true; error_message_ = "Failed to write " + chunk_id_string + " chunk."; - ::Com_Printf( - "%s%s\n", - S_COLOR_RED, - error_message_.c_str()); + ::Com_Printf("%s%s\n", S_COLOR_RED, error_message_.c_str()); return false; } - } - else - { + } else { const uint32_t size = static_cast(io_buffer_.size()); - saved_chunk_size += ::FS_Write( - &size, - static_cast(sizeof(size)), - file_handle_); + saved_chunk_size += ::FS_Write(&size, static_cast(sizeof(size)), file_handle_); #ifdef JK2_MODE - saved_chunk_size += ::FS_Write( - &checksum, - static_cast(sizeof(checksum)), - file_handle_); + saved_chunk_size += ::FS_Write(&checksum, static_cast(sizeof(checksum)), file_handle_); #endif // JK2_MODE - saved_chunk_size += ::FS_Write( - io_buffer_.data(), - size, - file_handle_); + saved_chunk_size += ::FS_Write(io_buffer_.data(), size, file_handle_); #ifdef JK2_MODE - saved_chunk_size += ::FS_Write( - &magic_value, - static_cast(sizeof(magic_value)), - file_handle_); + saved_chunk_size += ::FS_Write(&magic_value, static_cast(sizeof(magic_value)), file_handle_); #else - saved_chunk_size += ::FS_Write( - &checksum, - static_cast(sizeof(checksum)), - file_handle_); + saved_chunk_size += ::FS_Write(&checksum, static_cast(sizeof(checksum)), file_handle_); #endif // JK2_MODE - std::size_t ref_chunk_size = - sizeof(chunk_id) + - sizeof(size) + - sizeof(checksum) + - size; + std::size_t ref_chunk_size = sizeof(chunk_id) + sizeof(size) + sizeof(checksum) + size; #ifdef JK2_MODE ref_chunk_size += sizeof(magic_value); #endif // JK2_MODE - if (saved_chunk_size != ref_chunk_size) - { + if (saved_chunk_size != ref_chunk_size) { is_failed_ = true; error_message_ = "Failed to write " + chunk_id_string + " chunk."; - ::Com_Printf( - "%s%s\n", - S_COLOR_RED, - error_message_.c_str()); + ::Com_Printf("%s%s\n", S_COLOR_RED, error_message_.c_str()); return false; } @@ -560,178 +363,136 @@ bool SavedGame::write_chunk( return true; } -bool SavedGame::read( - void* dst_data, - int dst_size) -{ - if (is_failed_) - { +bool SavedGame::read(void *dst_data, int dst_size) { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_failed_ = true; error_message_ = "Not open or created."; return false; } - if (!dst_data) - { + if (!dst_data) { is_failed_ = true; error_message_ = "Null pointer."; return false; } - if (dst_size < 0) - { + if (dst_size < 0) { is_failed_ = true; error_message_ = "Negative size."; return false; } - if (!is_readable_) - { + if (!is_readable_) { is_failed_ = true; error_message_ = "Not readable."; return false; } - if (dst_size == 0) - { + if (dst_size == 0) { return true; } - if ((io_buffer_offset_ + dst_size) > io_buffer_.size()) - { + if ((io_buffer_offset_ + dst_size) > io_buffer_.size()) { is_failed_ = true; error_message_ = "Not enough data."; return false; } - std::uninitialized_copy_n( - &io_buffer_[io_buffer_offset_], - dst_size, - static_cast(dst_data)); + std::uninitialized_copy_n(&io_buffer_[io_buffer_offset_], dst_size, static_cast(dst_data)); io_buffer_offset_ += dst_size; return true; } -bool SavedGame::write( - const void* src_data, - int src_size) -{ - if (is_failed_) - { +bool SavedGame::write(const void *src_data, int src_size) { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_failed_ = true; error_message_ = "Not open or created."; return false; } - if (!src_data) - { + if (!src_data) { is_failed_ = true; error_message_ = "Null pointer."; return false; } - if (src_size < 0) - { + if (src_size < 0) { is_failed_ = true; error_message_ = "Negative size."; return false; } - if (!is_writable_) - { + if (!is_writable_) { is_failed_ = true; error_message_ = "Not writable."; return false; } - if (src_size == 0) - { + if (src_size == 0) { return true; } const std::size_t new_buffer_size = io_buffer_offset_ + src_size; - io_buffer_.resize( - new_buffer_size); + io_buffer_.resize(new_buffer_size); - std::uninitialized_copy_n( - static_cast(src_data), - src_size, - &io_buffer_[io_buffer_offset_]); + std::uninitialized_copy_n(static_cast(src_data), src_size, &io_buffer_[io_buffer_offset_]); io_buffer_offset_ = new_buffer_size; return true; } -bool SavedGame::is_failed() const -{ - return is_failed_; -} +bool SavedGame::is_failed() const { return is_failed_; } -bool SavedGame::skip( - int count) -{ - if (is_failed_) - { +bool SavedGame::skip(int count) { + if (is_failed_) { return false; } - if (file_handle_ == 0) - { + if (file_handle_ == 0) { is_failed_ = true; error_message_ = "Not open or created."; return false; } - if (!is_readable_ && !is_writable_) - { + if (!is_readable_ && !is_writable_) { is_failed_ = true; error_message_ = "Not open or created."; return false; } - if (count < 0) - { + if (count < 0) { is_failed_ = true; error_message_ = "Negative count."; return false; } - if (count == 0) - { + if (count == 0) { return true; } const std::size_t new_offset = io_buffer_offset_ + count; const std::size_t buffer_size = io_buffer_.size(); - if (new_offset > buffer_size) - { - if (is_readable_) - { + if (new_offset > buffer_size) { + if (is_readable_) { is_failed_ = true; error_message_ = "Not enough data."; return false; - } - else if (is_writable_) - { - if (new_offset > buffer_size) - { - io_buffer_.resize( - new_offset); + } else if (is_writable_) { + if (new_offset > buffer_size) { + io_buffer_.resize(new_offset); } } } @@ -741,92 +502,61 @@ bool SavedGame::skip( return true; } -void SavedGame::save_buffer() -{ +void SavedGame::save_buffer() { saved_io_buffer_ = io_buffer_; saved_io_buffer_offset_ = io_buffer_offset_; } -void SavedGame::load_buffer() -{ +void SavedGame::load_buffer() { io_buffer_ = saved_io_buffer_; io_buffer_offset_ = saved_io_buffer_offset_; } -const void* SavedGame::get_buffer_data() const -{ - return io_buffer_.data(); -} +const void *SavedGame::get_buffer_data() const { return io_buffer_.data(); } -int SavedGame::get_buffer_size() const -{ - return static_cast(io_buffer_.size()); -} +int SavedGame::get_buffer_size() const { return static_cast(io_buffer_.size()); } -void SavedGame::rename( - const std::string& old_base_file_name, - const std::string& new_base_file_name) -{ - const std::string old_path = generate_path( - old_base_file_name); +void SavedGame::rename(const std::string &old_base_file_name, const std::string &new_base_file_name) { + const std::string old_path = generate_path(old_base_file_name); - const std::string new_path = generate_path( - new_base_file_name); + const std::string new_path = generate_path(new_base_file_name); - const int rename_result = ::FS_MoveUserGenFile( - old_path.c_str(), - new_path.c_str()); + const int rename_result = ::FS_MoveUserGenFile(old_path.c_str(), new_path.c_str()); - if (rename_result == 0) - { - ::Com_Printf( - S_COLOR_RED "Error during savegame-rename." - " Check \"%s\" for write-protect or disk full!\n", - new_path.c_str()); + if (rename_result == 0) { + ::Com_Printf(S_COLOR_RED "Error during savegame-rename." + " Check \"%s\" for write-protect or disk full!\n", + new_path.c_str()); } } -void SavedGame::remove( - const std::string& base_file_name) -{ - const std::string path = generate_path( - base_file_name); +void SavedGame::remove(const std::string &base_file_name) { + const std::string path = generate_path(base_file_name); - ::FS_DeleteUserGenFile( - path.c_str()); + ::FS_DeleteUserGenFile(path.c_str()); } -SavedGame& SavedGame::get_instance() -{ +SavedGame &SavedGame::get_instance() { static SavedGame result; return result; } -void SavedGame::clear_error() -{ +void SavedGame::clear_error() { is_failed_ = false; error_message_.clear(); } -void SavedGame::throw_error() -{ - if (error_message_.empty()) - { +void SavedGame::throw_error() { + if (error_message_.empty()) { error_message_ = "Generic error."; } error_message_ = "SG: " + error_message_; - ::Com_Error( - ERR_DROP, - "%s", - error_message_.c_str()); + ::Com_Error(ERR_DROP, "%s", error_message_.c_str()); } -void SavedGame::compress( - const Buffer& src_buffer, - Buffer& dst_buffer) -{ +void SavedGame::compress(const Buffer &src_buffer, Buffer &dst_buffer) { const int src_size = static_cast(src_buffer.size()); dst_buffer.resize(2 * src_size); @@ -834,47 +564,31 @@ void SavedGame::compress( int src_count = 0; int dst_index = 0; - while (src_count < src_size) - { + while (src_count < src_size) { int src_index = src_count; uint8_t b = src_buffer[src_index++]; - while (src_index < src_size && - (src_index - src_count) < 127 && - src_buffer[src_index] == b) - { + while (src_index < src_size && (src_index - src_count) < 127 && src_buffer[src_index] == b) { src_index += 1; } - if ((src_index - src_count) == 1) - { - while (src_index < src_size && - (src_index - src_count) < 127 && ( - src_buffer[src_index] != src_buffer[src_index - 1] || ( - src_index > 1 && - src_buffer[src_index] != src_buffer[src_index - 2]))) - { + if ((src_index - src_count) == 1) { + while (src_index < src_size && (src_index - src_count) < 127 && + (src_buffer[src_index] != src_buffer[src_index - 1] || (src_index > 1 && src_buffer[src_index] != src_buffer[src_index - 2]))) { src_index += 1; } - while (src_index < src_size && - src_buffer[src_index] == src_buffer[src_index - 1]) - { + while (src_index < src_size && src_buffer[src_index] == src_buffer[src_index - 1]) { src_index -= 1; } - dst_buffer[dst_index++] = - static_cast(src_count - src_index); + dst_buffer[dst_index++] = static_cast(src_count - src_index); - for (int i = src_count; i < src_index; ++i) - { + for (int i = src_count; i < src_index; ++i) { dst_buffer[dst_index++] = src_buffer[i]; } - } - else - { - dst_buffer[dst_index++] = - static_cast(src_index - src_count); + } else { + dst_buffer[dst_index++] = static_cast(src_index - src_count); dst_buffer[dst_index++] = b; } @@ -882,40 +596,25 @@ void SavedGame::compress( src_count = src_index; } - dst_buffer.resize( - dst_index); + dst_buffer.resize(dst_index); } -void SavedGame::decompress( - const Buffer& src_buffer, - Buffer& dst_buffer) -{ +void SavedGame::decompress(const Buffer &src_buffer, Buffer &dst_buffer) { int src_index = 0; int dst_index = 0; int remain_size = static_cast(dst_buffer.size()); - while (remain_size > 0) - { + while (remain_size > 0) { int8_t count = static_cast(src_buffer[src_index++]); - if (count > 0) - { - std::uninitialized_fill_n( - &dst_buffer[dst_index], - count, - src_buffer[src_index++]); - } - else - { - if (count < 0) - { + if (count > 0) { + std::uninitialized_fill_n(&dst_buffer[dst_index], count, src_buffer[src_index++]); + } else { + if (count < 0) { count = -count; - std::uninitialized_copy_n( - &src_buffer[src_index], - count, - &dst_buffer[dst_index]); + std::uninitialized_copy_n(&src_buffer[src_index], count, &dst_buffer[dst_index]); src_index += count; } @@ -926,23 +625,15 @@ void SavedGame::decompress( } } -std::string SavedGame::generate_path( - const std::string& base_file_name) -{ +std::string SavedGame::generate_path(const std::string &base_file_name) { std::string normalized_file_name = base_file_name; - std::replace( - normalized_file_name.begin(), - normalized_file_name.end(), - '/', - '_'); + std::replace(normalized_file_name.begin(), normalized_file_name.end(), '/', '_'); return "saves/" + normalized_file_name + ".sav"; } -std::string SavedGame::get_chunk_id_string( - uint32_t chunk_id) -{ +std::string SavedGame::get_chunk_id_string(uint32_t chunk_id) { std::string result(4, '\0'); result[0] = static_cast((chunk_id >> 24) & 0xFF); @@ -953,21 +644,13 @@ std::string SavedGame::get_chunk_id_string( return result; } -void SavedGame::reset_buffer() -{ +void SavedGame::reset_buffer() { io_buffer_.clear(); reset_buffer_offset(); } -void SavedGame::reset_buffer_offset() -{ - io_buffer_offset_ = 0; -} - -const uint32_t SavedGame::get_jo_magic_value() -{ - return 0x1234ABCD; -} +void SavedGame::reset_buffer_offset() { io_buffer_offset_ = 0; } +const uint32_t SavedGame::get_jo_magic_value() { return 0x1234ABCD; } -} // ojk +} // namespace ojk diff --git a/code/qcommon/persistence.cpp b/code/qcommon/persistence.cpp index 8a559b09fb..39fd678adc 100644 --- a/code/qcommon/persistence.cpp +++ b/code/qcommon/persistence.cpp @@ -21,8 +21,7 @@ along with this program; if not, see . #include "q_shared.h" #include "qcommon.h" -typedef struct persisentData_t -{ +typedef struct persisentData_t { const void *data; size_t size; @@ -32,12 +31,9 @@ typedef struct persisentData_t #define MAX_PERSISENT_DATA_STORES (16) static persisentData_t persistentData[MAX_PERSISENT_DATA_STORES]; -static persisentData_t *FindEmptyStore ( persisentData_t *stores, size_t count ) -{ - for ( size_t i = 0; i < count; i++ ) - { - if ( stores[i].data == NULL ) - { +static persisentData_t *FindEmptyStore(persisentData_t *stores, size_t count) { + for (size_t i = 0; i < count; i++) { + if (stores[i].data == NULL) { return &stores[i]; } } @@ -45,12 +41,9 @@ static persisentData_t *FindEmptyStore ( persisentData_t *stores, size_t count ) return NULL; } -static persisentData_t *FindStoreWithName ( persisentData_t *stores, size_t count, const char *name ) -{ - for ( size_t i = 0; i < count; i++ ) - { - if ( Q_stricmp (stores[i].name, name) == 0 ) - { +static persisentData_t *FindStoreWithName(persisentData_t *stores, size_t count, const char *name) { + for (size_t i = 0; i < count; i++) { + if (Q_stricmp(stores[i].name, name) == 0) { return &stores[i]; } } @@ -58,33 +51,28 @@ static persisentData_t *FindStoreWithName ( persisentData_t *stores, size_t coun return NULL; } -bool PD_Store ( const char *name, const void *data, size_t size ) -{ - persisentData_t *store = FindEmptyStore (persistentData, MAX_PERSISENT_DATA_STORES); - if ( store == NULL ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: No persistent data store found.\n"); +bool PD_Store(const char *name, const void *data, size_t size) { + persisentData_t *store = FindEmptyStore(persistentData, MAX_PERSISENT_DATA_STORES); + if (store == NULL) { + Com_Printf(S_COLOR_YELLOW "WARNING: No persistent data store found.\n"); return false; } store->data = data; store->size = size; - Q_strncpyz (store->name, name, sizeof (store->name)); + Q_strncpyz(store->name, name, sizeof(store->name)); return true; } -const void *PD_Load ( const char *name, size_t *size ) -{ - persisentData_t *store = FindStoreWithName (persistentData, MAX_PERSISENT_DATA_STORES, name); - if ( store == NULL ) - { +const void *PD_Load(const char *name, size_t *size) { + persisentData_t *store = FindStoreWithName(persistentData, MAX_PERSISENT_DATA_STORES, name); + if (store == NULL) { return NULL; } const void *data = store->data; - if ( size != NULL ) - { + if (size != NULL) { *size = store->size; } diff --git a/code/qcommon/q_shared.cpp b/code/qcommon/q_shared.cpp index 6eb1a67097..f031bda9b8 100644 --- a/code/qcommon/q_shared.cpp +++ b/code/qcommon/q_shared.cpp @@ -31,15 +31,13 @@ along with this program; if not, see . COM_SkipPath ============ */ -char *COM_SkipPath (char *pathname) -{ - char *last; +char *COM_SkipPath(char *pathname) { + char *last; last = pathname; - while (*pathname) - { - if (*pathname=='/') - last = pathname+1; + while (*pathname) { + if (*pathname == '/') + last = pathname + 1; pathname++; } return last; @@ -50,8 +48,7 @@ char *COM_SkipPath (char *pathname) COM_GetExtension ============ */ -const char *COM_GetExtension( const char *name ) -{ +const char *COM_GetExtension(const char *name) { const char *dot = strrchr(name, '.'), *slash; if (dot && (!(slash = strrchr(name, '/')) || slash < dot)) return dot + 1; @@ -64,14 +61,13 @@ const char *COM_GetExtension( const char *name ) COM_StripExtension ============ */ -void COM_StripExtension( const char *in, char *out, int destsize ) -{ +void COM_StripExtension(const char *in, char *out, int destsize) { const char *dot = strrchr(in, '.'), *slash; if (dot && (!(slash = strrchr(in, '/')) || slash < dot)) - destsize = (destsize < dot-in+1 ? destsize : dot-in+1); + destsize = (destsize < dot - in + 1 ? destsize : dot - in + 1); - if ( in == out && destsize > 1 ) - out[destsize-1] = '\0'; + if (in == out && destsize > 1) + out[destsize - 1] = '\0'; else Q_strncpyz(out, in, destsize); } @@ -83,18 +79,16 @@ COM_CompareExtension string compare the end of the strings and return qtrue if strings match ============ */ -qboolean COM_CompareExtension(const char *in, const char *ext) -{ +qboolean COM_CompareExtension(const char *in, const char *ext) { int inlen, extlen; inlen = strlen(in); extlen = strlen(ext); - if(extlen <= inlen) - { + if (extlen <= inlen) { in += inlen - extlen; - if(!Q_stricmp(in, ext)) + if (!Q_stricmp(in, ext)) return qtrue; } @@ -106,8 +100,7 @@ qboolean COM_CompareExtension(const char *in, const char *ext) COM_DefaultExtension ================== */ -void COM_DefaultExtension( char *path, int maxSize, const char *extension ) -{ +void COM_DefaultExtension(char *path, int maxSize, const char *extension) { const char *dot = strrchr(path, '.'), *slash; if (dot && (!(slash = strrchr(path, '/')) || slash < dot)) return; @@ -123,25 +116,22 @@ PARSING ============================================================================ */ -static char com_token[MAX_TOKEN_CHARS]; -//JLFCALLOUT MPNOTUSED +static char com_token[MAX_TOKEN_CHARS]; +// JLFCALLOUT MPNOTUSED int parseDataCount = -1; const int MAX_PARSE_DATA = 5; parseData_t parseData[MAX_PARSE_DATA]; -void COM_ParseInit( void ) -{ +void COM_ParseInit(void) { memset(parseData, 0, sizeof(parseData)); parseDataCount = -1; } -void COM_BeginParseSession( void ) -{ +void COM_BeginParseSession(void) { parseDataCount++; #ifdef _DEBUG - if ( parseDataCount >= MAX_PARSE_DATA ) - { - Com_Error (ERR_FATAL, "COM_BeginParseSession: cannot nest more than %d parsing sessions.\n", MAX_PARSE_DATA); + if (parseDataCount >= MAX_PARSE_DATA) { + Com_Error(ERR_FATAL, "COM_BeginParseSession: cannot nest more than %d parsing sessions.\n", MAX_PARSE_DATA); } #endif @@ -149,29 +139,24 @@ void COM_BeginParseSession( void ) parseData[parseDataCount].com_tokenline = 0; } -void COM_EndParseSession( void ) -{ +void COM_EndParseSession(void) { parseDataCount--; #ifdef _DEBUG - assert (parseDataCount >= -1 && "COM_EndParseSession: called without a starting COM_BeginParseSession.\n"); + assert(parseDataCount >= -1 && "COM_EndParseSession: called without a starting COM_BeginParseSession.\n"); #endif } -int COM_GetCurrentParseLine( int index ) -{ - if(parseDataCount < 0) +int COM_GetCurrentParseLine(int index) { + if (parseDataCount < 0) Com_Error(ERR_FATAL, "COM_GetCurrentParseLine: parseDataCount < 0 (be sure to call COM_BeginParseSession!)"); - if ( parseData[parseDataCount].com_tokenline ) + if (parseData[parseDataCount].com_tokenline) return parseData[parseDataCount].com_tokenline; return parseData[parseDataCount].com_lines; } -char *COM_Parse( const char **data_p ) -{ - return COM_ParseExt( data_p, qtrue ); -} +char *COM_Parse(const char **data_p) { return COM_ParseExt(data_p, qtrue); } /* ============== @@ -185,21 +170,17 @@ string will be returned if the next token is a newline. ============== */ -const char *SkipWhitespace( const char *data, qboolean *hasNewLines ) -{ +const char *SkipWhitespace(const char *data, qboolean *hasNewLines) { int c; - if(parseDataCount < 0) + if (parseDataCount < 0) Com_Error(ERR_FATAL, "SkipWhitespace: parseDataCount < 0"); - while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') - { - if( !c ) - { + while ((c = *(const unsigned char * /*eurofix*/)data) <= ' ') { + if (!c) { return NULL; } - if( c == '\n' ) - { + if (c == '\n') { parseData[parseDataCount].com_lines++; *hasNewLines = qtrue; } @@ -209,7 +190,7 @@ const char *SkipWhitespace( const char *data, qboolean *hasNewLines ) return data; } -int COM_Compress( char *data_p ) { +int COM_Compress(char *data_p) { char *in, *out; int c; qboolean newline = qfalse, whitespace = qfalse; @@ -218,22 +199,22 @@ int COM_Compress( char *data_p ) { if (in) { while ((c = *in) != 0) { // skip double slash comments - if ( c == '/' && in[1] == '/' ) { + if (c == '/' && in[1] == '/') { while (*in && *in != '\n') { in++; } - // skip /* */ comments - } else if ( c == '/' && in[1] == '*' ) { - while ( *in && ( *in != '*' || in[1] != '/' ) ) + // skip /* */ comments + } else if (c == '/' && in[1] == '*') { + while (*in && (*in != '*' || in[1] != '/')) in++; - if ( *in ) + if (*in) in += 2; // record when we hit a newline - } else if ( c == '\n' || c == '\r' ) { + } else if (c == '\n' || c == '\r') { newline = qtrue; in++; // record when we hit whitespace - } else if ( c == ' ' || c == '\t') { + } else if (c == ' ' || c == '\t') { whitespace = qtrue; in++; // an actual token @@ -243,7 +224,8 @@ int COM_Compress( char *data_p ) { *out++ = '\n'; newline = qfalse; whitespace = qfalse; - } if (whitespace) { + } + if (whitespace) { *out++ = ' '; whitespace = qfalse; } @@ -278,8 +260,7 @@ int COM_Compress( char *data_p ) { return out - data_p; } -char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) -{ +char *COM_ParseExt(const char **data_p, qboolean allowLineBreaks) { int c = 0, len; qboolean hasNewLines = qfalse; const char *data; @@ -287,30 +268,26 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) data = *data_p; len = 0; com_token[0] = 0; - if(parseDataCount >= 0) + if (parseDataCount >= 0) parseData[parseDataCount].com_tokenline = 0; // make sure incoming data is valid - if ( !data ) - { + if (!data) { *data_p = NULL; return com_token; } - if(parseDataCount < 0) + if (parseDataCount < 0) Com_Error(ERR_FATAL, "COM_ParseExt: parseDataCount < 0 (be sure to call COM_BeginParseSession!)"); - while ( 1 ) - { + while (1) { // skip whitespace - data = SkipWhitespace( data, &hasNewLines ); - if ( !data ) - { + data = SkipWhitespace(data, &hasNewLines); + if (!data) { *data_p = NULL; return com_token; } - if ( hasNewLines && !allowLineBreaks ) - { + if (hasNewLines && !allowLineBreaks) { *data_p = data; return com_token; } @@ -318,32 +295,25 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { data += 2; while (*data && *data != '\n') { data++; } } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { + else if (c == '/' && data[1] == '*') { data += 2; - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { - if ( *data == '\n' ) - { + while (*data && (*data != '*' || data[1] != '/')) { + if (*data == '\n') { parseData[parseDataCount].com_lines++; } data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } @@ -352,24 +322,19 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) parseData[parseDataCount].com_tokenline = parseData[parseDataCount].com_lines; // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if ( c == '\n' ) - { + if (c == '\n') { parseData[parseDataCount].com_lines++; } - if (len < MAX_TOKEN_CHARS - 1) - { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } @@ -377,20 +342,18 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS - 1) - { + do { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32); + } while (c > 32); com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -399,11 +362,9 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) COM_ParseString =============== */ -qboolean COM_ParseString( const char **data, const char **s ) -{ - *s = COM_ParseExt( data, qfalse ); - if ( s[0] == 0 ) - { +qboolean COM_ParseString(const char **data, const char **s) { + *s = COM_ParseExt(data, qfalse); + if (s[0] == 0) { Com_Printf("unexpected EOF in COM_ParseString\n"); return qtrue; } @@ -415,18 +376,16 @@ qboolean COM_ParseString( const char **data, const char **s ) COM_ParseInt =============== */ -qboolean COM_ParseInt( const char **data, int *i ) -{ - const char *token; - - token = COM_ParseExt( data, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf( "unexpected EOF in COM_ParseInt\n" ); +qboolean COM_ParseInt(const char **data, int *i) { + const char *token; + + token = COM_ParseExt(data, qfalse); + if (token[0] == 0) { + Com_Printf("unexpected EOF in COM_ParseInt\n"); return qtrue; } - *i = atoi( token ); + *i = atoi(token); return qfalse; } @@ -435,18 +394,16 @@ qboolean COM_ParseInt( const char **data, int *i ) COM_ParseFloat =============== */ -qboolean COM_ParseFloat( const char **data, float *f ) -{ - const char *token; - - token = COM_ParseExt( data, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf( "unexpected EOF in COM_ParseFloat\n" ); +qboolean COM_ParseFloat(const char **data, float *f) { + const char *token; + + token = COM_ParseExt(data, qfalse); + if (token[0] == 0) { + Com_Printf("unexpected EOF in COM_ParseFloat\n"); return qtrue; } - *f = atof( token ); + *f = atof(token); return qfalse; } @@ -455,15 +412,12 @@ qboolean COM_ParseFloat( const char **data, float *f ) COM_ParseVec4 =============== */ -qboolean COM_ParseVec4( const char **buffer, vec4_t *c) -{ +qboolean COM_ParseVec4(const char **buffer, vec4_t *c) { int i; float f; - for (i = 0; i < 4; i++) - { - if (COM_ParseFloat(buffer, &f)) - { + for (i = 0; i < 4; i++) { + if (COM_ParseFloat(buffer, &f)) { return qtrue; } (*c)[i] = f; @@ -476,17 +430,15 @@ qboolean COM_ParseVec4( const char **buffer, vec4_t *c) COM_MatchToken ================== */ -void COM_MatchToken( const char **buf_p, const char *match ) { - const char *token; +void COM_MatchToken(const char **buf_p, const char *match) { + const char *token; - token = COM_Parse( buf_p ); - if ( strcmp( token, match ) ) - { - Com_Error( ERR_DROP, "MatchToken: %s != %s", token, match ); + token = COM_Parse(buf_p); + if (strcmp(token, match)) { + Com_Error(ERR_DROP, "MatchToken: %s != %s", token, match); } } - /* ================= SkipBracedSection @@ -496,21 +448,20 @@ Skips until a matching close brace is found. Internal brace depths are properly skipped. ================= */ -void SkipBracedSection ( const char **program) { - const char *token; - int depth=0; +void SkipBracedSection(const char **program) { + const char *token; + int depth = 0; - if (com_token[0]=='{') { //for tr_shader which just ate the brace + if (com_token[0] == '{') { // for tr_shader which just ate the brace depth = 1; } do { - token = COM_ParseExt( program, qtrue ); - if( token[1] == 0 ) { - if( token[0] == '{' ) { + token = COM_ParseExt(program, qtrue); + if (token[1] == 0) { + if (token[0] == '{') { depth++; - } - else if( token[0] == '}' ) { + } else if (token[0] == '}') { depth--; } } @@ -523,20 +474,20 @@ void SkipBracedSection ( const char **program) { SkipRestOfLine ================= */ -void SkipRestOfLine ( const char **data ) { - const char *p; - int c; +void SkipRestOfLine(const char **data) { + const char *p; + int c; - if(parseDataCount < 0) + if (parseDataCount < 0) Com_Error(ERR_FATAL, "SkipRestOfLine: parseDataCount < 0"); p = *data; - if ( !*p ) + if (!*p) return; - while ( (c = *p++) != 0 ) { - if ( c == '\n' ) { + while ((c = *p++) != 0) { + if (c == '\n') { parseData[parseDataCount].com_lines++; break; } @@ -545,43 +496,42 @@ void SkipRestOfLine ( const char **data ) { *data = p; } +void Parse1DMatrix(const char **buf_p, int x, float *m) { + const char *token; + int i; -void Parse1DMatrix ( const char **buf_p, int x, float *m) { - const char *token; - int i; - - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < x ; i++) { + for (i = 0; i < x; i++) { token = COM_Parse(buf_p); m[i] = atof(token); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } -void Parse2DMatrix ( const char **buf_p, int y, int x, float *m) { - int i; +void Parse2DMatrix(const char **buf_p, int y, int x, float *m) { + int i; - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < y ; i++) { - Parse1DMatrix (buf_p, x, m + i * x); + for (i = 0; i < y; i++) { + Parse1DMatrix(buf_p, x, m + i * x); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } -void Parse3DMatrix ( const char **buf_p, int z, int y, int x, float *m) { - int i; +void Parse3DMatrix(const char **buf_p, int z, int y, int x, float *m) { + int i; - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < z ; i++) { - Parse2DMatrix (buf_p, y, x, m + i * x*y); + for (i = 0; i < z; i++) { + Parse2DMatrix(buf_p, y, x, m + i * x * y); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } /* @@ -589,27 +539,24 @@ void Parse3DMatrix ( const char **buf_p, int z, int y, int x, float *m) { Com_HexStrToInt =================== */ -int Com_HexStrToInt( const char *str ) -{ - if ( !str || !str[ 0 ] ) +int Com_HexStrToInt(const char *str) { + if (!str || !str[0]) return -1; // check for hex code - if( str[ 0 ] == '0' && str[ 1 ] == 'x' ) - { + if (str[0] == '0' && str[1] == 'x') { size_t i, n = 0; - for( i = 2; i < strlen( str ); i++ ) - { + for (i = 2; i < strlen(str); i++) { char digit; n *= 16; - digit = tolower( str[ i ] ); + digit = tolower(str[i]); - if( digit >= '0' && digit <= '9' ) + if (digit >= '0' && digit <= '9') digit -= '0'; - else if( digit >= 'a' && digit <= 'f' ) + else if (digit >= 'a' && digit <= 'f') digit = digit - 'a' + 10; else return -1; @@ -623,7 +570,6 @@ int Com_HexStrToInt( const char *str ) return -1; } - /* ============================================================================ @@ -632,15 +578,15 @@ int Com_HexStrToInt( const char *str ) ============================================================================ */ -int QDECL Com_sprintf( char *dest, int size, const char *fmt, ...) { - int len; - va_list argptr; +int QDECL Com_sprintf(char *dest, int size, const char *fmt, ...) { + int len; + va_list argptr; - va_start (argptr,fmt); + va_start(argptr, fmt); len = Q_vsnprintf(dest, size, fmt, argptr); - va_end (argptr); + va_end(argptr); - if(len >= size) + if (len >= size) Com_Printf("Com_sprintf: Output length %d too short, require %d bytes.\n", size, len + 1); return len; @@ -655,20 +601,19 @@ varargs versions of all text functions. FIXME: make this buffer size safe someday ============ */ -#define MAX_VA_STRING 32000 +#define MAX_VA_STRING 32000 #define MAX_VA_BUFFERS 4 -char * QDECL va( const char *format, ... ) -{ - va_list argptr; - static char string[MAX_VA_BUFFERS][MAX_VA_STRING]; // in case va is called by nested functions - static int index = 0; - char *buf; +char *QDECL va(const char *format, ...) { + va_list argptr; + static char string[MAX_VA_BUFFERS][MAX_VA_STRING]; // in case va is called by nested functions + static int index = 0; + char *buf; - va_start( argptr, format ); + va_start(argptr, format); buf = (char *)&string[index++ & 3]; - Q_vsnprintf( buf, sizeof(*string), format, argptr ); - va_end( argptr ); + Q_vsnprintf(buf, sizeof(*string), format, argptr); + va_end(argptr); return buf; } @@ -679,15 +624,15 @@ Com_TruncateLongString Assumes buffer is atleast TRUNCATE_LENGTH big ============ */ -void Com_TruncateLongString( char *buffer, const char *s ) { - int length = strlen( s ); +void Com_TruncateLongString(char *buffer, const char *s) { + int length = strlen(s); - if ( length <= TRUNCATE_LENGTH ) - Q_strncpyz( buffer, s, TRUNCATE_LENGTH ); + if (length <= TRUNCATE_LENGTH) + Q_strncpyz(buffer, s, TRUNCATE_LENGTH); else { - Q_strncpyz( buffer, s, (TRUNCATE_LENGTH/2) - 3 ); - Q_strcat( buffer, TRUNCATE_LENGTH, " ... " ); - Q_strcat( buffer, TRUNCATE_LENGTH, s + length - (TRUNCATE_LENGTH/2) + 3 ); + Q_strncpyz(buffer, s, (TRUNCATE_LENGTH / 2) - 3); + Q_strcat(buffer, TRUNCATE_LENGTH, " ... "); + Q_strcat(buffer, TRUNCATE_LENGTH, s + length - (TRUNCATE_LENGTH / 2) + 3); } } @@ -708,29 +653,27 @@ key and returns the associated value, or an empty string. FIXME: overflow check? =============== */ -const char *Info_ValueForKey( const char *s, const char *key ) { - char pkey[MAX_INFO_KEY]; - static char value[2][MAX_INFO_VALUE]; // use two buffers so compares - // work without stomping on each other - static int valueindex = 0; - char *o; - - if ( !s || !key ) { +const char *Info_ValueForKey(const char *s, const char *key) { + char pkey[MAX_INFO_KEY]; + static char value[2][MAX_INFO_VALUE]; // use two buffers so compares + // work without stomping on each other + static int valueindex = 0; + char *o; + + if (!s || !key) { return ""; } - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" ); + if (strlen(s) >= MAX_INFO_STRING) { + Com_Error(ERR_DROP, "Info_ValueForKey: oversize infostring"); } valueindex ^= 1; if (*s == '\\') s++; - while (1) - { + while (1) { o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return ""; *o++ = *s++; @@ -740,13 +683,12 @@ const char *Info_ValueForKey( const char *s, const char *key ) { o = value[valueindex]; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { *o++ = *s++; } *o = 0; - if (!Q_stricmp (key, pkey) ) + if (!Q_stricmp(key, pkey)) return value[valueindex]; if (!*s) @@ -757,7 +699,6 @@ const char *Info_ValueForKey( const char *s, const char *key ) { return ""; } - /* =================== Info_NextPair @@ -765,21 +706,21 @@ Info_NextPair Used to itterate through all the key/value pairs in an info string =================== */ -void Info_NextPair( const char **head, char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] ) { - char *o; - const char *s; +void Info_NextPair(const char **head, char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE]) { + char *o; + const char *s; s = *head; - if ( *s == '\\' ) { + if (*s == '\\') { s++; } key[0] = 0; value[0] = 0; o = key; - while ( *s != '\\' ) { - if ( !*s ) { + while (*s != '\\') { + if (!*s) { *o = 0; *head = s; return; @@ -790,7 +731,7 @@ void Info_NextPair( const char **head, char key[MAX_INFO_KEY], char value[MAX_IN s++; o = value; - while ( *s != '\\' && *s ) { + while (*s != '\\' && *s) { *o++ = *s++; } *o = 0; @@ -798,34 +739,31 @@ void Info_NextPair( const char **head, char key[MAX_INFO_KEY], char value[MAX_IN *head = s; } - /* =================== Info_RemoveKey =================== */ -void Info_RemoveKey( char *s, const char *key ) { - char *start; - char pkey[MAX_INFO_KEY]; - char value[MAX_INFO_VALUE]; - char *o; - - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" ); +void Info_RemoveKey(char *s, const char *key) { + char *start; + char pkey[MAX_INFO_KEY]; + char value[MAX_INFO_VALUE]; + char *o; + + if (strlen(s) >= MAX_INFO_STRING) { + Com_Error(ERR_DROP, "Info_RemoveKey: oversize infostring"); } - if (strchr (key, '\\')) { + if (strchr(key, '\\')) { return; } - while (1) - { + while (1) { start = s; if (*s == '\\') s++; o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return; *o++ = *s++; @@ -834,18 +772,16 @@ void Info_RemoveKey( char *s, const char *key ) { s++; o = value; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; - //OJKNOTE: static analysis pointed out pkey may not be null-terminated - if (!strcmp (key, pkey) ) - { - memmove(start, s, strlen(s) + 1); // remove this part + // OJKNOTE: static analysis pointed out pkey may not be null-terminated + if (!strcmp(key, pkey)) { + memmove(start, s, strlen(s) + 1); // remove this part return; } @@ -854,7 +790,6 @@ void Info_RemoveKey( char *s, const char *key ) { } } - /* ================== Info_Validate @@ -863,11 +798,11 @@ Some characters are illegal in info strings because they can mess up the server's parsing ================== */ -qboolean Info_Validate( const char *s ) { - if ( strchr( s, '\"' ) ) { +qboolean Info_Validate(const char *s) { + if (strchr(s, '\"')) { return qfalse; } - if ( strchr( s, ';' ) ) { + if (strchr(s, ';')) { return qfalse; } return qtrue; @@ -880,37 +815,34 @@ Info_SetValueForKey Changes or adds a key/value pair ================== */ -void Info_SetValueForKey( char *s, const char *key, const char *value ) { - char newi[MAX_INFO_STRING]; - const char* blacklist = "\\;\""; +void Info_SetValueForKey(char *s, const char *key, const char *value) { + char newi[MAX_INFO_STRING]; + const char *blacklist = "\\;\""; - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" ); + if (strlen(s) >= MAX_INFO_STRING) { + Com_Error(ERR_DROP, "Info_SetValueForKey: oversize infostring"); } - for(; *blacklist; ++blacklist) - { - if (strchr (key, *blacklist) || strchr (value, *blacklist)) - { - Com_Printf (S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); + for (; *blacklist; ++blacklist) { + if (strchr(key, *blacklist) || strchr(value, *blacklist)) { + Com_Printf(S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); return; } } - Info_RemoveKey (s, key); + Info_RemoveKey(s, key); if (!value || !strlen(value)) return; - Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value); + Com_sprintf(newi, sizeof(newi), "\\%s\\%s", key, value); - if (strlen(newi) + strlen(s) >= MAX_INFO_STRING) - { - Com_Printf ("Info string length exceeded\n"); + if (strlen(newi) + strlen(s) >= MAX_INFO_STRING) { + Com_Printf("Info string length exceeded\n"); return; } - strcat (newi, s); - strcpy (s, newi); + strcat(newi, s); + strcpy(s, newi); } /* @@ -918,11 +850,11 @@ void Info_SetValueForKey( char *s, const char *key, const char *value ) { Com_CharIsOneOfCharset ================== */ -static qboolean Com_CharIsOneOfCharset( char c, char *set ) { +static qboolean Com_CharIsOneOfCharset(char c, char *set) { size_t i; - for ( i=0; i. // // some STL stuff... #ifdef _MSC_VER -#pragma warning ( disable : 4786 ) // disable the usual stupid and pointless STL warning +#pragma warning(disable : 4786) // disable the usual stupid and pointless STL warning #endif #include #include #include -typedef std::vector vStrings_t; -typedef std::vector vInts_t; +typedef std::vector vStrings_t; +typedef std::vector vInts_t; // /////////////////////////////////////////////// -cvar_t *se_language = NULL; -cvar_t *se_debug = NULL; -cvar_t *sp_leet = NULL; // kept as 'sp_' for JK2 compat. +cvar_t *se_language = NULL; +cvar_t *se_debug = NULL; +cvar_t *sp_leet = NULL; // kept as 'sp_' for JK2 compat. -#define __DEBUGOUT(_string) OutputDebugString(_string) -#define __ASSERT(_blah) assert(_blah) +#define __DEBUGOUT(_string) OutputDebugString(_string) +#define __ASSERT(_blah) assert(_blah) -typedef struct SE_Entry_s -{ - std::string m_strString; - std::string m_strDebug; // english and/or "#same", used for debugging only. Also prefixed by "SE:" to show which strings go through StringEd (ie aren't hardwired) - int m_iFlags; +typedef struct SE_Entry_s { + std::string m_strString; + std::string + m_strDebug; // english and/or "#same", used for debugging only. Also prefixed by "SE:" to show which strings go through StringEd (ie aren't hardwired) + int m_iFlags; - SE_Entry_s() - { - m_iFlags = 0; - } + SE_Entry_s() { m_iFlags = 0; } } SE_Entry_t; +typedef std::map mapStringEntries_t; -typedef std::map mapStringEntries_t; - -class CStringEdPackage -{ -private: +class CStringEdPackage { + private: + SE_BOOL m_bEndMarkerFound_ParseOnly; + std::string m_strCurrentEntryRef_ParseOnly; + std::string m_strCurrentEntryEnglish_ParseOnly; + std::string m_strCurrentFileRef_ParseOnly; + std::string m_strLoadingLanguage_ParseOnly; // eg "german" + SE_BOOL m_bLoadingEnglish_ParseOnly; - SE_BOOL m_bEndMarkerFound_ParseOnly; - std::string m_strCurrentEntryRef_ParseOnly; - std::string m_strCurrentEntryEnglish_ParseOnly; - std::string m_strCurrentFileRef_ParseOnly; - std::string m_strLoadingLanguage_ParseOnly; // eg "german" - SE_BOOL m_bLoadingEnglish_ParseOnly; + public: + CStringEdPackage() { Clear(SE_FALSE); } -public: - - CStringEdPackage() - { - Clear( SE_FALSE ); - } + ~CStringEdPackage() { Clear(SE_FALSE); } - ~CStringEdPackage() - { - Clear( SE_FALSE ); - } - - mapStringEntries_t m_StringEntries; // needs to be in public space now - SE_BOOL m_bLoadDebug; // "" + mapStringEntries_t m_StringEntries; // needs to be in public space now + SE_BOOL m_bLoadDebug; // "" // // flag stuff... // - std::vector m_vstrFlagNames; - std::map m_mapFlagMasks; - - void Clear( SE_BOOL bChangingLanguages ); - void SetupNewFileParse( const char *psFileName, SE_BOOL bLoadDebug ); - SE_BOOL ReadLine( const char *&psParsePos, char *psDest ); - const char *ParseLine( const char *psLine ); - int GetFlagMask( const char *psFlagName ); - const char *ExtractLanguageFromPath( const char *psFileName ); - SE_BOOL EndMarkerFoundDuringParse( void ) - { - return m_bEndMarkerFound_ParseOnly; - } - -private: - - void AddEntry( const char *psLocalReference ); - int GetNumStrings(void); - void SetString( const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug ); - SE_BOOL SetReference( int iIndex, const char *psNewString ); - void AddFlagReference( const char *psLocalReference, const char *psFlagName ); + std::vector m_vstrFlagNames; + std::map m_mapFlagMasks; + + void Clear(SE_BOOL bChangingLanguages); + void SetupNewFileParse(const char *psFileName, SE_BOOL bLoadDebug); + SE_BOOL ReadLine(const char *&psParsePos, char *psDest); + const char *ParseLine(const char *psLine); + int GetFlagMask(const char *psFlagName); + const char *ExtractLanguageFromPath(const char *psFileName); + SE_BOOL EndMarkerFoundDuringParse(void) { return m_bEndMarkerFound_ParseOnly; } + + private: + void AddEntry(const char *psLocalReference); + int GetNumStrings(void); + void SetString(const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug); + SE_BOOL SetReference(int iIndex, const char *psNewString); + void AddFlagReference(const char *psLocalReference, const char *psFlagName); const char *GetCurrentFileName(void); - const char *GetCurrentReference_ParseOnly( void ); - SE_BOOL CheckLineForKeyword( const char *psKeyword, const char *&psLine); - const char *InsideQuotes( const char *psLine ); - const char *ConvertCRLiterals_Read( const char *psString ); - void REMKill( char *psBuffer ); - char *Filename_PathOnly( const char *psFilename ); - char *Filename_WithoutPath(const char *psFilename); - char *Filename_WithoutExt(const char *psFilename); + const char *GetCurrentReference_ParseOnly(void); + SE_BOOL CheckLineForKeyword(const char *psKeyword, const char *&psLine); + const char *InsideQuotes(const char *psLine); + const char *ConvertCRLiterals_Read(const char *psString); + void REMKill(char *psBuffer); + char *Filename_PathOnly(const char *psFilename); + char *Filename_WithoutPath(const char *psFilename); + char *Filename_WithoutExt(const char *psFilename); }; CStringEdPackage TheStringPackage; - -void CStringEdPackage::Clear( SE_BOOL bChangingLanguages ) -{ +void CStringEdPackage::Clear(SE_BOOL bChangingLanguages) { m_StringEntries.clear(); - if ( !bChangingLanguages ) - { + if (!bChangingLanguages) { // if we're changing languages, then I'm going to leave these alone. This is to do with any (potentially) cached // flag bitmasks on the game side. It shouldn't matter since all files are written out at once using the build // command in StringEd. But if ever someone changed a file by hand, or added one, or whatever, and it had a @@ -168,53 +148,45 @@ void CStringEdPackage::Clear( SE_BOOL bChangingLanguages ) // } - - // loses anything after the path (if any), (eg) "dir/name.bmp" becomes "dir" // (copes with either slash-scheme for names) // // (normally I'd call another function for this, but this is supposed to be engine-independant, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_PathOnly(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_PathOnly(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p1= strrchr(sString,'\\'); - char *p2= strrchr(sString,'/'); - char *p = (p1>p2)?p1:p2; + char *p1 = strrchr(sString, '\\'); + char *p2 = strrchr(sString, '/'); + char *p = (p1 > p2) ? p1 : p2; if (p) - *p=0; + *p = 0; return sString; } - // returns (eg) "dir/name" for "dir/name.bmp" // (copes with either slash-scheme for names) // // (normally I'd call another function for this, but this is supposed to be engine-independant, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p = strrchr(sString,'.'); - char *p2= strrchr(sString,'\\'); - char *p3= strrchr(sString,'/'); + char *p = strrchr(sString, '.'); + char *p2 = strrchr(sString, '\\'); + char *p3 = strrchr(sString, '/'); // special check, make sure the first suffix we found from the end wasn't just a directory suffix (eg on a path'd filename with no extension anyway) // - if (p && - (p2==0 || (p2 && p>p2)) && - (p3==0 || (p3 && p>p3)) - ) - *p=0; + if (p && (p2 == 0 || (p2 && p > p2)) && (p3 == 0 || (p3 && p > p3))) + *p = 0; return sString; } @@ -225,59 +197,47 @@ char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) // (normally I'd call another function for this, but this is supposed to be engine-independant, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_WithoutPath(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_WithoutPath(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; const char *psCopyPos = psFilename; - while (*psFilename) - { + while (*psFilename) { if (*psFilename == '/' || *psFilename == '\\') - psCopyPos = psFilename+1; + psCopyPos = psFilename + 1; psFilename++; } - strcpy(sString,psCopyPos); + strcpy(sString, psCopyPos); return sString; } +const char *CStringEdPackage::ExtractLanguageFromPath(const char *psFileName) { return Filename_WithoutPath(Filename_PathOnly(psFileName)); } -const char *CStringEdPackage::ExtractLanguageFromPath( const char *psFileName ) -{ - return Filename_WithoutPath( Filename_PathOnly( psFileName ) ); -} - +void CStringEdPackage::SetupNewFileParse(const char *psFileName, SE_BOOL bLoadDebug) { + char sString[iSE_MAX_FILENAME_LENGTH]; -void CStringEdPackage::SetupNewFileParse( const char *psFileName, SE_BOOL bLoadDebug ) -{ - char sString[ iSE_MAX_FILENAME_LENGTH ]; - - strcpy(sString, Filename_WithoutPath( Filename_WithoutExt( psFileName ) )); + strcpy(sString, Filename_WithoutPath(Filename_WithoutExt(psFileName))); Q_strupr(sString); - m_strCurrentFileRef_ParseOnly = sString; // eg "OBJECTIVES" - m_strLoadingLanguage_ParseOnly = ExtractLanguageFromPath( psFileName ); - m_bLoadingEnglish_ParseOnly = (!Q_stricmp( m_strLoadingLanguage_ParseOnly.c_str(), "english" )) ? SE_TRUE : SE_FALSE; + m_strCurrentFileRef_ParseOnly = sString; // eg "OBJECTIVES" + m_strLoadingLanguage_ParseOnly = ExtractLanguageFromPath(psFileName); + m_bLoadingEnglish_ParseOnly = (!Q_stricmp(m_strLoadingLanguage_ParseOnly.c_str(), "english")) ? SE_TRUE : SE_FALSE; m_bLoadDebug = bLoadDebug; } - // returns SE_TRUE if supplied keyword found at line start (and advances supplied ptr past any whitespace to next arg (or line end if none), // // else returns SE_FALSE... // -SE_BOOL CStringEdPackage::CheckLineForKeyword( const char *psKeyword, const char *&psLine) -{ - if (!Q_stricmpn(psKeyword, psLine, strlen(psKeyword)) ) - { +SE_BOOL CStringEdPackage::CheckLineForKeyword(const char *psKeyword, const char *&psLine) { + if (!Q_stricmpn(psKeyword, psLine, strlen(psKeyword))) { psLine += strlen(psKeyword); // skip whitespace to arrive at next item... // - while ( *psLine == '\t' || *psLine == ' ' ) - { + while (*psLine == '\t' || *psLine == ' ') { psLine++; } return SE_TRUE; @@ -289,68 +249,57 @@ SE_BOOL CStringEdPackage::CheckLineForKeyword( const char *psKeyword, const char // change "\n" to '\n' (i.e. 2-byte char-string to 1-byte ctrl-code)... // (or "\r\n" in editor) // -const char *CStringEdPackage::ConvertCRLiterals_Read( const char *psString ) -{ +const char *CStringEdPackage::ConvertCRLiterals_Read(const char *psString) { static std::string str; str = psString; int iLoc; - while ( (iLoc = str.find("\\n")) != -1 ) - { - str[iLoc ] = '\n'; - str.erase( iLoc+1,1 ); + while ((iLoc = str.find("\\n")) != -1) { + str[iLoc] = '\n'; + str.erase(iLoc + 1, 1); } return str.c_str(); } - // kill off any "//" onwards part in the line, but NOT if it's inside a quoted string... // -void CStringEdPackage::REMKill( char *psBuffer ) -{ +void CStringEdPackage::REMKill(char *psBuffer) { char *psScanPos = psBuffer; char *p; int iDoubleQuotesSoFar = 0; // scan forwards in case there are more than one (and the first is inside quotes)... // - while ( (p=strstr(psScanPos,"//")) != NULL) - { + while ((p = strstr(psScanPos, "//")) != NULL) { // count the number of double quotes before this point, if odd number, then we're inside quotes... // int iDoubleQuoteCount = iDoubleQuotesSoFar; - for (int i=0; i=0 && isspace(psScanPos[iWhiteSpaceScanPos])) - { + int iWhiteSpaceScanPos = strlen(psScanPos) - 1; + while (iWhiteSpaceScanPos >= 0 && isspace(psScanPos[iWhiteSpaceScanPos])) { psScanPos[iWhiteSpaceScanPos--] = '\0'; } } return; - } - else - { + } else { // inside quotes (blast), oh well, skip past and keep scanning... // - psScanPos = p+1; + psScanPos = p + 1; iDoubleQuotesSoFar = iDoubleQuoteCount; } } @@ -358,24 +307,18 @@ void CStringEdPackage::REMKill( char *psBuffer ) // returns true while new lines available to be read... // -SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) -{ - if (psParsePos[0]) - { +SE_BOOL CStringEdPackage::ReadLine(const char *&psParsePos, char *psDest) { + if (psParsePos[0]) { const char *psLineEnd = strchr(psParsePos, '\n'); - if (psLineEnd) - { + if (psLineEnd) { int iCharsToCopy = (psLineEnd - psParsePos); strncpy(psDest, psParsePos, iCharsToCopy); - psDest[iCharsToCopy] = '\0'; + psDest[iCharsToCopy] = '\0'; psParsePos += iCharsToCopy; - while (*psParsePos && strchr("\r\n",*psParsePos)) - { - psParsePos++; // skip over CR or CR/LF pairs + while (*psParsePos && strchr("\r\n", *psParsePos)) { + psParsePos++; // skip over CR or CR/LF pairs } - } - else - { + } else { // last line... // strcpy(psDest, psParsePos); @@ -384,15 +327,13 @@ SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) // clean up the line... // - if (psDest[0]) - { - int iWhiteSpaceScanPos = strlen(psDest)-1; - while (iWhiteSpaceScanPos>=0 && isspace(psDest[iWhiteSpaceScanPos])) - { + if (psDest[0]) { + int iWhiteSpaceScanPos = strlen(psDest) - 1; + while (iWhiteSpaceScanPos >= 0 && isspace(psDest[iWhiteSpaceScanPos])) { psDest[iWhiteSpaceScanPos--] = '\0'; } - REMKill( psDest ); + REMKill(psDest); } return SE_TRUE; } @@ -402,25 +343,22 @@ SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) // remove any outside quotes from this supplied line, plus any leading or trailing whitespace... // -const char *CStringEdPackage::InsideQuotes( const char *psLine ) -{ +const char *CStringEdPackage::InsideQuotes(const char *psLine) { // I *could* replace this string object with a declared array, but wasn't sure how big to leave it, and it'd have to // be static as well, hence permanent. (problem on consoles?) // - static std::string str; - str = ""; // do NOT join to above line + static std::string str; + str = ""; // do NOT join to above line // skip any leading whitespace... // - while (*psLine == ' ' || *psLine == '\t') - { + while (*psLine == ' ' || *psLine == '\t') { psLine++; } // skip any leading quote... // - if (*psLine == '"') - { + if (*psLine == '"') { psLine++; } @@ -428,22 +366,17 @@ const char *CStringEdPackage::InsideQuotes( const char *psLine ) // str = psLine; - if (psLine[0]) - { + if (psLine[0]) { // lose any trailing whitespace... // - while ( str.c_str()[ strlen(str.c_str()) -1 ] == ' ' || - str.c_str()[ strlen(str.c_str()) -1 ] == '\t' - ) - { - str.erase( strlen(str.c_str()) -1, 1); + while (str.c_str()[strlen(str.c_str()) - 1] == ' ' || str.c_str()[strlen(str.c_str()) - 1] == '\t') { + str.erase(strlen(str.c_str()) - 1, 1); } // lose any trailing quote... // - if (str.c_str()[ strlen(str.c_str()) -1 ] == '"') - { - str.erase( strlen(str.c_str()) -1, 1); + if (str.c_str()[strlen(str.c_str()) - 1] == '"') { + str.erase(strlen(str.c_str()) - 1, 1); } } @@ -452,14 +385,11 @@ const char *CStringEdPackage::InsideQuotes( const char *psLine ) return str.c_str(); } - // returns flag bitmask (eg 00000010b), else 0 for not found // -int CStringEdPackage::GetFlagMask( const char *psFlagName ) -{ - std::map ::iterator itFlag = m_mapFlagMasks.find( psFlagName ); - if ( itFlag != m_mapFlagMasks.end() ) - { +int CStringEdPackage::GetFlagMask(const char *psFlagName) { + std::map::iterator itFlag = m_mapFlagMasks.find(psFlagName); + if (itFlag != m_mapFlagMasks.end()) { int &iMask = (*itFlag).second; return iMask; } @@ -467,24 +397,20 @@ int CStringEdPackage::GetFlagMask( const char *psFlagName ) return 0; } - -void CStringEdPackage::AddFlagReference( const char *psLocalReference, const char *psFlagName ) -{ +void CStringEdPackage::AddFlagReference(const char *psLocalReference, const char *psFlagName) { // add the flag to the list of known ones... // - int iMask = GetFlagMask( psFlagName ); - if (iMask == 0) - { - m_vstrFlagNames.push_back( psFlagName ); - iMask = 1 << (m_vstrFlagNames.size()-1); - m_mapFlagMasks[ psFlagName ] = iMask; + int iMask = GetFlagMask(psFlagName); + if (iMask == 0) { + m_vstrFlagNames.push_back(psFlagName); + iMask = 1 << (m_vstrFlagNames.size() - 1); + m_mapFlagMasks[psFlagName] = iMask; } // // then add the reference to this flag to the currently-parsed reference... // - mapStringEntries_t::iterator itEntry = m_StringEntries.find( va("%s_%s",m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ); - if (itEntry != m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = m_StringEntries.find(va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)); + if (itEntry != m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; Entry.m_iFlags |= iMask; } @@ -497,10 +423,9 @@ void CStringEdPackage::AddFlagReference( const char *psLocalReference, const cha // New bit, instead of static buffer (since XBox guys are desperately short of mem) I return a malloc'd buffer now, // so remember to free it! // -static char *CopeWithDumbStringData( const char *psSentence, const char *psThisLanguage ) -{ - const int iBufferSize = strlen(psSentence)*3; // *3 to allow for expansion of anything even stupid string consisting entirely of elipsis chars - char *psNewString = (char *) Z_Malloc(iBufferSize, TAG_TEMP_WORKSPACE, qfalse); +static char *CopeWithDumbStringData(const char *psSentence, const char *psThisLanguage) { + const int iBufferSize = strlen(psSentence) * 3; // *3 to allow for expansion of anything even stupid string consisting entirely of elipsis chars + char *psNewString = (char *)Z_Malloc(iBufferSize, TAG_TEMP_WORKSPACE, qfalse); Q_strncpyz(psNewString, psSentence, iBufferSize); // this is annoying, I have to just guess at which languages to do it for (ie NOT ASIAN/MBCS!!!) since the @@ -510,79 +435,65 @@ static char *CopeWithDumbStringData( const char *psSentence, const char *psThisL // Ok, bollocks to it, this will have to do. Any other languages that come later and have bugs in their text can // get fixed by them typing it in properly in the first place... // - if (!Q_stricmp(psThisLanguage,"ENGLISH") || - !Q_stricmp(psThisLanguage,"FRENCH") || - !Q_stricmp(psThisLanguage,"GERMAN") || - !Q_stricmp(psThisLanguage,"ITALIAN") || - !Q_stricmp(psThisLanguage,"SPANISH") || - !Q_stricmp(psThisLanguage,"POLISH") || - !Q_stricmp(psThisLanguage,"RUSSIAN") - ) - { + if (!Q_stricmp(psThisLanguage, "ENGLISH") || !Q_stricmp(psThisLanguage, "FRENCH") || !Q_stricmp(psThisLanguage, "GERMAN") || + !Q_stricmp(psThisLanguage, "ITALIAN") || !Q_stricmp(psThisLanguage, "SPANISH") || !Q_stricmp(psThisLanguage, "POLISH") || + !Q_stricmp(psThisLanguage, "RUSSIAN")) { char *p; - // strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" - while ((p=strchr(psNewString,0x92))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" + while ((p = strchr(psNewString, 0x92)) != NULL) // "rich" (and illegal) apostrophe { *p = 0x27; } - // strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' - while ((p=strchr(psNewString,0x93))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' + while ((p = strchr(psNewString, 0x93)) != NULL) { *p = '"'; } - // strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' - while ((p=strchr(psNewString,0x94))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' + while ((p = strchr(psNewString, 0x94)) != NULL) { *p = '"'; } - // strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop - while ((p=strchr(psNewString,0x0B))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop + while ((p = strchr(psNewString, 0x0B)) != NULL) { *p = '.'; } - // strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." - while ((p=strchr(psNewString,0x85))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." + while ((p = strchr(psNewString, 0x85)) != NULL) // "rich" (and illegal) apostrophe { - memmove(p+2,p,strlen(p)); + memmove(p + 2, p, strlen(p)); *p++ = '.'; *p++ = '.'; - *p = '.'; + *p = '.'; } - // strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" - while ((p=strchr(psNewString,0x91))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" + while ((p = strchr(psNewString, 0x91)) != NULL) { *p = 0x27; } - // strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" - while ((p=strchr(psNewString,0x96))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" + while ((p = strchr(psNewString, 0x96)) != NULL) { *p = 0x2D; } - // strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" - while ((p=strchr(psNewString,0x97))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" + while ((p = strchr(psNewString, 0x97)) != NULL) { *p = 0x2D; } // bug fix for picky grammatical errors, replace "?." with "? " // - while ((p=strstr(psNewString,"?."))!=NULL) - { + while ((p = strstr(psNewString, "?.")) != NULL) { p[1] = ' '; } // StripEd and our print code don't support tabs... // - while ((p=strchr(psNewString,0x09))!=NULL) - { + while ((p = strchr(psNewString, 0x09)) != NULL) { *p = ' '; } } @@ -592,150 +503,112 @@ static char *CopeWithDumbStringData( const char *psSentence, const char *psThisL // return is either NULL for good else error message to display... // -const char *CStringEdPackage::ParseLine( const char *psLine ) -{ +const char *CStringEdPackage::ParseLine(const char *psLine) { const char *psErrorMessage = NULL; - if (psLine) - { - if (CheckLineForKeyword( sSE_KEYWORD_VERSION, psLine )) - { + if (psLine) { + if (CheckLineForKeyword(sSE_KEYWORD_VERSION, psLine)) { // VERSION "1" // - const char *psVersionNumber = InsideQuotes( psLine ); - int iVersionNumber = atoi( psVersionNumber ); + const char *psVersionNumber = InsideQuotes(psLine); + int iVersionNumber = atoi(psVersionNumber); - if (iVersionNumber != iSE_VERSION) - { + if (iVersionNumber != iSE_VERSION) { psErrorMessage = va("Unexpected version number %d, expecting %d!\n", iVersionNumber, iSE_VERSION); } - } - else - if ( CheckLineForKeyword(sSE_KEYWORD_CONFIG, psLine) - || CheckLineForKeyword(sSE_KEYWORD_FILENOTES, psLine) - || CheckLineForKeyword(sSE_KEYWORD_NOTES, psLine) - ) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_CONFIG, psLine) || CheckLineForKeyword(sSE_KEYWORD_FILENOTES, psLine) || + CheckLineForKeyword(sSE_KEYWORD_NOTES, psLine)) { // not used ingame, but need to absorb the token - } - else - if (CheckLineForKeyword(sSE_KEYWORD_REFERENCE, psLine)) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_REFERENCE, psLine)) { // REFERENCE GUARD_GOOD_TO_SEE_YOU // - const char *psLocalReference = InsideQuotes( psLine ); - AddEntry( psLocalReference ); - } - else - if (CheckLineForKeyword(sSE_KEYWORD_FLAGS, psLine)) - { + const char *psLocalReference = InsideQuotes(psLine); + AddEntry(psLocalReference); + } else if (CheckLineForKeyword(sSE_KEYWORD_FLAGS, psLine)) { // FLAGS FLAG_CAPTION FLAG_TYPEMATIC // const char *psReference = GetCurrentReference_ParseOnly(); - if (psReference[0]) - { + if (psReference[0]) { static const char sSeperators[] = " \t"; - char sFlags[1024]={0}; // 1024 chars should be enough to store 8 flag names - strncpy(sFlags, psLine, sizeof(sFlags)-1); - char *psToken = strtok( sFlags, sSeperators ); - while( psToken != NULL ) - { + char sFlags[1024] = {0}; // 1024 chars should be enough to store 8 flag names + strncpy(sFlags, psLine, sizeof(sFlags) - 1); + char *psToken = strtok(sFlags, sSeperators); + while (psToken != NULL) { // psToken = flag name (in caps) // - Q_strupr(psToken); // jic - AddFlagReference( psReference, psToken ); + Q_strupr(psToken); // jic + AddFlagReference(psReference, psToken); // read next flag for this string... // - psToken = strtok( NULL, sSeperators ); + psToken = strtok(NULL, sSeperators); } - } - else - { + } else { psErrorMessage = "Error parsing file: Unexpected \"" sSE_KEYWORD_FLAGS "\"\n"; } - } - else - if (CheckLineForKeyword(sSE_KEYWORD_ENDMARKER, psLine)) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_ENDMARKER, psLine)) { // ENDMARKER // - m_bEndMarkerFound_ParseOnly = SE_TRUE; // the only major error checking I bother to do (for file truncation) - } - else - if (!Q_stricmpn(sSE_KEYWORD_LANG, psLine, strlen(sSE_KEYWORD_LANG))) - { + m_bEndMarkerFound_ParseOnly = SE_TRUE; // the only major error checking I bother to do (for file truncation) + } else if (!Q_stricmpn(sSE_KEYWORD_LANG, psLine, strlen(sSE_KEYWORD_LANG))) { // LANG_ENGLISH "GUARD: Good to see you, sir. Taylor is waiting for you in the clean tent. We need to get you suited up. " // const char *psReference = GetCurrentReference_ParseOnly(); - if ( psReference[0] ) - { + if (psReference[0]) { psLine += strlen(sSE_KEYWORD_LANG); // what language is this?... // const char *psWordEnd = psLine; - while (*psWordEnd && *psWordEnd != ' ' && *psWordEnd != '\t') - { + while (*psWordEnd && *psWordEnd != ' ' && *psWordEnd != '\t') { psWordEnd++; } - char sThisLanguage[1024]={0}; + char sThisLanguage[1024] = {0}; size_t iCharsToCopy = psWordEnd - psLine; - if (iCharsToCopy > sizeof(sThisLanguage)-1) - { - iCharsToCopy = sizeof(sThisLanguage)-1; + if (iCharsToCopy > sizeof(sThisLanguage) - 1) { + iCharsToCopy = sizeof(sThisLanguage) - 1; } - strncpy(sThisLanguage, psLine, iCharsToCopy); // already declared as {0} so no need to zero-cap dest buffer + strncpy(sThisLanguage, psLine, iCharsToCopy); // already declared as {0} so no need to zero-cap dest buffer psLine += strlen(sThisLanguage); - const char *_psSentence = ConvertCRLiterals_Read( InsideQuotes( psLine ) ); + const char *_psSentence = ConvertCRLiterals_Read(InsideQuotes(psLine)); // Dammit, I hate having to do crap like this just because other people mess up and put // stupid data in their text, so I have to cope with it. // // note hackery with _psSentence and psSentence because of const-ness. bleurgh. Just don't ask. // - char *psSentence = CopeWithDumbStringData( _psSentence, sThisLanguage ); + char *psSentence = CopeWithDumbStringData(_psSentence, sThisLanguage); - if ( m_bLoadingEnglish_ParseOnly ) - { + if (m_bLoadingEnglish_ParseOnly) { // if loading just "english", then go ahead and store it... // - SetString( psReference, psSentence, SE_FALSE ); - } - else - { + SetString(psReference, psSentence, SE_FALSE); + } else { // if loading a foreign language... // - SE_BOOL bSentenceIsEnglish = (!Q_stricmp(sThisLanguage,"english")) ? SE_TRUE: SE_FALSE; // see whether this is the english master or not + SE_BOOL bSentenceIsEnglish = (!Q_stricmp(sThisLanguage, "english")) ? SE_TRUE : SE_FALSE; // see whether this is the english master or not // this check can be omitted, I'm just being extra careful here... // - if ( !bSentenceIsEnglish ) - { + if (!bSentenceIsEnglish) { // basically this is just checking that an .STE file override is the same language as the .STR... // - if (Q_stricmp( m_strLoadingLanguage_ParseOnly.c_str(), sThisLanguage )) - { + if (Q_stricmp(m_strLoadingLanguage_ParseOnly.c_str(), sThisLanguage)) { psErrorMessage = va("Language \"%s\" found when expecting \"%s\"!\n", sThisLanguage, m_strLoadingLanguage_ParseOnly.c_str()); } } - if (!psErrorMessage) - { - SetString( psReference, psSentence, bSentenceIsEnglish ); + if (!psErrorMessage) { + SetString(psReference, psSentence, bSentenceIsEnglish); } } - Z_Free( psSentence ); - } - else - { + Z_Free(psSentence); + } else { psErrorMessage = "Error parsing file: Unexpected \"" sSE_KEYWORD_LANG "\"\n"; } - } - else - { + } else { psErrorMessage = va("Unknown keyword at linestart: \"%s\"\n", psLine); } } @@ -745,143 +618,111 @@ const char *CStringEdPackage::ParseLine( const char *psLine ) // returns reference of string being parsed, else "" for none. // -const char *CStringEdPackage::GetCurrentReference_ParseOnly( void ) -{ - return m_strCurrentEntryRef_ParseOnly.c_str(); -} +const char *CStringEdPackage::GetCurrentReference_ParseOnly(void) { return m_strCurrentEntryRef_ParseOnly.c_str(); } // add new string entry (during parse) // -void CStringEdPackage::AddEntry( const char *psLocalReference ) -{ +void CStringEdPackage::AddEntry(const char *psLocalReference) { // the reason I don't just assign it anyway is because the optional .STE override files don't contain flags, // and therefore would wipe out the parsed flags of the .STR file... // - mapStringEntries_t::iterator itEntry = m_StringEntries.find( va("%s_%s",m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ); - if (itEntry == m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = m_StringEntries.find(va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)); + if (itEntry == m_StringEntries.end()) { SE_Entry_t SE_Entry; - m_StringEntries[ va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ] = SE_Entry; + m_StringEntries[va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)] = SE_Entry; } m_strCurrentEntryRef_ParseOnly = psLocalReference; } -const char *Leetify( const char *psString ) -{ +const char *Leetify(const char *psString) { static std::string str; str = psString; - if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally + if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally { - static const - char cReplace[]={ 'o','0','l','1','e','3','a','4','s','5','t','7','i','!','h','#', - 'O','0','L','1','E','3','A','4','S','5','T','7','I','!','H','#' // laziness because of strchr() - }; + static const char cReplace[] = { + 'o', '0', 'l', '1', 'e', '3', 'a', '4', 's', '5', 't', '7', 'i', '!', 'h', '#', + 'O', '0', 'L', '1', 'E', '3', 'A', '4', 'S', '5', 'T', '7', 'I', '!', 'H', '#' // laziness because of strchr() + }; char *p; - for (size_t i=0; i( strchr(str.c_str(),cReplace[i]) ) ) != NULL ) - *p = cReplace[i+1]; + for (size_t i = 0; i < sizeof(cReplace); i += 2) { + while ((p = const_cast(strchr(str.c_str(), cReplace[i]))) != NULL) + *p = cReplace[i + 1]; } } return str.c_str(); } - -void CStringEdPackage::SetString( const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug ) -{ - mapStringEntries_t::iterator itEntry = m_StringEntries.find( va("%s_%s",m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ); - if (itEntry != m_StringEntries.end()) - { +void CStringEdPackage::SetString(const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug) { + mapStringEntries_t::iterator itEntry = m_StringEntries.find(va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)); + if (itEntry != m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; - if ( bEnglishDebug || m_bLoadingEnglish_ParseOnly) - { + if (bEnglishDebug || m_bLoadingEnglish_ParseOnly) { // then this is the leading english text of a foreign sentence pair (so it's the debug-key text), // or it's the only text when it's english being loaded... // - Entry.m_strString = Leetify( psNewString ); - if ( m_bLoadDebug ) - { + Entry.m_strString = Leetify(psNewString); + if (m_bLoadDebug) { Entry.m_strDebug = sSE_DEBUGSTR_PREFIX; - Entry.m_strDebug+= /* m_bLoadingEnglish_ParseOnly ? "" : */ psNewString; - Entry.m_strDebug+= sSE_DEBUGSTR_SUFFIX; + Entry.m_strDebug += /* m_bLoadingEnglish_ParseOnly ? "" : */ psNewString; + Entry.m_strDebug += sSE_DEBUGSTR_SUFFIX; } - m_strCurrentEntryEnglish_ParseOnly = psNewString; // for possible "#same" resolving in foreign later - } - else - { + m_strCurrentEntryEnglish_ParseOnly = psNewString; // for possible "#same" resolving in foreign later + } else { // then this is foreign text (so check for "#same" resolving)... // - if (!Q_stricmp(psNewString, sSE_EXPORT_SAME)) - { - Entry.m_strString = m_strCurrentEntryEnglish_ParseOnly; // foreign "#same" is now english - if (m_bLoadDebug) - { + if (!Q_stricmp(psNewString, sSE_EXPORT_SAME)) { + Entry.m_strString = m_strCurrentEntryEnglish_ParseOnly; // foreign "#same" is now english + if (m_bLoadDebug) { Entry.m_strDebug = sSE_DEBUGSTR_PREFIX; - Entry.m_strDebug+= sSE_EXPORT_SAME; // english (debug) is now "#same" - Entry.m_strDebug+= sSE_DEBUGSTR_SUFFIX; + Entry.m_strDebug += sSE_EXPORT_SAME; // english (debug) is now "#same" + Entry.m_strDebug += sSE_DEBUGSTR_SUFFIX; } - } - else - { - Entry.m_strString = psNewString; // foreign is just foreign + } else { + Entry.m_strString = psNewString; // foreign is just foreign } } - } - else - { - __ASSERT(0); // should never happen + } else { + __ASSERT(0); // should never happen } } - - // filename is local here, eg: "strings/german/obj.str" // // return is either NULL for good else error message to display... // -static const char *SE_Load_Actual( const char *psFileName, SE_BOOL bLoadDebug, SE_BOOL bSpeculativeLoad ) -{ +static const char *SE_Load_Actual(const char *psFileName, SE_BOOL bLoadDebug, SE_BOOL bSpeculativeLoad) { const char *psErrorMessage = NULL; - unsigned char *psLoadedData = SE_LoadFileData( psFileName ); - if ( psLoadedData ) - { + unsigned char *psLoadedData = SE_LoadFileData(psFileName); + if (psLoadedData) { // now parse the data... // - char *psParsePos = (char *) psLoadedData; + char *psParsePos = (char *)psLoadedData; - TheStringPackage.SetupNewFileParse( psFileName, bLoadDebug ); + TheStringPackage.SetupNewFileParse(psFileName, bLoadDebug); - char sLineBuffer[16384]; // should be enough for one line of text (some of them can be BIG though) - while ( !psErrorMessage && TheStringPackage.ReadLine((const char *&) psParsePos, sLineBuffer ) ) - { - if (strlen(sLineBuffer)) - { -// __DEBUGOUT( sLineBuffer ); -// __DEBUGOUT( "\n" ); + char sLineBuffer[16384]; // should be enough for one line of text (some of them can be BIG though) + while (!psErrorMessage && TheStringPackage.ReadLine((const char *&)psParsePos, sLineBuffer)) { + if (strlen(sLineBuffer)) { + // __DEBUGOUT( sLineBuffer ); + // __DEBUGOUT( "\n" ); - psErrorMessage = TheStringPackage.ParseLine( sLineBuffer ); + psErrorMessage = TheStringPackage.ParseLine(sLineBuffer); } } - SE_FreeFileDataAfterLoad( psLoadedData); + SE_FreeFileDataAfterLoad(psLoadedData); - if (!psErrorMessage && !TheStringPackage.EndMarkerFoundDuringParse()) - { + if (!psErrorMessage && !TheStringPackage.EndMarkerFoundDuringParse()) { psErrorMessage = va("Truncated file, failed to find \"%s\" at file end!", sSE_KEYWORD_ENDMARKER); } - } - else - { - if ( bSpeculativeLoad ) - { + } else { + if (bSpeculativeLoad) { // then it's ok to not find the file, so do nothing... - } - else - { + } else { psErrorMessage = va("Unable to load \"%s\"!", psFileName); } } @@ -889,31 +730,27 @@ static const char *SE_Load_Actual( const char *psFileName, SE_BOOL bLoadDebug, S return psErrorMessage; } -static const char *SE_GetFoundFile( std::string &strResult ) -{ - static char sTemp[1024/*MAX_PATH*/]; +static const char *SE_GetFoundFile(std::string &strResult) { + static char sTemp[1024 /*MAX_PATH*/]; if (!strlen(strResult.c_str())) return NULL; - strncpy(sTemp,strResult.c_str(),sizeof(sTemp)-1); - sTemp[sizeof(sTemp)-1]='\0'; + strncpy(sTemp, strResult.c_str(), sizeof(sTemp) - 1); + sTemp[sizeof(sTemp) - 1] = '\0'; - char *psSemiColon = strchr(sTemp,';'); - if ( psSemiColon) - { - *psSemiColon = '\0'; + char *psSemiColon = strchr(sTemp, ';'); + if (psSemiColon) { + *psSemiColon = '\0'; - strResult.erase(0,(psSemiColon-sTemp)+1); - } - else - { + strResult.erase(0, (psSemiColon - sTemp) + 1); + } else { // no semicolon found, probably last entry? (though i think even those have them on, oh well) // strResult.erase(); } -// strlwr(sTemp); // just for consistancy and set<> -> set<> erasure checking etc + // strlwr(sTemp); // just for consistancy and set<> -> set<> erasure checking etc return sTemp; } @@ -924,128 +761,106 @@ static const char *SE_GetFoundFile( std::string &strResult ) // // return is either NULL for good else error message to display... // -const char *SE_Load( const char *psFileName, SE_BOOL bLoadDebug = SE_TRUE, SE_BOOL bFailIsCritical = SE_TRUE ) -{ +const char *SE_Load(const char *psFileName, SE_BOOL bLoadDebug = SE_TRUE, SE_BOOL bFailIsCritical = SE_TRUE) { //////////////////////////////////////////////////// // // ingame here tends to pass in names without paths, but I expect them when doing a language load, so... // - char sTemp[1000]={0}; - if (!strchr(psFileName,'/')) - { - strcpy(sTemp,sSE_STRINGS_DIR); - strcat(sTemp,"/"); - if (se_language) - { - strcat(sTemp,se_language->string); - strcat(sTemp,"/"); + char sTemp[1000] = {0}; + if (!strchr(psFileName, '/')) { + strcpy(sTemp, sSE_STRINGS_DIR); + strcat(sTemp, "/"); + if (se_language) { + strcat(sTemp, se_language->string); + strcat(sTemp, "/"); } } - strcat(sTemp,psFileName); - COM_DefaultExtension( sTemp, sizeof(sTemp), sSE_INGAME_FILE_EXTENSION); + strcat(sTemp, psFileName); + COM_DefaultExtension(sTemp, sizeof(sTemp), sSE_INGAME_FILE_EXTENSION); psFileName = &sTemp[0]; // //////////////////////////////////////////////////// - - const char *psErrorMessage = SE_Load_Actual( psFileName, bLoadDebug, SE_FALSE ); + const char *psErrorMessage = SE_Load_Actual(psFileName, bLoadDebug, SE_FALSE); // check for any corresponding / overriding .STE files and load them afterwards... // - if ( !psErrorMessage ) - { - char sFileName[ iSE_MAX_FILENAME_LENGTH ]; - strncpy( sFileName, psFileName, sizeof(sFileName)-1 ); - sFileName[ sizeof(sFileName)-1 ] = '\0'; - char *p = strrchr( sFileName, '.' ); - if (p && strlen(p) == strlen(sSE_EXPORT_FILE_EXTENSION)) - { - strcpy( p, sSE_EXPORT_FILE_EXTENSION ); - - psErrorMessage = SE_Load_Actual( sFileName, bLoadDebug, SE_TRUE ); + if (!psErrorMessage) { + char sFileName[iSE_MAX_FILENAME_LENGTH]; + strncpy(sFileName, psFileName, sizeof(sFileName) - 1); + sFileName[sizeof(sFileName) - 1] = '\0'; + char *p = strrchr(sFileName, '.'); + if (p && strlen(p) == strlen(sSE_EXPORT_FILE_EXTENSION)) { + strcpy(p, sSE_EXPORT_FILE_EXTENSION); + + psErrorMessage = SE_Load_Actual(sFileName, bLoadDebug, SE_TRUE); } } - if (psErrorMessage) - { - if (bFailIsCritical) - { - // TheStringPackage.Clear(TRUE); // Will we want to do this? Any errors that arise should be fixed immediately - Com_Error( ERR_DROP, "SE_Load(): Couldn't load \"%s\"!\n\nError: \"%s\"\n", psFileName, psErrorMessage ); - } - else - { - Com_DPrintf(S_COLOR_YELLOW "SE_Load(): Couldn't load \"%s\"!\n", psFileName ); + if (psErrorMessage) { + if (bFailIsCritical) { + // TheStringPackage.Clear(TRUE); // Will we want to do this? Any errors that arise should be fixed immediately + Com_Error(ERR_DROP, "SE_Load(): Couldn't load \"%s\"!\n\nError: \"%s\"\n", psFileName, psErrorMessage); + } else { + Com_DPrintf(S_COLOR_YELLOW "SE_Load(): Couldn't load \"%s\"!\n", psFileName); } } return psErrorMessage; } - // convenience-function for the main GetString call... // -const char *SE_GetString( const char *psPackageReference, const char *psStringReference) -{ - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long +const char *SE_GetString(const char *psPackageReference, const char *psStringReference) { + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - Com_sprintf(sReference, sizeof(sReference),"%s_%s", psPackageReference, psStringReference); + Com_sprintf(sReference, sizeof(sReference), "%s_%s", psPackageReference, psStringReference); - return SE_GetString( Q_strupr(sReference) ); + return SE_GetString(Q_strupr(sReference)); } - -const char *SE_GetString( const char *psPackageAndStringReference ) -{ +const char *SE_GetString(const char *psPackageAndStringReference) { #ifdef JK2_MODE // Hacky but saves me from fixing 1000000 references --eez extern const char *JK2SP_GetStringTextString(const char *Reference); return JK2SP_GetStringTextString((const char *)psPackageAndStringReference); #else - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - assert(strlen(psPackageAndStringReference) < sizeof(sReference) ); - Q_strncpyz(sReference, psPackageAndStringReference, sizeof(sReference) ); + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long + assert(strlen(psPackageAndStringReference) < sizeof(sReference)); + Q_strncpyz(sReference, psPackageAndStringReference, sizeof(sReference)); Q_strupr(sReference); - mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find( sReference ); - if (itEntry != TheStringPackage.m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find(sReference); + if (itEntry != TheStringPackage.m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; - if ( se_debug->integer && TheStringPackage.m_bLoadDebug ) - { + if (se_debug->integer && TheStringPackage.m_bLoadDebug) { return Entry.m_strDebug.c_str(); - } - else - { + } else { return Entry.m_strString.c_str(); } } // should never get here, but fall back anyway... (except we DO use this to see if there's a debug-friendly key bind, which may not exist) // -// __ASSERT(0); - return ""; // you may want to replace this with something based on _DEBUG or not? + // __ASSERT(0); + return ""; // you may want to replace this with something based on _DEBUG or not? #endif } - // convenience-function for the main GetFlags call... // -int SE_GetFlags ( const char *psPackageReference, const char *psStringReference ) -{ - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long +int SE_GetFlags(const char *psPackageReference, const char *psStringReference) { + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - Com_sprintf(sReference, sizeof(sReference),"%s_%s", psPackageReference, psStringReference); + Com_sprintf(sReference, sizeof(sReference), "%s_%s", psPackageReference, psStringReference); - return SE_GetFlags( sReference ); + return SE_GetFlags(sReference); } -int SE_GetFlags ( const char *psPackageAndStringReference ) -{ - mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find( psPackageAndStringReference ); - if (itEntry != TheStringPackage.m_StringEntries.end()) - { +int SE_GetFlags(const char *psPackageAndStringReference) { + mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find(psPackageAndStringReference); + if (itEntry != TheStringPackage.m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; return Entry.m_iFlags; @@ -1058,17 +873,11 @@ int SE_GetFlags ( const char *psPackageAndStringReference ) return 0; } +int SE_GetNumFlags(void) { return TheStringPackage.m_vstrFlagNames.size(); } -int SE_GetNumFlags( void ) -{ - return TheStringPackage.m_vstrFlagNames.size(); -} - -const char *SE_GetFlagName( int iFlagIndex ) -{ - if ( iFlagIndex < (int)TheStringPackage.m_vstrFlagNames.size()) - { - return TheStringPackage.m_vstrFlagNames[ iFlagIndex ].c_str(); +const char *SE_GetFlagName(int iFlagIndex) { + if (iFlagIndex < (int)TheStringPackage.m_vstrFlagNames.size()) { + return TheStringPackage.m_vstrFlagNames[iFlagIndex].c_str(); } __ASSERT(0); @@ -1077,10 +886,7 @@ const char *SE_GetFlagName( int iFlagIndex ) // returns flag bitmask (eg 00000010b), else 0 for not found // -int SE_GetFlagMask( const char *psFlagName ) -{ - return TheStringPackage.GetFlagMask( psFlagName ); -} +int SE_GetFlagMask(const char *psFlagName) { return TheStringPackage.GetFlagMask(psFlagName); } // I could cache the result of this since it won't change during app lifetime unless someone does a build-publish // while you're still ingame. Cacheing would make sense since it can take a while to scan, but I'll leave it and @@ -1091,45 +897,38 @@ int SE_GetFlagMask( const char *psFlagName ) // Groan, except for Bob. I mentioned that this was slow and only call it once, but he's calling it from // every level-load... Ok, cacheing it is... // -std::vector gvLanguagesAvailable; -int SE_GetNumLanguages(void) -{ - if ( gvLanguagesAvailable.empty() ) - { +std::vector gvLanguagesAvailable; +int SE_GetNumLanguages(void) { + if (gvLanguagesAvailable.empty()) { std::string strResults; - /*int iFilesFound = */SE_BuildFileList( - #ifdef _STRINGED - va("C:\\Source\\Tools\\StringEd\\test_data\\%s",sSE_STRINGS_DIR) - #else - sSE_STRINGS_DIR - #endif - , strResults - ); - - std::set strUniqueStrings; // laziness + /*int iFilesFound = */ SE_BuildFileList( +#ifdef _STRINGED + va("C:\\Source\\Tools\\StringEd\\test_data\\%s", sSE_STRINGS_DIR) +#else + sSE_STRINGS_DIR +#endif + , + strResults); + + std::set strUniqueStrings; // laziness const char *p; - while ((p=SE_GetFoundFile (strResults)) != NULL) - { - const char *psLanguage = TheStringPackage.ExtractLanguageFromPath( p ); + while ((p = SE_GetFoundFile(strResults)) != NULL) { + const char *psLanguage = TheStringPackage.ExtractLanguageFromPath(p); - // __DEBUGOUT( p ); - // __DEBUGOUT( "\n" ); - // __DEBUGOUT( psLanguage ); - // __DEBUGOUT( "\n" ); + // __DEBUGOUT( p ); + // __DEBUGOUT( "\n" ); + // __DEBUGOUT( psLanguage ); + // __DEBUGOUT( "\n" ); - if (!strUniqueStrings.count( psLanguage )) - { - strUniqueStrings.insert( psLanguage ); + if (!strUniqueStrings.count(psLanguage)) { + strUniqueStrings.insert(psLanguage); // if english is available, it should always be first... ( I suppose ) // - if (!Q_stricmp(psLanguage,"english")) - { - gvLanguagesAvailable.insert( gvLanguagesAvailable.begin(), psLanguage ); - } - else - { - gvLanguagesAvailable.push_back( psLanguage ); + if (!Q_stricmp(psLanguage, "english")) { + gvLanguagesAvailable.insert(gvLanguagesAvailable.begin(), psLanguage); + } else { + gvLanguagesAvailable.push_back(psLanguage); } } } @@ -1140,11 +939,9 @@ int SE_GetNumLanguages(void) // SE_GetNumLanguages() must have been called before this... // -const char *SE_GetLanguageName( int iLangIndex ) -{ - if ( iLangIndex < (int)gvLanguagesAvailable.size() ) - { - return gvLanguagesAvailable[ iLangIndex ].c_str(); +const char *SE_GetLanguageName(int iLangIndex) { + if (iLangIndex < (int)gvLanguagesAvailable.size()) { + return gvLanguagesAvailable[iLangIndex].c_str(); } __ASSERT(0); @@ -1153,32 +950,24 @@ const char *SE_GetLanguageName( int iLangIndex ) // SE_GetNumLanguages() must have been called before this... // -const char *SE_GetLanguageDir( int iLangIndex ) -{ - if ( iLangIndex < (int)gvLanguagesAvailable.size() ) - { - return va("%s/%s", sSE_STRINGS_DIR, gvLanguagesAvailable[ iLangIndex ].c_str() ); +const char *SE_GetLanguageDir(int iLangIndex) { + if (iLangIndex < (int)gvLanguagesAvailable.size()) { + return va("%s/%s", sSE_STRINGS_DIR, gvLanguagesAvailable[iLangIndex].c_str()); } __ASSERT(0); return ""; } -void SE_NewLanguage(void) -{ - TheStringPackage.Clear( SE_TRUE ); -} - - +void SE_NewLanguage(void) { TheStringPackage.Clear(SE_TRUE); } // these two functions aren't needed other than to make Quake-type games happy and/or stop memory managers // complaining about leaks if they report them before the global StringEd package object calls it's own dtor. // // but here they are for completeness's sake I guess... // -void SE_Init(void) -{ - TheStringPackage.Clear( SE_FALSE ); +void SE_Init(void) { + TheStringPackage.Clear(SE_FALSE); #ifdef _DEBUG // int iNumLanguages = SE_GetNumLanguages(); @@ -1186,93 +975,75 @@ void SE_Init(void) se_language = Cvar_Get("se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); se_debug = Cvar_Get("se_debug", "0", 0); - sp_leet = Cvar_Get("sp_leet", "0", CVAR_ROM ); + sp_leet = Cvar_Get("sp_leet", "0", CVAR_ROM); // if doing a buildscript, load all languages... // extern cvar_t *com_buildScript; - if (com_buildScript->integer == 2) - { + if (com_buildScript->integer == 2) { int iLanguages = SE_GetNumLanguages(); - for (int iLang = 0; iLang < iLanguages; iLang++) - { - const char *psLanguage = SE_GetLanguageName( iLang ); // eg "german" - Com_Printf( "com_buildScript(2): Loading language \"%s\"...\n", psLanguage ); - SE_LoadLanguage( psLanguage ); + for (int iLang = 0; iLang < iLanguages; iLang++) { + const char *psLanguage = SE_GetLanguageName(iLang); // eg "german" + Com_Printf("com_buildScript(2): Loading language \"%s\"...\n", psLanguage); + SE_LoadLanguage(psLanguage); } } - const char *psErrorMessage = SE_LoadLanguage( se_language->string ); - if (psErrorMessage) - { - Com_Error( ERR_DROP, "SE_Init() Unable to load language: \"%s\"!\nError: \"%s\"\n", se_language->string,psErrorMessage ); + const char *psErrorMessage = SE_LoadLanguage(se_language->string); + if (psErrorMessage) { + Com_Error(ERR_DROP, "SE_Init() Unable to load language: \"%s\"!\nError: \"%s\"\n", se_language->string, psErrorMessage); } } -void SE_ShutDown(void) -{ - TheStringPackage.Clear( SE_FALSE ); -} - +void SE_ShutDown(void) { TheStringPackage.Clear(SE_FALSE); } // returns error message else NULL for ok. // // Any errors that result from this should probably be treated as game-fatal, since an asset file is fuxored. // -const char *SE_LoadLanguage( const char *psLanguage, SE_BOOL bLoadDebug /* = SE_TRUE */ ) -{ +const char *SE_LoadLanguage(const char *psLanguage, SE_BOOL bLoadDebug /* = SE_TRUE */) { const char *psErrorMessage = NULL; - if (psLanguage && psLanguage[0]) - { + if (psLanguage && psLanguage[0]) { SE_NewLanguage(); std::string strResults; - /*int iFilesFound = */SE_BuildFileList( - #ifdef _STRINGED - va("C:\\Source\\Tools\\StringEd\\test_data\\%s",sSE_STRINGS_DIR) - #else - sSE_STRINGS_DIR - #endif - , strResults - ); + /*int iFilesFound = */ SE_BuildFileList( +#ifdef _STRINGED + va("C:\\Source\\Tools\\StringEd\\test_data\\%s", sSE_STRINGS_DIR) +#else + sSE_STRINGS_DIR +#endif + , + strResults); const char *p; - while ( (p=SE_GetFoundFile (strResults)) != NULL && !psErrorMessage ) - { - const char *psThisLang = TheStringPackage.ExtractLanguageFromPath( p ); + while ((p = SE_GetFoundFile(strResults)) != NULL && !psErrorMessage) { + const char *psThisLang = TheStringPackage.ExtractLanguageFromPath(p); - if ( !Q_stricmp( psLanguage, psThisLang ) ) - { - psErrorMessage = SE_Load( p, bLoadDebug ); + if (!Q_stricmp(psLanguage, psThisLang)) { + psErrorMessage = SE_Load(p, bLoadDebug); } } - } - else - { - __ASSERT( 0 && "SE_LoadLanguage(): Bad language name!" ); + } else { + __ASSERT(0 && "SE_LoadLanguage(): Bad language name!"); } return psErrorMessage; } - // called in Com_Frame, so don't take up any time! (can also be called during dedicated) // // instead of re-loading just the files we've already loaded I'm going to load the whole language (simpler) // -void SE_CheckForLanguageUpdates(void) -{ - if (se_language && se_language->modified) - { - const char *psErrorMessage = SE_LoadLanguage( se_language->string, SE_TRUE ); - if ( psErrorMessage ) - { - Com_Error( ERR_DROP, psErrorMessage ); +void SE_CheckForLanguageUpdates(void) { + if (se_language && se_language->modified) { + const char *psErrorMessage = SE_LoadLanguage(se_language->string, SE_TRUE); + if (psErrorMessage) { + Com_Error(ERR_DROP, psErrorMessage); } se_language->modified = SE_FALSE; } } - ///////////////////////// eof ////////////////////////// diff --git a/code/qcommon/stringed_interface.cpp b/code/qcommon/stringed_interface.cpp index 0a6abd91cc..0a2e7ccf21 100644 --- a/code/qcommon/stringed_interface.cpp +++ b/code/qcommon/stringed_interface.cpp @@ -29,7 +29,6 @@ along with this program; if not, see . // into each project. // - ////////////////////////////////////////////////// // // stuff common to all qcommon files... @@ -50,47 +49,36 @@ along with this program; if not, see . #include "generic.h" #endif - // this just gets the binary of the file into memory, so I can parse it. Called by main SGE loader // // returns either char * of loaded file, else NULL for failed-to-open... // -unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = 0 */) -{ +unsigned char *SE_LoadFileData(const char *psFileName, int *piLoadedLength /* = 0 */) { unsigned char *psReturn = NULL; - if ( piLoadedLength ) - { + if (piLoadedLength) { *piLoadedLength = 0; } #ifdef _STRINGED - if (psFileName[1] == ':') - { + if (psFileName[1] == ':') { // full-path filename... // - FILE *fh = fopen( psFileName, "rb" ); - if (fh) - { + FILE *fh = fopen(psFileName, "rb"); + if (fh) { long lLength = filesize(fh); - if (lLength > 0) - { - psReturn = (unsigned char *) malloc( lLength + 1); - if (psReturn) - { - int iBytesRead = fread( psReturn, 1, lLength, fh ); - if (iBytesRead != lLength) - { + if (lLength > 0) { + psReturn = (unsigned char *)malloc(lLength + 1); + if (psReturn) { + int iBytesRead = fread(psReturn, 1, lLength, fh); + if (iBytesRead != lLength) { // error reading file!!!... // free(psReturn); - psReturn = NULL; - } - else - { - psReturn[ lLength ] = '\0'; - if ( piLoadedLength ) - { + psReturn = NULL; + } else { + psReturn[lLength] = '\0'; + if (piLoadedLength) { *piLoadedLength = iBytesRead; } } @@ -98,20 +86,17 @@ unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = } } } - } - else + } else #endif { // local filename, so prepend the base dir etc according to game and load it however (from PAK?) // unsigned char *pvLoadedData; - int iLen = FS_ReadFile( psFileName, (void **)&pvLoadedData ); + int iLen = FS_ReadFile(psFileName, (void **)&pvLoadedData); - if (iLen>0) - { + if (iLen > 0) { psReturn = pvLoadedData; - if ( piLoadedLength ) - { + if (piLoadedLength) { *piLoadedLength = iLen; } } @@ -120,65 +105,53 @@ unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = return psReturn; } - // called by main SGE code after loaded data has been parsedinto internal structures... // -void SE_FreeFileDataAfterLoad( unsigned char *psLoadedFile ) -{ +void SE_FreeFileDataAfterLoad(unsigned char *psLoadedFile) { #ifdef _STRINGED - if ( psLoadedFile ) - { - free( psLoadedFile ); + if (psLoadedFile) { + free(psLoadedFile); } #else - if ( psLoadedFile ) - { - FS_FreeFile( psLoadedFile ); + if (psLoadedFile) { + FS_FreeFile(psLoadedFile); } #endif } - - - - #ifndef _STRINGED // quake-style method of doing things since their file-list code doesn't have a 'recursive' flag... // int giFilesFound; -static void SE_R_ListFiles( const char *psExtension, const char *psDir, std::string &strResults ) -{ -// Com_Printf(va("Scanning Dir: %s\n",psDir)); +static void SE_R_ListFiles(const char *psExtension, const char *psDir, std::string &strResults) { + // Com_Printf(va("Scanning Dir: %s\n",psDir)); - char **sysFiles, **dirFiles; - int numSysFiles, i, numdirs; + char **sysFiles, **dirFiles; + int numSysFiles, i, numdirs; - dirFiles = FS_ListFiles( psDir, "/", &numdirs); - for (i=0;i. #include #include -cvar_t *sp_language; -static cvar_t *sp_show_strip; -static cvar_t *sp_leet; +cvar_t *sp_language; +static cvar_t *sp_show_strip; +static cvar_t *sp_leet; -#define STRIP_VERSION 1 +#define STRIP_VERSION 1 -#define MAX_LANGUAGES 10 -#define MAX_STRINGS 256 -#define MAX_ID 255 +#define MAX_LANGUAGES 10 +#define MAX_STRINGS 256 +#define MAX_ID 255 /*enum { @@ -56,104 +56,100 @@ static cvar_t *sp_leet; SP_LANGUAGE_ALL = 255 };*/ +#define SP_PACKAGE 0xff00 +#define SP_STRING 0x00ff -#define SP_PACKAGE 0xff00 -#define SP_STRING 0x00ff - -#define SP_GET_PACKAGE(x) ( (x & SP_PACKAGE) >> 8 ) +#define SP_GET_PACKAGE(x) ((x & SP_PACKAGE) >> 8) // Flags -#define SP_FLAG1 0x00000001 // CENTERED -#define SP_FLAG2 0x00000002 -#define SP_FLAG3 0x00000004 -#define SP_FLAG4 0x00000008 -#define SP_FLAG5 0x00000010 -#define SP_FLAG6 0x00000020 -#define SP_FLAG7 0x00000040 -#define SP_FLAG8 0x00000080 -#define SP_FLAG9 0x00000100 -#define SP_FLAG_ORIGINAL 0x00000200 +#define SP_FLAG1 0x00000001 // CENTERED +#define SP_FLAG2 0x00000002 +#define SP_FLAG3 0x00000004 +#define SP_FLAG4 0x00000008 +#define SP_FLAG5 0x00000010 +#define SP_FLAG6 0x00000020 +#define SP_FLAG7 0x00000040 +#define SP_FLAG8 0x00000080 +#define SP_FLAG9 0x00000100 +#define SP_FLAG_ORIGINAL 0x00000200 // Registration -#define SP_REGISTER_CLIENT (0x01) -#define SP_REGISTER_SERVER (0x02) -#define SP_REGISTER_MENU (0x04) +#define SP_REGISTER_CLIENT (0x01) +#define SP_REGISTER_SERVER (0x02) +#define SP_REGISTER_MENU (0x04) #define SP_REGISTER_REQUIRED (0x08) - //====================================================================== -class cStringPackageID -{ -private: - std::string name; - byte reg; -public: - cStringPackageID(const char *in_name, byte in_reg) { name = in_name; reg = in_reg; } - const char *GetName(void) const { return(name.c_str()); } - byte GetReg(void) const { return(reg); } -}; - +class cStringPackageID { + private: + std::string name; + byte reg; -class cStringPackage -{ -protected: - unsigned char ID; - unsigned char Registration; - std::string name; - char *Reference; - -public: - cStringPackage(const char *in, unsigned char initID = 0, char *initDescription = NULL, char *initReference = NULL); - virtual ~cStringPackage(void); + public: + cStringPackageID(const char *in_name, byte in_reg) { + name = in_name; + reg = in_reg; + } + const char *GetName(void) const { return (name.c_str()); } + byte GetReg(void) const { return (reg); } +}; - void Register(unsigned char newRegistration) { Registration |= newRegistration; } - bool UnRegister(unsigned char oldRegistration) { Registration &= ~oldRegistration; return (Registration == 0); } - bool RegisteredOnServer(void) const { return(!!(Registration & SP_REGISTER_SERVER)); } - byte GetRegistration(void) const { return(Registration); } +class cStringPackage { + protected: + unsigned char ID; + unsigned char Registration; + std::string name; + char *Reference; + + public: + cStringPackage(const char *in, unsigned char initID = 0, char *initDescription = NULL, char *initReference = NULL); + virtual ~cStringPackage(void); + + void Register(unsigned char newRegistration) { Registration |= newRegistration; } + bool UnRegister(unsigned char oldRegistration) { + Registration &= ~oldRegistration; + return (Registration == 0); + } + bool RegisteredOnServer(void) const { return (!!(Registration & SP_REGISTER_SERVER)); } + byte GetRegistration(void) const { return (Registration); } - void SetID(unsigned char newID) { ID = newID; } - void SetReference(char *newReference); + void SetID(unsigned char newID) { ID = newID; } + void SetReference(char *newReference); - unsigned char GetID(void) { return ID; } - char *GetReference(void) { return Reference; } - const char *GetName(void) const { return(name.c_str()); } + unsigned char GetID(void) { return ID; } + char *GetReference(void) { return Reference; } + const char *GetName(void) const { return (name.c_str()); } - virtual bool UnderstandToken(char *&Data, int &Size, int token, char *data ); + virtual bool UnderstandToken(char *&Data, int &Size, int token, char *data); #if 0 virtual bool Load(char *FileName ); #endif - virtual bool Load(char *Data, int &Size ); + virtual bool Load(char *Data, int &Size); }; +class cStringPackageSingle : public cStringPackage { + private: + cStringsSingle Strings[MAX_STRINGS]; + std::map ReferenceTable; -class cStringPackageSingle : public cStringPackage -{ -private: - cStringsSingle Strings[MAX_STRINGS]; - std::map ReferenceTable; - -public: - cStringPackageSingle(const char *in, unsigned char initID = 0, char *initReference = NULL); - ~cStringPackageSingle(void); + public: + cStringPackageSingle(const char *in, unsigned char initID = 0, char *initReference = NULL); + ~cStringPackageSingle(void); - cStringsSingle *FindString(int index) { return &Strings[index]; } - cStringsSingle *FindString(char *ReferenceLookup); - int FindStringID(const char *ReferenceLookup); + cStringsSingle *FindString(int index) { return &Strings[index]; } + cStringsSingle *FindString(char *ReferenceLookup); + int FindStringID(const char *ReferenceLookup); - virtual bool UnderstandToken(char *&Data, int &Size, int token, char *data ); + virtual bool UnderstandToken(char *&Data, int &Size, int token, char *data); }; - -typedef struct sFlagPair -{ - int Name; - unsigned long Value; +typedef struct sFlagPair { + int Name; + unsigned long Value; } tFlagPair; - -enum -{ +enum { TK_INVALID = -1, TK_TEXT_LANGUAGE1 = 0, TK_TEXT_LANGUAGE2, @@ -189,72 +185,54 @@ enum TK_END }; - -const char *Tokens[TK_END] = -{ - "TEXT_LANGUAGE1", - "TEXT_LANGUAGE2", - "TEXT_LANGUAGE3", - "TEXT_LANGUAGE4", - "TEXT_LANGUAGE5", - "TEXT_LANGUAGE6", - "TEXT_LANGUAGE7", - "TEXT_LANGUAGE8", - "TEXT_LANGUAGE9", - "TEXT_LANGUAGE10", - "VERSION", - "ID", - "REFERENCE", - "DESCRIPTION", - "COUNT", - "FLAGS", - "SP_FLAG1", - "SP_FLAG2", - "SP_FLAG3", - "SP_FLAG4", - "SP_FLAG5", - "SP_FLAG6", - "SP_FLAG7", - "SP_FLAG8", - "SP_FLAG9", - "SP_FLAG_ORIGINAL", - "{", - "}", - "INDEX", - "NOTES", - "CONFIG" -}; - - -sFlagPair FlagPairs[] = -{ - { TK_SP_FLAG1, SP_FLAG1 }, - { TK_SP_FLAG2, SP_FLAG2 }, - { TK_SP_FLAG3, SP_FLAG3 }, - { TK_SP_FLAG4, SP_FLAG4 }, - { TK_SP_FLAG5, SP_FLAG5 }, - { TK_SP_FLAG6, SP_FLAG6 }, - { TK_SP_FLAG7, SP_FLAG7 }, - { TK_SP_FLAG8, SP_FLAG8 }, - { TK_SP_FLAG9, SP_FLAG9 }, - { TK_SP_FLAG_ORIGINAL, SP_FLAG_ORIGINAL }, - { TK_INVALID, 0 } -}; - -sFlagPair LanguagePairs[] = -{ - { TK_TEXT_LANGUAGE1, SP_LANGUAGE_ENGLISH }, - { TK_TEXT_LANGUAGE2, SP_LANGUAGE_FRENCH }, - { TK_TEXT_LANGUAGE3, SP_LANGUAGE_GERMAN }, - { TK_TEXT_LANGUAGE4, SP_LANGUAGE_BRITISH }, - { TK_TEXT_LANGUAGE5, SP_LANGUAGE_KOREAN }, - { TK_TEXT_LANGUAGE6, SP_LANGUAGE_TAIWANESE }, - { TK_TEXT_LANGUAGE7, SP_LANGUAGE_ITALIAN }, - { TK_TEXT_LANGUAGE8, SP_LANGUAGE_SPANISH }, - { TK_TEXT_LANGUAGE9, SP_LANGUAGE_JAPANESE }, - { TK_TEXT_LANGUAGE10, SP_LANGUAGE_10}, - { TK_INVALID, 0 } -}; +const char *Tokens[TK_END] = {"TEXT_LANGUAGE1", + "TEXT_LANGUAGE2", + "TEXT_LANGUAGE3", + "TEXT_LANGUAGE4", + "TEXT_LANGUAGE5", + "TEXT_LANGUAGE6", + "TEXT_LANGUAGE7", + "TEXT_LANGUAGE8", + "TEXT_LANGUAGE9", + "TEXT_LANGUAGE10", + "VERSION", + "ID", + "REFERENCE", + "DESCRIPTION", + "COUNT", + "FLAGS", + "SP_FLAG1", + "SP_FLAG2", + "SP_FLAG3", + "SP_FLAG4", + "SP_FLAG5", + "SP_FLAG6", + "SP_FLAG7", + "SP_FLAG8", + "SP_FLAG9", + "SP_FLAG_ORIGINAL", + "{", + "}", + "INDEX", + "NOTES", + "CONFIG"}; + +sFlagPair FlagPairs[] = { + {TK_SP_FLAG1, SP_FLAG1}, {TK_SP_FLAG2, SP_FLAG2}, {TK_SP_FLAG3, SP_FLAG3}, {TK_SP_FLAG4, SP_FLAG4}, {TK_SP_FLAG5, SP_FLAG5}, + {TK_SP_FLAG6, SP_FLAG6}, {TK_SP_FLAG7, SP_FLAG7}, {TK_SP_FLAG8, SP_FLAG8}, {TK_SP_FLAG9, SP_FLAG9}, {TK_SP_FLAG_ORIGINAL, SP_FLAG_ORIGINAL}, + {TK_INVALID, 0}}; + +sFlagPair LanguagePairs[] = {{TK_TEXT_LANGUAGE1, SP_LANGUAGE_ENGLISH}, + {TK_TEXT_LANGUAGE2, SP_LANGUAGE_FRENCH}, + {TK_TEXT_LANGUAGE3, SP_LANGUAGE_GERMAN}, + {TK_TEXT_LANGUAGE4, SP_LANGUAGE_BRITISH}, + {TK_TEXT_LANGUAGE5, SP_LANGUAGE_KOREAN}, + {TK_TEXT_LANGUAGE6, SP_LANGUAGE_TAIWANESE}, + {TK_TEXT_LANGUAGE7, SP_LANGUAGE_ITALIAN}, + {TK_TEXT_LANGUAGE8, SP_LANGUAGE_SPANISH}, + {TK_TEXT_LANGUAGE9, SP_LANGUAGE_JAPANESE}, + {TK_TEXT_LANGUAGE10, SP_LANGUAGE_10}, + {TK_INVALID, 0}}; /************************************************************************************************ * FindToken @@ -267,30 +245,22 @@ sFlagPair LanguagePairs[] = * token enum * ************************************************************************************************/ -int FindToken(char *token, bool whole) -{ +int FindToken(char *token, bool whole) { int token_value; - int i; + int i; - for(token_value = 0; token_value != TK_END; token_value++) - { - if (whole) - { - if (Q_stricmp(token, Tokens[token_value]) == 0) - { + for (token_value = 0; token_value != TK_END; token_value++) { + if (whole) { + if (Q_stricmp(token, Tokens[token_value]) == 0) { return token_value; } - } - else - { - if (Q_stricmpn(token, Tokens[token_value], strlen(Tokens[token_value])) == 0) - { + } else { + if (Q_stricmpn(token, Tokens[token_value], strlen(Tokens[token_value])) == 0) { i = strlen(Tokens[token_value]); - while(token[i] == ' ') - { + while (token[i] == ' ') { i++; } - memmove(token, &token[i], strlen(token)-i+1); + memmove(token, &token[i], strlen(token) - i + 1); return token_value; } @@ -308,25 +278,22 @@ int FindToken(char *token, bool whole) * return: * ************************************************************************************************/ -bool ReadData(char *&Data, int &Size, char *Result, int Result_Size) -{ +bool ReadData(char *&Data, int &Size, char *Result, int Result_Size) { char *pos; Result[0] = 0; - if (Size <= 0) - { + if (Size <= 0) { return false; } pos = Result; - do - { + do { *pos = *Data; pos++; Data++; Size--; Result_Size--; - } while(Size > 0 && Result_Size > 0 && *(Data-1) != '\n'); + } while (Size > 0 && Result_Size > 0 && *(Data - 1) != '\n'); *pos = 0; @@ -341,61 +308,52 @@ bool ReadData(char *&Data, int &Size, char *Result, int Result_Size) * return: * ************************************************************************************************/ -void GetLine(char *&Data, int &Size, int &token, char *&data) -{ - static char save_data[8192]; - char temp_data[8192]; - char *test_token, *pos; +void GetLine(char *&Data, int &Size, int &token, char *&data) { + static char save_data[8192]; + char temp_data[8192]; + char *test_token, *pos; save_data[0] = 0; token = TK_INVALID; data = save_data; - if (!ReadData(Data, Size, temp_data, sizeof(temp_data))) - { + if (!ReadData(Data, Size, temp_data, sizeof(temp_data))) { return; } -// strcpy(temp_data, " DATA \"test of the data\ntest test\ndfa dfd"); -// strcpy(temp_data, " DATA"); + // strcpy(temp_data, " DATA \"test of the data\ntest test\ndfa dfd"); + // strcpy(temp_data, " DATA"); pos = temp_data; - while((*pos) && strchr(" \n\r", *pos)) - { // remove white space + while ((*pos) && strchr(" \n\r", *pos)) { // remove white space pos++; } test_token = pos; - while((*pos) && !strchr(" \n\r", *pos)) - { // scan until end of white space + while ((*pos) && !strchr(" \n\r", *pos)) { // scan until end of white space pos++; } - if ((*pos)) - { + if ((*pos)) { *pos = 0; pos++; } token = FindToken(test_token, true); - while((*pos) && strchr(" \n\r", *pos)) - { // remove white space + while ((*pos) && strchr(" \n\r", *pos)) { // remove white space pos++; } - if ((*pos) == '\"') - { + if ((*pos) == '\"') { pos++; test_token = save_data; memset(save_data, 0, sizeof(save_data)); - while(((*pos) != '\"' || !strchr("\n\r", (*(pos+1)))) && (*pos)) - { - if ((*pos) == '\\' && (*(pos+1)) == 'n') - { + while (((*pos) != '\"' || !strchr("\n\r", (*(pos + 1)))) && (*pos)) { + if ((*pos) == '\\' && (*(pos + 1)) == 'n') { *test_token = '\n'; test_token++; - pos+=2; + pos += 2; continue; } @@ -404,16 +362,12 @@ void GetLine(char *&Data, int &Size, int &token, char *&data) pos++; } - if ((*pos) == '\"') - { + if ((*pos) == '\"') { *pos = 0; } - } - else - { + } else { test_token = pos; - while((*pos) && !strchr("\n\r", *pos)) - { // scan until end of white space + while ((*pos) && !strchr("\n\r", *pos)) { // scan until end of white space pos++; } *pos = 0; @@ -422,7 +376,6 @@ void GetLine(char *&Data, int &Size, int &token, char *&data) } } - //====================================================================== /************************************************************************************************ @@ -433,8 +386,7 @@ void GetLine(char *&Data, int &Size, int &token, char *&data) * return: * ************************************************************************************************/ -cStrings::cStrings(unsigned int initFlags, char *initReference) -{ +cStrings::cStrings(unsigned int initFlags, char *initReference) { Flags = initFlags; Reference = NULL; @@ -449,10 +401,7 @@ cStrings::cStrings(unsigned int initFlags, char *initReference) * return: * ************************************************************************************************/ -cStrings::~cStrings(void) -{ - Clear(); -} +cStrings::~cStrings(void) { Clear(); } /************************************************************************************************ * Clear @@ -462,12 +411,10 @@ cStrings::~cStrings(void) * return: * ************************************************************************************************/ -void cStrings::Clear(void) -{ +void cStrings::Clear(void) { Flags = 0; - if (Reference) - { + if (Reference) { delete Reference; Reference = NULL; } @@ -481,67 +428,53 @@ void cStrings::Clear(void) * return: * ************************************************************************************************/ -void cStrings::SetFlags(unsigned int newFlags) -{ - Flags = newFlags; -} - +void cStrings::SetFlags(unsigned int newFlags) { Flags = newFlags; } -void cStrings::SetReference(char *newReference) -{ - if (Reference) - { +void cStrings::SetReference(char *newReference) { + if (Reference) { delete Reference; Reference = NULL; } - if (!newReference || !newReference[0]) - { + if (!newReference || !newReference[0]) { return; } - Reference = new char[strlen(newReference)+1]; + Reference = new char[strlen(newReference) + 1]; strcpy(Reference, newReference); } -bool cStrings::UnderstandToken(int token, char *data ) -{ - sFlagPair *FlagPair; - - switch(token) - { - case TK_FLAGS: - while(token != TK_INVALID) - { - token = FindToken(data, false); - for(FlagPair = FlagPairs; FlagPair->Name != TK_INVALID; FlagPair++) - { - if (FlagPair->Name == token) - { - Flags |= FlagPair->Value; - break; - } +bool cStrings::UnderstandToken(int token, char *data) { + sFlagPair *FlagPair; + + switch (token) { + case TK_FLAGS: + while (token != TK_INVALID) { + token = FindToken(data, false); + for (FlagPair = FlagPairs; FlagPair->Name != TK_INVALID; FlagPair++) { + if (FlagPair->Name == token) { + Flags |= FlagPair->Value; + break; } } - return true; + } + return true; - case TK_REFERENCE: - SetReference(data); - return true; + case TK_REFERENCE: + SetReference(data); + return true; - case TK_RIGHT_BRACE: - return false; + case TK_RIGHT_BRACE: + return false; } - if (token == TK_INVALID) - { + if (token == TK_INVALID) { return false; } return true; } - /************************************************************************************************ * Load - Load the given string packet file * @@ -554,222 +487,178 @@ bool cStrings::UnderstandToken(int token, char *data ) * done or not * ************************************************************************************************/ -bool cStrings::Load(char *&Data, int &Size ) -{ - int token; - char *data; +bool cStrings::Load(char *&Data, int &Size) { + int token; + char *data; Clear(); GetLine(Data, Size, token, data); - if (token != TK_LEFT_BRACE) - { + if (token != TK_LEFT_BRACE) { return false; } GetLine(Data, Size, token, data); - while (UnderstandToken(token, data) ) - { + while (UnderstandToken(token, data)) { GetLine(Data, Size, token, data); } - if (token != TK_RIGHT_BRACE) - { + if (token != TK_RIGHT_BRACE) { return false; } return true; } +cStringsSingle::cStringsSingle(unsigned int initFlags, char *initReference) : cStrings(initFlags, initReference) { Text = NULL; } +cStringsSingle::~cStringsSingle() { Clear(); } -cStringsSingle::cStringsSingle(unsigned int initFlags, char *initReference) -:cStrings(initFlags, initReference) -{ - Text = NULL; -} - -cStringsSingle::~cStringsSingle() -{ - Clear(); -} - -void cStringsSingle::Clear(void) -{ +void cStringsSingle::Clear(void) { cStrings::Clear(); - if (Text) - { + if (Text) { delete Text; Text = NULL; } } -void cStringsSingle::SetText(const char *newText) -{ - int length; - char *Dest; +void cStringsSingle::SetText(const char *newText) { + int length; + char *Dest; - if (Text) - { + if (Text) { delete Text; Text = NULL; } - if (!newText || !newText[0]) - { + if (!newText || !newText[0]) { return; } - length = strlen(newText)+1; + length = strlen(newText) + 1; // Following is for TESTING for SOF. - if(sp_show_strip->value) - { - const char sDebugString[]="SP:"; + if (sp_show_strip->value) { + const char sDebugString[] = "SP:"; Dest = Text = new char[length + strlen(sDebugString)]; - strcpy(Dest,sDebugString); + strcpy(Dest, sDebugString); Dest += strlen(Dest); - } - else - { + } else { Dest = Text = new char[length]; } strcpy(Dest, newText); } - // fix problems caused by fucking morons entering clever "rich" chars in to new text files *after* the auto-stripper // removed them all in the first place... // // ONLY DO THIS FOR EUROPEAN LANGUAGES, OR IT BREAKS ASIAN STRINGS!!!!!!!!!!!!!!!!!!!!! // -static void FixIllegalChars(char *psText) -{ +static void FixIllegalChars(char *psText) { char *p; -// strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" - while ((p=strchr(psText,0x92))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" + while ((p = strchr(psText, 0x92)) != NULL) // "rich" (and illegal) apostrophe { *p = 0x27; } -// strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' - while ((p=strchr(psText,0x93))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' + while ((p = strchr(psText, 0x93)) != NULL) // "rich" (and illegal) apostrophe { *p = '"'; } -// strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' - while ((p=strchr(psText,0x94))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' + while ((p = strchr(psText, 0x94)) != NULL) // "rich" (and illegal) apostrophe { *p = '"'; } -// strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop - while ((p=strchr(psText,0x0B))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop + while ((p = strchr(psText, 0x0B)) != NULL) // "rich" (and illegal) apostrophe { *p = '.'; } -// strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." - while ((p=strchr(psText,0x85))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." + while ((p = strchr(psText, 0x85)) != NULL) // "rich" (and illegal) apostrophe { - *p = '.'; // can't do in-string replace of "." with "...", so just forget it + *p = '.'; // can't do in-string replace of "." with "...", so just forget it } -// strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" - while ((p=strchr(psText,0x91))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" + while ((p = strchr(psText, 0x91)) != NULL) // "rich" (and illegal) apostrophe { *p = 0x27; } -// strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" - while ((p=strchr(psText,0x96))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" + while ((p = strchr(psText, 0x96)) != NULL) { *p = 0x2D; } -// strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" - while ((p=strchr(psText,0x97))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" + while ((p = strchr(psText, 0x97)) != NULL) { *p = 0x2D; } // bug fix for picky grammatical errors, replace "?." with "? " // - while ((p=strstr(psText,"?."))!=NULL) - { + while ((p = strstr(psText, "?.")) != NULL) { p[1] = ' '; } // StripEd and our print code don't support tabs... // - while ((p=strchr(psText,0x09))!=NULL) - { + while ((p = strchr(psText, 0x09)) != NULL) { *p = ' '; } - - if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally + if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally { - char cReplace[]={ 'o','0','l','1','e','3','a','4','s','5','t','7','i','!','h','#', - 'O','0','L','1','E','3','A','4','S','5','T','7','I','!','H','#' // laziness because of strchr() - }; - - for (size_t i=0; iName != TK_INVALID; LanguagePair++) - { - if (LanguagePair->Name == TK_TEXT_LANGUAGE1 && token == TK_TEXT_LANGUAGE1 && !Text) - { // default to english in case there is no foreign - if (LanguagePair->Name == TK_TEXT_LANGUAGE1 || - LanguagePair->Name == TK_TEXT_LANGUAGE2 || - LanguagePair->Name == TK_TEXT_LANGUAGE3 || - LanguagePair->Name == TK_TEXT_LANGUAGE8 - ) - { - FixIllegalChars(data); - } - SetText(data); - return true; - } - else if (LanguagePair->Name == token && (signed) LanguagePair->Value == sp_language->integer) - { - if (LanguagePair->Name == TK_TEXT_LANGUAGE1 || - LanguagePair->Name == TK_TEXT_LANGUAGE2 || - LanguagePair->Name == TK_TEXT_LANGUAGE3 || - LanguagePair->Name == TK_TEXT_LANGUAGE8 - ) - { - FixIllegalChars(data); - } - SetText(data); - return true; - } +bool cStringsSingle::UnderstandToken(int token, char *data) { + sFlagPair *LanguagePair; + + // switch(token) + // { + // default: + for (LanguagePair = LanguagePairs; LanguagePair->Name != TK_INVALID; LanguagePair++) { + if (LanguagePair->Name == TK_TEXT_LANGUAGE1 && token == TK_TEXT_LANGUAGE1 && !Text) { // default to english in case there is no foreign + if (LanguagePair->Name == TK_TEXT_LANGUAGE1 || LanguagePair->Name == TK_TEXT_LANGUAGE2 || LanguagePair->Name == TK_TEXT_LANGUAGE3 || + LanguagePair->Name == TK_TEXT_LANGUAGE8) { + FixIllegalChars(data); } + SetText(data); + return true; + } else if (LanguagePair->Name == token && (signed)LanguagePair->Value == sp_language->integer) { + if (LanguagePair->Name == TK_TEXT_LANGUAGE1 || LanguagePair->Name == TK_TEXT_LANGUAGE2 || LanguagePair->Name == TK_TEXT_LANGUAGE3 || + LanguagePair->Name == TK_TEXT_LANGUAGE8) { + FixIllegalChars(data); + } + SetText(data); + return true; + } + } - return cStrings::UnderstandToken(token, data ); -// } + return cStrings::UnderstandToken(token, data); + // } } - - -cStringPackage::cStringPackage(const char *in, unsigned char initID, char *initDescription, char *initReference) -{ +cStringPackage::cStringPackage(const char *in, unsigned char initID, char *initDescription, char *initReference) { ID = initID; Registration = 0; name = in; @@ -778,58 +667,48 @@ cStringPackage::cStringPackage(const char *in, unsigned char initID, char *initD SetReference(initReference); } -cStringPackage::~cStringPackage(void) -{ - if (Reference) - { +cStringPackage::~cStringPackage(void) { + if (Reference) { delete Reference; Reference = NULL; } } -void cStringPackage::SetReference(char *newReference) -{ - if (Reference) - { +void cStringPackage::SetReference(char *newReference) { + if (Reference) { delete Reference; Reference = NULL; } - if (!newReference || !newReference[0]) - { + if (!newReference || !newReference[0]) { return; } - Reference = new char[strlen(newReference)+1]; + Reference = new char[strlen(newReference) + 1]; strcpy(Reference, newReference); } +bool cStringPackage::UnderstandToken(char *&Data, int &Size, int token, char *data) { + switch (token) { + case TK_ID: + ID = (unsigned char)atol(data); + return true; -bool cStringPackage::UnderstandToken(char *&Data, int &Size, int token, char *data ) -{ - switch(token) - { - case TK_ID: - ID = (unsigned char)atol(data); - return true; + case TK_CONFIG: + return true; - case TK_CONFIG: - return true; - - case TK_REFERENCE: - SetReference(data); - return true; + case TK_REFERENCE: + SetReference(data); + return true; } - if (token == TK_INVALID) - { + if (token == TK_INVALID) { return false; } return true; } - #if 0 bool cStringPackage::Load(char *FileName ) { @@ -859,121 +738,95 @@ bool cStringPackage::Load(char *FileName ) } #endif -bool cStringPackage::Load(char *Data, int &Size ) -{ - char *token_data; - int token; +bool cStringPackage::Load(char *Data, int &Size) { + char *token_data; + int token; GetLine(Data, Size, token, token_data); - if (token != TK_VERSION || atol(token_data) != STRIP_VERSION) - { + if (token != TK_VERSION || atol(token_data) != STRIP_VERSION) { return false; } GetLine(Data, Size, token, token_data); - while (UnderstandToken(Data, Size, token, token_data) ) - { + while (UnderstandToken(Data, Size, token, token_data)) { GetLine(Data, Size, token, token_data); } return true; } +cStringPackageSingle::cStringPackageSingle(const char *in, unsigned char initID, char *initReference) : cStringPackage(in, initID, initReference) {} +cStringPackageSingle::~cStringPackageSingle(void) { ReferenceTable.clear(); } -cStringPackageSingle::cStringPackageSingle(const char *in, unsigned char initID, char *initReference) -:cStringPackage(in, initID, initReference) -{ -} - -cStringPackageSingle::~cStringPackageSingle(void) -{ - ReferenceTable.clear(); -} - -cStringsSingle *cStringPackageSingle::FindString(char *ReferenceLookup) -{ - int index; +cStringsSingle *cStringPackageSingle::FindString(char *ReferenceLookup) { + int index; index = FindStringID(ReferenceLookup); - if (index == -1) - { + if (index == -1) { return NULL; } return FindString(index & SP_STRING); } -int cStringPackageSingle::FindStringID(const char *ReferenceLookup) -{ - std::map::iterator i; - int size; +int cStringPackageSingle::FindStringID(const char *ReferenceLookup) { + std::map::iterator i; + int size; - if (!Reference) - { + if (!Reference) { return -1; } size = strlen(Reference); - if ((int)strlen(ReferenceLookup) < size+2) - { + if ((int)strlen(ReferenceLookup) < size + 2) { return -1; } - if (Q_stricmpn(ReferenceLookup, Reference, size)) - { + if (Q_stricmpn(ReferenceLookup, Reference, size)) { return -1; } i = ReferenceTable.find(std::string(ReferenceLookup + size + 1)); - if (i != ReferenceTable.end()) - { + if (i != ReferenceTable.end()) { return (*i).second; } return -1; } -bool cStringPackageSingle::UnderstandToken(char *&Data, int &Size, int token, char *data ) -{ - int count, i, pos; - char *ReferenceLookup; +bool cStringPackageSingle::UnderstandToken(char *&Data, int &Size, int token, char *data) { + int count, i, pos; + char *ReferenceLookup; - switch(token) - { - case TK_COUNT: - count = atol(data); - - for(i=0;i JK2SP_ListByName; -std::map JK2SP_ListByID; - +std::map JK2SP_ListByName; +std::map JK2SP_ListByID; // Registration /************************************************************************************************ @@ -987,14 +840,12 @@ std::map JK2SP_ListByID; * success/fail * ************************************************************************************************/ -qboolean JK2SP_Register(const char *inPackage, unsigned char Registration) -{ - char *buffer; - char Package[MAX_QPATH]; - int size; - cStringPackageSingle *new_sp; - std::map::iterator i; - +qboolean JK2SP_Register(const char *inPackage, unsigned char Registration) { + char *buffer; + char Package[MAX_QPATH]; + int size; + cStringPackageSingle *new_sp; + std::map::iterator i; assert(JK2SP_ListByName.size() == JK2SP_ListByID.size()); @@ -1002,18 +853,13 @@ qboolean JK2SP_Register(const char *inPackage, unsigned char Registration) Q_strupr(Package); i = JK2SP_ListByName.find(Package); - if (i != JK2SP_ListByName.end()) - { + if (i != JK2SP_ListByName.end()) { new_sp = (*i).second; - } - else - { + } else { size = FS_ReadFile(va("strip/%s.sp", Package), (void **)&buffer); - if (size == -1) - { - if ( Registration & SP_REGISTER_REQUIRED ) - { + if (size == -1) { + if (Registration & SP_REGISTER_REQUIRED) { Com_Error(ERR_FATAL, "Could not open string package '%s'", Package); } return qfalse; @@ -1021,15 +867,12 @@ qboolean JK2SP_Register(const char *inPackage, unsigned char Registration) // Create the new string package new_sp = new cStringPackageSingle(Package); - new_sp->Load(buffer, size ); + new_sp->Load(buffer, size); FS_FreeFile(buffer); - if (Registration & SP_REGISTER_CLIENT) - { + if (Registration & SP_REGISTER_CLIENT) { Com_DPrintf(S_COLOR_YELLOW "JK2SP_Register: Registered client string package '%s' with ID %02x\n", Package, (int)new_sp->GetID()); - } - else - { + } else { Com_DPrintf(S_COLOR_YELLOW "JK2SP_Register: Registered string package '%s' with ID %02x\n", Package, (int)new_sp->GetID()); } @@ -1041,26 +884,22 @@ qboolean JK2SP_Register(const char *inPackage, unsigned char Registration) // Or in the new registration data new_sp->Register(Registration); -// return new_sp; + // return new_sp; return qtrue; } - // Unload all packages with the relevant registration bits -void JK2SP_Unload(unsigned char Registration) -{ - std::map::iterator i, next; - std::map::iterator id; +void JK2SP_Unload(unsigned char Registration) { + std::map::iterator i, next; + std::map::iterator id; assert(JK2SP_ListByName.size() == JK2SP_ListByID.size()); - for(i = JK2SP_ListByName.begin(); i != JK2SP_ListByName.end(); i = next) - { + for (i = JK2SP_ListByName.begin(); i != JK2SP_ListByName.end(); i = next) { next = i; ++next; - if ((*i).second->UnRegister(Registration)) - { + if ((*i).second->UnRegister(Registration)) { Com_DPrintf(S_COLOR_YELLOW "JK2SP_UnRegister: Package '%s' with ID %02x\n", (*i).first.c_str(), (int)(*i).second->GetID()); id = JK2SP_ListByID.find((*i).second->GetID()); @@ -1069,24 +908,20 @@ void JK2SP_Unload(unsigned char Registration) JK2SP_ListByName.erase(i); } } - } // Direct string functions -int JK2SP_GetStringID(const char *inReference) -{ - std::map::iterator i; - int ID; +int JK2SP_GetStringID(const char *inReference) { + std::map::iterator i; + int ID; char Reference[MAX_QPATH]; Q_strncpyz(Reference, inReference, MAX_QPATH); Q_strupr(Reference); - for(i = JK2SP_ListByID.begin(); i != JK2SP_ListByID.end(); ++i) - { + for (i = JK2SP_ListByID.begin(); i != JK2SP_ListByID.end(); ++i) { ID = (*i).second->FindStringID(Reference); - if (ID >= 0) - { + if (ID >= 0) { ID |= ((int)(*i).first) << 8; return ID; } @@ -1104,15 +939,13 @@ int JK2SP_GetStringID(const char *inReference) * pointer to desired String Package * ************************************************************************************************/ -cStringsSingle *JK2SP_GetString(unsigned short ID) -{ - cStringPackageSingle *sp; - cStringsSingle *string; - std::map::iterator i; +cStringsSingle *JK2SP_GetString(unsigned short ID) { + cStringPackageSingle *sp; + cStringsSingle *string; + std::map::iterator i; i = JK2SP_ListByID.find(SP_GET_PACKAGE(ID)); - if (i == JK2SP_ListByID.end()) - { + if (i == JK2SP_ListByID.end()) { Com_Error(ERR_DROP, "String package not registered for ID %04x", ID); return NULL; } @@ -1120,20 +953,17 @@ cStringsSingle *JK2SP_GetString(unsigned short ID) sp = (*i).second; string = sp->FindString(ID & SP_STRING); - if (!string) - { + if (!string) { Com_Error(ERR_DROP, "String ID %04x not defined\n", ID); } return string; } -cStringsSingle *JK2SP_GetString(const char *Reference) -{ - int index; +cStringsSingle *JK2SP_GetString(const char *Reference) { + int index; index = JK2SP_GetStringID(Reference); - if (index == -1) - { + if (index == -1) { return NULL; } @@ -1143,14 +973,12 @@ cStringsSingle *JK2SP_GetString(const char *Reference) #ifdef _DEBUG // needed to add this to query which SP references the menus used -Ste. // -const char *JK2SP_GetReferenceText(unsigned short ID, const char *&psPackageName, const char *&psPackageReference, const char *&psText) -{ +const char *JK2SP_GetReferenceText(unsigned short ID, const char *&psPackageName, const char *&psPackageReference, const char *&psText) { cStringPackageSingle *sp; - std::map::iterator i; + std::map::iterator i; i = JK2SP_ListByID.find(SP_GET_PACKAGE(ID)); - if (i == JK2SP_ListByID.end()) - { + if (i == JK2SP_ListByID.end()) { assert(0); return NULL; } @@ -1160,94 +988,82 @@ const char *JK2SP_GetReferenceText(unsigned short ID, const char *&psPackageName sp = (*i).second; string = sp->FindString(ID & SP_STRING); - if (!string) - { + if (!string) { assert(0); return NULL; } psPackageName = sp->GetName(); - psPackageReference = sp->GetReference(); + psPackageReference = sp->GetReference(); psText = string->GetText(); if (!psText) - psText = ""; + psText = ""; return string->GetReference(); } #endif -const char *JK2SP_GetStringText(unsigned short ID) -{ - cStringsSingle *string; - const char *value; +const char *JK2SP_GetStringText(unsigned short ID) { + cStringsSingle *string; + const char *value; string = JK2SP_GetString(ID); value = string->GetText(); - if (!value) - { + if (!value) { value = ""; } return value; } -const char *JK2SP_GetStringTextString(const char *Reference) -{ - int index; +const char *JK2SP_GetStringTextString(const char *Reference) { + int index; index = JK2SP_GetStringID(Reference); - if (index == -1) - { + if (index == -1) { return ""; } return JK2SP_GetStringText(index); } - -static void JK2SP_UpdateLanguage(void) -{ - std::map::iterator it; - std::list sps; - std::list::iterator spit; +static void JK2SP_UpdateLanguage(void) { + std::map::iterator it; + std::list sps; + std::list::iterator spit; // Grab all SP ids - for(it = JK2SP_ListByID.begin(); it != JK2SP_ListByID.end(); ++it) - { + for (it = JK2SP_ListByID.begin(); it != JK2SP_ListByID.end(); ++it) { sps.push_back(cStringPackageID((*it).second->GetName(), (*it).second->GetRegistration())); } // Clear out all pointers JK2SP_Unload(SP_REGISTER_CLIENT | SP_REGISTER_SERVER | SP_REGISTER_MENU | SP_REGISTER_REQUIRED); // Reinitialise with new language - for(spit = sps.begin(); spit != sps.end(); ++spit) - { + for (spit = sps.begin(); spit != sps.end(); ++spit) { JK2SP_Register((*spit).GetName(), (*spit).GetReg()); } sps.clear(); } -void JK2SP_Init(void) -{ +void JK2SP_Init(void) { sp_language = Cvar_Get("sp_language", va("%d", SP_LANGUAGE_ENGLISH), CVAR_ARCHIVE | CVAR_NORESTART); - sp_show_strip = Cvar_Get ("sp_show_strip", "0", 0); // don't switch this on!!!!!!, test only (apparently) - sp_leet = Cvar_Get ("sp_leet", "0", CVAR_ROM); // do NOT leave this on in final product!!!! (only works when == 42 anyway ;-) + sp_show_strip = Cvar_Get("sp_show_strip", "0", 0); // don't switch this on!!!!!!, test only (apparently) + sp_leet = Cvar_Get("sp_leet", "0", CVAR_ROM); // do NOT leave this on in final product!!!! (only works when == 42 anyway ;-) -// Cvar_Set("sp_language", va("%d", SP_LANGUAGE_JAPANESE)); // stetest, do NOT leave in + // Cvar_Set("sp_language", va("%d", SP_LANGUAGE_JAPANESE)); // stetest, do NOT leave in JK2SP_UpdateLanguage(); sp_language->modified = qfalse; - JK2SP_Register("con_text", SP_REGISTER_REQUIRED); //reference is CON_TEXT + JK2SP_Register("con_text", SP_REGISTER_REQUIRED); // reference is CON_TEXT } // called in Com_Frame, so don't take up any time! (can also be called during dedicated) // -void JK2SP_CheckForLanguageUpdates(void) -{ - if (sp_language && sp_language->modified) - { - JK2SP_UpdateLanguage(); // force language package to reload +void JK2SP_CheckForLanguageUpdates(void) { + if (sp_language && sp_language->modified) { + JK2SP_UpdateLanguage(); // force language package to reload sp_language->modified = qfalse; } } diff --git a/code/qcommon/tri_coll_test.cpp b/code/qcommon/tri_coll_test.cpp index b9a5bb9d23..cb8967c200 100644 --- a/code/qcommon/tri_coll_test.cpp +++ b/code/qcommon/tri_coll_test.cpp @@ -33,293 +33,270 @@ #include "tri_coll_test.h" /* if USE_EPSILON_TEST is true then we do a check: - if |dv|b) \ - { \ - float c; \ - c=a; \ - a=b; \ - b=c; \ - } - -#define ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1) \ - isect0=VV0+(VV1-VV0)*D0/(D0-D1); \ - isect1=VV0+(VV2-VV0)*D0/(D0-D2); - - -#define COMPUTE_INTERVALS(VV0,VV1,VV2,D0,D1,D2,D0D1,D0D2,isect0,isect1) \ - if(D0D1>0.0f) \ - { \ - /* here we know that D0D2<=0.0 */ \ - /* that is D0, D1 are on the same side, D2 on the other or on the plane */ \ - ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \ - } \ - else if(D0D2>0.0f) \ - { \ - /* here we know that d0d1<=0.0 */ \ - ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \ - } \ - else if(D1*D2>0.0f || D0!=0.0f) \ - { \ - /* here we know that d0d1<=0.0 or that D0!=0.0 */ \ - ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1); \ - } \ - else if(D1!=0.0f) \ - { \ - ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \ - } \ - else if(D2!=0.0f) \ - { \ - ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \ - } \ - else \ - { \ - /* triangles are coplanar */ \ - return coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2); \ - } - +#define SORT(a, b) \ + if (a > b) { \ + float c; \ + c = a; \ + a = b; \ + b = c; \ + } +#define ISECT(VV0, VV1, VV2, D0, D1, D2, isect0, isect1) \ + isect0 = VV0 + (VV1 - VV0) * D0 / (D0 - D1); \ + isect1 = VV0 + (VV2 - VV0) * D0 / (D0 - D2); + +#define COMPUTE_INTERVALS(VV0, VV1, VV2, D0, D1, D2, D0D1, D0D2, isect0, isect1) \ + if (D0D1 > 0.0f) { \ + /* here we know that D0D2<=0.0 */ \ + /* that is D0, D1 are on the same side, D2 on the other or on the plane */ \ + ISECT(VV2, VV0, VV1, D2, D0, D1, isect0, isect1); \ + } else if (D0D2 > 0.0f) { \ + /* here we know that d0d1<=0.0 */ \ + ISECT(VV1, VV0, VV2, D1, D0, D2, isect0, isect1); \ + } else if (D1 * D2 > 0.0f || D0 != 0.0f) { \ + /* here we know that d0d1<=0.0 or that D0!=0.0 */ \ + ISECT(VV0, VV1, VV2, D0, D1, D2, isect0, isect1); \ + } else if (D1 != 0.0f) { \ + ISECT(VV1, VV0, VV2, D1, D0, D2, isect0, isect1); \ + } else if (D2 != 0.0f) { \ + ISECT(VV2, VV0, VV1, D2, D0, D1, isect0, isect1); \ + } else { \ + /* triangles are coplanar */ \ + return coplanar_tri_tri(N1, V0, V1, V2, U0, U1, U2); \ + } /* this edge to edge test is based on Franlin Antonio's gem: "Faster Line Segment Intersection", in Graphics Gems III, pp. 199-202 */ -#define EDGE_EDGE_TEST(V0,U0,U1) \ - Bx=U0[i0]-U1[i0]; \ - By=U0[i1]-U1[i1]; \ - Cx=V0[i0]-U0[i0]; \ - Cy=V0[i1]-U0[i1]; \ - f=Ay*Bx-Ax*By; \ - d=By*Cx-Bx*Cy; \ - if((f>0 && d>=0 && d<=f) || (f<0 && d<=0 && d>=f)) \ - { \ - e=Ax*Cy-Ay*Cx; \ - if(f>0) \ - { \ - if(e>=0 && e<=f) return qtrue; \ - } \ - else \ - { \ - if(e<=0 && e>=f) return qtrue; \ - } \ - } - -#define EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2) \ -{ \ - float Ax,Ay,Bx,By,Cx,Cy,e,d,f; \ - Ax=V1[i0]-V0[i0]; \ - Ay=V1[i1]-V0[i1]; \ - /* test edge U0,U1 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U0,U1); \ - /* test edge U1,U2 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U1,U2); \ - /* test edge U2,U1 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U2,U0); \ -} +#define EDGE_EDGE_TEST(V0, U0, U1) \ + Bx = U0[i0] - U1[i0]; \ + By = U0[i1] - U1[i1]; \ + Cx = V0[i0] - U0[i0]; \ + Cy = V0[i1] - U0[i1]; \ + f = Ay * Bx - Ax * By; \ + d = By * Cx - Bx * Cy; \ + if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) { \ + e = Ax * Cy - Ay * Cx; \ + if (f > 0) { \ + if (e >= 0 && e <= f) \ + return qtrue; \ + } else { \ + if (e <= 0 && e >= f) \ + return qtrue; \ + } \ + } -#define POINT_IN_TRI(V0,U0,U1,U2) \ -{ \ - float a,b,c,d0,d1,d2; \ - /* is T1 completly inside T2? */ \ - /* check if V0 is inside tri(U0,U1,U2) */ \ - a=U1[i1]-U0[i1]; \ - b=-(U1[i0]-U0[i0]); \ - c=-a*U0[i0]-b*U0[i1]; \ - d0=a*V0[i0]+b*V0[i1]+c; \ - \ - a=U2[i1]-U1[i1]; \ - b=-(U2[i0]-U1[i0]); \ - c=-a*U1[i0]-b*U1[i1]; \ - d1=a*V0[i0]+b*V0[i1]+c; \ - \ - a=U0[i1]-U2[i1]; \ - b=-(U0[i0]-U2[i0]); \ - c=-a*U2[i0]-b*U2[i1]; \ - d2=a*V0[i0]+b*V0[i1]+c; \ - if(d0*d1>0.0) \ - { \ - if(d0*d2>0.0) return qtrue; \ - } \ -} +#define EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2) \ + { \ + float Ax, Ay, Bx, By, Cx, Cy, e, d, f; \ + Ax = V1[i0] - V0[i0]; \ + Ay = V1[i1] - V0[i1]; \ + /* test edge U0,U1 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U0, U1); \ + /* test edge U1,U2 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U1, U2); \ + /* test edge U2,U1 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U2, U0); \ + } -qboolean coplanar_tri_tri(vec3_t N,vec3_t V0,vec3_t V1,vec3_t V2, - vec3_t U0,vec3_t U1,vec3_t U2) -{ - vec3_t A; - short i0,i1; - /* first project onto an axis-aligned plane, that maximizes the area */ - /* of the triangles, compute indices: i0,i1. */ - A[0]=fabs(N[0]); - A[1]=fabs(N[1]); - A[2]=fabs(N[2]); - if(A[0]>A[1]) - { - if(A[0]>A[2]) - { - i0=1; /* A[0] is greatest */ - i1=2; - } - else - { - i0=0; /* A[2] is greatest */ - i1=1; - } - } - else /* A[0]<=A[1] */ - { - if(A[2]>A[1]) - { - i0=0; /* A[2] is greatest */ - i1=1; - } - else - { - i0=0; /* A[1] is greatest */ - i1=2; - } - } - - /* test all edges of triangle 1 against the edges of triangle 2 */ - EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2); - EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2); - EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2); - - /* finally, test if tri1 is totally contained in tri2 or vice versa */ - POINT_IN_TRI(V0,U0,U1,U2); - POINT_IN_TRI(U0,V0,V1,V2); - - return qfalse; +#define POINT_IN_TRI(V0, U0, U1, U2) \ + { \ + float a, b, c, d0, d1, d2; \ + /* is T1 completly inside T2? */ \ + /* check if V0 is inside tri(U0,U1,U2) */ \ + a = U1[i1] - U0[i1]; \ + b = -(U1[i0] - U0[i0]); \ + c = -a * U0[i0] - b * U0[i1]; \ + d0 = a * V0[i0] + b * V0[i1] + c; \ + \ + a = U2[i1] - U1[i1]; \ + b = -(U2[i0] - U1[i0]); \ + c = -a * U1[i0] - b * U1[i1]; \ + d1 = a * V0[i0] + b * V0[i1] + c; \ + \ + a = U0[i1] - U2[i1]; \ + b = -(U0[i0] - U2[i0]); \ + c = -a * U2[i0] - b * U2[i1]; \ + d2 = a * V0[i0] + b * V0[i1] + c; \ + if (d0 * d1 > 0.0) { \ + if (d0 * d2 > 0.0) \ + return qtrue; \ + } \ + } + +qboolean coplanar_tri_tri(vec3_t N, vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2) { + vec3_t A; + short i0, i1; + /* first project onto an axis-aligned plane, that maximizes the area */ + /* of the triangles, compute indices: i0,i1. */ + A[0] = fabs(N[0]); + A[1] = fabs(N[1]); + A[2] = fabs(N[2]); + if (A[0] > A[1]) { + if (A[0] > A[2]) { + i0 = 1; /* A[0] is greatest */ + i1 = 2; + } else { + i0 = 0; /* A[2] is greatest */ + i1 = 1; + } + } else /* A[0]<=A[1] */ + { + if (A[2] > A[1]) { + i0 = 0; /* A[2] is greatest */ + i1 = 1; + } else { + i0 = 0; /* A[1] is greatest */ + i1 = 2; + } + } + + /* test all edges of triangle 1 against the edges of triangle 2 */ + EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2); + EDGE_AGAINST_TRI_EDGES(V1, V2, U0, U1, U2); + EDGE_AGAINST_TRI_EDGES(V2, V0, U0, U1, U2); + + /* finally, test if tri1 is totally contained in tri2 or vice versa */ + POINT_IN_TRI(V0, U0, U1, U2); + POINT_IN_TRI(U0, V0, V1, V2); + + return qfalse; } -qboolean tri_tri_intersect(vec3_t V0,vec3_t V1,vec3_t V2, - vec3_t U0,vec3_t U1,vec3_t U2) -{ - vec3_t E1,E2; - vec3_t N1,N2; - float d1,d2; - float du0,du1,du2,dv0,dv1,dv2; - vec3_t D; - float isect1[2], isect2[2]; - float du0du1,du0du2,dv0dv1,dv0dv2; - short index; - float vp0,vp1,vp2; - float up0,up1,up2; - float b,c,max; - - /* compute plane equation of triangle(V0,V1,V2) */ - SUB(E1,V1,V0); - SUB(E2,V2,V0); - CROSS(N1,E1,E2); - d1=-DOT(N1,V0); - /* plane equation 1: N1.X+d1=0 */ - - /* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/ - du0=DOT(N1,U0)+d1; - du1=DOT(N1,U1)+d1; - du2=DOT(N1,U2)+d1; - - /* coplanarity robustness check */ +qboolean tri_tri_intersect(vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2) { + vec3_t E1, E2; + vec3_t N1, N2; + float d1, d2; + float du0, du1, du2, dv0, dv1, dv2; + vec3_t D; + float isect1[2], isect2[2]; + float du0du1, du0du2, dv0dv1, dv0dv2; + short index; + float vp0, vp1, vp2; + float up0, up1, up2; + float b, c, max; + + /* compute plane equation of triangle(V0,V1,V2) */ + SUB(E1, V1, V0); + SUB(E2, V2, V0); + CROSS(N1, E1, E2); + d1 = -DOT(N1, V0); + /* plane equation 1: N1.X+d1=0 */ + + /* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/ + du0 = DOT(N1, U0) + d1; + du1 = DOT(N1, U1) + d1; + du2 = DOT(N1, U2) + d1; + + /* coplanarity robustness check */ #if USE_EPSILON_TEST - if(fabs(du0)0.0f && du0du2>0.0f) /* same sign on all of them + not equal 0 ? */ - return qfalse; /* no intersection occurs */ + if (du0du1 > 0.0f && du0du2 > 0.0f) /* same sign on all of them + not equal 0 ? */ + return qfalse; /* no intersection occurs */ - /* compute plane of triangle (U0,U1,U2) */ - SUB(E1,U1,U0); - SUB(E2,U2,U0); - CROSS(N2,E1,E2); - d2=-DOT(N2,U0); - /* plane equation 2: N2.X+d2=0 */ + /* compute plane of triangle (U0,U1,U2) */ + SUB(E1, U1, U0); + SUB(E2, U2, U0); + CROSS(N2, E1, E2); + d2 = -DOT(N2, U0); + /* plane equation 2: N2.X+d2=0 */ - /* put V0,V1,V2 into plane equation 2 */ - dv0=DOT(N2,V0)+d2; - dv1=DOT(N2,V1)+d2; - dv2=DOT(N2,V2)+d2; + /* put V0,V1,V2 into plane equation 2 */ + dv0 = DOT(N2, V0) + d2; + dv1 = DOT(N2, V1) + d2; + dv2 = DOT(N2, V2) + d2; #if USE_EPSILON_TEST - if(fabs(dv0)0.0f && dv0dv2>0.0f) /* same sign on all of them + not equal 0 ? */ - return qfalse; /* no intersection occurs */ + if (dv0dv1 > 0.0f && dv0dv2 > 0.0f) /* same sign on all of them + not equal 0 ? */ + return qfalse; /* no intersection occurs */ - /* compute direction of intersection line */ - CROSS(D,N1,N2); + /* compute direction of intersection line */ + CROSS(D, N1, N2); - /* compute and index to the largest component of D */ - max=fabs(D[0]); - index=0; - b=fabs(D[1]); - c=fabs(D[2]); - if(b>max) max=b,index=1; - if(c>max) max=c,index=2; + /* compute and index to the largest component of D */ + max = fabs(D[0]); + index = 0; + b = fabs(D[1]); + c = fabs(D[2]); + if (b > max) + max = b, index = 1; + if (c > max) + max = c, index = 2; - /* this is the simplified projection onto L*/ - vp0=V0[index]; - vp1=V1[index]; - vp2=V2[index]; + /* this is the simplified projection onto L*/ + vp0 = V0[index]; + vp1 = V1[index]; + vp2 = V2[index]; - up0=U0[index]; - up1=U1[index]; - up2=U2[index]; + up0 = U0[index]; + up1 = U1[index]; + up2 = U2[index]; - /* compute interval for triangle 1 */ - COMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,isect1[0],isect1[1]); + /* compute interval for triangle 1 */ + COMPUTE_INTERVALS(vp0, vp1, vp2, dv0, dv1, dv2, dv0dv1, dv0dv2, isect1[0], isect1[1]); - /* compute interval for triangle 2 */ - COMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,isect2[0],isect2[1]); + /* compute interval for triangle 2 */ + COMPUTE_INTERVALS(up0, up1, up2, du0, du1, du2, du0du1, du0du2, isect2[0], isect2[1]); - SORT(isect1[0],isect1[1]); - SORT(isect2[0],isect2[1]); + SORT(isect1[0], isect1[1]); + SORT(isect2[0], isect2[1]); - if(isect1[1] 0.001f ) - { - float s = -( (v2v2*DotProduct( v1, start_dif )) - (v1v2*DotProduct( v2, start_dif )) ) / denom; - float t = ( (v1v1*DotProduct( v2, start_dif )) - (v1v2*DotProduct( v1, start_dif )) ) / denom; + // if denom is small, then skip all this and jump to the section marked below + if (fabs(denom) > 0.001f) { + float s = -((v2v2 * DotProduct(v1, start_dif)) - (v1v2 * DotProduct(v2, start_dif))) / denom; + float t = ((v1v1 * DotProduct(v2, start_dif)) - (v1v2 * DotProduct(v1, start_dif))) / denom; qboolean done = qtrue; - if ( s < 0 ) - { + if (s < 0) { done = qfalse; - s = 0;// and see note below + s = 0; // and see note below } - if ( s > 1 ) - { + if (s > 1) { done = qfalse; - s = 1;// and see note below + s = 1; // and see note below } - if ( t < 0 ) - { + if (t < 0) { done = qfalse; - t = 0;// and see note below + t = 0; // and see note below } - if ( t > 1 ) - { + if (t > 1) { done = qfalse; - t = 1;// and see note below + t = 1; // and see note below } - //vec close_pnt1 = start1 + s * v1 - VectorMA( start1, s, v1, close_pnt1 ); - //vec close_pnt2 = start2 + t * v2 - VectorMA( start2, t, v2, close_pnt2 ); + // vec close_pnt1 = start1 + s * v1 + VectorMA(start1, s, v1, close_pnt1); + // vec close_pnt2 = start2 + t * v2 + VectorMA(start2, t, v2, close_pnt2); - current_dist = Distance( close_pnt1, close_pnt2 ); - //now, if none of those if's fired, you are done. - if ( done ) - { + current_dist = Distance(close_pnt1, close_pnt2); + // now, if none of those if's fired, you are done. + if (done) { return current_dist; } - //If they did fire, then we need to do some additional tests. + // If they did fire, then we need to do some additional tests. - //What we are gonna do is see if we can find a shorter distance than the above - //involving the endpoints. - } - else - { + // What we are gonna do is see if we can find a shorter distance than the above + // involving the endpoints. + } else { //******start here for paralell lines with current_dist = infinity**** current_dist = Q3_INFINITE; } - //test 2 close_pnts first + // test 2 close_pnts first /* G_FindClosestPointOnLineSegment( start1, end1, close_pnt2, new_pnt ); new_dist = Distance( close_pnt2, new_pnt ); @@ -441,74 +409,66 @@ float ShortestLineSegBewteen2LineSegs( vec3_t start1, vec3_t end1, vec3_t start2 current_dist = new_dist; } */ - //test all the endpoints - new_dist = Distance( start1, start2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + // test all the endpoints + new_dist = Distance(start1, start2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( start1, end2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + new_dist = Distance(start1, end2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( end1, start2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + new_dist = Distance(end1, start2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( end1, end2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + new_dist = Distance(end1, end2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } - //Then we have 4 more point / segment tests + // Then we have 4 more point / segment tests - G_FindClosestPointOnLineSegment( start2, end2, start1, new_pnt ); - new_dist = Distance( start1, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( new_pnt, close_pnt2 ); + G_FindClosestPointOnLineSegment(start2, end2, start1, new_pnt); + new_dist = Distance(start1, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(new_pnt, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start2, end2, end1, new_pnt ); - new_dist = Distance( end1, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( new_pnt, close_pnt2 ); + G_FindClosestPointOnLineSegment(start2, end2, end1, new_pnt); + new_dist = Distance(end1, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(new_pnt, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start1, end1, start2, new_pnt ); - new_dist = Distance( start2, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( new_pnt, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + G_FindClosestPointOnLineSegment(start1, end1, start2, new_pnt); + new_dist = Distance(start2, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(new_pnt, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start1, end1, end2, new_pnt ); - new_dist = Distance( end2, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( new_pnt, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + G_FindClosestPointOnLineSegment(start1, end1, end2, new_pnt); + new_dist = Distance(end2, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(new_pnt, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } diff --git a/code/qcommon/z_memman_pc.cpp b/code/qcommon/z_memman_pc.cpp index d0051ed635..055a774505 100644 --- a/code/qcommon/z_memman_pc.cpp +++ b/code/qcommon/z_memman_pc.cpp @@ -27,7 +27,7 @@ along with this program; if not, see . #ifdef DEBUG_ZONE_ALLOCS #include "sstring.h" -int giZoneSnaphotNum=0; +int giZoneSnaphotNum = 0; #define DEBUG_ZONE_ALLOC_OPTIONAL_LABEL_SIZE 256 typedef sstring sDebugString_t; #endif @@ -36,130 +36,109 @@ static void Z_Details_f(void); // define a string table of all mem tags... // -#ifdef TAGDEF // itu? +#ifdef TAGDEF // itu? #undef TAGDEF #endif #define TAGDEF(blah) #blah -static const char *psTagStrings[TAG_COUNT+1]= // +1 because TAG_COUNT will itself become a string here. Oh well. -{ - #include "tags.h" +static const char *psTagStrings[TAG_COUNT + 1] = // +1 because TAG_COUNT will itself become a string here. Oh well. + { +#include "tags.h" }; // This handles zone memory allocation. // It is a wrapper around malloc with a tag id and a magic number at the start -#define ZONE_MAGIC 0x21436587 +#define ZONE_MAGIC 0x21436587 // if you change ANYTHING in this structure, be sure to update the tables below using DEF_STATIC... // -typedef struct zoneHeader_s -{ - int iMagic; - memtag_t eTag; - int iSize; -struct zoneHeader_s *pNext; -struct zoneHeader_s *pPrev; +typedef struct zoneHeader_s { + int iMagic; + memtag_t eTag; + int iSize; + struct zoneHeader_s *pNext; + struct zoneHeader_s *pPrev; #ifdef DEBUG_ZONE_ALLOCS - char sSrcFileBaseName[MAX_QPATH]; - int iSrcFileLineNum; - char sOptionalLabel[DEBUG_ZONE_ALLOC_OPTIONAL_LABEL_SIZE]; - int iSnapshotNumber; + char sSrcFileBaseName[MAX_QPATH]; + int iSrcFileLineNum; + char sOptionalLabel[DEBUG_ZONE_ALLOC_OPTIONAL_LABEL_SIZE]; + int iSnapshotNumber; #endif } zoneHeader_t; -typedef struct -{ +typedef struct { int iMagic; } zoneTail_t; -static inline zoneTail_t *ZoneTailFromHeader(zoneHeader_t *pHeader) -{ - return (zoneTail_t*) ( (char*)pHeader + sizeof(*pHeader) + pHeader->iSize ); -} +static inline zoneTail_t *ZoneTailFromHeader(zoneHeader_t *pHeader) { return (zoneTail_t *)((char *)pHeader + sizeof(*pHeader) + pHeader->iSize); } #ifdef DETAILED_ZONE_DEBUG_CODE -std::map mapAllocatedZones; +std::map mapAllocatedZones; #endif - -typedef struct zoneStats_s -{ - int iCount; - int iCurrent; - int iPeak; +typedef struct zoneStats_s { + int iCount; + int iCurrent; + int iPeak; // I'm keeping these updated on the fly, since it's quicker for cache-pool // purposes rather than recalculating each time... // - int iSizesPerTag [TAG_COUNT]; - int iCountsPerTag[TAG_COUNT]; + int iSizesPerTag[TAG_COUNT]; + int iCountsPerTag[TAG_COUNT]; } zoneStats_t; -typedef struct zone_s -{ - zoneStats_t Stats; - zoneHeader_t Header; +typedef struct zone_s { + zoneStats_t Stats; + zoneHeader_t Header; } zone_t; -cvar_t *com_validateZone; - -zone_t TheZone = {}; - - +cvar_t *com_validateZone; +zone_t TheZone = {}; // Scans through the linked list of mallocs and makes sure no data has been overwritten -int Z_Validate(void) -{ - int ret=0; - if(!com_validateZone || !com_validateZone->integer) - { +int Z_Validate(void) { + int ret = 0; + if (!com_validateZone || !com_validateZone->integer) { return ret; } zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - #ifdef DETAILED_ZONE_DEBUG_CODE + while (pMemory) { +#ifdef DETAILED_ZONE_DEBUG_CODE // this won't happen here, but wtf? - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount <= 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount <= 0) { Com_Error(ERR_FATAL, "Z_Validate(): Bad block allocation count!"); return ret; } - #endif +#endif - if(pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Validate(): Corrupt zone header!"); return ret; } // this block of code is intended to make sure all of the data is paged in - if (pMemory->eTag != TAG_IMAGE_T - && pMemory->eTag != TAG_MODEL_MD3 - && pMemory->eTag != TAG_MODEL_GLM - && pMemory->eTag != TAG_MODEL_GLA ) //don't bother with disk caches as they've already been hit or will be thrown out next + if (pMemory->eTag != TAG_IMAGE_T && pMemory->eTag != TAG_MODEL_MD3 && pMemory->eTag != TAG_MODEL_GLM && + pMemory->eTag != TAG_MODEL_GLA) // don't bother with disk caches as they've already been hit or will be thrown out next { unsigned char *memstart = (unsigned char *)pMemory; int totalSize = pMemory->iSize; - while (totalSize > 4096) - { + while (totalSize > 4096) { memstart += 4096; ret += (int)(*memstart); // this fools the optimizer totalSize -= 4096; } } - - if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) - { + if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Validate(): Corrupt zone tail!"); return ret; } @@ -169,50 +148,38 @@ int Z_Validate(void) return ret; } - - // static mem blocks to reduce a lot of small zone overhead // #pragma pack(push) #pragma pack(1) -typedef struct -{ - zoneHeader_t Header; -// byte mem[0]; - zoneTail_t Tail; +typedef struct { + zoneHeader_t Header; + // byte mem[0]; + zoneTail_t Tail; } StaticZeroMem_t; -typedef struct -{ - zoneHeader_t Header; +typedef struct { + zoneHeader_t Header; byte mem[2]; - zoneTail_t Tail; + zoneTail_t Tail; } StaticMem_t; #pragma pack(pop) -const static StaticZeroMem_t gZeroMalloc = - { {ZONE_MAGIC, TAG_STATIC,0,NULL,NULL},{ZONE_MAGIC}}; +const static StaticZeroMem_t gZeroMalloc = {{ZONE_MAGIC, TAG_STATIC, 0, NULL, NULL}, {ZONE_MAGIC}}; #ifdef DEBUG_ZONE_ALLOCS -#define DEF_STATIC(_char) {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL, "",0,"",0},{_char,'\0'},{ZONE_MAGIC} +#define DEF_STATIC(_char) \ + {ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL, "", 0, "", 0}, {_char, '\0'}, { ZONE_MAGIC } #else -#define DEF_STATIC(_char) {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL },{_char,'\0'},{ZONE_MAGIC} +#define DEF_STATIC(_char) \ + {ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {_char, '\0'}, { ZONE_MAGIC } #endif -const static StaticMem_t gEmptyString = - { DEF_STATIC('\0') }; +const static StaticMem_t gEmptyString = {DEF_STATIC('\0')}; const static StaticMem_t gNumberString[] = { - { DEF_STATIC('0') }, - { DEF_STATIC('1') }, - { DEF_STATIC('2') }, - { DEF_STATIC('3') }, - { DEF_STATIC('4') }, - { DEF_STATIC('5') }, - { DEF_STATIC('6') }, - { DEF_STATIC('7') }, - { DEF_STATIC('8') }, - { DEF_STATIC('9') }, + {DEF_STATIC('0')}, {DEF_STATIC('1')}, {DEF_STATIC('2')}, {DEF_STATIC('3')}, {DEF_STATIC('4')}, + {DEF_STATIC('5')}, {DEF_STATIC('6')}, {DEF_STATIC('7')}, {DEF_STATIC('8')}, {DEF_STATIC('9')}, }; qboolean gbMemFreeupOccured = qfalse; @@ -224,99 +191,86 @@ qboolean gbMemFreeupOccured = qfalse; // (normally I'd call another function for this, but this is supposed to be engine-independent, // so a certain amount of re-invention of the wheel is to be expected...) // -char *_D_Z_Filename_WithoutPath(const char *psFilename) -{ - static char sString[ MAX_QPATH ]; +char *_D_Z_Filename_WithoutPath(const char *psFilename) { + static char sString[MAX_QPATH]; const char *psCopyPos = psFilename; - while (*psFilename) - { + while (*psFilename) { if (*psFilename == PATH_SEP) - psCopyPos = psFilename+1; + psCopyPos = psFilename + 1; psFilename++; } - strcpy(sString,psCopyPos); + strcpy(sString, psCopyPos); return sString; } #endif -#include "../rd-common/tr_public.h" // sorta hack sorta not +#include "../rd-common/tr_public.h" // sorta hack sorta not extern refexport_t re; #ifdef DEBUG_ZONE_ALLOCS -void *_D_Z_Malloc ( int iSize, memtag_t eTag, qboolean bZeroit, const char *psFile, int iLine) +void *_D_Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, const char *psFile, int iLine) #else void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int /*unusedAlign*/) #endif { gbMemFreeupOccured = qfalse; - if (iSize == 0) - { - zoneHeader_t *pMemory = (zoneHeader_t *) &gZeroMalloc; + if (iSize == 0) { + zoneHeader_t *pMemory = (zoneHeader_t *)&gZeroMalloc; return &pMemory[1]; } // Add in tracking info and round to a longword... (ignore longword aligning now we're not using contiguous blocks) // -// int iRealSize = (iSize + sizeof(zoneHeader_t) + sizeof(zoneTail_t) + 3) & 0xfffffffc; + // int iRealSize = (iSize + sizeof(zoneHeader_t) + sizeof(zoneTail_t) + 3) & 0xfffffffc; int iRealSize = (iSize + sizeof(zoneHeader_t) + sizeof(zoneTail_t)); // Allocate a chunk... // zoneHeader_t *pMemory = NULL; - while (pMemory == NULL) - { - if (gbMemFreeupOccured) - { - Sys_Sleep(1000); // sleep for a second, so Windows has a chance to shuffle mem to de-swiss-cheese it + while (pMemory == NULL) { + if (gbMemFreeupOccured) { + Sys_Sleep(1000); // sleep for a second, so Windows has a chance to shuffle mem to de-swiss-cheese it } if (bZeroit) { - pMemory = (zoneHeader_t *) calloc ( iRealSize, 1 ); + pMemory = (zoneHeader_t *)calloc(iRealSize, 1); } else { - pMemory = (zoneHeader_t *) malloc ( iRealSize ); + pMemory = (zoneHeader_t *)malloc(iRealSize); } - if (!pMemory) - { + if (!pMemory) { // new bit, if we fail to malloc memory, try dumping some of the cached stuff that's non-vital and try again... // // ditch the BSP cache... // - if (CM_DeleteCachedMap(qfalse)) - { + if (CM_DeleteCachedMap(qfalse)) { gbMemFreeupOccured = qtrue; - continue; // we've just ditched a whole load of memory, so try again with the malloc + continue; // we've just ditched a whole load of memory, so try again with the malloc } - // ditch any sounds not used on this level... // extern qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel); - if (SND_RegisterAudio_LevelLoadEnd(qtrue)) - { + if (SND_RegisterAudio_LevelLoadEnd(qtrue)) { gbMemFreeupOccured = qtrue; - continue; // we've dropped at least one sound, so try again with the malloc + continue; // we've dropped at least one sound, so try again with the malloc } - // ditch any image_t's (and associated GL texture mem) not used on this level... // - if (re.RegisterImages_LevelLoadEnd()) - { + if (re.RegisterImages_LevelLoadEnd()) { gbMemFreeupOccured = qtrue; - continue; // we've dropped at least one image, so try again with the malloc + continue; // we've dropped at least one image, so try again with the malloc } - // ditch the model-binaries cache... (must be getting desperate here!) // - if (re.RegisterModels_LevelLoadEnd(qtrue)) - { + if (re.RegisterModels_LevelLoadEnd(qtrue)) { gbMemFreeupOccured = qtrue; continue; } @@ -332,18 +286,15 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int /*unusedAlign*/) // eventually or not free up enough and drop through to the final ERR_DROP. No worries... // extern qboolean gbInsideLoadSound; - extern int SND_FreeOldestSound(void); // I had to add a void-arg version of this because of link issues, sigh - if (!gbInsideLoadSound) - { + extern int SND_FreeOldestSound(void); // I had to add a void-arg version of this because of link issues, sigh + if (!gbInsideLoadSound) { int iBytesFreed = SND_FreeOldestSound(); - if (iBytesFreed) - { + if (iBytesFreed) { int iTheseBytesFreed = 0; - while ( (iTheseBytesFreed = SND_FreeOldestSound()) != 0) - { + while ((iTheseBytesFreed = SND_FreeOldestSound()) != 0) { iBytesFreed += iTheseBytesFreed; if (iBytesFreed >= iRealSize) - break; // early opt-out since we've managed to recover enough (mem-contiguity issues aside) + break; // early opt-out since we've managed to recover enough (mem-contiguity issues aside) } gbMemFreeupOccured = qtrue; continue; @@ -354,29 +305,27 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int /*unusedAlign*/) // // findlabel: "recovermem" - Com_Printf(S_COLOR_RED"Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); + Com_Printf(S_COLOR_RED "Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); Z_Details_f(); - Com_Error(ERR_FATAL,"(Repeat): Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); + Com_Error(ERR_FATAL, "(Repeat): Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); return NULL; } } - #ifdef DEBUG_ZONE_ALLOCS Q_strncpyz(pMemory->sSrcFileBaseName, _D_Z_Filename_WithoutPath(psFile), sizeof(pMemory->sSrcFileBaseName)); - pMemory->iSrcFileLineNum = iLine; - pMemory->sOptionalLabel[0] = '\0'; - pMemory->iSnapshotNumber = giZoneSnaphotNum; + pMemory->iSrcFileLineNum = iLine; + pMemory->sOptionalLabel[0] = '\0'; + pMemory->iSnapshotNumber = giZoneSnaphotNum; #endif // Link in - pMemory->iMagic = ZONE_MAGIC; - pMemory->eTag = eTag; - pMemory->iSize = iSize; - pMemory->pNext = TheZone.Header.pNext; + pMemory->iMagic = ZONE_MAGIC; + pMemory->eTag = eTag; + pMemory->iSize = iSize; + pMemory->pNext = TheZone.Header.pNext; TheZone.Header.pNext = pMemory; - if (pMemory->pNext) - { + if (pMemory->pNext) { pMemory->pNext->pPrev = pMemory; } pMemory->pPrev = &TheZone.Header; @@ -389,19 +338,18 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int /*unusedAlign*/) // TheZone.Stats.iCurrent += iSize; TheZone.Stats.iCount++; - TheZone.Stats.iSizesPerTag [eTag] += iSize; - TheZone.Stats.iCountsPerTag [eTag]++; + TheZone.Stats.iSizesPerTag[eTag] += iSize; + TheZone.Stats.iCountsPerTag[eTag]++; - if (TheZone.Stats.iCurrent > TheZone.Stats.iPeak) - { - TheZone.Stats.iPeak = TheZone.Stats.iCurrent; + if (TheZone.Stats.iCurrent > TheZone.Stats.iPeak) { + TheZone.Stats.iPeak = TheZone.Stats.iCurrent; } #ifdef DETAILED_ZONE_DEBUG_CODE mapAllocatedZones[pMemory]++; #endif - Z_Validate(); // check for corruption + Z_Validate(); // check for corruption void *pvReturnMem = &pMemory[1]; return pvReturnMem; @@ -410,38 +358,30 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int /*unusedAlign*/) // Special wrapper around Z_Malloc for better separation between the main engine // code and the bundled minizip library. -extern "C" Q_EXPORT void* openjk_minizip_malloc(int size); -extern "C" Q_EXPORT int openjk_minizip_free(void* to_free); +extern "C" Q_EXPORT void *openjk_minizip_malloc(int size); +extern "C" Q_EXPORT int openjk_minizip_free(void *to_free); -void* openjk_minizip_malloc(int size) -{ - return Z_Malloc(size, TAG_MINIZIP, qfalse); -} +void *openjk_minizip_malloc(int size) { return Z_Malloc(size, TAG_MINIZIP, qfalse); } -int openjk_minizip_free(void *to_free) -{ - return Z_Free(to_free); -} +int openjk_minizip_free(void *to_free) { return Z_Free(to_free); } // used during model cacheing to save an extra malloc, lets us morph the disk-load buffer then // just not fs_freefile() it afterwards. // -void Z_MorphMallocTag( void *pvAddress, memtag_t eDesiredTag ) -{ +void Z_MorphMallocTag(void *pvAddress, memtag_t eDesiredTag) { zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_MorphMallocTag(): Not a valid zone header!"); - return; // won't get here + return; // won't get here } // DEC existing tag stats... // -// TheZone.Stats.iCurrent - unchanged -// TheZone.Stats.iCount - unchanged - TheZone.Stats.iSizesPerTag [pMemory->eTag] -= pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]--; + // TheZone.Stats.iCurrent - unchanged + // TheZone.Stats.iCount - unchanged + TheZone.Stats.iSizesPerTag[pMemory->eTag] -= pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]--; // morph... // @@ -449,24 +389,22 @@ void Z_MorphMallocTag( void *pvAddress, memtag_t eDesiredTag ) // INC new tag stats... // -// TheZone.Stats.iCurrent - unchanged -// TheZone.Stats.iCount - unchanged - TheZone.Stats.iSizesPerTag [pMemory->eTag] += pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]++; + // TheZone.Stats.iCurrent - unchanged + // TheZone.Stats.iCount - unchanged + TheZone.Stats.iSizesPerTag[pMemory->eTag] += pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]++; } - -static int Zone_FreeBlock(zoneHeader_t *pMemory) -{ +static int Zone_FreeBlock(zoneHeader_t *pMemory) { const int iSize = pMemory->iSize; - if (pMemory->eTag != TAG_STATIC) // belt and braces, should never hit this though + if (pMemory->eTag != TAG_STATIC) // belt and braces, should never hit this though { // Update stats... // TheZone.Stats.iCount--; TheZone.Stats.iCurrent -= pMemory->iSize; - TheZone.Stats.iSizesPerTag [pMemory->eTag] -= pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]--; + TheZone.Stats.iSizesPerTag[pMemory->eTag] -= pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]--; // Sanity checks... // @@ -476,51 +414,44 @@ static int Zone_FreeBlock(zoneHeader_t *pMemory) // Unlink and free... // pMemory->pPrev->pNext = pMemory->pNext; - if(pMemory->pNext) - { + if (pMemory->pNext) { pMemory->pNext->pPrev = pMemory->pPrev; } - //debugging double frees - pMemory->iMagic = INT_ID('F','R','E','E'); - free (pMemory); + // debugging double frees + pMemory->iMagic = INT_ID('F', 'R', 'E', 'E'); + free(pMemory); - - #ifdef DETAILED_ZONE_DEBUG_CODE +#ifdef DETAILED_ZONE_DEBUG_CODE // this has already been checked for in execution order, but wtf? - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount == 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount == 0) { Com_Error(ERR_FATAL, "Zone_FreeBlock(): Double-freeing block!"); return -1; } iAllocCount--; - #endif +#endif } return iSize; } // stats-query function to to see if it's our malloc // returns block size if so -qboolean Z_IsFromZone(const void *pvAddress, memtag_t eTag) -{ +qboolean Z_IsFromZone(const void *pvAddress, memtag_t eTag) { const zoneHeader_t *pMemory = ((const zoneHeader_t *)pvAddress) - 1; -#if 1 //debugging double free - if (pMemory->iMagic == INT_ID('F','R','E','E')) - { - Com_Printf("Z_IsFromZone(%x): Ptr has been freed already!(%9s)\n",pvAddress,pvAddress); +#if 1 // debugging double free + if (pMemory->iMagic == INT_ID('F', 'R', 'E', 'E')) { + Com_Printf("Z_IsFromZone(%x): Ptr has been freed already!(%9s)\n", pvAddress, pvAddress); return qfalse; } #endif - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { return qfalse; } - //looks like it is from our zone, let's double check the tag + // looks like it is from our zone, let's double check the tag - if (pMemory->eTag != eTag) - { + if (pMemory->eTag != eTag) { return qfalse; } @@ -529,91 +460,75 @@ qboolean Z_IsFromZone(const void *pvAddress, memtag_t eTag) // stats-query function to ask how big a malloc is... // -int Z_Size(void *pvAddress) -{ +int Z_Size(void *pvAddress) { zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->eTag == TAG_STATIC) - { - return 0; // kind of + if (pMemory->eTag == TAG_STATIC) { + return 0; // kind of } - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Size(): Not a valid zone header!"); - return 0; // won't get here + return 0; // won't get here } return pMemory->iSize; } - #ifdef DEBUG_ZONE_ALLOCS -void Z_Label(const void *pvAddress, const char *psLabel) -{ +void Z_Label(const void *pvAddress, const char *psLabel) { zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->eTag == TAG_STATIC) - { + if (pMemory->eTag == TAG_STATIC) { return; } - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "_D_Z_Label(): Not a valid zone header!"); } - Q_strncpyz( pMemory->sOptionalLabel, psLabel, sizeof(pMemory->sOptionalLabel)); + Q_strncpyz(pMemory->sOptionalLabel, psLabel, sizeof(pMemory->sOptionalLabel)); } #endif - - // Frees a block of memory... // -int Z_Free(void *pvAddress) -{ - if (!TheZone.Stats.iCount) - { - //Com_Error(ERR_FATAL, "Z_Free(): Zone has been cleard already!"); - Com_Printf("Z_Free(%x): Zone has been cleard already!\n",pvAddress); +int Z_Free(void *pvAddress) { + if (!TheZone.Stats.iCount) { + // Com_Error(ERR_FATAL, "Z_Free(): Zone has been cleard already!"); + Com_Printf("Z_Free(%x): Zone has been cleard already!\n", pvAddress); return -1; } zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; -#if 1 //debugging double free - if (pMemory->iMagic == INT_ID('F','R','E','E')) - { - Com_Error(ERR_FATAL, "Z_Free(%s): Block already-freed, or not allocated through Z_Malloc!",pvAddress); +#if 1 // debugging double free + if (pMemory->iMagic == INT_ID('F', 'R', 'E', 'E')) { + Com_Error(ERR_FATAL, "Z_Free(%s): Block already-freed, or not allocated through Z_Malloc!", pvAddress); return -1; } #endif - if (pMemory->eTag == TAG_STATIC) - { + if (pMemory->eTag == TAG_STATIC) { return 0; } - #ifdef DETAILED_ZONE_DEBUG_CODE +#ifdef DETAILED_ZONE_DEBUG_CODE // // check this error *before* barfing on bad magics... // - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount <= 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount <= 0) { Com_Error(ERR_FATAL, "Z_Free(): Block already-freed, or not allocated through Z_Malloc!"); return -1; } - #endif +#endif - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone header!"); return -1; } - if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) - { + if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone tail!"); return -1; } @@ -621,73 +536,56 @@ int Z_Free(void *pvAddress) return Zone_FreeBlock(pMemory); } - -int Z_MemSize(memtag_t eTag) -{ - return TheZone.Stats.iSizesPerTag[eTag]; -} +int Z_MemSize(memtag_t eTag) { return TheZone.Stats.iSizesPerTag[eTag]; } // Frees all blocks with the specified tag... // -void Z_TagFree(memtag_t eTag) -{ -//#ifdef _DEBUG -// int iZoneBlocks = TheZone.Stats.iCount; -//#endif +void Z_TagFree(memtag_t eTag) { + //#ifdef _DEBUG + // int iZoneBlocks = TheZone.Stats.iCount; + //#endif zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { + while (pMemory) { zoneHeader_t *pNext = pMemory->pNext; - if ( (eTag == TAG_ALL) || (pMemory->eTag == eTag)) - { + if ((eTag == TAG_ALL) || (pMemory->eTag == eTag)) { Zone_FreeBlock(pMemory); } pMemory = pNext; } -// these stupid pragmas don't work here???!?!?! -// -//#ifdef _DEBUG -//#pragma warning( disable : 4189) -// int iBlocksFreed = iZoneBlocks - TheZone.Stats.iCount; -//#pragma warning( default : 4189) -//#endif + // these stupid pragmas don't work here???!?!?! + // + //#ifdef _DEBUG + //#pragma warning( disable : 4189) + // int iBlocksFreed = iZoneBlocks - TheZone.Stats.iCount; + //#pragma warning( default : 4189) + //#endif } - #ifdef DEBUG_ZONE_ALLOCS -void *_D_S_Malloc ( int iSize, const char *psFile, int iLine) -{ - return _D_Z_Malloc( iSize, TAG_SMALL, qfalse, psFile, iLine ); -} +void *_D_S_Malloc(int iSize, const char *psFile, int iLine) { return _D_Z_Malloc(iSize, TAG_SMALL, qfalse, psFile, iLine); } #else -void *S_Malloc( int iSize ) -{ - return Z_Malloc( iSize, TAG_SMALL, qfalse); -} +void *S_Malloc(int iSize) { return Z_Malloc(iSize, TAG_SMALL, qfalse); } #endif - #ifdef _DEBUG -static void Z_MemRecoverTest_f(void) -{ +static void Z_MemRecoverTest_f(void) { // needs to be in _DEBUG only, not good for final game! // - if ( Cmd_Argc() != 2 ) { - Com_Printf( "Usage: zone_memrecovertest max2alloc\n" ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: zone_memrecovertest max2alloc\n"); return; } - int iMaxAlloc = 1024*1024*atoi( Cmd_Argv(1) ); + int iMaxAlloc = 1024 * 1024 * atoi(Cmd_Argv(1)); int iTotalMalloc = 0; - while (1) - { - const int iThisMalloc = 5* (1024 * 1024); - Z_Malloc(iThisMalloc, TAG_SPECIAL_MEM_TEST, qfalse); // and lose, just to consume memory + while (1) { + const int iThisMalloc = 5 * (1024 * 1024); + Z_Malloc(iThisMalloc, TAG_SPECIAL_MEM_TEST, qfalse); // and lose, just to consume memory iTotalMalloc += iThisMalloc; - if (gbMemFreeupOccured || (iTotalMalloc >= iMaxAlloc) ) + if (gbMemFreeupOccured || (iTotalMalloc >= iMaxAlloc)) break; } @@ -697,46 +595,33 @@ static void Z_MemRecoverTest_f(void) // Gives a summary of the zone memory usage -static void Z_Stats_f(void) -{ - Com_Printf("\nThe zone is using %d bytes (%.2fMB) in %d memory blocks\n", - TheZone.Stats.iCurrent, - (float)TheZone.Stats.iCurrent / 1024.0f / 1024.0f, - TheZone.Stats.iCount - ); - - Com_Printf("The zone peaked at %d bytes (%.2fMB)\n", - TheZone.Stats.iPeak, - (float)TheZone.Stats.iPeak / 1024.0f / 1024.0f - ); +static void Z_Stats_f(void) { + Com_Printf("\nThe zone is using %d bytes (%.2fMB) in %d memory blocks\n", TheZone.Stats.iCurrent, (float)TheZone.Stats.iCurrent / 1024.0f / 1024.0f, + TheZone.Stats.iCount); + + Com_Printf("The zone peaked at %d bytes (%.2fMB)\n", TheZone.Stats.iPeak, (float)TheZone.Stats.iPeak / 1024.0f / 1024.0f); } // Gives a detailed breakdown of the memory blocks in the zone // -static void Z_Details_f(void) -{ +static void Z_Details_f(void) { Com_Printf("---------------------------------------------------------------------------\n"); - Com_Printf("%20s %9s\n","Zone Tag","Bytes"); - Com_Printf("%20s %9s\n","--------","-----"); - for (int i=0; i LabelRefCount_t; // yet another place where Gil's string class works and MS's doesn't -typedef std::map TagBlockLabels_t; +typedef std::map LabelRefCount_t; // yet another place where Gil's string class works and MS's doesn't +typedef std::map TagBlockLabels_t; static TagBlockLabels_t AllTagBlockLabels; -static void Z_Snapshot_f(void) -{ +static void Z_Snapshot_f(void) { AllTagBlockLabels.clear(); zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { + while (pMemory) { AllTagBlockLabels[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel]++; pMemory = pMemory->pNext; } giZoneSnaphotNum++; - Com_Printf("Ok. ( Current snapshot num is now %d )\n",giZoneSnaphotNum); + Com_Printf("Ok. ( Current snapshot num is now %d )\n", giZoneSnaphotNum); } -static void Z_TagDebug_f(void) -{ +static void Z_TagDebug_f(void) { TagBlockLabels_t AllTagBlockLabels_Local; qboolean bSnapShotTestActive = qfalse; memtag_t eTag = TAG_ALL; const char *psTAGName = Cmd_Argv(1); - if (psTAGName[0]) - { + if (psTAGName[0]) { // check optional arg... // - if (!Q_stricmp(psTAGName,"#snap")) - { + if (!Q_stricmp(psTAGName, "#snap")) { bSnapShotTestActive = qtrue; - AllTagBlockLabels_Local = AllTagBlockLabels; // horrible great STL copy + AllTagBlockLabels_Local = AllTagBlockLabels; // horrible great STL copy psTAGName = Cmd_Argv(2); } - if (psTAGName[0]) - { + if (psTAGName[0]) { // skip over "tag_" if user supplied it... // - if (!Q_stricmpn(psTAGName,"TAG_",4)) - { + if (!Q_stricmpn(psTAGName, "TAG_", 4)) { psTAGName += 4; } // see if the user specified a valid tag... // - for (int i=0; i', e.g. TAG_GHOUL2, TAG_ALL (careful!)\n"); return; } - Com_Printf("Dumping debug data for tag \"%s\"...%s\n\n",psTagStrings[eTag], bSnapShotTestActive?"( since snapshot only )":""); + Com_Printf("Dumping debug data for tag \"%s\"...%s\n\n", psTagStrings[eTag], bSnapShotTestActive ? "( since snapshot only )" : ""); - Com_Printf("%8s"," "); // to compensate for code further down: Com_Printf("(%5d) ",iBlocksListed); - if (eTag == TAG_ALL) - { - Com_Printf("%20s ","Zone Tag"); + Com_Printf("%8s", " "); // to compensate for code further down: Com_Printf("(%5d) ",iBlocksListed); + if (eTag == TAG_ALL) { + Com_Printf("%20s ", "Zone Tag"); } - Com_Printf("%9s\n","Bytes"); - Com_Printf("%8s"," "); - if (eTag == TAG_ALL) - { - Com_Printf("%20s ","--------"); + Com_Printf("%9s\n", "Bytes"); + Com_Printf("%8s", " "); + if (eTag == TAG_ALL) { + Com_Printf("%20s ", "--------"); } - Com_Printf("%9s\n","-----"); - + Com_Printf("%9s\n", "-----"); - if (bSnapShotTestActive) - { + if (bSnapShotTestActive) { // dec ref counts in last snapshot for all current blocks (which will make new stuff go negative) // zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - if (pMemory->eTag == eTag || eTag == TAG_ALL) - { + while (pMemory) { + if (pMemory->eTag == eTag || eTag == TAG_ALL) { AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel]--; } pMemory = pMemory->pNext; @@ -849,38 +717,28 @@ static void Z_TagDebug_f(void) int iBlocksListed = 0; int iTotalSize = 0; zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - if ( (pMemory->eTag == eTag || eTag == TAG_ALL) - && (!bSnapShotTestActive || (pMemory->iSnapshotNumber == giZoneSnaphotNum && AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel] <0) ) - ) - { - float fSize = (float)(pMemory->iSize) / 1024.0f / 1024.0f; - int iSize = fSize; - int iRemainder = 100.0f * (fSize - floor(fSize)); - - Com_Printf("(%5d) ",iBlocksListed); - - if (eTag == TAG_ALL) - { - Com_Printf("%20s",psTagStrings[pMemory->eTag]); + while (pMemory) { + if ((pMemory->eTag == eTag || eTag == TAG_ALL) && + (!bSnapShotTestActive || + (pMemory->iSnapshotNumber == giZoneSnaphotNum && AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel] < 0))) { + float fSize = (float)(pMemory->iSize) / 1024.0f / 1024.0f; + int iSize = fSize; + int iRemainder = 100.0f * (fSize - floor(fSize)); + + Com_Printf("(%5d) ", iBlocksListed); + + if (eTag == TAG_ALL) { + Com_Printf("%20s", psTagStrings[pMemory->eTag]); } - Com_Printf(" %9d (%2d.%02dMB) File: \"%s\", Line: %d\n", - pMemory->iSize, - iSize,iRemainder, - pMemory->sSrcFileBaseName, - pMemory->iSrcFileLineNum - ); - if (pMemory->sOptionalLabel[0]) - { - Com_Printf("( Label: \"%s\" )\n",pMemory->sOptionalLabel); + Com_Printf(" %9d (%2d.%02dMB) File: \"%s\", Line: %d\n", pMemory->iSize, iSize, iRemainder, pMemory->sSrcFileBaseName, pMemory->iSrcFileLineNum); + if (pMemory->sOptionalLabel[0]) { + Com_Printf("( Label: \"%s\" )\n", pMemory->sOptionalLabel); } iBlocksListed++; iTotalSize += pMemory->iSize; - if (bSnapShotTestActive) - { + if (bSnapShotTestActive) { // bump ref count so we only 1 warning per new string, not for every one sharing that label... // AllTagBlockLabels_Local[psTagStrings[pMemory->eTag]][pMemory->sOptionalLabel]++; @@ -889,13 +747,12 @@ static void Z_TagDebug_f(void) pMemory = pMemory->pNext; } - Com_Printf("( %d blocks listed, %d bytes (%.2fMB) total )\n",iBlocksListed, iTotalSize, (float)iTotalSize / 1024.0f / 1024.0f); + Com_Printf("( %d blocks listed, %d bytes (%.2fMB) total )\n", iBlocksListed, iTotalSize, (float)iTotalSize / 1024.0f / 1024.0f); } #endif // Shuts down the zone memory system and frees up all memory -void Com_ShutdownZoneMemory(void) -{ +void Com_ShutdownZoneMemory(void) { Cmd_RemoveCommand("zone_stats"); Cmd_RemoveCommand("zone_details"); @@ -908,52 +765,46 @@ void Com_ShutdownZoneMemory(void) Cmd_RemoveCommand("zone_snapshot"); #endif - if(TheZone.Stats.iCount) - { + if (TheZone.Stats.iCount) { Com_Printf("Automatically freeing %d blocks making up %d bytes\n", TheZone.Stats.iCount, TheZone.Stats.iCurrent); Z_TagFree(TAG_ALL); - //assert(!TheZone.Stats.iCount); // These aren't really problematic per se, it's just warning us that we're freeing extra - //assert(!TheZone.Stats.iCurrent); // memory that is in the zone manager (but not actively tracked..) so if anything, zone_* - // commands will just simply be wrong in displaying bytes, but in my tests, it's only off - // by like 10 bytes / 1 block, which isn't a real problem --eez - if(TheZone.Stats.iCount < 0) { - Com_Printf(S_COLOR_YELLOW"WARNING: Freeing %d extra blocks (%d bytes) not tracked by the zone manager\n", - abs(TheZone.Stats.iCount), abs(TheZone.Stats.iCurrent)); + // assert(!TheZone.Stats.iCount); // These aren't really problematic per se, it's just warning us that we're freeing extra + // assert(!TheZone.Stats.iCurrent); // memory that is in the zone manager (but not actively tracked..) so if anything, zone_* + // commands will just simply be wrong in displaying bytes, but in my tests, it's only off + // by like 10 bytes / 1 block, which isn't a real problem --eez + if (TheZone.Stats.iCount < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: Freeing %d extra blocks (%d bytes) not tracked by the zone manager\n", abs(TheZone.Stats.iCount), + abs(TheZone.Stats.iCurrent)); } } } // Initialises the zone memory system -void Com_InitZoneMemory( void ) -{ +void Com_InitZoneMemory(void) { Com_Printf("Initialising zone memory .....\n"); memset(&TheZone, 0, sizeof(TheZone)); TheZone.Header.iMagic = ZONE_MAGIC; } -void Com_InitZoneMemoryVars( void) -{ +void Com_InitZoneMemoryVars(void) { com_validateZone = Cvar_Get("com_validateZone", "0", 0); - Cmd_AddCommand("zone_stats", Z_Stats_f); - Cmd_AddCommand("zone_details", Z_Details_f); + Cmd_AddCommand("zone_stats", Z_Stats_f); + Cmd_AddCommand("zone_details", Z_Details_f); #ifdef _DEBUG Cmd_AddCommand("zone_memrecovertest", Z_MemRecoverTest_f); #endif #ifdef DEBUG_ZONE_ALLOCS - Cmd_AddCommand("zone_tagdebug", Z_TagDebug_f); - Cmd_AddCommand("zone_snapshot", Z_Snapshot_f); + Cmd_AddCommand("zone_tagdebug", Z_TagDebug_f); + Cmd_AddCommand("zone_snapshot", Z_Snapshot_f); #endif } - - - /* ======================== CopyString @@ -962,27 +813,25 @@ CopyString memory from a memstatic_t might be returned ======================== */ -char *CopyString( const char *in ) { - char *out; +char *CopyString(const char *in) { + char *out; if (!in[0]) { return ((char *)&gEmptyString) + sizeof(zoneHeader_t); - } - else if (!in[1]) { + } else if (!in[1]) { if (in[0] >= '0' && in[0] <= '9') { - return ((char *)&gNumberString[in[0]-'0']) + sizeof(zoneHeader_t); + return ((char *)&gNumberString[in[0] - '0']) + sizeof(zoneHeader_t); } } - out = (char *) S_Malloc (strlen(in)+1); - strcpy (out, in); + out = (char *)S_Malloc(strlen(in) + 1); + strcpy(out, in); - Z_Label(out,in); + Z_Label(out, in); return out; } - /* =============== Com_TouchMemory @@ -990,34 +839,31 @@ Com_TouchMemory Touch all known used data to make sure it is paged in =============== */ -void Com_TouchMemory( void ) { - //int start, end; - int i, j; - unsigned int sum; - //int totalTouched; +void Com_TouchMemory(void) { + // int start, end; + int i, j; + unsigned int sum; + // int totalTouched; Z_Validate(); - //start = Sys_Milliseconds(); + // start = Sys_Milliseconds(); sum = 0; - //totalTouched=0; + // totalTouched=0; zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - byte *pMem = (byte *) &pMemory[1]; + while (pMemory) { + byte *pMem = (byte *)&pMemory[1]; j = pMemory->iSize >> 2; - for (i=0; iiSize; + // totalTouched+=pMemory->iSize; pMemory = pMemory->pNext; } - //end = Sys_Milliseconds(); + // end = Sys_Milliseconds(); - //Com_Printf( "Com_TouchMemory: %i bytes, %i msec\n", totalTouched, end - start ); + // Com_Printf( "Com_TouchMemory: %i bytes, %i msec\n", totalTouched, end - start ); } - - diff --git a/code/rd-common/tr_font.cpp b/code/rd-common/tr_font.cpp index 8724a18311..2c4d8d4e5c 100644 --- a/code/rd-common/tr_font.cpp +++ b/code/rd-common/tr_font.cpp @@ -24,7 +24,7 @@ along with this program; if not, see . #include #include -#include "../qcommon/sstring.h" // stl string class won't compile in here (MS shite), so use Gil's. +#include "../qcommon/sstring.h" // stl string class won't compile in here (MS shite), so use Gil's. #include "tr_local.h" #include "tr_font.h" @@ -42,120 +42,108 @@ cvar_t *r_fontSharpness; // ///////////////////////////////////////////////////////////////////////////////////////////////////////// -typedef enum -{ - eWestern, // ( I only care about asian languages in here at the moment ) +typedef enum { + eWestern, // ( I only care about asian languages in here at the moment ) #ifndef JK2_MODE - eRussian, // .. but now I need to care about this, since it uses a different TP - ePolish, // ditto + eRussian, // .. but now I need to care about this, since it uses a different TP + ePolish, // ditto #endif eKorean, - eTaiwanese, // 15x15 glyphs tucked against BR of 16x16 space + eTaiwanese, // 15x15 glyphs tucked against BR of 16x16 space eJapanese, // 15x15 glyphs tucked against TL of 16x16 space #ifndef JK2_MODE - eChinese, // 15x15 glyphs tucked against TL of 16x16 space - eThai, // 16x16 cells with glyphs against left edge, special file (tha_widths.dat) for variable widths + eChinese, // 15x15 glyphs tucked against TL of 16x16 space + eThai, // 16x16 cells with glyphs against left edge, special file (tha_widths.dat) for variable widths #endif } Language_e; // this is to cut down on all the stupid string compares I've been doing, and convert asian stuff to switch-case // -static Language_e GetLanguageEnum() -{ - static Language_e eLanguage = eWestern; +static Language_e GetLanguageEnum() { + static Language_e eLanguage = eWestern; #ifdef JK2_MODE - if ( !sp_language ) + if (!sp_language) return eLanguage; - else if ( sp_language->integer == SP_LANGUAGE_KOREAN ) + else if (sp_language->integer == SP_LANGUAGE_KOREAN) eLanguage = eKorean; - else if ( sp_language->integer == SP_LANGUAGE_JAPANESE ) + else if (sp_language->integer == SP_LANGUAGE_JAPANESE) eLanguage = eJapanese; - else if ( sp_language->integer == SP_LANGUAGE_TAIWANESE ) + else if (sp_language->integer == SP_LANGUAGE_TAIWANESE) eLanguage = eTaiwanese; return eLanguage; #else - static int iSE_Language_ModificationCount = -1234; // any old silly value that won't match the cvar mod count + static int iSE_Language_ModificationCount = -1234; // any old silly value that won't match the cvar mod count // only re-strcmp() when language string has changed from what we knew it as... // - if (iSE_Language_ModificationCount != se_language->modificationCount ) - { - iSE_Language_ModificationCount = se_language->modificationCount; - - if ( Language_IsRussian() ) eLanguage = eRussian; - else if ( Language_IsPolish() ) eLanguage = ePolish; - else if ( Language_IsKorean() ) eLanguage = eKorean; - else if ( Language_IsTaiwanese() ) eLanguage = eTaiwanese; - else if ( Language_IsJapanese() ) eLanguage = eJapanese; - else if ( Language_IsChinese() ) eLanguage = eChinese; - else if ( Language_IsThai() ) eLanguage = eThai; - else eLanguage = eWestern; + if (iSE_Language_ModificationCount != se_language->modificationCount) { + iSE_Language_ModificationCount = se_language->modificationCount; + + if (Language_IsRussian()) + eLanguage = eRussian; + else if (Language_IsPolish()) + eLanguage = ePolish; + else if (Language_IsKorean()) + eLanguage = eKorean; + else if (Language_IsTaiwanese()) + eLanguage = eTaiwanese; + else if (Language_IsJapanese()) + eLanguage = eJapanese; + else if (Language_IsChinese()) + eLanguage = eChinese; + else if (Language_IsThai()) + eLanguage = eThai; + else + eLanguage = eWestern; } return eLanguage; #endif } #ifndef JK2_MODE -struct SBCSOverrideLanguages_t -{ +struct SBCSOverrideLanguages_t { const char *m_psName; - Language_e m_eLanguage; + Language_e m_eLanguage; }; // so I can do some stuff with for-next loops when I add polish etc... // -SBCSOverrideLanguages_t g_SBCSOverrideLanguages[]= -{ - {"russian", eRussian}, - {"polish", ePolish}, - {NULL, eWestern} -}; - - +SBCSOverrideLanguages_t g_SBCSOverrideLanguages[] = {{"russian", eRussian}, {"polish", ePolish}, {NULL, eWestern}}; //================================================ // -#define sFILENAME_THAI_WIDTHS "fonts/tha_widths.dat" -#define sFILENAME_THAI_CODES "fonts/tha_codes.dat" +#define sFILENAME_THAI_WIDTHS "fonts/tha_widths.dat" +#define sFILENAME_THAI_CODES "fonts/tha_codes.dat" -struct ThaiCodes_t -{ - std::map m_mapValidCodes; - std::vector m_viGlyphWidths; - std::string m_strInitFailureReason; // so we don't have to keep retrying to work this out +struct ThaiCodes_t { + std::map m_mapValidCodes; + std::vector m_viGlyphWidths; + std::string m_strInitFailureReason; // so we don't have to keep retrying to work this out - void Clear( void ) - { + void Clear(void) { m_mapValidCodes.clear(); m_viGlyphWidths.clear(); - m_strInitFailureReason = ""; // if blank, never failed, else says don't bother re-trying + m_strInitFailureReason = ""; // if blank, never failed, else says don't bother re-trying } - ThaiCodes_t() - { - Clear(); - } + ThaiCodes_t() { Clear(); } // convert a supplied 1,2 or 3-byte multiplied-up integer into a valid 0..n index, else -1... // - int GetValidIndex( int iCode ) - { - std::map ::iterator it = m_mapValidCodes.find( iCode ); - if (it != m_mapValidCodes.end()) - { - return (*it).second; + int GetValidIndex(int iCode) { + std::map::iterator it = m_mapValidCodes.find(iCode); + if (it != m_mapValidCodes.end()) { + return (*it).second; } return -1; } - int GetWidth( int iGlyphIndex ) - { - if (iGlyphIndex < (int)m_viGlyphWidths.size()) - { - return m_viGlyphWidths[ iGlyphIndex ]; + int GetWidth(int iGlyphIndex) { + if (iGlyphIndex < (int)m_viGlyphWidths.size()) { + return m_viGlyphWidths[iGlyphIndex]; } assert(0); @@ -163,45 +151,36 @@ struct ThaiCodes_t } // return is error message to display, or NULL for success - const char *Init(void) - { - if (m_mapValidCodes.empty() && m_viGlyphWidths.empty()) - { - if (m_strInitFailureReason.empty()) // never tried and failed already? + const char *Init(void) { + if (m_mapValidCodes.empty() && m_viGlyphWidths.empty()) { + if (m_strInitFailureReason.empty()) // never tried and failed already? { - int *piData = NULL; // note , not , for []-access + int *piData = NULL; // note , not , for []-access // // read the valid-codes table in... // - int iBytesRead = ri.FS_ReadFile( sFILENAME_THAI_CODES, (void **) &piData ); - if (iBytesRead > 0 && !(iBytesRead&3)) // valid length and multiple of 4 bytes long + int iBytesRead = ri.FS_ReadFile(sFILENAME_THAI_CODES, (void **)&piData); + if (iBytesRead > 0 && !(iBytesRead & 3)) // valid length and multiple of 4 bytes long { int iTableEntries = iBytesRead / sizeof(int); - for (int i=0; i < iTableEntries; i++) - { - m_mapValidCodes[ piData[i] ] = i; // convert MBCS code to sequential index... + for (int i = 0; i < iTableEntries; i++) { + m_mapValidCodes[piData[i]] = i; // convert MBCS code to sequential index... } - ri.FS_FreeFile( piData ); // dispose of original + ri.FS_FreeFile(piData); // dispose of original // now read in the widths... (I'll keep these in a simple STL vector, so they'all disappear when the entries do... // - iBytesRead = ri.FS_ReadFile( sFILENAME_THAI_WIDTHS, (void **) &piData ); - if (iBytesRead > 0 && !(iBytesRead&3) && iBytesRead>>2/*sizeof(int)*/ == iTableEntries) - { - for (int i=0; i 0 && !(iBytesRead & 3) && iBytesRead >> 2 /*sizeof(int)*/ == iTableEntries) { + for (int i = 0; i < iTableEntries; i++) { + m_viGlyphWidths.push_back(piData[i]); } - ri.FS_FreeFile( piData ); // dispose of original - } - else - { + ri.FS_FreeFile(piData); // dispose of original + } else { m_strInitFailureReason = va("Error with file \"%s\", size = %d!\n", sFILENAME_THAI_WIDTHS, iBytesRead); } - } - else - { + } else { m_strInitFailureReason = va("Error with file \"%s\", size = %d!\n", sFILENAME_THAI_CODES, iBytesRead); } } @@ -212,87 +191,91 @@ struct ThaiCodes_t }; #endif - -#define GLYPH_MAX_KOREAN_SHADERS 3 +#define GLYPH_MAX_KOREAN_SHADERS 3 #define GLYPH_MAX_TAIWANESE_SHADERS 4 -#define GLYPH_MAX_JAPANESE_SHADERS 3 -#define GLYPH_MAX_CHINESE_SHADERS 3 -#define GLYPH_MAX_THAI_SHADERS 3 -#define GLYPH_MAX_ASIAN_SHADERS 4 // this MUST equal the larger of the above defines +#define GLYPH_MAX_JAPANESE_SHADERS 3 +#define GLYPH_MAX_CHINESE_SHADERS 3 +#define GLYPH_MAX_THAI_SHADERS 3 +#define GLYPH_MAX_ASIAN_SHADERS 4 // this MUST equal the larger of the above defines #define MAX_FONT_VARIANTS 8 -class CFontInfo -{ -private: +class CFontInfo { + private: // From the fontdat file - glyphInfo_t mGlyphs[GLYPH_COUNT]; + glyphInfo_t mGlyphs[GLYPH_COUNT]; -// int mAsianHack; // unused junk from John's fontdat file format. + // int mAsianHack; // unused junk from John's fontdat file format. // end of fontdat data - int mShader; // handle to the shader with the glyph + int mShader; // handle to the shader with the glyph - int m_hAsianShaders[GLYPH_MAX_ASIAN_SHADERS]; // shaders for Korean glyphs where applicable - glyphInfo_t m_AsianGlyph; // special glyph containing asian->western scaling info for all glyphs - int m_iAsianGlyphsAcross; // needed to dynamically calculate S,T coords - int m_iAsianPagesLoaded; - bool m_bAsianLastPageHalfHeight; + int m_hAsianShaders[GLYPH_MAX_ASIAN_SHADERS]; // shaders for Korean glyphs where applicable + glyphInfo_t m_AsianGlyph; // special glyph containing asian->western scaling info for all glyphs + int m_iAsianGlyphsAcross; // needed to dynamically calculate S,T coords + int m_iAsianPagesLoaded; + bool m_bAsianLastPageHalfHeight; #ifdef JK2_MODE - int m_iAsianLanguageLoaded; // doesn't matter what this is, so long as it's comparable as being changed + int m_iAsianLanguageLoaded; // doesn't matter what this is, so long as it's comparable as being changed #else - int m_iLanguageModificationCount; // doesn't matter what this is, so long as it's comparable as being changed + int m_iLanguageModificationCount; // doesn't matter what this is, so long as it's comparable as being changed #endif #ifndef JK2_MODE - ThaiCodes_t *m_pThaiData; + ThaiCodes_t *m_pThaiData; #endif -public: - char m_sFontName[MAX_QPATH]; // eg "fonts/lcd" // needed for korean font-hint if we need >1 hangul set - int mPointSize; - int mHeight; - int mAscender; - int mDescender; + public: + char m_sFontName[MAX_QPATH]; // eg "fonts/lcd" // needed for korean font-hint if we need >1 hangul set + int mPointSize; + int mHeight; + int mAscender; + int mDescender; - bool mbRoundCalcs; // trying to make this !@#$%^ thing work with scaling + bool mbRoundCalcs; // trying to make this !@#$%^ thing work with scaling #ifndef JK2_MODE - int m_iThisFont; // handle to itself - int m_iAltSBCSFont; // -1 == NULL // alternative single-byte font for languages like russian/polish etc that need to override high characters ? - int m_iOriginalFontWhenSBCSOverriden; - float m_fAltSBCSFontScaleFactor; // -1, else amount to adjust returned values by to make them fit the master western font they're substituting for + int m_iThisFont; // handle to itself + int m_iAltSBCSFont; // -1 == NULL // alternative single-byte font for languages like russian/polish etc that need to override high characters ? + int m_iOriginalFontWhenSBCSOverriden; + float m_fAltSBCSFontScaleFactor; // -1, else amount to adjust returned values by to make them fit the master western font they're substituting for #endif - bool m_bIsFakeAlienLanguage; // ... if true, don't process as MBCS or override as SBCS etc + bool m_bIsFakeAlienLanguage; // ... if true, don't process as MBCS or override as SBCS etc - CFontInfo *m_variants[MAX_FONT_VARIANTS]; - int m_numVariants; - int m_handle; - qboolean m_isVariant; + CFontInfo *m_variants[MAX_FONT_VARIANTS]; + int m_numVariants; + int m_handle; + qboolean m_isVariant; CFontInfo(const char *fontName); -// CFontInfo(int fill) { memset(this, fill, sizeof(*this)); } // wtf? + // CFontInfo(int fill) { memset(this, fill, sizeof(*this)); } // wtf? ~CFontInfo(void) {} - const int GetPointSize(void) const { return(mPointSize); } - const int GetHeight(void) const { return(mHeight); } - const int GetAscender(void) const { return(mAscender); } - const int GetDescender(void) const { return(mDescender); } + const int GetPointSize(void) const { return (mPointSize); } + const int GetHeight(void) const { return (mHeight); } + const int GetAscender(void) const { return (mAscender); } + const int GetDescender(void) const { return (mDescender); } const glyphInfo_t *GetLetter(const unsigned int uiLetter, int *piShader = NULL); const int GetCollapsedAsianCode(ulong uiLetter) const; const int GetLetterWidth(const unsigned int uiLetter); const int GetLetterHorizAdvance(const unsigned int uiLetter); - const int GetShader(void) const { return(mShader); } + const int GetShader(void) const { return (mShader); } #ifdef JK2_MODE - void FlagNoAsianGlyphs(void) { m_hAsianShaders[0] = 0; m_iAsianLanguageLoaded = -1; } // used during constructor + void FlagNoAsianGlyphs(void) { + m_hAsianShaders[0] = 0; + m_iAsianLanguageLoaded = -1; + } // used during constructor #else - void FlagNoAsianGlyphs(void) { m_hAsianShaders[0] = 0; m_iLanguageModificationCount = -1; } // used during constructor + void FlagNoAsianGlyphs(void) { + m_hAsianShaders[0] = 0; + m_iLanguageModificationCount = -1; + } // used during constructor #endif bool AsianGlyphsAvailable(void) const { return !!(m_hAsianShaders[0]); } - void UpdateAsianIfNeeded( bool bForceReEval = false); + void UpdateAsianIfNeeded(bool bForceReEval = false); int GetHandle(); @@ -303,103 +286,79 @@ class CFontInfo //================================================ - - - // round float to one decimal place... // -float RoundTenth( float fValue ) -{ - return ( floorf( (fValue*10.0f) + 0.5f) ) / 10.0f; -} - +float RoundTenth(float fValue) { return (floorf((fValue * 10.0f) + 0.5f)) / 10.0f; } -int g_iCurrentFontIndex; // entry 0 is reserved index for missing/invalid, else ++ with each new font registered -std::vector g_vFontArray; -typedef std::map FontIndexMap_t; +int g_iCurrentFontIndex; // entry 0 is reserved index for missing/invalid, else ++ with each new font registered +std::vector g_vFontArray; +typedef std::map FontIndexMap_t; FontIndexMap_t g_mapFontIndexes; -int g_iNonScaledCharRange; // this is used with auto-scaling of asian fonts, anything below this number is preserved in scale, anything above is scaled down by 0.75f +int g_iNonScaledCharRange; // this is used with auto-scaling of asian fonts, anything below this number is preserved in scale, anything above is scaled down by + // 0.75f -//paletteRGBA_c lastcolour; +// paletteRGBA_c lastcolour; // =============================== some korean stuff ======================================= -#define KSC5601_HANGUL_HIBYTE_START 0xB0 // range is... -#define KSC5601_HANGUL_HIBYTE_STOP 0xC8 // ... inclusive -#define KSC5601_HANGUL_LOBYTE_LOBOUND 0xA0 // range is... -#define KSC5601_HANGUL_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) -#define KSC5601_HANGUL_CODES_PER_ROW 96 // 2 more than the number of glyphs +#define KSC5601_HANGUL_HIBYTE_START 0xB0 // range is... +#define KSC5601_HANGUL_HIBYTE_STOP 0xC8 // ... inclusive +#define KSC5601_HANGUL_LOBYTE_LOBOUND 0xA0 // range is... +#define KSC5601_HANGUL_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) +#define KSC5601_HANGUL_CODES_PER_ROW 96 // 2 more than the number of glyphs -extern qboolean Language_IsKorean( void ); +extern qboolean Language_IsKorean(void); -static inline qboolean Korean_ValidKSC5601Hangul( byte _iHi, byte _iLo ) -{ - return (qboolean)( - _iHi >=KSC5601_HANGUL_HIBYTE_START && - _iHi <=KSC5601_HANGUL_HIBYTE_STOP && - _iLo > KSC5601_HANGUL_LOBYTE_LOBOUND && - _iLo < KSC5601_HANGUL_LOBYTE_HIBOUND); -} - -static inline qboolean Korean_ValidKSC5601Hangul( unsigned int uiCode ) -{ - return Korean_ValidKSC5601Hangul( uiCode >> 8, uiCode & 0xFF ); +static inline qboolean Korean_ValidKSC5601Hangul(byte _iHi, byte _iLo) { + return (qboolean)(_iHi >= KSC5601_HANGUL_HIBYTE_START && _iHi <= KSC5601_HANGUL_HIBYTE_STOP && _iLo > KSC5601_HANGUL_LOBYTE_LOBOUND && + _iLo < KSC5601_HANGUL_LOBYTE_HIBOUND); } +static inline qboolean Korean_ValidKSC5601Hangul(unsigned int uiCode) { return Korean_ValidKSC5601Hangul(uiCode >> 8, uiCode & 0xFF); } // takes a KSC5601 double-byte hangul code and collapses down to a 0..n glyph index... // Assumes rows are 96 wide (glyph slots), not 94 wide (actual glyphs), so I can ignore boundary markers // // (invalid hangul codes will return 0) // -static int Korean_CollapseKSC5601HangulCode(unsigned int uiCode) -{ - if (Korean_ValidKSC5601Hangul( uiCode )) - { - uiCode -= (KSC5601_HANGUL_HIBYTE_START * 256) + KSC5601_HANGUL_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards - uiCode = ((uiCode >> 8) * KSC5601_HANGUL_CODES_PER_ROW) + (uiCode & 0xFF); +static int Korean_CollapseKSC5601HangulCode(unsigned int uiCode) { + if (Korean_ValidKSC5601Hangul(uiCode)) { + uiCode -= (KSC5601_HANGUL_HIBYTE_START * 256) + KSC5601_HANGUL_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards + uiCode = ((uiCode >> 8) * KSC5601_HANGUL_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; } return 0; } -static int Korean_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "kor"; - iGlyphTPs = GLYPH_MAX_KOREAN_SHADERS; +static int Korean_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "kor"; + iGlyphTPs = GLYPH_MAX_KOREAN_SHADERS; g_iNonScaledCharRange = 255; - return 32; // m_iAsianGlyphsAcross + return 32; // m_iAsianGlyphsAcross } // ======================== some taiwanese stuff ============================== // (all ranges inclusive for Big5)... // -#define BIG5_HIBYTE_START0 0xA1 // (misc chars + level 1 hanzi) -#define BIG5_HIBYTE_STOP0 0xC6 // -#define BIG5_HIBYTE_START1 0xC9 // (level 2 hanzi) -#define BIG5_HIBYTE_STOP1 0xF9 // -#define BIG5_LOBYTE_LOBOUND0 0x40 // -#define BIG5_LOBYTE_HIBOUND0 0x7E // -#define BIG5_LOBYTE_LOBOUND1 0xA1 // -#define BIG5_LOBYTE_HIBOUND1 0xFE // -#define BIG5_CODES_PER_ROW 160 // 3 more than the number of glyphs - -extern qboolean Language_IsTaiwanese( void ); - -static qboolean Taiwanese_ValidBig5Code( unsigned int uiCode ) -{ - const byte _iHi = (uiCode >> 8)&0xFF; - if ( (_iHi >= BIG5_HIBYTE_START0 && _iHi <= BIG5_HIBYTE_STOP0) - || (_iHi >= BIG5_HIBYTE_START1 && _iHi <= BIG5_HIBYTE_STOP1) - ) - { +#define BIG5_HIBYTE_START0 0xA1 // (misc chars + level 1 hanzi) +#define BIG5_HIBYTE_STOP0 0xC6 // +#define BIG5_HIBYTE_START1 0xC9 // (level 2 hanzi) +#define BIG5_HIBYTE_STOP1 0xF9 // +#define BIG5_LOBYTE_LOBOUND0 0x40 // +#define BIG5_LOBYTE_HIBOUND0 0x7E // +#define BIG5_LOBYTE_LOBOUND1 0xA1 // +#define BIG5_LOBYTE_HIBOUND1 0xFE // +#define BIG5_CODES_PER_ROW 160 // 3 more than the number of glyphs + +extern qboolean Language_IsTaiwanese(void); + +static qboolean Taiwanese_ValidBig5Code(unsigned int uiCode) { + const byte _iHi = (uiCode >> 8) & 0xFF; + if ((_iHi >= BIG5_HIBYTE_START0 && _iHi <= BIG5_HIBYTE_STOP0) || (_iHi >= BIG5_HIBYTE_START1 && _iHi <= BIG5_HIBYTE_STOP1)) { const byte _iLo = uiCode & 0xFF; - if ( (_iLo >= BIG5_LOBYTE_LOBOUND0 && _iLo <= BIG5_LOBYTE_HIBOUND0) || - (_iLo >= BIG5_LOBYTE_LOBOUND1 && _iLo <= BIG5_LOBYTE_HIBOUND1) - ) - { + if ((_iLo >= BIG5_LOBYTE_LOBOUND0 && _iLo <= BIG5_LOBYTE_HIBOUND0) || (_iLo >= BIG5_LOBYTE_LOBOUND1 && _iLo <= BIG5_LOBYTE_HIBOUND1)) { return qtrue; } } @@ -407,37 +366,28 @@ static qboolean Taiwanese_ValidBig5Code( unsigned int uiCode ) return qfalse; } - // only call this when Taiwanese_ValidBig5Code() has already returned true... // -static qboolean Taiwanese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static qboolean Taiwanese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 21 chars, those seem to be all the basic punctuation... // - if ( uiCode >= ((BIG5_HIBYTE_START0<<8)|BIG5_LOBYTE_LOBOUND0) && - uiCode < (((BIG5_HIBYTE_START0<<8)|BIG5_LOBYTE_LOBOUND0)+20) - ) - { + if (uiCode >= ((BIG5_HIBYTE_START0 << 8) | BIG5_LOBYTE_LOBOUND0) && uiCode < (((BIG5_HIBYTE_START0 << 8) | BIG5_LOBYTE_LOBOUND0) + 20)) { return qtrue; } return qfalse; } - // takes a BIG5 double-byte code (including level 2 hanzi) and collapses down to a 0..n glyph index... // Assumes rows are 160 wide (glyph slots), not 157 wide (actual glyphs), so I can ignore boundary markers // // (invalid big5 codes will return 0) // -static int Taiwanese_CollapseBig5Code( unsigned int uiCode ) -{ - if (Taiwanese_ValidBig5Code( uiCode )) - { - uiCode -= (BIG5_HIBYTE_START0 * 256) + BIG5_LOBYTE_LOBOUND0; // sneaky maths on both bytes, reduce to 0x0000 onwards - if ( (uiCode & 0xFF) >= (BIG5_LOBYTE_LOBOUND1-1)-BIG5_LOBYTE_LOBOUND0) - { - uiCode -= ((BIG5_LOBYTE_LOBOUND1-1) - (BIG5_LOBYTE_HIBOUND0+1)) -1; +static int Taiwanese_CollapseBig5Code(unsigned int uiCode) { + if (Taiwanese_ValidBig5Code(uiCode)) { + uiCode -= (BIG5_HIBYTE_START0 * 256) + BIG5_LOBYTE_LOBOUND0; // sneaky maths on both bytes, reduce to 0x0000 onwards + if ((uiCode & 0xFF) >= (BIG5_LOBYTE_LOBOUND1 - 1) - BIG5_LOBYTE_LOBOUND0) { + uiCode -= ((BIG5_LOBYTE_LOBOUND1 - 1) - (BIG5_LOBYTE_HIBOUND0 + 1)) - 1; } uiCode = ((uiCode >> 8) * BIG5_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; @@ -445,43 +395,33 @@ static int Taiwanese_CollapseBig5Code( unsigned int uiCode ) return 0; } -static int Taiwanese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "tai"; - iGlyphTPs = GLYPH_MAX_TAIWANESE_SHADERS; +static int Taiwanese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "tai"; + iGlyphTPs = GLYPH_MAX_TAIWANESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } // ======================== some Japanese stuff ============================== - // ( all ranges inclusive for Shift-JIS ) // -#define SHIFTJIS_HIBYTE_START0 0x81 -#define SHIFTJIS_HIBYTE_STOP0 0x9F -#define SHIFTJIS_HIBYTE_START1 0xE0 -#define SHIFTJIS_HIBYTE_STOP1 0xEF +#define SHIFTJIS_HIBYTE_START0 0x81 +#define SHIFTJIS_HIBYTE_STOP0 0x9F +#define SHIFTJIS_HIBYTE_START1 0xE0 +#define SHIFTJIS_HIBYTE_STOP1 0xEF // -#define SHIFTJIS_LOBYTE_START0 0x40 -#define SHIFTJIS_LOBYTE_STOP0 0x7E -#define SHIFTJIS_LOBYTE_START1 0x80 -#define SHIFTJIS_LOBYTE_STOP1 0xFC -#define SHIFTJIS_CODES_PER_ROW (((SHIFTJIS_LOBYTE_STOP0-SHIFTJIS_LOBYTE_START0)+1)+((SHIFTJIS_LOBYTE_STOP1-SHIFTJIS_LOBYTE_START1)+1)) +#define SHIFTJIS_LOBYTE_START0 0x40 +#define SHIFTJIS_LOBYTE_STOP0 0x7E +#define SHIFTJIS_LOBYTE_START1 0x80 +#define SHIFTJIS_LOBYTE_STOP1 0xFC +#define SHIFTJIS_CODES_PER_ROW (((SHIFTJIS_LOBYTE_STOP0 - SHIFTJIS_LOBYTE_START0) + 1) + ((SHIFTJIS_LOBYTE_STOP1 - SHIFTJIS_LOBYTE_START1) + 1)) +extern qboolean Language_IsJapanese(void); -extern qboolean Language_IsJapanese( void ); - -static qboolean Japanese_ValidShiftJISCode( byte _iHi, byte _iLo ) -{ - if ( (_iHi >= SHIFTJIS_HIBYTE_START0 && _iHi <= SHIFTJIS_HIBYTE_STOP0) - || (_iHi >= SHIFTJIS_HIBYTE_START1 && _iHi <= SHIFTJIS_HIBYTE_STOP1) - ) - { - if ( (_iLo >= SHIFTJIS_LOBYTE_START0 && _iLo <= SHIFTJIS_LOBYTE_STOP0) || - (_iLo >= SHIFTJIS_LOBYTE_START1 && _iLo <= SHIFTJIS_LOBYTE_STOP1) - ) - { +static qboolean Japanese_ValidShiftJISCode(byte _iHi, byte _iLo) { + if ((_iHi >= SHIFTJIS_HIBYTE_START0 && _iHi <= SHIFTJIS_HIBYTE_STOP0) || (_iHi >= SHIFTJIS_HIBYTE_START1 && _iHi <= SHIFTJIS_HIBYTE_STOP1)) { + if ((_iLo >= SHIFTJIS_LOBYTE_START0 && _iLo <= SHIFTJIS_LOBYTE_STOP0) || (_iLo >= SHIFTJIS_LOBYTE_START1 && _iLo <= SHIFTJIS_LOBYTE_STOP1)) { return qtrue; } } @@ -489,47 +429,34 @@ static qboolean Japanese_ValidShiftJISCode( byte _iHi, byte _iLo ) return qfalse; } -static inline qboolean Japanese_ValidShiftJISCode( unsigned int uiCode ) -{ - return Japanese_ValidShiftJISCode( uiCode >> 8, uiCode & 0xFF ); -} - +static inline qboolean Japanese_ValidShiftJISCode(unsigned int uiCode) { return Japanese_ValidShiftJISCode(uiCode >> 8, uiCode & 0xFF); } // only call this when Japanese_ValidShiftJISCode() has already returned true... // -static qboolean Japanese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static qboolean Japanese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 18 chars, those seem to be all the basic punctuation... // - if ( uiCode >= ((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0) && - uiCode < (((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0)+18) - ) - { + if (uiCode >= ((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0) && uiCode < (((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0) + 18)) { return qtrue; } return qfalse; } - // takes a ShiftJIS double-byte code and collapse down to a 0..n glyph index... // // (invalid codes will return 0) // -static int Japanese_CollapseShiftJISCode( unsigned int uiCode ) -{ - if (Japanese_ValidShiftJISCode( uiCode )) - { - uiCode -= ((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0); // sneaky maths on both bytes, reduce to 0x0000 onwards +static int Japanese_CollapseShiftJISCode(unsigned int uiCode) { + if (Japanese_ValidShiftJISCode(uiCode)) { + uiCode -= ((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0); // sneaky maths on both bytes, reduce to 0x0000 onwards - if ( (uiCode & 0xFF) >= (SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_START0) - { - uiCode -= ((SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_STOP0)-1; + if ((uiCode & 0xFF) >= (SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_START0) { + uiCode -= ((SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_STOP0) - 1; } - if ( ((uiCode>>8)&0xFF) >= (SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_START0) - { - uiCode -= (((SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_STOP0)-1) << 8; + if (((uiCode >> 8) & 0xFF) >= (SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_START0) { + uiCode -= (((SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_STOP0) - 1) << 8; } uiCode = ((uiCode >> 8) * SHIFTJIS_CODES_PER_ROW) + (uiCode & 0xFF); @@ -539,50 +466,36 @@ static int Japanese_CollapseShiftJISCode( unsigned int uiCode ) return 0; } - -static int Japanese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "jap"; - iGlyphTPs = GLYPH_MAX_JAPANESE_SHADERS; +static int Japanese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "jap"; + iGlyphTPs = GLYPH_MAX_JAPANESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } #ifndef JK2_MODE // ======================== some Chinese stuff ============================== -#define GB_HIBYTE_START 0xA1 // range is... -#define GB_HIBYTE_STOP 0xF7 // ... inclusive -#define GB_LOBYTE_LOBOUND 0xA0 // range is... -#define GB_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) -#define GB_CODES_PER_ROW 95 // 1 more than the number of glyphs +#define GB_HIBYTE_START 0xA1 // range is... +#define GB_HIBYTE_STOP 0xF7 // ... inclusive +#define GB_LOBYTE_LOBOUND 0xA0 // range is... +#define GB_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) +#define GB_CODES_PER_ROW 95 // 1 more than the number of glyphs -extern qboolean Language_IsChinese( void ); +extern qboolean Language_IsChinese(void); -static inline qboolean Chinese_ValidGBCode( byte _iHi, byte _iLo ) -{ - return (qboolean)( - _iHi >=GB_HIBYTE_START && - _iHi <=GB_HIBYTE_STOP && - _iLo > GB_LOBYTE_LOBOUND && - _iLo < GB_LOBYTE_HIBOUND); +static inline qboolean Chinese_ValidGBCode(byte _iHi, byte _iLo) { + return (qboolean)(_iHi >= GB_HIBYTE_START && _iHi <= GB_HIBYTE_STOP && _iLo > GB_LOBYTE_LOBOUND && _iLo < GB_LOBYTE_HIBOUND); } -static inline qboolean Chinese_ValidGBCode( unsigned int uiCode) -{ - return Chinese_ValidGBCode( uiCode >> 8, uiCode & 0xFF ); -} +static inline qboolean Chinese_ValidGBCode(unsigned int uiCode) { return Chinese_ValidGBCode(uiCode >> 8, uiCode & 0xFF); } // only call this when Chinese_ValidGBCode() has already returned true... // -static qboolean Chinese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static qboolean Chinese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 13 chars, those seem to be all the basic punctuation... // - if ( uiCode > ((GB_HIBYTE_START<<8)|GB_LOBYTE_LOBOUND) && - uiCode < (((GB_HIBYTE_START<<8)|GB_LOBYTE_LOBOUND)+14) - ) - { + if (uiCode > ((GB_HIBYTE_START << 8) | GB_LOBYTE_LOBOUND) && uiCode < (((GB_HIBYTE_START << 8) | GB_LOBYTE_LOBOUND) + 14)) { return qtrue; } @@ -594,35 +507,32 @@ static qboolean Chinese_IsTrailingPunctuation( unsigned int uiCode ) // // (invalid GB codes will return 0) // -static int Chinese_CollapseGBCode( unsigned int uiCode ) -{ - if (Chinese_ValidGBCode( uiCode )) - { - uiCode -= (GB_HIBYTE_START * 256) + GB_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards - uiCode = ((uiCode >> 8) * GB_CODES_PER_ROW) + (uiCode & 0xFF); +static int Chinese_CollapseGBCode(unsigned int uiCode) { + if (Chinese_ValidGBCode(uiCode)) { + uiCode -= (GB_HIBYTE_START * 256) + GB_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards + uiCode = ((uiCode >> 8) * GB_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; } return 0; } -static int Chinese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "chi"; - iGlyphTPs = GLYPH_MAX_CHINESE_SHADERS; +static int Chinese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "chi"; + iGlyphTPs = GLYPH_MAX_CHINESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } // ======================== some Thai stuff ============================== -//TIS 620-2533 +// TIS 620-2533 -#define TIS_GLYPHS_START 160 -#define TIS_SARA_AM 0xD3 // special case letter, both a new letter and a trailing accent for the prev one -ThaiCodes_t g_ThaiCodes; // the one and only instance of this object +#define TIS_GLYPHS_START 160 +#define TIS_SARA_AM 0xD3 // special case letter, both a new letter and a trailing accent for the prev one +ThaiCodes_t g_ThaiCodes; // the one and only instance of this object -extern qboolean Language_IsThai( void ); +extern qboolean Language_IsThai(void); /* static int Thai_IsAccentChar( unsigned int uiCode ) @@ -641,33 +551,29 @@ static int Thai_IsAccentChar( unsigned int uiCode ) // returns a valid Thai code (or 0), based on taking 1,2 or 3 bytes from the supplied byte stream // Fills in with 1,2 or 3 -static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) -{ +static int Thai_ValidTISCode(const byte *psString, int &iThaiBytes) { // try a 1-byte code first... // - if (psString[0] >= 160) // so western letters drop through and use normal font + if (psString[0] >= 160) // so western letters drop through and use normal font { // this code is heavily little-endian, so someone else will need to port for Mac etc... (not my problem ;-) // - union CodeToTry_t - { - char sChars[4]; + union CodeToTry_t { + char sChars[4]; unsigned int uiCode; }; CodeToTry_t CodeToTry; - CodeToTry.uiCode = 0; // important that we clear all 4 bytes in sChars here + CodeToTry.uiCode = 0; // important that we clear all 4 bytes in sChars here // thai codes can be up to 3 bytes long, so see how high we can get... // int i = 0; - for (i = 0; i<3; i++) - { + for (i = 0; i < 3; i++) { CodeToTry.sChars[i] = psString[i]; - int iIndex = g_ThaiCodes.GetValidIndex( CodeToTry.uiCode ); - if (iIndex == -1) - { + int iIndex = g_ThaiCodes.GetValidIndex(CodeToTry.uiCode); + if (iIndex == -1) { // failed, so return previous-longest code... // CodeToTry.sChars[i] = 0; @@ -675,7 +581,7 @@ static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) } } iThaiBytes = i; - assert(i); // if 'i' was 0, then this may be an error, trying to get a thai accent as standalone char? + assert(i); // if 'i' was 0, then this may be an error, trying to get a thai accent as standalone char? return CodeToTry.uiCode; } @@ -686,22 +592,17 @@ static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) // we tell the translators to put an underscore ('_') between each word even though in Thai they're // all jammed together at final output onscreen... // -static inline qboolean Thai_IsTrailingPunctuation( unsigned int uiCode ) -{ - return (qboolean)(uiCode == '_'); -} +static inline qboolean Thai_IsTrailingPunctuation(unsigned int uiCode) { return (qboolean)(uiCode == '_'); } // takes a TIS 1,2 or 3 byte code and collapse down to a 0..n glyph index... // // (invalid codes will return 0) // -static int Thai_CollapseTISCode( unsigned int uiCode ) -{ - if (uiCode >= TIS_GLYPHS_START) // so western letters drop through as invalid +static int Thai_CollapseTISCode(unsigned int uiCode) { + if (uiCode >= TIS_GLYPHS_START) // so western letters drop through as invalid { - int iCollapsedIndex = g_ThaiCodes.GetValidIndex( uiCode ); - if (iCollapsedIndex != -1) - { + int iCollapsedIndex = g_ThaiCodes.GetValidIndex(uiCode); + if (iCollapsedIndex != -1) { return iCollapsedIndex; } } @@ -709,16 +610,14 @@ static int Thai_CollapseTISCode( unsigned int uiCode ) return 0; } -static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "tha"; - iGlyphTPs = GLYPH_MAX_THAI_SHADERS; - g_iNonScaledCharRange = INT_MAX; // in other words, don't scale any thai chars down - return 32; // m_iAsianGlyphsAcross +static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "tha"; + iGlyphTPs = GLYPH_MAX_THAI_SHADERS; + g_iNonScaledCharRange = INT_MAX; // in other words, don't scale any thai chars down + return 32; // m_iAsianGlyphsAcross } #endif - // ============================================================================ // takes char *, returns integer char at that point, and advances char * on by enough bytes to move @@ -726,19 +625,17 @@ static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) // // looks messy, but the actual execution route is quite short, so it's fast... // -// Note that I have to have this 3-param form instead of advancing a passed-in "const char **psText" because of VM-crap where you can only change ptr-contents, not ptrs themselves. Bleurgh. Ditto the qtrue:qfalse crap instead of just returning stuff straight through. +// Note that I have to have this 3-param form instead of advancing a passed-in "const char **psText" because of VM-crap where you can only change ptr-contents, +// not ptrs themselves. Bleurgh. Ditto the qtrue:qfalse crap instead of just returning stuff straight through. // -unsigned int AnyLanguage_ReadCharFromString( char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */) -{ +unsigned int AnyLanguage_ReadCharFromString(char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */) { #ifdef JK2_MODE // JK2 does this func a little differently --eez - const byte *psString = (const byte *) psText; // avoid sign-promote bug + const byte *psString = (const byte *)psText; // avoid sign-promote bug unsigned int uiLetter; - if ( Language_IsKorean() ) - { - if ( Korean_ValidKSC5601Hangul( psString[0], psString[1] )) - { + if (Language_IsKorean()) { + if (Korean_ValidKSC5601Hangul(psString[0], psString[1])) { uiLetter = (psString[0] * 256) + psString[1]; psText += 2; *piAdvanceCount = 2; @@ -746,47 +643,36 @@ unsigned int AnyLanguage_ReadCharFromString( char *psText, int *piAdvanceCount, // not going to bother testing for korean punctuation here, since korean already // uses spaces, and I don't have the punctuation glyphs defined, only the basic 2350 hanguls // - if ( pbIsTrailingPunctuation) - { + if (pbIsTrailingPunctuation) { *pbIsTrailingPunctuation = qfalse; } return uiLetter; } - } - else - if ( Language_IsTaiwanese() ) - { - if ( Taiwanese_ValidBig5Code( (psString[0] * 256) + psString[1] )) - { + } else if (Language_IsTaiwanese()) { + if (Taiwanese_ValidBig5Code((psString[0] * 256) + psString[1])) { uiLetter = (psString[0] * 256) + psString[1]; psText += 2; *piAdvanceCount = 2; // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation( uiLetter ); + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation(uiLetter); } return uiLetter; } - } - else - if ( Language_IsJapanese() ) - { - if ( Japanese_ValidShiftJISCode( psString[0], psString[1] )) - { + } else if (Language_IsJapanese()) { + if (Japanese_ValidShiftJISCode(psString[0], psString[1])) { uiLetter = (psString[0] * 256) + psString[1]; psText += 2; *piAdvanceCount = 2; // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation( uiLetter ); + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation(uiLetter); } return uiLetter; @@ -796,123 +682,95 @@ unsigned int AnyLanguage_ReadCharFromString( char *psText, int *piAdvanceCount, // ... must not have been an MBCS code... // uiLetter = psString[0]; - psText += 1; // NOT ++ + psText += 1; // NOT ++ *piAdvanceCount = 1; - if (pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = (qboolean)( - uiLetter == '!' || - uiLetter == '?' || - uiLetter == ',' || - uiLetter == '.' || - uiLetter == ';' || - uiLetter == ':'); + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = (qboolean)(uiLetter == '!' || uiLetter == '?' || uiLetter == ',' || uiLetter == '.' || uiLetter == ';' || uiLetter == ':'); } return uiLetter; #else - const byte *psString = (const byte *) psText; // avoid sign-promote bug + const byte *psString = (const byte *)psText; // avoid sign-promote bug unsigned int uiLetter; - switch ( GetLanguageEnum() ) - { - case eKorean: - { - if ( Korean_ValidKSC5601Hangul( psString[0], psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; - - // not going to bother testing for korean punctuation here, since korean already - // uses spaces, and I don't have the punctuation glyphs defined, only the basic 2350 hanguls - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = qfalse; - } + switch (GetLanguageEnum()) { + case eKorean: { + if (Korean_ValidKSC5601Hangul(psString[0], psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // not going to bother testing for korean punctuation here, since korean already + // uses spaces, and I don't have the punctuation glyphs defined, only the basic 2350 hanguls + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = qfalse; } - } - break; - case eTaiwanese: - { - if ( Taiwanese_ValidBig5Code( (psString[0] * 256) + psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eTaiwanese: { + if (Taiwanese_ValidBig5Code((psString[0] * 256) + psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eJapanese: - { - if ( Japanese_ValidShiftJISCode( psString[0], psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eJapanese: { + if (Japanese_ValidShiftJISCode(psString[0], psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eChinese: - { - if ( Chinese_ValidGBCode( (psString[0] * 256) + psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Chinese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eChinese: { + if (Chinese_ValidGBCode((psString[0] * 256) + psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Chinese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eThai: - { - int iThaiBytes; - uiLetter = Thai_ValidTISCode( psString, iThaiBytes ); - if ( uiLetter ) - { - *piAdvanceCount = iThaiBytes; + return uiLetter; + } + } break; - if ( pbIsTrailingPunctuation ) - { - *pbIsTrailingPunctuation = Thai_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eThai: { + int iThaiBytes; + uiLetter = Thai_ValidTISCode(psString, iThaiBytes); + if (uiLetter) { + *piAdvanceCount = iThaiBytes; - return uiLetter; + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Thai_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } + + return uiLetter; } - break; + } break; - default: + default: break; } @@ -921,15 +779,9 @@ unsigned int AnyLanguage_ReadCharFromString( char *psText, int *piAdvanceCount, uiLetter = psString[0]; *piAdvanceCount = 1; - if (pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = (uiLetter == '!' || - uiLetter == '?' || - uiLetter == ',' || - uiLetter == '.' || - uiLetter == ';' || - uiLetter == ':' - ) ? qtrue : qfalse; + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = + (uiLetter == '!' || uiLetter == '?' || uiLetter == ',' || uiLetter == '.' || uiLetter == ';' || uiLetter == ':') ? qtrue : qfalse; } return uiLetter; @@ -937,10 +789,9 @@ unsigned int AnyLanguage_ReadCharFromString( char *psText, int *piAdvanceCount, } #ifdef JK2_MODE -unsigned int AnyLanguage_ReadCharFromString( char **psText, qboolean *pbIsTrailingPunctuation /* = NULL */) -{ +unsigned int AnyLanguage_ReadCharFromString(char **psText, qboolean *pbIsTrailingPunctuation /* = NULL */) { int advance = 0; - unsigned int advance2 = AnyLanguage_ReadCharFromString (*psText, &advance, pbIsTrailingPunctuation); + unsigned int advance2 = AnyLanguage_ReadCharFromString(*psText, &advance, pbIsTrailingPunctuation); *psText += advance; return advance2; @@ -950,39 +801,35 @@ unsigned int AnyLanguage_ReadCharFromString( char **psText, qboolean *pbIsTraili // needed for subtitle printing since original code no longer worked once camera bar height was changed to 480/10 // rather than refdef height / 10. I now need to bodge the coords to come out right. // -qboolean Language_IsAsian(void) -{ - switch ( GetLanguageEnum() ) - { - case eKorean: - case eTaiwanese: - case eJapanese: +qboolean Language_IsAsian(void) { + switch (GetLanguageEnum()) { + case eKorean: + case eTaiwanese: + case eJapanese: #ifndef JK2_MODE - case eChinese: - case eThai: // this is asian, but the query is normally used for scaling + case eChinese: + case eThai: // this is asian, but the query is normally used for scaling #endif - return qtrue; - default: - break; + return qtrue; + default: + break; } return qfalse; } -qboolean Language_UsesSpaces(void) -{ +qboolean Language_UsesSpaces(void) { // ( korean uses spaces ) - switch ( GetLanguageEnum() ) - { - case eTaiwanese: - case eJapanese: + switch (GetLanguageEnum()) { + case eTaiwanese: + case eJapanese: #ifndef JK2_MODE - case eChinese: - case eThai: + case eChinese: + case eThai: #endif - return qfalse; - default: - break; + return qfalse; + default: + break; } return qtrue; @@ -994,20 +841,21 @@ qboolean Language_UsesSpaces(void) // If path present, it's a special language hack for SBCS override languages, eg: "lcd/russian", which means // just treat the file as "russian", but with the "lcd" part ensuring we don't find a different registered russian font // -static const char *FontDatPath( const char *_fontName ) { +static const char *FontDatPath(const char *_fontName) { static char fontName[MAX_QPATH]; - sprintf( fontName,"fonts/%s.fontdat",COM_SkipPath(const_cast(_fontName)) ); // COM_SkipPath should take a const char *, but it's just possible people use it as a char * I guess, so I have to hack around like this + sprintf(fontName, "fonts/%s.fontdat", + COM_SkipPath(const_cast(_fontName))); // COM_SkipPath should take a const char *, but it's just possible people use it as a char * I guess, + // so I have to hack around like this return fontName; } -CFontInfo::CFontInfo(const char *_fontName) -{ - int len, i; - void *buff; - dfontdat_t *fontdat; +CFontInfo::CFontInfo(const char *_fontName) { + int len, i; + void *buff; + dfontdat_t *fontdat; // remove any special hack name insertions... // - const char *fontName = FontDatPath( _fontName ); + const char *fontName = FontDatPath(_fontName); // clear some general things... // @@ -1018,16 +866,14 @@ CFontInfo::CFontInfo(const char *_fontName) m_iOriginalFontWhenSBCSOverriden = -1; m_fAltSBCSFontScaleFactor = -1; #endif - m_bIsFakeAlienLanguage = !strcmp(_fontName,"aurabesh"); // dont try and make SBCS or asian overrides for this + m_bIsFakeAlienLanguage = !strcmp(_fontName, "aurabesh"); // dont try and make SBCS or asian overrides for this len = ri.FS_ReadFile(fontName, NULL); - if (len == sizeof(dfontdat_t)) - { + if (len == sizeof(dfontdat_t)) { ri.FS_ReadFile(fontName, &buff); fontdat = (dfontdat_t *)buff; - for(i = 0; i < GLYPH_COUNT; i++) - { + for (i = 0; i < GLYPH_COUNT; i++) { #ifdef Q3_BIG_ENDIAN mGlyphs[i].width = LittleShort(fontdat->mGlyphs[i].width); mGlyphs[i].height = LittleShort(fontdat->mGlyphs[i].height); @@ -1046,28 +892,25 @@ CFontInfo::CFontInfo(const char *_fontName) mHeight = LittleShort(fontdat->mHeight); mAscender = LittleShort(fontdat->mAscender); mDescender = LittleShort(fontdat->mDescender); -// mAsianHack = LittleShort(fontdat->mKoreanHack); // ignore this crap, it's some junk in the fontdat file that no-one uses + // mAsianHack = LittleShort(fontdat->mKoreanHack); // ignore this crap, it's some junk in the fontdat file that no-one uses mbRoundCalcs = false /*!!strstr(fontName,"ergo")*/; // cope with bad fontdat headers... // - if (mHeight == 0) - { + if (mHeight == 0) { mHeight = mPointSize; - mAscender = mPointSize - Round( ((float)mPointSize/10.0f)+2 ); // have to completely guess at the baseline... sigh. - mDescender = mHeight - mAscender; + mAscender = mPointSize - Round(((float)mPointSize / 10.0f) + 2); // have to completely guess at the baseline... sigh. + mDescender = mHeight - mAscender; } ri.FS_FreeFile(buff); - } - else - { + } else { mHeight = 0; mShader = 0; } Q_strncpyz(m_sFontName, fontName, sizeof(m_sFontName)); - COM_StripExtension( m_sFontName, m_sFontName, sizeof(m_sFontName) ); // so we get better error printing if failed to load shader (ie lose ".fontdat") + COM_StripExtension(m_sFontName, m_sFontName, sizeof(m_sFontName)); // so we get better error printing if failed to load shader (ie lose ".fontdat") mShader = RE_RegisterShaderNoMip(m_sFontName); FlagNoAsianGlyphs(); @@ -1078,14 +921,11 @@ CFontInfo::CFontInfo(const char *_fontName) m_handle = g_iCurrentFontIndex; g_vFontArray[g_iCurrentFontIndex++] = this; - extern cvar_t *com_buildScript; - if (com_buildScript->integer == 2) - { - Com_Printf( "com_buildScript(2): Registering foreign fonts...\n" ); - static qboolean bDone = qfalse; // Do this once only (for speed)... - if (!bDone) - { + if (com_buildScript->integer == 2) { + Com_Printf("com_buildScript(2): Registering foreign fonts...\n"); + static qboolean bDone = qfalse; // Do this once only (for speed)... + if (!bDone) { bDone = qtrue; char sTemp[MAX_QPATH]; @@ -1096,62 +936,70 @@ CFontInfo::CFontInfo(const char *_fontName) // fileHandle_t f; #ifndef JK2_MODE - for (int i=0; g_SBCSOverrideLanguages[i].m_psName ;i++) - { + for (int i = 0; g_SBCSOverrideLanguages[i].m_psName; i++) { char sTemp[MAX_QPATH]; - sprintf(sTemp,"fonts/%s.tga", g_SBCSOverrideLanguages[i].m_psName ); - ri.FS_FOpenFileRead( sTemp, &f, qfalse ); - if (f) ri.FS_FCloseFile( f ); + sprintf(sTemp, "fonts/%s.tga", g_SBCSOverrideLanguages[i].m_psName); + ri.FS_FOpenFileRead(sTemp, &f, qfalse); + if (f) + ri.FS_FCloseFile(f); - sprintf(sTemp,"fonts/%s.fontdat", g_SBCSOverrideLanguages[i].m_psName ); - ri.FS_FOpenFileRead( sTemp, &f, qfalse ); - if (f) ri.FS_FCloseFile( f ); + sprintf(sTemp, "fonts/%s.fontdat", g_SBCSOverrideLanguages[i].m_psName); + ri.FS_FOpenFileRead(sTemp, &f, qfalse); + if (f) + ri.FS_FCloseFile(f); } #endif // asian MBCS override languages... // #ifdef JK2_MODE - for (int iLang=0; iLang<3; iLang++) + for (int iLang = 0; iLang < 3; iLang++) #else - for (int iLang=0; iLang<5; iLang++) + for (int iLang = 0; iLang < 5; iLang++) #endif { - switch (iLang) - { - case 0: m_iAsianGlyphsAcross = Korean_InitFields (iGlyphTPs, psLang); break; - case 1: m_iAsianGlyphsAcross = Taiwanese_InitFields (iGlyphTPs, psLang); break; - case 2: m_iAsianGlyphsAcross = Japanese_InitFields (iGlyphTPs, psLang); break; + switch (iLang) { + case 0: + m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); + break; + case 1: + m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); + break; + case 2: + m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); + break; #ifndef JK2_MODE - case 3: m_iAsianGlyphsAcross = Chinese_InitFields (iGlyphTPs, psLang); break; - case 4: m_iAsianGlyphsAcross = Thai_InitFields (iGlyphTPs, psLang); + case 3: + m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); + break; + case 4: + m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); { // additional files needed for Thai language... // - ri.FS_FOpenFileRead( sFILENAME_THAI_WIDTHS , &f, qfalse ); + ri.FS_FOpenFileRead(sFILENAME_THAI_WIDTHS, &f, qfalse); if (f) { - ri.FS_FCloseFile( f ); + ri.FS_FCloseFile(f); } - ri.FS_FOpenFileRead( sFILENAME_THAI_CODES, &f, qfalse ); + ri.FS_FOpenFileRead(sFILENAME_THAI_CODES, &f, qfalse); if (f) { - ri.FS_FCloseFile( f ); + ri.FS_FCloseFile(f); } } - break; + break; #endif } - for (int i=0; imodificationCount || !AsianGlyphsAvailable() || bForceReEval) - { - m_iLanguageModificationCount = se_language->modificationCount; + if (m_iLanguageModificationCount != se_language->modificationCount || !AsianGlyphsAvailable() || bForceReEval) { + m_iLanguageModificationCount = se_language->modificationCount; #endif int iGlyphTPs = 0; const char *psLang = NULL; - switch ( eLanguage ) - { - case eKorean: m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); break; - case eTaiwanese: m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); break; - case eJapanese: m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); break; + switch (eLanguage) { + case eKorean: + m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); + break; + case eTaiwanese: + m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); + break; + case eJapanese: + m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); + break; #ifndef JK2_MODE - case eChinese: m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); break; - case eThai: - { - m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); - - if (!m_pThaiData) - { - const char *psFailureReason = g_ThaiCodes.Init(); - if (!psFailureReason[0]) - { - m_pThaiData = &g_ThaiCodes; - } - else - { - // failed to load a needed file, reset to English... - // - ri.Cvar_Set("se_language", "english"); - Com_Error( ERR_DROP, psFailureReason ); - } + case eChinese: + m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); + break; + case eThai: { + m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); + + if (!m_pThaiData) { + const char *psFailureReason = g_ThaiCodes.Init(); + if (!psFailureReason[0]) { + m_pThaiData = &g_ThaiCodes; + } else { + // failed to load a needed file, reset to English... + // + ri.Cvar_Set("se_language", "english"); + Com_Error(ERR_DROP, psFailureReason); } } - break; + } break; #endif - default: + default: break; } // textures need loading... // - if (m_sFontName[0]) - { + if (m_sFontName[0]) { // Use this sometime if we need to do logic to load alternate-height glyphs to better fit other fonts. // (but for now, we just use the one glyph set) // } - for (int i = 0; i < iGlyphTPs; i++) - { + for (int i = 0; i < iGlyphTPs; i++) { // (Note!! assumption for S,T calculations: all Asian glyph textures pages are square except for last one) // char sTemp[MAX_QPATH]; - Com_sprintf(sTemp,sizeof(sTemp), "fonts/%s_%d_1024_%d", psLang, 1024/m_iAsianGlyphsAcross, i); + Com_sprintf(sTemp, sizeof(sTemp), "fonts/%s_%d_1024_%d", psLang, 1024 / m_iAsianGlyphsAcross, i); // // returning 0 here will automatically inhibit Asian glyph calculations at runtime... // - m_hAsianShaders[i] = RE_RegisterShaderNoMip( sTemp ); + m_hAsianShaders[i] = RE_RegisterShaderNoMip(sTemp); } // for now I'm hardwiring these, but if we ever have more than one glyph set per language then they'll be changed... // - m_iAsianPagesLoaded = iGlyphTPs; // not necessarily true, but will be safe, and show up obvious if something missing + m_iAsianPagesLoaded = iGlyphTPs; // not necessarily true, but will be safe, and show up obvious if something missing m_bAsianLastPageHalfHeight = true; bForceReEval = true; } - if (bForceReEval) - { + if (bForceReEval) { // now init the Asian member glyph fields to make them come out the same size as the western ones // that they serve as an alternative for... // - m_AsianGlyph.width = iCappedHeight; // square Asian chars same size as height of western set - m_AsianGlyph.height = iCappedHeight; // "" - switch (eLanguage) - { - default: m_AsianGlyph.horizAdvance = iCappedHeight; break; - case eKorean: m_AsianGlyph.horizAdvance = iCappedHeight - 1;break; // korean has a small amount of space at the edge of the glyph + m_AsianGlyph.width = iCappedHeight; // square Asian chars same size as height of western set + m_AsianGlyph.height = iCappedHeight; // "" + switch (eLanguage) { + default: + m_AsianGlyph.horizAdvance = iCappedHeight; + break; + case eKorean: + m_AsianGlyph.horizAdvance = iCappedHeight - 1; + break; // korean has a small amount of space at the edge of the glyph - case eTaiwanese: - case eJapanese: + case eTaiwanese: + case eJapanese: #ifndef JK2_MODE - case eChinese: + case eChinese: #endif - m_AsianGlyph.horizAdvance = iCappedHeight + 3; // need to force some spacing for these -// case eThai: // this is done dynamically elsewhere, since Thai glyphs are variable width + m_AsianGlyph.horizAdvance = iCappedHeight + 3; // need to force some spacing for these + // case eThai: // this is done dynamically elsewhere, since Thai glyphs are variable width } - m_AsianGlyph.horizOffset = 0; // "" - m_AsianGlyph.baseline = mAscender + ((iCappedHeight - mHeight) >> 1); + m_AsianGlyph.horizOffset = 0; // "" + m_AsianGlyph.baseline = mAscender + ((iCappedHeight - mHeight) >> 1); } - } - else - { + } else { // not using Asian... // FlagNoAsianGlyphs(); } - } - else - { + } else { // no western glyphs available, so don't attempt to match asian... // FlagNoAsianGlyphs(); } } -static CFontInfo *GetFont_Actual(int index) -{ +static CFontInfo *GetFont_Actual(int index) { index &= SET_MASK; - if((index >= 1) && (index < g_iCurrentFontIndex)) - { + if ((index >= 1) && (index < g_iCurrentFontIndex)) { CFontInfo *pFont = g_vFontArray[index]; - if (pFont) - { + if (pFont) { pFont->UpdateAsianIfNeeded(); } return pFont; } - return(NULL); + return (NULL); } static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { @@ -1330,8 +1161,7 @@ static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { if (variants > 0) { CFontInfo *variant; - int requestedSize = font->GetPointSize() * *scale * - r_fontSharpness->value * (glConfig.vidHeight / SCREEN_HEIGHT); + int requestedSize = font->GetPointSize() * *scale * r_fontSharpness->value * (glConfig.vidHeight / SCREEN_HEIGHT); if (requestedSize <= font->GetPointSize()) return font; @@ -1353,131 +1183,115 @@ static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { // needed to add *piShader param because of multiple TPs, // if not passed in, then I also skip S,T calculations for re-usable static asian glyphinfo struct... // -const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShader /* = NULL */) -{ - if ( AsianGlyphsAvailable() ) - { - int iCollapsedAsianCode = GetCollapsedAsianCode( uiLetter ); - if (iCollapsedAsianCode) - { - if (piShader) - { +const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShader /* = NULL */) { + if (AsianGlyphsAvailable()) { + int iCollapsedAsianCode = GetCollapsedAsianCode(uiLetter); + if (iCollapsedAsianCode) { + if (piShader) { // (Note!! assumption for S,T calculations: all asian glyph textures pages are square except for last one // which may or may not be half height) - but not for Thai // int iTexturePageIndex = iCollapsedAsianCode / (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); - if (iTexturePageIndex > m_iAsianPagesLoaded) - { - assert(0); // should never happen + if (iTexturePageIndex > m_iAsianPagesLoaded) { + assert(0); // should never happen iTexturePageIndex = 0; } #ifndef JK2_MODE - int iOriginalCollapsedAsianCode = iCollapsedAsianCode; // need to back this up (if Thai) for later + int iOriginalCollapsedAsianCode = iCollapsedAsianCode; // need to back this up (if Thai) for later #endif - iCollapsedAsianCode -= iTexturePageIndex * (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); + iCollapsedAsianCode -= iTexturePageIndex * (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); - const int iColumn = iCollapsedAsianCode % m_iAsianGlyphsAcross; - const int iRow = iCollapsedAsianCode / m_iAsianGlyphsAcross; - const bool bHalfT = (iTexturePageIndex == (m_iAsianPagesLoaded - 1) && m_bAsianLastPageHalfHeight); + const int iColumn = iCollapsedAsianCode % m_iAsianGlyphsAcross; + const int iRow = iCollapsedAsianCode / m_iAsianGlyphsAcross; + const bool bHalfT = (iTexturePageIndex == (m_iAsianPagesLoaded - 1) && m_bAsianLastPageHalfHeight); const int iAsianGlyphsDown = (bHalfT) ? m_iAsianGlyphsAcross / 2 : m_iAsianGlyphsAcross; - switch ( GetLanguageEnum() ) - { - case eKorean: - default: - { - m_AsianGlyph.s = (float)( iColumn ) / (float)m_iAsianGlyphsAcross; - m_AsianGlyph.t = (float)( iRow ) / (float) iAsianGlyphsDown; - m_AsianGlyph.s2 = (float)( iColumn + 1) / (float)m_iAsianGlyphsAcross; - m_AsianGlyph.t2 = (float)( iRow + 1 ) / (float) iAsianGlyphsDown; - } - break; - - case eTaiwanese: - { - m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn ))+1) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow ))+1) / 1024.0f; - m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn+1 )) ) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 )) ) / 1024.0f; - } - break; - - case eJapanese: + switch (GetLanguageEnum()) { + case eKorean: + default: { + m_AsianGlyph.s = (float)(iColumn) / (float)m_iAsianGlyphsAcross; + m_AsianGlyph.t = (float)(iRow) / (float)iAsianGlyphsDown; + m_AsianGlyph.s2 = (float)(iColumn + 1) / (float)m_iAsianGlyphsAcross; + m_AsianGlyph.t2 = (float)(iRow + 1) / (float)iAsianGlyphsDown; + } break; + + case eTaiwanese: { + m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn)) + 1) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow)) + 1) / 1024.0f; + m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn + 1))) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1))) / 1024.0f; + } break; + + case eJapanese: #ifndef JK2_MODE - case eChinese: + case eChinese: #endif - { - m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn )) ) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow )) ) / 1024.0f; - m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn+1 ))-1) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 ))-1) / 1024.0f; - } - break; + { + m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn))) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow))) / 1024.0f; + m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn + 1)) - 1) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1)) - 1) / 1024.0f; + } break; #ifndef JK2_MODE - case eThai: - { - int iGlyphXpos = (1024 / m_iAsianGlyphsAcross) * ( iColumn ); - int iGlyphWidth = g_ThaiCodes.GetWidth( iOriginalCollapsedAsianCode ); + case eThai: { + int iGlyphXpos = (1024 / m_iAsianGlyphsAcross) * (iColumn); + int iGlyphWidth = g_ThaiCodes.GetWidth(iOriginalCollapsedAsianCode); - // very thai-specific language-code... - // - if (uiLetter == TIS_SARA_AM) - { - iGlyphXpos += 9; // these are pixel coords on the source TP, so don't affect scaled output - iGlyphWidth= 20; // - } - m_AsianGlyph.s = (float)(iGlyphXpos) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow )) ) / 1024.0f; - // technically this .s2 line should be modified to blit only the correct width, but since - // all Thai glyphs are up against the left edge of their cells and have blank to the cell - // boundary then it's better to keep these calculations simpler... + // very thai-specific language-code... + // + if (uiLetter == TIS_SARA_AM) { + iGlyphXpos += 9; // these are pixel coords on the source TP, so don't affect scaled output + iGlyphWidth = 20; // + } + m_AsianGlyph.s = (float)(iGlyphXpos) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow))) / 1024.0f; + // technically this .s2 line should be modified to blit only the correct width, but since + // all Thai glyphs are up against the left edge of their cells and have blank to the cell + // boundary then it's better to keep these calculations simpler... - m_AsianGlyph.s2 = (float)(iGlyphXpos+iGlyphWidth) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 ))-1) / 1024.0f; + m_AsianGlyph.s2 = (float)(iGlyphXpos + iGlyphWidth) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1)) - 1) / 1024.0f; - // special addition for Thai, need to bodge up the width and advance fields... - // - m_AsianGlyph.width = iGlyphWidth; - m_AsianGlyph.horizAdvance = iGlyphWidth + 1; - } - break; + // special addition for Thai, need to bodge up the width and advance fields... + // + m_AsianGlyph.width = iGlyphWidth; + m_AsianGlyph.horizAdvance = iGlyphWidth + 1; + } break; #endif } - *piShader = m_hAsianShaders[ iTexturePageIndex ]; + *piShader = m_hAsianShaders[iTexturePageIndex]; } return &m_AsianGlyph; } } - if (piShader) - { + if (piShader) { *piShader = GetShader(); } - const glyphInfo_t *pGlyph = &mGlyphs[ uiLetter & 0xff ]; + const glyphInfo_t *pGlyph = &mGlyphs[uiLetter & 0xff]; // // SBCS language substitution?... // #ifndef JK2_MODE - if ( m_fAltSBCSFontScaleFactor != -1 ) - { + if (m_fAltSBCSFontScaleFactor != -1) { // sod it, use the asian glyph, that's fine... // - memcpy(&m_AsianGlyph,pGlyph,sizeof(m_AsianGlyph)); // *before* changin pGlyph! + memcpy(&m_AsianGlyph, pGlyph, sizeof(m_AsianGlyph)); // *before* changin pGlyph! -// CFontInfo *pOriginalFont = GetFont_Actual( this->m_iOriginalFontWhenSBCSOverriden ); -// pGlyph = &pOriginalFont->mGlyphs[ uiLetter & 0xff ]; + // CFontInfo *pOriginalFont = GetFont_Actual( this->m_iOriginalFontWhenSBCSOverriden ); + // pGlyph = &pOriginalFont->mGlyphs[ uiLetter & 0xff ]; - #define ASSIGN_WITH_ROUNDING(_dst,_src) _dst = mbRoundCalcs ? Round( m_fAltSBCSFontScaleFactor * _src ) : m_fAltSBCSFontScaleFactor * (float)_src; +#define ASSIGN_WITH_ROUNDING(_dst, _src) _dst = mbRoundCalcs ? Round(m_fAltSBCSFontScaleFactor * _src) : m_fAltSBCSFontScaleFactor * (float)_src; - ASSIGN_WITH_ROUNDING( m_AsianGlyph.baseline, pGlyph->baseline ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.height, pGlyph->height ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.horizAdvance,pGlyph->horizAdvance ); -// m_AsianGlyph.horizOffset = /*Round*/( m_fAltSBCSFontScaleFactor * pGlyph->horizOffset ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.width, pGlyph->width ); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.baseline, pGlyph->baseline); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.height, pGlyph->height); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.horizAdvance, pGlyph->horizAdvance); + // m_AsianGlyph.horizOffset = /*Round*/( m_fAltSBCSFontScaleFactor * pGlyph->horizOffset ); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.width, pGlyph->width); pGlyph = &m_AsianGlyph; } @@ -1486,72 +1300,76 @@ const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShad return pGlyph; } -const int CFontInfo::GetCollapsedAsianCode(ulong uiLetter) const -{ +const int CFontInfo::GetCollapsedAsianCode(ulong uiLetter) const { int iCollapsedAsianCode = 0; - if (AsianGlyphsAvailable()) - { - switch ( GetLanguageEnum() ) - { - case eKorean: iCollapsedAsianCode = Korean_CollapseKSC5601HangulCode( uiLetter ); break; - case eTaiwanese: iCollapsedAsianCode = Taiwanese_CollapseBig5Code( uiLetter ); break; - case eJapanese: iCollapsedAsianCode = Japanese_CollapseShiftJISCode( uiLetter ); break; + if (AsianGlyphsAvailable()) { + switch (GetLanguageEnum()) { + case eKorean: + iCollapsedAsianCode = Korean_CollapseKSC5601HangulCode(uiLetter); + break; + case eTaiwanese: + iCollapsedAsianCode = Taiwanese_CollapseBig5Code(uiLetter); + break; + case eJapanese: + iCollapsedAsianCode = Japanese_CollapseShiftJISCode(uiLetter); + break; #ifndef JK2_MODE - case eChinese: iCollapsedAsianCode = Chinese_CollapseGBCode( uiLetter ); break; - case eThai: iCollapsedAsianCode = Thai_CollapseTISCode( uiLetter ); break; + case eChinese: + iCollapsedAsianCode = Chinese_CollapseGBCode(uiLetter); + break; + case eThai: + iCollapsedAsianCode = Thai_CollapseTISCode(uiLetter); + break; #endif - default: assert(0); /* unhandled asian language */ break; + default: + assert(0); /* unhandled asian language */ + break; } } return iCollapsedAsianCode; } -const int CFontInfo::GetLetterWidth(unsigned int uiLetter) -{ - const glyphInfo_t *pGlyph = GetLetter( uiLetter ); +const int CFontInfo::GetLetterWidth(unsigned int uiLetter) { + const glyphInfo_t *pGlyph = GetLetter(uiLetter); return pGlyph->width ? pGlyph->width : mGlyphs[(unsigned)'.'].width; } -const int CFontInfo::GetLetterHorizAdvance(unsigned int uiLetter) -{ - const glyphInfo_t *pGlyph = GetLetter( uiLetter ); +const int CFontInfo::GetLetterHorizAdvance(unsigned int uiLetter) { + const glyphInfo_t *pGlyph = GetLetter(uiLetter); return pGlyph->horizAdvance ? pGlyph->horizAdvance : mGlyphs[(unsigned)'.'].horizAdvance; } // ensure any GetFont calls that need SBCS overriding (such as when playing in Russian) have the appropriate stuff done... // #ifndef JK2_MODE -static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBCS, const char *psLanguageNameSBCS ) -{ - if ( !pFont->m_bIsFakeAlienLanguage ) - { - if ( GetLanguageEnum() == eLanguageSBCS ) - { - if ( pFont->m_iAltSBCSFont == -1 ) // no reg attempted yet? +static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBCS, const char *psLanguageNameSBCS) { + if (!pFont->m_bIsFakeAlienLanguage) { + if (GetLanguageEnum() == eLanguageSBCS) { + if (pFont->m_iAltSBCSFont == -1) // no reg attempted yet? { // need to register this alternative SBCS font... // - int iAltFontIndex = RE_RegisterFont( va("%s/%s",COM_SkipPath(pFont->m_sFontName),psLanguageNameSBCS) ); // ensure unique name (eg: "lcd/russian") - CFontInfo *pAltFont = GetFont_Actual( iAltFontIndex ); - if ( pAltFont ) - { + int iAltFontIndex = + RE_RegisterFont(va("%s/%s", COM_SkipPath(pFont->m_sFontName), psLanguageNameSBCS)); // ensure unique name (eg: "lcd/russian") + CFontInfo *pAltFont = GetFont_Actual(iAltFontIndex); + if (pAltFont) { // work out the scaling factor for this font's glyphs...( round it to 1 decimal place to cut down on silly scale factors like 0.53125 ) // pAltFont->m_fAltSBCSFontScaleFactor = RoundTenth((float)pFont->GetPointSize() / (float)pAltFont->GetPointSize()); // // then override with the main properties of the original font... // - pAltFont->mPointSize = pFont->GetPointSize();//(float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mHeight = pFont->GetHeight();//(float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mAscender = pFont->GetAscender();//(float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mDescender = pFont->GetDescender();//(float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mPointSize = pFont->GetPointSize(); //(float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mHeight = pFont->GetHeight(); //(float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mAscender = pFont->GetAscender(); //(float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mDescender = pFont->GetDescender(); //(float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mPointSize = (float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mHeight = (float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mAscender = (float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mDescender = (float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mPointSize = (float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mHeight = (float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mAscender = (float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mDescender = (float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; pAltFont->mbRoundCalcs = true; pAltFont->m_iOriginalFontWhenSBCSOverriden = pFont->m_iThisFont; @@ -1559,9 +1377,8 @@ static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBC pFont->m_iAltSBCSFont = iAltFontIndex; } - if ( pFont->m_iAltSBCSFont > 0) - { - return GetFont_Actual( pFont->m_iAltSBCSFont ); + if (pFont->m_iAltSBCSFont > 0) { + return GetFont_Actual(pFont->m_iAltSBCSFont); } } } @@ -1570,22 +1387,16 @@ static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBC } #endif - - -CFontInfo *GetFont(int index) -{ - CFontInfo *pFont = GetFont_Actual( index ); +CFontInfo *GetFont(int index) { + CFontInfo *pFont = GetFont_Actual(index); #ifndef JK2_MODE - if (pFont) - { + if (pFont) { // any SBCS overrides? (this has to be pretty quick, and is (sort of))... // - for (int i=0; g_SBCSOverrideLanguages[i].m_psName; i++) - { - CFontInfo *pAltFont = GetFont_SBCSOverride( pFont, g_SBCSOverrideLanguages[i].m_eLanguage, g_SBCSOverrideLanguages[i].m_psName ); - if (pAltFont) - { + for (int i = 0; g_SBCSOverrideLanguages[i].m_psName; i++) { + CFontInfo *pAltFont = GetFont_SBCSOverride(pFont, g_SBCSOverrideLanguages[i].m_eLanguage, g_SBCSOverrideLanguages[i].m_psName); + if (pAltFont) { return pAltFont; } } @@ -1595,44 +1406,35 @@ CFontInfo *GetFont(int index) return pFont; } - -int RE_Font_StrLenPixels(const char *psText, const int iFontHandle, const float fScaleIn) -{ +int RE_Font_StrLenPixels(const char *psText, const int iFontHandle, const float fScaleIn) { float fScale = fScaleIn; #ifdef JK2_MODE // Yes..even this func is a little different, to the point where it doesn't work. --eez - float fMaxWidth = 0.0f; - float fThisWidth = 0.0f; - CFontInfo *curfont; + float fMaxWidth = 0.0f; + float fThisWidth = 0.0f; + CFontInfo *curfont; curfont = GetFont(iFontHandle); - if(!curfont) - { - return(0); + if (!curfont) { + return (0); } curfont = RE_Font_GetVariant(curfont, &fScale); float fScaleAsian = fScale; - if (Language_IsAsian() && fScale > 0.7f ) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; } - while(*psText) - { - unsigned int uiLetter = AnyLanguage_ReadCharFromString( (char **)&psText ); - if (uiLetter == 0x0A) - { + while (*psText) { + unsigned int uiLetter = AnyLanguage_ReadCharFromString((char **)&psText); + if (uiLetter == 0x0A) { fThisWidth = 0.0f; - } - else - { - int iPixelAdvance = curfont->GetLetterHorizAdvance( uiLetter ); + } else { + int iPixelAdvance = curfont->GetLetterHorizAdvance(uiLetter); float fValue = iPixelAdvance * ((uiLetter > 255) ? fScaleAsian : fScale); - fThisWidth += curfont->mbRoundCalcs ? Round( fValue ) : fValue; - if (fThisWidth > fMaxWidth) - { + fThisWidth += curfont->mbRoundCalcs ? Round(fValue) : fValue; + if (fThisWidth > fMaxWidth) { fMaxWidth = fThisWidth; } } @@ -1641,52 +1443,42 @@ int RE_Font_StrLenPixels(const char *psText, const int iFontHandle, const float // using ceil because we need to make sure that all the text is contained within the integer pixel width we're returning return (int)ceilf(fMaxWidth); #else - float fMaxWidth = 0.0f; - float fThisWidth = 0.0f; - CFontInfo *curfont; + float fMaxWidth = 0.0f; + float fThisWidth = 0.0f; + CFontInfo *curfont; curfont = GetFont(iFontHandle); - if(!curfont) - { - return(0); + if (!curfont) { + return (0); } curfont = RE_Font_GetVariant(curfont, &fScale); float fScaleAsian = fScale; - if (Language_IsAsian() && fScale > 0.7f ) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; } - while(*psText) - { + while (*psText) { int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( (char *)psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString((char *)psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - if (uiLetter == '^' ) - { - if (*psText >= '0' && - *psText <= '9') - { - uiLetter = AnyLanguage_ReadCharFromString( (char *)psText, &iAdvanceCount, NULL ); + if (uiLetter == '^') { + if (*psText >= '0' && *psText <= '9') { + uiLetter = AnyLanguage_ReadCharFromString((char *)psText, &iAdvanceCount, NULL); psText += iAdvanceCount; continue; } } - if (uiLetter == 0x0A) - { + if (uiLetter == 0x0A) { fThisWidth = 0.0f; - } - else - { - int iPixelAdvance = curfont->GetLetterHorizAdvance( uiLetter ); + } else { + int iPixelAdvance = curfont->GetLetterHorizAdvance(uiLetter); float fValue = iPixelAdvance * ((uiLetter > (unsigned)g_iNonScaledCharRange) ? fScaleAsian : fScale); - fThisWidth += curfont->mbRoundCalcs ? Round( fValue ) : fValue; - if (fThisWidth > fMaxWidth) - { + fThisWidth += curfont->mbRoundCalcs ? Round(fValue) : fValue; + if (fThisWidth > fMaxWidth) { fMaxWidth = fThisWidth; } } @@ -1699,107 +1491,107 @@ int RE_Font_StrLenPixels(const char *psText, const int iFontHandle, const float // not really a font function, but keeps naming consistant... // -int RE_Font_StrLenChars(const char *psText) -{ +int RE_Font_StrLenChars(const char *psText) { // logic for this function's letter counting must be kept same in this function and RE_Font_DrawString() // int iCharCount = 0; - while ( *psText ) - { + while (*psText) { // in other words, colour codes and CR/LF don't count as chars, all else does... // int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( (char *)psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString((char *)psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - switch (uiLetter) - { - case '^': - if (*psText >= '0' && - *psText <= '9') - { - psText++; - } - else - { - iCharCount++; - } - break; // colour code (note next-char skip) - case 10: break; // linefeed - case 13: break; // return + switch (uiLetter) { + case '^': + if (*psText >= '0' && *psText <= '9') { + psText++; + } else { + iCharCount++; + } + break; // colour code (note next-char skip) + case 10: + break; // linefeed + case 13: + break; // return #ifndef JK2_MODE - case '_': iCharCount += (GetLanguageEnum() == eThai && (((unsigned char *)psText)[0] >= TIS_GLYPHS_START))?0:1; break; // special word-break hack + case '_': + iCharCount += (GetLanguageEnum() == eThai && (((unsigned char *)psText)[0] >= TIS_GLYPHS_START)) ? 0 : 1; + break; // special word-break hack #endif - default: iCharCount++; break; + default: + iCharCount++; + break; } } return iCharCount; } -int RE_Font_HeightPixels(const int iFontHandle, const float fScaleIn) -{ +int RE_Font_HeightPixels(const int iFontHandle, const float fScaleIn) { float fScale = fScaleIn; - CFontInfo *curfont; + CFontInfo *curfont; curfont = GetFont(iFontHandle); - if(curfont) - { + if (curfont) { float fValue; curfont = RE_Font_GetVariant(curfont, &fScale); fValue = curfont->GetPointSize() * fScale; return curfont->mbRoundCalcs ? Round(fValue) : fValue; } - return(0); + return (0); } // iMaxPixelWidth is -1 for "all of string", else pixel display count... // -void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, const int iFontHandleIn, int iMaxPixelWidth, const float fScaleIn) -{ +void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, const int iFontHandleIn, int iMaxPixelWidth, const float fScaleIn) { int iFontHandle = iFontHandleIn; float fScale = fScaleIn; // HAAAAAAAAAAAAAAAX..fix me please --eez #ifdef JK2_MODE - static qboolean gbInShadow = qfalse; // MUST default to this - float fox, foy, fx, fy; - int colour, offset; - const glyphInfo_t *pLetter; - qhandle_t hShader; + static qboolean gbInShadow = qfalse; // MUST default to this + float fox, foy, fx, fy; + int colour, offset; + const glyphInfo_t *pLetter; + qhandle_t hShader; - assert (psText); + assert(psText); - if(iFontHandle & STYLE_BLINK) - { - if((ri.Milliseconds() >> 7) & 1) - { + if (iFontHandle & STYLE_BLINK) { + if ((ri.Milliseconds() >> 7) & 1) { return; } } -/* if (Language_IsTaiwanese()) - { - psText = "Wp:\B6}\B7F\A7a \BFp\B7G\B4\B5\A1A\A7Ʊ\E6\A7A\B9\B3\A5L\ADÌ»\A1\AA\BA\A4@\BC˦\E6\A1C"; - } - else - if (Language_IsKorean()) - { - psText = "Wp:\BC\EEŸ\C0\D3\C0Ì´\D9 \B8Ö¸\B0. \B1×µ\E9\C0\CC \B8\BB\C7Ñ´\EB\B7\CE \B3×°\A1 \C0\DF\C7\D2\C1\F6 \B1\E2\B4\EB\C7Ï°Ú´\D9."; - } - else - if (Language_IsJapanese()) - { - char sBlah[200]; - sprintf(sBlah,va("%c%c %c%c %c%c %c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); - psText = &sBlah[0]; - //psText = \A1@\A1A\A1B\A1C\A1D\A1E\A1F\A1G\A1H\A1I\A1J\A1K\A1L\A1M\A1N\A1O\A1P\A1Q\A1R\A1S\A1T\A1U\A1V\A1W\A1X\A1Y\A1Z\A1[\A1\\A1]\A1^\A1_\A1`\A1a\A1b\A1c\A1d\A1e\A1f\A1g\A1h\A1i\A1j\A1k\A1l\A1m\A1n\A1o\A1p\A1q\A1r\A1s\A1t\A1u\A1v\A1w\A1x\A1y\A1z\A1{\A1|\A1}\A1~ \A1\A1\A1\A2\A1\A3\A1\A4\A1\A5\A1\A6\A1\A7\A1\A8\A1\A9\A1\AA\A1\AB\A1\AC\A1\AD\A1\AE\A1\AF\A1\B0\A1\B1\A1\B2\A1\B3\A1\B4\A1\B5\A1\B6\A1\B7\A1\B8\A1\B9\A1\BA\A1\BB\A1\BC\A1\BD\A1\BE\A1\BF\A1\C0\A1\C1\A1¡áġšơǡȡɡʡˡ̡͡ΡϡСѡҡӡԡա֡סء١ڡۡܡݡޡߡ\E0\A1\E1\A1\E2\A1\E3\A1\E4\A1\E5\A1\E6\A1\E7\A1\E8\A1\E9\A1\EA\A1\EB\A1\EC\A1\ED\A1\EE\A1\EF\A1\F0\A1\F1\A1\F2\A1\F3\A1\F4\A1\F5\A1\F6\A1\F7\A1\F8\A1\F9\A1\FA\A1\FB\A1\FC\A1\FD\A1\FE 1\A2@\A2A\A2B\A2C\A2D\A2E\A2F\A2G\A2H\A2I\A2J\A2K\A2L\A2M\A2N\A2O\A2P\A2Q\A2R\A2S\A2T\A2U\A2V\A2W\A2X\A2Y\A2Z\A2[\A2\\A2]\A2^\A2_\A2`\A2a\A2b\A2c\A2d\A2e\A2f\A2g\A2h\A2i\A2j\A2k\A2l\A2m\A2n\A2o\A2p\A2q\A2r\A2s\A2t\A2u\A2v\A2w\A2x\A2y\A2z\A2{\A2|\A2}\A2~ \A2\A1\A2\A2\A2\A3\A2\A4\A2\A5\A2\A6\A2\A7\A2\A8\A2\A9\A2\AA\A2\AB\A2\AC\A2\AD\A2\AE\A2\AF\A2\B0\A2\B1\A2\B2\A2\B3\A2\B4\A2\B5\A2\B6\A2\B7\A2\B8\A2\B9\A2\BA\A2\BB\A2\BC\A2\BD\A2\BE\A2\BF\A2\C0\A2\C1\A2¢âĢŢƢǢȢɢʢˢ̢͢΢ϢТѢҢӢԢբ֢עآ٢ڢۢܢݢޢߢ\E0\A2\E1\A2\E2\A2\E3\A2\E4\A2\E5\A2\E6\A2\E7\A2\E8\A2\E9\A2\EA\A2\EB\A2\EC\A2\ED\A2\EE\A2\EF\A2\F0\A2\F1\A2\F2\A2\F3\A2\F4\A2\F5\A2\F6\A2\F7\A2\F8\A2\F9\A2\FA\A2\FB\A2\FC\A2\FD\A2\FE 2\A3@\A3A\A3B\A3C\A3D\A3E\A3F\A3G\A3H\A3I\A3J\A3K\A3L\A3M\A3N\A3O\A3P\A3Q\A3R\A3S\A3T\A3U\A3V\A3W\A3X\A3Y\A3Z\A3[\A3\\A3]\A3^\A3_\A3`\A3a\A3b\A3c\A3d\A3e\A3f\A3g\A3h\A3i\A3j\A3k\A3l\A3m\A3n\A3o\A3p\A3q\A3r\A3s\A3t\A3u\A3v\A3w\A3x\A3y\A3z\A3{\A3|\A3}\A3~ \A3\A1\A3\A2\A3\A3\A3\A4\A3\A5\A3\A6\A3\A7\A3\A8\A3\A9\A3\AA\A3\AB\A3\AC\A3\AD\A3\AE\A3\AF\A3\B0\A3\B1\A3\B2\A3\B3\A3\B4\A3\B5\A3\B6\A3\B7\A3\B8\A3\B9\A3\BA\A3\BB\A3\BC\A3\BD\A3\BE\A3\BF\A3\C0\A3\C1\A3£ãģţƣǣȣɣʣˣ̣ͣΣϣУѣңӣԣգ֣ףأ٣ڣۣܣݣޣߣ\E0\A3\E1\A3\E2\A3\E3\A3\E4\A3\E5\A3\E6\A3\E7\A3\E8\A3\E9\A3\EA\A3\EB\A3\EC\A3\ED\A3\EE\A3\EF\A3\F0\A3\F1\A3\F2\A3\F3\A3\F4\A3\F5\A3\F6\A3\F7\A3\F8\A3\F9\A3\FA\A3\FB\A3\FC\A3\FD\A3\FE 3\A4@\A4A\A4B\A4C\A4D\A4E\A4F\A4G\A4H\A4I\A4J\A4K\A4L\A4M\A4N\A4O\A4P\A4Q\A4R\A4S\A4T\A4U\A4V\A4W\A4X\A4Y\A4Z\A4[\A4\\A4]\A4^\A4 - } -*/ + /* if (Language_IsTaiwanese()) + { + psText = "Wp:\B6}\B7F\A7a \BFp\B7G\B4\B5\A1A\A7Ʊ\E6\A7A\B9\B3\A5L\ADÌ»\A1\AA\BA\A4@\BC˦\E6\A1C"; + } + else + if (Language_IsKorean()) + { + psText = "Wp:\BC\EEŸ\C0\D3\C0Ì´\D9 \B8Ö¸\B0. \B1×µ\E9\C0\CC \B8\BB\C7Ñ´\EB\B7\CE \B3×°\A1 \C0\DF\C7\D2\C1\F6 \B1\E2\B4\EB\C7Ï°Ú´\D9."; + } + else + if (Language_IsJapanese()) + { + char sBlah[200]; + sprintf(sBlah,va("%c%c %c%c %c%c %c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); + psText = &sBlah[0]; + //psText = + \A1@\A1A\A1B\A1C\A1D\A1E\A1F\A1G\A1H\A1I\A1J\A1K\A1L\A1M\A1N\A1O\A1P\A1Q\A1R\A1S\A1T\A1U\A1V\A1W\A1X\A1Y\A1Z\A1[\A1\\A1]\A1^\A1_\A1`\A1a\A1b\A1c\A1d\A1e\A1f\A1g\A1h\A1i\A1j\A1k\A1l\A1m\A1n\A1o\A1p\A1q\A1r\A1s\A1t\A1u\A1v\A1w\A1x\A1y\A1z\A1{\A1|\A1}\A1~ + \A1\A1\A1\A2\A1\A3\A1\A4\A1\A5\A1\A6\A1\A7\A1\A8\A1\A9\A1\AA\A1\AB\A1\AC\A1\AD\A1\AE\A1\AF\A1\B0\A1\B1\A1\B2\A1\B3\A1\B4\A1\B5\A1\B6\A1\B7\A1\B8\A1\B9\A1\BA\A1\BB\A1\BC\A1\BD\A1\BE\A1\BF\A1\C0\A1\C1\A1¡áġšơǡȡɡʡˡ̡͡ΡϡСѡҡӡԡա֡סء١ڡۡܡݡޡߡ\E0\A1\E1\A1\E2\A1\E3\A1\E4\A1\E5\A1\E6\A1\E7\A1\E8\A1\E9\A1\EA\A1\EB\A1\EC\A1\ED\A1\EE\A1\EF\A1\F0\A1\F1\A1\F2\A1\F3\A1\F4\A1\F5\A1\F6\A1\F7\A1\F8\A1\F9\A1\FA\A1\FB\A1\FC\A1\FD\A1\FE + 1\A2@\A2A\A2B\A2C\A2D\A2E\A2F\A2G\A2H\A2I\A2J\A2K\A2L\A2M\A2N\A2O\A2P\A2Q\A2R\A2S\A2T\A2U\A2V\A2W\A2X\A2Y\A2Z\A2[\A2\\A2]\A2^\A2_\A2`\A2a\A2b\A2c\A2d\A2e\A2f\A2g\A2h\A2i\A2j\A2k\A2l\A2m\A2n\A2o\A2p\A2q\A2r\A2s\A2t\A2u\A2v\A2w\A2x\A2y\A2z\A2{\A2|\A2}\A2~ + \A2\A1\A2\A2\A2\A3\A2\A4\A2\A5\A2\A6\A2\A7\A2\A8\A2\A9\A2\AA\A2\AB\A2\AC\A2\AD\A2\AE\A2\AF\A2\B0\A2\B1\A2\B2\A2\B3\A2\B4\A2\B5\A2\B6\A2\B7\A2\B8\A2\B9\A2\BA\A2\BB\A2\BC\A2\BD\A2\BE\A2\BF\A2\C0\A2\C1\A2¢âĢŢƢǢȢɢʢˢ̢͢΢ϢТѢҢӢԢբ֢עآ٢ڢۢܢݢޢߢ\E0\A2\E1\A2\E2\A2\E3\A2\E4\A2\E5\A2\E6\A2\E7\A2\E8\A2\E9\A2\EA\A2\EB\A2\EC\A2\ED\A2\EE\A2\EF\A2\F0\A2\F1\A2\F2\A2\F3\A2\F4\A2\F5\A2\F6\A2\F7\A2\F8\A2\F9\A2\FA\A2\FB\A2\FC\A2\FD\A2\FE + 2\A3@\A3A\A3B\A3C\A3D\A3E\A3F\A3G\A3H\A3I\A3J\A3K\A3L\A3M\A3N\A3O\A3P\A3Q\A3R\A3S\A3T\A3U\A3V\A3W\A3X\A3Y\A3Z\A3[\A3\\A3]\A3^\A3_\A3`\A3a\A3b\A3c\A3d\A3e\A3f\A3g\A3h\A3i\A3j\A3k\A3l\A3m\A3n\A3o\A3p\A3q\A3r\A3s\A3t\A3u\A3v\A3w\A3x\A3y\A3z\A3{\A3|\A3}\A3~ + \A3\A1\A3\A2\A3\A3\A3\A4\A3\A5\A3\A6\A3\A7\A3\A8\A3\A9\A3\AA\A3\AB\A3\AC\A3\AD\A3\AE\A3\AF\A3\B0\A3\B1\A3\B2\A3\B3\A3\B4\A3\B5\A3\B6\A3\B7\A3\B8\A3\B9\A3\BA\A3\BB\A3\BC\A3\BD\A3\BE\A3\BF\A3\C0\A3\C1\A3£ãģţƣǣȣɣʣˣ̣ͣΣϣУѣңӣԣգ֣ףأ٣ڣۣܣݣޣߣ\E0\A3\E1\A3\E2\A3\E3\A3\E4\A3\E5\A3\E6\A3\E7\A3\E8\A3\E9\A3\EA\A3\EB\A3\EC\A3\ED\A3\EE\A3\EF\A3\F0\A3\F1\A3\F2\A3\F3\A3\F4\A3\F5\A3\F6\A3\F7\A3\F8\A3\F9\A3\FA\A3\FB\A3\FC\A3\FD\A3\FE + 3\A4@\A4A\A4B\A4C\A4D\A4E\A4F\A4G\A4H\A4I\A4J\A4K\A4L\A4M\A4N\A4O\A4P\A4Q\A4R\A4S\A4T\A4U\A4V\A4W\A4X\A4Y\A4Z\A4[\A4\\A4]\A4^\A4 + } + */ CFontInfo *curfont = GetFont(iFontHandle); - if(!curfont) - { + if (!curfont) { return; } curfont = RE_Font_GetVariant(curfont, &fScale); @@ -1807,25 +1599,23 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c float fScaleAsian = fScale; float fAsianYAdjust = 0.0f; - if (Language_IsAsian() && fScale > 0.7f) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; fAsianYAdjust = ((curfont->GetPointSize() * fScale) - (curfont->GetPointSize() * fScaleAsian)) / 2.0f; } // Draw a dropshadow if required - if(iFontHandle & STYLE_DROPSHADOW) - { + if (iFontHandle & STYLE_DROPSHADOW) { offset = Round(curfont->GetPointSize() * fScale * 0.075f); - const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba?rgba[3]:1.0f}; + const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba ? rgba[3] : 1.0f}; gbInShadow = qtrue; RE_Font_DrawString(ox + offset, oy + offset, psText, v4DKGREY2, iFontHandle & SET_MASK, iMaxPixelWidth, fScale); gbInShadow = qfalse; } - RE_SetColor( rgba ); + RE_SetColor(rgba); // Now we take off the training wheels and become a big font renderer // It's all floats from here on out @@ -1833,147 +1623,133 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c foy = oy; fx = fox; - foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; + foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) + : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; qboolean bNextTextWouldOverflow = qfalse; - while (*psText && !bNextTextWouldOverflow) - { - unsigned int uiLetter = AnyLanguage_ReadCharFromString((char **)&psText); // 'psText' ptr has been advanced now - switch( uiLetter ) - { + while (*psText && !bNextTextWouldOverflow) { + unsigned int uiLetter = AnyLanguage_ReadCharFromString((char **)&psText); // 'psText' ptr has been advanced now + switch (uiLetter) { case '^': - if (*psText >= '0' && - *psText <= '9') - { + if (*psText >= '0' && *psText <= '9') { colour = ColorIndex(*psText++); - if (!gbInShadow) - { + if (!gbInShadow) { vec4_t color; - Com_Memcpy( color, g_color_table[colour], sizeof( color ) ); + Com_Memcpy(color, g_color_table[colour], sizeof(color)); color[3] = rgba ? rgba[3] : 1.0f; - RE_SetColor( color ); + RE_SetColor(color); } } break; - case 10: //linefeed + case 10: // linefeed fx = fox; foy += curfont->mbRoundCalcs ? Round(curfont->GetPointSize() * fScale) : curfont->GetPointSize() * fScale; - if (Language_IsAsian()) - { - foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder functions + if (Language_IsAsian()) { + foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder + // functions } break; - case 13: // Return + case 13: // Return break; - case 32: // Space + case 32: // Space pLetter = curfont->GetLetter(' '); fx += curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fScale) : pLetter->horizAdvance * fScale; - bNextTextWouldOverflow = (qboolean)( - iMaxPixelWidth != -1 && - ((fx - fox) > (float)iMaxPixelWidth)); + bNextTextWouldOverflow = (qboolean)(iMaxPixelWidth != -1 && ((fx - fox) > (float)iMaxPixelWidth)); break; default: - pLetter = curfont->GetLetter( uiLetter, &hShader ); // Description of pLetter - if(!pLetter->width) - { + pLetter = curfont->GetLetter(uiLetter, &hShader); // Description of pLetter + if (!pLetter->width) { pLetter = curfont->GetLetter('.'); } float fThisScale = uiLetter > 255 ? fScaleAsian : fScale; float fAdvancePixels = curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fThisScale) : pLetter->horizAdvance * fThisScale; - bNextTextWouldOverflow = (qboolean)( - iMaxPixelWidth != -1 && - (((fx + fAdvancePixels) - fox) > (float)iMaxPixelWidth)); - if (!bNextTextWouldOverflow) - { + bNextTextWouldOverflow = (qboolean)(iMaxPixelWidth != -1 && (((fx + fAdvancePixels) - fox) > (float)iMaxPixelWidth)); + if (!bNextTextWouldOverflow) { // this 'mbRoundCalcs' stuff is crap, but the only way to make the font code work. Sigh... // fy = foy - (curfont->mbRoundCalcs ? Round(pLetter->baseline * fThisScale) : pLetter->baseline * fThisScale); RE_StretchPic(curfont->mbRoundCalcs ? fx + Round(pLetter->horizOffset * fThisScale) : fx + pLetter->horizOffset * fThisScale, // float x - (uiLetter > 255) ? fy - fAsianYAdjust : fy, // float y - curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w - curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h - pLetter->s, // float s1 - pLetter->t, // float t1 - pLetter->s2, // float s2 - pLetter->t2, // float t2 - //lastcolour.c, - hShader // qhandle_t hShader - ); + (uiLetter > 255) ? fy - fAsianYAdjust : fy, // float y + curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w + curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h + pLetter->s, // float s1 + pLetter->t, // float t1 + pLetter->s2, // float s2 + pLetter->t2, // float t2 + // lastcolour.c, + hShader // qhandle_t hShader + ); fx += fAdvancePixels; } break; } } - //let it remember the old color //RE_SetColor(NULL); + // let it remember the old color //RE_SetColor(NULL); #else - static qboolean gbInShadow = qfalse; // MUST default to this - float fox, foy, fx, fy; - int colour, offset; - const glyphInfo_t *pLetter; - qhandle_t hShader; + static qboolean gbInShadow = qfalse; // MUST default to this + float fox, foy, fx, fy; + int colour, offset; + const glyphInfo_t *pLetter; + qhandle_t hShader; - assert (psText); + assert(psText); - if(iFontHandle & STYLE_BLINK) - { - if((ri.Milliseconds() >> 7) & 1) - { + if (iFontHandle & STYLE_BLINK) { + if ((ri.Milliseconds() >> 7) & 1) { return; } } -// // test code only -// if (GetLanguageEnum() == eTaiwanese) -// { -// psText = "Wp:\B6}\B7F\A7a \BFp\B7G\B4\B5\A1A\A7Ʊ\E6\A7A\B9\B3\A5L\ADÌ»\A1\AA\BA\A4@\BC˦\E6\A1C"; -// } -// else -// if (GetLanguageEnum() == eChinese) -// { -// //psText = "Ó¶\B1\F8Õ½\B3\A1II Ô¼\BA\B2?Ī\C1\D6˹ \C8\CE\CE\F1ʧ\B0\DC \C4\E3Òª\CC\D7\D3û\AD\C3\E6\C9趨\B5ı\E4\B8\FC\C2\F0\A3\BF Ô¤\C9\E8,S3 ѹ\CB\F5,DXT1 ѹ\CB\F5,DXT5 ѹ\CB\F5,16 Bit,32 Bit"; -// psText = "Ó¶\B1\F8Õ½\B3\A1II"; -// } -// else -// if (GetLanguageEnum() == eThai) -// { -// //psText = "\C1ҵðҹ\BC\C5Ôµ\C0ѳ\B1\EC\CDص\CA\D2Ë¡\C3\C3\C1\C3\CB\D1\CA\CA\D3\CB\C3Ѻ\CDÑ¡\A2\C3\D0\E4\B7·\D5\E8\E3\AA\E9\A1Ѻ\A4\CD\C1\BE\D4\C7\E0\B5\CD\C3\EC"; -// psText = "\C1ҵðҹ\BC\C5Ôµ"; -// psText = "\C3\CB\D1\CA\CA\D3\CB\C3Ѻ"; -// psText = "\C3\CB\D1\CA\CA\D3\CB\C3Ѻ \CD\D2_\A1Ô¹_\A4\CD\C3\EC\B7_1415"; -// } -// else -// if (GetLanguageEnum() == eKorean) -// { -// psText = "Wp:\BC\EEŸ\C0\D3\C0Ì´\D9 \B8Ö¸\B0. \B1×µ\E9\C0\CC \B8\BB\C7Ñ´\EB\B7\CE \B3×°\A1 \C0\DF\C7\D2\C1\F6 \B1\E2\B4\EB\C7Ï°Ú´\D9."; -// } -// else -// if (GetLanguageEnum() == eJapanese) -// { -// static char sBlah[200]; -// sprintf(sBlah,va("%c%c%c%c%c%c%c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); -// psText = &sBlah[0]; -// } -// else -// if (GetLanguageEnum() == eRussian) -// { -//// //psText = "\CD\E0 \E2\E5\F0\F8\E8\ED\E5 \F5\EE\EB\EC\E0 \F1\F2\EE\E8\F2 \F1\F2\E0\F0\FB\E9 \E4\EE\EC \F1 \EF\F0\E8\E2\E8\E4\E5\ED\E8\FF\EC\E8 \E8 \E1\E0\F8\ED\FF \F1 \E2\EE\EB\F8\E5\E1\ED\FB\EC\E8 \F7\E0\F1\E0\EC\E8." -// psText = "\CD\E0 \E2\E5\F0\F8\E8\ED\E5 \F5\EE\EB\EC\E0 \F1\F2\EE\E8\F2"; -// } -// else -// if (GetLanguageEnum() == ePolish) -// { -// psText = "za\B3o\BFony w 1364 roku, jest najstarsz\B9 polsk\B9 uczelni\B9 i nale\BFy..."; -// psText = "za\B3o\BFony nale\BFy"; -// } - + // // test code only + // if (GetLanguageEnum() == eTaiwanese) + // { + // psText = "Wp:\B6}\B7F\A7a \BFp\B7G\B4\B5\A1A\A7Ʊ\E6\A7A\B9\B3\A5L\ADÌ»\A1\AA\BA\A4@\BC˦\E6\A1C"; + // } + // else + // if (GetLanguageEnum() == eChinese) + // { + // //psText = "Ó¶\B1\F8Õ½\B3\A1II Ô¼\BA\B2?Ī\C1\D6˹ \C8\CE\CE\F1ʧ\B0\DC \C4\E3Òª\CC\D7\D3û\AD\C3\E6\C9趨\B5ı\E4\B8\FC\C2\F0\A3\BF Ô¤\C9\E8,S3 ѹ\CB\F5,DXT1 + //ѹ\CB\F5,DXT5 ѹ\CB\F5,16 Bit,32 Bit"; psText = "Ó¶\B1\F8Õ½\B3\A1II"; + // } + // else + // if (GetLanguageEnum() == eThai) + // { + // //psText = + //"\C1ҵðҹ\BC\C5Ôµ\C0ѳ\B1\EC\CDص\CA\D2Ë¡\C3\C3\C1\C3\CB\D1\CA\CA\D3\CB\C3Ѻ\CDÑ¡\A2\C3\D0\E4\B7·\D5\E8\E3\AA\E9\A1Ѻ\A4\CD\C1\BE\D4\C7\E0\B5\CD\C3\EC"; psText = + //"\C1ҵðҹ\BC\C5Ôµ"; psText = "\C3\CB\D1\CA\CA\D3\CB\C3Ѻ"; psText = "\C3\CB\D1\CA\CA\D3\CB\C3Ѻ \CD\D2_\A1Ô¹_\A4\CD\C3\EC\B7_1415"; + // } + // else + // if (GetLanguageEnum() == eKorean) + // { + // psText = "Wp:\BC\EEŸ\C0\D3\C0Ì´\D9 \B8Ö¸\B0. \B1×µ\E9\C0\CC \B8\BB\C7Ñ´\EB\B7\CE \B3×°\A1 \C0\DF\C7\D2\C1\F6 \B1\E2\B4\EB\C7Ï°Ú´\D9."; + // } + // else + // if (GetLanguageEnum() == eJapanese) + // { + // static char sBlah[200]; + // sprintf(sBlah,va("%c%c%c%c%c%c%c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); + // psText = &sBlah[0]; + // } + // else + // if (GetLanguageEnum() == eRussian) + // { + //// //psText = "\CD\E0 \E2\E5\F0\F8\E8\ED\E5 \F5\EE\EB\EC\E0 \F1\F2\EE\E8\F2 \F1\F2\E0\F0\FB\E9 \E4\EE\EC \F1 \EF\F0\E8\E2\E8\E4\E5\ED\E8\FF\EC\E8 \E8 + ///\E1\E0\F8\ED\FF \F1 \E2\EE\EB\F8\E5\E1\ED\FB\EC\E8 \F7\E0\F1\E0\EC\E8." + // psText = "\CD\E0 \E2\E5\F0\F8\E8\ED\E5 \F5\EE\EB\EC\E0 \F1\F2\EE\E8\F2"; + // } + // else + // if (GetLanguageEnum() == ePolish) + // { + // psText = "za\B3o\BFony w 1364 roku, jest najstarsz\B9 polsk\B9 uczelni\B9 i nale\BFy..."; + // psText = "za\B3o\BFony nale\BFy"; + // } CFontInfo *curfont = GetFont(iFontHandle); - if(!curfont || !psText) - { + if (!curfont || !psText) { return; } curfont = RE_Font_GetVariant(curfont, &fScale); @@ -1981,25 +1757,23 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c float fScaleAsian = fScale; float fAsianYAdjust = 0.0f; - if (Language_IsAsian() && fScale > 0.7f) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; fAsianYAdjust = ((curfont->GetPointSize() * fScale) - (curfont->GetPointSize() * fScaleAsian)) / 2.0f; } // Draw a dropshadow if required - if(iFontHandle & STYLE_DROPSHADOW) - { + if (iFontHandle & STYLE_DROPSHADOW) { offset = Round(curfont->GetPointSize() * fScale * 0.075f); - const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba?rgba[3]:1.0f}; + const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba ? rgba[3] : 1.0f}; gbInShadow = qtrue; RE_Font_DrawString(ox + offset, oy + offset, psText, v4DKGREY2, iFontHandle & SET_MASK, iMaxPixelWidth, fScale); gbInShadow = qfalse; } - RE_SetColor( rgba ); + RE_SetColor(rgba); // Now we take off the training wheels and become a big font renderer // It's all floats from here on out @@ -2007,60 +1781,54 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c foy = oy; fx = fox; - foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; + foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) + : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; qboolean bNextTextWouldOverflow = qfalse; - while (*psText && !bNextTextWouldOverflow) - { + while (*psText && !bNextTextWouldOverflow) { int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( (char *)psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString((char *)psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - switch( uiLetter ) - { - case 10: //linefeed + switch (uiLetter) { + case 10: // linefeed fx = fox; foy += curfont->mbRoundCalcs ? Round(curfont->GetPointSize() * fScale) : curfont->GetPointSize() * fScale; - if (Language_IsAsian()) - { - foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder functions + if (Language_IsAsian()) { + foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder + // functions } break; - case 13: // Return + case 13: // Return break; - case 32: // Space + case 32: // Space pLetter = curfont->GetLetter(' '); fx += curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fScale) : pLetter->horizAdvance * fScale; - bNextTextWouldOverflow = ( iMaxPixelWidth != -1 && ((fx-fox) > (float)iMaxPixelWidth) ) ? qtrue : qfalse; // yeuch + bNextTextWouldOverflow = (iMaxPixelWidth != -1 && ((fx - fox) > (float)iMaxPixelWidth)) ? qtrue : qfalse; // yeuch break; - case '_': // has a special word-break usage if in Thai (and followed by a thai char), and should not be displayed, else treat as normal - if (GetLanguageEnum()== eThai && ((unsigned char *)psText)[0] >= TIS_GLYPHS_START) - { + case '_': // has a special word-break usage if in Thai (and followed by a thai char), and should not be displayed, else treat as normal + if (GetLanguageEnum() == eThai && ((unsigned char *)psText)[0] >= TIS_GLYPHS_START) { break; } // else drop through and display as normal... case '^': - if (uiLetter != '_') // necessary because of fallthrough above + if (uiLetter != '_') // necessary because of fallthrough above { - if (*psText >= '0' && - *psText <= '9') - { + if (*psText >= '0' && *psText <= '9') { colour = ColorIndex(*psText++); - if (!gbInShadow) - { + if (!gbInShadow) { vec4_t color; - Com_Memcpy( color, g_color_table[colour], sizeof( color ) ); + Com_Memcpy(color, g_color_table[colour], sizeof(color)); color[3] = rgba ? rgba[3] : 1.0f; - RE_SetColor( color ); + RE_SetColor(color); } break; } } - //purposely falls thrugh + // purposely falls thrugh default: - pLetter = curfont->GetLetter( uiLetter, &hShader ); // Description of pLetter - if(!pLetter->width) - { + pLetter = curfont->GetLetter(uiLetter, &hShader); // Description of pLetter + if (!pLetter->width) { pLetter = curfont->GetLetter('.'); } @@ -2068,49 +1836,44 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c // sigh, super-language-specific hack... // - if (uiLetter == TIS_SARA_AM && GetLanguageEnum() == eThai) - { + if (uiLetter == TIS_SARA_AM && GetLanguageEnum() == eThai) { fx -= curfont->mbRoundCalcs ? Round(7.0f * fThisScale) : 7.0f * fThisScale; } float fAdvancePixels = curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fThisScale) : pLetter->horizAdvance * fThisScale; - bNextTextWouldOverflow = ( iMaxPixelWidth != -1 && (((fx+fAdvancePixels)-fox) > (float)iMaxPixelWidth) ) ? qtrue : qfalse; // yeuch - if (!bNextTextWouldOverflow) - { + bNextTextWouldOverflow = (iMaxPixelWidth != -1 && (((fx + fAdvancePixels) - fox) > (float)iMaxPixelWidth)) ? qtrue : qfalse; // yeuch + if (!bNextTextWouldOverflow) { // this 'mbRoundCalcs' stuff is crap, but the only way to make the font code work. Sigh... // fy = foy - (curfont->mbRoundCalcs ? Round(pLetter->baseline * fThisScale) : pLetter->baseline * fThisScale); - if (curfont->m_fAltSBCSFontScaleFactor != -1) - { + if (curfont->m_fAltSBCSFontScaleFactor != -1) { fy += 3.0f; // I'm sick and tired of going round in circles trying to do this legally, so bollocks to it } RE_StretchPic(curfont->mbRoundCalcs ? fx + Round(pLetter->horizOffset * fThisScale) : fx + pLetter->horizOffset * fThisScale, // float x - (uiLetter > (unsigned)g_iNonScaledCharRange) ? fy - fAsianYAdjust : fy, // float y - curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w - curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h - pLetter->s, // float s1 - pLetter->t, // float t1 - pLetter->s2, // float s2 - pLetter->t2, // float t2 - //lastcolour.c, - hShader // qhandle_t hShader - ); + (uiLetter > (unsigned)g_iNonScaledCharRange) ? fy - fAsianYAdjust : fy, // float y + curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w + curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h + pLetter->s, // float s1 + pLetter->t, // float t1 + pLetter->s2, // float s2 + pLetter->t2, // float t2 + // lastcolour.c, + hShader // qhandle_t hShader + ); fx += fAdvancePixels; } break; } } - //let it remember the old color //RE_SetColor(NULL); + // let it remember the old color //RE_SetColor(NULL); #endif } -int RE_RegisterFont_Real(const char *psName) -{ +int RE_RegisterFont_Real(const char *psName) { FontIndexMap_t::iterator it = g_mapFontIndexes.find(psName); - if (it != g_mapFontIndexes.end() ) - { + if (it != g_mapFontIndexes.end()) { int iFontIndex = (*it).second; return iFontIndex; } @@ -2119,18 +1882,15 @@ int RE_RegisterFont_Real(const char *psName) // { CFontInfo *pFont = new CFontInfo(psName); - if (pFont->GetPointSize() > 0) - { + if (pFont->GetPointSize() > 0) { int iFontIndex = g_iCurrentFontIndex - 1; g_mapFontIndexes[psName] = iFontIndex; #ifndef JK2_MODE pFont->m_iThisFont = iFontIndex; #endif return iFontIndex; - } - else - { - g_mapFontIndexes[psName] = 0; // missing/invalid + } else { + g_mapFontIndexes[psName] = 0; // missing/invalid } } @@ -2144,9 +1904,9 @@ int RE_RegisterFont(const char *psName) { if (oriFont->GetNumVariants() == 0) { for (int i = 0; i < MAX_FONT_VARIANTS; i++) { - const char *variantName = va( "%s_sharp%i", psName, i + 1 ); - const char *fontDatPath = FontDatPath( variantName ); - if ( ri.FS_ReadFile(fontDatPath, NULL) > 0 ) { + const char *variantName = va("%s_sharp%i", psName, i + 1); + const char *fontDatPath = FontDatPath(variantName); + if (ri.FS_ReadFile(fontDatPath, NULL) > 0) { int replacerFontHandle = RE_RegisterFont_Real(variantName); if (replacerFontHandle) { CFontInfo *replacerFont = GetFont_Actual(replacerFontHandle); @@ -2161,18 +1921,17 @@ int RE_RegisterFont(const char *psName) { } } } else { - ri.Printf( PRINT_WARNING, "RE_RegisterFont: Couldn't find font %s\n", psName ); + ri.Printf(PRINT_WARNING, "RE_RegisterFont: Couldn't find font %s\n", psName); } return oriFontHandle; } -void R_InitFonts(void) -{ - g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" - g_iNonScaledCharRange = INT_MAX; // default all chars to have no special scaling (other than user supplied) +void R_InitFonts(void) { + g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" + g_iNonScaledCharRange = INT_MAX; // default all chars to have no special scaling (other than user supplied) - r_fontSharpness = ri.Cvar_Get( "r_fontSharpness", "1", CVAR_ARCHIVE_ND ); + r_fontSharpness = ri.Cvar_Get("r_fontSharpness", "1", CVAR_ARCHIVE_ND); } /* @@ -2181,32 +1940,28 @@ R_FontList_f =============== */ -void R_FontList_f( void ) -{ - Com_Printf ("------------------------------------\n"); +void R_FontList_f(void) { + Com_Printf("------------------------------------\n"); FontIndexMap_t::iterator it; - for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) - { + for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) { CFontInfo *font = GetFont((*it).second); - if( font ) - { - Com_Printf("%3i:%s ps:%hi h:%hi a:%hi d:%hi\n", (*it).second, font->m_sFontName, - font->mPointSize, font->mHeight, font->mAscender, font->mDescender); + if (font) { + Com_Printf("%3i:%s ps:%hi h:%hi a:%hi d:%hi\n", (*it).second, font->m_sFontName, font->mPointSize, font->mHeight, font->mAscender, + font->mDescender); } } - Com_Printf ("------------------------------------\n"); + Com_Printf("------------------------------------\n"); } -void R_ShutdownFonts(void) -{ - for(int i = 1; i < g_iCurrentFontIndex; i++) // entry 0 is reserved for "missing/invalid" +void R_ShutdownFonts(void) { + for (int i = 1; i < g_iCurrentFontIndex; i++) // entry 0 is reserved for "missing/invalid" { delete g_vFontArray[i]; } g_mapFontIndexes.clear(); g_vFontArray.clear(); - g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" + g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" #ifndef JK2_MODE g_ThaiCodes.Clear(); @@ -2215,56 +1970,49 @@ void R_ShutdownFonts(void) // this is only really for debugging while tinkering with fonts, but harmless to leave in... // -void R_ReloadFonts_f(void) -{ +void R_ReloadFonts_f(void) { // first, grab all the currently-registered fonts IN THE ORDER THEY WERE REGISTERED... // - std::vector vstrFonts; + std::vector vstrFonts; int iFontToFind = 1; - for (; iFontToFind < g_iCurrentFontIndex; iFontToFind++) - { + for (; iFontToFind < g_iCurrentFontIndex; iFontToFind++) { FontIndexMap_t::iterator it = g_mapFontIndexes.begin(); - CFontInfo *font = GetFont( iFontToFind ); - if ( font && font->m_isVariant ) continue; - for (; it != g_mapFontIndexes.end(); ++it) - { - if (iFontToFind == (*it).second) - { - vstrFonts.push_back( (*it).first ); + CFontInfo *font = GetFont(iFontToFind); + if (font && font->m_isVariant) + continue; + for (; it != g_mapFontIndexes.end(); ++it) { + if (iFontToFind == (*it).second) { + vstrFonts.push_back((*it).first); break; } } - if ( it == g_mapFontIndexes.end() ) - { - break; // couldn't find this font + if (it == g_mapFontIndexes.end()) { + break; // couldn't find this font } } - if ( iFontToFind == g_iCurrentFontIndex ) // found all of them? + if (iFontToFind == g_iCurrentFontIndex) // found all of them? { // now restart the font system... // R_ShutdownFonts(); R_InitFonts(); // - // and re-register our fonts in the same order as before (note that some menu items etc cache the string lengths so really a vid_restart is better, but this is just for my testing) + // and re-register our fonts in the same order as before (note that some menu items etc cache the string lengths so really a vid_restart is better, but + // this is just for my testing) // - for (size_t font = 0; font < vstrFonts.size(); font++) - { + for (size_t font = 0; font < vstrFonts.size(); font++) { #ifdef _DEBUG - int iNewFontHandle = RE_RegisterFont( vstrFonts[font].c_str() ); - assert( (unsigned)iNewFontHandle == font+1 ); + int iNewFontHandle = RE_RegisterFont(vstrFonts[font].c_str()); + assert((unsigned)iNewFontHandle == font + 1); #else - RE_RegisterFont( vstrFonts[font].c_str() ); + RE_RegisterFont(vstrFonts[font].c_str()); #endif } - Com_Printf( "Done.\n" ); - } - else - { - Com_Printf( "Problem encountered finding current fonts, ignoring.\n" ); // poo. Oh well, forget it. + Com_Printf("Done.\n"); + } else { + Com_Printf("Problem encountered finding current fonts, ignoring.\n"); // poo. Oh well, forget it. } } - // end diff --git a/code/rd-common/tr_image_jpg.cpp b/code/rd-common/tr_image_jpg.cpp index a3ddb84a16..f0dbbfd770 100644 --- a/code/rd-common/tr_image_jpg.cpp +++ b/code/rd-common/tr_image_jpg.cpp @@ -36,11 +36,10 @@ along with this program; if not, see . #include -static void R_JPGErrorExit(j_common_ptr cinfo) -{ +static void R_JPGErrorExit(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; - (*cinfo->err->format_message) (cinfo, buffer); + (*cinfo->err->format_message)(cinfo, buffer); /* Let the memory manager delete any temp files before we die */ jpeg_destroy(cinfo); @@ -48,38 +47,37 @@ static void R_JPGErrorExit(j_common_ptr cinfo) Com_Printf("%s", buffer); } -static void R_JPGOutputMessage(j_common_ptr cinfo) -{ +static void R_JPGOutputMessage(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; /* Create the message */ - (*cinfo->err->format_message) (cinfo, buffer); + (*cinfo->err->format_message)(cinfo, buffer); /* Send it to stderr, adding a newline */ Com_Printf("%s\n", buffer); } -void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height ) { +void LoadJPG(const char *filename, unsigned char **pic, int *width, int *height) { /* This struct contains the JPEG decompression parameters and pointers to - * working space (which is allocated as needed by the JPEG library). - */ - struct jpeg_decompress_struct cinfo = { NULL }; + * working space (which is allocated as needed by the JPEG library). + */ + struct jpeg_decompress_struct cinfo = {NULL}; /* We use our private extension JPEG error handler. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ + * Note that this struct must live as long as the main JPEG parameter + * struct, to avoid dangling-pointer problems. + */ /* This struct represents a JPEG error handler. It is declared separately - * because applications often want to supply a specialized error handler - * (see the second half of this file for an example). But here we just - * take the easy way out and use the standard error handler, which will - * print a message on stderr and call exit() if compression fails. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ + * because applications often want to supply a specialized error handler + * (see the second half of this file for an example). But here we just + * take the easy way out and use the standard error handler, which will + * print a message on stderr and call exit() if compression fails. + * Note that this struct must live as long as the main JPEG parameter + * struct, to avoid dangling-pointer problems. + */ struct jpeg_error_mgr jerr; /* More stuff */ - JSAMPARRAY buffer; /* Output row buffer */ - unsigned int row_stride; /* physical row width in output buffer */ + JSAMPARRAY buffer; /* Output row buffer */ + unsigned int row_stride; /* physical row width in output buffer */ unsigned int pixelcount, memcount; unsigned int sindex, dindex; byte *out; @@ -87,14 +85,14 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height byte *b; void *v; } fbuffer; - byte *buf; + byte *buf; /* In this example we want to open the input file before doing anything else, - * so that the setjmp() error recovery below can assume the file is open. - * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that - * requires it in order to read binary files. - */ + * so that the setjmp() error recovery below can assume the file is open. + * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that + * requires it in order to read binary files. + */ - int len = ri.FS_ReadFile ( ( char * ) filename, &fbuffer.v); + int len = ri.FS_ReadFile((char *)filename, &fbuffer.v); if (!fbuffer.b || len < 0) { return; } @@ -102,10 +100,10 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* Step 1: allocate and initialize JPEG decompression object */ /* We have to set up the error handler first, in case the initialization - * step fails. (Unlikely, but it could happen if you are out of memory.) - * This routine fills in the contents of struct jerr, and returns jerr's - * address which we place into the link field in cinfo. - */ + * step fails. (Unlikely, but it could happen if you are out of memory.) + * This routine fills in the contents of struct jerr, and returns jerr's + * address which we place into the link field in cinfo. + */ cinfo.err = jpeg_std_error(&jerr); cinfo.err->error_exit = R_JPGErrorExit; cinfo.err->output_message = R_JPGOutputMessage; @@ -119,47 +117,43 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* Step 3: read file parameters with jpeg_read_header() */ - (void) jpeg_read_header(&cinfo, TRUE); + (void)jpeg_read_header(&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since - * (a) suspension is not possible with the stdio data source, and - * (b) we passed TRUE to reject a tables-only JPEG file as an error. - * See libjpeg.doc for more info. - */ + * (a) suspension is not possible with the stdio data source, and + * (b) we passed TRUE to reject a tables-only JPEG file as an error. + * See libjpeg.doc for more info. + */ /* Step 4: set parameters for decompression */ - /* Make sure it always converts images to RGB color space. This will - * automatically convert 8-bit greyscale images to RGB as well. */ + * automatically convert 8-bit greyscale images to RGB as well. */ cinfo.out_color_space = JCS_RGB; /* Step 5: Start decompressor */ - (void) jpeg_start_decompress(&cinfo); + (void)jpeg_start_decompress(&cinfo); /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ + * with the stdio data source. + */ /* We may need to do some setup of our own at this point before reading - * the data. After jpeg_start_decompress() we have the correct scaled - * output image dimensions available, as well as the output colormap - * if we asked for color quantization. - * In this example, we need to make an output work buffer of the right size. - */ + * the data. After jpeg_start_decompress() we have the correct scaled + * output image dimensions available, as well as the output colormap + * if we asked for color quantization. + * In this example, we need to make an output work buffer of the right size. + */ /* JSAMPLEs per row in output buffer */ pixelcount = cinfo.output_width * cinfo.output_height; - if(!cinfo.output_width || !cinfo.output_height - || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height - || pixelcount > 0x1FFFFFFF || cinfo.output_components != 3 - ) - { + if (!cinfo.output_width || !cinfo.output_height || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height || pixelcount > 0x1FFFFFFF || + cinfo.output_components != 3) { // Free the memory to make sure we don't leak memory - ri.FS_FreeFile (fbuffer.v); + ri.FS_FreeFile(fbuffer.v); jpeg_destroy_decompress(&cinfo); - ri.Printf( PRINT_ALL, "LoadJPG: %s has an invalid image format: %dx%d*4=%d, components: %d", filename, - cinfo.output_width, cinfo.output_height, pixelcount * 4, cinfo.output_components); + ri.Printf(PRINT_ALL, "LoadJPG: %s has an invalid image format: %dx%d*4=%d, components: %d", filename, cinfo.output_width, cinfo.output_height, + pixelcount * 4, cinfo.output_components); return; } @@ -175,16 +169,16 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* jpeg_read_scanlines(...); */ /* Here we use the library's state variable cinfo.output_scanline as the - * loop counter, so that we don't have to keep track ourselves. - */ + * loop counter, so that we don't have to keep track ourselves. + */ while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. - * Here the array is only one element long, but you could ask for - * more than one scanline at a time if that's more convenient. - */ - buf = ((out+(row_stride*cinfo.output_scanline))); + * Here the array is only one element long, but you could ask for + * more than one scanline at a time if that's more convenient. + */ + buf = ((out + (row_stride * cinfo.output_scanline))); buffer = &buf; - (void) jpeg_read_scanlines(&cinfo, buffer, 1); + (void)jpeg_read_scanlines(&cinfo, buffer, 1); } buf = out; @@ -197,16 +191,16 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; - } while(sindex); + } while (sindex); *pic = out; /* Step 7: Finish decompression */ - (void) jpeg_finish_decompress(&cinfo); + (void)jpeg_finish_decompress(&cinfo); /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ + * with the stdio data source. + */ /* Step 8: Release JPEG decompression object */ @@ -214,24 +208,24 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height jpeg_destroy_decompress(&cinfo); /* After finish_decompress, we can close the input file. - * Here we postpone it until after no more JPEG errors are possible, - * so as to simplify the setjmp error logic above. (Actually, I don't - * think that jpeg_destroy can do an error exit, but why assume anything...) - */ - ri.FS_FreeFile (fbuffer.v); + * Here we postpone it until after no more JPEG errors are possible, + * so as to simplify the setjmp error logic above. (Actually, I don't + * think that jpeg_destroy can do an error exit, but why assume anything...) + */ + ri.FS_FreeFile(fbuffer.v); /* At this point you may want to check to see whether any corrupt-data - * warnings occurred (test whether jerr.pub.num_warnings is nonzero). - */ + * warnings occurred (test whether jerr.pub.num_warnings is nonzero). + */ /* And we're done! */ } #ifdef JK2_MODE -void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int *width, int *height ) { +void LoadJPGFromBuffer(byte *inputBuffer, size_t len, unsigned char **pic, int *width, int *height) { /* This struct contains the JPEG decompression parameters and pointers to * working space (which is allocated as needed by the JPEG library). */ - struct jpeg_decompress_struct cinfo = { NULL }; + struct jpeg_decompress_struct cinfo = {NULL}; /* We use our private extension JPEG error handler. * Note that this struct must live as long as the main JPEG parameter * struct, to avoid dangling-pointer problems. @@ -246,12 +240,12 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int */ struct jpeg_error_mgr jerr; /* More stuff */ - JSAMPARRAY buffer; /* Output row buffer */ - unsigned int row_stride; /* physical row width in output buffer */ + JSAMPARRAY buffer; /* Output row buffer */ + unsigned int row_stride; /* physical row width in output buffer */ unsigned int pixelcount, memcount; unsigned int sindex, dindex; byte *out; - byte *buf; + byte *buf; if (!inputBuffer) { return; @@ -277,7 +271,7 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int /* Step 3: read file parameters with jpeg_read_header() */ - (void) jpeg_read_header(&cinfo, TRUE); + (void)jpeg_read_header(&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since * (a) suspension is not possible with the stdio data source, and * (b) we passed TRUE to reject a tables-only JPEG file as an error. @@ -286,14 +280,13 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int /* Step 4: set parameters for decompression */ - /* Make sure it always converts images to RGB color space. This will * automatically convert 8-bit greyscale images to RGB as well. */ cinfo.out_color_space = JCS_RGB; /* Step 5: Start decompressor */ - (void) jpeg_start_decompress(&cinfo); + (void)jpeg_start_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ @@ -307,16 +300,13 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int /* JSAMPLEs per row in output buffer */ pixelcount = cinfo.output_width * cinfo.output_height; - if(!cinfo.output_width || !cinfo.output_height - || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height - || pixelcount > 0x1FFFFFFF || cinfo.output_components != 3 - ) - { + if (!cinfo.output_width || !cinfo.output_height || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height || pixelcount > 0x1FFFFFFF || + cinfo.output_components != 3) { // Free the memory to make sure we don't leak memory jpeg_destroy_decompress(&cinfo); - ri.Printf( PRINT_ALL, "LoadJPG: invalid image format: %dx%d*4=%d, components: %d", - cinfo.output_width, cinfo.output_height, pixelcount * 4, cinfo.output_components); + ri.Printf(PRINT_ALL, "LoadJPG: invalid image format: %dx%d*4=%d, components: %d", cinfo.output_width, cinfo.output_height, pixelcount * 4, + cinfo.output_components); return; } @@ -339,9 +329,9 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int * Here the array is only one element long, but you could ask for * more than one scanline at a time if that's more convenient. */ - buf = ((out+(row_stride*(cinfo.output_height - cinfo.output_scanline - 1)))); + buf = ((out + (row_stride * (cinfo.output_height - cinfo.output_scanline - 1)))); buffer = &buf; - (void) jpeg_read_scanlines(&cinfo, buffer, 1); + (void)jpeg_read_scanlines(&cinfo, buffer, 1); } buf = out; @@ -354,13 +344,13 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; - } while(sindex); + } while (sindex); *pic = out; /* Step 7: Finish decompression */ - (void) jpeg_finish_decompress(&cinfo); + (void)jpeg_finish_decompress(&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ @@ -383,53 +373,49 @@ void LoadJPGFromBuffer( byte *inputBuffer, size_t len, unsigned char **pic, int typedef struct my_destination_mgr_s { struct jpeg_destination_mgr pub; /* public fields */ - byte* outfile; /* target stream */ - int size; + byte *outfile; /* target stream */ + int size; } my_destination_mgr; -typedef my_destination_mgr * my_dest_ptr; - +typedef my_destination_mgr *my_dest_ptr; /* -* Initialize destination --- called by jpeg_start_compress -* before any data is actually written. -*/ + * Initialize destination --- called by jpeg_start_compress + * before any data is actually written. + */ -static void init_destination (j_compress_ptr cinfo) -{ - my_dest_ptr dest = (my_dest_ptr) cinfo->dest; +static void init_destination(j_compress_ptr cinfo) { + my_dest_ptr dest = (my_dest_ptr)cinfo->dest; dest->pub.next_output_byte = dest->outfile; dest->pub.free_in_buffer = dest->size; } - /* -* Empty the output buffer --- called whenever buffer fills up. -* -* In typical applications, this should write the entire output buffer -* (ignoring the current state of next_output_byte & free_in_buffer), -* reset the pointer & count to the start of the buffer, and return TRUE -* indicating that the buffer has been dumped. -* -* In applications that need to be able to suspend compression due to output -* overrun, a FALSE return indicates that the buffer cannot be emptied now. -* In this situation, the compressor will return to its caller (possibly with -* an indication that it has not accepted all the supplied scanlines). The -* application should resume compression after it has made more room in the -* output buffer. Note that there are substantial restrictions on the use of -* suspension --- see the documentation. -* -* When suspending, the compressor will back up to a convenient restart point -* (typically the start of the current MCU). next_output_byte & free_in_buffer -* indicate where the restart point will be if the current call returns FALSE. -* Data beyond this point will be regenerated after resumption, so do not -* write it out when emptying the buffer externally. -*/ + * Empty the output buffer --- called whenever buffer fills up. + * + * In typical applications, this should write the entire output buffer + * (ignoring the current state of next_output_byte & free_in_buffer), + * reset the pointer & count to the start of the buffer, and return TRUE + * indicating that the buffer has been dumped. + * + * In applications that need to be able to suspend compression due to output + * overrun, a FALSE return indicates that the buffer cannot be emptied now. + * In this situation, the compressor will return to its caller (possibly with + * an indication that it has not accepted all the supplied scanlines). The + * application should resume compression after it has made more room in the + * output buffer. Note that there are substantial restrictions on the use of + * suspension --- see the documentation. + * + * When suspending, the compressor will back up to a convenient restart point + * (typically the start of the current MCU). next_output_byte & free_in_buffer + * indicate where the restart point will be if the current call returns FALSE. + * Data beyond this point will be regenerated after resumption, so do not + * write it out when emptying the buffer externally. + */ -static boolean empty_output_buffer (j_compress_ptr cinfo) -{ - my_dest_ptr dest = (my_dest_ptr) cinfo->dest; +static boolean empty_output_buffer(j_compress_ptr cinfo) { + my_dest_ptr dest = (my_dest_ptr)cinfo->dest; jpeg_destroy_compress(cinfo); @@ -440,42 +426,36 @@ static boolean empty_output_buffer (j_compress_ptr cinfo) } /* -* Terminate destination --- called by jpeg_finish_compress -* after all data has been written. Usually needs to flush buffer. -* -* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding -* application must deal with any cleanup that should happen even -* for error exit. -*/ - -static void term_destination(j_compress_ptr cinfo) -{ -} + * Terminate destination --- called by jpeg_finish_compress + * after all data has been written. Usually needs to flush buffer. + * + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding + * application must deal with any cleanup that should happen even + * for error exit. + */ +static void term_destination(j_compress_ptr cinfo) {} /* -* Prepare for output to a stdio stream. -* The caller must have already opened the stream, and is responsible -* for closing it after finishing compression. -*/ + * Prepare for output to a stdio stream. + * The caller must have already opened the stream, and is responsible + * for closing it after finishing compression. + */ -static void jpegDest (j_compress_ptr cinfo, byte* outfile, int size) -{ +static void jpegDest(j_compress_ptr cinfo, byte *outfile, int size) { my_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images - * can be written to the same file without re-executing jpeg_stdio_dest. - * This makes it dangerous to use this manager and a different destination - * manager serially with the same JPEG object, because their private object - * sizes may be different. Caveat programmer. - */ - if (cinfo->dest == NULL) { /* first time for this JPEG object? */ - cinfo->dest = (struct jpeg_destination_mgr *) - (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, - sizeof(my_destination_mgr)); + * can be written to the same file without re-executing jpeg_stdio_dest. + * This makes it dangerous to use this manager and a different destination + * manager serially with the same JPEG object, because their private object + * sizes may be different. Caveat programmer. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr)); } - dest = (my_dest_ptr) cinfo->dest; + dest = (my_dest_ptr)cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; @@ -491,14 +471,12 @@ Encodes JPEG from image in image_buffer and writes to buffer. Expects RGB input data ================= */ -size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, - int image_width, int image_height, byte *image_buffer, int padding, bool flip_vertical) -{ +size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, int image_width, int image_height, byte *image_buffer, int padding, bool flip_vertical) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; - JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ + JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ my_dest_ptr dest; - int row_stride; /* physical row width in image buffer */ + int row_stride; /* physical row width in image buffer */ size_t outcount; /* Step 1: allocate and initialize JPEG compression object */ @@ -516,10 +494,10 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, jpegDest(&cinfo, buffer, bufSize); /* Step 3: set parameters for compression */ - cinfo.image_width = image_width; /* image width and height, in pixels */ + cinfo.image_width = image_width; /* image width and height, in pixels */ cinfo.image_height = image_height; cinfo.input_components = 3; /* # of color components per pixel */ - cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ + cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); @@ -540,25 +518,24 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, while (cinfo.next_scanline < cinfo.image_height) { /* jpeg_write_scanlines expects an array of pointers to scanlines. - * Here the array is only one element long, but you could pass - * more than one scanline at a time if that's more convenient. - */ + * Here the array is only one element long, but you could pass + * more than one scanline at a time if that's more convenient. + */ int row_index = cinfo.next_scanline; - if (!flip_vertical) - { + if (!flip_vertical) { row_index = cinfo.image_height - cinfo.next_scanline - 1; } row_pointer[0] = &image_buffer[row_index * row_stride]; - (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); + (void)jpeg_write_scanlines(&cinfo, row_pointer, 1); } /* Step 6: Finish compression */ jpeg_finish_compress(&cinfo); - dest = (my_dest_ptr) cinfo.dest; + dest = (my_dest_ptr)cinfo.dest; outcount = dest->size - dest->pub.free_in_buffer; /* Step 7: release JPEG compression object */ @@ -568,18 +545,15 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, return outcount; } - -void RE_SaveJPG(const char * filename, int quality, int image_width, int image_height, byte *image_buffer, int padding) -{ +void RE_SaveJPG(const char *filename, int quality, int image_width, int image_height, byte *image_buffer, int padding) { byte *out; size_t bufSize; bufSize = image_width * image_height * 3; - out = (byte *) R_Malloc( bufSize, TAG_TEMP_WORKSPACE, qfalse ); + out = (byte *)R_Malloc(bufSize, TAG_TEMP_WORKSPACE, qfalse); bufSize = RE_SaveJPGToBuffer(out, bufSize, quality, image_width, image_height, image_buffer, padding, false); ri.FS_WriteFile(filename, out, bufSize); R_Free(out); } - diff --git a/code/rd-common/tr_image_load.cpp b/code/rd-common/tr_image_load.cpp index 12f009fa4d..15e53cfe34 100644 --- a/code/rd-common/tr_image_load.cpp +++ b/code/rd-common/tr_image_load.cpp @@ -27,8 +27,7 @@ along with this program; if not, see . #include "../rd-common/tr_common.h" const int MAX_IMAGE_LOADERS = 10; -struct ImageLoaderMap -{ +struct ImageLoaderMap { const char *extension; ImageLoaderFn loader; } imageLoaders[MAX_IMAGE_LOADERS]; @@ -39,12 +38,9 @@ int numImageLoaders; Finds the image loader associated with the given extension. ================= */ -const ImageLoaderMap *FindImageLoader ( const char *extension ) -{ - for ( int i = 0; i < numImageLoaders; i++ ) - { - if ( Q_stricmp (extension, imageLoaders[i].extension) == 0 ) - { +const ImageLoaderMap *FindImageLoader(const char *extension) { + for (int i = 0; i < numImageLoaders; i++) { + if (Q_stricmp(extension, imageLoaders[i].extension) == 0) { return &imageLoaders[i]; } } @@ -58,17 +54,14 @@ Adds a new image loader to load the specified image file extension. The 'extension' string should not begin with a period (full stop). ================= */ -qboolean R_ImageLoader_Add ( const char *extension, ImageLoaderFn imageLoader ) -{ - if ( numImageLoaders >= MAX_IMAGE_LOADERS ) - { - ri.Printf (PRINT_DEVELOPER, "R_AddImageLoader: Cannot add any more image loaders (maximum %d).\n", MAX_IMAGE_LOADERS); +qboolean R_ImageLoader_Add(const char *extension, ImageLoaderFn imageLoader) { + if (numImageLoaders >= MAX_IMAGE_LOADERS) { + ri.Printf(PRINT_DEVELOPER, "R_AddImageLoader: Cannot add any more image loaders (maximum %d).\n", MAX_IMAGE_LOADERS); return qfalse; } - if ( FindImageLoader (extension) != NULL ) - { - ri.Printf (PRINT_DEVELOPER, "R_AddImageLoader: Image loader already exists for extension \"%s\".\n", extension); + if (FindImageLoader(extension) != NULL) { + ri.Printf(PRINT_DEVELOPER, "R_AddImageLoader: Image loader already exists for extension \"%s\".\n", extension); return qfalse; } @@ -87,14 +80,13 @@ Initializes the image loader, and adds the built-in image loaders ================= */ -void R_ImageLoader_Init() -{ - Com_Memset (imageLoaders, 0, sizeof (imageLoaders)); +void R_ImageLoader_Init() { + Com_Memset(imageLoaders, 0, sizeof(imageLoaders)); numImageLoaders = 0; - R_ImageLoader_Add ("jpg", LoadJPG); - R_ImageLoader_Add ("png", LoadPNG); - R_ImageLoader_Add ("tga", LoadTGA); + R_ImageLoader_Add("jpg", LoadJPG); + R_ImageLoader_Add("png", LoadPNG); + R_ImageLoader_Add("tga", LoadTGA); } /* @@ -103,39 +95,34 @@ Loads any of the supported image types into a cannonical 32 bit format. ================= */ -void R_LoadImage( const char *shortname, byte **pic, int *width, int *height ) { +void R_LoadImage(const char *shortname, byte **pic, int *width, int *height) { *pic = NULL; *width = 0; *height = 0; // Try loading the image with the original extension (if possible). - const char *extension = COM_GetExtension (shortname); - const ImageLoaderMap *imageLoader = FindImageLoader (extension); - if ( imageLoader != NULL ) - { - imageLoader->loader (shortname, pic, width, height); - if ( *pic ) - { + const char *extension = COM_GetExtension(shortname); + const ImageLoaderMap *imageLoader = FindImageLoader(extension); + if (imageLoader != NULL) { + imageLoader->loader(shortname, pic, width, height); + if (*pic) { return; } } // Loop through all the image loaders trying to load this image. char extensionlessName[MAX_QPATH]; - COM_StripExtension(shortname, extensionlessName, sizeof( extensionlessName )); - for ( int i = 0; i < numImageLoaders; i++ ) - { + COM_StripExtension(shortname, extensionlessName, sizeof(extensionlessName)); + for (int i = 0; i < numImageLoaders; i++) { const ImageLoaderMap *tryLoader = &imageLoaders[i]; - if ( tryLoader == imageLoader ) - { + if (tryLoader == imageLoader) { // Already tried this one. continue; } - const char *name = va ("%s.%s", extensionlessName, tryLoader->extension); - tryLoader->loader (name, pic, width, height); - if ( *pic ) - { + const char *name = va("%s.%s", extensionlessName, tryLoader->extension); + tryLoader->loader(name, pic, width, height); + if (*pic) { return; } } diff --git a/code/rd-common/tr_image_png.cpp b/code/rd-common/tr_image_png.cpp index 9d07a26d73..87fe1df0df 100644 --- a/code/rd-common/tr_image_png.cpp +++ b/code/rd-common/tr_image_png.cpp @@ -27,20 +27,20 @@ along with this program; if not, see . #include "tr_common.h" #include -void user_write_data( png_structp png_ptr, png_bytep data, png_size_t length ) { - fileHandle_t fp = *(fileHandle_t*)png_get_io_ptr( png_ptr ); - ri.FS_Write( data, length, fp ); +void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { + fileHandle_t fp = *(fileHandle_t *)png_get_io_ptr(png_ptr); + ri.FS_Write(data, length, fp); } -void user_flush_data( png_structp png_ptr ) { - //TODO: ri->FS_Flush? +void user_flush_data(png_structp png_ptr) { + // TODO: ri->FS_Flush? } -int RE_SavePNG( const char *filename, byte *buf, size_t width, size_t height, int byteDepth ) { +int RE_SavePNG(const char *filename, byte *buf, size_t width, size_t height, int byteDepth) { fileHandle_t fp; png_structp png_ptr = NULL; png_infop info_ptr = NULL; unsigned int x, y; - png_byte ** row_pointers = NULL; + png_byte **row_pointers = NULL; /* "status" contains the return value of this function. At first it is set to a value which means 'failure'. When the routine has finished its work, it is set to a value which means @@ -51,47 +51,39 @@ int RE_SavePNG( const char *filename, byte *buf, size_t width, size_t height, in */ int depth = 8; - fp = ri.FS_FOpenFileWrite( filename, qtrue ); - if ( !fp ) { + fp = ri.FS_FOpenFileWrite(filename, qtrue); + if (!fp) { goto fopen_failed; } - png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { goto png_create_write_struct_failed; } - info_ptr = png_create_info_struct (png_ptr); + info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { goto png_create_info_struct_failed; } /* Set up error handling. */ - if (setjmp (png_jmpbuf (png_ptr))) { + if (setjmp(png_jmpbuf(png_ptr))) { goto png_failure; } /* Set image attributes. */ - png_set_IHDR (png_ptr, - info_ptr, - width, - height, - depth, - PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, - PNG_FILTER_TYPE_DEFAULT); + png_set_IHDR(png_ptr, info_ptr, width, height, depth, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); /* Initialize rows of PNG. */ - row_pointers = (png_byte **)png_malloc (png_ptr, height * sizeof (png_byte *)); - for ( y=0; y RGBA - png_set_add_alpha (png_ptr, 0xff, PNG_FILLER_AFTER); + png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); } - png_read_update_info (png_ptr, info_ptr); + png_read_update_info(png_ptr, info_ptr); // We always assume there are 4 channels. RGB channels are expanded to RGBA when read. - byte *tempData = (byte *) R_Malloc (width_ * height_ * 4, TAG_TEMP_PNG, qfalse); - if ( !tempData ) - { - ri.Printf (PRINT_ERROR, "Could not allocate enough memory to load the image."); + byte *tempData = (byte *)R_Malloc(width_ * height_ * 4, TAG_TEMP_PNG, qfalse); + if (!tempData) { + ri.Printf(PRINT_ERROR, "Could not allocate enough memory to load the image."); return 0; } // Dynamic array of row pointers, with 'height' elements, initialized to NULL. - byte **row_pointers = (byte **) R_Malloc (sizeof (byte *) * height_, TAG_TEMP_PNG, qfalse); - if ( !row_pointers ) - { - ri.Printf (PRINT_ERROR, "Could not allocate enough memory to load the image."); + byte **row_pointers = (byte **)R_Malloc(sizeof(byte *) * height_, TAG_TEMP_PNG, qfalse); + if (!row_pointers) { + ri.Printf(PRINT_ERROR, "Could not allocate enough memory to load the image."); - R_Free (tempData); + R_Free(tempData); return 0; } // Re-set the jmp so that these new memory allocations can be reclaimed - if ( setjmp (png_jmpbuf (png_ptr)) ) - { - R_Free (row_pointers); - R_Free (tempData); + if (setjmp(png_jmpbuf(png_ptr))) { + R_Free(row_pointers); + R_Free(tempData); return 0; } - for ( unsigned int i = 0, j = 0; i < height_; i++, j += 4 ) - { + for (unsigned int i = 0, j = 0; i < height_; i++, j += 4) { row_pointers[i] = tempData + j * width_; } - png_read_image (png_ptr, row_pointers); + png_read_image(png_ptr, row_pointers); // Finish reading - png_read_end (png_ptr, NULL); + png_read_end(png_ptr, NULL); - R_Free (row_pointers); + R_Free(row_pointers); // Finally assign all the parameters *data = tempData; @@ -280,35 +250,32 @@ struct PNGFileReader return 1; } - void ReadBytes ( void *dest, size_t len ) - { - memcpy (dest, buf + offset, len); + void ReadBytes(void *dest, size_t len) { + memcpy(dest, buf + offset, len); offset += len; } -private: + private: char *buf; size_t offset; png_structp png_ptr; png_infop info_ptr; }; -void user_read_data( png_structp png_ptr, png_bytep data, png_size_t length ) { - png_voidp r = png_get_io_ptr (png_ptr); +void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { + png_voidp r = png_get_io_ptr(png_ptr); PNGFileReader *reader = (PNGFileReader *)r; - reader->ReadBytes (data, length); + reader->ReadBytes(data, length); } // Loads a PNG image from file. -void LoadPNG ( const char *filename, byte **data, int *width, int *height ) -{ +void LoadPNG(const char *filename, byte **data, int *width, int *height) { char *buf = NULL; - int len = ri.FS_ReadFile (filename, (void **)&buf); - if ( len < 0 || buf == NULL ) - { + int len = ri.FS_ReadFile(filename, (void **)&buf); + if (len < 0 || buf == NULL) { return; } - PNGFileReader reader (buf); - reader.Read (data, width, height); + PNGFileReader reader(buf); + reader.Read(data, width, height); } diff --git a/code/rd-common/tr_image_tga.cpp b/code/rd-common/tr_image_tga.cpp index 05478ad5fa..e888df6c1c 100644 --- a/code/rd-common/tr_image_tga.cpp +++ b/code/rd-common/tr_image_tga.cpp @@ -29,114 +29,102 @@ along with this program; if not, see . // My TGA loader... // //--------------------------------------------------- -#pragma pack(push,1) +#pragma pack(push, 1) typedef struct TGAHeader_s { - byte byIDFieldLength; // must be 0 - byte byColourmapType; // 0 = truecolour, 1 = paletted, else bad - byte byImageType; // 1 = colour mapped (palette), uncompressed, 2 = truecolour, uncompressed, else bad - word w1stColourMapEntry; // must be 0 - word wColourMapLength; // 256 for 8-bit palettes, else 0 for true-colour - byte byColourMapEntrySize; // 24 for 8-bit palettes, else 0 for true-colour - word wImageXOrigin; // ignored - word wImageYOrigin; // ignored - word wImageWidth; // in pixels - word wImageHeight; // in pixels - byte byImagePlanes; // bits per pixel (8 for paletted, else 24 for true-colour) - byte byScanLineOrder; // Image descriptor bytes - // bits 0-3 = # attr bits (alpha chan) - // bits 4-5 = pixel order/dir - // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) + byte byIDFieldLength; // must be 0 + byte byColourmapType; // 0 = truecolour, 1 = paletted, else bad + byte byImageType; // 1 = colour mapped (palette), uncompressed, 2 = truecolour, uncompressed, else bad + word w1stColourMapEntry; // must be 0 + word wColourMapLength; // 256 for 8-bit palettes, else 0 for true-colour + byte byColourMapEntrySize; // 24 for 8-bit palettes, else 0 for true-colour + word wImageXOrigin; // ignored + word wImageYOrigin; // ignored + word wImageWidth; // in pixels + word wImageHeight; // in pixels + byte byImagePlanes; // bits per pixel (8 for paletted, else 24 for true-colour) + byte byScanLineOrder; // Image descriptor bytes + // bits 0-3 = # attr bits (alpha chan) + // bits 4-5 = pixel order/dir + // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) } TGAHeader_t; #pragma pack(pop) - // *pic == pic, else NULL for failed. // // returns false if found but had a format error, else true for either OK or not-found (there's a reason for this) // -void LoadTGA ( const char *name, byte **pic, int *width, int *height) -{ +void LoadTGA(const char *name, byte **pic, int *width, int *height) { char sErrorString[1024]; bool bFormatErrors = false; // these don't need to be declared or initialised until later, but the compiler whines that 'goto' skips them. // byte *pRGBA = NULL; - byte *pOut = NULL; - byte *pIn = NULL; - + byte *pOut = NULL; + byte *pIn = NULL; *pic = NULL; -#define TGA_FORMAT_ERROR(blah) {sprintf(sErrorString,blah); bFormatErrors = true; goto TGADone;} -//#define TGA_FORMAT_ERROR(blah) Com_Error( ERR_DROP, blah ); +#define TGA_FORMAT_ERROR(blah) \ + { \ + sprintf(sErrorString, blah); \ + bFormatErrors = true; \ + goto TGADone; \ + } + //#define TGA_FORMAT_ERROR(blah) Com_Error( ERR_DROP, blah ); // // load the file // byte *pTempLoadedBuffer = 0; - ri.FS_ReadFile ( ( char * ) name, (void **)&pTempLoadedBuffer); + ri.FS_ReadFile((char *)name, (void **)&pTempLoadedBuffer); if (!pTempLoadedBuffer) { return; } - TGAHeader_t *pHeader = (TGAHeader_t *) pTempLoadedBuffer; + TGAHeader_t *pHeader = (TGAHeader_t *)pTempLoadedBuffer; pHeader->wColourMapLength = LittleShort(pHeader->wColourMapLength); pHeader->wImageWidth = LittleShort(pHeader->wImageWidth); pHeader->wImageHeight = LittleShort(pHeader->wImageHeight); - if (pHeader->byColourmapType!=0) - { - TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n" ); + if (pHeader->byColourmapType != 0) { + TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n"); } - if (pHeader->byImageType != 2 && pHeader->byImageType != 3 && pHeader->byImageType != 10) - { + if (pHeader->byImageType != 2 && pHeader->byImageType != 3 && pHeader->byImageType != 10) { TGA_FORMAT_ERROR("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RLE-RGB) images supported\n"); } - if (pHeader->w1stColourMapEntry != 0) - { - TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n" ); + if (pHeader->w1stColourMapEntry != 0) { + TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n"); } - if (pHeader->wColourMapLength !=0 && pHeader->wColourMapLength != 256) - { - TGA_FORMAT_ERROR("LoadTGA: ColourMapLength must be either 0 or 256\n" ); + if (pHeader->wColourMapLength != 0 && pHeader->wColourMapLength != 256) { + TGA_FORMAT_ERROR("LoadTGA: ColourMapLength must be either 0 or 256\n"); } - if (pHeader->byColourMapEntrySize != 0 && pHeader->byColourMapEntrySize != 24) - { - TGA_FORMAT_ERROR("LoadTGA: ColourMapEntrySize must be either 0 or 24\n" ); + if (pHeader->byColourMapEntrySize != 0 && pHeader->byColourMapEntrySize != 24) { + TGA_FORMAT_ERROR("LoadTGA: ColourMapEntrySize must be either 0 or 24\n"); } - if ( ( pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) && (pHeader->byImagePlanes != 8 && pHeader->byImageType != 3)) - { + if ((pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) && (pHeader->byImagePlanes != 8 && pHeader->byImageType != 3)) { TGA_FORMAT_ERROR("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n"); } - if ((pHeader->byScanLineOrder&0x30)!=0x00 && - (pHeader->byScanLineOrder&0x30)!=0x10 && - (pHeader->byScanLineOrder&0x30)!=0x20 && - (pHeader->byScanLineOrder&0x30)!=0x30 - ) - { + if ((pHeader->byScanLineOrder & 0x30) != 0x00 && (pHeader->byScanLineOrder & 0x30) != 0x10 && (pHeader->byScanLineOrder & 0x30) != 0x20 && + (pHeader->byScanLineOrder & 0x30) != 0x30) { TGA_FORMAT_ERROR("LoadTGA: ScanLineOrder must be either 0x00,0x10,0x20, or 0x30\n"); } - - // these last checks are so i can use ID's RLE-code. I don't dare fiddle with it or it'll probably break... // - if ( pHeader->byImageType == 10) - { - if ((pHeader->byScanLineOrder & 0x30) != 0x00) - { + if (pHeader->byImageType == 10) { + if ((pHeader->byScanLineOrder & 0x30) != 0x00) { TGA_FORMAT_ERROR("LoadTGA: RLE-RGB Images (type 10) must be in bottom-to-top format\n"); } - if (pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) // probably won't happen, but avoids compressed greyscales? + if (pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) // probably won't happen, but avoids compressed greyscales? { TGA_FORMAT_ERROR("LoadTGA: RLE-RGB Images (type 10) must be 24 or 32 bit\n"); } @@ -149,50 +137,49 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) // bits 4-5 = pixel order/dir // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) // - int iYStart,iXStart,iYStep,iXStep; + int iYStart, iXStart, iYStep, iXStep; - switch(pHeader->byScanLineOrder & 0x30) - { - default: // default case stops the compiler complaining about using uninitialised vars - case 0x00: // left to right, bottom to top + switch (pHeader->byScanLineOrder & 0x30) { + default: // default case stops the compiler complaining about using uninitialised vars + case 0x00: // left to right, bottom to top - iXStart = 0; - iXStep = 1; + iXStart = 0; + iXStep = 1; - iYStart = pHeader->wImageHeight-1; - iYStep = -1; + iYStart = pHeader->wImageHeight - 1; + iYStep = -1; - break; + break; - case 0x10: // right to left, bottom to top + case 0x10: // right to left, bottom to top - iXStart = pHeader->wImageWidth-1; - iXStep = -1; + iXStart = pHeader->wImageWidth - 1; + iXStep = -1; - iYStart = pHeader->wImageHeight-1; - iYStep = -1; + iYStart = pHeader->wImageHeight - 1; + iYStep = -1; - break; + break; - case 0x20: // left to right, top to bottom + case 0x20: // left to right, top to bottom - iXStart = 0; - iXStep = 1; + iXStart = 0; + iXStep = 1; - iYStart = 0; - iYStep = 1; + iYStart = 0; + iYStep = 1; - break; + break; - case 0x30: // right to left, top to bottom + case 0x30: // right to left, top to bottom - iXStart = pHeader->wImageWidth-1; - iXStep = -1; + iXStart = pHeader->wImageWidth - 1; + iXStep = -1; - iYStart = 0; - iYStep = 1; + iYStart = 0; + iYStep = 1; - break; + break; } // feed back the results... @@ -202,116 +189,107 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) if (height) *height = pHeader->wImageHeight; - pRGBA = (byte *) R_Malloc (pHeader->wImageWidth * pHeader->wImageHeight * 4, TAG_TEMP_WORKSPACE, qfalse); - *pic = pRGBA; - pOut = pRGBA; - pIn = pTempLoadedBuffer + sizeof(*pHeader); + pRGBA = (byte *)R_Malloc(pHeader->wImageWidth * pHeader->wImageHeight * 4, TAG_TEMP_WORKSPACE, qfalse); + *pic = pRGBA; + pOut = pRGBA; + pIn = pTempLoadedBuffer + sizeof(*pHeader); // I don't know if this ID-thing here is right, since comments that I've seen are at the end of the file, // with a zero in this field. However, may as well... // if (pHeader->byIDFieldLength != 0) - pIn += pHeader->byIDFieldLength; // skip TARGA image comment + pIn += pHeader->byIDFieldLength; // skip TARGA image comment - byte red,green,blue,alpha; + byte red, green, blue, alpha; - if ( pHeader->byImageType == 2 || pHeader->byImageType == 3 ) // RGB or greyscale + if (pHeader->byImageType == 2 || pHeader->byImageType == 3) // RGB or greyscale { - for (int y=iYStart, iYCount=0; iYCountwImageHeight; y+=iYStep, iYCount++) - { - pOut = pRGBA + y * pHeader->wImageWidth *4; - for (int x=iXStart, iXCount=0; iXCountwImageWidth; x+=iXStep, iXCount++) - { - switch (pHeader->byImagePlanes) - { - case 8: - blue = *pIn++; - green = blue; - red = blue; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 24: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = alpha; - break; - - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: Image can only have 8, 24 or 32 planes for RGB/greyscale\n"); - break; + for (int y = iYStart, iYCount = 0; iYCount < pHeader->wImageHeight; y += iYStep, iYCount++) { + pOut = pRGBA + y * pHeader->wImageWidth * 4; + for (int x = iXStart, iXCount = 0; iXCount < pHeader->wImageWidth; x += iXStep, iXCount++) { + switch (pHeader->byImagePlanes) { + case 8: + blue = *pIn++; + green = blue; + red = blue; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 24: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 32: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = alpha; + break; + + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: Image can only have 8, 24 or 32 planes for RGB/greyscale\n"); + break; } } } - } - else - if (pHeader->byImageType == 10) // RLE-RGB + } else if (pHeader->byImageType == 10) // RLE-RGB { // I've no idea if this stuff works, I normally reject RLE targas, but this is from ID's code // so maybe I should try and support it... // byte packetHeader, packetSize, j; - for (int y = pHeader->wImageHeight-1; y >= 0; y--) - { - pOut = pRGBA + y * pHeader->wImageWidth *4; - for (int x=0; xwImageWidth;) - { + for (int y = pHeader->wImageHeight - 1; y >= 0; y--) { + pOut = pRGBA + y * pHeader->wImageWidth * 4; + for (int x = 0; x < pHeader->wImageWidth;) { packetHeader = *pIn++; - packetSize = 1 + (packetHeader & 0x7f); - if (packetHeader & 0x80) // run-length packet + packetSize = 1 + (packetHeader & 0x7f); + if (packetHeader & 0x80) // run-length packet { - switch (pHeader->byImagePlanes) - { - case 24: + switch (pHeader->byImagePlanes) { + case 24: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = 255; - break; + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = 255; + break; - case 32: + case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - break; + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + break; - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); - break; + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); + break; } - for (j=0; jwImageWidth) // run spans across rows + if (x == pHeader->wImageWidth) // run spans across rows { x = 0; if (y > 0) @@ -321,43 +299,39 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) pOut = pRGBA + y * pHeader->wImageWidth * 4; } } - } - else - { // non run-length packet + } else { // non run-length packet - for (j=0; jbyImagePlanes) - { - case 24: - - blue = *pIn++; - green = *pIn++; - red = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = alpha; - break; - - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); - break; + for (j = 0; j < packetSize; j++) { + switch (pHeader->byImagePlanes) { + case 24: + + blue = *pIn++; + green = *pIn++; + red = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 32: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = alpha; + break; + + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); + break; } x++; - if (x == pHeader->wImageWidth) // pixel packet run spans across rows + if (x == pHeader->wImageWidth) // pixel packet run spans across rows { x = 0; if (y > 0) @@ -375,11 +349,9 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) TGADone: - ri.FS_FreeFile (pTempLoadedBuffer); + ri.FS_FreeFile(pTempLoadedBuffer); - if (bFormatErrors) - { - Com_Error( ERR_DROP, "%s( File: \"%s\" )\n",sErrorString,name); + if (bFormatErrors) { + Com_Error(ERR_DROP, "%s( File: \"%s\" )\n", sErrorString, name); } } - diff --git a/code/rd-common/tr_noise.cpp b/code/rd-common/tr_noise.cpp index f771ffebe0..f42809ecd8 100644 --- a/code/rd-common/tr_noise.cpp +++ b/code/rd-common/tr_noise.cpp @@ -29,46 +29,41 @@ along with this program; if not, see . #include "tr_common.h" #define NOISE_SIZE 256 -#define NOISE_MASK ( NOISE_SIZE - 1 ) +#define NOISE_MASK (NOISE_SIZE - 1) -#define VAL( a ) s_noise_perm[ ( a ) & ( NOISE_MASK )] -#define INDEX( x, y, z, t ) VAL( x + VAL( y + VAL( z + VAL( t ) ) ) ) +#define VAL(a) s_noise_perm[(a) & (NOISE_MASK)] +#define INDEX(x, y, z, t) VAL(x + VAL(y + VAL(z + VAL(t)))) static float s_noise_table[NOISE_SIZE]; static int s_noise_perm[NOISE_SIZE]; -#define LERP( a, b, w ) ( a * ( 1.0f - w ) + b * w ) +#define LERP(a, b, w) (a * (1.0f - w) + b * w) -static float GetNoiseValue( int x, int y, int z, int t ) -{ - int index = INDEX( ( int ) x, ( int ) y, ( int ) z, ( int ) t ); +static float GetNoiseValue(int x, int y, int z, int t) { + int index = INDEX((int)x, (int)y, (int)z, (int)t); return s_noise_table[index]; } -float GetNoiseTime( int t ) -{ - int index = VAL( t ); +float GetNoiseTime(int t) { + int index = VAL(t); - return (1+s_noise_table[index]); + return (1 + s_noise_table[index]); } -void R_NoiseInit( void ) -{ +void R_NoiseInit(void) { int i; - srand( 1001 ); + srand(1001); - for ( i = 0; i < NOISE_SIZE; i++ ) - { - s_noise_table[i] = ( float ) ( ( ( rand() / ( float ) RAND_MAX ) * 2.0 - 1.0 ) ); - s_noise_perm[i] = ( unsigned char ) ( rand() / ( float ) RAND_MAX * 255 ); + for (i = 0; i < NOISE_SIZE; i++) { + s_noise_table[i] = (float)(((rand() / (float)RAND_MAX) * 2.0 - 1.0)); + s_noise_perm[i] = (unsigned char)(rand() / (float)RAND_MAX * 255); } - srand( ri.com_frameTime() ); + srand(ri.com_frameTime()); } -float R_NoiseGet4f( float x, float y, float z, float t ) -{ +float R_NoiseGet4f(float x, float y, float z, float t) { int i; int ix, iy, iz, it; float fx, fy, fz, ft; @@ -76,34 +71,33 @@ float R_NoiseGet4f( float x, float y, float z, float t ) float back[4]; float fvalue, bvalue, value[2], finalvalue; - ix = ( int ) floor( x ); + ix = (int)floor(x); fx = x - ix; - iy = ( int ) floor( y ); + iy = (int)floor(y); fy = y - iy; - iz = ( int ) floor( z ); + iz = (int)floor(z); fz = z - iz; - it = ( int ) floor( t ); + it = (int)floor(t); ft = t - it; - for ( i = 0; i < 2; i++ ) - { - front[0] = GetNoiseValue( ix, iy, iz, it + i ); - front[1] = GetNoiseValue( ix+1, iy, iz, it + i ); - front[2] = GetNoiseValue( ix, iy+1, iz, it + i ); - front[3] = GetNoiseValue( ix+1, iy+1, iz, it + i ); + for (i = 0; i < 2; i++) { + front[0] = GetNoiseValue(ix, iy, iz, it + i); + front[1] = GetNoiseValue(ix + 1, iy, iz, it + i); + front[2] = GetNoiseValue(ix, iy + 1, iz, it + i); + front[3] = GetNoiseValue(ix + 1, iy + 1, iz, it + i); - back[0] = GetNoiseValue( ix, iy, iz + 1, it + i ); - back[1] = GetNoiseValue( ix+1, iy, iz + 1, it + i ); - back[2] = GetNoiseValue( ix, iy+1, iz + 1, it + i ); - back[3] = GetNoiseValue( ix+1, iy+1, iz + 1, it + i ); + back[0] = GetNoiseValue(ix, iy, iz + 1, it + i); + back[1] = GetNoiseValue(ix + 1, iy, iz + 1, it + i); + back[2] = GetNoiseValue(ix, iy + 1, iz + 1, it + i); + back[3] = GetNoiseValue(ix + 1, iy + 1, iz + 1, it + i); - fvalue = LERP( LERP( front[0], front[1], fx ), LERP( front[2], front[3], fx ), fy ); - bvalue = LERP( LERP( back[0], back[1], fx ), LERP( back[2], back[3], fx ), fy ); + fvalue = LERP(LERP(front[0], front[1], fx), LERP(front[2], front[3], fx), fy); + bvalue = LERP(LERP(back[0], back[1], fx), LERP(back[2], back[3], fx), fy); - value[i] = LERP( fvalue, bvalue, fz ); + value[i] = LERP(fvalue, bvalue, fz); } - finalvalue = LERP( value[0], value[1], ft ); + finalvalue = LERP(value[0], value[1], ft); return finalvalue; } diff --git a/code/rd-vanilla/G2_API.cpp b/code/rd-vanilla/G2_API.cpp index 09bc27edc2..f073289e4e 100644 --- a/code/rd-vanilla/G2_API.cpp +++ b/code/rd-vanilla/G2_API.cpp @@ -34,26 +34,25 @@ along with this program; if not, see . #ifdef FINAL_BUILD #define G2API_DEBUG (0) // please don't change this #else - #if defined(_DEBUG) - #define G2API_DEBUG (1) - #else - #define G2API_DEBUG (0) // change this to test g2api in release - #endif +#if defined(_DEBUG) +#define G2API_DEBUG (1) +#else +#define G2API_DEBUG (0) // change this to test g2api in release +#endif #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #include "../ghoul2/ghoul2_gore.h" -//rww - RAGDOLL_END +// rww - RAGDOLL_END -extern mdxaBone_t worldMatrix; -extern mdxaBone_t worldMatrixInv; +extern mdxaBone_t worldMatrix; +extern mdxaBone_t worldMatrixInv; -extern cvar_t *r_Ghoul2TimeBase; +extern cvar_t *r_Ghoul2TimeBase; -extern refexport_t re; - -#define G2_MODEL_OK(g) ((g)&&(g)->mValid&&(g)->aHeader&&(g)->currentModel&&(g)->animModel) +extern refexport_t re; +#define G2_MODEL_OK(g) ((g) && (g)->mValid && (g)->aHeader && (g)->currentModel && (g)->animModel) #define G2_DEBUG_TIME (0) @@ -64,198 +63,164 @@ bool G2_TestModelPointers(CGhoul2Info *ghlInfo); #if G2API_DEBUG #include //for isnan - #define MAX_ERROR_PRINTS (3) -class ErrorReporter -{ +class ErrorReporter { std::string mName; - std::map mErrors; -public: - ErrorReporter(const std::string &name) : - mName(name) - { - } - ~ErrorReporter() - { + std::map mErrors; + + public: + ErrorReporter(const std::string &name) : mName(name) {} + ~ErrorReporter() { char mess[1000]; - int total=0; - sprintf(mess,"****** %s Error Report Begin******\n",mName.c_str()); + int total = 0; + sprintf(mess, "****** %s Error Report Begin******\n", mName.c_str()); Com_DPrintf(mess); - std::map::iterator i; - for (i=mErrors.begin();i!=mErrors.end();++i) - { - total+=(*i).second; - sprintf(mess,"%s (hits %d)\n",(*i).first.c_str(),(*i).second); + std::map::iterator i; + for (i = mErrors.begin(); i != mErrors.end(); ++i) { + total += (*i).second; + sprintf(mess, "%s (hits %d)\n", (*i).first.c_str(), (*i).second); Com_DPrintf(mess); } - sprintf(mess,"****** %s Error Report End %d errors of %ld kinds******\n",mName.c_str(),total,mErrors.size()); + sprintf(mess, "****** %s Error Report End %d errors of %ld kinds******\n", mName.c_str(), total, mErrors.size()); Com_DPrintf(mess); } - int AnimTest(CGhoul2Info_v &ghoul2,const char *m,const char *, int line) - { - if (G2_SetupModelPointers(ghoul2)) - { + int AnimTest(CGhoul2Info_v &ghoul2, const char *m, const char *, int line) { + if (G2_SetupModelPointers(ghoul2)) { int i; - for (i=0; ianimModel->name); - strcpy(GLAName2,ghlInfo->aHeader->name); - strcpy(GLMName1,ghlInfo->mFileName); - strcpy(GLMName2,ghlInfo->currentModel->name); + strcpy(GLAName1, ghlInfo->animModel->name); + strcpy(GLAName2, ghlInfo->aHeader->name); + strcpy(GLMName1, ghlInfo->mFileName); + strcpy(GLMName2, ghlInfo->currentModel->name); - int numFramesInFile=ghlInfo->aHeader->numFrames; + int numFramesInFile = ghlInfo->aHeader->numFrames; - int numActiveBones=0; - for (i=0;imBlist.size();i++) - { - if (ghlInfo->mBlist[i].boneNumber!=-1) // slot used? + int numActiveBones = 0; + for (i = 0; i < ghlInfo->mBlist.size(); i++) { + if (ghlInfo->mBlist[i].boneNumber != -1) // slot used? { - if (ghlInfo->mBlist[i].flags&BONE_ANIM_TOTAL) // anim on this? + if (ghlInfo->mBlist[i].flags & BONE_ANIM_TOTAL) // anim on this? { numActiveBones++; - bool loop=!!(ghlInfo->mBlist[i].flags&BONE_ANIM_OVERRIDE_LOOP); - bool not_loop=!!(ghlInfo->mBlist[i].flags&BONE_ANIM_OVERRIDE); + bool loop = !!(ghlInfo->mBlist[i].flags & BONE_ANIM_OVERRIDE_LOOP); + bool not_loop = !!(ghlInfo->mBlist[i].flags & BONE_ANIM_OVERRIDE); - if (loop==not_loop) - { - Error("Unusual animation flags, should have some sort of override, but not both",1,0,line); + if (loop == not_loop) { + Error("Unusual animation flags, should have some sort of override, but not both", 1, 0, line); } - bool freeze=(ghlInfo->mBlist[i].flags&BONE_ANIM_OVERRIDE_FREEZE) == BONE_ANIM_OVERRIDE_FREEZE; + bool freeze = (ghlInfo->mBlist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) == BONE_ANIM_OVERRIDE_FREEZE; - if (loop&&freeze) - { - Error("Unusual animation flags, loop and freeze",1,0,line); + if (loop && freeze) { + Error("Unusual animation flags, loop and freeze", 1, 0, line); } - bool no_lerp=!!(ghlInfo->mBlist[i].flags&BONE_ANIM_NO_LERP); - bool blend=!!(ghlInfo->mBlist[i].flags&BONE_ANIM_BLEND); - - - //comments according to jake - int startFrame=ghlInfo->mBlist[i].startFrame; // start frame for animation - int endFrame=ghlInfo->mBlist[i].endFrame; // end frame for animation NOTE anim actually ends on endFrame+1 - int startTime=ghlInfo->mBlist[i].startTime; // time we started this animation - int pauseTime=ghlInfo->mBlist[i].pauseTime; // time we paused this animation - 0 if not paused - float animSpeed=ghlInfo->mBlist[i].animSpeed; // speed at which this anim runs. 1.0f means full speed of animation incoming - ie if anim is 20hrtz, we run at 20hrts. If 5hrts, we run at 5 hrts - - float blendFrame=0.0f; // frame PLUS LERP value to blend - int blendLerpFrame=0; // frame to lerp the blend frame with. - - if (blend) - { - blendFrame=ghlInfo->mBlist[i].blendFrame; - blendLerpFrame=ghlInfo->mBlist[i].blendLerpFrame; - if (floor(blendFrame)<0.0f) - { - Error("negative blendFrame",1,0,line); + bool no_lerp = !!(ghlInfo->mBlist[i].flags & BONE_ANIM_NO_LERP); + bool blend = !!(ghlInfo->mBlist[i].flags & BONE_ANIM_BLEND); + + // comments according to jake + int startFrame = ghlInfo->mBlist[i].startFrame; // start frame for animation + int endFrame = ghlInfo->mBlist[i].endFrame; // end frame for animation NOTE anim actually ends on endFrame+1 + int startTime = ghlInfo->mBlist[i].startTime; // time we started this animation + int pauseTime = ghlInfo->mBlist[i].pauseTime; // time we paused this animation - 0 if not paused + float animSpeed = ghlInfo->mBlist[i].animSpeed; // speed at which this anim runs. 1.0f means full speed of animation incoming - ie if anim + // is 20hrtz, we run at 20hrts. If 5hrts, we run at 5 hrts + + float blendFrame = 0.0f; // frame PLUS LERP value to blend + int blendLerpFrame = 0; // frame to lerp the blend frame with. + + if (blend) { + blendFrame = ghlInfo->mBlist[i].blendFrame; + blendLerpFrame = ghlInfo->mBlist[i].blendLerpFrame; + if (floor(blendFrame) < 0.0f) { + Error("negative blendFrame", 1, 0, line); } - if (ceil(blendFrame)>=float(numFramesInFile)) - { - Error("blendFrame >= numFramesInFile",1,0,line); + if (ceil(blendFrame) >= float(numFramesInFile)) { + Error("blendFrame >= numFramesInFile", 1, 0, line); } - if (blendLerpFrame<0) - { - Error("negative blendLerpFrame",1,0,line); + if (blendLerpFrame < 0) { + Error("negative blendLerpFrame", 1, 0, line); } - if (blendLerpFrame>=numFramesInFile) - { - Error("blendLerpFrame >= numFramesInFile",1,0,line); + if (blendLerpFrame >= numFramesInFile) { + Error("blendLerpFrame >= numFramesInFile", 1, 0, line); } } - if (startFrame<0) - { - Error("negative startFrame",1,0,line); + if (startFrame < 0) { + Error("negative startFrame", 1, 0, line); } - if (startFrame>=numFramesInFile) - { - Error("startFrame >= numFramesInFile",1,0,line); + if (startFrame >= numFramesInFile) { + Error("startFrame >= numFramesInFile", 1, 0, line); } - if (endFrame<0) - { - Error("negative endFrame",1,0,line); + if (endFrame < 0) { + Error("negative endFrame", 1, 0, line); } - if (endFrame==0&&animSpeed>0.0f) - { - Error("Zero endFrame",1,0,line); + if (endFrame == 0 && animSpeed > 0.0f) { + Error("Zero endFrame", 1, 0, line); } - if (endFrame>numFramesInFile) - { - Error("endFrame > numFramesInFile",1,0,line); + if (endFrame > numFramesInFile) { + Error("endFrame > numFramesInFile", 1, 0, line); } // mikeg call out here for further checks. - ret=(int)startTime+(int)pauseTime+(int)no_lerp; // quiet VC. + ret = (int)startTime + (int)pauseTime + (int)no_lerp; // quiet VC. } } } return ret; } - int Error(const char *m,int kind,const char *, int line) - { + int Error(const char *m, int kind, const char *, int line) { char mess[1000]; assert(m); - std::string full=mName; - if (kind==2) - { - full+=":NOTE: "; - } - else if (kind==1) - { -// assert(!"G2API Warning"); - full+=":WARNING: "; - } - else - { -// assert(!"G2API Error"); - full+=":ERROR : "; + std::string full = mName; + if (kind == 2) { + full += ":NOTE: "; + } else if (kind == 1) { + // assert(!"G2API Warning"); + full += ":WARNING: "; + } else { + // assert(!"G2API Error"); + full += ":ERROR : "; } - full+=m; - sprintf(mess," [line %d]",line); - full+=mess; + full += m; + sprintf(mess, " [line %d]", line); + full += mess; // assert(0); - int ret=0; //place a breakpoint here - std::map::iterator f=mErrors.find(full); - if (f==mErrors.end()) - { + int ret = 0; // place a breakpoint here + std::map::iterator f = mErrors.find(full); + if (f == mErrors.end()) { ret++; // or a breakpoint here for the first occurance - mErrors.insert(std::make_pair(full,0)); - f=mErrors.find(full); + mErrors.insert(std::make_pair(full, 0)); + f = mErrors.find(full); } - assert(f!=mErrors.end()); + assert(f != mErrors.end()); (*f).second++; - if ((*f).second==1000) - { - ret*=-1; // breakpoint to find a specific occurance of an error + if ((*f).second == 1000) { + ret *= -1; // breakpoint to find a specific occurance of an error } - if ((*f).second<=MAX_ERROR_PRINTS&&kind<2) - { - Com_Printf("%s (hit # %d)\n",full.c_str(),(*f).second); - if (1) - { - sprintf(mess,"%s (hit # %d)\n",full.c_str(),(*f).second); + if ((*f).second <= MAX_ERROR_PRINTS && kind < 2) { + Com_Printf("%s (hit # %d)\n", full.c_str(), (*f).second); + if (1) { + sprintf(mess, "%s (hit # %d)\n", full.c_str(), (*f).second); Com_DPrintf(mess); } } @@ -264,326 +229,292 @@ class ErrorReporter }; #include "assert.h" -ErrorReporter &G2APIError() -{ +ErrorReporter &G2APIError() { static ErrorReporter singleton("G2API"); return singleton; } -#define G2ERROR(exp,m) (void)( (exp) || (G2APIError().Error(m,0,__FILE__,__LINE__), 0) ) -#define G2WARNING(exp,m) (void)( (exp) || (G2APIError().Error(m,1,__FILE__,__LINE__), 0) ) -#define G2NOTE(exp,m) (void)( (exp) || (G2APIError().Error(m,2,__FILE__,__LINE__), 0) ) -#define G2ANIM(ghlInfo,m) (void)((G2APIError().AnimTest(ghlInfo,m,__FILE__,__LINE__), 0) ) +#define G2ERROR(exp, m) (void)((exp) || (G2APIError().Error(m, 0, __FILE__, __LINE__), 0)) +#define G2WARNING(exp, m) (void)((exp) || (G2APIError().Error(m, 1, __FILE__, __LINE__), 0)) +#define G2NOTE(exp, m) (void)((exp) || (G2APIError().Error(m, 2, __FILE__, __LINE__), 0)) +#define G2ANIM(ghlInfo, m) (void)((G2APIError().AnimTest(ghlInfo, m, __FILE__, __LINE__), 0)) #else -#define G2ERROR(exp,m) ((void)0) -#define G2WARNING(exp,m) ((void)0) -#define G2NOTE(exp,m) ((void)0) -#define G2ANIM(ghlInfo,m) ((void)0) +#define G2ERROR(exp, m) ((void)0) +#define G2WARNING(exp, m) ((void)0) +#define G2NOTE(exp, m) ((void)0) +#define G2ANIM(ghlInfo, m) ((void)0) #endif #ifdef _DEBUG -void G2_Bone_Not_Found(const char *boneName,const char *modName) -{ - G2ERROR(boneName,"NULL Bone Name"); - G2ERROR(boneName[0],"Empty Bone Name"); - if (boneName) - { - G2NOTE(0,va("Bone Not Found (%s:%s)",boneName,modName)); +void G2_Bone_Not_Found(const char *boneName, const char *modName) { + G2ERROR(boneName, "NULL Bone Name"); + G2ERROR(boneName[0], "Empty Bone Name"); + if (boneName) { + G2NOTE(0, va("Bone Not Found (%s:%s)", boneName, modName)); } } -void G2_Bolt_Not_Found(const char *boneName,const char *modName) -{ - G2ERROR(boneName,"NULL Bolt/Bone Name"); - G2ERROR(boneName[0],"Empty Bolt/Bone Name"); - if (boneName) - { - G2NOTE(0,va("Bolt/Bone Not Found (%s:%s)",boneName,modName)); +void G2_Bolt_Not_Found(const char *boneName, const char *modName) { + G2ERROR(boneName, "NULL Bolt/Bone Name"); + G2ERROR(boneName[0], "Empty Bolt/Bone Name"); + if (boneName) { + G2NOTE(0, va("Bolt/Bone Not Found (%s:%s)", boneName, modName)); } } #endif -void G2API_SetTime(int currentTime,int clock) -{ - assert(clock>=0&&clock= 0 && clock < NUM_G2T_TIME); #if G2_DEBUG_TIME - Com_Printf("Set Time: before c%6d s%6d",G2TimeBases[1],G2TimeBases[0]); + Com_Printf("Set Time: before c%6d s%6d", G2TimeBases[1], G2TimeBases[0]); #endif - G2TimeBases[clock]=currentTime; - if (G2TimeBases[1]>G2TimeBases[0]+200) - { - G2TimeBases[1]=0; // use server time instead + G2TimeBases[clock] = currentTime; + if (G2TimeBases[1] > G2TimeBases[0] + 200) { + G2TimeBases[1] = 0; // use server time instead return; } #if G2_DEBUG_TIME - Com_Printf(" after c%6d s%6d\n",G2TimeBases[1],G2TimeBases[0]); + Com_Printf(" after c%6d s%6d\n", G2TimeBases[1], G2TimeBases[0]); #endif } -int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar +int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar { - int ret=G2TimeBases[1]; - if ( !ret ) - { + int ret = G2TimeBases[1]; + if (!ret) { ret = G2TimeBases[0]; } return ret; } - // must be a power of two #define MAX_G2_MODELS (512) #define G2_MODEL_BITS (9) -#define G2_INDEX_MASK (MAX_G2_MODELS-1) +#define G2_INDEX_MASK (MAX_G2_MODELS - 1) void RemoveBoneCache(CBoneCache *boneCache); -static size_t GetSizeOfGhoul2Info ( const CGhoul2Info& g2Info ) -{ +static size_t GetSizeOfGhoul2Info(const CGhoul2Info &g2Info) { size_t size = 0; // This is pretty ugly, but we don't want to save everything in the CGhoul2Info object. - size += offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + size += offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); // Surface vector + size - size += sizeof (int); - size += g2Info.mSlist.size() * sizeof (surfaceInfo_t); + size += sizeof(int); + size += g2Info.mSlist.size() * sizeof(surfaceInfo_t); // Bone vector + size - size += sizeof (int); - size += g2Info.mBlist.size() * sizeof (boneInfo_t); + size += sizeof(int); + size += g2Info.mBlist.size() * sizeof(boneInfo_t); // Bolt vector + size - size += sizeof (int); - size += g2Info.mBltlist.size() * sizeof (boltInfo_t); + size += sizeof(int); + size += g2Info.mBltlist.size() * sizeof(boltInfo_t); return size; } -static size_t SerializeGhoul2Info ( char *buffer, const CGhoul2Info& g2Info ) -{ +static size_t SerializeGhoul2Info(char *buffer, const CGhoul2Info &g2Info) { char *base = buffer; size_t blockSize; // Oh the ugliness... - blockSize = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (buffer, &g2Info.mModelindex, blockSize); + blockSize = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(buffer, &g2Info.mModelindex, blockSize); buffer += blockSize; // Surfaces vector + size *(int *)buffer = g2Info.mSlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mSlist.size() * sizeof (surfaceInfo_t); - memcpy (buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof (surfaceInfo_t)); + blockSize = g2Info.mSlist.size() * sizeof(surfaceInfo_t); + memcpy(buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof(surfaceInfo_t)); buffer += blockSize; // Bones vector + size *(int *)buffer = g2Info.mBlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mBlist.size() * sizeof (boneInfo_t); - memcpy (buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof (boneInfo_t)); + blockSize = g2Info.mBlist.size() * sizeof(boneInfo_t); + memcpy(buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof(boneInfo_t)); buffer += blockSize; // Bolts vector + size *(int *)buffer = g2Info.mBltlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mBltlist.size() * sizeof (boltInfo_t); - memcpy (buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof (boltInfo_t)); + blockSize = g2Info.mBltlist.size() * sizeof(boltInfo_t); + memcpy(buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof(boltInfo_t)); buffer += blockSize; return static_cast(buffer - base); } -static size_t DeserializeGhoul2Info ( const char *buffer, CGhoul2Info& g2Info ) -{ +static size_t DeserializeGhoul2Info(const char *buffer, CGhoul2Info &g2Info) { const char *base = buffer; size_t size; - size = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (&g2Info.mModelindex, buffer, size); + size = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(&g2Info.mModelindex, buffer, size); buffer += size; // Surfaces vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mSlist.assign ((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); - buffer += sizeof (surfaceInfo_t) * size; + g2Info.mSlist.assign((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); + buffer += sizeof(surfaceInfo_t) * size; // Bones vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBlist.assign ((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); - buffer += sizeof (boneInfo_t) * size; + g2Info.mBlist.assign((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); + buffer += sizeof(boneInfo_t) * size; // Bolt vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBltlist.assign ((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); - buffer += sizeof (boltInfo_t) * size; + g2Info.mBltlist.assign((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); + buffer += sizeof(boltInfo_t) * size; return static_cast(buffer - base); } -class Ghoul2InfoArray : public IGhoul2InfoArray -{ - std::vector mInfos[MAX_G2_MODELS]; - int mIds[MAX_G2_MODELS]; - std::list mFreeIndecies; - void DeleteLow(int idx) - { +class Ghoul2InfoArray : public IGhoul2InfoArray { + std::vector mInfos[MAX_G2_MODELS]; + int mIds[MAX_G2_MODELS]; + std::list mFreeIndecies; + void DeleteLow(int idx) { { - size_t model; - for (model=0; model< mInfos[idx].size(); model++) - { + size_t model; + for (model = 0; model < mInfos[idx].size(); model++) { RemoveBoneCache(mInfos[idx][model].mBoneCache); - mInfos[idx][model].mBoneCache=0; + mInfos[idx][model].mBoneCache = 0; } } mInfos[idx].clear(); - if ((mIds[idx]>>G2_MODEL_BITS)>(1<<(31-G2_MODEL_BITS))) - { - mIds[idx]=MAX_G2_MODELS+idx; //rollover reset id to minimum value + if ((mIds[idx] >> G2_MODEL_BITS) > (1 << (31 - G2_MODEL_BITS))) { + mIds[idx] = MAX_G2_MODELS + idx; // rollover reset id to minimum value mFreeIndecies.push_back(idx); - } - else - { - mIds[idx]+=MAX_G2_MODELS; + } else { + mIds[idx] += MAX_G2_MODELS; mFreeIndecies.push_front(idx); } } -public: - Ghoul2InfoArray() - { + + public: + Ghoul2InfoArray() { size_t i; - for (i=0;i(buffer - base); } - size_t Deserialize ( const char *buffer, size_t size ) - { + size_t Deserialize(const char *buffer, size_t size) { const char *base = buffer; size_t count; // Free indices count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mFreeIndecies.assign ((int *)buffer, (int *)buffer + count); - buffer += sizeof (int) * count; + mFreeIndecies.assign((int *)buffer, (int *)buffer + count); + buffer += sizeof(int) * count; // IDs - memcpy (mIds, buffer, sizeof (mIds)); - buffer += sizeof (mIds); + memcpy(mIds, buffer, sizeof(mIds)); + buffer += sizeof(mIds); // Ghoul2 infos - for ( size_t i = 0; i < MAX_G2_MODELS; i++ ) - { + for (size_t i = 0; i < MAX_G2_MODELS; i++) { mInfos[i].clear(); count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mInfos[i].resize (count); + mInfos[i].resize(count); - for ( size_t j = 0; j < count; j++ ) - { - buffer += DeserializeGhoul2Info (buffer, mInfos[i][j]); + for (size_t j = 0; j < count; j++) { + buffer += DeserializeGhoul2Info(buffer, mInfos[i][j]); } } return static_cast(buffer - base); } - ~Ghoul2InfoArray() - { - if (mFreeIndecies.size()::iterator j; - for (j=mFreeIndecies.begin();j!=mFreeIndecies.end();++j) - { - if (*j==i) + for (j = mFreeIndecies.begin(); j != mFreeIndecies.end(); ++j) { + if (*j == i) break; } - if (j==mFreeIndecies.end()) - { + if (j == mFreeIndecies.end()) { #if G2API_DEBUG - sprintf(mess,"Leaked Info idx=%d id=%d sz=%ld\n", i, mIds[i], mInfos[i].size()); + sprintf(mess, "Leaked Info idx=%d id=%d sz=%ld\n", i, mIds[i], mInfos[i].size()); Com_DPrintf(mess); - if (mInfos[i].size()) - { - sprintf(mess,"%s\n", mInfos[i][0].mFileName); + if (mInfos[i].size()) { + sprintf(mess, "%s\n", mInfos[i][0].mFileName); Com_DPrintf(mess); } #endif @@ -592,87 +523,71 @@ class Ghoul2InfoArray : public IGhoul2InfoArray } } #if G2API_DEBUG - else - { + else { Com_DPrintf("No ghoul2 info slots leaked\n"); } #endif } - int New() - { - if (mFreeIndecies.empty()) - { + int New() { + if (mFreeIndecies.empty()) { assert(0); Com_Error(ERR_FATAL, "Out of ghoul2 info slots"); - } // gonna pull from the front, doing a - int idx=*mFreeIndecies.begin(); + int idx = *mFreeIndecies.begin(); mFreeIndecies.erase(mFreeIndecies.begin()); return mIds[idx]; } - bool IsValid(int handle) const - { - if (!handle) - { + bool IsValid(int handle) const { + if (!handle) { return false; } - assert(handle>0); //negative handle??? - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK) 0); // negative handle??? + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + if (mIds[handle & G2_INDEX_MASK] != handle) // not a valid handle, could be old { return false; } return true; } - void Delete(int handle) - { - if (!handle) - { + void Delete(int handle) { + if (!handle) { return; } - assert(handle>0); //null handle - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK) 0); // null handle + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + if (mIds[handle & G2_INDEX_MASK] == handle) { + DeleteLow(handle & G2_INDEX_MASK); } } - std::vector &Get(int handle) - { - assert(handle>0); //null handle - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); + std::vector &Get(int handle) { + assert(handle > 0); // null handle + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + assert(!(handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle)); - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - const std::vector &Get(int handle) const - { - assert(handle>0); - assert(mIds[handle&G2_INDEX_MASK]==handle); // not a valid handle, could be old or garbage - return mInfos[handle&G2_INDEX_MASK]; + const std::vector &Get(int handle) const { + assert(handle > 0); + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + return mInfos[handle & G2_INDEX_MASK]; } #if G2API_DEBUG - std::vector &GetDebug(int handle) - { - assert (!(handle<=0||(handle&G2_INDEX_MASK)<0||(handle&G2_INDEX_MASK)>=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); + std::vector &GetDebug(int handle) { + assert(!(handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle)); - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - void TestAllAnims() - { - for (size_t j=0;j &ghoul2=mInfos[j]; - for (size_t i=0; i &ghoul2 = mInfos[j]; + for (size_t i = 0; i < ghoul2.size(); i++) { + if (G2_SetupModelPointers(&ghoul2[i])) { + G2ANIM(&ghoul2[i], "Test All"); } } } @@ -681,123 +596,97 @@ class Ghoul2InfoArray : public IGhoul2InfoArray #endif }; - static Ghoul2InfoArray *singleton = NULL; -IGhoul2InfoArray &TheGhoul2InfoArray() -{ - if(!singleton) { +IGhoul2InfoArray &TheGhoul2InfoArray() { + if (!singleton) { singleton = new Ghoul2InfoArray; } return *singleton; } #if G2API_DEBUG -std::vector &DebugG2Info(int handle) -{ - return ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->GetDebug(handle); -} +std::vector &DebugG2Info(int handle) { return ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->GetDebug(handle); } -CGhoul2Info &DebugG2InfoI(int handle,int item) -{ - return ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->GetDebug(handle)[item]; -} +CGhoul2Info &DebugG2InfoI(int handle, int item) { return ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->GetDebug(handle)[item]; } -void TestAllGhoul2Anims() -{ - ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->TestAllAnims(); -} +void TestAllGhoul2Anims() { ((Ghoul2InfoArray *)(&TheGhoul2InfoArray()))->TestAllAnims(); } #endif #define PERSISTENT_G2DATA "g2infoarray" -void RestoreGhoul2InfoArray() -{ - if (singleton == NULL) - { +void RestoreGhoul2InfoArray() { + if (singleton == NULL) { // Create the ghoul2 info array TheGhoul2InfoArray(); size_t size; - const void *data = ri.PD_Load (PERSISTENT_G2DATA, &size); - if ( data == NULL ) - { + const void *data = ri.PD_Load(PERSISTENT_G2DATA, &size); + if (data == NULL) { return; } #ifdef _DEBUG size_t read = #endif // _DEBUG - singleton->Deserialize ((const char *)data, size); - R_Free ((void *)data); + singleton->Deserialize((const char *)data, size); + R_Free((void *)data); #ifdef _DEBUG - assert (read == size); + assert(read == size); #endif } } -void SaveGhoul2InfoArray() -{ +void SaveGhoul2InfoArray() { size_t size = singleton->GetSerializedSize(); - void *data = R_Malloc (size, TAG_GHOUL2, qfalse); + void *data = R_Malloc(size, TAG_GHOUL2, qfalse); #ifdef _DEBUG size_t written = #endif // _DEBUG - singleton->Serialize ((char *)data); + singleton->Serialize((char *)data); #ifdef _DEBUG - assert (written == size); + assert(written == size); #endif // _DEBUG - if ( !ri.PD_Store (PERSISTENT_G2DATA, data, size) ) - { - Com_Printf (S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); + if (!ri.PD_Store(PERSISTENT_G2DATA, data, size)) { + Com_Printf(S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); } } // this is the ONLY function to read entity states directly -void G2API_CleanGhoul2Models(CGhoul2Info_v &ghoul2) -{ +void G2API_CleanGhoul2Models(CGhoul2Info_v &ghoul2) { #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif ghoul2.~CGhoul2Info_v(); } -qhandle_t G2API_PrecacheGhoul2Model(const char *fileName) -{ - return RE_RegisterModel((char *)fileName); -} +qhandle_t G2API_PrecacheGhoul2Model(const char *fileName) { return RE_RegisterModel((char *)fileName); } // initialise all that needs to be on a new Ghoul II model -int G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int, qhandle_t customSkin, - qhandle_t customShader, int modelFlags, int lodBias) -{ - int model = -1; +int G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias) { + int model = -1; - G2ERROR(fileName&&fileName[0],"NULL filename"); + G2ERROR(fileName && fileName[0], "NULL filename"); - if (!fileName||!fileName[0]) - { + if (!fileName || !fileName[0]) { assert(fileName[0]); return -1; } // find a free spot in the list - for (model=0; model< ghoul2.size(); model++) - { - if (ghoul2[model].mModelindex == -1) - { - ghoul2[model]=CGhoul2Info(); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModelindex == -1) { + ghoul2[model] = CGhoul2Info(); break; } } - if (model==ghoul2.size()) - { - assert(model < 8); //arb, just catching run-away models + if (model == ghoul2.size()) { + assert(model < 8); // arb, just catching run-away models CGhoul2Info info; Q_strncpyz(info.mFileName, fileName, sizeof(info.mFileName)); info.mModelindex = 0; - if(G2_TestModelPointers(&info)) { - ghoul2.push_back(CGhoul2Info()); + if (G2_TestModelPointers(&info)) { + ghoul2.push_back(CGhoul2Info()); } else { return -1; } @@ -805,13 +694,10 @@ int G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int, qhan Q_strncpyz(ghoul2[model].mFileName, fileName, sizeof(ghoul2[model].mFileName)); ghoul2[model].mModelindex = model; - if (!G2_TestModelPointers(&ghoul2[model])) - { - ghoul2[model].mFileName[0]=0; + if (!G2_TestModelPointers(&ghoul2[model])) { + ghoul2[model].mFileName[0] = 0; ghoul2[model].mModelindex = -1; - } - else - { + } else { G2_Init_Bone_List(ghoul2[model].mBlist, ghoul2[model].aHeader->numBones); G2_Init_Bolt_List(ghoul2[model].mBltlist); ghoul2[model].mCustomShader = customShader; @@ -825,35 +711,29 @@ int G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int, qhan return ghoul2[model].mModelindex; } -qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) -{ - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mLodBias = lodBias; return qtrue; } return qfalse; } -qboolean G2API_SetSkin(CGhoul2Info *ghlInfo, qhandle_t customSkin, qhandle_t renderSkin) -{ - G2ERROR(ghlInfo,"NULL ghlInfo"); +qboolean G2API_SetSkin(CGhoul2Info *ghlInfo, qhandle_t customSkin, qhandle_t renderSkin) { + G2ERROR(ghlInfo, "NULL ghlInfo"); #ifdef JK2_MODE - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomSkin = customSkin; return qtrue; } return qfalse; #else - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomSkin = customSkin; - if (renderSkin) - {//this is going to set the surfs on/off matching the skin file -extern void G2API_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin); //tr_ghoul2.cpp - G2API_SetSurfaceOnOffFromSkin( ghlInfo, renderSkin ); + if (renderSkin) { // this is going to set the surfs on/off matching the skin file + extern void G2API_SetSurfaceOnOffFromSkin(CGhoul2Info * ghlInfo, qhandle_t renderSkin); // tr_ghoul2.cpp + G2API_SetSurfaceOnOffFromSkin(ghlInfo, renderSkin); } return qtrue; } @@ -861,22 +741,18 @@ extern void G2API_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t rende return qfalse; } -qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) -{ - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomShader = customShader; return qtrue; } return qfalse; } -qboolean G2API_SetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName, const int flags) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(!(flags&~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS)),"G2API_SetSurfaceOnOff Illegal Flags"); +qboolean G2API_SetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName, const int flags) { + if (G2_SetupModelPointers(ghlInfo)) { + G2ERROR(!(flags & ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS)), "G2API_SetSurfaceOnOff Illegal Flags"); // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_SetSurfaceOnOff(ghlInfo, surfaceName, flags); @@ -884,26 +760,20 @@ qboolean G2API_SetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName, co return qfalse; } - -qboolean G2API_SetRootSurface(CGhoul2Info_v &ghlInfo, const int modelIndex, const char *surfaceName) -{ - G2ERROR(ghlInfo.IsValid(),"Invalid ghlInfo"); - G2ERROR(surfaceName,"Invalid surfaceName"); - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(modelIndex>=0&&modelIndex=0&&modelIndex= 0 && modelIndex < ghlInfo.size(), "Bad Model Index"); + if (modelIndex >= 0 && modelIndex < ghlInfo.size()) { + return G2_SetRootSurface(ghlInfo, modelIndex, surfaceName); } } return qfalse; } -int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); @@ -911,10 +781,8 @@ int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, fl return -1; } -qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_RemoveSurface(ghlInfo->mSlist, index); @@ -922,94 +790,81 @@ qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) return qfalse; } -int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetParentSurface(ghlInfo, index); } return -1; } -int G2API_GetSurfaceRenderStatus(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - G2ERROR(surfaceName,"Invalid surfaceName"); - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceRenderStatus(CGhoul2Info *ghlInfo, const char *surfaceName) { + G2ERROR(surfaceName, "Invalid surfaceName"); + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceRendered(ghlInfo, surfaceName, ghlInfo->mSlist); } return -1; } -qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v &ghlInfo, const int modelIndex) -{ +qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v &ghlInfo, const int modelIndex) { // sanity check - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || modelIndex < 0 || (ghlInfo[modelIndex].mModelindex <0)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || modelIndex < 0 || (ghlInfo[modelIndex].mModelindex < 0)) { // if we hit this assert then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. - G2ERROR(0,"Remove Nonexistant Model"); + G2ERROR(0, "Remove Nonexistant Model"); assert(0 && "remove non existing model"); return qfalse; } #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; - ghlInfo[modelIndex].mFileName[0]=0; + ghlInfo[modelIndex].mFileName[0] = 0; - ghlInfo[modelIndex]=CGhoul2Info(); + ghlInfo[modelIndex] = CGhoul2Info(); return qtrue; } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled -//rww - RAGDOLL_END +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +// rww - RAGDOLL_END -int G2API_GetAnimIndex(CGhoul2Info *ghlInfo) -{ - if (ghlInfo) - { +int G2API_GetAnimIndex(CGhoul2Info *ghlInfo) { + if (ghlInfo) { return ghlInfo->animModelIndexOffset; } return 0; } -qboolean G2API_SetAnimIndex(CGhoul2Info *ghlInfo, const int index) -{ +qboolean G2API_SetAnimIndex(CGhoul2Info *ghlInfo, const int index) { // Is This A Valid G2 Model? //--------------------------- - if (ghlInfo) - { + if (ghlInfo) { // Is This A New Anim Index? //--------------------------- - if (ghlInfo->animModelIndexOffset != index) - { + if (ghlInfo->animModelIndexOffset != index) { ghlInfo->animModelIndexOffset = index; - ghlInfo->currentAnimModelSize = 0; // Clear anim size so SetupModelPointers recalcs + ghlInfo->currentAnimModelSize = 0; // Clear anim size so SetupModelPointers recalcs -// RemoveBoneCache(ghlInfo[0].mBoneCache); -// ghlInfo[0].mBoneCache=0; + // RemoveBoneCache(ghlInfo[0].mBoneCache); + // ghlInfo[0].mBoneCache=0; // Kill All Existing Animation, Blending, Etc. //--------------------------------------------- - for (size_t index=0; indexmBlist.size(); index++) - { + for (size_t index = 0; index < ghlInfo->mBlist.size(); index++) { ghlInfo->mBlist[index].flags &= ~(BONE_ANIM_TOTAL); ghlInfo->mBlist[index].flags &= ~(BONE_ANGLES_TOTAL); -// G2_Remove_Bone_Index(ghlInfo->mBlist, index); + // G2_Remove_Bone_Index(ghlInfo->mBlist, index); } } return qtrue; @@ -1017,42 +872,36 @@ qboolean G2API_SetAnimIndex(CGhoul2Info *ghlInfo, const int index) return qfalse; } -qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) -{ - //rww - RAGDOLL_BEGIN - if (ghlInfo && (ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { +qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int AcurrentTime, const float setFrame, const int blendTime) { + // rww - RAGDOLL_BEGIN + if (ghlInfo && (ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { return qfalse; } - //rww - RAGDOLL_END - - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(startFrame>=0,"startframe<0"); - G2ERROR(startFrameaHeader->numFrames,"startframe>=numframes"); - G2ERROR(endFrame>0,"endframe<=0"); - G2ERROR(endFrame<=ghlInfo->aHeader->numFrames,"endframe>numframes"); - G2ERROR(setFrameaHeader->numFrames,"setframe>=numframes"); - G2ERROR(setFrame==-1.0f||setFrame>=0.0f,"setframe<0 but not -1"); - if (startFrame<0||startFrame>=ghlInfo->aHeader->numFrames) - { - *(int *)&startFrame=0; // cast away const + // rww - RAGDOLL_END + + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + G2ERROR(startFrame >= 0, "startframe<0"); + G2ERROR(startFrame < ghlInfo->aHeader->numFrames, "startframe>=numframes"); + G2ERROR(endFrame > 0, "endframe<=0"); + G2ERROR(endFrame <= ghlInfo->aHeader->numFrames, "endframe>numframes"); + G2ERROR(setFrame < ghlInfo->aHeader->numFrames, "setframe>=numframes"); + G2ERROR(setFrame == -1.0f || setFrame >= 0.0f, "setframe<0 but not -1"); + if (startFrame < 0 || startFrame >= ghlInfo->aHeader->numFrames) { + *(int *)&startFrame = 0; // cast away const } - if (endFrame<=0||endFrame>ghlInfo->aHeader->numFrames) - { - *(int *)&endFrame=1; + if (endFrame <= 0 || endFrame > ghlInfo->aHeader->numFrames) { + *(int *)&endFrame = 1; } - if (setFrame!=-1.0f&&(setFrame<0.0f||setFrame>=(float)ghlInfo->aHeader->numFrames)) - { - *(float *)&setFrame=0.0f; + if (setFrame != -1.0f && (setFrame < 0.0f || setFrame >= (float)ghlInfo->aHeader->numFrames)) { + *(float *)&setFrame = 0.0f; } ghlInfo->mSkelFrameNum = 0; - G2ERROR(index>=0&&index<(int)ghlInfo->mBlist.size(),va("Out of Range Bone Index (%s)",ghlInfo->mFileName)); - if (index>=0&&index<(int)ghlInfo->mBlist.size()) - { - G2ERROR(ghlInfo->mBlist[index].boneNumber>=0,va("Bone Index is not Active (%s)",ghlInfo->mFileName)); - int currentTime=G2API_GetTime(AcurrentTime); + G2ERROR(index >= 0 && index < (int)ghlInfo->mBlist.size(), va("Out of Range Bone Index (%s)", ghlInfo->mFileName)); + if (index >= 0 && index < (int)ghlInfo->mBlist.size()) { + G2ERROR(ghlInfo->mBlist[index].boneNumber >= 0, va("Bone Index is not Active (%s)", ghlInfo->mFileName)); + int currentTime = G2API_GetTime(AcurrentTime); #if 0 /* if ( ge->ValidateAnimRange( startFrame, endFrame, animSpeed ) == -1 ) @@ -1061,382 +910,324 @@ qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int } */ #endif - ret=G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime,ghlInfo->aHeader->numFrames); - G2ANIM(ghlInfo,"G2API_SetBoneAnimIndex"); + ret = G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, + ghlInfo->aHeader->numFrames); + G2ANIM(ghlInfo, "G2API_SetBoneAnimIndex"); } } - G2WARNING(ret,va("G2API_SetBoneAnimIndex Failed (%s)",ghlInfo->mFileName)); + G2WARNING(ret, va("G2API_SetBoneAnimIndex Failed (%s)", ghlInfo->mFileName)); return ret; } -qboolean G2API_SetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) -{ - //rww - RAGDOLL_BEGIN - if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { +qboolean G2API_SetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int AcurrentTime, const float setFrame, const int blendTime) { + // rww - RAGDOLL_BEGIN + if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } - //rww - RAGDOLL_END - - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(startFrame>=0,"startframe<0"); - G2ERROR(startFrameaHeader->numFrames,"startframe>=numframes"); - G2ERROR(endFrame>0,"endframe<=0"); - G2ERROR(endFrame<=ghlInfo->aHeader->numFrames,"endframe>numframes"); - G2ERROR(setFrameaHeader->numFrames,"setframe>=numframes"); - G2ERROR(setFrame==-1.0f||setFrame>=0.0f,"setframe<0 but not -1"); - if (startFrame<0||startFrame>=ghlInfo->aHeader->numFrames) - { - *(int *)&startFrame=0; // cast away const + // rww - RAGDOLL_END + + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + G2ERROR(startFrame >= 0, "startframe<0"); + G2ERROR(startFrame < ghlInfo->aHeader->numFrames, "startframe>=numframes"); + G2ERROR(endFrame > 0, "endframe<=0"); + G2ERROR(endFrame <= ghlInfo->aHeader->numFrames, "endframe>numframes"); + G2ERROR(setFrame < ghlInfo->aHeader->numFrames, "setframe>=numframes"); + G2ERROR(setFrame == -1.0f || setFrame >= 0.0f, "setframe<0 but not -1"); + if (startFrame < 0 || startFrame >= ghlInfo->aHeader->numFrames) { + *(int *)&startFrame = 0; // cast away const } - if (endFrame<=0||endFrame>ghlInfo->aHeader->numFrames) - { - *(int *)&endFrame=1; + if (endFrame <= 0 || endFrame > ghlInfo->aHeader->numFrames) { + *(int *)&endFrame = 1; } - if (setFrame!=-1.0f&&(setFrame<0.0f||setFrame>=(float)ghlInfo->aHeader->numFrames)) - { - *(float *)&setFrame=0.0f; + if (setFrame != -1.0f && (setFrame < 0.0f || setFrame >= (float)ghlInfo->aHeader->numFrames)) { + *(float *)&setFrame = 0.0f; } ghlInfo->mSkelFrameNum = 0; - int currentTime=G2API_GetTime(AcurrentTime); - ret=G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); - G2ANIM(ghlInfo,"G2API_SetBoneAnim"); + int currentTime = G2API_GetTime(AcurrentTime); + ret = G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); + G2ANIM(ghlInfo, "G2API_SetBoneAnim"); } - G2WARNING(ret,"G2API_SetBoneAnim Failed"); + G2WARNING(ret, "G2API_SetBoneAnim Failed"); return ret; } -qboolean G2API_GetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime, float *currentFrame, - int *startFrame, int *endFrame, int *flags, float *animSpeed, int *) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); - ret=G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime, currentFrame, - startFrame, endFrame, flags, animSpeed); - } - G2WARNING(ret,"G2API_GetBoneAnim Failed"); +qboolean G2API_GetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); + ret = G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed); + } + G2WARNING(ret, "G2API_GetBoneAnim Failed"); return ret; } -qboolean G2API_GetBoneAnimIndex(CGhoul2Info *ghlInfo, const int iBoneIndex, const int AcurrentTime, float *currentFrame, - int *startFrame, int *endFrame, int *flags, float *animSpeed, int *) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); - G2NOTE(iBoneIndex>=0&&iBoneIndex<(int)ghlInfo->mBlist.size(),va("Bad Bone Index (%d:%s)",iBoneIndex,ghlInfo->mFileName)); - if (iBoneIndex>=0&&iBoneIndex<(int)ghlInfo->mBlist.size()) - { - G2NOTE(ghlInfo->mBlist[iBoneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE),"GetBoneAnim on non-animating bone."); - if ((ghlInfo->mBlist[iBoneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) - { - int sf,ef; - ret=G2_Get_Bone_Anim_Index( ghlInfo->mBlist,// boneInfo_v &blist, - iBoneIndex, // const int index, - currentTime, // const int currentTime, - currentFrame, // float *currentFrame, - &sf, // int *startFrame, - &ef, // int *endFrame, - flags, // int *flags, - animSpeed, // float *retAnimSpeed, - ghlInfo->aHeader->numFrames - ); - G2ERROR(sf>=0,"returning startframe<0"); - G2ERROR(sfaHeader->numFrames,"returning startframe>=numframes"); - G2ERROR(ef>0,"returning endframe<=0"); - G2ERROR(ef<=ghlInfo->aHeader->numFrames,"returning endframe>numframes"); - if (currentFrame) - { - G2ERROR(*currentFrame>=0.0f,"returning currentframe<0"); - G2ERROR(((int)(*currentFrame))aHeader->numFrames,"returning currentframe>=numframes"); +qboolean G2API_GetBoneAnimIndex(CGhoul2Info *ghlInfo, const int iBoneIndex, const int AcurrentTime, float *currentFrame, int *startFrame, int *endFrame, + int *flags, float *animSpeed, int *) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); + G2NOTE(iBoneIndex >= 0 && iBoneIndex < (int)ghlInfo->mBlist.size(), va("Bad Bone Index (%d:%s)", iBoneIndex, ghlInfo->mFileName)); + if (iBoneIndex >= 0 && iBoneIndex < (int)ghlInfo->mBlist.size()) { + G2NOTE(ghlInfo->mBlist[iBoneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE), "GetBoneAnim on non-animating bone."); + if ((ghlInfo->mBlist[iBoneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) { + int sf, ef; + ret = G2_Get_Bone_Anim_Index(ghlInfo->mBlist, // boneInfo_v &blist, + iBoneIndex, // const int index, + currentTime, // const int currentTime, + currentFrame, // float *currentFrame, + &sf, // int *startFrame, + &ef, // int *endFrame, + flags, // int *flags, + animSpeed, // float *retAnimSpeed, + ghlInfo->aHeader->numFrames); + G2ERROR(sf >= 0, "returning startframe<0"); + G2ERROR(sf < ghlInfo->aHeader->numFrames, "returning startframe>=numframes"); + G2ERROR(ef > 0, "returning endframe<=0"); + G2ERROR(ef <= ghlInfo->aHeader->numFrames, "returning endframe>numframes"); + if (currentFrame) { + G2ERROR(*currentFrame >= 0.0f, "returning currentframe<0"); + G2ERROR(((int)(*currentFrame)) < ghlInfo->aHeader->numFrames, "returning currentframe>=numframes"); } - if (endFrame) - { - *endFrame=ef; + if (endFrame) { + *endFrame = ef; } - if (startFrame) - { - *startFrame=sf; + if (startFrame) { + *startFrame = sf; } - G2ANIM(ghlInfo,"G2API_GetBoneAnimIndex"); + G2ANIM(ghlInfo, "G2API_GetBoneAnimIndex"); } } } - if (!ret) - { - *endFrame=1; - *startFrame=0; - *flags=0; - *currentFrame=0.0f; - *animSpeed=1.0f; + if (!ret) { + *endFrame = 1; + *startFrame = 0; + *flags = 0; + *currentFrame = 0.0f; + *animSpeed = 1.0f; } - G2NOTE(ret,"G2API_GetBoneAnimIndex Failed"); + G2NOTE(ret, "G2API_GetBoneAnimIndex Failed"); return ret; } -qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); - G2ANIM(ghlInfo,"G2API_GetAnimRange"); - } -// looks like the game checks the return value -// G2WARNING(ret,"G2API_GetAnimRange Failed"); +qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); + G2ANIM(ghlInfo, "G2API_GetAnimRange"); + } + // looks like the game checks the return value + // G2WARNING(ret,"G2API_GetAnimRange Failed"); return ret; } -qboolean G2API_GetAnimRangeIndex(CGhoul2Info *ghlInfo, const int boneIndex, int *startFrame, int *endFrame) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(boneIndex>=0&&boneIndex<(int)ghlInfo->mBlist.size(),"Bad Bone Index"); - if (boneIndex>=0&&boneIndex<(int)ghlInfo->mBlist.size()) - { - ret=G2_Get_Bone_Anim_Range_Index(ghlInfo->mBlist, boneIndex, startFrame, endFrame); - G2ANIM(ghlInfo,"G2API_GetAnimRange"); +qboolean G2API_GetAnimRangeIndex(CGhoul2Info *ghlInfo, const int boneIndex, int *startFrame, int *endFrame) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + G2ERROR(boneIndex >= 0 && boneIndex < (int)ghlInfo->mBlist.size(), "Bad Bone Index"); + if (boneIndex >= 0 && boneIndex < (int)ghlInfo->mBlist.size()) { + ret = G2_Get_Bone_Anim_Range_Index(ghlInfo->mBlist, boneIndex, startFrame, endFrame); + G2ANIM(ghlInfo, "G2API_GetAnimRange"); } } -// looks like the game checks the return value -// G2WARNING(ret,"G2API_GetAnimRangeIndex Failed"); + // looks like the game checks the return value + // G2WARNING(ret,"G2API_GetAnimRangeIndex Failed"); return ret; } -qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); - ret=G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); - G2ANIM(ghlInfo,"G2API_PauseBoneAnim"); - } - G2NOTE(ret,"G2API_PauseBoneAnim Failed"); +qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); + ret = G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); + G2ANIM(ghlInfo, "G2API_PauseBoneAnim"); + } + G2NOTE(ret, "G2API_PauseBoneAnim Failed"); return ret; } -qboolean G2API_PauseBoneAnimIndex(CGhoul2Info *ghlInfo, const int boneIndex, const int AcurrentTime) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); - G2ERROR(boneIndex>=0&&boneIndex<(int)ghlInfo->mBlist.size(),"Bad Bone Index"); - if (boneIndex>=0&&boneIndex<(int)ghlInfo->mBlist.size()) - { - ret=G2_Pause_Bone_Anim_Index(ghlInfo->mBlist, boneIndex, currentTime,ghlInfo->aHeader->numFrames); - G2ANIM(ghlInfo,"G2API_PauseBoneAnimIndex"); +qboolean G2API_PauseBoneAnimIndex(CGhoul2Info *ghlInfo, const int boneIndex, const int AcurrentTime) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); + G2ERROR(boneIndex >= 0 && boneIndex < (int)ghlInfo->mBlist.size(), "Bad Bone Index"); + if (boneIndex >= 0 && boneIndex < (int)ghlInfo->mBlist.size()) { + ret = G2_Pause_Bone_Anim_Index(ghlInfo->mBlist, boneIndex, currentTime, ghlInfo->aHeader->numFrames); + G2ANIM(ghlInfo, "G2API_PauseBoneAnimIndex"); } } - G2WARNING(ret,"G2API_PauseBoneAnimIndex Failed"); + G2WARNING(ret, "G2API_PauseBoneAnimIndex Failed"); return ret; } -qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_IsPaused(ghlInfo, ghlInfo->mBlist, boneName); +qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_IsPaused(ghlInfo, ghlInfo->mBlist, boneName); } - G2WARNING(ret,"G2API_IsPaused Failed"); + G2WARNING(ret, "G2API_IsPaused Failed"); return ret; } -qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) -{ - qboolean ret=qfalse; - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(index>=0&&index<(int)ghlInfo->mBlist.size(),"Bad Bone Index"); - if (index>=0&&index<(int)ghlInfo->mBlist.size()) - { - ret=G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); - G2ANIM(ghlInfo,"G2API_StopBoneAnimIndex"); +qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) { + qboolean ret = qfalse; + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (G2_SetupModelPointers(ghlInfo)) { + G2ERROR(index >= 0 && index < (int)ghlInfo->mBlist.size(), "Bad Bone Index"); + if (index >= 0 && index < (int)ghlInfo->mBlist.size()) { + ret = G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); + G2ANIM(ghlInfo, "G2API_StopBoneAnimIndex"); } } - //G2WARNING(ret,"G2API_StopBoneAnimIndex Failed"); + // G2WARNING(ret,"G2API_StopBoneAnimIndex Failed"); return ret; } -qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Stop_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName); - G2ANIM(ghlInfo,"G2API_StopBoneAnim"); - } - G2WARNING(ret,"G2API_StopBoneAnim Failed"); +qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_Stop_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName); + G2ANIM(ghlInfo, "G2API_StopBoneAnim"); + } + G2WARNING(ret, "G2API_StopBoneAnim Failed"); return ret; } -qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, - const Eorientations yaw, const Eorientations pitch, const Eorientations roll, - qhandle_t *, int blendTime, int AcurrentTime) -{ - //rww - RAGDOLL_BEGIN - if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { +qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, qhandle_t *, int blendTime, int AcurrentTime) { + // rww - RAGDOLL_BEGIN + if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - G2ERROR(index>=0&&index<(int)ghlInfo->mBlist.size(),"G2API_SetBoneAnglesIndex:Invalid bone index"); - if (index>=0&&index<(int)ghlInfo->mBlist.size()) - { - ret=G2_Set_Bone_Angles_Index(ghlInfo, ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll,blendTime, currentTime); + G2ERROR(index >= 0 && index < (int)ghlInfo->mBlist.size(), "G2API_SetBoneAnglesIndex:Invalid bone index"); + if (index >= 0 && index < (int)ghlInfo->mBlist.size()) { + ret = G2_Set_Bone_Angles_Index(ghlInfo, ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, blendTime, currentTime); } } - G2WARNING(ret,"G2API_SetBoneAnglesIndex Failed"); + G2WARNING(ret, "G2API_SetBoneAnglesIndex Failed"); return ret; } -qboolean G2API_SetBoneAngles(CGhoul2Info *ghlInfo, const char *boneName, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *, int blendTime, int AcurrentTime ) -{ - //rww - RAGDOLL_BEGIN - if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { +qboolean G2API_SetBoneAngles(CGhoul2Info *ghlInfo, const char *boneName, const vec3_t angles, const int flags, const Eorientations up, const Eorientations left, + const Eorientations forward, qhandle_t *, int blendTime, int AcurrentTime) { + // rww - RAGDOLL_BEGIN + if (ghlInfo && ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); - // ensure we flush the cache + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); + // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - ret=G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, blendTime, currentTime); + ret = G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, blendTime, currentTime); } - G2WARNING(ret,"G2API_SetBoneAngles Failed"); + G2WARNING(ret, "G2API_SetBoneAngles Failed"); return ret; } -qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, - const int flags, qhandle_t *, int blendTime, int AcurrentTime) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); +qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *, int blendTime, + int AcurrentTime) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - G2ERROR(index>=0&&index<(int)ghlInfo->mBlist.size(),"Bad Bone Index"); - if (index>=0&&index<(int)ghlInfo->mBlist.size()) - { - ret=G2_Set_Bone_Angles_Matrix_Index(ghlInfo->mBlist, index, matrix, flags, blendTime, currentTime); + G2ERROR(index >= 0 && index < (int)ghlInfo->mBlist.size(), "Bad Bone Index"); + if (index >= 0 && index < (int)ghlInfo->mBlist.size()) { + ret = G2_Set_Bone_Angles_Matrix_Index(ghlInfo->mBlist, index, matrix, flags, blendTime, currentTime); } } - G2WARNING(ret,"G2API_SetBoneAnglesMatrixIndex Failed"); + G2WARNING(ret, "G2API_SetBoneAnglesMatrixIndex Failed"); return ret; } -qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int AcurrentTime) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - int currentTime=G2API_GetTime(AcurrentTime); +qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int AcurrentTime) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + int currentTime = G2API_GetTime(AcurrentTime); // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - ret=G2_Set_Bone_Angles_Matrix(ghlInfo, ghlInfo->mBlist, boneName, matrix, flags, blendTime, currentTime); + ret = G2_Set_Bone_Angles_Matrix(ghlInfo, ghlInfo->mBlist, boneName, matrix, flags, blendTime, currentTime); } - G2WARNING(ret,"G2API_SetBoneAnglesMatrix Failed"); + G2WARNING(ret, "G2API_SetBoneAnglesMatrix Failed"); return ret; } -qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - G2ERROR(index>=0&&index<(int)ghlInfo->mBlist.size(),"Bad Bone Index"); - if (index>=0&&index<(int)ghlInfo->mBlist.size()) - { - ret=G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); + G2ERROR(index >= 0 && index < (int)ghlInfo->mBlist.size(), "Bad Bone Index"); + if (index >= 0 && index < (int)ghlInfo->mBlist.size()) { + ret = G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); } } - G2WARNING(ret,"G2API_StopBoneAnglesIndex Failed"); + G2WARNING(ret, "G2API_StopBoneAnglesIndex Failed"); return ret; } -qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - ret=G2_Stop_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName); + ret = G2_Stop_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName); } - G2WARNING(ret,"G2API_StopBoneAngles Failed"); + G2WARNING(ret, "G2API_StopBoneAngles Failed"); return ret; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN class CRagDollParams; -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms); -void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms) -{ - G2_SetRagDoll(ghoul2,parms); -} -//rww - RAGDOLL_END - -qboolean G2API_RemoveBone(CGhoul2Info *ghlInfo, const char *boneName) -{ - qboolean ret=qfalse; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms); +void G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms) { G2_SetRagDoll(ghoul2, parms); } +// rww - RAGDOLL_END + +qboolean G2API_RemoveBone(CGhoul2Info *ghlInfo, const char *boneName) { + qboolean ret = qfalse; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - ret=G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); - G2ANIM(ghlInfo,"G2API_RemoveBone"); + ret = G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); + G2ANIM(ghlInfo, "G2API_RemoveBone"); } - G2WARNING(ret,"G2API_RemoveBone Failed"); + G2WARNING(ret, "G2API_RemoveBone Failed"); return ret; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef _DEBUG extern int ragTraceTime; extern int ragSSCount; extern int ragTraceCount; #endif -void G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUpdateParams *params) -{ +void G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) { int model; - int currentTime=G2API_GetTime(AcurrentTime); + int currentTime = G2API_GetTime(AcurrentTime); #ifdef _DEBUG ragTraceTime = 0; @@ -1445,64 +1236,55 @@ void G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUpdat #endif // Walk the list and find all models that are active - for (model = 0; model < ghoul2.size(); model++) - { - if (ghoul2[model].mModel) - { - G2_Animate_Bone_List(ghoul2,currentTime,model,params); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModel) { + G2_Animate_Bone_List(ghoul2, currentTime, model, params); } } #ifdef _DEBUG // Com_Printf("Rag trace time: %i (%i STARTSOLID, %i TOTAL)\n", ragTraceTime, ragSSCount, ragTraceCount); // assert(ragTraceTime < 15); - //assert(ragTraceCount < 600); +// assert(ragTraceCount < 600); #endif } -//rww - RAGDOLL_END +// rww - RAGDOLL_END int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); -#define RAG_PCJ (0x00001) -#define RAG_EFFECTOR (0x00100) +#define RAG_PCJ (0x00001) +#define RAG_EFFECTOR (0x00100) -static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) -{ +static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return NULL; } int boneIndex = G2_Find_Bone_Rag(ghlInfo, ghlInfo->mBlist, boneName); - if (boneIndex < 0) - { //bad bone specification + if (boneIndex < 0) { // bad bone specification return NULL; } boneInfo_t *bone = &ghlInfo->mBlist[boneIndex]; - if (!(bone->flags & BONE_ANGLES_RAGDOLL)) - { //only want to return rag bones + if (!(bone->flags & BONE_ANGLES_RAGDOLL)) { // only want to return rag bones return NULL; } return bone; } -qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) -{ +qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1512,17 +1294,14 @@ qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec return qtrue; } -qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) -{ +qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1531,48 +1310,38 @@ qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, return qtrue; } -qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) -{ +qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } - if (!pos) - { //go back to none in case we have one then + if (!pos) { // go back to none in case we have one then bone->hasOverGoal = false; - } - else - { + } else { VectorCopy(pos, bone->overGoalSpot); bone->hasOverGoal = true; } return qtrue; } -qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) -{ //do something? +qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { // do something? return qfalse; } -qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) -{ +qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } @@ -1583,22 +1352,17 @@ qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3 return qtrue; } -qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) -{ +qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return qfalse; } - if (force) - { + if (force) { ghlInfo->mFlags |= GHOUL2_RAG_FORCESOLVE; - } - else - { + } else { ghlInfo->mFlags &= ~GHOUL2_RAG_FORCESOLVE; } @@ -1607,238 +1371,182 @@ qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params); -qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ +qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return G2_SetBoneIKState(ghoul2, time, boneName, ikState, params); } qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params); -qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ - return G2_IKMove(ghoul2, time, params); -} +qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { return G2_IKMove(ghoul2, time, params); } -qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Remove_Bolt( ghlInfo->mBltlist, index); +qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + ret = G2_Remove_Bolt(ghlInfo->mBltlist, index); } - G2WARNING(ret,"G2API_RemoveBolt Failed"); + G2WARNING(ret, "G2API_RemoveBolt Failed"); return ret; } -int G2API_AddBolt(CGhoul2Info *ghlInfo, const char *boneName) -{ - int ret=-1; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Add_Bolt(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); - G2NOTE(ret>=0,va("G2API_AddBolt Failed (%s:%s)",boneName,ghlInfo->mFileName)); +int G2API_AddBolt(CGhoul2Info *ghlInfo, const char *boneName) { + int ret = -1; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_Add_Bolt(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); + G2NOTE(ret >= 0, va("G2API_AddBolt Failed (%s:%s)", boneName, ghlInfo->mFileName)); } return ret; } -int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) -{ - int ret=-1; - if (G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Add_Bolt_Surf_Num(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); +int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) { + int ret = -1; + if (G2_SetupModelPointers(ghlInfo)) { + ret = G2_Add_Bolt_Surf_Num(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); } - G2WARNING(ret>=0,"G2API_AddBoltSurfNum Failed"); + G2WARNING(ret >= 0, "G2API_AddBoltSurfNum Failed"); return ret; } - -qboolean G2API_AttachG2Model(CGhoul2Info *ghlInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int toModel) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)&&G2_SetupModelPointers(ghlInfoTo)) - { - G2ERROR(toBoltIndex>=0&&toBoltIndex<(int)ghlInfoTo->mBltlist.size(),"Invalid Bolt Index"); - G2ERROR(ghlInfoTo->mBltlist.size()>0,"Empty Bolt List"); - assert( toBoltIndex >= 0 ); - if ( toBoltIndex >= 0 && ghlInfoTo->mBltlist.size()) - { +qboolean G2API_AttachG2Model(CGhoul2Info *ghlInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int toModel) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo) && G2_SetupModelPointers(ghlInfoTo)) { + G2ERROR(toBoltIndex >= 0 && toBoltIndex < (int)ghlInfoTo->mBltlist.size(), "Invalid Bolt Index"); + G2ERROR(ghlInfoTo->mBltlist.size() > 0, "Empty Bolt List"); + assert(toBoltIndex >= 0); + if (toBoltIndex >= 0 && ghlInfoTo->mBltlist.size()) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if (((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if (((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModel &= MODEL_AND; - toBoltIndex &= BOLT_AND; - ghlInfo->mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); - ret=qtrue; + toModel &= MODEL_AND; + toBoltIndex &= BOLT_AND; + ghlInfo->mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); + ret = qtrue; } } } - G2WARNING(ret,"G2API_AttachG2Model Failed"); + G2WARNING(ret, "G2API_AttachG2Model Failed"); return ret; } - -qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - ghlInfo->mModelBoltLink = -1; - return qtrue; +qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { + ghlInfo->mModelBoltLink = -1; + return qtrue; } return qfalse; } -qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum) -{ - qboolean ret=qfalse; - G2ERROR(boltInfo,"NULL boltInfo"); - if (boltInfo&&G2_SetupModelPointers(ghlInfoTo)) - { +qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum) { + qboolean ret = qfalse; + G2ERROR(boltInfo, "NULL boltInfo"); + if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if ( ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if (ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModelNum &= MODEL_AND; - toBoltIndex &= BOLT_AND; - entNum &= ENTITY_AND; - *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); - ret=qtrue; + toModelNum &= MODEL_AND; + toBoltIndex &= BOLT_AND; + entNum &= ENTITY_AND; + *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); + ret = qtrue; } } - G2WARNING(ret,"G2API_AttachEnt Failed"); + G2WARNING(ret, "G2API_AttachEnt Failed"); return ret; } -void G2API_DetachEnt(int *boltInfo) -{ - G2ERROR(boltInfo,"NULL boltInfo"); - if (boltInfo) - { +void G2API_DetachEnt(int *boltInfo) { + G2ERROR(boltInfo, "NULL boltInfo"); + if (boltInfo) { *boltInfo = 0; } } +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum); -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum); - -qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int AframeNum, qhandle_t *modelList, const vec3_t scale ) -{ - G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo"); - G2ERROR(matrix,"NULL matrix"); - G2ERROR(modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size(), "Invalid ModelIndex"); + const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; G2_GenerateWorldMatrix(angles, position); - if (G2_SetupModelPointers(ghoul2)) - { - if (matrix&&modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size()) { + int frameNum = G2API_GetTime(AframeNum); CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - G2ERROR(boltIndex >= 0 && (boltIndex < (int)ghlInfo->mBltlist.size()),va("Invalid Bolt Index (%d:%s)",boltIndex,ghlInfo->mFileName)); + G2ERROR(boltIndex >= 0 && (boltIndex < (int)ghlInfo->mBltlist.size()), va("Invalid Bolt Index (%d:%s)", boltIndex, ghlInfo->mFileName)); - if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) ) - { + if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size())) { mdxaBone_t bolt; - if (G2_NeedsRecalc(ghlInfo,frameNum)) - { - G2_ConstructGhoulSkeleton(ghoul2,frameNum,true,scale); + if (G2_NeedsRecalc(ghlInfo, frameNum)) { + G2_ConstructGhoulSkeleton(ghoul2, frameNum, true, scale); } - G2_GetBoltMatrixLow(*ghlInfo,boltIndex,scale,bolt); + G2_GetBoltMatrixLow(*ghlInfo, boltIndex, scale, bolt); // scale the bolt position by the scale factor for this model since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); Multiply_3x4Matrix(matrix, &worldMatrix, &bolt); #if G2API_DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(matrix->matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(matrix->matrix[i][j])); } } -#endif// _DEBUG - G2ANIM(ghlInfo,"G2API_GetBoltMatrix"); +#endif // _DEBUG + G2ANIM(ghlInfo, "G2API_GetBoltMatrix"); return qtrue; } } - } - else - { - G2WARNING(0,"G2API_GetBoltMatrix Failed on empty or bad model"); + } else { + G2WARNING(0, "G2API_GetBoltMatrix Failed on empty or bad model"); } Multiply_3x4Matrix(matrix, &worldMatrix, &identityMatrix); return qfalse; } -void G2API_ListSurfaces(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListSurfaces(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Surfaces(ghlInfo->mFileName); } } -void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Bones(ghlInfo->mFileName, frame); } } // decide if we have Ghoul2 models associated with this ghoul list or not -qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) -{ - return (qboolean)ghoul2.IsValid(); -} +qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) { return (qboolean)ghoul2.IsValid(); } // run through the Ghoul2 models and set each of the mModel values to the correct one from the cgs.gameModel offset lsit -void G2API_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) -{ - G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo"); +void G2API_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + G2ERROR(ghoul2.IsValid(), "Invalid ghlInfo"); int i; - for (i=0; imdxm,"Bad Model"); - if (mod_m&&mod_m->mdxm) - { +char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) { + model_t *mod_m = R_GetModelByHandle(modelIndex); + G2ERROR(mod_m && mod_m->mdxm, "Bad Model"); + if (mod_m && mod_m->mdxm) { return mod_m->mdxm->animName; } return ""; @@ -1847,12 +1555,10 @@ char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) // as above, but gets the internal embedded name, not the name of the disk file. // This is needed for some unfortunate jiggery-hackery to do with frameskipping & the animevents.cfg file // -char *G2API_GetAnimFileInternalNameIndex(qhandle_t modelIndex) -{ - model_t *mod_a = R_GetModelByHandle(modelIndex); - G2ERROR(mod_a&&mod_a->mdxa,"Bad Model"); - if (mod_a&&mod_a->mdxa) - { +char *G2API_GetAnimFileInternalNameIndex(qhandle_t modelIndex) { + model_t *mod_a = R_GetModelByHandle(modelIndex); + G2ERROR(mod_a && mod_a->mdxa, "Bad Model"); + if (mod_a && mod_a->mdxa) { return mod_a->mdxa->name; } return ""; @@ -1869,14 +1575,12 @@ char *G2API_GetAnimFileInternalNameIndex(qhandle_t modelIndex) * true if a good filename was obtained, false otherwise * ************************************************************************************************/ -qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) -{ - qboolean ret=qfalse; - if (G2_SetupModelPointers(ghlInfo)) - { - ret=G2_GetAnimFileName(ghlInfo->mFileName, filename); +qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) { + qboolean ret = qfalse; + if (G2_SetupModelPointers(ghlInfo)) { + ret = G2_GetAnimFileName(ghlInfo->mFileName, filename); } - G2WARNING(ret,"G2API_GetAnimFileName Failed"); + G2WARNING(ret, "G2API_GetAnimFileName Failed"); return ret; } @@ -1885,31 +1589,27 @@ qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) SV_QsortEntityNumbers ======================= */ -static int QDECL QsortDistance( const void *a, const void *b ) { - const float &ea = ((CCollisionRecord*)a)->mDistance; - const float &eb = ((CCollisionRecord*)b)->mDistance; +static int QDECL QsortDistance(const void *a, const void *b) { + const float &ea = ((CCollisionRecord *)a)->mDistance; + const float &eb = ((CCollisionRecord *)b)->mDistance; - if ( ea < eb ) { + if (ea < eb) { return -1; } return 1; } +void G2API_CollisionDetect(CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int AframeNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, CMiniHeap *, EG2_Collision eG2TraceType, int useLod, float fRadius) { + G2ERROR(ghoul2.IsValid(), "Invalid ghlInfo"); + G2ERROR(collRecMap, "NULL Collision Rec"); + if (G2_SetupModelPointers(ghoul2) && collRecMap) { + int frameNumber = G2API_GetTime(AframeNumber); -void G2API_CollisionDetect(CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int AframeNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, CMiniHeap *, - EG2_Collision eG2TraceType, int useLod, float fRadius) -{ - G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo"); - G2ERROR(collRecMap,"NULL Collision Rec"); - if (G2_SetupModelPointers(ghoul2)&&collRecMap) - { - int frameNumber=G2API_GetTime(AframeNumber); - - vec3_t transRayStart, transRayEnd; + vec3_t transRayStart, transRayEnd; // make sure we have transformed the whole skeletons for each model - G2_ConstructGhoulSkeleton(ghoul2, frameNumber,true, scale); + G2_ConstructGhoulSkeleton(ghoul2, frameNumber, true, scale); // pre generate the world matrix - used to transform the incoming ray G2_GenerateWorldMatrix(angles, position); @@ -1920,7 +1620,7 @@ void G2API_CollisionDetect(CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, #ifdef _G2_GORE G2_TransformModel(ghoul2, frameNumber, scale, ri.GetG2VertSpaceServer(), useLod, false); #else - G2_TransformModel(ghoul2, frameNumber, scale,ri.GetG2VertSpaceServer(), useLod); + G2_TransformModel(ghoul2, frameNumber, scale, ri.GetG2VertSpaceServer(), useLod); #endif // model is built. Lets check to see if any triangles are actually hit. @@ -1930,23 +1630,20 @@ void G2API_CollisionDetect(CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, // now walk each model and check the ray against each poly - sigh, this is SO expensive. I wish there was a better way to do this. #ifdef _G2_GORE - G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, eG2TraceType, useLod, fRadius,0,0,0,0,0,qfalse); + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, eG2TraceType, useLod, fRadius, 0, 0, 0, 0, 0, qfalse); #else G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, eG2TraceType, useLod, fRadius); #endif ri.GetG2VertSpaceServer()->ResetHeap(); // now sort the resulting array of collision records so they are distance ordered - qsort( collRecMap, MAX_G2_COLLISIONS, - sizeof( CCollisionRecord ), QsortDistance ); - G2ANIM(ghoul2,"G2API_CollisionDetect"); + qsort(collRecMap, MAX_G2_COLLISIONS, sizeof(CCollisionRecord), QsortDistance); + G2ANIM(ghoul2, "G2API_CollisionDetect"); } } -qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mFlags &= GHOUL2_NEWORIGIN; ghlInfo->mFlags |= flags; return qtrue; @@ -1954,20 +1651,16 @@ qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) return qfalse; } -int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { return (ghlInfo->mFlags & ~GHOUL2_NEWORIGIN); } return 0; } // given a boltmatrix, return in vec a normalised vector for the axis requested in flags -void G2API_GiveMeVectorFromMatrix(mdxaBone_t &boltMatrix, Eorientations flags, vec3_t &vec) -{ - switch (flags) - { +void G2API_GiveMeVectorFromMatrix(mdxaBone_t &boltMatrix, Eorientations flags, vec3_t &vec) { + switch (flags) { case ORIGIN: vec[0] = boltMatrix.matrix[0][3]; vec[1] = boltMatrix.matrix[1][3]; @@ -1977,7 +1670,7 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t &boltMatrix, Eorientations flags, v vec[0] = boltMatrix.matrix[0][1]; vec[1] = boltMatrix.matrix[1][1]; vec[2] = boltMatrix.matrix[2][1]; - break; + break; case POSITIVE_X: vec[0] = boltMatrix.matrix[0][0]; vec[1] = boltMatrix.matrix[1][0]; @@ -2008,30 +1701,25 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t &boltMatrix, Eorientations flags, v // copy a model from one ghoul2 instance to another, and reset the root surface on the new model if need be // NOTE if modelIndex = -1 then copy all the models -void G2API_CopyGhoul2Instance(CGhoul2Info_v &ghoul2From, CGhoul2Info_v &ghoul2To, int modelIndex) -{ - //Ensiform: I'm commenting this out because modelIndex appears unused and legitimately set in gamecode - //assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it - // if ya want it, we will add it back correctly +void G2API_CopyGhoul2Instance(CGhoul2Info_v &ghoul2From, CGhoul2Info_v &ghoul2To, int modelIndex) { + // Ensiform: I'm commenting this out because modelIndex appears unused and legitimately set in gamecode + // assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it + // if ya want it, we will add it back correctly - G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); - if (ghoul2From.IsValid()) - { + G2ERROR(ghoul2From.IsValid(), "Invalid ghlInfo"); + if (ghoul2From.IsValid()) { ghoul2To.DeepCopy(ghoul2From); -#ifdef _G2_GORE //check through gore stuff then, as well. +#ifdef _G2_GORE // check through gore stuff then, as well. int model = 0; //(since we are sharing this gore set with the copied instance we will have to increment - //the reference count - if the goreset is "removed" while the refcount is > 0, the refcount - //is decremented to avoid giving other instances an invalid pointer -rww) - while (model < ghoul2To.size()) - { - if ( ghoul2To[model].mGoreSetTag ) - { - CGoreSet* gore = FindGoreSet ( ghoul2To[model].mGoreSetTag ); + // the reference count - if the goreset is "removed" while the refcount is > 0, the refcount + // is decremented to avoid giving other instances an invalid pointer -rww) + while (model < ghoul2To.size()) { + if (ghoul2To[model].mGoreSetTag) { + CGoreSet *gore = FindGoreSet(ghoul2To[model].mGoreSetTag); assert(gore); - if (gore) - { + if (gore) { gore->mRefCount++; } } @@ -2039,65 +1727,53 @@ void G2API_CopyGhoul2Instance(CGhoul2Info_v &ghoul2From, CGhoul2Info_v &ghoul2To model++; } #endif - G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); - G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); + G2ANIM(ghoul2From, "G2API_CopyGhoul2Instance (source)"); + G2ANIM(ghoul2To, "G2API_CopyGhoul2Instance (dest)"); } } -char *G2API_GetSurfaceName(CGhoul2Info *ghlInfo, int surfNumber) -{ +char *G2API_GetSurfaceName(CGhoul2Info *ghlInfo, int surfNumber) { static char noSurface[1] = ""; - if (G2_SetupModelPointers(ghlInfo)) - { - mdxmSurface_t *surf = 0; - mdxmSurfHierarchy_t *surfInfo = 0; - + if (G2_SetupModelPointers(ghlInfo)) { + mdxmSurface_t *surf = 0; + mdxmSurfHierarchy_t *surfInfo = 0; surf = (mdxmSurface_t *)G2_FindSurface(ghlInfo->currentModel, surfNumber, 0); - if (surf) - { + if (surf) { assert(G2_MODEL_OK(ghlInfo)); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->name; } } - G2WARNING(0,"Surface Not Found"); + G2WARNING(0, "Surface Not Found"); return noSurface; } - -int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - int ret=-1; - G2ERROR(surfaceName,"NULL surfaceName"); - if (surfaceName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_GetSurfaceIndex(ghlInfo, surfaceName); +int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + int ret = -1; + G2ERROR(surfaceName, "NULL surfaceName"); + if (surfaceName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_GetSurfaceIndex(ghlInfo, surfaceName); } - G2WARNING(ret>=0,"G2API_GetSurfaceIndex Failed"); + G2WARNING(ret >= 0, "G2API_GetSurfaceIndex Failed"); return ret; } -char *G2API_GetGLAName(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +char *G2API_GetGLAName(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { assert(G2_MODEL_OK(ghlInfo)); - return (char*)ghlInfo->aHeader->name; - //return ghlInfo->currentModel->mdxm->animName; + return (char *)ghlInfo->aHeader->name; + // return ghlInfo->currentModel->mdxm->animName; } return 0; } -qboolean G2API_SetNewOrigin(CGhoul2Info *ghlInfo, const int boltIndex) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - G2ERROR(boltIndex>=0&&boltIndex<(int)ghlInfo->mBltlist.size(),"invalid boltIndex"); +qboolean G2API_SetNewOrigin(CGhoul2Info *ghlInfo, const int boltIndex) { + if (G2_SetupModelPointers(ghlInfo)) { + G2ERROR(boltIndex >= 0 && boltIndex < (int)ghlInfo->mBltlist.size(), "invalid boltIndex"); - if (boltIndex>=0&&boltIndex<(int)ghlInfo->mBltlist.size()) - { + if (boltIndex >= 0 && boltIndex < (int)ghlInfo->mBltlist.size()) { ghlInfo->mNewOrigin = boltIndex; ghlInfo->mFlags |= GHOUL2_NEWORIGIN; } @@ -2106,240 +1782,200 @@ qboolean G2API_SetNewOrigin(CGhoul2Info *ghlInfo, const int boltIndex) return qfalse; } -int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName, qboolean bAddIfNotFound) -{ - int ret=-1; - G2ERROR(boneName,"NULL boneName"); - if (boneName&&G2_SetupModelPointers(ghlInfo)) - { - ret=G2_Get_Bone_Index(ghlInfo, boneName, bAddIfNotFound); - G2ANIM(ghlInfo,"G2API_GetBoneIndex"); - } - G2NOTE(ret>=0,"G2API_GetBoneIndex Failed"); +int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName, qboolean bAddIfNotFound) { + int ret = -1; + G2ERROR(boneName, "NULL boneName"); + if (boneName && G2_SetupModelPointers(ghlInfo)) { + ret = G2_Get_Bone_Index(ghlInfo, boneName, bAddIfNotFound); + G2ANIM(ghlInfo, "G2API_GetBoneIndex"); + } + G2NOTE(ret >= 0, "G2API_GetBoneIndex Failed"); return ret; } -void G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2) -{ - G2ANIM(ghoul2,"G2API_SaveGhoul2Models"); +void G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2) { + G2ANIM(ghoul2, "G2API_SaveGhoul2Models"); G2_SaveGhoul2Models(ghoul2); } -void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) -{ +void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) { G2_LoadGhoul2Model(ghoul2, buffer); - G2ANIM(ghoul2,"G2API_LoadGhoul2Models"); -// G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo after load"); + G2ANIM(ghoul2, "G2API_LoadGhoul2Models"); + // G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo after load"); } // this is kinda sad, but I need to call the destructor in this module (exe), not the game.dll... // -void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) -{ - ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning +void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) { + ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning } #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling -void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) -{ +void G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { int i; - for (i=0; iinteger)); - const int maxLod =Com_Clamp (0,ghoul2[0].currentModel->numLods,3); //limit to the number of lods the main model has - for(lod=lodbias;lodinteger)); + const int maxLod = Com_Clamp(0, ghoul2[0].currentModel->numLods, 3); // limit to the number of lods the main model has + for (lod = lodbias; lod < maxLod; lod++) { // now having done that, time to build the model ri.GetG2VertSpaceServer()->ResetHeap(); - G2_TransformModel(ghoul2, gore.currentTime, gore.scale,ri.GetG2VertSpaceServer(),lod,true,&gore); + G2_TransformModel(ghoul2, gore.currentTime, gore.scale, ri.GetG2VertSpaceServer(), lod, true, &gore); // now walk each model and compute new texture coordinates - G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, G2_NOCOLLIDE,lod,1.0f,gore.SSize,gore.TSize,gore.theta,gore.shader,&gore,qtrue); + G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, G2_NOCOLLIDE, lod, 1.0f, gore.SSize, gore.TSize, gore.theta, gore.shader, + &gore, qtrue); } - } -#else -void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) -{ } +#else +void G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) {} -void G2API_AddSkinGore(CGhoul2Info_v &ghoul2,SSkinGoreData &gore) -{ -} +void G2API_AddSkinGore(CGhoul2Info_v &ghoul2, SSkinGoreData &gore) {} #endif bool G2_TestModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up { - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return false; } - ghlInfo->mValid=false; - if (ghlInfo->mModelindex != -1) - { + ghlInfo->mValid = false; + if (ghlInfo->mModelindex != -1) { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); - if (ghlInfo->currentModel) - { - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + if (ghlInfo->currentModel) { + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; - ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex + ghlInfo->animModelIndexOffset); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); - if (!ghlInfo->aHeader) - { - Com_Error(ERR_DROP, "Ghoul2 Model has no mdxa (gla) %s",ghlInfo->mFileName); + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; + ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex + ghlInfo->animModelIndexOffset); + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + G2ERROR(ghlInfo->aHeader, va("Model has no mdxa (gla) %s", ghlInfo->mFileName)); + if (!ghlInfo->aHeader) { + Com_Error(ERR_DROP, "Ghoul2 Model has no mdxa (gla) %s", ghlInfo->mFileName); } - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + ghlInfo->mValid = true; } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } return ghlInfo->mValid; } bool G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up { - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return false; } - ghlInfo->mValid=false; -// G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); - if (ghlInfo->mModelindex != -1) - { - G2ERROR(ghlInfo->mFileName[0],"empty ghlInfo->mFileName"); + ghlInfo->mValid = false; + // G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); + if (ghlInfo->mModelindex != -1) { + G2ERROR(ghlInfo->mFileName[0], "empty ghlInfo->mFileName"); ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); - G2ERROR(ghlInfo->currentModel,va("NULL Model (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel) - { - G2ERROR(ghlInfo->currentModel->mdxm,va("Model has no mdxm (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + G2ERROR(ghlInfo->currentModel, va("NULL Model (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel) { + G2ERROR(ghlInfo->currentModel->mdxm, va("Model has no mdxm (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; - G2ERROR(ghlInfo->currentModelSize,va("Zero sized Model? (glm) %s",ghlInfo->mFileName)); - - ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex + ghlInfo->animModelIndexOffset); - G2ERROR(ghlInfo->animModel,va("NULL Model (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); - if (!ghlInfo->aHeader) - { - Com_Error(ERR_DROP, "Ghoul2 Model has no mdxa (gla) %s",ghlInfo->mFileName); + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; + G2ERROR(ghlInfo->currentModelSize, va("Zero sized Model? (glm) %s", ghlInfo->mFileName)); + + ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex + ghlInfo->animModelIndexOffset); + G2ERROR(ghlInfo->animModel, va("NULL Model (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + G2ERROR(ghlInfo->aHeader, va("Model has no mdxa (gla) %s", ghlInfo->mFileName)); + if (!ghlInfo->aHeader) { + Com_Error(ERR_DROP, "Ghoul2 Model has no mdxa (gla) %s", ghlInfo->mFileName); } - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - G2ERROR(ghlInfo->currentAnimModelSize,va("Zero sized Model? (gla) %s",ghlInfo->mFileName)); - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + G2ERROR(ghlInfo->currentAnimModelSize, va("Zero sized Model? (gla) %s", ghlInfo->mFileName)); + ghlInfo->mValid = true; } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } return ghlInfo->mValid; } bool G2_SetupModelPointers(CGhoul2Info_v &ghoul2) // returns true if any model is properly set up { - bool ret=false; + bool ret = false; int i; - for (i=0; i. #include "../server/exe_headers.h" #ifndef __Q_SHARED_H - #include "../qcommon/q_shared.h" +#include "../qcommon/q_shared.h" #endif #if !defined(TR_LOCAL_H) - #include "tr_local.h" +#include "tr_local.h" #endif #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -#define G2_MODEL_OK(g) ((g)&&(g)->mValid&&(g)->aHeader&&(g)->currentModel&&(g)->animModel) +#define G2_MODEL_OK(g) ((g) && (g)->mValid && (g)->aHeader && (g)->currentModel && (g)->animModel) //===================================================================================================================== // Bolt List handling routines - so entities can attach themselves to any part of the model in question // Given a bone number, see if that bone is already in our bone list -int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) -{ +int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) { // look through entire list - for(size_t i=0; imValid); - boltInfo_t tempBolt; +int G2_Add_Bolt_Surf_Num(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, const int surfNum) { + assert(ghlInfo && ghlInfo->mValid); + boltInfo_t tempBolt; - assert(surfNum>=0&&surfNum<(int)slist.size()); + assert(surfNum >= 0 && surfNum < (int)slist.size()); // ensure surface num is valid - if (surfNum >= (int)slist.size()) - { + if (surfNum >= (int)slist.size()) { return -1; } - // look through entire list - see if it's already there first - for(size_t i=0; imValid); - int surfNum = -1; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boltInfo_t tempBolt; - uint32_t flags; +void G2_Bolt_Not_Found(const char *boneName, const char *modName); +int G2_Add_Bolt(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, const char *boneName) { + assert(ghlInfo && ghlInfo->mValid); + int surfNum = -1; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boltInfo_t tempBolt; + uint32_t flags; assert(G2_MODEL_OK(ghlInfo)); @@ -138,31 +124,26 @@ int G2_Add_Bolt(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, surfNum = G2_IsSurfaceLegal(ghlInfo->currentModel, boneName, &flags); // did we find it as a surface? - if (surfNum != -1) - { - // look through entire list - see if it's already there first - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); int x; - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< ghlInfo->aHeader->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < ghlInfo->aHeader->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == ghlInfo->aHeader->numBones) - { + if (x == ghlInfo->aHeader->numBones) { // didn't find it? Error - //assert(0&&x == mod_a->mdxa->numBones); + // assert(0&&x == mod_a->mdxa->numBones); #if _DEBUG - G2_Bolt_Not_Found(boneName,ghlInfo->mFileName); + G2_Bolt_Not_Found(boneName, ghlInfo->mFileName); #endif return -1; } // look through entire list - see if it's already there first - for(size_t i=0; i=0&&index<(int)bltlist.size()); +qboolean G2_Remove_Bolt(boltInfo_v &bltlist, int index) { + assert(index >= 0 && index < (int)bltlist.size()); // did we find it? - if (index != -1) - { + if (index != -1) { bltlist[index].boltUsed--; - if (!bltlist[index].boltUsed) - { + if (!bltlist[index].boltUsed) { // set this bone to not used bltlist[index].boneNumber = -1; bltlist[index].surfaceNumber = -1; @@ -258,8 +228,4 @@ qboolean G2_Remove_Bolt (boltInfo_v &bltlist, int index) } // set the bolt list to all unused so the bone transformation routine ignores it. -void G2_Init_Bolt_List(boltInfo_v &bltlist) -{ - bltlist.clear(); -} - +void G2_Init_Bolt_List(boltInfo_v &bltlist) { bltlist.clear(); } diff --git a/code/rd-vanilla/G2_bones.cpp b/code/rd-vanilla/G2_bones.cpp index beb4bb309f..c1ad48c742 100644 --- a/code/rd-vanilla/G2_bones.cpp +++ b/code/rd-vanilla/G2_bones.cpp @@ -23,49 +23,46 @@ along with this program; if not, see . #include "../server/exe_headers.h" #ifndef __Q_SHARED_H - #include "../qcommon/q_shared.h" +#include "../qcommon/q_shared.h" #endif #if !defined(TR_LOCAL_H) - #include "tr_local.h" +#include "tr_local.h" #endif #if !defined(_QCOMMON_H_) - #include "../qcommon/qcommon.h" +#include "../qcommon/qcommon.h" #endif #include "qcommon/matcomp.h" #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #include #include "../ghoul2/ghoul2_gore.h" -//rww - RAGDOLL_END +// rww - RAGDOLL_END -extern cvar_t *r_Ghoul2BlendMultiplier; +extern cvar_t *r_Ghoul2BlendMultiplier; -void G2_Bone_Not_Found(const char *boneName,const char *modName); +void G2_Bone_Not_Found(const char *boneName, const char *modName); //===================================================================================================================== // Bone List handling routines - so entities can override bone info on a bone by bone level, and also interrogate this info // Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the // gla file, not the glm file type. -int G2_Find_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); +int G2_Find_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } #if _DEBUG - G2_Bone_Not_Found(boneName,ghlInfo->mFileName); + G2_Bone_Not_Found(boneName, ghlInfo->mFileName); #endif // didn't find it return -1; @@ -88,78 +84,63 @@ int G2_Find_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) #define DEBUG_G2_BONES (0) // we need to add a bone to the list - find a free one and see if we can find a corresponding bone in the gla file -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boneInfo_t tempBone; +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boneInfo_t tempBone; - //rww - RAGDOLL_BEGIN + // rww - RAGDOLL_BEGIN memset(&tempBone, 0, sizeof(tempBone)); - //rww - RAGDOLL_END + // rww - RAGDOLL_END - offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find int x; - for (x=0; x< mod->mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + for (x = 0; x < mod->mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mod->mdxa->numBones) - { + if (x == mod->mdxa->numBones) { #if _DEBUG - G2_Bone_Not_Found(boneName,mod->name); + G2_Bone_Not_Found(boneName, mod->name); #endif return -1; } // look through entire list - see if it's already there first - for(size_t i=0; imdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { #if DEBUG_G2_BONES { char mess[1000]; - sprintf(mess,"ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", - i, - x, - boneName); + sprintf(mess, "ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", i, x, boneName); OutputDebugString(mess); } #endif return i; } - } - else - { + } else { // if we found an entry that had a -1 for the bonenumber, then we hit a bone slot that was empty blist[i].boneNumber = x; blist[i].flags = 0; #if DEBUG_G2_BONES { char mess[1000]; - sprintf(mess,"ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", - i, - x, - boneName); + sprintf(mess, "ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", i, x, boneName); OutputDebugString(mess); } #endif - return i; + return i; } } @@ -170,26 +151,19 @@ int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) #if DEBUG_G2_BONES { char mess[1000]; - sprintf(mess,"ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", - blist.size()-1, - x, - boneName); + sprintf(mess, "ADD BONE1 blistIndex=%3d physicalIndex=%3d %s\n", blist.size() - 1, x, boneName); OutputDebugString(mess); } #endif - return blist.size()-1; + return blist.size() - 1; } - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) -{ +qboolean G2_Remove_Bone_Index(boneInfo_v &blist, int index) { // did we find it? - if (index != -1) - { + if (index != -1) { // check the flags first - if it's still being used Do NOT remove it - if (!blist[index].flags) - { + if (!blist[index].flags) { // set this bone to not used blist[index].boneNumber = -1; } @@ -199,13 +173,10 @@ qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) } // given a bone number, see if there is an override bone in the bone list -int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) -{ +int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) { // look through entire list - for(size_t i=0; imdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[index].boneNumber]); - Multiply_3x4Matrix(&temp1, boneOverride,&skel->BasePoseMatInv); - Multiply_3x4Matrix(boneOverride,&skel->BasePoseMat, &temp1); + Multiply_3x4Matrix(&temp1, boneOverride, &skel->BasePoseMatInv); + Multiply_3x4Matrix(boneOverride, &skel->BasePoseMat, &temp1); - } - else - { + } else { VectorCopy(angles, newAngles); // why I should need do this Fuck alone knows. But I do. - if (left == POSITIVE_Y) - { - newAngles[0] +=180; + if (left == POSITIVE_Y) { + newAngles[0] += 180; } Create_Matrix(newAngles, &temp1); @@ -345,13 +306,12 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[2][0] = permutation.matrix[2][1] = permutation.matrix[2][2] = permutation.matrix[2][3] = 0; // determine what axis newAngles Yaw should revolve around - switch (forward) - { + switch (forward) { case NEGATIVE_X: - permutation.matrix[0][0] = -1; // works + permutation.matrix[0][0] = -1; // works break; case POSITIVE_X: - permutation.matrix[0][0] = 1; // works + permutation.matrix[0][0] = 1; // works break; case NEGATIVE_Y: permutation.matrix[1][0] = -1; @@ -370,8 +330,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles pitch should revolve around - switch (left) - { + switch (left) { case NEGATIVE_X: permutation.matrix[0][1] = -1; break; @@ -379,10 +338,10 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[0][1] = 1; break; case NEGATIVE_Y: - permutation.matrix[1][1] = -1; // works + permutation.matrix[1][1] = -1; // works break; case POSITIVE_Y: - permutation.matrix[1][1] = 1; // works + permutation.matrix[1][1] = 1; // works break; case NEGATIVE_Z: permutation.matrix[2][1] = -1; @@ -395,8 +354,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles Roll should revolve around - switch (up) - { + switch (up) { case NEGATIVE_X: permutation.matrix[0][2] = -1; break; @@ -410,34 +368,29 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[1][2] = 1; break; case NEGATIVE_Z: - permutation.matrix[2][2] = -1; // works + permutation.matrix[2][2] = -1; // works break; case POSITIVE_Z: - permutation.matrix[2][2] = 1; // works + permutation.matrix[2][2] = 1; // works break; default: break; } - Multiply_3x4Matrix(boneOverride, &temp1,&permutation); - + Multiply_3x4Matrix(boneOverride, &temp1, &permutation); } // keep a copy of the matrix in the newmatrix which is actually what we use memcpy(&blist[index].newMatrix, &blist[index].matrix, sizeof(mdxaBone_t)); - } //========================================================================================= //// Public Bone Routines - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index==-1) - { +qboolean G2_Remove_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { return qfalse; } @@ -447,14 +400,10 @@ qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *bo #define DEBUG_PCJ (0) // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles_Index(CGhoul2Info *ghlInfo, boneInfo_v &blist, const int index, - const float *angles, const int flags, const Eorientations yaw, - const Eorientations pitch, const Eorientations roll, - const int blendTime, const int currentTime) -{ +qboolean G2_Set_Bone_Angles_Index(CGhoul2Info *ghlInfo, boneInfo_v &blist, const int index, const float *angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, const int blendTime, const int currentTime) { - if (index<0||(index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if (index < 0 || (index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { return qfalse; } @@ -464,25 +413,21 @@ qboolean G2_Set_Bone_Angles_Index(CGhoul2Info *ghlInfo, boneInfo_v &blist, const blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - OutputDebugString(va("%8x %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",(int)ghlInfo,index,currentTime,angles[0],angles[1],angles[2],yaw,pitch,roll,flags)); + OutputDebugString( + va("%8x %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", (int)ghlInfo, index, currentTime, angles[0], angles[1], angles[2], yaw, pitch, roll, flags)); #endif G2_Generate_Matrix(ghlInfo->animModel, blist, index, angles, flags, yaw, pitch, roll); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, - const int flags, const Eorientations up, const Eorientations left, const Eorientations forward, - const int blendTime, const int currentTime) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index == -1) - { +qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, const int blendTime, const int currentTime) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { index = G2_Add_Bone(ghlInfo->animModel, blist, boneName); } - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; blist[index].boneBlendStart = currentTime; @@ -495,13 +440,10 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, - const mdxaBone_t &matrix, const int flags, - const int blendTime, const int currentTime) -{ +qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, const mdxaBone_t &matrix, const int flags, const int blendTime, + const int currentTime) { - if (index<0||(index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if (index < 0 || (index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -515,20 +457,16 @@ qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, - const int flags,const int blendTime, const int currentTime) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index == -1) - { +qboolean G2_Set_Bone_Angles_Matrix(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, const int flags, + const int blendTime, const int currentTime) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { index = G2_Add_Bone(ghlInfo->animModel, blist, boneName); } - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); @@ -540,91 +478,70 @@ qboolean G2_Set_Bone_Angles_Matrix(CGhoul2Info *ghlInfo, boneInfo_v &blist, cons #define DEBUG_G2_TIMING (0) -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int startFrame, - const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame, const int AblendTime,int numFrames) -{ - int modFlags = flags; - int blendTime=AblendTime; - - if (r_Ghoul2BlendMultiplier) - { - if (r_Ghoul2BlendMultiplier->value!=1.0f) - { - if (r_Ghoul2BlendMultiplier->value<=0.0f) - { - modFlags&=~BONE_ANIM_BLEND; - } - else - { - blendTime=ceil(float(AblendTime)*r_Ghoul2BlendMultiplier->value); +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int currentTime, const float setFrame, const int AblendTime, int numFrames) { + int modFlags = flags; + int blendTime = AblendTime; + + if (r_Ghoul2BlendMultiplier) { + if (r_Ghoul2BlendMultiplier->value != 1.0f) { + if (r_Ghoul2BlendMultiplier->value <= 0.0f) { + modFlags &= ~BONE_ANIM_BLEND; + } else { + blendTime = ceil(float(AblendTime) * r_Ghoul2BlendMultiplier->value); } } } - - if (index<0||index >= (int)blist.size()||blist[index].boneNumber<0) - { + if (index < 0 || index >= (int)blist.size() || blist[index].boneNumber < 0) { return qfalse; } // sanity check to see if setfram is within animation bounds - assert((setFrame==-1) || ((setFrame>=startFrame) && (setFrameendFrame) && (setFrame<=(startFrame+1)))); - + assert((setFrame == -1) || ((setFrame >= startFrame) && (setFrame < endFrame)) || ((setFrame > endFrame) && (setFrame <= (startFrame + 1)))); // since we already existed, we can check to see if we want to start some blending - if (modFlags & BONE_ANIM_BLEND) - { - float currentFrame, animSpeed; - int startFrame, endFrame, flags; + if (modFlags & BONE_ANIM_BLEND) { + float currentFrame, animSpeed; + int startFrame, endFrame, flags; // figure out where we are now - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed,numFrames)) - { - if (blist[index].blendStart == currentTime) //we're replacing a blend in progress which hasn't started + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, numFrames)) { + if (blist[index].blendStart == currentTime) // we're replacing a blend in progress which hasn't started { // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; - } - else - { - if (animSpeed<0.0f) - { + } else { + if (animSpeed < 0.0f) { blist[index].blendFrame = floor(currentFrame); blist[index].blendLerpFrame = floor(currentFrame); - } - else - { + } else { blist[index].blendFrame = currentFrame; - blist[index].blendLerpFrame = currentFrame+1; + blist[index].blendLerpFrame = currentFrame + 1; // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendFrame >= blist[index].endFrame ) - { + if (blist[index].blendFrame >= blist[index].endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendFrame = blist[index].startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - assert(blist[index].endFrame>0); - blist[index].blendFrame = blist[index].endFrame -1; + else { + assert(blist[index].endFrame > 0); + blist[index].blendFrame = blist[index].endFrame - 1; } } // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendLerpFrame >= blist[index].endFrame ) - { + if (blist[index].blendLerpFrame >= blist[index].endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendLerpFrame = blist[index].startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - assert(blist[index].endFrame>0); + else { + assert(blist[index].endFrame > 0); blist[index].blendLerpFrame = blist[index].endFrame - 1; } } @@ -635,17 +552,14 @@ qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int st } } // hmm, we weren't animating on this bone. In which case disable the blend - else - { + else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = 0; // we aren't blending, so remove the option to do so modFlags &= ~BONE_ANIM_BLEND; - //return qfalse; + // return qfalse; } - } - else - { + } else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = blist[index].blendStart = 0; // we aren't blending, so remove the option to do so @@ -657,94 +571,65 @@ qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int st blist[index].startFrame = startFrame; blist[index].animSpeed = animSpeed; blist[index].pauseTime = 0; - assert(blist[index].blendFrame>=0&&blist[index].blendFrame=0&&blist[index].blendLerpFrame= 0 && blist[index].blendFrame < numFrames); + assert(blist[index].blendLerpFrame >= 0 && blist[index].blendLerpFrame < numFrames); // start up the animation:) - if (setFrame != -1) - { - blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); -/* - setFrame = bone.startFrame + ((currentTime - bone.startTime) / 50.0f * animSpeed); + if (setFrame != -1) { + blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0) / animSpeed)); + /* + setFrame = bone.startFrame + ((currentTime - bone.startTime) / 50.0f * animSpeed); - (setFrame - bone.startFrame) = ((currentTime - bone.startTime) / 50.0f * animSpeed); + (setFrame - bone.startFrame) = ((currentTime - bone.startTime) / 50.0f * animSpeed); - (setFrame - bone.startFrame)*50/animSpeed - currentTime = - bone.startTime; + (setFrame - bone.startFrame)*50/animSpeed - currentTime = - bone.startTime; - currentTime - (setFrame - bone.startFrame)*50/animSpeed = bone.startTime; -*/ - } - else - { + currentTime - (setFrame - bone.startFrame)*50/animSpeed = bone.startTime; + */ + } else { blist[index].startTime = currentTime; } blist[index].flags &= ~(BONE_ANIM_TOTAL); blist[index].flags |= modFlags; #if DEBUG_G2_TIMING - if (index>-10) - { - const boneInfo_t &bone=blist[index]; + if (index > -10) { + const boneInfo_t &bone = blist[index]; char mess[1000]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess,"sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); - } - else - { - sprintf(mess,"saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, "sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", index, currentTime, bone.startTime, bone.startFrame, + bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, "saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", index, currentTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, + bone.flags); } OutputDebugString(mess); } #endif -// assert(blist[index].startTime <= currentTime); + // assert(blist[index].startTime <= currentTime); return qtrue; - } -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int startFrame, - const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame, const int blendTime) -{ - int modFlags = flags; - int index = G2_Find_Bone(ghlInfo, blist, boneName); +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + int modFlags = flags; + int index = G2_Find_Bone(ghlInfo, blist, boneName); // sanity check to see if setfram is within animation bounds - if (setFrame != -1) - { + if (setFrame != -1) { assert((setFrame >= startFrame) && (setFrame <= endFrame)); } // did we find it? - if (index != -1) - { - return G2_Set_Bone_Anim_Index(blist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime,ghlInfo->aHeader->numFrames); + if (index != -1) { + return G2_Set_Bone_Anim_Index(blist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); } // no - lets try and add this bone in index = G2_Add_Bone(ghlInfo->animModel, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = 0; // we aren't blending, so remove the option to do so @@ -755,50 +640,25 @@ qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *b blist[index].animSpeed = animSpeed; blist[index].pauseTime = 0; // start up the animation:) - if (setFrame != -1) - { - blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); - } - else - { + if (setFrame != -1) { + blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0) / animSpeed)); + } else { blist[index].startTime = currentTime; } blist[index].flags &= ~BONE_ANIM_TOTAL; blist[index].flags |= modFlags; - assert(blist[index].blendFrame>=0&&blist[index].blendFrameaHeader->numFrames); - assert(blist[index].blendLerpFrame>=0&&blist[index].blendLerpFrameaHeader->numFrames); + assert(blist[index].blendFrame >= 0 && blist[index].blendFrame < ghlInfo->aHeader->numFrames); + assert(blist[index].blendLerpFrame >= 0 && blist[index].blendLerpFrame < ghlInfo->aHeader->numFrames); #if DEBUG_G2_TIMING - if (index>-10) - { - const boneInfo_t &bone=blist[index]; + if (index > -10) { + const boneInfo_t &bone = blist[index]; char mess[1000]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess,"s2b[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); - } - else - { - sprintf(mess,"s2a[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, "s2b[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", index, currentTime, bone.startTime, bone.startFrame, + bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, "s2a[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", index, currentTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, + bone.flags); } OutputDebugString(mess); } @@ -806,19 +666,16 @@ qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *b return qtrue; } - //assert(index != -1); - // no + // assert(index != -1); + // no return qfalse; } -qboolean G2_Get_Bone_Anim_Range_Index(boneInfo_v &blist, const int boneIndex, int *startFrame, int *endFrame) -{ - if (boneIndex != -1) - { - assert(boneIndex>=0&&boneIndex<(int)blist.size()); +qboolean G2_Get_Bone_Anim_Range_Index(boneInfo_v &blist, const int boneIndex, int *startFrame, int *endFrame) { + if (boneIndex != -1) { + assert(boneIndex >= 0 && boneIndex < (int)blist.size()); // are we an animating bone? - if (blist[boneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { + if (blist[boneIndex].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { *startFrame = blist[boneIndex].startFrame; *endFrame = blist[boneIndex].endFrame; return qtrue; @@ -826,17 +683,14 @@ qboolean G2_Get_Bone_Anim_Range_Index(boneInfo_v &blist, const int boneIndex, in } return qfalse; } -qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index==-1) - { +qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { return qfalse; } - if (G2_Get_Bone_Anim_Range_Index( blist, index, startFrame, endFrame)) - { - assert(*startFrame>=0&&*startFrameaHeader->numFrames); - assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); + if (G2_Get_Bone_Anim_Range_Index(blist, index, startFrame, endFrame)) { + assert(*startFrame >= 0 && *startFrame < ghlInfo->aHeader->numFrames); + assert(*endFrame > 0 && *endFrame <= ghlInfo->aHeader->numFrames); return qtrue; } return qfalse; @@ -844,117 +698,93 @@ qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const c // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int currentTime, - float *retcurrentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed,int numFrames) -{ +qboolean G2_Get_Bone_Anim_Index(boneInfo_v &blist, const int index, const int currentTime, float *retcurrentFrame, int *startFrame, int *endFrame, int *flags, + float *retAnimSpeed, int numFrames) { // did we find it? - if ((index>=0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) - { + if ((index >= 0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - int currentFrame,newFrame; + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + int currentFrame, newFrame; float lerp; - G2_TimingModel(blist[index],currentTime,numFrames,currentFrame,newFrame,lerp); + G2_TimingModel(blist[index], currentTime, numFrames, currentFrame, newFrame, lerp); - if (retcurrentFrame) - { - *retcurrentFrame =float(currentFrame)+lerp; + if (retcurrentFrame) { + *retcurrentFrame = float(currentFrame) + lerp; } - if (startFrame) - { + if (startFrame) { *startFrame = blist[index].startFrame; } - if (endFrame) - { + if (endFrame) { *endFrame = blist[index].endFrame; } - if (flags) - { + if (flags) { *flags = blist[index].flags; } - if (retAnimSpeed) - { + if (retAnimSpeed) { *retAnimSpeed = blist[index].animSpeed; } return qtrue; } } - if (startFrame) - { - *startFrame=0; + if (startFrame) { + *startFrame = 0; } - if (endFrame) - { - *endFrame=1; + if (endFrame) { + *endFrame = 1; } - if (retcurrentFrame) - { - *retcurrentFrame=0.0f; + if (retcurrentFrame) { + *retcurrentFrame = 0.0f; } - if (flags) - { - *flags=0; + if (flags) { + *flags = 0; } - if (retAnimSpeed) - { - *retAnimSpeed=0.0f; + if (retAnimSpeed) { + *retAnimSpeed = 0.0f; } return qfalse; } // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index==-1) - { +qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *retAnimSpeed) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { return qfalse; } assert(ghlInfo->aHeader); - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed,ghlInfo->aHeader->numFrames)) - { - assert(*startFrame>=0&&*startFrameaHeader->numFrames); - assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); - assert(*currentFrame>=0.0f&&((int)(*currentFrame))aHeader->numFrames); + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, ghlInfo->aHeader->numFrames)) { + assert(*startFrame >= 0 && *startFrame < ghlInfo->aHeader->numFrames); + assert(*endFrame > 0 && *endFrame <= ghlInfo->aHeader->numFrames); + assert(*currentFrame >= 0.0f && ((int)(*currentFrame)) < ghlInfo->aHeader->numFrames); return qtrue; } return qfalse; } - // given a model, bonelist and bonename, lets pause an anim if it's playing. -qboolean G2_Pause_Bone_Anim_Index( boneInfo_v &blist, const int boneIndex, const int currentTime,int numFrames) -{ - if (boneIndex>=0&&boneIndex<(int)blist.size()) - { +qboolean G2_Pause_Bone_Anim_Index(boneInfo_v &blist, const int boneIndex, const int currentTime, int numFrames) { + if (boneIndex >= 0 && boneIndex < (int)blist.size()) { // are we pausing or un pausing? - if (blist[boneIndex].pauseTime) - { - int startFrame, endFrame, flags; - float currentFrame, animSpeed; + if (blist[boneIndex].pauseTime) { + int startFrame, endFrame, flags; + float currentFrame, animSpeed; // figure out what frame we are on now - if (G2_Get_Bone_Anim_Index( blist, boneIndex, blist[boneIndex].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed,numFrames)) - { + if (G2_Get_Bone_Anim_Index(blist, boneIndex, blist[boneIndex].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, numFrames)) { // reset start time so we are actually on this frame right now - G2_Set_Bone_Anim_Index( blist, boneIndex, startFrame, endFrame, flags, animSpeed, currentTime, currentFrame, 0,numFrames); + G2_Set_Bone_Anim_Index(blist, boneIndex, startFrame, endFrame, flags, animSpeed, currentTime, currentFrame, 0, numFrames); // no pausing anymore blist[boneIndex].pauseTime = 0; - } - else - { + } else { return qfalse; } } // ahh, just pausing, the easy bit - else - { + else { blist[boneIndex].pauseTime = currentTime; } @@ -963,25 +793,20 @@ qboolean G2_Pause_Bone_Anim_Index( boneInfo_v &blist, const int boneIndex, const assert(0); return qfalse; } -qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index==-1) - { +qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index == -1) { return qfalse; } - return (G2_Pause_Bone_Anim_Index( blist, index, currentTime,ghlInfo->aHeader->numFrames) ); + return (G2_Pause_Bone_Anim_Index(blist, index, currentTime, ghlInfo->aHeader->numFrames)); } -qboolean G2_IsPaused(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index != -1) - { +qboolean G2_IsPaused(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index != -1) { // are we paused? - if (blist[index].pauseTime) - { + if (blist[index].pauseTime) { // yup. paused. return qtrue; } @@ -992,11 +817,9 @@ qboolean G2_IsPaused(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) { - if (index<0 || (index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if (index < 0 || (index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist return qfalse; } @@ -1006,11 +829,9 @@ qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index != -1) - { +qboolean G2_Stop_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index != -1) { blist[index].flags &= ~(BONE_ANIM_TOTAL); return G2_Remove_Bone_Index(blist, index); } @@ -1019,26 +840,21 @@ qboolean G2_Stop_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char * } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } blist[index].flags &= ~(BONE_ANGLES_TOTAL); return G2_Remove_Bone_Index(blist, index); - } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - int index = G2_Find_Bone(ghlInfo, blist, boneName); - if (index != -1) - { +qboolean G2_Stop_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + int index = G2_Find_Bone(ghlInfo, blist, boneName); + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); return G2_Remove_Bone_Index(blist, index); } @@ -1046,134 +862,125 @@ qboolean G2_Stop_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char return qfalse; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN /* rag stuff */ -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool LimitAngles,CRagDollUpdateParams *params = NULL); -static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale); -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V,const vec3_t currentOrg,CRagDollUpdateParams *params, int curTime); -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered); - -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum); +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool LimitAngles, + CRagDollUpdateParams *params = NULL); +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V, int g2Index, int frameNum, const vec3_t angles, const vec3_t position, const vec3_t scale); +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime); +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered); + +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv); +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum); #define MAX_BONES_RAG (256) -struct SRagEffector -{ - vec3_t currentOrigin; - vec3_t desiredDirection; - vec3_t desiredOrigin; - float radius; - float weight; +struct SRagEffector { + vec3_t currentOrigin; + vec3_t desiredDirection; + vec3_t desiredOrigin; + float radius; + float weight; }; -#define RAG_MASK (CONTENTS_SOLID|CONTENTS_TERRAIN)//|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) +#define RAG_MASK \ + (CONTENTS_SOLID | \ + CONTENTS_TERRAIN) //|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) -extern cvar_t *broadsword; -extern cvar_t *broadsword_kickbones; -extern cvar_t *broadsword_kickorigin; -extern cvar_t *broadsword_dontstopanim; -extern cvar_t *broadsword_waitforshot; -extern cvar_t *broadsword_playflop; +extern cvar_t *broadsword; +extern cvar_t *broadsword_kickbones; +extern cvar_t *broadsword_kickorigin; +extern cvar_t *broadsword_dontstopanim; +extern cvar_t *broadsword_waitforshot; +extern cvar_t *broadsword_playflop; -extern cvar_t *broadsword_effcorr; +extern cvar_t *broadsword_effcorr; -extern cvar_t *broadsword_ragtobase; +extern cvar_t *broadsword_ragtobase; -extern cvar_t *broadsword_dircap; +extern cvar_t *broadsword_dircap; -extern cvar_t *broadsword_extra1; -extern cvar_t *broadsword_extra2; +extern cvar_t *broadsword_extra1; +extern cvar_t *broadsword_extra2; -#define RAG_PCJ (0x00001) -#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well -#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well -#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well -#define RAG_EFFECTOR (0x00100) -#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint -#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint -#define RAG_BONE_LIGHTWEIGHT (0x04000) //used to indicate a bone's velocity treatment -#define RAG_PCJ_IK_CONTROLLED (0x08000) //controlled from IK move input -#define RAG_UNSNAPPABLE (0x10000) //cannot be broken out of constraints ever +#define RAG_PCJ (0x00001) +#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well +#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well +#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well +#define RAG_EFFECTOR (0x00100) +#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint +#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint +#define RAG_BONE_LIGHTWEIGHT (0x04000) // used to indicate a bone's velocity treatment +#define RAG_PCJ_IK_CONTROLLED (0x08000) // controlled from IK move input +#define RAG_UNSNAPPABLE (0x10000) // cannot be broken out of constraints ever // thiese flags are on the model and correspond to... //#define GHOUL2_RESERVED_FOR_RAGDOLL 0x0ff0 // these are not defined here for dependecies sake -#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll -#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim -#define GHOUL2_RAG_DONE 0x0200 // got end death anim -#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event -#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled - -#define flrand Q_flrand - -static mdxaBone_t* ragBasepose[MAX_BONES_RAG]; -static mdxaBone_t* ragBaseposeInv[MAX_BONES_RAG]; -static mdxaBone_t ragBones[MAX_BONES_RAG]; -static SRagEffector ragEffectors[MAX_BONES_RAG]; -static boneInfo_t *ragBoneData[MAX_BONES_RAG]; -static int tempDependents[MAX_BONES_RAG]; -static int ragBlistIndex[MAX_BONES_RAG]; -static int numRags; -static vec3_t ragBoneMins; -static vec3_t ragBoneMaxs; -static vec3_t ragBoneCM; -static bool haveDesiredPelvisOffset=false; -static vec3_t desiredPelvisOffset; // this is for the root -static float ragOriginChange=0.0f; -static vec3_t ragOriginChangeDir; -//debug -//static vec3_t handPos={0,0,0}; -//static vec3_t handPos2={0,0,0}; - -enum ERagState -{ - ERS_DYNAMIC, - ERS_SETTLING, - ERS_SETTLED -}; -static int ragState; - -static std::vector *rag = NULL; // once we get the dependents precomputed this can be local - +#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll +#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim +#define GHOUL2_RAG_DONE 0x0200 // got end death anim +#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event +#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled + +#define flrand Q_flrand + +static mdxaBone_t *ragBasepose[MAX_BONES_RAG]; +static mdxaBone_t *ragBaseposeInv[MAX_BONES_RAG]; +static mdxaBone_t ragBones[MAX_BONES_RAG]; +static SRagEffector ragEffectors[MAX_BONES_RAG]; +static boneInfo_t *ragBoneData[MAX_BONES_RAG]; +static int tempDependents[MAX_BONES_RAG]; +static int ragBlistIndex[MAX_BONES_RAG]; +static int numRags; +static vec3_t ragBoneMins; +static vec3_t ragBoneMaxs; +static vec3_t ragBoneCM; +static bool haveDesiredPelvisOffset = false; +static vec3_t desiredPelvisOffset; // this is for the root +static float ragOriginChange = 0.0f; +static vec3_t ragOriginChangeDir; +// debug +// static vec3_t handPos={0,0,0}; +// static vec3_t handPos2={0,0,0}; + +enum ERagState { ERS_DYNAMIC, ERS_SETTLING, ERS_SETTLED }; +static int ragState; + +static std::vector *rag = NULL; // once we get the dependents precomputed this can be local static void G2_Generate_MatrixRag( - // caution this must not be called before the whole skeleton is "remembered" - boneInfo_v &blist, - int index) -{ - + // caution this must not be called before the whole skeleton is "remembered" + boneInfo_v &blist, int index) { - boneInfo_t &bone=blist[index];//.sent; + boneInfo_t &bone = blist[index]; //.sent; - memcpy(&bone.matrix,&bone.ragOverrideMatrix, sizeof(mdxaBone_t)); + memcpy(&bone.matrix, &bone.ragOverrideMatrix, sizeof(mdxaBone_t)); #ifdef _DEBUG - int i,j; - for (i = 0; i < 3; i++ ) - { - for (j = 0; j < 4; j++ ) - { - assert( !Q_isnan(bone.matrix.matrix[i][j])); + int i, j; + for (i = 0; i < 3; i++) { + for (j = 0; j < 4; j++) { + assert(!Q_isnan(bone.matrix.matrix[i][j])); } } -#endif// _DEBUG - memcpy(&blist[index].newMatrix,&bone.matrix, sizeof(mdxaBone_t)); +#endif // _DEBUG + memcpy(&blist[index].newMatrix, &bone.matrix, sizeof(mdxaBone_t)); } -int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); /* @@ -1188,26 +995,23 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa aHeader = animModel->mdxa; assert(aHeader); - offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); */ // look through entire list - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); - //skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + // skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -1218,82 +1022,57 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa return -1; } -static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - CGhoul2Info &ghoul2, - const vec3_t scale, - const vec3_t origin) -{ +static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, CGhoul2Info &ghoul2, const vec3_t scale, const vec3_t origin) { // do not change the state of the skeleton here - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; - VectorCopy(origin,bone.extraVec1); + if (index != -1) { + boneInfo_t &bone = blist[index]; + VectorCopy(origin, bone.extraVec1); - G2_GetBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.originalTrueBoneMatrix,bone.basepose,bone.baseposeInv); -// bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); - bone.originalOrigin[0]=bone.originalTrueBoneMatrix.matrix[0][3]; - bone.originalOrigin[1]=bone.originalTrueBoneMatrix.matrix[1][3]; - bone.originalOrigin[2]=bone.originalTrueBoneMatrix.matrix[2][3]; + G2_GetBoneMatrixLow(ghoul2, bone.boneNumber, scale, bone.originalTrueBoneMatrix, bone.basepose, bone.baseposeInv); + // bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); + bone.originalOrigin[0] = bone.originalTrueBoneMatrix.matrix[0][3]; + bone.originalOrigin[1] = bone.originalTrueBoneMatrix.matrix[1][3]; + bone.originalOrigin[2] = bone.originalTrueBoneMatrix.matrix[2][3]; } return index; } -static int G2_Set_Bone_Angles_Rag( - CGhoul2Info &ghoul2, - const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - const int flags, - const float radius, - const vec3_t angleMin=0, - const vec3_t angleMax=0, - const int blendTime=500) -{ - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); +static int G2_Set_Bone_Angles_Rag(CGhoul2Info &ghoul2, const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, const int flags, const float radius, + const vec3_t angleMin = 0, const vec3_t angleMax = 0, const int blendTime = 500) { + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; + if (index != -1) { + boneInfo_t &bone = blist[index]; bone.flags &= ~(BONE_ANGLES_TOTAL); bone.flags |= BONE_ANGLES_RAGDOLL; - if (flags&RAG_PCJ) - { - if (flags&RAG_PCJ_POST_MULT) - { + if (flags & RAG_PCJ) { + if (flags & RAG_PCJ_POST_MULT) { bone.flags |= BONE_ANGLES_POSTMULT; - } - else if (flags&RAG_PCJ_MODEL_ROOT) - { + } else if (flags & RAG_PCJ_MODEL_ROOT) { bone.flags |= BONE_ANGLES_PREMULT; -// bone.flags |= BONE_ANGLES_POSTMULT; - } - else - { + // bone.flags |= BONE_ANGLES_POSTMULT; + } else { assert(!"Invalid RAG PCJ\n"); } } - bone.ragStartTime=G2API_GetTime(0); + bone.ragStartTime = G2API_GetTime(0); bone.boneBlendStart = bone.ragStartTime; bone.boneBlendTime = blendTime; - bone.radius=radius; - bone.weight=1.0f; + bone.radius = radius; + bone.weight = 1.0f; - //init the others to valid values + // init the others to valid values bone.epGravFactor = 0; VectorClear(bone.epVelocity); bone.solidCount = 0; @@ -1309,48 +1088,37 @@ static int G2_Set_Bone_Angles_Rag( bone.hasOverGoal = false; bone.hasAnimFrameMatrix = -1; -// bone.weight=pow(radius,1.7f); //cubed was too harsh -// bone.weight=radius*radius*radius; - if (angleMin&&angleMax) - { - VectorCopy(angleMin,bone.minAngles); - VectorCopy(angleMax,bone.maxAngles); - } - else - { - VectorCopy(bone.currentAngles,bone.minAngles); // I guess this isn't a rag pcj then - VectorCopy(bone.currentAngles,bone.maxAngles); - } - if (!bone.lastTimeUpdated) - { - static mdxaBone_t id = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - memcpy(&bone.ragOverrideMatrix,&id, sizeof(mdxaBone_t)); + // bone.weight=pow(radius,1.7f); //cubed was too harsh + // bone.weight=radius*radius*radius; + if (angleMin && angleMax) { + VectorCopy(angleMin, bone.minAngles); + VectorCopy(angleMax, bone.maxAngles); + } else { + VectorCopy(bone.currentAngles, bone.minAngles); // I guess this isn't a rag pcj then + VectorCopy(bone.currentAngles, bone.maxAngles); + } + if (!bone.lastTimeUpdated) { + static mdxaBone_t id = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + memcpy(&bone.ragOverrideMatrix, &id, sizeof(mdxaBone_t)); VectorClear(bone.anglesOffset); VectorClear(bone.positionOffset); - VectorClear(bone.velocityEffector); // this is actually a velocity now - VectorClear(bone.velocityRoot); // this is actually a velocity now + VectorClear(bone.velocityEffector); // this is actually a velocity now + VectorClear(bone.velocityRoot); // this is actually a velocity now VectorClear(bone.lastPosition); VectorClear(bone.lastShotDir); - bone.lastContents=0; + bone.lastContents = 0; // if this is non-zero, we are in a dynamic state - bone.firstCollisionTime=bone.ragStartTime; + bone.firstCollisionTime = bone.ragStartTime; // if this is non-zero, we are in a settling state - bone.restTime=0; + bone.restTime = 0; // if they are both zero, we are in a settled state - bone.firstTime=0; + bone.firstTime = 0; - bone.RagFlags=flags; - bone.DependentRagIndexMask=0; + bone.RagFlags = flags; + bone.DependentRagIndexMask = 0; - G2_Generate_MatrixRag(blist,index); // set everything to th id + G2_Generate_MatrixRag(blist, index); // set everything to th id #if 0 VectorClear(bone.currentAngles); @@ -1358,32 +1126,25 @@ static int G2_Set_Bone_Angles_Rag( // VectorScale(bone.currentAngles,0.5f,bone.currentAngles); #else { - if ( - (flags&RAG_PCJ_MODEL_ROOT) || - (flags&RAG_PCJ_PELVIS) || - !(flags&RAG_PCJ)) - { + if ((flags & RAG_PCJ_MODEL_ROOT) || (flags & RAG_PCJ_PELVIS) || !(flags & RAG_PCJ)) { VectorClear(bone.currentAngles); - } - else - { + } else { int k; - for (k=0;k<3;k++) - { - float scalar=flrand(-1.0f,1.0f); - scalar*=flrand(-1.0f,1.0f)*flrand(-1.0f,1.0f); + for (k = 0; k < 3; k++) { + float scalar = flrand(-1.0f, 1.0f); + scalar *= flrand(-1.0f, 1.0f) * flrand(-1.0f, 1.0f); // this is a heavily central distribution // center it on .5 (and make it small) - scalar*=0.5f; - scalar+=0.5f; + scalar *= 0.5f; + scalar += 0.5f; - bone.currentAngles[k]=(bone.minAngles[k]-bone.maxAngles[k])*scalar+bone.maxAngles[k]; + bone.currentAngles[k] = (bone.minAngles[k] - bone.maxAngles[k]) * scalar + bone.maxAngles[k]; } } } // VectorClear(bone.currentAngles); #endif - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); } } return index; @@ -1392,50 +1153,43 @@ static int G2_Set_Bone_Angles_Rag( class CRagDollParams; const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2); - -static void G2_RagDollMatchPosition() -{ - haveDesiredPelvisOffset=false; +static void G2_RagDollMatchPosition() { + haveDesiredPelvisOffset = false; int i; - for (i=0;inumBones); -#else //The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list - //and let them re-set their anims/angles gameside. +#else // The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list + // and let them re-set their anims/angles gameside. int i = 0; - while (i < blist.size()) - { + while (i < blist.size()) { boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) - { + if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -1523,120 +1269,83 @@ void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V) i++; } #endif - ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED); + ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED); } -//This is just a shell to avoid asserts on the initial position tracing -class CRagDollInitialUpdateParams : public CRagDollUpdateParams -{ -public: - virtual void EffectorCollision(const SRagDollEffectorCollision &data) - { - } - virtual void RagDollBegin() - { - } - virtual void RagDollSettled() - { - } - virtual void Collision() - { - } +// This is just a shell to avoid asserts on the initial position tracing +class CRagDollInitialUpdateParams : public CRagDollUpdateParams { + public: + virtual void EffectorCollision(const SRagDollEffectorCollision &data) {} + virtual void RagDollBegin() {} + virtual void RagDollSettled() {} + virtual void Collision() {} #ifdef _DEBUG - virtual void DebugLine(vec3_t p1,vec3_t p2,int color,bool bbox) - { - } + virtual void DebugLine(vec3_t p1, vec3_t p2, int color, bool bbox) {} #endif }; -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) -{ - if (parms) - { - parms->CallRagDollBegin=false; +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms) { + if (parms) { + parms->CallRagDollBegin = false; } - if (!broadsword||!broadsword->integer||!parms) - { + if (!broadsword || !broadsword->integer || !parms) { return; } int model; - for (model = 0; model < ghoul2V.size(); model++) - { - if (ghoul2V[model].mModelindex != -1) - { + for (model = 0; model < ghoul2V.size(); model++) { + if (ghoul2V[model].mModelindex != -1) { break; } } - if (model==ghoul2V.size()) - { + if (model == ghoul2V.size()) { return; } - CGhoul2Info &ghoul2=ghoul2V[model]; - const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); - if (!mod_a) - { + CGhoul2Info &ghoul2 = ghoul2V[model]; + const mdxaHeader_t *mod_a = G2_GetModA(ghoul2); + if (!mod_a) { return; } - int curTime=G2API_GetTime(0); + int curTime = G2API_GetTime(0); boneInfo_v &blist = ghoul2.mBlist; - int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); - switch (parms->RagPhase) - { + int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); + switch (parms->RagPhase) { case CRagDollParams::RP_START_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING; - return; /// not doing anything with this yet + ghoul2.mFlags |= GHOUL2_RAG_PENDING; + return; /// not doing anything with this yet break; case CRagDollParams::RP_END_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE; - if (broadsword_waitforshot && - broadsword_waitforshot->integer) - { - if (broadsword_waitforshot->integer==2) - { - if (!(ghoul2.mFlags&(GHOUL2_RAG_COLLISION_DURING_DEATH|GHOUL2_RAG_COLLISION_SLIDE))) - { - //nothing was encountered, lets just wait for the first shot + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE; + if (broadsword_waitforshot && broadsword_waitforshot->integer) { + if (broadsword_waitforshot->integer == 2) { + if (!(ghoul2.mFlags & (GHOUL2_RAG_COLLISION_DURING_DEATH | GHOUL2_RAG_COLLISION_SLIDE))) { + // nothing was encountered, lets just wait for the first shot return; // we ain't starting yet } - } - else - { + } else { return; // we ain't starting yet } } break; case CRagDollParams::RP_DEATH_COLLISION: - if (parms->collisionType) - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_SLIDE; - } - else - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_DURING_DEATH; + if (parms->collisionType) { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_SLIDE; + } else { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_DURING_DEATH; } - if (broadsword_dontstopanim && broadsword_waitforshot && - (broadsword_dontstopanim->integer || broadsword_waitforshot->integer) - ) - { - if (!(ghoul2.mFlags&GHOUL2_RAG_DONE)) - { + if (broadsword_dontstopanim && broadsword_waitforshot && (broadsword_dontstopanim->integer || broadsword_waitforshot->integer)) { + if (!(ghoul2.mFlags & GHOUL2_RAG_DONE)) { return; // we ain't starting yet } } break; case CRagDollParams::RP_CORPSE_SHOT: - if (broadsword_kickorigin && - broadsword_kickorigin->integer) - { - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - //rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. + if (broadsword_kickorigin && broadsword_kickorigin->integer) { + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + // rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. /* float magicFactor14=8.0f; //64.0f; // kick strength @@ -1661,29 +1370,22 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) } break; case CRagDollParams::RP_GET_PELVIS_OFFSET: - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { VectorClear(parms->pelvisAnglesOffset); VectorClear(parms->pelvisPositionOffset); } // intentional lack of a break case CRagDollParams::RP_SET_PELVIS_OFFSET: - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { - VectorCopy(bone.anglesOffset,parms->pelvisAnglesOffset); - VectorCopy(bone.positionOffset,parms->pelvisPositionOffset); - } - else - { - VectorCopy(parms->pelvisAnglesOffset,bone.anglesOffset); - VectorCopy(parms->pelvisPositionOffset,bone.positionOffset); + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { + VectorCopy(bone.anglesOffset, parms->pelvisAnglesOffset); + VectorCopy(bone.positionOffset, parms->pelvisPositionOffset); + } else { + VectorCopy(parms->pelvisAnglesOffset, bone.anglesOffset); + VectorCopy(parms->pelvisPositionOffset, bone.positionOffset); } } } @@ -1700,8 +1402,7 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) break; } - if (ghoul2.mFlags&GHOUL2_RAG_STARTED) - { + if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { // only going to begin ragdoll once, everything else depends on what happens to the origin return; } @@ -1712,289 +1413,283 @@ if (index>=0) } #endif - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED; // well anyway we are going live - parms->CallRagDollBegin=true; + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED; // well anyway we are going live + parms->CallRagDollBegin = true; G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); #if 1 - G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); - - G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"cranium",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "model_root", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "pelvis", ghoul2, parms->scale, parms->position); + + G2_Set_Bone_Rag(mod_a, blist, "lower_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "upper_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "thoracic", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "cranium", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhand", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhand", ghoul2, parms->scale, parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ceyebrow", ghoul2, parms->scale, parms->position); #else - G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"cervical",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "model_root", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "pelvis", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lower_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "upper_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "thoracic", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "cervical", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ceyebrow", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhand", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhand", ghoul2, parms->scale, parms->position); #endif - //int startFrame = 3665, endFrame = 3665+1; + // int startFrame = 3665, endFrame = 3665+1; int startFrame = parms->startFrame, endFrame = parms->endFrame; assert(startFrame < mod_a->numFrames); - assert(endFrame < mod_a->numFrames); - - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"upper_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lower_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"Motion",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); -// G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, -// BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, -// 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - -// should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); + assert(endFrame < mod_a->numFrames); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "upper_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lower_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "Motion", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + // G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, + // BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + // 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + // should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); #if 1 - static const float fRadScale = 0.3f;//0.5f; + static const float fRadScale = 0.3f; // 0.5f; - vec3_t pcjMin,pcjMax; - VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); - VectorSet(pcjMax,90.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + vec3_t pcjMin, pcjMax; + VectorSet(pcjMin, -90.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 90.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "model_root", RAG_PCJ_MODEL_ROOT | RAG_PCJ | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 100); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "pelvis", RAG_PCJ_PELVIS | RAG_PCJ | RAG_PCJ_POST_MULT | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, + 100); // new base anim, unconscious flop - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT; //|RAG_EFFECTOR; - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,15.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); - VectorSet(pcjMax,25.0f,25.0f,25.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -25.0f, -25.0f, -25.0f); + VectorSet(pcjMax, 25.0f, 25.0f, 25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 12.0f * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, 6.0f * fRadScale, pcjMin, pcjMax, 500); static const float sFactLeg = 1.0f; static const float sFactArm = 1.0f; static const float sRadArm = 1.0f; static const float sRadLeg = 1.0f; - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); - VectorSet(pcjMax,15.0f,40.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); + VectorSet(pcjMin, -50.0f, -80.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 40.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,30.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - - VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); - VectorSet(pcjMax,30.0f,5.0f,20.0f); + VectorSet(pcjMin, -80.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 5.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -60.0f, -5.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); float sRadEArm = 1.2f; float sRadELeg = 1.2f; -// int rhand= - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,5.0f); + // int rhand= + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ceyebrow", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 5.0f); #else - static const float fRadScale = 0.3f;//0.5f; - static int pcjflags = RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + static const float fRadScale = 0.3f; // 0.5f; + static int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT; //|RAG_EFFECTOR; static const float sFactLeg = 1.0f; static const float sFactArm = 1.0f; static const float sRadArm = 1.0f; static const float sRadLeg = 1.0f; - vec3_t pcjMin,pcjMax; - VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); - VectorSet(pcjMax,90.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - - //PCJ/EFFECTORS - VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); - VectorSet(pcjMax,30.0f,5.0f,20.0f); + vec3_t pcjMin, pcjMax; + VectorSet(pcjMin, -90.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 90.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "model_root", RAG_PCJ_MODEL_ROOT | RAG_PCJ | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 100); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "pelvis", RAG_PCJ_PELVIS | RAG_PCJ | RAG_PCJ_POST_MULT | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, + 100); + + // PCJ/EFFECTORS + VectorSet(pcjMin, -80.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 5.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -60.0f, -5.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - - - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,15.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); - VectorSet(pcjMax,25.0f,25.0f,25.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",RAG_PCJ|RAG_PCJ_POST_MULT|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -25.0f, -25.0f, -25.0f); + VectorSet(pcjMax, 25.0f, 25.0f, 25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 12.0f * fRadScale, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", RAG_PCJ | RAG_PCJ_POST_MULT | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, 6.0f * fRadScale, pcjMin, + pcjMax, 500); + + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); - VectorSet(pcjMax,15.0f,40.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -50.0f, -80.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 40.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,30.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - - //EFFECTORS + // EFFECTORS static const float sRadEArm = 1.2f; static const float sRadELeg = 1.2f; - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cervical",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cervical", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 10.0f * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ceyebrow", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 10.0f * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); #endif -//match the currrent animation - if (!G2_RagDollSetup(ghoul2,curTime,true,parms->position,false)) - { + // match the currrent animation + if (!G2_RagDollSetup(ghoul2, curTime, true, parms->position, false)) { assert(!"failed to add any rag bones"); return; } - G2_RagDollCurrentPosition(ghoul2V,model,curTime,parms->angles,parms->position,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, parms->position, parms->scale); int k; @@ -2007,7 +1702,7 @@ if (index>=0) fparms.settleFrame = parms->endFrame; fparms.groundEnt = parms->groundEnt; - //Guess I don't need to do this, do I? + // Guess I don't need to do this, do I? G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); vec3_t dPos; @@ -2016,50 +1711,41 @@ if (index>=0) dPos[2] -= 6; #endif - for (k=0;kangles,dPos,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, dPos, parms->scale); G2_RagDollMatchPosition(); - G2_RagDollSolve(ghoul2V,model,1.0f*(1.0f-k/40.0f),curTime,dPos,false); + G2_RagDollSolve(ghoul2V, model, 1.0f * (1.0f - k / 40.0f), curTime, dPos, false); } } -void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t hit) -{ - if (!broadsword||!broadsword->integer) - { +void G2_SetRagDollBullet(CGhoul2Info &ghoul2, const vec3_t rayStart, const vec3_t hit) { + if (!broadsword || !broadsword->integer) { return; } vec3_t shotDir; - VectorSubtract(hit,rayStart,shotDir); - float len=VectorLength(shotDir); - if (len<1.0f) - { + VectorSubtract(hit, rayStart, shotDir); + float len = VectorLength(shotDir); + if (len < 1.0f) { return; } - float lenr=1.0f/len; - shotDir[0]*=lenr; - shotDir[1]*=lenr; - shotDir[2]*=lenr; + float lenr = 1.0f / len; + shotDir[0] *= lenr; + shotDir[1] *= lenr; + shotDir[2] *= lenr; - bool firstOne=false; - if (broadsword_kickbones&&broadsword_kickbones->integer) - { + bool firstOne = false; + if (broadsword_kickbones && broadsword_kickbones->integer) { int i; - int magicFactor13=150.0f; // squared radius multiplier for shot effects + int magicFactor13 = 150.0f; // squared radius multiplier for shot effects boneInfo_v &blist = ghoul2.mBlist; - for(i=blist.size()-1;i>=0;i--) - { - boneInfo_t &bone=blist[i]; - if ((bone.flags & BONE_ANGLES_TOTAL)) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (!firstOne) - { - firstOne=true; + for (i = blist.size() - 1; i >= 0; i--) { + boneInfo_t &bone = blist[i]; + if ((bone.flags & BONE_ANGLES_TOTAL)) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (!firstOne) { + firstOne = true; #if 0 int curTime=G2API_GetTime(0); const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); @@ -2102,232 +1788,177 @@ void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t #endif } - VectorCopy(shotDir,bone.lastShotDir); + VectorCopy(shotDir, bone.lastShotDir); vec3_t dir; - VectorSubtract(bone.lastPosition,hit,dir); - len=VectorLength(dir); - if (len<1.0f) - { - len=1.0f; + VectorSubtract(bone.lastPosition, hit, dir); + len = VectorLength(dir); + if (len < 1.0f) { + len = 1.0f; } - lenr=1.0f/len; - float effect=lenr; - effect*=magicFactor13*effect; // this is cubed, one of them is absorbed by the next calc - bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f)); -// bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); - assert( !Q_isnan(shotDir[2])); - // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + lenr = 1.0f / len; + float effect = lenr; + effect *= magicFactor13 * effect; // this is cubed, one of them is absorbed by the next calc + bone.velocityEffector[0] = shotDir[0] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[1] = shotDir[1] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[2] = fabs(shotDir[2]) * (effect + flrand(0.0f, 0.05f)); + // bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + assert(!Q_isnan(shotDir[2])); + // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); // go dynamic - bone.firstCollisionTime=G2API_GetTime(0); -// bone.firstCollisionTime=0; - bone.restTime=0; + bone.firstCollisionTime = G2API_GetTime(0); + // bone.firstCollisionTime=0; + bone.restTime = 0; } } } } } +static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone, int frameNum, const vec3_t origin, bool &resetOrigin) { + ragOriginChange = DistanceSquared(origin, bone.extraVec1); + VectorSubtract(origin, bone.extraVec1, ragOriginChangeDir); -static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone,int frameNum,const vec3_t origin,bool &resetOrigin) -{ - ragOriginChange=DistanceSquared(origin,bone.extraVec1); - VectorSubtract(origin,bone.extraVec1,ragOriginChangeDir); + float decay = 1.0f; - float decay=1.0f; + int dynamicTime = 1000; + int settleTime = 1000; - int dynamicTime=1000; - int settleTime=1000; - - if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } - } - else if (bone.firstCollisionTime>0) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved - bone.firstCollisionTime=frameNum; - } - else - { + } else if (bone.firstCollisionTime > 0) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } -//decay=0.0f; - } - else if (bone.restTime>0) - { - decay=1.0f-(frameNum-bone.restTime)/float(dynamicTime); - if (decay<0.0f) - { - decay=0.0f; - } - if (decay>1.0f) - { - decay=1.0f; - } - float magicFactor8=1.0f; // Power for decay - decay=pow(decay,magicFactor8); - ragState=ERS_SETTLING; - if (frameNum>bone.restTime+settleTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { - bone.restTime=frameNum; - } - else - { + // decay=0.0f; + } else if (bone.restTime > 0) { + decay = 1.0f - (frameNum - bone.restTime) / float(dynamicTime); + if (decay < 0.0f) { + decay = 0.0f; + } + if (decay > 1.0f) { + decay = 1.0f; + } + float magicFactor8 = 1.0f; // Power for decay + decay = pow(decay, magicFactor8); + ragState = ERS_SETTLING; + if (frameNum > bone.restTime + settleTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { + bone.restTime = frameNum; + } else { // stop - bone.restTime=0; - ragState=ERS_SETTLED; + bone.restTime = 0; + ragState = ERS_SETTLED; } } -//decay=0.0f; - } - else - { - if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else if (ragOriginChange>15.0f) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else - { - ragState=ERS_SETTLED; - } - decay=0.0f; - } -// ragState=ERS_SETTLED; -// decay=0.0f; + // decay=0.0f; + } else { + if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else if (ragOriginChange > 15.0f) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else { + ragState = ERS_SETTLED; + } + decay = 0.0f; + } + // ragState=ERS_SETTLED; + // decay=0.0f; return decay; } -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered) -{ - int minSurvivingBone=10000; - //int minSurvivingBoneAt=-1; - int minSurvivingBoneAlt=10000; - //int minSurvivingBoneAtAlt=-1; +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered) { + int minSurvivingBone = 10000; + // int minSurvivingBoneAt=-1; + int minSurvivingBoneAlt = 10000; + // int minSurvivingBoneAtAlt=-1; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; - if(!rag) { - rag = new std::vector; + if (!rag) { + rag = new std::vector; } rag->clear(); - int numRendered=0; - int numNotRendered=0; - //int pelvisAt=-1; - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if ((bone.flags & BONE_ANGLES_RAGDOLL) || (bone.flags & BONE_ANGLES_IK)) { + // rww - this was (!anyRendered) before. Isn't that wrong? (if anyRendered, then wasRendered should be true) + bool wasRendered = (!anyRendered) || // offscreeen or something + G2_WasBoneRendered(ghoul2, bone.boneNumber); + if (!wasRendered) { + bone.RagFlags |= RAG_WAS_NOT_RENDERED; numNotRendered++; - } - else - { - bone.RagFlags&=~RAG_WAS_NOT_RENDERED; - bone.RagFlags|=RAG_WAS_EVER_RENDERED; + } else { + bone.RagFlags &= ~RAG_WAS_NOT_RENDERED; + bone.RagFlags |= RAG_WAS_EVER_RENDERED; numRendered++; } - if (bone.RagFlags&RAG_PCJ_PELVIS) - { - //pelvisAt=i; - } - else if (bone.RagFlags&RAG_PCJ_MODEL_ROOT) - { - } - else if (wasRendered && (bone.RagFlags&RAG_PCJ)) - { - if (minSurvivingBone>bone.boneNumber) - { - minSurvivingBone=bone.boneNumber; - //minSurvivingBoneAt=i; + if (bone.RagFlags & RAG_PCJ_PELVIS) { + // pelvisAt=i; + } else if (bone.RagFlags & RAG_PCJ_MODEL_ROOT) { + } else if (wasRendered && (bone.RagFlags & RAG_PCJ)) { + if (minSurvivingBone > bone.boneNumber) { + minSurvivingBone = bone.boneNumber; + // minSurvivingBoneAt=i; } - } - else if (wasRendered) - { - if (minSurvivingBoneAlt>bone.boneNumber) - { - minSurvivingBoneAlt=bone.boneNumber; - //minSurvivingBoneAtAlt=i; + } else if (wasRendered) { + if (minSurvivingBoneAlt > bone.boneNumber) { + minSurvivingBoneAlt = bone.boneNumber; + // minSurvivingBoneAtAlt=i; } } - if ( - anyRendered && - (bone.RagFlags&RAG_WAS_EVER_RENDERED) && - !(bone.RagFlags&RAG_PCJ_MODEL_ROOT) && - !(bone.RagFlags&RAG_PCJ_PELVIS) && - !wasRendered && - (bone.RagFlags&RAG_EFFECTOR) - ) - { + if (anyRendered && (bone.RagFlags & RAG_WAS_EVER_RENDERED) && !(bone.RagFlags & RAG_PCJ_MODEL_ROOT) && !(bone.RagFlags & RAG_PCJ_PELVIS) && + !wasRendered && (bone.RagFlags & RAG_EFFECTOR)) { // this thing was rendered in the past, but wasn't now, although other bones were, lets get rid of it -// bone.flags &= ~BONE_ANGLES_RAGDOLL; -// bone.RagFlags = 0; -//OutputDebugString(va("Deleted Effector %d\n",i)); -// continue; + // bone.flags &= ~BONE_ANGLES_RAGDOLL; + // bone.RagFlags = 0; + // OutputDebugString(va("Deleted Effector %d\n",i)); + // continue; } - if ((int)rag->size()resize(bone.boneNumber+1,0); + if ((int)rag->size() < bone.boneNumber + 1) { + rag->resize(bone.boneNumber + 1, 0); } - (*rag)[bone.boneNumber]=&bone; - ragBlistIndex[bone.boneNumber]=i; + (*rag)[bone.boneNumber] = &bone; + ragBlistIndex[bone.boneNumber] = i; - bone.lastTimeUpdated=frameNum; - if (resetOrigin) - { - VectorCopy(origin,bone.extraVec1); // this is only done incase a limb is removed + bone.lastTimeUpdated = frameNum; + if (resetOrigin) { + VectorCopy(origin, bone.extraVec1); // this is only done incase a limb is removed } } } @@ -2364,42 +1995,36 @@ static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,co } } #endif - numRags=0; - //int ragStartTime=0; - for(size_t i=0; isize(); i++) - { - if ((*rag)[i]) - { - boneInfo_t &bone=*(*rag)[i]; - assert(bone.boneNumber>=0); - assert(numRagssize(); i++) { + if ((*rag)[i]) { + boneInfo_t &bone = *(*rag)[i]; + assert(bone.boneNumber >= 0); + assert(numRags < MAX_BONES_RAG); + + // ragStartTime=bone.ragStartTime; + + bone.ragIndex = numRags; + ragBoneData[numRags] = &bone; + ragEffectors[numRags].radius = bone.radius; + ragEffectors[numRags].weight = bone.weight; + G2_GetBoneBasepose(ghoul2, bone.boneNumber, bone.basepose, bone.baseposeInv); numRags++; } } - if (!numRags) - { + if (!numRags) { return false; } return true; } -static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params, int curTime) -{ - if (!broadsword||!broadsword->integer) - { +static void G2_RagDoll(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params, int curTime) { + if (!broadsword || !broadsword->integer) { return; } - if (!params) - { + if (!params) { assert(0); return; } @@ -2410,9 +2035,9 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * dPos[2] -= 6; #endif -// params->DebugLine(handPos,handPos2,false); - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + // params->DebugLine(handPos,handPos2,false); + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; @@ -2449,23 +2074,19 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; // this loop checks for settled - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if (bone.flags & BONE_ANGLES_RAGDOLL) { // check for state transitions - decay=G2_RagSetState(ghoul2,bone,frameNum,dPos,resetOrigin); // set the current state - if (ragState==ERS_SETTLED) - { + decay = G2_RagSetState(ghoul2, bone, frameNum, dPos, resetOrigin); // set the current state + if (ragState == ERS_SETTLED) { #if 0 bool noneInSolid = true; @@ -2495,39 +2116,34 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * return; #endif } - if (G2_WasBoneRendered(ghoul2,bone.boneNumber)) - { - anyRendered=true; + if (G2_WasBoneRendered(ghoul2, bone.boneNumber)) { + anyRendered = true; break; } } } } - //int iters=(ragState==ERS_DYNAMIC)?2:1; - int iters=(ragState==ERS_DYNAMIC)?4:2; -/* - bool kicked=false; - if (ragOriginChangeDir[2]<-100.0f) - { - kicked=true; - //iters*=8; - iters*=5; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) - } -*/ - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,dPos,anyRendered)) + // int iters=(ragState==ERS_DYNAMIC)?2:1; + int iters = (ragState == ERS_DYNAMIC) ? 4 : 2; + /* + bool kicked=false; + if (ragOriginChangeDir[2]<-100.0f) { + kicked=true; + //iters*=8; + iters*=5; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) + } + */ + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, dPos, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (int i=0;iangles,dPos,params->scale); + for (int i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, dPos, params->scale); - if (G2_RagDollSettlePositionNumeroTrois(ghoul2V,dPos,params,curTime)) - { + if (G2_RagDollSettlePositionNumeroTrois(ghoul2V, dPos, params, curTime)) { #if 0 //effectors are start solid alot, so this was pretty extreme if (!kicked&&iters<4) @@ -2538,13 +2154,12 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif } - //params->position[2] += 16; - G2_RagDollSolve(ghoul2V,g2Index,decay*2.0f,frameNum,dPos,true,params); + // params->position[2] += 16; + G2_RagDollSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, dPos, true, params); } } - if (params->me != ENTITYNUM_NONE) - { + if (params->me != ENTITYNUM_NONE) { #if 0 vec3_t worldMins,worldMaxs; worldMins[0]=params->position[0]-17; @@ -2556,30 +2171,27 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * //OutputDebugString(va("%f \n",worldMins[2])); // params->DebugLine(worldMins,worldMaxs,true); #endif - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); -// SV_UnlinkEntity(params->me); -// params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); -// params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); -// SV_LinkEntity(params->me); + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); + // SV_UnlinkEntity(params->me); + // params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); + // params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); + // SV_LinkEntity(params->me); } } //#define _DEBUG_BONE_NAMES #ifdef _DEBUG_BONE_NAMES -static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); +static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; iragBoneMaxs[k]) - { - ragBoneMaxs[k]=ragEffectors[i].currentOrigin[k]; + + int k; + // float cmweight=ragEffectors[numRags].weight; + float cmweight = 1.0f; + for (k = 0; k < 3; k++) { + ragEffectors[i].currentOrigin[k] = ragBones[i].matrix[k][3]; + assert(!Q_isnan(ragEffectors[i].currentOrigin[k])); + if (!i) { + // set mins, maxs and cm + ragBoneCM[k] = ragEffectors[i].currentOrigin[k] * cmweight; + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; + ragBoneMins[k] = ragEffectors[i].currentOrigin[k]; + } else { + ragBoneCM[k] += ragEffectors[i].currentOrigin[k] * ragEffectors[i].weight; + if (ragEffectors[i].currentOrigin[k] > ragBoneMaxs[k]) { + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; } - if (ragEffectors[i].currentOrigin[k]0.0f); + assert(totalWt > 0.0f); int k; { - float wtInv=1.0f/totalWt; - for (k=0;k<3;k++) - { - ragBoneMaxs[k]-=position[k]; - ragBoneMins[k]-=position[k]; - ragBoneMaxs[k]+=10.0f; - ragBoneMins[k]-=10.0f; - ragBoneCM[k]*=wtInv; + float wtInv = 1.0f / totalWt; + for (k = 0; k < 3; k++) { + ragBoneMaxs[k] -= position[k]; + ragBoneMins[k] -= position[k]; + ragBoneMaxs[k] += 10.0f; + ragBoneMins[k] -= 10.0f; + ragBoneCM[k] *= wtInv; - ragBoneCM[k]=ragEffectors[0].currentOrigin[k]; // use the pelvis + ragBoneCM[k] = ragEffectors[0].currentOrigin[k]; // use the pelvis } } } -void VectorAdvance( const vec3_t veca, const float scale, const vec3_t vecb, vec3_t vecc); +void VectorAdvance(const vec3_t veca, const float scale, const vec3_t vecb, vec3_t vecc); #ifdef _DEBUG int ragTraceTime = 0; @@ -2671,8 +2274,8 @@ int ragSSCount = 0; int ragTraceCount = 0; #endif -void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) -{ +void Rag_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, + const EG2_Collision eG2TraceType, const int useLod) { #ifdef _DEBUG int ragPreTrace = ri.Milliseconds(); #endif @@ -2681,39 +2284,35 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v int ragPostTrace = ri.Milliseconds(); ragTraceTime += (ragPostTrace - ragPreTrace); - if (results->startsolid) - { + if (results->startsolid) { ragSSCount++; } ragTraceCount++; #endif } -//run advanced physics on each bone indivudually -//an adaption of my "exphys" custom game physics model -#define MAX_GRAVITY_PULL 256//512 +// run advanced physics on each bone indivudually +// an adaption of my "exphys" custom game physics model +#define MAX_GRAVITY_PULL 256 // 512 -static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) -{ +static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) { trace_t tr; vec3_t gSpot; VectorCopy(org, gSpot); - gSpot[2] -= 1.0f; //seems reasonable to me + gSpot[2] -= 1.0f; // seems reasonable to me Rag_Trace(&tr, org, mins, maxs, gSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) - { //not in solid, and hit something. Guess it's ground. + if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) { // not in solid, and hit something. Guess it's ground. return true; } return false; } -static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t goalBase, const vec3_t testMins, const vec3_t testMaxs, - const float gravity, const float mass, const float bounce) -{ +static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t goalBase, + const vec3_t testMins, const vec3_t testMaxs, const float gravity, const float mass, const float bounce) { trace_t tr; vec3_t projectedOrigin; vec3_t vNorm; @@ -2725,77 +2324,60 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR assert(mass <= 1.0f && mass >= 0.01f); - if (bone.physicsSettled) - { //then we have no need to continue + if (bone.physicsSettled) { // then we have no need to continue return true; } - if (goalBase) - { + if (goalBase) { VectorCopy(goalBase, usedOrigin); - } - else - { + } else { VectorCopy(e.currentOrigin, usedOrigin); } - if (gravity) - { //factor it in before we do anything. + if (gravity) { // factor it in before we do anything. VectorCopy(usedOrigin, ground); ground[2] -= 1.0f; Rag_Trace(&tr, usedOrigin, testMins, testMaxs, ground, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.entityNum == ENTITYNUM_NONE) - { + if (tr.entityNum == ENTITYNUM_NONE) { boneOnGround = false; - } - else - { + } else { boneOnGround = true; } - if (!boneOnGround) - { - if (!params->velocity[2]) - { //only increase gravitational pull once the actual entity is still + if (!boneOnGround) { + if (!params->velocity[2]) { // only increase gravitational pull once the actual entity is still bone.epGravFactor += gravity; } - if (bone.epGravFactor > MAX_GRAVITY_PULL) - { //cap it off if needed + if (bone.epGravFactor > MAX_GRAVITY_PULL) { // cap it off if needed bone.epGravFactor = MAX_GRAVITY_PULL; } bone.epVelocity[2] -= bone.epGravFactor; - } - else - { //if we're sitting on something then reset the gravity factor. + } else { // if we're sitting on something then reset the gravity factor. bone.epGravFactor = 0; } - } - else - { + } else { boneOnGround = G2_BoneOnGround(usedOrigin, testMins, testMaxs, params->me); } - if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) - { //nothing to do if we have no velocity even after gravity. + if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) { // nothing to do if we have no velocity even after gravity. VectorCopy(usedOrigin, goalSpot); return true; } - //get the projected origin based on velocity. + // get the projected origin based on velocity. VectorMA(usedOrigin, velScaling, bone.epVelocity, projectedOrigin); - //scale it down based on mass - VectorScale(bone.epVelocity, 1.0f-mass, bone.epVelocity); + // scale it down based on mass + VectorScale(bone.epVelocity, 1.0f - mass, bone.epVelocity); VectorCopy(bone.epVelocity, vNorm); vTotal = VectorNormalize(vNorm); - if (vTotal < 1 && boneOnGround) - { //we've pretty much stopped moving anyway, just clear it out then. + if (vTotal < 1 && boneOnGround) { // we've pretty much stopped moving anyway, just clear it out then. VectorClear(bone.epVelocity); bone.epGravFactor = 0; VectorCopy(usedOrigin, goalSpot); @@ -2804,52 +2386,44 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR Rag_Trace(&tr, usedOrigin, testMins, testMaxs, projectedOrigin, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.startsolid || tr.allsolid) - { //can't go anywhere from here + if (tr.startsolid || tr.allsolid) { // can't go anywhere from here return false; } - //Go ahead and set it to the trace endpoint regardless of what it hit + // Go ahead and set it to the trace endpoint regardless of what it hit VectorCopy(tr.endpos, goalSpot); - if (tr.fraction == 1.0f) - { //Nothing was in the way. + if (tr.fraction == 1.0f) { // Nothing was in the way. return true; } - if (bounce) - { - vTotal *= bounce; //scale it by bounce + if (bounce) { + vTotal *= bounce; // scale it by bounce - VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + VectorScale(tr.plane.normal, vTotal, vNorm); // scale the trace plane normal by the bounce factor - if (vNorm[2] > 0) - { - bone.epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. - if (bone.epGravFactor < 0) - { + if (vNorm[2] > 0) { + bone.epGravFactor -= vNorm[2] * (1.0f - mass); // The lighter it is the more gravity will be reduced by bouncing vertically. + if (bone.epGravFactor < 0) { bone.epGravFactor = 0; } } - VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); //add it into the existing velocity. + VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); // add it into the existing velocity. - //I suppose it could be sort of neat to make a game callback here to actual do stuff - //when bones slam into things. But it could be slow too. + // I suppose it could be sort of neat to make a game callback here to actual do stuff + // when bones slam into things. But it could be slow too. /* if (tr.entityNum != ENTITYNUM_NONE && ent->touch) { //then call the touch function ent->touch(ent, &g_entities[tr.entityNum], &tr); } */ - } - else - { //if no bounce, kill when it hits something. + } else { // if no bounce, kill when it hits something. bone.epVelocity[0] = 0; bone.epVelocity[1] = 0; - if (!gravity) - { + if (!gravity) { bone.epVelocity[2] = 0; } } @@ -2857,308 +2431,258 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR } #ifdef _DEBUG_BONE_NAMES -static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) -{ - return; //do something +static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) { + return; // do something } -static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) -{ - return; //do something +static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) { + return; // do something } #endif #ifdef _OLD_STYLE_SETTLE -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ - haveDesiredPelvisOffset=false; +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) { + haveDesiredPelvisOffset = false; vec3_t desiredPos; int i; assert(params); - //assert(params->me); //no longer valid, because me is an index! - int ignoreNum=params->me; + // assert(params->me); //no longer valid, because me is an index! + int ignoreNum = params->me; - bool anyStartSolid=false; + bool anyStartSolid = false; - vec3_t groundSpot={0,0,0}; + vec3_t groundSpot = {0, 0, 0}; // lets find the floor at our quake origin { vec3_t testStart; - VectorCopy(currentOrg,testStart); //last arg is dest + VectorCopy(currentOrg, testStart); // last arg is dest vec3_t testEnd; - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]-=200.0f; + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] -= 200.0f; vec3_t testMins; vec3_t testMaxs; - VectorSet(testMins,-10,-10,-10); - VectorSet(testMaxs,10,10,10); + VectorSet(testMins, -10, -10, -10); + VectorSet(testMaxs, 10, 10, 10); { - trace_t tr; - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0/*SV_TRACE_NO_PLAYER*/); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0 /*SV_TRACE_NO_PLAYER*/); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { - //hmmm, punt - VectorCopy(currentOrg,groundSpot); //last arg is dest - groundSpot[2]-=30.0f; - } - else - { - VectorCopy(tr.endpos,groundSpot); //last arg is dest + if (tr.startsolid) { + // hmmm, punt + VectorCopy(currentOrg, groundSpot); // last arg is dest + groundSpot[2] -= 30.0f; + } else { + VectorCopy(tr.endpos, groundSpot); // last arg is dest } } } - for (i=0;imBlist, bone.boneNumber); assert(debugBoneName); #endif // first we will see if we are start solid // if so, we are gonna run some bonus iterations - bool iAmStartSolid=false; + bool iAmStartSolid = false; vec3_t testStart; - VectorCopy(e.currentOrigin,testStart); //last arg is dest - testStart[2]+=12.0f; // we are no so concerned with minor penetration + VectorCopy(e.currentOrigin, testStart); // last arg is dest + testStart[2] += 12.0f; // we are no so concerned with minor penetration vec3_t testEnd; - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]-=8.0f; - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); - float vertEffectorTraceFraction=0.0f; + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] -= 8.0f; + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); + float vertEffectorTraceFraction = 0.0f; { - trace_t tr; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { + if (tr.startsolid) { // above the origin, so lets try lower - if (e.currentOrigin[2] > groundSpot[2]) - { - testStart[2]=groundSpot[2]+(e.radius-10.0f); - } - else - { + if (e.currentOrigin[2] > groundSpot[2]) { + testStart[2] = groundSpot[2] + (e.radius - 10.0f); + } else { // lets try higher - testStart[2]=groundSpot[2]+8.0f; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + testStart[2] = groundSpot[2] + 8.0f; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } } - } - if (tr.startsolid) - { - iAmStartSolid=true; - anyStartSolid=true; + if (tr.startsolid) { + iAmStartSolid = true; + anyStartSolid = true; // above the origin, so lets slide away - if (e.currentOrigin[2] > groundSpot[2]) - { - if (params) - { - SRagDollEffectorCollision args(e.currentOrigin,tr); + if (e.currentOrigin[2] > groundSpot[2]) { + if (params) { + SRagDollEffectorCollision args(e.currentOrigin, tr); params->EffectorCollision(args); } + } else { + // harumph, we are really screwed } - else - { - //harumph, we are really screwed - } - } - else - { - vertEffectorTraceFraction=tr.fraction; - if (params && - vertEffectorTraceFraction < .95f && - fabsf(tr.plane.normal[2]) < .707f) - { - SRagDollEffectorCollision args(e.currentOrigin,tr); - args.useTracePlane=true; + } else { + vertEffectorTraceFraction = tr.fraction; + if (params && vertEffectorTraceFraction < .95f && fabsf(tr.plane.normal[2]) < .707f) { + SRagDollEffectorCollision args(e.currentOrigin, tr); + args.useTracePlane = true; params->EffectorCollision(args); } } } vec3_t effectorGroundSpot; - VectorAdvance(testStart,vertEffectorTraceFraction,testEnd,effectorGroundSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorAdvance(testStart, vertEffectorTraceFraction, testEnd, effectorGroundSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // trace from the quake origin horzontally to the effector // gonna choose the maximum of the ground spot or the effector location // and clamp it to be roughly in the bbox - VectorCopy(groundSpot,testStart); //last arg is dest - if (iAmStartSolid) - { + VectorCopy(groundSpot, testStart); // last arg is dest + if (iAmStartSolid) { // we don't have a meaningful ground spot - VectorCopy(e.currentOrigin,testEnd); //last arg is dest + VectorCopy(e.currentOrigin, testEnd); // last arg is dest bone.solidCount++; - } - else - { - VectorCopy(effectorGroundSpot,testEnd); //last arg is dest + } else { + VectorCopy(effectorGroundSpot, testEnd); // last arg is dest bone.solidCount = 0; } - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); float ztest; - if (testEnd[2]>testStart[2]) - { - ztest=testEnd[2]; - } - else - { - ztest=testStart[2]; + if (testEnd[2] > testStart[2]) { + ztest = testEnd[2]; + } else { + ztest = testStart[2]; } - if (ztest c := (1-t)a+tb + float magicFactor44 = 1.0f; // going to trace a bit longer, this also serves as an expansion parameter + VectorAdvance(testStart, magicFactor44, testEnd, testEnd); // VA(a,t,b,c)-> c := (1-t)a+tb - float horzontalTraceFraction=0.0f; - vec3_t HorizontalHitSpot={0,0,0}; + float horzontalTraceFraction = 0.0f; + vec3_t HorizontalHitSpot = {0, 0, 0}; { - trace_t tr; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (tr.startsolid) - { - horzontalTraceFraction=1.0f; + horzontalTraceFraction = tr.fraction; + if (tr.startsolid) { + horzontalTraceFraction = 1.0f; // punt - VectorCopy(e.currentOrigin,HorizontalHitSpot); - } - else - { - VectorCopy(tr.endpos,HorizontalHitSpot); - int magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //rww - An..int? - VectorAdvance(tr.endpos,magicFactor46,testStart,HorizontalHitSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(e.currentOrigin, HorizontalHitSpot); + } else { + VectorCopy(tr.endpos, HorizontalHitSpot); + int magicFactor46 = 0.98f; // shorten percetage to make sure we can go down along a wall + // float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + // rww - An..int? + VectorAdvance(tr.endpos, magicFactor46, testStart, HorizontalHitSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // roughly speaking this is a wall - if (horzontalTraceFraction<0.9f) - { + if (horzontalTraceFraction < 0.9f) { // roughly speaking this is a wall - if (fabsf(tr.plane.normal[2])<0.7f) - { - SRagDollEffectorCollision args(e.currentOrigin,tr); - args.useTracePlane=true; + if (fabsf(tr.plane.normal[2]) < 0.7f) { + SRagDollEffectorCollision args(e.currentOrigin, tr); + args.useTracePlane = true; params->EffectorCollision(args); } - } - else if (!iAmStartSolid && - effectorGroundSpot[2] < groundSpot[2] - 8.0f) - { + } else if (!iAmStartSolid && effectorGroundSpot[2] < groundSpot[2] - 8.0f) { // this is a situation where we have something dangling below the pelvis, we want to find the plane going downhill away from the origin // for various reasons, without this correction the body will actually move away from places it can fall off. - //gotta run the trace backwards to get a plane + // gotta run the trace backwards to get a plane { - trace_t tr; - VectorCopy(effectorGroundSpot,testStart); - VectorCopy(groundSpot,testEnd); + trace_t tr; + VectorCopy(effectorGroundSpot, testStart); + VectorCopy(groundSpot, testEnd); // this can be a line trace, we just want the plane normal - Rag_Trace(&tr,testEnd,0,0,testStart,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + Rag_Trace(&tr, testEnd, 0, 0, testStart, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (!tr.startsolid && tr.fraction< 0.7f) - { - SRagDollEffectorCollision args(e.currentOrigin,tr); - args.useTracePlane=true; + horzontalTraceFraction = tr.fraction; + if (!tr.startsolid && tr.fraction < 0.7f) { + SRagDollEffectorCollision args(e.currentOrigin, tr); + args.useTracePlane = true; params->EffectorCollision(args); } } } } } - vec3_t goalSpot={0,0,0}; + vec3_t goalSpot = {0, 0, 0}; // now lets trace down - VectorCopy(HorizontalHitSpot,testStart); - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]=e.currentOrigin[2]-30.0f; + VectorCopy(HorizontalHitSpot, testStart); + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] = e.currentOrigin[2] - 30.0f; { - trace_t tr; - Rag_Trace(&tr,testStart,NULL,NULL,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, NULL, NULL, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { + if (tr.startsolid) { // punt, go to the origin I guess - VectorCopy(currentOrg,goalSpot); - } - else - { - VectorCopy(tr.endpos,goalSpot); - int magicFactor47=0.5f; // shorten percentage to make sure we can go down along a wall - VectorAdvance(tr.endpos,magicFactor47,testStart,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(currentOrg, goalSpot); + } else { + VectorCopy(tr.endpos, goalSpot); + int magicFactor47 = 0.5f; // shorten percentage to make sure we can go down along a wall + VectorAdvance(tr.endpos, magicFactor47, testStart, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb } } // ok now as the horizontal trace fraction approaches zero, we want to head toward the horizontalHitSpot - //geeze I would like some reasonable trace fractions - assert(horzontalTraceFraction>=0.0f&&horzontalTraceFraction<=1.0f); - VectorAdvance(HorizontalHitSpot,horzontalTraceFraction*horzontalTraceFraction,goalSpot,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + // geeze I would like some reasonable trace fractions + assert(horzontalTraceFraction >= 0.0f && horzontalTraceFraction <= 1.0f); + VectorAdvance(HorizontalHitSpot, horzontalTraceFraction * horzontalTraceFraction, goalSpot, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb #if 0 if ((bone.RagFlags & RAG_EFFECTOR) && (bone.RagFlags & RAG_BONE_LIGHTWEIGHT)) { //new rule - don't even bother unless it's a lightweight effector @@ -3212,22 +2736,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif int k; - int magicFactor12=0.8f; // dampening of velocity applied - int magicFactor16=10.0f; // effect multiplier of velocity applied + int magicFactor12 = 0.8f; // dampening of velocity applied + int magicFactor16 = 10.0f; // effect multiplier of velocity applied - if (iAmStartSolid) - { + if (iAmStartSolid) { magicFactor16 = 30.0f; } - for (k=0;k<3;k++) - { - e.desiredDirection[k]=goalSpot[k]-e.currentOrigin[k]; - e.desiredDirection[k]+=magicFactor16*bone.velocityEffector[k]; - e.desiredDirection[k]+=flrand(-0.75f,0.75f)*flrand(-0.75f,0.75f); - bone.velocityEffector[k]*=magicFactor12; + for (k = 0; k < 3; k++) { + e.desiredDirection[k] = goalSpot[k] - e.currentOrigin[k]; + e.desiredDirection[k] += magicFactor16 * bone.velocityEffector[k]; + e.desiredDirection[k] += flrand(-0.75f, 0.75f) * flrand(-0.75f, 0.75f); + bone.velocityEffector[k] *= magicFactor12; } - VectorCopy(e.currentOrigin,bone.lastPosition); // last arg is dest + VectorCopy(e.currentOrigin, bone.lastPosition); // last arg is dest } return anyStartSolid; } @@ -3248,36 +2770,33 @@ static inline int G2_RagIndexForBoneNum(int boneNum) } #endif -extern mdxaBone_t worldMatrix; +extern mdxaBone_t worldMatrix; void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale); void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame); -static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) -{ +static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) { static mdxaBone_t trueBaseMatrix, baseBoneMatrix; - //get matrix for the settleFrame to use as an ideal + // get matrix for the settleFrame to use as an ideal G2_RagGetAnimMatrix(ghoul2, bone.boneNumber, trueBaseMatrix, params->settleFrame); assert(bone.hasAnimFrameMatrix == params->settleFrame); - G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, - trueBaseMatrix, baseBoneMatrix, params->scale); + G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, trueBaseMatrix, baseBoneMatrix, params->scale); - //Use params to multiply world coordinate/dir matrix into the - //bone matrix and give us a useable world position + // Use params to multiply world coordinate/dir matrix into the + // bone matrix and give us a useable world position Multiply_3x4Matrix(&retMatrix, &worldMatrix, &baseBoneMatrix); assert(!Q_isnan(retMatrix.matrix[2][3])); } -//get the current pelvis Z direction and the base anim matrix Z direction -//so they can be compared and used to offset -rww -static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t &pos, vec3_t &dir, vec3_t &animPos, vec3_t &animDir) -{ +// get the current pelvis Z direction and the base anim matrix Z direction +// so they can be compared and used to offset -rww +static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t &pos, vec3_t &dir, vec3_t &animPos, vec3_t &animDir) { static mdxaBone_t final; static mdxaBone_t x; -// static mdxaBone_t *unused1, *unused2; - //static vec3_t lumbarPos; + // static mdxaBone_t *unused1, *unused2; + // static vec3_t lumbarPos; assert(ghoul2.animModel); int boneIndex = G2_Find_Bone(&ghoul2, ghoul2.mBlist, "pelvis"); @@ -3287,7 +2806,7 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd G2API_GiveMeVectorFromMatrix(final, ORIGIN, animPos); G2API_GiveMeVectorFromMatrix(final, POSITIVE_X, animDir); - //We have the anim matrix pelvis pos now, so get the normal one as well + // We have the anim matrix pelvis pos now, so get the normal one as well int bolt = G2API_AddBolt(&ghoul2, "pelvis"); G2_GetBoltMatrixLow(ghoul2, bolt, params->scale, x); Multiply_3x4Matrix(&final, &worldMatrix, &x); @@ -3314,8 +2833,8 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd */ } -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ //now returns true if any bone was in solid, otherwise false +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, + int curTime) { // now returns true if any bone was in solid, otherwise false int ignoreNum = params->me; static int i; static vec3_t goalSpot; @@ -3337,38 +2856,31 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve static bool hasBasePos; static vec3_t animPelvisDir, pelvisDir, animPelvisPos, pelvisPos; - //Maybe customize per-bone? + // Maybe customize per-bone? static const float gravity = 3.0f; static const float mass = 0.09f; - static const float bounce = 0.0f;//1.3f; - //Bouncing and stuff unfortunately does not work too well at the moment. - //Need to keep a seperate "physics origin" or make the filthy solve stuff - //better. + static const float bounce = 0.0f; // 1.3f; + // Bouncing and stuff unfortunately does not work too well at the moment. + // Need to keep a seperate "physics origin" or make the filthy solve stuff + // better. bool inAir = false; - if (params->velocity[0] || params->velocity[1] || params->velocity[2]) - { + if (params->velocity[0] || params->velocity[1] || params->velocity[2]) { inAir = true; } - if (!params->scale[0] && !params->scale[1] && !params->scale[2]) - { + if (!params->scale[0] && !params->scale[1] && !params->scale[2]) { VectorSet(entScale, 1.0f, 1.0f, 1.0f); - } - else - { + } else { VectorCopy(params->scale, entScale); } - if (broadsword_ragtobase && - broadsword_ragtobase->integer > 1) - { - //grab the pelvis directions to offset base positions for bones - G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, - animPelvisDir); + if (broadsword_ragtobase && broadsword_ragtobase->integer > 1) { + // grab the pelvis directions to offset base positions for bones + G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, animPelvisDir); - //don't care about the pitch offsets + // don't care about the pitch offsets pelvisDir[2] = 0; animPelvisDir[2] = 0; @@ -3382,24 +2894,21 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve params->DebugLine(animPelvisPos, blah, 0xff0000, false); */ - //just convert to angles now, that's all we'll ever use them for + // just convert to angles now, that's all we'll ever use them for vectoangles(pelvisDir, pelvisDir); vectoangles(animPelvisDir, animPelvisDir); } - for (i = 0; i < numRags; i++) - { + for (i = 0; i < numRags; i++) { boneInfo_t &bone = *ragBoneData[i]; SRagEffector &e = ragEffectors[i]; - if (inAir) - { + if (inAir) { bone.airTime = curTime + 30; } - if (bone.RagFlags & RAG_PCJ_PELVIS) - { - VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2]+DEFAULT_MINS_2)+((bone.radius*entScale[2])+2)); + if (bone.RagFlags & RAG_PCJ_PELVIS) { + VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2] + DEFAULT_MINS_2) + ((bone.radius * entScale[2]) + 2)); VectorSubtract(goalSpot, e.currentOrigin, desiredPelvisOffset); haveDesiredPelvisOffset = true; @@ -3407,17 +2916,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - if (!(bone.RagFlags & RAG_EFFECTOR)) - { + if (!(bone.RagFlags & RAG_EFFECTOR)) { continue; } - if (bone.hasOverGoal) - { //api call was made to override the goal spot + if (bone.hasOverGoal) { // api call was made to override the goal spot VectorCopy(bone.overGoalSpot, goalSpot); bone.solidCount = 0; - for (k = 0; k < 3; k++) - { + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); bone.velocityEffector[k] *= velocityDampening; @@ -3427,22 +2933,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - VectorSet(testMins, -e.radius*entScale[0], -e.radius*entScale[1], -e.radius*entScale[2]); - VectorSet(testMaxs, e.radius*entScale[0], e.radius*entScale[1], e.radius*entScale[2]); + VectorSet(testMins, -e.radius * entScale[0], -e.radius * entScale[1], -e.radius * entScale[2]); + VectorSet(testMaxs, e.radius * entScale[0], e.radius * entScale[1], e.radius * entScale[2]); assert(ghoul2V[0].mBoneCache); - //get the parent bone's position + // get the parent bone's position hasDaddy = false; - if (bone.boneNumber) - { + if (bone.boneNumber) { assert(ghoul2V[0].animModel); assert(ghoul2V[0].aHeader); - if (bone.parentBoneIndex == -1) - { - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; + if (bone.parentBoneIndex == -1) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; int bParentIndex, bParentListIndex = -1; offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); @@ -3450,67 +2954,56 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve bParentIndex = skel->parent; - while (bParentIndex > 0) - { //go upward through hierarchy searching for the first parent that is a rag bone + while (bParentIndex > 0) { // go upward through hierarchy searching for the first parent that is a rag bone skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bParentIndex]); bParentIndex = skel->parent; bParentListIndex = G2_Find_Bone(&ghoul2V[0], ghoul2V[0].mBlist, skel->name); - if (bParentListIndex != -1) - { + if (bParentListIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bParentListIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //valid rag bone + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // valid rag bone break; } } - //didn't work out, reset to -1 again + // didn't work out, reset to -1 again bParentListIndex = -1; } bone.parentBoneIndex = bParentListIndex; } - if (bone.parentBoneIndex != -1) - { + if (bone.parentBoneIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bone.parentBoneIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //has origin calculated for us already + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // has origin calculated for us already VectorCopy(ragEffectors[pbone.ragIndex].currentOrigin, parentOrigin); hasDaddy = true; } } } - //get the position this bone would be in if we were in the desired frame + // get the position this bone would be in if we were in the desired frame hasBasePos = false; - if (broadsword_ragtobase && - broadsword_ragtobase->integer) - { + if (broadsword_ragtobase && broadsword_ragtobase->integer) { vec3_t v, a; float f; G2_RagGetWorldAnimMatrix(ghoul2V[0], bone, params, worldBaseMatrix); G2API_GiveMeVectorFromMatrix(worldBaseMatrix, ORIGIN, basePos); - if (broadsword_ragtobase->integer > 1) - { - float fa = AngleNormalize180(animPelvisDir[YAW]-pelvisDir[YAW]); - float d = fa-bone.offsetRotation; + if (broadsword_ragtobase->integer > 1) { + float fa = AngleNormalize180(animPelvisDir[YAW] - pelvisDir[YAW]); + float d = fa - bone.offsetRotation; float tolerance = 16.0f; - if (d > tolerance || - d < -tolerance) - { //don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates + if (d > tolerance || d < -tolerance) { // don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis + // rotates bone.offsetRotation = fa; - } - else - { + } else { fa = bone.offsetRotation; } - //Rotate the point around the pelvis based on the offsets between pelvis positions + // Rotate the point around the pelvis based on the offsets between pelvis positions VectorSubtract(basePos, animPelvisPos, v); f = VectorLength(v); vectoangles(v, a); @@ -3519,14 +3012,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve VectorNormalize(v); VectorMA(animPelvisPos, f, v, basePos); - //re-orient the position of the bone to the current position of the pelvis + // re-orient the position of the bone to the current position of the pelvis VectorSubtract(basePos, animPelvisPos, v); - //push the spots outward? (to stretch the skeleton more) - //v[0] *= 1.5f; - //v[1] *= 1.5f; + // push the spots outward? (to stretch the skeleton more) + // v[0] *= 1.5f; + // v[1] *= 1.5f; VectorAdd(pelvisPos, v, basePos); } -#if 0 //for debugging frame skeleton +#if 0 // for debugging frame skeleton mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; @@ -3560,28 +3053,23 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve hasBasePos = true; } - //Are we in solid? - if (hasDaddy) - { + // Are we in solid? + if (hasDaddy) { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, parentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - //Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - } - else - { + // Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } else { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, params->position, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); } - - if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) - { //currently in solid, see what we can do about it + if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) { // currently in solid, see what we can do about it vec3_t vSub; startSolid = true; anySolid = true; - if (hasBasePos)// && bone.solidCount < 32) - { //only go to the base pos for slightly in solid bones -#if 0 //over-compensation + if (hasBasePos) // && bone.solidCount < 32) + { // only go to the base pos for slightly in solid bones +#if 0 // over-compensation float fl; float floorBase; @@ -3597,100 +3085,82 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #else VectorCopy(basePos, goalSpot); - goalSpot[2] = (params->position[2]-23)-testMins[2]; + goalSpot[2] = (params->position[2] - 23) - testMins[2]; #endif - //Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); - } - else - { //if deep in solid want to try to rise up out of solid before hinting back to base + // Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); + } else { // if deep in solid want to try to rise up out of solid before hinting back to base VectorSubtract(e.currentOrigin, params->position, vSub); VectorNormalize(vSub); VectorMA(params->position, 40.0f, vSub, goalSpot); - //should be 1 unit above the ground taking bounding box sizes into account - goalSpot[2] = (params->position[2]-23)-testMins[2]; + // should be 1 unit above the ground taking bounding box sizes into account + goalSpot[2] = (params->position[2] - 23) - testMins[2]; } - //Trace from the entity origin in the direction between the origin and current bone position to - //find a good eventual goal position + // Trace from the entity origin in the direction between the origin and current bone position to + // find a good eventual goal position Rag_Trace(&tr, params->position, testMins, testMaxs, goalSpot, params->me, RAG_MASK, G2_NOCOLLIDE, 0); VectorCopy(tr.endpos, goalSpot); - } - else - { + } else { startSolid = false; -#if 1 //do hinting? - //Hint the bone back to the base origin - if (hasDaddy || hasBasePos) - { - if (hasBasePos) - { +#if 1 // do hinting? + // Hint the bone back to the base origin + if (hasDaddy || hasBasePos) { + if (hasBasePos) { VectorSubtract(basePos, e.currentOrigin, velDir); - } - else - { + } else { VectorSubtract(e.currentOrigin, parentOrigin, velDir); } - } - else - { + } else { VectorSubtract(e.currentOrigin, params->position, velDir); } - if (VectorLength(velDir) > 2.0f) - { //don't bother if already close + if (VectorLength(velDir) > 2.0f) { // don't bother if already close VectorNormalize(velDir); VectorScale(velDir, 8.0f, velDir); - velDir[2] = 0; //don't want to nudge on Z, the gravity will take care of things. + velDir[2] = 0; // don't want to nudge on Z, the gravity will take care of things. VectorAdd(bone.epVelocity, velDir, bone.epVelocity); } #endif - //Factor the object's velocity into the bone's velocity, by pushing the bone - //opposite the velocity to give the apperance the lighter limbs are being "dragged" - //behind those of greater mass. - if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) - { + // Factor the object's velocity into the bone's velocity, by pushing the bone + // opposite the velocity to give the apperance the lighter limbs are being "dragged" + // behind those of greater mass. + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) { vec3_t vel; float vellen; VectorCopy(params->velocity, vel); - //Scale down since our velocity scale is different from standard game physics + // Scale down since our velocity scale is different from standard game physics VectorScale(vel, 0.5f, vel); vellen = VectorLength(vel); - if (vellen > 64.0f) - { //cap it off - VectorScale(vel, 64.0f/vellen, vel); + if (vellen > 64.0f) { // cap it off + VectorScale(vel, 64.0f / vellen, vel); } - //Invert the velocity so we go opposite the heavier parts and drag behind + // Invert the velocity so we go opposite the heavier parts and drag behind VectorInverse(vel); - if (vel[2]) - { //want to override entirely instead then + if (vel[2]) { // want to override entirely instead then VectorCopy(vel, bone.epVelocity); - } - else - { + } else { VectorAdd(bone.epVelocity, vel, bone.epVelocity); } } - //We're not in solid so we can apply physics freely now. - if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, NULL, testMins, testMaxs, - gravity, mass, bounce)) - { //if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin + // We're not in solid so we can apply physics freely now. + if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, NULL, testMins, testMaxs, gravity, mass, + bounce)) { // if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin VectorCopy(params->position, goalSpot); } } - //Set this now so we know what to do for angle limiting - if (startSolid) - { + // Set this now so we know what to do for angle limiting + if (startSolid) { bone.solidCount++; /* @@ -3708,19 +3178,17 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve Rag_Trace(&solidTr, params->position, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - if (solidTr.fraction != 1.0f && - (solidTr.plane.normal[0] || solidTr.plane.normal[1]) && - (solidTr.plane.normal[2] < 0.1f || solidTr.plane.normal[2] > -0.1f))// && //don't do anything against flat around + if (solidTr.fraction != 1.0f && (solidTr.plane.normal[0] || solidTr.plane.normal[1]) && + (solidTr.plane.normal[2] < 0.1f || solidTr.plane.normal[2] > -0.1f)) // && //don't do anything against flat around // e.currentOrigin[2] > pelvisPos[2]) - { //above pelvis, means not "even" with on ground level - SRagDollEffectorCollision args(e.currentOrigin,tr); + { // above pelvis, means not "even" with on ground level + SRagDollEffectorCollision args(e.currentOrigin, tr); args.useTracePlane = false; params->EffectorCollision(args); } #ifdef _DEBUG_BONE_NAMES - if (bone.solidCount > 64) - { + if (bone.solidCount > 64) { char *debugBoneName = G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber); vec3_t absmin, absmax; @@ -3735,14 +3203,12 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(e.currentOrigin, goalSpot, 50, 0x00ff00, 1); } #endif - } - else - { + } else { bone.solidCount = 0; } -#if 0 //standard goalSpot capping? - //unless we are really in solid, we should keep adjustments minimal +#if 0 // standard goalSpot capping? + // unless we are really in solid, we should keep adjustments minimal if (/*bone.epGravFactor < 64 &&*/ bone.solidCount < 2 && !inAir) { @@ -3761,24 +3227,19 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif - //params->DebugLine(e.currentOrigin, goalSpot, 0xff0000, false); + // params->DebugLine(e.currentOrigin, goalSpot, 0xff0000, false); - //Set the desired direction based on the goal position and other factors. - for (k = 0; k < 3; k++) - { + // Set the desired direction based on the goal position and other factors. + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); - if (broadsword_dircap && - broadsword_dircap->value) - { + if (broadsword_dircap && broadsword_dircap->value) { float cap = broadsword_dircap->value; - if (bone.solidCount > 5) - { - float solidFactor = bone.solidCount*0.2f; + if (bone.solidCount > 5) { + float solidFactor = bone.solidCount * 0.2f; - if (solidFactor > 16.0f) - { //don't go too high or something ugly might happen + if (solidFactor > 16.0f) { // don't go too high or something ugly might happen solidFactor = 16.0f; } @@ -3786,12 +3247,9 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve cap *= 8; } - if (e.desiredDirection[k] > cap) - { + if (e.desiredDirection[k] > cap) { e.desiredDirection[k] = cap; - } - else if (e.desiredDirection[k] < -cap) - { + } else if (e.desiredDirection[k] < -cap) { e.desiredDirection[k] = -cap; } } @@ -3808,23 +3266,18 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif -static float AngleNormZero(float theta) -{ - float ret=fmodf(theta,360.0f); - if (ret<-180.0f) - { - ret+=360.0f; +static float AngleNormZero(float theta) { + float ret = fmodf(theta, 360.0f); + if (ret < -180.0f) { + ret += 360.0f; + } else if (ret > 180.0f) { + ret -= 360.0f; } - else if (ret>180.0f) - { - ret-=360.0f; - } - assert(ret>=-180.0f&&ret<=180.0f); + assert(ret >= -180.0f && ret <= 180.0f); return ret; } -static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) -{ +static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) { /* if (!cgvm || !params) { @@ -3838,15 +3291,15 @@ static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDol VM_Call(cgvm, CG_RAG_CALLBACK, RAG_CALLBACK_BONESNAP); */ - //fixme: add params callback I suppose + // fixme: add params callback I suppose } -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool limitAngles,CRagDollUpdateParams *params) -{ +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool limitAngles, + CRagDollUpdateParams *params) { int i; - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; mdxaBone_t N; mdxaBone_t P; @@ -3860,89 +3313,82 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; - // END this is the objective function thing - for (i=0;igroundEnt != ENTITYNUM_NONE) @@ -3951,13 +3397,12 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f } */ - assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + assert(!Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); vec3_t deltaInEntitySpace; - TransformPoint(desiredPelvisOffset,deltaInEntitySpace,&N); // dest middle arg - for (k=0;k<3;k++) - { - float moveTo=bone.velocityRoot[k]+deltaInEntitySpace[k]*magicFactor13; - bone.velocityRoot[k]=(bone.velocityRoot[k]-moveTo)*magicFactor12+moveTo; + TransformPoint(desiredPelvisOffset, deltaInEntitySpace, &N); // dest middle arg + for (k = 0; k < 3; k++) { + float moveTo = bone.velocityRoot[k] + deltaInEntitySpace[k] * magicFactor13; + bone.velocityRoot[k] = (bone.velocityRoot[k] - moveTo) * magicFactor12 + moveTo; /* if (bone.velocityRoot[k]>50.0f) { @@ -3968,62 +3413,55 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f bone.velocityRoot[k]=-50.0f; } */ - //No -rww - bone.ragOverrideMatrix.matrix[k][3]=bone.velocityRoot[k]; + // No -rww + bone.ragOverrideMatrix.matrix[k][3] = bone.velocityRoot[k]; } } - } - else - { + } else { vec3_t delAngles; VectorClear(delAngles); - for (k=0;k<3;k++) - { - tAngles[k]+=0.5f; - Create_Matrix(tAngles,&temp2); //dest 2nd arg - tAngles[k]-=0.5f; - Multiply_3x4Matrix(&temp1,&P,&temp2); //dest first arg - Multiply_3x4Matrix(&Gs[k],&temp1,&N); //dest first arg - + for (k = 0; k < 3; k++) { + tAngles[k] += 0.5f; + Create_Matrix(tAngles, &temp2); // dest 2nd arg + tAngles[k] -= 0.5f; + Multiply_3x4Matrix(&temp1, &P, &temp2); // dest first arg + Multiply_3x4Matrix(&Gs[k], &temp1, &N); // dest first arg } - int allSolidCount = 0;//bone.solidCount; + int allSolidCount = 0; // bone.solidCount; // fixme precompute this - int numDep=G2_GetBoneDependents(ghoul2,bone.boneNumber,tempDependents,MAX_BONES_RAG); + int numDep = G2_GetBoneDependents(ghoul2, bone.boneNumber, tempDependents, MAX_BONES_RAG); int j; - int numRagDep=0; - for (j=0;jsize()&&(*rag)[tempDependents[j]])) - { + int numRagDep = 0; + for (j = 0; j < numDep; j++) { + // fixme why do this for the special roots? + if (!(tempDependents[j] < (int)rag->size() && (*rag)[tempDependents[j]])) { continue; } - int depIndex=(*rag)[tempDependents[j]]->ragIndex; - assert(depIndex>i); // these are supposed to be topologically sorted + int depIndex = (*rag)[tempDependents[j]]->ragIndex; + assert(depIndex > i); // these are supposed to be topologically sorted assert(ragBoneData[depIndex]); - boneInfo_t &depBone=*ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector + boneInfo_t &depBone = *ragBoneData[depIndex]; + if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } allSolidCount += depBone.solidCount; } @@ -4031,129 +3469,111 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f allSolidCount += bone.solidCount; - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9=0.75f; // dampfactor for angle changes - float magicFactor1=0.40f; //controls the speed of the gradient descent - float magicFactor32 = 1.5f; - float recip=0.0f; - if (numRagDep) - { - recip=sqrt(4.0f/float(numRagDep)); + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = 0.40f; // controls the speed of the gradient descent + float magicFactor32 = 1.5f; + float recip = 0.0f; + if (numRagDep) { + recip = sqrt(4.0f / float(numRagDep)); } - if (allSolidCount > 32) - { + if (allSolidCount > 32) { magicFactor1 = 0.6f; - } - else if (allSolidCount > 10) - { + } else if (allSolidCount > 10) { magicFactor1 = 0.5f; } - if (bone.overGradSpeed) - { //api call was made to specify a speed for this bone + if (bone.overGradSpeed) { // api call was made to specify a speed for this bone magicFactor1 = bone.overGradSpeed; } - float fac=decay*recip*magicFactor1; - assert(fac>=0.0f); + float fac = decay * recip * magicFactor1; + assert(fac >= 0.0f); #if 0 if (bone.RagFlags & RAG_PCJ_PELVIS) { magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable } #endif - if (ragState==ERS_DYNAMIC) - { - magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + if (ragState == ERS_DYNAMIC) { + magicFactor9 = .85f; // we don't want this swinging radically, make the whole thing kindof unstable } -#if 1 //constraint breaks? - if (bone.RagFlags & RAG_UNSNAPPABLE) - { +#if 1 // constraint breaks? + if (bone.RagFlags & RAG_UNSNAPPABLE) { magicFactor32 = 1.0f; } #endif - for (k=0;k<3;k++) - { - bone.currentAngles[k]+=delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k]=(bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; - bone.currentAngles[k]=AngleNormZero(bone.currentAngles[k]); + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); // bone.currentAngles[k]=flrand(bone.minAngles[k],bone.maxAngles[k]); -#if 1 //constraint breaks? - if (limitAngles && ( allSolidCount < 16 || (bone.RagFlags & RAG_UNSNAPPABLE) )) //16 tries and still in solid? Then we'll let you move freely +#if 1 // constraint breaks? + if (limitAngles && (allSolidCount < 16 || (bone.RagFlags & RAG_UNSNAPPABLE))) // 16 tries and still in solid? Then we'll let you move freely #else if (limitAngles) #endif { - if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) - { - //magicFactor32 += (allSolidCount/32); + if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) { + // magicFactor32 += (allSolidCount/32); - if (bone.currentAngles[k]>bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k]=bone.maxAngles[k]*magicFactor32; + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k]bone.maxAngles[k]*magicFactor32) - { + for (k = 0; k < 3; k++) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { isSnapped = true; break; } - if (bone.currentAngles[k]ragIndex; - if (!ragBoneData[depIndex]) - { + int depIndex = (*rag)[tempDependents[j]]->ragIndex; + if (!ragBoneData[depIndex]) { continue; } - boneInfo_t &depBone=*ragBoneData[depIndex]; + boneInfo_t &depBone = *ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) - { + if (depBone.RagFlags & RAG_EFFECTOR) { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } } } @@ -4276,222 +3684,174 @@ static void G2_IKSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameN VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9 = 0.75f; // dampfactor for angle changes - float magicFactor1 = bone.ikSpeed; //controls the speed of the gradient descent - float magicFactor32 = 1.0f; - float recip = 0.0f; - bool freeThisBone = false; + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = bone.ikSpeed; // controls the speed of the gradient descent + float magicFactor32 = 1.0f; + float recip = 0.0f; + bool freeThisBone = false; - if (!magicFactor1) - { + if (!magicFactor1) { magicFactor1 = 0.40f; } - recip = sqrt(4.0f/1.0f); + recip = sqrt(4.0f / 1.0f); - float fac = (decay*recip*magicFactor1); + float fac = (decay * recip * magicFactor1); assert(fac >= 0.0f); - if (ragState == ERS_DYNAMIC) - { + if (ragState == ERS_DYNAMIC) { magicFactor9 = 0.85f; // we don't want this swinging radically, make the whole thing kindof unstable } - - if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && - !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) - { + if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) { freeThisBone = true; } - for (k = 0; k < 3; k++) - { - bone.currentAngles[k] += delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k] = (bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); - if (limitAngles && !freeThisBone) - { - if (bone.currentAngles[k] > bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.maxAngles[k]*magicFactor32; + if (limitAngles && !freeThisBone) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k] < bone.minAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.minAngles[k]*magicFactor32; + if (bone.currentAngles[k] < bone.minAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.minAngles[k] * magicFactor32; } } } Create_Matrix(bone.currentAngles, &temp1); Multiply_3x4Matrix(&temp2, &temp1, bone.baseposeInv); Multiply_3x4Matrix(&bone.ragOverrideMatrix, bone.basepose, &temp2); - assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + assert(!Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); G2_Generate_MatrixRag(blist, ragBlistIndex[bone.boneNumber]); } } -static void G2_DoIK(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params) -{ +static void G2_DoIK(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params) { int i; - if (!params) - { + if (!params) { assert(0); return; } - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; - int iters = 12; //since we don't trace or anything, we can afford this. + int iters = 12; // since we don't trace or anything, we can afford this. - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,params->position,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, params->position, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (i=0;iangles,params->position,params->scale); + for (i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); G2_IKReposition(params->position, params); - G2_IKSolve(ghoul2V,g2Index,decay*2.0f,frameNum,params->position,true); + G2_IKSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, params->position, true); } } - if (params->me != ENTITYNUM_NONE) - { - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); + if (params->me != ENTITYNUM_NONE) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); } } -//rww - cut out the entire non-ragdoll section of this.. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index,CRagDollUpdateParams *params) -{ - bool anyRagDoll=false; +// rww - cut out the entire non-ragdoll section of this.. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index, CRagDollUpdateParams *params) { + bool anyRagDoll = false; bool anyIK = false; - for(size_t i=0; iangles, parms->position); @@ -4524,27 +3884,26 @@ void G2_InitIK(CGhoul2Info_v &ghoul2V, sharedRagDollUpdateParams_t *parms, int t G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); #endif - //Only need the standard effectors for this. - pcjFlags = RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rhand",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lhand",pcjFlags,6.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ceyebrow",pcjFlags,10.0f); + // Only need the standard effectors for this. + pcjFlags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rhand", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lhand", pcjFlags, 6.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ceyebrow", pcjFlags, 10.0f); } -qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ - model_t *mod_a; +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + model_t *mod_a; int g2index = 0; int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; @@ -4553,19 +3912,15 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName boneInfo_v &blist = g2.mBlist; mod_a = (model_t *)g2.animModel; - if (!boneName) - { //null bonename param means it's time to init the ik stuff on this instance + if (!boneName) { // null bonename param means it's time to init the ik stuff on this instance sharedRagDollUpdateParams_t sRDUP; - if (ikState == IKS_NONE) - { //this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags + if (ikState == IKS_NONE) { // this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags size_t i = 0; - while (i < blist.size()) - { //we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ - //limb after they reset it gameside, it's reasonable for IK bones. + while (i < blist.size()) { // we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ + // limb after they reset it gameside, it's reasonable for IK bones. boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1) - { + if (bone.boneNumber != -1) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -4577,8 +3932,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName } assert(params); - if (!params) - { + if (!params) { return qfalse; } @@ -4591,44 +3945,38 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } - if (!rmod_a || !mod_a) - { + if (!rmod_a || !mod_a) { return qfalse; } int index = G2_Find_Bone(&g2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index == -1) - { //couldn't find or add the bone.. + if (index == -1) { // couldn't find or add the bone.. return qfalse; } boneInfo_t &bone = blist[index]; - if (ikState == IKS_NONE) - { //remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since - //we don't store bone index handles gameside anywhere. - if (!(bone.flags & BONE_ANGLES_RAGDOLL)) - { //you can't set the ik state to none if it's not a rag/ik bone. + if (ikState == IKS_NONE) { // remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since + // we don't store bone index handles gameside anywhere. + if (!(bone.flags & BONE_ANGLES_RAGDOLL)) { // you can't set the ik state to none if it's not a rag/ik bone. return qfalse; } - //bone.flags = 0; - //G2_Remove_Bone_Index(blist, index); - //actually, I want to keep it on the rag list, and remove it as an IK bone instead. + // bone.flags = 0; + // G2_Remove_Bone_Index(blist, index); + // actually, I want to keep it on the rag list, and remove it as an IK bone instead. bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags |= BONE_ANGLES_IK; bone.RagFlags &= ~RAG_PCJ_IK_CONTROLLED; return qtrue; } - //need params if we're not resetting. - if (!params) - { + // need params if we're not resetting. + if (!params) { assert(0); return qfalse; } @@ -4639,7 +3987,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qfalse; } */ -#if 0 //this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's +#if 0 // this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's if (!(bone.flags & BONE_ANGLES_IK) && !(bone.flags & BONE_ANGLES_RAGDOLL)) { //IK system has not been inited yet, because any bone that can be IK should be in the ragdoll list, not flagged as BONE_ANGLES_RAGDOLL but as BONE_ANGLES_IK sharedRagDollUpdateParams_t sRDUP; @@ -4662,10 +4010,9 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); #endif - int pcjFlags = RAG_PCJ|RAG_PCJ_IK_CONTROLLED|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + int pcjFlags = RAG_PCJ | RAG_PCJ_IK_CONTROLLED | RAG_PCJ_POST_MULT | RAG_EFFECTOR; - if (params->pcjOverrides) - { + if (params->pcjOverrides) { pcjFlags = params->pcjOverrides; } @@ -4676,17 +4023,15 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName int startFrame = params->startFrame, endFrame = params->endFrame; - G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f, curTime, float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, float(startFrame), + 150, 0, true); G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); bone.lastTimeUpdated = 0; G2_Set_Bone_Angles_Rag(g2, rmod_a, blist, boneName, pcjFlags, params->radius, params->pcjMins, params->pcjMaxs, params->blendTime); - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { assert(!"failed to add any rag bones"); return qfalse; } @@ -4694,8 +4039,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } -qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { #if 0 model_t *mod_a; int g2index = 0; @@ -4736,17 +4080,15 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; - //rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { //changed models, possibly. + // rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { // changed models, possibly. return qfalse; } - for (int i=0;idesiredOrigin, bone.ikPosition); bone.ikSpeed = params->movementSpeed; @@ -4757,27 +4099,21 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params } // set the bone list to all unused so the bone transformation routine ignores it. -void G2_Init_Bone_List(boneInfo_v &blist, int numBones) -{ +void G2_Init_Bone_List(boneInfo_v &blist, int numBones) { blist.clear(); blist.reserve(numBones); } -int G2_Get_Bone_Index(CGhoul2Info *ghoul2, const char *boneName, qboolean bAddIfNotFound) -{ - if (bAddIfNotFound) - { +int G2_Get_Bone_Index(CGhoul2Info *ghoul2, const char *boneName, qboolean bAddIfNotFound) { + if (bAddIfNotFound) { return G2_Add_Bone(ghoul2->animModel, ghoul2->mBlist, boneName); - } - else - { + } else { return G2_Find_Bone(ghoul2, ghoul2->mBlist, boneName); } } -void G2_FreeRag(void) -{ - if(rag) { +void G2_FreeRag(void) { + if (rag) { delete rag; rag = NULL; } diff --git a/code/rd-vanilla/G2_misc.cpp b/code/rd-vanilla/G2_misc.cpp index bc5ca630a6..5499641939 100644 --- a/code/rd-vanilla/G2_misc.cpp +++ b/code/rd-vanilla/G2_misc.cpp @@ -23,26 +23,26 @@ along with this program; if not, see . #include "../server/exe_headers.h" #ifndef __Q_SHARED_H - #include "../qcommon/q_shared.h" +#include "../qcommon/q_shared.h" #endif #include "tr_common.h" #if !defined(TR_LOCAL_H) - #include "tr_local.h" +#include "tr_local.h" #endif #include "qcommon/matcomp.h" #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -#if !defined (MINIHEAP_H_INC) - #include "../qcommon/MiniHeap.h" +#if !defined(MINIHEAP_H_INC) +#include "../qcommon/MiniHeap.h" #endif -#define G2_MODEL_OK(g) ((g)&&(g)->mValid&&(g)->aHeader&&(g)->currentModel&&(g)->animModel) +#define G2_MODEL_OK(g) ((g) && (g)->mValid && (g)->aHeader && (g)->currentModel && (g)->animModel) #include "../server/server.h" @@ -56,233 +56,175 @@ along with this program; if not, see . #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) -static int CurrentTag=GORE_TAG_UPPER+1; -static int CurrentTagUpper=GORE_TAG_UPPER; +static int CurrentTag = GORE_TAG_UPPER + 1; +static int CurrentTagUpper = GORE_TAG_UPPER; -static std::map GoreRecords; -static std::map,int> GoreTagsTemp; // this is a surface index to gore tag map used only - // temporarily during the generation phase so we reuse gore tags per LOD +static std::map GoreRecords; +static std::map, int> GoreTagsTemp; // this is a surface index to gore tag map used only + // temporarily during the generation phase so we reuse gore tags per LOD int goreModelIndex; -static cvar_t *cg_g2MarksAllModels=NULL; +static cvar_t *cg_g2MarksAllModels = NULL; GoreTextureCoordinates *FindGoreRecord(int tag); -static inline void DestroyGoreTexCoordinates(int tag) -{ +static inline void DestroyGoreTexCoordinates(int tag) { GoreTextureCoordinates *gTC = FindGoreRecord(tag); - if (!gTC) - { + if (!gTC) { return; } (*gTC).~GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } -//TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all +// TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all #define MAX_GORE_RECORDS (500) -int AllocGoreRecord() -{ - while (GoreRecords.size()>MAX_GORE_RECORDS) - { - int tagHigh=(*GoreRecords.begin()).first&GORE_TAG_MASK; - std::map::iterator it; +int AllocGoreRecord() { + while (GoreRecords.size() > MAX_GORE_RECORDS) { + int tagHigh = (*GoreRecords.begin()).first & GORE_TAG_MASK; + std::map::iterator it; GoreTextureCoordinates *gTC; it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); - while (GoreRecords.size()) - { - if (((*GoreRecords.begin()).first&GORE_TAG_MASK)!=tagHigh) - { + while (GoreRecords.size()) { + if (((*GoreRecords.begin()).first & GORE_TAG_MASK) != tagHigh) { break; } it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); } } - int ret=CurrentTag; - GoreRecords[CurrentTag]=GoreTextureCoordinates(); + int ret = CurrentTag; + GoreRecords[CurrentTag] = GoreTextureCoordinates(); CurrentTag++; return ret; } -void ResetGoreTag() -{ +void ResetGoreTag() { GoreTagsTemp.clear(); - CurrentTag=CurrentTagUpper; - CurrentTagUpper+=GORE_TAG_UPPER; + CurrentTag = CurrentTagUpper; + CurrentTagUpper += GORE_TAG_UPPER; } -GoreTextureCoordinates *FindGoreRecord(int tag) -{ - std::map::iterator i=GoreRecords.find(tag); - if (i!=GoreRecords.end()) - { +GoreTextureCoordinates *FindGoreRecord(int tag) { + std::map::iterator i = GoreRecords.find(tag); + if (i != GoreRecords.end()) { return &(*i).second; } return 0; } -void *G2_GetGoreRecord(int tag) -{ - return FindGoreRecord(tag); -} +void *G2_GetGoreRecord(int tag) { return FindGoreRecord(tag); } -void DeleteGoreRecord(int tag) -{ +void DeleteGoreRecord(int tag) { DestroyGoreTexCoordinates(tag); GoreRecords.erase(tag); } -static int CurrentGoreSet=1; // this is a UUID for gore sets -static std::map GoreSets; // map from uuid to goreset +static int CurrentGoreSet = 1; // this is a UUID for gore sets +static std::map GoreSets; // map from uuid to goreset -CGoreSet *FindGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { +CGoreSet *FindGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { return (*f).second; } return 0; } -CGoreSet *NewGoreSet() -{ - CGoreSet *ret=new CGoreSet(CurrentGoreSet++); - GoreSets[ret->mMyGoreSetTag]=ret; +CGoreSet *NewGoreSet() { + CGoreSet *ret = new CGoreSet(CurrentGoreSet++); + GoreSets[ret->mMyGoreSetTag] = ret; ret->mRefCount = 1; return ret; } -void DeleteGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { - if ( (*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0 ) - { +void DeleteGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { + if ((*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0) { delete (*f).second; GoreSets.erase(f); - } - else - { + } else { (*f).second->mRefCount--; } } } - -CGoreSet::~CGoreSet() -{ - std::multimap::iterator i; - for (i=mGoreRecords.begin();i!=mGoreRecords.end();++i) - { +CGoreSet::~CGoreSet() { + std::multimap::iterator i; + for (i = mGoreRecords.begin(); i != mGoreRecords.end(); ++i) { DeleteGoreRecord((*i).second.mGoreTag); } }; #endif -extern mdxaBone_t worldMatrix; -extern mdxaBone_t worldMatrixInv; - -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache); -class CTraceSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - const model_t *currentModel; - const int lod; - vec3_t rayStart; - vec3_t rayEnd; - CCollisionRecord *collRecMap; - const int entNum; - const int modelIndex; - const skin_t *skin; - const shader_t *cust_shader; - intptr_t *TransformedVertsArray; - const EG2_Collision eG2TraceType; - bool hitOne; - float m_fRadius; +extern mdxaBone_t worldMatrix; +extern mdxaBone_t worldMatrixInv; + +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache); +class CTraceSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + const model_t *currentModel; + const int lod; + vec3_t rayStart; + vec3_t rayEnd; + CCollisionRecord *collRecMap; + const int entNum; + const int modelIndex; + const skin_t *skin; + const shader_t *cust_shader; + intptr_t *TransformedVertsArray; + const EG2_Collision eG2TraceType; + bool hitOne; + float m_fRadius; #ifdef _G2_GORE - //gore application thing - float ssize; - float tsize; - float theta; - int goreShader; - CGhoul2Info *ghoul2info; + // gore application thing + float ssize; + float tsize; + float theta; + int goreShader; + CGhoul2Info *ghoul2info; // Procedural-gore application things - SSkinGoreData *gore; + SSkinGoreData *gore; #endif - CTraceSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - const model_t *initcurrentModel, - int initlod, - vec3_t initrayStart, - vec3_t initrayEnd, - CCollisionRecord *initcollRecMap, - int initentNum, - int initmodelIndex, - const skin_t *initskin, - const shader_t *initcust_shader, - intptr_t *initTransformedVertsArray, - const EG2_Collision einitG2TraceType, + CTraceSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, const model_t *initcurrentModel, int initlod, vec3_t initrayStart, vec3_t initrayEnd, + CCollisionRecord *initcollRecMap, int initentNum, int initmodelIndex, const skin_t *initskin, const shader_t *initcust_shader, + intptr_t *initTransformedVertsArray, const EG2_Collision einitG2TraceType, #ifdef _G2_GORE - float fRadius, - float initssize, - float inittsize, - float inittheta, - int initgoreShader, - CGhoul2Info *initghoul2info, - SSkinGoreData *initgore + float fRadius, float initssize, float inittsize, float inittheta, int initgoreShader, CGhoul2Info *initghoul2info, SSkinGoreData *initgore #else - float fRadius + float fRadius #endif - ): - - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - currentModel(initcurrentModel), - lod(initlod), - collRecMap(initcollRecMap), - entNum(initentNum), - modelIndex(initmodelIndex), - skin(initskin), - cust_shader(initcust_shader), - TransformedVertsArray(initTransformedVertsArray), - eG2TraceType(einitG2TraceType), - hitOne(false), + ) + : + + surfaceNum(initsurfaceNum), rootSList(initrootSList), currentModel(initcurrentModel), lod(initlod), collRecMap(initcollRecMap), entNum(initentNum), + modelIndex(initmodelIndex), skin(initskin), cust_shader(initcust_shader), TransformedVertsArray(initTransformedVertsArray), + eG2TraceType(einitG2TraceType), hitOne(false), #ifdef _G2_GORE - m_fRadius(fRadius), - ssize(initssize), - tsize(inittsize), - theta(inittheta), - goreShader(initgoreShader), - ghoul2info(initghoul2info), - gore(initgore) + m_fRadius(fRadius), ssize(initssize), tsize(inittsize), theta(inittheta), goreShader(initgoreShader), ghoul2info(initghoul2info), gore(initgore) #else - m_fRadius(fRadius) + m_fRadius(fRadius) #endif - { + { VectorCopy(initrayStart, rayStart); VectorCopy(initrayEnd, rayEnd); } @@ -290,72 +232,62 @@ class CTraceSurface // assorted Ghoul 2 functions. // list all surfaces associated with a model -void G2_List_Model_Surfaces(const char *fileName) -{ - int i, x; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - mdxmSurfHierarchy_t *surf; +void G2_List_Model_Surfaces(const char *fileName) { + int i, x; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + mdxmSurfHierarchy_t *surf; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); mdxmSurface_t *surface = (mdxmSurface_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsLODs + sizeof(mdxmLOD_t)); - for ( x = 0 ; x < mod_m->mdxm->numSurfaces ; x++) - { + for (x = 0; x < mod_m->mdxm->numSurfaces; x++) { Com_Printf("Surface %i Name %s\n", x, surf->name); - if (r_verbose->value) - { - Com_Printf("Num Descendants %i\n", surf->numChildren); - for (i=0; inumChildren; i++) - { + if (r_verbose->value) { + Com_Printf("Num Descendants %i\n", surf->numChildren); + for (i = 0; i < surf->numChildren; i++) { Com_Printf("Descendant %i\n", surf->childIndexes[i]); } } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); - surface =(mdxmSurface_t *)( (byte *)surface + surface->ofsEnd ); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); + surface = (mdxmSurface_t *)((byte *)surface + surface->ofsEnd); } - } // list all bones associated with a model -void G2_List_Model_Bones(const char *fileName, int frame) -{ - int x, i; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); -// mdxaFrame_t *aframe=0; -// int frameSize; - mdxaHeader_t *header = mod_a->mdxa; +void G2_List_Model_Bones(const char *fileName, int frame) { + int x, i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + // mdxaFrame_t *aframe=0; + // int frameSize; + mdxaHeader_t *header = mod_a->mdxa; // figure out where the offset list is offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); -// frameSize = (int)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); + // frameSize = (int)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); -// aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); + // aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); // walk each bone and list it's name - for (x=0; x< mod_a->mdxa->numBones; x++) - { + for (x = 0; x < mod_a->mdxa->numBones; x++) { skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[x]); Com_Printf("Bone %i Name %s\n", x, skel->name); Com_Printf("X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); // if we are in verbose mode give us more details - if (r_verbose->value) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); - for (i=0; inumChildren; i++) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); + if (r_verbose->value) { + Com_Printf("Num Descendants %i\n", skel->numChildren); + for (i = 0; i < skel->numChildren; i++) { + Com_Printf("Num Descendants %i\n", skel->numChildren); } } } } - /************************************************************************************************ * G2_GetAnimFileName * obtain the .gla filename for a model @@ -367,104 +299,93 @@ void G2_List_Model_Bones(const char *fileName, int frame) * true if we successfully obtained a filename, false otherwise * ************************************************************************************************/ -qboolean G2_GetAnimFileName(const char *fileName, char **filename) -{ +qboolean G2_GetAnimFileName(const char *fileName, char **filename) { // find the model we want - model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); - if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) - { + if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) { *filename = mod->mdxm->animName; return qtrue; } return qfalse; } - ///////////////////////////////////////////////////////////////////// // // Code for collision detection for models gameside // ///////////////////////////////////////////////////////////////////// -int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) -{ +int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) { int returnLod = useLod; - // if we are overriding the LOD at top level, then we can afford to only check this level of model - if (ghoul2.mLodBias > returnLod) - { - returnLod = ghoul2.mLodBias; - } + // if we are overriding the LOD at top level, then we can afford to only check this level of model + if (ghoul2.mLodBias > returnLod) { + returnLod = ghoul2.mLodBias; + } assert(G2_MODEL_OK(&ghoul2)); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - //what about r_lodBias? + // what about r_lodBias? // now ensure that we haven't selected a lod that doesn't exist for this model - if ( returnLod >= ghoul2.currentModel->mdxm->numLODs ) - { - returnLod = ghoul2.currentModel->mdxm->numLODs - 1; - } + if (returnLod >= ghoul2.currentModel->mdxm->numLODs) { + returnLod = ghoul2.currentModel->mdxm->numLODs - 1; + } return returnLod; } -void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, CMiniHeap *G2VertSpace, intptr_t *TransformedVertsArray,CBoneCache *boneCache) -{ - int j, k; - mdxmVertex_t *v; - float *TransformedVerts; +void R_TransformEachSurface(const mdxmSurface_t *surface, vec3_t scale, CMiniHeap *G2VertSpace, intptr_t *TransformedVertsArray, CBoneCache *boneCache) { + int j, k; + mdxmVertex_t *v; + float *TransformedVerts; // // deform the vertexes by the lerped bones // - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); // alloc some space for the transformed verts to get put in TransformedVerts = (float *)G2VertSpace->MiniHeapAlloc(surface->numVerts * 5 * 4); TransformedVertsArray[surface->thisSurfaceIndex] = (intptr_t)TransformedVerts; - if (!TransformedVerts) - { + if (!TransformedVerts) { assert(TransformedVerts); Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust G2_MINIHEAP_SIZE in sv_init.cpp.\n"); } // whip through and actually transform each vertex const int numVerts = surface->numVerts; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // optimisation issue - if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) - { - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// mdxmWeight_t *w; + if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) { + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } int pos = j * 5; @@ -476,38 +397,34 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, CMiniHe TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } - } - else - { + } else { int pos = 0; - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// const mdxmWeight_t *w; + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // const mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } // copy tranformed verts into temp space @@ -518,48 +435,43 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, CMiniHe TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos++] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } } } -void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, CMiniHeap *G2VertSpace, intptr_t *TransformedVertArray, bool secondTimeAround) -{ - int i; +void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, + CMiniHeap *G2VertSpace, intptr_t *TransformedVertArray, bool secondTimeAround) { + int i; assert(currentModel); assert(currentModel->mdxm); // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(currentModel, surfaceNum, lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(currentModel, surfaceNum, lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { + if (!offFlags) { R_TransformEachSurface(surface, scale, G2VertSpace, TransformedVertArray, boneCache); } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { G2_TransformSurfaces(surfInfo->childIndexes[i], rootSList, boneCache, currentModel, lod, scale, G2VertSpace, TransformedVertArray, secondTimeAround); } } @@ -571,56 +483,46 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, CMiniHeap *G2VertSpace, int useLod) #endif { - int i, lod; - vec3_t correctScale; + int i, lod; + vec3_t correctScale; #if !defined(JK2_MODE) || defined(_G2_GORE) - qboolean firstModelOnly = qfalse; + qboolean firstModelOnly = qfalse; #endif // !JK2_MODE || _G2_GORE #ifndef JK2_MODE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0 ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif // !JK2_MODE #ifdef _G2_GORE - if ( gore - && gore->firstModel > 0 ) - { + if (gore && gore->firstModel > 0) { firstModelOnly = qfalse; } #endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe - if (!scale[0]) - { + if (!scale[0]) { correctScale[0] = 1.0; } - if (!scale[1]) - { + if (!scale[1]) { correctScale[1] = 1.0; } - if (!scale[2]) - { + if (!scale[2]) { correctScale[2] = 1.0; } // walk each possible model for this entity and try rendering it out - for (i=0; i=g.currentModel->numLods) - { + if (lod >= g.currentModel->numLods) { g.mTransformedVertsArray = 0; - if ( firstModelOnly ) - { + if (firstModelOnly) { // we don't really need to do multiple models for gore. return; } - //do the rest + // do the rest continue; } - } - else + } else #endif { lod = G2_DecideTraceLod(g, useLod); } // give us space for the transformed vertex array to be put in - g.mTransformedVertsArray = (intptr_t *)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof (intptr_t)); - if (!g.mTransformedVertsArray) - { + g.mTransformedVertsArray = (intptr_t *)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof(intptr_t)); + if (!g.mTransformedVertsArray) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust G2_MINIHEAP_SIZE in sv_init.cpp.\n"); } - memset(g.mTransformedVertsArray, 0,(g.currentModel->mdxm->numSurfaces * sizeof (intptr_t))); + memset(g.mTransformedVertsArray, 0, (g.currentModel->mdxm->numSurfaces * sizeof(intptr_t))); - G2_FindOverrideSurface(-1,g.mSlist); //reset the quick surface override lookup; + G2_FindOverrideSurface(-1, g.mSlist); // reset the quick surface override lookup; // recursively call the model surface transform - G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); + G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); #ifdef _G2_GORE - if (ApplyGore && firstModelOnly ) - { + if (ApplyGore && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -676,11 +572,9 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, } } - // work out how much space a triangle takes -static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) -{ - vec3_t cross, ab, cb; +static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) { + vec3_t cross, ab, cb; VectorSubtract(A, B, ab); VectorSubtract(C, B, cb); @@ -690,43 +584,34 @@ static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) } // actually determine the S and T of the coordinate we hit in a given poly -static void G2_BuildHitPointST( const vec3_t A, const float SA, const float TA, - const vec3_t B, const float SB, const float TB, - const vec3_t C, const float SC, const float TC, - const vec3_t P, float *s, float *t,float &bary_i,float &bary_j) -{ - float areaABC = G2_AreaOfTri(A, B, C); +static void G2_BuildHitPointST(const vec3_t A, const float SA, const float TA, const vec3_t B, const float SB, const float TB, const vec3_t C, const float SC, + const float TC, const vec3_t P, float *s, float *t, float &bary_i, float &bary_j) { + float areaABC = G2_AreaOfTri(A, B, C); float i = G2_AreaOfTri(P, B, C) / areaABC; - bary_i=i; + bary_i = i; float j = G2_AreaOfTri(A, P, C) / areaABC; - bary_j=j; + bary_j = j; float k = G2_AreaOfTri(A, B, P) / areaABC; *s = SA * i + SB * j + SC * k; *t = TA * i + TB * j + TC * k; - *s=fmod(*s, 1); - if (*s< 0) - { - *s+= 1.0; + *s = fmod(*s, 1); + if (*s < 0) { + *s += 1.0; } - *t=fmod(*t, 1); - if (*t< 0) - { - *t+= 1.0; + *t = fmod(*t, 1); + if (*t < 0) { + *t += 1.0; } - } - // routine that works out given a ray whether or not it hits a poly -static inline qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, - const vec3_t A, const vec3_t B, const vec3_t C, - qboolean backFaces,qboolean frontFaces,vec3_t returnedPoint,vec3_t returnedNormal, float *denom) -{ - static const float tiny=1E-10f; +static inline qboolean G2_SegmentTriangleTest(const vec3_t start, const vec3_t end, const vec3_t A, const vec3_t B, const vec3_t C, qboolean backFaces, + qboolean frontFaces, vec3_t returnedPoint, vec3_t returnedNormal, float *denom) { + static const float tiny = 1E-10f; vec3_t returnedNormalT; vec3_t edgeAC; @@ -738,11 +623,11 @@ static inline qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t vec3_t ray; VectorSubtract(end, start, ray); - *denom=DotProduct(ray, returnedNormal); + *denom = DotProduct(ray, returnedNormal); - if (Q_fabs(*denom)0)|| // not accepting back faces - (!frontFaces && *denom<0)) //not accepting front faces + if (Q_fabs(*denom) < tiny || // triangle parallel to ray + (!backFaces && *denom > 0) || // not accepting back faces + (!frontFaces && *denom < 0)) // not accepting front faces { return qfalse; } @@ -750,10 +635,9 @@ static inline qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t vec3_t toPlane; VectorSubtract(A, start, toPlane); - float t=DotProduct(toPlane, returnedNormal)/ *denom; + float t = DotProduct(toPlane, returnedNormal) / *denom; - if (t<0.0f||t>1.0f) - { + if (t < 0.0f || t > 1.0f) { return qfalse; // off segment } @@ -773,345 +657,295 @@ static inline qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t vec3_t temp; CrossProduct(edgePA, edgePB, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePC, edgePA, temp); - if (DotProduct(temp,returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePB, edgePC, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } return qtrue; } #ifdef _G2_GORE -struct SVertexTemp -{ +struct SVertexTemp { int flags; int touch; int newindex; float tex[2]; - SVertexTemp() - { - touch=0; - } + SVertexTemp() { touch = 0; } }; #define MAX_GORE_VERTS (3000) static SVertexTemp GoreVerts[MAX_GORE_VERTS]; static int GoreIndexCopy[MAX_GORE_VERTS]; -static int GoreTouch=1; +static int GoreTouch = 1; #define MAX_GORE_INDECIES (6000) static int GoreIndecies[MAX_GORE_INDECIES]; #define GORE_MARGIN (0.0f) -int G2API_GetTime(int argTime); +int G2API_GetTime(int argTime); // now we at poly level, check each model space transformed poly against the model world transfomed ray -static void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) -{ - int j; +static void G2_GorePolys(const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - if (!TS.gore) - { + if (!TS.gore) { return; } - if (!TS.gore->useTheta) - { - VectorCopy(TS.gore->uaxis,basis2); - CrossProduct(TS.rayEnd,basis2,basis1); - if (DotProduct(basis1,basis1)<0.005f) - { //shot dir and slash dir are too close + if (!TS.gore->useTheta) { + VectorCopy(TS.gore->uaxis, basis2); + CrossProduct(TS.rayEnd, basis2, basis1); + if (DotProduct(basis1, basis1) < 0.005f) { // shot dir and slash dir are too close return; } } - if (TS.gore->useTheta) - { - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + if (TS.gore->useTheta) { + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + CrossProduct(TS.rayEnd, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(TS.rayEnd, basis2, basis1); } - CrossProduct(TS.rayEnd,basis1,basis2); + CrossProduct(TS.rayEnd, basis1, basis2); } // Give me a shot direction not a bunch of zeros :) -Gil - assert(DotProduct(basis1,basis1)>.0001f); - assert(DotProduct(basis2,basis2)>.0001f); + assert(DotProduct(basis1, basis1) > .0001f); + assert(DotProduct(basis2, basis2) > .0001f); VectorNormalize(basis1); VectorNormalize(basis2); - float c=cos(TS.theta); - float s=sin(TS.theta); + float c = cos(TS.theta); + float s = sin(TS.theta); - VectorScale(basis1,.5f*c/TS.tsize,taxis); - VectorMA(taxis,.5f*s/TS.tsize,basis2,taxis); + VectorScale(basis1, .5f * c / TS.tsize, taxis); + VectorMA(taxis, .5f * s / TS.tsize, basis2, taxis); - VectorScale(basis1,-.5f*s/TS.ssize,saxis); - VectorMA(saxis,.5f*c/TS.ssize,basis2,saxis); + VectorScale(basis1, -.5f * s / TS.ssize, saxis); + VectorMA(saxis, .5f * c / TS.ssize, basis2, saxis); - //fixme, everything above here should be pre-calculated in G2API_AddSkinGore + // fixme, everything above here should be pre-calculated in G2API_AddSkinGore float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; int numVerts = surface->numVerts; - int flags=63; - assert(numVertsGORE_MARGIN) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + float s = DotProduct(delta, saxis) + 0.5f; + float t = DotProduct(delta, taxis) + 0.5f; + float depth = DotProduct(delta, TS.rayEnd); + int vflags = 0; + if (s > GORE_MARGIN) { + vflags |= 1; } - if (s<1.0f-GORE_MARGIN) - { - vflags|=2; + if (s < 1.0f - GORE_MARGIN) { + vflags |= 2; } - if (t>GORE_MARGIN) - { - vflags|=4; + if (t > GORE_MARGIN) { + vflags |= 4; } - if (t<1.0f-GORE_MARGIN) - { - vflags|=8; + if (t < 1.0f - GORE_MARGIN) { + vflags |= 8; } - if (depth > TS.gore->depthStart) - { - vflags|=16; + if (depth > TS.gore->depthStart) { + vflags |= 16; } - if (depth < TS.gore->depthEnd) - { - vflags|=32; + if (depth < TS.gore->depthEnd) { + vflags |= 32; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; - GoreVerts[j].tex[0]=s; - GoreVerts[j].tex[1]=t; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; + GoreVerts[j].tex[0] = s; + GoreVerts[j].tex[1] = t; } - if (flags) - { + if (flags) { return; // completely off the gore splotch. } - int numTris,newNumTris,newNumVerts; + int numTris, newNumTris, newNumVerts; numTris = surface->numTriangles; - mdxmTriangle_t *tris; - tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + mdxmTriangle_t *tris; + tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; - newNumTris=0; - newNumVerts=0; + newNumTris = 0; + newNumVerts = 0; GoreTouch++; - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 63 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; + if (flags) { continue; } - if (!TS.gore->frontFaces || !TS.gore->backFaces) - { + if (!TS.gore->frontFaces || !TS.gore->backFaces) { // we need to back/front face cull - vec3_t e1,e2,n; + vec3_t e1, e2, n; - VectorSubtract(&verts[tris[j].indexes[1]*5],&verts[tris[j].indexes[0]*5],e1); - VectorSubtract(&verts[tris[j].indexes[2]*5],&verts[tris[j].indexes[0]*5],e2); - CrossProduct(e1,e2,n); - if (DotProduct(TS.rayEnd,n)>0.0f) - { - if (!TS.gore->frontFaces) - { + VectorSubtract(&verts[tris[j].indexes[1] * 5], &verts[tris[j].indexes[0] * 5], e1); + VectorSubtract(&verts[tris[j].indexes[2] * 5], &verts[tris[j].indexes[0] * 5], e2); + CrossProduct(e1, e2, n); + if (DotProduct(TS.rayEnd, n) > 0.0f) { + if (!TS.gore->frontFaces) { continue; } - } - else - { - if (!TS.gore->backFaces) - { + } else { + if (!TS.gore->backFaces) { continue; } } - } int k; - assert(newNumTris*3+3,int>::iterator f=GoreTagsTemp.find(std::make_pair(goreModelIndex,TS.surfaceNum)); - if (f==GoreTagsTemp.end()) // need to generate a record + std::map, int>::iterator f = GoreTagsTemp.find(std::make_pair(goreModelIndex, TS.surfaceNum)); + if (f == GoreTagsTemp.end()) // need to generate a record { - newTag=AllocGoreRecord(); - CGoreSet *goreSet=0; - if (TS.ghoul2info->mGoreSetTag) - { - goreSet=FindGoreSet(TS.ghoul2info->mGoreSetTag); + newTag = AllocGoreRecord(); + CGoreSet *goreSet = 0; + if (TS.ghoul2info->mGoreSetTag) { + goreSet = FindGoreSet(TS.ghoul2info->mGoreSetTag); } - if (!goreSet) - { - goreSet=NewGoreSet(); - TS.ghoul2info->mGoreSetTag=goreSet->mMyGoreSetTag; + if (!goreSet) { + goreSet = NewGoreSet(); + TS.ghoul2info->mGoreSetTag = goreSet->mMyGoreSetTag; } assert(goreSet); SGoreSurface add; - add.shader=TS.goreShader; - add.mDeleteTime=0; - if (TS.gore->lifeTime) - { - add.mDeleteTime=G2API_GetTime(0) + TS.gore->lifeTime; + add.shader = TS.goreShader; + add.mDeleteTime = 0; + if (TS.gore->lifeTime) { + add.mDeleteTime = G2API_GetTime(0) + TS.gore->lifeTime; } add.mFadeTime = TS.gore->fadeOutTime; add.mFadeRGB = TS.gore->fadeRGB; add.mGoreTag = newTag; - add.mGoreGrowStartTime=G2API_GetTime(0); - if( TS.gore->growDuration == -1) - { - add.mGoreGrowEndTime = -1; // set this to -1 to disable growing - } - else - { + add.mGoreGrowStartTime = G2API_GetTime(0); + if (TS.gore->growDuration == -1) { + add.mGoreGrowEndTime = -1; // set this to -1 to disable growing + } else { add.mGoreGrowEndTime = G2API_GetTime(0) + TS.gore->growDuration; } assert(TS.gore->growDuration != 0); - add.mGoreGrowFactor = ( 1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); //curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; + add.mGoreGrowFactor = + (1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); // curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; - goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum,add)); - GoreTagsTemp[std::make_pair(goreModelIndex,TS.surfaceNum)]=newTag; - } - else - { - newTag=(*f).second; + goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum, add)); + GoreTagsTemp[std::make_pair(goreModelIndex, TS.surfaceNum)] = newTag; + } else { + newTag = (*f).second; } - GoreTextureCoordinates *gore=FindGoreRecord(newTag); - if (gore) - { - assert(sizeof(float)==sizeof(int)); + GoreTextureCoordinates *gore = FindGoreRecord(newTag); + if (gore) { + assert(sizeof(float) == sizeof(int)); // data block format: - unsigned int size= - sizeof(int)+ // num verts - sizeof(int)+ // num tris - sizeof(int)*newNumVerts+ // which verts to copy from original surface - sizeof(float)*4*newNumVerts+ // storgage for deformed verts - sizeof(float)*4*newNumVerts+ // storgage for deformed normal - sizeof(float)*2*newNumVerts+ // texture coordinates - sizeof(int)*newNumTris*3; // new indecies - - int *data=(int *)R_Malloc ( sizeof(int)*size, TAG_GHOUL2, qtrue ); - - if ( gore->tex[TS.lod] ) + unsigned int size = sizeof(int) + // num verts + sizeof(int) + // num tris + sizeof(int) * newNumVerts + // which verts to copy from original surface + sizeof(float) * 4 * newNumVerts + // storgage for deformed verts + sizeof(float) * 4 * newNumVerts + // storgage for deformed normal + sizeof(float) * 2 * newNumVerts + // texture coordinates + sizeof(int) * newNumTris * 3; // new indecies + + int *data = (int *)R_Malloc(sizeof(int) * size, TAG_GHOUL2, qtrue); + + if (gore->tex[TS.lod]) R_Free(gore->tex[TS.lod]); - gore->tex[TS.lod]=(float *)data; - *data++=newNumVerts; - *data++=newNumTris; + gore->tex[TS.lod] = (float *)data; + *data++ = newNumVerts; + *data++ = newNumTris; - memcpy(data,GoreIndexCopy,sizeof(int)*newNumVerts); - data+=newNumVerts*9; // skip verts and normals - float *fdata=(float *)data; + memcpy(data, GoreIndexCopy, sizeof(int) * newNumVerts); + data += newNumVerts * 9; // skip verts and normals + float *fdata = (float *)data; - for (j=0;jtex[TS.lod])*sizeof(int)==size); + data = (int *)fdata; + memcpy(data, GoreIndecies, sizeof(int) * newNumTris * 3); + data += newNumTris * 3; + assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); fdata = (float *)data; // build the entity to gore matrix - VectorCopy(saxis,fdata+0); - VectorCopy(taxis,fdata+4); - VectorCopy(TS.rayEnd,fdata+8); - VectorNormalize(fdata+0); - VectorNormalize(fdata+4); - VectorNormalize(fdata+8); - fdata[3]=-0.5f; // subtract texture center - fdata[7]=-0.5f; - fdata[11]=0.0f; - vec3_t shotOriginInCurrentSpace; // unknown space - TransformPoint(TS.rayStart,shotOriginInCurrentSpace,(mdxaBone_t *)fdata); // dest middle arg + VectorCopy(saxis, fdata + 0); + VectorCopy(taxis, fdata + 4); + VectorCopy(TS.rayEnd, fdata + 8); + VectorNormalize(fdata + 0); + VectorNormalize(fdata + 4); + VectorNormalize(fdata + 8); + fdata[3] = -0.5f; // subtract texture center + fdata[7] = -0.5f; + fdata[11] = 0.0f; + vec3_t shotOriginInCurrentSpace; // unknown space + TransformPoint(TS.rayStart, shotOriginInCurrentSpace, (mdxaBone_t *)fdata); // dest middle arg // this will insure the shot origin in our unknown space is now the shot origin, making it a known space - fdata[3]-=shotOriginInCurrentSpace[0]; - fdata[7]-=shotOriginInCurrentSpace[1]; - fdata[11]-=shotOriginInCurrentSpace[2]; - Inverse_Matrix((mdxaBone_t *)fdata,(mdxaBone_t *)(fdata+12)); // dest 2nd arg - data+=24; + fdata[3] -= shotOriginInCurrentSpace[0]; + fdata[7] -= shotOriginInCurrentSpace[1]; + fdata[11] -= shotOriginInCurrentSpace[2]; + Inverse_Matrix((mdxaBone_t *)fdata, (mdxaBone_t *)(fdata + 12)); // dest 2nd arg + data += 24; -// assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); + // assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); } } #else -struct SVertexTemp -{ +struct SVertexTemp { int flags; -// int touch; -// int newindex; -// float tex[2]; - SVertexTemp() - { -// touch=0; + // int touch; + // int newindex; + // float tex[2]; + SVertexTemp() { + // touch=0; } }; @@ -1120,50 +954,43 @@ static SVertexTemp GoreVerts[MAX_GORE_VERTS]; #endif // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) -{ - int j, numTris; +static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) { + int j, numTris; // whip through and actually transform each vertex - const mdxmTriangle_t *tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); const float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; numTris = surface->numTriangles; - for ( j = 0; j < numTris; j++ ) - { - float face; - vec3_t hitPoint, normal; + for (j = 0; j < numTris; j++) { + float face; + vec3_t hitPoint, normal; // determine actual coords for this triangle const float *point1 = &verts[(tris[j].indexes[0] * 5)]; const float *point2 = &verts[(tris[j].indexes[1] * 5)]; const float *point3 = &verts[(tris[j].indexes[2] * 5)]; // did we hit it? - if (G2_SegmentTriangleTest(TS.rayStart, TS.rayEnd, point1, point2, point3, qtrue, qtrue, hitPoint, normal, &face)) - { // find space in the collision records for this record - int i=0; - for (; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; - if (face>0) - { + if (face > 0) { newCol.mFlags = G2_FRONTFACE; - } - else - { + } else { newCol.mFlags = G2_BACKFACE; } VectorSubtract(hitPoint, TS.rayStart, distVect); newCol.mDistance = VectorLength(distVect); - assert( !Q_isnan(newCol.mDistance) ); + assert(!Q_isnan(newCol.mDistance)); // put the hit point back into world space TransformAndTranslatePoint(hitPoint, newCol.mCollisionPosition, &worldMatrix); @@ -1175,62 +1002,61 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ newCol.mMaterial = newCol.mLocation = 0; // Determine our location within the texture, and barycentric coordinates - G2_BuildHitPointST(point1, point1[3], point1[4], - point2, point2[3], point2[4], - point3, point3[3], point3[4], - hitPoint, &x_pos, &y_pos,newCol.mBarycentricI,newCol.mBarycentricJ); - -/* - const shader_t *shader = 0; - // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit location and hit material info - if ( cust_shader ) - { - shader = cust_shader; - } - else if ( skin ) - { - int j; - - // match the surface name to something in the skin file - shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { - // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = skin->surfaces[j]->shader; - break; - } - } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); - } - - // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little point - if ((shader->hitLocation) || (shader->hitMaterial)) - { - // ok, we have a floating point position. - determine location in data we need to look at - if (shader->hitLocation) - { - newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + - ((int)(y_pos * hitMatReg[shader->hitLocation].height) * hitMatReg[shader->hitLocation].width) + - ((int)(x_pos * hitMatReg[shader->hitLocation].width))); - Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); - } - - if (shader->hitMaterial) - { - newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + - ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * hitMatReg[shader->hitMaterial].width) + - ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); - } - } -*/ + G2_BuildHitPointST(point1, point1[3], point1[4], point2, point2[3], point2[4], point3, point3[3], point3[4], hitPoint, &x_pos, &y_pos, + newCol.mBarycentricI, newCol.mBarycentricJ); + + /* + const shader_t *shader = 0; + // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit + location and hit material info if ( cust_shader ) + { + shader = cust_shader; + } + else if ( skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little + point if ((shader->hitLocation) || (shader->hitMaterial)) + { + // ok, we have a floating point position. - determine location in data we need to look at + if (shader->hitLocation) + { + newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + + ((int)(y_pos * hitMatReg[shader->hitLocation].height) * + hitMatReg[shader->hitLocation].width) + + ((int)(x_pos * hitMatReg[shader->hitLocation].width))); + Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); + } + + if (shader->hitMaterial) + { + newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + + ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * + hitMatReg[shader->hitMaterial].width) + + ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); + } + } + */ // exit now if we should - if (TS.eG2TraceType == G2_RETURNONHIT) - { + if (TS.eG2TraceType == G2_RETURNONHIT) { TS.hitOne = true; return true; } @@ -1238,161 +1064,137 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ break; } } - if (i == MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } return false; } - // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_RadiusTracePolys( - const mdxmSurface_t *surface, - CTraceSurface &TS - ) -{ - int j; +static bool G2_RadiusTracePolys(const mdxmSurface_t *surface, CTraceSurface &TS) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; vec3_t v3RayDir; VectorSubtract(TS.rayEnd, TS.rayStart, v3RayDir); - CrossProduct(v3RayDir,basis2,basis1); + CrossProduct(v3RayDir, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(v3RayDir,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(v3RayDir, basis2, basis1); } - CrossProduct(v3RayDir,basis1,basis2); + CrossProduct(v3RayDir, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil -// assert(DotProduct(basis1,basis1)>.0001f); -// assert(DotProduct(basis2,basis2)>.0001f); + // assert(DotProduct(basis1,basis1)>.0001f); + // assert(DotProduct(basis2,basis2)>.0001f); VectorNormalize(basis1); VectorNormalize(basis2); - const float c=cos(0.0f);//theta - const float s=sin(0.0f);//theta + const float c = cos(0.0f); // theta + const float s = sin(0.0f); // theta - VectorScale(basis1, 0.5f * c / TS.m_fRadius,taxis); - VectorMA(taxis, 0.5f * s / TS.m_fRadius,basis2,taxis); + VectorScale(basis1, 0.5f * c / TS.m_fRadius, taxis); + VectorMA(taxis, 0.5f * s / TS.m_fRadius, basis2, taxis); - VectorScale(basis1,-0.5f * s /TS.m_fRadius,saxis); - VectorMA( saxis, 0.5f * c /TS.m_fRadius,basis2,saxis); + VectorScale(basis1, -0.5f * s / TS.m_fRadius, saxis); + VectorMA(saxis, 0.5f * c / TS.m_fRadius, basis2, saxis); - const float * const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + const float *const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; const int numVerts = surface->numVerts; - int flags=63; - //rayDir/=lengthSquared(raydir); + int flags = 63; + // rayDir/=lengthSquared(raydir); const float f = VectorLengthSquared(v3RayDir); - v3RayDir[0]/=f; - v3RayDir[1]/=f; - v3RayDir[2]/=f; + v3RayDir[0] /= f; + v3RayDir[1] /= f; + v3RayDir[2] /= f; - for ( j = 0; j < numVerts; j++ ) - { - const int pos=j*5; + for (j = 0; j < numVerts; j++) { + const int pos = j * 5; vec3_t delta; - delta[0]=verts[pos+0]-TS.rayStart[0]; - delta[1]=verts[pos+1]-TS.rayStart[1]; - delta[2]=verts[pos+2]-TS.rayStart[2]; - const float s=DotProduct(delta,saxis)+0.5f; - const float t=DotProduct(delta,taxis)+0.5f; - const float u=DotProduct(delta,v3RayDir); - int vflags=0; - - if (s>0) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + const float s = DotProduct(delta, saxis) + 0.5f; + const float t = DotProduct(delta, taxis) + 0.5f; + const float u = DotProduct(delta, v3RayDir); + int vflags = 0; + + if (s > 0) { + vflags |= 1; } - if (s<1) - { - vflags|=2; + if (s < 1) { + vflags |= 2; } - if (t>0) - { - vflags|=4; + if (t > 0) { + vflags |= 4; } - if (t<1) - { - vflags|=8; + if (t < 1) { + vflags |= 8; } - if (u>0) - { - vflags|=16; + if (u > 0) { + vflags |= 16; } - if (u<1) - { - vflags|=32; + if (u < 1) { + vflags |= 32; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; } - if (flags) - { + if (flags) { return false; // completely off the gore splotch (so presumably hit nothing? -Ste) } const int numTris = surface->numTriangles; - const mdxmTriangle_t * const tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); - - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]ofsTriangles); + + for (j = 0; j < numTris; j++) { + assert(tris[j].indexes[0] >= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 63 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; + if (flags) { continue; - } - else - { + } else { // we hit a triangle, so init a collision record... // int i = 0; - for (; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; -// if (face>0) -// { - newCol.mFlags = G2_FRONTFACE; -// } -// else -// { -// newCol.mFlags = G2_BACKFACE; -// } - - //get normal from triangle + // if (face>0) + // { + newCol.mFlags = G2_FRONTFACE; + // } + // else + // { + // newCol.mFlags = G2_BACKFACE; + // } + + // get normal from triangle const float *A = &verts[(tris[j].indexes[0] * 5)]; const float *B = &verts[(tris[j].indexes[1] * 5)]; const float *C = &verts[(tris[j].indexes[2] * 5)]; @@ -1409,44 +1211,40 @@ static bool G2_RadiusTracePolys( newCol.mMaterial = newCol.mLocation = 0; // exit now if we should - if (TS.eG2TraceType == G2_RETURNONHIT) - { + if (TS.eG2TraceType == G2_RETURNONHIT) { TS.hitOne = true; return true; } - vec3_t distVect; + vec3_t distVect; #if 0 //i don't know the hitPoint, but let's just assume it's the first vert for now... float *hitPoint = (float *)A; #else - //yeah, I want the collision point. Let's work out the impact point on the triangle. -rww + // yeah, I want the collision point. Let's work out the impact point on the triangle. -rww vec3_t hitPoint; float side, side2; float dist; - float third = -(A[0]*(B[1]*C[2] - C[1]*B[2]) + B[0]*(C[1]*A[2] - A[1]*C[2]) + C[0]*(A[1]*B[2] - B[1]*A[2]) ); + float third = -(A[0] * (B[1] * C[2] - C[1] * B[2]) + B[0] * (C[1] * A[2] - A[1] * C[2]) + C[0] * (A[1] * B[2] - B[1] * A[2])); VectorSubtract(TS.rayEnd, TS.rayStart, distVect); - side = normal[0]*TS.rayStart[0] + normal[1]*TS.rayStart[1] + normal[2]*TS.rayStart[2] + third; - side2 = normal[0]*distVect[0] + normal[1]*distVect[1] + normal[2]*distVect[2]; - if (fabsf(side2)<1E-8f) - { - //i don't know the hitPoint, but let's just assume it's the first vert for now... + side = normal[0] * TS.rayStart[0] + normal[1] * TS.rayStart[1] + normal[2] * TS.rayStart[2] + third; + side2 = normal[0] * distVect[0] + normal[1] * distVect[1] + normal[2] * distVect[2]; + if (fabsf(side2) < 1E-8f) { + // i don't know the hitPoint, but let's just assume it's the first vert for now... VectorSubtract(A, TS.rayStart, distVect); dist = VectorLength(distVect); VectorSubtract(TS.rayEnd, TS.rayStart, distVect); - VectorMA(TS.rayStart, dist/VectorLength(distVect), distVect, hitPoint); - } - else - { - dist = side/side2; + VectorMA(TS.rayStart, dist / VectorLength(distVect), distVect, hitPoint); + } else { + dist = side / side2; VectorMA(TS.rayStart, -dist, distVect, hitPoint); } #endif VectorSubtract(hitPoint, TS.rayStart, distVect); newCol.mDistance = VectorLength(distVect); - assert( !Q_isnan(newCol.mDistance) ); + assert(!Q_isnan(newCol.mDistance)); // put the hit point back into world space TransformAndTranslatePoint(hitPoint, newCol.mCollisionPosition, &worldMatrix); @@ -1455,11 +1253,10 @@ static bool G2_RadiusTracePolys( break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1467,24 +1264,21 @@ static bool G2_RadiusTracePolys( return false; } - // look at a surface and then do the trace on each poly -static void G2_TraceSurfaces(CTraceSurface &TS) -{ - int i; +static void G2_TraceSurfaces(CTraceSurface &TS) { + int i; // back track and get the surfinfo struct for this surface assert(TS.currentModel); assert(TS.currentModel->mdxm); - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); // don't allow recursion if we've already hit a polygon - if (TS.hitOne) - { + if (TS.hitOne) { return; } @@ -1492,39 +1286,28 @@ static void G2_TraceSurfaces(CTraceSurface &TS) int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, try to hit it - if (!offFlags) - { + if (!offFlags) { #ifdef _G2_GORE - if (TS.collRecMap) - { + if (TS.collRecMap) { #endif - if (!(Q_fabs(TS.m_fRadius) < 0.1)) // if not a point-trace + if (!(Q_fabs(TS.m_fRadius) < 0.1)) // if not a point-trace { // .. then use radius check // - if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, - TS - ) - && (TS.eG2TraceType == G2_RETURNONHIT) - ) - { + if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, + TS) && + (TS.eG2TraceType == G2_RETURNONHIT)) { TS.hitOne = true; return; } - } - else - { + } else { // go away and trace the polys in this surface - if (G2_TracePolys(surface, surfInfo, TS) - && (TS.eG2TraceType == G2_RETURNONHIT) - ) - { + if (G2_TracePolys(surface, surfInfo, TS) && (TS.eG2TraceType == G2_RETURNONHIT)) { // ok, we hit one, *and* we want to return instantly because the returnOnHit is set // so indicate we've hit one, so other surfaces don't get hit and return TS.hitOne = true; @@ -1532,138 +1315,119 @@ static void G2_TraceSurfaces(CTraceSurface &TS) } } #ifdef _G2_GORE - } - else - { + } else { G2_GorePolys(surface, TS, surfInfo); } #endif } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren && !TS.hitOne; i++) - { + for (i = 0; i < surfInfo->numChildren && !TS.hitOne; i++) { TS.surfaceNum = surfInfo->childIndexes[i]; G2_TraceSurfaces(TS); } } #ifdef _G2_GORE -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CCollisionRecord *collRecMap, int entNum, EG2_Collision eG2TraceType, int useLod, float fRadius, float ssize,float tsize,float theta,int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CCollisionRecord *collRecMap, int entNum, EG2_Collision eG2TraceType, int useLod, + float fRadius, float ssize, float tsize, float theta, int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) #else -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CCollisionRecord *collRecMap, int entNum, EG2_Collision eG2TraceType, int useLod, float fRadius) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CCollisionRecord *collRecMap, int entNum, EG2_Collision eG2TraceType, int useLod, + float fRadius) #endif { - int i, lod; - skin_t *skin; - shader_t *cust_shader; + int i, lod; + skin_t *skin; + shader_t *cust_shader; #if !defined(JK2_MODE) || defined(_G2_GORE) - qboolean firstModelOnly = qfalse; + qboolean firstModelOnly = qfalse; #endif // !JK2_MODE || _G2_GORE - int firstModel = 0; + int firstModel = 0; #ifndef JK2_MODE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0 ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif // !JK2_MODE #ifdef _G2_GORE - if ( gore - && gore->firstModel > 0 ) - { + if (gore && gore->firstModel > 0) { firstModel = gore->firstModel; firstModelOnly = qfalse; } #endif // walk each possible model for this entity and try tracing against it - for (i=firstModel; i 0 && g.mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( g.mSkin ); - } - else - { + if (g.mSkin > 0 && g.mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(g.mSkin); + } else { skin = NULL; } - lod = G2_DecideTraceLod(g,useLod); + lod = G2_DecideTraceLod(g, useLod); #ifndef JK2_MODE - if ( skipIfLODNotMatch ) - {//we only want to hit this SPECIFIC LOD... - if ( lod != useLod ) - {//doesn't match, skip this model + if (skipIfLODNotMatch) { // we only want to hit this SPECIFIC LOD... + if (lod != useLod) { // doesn't match, skip this model continue; } } #endif // !JK2_MODE - //reset the quick surface override lookup + // reset the quick surface override lookup G2_FindOverrideSurface(-1, g.mSlist); #ifdef _G2_GORE - CTraceSurface TS(g.mSurfaceRoot, g.mSlist, g.currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, g.mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &g, gore); + CTraceSurface TS(g.mSurfaceRoot, g.mSlist, g.currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, g.mTransformedVertsArray, + eG2TraceType, fRadius, ssize, tsize, theta, shader, &g, gore); #else - CTraceSurface TS(g.mSurfaceRoot, g.mSlist, g.currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, g.mTransformedVertsArray, eG2TraceType, fRadius); + CTraceSurface TS(g.mSurfaceRoot, g.mSlist, g.currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, g.mTransformedVertsArray, + eG2TraceType, fRadius); #endif // start the surface recursion loop G2_TraceSurfaces(TS); // if we've hit one surface on one model, don't bother doing the rest - if (TS.hitOne) - { + if (TS.hitOne) { break; } #ifdef _G2_GORE - if ( !collRecMap && firstModelOnly ) - { + if (!collRecMap && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -1671,29 +1435,25 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CColl } } -void TransformPoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2]; +void TransformPoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2]; } } -void TransformAndTranslatePoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { +void TransformAndTranslatePoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2] + mat->matrix[i][3]; + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2] + mat->matrix[i][3]; } } - // create a matrix using a set of angles -void Create_Matrix(const float *angle, mdxaBone_t *matrix) -{ - vec3_t axis[3]; +void Create_Matrix(const float *angle, mdxaBone_t *matrix) { + vec3_t axis[3]; // convert angles to axis - AnglesToAxis( angle, axis ); + AnglesToAxis(angle, axis); matrix->matrix[0][0] = axis[0][0]; matrix->matrix[1][0] = axis[0][1]; matrix->matrix[2][0] = axis[0][2]; @@ -1709,35 +1469,27 @@ void Create_Matrix(const float *angle, mdxaBone_t *matrix) matrix->matrix[0][3] = 0; matrix->matrix[1][3] = 0; matrix->matrix[2][3] = 0; - - } // given a matrix, generate the inverse of that matrix -void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) -{ +void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) { int i, j; - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - dest->matrix[i][j]=src->matrix[j][i]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + dest->matrix[i][j] = src->matrix[j][i]; } } - for (i = 0; i < 3; i++) - { - dest->matrix[i][3]=0; - for (j = 0; j < 3; j++) - { - dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + for (i = 0; i < 3; i++) { + dest->matrix[i][3] = 0; + for (j = 0; j < 3; j++) { + dest->matrix[i][3] -= dest->matrix[i][j] * src->matrix[j][3]; } } } // generate the world matrix for a given set of angles and origin - called from lots of places -void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) -{ +void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) { Create_Matrix(angles, &worldMatrix); worldMatrix.matrix[0][3] = origin[0]; worldMatrix.matrix[1][3] = origin[1]; @@ -1747,19 +1499,17 @@ void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) } // go away and determine what the pointer for a specific surface definition within the model definition is -void *G2_FindSurface(const model_s *mod, int index, int lod) -{ +void *G2_FindSurface(const model_s *mod, int index, int lod) { assert(mod); assert(mod->mdxm); // point at first lod list - byte *current = (byte*)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); + byte *current = (byte *)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); int i; - //walk the lods - assert(lod>=0&&lodmdxm->numLODs); - for (i=0; i= 0 && lod < mod->mdxm->numLODs); + for (i = 0; i < lod; i++) { mdxmLOD_t *lodData = (mdxmLOD_t *)current; current += lodData->ofsEnd; } @@ -1769,211 +1519,161 @@ void *G2_FindSurface(const model_s *mod, int index, int lod) mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; // we are now looking at the offset array - assert(index>=0&&indexmdxm->numSurfaces); + assert(index >= 0 && index < mod->mdxm->numSurfaces); current += indexes->offsets[index]; return (void *)current; } - -#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) +#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) #define BOLT_SAVE_BLOCK_SIZE sizeof(boltInfo_t) #define BONE_SAVE_BLOCK_SIZE sizeof(boneInfo_t) - -void G2_SaveGhoul2Models( - CGhoul2Info_v& ghoul2) -{ - ojk::SavedGameHelper saved_game( - ::ri.saved_game); +void G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2) { + ojk::SavedGameHelper saved_game(::ri.saved_game); saved_game.reset_buffer(); // is there anything to save? - if (!ghoul2.IsValid() || ghoul2.size() == 0) - { + if (!ghoul2.IsValid() || ghoul2.size() == 0) { const int zero_size = 0; #ifdef JK2_MODE - saved_game.write( - zero_size); + saved_game.write(zero_size); - saved_game.write_chunk_and_size( - INT_ID('G', 'L', '2', 'S'), - INT_ID('G', 'H', 'L', '2')); + saved_game.write_chunk_and_size(INT_ID('G', 'L', '2', 'S'), INT_ID('G', 'H', 'L', '2')); #else - saved_game.write_chunk( - INT_ID('G', 'H', 'L', '2'), - zero_size); //write out a zero buffer + saved_game.write_chunk(INT_ID('G', 'H', 'L', '2'), + zero_size); // write out a zero buffer #endif // JK2_MODE return; } - // save out how many ghoul2 models we have const int model_count = static_cast(ghoul2.size()); - saved_game.write( - model_count); + saved_game.write(model_count); - for (int i = 0; i < model_count; ++i) - { + for (int i = 0; i < model_count; ++i) { // first save out the ghoul2 details themselves - ghoul2[i].sg_export( - saved_game); + ghoul2[i].sg_export(saved_game); // save out how many surfaces we have const int surface_count = static_cast(ghoul2[i].mSlist.size()); - saved_game.write( - surface_count); + saved_game.write(surface_count); // now save the all the surface list info - for (int x = 0; x < surface_count; ++x) - { - ghoul2[i].mSlist[x].sg_export( - saved_game); + for (int x = 0; x < surface_count; ++x) { + ghoul2[i].mSlist[x].sg_export(saved_game); } // save out how many bones we have const int bone_count = static_cast(ghoul2[i].mBlist.size()); - saved_game.write( - bone_count); + saved_game.write(bone_count); // now save the all the bone list info - for (int x = 0; x < bone_count; ++x) - { - ghoul2[i].mBlist[x].sg_export( - saved_game); + for (int x = 0; x < bone_count; ++x) { + ghoul2[i].mBlist[x].sg_export(saved_game); } // save out how many bolts we have const int bolt_count = static_cast(ghoul2[i].mBltlist.size()); - saved_game.write( - bolt_count); + saved_game.write(bolt_count); // lastly save the all the bolt list info - for (int x = 0; x < bolt_count; ++x) - { - ghoul2[i].mBltlist[x].sg_export( - saved_game); + for (int x = 0; x < bolt_count; ++x) { + ghoul2[i].mBltlist[x].sg_export(saved_game); } } #ifdef JK2_MODE - saved_game.write_chunk_and_size( - INT_ID('G', 'L', '2', 'S'), - INT_ID('G', 'H', 'L', '2')); + saved_game.write_chunk_and_size(INT_ID('G', 'L', '2', 'S'), INT_ID('G', 'H', 'L', '2')); #else - saved_game.write_chunk( - INT_ID('G', 'H', 'L', '2')); + saved_game.write_chunk(INT_ID('G', 'H', 'L', '2')); #endif // JK2_MODE } // FIXME Remove 'buffer' parameter -void G2_LoadGhoul2Model( - CGhoul2Info_v& ghoul2, - char* buffer) -{ +void G2_LoadGhoul2Model(CGhoul2Info_v &ghoul2, char *buffer) { static_cast(buffer); - ojk::SavedGameHelper saved_game( - ::ri.saved_game); + ojk::SavedGameHelper saved_game(::ri.saved_game); // first thing, lets see how many ghoul2 models we have, and resize our buffers accordingly int model_count = 0; #ifdef JK2_MODE - if (saved_game.get_buffer_size() > 0) - { + if (saved_game.get_buffer_size() > 0) { #endif // JK2_MODE - saved_game.read( - model_count); + saved_game.read(model_count); #ifdef JK2_MODE } #endif // JK2_MODE - - ghoul2.resize( - model_count); + ghoul2.resize(model_count); // did we actually resize to a value? - if (model_count == 0) - { + if (model_count == 0) { // no, ok, well, done then. return; } // now we have enough instances, lets go through each one and load up the relevant details - for (decltype(model_count) i = 0; i < model_count; ++i) - { + for (decltype(model_count) i = 0; i < model_count; ++i) { ghoul2[i].mSkelFrameNum = 0; ghoul2[i].mModelindex = -1; ghoul2[i].mFileName[0] = 0; ghoul2[i].mValid = false; // load the ghoul2 info from the buffer - ghoul2[i].sg_import( - saved_game); + ghoul2[i].sg_import(saved_game); - if (ghoul2[i].mModelindex != -1 && ghoul2[i].mFileName[0]) - { + if (ghoul2[i].mModelindex != -1 && ghoul2[i].mFileName[0]) { ghoul2[i].mModelindex = i; - ::G2_SetupModelPointers( - &ghoul2[i]); + ::G2_SetupModelPointers(&ghoul2[i]); } // give us enough surfaces to load up the data int surface_count = 0; - saved_game.read( - surface_count); + saved_game.read(surface_count); ghoul2[i].mSlist.resize(surface_count); // now load all the surfaces - for (decltype(surface_count) x = 0; x < surface_count; ++x) - { - ghoul2[i].mSlist[x].sg_import( - saved_game); + for (decltype(surface_count) x = 0; x < surface_count; ++x) { + ghoul2[i].mSlist[x].sg_import(saved_game); } // give us enough bones to load up the data int bone_count = 0; - saved_game.read( - bone_count); + saved_game.read(bone_count); - ghoul2[i].mBlist.resize( - bone_count); + ghoul2[i].mBlist.resize(bone_count); // now load all the bones - for (decltype(bone_count) x = 0; x < bone_count; ++x) - { - ghoul2[i].mBlist[x].sg_import( - saved_game); + for (decltype(bone_count) x = 0; x < bone_count; ++x) { + ghoul2[i].mBlist[x].sg_import(saved_game); } // give us enough bolts to load up the data int bolt_count = 0; - saved_game.read( - bolt_count); + saved_game.read(bolt_count); - ghoul2[i].mBltlist.resize( - bolt_count); + ghoul2[i].mBltlist.resize(bolt_count); // now load all the bolts - for (decltype(bolt_count) x = 0; x < bolt_count; ++x) - { - ghoul2[i].mBltlist[x].sg_import( - saved_game); + for (decltype(bolt_count) x = 0; x < bolt_count; ++x) { + ghoul2[i].mBltlist[x].sg_import(saved_game); } } diff --git a/code/rd-vanilla/G2_surfaces.cpp b/code/rd-vanilla/G2_surfaces.cpp index e387baaedc..b9f61b5059 100644 --- a/code/rd-vanilla/G2_surfaces.cpp +++ b/code/rd-vanilla/G2_surfaces.cpp @@ -23,57 +23,46 @@ along with this program; if not, see . #include "../server/exe_headers.h" #ifndef __Q_SHARED_H - #include "../qcommon/q_shared.h" +#include "../qcommon/q_shared.h" #endif #if !defined(TR_LOCAL_H) - #include "tr_local.h" +#include "tr_local.h" #endif #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -#define G2_MODEL_OK(g) ((g)&&(g)->mValid&&(g)->aHeader&&(g)->currentModel&&(g)->animModel) +#define G2_MODEL_OK(g) ((g) && (g)->mValid && (g)->aHeader && (g)->currentModel && (g)->animModel) -class CQuickOverride -{ +class CQuickOverride { int mOverride[512]; int mAt[512]; int mCurrentTouch; -public: - CQuickOverride() - { - mCurrentTouch=1; + + public: + CQuickOverride() { + mCurrentTouch = 1; int i; - for (i=0;i<512;i++) - { - mOverride[i]=0; + for (i = 0; i < 512; i++) { + mOverride[i] = 0; } } - void Invalidate() - { - mCurrentTouch++; - } - void Set(int index,int pos) - { - if (index==10000) - { + void Invalidate() { mCurrentTouch++; } + void Set(int index, int pos) { + if (index == 10000) { return; } - assert(index>=0&&index<512); - mOverride[index]=mCurrentTouch; - mAt[index]=pos; + assert(index >= 0 && index < 512); + mOverride[index] = mCurrentTouch; + mAt[index] = pos; } - int Test(int index) - { - assert(index>=0&&index<512); - if (mOverride[index]!=mCurrentTouch) - { + int Test(int index) { + assert(index >= 0 && index < 512); + if (mOverride[index] != mCurrentTouch) { return -1; - } - else - { + } else { return mAt[index]; } } @@ -81,33 +70,24 @@ class CQuickOverride static CQuickOverride QuickOverride; - // find a particular surface in the surface override list -const surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum,const surfaceInfo_v &surfaceList) -{ +const surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, const surfaceInfo_v &surfaceList) { - if (surfaceNum<0) - { + if (surfaceNum < 0) { // starting a new lookup QuickOverride.Invalidate(); - for(size_t i=0; i=0) - { - QuickOverride.Set(surfaceList[i].surface,i); + for (size_t i = 0; i < surfaceList.size(); i++) { + if (surfaceList[i].surface >= 0) { + QuickOverride.Set(surfaceList[i].surface, i); } } return NULL; } - int idx=QuickOverride.Test(surfaceNum); - if (idx<0) - { - if (surfaceNum==10000) - { - for(size_t i=0; i=0&&idx<(int)surfaceList.size()); + assert(idx >= 0 && idx < (int)surfaceList.size()); assert(surfaceList[idx].surface == surfaceNum); return &surfaceList[idx]; } - // given a surface name, lets see if it's legal in the model -int G2_IsSurfaceLegal(const model_s *mod_m, const char *surfaceName, uint32_t *flags) -{ +int G2_IsSurfaceLegal(const model_s *mod_m, const char *surfaceName, uint32_t *flags) { assert(mod_m); assert(mod_m->mdxm); // damn include file dependancies - mdxmSurfHierarchy_t *surf; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy ); + mdxmSurfHierarchy_t *surf; + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mod_m->mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surf->name)) - { + for (int i = 0; i < mod_m->mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surf->name)) { *flags = surf->flags; return i; } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } return -1; } - /************************************************************************************************ * G2_FindSurface * find a surface in a ghoul2 surface override list based on it's name @@ -168,30 +141,24 @@ int G2_IsSurfaceLegal(const model_s *mod_m, const char *surfaceName, uint32_t *f * pointer to surface if successful, false otherwise * ************************************************************************************************/ -const mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, - int *surfIndex/*NULL*/) -{ - int i = 0; +const mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, int *surfIndex /*NULL*/) { + int i = 0; // find the model we want assert(G2_MODEL_OK(ghlInfo)); const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); - // first find if we already have this surface in the list - for (i = slist.size() - 1; i >= 0; i--) - { - if ((slist[i].surface != 10000) && (slist[i].surface != -1)) - { - const mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface(ghlInfo->currentModel, slist[i].surface, 0); + // first find if we already have this surface in the list + for (i = slist.size() - 1; i >= 0; i--) { + if ((slist[i].surface != 10000) && (slist[i].surface != -1)) { + const mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface(ghlInfo->currentModel, slist[i].surface, 0); // back track and get the surfinfo struct for this surface - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); - // are these the droids we're looking for? - if (!Q_stricmp (surfInfo->name, surfaceName)) - { + // are these the droids we're looking for? + if (!Q_stricmp(surfInfo->name, surfaceName)) { // yup - if (surfIndex) - { + if (surfIndex) { *surfIndex = i; } return surf; @@ -199,24 +166,21 @@ const mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, } } // didn't find it - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } // set a named surface offFlags - if it doesn't find a surface with this name in the list then it will add one. -qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, const char *surfaceName, const int offFlags) -{ - int surfIndex = -1; - surfaceInfo_t temp_slist_entry; +qboolean G2_SetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName, const int offFlags) { + int surfIndex = -1; + surfaceInfo_t temp_slist_entry; // find the model we want - // first find if we already have this surface in the list + // first find if we already have this surface in the list const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, ghlInfo->mSlist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value // slist[surfIndex].offFlags = offFlags; @@ -225,21 +189,17 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, const char *surfaceName, cons ghlInfo->mSlist[surfIndex].offFlags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); ghlInfo->mSlist[surfIndex].offFlags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); return qtrue; - } - else - { + } else { // ok, not in the list already - in that case, lets verify this surface exists in the model mesh uint32_t flags; int surfaceNum = G2_IsSurfaceLegal(ghlInfo->currentModel, surfaceName, &flags); - if (surfaceNum != -1) - { + if (surfaceNum != -1) { uint32_t newflags = flags; // the only bit we really care about in the incoming flags is the off bit newflags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); newflags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); - if (newflags != flags) - { // insert here then because it changed, no need to add an override otherwise + if (newflags != flags) { // insert here then because it changed, no need to add an override otherwise temp_slist_entry.offFlags = newflags; temp_slist_entry.surface = surfaceNum; @@ -251,59 +211,50 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, const char *surfaceName, cons return qfalse; } -void G2_FindRecursiveSurface(const model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) -{ +void G2_FindRecursiveSurface(const model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) { assert(currentModel); assert(currentModel->mdxm); - int i; - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(currentModel, surfaceNum, 0); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + int i; + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(currentModel, surfaceNum, 0); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, indicate as such in the active surface list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { + if (!(offFlags & G2SURFACEFLAG_OFF)) { activeSurfaces[surfaceNum] = 1; - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { surfaceNum = surfInfo->childIndexes[i]; G2_FindRecursiveSurface(currentModel, surfaceNum, rootList, activeSurfaces); } - } -qboolean G2_SetRootSurface( CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) -{ - int surf; - uint32_t flags; - assert(modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size()); assert(ghoul2[modelIndex].currentModel); assert(ghoul2[modelIndex].currentModel->mdxm); - // first find if we already have this surface in the list + // first find if we already have this surface in the list surf = G2_IsSurfaceLegal(ghoul2[modelIndex].currentModel, surfaceName, &flags); - if (surf != -1) - { + if (surf != -1) { ghoul2[modelIndex].mSurfaceRoot = surf; return qtrue; } @@ -311,28 +262,23 @@ qboolean G2_SetRootSurface( CGhoul2Info_v &ghoul2, const int modelIndex, const c return qfalse; } - -extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); -int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ +extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); +int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { lod = G2_DecideTraceLod(*ghoul2, lod); // first up, see if we have a free one already set up - look only from the end of the constant surfaces onwards size_t i; - for (i=0; imSlist.size(); i++) - { + for (i = 0; i < ghoul2->mSlist.size(); i++) { // is the surface count -1? That would indicate it's free - if (ghoul2->mSlist[i].surface == -1) - { + if (ghoul2->mSlist[i].surface == -1) { break; } } - if (i==ghoul2->mSlist.size()) - { + if (i == ghoul2->mSlist.size()) { ghoul2->mSlist.push_back(surfaceInfo_t()); } ghoul2->mSlist[i].offFlags = G2SURFACEFLAG_GENERATED; - ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces + ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces ghoul2->mSlist[i].genBarycentricI = BarycentricI; ghoul2->mSlist[i].genBarycentricJ = BarycentricJ; ghoul2->mSlist[i].genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); @@ -340,10 +286,8 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float return i; } -qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) -{ - if (index != -1) - { +qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) { + if (index != -1) { slist[index].surface = -1; return qtrue; } @@ -351,36 +295,30 @@ qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) return qfalse; } - -int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ +int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { assert(ghlInfo->currentModel); assert(ghlInfo->currentModel->mdxm); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); // walk each surface and see if this index is listed in it's children - const mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface(ghlInfo->currentModel, index, 0); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); + const mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface(ghlInfo->currentModel, index, 0); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->parentIndex; - } -int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - uint32_t flags; +int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + uint32_t flags; assert(ghlInfo->currentModel); return G2_IsSurfaceLegal(ghlInfo->currentModel, surfaceName, &flags); } -int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) -{ - uint32_t flags = 0u;//, surfFlags = 0; - int surfIndex = 0; +int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) { + uint32_t flags = 0u; //, surfFlags = 0; + int surfIndex = 0; assert(ghlInfo->currentModel); assert(ghlInfo->currentModel->mdxm); - if (!ghlInfo->currentModel->mdxm) - { + if (!ghlInfo->currentModel->mdxm) { return -1; } @@ -388,14 +326,12 @@ int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceI // find the original surface in the surface list int surfNum = G2_IsSurfaceLegal(ghlInfo->currentModel, surfaceName, &flags); - if ( surfNum != -1 ) - {//must be legal - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); + if (surfNum != -1) { // must be legal + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); surfNum = surfInfo->parentIndex; // walk the surface hierarchy up until we hit the root - while (surfNum != -1) - { + while (surfNum != -1) { const mdxmSurface_t *parentSurf; uint32_t parentFlags = 0u; const mdxmSurfHierarchy_t *parentSurfInfo; @@ -403,41 +339,34 @@ int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceI parentSurfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); // find the original surface in the surface list - //G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags + // G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags G2_IsSurfaceLegal(ghlInfo->currentModel, parentSurfInfo->name, &parentFlags); // now see if we already have overriden this surface in the slist parentSurf = G2_FindSurface(ghlInfo, slist, parentSurfInfo->name, &surfIndex); - if (parentSurf) - { + if (parentSurf) { // set descendants value parentFlags = slist[surfIndex].offFlags; } // now we have the parent flags, lets see if any have the 'no descendants' flag set - if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) { flags |= G2SURFACEFLAG_OFF; break; } // set up scan of next parent surfNum = parentSurfInfo->parentIndex; } - } - else - { + } else { return -1; } - if ( flags == 0 ) - {//it's not being overridden by a parent + if (flags == 0) { // it's not being overridden by a parent // now see if we already have overriden this surface in the slist const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value flags = slist[surfIndex].offFlags; } - // ok, at this point in flags we have what this surface is set to, and the index of the surface itself + // ok, at this point in flags we have what this surface is set to, and the index of the surface itself } return flags; - } diff --git a/code/rd-vanilla/tr_WorldEffects.cpp b/code/rd-vanilla/tr_WorldEffects.cpp index 6c65c8dad9..504e35bc8b 100644 --- a/code/rd-vanilla/tr_WorldEffects.cpp +++ b/code/rd-vanilla/tr_WorldEffects.cpp @@ -33,7 +33,7 @@ along with this program; if not, see . //////////////////////////////////////////////////////////////////////////////////////// // Externs & Fwd Decl. //////////////////////////////////////////////////////////////////////////////////////// -extern void SetViewportAndScissor( void ); +extern void SetViewportAndScissor(void); //////////////////////////////////////////////////////////////////////////////////////// // Includes @@ -47,175 +47,141 @@ extern void SetViewportAndScissor( void ); //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define GLS_ALPHA (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA) -#define MAX_WIND_ZONES 12 -#define MAX_WEATHER_ZONES 50 // so we can more zones that are smaller -#define MAX_PUFF_SYSTEMS 2 -#define MAX_PARTICLE_CLOUDS 5 -#define POINTCACHE_CELL_SIZE 32.0f +#define GLS_ALPHA (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA) +#define MAX_WIND_ZONES 12 +#define MAX_WEATHER_ZONES 50 // so we can more zones that are smaller +#define MAX_PUFF_SYSTEMS 2 +#define MAX_PARTICLE_CLOUDS 5 +#define POINTCACHE_CELL_SIZE 32.0f //////////////////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////////////////// -float mMillisecondsElapsed = 0; -float mSecondsElapsed = 0; -bool mFrozen = false; - -CVec3 mGlobalWindVelocity; -CVec3 mGlobalWindDirection; -float mGlobalWindSpeed; -int mParticlesRendered; - +float mMillisecondsElapsed = 0; +float mSecondsElapsed = 0; +bool mFrozen = false; +CVec3 mGlobalWindVelocity; +CVec3 mGlobalWindDirection; +float mGlobalWindSpeed; +int mParticlesRendered; //////////////////////////////////////////////////////////////////////////////////////// // Handy Functions //////////////////////////////////////////////////////////////////////////////////////// -inline void VectorMA( vec3_t vecAdd, const float scale, const vec3_t vecScale) -{ +inline void VectorMA(vec3_t vecAdd, const float scale, const vec3_t vecScale) { vecAdd[0] += (scale * vecScale[0]); vecAdd[1] += (scale * vecScale[1]); vecAdd[2] += (scale * vecScale[2]); } -inline void VectorFloor(vec3_t in) -{ +inline void VectorFloor(vec3_t in) { in[0] = floorf(in[0]); in[1] = floorf(in[1]); in[2] = floorf(in[2]); } -inline void VectorCeil(vec3_t in) -{ +inline void VectorCeil(vec3_t in) { in[0] = ceilf(in[0]); in[1] = ceilf(in[1]); in[2] = ceilf(in[2]); } -inline float FloatRand(void) -{ - return ((float)rand() / (float)RAND_MAX); -} +inline float FloatRand(void) { return ((float)rand() / (float)RAND_MAX); } -inline float fast_flrand(float min, float max) -{ - //return min + (max - min) * flrand; - return Q_flrand(min, max); //fixme? +inline float fast_flrand(float min, float max) { + // return min + (max - min) * flrand; + return Q_flrand(min, max); // fixme? } -inline void SnapFloatToGrid(float& f, int GridSize) -{ +inline void SnapFloatToGrid(float &f, int GridSize) { f = (int)(f); - bool fNeg = (f<0); - if (fNeg) - { - f *= -1; // Temporarly make it positive + bool fNeg = (f < 0); + if (fNeg) { + f *= -1; // Temporarly make it positive } - int Offset = ((int)(f) % (int)(GridSize)); - int OffsetAbs = abs(Offset); - if (OffsetAbs>(GridSize/2)) - { + int Offset = ((int)(f) % (int)(GridSize)); + int OffsetAbs = abs(Offset); + if (OffsetAbs > (GridSize / 2)) { Offset = (GridSize - OffsetAbs) * -1; } f -= Offset; - if (fNeg) - { - f *= -1; // Put It Back To Negative + if (fNeg) { + f *= -1; // Put It Back To Negative } f = (int)(f); - assert(((int)(f)%(int)(GridSize)) == 0); + assert(((int)(f) % (int)(GridSize)) == 0); } -inline void SnapVectorToGrid(CVec3& Vec, int GridSize) -{ +inline void SnapVectorToGrid(CVec3 &Vec, int GridSize) { SnapFloatToGrid(Vec[0], GridSize); SnapFloatToGrid(Vec[1], GridSize); SnapFloatToGrid(Vec[2], GridSize); } - - - - //////////////////////////////////////////////////////////////////////////////////////// // Range Structures //////////////////////////////////////////////////////////////////////////////////////// -struct SVecRange -{ - CVec3 mMins; - CVec3 mMaxs; +struct SVecRange { + CVec3 mMins; + CVec3 mMaxs; - inline void Clear() - { + inline void Clear() { mMins.Clear(); mMaxs.Clear(); } - inline void Pick(CVec3& V) - { + inline void Pick(CVec3 &V) { V[0] = Q_flrand(mMins[0], mMaxs[0]); V[1] = Q_flrand(mMins[1], mMaxs[1]); V[2] = Q_flrand(mMins[2], mMaxs[2]); } - inline void Wrap(CVec3& V) - { - if (V[0]<=mMins[0]) - { - if ((mMins[0]-V[0])>500) - { + inline void Wrap(CVec3 &V) { + if (V[0] <= mMins[0]) { + if ((mMins[0] - V[0]) > 500) { Pick(V); return; } V[0] = mMaxs[0] - 10.0f; } - if (V[0]>=mMaxs[0]) - { - if ((V[0]-mMaxs[0])>500) - { + if (V[0] >= mMaxs[0]) { + if ((V[0] - mMaxs[0]) > 500) { Pick(V); return; } V[0] = mMins[0] + 10.0f; } - if (V[1]<=mMins[1]) - { - if ((mMins[1]-V[1])>500) - { + if (V[1] <= mMins[1]) { + if ((mMins[1] - V[1]) > 500) { Pick(V); return; } V[1] = mMaxs[1] - 10.0f; } - if (V[1]>=mMaxs[1]) - { - if ((V[1]-mMaxs[1])>500) - { + if (V[1] >= mMaxs[1]) { + if ((V[1] - mMaxs[1]) > 500) { Pick(V); return; } V[1] = mMins[1] + 10.0f; } - if (V[2]<=mMins[2]) - { - if ((mMins[2]-V[2])>500) - { + if (V[2] <= mMins[2]) { + if ((mMins[2] - V[2]) > 500) { Pick(V); return; } V[2] = mMaxs[2] - 10.0f; } - if (V[2]>=mMaxs[2]) - { - if ((V[2]-mMaxs[2])>500) - { + if (V[2] >= mMaxs[2]) { + if ((V[2] - mMaxs[2]) > 500) { Pick(V); return; } @@ -223,64 +189,39 @@ struct SVecRange } } - inline bool In(const CVec3& V) - { - return (V>mMins && V mMins && V < mMaxs); } }; -struct SFloatRange -{ - float mMin; - float mMax; +struct SFloatRange { + float mMin; + float mMax; - inline void Clear() - { + inline void Clear() { mMin = 0; mMax = 0; } - inline void Pick(float& V) - { - V = Q_flrand(mMin, mMax); - } - inline bool In(const float& V) - { - return (V>mMin && V mMin && V < mMax); } }; -struct SIntRange -{ - int mMin; - int mMax; +struct SIntRange { + int mMin; + int mMax; - inline void Clear() - { + inline void Clear() { mMin = 0; mMax = 0; } - inline void Pick(int& V) - { - V = Q_irand(mMin, mMax); - } - inline bool In(const int& V) - { - return (V>mMin && V mMin && V < mMax); } }; - - - - //////////////////////////////////////////////////////////////////////////////////////// // The Particle Class //////////////////////////////////////////////////////////////////////////////////////// -class WFXParticle -{ -public: - enum - { +class WFXParticle { + public: + enum { FLAG_RENDER = 0, FLAG_FADEIN, @@ -289,60 +230,53 @@ class WFXParticle FLAG_MAX }; - typedef ratl::bits_vs TFlags; + typedef ratl::bits_vs TFlags; - float mAlpha; - TFlags mFlags; - CVec3 mPosition; - CVec3 mVelocity; - float mMass; // A higher number will more greatly resist force and result in greater gravity + float mAlpha; + TFlags mFlags; + CVec3 mPosition; + CVec3 mVelocity; + float mMass; // A higher number will more greatly resist force and result in greater gravity }; - - - - //////////////////////////////////////////////////////////////////////////////////////// // The Wind //////////////////////////////////////////////////////////////////////////////////////// -class CWindZone -{ -public: - bool mGlobal; - SVecRange mRBounds; - SVecRange mRVelocity; - SIntRange mRDuration; - SIntRange mRDeadTime; - float mMaxDeltaVelocityPerUpdate; - float mChanceOfDeadTime; - - CVec3 mCurrentVelocity; - CVec3 mTargetVelocity; - int mTargetVelocityTimeRemaining; - - -public: +class CWindZone { + public: + bool mGlobal; + SVecRange mRBounds; + SVecRange mRVelocity; + SIntRange mRDuration; + SIntRange mRDeadTime; + float mMaxDeltaVelocityPerUpdate; + float mChanceOfDeadTime; + + CVec3 mCurrentVelocity; + CVec3 mTargetVelocity; + int mTargetVelocityTimeRemaining; + + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - void Initialize() - { + void Initialize() { mRBounds.Clear(); - mGlobal = true; + mGlobal = true; - mRVelocity.mMins = -1500.0f; - mRVelocity.mMins[2] = -10.0f; - mRVelocity.mMaxs = 1500.0f; - mRVelocity.mMaxs[2] = 10.0f; + mRVelocity.mMins = -1500.0f; + mRVelocity.mMins[2] = -10.0f; + mRVelocity.mMaxs = 1500.0f; + mRVelocity.mMaxs[2] = 10.0f; - mMaxDeltaVelocityPerUpdate = 10.0f; + mMaxDeltaVelocityPerUpdate = 10.0f; - mRDuration.mMin = 1000; - mRDuration.mMax = 2000; + mRDuration.mMin = 1000; + mRDuration.mMax = 2000; - mChanceOfDeadTime = 0.3f; - mRDeadTime.mMin = 1000; - mRDeadTime.mMax = 3000; + mChanceOfDeadTime = 0.3f; + mRDeadTime.mMin = 1000; + mRDeadTime.mMax = 3000; mCurrentVelocity.Clear(); mTargetVelocity.Clear(); @@ -352,29 +286,21 @@ class CWindZone //////////////////////////////////////////////////////////////////////////////////// // Update - Changes wind when current target velocity expires //////////////////////////////////////////////////////////////////////////////////// - void Update() - { - if (mTargetVelocityTimeRemaining==0) - { - if (FloatRand() mMaxDeltaVelocityPerUpdate) - { + CVec3 DeltaVelocity(mTargetVelocity - mCurrentVelocity); + float DeltaVelocityLen = VectorNormalize(DeltaVelocity.v); + if (DeltaVelocityLen > mMaxDeltaVelocityPerUpdate) { DeltaVelocityLen = mMaxDeltaVelocityPerUpdate; } DeltaVelocity *= (DeltaVelocityLen); @@ -382,18 +308,14 @@ class CWindZone } } }; -ratl::vector_vs mWindZones; -ratl::vector_vs mLocalWindZones; +ratl::vector_vs mWindZones; +ratl::vector_vs mLocalWindZones; -bool R_GetWindVector(vec3_t windVector, vec3_t atpoint) -{ +bool R_GetWindVector(vec3_t windVector, vec3_t atpoint) { VectorCopy(mGlobalWindDirection.v, windVector); - if (atpoint && mLocalWindZones.size()) - { - for (int curLocalWindZone=0; curLocalWindZonemRBounds.In(atpoint)) - { + if (atpoint && mLocalWindZones.size()) { + for (int curLocalWindZone = 0; curLocalWindZone < mLocalWindZones.size(); curLocalWindZone++) { + if (mLocalWindZones[curLocalWindZone]->mRBounds.In(atpoint)) { VectorAdd(windVector, mLocalWindZones[curLocalWindZone]->mCurrentVelocity.v, windVector); } } @@ -402,15 +324,11 @@ bool R_GetWindVector(vec3_t windVector, vec3_t atpoint) return true; } -bool R_GetWindSpeed(float &windSpeed, vec3_t atpoint) -{ +bool R_GetWindSpeed(float &windSpeed, vec3_t atpoint) { windSpeed = mGlobalWindSpeed; - if (atpoint && mLocalWindZones.size()) - { - for (int curLocalWindZone=0; curLocalWindZonemRBounds.In(atpoint)) - { + if (atpoint && mLocalWindZones.size()) { + for (int curLocalWindZone = 0; curLocalWindZone < mLocalWindZones.size(); curLocalWindZone++) { + if (mLocalWindZones[curLocalWindZone]->mRBounds.In(atpoint)) { windSpeed += VectorLength(mLocalWindZones[curLocalWindZone]->mCurrentVelocity.v); } } @@ -418,66 +336,60 @@ bool R_GetWindSpeed(float &windSpeed, vec3_t atpoint) return true; } -bool R_GetWindGusting(vec3_t atpoint) -{ +bool R_GetWindGusting(vec3_t atpoint) { float windSpeed; R_GetWindSpeed(windSpeed, atpoint); - return (windSpeed>1000.0f); + return (windSpeed > 1000.0f); } //////////////////////////////////////////////////////////////////////////////////////// // Outside Point Cache //////////////////////////////////////////////////////////////////////////////////////// -class COutside -{ -#define COUTSIDE_STRUCT_VERSION 1 // you MUST increase this any time you change any binary (fields) inside this class, or cahced files will fuck up -public: +class COutside { +#define COUTSIDE_STRUCT_VERSION 1 // you MUST increase this any time you change any binary (fields) inside this class, or cahced files will fuck up + public: //////////////////////////////////////////////////////////////////////////////////// - //Global Public Outside Variables + // Global Public Outside Variables //////////////////////////////////////////////////////////////////////////////////// - bool mOutsideShake; - float mOutsidePain; + bool mOutsideShake; + float mOutsidePain; - CVec3 mFogColor; - int mFogColorInt; - bool mFogColorTempActive; + CVec3 mFogColor; + int mFogColorInt; + bool mFogColorTempActive; -private: + private: //////////////////////////////////////////////////////////////////////////////////// // The Outside Cache //////////////////////////////////////////////////////////////////////////////////// - bool mCacheInit; // Has It Been Cached? + bool mCacheInit; // Has It Been Cached? - struct SWeatherZone - { - static bool mMarkedOutside; - uint32_t *mPointCache; // malloc block ptr + struct SWeatherZone { + static bool mMarkedOutside; + uint32_t *mPointCache; // malloc block ptr - int miPointCacheByteSize; // size of block - SVecRange mExtents; - SVecRange mSize; - int mWidth; - int mHeight; - int mDepth; + int miPointCacheByteSize; // size of block + SVecRange mExtents; + SVecRange mSize; + int mWidth; + int mHeight; + int mDepth; - void WriteToDisk( fileHandle_t f ) - { - ri.FS_Write(&mMarkedOutside,sizeof(mMarkedOutside),f); - ri.FS_Write( mPointCache, miPointCacheByteSize, f ); + void WriteToDisk(fileHandle_t f) { + ri.FS_Write(&mMarkedOutside, sizeof(mMarkedOutside), f); + ri.FS_Write(mPointCache, miPointCacheByteSize, f); } - void ReadFromDisk( fileHandle_t f ) - { - ri.FS_Read(&mMarkedOutside,sizeof(mMarkedOutside),f); - ri.FS_Read( mPointCache, miPointCacheByteSize, f); + void ReadFromDisk(fileHandle_t f) { + ri.FS_Read(&mMarkedOutside, sizeof(mMarkedOutside), f); + ri.FS_Read(mPointCache, miPointCacheByteSize, f); } //////////////////////////////////////////////////////////////////////////////////// // Convert To Cell //////////////////////////////////////////////////////////////////////////////////// - inline void ConvertToCell(const CVec3& pos, int& x, int& y, int& z, int& bit) - { + inline void ConvertToCell(const CVec3 &pos, int &x, int &y, int &z, int &bit) { x = (int)((pos[0] / POINTCACHE_CELL_SIZE) - mSize.mMins[0]); y = (int)((pos[1] / POINTCACHE_CELL_SIZE) - mSize.mMins[1]); z = (int)((pos[2] / POINTCACHE_CELL_SIZE) - mSize.mMins[2]); @@ -489,66 +401,52 @@ class COutside //////////////////////////////////////////////////////////////////////////////////// // CellOutside - Test to see if a given cell is outside //////////////////////////////////////////////////////////////////////////////////// - inline bool CellOutside(int x, int y, int z, int bit) - { - if ((x < 0 || x >= mWidth) || (y < 0 || y >= mHeight) || (z < 0 || z >= mDepth) || (bit < 0 || bit >= 32)) - { + inline bool CellOutside(int x, int y, int z, int bit) { + if ((x < 0 || x >= mWidth) || (y < 0 || y >= mHeight) || (z < 0 || z >= mDepth) || (bit < 0 || bit >= 32)) { return !(mMarkedOutside); } - return (mMarkedOutside==(!!(mPointCache[((z * mWidth * mHeight) + (y * mWidth) + x)]&(1 << bit)))); + return (mMarkedOutside == (!!(mPointCache[((z * mWidth * mHeight) + (y * mWidth) + x)] & (1 << bit)))); } }; - ratl::vector_vs mWeatherZones; + ratl::vector_vs mWeatherZones; - -private: + private: //////////////////////////////////////////////////////////////////////////////////// // Iteration Variables //////////////////////////////////////////////////////////////////////////////////// - int mWCells; - int mHCells; - - int mXCell; - int mYCell; - int mZBit; - - int mXMax; - int mYMax; - int mZMax; + int mWCells; + int mHCells; + int mXCell; + int mYCell; + int mZBit; -private: - + int mXMax; + int mYMax; + int mZMax; + private: //////////////////////////////////////////////////////////////////////////////////// // Contents Outside //////////////////////////////////////////////////////////////////////////////////// - inline bool ContentsOutside(int contents) - { - if (contents&CONTENTS_WATER || contents&CONTENTS_SOLID) - { + inline bool ContentsOutside(int contents) { + if (contents & CONTENTS_WATER || contents & CONTENTS_SOLID) { return false; } - if (mCacheInit) - { - if (SWeatherZone::mMarkedOutside) - { - return (!!(contents&CONTENTS_OUTSIDE)); + if (mCacheInit) { + if (SWeatherZone::mMarkedOutside) { + return (!!(contents & CONTENTS_OUTSIDE)); } - return (!(contents&CONTENTS_INSIDE)); + return (!(contents & CONTENTS_INSIDE)); } - return !!(contents&CONTENTS_OUTSIDE); + return !!(contents & CONTENTS_OUTSIDE); } - - - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Constructor - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - void Reset() - { + void Reset() { mOutsideShake = false; mOutsidePain = 0.0; mCacheInit = false; @@ -558,41 +456,28 @@ class COutside mFogColorInt = 0; mFogColorTempActive = false; - for (int wz=0; wz> 5; + Wz.mWidth = (int)(Wz.mSize.mMaxs[0] - Wz.mSize.mMins[0]); + Wz.mHeight = (int)(Wz.mSize.mMaxs[1] - Wz.mSize.mMins[1]); + Wz.mDepth = ((int)(Wz.mSize.mMaxs[2] - Wz.mSize.mMins[2]) + 31) >> 5; Wz.miPointCacheByteSize = (Wz.mWidth * Wz.mHeight * Wz.mDepth) * sizeof(uint32_t); - Wz.mPointCache = (uint32_t *)R_Malloc( Wz.miPointCacheByteSize, TAG_POINTCACHE, qtrue ); - } - else - { - assert("MaxWeatherZones Hit!"==0); + Wz.mPointCache = (uint32_t *)R_Malloc(Wz.miPointCacheByteSize, TAG_POINTCACHE, qtrue); + } else { + assert("MaxWeatherZones Hit!" == 0); } } - const char *GenCachedWeatherFilename(void) - { - return va("maps/%s.weather", sv_mapname->string); - } + const char *GenCachedWeatherFilename(void) { return va("maps/%s.weather", sv_mapname->string); } // weather file format... // - struct WeatherFileHeader_t - { + struct WeatherFileHeader_t { int m_iVersion; int m_iChecksum; - WeatherFileHeader_t() - { - m_iVersion = COUTSIDE_STRUCT_VERSION; - m_iChecksum = sv_mapChecksum->integer; + WeatherFileHeader_t() { + m_iVersion = COUTSIDE_STRUCT_VERSION; + m_iChecksum = sv_mapChecksum->integer; } }; - fileHandle_t WriteCachedWeatherFile( void ) - { - fileHandle_t f = ri.FS_FOpenFileWrite( GenCachedWeatherFilename(), qtrue ); - if (f) - { + fileHandle_t WriteCachedWeatherFile(void) { + fileHandle_t f = ri.FS_FOpenFileWrite(GenCachedWeatherFilename(), qtrue); + if (f) { WeatherFileHeader_t WeatherFileHeader; - ri.FS_Write(&WeatherFileHeader, sizeof(WeatherFileHeader), f); + ri.FS_Write(&WeatherFileHeader, sizeof(WeatherFileHeader), f); return f; - } - else - { - ri.Printf( PRINT_WARNING, "(Unable to open weather file \"%s\" for writing!)\n",GenCachedWeatherFilename()); + } else { + ri.Printf(PRINT_WARNING, "(Unable to open weather file \"%s\" for writing!)\n", GenCachedWeatherFilename()); } return 0; @@ -656,12 +530,10 @@ class COutside // returns 0 for not-found or invalid file, else open handle to continue read from (which you then close yourself)... // - fileHandle_t ReadCachedWeatherFile( void ) - { + fileHandle_t ReadCachedWeatherFile(void) { fileHandle_t f = 0; - ri.FS_FOpenFileRead( GenCachedWeatherFilename(), &f, qfalse ); - if ( f ) - { + ri.FS_FOpenFileRead(GenCachedWeatherFilename(), &f, qfalse); + if (f) { // ok, it exists, but is it valid for this map?... // WeatherFileHeader_t WeatherFileHeaderForCompare; @@ -669,19 +541,16 @@ class COutside ri.FS_Read(&WeatherFileHeaderFromDisk, sizeof(WeatherFileHeaderFromDisk), f); - if (!memcmp(&WeatherFileHeaderForCompare, &WeatherFileHeaderFromDisk, sizeof(WeatherFileHeaderFromDisk))) - { + if (!memcmp(&WeatherFileHeaderForCompare, &WeatherFileHeaderFromDisk, sizeof(WeatherFileHeaderFromDisk))) { // go for it... // return f; } - ri.Printf( PRINT_WARNING, "( Cached weather file \"%s\" out of date, regenerating... )\n",GenCachedWeatherFilename()); - ri.FS_FCloseFile( f ); - } - else - { - ri.Printf( PRINT_WARNING, "( No cached weather file found, generating... )\n"); + ri.Printf(PRINT_WARNING, "( Cached weather file \"%s\" out of date, regenerating... )\n", GenCachedWeatherFilename()); + ri.FS_FCloseFile(f); + } else { + ri.Printf(PRINT_WARNING, "( No cached weather file found, generating... )\n"); } return 0; @@ -690,41 +559,33 @@ class COutside //////////////////////////////////////////////////////////////////////////////////// // Cache - Will Scan the World, Creating The Cache //////////////////////////////////////////////////////////////////////////////////// - void Cache() - { - if (!tr.world || mCacheInit) - { + void Cache() { + if (!tr.world || mCacheInit) { return; } // all this piece of code does really is fill in the bool "SWeatherZone::mMarkedOutside", plus the mPointCache[] for each zone, // so we can diskload those. Maybe. fileHandle_t f = ReadCachedWeatherFile(); - if ( f ) - { - for (int iZone=0; iZonebmodels[0].bounds[0], tr.world->bmodels[0].bounds[1]); } @@ -733,50 +594,39 @@ class COutside // Iterate Over All Weather Zones //-------------------------------- - for (int zone=0; zoneglobalFog != -1) - { +bool R_SetTempGlobalFogColor(vec3_t color) { + if (tr.world && tr.world->globalFog != -1) { // If Non Zero, Try To Set The Color //----------------------------------- - if (color[0] || color[1] || color[2]) - { + if (color[0] || color[1] || color[2]) { // Remember The Normal Fog Color //------------------------------- - if (!mOutside.mFogColorTempActive) - { - mOutside.mFogColor = tr.world->fogs[tr.world->globalFog].parms.color; - mOutside.mFogColorInt = tr.world->fogs[tr.world->globalFog].colorInt; - mOutside.mFogColorTempActive = true; + if (!mOutside.mFogColorTempActive) { + mOutside.mFogColor = tr.world->fogs[tr.world->globalFog].parms.color; + mOutside.mFogColorInt = tr.world->fogs[tr.world->globalFog].colorInt; + mOutside.mFogColorTempActive = true; } // Set The New One @@ -925,23 +741,19 @@ bool R_SetTempGlobalFogColor(vec3_t color) tr.world->fogs[tr.world->globalFog].parms.color[0] = color[0]; tr.world->fogs[tr.world->globalFog].parms.color[1] = color[1]; tr.world->fogs[tr.world->globalFog].parms.color[2] = color[2]; - tr.world->fogs[tr.world->globalFog].colorInt = ColorBytes4 ( - color[0] * tr.identityLight, - color[1] * tr.identityLight, - color[2] * tr.identityLight, - 1.0 ); + tr.world->fogs[tr.world->globalFog].colorInt = + ColorBytes4(color[0] * tr.identityLight, color[1] * tr.identityLight, color[2] * tr.identityLight, 1.0); } // If Unable TO Parse The Command Color Vector, Restore The Previous Fog Color //----------------------------------------------------------------------------- - else if (mOutside.mFogColorTempActive) - { + else if (mOutside.mFogColorTempActive) { mOutside.mFogColorTempActive = false; tr.world->fogs[tr.world->globalFog].parms.color[0] = mOutside.mFogColor[0]; tr.world->fogs[tr.world->globalFog].parms.color[1] = mOutside.mFogColor[1]; tr.world->fogs[tr.world->globalFog].parms.color[2] = mOutside.mFogColor[2]; - tr.world->fogs[tr.world->globalFog].colorInt = mOutside.mFogColorInt; + tr.world->fogs[tr.world->globalFog].colorInt = mOutside.mFogColorInt; } } return true; @@ -950,186 +762,166 @@ bool R_SetTempGlobalFogColor(vec3_t color) //////////////////////////////////////////////////////////////////////////////////////// // Particle Cloud //////////////////////////////////////////////////////////////////////////////////////// -class CParticleCloud -{ -private: +class CParticleCloud { + private: //////////////////////////////////////////////////////////////////////////////////// // DYNAMIC MEMORY //////////////////////////////////////////////////////////////////////////////////// - image_t* mImage; - WFXParticle* mParticles; + image_t *mImage; + WFXParticle *mParticles; -private: + private: //////////////////////////////////////////////////////////////////////////////////// // RUN TIME VARIANTS //////////////////////////////////////////////////////////////////////////////////// - float mSpawnSpeed; - CVec3 mSpawnPlaneNorm; - CVec3 mSpawnPlaneRight; - CVec3 mSpawnPlaneUp; - SVecRange mRange; - - CVec3 mCameraPosition; - CVec3 mCameraForward; - CVec3 mCameraLeft; - CVec3 mCameraDown; - CVec3 mCameraLeftPlusUp; - CVec3 mCameraLeftMinusUp; - + float mSpawnSpeed; + CVec3 mSpawnPlaneNorm; + CVec3 mSpawnPlaneRight; + CVec3 mSpawnPlaneUp; + SVecRange mRange; - int mParticleCountRender; - int mGLModeEnum; + CVec3 mCameraPosition; + CVec3 mCameraForward; + CVec3 mCameraLeft; + CVec3 mCameraDown; + CVec3 mCameraLeftPlusUp; + CVec3 mCameraLeftMinusUp; - bool mPopulated; + int mParticleCountRender; + int mGLModeEnum; + bool mPopulated; -public: + public: //////////////////////////////////////////////////////////////////////////////////// // CONSTANTS //////////////////////////////////////////////////////////////////////////////////// - bool mOrientWithVelocity; - float mSpawnPlaneSize; - float mSpawnPlaneDistance; - SVecRange mSpawnRange; + bool mOrientWithVelocity; + float mSpawnPlaneSize; + float mSpawnPlaneDistance; + SVecRange mSpawnRange; - float mGravity; // How much gravity affects the velocity of a particle - CVec4 mColor; // RGBA color - int mVertexCount; // 3 for triangle, 4 for quad, other numbers not supported + float mGravity; // How much gravity affects the velocity of a particle + CVec4 mColor; // RGBA color + int mVertexCount; // 3 for triangle, 4 for quad, other numbers not supported - float mWidth; - float mHeight; + float mWidth; + float mHeight; - int mBlendMode; // 0 = ALPHA, 1 = SRC->SRC - int mFilterMode; // 0 = LINEAR, 1 = NEAREST + int mBlendMode; // 0 = ALPHA, 1 = SRC->SRC + int mFilterMode; // 0 = LINEAR, 1 = NEAREST - float mFade; // How much to fade in and out 1.0 = instant, 0.01 = very slow + float mFade; // How much to fade in and out 1.0 = instant, 0.01 = very slow - SFloatRange mRotation; - float mRotationDelta; - float mRotationDeltaTarget; - float mRotationCurrent; - SIntRange mRotationChangeTimer; - int mRotationChangeNext; + SFloatRange mRotation; + float mRotationDelta; + float mRotationDeltaTarget; + float mRotationCurrent; + SIntRange mRotationChangeTimer; + int mRotationChangeNext; - SFloatRange mMass; // Determines how slowness to accelerate, higher number = slower - float mFrictionInverse; // How much air friction does this particle have 1.0=none, 0.0=nomove + SFloatRange mMass; // Determines how slowness to accelerate, higher number = slower + float mFrictionInverse; // How much air friction does this particle have 1.0=none, 0.0=nomove - int mParticleCount; + int mParticleCount; - bool mWaterParticles; + bool mWaterParticles; - - - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize - Create Image, Particles, And Setup All Values //////////////////////////////////////////////////////////////////////////////////// - void Initialize(int count, const char* texturePath, int VertexCount=4) - { + void Initialize(int count, const char *texturePath, int VertexCount = 4) { Reset(); - assert(mParticleCount==0 && mParticles==0); - assert(mImage==0); + assert(mParticleCount == 0 && mParticles == 0); + assert(mImage == 0); // Create The Image //------------------ mImage = R_FindImageFile(texturePath, qfalse, qfalse, qfalse, GL_CLAMP); - if (!mImage) - { + if (!mImage) { Com_Error(ERR_DROP, "CParticleCloud: Could not texture %s", texturePath); } GL_Bind(mImage); - - // Create The Particles //---------------------- - mParticleCount = count; - mParticles = new WFXParticle[mParticleCount]; - + mParticleCount = count; + mParticles = new WFXParticle[mParticleCount]; - - WFXParticle* part=0; - for (int particleNum=0; particleNummPosition.Clear(); part->mVelocity.Clear(); - part->mAlpha = 0.0f; + part->mAlpha = 0.0f; mMass.Pick(part->mMass); } mVertexCount = VertexCount; - mGLModeEnum = (mVertexCount==3)?(GL_TRIANGLES):(GL_QUADS); + mGLModeEnum = (mVertexCount == 3) ? (GL_TRIANGLES) : (GL_QUADS); } - //////////////////////////////////////////////////////////////////////////////////// // Reset - Initializes all data to default values //////////////////////////////////////////////////////////////////////////////////// - void Reset() - { - if (mImage) - { + void Reset() { + if (mImage) { // TODO: Free Image? } - mImage = 0; - if (mParticleCount) - { - delete [] mParticles; + mImage = 0; + if (mParticleCount) { + delete[] mParticles; } - mParticleCount = 0; - mParticles = 0; - - mPopulated = 0; - + mParticleCount = 0; + mParticles = 0; + mPopulated = 0; // These Are The Default Startup Values For Constant Data //======================================================== mOrientWithVelocity = false; - mWaterParticles = false; + mWaterParticles = false; - mSpawnPlaneDistance = 500; - mSpawnPlaneSize = 500; - mSpawnRange.mMins = -(mSpawnPlaneDistance*1.25f); - mSpawnRange.mMaxs = (mSpawnPlaneDistance*1.25f); + mSpawnPlaneDistance = 500; + mSpawnPlaneSize = 500; + mSpawnRange.mMins = -(mSpawnPlaneDistance * 1.25f); + mSpawnRange.mMaxs = (mSpawnPlaneDistance * 1.25f); - mGravity = 300.0f; // Units Per Second + mGravity = 300.0f; // Units Per Second - mColor = 1.0f; + mColor = 1.0f; - mVertexCount = 4; - mWidth = 1.0f; - mHeight = 1.0f; + mVertexCount = 4; + mWidth = 1.0f; + mHeight = 1.0f; - mBlendMode = 0; - mFilterMode = 0; + mBlendMode = 0; + mFilterMode = 0; - mFade = 10.0f; + mFade = 10.0f; mRotation.Clear(); - mRotationDelta = 0.0f; - mRotationDeltaTarget= 0.0f; - mRotationCurrent = 0.0f; - mRotationChangeNext = -1; - mRotation.mMin = -0.7f; - mRotation.mMax = 0.7f; + mRotationDelta = 0.0f; + mRotationDeltaTarget = 0.0f; + mRotationCurrent = 0.0f; + mRotationChangeNext = -1; + mRotation.mMin = -0.7f; + mRotation.mMax = 0.7f; mRotationChangeTimer.mMin = 500; mRotationChangeTimer.mMax = 2000; - mMass.mMin = 5.0f; - mMass.mMax = 10.0f; + mMass.mMin = 5.0f; + mMass.mMax = 10.0f; - mFrictionInverse = 0.7f; // No Friction? + mFrictionInverse = 0.7f; // No Friction? } //////////////////////////////////////////////////////////////////////////////////// // Constructor - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - CParticleCloud() - { + CParticleCloud() { mImage = 0; mParticleCount = 0; Reset(); @@ -1138,89 +930,72 @@ class CParticleCloud //////////////////////////////////////////////////////////////////////////////////// // Initialize - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - ~CParticleCloud() - { - Reset(); - } - + ~CParticleCloud() { Reset(); } //////////////////////////////////////////////////////////////////////////////////// // UseSpawnPlane - Check To See If We Should Spawn On A Plane, Or Just Wrap The Box //////////////////////////////////////////////////////////////////////////////////// - inline bool UseSpawnPlane() - { - return (mGravity!=0.0f); - } - + inline bool UseSpawnPlane() { return (mGravity != 0.0f); } //////////////////////////////////////////////////////////////////////////////////// // Update - Applies All Physics Forces To All Contained Particles //////////////////////////////////////////////////////////////////////////////////// - void Update() - { - WFXParticle* part=0; - CVec3 partForce; - CVec3 partMoved; - CVec3 partToCamera; - bool partRendering; - bool partOutside; - bool partInRange; - bool partInView; - int particleNum; - float particleFade = (mFade * mSecondsElapsed); - int numLocalWindZones = mLocalWindZones.size(); - int curLocalWindZone; - + void Update() { + WFXParticle *part = 0; + CVec3 partForce; + CVec3 partMoved; + CVec3 partToCamera; + bool partRendering; + bool partOutside; + bool partInRange; + bool partInView; + int particleNum; + float particleFade = (mFade * mSecondsElapsed); + int numLocalWindZones = mLocalWindZones.size(); + int curLocalWindZone; // Compute Camera //---------------- { - mCameraPosition = backEnd.viewParms.ori.origin; - mCameraForward = backEnd.viewParms.ori.axis[0]; - mCameraLeft = backEnd.viewParms.ori.axis[1]; - mCameraDown = backEnd.viewParms.ori.axis[2]; + mCameraPosition = backEnd.viewParms.ori.origin; + mCameraForward = backEnd.viewParms.ori.axis[0]; + mCameraLeft = backEnd.viewParms.ori.axis[1]; + mCameraDown = backEnd.viewParms.ori.axis[2]; - if (mRotationChangeNext!=-1) - { - if (mRotationChangeNext==0) - { + if (mRotationChangeNext != -1) { + if (mRotationChangeNext == 0) { mRotation.Pick(mRotationDeltaTarget); mRotationChangeTimer.Pick(mRotationChangeNext); - if (mRotationChangeNext<=0) - { + if (mRotationChangeNext <= 0) { mRotationChangeNext = 1; } } mRotationChangeNext--; - float RotationDeltaDifference = (mRotationDeltaTarget - mRotationDelta); - if (fabsf(RotationDeltaDifference)>0.01) - { - mRotationDelta += RotationDeltaDifference; // Blend To New Delta + float RotationDeltaDifference = (mRotationDeltaTarget - mRotationDelta); + if (fabsf(RotationDeltaDifference) > 0.01) { + mRotationDelta += RotationDeltaDifference; // Blend To New Delta } - mRotationCurrent += (mRotationDelta * mSecondsElapsed); + mRotationCurrent += (mRotationDelta * mSecondsElapsed); float s = sinf(mRotationCurrent); float c = cosf(mRotationCurrent); - CVec3 TempCamLeft(mCameraLeft); + CVec3 TempCamLeft(mCameraLeft); mCameraLeft *= (c * mWidth); mCameraLeft.ScaleAdd(mCameraDown, (s * mWidth * -1.0f)); mCameraDown *= (c * mHeight); mCameraDown.ScaleAdd(TempCamLeft, (s * mHeight)); - } - else - { - mCameraLeft *= mWidth; - mCameraDown *= mHeight; + } else { + mCameraLeft *= mWidth; + mCameraDown *= mHeight; } } - // Compute Global Force //---------------------- - CVec3 force; + CVec3 force; { force.Clear(); @@ -1230,10 +1005,9 @@ class CParticleCloud // Apply Wind Velocity //--------------------- - force += mGlobalWindVelocity; + force += mGlobalWindVelocity; } - // Update Range //-------------- { @@ -1242,68 +1016,52 @@ class CParticleCloud // If Using A Spawn Plane, Increase The Range Box A Bit To Account For Rotation On The Spawn Plane //------------------------------------------------------------------------------------------------- - if (UseSpawnPlane()) - { - for (int dim=0; dim<3; dim++) - { - if (force[dim]>0.01) - { - mRange.mMins[dim] -= (mSpawnPlaneDistance/2.0f); - } - else if (force[dim]<-0.01) - { - mRange.mMaxs[dim] += (mSpawnPlaneDistance/2.0f); + if (UseSpawnPlane()) { + for (int dim = 0; dim < 3; dim++) { + if (force[dim] > 0.01) { + mRange.mMins[dim] -= (mSpawnPlaneDistance / 2.0f); + } else if (force[dim] < -0.01) { + mRange.mMaxs[dim] += (mSpawnPlaneDistance / 2.0f); } } - mSpawnPlaneNorm = force; - mSpawnSpeed = VectorNormalize(mSpawnPlaneNorm.v); + mSpawnPlaneNorm = force; + mSpawnSpeed = VectorNormalize(mSpawnPlaneNorm.v); MakeNormalVectors(mSpawnPlaneNorm.v, mSpawnPlaneRight.v, mSpawnPlaneUp.v); } // Optimization For Quad Position Calculation //-------------------------------------------- - if (mVertexCount==4) - { - mCameraLeftPlusUp = (mCameraLeft - mCameraDown); + if (mVertexCount == 4) { + mCameraLeftPlusUp = (mCameraLeft - mCameraDown); mCameraLeftMinusUp = (mCameraLeft + mCameraDown); - } - else - { - mCameraLeftPlusUp = (mCameraDown + mCameraLeft); // should really be called mCamera Left + Down + } else { + mCameraLeftPlusUp = (mCameraDown + mCameraLeft); // should really be called mCamera Left + Down } } // Stop All Additional Processing //-------------------------------- - if (mFrozen) - { + if (mFrozen) { return; } - - // Now Update All Particles //-------------------------- mParticleCountRender = 0; - for (particleNum=0; particleNummPosition); // First Time Spawn Location + if (!mPopulated) { + mRange.Pick(part->mPosition); // First Time Spawn Location } // Grab The Force And Apply Non Global Wind //------------------------------------------ partForce = force; - if (numLocalWindZones) - { - for (curLocalWindZone=0; curLocalWindZonemRBounds.In(part->mPosition)) - { + if (numLocalWindZones) { + for (curLocalWindZone = 0; curLocalWindZone < numLocalWindZones; curLocalWindZone++) { + if (mLocalWindZones[curLocalWindZone]->mRBounds.In(part->mPosition)) { partForce += mLocalWindZones[curLocalWindZone]->mCurrentVelocity; } } @@ -1311,40 +1069,36 @@ class CParticleCloud partForce /= part->mMass; - // Apply The Force //----------------- - part->mVelocity += partForce; - part->mVelocity *= mFrictionInverse; + part->mVelocity += partForce; + part->mVelocity *= mFrictionInverse; part->mPosition.ScaleAdd(part->mVelocity, mSecondsElapsed); - partToCamera = (part->mPosition - mCameraPosition); - partRendering = part->mFlags.get_bit(WFXParticle::FLAG_RENDER); - partOutside = mOutside.PointOutside(part->mPosition, mWidth, mHeight); - partInRange = mRange.In(part->mPosition); - partInView = (partOutside && partInRange && (partToCamera.Dot(mCameraForward)>0.0f)); + partToCamera = (part->mPosition - mCameraPosition); + partRendering = part->mFlags.get_bit(WFXParticle::FLAG_RENDER); + partOutside = mOutside.PointOutside(part->mPosition, mWidth, mHeight); + partInRange = mRange.In(part->mPosition); + partInView = (partOutside && partInRange && (partToCamera.Dot(mCameraForward) > 0.0f)); // Process Respawn //----------------- - if (!partInRange && !partRendering) - { + if (!partInRange && !partRendering) { part->mVelocity.Clear(); // Reselect A Position On The Spawn Plane //---------------------------------------- - if (UseSpawnPlane()) - { - part->mPosition = mCameraPosition; - part->mPosition -= (mSpawnPlaneNorm* mSpawnPlaneDistance); - part->mPosition += (mSpawnPlaneRight*Q_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); - part->mPosition += (mSpawnPlaneUp* Q_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); + if (UseSpawnPlane()) { + part->mPosition = mCameraPosition; + part->mPosition -= (mSpawnPlaneNorm * mSpawnPlaneDistance); + part->mPosition += (mSpawnPlaneRight * Q_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); + part->mPosition += (mSpawnPlaneUp * Q_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); } // Otherwise, Just Wrap Around To The Other End Of The Range //----------------------------------------------------------- - else - { + else { mRange.Wrap(part->mPosition); } partInRange = true; @@ -1355,24 +1109,21 @@ class CParticleCloud { // Start A Fade Out //------------------ - if (partRendering && !partInView) - { + if (partRendering && !partInView) { part->mFlags.clear_bit(WFXParticle::FLAG_FADEIN); part->mFlags.set_bit(WFXParticle::FLAG_FADEOUT); } // Switch From Fade Out To Fade In //--------------------------------- - else if (partRendering && partInView && part->mFlags.get_bit(WFXParticle::FLAG_FADEOUT)) - { + else if (partRendering && partInView && part->mFlags.get_bit(WFXParticle::FLAG_FADEOUT)) { part->mFlags.set_bit(WFXParticle::FLAG_FADEIN); part->mFlags.clear_bit(WFXParticle::FLAG_FADEOUT); } // Start A Fade In //----------------- - else if (!partRendering && partInView) - { + else if (!partRendering && partInView) { partRendering = true; part->mAlpha = 0.0f; part->mFlags.set_bit(WFXParticle::FLAG_RENDER); @@ -1382,16 +1133,13 @@ class CParticleCloud // Update Fade //------------- - if (partRendering) - { + if (partRendering) { // Update Fade Out //----------------- - if (part->mFlags.get_bit(WFXParticle::FLAG_FADEOUT)) - { + if (part->mFlags.get_bit(WFXParticle::FLAG_FADEOUT)) { part->mAlpha -= particleFade; - if (part->mAlpha<=0.0f) - { + if (part->mAlpha <= 0.0f) { part->mAlpha = 0.0f; part->mFlags.clear_bit(WFXParticle::FLAG_FADEOUT); part->mFlags.clear_bit(WFXParticle::FLAG_FADEIN); @@ -1402,11 +1150,9 @@ class CParticleCloud // Update Fade In //---------------- - else if (part->mFlags.get_bit(WFXParticle::FLAG_FADEIN)) - { + else if (part->mFlags.get_bit(WFXParticle::FLAG_FADEIN)) { part->mAlpha += particleFade; - if (part->mAlpha>=mColor[3]) - { + if (part->mAlpha >= mColor[3]) { part->mFlags.clear_bit(WFXParticle::FLAG_FADEIN); part->mAlpha = mColor[3]; } @@ -1416,9 +1162,8 @@ class CParticleCloud // Keep Track Of The Number Of Particles To Render //------------------------------------------------- - if (part->mFlags.get_bit(WFXParticle::FLAG_RENDER)) - { - mParticleCountRender ++; + if (part->mFlags.get_bit(WFXParticle::FLAG_RENDER)) { + mParticleCountRender++; } } mPopulated = true; @@ -1427,126 +1172,96 @@ class CParticleCloud //////////////////////////////////////////////////////////////////////////////////// // Render - //////////////////////////////////////////////////////////////////////////////////// - void Render() - { - WFXParticle* part=0; - int particleNum; - CVec3 partDirection; - + void Render() { + WFXParticle *part = 0; + int particleNum; + CVec3 partDirection; // Set The GL State And Image Binding //------------------------------------ - GL_State((mBlendMode==0)?(GLS_ALPHA):(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)); + GL_State((mBlendMode == 0) ? (GLS_ALPHA) : (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)); GL_Bind(mImage); - // Enable And Disable Things //--------------------------- qglEnable(GL_TEXTURE_2D); qglDisable(GL_CULL_FACE); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (mFilterMode==0)?(GL_LINEAR):(GL_NEAREST)); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (mFilterMode==0)?(GL_LINEAR):(GL_NEAREST)); - + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (mFilterMode == 0) ? (GL_LINEAR) : (GL_NEAREST)); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (mFilterMode == 0) ? (GL_LINEAR) : (GL_NEAREST)); // Setup Matrix Mode And Translation //----------------------------------- qglMatrixMode(GL_MODELVIEW); qglPushMatrix(); - // Begin //------- qglBegin(mGLModeEnum); - for (particleNum=0; particleNummFlags.get_bit(WFXParticle::FLAG_RENDER)) - { + if (!part->mFlags.get_bit(WFXParticle::FLAG_RENDER)) { continue; } // If Oriented With Velocity, We Want To Calculate Vertx Offsets Differently For Each Particle //--------------------------------------------------------------------------------------------- - if (mOrientWithVelocity) - { + if (mOrientWithVelocity) { partDirection = part->mVelocity; VectorNormalize(partDirection.v); mCameraDown = partDirection; mCameraDown *= (mHeight * -1); - if (mVertexCount==4) - { - mCameraLeftPlusUp = (mCameraLeft - mCameraDown); + if (mVertexCount == 4) { + mCameraLeftPlusUp = (mCameraLeft - mCameraDown); mCameraLeftMinusUp = (mCameraLeft + mCameraDown); - } - else - { - mCameraLeftPlusUp = (mCameraDown + mCameraLeft); + } else { + mCameraLeftPlusUp = (mCameraDown + mCameraLeft); } } // Blend Mode Zero -> Apply Alpha Just To Alpha Channel //------------------------------------------------------ - if (mBlendMode==0) - { + if (mBlendMode == 0) { qglColor4f(mColor[0], mColor[1], mColor[2], part->mAlpha); } // Otherwise Apply Alpha To All Channels //--------------------------------------- - else - { - qglColor4f(mColor[0]*part->mAlpha, mColor[1]*part->mAlpha, mColor[2]*part->mAlpha, mColor[3]*part->mAlpha); + else { + qglColor4f(mColor[0] * part->mAlpha, mColor[1] * part->mAlpha, mColor[2] * part->mAlpha, mColor[3] * part->mAlpha); } - // Render A Triangle //------------------- - if (mVertexCount==3) - { - qglTexCoord2f(1.0, 0.0); - qglVertex3f(part->mPosition[0], - part->mPosition[1], - part->mPosition[2]); + if (mVertexCount == 3) { + qglTexCoord2f(1.0, 0.0); + qglVertex3f(part->mPosition[0], part->mPosition[1], part->mPosition[2]); qglTexCoord2f(0.0, 1.0); - qglVertex3f(part->mPosition[0] + mCameraLeft[0], - part->mPosition[1] + mCameraLeft[1], - part->mPosition[2] + mCameraLeft[2]); + qglVertex3f(part->mPosition[0] + mCameraLeft[0], part->mPosition[1] + mCameraLeft[1], part->mPosition[2] + mCameraLeft[2]); qglTexCoord2f(0.0, 0.0); - qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], - part->mPosition[1] + mCameraLeftPlusUp[1], - part->mPosition[2] + mCameraLeftPlusUp[2]); + qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], part->mPosition[1] + mCameraLeftPlusUp[1], part->mPosition[2] + mCameraLeftPlusUp[2]); } // Render A Quad //--------------- - else - { + else { // Left bottom. - qglTexCoord2f( 0.0, 0.0 ); - qglVertex3f(part->mPosition[0] - mCameraLeftMinusUp[0], - part->mPosition[1] - mCameraLeftMinusUp[1], - part->mPosition[2] - mCameraLeftMinusUp[2] ); + qglTexCoord2f(0.0, 0.0); + qglVertex3f(part->mPosition[0] - mCameraLeftMinusUp[0], part->mPosition[1] - mCameraLeftMinusUp[1], part->mPosition[2] - mCameraLeftMinusUp[2]); // Right bottom. - qglTexCoord2f( 1.0, 0.0 ); - qglVertex3f(part->mPosition[0] - mCameraLeftPlusUp[0], - part->mPosition[1] - mCameraLeftPlusUp[1], - part->mPosition[2] - mCameraLeftPlusUp[2] ); + qglTexCoord2f(1.0, 0.0); + qglVertex3f(part->mPosition[0] - mCameraLeftPlusUp[0], part->mPosition[1] - mCameraLeftPlusUp[1], part->mPosition[2] - mCameraLeftPlusUp[2]); // Right top. - qglTexCoord2f( 1.0, 1.0 ); - qglVertex3f(part->mPosition[0] + mCameraLeftMinusUp[0], - part->mPosition[1] + mCameraLeftMinusUp[1], - part->mPosition[2] + mCameraLeftMinusUp[2] ); + qglTexCoord2f(1.0, 1.0); + qglVertex3f(part->mPosition[0] + mCameraLeftMinusUp[0], part->mPosition[1] + mCameraLeftMinusUp[1], part->mPosition[2] + mCameraLeftMinusUp[2]); // Left top. - qglTexCoord2f( 0.0, 1.0 ); - qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], - part->mPosition[1] + mCameraLeftPlusUp[1], - part->mPosition[2] + mCameraLeftPlusUp[2] ); + qglTexCoord2f(0.0, 1.0); + qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], part->mPosition[1] + mCameraLeftPlusUp[1], part->mPosition[2] + mCameraLeftPlusUp[2]); } } qglEnd(); @@ -1557,17 +1272,13 @@ class CParticleCloud mParticlesRendered += mParticleCountRender; } }; -ratl::vector_vs mParticleClouds; - - +ratl::vector_vs mParticleClouds; //////////////////////////////////////////////////////////////////////////////////////// // Init World Effects - Will Iterate Over All Particle Clouds, Clear Them Out, And Erase //////////////////////////////////////////////////////////////////////////////////////// -void R_InitWorldEffects(void) -{ - for (int i=0; i1000.0f) - { + if (mMillisecondsElapsed > 1000.0f) { mMillisecondsElapsed = 1000.0f; } mSecondsElapsed = (mMillisecondsElapsed / 1000.0f); - // Make Sure We Are Always Outside Cached //---------------------------------------- - if (!mOutside.Initialized()) - { + if (!mOutside.Initialized()) { mOutside.Cache(); - } - else - { + } else { // Update All Wind Zones //----------------------- - if (!mFrozen) - { + if (!mFrozen) { mGlobalWindVelocity.Clear(); - for (int wz=0; wz. // This vertex shader basically passes through most values and calculates no lighting. The only // unusual thing it does is add the inputed texel offsets to all four texture units (this allows // nearest neighbor pixel peeking). -const unsigned char g_strGlowVShaderARB[] = -{ - "!!ARBvp1.0\ +const unsigned char g_strGlowVShaderARB[] = {"!!ARBvp1.0\ \ # Input.\n\ ATTRIB iPos = vertex.position;\ @@ -69,14 +67,11 @@ const unsigned char g_strGlowVShaderARB[] = ADD oTex2, iTex0, TexelOffset2;\ ADD oTex3, iTex0, TexelOffset3;\ \ - END" -}; + END"}; // This Pixel Shader loads four texture units and adds them all together (with a modifier // multiplied to each in the process). The final output is r0 = t0 + t1 + t2 + t3. -const unsigned char g_strGlowPShaderARB[] = -{ - "!!ARBfp1.0\ +const unsigned char g_strGlowPShaderARB[] = {"!!ARBfp1.0\ \ # Input.\n\ ATTRIB iColor = fragment.color.primary;\ @@ -105,25 +100,23 @@ const unsigned char g_strGlowPShaderARB[] = \ MOV oColor, r0;\ \ - END" -}; + END"}; /***********************************************************************************************************/ -#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 -#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B void ARB_InitGlowShaders(void) { // Allocate and Load the global 'Glow' Vertex Program. - AReis - if ( qglGenProgramsARB ) - { - qglGenProgramsARB( 1, &tr.glowVShader ); - qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, tr.glowVShader ); - qglProgramStringARB( GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, ( GLsizei ) strlen( ( char * ) g_strGlowVShaderARB ), g_strGlowVShaderARB ); + if (qglGenProgramsARB) { + qglGenProgramsARB(1, &tr.glowVShader); + qglBindProgramARB(GL_VERTEX_PROGRAM_ARB, tr.glowVShader); + qglProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen((char *)g_strGlowVShaderARB), g_strGlowVShaderARB); -// const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); + // const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); int iErrPos = 0; - qglGetIntegerv( GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos ); - assert( iErrPos == -1 ); + qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos); + assert(iErrPos == -1); } // NOTE: I make an assumption here. If you have (current) nvidia hardware, you obviously support register combiners instead of fragment @@ -131,8 +124,7 @@ void ARB_InitGlowShaders(void) { // if you always ask for regcoms before fragment shaders, you'll always just use regcoms (problem solved... for now). - AReis // Load Pixel Shaders (either regcoms or fragprogs). - if ( qglCombinerParameteriNV ) - { + if (qglCombinerParameteriNV) { // The purpose of this regcom is to blend all the pixels together from the 4 texture units, but with their // texture coordinates offset by 1 (or more) texels, effectively letting us blend adjoining pixels. The weight is // used to either strengthen or weaken the pixel intensity. The more it diffuses (the higher the radius of the glow), @@ -153,40 +145,38 @@ void ARB_InitGlowShaders(void) { madd r0, c0, t2, r0; madd r0, c0, t3, r0; */ - tr.glowPShader = qglGenLists( 1 ); - qglNewList( tr.glowPShader, GL_COMPILE ); - qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 2 ); - - // spare0 = fBlend * tex0 + fBlend * tex1. - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); - - // spare1 = fBlend * tex2 + fBlend * tex3. - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE1_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); - - // ( A * B ) + ( ( 1 - A ) * C ) + D = ( spare0 * 1 ) + ( ( 1 - spare0 ) * 0 ) + spare1 == spare0 + spare1. - qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); + tr.glowPShader = qglGenLists(1); + qglNewList(tr.glowPShader, GL_COMPILE); + qglCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, 2); + + // spare0 = fBlend * tex0 + fBlend * tex1. + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); + + // spare1 = fBlend * tex2 + fBlend * tex3. + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerOutputNV(GL_COMBINER1_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE1_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); + + // ( A * B ) + ( ( 1 - A ) * C ) + D = ( spare0 * 1 ) + ( ( 1 - spare0 ) * 0 ) + spare1 == spare0 + spare1. + qglFinalCombinerInputNV(GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_D_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); qglEndList(); - } - else if ( qglGenProgramsARB ) - { - qglGenProgramsARB( 1, &tr.glowPShader ); - qglBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader ); - qglProgramStringARB( GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, ( GLsizei ) strlen( ( char * ) g_strGlowPShaderARB ), g_strGlowPShaderARB ); + } else if (qglGenProgramsARB) { + qglGenProgramsARB(1, &tr.glowPShader); + qglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader); + qglProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen((char *)g_strGlowPShaderARB), g_strGlowPShaderARB); -// const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); + // const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); int iErrPos = 0; - qglGetIntegerv( GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos ); - assert( iErrPos == -1 ); + qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos); + assert(iErrPos == -1); } } diff --git a/code/rd-vanilla/tr_backend.cpp b/code/rd-vanilla/tr_backend.cpp index 741bb95b17..2f6bd2cf42 100644 --- a/code/rd-vanilla/tr_backend.cpp +++ b/code/rd-vanilla/tr_backend.cpp @@ -26,14 +26,14 @@ along with this program; if not, see . #include "tr_local.h" #include "tr_common.h" -backEndData_t *backEndData; -backEndState_t backEnd; +backEndData_t *backEndData; +backEndState_t backEnd; bool tr_stencilled = false; -extern qboolean tr_distortionPrePost; //tr_shadows.cpp -extern qboolean tr_distortionNegate; //tr_shadows.cpp -extern void RB_CaptureScreenImage(void); //tr_shadows.cpp -extern void RB_DistortionFill(void); //tr_shadows.cpp +extern qboolean tr_distortionPrePost; // tr_shadows.cpp +extern qboolean tr_distortionNegate; // tr_shadows.cpp +extern void RB_CaptureScreenImage(void); // tr_shadows.cpp +extern void RB_DistortionFill(void); // tr_shadows.cpp static void RB_DrawGlowOverlay(); static void RB_BlurGlowTexture(); @@ -46,123 +46,95 @@ bool g_bDynamicGlowSupported = false; static const float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; - + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; /* ** GL_Bind */ -void GL_Bind( image_t *image ) { +void GL_Bind(image_t *image) { int texnum; - if ( !image ) { - ri.Printf( PRINT_WARNING, "GL_Bind: NULL image\n" ); + if (!image) { + ri.Printf(PRINT_WARNING, "GL_Bind: NULL image\n"); texnum = tr.defaultImage->texnum; } else { texnum = image->texnum; } - if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option + if (r_nobind->integer && tr.dlightImage) { // performance evaluation option texnum = tr.dlightImage->texnum; } - if ( glState.currenttextures[glState.currenttmu] != texnum ) { + if (glState.currenttextures[glState.currenttmu] != texnum) { image->frameUsed = tr.frameCount; glState.currenttextures[glState.currenttmu] = texnum; - qglBindTexture (GL_TEXTURE_2D, texnum); + qglBindTexture(GL_TEXTURE_2D, texnum); } } /* ** GL_SelectTexture */ -void GL_SelectTexture( int unit ) -{ - if ( glState.currenttmu == unit ) - { +void GL_SelectTexture(int unit) { + if (glState.currenttmu == unit) { return; } - if ( unit == 0 ) - { - qglActiveTextureARB( GL_TEXTURE0_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE0_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE0_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE0_ARB )\n" ); - } - else if ( unit == 1 ) - { - qglActiveTextureARB( GL_TEXTURE1_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE1_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE1_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE1_ARB )\n" ); - } - else if ( unit == 2 ) - { - qglActiveTextureARB( GL_TEXTURE2_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE2_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE2_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE2_ARB )\n" ); - } - else if ( unit == 3 ) - { - qglActiveTextureARB( GL_TEXTURE3_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE3_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE3_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE3_ARB )\n" ); - } - else { - Com_Error( ERR_DROP, "GL_SelectTexture: unit = %i", unit ); + if (unit == 0) { + qglActiveTextureARB(GL_TEXTURE0_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE0_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE0_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE0_ARB )\n"); + } else if (unit == 1) { + qglActiveTextureARB(GL_TEXTURE1_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE1_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE1_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE1_ARB )\n"); + } else if (unit == 2) { + qglActiveTextureARB(GL_TEXTURE2_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE2_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE2_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE2_ARB )\n"); + } else if (unit == 3) { + qglActiveTextureARB(GL_TEXTURE3_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE3_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE3_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE3_ARB )\n"); + } else { + Com_Error(ERR_DROP, "GL_SelectTexture: unit = %i", unit); } glState.currenttmu = unit; } - /* ** GL_Cull */ -void GL_Cull( int cullType ) { - if ( glState.faceCulling == cullType ) { +void GL_Cull(int cullType) { + if (glState.faceCulling == cullType) { return; } glState.faceCulling = cullType; - if (backEnd.projection2D){ //don't care, we're in 2d when it's always disabled + if (backEnd.projection2D) { // don't care, we're in 2d when it's always disabled return; } - if ( cullType == CT_TWO_SIDED ) - { - qglDisable( GL_CULL_FACE ); - } - else - { - qglEnable( GL_CULL_FACE ); + if (cullType == CT_TWO_SIDED) { + qglDisable(GL_CULL_FACE); + } else { + qglEnable(GL_CULL_FACE); - if ( cullType == CT_BACK_SIDED ) - { - if ( backEnd.viewParms.isMirror ) - { - qglCullFace( GL_FRONT ); - } - else - { - qglCullFace( GL_BACK ); - } - } - else - { - if ( backEnd.viewParms.isMirror ) - { - qglCullFace( GL_BACK ); + if (cullType == CT_BACK_SIDED) { + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_FRONT); + } else { + qglCullFace(GL_BACK); } - else - { - qglCullFace( GL_FRONT ); + } else { + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_BACK); + } else { + qglCullFace(GL_FRONT); } } } @@ -171,32 +143,28 @@ void GL_Cull( int cullType ) { /* ** GL_TexEnv */ -void GL_TexEnv( int env ) -{ - if ( env == glState.texEnv[glState.currenttmu] ) - { +void GL_TexEnv(int env) { + if (env == glState.texEnv[glState.currenttmu]) { return; } glState.texEnv[glState.currenttmu] = env; - - switch ( env ) - { + switch (env) { case GL_MODULATE: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); break; case GL_REPLACE: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); break; case GL_DECAL: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); break; case GL_ADD: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); break; default: - Com_Error( ERR_DROP, "GL_TexEnv: invalid env '%d' passed\n", env ); + Com_Error(ERR_DROP, "GL_TexEnv: invalid env '%d' passed\n", env); break; } } @@ -207,41 +175,32 @@ void GL_TexEnv( int env ) ** This routine is responsible for setting the most commonly changed state ** in Q3. */ -void GL_State( uint32_t stateBits ) -{ +void GL_State(uint32_t stateBits) { uint32_t diff = stateBits ^ glState.glStateBits; - if ( !diff ) - { + if (!diff) { return; } // // check depthFunc bits // - if ( diff & GLS_DEPTHFUNC_EQUAL ) - { - if ( stateBits & GLS_DEPTHFUNC_EQUAL ) - { - qglDepthFunc( GL_EQUAL ); - } - else - { - qglDepthFunc( GL_LEQUAL ); + if (diff & GLS_DEPTHFUNC_EQUAL) { + if (stateBits & GLS_DEPTHFUNC_EQUAL) { + qglDepthFunc(GL_EQUAL); + } else { + qglDepthFunc(GL_LEQUAL); } } // // check blend bits // - if ( diff & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { + if (diff & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { GLenum srcFactor, dstFactor; - if ( stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { - switch ( stateBits & GLS_SRCBLEND_BITS ) - { + if (stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { + switch (stateBits & GLS_SRCBLEND_BITS) { case GLS_SRCBLEND_ZERO: srcFactor = GL_ZERO; break; @@ -270,13 +229,12 @@ void GL_State( uint32_t stateBits ) srcFactor = GL_SRC_ALPHA_SATURATE; break; default: - srcFactor = GL_ONE; // to get warning to shut up - Com_Error( ERR_DROP, "GL_State: invalid src blend state bits\n" ); + srcFactor = GL_ONE; // to get warning to shut up + Com_Error(ERR_DROP, "GL_State: invalid src blend state bits\n"); break; } - switch ( stateBits & GLS_DSTBLEND_BITS ) - { + switch (stateBits & GLS_DSTBLEND_BITS) { case GLS_DSTBLEND_ZERO: dstFactor = GL_ZERO; break; @@ -302,93 +260,77 @@ void GL_State( uint32_t stateBits ) dstFactor = GL_ONE_MINUS_DST_ALPHA; break; default: - dstFactor = GL_ONE; // to get warning to shut up - Com_Error( ERR_DROP, "GL_State: invalid dst blend state bits\n" ); + dstFactor = GL_ONE; // to get warning to shut up + Com_Error(ERR_DROP, "GL_State: invalid dst blend state bits\n"); break; } - qglEnable( GL_BLEND ); - qglBlendFunc( srcFactor, dstFactor ); - } - else - { - qglDisable( GL_BLEND ); + qglEnable(GL_BLEND); + qglBlendFunc(srcFactor, dstFactor); + } else { + qglDisable(GL_BLEND); } } // // check depthmask // - if ( diff & GLS_DEPTHMASK_TRUE ) - { - if ( stateBits & GLS_DEPTHMASK_TRUE ) - { - qglDepthMask( GL_TRUE ); - } - else - { - qglDepthMask( GL_FALSE ); + if (diff & GLS_DEPTHMASK_TRUE) { + if (stateBits & GLS_DEPTHMASK_TRUE) { + qglDepthMask(GL_TRUE); + } else { + qglDepthMask(GL_FALSE); } } // // fill/line mode // - if ( diff & GLS_POLYMODE_LINE ) - { - if ( stateBits & GLS_POLYMODE_LINE ) - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); - } - else - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + if (diff & GLS_POLYMODE_LINE) { + if (stateBits & GLS_POLYMODE_LINE) { + qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + } else { + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } // // depthtest // - if ( diff & GLS_DEPTHTEST_DISABLE ) - { - if ( stateBits & GLS_DEPTHTEST_DISABLE ) - { - qglDisable( GL_DEPTH_TEST ); - } - else - { - qglEnable( GL_DEPTH_TEST ); + if (diff & GLS_DEPTHTEST_DISABLE) { + if (stateBits & GLS_DEPTHTEST_DISABLE) { + qglDisable(GL_DEPTH_TEST); + } else { + qglEnable(GL_DEPTH_TEST); } } // // alpha test // - if ( diff & GLS_ATEST_BITS ) - { - switch ( stateBits & GLS_ATEST_BITS ) - { + if (diff & GLS_ATEST_BITS) { + switch (stateBits & GLS_ATEST_BITS) { case 0: - qglDisable( GL_ALPHA_TEST ); + qglDisable(GL_ALPHA_TEST); break; case GLS_ATEST_GT_0: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GREATER, 0.0f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GREATER, 0.0f); break; case GLS_ATEST_LT_80: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_LESS, 0.5f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_LESS, 0.5f); break; case GLS_ATEST_GE_80: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GEQUAL, 0.5f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GEQUAL, 0.5f); break; case GLS_ATEST_GE_C0: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GEQUAL, 0.75f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GEQUAL, 0.75f); break; default: - assert( 0 ); + assert(0); break; } } @@ -396,8 +338,6 @@ void GL_State( uint32_t stateBits ) glState.glStateBits = stateBits; } - - /* ================ RB_Hyperspace @@ -405,31 +345,28 @@ RB_Hyperspace A player has predicted a teleport, but hasn't arrived yet ================ */ -static void RB_Hyperspace( void ) { - float c; +static void RB_Hyperspace(void) { + float c; - if ( !backEnd.isHyperspace ) { + if (!backEnd.isHyperspace) { // do initialization shit } - c = ( backEnd.refdef.time & 255 ) / 255.0f; - qglClearColor( c, c, c, 1 ); - qglClear( GL_COLOR_BUFFER_BIT ); + c = (backEnd.refdef.time & 255) / 255.0f; + qglClearColor(c, c, c, 1); + qglClear(GL_COLOR_BUFFER_BIT); backEnd.isHyperspace = qtrue; } - -void SetViewportAndScissor( void ) { +void SetViewportAndScissor(void) { qglMatrixMode(GL_PROJECTION); - qglLoadMatrixf( backEnd.viewParms.projectionMatrix ); + qglLoadMatrixf(backEnd.viewParms.projectionMatrix); qglMatrixMode(GL_MODELVIEW); // set the window clipping - qglViewport( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - qglScissor( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglViewport(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); + qglScissor(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); } /* @@ -440,15 +377,15 @@ Any mirrored or portaled views have already been drawn, so prepare to actually render the visible surfaces for this view ================= */ -static void RB_BeginDrawingView (void) { +static void RB_BeginDrawingView(void) { int clearBits = GL_DEPTH_BUFFER_BIT; // sync with gl if needed - if ( r_finish->integer == 1 && !glState.finishCalled ) { - qglFinish (); + if (r_finish->integer == 1 && !glState.finishCalled) { + qglFinish(); glState.finishCalled = qtrue; } - if ( r_finish->integer == 0 ) { + if (r_finish->integer == 0) { glState.finishCalled = qtrue; } @@ -462,145 +399,124 @@ static void RB_BeginDrawingView (void) { SetViewportAndScissor(); // ensures that depth writes are enabled for the depth clear - GL_State( GLS_DEFAULT ); + GL_State(GLS_DEFAULT); // clear relevant buffers - if ( r_measureOverdraw->integer || r_shadows->integer == 2 || tr_stencilled ) - { + if (r_measureOverdraw->integer || r_shadows->integer == 2 || tr_stencilled) { clearBits |= GL_STENCIL_BUFFER_BIT; tr_stencilled = false; } - if (skyboxportal) - { - if ( backEnd.refdef.rdflags & RDF_SKYBOXPORTAL ) - { // portal scene, clear whatever is necessary - if (r_fastsky->integer || (backEnd.refdef.rdflags & RDF_NOWORLDMODEL) ) - { // fastsky: clear color + if (skyboxportal) { + if (backEnd.refdef.rdflags & RDF_SKYBOXPORTAL) { // portal scene, clear whatever is necessary + if (r_fastsky->integer || (backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) { // fastsky: clear color // try clearing first with the portal sky fog color, then the world fog color, then finally a default clearBits |= GL_COLOR_BUFFER_BIT; - if (tr.world && tr.world->globalFog != -1) - { - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); - } - else - { - qglClearColor ( 0.3f, 0.3f, 0.3f, 1.0 ); + if (tr.world && tr.world->globalFog != -1) { + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); + } else { + qglClearColor(0.3f, 0.3f, 0.3f, 1.0); } } } - } - else - { - if ( r_fastsky->integer && !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && !g_bRenderGlowingObjects ) - { - if (tr.world && tr.world->globalFog != -1) - { - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); - } - else - { - qglClearColor( 0.3f, 0.3f, 0.3f, 1 ); // FIXME: get color of sky + } else { + if (r_fastsky->integer && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && !g_bRenderGlowingObjects) { + if (tr.world && tr.world->globalFog != -1) { + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); + } else { + qglClearColor(0.3f, 0.3f, 0.3f, 1); // FIXME: get color of sky } - clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used + clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used } } - if ( !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && ( r_DynamicGlow->integer && !g_bRenderGlowingObjects ) ) - { - if (tr.world && tr.world->globalFog != -1) - { //this is because of a bug in multiple scenes I think, it needs to clear for the second scene but it doesn't normally. - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + if (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && (r_DynamicGlow->integer && !g_bRenderGlowingObjects)) { + if (tr.world && + tr.world->globalFog != -1) { // this is because of a bug in multiple scenes I think, it needs to clear for the second scene but it doesn't normally. + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); clearBits |= GL_COLOR_BUFFER_BIT; } } // If this pass is to just render the glowing objects, don't clear the depth buffer since // we're sharing it with the main scene (since the main scene has already been rendered). -AReis - if ( g_bRenderGlowingObjects ) - { + if (g_bRenderGlowingObjects) { clearBits &= ~GL_DEPTH_BUFFER_BIT; } - if (clearBits) - { - qglClear( clearBits ); + if (clearBits) { + qglClear(clearBits); } - if ( ( backEnd.refdef.rdflags & RDF_HYPERSPACE ) ) - { + if ((backEnd.refdef.rdflags & RDF_HYPERSPACE)) { RB_Hyperspace(); return; - } - else - { + } else { backEnd.isHyperspace = qfalse; } - glState.faceCulling = -1; // force face culling to set next time + glState.faceCulling = -1; // force face culling to set next time // we will only draw a sun if there was sky rendered in this view backEnd.skyRenderedThisView = qfalse; // clip to the plane of the portal - if ( backEnd.viewParms.isPortal ) { - float plane[4]; - double plane2[4]; + if (backEnd.viewParms.isPortal) { + float plane[4]; + double plane2[4]; plane[0] = backEnd.viewParms.portalPlane.normal[0]; plane[1] = backEnd.viewParms.portalPlane.normal[1]; plane[2] = backEnd.viewParms.portalPlane.normal[2]; plane[3] = backEnd.viewParms.portalPlane.dist; - plane2[0] = DotProduct (backEnd.viewParms.ori.axis[0], plane); - plane2[1] = DotProduct (backEnd.viewParms.ori.axis[1], plane); - plane2[2] = DotProduct (backEnd.viewParms.ori.axis[2], plane); - plane2[3] = DotProduct (plane, backEnd.viewParms.ori.origin) - plane[3]; + plane2[0] = DotProduct(backEnd.viewParms.ori.axis[0], plane); + plane2[1] = DotProduct(backEnd.viewParms.ori.axis[1], plane); + plane2[2] = DotProduct(backEnd.viewParms.ori.axis[2], plane); + plane2[3] = DotProduct(plane, backEnd.viewParms.ori.origin) - plane[3]; - qglLoadMatrixf( s_flipMatrix ); - qglClipPlane (GL_CLIP_PLANE0, plane2); - qglEnable (GL_CLIP_PLANE0); + qglLoadMatrixf(s_flipMatrix); + qglClipPlane(GL_CLIP_PLANE0, plane2); + qglEnable(GL_CLIP_PLANE0); } else { - qglDisable (GL_CLIP_PLANE0); + qglDisable(GL_CLIP_PLANE0); } } -//used by RF_DISTORTION -static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) -{ - int xcenter, ycenter; - vec3_t local, transformed; - vec3_t vfwd; - vec3_t vright; - vec3_t vup; +// used by RF_DISTORTION +static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { + int xcenter, ycenter; + vec3_t local, transformed; + vec3_t vfwd; + vec3_t vright; + vec3_t vup; float xzi; float yzi; xcenter = glConfig.vidWidth / 2; ycenter = glConfig.vidHeight / 2; - //AngleVectors (tr.refdef.viewangles, vfwd, vright, vup); + // AngleVectors (tr.refdef.viewangles, vfwd, vright, vup); VectorCopy(tr.refdef.viewaxis[0], vfwd); VectorCopy(tr.refdef.viewaxis[1], vright); VectorCopy(tr.refdef.viewaxis[2], vup); - VectorSubtract (worldCoord, tr.refdef.vieworg, local); + VectorSubtract(worldCoord, tr.refdef.vieworg, local); - transformed[0] = DotProduct(local,vright); - transformed[1] = DotProduct(local,vup); - transformed[2] = DotProduct(local,vfwd); + transformed[0] = DotProduct(local, vright); + transformed[1] = DotProduct(local, vup); + transformed[2] = DotProduct(local, vfwd); // Make sure Z is not negative. - if(transformed[2] < 0.01) - { + if (transformed[2] < 0.01) { return false; } - xzi = xcenter / transformed[2] * (90.0/tr.refdef.fov_x); - yzi = ycenter / transformed[2] * (90.0/tr.refdef.fov_y); + xzi = xcenter / transformed[2] * (90.0 / tr.refdef.fov_x); + yzi = ycenter / transformed[2] * (90.0 / tr.refdef.fov_y); *x = xcenter + xzi * transformed[0]; *y = ycenter - yzi * transformed[1]; @@ -608,11 +524,10 @@ static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, f return true; } -//used by RF_DISTORTION -static inline bool R_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) -{ - float xF, yF; - bool retVal = R_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ); +// used by RF_DISTORTION +static inline bool R_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) { + float xF, yF; + bool retVal = R_WorldCoordToScreenCoordFloat(worldCoord, &xF, &yF); *x = (int)xF; *y = (int)yF; return retVal; @@ -623,40 +538,38 @@ static inline bool R_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y RB_RenderDrawSurfList ================== */ -//number of possible surfs we can postrender. -//note that postrenders lack much of the optimization that the standard sort-render crap does, -//so it's slower. -#define MAX_POST_RENDERS 128 - -typedef struct -{ - int fogNum; - int entNum; - int dlighted; - int depthRange; - drawSurf_t *drawSurf; - shader_t *shader; +// number of possible surfs we can postrender. +// note that postrenders lack much of the optimization that the standard sort-render crap does, +// so it's slower. +#define MAX_POST_RENDERS 128 + +typedef struct { + int fogNum; + int entNum; + int dlighted; + int depthRange; + drawSurf_t *drawSurf; + shader_t *shader; } postRender_t; static postRender_t g_postRenders[MAX_POST_RENDERS]; static int g_numPostRenders = 0; -void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { - shader_t *shader, *oldShader; - int fogNum, oldFogNum; - int entityNum, oldEntityNum; - int dlighted, oldDlighted; - int depthRange, oldDepthRange; - int i; - drawSurf_t *drawSurf; - unsigned int oldSort; - float originalTime; - trRefEntity_t *curEnt; - postRender_t *pRender; - bool didShadowPass = false; - - if (g_bRenderGlowingObjects) - { //only shadow on initial passes +void RB_RenderDrawSurfList(drawSurf_t *drawSurfs, int numDrawSurfs) { + shader_t *shader, *oldShader; + int fogNum, oldFogNum; + int entityNum, oldEntityNum; + int dlighted, oldDlighted; + int depthRange, oldDepthRange; + int i; + drawSurf_t *drawSurf; + unsigned int oldSort; + float originalTime; + trRefEntity_t *curEnt; + postRender_t *pRender; + bool didShadowPass = false; + + if (g_bRenderGlowingObjects) { // only shadow on initial passes didShadowPass = true; } @@ -664,7 +577,7 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { originalTime = backEnd.refdef.floatTime; // clear the z buffer, set the modelview, etc - RB_BeginDrawingView (); + RB_BeginDrawingView(); // draw everything oldEntityNum = -1; @@ -673,22 +586,21 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { oldFogNum = -1; oldDepthRange = qfalse; oldDlighted = qfalse; - oldSort = (unsigned int) -1; + oldSort = (unsigned int)-1; depthRange = qfalse; backEnd.pc.c_surfaces += numDrawSurfs; - for (i = 0, drawSurf = drawSurfs ; i < numDrawSurfs ; i++, drawSurf++) { - if ( drawSurf->sort == oldSort ) { + for (i = 0, drawSurf = drawSurfs; i < numDrawSurfs; i++, drawSurf++) { + if (drawSurf->sort == oldSort) { // fast path, same as previous sort - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); continue; } - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted ); + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted); // If we're rendering glowing objects, but this shader has no stages with glow, skip it! - if ( g_bRenderGlowingObjects && !shader->hasGlow ) - { + if (g_bRenderGlowingObjects && !shader->hasGlow) { shader = oldShader; entityNum = oldEntityNum; fogNum = oldFogNum; @@ -702,68 +614,59 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // change the tess parameters if needed // a "entityMergable" shader is a shader that can have surfaces from seperate // entities merged into a single batch, like smoke and blood puff sprites - if (entityNum != REFENTITYNUM_WORLD && - g_numPostRenders < MAX_POST_RENDERS) - { - if ( (backEnd.refdef.entities[entityNum].e.renderfx & RF_DISTORTION) || - (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCE_ENT_ALPHA)) - { //must render last + if (entityNum != REFENTITYNUM_WORLD && g_numPostRenders < MAX_POST_RENDERS) { + if ((backEnd.refdef.entities[entityNum].e.renderfx & RF_DISTORTION) || + (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCE_ENT_ALPHA)) { // must render last curEnt = &backEnd.refdef.entities[entityNum]; pRender = &g_postRenders[g_numPostRenders]; g_numPostRenders++; depthRange = 0; - //figure this stuff out now and store it - if ( curEnt->e.renderfx & RF_NODEPTH ) - { + // figure this stuff out now and store it + if (curEnt->e.renderfx & RF_NODEPTH) { depthRange = 2; - } - else if ( curEnt->e.renderfx & RF_DEPTHHACK ) - { + } else if (curEnt->e.renderfx & RF_DEPTHHACK) { depthRange = 1; } pRender->depthRange = depthRange; - //It is not necessary to update the old* values because - //we are not updating now with the current values. + // It is not necessary to update the old* values because + // we are not updating now with the current values. depthRange = oldDepthRange; - //store off the ent num + // store off the ent num pRender->entNum = entityNum; - //remember the other values necessary for rendering this surf + // remember the other values necessary for rendering this surf pRender->drawSurf = drawSurf; pRender->dlighted = dlighted; pRender->fogNum = fogNum; pRender->shader = shader; - //assure the info is back to the last set state + // assure the info is back to the last set state shader = oldShader; entityNum = oldEntityNum; fogNum = oldFogNum; dlighted = oldDlighted; - oldSort = (unsigned int)-1; //invalidate this thing, cause we may want to postrender more surfs of the same sort + oldSort = (unsigned int)-1; // invalidate this thing, cause we may want to postrender more surfs of the same sort - //continue without bothering to begin a draw surf + // continue without bothering to begin a draw surf continue; } } - if (shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted - || ( entityNum != oldEntityNum && !shader->entityMergable ) ) - { + if (shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted || (entityNum != oldEntityNum && !shader->entityMergable)) { if (oldShader != NULL) { RB_EndSurface(); - if (!didShadowPass && shader && shader->sort > SS_BANNER) - { + if (!didShadowPass && shader && shader->sort > SS_BANNER) { RB_ShadowFinish(); didShadowPass = true; } } - RB_BeginSurface( shader, fogNum ); + RB_BeginSurface(shader, fogNum); oldShader = shader; oldFogNum = fogNum; oldDlighted = dlighted; @@ -772,26 +675,25 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // // change the modelview matrix if needed // - if ( entityNum != oldEntityNum ) { + if (entityNum != oldEntityNum) { depthRange = qfalse; - if ( entityNum != REFENTITYNUM_WORLD ) { + if (entityNum != REFENTITYNUM_WORLD) { backEnd.currentEntity = &backEnd.refdef.entities[entityNum]; backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; // set up the transformation matrix - R_RotateForEntity( backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori ); + R_RotateForEntity(backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori); // set up the dynamic lighting if needed - if ( backEnd.currentEntity->needDlights ) { - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + if (backEnd.currentEntity->needDlights) { + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } - if ( backEnd.currentEntity->e.renderfx & RF_NODEPTH ) { + if (backEnd.currentEntity->e.renderfx & RF_NODEPTH) { // No depth at all, very rare but some things for seeing through walls depthRange = 2; - } - else if ( backEnd.currentEntity->e.renderfx & RF_DEPTHHACK ) { + } else if (backEnd.currentEntity->e.renderfx & RF_DEPTHHACK) { // hack the depth range to prevent view model from poking into walls depthRange = qtrue; } @@ -799,28 +701,28 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { backEnd.currentEntity = &tr.worldEntity; backEnd.refdef.floatTime = originalTime; backEnd.ori = backEnd.viewParms.world; - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } - qglLoadMatrixf( backEnd.ori.modelMatrix ); + qglLoadMatrixf(backEnd.ori.modelMatrix); // // change depthrange if needed // - if ( oldDepthRange != depthRange ) { - switch ( depthRange ) { - default: - case 0: - qglDepthRange (0, 1); - break; - - case 1: - qglDepthRange (0, .3); - break; - - case 2: - qglDepthRange (0, 0); - break; + if (oldDepthRange != depthRange) { + switch (depthRange) { + default: + case 0: + qglDepthRange(0, 1); + break; + + case 1: + qglDepthRange(0, .3); + break; + + case 2: + qglDepthRange(0, 0); + break; } oldDepthRange = depthRange; @@ -830,7 +732,7 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { } // add the triangles for this surface - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); } // draw the contents of the last shader batch @@ -838,126 +740,110 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { RB_EndSurface(); } - if (tr_stencilled && tr_distortionPrePost) - { //ok, cap it now + if (tr_stencilled && tr_distortionPrePost) { // ok, cap it now RB_CaptureScreenImage(); RB_DistortionFill(); } - //render distortion surfs (or anything else that needs to be post-rendered) - if (g_numPostRenders > 0) - { + // render distortion surfs (or anything else that needs to be post-rendered) + if (g_numPostRenders > 0) { int lastPostEnt = -1; - while (g_numPostRenders > 0) - { + while (g_numPostRenders > 0) { g_numPostRenders--; pRender = &g_postRenders[g_numPostRenders]; - RB_BeginSurface( pRender->shader, pRender->fogNum ); + RB_BeginSurface(pRender->shader, pRender->fogNum); backEnd.currentEntity = &backEnd.refdef.entities[pRender->entNum]; backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; // set up the transformation matrix - R_RotateForEntity( backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori ); + R_RotateForEntity(backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori); // set up the dynamic lighting if needed - if ( backEnd.currentEntity->needDlights ) - { - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + if (backEnd.currentEntity->needDlights) { + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } - qglLoadMatrixf( backEnd.ori.modelMatrix ); + qglLoadMatrixf(backEnd.ori.modelMatrix); depthRange = pRender->depthRange; - switch ( depthRange ) - { - default: - case 0: - qglDepthRange (0, 1); - break; + switch (depthRange) { + default: + case 0: + qglDepthRange(0, 1); + break; - case 1: - qglDepthRange (0, .3); - break; + case 1: + qglDepthRange(0, .3); + break; - case 2: - qglDepthRange (0, 0); - break; + case 2: + qglDepthRange(0, 0); + break; } if ((backEnd.currentEntity->e.renderfx & RF_DISTORTION) && - lastPostEnt != pRender->entNum) - { //do the capture now, we only need to do it once per ent + lastPostEnt != pRender->entNum) { // do the capture now, we only need to do it once per ent int x, y; int rad = backEnd.currentEntity->e.radius; - //We are going to just bind this, and then the CopyTexImage is going to - //stomp over this texture num in texture memory. - GL_Bind( tr.screenImage ); + // We are going to just bind this, and then the CopyTexImage is going to + // stomp over this texture num in texture memory. + GL_Bind(tr.screenImage); - if (R_WorldCoordToScreenCoord( backEnd.currentEntity->e.origin, &x, &y )) - { + if (R_WorldCoordToScreenCoord(backEnd.currentEntity->e.origin, &x, &y)) { int cX, cY; - cX = glConfig.vidWidth-x-(rad/2); - cY = glConfig.vidHeight-y-(rad/2); + cX = glConfig.vidWidth - x - (rad / 2); + cY = glConfig.vidHeight - y - (rad / 2); - if (cX+rad > glConfig.vidWidth) - { //would it go off screen? - cX = glConfig.vidWidth-rad; - } - else if (cX < 0) - { //cap it off at 0 + if (cX + rad > glConfig.vidWidth) { // would it go off screen? + cX = glConfig.vidWidth - rad; + } else if (cX < 0) { // cap it off at 0 cX = 0; } - if (cY+rad > glConfig.vidHeight) - { //would it go off screen? - cY = glConfig.vidHeight-rad; - } - else if (cY < 0) - { //cap it off at 0 + if (cY + rad > glConfig.vidHeight) { // would it go off screen? + cY = glConfig.vidHeight - rad; + } else if (cY < 0) { // cap it off at 0 cY = 0; } - //now copy a portion of the screen to this texture + // now copy a portion of the screen to this texture qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, cX, cY, rad, rad, 0); lastPostEnt = pRender->entNum; } } - rb_surfaceTable[ *pRender->drawSurf->surface ]( pRender->drawSurf->surface ); + rb_surfaceTable[*pRender->drawSurf->surface](pRender->drawSurf->surface); RB_EndSurface(); } } // go back to the world modelview matrix - qglLoadMatrixf( backEnd.viewParms.world.modelMatrix ); - if ( depthRange ) { - qglDepthRange (0, 1); + qglLoadMatrixf(backEnd.viewParms.world.modelMatrix); + if (depthRange) { + qglDepthRange(0, 1); } #if 0 RB_DrawSun(); #endif - if (tr_stencilled && !tr_distortionPrePost) - { //draw in the stencil buffer's cutout + if (tr_stencilled && !tr_distortionPrePost) { // draw in the stencil buffer's cutout RB_DistortionFill(); } - if (!didShadowPass) - { + if (!didShadowPass) { // darken down any stencil shadows RB_ShadowFinish(); didShadowPass = true; } -// add light flares on lights that aren't obscured -// RB_RenderFlares(); + // add light flares on lights that aren't obscured + // RB_RenderFlares(); } - /* ============================================================================ @@ -972,39 +858,36 @@ RB_SetGL2D ================ */ -void RB_SetGL2D (void) { +void RB_SetGL2D(void) { backEnd.projection2D = qtrue; // set 2D virtual screen size - qglViewport( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); - qglScissor( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); + qglViewport(0, 0, glConfig.vidWidth, glConfig.vidHeight); + qglScissor(0, 0, glConfig.vidWidth, glConfig.vidHeight); qglMatrixMode(GL_PROJECTION); - qglLoadIdentity (); - qglOrtho (0, 640, 480, 0, 0, 1); + qglLoadIdentity(); + qglOrtho(0, 640, 480, 0, 0, 1); qglMatrixMode(GL_MODELVIEW); - qglLoadIdentity (); + qglLoadIdentity(); - GL_State( GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - qglDisable( GL_CULL_FACE ); - qglDisable( GL_CLIP_PLANE0 ); + qglDisable(GL_CULL_FACE); + qglDisable(GL_CLIP_PLANE0); // set time for 2D shaders backEnd.refdef.time = ri.Milliseconds(); backEnd.refdef.floatTime = backEnd.refdef.time * 0.001f; } - /* ============= RB_SetColor ============= */ -const void *RB_SetColor( const void *data ) { - const setColorCommand_t *cmd; +const void *RB_SetColor(const void *data) { + const setColorCommand_t *cmd; cmd = (const setColorCommand_t *)data; @@ -1021,162 +904,164 @@ const void *RB_SetColor( const void *data ) { RB_StretchPic ============= */ -const void *RB_StretchPic ( const void *data ) { - const stretchPicCommand_t *cmd; +const void *RB_StretchPic(const void *data) { + const stretchPicCommand_t *cmd; shader_t *shader; - int numVerts, numIndexes; + int numVerts, numIndexes; cmd = (const stretchPicCommand_t *)data; - if ( !backEnd.projection2D ) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); numVerts = tess.numVertexes; numIndexes = tess.numIndexes; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = cmd->x; - tess.xyz[ numVerts ][1] = cmd->y; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = cmd->x; + tess.xyz[numVerts][1] = cmd->y; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 1 ][1] = cmd->y; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 1][1] = cmd->y; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 2 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 2][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = cmd->x; - tess.xyz[ numVerts + 3 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = cmd->x; + tess.xyz[numVerts + 3][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } - /* ============= RB_RotatePic ============= */ -const void *RB_RotatePic ( const void *data ) -{ - const rotatePicCommand_t *cmd; +const void *RB_RotatePic(const void *data) { + const rotatePicCommand_t *cmd; shader_t *shader; cmd = (const rotatePicCommand_t *)data; shader = cmd->shader; - if ( !backEnd.projection2D ) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd-> a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x + cmd->w, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x + cmd->w, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[2][0]; + tess.xyz[numVerts + 1][1] = m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } @@ -1186,9 +1071,8 @@ const void *RB_RotatePic ( const void *data ) RB_RotatePic2 ============= */ -const void *RB_RotatePic2 ( const void *data ) -{ - const rotatePicCommand_t *cmd; +const void *RB_RotatePic2(const void *data) { + const rotatePicCommand_t *cmd; shader_t *shader; cmd = (const rotatePicCommand_t *)data; @@ -1196,78 +1080,77 @@ const void *RB_RotatePic2 ( const void *data ) shader = cmd->shader; // FIXME is this needed - if ( shader->numUnfoggedPasses ) - { - if ( !backEnd.projection2D ) { + if (shader->numUnfoggedPasses) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd-> a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 1][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; } return (const void *)(cmd + 1); @@ -1278,24 +1161,19 @@ const void *RB_RotatePic2 ( const void *data ) RB_ScissorPic ============= */ -const void *RB_Scissor ( const void *data ) -{ - const scissorCommand_t *cmd; +const void *RB_Scissor(const void *data) { + const scissorCommand_t *cmd; cmd = (const scissorCommand_t *)data; - if ( !backEnd.projection2D ) - { + if (!backEnd.projection2D) { RB_SetGL2D(); } - if (cmd->x >= 0) - { - qglScissor( cmd->x,(glConfig.vidHeight - cmd->y - cmd->h),cmd->w,cmd->h); - } - else - { - qglScissor( 0, 0, glConfig.vidWidth, glConfig.vidHeight); + if (cmd->x >= 0) { + qglScissor(cmd->x, (glConfig.vidHeight - cmd->y - cmd->h), cmd->w, cmd->h); + } else { + qglScissor(0, 0, glConfig.vidWidth, glConfig.vidHeight); } return (const void *)(cmd + 1); @@ -1307,11 +1185,11 @@ RB_DrawSurfs ============= */ -const void *RB_DrawSurfs( const void *data ) { - const drawSurfsCommand_t *cmd; +const void *RB_DrawSurfs(const void *data) { + const drawSurfsCommand_t *cmd; // finish any 2D drawing if needed - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } @@ -1320,7 +1198,7 @@ const void *RB_DrawSurfs( const void *data ) { backEnd.refdef = cmd->refdef; backEnd.viewParms = cmd->viewParms; - RB_RenderDrawSurfList( cmd->drawSurfs, cmd->numDrawSurfs ); + RB_RenderDrawSurfList(cmd->drawSurfs, cmd->numDrawSurfs); // Dynamic Glow/Flares: /* @@ -1332,33 +1210,34 @@ const void *RB_DrawSurfs( const void *data ) { */ // Render dynamic glowing/flaring objects. - if ( !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && g_bDynamicGlowSupported && r_DynamicGlow->integer ) - { + if (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && g_bDynamicGlowSupported && r_DynamicGlow->integer) { // Copy the normal scene to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, + backEnd.viewParms.viewportHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Just clear colors, but leave the depth buffer intact so we can 'share' it. - qglClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); - qglClear( GL_COLOR_BUFFER_BIT ); + qglClearColor(0.0f, 0.0f, 0.0f, 0.0f); + qglClear(GL_COLOR_BUFFER_BIT); // Render the glowing objects. g_bRenderGlowingObjects = true; - RB_RenderDrawSurfList( cmd->drawSurfs, cmd->numDrawSurfs ); + RB_RenderDrawSurfList(cmd->drawSurfs, cmd->numDrawSurfs); g_bRenderGlowingObjects = false; qglFinish(); // Copy the glow scene to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, + backEnd.viewParms.viewportHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Resize the viewport to the blur texture size. const int oldViewWidth = backEnd.viewParms.viewportWidth; @@ -1371,18 +1250,18 @@ const void *RB_DrawSurfs( const void *data ) { RB_BlurGlowTexture(); // Copy the finished glow scene back to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Set the viewport back to normal. backEnd.viewParms.viewportWidth = oldViewWidth; backEnd.viewParms.viewportHeight = oldViewHeight; SetViewportAndScissor(); - qglClear( GL_COLOR_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT); // Draw the glow additively over the screen. RB_DrawGlowOverlay(); @@ -1391,72 +1270,67 @@ const void *RB_DrawSurfs( const void *data ) { return (const void *)(cmd + 1); } - /* ============= RB_DrawBuffer ============= */ -const void *RB_DrawBuffer( const void *data ) { - const drawBufferCommand_t *cmd; +const void *RB_DrawBuffer(const void *data) { + const drawBufferCommand_t *cmd; cmd = (const drawBufferCommand_t *)data; - qglDrawBuffer( cmd->buffer ); + qglDrawBuffer(cmd->buffer); - // clear screen for debugging - if (!( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && tr.world && tr.refdef.rdflags & RDF_doLAGoggles) - { - const fog_t *fog = &tr.world->fogs[tr.world->numfogs]; + // clear screen for debugging + if (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && tr.world && tr.refdef.rdflags & RDF_doLAGoggles) { + const fog_t *fog = &tr.world->fogs[tr.world->numfogs]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - } - else if (!( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && tr.world && tr.world->globalFog != -1 && tr.sceneCount)//don't clear during menus, wait for real scene + } else if (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && tr.world && tr.world->globalFog != -1 && + tr.sceneCount) // don't clear during menus, wait for real scene { - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); - qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); - } - else if ( r_clear->integer ) - { // clear screen for debugging + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); + qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } else if (r_clear->integer) { // clear screen for debugging int i = r_clear->integer; if (i == 42) { - i = Q_irand(0,8); + i = Q_irand(0, 8); } - switch (i) - { + switch (i) { default: - qglClearColor( 1, 0, 0.5, 1 ); + qglClearColor(1, 0, 0.5, 1); break; case 1: - qglClearColor( 1.0, 0.0, 0.0, 1.0); //red + qglClearColor(1.0, 0.0, 0.0, 1.0); // red break; case 2: - qglClearColor( 0.0, 1.0, 0.0, 1.0); //green + qglClearColor(0.0, 1.0, 0.0, 1.0); // green break; case 3: - qglClearColor( 1.0, 1.0, 0.0, 1.0); //yellow + qglClearColor(1.0, 1.0, 0.0, 1.0); // yellow break; case 4: - qglClearColor( 0.0, 0.0, 1.0, 1.0); //blue + qglClearColor(0.0, 0.0, 1.0, 1.0); // blue break; case 5: - qglClearColor( 0.0, 1.0, 1.0, 1.0); //cyan + qglClearColor(0.0, 1.0, 1.0, 1.0); // cyan break; case 6: - qglClearColor( 1.0, 0.0, 1.0, 1.0); //magenta + qglClearColor(1.0, 0.0, 1.0, 1.0); // magenta break; case 7: - qglClearColor( 1.0, 1.0, 1.0, 1.0); //white + qglClearColor(1.0, 1.0, 1.0, 1.0); // white break; case 8: - qglClearColor( 0.0, 0.0, 0.0, 1.0); //black + qglClearColor(0.0, 0.0, 0.0, 1.0); // black break; } - qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } return (const void *)(cmd + 1); @@ -1472,73 +1346,71 @@ was there. This is used to test for texture thrashing. Also called by RE_EndRegistration =============== */ -void RB_ShowImages( void ) { - image_t *image; - float x, y, w, h; - //int start, end; +void RB_ShowImages(void) { + image_t *image; + float x, y, w, h; + // int start, end; - if ( !backEnd.projection2D ) { + if (!backEnd.projection2D) { RB_SetGL2D(); } qglFinish(); - //start = ri.Milliseconds(); + // start = ri.Milliseconds(); - int i=0; -// int iNumImages = - R_Images_StartIteration(); - while ( (image = R_Images_GetNextIteration()) != NULL) - { + int i = 0; + // int iNumImages = + R_Images_StartIteration(); + while ((image = R_Images_GetNextIteration()) != NULL) { w = glConfig.vidWidth / 20; h = glConfig.vidHeight / 15; x = i % 20 * w; y = i / 20 * h; // show in proportional size in mode 2 - if ( r_showImages->integer == 2 ) { + if (r_showImages->integer == 2) { w *= image->width / 512.0; h *= image->height / 512.0; } - GL_Bind( image ); - qglBegin (GL_QUADS); - qglTexCoord2f( 0, 0 ); - qglVertex2f( x, y ); - qglTexCoord2f( 1, 0 ); - qglVertex2f( x + w, y ); - qglTexCoord2f( 1, 1 ); - qglVertex2f( x + w, y + h ); - qglTexCoord2f( 0, 1 ); - qglVertex2f( x, y + h ); + GL_Bind(image); + qglBegin(GL_QUADS); + qglTexCoord2f(0, 0); + qglVertex2f(x, y); + qglTexCoord2f(1, 0); + qglVertex2f(x + w, y); + qglTexCoord2f(1, 1); + qglVertex2f(x + w, y + h); + qglTexCoord2f(0, 1); + qglVertex2f(x, y + h); qglEnd(); i++; } qglFinish(); - //end = ri.Milliseconds(); - //ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); + // end = ri.Milliseconds(); + // ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); } - /* ============= RB_SwapBuffers ============= */ -extern void RB_RenderWorldEffects( void ); -const void *RB_SwapBuffers( const void *data ) { - const swapBuffersCommand_t *cmd; +extern void RB_RenderWorldEffects(void); +const void *RB_SwapBuffers(const void *data) { + const swapBuffersCommand_t *cmd; // finish any 2D drawing if needed - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } // texture swapping test - if ( r_showImages->integer ) { + if (r_showImages->integer) { RB_ShowImages(); } @@ -1546,27 +1418,27 @@ const void *RB_SwapBuffers( const void *data ) { // we measure overdraw by reading back the stencil buffer and // counting up the number of increments that have happened - if ( r_measureOverdraw->integer ) { + if (r_measureOverdraw->integer) { int i; long sum = 0; unsigned char *stencilReadback; - stencilReadback = (unsigned char *) R_Malloc( glConfig.vidWidth * glConfig.vidHeight, TAG_TEMP_WORKSPACE, qfalse ); - qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback ); + stencilReadback = (unsigned char *)R_Malloc(glConfig.vidWidth * glConfig.vidHeight, TAG_TEMP_WORKSPACE, qfalse); + qglReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback); - for ( i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++ ) { + for (i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++) { sum += stencilReadback[i]; } backEnd.pc.c_overDraw += sum; - R_Free( stencilReadback ); + R_Free(stencilReadback); } - if ( !glState.finishCalled ) { - qglFinish(); + if (!glState.finishCalled) { + qglFinish(); } - GLimp_LogComment( "***************** RB_SwapBuffers *****************\n\n\n" ); + GLimp_LogComment("***************** RB_SwapBuffers *****************\n\n\n"); ri.WIN_Present(&window); @@ -1575,22 +1447,19 @@ const void *RB_SwapBuffers( const void *data ) { return (const void *)(cmd + 1); } -const void *RB_WorldEffects( const void *data ) -{ - const setModeCommand_t *cmd; +const void *RB_WorldEffects(const void *data) { + const setModeCommand_t *cmd; cmd = (const setModeCommand_t *)data; // Always flush the tess buffer - if ( tess.shader && tess.numIndexes ) - { + if (tess.shader && tess.numIndexes) { RB_EndSurface(); } RB_RenderWorldEffects(); - if(tess.shader) - { - RB_BeginSurface( tess.shader, tess.fogNum ); + if (tess.shader) { + RB_BeginSurface(tess.shader, tess.fogNum); } return (const void *)(cmd + 1); @@ -1601,109 +1470,102 @@ const void *RB_WorldEffects( const void *data ) RB_ExecuteRenderCommands ==================== */ -void RB_ExecuteRenderCommands( const void *data ) { - int t1, t2; +void RB_ExecuteRenderCommands(const void *data) { + int t1, t2; - t1 = ri.Milliseconds (); + t1 = ri.Milliseconds(); - while ( 1 ) { + while (1) { data = PADP(data, sizeof(void *)); - switch ( *(const int *)data ) { + switch (*(const int *)data) { case RC_SET_COLOR: - data = RB_SetColor( data ); + data = RB_SetColor(data); break; case RC_STRETCH_PIC: - data = RB_StretchPic( data ); + data = RB_StretchPic(data); break; case RC_ROTATE_PIC: - data = RB_RotatePic( data ); + data = RB_RotatePic(data); break; case RC_ROTATE_PIC2: - data = RB_RotatePic2( data ); + data = RB_RotatePic2(data); break; case RC_SCISSOR: - data = RB_Scissor( data ); + data = RB_Scissor(data); break; case RC_DRAW_SURFS: - data = RB_DrawSurfs( data ); + data = RB_DrawSurfs(data); break; case RC_DRAW_BUFFER: - data = RB_DrawBuffer( data ); + data = RB_DrawBuffer(data); break; case RC_SWAP_BUFFERS: - data = RB_SwapBuffers( data ); + data = RB_SwapBuffers(data); break; case RC_WORLD_EFFECTS: - data = RB_WorldEffects( data ); + data = RB_WorldEffects(data); break; case RC_END_OF_LIST: default: // stop rendering - t2 = ri.Milliseconds (); + t2 = ri.Milliseconds(); backEnd.pc.msec = t2 - t1; return; } } - } // What Pixel Shader type is currently active (regcoms or fragment programs). GLuint g_uiCurrentPixelShaderType = 0x0; // Begin using a Pixel Shader. -void BeginPixelShader( GLuint uiType, GLuint uiID ) -{ - switch ( uiType ) - { - // Using Register Combiners, so call the Display List that stores it. - case GL_REGISTER_COMBINERS_NV: - { - // Just in case... - if ( !qglCombinerParameterfvNV ) - return; - - // Call the list with the regcom in it. - qglEnable( GL_REGISTER_COMBINERS_NV ); - qglCallList( uiID ); - - g_uiCurrentPixelShaderType = GL_REGISTER_COMBINERS_NV; - } +void BeginPixelShader(GLuint uiType, GLuint uiID) { + switch (uiType) { + // Using Register Combiners, so call the Display List that stores it. + case GL_REGISTER_COMBINERS_NV: { + // Just in case... + if (!qglCombinerParameterfvNV) + return; + + // Call the list with the regcom in it. + qglEnable(GL_REGISTER_COMBINERS_NV); + qglCallList(uiID); + + g_uiCurrentPixelShaderType = GL_REGISTER_COMBINERS_NV; + } return; - // Using Fragment Programs, so call the program. - case GL_FRAGMENT_PROGRAM_ARB: - { - // Just in case... - if ( !qglGenProgramsARB ) - return; + // Using Fragment Programs, so call the program. + case GL_FRAGMENT_PROGRAM_ARB: { + // Just in case... + if (!qglGenProgramsARB) + return; - qglEnable( GL_FRAGMENT_PROGRAM_ARB ); - qglBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, uiID ); + qglEnable(GL_FRAGMENT_PROGRAM_ARB); + qglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, uiID); - g_uiCurrentPixelShaderType = GL_FRAGMENT_PROGRAM_ARB; - } + g_uiCurrentPixelShaderType = GL_FRAGMENT_PROGRAM_ARB; + } return; } } // Stop using a Pixel Shader and return states to normal. -void EndPixelShader() -{ - if ( g_uiCurrentPixelShaderType == 0x0 ) +void EndPixelShader() { + if (g_uiCurrentPixelShaderType == 0x0) return; - qglDisable( g_uiCurrentPixelShaderType ); + qglDisable(g_uiCurrentPixelShaderType); } // Hack variable for deciding which kind of texture rectangle thing to do (for some // reason it acts different on radeon! It's against the spec!). extern bool g_bTextureRectangleHack; -static inline void RB_BlurGlowTexture() -{ - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); +static inline void RB_BlurGlowTexture() { + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); // Go into orthographic 2d mode. qglMatrixMode(GL_PROJECTION); @@ -1723,26 +1585,23 @@ static inline void RB_BlurGlowTexture() // NOTE: The 0.25 is because we're blending 4 textures (so = 1.0) and we want a relatively normalized pixel // intensity distribution, but this won't happen anyways if intensity is higher than 1.0. float fBlurDistribution = r_DynamicGlowIntensity->value * 0.25f; - float fBlurWeight[4] = { fBlurDistribution, fBlurDistribution, fBlurDistribution, 1.0f }; + float fBlurWeight[4] = {fBlurDistribution, fBlurDistribution, fBlurDistribution, 1.0f}; // Enable and set the Vertex Program. - qglEnable( GL_VERTEX_PROGRAM_ARB ); - qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, tr.glowVShader ); + qglEnable(GL_VERTEX_PROGRAM_ARB); + qglBindProgramARB(GL_VERTEX_PROGRAM_ARB, tr.glowVShader); // Apply Pixel Shaders. - if ( qglCombinerParameterfvNV ) - { - BeginPixelShader( GL_REGISTER_COMBINERS_NV, tr.glowPShader ); + if (qglCombinerParameterfvNV) { + BeginPixelShader(GL_REGISTER_COMBINERS_NV, tr.glowPShader); // Pass the blur weight to the regcom. - qglCombinerParameterfvNV( GL_CONSTANT_COLOR0_NV, (float*)&fBlurWeight ); - } - else if ( qglProgramEnvParameter4fARB ) - { - BeginPixelShader( GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader ); + qglCombinerParameterfvNV(GL_CONSTANT_COLOR0_NV, (float *)&fBlurWeight); + } else if (qglProgramEnvParameter4fARB) { + BeginPixelShader(GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader); // Pass the blur weight to the Fragment Program. - qglProgramEnvParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 0, fBlurWeight[0], fBlurWeight[1], fBlurWeight[2], fBlurWeight[3] ); + qglProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, fBlurWeight[0], fBlurWeight[1], fBlurWeight[2], fBlurWeight[3]); } ///////////////////////////////////////////////////////// @@ -1754,87 +1613,84 @@ static inline void RB_BlurGlowTexture() GLuint uiTex = tr.screenGlow; - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); ///////////////////////////////////////////////////////// // Draw the blur passes (each pass blurs it more, increasing the blur radius ). ///////////////////////////////////////////////////////// - //int iTexWidth = backEnd.viewParms.viewportWidth, iTexHeight = backEnd.viewParms.viewportHeight; + // int iTexWidth = backEnd.viewParms.viewportWidth, iTexHeight = backEnd.viewParms.viewportHeight; int iTexWidth = glConfig.vidWidth, iTexHeight = glConfig.vidHeight; - for ( int iNumBlurPasses = 0; iNumBlurPasses < r_DynamicGlowPasses->integer; iNumBlurPasses++ ) - { + for (int iNumBlurPasses = 0; iNumBlurPasses < r_DynamicGlowPasses->integer; iNumBlurPasses++) { // Load the Texel Offsets into the Vertex Program. - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 0, -fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 1, -fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 2, fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 3, fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f ); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 0, -fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 1, -fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 2, fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 3, fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f); // After first pass put the tex coords to the viewport size. - if ( iNumBlurPasses == 1 ) - { - if ( !g_bTextureRectangleHack ) - { + if (iNumBlurPasses == 1) { + if (!g_bTextureRectangleHack) { iTexWidth = backEnd.viewParms.viewportWidth; iTexHeight = backEnd.viewParms.viewportHeight; } uiTex = tr.blurImage; - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); // Copy the current image over. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); } // Draw the fullscreen quad. - qglBegin( GL_QUADS ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, iTexHeight ); - qglVertex2f( 0, 0 ); + qglBegin(GL_QUADS); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, iTexHeight); + qglVertex2f(0, 0); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 0 ); - qglVertex2f( 0, backEnd.viewParms.viewportHeight ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 0); + qglVertex2f(0, backEnd.viewParms.viewportHeight); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, iTexWidth, 0 ); - qglVertex2f( backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, iTexWidth, 0); + qglVertex2f(backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, iTexWidth, iTexHeight ); - qglVertex2f( backEnd.viewParms.viewportWidth, 0 ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, iTexWidth, iTexHeight); + qglVertex2f(backEnd.viewParms.viewportWidth, 0); qglEnd(); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); // Increase the texel offsets. // NOTE: This is possibly the most important input to the effect. Even by using an exponential function I've been able to @@ -1846,20 +1702,20 @@ static inline void RB_BlurGlowTexture() } // Disable multi-texturing. - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); - qglDisable( GL_VERTEX_PROGRAM_ARB ); + qglDisable(GL_VERTEX_PROGRAM_ARB); EndPixelShader(); qglMatrixMode(GL_PROJECTION); @@ -1867,15 +1723,14 @@ static inline void RB_BlurGlowTexture() qglMatrixMode(GL_MODELVIEW); qglPopMatrix(); - qglDisable( GL_BLEND ); - glState.currenttmu = 0; //this matches the last one we activated + qglDisable(GL_BLEND); + glState.currenttmu = 0; // this matches the last one we activated } // Draw the glow blur over the screen additively. -static inline void RB_DrawGlowOverlay() -{ - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); +static inline void RB_DrawGlowOverlay() { + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); // Go into orthographic 2d mode. qglMatrixMode(GL_PROJECTION); @@ -1888,63 +1743,59 @@ static inline void RB_DrawGlowOverlay() GL_State(GLS_DEPTHTEST_DISABLE); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); // For debug purposes. - if ( r_DynamicGlow->integer != 2 ) - { + if (r_DynamicGlow->integer != 2) { // Render the normal scene texture. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage); qglBegin(GL_QUADS); - qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - qglTexCoord2f( 0, glConfig.vidHeight ); - qglVertex2f( 0, 0 ); + qglColor4f(1.0f, 1.0f, 1.0f, 1.0f); + qglTexCoord2f(0, glConfig.vidHeight); + qglVertex2f(0, 0); - qglTexCoord2f( 0, 0 ); - qglVertex2f( 0, glConfig.vidHeight ); + qglTexCoord2f(0, 0); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f( glConfig.vidWidth, 0 ); - qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); + qglTexCoord2f(glConfig.vidWidth, 0); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f( glConfig.vidWidth, glConfig.vidHeight ); - qglVertex2f( glConfig.vidWidth, 0 ); + qglTexCoord2f(glConfig.vidWidth, glConfig.vidHeight); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); } // One and Inverse Src Color give a very soft addition, while one one is a bit stronger. With one one we can // use additive blending through multitexture though. - if ( r_DynamicGlowSoft->integer ) - { - qglBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_COLOR ); - } - else - { - qglBlendFunc( GL_ONE, GL_ONE ); + if (r_DynamicGlowSoft->integer) { + qglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); + } else { + qglBlendFunc(GL_ONE, GL_ONE); } - qglEnable( GL_BLEND ); + qglEnable(GL_BLEND); // Now additively render the glow texture. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); qglBegin(GL_QUADS); - qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - qglTexCoord2f( 0, r_DynamicGlowHeight->integer ); - qglVertex2f( 0, 0 ); + qglColor4f(1.0f, 1.0f, 1.0f, 1.0f); + qglTexCoord2f(0, r_DynamicGlowHeight->integer); + qglVertex2f(0, 0); - qglTexCoord2f( 0, 0 ); - qglVertex2f( 0, glConfig.vidHeight ); + qglTexCoord2f(0, 0); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f( r_DynamicGlowWidth->integer, 0 ); - qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); + qglTexCoord2f(r_DynamicGlowWidth->integer, 0); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f( r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer ); - qglVertex2f( glConfig.vidWidth, 0 ); + qglTexCoord2f(r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); - qglBlendFunc( GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR ); - qglDisable( GL_BLEND ); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); + qglBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR); + qglDisable(GL_BLEND); qglMatrixMode(GL_PROJECTION); qglPopMatrix(); diff --git a/code/rd-vanilla/tr_bsp.cpp b/code/rd-vanilla/tr_bsp.cpp index afbbb175f6..e9caac7c34 100644 --- a/code/rd-vanilla/tr_bsp.cpp +++ b/code/rd-vanilla/tr_bsp.cpp @@ -39,31 +39,29 @@ void RE_LoadWorldMap( const char *name ); */ -static world_t s_worldData; -static byte *fileBase; +static world_t s_worldData; +static byte *fileBase; -int c_subdivisions; -int c_gridVerts; +int c_subdivisions; +int c_gridVerts; //=============================================================================== -static void HSVtoRGB( float h, float s, float v, float rgb[3] ) -{ +static void HSVtoRGB(float h, float s, float v, float rgb[3]) { int i; float f; float p, q, t; h *= 5; - i = floor( h ); + i = floor(h); f = h - i; - p = v * ( 1 - s ); - q = v * ( 1 - s * f ); - t = v * ( 1 - s * ( 1 - f ) ); + p = v * (1 - s); + q = v * (1 - s * f); + t = v * (1 - s * (1 - f)); - switch ( i ) - { + switch (i) { case 0: rgb[0] = v; rgb[1] = t; @@ -103,11 +101,11 @@ R_ColorShiftLightingBytes =============== */ -void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { +void R_ColorShiftLightingBytes(byte in[4], byte out[4]) { int shift, r, g, b; // shift the color data based on overbright range - shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + shift = Q_max(0, r_mapOverBrightBits->integer - tr.overbrightBits); // shift the data based on overbright range r = in[0] << shift; @@ -115,8 +113,8 @@ void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { b = in[2] << shift; // normalize by color instead of saturating to white - if ( (r|g|b) > 255 ) { - int max; + if ((r | g | b) > 255) { + int max; max = r > g ? r : g; max = max > b ? max : b; @@ -137,11 +135,11 @@ R_ColorShiftLightingBytes =============== */ -void R_ColorShiftLightingBytes( byte in[3] ) { +void R_ColorShiftLightingBytes(byte in[3]) { int shift, r, g, b; // shift the color data based on overbright range - shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + shift = Q_max(0, r_mapOverBrightBits->integer - tr.overbrightBits); // shift the data based on overbright range r = in[0] << shift; @@ -149,8 +147,8 @@ void R_ColorShiftLightingBytes( byte in[3] ) { b = in[2] << shift; // normalize by color instead of saturating to white - if ( (r|g|b) > 255 ) { - int max; + if ((r | g | b) > 255) { + int max; max = r > g ? r : g; max = max > b ? max : b; @@ -170,24 +168,22 @@ R_LoadLightmaps =============== */ -#define LIGHTMAP_SIZE 128 -static void R_LoadLightmaps( lump_t *l, const char *psMapName, world_t &worldData ) -{ - byte *buf, *buf_p; - int len; - byte image[LIGHTMAP_SIZE*LIGHTMAP_SIZE*4]; - int i, j; - float maxIntensity = 0; - double sumIntensity = 0; - int count; - - if (&worldData == &s_worldData) - { +#define LIGHTMAP_SIZE 128 +static void R_LoadLightmaps(lump_t *l, const char *psMapName, world_t &worldData) { + byte *buf, *buf_p; + int len; + byte image[LIGHTMAP_SIZE * LIGHTMAP_SIZE * 4]; + int i, j; + float maxIntensity = 0; + double sumIntensity = 0; + int count; + + if (&worldData == &s_worldData) { tr.numLightmaps = 0; } - len = l->filelen; - if ( !len ) { + len = l->filelen; + if (!len) { return; } buf = fileBase + l->fileofs; @@ -201,66 +197,60 @@ static void R_LoadLightmaps( lump_t *l, const char *psMapName, world_t &worldDat tr.numLightmaps += count; // if we are in r_vertexLight mode, we don't need the lightmaps at all - if ( r_vertexLight->integer ) { + if (r_vertexLight->integer) { return; } char sMapName[MAX_QPATH]; - COM_StripExtension(psMapName,sMapName, sizeof(sMapName)); + COM_StripExtension(psMapName, sMapName, sizeof(sMapName)); - for ( i = 0 ; i < count ; i++ ) { + for (i = 0; i < count; i++) { // expand the 24 bit on-disk to 32 bit - buf_p = buf + i * LIGHTMAP_SIZE*LIGHTMAP_SIZE * 3; - - if ( r_lightmap->integer == 2 ) - { // color code by intensity as development tool (FIXME: check range) - for ( j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ ) - { - float r = buf_p[j*3+0]; - float g = buf_p[j*3+1]; - float b = buf_p[j*3+2]; + buf_p = buf + i * LIGHTMAP_SIZE * LIGHTMAP_SIZE * 3; + + if (r_lightmap->integer == 2) { // color code by intensity as development tool (FIXME: check range) + for (j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++) { + float r = buf_p[j * 3 + 0]; + float g = buf_p[j * 3 + 1]; + float b = buf_p[j * 3 + 2]; float intensity; float out[3] = {0.0f, 0.0f, 0.0f}; intensity = 0.33f * r + 0.685f * g + 0.063f * b; - if ( intensity > 255 ) + if (intensity > 255) intensity = 1.0f; else intensity /= 255.0f; - if ( intensity > maxIntensity ) + if (intensity > maxIntensity) maxIntensity = intensity; - HSVtoRGB( intensity, 1.00, 0.50, out ); + HSVtoRGB(intensity, 1.00, 0.50, out); - image[j*4+0] = out[0] * 255; - image[j*4+1] = out[1] * 255; - image[j*4+2] = out[2] * 255; - image[j*4+3] = 255; + image[j * 4 + 0] = out[0] * 255; + image[j * 4 + 1] = out[1] * 255; + image[j * 4 + 2] = out[2] * 255; + image[j * 4 + 3] = 255; sumIntensity += intensity; } } else { - for ( j = 0 ; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ ) { - R_ColorShiftLightingBytes( &buf_p[j*3], &image[j*4] ); - image[j*4+3] = 255; + for (j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++) { + R_ColorShiftLightingBytes(&buf_p[j * 3], &image[j * 4]); + image[j * 4 + 3] = 255; } } - tr.lightmaps[worldData.startLightMapIndex+i] = R_CreateImage( - va("$%s/lightmap%d", sMapName, worldData.startLightMapIndex+i), - image, LIGHTMAP_SIZE, LIGHTMAP_SIZE, GL_RGBA, qfalse, qfalse, - (qboolean)(r_ext_compressed_lightmaps->integer != 0), - GL_CLAMP); + tr.lightmaps[worldData.startLightMapIndex + i] = + R_CreateImage(va("$%s/lightmap%d", sMapName, worldData.startLightMapIndex + i), image, LIGHTMAP_SIZE, LIGHTMAP_SIZE, GL_RGBA, qfalse, qfalse, + (qboolean)(r_ext_compressed_lightmaps->integer != 0), GL_CLAMP); } - if ( r_lightmap->integer == 2 ) { - ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) ); + if (r_lightmap->integer == 2) { + ri.Printf(PRINT_ALL, "Brightest lightmap value: %d\n", (int)(maxIntensity * 255)); } } - - /* ================= RE_SetWorldVisData @@ -269,42 +259,39 @@ This is called by the clipmodel subsystem so we can share the 1.8 megs of space in big maps... ================= */ -void RE_SetWorldVisData( const byte *vis ) { - tr.externalVisData = vis; -} - +void RE_SetWorldVisData(const byte *vis) { tr.externalVisData = vis; } /* ================= R_LoadVisibility ================= */ -static void R_LoadVisibility( lump_t *l, world_t &worldData ) { - int len; - byte *buf; +static void R_LoadVisibility(lump_t *l, world_t &worldData) { + int len; + byte *buf; - len = ( worldData.numClusters + 63 ) & ~63; - worldData.novis = ( unsigned char *) R_Hunk_Alloc( len, qfalse ); - memset( worldData.novis, 0xff, len ); + len = (worldData.numClusters + 63) & ~63; + worldData.novis = (unsigned char *)R_Hunk_Alloc(len, qfalse); + memset(worldData.novis, 0xff, len); - len = l->filelen; - if ( !len ) { + len = l->filelen; + if (!len) { return; } buf = fileBase + l->fileofs; - worldData.numClusters = LittleLong( ((int *)buf)[0] ); - worldData.clusterBytes = LittleLong( ((int *)buf)[1] ); + worldData.numClusters = LittleLong(((int *)buf)[0]); + worldData.clusterBytes = LittleLong(((int *)buf)[1]); // CM_Load should have given us the vis data to share, so // we don't need to allocate another copy - if ( tr.externalVisData ) { + if (tr.externalVisData) { worldData.vis = tr.externalVisData; } else { - byte *dest; + byte *dest; - dest = (byte *) R_Hunk_Alloc( len - 8, qfalse ); - memcpy( dest, buf + 8, len - 8 ); + dest = (byte *)R_Hunk_Alloc(len - 8, qfalse); + memcpy(dest, buf + 8, len - 8); worldData.vis = dest; } } @@ -316,40 +303,38 @@ static void R_LoadVisibility( lump_t *l, world_t &worldData ) { ShaderForShaderNum =============== */ -static shader_t *ShaderForShaderNum( int shaderNum, const int *lightmapNum, const byte *lightmapStyles, const byte *vertexStyles, world_t &worldData ) { - shader_t *shader; - dshader_t *dsh; - const byte *styles; +static shader_t *ShaderForShaderNum(int shaderNum, const int *lightmapNum, const byte *lightmapStyles, const byte *vertexStyles, world_t &worldData) { + shader_t *shader; + dshader_t *dsh; + const byte *styles; styles = lightmapStyles; - shaderNum = LittleLong( shaderNum ); - if ( shaderNum < 0 || shaderNum >= worldData.numShaders ) { - Com_Error( ERR_DROP, "ShaderForShaderNum: bad num %i", shaderNum ); + shaderNum = LittleLong(shaderNum); + if (shaderNum < 0 || shaderNum >= worldData.numShaders) { + Com_Error(ERR_DROP, "ShaderForShaderNum: bad num %i", shaderNum); } - dsh = &worldData.shaders[ shaderNum ]; + dsh = &worldData.shaders[shaderNum]; - if (lightmapNum[0] == LIGHTMAP_BY_VERTEX) - { + if (lightmapNum[0] == LIGHTMAP_BY_VERTEX) { styles = vertexStyles; } - if ( r_vertexLight->integer ) - { + if (r_vertexLight->integer) { lightmapNum = lightmapsVertex; styles = vertexStyles; } -/* if ( r_fullbright->integer ) - { - lightmapNum = lightmapsFullBright; - styles = vertexStyles; - } -*/ - shader = R_FindShader( dsh->shader, lightmapNum, styles, qtrue ); + /* if ( r_fullbright->integer ) + { + lightmapNum = lightmapsFullBright; + styles = vertexStyles; + } + */ + shader = R_FindShader(dsh->shader, lightmapNum, styles, qtrue); // if the shader had errors, just use default shader - if ( shader->defaultShader ) { + if (shader->defaultShader) { return tr.defaultShader; } @@ -361,169 +346,157 @@ static shader_t *ShaderForShaderNum( int shaderNum, const int *lightmapNum, cons ParseFace =============== */ -static void ParseFace( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, byte *&pFaceDataBuffer, world_t &worldData, int index ) -{ - int i, j, k; - srfSurfaceFace_t *cv; - int numPoints, numIndexes; - int lightmapNum[MAXLIGHTMAPS]; - int sfaceSize, ofsIndexes; - - for(i=0;ilightmapNum[i] ); - if (lightmapNum[i] >= 0) - { +static void ParseFace(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, byte *&pFaceDataBuffer, world_t &worldData, int index) { + int i, j, k; + srfSurfaceFace_t *cv; + int numPoints, numIndexes; + int lightmapNum[MAXLIGHTMAPS]; + int sfaceSize, ofsIndexes; + + for (i = 0; i < MAXLIGHTMAPS; i++) { + lightmapNum[i] = LittleLong(ds->lightmapNum[i]); + if (lightmapNum[i] >= 0) { lightmapNum[i] += worldData.startLightMapIndex; } } // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader value - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - numPoints = LittleLong( ds->numVerts ); - numIndexes = LittleLong( ds->numIndexes ); + numPoints = LittleLong(ds->numVerts); + numIndexes = LittleLong(ds->numIndexes); // create the srfSurfaceFace_t - sfaceSize = sizeof( *cv ) - sizeof( cv->points ) + sizeof( cv->points[0] ) * numPoints; + sfaceSize = sizeof(*cv) - sizeof(cv->points) + sizeof(cv->points[0]) * numPoints; ofsIndexes = sfaceSize; - sfaceSize += sizeof( int ) * numIndexes; + sfaceSize += sizeof(int) * numIndexes; - cv = (srfSurfaceFace_t *) pFaceDataBuffer;//R_Hunk_Alloc( sfaceSize ); - pFaceDataBuffer += sfaceSize; // :-) + cv = (srfSurfaceFace_t *)pFaceDataBuffer; // R_Hunk_Alloc( sfaceSize ); + pFaceDataBuffer += sfaceSize; // :-) cv->surfaceType = SF_FACE; cv->numPoints = numPoints; cv->numIndices = numIndexes; cv->ofsIndices = ofsIndexes; - verts += LittleLong( ds->firstVert ); - for ( i = 0 ; i < numPoints ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - cv->points[i][j] = LittleFloat( verts[i].xyz[j] ); + verts += LittleLong(ds->firstVert); + for (i = 0; i < numPoints; i++) { + for (j = 0; j < 3; j++) { + cv->points[i][j] = LittleFloat(verts[i].xyz[j]); } - for ( j = 0 ; j < 2 ; j++ ) { - cv->points[i][3+j] = LittleFloat( verts[i].st[j] ); - for(k=0;kpoints[i][VERTEX_LM+j+(k*2)] = LittleFloat( verts[i].lightmap[k][j] ); + for (j = 0; j < 2; j++) { + cv->points[i][3 + j] = LittleFloat(verts[i].st[j]); + for (k = 0; k < MAXLIGHTMAPS; k++) { + cv->points[i][VERTEX_LM + j + (k * 2)] = LittleFloat(verts[i].lightmap[k][j]); } } - for(k=0;kpoints[i][VERTEX_COLOR+k] ); + for (k = 0; k < MAXLIGHTMAPS; k++) { + R_ColorShiftLightingBytes(verts[i].color[k], (byte *)&cv->points[i][VERTEX_COLOR + k]); } } - indexes += LittleLong( ds->firstIndex ); - for ( i = 0 ; i < numIndexes ; i++ ) { - ((int *)((byte *)cv + cv->ofsIndices ))[i] = LittleLong( indexes[ i ] ); + indexes += LittleLong(ds->firstIndex); + for (i = 0; i < numIndexes; i++) { + ((int *)((byte *)cv + cv->ofsIndices))[i] = LittleLong(indexes[i]); } // take the plane information from the lightmap vector - for ( i = 0 ; i < 3 ; i++ ) { - cv->plane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + cv->plane.normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } - cv->plane.dist = DotProduct( cv->points[0], cv->plane.normal ); - SetPlaneSignbits( &cv->plane ); - cv->plane.type = PlaneTypeForNormal( cv->plane.normal ); + cv->plane.dist = DotProduct(cv->points[0], cv->plane.normal); + SetPlaneSignbits(&cv->plane); + cv->plane.type = PlaneTypeForNormal(cv->plane.normal); surf->data = (surfaceType_t *)cv; } - /* =============== ParseMesh =============== */ -static void ParseMesh ( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, world_t &worldData, int index) { - srfGridMesh_t *grid; - int i, j, k; - int width, height, numPoints; - drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE]; - int lightmapNum[MAXLIGHTMAPS]; - vec3_t bounds[2]; - vec3_t tmpVec; - static surfaceType_t skipData = SF_SKIP; - - for(i=0;ilightmapNum[i] ); - if (lightmapNum[i] >= 0) - { +static void ParseMesh(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, world_t &worldData, int index) { + srfGridMesh_t *grid; + int i, j, k; + int width, height, numPoints; + drawVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]; + int lightmapNum[MAXLIGHTMAPS]; + vec3_t bounds[2]; + vec3_t tmpVec; + static surfaceType_t skipData = SF_SKIP; + + for (i = 0; i < MAXLIGHTMAPS; i++) { + lightmapNum[i] = LittleLong(ds->lightmapNum[i]); + if (lightmapNum[i] >= 0) { lightmapNum[i] += worldData.startLightMapIndex; } } // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader value - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } // we may have a nodraw surface, because they might still need to // be around for movement clipping - if ( worldData.shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) { + if (worldData.shaders[LittleLong(ds->shaderNum)].surfaceFlags & SURF_NODRAW) { surf->data = &skipData; return; } - width = LittleLong( ds->patchWidth ); - height = LittleLong( ds->patchHeight ); + width = LittleLong(ds->patchWidth); + height = LittleLong(ds->patchHeight); - verts += LittleLong( ds->firstVert ); + verts += LittleLong(ds->firstVert); numPoints = width * height; - for ( i = 0 ; i < numPoints ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - points[i].xyz[j] = LittleFloat( verts[i].xyz[j] ); - points[i].normal[j] = LittleFloat( verts[i].normal[j] ); + for (i = 0; i < numPoints; i++) { + for (j = 0; j < 3; j++) { + points[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + points[i].normal[j] = LittleFloat(verts[i].normal[j]); } - for ( j = 0 ; j < 2 ; j++ ) { - points[i].st[j] = LittleFloat( verts[i].st[j] ); - for(k=0;kdata = (surfaceType_t *)grid; // copy the level of detail origin, which is the center // of the group of all curves that must subdivide the same // to avoid cracking - for ( i = 0 ; i < 3 ; i++ ) { - bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] ); - bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] ); - } - VectorAdd( bounds[0], bounds[1], bounds[1] ); - VectorScale( bounds[1], 0.5f, grid->lodOrigin ); - VectorSubtract( bounds[0], grid->lodOrigin, tmpVec ); - grid->lodRadius = VectorLength( tmpVec ); + for (i = 0; i < 3; i++) { + bounds[0][i] = LittleFloat(ds->lightmapVecs[0][i]); + bounds[1][i] = LittleFloat(ds->lightmapVecs[1][i]); + } + VectorAdd(bounds[0], bounds[1], bounds[1]); + VectorScale(bounds[1], 0.5f, grid->lodOrigin); + VectorSubtract(bounds[0], grid->lodOrigin, tmpVec); + grid->lodRadius = VectorLength(tmpVec); } /* @@ -531,72 +504,69 @@ static void ParseMesh ( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, worl ParseTriSurf =============== */ -static void ParseTriSurf( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index ) { - srfTriangles_t *tri; - int i, j, k; - int numVerts, numIndexes; +static void ParseTriSurf(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index) { + srfTriangles_t *tri; + int i, j, k; + int numVerts, numIndexes; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - numVerts = LittleLong( ds->numVerts ); - numIndexes = LittleLong( ds->numIndexes ); + numVerts = LittleLong(ds->numVerts); + numIndexes = LittleLong(ds->numIndexes); - if ( numVerts >= SHADER_MAX_VERTEXES ) { - Com_Error(ERR_DROP, "ParseTriSurf: verts > MAX (%d > %d) on misc_model %s", numVerts, SHADER_MAX_VERTEXES, surf->shader->name ); + if (numVerts >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "ParseTriSurf: verts > MAX (%d > %d) on misc_model %s", numVerts, SHADER_MAX_VERTEXES, surf->shader->name); } - if ( numIndexes >= SHADER_MAX_INDEXES ) { - Com_Error(ERR_DROP, "ParseTriSurf: indices > MAX (%d > %d) on misc_model %s", numIndexes, SHADER_MAX_INDEXES, surf->shader->name ); + if (numIndexes >= SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "ParseTriSurf: indices > MAX (%d > %d) on misc_model %s", numIndexes, SHADER_MAX_INDEXES, surf->shader->name); } - tri = (srfTriangles_t *) R_Malloc( sizeof( *tri ) + numVerts * sizeof( tri->verts[0] ) + numIndexes * sizeof( tri->indexes[0] ), TAG_HUNKMISCMODELS, qfalse ); - tri->dlightBits = 0; //JIC + tri = (srfTriangles_t *)R_Malloc(sizeof(*tri) + numVerts * sizeof(tri->verts[0]) + numIndexes * sizeof(tri->indexes[0]), TAG_HUNKMISCMODELS, qfalse); + tri->dlightBits = 0; // JIC tri->surfaceType = SF_TRIANGLES; tri->numVerts = numVerts; tri->numIndexes = numIndexes; tri->verts = (drawVert_t *)(tri + 1); - tri->indexes = (int *)(tri->verts + tri->numVerts ); + tri->indexes = (int *)(tri->verts + tri->numVerts); surf->data = (surfaceType_t *)tri; // copy vertexes - verts += LittleLong( ds->firstVert ); - ClearBounds( tri->bounds[0], tri->bounds[1] ); - for ( i = 0 ; i < numVerts ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - tri->verts[i].xyz[j] = LittleFloat( verts[i].xyz[j] ); - tri->verts[i].normal[j] = LittleFloat( verts[i].normal[j] ); + verts += LittleLong(ds->firstVert); + ClearBounds(tri->bounds[0], tri->bounds[1]); + for (i = 0; i < numVerts; i++) { + for (j = 0; j < 3; j++) { + tri->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + tri->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); } - AddPointToBounds( tri->verts[i].xyz, tri->bounds[0], tri->bounds[1] ); - for ( j = 0 ; j < 2 ; j++ ) { - tri->verts[i].st[j] = LittleFloat( verts[i].st[j] ); - for(k=0;kverts[i].lightmap[k][j] = LittleFloat( verts[i].lightmap[k][j] ); + AddPointToBounds(tri->verts[i].xyz, tri->bounds[0], tri->bounds[1]); + for (j = 0; j < 2; j++) { + tri->verts[i].st[j] = LittleFloat(verts[i].st[j]); + for (k = 0; k < MAXLIGHTMAPS; k++) { + tri->verts[i].lightmap[k][j] = LittleFloat(verts[i].lightmap[k][j]); } } - for(k=0;kverts[i].color[k] ); + for (k = 0; k < MAXLIGHTMAPS; k++) { + R_ColorShiftLightingBytes(verts[i].color[k], tri->verts[i].color[k]); } } // copy indexes - indexes += LittleLong( ds->firstIndex ); - for ( i = 0 ; i < numIndexes ; i++ ) { - tri->indexes[i] = LittleLong( indexes[i] ); - if ( tri->indexes[i] < 0 || tri->indexes[i] >= numVerts ) { - Com_Error( ERR_DROP, "Bad index in triangle surface" ); + indexes += LittleLong(ds->firstIndex); + for (i = 0; i < numIndexes; i++) { + tri->indexes[i] = LittleLong(indexes[i]); + if (tri->indexes[i] < 0 || tri->indexes[i] >= numVerts) { + Com_Error(ERR_DROP, "Bad index in triangle surface"); } } } @@ -606,33 +576,32 @@ static void ParseTriSurf( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, in ParseFlare =============== */ -static void ParseFlare( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index ) { - srfFlare_t *flare; - int i; - int lightmaps[MAXLIGHTMAPS] = { LIGHTMAP_BY_VERTEX }; +static void ParseFlare(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index) { + srfFlare_t *flare; + int i; + int lightmaps[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX}; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmaps, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmaps, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - flare = (srfFlare_t *) R_Hunk_Alloc( sizeof( *flare ), qtrue ); + flare = (srfFlare_t *)R_Hunk_Alloc(sizeof(*flare), qtrue); flare->surfaceType = SF_FLARE; surf->data = (surfaceType_t *)flare; - for ( i = 0 ; i < 3 ; i++ ) { - flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] ); - flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] ); - flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + flare->origin[i] = LittleFloat(ds->lightmapOrigin[i]); + flare->color[i] = LittleFloat(ds->lightmapVecs[0][i]); + flare->normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } } @@ -641,14 +610,14 @@ static void ParseFlare( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int R_LoadSurfaces =============== */ -static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump, world_t &worldData, int index ) { - dsurface_t *in; - msurface_t *out; - mapVert_t *dv; - int *indexes; - int count; - int numFaces, numMeshes, numTriSurfs, numFlares; - int i; +static void R_LoadSurfaces(lump_t *surfs, lump_t *verts, lump_t *indexLump, world_t &worldData, int index) { + dsurface_t *in; + msurface_t *out; + mapVert_t *dv; + int *indexes; + int count; + int numFaces, numMeshes, numTriSurfs, numFlares; + int i; numFaces = 0; numMeshes = 0; @@ -657,18 +626,18 @@ static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump, wor in = (dsurface_t *)(fileBase + surfs->fileofs); if (surfs->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = surfs->filelen / sizeof(*in); dv = (mapVert_t *)(fileBase + verts->fileofs); if (verts->filelen % sizeof(*dv)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); indexes = (int *)(fileBase + indexLump->fileofs); - if ( indexLump->filelen % sizeof(*indexes)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + if (indexLump->filelen % sizeof(*indexes)) + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); - out = (struct msurface_s *) R_Hunk_Alloc ( count * sizeof(*out), qtrue ); + out = (struct msurface_s *)R_Hunk_Alloc(count * sizeof(*out), qtrue); worldData.surfaces = out; worldData.numsurfaces = count; @@ -678,116 +647,106 @@ static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump, wor // so special-case pre-alloc enough space for this data (the patches etc can stay as they are)... // int iFaceDataSizeRequired = 0; - for ( i = 0 ; i < count ; i++, in++) - { - switch ( LittleLong( in->surfaceType ) ) - { - case MST_PLANAR: + for (i = 0; i < count; i++, in++) { + switch (LittleLong(in->surfaceType)) { + case MST_PLANAR: - int sfaceSize = sizeof( srfSurfaceFace_t ) - sizeof( float[1][VERTEXSIZE] ) + sizeof( float[VERTEXSIZE] ) * LittleLong(in->numVerts); - sfaceSize += sizeof( int ) * LittleLong(in->numIndexes); + int sfaceSize = sizeof(srfSurfaceFace_t) - sizeof(float[1][VERTEXSIZE]) + sizeof(float[VERTEXSIZE]) * LittleLong(in->numVerts); + sfaceSize += sizeof(int) * LittleLong(in->numIndexes); - iFaceDataSizeRequired += sfaceSize; - break; + iFaceDataSizeRequired += sfaceSize; + break; } } - in -= count; // back it up, ready for loop-proper + in -= count; // back it up, ready for loop-proper // since this ptr is to hunk data, I can pass it in and have it advanced without worrying about losing // the original alloc ptr... // - byte *pFaceDataBuffer = (byte *)R_Hunk_Alloc( iFaceDataSizeRequired, qtrue ); + byte *pFaceDataBuffer = (byte *)R_Hunk_Alloc(iFaceDataSizeRequired, qtrue); // now do regular loop... // - for ( i = 0 ; i < count ; i++, in++, out++ ) { - switch ( LittleLong( in->surfaceType ) ) { + for (i = 0; i < count; i++, in++, out++) { + switch (LittleLong(in->surfaceType)) { case MST_PATCH: - ParseMesh ( in, dv, out, worldData, index ); + ParseMesh(in, dv, out, worldData, index); numMeshes++; break; case MST_TRIANGLE_SOUP: - ParseTriSurf( in, dv, out, indexes, worldData, index ); + ParseTriSurf(in, dv, out, indexes, worldData, index); numTriSurfs++; break; case MST_PLANAR: - ParseFace( in, dv, out, indexes, pFaceDataBuffer, worldData, index ); + ParseFace(in, dv, out, indexes, pFaceDataBuffer, worldData, index); numFaces++; break; case MST_FLARE: - ParseFlare( in, dv, out, indexes, worldData, index ); + ParseFlare(in, dv, out, indexes, worldData, index); numFlares++; break; default: - Com_Error( ERR_DROP, "Bad surfaceType" ); + Com_Error(ERR_DROP, "Bad surfaceType"); } } - ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", - numFaces, numMeshes, numTriSurfs, numFlares ); + ri.Printf(PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", numFaces, numMeshes, numTriSurfs, numFlares); } - - /* ================= R_LoadSubmodels ================= */ -static void R_LoadSubmodels( lump_t *l, world_t &worldData, int index ) { - dmodel_t *in; - bmodel_t *out; - int i, j, count; +static void R_LoadSubmodels(lump_t *l, world_t &worldData, int index) { + dmodel_t *in; + bmodel_t *out; + int i, j, count; in = (dmodel_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - worldData.bmodels = out = (bmodel_t *) R_Hunk_Alloc( count * sizeof(*out), qtrue ); + worldData.bmodels = out = (bmodel_t *)R_Hunk_Alloc(count * sizeof(*out), qtrue); - for ( i=0 ; itype = MOD_BRUSH; model->bmodel = out; - if (index) - { - Com_sprintf( model->name, sizeof( model->name ), "*%d-%d", index, i ); + if (index) { + Com_sprintf(model->name, sizeof(model->name), "*%d-%d", index, i); model->bspInstance = true; - } - else - { - Com_sprintf( model->name, sizeof( model->name ), "*%d", i); + } else { + Com_sprintf(model->name, sizeof(model->name), "*%d", i); } - for (j=0 ; j<3 ; j++) { - out->bounds[0][j] = LittleFloat (in->mins[j]); - out->bounds[1][j] = LittleFloat (in->maxs[j]); + for (j = 0; j < 3; j++) { + out->bounds[0][j] = LittleFloat(in->mins[j]); + out->bounds[1][j] = LittleFloat(in->maxs[j]); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ RE_InsertModelIntoHash(model->name, model); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - out->firstSurface = worldData.surfaces + LittleLong( in->firstSurface ); - out->numSurfaces = LittleLong( in->numSurfaces ); + out->firstSurface = worldData.surfaces + LittleLong(in->firstSurface); + out->numSurfaces = LittleLong(in->numSurfaces); } } - - //================================================================== /* @@ -795,13 +754,12 @@ Ghoul2 Insert End R_SetParent ================= */ -static void R_SetParent (mnode_t *node, mnode_t *parent) -{ +static void R_SetParent(mnode_t *node, mnode_t *parent) { node->parent = parent; if (node->contents != -1) return; - R_SetParent (node->children[0], node); - R_SetParent (node->children[1], node); + R_SetParent(node->children[0], node); + R_SetParent(node->children[1], node); } /* @@ -809,44 +767,40 @@ static void R_SetParent (mnode_t *node, mnode_t *parent) R_LoadNodesAndLeafs ================= */ -static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &worldData) { - int i, j, p; - dnode_t *in; - dleaf_t *inLeaf; - mnode_t *out; - int numNodes, numLeafs; +static void R_LoadNodesAndLeafs(lump_t *nodeLump, lump_t *leafLump, world_t &worldData) { + int i, j, p; + dnode_t *in; + dleaf_t *inLeaf; + mnode_t *out; + int numNodes, numLeafs; in = (dnode_t *)(fileBase + nodeLump->fileofs); - if (nodeLump->filelen % sizeof(dnode_t) || - leafLump->filelen % sizeof(dleaf_t) ) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + if (nodeLump->filelen % sizeof(dnode_t) || leafLump->filelen % sizeof(dleaf_t)) { + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } numNodes = nodeLump->filelen / sizeof(dnode_t); numLeafs = leafLump->filelen / sizeof(dleaf_t); - out = (struct mnode_s *) R_Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), qtrue ); + out = (struct mnode_s *)R_Hunk_Alloc((numNodes + numLeafs) * sizeof(*out), qtrue); worldData.nodes = out; worldData.numnodes = numNodes + numLeafs; worldData.numDecisionNodes = numNodes; // load nodes - for ( i=0 ; imins[j] = LittleLong (in->mins[j]); - out->maxs[j] = LittleLong (in->maxs[j]); + for (i = 0; i < numNodes; i++, in++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(in->mins[j]); + out->maxs[j] = LittleLong(in->maxs[j]); } p = LittleLong(in->planeNum); out->plane = worldData.planes + p; - out->contents = CONTENTS_NODE; // differentiate from leafs + out->contents = CONTENTS_NODE; // differentiate from leafs - for (j=0 ; j<2 ; j++) - { - p = LittleLong (in->children[j]); + for (j = 0; j < 2; j++) { + p = LittleLong(in->children[j]); if (p >= 0) out->children[j] = worldData.nodes + p; else @@ -856,28 +810,25 @@ static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &wo // load leafs inLeaf = (dleaf_t *)(fileBase + leafLump->fileofs); - for ( i=0 ; imins[j] = LittleLong (inLeaf->mins[j]); - out->maxs[j] = LittleLong (inLeaf->maxs[j]); + for (i = 0; i < numLeafs; i++, inLeaf++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(inLeaf->mins[j]); + out->maxs[j] = LittleLong(inLeaf->maxs[j]); } out->cluster = LittleLong(inLeaf->cluster); out->area = LittleLong(inLeaf->area); - if ( out->cluster >= worldData.numClusters ) { + if (out->cluster >= worldData.numClusters) { worldData.numClusters = out->cluster + 1; } - out->firstmarksurface = worldData.marksurfaces + - LittleLong(inLeaf->firstLeafSurface); + out->firstmarksurface = worldData.marksurfaces + LittleLong(inLeaf->firstLeafSurface); out->nummarksurfaces = LittleLong(inLeaf->numLeafSurfaces); } // chain decendants - R_SetParent (worldData.nodes, NULL); + R_SetParent(worldData.nodes, NULL); } //============================================================================= @@ -887,88 +838,84 @@ static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &wo R_LoadShaders ================= */ -static void R_LoadShaders( lump_t *l, world_t &worldData ) { - int i, count; - dshader_t *in, *out; +static void R_LoadShaders(lump_t *l, world_t &worldData) { + int i, count; + dshader_t *in, *out; in = (dshader_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (dshader_t *) R_Hunk_Alloc ( count*sizeof(*out), qfalse ); + out = (dshader_t *)R_Hunk_Alloc(count * sizeof(*out), qfalse); worldData.shaders = out; worldData.numShaders = count; - memcpy( out, in, count*sizeof(*out) ); + memcpy(out, in, count * sizeof(*out)); - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (struct msurface_s **) R_Hunk_Alloc ( count*sizeof(*out), qtrue ); + out = (struct msurface_s **)R_Hunk_Alloc(count * sizeof(*out), qtrue); worldData.marksurfaces = out; worldData.nummarksurfaces = count; - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (struct cplane_s *) R_Hunk_Alloc ( count*2*sizeof(*out), qtrue ); + out = (struct cplane_s *)R_Hunk_Alloc(count * 2 * sizeof(*out), qtrue); worldData.planes = out; worldData.numplanes = count; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + for (j = 0; j < 3; j++) { + out->normal[j] = LittleFloat(in->normal[j]); if (out->normal[j] < 0) { - bits |= 1<dist = LittleFloat (in->dist); - out->type = PlaneTypeForNormal( out->normal ); + out->dist = LittleFloat(in->dist); + out->type = PlaneTypeForNormal(out->normal); out->signbits = bits; } } @@ -979,37 +926,35 @@ R_LoadFogs ================= */ -static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world_t &worldData, int index ) { - int i; - fog_t *out; - dfog_t *fogs; - dbrush_t *brushes, *brush; - dbrushside_t *sides; - int count, brushesCount, sidesCount; - int sideNum; - int planeNum; - shader_t *shader; - float d; - int firstSide=0; - int lightmaps[MAXLIGHTMAPS] = { LIGHTMAP_NONE } ; +static void R_LoadFogs(lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world_t &worldData, int index) { + int i; + fog_t *out; + dfog_t *fogs; + dbrush_t *brushes, *brush; + dbrushside_t *sides; + int count, brushesCount, sidesCount; + int sideNum; + int planeNum; + shader_t *shader; + float d; + int firstSide = 0; + int lightmaps[MAXLIGHTMAPS] = {LIGHTMAP_NONE}; fogs = (dfog_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*fogs)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } count = l->filelen / sizeof(*fogs); // create fog strucutres for them worldData.numfogs = count + 1; - worldData.fogs = (fog_t *)R_Hunk_Alloc ( (worldData.numfogs+1)*sizeof(*out), qtrue); + worldData.fogs = (fog_t *)R_Hunk_Alloc((worldData.numfogs + 1) * sizeof(*out), qtrue); worldData.globalFog = -1; out = worldData.fogs + 1; // Copy the global fog from the main world into the bsp instance - if(index) - { - if(tr.world && (tr.world->globalFog != -1)) - { + if (index) { + if (tr.world && (tr.world->globalFog != -1)) { // Use the nightvision fog slot worldData.fogs[worldData.numfogs] = tr.world->fogs[tr.world->globalFog]; worldData.globalFog = worldData.numfogs; @@ -1017,112 +962,102 @@ static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world } } - if ( !count ) { + if (!count) { return; } brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); if (brushesLump->filelen % sizeof(*brushes)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } brushesCount = brushesLump->filelen / sizeof(*brushes); sides = (dbrushside_t *)(fileBase + sidesLump->fileofs); if (sidesLump->filelen % sizeof(*sides)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } sidesCount = sidesLump->filelen / sizeof(*sides); - for ( i=0 ; ioriginalBrushNumber = LittleLong( fogs->brushNum ); - if (out->originalBrushNumber == -1) - { - if(index) - { - Com_Error (ERR_DROP, "LoadMap: global fog not allowed in bsp instances - %s", worldData.name); + for (i = 0; i < count; i++, fogs++) { + out->originalBrushNumber = LittleLong(fogs->brushNum); + if (out->originalBrushNumber == -1) { + if (index) { + Com_Error(ERR_DROP, "LoadMap: global fog not allowed in bsp instances - %s", worldData.name); } VectorSet(out->bounds[0], MIN_WORLD_COORD, MIN_WORLD_COORD, MIN_WORLD_COORD); VectorSet(out->bounds[1], MAX_WORLD_COORD, MAX_WORLD_COORD, MAX_WORLD_COORD); worldData.globalFog = i + 1; - } - else - { - if ( (unsigned)out->originalBrushNumber >= (unsigned)brushesCount ) { - Com_Error( ERR_DROP, "fog brushNumber out of range" ); + } else { + if ((unsigned)out->originalBrushNumber >= (unsigned)brushesCount) { + Com_Error(ERR_DROP, "fog brushNumber out of range"); } brush = brushes + out->originalBrushNumber; - firstSide = LittleLong( brush->firstSide ); + firstSide = LittleLong(brush->firstSide); - if ( (unsigned)firstSide > (unsigned)(sidesCount - 6) ) { - Com_Error( ERR_DROP, "fog brush sideNumber out of range" ); + if ((unsigned)firstSide > (unsigned)(sidesCount - 6)) { + Com_Error(ERR_DROP, "fog brush sideNumber out of range"); } // brushes are always sorted with the axial sides first sideNum = firstSide + 0; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][0] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][0] = -worldData.planes[planeNum].dist; sideNum = firstSide + 1; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][0] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][0] = worldData.planes[planeNum].dist; sideNum = firstSide + 2; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][1] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][1] = -worldData.planes[planeNum].dist; sideNum = firstSide + 3; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][1] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][1] = worldData.planes[planeNum].dist; sideNum = firstSide + 4; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][2] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][2] = -worldData.planes[planeNum].dist; sideNum = firstSide + 5; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][2] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][2] = worldData.planes[planeNum].dist; } // get information from the shader for fog parameters - shader = R_FindShader( fogs->shader, lightmaps, stylesDefault, qtrue ); + shader = R_FindShader(fogs->shader, lightmaps, stylesDefault, qtrue); assert(shader->fogParms); - if (!shader->fogParms) - {//bad shader!! + if (!shader->fogParms) { // bad shader!! out->parms.color[0] = 1.0f; out->parms.color[1] = 0.0f; out->parms.color[2] = 0.0f; out->parms.depthForOpaque = 250.0f; - } - else - { + } else { out->parms = *shader->fogParms; } - out->colorInt = ColorBytes4 ( out->parms.color[0], - out->parms.color[1], - out->parms.color[2], 1.0 ); + out->colorInt = ColorBytes4(out->parms.color[0], out->parms.color[1], out->parms.color[2], 1.0); d = out->parms.depthForOpaque < 1 ? 1 : out->parms.depthForOpaque; - out->tcScale = 1.0f / ( d * 8 ); + out->tcScale = 1.0f / (d * 8); // set the gradient vector - sideNum = LittleLong( fogs->visibleSide ); + sideNum = LittleLong(fogs->visibleSide); - if ( sideNum == -1 ) { + if (sideNum == -1) { out->hasSurface = qfalse; } else { out->hasSurface = qtrue; - planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum ); - VectorSubtract( vec3_origin, worldData.planes[ planeNum ].normal, out->surface ); - out->surface[3] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[firstSide + sideNum].planeNum); + VectorSubtract(vec3_origin, worldData.planes[planeNum].normal, out->surface); + out->surface[3] = -worldData.planes[planeNum].dist; } out++; } - if (!index) - { + if (!index) { // Initialise the last fog so we can use it with the LA Goggles // NOTE: We are might appear to be off the end of the array, but we allocated an extra memory slot above but [purposely] didn't // increment the total world numFogs to match our array size @@ -1139,18 +1074,17 @@ static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world } } - /* ================ R_LoadLightGrid ================ */ -void R_LoadLightGrid( lump_t *l, world_t &worldData ) { - int i, j; - vec3_t maxs; - world_t *w; - float *wMins, *wMaxs; +void R_LoadLightGrid(lump_t *l, world_t &worldData) { + int i, j; + vec3_t maxs; + world_t *w; + float *wMins, *wMaxs; w = &worldData; @@ -1161,21 +1095,20 @@ void R_LoadLightGrid( lump_t *l, world_t &worldData ) { wMins = w->bmodels[0].bounds[0]; wMaxs = w->bmodels[0].bounds[1]; - for ( i = 0 ; i < 3 ; i++ ) { - w->lightGridOrigin[i] = w->lightGridSize[i] * ceil( wMins[i] / w->lightGridSize[i] ); - maxs[i] = w->lightGridSize[i] * floor( wMaxs[i] / w->lightGridSize[i] ); - w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i])/w->lightGridSize[i] + 1; + for (i = 0; i < 3; i++) { + w->lightGridOrigin[i] = w->lightGridSize[i] * ceil(wMins[i] / w->lightGridSize[i]); + maxs[i] = w->lightGridSize[i] * floor(wMaxs[i] / w->lightGridSize[i]); + w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i]) / w->lightGridSize[i] + 1; } int numGridDataElements = l->filelen / sizeof(*w->lightGridData); - w->lightGridData = (mgrid_t *)R_Hunk_Alloc( l->filelen, qfalse ); - memcpy( w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen ); + w->lightGridData = (mgrid_t *)R_Hunk_Alloc(l->filelen, qfalse); + memcpy(w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen); // deal with overbright bits - for ( i = 0 ; i < numGridDataElements ; i++ ) { - for(j=0;jlightGridData[i].ambientLight[j]); R_ColorShiftLightingBytes(w->lightGridData[i].directLight[j]); } @@ -1188,8 +1121,8 @@ R_LoadLightGridArray ================ */ -void R_LoadLightGridArray( lump_t *l, world_t &worldData ) { - world_t *w; +void R_LoadLightGridArray(lump_t *l, world_t &worldData) { + world_t *w; #ifdef Q3_BIG_ENDIAN int i; #endif @@ -1198,33 +1131,32 @@ void R_LoadLightGridArray( lump_t *l, world_t &worldData ) { w->numGridArrayElements = w->lightGridBounds[0] * w->lightGridBounds[1] * w->lightGridBounds[2]; - if ( l->filelen != (int)(w->numGridArrayElements * sizeof(*w->lightGridArray)) ) { - if (l->filelen>0)//don't warn if not even lit - ri.Printf( PRINT_WARNING, "WARNING: light grid array mismatch\n" ); + if (l->filelen != (int)(w->numGridArrayElements * sizeof(*w->lightGridArray))) { + if (l->filelen > 0) // don't warn if not even lit + ri.Printf(PRINT_WARNING, "WARNING: light grid array mismatch\n"); w->lightGridData = NULL; return; } - w->lightGridArray = (unsigned short *)R_Hunk_Alloc( l->filelen, qfalse ); - memcpy( w->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen ); + w->lightGridArray = (unsigned short *)R_Hunk_Alloc(l->filelen, qfalse); + memcpy(w->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen); #ifdef Q3_BIG_ENDIAN - for ( i = 0 ; i < w->numGridArrayElements ; i++ ) { + for (i = 0; i < w->numGridArrayElements; i++) { w->lightGridArray[i] = LittleShort(w->lightGridArray[i]); } #endif } - /* ================ R_LoadEntities ================ */ -void R_LoadEntities( lump_t *l, world_t &worldData ) { +void R_LoadEntities(lump_t *l, world_t &worldData) { const char *p, *token; char keyname[MAX_TOKEN_CHARS]; char value[MAX_TOKEN_CHARS]; - world_t *w; + world_t *w; float ambient = 1; COM_BeginParseSession(); @@ -1235,78 +1167,79 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { w->lightGridSize[2] = 128; VectorSet(tr.sunAmbient, 1, 1, 1); - tr.distanceCull = 12000;//DEFAULT_DISTANCE_CULL; + tr.distanceCull = 12000; // DEFAULT_DISTANCE_CULL; p = (char *)(fileBase + l->fileofs); - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); if (!*token || *token != '{') { COM_EndParseSession(); return; } // only parse the world spawn - while ( 1 ) { + while (1) { // parse key - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(keyname, token, sizeof(keyname)); // parse value - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(value, token, sizeof(value)); // check for remapping of shaders for vertex lighting -/* s = "vertexremapshader"; - if (!Q_strncmp(keyname, s, strlen(s)) ) { - s = strchr(value, ';'); - if (!s) { - ri.Printf( S_COLOR_YELLOW "WARNING: no semi colon in vertexshaderremap '%s'\n", value ); - break; - } - *s++ = 0; - if (r_vertexLight->integer) { - R_RemapShader(value, s, "0"); - } - continue; - } - // check for remapping of shaders - s = "remapshader"; - if (!Q_strncmp(keyname, s, strlen(s)) ) { - s = strchr(value, ';'); - if (!s) { - ri.Printf( S_COLOR_YELLOW "WARNING: no semi colon in shaderremap '%s'\n", value ); - break; - } - *s++ = 0; - R_RemapShader(value, s, "0"); - continue; - } -*/ if (!Q_stricmp(keyname, "distanceCull")) { - sscanf(value, "%f", &tr.distanceCull ); + /* s = "vertexremapshader"; + if (!Q_strncmp(keyname, s, strlen(s)) ) { + s = strchr(value, ';'); + if (!s) { + ri.Printf( S_COLOR_YELLOW "WARNING: no semi colon in vertexshaderremap '%s'\n", value ); + break; + } + *s++ = 0; + if (r_vertexLight->integer) { + R_RemapShader(value, s, "0"); + } + continue; + } + // check for remapping of shaders + s = "remapshader"; + if (!Q_strncmp(keyname, s, strlen(s)) ) { + s = strchr(value, ';'); + if (!s) { + ri.Printf( S_COLOR_YELLOW "WARNING: no semi colon in shaderremap '%s'\n", value ); + break; + } + *s++ = 0; + R_RemapShader(value, s, "0"); + continue; + } + */ + if (!Q_stricmp(keyname, "distanceCull")) { + sscanf(value, "%f", &tr.distanceCull); continue; } - //check for linear fog -rww + // check for linear fog -rww if (!Q_stricmp(keyname, "linFogStart")) { - sscanf(value, "%f", &tr.rangedFog ); + sscanf(value, "%f", &tr.rangedFog); tr.rangedFog = -tr.rangedFog; continue; } // check for a different grid size if (!Q_stricmp(keyname, "gridsize")) { - sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] ); + sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2]); continue; } - // find the optional world ambient for arioche + // find the optional world ambient for arioche if (!Q_stricmp(keyname, "_color")) { - sscanf(value, "%f %f %f", &tr.sunAmbient[0], &tr.sunAmbient[1], &tr.sunAmbient[2] ); + sscanf(value, "%f %f %f", &tr.sunAmbient[0], &tr.sunAmbient[1], &tr.sunAmbient[2]); continue; } if (!Q_stricmp(keyname, "ambient")) { @@ -1314,13 +1247,12 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { continue; } } - //both default to 1 so no harm if not present. - VectorScale( tr.sunAmbient, ambient, tr.sunAmbient); + // both default to 1 so no harm if not present. + VectorScale(tr.sunAmbient, ambient, tr.sunAmbient); COM_EndParseSession(); } - /* ================= RE_LoadWorldMap @@ -1328,26 +1260,25 @@ RE_LoadWorldMap Called directly from cgame ================= */ -void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) { - dheader_t *header; - byte *buffer = NULL; - qboolean loadedSubBSP = qfalse; +void RE_LoadWorldMap_Actual(const char *name, world_t &worldData, int index) { + dheader_t *header; + byte *buffer = NULL; + qboolean loadedSubBSP = qfalse; - if ( tr.worldMapLoaded && !index ) { - Com_Error( ERR_DROP, "ERROR: attempted to redundantly load world map\n" ); + if (tr.worldMapLoaded && !index) { + Com_Error(ERR_DROP, "ERROR: attempted to redundantly load world map\n"); } // set default sun direction to be used if it isn't // overridden by a shader - if (!index) - { + if (!index) { skyboxportal = 0; tr.sunDirection[0] = 0.45f; tr.sunDirection[1] = 0.3f; tr.sunDirection[2] = 0.9f; - VectorNormalize( tr.sunDirection ); + VectorNormalize(tr.sunDirection); tr.worldMapLoaded = qtrue; @@ -1358,22 +1289,18 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) { // check for cached disk file from the server first... // - if (ri.gpvCachedMapDiskImage()) - { - if (!strcmp(name, ri.gsCachedMapDiskImage())) - { + if (ri.gpvCachedMapDiskImage()) { + if (!strcmp(name, ri.gsCachedMapDiskImage())) { // we should always get here, if inside the first IF... // buffer = (byte *)ri.gpvCachedMapDiskImage(); - } - else - { + } else { // this should never happen (ie renderer loading a different map than the server), but just in case... // - // assert(0); - // R_Free(gpvCachedMapDiskImage); - // gpvCachedMapDiskImage = NULL; - //rww - this is a valid possibility now because of sub-bsp loading.\ + // assert(0); + // R_Free(gpvCachedMapDiskImage); + // gpvCachedMapDiskImage = NULL; + // rww - this is a valid possibility now because of sub-bsp loading.\ //it's alright, just keep the current cache loadedSubBSP = qtrue; } @@ -1381,65 +1308,60 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) { tr.worldDir[0] = '\0'; - if (buffer == NULL) - { + if (buffer == NULL) { // still needs loading... // - ri.FS_ReadFile( name, (void **)&buffer ); - if ( !buffer ) { - Com_Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name); + ri.FS_ReadFile(name, (void **)&buffer); + if (!buffer) { + Com_Error(ERR_DROP, "RE_LoadWorldMap: %s not found", name); } } - memset( &worldData, 0, sizeof( worldData ) ); - Q_strncpyz( worldData.name, name, sizeof( worldData.name ) ); - Q_strncpyz( tr.worldDir, name, sizeof( tr.worldDir ) ); - Q_strncpyz( worldData.baseName, COM_SkipPath( worldData.name ), sizeof( worldData.name ) ); + memset(&worldData, 0, sizeof(worldData)); + Q_strncpyz(worldData.name, name, sizeof(worldData.name)); + Q_strncpyz(tr.worldDir, name, sizeof(tr.worldDir)); + Q_strncpyz(worldData.baseName, COM_SkipPath(worldData.name), sizeof(worldData.name)); - COM_StripExtension( worldData.baseName, worldData.baseName, sizeof( worldData.baseName ) ); - COM_StripExtension( tr.worldDir, tr.worldDir, sizeof( tr.worldDir ) ); + COM_StripExtension(worldData.baseName, worldData.baseName, sizeof(worldData.baseName)); + COM_StripExtension(tr.worldDir, tr.worldDir, sizeof(tr.worldDir)); c_gridVerts = 0; header = (dheader_t *)buffer; fileBase = (byte *)header; - header->version = LittleLong (header->version); + header->version = LittleLong(header->version); - if ( header->version != BSP_VERSION ) - { - Com_Error (ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)", name, header->version, BSP_VERSION); + if (header->version != BSP_VERSION) { + Com_Error(ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)", name, header->version, BSP_VERSION); } // swap all the lumps - for (size_t i=0 ; ilumps[LUMP_SHADERS], worldData ); - R_LoadLightmaps( &header->lumps[LUMP_LIGHTMAPS], name, worldData ); - R_LoadPlanes (&header->lumps[LUMP_PLANES], worldData); - R_LoadFogs( &header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES], worldData, index ); - R_LoadSurfaces( &header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES], worldData, index ); - R_LoadMarksurfaces (&header->lumps[LUMP_LEAFSURFACES], worldData); - R_LoadNodesAndLeafs (&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS], worldData); - R_LoadSubmodels (&header->lumps[LUMP_MODELS], worldData, index); - R_LoadVisibility( &header->lumps[LUMP_VISIBILITY], worldData ); - - if (!index) - { - R_LoadEntities( &header->lumps[LUMP_ENTITIES], worldData ); - R_LoadLightGrid( &header->lumps[LUMP_LIGHTGRID], worldData ); - R_LoadLightGridArray( &header->lumps[LUMP_LIGHTARRAY], worldData ); + R_LoadShaders(&header->lumps[LUMP_SHADERS], worldData); + R_LoadLightmaps(&header->lumps[LUMP_LIGHTMAPS], name, worldData); + R_LoadPlanes(&header->lumps[LUMP_PLANES], worldData); + R_LoadFogs(&header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES], worldData, index); + R_LoadSurfaces(&header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES], worldData, index); + R_LoadMarksurfaces(&header->lumps[LUMP_LEAFSURFACES], worldData); + R_LoadNodesAndLeafs(&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS], worldData); + R_LoadSubmodels(&header->lumps[LUMP_MODELS], worldData, index); + R_LoadVisibility(&header->lumps[LUMP_VISIBILITY], worldData); + + if (!index) { + R_LoadEntities(&header->lumps[LUMP_ENTITIES], worldData); + R_LoadLightGrid(&header->lumps[LUMP_LIGHTGRID], worldData); + R_LoadLightGridArray(&header->lumps[LUMP_LIGHTARRAY], worldData); // only set tr.world now that we know the entire level has loaded properly tr.world = &worldData; } - - if (ri.gpvCachedMapDiskImage() && !loadedSubBSP) - { + if (ri.gpvCachedMapDiskImage() && !loadedSubBSP) { // For the moment, I'm going to keep this disk image around in case we need it to respawn. // No problem for memory, since it'll only be a NZ ptr if we're not low on physical memory // ( ie we've got > 96MB). @@ -1448,21 +1370,17 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) { // // R_Free( gpvCachedMapDiskImage ); // gpvCachedMapDiskImage = NULL; - } - else - { - ri.FS_FreeFile( buffer ); + } else { + ri.FS_FreeFile(buffer); } } - // new wrapper used for convenience to tell z_malloc()-fail recovery code whether it's safe to dump the cached-bsp or not. // -void RE_LoadWorldMap( const char *name ) -{ - *(ri.gbUsingCachedMapDataRightNow()) = qtrue; // !!!!!!!!!!!! +void RE_LoadWorldMap(const char *name) { + *(ri.gbUsingCachedMapDataRightNow()) = qtrue; // !!!!!!!!!!!! - RE_LoadWorldMap_Actual( name, s_worldData, 0 ); + RE_LoadWorldMap_Actual(name, s_worldData, 0); - *(ri.gbUsingCachedMapDataRightNow()) = qfalse; // !!!!!!!!!!!! + *(ri.gbUsingCachedMapDataRightNow()) = qfalse; // !!!!!!!!!!!! } diff --git a/code/rd-vanilla/tr_cmds.cpp b/code/rd-vanilla/tr_cmds.cpp index 04ad9bdb4e..4280005bb7 100644 --- a/code/rd-vanilla/tr_cmds.cpp +++ b/code/rd-vanilla/tr_cmds.cpp @@ -26,62 +26,51 @@ along with this program; if not, see . #include "tr_local.h" - /* ===================== R_PerformanceCounters ===================== */ -void R_PerformanceCounters( void ) { - if ( !r_speeds->integer ) { +void R_PerformanceCounters(void) { + if (!r_speeds->integer) { // clear the counters even if we aren't printing - memset( &tr.pc, 0, sizeof( tr.pc ) ); - memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + memset(&tr.pc, 0, sizeof(tr.pc)); + memset(&backEnd.pc, 0, sizeof(backEnd.pc)); return; } if (r_speeds->integer == 1) { - const float texSize = R_SumOfUsedImages( qfalse )/(8*1048576.0f)*(r_texturebits->integer?r_texturebits->integer:glConfig.colorBits); - ri.Printf (PRINT_ALL, "%i/%i shdrs/srfs %i leafs %i vrts %i/%i tris %.2fMB tex %.2f dc\n", - backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, - backEnd.pc.c_indexes/3, backEnd.pc.c_totalIndexes/3, - texSize, backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight) ); + const float texSize = R_SumOfUsedImages(qfalse) / (8 * 1048576.0f) * (r_texturebits->integer ? r_texturebits->integer : glConfig.colorBits); + ri.Printf(PRINT_ALL, "%i/%i shdrs/srfs %i leafs %i vrts %i/%i tris %.2fMB tex %.2f dc\n", backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, + backEnd.pc.c_vertexes, backEnd.pc.c_indexes / 3, backEnd.pc.c_totalIndexes / 3, texSize, + backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight)); } else if (r_speeds->integer == 2) { - ri.Printf (PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out, - tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out ); - ri.Printf (PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out, - tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out ); + ri.Printf(PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, + tr.pc.c_sphere_cull_patch_out, tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out); + ri.Printf(PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, + tr.pc.c_sphere_cull_md3_out, tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out); } else if (r_speeds->integer == 3) { - ri.Printf (PRINT_ALL, "viewcluster: %i\n", tr.viewCluster ); + ri.Printf(PRINT_ALL, "viewcluster: %i\n", tr.viewCluster); } else if (r_speeds->integer == 4) { - if ( backEnd.pc.c_dlightVertexes ) { - ri.Printf (PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", - tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, - backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 ); + if (backEnd.pc.c_dlightVertexes) { + ri.Printf(PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, + backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3); } - } - else if (r_speeds->integer == 5 ) - { - ri.Printf( PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar ); - } - else if (r_speeds->integer == 6 ) - { - ri.Printf( PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", - backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders ); - } - else if (r_speeds->integer == 7) { + } else if (r_speeds->integer == 5) { + ri.Printf(PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar); + } else if (r_speeds->integer == 6) { + ri.Printf(PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders); + } else if (r_speeds->integer == 7) { const float texSize = R_SumOfUsedImages(qtrue) / (1048576.0f); - const float backBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.colorBits / (8.0f * 1024*1024); - const float depthBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.depthBits / (8.0f * 1024*1024); - const float stencilBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.stencilBits / (8.0f * 1024*1024); - ri.Printf (PRINT_ALL, "Tex MB %.2f + buffers %.2f MB = Total %.2fMB\n", - texSize, backBuff*2+depthBuff+stencilBuff, texSize+backBuff*2+depthBuff+stencilBuff); + const float backBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.colorBits / (8.0f * 1024 * 1024); + const float depthBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.depthBits / (8.0f * 1024 * 1024); + const float stencilBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.stencilBits / (8.0f * 1024 * 1024); + ri.Printf(PRINT_ALL, "Tex MB %.2f + buffers %.2f MB = Total %.2fMB\n", texSize, backBuff * 2 + depthBuff + stencilBuff, + texSize + backBuff * 2 + depthBuff + stencilBuff); } - memset( &tr.pc, 0, sizeof( tr.pc ) ); - memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + memset(&tr.pc, 0, sizeof(tr.pc)); + memset(&backEnd.pc, 0, sizeof(backEnd.pc)); } /* @@ -89,8 +78,8 @@ void R_PerformanceCounters( void ) { R_IssueRenderCommands ==================== */ -void R_IssueRenderCommands( qboolean runPerformanceCounters ) { - renderCommandList_t *cmdList; +void R_IssueRenderCommands(qboolean runPerformanceCounters) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; @@ -103,18 +92,17 @@ void R_IssueRenderCommands( qboolean runPerformanceCounters ) { // at this point, the back end thread is idle, so it is ok // to look at it's performance counters - if ( runPerformanceCounters ) { + if (runPerformanceCounters) { R_PerformanceCounters(); } // actually start the commands going - if ( !r_skipBackEnd->integer ) { + if (!r_skipBackEnd->integer) { // let it start on the new batch - RB_ExecuteRenderCommands( cmdList->cmds ); + RB_ExecuteRenderCommands(cmdList->cmds); } } - /* ==================== R_IssuePendingRenderCommands @@ -122,11 +110,11 @@ R_IssuePendingRenderCommands Issue any pending commands and wait for them to complete. ==================== */ -void R_IssuePendingRenderCommands( void ) { - if ( !tr.registered ) { +void R_IssuePendingRenderCommands(void) { + if (!tr.registered) { return; } - R_IssueRenderCommands( qfalse ); + R_IssueRenderCommands(qfalse); } /* @@ -136,16 +124,16 @@ R_GetCommandBufferReserved make sure there is enough command space ============ */ -static void *R_GetCommandBufferReserved( int bytes, int reservedBytes ) { - renderCommandList_t *cmdList; +static void *R_GetCommandBufferReserved(int bytes, int reservedBytes) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; bytes = PAD(bytes, sizeof(void *)); // always leave room for the end of list command - if ( cmdList->used + bytes + sizeof( int ) + reservedBytes > MAX_RENDER_COMMANDS ) { - if ( bytes > MAX_RENDER_COMMANDS - (int)sizeof( int ) ) { - ri.Error( ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes ); + if (cmdList->used + bytes + sizeof(int) + reservedBytes > MAX_RENDER_COMMANDS) { + if (bytes > MAX_RENDER_COMMANDS - (int)sizeof(int)) { + ri.Error(ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes); } // if we run out of room, just start dropping commands return NULL; @@ -163,10 +151,7 @@ R_GetCommandBuffer make sure there is enough command space ============ */ -static void *R_GetCommandBuffer( int bytes ) { - return R_GetCommandBufferReserved( bytes, PAD( sizeof( swapBuffersCommand_t ), sizeof(void *) ) ); -} - +static void *R_GetCommandBuffer(int bytes) { return R_GetCommandBufferReserved(bytes, PAD(sizeof(swapBuffersCommand_t), sizeof(void *))); } /* ============= @@ -174,11 +159,11 @@ R_AddDrawSurfCmd ============= */ -void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { - drawSurfsCommand_t *cmd; +void R_AddDrawSurfCmd(drawSurf_t *drawSurfs, int numDrawSurfs) { + drawSurfsCommand_t *cmd; - cmd = (drawSurfsCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawSurfsCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_DRAW_SURFS; @@ -190,7 +175,6 @@ void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { cmd->viewParms = tr.viewParms; } - /* ============= RE_SetColor @@ -198,46 +182,43 @@ RE_SetColor Passing NULL will set the color to white ============= */ -void RE_SetColor( const float *rgba ) { - setColorCommand_t *cmd; +void RE_SetColor(const float *rgba) { + setColorCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (setColorCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (setColorCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_SET_COLOR; - if ( !rgba ) { + if (!rgba) { rgba = colorWhite; } cmd->color[0] = rgba[0]; cmd->color[1] = rgba[1]; cmd->color[2] = rgba[2]; cmd->color[3] = rgba[3]; - } - /* ============= RE_StretchPic ============= */ -void RE_StretchPic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2, qhandle_t hShader ) { - stretchPicCommand_t *cmd; +void RE_StretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + stretchPicCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (stretchPicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (stretchPicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_STRETCH_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -253,19 +234,18 @@ void RE_StretchPic ( float x, float y, float w, float h, RE_RotatePic ============= */ -void RE_RotatePic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -282,20 +262,19 @@ void RE_RotatePic ( float x, float y, float w, float h, RE_RotatePic2 ============= */ -void RE_RotatePic2 ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC2; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -307,31 +286,29 @@ void RE_RotatePic2 ( float x, float y, float w, float h, cmd->a = a; } -void RE_LAGoggles( void ) -{ - tr.refdef.rdflags |= (RDF_doLAGoggles|RDF_doFullbright); +void RE_LAGoggles(void) { + tr.refdef.rdflags |= (RDF_doLAGoggles | RDF_doFullbright); tr.refdef.doLAGoggles = qtrue; - fog_t *fog = &tr.world->fogs[tr.world->numfogs]; + fog_t *fog = &tr.world->fogs[tr.world->numfogs]; fog->parms.color[0] = 0.75f; fog->parms.color[1] = 0.42f + Q_flrand(0.0f, 1.0f) * 0.025f; fog->parms.color[2] = 0.07f; fog->parms.depthForOpaque = 10000; fog->colorInt = ColorBytes4(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); - fog->tcScale = 2.0f / ( fog->parms.depthForOpaque * (1.0f + cos( tr.refdef.floatTime) * 0.1f)); + fog->tcScale = 2.0f / (fog->parms.depthForOpaque * (1.0f + cos(tr.refdef.floatTime) * 0.1f)); } -void RE_RenderWorldEffects(void) -{ - setModeCommand_t *cmd; +void RE_RenderWorldEffects(void) { + setModeCommand_t *cmd; if (!tr.registered) { return; } - cmd = (setModeCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (setModeCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_WORLD_EFFECTS; @@ -342,16 +319,15 @@ void RE_RenderWorldEffects(void) RE_Scissor ============= */ -void RE_Scissor ( float x, float y, float w, float h) -{ - scissorCommand_t *cmd; +void RE_Scissor(float x, float y, float w, float h) { + scissorCommand_t *cmd; if (!tr.registered) { return; } - cmd = (scissorCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (scissorCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_SCISSOR; @@ -369,10 +345,10 @@ If running in stereo, RE_BeginFrame will be called twice for each RE_EndFrame ==================== */ -void RE_BeginFrame( stereoFrame_t stereoFrame ) { - drawBufferCommand_t *cmd = NULL; +void RE_BeginFrame(stereoFrame_t stereoFrame) { + drawBufferCommand_t *cmd = NULL; - if ( !tr.registered ) { + if (!tr.registered) { return; } glState.finishCalled = qfalse; @@ -383,37 +359,29 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // do overdraw measurement // - if ( r_measureOverdraw->integer ) - { - if ( glConfig.stencilBits < 4 ) - { - ri.Printf( PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + if (r_measureOverdraw->integer) { + if (glConfig.stencilBits < 4) { + ri.Printf(PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else if ( r_shadows->integer == 2 ) - { - ri.Printf( PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + } else if (r_shadows->integer == 2) { + ri.Printf(PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n"); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else - { + } else { R_IssuePendingRenderCommands(); - qglEnable( GL_STENCIL_TEST ); - qglStencilMask( ~0U ); - qglClearStencil( 0U ); - qglStencilFunc( GL_ALWAYS, 0U, ~0U ); - qglStencilOp( GL_KEEP, GL_INCR, GL_INCR ); + qglEnable(GL_STENCIL_TEST); + qglStencilMask(~0U); + qglClearStencil(0U); + qglStencilFunc(GL_ALWAYS, 0U, ~0U); + qglStencilOp(GL_KEEP, GL_INCR, GL_INCR); } r_measureOverdraw->modified = qfalse; - } - else - { + } else { // this is only reached if it was on and is now off - if ( r_measureOverdraw->modified ) { + if (r_measureOverdraw->modified) { R_IssuePendingRenderCommands(); - qglDisable( GL_STENCIL_TEST ); + qglDisable(GL_STENCIL_TEST); r_measureOverdraw->modified = qfalse; } } @@ -421,9 +389,9 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // texturemode stuff // - if ( r_textureMode->modified || r_ext_texture_filter_anisotropic->modified) { + if (r_textureMode->modified || r_ext_texture_filter_anisotropic->modified) { R_IssuePendingRenderCommands(); - GL_TextureMode( r_textureMode->string ); + GL_TextureMode(r_textureMode->string); r_textureMode->modified = qfalse; r_ext_texture_filter_anisotropic->modified = qfalse; } @@ -431,54 +399,51 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // gamma stuff // - if ( r_gamma->modified ) { + if (r_gamma->modified) { r_gamma->modified = qfalse; R_IssuePendingRenderCommands(); R_SetColorMappings(); } - // check for errors - if ( !r_ignoreGLErrors->integer ) { - int err; + // check for errors + if (!r_ignoreGLErrors->integer) { + int err; R_IssuePendingRenderCommands(); - if ( ( err = qglGetError() ) != GL_NO_ERROR ) { - Com_Error( ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err ); - } - } + if ((err = qglGetError()) != GL_NO_ERROR) { + Com_Error(ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err); + } + } // // draw buffer stuff // - cmd = (drawBufferCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_DRAW_BUFFER; - if ( glConfig.stereoEnabled ) { - if ( stereoFrame == STEREO_LEFT ) { + if (glConfig.stereoEnabled) { + if (stereoFrame == STEREO_LEFT) { cmd->buffer = (int)GL_BACK_LEFT; - } else if ( stereoFrame == STEREO_RIGHT ) { + } else if (stereoFrame == STEREO_RIGHT) { cmd->buffer = (int)GL_BACK_RIGHT; } else { - Com_Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + Com_Error(ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame); } } else { - if ( stereoFrame != STEREO_CENTER ) { - Com_Error( ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame ); - } -// if ( !Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) ) { -// cmd->buffer = (int)GL_FRONT; -// } else - { - cmd->buffer = (int)GL_BACK; + if (stereoFrame != STEREO_CENTER) { + Com_Error(ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame); } + // if ( !Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) ) { + // cmd->buffer = (int)GL_FRONT; + // } else + { cmd->buffer = (int)GL_BACK; } } } - /* ============= RE_EndFrame @@ -486,33 +451,32 @@ RE_EndFrame Returns the number of msec spent in the back end ============= */ -void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { - swapBuffersCommand_t *cmd; +void RE_EndFrame(int *frontEndMsec, int *backEndMsec) { + swapBuffersCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (swapBuffersCommand_t *) R_GetCommandBufferReserved( sizeof( *cmd ), 0 ); - if ( !cmd ) { + cmd = (swapBuffersCommand_t *)R_GetCommandBufferReserved(sizeof(*cmd), 0); + if (!cmd) { return; } cmd->commandId = RC_SWAP_BUFFERS; - R_IssueRenderCommands( qtrue ); + R_IssueRenderCommands(qtrue); R_InitNextFrame(); - if ( frontEndMsec ) { + if (frontEndMsec) { *frontEndMsec = tr.frontEndMsec; } tr.frontEndMsec = 0; - if ( backEndMsec ) { + if (backEndMsec) { *backEndMsec = backEnd.pc.msec; } backEnd.pc.msec = 0; - for(int i=0;ixyz[0] = 0.5 * (a->xyz[0] + b->xyz[0]); out->xyz[1] = 0.5 * (a->xyz[1] + b->xyz[1]); out->xyz[2] = 0.5 * (a->xyz[2] + b->xyz[2]); @@ -61,8 +60,7 @@ static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) { out->normal[1] = 0.5 * (a->normal[1] + b->normal[1]); out->normal[2] = 0.5 * (a->normal[2] + b->normal[2]); - for(k=0;klightmap[k][0] = 0.5 * (a->lightmap[k][0] + b->lightmap[k][0]); out->lightmap[k][1] = 0.5 * (a->lightmap[k][1] + b->lightmap[k][1]); @@ -78,14 +76,14 @@ static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) { Transpose ============ */ -static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - drawVert_t temp; - - if ( width > height ) { - for ( i = 0 ; i < height ; i++ ) { - for ( j = i + 1 ; j < width ; j++ ) { - if ( j < height ) { +static void Transpose(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + drawVert_t temp; + + if (width > height) { + for (i = 0; i < height; i++) { + for (j = i + 1; j < width; j++) { + if (j < height) { // swap the value temp = ctrl[j][i]; ctrl[j][i] = ctrl[i][j]; @@ -97,9 +95,9 @@ static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX } } } else { - for ( i = 0 ; i < width ; i++ ) { - for ( j = i + 1 ; j < height ; j++ ) { - if ( j < width ) { + for (i = 0; i < width; i++) { + for (j = i + 1; j < height; j++) { + if (j < width) { // swap the value temp = ctrl[i][j]; ctrl[i][j] = ctrl[j][i]; @@ -111,7 +109,6 @@ static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX } } } - } /* @@ -121,125 +118,121 @@ MakeMeshNormals Handles all the complicated wrapping and degenerate cases ================= */ -static void MakeMeshNormals( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j, k, dist; - vec3_t normal; - vec3_t sum; - int count; - vec3_t base; - vec3_t delta; - int x, y; - drawVert_t *dv; - vec3_t around[8], temp; - qboolean good[8]; - qboolean wrapWidth, wrapHeight; - float len; -static int neighbors[8][2] = { - {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} - }; +static void MakeMeshNormals(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j, k, dist; + vec3_t normal; + vec3_t sum; + int count; + vec3_t base; + vec3_t delta; + int x, y; + drawVert_t *dv; + vec3_t around[8], temp; + qboolean good[8]; + qboolean wrapWidth, wrapHeight; + float len; + static int neighbors[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; wrapWidth = qfalse; - for ( i = 0 ; i < height ; i++ ) { - VectorSubtract( ctrl[i][0].xyz, ctrl[i][width-1].xyz, delta ); - len = VectorLength( delta ); - if ( len > 1.0 ) { + for (i = 0; i < height; i++) { + VectorSubtract(ctrl[i][0].xyz, ctrl[i][width - 1].xyz, delta); + len = VectorLength(delta); + if (len > 1.0) { break; } } - if ( i == height ) { + if (i == height) { wrapWidth = qtrue; } wrapHeight = qfalse; - for ( i = 0 ; i < width ; i++ ) { - VectorSubtract( ctrl[0][i].xyz, ctrl[height-1][i].xyz, delta ); - len = VectorLength( delta ); - if ( len > 1.0 ) { + for (i = 0; i < width; i++) { + VectorSubtract(ctrl[0][i].xyz, ctrl[height - 1][i].xyz, delta); + len = VectorLength(delta); + if (len > 1.0) { break; } } - if ( i == width) { + if (i == width) { wrapHeight = qtrue; } - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { count = 0; dv = &ctrl[j][i]; - VectorCopy( dv->xyz, base ); - for ( k = 0 ; k < 8 ; k++ ) { - VectorClear( around[k] ); + VectorCopy(dv->xyz, base); + for (k = 0; k < 8; k++) { + VectorClear(around[k]); good[k] = qfalse; - for ( dist = 1 ; dist <= 3 ; dist++ ) { + for (dist = 1; dist <= 3; dist++) { x = i + neighbors[k][0] * dist; y = j + neighbors[k][1] * dist; - if ( wrapWidth ) { - if ( x < 0 ) { + if (wrapWidth) { + if (x < 0) { x = width - 1 + x; - } else if ( x >= width ) { + } else if (x >= width) { x = 1 + x - width; } } - if ( wrapHeight ) { - if ( y < 0 ) { + if (wrapHeight) { + if (y < 0) { y = height - 1 + y; - } else if ( y >= height ) { + } else if (y >= height) { y = 1 + y - height; } } - if ( x < 0 || x >= width || y < 0 || y >= height ) { - break; // edge of patch + if (x < 0 || x >= width || y < 0 || y >= height) { + break; // edge of patch } - VectorSubtract( ctrl[y][x].xyz, base, temp ); - if ( VectorNormalize2( temp, temp ) == 0 ) { - continue; // degenerate edge, get more dist + VectorSubtract(ctrl[y][x].xyz, base, temp); + if (VectorNormalize2(temp, temp) == 0) { + continue; // degenerate edge, get more dist } else { good[k] = qtrue; - VectorCopy( temp, around[k] ); - break; // good edge + VectorCopy(temp, around[k]); + break; // good edge } } } - VectorClear( sum ); - for ( k = 0 ; k < 8 ; k++ ) { - if ( !good[k] || !good[(k+1)&7] ) { - continue; // didn't get two points + VectorClear(sum); + for (k = 0; k < 8; k++) { + if (!good[k] || !good[(k + 1) & 7]) { + continue; // didn't get two points } - CrossProduct( around[(k+1)&7], around[k], normal ); - if ( VectorNormalize2( normal, normal ) == 0 ) { + CrossProduct(around[(k + 1) & 7], around[k], normal); + if (VectorNormalize2(normal, normal) == 0) { continue; } - VectorAdd( normal, sum, sum ); + VectorAdd(normal, sum, sum); count++; } - if ( count == 0 ) { -//printf("bad normal\n"); + if (count == 0) { + // printf("bad normal\n"); count = 1; } - VectorNormalize2( sum, dv->normal ); + VectorNormalize2(sum, dv->normal); } } } - /* ============ InvertCtrl ============ */ -static void InvertCtrl( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - drawVert_t temp; +static void InvertCtrl(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + drawVert_t temp; - for ( i = 0 ; i < height ; i++ ) { - for ( j = 0 ; j < width/2 ; j++ ) { + for (i = 0; i < height; i++) { + for (j = 0; j < width / 2; j++) { temp = ctrl[i][j]; - ctrl[i][j] = ctrl[i][width-1-j]; - ctrl[i][width-1-j] = temp; + ctrl[i][j] = ctrl[i][width - 1 - j]; + ctrl[i][width - 1 - j] = temp; } } } @@ -249,20 +242,19 @@ static void InvertCtrl( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MA InvertErrorTable ================= */ -static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int height ) { - int i; - float copy[2][MAX_GRID_SIZE]; +static void InvertErrorTable(float errorTable[2][MAX_GRID_SIZE], int width, int height) { + int i; + float copy[2][MAX_GRID_SIZE]; - memcpy( copy, errorTable, sizeof( copy ) ); + memcpy(copy, errorTable, sizeof(copy)); - for ( i = 0 ; i < width ; i++ ) { - errorTable[1][i] = copy[0][i]; //[width-1-i]; + for (i = 0; i < width; i++) { + errorTable[1][i] = copy[0][i]; //[width-1-i]; } - for ( i = 0 ; i < height ; i++ ) { - errorTable[0][i] = copy[1][height-1-i]; + for (i = 0; i < height; i++) { + errorTable[0][i] = copy[1][height - 1 - i]; } - } /* @@ -270,25 +262,23 @@ static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int PutPointsOnCurve ================== */ -static void PutPointsOnCurve( drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], - int width, int height ) { - int i, j; - drawVert_t prev, next; - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 1 ; j < height ; j += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j+1][i], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j-1][i], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); +static void PutPointsOnCurve(drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], int width, int height) { + int i, j; + drawVert_t prev, next; + + for (i = 0; i < width; i++) { + for (j = 1; j < height; j += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j + 1][i], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j - 1][i], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } - - for ( j = 0 ; j < height ; j++ ) { - for ( i = 1 ; i < width ; i += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j][i+1], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j][i-1], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); + for (j = 0; j < height; j++) { + for (i = 1; i < width; i += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j][i + 1], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j][i - 1], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } } @@ -299,93 +289,91 @@ R_SubdividePatchToGrid ================= */ -srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, - drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) { - int i, j, k, l; - drawVert_t prev, next, mid; - float len, maxLen; - int dir; - int t; - drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; - float errorTable[2][MAX_GRID_SIZE]; - srfGridMesh_t *grid; - drawVert_t *vert; - vec3_t tmpVec; - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - ctrl[j][i] = points[j*width+i]; +srfGridMesh_t *R_SubdividePatchToGrid(int width, int height, drawVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]) { + int i, j, k, l; + drawVert_t prev, next, mid; + float len, maxLen; + int dir; + int t; + drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + srfGridMesh_t *grid; + drawVert_t *vert; + vec3_t tmpVec; + + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + ctrl[j][i] = points[j * width + i]; } } - for ( dir = 0 ; dir < 2 ; dir++ ) { + for (dir = 0; dir < 2; dir++) { - for ( j = 0 ; j < MAX_GRID_SIZE ; j++ ) { + for (j = 0; j < MAX_GRID_SIZE; j++) { errorTable[dir][j] = 0; } // horizontal subdivisions - for ( j = 0 ; j + 2 < width ; j += 2 ) { + for (j = 0; j + 2 < width; j += 2) { // check subdivided midpoints against control points maxLen = 0; - for ( i = 0 ; i < height ; i++ ) { - vec3_t midxyz; - vec3_t dir; - vec3_t projected; - float d; + for (i = 0; i < height; i++) { + vec3_t midxyz; + vec3_t dir; + vec3_t projected; + float d; // calculate the point on the curve - for ( l = 0 ; l < 3 ; l++ ) { - midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j+1].xyz[l] * 2 - + ctrl[i][j+2].xyz[l] ) * 0.25; + for (l = 0; l < 3; l++) { + midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j + 1].xyz[l] * 2 + ctrl[i][j + 2].xyz[l]) * 0.25; } // see how far off the line it is // using dist-from-line will not account for internal // texture warping, but it gives a lot less polygons than // dist-from-midpoint - VectorSubtract( midxyz, ctrl[i][j].xyz, midxyz ); - VectorSubtract( ctrl[i][j+2].xyz, ctrl[i][j].xyz, dir ); - VectorNormalize( dir ); + VectorSubtract(midxyz, ctrl[i][j].xyz, midxyz); + VectorSubtract(ctrl[i][j + 2].xyz, ctrl[i][j].xyz, dir); + VectorNormalize(dir); - d = DotProduct( midxyz, dir ); - VectorScale( dir, d, projected ); - VectorSubtract( midxyz, projected, midxyz); - len = VectorLength( midxyz ); + d = DotProduct(midxyz, dir); + VectorScale(dir, d, projected); + VectorSubtract(midxyz, projected, midxyz); + len = VectorLength(midxyz); - if ( len > maxLen ) { + if (len > maxLen) { maxLen = len; } } // if all the points are on the lines, remove the entire columns - if ( maxLen < 0.1 ) { - errorTable[dir][j+1] = 999; + if (maxLen < 0.1) { + errorTable[dir][j + 1] = 999; continue; } // see if we want to insert subdivided columns - if ( width + 2 > MAX_GRID_SIZE ) { - errorTable[dir][j+1] = 1.0/maxLen; - continue; // can't subdivide any more + if (width + 2 > MAX_GRID_SIZE) { + errorTable[dir][j + 1] = 1.0 / maxLen; + continue; // can't subdivide any more } - if ( maxLen <= r_subdivisions->value ) { - errorTable[dir][j+1] = 1.0/maxLen; - continue; // didn't need subdivision + if (maxLen <= r_subdivisions->value) { + errorTable[dir][j + 1] = 1.0 / maxLen; + continue; // didn't need subdivision } - errorTable[dir][j+2] = 1.0/maxLen; + errorTable[dir][j + 2] = 1.0 / maxLen; // insert two columns and replace the peak width += 2; - for ( i = 0 ; i < height ; i++ ) { - LerpDrawVert( &ctrl[i][j], &ctrl[i][j+1], &prev ); - LerpDrawVert( &ctrl[i][j+1], &ctrl[i][j+2], &next ); - LerpDrawVert( &prev, &next, &mid ); + for (i = 0; i < height; i++) { + LerpDrawVert(&ctrl[i][j], &ctrl[i][j + 1], &prev); + LerpDrawVert(&ctrl[i][j + 1], &ctrl[i][j + 2], &next); + LerpDrawVert(&prev, &next, &mid); - for ( k = width - 1 ; k > j + 3 ; k-- ) { - ctrl[i][k] = ctrl[i][k-2]; + for (k = width - 1; k > j + 3; k--) { + ctrl[i][k] = ctrl[i][k - 2]; } ctrl[i][j + 1] = prev; ctrl[i][j + 2] = mid; @@ -394,42 +382,40 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, // back up and recheck this set again, it may need more subdivision j -= 2; - } - Transpose( width, height, ctrl ); + Transpose(width, height, ctrl); t = width; width = height; height = t; } - // put all the aproximating points on the curve - PutPointsOnCurve( ctrl, width, height ); + PutPointsOnCurve(ctrl, width, height); // cull out any rows or columns that are colinear - for ( i = 1 ; i < width-1 ; i++ ) { - if ( errorTable[0][i] != 999 ) { + for (i = 1; i < width - 1; i++) { + if (errorTable[0][i] != 999) { continue; } - for ( j = i+1 ; j < width ; j++ ) { - for ( k = 0 ; k < height ; k++ ) { - ctrl[k][j-1] = ctrl[k][j]; + for (j = i + 1; j < width; j++) { + for (k = 0; k < height; k++) { + ctrl[k][j - 1] = ctrl[k][j]; } - errorTable[0][j-1] = errorTable[0][j]; + errorTable[0][j - 1] = errorTable[0][j]; } width--; } - for ( i = 1 ; i < height-1 ; i++ ) { - if ( errorTable[1][i] != 999 ) { + for (i = 1; i < height - 1; i++) { + if (errorTable[1][i] != 999) { continue; } - for ( j = i+1 ; j < height ; j++ ) { - for ( k = 0 ; k < width ; k++ ) { - ctrl[j-1][k] = ctrl[j][k]; + for (j = i + 1; j < height; j++) { + for (k = 0; k < width; k++) { + ctrl[j - 1][k] = ctrl[j][k]; } - errorTable[1][j-1] = errorTable[1][j]; + errorTable[1][j - 1] = errorTable[1][j]; } height--; } @@ -438,47 +424,47 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, // flip for longest tristrips as an optimization // the results should be visually identical with or // without this step - if ( height > width ) { - Transpose( width, height, ctrl ); - InvertErrorTable( errorTable, width, height ); + if (height > width) { + Transpose(width, height, ctrl); + InvertErrorTable(errorTable, width, height); t = width; width = height; height = t; - InvertCtrl( width, height, ctrl ); + InvertCtrl(width, height, ctrl); } #endif // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); // copy the results out to a grid - grid = (struct srfGridMesh_s *) R_Hunk_Alloc( (width * height - 1) * sizeof( drawVert_t ) + sizeof( *grid ), qtrue ); + grid = (struct srfGridMesh_s *)R_Hunk_Alloc((width * height - 1) * sizeof(drawVert_t) + sizeof(*grid), qtrue); - grid->widthLodError = (float *) R_Hunk_Alloc( width * 4, qfalse ); - memcpy( grid->widthLodError, errorTable[0], width * 4 ); + grid->widthLodError = (float *)R_Hunk_Alloc(width * 4, qfalse); + memcpy(grid->widthLodError, errorTable[0], width * 4); - grid->heightLodError = (float *) R_Hunk_Alloc( height * 4, qfalse ); - memcpy( grid->heightLodError, errorTable[1], height * 4 ); + grid->heightLodError = (float *)R_Hunk_Alloc(height * 4, qfalse); + memcpy(grid->heightLodError, errorTable[1], height * 4); grid->width = width; grid->height = height; grid->surfaceType = SF_GRID; - ClearBounds( grid->meshBounds[0], grid->meshBounds[1] ); - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - vert = &grid->verts[j*width+i]; + ClearBounds(grid->meshBounds[0], grid->meshBounds[1]); + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + vert = &grid->verts[j * width + i]; *vert = ctrl[j][i]; - AddPointToBounds( vert->xyz, grid->meshBounds[0], grid->meshBounds[1] ); + AddPointToBounds(vert->xyz, grid->meshBounds[0], grid->meshBounds[1]); } } // compute local origin and bounds - VectorAdd( grid->meshBounds[0], grid->meshBounds[1], grid->localOrigin ); - VectorScale( grid->localOrigin, 0.5f, grid->localOrigin ); - VectorSubtract( grid->meshBounds[0], grid->localOrigin, tmpVec ); - grid->meshRadius = VectorLength( tmpVec ); + VectorAdd(grid->meshBounds[0], grid->meshBounds[1], grid->localOrigin); + VectorScale(grid->localOrigin, 0.5f, grid->localOrigin); + VectorSubtract(grid->meshBounds[0], grid->localOrigin, tmpVec); + grid->meshRadius = VectorLength(tmpVec); - VectorCopy( grid->localOrigin, grid->lodOrigin ); + VectorCopy(grid->localOrigin, grid->lodOrigin); grid->lodRadius = grid->meshRadius; return grid; diff --git a/code/rd-vanilla/tr_draw.cpp b/code/rd-vanilla/tr_draw.cpp index 9543a81e0d..181d062e9d 100644 --- a/code/rd-vanilla/tr_draw.cpp +++ b/code/rd-vanilla/tr_draw.cpp @@ -37,15 +37,14 @@ Used for cinematics. */ // param 'bDirty' should be true 99% of the time -void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int iClient, qboolean bDirty ) -{ - if ( !tr.registered ) { +void RE_StretchRaw(int x, int y, int w, int h, int cols, int rows, const byte *data, int iClient, qboolean bDirty) { + if (!tr.registered) { return; } R_IssuePendingRenderCommands(); - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } @@ -54,151 +53,137 @@ void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte * #ifdef TIMEBIND int start, end; - start = end = 0; // only to stop compiler whining, don't need to be initialised + start = end = 0; // only to stop compiler whining, don't need to be initialised #endif // make sure rows and cols are powers of 2 - if ( (cols&(cols-1)) || (rows&(rows-1)) ) - { - Com_Error (ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); + if ((cols & (cols - 1)) || (rows & (rows - 1))) { + Com_Error(ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); } - GL_Bind( tr.scratchImage[iClient] ); + GL_Bind(tr.scratchImage[iClient]); // if the scratchImage isn't in the format we want, specify it as a new texture... // - if ( cols != tr.scratchImage[iClient]->width || rows != tr.scratchImage[iClient]->height ) - { + if (cols != tr.scratchImage[iClient]->width || rows != tr.scratchImage[iClient]->height) { tr.scratchImage[iClient]->width = cols; tr.scratchImage[iClient]->height = rows; #ifdef TIMEBIND - if ( r_ignore->integer ) - { + if (r_ignore->integer) { start = ri.Milliseconds(); } #endif - qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); #ifdef TIMEBIND - if ( r_ignore->integer ) - { + if (r_ignore->integer) { end = ri.Milliseconds(); - ri.Printf( PRINT_ALL, "qglTexImage2D %i, %i: %i msec\n", cols, rows, end - start ); + ri.Printf(PRINT_ALL, "qglTexImage2D %i, %i: %i msec\n", cols, rows, end - start); } #endif - } - else - { - if (bDirty) // FIXME: some TA addition or other, not sure why, yet. Should probably be true 99% of the time? + } else { + if (bDirty) // FIXME: some TA addition or other, not sure why, yet. Should probably be true 99% of the time? { // otherwise, just subimage upload it so that drivers can tell we are going to be changing // it and don't try and do a texture compression - #ifdef TIMEBIND - if ( r_ignore->integer ) - { +#ifdef TIMEBIND + if (r_ignore->integer) { start = ri.Milliseconds(); } - #endif +#endif - qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data); - #ifdef TIMEBIND - if ( r_ignore->integer ) - { +#ifdef TIMEBIND + if (r_ignore->integer) { end = ri.Milliseconds(); - ri.Printf( PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start ); + ri.Printf(PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start); } - #endif +#endif } } - - extern void RB_SetGL2D (void); - if (!backEnd.projection2D) - { + extern void RB_SetGL2D(void); + if (!backEnd.projection2D) { RB_SetGL2D(); } - qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight ); - - qglBegin (GL_QUADS); - qglTexCoord2f ( 0.5f / cols, 0.5f / rows ); - qglVertex2f (x, y); - qglTexCoord2f ( ( cols - 0.5f ) / cols , 0.5f / rows ); - qglVertex2f (x+w, y); - qglTexCoord2f ( ( cols - 0.5f ) / cols, ( rows - 0.5f ) / rows ); - qglVertex2f (x+w, y+h); - qglTexCoord2f ( 0.5f / cols, ( rows - 0.5f ) / rows ); - qglVertex2f (x, y+h); - qglEnd (); + qglColor3f(tr.identityLight, tr.identityLight, tr.identityLight); + + qglBegin(GL_QUADS); + qglTexCoord2f(0.5f / cols, 0.5f / rows); + qglVertex2f(x, y); + qglTexCoord2f((cols - 0.5f) / cols, 0.5f / rows); + qglVertex2f(x + w, y); + qglTexCoord2f((cols - 0.5f) / cols, (rows - 0.5f) / rows); + qglVertex2f(x + w, y + h); + qglTexCoord2f(0.5f / cols, (rows - 0.5f) / rows); + qglVertex2f(x, y + h); + qglEnd(); } +void RE_UploadCinematic(int cols, int rows, const byte *data, int client, qboolean dirty) { - -void RE_UploadCinematic (int cols, int rows, const byte *data, int client, qboolean dirty) { - - GL_Bind( tr.scratchImage[client] ); + GL_Bind(tr.scratchImage[client]); // if the scratchImage isn't in the format we want, specify it as a new texture - if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) { + if (cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height) { tr.scratchImage[client]->width = cols; tr.scratchImage[client]->height = rows; - qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); } else { if (dirty) { // otherwise, just subimage upload it so that drivers can tell we are going to be changing // it and don't try and do a texture compression - qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data); } } } extern byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen); -void RE_GetScreenShot(byte *buffer, int w, int h) -{ - byte *source; - byte *src, *dst; +void RE_GetScreenShot(byte *buffer, int w, int h) { + byte *source; + byte *src, *dst; size_t offset = 0, memcount; int padlen; - int x, y; - int r, g, b; - float xScale, yScale; - int xx, yy; - + int x, y; + int r, g, b; + float xScale, yScale; + int xx, yy; source = RB_ReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, &offset, &padlen); memcount = (glConfig.vidWidth * 3 + padlen) * glConfig.vidHeight; // gamma correct - if(glConfig.deviceSupportsGamma) + if (glConfig.deviceSupportsGamma) R_GammaCorrect(source + offset, memcount); // resample from source - xScale = glConfig.vidWidth / (4.0*w); - yScale = glConfig.vidHeight / (3.0*h); - for ( y = 0 ; y < h ; y++ ) { - for ( x = 0 ; x < w ; x++ ) { + xScale = glConfig.vidWidth / (4.0 * w); + yScale = glConfig.vidHeight / (3.0 * h); + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) { r = g = b = 0; - for ( yy = 0 ; yy < 3 ; yy++ ) { - for ( xx = 0 ; xx < 4 ; xx++ ) { - src = source + offset + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) ); + for (yy = 0; yy < 3; yy++) { + for (xx = 0; xx < 4; xx++) { + src = source + offset + 3 * (glConfig.vidWidth * (int)((y * 3 + yy) * yScale) + (int)((x * 4 + xx) * xScale)); r += src[0]; g += src[1]; b += src[2]; } } - dst = buffer + 3 * ( y * w + x ); + dst = buffer + 3 * (y * w + x); dst[0] = r / 12; dst[1] = g / 12; dst[2] = b / 12; @@ -211,47 +196,37 @@ void RE_GetScreenShot(byte *buffer, int w, int h) // this is just a chunk of code from RE_TempRawImage_ReadFromFile() below, subroutinised so I can call it // from the screen dissolve code as well... // -static byte *RE_ReSample(byte *pbLoadedPic, int iLoadedWidth, int iLoadedHeight, - byte *pbReSampleBuffer, int *piWidth, int *piHeight - ) -{ +static byte *RE_ReSample(byte *pbLoadedPic, int iLoadedWidth, int iLoadedHeight, byte *pbReSampleBuffer, int *piWidth, int *piHeight) { byte *pbReturn = NULL; // if not resampling, just return some values and return... // - if ( pbReSampleBuffer == NULL || (iLoadedWidth == *piWidth && iLoadedHeight == *piHeight) ) - { + if (pbReSampleBuffer == NULL || (iLoadedWidth == *piWidth && iLoadedHeight == *piHeight)) { // if not resampling, we're done, just return the loaded size... // *piWidth = iLoadedWidth; - *piHeight= iLoadedHeight; + *piHeight = iLoadedHeight; pbReturn = pbLoadedPic; - } - else - { + } else { // resample from pbLoadedPic to pbReSampledBuffer... // - float fXStep = (float)iLoadedWidth / (float)*piWidth; - float fYStep = (float)iLoadedHeight/ (float)*piHeight; - int iTotPixelsPerDownSample = (int)ceil(fXStep) * (int)ceil(fYStep); + float fXStep = (float)iLoadedWidth / (float)*piWidth; + float fYStep = (float)iLoadedHeight / (float)*piHeight; + int iTotPixelsPerDownSample = (int)ceil(fXStep) * (int)ceil(fYStep); - int r,g,b; + int r, g, b; - byte *pbDst = pbReSampleBuffer; + byte *pbDst = pbReSampleBuffer; - for ( int y=0; y<*piHeight; y++ ) - { - for ( int x=0; x<*piWidth; x++ ) - { - r=g=b=0; + for (int y = 0; y < *piHeight; y++) { + for (int x = 0; x < *piWidth; x++) { + r = g = b = 0; - for ( float yy = (float)y*fYStep; yy < (float)(y+1)*fYStep ; yy+=1 ) - { - for ( float xx = (float)x*fXStep; xx < (float)(x+1)*fXStep ; xx+=1 ) - { - byte *pbSrc = pbLoadedPic + 4 * ( ((int)yy * iLoadedWidth) + (int)xx ); + for (float yy = (float)y * fYStep; yy < (float)(y + 1) * fYStep; yy += 1) { + for (float xx = (float)x * fXStep; xx < (float)(x + 1) * fXStep; xx += 1) { + byte *pbSrc = pbLoadedPic + 4 * (((int)yy * iLoadedWidth) + (int)xx); - assert(pbSrc < pbLoadedPic + (iLoadedWidth * iLoadedHeight * 4) ); + assert(pbSrc < pbLoadedPic + (iLoadedWidth * iLoadedHeight * 4)); r += pbSrc[0]; g += pbSrc[1]; @@ -277,7 +252,6 @@ static byte *RE_ReSample(byte *pbLoadedPic, int iLoadedWidth, int iLoadedHeigh return pbReturn; } - // this is so the server (or anyone else) can get access to raw pixels if they really need to, // currently it's only used by the server so that savegames can embed a graphic in the auto-save files // (which can't do a screenshot since they're saved out before the level is drawn). @@ -300,36 +274,29 @@ static byte *RE_ReSample(byte *pbLoadedPic, int iLoadedWidth, int iLoadedHeigh // // (not brilliantly fast, but it's only used for weird stuff anyway) // -byte* pbLoadedPic = NULL; +byte *pbLoadedPic = NULL; -byte* RE_TempRawImage_ReadFromFile(const char *psLocalFilename, int *piWidth, int *piHeight, byte *pbReSampleBuffer, qboolean qbVertFlip) -{ - RE_TempRawImage_CleanUp(); // jic +byte *RE_TempRawImage_ReadFromFile(const char *psLocalFilename, int *piWidth, int *piHeight, byte *pbReSampleBuffer, qboolean qbVertFlip) { + RE_TempRawImage_CleanUp(); // jic byte *pbReturn = NULL; - if (psLocalFilename && piWidth && piHeight) - { - int iLoadedWidth, iLoadedHeight; + if (psLocalFilename && piWidth && piHeight) { + int iLoadedWidth, iLoadedHeight; - R_LoadImage( psLocalFilename, &pbLoadedPic, &iLoadedWidth, &iLoadedHeight); - if ( pbLoadedPic ) - { - pbReturn = RE_ReSample( pbLoadedPic, iLoadedWidth, iLoadedHeight, - pbReSampleBuffer, piWidth, piHeight); + R_LoadImage(psLocalFilename, &pbLoadedPic, &iLoadedWidth, &iLoadedHeight); + if (pbLoadedPic) { + pbReturn = RE_ReSample(pbLoadedPic, iLoadedWidth, iLoadedHeight, pbReSampleBuffer, piWidth, piHeight); } } - if (pbReturn && qbVertFlip) - { - unsigned int *pSrcLine = (unsigned int *) pbReturn; - unsigned int *pDstLine = (unsigned int *) pbReturn + (*piHeight * *piWidth ); // *4 done by compiler (longs) - pDstLine-= *piWidth; // point at start of last line, not first after buffer + if (pbReturn && qbVertFlip) { + unsigned int *pSrcLine = (unsigned int *)pbReturn; + unsigned int *pDstLine = (unsigned int *)pbReturn + (*piHeight * *piWidth); // *4 done by compiler (longs) + pDstLine -= *piWidth; // point at start of last line, not first after buffer - for (int iLineCount=0; iLineCount<*piHeight/2; iLineCount++) - { - for (int x=0; x<*piWidth; x++) - { + for (int iLineCount = 0; iLineCount < *piHeight / 2; iLineCount++) { + for (int x = 0; x < *piWidth; x++) { unsigned int l = pSrcLine[x]; pSrcLine[x] = pDstLine[x]; pDstLine[x] = l; @@ -342,141 +309,124 @@ byte* RE_TempRawImage_ReadFromFile(const char *psLocalFilename, int *piWidth, in return pbReturn; } -void RE_TempRawImage_CleanUp(void) -{ - if ( pbLoadedPic ) - { - R_Free( pbLoadedPic ); +void RE_TempRawImage_CleanUp(void) { + if (pbLoadedPic) { + R_Free(pbLoadedPic); pbLoadedPic = NULL; } } - - -typedef enum -{ +typedef enum { eDISSOLVE_RT_TO_LT = 0, eDISSOLVE_LT_TO_RT, eDISSOLVE_TP_TO_BT, eDISSOLVE_BT_TO_TP, - eDISSOLVE_CIRCULAR_OUT, // new image comes out from centre + eDISSOLVE_CIRCULAR_OUT, // new image comes out from centre // - eDISSOLVE_RAND_LIMIT, // label only, not valid to select + eDISSOLVE_RAND_LIMIT, // label only, not valid to select // // any others... // - eDISSOLVE_CIRCULAR_IN, // new image comes in from edges + eDISSOLVE_CIRCULAR_IN, // new image comes in from edges // eDISSOLVE_NUMBEROF } Dissolve_e; -typedef struct -{ - int iWidth; - int iHeight; - int iUploadWidth; - int iUploadHeight; - int iScratchPadNumber; - image_t *pImage; // old image screen - image_t *pDissolve; // fuzzy thing - image_t *pBlack; // small black image for clearing - int iStartTime; // 0 = not processing - Dissolve_e eDissolveType; - qboolean bTouchNeeded; +typedef struct { + int iWidth; + int iHeight; + int iUploadWidth; + int iUploadHeight; + int iScratchPadNumber; + image_t *pImage; // old image screen + image_t *pDissolve; // fuzzy thing + image_t *pBlack; // small black image for clearing + int iStartTime; // 0 = not processing + Dissolve_e eDissolveType; + qboolean bTouchNeeded; } Dissolve_t; -static int PowerOf2(int iArg) -{ - if ( (iArg & (iArg-1)) != 0) - { - int iShift=0; - while (iArg) - { - iArg>>=1; +static int PowerOf2(int iArg) { + if ((iArg & (iArg - 1)) != 0) { + int iShift = 0; + while (iArg) { + iArg >>= 1; iShift++; } - iArg = 1<width, fV0 / (float)pImage->height ); - qglTexCoord2f( 0,0 ); - qglVertex2f( fX0, fY0 ); + // qglTexCoord2f( fU0 / (float)pImage->width, fV0 / (float)pImage->height ); + qglTexCoord2f(0, 0); + qglVertex2f(fX0, fY0); // TR... // -// qglTexCoord2f( fU1 / (float)pImage->width, fV1 / (float)pImage->height ); - qglTexCoord2f( 1,0 ); - qglVertex2f( fX1, fY1 ); + // qglTexCoord2f( fU1 / (float)pImage->width, fV1 / (float)pImage->height ); + qglTexCoord2f(1, 0); + qglVertex2f(fX1, fY1); // BR... // -// qglTexCoord2f( fU2 / (float)pImage->width, fV2 / (float)pImage->height ); - qglTexCoord2f( 1,1 ); - qglVertex2f( fX2, fY2); + // qglTexCoord2f( fU2 / (float)pImage->width, fV2 / (float)pImage->height ); + qglTexCoord2f(1, 1); + qglVertex2f(fX2, fY2); // BL... // -// qglTexCoord2f( fU3 / (float)pImage->width, fV3 / (float)pImage->height ); - qglTexCoord2f( 0,1 ); - qglVertex2f( fX3, fY3); + // qglTexCoord2f( fU3 / (float)pImage->width, fV3 / (float)pImage->height ); + qglTexCoord2f(0, 1); + qglVertex2f(fX3, fY3); } - qglEnd (); + qglEnd(); } -static void RE_KillDissolve(void) -{ +static void RE_KillDissolve(void) { Dissolve.iStartTime = 0; - if (Dissolve.pImage) - { - R_Images_DeleteImage( Dissolve.pImage ); - Dissolve.pImage = NULL; + if (Dissolve.pImage) { + R_Images_DeleteImage(Dissolve.pImage); + Dissolve.pImage = NULL; } } // Draw the dissolve pic to the screen, over the top of what's already been rendered. // // return = qtrue while still processing, for those interested... // -#define iSAFETY_SPRITE_OVERLAP 2 // #pixels to overlap blit region by, in case some drivers leave onscreen seams -qboolean RE_ProcessDissolve(void) -{ - if (Dissolve.iStartTime) - { - if (Dissolve.bTouchNeeded) - { +#define iSAFETY_SPRITE_OVERLAP 2 // #pixels to overlap blit region by, in case some drivers leave onscreen seams +qboolean RE_ProcessDissolve(void) { + if (Dissolve.iStartTime) { + if (Dissolve.bTouchNeeded) { // Stuff to avoid music stutter... // // The problem is, that if I call RE_InitDissolve() then call RestartMusic, then by the time the music @@ -491,245 +441,226 @@ qboolean RE_ProcessDissolve(void) Dissolve.iStartTime = ri.Milliseconds(); } - int iDissolvePercentage = ((ri.Milliseconds() - Dissolve.iStartTime)*100) / (1000.0f * fDISSOLVE_SECONDS); + int iDissolvePercentage = ((ri.Milliseconds() - Dissolve.iStartTime) * 100) / (1000.0f * fDISSOLVE_SECONDS); -// ri.Printf(PRINT_ALL,"iDissolvePercentage %d\n",iDissolvePercentage); + // ri.Printf(PRINT_ALL,"iDissolvePercentage %d\n",iDissolvePercentage); - if (iDissolvePercentage <= 100) - { - extern void RB_SetGL2D (void); + if (iDissolvePercentage <= 100) { + extern void RB_SetGL2D(void); RB_SetGL2D(); -// GLdouble glD; -// qglGetDoublev(GL_DEPTH_CLEAR_VALUE,&glD); -// qglClearColor(0,0,0,1); + // GLdouble glD; + // qglGetDoublev(GL_DEPTH_CLEAR_VALUE,&glD); + // qglClearColor(0,0,0,1); qglClearDepth(1.0f); - qglClear( GL_DEPTH_BUFFER_BIT ); - + qglClear(GL_DEPTH_BUFFER_BIT); float fXScaleFactor = (float)SCREEN_WIDTH / (float)Dissolve.iWidth; - float fYScaleFactor = (float)SCREEN_HEIGHT/ (float)Dissolve.iHeight; - float x0,y0, x1,y1, x2,y2, x3,y3; + float fYScaleFactor = (float)SCREEN_HEIGHT / (float)Dissolve.iHeight; + float x0, y0, x1, y1, x2, y2, x3, y3; - switch (Dissolve.eDissolveType) - { - case eDISSOLVE_RT_TO_LT: - { - float fXboundary = (float) Dissolve.iWidth - (((float)(Dissolve.iWidth+Dissolve.pDissolve->width)*(float)iDissolvePercentage)/100.0f); - - // blit the fuzzy-dissolve sprite... - // - x0 = fXScaleFactor * fXboundary; - y0 = 0.0f; - x1 = fXScaleFactor * (fXboundary + Dissolve.pDissolve->width); - y1 = 0.0f; - x2 = x1; - y2 = fYScaleFactor * Dissolve.iHeight; - x3 = x0; - y3 = y2; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - - // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... - // (to the left of fXboundary) - // - x0 = 0.0f; - y0 = 0.0f; - x1 = fXScaleFactor * (fXboundary + iSAFETY_SPRITE_OVERLAP); - y1 = 0.0f; - x2 = x1; - y2 = fYScaleFactor * Dissolve.iHeight; - x3 = x0; - y3 = y2; - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); - } - break; + switch (Dissolve.eDissolveType) { + case eDISSOLVE_RT_TO_LT: { + float fXboundary = (float)Dissolve.iWidth - (((float)(Dissolve.iWidth + Dissolve.pDissolve->width) * (float)iDissolvePercentage) / 100.0f); - case eDISSOLVE_LT_TO_RT: - { - float fXboundary = (((float)(Dissolve.iWidth+(2*Dissolve.pDissolve->width))*(float)iDissolvePercentage)/100.0f) - Dissolve.pDissolve->width; - - // blit the fuzzy-dissolve sprite... - // - x0 = fXScaleFactor * (fXboundary + Dissolve.pDissolve->width); - y0 = 0.0f; - x1 = fXScaleFactor * fXboundary; - y1 = 0.0f; - x2 = x1; - y2 = fYScaleFactor * Dissolve.iHeight; - x3 = x0; - y3 = y2; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - - // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... - // (to the right of fXboundary) - // - x0 = fXScaleFactor * (( fXboundary + Dissolve.pDissolve->width) - iSAFETY_SPRITE_OVERLAP); - y0 = 0.0f; - x1 = fXScaleFactor * Dissolve.iWidth; - y0 = 0.0f; - x2 = x1; - y2 = fYScaleFactor * Dissolve.iHeight; - x3 = x0; - y3 = y2; - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); - } - break; + // blit the fuzzy-dissolve sprite... + // + x0 = fXScaleFactor * fXboundary; + y0 = 0.0f; + x1 = fXScaleFactor * (fXboundary + Dissolve.pDissolve->width); + y1 = 0.0f; + x2 = x1; + y2 = fYScaleFactor * Dissolve.iHeight; + x3 = x0; + y3 = y2; - case eDISSOLVE_TP_TO_BT: - { - float fYboundary = (((float)(Dissolve.iHeight+(2*Dissolve.pDissolve->width))*(float)iDissolvePercentage)/100.0f) - Dissolve.pDissolve->width; - - // blit the fuzzy-dissolve sprite... - // - x0 = 0.0f; - y0 = fYScaleFactor * (fYboundary + Dissolve.pDissolve->width); - x1 = x0; - y1 = fYScaleFactor * fYboundary; - x2 = fXScaleFactor * Dissolve.iWidth; - y2 = y1; - x3 = x2; - y3 = y0; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - - // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... - // (underneath fYboundary) - // - x0 = 0.0f; - y0 = fYScaleFactor * ( (fYboundary + Dissolve.pDissolve->width) - iSAFETY_SPRITE_OVERLAP); - x1 = fXScaleFactor * Dissolve.iWidth; - y1 = y0; - x2 = x1; - y2 = fYScaleFactor * Dissolve.iHeight; - x3 = x0; - y3 = y2; - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); - } - break; + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - case eDISSOLVE_BT_TO_TP: - { - float fYboundary = Dissolve.iHeight - (((float)(Dissolve.iHeight+Dissolve.pDissolve->width)*(float)iDissolvePercentage)/100.0f); - - // blit the fuzzy-dissolve sprite... - // - x0 = 0.0f; - y0 = fYScaleFactor * fYboundary; - x1 = x0; - y1 = fYScaleFactor * (fYboundary + Dissolve.pDissolve->width); - x2 = fXScaleFactor * Dissolve.iWidth; - y2 = y1; - x3 = x2; - y3 = y0; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - - // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... - // (above fYboundary) - // - x0 = 0.0f; - y0 = 0.0f; - x1 = fXScaleFactor * Dissolve.iWidth; - y1 = y0; - x2 = x1; - y2 = fYScaleFactor * (fYboundary + iSAFETY_SPRITE_OVERLAP); - x3 = x0; - y3 = y2; - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); - } - break; + // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... + // (to the left of fXboundary) + // + x0 = 0.0f; + y0 = 0.0f; + x1 = fXScaleFactor * (fXboundary + iSAFETY_SPRITE_OVERLAP); + y1 = 0.0f; + x2 = x1; + y2 = fYScaleFactor * Dissolve.iHeight; + x3 = x0; + y3 = y2; + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + } break; - case eDISSOLVE_CIRCULAR_IN: - { - float fDiagZoom = ( ((float)Dissolve.iWidth*0.8) * (100-iDissolvePercentage))/100.0f; - - // - // blit circular graphic... - // - x0 = fXScaleFactor * ((Dissolve.iWidth/2) - fDiagZoom); - y0 = fYScaleFactor * ((Dissolve.iHeight/2)- fDiagZoom); - x1 = fXScaleFactor * ((Dissolve.iWidth/2) + fDiagZoom); - y1 = y0; - x2 = x1; - y2 = fYScaleFactor * ((Dissolve.iHeight/2)+ fDiagZoom); - x3 = x0; - y3 = y2; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - } - break; + case eDISSOLVE_LT_TO_RT: { + float fXboundary = + (((float)(Dissolve.iWidth + (2 * Dissolve.pDissolve->width)) * (float)iDissolvePercentage) / 100.0f) - Dissolve.pDissolve->width; - case eDISSOLVE_CIRCULAR_OUT: - { - float fDiagZoom = ( ((float)Dissolve.iWidth*0.8) * iDissolvePercentage)/100.0f; - - // - // blit circular graphic... - // - x0 = fXScaleFactor * ((Dissolve.iWidth/2) - fDiagZoom); - y0 = fYScaleFactor * ((Dissolve.iHeight/2)- fDiagZoom); - x1 = fXScaleFactor * ((Dissolve.iWidth/2) + fDiagZoom); - y1 = y0; - x2 = x1; - y2 = fYScaleFactor * ((Dissolve.iHeight/2)+ fDiagZoom); - x3 = x0; - y3 = y2; - - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); - // now blit the 4 black squares around it to mask off the rest of the screen... - // - // LHS, top to bottom... - // - RE_Blit(0,0, // x0,y0 - x0+iSAFETY_SPRITE_OVERLAP,0, // x1,y1 - x0+iSAFETY_SPRITE_OVERLAP,(fYScaleFactor * Dissolve.iHeight),// x2,y2 - 0,(fYScaleFactor * Dissolve.iHeight), // x3,y3, - Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE - ); - - // RHS top to bottom... - // - RE_Blit(x1-iSAFETY_SPRITE_OVERLAP,0, // x0,y0 - (fXScaleFactor * Dissolve.iWidth),0, // x1,y1 - (fXScaleFactor * Dissolve.iWidth),(fYScaleFactor * Dissolve.iHeight),// x2,y2 - x1-iSAFETY_SPRITE_OVERLAP,(fYScaleFactor * Dissolve.iHeight), // x3,y3, - Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE - ); - - // top... - // - RE_Blit(x0-iSAFETY_SPRITE_OVERLAP,0, // x0,y0 - x1+iSAFETY_SPRITE_OVERLAP,0, // x1,y1 - x1+iSAFETY_SPRITE_OVERLAP,y0 + iSAFETY_SPRITE_OVERLAP, // x2,y2 - x0-iSAFETY_SPRITE_OVERLAP,y0 + iSAFETY_SPRITE_OVERLAP, // x3,y3 - Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE - ); - - // bottom... - // - RE_Blit(x0-iSAFETY_SPRITE_OVERLAP,y3-iSAFETY_SPRITE_OVERLAP, // x0,y0 - x1+iSAFETY_SPRITE_OVERLAP,y2-iSAFETY_SPRITE_OVERLAP, // x1,y1 - x1+iSAFETY_SPRITE_OVERLAP,(fYScaleFactor * Dissolve.iHeight), // x2,y2 - x0-iSAFETY_SPRITE_OVERLAP,(fYScaleFactor * Dissolve.iHeight), // x3,y3 - Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE - ); - } - break; + // blit the fuzzy-dissolve sprite... + // + x0 = fXScaleFactor * (fXboundary + Dissolve.pDissolve->width); + y0 = 0.0f; + x1 = fXScaleFactor * fXboundary; + y1 = 0.0f; + x2 = x1; + y2 = fYScaleFactor * Dissolve.iHeight; + x3 = x0; + y3 = y2; - default: - { - assert(0); - iDissolvePercentage = 101; // force a dissolve-kill - break; - } + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); + + // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... + // (to the right of fXboundary) + // + x0 = fXScaleFactor * ((fXboundary + Dissolve.pDissolve->width) - iSAFETY_SPRITE_OVERLAP); + y0 = 0.0f; + x1 = fXScaleFactor * Dissolve.iWidth; + y0 = 0.0f; + x2 = x1; + y2 = fYScaleFactor * Dissolve.iHeight; + x3 = x0; + y3 = y2; + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + } break; + + case eDISSOLVE_TP_TO_BT: { + float fYboundary = + (((float)(Dissolve.iHeight + (2 * Dissolve.pDissolve->width)) * (float)iDissolvePercentage) / 100.0f) - Dissolve.pDissolve->width; + + // blit the fuzzy-dissolve sprite... + // + x0 = 0.0f; + y0 = fYScaleFactor * (fYboundary + Dissolve.pDissolve->width); + x1 = x0; + y1 = fYScaleFactor * fYboundary; + x2 = fXScaleFactor * Dissolve.iWidth; + y2 = y1; + x3 = x2; + y3 = y0; + + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); + + // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... + // (underneath fYboundary) + // + x0 = 0.0f; + y0 = fYScaleFactor * ((fYboundary + Dissolve.pDissolve->width) - iSAFETY_SPRITE_OVERLAP); + x1 = fXScaleFactor * Dissolve.iWidth; + y1 = y0; + x2 = x1; + y2 = fYScaleFactor * Dissolve.iHeight; + x3 = x0; + y3 = y2; + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + } break; + + case eDISSOLVE_BT_TO_TP: { + float fYboundary = Dissolve.iHeight - (((float)(Dissolve.iHeight + Dissolve.pDissolve->width) * (float)iDissolvePercentage) / 100.0f); + + // blit the fuzzy-dissolve sprite... + // + x0 = 0.0f; + y0 = fYScaleFactor * fYboundary; + x1 = x0; + y1 = fYScaleFactor * (fYboundary + Dissolve.pDissolve->width); + x2 = fXScaleFactor * Dissolve.iWidth; + y2 = y1; + x3 = x2; + y3 = y0; + + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); + + // blit a blank thing over the area the old screen is to be displayed on to enable screen-writing... + // (above fYboundary) + // + x0 = 0.0f; + y0 = 0.0f; + x1 = fXScaleFactor * Dissolve.iWidth; + y1 = y0; + x2 = x1; + y2 = fYScaleFactor * (fYboundary + iSAFETY_SPRITE_OVERLAP); + x3 = x0; + y3 = y2; + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + } break; + + case eDISSOLVE_CIRCULAR_IN: { + float fDiagZoom = (((float)Dissolve.iWidth * 0.8) * (100 - iDissolvePercentage)) / 100.0f; + + // + // blit circular graphic... + // + x0 = fXScaleFactor * ((Dissolve.iWidth / 2) - fDiagZoom); + y0 = fYScaleFactor * ((Dissolve.iHeight / 2) - fDiagZoom); + x1 = fXScaleFactor * ((Dissolve.iWidth / 2) + fDiagZoom); + y1 = y0; + x2 = x1; + y2 = fYScaleFactor * ((Dissolve.iHeight / 2) + fDiagZoom); + x3 = x0; + y3 = y2; + + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); + } break; + + case eDISSOLVE_CIRCULAR_OUT: { + float fDiagZoom = (((float)Dissolve.iWidth * 0.8) * iDissolvePercentage) / 100.0f; + + // + // blit circular graphic... + // + x0 = fXScaleFactor * ((Dissolve.iWidth / 2) - fDiagZoom); + y0 = fYScaleFactor * ((Dissolve.iHeight / 2) - fDiagZoom); + x1 = fXScaleFactor * ((Dissolve.iWidth / 2) + fDiagZoom); + y1 = y0; + x2 = x1; + y2 = fYScaleFactor * ((Dissolve.iHeight / 2) + fDiagZoom); + x3 = x0; + y3 = y2; + + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pDissolve, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE | GLS_ATEST_LT_80); + // now blit the 4 black squares around it to mask off the rest of the screen... + // + // LHS, top to bottom... + // + RE_Blit(0, 0, // x0,y0 + x0 + iSAFETY_SPRITE_OVERLAP, 0, // x1,y1 + x0 + iSAFETY_SPRITE_OVERLAP, (fYScaleFactor * Dissolve.iHeight), // x2,y2 + 0, (fYScaleFactor * Dissolve.iHeight), // x3,y3, + Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + + // RHS top to bottom... + // + RE_Blit(x1 - iSAFETY_SPRITE_OVERLAP, 0, // x0,y0 + (fXScaleFactor * Dissolve.iWidth), 0, // x1,y1 + (fXScaleFactor * Dissolve.iWidth), (fYScaleFactor * Dissolve.iHeight), // x2,y2 + x1 - iSAFETY_SPRITE_OVERLAP, (fYScaleFactor * Dissolve.iHeight), // x3,y3, + Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + + // top... + // + RE_Blit(x0 - iSAFETY_SPRITE_OVERLAP, 0, // x0,y0 + x1 + iSAFETY_SPRITE_OVERLAP, 0, // x1,y1 + x1 + iSAFETY_SPRITE_OVERLAP, y0 + iSAFETY_SPRITE_OVERLAP, // x2,y2 + x0 - iSAFETY_SPRITE_OVERLAP, y0 + iSAFETY_SPRITE_OVERLAP, // x3,y3 + Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + + // bottom... + // + RE_Blit(x0 - iSAFETY_SPRITE_OVERLAP, y3 - iSAFETY_SPRITE_OVERLAP, // x0,y0 + x1 + iSAFETY_SPRITE_OVERLAP, y2 - iSAFETY_SPRITE_OVERLAP, // x1,y1 + x1 + iSAFETY_SPRITE_OVERLAP, (fYScaleFactor * Dissolve.iHeight), // x2,y2 + x0 - iSAFETY_SPRITE_OVERLAP, (fYScaleFactor * Dissolve.iHeight), // x3,y3 + Dissolve.pBlack, GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE); + } break; + + default: { + assert(0); + iDissolvePercentage = 101; // force a dissolve-kill + break; + } } // re-check in case we hit the default case above... // - if (iDissolvePercentage <= 100) - { + if (iDissolvePercentage <= 100) { // still dissolving, so now (finally), blit old image over top... // x0 = 0.0f; @@ -741,12 +672,11 @@ qboolean RE_ProcessDissolve(void) x3 = x0; y3 = y2; - RE_Blit(x0,y0,x1,y1,x2,y2,x3,y3, Dissolve.pImage,GLS_DEPTHFUNC_EQUAL); + RE_Blit(x0, y0, x1, y1, x2, y2, x3, y3, Dissolve.pImage, GLS_DEPTHFUNC_EQUAL); } } - if (iDissolvePercentage > 100) - { + if (iDissolvePercentage > 100) { RE_KillDissolve(); } } @@ -756,36 +686,33 @@ qboolean RE_ProcessDissolve(void) // return = qtrue(success) else fail, for those interested... // -qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) -{ +qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) { R_IssuePendingRenderCommands(); -// ri.Printf( PRINT_ALL, "RE_InitDissolve()\n"); + // ri.Printf( PRINT_ALL, "RE_InitDissolve()\n"); qboolean bReturn = qfalse; - if (//Dissolve.iStartTime == 0 // no point in interruping an existing one - //&& - tr.registered == qtrue // ... stops it crashing during first cinematic before the menus... :-) - ) - { - RE_KillDissolve(); // kill any that are already running + if ( // Dissolve.iStartTime == 0 // no point in interruping an existing one + //&& + tr.registered == qtrue // ... stops it crashing during first cinematic before the menus... :-) + ) { + RE_KillDissolve(); // kill any that are already running - int iPow2VidWidth = PowerOf2( glConfig.vidWidth ); - int iPow2VidHeight = PowerOf2( glConfig.vidHeight); + int iPow2VidWidth = PowerOf2(glConfig.vidWidth); + int iPow2VidHeight = PowerOf2(glConfig.vidHeight); - int iBufferBytes = iPow2VidWidth * iPow2VidHeight * 4; - byte *pBuffer = (byte *) R_Malloc( iBufferBytes, TAG_TEMP_WORKSPACE, qfalse); - if (pBuffer) - { + int iBufferBytes = iPow2VidWidth * iPow2VidHeight * 4; + byte *pBuffer = (byte *)R_Malloc(iBufferBytes, TAG_TEMP_WORKSPACE, qfalse); + if (pBuffer) { // read current screen image... (GL_RGBA should work even on 3DFX in that the RGB parts will be valid at least) // - qglReadPixels (0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_RGBA, GL_UNSIGNED_BYTE, pBuffer ); + qglReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_RGBA, GL_UNSIGNED_BYTE, pBuffer); // // now expand the pic over the top of itself so that it has a stride value of {PowerOf2(glConfig.vidWidth)} // (for GL power-of-2 rules) // - byte *pbSrc = &pBuffer[ glConfig.vidWidth * glConfig.vidHeight * 4]; - byte *pbDst = &pBuffer[ iPow2VidWidth * glConfig.vidHeight * 4]; + byte *pbSrc = &pBuffer[glConfig.vidWidth * glConfig.vidHeight * 4]; + byte *pbDst = &pBuffer[iPow2VidWidth * glConfig.vidHeight * 4]; // // ( clear to end, since we've got pbDst nicely setup here) // @@ -794,15 +721,14 @@ qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) // // work out copy/stride vals... // - iClearBytes = ( iPow2VidWidth - glConfig.vidWidth ) * 4; - int iCopyBytes = glConfig.vidWidth * 4; + iClearBytes = (iPow2VidWidth - glConfig.vidWidth) * 4; + int iCopyBytes = glConfig.vidWidth * 4; // // do it... // - for (int y = 0; y < glConfig.vidHeight; y++) - { + for (int y = 0; y < glConfig.vidHeight; y++) { pbDst -= iClearBytes; - memset(pbDst,0,iClearBytes); + memset(pbDst, 0, iClearBytes); pbDst -= iCopyBytes; pbSrc -= iCopyBytes; memmove(pbDst, pbSrc, iCopyBytes); @@ -812,16 +738,15 @@ qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) // but of course the damn thing's upside down (thanks, GL), so invert it, but only within // the picture pixels, NOT the upload texture as a whole... // - byte *pbSwapLineBuffer = (byte *)R_Malloc( iCopyBytes, TAG_TEMP_WORKSPACE, qfalse); + byte *pbSwapLineBuffer = (byte *)R_Malloc(iCopyBytes, TAG_TEMP_WORKSPACE, qfalse); pbSrc = &pBuffer[0]; - pbDst = &pBuffer[(glConfig.vidHeight-1) * iPow2VidWidth * 4]; - for (int y = 0; y < glConfig.vidHeight/2; y++) - { + pbDst = &pBuffer[(glConfig.vidHeight - 1) * iPow2VidWidth * 4]; + for (int y = 0; y < glConfig.vidHeight / 2; y++) { memcpy(pbSwapLineBuffer, pbDst, iCopyBytes); memcpy(pbDst, pbSrc, iCopyBytes); memcpy(pbSrc, pbSwapLineBuffer, iCopyBytes); - pbDst -= iPow2VidWidth*4; - pbSrc += iPow2VidWidth*4; + pbDst -= iPow2VidWidth * 4; + pbSrc += iPow2VidWidth * 4; } R_Free(pbSwapLineBuffer); @@ -829,20 +754,19 @@ qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) // Now, in case of busted drivers, 3DFX cards, etc etc we stomp the alphas to 255... // byte *pPix = pBuffer; - for (int i=0; iinteger) - { + if (com_buildScript->integer) { // register any/all of the possible CASE statements below... // - Dissolve.pDissolve = R_FindImageFile( "gfx/2d/iris_mono", // const char *name - qfalse, // qboolean mipmap - qfalse, // qboolean allowPicmip - qfalse, // qboolean allowTC - GL_CLAMP // int glWrapClampMode - ); - Dissolve.pDissolve = R_FindImageFile( "textures/common/dissolve", // const char *name - qfalse, // qboolean mipmap - qfalse, // qboolean allowPicmip - qfalse, // qboolean allowTC - GL_REPEAT // int glWrapClampMode - ); + Dissolve.pDissolve = R_FindImageFile("gfx/2d/iris_mono", // const char *name + qfalse, // qboolean mipmap + qfalse, // qboolean allowPicmip + qfalse, // qboolean allowTC + GL_CLAMP // int glWrapClampMode + ); + Dissolve.pDissolve = R_FindImageFile("textures/common/dissolve", // const char *name + qfalse, // qboolean mipmap + qfalse, // qboolean allowPicmip + qfalse, // qboolean allowTC + GL_REPEAT // int glWrapClampMode + ); } - switch (Dissolve.eDissolveType) - { - case eDISSOLVE_CIRCULAR_IN: - { - Dissolve.pDissolve = R_FindImageFile( "gfx/2d/iris_mono_rev", // const char *name - qfalse, // qboolean mipmap - qfalse, // qboolean allowPicmip - qfalse, // qboolean allowTC - GL_CLAMP // int glWrapClampMode - ); - } - break; - - case eDISSOLVE_CIRCULAR_OUT: - { - Dissolve.pDissolve = R_FindImageFile( "gfx/2d/iris_mono", // const char *name - qfalse, // qboolean mipmap - qfalse, // qboolean allowPicmip - qfalse, // qboolean allowTC - GL_CLAMP // int glWrapClampMode - ); - } - break; - - default: - { - Dissolve.pDissolve = R_FindImageFile( "textures/common/dissolve", // const char *name - qfalse, // qboolean mipmap - qfalse, // qboolean allowPicmip - qfalse, // qboolean allowTC - GL_REPEAT // int glWrapClampMode - ); - } - break; + switch (Dissolve.eDissolveType) { + case eDISSOLVE_CIRCULAR_IN: { + Dissolve.pDissolve = R_FindImageFile("gfx/2d/iris_mono_rev", // const char *name + qfalse, // qboolean mipmap + qfalse, // qboolean allowPicmip + qfalse, // qboolean allowTC + GL_CLAMP // int glWrapClampMode + ); + } break; + + case eDISSOLVE_CIRCULAR_OUT: { + Dissolve.pDissolve = R_FindImageFile("gfx/2d/iris_mono", // const char *name + qfalse, // qboolean mipmap + qfalse, // qboolean allowPicmip + qfalse, // qboolean allowTC + GL_CLAMP // int glWrapClampMode + ); + } break; + + default: { + Dissolve.pDissolve = R_FindImageFile("textures/common/dissolve", // const char *name + qfalse, // qboolean mipmap + qfalse, // qboolean allowPicmip + qfalse, // qboolean allowTC + GL_REPEAT // int glWrapClampMode + ); + } break; } // all good?... // - if (Dissolve.pDissolve) // test if image was found, if not, don't do dissolves + if (Dissolve.pDissolve) // test if image was found, if not, don't do dissolves { - Dissolve.iStartTime = ri.Milliseconds(); // gets overwritten first time, but MUST be set to NZ + Dissolve.iStartTime = ri.Milliseconds(); // gets overwritten first time, but MUST be set to NZ Dissolve.bTouchNeeded = qtrue; bReturn = qtrue; - } - else - { + } else { RE_KillDissolve(); } } @@ -1021,4 +930,3 @@ qboolean RE_InitDissolve(qboolean bForceCircularExtroWipe) return bReturn; } - diff --git a/code/rd-vanilla/tr_ghoul2.cpp b/code/rd-vanilla/tr_ghoul2.cpp index b1f6d43a6b..80ae53606b 100644 --- a/code/rd-vanilla/tr_ghoul2.cpp +++ b/code/rd-vanilla/tr_ghoul2.cpp @@ -22,30 +22,30 @@ along with this program; if not, see . #include "../server/exe_headers.h" -#include "../client/client.h" //FIXME!! EVIL - just include the definitions needed +#include "../client/client.h" //FIXME!! EVIL - just include the definitions needed #include "../client/vmachine.h" #if !defined(TR_LOCAL_H) - #include "tr_local.h" +#include "tr_local.h" #endif #include "tr_common.h" #include "qcommon/matcomp.h" #if !defined(_QCOMMON_H_) - #include "../qcommon/qcommon.h" +#include "../qcommon/qcommon.h" #endif #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif #ifdef _G2_GORE #include "../ghoul2/ghoul2_gore.h" #endif -#define LL(x) x=LittleLong(x) -#define LS(x) x=LittleShort(x) -#define LF(x) x=LittleFloat(x) +#define LL(x) x = LittleLong(x) +#define LS(x) x = LittleShort(x) +#define LF(x) x = LittleFloat(x) #ifdef G2_PERFORMANCE_ANALYSIS #include "../qcommon/timing.h" @@ -55,159 +55,133 @@ int G2PerformanceCounter_G2_TransformGhoulBones = 0; int G2Time_RB_SurfaceGhoul = 0; -void G2Time_ResetTimers(void) -{ +void G2Time_ResetTimers(void) { G2Time_RB_SurfaceGhoul = 0; G2PerformanceCounter_G2_TransformGhoulBones = 0; } -void G2Time_ReportTimers(void) -{ +void G2Time_ReportTimers(void) { Com_Printf("\n---------------------------------\nRB_SurfaceGhoul: %i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", - G2Time_RB_SurfaceGhoul, - G2PerformanceCounter_G2_TransformGhoulBones - ); + G2Time_RB_SurfaceGhoul, G2PerformanceCounter_G2_TransformGhoulBones); } #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #include -//rww - RAGDOLL_END +// rww - RAGDOLL_END -extern cvar_t *r_Ghoul2UnSqash; -extern cvar_t *r_Ghoul2AnimSmooth; -extern cvar_t *r_Ghoul2NoLerp; -extern cvar_t *r_Ghoul2NoBlend; -extern cvar_t *r_Ghoul2UnSqashAfterSmooth; +extern cvar_t *r_Ghoul2UnSqash; +extern cvar_t *r_Ghoul2AnimSmooth; +extern cvar_t *r_Ghoul2NoLerp; +extern cvar_t *r_Ghoul2NoBlend; +extern cvar_t *r_Ghoul2UnSqashAfterSmooth; -bool HackadelicOnClient=false; // means this is a render traversal +bool HackadelicOnClient = false; // means this is a render traversal // I hate doing this, but this is the simplest way to get this into the routines it needs to be -mdxaBone_t worldMatrix; -mdxaBone_t worldMatrixInv; +mdxaBone_t worldMatrix; +mdxaBone_t worldMatrixInv; #ifdef _G2_GORE -qhandle_t goreShader=-1; +qhandle_t goreShader = -1; #endif -const static mdxaBone_t identityMatrix = -{ - { - { 0.0f, -1.0f, 0.0f, 0.0f }, - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } -}; +const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; -class CTransformBone -{ -public: - //rww - RAGDOLL_BEGIN - int touchRender; - //rww - RAGDOLL_END - - mdxaBone_t boneMatrix; //final matrix - int parent; // only set once - int touch; // for minimal recalculation - CTransformBone() - { - touch=0; +class CTransformBone { + public: + // rww - RAGDOLL_BEGIN + int touchRender; + // rww - RAGDOLL_END - //rww - RAGDOLL_BEGIN + mdxaBone_t boneMatrix; // final matrix + int parent; // only set once + int touch; // for minimal recalculation + CTransformBone() { + touch = 0; + + // rww - RAGDOLL_BEGIN touchRender = 0; - //rww - RAGDOLL_END + // rww - RAGDOLL_END } - }; -struct SBoneCalc -{ - int newFrame; - int currentFrame; - float backlerp; - float blendFrame; - int blendOldFrame; - bool blendMode; - float blendLerp; +struct SBoneCalc { + int newFrame; + int currentFrame; + float backlerp; + float blendFrame; + int blendOldFrame; + bool blendMode; + float blendLerp; }; class CBoneCache; -void G2_TransformBone(int index,CBoneCache &CB); +void G2_TransformBone(int index, CBoneCache &CB); -class CBoneCache -{ - void EvalLow(int index) - { - assert(index>=0&&index= 0 && index < mNumBones); + if (mFinalBones[index].touch != mCurrentTouch) { // need to evaluate the bone - assert((mFinalBones[index].parent>=0&&mFinalBones[index].parent=0) - { + assert((mFinalBones[index].parent >= 0 && mFinalBones[index].parent < mNumBones) || (index == 0 && mFinalBones[index].parent == -1)); + if (mFinalBones[index].parent >= 0) { EvalLow(mFinalBones[index].parent); // make sure parent is evaluated - SBoneCalc &par=mBones[mFinalBones[index].parent]; - mBones[index].newFrame=par.newFrame; - mBones[index].currentFrame=par.currentFrame; - mBones[index].backlerp=par.backlerp; - mBones[index].blendFrame=par.blendFrame; - mBones[index].blendOldFrame=par.blendOldFrame; - mBones[index].blendMode=par.blendMode; - mBones[index].blendLerp=par.blendLerp; + SBoneCalc &par = mBones[mFinalBones[index].parent]; + mBones[index].newFrame = par.newFrame; + mBones[index].currentFrame = par.currentFrame; + mBones[index].backlerp = par.backlerp; + mBones[index].blendFrame = par.blendFrame; + mBones[index].blendOldFrame = par.blendOldFrame; + mBones[index].blendMode = par.blendMode; + mBones[index].blendLerp = par.blendLerp; } - G2_TransformBone(index,*this); - mFinalBones[index].touch=mCurrentTouch; + G2_TransformBone(index, *this); + mFinalBones[index].touch = mCurrentTouch; } } -//rww - RAGDOLL_BEGIN - void SmoothLow(int index) - { - if (mSmoothBones[index].touch==mLastTouch) - { + // rww - RAGDOLL_BEGIN + void SmoothLow(int index) { + if (mSmoothBones[index].touch == mLastTouch) { int i; - float *oldM=&mSmoothBones[index].boneMatrix.matrix[0][0]; - float *newM=&mFinalBones[index].boneMatrix.matrix[0][0]; - for (i=0;i<12;i++,oldM++,newM++) - { - *oldM=mSmoothFactor*(*oldM-*newM)+*newM; + float *oldM = &mSmoothBones[index].boneMatrix.matrix[0][0]; + float *newM = &mFinalBones[index].boneMatrix.matrix[0][0]; + for (i = 0; i < 12; i++, oldM++, newM++) { + *oldM = mSmoothFactor * (*oldM - *newM) + *newM; } - } - else - { - memcpy(&mSmoothBones[index].boneMatrix,&mFinalBones[index].boneMatrix,sizeof(mdxaBone_t)); + } else { + memcpy(&mSmoothBones[index].boneMatrix, &mFinalBones[index].boneMatrix, sizeof(mdxaBone_t)); } mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[index]); mdxaBone_t tempMatrix; - Multiply_3x4Matrix(&tempMatrix,&mSmoothBones[index].boneMatrix, &skel->BasePoseMat); + Multiply_3x4Matrix(&tempMatrix, &mSmoothBones[index].boneMatrix, &skel->BasePoseMat); float maxl; - maxl=VectorLength(&skel->BasePoseMat.matrix[0][0]); + maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[1][0]); VectorNormalize(&tempMatrix.matrix[2][0]); - VectorScale(&tempMatrix.matrix[0][0],maxl,&tempMatrix.matrix[0][0]); - VectorScale(&tempMatrix.matrix[1][0],maxl,&tempMatrix.matrix[1][0]); - VectorScale(&tempMatrix.matrix[2][0],maxl,&tempMatrix.matrix[2][0]); - Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); + VectorScale(&tempMatrix.matrix[0][0], maxl, &tempMatrix.matrix[0][0]); + VectorScale(&tempMatrix.matrix[1][0], maxl, &tempMatrix.matrix[1][0]); + VectorScale(&tempMatrix.matrix[2][0], maxl, &tempMatrix.matrix[2][0]); + Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix, &tempMatrix, &skel->BasePoseMatInv); // Added by BTO (VV) - I hope this is right. - mSmoothBones[index].touch=mCurrentTouch; + mSmoothBones[index].touch = mCurrentTouch; #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -//rww - RAGDOLL_END + // rww - RAGDOLL_END -public: - int frameSize; - const mdxaHeader_t *header; - const model_t *mod; + public: + int frameSize; + const mdxaHeader_t *header; + const model_t *mod; // these are split for better cpu cache behavior SBoneCalc *mBones; @@ -216,84 +190,75 @@ class CBoneCache CTransformBone *mSmoothBones; // for render smoothing mdxaSkel_t **mSkels; - int mNumBones; + int mNumBones; - boneInfo_v *rootBoneList; - mdxaBone_t rootMatrix; - int incomingTime; + boneInfo_v *rootBoneList; + mdxaBone_t rootMatrix; + int incomingTime; - int mCurrentTouch; + int mCurrentTouch; - //rww - RAGDOLL_BEGIN - int mCurrentTouchRender; - int mLastTouch; - int mLastLastTouch; - //rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + int mCurrentTouchRender; + int mLastTouch; + int mLastLastTouch; + // rww - RAGDOLL_END // for render smoothing - bool mSmoothingActive; - bool mUnsquash; - float mSmoothFactor; -// int mWraithID; // this is just used for debug prints, can use it for any int of interest in JK2 - - CBoneCache(const model_t *amod,const mdxaHeader_t *aheader) : - header(aheader), - mod(amod) - { + bool mSmoothingActive; + bool mUnsquash; + float mSmoothFactor; + // int mWraithID; // this is just used for debug prints, can use it for any int of interest in JK2 + + CBoneCache(const model_t *amod, const mdxaHeader_t *aheader) : header(aheader), mod(amod) { assert(amod); assert(aheader); - mSmoothingActive=false; - mUnsquash=false; - mSmoothFactor=0.0f; + mSmoothingActive = false; + mUnsquash = false; + mSmoothFactor = 0.0f; mNumBones = header->numBones; mBones = new SBoneCalc[mNumBones]; - mFinalBones = (CTransformBone*) R_Malloc(sizeof(CTransformBone) * mNumBones, TAG_GHOUL2, qtrue); - mSmoothBones = (CTransformBone*) R_Malloc(sizeof(CTransformBone) * mNumBones, TAG_GHOUL2, qtrue); - mSkels = new mdxaSkel_t*[mNumBones]; + mFinalBones = (CTransformBone *)R_Malloc(sizeof(CTransformBone) * mNumBones, TAG_GHOUL2, qtrue); + mSmoothBones = (CTransformBone *)R_Malloc(sizeof(CTransformBone) * mNumBones, TAG_GHOUL2, qtrue); + mSkels = new mdxaSkel_t *[mNumBones]; mdxaSkelOffsets_t *offsets; - mdxaSkel_t *skel; + mdxaSkel_t *skel; offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); int i; - for (i=0;ioffsets[i]); - mSkels[i]=skel; - mFinalBones[i].parent=skel->parent; + mSkels[i] = skel; + mFinalBones[i].parent = skel->parent; } - mCurrentTouch=3; + mCurrentTouch = 3; -//rww - RAGDOLL_BEGIN - mLastTouch=2; - mLastLastTouch=1; -//rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + mLastTouch = 2; + mLastLastTouch = 1; + // rww - RAGDOLL_END } - ~CBoneCache () - { - delete [] mBones; + ~CBoneCache() { + delete[] mBones; // Alignment R_Free(mFinalBones); R_Free(mSmoothBones); - delete [] mSkels; + delete[] mSkels; } - SBoneCalc &Root() - { + SBoneCalc &Root() { assert(mNumBones); return mBones[0]; } - const mdxaBone_t &EvalUnsmooth(int index) - { + const mdxaBone_t &EvalUnsmooth(int index) { EvalLow(index); - if (mSmoothingActive&&mSmoothBones[index].touch) - { + if (mSmoothingActive && mSmoothBones[index].touch) { return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - const mdxaBone_t &Eval(int index) - { + const mdxaBone_t &Eval(int index) { /* bool wasEval=EvalLow(index); if (mSmoothingActive) @@ -347,183 +312,158 @@ class CBoneCache } return mFinalBones[index].boneMatrix; */ - //all above is not necessary, smoothing is taken care of when we want to use smoothlow (only when evalrender) - assert(index>=0&&index= 0 && index < mNumBones); + if (mFinalBones[index].touch != mCurrentTouch) { EvalLow(index); } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_BEGIN - const inline mdxaBone_t &EvalRender(int index) - { - assert(index>=0&&index= 0 && index < mNumBones); + if (mFinalBones[index].touch != mCurrentTouch) { + mFinalBones[index].touchRender = mCurrentTouchRender; EvalLow(index); } - if (mSmoothingActive) - { - if (mSmoothBones[index].touch!=mCurrentTouch) - { + if (mSmoothingActive) { + if (mSmoothBones[index].touch != mCurrentTouch) { SmoothLow(index); } return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_END - //rww - RAGDOLL_BEGIN - bool WasRendered(int index) - { - assert(index>=0&&index= 0 && index < mNumBones); + return mFinalBones[index].touchRender == mCurrentTouchRender; } - int GetParent(int index) - { - if (index==0) - { + int GetParent(int index) { + if (index == 0) { return -1; } - assert(index>=0&&index= 0 && index < mNumBones); return mFinalBones[index].parent; } - //rww - RAGDOLL_END + // rww - RAGDOLL_END // Added by BTO (VV) - This is probably broken // Need to add in smoothing step? - CTransformBone *EvalFull(int index) - { + CTransformBone *EvalFull(int index) { #ifdef JK2_MODE -// Eval(index); + // Eval(index); -// FIXME BBi Was commented + // FIXME BBi Was commented Eval(index); #else EvalRender(index); #endif // JK2_MODE - if (mSmoothingActive) - { + if (mSmoothingActive) { return mSmoothBones + index; } return mFinalBones + index; } }; -static inline float G2_GetVertBoneWeightNotSlow( const mdxmVertex_t *pVert, const int iWeightNum) -{ +static inline float G2_GetVertBoneWeightNotSlow(const mdxmVertex_t *pVert, const int iWeightNum) { float fBoneWeight; int iTemp = pVert->BoneWeightings[iWeightNum]; - iTemp|= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT+(iWeightNum*2)) ) & iG2_BONEWEIGHT_TOPBITS_AND; + iTemp |= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT + (iWeightNum * 2))) & iG2_BONEWEIGHT_TOPBITS_AND; fBoneWeight = fG2_BONEWEIGHT_RECIPROCAL_MULT * iTemp; return fBoneWeight; } -//rww - RAGDOLL_BEGIN -const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) -{ - if (!ghoul2.mBoneCache) - { +// rww - RAGDOLL_BEGIN +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) { + if (!ghoul2.mBoneCache) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.header; } -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep) -{ +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep) { // fixme, these should be precomputed - if (!ghoul2.mBoneCache||!maxDep) - { + if (!ghoul2.mBoneCache || !maxDep) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; - mdxaSkel_t *skel; + CBoneCache &boneCache = *ghoul2.mBoneCache; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); int i; - int ret=0; - for (i=0;inumChildren;i++) - { - if (!maxDep) - { + int ret = 0; + for (i = 0; i < skel->numChildren; i++) { + if (!maxDep) { return i; // number added } - *tempDependents=skel->children[i]; - assert(*tempDependents>0&&*tempDependentsnumBones); + *tempDependents = skel->children[i]; + assert(*tempDependents > 0 && *tempDependents < boneCache.header->numBones); maxDep--; tempDependents++; ret++; } - for (i=0;inumChildren;i++) - { - int num=G2_GetBoneDependents(ghoul2,skel->children[i],tempDependents,maxDep); - tempDependents+=num; - ret+=num; - maxDep-=num; - assert(maxDep>=0); - if (!maxDep) - { + for (i = 0; i < skel->numChildren; i++) { + int num = G2_GetBoneDependents(ghoul2, skel->children[i], tempDependents, maxDep); + tempDependents += num; + ret += num; + maxDep -= num; + assert(maxDep >= 0); + if (!maxDep) { break; } } return ret; } -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) -{ - if (!ghoul2.mBoneCache) - { +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return false; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.WasRendered(boneNum); } -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; } -char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) -{ - if (!ghoul2.mBoneCache) - { +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return NULL; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); @@ -531,195 +471,155 @@ char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) return skel->name; } -void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) -{ +void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) { assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&retMatrix, &boneMatrix, &skel->BasePoseMat); - if (scale[0]) - { + if (scale[0]) { retMatrix.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { retMatrix.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { retMatrix.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&retMatrix.matrix[0]); - VectorNormalize((float*)&retMatrix.matrix[1]); - VectorNormalize((float*)&retMatrix.matrix[2]); + VectorNormalize((float *)&retMatrix.matrix[0]); + VectorNormalize((float *)&retMatrix.matrix[1]); + VectorNormalize((float *)&retMatrix.matrix[2]); } -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } mdxaBone_t bolt; assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&bolt, &boneCache.Eval(boneNum), &skel->BasePoseMat); // DEST FIRST ARG - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); - Multiply_3x4Matrix(&retMatrix,&worldMatrix, &bolt); + Multiply_3x4Matrix(&retMatrix, &worldMatrix, &bolt); #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(retMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(retMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - int parent=-1; - if (ghoul2.mBoneCache) - { - CBoneCache &boneCache=*ghoul2.mBoneCache; +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) { + int parent = -1; + if (ghoul2.mBoneCache) { + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); - parent=boneCache.GetParent(boneNum); - if (parent<0||parent>=boneCache.header->numBones) - { - parent=-1; - retMatrix=identityMatrix; + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + parent = boneCache.GetParent(boneNum); + if (parent < 0 || parent >= boneCache.header->numBones) { + parent = -1; + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); - } - else - { - G2_GetBoneMatrixLow(ghoul2,parent,scale,retMatrix,retBasepose,retBaseposeInv); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + } else { + G2_GetBoneMatrixLow(ghoul2, parent, scale, retMatrix, retBasepose, retBaseposeInv); } } return parent; } -//rww - RAGDOLL_END +// rww - RAGDOLL_END -void RemoveBoneCache(CBoneCache *boneCache) -{ - delete boneCache; -} +void RemoveBoneCache(CBoneCache *boneCache) { delete boneCache; } -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache) -{ +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache) { assert(boneCache); return boneCache->Eval(index); } - -class CRenderSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - const shader_t *cust_shader; - int fogNum; - qboolean personalModel; - CBoneCache *boneCache; - int renderfx; - const skin_t *skin; - const model_t *currentModel; - int lod; - boltInfo_v &boltList; +class CRenderSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + const shader_t *cust_shader; + int fogNum; + qboolean personalModel; + CBoneCache *boneCache; + int renderfx; + const skin_t *skin; + const model_t *currentModel; + int lod; + boltInfo_v &boltList; #ifdef _G2_GORE - shader_t *gore_shader; - CGoreSet *gore_set; + shader_t *gore_shader; + CGoreSet *gore_set; #endif - CRenderSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - const shader_t *initcust_shader, - int initfogNum, - qboolean initpersonalModel, - CBoneCache *initboneCache, - int initrenderfx, - const skin_t *initskin, - const model_t *initcurrentModel, - int initlod, + CRenderSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, const shader_t *initcust_shader, int initfogNum, qboolean initpersonalModel, + CBoneCache *initboneCache, int initrenderfx, const skin_t *initskin, const model_t *initcurrentModel, int initlod, #ifdef _G2_GORE - boltInfo_v &initboltList, - shader_t *initgore_shader, - CGoreSet *initgore_set): + boltInfo_v &initboltList, shader_t *initgore_shader, CGoreSet *initgore_set) + : #else - boltInfo_v &initboltList): + boltInfo_v &initboltList) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - cust_shader(initcust_shader), - fogNum(initfogNum), - personalModel(initpersonalModel), - boneCache(initboneCache), - renderfx(initrenderfx), - skin(initskin), - currentModel(initcurrentModel), - lod(initlod), + surfaceNum(initsurfaceNum), rootSList(initrootSList), cust_shader(initcust_shader), fogNum(initfogNum), personalModel(initpersonalModel), + boneCache(initboneCache), renderfx(initrenderfx), skin(initskin), currentModel(initcurrentModel), lod(initlod), #ifdef _G2_GORE - boltList(initboltList), - gore_shader(initgore_shader), - gore_set(initgore_set) + boltList(initboltList), gore_shader(initgore_shader), gore_set(initgore_set) #else - boltList(initboltList) + boltList(initboltList) #endif - {} + { + } }; #define MAX_RENDER_SURFACES (2048) static CRenderableSurface RSStorage[MAX_RENDER_SURFACES]; -static unsigned int NextRS=0; +static unsigned int NextRS = 0; -CRenderableSurface *AllocRS() -{ - CRenderableSurface *ret=&RSStorage[NextRS]; +CRenderableSurface *AllocRS() { + CRenderableSurface *ret = &RSStorage[NextRS]; ret->Init(); NextRS++; - NextRS%=MAX_RENDER_SURFACES; + NextRS %= MAX_RENDER_SURFACES; return ret; } @@ -734,36 +634,31 @@ frame. */ - /* ============= R_ACullModel ============= */ -static int R_GCullModel( trRefEntity_t *ent ) { +static int R_GCullModel(trRefEntity_t *ent) { // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } // cull bounding sphere - switch ( R_CullLocalPointAndRadius( vec3_origin, ent->e.radius * largestScale) ) - { - case CULL_OUT: - tr.pc.c_sphere_cull_md3_out++; - return CULL_OUT; + switch (R_CullLocalPointAndRadius(vec3_origin, ent->e.radius * largestScale)) { + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; case CULL_IN: tr.pc.c_sphere_cull_md3_in++; @@ -772,334 +667,272 @@ static int R_GCullModel( trRefEntity_t *ent ) { case CULL_CLIP: tr.pc.c_sphere_cull_md3_clip++; return CULL_IN; - } + } return CULL_IN; } - /* ================= R_AComputeFogNum ================= */ -static int R_GComputeFogNum( trRefEntity_t *ent ) { +static int R_GComputeFogNum(trRefEntity_t *ent) { - int i; - fog_t *fog; + int i; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - if ( tr.refdef.doLAGoggles ) - { + if (tr.refdef.doLAGoggles) { return tr.world->numfogs; } int partialFog = 0; - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - if ( ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] - && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] - && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] - && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] - && ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] - && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2] ) - {//totally inside it + if (ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && + ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2]) { // totally inside it return i; break; } - if ( ( ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && - ent->e.origin[0] - ent->e.radius <= fog->bounds[1][0] && ent->e.origin[1] - ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] - ent->e.radius <= fog->bounds[1][2] ) || - ( ent->e.origin[0] + ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] + ent->e.radius >= fog->bounds[0][1] && ent->e.origin[2] + ent->e.radius >= fog->bounds[0][2] && - ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2] ) ) - {//partially inside it - if ( tr.refdef.fogIndex == i || R_FogParmsMatch( tr.refdef.fogIndex, i ) ) - {//take new one only if it's the same one that the viewpoint is in + if ((ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && + ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && ent->e.origin[0] - ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] - ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] - ent->e.radius <= fog->bounds[1][2]) || + (ent->e.origin[0] + ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] + ent->e.radius >= fog->bounds[0][1] && + ent->e.origin[2] + ent->e.radius >= fog->bounds[0][2] && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2])) { // partially inside it + if (tr.refdef.fogIndex == i || R_FogParmsMatch(tr.refdef.fogIndex, i)) { // take new one only if it's the same one that the viewpoint is in return i; break; - } - else if ( !partialFog ) - {//first partialFog + } else if (!partialFog) { // first partialFog partialFog = i; } } } - //if nothing else, use the first partial fog you found + // if nothing else, use the first partial fog you found return partialFog; } // work out lod for this entity. -static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int lodBias ) -{ +static int G2_ComputeLOD(trRefEntity_t *ent, const model_t *currentModel, int lodBias) { float flod, lodscale; float projectedRadius; int lod; - if ( currentModel->numLods < 2 ) - { // model has only 1 LOD level, skip computations and bias - return(0); + if (currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias + return (0); } - if (r_lodbias->integer > lodBias) - { + if (r_lodbias->integer > lodBias) { lodBias = r_lodbias->integer; } //**early out, it's going to be max lod - if (lodBias >= currentModel->numLods ) - { + if (lodBias >= currentModel->numLods) { return currentModel->numLods - 1; } - // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } - if ( ( projectedRadius = ProjectRadius( 0.75*largestScale*ent->e.radius, ent->e.origin ) ) != 0 ) //we reduce the radius to make the LOD match other model types which use the actual bound box size - { - lodscale = r_lodscale->value; - if (lodscale > 20) lodscale = 20; - flod = 1.0f - projectedRadius * lodscale; - } - else - { - // object intersects near view plane, e.g. view weapon - flod = 0; - } - - flod *= currentModel->numLods; - lod = Q_ftol( flod ); + if ((projectedRadius = ProjectRadius(0.75 * largestScale * ent->e.radius, ent->e.origin)) != + 0) // we reduce the radius to make the LOD match other model types which use the actual bound box size + { + lodscale = r_lodscale->value; + if (lodscale > 20) + lodscale = 20; + flod = 1.0f - projectedRadius * lodscale; + } else { + // object intersects near view plane, e.g. view weapon + flod = 0; + } - if ( lod < 0 ) - { - lod = 0; - } - else if ( lod >= currentModel->numLods ) - { - lod = currentModel->numLods - 1; - } + flod *= currentModel->numLods; + lod = Q_ftol(flod); + if (lod < 0) { + lod = 0; + } else if (lod >= currentModel->numLods) { + lod = currentModel->numLods - 1; + } lod += lodBias; - if ( lod >= currentModel->numLods ) + if (lod >= currentModel->numLods) lod = currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; } - -void Multiply_3x4Matrix(mdxaBone_t *out,const mdxaBone_t *in2,const mdxaBone_t *in) -{ +void Multiply_3x4Matrix(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *in) { // first row of out out->matrix[0][0] = (in2->matrix[0][0] * in->matrix[0][0]) + (in2->matrix[0][1] * in->matrix[1][0]) + (in2->matrix[0][2] * in->matrix[2][0]); out->matrix[0][1] = (in2->matrix[0][0] * in->matrix[0][1]) + (in2->matrix[0][1] * in->matrix[1][1]) + (in2->matrix[0][2] * in->matrix[2][1]); out->matrix[0][2] = (in2->matrix[0][0] * in->matrix[0][2]) + (in2->matrix[0][1] * in->matrix[1][2]) + (in2->matrix[0][2] * in->matrix[2][2]); - out->matrix[0][3] = (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; + out->matrix[0][3] = + (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; // second row of outf out out->matrix[1][0] = (in2->matrix[1][0] * in->matrix[0][0]) + (in2->matrix[1][1] * in->matrix[1][0]) + (in2->matrix[1][2] * in->matrix[2][0]); out->matrix[1][1] = (in2->matrix[1][0] * in->matrix[0][1]) + (in2->matrix[1][1] * in->matrix[1][1]) + (in2->matrix[1][2] * in->matrix[2][1]); out->matrix[1][2] = (in2->matrix[1][0] * in->matrix[0][2]) + (in2->matrix[1][1] * in->matrix[1][2]) + (in2->matrix[1][2] * in->matrix[2][2]); - out->matrix[1][3] = (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; + out->matrix[1][3] = + (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; // third row of out out out->matrix[2][0] = (in2->matrix[2][0] * in->matrix[0][0]) + (in2->matrix[2][1] * in->matrix[1][0]) + (in2->matrix[2][2] * in->matrix[2][0]); out->matrix[2][1] = (in2->matrix[2][0] * in->matrix[0][1]) + (in2->matrix[2][1] * in->matrix[1][1]) + (in2->matrix[2][2] * in->matrix[2][1]); out->matrix[2][2] = (in2->matrix[2][0] * in->matrix[0][2]) + (in2->matrix[2][1] * in->matrix[1][2]) + (in2->matrix[2][2] * in->matrix[2][2]); - out->matrix[2][3] = (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; + out->matrix[2][3] = + (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; } -static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) -{ - assert(iFrame>=0&&iFramenumFrames); - assert(iBone>=0&&iBonenumBones); +static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) { + assert(iFrame >= 0 && iFrame < pMDXAHeader->numFrames); + assert(iBone >= 0 && iBone < pMDXAHeader->numBones); - const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); - mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte*)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); + const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); + mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); return (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); } - -/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) -{ - mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); - MC_UnCompressQuat(mat, pCompBonePool[ G2_GetBonePoolIndex( pMDXAHeader, iFrame, iBoneIndex ) ].Comp); +/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) { + mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); + MC_UnCompressQuat(mat, pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); } - - #define DEBUG_G2_TIMING (0) #define DEBUG_G2_TIMING_RENDER_ONLY (1) -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp) -{ - assert(bone.startFrame>=0); - assert(bone.startFrame<=numFramesInFile); - assert(bone.endFrame>=0); - assert(bone.endFrame<=numFramesInFile); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp) { + assert(bone.startFrame >= 0); + assert(bone.startFrame <= numFramesInFile); + assert(bone.endFrame >= 0); + assert(bone.endFrame <= numFramesInFile); // yes - add in animation speed to current frame - float animSpeed = bone.animSpeed; - float time; - if (bone.pauseTime) - { + float animSpeed = bone.animSpeed; + float time; + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (currentTime - bone.startTime) / 50.0f; } - if (time<0.0f) - { - time=0.0f; + if (time < 0.0f) { + time = 0.0f; } - float newFrame_g = bone.startFrame + (time * animSpeed); + float newFrame_g = bone.startFrame + (time * animSpeed); - int animSize = bone.endFrame - bone.startFrame; - float endFrame = (float)bone.endFrame; + int animSize = bone.endFrame - bone.startFrame; + float endFrame = (float)bone.endFrame; // we are supposed to be animating right? - if (animSize) - { + if (animSize) { // did we run off the end? - if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { + if (animSpeed < 0.0f) { // we don't use this case, or so I am told // if we do, let me know, I need to insure the mod works // should we be creating a virtual frame? - if ((newFrame_g < endFrame+1) && (newFrame_g >= endFrame)) - { + if ((newFrame_g < endFrame + 1) && (newFrame_g >= endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = float(endFrame+1)-newFrame_g; + lerp = float(endFrame + 1) - newFrame_g; // frames are easy to calculate currentFrame = endFrame; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = (ceil(newFrame_g)-newFrame_g); + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (currentFrame <= endFrame+1 ) - { + if (currentFrame <= endFrame + 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame - 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - } - else - { + } else { // should we be creating a virtual frame? - if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) - { + if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + assert(newFrame >= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (newFrame_g >= endFrame - 1) - { + if (newFrame_g >= endFrame - 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame + 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } // sanity check - assert (((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); - } - else - { - if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) - { + assert(((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); + } else { + if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) { // if we are supposed to reset the default anim, then do so - if (animSpeed > 0.0f) - { + if (animSpeed > 0.0f) { currentFrame = bone.endFrame - 1; - assert(currentFrame>=0&¤tFrame=0&¤tFrame= 0 && currentFrame < numFramesInFile); + } else { + currentFrame = bone.endFrame + 1; + assert(currentFrame >= 0 && currentFrame < numFramesInFile); } newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } - else - { + } else { bone.flags &= ~(BONE_ANIM_TOTAL); } - } - } - else - { - if (animSpeed> 0.0) - { + } else { + if (animSpeed > 0.0) { // frames are easy to calculate currentFrame = (int)newFrame_g; @@ -1107,83 +940,65 @@ void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int &cu // frame we want to display lerp = (newFrame_g - currentFrame); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame + 1; // are we now on the end frame? - assert((int)endFrame<=numFramesInFile); - if (newFrame >= (int)endFrame) - { + assert((int)endFrame <= numFramesInFile); + if (newFrame >= (int)endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame-1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - if (currentFrame>bone.startFrame) - { - currentFrame=bone.startFrame; + if (currentFrame > bone.startFrame) { + currentFrame = bone.startFrame; newFrame = currentFrame; - lerp=0.0f; - } - else - { - newFrame=currentFrame-1; + lerp = 0.0f; + } else { + newFrame = currentFrame - 1; // are we now on the end frame? - if (newFrame < endFrame+1) - { + if (newFrame < endFrame + 1) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame+1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } - assert(currentFrame>=0&¤tFrame=0&&newFrame= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); } } - } - else - { - if (animSpeed<0.0) - { - currentFrame = bone.endFrame+1; - } - else - { - currentFrame = bone.endFrame-1; + } else { + if (animSpeed < 0.0) { + currentFrame = bone.endFrame + 1; + } else { + currentFrame = bone.endFrame - 1; } - if (currentFrame<0) - { - currentFrame=0; + if (currentFrame < 0) { + currentFrame = 0; } - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } /* assert(currentFrame>=0&¤tFrameheader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - //find/add the bone in the list - if (!skel->name[0]) - { + // find/add the bone in the list + if (!skel->name[0]) { bListIndex = -1; - } - else - { + } else { bListIndex = G2_Find_Bone(&ghoul2, ghoul2.mBlist, skel->name); - if (bListIndex == -1) - { + if (bListIndex == -1) { #ifdef _RAG_PRINT_TEST Com_Printf("Attempting to add %s\n", skel->name); #endif @@ -1237,34 +1047,28 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &bone = ghoul2.mBlist[bListIndex]; - if (bone.hasAnimFrameMatrix == frame) - { //already calculated so just grab it + if (bone.hasAnimFrameMatrix == frame) { // already calculated so just grab it matrix = bone.animFrameMatrix; return; } - //get the base matrix for the specified frame + // get the base matrix for the specified frame UnCompressBone(animMatrix.matrix, boneNum, ghoul2.mBoneCache->header, frame); parent = skel->parent; - if (boneNum > 0 && parent > -1) - { - //recursively call to assure all parent matrices are set up + if (boneNum > 0 && parent > -1) { + // recursively call to assure all parent matrices are set up G2_RagGetAnimMatrix(ghoul2, parent, matrix, frame); - //assign the new skel ptr for our parent + // assign the new skel ptr for our parent pskel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[parent]); - //taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix - if (!pskel->name[0]) - { + // taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix + if (!pskel->name[0]) { parentBlistIndex = -1; - } - else - { + } else { parentBlistIndex = G2_Find_Bone(&ghoul2, ghoul2.mBlist, pskel->name); - if (parentBlistIndex == -1) - { + if (parentBlistIndex == -1) { parentBlistIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); } } @@ -1273,46 +1077,37 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &pbone = ghoul2.mBlist[parentBlistIndex]; - assert(pbone.hasAnimFrameMatrix == frame); //this should have been calc'd in the recursive call + assert(pbone.hasAnimFrameMatrix == frame); // this should have been calc'd in the recursive call Multiply_3x4Matrix(&bone.animFrameMatrix, &pbone.animFrameMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (parentBlistIndex != -1 && bListIndex != -1) - { + if (parentBlistIndex != -1 && bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); } #endif - } - else - { //root + } else { // root Multiply_3x4Matrix(&bone.animFrameMatrix, &ghoul2.mBoneCache->rootMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (bListIndex != -1) - { + if (bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s\n", skel->name); } #endif - //bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; - //Maybe use this for the root, so that the orientation is in sync with the current - //root matrix? However this would require constant recalculation of this base - //skeleton which I currently do not want. + // bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; + // Maybe use this for the root, so that the orientation is in sync with the current + // root matrix? However this would require constant recalculation of this base + // skeleton which I currently do not want. } - //never need to figure it out again + // never need to figure it out again bone.hasAnimFrameMatrix = frame; #ifdef _RAG_PRINT_TEST - if (!actuallySet) - { + if (!actuallySet) { Com_Printf("SET FAILURE\n"); } #endif @@ -1322,351 +1117,271 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat // transform each individual bone's information - making sure to use any override information provided, both for angles and for animations, as // well as multiplying each bone's matrix by it's parents matrix -void G2_TransformBone (int child,CBoneCache &BC) -{ - SBoneCalc &TB=BC.mBones[child]; - mdxaBone_t tbone[6]; -// mdxaFrame_t *aFrame=0; -// mdxaFrame_t *bFrame=0; -// mdxaFrame_t *aoldFrame=0; -// mdxaFrame_t *boldFrame=0; - mdxaSkel_t *skel; +void G2_TransformBone(int child, CBoneCache &BC) { + SBoneCalc &TB = BC.mBones[child]; + mdxaBone_t tbone[6]; + // mdxaFrame_t *aFrame=0; + // mdxaFrame_t *bFrame=0; + // mdxaFrame_t *aoldFrame=0; + // mdxaFrame_t *boldFrame=0; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; - boneInfo_v &boneList = *BC.rootBoneList; - int j, boneListIndex; - int angleOverride = 0; + boneInfo_v &boneList = *BC.rootBoneList; + int j, boneListIndex; + int angleOverride = 0; #if DEBUG_G2_TIMING - bool printTiming=false; + bool printTiming = false; #endif // should this bone be overridden by a bone in the bone list? boneListIndex = G2_Find_Bone_In_List(boneList, child); - if (boneListIndex != -1) - { + if (boneListIndex != -1) { // we found a bone in the list - we need to override something here. // do we override the rotational angles? - if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) - { + if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) { angleOverride = (boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL); } // set blending stuff if we need to - if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) - { + if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) { float blendTime = BC.incomingTime - boneList[boneListIndex].blendStart; - // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the hiearchy - if (blendTime>=0.0f&&blendTime < boneList[boneListIndex].blendTime) - { - TB.blendFrame = boneList[boneListIndex].blendFrame; + // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the + // hiearchy + if (blendTime >= 0.0f && blendTime < boneList[boneListIndex].blendTime) { + TB.blendFrame = boneList[boneListIndex].blendFrame; TB.blendOldFrame = boneList[boneListIndex].blendLerpFrame; TB.blendLerp = (blendTime / boneList[boneListIndex].blendTime); TB.blendMode = true; - } - else - { + } else { TB.blendMode = false; } - } - else if (r_Ghoul2NoBlend->integer||((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) + } else if (r_Ghoul2NoBlend->integer || ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) // turn off blending if we are just doing a straing animation override { TB.blendMode = false; } // should this animation be overridden by an animation in the bone list? - if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - G2_TimingModel(boneList[boneListIndex],BC.incomingTime,BC.header->numFrames,TB.currentFrame,TB.newFrame,TB.backlerp); + if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + G2_TimingModel(boneList[boneListIndex], BC.incomingTime, BC.header->numFrames, TB.currentFrame, TB.newFrame, TB.backlerp); } #if DEBUG_G2_TIMING - printTiming=true; + printTiming = true; #endif - if ((r_Ghoul2NoLerp->integer)||((boneList[boneListIndex].flags) & (BONE_ANIM_NO_LERP))) - { + if ((r_Ghoul2NoLerp->integer) || ((boneList[boneListIndex].flags) & (BONE_ANIM_NO_LERP))) { TB.backlerp = 0.0f; } } // figure out where the location of the bone animation data is - assert(TB.newFrame>=0&&TB.newFramenumFrames); - if (!(TB.newFrame>=0&&TB.newFramenumFrames)) - { - TB.newFrame=0; + assert(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames); + if (!(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames)) { + TB.newFrame = 0; } -// aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); - assert(TB.currentFrame>=0&&TB.currentFramenumFrames); - if (!(TB.currentFrame>=0&&TB.currentFramenumFrames)) - { - TB.currentFrame=0; + // aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); + assert(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames); + if (!(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames)) { + TB.currentFrame = 0; } -// aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); + // aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); // figure out where the location of the blended animation data is - assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1))); - if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1) ) - { - TB.blendFrame=0.0; + assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1))); + if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1)) { + TB.blendFrame = 0.0; } -// bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); - assert(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames); - if (!(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames)) - { - TB.blendOldFrame=0; + // bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); + assert(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames); + if (!(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames)) { + TB.blendOldFrame = 0; } #if DEBUG_G2_TIMING #if DEBUG_G2_TIMING_RENDER_ONLY - if (!HackadelicOnClient) - { - printTiming=false; + if (!HackadelicOnClient) { + printTiming = false; } #endif - if (printTiming) - { + if (printTiming) { char mess[1000]; - if (TB.blendMode) - { - sprintf(mess,"b %2d %5d %4d %4d %4d %4d %f %f\n",boneListIndex,BC.incomingTime,(int)TB.newFrame,(int)TB.currentFrame,(int)TB.blendFrame,(int)TB.blendOldFrame,TB.backlerp,TB.blendLerp); - } - else - { - sprintf(mess,"a %2d %5d %4d %4d %f\n",boneListIndex,BC.incomingTime,TB.newFrame,TB.currentFrame,TB.backlerp); + if (TB.blendMode) { + sprintf(mess, "b %2d %5d %4d %4d %4d %4d %f %f\n", boneListIndex, BC.incomingTime, (int)TB.newFrame, (int)TB.currentFrame, (int)TB.blendFrame, + (int)TB.blendOldFrame, TB.backlerp, TB.blendLerp); + } else { + sprintf(mess, "a %2d %5d %4d %4d %f\n", boneListIndex, BC.incomingTime, TB.newFrame, TB.currentFrame, TB.backlerp); } OutputDebugString(mess); - const boneInfo_t &bone=boneList[boneListIndex]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess," bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); - } - else - { - sprintf(mess," bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); - } -// OutputDebugString(mess); + const boneInfo_t &bone = boneList[boneListIndex]; + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, + " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + boneListIndex, BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, + bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, " bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", boneListIndex, + BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags); + } + // OutputDebugString(mess); } #endif -// boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); + // boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); -// mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); + // mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); - assert(child>=0&&childnumBones); -// assert(bFrame->boneIndexes[child]>=0); -// assert(boldFrame->boneIndexes[child]>=0); -// assert(aFrame->boneIndexes[child]>=0); -// assert(aoldFrame->boneIndexes[child]>=0); + assert(child >= 0 && child < BC.header->numBones); + // assert(bFrame->boneIndexes[child]>=0); + // assert(boldFrame->boneIndexes[child]>=0); + // assert(aFrame->boneIndexes[child]>=0); + // assert(aoldFrame->boneIndexes[child]>=0); // decide where the transformed bone is going // are we blending with another frame of anim? - if (TB.blendMode) - { + if (TB.blendMode) { float backlerp = TB.blendFrame - (int)TB.blendFrame; float frontlerp = 1.0 - backlerp; -// MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[3].matrix, child, BC.header, TB.blendFrame); UnCompressBone(tbone[4].matrix, child, BC.header, TB.blendOldFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) - + (frontlerp * ((float *)&tbone[4])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) + (frontlerp * ((float *)&tbone[4])[j]); } } - // - // lerp this bone - use the temp space on the ref entity to put the bone transforms into - // - if (!TB.backlerp) - { -// MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // + // lerp this bone - use the temp space on the ref entity to put the bone transforms into + // + if (!TB.backlerp) { + // MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[2].matrix, child, BC.header, TB.currentFrame); // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } - } - else - { + } + } else { float frontlerp = 1.0 - TB.backlerp; -// MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[0].matrix, child, BC.header, TB.newFrame); UnCompressBone(tbone[1].matrix, child, BC.header, TB.currentFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) - + (frontlerp * ((float *)&tbone[1])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) + (frontlerp * ((float *)&tbone[1])[j]); } // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } + } } // figure out where the bone hirearchy info is offsets = (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)BC.header + sizeof(mdxaHeader_t) + offsets->offsets[child]); - int parent=BC.mFinalBones[child].parent; - assert((parent==-1&&child==0)||(parent>=0&&parent= 0 && parent < BC.mNumBones)); + if (angleOverride & BONE_ANGLES_REPLACE) { + bool isRag = !!(angleOverride & BONE_ANGLES_RAGDOLL); + if (!isRag) { // do the same for ik.. I suppose. isRag = !!(angleOverride & BONE_ANGLES_IK); } mdxaBone_t &bone = BC.mFinalBones[child].boneMatrix; boneInfo_t &boneOverride = boneList[boneListIndex]; - if (isRag) - { + if (isRag) { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // this is crazy, we are gonna drive the animation to ID while we are doing post mults to compensate. - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); - static mdxaBone_t toMatrix = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - toMatrix.matrix[0][0]=matrixScale; - toMatrix.matrix[1][1]=matrixScale; - toMatrix.matrix[2][2]=matrixScale; - toMatrix.matrix[0][3]=temp.matrix[0][3]; - toMatrix.matrix[1][3]=temp.matrix[1][3]; - toMatrix.matrix[2][3]=temp.matrix[2][3]; - - Multiply_3x4Matrix(&temp, &toMatrix,&skel->BasePoseMatInv); //dest first arg + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); + static mdxaBone_t toMatrix = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + toMatrix.matrix[0][0] = matrixScale; + toMatrix.matrix[1][1] = matrixScale; + toMatrix.matrix[2][2] = matrixScale; + toMatrix.matrix[0][3] = temp.matrix[0][3]; + toMatrix.matrix[1][3] = temp.matrix[1][3]; + toMatrix.matrix[2][3] = temp.matrix[2][3]; + + Multiply_3x4Matrix(&temp, &toMatrix, &skel->BasePoseMatInv); // dest first arg float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp>0.0f) - { + if (blendLerp > 0.0f) { // has started - if (blendLerp>1.0f) - { + if (blendLerp > 1.0f) { // done -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); - memcpy (&bone,&temp, sizeof(mdxaBone_t)); - } - else - { -// mdxaBone_t lerp; + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); + memcpy(&bone, &temp, sizeof(mdxaBone_t)); + } else { + // mdxaBone_t lerp; // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&tbone[2])[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&tbone[2])[j]); } -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); } } - } - else - { + } else { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // are we attempting to blend with the base animation? and still within blend time? - if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) - { + if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) { // ok, we are supposed to be blending. Work out lerp float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp <= 1) - { - if (blendLerp < 0) - { + if (blendLerp <= 1) { + if (blendLerp < 0) { assert(0); } // now work out the matrix we want to get *to* - firstPass is where we are coming *from* Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1675,51 +1390,39 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&temp, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&temp, &newMatrixTemp, &skel->BasePoseMatInv); // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&firstPass)[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&firstPass)[j]); } - } - else - { + } else { bone = firstPass; } } // no, so just override it directly - else - { + else { - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1728,159 +1431,113 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&bone, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&bone, &newMatrixTemp, &skel->BasePoseMatInv); } } - } - else if (angleOverride & BONE_ANGLES_PREMULT) - { - if ((angleOverride&BONE_ANGLES_RAGDOLL) || (angleOverride&BONE_ANGLES_IK)) - { - mdxaBone_t tmp; - if (!child) - { - if (HackadelicOnClient) - { + } else if (angleOverride & BONE_ANGLES_PREMULT) { + if ((angleOverride & BONE_ANGLES_RAGDOLL) || (angleOverride & BONE_ANGLES_IK)) { + mdxaBone_t tmp; + if (!child) { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { - if (HackadelicOnClient) - { + } else { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tmp, &tbone[2]); - } - else - { - if (!child) - { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tmp, &tbone[2]); + } else { + if (!child) { // use the in coming root matrix as our basis - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { + } else { // convert from 3x4 matrix to a 4x4 matrix - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } } - } - else - // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely - if (child) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); - } + } else + // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely + if (child) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); + } // now multiply our resulting bone by an override matrix should we need to - if (angleOverride & BONE_ANGLES_POSTMULT) - { - mdxaBone_t tempMatrix; - memcpy (&tempMatrix,&BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); - if (HackadelicOnClient) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); - } - else - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); + if (angleOverride & BONE_ANGLES_POSTMULT) { + mdxaBone_t tempMatrix; + memcpy(&tempMatrix, &BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); + if (HackadelicOnClient) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); + } else { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); } } - if (r_Ghoul2UnSqash->integer) - { + if (r_Ghoul2UnSqash->integer) { mdxaBone_t tempMatrix; - Multiply_3x4Matrix(&tempMatrix,&BC.mFinalBones[child].boneMatrix, &skel->BasePoseMat); + Multiply_3x4Matrix(&tempMatrix, &BC.mFinalBones[child].boneMatrix, &skel->BasePoseMat); float maxl; - maxl=VectorLength(&skel->BasePoseMat.matrix[0][0]); + maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[1][0]); VectorNormalize(&tempMatrix.matrix[2][0]); - VectorScale(&tempMatrix.matrix[0][0],maxl,&tempMatrix.matrix[0][0]); - VectorScale(&tempMatrix.matrix[1][0],maxl,&tempMatrix.matrix[1][0]); - VectorScale(&tempMatrix.matrix[2][0],maxl,&tempMatrix.matrix[2][0]); - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); + VectorScale(&tempMatrix.matrix[0][0], maxl, &tempMatrix.matrix[0][0]); + VectorScale(&tempMatrix.matrix[1][0], maxl, &tempMatrix.matrix[1][0]); + VectorScale(&tempMatrix.matrix[2][0], maxl, &tempMatrix.matrix[2][0]); + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &skel->BasePoseMatInv); } - } - -#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_STARTED 0x0010 // start the recursive hirearchial bone transform and lerp process for this model -void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time,bool smooth=true) -{ +void G2_TransformGhoulBones(boneInfo_v &rootBoneList, mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time, bool smooth = true) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceCounter_G2_TransformGhoulBones++; #endif assert(ghoul2.aHeader); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - if (!ghoul2.aHeader->numBones) - { + if (!ghoul2.aHeader->numBones) { assert(0); // this would be strange return; } - if (!ghoul2.mBoneCache) - { - ghoul2.mBoneCache=new CBoneCache(ghoul2.currentModel,ghoul2.aHeader); + if (!ghoul2.mBoneCache) { + ghoul2.mBoneCache = new CBoneCache(ghoul2.currentModel, ghoul2.aHeader); } - ghoul2.mBoneCache->mod=ghoul2.currentModel; - ghoul2.mBoneCache->header=ghoul2.aHeader; - assert((int)ghoul2.mBoneCache->mNumBones==ghoul2.aHeader->numBones); + ghoul2.mBoneCache->mod = ghoul2.currentModel; + ghoul2.mBoneCache->header = ghoul2.aHeader; + assert((int)ghoul2.mBoneCache->mNumBones == ghoul2.aHeader->numBones); - ghoul2.mBoneCache->mSmoothingActive=false; - ghoul2.mBoneCache->mUnsquash=false; + ghoul2.mBoneCache->mSmoothingActive = false; + ghoul2.mBoneCache->mUnsquash = false; // master smoothing control - float val=r_Ghoul2AnimSmooth->value; - if (smooth&&val>0.0f&&val<1.0f) - { - ghoul2.mBoneCache->mLastTouch=ghoul2.mBoneCache->mLastLastTouch; - - if(ghoul2.mFlags & GHOUL2_RAG_STARTED) - { - for (size_t k=0;ktime-250 && - bone.firstCollisionTime time) - { + float val = r_Ghoul2AnimSmooth->value; + if (smooth && val > 0.0f && val < 1.0f) { + ghoul2.mBoneCache->mLastTouch = ghoul2.mBoneCache->mLastLastTouch; + + if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { + for (size_t k = 0; k < rootBoneList.size(); k++) { + boneInfo_t &bone = rootBoneList[k]; + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (bone.firstCollisionTime && bone.firstCollisionTime > time - 250 && bone.firstCollisionTime < time) { + val = 0.9f; //(val+0.8f)/2.0f; + } else if (bone.airTime > time) { val = 0.2f; - } - else - { + } else { val = 0.8f; } break; @@ -1888,74 +1545,64 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh } } - ghoul2.mBoneCache->mSmoothFactor=val; - ghoul2.mBoneCache->mSmoothingActive=true; - if (r_Ghoul2UnSqashAfterSmooth->integer) - { - ghoul2.mBoneCache->mUnsquash=true; + ghoul2.mBoneCache->mSmoothFactor = val; + ghoul2.mBoneCache->mSmoothingActive = true; + if (r_Ghoul2UnSqashAfterSmooth->integer) { + ghoul2.mBoneCache->mUnsquash = true; } - } - else - { - ghoul2.mBoneCache->mSmoothFactor=1.0f; + } else { + ghoul2.mBoneCache->mSmoothFactor = 1.0f; } ghoul2.mBoneCache->mCurrentTouch++; -//rww - RAGDOLL_BEGIN - if (HackadelicOnClient) - { - ghoul2.mBoneCache->mLastLastTouch=ghoul2.mBoneCache->mCurrentTouch; - ghoul2.mBoneCache->mCurrentTouchRender=ghoul2.mBoneCache->mCurrentTouch; - } - else - { - ghoul2.mBoneCache->mCurrentTouchRender=0; - } -//rww - RAGDOLL_END - -// ghoul2.mBoneCache->mWraithID=0; - ghoul2.mBoneCache->frameSize = 0;// can be deleted in new G2 format //(int)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); - - ghoul2.mBoneCache->rootBoneList=&rootBoneList; - ghoul2.mBoneCache->rootMatrix=rootMatrix; - ghoul2.mBoneCache->incomingTime=time; - - SBoneCalc &TB=ghoul2.mBoneCache->Root(); - TB.newFrame=0; - TB.currentFrame=0; - TB.backlerp=0.0f; - TB.blendFrame=0; - TB.blendOldFrame=0; - TB.blendMode=false; - TB.blendLerp=0; - + // rww - RAGDOLL_BEGIN + if (HackadelicOnClient) { + ghoul2.mBoneCache->mLastLastTouch = ghoul2.mBoneCache->mCurrentTouch; + ghoul2.mBoneCache->mCurrentTouchRender = ghoul2.mBoneCache->mCurrentTouch; + } else { + ghoul2.mBoneCache->mCurrentTouchRender = 0; + } + // rww - RAGDOLL_END + + // ghoul2.mBoneCache->mWraithID=0; + ghoul2.mBoneCache->frameSize = 0; // can be deleted in new G2 format //(int)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); + + ghoul2.mBoneCache->rootBoneList = &rootBoneList; + ghoul2.mBoneCache->rootMatrix = rootMatrix; + ghoul2.mBoneCache->incomingTime = time; + + SBoneCalc &TB = ghoul2.mBoneCache->Root(); + TB.newFrame = 0; + TB.currentFrame = 0; + TB.backlerp = 0.0f; + TB.blendFrame = 0; + TB.blendOldFrame = 0; + TB.blendMode = false; + TB.blendLerp = 0; } - #define MDX_TAG_ORIGIN 2 //====================================================================== // // Surface Manipulation code - // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, const model_t *mod,mdxaBone_t &retMatrix) -{ - mdxmVertex_t *v, *vert0, *vert1, *vert2; - vec3_t axes[3], sides[3]; - float pTri[3][3], d; - int j, k; +void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, + const model_t *mod, mdxaBone_t &retMatrix) { + mdxmVertex_t *v, *vert0, *vert1, *vert2; + vec3_t axes[3], sides[3]; + float pTri[3][3], d; + int j, k; // now there are two types of tag surface - model ones and procedural generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; - int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface(mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface(mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -1963,70 +1610,67 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int index2 = originalTriangleIndexes[polyNumber].indexes[2]; // decide where the original verts are - vert0 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert0+=index0; + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; - vert1 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert1+=index1; + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; - vert2 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert2+=index2; + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; // clear out the triangle verts to be - VectorClear( pTri[0] ); - VectorClear( pTri[1] ); - VectorClear( pTri[2] ); - int *piBoneReferences = (int*) ((byte*)originalSurf + originalSurf->ofsBoneReferences); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + int *piBoneReferences = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); -// mdxmWeight_t *w; + // mdxmWeight_t *w; // now go and transform just the points we need from the surface that was hit originally -// w = vert0->weights; + // w = vert0->weights; float fTotalWeight = 0.0f; - int iNumWeights = G2_GetVertWeights( vert0 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert0, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert0, k, fTotalWeight, iNumWeights ); + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); - pTri[0][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert0->vertCoords ) + bone.matrix[0][3] ); - pTri[0][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert0->vertCoords ) + bone.matrix[1][3] ); - pTri[0][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert0->vertCoords ) + bone.matrix[2][3] ); + pTri[0][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert0->vertCoords) + bone.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert0->vertCoords) + bone.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert0->vertCoords) + bone.matrix[2][3]); } -// w = vert1->weights; + // w = vert1->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert1 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert1, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert1, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); - pTri[1][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert1->vertCoords ) + bone.matrix[0][3] ); - pTri[1][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert1->vertCoords ) + bone.matrix[1][3] ); - pTri[1][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert1->vertCoords ) + bone.matrix[2][3] ); + pTri[1][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert1->vertCoords) + bone.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert1->vertCoords) + bone.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert1->vertCoords) + bone.matrix[2][3]); } -// w = vert2->weights; + // w = vert2->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert2 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert2, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert2, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); - pTri[2][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert2->vertCoords ) + bone.matrix[0][3] ); - pTri[2][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert2->vertCoords ) + bone.matrix[1][3] ); - pTri[2][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert2->vertCoords ) + bone.matrix[2][3] ); + pTri[2][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert2->vertCoords) + bone.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert2->vertCoords) + bone.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert2->vertCoords) + bone.matrix[2][3]); } - vec3_t normal; + vec3_t normal; vec3_t up; vec3_t right; vec3_t vec0, vec1; @@ -2066,75 +1710,70 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, // right is always straight - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector retMatrix.matrix[0][2] = right[0]; retMatrix.matrix[1][2] = right[1]; retMatrix.matrix[2][2] = right[2]; - } // no, we are looking at a normal model tag - else - { - // whip through and actually transform each vertex - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); - for ( j = 0; j < 3; j++ ) - { -// mdxmWeight_t *w; + else { + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); + for (j = 0; j < 3; j++) { + // mdxmWeight_t *w; - VectorClear( pTri[j] ); - // w = v->weights; + VectorClear(pTri[j]); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); - - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); - - pTri[j][0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - pTri[j][1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - pTri[j][2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); - } - - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; - } - - // clear out used arrays - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); - - // work out actual sides of the tag triangle - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j+1)%3][0] - pTri[j][0]; - sides[j][1] = pTri[(j+1)%3][1] - pTri[j][1]; - sides[j][2] = pTri[(j+1)%3][2] - pTri[j][2]; - } - - // do math trig to work out what the matrix will be from this triangle's translated position - VectorNormalize2( sides[iG2_TRISIDE_LONGEST], axes[0] ); - VectorNormalize2( sides[iG2_TRISIDE_SHORTEST], axes[1] ); - - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize2( axes[0], axes[0] ); - - CrossProduct( sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2] ); - VectorNormalize2( axes[2], axes[2] ); - - // set up location in world space of the origin point in out going matrix - retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; - - // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); + + pTri[j][0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); + } + + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } + + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); + + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } + + // do math trig to work out what the matrix will be from this triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + + // project shortest side so that it is exactly 90 degrees to the longer side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); + + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); + + // set up location in world space of the origin point in out going matrix + retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + + // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly retMatrix.matrix[0][0] = axes[1][0]; retMatrix.matrix[0][1] = axes[0][0]; retMatrix.matrix[0][2] = -axes[2][0]; @@ -2147,88 +1786,68 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, retMatrix.matrix[2][1] = axes[0][2]; retMatrix.matrix[2][2] = -axes[2][2]; } - } - -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - boltInfo_v &boltList=ghoul2.mBltlist; - assert(boltNum>=0&&boltNum<(int)boltList.size()); - if (boltList[boltNum].boneNumber>=0) - { - mdxaSkel_t *skel; + boltInfo_v &boltList = ghoul2.mBltlist; + assert(boltNum >= 0 && boltNum < (int)boltList.size()); + if (boltList[boltNum].boneNumber >= 0) { + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boltList[boltNum].boneNumber]); Multiply_3x4Matrix(&retMatrix, &boneCache.EvalUnsmooth(boltList[boltNum].boneNumber), &skel->BasePoseMat); - } - else if (boltList[boltNum].surfaceNumber>=0) - { - const surfaceInfo_t *surfInfo=0; + } else if (boltList[boltNum].surfaceNumber >= 0) { + const surfaceInfo_t *surfInfo = 0; { - for (size_t i=0;isurface<10000) - { - surface = (mdxmSurface_t *)G2_FindSurface(boneCache.mod,surfInfo->surface, 0); + if (!surface && surfInfo && surfInfo->surface < 10000) { + surface = (mdxmSurface_t *)G2_FindSurface(boneCache.mod, surfInfo->surface, 0); } - G2_ProcessSurfaceBolt2(boneCache,surface,boltNum,boltList,surfInfo,(model_t *)boneCache.mod,retMatrix); - } - else - { - // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix - retMatrix=identityMatrix; + G2_ProcessSurfaceBolt2(boneCache, surface, boltNum, boltList, surfInfo, (model_t *)boneCache.mod, retMatrix); + } else { + // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix + retMatrix = identityMatrix; } } - - -void G2API_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) -{ +void G2API_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin) { int j; - const skin_t *skin = R_GetSkinByHandle( renderSkin ); - //FIXME: using skin handles means we have to increase the numsurfs in a skin, but reading directly would cause file hits, we need another way to cache or just deal with the larger skin_t + const skin_t *skin = R_GetSkinByHandle(renderSkin); + // FIXME: using skin handles means we have to increase the numsurfs in a skin, but reading directly would cause file hits, we need another way to cache or + // just deal with the larger skin_t - if (skin) - { - ghlInfo->mSlist.clear(); //remove any overrides we had before. + if (skin) { + ghlInfo->mSlist.clear(); // remove any overrides we had before. ghlInfo->mMeshFrameNum = 0; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { + for (j = 0; j < skin->numSurfaces; j++) { uint32_t flags; int surfaceNum = G2_IsSurfaceLegal(ghlInfo->currentModel, skin->surfaces[j]->name, &flags); // the names have both been lowercased - if ( !(flags&G2SURFACEFLAG_OFF) && !strcmp( skin->surfaces[j]->shader->name , "*off") ) - { + if (!(flags & G2SURFACEFLAG_OFF) && !strcmp(skin->surfaces[j]->shader->name, "*off")) { G2_SetSurfaceOnOff(ghlInfo, skin->surfaces[j]->name, G2SURFACEFLAG_OFF); - } - else - { - //if ( strcmp( &skin->surfaces[j]->name[strlen(skin->surfaces[j]->name)-4],"_off") ) - if ( (surfaceNum != -1) && (!(flags&G2SURFACEFLAG_OFF)) ) //only turn on if it's not an "_off" surface + } else { + // if ( strcmp( &skin->surfaces[j]->name[strlen(skin->surfaces[j]->name)-4],"_off") ) + if ((surfaceNum != -1) && (!(flags & G2SURFACEFLAG_OFF))) // only turn on if it's not an "_off" surface { - //G2_SetSurfaceOnOff(ghlInfo, skin->surfaces[j]->name, 0); + // G2_SetSurfaceOnOff(ghlInfo, skin->surfaces[j]->name, 0); } } } @@ -2236,187 +1855,158 @@ void G2API_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) } // set up each surface ready for rendering in the back end -void RenderSurfaces(CRenderSurface &RS) -{ - int i; - const shader_t *shader = 0; - int offFlags = 0; +void RenderSurfaces(CRenderSurface &RS) { + int i; + const shader_t *shader = 0; + int offFlags = 0; #ifdef _G2_GORE - bool drawGore = true; + bool drawGore = true; #endif - assert(RS.currentModel); assert(RS.currentModel->mdxm); // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)RS.currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)RS.currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { - if ( RS.cust_shader ) - { + if (!offFlags) { + if (RS.cust_shader) { shader = RS.cust_shader; - } - else if ( RS.skin ) - { - int j; + } else if (RS.skin) { + int j; // match the surface name to something in the skin file - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); //tr.defaultShader; - for ( j = 0 ; j < RS.skin->numSurfaces ; j++ ) - { + shader = R_GetShaderByHandle(surfInfo->shaderIndex); // tr.defaultShader; + for (j = 0; j < RS.skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( RS.skin->surfaces[j]->name, surfInfo->name ) ) - { + if (!strcmp(RS.skin->surfaces[j]->name, surfInfo->name)) { shader = RS.skin->surfaces[j]->shader; break; } } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } else { + shader = R_GetShaderByHandle(surfInfo->shaderIndex); } // we will add shadows even if the main object isn't visible in the view // stencil shadows can't do personal models unless I polyhedron clip - //using z-fail now so can do personal models -rww - if ( /*!RS.personalModel - && */r_shadows->integer == 2 -// && RS.fogNum == 0 - && (RS.renderfx & RF_SHADOW_PLANE ) - && !(RS.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + // using z-fail now so can do personal models -rww + if (/*!RS.personalModel + && */ r_shadows->integer == 2 + // && RS.fogNum == 0 + && (RS.renderfx & RF_SHADOW_PLANE) && !(RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && + shader->sort == + SS_OPAQUE) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = AllocRS(); - if (surface->numVerts >= SHADER_MAX_VERTEXES/2) - { //we need numVerts*2 xyz slots free in tess to do shadow, if this surf is going to exceed that then let's try the lowest lod -rww - mdxmSurface_t *lowsurface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.currentModel->numLods-1); + if (surface->numVerts >= + SHADER_MAX_VERTEXES / + 2) { // we need numVerts*2 xyz slots free in tess to do shadow, if this surf is going to exceed that then let's try the lowest lod -rww + mdxmSurface_t *lowsurface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.currentModel->numLods - 1); newSurf->surfaceData = lowsurface; - } - else - { + } else { newSurf->surfaceData = surface; } newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, tr.shadowShader, 0, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, tr.shadowShader, 0, qfalse); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 -// && RS.fogNum == 0 - && (RS.renderfx & RF_SHADOW_PLANE ) - && !(RS.renderfx & ( RF_NOSHADOW ) ) - && shader->sort == SS_OPAQUE ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + if (r_shadows->integer == 3 + // && RS.fogNum == 0 + && (RS.renderfx & RF_SHADOW_PLANE) && !(RS.renderfx & (RF_NOSHADOW)) && + shader->sort == + SS_OPAQUE) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = AllocRS(); newSurf->surfaceData = surface; newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, tr.projectionShadowShader, 0, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, tr.projectionShadowShader, 0, qfalse); } // don't add third_person objects if not viewing through a portal - if ( !RS.personalModel ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + if (!RS.personalModel) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = AllocRS(); newSurf->surfaceData = surface; newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, shader, RS.fogNum, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, shader, RS.fogNum, qfalse); #ifdef _G2_GORE - if (RS.gore_set && drawGore) - { + if (RS.gore_set && drawGore) { int curTime = G2API_GetTime(tr.refdef.time); - std::pair::iterator,std::multimap::iterator> range= + std::pair::iterator, std::multimap::iterator> range = RS.gore_set->mGoreRecords.equal_range(RS.surfaceNum); - std::multimap::iterator k,kcur; - CRenderableSurface *last=newSurf; - for (k=range.first;k!=range.second;) - { - kcur=k; + std::multimap::iterator k, kcur; + CRenderableSurface *last = newSurf; + for (k = range.first; k != range.second;) { + kcur = k; ++k; - GoreTextureCoordinates *tex=FindGoreRecord((*kcur).second.mGoreTag); - if (!tex || // it is gone, lets get rid of it - (kcur->second.mDeleteTime && curTime>=kcur->second.mDeleteTime)) // out of time + GoreTextureCoordinates *tex = FindGoreRecord((*kcur).second.mGoreTag); + if (!tex || // it is gone, lets get rid of it + (kcur->second.mDeleteTime && curTime >= kcur->second.mDeleteTime)) // out of time { - if (tex) - { + if (tex) { (*tex).~GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } RS.gore_set->mGoreRecords.erase(kcur); - } - else if (tex->tex[RS.lod]) - { + } else if (tex->tex[RS.lod]) { CRenderableSurface *newSurf2 = AllocRS(); - *newSurf2=*newSurf; - newSurf2->goreChain=0; - newSurf2->alternateTex=tex->tex[RS.lod]; - newSurf2->scale=1.0f; - newSurf2->fade=1.0f; - newSurf2->impactTime=1.0f; // done with - int magicFactor42=500; // ms, impact time - if (curTime>(*kcur).second.mGoreGrowStartTime && curTime<(*kcur).second.mGoreGrowStartTime+magicFactor42) - { - newSurf2->impactTime=float(curTime-(*kcur).second.mGoreGrowStartTime)/float(magicFactor42); // linear + *newSurf2 = *newSurf; + newSurf2->goreChain = 0; + newSurf2->alternateTex = tex->tex[RS.lod]; + newSurf2->scale = 1.0f; + newSurf2->fade = 1.0f; + newSurf2->impactTime = 1.0f; // done with + int magicFactor42 = 500; // ms, impact time + if (curTime > (*kcur).second.mGoreGrowStartTime && curTime < (*kcur).second.mGoreGrowStartTime + magicFactor42) { + newSurf2->impactTime = float(curTime - (*kcur).second.mGoreGrowStartTime) / float(magicFactor42); // linear } - if (curTime<(*kcur).second.mGoreGrowEndTime) - { - newSurf2->scale=1.0f/((curTime-(*kcur).second.mGoreGrowStartTime)*(*kcur).second.mGoreGrowFactor + (*kcur).second.mGoreGrowOffset); - if (newSurf2->scale<1.0f) - { - newSurf2->scale=1.0f; + if (curTime < (*kcur).second.mGoreGrowEndTime) { + newSurf2->scale = + 1.0f / ((curTime - (*kcur).second.mGoreGrowStartTime) * (*kcur).second.mGoreGrowFactor + (*kcur).second.mGoreGrowOffset); + if (newSurf2->scale < 1.0f) { + newSurf2->scale = 1.0f; } } shader_t *gshader; - if ((*kcur).second.shader) - { - gshader=R_GetShaderByHandle((*kcur).second.shader); - } - else - { - gshader=R_GetShaderByHandle(goreShader); + if ((*kcur).second.shader) { + gshader = R_GetShaderByHandle((*kcur).second.shader); + } else { + gshader = R_GetShaderByHandle(goreShader); } // Set fade on surf. - //Only if we have a fade time set, and let us fade on rgb if we want -rww - if ((*kcur).second.mDeleteTime && (*kcur).second.mFadeTime) - { - if ((*kcur).second.mDeleteTime - curTime < (*kcur).second.mFadeTime) - { - newSurf2->fade=(float)((*kcur).second.mDeleteTime - curTime)/(*kcur).second.mFadeTime; - if ((*kcur).second.mFadeRGB) - { //RGB fades are scaled from 2.0f to 3.0f (simply to differentiate) + // Only if we have a fade time set, and let us fade on rgb if we want -rww + if ((*kcur).second.mDeleteTime && (*kcur).second.mFadeTime) { + if ((*kcur).second.mDeleteTime - curTime < (*kcur).second.mFadeTime) { + newSurf2->fade = (float)((*kcur).second.mDeleteTime - curTime) / (*kcur).second.mFadeTime; + if ((*kcur).second.mFadeRGB) { // RGB fades are scaled from 2.0f to 3.0f (simply to differentiate) newSurf2->fade += 2.0f; - if (newSurf2->fade < 2.01f) - { + if (newSurf2->fade < 2.01f) { newSurf2->fade = 2.01f; } } } } - last->goreChain=newSurf2; - last=newSurf2; - R_AddDrawSurf( (surfaceType_t *)newSurf2,gshader, RS.fogNum, qfalse ); + last->goreChain = newSurf2; + last = newSurf2; + R_AddDrawSurf((surfaceType_t *)newSurf2, gshader, RS.fogNum, qfalse); } } } @@ -2425,71 +2015,58 @@ void RenderSurfaces(CRenderSurface &RS) } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { RS.surfaceNum = surfInfo->childIndexes[i]; RenderSurfaces(RS); } } - // sort all the ghoul models in this list so if they go in reference order. This will ensure the bolt on's are attached to the right place // on the previous model, since it ensures the model being attached to is built and rendered first. // NOTE!! This assumes at least one model will NOT have a parent. If it does - we are screwed -static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int * const modelList, int * const modelCount) -{ - int startPoint, endPoint; - int i, boltTo, j; +static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int *const modelList, int *const modelCount) { + int startPoint, endPoint; + int i, boltTo, j; *modelCount = 0; // first walk all the possible ghoul2 models, and stuff the out array with those with no parents - for (i=0; i> MODEL_SHIFT) & MODEL_AND; // is it any of the models we just added to the list? - for (j=startPoint; jvalue); } @@ -2555,70 +2125,65 @@ static inline bool bInShadowRange(vec3_t location) R_AddGHOULSurfaces ============== */ -void R_AddGhoulSurfaces( trRefEntity_t *ent ) { - shader_t *cust_shader = 0; +void R_AddGhoulSurfaces(trRefEntity_t *ent) { + shader_t *cust_shader = 0; #ifdef _G2_GORE - shader_t *gore_shader = 0; + shader_t *gore_shader = 0; #endif - int fogNum = 0; - qboolean personalModel; - int cull; - int i, whichLod, j; - skin_t *skin; - int modelCount; - mdxaBone_t rootMatrix; + int fogNum = 0; + qboolean personalModel; + int cull; + int i, whichLod, j; + skin_t *skin; + int modelCount; + mdxaBone_t rootMatrix; // if we don't want ghoul2 models, then return - if (r_noGhoul2->integer) - { + if (r_noGhoul2->integer) { return; } - assert (ent->e.ghoul2); //entity is foo if it has a glm model handle but no ghoul2 pointer! - CGhoul2Info_v &ghoul2 = *ent->e.ghoul2; + assert(ent->e.ghoul2); // entity is foo if it has a glm model handle but no ghoul2 pointer! + CGhoul2Info_v &ghoul2 = *ent->e.ghoul2; - if (!G2_SetupModelPointers(ghoul2)) - { + if (!G2_SetupModelPointers(ghoul2)) { return; } - int currentTime=G2API_GetTime(tr.refdef.time); - + int currentTime = G2API_GetTime(tr.refdef.time); // cull the entire model if merged bounding box of both frames // is outside the view frustum. - cull = R_GCullModel (ent ); - if ( cull == CULL_OUT ) - { + cull = R_GCullModel(ent); + if (cull == CULL_OUT) { return; } - HackadelicOnClient=true; + HackadelicOnClient = true; // are any of these models setting a new origin? - RootMatrix(ghoul2,currentTime, ent->e.modelScale,rootMatrix); + RootMatrix(ghoul2, currentTime, ent->e.modelScale, rootMatrix); - // don't add third_person objects if not in a portal + // don't add third_person objects if not in a portal personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); int modelList[32]; - assert(ghoul2.size()<=31); - modelList[31]=548; + assert(ghoul2.size() <= 31); + modelList[31] = 548; // set up lighting now that we know we aren't culled - if ( !personalModel || r_shadows->integer > 1 ) { - R_SetupEntityLighting( &tr.refdef, ent ); + if (!personalModel || r_shadows->integer > 1) { + R_SetupEntityLighting(&tr.refdef, ent); } // see if we are in a fog volume - fogNum = R_GComputeFogNum( ent ); + fogNum = R_GComputeFogNum(ent); // sort the ghoul 2 models so bolt ons get bolted to the right model G2_Sort_Models(ghoul2, modelList, &modelCount); - assert(modelList[31]==548); + assert(modelList[31] == 548); #ifdef _G2_GORE - if (goreShader == -1) - { - goreShader=RE_RegisterShader("gfx/damage/burnmark1"); + if (goreShader == -1) { + goreShader = RE_RegisterShader("gfx/damage/burnmark1"); } #endif @@ -2626,87 +2191,70 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent ) { G2_GenerateWorldMatrix(ent->e.angles, ent->e.origin); // walk each possible model for this entity and try rendering it out - for (j=0; je.customShader) - { - cust_shader = R_GetShaderByHandle(ent->e.customShader ); - } - else - { + if (ent->e.customShader) { + cust_shader = R_GetShaderByHandle(ent->e.customShader); + } else { cust_shader = NULL; // figure out the custom skin thing - if (ent->e.customSkin) - { - skin = R_GetSkinByHandle(ent->e.customSkin ); - } - else if ( ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( ghoul2[i].mSkin ); + if (ent->e.customSkin) { + skin = R_GetSkinByHandle(ent->e.customSkin); + } else if (ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(ghoul2[i].mSkin); } } - if (j&&ghoul2[i].mModelBoltLink != -1) - { - int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (j && ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; - G2_GetBoltMatrixLow(ghoul2[boltMod],boltNum,ent->e.modelScale,bolt); - G2_TransformGhoulBones(ghoul2[i].mBlist,bolt, ghoul2[i],currentTime); + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, ent->e.modelScale, bolt); + G2_TransformGhoulBones(ghoul2[i].mBlist, bolt, ghoul2[i], currentTime); + } else { + G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i], currentTime); } - else - { - G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i],currentTime); - } - if ( ent->e.renderfx & RF_G2MINLOD ) - { - whichLod = G2_ComputeLOD( ent, ghoul2[i].currentModel, 10 ); - } else - { - whichLod = G2_ComputeLOD( ent, ghoul2[i].currentModel, ghoul2[i].mLodBias ); + if (ent->e.renderfx & RF_G2MINLOD) { + whichLod = G2_ComputeLOD(ent, ghoul2[i].currentModel, 10); + } else { + whichLod = G2_ComputeLOD(ent, ghoul2[i].currentModel, ghoul2[i].mLodBias); } - G2_FindOverrideSurface(-1,ghoul2[i].mSlist); //reset the quick surface override lookup; + G2_FindOverrideSurface(-1, ghoul2[i].mSlist); // reset the quick surface override lookup; #ifdef _G2_GORE - CGoreSet *gore=0; - if (ghoul2[i].mGoreSetTag) - { - gore=FindGoreSet(ghoul2[i].mGoreSetTag); + CGoreSet *gore = 0; + if (ghoul2[i].mGoreSetTag) { + gore = FindGoreSet(ghoul2[i].mGoreSetTag); if (!gore) // my gore is gone, so remove it { - ghoul2[i].mGoreSetTag=0; + ghoul2[i].mGoreSetTag = 0; } } - CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin,ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist, gore_shader, gore); + CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, + ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist, gore_shader, gore); #else - CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin,ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist); + CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, + ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist); #endif - if (!personalModel && (RS.renderfx & RF_SHADOW_PLANE) && !bInShadowRange(ent->e.origin)) - { + if (!personalModel && (RS.renderfx & RF_SHADOW_PLANE) && !bInShadowRange(ent->e.origin)) { RS.renderfx |= RF_NOSHADOW; } RenderSurfaces(RS); } } - HackadelicOnClient=false; + HackadelicOnClient = false; } -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) -{ +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum) { G2_SetupModelPointers(ghlInfo); // not sure if I still need this test, probably - if (ghlInfo->mSkelFrameNum!=frameNum|| - !ghlInfo->mBoneCache|| - ghlInfo->mBoneCache->mod!=ghlInfo->currentModel) - { - ghlInfo->mSkelFrameNum=frameNum; + if (ghlInfo->mSkelFrameNum != frameNum || !ghlInfo->mBoneCache || ghlInfo->mBoneCache->mod != ghlInfo->currentModel) { + ghlInfo->mSkelFrameNum = frameNum; return true; } return false; @@ -2717,47 +2265,38 @@ bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) G2_ConstructGhoulSkeleton - builds a complete skeleton for all ghoul models in a CGhoul2Info_v class - using LOD 0 ============== */ -void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool checkForNewOrigin,const vec3_t scale) -{ - int i, j; - int modelCount; - mdxaBone_t rootMatrix; +void G2_ConstructGhoulSkeleton(CGhoul2Info_v &ghoul2, const int frameNum, bool checkForNewOrigin, const vec3_t scale) { + int i, j; + int modelCount; + mdxaBone_t rootMatrix; int modelList[32]; - assert(ghoul2.size()<=31); - modelList[31]=548; + assert(ghoul2.size() <= 31); + modelList[31] = 548; - if (checkForNewOrigin) - { - RootMatrix(ghoul2,frameNum,scale,rootMatrix); - } - else - { + if (checkForNewOrigin) { + RootMatrix(ghoul2, frameNum, scale, rootMatrix); + } else { rootMatrix = identityMatrix; } G2_Sort_Models(ghoul2, modelList, &modelCount); - assert(modelList[31]==548); + assert(modelList[31] == 548); - for (j=0; j> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mValid) { + if (j && ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; - G2_GetBoltMatrixLow(ghoul2[boltMod],boltNum,scale,bolt); - G2_TransformGhoulBones(ghoul2[i].mBlist,bolt,ghoul2[i],frameNum,checkForNewOrigin); - } - else - { - G2_TransformGhoulBones(ghoul2[i].mBlist,rootMatrix,ghoul2[i],frameNum,checkForNewOrigin); + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, scale, bolt); + G2_TransformGhoulBones(ghoul2[i].mBlist, bolt, ghoul2[i], frameNum, checkForNewOrigin); + } else { + G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i], frameNum, checkForNewOrigin); } } } @@ -2768,25 +2307,23 @@ void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool ch RB_SurfaceGhoul ============== */ -void RB_SurfaceGhoul( CRenderableSurface *surf ) -{ +void RB_SurfaceGhoul(CRenderableSurface *surf) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_RB_SurfaceGhoul.Start(); #endif - int j, k; - int baseIndex, baseVertex; - int numVerts; - mdxmVertex_t *v; - int *triangles; - int indexes; - glIndex_t *tessIndexes; + int j, k; + int baseIndex, baseVertex; + int numVerts; + mdxmVertex_t *v; + int *triangles; + int indexes; + glIndex_t *tessIndexes; mdxmVertexTexCoord_t *pTexCoords; - int *piBoneReferences; + int *piBoneReferences; #ifdef _G2_GORE - if (surf->alternateTex) - { + if (surf->alternateTex) { // a gore surface ready to go. @@ -2800,95 +2337,83 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) sizeof(int)*newNumTris*3; // new indecies */ - int *data=(int *)surf->alternateTex; - numVerts=*data++; - indexes=(*data++); + int *data = (int *)surf->alternateTex; + numVerts = *data++; + indexes = (*data++); // first up, sanity check our numbers - RB_CheckOverflow(numVerts,indexes); - indexes*=3; + RB_CheckOverflow(numVerts, indexes); + indexes *= 3; - data+=numVerts; + data += numVerts; baseIndex = tess.numIndexes; baseVertex = tess.numVertexes; - memcpy(&tess.xyz[baseVertex][0],data,sizeof(float)*4*numVerts); - data+=4*numVerts; - memcpy(&tess.normal[baseVertex][0],data,sizeof(float)*4*numVerts); - data+=4*numVerts; - assert(numVerts>0); + memcpy(&tess.xyz[baseVertex][0], data, sizeof(float) * 4 * numVerts); + data += 4 * numVerts; + memcpy(&tess.normal[baseVertex][0], data, sizeof(float) * 4 * numVerts); + data += 4 * numVerts; + assert(numVerts > 0); - //float *texCoords = tess.texCoords[0][baseVertex]; + // float *texCoords = tess.texCoords[0][baseVertex]; float *texCoords = tess.texCoords[baseVertex][0]; int hack = baseVertex; - //rww - since the array is arranged as such we cannot increment - //the relative memory position to get where we want. Maybe this - //is why sof2 has the texCoords array reversed. In any case, I - //am currently too lazy to get around it. - //Or can you += array[.][x]+2? - if (surf->scale>1.0f) - { - for ( j = 0; j < numVerts; j++) - { - texCoords[0]=((*(float *)data)-0.5f)*surf->scale+0.5f; + // rww - since the array is arranged as such we cannot increment + // the relative memory position to get where we want. Maybe this + // is why sof2 has the texCoords array reversed. In any case, I + // am currently too lazy to get around it. + // Or can you += array[.][x]+2? + if (surf->scale > 1.0f) { + for (j = 0; j < numVerts; j++) { + texCoords[0] = ((*(float *)data) - 0.5f) * surf->scale + 0.5f; data++; - texCoords[1]=((*(float *)data)-0.5f)*surf->scale+0.5f; + texCoords[1] = ((*(float *)data) - 0.5f) * surf->scale + 0.5f; data++; - //texCoords+=2;// Size of gore (s,t). + // texCoords+=2;// Size of gore (s,t). hack++; texCoords = tess.texCoords[hack][0]; } - } - else - { - for (j=0;jfade) - { + // now check for fade overrides -rww + if (surf->fade) { static int lFade; static int j; - if (surf->fade<1.0) - { + if (surf->fade < 1.0) { tess.fading = true; - lFade = Q_ftol(254.4f*surf->fade); + lFade = Q_ftol(254.4f * surf->fade); - for (j=0;jfade > 2.0f && surf->fade < 3.0f) - { //hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww + } else if (surf->fade > 2.0f && surf->fade < 3.0f) { // hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww tess.fading = true; - lFade = Q_ftol(254.4f*(surf->fade-2.0f)); + lFade = Q_ftol(254.4f * (surf->fade - 2.0f)); - for (j=0;jsurfaceData; + mdxmSurface_t *surface = surf->surfaceData; CBoneCache *bones = surf->boneCache; // first up, sanity check our numbers - RB_CheckOverflow( surface->numVerts, surface->numTriangles ); + RB_CheckOverflow(surface->numVerts, surface->numTriangles); // // deform the vertexes by the lerped bones @@ -2911,7 +2436,7 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) // first up, sanity check our numbers baseVertex = tess.numVertexes; - triangles = (int *) ((byte *)surface + surface->ofsTriangles); + triangles = (int *)((byte *)surface + surface->ofsTriangles); baseIndex = tess.numIndexes; #if 0 indexes = surface->numTriangles * 3; @@ -2922,20 +2447,20 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) #else indexes = surface->numTriangles; //*3; //unrolled 3 times, don't multiply tessIndexes = &tess.indexes[baseIndex]; - for (j = 0 ; j < indexes ; j++) { + for (j = 0; j < indexes; j++) { *tessIndexes++ = baseVertex + *triangles++; *tessIndexes++ = baseVertex + *triangles++; *tessIndexes++ = baseVertex + *triangles++; } - tess.numIndexes += indexes*3; + tess.numIndexes += indexes * 3; #endif numVerts = surface->numVerts; - piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); baseVertex = tess.numVertexes; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // if (r_ghoul2fastnormals&&r_ghoul2fastnormals->integer==0) #if 0 @@ -2983,108 +2508,98 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) else { #endif - float fTotalWeight; - float fBoneWeight; - float t1; - float t2; - const mdxaBone_t *bone; - const mdxaBone_t *bone2; - for ( j = 0; j < numVerts; j++, baseVertex++,v++ ) - { + float fTotalWeight; + float fBoneWeight; + float t1; + float t2; + const mdxaBone_t *bone; + const mdxaBone_t *bone2; + for (j = 0; j < numVerts; j++, baseVertex++, v++) { #ifdef JK2_MODE - bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex( v, 0 )]); + bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex(v, 0)]); #else - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, 0 )]); + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, 0)]); #endif // JK2_MODE - int iNumWeights = G2_GetVertWeights( v ); - tess.normal[baseVertex][0] = DotProduct( bone->matrix[0], v->normal ); - tess.normal[baseVertex][1] = DotProduct( bone->matrix[1], v->normal ); - tess.normal[baseVertex][2] = DotProduct( bone->matrix[2], v->normal ); - - if (iNumWeights==1) - { - tess.xyz[baseVertex][0] = ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] = ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] = ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } - else - { - fBoneWeight = G2_GetVertBoneWeightNotSlow( v, 0); - if (iNumWeights==2) - { + int iNumWeights = G2_GetVertWeights(v); + tess.normal[baseVertex][0] = DotProduct(bone->matrix[0], v->normal); + tess.normal[baseVertex][1] = DotProduct(bone->matrix[1], v->normal); + tess.normal[baseVertex][2] = DotProduct(bone->matrix[2], v->normal); + + if (iNumWeights == 1) { + tess.xyz[baseVertex][0] = (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] = (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] = (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + } else { + fBoneWeight = G2_GetVertBoneWeightNotSlow(v, 0); + if (iNumWeights == 2) { #ifdef JK2_MODE - bone2 = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex( v, 1 )]); + bone2 = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex(v, 1)]); #else - bone2 = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, 1 )]); + bone2 = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, 1)]); #endif // JK2_MODE - /* - useless transposition - tess.xyz[baseVertex][0] = - v[0]*(w*(bone->matrix[0][0]-bone2->matrix[0][0])+bone2->matrix[0][0])+ - v[1]*(w*(bone->matrix[0][1]-bone2->matrix[0][1])+bone2->matrix[0][1])+ - v[2]*(w*(bone->matrix[0][2]-bone2->matrix[0][2])+bone2->matrix[0][2])+ - w*(bone->matrix[0][3]-bone2->matrix[0][3]) + bone2->matrix[0][3]; - */ - t1 = ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - t2 = ( DotProduct( bone2->matrix[0], v->vertCoords ) + bone2->matrix[0][3] ); - tess.xyz[baseVertex][0] = fBoneWeight * (t1-t2) + t2; - t1 = ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - t2 = ( DotProduct( bone2->matrix[1], v->vertCoords ) + bone2->matrix[1][3] ); - tess.xyz[baseVertex][1] = fBoneWeight * (t1-t2) + t2; - t1 = ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - t2 = ( DotProduct( bone2->matrix[2], v->vertCoords ) + bone2->matrix[2][3] ); - tess.xyz[baseVertex][2] = fBoneWeight * (t1-t2) + t2; - } - else - { - - tess.xyz[baseVertex][0] = fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] = fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] = fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - - fTotalWeight=fBoneWeight; - for (k=1; k < iNumWeights-1 ; k++) - { + /* + useless transposition + tess.xyz[baseVertex][0] = + v[0]*(w*(bone->matrix[0][0]-bone2->matrix[0][0])+bone2->matrix[0][0])+ + v[1]*(w*(bone->matrix[0][1]-bone2->matrix[0][1])+bone2->matrix[0][1])+ + v[2]*(w*(bone->matrix[0][2]-bone2->matrix[0][2])+bone2->matrix[0][2])+ + w*(bone->matrix[0][3]-bone2->matrix[0][3]) + bone2->matrix[0][3]; + */ + t1 = (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + t2 = (DotProduct(bone2->matrix[0], v->vertCoords) + bone2->matrix[0][3]); + tess.xyz[baseVertex][0] = fBoneWeight * (t1 - t2) + t2; + t1 = (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + t2 = (DotProduct(bone2->matrix[1], v->vertCoords) + bone2->matrix[1][3]); + tess.xyz[baseVertex][1] = fBoneWeight * (t1 - t2) + t2; + t1 = (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + t2 = (DotProduct(bone2->matrix[2], v->vertCoords) + bone2->matrix[2][3]); + tess.xyz[baseVertex][2] = fBoneWeight * (t1 - t2) + t2; + } else { + + tess.xyz[baseVertex][0] = fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] = fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] = fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + + fTotalWeight = fBoneWeight; + for (k = 1; k < iNumWeights - 1; k++) { #ifdef JK2_MODE - bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex( v, k )]); + bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex(v, k)]); #else - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, k )]); + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, k)]); #endif // JK2_MODE - fBoneWeight = G2_GetVertBoneWeightNotSlow( v, k); - fTotalWeight += fBoneWeight; + fBoneWeight = G2_GetVertBoneWeightNotSlow(v, k); + fTotalWeight += fBoneWeight; - tess.xyz[baseVertex][0] += fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] += fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] += fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } + tess.xyz[baseVertex][0] += fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] += fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] += fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + } #ifdef JK2_MODE - bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex( v, k )]); + bone = &bones->Eval(piBoneReferences[G2_GetVertBoneIndex(v, k)]); #else - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, k )]); + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, k)]); #endif // JK2_MODE - fBoneWeight = 1.0f-fTotalWeight; + fBoneWeight = 1.0f - fTotalWeight; - tess.xyz[baseVertex][0] += fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] += fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] += fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } + tess.xyz[baseVertex][0] += fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] += fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] += fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); } - - tess.texCoords[baseVertex][0][0] = pTexCoords[j].texCoords[0]; - tess.texCoords[baseVertex][0][1] = pTexCoords[j].texCoords[1]; } + + tess.texCoords[baseVertex][0][0] = pTexCoords[j].texCoords[0]; + tess.texCoords[baseVertex][0][1] = pTexCoords[j].texCoords[1]; + } #if 0 } #endif #ifdef _G2_GORE - while (surf->goreChain) - { - surf=(CRenderableSurface *)surf->goreChain; - if (surf->alternateTex) - { + while (surf->goreChain) { + surf = (CRenderableSurface *)surf->goreChain; + if (surf->alternateTex) { // get a gore surface ready to go. /* @@ -3097,30 +2612,25 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) sizeof(int)*newNumTris*3; // new indecies */ - int *data=(int *)surf->alternateTex; - int gnumVerts=*data++; + int *data = (int *)surf->alternateTex; + int gnumVerts = *data++; data++; - float *fdata=(float *)data; - fdata+=gnumVerts; - for (j=0;j=0&&data[j]= 0 && data[j] < numVerts); + memcpy(fdata, &tess.xyz[tess.numVertexes + data[j]][0], sizeof(float) * 3); + fdata += 4; } - for (j=0;j=0&&data[j]= 0 && data[j] < numVerts); + memcpy(fdata, &tess.normal[tess.numVertexes + data[j]][0], sizeof(float) * 3); + fdata += 4; } - } - else - { + } else { assert(0); } - } // NOTE: This is required because a ghoul model might need to be rendered twice a frame (don't cringe, @@ -3149,404 +2659,401 @@ Complete list of all 72 bones: */ int OldToNewRemapTable[72] = { -0,// Bone 0: "model_root": Parent: "" (index -1) -1,// Bone 1: "pelvis": Parent: "model_root" (index 0) -2,// Bone 2: "Motion": Parent: "pelvis" (index 1) -3,// Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) -4,// Bone 4: "lfemurX": Parent: "pelvis" (index 1) -5,// Bone 5: "ltibia": Parent: "pelvis" (index 1) -6,// Bone 6: "ltalus": Parent: "pelvis" (index 1) -6,// Bone 7: "ltarsal": Parent: "pelvis" (index 1) -7,// Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) -8,// Bone 9: "rfemurX": Parent: "pelvis" (index 1) -9,// Bone10: "rtibia": Parent: "pelvis" (index 1) -10,// Bone11: "rtalus": Parent: "pelvis" (index 1) -10,// Bone12: "rtarsal": Parent: "pelvis" (index 1) -11,// Bone13: "lower_lumbar": Parent: "pelvis" (index 1) -12,// Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) -13,// Bone15: "thoracic": Parent: "upper_lumbar" (index 14) -14,// Bone16: "cervical": Parent: "thoracic" (index 15) -15,// Bone17: "cranium": Parent: "cervical" (index 16) -16,// Bone18: "ceyebrow": Parent: "face_always_" (index 71) -17,// Bone19: "jaw": Parent: "face_always_" (index 71) -18,// Bone20: "lblip2": Parent: "face_always_" (index 71) -19,// Bone21: "leye": Parent: "face_always_" (index 71) -20,// Bone22: "rblip2": Parent: "face_always_" (index 71) -21,// Bone23: "ltlip2": Parent: "face_always_" (index 71) -22,// Bone24: "rtlip2": Parent: "face_always_" (index 71) -23,// Bone25: "reye": Parent: "face_always_" (index 71) -24,// Bone26: "rclavical": Parent: "thoracic" (index 15) -25,// Bone27: "rhumerus": Parent: "thoracic" (index 15) -26,// Bone28: "rhumerusX": Parent: "thoracic" (index 15) -27,// Bone29: "rradius": Parent: "thoracic" (index 15) -28,// Bone30: "rradiusX": Parent: "thoracic" (index 15) -29,// Bone31: "rhand": Parent: "thoracic" (index 15) -29,// Bone32: "mc7": Parent: "thoracic" (index 15) -34,// Bone33: "r_d5_j1": Parent: "thoracic" (index 15) -35,// Bone34: "r_d5_j2": Parent: "thoracic" (index 15) -35,// Bone35: "r_d5_j3": Parent: "thoracic" (index 15) -30,// Bone36: "r_d1_j1": Parent: "thoracic" (index 15) -31,// Bone37: "r_d1_j2": Parent: "thoracic" (index 15) -31,// Bone38: "r_d1_j3": Parent: "thoracic" (index 15) -32,// Bone39: "r_d2_j1": Parent: "thoracic" (index 15) -33,// Bone40: "r_d2_j2": Parent: "thoracic" (index 15) -33,// Bone41: "r_d2_j3": Parent: "thoracic" (index 15) -32,// Bone42: "r_d3_j1": Parent: "thoracic" (index 15) -33,// Bone43: "r_d3_j2": Parent: "thoracic" (index 15) -33,// Bone44: "r_d3_j3": Parent: "thoracic" (index 15) -34,// Bone45: "r_d4_j1": Parent: "thoracic" (index 15) -35,// Bone46: "r_d4_j2": Parent: "thoracic" (index 15) -35,// Bone47: "r_d4_j3": Parent: "thoracic" (index 15) -36,// Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) -37,// Bone49: "lclavical": Parent: "thoracic" (index 15) -38,// Bone50: "lhumerus": Parent: "thoracic" (index 15) -39,// Bone51: "lhumerusX": Parent: "thoracic" (index 15) -40,// Bone52: "lradius": Parent: "thoracic" (index 15) -41,// Bone53: "lradiusX": Parent: "thoracic" (index 15) -42,// Bone54: "lhand": Parent: "thoracic" (index 15) -42,// Bone55: "mc5": Parent: "thoracic" (index 15) -43,// Bone56: "l_d5_j1": Parent: "thoracic" (index 15) -44,// Bone57: "l_d5_j2": Parent: "thoracic" (index 15) -44,// Bone58: "l_d5_j3": Parent: "thoracic" (index 15) -43,// Bone59: "l_d4_j1": Parent: "thoracic" (index 15) -44,// Bone60: "l_d4_j2": Parent: "thoracic" (index 15) -44,// Bone61: "l_d4_j3": Parent: "thoracic" (index 15) -45,// Bone62: "l_d3_j1": Parent: "thoracic" (index 15) -46,// Bone63: "l_d3_j2": Parent: "thoracic" (index 15) -46,// Bone64: "l_d3_j3": Parent: "thoracic" (index 15) -45,// Bone65: "l_d2_j1": Parent: "thoracic" (index 15) -46,// Bone66: "l_d2_j2": Parent: "thoracic" (index 15) -46,// Bone67: "l_d2_j3": Parent: "thoracic" (index 15) -47,// Bone68: "l_d1_j1": Parent: "thoracic" (index 15) -48,// Bone69: "l_d1_j2": Parent: "thoracic" (index 15) -48,// Bone70: "l_d1_j3": Parent: "thoracic" (index 15) -52// Bone71: "face_always_": Parent: "cranium" (index 17) + 0, // Bone 0: "model_root": Parent: "" (index -1) + 1, // Bone 1: "pelvis": Parent: "model_root" (index 0) + 2, // Bone 2: "Motion": Parent: "pelvis" (index 1) + 3, // Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) + 4, // Bone 4: "lfemurX": Parent: "pelvis" (index 1) + 5, // Bone 5: "ltibia": Parent: "pelvis" (index 1) + 6, // Bone 6: "ltalus": Parent: "pelvis" (index 1) + 6, // Bone 7: "ltarsal": Parent: "pelvis" (index 1) + 7, // Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) + 8, // Bone 9: "rfemurX": Parent: "pelvis" (index 1) + 9, // Bone10: "rtibia": Parent: "pelvis" (index 1) + 10, // Bone11: "rtalus": Parent: "pelvis" (index 1) + 10, // Bone12: "rtarsal": Parent: "pelvis" (index 1) + 11, // Bone13: "lower_lumbar": Parent: "pelvis" (index 1) + 12, // Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) + 13, // Bone15: "thoracic": Parent: "upper_lumbar" (index 14) + 14, // Bone16: "cervical": Parent: "thoracic" (index 15) + 15, // Bone17: "cranium": Parent: "cervical" (index 16) + 16, // Bone18: "ceyebrow": Parent: "face_always_" (index 71) + 17, // Bone19: "jaw": Parent: "face_always_" (index 71) + 18, // Bone20: "lblip2": Parent: "face_always_" (index 71) + 19, // Bone21: "leye": Parent: "face_always_" (index 71) + 20, // Bone22: "rblip2": Parent: "face_always_" (index 71) + 21, // Bone23: "ltlip2": Parent: "face_always_" (index 71) + 22, // Bone24: "rtlip2": Parent: "face_always_" (index 71) + 23, // Bone25: "reye": Parent: "face_always_" (index 71) + 24, // Bone26: "rclavical": Parent: "thoracic" (index 15) + 25, // Bone27: "rhumerus": Parent: "thoracic" (index 15) + 26, // Bone28: "rhumerusX": Parent: "thoracic" (index 15) + 27, // Bone29: "rradius": Parent: "thoracic" (index 15) + 28, // Bone30: "rradiusX": Parent: "thoracic" (index 15) + 29, // Bone31: "rhand": Parent: "thoracic" (index 15) + 29, // Bone32: "mc7": Parent: "thoracic" (index 15) + 34, // Bone33: "r_d5_j1": Parent: "thoracic" (index 15) + 35, // Bone34: "r_d5_j2": Parent: "thoracic" (index 15) + 35, // Bone35: "r_d5_j3": Parent: "thoracic" (index 15) + 30, // Bone36: "r_d1_j1": Parent: "thoracic" (index 15) + 31, // Bone37: "r_d1_j2": Parent: "thoracic" (index 15) + 31, // Bone38: "r_d1_j3": Parent: "thoracic" (index 15) + 32, // Bone39: "r_d2_j1": Parent: "thoracic" (index 15) + 33, // Bone40: "r_d2_j2": Parent: "thoracic" (index 15) + 33, // Bone41: "r_d2_j3": Parent: "thoracic" (index 15) + 32, // Bone42: "r_d3_j1": Parent: "thoracic" (index 15) + 33, // Bone43: "r_d3_j2": Parent: "thoracic" (index 15) + 33, // Bone44: "r_d3_j3": Parent: "thoracic" (index 15) + 34, // Bone45: "r_d4_j1": Parent: "thoracic" (index 15) + 35, // Bone46: "r_d4_j2": Parent: "thoracic" (index 15) + 35, // Bone47: "r_d4_j3": Parent: "thoracic" (index 15) + 36, // Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) + 37, // Bone49: "lclavical": Parent: "thoracic" (index 15) + 38, // Bone50: "lhumerus": Parent: "thoracic" (index 15) + 39, // Bone51: "lhumerusX": Parent: "thoracic" (index 15) + 40, // Bone52: "lradius": Parent: "thoracic" (index 15) + 41, // Bone53: "lradiusX": Parent: "thoracic" (index 15) + 42, // Bone54: "lhand": Parent: "thoracic" (index 15) + 42, // Bone55: "mc5": Parent: "thoracic" (index 15) + 43, // Bone56: "l_d5_j1": Parent: "thoracic" (index 15) + 44, // Bone57: "l_d5_j2": Parent: "thoracic" (index 15) + 44, // Bone58: "l_d5_j3": Parent: "thoracic" (index 15) + 43, // Bone59: "l_d4_j1": Parent: "thoracic" (index 15) + 44, // Bone60: "l_d4_j2": Parent: "thoracic" (index 15) + 44, // Bone61: "l_d4_j3": Parent: "thoracic" (index 15) + 45, // Bone62: "l_d3_j1": Parent: "thoracic" (index 15) + 46, // Bone63: "l_d3_j2": Parent: "thoracic" (index 15) + 46, // Bone64: "l_d3_j3": Parent: "thoracic" (index 15) + 45, // Bone65: "l_d2_j1": Parent: "thoracic" (index 15) + 46, // Bone66: "l_d2_j2": Parent: "thoracic" (index 15) + 46, // Bone67: "l_d2_j3": Parent: "thoracic" (index 15) + 47, // Bone68: "l_d1_j1": Parent: "thoracic" (index 15) + 48, // Bone69: "l_d1_j2": Parent: "thoracic" (index 15) + 48, // Bone70: "l_d1_j3": Parent: "thoracic" (index 15) + 52 // Bone71: "face_always_": Parent: "cranium" (index 17) }; - /* Bone 0: "model_root": - Parent: "" (index -1) - #Kids: 1 - Child 0: (index 1), name "pelvis" + Parent: "" (index -1) + #Kids: 1 + Child 0: (index 1), name "pelvis" Bone 1: "pelvis": - Parent: "model_root" (index 0) - #Kids: 4 - Child 0: (index 2), name "Motion" - Child 1: (index 3), name "lfemurYZ" - Child 2: (index 7), name "rfemurYZ" - Child 3: (index 11), name "lower_lumbar" + Parent: "model_root" (index 0) + #Kids: 4 + Child 0: (index 2), name "Motion" + Child 1: (index 3), name "lfemurYZ" + Child 2: (index 7), name "rfemurYZ" + Child 3: (index 11), name "lower_lumbar" Bone 2: "Motion": - Parent: "pelvis" (index 1) - #Kids: 0 + Parent: "pelvis" (index 1) + #Kids: 0 Bone 3: "lfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 4), name "lfemurX" - Child 1: (index 5), name "ltibia" - Child 2: (index 49), name "ltail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 4), name "lfemurX" + Child 1: (index 5), name "ltibia" + Child 2: (index 49), name "ltail" Bone 4: "lfemurX": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 5: "ltibia": - Parent: "lfemurYZ" (index 3) - #Kids: 1 - Child 0: (index 6), name "ltalus" + Parent: "lfemurYZ" (index 3) + #Kids: 1 + Child 0: (index 6), name "ltalus" Bone 6: "ltalus": - Parent: "ltibia" (index 5) - #Kids: 0 + Parent: "ltibia" (index 5) + #Kids: 0 Bone 7: "rfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 8), name "rfemurX" - Child 1: (index 9), name "rtibia" - Child 2: (index 50), name "rtail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 8), name "rfemurX" + Child 1: (index 9), name "rtibia" + Child 2: (index 50), name "rtail" Bone 8: "rfemurX": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 9: "rtibia": - Parent: "rfemurYZ" (index 7) - #Kids: 1 - Child 0: (index 10), name "rtalus" + Parent: "rfemurYZ" (index 7) + #Kids: 1 + Child 0: (index 10), name "rtalus" Bone 10: "rtalus": - Parent: "rtibia" (index 9) - #Kids: 0 + Parent: "rtibia" (index 9) + #Kids: 0 Bone 11: "lower_lumbar": - Parent: "pelvis" (index 1) - #Kids: 1 - Child 0: (index 12), name "upper_lumbar" + Parent: "pelvis" (index 1) + #Kids: 1 + Child 0: (index 12), name "upper_lumbar" Bone 12: "upper_lumbar": - Parent: "lower_lumbar" (index 11) - #Kids: 1 - Child 0: (index 13), name "thoracic" + Parent: "lower_lumbar" (index 11) + #Kids: 1 + Child 0: (index 13), name "thoracic" Bone 13: "thoracic": - Parent: "upper_lumbar" (index 12) - #Kids: 5 - Child 0: (index 14), name "cervical" - Child 1: (index 24), name "rclavical" - Child 2: (index 25), name "rhumerus" - Child 3: (index 37), name "lclavical" - Child 4: (index 38), name "lhumerus" + Parent: "upper_lumbar" (index 12) + #Kids: 5 + Child 0: (index 14), name "cervical" + Child 1: (index 24), name "rclavical" + Child 2: (index 25), name "rhumerus" + Child 3: (index 37), name "lclavical" + Child 4: (index 38), name "lhumerus" Bone 14: "cervical": - Parent: "thoracic" (index 13) - #Kids: 1 - Child 0: (index 15), name "cranium" + Parent: "thoracic" (index 13) + #Kids: 1 + Child 0: (index 15), name "cranium" Bone 15: "cranium": - Parent: "cervical" (index 14) - #Kids: 1 - Child 0: (index 52), name "face_always_" + Parent: "cervical" (index 14) + #Kids: 1 + Child 0: (index 52), name "face_always_" Bone 16: "ceyebrow": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 17: "jaw": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 18: "lblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 19: "leye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 20: "rblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 21: "ltlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 22: "rtlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 23: "reye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 24: "rclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 25: "rhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 26), name "rhumerusX" - Child 1: (index 27), name "rradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 26), name "rhumerusX" + Child 1: (index 27), name "rradius" Bone 26: "rhumerusX": - Parent: "rhumerus" (index 25) - #Kids: 0 + Parent: "rhumerus" (index 25) + #Kids: 0 Bone 27: "rradius": - Parent: "rhumerus" (index 25) - #Kids: 9 - Child 0: (index 28), name "rradiusX" - Child 1: (index 29), name "rhand" - Child 2: (index 30), name "r_d1_j1" - Child 3: (index 31), name "r_d1_j2" - Child 4: (index 32), name "r_d2_j1" - Child 5: (index 33), name "r_d2_j2" - Child 6: (index 34), name "r_d4_j1" - Child 7: (index 35), name "r_d4_j2" - Child 8: (index 36), name "rhang_tag_bone" + Parent: "rhumerus" (index 25) + #Kids: 9 + Child 0: (index 28), name "rradiusX" + Child 1: (index 29), name "rhand" + Child 2: (index 30), name "r_d1_j1" + Child 3: (index 31), name "r_d1_j2" + Child 4: (index 32), name "r_d2_j1" + Child 5: (index 33), name "r_d2_j2" + Child 6: (index 34), name "r_d4_j1" + Child 7: (index 35), name "r_d4_j2" + Child 8: (index 36), name "rhang_tag_bone" Bone 28: "rradiusX": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 29: "rhand": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 30: "r_d1_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 31: "r_d1_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 32: "r_d2_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 33: "r_d2_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 34: "r_d4_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 35: "r_d4_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 36: "rhang_tag_bone": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 37: "lclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 38: "lhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 39), name "lhumerusX" - Child 1: (index 40), name "lradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 39), name "lhumerusX" + Child 1: (index 40), name "lradius" Bone 39: "lhumerusX": - Parent: "lhumerus" (index 38) - #Kids: 0 + Parent: "lhumerus" (index 38) + #Kids: 0 Bone 40: "lradius": - Parent: "lhumerus" (index 38) - #Kids: 9 - Child 0: (index 41), name "lradiusX" - Child 1: (index 42), name "lhand" - Child 2: (index 43), name "l_d4_j1" - Child 3: (index 44), name "l_d4_j2" - Child 4: (index 45), name "l_d2_j1" - Child 5: (index 46), name "l_d2_j2" - Child 6: (index 47), name "l_d1_j1" - Child 7: (index 48), name "l_d1_j2" - Child 8: (index 51), name "lhang_tag_bone" + Parent: "lhumerus" (index 38) + #Kids: 9 + Child 0: (index 41), name "lradiusX" + Child 1: (index 42), name "lhand" + Child 2: (index 43), name "l_d4_j1" + Child 3: (index 44), name "l_d4_j2" + Child 4: (index 45), name "l_d2_j1" + Child 5: (index 46), name "l_d2_j2" + Child 6: (index 47), name "l_d1_j1" + Child 7: (index 48), name "l_d1_j2" + Child 8: (index 51), name "lhang_tag_bone" Bone 41: "lradiusX": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 42: "lhand": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 43: "l_d4_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 44: "l_d4_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 45: "l_d2_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 46: "l_d2_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 47: "l_d1_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 48: "l_d1_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 49: "ltail": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 50: "rtail": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 51: "lhang_tag_bone": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 52: "face_always_": - Parent: "cranium" (index 15) - #Kids: 8 - Child 0: (index 16), name "ceyebrow" - Child 1: (index 17), name "jaw" - Child 2: (index 18), name "lblip2" - Child 3: (index 19), name "leye" - Child 4: (index 20), name "rblip2" - Child 5: (index 21), name "ltlip2" - Child 6: (index 22), name "rtlip2" - Child 7: (index 23), name "reye" + Parent: "cranium" (index 15) + #Kids: 8 + Child 0: (index 16), name "ceyebrow" + Child 1: (index 17), name "jaw" + Child 2: (index 18), name "lblip2" + Child 3: (index 19), name "leye" + Child 4: (index 20), name "rblip2" + Child 5: (index 21), name "ltlip2" + Child 6: (index 22), name "rtlip2" + Child 7: (index 23), name "reye" */ -qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i, l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - shader_t *sh; - mdxmSurfHierarchy_t *surfInfo; +qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + shader_t *sh; + mdxmSurfHierarchy_t *surfInfo; #ifdef Q3_BIG_ENDIAN - int k; - mdxmTriangle_t *tri; - mdxmVertex_t *v; - int *boneRef; - mdxmLODSurfOffset_t *indexes; - mdxmVertexTexCoord_t *pTexCoords; - mdxmHierarchyOffsets_t *surfIndexes; + int k; + mdxmTriangle_t *tri; + mdxmVertex_t *v; + int *boneRef; + mdxmLODSurfOffset_t *indexes; + mdxmVertexTexCoord_t *pTexCoords; + mdxmHierarchyOffsets_t *surfIndexes; #endif - pinmodel= (mdxmHeader_t *)buffer; + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXM_VERSION) { #ifdef _DEBUG - Com_Error( ERR_DROP, "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); + Com_Error(ERR_DROP, "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); #else - ri.Printf( PRINT_WARNING, "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); + ri.Printf(PRINT_WARNING, "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); #endif return qfalse; } - mod->type = MOD_MDXM; + mod->type = MOD_MDXM; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxm = mod->mdxm = (mdxmHeader_t*) //R_Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mdxm = mod->mdxm = (mdxmHeader_t *) // R_Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an FS_Freefile since // we've hijacked that memory block... @@ -3554,8 +3061,8 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -3568,125 +3075,108 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean } // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterModel(va ("%s.gla",mdxm->animName)); - - char animGLAName[MAX_QPATH]; - char *strippedName; - char *slash = NULL; - const char*mapname = sv_mapname->string; - - if (strcmp(mapname,"nomap") ) - { - if (strrchr(mapname,'/') ) //maps in subfolders use the root name, ( presuming only one level deep!) + mdxm->animIndex = RE_RegisterModel(va("%s.gla", mdxm->animName)); + + char animGLAName[MAX_QPATH]; + char *strippedName; + char *slash = NULL; + const char *mapname = sv_mapname->string; + + if (strcmp(mapname, "nomap")) { + if (strrchr(mapname, '/')) // maps in subfolders use the root name, ( presuming only one level deep!) { - mapname = strrchr(mapname,'/')+1; + mapname = strrchr(mapname, '/') + 1; } - //stripped name of GLA for this model + // stripped name of GLA for this model Q_strncpyz(animGLAName, mdxm->animName, sizeof(animGLAName)); slash = strrchr(animGLAName, '/'); - if (slash) - { + if (slash) { *slash = 0; } strippedName = COM_SkipPath(animGLAName); - if (VALIDSTRING(strippedName)) - { + if (VALIDSTRING(strippedName)) { RE_RegisterModel(va("models/players/%s_%s/%s_%s.gla", strippedName, mapname, strippedName, mapname)); } - } + } #ifndef JK2_MODE bool isAnOldModelFile = false; - if (mdxm->numBones == 72 && strstr(mdxm->animName,"_humanoid") ) - { + if (mdxm->numBones == 72 && strstr(mdxm->animName, "_humanoid")) { isAnOldModelFile = true; } #endif - if (!mdxm->animIndex) - { - ri.Printf( PRINT_WARNING, "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); + if (!mdxm->animIndex) { + ri.Printf(PRINT_WARNING, "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); return qfalse; } #ifndef JK2_MODE - else - { - assert (tr.models[mdxm->animIndex]->mdxa->numBones == mdxm->numBones); - if (tr.models[mdxm->animIndex]->mdxa->numBones != mdxm->numBones) - { - if ( isAnOldModelFile ) - { - ri.Printf( PRINT_WARNING, "R_LoadMDXM: converting jk2 model %s\n", mod_name); - } - else - { + else { + assert(tr.models[mdxm->animIndex]->mdxa->numBones == mdxm->numBones); + if (tr.models[mdxm->animIndex]->mdxa->numBones != mdxm->numBones) { + if (isAnOldModelFile) { + ri.Printf(PRINT_WARNING, "R_LoadMDXM: converting jk2 model %s\n", mod_name); + } else { #ifdef _DEBUG - Com_Error( ERR_DROP, "R_LoadMDXM: %s has different bones than anim (%i != %i)\n", mod_name, mdxm->numBones, tr.models[mdxm->animIndex]->mdxa->numBones); + Com_Error(ERR_DROP, "R_LoadMDXM: %s has different bones than anim (%i != %i)\n", mod_name, mdxm->numBones, + tr.models[mdxm->animIndex]->mdxa->numBones); #else - ri.Printf( PRINT_WARNING, "R_LoadMDXM: %s has different bones than anim (%i != %i)\n", mod_name, mdxm->numBones, tr.models[mdxm->animIndex]->mdxa->numBones); + ri.Printf(PRINT_WARNING, "R_LoadMDXM: %s has different bones than anim (%i != %i)\n", mod_name, mdxm->numBones, + tr.models[mdxm->animIndex]->mdxa->numBones); #endif } - if ( !isAnOldModelFile ) - {//hmm, load up the old JK2 ones anyway? + if (!isAnOldModelFile) { // hmm, load up the old JK2 ones anyway? return qfalse; } } } #endif - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); #ifdef Q3_BIG_ENDIAN surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); #endif - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->flags); LL(surfInfo->numChildren); LL(surfInfo->parentIndex); #ifndef JK2_MODE - Q_strlwr(surfInfo->name); //just in case - if ( !strcmp( &surfInfo->name[strlen(surfInfo->name)-4],"_off") ) - { - surfInfo->name[strlen(surfInfo->name)-4]=0; //remove "_off" from name + Q_strlwr(surfInfo->name); // just in case + if (!strcmp(&surfInfo->name[strlen(surfInfo->name) - 4], "_off")) { + surfInfo->name[strlen(surfInfo->name) - 4] = 0; // remove "_off" from name } #endif - if ( surfInfo->shader[0] == '[' ) - { - surfInfo->shader[0] = 0; //kill the stupid [nomaterial] since carcass doesn't + if (surfInfo->shader[0] == '[') { + surfInfo->shader[0] = 0; // kill the stupid [nomaterial] since carcass doesn't } // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } // get the shader name - sh = R_FindShader( surfInfo->shader, lightmapsNone, stylesDefault, qtrue ); + sh = R_FindShader(surfInfo->shader, lightmapsNone, stylesDefault, qtrue); // insert it in the surface list - if( !sh ) - { - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); + if (!sh) { + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); continue; } - if ( !sh->defaultShader ) - { + if (!sh->defaultShader) { surfInfo->shaderIndex = sh->index; } - if (surfInfo->shaderIndex) - { + if (surfInfo->shaderIndex) { RE_RegisterModels_StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); } @@ -3697,20 +3187,18 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean #endif // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->thisSurfaceIndex); LL(surf->ofsHeader); LL(surf->numVerts); @@ -3723,13 +3211,11 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean triCount += surf->numTriangles; - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", - mod_name, SHADER_MAX_VERTEXES, surf->numVerts ); + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", - mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles ); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } // change to surface identifier @@ -3742,28 +3228,24 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean LL(indexes->offsets[surf->thisSurfaceIndex]); // do all the bone reference data - boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { - LL(boneRef[j]); + boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { + LL(boneRef[j]); } - // swap all the triangles - tri = (mdxmTriangle_t *) ( (byte *)surf + surf->ofsTriangles ); - for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) - { + tri = (mdxmTriangle_t *)((byte *)surf + surf->ofsTriangles); + for (j = 0; j < surf->numTriangles; j++, tri++) { LL(tri->indexes[0]); LL(tri->indexes[1]); LL(tri->indexes[2]); } // swap all the vertexes - v = (mdxmVertex_t *) ( (byte *)surf + surf->ofsVerts ); - pTexCoords = (mdxmVertexTexCoord_t *) &v[surf->numVerts]; + v = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); + pTexCoords = (mdxmVertexTexCoord_t *)&v[surf->numVerts]; - for ( j = 0 ; j < surf->numVerts ; j++ ) - { + for (j = 0; j < surf->numVerts; j++) { LF(v->normal[0]); LF(v->normal[1]); LF(v->normal[2]); @@ -3782,28 +3264,23 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean #endif #ifndef JK2_MODE - if (isAnOldModelFile) - { - int *boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { + if (isAnOldModelFile) { + int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { assert(boneRef[j] >= 0 && boneRef[j] < 72); - if (boneRef[j] >= 0 && boneRef[j] < 72) - { - boneRef[j]=OldToNewRemapTable[boneRef[j]]; - } - else - { - boneRef[j]=0; + if (boneRef[j] >= 0 && boneRef[j] < 72) { + boneRef[j] = OldToNewRemapTable[boneRef[j]]; + } else { + boneRef[j] = 0; } } } #endif // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; @@ -3814,53 +3291,50 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean R_LoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; #ifdef Q3_BIG_ENDIAN - int j, k, i; - mdxaSkel_t *boneInfo; - mdxaSkelOffsets_t *offsets; - int maxBoneIndex = 0; - mdxaCompQuatBone_t *pCompBonePool; - unsigned short *pwIn; - mdxaIndex_t *pIndex; - int tmp; + int j, k, i; + mdxaSkel_t *boneInfo; + mdxaSkelOffsets_t *offsets; + int maxBoneIndex = 0; + mdxaCompQuatBone_t *pCompBonePool; + unsigned short *pwIn; + mdxaIndex_t *pIndex; + int tmp; #endif - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXA_VERSION) { - ri.Printf( PRINT_WARNING, "R_LoadMDXA: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXA_VERSION); + ri.Printf(PRINT_WARNING, "R_LoadMDXA: %s has wrong version (%i should be %i)\n", mod_name, version, MDXA_VERSION); return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxa = mod->mdxa = (mdxaHeader_t*) //R_Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = mod->mdxa = (mdxaHeader_t *) // R_Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an FS_Freefile since // we've hijacked that memory block... @@ -3868,12 +3342,12 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); -// memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxa == buffer); + // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing LL(mdxa->ident); LL(mdxa->version); - //LF(mdxa->fScale); + // LF(mdxa->fScale); LL(mdxa->numFrames); LL(mdxa->ofsFrames); LL(mdxa->numBones); @@ -3882,37 +3356,32 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean LL(mdxa->ofsEnd); } - if ( mdxa->numFrames < 1 ) { - ri.Printf( PRINT_WARNING, "R_LoadMDXA: %s has no frames\n", mod_name ); + if (mdxa->numFrames < 1) { + ri.Printf(PRINT_WARNING, "R_LoadMDXA: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } #ifdef Q3_BIG_ENDIAN // swap the bone info offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for ( i = 0; i < mdxa->numBones ; i++ ) - { + for (i = 0; i < mdxa->numBones; i++) { LL(offsets->offsets[i]); - boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); LL(boneInfo->flags); LL(boneInfo->parent); - for ( j = 0; j < 3; j++ ) - { - for ( k = 0; k < 4; k++) - { + for (j = 0; j < 3; j++) { + for (k = 0; k < 4; k++) { LF(boneInfo->BasePoseMat.matrix[j][k]); LF(boneInfo->BasePoseMatInv.matrix[j][k]); } } LL(boneInfo->numChildren); - for (k=0; knumChildren; k++) - { + for (k = 0; k < boneInfo->numChildren; k++) { LL(boneInfo->children[k]); } } @@ -3922,28 +3391,26 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean // Find the largest index by iterating through all frames. // It is not guaranteed that the compressed bone pool resides // at the end of the file. - for(i = 0; i < mdxa->numFrames; i++){ - for(j = 0; j < mdxa->numBones; j++){ - k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex - pIndex = (mdxaIndex_t *) ((byte *)mdxa + mdxa->ofsFrames + k); - tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); + for (i = 0; i < mdxa->numFrames; i++) { + for (j = 0; j < mdxa->numBones; j++) { + k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex + pIndex = (mdxaIndex_t *)((byte *)mdxa + mdxa->ofsFrames + k); + tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); - if(maxBoneIndex < tmp){ + if (maxBoneIndex < tmp) { maxBoneIndex = tmp; } } } // Swap the compressed bones. - pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)mdxa + mdxa->ofsCompBonePool); - for ( i = 0 ; i <= maxBoneIndex ; i++ ) - { - pwIn = (unsigned short *) pCompBonePool[i].Comp; + pCompBonePool = (mdxaCompQuatBone_t *)((byte *)mdxa + mdxa->ofsCompBonePool); + for (i = 0; i <= maxBoneIndex; i++) { + pwIn = (unsigned short *)pCompBonePool[i].Comp; - for ( k = 0 ; k < 7 ; k++ ) + for (k = 0; k < 7; k++) LS(pwIn[k]); } #endif return qtrue; } - diff --git a/code/rd-vanilla/tr_image.cpp b/code/rd-vanilla/tr_image.cpp index 276698ec0b..aed91dbd05 100644 --- a/code/rd-vanilla/tr_image.cpp +++ b/code/rd-vanilla/tr_image.cpp @@ -31,39 +31,37 @@ along with this program; if not, see . #include #include -static byte s_intensitytable[256]; +static byte s_intensitytable[256]; static unsigned char s_gammatable[256]; -int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; -int gl_filter_max = GL_LINEAR; +int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; +int gl_filter_max = GL_LINEAR; -#define FILE_HASH_SIZE 1024 // actually, the shader code needs this (from another module, great). -//static image_t* hashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 // actually, the shader code needs this (from another module, great). +// static image_t* hashTable[FILE_HASH_SIZE]; /* ** R_GammaCorrect */ -void R_GammaCorrect( byte *buffer, int bufSize ) { +void R_GammaCorrect(byte *buffer, int bufSize) { int i; - for ( i = 0; i < bufSize; i++ ) { + for (i = 0; i < bufSize; i++) { buffer[i] = s_gammatable[buffer[i]]; } } typedef struct { const char *name; - int minimize, maximize; + int minimize, maximize; } textureMode_t; -textureMode_t modes[] = { - {"GL_NEAREST", GL_NEAREST, GL_NEAREST}, - {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR} -}; +textureMode_t modes[] = {{"GL_NEAREST", GL_NEAREST, GL_NEAREST}, + {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}}; static const size_t numTextureModes = ARRAY_LEN(modes); @@ -72,40 +70,42 @@ static const size_t numTextureModes = ARRAY_LEN(modes); return a hash value for the filename ================ */ -long generateHashValue( const char *fname ) { - int i; - long hash; - char letter; +long generateHashValue(const char *fname) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (FILE_HASH_SIZE-1); + hash &= (FILE_HASH_SIZE - 1); return hash; } // makeup a nice clean, consistant name to query for and file under, for map<> usage... // -char *GenerateImageMappingName( const char *name ) -{ +char *GenerateImageMappingName(const char *name) { static char sName[MAX_QPATH]; - int i=0; - char letter; + int i = 0; + char letter; - while (name[i] != '\0' && ivalue > glConfig.maxTextureFilterAnisotropy ) - { - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy ); + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) { + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy); } // change all the existing mipmap texture objects -// int iNumImages = - R_Images_StartIteration(); - while ( (glt = R_Images_GetNextIteration()) != NULL) - { - if ( glt->mipmap ) { - GL_Bind (glt); + // int iNumImages = + R_Images_StartIteration(); + while ((glt = R_Images_GetNextIteration()) != NULL) { + if (glt->mipmap) { + GL_Bind(glt); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - if(glConfig.maxTextureFilterAnisotropy>0) { - if(r_ext_texture_filter_anisotropic->integer>1) { + if (glConfig.maxTextureFilterAnisotropy > 0) { + if (r_ext_texture_filter_anisotropic->integer > 1) { qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); } else { qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); @@ -163,9 +161,8 @@ void GL_TextureMode( const char *string ) { } } -static float R_BytesPerTex (int format) -{ - switch ( format ) { +static float R_BytesPerTex(int format) { + switch (format) { case 1: //"I " return 1; @@ -176,11 +173,11 @@ static float R_BytesPerTex (int format) break; case 3: //"RGB " - return glConfig.colorBits/8.0f; + return glConfig.colorBits / 8.0f; break; case 4: //"RGBA " - return glConfig.colorBits/8.0f; + return glConfig.colorBits / 8.0f; break; case GL_RGBA4: @@ -224,22 +221,17 @@ static float R_BytesPerTex (int format) R_SumOfUsedImages =============== */ -float R_SumOfUsedImages( qboolean bUseFormat ) -{ - int total = 0; +float R_SumOfUsedImages(qboolean bUseFormat) { + int total = 0; image_t *pImage; - R_Images_StartIteration(); - while ( (pImage = R_Images_GetNextIteration()) != NULL) - { - if ( pImage->frameUsed == tr.frameCount- 1 ) {//it has already been advanced for the next frame, so... - if (bUseFormat) - { - float bytePerTex = R_BytesPerTex (pImage->internalFormat); + R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { + if (pImage->frameUsed == tr.frameCount - 1) { // it has already been advanced for the next frame, so... + if (bUseFormat) { + float bytePerTex = R_BytesPerTex(pImage->internalFormat); total += bytePerTex * (pImage->width * pImage->height); - } - else - { + } else { total += pImage->width * pImage->height; } } @@ -253,94 +245,91 @@ float R_SumOfUsedImages( qboolean bUseFormat ) R_ImageList_f =============== */ -void R_ImageList_f( void ) { - int i=0; - image_t *image; - int texels = 0; -// int totalFileSizeK = 0; - float texBytes = 0.0f; +void R_ImageList_f(void) { + int i = 0; + image_t *image; + int texels = 0; + // int totalFileSizeK = 0; + float texBytes = 0.0f; const char *yesno[] = {"no ", "yes"}; - ri.Printf (PRINT_ALL, "\n -w-- -h-- -fsK- -mm- -if- wrap --name-------\n"); + ri.Printf(PRINT_ALL, "\n -w-- -h-- -fsK- -mm- -if- wrap --name-------\n"); int iNumImages = R_Images_StartIteration(); - while ( (image = R_Images_GetNextIteration()) != NULL) - { - texels += image->width*image->height; - texBytes += image->width*image->height * R_BytesPerTex (image->internalFormat); -// totalFileSizeK += (image->imgfileSize+1023)/1024; - //ri.Printf (PRINT_ALL, "%4i: %4i %4i %5i %s ", + while ((image = R_Images_GetNextIteration()) != NULL) { + texels += image->width * image->height; + texBytes += image->width * image->height * R_BytesPerTex(image->internalFormat); + // totalFileSizeK += (image->imgfileSize+1023)/1024; + // ri.Printf (PRINT_ALL, "%4i: %4i %4i %5i %s ", // i, image->width, image->height,(image->fileSize+1023)/1024, yesno[image->mipmap] ); - ri.Printf (PRINT_ALL, "%4i: %4i %4i %s ", - i, image->width, image->height,yesno[image->mipmap] ); + ri.Printf(PRINT_ALL, "%4i: %4i %4i %s ", i, image->width, image->height, yesno[image->mipmap]); - switch ( image->internalFormat ) { + switch (image->internalFormat) { case 1: - ri.Printf( PRINT_ALL, "I " ); + ri.Printf(PRINT_ALL, "I "); break; case 2: - ri.Printf( PRINT_ALL, "IA " ); + ri.Printf(PRINT_ALL, "IA "); break; case 3: - ri.Printf( PRINT_ALL, "RGB " ); + ri.Printf(PRINT_ALL, "RGB "); break; case 4: - ri.Printf( PRINT_ALL, "RGBA " ); + ri.Printf(PRINT_ALL, "RGBA "); break; case GL_RGBA8: - ri.Printf( PRINT_ALL, "RGBA8" ); + ri.Printf(PRINT_ALL, "RGBA8"); break; case GL_RGB8: - ri.Printf( PRINT_ALL, "RGB8 " ); + ri.Printf(PRINT_ALL, "RGB8 "); break; case GL_RGB4_S3TC: - ri.Printf( PRINT_ALL, "S3TC " ); + ri.Printf(PRINT_ALL, "S3TC "); break; case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: - ri.Printf( PRINT_ALL, "DXT1 " ); + ri.Printf(PRINT_ALL, "DXT1 "); break; case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - ri.Printf( PRINT_ALL, "DXT5 " ); + ri.Printf(PRINT_ALL, "DXT5 "); break; case GL_RGBA4: - ri.Printf( PRINT_ALL, "RGBA4" ); + ri.Printf(PRINT_ALL, "RGBA4"); break; case GL_RGB5: - ri.Printf( PRINT_ALL, "RGB5 " ); + ri.Printf(PRINT_ALL, "RGB5 "); break; default: - ri.Printf( PRINT_ALL, "???? " ); + ri.Printf(PRINT_ALL, "???? "); } - switch ( image->wrapClampMode ) { + switch (image->wrapClampMode) { case GL_REPEAT: - ri.Printf( PRINT_ALL, "rept " ); + ri.Printf(PRINT_ALL, "rept "); break; case GL_CLAMP: - ri.Printf( PRINT_ALL, "clmp " ); + ri.Printf(PRINT_ALL, "clmp "); break; case GL_CLAMP_TO_EDGE: - ri.Printf( PRINT_ALL, "clpE " ); + ri.Printf(PRINT_ALL, "clpE "); break; default: - ri.Printf( PRINT_ALL, "%4i ", image->wrapClampMode ); + ri.Printf(PRINT_ALL, "%4i ", image->wrapClampMode); break; } - ri.Printf( PRINT_ALL, "%s\n", image->imgName ); + ri.Printf(PRINT_ALL, "%s\n", image->imgName); i++; } - ri.Printf (PRINT_ALL, " ---------\n"); - ri.Printf (PRINT_ALL, " -w-- -h-- -mm- -if- wrap --name-------\n"); - ri.Printf (PRINT_ALL, " %i total texels (not including mipmaps)\n", texels ); -// ri.Printf (PRINT_ALL, " %iMB total filesize\n", (totalFileSizeK+1023)/1024 ); - ri.Printf (PRINT_ALL, " %.2fMB total texture mem (not including mipmaps)\n", texBytes/1048576.0f ); - ri.Printf (PRINT_ALL, " %i total images\n\n", iNumImages ); + ri.Printf(PRINT_ALL, " ---------\n"); + ri.Printf(PRINT_ALL, " -w-- -h-- -mm- -if- wrap --name-------\n"); + ri.Printf(PRINT_ALL, " %i total texels (not including mipmaps)\n", texels); + // ri.Printf (PRINT_ALL, " %iMB total filesize\n", (totalFileSizeK+1023)/1024 ); + ri.Printf(PRINT_ALL, " %.2fMB total texture mem (not including mipmaps)\n", texBytes / 1048576.0f); + ri.Printf(PRINT_ALL, " %i total images\n\n", iNumImages); } //======================================================================= - /* ================ R_LightScaleTexture @@ -349,48 +338,37 @@ Scale up the pixel values in a texture to increase the lighting range ================ */ -static void R_LightScaleTexture (unsigned *in, int inwidth, int inheight, qboolean only_gamma ) -{ - if ( only_gamma ) - { - if ( !glConfig.deviceSupportsGamma ) - { - int i, c; - byte *p; +static void R_LightScaleTexture(unsigned *in, int inwidth, int inheight, qboolean only_gamma) { + if (only_gamma) { + if (!glConfig.deviceSupportsGamma) { + int i, c; + byte *p; p = (byte *)in; - c = inwidth*inheight; - for (i=0 ; i> 1; outHeight = inHeight >> 1; - temp = (unsigned int *) R_Malloc( outWidth * outHeight * 4, TAG_TEMP_WORKSPACE, qfalse ); + temp = (unsigned int *)R_Malloc(outWidth * outHeight * 4, TAG_TEMP_WORKSPACE, qfalse); inWidthMask = inWidth - 1; inHeightMask = inHeight - 1; - for ( i = 0 ; i < outHeight ; i++ ) { - for ( j = 0 ; j < outWidth ; j++ ) { - outpix = (byte *) ( temp + i * outWidth + j ); - for ( k = 0 ; k < 4 ; k++ ) { - total = - 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k]; + for (i = 0; i < outHeight; i++) { + for (j = 0; j < outWidth; j++) { + outpix = (byte *)(temp + i * outWidth + j); + for (k = 0; k < 4; k++) { + total = 1 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 1 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 2 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 2 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 1 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 1 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k]; outpix[k] = total / 36; } } } - memcpy( in, temp, outWidth * outHeight * 4 ); - R_Free( temp ); + memcpy(in, temp, outWidth * outHeight * 4); + R_Free(temp); } /* @@ -463,17 +439,17 @@ R_MipMap Operates in place, quartering the size of the texture ================ */ -static void R_MipMap (byte *in, int width, int height) { - int i, j; - byte *out; - int row; +static void R_MipMap(byte *in, int width, int height) { + int i, j; + byte *out; + int row; - if ( width == 1 && height == 1 ) { + if (width == 1 && height == 1) { return; } - if ( !r_simpleMipMaps->integer ) { - R_MipMap2( (unsigned *)in, width, height ); + if (!r_simpleMipMaps->integer) { + R_MipMap2((unsigned *)in, width, height); return; } @@ -482,28 +458,27 @@ static void R_MipMap (byte *in, int width, int height) { width >>= 1; height >>= 1; - if ( width == 0 || height == 0 ) { - width += height; // get largest - for (i=0 ; i>1; - out[1] = ( in[1] + in[5] )>>1; - out[2] = ( in[2] + in[6] )>>1; - out[3] = ( in[3] + in[7] )>>1; + if (width == 0 || height == 0) { + width += height; // get largest + for (i = 0; i < width; i++, out += 4, in += 8) { + out[0] = (in[0] + in[4]) >> 1; + out[1] = (in[1] + in[5]) >> 1; + out[2] = (in[2] + in[6]) >> 1; + out[3] = (in[3] + in[7]) >> 1; } return; } - for (i=0 ; i>2; - out[1] = (in[1] + in[5] + in[row+1] + in[row+5])>>2; - out[2] = (in[2] + in[6] + in[row+2] + in[row+6])>>2; - out[3] = (in[3] + in[7] + in[row+3] + in[row+7])>>2; + for (i = 0; i < height; i++, in += row) { + for (j = 0; j < width; j++, out += 4, in += 8) { + out[0] = (in[0] + in[4] + in[row + 0] + in[row + 4]) >> 2; + out[1] = (in[1] + in[5] + in[row + 1] + in[row + 5]) >> 2; + out[2] = (in[2] + in[6] + in[row + 2] + in[row + 6]) >> 2; + out[3] = (in[3] + in[7] + in[row + 3] + in[row + 7]) >> 2; } } } - /* ================== R_BlendOverTexture @@ -511,268 +486,201 @@ R_BlendOverTexture Apply a color blend over a set of pixels ================== */ -static void R_BlendOverTexture( byte *data, int pixelCount, byte blend[4] ) { - int i; - int inverseAlpha; - int premult[3]; +static void R_BlendOverTexture(byte *data, int pixelCount, byte blend[4]) { + int i; + int inverseAlpha; + int premult[3]; inverseAlpha = 255 - blend[3]; premult[0] = blend[0] * blend[3]; premult[1] = blend[1] * blend[3]; premult[2] = blend[2] * blend[3]; - for ( i = 0 ; i < pixelCount ; i++, data+=4 ) { - data[0] = ( data[0] * inverseAlpha + premult[0] ) >> 9; - data[1] = ( data[1] * inverseAlpha + premult[1] ) >> 9; - data[2] = ( data[2] * inverseAlpha + premult[2] ) >> 9; + for (i = 0; i < pixelCount; i++, data += 4) { + data[0] = (data[0] * inverseAlpha + premult[0]) >> 9; + data[1] = (data[1] * inverseAlpha + premult[1]) >> 9; + data[2] = (data[2] * inverseAlpha + premult[2]) >> 9; } } -byte mipBlendColors[16][4] = { - {0,0,0,0}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, +byte mipBlendColors[16][4] = { + {0, 0, 0, 0}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, + {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, }; - /* =============== Upload32 =============== */ -static void Upload32( unsigned *data, - GLenum format, - qboolean mipmap, - qboolean picmip, - qboolean isLightmap, - qboolean allowTC, - int *pformat, - word *pUploadWidth, word *pUploadHeight ) -{ - if (format == GL_RGBA) - { - int samples; - int i, c; - byte *scan; - float rMax = 0, gMax = 0, bMax = 0; - int width = *pUploadWidth; - int height = *pUploadHeight; - - // - // perform optional picmip operation - // - if ( picmip ) { - for(i = 0; i < r_picmip->integer; i++) { - R_MipMap( (byte *)data, width, height ); - width >>= 1; - height >>= 1; - if (width < 1) { - width = 1; - } - if (height < 1) { - height = 1; - } - } - } - - // - // clamp to the current upper OpenGL limit - // scale both axis down equally so we don't have to - // deal with a half mip resampling - // - while ( width > glConfig.maxTextureSize || height > glConfig.maxTextureSize ) { - R_MipMap( (byte *)data, width, height ); - width >>= 1; - height >>= 1; - } - - // - // scan the texture for each channel's max values - // and verify if the alpha channel is being used or not - // - c = width*height; - scan = ((byte *)data); - samples = 3; - for ( i = 0; i < c; i++ ) - { - if ( scan[i*4+0] > rMax ) - { - rMax = scan[i*4+0]; - } - if ( scan[i*4+1] > gMax ) - { - gMax = scan[i*4+1]; - } - if ( scan[i*4+2] > bMax ) - { - bMax = scan[i*4+2]; - } - if ( scan[i*4 + 3] != 255 ) - { - samples = 4; - break; - } - } - - // select proper internal format - if ( samples == 3 ) - { - if ( glConfig.textureCompression == TC_S3TC && allowTC ) - { - *pformat = GL_RGB4_S3TC; - } - else if ( glConfig.textureCompression == TC_S3TC_DXT && allowTC ) - { // Compress purely color - no alpha - if ( r_texturebits->integer == 16 ) { - *pformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; //this format cuts to 16 bit - } - else {//if we aren't using 16 bit then, use 32 bit compression - *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - } - } - else if ( isLightmap && r_texturebitslm->integer > 0 ) - { - // Allow different bit depth when we are a lightmap - if ( r_texturebitslm->integer == 16 ) - { - *pformat = GL_RGB5; - } - else if ( r_texturebitslm->integer == 32 ) - { - *pformat = GL_RGB8; - } - } - else if ( r_texturebits->integer == 16 ) - { - *pformat = GL_RGB5; - } - else if ( r_texturebits->integer == 32 ) - { - *pformat = GL_RGB8; - } - else - { - *pformat = 3; - } - } - else if ( samples == 4 ) - { - if ( glConfig.textureCompression == TC_S3TC_DXT && allowTC) - { // Compress both alpha and color - *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - } - else if ( r_texturebits->integer == 16 ) - { - *pformat = GL_RGBA4; - } - else if ( r_texturebits->integer == 32 ) - { - *pformat = GL_RGBA8; - } - else - { - *pformat = 4; - } - } +static void Upload32(unsigned *data, GLenum format, qboolean mipmap, qboolean picmip, qboolean isLightmap, qboolean allowTC, int *pformat, word *pUploadWidth, + word *pUploadHeight) { + if (format == GL_RGBA) { + int samples; + int i, c; + byte *scan; + float rMax = 0, gMax = 0, bMax = 0; + int width = *pUploadWidth; + int height = *pUploadHeight; + + // + // perform optional picmip operation + // + if (picmip) { + for (i = 0; i < r_picmip->integer; i++) { + R_MipMap((byte *)data, width, height); + width >>= 1; + height >>= 1; + if (width < 1) { + width = 1; + } + if (height < 1) { + height = 1; + } + } + } + + // + // clamp to the current upper OpenGL limit + // scale both axis down equally so we don't have to + // deal with a half mip resampling + // + while (width > glConfig.maxTextureSize || height > glConfig.maxTextureSize) { + R_MipMap((byte *)data, width, height); + width >>= 1; + height >>= 1; + } + + // + // scan the texture for each channel's max values + // and verify if the alpha channel is being used or not + // + c = width * height; + scan = ((byte *)data); + samples = 3; + for (i = 0; i < c; i++) { + if (scan[i * 4 + 0] > rMax) { + rMax = scan[i * 4 + 0]; + } + if (scan[i * 4 + 1] > gMax) { + gMax = scan[i * 4 + 1]; + } + if (scan[i * 4 + 2] > bMax) { + bMax = scan[i * 4 + 2]; + } + if (scan[i * 4 + 3] != 255) { + samples = 4; + break; + } + } + + // select proper internal format + if (samples == 3) { + if (glConfig.textureCompression == TC_S3TC && allowTC) { + *pformat = GL_RGB4_S3TC; + } else if (glConfig.textureCompression == TC_S3TC_DXT && allowTC) { // Compress purely color - no alpha + if (r_texturebits->integer == 16) { + *pformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; // this format cuts to 16 bit + } else { // if we aren't using 16 bit then, use 32 bit compression + *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + } + } else if (isLightmap && r_texturebitslm->integer > 0) { + // Allow different bit depth when we are a lightmap + if (r_texturebitslm->integer == 16) { + *pformat = GL_RGB5; + } else if (r_texturebitslm->integer == 32) { + *pformat = GL_RGB8; + } + } else if (r_texturebits->integer == 16) { + *pformat = GL_RGB5; + } else if (r_texturebits->integer == 32) { + *pformat = GL_RGB8; + } else { + *pformat = 3; + } + } else if (samples == 4) { + if (glConfig.textureCompression == TC_S3TC_DXT && allowTC) { // Compress both alpha and color + *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else if (r_texturebits->integer == 16) { + *pformat = GL_RGBA4; + } else if (r_texturebits->integer == 32) { + *pformat = GL_RGBA8; + } else { + *pformat = 4; + } + } *pUploadWidth = width; *pUploadHeight = height; - // copy or resample data as appropriate for first MIP level - if (!mipmap) - { - qglTexImage2D (GL_TEXTURE_2D, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - goto done; - } - - R_LightScaleTexture (data, width, height, (qboolean)!mipmap); - - qglTexImage2D (GL_TEXTURE_2D, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); - - if (mipmap) - { - int miplevel; - - miplevel = 0; - while (width > 1 || height > 1) - { - R_MipMap( (byte *)data, width, height ); - width >>= 1; - height >>= 1; - if (width < 1) - width = 1; - if (height < 1) - height = 1; - miplevel++; - - if ( r_colorMipLevels->integer ) - { - R_BlendOverTexture( (byte *)data, width * height, mipBlendColors[miplevel] ); - } - - qglTexImage2D (GL_TEXTURE_2D, miplevel, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); - } - } - } - else - { + // copy or resample data as appropriate for first MIP level + if (!mipmap) { + qglTexImage2D(GL_TEXTURE_2D, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + goto done; + } + + R_LightScaleTexture(data, width, height, (qboolean)!mipmap); + + qglTexImage2D(GL_TEXTURE_2D, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + if (mipmap) { + int miplevel; + + miplevel = 0; + while (width > 1 || height > 1) { + R_MipMap((byte *)data, width, height); + width >>= 1; + height >>= 1; + if (width < 1) + width = 1; + if (height < 1) + height = 1; + miplevel++; + + if (r_colorMipLevels->integer) { + R_BlendOverTexture((byte *)data, width * height, mipBlendColors[miplevel]); + } + + qglTexImage2D(GL_TEXTURE_2D, miplevel, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + } + } + } else { } done: - if (mipmap) - { + if (mipmap) { qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - if( r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0 ) - { - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value ); + if (r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0) { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); } - } - else - { - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } else { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } GL_CheckErrors(); } -class CStringComparator -{ -public: - bool operator()(const char *s1, const char *s2) const { return(Q_stricmp(s1, s2) < 0); } +class CStringComparator { + public: + bool operator()(const char *s1, const char *s2) const { return (Q_stricmp(s1, s2) < 0); } }; -typedef std::map AllocatedImages_t; +typedef std::map AllocatedImages_t; AllocatedImages_t AllocatedImages; AllocatedImages_t::iterator itAllocatedImages; -int giTextureBindNum = 1024; // will be set to this anyway at runtime, but wtf? +int giTextureBindNum = 1024; // will be set to this anyway at runtime, but wtf? -int R_Images_StartIteration(void) -{ +int R_Images_StartIteration(void) { itAllocatedImages = AllocatedImages.begin(); return AllocatedImages.size(); } -image_t *R_Images_GetNextIteration(void) -{ +image_t *R_Images_GetNextIteration(void) { if (itAllocatedImages == AllocatedImages.end()) return NULL; @@ -781,47 +689,41 @@ image_t *R_Images_GetNextIteration(void) return pImage; } -// clean up anything to do with an image_t struct, but caller will have to clear the internal to an image_t struct ready for either struct free() or overwrite... +// clean up anything to do with an image_t struct, but caller will have to clear the internal to an image_t struct ready for either struct free() or +// overwrite... // -static void R_Images_DeleteImageContents( image_t *pImage ) -{ - assert(pImage); // should never be called with NULL - if (pImage) - { - qglDeleteTextures( 1, &pImage->texnum ); +static void R_Images_DeleteImageContents(image_t *pImage) { + assert(pImage); // should never be called with NULL + if (pImage) { + qglDeleteTextures(1, &pImage->texnum); R_Free(pImage); } } -static void GL_ResetBinds(void) -{ - memset( glState.currenttextures, 0, sizeof( glState.currenttextures ) ); - if ( qglActiveTextureARB ) { - GL_SelectTexture( 1 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); - GL_SelectTexture( 0 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); +static void GL_ResetBinds(void) { + memset(glState.currenttextures, 0, sizeof(glState.currenttextures)); + if (qglActiveTextureARB) { + GL_SelectTexture(1); + qglBindTexture(GL_TEXTURE_2D, 0); + GL_SelectTexture(0); + qglBindTexture(GL_TEXTURE_2D, 0); } else { - qglBindTexture( GL_TEXTURE_2D, 0 ); + qglBindTexture(GL_TEXTURE_2D, 0); } } // special function used in conjunction with "devmapbsp"... // -void R_Images_DeleteLightMaps(void) -{ - for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* empty */) - { +void R_Images_DeleteLightMaps(void) { + for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* empty */) { image_t *pImage = (*itImage).second; - if (pImage->imgName[0] == '$' /*&& strstr(pImage->imgName,"lightmap")*/) // loose check, but should be ok + if (pImage->imgName[0] == '$' /*&& strstr(pImage->imgName,"lightmap")*/) // loose check, but should be ok { R_Images_DeleteImageContents(pImage); AllocatedImages.erase(itImage++); - } - else - { + } else { ++itImage; } } @@ -831,31 +733,25 @@ void R_Images_DeleteLightMaps(void) // special function currently only called by Dissolve code... // -void R_Images_DeleteImage(image_t *pImage) -{ +void R_Images_DeleteImage(image_t *pImage) { // Even though we supply the image handle, we need to get the corresponding iterator entry... // AllocatedImages_t::iterator itImage = AllocatedImages.find(pImage->imgName); - if (itImage != AllocatedImages.end()) - { + if (itImage != AllocatedImages.end()) { R_Images_DeleteImageContents(pImage); AllocatedImages.erase(itImage); - } - else - { + } else { assert(0); } } // called only at app startup, vid_restart, app-exit // -void R_Images_Clear(void) -{ +void R_Images_Clear(void) { image_t *pImage; // int iNumImages = - R_Images_StartIteration(); - while ( (pImage = R_Images_GetNextIteration()) != NULL) - { + R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { R_Images_DeleteImageContents(pImage); } @@ -863,48 +759,41 @@ void R_Images_Clear(void) giTextureBindNum = 1024; } +void RE_RegisterImages_Info_f(void) { + image_t *pImage = NULL; + int iImage = 0; + int iTexels = 0; -void RE_RegisterImages_Info_f( void ) -{ - image_t *pImage = NULL; - int iImage = 0; - int iTexels = 0; - - int iNumImages = R_Images_StartIteration(); - while ( (pImage = R_Images_GetNextIteration()) != NULL) - { - ri.Printf( PRINT_ALL, "%d: (%4dx%4dy) \"%s\"",iImage, pImage->width, pImage->height, pImage->imgName); - ri.Printf( PRINT_ALL, ", levused %d",pImage->iLastLevelUsedOn); - ri.Printf( PRINT_ALL, "\n"); + int iNumImages = R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { + ri.Printf(PRINT_ALL, "%d: (%4dx%4dy) \"%s\"", iImage, pImage->width, pImage->height, pImage->imgName); + ri.Printf(PRINT_ALL, ", levused %d", pImage->iLastLevelUsedOn); + ri.Printf(PRINT_ALL, "\n"); iTexels += pImage->width * pImage->height; iImage++; } - ri.Printf( PRINT_ALL, "%d Images. %d (%.2fMB) texels total, (not including mipmaps)\n",iNumImages, iTexels, (float)iTexels / 1024.0f / 1024.0f); - ri.Printf( PRINT_DEVELOPER, "RE_RegisterMedia_GetLevel(): %d",RE_RegisterMedia_GetLevel()); + ri.Printf(PRINT_ALL, "%d Images. %d (%.2fMB) texels total, (not including mipmaps)\n", iNumImages, iTexels, (float)iTexels / 1024.0f / 1024.0f); + ri.Printf(PRINT_DEVELOPER, "RE_RegisterMedia_GetLevel(): %d", RE_RegisterMedia_GetLevel()); } // currently, this just goes through all the images and dumps any not referenced on this level... // -qboolean RE_RegisterImages_LevelLoadEnd(void) -{ - //ri.Printf( PRINT_DEVELOPER, "RE_RegisterImages_LevelLoadEnd():\n"); +qboolean RE_RegisterImages_LevelLoadEnd(void) { + // ri.Printf( PRINT_DEVELOPER, "RE_RegisterImages_LevelLoadEnd():\n"); qboolean imageDeleted = qtrue; - for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* blank */) - { + for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* blank */) { qboolean bEraseOccured = qfalse; image_t *pImage = (*itImage).second; // don't un-register system shaders (*fog, *dlight, *white, *default), but DO de-register lightmaps ("$/lightmap%d") - if (pImage->imgName[0] != '*') - { + if (pImage->imgName[0] != '*') { // image used on this level? // - if ( pImage->iLastLevelUsedOn != RE_RegisterMedia_GetLevel() ) - { // nope, so dump it... - //ri.Printf( PRINT_DEVELOPER, "Dumping image \"%s\"\n",pImage->imgName); + if (pImage->iLastLevelUsedOn != RE_RegisterMedia_GetLevel()) { // nope, so dump it... + // ri.Printf( PRINT_DEVELOPER, "Dumping image \"%s\"\n",pImage->imgName); R_Images_DeleteImageContents(pImage); AllocatedImages.erase(itImage++); @@ -913,28 +802,24 @@ qboolean RE_RegisterImages_LevelLoadEnd(void) } } - if ( !bEraseOccured ) - { + if (!bEraseOccured) { ++itImage; } } - //ri.Printf( PRINT_DEVELOPER, "RE_RegisterImages_LevelLoadEnd(): Ok\n"); + // ri.Printf( PRINT_DEVELOPER, "RE_RegisterImages_LevelLoadEnd(): Ok\n"); GL_ResetBinds(); return imageDeleted; } - - // returns image_t struct if we already have this, else NULL. No disk-open performed // (important for creating default images). // // This is called by both R_FindImageFile and anything that creates default images... // -static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode ) -{ +static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode) { if (!name) { return NULL; } @@ -945,21 +830,20 @@ static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboole // see if the image is already loaded // AllocatedImages_t::iterator itAllocatedImage = AllocatedImages.find(pName); - if (itAllocatedImage != AllocatedImages.end()) - { + if (itAllocatedImage != AllocatedImages.end()) { image_t *pImage = (*itAllocatedImage).second; // the white image can be used with any set of parms, but other mismatches are errors... // - if ( strcmp( pName, "*white" ) ) { - if ( pImage->mipmap != !!mipmap ) { - ri.Printf( PRINT_WARNING, "WARNING: reused image %s with mixed mipmap parm\n", pName ); + if (strcmp(pName, "*white")) { + if (pImage->mipmap != !!mipmap) { + ri.Printf(PRINT_WARNING, "WARNING: reused image %s with mixed mipmap parm\n", pName); } - if ( pImage->allowPicmip != !!allowPicmip ) { - ri.Printf( PRINT_WARNING, "WARNING: reused image %s with mixed allowPicmip parm\n", pName ); + if (pImage->allowPicmip != !!allowPicmip) { + ri.Printf(PRINT_WARNING, "WARNING: reused image %s with mixed allowPicmip parm\n", pName); } - if ( pImage->wrapClampMode != glWrapClampMode ) { - ri.Printf( PRINT_WARNING, "WARNING: reused image %s with mixed glWrapClampMode parm\n", pName ); + if (pImage->wrapClampMode != glWrapClampMode) { + ri.Printf(PRINT_WARNING, "WARNING: reused image %s with mixed glWrapClampMode parm\n", pName); } } @@ -971,7 +855,6 @@ static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboole return NULL; } - /* ================ R_CreateImage @@ -979,40 +862,37 @@ R_CreateImage This is the only way any image_t are created ================ */ -image_t *R_CreateImage( const char *name, const byte *pic, int width, int height, - GLenum format, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode) -{ - image_t *image; - qboolean isLightmap = qfalse; - - if (strlen(name) >= MAX_QPATH ) { - Com_Error (ERR_DROP, "R_CreateImage: \"%s\" is too long\n", name); +image_t *R_CreateImage(const char *name, const byte *pic, int width, int height, GLenum format, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, + int glWrapClampMode) { + image_t *image; + qboolean isLightmap = qfalse; + + if (strlen(name) >= MAX_QPATH) { + Com_Error(ERR_DROP, "R_CreateImage: \"%s\" is too long\n", name); } - if(glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { + if (glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { glWrapClampMode = GL_CLAMP_TO_EDGE; } - if (name[0] == '$') - { + if (name[0] == '$') { isLightmap = qtrue; } - if ( (width&(width-1)) || (height&(height-1)) ) - { - Com_Error( ERR_FATAL, "R_CreateImage: %s dimensions (%i x %i) not power of 2!\n",name,width,height); + if ((width & (width - 1)) || (height & (height - 1))) { + Com_Error(ERR_FATAL, "R_CreateImage: %s dimensions (%i x %i) not power of 2!\n", name, width, height); } - image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode ); + image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode); if (image) { return image; } - image = (image_t*) R_Malloc( sizeof( image_t ), TAG_IMAGE_T, qtrue ); + image = (image_t *)R_Malloc(sizeof(image_t), TAG_IMAGE_T, qtrue); - //image->imgfileSize=fileSize; + // image->imgfileSize=fileSize; - image->texnum = 1024 + giTextureBindNum++; // ++ is of course staggeringly important... + image->texnum = 1024 + giTextureBindNum++; // ++ is of course staggeringly important... // record which map it was used on... // @@ -1027,30 +907,23 @@ image_t *R_CreateImage( const char *name, const byte *pic, int width, int height image->height = height; image->wrapClampMode = glWrapClampMode; - if ( qglActiveTextureARB ) { - GL_SelectTexture( 0 ); + if (qglActiveTextureARB) { + GL_SelectTexture(0); } GL_Bind(image); - Upload32( (unsigned *)pic, format, - (qboolean)image->mipmap, - allowPicmip, - isLightmap, - allowTC, - &image->internalFormat, - &image->width, - &image->height ); + Upload32((unsigned *)pic, format, (qboolean)image->mipmap, allowPicmip, isLightmap, allowTC, &image->internalFormat, &image->width, &image->height); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode); - qglBindTexture( GL_TEXTURE_2D, 0 ); //jfm: i don't know why this is here, but it breaks lightmaps when there's only 1 - glState.currenttextures[glState.currenttmu] = 0; //mark it not bound + qglBindTexture(GL_TEXTURE_2D, 0); // jfm: i don't know why this is here, but it breaks lightmaps when there's only 1 + glState.currenttextures[glState.currenttmu] = 0; // mark it not bound const char *psNewName = GenerateImageMappingName(name); Q_strncpyz(image->imgName, psNewName, sizeof(image->imgName)); - AllocatedImages[ image->imgName ] = image; + AllocatedImages[image->imgName] = image; return image; } @@ -1063,10 +936,10 @@ Finds or loads the given image. Returns NULL if it fails, not a default image. ============== */ -image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode ) { - image_t *image; - int width, height; - byte *pic; +image_t *R_FindImageFile(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode) { + image_t *image; + int width, height; + byte *pic; if (!name) { return NULL; @@ -1075,11 +948,11 @@ image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmi // need to do this here as well as in R_CreateImage, or R_FindImageFile_NoLoad() may complain about // different clamp parms used... // - if(glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { + if (glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { glWrapClampMode = GL_CLAMP_TO_EDGE; } - image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode ); + image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode); if (image) { return image; } @@ -1087,94 +960,79 @@ image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmi // // load the pic from disk // - R_LoadImage( name, &pic, &width, &height ); - if ( !pic ) { - return NULL; + R_LoadImage(name, &pic, &width, &height); + if (!pic) { + return NULL; } - image = R_CreateImage( ( char * ) name, pic, width, height, GL_RGBA, mipmap, allowPicmip, allowTC, glWrapClampMode ); - R_Free( pic ); + image = R_CreateImage((char *)name, pic, width, height, GL_RGBA, mipmap, allowPicmip, allowTC, glWrapClampMode); + R_Free(pic); return image; } - /* ================ R_CreateDlightImage ================ */ -#define DLIGHT_SIZE 64 -static void R_CreateDlightImage( void ) -{ +#define DLIGHT_SIZE 64 +static void R_CreateDlightImage(void) { #ifdef JK2_MODE - int x,y; - byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; - int xs, ys; + int x, y; + byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; + int xs, ys; int b; // The old code claims to have made a centered inverse-square falloff blob for dynamic lighting // and it looked nasty, so, just doing something simpler that seems to have a much softer result - for ( x = 0; x < DLIGHT_SIZE; x++ ) - { - for ( y = 0; y < DLIGHT_SIZE; y++ ) - { + for (x = 0; x < DLIGHT_SIZE; x++) { + for (y = 0; y < DLIGHT_SIZE; y++) { xs = (DLIGHT_SIZE * 0.5f - x); ys = (DLIGHT_SIZE * 0.5f - y); - b = 255 - sqrt((double) xs * xs + ys * ys ) * 9.0f; // try and generate numbers in the range of 255-0 + b = 255 - sqrt((double)xs * xs + ys * ys) * 9.0f; // try and generate numbers in the range of 255-0 // should be close, but clamp anyway - if ( b > 255 ) - { + if (b > 255) { b = 255; - } - else if ( b < 0 ) - { + } else if (b < 0) { b = 0; } - data[y][x][0] = - data[y][x][1] = - data[y][x][2] = b; + data[y][x][0] = data[y][x][1] = data[y][x][2] = b; data[y][x][3] = 255; } } - tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP ); + tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP); #else - int width, height; - byte *pic; + int width, height; + byte *pic; R_LoadImage("gfx/2d/dlight", &pic, &width, &height); - if (pic) - { - tr.dlightImage = R_CreateImage("*dlight", pic, width, height, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP ); + if (pic) { + tr.dlightImage = R_CreateImage("*dlight", pic, width, height, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP); R_Free(pic); - } - else - { // if we dont get a successful load - int x,y; - byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; - int b; + } else { // if we dont get a successful load + int x, y; + byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; + int b; // make a centered inverse-square falloff blob for dynamic lighting - for (x=0 ; x 255) { b = 255; - } else if ( b < 75 ) { + } else if (b < 75) { b = 0; } - data[y][x][0] = - data[y][x][1] = - data[y][x][2] = b; + data[y][x][0] = data[y][x][1] = data[y][x][2] = b; data[y][x][3] = 255; } } - tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP ); + tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP); } #endif } @@ -1184,15 +1042,15 @@ static void R_CreateDlightImage( void ) R_InitFogTable ================= */ -void R_InitFogTable( void ) { - int i; - float d; - float exp; +void R_InitFogTable(void) { + int i; + float d; + float exp; exp = 0.5; - for ( i = 0 ; i < FOG_TABLE_SIZE ; i++ ) { - d = pow ( (float)i/(FOG_TABLE_SIZE-1), exp ); + for (i = 0; i < FOG_TABLE_SIZE; i++) { + d = pow((float)i / (FOG_TABLE_SIZE - 1), exp); tr.fogTable[i] = d; } @@ -1207,28 +1065,28 @@ This is called for each texel of the fog texture on startup and for each vertex of transparent shaders in fog dynamically ================ */ -float R_FogFactor( float s, float t ) { - float d; +float R_FogFactor(float s, float t) { + float d; - s -= 1.0/512; - if ( s < 0 ) { + s -= 1.0 / 512; + if (s < 0) { return 0; } - if ( t < 1.0/32 ) { + if (t < 1.0 / 32) { return 0; } - if ( t < 31.0/32 ) { - s *= (t - 1.0f/32.0f) / (30.0f/32.0f); + if (t < 31.0 / 32) { + s *= (t - 1.0f / 32.0f) / (30.0f / 32.0f); } // we need to leave a lot of clamp range s *= 8; - if ( s > 1.0 ) { + if (s > 1.0) { s = 1.0; } - d = tr.fogTable[ (int)(s * (FOG_TABLE_SIZE-1)) ]; + d = tr.fogTable[(int)(s * (FOG_TABLE_SIZE - 1))]; return d; } @@ -1238,39 +1096,37 @@ float R_FogFactor( float s, float t ) { R_CreateFogImage ================ */ -#define FOG_S 256 -#define FOG_T 32 -static void R_CreateFogImage( void ) { - int x,y; - byte *data; - float d; - float borderColor[4]; +#define FOG_S 256 +#define FOG_T 32 +static void R_CreateFogImage(void) { + int x, y; + byte *data; + float d; + float borderColor[4]; - data = (byte*) R_Malloc( FOG_S * FOG_T * 4, TAG_TEMP_WORKSPACE, qfalse ); + data = (byte *)R_Malloc(FOG_S * FOG_T * 4, TAG_TEMP_WORKSPACE, qfalse); // S is distance, T is depth - for (x=0 ; xinteger > glConfig.vidWidth ) - { + if (r_DynamicGlowWidth->integer > glConfig.vidWidth) { r_DynamicGlowWidth->integer = glConfig.vidWidth; } - if ( r_DynamicGlowHeight->integer > glConfig.vidHeight ) - { + if (r_DynamicGlowHeight->integer > glConfig.vidHeight) { r_DynamicGlowHeight->integer = glConfig.vidHeight; } tr.blurImage = 1024 + giTextureBindNum++; - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglTexImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA16, r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer, 0, GL_RGB, GL_FLOAT, 0 ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); - + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA16, r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer, 0, GL_RGB, GL_FLOAT, 0); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // with overbright bits active, we need an image which is some fraction of full color, // for default lightmaps, etc - for (x=0 ; xinteger; - if ( !glConfig.deviceSupportsGamma ) { - tr.overbrightBits = 0; // need hardware gamma for overbright + if (!glConfig.deviceSupportsGamma) { + tr.overbrightBits = 0; // need hardware gamma for overbright } // never overbright in windowed mode - if ( !glConfig.isFullscreen ) - { + if (!glConfig.isFullscreen) { tr.overbrightBits = 0; } - if ( tr.overbrightBits > 1 ) { + if (tr.overbrightBits > 1) { tr.overbrightBits = 1; } - if ( tr.overbrightBits < 0 ) { + if (tr.overbrightBits < 0) { tr.overbrightBits = 0; } - tr.identityLight = 1.0 / ( 1 << tr.overbrightBits ); + tr.identityLight = 1.0 / (1 << tr.overbrightBits); tr.identityLightByte = 255 * tr.identityLight; - - if ( r_intensity->value < 1.0f ) { - ri.Cvar_Set( "r_intensity", "1.0" ); + if (r_intensity->value < 1.0f) { + ri.Cvar_Set("r_intensity", "1.0"); } - if ( r_gamma->value < 0.5f ) { - ri.Cvar_Set( "r_gamma", "0.5" ); - } else if ( r_gamma->value > 3.0f ) { - ri.Cvar_Set( "r_gamma", "3.0" ); + if (r_gamma->value < 0.5f) { + ri.Cvar_Set("r_gamma", "0.5"); + } else if (r_gamma->value > 3.0f) { + ri.Cvar_Set("r_gamma", "3.0"); } g = r_gamma->value; shift = tr.overbrightBits; - for ( i = 0; i < 256; i++ ) { - if ( g == 1 ) { + for (i = 0; i < 256; i++) { + if (g == 1) { inf = i; } else { - inf = 255 * pow ( i/255.0f, 1.0f / g ) + 0.5f; + inf = 255 * pow(i / 255.0f, 1.0f / g) + 0.5f; } inf <<= shift; if (inf < 0) { @@ -1459,7 +1293,7 @@ void R_SetColorMappings( void ) { s_gammatable[i] = inf; } - for (i=0 ; i<256 ; i++) { + for (i = 0; i < 256; i++) { j = i * r_intensity->value; if (j > 255) { j = 255; @@ -1467,9 +1301,8 @@ void R_SetColorMappings( void ) { s_intensitytable[i] = j; } - if ( glConfig.deviceSupportsGamma ) - { - ri.WIN_SetGamma( &glConfig, s_gammatable, s_gammatable, s_gammatable ); + if (glConfig.deviceSupportsGamma) { + ri.WIN_SetGamma(&glConfig, s_gammatable, s_gammatable, s_gammatable); } } @@ -1478,8 +1311,8 @@ void R_SetColorMappings( void ) { R_InitImages =============== */ -void R_InitImages( void ) { - //memset(hashTable, 0, sizeof(hashTable)); // DO NOT DO THIS NOW (because of image cacheing) -ste. +void R_InitImages(void) { + // memset(hashTable, 0, sizeof(hashTable)); // DO NOT DO THIS NOW (because of image cacheing) -ste. // build brightness translation tables R_SetColorMappings(); @@ -1495,9 +1328,8 @@ R_DeleteTextures */ // (only gets called during vid_restart now (and app exit), not during map load) // -void R_DeleteTextures( void ) { +void R_DeleteTextures(void) { R_Images_Clear(); GL_ResetBinds(); } - diff --git a/code/rd-vanilla/tr_init.cpp b/code/rd-vanilla/tr_init.cpp index 13c72e66ee..193c5edf8f 100644 --- a/code/rd-vanilla/tr_init.cpp +++ b/code/rd-vanilla/tr_init.cpp @@ -32,157 +32,157 @@ along with this program; if not, see . #include "../rd-common/tr_font.h" #include "tr_WorldEffects.h" -glconfig_t glConfig; -glstate_t glState; -window_t window; +glconfig_t glConfig; +glstate_t glState; +window_t window; -static void GfxInfo_f( void ); +static void GfxInfo_f(void); -cvar_t *r_verbose; -cvar_t *r_ignore; +cvar_t *r_verbose; +cvar_t *r_ignore; -cvar_t *r_detailTextures; +cvar_t *r_detailTextures; -cvar_t *r_znear; +cvar_t *r_znear; -cvar_t *r_skipBackEnd; +cvar_t *r_skipBackEnd; -cvar_t *r_measureOverdraw; +cvar_t *r_measureOverdraw; -cvar_t *r_fastsky; -cvar_t *r_drawSun; -cvar_t *r_dynamiclight; +cvar_t *r_fastsky; +cvar_t *r_drawSun; +cvar_t *r_dynamiclight; // rjr - removed for hacking cvar_t *r_dlightBacks; -cvar_t *r_lodbias; -cvar_t *r_lodscale; - -cvar_t *r_norefresh; -cvar_t *r_drawentities; -cvar_t *r_drawworld; -cvar_t *r_drawfog; -cvar_t *r_speeds; -cvar_t *r_fullbright; -cvar_t *r_novis; -cvar_t *r_nocull; -cvar_t *r_facePlaneCull; -cvar_t *r_showcluster; -cvar_t *r_nocurves; - -cvar_t *r_dlightStyle; -cvar_t *r_surfaceSprites; -cvar_t *r_surfaceWeather; - -cvar_t *r_windSpeed; -cvar_t *r_windAngle; -cvar_t *r_windGust; -cvar_t *r_windDampFactor; -cvar_t *r_windPointForce; -cvar_t *r_windPointX; -cvar_t *r_windPointY; - -cvar_t *r_allowExtensions; - -cvar_t *r_ext_compressed_textures; -cvar_t *r_ext_compressed_lightmaps; -cvar_t *r_ext_preferred_tc_method; -cvar_t *r_ext_gamma_control; -cvar_t *r_ext_multitexture; -cvar_t *r_ext_compiled_vertex_array; -cvar_t *r_ext_texture_env_add; -cvar_t *r_ext_texture_filter_anisotropic; - -cvar_t *r_DynamicGlow; -cvar_t *r_DynamicGlowPasses; -cvar_t *r_DynamicGlowDelta; -cvar_t *r_DynamicGlowIntensity; -cvar_t *r_DynamicGlowSoft; -cvar_t *r_DynamicGlowWidth; -cvar_t *r_DynamicGlowHeight; - -cvar_t *r_ignoreGLErrors; -cvar_t *r_logFile; - -cvar_t *r_primitives; -cvar_t *r_texturebits; -cvar_t *r_texturebitslm; - -cvar_t *r_lightmap; -cvar_t *r_vertexLight; -cvar_t *r_shadows; -cvar_t *r_shadowRange; -cvar_t *r_flares; -cvar_t *r_nobind; -cvar_t *r_singleShader; -cvar_t *r_colorMipLevels; -cvar_t *r_picmip; -cvar_t *r_showtris; -cvar_t *r_showtriscolor; -cvar_t *r_showsky; -cvar_t *r_shownormals; -cvar_t *r_finish; -cvar_t *r_clear; -cvar_t *r_textureMode; -cvar_t *r_offsetFactor; -cvar_t *r_offsetUnits; -cvar_t *r_gamma; -cvar_t *r_intensity; -cvar_t *r_lockpvs; -cvar_t *r_noportals; -cvar_t *r_portalOnly; - -cvar_t *r_subdivisions; -cvar_t *r_lodCurveError; - -cvar_t *r_overBrightBits; -cvar_t *r_mapOverBrightBits; - -cvar_t *r_debugSurface; -cvar_t *r_simpleMipMaps; - -cvar_t *r_showImages; - -cvar_t *r_ambientScale; -cvar_t *r_directedScale; -cvar_t *r_debugLight; -cvar_t *r_debugSort; -cvar_t *r_debugStyle; - -cvar_t *r_modelpoolmegs; - -cvar_t *r_noGhoul2; -cvar_t *r_Ghoul2AnimSmooth; -cvar_t *r_Ghoul2UnSqash; -cvar_t *r_Ghoul2TimeBase=0; -cvar_t *r_Ghoul2NoLerp; -cvar_t *r_Ghoul2NoBlend; -cvar_t *r_Ghoul2BlendMultiplier=0; -cvar_t *r_Ghoul2UnSqashAfterSmooth; - -cvar_t *broadsword; -cvar_t *broadsword_kickbones; -cvar_t *broadsword_kickorigin; -cvar_t *broadsword_playflop; -cvar_t *broadsword_dontstopanim; -cvar_t *broadsword_waitforshot; -cvar_t *broadsword_smallbbox; -cvar_t *broadsword_extra1; -cvar_t *broadsword_extra2; - -cvar_t *broadsword_effcorr; -cvar_t *broadsword_ragtobase; -cvar_t *broadsword_dircap; +cvar_t *r_lodbias; +cvar_t *r_lodscale; + +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawworld; +cvar_t *r_drawfog; +cvar_t *r_speeds; +cvar_t *r_fullbright; +cvar_t *r_novis; +cvar_t *r_nocull; +cvar_t *r_facePlaneCull; +cvar_t *r_showcluster; +cvar_t *r_nocurves; + +cvar_t *r_dlightStyle; +cvar_t *r_surfaceSprites; +cvar_t *r_surfaceWeather; + +cvar_t *r_windSpeed; +cvar_t *r_windAngle; +cvar_t *r_windGust; +cvar_t *r_windDampFactor; +cvar_t *r_windPointForce; +cvar_t *r_windPointX; +cvar_t *r_windPointY; + +cvar_t *r_allowExtensions; + +cvar_t *r_ext_compressed_textures; +cvar_t *r_ext_compressed_lightmaps; +cvar_t *r_ext_preferred_tc_method; +cvar_t *r_ext_gamma_control; +cvar_t *r_ext_multitexture; +cvar_t *r_ext_compiled_vertex_array; +cvar_t *r_ext_texture_env_add; +cvar_t *r_ext_texture_filter_anisotropic; + +cvar_t *r_DynamicGlow; +cvar_t *r_DynamicGlowPasses; +cvar_t *r_DynamicGlowDelta; +cvar_t *r_DynamicGlowIntensity; +cvar_t *r_DynamicGlowSoft; +cvar_t *r_DynamicGlowWidth; +cvar_t *r_DynamicGlowHeight; + +cvar_t *r_ignoreGLErrors; +cvar_t *r_logFile; + +cvar_t *r_primitives; +cvar_t *r_texturebits; +cvar_t *r_texturebitslm; + +cvar_t *r_lightmap; +cvar_t *r_vertexLight; +cvar_t *r_shadows; +cvar_t *r_shadowRange; +cvar_t *r_flares; +cvar_t *r_nobind; +cvar_t *r_singleShader; +cvar_t *r_colorMipLevels; +cvar_t *r_picmip; +cvar_t *r_showtris; +cvar_t *r_showtriscolor; +cvar_t *r_showsky; +cvar_t *r_shownormals; +cvar_t *r_finish; +cvar_t *r_clear; +cvar_t *r_textureMode; +cvar_t *r_offsetFactor; +cvar_t *r_offsetUnits; +cvar_t *r_gamma; +cvar_t *r_intensity; +cvar_t *r_lockpvs; +cvar_t *r_noportals; +cvar_t *r_portalOnly; + +cvar_t *r_subdivisions; +cvar_t *r_lodCurveError; + +cvar_t *r_overBrightBits; +cvar_t *r_mapOverBrightBits; + +cvar_t *r_debugSurface; +cvar_t *r_simpleMipMaps; + +cvar_t *r_showImages; + +cvar_t *r_ambientScale; +cvar_t *r_directedScale; +cvar_t *r_debugLight; +cvar_t *r_debugSort; +cvar_t *r_debugStyle; + +cvar_t *r_modelpoolmegs; + +cvar_t *r_noGhoul2; +cvar_t *r_Ghoul2AnimSmooth; +cvar_t *r_Ghoul2UnSqash; +cvar_t *r_Ghoul2TimeBase = 0; +cvar_t *r_Ghoul2NoLerp; +cvar_t *r_Ghoul2NoBlend; +cvar_t *r_Ghoul2BlendMultiplier = 0; +cvar_t *r_Ghoul2UnSqashAfterSmooth; + +cvar_t *broadsword; +cvar_t *broadsword_kickbones; +cvar_t *broadsword_kickorigin; +cvar_t *broadsword_playflop; +cvar_t *broadsword_dontstopanim; +cvar_t *broadsword_waitforshot; +cvar_t *broadsword_smallbbox; +cvar_t *broadsword_extra1; +cvar_t *broadsword_extra2; + +cvar_t *broadsword_effcorr; +cvar_t *broadsword_ragtobase; +cvar_t *broadsword_dircap; // More bullshit needed for the proper modular renderer --eez -cvar_t *sv_mapname; -cvar_t *sv_mapChecksum; -cvar_t *se_language; // JKA +cvar_t *sv_mapname; +cvar_t *sv_mapChecksum; +cvar_t *se_language; // JKA #ifdef JK2_MODE -cvar_t *sp_language; // JK2 +cvar_t *sp_language; // JK2 #endif -cvar_t *com_buildScript; +cvar_t *com_buildScript; -cvar_t *r_environmentMapping; +cvar_t *r_environmentMapping; cvar_t *r_screenshotJpegQuality; #if !defined(__APPLE__) @@ -235,22 +235,18 @@ bool g_bTextureRectangleHack = false; void RE_SetLightStyle(int style, int color); -void R_Splash() -{ - image_t *pImage = R_FindImageFile( "menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); +void R_Splash() { + image_t *pImage = R_FindImageFile("menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); - if ( !pImage ) - { + if (!pImage) { // Can't find the splash image so just clear to black - qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); - qglClear( GL_COLOR_BUFFER_BIT ); - } - else - { - extern void RB_SetGL2D (void); + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); + qglClear(GL_COLOR_BUFFER_BIT); + } else { + extern void RB_SetGL2D(void); RB_SetGL2D(); - GL_Bind( pImage ); + GL_Bind(pImage); GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); const int width = 640; @@ -260,19 +256,19 @@ void R_Splash() const float y1 = 240 - height / 2; const float y2 = 240 + height / 2; - qglBegin (GL_TRIANGLE_STRIP); - qglTexCoord2f( 0, 0 ); - qglVertex2f(x1, y1); - qglTexCoord2f( 1 , 0 ); - qglVertex2f(x2, y1); - qglTexCoord2f( 0, 1 ); - qglVertex2f(x1, y2); - qglTexCoord2f( 1, 1 ); - qglVertex2f(x2, y2); + qglBegin(GL_TRIANGLE_STRIP); + qglTexCoord2f(0, 0); + qglVertex2f(x1, y1); + qglTexCoord2f(1, 0); + qglVertex2f(x2, y1); + qglTexCoord2f(0, 1); + qglVertex2f(x1, y2); + qglTexCoord2f(1, 1); + qglVertex2f(x2, y2); qglEnd(); } - ri.WIN_Present( &window ); + ri.WIN_Present(&window); } /* @@ -281,104 +277,75 @@ void R_Splash() Cannot use strstr directly to differentiate between (for eg) reg_combiners and reg_combiners2 */ -static void GLW_InitTextureCompression( void ) -{ +static void GLW_InitTextureCompression(void) { bool newer_tc, old_tc; // Check for available tc methods. newer_tc = ri.GL_ExtensionSupported("GL_ARB_texture_compression") && ri.GL_ExtensionSupported("GL_EXT_texture_compression_s3tc"); old_tc = ri.GL_ExtensionSupported("GL_S3_s3tc"); - if ( old_tc ) - { - Com_Printf ("...GL_S3_s3tc available\n" ); + if (old_tc) { + Com_Printf("...GL_S3_s3tc available\n"); } - if ( newer_tc ) - { - Com_Printf ("...GL_EXT_texture_compression_s3tc available\n" ); + if (newer_tc) { + Com_Printf("...GL_EXT_texture_compression_s3tc available\n"); } - if ( !r_ext_compressed_textures->value ) - { + if (!r_ext_compressed_textures->value) { // Compressed textures are off glConfig.textureCompression = TC_NONE; - Com_Printf ("...ignoring texture compression\n" ); - } - else if ( !old_tc && !newer_tc ) - { + Com_Printf("...ignoring texture compression\n"); + } else if (!old_tc && !newer_tc) { // Requesting texture compression, but no method found glConfig.textureCompression = TC_NONE; - Com_Printf ("...no supported texture compression method found\n" ); - Com_Printf (".....ignoring texture compression\n" ); - } - else - { + Com_Printf("...no supported texture compression method found\n"); + Com_Printf(".....ignoring texture compression\n"); + } else { // some form of supported texture compression is avaiable, so see if the user has a preference - if ( r_ext_preferred_tc_method->integer == TC_NONE ) - { + if (r_ext_preferred_tc_method->integer == TC_NONE) { // No preference, so pick the best - if ( newer_tc ) - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_S3_s3tc\n" ); + } else { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } - } - else - { + } else { // User has specified a preference, now see if this request can be honored - if ( old_tc && newer_tc ) - { + if (old_tc && newer_tc) { // both are avaiable, so we can use the desired tc method - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { - Com_Printf ("...using preferred tc method, GL_S3_s3tc\n" ); + if (r_ext_preferred_tc_method->integer == TC_S3TC) { + Com_Printf("...using preferred tc method, GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { - Com_Printf ("...using preferred tc method, GL_EXT_texture_compression_s3tc\n" ); + } else { + Com_Printf("...using preferred tc method, GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Both methods are not available, so this gets trickier - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { + if (r_ext_preferred_tc_method->integer == TC_S3TC) { // Preferring to user older compression - if ( old_tc ) - { - Com_Printf ("...using GL_S3_s3tc\n" ); + if (old_tc) { + Com_Printf("...using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_S3_s3tc not available\n" ); - Com_Printf (".....falling back to GL_EXT_texture_compression_s3tc\n" ); + Com_Printf("...preferred tc method, GL_S3_s3tc not available\n"); + Com_Printf(".....falling back to GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Preferring to user newer compression - if ( newer_tc ) - { - Com_Printf ("...using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n" ); - Com_Printf (".....falling back to GL_S3_s3tc\n" ); + Com_Printf("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n"); + Com_Printf(".....falling back to GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } } @@ -393,182 +360,145 @@ GLimp_InitExtensions =============== */ extern bool g_bDynamicGlowSupported; -static void GLimp_InitExtensions( void ) -{ - if ( !r_allowExtensions->integer ) - { - Com_Printf ("*** IGNORING OPENGL EXTENSIONS ***\n" ); +static void GLimp_InitExtensions(void) { + if (!r_allowExtensions->integer) { + Com_Printf("*** IGNORING OPENGL EXTENSIONS ***\n"); g_bDynamicGlowSupported = false; - ri.Cvar_Set( "r_DynamicGlow","0" ); + ri.Cvar_Set("r_DynamicGlow", "0"); return; } - Com_Printf ("Initializing OpenGL extensions\n" ); + Com_Printf("Initializing OpenGL extensions\n"); // Select our tc scheme GLW_InitTextureCompression(); // GL_EXT_texture_env_add glConfig.textureEnvAddAvailable = qfalse; - if ( ri.GL_ExtensionSupported( "GL_EXT_texture_env_add" ) ) - { - if ( r_ext_texture_env_add->integer ) - { + if (ri.GL_ExtensionSupported("GL_EXT_texture_env_add")) { + if (r_ext_texture_env_add->integer) { glConfig.textureEnvAddAvailable = qtrue; - Com_Printf ("...using GL_EXT_texture_env_add\n" ); - } - else - { + Com_Printf("...using GL_EXT_texture_env_add\n"); + } else { glConfig.textureEnvAddAvailable = qfalse; - Com_Printf ("...ignoring GL_EXT_texture_env_add\n" ); + Com_Printf("...ignoring GL_EXT_texture_env_add\n"); } - } - else - { - Com_Printf ("...GL_EXT_texture_env_add not found\n" ); + } else { + Com_Printf("...GL_EXT_texture_env_add not found\n"); } // GL_EXT_texture_filter_anisotropic glConfig.maxTextureFilterAnisotropy = 0; - if ( ri.GL_ExtensionSupported( "GL_EXT_texture_filter_anisotropic" ) ) - { - qglGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy ); - Com_Printf ("...GL_EXT_texture_filter_anisotropic available\n" ); - - if ( r_ext_texture_filter_anisotropic->integer > 1 ) - { - Com_Printf ("...using GL_EXT_texture_filter_anisotropic\n" ); - } - else - { - Com_Printf ("...ignoring GL_EXT_texture_filter_anisotropic\n" ); + if (ri.GL_ExtensionSupported("GL_EXT_texture_filter_anisotropic")) { + qglGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy); + Com_Printf("...GL_EXT_texture_filter_anisotropic available\n"); + + if (r_ext_texture_filter_anisotropic->integer > 1) { + Com_Printf("...using GL_EXT_texture_filter_anisotropic\n"); + } else { + Com_Printf("...ignoring GL_EXT_texture_filter_anisotropic\n"); } - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); - if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) - { - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) { + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); } - } - else - { - Com_Printf ("...GL_EXT_texture_filter_anisotropic not found\n" ); - ri.Cvar_Set( "r_ext_texture_filter_anisotropic_avail", "0" ); + } else { + Com_Printf("...GL_EXT_texture_filter_anisotropic not found\n"); + ri.Cvar_Set("r_ext_texture_filter_anisotropic_avail", "0"); } // GL_EXT_clamp_to_edge glConfig.clampToEdgeAvailable = qtrue; - Com_Printf ("...using GL_EXT_texture_edge_clamp\n" ); + Com_Printf("...using GL_EXT_texture_edge_clamp\n"); // GL_ARB_multitexture qglMultiTexCoord2fARB = NULL; qglActiveTextureARB = NULL; qglClientActiveTextureARB = NULL; - if ( ri.GL_ExtensionSupported( "GL_ARB_multitexture" ) ) - { - if ( r_ext_multitexture->integer ) - { - qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) ri.GL_GetProcAddress( "glMultiTexCoord2fARB" ); - qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) ri.GL_GetProcAddress( "glActiveTextureARB" ); - qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) ri.GL_GetProcAddress( "glClientActiveTextureARB" ); - - if ( qglActiveTextureARB ) - { - qglGetIntegerv( GL_MAX_TEXTURE_UNITS_ARB, &glConfig.maxActiveTextures ); - - if ( glConfig.maxActiveTextures > 1 ) - { - Com_Printf ("...using GL_ARB_multitexture\n" ); - } - else - { + if (ri.GL_ExtensionSupported("GL_ARB_multitexture")) { + if (r_ext_multitexture->integer) { + qglMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC)ri.GL_GetProcAddress("glMultiTexCoord2fARB"); + qglActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)ri.GL_GetProcAddress("glActiveTextureARB"); + qglClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)ri.GL_GetProcAddress("glClientActiveTextureARB"); + + if (qglActiveTextureARB) { + qglGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &glConfig.maxActiveTextures); + + if (glConfig.maxActiveTextures > 1) { + Com_Printf("...using GL_ARB_multitexture\n"); + } else { qglMultiTexCoord2fARB = NULL; qglActiveTextureARB = NULL; qglClientActiveTextureARB = NULL; - Com_Printf ("...not using GL_ARB_multitexture, < 2 texture units\n" ); + Com_Printf("...not using GL_ARB_multitexture, < 2 texture units\n"); } } + } else { + Com_Printf("...ignoring GL_ARB_multitexture\n"); } - else - { - Com_Printf ("...ignoring GL_ARB_multitexture\n" ); - } - } - else - { - Com_Printf ("...GL_ARB_multitexture not found\n" ); + } else { + Com_Printf("...GL_ARB_multitexture not found\n"); } // GL_EXT_compiled_vertex_array qglLockArraysEXT = NULL; qglUnlockArraysEXT = NULL; - if ( ri.GL_ExtensionSupported( "GL_EXT_compiled_vertex_array" ) ) - { - if ( r_ext_compiled_vertex_array->integer ) - { - Com_Printf ("...using GL_EXT_compiled_vertex_array\n" ); - qglLockArraysEXT = ( PFNGLLOCKARRAYSEXTPROC ) ri.GL_GetProcAddress( "glLockArraysEXT" ); - qglUnlockArraysEXT = ( PFNGLUNLOCKARRAYSEXTPROC ) ri.GL_GetProcAddress( "glUnlockArraysEXT" ); + if (ri.GL_ExtensionSupported("GL_EXT_compiled_vertex_array")) { + if (r_ext_compiled_vertex_array->integer) { + Com_Printf("...using GL_EXT_compiled_vertex_array\n"); + qglLockArraysEXT = (PFNGLLOCKARRAYSEXTPROC)ri.GL_GetProcAddress("glLockArraysEXT"); + qglUnlockArraysEXT = (PFNGLUNLOCKARRAYSEXTPROC)ri.GL_GetProcAddress("glUnlockArraysEXT"); if (!qglLockArraysEXT || !qglUnlockArraysEXT) { - Com_Error (ERR_FATAL, "bad getprocaddress"); + Com_Error(ERR_FATAL, "bad getprocaddress"); } + } else { + Com_Printf("...ignoring GL_EXT_compiled_vertex_array\n"); } - else - { - Com_Printf ("...ignoring GL_EXT_compiled_vertex_array\n" ); - } - } - else - { - Com_Printf ("...GL_EXT_compiled_vertex_array not found\n" ); + } else { + Com_Printf("...GL_EXT_compiled_vertex_array not found\n"); } bool bNVRegisterCombiners = false; // Register Combiners. - if ( ri.GL_ExtensionSupported( "GL_NV_register_combiners" ) ) - { + if (ri.GL_ExtensionSupported("GL_NV_register_combiners")) { // NOTE: This extension requires multitexture support (over 2 units). - if ( glConfig.maxActiveTextures >= 2 ) - { + if (glConfig.maxActiveTextures >= 2) { bNVRegisterCombiners = true; // Register Combiners function pointer address load. - AReis // NOTE: VV guys will _definetly_ not be able to use regcoms. Pixel Shaders are just as good though :-) // NOTE: Also, this is an nVidia specific extension (of course), so fragment shaders would serve the same purpose // if we needed some kind of fragment/pixel manipulation support. - qglCombinerParameterfvNV = (PFNGLCOMBINERPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glCombinerParameterfvNV" ); - qglCombinerParameterivNV = (PFNGLCOMBINERPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glCombinerParameterivNV" ); - qglCombinerParameterfNV = (PFNGLCOMBINERPARAMETERFNVPROC)ri.GL_GetProcAddress( "glCombinerParameterfNV" ); - qglCombinerParameteriNV = (PFNGLCOMBINERPARAMETERINVPROC)ri.GL_GetProcAddress( "glCombinerParameteriNV" ); - qglCombinerInputNV = (PFNGLCOMBINERINPUTNVPROC)ri.GL_GetProcAddress( "glCombinerInputNV" ); - qglCombinerOutputNV = (PFNGLCOMBINEROUTPUTNVPROC)ri.GL_GetProcAddress( "glCombinerOutputNV" ); - qglFinalCombinerInputNV = (PFNGLFINALCOMBINERINPUTNVPROC)ri.GL_GetProcAddress( "glFinalCombinerInputNV" ); - qglGetCombinerInputParameterfvNV = (PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetCombinerInputParameterfvNV" ); - qglGetCombinerInputParameterivNV = (PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetCombinerInputParameterivNV" ); - qglGetCombinerOutputParameterfvNV = (PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetCombinerOutputParameterfvNV" ); - qglGetCombinerOutputParameterivNV = (PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetCombinerOutputParameterivNV" ); - qglGetFinalCombinerInputParameterfvNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetFinalCombinerInputParameterfvNV" ); - qglGetFinalCombinerInputParameterivNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetFinalCombinerInputParameterivNV" ); + qglCombinerParameterfvNV = (PFNGLCOMBINERPARAMETERFVNVPROC)ri.GL_GetProcAddress("glCombinerParameterfvNV"); + qglCombinerParameterivNV = (PFNGLCOMBINERPARAMETERIVNVPROC)ri.GL_GetProcAddress("glCombinerParameterivNV"); + qglCombinerParameterfNV = (PFNGLCOMBINERPARAMETERFNVPROC)ri.GL_GetProcAddress("glCombinerParameterfNV"); + qglCombinerParameteriNV = (PFNGLCOMBINERPARAMETERINVPROC)ri.GL_GetProcAddress("glCombinerParameteriNV"); + qglCombinerInputNV = (PFNGLCOMBINERINPUTNVPROC)ri.GL_GetProcAddress("glCombinerInputNV"); + qglCombinerOutputNV = (PFNGLCOMBINEROUTPUTNVPROC)ri.GL_GetProcAddress("glCombinerOutputNV"); + qglFinalCombinerInputNV = (PFNGLFINALCOMBINERINPUTNVPROC)ri.GL_GetProcAddress("glFinalCombinerInputNV"); + qglGetCombinerInputParameterfvNV = (PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetCombinerInputParameterfvNV"); + qglGetCombinerInputParameterivNV = (PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetCombinerInputParameterivNV"); + qglGetCombinerOutputParameterfvNV = (PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetCombinerOutputParameterfvNV"); + qglGetCombinerOutputParameterivNV = (PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetCombinerOutputParameterivNV"); + qglGetFinalCombinerInputParameterfvNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetFinalCombinerInputParameterfvNV"); + qglGetFinalCombinerInputParameterivNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetFinalCombinerInputParameterivNV"); // Validate the functions we need. - if ( !qglCombinerParameterfvNV || !qglCombinerParameterivNV || !qglCombinerParameterfNV || !qglCombinerParameteriNV || !qglCombinerInputNV || - !qglCombinerOutputNV || !qglFinalCombinerInputNV || !qglGetCombinerInputParameterfvNV || !qglGetCombinerInputParameterivNV || - !qglGetCombinerOutputParameterfvNV || !qglGetCombinerOutputParameterivNV || !qglGetFinalCombinerInputParameterfvNV || !qglGetFinalCombinerInputParameterivNV ) - { + if (!qglCombinerParameterfvNV || !qglCombinerParameterivNV || !qglCombinerParameterfNV || !qglCombinerParameteriNV || !qglCombinerInputNV || + !qglCombinerOutputNV || !qglFinalCombinerInputNV || !qglGetCombinerInputParameterfvNV || !qglGetCombinerInputParameterivNV || + !qglGetCombinerOutputParameterfvNV || !qglGetCombinerOutputParameterivNV || !qglGetFinalCombinerInputParameterfvNV || + !qglGetFinalCombinerInputParameterivNV) { bNVRegisterCombiners = false; qglCombinerParameterfvNV = NULL; qglCombinerParameteriNV = NULL; - Com_Printf ("...GL_NV_register_combiners failed\n" ); + Com_Printf("...GL_NV_register_combiners failed\n"); } - } - else - { + } else { bNVRegisterCombiners = false; - Com_Printf ("...ignoring GL_NV_register_combiners\n" ); + Com_Printf("...ignoring GL_NV_register_combiners\n"); } - } - else - { + } else { bNVRegisterCombiners = false; - Com_Printf ("...GL_NV_register_combiners not found\n" ); + Com_Printf("...GL_NV_register_combiners not found\n"); } // NOTE: Vertex and Fragment Programs are very dependant on each other - this is actually a @@ -577,106 +507,91 @@ static void GLimp_InitExtensions( void ) // Vertex Programs. bool bARBVertexProgram = false; - if ( ri.GL_ExtensionSupported( "GL_ARB_vertex_program" ) ) - { + if (ri.GL_ExtensionSupported("GL_ARB_vertex_program")) { bARBVertexProgram = true; - } - else - { + } else { bARBVertexProgram = false; - Com_Printf ("...GL_ARB_vertex_program not found\n" ); + Com_Printf("...GL_ARB_vertex_program not found\n"); } // Fragment Programs. bool bARBFragmentProgram = false; - if ( ri.GL_ExtensionSupported( "GL_ARB_fragment_program" ) ) - { + if (ri.GL_ExtensionSupported("GL_ARB_fragment_program")) { bARBFragmentProgram = true; - } - else - { + } else { bARBFragmentProgram = false; - Com_Printf ("...GL_ARB_fragment_program not found\n" ); + Com_Printf("...GL_ARB_fragment_program not found\n"); } // If we support one or the other, load the shared function pointers. - if ( bARBVertexProgram || bARBFragmentProgram ) - { - qglProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC) ri.GL_GetProcAddress("glProgramStringARB"); - qglBindProgramARB = (PFNGLBINDPROGRAMARBPROC) ri.GL_GetProcAddress("glBindProgramARB"); - qglDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC) ri.GL_GetProcAddress("glDeleteProgramsARB"); - qglGenProgramsARB = (PFNGLGENPROGRAMSARBPROC) ri.GL_GetProcAddress("glGenProgramsARB"); - qglProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4dARB"); - qglProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4dvARB"); - qglProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4fARB"); - qglProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4fvARB"); - qglProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4dARB"); - qglProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4dvARB"); - qglProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4fARB"); - qglProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4fvARB"); - qglGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC) ri.GL_GetProcAddress("glGetProgramEnvParameterdvARB"); - qglGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC) ri.GL_GetProcAddress("glGetProgramEnvParameterfvARB"); - qglGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) ri.GL_GetProcAddress("glGetProgramLocalParameterdvARB"); - qglGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) ri.GL_GetProcAddress("glGetProgramLocalParameterfvARB"); - qglGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC) ri.GL_GetProcAddress("glGetProgramivARB"); - qglGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC) ri.GL_GetProcAddress("glGetProgramStringARB"); - qglIsProgramARB = (PFNGLISPROGRAMARBPROC) ri.GL_GetProcAddress("glIsProgramARB"); + if (bARBVertexProgram || bARBFragmentProgram) { + qglProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)ri.GL_GetProcAddress("glProgramStringARB"); + qglBindProgramARB = (PFNGLBINDPROGRAMARBPROC)ri.GL_GetProcAddress("glBindProgramARB"); + qglDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)ri.GL_GetProcAddress("glDeleteProgramsARB"); + qglGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)ri.GL_GetProcAddress("glGenProgramsARB"); + qglProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4dARB"); + qglProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4dvARB"); + qglProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4fARB"); + qglProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4fvARB"); + qglProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4dARB"); + qglProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4dvARB"); + qglProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4fARB"); + qglProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4fvARB"); + qglGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC)ri.GL_GetProcAddress("glGetProgramEnvParameterdvARB"); + qglGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC)ri.GL_GetProcAddress("glGetProgramEnvParameterfvARB"); + qglGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC)ri.GL_GetProcAddress("glGetProgramLocalParameterdvARB"); + qglGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC)ri.GL_GetProcAddress("glGetProgramLocalParameterfvARB"); + qglGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC)ri.GL_GetProcAddress("glGetProgramivARB"); + qglGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC)ri.GL_GetProcAddress("glGetProgramStringARB"); + qglIsProgramARB = (PFNGLISPROGRAMARBPROC)ri.GL_GetProcAddress("glIsProgramARB"); // Validate the functions we need. - if ( !qglProgramStringARB || !qglBindProgramARB || !qglDeleteProgramsARB || !qglGenProgramsARB || - !qglProgramEnvParameter4dARB || !qglProgramEnvParameter4dvARB || !qglProgramEnvParameter4fARB || - !qglProgramEnvParameter4fvARB || !qglProgramLocalParameter4dARB || !qglProgramLocalParameter4dvARB || - !qglProgramLocalParameter4fARB || !qglProgramLocalParameter4fvARB || !qglGetProgramEnvParameterdvARB || - !qglGetProgramEnvParameterfvARB || !qglGetProgramLocalParameterdvARB || !qglGetProgramLocalParameterfvARB || - !qglGetProgramivARB || !qglGetProgramStringARB || !qglIsProgramARB ) - { + if (!qglProgramStringARB || !qglBindProgramARB || !qglDeleteProgramsARB || !qglGenProgramsARB || !qglProgramEnvParameter4dARB || + !qglProgramEnvParameter4dvARB || !qglProgramEnvParameter4fARB || !qglProgramEnvParameter4fvARB || !qglProgramLocalParameter4dARB || + !qglProgramLocalParameter4dvARB || !qglProgramLocalParameter4fARB || !qglProgramLocalParameter4fvARB || !qglGetProgramEnvParameterdvARB || + !qglGetProgramEnvParameterfvARB || !qglGetProgramLocalParameterdvARB || !qglGetProgramLocalParameterfvARB || !qglGetProgramivARB || + !qglGetProgramStringARB || !qglIsProgramARB) { bARBVertexProgram = false; bARBFragmentProgram = false; - qglGenProgramsARB = NULL; //clear ptrs that get checked + qglGenProgramsARB = NULL; // clear ptrs that get checked qglProgramEnvParameter4fARB = NULL; - Com_Printf ("...ignoring GL_ARB_vertex_program\n" ); - Com_Printf ("...ignoring GL_ARB_fragment_program\n" ); + Com_Printf("...ignoring GL_ARB_vertex_program\n"); + Com_Printf("...ignoring GL_ARB_fragment_program\n"); } } // Figure out which texture rectangle extension to use. bool bTexRectSupported = false; - if ( Q_stricmpn( glConfig.vendor_string, "ATI Technologies",16 )==0 - && Q_stricmpn( glConfig.version_string, "1.3.3",5 )==0 - && glConfig.version_string[5] < '9' ) //1.3.34 and 1.3.37 and 1.3.38 are broken for sure, 1.3.39 is not + if (Q_stricmpn(glConfig.vendor_string, "ATI Technologies", 16) == 0 && Q_stricmpn(glConfig.version_string, "1.3.3", 5) == 0 && + glConfig.version_string[5] < '9') // 1.3.34 and 1.3.37 and 1.3.38 are broken for sure, 1.3.39 is not { g_bTextureRectangleHack = true; } - if ( ri.GL_ExtensionSupported( "GL_NV_texture_rectangle" ) || ri.GL_ExtensionSupported( "GL_EXT_texture_rectangle" ) ) - { + if (ri.GL_ExtensionSupported("GL_NV_texture_rectangle") || ri.GL_ExtensionSupported("GL_EXT_texture_rectangle")) { bTexRectSupported = true; } - // Find out how many general combiners they have. - #define GL_MAX_GENERAL_COMBINERS_NV 0x854D +// Find out how many general combiners they have. +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D GLint iNumGeneralCombiners = 0; - if(bNVRegisterCombiners) - qglGetIntegerv( GL_MAX_GENERAL_COMBINERS_NV, &iNumGeneralCombiners ); + if (bNVRegisterCombiners) + qglGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &iNumGeneralCombiners); // Only allow dynamic glows/flares if they have the hardware - if ( bTexRectSupported && bARBVertexProgram && qglActiveTextureARB && glConfig.maxActiveTextures >= 4 && - ( ( bNVRegisterCombiners && iNumGeneralCombiners >= 2 ) || bARBFragmentProgram ) ) - { + if (bTexRectSupported && bARBVertexProgram && qglActiveTextureARB && glConfig.maxActiveTextures >= 4 && + ((bNVRegisterCombiners && iNumGeneralCombiners >= 2) || bARBFragmentProgram)) { g_bDynamicGlowSupported = true; // this would overwrite any achived setting gwg // ri.Cvar_Set( "r_DynamicGlow", "1" ); - } - else - { + } else { g_bDynamicGlowSupported = false; - ri.Cvar_Set( "r_DynamicGlow","0" ); + ri.Cvar_Set("r_DynamicGlow", "0"); } #if !defined(__APPLE__) qglStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)ri.GL_GetProcAddress("glStencilOpSeparate"); - if (qglStencilOpSeparate) - { + if (qglStencilOpSeparate) { glConfig.doStencilShadowsInOneDrawcall = qtrue; } #else @@ -692,8 +607,7 @@ static void GLimp_InitExtensions( void ) ** setting variables, checking GL constants, and reporting the gfx system config ** to the user. */ -static void InitOpenGL( void ) -{ +static void InitOpenGL(void) { // // initialize OS specific portions of the renderer // @@ -705,34 +619,31 @@ static void InitOpenGL( void ) // - r_gamma // - if ( glConfig.vidWidth == 0 ) - { - windowDesc_t windowDesc = { GRAPHICS_API_OPENGL }; + if (glConfig.vidWidth == 0) { + windowDesc_t windowDesc = {GRAPHICS_API_OPENGL}; memset(&glConfig, 0, sizeof(glConfig)); window = ri.WIN_Init(&windowDesc, &glConfig); // get our config strings - glConfig.vendor_string = (const char *)qglGetString (GL_VENDOR); - glConfig.renderer_string = (const char *)qglGetString (GL_RENDERER); - glConfig.version_string = (const char *)qglGetString (GL_VERSION); - glConfig.extensions_string = (const char *)qglGetString (GL_EXTENSIONS); + glConfig.vendor_string = (const char *)qglGetString(GL_VENDOR); + glConfig.renderer_string = (const char *)qglGetString(GL_RENDERER); + glConfig.version_string = (const char *)qglGetString(GL_VERSION); + glConfig.extensions_string = (const char *)qglGetString(GL_EXTENSIONS); // OpenGL driver constants - qglGetIntegerv( GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize ); + qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize); // stubbed or broken drivers may have reported 0... glConfig.maxTextureSize = Q_max(0, glConfig.maxTextureSize); // initialize extensions - GLimp_InitExtensions( ); + GLimp_InitExtensions(); // set default state GL_SetDefaultState(); - R_Splash(); //get something on screen asap - } - else - { + R_Splash(); // get something on screen asap + } else { // set default state GL_SetDefaultState(); } @@ -743,42 +654,42 @@ static void InitOpenGL( void ) GL_CheckErrors ================== */ -void GL_CheckErrors( void ) { - int err; - char s[64]; - - err = qglGetError(); - if ( err == GL_NO_ERROR ) { - return; - } - if ( r_ignoreGLErrors->integer ) { - return; - } - switch( err ) { - case GL_INVALID_ENUM: - strcpy( s, "GL_INVALID_ENUM" ); - break; - case GL_INVALID_VALUE: - strcpy( s, "GL_INVALID_VALUE" ); - break; - case GL_INVALID_OPERATION: - strcpy( s, "GL_INVALID_OPERATION" ); - break; - case GL_STACK_OVERFLOW: - strcpy( s, "GL_STACK_OVERFLOW" ); - break; - case GL_STACK_UNDERFLOW: - strcpy( s, "GL_STACK_UNDERFLOW" ); - break; - case GL_OUT_OF_MEMORY: - strcpy( s, "GL_OUT_OF_MEMORY" ); - break; - default: - Com_sprintf( s, sizeof(s), "%i", err); - break; - } - - Com_Error( ERR_FATAL, "GL_CheckErrors: %s", s ); +void GL_CheckErrors(void) { + int err; + char s[64]; + + err = qglGetError(); + if (err == GL_NO_ERROR) { + return; + } + if (r_ignoreGLErrors->integer) { + return; + } + switch (err) { + case GL_INVALID_ENUM: + strcpy(s, "GL_INVALID_ENUM"); + break; + case GL_INVALID_VALUE: + strcpy(s, "GL_INVALID_VALUE"); + break; + case GL_INVALID_OPERATION: + strcpy(s, "GL_INVALID_OPERATION"); + break; + case GL_STACK_OVERFLOW: + strcpy(s, "GL_STACK_OVERFLOW"); + break; + case GL_STACK_UNDERFLOW: + strcpy(s, "GL_STACK_UNDERFLOW"); + break; + case GL_OUT_OF_MEMORY: + strcpy(s, "GL_OUT_OF_MEMORY"); + break; + default: + Com_sprintf(s, sizeof(s), "%i", err); + break; + } + + Com_Error(ERR_FATAL, "GL_CheckErrors: %s", s); } /* @@ -807,8 +718,7 @@ Return value must be freed with Hunk_FreeTempMemory() ================== */ -byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen) -{ +byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen) { byte *buffer, *bufstart; int padwidth, linelen; GLint packAlign; @@ -819,9 +729,9 @@ byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *pa padwidth = PAD(linelen, packAlign); // Allocate a few more bytes so that we can choose an alignment we like - buffer = (byte *) R_Malloc(padwidth * height + *offset + packAlign - 1, TAG_TEMP_WORKSPACE, qfalse); + buffer = (byte *)R_Malloc(padwidth * height + *offset + packAlign - 1, TAG_TEMP_WORKSPACE, qfalse); - bufstart = (byte *)PADP((intptr_t) buffer + *offset, packAlign); + bufstart = (byte *)PADP((intptr_t)buffer + *offset, packAlign); qglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, bufstart); *offset = bufstart - buffer; @@ -835,7 +745,7 @@ byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *pa R_TakeScreenshot ================== */ -void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { +void R_TakeScreenshot(int x, int y, int width, int height, char *fileName) { byte *allbuf, *buffer; byte *srcptr, *destptr; byte *endline, *endmem; @@ -847,13 +757,13 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { allbuf = RB_ReadPixels(x, y, width, height, &offset, &padlen); buffer = allbuf + offset - 18; - Com_Memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type + Com_Memset(buffer, 0, 18); + buffer[2] = 2; // uncompressed type buffer[12] = width & 255; buffer[13] = width >> 8; buffer[14] = height & 255; buffer[15] = height >> 8; - buffer[16] = 24; // pixel size + buffer[16] = 24; // pixel size // swap rgb to bgr and remove padding from line endings linelen = width * 3; @@ -861,12 +771,10 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { srcptr = destptr = allbuf + offset; endmem = srcptr + (linelen + padlen) * height; - while(srcptr < endmem) - { + while (srcptr < endmem) { endline = srcptr + linelen; - while(srcptr < endline) - { + while (srcptr < endline) { temp = srcptr[0]; *destptr++ = srcptr[2]; *destptr++ = srcptr[1]; @@ -882,7 +790,7 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { memcount = linelen * height; // gamma correct - if(glConfig.deviceSupportsGamma) + if (glConfig.deviceSupportsGamma) R_GammaCorrect(allbuf + offset, memcount); ri.FS_WriteFile(fileName, buffer, memcount + 18); @@ -895,14 +803,14 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { R_TakeScreenshotPNG ================== */ -void R_TakeScreenshotPNG( int x, int y, int width, int height, char *fileName ) { - byte *buffer=NULL; - size_t offset=0; - int padlen=0; - - buffer = RB_ReadPixels( x, y, width, height, &offset, &padlen ); - RE_SavePNG( fileName, buffer, width, height, 3 ); - R_Free( buffer ); +void R_TakeScreenshotPNG(int x, int y, int width, int height, char *fileName) { + byte *buffer = NULL; + size_t offset = 0; + int padlen = 0; + + buffer = RB_ReadPixels(x, y, width, height, &offset, &padlen); + RE_SavePNG(fileName, buffer, width, height, 3); + R_Free(buffer); } /* @@ -910,7 +818,7 @@ void R_TakeScreenshotPNG( int x, int y, int width, int height, char *fileName ) R_TakeScreenshotJPEG ================== */ -void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) { +void R_TakeScreenshotJPEG(int x, int y, int width, int height, char *fileName) { byte *buffer; size_t offset = 0, memcount; int padlen; @@ -919,7 +827,7 @@ void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) memcount = (width * 3 + padlen) * height; // gamma correct - if(glConfig.deviceSupportsGamma) + if (glConfig.deviceSupportsGamma) R_GammaCorrect(buffer + offset, memcount); RE_SaveJPG(fileName, r_screenshotJpegQuality->integer, width, height, buffer + offset, padlen); @@ -931,14 +839,14 @@ void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) R_ScreenshotFilename ================== */ -void R_ScreenshotFilename( char *buf, int bufSize, const char *ext ) { +void R_ScreenshotFilename(char *buf, int bufSize, const char *ext) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "screenshots/shot%s%s", timeStr, ext ); + Com_sprintf(buf, bufSize, "screenshots/shot%s%s", timeStr, ext); } /* @@ -950,47 +858,47 @@ the menu system, sampled down from full screen distorted images ==================== */ #define LEVELSHOTSIZE 256 -static void R_LevelShot( void ) { - char checkname[MAX_OSPATH]; - byte *buffer; - byte *source, *allsource; - byte *src, *dst; - size_t offset = 0; - int padlen; - int x, y; - int r, g, b; - float xScale, yScale; - int xx, yy; - - Com_sprintf( checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName ); +static void R_LevelShot(void) { + char checkname[MAX_OSPATH]; + byte *buffer; + byte *source, *allsource; + byte *src, *dst; + size_t offset = 0; + int padlen; + int x, y; + int r, g, b; + float xScale, yScale; + int xx, yy; + + Com_sprintf(checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName); allsource = RB_ReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, &offset, &padlen); source = allsource + offset; - buffer = (byte *) R_Malloc(LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18, TAG_TEMP_WORKSPACE, qfalse); - Com_Memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type + buffer = (byte *)R_Malloc(LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18, TAG_TEMP_WORKSPACE, qfalse); + Com_Memset(buffer, 0, 18); + buffer[2] = 2; // uncompressed type buffer[12] = LEVELSHOTSIZE & 255; buffer[13] = LEVELSHOTSIZE >> 8; buffer[14] = LEVELSHOTSIZE & 255; buffer[15] = LEVELSHOTSIZE >> 8; - buffer[16] = 24; // pixel size + buffer[16] = 24; // pixel size // resample from source - xScale = glConfig.vidWidth / (4.0*LEVELSHOTSIZE); - yScale = glConfig.vidHeight / (3.0*LEVELSHOTSIZE); - for ( y = 0 ; y < LEVELSHOTSIZE ; y++ ) { - for ( x = 0 ; x < LEVELSHOTSIZE ; x++ ) { + xScale = glConfig.vidWidth / (4.0 * LEVELSHOTSIZE); + yScale = glConfig.vidHeight / (3.0 * LEVELSHOTSIZE); + for (y = 0; y < LEVELSHOTSIZE; y++) { + for (x = 0; x < LEVELSHOTSIZE; x++) { r = g = b = 0; - for ( yy = 0 ; yy < 3 ; yy++ ) { - for ( xx = 0 ; xx < 4 ; xx++ ) { - src = source + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) ); + for (yy = 0; yy < 3; yy++) { + for (xx = 0; xx < 4; xx++) { + src = source + 3 * (glConfig.vidWidth * (int)((y * 3 + yy) * yScale) + (int)((x * 4 + xx) * xScale)); r += src[0]; g += src[1]; b += src[2]; } } - dst = buffer + 18 + 3 * ( y * LEVELSHOTSIZE + x ); + dst = buffer + 18 + 3 * (y * LEVELSHOTSIZE + x); dst[0] = b / 12; dst[1] = g / 12; dst[2] = r / 12; @@ -998,16 +906,16 @@ static void R_LevelShot( void ) { } // gamma correct - if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) { - R_GammaCorrect( buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 ); + if ((tr.overbrightBits > 0) && glConfig.deviceSupportsGamma) { + R_GammaCorrect(buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3); } - ri.FS_WriteFile( checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18 ); + ri.FS_WriteFile(checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18); - R_Free( buffer ); - R_Free( allsource ); + R_Free(buffer); + R_Free(allsource); - Com_Printf ("Wrote %s\n", checkname ); + Com_Printf("Wrote %s\n", checkname); } /* @@ -1022,36 +930,35 @@ screenshot [filename] Doesn't print the pacifier message if there is a second arg ================== */ -void R_ScreenShotTGA_f (void) { +void R_ScreenShotTGA_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.tga", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.tga", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".tga" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".tga"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshot(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - Com_Printf( "Wrote %s\n", checkname ); + if (!silent) + Com_Printf("Wrote %s\n", checkname); } /* @@ -1066,67 +973,65 @@ screenshot [filename] Doesn't print the pacifier message if there is a second arg ================== */ -void R_ScreenShotPNG_f (void) { +void R_ScreenShotPNG_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.png", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.png", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".png" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".png"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshotPNG( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshotPNG(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - Com_Printf( "Wrote %s\n", checkname ); + if (!silent) + Com_Printf("Wrote %s\n", checkname); } -void R_ScreenShot_f (void) { +void R_ScreenShot_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.jpg", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.jpg", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".jpg" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".jpg"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n" ); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshotJPEG( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshotJPEG(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - Com_Printf( "Wrote %s\n", checkname ); + if (!silent) + Com_Printf("Wrote %s\n", checkname); } //============================================================================ @@ -1134,51 +1039,49 @@ void R_ScreenShot_f (void) { /* ** GL_SetDefaultState */ -void GL_SetDefaultState( void ) -{ - qglClearDepth( 1.0f ); +void GL_SetDefaultState(void) { + qglClearDepth(1.0f); qglCullFace(GL_FRONT); - qglColor4f (1,1,1,1); + qglColor4f(1, 1, 1, 1); // initialize downstream texture unit if we're running // in a multitexture environment - if ( qglActiveTextureARB ) { - GL_SelectTexture( 1 ); - GL_TextureMode( r_textureMode->string ); - GL_TexEnv( GL_MODULATE ); - qglDisable( GL_TEXTURE_2D ); - GL_SelectTexture( 0 ); + if (qglActiveTextureARB) { + GL_SelectTexture(1); + GL_TextureMode(r_textureMode->string); + GL_TexEnv(GL_MODULATE); + qglDisable(GL_TEXTURE_2D); + GL_SelectTexture(0); } qglEnable(GL_TEXTURE_2D); - GL_TextureMode( r_textureMode->string ); - GL_TexEnv( GL_MODULATE ); + GL_TextureMode(r_textureMode->string); + GL_TexEnv(GL_MODULATE); - qglShadeModel( GL_SMOOTH ); - qglDepthFunc( GL_LEQUAL ); + qglShadeModel(GL_SMOOTH); + qglDepthFunc(GL_LEQUAL); // the vertex array is always enabled, but the color and texture // arrays are enabled and disabled around the compiled vertex array call - qglEnableClientState (GL_VERTEX_ARRAY); + qglEnableClientState(GL_VERTEX_ARRAY); // // make sure our GL state vector is set correctly // glState.glStateBits = GLS_DEPTHTEST_DISABLE | GLS_DEPTHMASK_TRUE; - qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - qglDepthMask( GL_TRUE ); - qglDisable( GL_DEPTH_TEST ); - qglEnable( GL_SCISSOR_TEST ); - qglDisable( GL_CULL_FACE ); - qglDisable( GL_BLEND ); - qglDisable( GL_ALPHA_TEST ); - qglBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + qglDepthMask(GL_TRUE); + qglDisable(GL_DEPTH_TEST); + qglEnable(GL_SCISSOR_TEST); + qglDisable(GL_CULL_FACE); + qglDisable(GL_BLEND); + qglDisable(GL_ALPHA_TEST); + qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } - /* ================ R_PrintLongString @@ -1186,14 +1089,12 @@ R_PrintLongString Workaround for Com_Printf's 1024 characters buffer limit. ================ */ -void R_PrintLongString(const char *string) -{ +void R_PrintLongString(const char *string) { char buffer[1024]; const char *p = string; int remainingLength = strlen(string); - while (remainingLength > 0) - { + while (remainingLength > 0) { // Take as much characters as possible from the string without splitting words between buffers // This avoids the client console splitting a word up when one half fits on the current line, // but the second half would have to be written on a new line @@ -1210,8 +1111,8 @@ void R_PrintLongString(const char *string) charsToTake = remainingLength; } - Q_strncpyz( buffer, p, charsToTake + 1 ); - Com_Printf( "%s", buffer ); + Q_strncpyz(buffer, p, charsToTake + 1); + Com_Printf("%s", buffer); remainingLength -= charsToTake; p += charsToTake; } @@ -1224,26 +1125,12 @@ GfxInfo_f */ extern bool g_bTextureRectangleHack; -void GfxInfo_f( void ) -{ - const char *enablestrings[] = - { - "disabled", - "enabled" - }; - const char *fsstrings[] = - { - "windowed", - "fullscreen" - }; - const char *noborderstrings[] = - { - "", - "noborder " - }; +void GfxInfo_f(void) { + const char *enablestrings[] = {"disabled", "enabled"}; + const char *fsstrings[] = {"windowed", "fullscreen"}; + const char *noborderstrings[] = {"", "noborder "}; - const char *tc_table[] = - { + const char *tc_table[] = { "None", "GL_S3_s3tc", "GL_EXT_texture_compression_s3tc", @@ -1252,106 +1139,93 @@ void GfxInfo_f( void ) int fullscreen = ri.Cvar_VariableIntegerValue("r_fullscreen"); int noborder = ri.Cvar_VariableIntegerValue("r_noborder"); - ri.Printf( PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string ); - ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string ); - ri.Printf( PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string ); + ri.Printf(PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string); + ri.Printf(PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string); + ri.Printf(PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string); R_PrintLongString(glConfig.extensions_string); - Com_Printf ("\n"); - ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize ); - ri.Printf( PRINT_ALL, "GL_MAX_ACTIVE_TEXTURES_ARB: %d\n", glConfig.maxActiveTextures ); - ri.Printf( PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); - ri.Printf( PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", - ri.Cvar_VariableIntegerValue("r_mode"), - glConfig.vidWidth, glConfig.vidHeight, - fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], - fsstrings[fullscreen == 1] ); - if ( glConfig.displayFrequency ) - { - ri.Printf( PRINT_ALL, "%d\n", glConfig.displayFrequency ); - } - else - { - ri.Printf( PRINT_ALL, "N/A\n" ); - } - if ( glConfig.deviceSupportsGamma ) - { - ri.Printf( PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits ); - } - else - { - ri.Printf( PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits ); + Com_Printf("\n"); + ri.Printf(PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize); + ri.Printf(PRINT_ALL, "GL_MAX_ACTIVE_TEXTURES_ARB: %d\n", glConfig.maxActiveTextures); + ri.Printf(PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits); + ri.Printf(PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", ri.Cvar_VariableIntegerValue("r_mode"), glConfig.vidWidth, glConfig.vidHeight, + fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], fsstrings[fullscreen == 1]); + if (glConfig.displayFrequency) { + ri.Printf(PRINT_ALL, "%d\n", glConfig.displayFrequency); + } else { + ri.Printf(PRINT_ALL, "N/A\n"); + } + if (glConfig.deviceSupportsGamma) { + ri.Printf(PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits); + } else { + ri.Printf(PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits); } // rendering primitives { - int primitives; + int primitives; // default is to use triangles if compiled vertex arrays are present - ri.Printf( PRINT_ALL, "rendering primitives: " ); + ri.Printf(PRINT_ALL, "rendering primitives: "); primitives = r_primitives->integer; - if ( primitives == 0 ) { - if ( qglLockArraysEXT ) { + if (primitives == 0) { + if (qglLockArraysEXT) { primitives = 2; } else { primitives = 1; } } - if ( primitives == -1 ) { - ri.Printf( PRINT_ALL, "none\n" ); - } else if ( primitives == 2 ) { - ri.Printf( PRINT_ALL, "single glDrawElements\n" ); - } else if ( primitives == 1 ) { - ri.Printf( PRINT_ALL, "multiple glArrayElement\n" ); - } else if ( primitives == 3 ) { - ri.Printf( PRINT_ALL, "multiple glColor4ubv + glTexCoord2fv + glVertex3fv\n" ); + if (primitives == -1) { + ri.Printf(PRINT_ALL, "none\n"); + } else if (primitives == 2) { + ri.Printf(PRINT_ALL, "single glDrawElements\n"); + } else if (primitives == 1) { + ri.Printf(PRINT_ALL, "multiple glArrayElement\n"); + } else if (primitives == 3) { + ri.Printf(PRINT_ALL, "multiple glColor4ubv + glTexCoord2fv + glVertex3fv\n"); } } - ri.Printf( PRINT_ALL, "texturemode: %s\n", r_textureMode->string ); - ri.Printf( PRINT_ALL, "picmip: %d\n", r_picmip->integer ); - ri.Printf( PRINT_ALL, "texture bits: %d\n", r_texturebits->integer ); - if ( r_texturebitslm->integer > 0 ) - ri.Printf( PRINT_ALL, "lightmap texture bits: %d\n", r_texturebitslm->integer ); - ri.Printf( PRINT_ALL, "multitexture: %s\n", enablestrings[qglActiveTextureARB != 0] ); - ri.Printf( PRINT_ALL, "compiled vertex arrays: %s\n", enablestrings[qglLockArraysEXT != 0 ] ); - ri.Printf( PRINT_ALL, "texenv add: %s\n", enablestrings[glConfig.textureEnvAddAvailable != 0] ); - ri.Printf( PRINT_ALL, "compressed textures: %s\n", enablestrings[glConfig.textureCompression != TC_NONE] ); - ri.Printf( PRINT_ALL, "compressed lightmaps: %s\n", enablestrings[(r_ext_compressed_lightmaps->integer != 0 && glConfig.textureCompression != TC_NONE)] ); - ri.Printf( PRINT_ALL, "texture compression method: %s\n", tc_table[glConfig.textureCompression] ); - ri.Printf( PRINT_ALL, "anisotropic filtering: %s ", enablestrings[(r_ext_texture_filter_anisotropic->integer != 0) && glConfig.maxTextureFilterAnisotropy] ); - if (r_ext_texture_filter_anisotropic->integer != 0 && glConfig.maxTextureFilterAnisotropy) - { + ri.Printf(PRINT_ALL, "texturemode: %s\n", r_textureMode->string); + ri.Printf(PRINT_ALL, "picmip: %d\n", r_picmip->integer); + ri.Printf(PRINT_ALL, "texture bits: %d\n", r_texturebits->integer); + if (r_texturebitslm->integer > 0) + ri.Printf(PRINT_ALL, "lightmap texture bits: %d\n", r_texturebitslm->integer); + ri.Printf(PRINT_ALL, "multitexture: %s\n", enablestrings[qglActiveTextureARB != 0]); + ri.Printf(PRINT_ALL, "compiled vertex arrays: %s\n", enablestrings[qglLockArraysEXT != 0]); + ri.Printf(PRINT_ALL, "texenv add: %s\n", enablestrings[glConfig.textureEnvAddAvailable != 0]); + ri.Printf(PRINT_ALL, "compressed textures: %s\n", enablestrings[glConfig.textureCompression != TC_NONE]); + ri.Printf(PRINT_ALL, "compressed lightmaps: %s\n", enablestrings[(r_ext_compressed_lightmaps->integer != 0 && glConfig.textureCompression != TC_NONE)]); + ri.Printf(PRINT_ALL, "texture compression method: %s\n", tc_table[glConfig.textureCompression]); + ri.Printf(PRINT_ALL, "anisotropic filtering: %s ", enablestrings[(r_ext_texture_filter_anisotropic->integer != 0) && glConfig.maxTextureFilterAnisotropy]); + if (r_ext_texture_filter_anisotropic->integer != 0 && glConfig.maxTextureFilterAnisotropy) { if (Q_isintegral(r_ext_texture_filter_anisotropic->value)) - ri.Printf( PRINT_ALL, "(%i of ", (int)r_ext_texture_filter_anisotropic->value); + ri.Printf(PRINT_ALL, "(%i of ", (int)r_ext_texture_filter_anisotropic->value); else - ri.Printf( PRINT_ALL, "(%f of ", r_ext_texture_filter_anisotropic->value); + ri.Printf(PRINT_ALL, "(%f of ", r_ext_texture_filter_anisotropic->value); if (Q_isintegral(glConfig.maxTextureFilterAnisotropy)) - ri.Printf( PRINT_ALL, "%i)\n", (int)glConfig.maxTextureFilterAnisotropy); + ri.Printf(PRINT_ALL, "%i)\n", (int)glConfig.maxTextureFilterAnisotropy); else - ri.Printf( PRINT_ALL, "%f)\n", glConfig.maxTextureFilterAnisotropy); + ri.Printf(PRINT_ALL, "%f)\n", glConfig.maxTextureFilterAnisotropy); } - ri.Printf( PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_DynamicGlow->integer ? 1 : 0] ); - if (g_bTextureRectangleHack) Com_Printf ("Dynamic Glow ATI BAD DRIVER HACK %s\n", enablestrings[g_bTextureRectangleHack] ); + ri.Printf(PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_DynamicGlow->integer ? 1 : 0]); + if (g_bTextureRectangleHack) + Com_Printf("Dynamic Glow ATI BAD DRIVER HACK %s\n", enablestrings[g_bTextureRectangleHack]); - if ( r_finish->integer ) { - ri.Printf( PRINT_ALL, "Forcing glFinish\n" ); + if (r_finish->integer) { + ri.Printf(PRINT_ALL, "Forcing glFinish\n"); } int displayRefresh = ri.Cvar_VariableIntegerValue("r_displayRefresh"); - if ( displayRefresh ) { - ri.Printf( PRINT_ALL, "Display refresh set to %d\n", displayRefresh); + if (displayRefresh) { + ri.Printf(PRINT_ALL, "Display refresh set to %d\n", displayRefresh); } - if (tr.world) - { - ri.Printf( PRINT_ALL, "Light Grid size set to (%.2f %.2f %.2f)\n", tr.world->lightGridSize[0], tr.world->lightGridSize[1], tr.world->lightGridSize[2] ); + if (tr.world) { + ri.Printf(PRINT_ALL, "Light Grid size set to (%.2f %.2f %.2f)\n", tr.world->lightGridSize[0], tr.world->lightGridSize[1], tr.world->lightGridSize[2]); } } -void R_AtiHackToggle_f(void) -{ - g_bTextureRectangleHack = !g_bTextureRectangleHack; -} +void R_AtiHackToggle_f(void) { g_bTextureRectangleHack = !g_bTextureRectangleHack; } /************************************************************************************************ * R_FogDistance_f * @@ -1367,51 +1241,43 @@ void R_AtiHackToggle_f(void) * none * * * ************************************************************************************************/ -void R_FogDistance_f(void) -{ - float distance; +void R_FogDistance_f(void) { + float distance; - if (!tr.world) - { + if (!tr.world) { ri.Printf(PRINT_ALL, "R_FogDistance_f: World is not initialized\n"); return; } - if (tr.world->globalFog == -1) - { + if (tr.world->globalFog == -1) { ri.Printf(PRINT_ALL, "R_FogDistance_f: World does not have a global fog\n"); return; } - if (ri.Cmd_Argc() <= 1) - { -// should not ever be 0.0 -// if (tr.world->fogs[tr.world->globalFog].tcScale == 0.0) -// { -// distance = 0.0; -// } -// else - { - distance = 1.0 / (8.0 * tr.world->fogs[tr.world->globalFog].tcScale); - } + if (ri.Cmd_Argc() <= 1) { + // should not ever be 0.0 + // if (tr.world->fogs[tr.world->globalFog].tcScale == 0.0) + // { + // distance = 0.0; + // } + // else + { distance = 1.0 / (8.0 * tr.world->fogs[tr.world->globalFog].tcScale); } ri.Printf(PRINT_ALL, "R_FogDistance_f: Current Distance: %.0f\n", distance); return; } - if (ri.Cmd_Argc() != 2) - { + if (ri.Cmd_Argc() != 2) { ri.Printf(PRINT_ALL, "R_FogDistance_f: Invalid number of arguments to set distance\n"); return; } distance = atof(ri.Cmd_Argv(1)); - if (distance < 1.0) - { + if (distance < 1.0) { distance = 1.0; } tr.world->fogs[tr.world->globalFog].parms.depthForOpaque = distance; - tr.world->fogs[tr.world->globalFog].tcScale = 1.0 / ( distance * 8 ); + tr.world->fogs[tr.world->globalFog].tcScale = 1.0 / (distance * 8); } /************************************************************************************************ @@ -1427,33 +1293,25 @@ void R_FogDistance_f(void) * none * * * ************************************************************************************************/ -void R_FogColor_f(void) -{ - if (!tr.world) - { +void R_FogColor_f(void) { + if (!tr.world) { ri.Printf(PRINT_ALL, "R_FogColor_f: World is not initialized\n"); return; } - if (tr.world->globalFog == -1) - { + if (tr.world->globalFog == -1) { ri.Printf(PRINT_ALL, "R_FogColor_f: World does not have a global fog\n"); return; } - if (ri.Cmd_Argc() <= 1) - { - unsigned i = tr.world->fogs[tr.world->globalFog].colorInt; + if (ri.Cmd_Argc() <= 1) { + unsigned i = tr.world->fogs[tr.world->globalFog].colorInt; - ri.Printf(PRINT_ALL, "R_FogColor_f: Current Color: %0f %0f %0f\n", - ( (byte *)&i )[0] / 255.0, - ( (byte *)&i )[1] / 255.0, - ( (byte *)&i )[2] / 255.0); + ri.Printf(PRINT_ALL, "R_FogColor_f: Current Color: %0f %0f %0f\n", ((byte *)&i)[0] / 255.0, ((byte *)&i)[1] / 255.0, ((byte *)&i)[2] / 255.0); return; } - if (ri.Cmd_Argc() != 4) - { + if (ri.Cmd_Argc() != 4) { ri.Printf(PRINT_ALL, "R_FogColor_f: Invalid number of arguments to set color\n"); return; } @@ -1461,38 +1319,37 @@ void R_FogColor_f(void) tr.world->fogs[tr.world->globalFog].parms.color[0] = atof(ri.Cmd_Argv(1)); tr.world->fogs[tr.world->globalFog].parms.color[1] = atof(ri.Cmd_Argv(2)); tr.world->fogs[tr.world->globalFog].parms.color[2] = atof(ri.Cmd_Argv(3)); - tr.world->fogs[tr.world->globalFog].colorInt = ColorBytes4 ( atof(ri.Cmd_Argv(1)) * tr.identityLight, - atof(ri.Cmd_Argv(2)) * tr.identityLight, - atof(ri.Cmd_Argv(3)) * tr.identityLight, 1.0 ); + tr.world->fogs[tr.world->globalFog].colorInt = + ColorBytes4(atof(ri.Cmd_Argv(1)) * tr.identityLight, atof(ri.Cmd_Argv(2)) * tr.identityLight, atof(ri.Cmd_Argv(3)) * tr.identityLight, 1.0); } typedef struct consoleCommand_s { - const char *cmd; - xcommand_t func; + const char *cmd; + xcommand_t func; } consoleCommand_t; -void R_ReloadFonts_f( void ); - -static consoleCommand_t commands[] = { - { "imagelist", R_ImageList_f }, - { "shaderlist", R_ShaderList_f }, - { "skinlist", R_SkinList_f }, - { "fontlist", R_FontList_f }, - { "screenshot", R_ScreenShot_f }, - { "screenshot_png", R_ScreenShotPNG_f }, - { "screenshot_tga", R_ScreenShotTGA_f }, - { "gfxinfo", GfxInfo_f }, - { "r_atihack", R_AtiHackToggle_f }, - { "r_we", R_WorldEffect_f }, - { "imagecacheinfo", RE_RegisterImages_Info_f }, - { "modellist", R_Modellist_f }, - { "modelcacheinfo", RE_RegisterModels_Info_f }, - { "r_fogDistance", R_FogDistance_f }, - { "r_fogColor", R_FogColor_f }, - { "r_reloadfonts", R_ReloadFonts_f }, +void R_ReloadFonts_f(void); + +static consoleCommand_t commands[] = { + {"imagelist", R_ImageList_f}, + {"shaderlist", R_ShaderList_f}, + {"skinlist", R_SkinList_f}, + {"fontlist", R_FontList_f}, + {"screenshot", R_ScreenShot_f}, + {"screenshot_png", R_ScreenShotPNG_f}, + {"screenshot_tga", R_ScreenShotTGA_f}, + {"gfxinfo", GfxInfo_f}, + {"r_atihack", R_AtiHackToggle_f}, + {"r_we", R_WorldEffect_f}, + {"imagecacheinfo", RE_RegisterImages_Info_f}, + {"modellist", R_Modellist_f}, + {"modelcacheinfo", RE_RegisterModels_Info_f}, + {"r_fogDistance", R_FogDistance_f}, + {"r_fogColor", R_FogColor_f}, + {"r_reloadfonts", R_ReloadFonts_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); #ifdef _DEBUG #define MIN_PRIMITIVES -1 @@ -1506,193 +1363,188 @@ static const size_t numCommands = ARRAY_LEN( commands ); R_Register =============== */ -void R_Register( void ) -{ +void R_Register(void) { // // latched and archived variables // - r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compress_textures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_compressed_lightmaps = ri.Cvar_Get( "r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_preferred_tc_method = ri.Cvar_Get( "r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_gamma_control = ri.Cvar_Get( "r_ext_gamma_control", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); - r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); - r_ext_texture_filter_anisotropic = ri.Cvar_Get( "r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND ); - - r_DynamicGlow = ri.Cvar_Get( "r_DynamicGlow", "0", CVAR_ARCHIVE_ND ); - r_DynamicGlowPasses = ri.Cvar_Get( "r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND ); - r_DynamicGlowDelta = ri.Cvar_Get( "r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND ); - r_DynamicGlowIntensity = ri.Cvar_Get( "r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND ); - r_DynamicGlowSoft = ri.Cvar_Get( "r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND ); - r_DynamicGlowWidth = ri.Cvar_Get( "r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_DynamicGlowHeight = ri.Cvar_Get( "r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND | CVAR_LATCH ); - - r_picmip = ri.Cvar_Get ("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH ); - ri.Cvar_CheckRange( r_picmip, 0, 16, qtrue ); - r_colorMipLevels = ri.Cvar_Get ("r_colorMipLevels", "0", CVAR_LATCH ); - r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_texturebitslm = ri.Cvar_Get( "r_texturebitslm", "0", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_overBrightBits = ri.Cvar_Get ("r_overBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_mapOverBrightBits = ri.Cvar_Get( "r_mapOverBrightBits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE_ND | CVAR_LATCH ); - r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH ); - r_subdivisions = ri.Cvar_Get ("r_subdivisions", "4", CVAR_ARCHIVE_ND | CVAR_LATCH); - ri.Cvar_CheckRange( r_subdivisions, 0, 80, qfalse ); - r_intensity = ri.Cvar_Get ("r_intensity", "1", CVAR_LATCH|CVAR_ARCHIVE_ND ); + r_allowExtensions = ri.Cvar_Get("r_allowExtensions", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_compressed_textures = ri.Cvar_Get("r_ext_compress_textures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_compressed_lightmaps = ri.Cvar_Get("r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_preferred_tc_method = ri.Cvar_Get("r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_gamma_control = ri.Cvar_Get("r_ext_gamma_control", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_multitexture = ri.Cvar_Get("r_ext_multitexture", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_compiled_vertex_array = ri.Cvar_Get("r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_texture_env_add = ri.Cvar_Get("r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_texture_filter_anisotropic = ri.Cvar_Get("r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND); + + r_DynamicGlow = ri.Cvar_Get("r_DynamicGlow", "0", CVAR_ARCHIVE_ND); + r_DynamicGlowPasses = ri.Cvar_Get("r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND); + r_DynamicGlowDelta = ri.Cvar_Get("r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND); + r_DynamicGlowIntensity = ri.Cvar_Get("r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND); + r_DynamicGlowSoft = ri.Cvar_Get("r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND); + r_DynamicGlowWidth = ri.Cvar_Get("r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_DynamicGlowHeight = ri.Cvar_Get("r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND | CVAR_LATCH); + + r_picmip = ri.Cvar_Get("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH); + ri.Cvar_CheckRange(r_picmip, 0, 16, qtrue); + r_colorMipLevels = ri.Cvar_Get("r_colorMipLevels", "0", CVAR_LATCH); + r_detailTextures = ri.Cvar_Get("r_detailtextures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_texturebits = ri.Cvar_Get("r_texturebits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_texturebitslm = ri.Cvar_Get("r_texturebitslm", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_overBrightBits = ri.Cvar_Get("r_overBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_mapOverBrightBits = ri.Cvar_Get("r_mapOverBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_simpleMipMaps = ri.Cvar_Get("r_simpleMipMaps", "1", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_vertexLight = ri.Cvar_Get("r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH); + r_subdivisions = ri.Cvar_Get("r_subdivisions", "4", CVAR_ARCHIVE_ND | CVAR_LATCH); + ri.Cvar_CheckRange(r_subdivisions, 0, 80, qfalse); + r_intensity = ri.Cvar_Get("r_intensity", "1", CVAR_LATCH | CVAR_ARCHIVE_ND); // // temporary latched variables that can only change over a restart // - r_fullbright = ri.Cvar_Get ("r_fullbright", "0", CVAR_LATCH ); - r_singleShader = ri.Cvar_Get ("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH ); + r_fullbright = ri.Cvar_Get("r_fullbright", "0", CVAR_LATCH); + r_singleShader = ri.Cvar_Get("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH); // // archived variables that can change at any time // - r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE_ND ); - r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE_ND ); - r_flares = ri.Cvar_Get ("r_flares", "1", CVAR_ARCHIVE_ND ); - r_lodscale = ri.Cvar_Get( "r_lodscale", "10", CVAR_ARCHIVE_ND ); - - r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_ARCHIVE_ND ); //if set any lower, you lose a lot of precision in the distance - ri.Cvar_CheckRange( r_znear, 0.001f, 10, qfalse ); // was qtrue in JA, is qfalse properly in ioq3 - r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND ); - r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE_ND ); - r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE_ND ); - r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE ); + r_lodCurveError = ri.Cvar_Get("r_lodCurveError", "250", CVAR_ARCHIVE_ND); + r_lodbias = ri.Cvar_Get("r_lodbias", "0", CVAR_ARCHIVE_ND); + r_flares = ri.Cvar_Get("r_flares", "1", CVAR_ARCHIVE_ND); + r_lodscale = ri.Cvar_Get("r_lodscale", "10", CVAR_ARCHIVE_ND); + + r_znear = ri.Cvar_Get("r_znear", "4", CVAR_ARCHIVE_ND); // if set any lower, you lose a lot of precision in the distance + ri.Cvar_CheckRange(r_znear, 0.001f, 10, qfalse); // was qtrue in JA, is qfalse properly in ioq3 + r_ignoreGLErrors = ri.Cvar_Get("r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND); + r_fastsky = ri.Cvar_Get("r_fastsky", "0", CVAR_ARCHIVE_ND); + r_drawSun = ri.Cvar_Get("r_drawSun", "0", CVAR_ARCHIVE_ND); + r_dynamiclight = ri.Cvar_Get("r_dynamiclight", "1", CVAR_ARCHIVE); // rjr - removed for hacking -// r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "0", CVAR_ARCHIVE ); - r_finish = ri.Cvar_Get ("r_finish", "0", CVAR_ARCHIVE_ND); - r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_LINEAR", CVAR_ARCHIVE ); - r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE_ND ); - r_facePlaneCull = ri.Cvar_Get ("r_facePlaneCull", "1", CVAR_ARCHIVE_ND ); - - r_dlightStyle = ri.Cvar_Get ("r_dlightStyle", "1", CVAR_ARCHIVE_ND); - r_surfaceSprites = ri.Cvar_Get ("r_surfaceSprites", "1", CVAR_ARCHIVE_ND); - r_surfaceWeather = ri.Cvar_Get ("r_surfaceWeather", "0", CVAR_TEMP); - - r_windSpeed = ri.Cvar_Get ("r_windSpeed", "0", 0); - r_windAngle = ri.Cvar_Get ("r_windAngle", "0", 0); - r_windGust = ri.Cvar_Get ("r_windGust", "0", 0); - r_windDampFactor = ri.Cvar_Get ("r_windDampFactor", "0.1", 0); - r_windPointForce = ri.Cvar_Get ("r_windPointForce", "0", 0); - r_windPointX = ri.Cvar_Get ("r_windPointX", "0", 0); - r_windPointY = ri.Cvar_Get ("r_windPointY", "0", 0); - - r_primitives = ri.Cvar_Get( "r_primitives", "0", CVAR_ARCHIVE_ND ); - ri.Cvar_CheckRange( r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue ); - - r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.5", CVAR_CHEAT ); - r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT ); + // r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "0", CVAR_ARCHIVE ); + r_finish = ri.Cvar_Get("r_finish", "0", CVAR_ARCHIVE_ND); + r_textureMode = ri.Cvar_Get("r_textureMode", "GL_LINEAR_MIPMAP_LINEAR", CVAR_ARCHIVE); + r_gamma = ri.Cvar_Get("r_gamma", "1", CVAR_ARCHIVE_ND); + r_facePlaneCull = ri.Cvar_Get("r_facePlaneCull", "1", CVAR_ARCHIVE_ND); + + r_dlightStyle = ri.Cvar_Get("r_dlightStyle", "1", CVAR_ARCHIVE_ND); + r_surfaceSprites = ri.Cvar_Get("r_surfaceSprites", "1", CVAR_ARCHIVE_ND); + r_surfaceWeather = ri.Cvar_Get("r_surfaceWeather", "0", CVAR_TEMP); + + r_windSpeed = ri.Cvar_Get("r_windSpeed", "0", 0); + r_windAngle = ri.Cvar_Get("r_windAngle", "0", 0); + r_windGust = ri.Cvar_Get("r_windGust", "0", 0); + r_windDampFactor = ri.Cvar_Get("r_windDampFactor", "0.1", 0); + r_windPointForce = ri.Cvar_Get("r_windPointForce", "0", 0); + r_windPointX = ri.Cvar_Get("r_windPointX", "0", 0); + r_windPointY = ri.Cvar_Get("r_windPointY", "0", 0); + + r_primitives = ri.Cvar_Get("r_primitives", "0", CVAR_ARCHIVE_ND); + ri.Cvar_CheckRange(r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue); + + r_ambientScale = ri.Cvar_Get("r_ambientScale", "0.5", CVAR_CHEAT); + r_directedScale = ri.Cvar_Get("r_directedScale", "1", CVAR_CHEAT); // // temporary variables that can change at any time // - r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_CHEAT ); + r_showImages = ri.Cvar_Get("r_showImages", "0", CVAR_CHEAT); - r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP ); - r_debugStyle = ri.Cvar_Get( "r_debugStyle", "-1", CVAR_CHEAT ); - r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT ); + r_debugLight = ri.Cvar_Get("r_debuglight", "0", CVAR_TEMP); + r_debugStyle = ri.Cvar_Get("r_debugStyle", "-1", CVAR_CHEAT); + r_debugSort = ri.Cvar_Get("r_debugSort", "0", CVAR_CHEAT); - r_nocurves = ri.Cvar_Get ("r_nocurves", "0", CVAR_CHEAT ); - r_drawworld = ri.Cvar_Get ("r_drawworld", "1", CVAR_CHEAT ); + r_nocurves = ri.Cvar_Get("r_nocurves", "0", CVAR_CHEAT); + r_drawworld = ri.Cvar_Get("r_drawworld", "1", CVAR_CHEAT); #ifdef JK2_MODE - r_drawfog = ri.Cvar_Get ("r_drawfog", "1", CVAR_CHEAT ); + r_drawfog = ri.Cvar_Get("r_drawfog", "1", CVAR_CHEAT); #else - r_drawfog = ri.Cvar_Get ("r_drawfog", "2", CVAR_CHEAT ); + r_drawfog = ri.Cvar_Get("r_drawfog", "2", CVAR_CHEAT); #endif - r_lightmap = ri.Cvar_Get ("r_lightmap", "0", CVAR_CHEAT ); - r_portalOnly = ri.Cvar_Get ("r_portalOnly", "0", CVAR_CHEAT ); - - r_skipBackEnd = ri.Cvar_Get ("r_skipBackEnd", "0", CVAR_CHEAT); - - r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT ); - r_norefresh = ri.Cvar_Get ("r_norefresh", "0", CVAR_CHEAT); - r_drawentities = ri.Cvar_Get ("r_drawentities", "1", CVAR_CHEAT ); - r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_TEMP ); - r_nocull = ri.Cvar_Get ("r_nocull", "0", CVAR_CHEAT); - r_novis = ri.Cvar_Get ("r_novis", "0", CVAR_CHEAT); - r_showcluster = ri.Cvar_Get ("r_showcluster", "0", CVAR_CHEAT); - r_speeds = ri.Cvar_Get ("r_speeds", "0", CVAR_CHEAT); - r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT ); - r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT ); - r_debugSurface = ri.Cvar_Get ("r_debugSurface", "0", CVAR_CHEAT); - r_nobind = ri.Cvar_Get ("r_nobind", "0", CVAR_CHEAT); - r_showtris = ri.Cvar_Get ("r_showtris", "0", CVAR_CHEAT); - r_showtriscolor = ri.Cvar_Get ("r_showtriscolor", "0", CVAR_ARCHIVE_ND); - r_showsky = ri.Cvar_Get ("r_showsky", "0", CVAR_CHEAT); - r_shownormals = ri.Cvar_Get ("r_shownormals", "0", CVAR_CHEAT); - r_clear = ri.Cvar_Get ("r_clear", "0", CVAR_CHEAT); - r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT ); - r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT ); - r_lockpvs = ri.Cvar_Get ("r_lockpvs", "0", CVAR_CHEAT); - r_noportals = ri.Cvar_Get ("r_noportals", "0", CVAR_CHEAT); - r_shadows = ri.Cvar_Get( "cg_shadows", "1", 0 ); - r_shadowRange = ri.Cvar_Get( "r_shadowRange", "1000", CVAR_ARCHIVE_ND ); - -/* -Ghoul2 Insert Start -*/ - r_noGhoul2 = ri.Cvar_Get( "r_noghoul2", "0", CVAR_CHEAT); - r_Ghoul2AnimSmooth = ri.Cvar_Get( "r_ghoul2animsmooth", "0.25", 0); - r_Ghoul2UnSqash = ri.Cvar_Get( "r_ghoul2unsquash", "1", 0); - r_Ghoul2TimeBase = ri.Cvar_Get( "r_ghoul2timebase", "2", 0); - r_Ghoul2NoLerp = ri.Cvar_Get( "r_ghoul2nolerp", "0", 0); - r_Ghoul2NoBlend = ri.Cvar_Get( "r_ghoul2noblend", "0", 0); - r_Ghoul2BlendMultiplier = ri.Cvar_Get( "r_ghoul2blendmultiplier", "1", 0); - r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get( "r_ghoul2unsquashaftersmooth", "1", 0); - - broadsword = ri.Cvar_Get( "broadsword", "1", 0); - broadsword_kickbones = ri.Cvar_Get( "broadsword_kickbones", "1", 0); - broadsword_kickorigin = ri.Cvar_Get( "broadsword_kickorigin", "1", 0); - broadsword_dontstopanim = ri.Cvar_Get( "broadsword_dontstopanim", "0", 0); - broadsword_waitforshot = ri.Cvar_Get( "broadsword_waitforshot", "0", 0); - broadsword_playflop = ri.Cvar_Get( "broadsword_playflop", "1", 0); - broadsword_smallbbox = ri.Cvar_Get( "broadsword_smallbbox", "0", 0); - broadsword_extra1 = ri.Cvar_Get( "broadsword_extra1", "0", 0); - broadsword_extra2 = ri.Cvar_Get( "broadsword_extra2", "0", 0); - broadsword_effcorr = ri.Cvar_Get( "broadsword_effcorr", "1", 0); - broadsword_ragtobase = ri.Cvar_Get( "broadsword_ragtobase", "2", 0); - broadsword_dircap = ri.Cvar_Get( "broadsword_dircap", "64", 0); - -/* -Ghoul2 Insert End -*/ - - sv_mapname = ri.Cvar_Get ( "mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM ); - sv_mapChecksum = ri.Cvar_Get ( "sv_mapChecksum", "", CVAR_ROM ); - se_language = ri.Cvar_Get ( "se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART ); + r_lightmap = ri.Cvar_Get("r_lightmap", "0", CVAR_CHEAT); + r_portalOnly = ri.Cvar_Get("r_portalOnly", "0", CVAR_CHEAT); + + r_skipBackEnd = ri.Cvar_Get("r_skipBackEnd", "0", CVAR_CHEAT); + + r_measureOverdraw = ri.Cvar_Get("r_measureOverdraw", "0", CVAR_CHEAT); + r_norefresh = ri.Cvar_Get("r_norefresh", "0", CVAR_CHEAT); + r_drawentities = ri.Cvar_Get("r_drawentities", "1", CVAR_CHEAT); + r_ignore = ri.Cvar_Get("r_ignore", "1", CVAR_TEMP); + r_nocull = ri.Cvar_Get("r_nocull", "0", CVAR_CHEAT); + r_novis = ri.Cvar_Get("r_novis", "0", CVAR_CHEAT); + r_showcluster = ri.Cvar_Get("r_showcluster", "0", CVAR_CHEAT); + r_speeds = ri.Cvar_Get("r_speeds", "0", CVAR_CHEAT); + r_verbose = ri.Cvar_Get("r_verbose", "0", CVAR_CHEAT); + r_logFile = ri.Cvar_Get("r_logFile", "0", CVAR_CHEAT); + r_debugSurface = ri.Cvar_Get("r_debugSurface", "0", CVAR_CHEAT); + r_nobind = ri.Cvar_Get("r_nobind", "0", CVAR_CHEAT); + r_showtris = ri.Cvar_Get("r_showtris", "0", CVAR_CHEAT); + r_showtriscolor = ri.Cvar_Get("r_showtriscolor", "0", CVAR_ARCHIVE_ND); + r_showsky = ri.Cvar_Get("r_showsky", "0", CVAR_CHEAT); + r_shownormals = ri.Cvar_Get("r_shownormals", "0", CVAR_CHEAT); + r_clear = ri.Cvar_Get("r_clear", "0", CVAR_CHEAT); + r_offsetFactor = ri.Cvar_Get("r_offsetfactor", "-1", CVAR_CHEAT); + r_offsetUnits = ri.Cvar_Get("r_offsetunits", "-2", CVAR_CHEAT); + r_lockpvs = ri.Cvar_Get("r_lockpvs", "0", CVAR_CHEAT); + r_noportals = ri.Cvar_Get("r_noportals", "0", CVAR_CHEAT); + r_shadows = ri.Cvar_Get("cg_shadows", "1", 0); + r_shadowRange = ri.Cvar_Get("r_shadowRange", "1000", CVAR_ARCHIVE_ND); + + /* + Ghoul2 Insert Start + */ + r_noGhoul2 = ri.Cvar_Get("r_noghoul2", "0", CVAR_CHEAT); + r_Ghoul2AnimSmooth = ri.Cvar_Get("r_ghoul2animsmooth", "0.25", 0); + r_Ghoul2UnSqash = ri.Cvar_Get("r_ghoul2unsquash", "1", 0); + r_Ghoul2TimeBase = ri.Cvar_Get("r_ghoul2timebase", "2", 0); + r_Ghoul2NoLerp = ri.Cvar_Get("r_ghoul2nolerp", "0", 0); + r_Ghoul2NoBlend = ri.Cvar_Get("r_ghoul2noblend", "0", 0); + r_Ghoul2BlendMultiplier = ri.Cvar_Get("r_ghoul2blendmultiplier", "1", 0); + r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get("r_ghoul2unsquashaftersmooth", "1", 0); + + broadsword = ri.Cvar_Get("broadsword", "1", 0); + broadsword_kickbones = ri.Cvar_Get("broadsword_kickbones", "1", 0); + broadsword_kickorigin = ri.Cvar_Get("broadsword_kickorigin", "1", 0); + broadsword_dontstopanim = ri.Cvar_Get("broadsword_dontstopanim", "0", 0); + broadsword_waitforshot = ri.Cvar_Get("broadsword_waitforshot", "0", 0); + broadsword_playflop = ri.Cvar_Get("broadsword_playflop", "1", 0); + broadsword_smallbbox = ri.Cvar_Get("broadsword_smallbbox", "0", 0); + broadsword_extra1 = ri.Cvar_Get("broadsword_extra1", "0", 0); + broadsword_extra2 = ri.Cvar_Get("broadsword_extra2", "0", 0); + broadsword_effcorr = ri.Cvar_Get("broadsword_effcorr", "1", 0); + broadsword_ragtobase = ri.Cvar_Get("broadsword_ragtobase", "2", 0); + broadsword_dircap = ri.Cvar_Get("broadsword_dircap", "64", 0); + + /* + Ghoul2 Insert End + */ + + sv_mapname = ri.Cvar_Get("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM); + sv_mapChecksum = ri.Cvar_Get("sv_mapChecksum", "", CVAR_ROM); + se_language = ri.Cvar_Get("se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); #ifdef JK2_MODE - sp_language = ri.Cvar_Get ( "sp_language", va("%d", SP_LANGUAGE_ENGLISH), CVAR_ARCHIVE | CVAR_NORESTART ); + sp_language = ri.Cvar_Get("sp_language", va("%d", SP_LANGUAGE_ENGLISH), CVAR_ARCHIVE | CVAR_NORESTART); #endif - com_buildScript = ri.Cvar_Get ( "com_buildScript", "0", 0 ); + com_buildScript = ri.Cvar_Get("com_buildScript", "0", 0); r_modelpoolmegs = ri.Cvar_Get("r_modelpoolmegs", "20", CVAR_ARCHIVE); - if (ri.LowPhysicalMemory() ) - { + if (ri.LowPhysicalMemory()) { ri.Cvar_Set("r_modelpoolmegs", "0"); } - r_environmentMapping = ri.Cvar_Get( "r_environmentMapping", "1", CVAR_ARCHIVE_ND ); + r_environmentMapping = ri.Cvar_Get("r_environmentMapping", "1", CVAR_ARCHIVE_ND); - r_screenshotJpegQuality = ri.Cvar_Get( "r_screenshotJpegQuality", "95", CVAR_ARCHIVE_ND ); + r_screenshotJpegQuality = ri.Cvar_Get("r_screenshotJpegQuality", "95", CVAR_ARCHIVE_ND); - ri.Cvar_CheckRange( r_screenshotJpegQuality, 10, 100, qtrue ); + ri.Cvar_CheckRange(r_screenshotJpegQuality, 10, 100, qtrue); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_AddCommand( commands[i].cmd, commands[i].func ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_AddCommand(commands[i].cmd, commands[i].func); } // need to do this hackery so ghoul2 doesn't crash the game because of ITS hackery... // -void R_ClearStuffToStopGhoul2CrashingThings(void) -{ - memset( &tr, 0, sizeof( tr ) ); -} +void R_ClearStuffToStopGhoul2CrashingThings(void) { memset(&tr, 0, sizeof(tr)); } /* =============== @@ -1700,49 +1552,42 @@ R_Init =============== */ extern void R_InitWorldEffects(); -void R_Init( void ) { - int err; +void R_Init(void) { + int err; int i; - //ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); + // ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); ShaderEntryPtrs_Clear(); // clear all our internal state - memset( &tr, 0, sizeof( tr ) ); - memset( &backEnd, 0, sizeof( backEnd ) ); - memset( &tess, 0, sizeof( tess ) ); + memset(&tr, 0, sizeof(tr)); + memset(&backEnd, 0, sizeof(backEnd)); + memset(&tess, 0, sizeof(tess)); #ifndef FINAL_BUILD - if ( (intptr_t)tess.xyz & 15 ) { - Com_Printf( "WARNING: tess.xyz not 16 byte aligned\n" ); + if ((intptr_t)tess.xyz & 15) { + Com_Printf("WARNING: tess.xyz not 16 byte aligned\n"); } #endif // // init function tables // - for ( i = 0; i < FUNCTABLE_SIZE; i++ ) - { - tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) ); - tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f; + for (i = 0; i < FUNCTABLE_SIZE; i++) { + tr.sinTable[i] = sin(DEG2RAD(i * 360.0f / ((float)(FUNCTABLE_SIZE - 1)))); + tr.squareTable[i] = (i < FUNCTABLE_SIZE / 2) ? 1.0f : -1.0f; tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE; tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i]; - if ( i < FUNCTABLE_SIZE / 2 ) - { - if ( i < FUNCTABLE_SIZE / 4 ) - { - tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 ); - } - else - { - tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4]; + if (i < FUNCTABLE_SIZE / 2) { + if (i < FUNCTABLE_SIZE / 4) { + tr.triangleTable[i] = (float)i / (FUNCTABLE_SIZE / 4); + } else { + tr.triangleTable[i] = 1.0f - tr.triangleTable[i - FUNCTABLE_SIZE / 4]; } - } - else - { - tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2]; + } else { + tr.triangleTable[i] = -tr.triangleTable[i - FUNCTABLE_SIZE / 2]; } } R_InitFogTable(); @@ -1751,13 +1596,13 @@ void R_Init( void ) { R_NoiseInit(); R_Register(); - backEndData = (backEndData_t *) R_Hunk_Alloc( sizeof( backEndData_t ), qtrue ); + backEndData = (backEndData_t *)R_Hunk_Alloc(sizeof(backEndData_t), qtrue); R_InitNextFrame(); const color4ub_t color = {0xff, 0xff, 0xff, 0xff}; - for ( i = 0; i < MAX_LIGHT_STYLES; i++ ) { + for (i = 0; i < MAX_LIGHT_STYLES; i++) { byteAlias_t *ba = (byteAlias_t *)&color; - RE_SetLightStyle( i, ba->i ); + RE_SetLightStyle(i, ba->i); } InitOpenGL(); @@ -1769,14 +1614,14 @@ void R_Init( void ) { R_InitFonts(); err = qglGetError(); - if ( err != GL_NO_ERROR ) - ri.Printf (PRINT_ALL, "glGetError() = 0x%x\n", err); + if (err != GL_NO_ERROR) + ri.Printf(PRINT_ALL, "glGetError() = 0x%x\n", err); RestoreGhoul2InfoArray(); // print info GfxInfo_f(); - //ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); + // ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); } /* @@ -1785,61 +1630,52 @@ RE_Shutdown =============== */ extern void R_ShutdownWorldEffects(void); -void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_RemoveCommand( commands[i].cmd ); +void RE_Shutdown(qboolean destroyWindow, qboolean restarting) { + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_RemoveCommand(commands[i].cmd); - if ( r_DynamicGlow && r_DynamicGlow->integer ) - { + if (r_DynamicGlow && r_DynamicGlow->integer) { // Release the Glow Vertex Shader. - if ( tr.glowVShader ) - { - qglDeleteProgramsARB( 1, &tr.glowVShader ); + if (tr.glowVShader) { + qglDeleteProgramsARB(1, &tr.glowVShader); } // Release Pixel Shader. - if ( tr.glowPShader ) - { - if ( qglCombinerParameteriNV ) - { + if (tr.glowPShader) { + if (qglCombinerParameteriNV) { // Release the Glow Regcom call list. - qglDeleteLists( tr.glowPShader, 1 ); - } - else if ( qglGenProgramsARB ) - { + qglDeleteLists(tr.glowPShader, 1); + } else if (qglGenProgramsARB) { // Release the Glow Fragment Shader. - qglDeleteProgramsARB( 1, &tr.glowPShader ); + qglDeleteProgramsARB(1, &tr.glowPShader); } } // Release the scene glow texture. - qglDeleteTextures( 1, &tr.screenGlow ); + qglDeleteTextures(1, &tr.screenGlow); // Release the scene texture. - qglDeleteTextures( 1, &tr.sceneImage ); + qglDeleteTextures(1, &tr.sceneImage); // Release the blur texture. - qglDeleteTextures( 1, &tr.blurImage ); + qglDeleteTextures(1, &tr.blurImage); } R_ShutdownWorldEffects(); R_ShutdownFonts(); - if ( tr.registered ) - { + if (tr.registered) { R_IssuePendingRenderCommands(); - if ( destroyWindow ) - { - R_DeleteTextures(); // only do this for vid_restart now, not during things like map load + if (destroyWindow) { + R_DeleteTextures(); // only do this for vid_restart now, not during things like map load - if ( restarting ) - { + if (restarting) { SaveGhoul2InfoArray(); } } } // shut down platform specific OpenGL stuff - if ( destroyWindow ) { + if (destroyWindow) { ri.WIN_Shutdown(); } tr.registered = qfalse; @@ -1852,16 +1688,11 @@ RE_EndRegistration Touch all images to make sure they are resident ============= */ -void RE_EndRegistration( void ) { - R_IssuePendingRenderCommands(); -} +void RE_EndRegistration(void) { R_IssuePendingRenderCommands(); } - -void RE_GetLightStyle(int style, color4ub_t color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_GetLightStyle: %d is out of range", (int)style ); +void RE_GetLightStyle(int style, color4ub_t color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_GetLightStyle: %d is out of range", (int)style); return; } @@ -1869,16 +1700,14 @@ void RE_GetLightStyle(int style, color4ub_t color) baDest->i = baSource->i; } -void RE_SetLightStyle(int style, int color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_SetLightStyle: %d is out of range", (int)style ); +void RE_SetLightStyle(int style, int color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_SetLightStyle: %d is out of range", (int)style); return; } byteAlias_t *ba = (byteAlias_t *)&styleColors[style]; - if ( ba->i != color) { + if (ba->i != color) { ba->i = color; styleUpdated[style] = true; } @@ -1897,50 +1726,34 @@ extern float tr_distortionStretch; extern qboolean tr_distortionPrePost; extern qboolean tr_distortionNegate; -float *get_tr_distortionAlpha( void ) -{ - return &tr_distortionAlpha; -} +float *get_tr_distortionAlpha(void) { return &tr_distortionAlpha; } -float *get_tr_distortionStretch( void ) -{ - return &tr_distortionStretch; -} +float *get_tr_distortionStretch(void) { return &tr_distortionStretch; } -qboolean *get_tr_distortionPrePost( void ) -{ - return &tr_distortionPrePost; -} +qboolean *get_tr_distortionPrePost(void) { return &tr_distortionPrePost; } -qboolean *get_tr_distortionNegate( void ) -{ - return &tr_distortionNegate; -} +qboolean *get_tr_distortionNegate(void) { return &tr_distortionNegate; } float g_oldRangedFog = 0.0f; -void RE_SetRangedFog( float dist ) -{ - if (tr.rangedFog <= 0.0f) - { +void RE_SetRangedFog(float dist) { + if (tr.rangedFog <= 0.0f) { g_oldRangedFog = tr.rangedFog; } tr.rangedFog = dist; - if (tr.rangedFog == 0.0f && g_oldRangedFog) - { //restore to previous state if applicable + if (tr.rangedFog == 0.0f && g_oldRangedFog) { // restore to previous state if applicable tr.rangedFog = g_oldRangedFog; } } -//bool inServer = false; -void RE_SVModelInit( void ) -{ +// bool inServer = false; +void RE_SVModelInit(void) { tr.numModels = 0; tr.numShaders = 0; tr.numSkins = 0; R_InitImages(); - //inServer = true; + // inServer = true; R_InitShaders(); - //inServer = false; + // inServer = false; R_ModelInit(); } @@ -1950,11 +1763,11 @@ GetRefAPI @@@@@@@@@@@@@@@@@@@@@ */ -extern void R_LoadImage( const char *shortname, byte **pic, int *width, int *height ); +extern void R_LoadImage(const char *shortname, byte **pic, int *width, int *height); extern void R_WorldEffectCommand(const char *command); -extern qboolean R_inPVS( vec3_t p1, vec3_t p2 ); +extern qboolean R_inPVS(vec3_t p1, vec3_t p2); extern void RE_GetModelBounds(refEntity_t *refEnt, vec3_t bounds1, vec3_t bounds2); -extern void G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUpdateParams *params); +extern void G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params); extern qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale); extern qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity); extern qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force); @@ -1963,7 +1776,7 @@ extern qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams extern qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos); extern qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed); extern qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max); -extern void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms); +extern void G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms); #ifdef G2_PERFORMANCE_ANALYSIS extern void G2Time_ResetTimers(void); extern void G2Time_ReportTimers(void); @@ -1971,27 +1784,26 @@ extern void G2Time_ReportTimers(void); extern IGhoul2InfoArray &TheGhoul2InfoArray(); #ifdef JK2_MODE -unsigned int AnyLanguage_ReadCharFromString_JK2 ( char **text, qboolean *pbIsTrailingPunctuation ) { - return AnyLanguage_ReadCharFromString (text, pbIsTrailingPunctuation); +unsigned int AnyLanguage_ReadCharFromString_JK2(char **text, qboolean *pbIsTrailingPunctuation) { + return AnyLanguage_ReadCharFromString(text, pbIsTrailingPunctuation); } #endif -extern "C" Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t *refimp ) { - static refexport_t re; +extern "C" Q_EXPORT refexport_t *QDECL GetRefAPI(int apiVersion, refimport_t *refimp) { + static refexport_t re; ri = *refimp; - memset( &re, 0, sizeof( re ) ); + memset(&re, 0, sizeof(re)); - if ( apiVersion != REF_API_VERSION ) { - ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", - REF_API_VERSION, apiVersion ); + if (apiVersion != REF_API_VERSION) { + ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion); return NULL; } // the RE_ functions are Renderer Entry points -#define REX(x) re.x = RE_##x +#define REX(x) re.x = RE_##x REX(Shutdown); @@ -2091,7 +1903,7 @@ extern "C" Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t * re.TheGhoul2InfoArray = TheGhoul2InfoArray; -#define G2EX(x) re.G2API_##x = G2API_##x +#define G2EX(x) re.G2API_##x = G2API_##x G2EX(AddBolt); G2EX(AddBoltSurfNum); @@ -2154,7 +1966,7 @@ extern "C" Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t * G2EX(SetGhoul2ModelFlags); G2EX(SetGhoul2ModelIndexes); G2EX(SetLodBias); - //G2EX(SetModelIndexes); + // G2EX(SetModelIndexes); G2EX(SetNewOrigin); G2EX(SetRagDoll); G2EX(SetRootSurface); @@ -2176,7 +1988,7 @@ extern "C" Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t * re.G2Time_ResetTimers = G2Time_ResetTimers; #endif - //Swap_Init(); + // Swap_Init(); return &re; } diff --git a/code/rd-vanilla/tr_light.cpp b/code/rd-vanilla/tr_light.cpp index d176af56c5..53eb51b08f 100644 --- a/code/rd-vanilla/tr_light.cpp +++ b/code/rd-vanilla/tr_light.cpp @@ -28,13 +28,12 @@ along with this program; if not, see . #include "tr_local.h" -#define DLIGHT_AT_RADIUS 16 +#define DLIGHT_AT_RADIUS 16 // at the edge of a dlight's influence, this amount of light will be added -#define DLIGHT_MINIMUM_RADIUS 16 +#define DLIGHT_MINIMUM_RADIUS 16 // never calculate a range less than this to prevent huge light numbers - /* =============== R_TransformDlights @@ -44,15 +43,15 @@ Used by both the front end (for DlightBmodel) and the back end (before doing the lighting calculation) =============== */ -void R_TransformDlights( int count, dlight_t *dl, orientationr_t *ori) { - int i; - vec3_t temp; - - for ( i = 0 ; i < count ; i++, dl++ ) { - VectorSubtract( dl->origin, ori->origin, temp ); - dl->transformed[0] = DotProduct( temp, ori->axis[0] ); - dl->transformed[1] = DotProduct( temp, ori->axis[1] ); - dl->transformed[2] = DotProduct( temp, ori->axis[2] ); +void R_TransformDlights(int count, dlight_t *dl, orientationr_t *ori) { + int i; + vec3_t temp; + + for (i = 0; i < count; i++, dl++) { + VectorSubtract(dl->origin, ori->origin, temp); + dl->transformed[0] = DotProduct(temp, ori->axis[0]); + dl->transformed[1] = DotProduct(temp, ori->axis[1]); + dl->transformed[2] = DotProduct(temp, ori->axis[2]); } } @@ -63,31 +62,30 @@ R_DlightBmodel Determine which dynamic lights may effect this bmodel ============= */ -void R_DlightBmodel( bmodel_t *bmodel, qboolean NoLight ) { - int i, j; - dlight_t *dl; - int mask; - msurface_t *surf; +void R_DlightBmodel(bmodel_t *bmodel, qboolean NoLight) { + int i, j; + dlight_t *dl; + int mask; + msurface_t *surf; // transform all the lights - R_TransformDlights( tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori ); + R_TransformDlights(tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori); mask = 0; - if (!NoLight) - { - for ( i=0 ; itransformed[j] - bmodel->bounds[1][j] > dl->radius ) { + for (j = 0; j < 3; j++) { + if (dl->transformed[j] - bmodel->bounds[1][j] > dl->radius) { break; } - if ( bmodel->bounds[0][j] - dl->transformed[j] > dl->radius ) { + if (bmodel->bounds[0][j] - dl->transformed[j] > dl->radius) { break; } } - if ( j < 3 ) { + if (j < 3) { continue; } @@ -99,16 +97,15 @@ void R_DlightBmodel( bmodel_t *bmodel, qboolean NoLight ) { tr.currentEntity->needDlights = (qboolean)(mask != 0); tr.currentEntity->dlightBits = mask; - // set the dlight bits in all the surfaces - for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { + for (i = 0; i < bmodel->numSurfaces; i++) { surf = bmodel->firstSurface + i; - if ( *surf->data == SF_FACE ) { + if (*surf->data == SF_FACE) { ((srfSurfaceFace_t *)surf->data)->dlightBits = mask; - } else if ( *surf->data == SF_GRID ) { + } else if (*surf->data == SF_GRID) { ((srfGridMesh_t *)surf->data)->dlightBits = mask; - } else if ( *surf->data == SF_TRIANGLES ) { + } else if (*surf->data == SF_TRIANGLES) { ((srfTriangles_t *)surf->data)->dlightBits = mask; } } @@ -122,9 +119,9 @@ LIGHT SAMPLING ============================================================================= */ -extern cvar_t *r_ambientScale; -extern cvar_t *r_directedScale; -extern cvar_t *r_debugLight; +extern cvar_t *r_ambientScale; +extern cvar_t *r_directedScale; +extern cvar_t *r_debugLight; /* ================= @@ -132,85 +129,83 @@ R_SetupEntityLightingGrid ================= */ -static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { - vec3_t lightOrigin; - int pos[3]; - int i, j; - float frac[3]; - int gridStep[3]; - vec3_t direction; - float totalFactor; - unsigned short *startGridPos; - - if (r_fullbright->integer || (tr.refdef.rdflags & RDF_doLAGoggles) ) - { +static void R_SetupEntityLightingGrid(trRefEntity_t *ent) { + vec3_t lightOrigin; + int pos[3]; + int i, j; + float frac[3]; + int gridStep[3]; + vec3_t direction; + float totalFactor; + unsigned short *startGridPos; + + if (r_fullbright->integer || (tr.refdef.rdflags & RDF_doLAGoggles)) { ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = 255.0; ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = 255.0; - VectorCopy( tr.sunDirection, ent->lightDir ); + VectorCopy(tr.sunDirection, ent->lightDir); return; } - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } #define ACCURATE_LIGHTGRID_SAMPLING 1 #if ACCURATE_LIGHTGRID_SAMPLING - vec3_t startLightOrigin; - VectorCopy( lightOrigin, startLightOrigin ); + vec3_t startLightOrigin; + VectorCopy(lightOrigin, startLightOrigin); #endif - VectorSubtract( lightOrigin, tr.world->lightGridOrigin, lightOrigin ); - for ( i = 0 ; i < 3 ; i++ ) { - float v; + VectorSubtract(lightOrigin, tr.world->lightGridOrigin, lightOrigin); + for (i = 0; i < 3; i++) { + float v; - v = lightOrigin[i]*tr.world->lightGridInverseSize[i]; - pos[i] = floor( v ); + v = lightOrigin[i] * tr.world->lightGridInverseSize[i]; + pos[i] = floor(v); frac[i] = v - pos[i]; - if ( pos[i] < 0 ) { + if (pos[i] < 0) { pos[i] = 0; - } else if ( pos[i] >= tr.world->lightGridBounds[i] - 1 ) { + } else if (pos[i] >= tr.world->lightGridBounds[i] - 1) { pos[i] = tr.world->lightGridBounds[i] - 1; } } - VectorClear( ent->ambientLight ); - VectorClear( ent->directedLight ); - VectorClear( direction ); + VectorClear(ent->ambientLight); + VectorClear(ent->directedLight); + VectorClear(direction); // trilerp the light value gridStep[0] = 1; gridStep[1] = tr.world->lightGridBounds[0]; gridStep[2] = tr.world->lightGridBounds[0] * tr.world->lightGridBounds[1]; - startGridPos = tr.world->lightGridArray + pos[0] * gridStep[0] - + pos[1] * gridStep[1] + pos[2] * gridStep[2]; + startGridPos = tr.world->lightGridArray + pos[0] * gridStep[0] + pos[1] * gridStep[1] + pos[2] * gridStep[2]; #if ACCURATE_LIGHTGRID_SAMPLING - vec3_t startGridOrg; - VectorCopy( tr.world->lightGridOrigin, startGridOrg ); + vec3_t startGridOrg; + VectorCopy(tr.world->lightGridOrigin, startGridOrg); startGridOrg[0] += pos[0] * tr.world->lightGridSize[0]; startGridOrg[1] += pos[1] * tr.world->lightGridSize[1]; startGridOrg[2] += pos[2] * tr.world->lightGridSize[2]; #endif totalFactor = 0; - for ( i = 0 ; i < 8 ; i++ ) { - float factor; - mgrid_t *data; - unsigned short *gridPos; - int lat, lng; - vec3_t normal; + for (i = 0; i < 8; i++) { + float factor; + mgrid_t *data; + unsigned short *gridPos; + int lat, lng; + vec3_t normal; #if ACCURATE_LIGHTGRID_SAMPLING - vec3_t gridOrg; - VectorCopy( startGridOrg, gridOrg ); + vec3_t gridOrg; + VectorCopy(startGridOrg, gridOrg); #endif factor = 1.0; gridPos = startGridPos; - for ( j = 0 ; j < 3 ; j++ ) { - if ( i & (1<= tr.world->lightGridArray + tr.world->numGridArrayElements) - {//we've gone off the array somehow + if (gridPos >= tr.world->lightGridArray + tr.world->numGridArrayElements) { // we've gone off the array somehow continue; } data = tr.world->lightGridData + *gridPos; - if ( data->styles[0] == LS_NONE ) - { - continue; // ignore samples in walls + if (data->styles[0] == LS_NONE) { + continue; // ignore samples in walls } #if 0 @@ -241,11 +234,9 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { totalFactor += factor; - for(j=0;jstyles[j] != LS_NONE) - { - const byte style= data->styles[j]; + for (j = 0; j < MAXLIGHTMAPS; j++) { + if (data->styles[j] != LS_NONE) { + const byte style = data->styles[j]; ent->ambientLight[0] += factor * data->ambientLight[j][0] * styleColors[style][0] / 255.0f; ent->ambientLight[1] += factor * data->ambientLight[j][1] * styleColors[style][1] / 255.0f; @@ -254,88 +245,83 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { ent->directedLight[0] += factor * data->directLight[j][0] * styleColors[style][0] / 255.0f; ent->directedLight[1] += factor * data->directLight[j][1] * styleColors[style][1] / 255.0f; ent->directedLight[2] += factor * data->directLight[j][2] * styleColors[style][2] / 255.0f; - } - else - { + } else { break; } } lat = data->latLong[1]; lng = data->latLong[0]; - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) // decode Z as cos( long ) - normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + normal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + normal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; - VectorMA( direction, factor, normal, direction ); + VectorMA(direction, factor, normal, direction); #if ACCURATE_LIGHTGRID_SAMPLING - if ( r_debugLight->integer && ent->e.hModel == -1 ) - { - //draw + if (r_debugLight->integer && ent->e.hModel == -1) { + // draw refEntity_t refEnt; refEnt.hModel = 0; refEnt.ghoul2 = NULL; refEnt.renderfx = 0; - VectorCopy( gridOrg, refEnt.origin ); - vectoangles( normal, refEnt.angles ); - AnglesToAxis( refEnt.angles, refEnt.axis ); + VectorCopy(gridOrg, refEnt.origin); + vectoangles(normal, refEnt.angles); + AnglesToAxis(refEnt.angles, refEnt.axis); refEnt.reType = RT_MODEL; - RE_AddRefEntityToScene( &refEnt ); + RE_AddRefEntityToScene(&refEnt); refEnt.renderfx = RF_DEPTHHACK; refEnt.reType = RT_SPRITE; - refEnt.customShader = RE_RegisterShader( "gfx/misc/debugAmbient" ); + refEnt.customShader = RE_RegisterShader("gfx/misc/debugAmbient"); refEnt.shaderRGBA[0] = data->ambientLight[0][0]; refEnt.shaderRGBA[1] = data->ambientLight[0][1]; refEnt.shaderRGBA[2] = data->ambientLight[0][2]; refEnt.shaderRGBA[3] = 255; - refEnt.radius = factor*50+2.0f; // maybe always give it a minimum size? - refEnt.rotation = 0; // don't let the sprite wobble around - RE_AddRefEntityToScene( &refEnt ); + refEnt.radius = factor * 50 + 2.0f; // maybe always give it a minimum size? + refEnt.rotation = 0; // don't let the sprite wobble around + RE_AddRefEntityToScene(&refEnt); refEnt.reType = RT_LINE; - refEnt.customShader = RE_RegisterShader( "gfx/misc/debugArrow" ); + refEnt.customShader = RE_RegisterShader("gfx/misc/debugArrow"); refEnt.shaderRGBA[0] = data->directLight[0][0]; refEnt.shaderRGBA[1] = data->directLight[0][1]; refEnt.shaderRGBA[2] = data->directLight[0][2]; refEnt.shaderRGBA[3] = 255; - VectorCopy( refEnt.origin, refEnt.oldorigin ); - VectorMA( gridOrg, (factor*-255) - 2.0f, normal, refEnt.origin ); // maybe always give it a minimum length + VectorCopy(refEnt.origin, refEnt.oldorigin); + VectorMA(gridOrg, (factor * -255) - 2.0f, normal, refEnt.origin); // maybe always give it a minimum length refEnt.radius = 1.5f; - RE_AddRefEntityToScene( &refEnt ); + RE_AddRefEntityToScene(&refEnt); } #endif } - if ( totalFactor > 0 && totalFactor < 0.99 ) - { + if (totalFactor > 0 && totalFactor < 0.99) { totalFactor = 1.0 / totalFactor; - VectorScale( ent->ambientLight, totalFactor, ent->ambientLight ); - VectorScale( ent->directedLight, totalFactor, ent->directedLight ); + VectorScale(ent->ambientLight, totalFactor, ent->ambientLight); + VectorScale(ent->directedLight, totalFactor, ent->directedLight); } - VectorScale( ent->ambientLight, r_ambientScale->value, ent->ambientLight ); - VectorScale( ent->directedLight, r_directedScale->value, ent->directedLight ); + VectorScale(ent->ambientLight, r_ambientScale->value, ent->ambientLight); + VectorScale(ent->directedLight, r_directedScale->value, ent->directedLight); - VectorNormalize2( direction, ent->lightDir ); + VectorNormalize2(direction, ent->lightDir); } - /* =============== LogLight =============== */ -static void LogLight( trRefEntity_t *ent ) { - int max1, max2; +static void LogLight(trRefEntity_t *ent) { + int max1, max2; /* if ( !(ent->e.renderfx & RF_FIRST_PERSON ) ) { @@ -343,7 +329,7 @@ static void LogLight( trRefEntity_t *ent ) { } */ - max1 = VectorLength( ent->ambientLight ); + max1 = VectorLength(ent->ambientLight); /* max1 = ent->ambientLight[0]; if ( ent->ambientLight[1] > max1 ) { @@ -353,7 +339,7 @@ static void LogLight( trRefEntity_t *ent ) { } */ - max2 = VectorLength( ent->directedLight ); + max2 = VectorLength(ent->directedLight); /* max2 = ent->directedLight[0]; if ( ent->directedLight[1] > max2 ) { @@ -363,7 +349,7 @@ static void LogLight( trRefEntity_t *ent ) { } */ - ri.Printf( PRINT_ALL, "amb:%i dir:%i direction: (%4.2f, %4.2f, %4.2f)\n", max1, max2, ent->lightDir[0], ent->lightDir[1], ent->lightDir[2] ); + ri.Printf(PRINT_ALL, "amb:%i dir:%i direction: (%4.2f, %4.2f, %4.2f)\n", max1, max2, ent->lightDir[0], ent->lightDir[1], ent->lightDir[2]); } /* @@ -374,17 +360,17 @@ Calculates all the lighting values that will be used by the Calc_* functions ================= */ -void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { - int i; - dlight_t *dl; - float power; - vec3_t dir; - float d; - vec3_t lightDir; - vec3_t lightOrigin; +void R_SetupEntityLighting(const trRefdef_t *refdef, trRefEntity_t *ent) { + int i; + dlight_t *dl; + float power; + vec3_t dir; + float d; + vec3_t lightDir; + vec3_t lightOrigin; // lighting calculations - if ( ent->lightingCalculated ) { + if (ent->lightingCalculated) { return; } ent->lightingCalculated = qtrue; @@ -392,34 +378,30 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { // // trace a sample point down to find ambient light // - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } // if NOWORLDMODEL, only use dynamic lights (menu system, etc) - if ( !(refdef->rdflags & RDF_NOWORLDMODEL ) - && tr.world->lightGridData ) { - R_SetupEntityLightingGrid( ent ); + if (!(refdef->rdflags & RDF_NOWORLDMODEL) && tr.world->lightGridData) { + R_SetupEntityLightingGrid(ent); } else { - ent->ambientLight[0] = ent->ambientLight[1] = - ent->ambientLight[2] = tr.identityLight * 150; - ent->directedLight[0] = ent->directedLight[1] = - ent->directedLight[2] = tr.identityLight * 150; - VectorCopy( tr.sunDirection, ent->lightDir ); + ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = tr.identityLight * 150; + ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = tr.identityLight * 150; + VectorCopy(tr.sunDirection, ent->lightDir); } // bonus items and view weapons have a fixed minimum add - if ( ent->e.renderfx & RF_MORELIGHT ) { + if (ent->e.renderfx & RF_MORELIGHT) { ent->ambientLight[0] += tr.identityLight * 96; ent->ambientLight[1] += tr.identityLight * 96; ent->ambientLight[2] += tr.identityLight * 96; - } - else { + } else { // give everything a minimum light add ent->ambientLight[0] += tr.identityLight * 32; ent->ambientLight[1] += tr.identityLight * 32; @@ -429,70 +411,69 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { // // modify the light by dynamic lights // - d = VectorLength( ent->directedLight ); - VectorScale( ent->lightDir, d, lightDir ); + d = VectorLength(ent->directedLight); + VectorScale(ent->lightDir, d, lightDir); - for ( i = 0 ; i < refdef->num_dlights ; i++ ) { + for (i = 0; i < refdef->num_dlights; i++) { dl = &refdef->dlights[i]; - VectorSubtract( dl->origin, lightOrigin, dir ); - d = VectorNormalize( dir ); + VectorSubtract(dl->origin, lightOrigin, dir); + d = VectorNormalize(dir); - power = DLIGHT_AT_RADIUS * ( dl->radius * dl->radius ); - if ( d < DLIGHT_MINIMUM_RADIUS ) { + power = DLIGHT_AT_RADIUS * (dl->radius * dl->radius); + if (d < DLIGHT_MINIMUM_RADIUS) { d = DLIGHT_MINIMUM_RADIUS; } - d = power / ( d * d ); + d = power / (d * d); - VectorMA( ent->directedLight, d, dl->color, ent->directedLight ); - VectorMA( lightDir, d, dir, lightDir ); + VectorMA(ent->directedLight, d, dl->color, ent->directedLight); + VectorMA(lightDir, d, dir, lightDir); } // clamp ambient - for ( i = 0 ; i < 3 ; i++ ) { - if ( ent->ambientLight[i] > tr.identityLightByte ) { + for (i = 0; i < 3; i++) { + if (ent->ambientLight[i] > tr.identityLightByte) { ent->ambientLight[i] = tr.identityLightByte; } } - if ( r_debugLight->integer ) { - LogLight( ent ); + if (r_debugLight->integer) { + LogLight(ent); } // save out the byte packet version - ((byte *)&ent->ambientLightInt)[0] = Q_ftol( ent->ambientLight[0] ); - ((byte *)&ent->ambientLightInt)[1] = Q_ftol( ent->ambientLight[1] ); - ((byte *)&ent->ambientLightInt)[2] = Q_ftol( ent->ambientLight[2] ); + ((byte *)&ent->ambientLightInt)[0] = Q_ftol(ent->ambientLight[0]); + ((byte *)&ent->ambientLightInt)[1] = Q_ftol(ent->ambientLight[1]); + ((byte *)&ent->ambientLightInt)[2] = Q_ftol(ent->ambientLight[2]); ((byte *)&ent->ambientLightInt)[3] = 0xff; // transform the direction to local space - VectorNormalize( lightDir ); - ent->lightDir[0] = DotProduct( lightDir, ent->e.axis[0] ); - ent->lightDir[1] = DotProduct( lightDir, ent->e.axis[1] ); - ent->lightDir[2] = DotProduct( lightDir, ent->e.axis[2] ); + VectorNormalize(lightDir); + ent->lightDir[0] = DotProduct(lightDir, ent->e.axis[0]); + ent->lightDir[1] = DotProduct(lightDir, ent->e.axis[1]); + ent->lightDir[2] = DotProduct(lightDir, ent->e.axis[2]); } -//pass in origin -qboolean RE_GetLighting( const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { +// pass in origin +qboolean RE_GetLighting(const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { trRefEntity_t tr_ent; - if ( !tr.world || !tr.world->lightGridData) { + if (!tr.world || !tr.world->lightGridData) { ambientLight[0] = ambientLight[1] = ambientLight[2] = 255.0; directedLight[0] = directedLight[1] = directedLight[2] = 255.0; - VectorCopy( tr.sunDirection, lightDir ); + VectorCopy(tr.sunDirection, lightDir); return qfalse; } - memset (&tr_ent, 0, sizeof(tr_ent) ); + memset(&tr_ent, 0, sizeof(tr_ent)); - if ( ambientLight[0] == 666 ) - {//HAX0R + if (ambientLight[0] == 666) { // HAX0R tr_ent.e.hModel = -1; } - VectorCopy (origin, tr_ent.e.origin); - R_SetupEntityLightingGrid( &tr_ent ); - VectorCopy ( tr_ent.ambientLight, ambientLight); - VectorCopy ( tr_ent.directedLight, directedLight); - VectorCopy ( tr_ent.lightDir, lightDir); + VectorCopy(origin, tr_ent.e.origin); + R_SetupEntityLightingGrid(&tr_ent); + VectorCopy(tr_ent.ambientLight, ambientLight); + VectorCopy(tr_ent.directedLight, directedLight); + VectorCopy(tr_ent.lightDir, lightDir); return qtrue; } @@ -501,17 +482,16 @@ qboolean RE_GetLighting( const vec3_t origin, vec3_t ambientLight, vec3_t direct R_LightForPoint ================= */ -int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) -{ +int R_LightForPoint(vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { trRefEntity_t ent; // bk010103 - this segfaults with -nolight maps - if ( tr.world->lightGridData == NULL ) - return qfalse; + if (tr.world->lightGridData == NULL) + return qfalse; memset(&ent, 0, sizeof(ent)); - VectorCopy( point, ent.e.origin ); - R_SetupEntityLightingGrid( &ent ); + VectorCopy(point, ent.e.origin); + R_SetupEntityLightingGrid(&ent); VectorCopy(ent.ambientLight, ambientLight); VectorCopy(ent.directedLight, directedLight); VectorCopy(ent.lightDir, lightDir); diff --git a/code/rd-vanilla/tr_main.cpp b/code/rd-vanilla/tr_main.cpp index da619736ae..1cac832b2a 100644 --- a/code/rd-vanilla/tr_main.cpp +++ b/code/rd-vanilla/tr_main.cpp @@ -29,25 +29,21 @@ along with this program; if not, see . #include "tr_local.h" #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -trGlobals_t tr; +trGlobals_t tr; -static float s_flipMatrix[16] = { +static float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; refimport_t ri; // entities that will have procedurally generated surfaces will just // point at this for their sorting surface -surfaceType_t entitySurface = SF_ENTITY; +surfaceType_t entitySurface = SF_ENTITY; /* ================= @@ -56,138 +52,126 @@ R_CullLocalBox Returns CULL_IN, CULL_CLIP, or CULL_OUT ================= */ -int R_CullLocalBox (const vec3_t bounds[2]) { - int i, j; - vec3_t transformed[8]; - float dists[8]; - vec3_t v; - cplane_t *frust; - int anyBack; - int front, back; - - if ( r_nocull->integer==1 ) { +int R_CullLocalBox(const vec3_t bounds[2]) { + int i, j; + vec3_t transformed[8]; + float dists[8]; + vec3_t v; + cplane_t *frust; + int anyBack; + int front, back; + + if (r_nocull->integer == 1) { return CULL_CLIP; } // transform into world space - for (i = 0 ; i < 8 ; i++) { - v[0] = bounds[i&1][0]; - v[1] = bounds[(i>>1)&1][1]; - v[2] = bounds[(i>>2)&1][2]; - - VectorCopy( tr.ori.origin, transformed[i] ); - VectorMA( transformed[i], v[0], tr.ori.axis[0], transformed[i] ); - VectorMA( transformed[i], v[1], tr.ori.axis[1], transformed[i] ); - VectorMA( transformed[i], v[2], tr.ori.axis[2], transformed[i] ); + for (i = 0; i < 8; i++) { + v[0] = bounds[i & 1][0]; + v[1] = bounds[(i >> 1) & 1][1]; + v[2] = bounds[(i >> 2) & 1][2]; + + VectorCopy(tr.ori.origin, transformed[i]); + VectorMA(transformed[i], v[0], tr.ori.axis[0], transformed[i]); + VectorMA(transformed[i], v[1], tr.ori.axis[1], transformed[i]); + VectorMA(transformed[i], v[2], tr.ori.axis[2], transformed[i]); } // check against frustum planes anyBack = 0; - for (i = 0 ; i < 5 ; i++) { + for (i = 0; i < 5; i++) { frust = &tr.viewParms.frustum[i]; front = back = 0; - for (j = 0 ; j < 8 ; j++) { + for (j = 0; j < 8; j++) { dists[j] = DotProduct(transformed[j], frust->normal); - if ( dists[j] > frust->dist ) { + if (dists[j] > frust->dist) { front = 1; - if ( back ) { - break; // a point is in front + if (back) { + break; // a point is in front } } else { back = 1; } } - if ( !front ) { + if (!front) { // all points were behind one of the planes return CULL_OUT; } anyBack |= back; } - if ( !anyBack ) { - return CULL_IN; // completely inside frustum + if (!anyBack) { + return CULL_IN; // completely inside frustum } - return CULL_CLIP; // partially clipped + return CULL_CLIP; // partially clipped } /* ** R_CullLocalPointAndRadius */ -int R_CullLocalPointAndRadius( const vec3_t pt, float radius ) -{ +int R_CullLocalPointAndRadius(const vec3_t pt, float radius) { vec3_t transformed; - R_LocalPointToWorld( pt, transformed ); + R_LocalPointToWorld(pt, transformed); - return R_CullPointAndRadius( transformed, radius ); + return R_CullPointAndRadius(transformed, radius); } /* ** R_CullPointAndRadius */ -int R_CullPointAndRadius( const vec3_t pt, float radius ) -{ - int i; - float dist; - cplane_t *frust; +int R_CullPointAndRadius(const vec3_t pt, float radius) { + int i; + float dist; + cplane_t *frust; qboolean mightBeClipped = qfalse; - if ( r_nocull->integer==1 ) { + if (r_nocull->integer == 1) { return CULL_CLIP; } // check against frustum planes #ifdef JK2_MODE // They used 4 frustrum planes in JK2, and 5 in JKA --eez - for (i = 0 ; i < 4 ; i++) - { + for (i = 0; i < 4; i++) { frust = &tr.viewParms.frustum[i]; - dist = DotProduct( pt, frust->normal) - frust->dist; - if ( dist < -radius ) - { + dist = DotProduct(pt, frust->normal) - frust->dist; + if (dist < -radius) { return CULL_OUT; - } - else if ( dist <= radius ) - { + } else if (dist <= radius) { mightBeClipped = qtrue; } } #else - for (i = 0 ; i < 5 ; i++) - { + for (i = 0; i < 5; i++) { frust = &tr.viewParms.frustum[i]; - dist = DotProduct( pt, frust->normal) - frust->dist; - if ( dist < -radius ) - { + dist = DotProduct(pt, frust->normal) - frust->dist; + if (dist < -radius) { return CULL_OUT; - } - else if ( dist <= radius ) - { + } else if (dist <= radius) { mightBeClipped = qtrue; } } #endif - if ( mightBeClipped ) - { + if (mightBeClipped) { return CULL_CLIP; } - return CULL_IN; // completely inside frustum + return CULL_IN; // completely inside frustum } - /* ================= R_LocalNormalToWorld ================= */ -void R_LocalNormalToWorld (const vec3_t local, vec3_t world) { +void R_LocalNormalToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2]; @@ -199,7 +183,7 @@ R_LocalPointToWorld ================= */ -void R_LocalPointToWorld (const vec3_t local, vec3_t world) { +void R_LocalPointToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0] + tr.ori.origin[0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1] + tr.ori.origin[1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2] + tr.ori.origin[2]; @@ -207,24 +191,19 @@ void R_LocalPointToWorld (const vec3_t local, vec3_t world) { float preTransEntMatrix[16]; -void R_InvertMatrix(float *sourcemat, float *destmat) -{ - int i, j, temp=0; +void R_InvertMatrix(float *sourcemat, float *destmat) { + int i, j, temp = 0; - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - destmat[j*4 + i] = sourcemat[temp++]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + destmat[j * 4 + i] = sourcemat[temp++]; } } - for (i = 0; i < 3; i++) - { - temp = i*4; - destmat[temp+3]=0; // destmat[destmat[i][3]=0; - for (j = 0; j < 3; j++) - { - destmat[temp+3]-=destmat[temp+j]*sourcemat[j*4+3]; // dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + for (i = 0; i < 3; i++) { + temp = i * 4; + destmat[temp + 3] = 0; // destmat[destmat[i][3]=0; + for (j = 0; j < 3; j++) { + destmat[temp + 3] -= destmat[temp + j] * sourcemat[j * 4 + 3]; // dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; } } } @@ -235,8 +214,7 @@ R_WorldNormalToEntity ================= */ -void R_WorldNormalToEntity (const vec3_t worldvec, vec3_t entvec) -{ +void R_WorldNormalToEntity(const vec3_t worldvec, vec3_t entvec) { entvec[0] = -worldvec[0] * preTransEntMatrix[0] - worldvec[1] * preTransEntMatrix[4] + worldvec[2] * preTransEntMatrix[8]; entvec[1] = -worldvec[0] * preTransEntMatrix[1] - worldvec[1] * preTransEntMatrix[5] + worldvec[2] * preTransEntMatrix[9]; entvec[2] = -worldvec[0] * preTransEntMatrix[2] - worldvec[1] * preTransEntMatrix[6] + worldvec[2] * preTransEntMatrix[10]; @@ -262,7 +240,7 @@ R_WorldToLocal ================= */ -void R_WorldToLocal (vec3_t world, vec3_t local) { +void R_WorldToLocal(vec3_t world, vec3_t local) { local[0] = DotProduct(world, tr.ori.axis[0]); local[1] = DotProduct(world, tr.ori.axis[1]); local[2] = DotProduct(world, tr.ori.axis[2]); @@ -274,24 +252,16 @@ R_TransformModelToClip ========================== */ -void R_TransformModelToClip( const vec3_t src, const float *modelMatrix, const float *projectionMatrix, - vec4_t eye, vec4_t dst ) { +void R_TransformModelToClip(const vec3_t src, const float *modelMatrix, const float *projectionMatrix, vec4_t eye, vec4_t dst) { int i; - for ( i = 0 ; i < 4 ; i++ ) { - eye[i] = - src[0] * modelMatrix[ i + 0 * 4 ] + - src[1] * modelMatrix[ i + 1 * 4 ] + - src[2] * modelMatrix[ i + 2 * 4 ] + - 1 * modelMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + eye[i] = src[0] * modelMatrix[i + 0 * 4] + src[1] * modelMatrix[i + 1 * 4] + src[2] * modelMatrix[i + 2 * 4] + 1 * modelMatrix[i + 3 * 4]; } - for ( i = 0 ; i < 4 ; i++ ) { - dst[i] = - eye[0] * projectionMatrix[ i + 0 * 4 ] + - eye[1] * projectionMatrix[ i + 1 * 4 ] + - eye[2] * projectionMatrix[ i + 2 * 4 ] + - eye[3] * projectionMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + dst[i] = eye[0] * projectionMatrix[i + 0 * 4] + eye[1] * projectionMatrix[i + 1 * 4] + eye[2] * projectionMatrix[i + 2 * 4] + + eye[3] * projectionMatrix[i + 3 * 4]; } } @@ -301,36 +271,31 @@ R_TransformClipToWindow ========================== */ -void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ) { +void R_TransformClipToWindow(const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window) { normalized[0] = clip[0] / clip[3]; normalized[1] = clip[1] / clip[3]; - normalized[2] = ( clip[2] + clip[3] ) / ( 2 * clip[3] ); + normalized[2] = (clip[2] + clip[3]) / (2 * clip[3]); - window[0] = 0.5 * ( 1.0 + normalized[0] ) * view->viewportWidth; - window[1] = 0.5 * ( 1.0 + normalized[1] ) * view->viewportHeight; + window[0] = 0.5 * (1.0 + normalized[0]) * view->viewportWidth; + window[1] = 0.5 * (1.0 + normalized[1]) * view->viewportHeight; window[2] = normalized[2]; - window[0] = (int) ( window[0] + 0.5 ); - window[1] = (int) ( window[1] + 0.5 ); + window[0] = (int)(window[0] + 0.5); + window[1] = (int)(window[1] + 0.5); } - /* ========================== myGlMultMatrix ========================== */ -void myGlMultMatrix( const float *a, const float *b, float *out ) { - int i, j; - - for ( i = 0 ; i < 4 ; i++ ) { - for ( j = 0 ; j < 4 ; j++ ) { - out[ i * 4 + j ] = - a [ i * 4 + 0 ] * b [ 0 * 4 + j ] - + a [ i * 4 + 1 ] * b [ 1 * 4 + j ] - + a [ i * 4 + 2 ] * b [ 2 * 4 + j ] - + a [ i * 4 + 3 ] * b [ 3 * 4 + j ]; +void myGlMultMatrix(const float *a, const float *b, float *out) { + int i, j; + + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + out[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] + a[i * 4 + 1] * b[1 * 4 + j] + a[i * 4 + 2] * b[2 * 4 + j] + a[i * 4 + 3] * b[3 * 4 + j]; } } } @@ -344,22 +309,21 @@ Does NOT produce any GL calls Called by both the front end and the back end ================= */ -void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, - orientationr_t *ori ) { -// float glMatrix[16]; - vec3_t delta; - float axisLength; +void R_RotateForEntity(const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *ori) { + // float glMatrix[16]; + vec3_t delta; + float axisLength; - if ( ent->e.reType != RT_MODEL ) { + if (ent->e.reType != RT_MODEL) { *ori = viewParms->world; return; } - VectorCopy( ent->e.origin, ori->origin ); + VectorCopy(ent->e.origin, ori->origin); - VectorCopy( ent->e.axis[0], ori->axis[0] ); - VectorCopy( ent->e.axis[1], ori->axis[1] ); - VectorCopy( ent->e.axis[2], ori->axis[2] ); + VectorCopy(ent->e.axis[0], ori->axis[0]); + VectorCopy(ent->e.axis[1], ori->axis[1]); + VectorCopy(ent->e.axis[2], ori->axis[2]); preTransEntMatrix[0] = ori->axis[0][0]; preTransEntMatrix[4] = ori->axis[1][0]; @@ -381,16 +345,16 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, preTransEntMatrix[11] = 0; preTransEntMatrix[15] = 1; - myGlMultMatrix( preTransEntMatrix, viewParms->world.modelMatrix, ori->modelMatrix ); + myGlMultMatrix(preTransEntMatrix, viewParms->world.modelMatrix, ori->modelMatrix); // calculate the viewer origin in the model's space // needed for fog, specular, and environment mapping - VectorSubtract( viewParms->ori.origin, ori->origin, delta ); + VectorSubtract(viewParms->ori.origin, ori->origin, delta); // compensate for scale in the axes if necessary - if ( ent->e.nonNormalizedAxes ) { - axisLength = VectorLength( ent->e.axis[0] ); - if ( !axisLength ) { + if (ent->e.nonNormalizedAxes) { + axisLength = VectorLength(ent->e.axis[0]); + if (!axisLength) { axisLength = 0; } else { axisLength = 1.0 / axisLength; @@ -399,9 +363,9 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, axisLength = 1.0; } - ori->viewOrigin[0] = DotProduct( delta, ori->axis[0] ) * axisLength; - ori->viewOrigin[1] = DotProduct( delta, ori->axis[1] ) * axisLength; - ori->viewOrigin[2] = DotProduct( delta, ori->axis[2] ) * axisLength; + ori->viewOrigin[0] = DotProduct(delta, ori->axis[0]) * axisLength; + ori->viewOrigin[1] = DotProduct(delta, ori->axis[1]) * axisLength; + ori->viewOrigin[2] = DotProduct(delta, ori->axis[2]) * axisLength; } /* @@ -411,19 +375,18 @@ R_RotateForViewer Sets up the modelview matrix for a given viewParm ================= */ -void R_RotateForViewer (void) -{ - float viewerMatrix[16]; - vec3_t origin; +void R_RotateForViewer(void) { + float viewerMatrix[16]; + vec3_t origin; - memset (&tr.ori, 0, sizeof(tr.ori)); + memset(&tr.ori, 0, sizeof(tr.ori)); tr.ori.axis[0][0] = 1; tr.ori.axis[1][1] = 1; tr.ori.axis[2][2] = 1; - VectorCopy (tr.viewParms.ori.origin, tr.ori.viewOrigin); + VectorCopy(tr.viewParms.ori.origin, tr.ori.viewOrigin); // transform by the camera placement - VectorCopy( tr.viewParms.ori.origin, origin ); + VectorCopy(tr.viewParms.ori.origin, origin); viewerMatrix[0] = tr.viewParms.ori.axis[0][0]; viewerMatrix[4] = tr.viewParms.ori.axis[0][1]; @@ -447,23 +410,21 @@ void R_RotateForViewer (void) // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - myGlMultMatrix( viewerMatrix, s_flipMatrix, tr.ori.modelMatrix ); + myGlMultMatrix(viewerMatrix, s_flipMatrix, tr.ori.modelMatrix); tr.viewParms.world = tr.ori; - } /* ** SetFarClip */ -static void SetFarClip( void ) -{ - float farthestCornerDistance = 0; - int i; +static void SetFarClip(void) { + float farthestCornerDistance = 0; + int i; // if not rendering the world (icons, menus, etc) // set a 2k far clip plane - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { tr.viewParms.zFar = 2048; return; } @@ -471,61 +432,49 @@ static void SetFarClip( void ) // // set far clipping planes dynamically // - for ( i = 0; i < 8; i++ ) - { + for (i = 0; i < 8; i++) { vec3_t v; float distance; - if ( i & 1 ) - { + if (i & 1) { v[0] = tr.viewParms.visBounds[0][0]; - } - else - { + } else { v[0] = tr.viewParms.visBounds[1][0]; } - if ( i & 2 ) - { + if (i & 2) { v[1] = tr.viewParms.visBounds[0][1]; - } - else - { + } else { v[1] = tr.viewParms.visBounds[1][1]; } - if ( i & 4 ) - { + if (i & 4) { v[2] = tr.viewParms.visBounds[0][2]; - } - else - { + } else { v[2] = tr.viewParms.visBounds[1][2]; } distance = DistanceSquared(tr.viewParms.ori.origin, v); - if ( distance > farthestCornerDistance ) - { + if (distance > farthestCornerDistance) { farthestCornerDistance = distance; } } // Bring in the zFar to the distanceCull distance // The sky renders at zFar so need to move it out a little // ...and make sure there is a minimum zfar to prevent problems - tr.viewParms.zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf( farthestCornerDistance )); + tr.viewParms.zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf(farthestCornerDistance)); } - /* =============== R_SetupProjection =============== */ -void R_SetupProjection( void ) { - float xmin, xmax, ymin, ymax; - float width, height, depth; - float zNear, zFar; +void R_SetupProjection(void) { + float xmin, xmax, ymin, ymax; + float width, height, depth; + float zNear, zFar; // dynamically compute far clip plane distance SetFarClip(); @@ -533,13 +482,13 @@ void R_SetupProjection( void ) { // // set up projection matrix // - zNear = r_znear->value; - zFar = tr.viewParms.zFar; + zNear = r_znear->value; + zFar = tr.viewParms.zFar; - ymax = zNear * tan( tr.refdef.fov_y * M_PI / 360.0f ); + ymax = zNear * tan(tr.refdef.fov_y * M_PI / 360.0f); ymin = -ymax; - xmax = zNear * tan( tr.refdef.fov_x * M_PI / 360.0f ); + xmax = zNear * tan(tr.refdef.fov_x * M_PI / 360.0f); xmin = -xmax; width = xmax - xmin; @@ -548,17 +497,17 @@ void R_SetupProjection( void ) { tr.viewParms.projectionMatrix[0] = 2 * zNear / width; tr.viewParms.projectionMatrix[4] = 0; - tr.viewParms.projectionMatrix[8] = ( xmax + xmin ) / width; // normally 0 + tr.viewParms.projectionMatrix[8] = (xmax + xmin) / width; // normally 0 tr.viewParms.projectionMatrix[12] = 0; tr.viewParms.projectionMatrix[1] = 0; tr.viewParms.projectionMatrix[5] = 2 * zNear / height; - tr.viewParms.projectionMatrix[9] = ( ymax + ymin ) / height; // normally 0 + tr.viewParms.projectionMatrix[9] = (ymax + ymin) / height; // normally 0 tr.viewParms.projectionMatrix[13] = 0; tr.viewParms.projectionMatrix[2] = 0; tr.viewParms.projectionMatrix[6] = 0; - tr.viewParms.projectionMatrix[10] = -( zFar + zNear ) / depth; + tr.viewParms.projectionMatrix[10] = -(zFar + zNear) / depth; tr.viewParms.projectionMatrix[14] = -2 * zFar * zNear / depth; tr.viewParms.projectionMatrix[3] = 0; @@ -574,96 +523,92 @@ R_SetupFrustum Setup that culling frustum planes for the current view ================= */ -void R_SetupFrustum (void) { - int i; - float xs, xc; - float ang; +void R_SetupFrustum(void) { + int i; + float xs, xc; + float ang; ang = tr.viewParms.fovX / 180 * M_PI * 0.5; - xs = sin( ang ); - xc = cos( ang ); + xs = sin(ang); + xc = cos(ang); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[0].normal ); - VectorMA( tr.viewParms.frustum[0].normal, xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[0].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[0].normal); + VectorMA(tr.viewParms.frustum[0].normal, xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[0].normal); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[1].normal ); - VectorMA( tr.viewParms.frustum[1].normal, -xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[1].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[1].normal); + VectorMA(tr.viewParms.frustum[1].normal, -xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[1].normal); ang = tr.viewParms.fovY / 180 * M_PI * 0.5; - xs = sin( ang ); - xc = cos( ang ); - - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[2].normal ); - VectorMA( tr.viewParms.frustum[2].normal, xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[2].normal ); + xs = sin(ang); + xc = cos(ang); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[3].normal ); - VectorMA( tr.viewParms.frustum[3].normal, -xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[3].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[2].normal); + VectorMA(tr.viewParms.frustum[2].normal, xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[2].normal); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[3].normal); + VectorMA(tr.viewParms.frustum[3].normal, -xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[3].normal); // this is the far plane - VectorScale( tr.viewParms.ori.axis[0],-1.0f, tr.viewParms.frustum[4].normal ); + VectorScale(tr.viewParms.ori.axis[0], -1.0f, tr.viewParms.frustum[4].normal); - for (i=0 ; i<5 ; i++) { + for (i = 0; i < 5; i++) { tr.viewParms.frustum[i].type = PLANE_NON_AXIAL; - tr.viewParms.frustum[i].dist = DotProduct (tr.viewParms.ori.origin, tr.viewParms.frustum[i].normal); - if (i==4) - { + tr.viewParms.frustum[i].dist = DotProduct(tr.viewParms.ori.origin, tr.viewParms.frustum[i].normal); + if (i == 4) { // far plane does not go through the view point, it goes alot farther.. - tr.viewParms.frustum[i].dist -= tr.distanceCull*1.02f; // a little slack so we don't cull stuff + tr.viewParms.frustum[i].dist -= tr.distanceCull * 1.02f; // a little slack so we don't cull stuff } - SetPlaneSignbits( &tr.viewParms.frustum[i] ); + SetPlaneSignbits(&tr.viewParms.frustum[i]); } } - /* ================= R_MirrorPoint ================= */ -void R_MirrorPoint (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - vec3_t local; - vec3_t transformed; - float d; +void R_MirrorPoint(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + vec3_t local; + vec3_t transformed; + float d; - VectorSubtract( in, surface->origin, local ); + VectorSubtract(in, surface->origin, local); - VectorClear( transformed ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(transformed); + for (i = 0; i < 3; i++) { d = DotProduct(local, surface->axis[i]); - VectorMA( transformed, d, camera->axis[i], transformed ); + VectorMA(transformed, d, camera->axis[i], transformed); } - VectorAdd( transformed, camera->origin, out ); + VectorAdd(transformed, camera->origin, out); } -void R_MirrorVector (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - float d; +void R_MirrorVector(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + float d; - VectorClear( out ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(out); + for (i = 0; i < 3; i++) { d = DotProduct(in, surface->axis[i]); - VectorMA( out, d, camera->axis[i], out ); + VectorMA(out, d, camera->axis[i], out); } } - /* ============= R_PlaneForSurface ============= */ -void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { - srfTriangles_t *tri; +void R_PlaneForSurface(surfaceType_t *surfType, cplane_t *plane) { + srfTriangles_t *tri; srfGridMesh_t *grid; - srfPoly_t *poly; - drawVert_t *v1, *v2, *v3; - vec4_t plane4; + srfPoly_t *poly; + drawVert_t *v1, *v2, *v3; + vec4_t plane4; if (!surfType) { - memset (plane, 0, sizeof(*plane)); + memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -676,14 +621,14 @@ void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { v1 = tri->verts + tri->indexes[0]; v2 = tri->verts + tri->indexes[1]; v3 = tri->verts + tri->indexes[2]; - PlaneFromPoints( plane4, v1->xyz, v2->xyz, v3->xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, v1->xyz, v2->xyz, v3->xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; case SF_POLY: poly = (srfPoly_t *)surfType; - PlaneFromPoints( plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; case SF_GRID: @@ -691,12 +636,12 @@ void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { v1 = &grid->verts[0]; v2 = &grid->verts[1]; v3 = &grid->verts[2]; - PlaneFromPoints( plane4, v3->xyz, v2->xyz, v1->xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, v3->xyz, v2->xyz, v1->xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; default: - memset (plane, 0, sizeof(*plane)); + memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -712,67 +657,63 @@ be moving and rotating. Returns qtrue if it should be mirrored ================= */ -qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, - orientation_t *surface, orientation_t *camera, - vec3_t pvsOrigin, qboolean *mirror ) { - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; - vec3_t transformed; +qboolean R_GetPortalOrientations(drawSurf_t *drawSurf, int entityNum, orientation_t *surface, orientation_t *camera, vec3_t pvsOrigin, qboolean *mirror) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; + vec3_t transformed; // create plane axis for the portal we are seeing - R_PlaneForSurface( drawSurf->surface, &originalPlane ); + R_PlaneForSurface(drawSurf->surface, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) { + if (entityNum != REFENTITYNUM_WORLD) { tr.currentEntityNum = entityNum; tr.currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(tr.currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); } else { plane = originalPlane; } - VectorCopy( plane.normal, surface->axis[0] ); - PerpendicularVector( surface->axis[1], surface->axis[0] ); - CrossProduct( surface->axis[0], surface->axis[1], surface->axis[2] ); + VectorCopy(plane.normal, surface->axis[0]); + PerpendicularVector(surface->axis[1], surface->axis[0]); + CrossProduct(surface->axis[0], surface->axis[1], surface->axis[2]); // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // get the pvsOrigin from the entity - VectorCopy( e->e.oldorigin, pvsOrigin ); + VectorCopy(e->e.oldorigin, pvsOrigin); // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) { - VectorScale( plane.normal, plane.dist, surface->origin ); - VectorCopy( surface->origin, camera->origin ); - VectorSubtract( vec3_origin, surface->axis[0], camera->axis[0] ); - VectorCopy( surface->axis[1], camera->axis[1] ); - VectorCopy( surface->axis[2], camera->axis[2] ); + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { + VectorScale(plane.normal, plane.dist, surface->origin); + VectorCopy(surface->origin, camera->origin); + VectorSubtract(vec3_origin, surface->axis[0], camera->axis[0]); + VectorCopy(surface->axis[1], camera->axis[1]); + VectorCopy(surface->axis[2], camera->axis[2]); *mirror = qtrue; return qtrue; @@ -780,29 +721,29 @@ qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, // project the origin onto the surface plane to get // an origin point we can rotate around - d = DotProduct( e->e.origin, plane.normal ) - plane.dist; - VectorMA( e->e.origin, -d, surface->axis[0], surface->origin ); + d = DotProduct(e->e.origin, plane.normal) - plane.dist; + VectorMA(e->e.origin, -d, surface->axis[0], surface->origin); // now get the camera origin and orientation - VectorCopy( e->e.oldorigin, camera->origin ); - AxisCopy( e->e.axis, camera->axis ); - VectorSubtract( vec3_origin, camera->axis[0], camera->axis[0] ); - VectorSubtract( vec3_origin, camera->axis[1], camera->axis[1] ); + VectorCopy(e->e.oldorigin, camera->origin); + AxisCopy(e->e.axis, camera->axis); + VectorSubtract(vec3_origin, camera->axis[0], camera->axis[0]); + VectorSubtract(vec3_origin, camera->axis[1], camera->axis[1]); // optionally rotate - if ( e->e.frame ) { + if (e->e.frame) { // continuous rotate - d = (tr.refdef.time/1000.0f) * e->e.frame; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); - } else if (e->e.skinNum){ + d = (tr.refdef.time / 1000.0f) * e->e.frame; + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); + } else if (e->e.skinNum) { // bobbing rotate - //d = 4 * sin( tr.refdef.time * 0.003 ); + // d = 4 * sin( tr.refdef.time * 0.003 ); d = e->e.skinNum; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } *mirror = qfalse; return qtrue; @@ -817,63 +758,55 @@ qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, // to see a surface before the server has communicated the matching // portal surface entity, so we don't want to print anything here... - //ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); + // ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); return qfalse; } -static qboolean IsMirror( const drawSurf_t *drawSurf, int entityNum ) -{ - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; +static qboolean IsMirror(const drawSurf_t *drawSurf, int entityNum) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; // create plane axis for the portal we are seeing - R_PlaneForSurface( drawSurf->surface, &originalPlane ); + R_PlaneForSurface(drawSurf->surface, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) - { + if (entityNum != REFENTITYNUM_WORLD) { tr.currentEntityNum = entityNum; tr.currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(tr.currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); - } - else - { + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); + } else { plane = originalPlane; } // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) - { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) - { + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { return qtrue; } @@ -887,12 +820,12 @@ static qboolean IsMirror( const drawSurf_t *drawSurf, int entityNum ) ** ** Determines if a surface is completely offscreen. */ -static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128] ) { +static qboolean SurfIsOffscreen(const drawSurf_t *drawSurf, vec4_t clipDest[128]) { float shortest = 1000000000; int entityNum; int numTriangles; shader_t *shader; - int fogNum; + int fogNum; int dlighted; vec4_t clip, eye; int i; @@ -901,28 +834,23 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 R_RotateForViewer(); - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted ); - RB_BeginSurface( shader, fogNum ); - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted); + RB_BeginSurface(shader, fogNum); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); - assert( tess.numVertexes < 128 ); + assert(tess.numVertexes < 128); - for ( i = 0; i < tess.numVertexes; i++ ) - { + for (i = 0; i < tess.numVertexes; i++) { int j; unsigned int pointFlags = 0; - R_TransformModelToClip( tess.xyz[i], tr.ori.modelMatrix, tr.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(tess.xyz[i], tr.ori.modelMatrix, tr.viewParms.projectionMatrix, eye, clip); - for ( j = 0; j < 3; j++ ) - { - if ( clip[j] >= clip[3] ) - { - pointFlags |= (1 << (j*2)); - } - else if ( clip[j] <= -clip[3] ) - { - pointFlags |= ( 1 << (j*2+1)); + for (j = 0; j < 3; j++) { + if (clip[j] >= clip[3]) { + pointFlags |= (1 << (j * 2)); + } else if (clip[j] <= -clip[3]) { + pointFlags |= (1 << (j * 2 + 1)); } } pointAnd &= pointFlags; @@ -930,8 +858,7 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 } // trivially reject - if ( pointAnd ) - { + if (pointAnd) { return qtrue; } @@ -942,39 +869,33 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 // we have in the game right now. numTriangles = tess.numIndexes / 3; - for ( i = 0; i < tess.numIndexes; i += 3 ) - { + for (i = 0; i < tess.numIndexes; i += 3) { vec3_t normal; float dot; float len; - VectorSubtract( tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal ); + VectorSubtract(tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal); - len = VectorLengthSquared( normal ); // lose the sqrt - if ( len < shortest ) - { + len = VectorLengthSquared(normal); // lose the sqrt + if (len < shortest) { shortest = len; } - if ( ( dot = DotProduct( normal, tess.normal[tess.indexes[i]] ) ) >= 0 ) - { + if ((dot = DotProduct(normal, tess.normal[tess.indexes[i]])) >= 0) { numTriangles--; } } - if ( !numTriangles ) - { + if (!numTriangles) { return qtrue; } // mirrors can early out at this point, since we don't do a fade over distance // with them (although we could) - if ( IsMirror( drawSurf, entityNum ) ) - { + if (IsMirror(drawSurf, entityNum)) { return qfalse; } - if ( shortest > (tess.shader->portalRange * tess.shader->portalRange)) - { + if (shortest > (tess.shader->portalRange * tess.shader->portalRange)) { return qtrue; } @@ -988,26 +909,25 @@ R_MirrorViewBySurface Returns qtrue if another view has been rendered ======================== */ -int recursivePortalCount; -qboolean R_MirrorViewBySurface (drawSurf_t *drawSurf, int entityNum) { - vec4_t clipDest[128]; - viewParms_t newParms; - viewParms_t oldParms; - orientation_t surface, camera; +int recursivePortalCount; +qboolean R_MirrorViewBySurface(drawSurf_t *drawSurf, int entityNum) { + vec4_t clipDest[128]; + viewParms_t newParms; + viewParms_t oldParms; + orientation_t surface, camera; // don't recursively mirror - if (tr.viewParms.isPortal) - { - ri.Printf( PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n" ); + if (tr.viewParms.isPortal) { + ri.Printf(PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n"); return qfalse; } - if ( r_noportals->integer || r_fastsky->integer ) { + if (r_noportals->integer || r_fastsky->integer) { return qfalse; } // trivially reject portal/mirror - if ( SurfIsOffscreen( drawSurf, clipDest ) ) { + if (SurfIsOffscreen(drawSurf, clipDest)) { return qfalse; } @@ -1016,24 +936,23 @@ qboolean R_MirrorViewBySurface (drawSurf_t *drawSurf, int entityNum) { newParms = tr.viewParms; newParms.isPortal = qtrue; - if ( !R_GetPortalOrientations( drawSurf, entityNum, &surface, &camera, - newParms.pvsOrigin, &newParms.isMirror ) ) { - return qfalse; // bad portal, no portalentity + if (!R_GetPortalOrientations(drawSurf, entityNum, &surface, &camera, newParms.pvsOrigin, &newParms.isMirror)) { + return qfalse; // bad portal, no portalentity } - R_MirrorPoint (oldParms.ori.origin, &surface, &camera, newParms.ori.origin ); + R_MirrorPoint(oldParms.ori.origin, &surface, &camera, newParms.ori.origin); - VectorSubtract( vec3_origin, camera.axis[0], newParms.portalPlane.normal ); - newParms.portalPlane.dist = DotProduct( camera.origin, newParms.portalPlane.normal ); + VectorSubtract(vec3_origin, camera.axis[0], newParms.portalPlane.normal); + newParms.portalPlane.dist = DotProduct(camera.origin, newParms.portalPlane.normal); - R_MirrorVector (oldParms.ori.axis[0], &surface, &camera, newParms.ori.axis[0]); - R_MirrorVector (oldParms.ori.axis[1], &surface, &camera, newParms.ori.axis[1]); - R_MirrorVector (oldParms.ori.axis[2], &surface, &camera, newParms.ori.axis[2]); + R_MirrorVector(oldParms.ori.axis[0], &surface, &camera, newParms.ori.axis[0]); + R_MirrorVector(oldParms.ori.axis[1], &surface, &camera, newParms.ori.axis[1]); + R_MirrorVector(oldParms.ori.axis[2], &surface, &camera, newParms.ori.axis[2]); // OPTIMIZE: restrict the viewport on the mirrored view // render the mirror view - R_RenderView (&newParms); + R_RenderView(&newParms); tr.viewParms = oldParms; @@ -1047,44 +966,37 @@ R_SpriteFogNum See if a sprite is inside a fog volume ================= */ -int R_SpriteFogNum( trRefEntity_t *ent ) { - int i; - fog_t *fog; +int R_SpriteFogNum(trRefEntity_t *ent) { + int i; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - if ( tr.refdef.doLAGoggles ) - { + if (tr.refdef.doLAGoggles) { return tr.world->numfogs; } int partialFog = 0; - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - if ( ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] - && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] - && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] - && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] - && ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] - && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2] ) - {//totally inside it + if (ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && + ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2]) { // totally inside it return i; break; } - if ( ( ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && - ent->e.origin[0] - ent->e.radius <= fog->bounds[1][0] && ent->e.origin[1] - ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] - ent->e.radius <= fog->bounds[1][2] ) || - ( ent->e.origin[0] + ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] + ent->e.radius >= fog->bounds[0][1] && ent->e.origin[2] + ent->e.radius >= fog->bounds[0][2] && - ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2] ) ) - {//partially inside it - if ( tr.refdef.fogIndex == i || R_FogParmsMatch( tr.refdef.fogIndex, i ) ) - {//take new one only if it's the same one that the viewpoint is in + if ((ent->e.origin[0] - ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] - ent->e.radius >= fog->bounds[0][1] && + ent->e.origin[2] - ent->e.radius >= fog->bounds[0][2] && ent->e.origin[0] - ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] - ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] - ent->e.radius <= fog->bounds[1][2]) || + (ent->e.origin[0] + ent->e.radius >= fog->bounds[0][0] && ent->e.origin[1] + ent->e.radius >= fog->bounds[0][1] && + ent->e.origin[2] + ent->e.radius >= fog->bounds[0][2] && ent->e.origin[0] + ent->e.radius <= fog->bounds[1][0] && + ent->e.origin[1] + ent->e.radius <= fog->bounds[1][1] && ent->e.origin[2] + ent->e.radius <= fog->bounds[1][2])) { // partially inside it + if (tr.refdef.fogIndex == i || R_FogParmsMatch(tr.refdef.fogIndex, i)) { // take new one only if it's the same one that the viewpoint is in return i; break; - } - else if ( !partialFog ) - {//first partialFog + } else if (!partialFog) { // first partialFog partialFog = i; } } @@ -1106,27 +1018,26 @@ DRAWSURF SORTING R_Radix =============== */ -static QINLINE void R_Radix( int byte, int size, drawSurf_t *source, drawSurf_t *dest ) -{ - int count[ 256 ] = { 0 }; - int index[ 256 ]; - int i; - unsigned char *sortKey = NULL; - unsigned char *end = NULL; +static QINLINE void R_Radix(int byte, int size, drawSurf_t *source, drawSurf_t *dest) { + int count[256] = {0}; + int index[256]; + int i; + unsigned char *sortKey = NULL; + unsigned char *end = NULL; - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - end = sortKey + ( size * sizeof( drawSurf_t ) ); - for( ; sortKey < end; sortKey += sizeof( drawSurf_t ) ) - ++count[ *sortKey ]; + sortKey = ((unsigned char *)&source[0].sort) + byte; + end = sortKey + (size * sizeof(drawSurf_t)); + for (; sortKey < end; sortKey += sizeof(drawSurf_t)) + ++count[*sortKey]; - index[ 0 ] = 0; + index[0] = 0; - for( i = 1; i < 256; ++i ) - index[ i ] = index[ i - 1 ] + count[ i - 1 ]; + for (i = 1; i < 256; ++i) + index[i] = index[i - 1] + count[i - 1]; - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - for( i = 0; i < size; ++i, sortKey += sizeof( drawSurf_t ) ) - dest[ index[ *sortKey ]++ ] = source[ i ]; + sortKey = ((unsigned char *)&source[0].sort) + byte; + for (i = 0; i < size; ++i, sortKey += sizeof(drawSurf_t)) + dest[index[*sortKey]++] = source[i]; } /* @@ -1136,20 +1047,19 @@ R_RadixSort Radix sort with 4 byte size buckets =============== */ -static void R_RadixSort( drawSurf_t *source, int size ) -{ - static drawSurf_t scratch[ MAX_DRAWSURFS ]; +static void R_RadixSort(drawSurf_t *source, int size) { + static drawSurf_t scratch[MAX_DRAWSURFS]; #ifdef Q3_LITTLE_ENDIAN - R_Radix( 0, size, source, scratch ); - R_Radix( 1, size, scratch, source ); - R_Radix( 2, size, source, scratch ); - R_Radix( 3, size, scratch, source ); + R_Radix(0, size, source, scratch); + R_Radix(1, size, scratch, source); + R_Radix(2, size, source, scratch); + R_Radix(3, size, scratch, source); #else - R_Radix( 3, size, source, scratch ); - R_Radix( 2, size, scratch, source ); - R_Radix( 1, size, source, scratch ); - R_Radix( 0, size, scratch, source ); -#endif //Q3_LITTLE_ENDIAN + R_Radix(3, size, source, scratch); + R_Radix(2, size, scratch, source); + R_Radix(1, size, source, scratch); + R_Radix(0, size, scratch, source); +#endif // Q3_LITTLE_ENDIAN } //========================================================================================== @@ -1159,28 +1069,25 @@ static void R_RadixSort( drawSurf_t *source, int size ) R_AddDrawSurf ================= */ -void R_AddDrawSurf( const surfaceType_t *surface, const shader_t *shader, int fogIndex, int dlightMap ) -{ - int index; +void R_AddDrawSurf(const surfaceType_t *surface, const shader_t *shader, int fogIndex, int dlightMap) { + int index; // instead of checking for overflow, we just mask the index // so it wraps around index = tr.refdef.numDrawSurfs & DRAWSURF_MASK; - if ( tr.refdef.doLAGoggles ) - { + if (tr.refdef.doLAGoggles) { fogIndex = tr.world->numfogs; } - if ( (shader->surfaceFlags & SURF_FORCESIGHT) && !(tr.refdef.rdflags & RDF_ForceSightOn) ) - { //if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw + if ((shader->surfaceFlags & SURF_FORCESIGHT) && + !(tr.refdef.rdflags & RDF_ForceSightOn)) { // if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw return; } // the sort data is packed into a single 32 bit value so it can be // compared quickly during the qsorting process - tr.refdef.drawSurfs[index].sort = (shader->sortedIndex << QSORT_SHADERNUM_SHIFT) - | tr.shiftedEntityNum | ( fogIndex << QSORT_FOGNUM_SHIFT ) | (int)dlightMap; + tr.refdef.drawSurfs[index].sort = (shader->sortedIndex << QSORT_SHADERNUM_SHIFT) | tr.shiftedEntityNum | (fogIndex << QSORT_FOGNUM_SHIFT) | (int)dlightMap; tr.refdef.drawSurfs[index].surface = (surfaceType_t *)surface; tr.refdef.numDrawSurfs++; } @@ -1190,11 +1097,10 @@ void R_AddDrawSurf( const surfaceType_t *surface, const shader_t *shader, int fo R_DecomposeSort ================= */ -void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader, - int *fogNum, int *dlightMap ) { - *fogNum = ( sort >> QSORT_FOGNUM_SHIFT ) & 31; - *shader = tr.sortedShaders[ ( sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1) ]; - *entityNum = ( sort >> QSORT_REFENTITYNUM_SHIFT ) & REFENTITYNUM_MASK; +void R_DecomposeSort(unsigned sort, int *entityNum, shader_t **shader, int *fogNum, int *dlightMap) { + *fogNum = (sort >> QSORT_FOGNUM_SHIFT) & 31; + *shader = tr.sortedShaders[(sort >> QSORT_SHADERNUM_SHIFT) & (MAX_SHADERS - 1)]; + *entityNum = (sort >> QSORT_REFENTITYNUM_SHIFT) & REFENTITYNUM_MASK; *dlightMap = sort & 3; } @@ -1203,54 +1109,54 @@ void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader, R_SortDrawSurfs ================= */ -void R_SortDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { - shader_t *shader; - int fogNum; - int entityNum; - int dlighted; +void R_SortDrawSurfs(drawSurf_t *drawSurfs, int numDrawSurfs) { + shader_t *shader; + int fogNum; + int entityNum; + int dlighted; // it is possible for some views to not have any surfaces - if ( numDrawSurfs < 1 ) { + if (numDrawSurfs < 1) { // we still need to add it for hyperspace cases - R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); + R_AddDrawSurfCmd(drawSurfs, numDrawSurfs); return; } // if we overflowed MAX_DRAWSURFS, the drawsurfs // wrapped around in the buffer and we will be missing // the first surfaces, not the last ones - if ( numDrawSurfs > MAX_DRAWSURFS ) { + if (numDrawSurfs > MAX_DRAWSURFS) { numDrawSurfs = MAX_DRAWSURFS; } // sort the drawsurfs by sort type, then orientation, then shader - R_RadixSort( drawSurfs, numDrawSurfs ); + R_RadixSort(drawSurfs, numDrawSurfs); // check for any pass through drawing, which // may cause another view to be rendered first - for ( int i = 0 ; i < numDrawSurfs ; i++ ) { - R_DecomposeSort( (drawSurfs+i)->sort, &entityNum, &shader, &fogNum, &dlighted ); + for (int i = 0; i < numDrawSurfs; i++) { + R_DecomposeSort((drawSurfs + i)->sort, &entityNum, &shader, &fogNum, &dlighted); - if ( shader->sort > SS_PORTAL ) { + if (shader->sort > SS_PORTAL) { break; } // no shader should ever have this sort type - if ( shader->sort == SS_BAD ) { - Com_Error (ERR_DROP, "Shader '%s'with sort == SS_BAD", shader->name ); + if (shader->sort == SS_BAD) { + Com_Error(ERR_DROP, "Shader '%s'with sort == SS_BAD", shader->name); } // if the mirror was completely clipped away, we may need to check another surface - if ( R_MirrorViewBySurface( (drawSurfs+i), entityNum) ) { + if (R_MirrorViewBySurface((drawSurfs + i), entityNum)) { // this is a debug option to see exactly what is being mirrored - if ( r_portalOnly->integer ) { + if (r_portalOnly->integer) { return; } - break; // only one mirror view at a time + break; // only one mirror view at a time } } - R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); + R_AddDrawSurfCmd(drawSurfs, numDrawSurfs); } /* @@ -1258,17 +1164,15 @@ void R_SortDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { R_AddEntitySurfaces ============= */ -void R_AddEntitySurfaces (void) { - trRefEntity_t *ent; - shader_t *shader; +void R_AddEntitySurfaces(void) { + trRefEntity_t *ent; + shader_t *shader; - if ( !r_drawentities->integer ) { + if (!r_drawentities->integer) { return; } - for ( tr.currentEntityNum = 0; - tr.currentEntityNum < tr.refdef.num_entities; - tr.currentEntityNum++ ) { + for (tr.currentEntityNum = 0; tr.currentEntityNum < tr.refdef.num_entities; tr.currentEntityNum++) { ent = tr.currentEntity = &tr.refdef.entities[tr.currentEntityNum]; ent->needDlights = qfalse; @@ -1276,8 +1180,7 @@ void R_AddEntitySurfaces (void) { // preshift the value we are going to OR into the drawsurf sort tr.shiftedEntityNum = tr.currentEntityNum << QSORT_REFENTITYNUM_SHIFT; - if ((ent->e.renderfx & RF_ALPHA_FADE)) - { + if ((ent->e.renderfx & RF_ALPHA_FADE)) { // we need to make sure this is not sorted before the world..in fact we // want this to be sorted quite late...like how about last. // I don't want to use the highest bit, since no doubt someone fumbled @@ -1289,15 +1192,14 @@ void R_AddEntitySurfaces (void) { // we don't want the hacked weapon position showing in // mirrors, because the true body position will already be drawn // - if ( (ent->e.renderfx & RF_FIRST_PERSON) && tr.viewParms.isPortal) { + if ((ent->e.renderfx & RF_FIRST_PERSON) && tr.viewParms.isPortal) { continue; } - // simple generated models, like sprites and beams, are not culled - switch ( ent->e.reType ) { + switch (ent->e.reType) { case RT_PORTALSURFACE: - break; // don't draw anything + break; // don't draw anything case RT_SPRITE: case RT_ORIENTED_QUAD: case RT_BEAM: @@ -1310,77 +1212,72 @@ void R_AddEntitySurfaces (void) { // self blood sprites, talk balloons, etc should not be drawn in the primary // view. We can't just do this check for all entities, because md3 // entities may still want to cast shadows from them - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { continue; } - shader = R_GetShaderByHandle( ent->e.customShader ); - R_AddDrawSurf( &entitySurface, shader, R_SpriteFogNum( ent ), 0 ); + shader = R_GetShaderByHandle(ent->e.customShader); + R_AddDrawSurf(&entitySurface, shader, R_SpriteFogNum(ent), 0); break; case RT_MODEL: // we must set up parts of tr.or for model culling - R_RotateForEntity( ent, &tr.viewParms, &tr.ori ); + R_RotateForEntity(ent, &tr.viewParms, &tr.ori); - tr.currentModel = R_GetModelByHandle( ent->e.hModel ); + tr.currentModel = R_GetModelByHandle(ent->e.hModel); if (!tr.currentModel) { - R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, 0 ); + R_AddDrawSurf(&entitySurface, tr.defaultShader, 0, 0); } else { - switch ( tr.currentModel->type ) { + switch (tr.currentModel->type) { case MOD_MESH: - R_AddMD3Surfaces( ent ); + R_AddMD3Surfaces(ent); break; case MOD_BRUSH: - R_AddBrushModelSurfaces( ent ); + R_AddBrushModelSurfaces(ent); break; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ case MOD_MDXM: - R_AddGhoulSurfaces( ent); - break; - case MOD_BAD: // null model axis - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) - { - if (!(ent->e.renderfx & RF_SHADOW_ONLY)) - { - break; - } + R_AddGhoulSurfaces(ent); + break; + case MOD_BAD: // null model axis + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + if (!(ent->e.renderfx & RF_SHADOW_ONLY)) { + break; + } } - if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) - { - R_AddGhoulSurfaces( ent); - break; - } + if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) { + R_AddGhoulSurfaces(ent); + break; + } - R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, false ); + R_AddDrawSurf(&entitySurface, tr.defaultShader, 0, false); break; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ default: - Com_Error( ERR_DROP, "R_AddEntitySurfaces: Bad modeltype" ); + Com_Error(ERR_DROP, "R_AddEntitySurfaces: Bad modeltype"); break; } } break; default: - Com_Error( ERR_DROP, "R_AddEntitySurfaces: Bad reType" ); + Com_Error(ERR_DROP, "R_AddEntitySurfaces: Bad reType"); } } - } - /* ==================== R_GenerateDrawSurfs ==================== */ -void R_GenerateDrawSurfs( void ) { - R_AddWorldSurfaces (); +void R_GenerateDrawSurfs(void) { + R_AddWorldSurfaces(); R_AddPolygonSurfaces(); @@ -1389,9 +1286,9 @@ void R_GenerateDrawSurfs( void ) { // this needs to be done before entities are // added, because they use the projection // matrix for lod calculation - R_SetupProjection (); + R_SetupProjection(); - R_AddEntitySurfaces (); + R_AddEntitySurfaces(); } /* @@ -1399,30 +1296,30 @@ void R_GenerateDrawSurfs( void ) { R_DebugPolygon ================ */ -void R_DebugPolygon( int color, int numPoints, float *points ) { - int i; +void R_DebugPolygon(int color, int numPoints, float *points) { + int i; - GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + GL_State(GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); // draw solid shade - qglColor3f( color&1, (color>>1)&1, (color>>2)&1 ); - qglBegin( GL_POLYGON ); - for ( i = 0 ; i < numPoints ; i++ ) { - qglVertex3fv( points + i * 3 ); + qglColor3f(color & 1, (color >> 1) & 1, (color >> 2) & 1); + qglBegin(GL_POLYGON); + for (i = 0; i < numPoints; i++) { + qglVertex3fv(points + i * 3); } qglEnd(); // draw wireframe outline - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); - qglDepthRange( 0, 0 ); - qglColor3f( 1, 1, 1 ); - qglBegin( GL_POLYGON ); - for ( i = 0 ; i < numPoints ; i++ ) { - qglVertex3fv( points + i * 3 ); + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); + qglDepthRange(0, 0); + qglColor3f(1, 1, 1); + qglBegin(GL_POLYGON); + for (i = 0; i < numPoints; i++) { + qglVertex3fv(points + i * 3); } qglEnd(); - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } /* @@ -1432,68 +1329,52 @@ R_DebugGraphics Visualization aid for movement clipping debugging ==================== */ -void R_DebugGraphics( void ) { - if ( !r_debugSurface->integer ) { +void R_DebugGraphics(void) { + if (!r_debugSurface->integer) { return; } // the render thread can't make callbacks to the main thread R_IssuePendingRenderCommands(); // - GL_Bind( tr.whiteImage); - GL_Cull( CT_FRONT_SIDED ); - ri.CM_DrawDebugSurface( R_DebugPolygon ); + GL_Bind(tr.whiteImage); + GL_Cull(CT_FRONT_SIDED); + ri.CM_DrawDebugSurface(R_DebugPolygon); } -qboolean R_FogParmsMatch( int fog1, int fog2 ) -{ - for ( int i = 0; i < 2; i++ ) - { - if ( tr.world->fogs[fog1].parms.color[i] != tr.world->fogs[fog2].parms.color[i] ) - { +qboolean R_FogParmsMatch(int fog1, int fog2) { + for (int i = 0; i < 2; i++) { + if (tr.world->fogs[fog1].parms.color[i] != tr.world->fogs[fog2].parms.color[i]) { return qfalse; } } return qtrue; } -void R_SetViewFogIndex (void) -{ - if ( tr.world->numfogs > 1 ) - {//more than just the LA goggles +void R_SetViewFogIndex(void) { + if (tr.world->numfogs > 1) { // more than just the LA goggles fog_t *fog; - int contents = ri.SV_PointContents( tr.refdef.vieworg, 0 ); - if ( (contents&CONTENTS_FOG) ) - {//only take a tr.refdef.fogIndex if the tr.refdef.vieworg is actually *in* that fog brush (assumption: checks pointcontents for any CONTENTS_FOG, not that particular brush...) - for ( tr.refdef.fogIndex = 1 ; tr.refdef.fogIndex < tr.world->numfogs ; tr.refdef.fogIndex++ ) - { + int contents = ri.SV_PointContents(tr.refdef.vieworg, 0); + if ((contents & CONTENTS_FOG)) { // only take a tr.refdef.fogIndex if the tr.refdef.vieworg is actually *in* that fog brush (assumption: checks + // pointcontents for any CONTENTS_FOG, not that particular brush...) + for (tr.refdef.fogIndex = 1; tr.refdef.fogIndex < tr.world->numfogs; tr.refdef.fogIndex++) { fog = &tr.world->fogs[tr.refdef.fogIndex]; - if ( tr.refdef.vieworg[0] >= fog->bounds[0][0] - && tr.refdef.vieworg[1] >= fog->bounds[0][1] - && tr.refdef.vieworg[2] >= fog->bounds[0][2] - && tr.refdef.vieworg[0] <= fog->bounds[1][0] - && tr.refdef.vieworg[1] <= fog->bounds[1][1] - && tr.refdef.vieworg[2] <= fog->bounds[1][2] ) - { + if (tr.refdef.vieworg[0] >= fog->bounds[0][0] && tr.refdef.vieworg[1] >= fog->bounds[0][1] && tr.refdef.vieworg[2] >= fog->bounds[0][2] && + tr.refdef.vieworg[0] <= fog->bounds[1][0] && tr.refdef.vieworg[1] <= fog->bounds[1][1] && tr.refdef.vieworg[2] <= fog->bounds[1][2]) { break; } } - if ( tr.refdef.fogIndex == tr.world->numfogs ) - { + if (tr.refdef.fogIndex == tr.world->numfogs) { tr.refdef.fogIndex = 0; } - } - else - { + } else { tr.refdef.fogIndex = 0; } - } - else - { + } else { tr.refdef.fogIndex = 0; } } -void RE_SetLightStyle(int style, int colors ); +void RE_SetLightStyle(int style, int colors); /* ================ @@ -1503,25 +1384,24 @@ A view may be either the actual camera view, or a mirror / remote location ================ */ -void R_RenderView (viewParms_t *parms) { - int firstDrawSurf; +void R_RenderView(viewParms_t *parms) { + int firstDrawSurf; - if ( parms->viewportWidth <= 0 || parms->viewportHeight <= 0 ) { + if (parms->viewportWidth <= 0 || parms->viewportHeight <= 0) { return; } - if (r_debugStyle->integer >= 0) - { - int i; - color4ub_t whitecolor = {0xff, 0xff, 0xff, 0xff}; - color4ub_t blackcolor = {0x00, 0x00, 0x00, 0xff}; + if (r_debugStyle->integer >= 0) { + int i; + color4ub_t whitecolor = {0xff, 0xff, 0xff, 0xff}; + color4ub_t blackcolor = {0x00, 0x00, 0x00, 0xff}; byteAlias_t *ba = (byteAlias_t *)&blackcolor; - for ( i = 0; i < MAX_LIGHT_STYLES; i++ ) { - RE_SetLightStyle( i, ba->i ); + for (i = 0; i < MAX_LIGHT_STYLES; i++) { + RE_SetLightStyle(i, ba->i); } ba = (byteAlias_t *)&whitecolor; - RE_SetLightStyle( r_debugStyle->integer, ba->i ); + RE_SetLightStyle(r_debugStyle->integer, ba->i); } tr.viewCount++; @@ -1535,18 +1415,17 @@ void R_RenderView (viewParms_t *parms) { tr.viewCount++; // set viewParms.world - R_RotateForViewer (); + R_RotateForViewer(); - R_SetupFrustum (); + R_SetupFrustum(); - if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) - { // Trying to do this with no world is not good. - R_SetViewFogIndex (); + if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) { // Trying to do this with no world is not good. + R_SetViewFogIndex(); } R_GenerateDrawSurfs(); - R_SortDrawSurfs( tr.refdef.drawSurfs + firstDrawSurf, tr.refdef.numDrawSurfs - firstDrawSurf ); + R_SortDrawSurfs(tr.refdef.drawSurfs + firstDrawSurf, tr.refdef.numDrawSurfs - firstDrawSurf); // draw main system development information (surface outlines, etc) R_DebugGraphics(); diff --git a/code/rd-vanilla/tr_marks.cpp b/code/rd-vanilla/tr_marks.cpp index 2da2512ae1..f308c12e71 100644 --- a/code/rd-vanilla/tr_marks.cpp +++ b/code/rd-vanilla/tr_marks.cpp @@ -28,9 +28,9 @@ along with this program; if not, see . #include "tr_local.h" -#define MAX_VERTS_ON_POLY 64 +#define MAX_VERTS_ON_POLY 64 -#define MARKER_OFFSET 0 // 1 +#define MARKER_OFFSET 0 // 1 /* ============= @@ -39,22 +39,21 @@ R_ChopPolyBehindPlane Out must have space for two more vertexes than in ============= */ -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 -static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], - int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], - vec3_t normal, vec_t dist, vec_t epsilon) { - float dists[MAX_VERTS_ON_POLY+4] = { 0 }; - int sides[MAX_VERTS_ON_POLY+4] = { 0 }; - int counts[3]; - float dot; - int i, j; - float *p1, *p2, *clip; - float d; +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 +static void R_ChopPolyBehindPlane(int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], vec3_t normal, + vec_t dist, vec_t epsilon) { + float dists[MAX_VERTS_ON_POLY + 4] = {0}; + int sides[MAX_VERTS_ON_POLY + 4] = {0}; + int counts[3]; + float dot; + int i, j; + float *p1, *p2, *clip; + float d; // don't clip if it might overflow - if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) { + if (numInPoints >= MAX_VERTS_ON_POLY - 2) { *numOutPoints = 0; return; } @@ -62,13 +61,13 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - for ( i = 0 ; i < numInPoints ; i++ ) { - dot = DotProduct( inPoints[i], normal ); + for (i = 0; i < numInPoints; i++) { + dot = DotProduct(inPoints[i], normal); dot -= dist; dists[i] = dot; - if ( dot > epsilon ) { + if (dot > epsilon) { sides[i] = SIDE_FRONT; - } else if ( dot < -epsilon ) { + } else if (dot < -epsilon) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; @@ -80,40 +79,40 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON *numOutPoints = 0; - if ( !counts[0] ) { + if (!counts[0]) { return; } - if ( !counts[1] ) { + if (!counts[1]) { *numOutPoints = numInPoints; - memcpy( outPoints, inPoints, numInPoints * sizeof(vec3_t) ); + memcpy(outPoints, inPoints, numInPoints * sizeof(vec3_t)); return; } - for ( i = 0 ; i < numInPoints ; i++ ) { + for (i = 0; i < numInPoints; i++) { p1 = inPoints[i]; - clip = outPoints[ *numOutPoints ]; + clip = outPoints[*numOutPoints]; - if ( sides[i] == SIDE_ON ) { - VectorCopy( p1, clip ); + if (sides[i] == SIDE_ON) { + VectorCopy(p1, clip); (*numOutPoints)++; continue; } - if ( sides[i] == SIDE_FRONT ) { - VectorCopy( p1, clip ); + if (sides[i] == SIDE_FRONT) { + VectorCopy(p1, clip); (*numOutPoints)++; - clip = outPoints[ *numOutPoints ]; + clip = outPoints[*numOutPoints]; } - if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) { + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) { continue; } // generate a split point - p2 = inPoints[ (i+1) % numInPoints ]; + p2 = inPoints[(i + 1) % numInPoints]; - d = dists[i] - dists[i+1]; - if ( d == 0 ) { + d = dists[i] - dists[i + 1]; + if (d == 0) { dot = 0; } else { dot = dists[i] / d; @@ -121,8 +120,8 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON // clip xyz - for (j=0 ; j<3 ; j++) { - clip[j] = p1[j] + dot * ( p2[j] - p1[j] ); + for (j = 0; j < 3; j++) { + clip[j] = p1[j] + dot * (p2[j] - p1[j]); } (*numOutPoints)++; @@ -137,12 +136,12 @@ R_BoxSurfaces_r */ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **list, int listsize, int *listlength, vec3_t dir) { - int s, c; - msurface_t *surf, **mark; + int s, c; + msurface_t *surf, **mark; // do the tail recursion in a loop - while ( node->contents == -1 ) { - s = BoxOnPlaneSide( mins, maxs, node->plane ); + while (node->contents == -1) { + s = BoxOnPlaneSide(mins, maxs, node->plane); if (s == 1) { node = node->children[0]; } else if (s == 2) { @@ -158,36 +157,33 @@ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **li c = node->nummarksurfaces; while (c--) { // - if (*listlength >= listsize) break; + if (*listlength >= listsize) + break; // surf = *mark; // check if the surface has NOIMPACT or NOMARKS set - if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) ) - || ( surf->shader->contentFlags & CONTENTS_FOG ) ) { + if ((surf->shader->surfaceFlags & (SURF_NOIMPACT | SURF_NOMARKS)) || (surf->shader->contentFlags & CONTENTS_FOG)) { surf->viewCount = tr.viewCount; } // extra check for surfaces to avoid list overflows else if (*(surf->data) == SF_FACE) { // the face plane should go through the box - s = BoxOnPlaneSide( mins, maxs, &(( srfSurfaceFace_t * ) surf->data)->plane ); + s = BoxOnPlaneSide(mins, maxs, &((srfSurfaceFace_t *)surf->data)->plane); if (s == 1 || s == 2) { surf->viewCount = tr.viewCount; - } else if (DotProduct((( srfSurfaceFace_t * ) surf->data)->plane.normal, dir) > -0.5) { - // don't add faces that make sharp angles with the projection direction + } else if (DotProduct(((srfSurfaceFace_t *)surf->data)->plane.normal, dir) > -0.5) { + // don't add faces that make sharp angles with the projection direction surf->viewCount = tr.viewCount; } - } - else if (*(surfaceType_t *) (surf->data) != SF_GRID - && *(surfaceType_t *) (surf->data) != SF_TRIANGLES ) - { + } else if (*(surfaceType_t *)(surf->data) != SF_GRID && *(surfaceType_t *)(surf->data) != SF_TRIANGLES) { surf->viewCount = tr.viewCount; } // check the viewCount because the surface may have // already been added if it spans multiple leafs if (surf->viewCount != tr.viewCount) { surf->viewCount = tr.viewCount; - list[*listlength] = (surfaceType_t *) surf->data; + list[*listlength] = (surfaceType_t *)surf->data; (*listlength)++; } mark++; @@ -200,36 +196,31 @@ R_AddMarkFragments ================= */ -void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], - int numPlanes, vec3_t *normals, float *dists, - int maxPoints, vec3_t pointBuffer, - int maxFragments, markFragment_t *fragmentBuffer, - int *returnedPoints, int *returnedFragments, - vec3_t mins, vec3_t maxs) { +void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], int numPlanes, vec3_t *normals, float *dists, int maxPoints, + vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer, int *returnedPoints, int *returnedFragments, vec3_t mins, + vec3_t maxs) { int pingPong, i; - markFragment_t *mf; + markFragment_t *mf; // chop the surface by all the bounding planes of the to be projected polygon pingPong = 0; - for ( i = 0 ; i < numPlanes ; i++ ) { + for (i = 0; i < numPlanes; i++) { - R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong], - &numClipPoints, clipPoints[!pingPong], - normals[i], dists[i], 0.5 ); + R_ChopPolyBehindPlane(numClipPoints, clipPoints[pingPong], &numClipPoints, clipPoints[!pingPong], normals[i], dists[i], 0.5); pingPong ^= 1; - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { break; } } // completely clipped away? - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { return; } // add this fragment to the returned list - if ( numClipPoints + (*returnedPoints) > maxPoints ) { - return; // not enough space for this polygon + if (numClipPoints + (*returnedPoints) > maxPoints) { + return; // not enough space for this polygon } /* // all the clip points should be within the bounding box @@ -247,7 +238,7 @@ void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POL mf = fragmentBuffer + (*returnedFragments); mf->firstPoint = (*returnedPoints); mf->numPoints = numClipPoints; - memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t) ); + memcpy(pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t)); (*returnedPoints) += numClipPoints; (*returnedFragments)++; @@ -259,43 +250,44 @@ R_MarkFragments ================= */ -int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, - int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) { - int numsurfaces, numPlanes; - int i, j, k, m, n; - surfaceType_t *surfaces[64]; - vec3_t mins, maxs; - int returnedFragments; - int returnedPoints; - vec3_t normals[MAX_VERTS_ON_POLY+2]; - float dists[MAX_VERTS_ON_POLY+2]; - vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; - vec3_t normal; - vec3_t projectionDir; - vec3_t v1, v2; - - //increment view count for double check prevention +int R_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + int numsurfaces, numPlanes; + int i, j, k, m, n; + surfaceType_t *surfaces[64]; + vec3_t mins, maxs; + int returnedFragments; + int returnedPoints; + vec3_t normals[MAX_VERTS_ON_POLY + 2]; + float dists[MAX_VERTS_ON_POLY + 2]; + vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; + vec3_t normal; + vec3_t projectionDir; + vec3_t v1, v2; + + // increment view count for double check prevention tr.viewCount++; // - VectorNormalize2( projection, projectionDir ); + VectorNormalize2(projection, projectionDir); // find all the brushes that are to be considered - ClearBounds( mins, maxs ); - for ( i = 0 ; i < numPoints ; i++ ) { - vec3_t temp; + ClearBounds(mins, maxs); + for (i = 0; i < numPoints; i++) { + vec3_t temp; - AddPointToBounds( points[i], mins, maxs ); - VectorAdd( points[i], projection, temp ); - AddPointToBounds( temp, mins, maxs ); + AddPointToBounds(points[i], mins, maxs); + VectorAdd(points[i], projection, temp); + AddPointToBounds(temp, mins, maxs); // make sure we get all the leafs (also the one(s) in front of the hit surface) - VectorMA( points[i], -20, projectionDir, temp ); - AddPointToBounds( temp, mins, maxs ); + VectorMA(points[i], -20, projectionDir, temp); + AddPointToBounds(temp, mins, maxs); } - if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY; + if (numPoints > MAX_VERTS_ON_POLY) + numPoints = MAX_VERTS_ON_POLY; // create the bounding planes for the to be projected polygon - for ( i = 0 ; i < numPoints ; i++ ) { - VectorSubtract(points[(i+1)%numPoints], points[i], v1); + for (i = 0; i < numPoints; i++) { + VectorSubtract(points[(i + 1) % numPoints], points[i], v1); VectorAdd(points[i], projection, v2); VectorSubtract(points[i], v2, v2); CrossProduct(v1, v2, normals[i]); @@ -305,25 +297,25 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio // add near and far clipping planes for projection VectorCopy(projectionDir, normals[numPoints]); dists[numPoints] = DotProduct(normals[numPoints], points[0]) - 32; - VectorCopy(projectionDir, normals[numPoints+1]); - VectorInverse(normals[numPoints+1]); - dists[numPoints+1] = DotProduct(normals[numPoints+1], points[0]) - 20; + VectorCopy(projectionDir, normals[numPoints + 1]); + VectorInverse(normals[numPoints + 1]); + dists[numPoints + 1] = DotProduct(normals[numPoints + 1], points[0]) - 20; numPlanes = numPoints + 2; numsurfaces = 0; R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir); - //assert(numsurfaces <= 64); - //assert(numsurfaces != 64); + // assert(numsurfaces <= 64); + // assert(numsurfaces != 64); returnedPoints = 0; returnedFragments = 0; - for ( i = 0 ; i < numsurfaces ; i++ ) { + for (i = 0; i < numsurfaces; i++) { if (*surfaces[i] == SF_GRID) { - const srfGridMesh_t * const cv = (srfGridMesh_t *) surfaces[i]; - for ( m = 0 ; m < cv->height - 1 ; m++ ) { - for ( n = 0 ; n < cv->width - 1 ; n++ ) { + const srfGridMesh_t *const cv = (srfGridMesh_t *)surfaces[i]; + for (m = 0; m < cv->height - 1; m++) { + for (n = 0; n < cv->width - 1; n++) { // We triangulate the grid and chop all triangles within // the bounding planes of the to be projected polygon. // LOD is not taken into account, not such a big deal though. @@ -347,7 +339,7 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio const int numClipPoints = 3; - const drawVert_t * const dv = cv->verts + m * cv->width + n; + const drawVert_t *const dv = cv->verts + m * cv->width + n; VectorCopy(dv[0].xyz, clipPoints[0][0]); VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[0].normal, clipPoints[0][0]); @@ -362,14 +354,11 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.1) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } @@ -377,8 +366,8 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[1].normal, clipPoints[0][0]); VectorCopy(dv[cv->width].xyz, clipPoints[0][1]); VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]); - VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]); - VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width+1].normal, clipPoints[0][2]); + VectorCopy(dv[cv->width + 1].xyz, clipPoints[0][2]); + VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width + 1].normal, clipPoints[0][2]); // check the normal of this triangle VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1); VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2); @@ -386,79 +375,63 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.05) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } } - } - else if (*surfaces[i] == SF_FACE) { - const srfSurfaceFace_t * const surf = ( srfSurfaceFace_t * ) surfaces[i]; + } else if (*surfaces[i] == SF_FACE) { + const srfSurfaceFace_t *const surf = (srfSurfaceFace_t *)surfaces[i]; // check the normal of this face if (DotProduct(surf->plane.normal, projectionDir) > -0.5) { continue; } - const int * const indexes = (int *)( (byte *)surf + surf->ofsIndices ); + const int *const indexes = (int *)((byte *)surf + surf->ofsIndices); - for ( k = 0 ; k < surf->numIndices ; k += 3 ) { - for ( j = 0 ; j < 3 ; j++ ) { - const float * const v = surf->points[0] + VERTEXSIZE * indexes[k+j]; - VectorMA( v, MARKER_OFFSET, surf->plane.normal, clipPoints[0][j] ); + for (k = 0; k < surf->numIndices; k += 3) { + for (j = 0; j < 3; j++) { + const float *const v = surf->points[0] + VERTEXSIZE * indexes[k + j]; + VectorMA(v, MARKER_OFFSET, surf->plane.normal, clipPoints[0][j]); } // add the fragments of this face - R_AddMarkFragments( 3 , clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, - &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } continue; - } - else if (*surfaces[i] == SF_TRIANGLES) - { - const srfTriangles_t * const surf = ( srfTriangles_t * ) surfaces[i]; - - for ( k = 0 ; k < surf->numIndexes ; k += 3 ) - { - int i1=surf->indexes[k]; - int i2=surf->indexes[k+1]; - int i3=surf->indexes[k+2]; - VectorSubtract(surf->verts[i1].xyz,surf->verts[i2].xyz, v1); - VectorSubtract(surf->verts[i3].xyz,surf->verts[i2].xyz, v2); + } else if (*surfaces[i] == SF_TRIANGLES) { + const srfTriangles_t *const surf = (srfTriangles_t *)surfaces[i]; + + for (k = 0; k < surf->numIndexes; k += 3) { + int i1 = surf->indexes[k]; + int i2 = surf->indexes[k + 1]; + int i3 = surf->indexes[k + 2]; + VectorSubtract(surf->verts[i1].xyz, surf->verts[i2].xyz, v1); + VectorSubtract(surf->verts[i3].xyz, surf->verts[i2].xyz, v2); CrossProduct(v1, v2, normal); VectorNormalizeFast(normal); // check the normal of this triangle - if (DotProduct(normal, projectionDir) < -0.1) - { + if (DotProduct(normal, projectionDir) < -0.1) { VectorMA(surf->verts[i1].xyz, MARKER_OFFSET, normal, clipPoints[0][0]); VectorMA(surf->verts[i2].xyz, MARKER_OFFSET, normal, clipPoints[0][1]); VectorMA(surf->verts[i3].xyz, MARKER_OFFSET, normal, clipPoints[0][2]); // add the fragments of this triangle - R_AddMarkFragments( 3 , clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, - &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) - { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } - } - else { + } else { // ignore all other world surfaces // might be cool to also project polygons on a triangle soup // however this will probably create huge amounts of extra polys @@ -468,4 +441,3 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio } return returnedFragments; } - diff --git a/code/rd-vanilla/tr_mesh.cpp b/code/rd-vanilla/tr_mesh.cpp index c9aa9fa0e8..1d8731bafc 100644 --- a/code/rd-vanilla/tr_mesh.cpp +++ b/code/rd-vanilla/tr_mesh.cpp @@ -29,38 +29,33 @@ along with this program; if not, see . #include "tr_local.h" #include "qcommon/matcomp.h" -float ProjectRadius( float r, vec3_t location ) -{ +float ProjectRadius(float r, vec3_t location) { float pr; float dist; float c; - vec3_t p; + vec3_t p; float width; float depth; - c = DotProduct( tr.viewParms.ori.axis[0], tr.viewParms.ori.origin ); - dist = DotProduct( tr.viewParms.ori.axis[0], location ) - c; + c = DotProduct(tr.viewParms.ori.axis[0], tr.viewParms.ori.origin); + dist = DotProduct(tr.viewParms.ori.axis[0], location) - c; - if ( dist <= 0 ) + if (dist <= 0) return 0; p[0] = 0; - p[1] = Q_fabs( r ); + p[1] = Q_fabs(r); p[2] = -dist; - width = p[0] * tr.viewParms.projectionMatrix[1] + - p[1] * tr.viewParms.projectionMatrix[5] + - p[2] * tr.viewParms.projectionMatrix[9] + - tr.viewParms.projectionMatrix[13]; + width = p[0] * tr.viewParms.projectionMatrix[1] + p[1] * tr.viewParms.projectionMatrix[5] + p[2] * tr.viewParms.projectionMatrix[9] + + tr.viewParms.projectionMatrix[13]; - depth = p[0] * tr.viewParms.projectionMatrix[3] + - p[1] * tr.viewParms.projectionMatrix[7] + - p[2] * tr.viewParms.projectionMatrix[11] + - tr.viewParms.projectionMatrix[15]; + depth = p[0] * tr.viewParms.projectionMatrix[3] + p[1] * tr.viewParms.projectionMatrix[7] + p[2] * tr.viewParms.projectionMatrix[11] + + tr.viewParms.projectionMatrix[15]; pr = width / depth; - if ( pr > 1.0f ) + if (pr > 1.0f) pr = 1.0f; return pr; @@ -71,22 +66,19 @@ float ProjectRadius( float r, vec3_t location ) R_CullModel ============= */ -static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { - vec3_t bounds[2]; - md3Frame_t *oldFrame, *newFrame; - int i; +static int R_CullModel(md3Header_t *header, trRefEntity_t *ent) { + vec3_t bounds[2]; + md3Frame_t *oldFrame, *newFrame; + int i; // compute frame pointers - newFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame; - oldFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.oldframe; + newFrame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.frame; + oldFrame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.oldframe; // cull bounding sphere ONLY if this is not an upscaled entity - if ( !ent->e.nonNormalizedAxes ) - { - if ( ent->e.frame == ent->e.oldframe ) - { - switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) - { + if (!ent->e.nonNormalizedAxes) { + if (ent->e.frame == ent->e.oldframe) { + switch (R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius)) { case CULL_OUT: tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; @@ -99,32 +91,24 @@ static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { tr.pc.c_sphere_cull_md3_clip++; break; } - } - else - { + } else { int sphereCull, sphereCullB; - sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); - if ( newFrame == oldFrame ) { + sphereCull = R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius); + if (newFrame == oldFrame) { sphereCullB = sphereCull; } else { - sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + sphereCullB = R_CullLocalPointAndRadius(oldFrame->localOrigin, oldFrame->radius); } - if ( sphereCull == sphereCullB ) - { - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == sphereCullB) { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; - } - else if ( sphereCull == CULL_IN ) - { + } else if (sphereCull == CULL_IN) { tr.pc.c_sphere_cull_md3_in++; return CULL_IN; - } - else - { + } else { tr.pc.c_sphere_cull_md3_clip++; } } @@ -132,13 +116,12 @@ static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { } // calculate a bounding box in the current coordinate system - for (i = 0 ; i < 3 ; i++) { + for (i = 0; i < 3; i++) { bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; } - switch ( R_CullLocalBox( bounds ) ) - { + switch (R_CullLocalBox(bounds)) { case CULL_IN: tr.pc.c_box_cull_md3_in++; return CULL_IN; @@ -161,19 +144,18 @@ RE_GetModelBounds ================= */ -void RE_GetModelBounds(refEntity_t *refEnt, vec3_t bounds1, vec3_t bounds2) -{ - md3Frame_t *frame; - md3Header_t *header; - model_t *model; +void RE_GetModelBounds(refEntity_t *refEnt, vec3_t bounds1, vec3_t bounds2) { + md3Frame_t *frame; + md3Header_t *header; + model_t *model; assert(refEnt); - model = R_GetModelByHandle( refEnt->hModel ); + model = R_GetModelByHandle(refEnt->hModel); assert(model); header = model->md3[0]; assert(header); - frame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + refEnt->frame; + frame = (md3Frame_t *)((byte *)header + header->ofsFrames) + refEnt->frame; assert(frame); VectorCopy(frame->bounds[0], bounds1); @@ -186,49 +168,45 @@ R_ComputeLOD ================= */ -static int R_ComputeLOD( trRefEntity_t *ent ) { +static int R_ComputeLOD(trRefEntity_t *ent) { float radius; float flod; float projectedRadius; - int lod; + int lod; - if ( tr.currentModel->numLods < 2 ) - { // model has only 1 LOD level, skip computations and bias - return(0); + if (tr.currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias + return (0); } // multiple LODs exist, so compute projected bounding sphere // and use that as a criteria for selecting LOD -// if ( tr.currentModel->md3[0] ) - { //normal md3 + // if ( tr.currentModel->md3[0] ) + { // normal md3 md3Frame_t *frame; - frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames ); + frame = (md3Frame_t *)(((unsigned char *)tr.currentModel->md3[0]) + tr.currentModel->md3[0]->ofsFrames); frame += ent->e.frame; - radius = RadiusFromBounds( frame->bounds[0], frame->bounds[1] ); + radius = RadiusFromBounds(frame->bounds[0], frame->bounds[1]); } - if ( ( projectedRadius = ProjectRadius( radius, ent->e.origin ) ) != 0 ) - { + if ((projectedRadius = ProjectRadius(radius, ent->e.origin)) != 0) { flod = 1.0f - projectedRadius * r_lodscale->value; flod *= tr.currentModel->numLods; - } - else - { // object intersects near view plane, e.g. view weapon + } else { // object intersects near view plane, e.g. view weapon flod = 0; } - lod = Q_ftol( flod ); + lod = Q_ftol(flod); - if ( lod < 0 ) { + if (lod < 0) { lod = 0; - } else if ( lod >= tr.currentModel->numLods ) { + } else if (lod >= tr.currentModel->numLods) { lod = tr.currentModel->numLods - 1; } lod += r_lodbias->integer; - if ( lod >= tr.currentModel->numLods ) + if (lod >= tr.currentModel->numLods) lod = tr.currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; @@ -240,56 +218,48 @@ R_ComputeFogNum ================= */ -static int R_ComputeFogNum( md3Header_t *header, trRefEntity_t *ent ) { - int i; - fog_t *fog; - md3Frame_t *md3Frame; - vec3_t localOrigin; +static int R_ComputeFogNum(md3Header_t *header, trRefEntity_t *ent) { + int i; + fog_t *fog; + md3Frame_t *md3Frame; + vec3_t localOrigin; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - if ( tr.refdef.doLAGoggles ) - { + if (tr.refdef.doLAGoggles) { return tr.world->numfogs; } - // FIXME: non-normalized axis issues - md3Frame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame; - VectorAdd( ent->e.origin, md3Frame->localOrigin, localOrigin ); + md3Frame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.frame; + VectorAdd(ent->e.origin, md3Frame->localOrigin, localOrigin); int partialFog = 0; - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - if ( localOrigin[0] - md3Frame->radius >= fog->bounds[0][0] - && localOrigin[0] + md3Frame->radius <= fog->bounds[1][0] - && localOrigin[1] - md3Frame->radius >= fog->bounds[0][1] - && localOrigin[1] + md3Frame->radius <= fog->bounds[1][1] - && localOrigin[2] - md3Frame->radius >= fog->bounds[0][2] - && localOrigin[2] + md3Frame->radius <= fog->bounds[1][2] ) - {//totally inside it + if (localOrigin[0] - md3Frame->radius >= fog->bounds[0][0] && localOrigin[0] + md3Frame->radius <= fog->bounds[1][0] && + localOrigin[1] - md3Frame->radius >= fog->bounds[0][1] && localOrigin[1] + md3Frame->radius <= fog->bounds[1][1] && + localOrigin[2] - md3Frame->radius >= fog->bounds[0][2] && localOrigin[2] + md3Frame->radius <= fog->bounds[1][2]) { // totally inside it return i; break; } - if ( ( localOrigin[0] - md3Frame->radius >= fog->bounds[0][0] && localOrigin[1] - md3Frame->radius >= fog->bounds[0][1] && localOrigin[2] - md3Frame->radius >= fog->bounds[0][2] && - localOrigin[0] - md3Frame->radius <= fog->bounds[1][0] && localOrigin[1] - md3Frame->radius <= fog->bounds[1][1] && localOrigin[2] - md3Frame->radius <= fog->bounds[1][2]) || - ( localOrigin[0] + md3Frame->radius >= fog->bounds[0][0] && localOrigin[1] + md3Frame->radius >= fog->bounds[0][1] && localOrigin[2] + md3Frame->radius >= fog->bounds[0][2] && - localOrigin[0] + md3Frame->radius <= fog->bounds[1][0] && localOrigin[1] + md3Frame->radius <= fog->bounds[1][1] && localOrigin[2] + md3Frame->radius <= fog->bounds[1][2] ) ) - {//partially inside it - if ( tr.refdef.fogIndex == i || R_FogParmsMatch( tr.refdef.fogIndex, i ) ) - {//take new one only if it's the same one that the viewpoint is in + if ((localOrigin[0] - md3Frame->radius >= fog->bounds[0][0] && localOrigin[1] - md3Frame->radius >= fog->bounds[0][1] && + localOrigin[2] - md3Frame->radius >= fog->bounds[0][2] && localOrigin[0] - md3Frame->radius <= fog->bounds[1][0] && + localOrigin[1] - md3Frame->radius <= fog->bounds[1][1] && localOrigin[2] - md3Frame->radius <= fog->bounds[1][2]) || + (localOrigin[0] + md3Frame->radius >= fog->bounds[0][0] && localOrigin[1] + md3Frame->radius >= fog->bounds[0][1] && + localOrigin[2] + md3Frame->radius >= fog->bounds[0][2] && localOrigin[0] + md3Frame->radius <= fog->bounds[1][0] && + localOrigin[1] + md3Frame->radius <= fog->bounds[1][1] && localOrigin[2] + md3Frame->radius <= fog->bounds[1][2])) { // partially inside it + if (tr.refdef.fogIndex == i || R_FogParmsMatch(tr.refdef.fogIndex, i)) { // take new one only if it's the same one that the viewpoint is in return i; break; - } - else if ( !partialFog ) - {//first partialFog + } else if (!partialFog) { // first partialFog partialFog = i; } } } - //if all else fails, return the first partialFog + // if all else fails, return the first partialFog return partialFog; } @@ -299,28 +269,27 @@ R_AddMD3Surfaces ================= */ -void R_AddMD3Surfaces( trRefEntity_t *ent ) { - int i; - md3Header_t *header = 0; - md3Surface_t *surface = 0; - md3Shader_t *md3Shader = 0; - shader_t *shader = 0; - shader_t *main_shader = 0; - int cull; - int lod; - int fogNum; - qboolean personalModel; +void R_AddMD3Surfaces(trRefEntity_t *ent) { + int i; + md3Header_t *header = 0; + md3Surface_t *surface = 0; + md3Shader_t *md3Shader = 0; + shader_t *shader = 0; + shader_t *main_shader = 0; + int cull; + int lod; + int fogNum; + qboolean personalModel; // don't add third_person objects if not in a portal personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); - if ( ent->e.renderfx & RF_CAP_FRAMES) { - if (ent->e.frame > tr.currentModel->md3[0]->numFrames-1) - ent->e.frame = tr.currentModel->md3[0]->numFrames-1; - if (ent->e.oldframe > tr.currentModel->md3[0]->numFrames-1) - ent->e.oldframe = tr.currentModel->md3[0]->numFrames-1; - } - else if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + if (ent->e.renderfx & RF_CAP_FRAMES) { + if (ent->e.frame > tr.currentModel->md3[0]->numFrames - 1) + ent->e.frame = tr.currentModel->md3[0]->numFrames - 1; + if (ent->e.oldframe > tr.currentModel->md3[0]->numFrames - 1) + ent->e.oldframe = tr.currentModel->md3[0]->numFrames - 1; + } else if (ent->e.renderfx & RF_WRAP_FRAMES) { ent->e.frame %= tr.currentModel->md3[0]->numFrames; ent->e.oldframe %= tr.currentModel->md3[0]->numFrames; } @@ -331,22 +300,17 @@ void R_AddMD3Surfaces( trRefEntity_t *ent ) { // when the surfaces are rendered, they don't need to be // range checked again. // - if ( (ent->e.frame >= tr.currentModel->md3[0]->numFrames) - || (ent->e.frame < 0) - || (ent->e.oldframe >= tr.currentModel->md3[0]->numFrames) - || (ent->e.oldframe < 0) ) - { - ri.Printf (PRINT_ALL, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", - ent->e.oldframe, ent->e.frame, - tr.currentModel->name ); - ent->e.frame = 0; - ent->e.oldframe = 0; + if ((ent->e.frame >= tr.currentModel->md3[0]->numFrames) || (ent->e.frame < 0) || (ent->e.oldframe >= tr.currentModel->md3[0]->numFrames) || + (ent->e.oldframe < 0)) { + ri.Printf(PRINT_ALL, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", ent->e.oldframe, ent->e.frame, tr.currentModel->name); + ent->e.frame = 0; + ent->e.oldframe = 0; } // // compute LOD // - lod = R_ComputeLOD( ent ); + lod = R_ComputeLOD(ent); header = tr.currentModel->md3[lod]; @@ -354,84 +318,74 @@ void R_AddMD3Surfaces( trRefEntity_t *ent ) { // cull the entire model if merged bounding box of both frames // is outside the view frustum. // - cull = R_CullModel ( header, ent ); - if ( cull == CULL_OUT ) { + cull = R_CullModel(header, ent); + if (cull == CULL_OUT) { return; } // // set up lighting now that we know we aren't culled // - if ( !personalModel || r_shadows->integer > 1 ) { - R_SetupEntityLighting( &tr.refdef, ent ); + if (!personalModel || r_shadows->integer > 1) { + R_SetupEntityLighting(&tr.refdef, ent); } // // see if we are in a fog volume // - fogNum = R_ComputeFogNum( header, ent ); + fogNum = R_ComputeFogNum(header, ent); // // draw all surfaces // - main_shader = R_GetShaderByHandle( ent->e.customShader ); + main_shader = R_GetShaderByHandle(ent->e.customShader); - surface = (md3Surface_t *)( (byte *)header + header->ofsSurfaces ); - for ( i = 0 ; i < header->numSurfaces ; i++ ) { + surface = (md3Surface_t *)((byte *)header + header->ofsSurfaces); + for (i = 0; i < header->numSurfaces; i++) { - if ( ent->e.customShader ) {// a little more efficient + if (ent->e.customShader) { // a little more efficient shader = main_shader; - } else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) { + } else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin_t *skin; - int j; + int j; - skin = R_GetSkinByHandle( ent->e.customSkin ); + skin = R_GetSkinByHandle(ent->e.customSkin); // match the surface name to something in the skin file shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surface->name ) ) { + if (!strcmp(skin->surfaces[j]->name, surface->name)) { shader = skin->surfaces[j]->shader; break; } } - } else if ( surface->numShaders <= 0 ) { + } else if (surface->numShaders <= 0) { shader = tr.defaultShader; } else { - md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders ); + md3Shader = (md3Shader_t *)((byte *)surface + surface->ofsShaders); md3Shader += ent->e.skinNum % surface->numShaders; - shader = tr.shaders[ md3Shader->shaderIndex ]; + shader = tr.shaders[md3Shader->shaderIndex]; } - // we will add shadows even if the main object isn't visible in the view // stencil shadows can't do personal models unless I polyhedron clip - if ( !personalModel - && r_shadows->integer == 2 - && fogNum == 0 - && (ent->e.renderfx & RF_SHADOW_PLANE ) - && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, tr.shadowShader, 0, qfalse ); + if (!personalModel && r_shadows->integer == 2 && fogNum == 0 && (ent->e.renderfx & RF_SHADOW_PLANE) && + !(ent->e.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, tr.shadowShader, 0, qfalse); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 - && fogNum == 0 - && (ent->e.renderfx & RF_SHADOW_PLANE ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, tr.projectionShadowShader, 0, qfalse ); + if (r_shadows->integer == 3 && fogNum == 0 && (ent->e.renderfx & RF_SHADOW_PLANE) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, tr.projectionShadowShader, 0, qfalse); } // don't add third_person objects if not viewing through a portal - if ( !personalModel ) { - R_AddDrawSurf( (surfaceType_t *)surface, shader, fogNum, qfalse ); + if (!personalModel) { + R_AddDrawSurf((surfaceType_t *)surface, shader, fogNum, qfalse); } - surface = (md3Surface_t *)( (byte *)surface + surface->ofsEnd ); + surface = (md3Surface_t *)((byte *)surface + surface->ofsEnd); } - } - diff --git a/code/rd-vanilla/tr_model.cpp b/code/rd-vanilla/tr_model.cpp index a6d5bc7b34..d52572af9c 100644 --- a/code/rd-vanilla/tr_model.cpp +++ b/code/rd-vanilla/tr_model.cpp @@ -31,165 +31,136 @@ along with this program; if not, see . #include "qcommon/matcomp.h" #include "../qcommon/sstring.h" -#define LL(x) x=LittleLong(x) -#define LS(x) x=LittleShort(x) -#define LF(x) x=LittleFloat(x) +#define LL(x) x = LittleLong(x) +#define LS(x) x = LittleShort(x) +#define LF(x) x = LittleFloat(x) -void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ); //should only be called for sub-bsp instances +void RE_LoadWorldMap_Actual(const char *name, world_t &worldData, int index); // should only be called for sub-bsp instances -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached ); +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached); /* Ghoul2 Insert Start */ -typedef struct modelHash_s -{ - char name[MAX_QPATH]; - qhandle_t handle; - struct modelHash_s *next; +typedef struct modelHash_s { + char name[MAX_QPATH]; + qhandle_t handle; + struct modelHash_s *next; -}modelHash_t; - -#define FILE_HASH_SIZE 1024 -modelHash_t *mhHashTable[FILE_HASH_SIZE]; +} modelHash_t; +#define FILE_HASH_SIZE 1024 +modelHash_t *mhHashTable[FILE_HASH_SIZE]; /* Ghoul2 Insert End */ - - // This stuff looks a bit messy, but it's kept here as black box, and nothing appears in any .H files for other // modules to worry about. I may make another module for this sometime. // -typedef std::pair StringOffsetAndShaderIndexDest_t; -typedef std::vector ShaderRegisterData_t; -struct CachedEndianedModelBinary_s -{ - void *pModelDiskImage; - int iAllocSize; // may be useful for mem-query, but I don't actually need it +typedef std::pair StringOffsetAndShaderIndexDest_t; +typedef std::vector ShaderRegisterData_t; +struct CachedEndianedModelBinary_s { + void *pModelDiskImage; + int iAllocSize; // may be useful for mem-query, but I don't actually need it ShaderRegisterData_t ShaderRegisterData; - int iLastLevelUsedOn; + int iLastLevelUsedOn; - CachedEndianedModelBinary_s() - { + CachedEndianedModelBinary_s() { pModelDiskImage = 0; - iLastLevelUsedOn = -1; + iLastLevelUsedOn = -1; iAllocSize = 0; ShaderRegisterData.clear(); } }; typedef struct CachedEndianedModelBinary_s CachedEndianedModelBinary_t; -typedef std::map CachedModels_t; - CachedModels_t *CachedModels = NULL; // the important cache item. +typedef std::map CachedModels_t; +CachedModels_t *CachedModels = NULL; // the important cache item. -void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, const int *piShaderIndexPoke) -{ +void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, const int *piShaderIndexPoke) { char sModelName[MAX_QPATH]; - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { - assert(0); // should never happen, means that we're being called on a model that wasn't loaded - } - else - { - const int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; - const int iPokeOffset = (char*) piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; + if (ModelBin.pModelDiskImage == NULL) { + assert(0); // should never happen, means that we're being called on a model that wasn't loaded + } else { + const int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; + const int iPokeOffset = (char *)piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; - ModelBin.ShaderRegisterData.push_back( StringOffsetAndShaderIndexDest_t( iNameOffset,iPokeOffset) ); + ModelBin.ShaderRegisterData.push_back(StringOffsetAndShaderIndexDest_t(iNameOffset, iPokeOffset)); } } - -static const byte FakeGLAFile[] = -{ -0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x01, 0x00, 0x00, 0x00, -0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, -0x26, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, -0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, -0x00, 0x80, 0x00, 0x80, 0x00, 0x80 -}; - +static const byte FakeGLAFile[] = { + 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0x3F, 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x26, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6C, 0x74, 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, + 0xFF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80}; // returns qtrue if loaded, and sets the supplied qbool to true if it was from cache (instead of disk) // (which we need to know to avoid LittleLong()ing everything again (well, the Mac needs to know anyway)... // -qboolean RE_RegisterModels_GetDiskFile( const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) -{ +qboolean RE_RegisterModels_GetDiskFile(const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) { char sModelName[MAX_QPATH]; - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // didn't have it cached, so try the disk... // - // special case intercept first... + // special case intercept first... + // + if (!strcmp(sDEFAULT_GLA_NAME ".gla", psModelFileName)) { + // return fake params as though it was found on disk... // - if (!strcmp(sDEFAULT_GLA_NAME ".gla" , psModelFileName)) - { - // return fake params as though it was found on disk... - // - void *pvFakeGLAFile = R_Malloc( sizeof(FakeGLAFile), TAG_FILESYS, qfalse ); - memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); - *ppvBuffer = pvFakeGLAFile; - *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well - return qtrue; - } + void *pvFakeGLAFile = R_Malloc(sizeof(FakeGLAFile), TAG_FILESYS, qfalse); + memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); + *ppvBuffer = pvFakeGLAFile; + *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well + return qtrue; + } - ri.FS_ReadFile( sModelName, ppvBuffer ); + ri.FS_ReadFile(sModelName, ppvBuffer); *pqbAlreadyCached = qfalse; return (qboolean)(*ppvBuffer != 0); - } - else - { + } else { *ppvBuffer = ModelBin.pModelDiskImage; *pqbAlreadyCached = qtrue; return qtrue; } } - // if return == true, no further action needed by the caller... // -void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) -{ +void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) { char sModelName[MAX_QPATH]; - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // ... then this entry has only just been created, ie we need to load it fully... // // new, instead of doing a R_Malloc and assigning that we just morph the disk buffer alloc @@ -197,42 +168,35 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const // // ... groan, but not if doing a limb hierarchy creation (some VV stuff?), in which case it's NULL // - if ( pvDiskBufferIfJustLoaded ) - { - R_MorphMallocTag( pvDiskBufferIfJustLoaded, eTag ); - } - else - { - pvDiskBufferIfJustLoaded = R_Malloc(iSize,eTag, qfalse ); + if (pvDiskBufferIfJustLoaded) { + R_MorphMallocTag(pvDiskBufferIfJustLoaded, eTag); + } else { + pvDiskBufferIfJustLoaded = R_Malloc(iSize, eTag, qfalse); } - ModelBin.pModelDiskImage= pvDiskBufferIfJustLoaded; - ModelBin.iAllocSize = iSize; - *pqbAlreadyFound = qfalse; - } - else - { + ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; + ModelBin.iAllocSize = iSize; + *pqbAlreadyFound = qfalse; + } else { // if we already had this model entry, then re-register all the shaders it wanted... // const int iEntries = ModelBin.ShaderRegisterData.size(); - for (int i=0; idefaultShader ) - { + if (sh->defaultShader) { *piShaderPokePtr = 0; } else { *piShaderPokePtr = sh->index; } } - *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary + *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary } ModelBin.iLastLevelUsedOn = RE_RegisterMedia_GetLevel(); @@ -240,114 +204,93 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const return ModelBin.pModelDiskImage; } - // dump any models not being used by this level if we're running low on memory... // -static int GetModelDataAllocSize(void) -{ - return R_MemSize( TAG_MODEL_MD3) + - R_MemSize( TAG_MODEL_GLM) + - R_MemSize( TAG_MODEL_GLA); -} +static int GetModelDataAllocSize(void) { return R_MemSize(TAG_MODEL_MD3) + R_MemSize(TAG_MODEL_GLM) + R_MemSize(TAG_MODEL_GLA); } extern cvar_t *r_modelpoolmegs; // // return qtrue if at least one cached model was freed (which tells z_malloc()-fail recovery code to try again) // extern qboolean gbInsideRegisterModel; -qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) -{ +qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) { qboolean bAtLeastoneModelFreed = qfalse; - if (gbInsideRegisterModel) - { - Com_DPrintf( "(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); - } - else - { - int iLoadedModelBytes = GetModelDataAllocSize(); - const int iMaxModelBytes= r_modelpoolmegs->integer * 1024 * 1024; + if (gbInsideRegisterModel) { + Com_DPrintf("(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); + } else { + int iLoadedModelBytes = GetModelDataAllocSize(); + const int iMaxModelBytes = r_modelpoolmegs->integer * 1024 * 1024; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end() && ( bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes ); ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); + itModel != CachedModels->end() && (bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes);) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; qboolean bDeleteThis = qfalse; - if (bDeleteEverythingNotUsedThisLevel) - { + if (bDeleteEverythingNotUsedThisLevel) { bDeleteThis = (qboolean)(CachedModel.iLastLevelUsedOn != RE_RegisterMedia_GetLevel()); - } - else - { + } else { bDeleteThis = (qboolean)(CachedModel.iLastLevelUsedOn < RE_RegisterMedia_GetLevel()); } // if it wasn't used on this level, dump it... // - if (bDeleteThis) - { - #ifdef _DEBUG -// LPCSTR psModelName = (*itModel).first.c_str(); -// ri.Printf( PRINT_DEVELOPER, "Dumping \"%s\"", psModelName); -// ri.Printf( PRINT_DEVELOPER, ", used on lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif + if (bDeleteThis) { +#ifdef _DEBUG + // LPCSTR psModelName = (*itModel).first.c_str(); + // ri.Printf( PRINT_DEVELOPER, "Dumping \"%s\"", psModelName); + // ri.Printf( PRINT_DEVELOPER, ", used on lvl %d\n",CachedModel.iLastLevelUsedOn); +#endif if (CachedModel.pModelDiskImage) { R_Free(CachedModel.pModelDiskImage); - //CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. + // CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. bAtLeastoneModelFreed = qtrue; } CachedModels->erase(itModel++); iLoadedModelBytes = GetModelDataAllocSize(); - } - else - { + } else { ++itModel; } } } - //ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_LevelLoadEnd(): Ok\n"); + // ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_LevelLoadEnd(): Ok\n"); return bAtLeastoneModelFreed; } -void RE_RegisterModels_Info_f( void ) -{ +void RE_RegisterModels_Info_f(void) { int iTotalBytes = 0; - if(!CachedModels) { - Com_Printf ("%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + if (!CachedModels) { + Com_Printf("%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); return; } int iModels = CachedModels->size(); - int iModel = 0; + int iModel = 0; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel,iModel++) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel, iModel++) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; - ri.Printf( PRINT_ALL, "%d/%d: \"%s\" (%d bytes)",iModel,iModels,(*itModel).first.c_str(),CachedModel.iAllocSize ); + ri.Printf(PRINT_ALL, "%d/%d: \"%s\" (%d bytes)", iModel, iModels, (*itModel).first.c_str(), CachedModel.iAllocSize); - #ifdef _DEBUG - ri.Printf( PRINT_ALL, ", lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif +#ifdef _DEBUG + ri.Printf(PRINT_ALL, ", lvl %d\n", CachedModel.iLastLevelUsedOn); +#endif iTotalBytes += CachedModel.iAllocSize; } - ri.Printf( PRINT_ALL, "%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + ri.Printf(PRINT_ALL, "%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); } - -static void RE_RegisterModels_DeleteAll(void) -{ - if(!CachedModels) { - return; //argh! +static void RE_RegisterModels_DeleteAll(void) { + if (!CachedModels) { + return; // argh! } - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end();) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; if (CachedModel.pModelDiskImage) { @@ -361,47 +304,44 @@ static void RE_RegisterModels_DeleteAll(void) RE_AnimationCFGs_DeleteAll(); } - -static int giRegisterMedia_CurrentLevel=0; +static int giRegisterMedia_CurrentLevel = 0; static qboolean gbAllowScreenDissolve = qtrue; // // param "bAllowScreenDissolve" is just a convenient way of getting hold of a bool which can be checked by the code that // issues the InitDissolve command later in RE_RegisterMedia_LevelLoadEnd() // -void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload, qboolean bAllowScreenDissolve) -{ +void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload, qboolean bAllowScreenDissolve) { gbAllowScreenDissolve = bAllowScreenDissolve; tr.numBSPModels = 0; // for development purposes we may want to ditch certain media just before loading a map... // - switch (eForceReload) - { - case eForceReload_BSP: + switch (eForceReload) { + case eForceReload_BSP: - ri.CM_DeleteCachedMap(qtrue); - R_Images_DeleteLightMaps(); - break; + ri.CM_DeleteCachedMap(qtrue); + R_Images_DeleteLightMaps(); + break; - case eForceReload_MODELS: + case eForceReload_MODELS: - RE_RegisterModels_DeleteAll(); - break; + RE_RegisterModels_DeleteAll(); + break; - case eForceReload_ALL: + case eForceReload_ALL: - // BSP... - // - ri.CM_DeleteCachedMap(qtrue); - R_Images_DeleteLightMaps(); - // - // models... - // - RE_RegisterModels_DeleteAll(); - break; - default: - break; + // BSP... + // + ri.CM_DeleteCachedMap(qtrue); + R_Images_DeleteLightMaps(); + // + // models... + // + RE_RegisterModels_DeleteAll(); + break; + default: + break; } // at some stage I'll probably want to put some special logic here, like not incrementing the level number @@ -411,27 +351,21 @@ void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForce // only bump level number if we're not on the same level. // Note that this will hide uncached models, which is perhaps a bad thing?... // - static char sPrevMapName[MAX_QPATH]={0}; - if (Q_stricmp( psMapName,sPrevMapName )) - { - Q_strncpyz( sPrevMapName, psMapName, sizeof(sPrevMapName) ); + static char sPrevMapName[MAX_QPATH] = {0}; + if (Q_stricmp(psMapName, sPrevMapName)) { + Q_strncpyz(sPrevMapName, psMapName, sizeof(sPrevMapName)); giRegisterMedia_CurrentLevel++; } } -int RE_RegisterMedia_GetLevel(void) -{ - return giRegisterMedia_CurrentLevel; -} +int RE_RegisterMedia_GetLevel(void) { return giRegisterMedia_CurrentLevel; } -void RE_RegisterMedia_LevelLoadEnd(void) -{ +void RE_RegisterMedia_LevelLoadEnd(void) { RE_RegisterModels_LevelLoadEnd(qfalse); RE_RegisterImages_LevelLoadEnd(); ri.SND_RegisterAudio_LevelLoadEnd(qfalse); - if (gbAllowScreenDissolve) - { + if (gbAllowScreenDissolve) { RE_InitDissolve(qfalse); } @@ -440,17 +374,14 @@ void RE_RegisterMedia_LevelLoadEnd(void) *(ri.gbAlreadyDoingLoad()) = qfalse; } - - - /* ** R_GetModelByHandle */ -model_t *R_GetModelByHandle( qhandle_t index ) { - model_t *mod; +model_t *R_GetModelByHandle(qhandle_t index) { + model_t *mod; // out of range gets the defualt model - if ( index < 1 || index >= tr.numModels ) { + if (index < 1 || index >= tr.numModels) { return tr.models[0]; } @@ -464,15 +395,15 @@ model_t *R_GetModelByHandle( qhandle_t index ) { /* ** R_AllocModel */ -model_t *R_AllocModel( void ) { - model_t *mod; +model_t *R_AllocModel(void) { + model_t *mod; - if ( tr.numModels == MAX_MOD_KNOWN ) { + if (tr.numModels == MAX_MOD_KNOWN) { return NULL; } - mod = (model_t*) R_Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), qtrue ); - mod->index= tr.numModels; + mod = (model_t *)R_Hunk_Alloc(sizeof(*tr.models[tr.numModels]), qtrue); + mod->index = tr.numModels; tr.models[tr.numModels] = mod; tr.numModels++; @@ -488,35 +419,36 @@ Ghoul2 Insert Start return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (size-1); + hash &= (size - 1); return hash; } -void RE_InsertModelIntoHash(const char *name, model_t *mod) -{ - int hash; - modelHash_t *mh; +void RE_InsertModelIntoHash(const char *name, model_t *mod) { + int hash; + modelHash_t *mh; hash = generateHashValue(name, FILE_HASH_SIZE); // insert this file into the hash table so we can look it up faster later - mh = (modelHash_t*)R_Hunk_Alloc( sizeof( modelHash_t ), qtrue ); + mh = (modelHash_t *)R_Hunk_Alloc(sizeof(modelHash_t), qtrue); - mh->next = mhHashTable[hash]; // I have the breakpoint triggered here where mhHashTable[986] would be assigned + mh->next = mhHashTable[hash]; // I have the breakpoint triggered here where mhHashTable[986] would be assigned mh->handle = mod->index; strcpy(mh->name, name); mhHashTable[hash] = mh; @@ -525,7 +457,6 @@ void RE_InsertModelIntoHash(const char *name, model_t *mod) Ghoul2 Insert End */ - /* ==================== RE_RegisterModel @@ -538,41 +469,40 @@ optimization to prevent disk rescanning if they are asked for again. ==================== */ -static qhandle_t RE_RegisterModel_Actual( const char *name ) -{ - model_t *mod; - unsigned *buf; - int lod; - int ident; - qboolean loaded; -// qhandle_t hModel; - int numLoaded; -/* -Ghoul2 Insert Start -*/ - int hash; - modelHash_t *mh; -/* -Ghoul2 Insert End -*/ - - if ( !name || !name[0] ) { - ri.Printf( PRINT_WARNING, "RE_RegisterModel: NULL name\n" ); +static qhandle_t RE_RegisterModel_Actual(const char *name) { + model_t *mod; + unsigned *buf; + int lod; + int ident; + qboolean loaded; + // qhandle_t hModel; + int numLoaded; + /* + Ghoul2 Insert Start + */ + int hash; + modelHash_t *mh; + /* + Ghoul2 Insert End + */ + + if (!name || !name[0]) { + ri.Printf(PRINT_WARNING, "RE_RegisterModel: NULL name\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_DEVELOPER, "Model name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_DEVELOPER, "Model name exceeds MAX_QPATH\n"); return 0; } -/* -Ghoul2 Insert Start -*/ -// if (!tr.registered) { -// ri.Printf( PRINT_WARNING, "RE_RegisterModel (%s) called before ready!\n",name ); -// return 0; -// } + /* + Ghoul2 Insert Start + */ + // if (!tr.registered) { + // ri.Printf( PRINT_WARNING, "RE_RegisterModel (%s) called before ready!\n",name ); + // return 0; + // } // // search the currently loaded models // @@ -582,34 +512,31 @@ Ghoul2 Insert Start // // see if the model is already loaded //_ - for (mh=mhHashTable[hash]; mh; mh=mh->next) { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { if (Q_stricmp(mh->name, name) == 0) { - if (tr.models[mh->handle]->type == MOD_BAD) - { + if (tr.models[mh->handle]->type == MOD_BAD) { return 0; } return mh->handle; } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if (name[0] == '#') - { - char temp[MAX_QPATH]; + if (name[0] == '#') { + char temp[MAX_QPATH]; tr.numBSPModels++; #ifndef DEDICATED - RE_LoadWorldMap_Actual(va("maps/%s.bsp", name + 1), tr.bspModels[tr.numBSPModels - 1], tr.numBSPModels); //this calls R_LoadSubmodels which will put them into the Hash + RE_LoadWorldMap_Actual(va("maps/%s.bsp", name + 1), tr.bspModels[tr.numBSPModels - 1], + tr.numBSPModels); // this calls R_LoadSubmodels which will put them into the Hash #endif Com_sprintf(temp, MAX_QPATH, "*%d-0", tr.numBSPModels); hash = generateHashValue(temp, FILE_HASH_SIZE); - for (mh=mhHashTable[hash]; mh; mh=mh->next) - { - if (Q_stricmp(mh->name, temp) == 0) - { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { + if (Q_stricmp(mh->name, temp) == 0) { return mh->handle; } } @@ -619,20 +546,20 @@ Ghoul2 Insert End // allocate a new model_t - if ( ( mod = R_AllocModel() ) == NULL ) { - ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + if ((mod = R_AllocModel()) == NULL) { + ri.Printf(PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); // make sure the render thread is stopped R_IssuePendingRenderCommands(); // int iLODStart = 0; - if (strstr (name, ".md3")) { - iLODStart = MD3_MAX_LODS-1; //this loads the md3s in reverse so they can be biased + if (strstr(name, ".md3")) { + iLODStart = MD3_MAX_LODS - 1; // this loads the md3s in reverse so they can be biased } mod->numLods = 0; @@ -641,76 +568,73 @@ Ghoul2 Insert End // numLoaded = 0; - for ( lod = iLODStart; lod >= 0 ; lod-- ) { + for (lod = iLODStart; lod >= 0; lod--) { char filename[1024]; - strcpy( filename, name ); + strcpy(filename, name); - if ( lod != 0 ) { + if (lod != 0) { char namebuf[80]; - if ( strrchr( filename, '.' ) ) { - *strrchr( filename, '.' ) = 0; + if (strrchr(filename, '.')) { + *strrchr(filename, '.') = 0; } - sprintf( namebuf, "_%d.md3", lod ); - strcat( filename, namebuf ); + sprintf(namebuf, "_%d.md3", lod); + strcat(filename, namebuf); } qboolean bAlreadyCached = qfalse; - if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) - { - if (numLoaded) //we loaded one already, but a higher LOD is missing! + if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) { + if (numLoaded) // we loaded one already, but a higher LOD is missing! { - Com_Error (ERR_DROP, "R_LoadMD3: %s has LOD %d but is missing LOD %d ('%s')!", mod->name, lod+1, lod, filename); + Com_Error(ERR_DROP, "R_LoadMD3: %s has LOD %d but is missing LOD %d ('%s')!", mod->name, lod + 1, lod, filename); } continue; } - //loadmodel = mod; // this seems to be fairly pointless + // loadmodel = mod; // this seems to be fairly pointless // important that from now on we pass 'filename' instead of 'name' to all model load functions, // because 'filename' accounts for any LOD mangling etc so guarantees unique lookups for yet more // internal caching... // ident = *(unsigned *)buf; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { ident = LittleLong(ident); } - switch (ident) - { - // if you add any new types of model load in this switch-case, tell me, - // or copy what I've done with the cache scheme (-ste). - // - case MDXA_IDENT: + switch (ident) { + // if you add any new types of model load in this switch-case, tell me, + // or copy what I've done with the cache scheme (-ste). + // + case MDXA_IDENT: - loaded = R_LoadMDXA( mod, buf, filename, bAlreadyCached ); - break; + loaded = R_LoadMDXA(mod, buf, filename, bAlreadyCached); + break; - case MDXM_IDENT: + case MDXM_IDENT: - loaded = R_LoadMDXM( mod, buf, filename, bAlreadyCached ); - break; + loaded = R_LoadMDXM(mod, buf, filename, bAlreadyCached); + break; - case MD3_IDENT: + case MD3_IDENT: - loaded = R_LoadMD3( mod, lod, buf, filename, bAlreadyCached ); - break; + loaded = R_LoadMD3(mod, lod, buf, filename, bAlreadyCached); + break; - default: + default: - ri.Printf (PRINT_WARNING,"RE_RegisterModel: unknown fileid for %s\n", filename); - goto fail; + ri.Printf(PRINT_WARNING, "RE_RegisterModel: unknown fileid for %s\n", filename); + goto fail; } - if (!bAlreadyCached){ // important to check!! - ri.FS_FreeFile (buf); + if (!bAlreadyCached) { // important to check!! + ri.FS_FreeFile(buf); } - if ( !loaded ) { - if ( lod == 0 ) { - ri.Printf (PRINT_WARNING,"RE_RegisterModel: cannot load %s\n", filename); + if (!loaded) { + if (lod == 0) { + ri.Printf(PRINT_WARNING, "RE_RegisterModel: cannot load %s\n", filename); goto fail; } else { break; @@ -721,32 +645,30 @@ Ghoul2 Insert End // if we have a valid model and are biased // so that we won't see any higher detail ones, // stop loading them - if ( lod <= r_lodbias->integer ) { + if (lod <= r_lodbias->integer) { break; } } } - if ( numLoaded ) { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for ( lod-- ; lod >= 0 ; lod-- ) { + for (lod--; lod >= 0; lod--) { mod->numLods++; - mod->md3[lod] = mod->md3[lod+1]; + mod->md3[lod] = mod->md3[lod + 1]; } -/* -Ghoul2 Insert Start -*/ - - RE_InsertModelIntoHash(name, mod); - return mod->index; -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert Start + */ + + RE_InsertModelIntoHash(name, mod); + return mod->index; + /* + Ghoul2 Insert End + */ } - fail: // we still keep the model_t around, so if the model name is asked for // again, we won't bother scanning the filesystem @@ -755,78 +677,70 @@ Ghoul2 Insert End return 0; } - - - // wrapper function needed to avoid problems with mid-function returns so I can safely use this bool to tell the // z_malloc-fail recovery code whether it's safe to ditch any model caches... // qboolean gbInsideRegisterModel = qfalse; -qhandle_t RE_RegisterModel( const char *name ) -{ - gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! +qhandle_t RE_RegisterModel(const char *name) { + gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! - qhandle_t q = RE_RegisterModel_Actual( name ); + qhandle_t q = RE_RegisterModel_Actual(name); if (!COM_CompareExtension(name, ".gla")) { - gbInsideRegisterModel = qfalse; // GLA files recursively call this, so don't turn off half way. A reference count would be nice, but if any ERR_DROP ever occurs within the load then the refcount will be knackered from then on + gbInsideRegisterModel = qfalse; // GLA files recursively call this, so don't turn off half way. A reference count would be nice, but if any ERR_DROP + // ever occurs within the load then the refcount will be knackered from then on } return q; } - /* ================= R_LoadMD3 ================= */ -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i, j; - md3Header_t *pinmodel; - md3Surface_t *surf; - md3Shader_t *shader; - int version; - int size; +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, j; + md3Header_t *pinmodel; + md3Surface_t *surf; + md3Shader_t *shader; + int version; + int size; #ifdef Q3_BIG_ENDIAN - md3Frame_t *frame; - md3Triangle_t *tri; - md3St_t *st; - md3XyzNormal_t *xyz; - md3Tag_t *tag; + md3Frame_t *frame; + md3Triangle_t *tri; + md3St_t *st; + md3XyzNormal_t *xyz; + md3Tag_t *tag; #endif - - pinmodel= (md3Header_t *)buffer; + pinmodel = (md3Header_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = pinmodel->version; - size = pinmodel->ofsEnd; + size = pinmodel->ofsEnd; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { version = LittleLong(version); - size = LittleLong(size); + size = LittleLong(size); } if (version != MD3_VERSION) { - ri.Printf( PRINT_WARNING, "R_LoadMD3: %s has wrong version (%i should be %i)\n", - mod_name, version, MD3_VERSION); + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has wrong version (%i should be %i)\n", mod_name, version, MD3_VERSION); return qfalse; } - mod->type = MOD_MESH; + mod->type = MOD_MESH; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mod->md3[lod] = (md3Header_t *) RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); + mod->md3[lod] = (md3Header_t *)RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an FS_Freefile since // we've hijacked that memory block... @@ -834,8 +748,8 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mod->md3[lod] == buffer ); -// memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing + assert(mod->md3[lod] == buffer); + // memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing LL(mod->md3[lod]->ident); LL(mod->md3[lod]->version); @@ -848,22 +762,21 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ LL(mod->md3[lod]->ofsEnd); } - if ( mod->md3[lod]->numFrames < 1 ) { - ri.Printf( PRINT_WARNING, "R_LoadMD3: %s has no frames\n", mod_name ); + if (mod->md3[lod]->numFrames < 1) { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not pass Go... } #ifdef Q3_BIG_ENDIAN // swap all the frames - frame = (md3Frame_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsFrames ); - for ( i = 0 ; i < mod->md3[lod]->numFrames ; i++, frame++) { + frame = (md3Frame_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsFrames); + for (i = 0; i < mod->md3[lod]->numFrames; i++, frame++) { LF(frame->radius); - for ( j = 0 ; j < 3 ; j++ ) { + for (j = 0; j < 3; j++) { LF(frame->bounds[0][j]); LF(frame->bounds[1][j]); LF(frame->localOrigin[j]); @@ -871,9 +784,9 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ } // swap all the tags - tag = (md3Tag_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsTags ); - for ( i = 0 ; i < mod->md3[lod]->numTags * mod->md3[lod]->numFrames ; i++, tag++) { - for ( j = 0 ; j < 3 ; j++ ) { + tag = (md3Tag_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsTags); + for (i = 0; i < mod->md3[lod]->numTags * mod->md3[lod]->numFrames; i++, tag++) { + for (j = 0; j < 3; j++) { LF(tag->origin[j]); LF(tag->axis[0][j]); LF(tag->axis[1][j]); @@ -883,76 +796,72 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // swap all the surfaces - surf = (md3Surface_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces ); - for ( i = 0 ; i < mod->md3[lod]->numSurfaces ; i++) { - LL(surf->flags); - LL(surf->numFrames); - LL(surf->numShaders); - LL(surf->numTriangles); - LL(surf->ofsTriangles); - LL(surf->numVerts); - LL(surf->ofsShaders); - LL(surf->ofsSt); - LL(surf->ofsXyzNormals); - LL(surf->ofsEnd); - - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)", - mod_name, SHADER_MAX_VERTEXES, surf->numVerts ); + surf = (md3Surface_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces); + for (i = 0; i < mod->md3[lod]->numSurfaces; i++) { + LL(surf->flags); + LL(surf->numFrames); + LL(surf->numShaders); + LL(surf->numTriangles); + LL(surf->ofsTriangles); + LL(surf->numVerts); + LL(surf->ofsShaders); + LL(surf->ofsSt); + LL(surf->ofsXyzNormals); + LL(surf->ofsEnd); + + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)", - mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles ); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } // change to surface identifier surf->ident = SF_MD3; // lowercase the surface name so skin compares are faster - Q_strlwr( surf->name ); + Q_strlwr(surf->name); // strip off a trailing _1 or _2 // this is a crutch for q3data being a mess - j = strlen( surf->name ); - if ( j > 2 && surf->name[j-2] == '_' ) { - surf->name[j-2] = 0; + j = strlen(surf->name); + if (j > 2 && surf->name[j - 2] == '_') { + surf->name[j - 2] = 0; } - // register the shaders - shader = (md3Shader_t *) ( (byte *)surf + surf->ofsShaders ); - for ( j = 0 ; j < surf->numShaders ; j++, shader++ ) { - shader_t *sh; + // register the shaders + shader = (md3Shader_t *)((byte *)surf + surf->ofsShaders); + for (j = 0; j < surf->numShaders; j++, shader++) { + shader_t *sh; - sh = R_FindShader( shader->name, lightmapsNone, stylesDefault, qtrue ); - if ( sh->defaultShader ) { + sh = R_FindShader(shader->name, lightmapsNone, stylesDefault, qtrue); + if (sh->defaultShader) { shader->shaderIndex = 0; } else { shader->shaderIndex = sh->index; } RE_RegisterModels_StoreShaderRequest(mod_name, &shader->name[0], &shader->shaderIndex); - } - + } #ifdef Q3_BIG_ENDIAN // swap all the triangles - tri = (md3Triangle_t *) ( (byte *)surf + surf->ofsTriangles ); - for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) { + tri = (md3Triangle_t *)((byte *)surf + surf->ofsTriangles); + for (j = 0; j < surf->numTriangles; j++, tri++) { LL(tri->indexes[0]); LL(tri->indexes[1]); LL(tri->indexes[2]); } // swap all the ST - st = (md3St_t *) ( (byte *)surf + surf->ofsSt ); - for ( j = 0 ; j < surf->numVerts ; j++, st++ ) { + st = (md3St_t *)((byte *)surf + surf->ofsSt); + for (j = 0; j < surf->numVerts; j++, st++) { LF(st->st[0]); LF(st->st[1]); } // swap all the XyzNormals - xyz = (md3XyzNormal_t *) ( (byte *)surf + surf->ofsXyzNormals ); - for ( j = 0 ; j < surf->numVerts * surf->numFrames ; j++, xyz++ ) - { + xyz = (md3XyzNormal_t *)((byte *)surf + surf->ofsXyzNormals); + for (j = 0; j < surf->numVerts * surf->numFrames; j++, xyz++) { LS(xyz->xyz[0]); LS(xyz->xyz[1]); LS(xyz->xyz[2]); @@ -962,13 +871,12 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // find the next surface - surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (md3Surface_t *)((byte *)surf + surf->ofsEnd); } return qtrue; } - //============================================================================= void CM_LoadShaderText(bool forceReload); @@ -977,7 +885,7 @@ void CM_SetupShaderProperties(void); /* ** RE_BeginRegistration */ -void RE_BeginRegistration( glconfig_t *glconfigOut ) { +void RE_BeginRegistration(glconfig_t *glconfigOut) { ri.Hunk_ClearToMark(); R_Init(); @@ -986,13 +894,11 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { R_IssuePendingRenderCommands(); - tr.viewCluster = -1; // force markleafs to regenerate - + tr.viewCluster = -1; // force markleafs to regenerate RE_ClearScene(); tr.registered = qtrue; - } //============================================================================= @@ -1002,111 +908,106 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { R_ModelInit =============== */ -void R_ModelInit( void ) -{ - static CachedModels_t singleton; // sorry vv, your dynamic allocation was a (false) memory leak +void R_ModelInit(void) { + static CachedModels_t singleton; // sorry vv, your dynamic allocation was a (false) memory leak CachedModels = &singleton; - model_t *mod; + model_t *mod; // leave a space for NULL model tr.numModels = 0; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ memset(mhHashTable, 0, sizeof(mhHashTable)); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ mod = R_AllocModel(); mod->type = MOD_BAD; - } - /* ================ R_Modellist_f ================ */ -void R_Modellist_f( void ) { - int i, j; - model_t *mod; - int total; - int lods; +void R_Modellist_f(void) { + int i, j; + model_t *mod; + int total; + int lods; total = 0; - for ( i = 1 ; i < tr.numModels; i++ ) { + for (i = 1; i < tr.numModels; i++) { mod = tr.models[i]; - switch (mod->type) - { - default: - assert(0); - ri.Printf( PRINT_ALL, "UNKNOWN : %s\n", mod->name ); - break; + switch (mod->type) { + default: + assert(0); + ri.Printf(PRINT_ALL, "UNKNOWN : %s\n", mod->name); + break; - case MOD_BAD: - ri.Printf( PRINT_ALL, "MOD_BAD : %s\n", mod->name ); - break; + case MOD_BAD: + ri.Printf(PRINT_ALL, "MOD_BAD : %s\n", mod->name); + break; - case MOD_BRUSH: - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name ); - break; + case MOD_BRUSH: + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name); + break; - case MOD_MDXA: + case MOD_MDXA: - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name ); - break; + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name); + break; - case MOD_MDXM: + case MOD_MDXM: - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name ); - break; + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, mod->numLods, mod->name); + break; - case MOD_MESH: + case MOD_MESH: - lods = 1; - for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) { - if ( mod->md3[j] && mod->md3[j] != mod->md3[j-1] ) { - lods++; - } + lods = 1; + for (j = 1; j < MD3_MAX_LODS; j++) { + if (mod->md3[j] && mod->md3[j] != mod->md3[j - 1]) { + lods++; } - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n",mod->dataSize, lods, mod->name ); - break; + } + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, lods, mod->name); + break; } total += mod->dataSize; } - ri.Printf( PRINT_ALL, "%8i : Total models\n", total ); + ri.Printf(PRINT_ALL, "%8i : Total models\n", total); -/* this doesn't work with the new hunks - if ( tr.world ) { - ri.Printf( PRINT_ALL, "%8i : %s\n", tr.world->dataSize, tr.world->name ); - } */ + /* this doesn't work with the new hunks + if ( tr.world ) { + ri.Printf( PRINT_ALL, "%8i : %s\n", tr.world->dataSize, tr.world->name ); + } */ } //============================================================================= - /* ================ R_GetTag for MD3s ================ */ -static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { - md3Tag_t *tag; - int i; +static md3Tag_t *R_GetTag(md3Header_t *mod, int frame, const char *tagName) { + md3Tag_t *tag; + int i; - if ( frame >= mod->numFrames ) { + if (frame >= mod->numFrames) { // it is possible to have a bad frame while changing models, so don't error frame = mod->numFrames - 1; } tag = (md3Tag_t *)((byte *)mod + mod->ofsTags) + frame * mod->numTags; - for ( i = 0 ; i < mod->numTags ; i++, tag++ ) { - if ( !strcmp( tag->name, tagName ) ) { - return tag; // found it + for (i = 0; i < mod->numTags; i++, tag++) { + if (!strcmp(tag->name, tagName)) { + return tag; // found it } } @@ -1118,77 +1019,70 @@ static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { R_LerpTag ================ */ -void R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, - float frac, const char *tagName ) { - md3Tag_t *start, *finish; - int i; - float frontLerp, backLerp; - model_t *model; - - model = R_GetModelByHandle( handle ); - if ( model->md3[0] ) - { - start = R_GetTag( model->md3[0], startFrame, tagName ); - finish = R_GetTag( model->md3[0], endFrame, tagName ); - } - else - { - AxisClear( tag->axis ); - VectorClear( tag->origin ); +void R_LerpTag(orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, float frac, const char *tagName) { + md3Tag_t *start, *finish; + int i; + float frontLerp, backLerp; + model_t *model; + + model = R_GetModelByHandle(handle); + if (model->md3[0]) { + start = R_GetTag(model->md3[0], startFrame, tagName); + finish = R_GetTag(model->md3[0], endFrame, tagName); + } else { + AxisClear(tag->axis); + VectorClear(tag->origin); return; } - if ( !start || !finish ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + if (!start || !finish) { + AxisClear(tag->axis); + VectorClear(tag->origin); return; } frontLerp = frac; backLerp = 1.0 - frac; - for ( i = 0 ; i < 3 ; i++ ) { - tag->origin[i] = start->origin[i] * backLerp + finish->origin[i] * frontLerp; - tag->axis[0][i] = start->axis[0][i] * backLerp + finish->axis[0][i] * frontLerp; - tag->axis[1][i] = start->axis[1][i] * backLerp + finish->axis[1][i] * frontLerp; - tag->axis[2][i] = start->axis[2][i] * backLerp + finish->axis[2][i] * frontLerp; + for (i = 0; i < 3; i++) { + tag->origin[i] = start->origin[i] * backLerp + finish->origin[i] * frontLerp; + tag->axis[0][i] = start->axis[0][i] * backLerp + finish->axis[0][i] * frontLerp; + tag->axis[1][i] = start->axis[1][i] * backLerp + finish->axis[1][i] * frontLerp; + tag->axis[2][i] = start->axis[2][i] * backLerp + finish->axis[2][i] * frontLerp; } - VectorNormalize( tag->axis[0] ); - VectorNormalize( tag->axis[1] ); - VectorNormalize( tag->axis[2] ); + VectorNormalize(tag->axis[0]); + VectorNormalize(tag->axis[1]); + VectorNormalize(tag->axis[2]); } - /* ==================== R_ModelBounds ==================== */ -void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) { - model_t *model; +void R_ModelBounds(qhandle_t handle, vec3_t mins, vec3_t maxs) { + model_t *model; - model = R_GetModelByHandle( handle ); + model = R_GetModelByHandle(handle); - if ( model->bmodel ) { - VectorCopy( model->bmodel->bounds[0], mins ); - VectorCopy( model->bmodel->bounds[1], maxs ); + if (model->bmodel) { + VectorCopy(model->bmodel->bounds[0], mins); + VectorCopy(model->bmodel->bounds[1], maxs); return; } - if ( model->md3[0] ) { - md3Header_t *header; - md3Frame_t *frame; + if (model->md3[0]) { + md3Header_t *header; + md3Frame_t *frame; header = model->md3[0]; - frame = (md3Frame_t *)( (byte *)header + header->ofsFrames ); + frame = (md3Frame_t *)((byte *)header + header->ofsFrames); - VectorCopy( frame->bounds[0], mins ); - VectorCopy( frame->bounds[1], maxs ); - } - else - { - VectorClear( mins ); - VectorClear( maxs ); + VectorCopy(frame->bounds[0], mins); + VectorCopy(frame->bounds[1], maxs); + } else { + VectorClear(mins); + VectorClear(maxs); return; } } diff --git a/code/rd-vanilla/tr_quicksprite.cpp b/code/rd-vanilla/tr_quicksprite.cpp index 9a0a02e1ac..a3ede6bfc1 100644 --- a/code/rd-vanilla/tr_quicksprite.cpp +++ b/code/rd-vanilla/tr_quicksprite.cpp @@ -27,34 +27,25 @@ along with this program; if not, see . #include "../server/exe_headers.h" #include "tr_quicksprite.h" -extern void R_BindAnimatedImage( const textureBundle_t *bundle ); - +extern void R_BindAnimatedImage(const textureBundle_t *bundle); ////////////////////////////////////////////////////////////////////// // Singleton System ////////////////////////////////////////////////////////////////////// CQuickSpriteSystem SQuickSprite; - ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// -CQuickSpriteSystem::CQuickSpriteSystem() : - mTexBundle(NULL), - mGLStateBits(0), - mFogIndex(-1), - mUseFog(qfalse), - mNextVert(0) -{ +CQuickSpriteSystem::CQuickSpriteSystem() : mTexBundle(NULL), mGLStateBits(0), mFogIndex(-1), mUseFog(qfalse), mNextVert(0) { int i; - memset( mVerts, 0, sizeof( mVerts ) ); - memset( mFogTextureCoords, 0, sizeof( mFogTextureCoords ) ); - memset( mColors, 0, sizeof( mColors ) ); + memset(mVerts, 0, sizeof(mVerts)); + memset(mFogTextureCoords, 0, sizeof(mFogTextureCoords)); + memset(mColors, 0, sizeof(mColors)); - for (i = 0; i < SHADER_MAX_VERTEXES; i += 4) - { + for (i = 0; i < SHADER_MAX_VERTEXES; i += 4) { // Bottom right mTextureCoords[i + 0][0] = 1.0; mTextureCoords[i + 0][1] = 1.0; @@ -70,14 +61,10 @@ CQuickSpriteSystem::CQuickSpriteSystem() : } } -CQuickSpriteSystem::~CQuickSpriteSystem(void) -{ -} +CQuickSpriteSystem::~CQuickSpriteSystem(void) {} -void CQuickSpriteSystem::Flush(void) -{ - if (mNextVert==0) - { +void CQuickSpriteSystem::Flush(void) { + if (mNextVert == 0) { return; } @@ -93,29 +80,28 @@ void CQuickSpriteSystem::Flush(void) qglEnable(GL_FOG); } */ - //this should not be needed, since I just wait to disable fog for the surface til after surface sprites are done + // this should not be needed, since I just wait to disable fog for the surface til after surface sprites are done // // render the main pass // - R_BindAnimatedImage( mTexBundle ); + R_BindAnimatedImage(mTexBundle); GL_State(mGLStateBits); // // set arrays and lock // - qglEnableClientState( GL_TEXTURE_COORD_ARRAY); - qglTexCoordPointer( 2, GL_FLOAT, 0, mTextureCoords ); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, mTextureCoords); - qglEnableClientState( GL_COLOR_ARRAY); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, mColors ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, mColors); - qglVertexPointer (3, GL_FLOAT, 16, mVerts); + qglVertexPointer(3, GL_FLOAT, 16, mVerts); - if ( qglLockArraysEXT ) - { + if (qglLockArraysEXT) { qglLockArraysEXT(0, mNextVert); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } qglDrawArrays(GL_QUADS, 0, mNextVert); @@ -127,7 +113,7 @@ void CQuickSpriteSystem::Flush(void) #ifdef JK2_MODE if (mUseFog) #else - //only for software fog pass (global soft/volumetric) -rww + // only for software fog pass (global soft/volumetric) -rww if (mUseFog && (r_drawfog->integer != 2 || mFogIndex != tr.world->globalFog)) #endif { @@ -136,19 +122,19 @@ void CQuickSpriteSystem::Flush(void) // // render the fog pass // - GL_Bind( tr.fogImage ); - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL ); + GL_Bind(tr.fogImage); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL); // // set arrays and lock // - qglTexCoordPointer( 2, GL_FLOAT, 0, mFogTextureCoords); -// qglEnableClientState( GL_TEXTURE_COORD_ARRAY); // Done above + qglTexCoordPointer(2, GL_FLOAT, 0, mFogTextureCoords); + // qglEnableClientState( GL_TEXTURE_COORD_ARRAY); // Done above - qglDisableClientState( GL_COLOR_ARRAY ); + qglDisableClientState(GL_COLOR_ARRAY); qglColor4ubv((GLubyte *)&fog->colorInt); -// qglVertexPointer (3, GL_FLOAT, 16, mVerts); // Done above + // qglVertexPointer (3, GL_FLOAT, 16, mVerts); // Done above qglDrawArrays(GL_QUADS, 0, mNextVert); @@ -159,75 +145,58 @@ void CQuickSpriteSystem::Flush(void) // // unlock arrays // - if (qglUnlockArraysEXT) - { + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } - mNextVert=0; + mNextVert = 0; } - -void CQuickSpriteSystem::StartGroup(textureBundle_t *bundle, uint32_t glbits, int fogIndex ) -{ +void CQuickSpriteSystem::StartGroup(textureBundle_t *bundle, uint32_t glbits, int fogIndex) { mNextVert = 0; mTexBundle = bundle; mGLStateBits = glbits; - if (fogIndex != -1) - { + if (fogIndex != -1) { mUseFog = qtrue; mFogIndex = fogIndex; - } - else - { + } else { mUseFog = qfalse; } int cullingOn; - qglGetIntegerv(GL_CULL_FACE,&cullingOn); + qglGetIntegerv(GL_CULL_FACE, &cullingOn); - if(cullingOn) - { - mTurnCullBackOn=qtrue; - } - else - { - mTurnCullBackOn=qfalse; + if (cullingOn) { + mTurnCullBackOn = qtrue; + } else { + mTurnCullBackOn = qfalse; } qglDisable(GL_CULL_FACE); } - -void CQuickSpriteSystem::EndGroup(void) -{ +void CQuickSpriteSystem::EndGroup(void) { Flush(); - qglColor4ub(255,255,255,255); - if(mTurnCullBackOn) - { + qglColor4ub(255, 255, 255, 255); + if (mTurnCullBackOn) { qglEnable(GL_CULL_FACE); } } - - - -void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) -{ +void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) { float *curcoord; float *curfogtexcoord; uint32_t *curcolor; - if (mNextVert>SHADER_MAX_VERTEXES-4) - { + if (mNextVert > SHADER_MAX_VERTEXES - 4) { Flush(); } curcoord = mVerts[mNextVert]; // This is 16*sizeof(float) because, pointdata comes from a float[16] - memcpy(curcoord, pointdata, 16*sizeof(float)); + memcpy(curcoord, pointdata, 16 * sizeof(float)); // Set up color curcolor = &mColors[mNextVert]; @@ -236,8 +205,7 @@ void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) *curcolor++ = *(uint32_t *)color; *curcolor++ = *(uint32_t *)color; - if (fog) - { + if (fog) { curfogtexcoord = &mFogTextureCoords[mNextVert][0]; *curfogtexcoord++ = fog[0]; *curfogtexcoord++ = fog[1]; @@ -251,12 +219,10 @@ void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) *curfogtexcoord++ = fog[0]; *curfogtexcoord++ = fog[1]; - mUseFog=qtrue; - } - else - { - mUseFog=qfalse; + mUseFog = qtrue; + } else { + mUseFog = qfalse; } - mNextVert+=4; + mNextVert += 4; } diff --git a/code/rd-vanilla/tr_scene.cpp b/code/rd-vanilla/tr_scene.cpp index d0b6b54977..c6259f52fd 100644 --- a/code/rd-vanilla/tr_scene.cpp +++ b/code/rd-vanilla/tr_scene.cpp @@ -26,21 +26,21 @@ along with this program; if not, see . #include "tr_local.h" -int r_firstSceneDrawSurf; +int r_firstSceneDrawSurf; -int r_numdlights; -int r_firstSceneDlight; +int r_numdlights; +int r_firstSceneDlight; -int r_numentities; -int r_firstSceneEntity; +int r_numentities; +int r_firstSceneEntity; -int r_numpolys; -int r_firstScenePoly; +int r_numpolys; +int r_firstScenePoly; -int r_numpolyverts; +int r_numpolyverts; -int skyboxportal; -int drawskyboxportal; +int skyboxportal; +int drawskyboxportal; /* ==================== @@ -48,7 +48,7 @@ R_InitNextFrame ==================== */ -void R_InitNextFrame( void ) { +void R_InitNextFrame(void) { backEndData->commands.used = 0; @@ -66,18 +66,17 @@ void R_InitNextFrame( void ) { r_numpolyverts = 0; } - /* ==================== RE_ClearScene ==================== */ -void RE_ClearScene( void ) { +void RE_ClearScene(void) { r_firstSceneDlight = r_numdlights; r_firstSceneEntity = r_numentities; r_firstScenePoly = r_numpolys; - tr.refdef.rdflags &= ~(RDF_doLAGoggles|RDF_doFullbright); //probably not needed since it gets copied over in RE_RenderScene + tr.refdef.rdflags &= ~(RDF_doLAGoggles | RDF_doFullbright); // probably not needed since it gets copied over in RE_RenderScene tr.refdef.doLAGoggles = qfalse; } @@ -96,17 +95,17 @@ R_AddPolygonSurfaces Adds all the scene's polys into this view's drawsurf list ===================== */ -void R_AddPolygonSurfaces( void ) { - int i; - shader_t *sh; - srfPoly_t *poly; +void R_AddPolygonSurfaces(void) { + int i; + shader_t *sh; + srfPoly_t *poly; tr.currentEntityNum = REFENTITYNUM_WORLD; tr.shiftedEntityNum = tr.currentEntityNum << QSORT_REFENTITYNUM_SHIFT; - for ( i = 0, poly = tr.refdef.polys; i < tr.refdef.numPolys ; i++, poly++ ) { - sh = R_GetShaderByHandle( poly->hShader ); - R_AddDrawSurf( ( surfaceType_t * )poly, sh, poly->fogIndex, qfalse ); + for (i = 0, poly = tr.refdef.polys; i < tr.refdef.numPolys; i++, poly++) { + sh = R_GetShaderByHandle(poly->hShader); + R_AddDrawSurf((surfaceType_t *)poly, sh, poly->fogIndex, qfalse); } } @@ -116,32 +115,32 @@ RE_AddPolyToScene ===================== */ -void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) { - srfPoly_t *poly; - int i; - int fogIndex = 0; - fog_t *fog; - vec3_t bounds[2]; - - if ( !tr.registered ) { +void RE_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts) { + srfPoly_t *poly; + int i; + int fogIndex = 0; + fog_t *fog; + vec3_t bounds[2]; + + if (!tr.registered) { return; } - if ( !hShader ) { + if (!hShader) { #ifndef FINAL_BUILD - Com_DPrintf( S_COLOR_YELLOW"WARNING: RE_AddPolyToScene: NULL poly shader\n"); + Com_DPrintf(S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: NULL poly shader\n"); #endif return; } - if ( r_numpolyverts + numVerts >= MAX_POLYVERTS || r_numpolys >= MAX_POLYS ) { - /* - NOTE TTimo this was initially a PRINT_WARNING - but it happens a lot with high fighting scenes and particles - since we don't plan on changing the const and making for room for those effects - simply cut this message to developer only - */ - ri.Printf( PRINT_DEVELOPER, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); + if (r_numpolyverts + numVerts >= MAX_POLYVERTS || r_numpolys >= MAX_POLYS) { + /* + NOTE TTimo this was initially a PRINT_WARNING + but it happens a lot with high fighting scenes and particles + since we don't plan on changing the const and making for room for those effects + simply cut this message to developer only + */ + ri.Printf(PRINT_DEVELOPER, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); return; } @@ -151,44 +150,34 @@ void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *vert poly->numVerts = numVerts; poly->verts = &backEndData->polyVerts[r_numpolyverts]; - memcpy( poly->verts, verts, numVerts * sizeof( *verts ) ); + memcpy(poly->verts, verts, numVerts * sizeof(*verts)); r_numpolys++; r_numpolyverts += numVerts; // see if it is in a fog volume - if ( !tr.world || tr.world->numfogs == 1) { + if (!tr.world || tr.world->numfogs == 1) { fogIndex = 0; } else { // find which fog volume the poly is in - VectorCopy( poly->verts[0].xyz, bounds[0] ); - VectorCopy( poly->verts[0].xyz, bounds[1] ); - for ( i = 1 ; i < poly->numVerts ; i++ ) { - AddPointToBounds( poly->verts[i].xyz, bounds[0], bounds[1] ); + VectorCopy(poly->verts[0].xyz, bounds[0]); + VectorCopy(poly->verts[0].xyz, bounds[1]); + for (i = 1; i < poly->numVerts; i++) { + AddPointToBounds(poly->verts[i].xyz, bounds[0], bounds[1]); } - for ( int fI = 1 ; fI < tr.world->numfogs ; fI++ ) { + for (int fI = 1; fI < tr.world->numfogs; fI++) { fog = &tr.world->fogs[fI]; - if ( bounds[0][0] >= fog->bounds[0][0] - && bounds[0][1] >= fog->bounds[0][1] - && bounds[0][2] >= fog->bounds[0][2] - && bounds[1][0] <= fog->bounds[1][0] - && bounds[1][1] <= fog->bounds[1][1] - && bounds[1][2] <= fog->bounds[1][2] ) - {//completely in this one + if (bounds[0][0] >= fog->bounds[0][0] && bounds[0][1] >= fog->bounds[0][1] && bounds[0][2] >= fog->bounds[0][2] && + bounds[1][0] <= fog->bounds[1][0] && bounds[1][1] <= fog->bounds[1][1] && bounds[1][2] <= fog->bounds[1][2]) { // completely in this one fogIndex = fI; break; - } - else if ( ( bounds[0][0] >= fog->bounds[0][0] && bounds[0][1] >= fog->bounds[0][1] && bounds[0][2] >= fog->bounds[0][2] && + } else if ((bounds[0][0] >= fog->bounds[0][0] && bounds[0][1] >= fog->bounds[0][1] && bounds[0][2] >= fog->bounds[0][2] && bounds[0][0] <= fog->bounds[1][0] && bounds[0][1] <= fog->bounds[1][1] && bounds[0][2] <= fog->bounds[1][2]) || - ( bounds[1][0] >= fog->bounds[0][0] && bounds[1][1] >= fog->bounds[0][1] && bounds[1][2] >= fog->bounds[0][2] && - bounds[1][0] <= fog->bounds[1][0] && bounds[1][1] <= fog->bounds[1][1] && bounds[1][2] <= fog->bounds[1][2] ) ) - {//partially in this one - if ( tr.refdef.fogIndex == fI || R_FogParmsMatch( tr.refdef.fogIndex, fI ) ) - {//take new one only if it's the same one that the viewpoint is in + (bounds[1][0] >= fog->bounds[0][0] && bounds[1][1] >= fog->bounds[0][1] && bounds[1][2] >= fog->bounds[0][2] && + bounds[1][0] <= fog->bounds[1][0] && bounds[1][1] <= fog->bounds[1][1] && bounds[1][2] <= fog->bounds[1][2])) { // partially in this one + if (tr.refdef.fogIndex == fI || R_FogParmsMatch(tr.refdef.fogIndex, fI)) { // take new one only if it's the same one that the viewpoint is in fogIndex = fI; break; - } - else if ( !fogIndex ) - {//didn't find one yet, so use this one + } else if (!fogIndex) { // didn't find one yet, so use this one fogIndex = fI; } } @@ -197,28 +186,26 @@ void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *vert poly->fogIndex = fogIndex; } - //================================================================================= - /* ===================== RE_AddRefEntityToScene ===================== */ -void RE_AddRefEntityToScene( const refEntity_t *ent ) { - if ( !tr.registered ) { +void RE_AddRefEntityToScene(const refEntity_t *ent) { + if (!tr.registered) { return; } - if ( r_numentities >= MAX_REFENTITIES ) { + if (r_numentities >= MAX_REFENTITIES) { #ifndef FINAL_BUILD - ri.Printf( PRINT_WARNING, "WARNING: RE_AddRefEntityToScene: too many entities\n"); + ri.Printf(PRINT_WARNING, "WARNING: RE_AddRefEntityToScene: too many entities\n"); #endif return; } - if ( ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) { - Com_Error( ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType ); + if (ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE) { + Com_Error(ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType); } backEndData->entities[r_numentities].e = *ent; @@ -227,34 +214,32 @@ void RE_AddRefEntityToScene( const refEntity_t *ent ) { r_numentities++; } - /* ===================== RE_AddLightToScene ===================== */ -void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - dlight_t *dl; +void RE_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + dlight_t *dl; - if ( !tr.registered ) { + if (!tr.registered) { return; } - if ( r_numdlights >= MAX_DLIGHTS ) { + if (r_numdlights >= MAX_DLIGHTS) { return; } - if ( intensity <= 0 ) { + if (intensity <= 0) { return; } dl = &backEndData->dlights[r_numdlights++]; - VectorCopy (org, dl->origin); + VectorCopy(org, dl->origin); dl->radius = intensity; dl->color[0] = r; dl->color[1] = g; dl->color[2] = b; } - /* @@@@@@@@@@@@@@@@@@@@@ RE_RenderScene @@ -266,28 +251,28 @@ Rendering a scene may require multiple views to be rendered to handle mirrors, @@@@@@@@@@@@@@@@@@@@@ */ -extern int recursivePortalCount; -void RE_RenderScene( const refdef_t *fd ) { - viewParms_t parms; - int startTime; - static int lastTime = 0; +extern int recursivePortalCount; +void RE_RenderScene(const refdef_t *fd) { + viewParms_t parms; + int startTime; + static int lastTime = 0; - if ( !tr.registered ) { + if (!tr.registered) { return; } - GLimp_LogComment( "====== RE_RenderScene =====\n" ); + GLimp_LogComment("====== RE_RenderScene =====\n"); - if ( r_norefresh->integer ) { + if (r_norefresh->integer) { return; } startTime = ri.Milliseconds(); - if (!tr.world && !( fd->rdflags & RDF_NOWORLDMODEL ) ) { - Com_Error (ERR_DROP, "R_RenderScene: NULL worldmodel"); + if (!tr.world && !(fd->rdflags & RDF_NOWORLDMODEL)) { + Com_Error(ERR_DROP, "R_RenderScene: NULL worldmodel"); } -// memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) ); + // memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) ); tr.refdef.x = fd->x; tr.refdef.y = fd->y; @@ -296,10 +281,10 @@ void RE_RenderScene( const refdef_t *fd ) { tr.refdef.fov_x = fd->fov_x; tr.refdef.fov_y = fd->fov_y; - VectorCopy( fd->vieworg, tr.refdef.vieworg ); - VectorCopy( fd->viewaxis[0], tr.refdef.viewaxis[0] ); - VectorCopy( fd->viewaxis[1], tr.refdef.viewaxis[1] ); - VectorCopy( fd->viewaxis[2], tr.refdef.viewaxis[2] ); + VectorCopy(fd->vieworg, tr.refdef.vieworg); + VectorCopy(fd->viewaxis[0], tr.refdef.viewaxis[0]); + VectorCopy(fd->viewaxis[1], tr.refdef.viewaxis[1]); + VectorCopy(fd->viewaxis[2], tr.refdef.viewaxis[2]); tr.refdef.time = fd->time; tr.refdef.frametime = fd->time - lastTime; @@ -308,46 +293,39 @@ void RE_RenderScene( const refdef_t *fd ) { // We need to figure out what's going on in fd->rdflags first :S .. I'm half-tempted to just revert // back to JK2 and use a qbool for it --eez - if (fd->rdflags & RDF_SKYBOXPORTAL) - { + if (fd->rdflags & RDF_SKYBOXPORTAL) { skyboxportal = 1; - } - else - { + } else { // cdr - only change last time for the real render, not the portal lastTime = fd->time; } - if (fd->rdflags & RDF_DRAWSKYBOX) - { + if (fd->rdflags & RDF_DRAWSKYBOX) { drawskyboxportal = 1; - } - else - { + } else { drawskyboxportal = 0; } // copy the areamask data over and note if it has changed, which // will force a reset of the visible leafs even if the view hasn't moved tr.refdef.areamaskModified = qfalse; - if ( ! (tr.refdef.rdflags & RDF_NOWORLDMODEL) ) { - int areaDiff; - int i; + if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) { + int areaDiff; + int i; // compare the area bits areaDiff = 0; - for (i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++) { + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { areaDiff |= ((int *)tr.refdef.areamask)[i] ^ ((int *)fd->areamask)[i]; ((int *)tr.refdef.areamask)[i] = ((int *)fd->areamask)[i]; } - if ( areaDiff ) { + if (areaDiff) { // a door just opened or something tr.refdef.areamaskModified = qtrue; } } - // derived info tr.refdef.floatTime = tr.refdef.time * 0.001; @@ -365,8 +343,7 @@ void RE_RenderScene( const refdef_t *fd ) { // turn off dynamic lighting globally by clearing all the // dlights if it needs to be disabled or if vertex lighting is enabled - if ( r_dynamiclight->integer == 0 || - r_vertexLight->integer == 1 ) { + if (r_dynamiclight->integer == 0 || r_vertexLight->integer == 1) { tr.refdef.num_dlights = 0; } @@ -384,9 +361,9 @@ void RE_RenderScene( const refdef_t *fd ) { // The refdef takes 0-at-the-top y coordinates, so // convert to GL's 0-at-the-bottom space // - memset( &parms, 0, sizeof( parms ) ); + memset(&parms, 0, sizeof(parms)); parms.viewportX = tr.refdef.x; - parms.viewportY = glConfig.vidHeight - ( tr.refdef.y + tr.refdef.height ); + parms.viewportY = glConfig.vidHeight - (tr.refdef.y + tr.refdef.height); parms.viewportWidth = tr.refdef.width; parms.viewportHeight = tr.refdef.height; parms.isPortal = qfalse; @@ -394,15 +371,15 @@ void RE_RenderScene( const refdef_t *fd ) { parms.fovX = tr.refdef.fov_x; parms.fovY = tr.refdef.fov_y; - VectorCopy( fd->vieworg, parms.ori.origin ); - VectorCopy( fd->viewaxis[0], parms.ori.axis[0] ); - VectorCopy( fd->viewaxis[1], parms.ori.axis[1] ); - VectorCopy( fd->viewaxis[2], parms.ori.axis[2] ); + VectorCopy(fd->vieworg, parms.ori.origin); + VectorCopy(fd->viewaxis[0], parms.ori.axis[0]); + VectorCopy(fd->viewaxis[1], parms.ori.axis[1]); + VectorCopy(fd->viewaxis[2], parms.ori.axis[2]); - VectorCopy( fd->vieworg, parms.pvsOrigin ); + VectorCopy(fd->vieworg, parms.pvsOrigin); recursivePortalCount = 0; - R_RenderView( &parms ); + R_RenderView(&parms); // the next scene rendered in this frame will tack on after this one r_firstSceneDrawSurf = tr.refdef.numDrawSurfs; diff --git a/code/rd-vanilla/tr_shade.cpp b/code/rd-vanilla/tr_shade.cpp index 48f3ed1332..6d1df2a540 100644 --- a/code/rd-vanilla/tr_shade.cpp +++ b/code/rd-vanilla/tr_shade.cpp @@ -35,11 +35,11 @@ along with this program; if not, see . This file deals with applying shaders to surface data in the tess struct. */ -shaderCommands_t tess; -static qboolean setArraysOnce; +shaderCommands_t tess; +static qboolean setArraysOnce; -color4ub_t styleColors[MAX_LIGHT_STYLES]; -bool styleUpdated[MAX_LIGHT_STYLES]; +color4ub_t styleColors[MAX_LIGHT_STYLES]; +bool styleUpdated[MAX_LIGHT_STYLES]; extern bool g_bRenderGlowingObjects; @@ -50,15 +50,15 @@ R_ArrayElementDiscrete This is just for OpenGL conformance testing, it should never be the fastest ================ */ -static void APIENTRY R_ArrayElementDiscrete( GLint index ) { - qglColor4ubv( tess.svars.colors[ index ] ); - if ( glState.currenttmu ) { - qglMultiTexCoord2fARB( 0, tess.svars.texcoords[ 0 ][ index ][0], tess.svars.texcoords[ 0 ][ index ][1] ); - qglMultiTexCoord2fARB( 1, tess.svars.texcoords[ 1 ][ index ][0], tess.svars.texcoords[ 1 ][ index ][1] ); +static void APIENTRY R_ArrayElementDiscrete(GLint index) { + qglColor4ubv(tess.svars.colors[index]); + if (glState.currenttmu) { + qglMultiTexCoord2fARB(0, tess.svars.texcoords[0][index][0], tess.svars.texcoords[0][index][1]); + qglMultiTexCoord2fARB(1, tess.svars.texcoords[1][index][0], tess.svars.texcoords[1][index][1]); } else { - qglTexCoord2fv( tess.svars.texcoords[ 0 ][ index ] ); + qglTexCoord2fv(tess.svars.texcoords[0][index]); } - qglVertex3fv( tess.xyz[ index ] ); + qglVertex3fv(tess.xyz[index]); } /* @@ -67,24 +67,24 @@ R_DrawStripElements =================== */ -static int c_vertexes; // for seeing how long our average strips are -static int c_begins; -static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void ( APIENTRY *element )(GLint) ) { +static int c_vertexes; // for seeing how long our average strips are +static int c_begins; +static void R_DrawStripElements(int numIndexes, const glIndex_t *indexes, void(APIENTRY *element)(GLint)) { int i; glIndex_t last[3]; qboolean even; - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); c_begins++; - if ( numIndexes <= 0 ) { + if (numIndexes <= 0) { return; } // prime the strip - element( indexes[0] ); - element( indexes[1] ); - element( indexes[2] ); + element(indexes[0]); + element(indexes[1]); + element(indexes[2]); c_vertexes += 3; last[0] = indexes[0]; @@ -93,59 +93,51 @@ static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void even = qfalse; - for ( i = 3; i < numIndexes; i += 3 ) - { + for (i = 3; i < numIndexes; i += 3) { // odd numbered triangle in potential strip - if ( !even ) - { + if (!even) { // check previous triangle to see if we're continuing a strip - if ( ( indexes[i+0] == last[2] ) && ( indexes[i+1] == last[1] ) ) - { - element( indexes[i+2] ); + if ((indexes[i + 0] == last[2]) && (indexes[i + 1] == last[1])) { + element(indexes[i + 2]); c_vertexes++; - assert( (int)indexes[i+2] < tess.numVertexes ); + assert((int)indexes[i + 2] < tess.numVertexes); even = qtrue; } // otherwise we're done with this strip so finish it and start // a new one - else - { + else { qglEnd(); - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); c_begins++; - element( indexes[i+0] ); - element( indexes[i+1] ); - element( indexes[i+2] ); + element(indexes[i + 0]); + element(indexes[i + 1]); + element(indexes[i + 2]); c_vertexes += 3; even = qfalse; } - } - else - { + } else { // check previous triangle to see if we're continuing a strip - if ( ( last[2] == indexes[i+1] ) && ( last[0] == indexes[i+0] ) ) - { - element( indexes[i+2] ); + if ((last[2] == indexes[i + 1]) && (last[0] == indexes[i + 0])) { + element(indexes[i + 2]); c_vertexes++; even = qfalse; } // otherwise we're done with this strip so finish it and start // a new one - else - { + else { qglEnd(); - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); c_begins++; - element( indexes[i+0] ); - element( indexes[i+1] ); - element( indexes[i+2] ); + element(indexes[i + 0]); + element(indexes[i + 1]); + element(indexes[i + 2]); c_vertexes += 3; even = qfalse; @@ -153,9 +145,9 @@ static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void } // cache the last three vertices - last[0] = indexes[i+0]; - last[1] = indexes[i+1]; - last[2] = indexes[i+2]; + last[0] = indexes[i + 0]; + last[1] = indexes[i + 1]; + last[2] = indexes[i + 2]; } qglEnd(); @@ -170,46 +162,38 @@ instead of using the single glDrawElements call that may be inefficient without compiled vertex arrays. ================== */ -static void R_DrawElements( int numIndexes, const glIndex_t *indexes ) { - int primitives; +static void R_DrawElements(int numIndexes, const glIndex_t *indexes) { + int primitives; primitives = r_primitives->integer; // default is to use triangles if compiled vertex arrays are present - if ( primitives == 0 ) { - if ( qglLockArraysEXT ) { + if (primitives == 0) { + if (qglLockArraysEXT) { primitives = 2; } else { primitives = 1; } } - - if ( primitives == 2 ) { - qglDrawElements( GL_TRIANGLES, - numIndexes, - GL_INDEX_TYPE, - indexes ); + if (primitives == 2) { + qglDrawElements(GL_TRIANGLES, numIndexes, GL_INDEX_TYPE, indexes); return; } - if ( primitives == 1 ) { - R_DrawStripElements( numIndexes, indexes, qglArrayElement ); + if (primitives == 1) { + R_DrawStripElements(numIndexes, indexes, qglArrayElement); return; } - if ( primitives == 3 ) { - R_DrawStripElements( numIndexes, indexes, R_ArrayElementDiscrete ); + if (primitives == 3) { + R_DrawStripElements(numIndexes, indexes, R_ArrayElementDiscrete); return; } // anything else will cause no drawing } - - - - /* ============================================================= @@ -218,67 +202,57 @@ SURFACE SHADERS ============================================================= */ - /* ================= R_BindAnimatedImage ================= */ -void R_BindAnimatedImage( const textureBundle_t *bundle) { - int index; +void R_BindAnimatedImage(const textureBundle_t *bundle) { + int index; - if ( bundle->isVideoMap ) { + if (bundle->isVideoMap) { ri.CIN_RunCinematic(bundle->videoMapHandle); ri.CIN_UploadCinematic(bundle->videoMapHandle); return; } - if ((r_fullbright->integer || tr.refdef.doLAGoggles || (tr.refdef.rdflags & RDF_doFullbright) ) && bundle->isLightmap) - { - GL_Bind( tr.whiteImage ); + if ((r_fullbright->integer || tr.refdef.doLAGoggles || (tr.refdef.rdflags & RDF_doFullbright)) && bundle->isLightmap) { + GL_Bind(tr.whiteImage); return; } - if ( bundle->numImageAnimations <= 1 ) { - GL_Bind( bundle->image ); + if (bundle->numImageAnimations <= 1) { + GL_Bind(bundle->image); return; } - if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) - { + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX) { index = backEnd.currentEntity->e.skinNum; - } - else - { + } else { // it is necessary to do this messy calc to make sure animations line up // exactly with waveforms of the same frequency - index = Q_ftol( backEnd.refdef.floatTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index = Q_ftol(backEnd.refdef.floatTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE); index >>= FUNCTABLE_SIZE2; - if ( index < 0 ) { - index = 0; // may happen with shader time offsets + if (index < 0) { + index = 0; // may happen with shader time offsets } } - if ( bundle->oneShotAnimMap ) - { - if ( index >= bundle->numImageAnimations ) - { + if (bundle->oneShotAnimMap) { + if (index >= bundle->numImageAnimations) { // stick on last frame index = bundle->numImageAnimations - 1; } - } - else - { + } else { // loop index %= bundle->numImageAnimations; } - GL_Bind( *((image_t**)bundle->image + index) ); + GL_Bind(*((image_t **)bundle->image + index)); } - /* ================ DrawTris @@ -286,102 +260,92 @@ DrawTris Draws triangle outlines for debugging ================ */ -static void DrawTris (shaderCommands_t *input) -{ - GL_Bind( tr.whiteImage ); +static void DrawTris(shaderCommands_t *input) { + GL_Bind(tr.whiteImage); - if ( r_showtriscolor->integer ) - { + if (r_showtriscolor->integer) { int i = r_showtriscolor->integer; if (i == 42) { - i = Q_irand(0,8); + i = Q_irand(0, 8); } - switch (i) - { + switch (i) { case 1: - qglColor3f( 1.0, 0.0, 0.0); //red + qglColor3f(1.0, 0.0, 0.0); // red break; case 2: - qglColor3f( 0.0, 1.0, 0.0); //green + qglColor3f(0.0, 1.0, 0.0); // green break; case 3: - qglColor3f( 1.0, 1.0, 0.0); //yellow + qglColor3f(1.0, 1.0, 0.0); // yellow break; case 4: - qglColor3f( 0.0, 0.0, 1.0); //blue + qglColor3f(0.0, 0.0, 1.0); // blue break; case 5: - qglColor3f( 0.0, 1.0, 1.0); //cyan + qglColor3f(0.0, 1.0, 1.0); // cyan break; case 6: - qglColor3f( 1.0, 0.0, 1.0); //magenta + qglColor3f(1.0, 0.0, 1.0); // magenta break; case 7: - qglColor3f( 0.8f, 0.8f, 0.8f); //white/grey + qglColor3f(0.8f, 0.8f, 0.8f); // white/grey break; case 8: - qglColor3f( 0.0, 0.0, 0.0); //black + qglColor3f(0.0, 0.0, 0.0); // black break; } - } - else - { - qglColor3f( 1.0, 1.0, 1.0); //white + } else { + qglColor3f(1.0, 1.0, 1.0); // white } - if ( r_showtris->integer == 2 ) - { + if (r_showtris->integer == 2) { // tries to do non-xray style showtris - GL_State( GLS_POLYMODE_LINE ); + GL_State(GLS_POLYMODE_LINE); - qglEnable( GL_POLYGON_OFFSET_LINE ); - qglPolygonOffset( -1, -2 ); + qglEnable(GL_POLYGON_OFFSET_LINE); + qglPolygonOffset(-1, -2); - qglDisableClientState( GL_COLOR_ARRAY ); - qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); + qglDisableClientState(GL_COLOR_ARRAY); + qglDisableClientState(GL_TEXTURE_COORD_ARRAY); - qglVertexPointer( 3, GL_FLOAT, 16, input->xyz ); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, input->xyz); // padded for SIMD - if ( qglLockArraysEXT ) - { - qglLockArraysEXT( 0, input->numVertexes ); - GLimp_LogComment( "glLockArraysEXT\n" ); + if (qglLockArraysEXT) { + qglLockArraysEXT(0, input->numVertexes); + GLimp_LogComment("glLockArraysEXT\n"); } - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); - if ( qglUnlockArraysEXT ) - { - qglUnlockArraysEXT( ); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + if (qglUnlockArraysEXT) { + qglUnlockArraysEXT(); + GLimp_LogComment("glUnlockArraysEXT\n"); } - qglDisable( GL_POLYGON_OFFSET_LINE ); - } - else - { + qglDisable(GL_POLYGON_OFFSET_LINE); + } else { // same old showtris - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE ); - qglDepthRange( 0, 0 ); + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE); + qglDepthRange(0, 0); - qglDisableClientState (GL_COLOR_ARRAY); - qglDisableClientState (GL_TEXTURE_COORD_ARRAY); + qglDisableClientState(GL_COLOR_ARRAY); + qglDisableClientState(GL_TEXTURE_COORD_ARRAY); - qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, input->xyz); // padded for SIMD if (qglLockArraysEXT) { qglLockArraysEXT(0, input->numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } } @@ -392,27 +356,26 @@ DrawNormals Draws vertex normals for debugging ================ */ -static void DrawNormals (shaderCommands_t *input) { - int i; - vec3_t temp; - - GL_Bind( tr.whiteImage ); - qglColor3f (1,1,1); - qglDepthRange( 0, 0 ); // never occluded - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE ); - - qglBegin (GL_LINES); - for (i = 0 ; i < input->numVertexes ; i++) { - qglVertex3fv (input->xyz[i]); - VectorMA (input->xyz[i], 2, input->normal[i], temp); - qglVertex3fv (temp); +static void DrawNormals(shaderCommands_t *input) { + int i; + vec3_t temp; + + GL_Bind(tr.whiteImage); + qglColor3f(1, 1, 1); + qglDepthRange(0, 0); // never occluded + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE); + + qglBegin(GL_LINES); + for (i = 0; i < input->numVertexes; i++) { + qglVertex3fv(input->xyz[i]); + VectorMA(input->xyz[i], 2, input->normal[i], temp); + qglVertex3fv(temp); } - qglEnd (); + qglEnd(); - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } - /* ============== RB_BeginSurface @@ -422,17 +385,17 @@ because a surface may be forced to perform a RB_End due to overflow. ============== */ -void RB_BeginSurface( shader_t *shader, int fogNum ) { -// shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader; +void RB_BeginSurface(shader_t *shader, int fogNum) { + // shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader; shader_t *state = shader; tess.numIndexes = 0; tess.numVertexes = 0; - tess.shader = state;//shader; + tess.shader = state; // shader; tess.fogNum = fogNum; - tess.dlightBits = 0; // will be OR'd in by surface functions + tess.dlightBits = 0; // will be OR'd in by surface functions - tess.SSInitializedWind = qfalse; //is this right? + tess.SSInitializedWind = qfalse; // is this right? tess.xstages = state->stages; tess.numPasses = state->numUnfoggedPasses; @@ -454,45 +417,45 @@ t0 = most upstream according to spec t1 = most downstream according to spec =================== */ -static void DrawMultitextured( shaderCommands_t *input, int stage ) { - shaderStage_t *pStage; +static void DrawMultitextured(shaderCommands_t *input, int stage) { + shaderStage_t *pStage; pStage = &tess.xstages[stage]; - GL_State( pStage->stateBits ); + GL_State(pStage->stateBits); // // base // - GL_SelectTexture( 0 ); - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] ); - R_BindAnimatedImage( &pStage->bundle[0] ); + GL_SelectTexture(0); + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[0]); + R_BindAnimatedImage(&pStage->bundle[0]); // // lightmap/secondary pass // - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); - if ( r_lightmap->integer ) { - GL_TexEnv( GL_REPLACE ); + if (r_lightmap->integer) { + GL_TexEnv(GL_REPLACE); } else { - GL_TexEnv( tess.shader->multitextureEnv ); + GL_TexEnv(tess.shader->multitextureEnv); } - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[1]); - R_BindAnimatedImage( &pStage->bundle[1] ); + R_BindAnimatedImage(&pStage->bundle[1]); - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); // // disable texturing on TEXTURE1, then select TEXTURE0 // - qglDisable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); - GL_SelectTexture( 0 ); + GL_SelectTexture(0); } //--EF_old dlight code...reverting back to Quake III dlight to see if people like that better @@ -657,168 +620,149 @@ ProjectDlightTexture Perform dynamic lighting with another rendering pass =================== */ -static void ProjectDlightTexture2( void ) { - int i, l; - vec3_t origin; - byte clipBits[SHADER_MAX_VERTEXES]; - float texCoordsArray[SHADER_MAX_VERTEXES][2]; - float oldTexCoordsArray[SHADER_MAX_VERTEXES][2]; - float vertCoordsArray[SHADER_MAX_VERTEXES][4]; - unsigned int colorArray[SHADER_MAX_VERTEXES]; - glIndex_t hitIndexes[SHADER_MAX_INDEXES]; - int numIndexes; - float radius; +static void ProjectDlightTexture2(void) { + int i, l; + vec3_t origin; + byte clipBits[SHADER_MAX_VERTEXES]; + float texCoordsArray[SHADER_MAX_VERTEXES][2]; + float oldTexCoordsArray[SHADER_MAX_VERTEXES][2]; + float vertCoordsArray[SHADER_MAX_VERTEXES][4]; + unsigned int colorArray[SHADER_MAX_VERTEXES]; + glIndex_t hitIndexes[SHADER_MAX_INDEXES]; + int numIndexes; + float radius; #ifndef JK2_MODE - int fogging; + int fogging; #endif shaderStage_t *dStage; - vec3_t posa; - vec3_t posb; - vec3_t posc; - vec3_t dist; - vec3_t e1; - vec3_t e2; - vec3_t normal; - float fac,modulate; - vec3_t floatColor; + vec3_t posa; + vec3_t posb; + vec3_t posc; + vec3_t dist; + vec3_t e1; + vec3_t e2; + vec3_t normal; + float fac, modulate; + vec3_t floatColor; byte colorTemp[4]; - int needResetVerts=0; + int needResetVerts = 0; - if ( !backEnd.refdef.num_dlights ) - { + if (!backEnd.refdef.num_dlights) { return; } - for ( l = 0 ; l < backEnd.refdef.num_dlights ; l++ ) - { - dlight_t *dl; + for (l = 0; l < backEnd.refdef.num_dlights; l++) { + dlight_t *dl; - if ( !( tess.dlightBits & ( 1 << l ) ) ) { - continue; // this surface definately doesn't have any of this light + if (!(tess.dlightBits & (1 << l))) { + continue; // this surface definately doesn't have any of this light } dl = &backEnd.refdef.dlights[l]; - VectorCopy( dl->transformed, origin ); + VectorCopy(dl->transformed, origin); radius = dl->radius; - int clipall = 63; - for ( i = 0 ; i < tess.numVertexes ; i++) - { - int clip; - VectorSubtract( origin, tess.xyz[i], dist ); + int clipall = 63; + for (i = 0; i < tess.numVertexes; i++) { + int clip; + VectorSubtract(origin, tess.xyz[i], dist); clip = 0; - if ( dist[0] < -radius ) - { + if (dist[0] < -radius) { clip |= 1; - } - else if ( dist[0] > radius ) - { + } else if (dist[0] > radius) { clip |= 2; } - if ( dist[1] < -radius ) - { + if (dist[1] < -radius) { clip |= 4; - } - else if ( dist[1] > radius ) - { + } else if (dist[1] > radius) { clip |= 8; } - if ( dist[2] < -radius ) - { + if (dist[2] < -radius) { clip |= 16; - } - else if ( dist[2] > radius ) - { + } else if (dist[2] > radius) { clip |= 32; } clipBits[i] = clip; clipall &= clip; } - if ( clipall ) - { - continue; // this surface doesn't have any of this light + if (clipall) { + continue; // this surface doesn't have any of this light } floatColor[0] = dl->color[0] * 255.0f; floatColor[1] = dl->color[1] * 255.0f; floatColor[2] = dl->color[2] * 255.0f; // build a list of triangles that need light numIndexes = 0; - for ( i = 0 ; i < tess.numIndexes ; i += 3 ) - { - int a, b, c; + for (i = 0; i < tess.numIndexes; i += 3) { + int a, b, c; a = tess.indexes[i]; - b = tess.indexes[i+1]; - c = tess.indexes[i+2]; - if ( clipBits[a] & clipBits[b] & clipBits[c] ) - { - continue; // not lighted + b = tess.indexes[i + 1]; + c = tess.indexes[i + 2]; + if (clipBits[a] & clipBits[b] & clipBits[c]) { + continue; // not lighted } // copy the vertex positions - VectorCopy(tess.xyz[a],posa); - VectorCopy(tess.xyz[b],posb); - VectorCopy(tess.xyz[c],posc); - - VectorSubtract( posa, posb,e1); - VectorSubtract( posc, posb,e2); - CrossProduct(e1,e2,normal); -// fac=DotProduct(normal,origin)-DotProduct(normal,posa); -// if (fac <= 0.0f || // backface -// rjr - removed for hacking if ( (!r_dlightBacks->integer && DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f) || // backface - if ( DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f || // backface - DotProduct(normal,normal) < 1E-8f) // junk triangle + VectorCopy(tess.xyz[a], posa); + VectorCopy(tess.xyz[b], posb); + VectorCopy(tess.xyz[c], posc); + + VectorSubtract(posa, posb, e1); + VectorSubtract(posc, posb, e2); + CrossProduct(e1, e2, normal); + // fac=DotProduct(normal,origin)-DotProduct(normal,posa); + // if (fac <= 0.0f || // backface + // rjr - removed for hacking if ( (!r_dlightBacks->integer && DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f) || // backface + if (DotProduct(normal, origin) - DotProduct(normal, posa) <= 0.0f || // backface + DotProduct(normal, normal) < 1E-8f) // junk triangle { continue; } VectorNormalize(normal); - fac=DotProduct(normal,origin)-DotProduct(normal,posa); - if (fac >= radius) // out of range + fac = DotProduct(normal, origin) - DotProduct(normal, posa); + if (fac >= radius) // out of range { continue; } - modulate = 1.0f-((fac*fac) / (radius*radius)); - fac = 0.5f/sqrtf(radius*radius - fac*fac); + modulate = 1.0f - ((fac * fac) / (radius * radius)); + fac = 0.5f / sqrtf(radius * radius - fac * fac); // save the verts - VectorCopy(posa,vertCoordsArray[numIndexes]); - VectorCopy(posb,vertCoordsArray[numIndexes+1]); - VectorCopy(posc,vertCoordsArray[numIndexes+2]); + VectorCopy(posa, vertCoordsArray[numIndexes]); + VectorCopy(posb, vertCoordsArray[numIndexes + 1]); + VectorCopy(posc, vertCoordsArray[numIndexes + 2]); // now we need e1 and e2 to be an orthonormal basis - if (DotProduct(e1,e1) > DotProduct(e2,e2)) - { + if (DotProduct(e1, e1) > DotProduct(e2, e2)) { VectorNormalize(e1); - CrossProduct(e1,normal,e2); - } - else - { + CrossProduct(e1, normal, e2); + } else { VectorNormalize(e2); - CrossProduct(normal,e2,e1); + CrossProduct(normal, e2, e1); } - VectorScale(e1,fac,e1); - VectorScale(e2,fac,e2); + VectorScale(e1, fac, e1); + VectorScale(e2, fac, e2); - VectorSubtract( posa, origin,dist); - texCoordsArray[numIndexes][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posa, origin, dist); + texCoordsArray[numIndexes][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes][1] = DotProduct(dist, e2) + 0.5f; - VectorSubtract( posb, origin,dist); - texCoordsArray[numIndexes+1][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes+1][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posb, origin, dist); + texCoordsArray[numIndexes + 1][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes + 1][1] = DotProduct(dist, e2) + 0.5f; - VectorSubtract( posc, origin,dist); - texCoordsArray[numIndexes+2][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes+2][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posc, origin, dist); + texCoordsArray[numIndexes + 2][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes + 2][1] = DotProduct(dist, e2) + 0.5f; - if ((texCoordsArray[numIndexes][0] < 0.0f && texCoordsArray[numIndexes+1][0] < 0.0f && texCoordsArray[numIndexes+2][0] < 0.0f) || - (texCoordsArray[numIndexes][0] > 1.0f && texCoordsArray[numIndexes+1][0] > 1.0f && texCoordsArray[numIndexes+2][0] > 1.0f) || - (texCoordsArray[numIndexes][1] < 0.0f && texCoordsArray[numIndexes+1][1] < 0.0f && texCoordsArray[numIndexes+2][1] < 0.0f) || - (texCoordsArray[numIndexes][1] > 1.0f && texCoordsArray[numIndexes+1][1] > 1.0f && texCoordsArray[numIndexes+2][1] > 1.0f) ) - { + if ((texCoordsArray[numIndexes][0] < 0.0f && texCoordsArray[numIndexes + 1][0] < 0.0f && texCoordsArray[numIndexes + 2][0] < 0.0f) || + (texCoordsArray[numIndexes][0] > 1.0f && texCoordsArray[numIndexes + 1][0] > 1.0f && texCoordsArray[numIndexes + 2][0] > 1.0f) || + (texCoordsArray[numIndexes][1] < 0.0f && texCoordsArray[numIndexes + 1][1] < 0.0f && texCoordsArray[numIndexes + 2][1] < 0.0f) || + (texCoordsArray[numIndexes][1] > 1.0f && texCoordsArray[numIndexes + 1][1] > 1.0f && texCoordsArray[numIndexes + 2][1] > 1.0f)) { continue; // didn't end up hitting this tri } @@ -832,12 +776,12 @@ static void ProjectDlightTexture2( void ) { oldTexCoordsArray[numIndexes+2][0]=tess.svars.texcoords[0][c][0]; oldTexCoordsArray[numIndexes+2][1]=tess.svars.texcoords[0][c][1]; */ - oldTexCoordsArray[numIndexes][0]=tess.texCoords[a][0][0]; - oldTexCoordsArray[numIndexes][1]=tess.texCoords[a][0][1]; - oldTexCoordsArray[numIndexes+1][0]=tess.texCoords[b][0][0]; - oldTexCoordsArray[numIndexes+1][1]=tess.texCoords[b][0][1]; - oldTexCoordsArray[numIndexes+2][0]=tess.texCoords[c][0][0]; - oldTexCoordsArray[numIndexes+2][1]=tess.texCoords[c][0][1]; + oldTexCoordsArray[numIndexes][0] = tess.texCoords[a][0][0]; + oldTexCoordsArray[numIndexes][1] = tess.texCoords[a][0][1]; + oldTexCoordsArray[numIndexes + 1][0] = tess.texCoords[b][0][0]; + oldTexCoordsArray[numIndexes + 1][1] = tess.texCoords[b][0][1]; + oldTexCoordsArray[numIndexes + 2][0] = tess.texCoords[c][0][0]; + oldTexCoordsArray[numIndexes + 2][1] = tess.texCoords[c][0][1]; colorTemp[0] = Q_ftol(floatColor[0] * modulate); colorTemp[1] = Q_ftol(floatColor[1] * modulate); @@ -850,124 +794,105 @@ static void ProjectDlightTexture2( void ) { colorArray[numIndexes + 2] = ba->ui; hitIndexes[numIndexes] = numIndexes; - hitIndexes[numIndexes+1] = numIndexes+1; - hitIndexes[numIndexes+2] = numIndexes+2; + hitIndexes[numIndexes + 1] = numIndexes + 1; + hitIndexes[numIndexes + 2] = numIndexes + 2; numIndexes += 3; - if (numIndexes>=SHADER_MAX_VERTEXES-3) - { + if (numIndexes >= SHADER_MAX_VERTEXES - 3) { break; // we are out of space, so we are done :) } } - if ( !numIndexes ) { + if (!numIndexes) { continue; } #ifndef JK2_MODE - //don't have fog enabled when we redraw with alpha test, or it will double over - //and screw the tri up -rww - if (r_drawfog->value == 2 && - tr.world && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't have fog enabled when we redraw with alpha test, or it will double over + // and screw the tri up -rww + if (r_drawfog->value == 2 && tr.world && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { fogging = qglIsEnabled(GL_FOG); - if (fogging) - { + if (fogging) { qglDisable(GL_FOG); } - } - else - { + } else { fogging = 0; } #endif - if (!needResetVerts) - { - needResetVerts=1; - if (qglUnlockArraysEXT) - { + if (!needResetVerts) { + needResetVerts = 1; + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } } - qglVertexPointer (3, GL_FLOAT, 16, vertCoordsArray); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, vertCoordsArray); // padded for SIMD dStage = NULL; - if (tess.shader && qglActiveTextureARB) - { + if (tess.shader && qglActiveTextureARB) { int i = 0; - while (i < tess.shader->numUnfoggedPasses) - { - const int blendBits = (GLS_SRCBLEND_BITS+GLS_DSTBLEND_BITS); - if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || - (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && - (tess.shader->stages[i].stateBits & blendBits) == 0 ) - { //only use non-lightmap opaque stages - dStage = &tess.shader->stages[i]; + while (i < tess.shader->numUnfoggedPasses) { + const int blendBits = (GLS_SRCBLEND_BITS + GLS_DSTBLEND_BITS); + if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && + tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || + (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && + tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && + (tess.shader->stages[i].stateBits & blendBits) == 0) { // only use non-lightmap opaque stages + dStage = &tess.shader->stages[i]; break; } i++; } } - if (dStage) - { - GL_SelectTexture( 0 ); + if (dStage) { + GL_SelectTexture(0); GL_State(0); - qglTexCoordPointer( 2, GL_FLOAT, 0, oldTexCoordsArray[0] ); - if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) - { - R_BindAnimatedImage( &dStage->bundle[0] ); - } - else - { - R_BindAnimatedImage( &dStage->bundle[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, oldTexCoordsArray[0]); + if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && + dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) { + R_BindAnimatedImage(&dStage->bundle[0]); + } else { + R_BindAnimatedImage(&dStage->bundle[1]); } - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); - GL_Bind( tr.dlightImage ); - GL_TexEnv( GL_MODULATE ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); + GL_Bind(tr.dlightImage); + GL_TexEnv(GL_MODULATE); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); // | GLS_ATEST_GT_0); - GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL);// | GLS_ATEST_GT_0); + R_DrawElements(numIndexes, hitIndexes); - R_DrawElements( numIndexes, hitIndexes ); - - qglDisable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); GL_SelectTexture(0); - } - else - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); + } else { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); - GL_Bind( tr.dlightImage ); + GL_Bind(tr.dlightImage); // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light // where they aren't rendered - //if ( dl->additive ) { + // if ( dl->additive ) { // GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); //} - //else - { - GL_State( GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); - } + // else + { GL_State(GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); } - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); } #ifndef JK2_MODE - if (fogging) - { + if (fogging) { qglEnable(GL_FOG); } #endif @@ -975,50 +900,48 @@ static void ProjectDlightTexture2( void ) { backEnd.pc.c_totalIndexes += numIndexes; backEnd.pc.c_dlightIndexes += numIndexes; } - if (needResetVerts) - { - qglVertexPointer (3, GL_FLOAT, 16, tess.xyz); // padded for SIMD - if (qglLockArraysEXT) - { + if (needResetVerts) { + qglVertexPointer(3, GL_FLOAT, 16, tess.xyz); // padded for SIMD + if (qglLockArraysEXT) { qglLockArraysEXT(0, tess.numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } } } -static void ProjectDlightTexture( void ) { - int i, l; - vec3_t origin; - float *texCoords; - byte *colors; - byte clipBits[SHADER_MAX_VERTEXES]; - float texCoordsArray[SHADER_MAX_VERTEXES][2]; - byte colorArray[SHADER_MAX_VERTEXES][4]; - glIndex_t hitIndexes[SHADER_MAX_INDEXES]; - int numIndexes; - float scale; - float radius; +static void ProjectDlightTexture(void) { + int i, l; + vec3_t origin; + float *texCoords; + byte *colors; + byte clipBits[SHADER_MAX_VERTEXES]; + float texCoordsArray[SHADER_MAX_VERTEXES][2]; + byte colorArray[SHADER_MAX_VERTEXES][4]; + glIndex_t hitIndexes[SHADER_MAX_INDEXES]; + int numIndexes; + float scale; + float radius; #ifndef JK2_MODE - int fogging; + int fogging; #endif - vec3_t floatColor; + vec3_t floatColor; shaderStage_t *dStage; - if ( !backEnd.refdef.num_dlights ) { + if (!backEnd.refdef.num_dlights) { return; } - for ( l = 0 ; l < backEnd.refdef.num_dlights ; l++ ) { - dlight_t *dl; + for (l = 0; l < backEnd.refdef.num_dlights; l++) { + dlight_t *dl; - if ( !( tess.dlightBits & ( 1 << l ) ) ) { - continue; // this surface definately doesn't have any of this light + if (!(tess.dlightBits & (1 << l))) { + continue; // this surface definately doesn't have any of this light } texCoords = texCoordsArray[0]; colors = colorArray[0]; dl = &backEnd.refdef.dlights[l]; - VectorCopy( dl->transformed, origin ); + VectorCopy(dl->transformed, origin); radius = dl->radius; scale = 1.0f / radius; @@ -1026,37 +949,29 @@ static void ProjectDlightTexture( void ) { floatColor[1] = dl->color[1] * 255.0f; floatColor[2] = dl->color[2] * 255.0f; - for ( i = 0 ; i < tess.numVertexes ; i++, texCoords += 2, colors += 4 ) { - vec3_t dist; - int clip; - float modulate; + for (i = 0; i < tess.numVertexes; i++, texCoords += 2, colors += 4) { + vec3_t dist; + int clip; + float modulate; backEnd.pc.c_dlightVertexes++; - VectorSubtract( origin, tess.xyz[i], dist ); + VectorSubtract(origin, tess.xyz[i], dist); int l = 1; int bestIndex = 0; float greatest = tess.normal[i][0]; - if (greatest < 0.0f) - { + if (greatest < 0.0f) { greatest = -greatest; } - if (VectorCompare(tess.normal[i], vec3_origin)) - { //damn you terrain! + if (VectorCompare(tess.normal[i], vec3_origin)) { // damn you terrain! bestIndex = 2; - } - else - { - while (l < 3) - { - if ((tess.normal[i][l] > greatest && tess.normal[i][l] > 0.0f) || - (tess.normal[i][l] < -greatest && tess.normal[i][l] < 0.0f)) - { + } else { + while (l < 3) { + if ((tess.normal[i][l] > greatest && tess.normal[i][l] > 0.0f) || (tess.normal[i][l] < -greatest && tess.normal[i][l] < 0.0f)) { greatest = tess.normal[i][l]; - if (greatest < 0.0f) - { + if (greatest < 0.0f) { greatest = -greatest; } bestIndex = l; @@ -1070,96 +985,63 @@ static void ProjectDlightTexture( void ) { const float maxGroundScale = 1.4f; const float lightScaleTolerance = 0.1f; - if (bestIndex == 2) - { - dUse = origin[2]-tess.xyz[i][2]; - if (dUse < 0.0f) - { + if (bestIndex == 2) { + dUse = origin[2] - tess.xyz[i][2]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxGroundScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxGroundScale) { dUse = maxGroundScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (VectorCompare(tess.normal[i], vec3_origin) || - tess.normal[i][0] > lightScaleTolerance || - tess.normal[i][0] < -lightScaleTolerance || - tess.normal[i][1] > lightScaleTolerance || - tess.normal[i][1] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (VectorCompare(tess.normal[i], vec3_origin) || tess.normal[i][0] > lightScaleTolerance || tess.normal[i][0] < -lightScaleTolerance || + tess.normal[i][1] > lightScaleTolerance || tess.normal[i][1] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[0] * scale; texCoords[1] = 0.5f + dist[1] * scale; - } - else if (bestIndex == 1) - { - dUse = origin[1]-tess.xyz[i][1]; - if (dUse < 0.0f) - { + } else if (bestIndex == 1) { + dUse = origin[1] - tess.xyz[i][1]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxScale) { dUse = maxScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (tess.normal[i][0] > lightScaleTolerance || - tess.normal[i][0] < -lightScaleTolerance || - tess.normal[i][2] > lightScaleTolerance || - tess.normal[i][2] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (tess.normal[i][0] > lightScaleTolerance || tess.normal[i][0] < -lightScaleTolerance || tess.normal[i][2] > lightScaleTolerance || + tess.normal[i][2] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[0] * scale; texCoords[1] = 0.5f + dist[2] * scale; - } - else - { - dUse = origin[0]-tess.xyz[i][0]; - if (dUse < 0.0f) - { + } else { + dUse = origin[0] - tess.xyz[i][0]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxScale) { dUse = maxScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (tess.normal[i][2] > lightScaleTolerance || - tess.normal[i][2] < -lightScaleTolerance || - tess.normal[i][1] > lightScaleTolerance || - tess.normal[i][1] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (tess.normal[i][2] > lightScaleTolerance || tess.normal[i][2] < -lightScaleTolerance || tess.normal[i][1] > lightScaleTolerance || + tess.normal[i][1] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[1] * scale; @@ -1167,26 +1049,26 @@ static void ProjectDlightTexture( void ) { } clip = 0; - if ( texCoords[0] < 0.0f ) { + if (texCoords[0] < 0.0f) { clip |= 1; - } else if ( texCoords[0] > 1.0f ) { + } else if (texCoords[0] > 1.0f) { clip |= 2; } - if ( texCoords[1] < 0.0f ) { + if (texCoords[1] < 0.0f) { clip |= 4; - } else if ( texCoords[1] > 1.0f ) { + } else if (texCoords[1] > 1.0f) { clip |= 8; } // modulate the strength based on the height and color - if ( dist[bestIndex] > radius ) { + if (dist[bestIndex] > radius) { clip |= 16; modulate = 0.0f; - } else if ( dist[bestIndex] < -radius ) { + } else if (dist[bestIndex] < -radius) { clip |= 32; modulate = 0.0f; } else { dist[bestIndex] = Q_fabs(dist[bestIndex]); - if ( dist[bestIndex] < radius * 0.5f ) { + if (dist[bestIndex] < radius * 0.5f) { modulate = 1.0f; } else { modulate = 2.0f * (radius - dist[bestIndex]) * scale; @@ -1201,119 +1083,103 @@ static void ProjectDlightTexture( void ) { } // build a list of triangles that need light numIndexes = 0; - for ( i = 0 ; i < tess.numIndexes ; i += 3 ) { - int a, b, c; + for (i = 0; i < tess.numIndexes; i += 3) { + int a, b, c; a = tess.indexes[i]; - b = tess.indexes[i+1]; - c = tess.indexes[i+2]; - if ( clipBits[a] & clipBits[b] & clipBits[c] ) { - continue; // not lighted + b = tess.indexes[i + 1]; + c = tess.indexes[i + 2]; + if (clipBits[a] & clipBits[b] & clipBits[c]) { + continue; // not lighted } hitIndexes[numIndexes] = a; - hitIndexes[numIndexes+1] = b; - hitIndexes[numIndexes+2] = c; + hitIndexes[numIndexes + 1] = b; + hitIndexes[numIndexes + 2] = c; numIndexes += 3; } - if ( !numIndexes ) { + if (!numIndexes) { continue; } #ifndef JK2_MODE - //don't have fog enabled when we redraw with alpha test, or it will double over - //and screw the tri up -rww - if (r_drawfog->value == 2 && - tr.world && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't have fog enabled when we redraw with alpha test, or it will double over + // and screw the tri up -rww + if (r_drawfog->value == 2 && tr.world && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { fogging = qglIsEnabled(GL_FOG); - if (fogging) - { + if (fogging) { qglDisable(GL_FOG); } - } - else - { + } else { fogging = 0; } #endif - dStage = NULL; - if (tess.shader && qglActiveTextureARB) - { + if (tess.shader && qglActiveTextureARB) { int i = 0; - while (i < tess.shader->numUnfoggedPasses) - { - const int blendBits = (GLS_SRCBLEND_BITS+GLS_DSTBLEND_BITS); - if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || - (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && - (tess.shader->stages[i].stateBits & blendBits) == 0 ) - { //only use non-lightmap opaque stages - dStage = &tess.shader->stages[i]; + while (i < tess.shader->numUnfoggedPasses) { + const int blendBits = (GLS_SRCBLEND_BITS + GLS_DSTBLEND_BITS); + if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && + tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || + (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && + tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && + (tess.shader->stages[i].stateBits & blendBits) == 0) { // only use non-lightmap opaque stages + dStage = &tess.shader->stages[i]; break; } i++; } } - if (dStage) - { - GL_SelectTexture( 0 ); + if (dStage) { + GL_SelectTexture(0); GL_State(0); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); - if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) - { - R_BindAnimatedImage( &dStage->bundle[0] ); - } - else - { - R_BindAnimatedImage( &dStage->bundle[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); + if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && + dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) { + R_BindAnimatedImage(&dStage->bundle[0]); + } else { + R_BindAnimatedImage(&dStage->bundle[1]); } - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); - GL_Bind( tr.dlightImage ); - GL_TexEnv( GL_MODULATE ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); + GL_Bind(tr.dlightImage); + GL_TexEnv(GL_MODULATE); - GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL);// | GLS_ATEST_GT_0); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); // | GLS_ATEST_GT_0); - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); - qglDisable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); GL_SelectTexture(0); - } - else - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); + } else { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); - GL_Bind( tr.dlightImage ); + GL_Bind(tr.dlightImage); // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light // where they aren't rendered - //if ( dl->additive ) { + // if ( dl->additive ) { // GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); //} - //else - { - GL_State( GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); - } + // else + { GL_State(GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); } - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); } #ifndef JK2_MODE - if (fogging) - { + if (fogging) { qglEnable(GL_FOG); } #endif @@ -1330,50 +1196,47 @@ RB_FogPass Blends a fog texture on top of everything else =================== */ -static void RB_FogPass( void ) { - fog_t *fog; - int i; +static void RB_FogPass(void) { + fog_t *fog; + int i; - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, tess.svars.colors); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); fog = tr.world->fogs + tess.fogNum; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; ba->i = fog->colorInt; } - RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[0] ); + RB_CalcFogTexCoords((float *)tess.svars.texcoords[0]); - GL_Bind( tr.fogImage ); + GL_Bind(tr.fogImage); - if ( tess.shader->fogPass == FP_EQUAL ) { - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL ); + if (tess.shader->fogPass == FP_EQUAL) { + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL); } else { - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); } - R_DrawElements( tess.numIndexes, tess.indexes ); + R_DrawElements(tess.numIndexes, tess.indexes); } - /* =============== ComputeColors =============== */ -static void ComputeColors( shaderStage_t *pStage, alphaGen_t forceAlphaGen, colorGen_t forceRGBGen ) -{ +static void ComputeColors(shaderStage_t *pStage, alphaGen_t forceAlphaGen, colorGen_t forceRGBGen) { int i; - if ( tess.shader != tr.projectionShadowShader && tess.shader != tr.shadowShader && - ( backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1|RF_DISINTEGRATE2))) - { - RB_CalcDisintegrateColors( (unsigned char *)tess.svars.colors, pStage->rgbGen ); + if (tess.shader != tr.projectionShadowShader && tess.shader != tr.shadowShader && + (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2))) { + RB_CalcDisintegrateColors((unsigned char *)tess.svars.colors, pStage->rgbGen); RB_CalcDisintegrateVertDeform(); // We've done some custom alpha and color stuff, so we can skip the rest. Let it do fog though @@ -1384,240 +1247,205 @@ static void ComputeColors( shaderStage_t *pStage, alphaGen_t forceAlphaGen, colo // // rgbGen // - if ( !forceRGBGen ) - { + if (!forceRGBGen) { forceRGBGen = pStage->rgbGen; } - if ( backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC ) // does not work for rotated models, technically, this should also be a CGEN type, but that would entail adding new shader commands....which is too much work for one thing + if (backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC) // does not work for rotated models, technically, this should also be a CGEN type, but that would + // entail adding new shader commands....which is too much work for one thing { - int i; - float *normal, dot; + int i; + float *normal, dot; unsigned char *color; - int numVertexes; + int numVertexes; normal = tess.normal[0]; color = tess.svars.colors[0]; numVertexes = tess.numVertexes; - for ( i = 0 ; i < numVertexes ; i++, normal += 4, color += 4) - { - dot = DotProduct( normal, backEnd.refdef.viewaxis[0] ); + for (i = 0; i < numVertexes; i++, normal += 4, color += 4) { + dot = DotProduct(normal, backEnd.refdef.viewaxis[0]); dot *= dot * dot * dot; - if ( dot < 0.2f ) // so low, so just clamp it + if (dot < 0.2f) // so low, so just clamp it { dot = 0.0f; } - color[0] = color[1] = color[2] = color[3] = Q_ftol( backEnd.currentEntity->e.shaderRGBA[0] * (1-dot) ); + color[0] = color[1] = color[2] = color[3] = Q_ftol(backEnd.currentEntity->e.shaderRGBA[0] * (1 - dot)); } forceRGBGen = CGEN_SKIP; forceAlphaGen = AGEN_SKIP; } - if ( !forceAlphaGen ) //set this up so we can override below + if (!forceAlphaGen) // set this up so we can override below { forceAlphaGen = pStage->alphaGen; } - switch ( forceRGBGen ) - { - case CGEN_SKIP: - break; - case CGEN_IDENTITY: - memset( tess.svars.colors, 0xff, tess.numVertexes * 4 ); - break; - default: - case CGEN_IDENTITY_LIGHTING: - memset( tess.svars.colors, tr.identityLightByte, tess.numVertexes * 4 ); - break; - case CGEN_LIGHTING_DIFFUSE: - RB_CalcDiffuseColor( ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_LIGHTING_DIFFUSE_ENTITY: - RB_CalcDiffuseEntityColor( ( unsigned char * ) tess.svars.colors ); + switch (forceRGBGen) { + case CGEN_SKIP: + break; + case CGEN_IDENTITY: + memset(tess.svars.colors, 0xff, tess.numVertexes * 4); + break; + default: + case CGEN_IDENTITY_LIGHTING: + memset(tess.svars.colors, tr.identityLightByte, tess.numVertexes * 4); + break; + case CGEN_LIGHTING_DIFFUSE: + RB_CalcDiffuseColor((unsigned char *)tess.svars.colors); + break; + case CGEN_LIGHTING_DIFFUSE_ENTITY: + RB_CalcDiffuseEntityColor((unsigned char *)tess.svars.colors); - if ( forceAlphaGen == AGEN_IDENTITY && - backEnd.currentEntity->e.shaderRGBA[3] == 0xff - ) - { - forceAlphaGen = AGEN_SKIP; //already got it in this set since it does all 4 components - } - break; - case CGEN_EXACT_VERTEX: - memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) ); - break; - case CGEN_CONST: - for ( i = 0; i < tess.numVertexes; i++ ) { - byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], - *baSource = (byteAlias_t *)&pStage->constantColor; - baDest->i = baSource->i; - } - break; - case CGEN_VERTEX: - if ( tr.identityLight == 1 ) - { - memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) ); - } - else - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = tess.vertexColors[i][0] * tr.identityLight; - tess.svars.colors[i][1] = tess.vertexColors[i][1] * tr.identityLight; - tess.svars.colors[i][2] = tess.vertexColors[i][2] * tr.identityLight; - tess.svars.colors[i][3] = tess.vertexColors[i][3]; - } + if (forceAlphaGen == AGEN_IDENTITY && backEnd.currentEntity->e.shaderRGBA[3] == 0xff) { + forceAlphaGen = AGEN_SKIP; // already got it in this set since it does all 4 components + } + break; + case CGEN_EXACT_VERTEX: + memcpy(tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof(tess.vertexColors[0])); + break; + case CGEN_CONST: + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], *baSource = (byteAlias_t *)&pStage->constantColor; + baDest->i = baSource->i; + } + break; + case CGEN_VERTEX: + if (tr.identityLight == 1) { + memcpy(tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof(tess.vertexColors[0])); + } else { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = tess.vertexColors[i][0] * tr.identityLight; + tess.svars.colors[i][1] = tess.vertexColors[i][1] * tr.identityLight; + tess.svars.colors[i][2] = tess.vertexColors[i][2] * tr.identityLight; + tess.svars.colors[i][3] = tess.vertexColors[i][3]; } - break; - case CGEN_ONE_MINUS_VERTEX: - if ( tr.identityLight == 1 ) - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = 255 - tess.vertexColors[i][0]; - tess.svars.colors[i][1] = 255 - tess.vertexColors[i][1]; - tess.svars.colors[i][2] = 255 - tess.vertexColors[i][2]; - } + } + break; + case CGEN_ONE_MINUS_VERTEX: + if (tr.identityLight == 1) { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = 255 - tess.vertexColors[i][0]; + tess.svars.colors[i][1] = 255 - tess.vertexColors[i][1]; + tess.svars.colors[i][2] = 255 - tess.vertexColors[i][2]; } - else - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = ( 255 - tess.vertexColors[i][0] ) * tr.identityLight; - tess.svars.colors[i][1] = ( 255 - tess.vertexColors[i][1] ) * tr.identityLight; - tess.svars.colors[i][2] = ( 255 - tess.vertexColors[i][2] ) * tr.identityLight; - } + } else { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = (255 - tess.vertexColors[i][0]) * tr.identityLight; + tess.svars.colors[i][1] = (255 - tess.vertexColors[i][1]) * tr.identityLight; + tess.svars.colors[i][2] = (255 - tess.vertexColors[i][2]) * tr.identityLight; } - break; - case CGEN_FOG: - { - const fog_t *fog = tr.world->fogs + tess.fogNum; + } + break; + case CGEN_FOG: { + const fog_t *fog = tr.world->fogs + tess.fogNum; - for ( i = 0; i < tess.numVertexes; i++ ) { - byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; - ba->i = fog->colorInt; - } - } - break; - case CGEN_WAVEFORM: - RB_CalcWaveColor( &pStage->rgbWave, ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_ENTITY: - RB_CalcColorFromEntity( ( unsigned char * ) tess.svars.colors ); - if ( forceAlphaGen == AGEN_IDENTITY && - backEnd.currentEntity->e.shaderRGBA[3] == 0xff - ) - { - forceAlphaGen = AGEN_SKIP; //already got it in this set since it does all 4 components - } + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; + ba->i = fog->colorInt; + } + } break; + case CGEN_WAVEFORM: + RB_CalcWaveColor(&pStage->rgbWave, (unsigned char *)tess.svars.colors); + break; + case CGEN_ENTITY: + RB_CalcColorFromEntity((unsigned char *)tess.svars.colors); + if (forceAlphaGen == AGEN_IDENTITY && backEnd.currentEntity->e.shaderRGBA[3] == 0xff) { + forceAlphaGen = AGEN_SKIP; // already got it in this set since it does all 4 components + } - break; - case CGEN_ONE_MINUS_ENTITY: - RB_CalcColorFromOneMinusEntity( ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_LIGHTMAPSTYLE: - for ( i = 0; i < tess.numVertexes; i++ ) - { - byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], - *baSource = (byteAlias_t *)&styleColors[pStage->lightmapStyle]; - baDest->ui = baSource->ui; - } - break; + break; + case CGEN_ONE_MINUS_ENTITY: + RB_CalcColorFromOneMinusEntity((unsigned char *)tess.svars.colors); + break; + case CGEN_LIGHTMAPSTYLE: + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], *baSource = (byteAlias_t *)&styleColors[pStage->lightmapStyle]; + baDest->ui = baSource->ui; } + break; + } // // alphaGen // - switch ( forceAlphaGen ) - { + switch (forceAlphaGen) { case AGEN_SKIP: break; case AGEN_IDENTITY: - if ( forceRGBGen != CGEN_IDENTITY && forceRGBGen != CGEN_LIGHTING_DIFFUSE ) { - if ( ( forceRGBGen == CGEN_VERTEX && tr.identityLight != 1 ) || - forceRGBGen != CGEN_VERTEX ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + if (forceRGBGen != CGEN_IDENTITY && forceRGBGen != CGEN_LIGHTING_DIFFUSE) { + if ((forceRGBGen == CGEN_VERTEX && tr.identityLight != 1) || forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = 0xff; } } } break; case AGEN_CONST: - if ( forceRGBGen != CGEN_CONST ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + if (forceRGBGen != CGEN_CONST) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = pStage->constantColor[3]; } } break; case AGEN_WAVEFORM: - RB_CalcWaveAlpha( &pStage->alphaWave, ( unsigned char * ) tess.svars.colors ); + RB_CalcWaveAlpha(&pStage->alphaWave, (unsigned char *)tess.svars.colors); break; case AGEN_LIGHTING_SPECULAR: - RB_CalcSpecularAlpha( ( unsigned char * ) tess.svars.colors ); + RB_CalcSpecularAlpha((unsigned char *)tess.svars.colors); break; case AGEN_ENTITY: - if ( forceRGBGen != CGEN_ENTITY ) { //already got it in the CGEN_entity since it does all 4 components - RB_CalcAlphaFromEntity( ( unsigned char * ) tess.svars.colors ); + if (forceRGBGen != CGEN_ENTITY) { // already got it in the CGEN_entity since it does all 4 components + RB_CalcAlphaFromEntity((unsigned char *)tess.svars.colors); } break; case AGEN_ONE_MINUS_ENTITY: - RB_CalcAlphaFromOneMinusEntity( ( unsigned char * ) tess.svars.colors ); + RB_CalcAlphaFromOneMinusEntity((unsigned char *)tess.svars.colors); break; case AGEN_VERTEX: - if ( forceRGBGen != CGEN_VERTEX ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + if (forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = tess.vertexColors[i][3]; } } - break; - case AGEN_ONE_MINUS_VERTEX: - for ( i = 0; i < tess.numVertexes; i++ ) - { + break; + case AGEN_ONE_MINUS_VERTEX: + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = 255 - tess.vertexColors[i][3]; } break; - case AGEN_PORTAL: - { - unsigned char alpha; + case AGEN_PORTAL: { + unsigned char alpha; - for ( i = 0; i < tess.numVertexes; i++ ) - { - float len; - vec3_t v; + for (i = 0; i < tess.numVertexes; i++) { + float len; + vec3_t v; - VectorSubtract( tess.xyz[i], backEnd.viewParms.ori.origin, v ); - len = VectorLength( v ); + VectorSubtract(tess.xyz[i], backEnd.viewParms.ori.origin, v); + len = VectorLength(v); - len /= tess.shader->portalRange; + len /= tess.shader->portalRange; - if ( len < 0 ) - { - alpha = 0; - } - else if ( len > 1 ) - { - alpha = 0xff; - } - else - { - alpha = len * 0xff; - } - - tess.svars.colors[i][3] = alpha; + if (len < 0) { + alpha = 0; + } else if (len > 1) { + alpha = 0xff; + } else { + alpha = len * 0xff; } + + tess.svars.colors[i][3] = alpha; } - break; + } break; case AGEN_BLEND: - if ( forceRGBGen != CGEN_VERTEX ) - { - for ( i = 0; i < tess.numVertexes; i++ ) - { + if (forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = tess.vertexAlphas[i][pStage->index]; } } @@ -1629,18 +1457,16 @@ static void ComputeColors( shaderStage_t *pStage, alphaGen_t forceAlphaGen, colo // // fog adjustment for colors to fade out as fog increases // - if ( tess.fogNum ) - { - switch ( pStage->adjustColorsForFog ) - { + if (tess.fogNum) { + switch (pStage->adjustColorsForFog) { case ACFF_MODULATE_RGB: - RB_CalcModulateColorsByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateColorsByFog((unsigned char *)tess.svars.colors); break; case ACFF_MODULATE_ALPHA: - RB_CalcModulateAlphasByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateAlphasByFog((unsigned char *)tess.svars.colors); break; case ACFF_MODULATE_RGBA: - RB_CalcModulateRGBAsByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateRGBAsByFog((unsigned char *)tess.svars.colors); break; case ACFF_NONE: break; @@ -1655,65 +1481,64 @@ static void ComputeColors( shaderStage_t *pStage, alphaGen_t forceAlphaGen, colo ComputeTexCoords =============== */ -static void ComputeTexCoords( shaderStage_t *pStage ) { - int i; +static void ComputeTexCoords(shaderStage_t *pStage) { + int i; int b; - for ( b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) { + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { int tm; // // generate the texture coordinates // - switch ( pStage->bundle[b].tcGen ) - { + switch (pStage->bundle[b].tcGen) { case TCGEN_IDENTITY: - memset( tess.svars.texcoords[b], 0, sizeof( float ) * 2 * tess.numVertexes ); + memset(tess.svars.texcoords[b], 0, sizeof(float) * 2 * tess.numVertexes); break; case TCGEN_TEXTURE: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][0][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][0][1]; } break; case TCGEN_LIGHTMAP: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][1][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][1][1]; } break; case TCGEN_LIGHTMAP1: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][2][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][2][1]; } break; case TCGEN_LIGHTMAP2: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][3][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][3][1]; } break; case TCGEN_LIGHTMAP3: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][4][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][4][1]; } break; case TCGEN_VECTOR: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - tess.svars.texcoords[b][i][0] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[0] ); - tess.svars.texcoords[b][i][1] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[1] ); + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.texcoords[b][i][0] = DotProduct(tess.xyz[i], pStage->bundle[b].tcGenVectors[0]); + tess.svars.texcoords[b][i][1] = DotProduct(tess.xyz[i], pStage->bundle[b].tcGenVectors[1]); } break; case TCGEN_FOG: - RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[b] ); + RB_CalcFogTexCoords((float *)tess.svars.texcoords[b]); break; case TCGEN_ENVIRONMENT_MAPPED: - if ( r_environmentMapping->integer ) - RB_CalcEnvironmentTexCoords( (float *)tess.svars.texcoords[b] ); + if (r_environmentMapping->integer) + RB_CalcEnvironmentTexCoords((float *)tess.svars.texcoords[b]); else - memset( tess.svars.texcoords[b], 0, sizeof( float ) * 2 * tess.numVertexes ); + memset(tess.svars.texcoords[b], 0, sizeof(float) * 2 * tess.numVertexes); break; case TCGEN_BAD: return; @@ -1722,64 +1547,57 @@ static void ComputeTexCoords( shaderStage_t *pStage ) { // // alter texture coordinates // - for ( tm = 0; tm < pStage->bundle[b].numTexMods ; tm++ ) { - switch ( pStage->bundle[b].texMods[tm].type ) - { + for (tm = 0; tm < pStage->bundle[b].numTexMods; tm++) { + switch (pStage->bundle[b].texMods[tm].type) { case TMOD_NONE: - tm = TR_MAX_TEXMODS; // break out of for loop + tm = TR_MAX_TEXMODS; // break out of for loop break; case TMOD_TURBULENT: - RB_CalcTurbulentTexCoords( &pStage->bundle[b].texMods[tm].wave, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcTurbulentTexCoords(&pStage->bundle[b].texMods[tm].wave, (float *)tess.svars.texcoords[b]); break; case TMOD_ENTITY_TRANSLATE: - RB_CalcScrollTexCoords( backEnd.currentEntity->e.shaderTexCoord, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScrollTexCoords(backEnd.currentEntity->e.shaderTexCoord, (float *)tess.svars.texcoords[b]); break; case TMOD_SCROLL: - RB_CalcScrollTexCoords( pStage->bundle[b].texMods[tm].translate, //union scroll into translate - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScrollTexCoords(pStage->bundle[b].texMods[tm].translate, // union scroll into translate + (float *)tess.svars.texcoords[b]); break; case TMOD_SCALE: - RB_CalcScaleTexCoords( pStage->bundle[b].texMods[tm].translate, //union scroll into translate - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScaleTexCoords(pStage->bundle[b].texMods[tm].translate, // union scroll into translate + (float *)tess.svars.texcoords[b]); break; case TMOD_STRETCH: - RB_CalcStretchTexCoords( &pStage->bundle[b].texMods[tm].wave, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcStretchTexCoords(&pStage->bundle[b].texMods[tm].wave, (float *)tess.svars.texcoords[b]); break; case TMOD_TRANSFORM: - RB_CalcTransformTexCoords( &pStage->bundle[b].texMods[tm], - ( float * ) tess.svars.texcoords[b] ); + RB_CalcTransformTexCoords(&pStage->bundle[b].texMods[tm], (float *)tess.svars.texcoords[b]); break; case TMOD_ROTATE: - RB_CalcRotateTexCoords( pStage->bundle[b].texMods[tm].translate[0], //union rotateSpeed into translate[0] - ( float * ) tess.svars.texcoords[b] ); + RB_CalcRotateTexCoords(pStage->bundle[b].texMods[tm].translate[0], // union rotateSpeed into translate[0] + (float *)tess.svars.texcoords[b]); break; default: - Com_Error( ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'\n", pStage->bundle[b].texMods[tm].type, tess.shader->name ); + Com_Error(ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'\n", pStage->bundle[b].texMods[tm].type, tess.shader->name); break; } } } } -void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) -{ - int i; +void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) { + int i; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = TR_ForceEntAlpha; } } @@ -1788,53 +1606,43 @@ void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) ** RB_IterateStagesGeneric */ #ifndef JK2_MODE -static vec4_t GLFogOverrideColors[GLFOGOVERRIDE_MAX] = -{ - { 0.0, 0.0, 0.0, 1.0 }, // GLFOGOVERRIDE_NONE - { 0.0, 0.0, 0.0, 1.0 }, // GLFOGOVERRIDE_BLACK - { 1.0, 1.0, 1.0, 1.0 } // GLFOGOVERRIDE_WHITE +static vec4_t GLFogOverrideColors[GLFOGOVERRIDE_MAX] = { + {0.0, 0.0, 0.0, 1.0}, // GLFOGOVERRIDE_NONE + {0.0, 0.0, 0.0, 1.0}, // GLFOGOVERRIDE_BLACK + {1.0, 1.0, 1.0, 1.0} // GLFOGOVERRIDE_WHITE }; -static const float logtestExp2 = (sqrt( -log( 1.0 / 255.0 ) )); +static const float logtestExp2 = (sqrt(-log(1.0 / 255.0))); #endif -extern bool tr_stencilled; //tr_backend.cpp -static void RB_IterateStagesGeneric( shaderCommands_t *input ) -{ +extern bool tr_stencilled; // tr_backend.cpp +static void RB_IterateStagesGeneric(shaderCommands_t *input) { int stage; #ifndef JK2_MODE - bool UseGLFog = false; - bool FogColorChange = false; - fog_t *fog = NULL; + bool UseGLFog = false; + bool FogColorChange = false; + fog_t *fog = NULL; - if (tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs) - && r_drawfog->value == 2) - { // only gl fog global fog and the "special fog" + if (tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs) && + r_drawfog->value == 2) { // only gl fog global fog and the "special fog" fog = tr.world->fogs + tess.fogNum; - if (tr.rangedFog) - { //ranged fog, used for sniper scope + if (tr.rangedFog) { // ranged fog, used for sniper scope float fStart = fog->parms.depthForOpaque; float fEnd = tr.distanceCull; - if (tr.rangedFog < 0.0f) - { //special designer override + if (tr.rangedFog < 0.0f) { // special designer override fStart = -tr.rangedFog; fEnd = fog->parms.depthForOpaque; - if (fStart >= fEnd) - { - fStart = fEnd-1.0f; + if (fStart >= fEnd) { + fStart = fEnd - 1.0f; } - } - else - { - //the greater tr.rangedFog is, the more fog we will get between the view point and cull distance - if ((tr.distanceCull-fStart) < tr.rangedFog) - { //assure a minimum range between fog beginning and cutoff distance - fStart = tr.distanceCull-tr.rangedFog; + } else { + // the greater tr.rangedFog is, the more fog we will get between the view point and cull distance + if ((tr.distanceCull - fStart) < tr.rangedFog) { // assure a minimum range between fog beginning and cutoff distance + fStart = tr.distanceCull - tr.rangedFog; - if (fStart < 16.0f) - { + if (fStart < 16.0f) { fStart = 16.0f; } } @@ -1843,20 +1651,15 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) qglFogi(GL_FOG_MODE, GL_LINEAR); qglFogf(GL_FOG_START, fStart); qglFogf(GL_FOG_END, fEnd); - } - else - { + } else { qglFogi(GL_FOG_MODE, GL_EXP2); qglFogf(GL_FOG_DENSITY, logtestExp2 / fog->parms.depthForOpaque); } - if ( g_bRenderGlowingObjects ) - { - const float fogColor[3] = { 0.0f, 0.0f, 0.0f }; - qglFogfv(GL_FOG_COLOR, fogColor ); - } - else - { + if (g_bRenderGlowingObjects) { + const float fogColor[3] = {0.0f, 0.0f, 0.0f}; + qglFogfv(GL_FOG_COLOR, fogColor); + } else { qglFogfv(GL_FOG_COLOR, fog->parms.color); } @@ -1865,103 +1668,82 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) } #endif - for ( stage = 0; stage < input->shader->numUnfoggedPasses; stage++ ) - { + for (stage = 0; stage < input->shader->numUnfoggedPasses; stage++) { shaderStage_t *pStage = &tess.xstages[stage]; - if ( !pStage->active ) - { + if (!pStage->active) { break; } // Reject this stage if it's not a glow stage but we are doing a glow pass. - if ( g_bRenderGlowingObjects && !pStage->glow ) - { + if (g_bRenderGlowingObjects && !pStage->glow) { continue; } - int stateBits = pStage->stateBits; - alphaGen_t forceAlphaGen = (alphaGen_t)0; - colorGen_t forceRGBGen = (colorGen_t)0; + int stateBits = pStage->stateBits; + alphaGen_t forceAlphaGen = (alphaGen_t)0; + colorGen_t forceRGBGen = (colorGen_t)0; // allow skipping out to show just lightmaps during development - if ( stage && r_lightmap->integer) - { - if ( !( pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap || pStage->bundle[0].vertexLightmap ) ) - { - continue; // need to keep going in case the LM is in a later stage - } - else - { - stateBits = (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_ONE); //we want to replace the prior stages with this LM, not blend + if (stage && r_lightmap->integer) { + if (!(pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap || pStage->bundle[0].vertexLightmap)) { + continue; // need to keep going in case the LM is in a later stage + } else { + stateBits = (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_ONE); // we want to replace the prior stages with this LM, not blend } } - if ( backEnd.currentEntity ) - { - if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1 ) - { - // we want to be able to rip a hole in the thing being disintegrated, and by doing the depth-testing it avoids some kinds of artefacts, but will probably introduce others? + if (backEnd.currentEntity) { + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1) { + // we want to be able to rip a hole in the thing being disintegrated, and by doing the depth-testing it avoids some kinds of artefacts, but will + // probably introduce others? // NOTE: adjusting the alphaFunc seems to help a bit stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHMASK_TRUE | GLS_ATEST_GE_C0; } - if ( backEnd.currentEntity->e.renderfx & RF_ALPHA_FADE ) - { - if ( backEnd.currentEntity->e.shaderRGBA[3] < 255 ) - { + if (backEnd.currentEntity->e.renderfx & RF_ALPHA_FADE) { + if (backEnd.currentEntity->e.shaderRGBA[3] < 255) { stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; forceAlphaGen = AGEN_ENTITY; } } - if ( backEnd.currentEntity->e.renderfx & RF_RGB_TINT ) - {//want to use RGBGen from ent + if (backEnd.currentEntity->e.renderfx & RF_RGB_TINT) { // want to use RGBGen from ent forceRGBGen = CGEN_ENTITY; } } - if (pStage->ss && pStage->ss->surfaceSpriteType) - { + if (pStage->ss && pStage->ss->surfaceSpriteType) { // We check for surfacesprites AFTER drawing everything else continue; } #ifndef JK2_MODE - if (UseGLFog) - { - if (pStage->mGLFogColorOverride) - { + if (UseGLFog) { + if (pStage->mGLFogColorOverride) { qglFogfv(GL_FOG_COLOR, GLFogOverrideColors[pStage->mGLFogColorOverride]); FogColorChange = true; - } - else if (FogColorChange && fog) - { + } else if (FogColorChange && fog) { FogColorChange = false; qglFogfv(GL_FOG_COLOR, fog->parms.color); } } #endif - if (!input->fading) - { //this means ignore this, while we do a fade-out - ComputeColors( pStage, forceAlphaGen, forceRGBGen ); + if (!input->fading) { // this means ignore this, while we do a fade-out + ComputeColors(pStage, forceAlphaGen, forceRGBGen); } - ComputeTexCoords( pStage ); + ComputeTexCoords(pStage); - if ( !setArraysOnce ) - { - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, input->svars.colors ); + if (!setArraysOnce) { + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, input->svars.colors); } - if (pStage->bundle[0].isLightmap && r_debugStyle->integer >= 0) - { - if (pStage->lightmapStyle != r_debugStyle->integer) - { - if (pStage->lightmapStyle == 0) - { - GL_State( GLS_DSTBLEND_ZERO | GLS_SRCBLEND_ZERO ); - R_DrawElements( input->numIndexes, input->indexes ); + if (pStage->bundle[0].isLightmap && r_debugStyle->integer >= 0) { + if (pStage->lightmapStyle != r_debugStyle->integer) { + if (pStage->lightmapStyle == 0) { + GL_State(GLS_DSTBLEND_ZERO | GLS_SRCBLEND_ZERO); + R_DrawElements(input->numIndexes, input->indexes); } continue; } @@ -1970,39 +1752,29 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) // // do multitexture // - if ( pStage->bundle[1].image != 0 ) - { - DrawMultitextured( input, stage ); - } - else - { + if (pStage->bundle[1].image != 0) { + DrawMultitextured(input, stage); + } else { static bool lStencilled = false; - if ( !setArraysOnce ) - { - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] ); + if (!setArraysOnce) { + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[0]); } // // set state // - if ( (tess.shader == tr.distortionShader) || - (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_DISTORTION)) ) - { //special distortion effect -rww - //tr.screenImage should have been set for this specific entity before we got in here. - GL_Bind( tr.screenImage ); + if ((tess.shader == tr.distortionShader) || + (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_DISTORTION))) { // special distortion effect -rww + // tr.screenImage should have been set for this specific entity before we got in here. + GL_Bind(tr.screenImage); GL_Cull(CT_TWO_SIDED); - } - else if ( pStage->bundle[0].vertexLightmap && ( r_vertexLight->integer ) && r_lightmap->integer ) - { - GL_Bind( tr.whiteImage ); - } - else - R_BindAnimatedImage( &pStage->bundle[0] ); + } else if (pStage->bundle[0].vertexLightmap && (r_vertexLight->integer) && r_lightmap->integer) { + GL_Bind(tr.whiteImage); + } else + R_BindAnimatedImage(&pStage->bundle[0]); - if (tess.shader == tr.distortionShader && - glConfig.stencilBits >= 4) - { //draw it to the stencil buffer! + if (tess.shader == tr.distortionShader && glConfig.stencilBits >= 4) { // draw it to the stencil buffer! tr_stencilled = true; lStencilled = true; qglEnable(GL_STENCIL_TEST); @@ -2010,26 +1782,21 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - //don't depthmask, don't blend.. don't do anything + // don't depthmask, don't blend.. don't do anything GL_State(0); - } - else if (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA)) - { - ForceAlpha((unsigned char *) tess.svars.colors, backEnd.currentEntity->e.shaderRGBA[3]); + } else if (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA)) { + ForceAlpha((unsigned char *)tess.svars.colors, backEnd.currentEntity->e.shaderRGBA[3]); GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - } - else - { - GL_State( stateBits ); + } else { + GL_State(stateBits); } // // draw // - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); - if (lStencilled) - { //re-enable the color buffer, disable stencil test + if (lStencilled) { // re-enable the color buffer, disable stencil test lStencilled = false; qglDisable(GL_STENCIL_TEST); qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); @@ -2037,8 +1804,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) } } #ifndef JK2_MODE - if (FogColorChange) - { + if (FogColorChange) { qglFogfv(GL_FOG_COLOR, fog->parms.color); } #endif @@ -2047,8 +1813,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) /* ** RB_StageIteratorGeneric */ -void RB_StageIteratorGeneric( void ) -{ +void RB_StageIteratorGeneric(void) { shaderCommands_t *input; int stage; @@ -2059,23 +1824,21 @@ void RB_StageIteratorGeneric( void ) // // log this call // - if ( r_logFile->integer ) - { + if (r_logFile->integer) { // don't just call LogComment, or we will get // a call to va() every frame! - GLimp_LogComment( va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name) ); + GLimp_LogComment(va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name)); } // // set face culling appropriately // - GL_Cull( input->shader->cullType ); + GL_Cull(input->shader->cullType); // set polygon offset if necessary - if ( input->shader->polygonOffset ) - { - qglEnable( GL_POLYGON_OFFSET_FILL ); - qglPolygonOffset( r_offsetFactor->value, r_offsetUnits->value ); + if (input->shader->polygonOffset) { + qglEnable(GL_POLYGON_OFFSET_FILL); + qglPolygonOffset(r_offsetFactor->value, r_offsetUnits->value); } // @@ -2084,59 +1847,50 @@ void RB_StageIteratorGeneric( void ) // to avoid compiling those arrays since they will change // during multipass rendering // - if ( tess.numPasses > 1 || input->shader->multitextureEnv ) - { + if (tess.numPasses > 1 || input->shader->multitextureEnv) { setArraysOnce = qfalse; - qglDisableClientState (GL_COLOR_ARRAY); - qglDisableClientState (GL_TEXTURE_COORD_ARRAY); - } - else - { + qglDisableClientState(GL_COLOR_ARRAY); + qglDisableClientState(GL_TEXTURE_COORD_ARRAY); + } else { setArraysOnce = qtrue; - qglEnableClientState( GL_COLOR_ARRAY); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, tess.svars.colors); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); } // // lock XYZ // - qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, input->xyz); // padded for SIMD - if (qglLockArraysEXT) - { + if (qglLockArraysEXT) { qglLockArraysEXT(0, input->numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } // // enable color and texcoord arrays after the lock if necessary // - if ( !setArraysOnce ) - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglEnableClientState( GL_COLOR_ARRAY ); + if (!setArraysOnce) { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglEnableClientState(GL_COLOR_ARRAY); } // // call shader function // - RB_IterateStagesGeneric( input ); + RB_IterateStagesGeneric(input); // // now do any dynamic lighting needed // - if ( tess.dlightBits && tess.shader->sort <= SS_OPAQUE - && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY) ) ) { - if (r_dlightStyle->integer>0) - { + if (tess.dlightBits && tess.shader->sort <= SS_OPAQUE && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY))) { + if (r_dlightStyle->integer > 0) { ProjectDlightTexture2(); - } - else - { + } else { ProjectDlightTexture(); } } @@ -2156,48 +1910,39 @@ void RB_StageIteratorGeneric( void ) // // unlock arrays // - if (qglUnlockArraysEXT) - { + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } // // reset polygon offset // - if ( input->shader->polygonOffset ) - { - qglDisable( GL_POLYGON_OFFSET_FILL ); + if (input->shader->polygonOffset) { + qglDisable(GL_POLYGON_OFFSET_FILL); } // Now check for surfacesprites. - if (r_surfaceSprites->integer) - { - for ( stage = 1; stage < tess.shader->numUnfoggedPasses; stage++ ) - { - if (tess.xstages[stage].ss && tess.xstages[stage].ss->surfaceSpriteType) - { // Draw the surfacesprite - RB_DrawSurfaceSprites( &tess.xstages[stage], input); + if (r_surfaceSprites->integer) { + for (stage = 1; stage < tess.shader->numUnfoggedPasses; stage++) { + if (tess.xstages[stage].ss && tess.xstages[stage].ss->surfaceSpriteType) { // Draw the surfacesprite + RB_DrawSurfaceSprites(&tess.xstages[stage], input); } } } #ifndef JK2_MODE - //don't disable the hardware fog til after we do surface sprites - if (r_drawfog->value == 2 && - tess.fogNum && tess.shader->fogPass && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't disable the hardware fog til after we do surface sprites + if (r_drawfog->value == 2 && tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { qglDisable(GL_FOG); } #endif } - /* ** RB_EndSurface */ -void RB_EndSurface( void ) { +void RB_EndSurface(void) { shaderCommands_t *input; input = &tess; @@ -2206,40 +1951,34 @@ void RB_EndSurface( void ) { return; } - if (input->indexes[SHADER_MAX_INDEXES-1] != 0) { - Com_Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); + if (input->indexes[SHADER_MAX_INDEXES - 1] != 0) { + Com_Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); } - if (input->xyz[SHADER_MAX_VERTEXES-1][0] != 0) { - Com_Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); + if (input->xyz[SHADER_MAX_VERTEXES - 1][0] != 0) { + Com_Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); } - if ( tess.shader == tr.shadowShader ) { + if (tess.shader == tr.shadowShader) { RB_ShadowTessEnd(); return; } // for debugging of sort order issues, stop rendering after a given sort value - if ( r_debugSort->integer && r_debugSort->integer < tess.shader->sort ) { + if (r_debugSort->integer && r_debugSort->integer < tess.shader->sort) { return; } - if ( skyboxportal ) - { + if (skyboxportal) { // world - if(!(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) - { - if(tess.currentStageIteratorFunc == RB_StageIteratorSky) - { // don't process these tris at all + if (!(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) { + if (tess.currentStageIteratorFunc == RB_StageIteratorSky) { // don't process these tris at all return; } } // portal sky - else - { - if(!drawskyboxportal) - { - if( !(tess.currentStageIteratorFunc == RB_StageIteratorSky)) - { // /only/ process sky tris + else { + if (!drawskyboxportal) { + if (!(tess.currentStageIteratorFunc == RB_StageIteratorSky)) { // /only/ process sky tris return; } } @@ -2249,8 +1988,7 @@ void RB_EndSurface( void ) { // // update performance counters // - if (!backEnd.projection2D) - { + if (!backEnd.projection2D) { backEnd.pc.c_shaders++; backEnd.pc.c_vertexes += tess.numVertexes; backEnd.pc.c_indexes += tess.numIndexes; @@ -2260,7 +1998,7 @@ void RB_EndSurface( void ) { #else if (tess.fogNum && tess.shader->fogPass && r_drawfog->value == 1) #endif - { // Fogging adds an additional pass + { // Fogging adds an additional pass backEnd.pc.c_totalIndexes += tess.numIndexes; } } @@ -2273,18 +2011,16 @@ void RB_EndSurface( void ) { // // draw debugging stuff // - if ( r_showtris->integer ) - { - DrawTris (input); + if (r_showtris->integer) { + DrawTris(input); } - if ( r_shownormals->integer ) { - DrawNormals (input); + if (r_shownormals->integer) { + DrawNormals(input); } // clear shader so we can tell we don't have any unclosed surfaces tess.numIndexes = 0; - GLimp_LogComment( "----------\n" ); + GLimp_LogComment("----------\n"); } - diff --git a/code/rd-vanilla/tr_shade_calc.cpp b/code/rd-vanilla/tr_shade_calc.cpp index 5df2dbef44..b98a1534b8 100644 --- a/code/rd-vanilla/tr_shade_calc.cpp +++ b/code/rd-vanilla/tr_shade_calc.cpp @@ -27,12 +27,11 @@ along with this program; if not, see . #include "tr_local.h" #include "../rd-common/tr_common.h" -#define WAVEVALUE( table, base, amplitude, phase, freq ) ((base) + table[ Q_ftol( ( ( (phase) + backEnd.refdef.floatTime * (freq) ) * FUNCTABLE_SIZE ) ) & FUNCTABLE_MASK ] * (amplitude)) +#define WAVEVALUE(table, base, amplitude, phase, freq) \ + ((base) + table[Q_ftol((((phase) + backEnd.refdef.floatTime * (freq)) * FUNCTABLE_SIZE)) & FUNCTABLE_MASK] * (amplitude)) -static float *TableForFunc( genFunc_t func ) -{ - switch ( func ) - { +static float *TableForFunc(genFunc_t func) { + switch (func) { case GF_SIN: return tr.sinTable; case GF_TRIANGLE: @@ -48,7 +47,7 @@ static float *TableForFunc( genFunc_t func ) break; } - Com_Error( ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'\n", func, tess.shader->name ); + Com_Error(ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'\n", func, tess.shader->name); return NULL; } @@ -57,34 +56,30 @@ static float *TableForFunc( genFunc_t func ) ** ** Evaluates a given waveForm_t, referencing backEnd.refdef.time directly */ -static float EvalWaveForm( const waveForm_t *wf ) -{ - float *table; +static float EvalWaveForm(const waveForm_t *wf) { + float *table; - if ( wf->func == GF_NOISE ) { - return ( wf->base + R_NoiseGet4f( 0, 0, 0, ( backEnd.refdef.floatTime + wf->phase ) * wf->frequency ) * wf->amplitude ); + if (wf->func == GF_NOISE) { + return (wf->base + R_NoiseGet4f(0, 0, 0, (backEnd.refdef.floatTime + wf->phase) * wf->frequency) * wf->amplitude); } else if (wf->func == GF_RAND) { - if( GetNoiseTime( backEnd.refdef.time + wf->phase ) <= wf->frequency ) { + if (GetNoiseTime(backEnd.refdef.time + wf->phase) <= wf->frequency) { return (wf->base + wf->amplitude); } else { return wf->base; } } - table = TableForFunc( wf->func ); - return WAVEVALUE( table, wf->base, wf->amplitude, wf->phase, wf->frequency ); + table = TableForFunc(wf->func); + return WAVEVALUE(table, wf->base, wf->amplitude, wf->phase, wf->frequency); } -static float EvalWaveFormClamped( const waveForm_t *wf ) -{ - float glow = EvalWaveForm( wf ); +static float EvalWaveFormClamped(const waveForm_t *wf) { + float glow = EvalWaveForm(wf); - if ( glow < 0 ) - { + if (glow < 0) { return 0; } - if ( glow > 1 ) - { + if (glow > 1) { return 1; } @@ -94,12 +89,11 @@ static float EvalWaveFormClamped( const waveForm_t *wf ) /* ** RB_CalcStretchTexCoords */ -void RB_CalcStretchTexCoords( const waveForm_t *wf, float *st ) -{ +void RB_CalcStretchTexCoords(const waveForm_t *wf, float *st) { float p; texModInfo_t tmi; - p = 1.0f / EvalWaveForm( wf ); + p = 1.0f / EvalWaveForm(wf); tmi.matrix[0][0] = p; tmi.matrix[1][0] = 0; @@ -109,7 +103,7 @@ void RB_CalcStretchTexCoords( const waveForm_t *wf, float *st ) tmi.matrix[1][1] = p; tmi.translate[1] = 0.5f - 0.5f * p; - RB_CalcTransformTexCoords( &tmi, st ); + RB_CalcTransformTexCoords(&tmi, st); } /* @@ -126,42 +120,33 @@ RB_CalcDeformVertexes ======================== */ -void RB_CalcDeformVertexes( deformStage_t *ds ) -{ +void RB_CalcDeformVertexes(deformStage_t *ds) { int i; - vec3_t offset; - float scale; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float *table; + vec3_t offset; + float scale; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float *table; - if ( ds->deformationWave.frequency == 0 ) - { - scale = EvalWaveForm( &ds->deformationWave ); + if (ds->deformationWave.frequency == 0) { + scale = EvalWaveForm(&ds->deformationWave); - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - VectorScale( normal, scale, offset ); + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + VectorScale(normal, scale, offset); xyz[0] += offset[0]; xyz[1] += offset[1]; xyz[2] += offset[2]; } - } - else - { - table = TableForFunc( ds->deformationWave.func ); + } else { + table = TableForFunc(ds->deformationWave.func); - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - float off = ( xyz[0] + xyz[1] + xyz[2] ) * ds->deformationSpread; + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + float off = (xyz[0] + xyz[1] + xyz[2]) * ds->deformationSpread; - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase + off, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase + off, ds->deformationWave.frequency); - VectorScale( normal, scale, offset ); + VectorScale(normal, scale, offset); xyz[0] += offset[0]; xyz[1] += offset[1]; @@ -177,29 +162,26 @@ RB_CalcDeformNormals Wiggle the normals for wavy environment mapping ========================= */ -void RB_CalcDeformNormals( deformStage_t *ds ) { +void RB_CalcDeformNormals(deformStage_t *ds) { int i; - float scale; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; + float scale; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) { + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { scale = 0.98f; - scale = R_NoiseGet4f( xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - backEnd.refdef.floatTime * ds->deformationWave.frequency ); - normal[ 0 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, backEnd.refdef.floatTime * ds->deformationWave.frequency); + normal[0] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - backEnd.refdef.floatTime * ds->deformationWave.frequency ); - normal[ 1 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, backEnd.refdef.floatTime * ds->deformationWave.frequency); + normal[1] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - backEnd.refdef.floatTime * ds->deformationWave.frequency ); - normal[ 2 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, backEnd.refdef.floatTime * ds->deformationWave.frequency); + normal[2] += ds->deformationWave.amplitude * scale; - VectorNormalizeFast( normal ); + VectorNormalizeFast(normal); } } @@ -209,38 +191,32 @@ RB_CalcBulgeVertexes ======================== */ -void RB_CalcBulgeVertexes( deformStage_t *ds ) -{ - int i; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float scale; - - if ( ds->bulgeSpeed == 0.0f && ds->bulgeWidth == 0.0f ) - { +void RB_CalcBulgeVertexes(deformStage_t *ds) { + int i; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float scale; + + if (ds->bulgeSpeed == 0.0f && ds->bulgeWidth == 0.0f) { // We don't have a speed and width, so just use height to expand uniformly - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { xyz[0] += normal[0] * ds->bulgeHeight; xyz[1] += normal[1] * ds->bulgeHeight; xyz[2] += normal[2] * ds->bulgeHeight; } - } - else - { + } else { // I guess do some extra dumb stuff..the fact that it uses ST seems bad though because skin pages may be set up in certain ways that can cause // very noticeable seams on sufaces ( like on the huge ion_cannon ). - const float *st = ( const float * ) tess.texCoords[0]; - float now; - int off; + const float *st = (const float *)tess.texCoords[0]; + float now; + int off; now = backEnd.refdef.time * ds->bulgeSpeed * 0.001f; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, st += 2 * NUM_TEX_COORDS, normal += 4 ) - { - off = (float)( FUNCTABLE_SIZE / (M_PI*2) ) * ( st[0] * ds->bulgeWidth + now ); + for (i = 0; i < tess.numVertexes; i++, xyz += 4, st += 2 * NUM_TEX_COORDS, normal += 4) { + off = (float)(FUNCTABLE_SIZE / (M_PI * 2)) * (st[0] * ds->bulgeWidth + now); - scale = tr.sinTable[ off & FUNCTABLE_MASK ] * ds->bulgeHeight; + scale = tr.sinTable[off & FUNCTABLE_MASK] * ds->bulgeHeight; xyz[0] += normal[0] * scale; xyz[1] += normal[1] * scale; @@ -249,7 +225,6 @@ void RB_CalcBulgeVertexes( deformStage_t *ds ) } } - /* ====================== RB_CalcMoveVertexes @@ -257,29 +232,25 @@ RB_CalcMoveVertexes A deformation that can move an entire surface along a wave path ====================== */ -void RB_CalcMoveVertexes( deformStage_t *ds ) { - int i; - float *xyz; - float *table; - float scale; - vec3_t offset; +void RB_CalcMoveVertexes(deformStage_t *ds) { + int i; + float *xyz; + float *table; + float scale; + vec3_t offset; - table = TableForFunc( ds->deformationWave.func ); + table = TableForFunc(ds->deformationWave.func); - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase, ds->deformationWave.frequency); - VectorScale( ds->moveVector, scale, offset ); + VectorScale(ds->moveVector, scale, offset); - xyz = ( float * ) tess.xyz; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - VectorAdd( xyz, offset, xyz ); + xyz = (float *)tess.xyz; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + VectorAdd(xyz, offset, xyz); } } - /* ============= DeformText @@ -287,45 +258,45 @@ DeformText Change a polygon into a bunch of text polygons ============= */ -void DeformText( const char *text ) { - int i; - vec3_t origin, width, height; - int len; - int ch; - byte color[4]; - float bottom, top; - vec3_t mid; +void DeformText(const char *text) { + int i; + vec3_t origin, width, height; + int len; + int ch; + byte color[4]; + float bottom, top; + vec3_t mid; height[0] = 0; height[1] = 0; height[2] = -1; - CrossProduct( tess.normal[0], height, width ); + CrossProduct(tess.normal[0], height, width); // find the midpoint of the box - VectorClear( mid ); - bottom = WORLD_SIZE; //999999; // WORLD_SIZE instead of MAX_WORLD_COORD so guaranteed to be... - top = -WORLD_SIZE; //-999999; // ... outside the legal range. - for ( i = 0 ; i < 4 ; i++ ) { - VectorAdd( tess.xyz[i], mid, mid ); - if ( tess.xyz[i][2] < bottom ) { + VectorClear(mid); + bottom = WORLD_SIZE; // 999999; // WORLD_SIZE instead of MAX_WORLD_COORD so guaranteed to be... + top = -WORLD_SIZE; //-999999; // ... outside the legal range. + for (i = 0; i < 4; i++) { + VectorAdd(tess.xyz[i], mid, mid); + if (tess.xyz[i][2] < bottom) { bottom = tess.xyz[i][2]; } - if ( tess.xyz[i][2] > top ) { + if (tess.xyz[i][2] > top) { top = tess.xyz[i][2]; } } - VectorScale( mid, 0.25f, origin ); + VectorScale(mid, 0.25f, origin); // determine the individual character size height[0] = 0; height[1] = 0; - height[2] = ( top - bottom ) * 0.5f; + height[2] = (top - bottom) * 0.5f; - VectorScale( width, height[2] * -0.75f, width ); + VectorScale(width, height[2] * -0.75f, width); // determine the starting position - len = strlen( text ); - VectorMA( origin, (len-1), width, origin ); + len = strlen(text); + VectorMA(origin, (len - 1), width, origin); // clear the shader indexes tess.numIndexes = 0; @@ -334,24 +305,24 @@ void DeformText( const char *text ) { color[0] = color[1] = color[2] = color[3] = 255; // draw each character - for ( i = 0 ; i < len ; i++ ) { + for (i = 0; i < len; i++) { ch = text[i]; ch &= 255; - if ( ch != ' ' ) { - int row, col; - float frow, fcol, size; + if (ch != ' ') { + int row, col; + float frow, fcol, size; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; - frow = row*0.0625f; - fcol = col*0.0625f; + frow = row * 0.0625f; + fcol = col * 0.0625f; size = 0.0625f; - RB_AddQuadStampExt( origin, width, height, color, fcol, frow, fcol + size, frow + size ); + RB_AddQuadStampExt(origin, width, height, color, fcol, frow, fcol + size, frow + size); } - VectorMA( origin, -2, width, origin ); + VectorMA(origin, -2, width, origin); } } @@ -360,10 +331,10 @@ void DeformText( const char *text ) { GlobalVectorToLocal ================== */ -static void GlobalVectorToLocal( const vec3_t in, vec3_t out ) { - out[0] = DotProduct( in, backEnd.ori.axis[0] ); - out[1] = DotProduct( in, backEnd.ori.axis[1] ); - out[2] = DotProduct( in, backEnd.ori.axis[2] ); +static void GlobalVectorToLocal(const vec3_t in, vec3_t out) { + out[0] = DotProduct(in, backEnd.ori.axis[0]); + out[1] = DotProduct(in, backEnd.ori.axis[1]); + out[2] = DotProduct(in, backEnd.ori.axis[2]); } /* @@ -374,35 +345,35 @@ Assuming all the triangles for this shader are independant quads, rebuild them as forward facing sprites ===================== */ -static void AutospriteDeform( void ) { - int i; - int oldVerts; - float *xyz; - vec3_t mid, delta; - float radius; - vec3_t left, up; - vec3_t leftDir, upDir; - - if ( tess.numVertexes & 3 ) { - Com_Error( ERR_DROP, "Autosprite shader %s had odd vertex count", tess.shader->name ); +static void AutospriteDeform(void) { + int i; + int oldVerts; + float *xyz; + vec3_t mid, delta; + float radius; + vec3_t left, up; + vec3_t leftDir, upDir; + + if (tess.numVertexes & 3) { + Com_Error(ERR_DROP, "Autosprite shader %s had odd vertex count", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - Com_Error( ERR_DROP, "Autosprite shader %s had odd index count", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + Com_Error(ERR_DROP, "Autosprite shader %s had odd index count", tess.shader->name); } oldVerts = tess.numVertexes; tess.numVertexes = 0; tess.numIndexes = 0; - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[1], leftDir ); - GlobalVectorToLocal( backEnd.viewParms.ori.axis[2], upDir ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[1], leftDir); + GlobalVectorToLocal(backEnd.viewParms.ori.axis[2], upDir); } else { - VectorCopy( backEnd.viewParms.ori.axis[1], leftDir ); - VectorCopy( backEnd.viewParms.ori.axis[2], upDir ); + VectorCopy(backEnd.viewParms.ori.axis[1], leftDir); + VectorCopy(backEnd.viewParms.ori.axis[2], upDir); } - for ( i = 0 ; i < oldVerts ; i+=4 ) { + for (i = 0; i < oldVerts; i += 4) { // find the midpoint xyz = tess.xyz[i]; @@ -410,21 +381,20 @@ static void AutospriteDeform( void ) { mid[1] = 0.25f * (xyz[1] + xyz[5] + xyz[9] + xyz[13]); mid[2] = 0.25f * (xyz[2] + xyz[6] + xyz[10] + xyz[14]); - VectorSubtract( xyz, mid, delta ); - radius = VectorLength( delta ) * 0.707f; // / sqrt(2) + VectorSubtract(xyz, mid, delta); + radius = VectorLength(delta) * 0.707f; // / sqrt(2) - VectorScale( leftDir, radius, left ); - VectorScale( upDir, radius, up ); + VectorScale(leftDir, radius, left); + VectorScale(upDir, radius, up); - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( mid, left, up, tess.vertexColors[i] ); + RB_AddQuadStamp(mid, left, up, tess.vertexColors[i]); } } - /* ===================== Autosprite2Deform @@ -432,73 +402,66 @@ Autosprite2Deform Autosprite2 will pivot a rectangular quad along the center of its long axis ===================== */ -static const glIndex_t edgeVerts[6][2] = { - { 0, 1 }, - { 0, 2 }, - { 0, 3 }, - { 1, 2 }, - { 1, 3 }, - { 2, 3 } -}; - -static void Autosprite2Deform( void ) { - int i, j, k; - int indexes; - float *xyz; - vec3_t forward; - - if ( tess.numVertexes & 3 ) { - ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd vertex count", tess.shader->name ); +static const glIndex_t edgeVerts[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}}; + +static void Autosprite2Deform(void) { + int i, j, k; + int indexes; + float *xyz; + vec3_t forward; + + if (tess.numVertexes & 3) { + ri.Printf(PRINT_WARNING, "Autosprite shader %s had odd vertex count", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd index count", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + ri.Printf(PRINT_WARNING, "Autosprite shader %s had odd index count", tess.shader->name); } - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[0], forward ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[0], forward); } else { - VectorCopy( backEnd.viewParms.ori.axis[0], forward ); + VectorCopy(backEnd.viewParms.ori.axis[0], forward); } // this is a lot of work for two triangles... // we could precalculate a lot of it is an issue, but it would mess up // the shader abstraction - for ( i = 0, indexes = 0 ; i < tess.numVertexes ; i+=4, indexes+=6 ) { - float lengths[2]; - int nums[2]; - vec3_t mid[2]; - vec3_t major, minor; - float *v1, *v2; + for (i = 0, indexes = 0; i < tess.numVertexes; i += 4, indexes += 6) { + float lengths[2]; + int nums[2]; + vec3_t mid[2]; + vec3_t major, minor; + float *v1, *v2; // find the midpoint xyz = tess.xyz[i]; // identify the two shortest edges nums[0] = nums[1] = 0; - lengths[0] = lengths[1] = WORLD_SIZE;//999999; // ... instead of MAX_WORLD_COORD, so guaranteed to be outside legal range + lengths[0] = lengths[1] = WORLD_SIZE; // 999999; // ... instead of MAX_WORLD_COORD, so guaranteed to be outside legal range - for ( j = 0 ; j < 6 ; j++ ) { - float l; - vec3_t temp; + for (j = 0; j < 6; j++) { + float l; + vec3_t temp; v1 = xyz + 4 * edgeVerts[j][0]; v2 = xyz + 4 * edgeVerts[j][1]; - VectorSubtract( v1, v2, temp ); + VectorSubtract(v1, v2, temp); - l = DotProduct( temp, temp ); - if ( l < lengths[0] ) { + l = DotProduct(temp, temp); + if (l < lengths[0]) { nums[1] = nums[0]; lengths[1] = lengths[0]; nums[0] = j; lengths[0] = l; - } else if ( l < lengths[1] ) { + } else if (l < lengths[1]) { nums[1] = j; lengths[1] = l; } } - for ( j = 0 ; j < 2 ; j++ ) { + for (j = 0; j < 2; j++) { v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; @@ -508,69 +471,67 @@ static void Autosprite2Deform( void ) { } // find the vector of the major axis - VectorSubtract( mid[1], mid[0], major ); + VectorSubtract(mid[1], mid[0], major); // cross this with the view direction to get minor axis - CrossProduct( major, forward, minor ); - VectorNormalize( minor ); + CrossProduct(major, forward, minor); + VectorNormalize(minor); // re-project the points - for ( j = 0 ; j < 2 ; j++ ) { - float l; + for (j = 0; j < 2; j++) { + float l; v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; - l = 0.5 * sqrt( lengths[j] ); + l = 0.5 * sqrt(lengths[j]); // we need to see which direction this edge // is used to determine direction of projection - for ( k = 0 ; k < 5 ; k++ ) { - if ( tess.indexes[ indexes + k ] == i + edgeVerts[nums[j]][0] - && tess.indexes[ indexes + k + 1 ] == i + edgeVerts[nums[j]][1] ) { + for (k = 0; k < 5; k++) { + if (tess.indexes[indexes + k] == i + edgeVerts[nums[j]][0] && tess.indexes[indexes + k + 1] == i + edgeVerts[nums[j]][1]) { break; } } - if ( k == 5 ) { - VectorMA( mid[j], l, minor, v1 ); - VectorMA( mid[j], -l, minor, v2 ); + if (k == 5) { + VectorMA(mid[j], l, minor, v1); + VectorMA(mid[j], -l, minor, v2); } else { - VectorMA( mid[j], -l, minor, v1 ); - VectorMA( mid[j], l, minor, v2 ); + VectorMA(mid[j], -l, minor, v1); + VectorMA(mid[j], l, minor, v2); } } } } - /* ===================== RB_DeformTessGeometry ===================== */ -void RB_DeformTessGeometry( void ) { - int i; - deformStage_t *ds; +void RB_DeformTessGeometry(void) { + int i; + deformStage_t *ds; - for ( i = 0 ; i < tess.shader->numDeforms ; i++ ) { - ds = tess.shader->deforms[ i ]; + for (i = 0; i < tess.shader->numDeforms; i++) { + ds = tess.shader->deforms[i]; - switch ( ds->deformation ) { - case DEFORM_NONE: - break; + switch (ds->deformation) { + case DEFORM_NONE: + break; case DEFORM_NORMALS: - RB_CalcDeformNormals( ds ); + RB_CalcDeformNormals(ds); break; case DEFORM_WAVE: - RB_CalcDeformVertexes( ds ); + RB_CalcDeformVertexes(ds); break; case DEFORM_BULGE: - RB_CalcBulgeVertexes( ds ); + RB_CalcBulgeVertexes(ds); break; case DEFORM_MOVE: - RB_CalcMoveVertexes( ds ); + RB_CalcMoveVertexes(ds); break; case DEFORM_PROJECTION_SHADOW: RB_ProjectionShadowDeform(); @@ -589,8 +550,8 @@ void RB_DeformTessGeometry( void ) { case DEFORM_TEXT5: case DEFORM_TEXT6: case DEFORM_TEXT7: -// DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] ); - DeformText( "Raven Software" ); + // DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] ); + DeformText("Raven Software"); break; } } @@ -604,21 +565,19 @@ COLORS ==================================================================== */ - /* ** RB_CalcColorFromEntity */ -void RB_CalcColorFromEntity( unsigned char *dstColors ) -{ - int i; - int *pColors = ( int * ) dstColors; +void RB_CalcColorFromEntity(unsigned char *dstColors) { + int i; + int *pColors = (int *)dstColors; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; const byteAlias_t *ba = (byteAlias_t *)&backEnd.currentEntity->e.shaderRGBA; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *pColors++ = ba->i; } } @@ -626,23 +585,22 @@ void RB_CalcColorFromEntity( unsigned char *dstColors ) /* ** RB_CalcColorFromOneMinusEntity */ -void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ) -{ - int i; - int *pColors = ( int * ) dstColors; +void RB_CalcColorFromOneMinusEntity(unsigned char *dstColors) { + int i; + int *pColors = (int *)dstColors; unsigned char invModulate[4]; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; invModulate[0] = 255 - backEnd.currentEntity->e.shaderRGBA[0]; invModulate[1] = 255 - backEnd.currentEntity->e.shaderRGBA[1]; invModulate[2] = 255 - backEnd.currentEntity->e.shaderRGBA[2]; - invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3]; // this trashes alpha, but the AGEN block fixes it + invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3]; // this trashes alpha, but the AGEN block fixes it byteAlias_t *ba = (byteAlias_t *)&invModulate; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *pColors++ = ba->i; } } @@ -650,17 +608,15 @@ void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ) /* ** RB_CalcAlphaFromEntity */ -void RB_CalcAlphaFromEntity( unsigned char *dstColors ) -{ - int i; +void RB_CalcAlphaFromEntity(unsigned char *dstColors) { + int i; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = backEnd.currentEntity->e.shaderRGBA[3]; } } @@ -668,17 +624,15 @@ void RB_CalcAlphaFromEntity( unsigned char *dstColors ) /* ** RB_CalcAlphaFromOneMinusEntity */ -void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors ) -{ - int i; +void RB_CalcAlphaFromOneMinusEntity(unsigned char *dstColors) { + int i; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = 0xff - backEnd.currentEntity->e.shaderRGBA[3]; } } @@ -686,34 +640,32 @@ void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors ) /* ** RB_CalcWaveColor */ -void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors ) -{ +void RB_CalcWaveColor(const waveForm_t *wf, unsigned char *dstColors) { int i; int v; float glow; - int *colors = ( int * ) dstColors; - byte color[4]; + int *colors = (int *)dstColors; + byte color[4]; - if ( wf->func == GF_NOISE ) { - glow = wf->base + R_NoiseGet4f( 0, 0, 0, ( backEnd.refdef.floatTime + wf->phase ) * wf->frequency ) * wf->amplitude; + if (wf->func == GF_NOISE) { + glow = wf->base + R_NoiseGet4f(0, 0, 0, (backEnd.refdef.floatTime + wf->phase) * wf->frequency) * wf->amplitude; } else { - glow = EvalWaveForm( wf ) * tr.identityLight; + glow = EvalWaveForm(wf) * tr.identityLight; } - if ( glow < 0 ) { + if (glow < 0) { glow = 0; - } - else if ( glow > 1 ) { + } else if (glow > 1) { glow = 1; } - v = Q_ftol( 255 * glow ); + v = Q_ftol(255 * glow); color[0] = color[1] = color[2] = v; color[3] = 255; byteAlias_t *ba = (byteAlias_t *)&color; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *colors++ = ba->i; } } @@ -721,18 +673,16 @@ void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors ) /* ** RB_CalcWaveAlpha */ -void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors ) -{ +void RB_CalcWaveAlpha(const waveForm_t *wf, unsigned char *dstColors) { int i; int v; float glow; - glow = EvalWaveFormClamped( wf ); + glow = EvalWaveFormClamped(wf); v = 255 * glow; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { dstColors[3] = v; } } @@ -740,17 +690,17 @@ void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors ) /* ** RB_CalcModulateColorsByFog */ -void RB_CalcModulateColorsByFog( unsigned char *colors ) { +void RB_CalcModulateColorsByFog(unsigned char *colors) { int i; - float texCoords[SHADER_MAX_VERTEXES][2]; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[0] *= f; colors[1] *= f; colors[2] *= f; @@ -760,17 +710,17 @@ void RB_CalcModulateColorsByFog( unsigned char *colors ) { /* ** RB_CalcModulateAlphasByFog */ -void RB_CalcModulateAlphasByFog( unsigned char *colors ) { +void RB_CalcModulateAlphasByFog(unsigned char *colors) { int i; - float texCoords[SHADER_MAX_VERTEXES][2]; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[3] *= f; } } @@ -778,17 +728,17 @@ void RB_CalcModulateAlphasByFog( unsigned char *colors ) { /* ** RB_CalcModulateRGBAsByFog */ -void RB_CalcModulateRGBAsByFog( unsigned char *colors ) { +void RB_CalcModulateRGBAsByFog(unsigned char *colors) { int i; - float texCoords[SHADER_MAX_VERTEXES][2]; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[0] *= f; colors[1] *= f; colors[2] *= f; @@ -796,7 +746,6 @@ void RB_CalcModulateRGBAsByFog( unsigned char *colors ) { } } - /* ==================================================================== @@ -815,24 +764,24 @@ doesn't fit our shader data. ======================== */ -void RB_CalcFogTexCoords( float *st ) { - int i; - float *v; - float s, t; - float eyeT; - qboolean eyeOutside; - fog_t *fog; - vec3_t localVec; - vec4_t fogDistanceVector, fogDepthVector; +void RB_CalcFogTexCoords(float *st) { + int i; + float *v; + float s, t; + float eyeT; + qboolean eyeOutside; + fog_t *fog; + vec3_t localVec; + vec4_t fogDistanceVector, fogDepthVector; fog = tr.world->fogs + tess.fogNum; // all fogging distance is based on world Z units - VectorSubtract( backEnd.ori.origin, backEnd.viewParms.ori.origin, localVec ); + VectorSubtract(backEnd.ori.origin, backEnd.viewParms.ori.origin, localVec); fogDistanceVector[0] = -backEnd.ori.modelMatrix[2]; fogDistanceVector[1] = -backEnd.ori.modelMatrix[6]; fogDistanceVector[2] = -backEnd.ori.modelMatrix[10]; - fogDistanceVector[3] = DotProduct( localVec, backEnd.viewParms.ori.axis[0] ); + fogDistanceVector[3] = DotProduct(localVec, backEnd.viewParms.ori.axis[0]); // scale the fog vectors based on the fog's thickness fogDistanceVector[0] *= fog->tcScale; @@ -841,18 +790,15 @@ void RB_CalcFogTexCoords( float *st ) { fogDistanceVector[3] *= fog->tcScale; // rotate the gradient vector for this orientation - if ( fog->hasSurface ) { - fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + - fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; - fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + - fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; - fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + - fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; - fogDepthVector[3] = -fog->surface[3] + DotProduct( backEnd.ori.origin, fog->surface ); - - eyeT = DotProduct( backEnd.ori.viewOrigin, fogDepthVector ) + fogDepthVector[3]; + if (fog->hasSurface) { + fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; + fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; + fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; + fogDepthVector[3] = -fog->surface[3] + DotProduct(backEnd.ori.origin, fog->surface); + + eyeT = DotProduct(backEnd.ori.viewOrigin, fogDepthVector) + fogDepthVector[3]; } else { - eyeT = 1; // non-surface fog always has eye inside + eyeT = 1; // non-surface fog always has eye inside fogDepthVector[0] = fogDepthVector[1] = fogDepthVector[2] = 0.0f; fogDepthVector[3] = 1.0f; } @@ -860,72 +806,68 @@ void RB_CalcFogTexCoords( float *st ) { // see if the viewpoint is outside // this is needed for clipping distance even for constant fog - if ( eyeT < 0 ) { + if (eyeT < 0) { eyeOutside = qtrue; } else { eyeOutside = qfalse; } - fogDistanceVector[3] += 1.0/512; + fogDistanceVector[3] += 1.0 / 512; // calculate density for each point - for (i = 0, v = tess.xyz[0] ; i < tess.numVertexes ; i++, v += 4) { + for (i = 0, v = tess.xyz[0]; i < tess.numVertexes; i++, v += 4) { // calculate the length in fog - s = DotProduct( v, fogDistanceVector ) + fogDistanceVector[3]; - t = DotProduct( v, fogDepthVector ) + fogDepthVector[3]; + s = DotProduct(v, fogDistanceVector) + fogDistanceVector[3]; + t = DotProduct(v, fogDepthVector) + fogDepthVector[3]; // partially clipped fogs use the T axis - if ( eyeOutside ) { - if ( t < 1.0 ) { - t = 1.0/32; // point is outside, so no fogging + if (eyeOutside) { + if (t < 1.0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 1.0/32 + 30.0/32 * t / ( t - eyeT ); // cut the distance at the fog plane + t = 1.0 / 32 + 30.0 / 32 * t / (t - eyeT); // cut the distance at the fog plane } } else { - if ( t < 0 ) { - t = 1.0/32; // point is outside, so no fogging + if (t < 0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 31.0/32; + t = 31.0 / 32; } } - st[0] = Q_isnan (s) ? 0.0f : s; - st[1] = Q_isnan (s) ? 0.0f : t; + st[0] = Q_isnan(s) ? 0.0f : s; + st[1] = Q_isnan(s) ? 0.0f : t; st += 2; } } - /* ** RB_CalcEnvironmentTexCoords */ -void RB_CalcEnvironmentTexCoords( float *st ) -{ - int i; - float *v, *normal; - vec3_t viewer; - float d; +void RB_CalcEnvironmentTexCoords(float *st) { + int i; + float *v, *normal; + vec3_t viewer; + float d; v = tess.xyz[0]; normal = tess.normal[0]; - if (backEnd.currentEntity && backEnd.currentEntity->e.renderfx&RF_FIRST_PERSON) //this is a view model so we must use world lights instead of vieworg + if (backEnd.currentEntity && backEnd.currentEntity->e.renderfx & RF_FIRST_PERSON) // this is a view model so we must use world lights instead of vieworg { - for (i = 0 ; i < tess.numVertexes ; i++, v += 4, normal += 4, st += 2 ) - { - d = DotProduct (normal, backEnd.currentEntity->lightDir); - st[0] = normal[0]*d - backEnd.currentEntity->lightDir[0]; - st[1] = normal[1]*d - backEnd.currentEntity->lightDir[1]; + for (i = 0; i < tess.numVertexes; i++, v += 4, normal += 4, st += 2) { + d = DotProduct(normal, backEnd.currentEntity->lightDir); + st[0] = normal[0] * d - backEnd.currentEntity->lightDir[0]; + st[1] = normal[1] * d - backEnd.currentEntity->lightDir[1]; } - } else { //the normal way - for (i = 0 ; i < tess.numVertexes ; i++, v += 4, normal += 4, st += 2 ) - { - VectorSubtract (backEnd.ori.viewOrigin, v, viewer); - VectorNormalizeFast (viewer); - - d = DotProduct (normal, viewer); - st[0] = normal[0]*d - 0.5*viewer[0]; - st[1] = normal[1]*d - 0.5*viewer[1]; + } else { // the normal way + for (i = 0; i < tess.numVertexes; i++, v += 4, normal += 4, st += 2) { + VectorSubtract(backEnd.ori.viewOrigin, v, viewer); + VectorNormalizeFast(viewer); + + d = DotProduct(normal, viewer); + st[0] = normal[0] * d - 0.5 * viewer[0]; + st[1] = normal[1] * d - 0.5 * viewer[1]; } } } @@ -933,32 +875,28 @@ void RB_CalcEnvironmentTexCoords( float *st ) /* ** RB_CalcTurbulentTexCoords */ -void RB_CalcTurbulentTexCoords( const waveForm_t *wf, float *st ) -{ +void RB_CalcTurbulentTexCoords(const waveForm_t *wf, float *st) { int i; float now; - now = ( wf->phase + backEnd.refdef.floatTime * wf->frequency ); + now = (wf->phase + backEnd.refdef.floatTime * wf->frequency); - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { float s = st[0]; float t = st[1]; - st[0] = s + tr.sinTable[ ( ( int ) ( ( ( tess.xyz[i][0] + tess.xyz[i][2] )* 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude; - st[1] = t + tr.sinTable[ ( ( int ) ( ( tess.xyz[i][1] * 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude; + st[0] = s + tr.sinTable[((int)(((tess.xyz[i][0] + tess.xyz[i][2]) * 1.0 / 128 * 0.125 + now) * FUNCTABLE_SIZE)) & (FUNCTABLE_MASK)] * wf->amplitude; + st[1] = t + tr.sinTable[((int)((tess.xyz[i][1] * 1.0 / 128 * 0.125 + now) * FUNCTABLE_SIZE)) & (FUNCTABLE_MASK)] * wf->amplitude; } } /* ** RB_CalcScaleTexCoords */ -void RB_CalcScaleTexCoords( const float scale[2], float *st ) -{ +void RB_CalcScaleTexCoords(const float scale[2], float *st) { int i; - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { st[0] *= scale[0]; st[1] *= scale[1]; } @@ -967,8 +905,7 @@ void RB_CalcScaleTexCoords( const float scale[2], float *st ) /* ** RB_CalcScrollTexCoords */ -void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) -{ +void RB_CalcScrollTexCoords(const float scrollSpeed[2], float *st) { int i; float timeScale = backEnd.refdef.floatTime; float adjustedScrollS, adjustedScrollT; @@ -978,11 +915,10 @@ void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) // clamp so coordinates don't continuously get larger, causing problems // with hardware limits - adjustedScrollS = adjustedScrollS - floor( adjustedScrollS ); - adjustedScrollT = adjustedScrollT - floor( adjustedScrollT ); + adjustedScrollS = adjustedScrollS - floor(adjustedScrollS); + adjustedScrollT = adjustedScrollT - floor(adjustedScrollT); - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { st[0] += adjustedScrollS; st[1] += adjustedScrollT; } @@ -991,12 +927,10 @@ void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) /* ** RB_CalcTransformTexCoords */ -void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *st ) -{ +void RB_CalcTransformTexCoords(const texModInfo_t *tmi, float *st) { int i; - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { float s = st[0]; float t = st[1]; @@ -1005,9 +939,7 @@ void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *st ) } } - -void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) -{ +void RB_CalcRotateTexCoords(float degsPerSecond, float *st) { float timeScale = backEnd.refdef.floatTime; float degs; int index; @@ -1015,10 +947,10 @@ void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) texModInfo_t tmi; degs = -degsPerSecond * timeScale; - index = degs * ( FUNCTABLE_SIZE / 360.0f ); + index = degs * (FUNCTABLE_SIZE / 360.0f); - sinValue = tr.sinTable[ index & FUNCTABLE_MASK ]; - cosValue = tr.sinTable[ ( index + FUNCTABLE_SIZE / 4 ) & FUNCTABLE_MASK ]; + sinValue = tr.sinTable[index & FUNCTABLE_MASK]; + cosValue = tr.sinTable[(index + FUNCTABLE_SIZE / 4) & FUNCTABLE_MASK]; tmi.matrix[0][0] = cosValue; tmi.matrix[1][0] = -sinValue; @@ -1028,29 +960,24 @@ void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) tmi.matrix[1][1] = cosValue; tmi.translate[1] = 0.5 - 0.5 * sinValue - 0.5 * cosValue; - RB_CalcTransformTexCoords( &tmi, st ); + RB_CalcTransformTexCoords(&tmi, st); } - - - - - /* ** RB_CalcSpecularAlpha ** ** Calculates specular coefficient and places it in the alpha channel */ -vec3_t lightOrigin = { -960, 1980, 96 }; // FIXME: track dynamically +vec3_t lightOrigin = {-960, 1980, 96}; // FIXME: track dynamically -void RB_CalcSpecularAlpha( unsigned char *alphas ) { - int i; - float *v, *normal; - vec3_t viewer, reflected; - float l, d; - int b; - vec3_t lightDir; - int numVertexes; +void RB_CalcSpecularAlpha(unsigned char *alphas) { + int i; + float *v, *normal; + vec3_t viewer, reflected; + float l, d; + int b; + vec3_t lightDir; + int numVertexes; v = tess.xyz[0]; normal = tess.normal[0]; @@ -1058,36 +985,36 @@ void RB_CalcSpecularAlpha( unsigned char *alphas ) { alphas += 3; numVertexes = tess.numVertexes; - for (i = 0 ; i < numVertexes ; i++, v += 4, normal += 4, alphas += 4) { + for (i = 0; i < numVertexes; i++, v += 4, normal += 4, alphas += 4) { float ilength; if (backEnd.currentEntity && - (backEnd.currentEntity->e.hModel||backEnd.currentEntity->e.ghoul2) ) //this is a model so we can use world lights instead fake light + (backEnd.currentEntity->e.hModel || backEnd.currentEntity->e.ghoul2)) // this is a model so we can use world lights instead fake light { - VectorCopy (backEnd.currentEntity->lightDir, lightDir); + VectorCopy(backEnd.currentEntity->lightDir, lightDir); } else { - VectorSubtract( lightOrigin, v, lightDir ); - VectorNormalizeFast( lightDir ); + VectorSubtract(lightOrigin, v, lightDir); + VectorNormalizeFast(lightDir); } // calculate the specular color - d = 2 * DotProduct (normal, lightDir); + d = 2 * DotProduct(normal, lightDir); // we don't optimize for the d < 0 case since this tends to // cause visual artifacts such as faceted "snapping" - reflected[0] = normal[0]*d - lightDir[0]; - reflected[1] = normal[1]*d - lightDir[1]; - reflected[2] = normal[2]*d - lightDir[2]; + reflected[0] = normal[0] * d - lightDir[0]; + reflected[1] = normal[1] * d - lightDir[1]; + reflected[2] = normal[2] * d - lightDir[2]; - VectorSubtract (backEnd.ori.viewOrigin, v, viewer); - ilength = Q_rsqrt( DotProduct( viewer, viewer ) ); - l = DotProduct (reflected, viewer); + VectorSubtract(backEnd.ori.viewOrigin, v, viewer); + ilength = Q_rsqrt(DotProduct(viewer, viewer)); + l = DotProduct(reflected, viewer); l *= ilength; if (l < 0) { b = 0; } else { - l = l*l; - l = l*l; + l = l * l; + l = l * l; b = l * 255; if (b > 255) { b = 255; @@ -1103,55 +1030,53 @@ void RB_CalcSpecularAlpha( unsigned char *alphas ) { ** ** The basic vertex lighting calc */ -void RB_CalcDiffuseColor( unsigned char *colors ) -{ - int i, j; - float *v, *normal; - float incoming; - trRefEntity_t *ent; - int ambientLightInt; - vec3_t ambientLight; - vec3_t lightDir; - vec3_t directedLight; - int numVertexes; +void RB_CalcDiffuseColor(unsigned char *colors) { + int i, j; + float *v, *normal; + float incoming; + trRefEntity_t *ent; + int ambientLightInt; + vec3_t ambientLight; + vec3_t lightDir; + vec3_t directedLight; + int numVertexes; ent = backEnd.currentEntity; ambientLightInt = ent->ambientLightInt; - VectorCopy( ent->ambientLight, ambientLight ); - VectorCopy( ent->directedLight, directedLight ); - VectorCopy( ent->lightDir, lightDir ); + VectorCopy(ent->ambientLight, ambientLight); + VectorCopy(ent->directedLight, directedLight); + VectorCopy(ent->lightDir, lightDir); v = tess.xyz[0]; normal = tess.normal[0]; numVertexes = tess.numVertexes; - for ( i = 0 ; i < numVertexes ; i++, v += 4, normal += 4) - { - incoming = DotProduct (normal, lightDir); - if ( incoming <= 0 ) { - *(int *)&colors[i*4] = ambientLightInt; + for (i = 0; i < numVertexes; i++, v += 4, normal += 4) { + incoming = DotProduct(normal, lightDir); + if (incoming <= 0) { + *(int *)&colors[i * 4] = ambientLightInt; continue; } - j = Q_ftol( ambientLight[0] + incoming * directedLight[0] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[0] + incoming * directedLight[0]); + if (j > 255) { j = 255; } - colors[i*4+0] = j; + colors[i * 4 + 0] = j; - j = Q_ftol( ambientLight[1] + incoming * directedLight[1] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[1] + incoming * directedLight[1]); + if (j > 255) { j = 255; } - colors[i*4+1] = j; + colors[i * 4 + 1] = j; - j = Q_ftol( ambientLight[2] + incoming * directedLight[2] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[2] + incoming * directedLight[2]); + if (j > 255) { j = 255; } - colors[i*4+2] = j; + colors[i * 4 + 2] = j; - colors[i*4+3] = 255; + colors[i * 4 + 3] = 255; } } @@ -1160,36 +1085,34 @@ void RB_CalcDiffuseColor( unsigned char *colors ) ** ** The basic vertex lighting calc * Entity Color */ -void RB_CalcDiffuseEntityColor( unsigned char *colors ) -{ - int i; - float *v, *normal; - float incoming; - trRefEntity_t *ent; - int ambientLightInt; - vec3_t ambientLight; - vec3_t lightDir; - vec3_t directedLight; - int numVertexes; - float j,r,g,b; - - if ( !backEnd.currentEntity ) - {//error, use the normal lighting +void RB_CalcDiffuseEntityColor(unsigned char *colors) { + int i; + float *v, *normal; + float incoming; + trRefEntity_t *ent; + int ambientLightInt; + vec3_t ambientLight; + vec3_t lightDir; + vec3_t directedLight; + int numVertexes; + float j, r, g, b; + + if (!backEnd.currentEntity) { // error, use the normal lighting RB_CalcDiffuseColor(colors); } ent = backEnd.currentEntity; - VectorCopy( ent->ambientLight, ambientLight ); - VectorCopy( ent->directedLight, directedLight ); - VectorCopy( ent->lightDir, lightDir ); + VectorCopy(ent->ambientLight, ambientLight); + VectorCopy(ent->directedLight, directedLight); + VectorCopy(ent->lightDir, lightDir); - r = backEnd.currentEntity->e.shaderRGBA[0]/255.0f; - g = backEnd.currentEntity->e.shaderRGBA[1]/255.0f; - b = backEnd.currentEntity->e.shaderRGBA[2]/255.0f; + r = backEnd.currentEntity->e.shaderRGBA[0] / 255.0f; + g = backEnd.currentEntity->e.shaderRGBA[1] / 255.0f; + b = backEnd.currentEntity->e.shaderRGBA[2] / 255.0f; - ((byte *)&ambientLightInt)[0] = Q_ftol( r*ent->ambientLight[0] ); - ((byte *)&ambientLightInt)[1] = Q_ftol( g*ent->ambientLight[1] ); - ((byte *)&ambientLightInt)[2] = Q_ftol( b*ent->ambientLight[2] ); + ((byte *)&ambientLightInt)[0] = Q_ftol(r * ent->ambientLight[0]); + ((byte *)&ambientLightInt)[1] = Q_ftol(g * ent->ambientLight[1]); + ((byte *)&ambientLightInt)[2] = Q_ftol(b * ent->ambientLight[2]); ((byte *)&ambientLightInt)[3] = backEnd.currentEntity->e.shaderRGBA[3]; v = tess.xyz[0]; @@ -1197,43 +1120,41 @@ void RB_CalcDiffuseEntityColor( unsigned char *colors ) numVertexes = tess.numVertexes; - for ( i = 0 ; i < numVertexes ; i++, v += 4, normal += 4) - { - incoming = DotProduct (normal, lightDir); - if ( incoming <= 0 ) { - *(int *)&colors[i*4] = ambientLightInt; + for (i = 0; i < numVertexes; i++, v += 4, normal += 4) { + incoming = DotProduct(normal, lightDir); + if (incoming <= 0) { + *(int *)&colors[i * 4] = ambientLightInt; continue; } - j = ( ambientLight[0] + incoming * directedLight[0] ); - if ( j > 255 ) { + j = (ambientLight[0] + incoming * directedLight[0]); + if (j > 255) { j = 255; } - colors[i*4+0] = Q_ftol(j*r); + colors[i * 4 + 0] = Q_ftol(j * r); - j = ( ambientLight[1] + incoming * directedLight[1] ); - if ( j > 255 ) { + j = (ambientLight[1] + incoming * directedLight[1]); + if (j > 255) { j = 255; } - colors[i*4+1] = Q_ftol(j*g); + colors[i * 4 + 1] = Q_ftol(j * g); - j = ( ambientLight[2] + incoming * directedLight[2] ); - if ( j > 255 ) { + j = (ambientLight[2] + incoming * directedLight[2]); + if (j > 255) { j = 255; } - colors[i*4+2] = Q_ftol(j*b); + colors[i * 4 + 2] = Q_ftol(j * b); - colors[i*4+3] = backEnd.currentEntity->e.shaderRGBA[3]; + colors[i * 4 + 3] = backEnd.currentEntity->e.shaderRGBA[3]; } } //--------------------------------------------------------- -void RB_CalcDisintegrateColors( unsigned char *colors, colorGen_t rgbGen ) -{ - int i, numVertexes; - float dis, threshold; - float *v; - vec3_t temp; - refEntity_t *ent; +void RB_CalcDisintegrateColors(unsigned char *colors, colorGen_t rgbGen) { + int i, numVertexes; + float dis, threshold; + float *v; + vec3_t temp; + refEntity_t *ent; ent = &backEnd.currentEntity->e; v = tess.xyz[0]; @@ -1243,139 +1164,107 @@ void RB_CalcDisintegrateColors( unsigned char *colors, colorGen_t rgbGen ) numVertexes = tess.numVertexes; - if ( ent->renderfx & RF_DISINTEGRATE1 ) - { + if (ent->renderfx & RF_DISINTEGRATE1) { // this handles the blacken and fading out of the regular player model - for ( i = 0 ; i < numVertexes ; i++, v += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, v, temp ); + for (i = 0; i < numVertexes; i++, v += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, v, temp); - dis = VectorLengthSquared( temp ); + dis = VectorLengthSquared(temp); - if ( dis < threshold * threshold ) - { + if (dis < threshold * threshold) { // completely disintegrated - colors[i*4+3] = 0x00; - } - else if ( dis < threshold * threshold + 60 ) - { + colors[i * 4 + 3] = 0x00; + } else if (dis < threshold * threshold + 60) { // blacken before fading out - colors[i*4+0] = 0x0; - colors[i*4+1] = 0x0; - colors[i*4+2] = 0x0; - colors[i*4+3] = 0xff; - } - else if ( dis < threshold * threshold + 150 ) - { + colors[i * 4 + 0] = 0x0; + colors[i * 4 + 1] = 0x0; + colors[i * 4 + 2] = 0x0; + colors[i * 4 + 3] = 0xff; + } else if (dis < threshold * threshold + 150) { // darken more - if ( rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY ) - { - colors[i*4+0] = backEnd.currentEntity->e.shaderRGBA[0]*0x6f/255.0f; - colors[i*4+1] = backEnd.currentEntity->e.shaderRGBA[1]*0x6f/255.0f; - colors[i*4+2] = backEnd.currentEntity->e.shaderRGBA[2]*0x6f/255.0f; - } - else - { - colors[i*4+0] = 0x6f; - colors[i*4+1] = 0x6f; - colors[i*4+2] = 0x6f; + if (rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) { + colors[i * 4 + 0] = backEnd.currentEntity->e.shaderRGBA[0] * 0x6f / 255.0f; + colors[i * 4 + 1] = backEnd.currentEntity->e.shaderRGBA[1] * 0x6f / 255.0f; + colors[i * 4 + 2] = backEnd.currentEntity->e.shaderRGBA[2] * 0x6f / 255.0f; + } else { + colors[i * 4 + 0] = 0x6f; + colors[i * 4 + 1] = 0x6f; + colors[i * 4 + 2] = 0x6f; } - colors[i*4+3] = 0xff; - } - else if ( dis < threshold * threshold + 180 ) - { + colors[i * 4 + 3] = 0xff; + } else if (dis < threshold * threshold + 180) { // darken at edge of burn - if ( rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY ) - { - colors[i*4+0] = backEnd.currentEntity->e.shaderRGBA[0]*0xaf/255.0f; - colors[i*4+1] = backEnd.currentEntity->e.shaderRGBA[1]*0xaf/255.0f; - colors[i*4+2] = backEnd.currentEntity->e.shaderRGBA[2]*0xaf/255.0f; - } - else - { - colors[i*4+0] = 0xaf; - colors[i*4+1] = 0xaf; - colors[i*4+2] = 0xaf; + if (rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) { + colors[i * 4 + 0] = backEnd.currentEntity->e.shaderRGBA[0] * 0xaf / 255.0f; + colors[i * 4 + 1] = backEnd.currentEntity->e.shaderRGBA[1] * 0xaf / 255.0f; + colors[i * 4 + 2] = backEnd.currentEntity->e.shaderRGBA[2] * 0xaf / 255.0f; + } else { + colors[i * 4 + 0] = 0xaf; + colors[i * 4 + 1] = 0xaf; + colors[i * 4 + 2] = 0xaf; } - colors[i*4+3] = 0xff; - } - else - { + colors[i * 4 + 3] = 0xff; + } else { // not burning at all yet - if ( rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY ) - { - colors[i*4+0] = backEnd.currentEntity->e.shaderRGBA[0]; - colors[i*4+1] = backEnd.currentEntity->e.shaderRGBA[1]; - colors[i*4+2] = backEnd.currentEntity->e.shaderRGBA[2]; - } - else - { - colors[i*4+0] = 0xff; - colors[i*4+1] = 0xff; - colors[i*4+2] = 0xff; + if (rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) { + colors[i * 4 + 0] = backEnd.currentEntity->e.shaderRGBA[0]; + colors[i * 4 + 1] = backEnd.currentEntity->e.shaderRGBA[1]; + colors[i * 4 + 2] = backEnd.currentEntity->e.shaderRGBA[2]; + } else { + colors[i * 4 + 0] = 0xff; + colors[i * 4 + 1] = 0xff; + colors[i * 4 + 2] = 0xff; } - colors[i*4+3] = 0xff; + colors[i * 4 + 3] = 0xff; } } - } - else if ( ent->renderfx & RF_DISINTEGRATE2 ) - { + } else if (ent->renderfx & RF_DISINTEGRATE2) { // this handles the glowing, burning bit that scales away from the model - for ( i = 0 ; i < numVertexes ; i++, v += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, v, temp ); + for (i = 0; i < numVertexes; i++, v += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, v, temp); - dis = VectorLengthSquared( temp ); + dis = VectorLengthSquared(temp); - if ( dis < threshold * threshold ) - { + if (dis < threshold * threshold) { // done burning - colors[i*4+0] = 0x00; - colors[i*4+1] = 0x00; - colors[i*4+2] = 0x00; - colors[i*4+3] = 0x00; - } - else - { + colors[i * 4 + 0] = 0x00; + colors[i * 4 + 1] = 0x00; + colors[i * 4 + 2] = 0x00; + colors[i * 4 + 3] = 0x00; + } else { // still full burn - colors[i*4+0] = 0xff; - colors[i*4+1] = 0xff; - colors[i*4+2] = 0xff; - colors[i*4+3] = 0xff; + colors[i * 4 + 0] = 0xff; + colors[i * 4 + 1] = 0xff; + colors[i * 4 + 2] = 0xff; + colors[i * 4 + 3] = 0xff; } } } } //--------------------------------------------------------- -void RB_CalcDisintegrateVertDeform( void ) -{ - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float scale; - vec3_t temp; - - if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2 ) - { - float threshold = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; +void RB_CalcDisintegrateVertDeform(void) { + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float scale; + vec3_t temp; - for ( int i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, xyz, temp ); + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2) { + float threshold = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; - scale = VectorLengthSquared( temp ); + for (int i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, xyz, temp); - if ( scale < threshold * threshold ) - { + scale = VectorLengthSquared(temp); + + if (scale < threshold * threshold) { xyz[0] += normal[0] * 2.0f; xyz[1] += normal[1] * 2.0f; xyz[2] += normal[2] * 0.5f; - } - else if ( scale < threshold * threshold + 50 ) - { + } else if (scale < threshold * threshold + 50) { xyz[0] += normal[0] * 1.0f; xyz[1] += normal[1] * 1.0f; -// xyz[2] += normal[2] * 1; + // xyz[2] += normal[2] * 1; } } } diff --git a/code/rd-vanilla/tr_shader.cpp b/code/rd-vanilla/tr_shader.cpp index 1fd3d40296..30c9916d68 100644 --- a/code/rd-vanilla/tr_shader.cpp +++ b/code/rd-vanilla/tr_shader.cpp @@ -34,9 +34,9 @@ static char *s_shaderText; // the shader is parsed into these global variables, then copied into // dynamically allocated memory if it is valid. -static shaderStage_t stages[MAX_SHADER_STAGES]; -static shader_t shader; -static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; +static shaderStage_t stages[MAX_SHADER_STAGES]; +static shader_t shader; +static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; // Hash value (generated using the generateHashValueForText function) for the original // retail JK2/JKA shader for gfx/2d/wedge. @@ -52,70 +52,36 @@ static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; #define RETAIL_ARROW_W_SHADER_HASH (1650186) #endif +#define FILE_HASH_SIZE 1024 +static shader_t *sh_hashTable[FILE_HASH_SIZE]; -#define FILE_HASH_SIZE 1024 -static shader_t* sh_hashTable[FILE_HASH_SIZE]; +const int lightmapsNone[MAXLIGHTMAPS] = {LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE}; -const int lightmapsNone[MAXLIGHTMAPS] = -{ - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE -}; - -const int lightmaps2d[MAXLIGHTMAPS] = -{ - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D -}; +const int lightmaps2d[MAXLIGHTMAPS] = {LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D}; -const int lightmapsVertex[MAXLIGHTMAPS] = -{ - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX -}; +const int lightmapsVertex[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX}; -const int lightmapsFullBright[MAXLIGHTMAPS] = -{ - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE -}; +const int lightmapsFullBright[MAXLIGHTMAPS] = {LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE}; -const byte stylesDefault[MAXLIGHTMAPS] = -{ - LS_NORMAL, - LS_NONE, - LS_NONE, - LS_NONE -}; +const byte stylesDefault[MAXLIGHTMAPS] = {LS_NORMAL, LS_NONE, LS_NONE, LS_NONE}; -static void ClearGlobalShader(void) -{ - int i; +static void ClearGlobalShader(void) { + int i; - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; } shader.contentFlags = CONTENTS_SOLID | CONTENTS_OPAQUE; } -static uint32_t generateHashValueForText( const char *string, size_t length ) -{ +static uint32_t generateHashValueForText(const char *string, size_t length) { int i = 0; uint32_t hash = 0; - while ( length-- ) - { + while (length--) { hash += string[i] * (i + 119); i++; } @@ -134,23 +100,22 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndex, const byte *styles ) -{ - shader_t *sh; +qhandle_t RE_RegisterShaderLightMap(const char *name, const int *lightmapIndex, const byte *styles) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmapIndex, styles, qtrue ); + sh = R_FindShader(name, lightmapIndex, styles, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } @@ -165,23 +130,23 @@ Will always return a valid shader, but it might be the default shader if the real one can't be found. ================== */ -shader_t *R_FindShaderByName( const char *name ) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindShaderByName(const char *name) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( (name==NULL) || (name[0] == 0) ) { // bk001205 + if ((name == NULL) || (name[0] == 0)) { // bk001205 return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof(strippedName) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName); // // see if the shader is already loaded // - for (sh=sh_hashTable[hash]; sh; sh=sh->next) { + for (sh = sh_hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader @@ -247,109 +212,81 @@ void R_RemapShader(const char *shaderName, const char *newShaderName, const char ParseVector =============== */ -qboolean ParseVector( const char **text, int count, float *v ) { - char *token; - int i; +qboolean ParseVector(const char **text, int count, float *v) { + char *token; + int i; // FIXME: spaces are currently required after parens, should change parseext... - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "(" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "(")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } - for ( i = 0 ; i < count ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { - ri.Printf( PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name ); + for (i = 0; i < count; i++) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name); return qfalse; } - v[i] = atof( token ); + v[i] = atof(token); } - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, ")" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, ")")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } return qtrue; } - /* =============== NameToAFunc =============== */ -static unsigned NameToAFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "GT0" ) ) - { +static unsigned NameToAFunc(const char *funcname) { + if (!Q_stricmp(funcname, "GT0")) { return GLS_ATEST_GT_0; - } - else if ( !Q_stricmp( funcname, "LT128" ) ) - { + } else if (!Q_stricmp(funcname, "LT128")) { return GLS_ATEST_LT_80; - } - else if ( !Q_stricmp( funcname, "GE128" ) ) - { + } else if (!Q_stricmp(funcname, "GE128")) { return GLS_ATEST_GE_80; - } - else if ( !Q_stricmp( funcname, "GE192" ) ) - { + } else if (!Q_stricmp(funcname, "GE192")) { return GLS_ATEST_GE_C0; } - ri.Printf( PRINT_WARNING, "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name); return 0; } - /* =============== NameToSrcBlendMode =============== */ -static int NameToSrcBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToSrcBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_SRCBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_SRCBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_COLOR")) { return GLS_SRCBLEND_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_COLOR")) { return GLS_SRCBLEND_ONE_MINUS_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_SRCBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_SRCBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA_SATURATE")) { return GLS_SRCBLEND_ALPHA_SATURATE; } - ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_SRCBLEND_ONE; } @@ -358,41 +295,25 @@ static int NameToSrcBlendMode( const char *name ) NameToDstBlendMode =============== */ -static int NameToDstBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToDstBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_DSTBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_DSTBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_DSTBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_DSTBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_COLOR")) { return GLS_DSTBLEND_SRC_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_COLOR")) { return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; } - ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_DSTBLEND_ONE; } @@ -401,327 +322,271 @@ static int NameToDstBlendMode( const char *name ) NameToGenFunc =============== */ -static genFunc_t NameToGenFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "sin" ) ) - { +static genFunc_t NameToGenFunc(const char *funcname) { + if (!Q_stricmp(funcname, "sin")) { return GF_SIN; - } - else if ( !Q_stricmp( funcname, "square" ) ) - { + } else if (!Q_stricmp(funcname, "square")) { return GF_SQUARE; - } - else if ( !Q_stricmp( funcname, "triangle" ) ) - { + } else if (!Q_stricmp(funcname, "triangle")) { return GF_TRIANGLE; - } - else if ( !Q_stricmp( funcname, "sawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "sawtooth")) { return GF_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "inversesawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "inversesawtooth")) { return GF_INVERSE_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "noise" ) ) - { + } else if (!Q_stricmp(funcname, "noise")) { return GF_NOISE; - } - else if ( !Q_stricmp( funcname, "random" ) ) - { + } else if (!Q_stricmp(funcname, "random")) { return GF_RAND; } - - ri.Printf( PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name); return GF_SIN; } - /* =================== ParseWaveForm =================== */ -static void ParseWaveForm( const char **text, waveForm_t *wave ) -{ +static void ParseWaveForm(const char **text, waveForm_t *wave) { char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->func = NameToGenFunc( token ); + wave->func = NameToGenFunc(token); // BASE, AMP, PHASE, FREQ - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->base = atof( token ); + wave->base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->amplitude = atof( token ); + wave->amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->phase = atof( token ); + wave->phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->frequency = atof( token ); + wave->frequency = atof(token); } - /* =================== ParseTexMod =================== */ -static void ParseTexMod( const char *_text, shaderStage_t *stage ) -{ +static void ParseTexMod(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; texModInfo_t *tmi; - if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) { - Com_Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name ); + if (stage->bundle[0].numTexMods == TR_MAX_TEXMODS) { + Com_Error(ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name); return; } tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods]; stage->bundle[0].numTexMods++; - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); // // turb // - if ( !Q_stricmp( token, "turb" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "turb")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.base = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.amplitude = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.phase = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_TURBULENT; } // // scale // - else if ( !Q_stricmp( token, "scale" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scale unioned + tmi->translate[0] = atof(token); // scale unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scale unioned + tmi->translate[1] = atof(token); // scale unioned tmi->type = TMOD_SCALE; } // // scroll // - else if ( !Q_stricmp( token, "scroll" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scroll")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scroll unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + tmi->translate[0] = atof(token); // scroll unioned + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scroll unioned + tmi->translate[1] = atof(token); // scroll unioned tmi->type = TMOD_SCROLL; } // // stretch // - else if ( !Q_stricmp( token, "stretch" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "stretch")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.func = NameToGenFunc( token ); + tmi->wave.func = NameToGenFunc(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); + tmi->wave.base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); + tmi->wave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); + tmi->wave.phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_STRETCH; } // // transform // - else if ( !Q_stricmp( token, "transform" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "transform")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][0] = atof( token ); + tmi->matrix[0][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][1] = atof( token ); + tmi->matrix[0][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][0] = atof( token ); + tmi->matrix[1][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][1] = atof( token ); + tmi->matrix[1][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); + tmi->translate[0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); + tmi->translate[1] = atof(token); tmi->type = TMOD_TRANSFORM; } // // rotate // - else if ( !Q_stricmp( token, "rotate" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rotate")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name); return; } - tmi->translate[0]= atof( token ); //rotateSpeed unioned + tmi->translate[0] = atof(token); // rotateSpeed unioned tmi->type = TMOD_ROTATE; } // // entityTranslate // - else if ( !Q_stricmp( token, "entityTranslate" ) ) - { + else if (!Q_stricmp(token, "entityTranslate")) { tmi->type = TMOD_ENTITY_TRANSLATE; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name); } } - - - /* /////===== Part of the VERTIGON system =====///// =================== @@ -732,113 +597,93 @@ ParseSurfaceSprites // // NOTE: This parsing function used to be 12 pages long and very complex. The new version of surfacesprites // utilizes optional parameters parsed in ParseSurfaceSpriteOptional. -static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; float width, height, density, fadedist; - int sstype=SURFSPRITE_NONE; + int sstype = SURFSPRITE_NONE; // // spritetype // - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - if (!Q_stricmp(token, "vertical")) - { + if (!Q_stricmp(token, "vertical")) { sstype = SURFSPRITE_VERTICAL; - } - else if (!Q_stricmp(token, "oriented")) - { + } else if (!Q_stricmp(token, "oriented")) { sstype = SURFSPRITE_ORIENTED; - } - else if (!Q_stricmp(token, "effect")) - { + } else if (!Q_stricmp(token, "effect")) { sstype = SURFSPRITE_EFFECT; - } - else if (!Q_stricmp(token, "flattened")) - { + } else if (!Q_stricmp(token, "flattened")) { sstype = SURFSPRITE_FLATTENED; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: invalid type in shader '%s'\n", shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: invalid type in shader '%s'\n", shader.name); return; } // // width // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - width=atof(token); - if (width <= 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid width in shader '%s'\n", shader.name ); + width = atof(token); + if (width <= 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid width in shader '%s'\n", shader.name); return; } // // height // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - height=atof(token); - if (height <= 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid height in shader '%s'\n", shader.name ); + height = atof(token); + if (height <= 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid height in shader '%s'\n", shader.name); return; } // // density // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - density=atof(token); - if (density <= 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid density in shader '%s'\n", shader.name ); + density = atof(token); + if (density <= 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid density in shader '%s'\n", shader.name); return; } // // fadedist // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - fadedist=atof(token); - if (fadedist < 32) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name ); + fadedist = atof(token); + if (fadedist < 32) { + ri.Printf(PRINT_WARNING, "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name); return; } - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)R_Hunk_Alloc( sizeof( surfaceSprite_t ), qtrue ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)R_Hunk_Alloc(sizeof(surfaceSprite_t), qtrue); } // These are all set by the command lines. @@ -849,7 +694,7 @@ static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage ) stage->ss->fadeDist = fadedist; // These are defaults that can be overwritten. - stage->ss->fadeMax = fadedist*1.33; + stage->ss->fadeMax = fadedist * 1.33; stage->ss->fadeScale = 0.0; stage->ss->wind = 0.0; stage->ss->windIdle = 0.0; @@ -861,16 +706,13 @@ static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage ) stage->ss->vertSkew = 0.0f; // These are effect parameters that need defaults nonetheless. - stage->ss->fxDuration = 1000; // 1 second + stage->ss->fxDuration = 1000; // 1 second stage->ss->fxGrow[0] = 0.0; stage->ss->fxGrow[1] = 0.0; stage->ss->fxAlphaStart = 1.0; stage->ss->fxAlphaEnd = 0.0; } - - - /* /////===== Part of the VERTIGON system =====///// =========================== @@ -894,150 +736,129 @@ ParseSurfaceSpritesOptional // // Optional parameters that will override the defaults set in the surfacesprites command above. // -static void ParseSurfaceSpritesOptional( const char *param, const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSpritesOptional(const char *param, const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; - float value; + float value; - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)R_Hunk_Alloc( sizeof( surfaceSprite_t ), qtrue ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)R_Hunk_Alloc(sizeof(surfaceSprite_t), qtrue); } // // fademax // - if (!Q_stricmp(param, "ssFademax")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFademax")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= stage->ss->fadeDist) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, shader.name ); + if (value <= stage->ss->fadeDist) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, + shader.name); return; } - stage->ss->fadeMax=value; + stage->ss->fadeMax = value; return; } // // fadescale // - if (!Q_stricmp(param, "ssFadescale")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFadescale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name); return; } value = atof(token); - stage->ss->fadeScale=value; + stage->ss->fadeScale = value; return; } // // variance // - if (!Q_stricmp(param, "ssVariance")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVariance")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name); return; } - stage->ss->variance[0]=value; + stage->ss->variance[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name); return; } - stage->ss->variance[1]=value; + stage->ss->variance[1] = value; return; } // // hangdown // - if (!Q_stricmp(param, "ssHangdown")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_WARNING, "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssHangdown")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_WARNING, "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_DOWN; + stage->ss->facing = SURFSPRITE_FACING_DOWN; return; } // // anyangle // - if (!Q_stricmp(param, "ssAnyangle")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_WARNING, "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssAnyangle")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_WARNING, "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_ANY; + stage->ss->facing = SURFSPRITE_FACING_ANY; return; } // // faceup // - if (!Q_stricmp(param, "ssFaceup")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_WARNING, "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFaceup")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_WARNING, "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_UP; + stage->ss->facing = SURFSPRITE_FACING_UP; return; } // // wind // - if (!Q_stricmp(param, "ssWind")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWind")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name); return; } - stage->ss->wind=value; - if (stage->ss->windIdle <= 0) - { // Also override the windidle, it usually is the same as wind + stage->ss->wind = value; + if (stage->ss->windIdle <= 0) { // Also override the windidle, it usually is the same as wind stage->ss->windIdle = value; } return; @@ -1046,144 +867,123 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // windidle // - if (!Q_stricmp(param, "ssWindidle")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWindidle")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name); return; } - stage->ss->windIdle=value; + stage->ss->windIdle = value; return; } // // vertskew // - if (!Q_stricmp(param, "ssVertskew")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVertskew")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name); return; } - stage->ss->vertSkew=value; + stage->ss->vertSkew = value; return; } // // fxduration // - if (!Q_stricmp(param, "ssFXDuration")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXDuration")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name ); + if (value <= 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name); return; } - stage->ss->fxDuration=value; + stage->ss->fxDuration = value; return; } // // fxgrow // - if (!Q_stricmp(param, "ssFXGrow")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXGrow")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[0]=value; + stage->ss->fxGrow[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[1]=value; + stage->ss->fxGrow[1] = value; return; } // // fxalpharange // - if (!Q_stricmp(param, "ssFXAlphaRange")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXAlphaRange")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaStart=value; + stage->ss->fxAlphaStart = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_WARNING, "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_WARNING, "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_WARNING, "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaEnd=value; + stage->ss->fxAlphaEnd = value; return; } // // fxweather // - if (!Q_stricmp(param, "ssFXWeather")) - { - if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) - { - ri.Printf( PRINT_WARNING, "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXWeather")) { + if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) { + ri.Printf(PRINT_WARNING, "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name); return; } stage->ss->surfaceSpriteType = SURFSPRITE_WEATHERFX; @@ -1193,78 +993,60 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // invalid ss command. // - ri.Printf( PRINT_WARNING, "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name); return; } - /* =================== ParseStage =================== */ -static qboolean ParseStage( shaderStage_t *stage, const char **text ) -{ +static qboolean ParseStage(shaderStage_t *stage, const char **text) { char *token; int depthMaskBits = GLS_DEPTHMASK_TRUE, blendSrcBits = 0, blendDstBits = 0, atestBits = 0, depthFuncBits = 0; qboolean depthMaskExplicit = qfalse; stage->active = true; - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: no matching '}' found\n" ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: no matching '}' found\n"); return qfalse; } - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // // map // - else if ( !Q_stricmp( token, "map" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "map")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "$whiteimage" ) ) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[0].image = tr.whiteImage; continue; - } - else if ( !Q_stricmp( token, "$lightmap" ) ) - { + } else if (!Q_stricmp(token, "$lightmap")) { stage->bundle[0].isLightmap = true; - if ( shader.lightmapIndex[0] < 0 ) { + if (shader.lightmapIndex[0] < 0) { stage->bundle[0].image = tr.whiteImage; #ifndef FINAL_BUILD - //ri.Printf( PRINT_WARNING, "WARNING: $lightmap requested but none available '%s'\n", shader.name ); + // ri.Printf( PRINT_WARNING, "WARNING: $lightmap requested but none available '%s'\n", shader.name ); #endif } else { stage->bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; } continue; - } - else - { - stage->bundle[0].image = R_FindImageFile( - token, - (qboolean)!shader.noMipMaps, - (qboolean)!shader.noPicMip, - (qboolean)!shader.noTC, - GL_REPEAT ); - if ( !stage->bundle[0].image ) - { - ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + } else { + stage->bundle[0].image = R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_REPEAT); + if (!stage->bundle[0].image) { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1272,83 +1054,65 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // clampmap // - else if ( !Q_stricmp( token, "clampmap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "clampmap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name); return qfalse; } - stage->bundle[0].image = R_FindImageFile( - token, - (qboolean)!shader.noMipMaps, - (qboolean)!shader.noPicMip, - (qboolean)!shader.noTC, - GL_CLAMP ); - if ( !stage->bundle[0].image ) - { - ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + stage->bundle[0].image = R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_CLAMP); + if (!stage->bundle[0].image) { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } } // // animMap[/clampanimMap] .... // - else if ( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampanimMap" ) || !Q_stricmp( token, "oneshotanimMap" )) - { - #define MAX_IMAGE_ANIMATIONS 32 + else if (!Q_stricmp(token, "animMap") || !Q_stricmp(token, "clampanimMap") || !Q_stricmp(token, "oneshotanimMap")) { +#define MAX_IMAGE_ANIMATIONS 32 image_t *images[MAX_IMAGE_ANIMATIONS]; - bool bClamp = !Q_stricmp( token, "clampanimMap" ); - bool oneShot = !Q_stricmp( token, "oneshotanimMap" ); + bool bClamp = !Q_stricmp(token, "clampanimMap"); + bool oneShot = !Q_stricmp(token, "oneshotanimMap"); - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap":"clampanimMap"), shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap" : "clampanimMap"), shader.name); return qfalse; } - stage->bundle[0].imageAnimationSpeed = atof( token ); + stage->bundle[0].imageAnimationSpeed = atof(token); stage->bundle[0].oneShotAnimMap = oneShot; // parse up to MAX_IMAGE_ANIMATIONS animations - while ( 1 ) { - int num; + while (1) { + int num; - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { break; } num = stage->bundle[0].numImageAnimations; - if ( num < MAX_IMAGE_ANIMATIONS ) { - images[num] = R_FindImageFile( - token, - (qboolean)!shader.noMipMaps, - (qboolean)!shader.noPicMip, - (qboolean)!shader.noTC, - bClamp?GL_CLAMP:GL_REPEAT); - if ( !images[num] ) - { - ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + if (num < MAX_IMAGE_ANIMATIONS) { + images[num] = + R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, bClamp ? GL_CLAMP : GL_REPEAT); + if (!images[num]) { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } stage->bundle[0].numImageAnimations++; } } // Copy image ptrs into an array of ptrs - stage->bundle[0].image = (image_t*) R_Hunk_Alloc( stage->bundle[0].numImageAnimations * sizeof( image_t* ), qfalse ); - memcpy( stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof( image_t* ) ); - } - else if ( !Q_stricmp( token, "videoMap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name ); + stage->bundle[0].image = (image_t *)R_Hunk_Alloc(stage->bundle[0].numImageAnimations * sizeof(image_t *), qfalse); + memcpy(stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof(image_t *)); + } else if (!Q_stricmp(token, "videoMap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name); return qfalse; } - stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic( token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader), NULL); + stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic(token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader), NULL); if (stage->bundle[0].videoMapHandle != -1) { stage->bundle[0].isVideoMap = true; stage->bundle[0].image = tr.scratchImage[stage->bundle[0].videoMapHandle]; @@ -1357,329 +1121,242 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // alphafunc // - else if ( !Q_stricmp( token, "alphaFunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaFunc")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name); return qfalse; } - atestBits = NameToAFunc( token ); + atestBits = NameToAFunc(token); } // // depthFunc // - else if ( !Q_stricmp( token, "depthfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "depthfunc")) { + token = COM_ParseExt(text, qfalse); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name ); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "lequal" ) ) - { + if (!Q_stricmp(token, "lequal")) { depthFuncBits = 0; - } - else if ( !Q_stricmp( token, "equal" ) ) - { + } else if (!Q_stricmp(token, "equal")) { depthFuncBits = GLS_DEPTHFUNC_EQUAL; - } - else if ( !Q_stricmp( token, "disable" ) ) - { + } else if (!Q_stricmp(token, "disable")) { depthFuncBits = GLS_DEPTHTEST_DISABLE; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name); continue; } } // // detail // - else if ( !Q_stricmp( token, "detail" ) ) - { + else if (!Q_stricmp(token, "detail")) { stage->isDetail = true; } // // blendfunc // or blendfunc // - else if ( !Q_stricmp( token, "blendfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "blendfunc")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } // check for "simple" blends first - if ( !Q_stricmp( token, "add" ) ) { + if (!Q_stricmp(token, "add")) { blendSrcBits = GLS_SRCBLEND_ONE; blendDstBits = GLS_DSTBLEND_ONE; - } else if ( !Q_stricmp( token, "filter" ) ) { + } else if (!Q_stricmp(token, "filter")) { blendSrcBits = GLS_SRCBLEND_DST_COLOR; blendDstBits = GLS_DSTBLEND_ZERO; - } else if ( !Q_stricmp( token, "blend" ) ) { + } else if (!Q_stricmp(token, "blend")) { blendSrcBits = GLS_SRCBLEND_SRC_ALPHA; blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } else { // complex double blends - blendSrcBits = NameToSrcBlendMode( token ); + blendSrcBits = NameToSrcBlendMode(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } - blendDstBits = NameToDstBlendMode( token ); + blendDstBits = NameToDstBlendMode(token); } // clear depth mask for blended surfaces - if ( !depthMaskExplicit ) - { + if (!depthMaskExplicit) { depthMaskBits = 0; } } // // rgbGen // - else if ( !Q_stricmp( token, "rgbGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rgbGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->rgbWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->rgbWave); stage->rgbGen = CGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - vec3_t color; + } else if (!Q_stricmp(token, "const")) { + vec3_t color; - VectorClear( color ); + VectorClear(color); - ParseVector( text, 3, color ); + ParseVector(text, 3, color); stage->constantColor[0] = 255 * color[0]; stage->constantColor[1] = 255 * color[1]; stage->constantColor[2] = 255 * color[2]; stage->rgbGen = CGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->rgbGen = CGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "identityLighting" ) ) - { + } else if (!Q_stricmp(token, "identityLighting")) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->rgbGen = CGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->rgbGen = CGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { - if (shader.lightmapIndex[0] == LIGHTMAP_NONE) - { - ri.Printf( PRINT_ERROR, "ERROR: rgbGen vertex used on a model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "vertex")) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { + ri.Printf(PRINT_ERROR, "ERROR: rgbGen vertex used on a model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_VERTEX; - if ( stage->alphaGen == 0 ) { + if (stage->alphaGen == 0) { stage->alphaGen = AGEN_VERTEX; } - } - else if ( !Q_stricmp( token, "exactVertex" ) ) - { + } else if (!Q_stricmp(token, "exactVertex")) { stage->rgbGen = CGEN_EXACT_VERTEX; - } - else if ( !Q_stricmp( token, "lightingDiffuse" ) ) - { - if (shader.lightmapIndex[0] != LIGHTMAP_NONE) - { - ri.Printf( PRINT_ERROR, "ERROR: rgbGen lightingDiffuse used on a misc_model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "lightingDiffuse")) { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) { + ri.Printf(PRINT_ERROR, "ERROR: rgbGen lightingDiffuse used on a misc_model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_LIGHTING_DIFFUSE; - } - else if ( !Q_stricmp( token, "lightingDiffuseEntity" ) ) - { - if (shader.lightmapIndex[0] != LIGHTMAP_NONE) - { - ri.Printf( PRINT_ERROR, "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "lightingDiffuseEntity")) { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) { + ri.Printf(PRINT_ERROR, "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->rgbGen = CGEN_ONE_MINUS_VERTEX; - } - else - { - ri.Printf( PRINT_ERROR, "ERROR: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ERROR, "ERROR: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // alphaGen // - else if ( !Q_stricmp( token, "alphaGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->alphaWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->alphaWave); stage->alphaGen = AGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - token = COM_ParseExt( text, qfalse ); - stage->constantColor[3] = 255 * atof( token ); + } else if (!Q_stricmp(token, "const")) { + token = COM_ParseExt(text, qfalse); + stage->constantColor[3] = 255 * atof(token); stage->alphaGen = AGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->alphaGen = AGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->alphaGen = AGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->alphaGen = AGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->alphaGen = AGEN_VERTEX; - } - else if ( !Q_stricmp( token, "lightingSpecular" ) ) - { + } else if (!Q_stricmp(token, "lightingSpecular")) { stage->alphaGen = AGEN_LIGHTING_SPECULAR; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->alphaGen = AGEN_ONE_MINUS_VERTEX; - } - else if ( !Q_stricmp( token, "dot" ) ) - { + } else if (!Q_stricmp(token, "dot")) { stage->alphaGen = AGEN_DOT; - } - else if ( !Q_stricmp( token, "oneMinusDot" ) ) - { + } else if (!Q_stricmp(token, "oneMinusDot")) { stage->alphaGen = AGEN_ONE_MINUS_DOT; - } - else if ( !Q_stricmp( token, "portal" ) ) - { + } else if (!Q_stricmp(token, "portal")) { stage->alphaGen = AGEN_PORTAL; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { shader.portalRange = 256; - ri.Printf( PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name ); - } - else - { - shader.portalRange = atof( token ); + ri.Printf(PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name); + } else { + shader.portalRange = atof(token); } - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // tcGen // - else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "texgen") || !Q_stricmp(token, "tcGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "environment" ) ) - { + if (!Q_stricmp(token, "environment")) { stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED; - } - else if ( !Q_stricmp( token, "lightmap" ) ) - { + } else if (!Q_stricmp(token, "lightmap")) { stage->bundle[0].tcGen = TCGEN_LIGHTMAP; - } - else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) ) - { + } else if (!Q_stricmp(token, "texture") || !Q_stricmp(token, "base")) { stage->bundle[0].tcGen = TCGEN_TEXTURE; - } - else if ( !Q_stricmp( token, "vector" ) ) - { - stage->bundle[0].tcGenVectors = ( vec3_t *) R_Hunk_Alloc( 2 * sizeof( vec3_t ), qfalse ); + } else if (!Q_stricmp(token, "vector")) { + stage->bundle[0].tcGenVectors = (vec3_t *)R_Hunk_Alloc(2 * sizeof(vec3_t), qfalse); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] ); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[0]); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[1]); stage->bundle[0].tcGen = TCGEN_VECTOR; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name); } } // // tcMod <...> // - else if ( !Q_stricmp( token, "tcMod" ) ) - { + else if (!Q_stricmp(token, "tcMod")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseTexMod( buffer, stage ); + ParseTexMod(buffer, stage); continue; } // // depthmask // - else if ( !Q_stricmp( token, "depthwrite" ) ) - { + else if (!Q_stricmp(token, "depthwrite")) { depthMaskBits = GLS_DEPTHMASK_TRUE; depthMaskExplicit = qtrue; continue; } // If this stage has glow... - else if ( Q_stricmp( token, "glow" ) == 0 ) - { + else if (Q_stricmp(token, "glow") == 0) { stage->glow = true; continue; @@ -1687,20 +1364,18 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // surfaceSprites ... // - else if ( !Q_stricmp( token, "surfaceSprites" ) ) - { + else if (!Q_stricmp(token, "surfaceSprites")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSprites( buffer, stage ); + ParseSurfaceSprites(buffer, stage); continue; } @@ -1717,28 +1392,25 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // ssGrow // ssWeather // - else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS + else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS { char buffer[1024] = ""; char param[128]; - strcpy(param,token); + strcpy(param, token); - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSpritesOptional( param, buffer, stage ); + ParseSurfaceSpritesOptional(param, buffer, stage); continue; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1746,31 +1418,26 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // if cgen isn't explicitly specified, use either identity or identitylighting // - if ( stage->rgbGen == CGEN_BAD ) { - if ( //blendSrcBits == 0 || - blendSrcBits == GLS_SRCBLEND_ONE || - blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) { + if (stage->rgbGen == CGEN_BAD) { + if ( // blendSrcBits == 0 || + blendSrcBits == GLS_SRCBLEND_ONE || blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; } else { stage->rgbGen = CGEN_IDENTITY; } } - // // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending // - if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && - ( blendDstBits == GLS_DSTBLEND_ZERO ) ) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ZERO)) { blendDstBits = blendSrcBits = 0; depthMaskBits = GLS_DEPTHMASK_TRUE; } // decide which agens we can skip - if ( stage->alphaGen == AGEN_IDENTITY ) { - if ( stage->rgbGen == CGEN_IDENTITY - || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) { + if (stage->alphaGen == AGEN_IDENTITY) { + if (stage->rgbGen == CGEN_IDENTITY || stage->rgbGen == CGEN_LIGHTING_DIFFUSE) { stage->alphaGen = AGEN_SKIP; } } @@ -1778,10 +1445,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // compute state bits // - stage->stateBits = depthMaskBits | - blendSrcBits | blendDstBits | - atestBits | - depthFuncBits; + stage->stateBits = depthMaskBits | blendSrcBits | blendDstBits | atestBits | depthFuncBits; return qtrue; } @@ -1800,149 +1464,136 @@ deformVertexes autoSprite2 deformVertexes text[0-7] =============== */ -static void ParseDeform( const char **text ) { - char *token; - deformStage_t *ds; +static void ParseDeform(const char **text) { + char *token; + deformStage_t *ds; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name); return; } - if ( shader.numDeforms == MAX_SHADER_DEFORMS ) { - ri.Printf( PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name ); + if (shader.numDeforms == MAX_SHADER_DEFORMS) { + ri.Printf(PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name); return; } - shader.deforms[ shader.numDeforms ] = (deformStage_t *)R_Hunk_Alloc( sizeof( deformStage_t ), qtrue ); + shader.deforms[shader.numDeforms] = (deformStage_t *)R_Hunk_Alloc(sizeof(deformStage_t), qtrue); - ds = shader.deforms[ shader.numDeforms ]; + ds = shader.deforms[shader.numDeforms]; shader.numDeforms++; - if ( !Q_stricmp( token, "projectionShadow" ) ) { + if (!Q_stricmp(token, "projectionShadow")) { ds->deformation = DEFORM_PROJECTION_SHADOW; return; } - if ( !Q_stricmp( token, "autosprite" ) ) { + if (!Q_stricmp(token, "autosprite")) { ds->deformation = DEFORM_AUTOSPRITE; return; } - if ( !Q_stricmp( token, "autosprite2" ) ) { + if (!Q_stricmp(token, "autosprite2")) { ds->deformation = DEFORM_AUTOSPRITE2; return; } - if ( !Q_stricmpn( token, "text", 4 ) ) { - int n; + if (!Q_stricmpn(token, "text", 4)) { + int n; n = token[4] - '0'; - if ( n < 0 || n > 7 ) { + if (n < 0 || n > 7) { n = 0; } - ds->deformation = (deform_t) (DEFORM_TEXT0 + n); + ds->deformation = (deform_t)(DEFORM_TEXT0 + n); return; } - if ( !Q_stricmp( token, "bulge" ) ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "bulge")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeWidth = atof( token ); + ds->bulgeWidth = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeHeight = atof( token ); + ds->bulgeHeight = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeSpeed = atof( token ); + ds->bulgeSpeed = atof(token); ds->deformation = DEFORM_BULGE; return; } - if ( !Q_stricmp( token, "wave" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "wave")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - if ( atof( token ) != 0 ) - { - ds->deformationSpread = 1.0f / atof( token ); - } - else - { + if (atof(token) != 0) { + ds->deformationSpread = 1.0f / atof(token); + } else { ds->deformationSpread = 100.0f; - ri.Printf( PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_WAVE; return; } - if ( !Q_stricmp( token, "normal" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "normal")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.amplitude = atof( token ); + ds->deformationWave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.frequency = atof( token ); + ds->deformationWave.frequency = atof(token); ds->deformation = DEFORM_NORMALS; return; } - if ( !Q_stricmp( token, "move" ) ) { - int i; + if (!Q_stricmp(token, "move")) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + for (i = 0; i < 3; i++) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->moveVector[i] = atof( token ); + ds->moveVector[i] = atof(token); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_MOVE; return; } - ri.Printf( PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name); } - /* =============== ParseSkyParms @@ -1950,28 +1601,28 @@ ParseSkyParms skyParms =============== */ -static void ParseSkyParms( const char **text ) { - char *token; - const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; - char pathname[MAX_QPATH]; - int i; +static void ParseSkyParms(const char **text) { + char *token; + const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; + char pathname[MAX_QPATH]; + int i; - shader.sky = (skyParms_t *)R_Hunk_Alloc( sizeof( skyParms_t ), qtrue ); + shader.sky = (skyParms_t *)R_Hunk_Alloc(sizeof(skyParms_t), qtrue); // outerbox - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name); return; } - if ( strcmp( token, "-" ) ) { - for (i=0 ; i<6 ; i++) { - Com_sprintf( pathname, sizeof(pathname), "%s_%s", token, suf[i] ); - shader.sky->outerbox[i] = R_FindImageFile( ( char * ) pathname, qtrue, qtrue, (qboolean)!shader.noTC, GL_CLAMP ); - if ( !shader.sky->outerbox[i] ) { + if (strcmp(token, "-")) { + for (i = 0; i < 6; i++) { + Com_sprintf(pathname, sizeof(pathname), "%s_%s", token, suf[i]); + shader.sky->outerbox[i] = R_FindImageFile((char *)pathname, qtrue, qtrue, (qboolean)!shader.noTC, GL_CLAMP); + if (!shader.sky->outerbox[i]) { if (i) { - shader.sky->outerbox[i] = shader.sky->outerbox[i-1];//not found, so let's use the previous image - }else{ + shader.sky->outerbox[i] = shader.sky->outerbox[i - 1]; // not found, so let's use the previous image + } else { shader.sky->outerbox[i] = tr.defaultImage; } } @@ -1979,123 +1630,117 @@ static void ParseSkyParms( const char **text ) { } // cloudheight - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name); return; } - shader.sky->cloudHeight = atof( token ); - if ( !shader.sky->cloudHeight ) { + shader.sky->cloudHeight = atof(token); + if (!shader.sky->cloudHeight) { shader.sky->cloudHeight = 512; } - R_InitSkyTexCoords( shader.sky->cloudHeight ); + R_InitSkyTexCoords(shader.sky->cloudHeight); // innerbox - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "-" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "-")) { + ri.Printf(PRINT_WARNING, "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); } } - /* ================= ParseSort ================= */ -void ParseSort( const char **text ) -{ - char *token; +void ParseSort(const char **text) { + char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name); return; } - if ( !Q_stricmp( token, "portal" ) ) { + if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; - } else if ( !Q_stricmp( token, "sky" ) ) { + } else if (!Q_stricmp(token, "sky")) { shader.sort = SS_ENVIRONMENT; - } else if ( !Q_stricmp( token, "opaque" ) ) { + } else if (!Q_stricmp(token, "opaque")) { shader.sort = SS_OPAQUE; - } else if ( !Q_stricmp( token, "decal" ) ) { + } else if (!Q_stricmp(token, "decal")) { shader.sort = SS_DECAL; - } else if ( !Q_stricmp( token, "seeThrough" ) ) { + } else if (!Q_stricmp(token, "seeThrough")) { shader.sort = SS_SEE_THROUGH; - } else if ( !Q_stricmp( token, "banner" ) ) { + } else if (!Q_stricmp(token, "banner")) { shader.sort = SS_BANNER; - } else if ( !Q_stricmp( token, "additive" ) ) { + } else if (!Q_stricmp(token, "additive")) { shader.sort = SS_BLEND1; - } else if ( !Q_stricmp( token, "nearest" ) ) { + } else if (!Q_stricmp(token, "nearest")) { shader.sort = SS_NEAREST; - } else if ( !Q_stricmp( token, "underwater" ) ) { + } else if (!Q_stricmp(token, "underwater")) { shader.sort = SS_UNDERWATER; - } else if ( !Q_stricmp( token, "inside" ) ) { + } else if (!Q_stricmp(token, "inside")) { shader.sort = SS_INSIDE; - } else if ( !Q_stricmp( token, "mid_inside" ) ) { + } else if (!Q_stricmp(token, "mid_inside")) { shader.sort = SS_MID_INSIDE; - } else if ( !Q_stricmp( token, "middle" ) ) { + } else if (!Q_stricmp(token, "middle")) { shader.sort = SS_MIDDLE; - } else if ( !Q_stricmp( token, "mid_outside" ) ) { + } else if (!Q_stricmp(token, "mid_outside")) { shader.sort = SS_MID_OUTSIDE; - } else if ( !Q_stricmp( token, "outside" ) ) { + } else if (!Q_stricmp(token, "outside")) { shader.sort = SS_OUTSIDE; - } - else - { - shader.sort = atof( token ); + } else { + shader.sort = atof(token); } } - // this table is also present in q3map typedef struct infoParm_s { - const char *name; - uint32_t clearSolid, surfaceFlags, contents; + const char *name; + uint32_t clearSolid, surfaceFlags, contents; } infoParm_t; -infoParm_t infoParms[] = { +infoParm_t infoParms[] = { // Game content Flags - { "nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE }, // special hack to clear solid flag - { "nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE }, // special hack to clear opaque flag - { "lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA }, // very damaging - { "slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME }, // mildly damaging - { "water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER }, // - { "fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering - { "shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP }, // block shots, but not people - { "playerclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP }, // block only the player - { "monsterclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP }, // - { "botclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP }, // for bots - { "trigger", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER }, // - { "nodrop", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc) - { "terrain", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN }, // use special terrain collsion - { "ladder", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER }, // climb up in it like water - { "abseil", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL }, // can abseil down this brush - { "outside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE }, // volume is considered to be in the outside (i.e. not indoors) - { "inside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE }, // volume is considered to be inside (i.e. indoors) - - { "detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL }, // don't include in structural bsp - { "trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT }, // surface has an alpha component + {"nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE}, // special hack to clear solid flag + {"nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE}, // special hack to clear opaque flag + {"lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA}, // very damaging + {"slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME}, // mildly damaging + {"water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER}, // + {"fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering + {"shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP}, // block shots, but not people + {"playerclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP}, // block only the player + {"monsterclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP}, // + {"botclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP}, // for bots + {"trigger", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER}, // + {"nodrop", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP}, // don't drop items or leave bodies (death fog, lava, etc) + {"terrain", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN}, // use special terrain collsion + {"ladder", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER}, // climb up in it like water + {"abseil", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL}, // can abseil down this brush + {"outside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE}, // volume is considered to be in the outside (i.e. not indoors) + {"inside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE}, // volume is considered to be inside (i.e. indoors) + + {"detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL}, // don't include in structural bsp + {"trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT}, // surface has an alpha component /* Game surface flags */ - { "sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE }, // emit light from an environment map - { "slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE }, // - - { "nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE }, // - { "noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE }, // don't make impact explosions or marks - { "nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE }, // don't make impact marks, but still explode - { "nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE }, // don't generate a drawsurface (or a lightmap) - { "nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE }, // - { "nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE }, // don't ever add dynamic lights - { "metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE }, // - { "nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE }, // No misc ents on this surface - { "forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE }, // - { "forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE }, // only visible with force sight + {"sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE}, // emit light from an environment map + {"slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE}, // + + {"nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE}, // + {"noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE}, // don't make impact explosions or marks + {"nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE}, // don't make impact marks, but still explode + {"nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE}, // don't generate a drawsurface (or a lightmap) + {"nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE}, // + {"nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE}, // don't ever add dynamic lights + {"metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE}, // + {"nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE}, // No misc ents on this surface + {"forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE}, // + {"forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE}, // only visible with force sight }; - /* =============== ParseSurfaceParm @@ -2103,14 +1748,14 @@ ParseSurfaceParm surfaceparm =============== */ -static void ParseSurfaceParm( const char **text ) { - char *token; - int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); - int i; - - token = COM_ParseExt( text, qfalse ); - for ( i = 0 ; i < numInfoParms ; i++ ) { - if ( !Q_stricmp( token, infoParms[i].name ) ) { +static void ParseSurfaceParm(const char **text) { + char *token; + int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); + int i; + + token = COM_ParseExt(text, qfalse); + for (i = 0; i < numInfoParms; i++) { + if (!Q_stricmp(token, infoParms[i].name)) { shader.surfaceFlags |= infoParms[i].surfaceFlags; shader.contentFlags |= infoParms[i].contents; shader.contentFlags &= infoParms[i].clearSolid; @@ -2124,34 +1769,26 @@ static void ParseSurfaceParm( const char **text ) { ParseMaterial ================= */ -const char *materialNames[MATERIAL_LAST] = -{ - MATERIALS -}; +const char *materialNames[MATERIAL_LAST] = {MATERIALS}; -static void ParseMaterial( const char **text ) -{ - char *token; - int i; +static void ParseMaterial(const char **text) { + char *token; + int i; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf( S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name); return; } - for(i = 0; i < MATERIAL_LAST; i++) - { - if ( !Q_stricmp( token, materialNames[i] ) ) - { - shader.surfaceFlags &= ~MATERIAL_MASK;//safety, clear it first + for (i = 0; i < MATERIAL_LAST; i++) { + if (!Q_stricmp(token, materialNames[i])) { + shader.surfaceFlags &= ~MATERIAL_MASK; // safety, clear it first shader.surfaceFlags |= i; break; } } } - /* ================= ParseShader @@ -2161,168 +1798,144 @@ shader. Parse it into the global shader variable. Later functions will optimize it. ================= */ -static qboolean ParseShader( const char **text ) -{ +static qboolean ParseShader(const char **text) { char *token; const char *begin = *text; int s = 0; COM_BeginParseSession(); - - token = COM_ParseExt( text, qtrue ); - if ( token[0] != '{' ) - { - ri.Printf( PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name ); + token = COM_ParseExt(text, qtrue); + if (token[0] != '{') { + ri.Printf(PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name); COM_EndParseSession(); return qfalse; } - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name); COM_EndParseSession(); return qfalse; } // end of shader definition - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // stage definition - else if ( token[0] == '{' ) - { - if ( s >= MAX_SHADER_STAGES ) { - ri.Printf( PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES ); + else if (token[0] == '{') { + if (s >= MAX_SHADER_STAGES) { + ri.Printf(PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES); COM_EndParseSession(); return qfalse; } - if ( !ParseStage( &stages[s], text ) ) - { + if (!ParseStage(&stages[s], text)) { COM_EndParseSession(); return qfalse; } stages[s].active = true; - if ( stages[s].glow ) - { + if (stages[s].glow) { shader.hasGlow = true; } s++; continue; } // skip stuff that only the QuakeEdRadient needs - else if ( !Q_stricmpn( token, "qer", 3 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "qer", 3)) { + SkipRestOfLine(text); continue; } // material deprecated as of 11 Jan 01 // material undeprecated as of 7 May 01 - q3map_material deprecated - else if ( !Q_stricmp( token, "material" ) || !Q_stricmp( token, "q3map_material" ) ) - { - ParseMaterial( text ); + else if (!Q_stricmp(token, "material") || !Q_stricmp(token, "q3map_material")) { + ParseMaterial(text); } // sun parms - else if ( !Q_stricmp( token, "sun" ) || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunLight[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[1] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[2] = atof( token ); - - VectorNormalize( tr.sunLight ); - - token = COM_ParseExt( text, qfalse ); - float a = atof( token ); - VectorScale( tr.sunLight, a, tr.sunLight); - - token = COM_ParseExt( text, qfalse ); - a = atof( token ); + else if (!Q_stricmp(token, "sun") || !Q_stricmp(token, "q3map_sun") || !Q_stricmp(token, "q3map_sunExt")) { + token = COM_ParseExt(text, qfalse); + tr.sunLight[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[1] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[2] = atof(token); + + VectorNormalize(tr.sunLight); + + token = COM_ParseExt(text, qfalse); + float a = atof(token); + VectorScale(tr.sunLight, a, tr.sunLight); + + token = COM_ParseExt(text, qfalse); + a = atof(token); a = a / 180 * M_PI; - token = COM_ParseExt( text, qfalse ); - float b = atof( token ); + token = COM_ParseExt(text, qfalse); + float b = atof(token); b = b / 180 * M_PI; - tr.sunDirection[0] = cos( a ) * cos( b ); - tr.sunDirection[1] = sin( a ) * cos( b ); - tr.sunDirection[2] = sin( b ); + tr.sunDirection[0] = cos(a) * cos(b); + tr.sunDirection[1] = sin(a) * cos(b); + tr.sunDirection[2] = sin(b); - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // q3map_surfacelight deprecated as of 16 Jul 01 - else if ( !Q_stricmp( token, "surfacelight" ) || !Q_stricmp( token, "q3map_surfacelight" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunSurfaceLight = atoi( token ); - } - else if ( !Q_stricmp( token, "lightColor" ) ) - { + else if (!Q_stricmp(token, "surfacelight") || !Q_stricmp(token, "q3map_surfacelight")) { + token = COM_ParseExt(text, qfalse); + tr.sunSurfaceLight = atoi(token); + } else if (!Q_stricmp(token, "lightColor")) { /* if ( !ParseVector( text, 3, tr.sunAmbient ) ) { return qfalse; } */ - //SP skips this so I'm skipping it here too. - SkipRestOfLine( text ); + // SP skips this so I'm skipping it here too. + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "deformvertexes" ) || !Q_stricmp( token, "deform" )) { - ParseDeform( text ); + } else if (!Q_stricmp(token, "deformvertexes") || !Q_stricmp(token, "deform")) { + ParseDeform(text); continue; - } - else if ( !Q_stricmp( token, "tesssize" ) ) { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "tesssize")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "clampTime" ) ) { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "clampTime")) { + SkipRestOfLine(text); } // skip stuff that only the q3map needs - else if ( !Q_stricmpn( token, "q3map", 5 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "q3map", 5)) { + SkipRestOfLine(text); continue; } // skip stuff that only q3map or the server needs - else if ( !Q_stricmp( token, "surfaceParm" ) ) { - ParseSurfaceParm( text ); + else if (!Q_stricmp(token, "surfaceParm")) { + ParseSurfaceParm(text); continue; } // no mip maps - else if ( !Q_stricmp( token, "nomipmaps" ) ) - { + else if (!Q_stricmp(token, "nomipmaps")) { shader.noMipMaps = true; shader.noPicMip = true; continue; } // no picmip adjustment - else if ( !Q_stricmp( token, "nopicmip" ) ) - { + else if (!Q_stricmp(token, "nopicmip")) { shader.noPicMip = true; continue; - } - else if ( !Q_stricmp( token, "noglfog" ) ) - { + } else if (!Q_stricmp(token, "noglfog")) { shader.fogPass = FP_NONE; continue; } // polygonOffset - else if ( !Q_stricmp( token, "polygonOffset" ) ) - { + else if (!Q_stricmp(token, "polygonOffset")) { shader.polygonOffset = true; continue; - } - else if ( !Q_stricmp( token, "noTC" ) ) - { + } else if (!Q_stricmp(token, "noTC")) { shader.noTC = true; continue; } @@ -2330,116 +1943,99 @@ static qboolean ParseShader( const char **text ) // to be merged into one batch. This is a savings for smoke // puffs and blood, but can't be used for anything where the // shader calcs (not the surface function) reference the entity color or scroll - else if ( !Q_stricmp( token, "entityMergable" ) ) - { + else if (!Q_stricmp(token, "entityMergable")) { shader.entityMergable = true; continue; } // fogParms - else if ( !Q_stricmp( token, "fogParms" ) ) - { - shader.fogParms = (fogParms_t *)R_Hunk_Alloc( sizeof( fogParms_t ), qtrue ); - if ( !ParseVector( text, 3, shader.fogParms->color ) ) { + else if (!Q_stricmp(token, "fogParms")) { + shader.fogParms = (fogParms_t *)R_Hunk_Alloc(sizeof(fogParms_t), qtrue); + if (!ParseVector(text, 3, shader.fogParms->color)) { COM_EndParseSession(); return qfalse; } - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name); continue; } - shader.fogParms->depthForOpaque = atof( token ); + shader.fogParms->depthForOpaque = atof(token); // skip any old gradient directions - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // portal - else if ( !Q_stricmp(token, "portal") ) - { + else if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; continue; } // skyparms - else if ( !Q_stricmp( token, "skyparms" ) ) - { - ParseSkyParms( text ); + else if (!Q_stricmp(token, "skyparms")) { + ParseSkyParms(text); continue; } // light determines flaring in q3map, not needed here - else if ( !Q_stricmp(token, "light") ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "light")) { + token = COM_ParseExt(text, qfalse); continue; } // cull - else if ( !Q_stricmp( token, "cull") ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "cull")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) ) - { + if (!Q_stricmp(token, "none") || !Q_stricmp(token, "twosided") || !Q_stricmp(token, "disable")) { shader.cullType = CT_TWO_SIDED; - } - else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) ) - { + } else if (!Q_stricmp(token, "back") || !Q_stricmp(token, "backside") || !Q_stricmp(token, "backsided")) { shader.cullType = CT_BACK_SIDED; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name); } continue; } // sort - else if ( !Q_stricmp( token, "sort" ) ) - { - ParseSort( text ); + else if (!Q_stricmp(token, "sort")) { + ParseSort(text); continue; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // // location hit mesh load // - else if ( !Q_stricmp( token, "hitLocation" ) ) - { + else if (!Q_stricmp(token, "hitLocation")) { // grab the filename of the hit location texture - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; continue; } // // location hit material mesh load // - else if ( !Q_stricmp( token, "hitMaterial" ) ) - { + else if (!Q_stricmp(token, "hitMaterial")) { // grab the filename of the hit location texture - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; continue; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name ); + else { + ri.Printf(PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name); COM_EndParseSession(); return qfalse; } @@ -2448,7 +2044,7 @@ Ghoul2 Insert End // // ignore shaders that don't have any stages, unless it is a sky or fog // - if ( s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG ) ) { + if (s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG)) { COM_EndParseSession(); return qfalse; } @@ -2463,10 +2059,8 @@ Ghoul2 Insert End // We match against the retail version of gfx/2d/wedge by calculating the // hash value of the shader text, and comparing it against a precalculated // value. - uint32_t shaderHash = generateHashValueForText( begin, *text - begin ); - if ( shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && - Q_stricmp( shader.name, "gfx/2d/wedge" ) == 0 ) - { + uint32_t shaderHash = generateHashValueForText(begin, *text - begin); + if (shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && Q_stricmp(shader.name, "gfx/2d/wedge") == 0) { stages[0].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); stages[0].stateBits |= GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } @@ -2478,11 +2072,9 @@ Ghoul2 Insert End // functioned because rgbGen identity doesn't work with setcolor. // // We match against retail version of gfx/menus/radar/arrow_w by calculating - // the hash value of the shader text, and comparing it against a + // the hash value of the shader text, and comparing it against a // precalculated value. - if ( shaderHash == RETAIL_ARROW_W_SHADER_HASH && - Q_stricmp( shader.name, "gfx/menus/radar/arrow_w" ) == 0 ) - { + if (shaderHash == RETAIL_ARROW_W_SHADER_HASH && Q_stricmp(shader.name, "gfx/menus/radar/arrow_w") == 0) { stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; } @@ -2501,43 +2093,34 @@ SHADER OPTIMIZATION AND FOGGING */ typedef struct { - int blendA; - int blendB; + int blendA; + int blendB; - int multitextureEnv; - int multitextureBlend; + int multitextureEnv; + int multitextureBlend; } collapse_t; -static collapse_t collapse[] = { - { 0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, 0 }, +static collapse_t collapse[] = { + {0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, 0}, - { 0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, 0 }, + {0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, 0}, - { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { 0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, - GL_ADD, 0 }, + {0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GL_ADD, 0}, - { GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, - GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE }, + {GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE}, #if 0 { 0, GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_SRCBLEND_SRC_ALPHA, GL_DECAL, 0 }, #endif - { -1 } -}; + {-1}}; /* ================ @@ -2547,17 +2130,17 @@ Attempt to combine two stages into a single multitexture stage FIXME: I think modulated add + modulated add collapses incorrectly ================= */ -static qboolean CollapseMultitexture( void ) { +static qboolean CollapseMultitexture(void) { int abits, bbits; int i; textureBundle_t tmpBundle; - if ( !qglActiveTextureARB ) { + if (!qglActiveTextureARB) { return qfalse; } // make sure both stages are active - if ( !stages[0].active || !stages[1].active ) { + if (!stages[0].active || !stages[1].active) { return qfalse; } @@ -2565,85 +2148,70 @@ static qboolean CollapseMultitexture( void ) { bbits = stages[1].stateBits; // make sure that both stages have identical state other than blend modes - if ( ( abits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) != - ( bbits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) ) { + if ((abits & ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE)) != (bbits & ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE))) { return qfalse; } - abits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); - bbits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + abits &= (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); + bbits &= (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); // search for a valid multitexture blend function - for ( i = 0; collapse[i].blendA != -1 ; i++ ) { - if ( abits == collapse[i].blendA - && bbits == collapse[i].blendB ) { + for (i = 0; collapse[i].blendA != -1; i++) { + if (abits == collapse[i].blendA && bbits == collapse[i].blendB) { break; } } // nothing found - if ( collapse[i].blendA == -1 ) { + if (collapse[i].blendA == -1) { return qfalse; } // GL_ADD is a separate extension - if ( collapse[i].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable ) { + if (collapse[i].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable) { return qfalse; } // make sure waveforms have identical parameters - if (( stages[0].rgbGen != stages[1].rgbGen ) || - ( stages[0].alphaGen != stages[1].alphaGen ) ) { + if ((stages[0].rgbGen != stages[1].rgbGen) || (stages[0].alphaGen != stages[1].alphaGen)) { return qfalse; } // an add collapse can only have identity colors - if ( collapse[i].multitextureEnv == GL_ADD && stages[0].rgbGen != CGEN_IDENTITY ) { + if (collapse[i].multitextureEnv == GL_ADD && stages[0].rgbGen != CGEN_IDENTITY) { return qfalse; } - if ( stages[0].rgbGen == CGEN_WAVEFORM ) - { - if ( memcmp( &stages[0].rgbWave, - &stages[1].rgbWave, - sizeof( stages[0].rgbWave ) ) ) - { + if (stages[0].rgbGen == CGEN_WAVEFORM) { + if (memcmp(&stages[0].rgbWave, &stages[1].rgbWave, sizeof(stages[0].rgbWave))) { return qfalse; } } - if ( stages[0].alphaGen == AGEN_WAVEFORM ) - { - if ( memcmp( &stages[0].alphaWave, - &stages[1].alphaWave, - sizeof( stages[0].alphaWave ) ) ) - { + if (stages[0].alphaGen == AGEN_WAVEFORM) { + if (memcmp(&stages[0].alphaWave, &stages[1].alphaWave, sizeof(stages[0].alphaWave))) { return qfalse; } } - // make sure that lightmaps are in bundle 1 for 3dfx - if ( stages[0].bundle[0].isLightmap ) - { + if (stages[0].bundle[0].isLightmap) { tmpBundle = stages[0].bundle[0]; stages[0].bundle[0] = stages[1].bundle[0]; stages[0].bundle[1] = tmpBundle; - } - else - { + } else { stages[0].bundle[1] = stages[1].bundle[0]; } // set the new blend state bits shader.multitextureEnv = collapse[i].multitextureEnv; - stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + stages[0].stateBits &= ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); stages[0].stateBits |= collapse[i].multitextureBlend; // // move down subsequent shaders // - memmove( &stages[1], &stages[2], sizeof( stages[0] ) * ( MAX_SHADER_STAGES - 2 ) ); - memset( &stages[MAX_SHADER_STAGES-1], 0, sizeof( stages[0] ) ); + memmove(&stages[1], &stages[2], sizeof(stages[0]) * (MAX_SHADER_STAGES - 2)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(stages[0])); return qtrue; } @@ -2763,84 +2331,80 @@ shaders. Sets shader->sortedIndex ============== */ -static void SortNewShader( void ) { - int i; - float sort; - shader_t *newShader; +static void SortNewShader(void) { + int i; + float sort; + shader_t *newShader; - newShader = tr.shaders[ tr.numShaders - 1 ]; + newShader = tr.shaders[tr.numShaders - 1]; sort = newShader->sort; - for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) { - if ( tr.sortedShaders[ i ]->sort <= sort ) { + for (i = tr.numShaders - 2; i >= 0; i--) { + if (tr.sortedShaders[i]->sort <= sort) { break; } - tr.sortedShaders[i+1] = tr.sortedShaders[i]; - tr.sortedShaders[i+1]->sortedIndex++; + tr.sortedShaders[i + 1] = tr.sortedShaders[i]; + tr.sortedShaders[i + 1]->sortedIndex++; } // Arnout: fix rendercommandlist // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 - //FixRenderCommandList( i+1 ); + // FixRenderCommandList( i+1 ); - newShader->sortedIndex = i+1; - tr.sortedShaders[i+1] = newShader; + newShader->sortedIndex = i + 1; + tr.sortedShaders[i + 1] = newShader; } - /* ==================== GeneratePermanentShader ==================== */ -static shader_t *GeneratePermanentShader( void ) { - shader_t *newShader; - int i, b; - int size; +static shader_t *GeneratePermanentShader(void) { + shader_t *newShader; + int i, b; + int size; - if ( tr.numShaders == MAX_SHADERS ) { + if (tr.numShaders == MAX_SHADERS) { tr.iNumDeniedShaders++; - ri.Printf( PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS (%d) hit (overflowed by %d)\n", MAX_SHADERS, tr.iNumDeniedShaders); + ri.Printf(PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS (%d) hit (overflowed by %d)\n", MAX_SHADERS, tr.iNumDeniedShaders); return tr.defaultShader; } - newShader = (shader_t *)R_Hunk_Alloc( sizeof( shader_t ), qtrue ); + newShader = (shader_t *)R_Hunk_Alloc(sizeof(shader_t), qtrue); *newShader = shader; - if ( shader.sort <= /*SS_OPAQUE*/SS_SEE_THROUGH ) { + if (shader.sort <= /*SS_OPAQUE*/ SS_SEE_THROUGH) { newShader->fogPass = FP_EQUAL; - } else if ( shader.contentFlags & CONTENTS_FOG ) { + } else if (shader.contentFlags & CONTENTS_FOG) { newShader->fogPass = FP_LE; } - tr.shaders[ tr.numShaders ] = newShader; + tr.shaders[tr.numShaders] = newShader; newShader->index = tr.numShaders; - tr.sortedShaders[ tr.numShaders ] = newShader; + tr.sortedShaders[tr.numShaders] = newShader; newShader->sortedIndex = tr.numShaders; tr.numShaders++; - size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof( stages[0] ) : sizeof( stages[0] ); - newShader->stages = (shaderStage_t *) R_Hunk_Alloc( size, qtrue ); + size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof(stages[0]) : sizeof(stages[0]); + newShader->stages = (shaderStage_t *)R_Hunk_Alloc(size, qtrue); - for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) { - if ( !stages[i].active ) { + for (i = 0; i < newShader->numUnfoggedPasses; i++) { + if (!stages[i].active) { break; } newShader->stages[i] = stages[i]; - for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) { - if (newShader->stages[i].bundle[b].numTexMods) - { - size = newShader->stages[i].bundle[b].numTexMods * sizeof( texModInfo_t ); - newShader->stages[i].bundle[b].texMods = (texModInfo_t *) R_Hunk_Alloc( size, qfalse ); - memcpy( newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size ); - } - else - { - newShader->stages[i].bundle[b].texMods = 0; //clear the globabl ptr jic + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { + if (newShader->stages[i].bundle[b].numTexMods) { + size = newShader->stages[i].bundle[b].numTexMods * sizeof(texModInfo_t); + newShader->stages[i].bundle[b].texMods = (texModInfo_t *)R_Hunk_Alloc(size, qfalse); + memcpy(newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size); + } else { + newShader->stages[i].bundle[b].texMods = 0; // clear the globabl ptr jic } } } @@ -2865,57 +2429,56 @@ what it is supposed to look like. OUTPUT: Number of stages after the collapse (in the case of surfacesprites this isn't one). ================= */ -static int VertexLightingCollapse( void ) { - int stage, nextopenstage; - shaderStage_t *bestStage; - int bestImageRank; - int rank; - int finalstagenum=1; +static int VertexLightingCollapse(void) { + int stage, nextopenstage; + shaderStage_t *bestStage; + int bestImageRank; + int rank; + int finalstagenum = 1; // if we aren't opaque, just use the first pass - if ( shader.sort == SS_OPAQUE ) { + if (shader.sort == SS_OPAQUE) { // pick the best texture for the single pass bestStage = &stages[0]; bestImageRank = -999999; - for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) { + for (stage = 0; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } rank = 0; - if ( pStage->bundle[0].isLightmap ) { + if (pStage->bundle[0].isLightmap) { rank -= 100; } - if ( pStage->bundle[0].tcGen != TCGEN_TEXTURE ) { + if (pStage->bundle[0].tcGen != TCGEN_TEXTURE) { rank -= 5; } - if ( pStage->bundle[0].numTexMods ) { + if (pStage->bundle[0].numTexMods) { rank -= 5; } - if ( pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING ) { + if (pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING) { rank -= 3; } // SurfaceSprites are most certainly NOT desireable as the collapsed surface texture. - if ( pStage->ss && pStage->ss->surfaceSpriteType) - { + if (pStage->ss && pStage->ss->surfaceSpriteType) { rank -= 1000; } - if ( rank > bestImageRank ) { + if (rank > bestImageRank) { bestImageRank = rank; bestStage = pStage; } } stages[0].bundle[0] = bestStage->bundle[0]; - stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + stages[0].stateBits &= ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); stages[0].stateBits |= GLS_DEPTHMASK_TRUE; - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; } else { stages[0].rgbGen = CGEN_EXACT_VERTEX; @@ -2923,36 +2486,34 @@ static int VertexLightingCollapse( void ) { stages[0].alphaGen = AGEN_SKIP; } else { // don't use a lightmap (tesla coils) - if ( stages[0].bundle[0].isLightmap ) { + if (stages[0].bundle[0].isLightmap) { stages[0] = stages[1]; } // if we were in a cross-fade cgen, hack it to normal - if ( stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY ) { + if (stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } - if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH ) - && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH ) ) { + if ((stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH) && + (stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH)) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } - if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH ) - && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH ) ) { + if ((stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH) && + (stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH)) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } } - for ( stage=1, nextopenstage=1; stage < MAX_SHADER_STAGES; stage++ ) { + for (stage = 1, nextopenstage = 1; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } - if (pStage->ss && pStage->ss->surfaceSpriteType) - { + if (pStage->ss && pStage->ss->surfaceSpriteType) { // Copy this stage to the next open stage list (that is, we don't want any inactive stages before this one) - if (nextopenstage != stage) - { + if (nextopenstage != stage) { stages[nextopenstage] = *pStage; stages[nextopenstage].bundle[0] = pStage->bundle[0]; } @@ -2961,7 +2522,7 @@ static int VertexLightingCollapse( void ) { continue; } - memset( pStage, 0, sizeof( *pStage ) ); + memset(pStage, 0, sizeof(*pStage)); } return finalstagenum; @@ -2975,98 +2536,83 @@ Returns a freshly allocated shader with all the needed info from the current global working shader ========================= */ -static shader_t *FinishShader( void ) { - int stage, lmStage, stageIndex; - qboolean hasLightmapStage; +static shader_t *FinishShader(void) { + int stage, lmStage, stageIndex; + qboolean hasLightmapStage; hasLightmapStage = qfalse; // // set sky stuff appropriate // - if ( shader.sky ) { + if (shader.sky) { shader.sort = SS_ENVIRONMENT; } // // set polygon offset // - if ( shader.polygonOffset && !shader.sort ) { + if (shader.polygonOffset && !shader.sort) { shader.sort = SS_DECAL; } - for(lmStage=0;lmStageactive && pStage->bundle[0].isLightmap) - { + if (pStage->active && pStage->bundle[0].isLightmap) { break; } } - if (lmStage < MAX_SHADER_STAGES) - { - if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) - { - if (lmStage == 0) //< MAX_SHADER_STAGES-1) - {//copy the rest down over the lightmap slot - memmove(&stages[lmStage], &stages[lmStage+1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES-lmStage-1)); - memset(&stages[MAX_SHADER_STAGES-1], 0, sizeof(shaderStage_t)); - //change blending on the moved down stage + if (lmStage < MAX_SHADER_STAGES) { + if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { + if (lmStage == 0) //< MAX_SHADER_STAGES-1) + { // copy the rest down over the lightmap slot + memmove(&stages[lmStage], &stages[lmStage + 1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES - lmStage - 1)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(shaderStage_t)); + // change blending on the moved down stage stages[lmStage].stateBits = GLS_DEFAULT; } - //change anything that was moved down (or the *white if LM is first) to use vertex color + // change anything that was moved down (or the *white if LM is first) to use vertex color stages[lmStage].rgbGen = CGEN_EXACT_VERTEX; stages[lmStage].alphaGen = AGEN_SKIP; - lmStage = MAX_SHADER_STAGES; //skip the style checking below + lmStage = MAX_SHADER_STAGES; // skip the style checking below } } - if (lmStage < MAX_SHADER_STAGES)// && !r_fullbright->value) + if (lmStage < MAX_SHADER_STAGES) // && !r_fullbright->value) { - int numStyles; - int i; + int numStyles; + int i; - for(numStyles=0;numStyles= LS_UNUSED) - { + for (numStyles = 0; numStyles < MAXLIGHTMAPS; numStyles++) { + if (shader.styles[numStyles] >= LS_UNUSED) { break; } } numStyles--; - if (numStyles > 0) - { - for(i=MAX_SHADER_STAGES-1;i>lmStage+numStyles;i--) - { - stages[i] = stages[i-numStyles]; + if (numStyles > 0) { + for (i = MAX_SHADER_STAGES - 1; i > lmStage + numStyles; i--) { + stages[i] = stages[i - numStyles]; } - for(i=0;iactive ) { + if (!pStage->active) { break; } // check for a missing texture - if ( !pStage->bundle[0].image ) { - ri.Printf( PRINT_WARNING, "Shader %s has a stage with no image\n", shader.name ); + if (!pStage->bundle[0].image) { + ri.Printf(PRINT_WARNING, "Shader %s has a stage with no image\n", shader.name); pStage->active = false; stage++; continue; @@ -3092,21 +2638,21 @@ static shader_t *FinishShader( void ) { // // ditch this stage if it's detail and detail textures are disabled // - if ( pStage->isDetail && !r_detailTextures->integer ) { + if (pStage->isDetail && !r_detailTextures->integer) { int index; - for ( index = stage + 1; indexbundle[0].isLightmap ) { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].isLightmap) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_LIGHTMAP; } hasLightmapStage = qtrue; } else { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_TEXTURE; } } @@ -3131,8 +2677,7 @@ static shader_t *FinishShader( void ) { // // determine sort order and fog color adjustment // - if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) && - ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) { + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) && (stages[0].stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS))) { int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS; int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS; @@ -3143,89 +2688,65 @@ static shader_t *FinishShader( void ) { // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA // modulate, additive - if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) || - ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) { + if (((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) || + ((blendSrcBits == GLS_SRCBLEND_ZERO) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR))) { pStage->adjustColorsForFog = ACFF_MODULATE_RGB; } // strict blend - else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA; } // premultiplied alpha - else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_RGBA; } else { // we can't adjust this one correctly, so it won't be exactly correct in fog } // don't screw with sort order if this is a portal or environment - if ( !shader.sort ) { + if (!shader.sort) { // see through item, like a grill or grate - if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) - { + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) { shader.sort = SS_SEE_THROUGH; - } - else - { - if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) - { + } else { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) { // GL_ONE GL_ONE needs to come a bit later shader.sort = SS_BLEND1; - } - else - { + } else { shader.sort = SS_BLEND0; } } } } - //rww - begin hw fog - if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) - { + // rww - begin hw fog + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_ONE) && - pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE) && + pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && stage) - { // + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && stage) { // pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES-1 && - stages[stage+1].bundle[0].isLightmap) - { // multiple light map blending + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES - 1 && + stages[stage + 1].bundle[0].isLightmap) { // multiple light map blending pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO) && pStage->bundle[0].isLightmap) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO) && + pStage->bundle[0].isLightmap) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else - { + } else { pStage->mGLFogColorOverride = GLFOGOVERRIDE_NONE; } - //rww - end hw fog + // rww - end hw fog stageIndex++; stage++; @@ -3233,14 +2754,14 @@ static shader_t *FinishShader( void ) { // there are times when you will need to manually apply a sort to // opaque alpha tested shaders that have later blend passes - if ( !shader.sort ) { + if (!shader.sort) { shader.sort = SS_OPAQUE; } // // if we are in r_vertexLight mode, never use a lightmap texture // - if ( stage > 1 && ( r_vertexLight->integer ) ) { + if (stage > 1 && (r_vertexLight->integer)) { stage = VertexLightingCollapse(); hasLightmapStage = qfalse; } @@ -3248,24 +2769,23 @@ static shader_t *FinishShader( void ) { // // look for multitexture potential // - if ( stage > 1 && CollapseMultitexture() ) { + if (stage > 1 && CollapseMultitexture()) { stage--; } - if ( shader.lightmapIndex[0] >= 0 && !hasLightmapStage ) { - ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name ); + if (shader.lightmapIndex[0] >= 0 && !hasLightmapStage) { + ri.Printf(PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name); memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); memcpy(shader.styles, stylesDefault, sizeof(shader.styles)); } - // // compute number of passes // shader.numUnfoggedPasses = stage; // fogonly shaders don't have any normal passes - if ( stage == 0 ) { + if (stage == 0) { shader.sort = SS_FOG; } @@ -3286,18 +2806,18 @@ return NULL if not found If found, it will return a valid shader ===================== */ -static const char *FindShaderInShaderText( const char *shadername ) { +static const char *FindShaderInShaderText(const char *shadername) { char *p = s_shaderText; - if ( !p ) { + if (!p) { return NULL; } #ifdef USE_STL_FOR_SHADER_LOOKUPS char sLowerCaseName[MAX_QPATH]; - Q_strncpyz(sLowerCaseName,shadername,sizeof(sLowerCaseName)); - Q_strlwr(sLowerCaseName); // Q_strlwr is pretty gay, so I'm not using it + Q_strncpyz(sLowerCaseName, shadername, sizeof(sLowerCaseName)); + Q_strlwr(sLowerCaseName); // Q_strlwr is pretty gay, so I'm not using it return ShaderEntryPtrs_Lookup(sLowerCaseName); @@ -3308,21 +2828,21 @@ static const char *FindShaderInShaderText( const char *shadername ) { // look for label // note that this could get confused if a shader name is used inside // another shader definition - while ( 1 ) { + while (1) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( token[0] == '{' ) { + if (token[0] == '{') { // skip the definition - SkipBracedSection( &p ); - } else if ( !Q_stricmp( token, shadername ) ) { + SkipBracedSection(&p); + } else if (!Q_stricmp(token, shadername)) { return p; } else { // skip to end of line - SkipRestOfLine( &p ); + SkipRestOfLine(&p); } } @@ -3331,25 +2851,19 @@ static const char *FindShaderInShaderText( const char *shadername ) { #endif } -inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) -{ - int i; +inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) { + int i; - if (Q_stricmp(sh->name, name)) - { + if (Q_stricmp(sh->name, name)) { return qfalse; } - if (!sh->defaultShader) - { - for(i=0;ilightmapIndex[i] != lightmapIndex[i]) - { + if (!sh->defaultShader) { + for (i = 0; i < MAXLIGHTMAPS; i++) { + if (sh->lightmapIndex[i] != lightmapIndex[i]) { return qfalse; } - if (sh->styles[i] != styles[i]) - { + if (sh->styles[i] != styles[i]) { return qfalse; } } @@ -3365,23 +2879,21 @@ given a (potentially erroneous) lightmap index, attempts to load an external lightmap image and/or sets the index to a valid number =============== */ -#define EXTERNAL_LIGHTMAP "lm_%04d.tga" // THIS MUST BE IN SYNC WITH Q3MAP2 -static inline const int *R_FindLightmap( const int *lightmapIndex ) -{ - image_t *image; - char fileName[ MAX_QPATH ]; +#define EXTERNAL_LIGHTMAP "lm_%04d.tga" // THIS MUST BE IN SYNC WITH Q3MAP2 +static inline const int *R_FindLightmap(const int *lightmapIndex) { + image_t *image; + char fileName[MAX_QPATH]; // don't bother with vertex lighting - if( *lightmapIndex < 0 ) + if (*lightmapIndex < 0) return lightmapIndex; // does this lightmap already exist? - if( *lightmapIndex < tr.numLightmaps && tr.lightmaps[ *lightmapIndex ] != NULL ) + if (*lightmapIndex < tr.numLightmaps && tr.lightmaps[*lightmapIndex] != NULL) return lightmapIndex; // bail if no world dir - if( tr.worldDir[0] == '\0' ) - { + if (tr.worldDir[0] == '\0') { return lightmapsVertex; } @@ -3389,17 +2901,16 @@ static inline const int *R_FindLightmap( const int *lightmapIndex ) R_IssuePendingRenderCommands(); // // attempt to load an external lightmap - Com_sprintf( fileName, sizeof(fileName), "%s/" EXTERNAL_LIGHTMAP, tr.worldDir, *lightmapIndex ); - image = R_FindImageFile( fileName, qfalse, qfalse, (qboolean)(r_ext_compressed_lightmaps->integer != 0), GL_CLAMP ); - if( image == NULL ) - { + Com_sprintf(fileName, sizeof(fileName), "%s/" EXTERNAL_LIGHTMAP, tr.worldDir, *lightmapIndex); + image = R_FindImageFile(fileName, qfalse, qfalse, (qboolean)(r_ext_compressed_lightmaps->integer != 0), GL_CLAMP); + if (image == NULL) { return lightmapsVertex; } // add it to the lightmap list - if( *lightmapIndex >= tr.numLightmaps ) + if (*lightmapIndex >= tr.numLightmaps) tr.numLightmaps = *lightmapIndex + 1; - tr.lightmaps[ *lightmapIndex ] = image; + tr.lightmaps[*lightmapIndex] = image; return lightmapIndex; } @@ -3430,43 +2941,42 @@ and src*dest blending applied with the texture, as apropriate for most world construction surfaces. =============== */ -shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ) { - char strippedName[MAX_QPATH]; - int hash; - const char *shaderText; - image_t *image; - shader_t *sh; - - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( S_COLOR_RED"Shader name exceeds MAX_QPATH! %s\n",name ); +shader_t *R_FindShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + int hash; + const char *shaderText; + image_t *image; + shader_t *sh; + + if (strlen(name) >= MAX_QPATH) { + Com_Printf(S_COLOR_RED "Shader name exceeds MAX_QPATH! %s\n", name); return tr.defaultShader; } - if ( name[0] == 0 ) { + if (name[0] == 0) { return tr.defaultShader; } // use (fullbright) vertex lighting if the bsp file doesn't have // lightmaps -/* if ( lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps ) { - lightmapIndex = lightmapsVertex; - } -*/ + /* if ( lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps ) { + lightmapIndex = lightmapsVertex; + } + */ lightmapIndex = R_FindLightmap(lightmapIndex); - COM_StripExtension( name, strippedName, sizeof(strippedName) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName); // // see if the shader is already loaded // - for (sh=sh_hashTable[hash]; sh; sh=sh->next) { + for (sh = sh_hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, strippedName, lightmapIndex, styles)) - { // match found + if (IsShader(sh, strippedName, lightmapIndex, styles)) { // match found return sh; } } @@ -3484,9 +2994,9 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // // attempt to define shader from an explicit parameter file // - shaderText = FindShaderInShaderText( strippedName ); - if ( shaderText ) { - if ( !ParseShader( &shaderText ) ) { + shaderText = FindShaderInShaderText(strippedName); + if (shaderText) { + if (!ParseShader(&shaderText)) { // had errors, so use default shader shader.defaultShader = true; } @@ -3494,16 +3004,14 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * return sh; } - // // if not defined in the in-memory shader descriptions, // look for a single TGA, BMP, or PCX // - image = R_FindImageFile( name, mipRawImage, mipRawImage, qtrue, mipRawImage ? GL_REPEAT : GL_CLAMP ); - if ( !image ) { - if (strncmp(name, "levelshots", 10 ) && strcmp(name, "*off")) - { //hide these warnings - ri.Printf( PRINT_WARNING, "WARNING: Couldn't find image for shader %s\n", name ); + image = R_FindImageFile(name, mipRawImage, mipRawImage, qtrue, mipRawImage ? GL_REPEAT : GL_CLAMP); + if (!image) { + if (strncmp(name, "levelshots", 10) && strcmp(name, "*off")) { // hide these warnings + ri.Printf(PRINT_WARNING, "WARNING: Couldn't find image for shader %s\n", name); } shader.defaultShader = true; return FinishShader(); @@ -3512,29 +3020,27 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // // create the default shading commands // - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image = image; stages[0].active = true; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image = image; stages[0].active = true; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image = image; stages[0].active = true; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image = tr.whiteImage; stages[0].active = true; @@ -3550,10 +3056,10 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * stages[0].bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; stages[0].bundle[0].isLightmap = true; stages[0].active = true; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight - // light map 0 should always be style 0, which means - // that this will always be on + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight + // light map 0 should always be style 0, which means + // that this will always be on stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image = image; @@ -3576,24 +3082,23 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShader( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShader(const char *name) { + shader_t *sh; - sh = R_FindShader( name, lightmaps2d, stylesDefault, qtrue ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShaderNoMip @@ -3601,24 +3106,23 @@ RE_RegisterShaderNoMip For menu graphics that should never be picmiped ==================== */ -qhandle_t RE_RegisterShaderNoMip( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShaderNoMip(const char *name) { + shader_t *sh; - sh = R_FindShader( name, lightmaps2d, stylesDefault, qfalse ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qfalse); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== R_GetShaderByHandle @@ -3627,13 +3131,13 @@ When a handle is passed in by another module, this range checks it and returns a valid (possibly default) shader_t to be used internally. ==================== */ -shader_t *R_GetShaderByHandle( qhandle_t hShader ) { - if ( hShader < 0 ) { - ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); +shader_t *R_GetShaderByHandle(qhandle_t hShader) { + if (hShader < 0) { + ri.Printf(PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } - if ( hShader >= tr.numShaders ) { - ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + if (hShader >= tr.numShaders) { + ri.Printf(PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } return tr.shaders[hShader]; @@ -3647,107 +3151,99 @@ Dump information on all valid shaders to the console A second parameter will cause it to print in sorted order =============== */ -void R_ShaderList_f (void) { - int i; - int count; - shader_t *shader; +void R_ShaderList_f(void) { + int i; + int count; + shader_t *shader; - ri.Printf (PRINT_ALL, "-----------------------\n"); + ri.Printf(PRINT_ALL, "-----------------------\n"); count = 0; - for ( i = 0 ; i < tr.numShaders ; i++ ) { - if ( ri.Cmd_Argc() > 1 ) { + for (i = 0; i < tr.numShaders; i++) { + if (ri.Cmd_Argc() > 1) { shader = tr.sortedShaders[i]; } else { shader = tr.shaders[i]; } - ri.Printf( PRINT_ALL, "%i ", shader->numUnfoggedPasses ); + ri.Printf(PRINT_ALL, "%i ", shader->numUnfoggedPasses); - if (shader->lightmapIndex[0] >= 0 ) { - ri.Printf (PRINT_ALL, "L "); + if (shader->lightmapIndex[0] >= 0) { + ri.Printf(PRINT_ALL, "L "); } else { - ri.Printf (PRINT_ALL, " "); - } - if ( shader->multitextureEnv == GL_ADD ) { - ri.Printf( PRINT_ALL, "MT(a) " ); - } else if ( shader->multitextureEnv == GL_MODULATE ) { - ri.Printf( PRINT_ALL, "MT(m) " ); - } else if ( shader->multitextureEnv == GL_DECAL ) { - ri.Printf( PRINT_ALL, "MT(d) " ); + ri.Printf(PRINT_ALL, " "); + } + if (shader->multitextureEnv == GL_ADD) { + ri.Printf(PRINT_ALL, "MT(a) "); + } else if (shader->multitextureEnv == GL_MODULATE) { + ri.Printf(PRINT_ALL, "MT(m) "); + } else if (shader->multitextureEnv == GL_DECAL) { + ri.Printf(PRINT_ALL, "MT(d) "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->explicitlyDefined ) { - ri.Printf( PRINT_ALL, "E " ); + if (shader->explicitlyDefined) { + ri.Printf(PRINT_ALL, "E "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->sky ) - { - ri.Printf( PRINT_ALL, "sky " ); + if (shader->sky) { + ri.Printf(PRINT_ALL, "sky "); } else { - ri.Printf( PRINT_ALL, "gen " ); + ri.Printf(PRINT_ALL, "gen "); } - if ( shader->defaultShader ) { - ri.Printf (PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); + if (shader->defaultShader) { + ri.Printf(PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); } else { - ri.Printf (PRINT_ALL, ": %s\n", shader->name); + ri.Printf(PRINT_ALL, ": %s\n", shader->name); } count++; } - ri.Printf (PRINT_ALL, "%i total shaders\n", count); - ri.Printf (PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "%i total shaders\n", count); + ri.Printf(PRINT_ALL, "------------------\n"); } - - #ifdef USE_STL_FOR_SHADER_LOOKUPS // setup my STL shortcut list as to where all the shaders are, saves re-parsing every line for every .TGA request. // -static void SetupShaderEntryPtrs(void) -{ +static void SetupShaderEntryPtrs(void) { const char *p = s_shaderText; char *token; - ShaderEntryPtrs_Clear(); // extra safe, though done elsewhere already + ShaderEntryPtrs_Clear(); // extra safe, though done elsewhere already - if ( !p ) + if (!p) return; // FIXED this nasty little bugger --eez COM_BeginParseSession(); - while (1) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - break; // EOF + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) + break; // EOF - if ( token[0] == '{' ) // '}' // counterbrace for matching + if (token[0] == '{') // '}' // counterbrace for matching { - SkipBracedSection( &p ); - } - else - { - Q_strlwr(token); // token is always a ptr to com_token here, not the original buffer. - // (Not that it matters, except for reasons of speed by not strlwr'ing the whole buffer) + SkipBracedSection(&p); + } else { + Q_strlwr(token); // token is always a ptr to com_token here, not the original buffer. + // (Not that it matters, except for reasons of speed by not strlwr'ing the whole buffer) // token = a string of this shader name, p = ptr within s_shadertext it's found at, so store it... // - ShaderEntryPtrs_Insert(token,p); - SkipRestOfLine( &p ); // now legally skip over this name and go get the next one + ShaderEntryPtrs_Insert(token, p); + SkipRestOfLine(&p); // now legally skip over this name and go get the next one } } - COM_EndParseSession( ); + COM_EndParseSession(); - //ri.Printf( PRINT_DEVELOPER, "SetupShaderEntryPtrs(): Stored %d shader ptrs\n",ShaderEntryPtrs_Size() ); + // ri.Printf( PRINT_DEVELOPER, "SetupShaderEntryPtrs(): Stored %d shader ptrs\n",ShaderEntryPtrs_Size() ); } #endif - /* ==================== ScanAndLoadShaderFiles @@ -3756,9 +3252,8 @@ Finds and loads all .shader files, combining them into a single large text block that can be scanned for shader names ===================== */ -#define MAX_SHADER_FILES 4096 -static void ScanAndLoadShaderFiles( void ) -{ +#define MAX_SHADER_FILES 4096 +static void ScanAndLoadShaderFiles(void) { char **shaderFiles; char *buffers[MAX_SHADER_FILES]; char *textEnd; @@ -3767,59 +3262,56 @@ static void ScanAndLoadShaderFiles( void ) long sum = 0, summand; // scan for shader files - shaderFiles = ri.FS_ListFiles( "shaders", ".shader", &numShaderFiles ); + shaderFiles = ri.FS_ListFiles("shaders", ".shader", &numShaderFiles); - if ( !shaderFiles || !numShaderFiles ) - { - ri.Error( ERR_FATAL, "WARNING: no shader files found\n" ); + if (!shaderFiles || !numShaderFiles) { + ri.Error(ERR_FATAL, "WARNING: no shader files found\n"); return; } - if ( numShaderFiles > MAX_SHADER_FILES ) { + if (numShaderFiles > MAX_SHADER_FILES) { numShaderFiles = MAX_SHADER_FILES; } // load and store shader files - for ( i = 0; i < numShaderFiles; i++ ) - { + for (i = 0; i < numShaderFiles; i++) { char filename[MAX_QPATH]; - Com_sprintf( filename, sizeof( filename ), "shaders/%s", shaderFiles[i] ); - //ri.Printf( PRINT_DEVELOPER, "...loading '%s'\n", filename ); - // Looks like stripping out crap in the shaders will save about 200k - summand = ri.FS_ReadFile( filename, (void **)&buffers[i] ); - if ( !buffers[i] ) - ri.Error( ERR_DROP, "Couldn't load %s", filename ); + Com_sprintf(filename, sizeof(filename), "shaders/%s", shaderFiles[i]); + // ri.Printf( PRINT_DEVELOPER, "...loading '%s'\n", filename ); + // Looks like stripping out crap in the shaders will save about 200k + summand = ri.FS_ReadFile(filename, (void **)&buffers[i]); + if (!buffers[i]) + ri.Error(ERR_DROP, "Couldn't load %s", filename); - if ( buffers[i] ) + if (buffers[i]) sum += summand; } // build single large buffer - s_shaderText = (char *) R_Hunk_Alloc( sum + numShaderFiles*2, qtrue ); + s_shaderText = (char *)R_Hunk_Alloc(sum + numShaderFiles * 2, qtrue); s_shaderText[0] = '\0'; textEnd = s_shaderText; // free in reverse order, so the temp files are all dumped - for ( i = numShaderFiles - 1; i >= 0 ; i-- ) - { - if ( !buffers[i] ) + for (i = numShaderFiles - 1; i >= 0; i--) { + if (!buffers[i]) continue; - strcat( textEnd, buffers[i] ); - strcat( textEnd, "\n" ); - textEnd += strlen( textEnd ); - ri.FS_FreeFile( buffers[i] ); + strcat(textEnd, buffers[i]); + strcat(textEnd, "\n"); + textEnd += strlen(textEnd); + ri.FS_FreeFile(buffers[i]); } - COM_Compress( s_shaderText ); + COM_Compress(s_shaderText); // free up memory - ri.FS_FreeFileList( shaderFiles ); + ri.FS_FreeFileList(shaderFiles); - #ifdef USE_STL_FOR_SHADER_LOOKUPS +#ifdef USE_STL_FOR_SHADER_LOOKUPS SetupShaderEntryPtrs(); - #endif +#endif } /* @@ -3827,19 +3319,19 @@ static void ScanAndLoadShaderFiles( void ) CreateInternalShaders ==================== */ -static void CreateInternalShaders( void ) { +static void CreateInternalShaders(void) { tr.numShaders = 0; tr.iNumDeniedShaders = 0; // init the default shader - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "", sizeof(shader.name)); memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); memcpy(shader.styles, stylesDefault, sizeof(shader.styles)); - for ( int i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + for (int i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; } stages[0].bundle[0].image = tr.defaultImage; @@ -3848,12 +3340,12 @@ static void CreateInternalShaders( void ) { tr.defaultShader = FinishShader(); // shadow shader is just a marker - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); - shader.sort = SS_BANNER; //SS_STENCIL_SHADOW; + Q_strncpyz(shader.name, "", sizeof(shader.name)); + shader.sort = SS_BANNER; // SS_STENCIL_SHADOW; tr.shadowShader = FinishShader(); // distortion shader is just a marker - Q_strncpyz( shader.name, "internal_distortion", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "internal_distortion", sizeof(shader.name)); shader.sort = SS_BLEND0; shader.defaultShader = false; tr.distortionShader = FinishShader(); @@ -3862,10 +3354,10 @@ static void CreateInternalShaders( void ) { ARB_InitGlowShaders(); } -static void CreateExternalShaders( void ) { - tr.projectionShadowShader = R_FindShader( "projectionShadow", lightmapsNone, stylesDefault, qtrue ); +static void CreateExternalShaders(void) { + tr.projectionShadowShader = R_FindShader("projectionShadow", lightmapsNone, stylesDefault, qtrue); tr.projectionShadowShader->sort = SS_STENCIL_SHADOW; - tr.sunShader = R_FindShader( "sun", lightmapsVertex, stylesDefault, qtrue ); + tr.sunShader = R_FindShader("sun", lightmapsVertex, stylesDefault, qtrue); } /* @@ -3873,19 +3365,18 @@ static void CreateExternalShaders( void ) { R_InitShaders ================== */ -void R_InitShaders( void ) { - //ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); +void R_InitShaders(void) { + // ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); memset(sh_hashTable, 0, sizeof(sh_hashTable)); -/* -Ghoul2 Insert Start -*/ -// memset(hitMatReg, 0, sizeof(hitMatReg)); -// hitMatCount = 0; -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert Start + */ + // memset(hitMatReg, 0, sizeof(hitMatReg)); + // hitMatCount = 0; + /* + Ghoul2 Insert End + */ CreateInternalShaders(); diff --git a/code/rd-vanilla/tr_shadows.cpp b/code/rd-vanilla/tr_shadows.cpp index c0331e9763..f884ab2bef 100644 --- a/code/rd-vanilla/tr_shadows.cpp +++ b/code/rd-vanilla/tr_shadows.cpp @@ -39,44 +39,43 @@ along with this program; if not, see . #define _STENCIL_REVERSE typedef struct { - int i2; - int facing; + int i2; + int facing; } edgeDef_t; -#define MAX_EDGE_DEFS 32 +#define MAX_EDGE_DEFS 32 -static edgeDef_t edgeDefs[SHADER_MAX_VERTEXES][MAX_EDGE_DEFS]; -static int numEdgeDefs[SHADER_MAX_VERTEXES]; -static int facing[SHADER_MAX_INDEXES/3]; -static vec3_t shadowXyz[SHADER_MAX_VERTEXES]; +static edgeDef_t edgeDefs[SHADER_MAX_VERTEXES][MAX_EDGE_DEFS]; +static int numEdgeDefs[SHADER_MAX_VERTEXES]; +static int facing[SHADER_MAX_INDEXES / 3]; +static vec3_t shadowXyz[SHADER_MAX_VERTEXES]; +void R_AddEdgeDef(int i1, int i2, int facing) { + int c; -void R_AddEdgeDef( int i1, int i2, int facing ) { - int c; - - c = numEdgeDefs[ i1 ]; - if ( c == MAX_EDGE_DEFS ) { - return; // overflow + c = numEdgeDefs[i1]; + if (c == MAX_EDGE_DEFS) { + return; // overflow } - edgeDefs[ i1 ][ c ].i2 = i2; - edgeDefs[ i1 ][ c ].facing = facing; + edgeDefs[i1][c].i2 = i2; + edgeDefs[i1][c].facing = facing; - numEdgeDefs[ i1 ]++; + numEdgeDefs[i1]++; } -void R_RenderShadowEdges( void ) { - int i; - int c; - int j; - int i2; - //int c_edges, c_rejected; +void R_RenderShadowEdges(void) { + int i; + int c; + int j; + int i2; + // int c_edges, c_rejected; #if 0 int c2, k; int hit[2]; #endif #ifdef _STENCIL_REVERSE - int numTris; - int o1, o2, o3; + int numTris; + int o1, o2, o3; #endif // an edge is NOT a silhouette edge if its face doesn't face the light, @@ -88,44 +87,44 @@ void R_RenderShadowEdges( void ) { c_rejected = 0; #endif - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - c = numEdgeDefs[ i ]; - for ( j = 0 ; j < c ; j++ ) { - if ( !edgeDefs[ i ][ j ].facing ) { + for (i = 0; i < tess.numVertexes; i++) { + c = numEdgeDefs[i]; + for (j = 0; j < c; j++) { + if (!edgeDefs[i][j].facing) { continue; } - //with this system we can still get edges shared by more than 2 tris which - //produces artifacts including seeing the shadow through walls. So for now - //we are going to render all edges even though it is a tiny bit slower. -rww + // with this system we can still get edges shared by more than 2 tris which + // produces artifacts including seeing the shadow through walls. So for now + // we are going to render all edges even though it is a tiny bit slower. -rww #if 1 - i2 = edgeDefs[ i ][ j ].i2; - qglBegin( GL_TRIANGLE_STRIP ); - qglVertex3fv( tess.xyz[ i ] ); - qglVertex3fv( shadowXyz[ i ] ); - qglVertex3fv( tess.xyz[ i2 ] ); - qglVertex3fv( shadowXyz[ i2 ] ); + i2 = edgeDefs[i][j].i2; + qglBegin(GL_TRIANGLE_STRIP); + qglVertex3fv(tess.xyz[i]); + qglVertex3fv(shadowXyz[i]); + qglVertex3fv(tess.xyz[i2]); + qglVertex3fv(shadowXyz[i2]); qglEnd(); #else hit[0] = 0; hit[1] = 0; - i2 = edgeDefs[ i ][ j ].i2; - c2 = numEdgeDefs[ i2 ]; - for ( k = 0 ; k < c2 ; k++ ) { - if ( edgeDefs[ i2 ][ k ].i2 == i ) { - hit[ edgeDefs[ i2 ][ k ].facing ]++; + i2 = edgeDefs[i][j].i2; + c2 = numEdgeDefs[i2]; + for (k = 0; k < c2; k++) { + if (edgeDefs[i2][k].i2 == i) { + hit[edgeDefs[i2][k].facing]++; } } // if it doesn't share the edge with another front facing // triangle, it is a sil edge - if ( hit[ 1 ] == 0 ) { - qglBegin( GL_TRIANGLE_STRIP ); - qglVertex3fv( tess.xyz[ i ] ); - qglVertex3fv( shadowXyz[ i ] ); - qglVertex3fv( tess.xyz[ i2 ] ); - qglVertex3fv( shadowXyz[ i2 ] ); + if (hit[1] == 0) { + qglBegin(GL_TRIANGLE_STRIP); + qglVertex3fv(tess.xyz[i]); + qglVertex3fv(shadowXyz[i]); + qglVertex3fv(tess.xyz[i2]); + qglVertex3fv(shadowXyz[i2]); qglEnd(); c_edges++; } else { @@ -136,30 +135,28 @@ void R_RenderShadowEdges( void ) { } #ifdef _STENCIL_REVERSE - //Carmack Reverse method requires that volumes - //be capped properly -rww + // Carmack Reverse method requires that volumes + // be capped properly -rww numTris = tess.numIndexes / 3; - for ( i = 0 ; i < numTris ; i++ ) - { - if ( !facing[i] ) - { + for (i = 0; i < numTris; i++) { + if (!facing[i]) { continue; } - o1 = tess.indexes[ i*3 + 0 ]; - o2 = tess.indexes[ i*3 + 1 ]; - o3 = tess.indexes[ i*3 + 2 ]; + o1 = tess.indexes[i * 3 + 0]; + o2 = tess.indexes[i * 3 + 1]; + o3 = tess.indexes[i * 3 + 2]; qglBegin(GL_TRIANGLES); - qglVertex3fv(tess.xyz[o1]); - qglVertex3fv(tess.xyz[o2]); - qglVertex3fv(tess.xyz[o3]); + qglVertex3fv(tess.xyz[o1]); + qglVertex3fv(tess.xyz[o2]); + qglVertex3fv(tess.xyz[o3]); qglEnd(); qglBegin(GL_TRIANGLES); - qglVertex3fv(shadowXyz[o3]); - qglVertex3fv(shadowXyz[o2]); - qglVertex3fv(shadowXyz[o1]); + qglVertex3fv(shadowXyz[o3]); + qglVertex3fv(shadowXyz[o2]); + qglVertex3fv(shadowXyz[o1]); qglEnd(); } #endif @@ -179,9 +176,8 @@ triangleFromEdge[ v1 ][ v2 ] } ================= */ -void RB_DoShadowTessEnd( vec3_t lightPos ); -void RB_ShadowTessEnd( void ) -{ +void RB_DoShadowTessEnd(vec3_t lightPos); +void RB_ShadowTessEnd(void) { #if 0 if (backEnd.currentEntity && (backEnd.currentEntity->directedLight[0] || @@ -217,150 +213,134 @@ void RB_ShadowTessEnd( void ) RB_DoShadowTessEnd(dl->transformed); -#else //old ents-only way +#else // old ents-only way RB_DoShadowTessEnd(NULL); #endif } -void RB_DoShadowTessEnd( vec3_t lightPos ) -{ - int i; - int numTris; - vec3_t lightDir; +void RB_DoShadowTessEnd(vec3_t lightPos) { + int i; + int numTris; + vec3_t lightDir; - if ( glConfig.stencilBits < 4 ) { + if (glConfig.stencilBits < 4) { return; } -#if 1 //controlled method - try to keep shadows in range so they don't show through so much -rww - vec3_t worldxyz; - vec3_t entLight; - float groundDist; +#if 1 // controlled method - try to keep shadows in range so they don't show through so much -rww + vec3_t worldxyz; + vec3_t entLight; + float groundDist; - VectorCopy( backEnd.currentEntity->lightDir, entLight ); + VectorCopy(backEnd.currentEntity->lightDir, entLight); entLight[2] = 0.0f; VectorNormalize(entLight); - //Oh well, just cast them straight down no matter what onto the ground plane. - //This presets no chance of screwups and still looks better than a stupid - //shader blob. - VectorSet(lightDir, entLight[0]*0.3f, entLight[1]*0.3f, 1.0f); + // Oh well, just cast them straight down no matter what onto the ground plane. + // This presets no chance of screwups and still looks better than a stupid + // shader blob. + VectorSet(lightDir, entLight[0] * 0.3f, entLight[1] * 0.3f, 1.0f); // project vertexes away from light direction - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - //add or.origin to vert xyz to end up with world oriented coord, then figure - //out the ground pos for the vert to project the shadow volume to + for (i = 0; i < tess.numVertexes; i++) { + // add or.origin to vert xyz to end up with world oriented coord, then figure + // out the ground pos for the vert to project the shadow volume to VectorAdd(tess.xyz[i], backEnd.ori.origin, worldxyz); groundDist = worldxyz[2] - backEnd.currentEntity->e.shadowPlane; - groundDist += 16.0f; //fudge factor - VectorMA( tess.xyz[i], -groundDist, lightDir, shadowXyz[i] ); + groundDist += 16.0f; // fudge factor + VectorMA(tess.xyz[i], -groundDist, lightDir, shadowXyz[i]); } #else - if (lightPos) - { - for ( i = 0 ; i < tess.numVertexes ; i++ ) - { - shadowXyz[i][0] = tess.xyz[i][0]+(( tess.xyz[i][0]-lightPos[0] )*128.0f); - shadowXyz[i][1] = tess.xyz[i][1]+(( tess.xyz[i][1]-lightPos[1] )*128.0f); - shadowXyz[i][2] = tess.xyz[i][2]+(( tess.xyz[i][2]-lightPos[2] )*128.0f); + if (lightPos) { + for (i = 0; i < tess.numVertexes; i++) { + shadowXyz[i][0] = tess.xyz[i][0] + ((tess.xyz[i][0] - lightPos[0]) * 128.0f); + shadowXyz[i][1] = tess.xyz[i][1] + ((tess.xyz[i][1] - lightPos[1]) * 128.0f); + shadowXyz[i][2] = tess.xyz[i][2] + ((tess.xyz[i][2] - lightPos[2]) * 128.0f); } - } - else - { - VectorCopy( backEnd.currentEntity->lightDir, lightDir ); + } else { + VectorCopy(backEnd.currentEntity->lightDir, lightDir); // project vertexes away from light direction - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - VectorMA( tess.xyz[i], -512, lightDir, shadowXyz[i] ); + for (i = 0; i < tess.numVertexes; i++) { + VectorMA(tess.xyz[i], -512, lightDir, shadowXyz[i]); } } #endif // decide which triangles face the light - memset( numEdgeDefs, 0, 4 * tess.numVertexes ); + memset(numEdgeDefs, 0, 4 * tess.numVertexes); numTris = tess.numIndexes / 3; - for ( i = 0 ; i < numTris ; i++ ) { - int i1, i2, i3; - vec3_t d1, d2, normal; - float *v1, *v2, *v3; - float d; - - i1 = tess.indexes[ i*3 + 0 ]; - i2 = tess.indexes[ i*3 + 1 ]; - i3 = tess.indexes[ i*3 + 2 ]; - - v1 = tess.xyz[ i1 ]; - v2 = tess.xyz[ i2 ]; - v3 = tess.xyz[ i3 ]; - - if (!lightPos) - { - VectorSubtract( v2, v1, d1 ); - VectorSubtract( v3, v1, d2 ); - CrossProduct( d1, d2, normal ); - - d = DotProduct( normal, lightDir ); - } - else - { + for (i = 0; i < numTris; i++) { + int i1, i2, i3; + vec3_t d1, d2, normal; + float *v1, *v2, *v3; + float d; + + i1 = tess.indexes[i * 3 + 0]; + i2 = tess.indexes[i * 3 + 1]; + i3 = tess.indexes[i * 3 + 2]; + + v1 = tess.xyz[i1]; + v2 = tess.xyz[i2]; + v3 = tess.xyz[i3]; + + if (!lightPos) { + VectorSubtract(v2, v1, d1); + VectorSubtract(v3, v1, d2); + CrossProduct(d1, d2, normal); + + d = DotProduct(normal, lightDir); + } else { float planeEq[4]; - planeEq[0] = v1[1]*(v2[2]-v3[2]) + v2[1]*(v3[2]-v1[2]) + v3[1]*(v1[2]-v2[2]); - planeEq[1] = v1[2]*(v2[0]-v3[0]) + v2[2]*(v3[0]-v1[0]) + v3[2]*(v1[0]-v2[0]); - planeEq[2] = v1[0]*(v2[1]-v3[1]) + v2[0]*(v3[1]-v1[1]) + v3[0]*(v1[1]-v2[1]); - planeEq[3] = -( v1[0]*( v2[1]*v3[2] - v3[1]*v2[2] ) + - v2[0]*(v3[1]*v1[2] - v1[1]*v3[2]) + - v3[0]*(v1[1]*v2[2] - v2[1]*v1[2]) ); - - d = planeEq[0]*lightPos[0]+ - planeEq[1]*lightPos[1]+ - planeEq[2]*lightPos[2]+ - planeEq[3]; + planeEq[0] = v1[1] * (v2[2] - v3[2]) + v2[1] * (v3[2] - v1[2]) + v3[1] * (v1[2] - v2[2]); + planeEq[1] = v1[2] * (v2[0] - v3[0]) + v2[2] * (v3[0] - v1[0]) + v3[2] * (v1[0] - v2[0]); + planeEq[2] = v1[0] * (v2[1] - v3[1]) + v2[0] * (v3[1] - v1[1]) + v3[0] * (v1[1] - v2[1]); + planeEq[3] = -(v1[0] * (v2[1] * v3[2] - v3[1] * v2[2]) + v2[0] * (v3[1] * v1[2] - v1[1] * v3[2]) + v3[0] * (v1[1] * v2[2] - v2[1] * v1[2])); + + d = planeEq[0] * lightPos[0] + planeEq[1] * lightPos[1] + planeEq[2] * lightPos[2] + planeEq[3]; } - if ( d > 0 ) { - facing[ i ] = 1; + if (d > 0) { + facing[i] = 1; } else { - facing[ i ] = 0; + facing[i] = 0; } // create the edges - R_AddEdgeDef( i1, i2, facing[ i ] ); - R_AddEdgeDef( i2, i3, facing[ i ] ); - R_AddEdgeDef( i3, i1, facing[ i ] ); + R_AddEdgeDef(i1, i2, facing[i]); + R_AddEdgeDef(i2, i3, facing[i]); + R_AddEdgeDef(i3, i1, facing[i]); } - GL_Bind( tr.whiteImage ); - //qglEnable( GL_CULL_FACE ); - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); + GL_Bind(tr.whiteImage); + // qglEnable( GL_CULL_FACE ); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); #ifndef _DEBUG_STENCIL_SHADOWS - qglColor3f( 0.2f, 0.2f, 0.2f ); + qglColor3f(0.2f, 0.2f, 0.2f); // don't write to the color buffer - qglColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); + qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - qglEnable( GL_STENCIL_TEST ); - qglStencilFunc( GL_ALWAYS, 1, 255 ); + qglEnable(GL_STENCIL_TEST); + qglStencilFunc(GL_ALWAYS, 1, 255); #else - qglColor3f( 1.0f, 0.0f, 0.0f ); + qglColor3f(1.0f, 0.0f, 0.0f); qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - //qglDisable(GL_DEPTH_TEST); + // qglDisable(GL_DEPTH_TEST); #endif #ifdef _STENCIL_REVERSE qglDepthFunc(GL_LESS); - //now using the Carmack Reverse -rww - if (glConfig.doStencilShadowsInOneDrawcall) - { + // now using the Carmack Reverse -rww + if (glConfig.doStencilShadowsInOneDrawcall) { GL_Cull(CT_TWO_SIDED); qglStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_KEEP); qglStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_KEEP); R_RenderShadowEdges(); qglDisable(GL_STENCIL_TEST); - } - else - { + } else { GL_Cull(CT_FRONT_SIDED); qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP); @@ -375,38 +355,37 @@ void RB_DoShadowTessEnd( vec3_t lightPos ) qglDepthFunc(GL_LEQUAL); #else // mirrors have the culling order reversed - if ( backEnd.viewParms.isMirror ) { - qglCullFace( GL_FRONT ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR ); + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_FRONT); + qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); R_RenderShadowEdges(); - qglCullFace( GL_BACK ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR ); + qglCullFace(GL_BACK); + qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR); R_RenderShadowEdges(); } else { - qglCullFace( GL_BACK ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR ); + qglCullFace(GL_BACK); + qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); R_RenderShadowEdges(); - qglCullFace( GL_FRONT ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR ); + qglCullFace(GL_FRONT); + qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR); R_RenderShadowEdges(); } #endif // reenable writing to the color buffer - qglColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); + qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); #ifdef _DEBUG_STENCIL_SHADOWS qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif } - /* ================= RB_ShadowFinish @@ -417,11 +396,11 @@ because otherwise shadows from different body parts would overlap and double darken. ================= */ -void RB_ShadowFinish( void ) { - if ( r_shadows->integer != 2 ) { +void RB_ShadowFinish(void) { + if (r_shadows->integer != 2) { return; } - if ( glConfig.stencilBits < 4 ) { + if (glConfig.stencilBits < 4) { return; } @@ -429,69 +408,66 @@ void RB_ShadowFinish( void ) { return; #endif - qglEnable( GL_STENCIL_TEST ); - qglStencilFunc( GL_NOTEQUAL, 0, 255 ); + qglEnable(GL_STENCIL_TEST); + qglStencilFunc(GL_NOTEQUAL, 0, 255); - qglStencilOp( GL_KEEP, GL_KEEP, GL_KEEP ); + qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); bool planeZeroBack = false; - if (qglIsEnabled(GL_CLIP_PLANE0)) - { + if (qglIsEnabled(GL_CLIP_PLANE0)) { planeZeroBack = true; - qglDisable (GL_CLIP_PLANE0); + qglDisable(GL_CLIP_PLANE0); } GL_Cull(CT_TWO_SIDED); - //qglDisable (GL_CULL_FACE); + // qglDisable (GL_CULL_FACE); - GL_Bind( tr.whiteImage ); + GL_Bind(tr.whiteImage); qglPushMatrix(); - qglLoadIdentity (); + qglLoadIdentity(); -// qglColor3f( 0.6f, 0.6f, 0.6f ); -// GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO ); + // qglColor3f( 0.6f, 0.6f, 0.6f ); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO ); -// qglColor3f( 1, 0, 0 ); -// GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); + // qglColor3f( 1, 0, 0 ); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); - qglColor4f( 0.0f, 0.0f, 0.0f, 0.5f ); - //GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + qglColor4f(0.0f, 0.0f, 0.0f, 0.5f); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - qglBegin( GL_QUADS ); - qglVertex3f( -100, 100, -10 ); - qglVertex3f( 100, 100, -10 ); - qglVertex3f( 100, -100, -10 ); - qglVertex3f( -100, -100, -10 ); - qglEnd (); + qglBegin(GL_QUADS); + qglVertex3f(-100, 100, -10); + qglVertex3f(100, 100, -10); + qglVertex3f(100, -100, -10); + qglVertex3f(-100, -100, -10); + qglEnd(); - qglColor4f(1,1,1,1); - qglDisable( GL_STENCIL_TEST ); - if (planeZeroBack) - { - qglEnable (GL_CLIP_PLANE0); + qglColor4f(1, 1, 1, 1); + qglDisable(GL_STENCIL_TEST); + if (planeZeroBack) { + qglEnable(GL_CLIP_PLANE0); } qglPopMatrix(); } - /* ================= RB_ProjectionShadowDeform ================= */ -void RB_ProjectionShadowDeform( void ) { - float *xyz; - int i; - float h; - vec3_t ground; - vec3_t light; - float groundDist; - float d; - vec3_t lightDir; - - xyz = ( float * ) tess.xyz; +void RB_ProjectionShadowDeform(void) { + float *xyz; + int i; + float h; + vec3_t ground; + vec3_t light; + float groundDist; + float d; + vec3_t lightDir; + + xyz = (float *)tess.xyz; ground[0] = backEnd.ori.axis[0][2]; ground[1] = backEnd.ori.axis[1][2]; @@ -499,12 +475,12 @@ void RB_ProjectionShadowDeform( void ) { groundDist = backEnd.ori.origin[2] - backEnd.currentEntity->e.shadowPlane; - VectorCopy( backEnd.currentEntity->lightDir, lightDir ); - d = DotProduct( lightDir, ground ); + VectorCopy(backEnd.currentEntity->lightDir, lightDir); + d = DotProduct(lightDir, ground); // don't let the shadows get too long or go negative - if ( d < 0.5 ) { - VectorMA( lightDir, (0.5 - d), ground, lightDir ); - d = DotProduct( lightDir, ground ); + if (d < 0.5) { + VectorMA(lightDir, (0.5 - d), ground, lightDir); + d = DotProduct(lightDir, ground); } d = 1.0 / d; @@ -512,8 +488,8 @@ void RB_ProjectionShadowDeform( void ) { light[1] = lightDir[1] * d; light[2] = lightDir[2] * d; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - h = DotProduct( xyz, ground ) + groundDist; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + h = DotProduct(xyz, ground) + groundDist; xyz[0] -= light[0] * h; xyz[1] -= light[1] * h; @@ -521,18 +497,17 @@ void RB_ProjectionShadowDeform( void ) { } } -//update tr.screenImage -void RB_CaptureScreenImage(void) -{ +// update tr.screenImage +void RB_CaptureScreenImage(void) { int radX = 2048; int radY = 2048; - int x = glConfig.vidWidth/2; - int y = glConfig.vidHeight/2; + int x = glConfig.vidWidth / 2; + int y = glConfig.vidHeight / 2; int cX, cY; - GL_Bind( tr.screenImage ); - //using this method, we could pixel-filter the texture and all sorts of crazy stuff. - //but, it is slow as hell. + GL_Bind(tr.screenImage); + // using this method, we could pixel-filter the texture and all sorts of crazy stuff. + // but, it is slow as hell. /* static byte *tmp = NULL; if (!tmp) @@ -543,68 +518,54 @@ void RB_CaptureScreenImage(void) qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 512, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, tmp); */ - if (radX > glConfig.maxTextureSize) - { + if (radX > glConfig.maxTextureSize) { radX = glConfig.maxTextureSize; } - if (radY > glConfig.maxTextureSize) - { + if (radY > glConfig.maxTextureSize) { radY = glConfig.maxTextureSize; } - while (glConfig.vidWidth < radX) - { + while (glConfig.vidWidth < radX) { radX /= 2; } - while (glConfig.vidHeight < radY) - { + while (glConfig.vidHeight < radY) { radY /= 2; } - cX = x-(radX/2); - cY = y-(radY/2); + cX = x - (radX / 2); + cY = y - (radY / 2); - if (cX+radX > glConfig.vidWidth) - { //would it go off screen? - cX = glConfig.vidWidth-radX; - } - else if (cX < 0) - { //cap it off at 0 + if (cX + radX > glConfig.vidWidth) { // would it go off screen? + cX = glConfig.vidWidth - radX; + } else if (cX < 0) { // cap it off at 0 cX = 0; } - if (cY+radY > glConfig.vidHeight) - { //would it go off screen? - cY = glConfig.vidHeight-radY; - } - else if (cY < 0) - { //cap it off at 0 + if (cY + radY > glConfig.vidHeight) { // would it go off screen? + cY = glConfig.vidHeight - radY; + } else if (cY < 0) { // cap it off at 0 cY = 0; } qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, cX, cY, radX, radY, 0); } - -//yeah.. not really shadow-related.. but it's stencil-related. -rww -float tr_distortionAlpha = 1.0f; //opaque -float tr_distortionStretch = 0.0f; //no stretch override -qboolean tr_distortionPrePost = qfalse; //capture before postrender phase? -qboolean tr_distortionNegate = qfalse; //negative blend mode -void RB_DistortionFill(void) -{ +// yeah.. not really shadow-related.. but it's stencil-related. -rww +float tr_distortionAlpha = 1.0f; // opaque +float tr_distortionStretch = 0.0f; // no stretch override +qboolean tr_distortionPrePost = qfalse; // capture before postrender phase? +qboolean tr_distortionNegate = qfalse; // negative blend mode +void RB_DistortionFill(void) { float alpha = tr_distortionAlpha; float spost = 0.0f; float spost2 = 0.0f; - if ( glConfig.stencilBits < 4 ) - { + if (glConfig.stencilBits < 4) { return; } - //ok, cap the stupid thing now I guess - if (!tr_distortionPrePost) - { + // ok, cap the stupid thing now I guess + if (!tr_distortionPrePost) { RB_CaptureScreenImage(); } @@ -612,10 +573,10 @@ void RB_DistortionFill(void) qglStencilFunc(GL_NOTEQUAL, 0, 0xFFFFFFFF); qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); - //reset the view matrices and go into ortho mode + // reset the view matrices and go into ortho mode qglMatrixMode(GL_PROJECTION); qglPushMatrix(); qglLoadIdentity(); @@ -624,100 +585,86 @@ void RB_DistortionFill(void) qglPushMatrix(); qglLoadIdentity(); - if (tr_distortionStretch) - { //override + if (tr_distortionStretch) { // override spost = tr_distortionStretch; spost2 = tr_distortionStretch; - } - else - { //do slow stretchy effect - spost = sin(tr.refdef.time*0.0005f); - if (spost < 0.0f) - { + } else { // do slow stretchy effect + spost = sin(tr.refdef.time * 0.0005f); + if (spost < 0.0f) { spost = -spost; } spost *= 0.2f; - spost2 = sin(tr.refdef.time*0.0005f); - if (spost2 < 0.0f) - { + spost2 = sin(tr.refdef.time * 0.0005f); + if (spost2 < 0.0f) { spost2 = -spost2; } spost2 *= 0.08f; } - if (alpha != 1.0f) - { //blend - GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_ALPHA); - } - else - { //be sure to reset the draw state + if (alpha != 1.0f) { // blend + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_SRC_ALPHA); + } else { // be sure to reset the draw state GL_State(0); } qglBegin(GL_QUADS); - qglColor4f(1.0f, 1.0f, 1.0f, alpha); - qglTexCoord2f(0+spost2, 1-spost); - qglVertex2f(0, 0); + qglColor4f(1.0f, 1.0f, 1.0f, alpha); + qglTexCoord2f(0 + spost2, 1 - spost); + qglVertex2f(0, 0); - qglTexCoord2f(0+spost2, 0+spost); - qglVertex2f(0, glConfig.vidHeight); + qglTexCoord2f(0 + spost2, 0 + spost); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 0+spost); - qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); + qglTexCoord2f(1 - spost2, 0 + spost); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 1-spost); - qglVertex2f(glConfig.vidWidth, 0); + qglTexCoord2f(1 - spost2, 1 - spost); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); - if (tr_distortionAlpha == 1.0f && tr_distortionStretch == 0.0f) - { //no overrides - if (tr_distortionNegate) - { //probably the crazy alternate saber trail + if (tr_distortionAlpha == 1.0f && tr_distortionStretch == 0.0f) { // no overrides + if (tr_distortionNegate) { // probably the crazy alternate saber trail alpha = 0.8f; - GL_State(GLS_SRCBLEND_ZERO|GLS_DSTBLEND_ONE_MINUS_SRC_COLOR); - } - else - { + GL_State(GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR); + } else { alpha = 0.5f; - GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_ALPHA); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_SRC_ALPHA); } - spost = sin(tr.refdef.time*0.0008f); - if (spost < 0.0f) - { + spost = sin(tr.refdef.time * 0.0008f); + if (spost < 0.0f) { spost = -spost; } spost *= 0.08f; - spost2 = sin(tr.refdef.time*0.0008f); - if (spost2 < 0.0f) - { + spost2 = sin(tr.refdef.time * 0.0008f); + if (spost2 < 0.0f) { spost2 = -spost2; } spost2 *= 0.2f; qglBegin(GL_QUADS); - qglColor4f(1.0f, 1.0f, 1.0f, alpha); - qglTexCoord2f(0+spost2, 1-spost); - qglVertex2f(0, 0); + qglColor4f(1.0f, 1.0f, 1.0f, alpha); + qglTexCoord2f(0 + spost2, 1 - spost); + qglVertex2f(0, 0); - qglTexCoord2f(0+spost2, 0+spost); - qglVertex2f(0, glConfig.vidHeight); + qglTexCoord2f(0 + spost2, 0 + spost); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 0+spost); - qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); + qglTexCoord2f(1 - spost2, 0 + spost); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 1-spost); - qglVertex2f(glConfig.vidWidth, 0); + qglTexCoord2f(1 - spost2, 1 - spost); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); } - //pop the view matrices back + // pop the view matrices back qglMatrixMode(GL_PROJECTION); qglPopMatrix(); qglMatrixMode(GL_MODELVIEW); qglPopMatrix(); - qglDisable( GL_STENCIL_TEST ); + qglDisable(GL_STENCIL_TEST); } diff --git a/code/rd-vanilla/tr_skin.cpp b/code/rd-vanilla/tr_skin.cpp index 48e474a881..94dfba6b82 100644 --- a/code/rd-vanilla/tr_skin.cpp +++ b/code/rd-vanilla/tr_skin.cpp @@ -42,76 +42,65 @@ This is unfortunate, but the skin files aren't compatible with our normal parsing rules. ================== */ -static char *CommaParse( char **data_p ) { +static char *CommaParse(char **data_p) { int c = 0, len; char *data; - static char com_token[MAX_TOKEN_CHARS]; + static char com_token[MAX_TOKEN_CHARS]; data = *data_p; len = 0; com_token[0] = 0; // make sure incoming data is valid - if ( !data ) { + if (!data) { *data_p = NULL; return com_token; } - while ( 1 ) { + while (1) { // skip whitespace - while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') { - if( !c ) { + while ((c = *(const unsigned char * /*eurofix*/)data) <= ' ') { + if (!c) { break; } data++; } - c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { while (*data && *data != '\n') data++; } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { + else if (c == '/' && data[1] == '*') { + while (*data && (*data != '*' || data[1] != '/')) { data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } - if ( c == 0 ) { + if (c == 0) { return ""; } // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if (len < MAX_TOKEN_CHARS - 1) - { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } @@ -119,20 +108,18 @@ static char *CommaParse( char **data_p ) { } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS - 1) - { + do { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32 && c != ',' ); + } while (c > 32 && c != ','); com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -143,8 +130,8 @@ class CStringComparator bool operator()(const char *s1, const char *s2) const { return(stricmp(s1, s2) < 0); } }; */ -typedef std::map AnimationCFGs_t; - AnimationCFGs_t AnimationCFGs; +typedef std::map AnimationCFGs_t; +AnimationCFGs_t AnimationCFGs; // I added this function for development purposes (and it's VM-safe) so we don't have problems // with our use of cached models but uncached animation.cfg files (so frame sequences are out of sync @@ -153,40 +140,34 @@ typedef std::map AnimationCFGs_t; // Usage: call with psDest == NULL for a size enquire (for malloc), // then with NZ ptr for it to copy to your supplied buffer... // -int RE_GetAnimationCFG(const char *psCFGFilename, char *psDest, int iDestSize) -{ +int RE_GetAnimationCFG(const char *psCFGFilename, char *psDest, int iDestSize) { char *psText = NULL; AnimationCFGs_t::iterator it = AnimationCFGs.find(psCFGFilename); - if (it != AnimationCFGs.end()) - { + if (it != AnimationCFGs.end()) { psText = (*it).second; - } - else - { + } else { // not found, so load it... // fileHandle_t f; - int iLen = ri.FS_FOpenFileRead( psCFGFilename, &f, qfalse ); - if (iLen <= 0) - { + int iLen = ri.FS_FOpenFileRead(psCFGFilename, &f, qfalse); + if (iLen <= 0) { return 0; } - psText = (char *) R_Malloc( iLen+1, TAG_ANIMATION_CFG, qfalse ); + psText = (char *)R_Malloc(iLen + 1, TAG_ANIMATION_CFG, qfalse); - ri.FS_Read( psText, iLen, f ); + ri.FS_Read(psText, iLen, f); psText[iLen] = '\0'; - ri.FS_FCloseFile( f ); + ri.FS_FCloseFile(f); AnimationCFGs[psCFGFilename] = psText; } - if (psText) // sanity, but should always be NZ + if (psText) // sanity, but should always be NZ { - if (psDest) - { - Q_strncpyz(psDest,psText,iDestSize); + if (psDest) { + Q_strncpyz(psDest, psText, iDestSize); } return strlen(psText); @@ -197,10 +178,8 @@ int RE_GetAnimationCFG(const char *psCFGFilename, char *psDest, int iDestSize) // only called from devmapbsp, devmapall, or ... // -void RE_AnimationCFGs_DeleteAll(void) -{ - for (AnimationCFGs_t::iterator it = AnimationCFGs.begin(); it != AnimationCFGs.end(); ++it) - { +void RE_AnimationCFGs_DeleteAll(void) { + for (AnimationCFGs_t::iterator it = AnimationCFGs.begin(); it != AnimationCFGs.end(); ++it) { char *psText = (*it).second; R_Free(psText); } @@ -216,47 +195,42 @@ return= true if three part skins found output= qualified names to three skins if return is true, undefined if false =============== */ -bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) -{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; - if (strchr(INname, '|')) - { +bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) { // INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; + if (strchr(INname, '|')) { char name[MAX_QPATH]; strcpy(name, INname); char *p = strchr(name, '|'); - *p=0; + *p = 0; p++; - //fill in the base path - strcpy (skinhead, name); - strcpy (skintorso, name); - strcpy (skinlower, name); + // fill in the base path + strcpy(skinhead, name); + strcpy(skintorso, name); + strcpy(skinlower, name); - //now get the the individual files + // now get the the individual files - //advance to second + // advance to second char *p2 = strchr(p, '|'); - if (!p2) - { + if (!p2) { return false; } - *p2=0; + *p2 = 0; p2++; - strcat (skinhead, p); - strcat (skinhead, ".skin"); - + strcat(skinhead, p); + strcat(skinhead, ".skin"); - //advance to third + // advance to third p = strchr(p2, '|'); - if (!p) - { + if (!p) { return false; } - *p=0; + *p = 0; p++; - strcat (skintorso,p2); - strcat (skintorso, ".skin"); + strcat(skintorso, p2); + strcat(skintorso, ".skin"); - strcat (skinlower,p); - strcat (skinlower, ".skin"); + strcat(skinlower, p); + strcat(skinlower, ".skin"); return true; } @@ -264,76 +238,71 @@ bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *sk } // given a name, go get the skin we want and return -qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin) -{ - skin_t *skin; - skinSurface_t *surf; - char *text, *text_p; - char *token; - char surfName[MAX_QPATH]; +qhandle_t RE_RegisterIndividualSkin(const char *name, qhandle_t hSkin) { + skin_t *skin; + skinSurface_t *surf; + char *text, *text_p; + char *token; + char surfName[MAX_QPATH]; // load and parse the skin file - ri.FS_ReadFile( name, (void **)&text ); - if ( !text ) { - ri.Printf( PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name ); + ri.FS_ReadFile(name, (void **)&text); + if (!text) { + ri.Printf(PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name); return 0; } - assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append + assert(tr.skins[hSkin]); // should already be setup, but might be an 3part append skin = tr.skins[hSkin]; text_p = text; - while ( text_p && *text_p ) { + while (text_p && *text_p) { // get surface name - token = CommaParse( &text_p ); - Q_strncpyz( surfName, token, sizeof( surfName ) ); + token = CommaParse(&text_p); + Q_strncpyz(surfName, token, sizeof(surfName)); - if ( !token[0] ) { + if (!token[0]) { break; } // lowercase the surface name so skin compares are faster - Q_strlwr( surfName ); + Q_strlwr(surfName); - if ( *text_p == ',' ) { + if (*text_p == ',') { text_p++; } - if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one... + if (!strncmp(token, "tag_", 4)) { // these aren't in there, but just in case you load an id style one... continue; } // parse the shader name - token = CommaParse( &text_p ); + token = CommaParse(&text_p); #ifndef JK2_MODE - if ( !strcmp( &surfName[strlen(surfName)-4], "_off") ) - { - if ( !strcmp( token ,"*off" ) ) - { - continue; //don't need these double offs + if (!strcmp(&surfName[strlen(surfName) - 4], "_off")) { + if (!strcmp(token, "*off")) { + continue; // don't need these double offs } - surfName[strlen(surfName)-4] = 0; //remove the "_off" + surfName[strlen(surfName) - 4] = 0; // remove the "_off" } #endif - if ( (unsigned)skin->numSurfaces >= ARRAY_LEN( skin->surfaces ) ) - { - assert( ARRAY_LEN( skin->surfaces ) > (unsigned)skin->numSurfaces ); - ri.Printf( PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces) ); + if ((unsigned)skin->numSurfaces >= ARRAY_LEN(skin->surfaces)) { + assert(ARRAY_LEN(skin->surfaces) > (unsigned)skin->numSurfaces); + ri.Printf(PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces)); break; } - surf = skin->surfaces[ skin->numSurfaces ] = (skinSurface_t *) R_Hunk_Alloc( sizeof( *skin->surfaces[0] ), qtrue ); - Q_strncpyz( surf->name, surfName, sizeof( surf->name ) ); - surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue ); + surf = skin->surfaces[skin->numSurfaces] = (skinSurface_t *)R_Hunk_Alloc(sizeof(*skin->surfaces[0]), qtrue); + Q_strncpyz(surf->name, surfName, sizeof(surf->name)); + surf->shader = R_FindShader(token, lightmapsNone, stylesDefault, qtrue); skin->numSurfaces++; } - ri.FS_FreeFile( text ); - + ri.FS_FreeFile(text); // never let a skin have 0 shaders - if ( skin->numSurfaces == 0 ) { - return 0; // use default skin + if (skin->numSurfaces == 0) { + return 0; // use default skin } return hSkin; @@ -345,108 +314,100 @@ RE_RegisterSkin =============== */ -qhandle_t RE_RegisterSkin( const char *name) { - qhandle_t hSkin; - skin_t *skin; - -// if (!cls.cgameStarted && !cls.uiStarted) -// { - //rww - added uiStarted exception because we want ghoul2 models in the menus. - // gwg well we need our skins to set surfaces on and off, so we gotta get em - //return 1; // cope with Ghoul2's calling-the-renderer-before-its-even-started hackery, must be any NZ amount here to trigger configstring setting -// } - - if (!tr.numSkins) - { - R_InitSkins(); //make sure we have numSkins set to at least one. +qhandle_t RE_RegisterSkin(const char *name) { + qhandle_t hSkin; + skin_t *skin; + + // if (!cls.cgameStarted && !cls.uiStarted) + // { + // rww - added uiStarted exception because we want ghoul2 models in the menus. + // gwg well we need our skins to set surfaces on and off, so we gotta get em + // return 1; // cope with Ghoul2's calling-the-renderer-before-its-even-started hackery, must be any NZ amount here to trigger configstring setting + // } + + if (!tr.numSkins) { + R_InitSkins(); // make sure we have numSkins set to at least one. } - if ( !name || !name[0] ) { - Com_Printf( "Empty name passed to RE_RegisterSkin\n" ); + if (!name || !name[0]) { + Com_Printf("Empty name passed to RE_RegisterSkin\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Skin name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Skin name exceeds MAX_QPATH\n"); return 0; } // see if the skin is already loaded - for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) { + for (hSkin = 1; hSkin < tr.numSkins; hSkin++) { skin = tr.skins[hSkin]; - if ( !Q_stricmp( skin->name, name ) ) { - if( skin->numSurfaces == 0 ) { - return 0; // default skin + if (!Q_stricmp(skin->name, name)) { + if (skin->numSurfaces == 0) { + return 0; // default skin } return hSkin; } } - if ( tr.numSkins == MAX_SKINS ) { - ri.Printf( PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); + if (tr.numSkins == MAX_SKINS) { + ri.Printf(PRINT_WARNING, "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name); return 0; } // allocate a new skin tr.numSkins++; - skin = (skin_t*) R_Hunk_Alloc( sizeof( skin_t ), qtrue ); + skin = (skin_t *)R_Hunk_Alloc(sizeof(skin_t), qtrue); tr.skins[hSkin] = skin; - Q_strncpyz( skin->name, name, sizeof( skin->name ) ); //always make one so it won't search for it again + Q_strncpyz(skin->name, name, sizeof(skin->name)); // always make one so it won't search for it again // If not a .skin file, load as a single shader - then return - if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) { + if (strcmp(name + strlen(name) - 5, ".skin")) { #ifdef JK2_MODE skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *) R_Hunk_Alloc( sizeof(skin->surfaces[0]), qtrue ); - skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + skin->surfaces[0] = (skinSurface_t *)R_Hunk_Alloc(sizeof(skin->surfaces[0]), qtrue); + skin->surfaces[0]->shader = R_FindShader(name, lightmapsNone, stylesDefault, qtrue); return hSkin; #endif -/* skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *) R_Hunk_Alloc( sizeof(skin->surfaces[0]), qtrue ); - skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); - return hSkin; -*/ + /* skin->numSurfaces = 1; + skin->surfaces[0] = (skinSurface_t *) R_Hunk_Alloc( sizeof(skin->surfaces[0]), qtrue ); + skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + return hSkin; + */ } - char skinhead[MAX_QPATH]={0}; - char skintorso[MAX_QPATH]={0}; - char skinlower[MAX_QPATH]={0}; - if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) ) - {//three part + char skinhead[MAX_QPATH] = {0}; + char skintorso[MAX_QPATH] = {0}; + char skinlower[MAX_QPATH] = {0}; + if (RE_SplitSkins(name, (char *)&skinhead, (char *)&skintorso, (char *)&skinlower)) { // three part hSkin = RE_RegisterIndividualSkin(skinhead, hSkin); - if (hSkin && strcmp(skinhead, skintorso)) - { + if (hSkin && strcmp(skinhead, skintorso)) { hSkin = RE_RegisterIndividualSkin(skintorso, hSkin); } - if (hSkin && strcmp(skinhead, skinlower) && strcmp(skintorso, skinlower)) - { + if (hSkin && strcmp(skinhead, skinlower) && strcmp(skintorso, skinlower)) { hSkin = RE_RegisterIndividualSkin(skinlower, hSkin); } - } - else - {//single skin + } else { // single skin hSkin = RE_RegisterIndividualSkin(name, hSkin); } - return(hSkin); + return (hSkin); } - - /* =============== R_InitSkins =============== */ -void R_InitSkins( void ) { - skin_t *skin; +void R_InitSkins(void) { + skin_t *skin; tr.numSkins = 1; // make the default skin have all default shaders - skin = tr.skins[0] = (skin_t*) R_Hunk_Alloc( sizeof( skin_t ), qtrue ); - Q_strncpyz( skin->name, "", sizeof( skin->name ) ); + skin = tr.skins[0] = (skin_t *)R_Hunk_Alloc(sizeof(skin_t), qtrue); + Q_strncpyz(skin->name, "", sizeof(skin->name)); skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *) R_Hunk_Alloc( sizeof( *skin->surfaces[0] ), qtrue ); + skin->surfaces[0] = (skinSurface_t *)R_Hunk_Alloc(sizeof(*skin->surfaces[0]), qtrue); skin->surfaces[0]->shader = tr.defaultShader; } @@ -455,11 +416,11 @@ void R_InitSkins( void ) { R_GetSkinByHandle =============== */ -skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { - if ( hSkin < 1 || hSkin >= tr.numSkins ) { +skin_t *R_GetSkinByHandle(qhandle_t hSkin) { + if (hSkin < 1 || hSkin >= tr.numSkins) { return tr.skins[0]; } - return tr.skins[ hSkin ]; + return tr.skins[hSkin]; } /* @@ -467,19 +428,18 @@ skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { R_SkinList_f =============== */ -void R_SkinList_f (void) { - int i, j; - skin_t *skin; +void R_SkinList_f(void) { + int i, j; + skin_t *skin; - ri.Printf (PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "------------------\n"); - for ( i = 0 ; i < tr.numSkins ; i++ ) { + for (i = 0; i < tr.numSkins; i++) { skin = tr.skins[i]; - ri.Printf( PRINT_ALL, "%3i:%s\n", i, skin->name ); - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { - ri.Printf( PRINT_ALL, " %s = %s\n", - skin->surfaces[j]->name, skin->surfaces[j]->shader->name ); + ri.Printf(PRINT_ALL, "%3i:%s\n", i, skin->name); + for (j = 0; j < skin->numSurfaces; j++) { + ri.Printf(PRINT_ALL, " %s = %s\n", skin->surfaces[j]->name, skin->surfaces[j]->shader->name); } } - ri.Printf (PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "------------------\n"); } diff --git a/code/rd-vanilla/tr_sky.cpp b/code/rd-vanilla/tr_sky.cpp index 4c4dfcfb4f..ab02d3447a 100644 --- a/code/rd-vanilla/tr_sky.cpp +++ b/code/rd-vanilla/tr_sky.cpp @@ -28,11 +28,11 @@ along with this program; if not, see . #include "tr_local.h" -#define SKY_SUBDIVISIONS 8 -#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS/2) +#define SKY_SUBDIVISIONS 8 +#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS / 2) -static float s_cloudTexCoords[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; -static float s_cloudTexP[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; +static float s_cloudTexCoords[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; +static float s_cloudTexP[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; /* =================================================================================== @@ -42,72 +42,56 @@ POLYGON TO BOX SIDE PROJECTION =================================================================================== */ -static vec3_t sky_clip[6] = -{ - {1,1,0}, - {1,-1,0}, - {0,-1,1}, - {0,1,1}, - {1,0,1}, - {-1,0,1} -}; +static vec3_t sky_clip[6] = {{1, 1, 0}, {1, -1, 0}, {0, -1, 1}, {0, 1, 1}, {1, 0, 1}, {-1, 0, 1}}; -static float sky_mins[2][6], sky_maxs[2][6]; -static float sky_min, sky_max; +static float sky_mins[2][6], sky_maxs[2][6]; +static float sky_min, sky_max; /* ================ AddSkyPolygon ================ */ -static void AddSkyPolygon (int nump, vec3_t vecs) -{ - int i,j; - vec3_t v, av; - float s, t, dv; - int axis; - float *vp; +static void AddSkyPolygon(int nump, vec3_t vecs) { + int i, j; + vec3_t v, av; + float s, t, dv; + int axis; + float *vp; // s = [0]/[2], t = [1]/[2] - static int vec_to_st[6][3] = - { - {-2,3,1}, - {2,3,-1}, + static int vec_to_st[6][3] = { + {-2, 3, 1}, + {2, 3, -1}, - {1,3,2}, - {-1,3,-2}, + {1, 3, 2}, + {-1, 3, -2}, - {-2,-1,3}, - {-2,1,-3} + {-2, -1, 3}, + {-2, 1, -3} - // {-1,2,3}, - // {1,2,-3} + // {-1,2,3}, + // {1,2,-3} }; // decide which face it maps to - VectorCopy (vec3_origin, v); - for (i=0, vp=vecs ; i av[1] && av[0] > av[2]) - { + if (av[0] > av[1] && av[0] > av[2]) { if (v[0] < 0) axis = 1; else axis = 0; - } - else if (av[1] > av[2] && av[1] > av[0]) - { + } else if (av[1] > av[2] && av[1] > av[0]) { if (v[1] < 0) axis = 3; else axis = 2; - } - else - { + } else { if (v[2] < 0) axis = 5; else @@ -115,25 +99,24 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } // project new texture coords - for (i=0 ; i 0) dv = vecs[j - 1]; else dv = -vecs[-j - 1]; if (dv < 0.001) - continue; // don't divide by zero + continue; // don't divide by zero j = vec_to_st[axis][0]; if (j < 0) - s = -vecs[-j -1] / dv; + s = -vecs[-j - 1] / dv; else - s = vecs[j-1] / dv; + s = vecs[j - 1] / dv; j = vec_to_st[axis][1]; if (j < 0) - t = -vecs[-j -1] / dv; + t = -vecs[-j - 1] / dv; else - t = vecs[j-1] / dv; + t = vecs[j - 1] / dv; if (s < sky_mins[0][axis]) sky_mins[0][axis] = s; @@ -146,92 +129,81 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } } -#define ON_EPSILON 0.1f // point on plane side epsilon -#define MAX_CLIP_VERTS 64 +#define ON_EPSILON 0.1f // point on plane side epsilon +#define MAX_CLIP_VERTS 64 /* ================ ClipSkyPolygon ================ */ -static void ClipSkyPolygon (int nump, vec3_t vecs, int stage) -{ - float *norm; - float *v; - qboolean front, back; - float d, e; - float dists[MAX_CLIP_VERTS]; - int sides[MAX_CLIP_VERTS]; - vec3_t newv[2][MAX_CLIP_VERTS]; - int newc[2]; - int i, j; - - if (nump > MAX_CLIP_VERTS-2) - Com_Error (ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); - if (stage == 6) - { // fully clipped, so draw it - AddSkyPolygon (nump, vecs); +static void ClipSkyPolygon(int nump, vec3_t vecs, int stage) { + float *norm; + float *v; + qboolean front, back; + float d, e; + float dists[MAX_CLIP_VERTS]; + int sides[MAX_CLIP_VERTS]; + vec3_t newv[2][MAX_CLIP_VERTS]; + int newc[2]; + int i, j; + + if (nump > MAX_CLIP_VERTS - 2) + Com_Error(ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); + if (stage == 6) { // fully clipped, so draw it + AddSkyPolygon(nump, vecs); return; } front = back = qfalse; norm = sky_clip[stage]; - for (i=0, v = vecs ; i ON_EPSILON) - { + for (i = 0, v = vecs; i < nump; i++, v += 3) { + d = DotProduct(v, norm); + if (d > ON_EPSILON) { front = qtrue; sides[i] = SIDE_FRONT; - } - else if (d < -ON_EPSILON) - { + } else if (d < -ON_EPSILON) { back = qtrue; sides[i] = SIDE_BACK; - } - else + } else sides[i] = SIDE_ON; dists[i] = d; } - if (!front || !back) - { // not clipped - ClipSkyPolygon (nump, vecs, stage+1); + if (!front || !back) { // not clipped + ClipSkyPolygon(nump, vecs, stage + 1); return; } // clip it sides[i] = sides[0]; dists[i] = dists[0]; - VectorCopy (vecs, (vecs+(i*3)) ); + VectorCopy(vecs, (vecs + (i * 3))); newc[0] = newc[1] = 0; - for (i=0, v = vecs ; inumIndexes; i += 3 ) - { - for (j = 0 ; j < 3 ; j++) - { - VectorSubtract( input->xyz[input->indexes[i+j]], - backEnd.viewParms.ori.origin, - p[j] ); + for (i = 0; i < input->numIndexes; i += 3) { + for (j = 0; j < 3; j++) { + VectorSubtract(input->xyz[input->indexes[i + j]], backEnd.viewParms.ori.origin, p[j]); } - ClipSkyPolygon( 3, p[0], 0 ); + ClipSkyPolygon(3, p[0], 0); } } @@ -295,122 +262,99 @@ CLOUD VERTEX GENERATION ** ** Parms: s, t range from -1 to 1 */ -static void MakeSkyVec( float s, float t, int axis, float outSt[2], vec3_t outXYZ ) -{ +static void MakeSkyVec(float s, float t, int axis, float outSt[2], vec3_t outXYZ) { // 1 = s, 2 = t, 3 = 2048 - static int st_to_vec[6][3] = - { - {3,-1,2}, - {-3,1,2}, + static int st_to_vec[6][3] = { + {3, -1, 2}, {-3, 1, 2}, - {1,3,2}, - {-1,-3,2}, + {1, 3, 2}, {-1, -3, 2}, - {-2,-1,3}, // 0 degrees yaw, look straight up - {2,-1,-3} // look straight down + {-2, -1, 3}, // 0 degrees yaw, look straight up + {2, -1, -3} // look straight down }; - vec3_t b; - int j, k; - float boxSize; + vec3_t b; + int j, k; + float boxSize; - boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) - b[0] = s*boxSize; - b[1] = t*boxSize; + boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + b[0] = s * boxSize; + b[1] = t * boxSize; b[2] = boxSize; - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { k = st_to_vec[axis][j]; - if (k < 0) - { + if (k < 0) { outXYZ[j] = -b[-k - 1]; - } - else - { + } else { outXYZ[j] = b[k - 1]; } } // avoid bilerp seam - s = (s+1)*0.5; - t = (t+1)*0.5; - if (s < sky_min) - { + s = (s + 1) * 0.5; + t = (t + 1) * 0.5; + if (s < sky_min) { s = sky_min; - } - else if (s > sky_max) - { + } else if (s > sky_max) { s = sky_max; } - if (t < sky_min) - { + if (t < sky_min) { t = sky_min; - } - else if (t > sky_max) - { + } else if (t > sky_max) { t = sky_max; } t = 1.0 - t; - - if ( outSt ) - { + if (outSt) { outSt[0] = s; outSt[1] = t; } } -static vec3_t s_skyPoints[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; -static float s_skyTexCoords[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; +static vec3_t s_skyPoints[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; +static float s_skyTexCoords[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; -static void DrawSkySide( struct image_s *image, const int mins[2], const int maxs[2] ) -{ +static void DrawSkySide(struct image_s *image, const int mins[2], const int maxs[2]) { int s, t; - GL_Bind( image ); + GL_Bind(image); - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t < maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - qglBegin( GL_TRIANGLE_STRIP ); + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t < maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + qglBegin(GL_TRIANGLE_STRIP); - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - qglTexCoord2fv( s_skyTexCoords[t][s] ); - qglVertex3fv( s_skyPoints[t][s] ); + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { + qglTexCoord2fv(s_skyTexCoords[t][s]); + qglVertex3fv(s_skyPoints[t][s]); - qglTexCoord2fv( s_skyTexCoords[t+1][s] ); - qglVertex3fv( s_skyPoints[t+1][s] ); + qglTexCoord2fv(s_skyTexCoords[t + 1][s]); + qglVertex3fv(s_skyPoints[t + 1][s]); } qglEnd(); } } -static void DrawSkyBox( shader_t *shader ) -{ - int i; +static void DrawSkyBox(shader_t *shader) { + int i; sky_min = 0.0f; sky_max = 1.0f; - memset( s_skyTexCoords, 0, sizeof( s_skyTexCoords ) ); + memset(s_skyTexCoords, 0, sizeof(s_skyTexCoords)); - for (i=0 ; i<6 ; i++) - { + for (i = 0; i < 6; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } @@ -419,48 +363,39 @@ static void DrawSkyBox( shader_t *shader ) sky_maxs_subd[0] = sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS; sky_maxs_subd[1] = sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - s_skyTexCoords[t][s], - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, + s_skyTexCoords[t][s], s_skyPoints[t][s]); } } - DrawSkySide( shader->sky->outerbox[i], - sky_mins_subd, - sky_maxs_subd ); + DrawSkySide(shader->sky->outerbox[i], sky_mins_subd, sky_maxs_subd); } - } -static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean addIndexes ) -{ +static void FillCloudySkySide(const int mins[2], const int maxs[2], qboolean addIndexes) { int s, t; int vertexStart = tess.numVertexes; int tHeight, sWidth; @@ -468,69 +403,59 @@ static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean ad tHeight = maxs[1] - mins[1] + 1; sWidth = maxs[0] - mins[0] + 1; - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - VectorAdd( s_skyPoints[t][s], backEnd.viewParms.ori.origin, tess.xyz[tess.numVertexes] ); + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t <= maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { + VectorAdd(s_skyPoints[t][s], backEnd.viewParms.ori.origin, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0]; tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1]; tess.numVertexes++; - if ( tess.numVertexes >= SHADER_MAX_VERTEXES ) - { - Com_Error( ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()\n" ); + if (tess.numVertexes >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()\n"); } } } // only add indexes for one pass, otherwise it would draw multiple times for each pass - if ( addIndexes ) { - for ( t = 0; t < tHeight-1; t++ ) - { - for ( s = 0; s < sWidth-1; s++ ) - { - tess.indexes[tess.numIndexes] = vertexStart + s + t * ( sWidth ); + if (addIndexes) { + for (t = 0; t < tHeight - 1; t++) { + for (s = 0; s < sWidth - 1; s++) { + tess.indexes[tess.numIndexes] = vertexStart + s + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; } } } } -static void FillCloudBox( const shader_t *shader, int stage ) -{ +static void FillCloudBox(const shader_t *shader, int stage) { int i; - for ( i =0; i < 6; i++ ) - { + for (i = 0; i < 6; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; float MIN_T; - if ( 1 ) // FIXME? shader->sky->fullClouds ) + if (1) // FIXME? shader->sky->fullClouds ) { MIN_T = -HALF_SKY_SUBDIVISIONS; // still don't want to draw the bottom, even if fullClouds - if ( i == 5 ) + if (i == 5) continue; - } - else - { - switch( i ) - { + } else { + switch (i) { case 0: case 1: case 2: @@ -540,59 +465,52 @@ static void FillCloudBox( const shader_t *shader, int stage ) case 5: // don't draw clouds beneath you continue; - case 4: // top + case 4: // top default: MIN_T = -HALF_SKY_SUBDIVISIONS; break; } } - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } - sky_mins_subd[0] = Q_ftol( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ); - sky_mins_subd[1] = Q_ftol( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ); - sky_maxs_subd[0] = Q_ftol( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ); - sky_maxs_subd[1] = Q_ftol( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ); + sky_mins_subd[0] = Q_ftol(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS); + sky_mins_subd[1] = Q_ftol(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[0] = Q_ftol(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[1] = Q_ftol(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS); - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < MIN_T ) + if (sky_mins_subd[1] < MIN_T) sky_mins_subd[1] = MIN_T; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < MIN_T ) + if (sky_maxs_subd[1] < MIN_T) sky_maxs_subd[1] = MIN_T; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + s_skyPoints[t][s]); s_skyTexCoords[t][s][0] = s_cloudTexCoords[i][t][s][0]; s_skyTexCoords[t][s][1] = s_cloudTexCoords[i][t][s][1]; @@ -600,31 +518,28 @@ static void FillCloudBox( const shader_t *shader, int stage ) } // only add indexes for first stage - FillCloudySkySide( sky_mins_subd, sky_maxs_subd, (qboolean)( stage == 0 ) ); + FillCloudySkySide(sky_mins_subd, sky_maxs_subd, (qboolean)(stage == 0)); } } /* ** R_BuildCloudData */ -void R_BuildCloudData( shaderCommands_t *input ) -{ - int i; +void R_BuildCloudData(shaderCommands_t *input) { + int i; - assert( input->shader->sky ); + assert(input->shader->sky); - sky_min = 1.0 / 256.0f; // FIXME: not correct? + sky_min = 1.0 / 256.0f; // FIXME: not correct? sky_max = 255.0 / 256.0f; // set up for drawing tess.numIndexes = 0; tess.numVertexes = 0; - if ( input->shader->sky->cloudHeight ) - { - for ( i = 0; i < input->shader->numUnfoggedPasses; i++ ) - { - FillCloudBox( input->shader, i ); + if (input->shader->sky->cloudHeight) { + for (i = 0; i < input->shader->numUnfoggedPasses; i++) { + FillCloudBox(input->shader, i); } } } @@ -633,10 +548,9 @@ void R_BuildCloudData( shaderCommands_t *input ) ** R_InitSkyTexCoords ** Called when a sky shader is parsed */ -#define SQR( a ) ((a)*(a)) +#define SQR(a) ((a) * (a)) -void R_InitSkyTexCoords( float heightCloud ) -{ +void R_InitSkyTexCoords(float heightCloud) { int i, s, t; float radiusWorld = MAX_WORLD_COORD; float p; @@ -648,41 +562,31 @@ void R_InitSkyTexCoords( float heightCloud ) // a world hasn't been bounded backEnd.viewParms.zFar = 1024; - for ( i = 0; i < 6; i++ ) - { - for ( t = 0; t <= SKY_SUBDIVISIONS; t++ ) - { - for ( s = 0; s <= SKY_SUBDIVISIONS; s++ ) - { + for (i = 0; i < 6; i++) { + for (t = 0; t <= SKY_SUBDIVISIONS; t++) { + for (s = 0; s <= SKY_SUBDIVISIONS; s++) { // compute vector from view origin to sky side integral point - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - skyVec ); + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + skyVec); // compute parametric value 'p' that intersects with cloud layer - p = ( 1.0f / ( 2 * DotProduct( skyVec, skyVec ) ) ) * - ( -2 * skyVec[2] * radiusWorld + - 2 * sqrt( SQR( skyVec[2] ) * SQR( radiusWorld ) + - 2 * SQR( skyVec[0] ) * radiusWorld * heightCloud + - SQR( skyVec[0] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[1] ) * radiusWorld * heightCloud + - SQR( skyVec[1] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[2] ) * radiusWorld * heightCloud + - SQR( skyVec[2] ) * SQR( heightCloud ) ) ); + p = (1.0f / (2 * DotProduct(skyVec, skyVec))) * + (-2 * skyVec[2] * radiusWorld + + 2 * sqrt(SQR(skyVec[2]) * SQR(radiusWorld) + 2 * SQR(skyVec[0]) * radiusWorld * heightCloud + SQR(skyVec[0]) * SQR(heightCloud) + + 2 * SQR(skyVec[1]) * radiusWorld * heightCloud + SQR(skyVec[1]) * SQR(heightCloud) + + 2 * SQR(skyVec[2]) * radiusWorld * heightCloud + SQR(skyVec[2]) * SQR(heightCloud))); s_cloudTexP[i][t][s] = p; // compute intersection point based on p - VectorScale( skyVec, p, v ); + VectorScale(skyVec, p, v); v[2] += radiusWorld; // compute vector from world origin to intersection point 'v' - VectorNormalize( v ); + VectorNormalize(v); - sRad = acos( v[0] ); - tRad = acos( v[1] ); + sRad = acos(v[0]); + tRad = acos(v[1]); s_cloudTexCoords[i][t][s][0] = sRad; s_cloudTexCoords[i][t][s][1] = tRad; @@ -696,96 +600,93 @@ void R_InitSkyTexCoords( float heightCloud ) /* ** RB_DrawSun */ -void RB_DrawSun( void ) { - float size; - float dist; - vec3_t origin, vec1, vec2; - vec3_t temp; +void RB_DrawSun(void) { + float size; + float dist; + vec3_t origin, vec1, vec2; + vec3_t temp; - if ( !backEnd.skyRenderedThisView ) { + if (!backEnd.skyRenderedThisView) { return; } - if ( !r_drawSun->integer ) { + if (!r_drawSun->integer) { return; } - qglLoadMatrixf( backEnd.viewParms.world.modelMatrix ); - qglTranslatef (backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); + qglLoadMatrixf(backEnd.viewParms.world.modelMatrix); + qglTranslatef(backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); - dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) size = dist * 0.4; - VectorScale( tr.sunDirection, dist, origin ); - PerpendicularVector( vec1, tr.sunDirection ); - CrossProduct( tr.sunDirection, vec1, vec2 ); + VectorScale(tr.sunDirection, dist, origin); + PerpendicularVector(vec1, tr.sunDirection); + CrossProduct(tr.sunDirection, vec1, vec2); - VectorScale( vec1, size, vec1 ); - VectorScale( vec2, size, vec2 ); + VectorScale(vec1, size, vec1); + VectorScale(vec2, size, vec2); // farthest depth range - qglDepthRange( 1.0, 1.0 ); + qglDepthRange(1.0, 1.0); // FIXME: use quad stamp - RB_BeginSurface( tr.sunShader, tess.fogNum ); - VectorCopy( origin, temp ); - VectorSubtract( temp, vec1, temp ); - VectorSubtract( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorAdd( temp, vec1, temp ); - VectorSubtract( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorAdd( temp, vec1, temp ); - VectorAdd( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1; - tess.texCoords[tess.numVertexes][0][1] = 1; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorSubtract( temp, vec1, temp ); - VectorAdd( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1; - tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - tess.indexes[tess.numIndexes++] = 0; - tess.indexes[tess.numIndexes++] = 1; - tess.indexes[tess.numIndexes++] = 2; - tess.indexes[tess.numIndexes++] = 0; - tess.indexes[tess.numIndexes++] = 2; - tess.indexes[tess.numIndexes++] = 3; + RB_BeginSurface(tr.sunShader, tess.fogNum); + VectorCopy(origin, temp); + VectorSubtract(temp, vec1, temp); + VectorSubtract(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 0; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorAdd(temp, vec1, temp); + VectorSubtract(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 1; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorAdd(temp, vec1, temp); + VectorAdd(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = 1; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorSubtract(temp, vec1, temp); + VectorAdd(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = 0; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 1; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 3; RB_EndSurface(); // back to normal depth range - qglDepthRange( 0.0, 1.0 ); + qglDepthRange(0.0, 1.0); } - - - /* ================ RB_StageIteratorSky @@ -795,56 +696,53 @@ All of the visible sky triangles are in tess Other things could be stuck in here, like birds in the sky, etc ================ */ -void RB_StageIteratorSky( void ) { - if ( r_fastsky->integer ) { +void RB_StageIteratorSky(void) { + if (r_fastsky->integer) { return; } - if (skyboxportal && !(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) - { + if (skyboxportal && !(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) { return; } // go through all the polygons and project them onto // the sky box to see which blocks on each side need // to be drawn - RB_ClipSkyPolygons( &tess ); + RB_ClipSkyPolygons(&tess); // r_showsky will let all the sky blocks be drawn in // front of everything to allow developers to see how // much sky is getting sucked in - if ( r_showsky->integer ) { - qglDepthRange( 0.0, 0.0 ); + if (r_showsky->integer) { + qglDepthRange(0.0, 0.0); } else { - qglDepthRange( 1.0, 1.0 ); + qglDepthRange(1.0, 1.0); } // draw the outer skybox - if ( tess.shader->sky->outerbox[0] && tess.shader->sky->outerbox[0] != tr.defaultImage ) { - qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight ); + if (tess.shader->sky->outerbox[0] && tess.shader->sky->outerbox[0] != tr.defaultImage) { + qglColor3f(tr.identityLight, tr.identityLight, tr.identityLight); - qglPushMatrix (); - GL_State( 0 ); - qglTranslatef (backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); + qglPushMatrix(); + GL_State(0); + qglTranslatef(backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); - DrawSkyBox( tess.shader ); + DrawSkyBox(tess.shader); qglPopMatrix(); } // generate the vertexes for all the clouds, which will be drawn // by the generic shader routine - R_BuildCloudData( &tess ); + R_BuildCloudData(&tess); RB_StageIteratorGeneric(); // draw the inner skybox - // back to normal depth range - qglDepthRange( 0.0, 1.0 ); + qglDepthRange(0.0, 1.0); // note that sky was drawn so we will draw a sun later backEnd.skyRenderedThisView = qtrue; } - diff --git a/code/rd-vanilla/tr_stl.cpp b/code/rd-vanilla/tr_stl.cpp index f3648d1b37..063d2df6d3 100644 --- a/code/rd-vanilla/tr_stl.cpp +++ b/code/rd-vanilla/tr_stl.cpp @@ -28,48 +28,35 @@ along with this program; if not, see . // and didn't want them showing up in the renderer files they were used in. This way keeps them more or less invisible // because of minimal dependancies // -#include "tr_local.h" // this isn't actually needed other than getting rid of warnings via pragmas +#include "tr_local.h" // this isn't actually needed other than getting rid of warnings via pragmas #include "tr_stl.h" #include -#include "../qcommon/sstring.h" // #include +#include "../qcommon/sstring.h" // #include -typedef std::map ShaderEntryPtrs_t; -typedef ShaderEntryPtrs_t::size_type ShaderEntryPtr_size; - ShaderEntryPtrs_t ShaderEntryPtrs; - -void ShaderEntryPtrs_Clear(void) -{ - ShaderEntryPtrs.clear(); -} +typedef std::map ShaderEntryPtrs_t; +typedef ShaderEntryPtrs_t::size_type ShaderEntryPtr_size; +ShaderEntryPtrs_t ShaderEntryPtrs; +void ShaderEntryPtrs_Clear(void) { ShaderEntryPtrs.clear(); } -int ShaderEntryPtrs_Size(void) -{ - return ShaderEntryPtrs.size(); -} +int ShaderEntryPtrs_Size(void) { return ShaderEntryPtrs.size(); } -void ShaderEntryPtrs_Insert(const char *token, const char *p) -{ +void ShaderEntryPtrs_Insert(const char *token, const char *p) { ShaderEntryPtrs_t::iterator it = ShaderEntryPtrs.find(token); - if (it == ShaderEntryPtrs.end()) - { + if (it == ShaderEntryPtrs.end()) { ShaderEntryPtrs[token] = p; - } - else - { - ri.Printf( PRINT_DEVELOPER, "Duplicate shader entry %s!\n",token ); + } else { + ri.Printf(PRINT_DEVELOPER, "Duplicate shader entry %s!\n", token); } } // returns NULL if not found... // -const char *ShaderEntryPtrs_Lookup(const char *psShaderName) -{ +const char *ShaderEntryPtrs_Lookup(const char *psShaderName) { ShaderEntryPtrs_t::iterator it = ShaderEntryPtrs.find(psShaderName); - if (it != ShaderEntryPtrs.end()) - { + if (it != ShaderEntryPtrs.end()) { const char *p = (*it).second; return p; } diff --git a/code/rd-vanilla/tr_subs.cpp b/code/rd-vanilla/tr_subs.cpp index c52bba0982..7a89f48692 100644 --- a/code/rd-vanilla/tr_subs.cpp +++ b/code/rd-vanilla/tr_subs.cpp @@ -27,10 +27,9 @@ along with this program; if not, see . // tr_subs.cpp - common function replacements for modular renderer #include "tr_local.h" -void QDECL Com_Printf( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Printf(const char *msg, ...) { + va_list argptr; + char text[1024]; va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); @@ -39,10 +38,9 @@ void QDECL Com_Printf( const char *msg, ... ) ri.Printf(PRINT_ALL, "%s", text); } -void QDECL Com_Error( int level, const char *error, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Error(int level, const char *error, ...) { + va_list argptr; + char text[1024]; va_start(argptr, error); Q_vsnprintf(text, sizeof(text), error, argptr); @@ -58,10 +56,9 @@ Com_DPrintf DLL glue ================ */ -void Com_DPrintf(const char *format, ...) -{ - va_list argptr; - char text[1024]; +void Com_DPrintf(const char *format, ...) { + va_list argptr; + char text[1024]; va_start(argptr, format); Q_vsnprintf(text, sizeof(text), format, argptr); @@ -72,28 +69,18 @@ void Com_DPrintf(const char *format, ...) // HUNK -//int Hunk_MemoryRemaining( void ) { +// int Hunk_MemoryRemaining( void ) { // return ri.Hunk_MemoryRemaining(); -//} +// } // ZONE -void *R_Malloc( int iSize, memtag_t eTag, qboolean bZeroit ) { - return ri.Malloc( iSize, eTag, bZeroit, 4 ); -} +void *R_Malloc(int iSize, memtag_t eTag, qboolean bZeroit) { return ri.Malloc(iSize, eTag, bZeroit, 4); } -void R_Free( void *ptr ) { - ri.Z_Free( ptr ); -} +void R_Free(void *ptr) { ri.Z_Free(ptr); } -int R_MemSize( memtag_t eTag ) { - return ri.Z_MemSize( eTag ); -} +int R_MemSize(memtag_t eTag) { return ri.Z_MemSize(eTag); } -void R_MorphMallocTag( void *pvBuffer, memtag_t eDesiredTag ) { - ri.Z_MorphMallocTag( pvBuffer, eDesiredTag ); -} +void R_MorphMallocTag(void *pvBuffer, memtag_t eDesiredTag) { ri.Z_MorphMallocTag(pvBuffer, eDesiredTag); } -void *R_Hunk_Alloc( int iSize, qboolean bZeroit ) { - return ri.Malloc( iSize, TAG_HUNKALLOC, bZeroit, 4 ); -} +void *R_Hunk_Alloc(int iSize, qboolean bZeroit) { return ri.Malloc(iSize, TAG_HUNKALLOC, bZeroit, 4); } diff --git a/code/rd-vanilla/tr_surface.cpp b/code/rd-vanilla/tr_surface.cpp index 1e51e71c90..9d0703840f 100644 --- a/code/rd-vanilla/tr_surface.cpp +++ b/code/rd-vanilla/tr_surface.cpp @@ -41,92 +41,87 @@ It is safe to actually issue drawing commands here if you don't want to use the shader system. */ - //============================================================================ - /* ============== RB_CheckOverflow ============== */ -void RB_CheckOverflow( int verts, int indexes ) { - if (tess.numVertexes + verts < SHADER_MAX_VERTEXES - && tess.numIndexes + indexes < SHADER_MAX_INDEXES) { +void RB_CheckOverflow(int verts, int indexes) { + if (tess.numVertexes + verts < SHADER_MAX_VERTEXES && tess.numIndexes + indexes < SHADER_MAX_INDEXES) { return; } RB_EndSurface(); - if ( verts >= SHADER_MAX_VERTEXES ) { - Com_Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES ); + if (verts >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES); } - if ( indexes >= SHADER_MAX_INDEXES ) { - Com_Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES ); + if (indexes >= SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES); } - RB_BeginSurface(tess.shader, tess.fogNum ); + RB_BeginSurface(tess.shader, tess.fogNum); } - /* ============== RB_AddQuadStampExt ============== */ -void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2 ) { - vec3_t normal; - int ndx; +void RB_AddQuadStampExt(vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2) { + vec3_t normal; + int ndx; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); ndx = tess.numVertexes; // triangle indexes for a simple quad - tess.indexes[ tess.numIndexes ] = ndx; - tess.indexes[ tess.numIndexes + 1 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 2 ] = ndx + 3; + tess.indexes[tess.numIndexes] = ndx; + tess.indexes[tess.numIndexes + 1] = ndx + 1; + tess.indexes[tess.numIndexes + 2] = ndx + 3; - tess.indexes[ tess.numIndexes + 3 ] = ndx + 3; - tess.indexes[ tess.numIndexes + 4 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 5 ] = ndx + 2; + tess.indexes[tess.numIndexes + 3] = ndx + 3; + tess.indexes[tess.numIndexes + 4] = ndx + 1; + tess.indexes[tess.numIndexes + 5] = ndx + 2; tess.xyz[ndx][0] = origin[0] + left[0] + up[0]; tess.xyz[ndx][1] = origin[1] + left[1] + up[1]; tess.xyz[ndx][2] = origin[2] + left[2] + up[2]; - tess.xyz[ndx+1][0] = origin[0] - left[0] + up[0]; - tess.xyz[ndx+1][1] = origin[1] - left[1] + up[1]; - tess.xyz[ndx+1][2] = origin[2] - left[2] + up[2]; - - tess.xyz[ndx+2][0] = origin[0] - left[0] - up[0]; - tess.xyz[ndx+2][1] = origin[1] - left[1] - up[1]; - tess.xyz[ndx+2][2] = origin[2] - left[2] - up[2]; + tess.xyz[ndx + 1][0] = origin[0] - left[0] + up[0]; + tess.xyz[ndx + 1][1] = origin[1] - left[1] + up[1]; + tess.xyz[ndx + 1][2] = origin[2] - left[2] + up[2]; - tess.xyz[ndx+3][0] = origin[0] + left[0] - up[0]; - tess.xyz[ndx+3][1] = origin[1] + left[1] - up[1]; - tess.xyz[ndx+3][2] = origin[2] + left[2] - up[2]; + tess.xyz[ndx + 2][0] = origin[0] - left[0] - up[0]; + tess.xyz[ndx + 2][1] = origin[1] - left[1] - up[1]; + tess.xyz[ndx + 2][2] = origin[2] - left[2] - up[2]; + tess.xyz[ndx + 3][0] = origin[0] + left[0] - up[0]; + tess.xyz[ndx + 3][1] = origin[1] + left[1] - up[1]; + tess.xyz[ndx + 3][2] = origin[2] + left[2] - up[2]; // constant normal all the way around - VectorSubtract( vec3_origin, backEnd.viewParms.ori.axis[0], normal ); + VectorSubtract(vec3_origin, backEnd.viewParms.ori.axis[0], normal); - tess.normal[ndx][0] = tess.normal[ndx+1][0] = tess.normal[ndx+2][0] = tess.normal[ndx+3][0] = normal[0]; - tess.normal[ndx][1] = tess.normal[ndx+1][1] = tess.normal[ndx+2][1] = tess.normal[ndx+3][1] = normal[1]; - tess.normal[ndx][2] = tess.normal[ndx+1][2] = tess.normal[ndx+2][2] = tess.normal[ndx+3][2] = normal[2]; + tess.normal[ndx][0] = tess.normal[ndx + 1][0] = tess.normal[ndx + 2][0] = tess.normal[ndx + 3][0] = normal[0]; + tess.normal[ndx][1] = tess.normal[ndx + 1][1] = tess.normal[ndx + 2][1] = tess.normal[ndx + 3][1] = normal[1]; + tess.normal[ndx][2] = tess.normal[ndx + 1][2] = tess.normal[ndx + 2][2] = tess.normal[ndx + 3][2] = normal[2]; // standard square texture coordinates tess.texCoords[ndx][0][0] = tess.texCoords[ndx][1][0] = s1; tess.texCoords[ndx][0][1] = tess.texCoords[ndx][1][1] = t1; - tess.texCoords[ndx+1][0][0] = tess.texCoords[ndx+1][1][0] = s2; - tess.texCoords[ndx+1][0][1] = tess.texCoords[ndx+1][1][1] = t1; + tess.texCoords[ndx + 1][0][0] = tess.texCoords[ndx + 1][1][0] = s2; + tess.texCoords[ndx + 1][0][1] = tess.texCoords[ndx + 1][1][1] = t1; - tess.texCoords[ndx+2][0][0] = tess.texCoords[ndx+2][1][0] = s2; - tess.texCoords[ndx+2][0][1] = tess.texCoords[ndx+2][1][1] = t2; + tess.texCoords[ndx + 2][0][0] = tess.texCoords[ndx + 2][1][0] = s2; + tess.texCoords[ndx + 2][0][1] = tess.texCoords[ndx + 2][1][1] = t2; - tess.texCoords[ndx+3][0][0] = tess.texCoords[ndx+3][1][0] = s1; - tess.texCoords[ndx+3][0][1] = tess.texCoords[ndx+3][1][1] = t2; + tess.texCoords[ndx + 3][0][0] = tess.texCoords[ndx + 3][1][0] = s1; + tess.texCoords[ndx + 3][0][1] = tess.texCoords[ndx + 3][1][1] = t2; // constant color all the way around // should this be identity and let the shader specify from entity? @@ -149,43 +144,41 @@ void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, flo RB_AddQuadStamp ============== */ -void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, byte *color ) { - RB_AddQuadStampExt( origin, left, up, color, 0, 0, 1, 1 ); -} +void RB_AddQuadStamp(vec3_t origin, vec3_t left, vec3_t up, byte *color) { RB_AddQuadStampExt(origin, left, up, color, 0, 0, 1, 1); } /* ============== RB_SurfaceSprite ============== */ -static void RB_SurfaceSprite( void ) { - vec3_t left, up; - float radius; +static void RB_SurfaceSprite(void) { + vec3_t left, up; + float radius; // calculate the xyz locations for the four corners radius = backEnd.currentEntity->e.radius; - if ( backEnd.currentEntity->e.rotation == 0 ) { - VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); - VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); + if (backEnd.currentEntity->e.rotation == 0) { + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); } else { - float s, c; - float ang; + float s, c; + float ang; ang = M_PI * backEnd.currentEntity->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); } - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA); } /* @@ -193,47 +186,42 @@ static void RB_SurfaceSprite( void ) { RB_SurfaceOrientedQuad ======================= */ -static void RB_SurfaceOrientedQuad( void ) -{ - vec3_t left, up; - float radius; +static void RB_SurfaceOrientedQuad(void) { + vec3_t left, up; + float radius; // calculate the xyz locations for the four corners radius = backEnd.currentEntity->e.radius; - MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); + MakeNormalVectors(backEnd.currentEntity->e.axis[0], left, up); - if ( backEnd.currentEntity->e.rotation == 0 ) - { - VectorScale( left, radius, left ); - VectorScale( up, radius, up ); - } - else - { - vec3_t tempLeft, tempUp; - float s, c; - float ang; + if (backEnd.currentEntity->e.rotation == 0) { + VectorScale(left, radius, left); + VectorScale(up, radius, up); + } else { + vec3_t tempLeft, tempUp; + float s, c; + float ang; ang = M_PI * backEnd.currentEntity->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); // Use a temp so we don't trash the values we'll need later - VectorScale( left, c * radius, tempLeft ); - VectorMA( tempLeft, -s * radius, up, tempLeft ); + VectorScale(left, c * radius, tempLeft); + VectorMA(tempLeft, -s * radius, up, tempLeft); - VectorScale( up, c * radius, tempUp ); - VectorMA( tempUp, s * radius, left, up ); // no need to use the temp anymore, so copy into the dest vector ( up ) + VectorScale(up, c * radius, tempUp); + VectorMA(tempUp, s * radius, left, up); // no need to use the temp anymore, so copy into the dest vector ( up ) // This was copied for safekeeping, we're done, so we can move it back to left - VectorCopy( tempLeft, left ); + VectorCopy(tempLeft, left); } - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA); } /* @@ -255,28 +243,27 @@ RB_SurfaceLine // startRGB, endRGB // -static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) -{ - float spanWidth2; - int vbase; +static void DoLine(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth) { + float spanWidth2; + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; spanWidth2 = -spanWidth; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];// * 0.25;//wtf??not sure why the code would be doing this - tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];// * 0.25; - tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];// * 0.25; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; // * 0.25;//wtf??not sure why the code would be doing this + tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; // * 0.25; + tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; // * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = 0; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; @@ -284,19 +271,19 @@ static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; @@ -312,25 +299,24 @@ static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float tess.indexes[tess.numIndexes++] = vbase + 3; } -static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2, const float tcStart, const float tcEnd ) -{ - int vbase; +static void DoLine2(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2, const float tcStart, const float tcEnd) { + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = tcStart; - tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];// * 0.25;//wtf??not sure why the code would be doing this - tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];// * 0.25; - tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];// * 0.25; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; // * 0.25;//wtf??not sure why the code would be doing this + tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; // * 0.25; + tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; // * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( start, -spanWidth, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, -spanWidth, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = tcStart; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; @@ -338,19 +324,19 @@ static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, floa tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = tcEnd;//backEnd.currentEntity->e.shaderTexCoord[1]; + tess.texCoords[tess.numVertexes][0][1] = tcEnd; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, -spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = tcEnd;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorMA(end, -spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = tcEnd; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; @@ -369,25 +355,24 @@ static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, floa //----------------- // RB_SurfaceLine //----------------- -static void RB_SurfaceLine( void ) -{ +static void RB_SurfaceLine(void) { refEntity_t *e; - vec3_t right; - vec3_t start, end; - vec3_t v1, v2; + vec3_t right; + vec3_t start, end; + vec3_t v1, v2; e = &backEnd.currentEntity->e; - VectorCopy( e->oldorigin, end ); - VectorCopy( e->origin, start ); + VectorCopy(e->oldorigin, end); + VectorCopy(e->origin, start); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); - DoLine( start, end, right, e->radius); + DoLine(start, end, right, e->radius); } /* @@ -402,84 +387,77 @@ RB_SurfaceCylinder // e->oldorigin holds the top point // e->radius holds the radius -// If a cylinder has a tapered end that has a very small radius, the engine converts it to a cone. Not a huge savings, but the texture mapping is slightly better +// If a cylinder has a tapered end that has a very small radius, the engine converts it to a cone. Not a huge savings, but the texture mapping is slightly +// better // and it uses half as many indicies as the cylinder version //------------------------------------- -static void RB_SurfaceCone( void ) +static void RB_SurfaceCone(void) //------------------------------------- { static vec3_t points[NUM_CYLINDER_SEGMENTS]; - vec3_t vr, vu, midpoint; - vec3_t tapered, base; - float detail, length; - int i; - int segments; + vec3_t vr, vu, midpoint; + vec3_t tapered, base; + float detail, length; + int i; + int segments; refEntity_t *e; e = &backEnd.currentEntity->e; - //Work out the detail level of this cylinder - VectorAdd( e->origin, e->oldorigin, midpoint ); - VectorScale(midpoint, 0.5, midpoint); // Average start and end + // Work out the detail level of this cylinder + VectorAdd(e->origin, e->oldorigin, midpoint); + VectorScale(midpoint, 0.5, midpoint); // Average start and end - VectorSubtract( midpoint, backEnd.viewParms.ori.origin, midpoint ); - length = VectorNormalize( midpoint ); + VectorSubtract(midpoint, backEnd.viewParms.ori.origin, midpoint); + length = VectorNormalize(midpoint); // this doesn't need to be perfect....just a rough compensation for zoom level is enough length *= (backEnd.viewParms.fovX / 90.0f); - detail = 1 - ((float) length / 2048 ); + detail = 1 - ((float)length / 2048); segments = NUM_CYLINDER_SEGMENTS * detail; // 3 is the absolute minimum, but the pop between 3-8 is too noticeable - if ( segments < 8 ) - { + if (segments < 8) { segments = 8; } - if ( segments > NUM_CYLINDER_SEGMENTS ) - { + if (segments > NUM_CYLINDER_SEGMENTS) { segments = NUM_CYLINDER_SEGMENTS; } // Get the direction vector - MakeNormalVectors( e->axis[0], vr, vu ); + MakeNormalVectors(e->axis[0], vr, vu); // we only need to rotate around the larger radius, the smaller radius get's welded - if ( e->radius < e->backlerp ) - { - VectorScale( vu, e->backlerp, vu ); - VectorCopy( e->origin, base ); - VectorCopy( e->oldorigin, tapered ); - } - else - { - VectorScale( vu, e->radius, vu ); - VectorCopy( e->origin, tapered ); - VectorCopy( e->oldorigin, base ); + if (e->radius < e->backlerp) { + VectorScale(vu, e->backlerp, vu); + VectorCopy(e->origin, base); + VectorCopy(e->oldorigin, tapered); + } else { + VectorScale(vu, e->radius, vu); + VectorCopy(e->origin, tapered); + VectorCopy(e->oldorigin, base); } - // Calculate the step around the cylinder detail = 360.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { + for (i = 0; i < segments; i++) { // ring - RotatePointAroundVector( points[i], e->axis[0], vu, detail * i ); - VectorAdd( points[i], base, points[i] ); + RotatePointAroundVector(points[i], e->axis[0], vu, detail * i); + VectorAdd(points[i], base, points[i]); } // Calculate the texture coords so the texture can wrap around the whole cylinder detail = 1.0f / (float)segments; - RB_CHECKOVERFLOW( 2 * (segments+1), 3 * segments ); // this isn't 100% accurate + RB_CHECKOVERFLOW(2 * (segments + 1), 3 * segments); // this isn't 100% accurate int vbase = tess.numVertexes; - for ( i = 0; i < segments; i++ ) - { - VectorCopy( points[i], tess.xyz[tess.numVertexes] ); + for (i = 0; i < segments; i++) { + VectorCopy(points[i], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 1.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -489,8 +467,9 @@ static void RB_SurfaceCone( void ) tess.numVertexes++; // We could add this vert once, but using the given texture mapping method, we need to generate different texture coordinates - VectorCopy( tapered, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = detail * i + detail * 0.5f; // set the texture coordinates to the point half-way between the untapered ends....but on the other end of the texture + VectorCopy(tapered, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = + detail * i + detail * 0.5f; // set the texture coordinates to the point half-way between the untapered ends....but on the other end of the texture tess.texCoords[tess.numVertexes][0][1] = 0.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = e->shaderRGBA[1]; @@ -500,7 +479,7 @@ static void RB_SurfaceCone( void ) } // last point has the same verts as the first, but does not share the same tex coords, so we have to duplicate it - VectorCopy( points[0], tess.xyz[tess.numVertexes] ); + VectorCopy(points[0], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 1.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -509,7 +488,7 @@ static void RB_SurfaceCone( void ) tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorCopy( tapered, tess.xyz[tess.numVertexes] ); + VectorCopy(tapered, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i + detail * 0.5f; tess.texCoords[tess.numVertexes][0][1] = 0.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -519,8 +498,7 @@ static void RB_SurfaceCone( void ) tess.numVertexes++; // do the welding - for ( i = 0; i < segments; i++ ) - { + for (i = 0; i < segments; i++) { tess.indexes[tess.numIndexes++] = vbase; tess.indexes[tess.numIndexes++] = vbase + 1; tess.indexes[tess.numIndexes++] = vbase + 2; @@ -530,80 +508,75 @@ static void RB_SurfaceCone( void ) } //------------------------------------- -static void RB_SurfaceCylinder( void ) +static void RB_SurfaceCylinder(void) //------------------------------------- { static vec3_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS]; - vec3_t vr, vu, midpoint, v1; - float detail, length; - int i; - int segments; + vec3_t vr, vu, midpoint, v1; + float detail, length; + int i; + int segments; refEntity_t *e; e = &backEnd.currentEntity->e; // check for tapering - if ( !( e->radius < 0.3f && e->backlerp < 0.3f) && ( e->radius < 0.3f || e->backlerp < 0.3f )) - { + if (!(e->radius < 0.3f && e->backlerp < 0.3f) && (e->radius < 0.3f || e->backlerp < 0.3f)) { // One end is sufficiently tapered to consider changing it to a cone RB_SurfaceCone(); return; } - //Work out the detail level of this cylinder - VectorAdd( e->origin, e->oldorigin, midpoint ); - VectorScale(midpoint, 0.5, midpoint); // Average start and end + // Work out the detail level of this cylinder + VectorAdd(e->origin, e->oldorigin, midpoint); + VectorScale(midpoint, 0.5, midpoint); // Average start and end - VectorSubtract( midpoint, backEnd.viewParms.ori.origin, midpoint ); - length = VectorNormalize( midpoint ); + VectorSubtract(midpoint, backEnd.viewParms.ori.origin, midpoint); + length = VectorNormalize(midpoint); // this doesn't need to be perfect....just a rough compensation for zoom level is enough length *= (backEnd.viewParms.fovX / 90.0f); - detail = 1 - ((float) length / 2048 ); + detail = 1 - ((float)length / 2048); segments = NUM_CYLINDER_SEGMENTS * detail; // 3 is the absolute minimum, but the pop between 3-8 is too noticeable - if ( segments < 8 ) - { + if (segments < 8) { segments = 8; } - if ( segments > NUM_CYLINDER_SEGMENTS ) - { + if (segments > NUM_CYLINDER_SEGMENTS) { segments = NUM_CYLINDER_SEGMENTS; } - //Get the direction vector - MakeNormalVectors( e->axis[0], vr, vu ); + // Get the direction vector + MakeNormalVectors(e->axis[0], vr, vu); - VectorScale( vu, e->radius, v1 ); // size1 - VectorScale( vu, e->backlerp, vu ); // size2 + VectorScale(vu, e->radius, v1); // size1 + VectorScale(vu, e->backlerp, vu); // size2 // Calculate the step around the cylinder detail = 360.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { - //Upper ring - RotatePointAroundVector( upper_points[i], e->axis[0], vu, detail * i ); - VectorAdd( upper_points[i], e->origin, upper_points[i] ); + for (i = 0; i < segments; i++) { + // Upper ring + RotatePointAroundVector(upper_points[i], e->axis[0], vu, detail * i); + VectorAdd(upper_points[i], e->origin, upper_points[i]); - //Lower ring - RotatePointAroundVector( lower_points[i], e->axis[0], v1, detail * i ); - VectorAdd( lower_points[i], e->oldorigin, lower_points[i] ); + // Lower ring + RotatePointAroundVector(lower_points[i], e->axis[0], v1, detail * i); + VectorAdd(lower_points[i], e->oldorigin, lower_points[i]); } // Calculate the texture coords so the texture can wrap around the whole cylinder detail = 1.0f / (float)segments; - RB_CHECKOVERFLOW( 2 * (segments+1), 6 * segments ); // this isn't 100% accurate + RB_CHECKOVERFLOW(2 * (segments + 1), 6 * segments); // this isn't 100% accurate int vbase = tess.numVertexes; - for ( i = 0; i < segments; i++ ) - { - VectorCopy( upper_points[i], tess.xyz[tess.numVertexes] ); + for (i = 0; i < segments; i++) { + VectorCopy(upper_points[i], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 1.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -612,7 +585,7 @@ static void RB_SurfaceCylinder( void ) tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorCopy( lower_points[i], tess.xyz[tess.numVertexes] ); + VectorCopy(lower_points[i], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 0.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -623,7 +596,7 @@ static void RB_SurfaceCylinder( void ) } // last point has the same verts as the first, but does not share the same tex coords, so we have to duplicate it - VectorCopy( upper_points[0], tess.xyz[tess.numVertexes] ); + VectorCopy(upper_points[0], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 1.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -632,7 +605,7 @@ static void RB_SurfaceCylinder( void ) tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorCopy( lower_points[0], tess.xyz[tess.numVertexes] ); + VectorCopy(lower_points[0], tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = detail * i; tess.texCoords[tess.numVertexes][0][1] = 0.0f; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; @@ -642,8 +615,7 @@ static void RB_SurfaceCylinder( void ) tess.numVertexes++; // glue the verts - for ( i = 0; i < segments; i++ ) - { + for (i = 0; i < segments; i++) { tess.indexes[tess.numIndexes++] = vbase; tess.indexes[tess.numIndexes++] = vbase + 1; tess.indexes[tess.numIndexes++] = vbase + 2; @@ -664,43 +636,41 @@ static int f_count; static void CreateShape() //---------------------------------------------------------------------------- { - VectorSet( sh1, 0.66f,// + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - 0.08f + Q_flrand(-1.0f, 1.0f) * 0.02f, - 0.08f + Q_flrand(-1.0f, 1.0f) * 0.02f ); + VectorSet(sh1, 0.66f, // + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + 0.08f + Q_flrand(-1.0f, 1.0f) * 0.02f, 0.08f + Q_flrand(-1.0f, 1.0f) * 0.02f); // it seems to look best to have a point on one side of the ideal line, then the other point on the other side. - VectorSet( sh2, 0.33f,// + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right - -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f );// up + VectorSet(sh2, 0.33f, // + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right + -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f); // up } //---------------------------------------------------------------------------- -static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count, float startPerc, float endPerc ) +static void ApplyShape(vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count, float startPerc, float endPerc) //---------------------------------------------------------------------------- { - vec3_t point1, point2, fwd; - vec3_t rt, up; - float perc, dis; + vec3_t point1, point2, fwd; + vec3_t rt, up; + float perc, dis; - if ( count < 1 ) - { + if (count < 1) { // done recursing - DoLine2( start, end, right, sradius, eradius, startPerc, endPerc ); + DoLine2(start, end, right, sradius, eradius, startPerc, endPerc); return; } - CreateShape(); + CreateShape(); - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ) * 0.7f; - MakeNormalVectors( fwd, rt, up ); + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd) * 0.7f; + MakeNormalVectors(fwd, rt, up); perc = sh1[0]; - VectorScale( start, perc, point1 ); - VectorMA( point1, 1.0f - perc, end, point1 ); - VectorMA( point1, dis * sh1[1], rt, point1 ); - VectorMA( point1, dis * sh1[2], up, point1 ); + VectorScale(start, perc, point1); + VectorMA(point1, 1.0f - perc, end, point1); + VectorMA(point1, dis * sh1[1], rt, point1); + VectorMA(point1, dis * sh1[2], up, point1); // do a quick and dirty interpolation of the radius at that point float rads1, rads2; @@ -709,109 +679,102 @@ static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, f rads2 = sradius * 0.333f + eradius * 0.666f; // recursion - ApplyShape( start, point1, right, sradius, rads1, count - 1, startPerc, startPerc * 0.666f + endPerc * 0.333f ); + ApplyShape(start, point1, right, sradius, rads1, count - 1, startPerc, startPerc * 0.666f + endPerc * 0.333f); perc = sh2[0]; - VectorScale( start, perc, point2 ); - VectorMA( point2, 1.0f - perc, end, point2 ); - VectorMA( point2, dis * sh2[1], rt, point2 ); - VectorMA( point2, dis * sh2[2], up, point2 ); + VectorScale(start, perc, point2); + VectorMA(point2, 1.0f - perc, end, point2); + VectorMA(point2, dis * sh2[1], rt, point2); + VectorMA(point2, dis * sh2[2], up, point2); // recursion - ApplyShape( point2, point1, right, rads1, rads2, count - 1, startPerc * 0.333f + endPerc * 0.666f, startPerc * 0.666f + endPerc * 0.333f ); - ApplyShape( point2, end, right, rads2, eradius, count - 1, startPerc * 0.333f + endPerc * 0.666f, endPerc ); + ApplyShape(point2, point1, right, rads1, rads2, count - 1, startPerc * 0.333f + endPerc * 0.666f, startPerc * 0.666f + endPerc * 0.333f); + ApplyShape(point2, end, right, rads2, eradius, count - 1, startPerc * 0.333f + endPerc * 0.666f, endPerc); } //---------------------------------------------------------------------------- -static void DoBoltSeg( vec3_t start, vec3_t end, vec3_t right, float radius ) +static void DoBoltSeg(vec3_t start, vec3_t end, vec3_t right, float radius) //---------------------------------------------------------------------------- { refEntity_t *e; vec3_t fwd, old; - vec3_t cur, off={10,10,10}; + vec3_t cur, off = {10, 10, 10}; vec3_t rt, up; vec3_t temp; - int i; - float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; + int i; + float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; e = &backEnd.currentEntity->e; - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd); - if (dis > 2000) //freaky long + if (dis > 2000) // freaky long { -// ri.Printf( PRINT_WARNING, "DoBoltSeg: insane distance.\n" ); + // ri.Printf( PRINT_WARNING, "DoBoltSeg: insane distance.\n" ); dis = 2000; } - MakeNormalVectors( fwd, rt, up ); + MakeNormalVectors(fwd, rt, up); - VectorCopy( start, old ); + VectorCopy(start, old); newRadius = oldRadius = radius; - for ( i = 16; i <= dis; i+= 16 ) - { + for (i = 16; i <= dis; i += 16) { // because of our large step size, we may not actually draw to the end. In this case, fudge our percent so that we are basically complete - if ( i + 16 > dis ) - { + if (i + 16 > dis) { perc = 1.0f; - } - else - { + } else { // percentage of the amount of line completed perc = (float)i / dis; } // create our level of deviation for this point - VectorScale( fwd, Q_crandom(&e->frame) * 3.0f, temp ); // move less in fwd direction, chaos also does not affect this - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->angles[0], rt, temp ); // move more in direction perpendicular to line, angles is really the chaos - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->angles[0], up, temp ); // move more in direction perpendicular to line + VectorScale(fwd, Q_crandom(&e->frame) * 3.0f, temp); // move less in fwd direction, chaos also does not affect this + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->angles[0], rt, temp); // move more in direction perpendicular to line, angles is really the chaos + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->angles[0], up, temp); // move more in direction perpendicular to line // track our total level of offset from the ideal line - VectorAdd( off, temp, off ); + VectorAdd(off, temp, off); - // Move from start to end, always adding our current level of offset from the ideal line + // Move from start to end, always adding our current level of offset from the ideal line // Even though we are adding a random offset.....by nature, we always move from exactly start....to end - VectorAdd( start, off, cur ); - VectorScale( cur, 1.0f - perc, cur ); - VectorMA( cur, perc, end, cur ); + VectorAdd(start, off, cur); + VectorScale(cur, 1.0f - perc, cur); + VectorMA(cur, perc, end, cur); - if ( e->renderfx & RF_TAPERED ) - { + if (e->renderfx & RF_TAPERED) { // This does pretty close to perfect tapering since apply shape interpolates the old and new as it goes along. // by using one minus the square, the radius stays fairly constant, then drops off quickly at the very point of the bolt - oldRadius = radius * (1.0f-oldPerc*oldPerc); - newRadius = radius * (1.0f-perc*perc); + oldRadius = radius * (1.0f - oldPerc * oldPerc); + newRadius = radius * (1.0f - perc * perc); } // Apply the random shape to our line seg to give it some micro-detail-jaggy-coolness. - ApplyShape( cur, old, right, newRadius, oldRadius, 2 - r_lodbias->integer, 0, 1 ); + ApplyShape(cur, old, right, newRadius, oldRadius, 2 - r_lodbias->integer, 0, 1); // randomly split off to create little tendrils, but don't do it too close to the end and especially if we are not even of the forked variety - if (( e->renderfx & RF_FORKED ) && f_count > 0 && Q_random(&e->frame) > 0.93f && (1.0f - perc) > 0.8f ) - { + if ((e->renderfx & RF_FORKED) && f_count > 0 && Q_random(&e->frame) > 0.93f && (1.0f - perc) > 0.8f) { vec3_t newDest; f_count--; // Pick a point somewhere between the current point and the final endpoint - VectorAdd( cur, e->oldorigin, newDest ); - VectorScale( newDest, 0.5f, newDest ); + VectorAdd(cur, e->oldorigin, newDest); + VectorScale(newDest, 0.5f, newDest); // And then add some crazy offset - for ( int t = 0; t < 3; t++ ) - { + for (int t = 0; t < 3; t++) { newDest[t] += Q_crandom(&e->frame) * 80; } // we could branch off using OLD and NEWDEST, but that would allow multiple forks...whereas, we just want simpler brancing - DoBoltSeg( cur, newDest, right, newRadius ); + DoBoltSeg(cur, newDest, right, newRadius); } // Current point along the line becomes our new old attach point - VectorCopy( cur, old ); + VectorCopy(cur, old); oldPerc = perc; } } @@ -821,46 +784,42 @@ static void RB_SurfaceElectricity() //------------------------------------------ { refEntity_t *e; - vec3_t right, fwd; - vec3_t start, end; - vec3_t v1, v2; - float radius, perc = 1.0f, dis; + vec3_t right, fwd; + vec3_t start, end; + vec3_t v1, v2; + float radius, perc = 1.0f, dis; e = &backEnd.currentEntity->e; radius = e->radius; - VectorCopy( e->origin, start ); + VectorCopy(e->origin, start); - VectorSubtract( e->oldorigin, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(e->oldorigin, start, fwd); + dis = VectorNormalize(fwd); // see if we should grow from start to end - if ( e->renderfx & RF_GROW ) - { - perc = 1.0f - ( e->endTime - tr.refdef.time ) / e->angles[1]/*duration*/; + if (e->renderfx & RF_GROW) { + perc = 1.0f - (e->endTime - tr.refdef.time) / e->angles[1] /*duration*/; - if ( perc > 1.0f ) - { + if (perc > 1.0f) { perc = 1.0f; - } - else if ( perc < 0.0f ) - { + } else if (perc < 0.0f) { perc = 0.0f; } } - VectorMA( start, perc * dis, fwd, e->oldorigin ); - VectorCopy( e->oldorigin, end ); + VectorMA(start, perc * dis, fwd, e->oldorigin); + VectorCopy(e->oldorigin, end); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); // allow now more than three branches on branch type electricity f_count = 3; - DoBoltSeg( start, end, right, radius ); + DoBoltSeg(start, end, right, radius); } /* @@ -908,25 +867,24 @@ void RB_SurfacePolychain( srfPoly_t *p ) { tess.numVertexes = numv; } */ -void RB_SurfacePolychain( srfPoly_t *p ) { - int i; - int numv; +void RB_SurfacePolychain(srfPoly_t *p) { + int i; + int numv; - RB_CHECKOVERFLOW( p->numVerts, 3*(p->numVerts - 2) ); + RB_CHECKOVERFLOW(p->numVerts, 3 * (p->numVerts - 2)); // fan triangles into the tess array numv = tess.numVertexes; - for ( i = 0; i < p->numVerts; i++ ) { - VectorCopy( p->verts[i].xyz, tess.xyz[numv] ); + for (i = 0; i < p->numVerts; i++) { + VectorCopy(p->verts[i].xyz, tess.xyz[numv]); tess.texCoords[numv][0][0] = p->verts[i].st[0]; tess.texCoords[numv][0][1] = p->verts[i].st[1]; - byteAlias_t *baDest = (byteAlias_t *)&tess.vertexColors[numv++], - *baSource = (byteAlias_t *)&p->verts[ i ].modulate; + byteAlias_t *baDest = (byteAlias_t *)&tess.vertexColors[numv++], *baSource = (byteAlias_t *)&p->verts[i].modulate; baDest->i = baSource->i; } // generate fan indexes into the tess array - for ( i = 0; i < p->numVerts-2; i++ ) { + for (i = 0; i < p->numVerts - 2; i++) { tess.indexes[tess.numIndexes + 0] = tess.numVertexes; tess.indexes[tess.numIndexes + 1] = tess.numVertexes + i + 1; tess.indexes[tess.numIndexes + 2] = tess.numVertexes + i + 2; @@ -936,18 +894,18 @@ void RB_SurfacePolychain( srfPoly_t *p ) { tess.numVertexes = numv; } -inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { +inline static uint32_t ComputeFinalVertexColor(const byte *colors) { int k; byteAlias_t result; uint32_t r, g, b; - for ( k=0; k<4; k++ ) + for (k = 0; k < 4; k++) result.b[k] = colors[k]; - if ( tess.shader->lightmapIndex[0] != LIGHTMAP_BY_VERTEX ) + if (tess.shader->lightmapIndex[0] != LIGHTMAP_BY_VERTEX) return result.ui; - if ( r_fullbright->integer ) { + if (r_fullbright->integer) { result.b[0] = 255; result.b[1] = 255; result.b[2] = 255; @@ -955,21 +913,20 @@ inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { } // an optimization could be added here to compute the style[0] (which is always the world normal light) r = g = b = 0; - for( k=0; kstyles[k] < LS_UNUSED ) { + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->styles[k] < LS_UNUSED) { byte *styleColor = styleColors[tess.shader->styles[k]]; r += (uint32_t)(*colors++) * (uint32_t)(*styleColor++); g += (uint32_t)(*colors++) * (uint32_t)(*styleColor++); b += (uint32_t)(*colors++) * (uint32_t)(*styleColor); colors++; - } - else + } else break; } - result.b[0] = Com_Clamp( 0, 255, r >> 8 ); - result.b[1] = Com_Clamp( 0, 255, g >> 8 ); - result.b[2] = Com_Clamp( 0, 255, b >> 8 ); + result.b[0] = Com_Clamp(0, 255, r >> 8); + result.b[1] = Com_Clamp(0, 255, g >> 8); + result.b[2] = Com_Clamp(0, 255, b >> 8); return result.ui; } @@ -979,39 +936,38 @@ inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { RB_SurfaceTriangles ============= */ -void RB_SurfaceTriangles( srfTriangles_t *srf ) { - int i, k; - drawVert_t *dv; - float *xyz, *normal, *texCoords; - byte *color; - int dlightBits; +void RB_SurfaceTriangles(srfTriangles_t *srf) { + int i, k; + drawVert_t *dv; + float *xyz, *normal, *texCoords; + byte *color; + int dlightBits; dlightBits = srf->dlightBits; tess.dlightBits |= dlightBits; - RB_CHECKOVERFLOW( srf->numVerts, srf->numIndexes ); + RB_CHECKOVERFLOW(srf->numVerts, srf->numIndexes); - for ( i = 0 ; i < srf->numIndexes ; i += 3 ) { - tess.indexes[ tess.numIndexes + i + 0 ] = tess.numVertexes + srf->indexes[ i + 0 ]; - tess.indexes[ tess.numIndexes + i + 1 ] = tess.numVertexes + srf->indexes[ i + 1 ]; - tess.indexes[ tess.numIndexes + i + 2 ] = tess.numVertexes + srf->indexes[ i + 2 ]; + for (i = 0; i < srf->numIndexes; i += 3) { + tess.indexes[tess.numIndexes + i + 0] = tess.numVertexes + srf->indexes[i + 0]; + tess.indexes[tess.numIndexes + i + 1] = tess.numVertexes + srf->indexes[i + 1]; + tess.indexes[tess.numIndexes + i + 2] = tess.numVertexes + srf->indexes[i + 2]; } tess.numIndexes += srf->numIndexes; dv = srf->verts; - xyz = tess.xyz[ tess.numVertexes ]; - normal = tess.normal[ tess.numVertexes ]; - texCoords = tess.texCoords[ tess.numVertexes ][0]; - color = tess.vertexColors[ tess.numVertexes ]; + xyz = tess.xyz[tess.numVertexes]; + normal = tess.normal[tess.numVertexes]; + texCoords = tess.texCoords[tess.numVertexes][0]; + color = tess.vertexColors[tess.numVertexes]; - for ( i = 0 ; i < srf->numVerts ; i++, dv++) - { + for (i = 0; i < srf->numVerts; i++, dv++) { xyz[0] = dv->xyz[0]; xyz[1] = dv->xyz[1]; xyz[2] = dv->xyz[2]; xyz += 4; - //if ( needsNormal ) + // if ( needsNormal ) { normal[0] = dv->normal[0]; normal[1] = dv->normal[1]; @@ -1022,46 +978,39 @@ void RB_SurfaceTriangles( srfTriangles_t *srf ) { texCoords[0] = dv->st[0]; texCoords[1] = dv->st[1]; - for(k=0;klightmapIndex[k] >= 0) - { - texCoords[2+(k*2)] = dv->lightmap[k][0]; - texCoords[2+(k*2)+1] = dv->lightmap[k][1]; - } - else - { // can't have an empty slot in the middle, so we are done + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->lightmapIndex[k] >= 0) { + texCoords[2 + (k * 2)] = dv->lightmap[k][0]; + texCoords[2 + (k * 2) + 1] = dv->lightmap[k][1]; + } else { // can't have an empty slot in the middle, so we are done break; } } - texCoords += NUM_TEX_COORDS*2; + texCoords += NUM_TEX_COORDS * 2; *(unsigned *)color = ComputeFinalVertexColor((byte *)dv->color); color += 4; } - for ( i = 0 ; i < srf->numVerts ; i++ ) { - tess.vertexDlightBits[ tess.numVertexes + i] = dlightBits; + for (i = 0; i < srf->numVerts; i++) { + tess.vertexDlightBits[tess.numVertexes + i] = dlightBits; } tess.numVertexes += srf->numVerts; } - - /* ============== RB_SurfaceBeam ============== */ -static void RB_SurfaceBeam( void ) -{ +static void RB_SurfaceBeam(void) { #define NUM_BEAM_SEGS 6 refEntity_t *e; - int i; + int i; vec3_t perpvec; vec3_t direction, normalized_direction; - vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; + vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; vec3_t oldorigin, origin; e = &backEnd.currentEntity->e; @@ -1078,117 +1027,108 @@ static void RB_SurfaceBeam( void ) normalized_direction[1] = direction[1] = oldorigin[1] - origin[1]; normalized_direction[2] = direction[2] = oldorigin[2] - origin[2]; - if ( VectorNormalize( normalized_direction ) == 0 ) + if (VectorNormalize(normalized_direction) == 0) return; - PerpendicularVector( perpvec, normalized_direction ); + PerpendicularVector(perpvec, normalized_direction); - VectorScale( perpvec, 4, perpvec ); + VectorScale(perpvec, 4, perpvec); - for ( i = 0; i < NUM_BEAM_SEGS ; i++ ) - { - RotatePointAroundVector( start_points[i], normalized_direction, perpvec, (360.0/NUM_BEAM_SEGS)*i ); -// VectorAdd( start_points[i], origin, start_points[i] ); - VectorAdd( start_points[i], direction, end_points[i] ); + for (i = 0; i < NUM_BEAM_SEGS; i++) { + RotatePointAroundVector(start_points[i], normalized_direction, perpvec, (360.0 / NUM_BEAM_SEGS) * i); + // VectorAdd( start_points[i], origin, start_points[i] ); + VectorAdd(start_points[i], direction, end_points[i]); } - GL_Bind( tr.whiteImage ); + GL_Bind(tr.whiteImage); - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); - switch(e->skinNum) - { - case 1://Green - qglColor3f( 0, 1, 0 ); + switch (e->skinNum) { + case 1: // Green + qglColor3f(0, 1, 0); break; - case 2://Blue - qglColor3f( 0.5, 0.5, 1 ); + case 2: // Blue + qglColor3f(0.5, 0.5, 1); break; - case 0://red + case 0: // red default: - qglColor3f( 1, 0, 0 ); + qglColor3f(1, 0, 0); break; } - qglBegin( GL_TRIANGLE_STRIP ); - for ( i = 0; i <= NUM_BEAM_SEGS; i++ ) { - qglVertex3fv( start_points[ i % NUM_BEAM_SEGS] ); - qglVertex3fv( end_points[ i % NUM_BEAM_SEGS] ); + qglBegin(GL_TRIANGLE_STRIP); + for (i = 0; i <= NUM_BEAM_SEGS; i++) { + qglVertex3fv(start_points[i % NUM_BEAM_SEGS]); + qglVertex3fv(end_points[i % NUM_BEAM_SEGS]); } qglEnd(); } - //------------------ // DoSprite //------------------ -static void DoSprite( vec3_t origin, float radius, float rotation ) -{ - float s, c; - float ang; - vec3_t left, up; +static void DoSprite(vec3_t origin, float radius, float rotation) { + float s, c; + float ang; + vec3_t left, up; ang = M_PI * rotation / 180.0f; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(origin, left, up, backEnd.currentEntity->e.shaderRGBA); } //------------------ // RB_SurfaceSaber //------------------ -static void RB_SurfaceSaberGlow() -{ - vec3_t end; +static void RB_SurfaceSaberGlow() { + vec3_t end; refEntity_t *e; e = &backEnd.currentEntity->e; // Render the glow part of the blade - for ( float i = e->saberLength; i > 0; i -= e->radius * 0.65f ) - { - VectorMA( e->origin, i, e->axis[0], end ); + for (float i = e->saberLength; i > 0; i -= e->radius * 0.65f) { + VectorMA(e->origin, i, e->axis[0], end); - DoSprite( end, e->radius, 0.0f );//Q_flrand(0.0f, 1.0f) * 360.0f ); + DoSprite(end, e->radius, 0.0f); // Q_flrand(0.0f, 1.0f) * 360.0f ); e->radius += 0.017f; } // Big hilt sprite // Please don't kill me Pat...I liked the hilt glow blob, but wanted a subtle pulse.:) Feel free to ditch it if you don't like it. --Jeff // Please don't kill me Jeff... The pulse is good, but now I want the halo bigger if the saber is shorter... --Pat - DoSprite( e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f );//Q_flrand(0.0f, 1.0f) * 360.0f ); + DoSprite(e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f); // Q_flrand(0.0f, 1.0f) * 360.0f ); } /* ** LerpMeshVertexes */ -static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) -{ - short *oldXyz, *newXyz, *oldNormals, *newNormals; - float *outXyz, *outNormal; - float oldXyzScale, newXyzScale; - float oldNormalScale, newNormalScale; - int vertNum; +static void LerpMeshVertexes(md3Surface_t *surf, float backlerp) { + short *oldXyz, *newXyz, *oldNormals, *newNormals; + float *outXyz, *outNormal; + float oldXyzScale, newXyzScale; + float oldNormalScale, newNormalScale; + int vertNum; unsigned lat, lng; - int numVerts; + int numVerts; outXyz = tess.xyz[tess.numVertexes]; outNormal = tess.normal[tess.numVertexes]; - newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) - + (backEnd.currentEntity->e.frame * surf->numVerts * 4); + newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + (backEnd.currentEntity->e.frame * surf->numVerts * 4); newNormals = newXyz + 3; newXyzScale = MD3_XYZ_SCALE * (1.0 - backlerp); @@ -1196,46 +1136,39 @@ static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) numVerts = surf->numVerts; - if ( backlerp == 0 ) { + if (backlerp == 0) { // // just copy the vertexes // - for (vertNum=0 ; vertNum < numVerts ; vertNum++, - newXyz += 4, newNormals += 4, - outXyz += 4, outNormal += 4) - { + for (vertNum = 0; vertNum < numVerts; vertNum++, newXyz += 4, newNormals += 4, outXyz += 4, outNormal += 4) { outXyz[0] = newXyz[0] * newXyzScale; outXyz[1] = newXyz[1] * newXyzScale; outXyz[2] = newXyz[2] * newXyzScale; - lat = ( newNormals[0] >> 8 ) & 0xff; - lng = ( newNormals[0] & 0xff ); - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat = (newNormals[0] >> 8) & 0xff; + lng = (newNormals[0] & 0xff); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) // decode Z as cos( long ) - outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + outNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + outNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; } } else { // // interpolate and copy the vertex and normal // - oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) - + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); + oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); oldNormals = oldXyz + 3; oldXyzScale = MD3_XYZ_SCALE * backlerp; oldNormalScale = backlerp; - for (vertNum=0 ; vertNum < numVerts ; vertNum++, - oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, - outXyz += 4, outNormal += 4) - { + for (vertNum = 0; vertNum < numVerts; vertNum++, oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, outXyz += 4, outNormal += 4) { vec3_t uncompressedOldNormal, uncompressedNewNormal; // interpolate the xyz @@ -1244,28 +1177,28 @@ static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) outXyz[2] = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale; // FIXME: interpolate lat/long instead? - lat = ( newNormals[0] >> 8 ) & 0xff; - lng = ( newNormals[0] & 0xff ); + lat = (newNormals[0] >> 8) & 0xff; + lng = (newNormals[0] & 0xff); lat *= 4; lng *= 4; - uncompressedNewNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedNewNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; uncompressedNewNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - uncompressedNewNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + uncompressedNewNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; - lat = ( oldNormals[0] >> 8 ) & 0xff; - lng = ( oldNormals[0] & 0xff ); + lat = (oldNormals[0] >> 8) & 0xff; + lng = (oldNormals[0] & 0xff); lat *= 4; lng *= 4; - uncompressedOldNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedOldNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; uncompressedOldNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - uncompressedOldNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + uncompressedOldNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; outNormal[0] = uncompressedOldNormal[0] * oldNormalScale + uncompressedNewNormal[0] * newNormalScale; outNormal[1] = uncompressedOldNormal[1] * oldNormalScale + uncompressedNewNormal[1] * newNormalScale; outNormal[2] = uncompressedOldNormal[2] * oldNormalScale + uncompressedNewNormal[2] * newNormalScale; - VectorNormalize (outNormal); + VectorNormalize(outNormal); } } } @@ -1276,73 +1209,72 @@ RB_SurfaceMesh ============= */ void RB_SurfaceMesh(md3Surface_t *surface) { - int j; - float backlerp; - int *triangles; - float *texCoords; - int indexes; - int Bob, Doug; - int numVerts; - - if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) { + int j; + float backlerp; + int *triangles; + float *texCoords; + int indexes; + int Bob, Doug; + int numVerts; + + if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) { backlerp = 0; - } else { + } else { backlerp = backEnd.currentEntity->e.backlerp; } - RB_CHECKOVERFLOW( surface->numVerts, surface->numTriangles*3 ); + RB_CHECKOVERFLOW(surface->numVerts, surface->numTriangles * 3); - LerpMeshVertexes (surface, backlerp); + LerpMeshVertexes(surface, backlerp); - triangles = (int *) ((byte *)surface + surface->ofsTriangles); + triangles = (int *)((byte *)surface + surface->ofsTriangles); indexes = surface->numTriangles * 3; Bob = tess.numIndexes; Doug = tess.numVertexes; - for (j = 0 ; j < indexes ; j++) { + for (j = 0; j < indexes; j++) { tess.indexes[Bob + j] = Doug + triangles[j]; } tess.numIndexes += indexes; - texCoords = (float *) ((byte *)surface + surface->ofsSt); + texCoords = (float *)((byte *)surface + surface->ofsSt); numVerts = surface->numVerts; - for ( j = 0; j < numVerts; j++ ) { - tess.texCoords[Doug + j][0][0] = texCoords[j*2+0]; - tess.texCoords[Doug + j][0][1] = texCoords[j*2+1]; + for (j = 0; j < numVerts; j++) { + tess.texCoords[Doug + j][0][0] = texCoords[j * 2 + 0]; + tess.texCoords[Doug + j][0][1] = texCoords[j * 2 + 1]; // FIXME: fill in lightmapST for completeness? } tess.numVertexes += surface->numVerts; } - /* ============== RB_SurfaceFace ============== */ -void RB_SurfaceFace( srfSurfaceFace_t *surf ) { - int i, j, k; +void RB_SurfaceFace(srfSurfaceFace_t *surf) { + int i, j, k; unsigned int *indices; - glIndex_t *tessIndexes; - float *v; - float *normal; - int ndx; - int Bob; - int numPoints; - int dlightBits; - byteAlias_t ba; + glIndex_t *tessIndexes; + float *v; + float *normal; + int ndx; + int Bob; + int numPoints; + int dlightBits; + byteAlias_t ba; - RB_CHECKOVERFLOW( surf->numPoints, surf->numIndices ); + RB_CHECKOVERFLOW(surf->numPoints, surf->numIndices); dlightBits = surf->dlightBits; tess.dlightBits |= dlightBits; - indices = ( unsigned * ) ( ( ( char * ) surf ) + surf->ofsIndices ); + indices = (unsigned *)(((char *)surf) + surf->ofsIndices); Bob = tess.numVertexes; tessIndexes = tess.indexes + tess.numIndexes; - for ( i = surf->numIndices-1 ; i >= 0 ; i-- ) { + for (i = surf->numIndices - 1; i >= 0; i--) { tessIndexes[i] = indices[i] + Bob; } @@ -1354,32 +1286,28 @@ void RB_SurfaceFace( srfSurfaceFace_t *surf ) { numPoints = surf->numPoints; - //if ( tess.shader->needsNormal ) + // if ( tess.shader->needsNormal ) { normal = surf->plane.normal; - for ( i = 0, ndx = tess.numVertexes; i < numPoints; i++, ndx++ ) { - VectorCopy( normal, tess.normal[ndx] ); + for (i = 0, ndx = tess.numVertexes; i < numPoints; i++, ndx++) { + VectorCopy(normal, tess.normal[ndx]); } } - for ( i = 0, v = surf->points[0], ndx = tess.numVertexes; i < numPoints; i++, v += VERTEXSIZE, ndx++ ) { - VectorCopy( v, tess.xyz[ndx]); + for (i = 0, v = surf->points[0], ndx = tess.numVertexes; i < numPoints; i++, v += VERTEXSIZE, ndx++) { + VectorCopy(v, tess.xyz[ndx]); tess.texCoords[ndx][0][0] = v[3]; tess.texCoords[ndx][0][1] = v[4]; - for(k=0;klightmapIndex[k] >= 0) - { - tess.texCoords[ndx][k+1][0] = v[VERTEX_LM+(k*2)]; - tess.texCoords[ndx][k+1][1] = v[VERTEX_LM+(k*2)+1]; - } - else - { + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->lightmapIndex[k] >= 0) { + tess.texCoords[ndx][k + 1][0] = v[VERTEX_LM + (k * 2)]; + tess.texCoords[ndx][k + 1][1] = v[VERTEX_LM + (k * 2) + 1]; + } else { break; } } - ba.ui = ComputeFinalVertexColor( (byte *)&v[VERTEX_COLOR] ); - for ( j=0; j<4; j++ ) + ba.ui = ComputeFinalVertexColor((byte *)&v[VERTEX_COLOR]); + for (j = 0; j < 4; j++) tess.vertexColors[ndx][j] = ba.b[j]; tess.vertexDlightBits[ndx] = dlightBits; } @@ -1387,31 +1315,27 @@ void RB_SurfaceFace( srfSurfaceFace_t *surf ) { tess.numVertexes += surf->numPoints; } - -static float LodErrorForVolume( vec3_t local, float radius ) { - vec3_t world; - float d; +static float LodErrorForVolume(vec3_t local, float radius) { + vec3_t world; + float d; // never let it go negative - if ( r_lodCurveError->value < 0 ) { + if (r_lodCurveError->value < 0) { return 0; } - world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + - local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; - world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + - local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; - world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + - local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; + world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; + world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; + world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; - VectorSubtract( world, backEnd.viewParms.ori.origin, world ); - d = DotProduct( world, backEnd.viewParms.ori.axis[0] ); + VectorSubtract(world, backEnd.viewParms.ori.origin, world); + d = DotProduct(world, backEnd.viewParms.ori.axis[0]); - if ( d < 0 ) { + if (d < 0) { d = -d; } d -= radius; - if ( d < 1 ) { + if (d < 1) { d = 1; } @@ -1425,79 +1349,78 @@ RB_SurfaceGrid Just copy the grid of points and triangulate ============= */ -void RB_SurfaceGrid( srfGridMesh_t *cv ) { - int i, j, k; - float *xyz; - float *texCoords; - float *normal; +void RB_SurfaceGrid(srfGridMesh_t *cv) { + int i, j, k; + float *xyz; + float *texCoords; + float *normal; unsigned char *color; - drawVert_t *dv; - int rows, irows, vrows; - int used; - int widthTable[MAX_GRID_SIZE]; - int heightTable[MAX_GRID_SIZE]; - float lodError; - int lodWidth, lodHeight; - int numVertexes; - int dlightBits; - int *vDlightBits; + drawVert_t *dv; + int rows, irows, vrows; + int used; + int widthTable[MAX_GRID_SIZE]; + int heightTable[MAX_GRID_SIZE]; + float lodError; + int lodWidth, lodHeight; + int numVertexes; + int dlightBits; + int *vDlightBits; dlightBits = cv->dlightBits; tess.dlightBits |= dlightBits; // determine the allowable discrepance - lodError = LodErrorForVolume( cv->lodOrigin, cv->lodRadius ); + lodError = LodErrorForVolume(cv->lodOrigin, cv->lodRadius); // determine which rows and columns of the subdivision // we are actually going to use widthTable[0] = 0; lodWidth = 1; - for ( i = 1 ; i < cv->width-1 ; i++ ) { - if ( cv->widthLodError[i] <= lodError ) { + for (i = 1; i < cv->width - 1; i++) { + if (cv->widthLodError[i] <= lodError) { widthTable[lodWidth] = i; lodWidth++; } } - widthTable[lodWidth] = cv->width-1; + widthTable[lodWidth] = cv->width - 1; lodWidth++; heightTable[0] = 0; lodHeight = 1; - for ( i = 1 ; i < cv->height-1 ; i++ ) { - if ( cv->heightLodError[i] <= lodError ) { + for (i = 1; i < cv->height - 1; i++) { + if (cv->heightLodError[i] <= lodError) { heightTable[lodHeight] = i; lodHeight++; } } - heightTable[lodHeight] = cv->height-1; + heightTable[lodHeight] = cv->height - 1; lodHeight++; - // very large grids may have more points or indexes than can be fit // in the tess structure, so we may have to issue it in multiple passes used = 0; rows = 0; - while ( used < lodHeight - 1 ) { + while (used < lodHeight - 1) { // see how many rows of both verts and indexes we can add without overflowing do { - vrows = ( SHADER_MAX_VERTEXES - tess.numVertexes ) / lodWidth; - irows = ( SHADER_MAX_INDEXES - tess.numIndexes ) / ( lodWidth * 6 ); + vrows = (SHADER_MAX_VERTEXES - tess.numVertexes) / lodWidth; + irows = (SHADER_MAX_INDEXES - tess.numIndexes) / (lodWidth * 6); // if we don't have enough space for at least one strip, flush the buffer - if ( vrows < 2 || irows < 1 ) { + if (vrows < 2 || irows < 1) { RB_EndSurface(); - RB_BeginSurface(tess.shader, tess.fogNum ); + RB_BeginSurface(tess.shader, tess.fogNum); } else { break; } - } while ( 1 ); + } while (1); rows = irows; - if ( vrows < irows + 1 ) { + if (vrows < irows + 1) { rows = vrows - 1; } - if ( used + rows > lodHeight ) { + if (used + rows > lodHeight) { rows = lodHeight - used; } @@ -1506,13 +1429,12 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { xyz = tess.xyz[numVertexes]; normal = tess.normal[numVertexes]; texCoords = tess.texCoords[numVertexes][0]; - color = ( unsigned char * ) &tess.vertexColors[numVertexes]; + color = (unsigned char *)&tess.vertexColors[numVertexes]; vDlightBits = &tess.vertexDlightBits[numVertexes]; - for ( i = 0 ; i < rows ; i++ ) { - for ( j = 0 ; j < lodWidth ; j++ ) { - dv = cv->verts + heightTable[ used + i ] * cv->width - + widthTable[ j ]; + for (i = 0; i < rows; i++) { + for (j = 0; j < lodWidth; j++) { + dv = cv->verts + heightTable[used + i] * cv->width + widthTable[j]; xyz[0] = dv->xyz[0]; xyz[1] = dv->xyz[1]; @@ -1522,14 +1444,13 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { texCoords[0] = dv->st[0]; texCoords[1] = dv->st[1]; - for(k=0;klightmap[k][0]; - texCoords[2+(k*2)+1]= dv->lightmap[k][1]; + for (k = 0; k < MAXLIGHTMAPS; k++) { + texCoords[2 + (k * 2)] = dv->lightmap[k][0]; + texCoords[2 + (k * 2) + 1] = dv->lightmap[k][1]; } - texCoords += NUM_TEX_COORDS*2; + texCoords += NUM_TEX_COORDS * 2; -// if ( needsNormal ) + // if ( needsNormal ) { normal[0] = dv->normal[0]; normal[1] = dv->normal[1]; @@ -1544,29 +1465,29 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { // add the indexes { - int numIndexes; - int w, h; + int numIndexes; + int w, h; h = rows - 1; w = lodWidth - 1; numIndexes = tess.numIndexes; - for (i = 0 ; i < h ; i++) { - for (j = 0 ; j < w ; j++) { - int v1, v2, v3, v4; + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) { + int v1, v2, v3, v4; // vertex order to be reckognized as tristrips - v1 = numVertexes + i*lodWidth + j + 1; + v1 = numVertexes + i * lodWidth + j + 1; v2 = v1 - 1; v3 = v2 + lodWidth; v4 = v3 + 1; tess.indexes[numIndexes] = v2; - tess.indexes[numIndexes+1] = v3; - tess.indexes[numIndexes+2] = v1; + tess.indexes[numIndexes + 1] = v3; + tess.indexes[numIndexes + 2] = v1; - tess.indexes[numIndexes+3] = v1; - tess.indexes[numIndexes+4] = v3; - tess.indexes[numIndexes+5] = v4; + tess.indexes[numIndexes + 3] = v1; + tess.indexes[numIndexes + 4] = v3; + tess.indexes[numIndexes + 5] = v4; numIndexes += 6; } } @@ -1580,82 +1501,74 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { } } -#define LATHE_SEG_STEP 10 -#define BEZIER_STEP 0.05f // must be in the range of 0 to 1 +#define LATHE_SEG_STEP 10 +#define BEZIER_STEP 0.05f // must be in the range of 0 to 1 // FIXME: This function is horribly expensive -static void RB_SurfaceLathe() -{ +static void RB_SurfaceLathe() { refEntity_t *e; - vec2_t pt, oldpt, l_oldpt; - vec2_t pt2, oldpt2, l_oldpt2; - float bezierStep, latheStep; - float temp, mu, mum1; - float mum13, mu3, group1, group2; - float s, c, d = 1.0f, pain = 0.0f; - int i, t, vbase; + vec2_t pt, oldpt, l_oldpt; + vec2_t pt2, oldpt2, l_oldpt2; + float bezierStep, latheStep; + float temp, mu, mum1; + float mum13, mu3, group1, group2; + float s, c, d = 1.0f, pain = 0.0f; + int i, t, vbase; e = &backEnd.currentEntity->e; - if ( e->endTime && e->endTime > backEnd.refdef.time ) - { - d = 1.0f - ( e->endTime - backEnd.refdef.time ) / 1000.0f; + if (e->endTime && e->endTime > backEnd.refdef.time) { + d = 1.0f - (e->endTime - backEnd.refdef.time) / 1000.0f; } - if ( e->frame && e->frame + 1000 > backEnd.refdef.time ) - { - pain = ( backEnd.refdef.time - e->frame ) / 1000.0f; -// pain *= pain; - pain = ( 1.0f - pain ) * 0.08f; + if (e->frame && e->frame + 1000 > backEnd.refdef.time) { + pain = (backEnd.refdef.time - e->frame) / 1000.0f; + // pain *= pain; + pain = (1.0f - pain) * 0.08f; } - VectorSet2( l_oldpt, e->axis[0][0], e->axis[0][1] ); + VectorSet2(l_oldpt, e->axis[0][0], e->axis[0][1]); // do scalability stuff...r_lodbias 0-3 int lod = r_lodbias->integer + 1; - if ( lod > 4 ) - { + if (lod > 4) { lod = 4; } - if ( lod < 1 ) - { + if (lod < 1) { lod = 1; } bezierStep = BEZIER_STEP * lod; latheStep = LATHE_SEG_STEP * lod; // Do bezier profile strip, then lathe this around to make a 3d model - for ( mu = 0.0f; mu <= 1.01f * d; mu += bezierStep ) - { + for (mu = 0.0f; mu <= 1.01f * d; mu += bezierStep) { // Four point curve - mum1 = 1 - mu; - mum13 = mum1 * mum1 * mum1; - mu3 = mu * mu * mu; - group1 = 3 * mu * mum1 * mum1; - group2 = 3 * mu * mu *mum1; + mum1 = 1 - mu; + mum13 = mum1 * mum1 * mum1; + mu3 = mu * mu * mu; + group1 = 3 * mu * mum1 * mum1; + group2 = 3 * mu * mu * mum1; // Calc the current point on the curve - for ( i = 0; i < 2; i++ ) - { + for (i = 0; i < 2; i++) { l_oldpt2[i] = mum13 * e->axis[0][i] + group1 * e->axis[1][i] + group2 * e->axis[2][i] + mu3 * e->oldorigin[i]; } - VectorSet2( oldpt, l_oldpt[0], 0 ); - VectorSet2( oldpt2, l_oldpt2[0], 0 ); + VectorSet2(oldpt, l_oldpt[0], 0); + VectorSet2(oldpt2, l_oldpt2[0], 0); // lathe patch section around in a complete circle - for ( t = latheStep; t <= 360; t += latheStep ) - { - VectorSet2( pt, l_oldpt[0], 0 ); - VectorSet2( pt2, l_oldpt2[0], 0 ); + for (t = latheStep; t <= 360; t += latheStep) { + VectorSet2(pt, l_oldpt[0], 0); + VectorSet2(pt2, l_oldpt2[0], 0); - s = sin( DEG2RAD( t )); - c = cos( DEG2RAD( t )); + s = sin(DEG2RAD(t)); + c = cos(DEG2RAD(t)); // rotate lathe points -//c -s 0 -//s c 0 -//0 0 1 + // c -s 0 + // s c 0 + // 0 0 1 temp = c * pt[0] - s * pt[1]; pt[1] = s * pt[0] + c * pt[1]; pt[0] = temp; @@ -1663,53 +1576,53 @@ static void RB_SurfaceLathe() pt2[1] = s * pt2[0] + c * pt2[1]; pt2[0] = temp; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; // Actually generate the necessary verts - VectorSet( tess.normal[tess.numVertexes], oldpt[0], oldpt[1], l_oldpt[1] ); - VectorAdd( e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes] ); - VectorNormalize( tess.normal[tess.numVertexes] ); + VectorSet(tess.normal[tess.numVertexes], oldpt[0], oldpt[1], l_oldpt[1]); + VectorAdd(e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes]); + VectorNormalize(tess.normal[tess.numVertexes]); i = oldpt[0] * 0.1f + oldpt[1] * 0.1f; - tess.texCoords[tess.numVertexes][0][0] = (t-latheStep)/360.0f; - tess.texCoords[tess.numVertexes][0][1] = mu-bezierStep + cos( i + backEnd.refdef.floatTime ) * pain; + tess.texCoords[tess.numVertexes][0][0] = (t - latheStep) / 360.0f; + tess.texCoords[tess.numVertexes][0][1] = mu - bezierStep + cos(i + backEnd.refdef.floatTime) * pain; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = e->shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorSet( tess.normal[tess.numVertexes], oldpt2[0], oldpt2[1], l_oldpt2[1] ); - VectorAdd( e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes] ); - VectorNormalize( tess.normal[tess.numVertexes] ); + VectorSet(tess.normal[tess.numVertexes], oldpt2[0], oldpt2[1], l_oldpt2[1]); + VectorAdd(e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes]); + VectorNormalize(tess.normal[tess.numVertexes]); i = oldpt2[0] * 0.1f + oldpt2[1] * 0.1f; - tess.texCoords[tess.numVertexes][0][0] = (t-latheStep) / 360.0f; - tess.texCoords[tess.numVertexes][0][1] = mu + cos( i + backEnd.refdef.floatTime ) * pain; + tess.texCoords[tess.numVertexes][0][0] = (t - latheStep) / 360.0f; + tess.texCoords[tess.numVertexes][0][1] = mu + cos(i + backEnd.refdef.floatTime) * pain; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = e->shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorSet( tess.normal[tess.numVertexes], pt[0], pt[1], l_oldpt[1] ); - VectorAdd( e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes] ); - VectorNormalize( tess.normal[tess.numVertexes] ); + VectorSet(tess.normal[tess.numVertexes], pt[0], pt[1], l_oldpt[1]); + VectorAdd(e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes]); + VectorNormalize(tess.normal[tess.numVertexes]); i = pt[0] * 0.1f + pt[1] * 0.1f; - tess.texCoords[tess.numVertexes][0][0] = t/360.0f; - tess.texCoords[tess.numVertexes][0][1] = mu-bezierStep + cos( i + backEnd.refdef.floatTime ) * pain; + tess.texCoords[tess.numVertexes][0][0] = t / 360.0f; + tess.texCoords[tess.numVertexes][0][1] = mu - bezierStep + cos(i + backEnd.refdef.floatTime) * pain; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = e->shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorSet( tess.normal[tess.numVertexes], pt2[0], pt2[1], l_oldpt2[1] ); - VectorAdd( e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes] ); - VectorNormalize( tess.normal[tess.numVertexes] ); + VectorSet(tess.normal[tess.numVertexes], pt2[0], pt2[1], l_oldpt2[1]); + VectorAdd(e->origin, tess.normal[tess.numVertexes], tess.xyz[tess.numVertexes]); + VectorNormalize(tess.normal[tess.numVertexes]); i = pt2[0] * 0.1f + pt2[1] * 0.1f; - tess.texCoords[tess.numVertexes][0][0] = t/360.0f; - tess.texCoords[tess.numVertexes][0][1] = mu + cos( i + backEnd.refdef.floatTime ) * pain; + tess.texCoords[tess.numVertexes][0][0] = t / 360.0f; + tess.texCoords[tess.numVertexes][0][1] = mu + cos(i + backEnd.refdef.floatTime) * pain; tess.vertexColors[tess.numVertexes][0] = e->shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = e->shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[2]; @@ -1725,85 +1638,52 @@ static void RB_SurfaceLathe() tess.indexes[tess.numIndexes++] = vbase; // Shuffle new points to old - VectorCopy2( pt, oldpt ); - VectorCopy2( pt2, oldpt2 ); + VectorCopy2(pt, oldpt); + VectorCopy2(pt2, oldpt2); } // shuffle lathe points - VectorCopy2( l_oldpt2, l_oldpt ); + VectorCopy2(l_oldpt2, l_oldpt); } } -#define DISK_DEF 4 -#define TUBE_DEF 6 +#define DISK_DEF 4 +#define TUBE_DEF 6 -static void RB_SurfaceClouds() -{ +static void RB_SurfaceClouds() { // Disk definition - float diskStripDef[DISK_DEF] = { - 0.0f, - 0.4f, - 0.7f, - 1.0f }; - - float diskAlphaDef[DISK_DEF] = { - 1.0f, - 1.0f, - 0.4f, - 0.0f }; - - float diskCurveDef[DISK_DEF] = { - 0.0f, - 0.0f, - 0.008f, - 0.02f }; + float diskStripDef[DISK_DEF] = {0.0f, 0.4f, 0.7f, 1.0f}; + + float diskAlphaDef[DISK_DEF] = {1.0f, 1.0f, 0.4f, 0.0f}; + + float diskCurveDef[DISK_DEF] = {0.0f, 0.0f, 0.008f, 0.02f}; // tube definition - float tubeStripDef[TUBE_DEF] = { - 0.0f, - 0.05f, - 0.1f, - 0.5f, - 0.7f, - 1.0f }; - - float tubeAlphaDef[TUBE_DEF] = { - 0.0f, - 0.45f, - 1.0f, - 1.0f, - 0.45f, - 0.0f }; - - float tubeCurveDef[TUBE_DEF] = { - 0.0f, - 0.004f, - 0.006f, - 0.01f, - 0.006f, - 0.0f }; + float tubeStripDef[TUBE_DEF] = {0.0f, 0.05f, 0.1f, 0.5f, 0.7f, 1.0f}; + + float tubeAlphaDef[TUBE_DEF] = {0.0f, 0.45f, 1.0f, 1.0f, 0.45f, 0.0f}; + + float tubeCurveDef[TUBE_DEF] = {0.0f, 0.004f, 0.006f, 0.01f, 0.006f, 0.0f}; refEntity_t *e; - vec3_t pt, oldpt; - vec3_t pt2, oldpt2; - float latheStep = 30.0f; - float s, c, temp; - float *stripDef, *alphaDef, *curveDef, ct; - int i, t, vbase; + vec3_t pt, oldpt; + vec3_t pt2, oldpt2; + float latheStep = 30.0f; + float s, c, temp; + float *stripDef, *alphaDef, *curveDef, ct; + int i, t, vbase; e = &backEnd.currentEntity->e; // select which type we shall be doing - if ( e->renderfx & RF_GROW ) // doing tube type + if (e->renderfx & RF_GROW) // doing tube type { ct = TUBE_DEF; stripDef = tubeStripDef; alphaDef = tubeAlphaDef; curveDef = tubeCurveDef; e->backlerp *= -1; // needs to be reversed - } - else - { + } else { ct = DISK_DEF; stripDef = diskStripDef; alphaDef = diskAlphaDef; @@ -1811,77 +1691,68 @@ static void RB_SurfaceClouds() } // do the strip def, then lathe this around to make a 3d model - for ( i = 0; i < ct - 1; i++ ) - { - VectorSet( oldpt, (stripDef[i] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i] * e->radius * e->backlerp ); - VectorSet( oldpt2, (stripDef[i+1] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i+1] * e->radius * e->backlerp ); + for (i = 0; i < ct - 1; i++) { + VectorSet(oldpt, (stripDef[i] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i] * e->radius * e->backlerp); + VectorSet(oldpt2, (stripDef[i + 1] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i + 1] * e->radius * e->backlerp); // lathe section around in a complete circle - for ( t = latheStep; t <= 360; t += latheStep ) - { + for (t = latheStep; t <= 360; t += latheStep) { // rotate every time except last seg - if ( t < 360.0f ) - { - VectorCopy( oldpt, pt ); - VectorCopy( oldpt2, pt2 ); + if (t < 360.0f) { + VectorCopy(oldpt, pt); + VectorCopy(oldpt2, pt2); - s = sin( DEG2RAD( latheStep )); - c = cos( DEG2RAD( latheStep )); + s = sin(DEG2RAD(latheStep)); + c = cos(DEG2RAD(latheStep)); // rotate lathe points - temp = c * pt[0] - s * pt[1]; // c -s 0 - pt[1] = s * pt[0] + c * pt[1]; // s c 0 - pt[0] = temp; // 0 0 1 + temp = c * pt[0] - s * pt[1]; // c -s 0 + pt[1] = s * pt[0] + c * pt[1]; // s c 0 + pt[0] = temp; // 0 0 1 - temp = c * pt2[0] - s * pt2[1]; // c -s 0 - pt2[1] = s * pt2[0] + c * pt2[1];// s c 0 - pt2[0] = temp; // 0 0 1 - } - else - { + temp = c * pt2[0] - s * pt2[1]; // c -s 0 + pt2[1] = s * pt2[0] + c * pt2[1]; // s c 0 + pt2[0] = temp; // 0 0 1 + } else { // just glue directly to the def points. - VectorSet( pt, (stripDef[i] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i] * e->radius * e->backlerp ); - VectorSet( pt2, (stripDef[i+1] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i+1] * e->radius * e->backlerp ); + VectorSet(pt, (stripDef[i] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i] * e->radius * e->backlerp); + VectorSet(pt2, (stripDef[i + 1] * (e->radius - e->rotation)) + e->rotation, 0, curveDef[i + 1] * e->radius * e->backlerp); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; // Actually generate the necessary verts - VectorAdd( e->origin, oldpt, tess.xyz[tess.numVertexes] ); + VectorAdd(e->origin, oldpt, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = tess.xyz[tess.numVertexes][0] * 0.1f; tess.texCoords[tess.numVertexes][0][1] = tess.xyz[tess.numVertexes][1] * 0.1f; - tess.vertexColors[tess.numVertexes][0] = - tess.vertexColors[tess.numVertexes][1] = - tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[0] * alphaDef[i]; + tess.vertexColors[tess.numVertexes][0] = tess.vertexColors[tess.numVertexes][1] = tess.vertexColors[tess.numVertexes][2] = + e->shaderRGBA[0] * alphaDef[i]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorAdd( e->origin, oldpt2, tess.xyz[tess.numVertexes] ); + VectorAdd(e->origin, oldpt2, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = tess.xyz[tess.numVertexes][0] * 0.1f; tess.texCoords[tess.numVertexes][0][1] = tess.xyz[tess.numVertexes][1] * 0.1f; - tess.vertexColors[tess.numVertexes][0] = - tess.vertexColors[tess.numVertexes][1] = - tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[0] * alphaDef[i+1]; + tess.vertexColors[tess.numVertexes][0] = tess.vertexColors[tess.numVertexes][1] = tess.vertexColors[tess.numVertexes][2] = + e->shaderRGBA[0] * alphaDef[i + 1]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorAdd( e->origin, pt, tess.xyz[tess.numVertexes] ); + VectorAdd(e->origin, pt, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = tess.xyz[tess.numVertexes][0] * 0.1f; tess.texCoords[tess.numVertexes][0][1] = tess.xyz[tess.numVertexes][1] * 0.1f; - tess.vertexColors[tess.numVertexes][0] = - tess.vertexColors[tess.numVertexes][1] = - tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[0] * alphaDef[i]; + tess.vertexColors[tess.numVertexes][0] = tess.vertexColors[tess.numVertexes][1] = tess.vertexColors[tess.numVertexes][2] = + e->shaderRGBA[0] * alphaDef[i]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; - VectorAdd( e->origin, pt2, tess.xyz[tess.numVertexes] ); + VectorAdd(e->origin, pt2, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = tess.xyz[tess.numVertexes][0] * 0.1f; tess.texCoords[tess.numVertexes][0][1] = tess.xyz[tess.numVertexes][1] * 0.1f; - tess.vertexColors[tess.numVertexes][0] = - tess.vertexColors[tess.numVertexes][1] = - tess.vertexColors[tess.numVertexes][2] = e->shaderRGBA[0] * alphaDef[i+1]; + tess.vertexColors[tess.numVertexes][0] = tess.vertexColors[tess.numVertexes][1] = tess.vertexColors[tess.numVertexes][2] = + e->shaderRGBA[0] * alphaDef[i + 1]; tess.vertexColors[tess.numVertexes][3] = e->shaderRGBA[3]; tess.numVertexes++; @@ -1894,13 +1765,12 @@ static void RB_SurfaceClouds() tess.indexes[tess.numIndexes++] = vbase; // Shuffle new points to old - VectorCopy2( pt, oldpt ); - VectorCopy2( pt2, oldpt2 ); + VectorCopy2(pt, oldpt); + VectorCopy2(pt2, oldpt2); } } } - /* =========================================================================== @@ -1916,22 +1786,22 @@ RB_SurfaceAxis Draws x/y/z lines from the origin for orientation debugging =================== */ -static void RB_SurfaceAxis( void ) { - GL_Bind( tr.whiteImage ); - GL_State( GLS_DEFAULT ); - qglLineWidth( 3 ); - qglBegin( GL_LINES ); - qglColor3f( 1,0,0 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 16,0,0 ); - qglColor3f( 0,1,0 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 0,16,0 ); - qglColor3f( 0,0,1 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 0,0,16 ); +static void RB_SurfaceAxis(void) { + GL_Bind(tr.whiteImage); + GL_State(GLS_DEFAULT); + qglLineWidth(3); + qglBegin(GL_LINES); + qglColor3f(1, 0, 0); + qglVertex3f(0, 0, 0); + qglVertex3f(16, 0, 0); + qglColor3f(0, 1, 0); + qglVertex3f(0, 0, 0); + qglVertex3f(0, 16, 0); + qglColor3f(0, 0, 1); + qglVertex3f(0, 0, 0); + qglVertex3f(0, 0, 16); qglEnd(); - qglLineWidth( 1 ); + qglLineWidth(1); } //=========================================================================== @@ -1943,8 +1813,8 @@ RB_SurfaceEntity Entities that have a single procedurally generated surface ==================== */ -void RB_SurfaceEntity( surfaceType_t *surfType ) { - switch( backEnd.currentEntity->e.reType ) { +void RB_SurfaceEntity(surfaceType_t *surfType) { + switch (backEnd.currentEntity->e.reType) { case RT_SPRITE: RB_SurfaceSprite(); break; @@ -1979,10 +1849,7 @@ void RB_SurfaceEntity( surfaceType_t *surfType ) { return; } -void RB_SurfaceBad( surfaceType_t *surfType ) { - ri.Printf( PRINT_ALL, "Bad surface tesselated.\n" ); -} - +void RB_SurfaceBad(surfaceType_t *surfType) { ri.Printf(PRINT_ALL, "Bad surface tesselated.\n"); } /* ================== @@ -1991,75 +1858,72 @@ RB_TestZFlare This is called at surface tesselation time ================== */ -static bool RB_TestZFlare( vec3_t point) { - int i; - vec4_t eye, clip, normalized, window; +static bool RB_TestZFlare(vec3_t point) { + int i; + vec4_t eye, clip, normalized, window; // if the point is off the screen, don't bother adding it // calculate screen coordinates and depth - R_TransformModelToClip( point, backEnd.ori.modelMatrix, - backEnd.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(point, backEnd.ori.modelMatrix, backEnd.viewParms.projectionMatrix, eye, clip); // check to see if the point is completely off screen - for ( i = 0 ; i < 3 ; i++ ) { - if ( clip[i] >= clip[3] || clip[i] <= -clip[3] ) { + for (i = 0; i < 3; i++) { + if (clip[i] >= clip[3] || clip[i] <= -clip[3]) { return qfalse; } } - R_TransformClipToWindow( clip, &backEnd.viewParms, normalized, window ); + R_TransformClipToWindow(clip, &backEnd.viewParms, normalized, window); - if ( window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth - || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight ) { - return qfalse; // shouldn't happen, since we check the clip[] above, except for FP rounding + if (window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight) { + return qfalse; // shouldn't happen, since we check the clip[] above, except for FP rounding } -//do test - float depth = 0.0f; - bool visible; - float screenZ; + // do test + float depth = 0.0f; + bool visible; + float screenZ; // read back the z buffer contents - if ( r_flares->integer !=1 ) { //skipping the the z-test + if (r_flares->integer != 1) { // skipping the the z-test return true; } // doing a readpixels is as good as doing a glFinish(), so // don't bother with another sync glState.finishCalled = qfalse; - qglReadPixels( backEnd.viewParms.viewportX + window[0],backEnd.viewParms.viewportY + window[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth ); + qglReadPixels(backEnd.viewParms.viewportX + window[0], backEnd.viewParms.viewportY + window[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); - screenZ = backEnd.viewParms.projectionMatrix[14] / - ( ( 2*depth - 1 ) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10] ); + screenZ = backEnd.viewParms.projectionMatrix[14] / ((2 * depth - 1) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10]); - visible = ( -eye[2] - -screenZ ) < 24; + visible = (-eye[2] - -screenZ) < 24; return visible; } -void RB_SurfaceFlare( srfFlare_t *surf ) { - vec3_t left, up; - float radius; - byte color[4]; - vec3_t dir; - vec3_t origin; - float d, dist; +void RB_SurfaceFlare(srfFlare_t *surf) { + vec3_t left, up; + float radius; + byte color[4]; + vec3_t dir; + vec3_t origin; + float d, dist; - if ( !r_flares->integer ) { + if (!r_flares->integer) { return; } - if (!RB_TestZFlare( surf->origin ) ) { + if (!RB_TestZFlare(surf->origin)) { return; } // calculate the xyz locations for the four corners - VectorMA( surf->origin, 3, surf->normal, origin ); - float* snormal = surf->normal; + VectorMA(surf->origin, 3, surf->normal, origin); + float *snormal = surf->normal; - VectorSubtract( origin, backEnd.viewParms.ori.origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(origin, backEnd.viewParms.ori.origin, dir); + dist = VectorNormalize(dir); - d = -DotProduct( dir, snormal ); - if ( d < 0 ) { + d = -DotProduct(dir, snormal); + if (d < 0) { d = -d; } @@ -2068,54 +1932,50 @@ void RB_SurfaceFlare( srfFlare_t *surf ) { color[0] = d * 255; color[1] = d * 255; color[2] = d * 255; - color[3] = 255; //only gets used if the shader has cgen exact_vertex! + color[3] = 255; // only gets used if the shader has cgen exact_vertex! - radius = tess.shader->portalRange ? tess.shader->portalRange: 30; - if (dist < 512.0f) - { + radius = tess.shader->portalRange ? tess.shader->portalRange : 30; + if (dist < 512.0f) { radius = radius * dist / 512.0f; } - if (radius<5.0f) - { + if (radius < 5.0f) { radius = 5.0f; } - VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); - VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( origin, left, up, color ); + RB_AddQuadStamp(origin, left, up, color); } - -void RB_SurfaceDisplayList( srfDisplayList_t *surf ) { +void RB_SurfaceDisplayList(srfDisplayList_t *surf) { // all appropriate state must be set in RB_BeginSurface // this isn't implemented yet... - qglCallList( surf->listNum ); -} - -void RB_SurfaceSkip( void *surf ) { + qglCallList(surf->listNum); } -void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])( void *) = { - (void(*)(void*))RB_SurfaceBad, // SF_BAD, - (void(*)(void*))RB_SurfaceSkip, // SF_SKIP, - (void(*)(void*))RB_SurfaceFace, // SF_FACE, - (void(*)(void*))RB_SurfaceGrid, // SF_GRID, - (void(*)(void*))RB_SurfaceTriangles, // SF_TRIANGLES, - (void(*)(void*))RB_SurfacePolychain, // SF_POLY, - (void(*)(void*))RB_SurfaceMesh, // SF_MD3, -/* -Ghoul2 Insert Start -*/ - - (void(*)(void*))RB_SurfaceGhoul, // SF_MDX, -/* -Ghoul2 Insert End -*/ - - (void(*)(void*))RB_SurfaceFlare, // SF_FLARE, - (void(*)(void*))RB_SurfaceEntity, // SF_ENTITY - (void(*)(void*))RB_SurfaceDisplayList // SF_DISPLAY_LIST +void RB_SurfaceSkip(void *surf) {} + +void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *) = { + (void (*)(void *))RB_SurfaceBad, // SF_BAD, + (void (*)(void *))RB_SurfaceSkip, // SF_SKIP, + (void (*)(void *))RB_SurfaceFace, // SF_FACE, + (void (*)(void *))RB_SurfaceGrid, // SF_GRID, + (void (*)(void *))RB_SurfaceTriangles, // SF_TRIANGLES, + (void (*)(void *))RB_SurfacePolychain, // SF_POLY, + (void (*)(void *))RB_SurfaceMesh, // SF_MD3, + /* + Ghoul2 Insert Start + */ + + (void (*)(void *))RB_SurfaceGhoul, // SF_MDX, + /* + Ghoul2 Insert End + */ + + (void (*)(void *))RB_SurfaceFlare, // SF_FLARE, + (void (*)(void *))RB_SurfaceEntity, // SF_ENTITY + (void (*)(void *))RB_SurfaceDisplayList // SF_DISPLAY_LIST }; diff --git a/code/rd-vanilla/tr_surfacesprites.cpp b/code/rd-vanilla/tr_surfacesprites.cpp index f0c210a3b8..4a072e4db0 100644 --- a/code/rd-vanilla/tr_surfacesprites.cpp +++ b/code/rd-vanilla/tr_surfacesprites.cpp @@ -36,91 +36,70 @@ along with this program; if not, see . // The vertigons are applied as part of the renderer backend. That is, they access OpenGL calls directly. - unsigned char randomindex, randominterval; const float randomchart[256] = { - 0.6554f, 0.6909f, 0.4806f, 0.6218f, 0.5717f, 0.3896f, 0.0677f, 0.7356f, - 0.8333f, 0.1105f, 0.4445f, 0.8161f, 0.4689f, 0.0433f, 0.7152f, 0.0336f, - 0.0186f, 0.9140f, 0.1626f, 0.6553f, 0.8340f, 0.7094f, 0.2020f, 0.8087f, - 0.9119f, 0.8009f, 0.1339f, 0.8492f, 0.9173f, 0.5003f, 0.6012f, 0.6117f, - 0.5525f, 0.5787f, 0.1586f, 0.3293f, 0.9273f, 0.7791f, 0.8589f, 0.4985f, - 0.0883f, 0.8545f, 0.2634f, 0.4727f, 0.3624f, 0.1631f, 0.7825f, 0.0662f, - 0.6704f, 0.3510f, 0.7525f, 0.9486f, 0.4685f, 0.1535f, 0.1545f, 0.1121f, - 0.4724f, 0.8483f, 0.3833f, 0.1917f, 0.8207f, 0.3885f, 0.9702f, 0.9200f, - 0.8348f, 0.7501f, 0.6675f, 0.4994f, 0.0301f, 0.5225f, 0.8011f, 0.1696f, - 0.5351f, 0.2752f, 0.2962f, 0.7550f, 0.5762f, 0.7303f, 0.2835f, 0.4717f, - 0.1818f, 0.2739f, 0.6914f, 0.7748f, 0.7640f, 0.8355f, 0.7314f, 0.5288f, - 0.7340f, 0.6692f, 0.6813f, 0.2810f, 0.8057f, 0.0648f, 0.8749f, 0.9199f, - 0.1462f, 0.5237f, 0.3014f, 0.4994f, 0.0278f, 0.4268f, 0.7238f, 0.5107f, - 0.1378f, 0.7303f, 0.7200f, 0.3819f, 0.2034f, 0.7157f, 0.5552f, 0.4887f, - 0.0871f, 0.3293f, 0.2892f, 0.4545f, 0.0088f, 0.1404f, 0.0275f, 0.0238f, - 0.0515f, 0.4494f, 0.7206f, 0.2893f, 0.6060f, 0.5785f, 0.4182f, 0.5528f, - 0.9118f, 0.8742f, 0.3859f, 0.6030f, 0.3495f, 0.4550f, 0.9875f, 0.6900f, - 0.6416f, 0.2337f, 0.7431f, 0.9788f, 0.6181f, 0.2464f, 0.4661f, 0.7621f, - 0.7020f, 0.8203f, 0.8869f, 0.2145f, 0.7724f, 0.6093f, 0.6692f, 0.9686f, - 0.5609f, 0.0310f, 0.2248f, 0.2950f, 0.2365f, 0.1347f, 0.2342f, 0.1668f, - 0.3378f, 0.4330f, 0.2775f, 0.9901f, 0.7053f, 0.7266f, 0.4840f, 0.2820f, - 0.5733f, 0.4555f, 0.6049f, 0.0770f, 0.4760f, 0.6060f, 0.4159f, 0.3427f, - 0.1234f, 0.7062f, 0.8569f, 0.1878f, 0.9057f, 0.9399f, 0.8139f, 0.1407f, - 0.1794f, 0.9123f, 0.9493f, 0.2827f, 0.9934f, 0.0952f, 0.4879f, 0.5160f, - 0.4118f, 0.4873f, 0.3642f, 0.7470f, 0.0866f, 0.5172f, 0.6365f, 0.2676f, - 0.2407f, 0.7223f, 0.5761f, 0.1143f, 0.7137f, 0.2342f, 0.3353f, 0.6880f, - 0.2296f, 0.6023f, 0.6027f, 0.4138f, 0.5408f, 0.9859f, 0.1503f, 0.7238f, - 0.6054f, 0.2477f, 0.6804f, 0.1432f, 0.4540f, 0.9776f, 0.8762f, 0.7607f, - 0.9025f, 0.9807f, 0.0652f, 0.8661f, 0.7663f, 0.2586f, 0.3994f, 0.0335f, - 0.7328f, 0.0166f, 0.9589f, 0.4348f, 0.5493f, 0.7269f, 0.6867f, 0.6614f, - 0.6800f, 0.7804f, 0.5591f, 0.8381f, 0.0910f, 0.7573f, 0.8985f, 0.3083f, - 0.3188f, 0.8481f, 0.2356f, 0.6736f, 0.4770f, 0.4560f, 0.6266f, 0.4677f -}; + 0.6554f, 0.6909f, 0.4806f, 0.6218f, 0.5717f, 0.3896f, 0.0677f, 0.7356f, 0.8333f, 0.1105f, 0.4445f, 0.8161f, 0.4689f, 0.0433f, 0.7152f, 0.0336f, + 0.0186f, 0.9140f, 0.1626f, 0.6553f, 0.8340f, 0.7094f, 0.2020f, 0.8087f, 0.9119f, 0.8009f, 0.1339f, 0.8492f, 0.9173f, 0.5003f, 0.6012f, 0.6117f, + 0.5525f, 0.5787f, 0.1586f, 0.3293f, 0.9273f, 0.7791f, 0.8589f, 0.4985f, 0.0883f, 0.8545f, 0.2634f, 0.4727f, 0.3624f, 0.1631f, 0.7825f, 0.0662f, + 0.6704f, 0.3510f, 0.7525f, 0.9486f, 0.4685f, 0.1535f, 0.1545f, 0.1121f, 0.4724f, 0.8483f, 0.3833f, 0.1917f, 0.8207f, 0.3885f, 0.9702f, 0.9200f, + 0.8348f, 0.7501f, 0.6675f, 0.4994f, 0.0301f, 0.5225f, 0.8011f, 0.1696f, 0.5351f, 0.2752f, 0.2962f, 0.7550f, 0.5762f, 0.7303f, 0.2835f, 0.4717f, + 0.1818f, 0.2739f, 0.6914f, 0.7748f, 0.7640f, 0.8355f, 0.7314f, 0.5288f, 0.7340f, 0.6692f, 0.6813f, 0.2810f, 0.8057f, 0.0648f, 0.8749f, 0.9199f, + 0.1462f, 0.5237f, 0.3014f, 0.4994f, 0.0278f, 0.4268f, 0.7238f, 0.5107f, 0.1378f, 0.7303f, 0.7200f, 0.3819f, 0.2034f, 0.7157f, 0.5552f, 0.4887f, + 0.0871f, 0.3293f, 0.2892f, 0.4545f, 0.0088f, 0.1404f, 0.0275f, 0.0238f, 0.0515f, 0.4494f, 0.7206f, 0.2893f, 0.6060f, 0.5785f, 0.4182f, 0.5528f, + 0.9118f, 0.8742f, 0.3859f, 0.6030f, 0.3495f, 0.4550f, 0.9875f, 0.6900f, 0.6416f, 0.2337f, 0.7431f, 0.9788f, 0.6181f, 0.2464f, 0.4661f, 0.7621f, + 0.7020f, 0.8203f, 0.8869f, 0.2145f, 0.7724f, 0.6093f, 0.6692f, 0.9686f, 0.5609f, 0.0310f, 0.2248f, 0.2950f, 0.2365f, 0.1347f, 0.2342f, 0.1668f, + 0.3378f, 0.4330f, 0.2775f, 0.9901f, 0.7053f, 0.7266f, 0.4840f, 0.2820f, 0.5733f, 0.4555f, 0.6049f, 0.0770f, 0.4760f, 0.6060f, 0.4159f, 0.3427f, + 0.1234f, 0.7062f, 0.8569f, 0.1878f, 0.9057f, 0.9399f, 0.8139f, 0.1407f, 0.1794f, 0.9123f, 0.9493f, 0.2827f, 0.9934f, 0.0952f, 0.4879f, 0.5160f, + 0.4118f, 0.4873f, 0.3642f, 0.7470f, 0.0866f, 0.5172f, 0.6365f, 0.2676f, 0.2407f, 0.7223f, 0.5761f, 0.1143f, 0.7137f, 0.2342f, 0.3353f, 0.6880f, + 0.2296f, 0.6023f, 0.6027f, 0.4138f, 0.5408f, 0.9859f, 0.1503f, 0.7238f, 0.6054f, 0.2477f, 0.6804f, 0.1432f, 0.4540f, 0.9776f, 0.8762f, 0.7607f, + 0.9025f, 0.9807f, 0.0652f, 0.8661f, 0.7663f, 0.2586f, 0.3994f, 0.0335f, 0.7328f, 0.0166f, 0.9589f, 0.4348f, 0.5493f, 0.7269f, 0.6867f, 0.6614f, + 0.6800f, 0.7804f, 0.5591f, 0.8381f, 0.0910f, 0.7573f, 0.8985f, 0.3083f, 0.3188f, 0.8481f, 0.2356f, 0.6736f, 0.4770f, 0.4560f, 0.6266f, 0.4677f}; #define WIND_DAMP_INTERVAL 50 #define WIND_GUST_TIME 2500.0 #define WIND_GUST_DECAY (1.0 / WIND_GUST_TIME) -int lastSSUpdateTime = 0; -float curWindSpeed=0; -float curWindGust=5; -float curWeatherAmount=1; -vec3_t curWindBlowVect={0,0,0}, targetWindBlowVect={0,0,0}; -vec3_t curWindGrassDir={0,0,0}, targetWindGrassDir={0,0,0}; -int totalsurfsprites=0, sssurfaces=0; +int lastSSUpdateTime = 0; +float curWindSpeed = 0; +float curWindGust = 5; +float curWeatherAmount = 1; +vec3_t curWindBlowVect = {0, 0, 0}, targetWindBlowVect = {0, 0, 0}; +vec3_t curWindGrassDir = {0, 0, 0}, targetWindGrassDir = {0, 0, 0}; +int totalsurfsprites = 0, sssurfaces = 0; -qboolean curWindPointActive=qfalse; +qboolean curWindPointActive = qfalse; float curWindPointForce = 0; vec3_t curWindPoint; -int nextGustTime=0; -float gustLeft=0; - -qboolean standardfovinitialized=qfalse; -float standardfovx = 90, standardscalex = 1.0; -float rangescalefactor=1.0; +int nextGustTime = 0; +float gustLeft = 0; -vec3_t ssrightvectors[4]; -vec3_t ssfwdvector; -int rightvectorcount; +qboolean standardfovinitialized = qfalse; +float standardfovx = 90, standardscalex = 1.0; +float rangescalefactor = 1.0; -trRefEntity_t *ssLastEntityDrawn=NULL; -vec3_t ssViewOrigin, ssViewRight, ssViewUp; +vec3_t ssrightvectors[4]; +vec3_t ssfwdvector; +int rightvectorcount; +trRefEntity_t *ssLastEntityDrawn = NULL; +vec3_t ssViewOrigin, ssViewRight, ssViewUp; -static void R_SurfaceSpriteFrameUpdate(void) -{ - float dtime, dampfactor; // Time since last update and damping time for wind changes +static void R_SurfaceSpriteFrameUpdate(void) { + float dtime, dampfactor; // Time since last update and damping time for wind changes float ratio; vec3_t ang, diff, retwindvec; float targetspeed; - vec3_t up={0,0,1}; + vec3_t up = {0, 0, 1}; if (backEnd.refdef.time == lastSSUpdateTime) return; - if (backEnd.refdef.time < lastSSUpdateTime) - { // Time is BEFORE the last update time, so reset everything. + if (backEnd.refdef.time < lastSSUpdateTime) { // Time is BEFORE the last update time, so reset everything. curWindGust = 5; curWindSpeed = r_windSpeed->value; nextGustTime = 0; gustLeft = 0; - curWindGrassDir[0]=curWindGrassDir[1]=curWindGrassDir[2]=0.0f; + curWindGrassDir[0] = curWindGrassDir[1] = curWindGrassDir[2] = 0.0f; } // Reset the last entity drawn, since this is a new frame. @@ -129,34 +108,24 @@ static void R_SurfaceSpriteFrameUpdate(void) // Adjust for an FOV. If things look twice as wide on the screen, pretend the shaders have twice the range. // ASSUMPTION HERE IS THAT "standard" fov is the first one rendered. - if (!standardfovinitialized) - { // This isn't initialized yet. - if (backEnd.refdef.fov_x > 50 && backEnd.refdef.fov_x < 135) // I don't consider anything below 50 or above 135 to be "normal". + if (!standardfovinitialized) { // This isn't initialized yet. + if (backEnd.refdef.fov_x > 50 && backEnd.refdef.fov_x < 135) // I don't consider anything below 50 or above 135 to be "normal". { standardfovx = backEnd.refdef.fov_x; - standardscalex = tan(standardfovx * 0.5 * (M_PI/180.0f)); + standardscalex = tan(standardfovx * 0.5 * (M_PI / 180.0f)); standardfovinitialized = qtrue; - } - else - { + } else { standardfovx = 90; - standardscalex = tan(standardfovx * 0.5 * (M_PI/180.0f)); + standardscalex = tan(standardfovx * 0.5 * (M_PI / 180.0f)); } - rangescalefactor = 1.0; // Don't multiply the shader range by anything. - } - else if (standardfovx == backEnd.refdef.fov_x) - { // This is the standard FOV (or higher), don't multiply the shader range. + rangescalefactor = 1.0; // Don't multiply the shader range by anything. + } else if (standardfovx == backEnd.refdef.fov_x) { // This is the standard FOV (or higher), don't multiply the shader range. rangescalefactor = 1.0; - } - else - { // We are using a non-standard FOV. We need to multiply the range of the shader by a scale factor. - if (backEnd.refdef.fov_x > 135) - { - rangescalefactor = standardscalex / tan(135.0f * 0.5f * (M_PI/180.0f)); - } - else - { - rangescalefactor = standardscalex / tan(backEnd.refdef.fov_x * 0.5 * (M_PI/180.0f)); + } else { // We are using a non-standard FOV. We need to multiply the range of the shader by a scale factor. + if (backEnd.refdef.fov_x > 135) { + rangescalefactor = standardscalex / tan(135.0f * 0.5f * (M_PI / 180.0f)); + } else { + rangescalefactor = standardscalex / tan(backEnd.refdef.fov_x * 0.5 * (M_PI / 180.0f)); } } @@ -172,116 +141,93 @@ static void R_SurfaceSpriteFrameUpdate(void) VectorScale(ssViewRight, 0.866f, ssrightvectors[1]); VectorMA(ssrightvectors[1], -0.5f, ssfwdvector, ssrightvectors[1]); - // Right two has a big nudge forward (30 degrees). VectorScale(ssViewRight, 0.866f, ssrightvectors[2]); VectorMA(ssrightvectors[2], 0.5f, ssfwdvector, ssrightvectors[2]); - // Right three has a nudge back (10 degrees). VectorScale(ssViewRight, 0.985f, ssrightvectors[3]); VectorMA(ssrightvectors[3], -0.174f, ssfwdvector, ssrightvectors[3]); - // Update the wind. // If it is raining, get the windspeed from the rain system rather than the cvar - if (R_IsRaining() /*|| R_IsSnowing()*/ || R_IsPuffing() ) - { + if (R_IsRaining() /*|| R_IsSnowing()*/ || R_IsPuffing()) { curWeatherAmount = 1.0; - } - else - { + } else { curWeatherAmount = r_surfaceWeather->value; } - if (R_GetWindSpeed(targetspeed, NULL)) - { // We successfully got a speed from the rain system. + if (R_GetWindSpeed(targetspeed, NULL)) { // We successfully got a speed from the rain system. // Set the windgust to 5, since that looks pretty good. targetspeed *= 0.02f; - if (targetspeed >= 1.0) - { - curWindGust = 300/targetspeed; - } - else - { + if (targetspeed >= 1.0) { + curWindGust = 300 / targetspeed; + } else { curWindGust = 0; } - } - else - { // Use the cvar. - targetspeed = r_windSpeed->value; // Minimum gust delay, in seconds. + } else { // Use the cvar. + targetspeed = r_windSpeed->value; // Minimum gust delay, in seconds. curWindGust = r_windGust->value; } - if (targetspeed > 0 && curWindGust) - { - if (gustLeft > 0) - { // We are gusting + if (targetspeed > 0 && curWindGust) { + if (gustLeft > 0) { // We are gusting // Add an amount to the target wind speed targetspeed *= 1.0 + gustLeft; - gustLeft -= (float)(backEnd.refdef.time - lastSSUpdateTime)*WIND_GUST_DECAY; - if (gustLeft <= 0) - { - nextGustTime = backEnd.refdef.time + (curWindGust*1000)*Q_flrand(1.0f,4.0f); + gustLeft -= (float)(backEnd.refdef.time - lastSSUpdateTime) * WIND_GUST_DECAY; + if (gustLeft <= 0) { + nextGustTime = backEnd.refdef.time + (curWindGust * 1000) * Q_flrand(1.0f, 4.0f); } - } - else if (backEnd.refdef.time >= nextGustTime) - { // See if there is another right now + } else if (backEnd.refdef.time >= nextGustTime) { // See if there is another right now // Gust next time, mano - gustLeft = Q_flrand(0.75f,1.5f); + gustLeft = Q_flrand(0.75f, 1.5f); } } // See if there is a weather system that will tell us a windspeed. - if (R_GetWindVector(retwindvec, NULL)) - { - retwindvec[2]=0; - //VectorScale(retwindvec, -1.0f, retwindvec); + if (R_GetWindVector(retwindvec, NULL)) { + retwindvec[2] = 0; + // VectorScale(retwindvec, -1.0f, retwindvec); vectoangles(retwindvec, ang); - } - else - { // Calculate the target wind vector based off cvars + } else { // Calculate the target wind vector based off cvars ang[YAW] = r_windAngle->value; } ang[PITCH] = -90.0 + targetspeed; - if (ang[PITCH]>-45.0) - { + if (ang[PITCH] > -45.0) { ang[PITCH] = -45.0; } ang[ROLL] = 0; - if (targetspeed>0) - { -// ang[YAW] += cos(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; -// ang[PITCH] += sin(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; + if (targetspeed > 0) { + // ang[YAW] += cos(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; + // ang[PITCH] += sin(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; } // Get the grass wind vector first AngleVectors(ang, targetWindGrassDir, NULL, NULL); - targetWindGrassDir[2]-=1.0; -// VectorScale(targetWindGrassDir, targetspeed, targetWindGrassDir); + targetWindGrassDir[2] -= 1.0; + // VectorScale(targetWindGrassDir, targetspeed, targetWindGrassDir); // Now get the general wind vector (no pitch) - ang[PITCH]=0; + ang[PITCH] = 0; AngleVectors(ang, targetWindBlowVect, NULL, NULL); // Start calculating a smoothing factor so wind doesn't change abruptly between speeds. - dampfactor = 1.0-r_windDampFactor->value; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(backEnd.refdef.time - lastSSUpdateTime) * (1.0/(float)WIND_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - r_windDampFactor->value; // We must exponent the amount LEFT rather than the amount bled off + dtime = + (float)(backEnd.refdef.time - lastSSUpdateTime) * (1.0 / (float)WIND_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. ratio = pow(dampfactor, dtime); // Apply this ratio to the windspeed... - if (fabsf(targetspeed-curWindSpeed) > ratio) - { - curWindSpeed = targetspeed - (ratio * (targetspeed-curWindSpeed)); + if (fabsf(targetspeed - curWindSpeed) > ratio) { + curWindSpeed = targetspeed - (ratio * (targetspeed - curWindSpeed)); } - // Use the curWindSpeed to calculate the final target wind vector (with speed) VectorScale(targetWindBlowVect, curWindSpeed, targetWindBlowVect); VectorSubtract(targetWindBlowVect, curWindBlowVect, diff); @@ -293,149 +239,124 @@ static void R_SurfaceSpriteFrameUpdate(void) lastSSUpdateTime = backEnd.refdef.time; - if (fabsf(r_windPointForce->value - curWindPointForce) > ratio) - {// Make sure not to get infinitly small number here + if (fabsf(r_windPointForce->value - curWindPointForce) > ratio) { // Make sure not to get infinitly small number here curWindPointForce = r_windPointForce->value - (ratio * (r_windPointForce->value - curWindPointForce)); } assert(!Q_isnan(curWindPointForce)); - if (curWindPointForce < 0.01) - { + if (curWindPointForce < 0.01) { curWindPointActive = qfalse; - } - else - { + } else { curWindPointActive = qtrue; curWindPoint[0] = r_windPointX->value; curWindPoint[1] = r_windPointY->value; curWindPoint[2] = 0; } - if (r_surfaceSprites->integer >= 2) - { + if (r_surfaceSprites->integer >= 2) { Com_Printf("Surfacesprites Drawn: %d, on %d surfaces\n", totalsurfsprites, sssurfaces); } - totalsurfsprites=0; - sssurfaces=0; + totalsurfsprites = 0; + sssurfaces = 0; } - - ///////////////////////////////////////////// // Surface sprite calculation and drawing. ///////////////////////////////////////////// -#define FADE_RANGE 250.0 -#define WINDPOINT_RADIUS 750.0 +#define FADE_RANGE 250.0 +#define WINDPOINT_RADIUS 750.0 float SSVertAlpha[SHADER_MAX_VERTEXES]; float SSVertWindForce[SHADER_MAX_VERTEXES]; vec2_t SSVertWindDir[SHADER_MAX_VERTEXES]; -qboolean SSAdditiveTransparency=qfalse; -qboolean SSUsingFog=qfalse; - +qboolean SSAdditiveTransparency = qfalse; +qboolean SSUsingFog = qfalse; ///////////////////////////////////////////// // Vertical surface sprites -static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte light, - byte alpha, float wind, float windidle, vec2_t fog, int hangdown, vec2_t skew, bool flattened) -{ +static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float wind, float windidle, vec2_t fog, int hangdown, + vec2_t skew, bool flattened) { vec3_t loc2, right; float angle; float windsway; float points[16]; color4ub_t color; - angle = ((loc[0]+loc[1])*0.02+(tr.refdef.time*0.0015)); + angle = ((loc[0] + loc[1]) * 0.02 + (tr.refdef.time * 0.0015)); - if (windidle>0.0) - { - windsway = (height*windidle*0.075); - loc2[0] = loc[0]+skew[0]+cos(angle)*windsway; - loc2[1] = loc[1]+skew[1]+sin(angle)*windsway; + if (windidle > 0.0) { + windsway = (height * windidle * 0.075); + loc2[0] = loc[0] + skew[0] + cos(angle) * windsway; + loc2[1] = loc[1] + skew[1] + sin(angle) * windsway; - if (hangdown) - { - loc2[2] = loc[2]-height; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } - else - { - loc2[2] = loc[2]+height; - } - } - else - { - loc2[0] = loc[0]+skew[0]; - loc2[1] = loc[1]+skew[1]; - if (hangdown) - { - loc2[2] = loc[2]-height; - } - else - { - loc2[2] = loc[2]+height; + } else { + loc2[0] = loc[0] + skew[0]; + loc2[1] = loc[1] + skew[1]; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } } - if (wind>0.0 && curWindSpeed > 0.001) - { - windsway = (height*wind*0.075); + if (wind > 0.0 && curWindSpeed > 0.001) { + windsway = (height * wind * 0.075); // Add the angle - VectorMA(loc2, height*wind, curWindGrassDir, loc2); + VectorMA(loc2, height * wind, curWindGrassDir, loc2); // Bob up and down - if (curWindSpeed < 40.0) - { - windsway *= curWindSpeed*(1.0/100.0); - } - else - { + if (curWindSpeed < 40.0) { + windsway *= curWindSpeed * (1.0 / 100.0); + } else { windsway *= 0.4f; } - loc2[2] += sin(angle*2.5)*windsway; + loc2[2] += sin(angle * 2.5) * windsway; } - if ( flattened ) - { - right[0] = sin( DEG2RAD( loc[0] ) ) * width; - right[1] = cos( DEG2RAD( loc[0] ) ) * height; + if (flattened) { + right[0] = sin(DEG2RAD(loc[0])) * width; + right[1] = cos(DEG2RAD(loc[0])) * height; right[2] = 0.0f; - } - else - { - VectorScale(ssrightvectors[rightvectorcount], width*0.5, right); + } else { + VectorScale(ssrightvectors[rightvectorcount], width * 0.5, right); } - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; // Bottom right -// VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right -// VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left -// VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0] + ssfwdvector[0] * width * 0.2; points[9] = loc2[1] - right[1] + ssfwdvector[1] * width * 0.2; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left -// VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -445,10 +366,8 @@ static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte SQuickSprite.Add(points, color, fog); } -static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float height, byte light, - byte alpha, float wind, float windidle, vec2_t fog, - int hangdown, vec2_t skew, vec2_t winddiff, float windforce, bool flattened) -{ +static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float height, byte light, byte alpha, float wind, float windidle, vec2_t fog, + int hangdown, vec2_t skew, vec2_t winddiff, float windforce, bool flattened) { vec3_t loc2, right; float angle; float windsway; @@ -458,80 +377,69 @@ static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float hei if (windforce > 1) windforce = 1; -// wind += 1.0-windforce; + // wind += 1.0-windforce; - angle = (loc[0]+loc[1])*0.02+(tr.refdef.time*0.0015); + angle = (loc[0] + loc[1]) * 0.02 + (tr.refdef.time * 0.0015); - if (curWindSpeed <80.0) - { - windsway = (height*windidle*0.1)*(1.0+windforce); - loc2[0] = loc[0]+skew[0]+cos(angle)*windsway; - loc2[1] = loc[1]+skew[1]+sin(angle)*windsway; - } - else - { - loc2[0] = loc[0]+skew[0]; - loc2[1] = loc[1]+skew[1]; + if (curWindSpeed < 80.0) { + windsway = (height * windidle * 0.1) * (1.0 + windforce); + loc2[0] = loc[0] + skew[0] + cos(angle) * windsway; + loc2[1] = loc[1] + skew[1] + sin(angle) * windsway; + } else { + loc2[0] = loc[0] + skew[0]; + loc2[1] = loc[1] + skew[1]; } - if (hangdown) - { - loc2[2] = loc[2]-height; - } - else - { - loc2[2] = loc[2]+height; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } - if (curWindSpeed > 0.001) - { + if (curWindSpeed > 0.001) { // Add the angle - VectorMA(loc2, height*wind, curWindGrassDir, loc2); + VectorMA(loc2, height * wind, curWindGrassDir, loc2); } - loc2[0] += height*winddiff[0]*windforce; - loc2[1] += height*winddiff[1]*windforce; - loc2[2] -= height*windforce*(0.75 + 0.15*sin((tr.refdef.time + 500*windforce)*0.01)); + loc2[0] += height * winddiff[0] * windforce; + loc2[1] += height * winddiff[1] * windforce; + loc2[2] -= height * windforce * (0.75 + 0.15 * sin((tr.refdef.time + 500 * windforce) * 0.01)); - if ( flattened ) - { - right[0] = sin( DEG2RAD( loc[0] ) ) * width; - right[1] = cos( DEG2RAD( loc[0] ) ) * height; + if (flattened) { + right[0] = sin(DEG2RAD(loc[0])) * width; + right[1] = cos(DEG2RAD(loc[0])) * height; right[2] = 0.0f; - } - else - { - VectorScale(ssrightvectors[rightvectorcount], width*0.5, right); + } else { + VectorScale(ssrightvectors[rightvectorcount], width * 0.5, right); } - - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; // Bottom right -// VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right -// VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left -// VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0] + ssfwdvector[0] * width * 0.15; points[9] = loc2[1] - right[1] + ssfwdvector[1] * width * 0.15; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left -// VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -541,23 +449,22 @@ static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float hei SQuickSprite.Add(points, color, fog); } -static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawVerticalSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; vec2_t fog1, fog2, fog3; vec2_t winddiff1, winddiff2, winddiff3; - float windforce1, windforce2, windforce3; + float windforce1, windforce2, windforce3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; vec3_t curpoint; float width, height; @@ -565,145 +472,118 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ byte randomindex2; - vec2_t skew={0,0}; + vec2_t skew = {0, 0}; vec2_t fogv; vec2_t winddiffv; - float windforce=0; - qboolean usewindpoint = (qboolean) !! (curWindPointActive && stage->ss->wind > 0); + float windforce = 0; + qboolean usewindpoint = (qboolean) !!(curWindPointActive && stage->ss->wind > 0); - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); + float faderange = FADE_RANGE / (cutdist - fadedist); - if (faderange > 1.0) - { // Don't want to force a new fade_rand + if (faderange > 1.0) { // Don't want to force a new fade_rand faderange = 1.0; } // Quickly calc all the alphas and windstuff for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0 - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; } // Wind only needs initialization once per tess. - if (usewindpoint && !tess.SSInitializedWind) - { - for (curvert=0; curvertnumVertexes;curvert++) - { // Calc wind at each point - dist[0]=input->xyz[curvert][0] - curWindPoint[0]; - dist[1]=input->xyz[curvert][1] - curWindPoint[1]; - step = (dist[0]*dist[0] + dist[1]*dist[1]); // dist squared - - if (step >= (float)(WINDPOINT_RADIUS*WINDPOINT_RADIUS)) - { // No wind + if (usewindpoint && !tess.SSInitializedWind) { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc wind at each point + dist[0] = input->xyz[curvert][0] - curWindPoint[0]; + dist[1] = input->xyz[curvert][1] - curWindPoint[1]; + step = (dist[0] * dist[0] + dist[1] * dist[1]); // dist squared + + if (step >= (float)(WINDPOINT_RADIUS * WINDPOINT_RADIUS)) { // No wind SSVertWindDir[curvert][0] = 0; SSVertWindDir[curvert][1] = 0; - SSVertWindForce[curvert]=0; // Should be < 1 - } - else - { - if (step<1) - { // Don't want to divide by zero + SSVertWindForce[curvert] = 0; // Should be < 1 + } else { + if (step < 1) { // Don't want to divide by zero SSVertWindDir[curvert][0] = 0; SSVertWindDir[curvert][1] = 0; SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind; - } - else - { - step = Q_rsqrt(step); // Equals 1 over the distance. + } else { + step = Q_rsqrt(step); // Equals 1 over the distance. SSVertWindDir[curvert][0] = dist[0] * step; SSVertWindDir[curvert][1] = dist[1] * step; - step = 1.0 - (1.0 / (step * WINDPOINT_RADIUS)); // 1- (dist/maxradius) = a scale from 0 to 1 linearly dropping off - SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind * step; // *step means divide by the distance. + step = 1.0 - (1.0 / (step * WINDPOINT_RADIUS)); // 1- (dist/maxradius) = a scale from 0 to 1 linearly dropping off + SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind * step; // *step means divide by the distance. } } } tess.SSInitializedWind = qtrue; } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - fog1[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog1[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog1[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog1[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff1[0] = SSVertWindDir[curvert][0]; winddiff1[1] = SSVertWindDir[curvert][1]; windforce1 = SSVertWindForce[curvert]; - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - fog2[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog2[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog2[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog2[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff2[0] = SSVertWindDir[curvert][0]; winddiff2[1] = SSVertWindDir[curvert][1]; windforce2 = SSVertWindForce[curvert]; - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - fog3[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog3[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog3[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog3[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff3[0] = SSVertWindDir[curvert][0]; winddiff3[1] = SSVertWindDir[curvert][1]; windforce3 = SSVertWindForce[curvert]; - if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) - { + if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) { continue; } @@ -714,121 +594,102 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0) { // Insanely small abhorrent triangle. continue; } step = stage->ss->density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd rightvectorcount = 0; - for (posi=0; posi<1.0; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - fa=posi+randomchart[randomindex]*step; + for (posi = 0; posi < 1.0; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + fa = posi + randomchart[randomindex] * step; randomindex += randominterval; - fb=posj+randomchart[randomindex]*step; + fb = posj + randomchart[randomindex] * step; randomindex += randominterval; - rightvectorcount=(rightvectorcount+1)&3; + rightvectorcount = (rightvectorcount + 1) & 3; - if (fa>1.0) + if (fa > 1.0) continue; - if (fb>(1.0-fa)) + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0 to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex]; randomindex += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0 - ((thisspritesfadestart-alphapos)/faderange); - if (alpha > 0.0) - { + alpha = 1.0 - ((thisspritesfadestart - alphapos) / faderange); + if (alpha > 0.0) { if (alpha > 1.0) - alpha=1.0; + alpha = 1.0; - if (SSUsingFog) - { - fogv[0] = fog1[0]*fa + fog2[0]*fb + fog3[0]*fc; - fogv[1] = fog1[1]*fa + fog2[1]*fb + fog3[1]*fc; + if (SSUsingFog) { + fogv[0] = fog1[0] * fa + fog2[0] * fb + fog3[0] * fc; + fogv[1] = fog1[1] * fa + fog2[1] * fb + fog3[1] * fc; } - if (usewindpoint) - { - winddiffv[0] = winddiff1[0]*fa + winddiff2[0]*fb + winddiff3[0]*fc; - winddiffv[1] = winddiff1[1]*fa + winddiff2[1]*fb + winddiff3[1]*fc; - windforce = windforce1*fa + windforce2*fb + windforce3*fc; + if (usewindpoint) { + winddiffv[0] = winddiff1[0] * fa + winddiff2[0] * fb + winddiff3[0] * fc; + winddiffv[1] = winddiff1[1] * fa + winddiff2[1] * fb + winddiff3[1] * fc; + windforce = windforce1 * fa + windforce2 * fb + windforce3 * fc; } VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + light = l1 * fa + l2 * fb + l3 * fc; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } randomindex2 = randomindex; - width = stage->ss->width*(1.0 + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0 + (stage->ss->variance[1]*randomchart[randomindex2++])); - if (randomchart[randomindex2++]>0.5) - { + width = stage->ss->width * (1.0 + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0 + (stage->ss->variance[1] * randomchart[randomindex2++])); + if (randomchart[randomindex2++] > 0.5) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0) - { - width *= 1.0 + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0) { + width *= 1.0 + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (stage->ss->vertSkew != 0) - { // flrand(-vertskew, vertskew) - skew[0] = height * ((stage->ss->vertSkew*2.0f*randomchart[randomindex2++])-stage->ss->vertSkew); - skew[1] = height * ((stage->ss->vertSkew*2.0f*randomchart[randomindex2++])-stage->ss->vertSkew); + if (stage->ss->vertSkew != 0) { // flrand(-vertskew, vertskew) + skew[0] = height * ((stage->ss->vertSkew * 2.0f * randomchart[randomindex2++]) - stage->ss->vertSkew); + skew[1] = height * ((stage->ss->vertSkew * 2.0f * randomchart[randomindex2++]) - stage->ss->vertSkew); } - if (usewindpoint && windforce > 0 && stage->ss->wind > 0.0) - { - if (SSUsingFog) - { - RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, fogv, stage->ss->facing, skew, - winddiffv, windforce, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + if (usewindpoint && windforce > 0 && stage->ss->wind > 0.0) { + if (SSUsingFog) { + RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, + fogv, stage->ss->facing, skew, winddiffv, windforce, + SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, + NULL, stage->ss->facing, skew, winddiffv, windforce, + SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); } - else - { - RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, NULL, stage->ss->facing, skew, - winddiffv, windforce, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); - } - } - else - { - if (SSUsingFog) - { - RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, fogv, stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); - } - else - { - RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, NULL, stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + if (SSUsingFog) { + RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, fogv, + stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, NULL, + stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); } } @@ -839,82 +700,77 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ } } - ///////////////////////////////////////////// // Oriented surface sprites -static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, vec2_t fog, int faceup) -{ +static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, vec2_t fog, int faceup) { vec3_t loc2, right; float points[16]; color4ub_t color; - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; - if (faceup) - { + if (faceup) { width *= 0.5; height *= 0.5; // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + width; points[1] = loc[1] - width; points[2] = loc[2] + 1.0; points[3] = 0; // Top right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[4] = loc[0] + width; points[5] = loc[1] + width; points[6] = loc[2] + 1.0; points[7] = 0; // Top left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[8] = loc[0] - width; points[9] = loc[1] + width; points[10] = loc[2] + 1.0; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - width; points[13] = loc[1] - width; points[14] = loc[2] + 1.0; points[15] = 0; - } - else - { + } else { VectorMA(loc, height, ssViewUp, loc2); - VectorScale(ssViewRight, width*0.5, right); + VectorScale(ssViewRight, width * 0.5, right); // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right - // VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left - // VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0]; points[9] = loc2[1] - right[1]; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -925,21 +781,20 @@ static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte SQuickSprite.Add(points, color, fog); } -static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawOrientedSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea, minnormal; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; vec2_t fog1, fog2, fog3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; vec3_t curpoint; float width, height; @@ -947,74 +802,64 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ byte randomindex2; vec2_t fogv; - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); + float faderange = FADE_RANGE / (cutdist - fadedist); - if (faderange > 1.0) - { // Don't want to force a new fade_rand + if (faderange > 1.0) { // Don't want to force a new fade_rand faderange = 1.0; } - if (stage->ss->facing) - { // Faceup sprite. + if (stage->ss->facing) { // Faceup sprite. minnormal = 0.99f; - } - else - { // Normal oriented sprite + } else { // Normal oriented sprite minnormal = 0.5f; } // Quickly calc all the alphas for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc alpha at each point VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0 - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - fog1[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog1[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog1[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog1[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - fog2[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog2[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog2[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog2[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - fog3[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog3[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog3[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog3[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) - { + if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) { continue; } @@ -1025,86 +870,75 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0) { // Insanely small abhorrent triangle. continue; } step = stage->ss->density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd - for (posi=0; posi<1.0; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - fa=posi+randomchart[randomindex]*step; + for (posi = 0; posi < 1.0; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + fa = posi + randomchart[randomindex] * step; randomindex += randominterval; - if (fa>1.0) + if (fa > 1.0) continue; - fb=posj+randomchart[randomindex]*step; + fb = posj + randomchart[randomindex] * step; randomindex += randominterval; - if (fb>(1.0-fa)) + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0 to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex]; randomindex += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0 - ((thisspritesfadestart-alphapos)/faderange); + alpha = 1.0 - ((thisspritesfadestart - alphapos) / faderange); randomindex += randominterval; - if (alpha > 0.0) - { + if (alpha > 0.0) { if (alpha > 1.0) - alpha=1.0; + alpha = 1.0; - if (SSUsingFog) - { - fogv[0] = fog1[0]*fa + fog2[0]*fb + fog3[0]*fc; - fogv[1] = fog1[1]*fa + fog2[1]*fb + fog3[1]*fc; + if (SSUsingFog) { + fogv[0] = fog1[0] * fa + fog2[0] * fb + fog3[0] * fc; + fogv[1] = fog1[1] * fa + fog2[1] * fb + fog3[1] * fc; } VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + light = l1 * fa + l2 * fb + l3 * fc; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } randomindex2 = randomindex; - width = stage->ss->width*(1.0 + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0 + (stage->ss->variance[1]*randomchart[randomindex2++])); - if (randomchart[randomindex2++]>0.5) - { + width = stage->ss->width * (1.0 + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0 + (stage->ss->variance[1] * randomchart[randomindex2++])); + if (randomchart[randomindex2++] > 0.5) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0) - { - width *= 1.0 + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0) { + width *= 1.0 + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (SSUsingFog) - { - RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), fogv, stage->ss->facing); - } - else - { - RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), NULL, stage->ss->facing); + if (SSUsingFog) { + RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), fogv, stage->ss->facing); + } else { + RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), NULL, stage->ss->facing); } totalsurfsprites++; @@ -1114,82 +948,77 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ } } - ///////////////////////////////////////////// // Effect surface sprites -static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float life, int faceup) -{ +static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float life, int faceup) { vec3_t loc2, right; float points[16]; color4ub_t color; - color[0]=light; //light; - color[1]=light; //light; - color[2]=light; //light; - color[3]=alpha; //alpha; + color[0] = light; // light; + color[1] = light; // light; + color[2] = light; // light; + color[3] = alpha; // alpha; - if (faceup) - { + if (faceup) { width *= 0.5; height *= 0.5; // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + width; points[1] = loc[1] - width; points[2] = loc[2] + 1.0; points[3] = 0; // Top right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[4] = loc[0] + width; points[5] = loc[1] + width; points[6] = loc[2] + 1.0; points[7] = 0; // Top left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[8] = loc[0] - width; points[9] = loc[1] + width; points[10] = loc[2] + 1.0; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - width; points[13] = loc[1] - width; points[14] = loc[2] + 1.0; points[15] = 0; - } - else - { + } else { VectorMA(loc, height, ssViewUp, loc2); - VectorScale(ssViewRight, width*0.5, right); + VectorScale(ssViewRight, width * 0.5, right); // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right - // VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left - // VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0]; points[9] = loc2[1] - right[1]; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -1200,20 +1029,19 @@ static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte l SQuickSprite.Add(points, color, NULL); } -static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawEffectSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea, minnormal; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; float effecttime, effectpos; float density; @@ -1222,99 +1050,82 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t float alpha, alphapos, thisspritesfadestart, light; byte randomindex2; - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; float fxalpha = stage->ss->fxAlphaEnd - stage->ss->fxAlphaStart; - qboolean fadeinout=qfalse; + qboolean fadeinout = qfalse; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); - if (faderange > 1.0f) - { // Don't want to force a new fade_rand + float faderange = FADE_RANGE / (cutdist - fadedist); + if (faderange > 1.0f) { // Don't want to force a new fade_rand faderange = 1.0f; } - if (stage->ss->facing) - { // Faceup sprite. + if (stage->ss->facing) { // Faceup sprite. minnormal = 0.99f; - } - else - { // Normal oriented sprite + } else { // Normal oriented sprite minnormal = 0.5f; } // Make the object fade in. - if (stage->ss->fxAlphaEnd < 0.05 && stage->ss->height >= 0.1 && stage->ss->width >= 0.1) - { // The sprite fades out, and it doesn't start at a pinpoint. Let's fade it in. - fadeinout=qtrue; + if (stage->ss->fxAlphaEnd < 0.05 && stage->ss->height >= 0.1 && + stage->ss->width >= 0.1) { // The sprite fades out, and it doesn't start at a pinpoint. Let's fade it in. + fadeinout = qtrue; } - if (stage->ss->surfaceSpriteType == SURFSPRITE_WEATHERFX) - { // This effect is affected by weather settings. - if (curWeatherAmount < 0.01) - { // Don't show these effects + if (stage->ss->surfaceSpriteType == SURFSPRITE_WEATHERFX) { // This effect is affected by weather settings. + if (curWeatherAmount < 0.01) { // Don't show these effects return; - } - else - { + } else { density = stage->ss->density / curWeatherAmount; } - } - else - { + } else { density = stage->ss->density; } // Quickly calc all the alphas for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc alpha at each point VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0f - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; - // Note this is the proper equation, but isn't used right now because it would be just a tad slower. + // Note this is the proper equation, but isn't used right now because it would be just a tad slower. // Formula for alpha is 1.0f - ((len-fade)/(cut-fade)) // Which is equal to (1.0+fade/(cut-fade)) - (len/(cut-fade)) // So mult=1/(cut-fade), and base=(1+fade*mult). - // SSVertAlpha[curvert] = fadebase - (VectorLength(dist) * fademult); - + // SSVertAlpha[curvert] = fadebase - (VectorLength(dist) * fademult); } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - if (a1 <= 0.0f && a2 <= 0.0f && a3 <= 0.0f) - { + if (a1 <= 0.0f && a2 <= 0.0f && a3 <= 0.0f) { continue; } @@ -1325,105 +1136,89 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0f) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0f) { // Insanely small abhorrent triangle. continue; } step = density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd - for (posi=0; posi<1.0f; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - effecttime = (tr.refdef.time+10000.0*randomchart[randomindex])/stage->ss->fxDuration; + for (posi = 0; posi < 1.0f; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + effecttime = (tr.refdef.time + 10000.0 * randomchart[randomindex]) / stage->ss->fxDuration; effectpos = (float)effecttime - (int)effecttime; - randomindex2 = randomindex+effecttime; + randomindex2 = randomindex + effecttime; randomindex += randominterval; - fa=posi+randomchart[randomindex2++]*step; - if (fa>1.0f) + fa = posi + randomchart[randomindex2++] * step; + if (fa > 1.0f) continue; - fb=posj+randomchart[randomindex2++]*step; - if (fb>(1.0-fa)) + fb = posj + randomchart[randomindex2++] * step; + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0f to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex2]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex2]; randomindex2 += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0f - ((thisspritesfadestart-alphapos)/faderange); - if (alpha > 0.0f) - { + alpha = 1.0f - ((thisspritesfadestart - alphapos) / faderange); + if (alpha > 0.0f) { if (alpha > 1.0f) - alpha=1.0f; + alpha = 1.0f; VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; + light = l1 * fa + l2 * fb + l3 * fc; randomindex2 = randomindex; - width = stage->ss->width*(1.0f + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0f + (stage->ss->variance[1]*randomchart[randomindex2++])); + width = stage->ss->width * (1.0f + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0f + (stage->ss->variance[1] * randomchart[randomindex2++])); - width = width + (effectpos*stage->ss->fxGrow[0]*width); - height = height + (effectpos*stage->ss->fxGrow[1]*height); + width = width + (effectpos * stage->ss->fxGrow[0] * width); + height = height + (effectpos * stage->ss->fxGrow[1] * height); // If we want to fade in and out, that's different than a straight fade. - if (fadeinout) - { - if (effectpos > 0.5) - { // Fade out - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*(effectpos-0.5)*2.0)); - } - else - { // Fade in - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*(0.5-effectpos)*2.0)); + if (fadeinout) { + if (effectpos > 0.5) { // Fade out + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * (effectpos - 0.5) * 2.0)); + } else { // Fade in + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * (0.5 - effectpos) * 2.0)); } - } - else - { // Normal fade - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*effectpos)); + } else { // Normal fade + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * effectpos)); } - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } - if (randomchart[randomindex2]>0.5f) - { + if (randomchart[randomindex2] > 0.5f) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0f) - { - width *= 1.0f + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0f) { + width *= 1.0f + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (stage->ss->wind>0.0f && curWindSpeed > 0.001) - { + if (stage->ss->wind > 0.0f && curWindSpeed > 0.001) { vec3_t drawpoint; - VectorMA(curpoint, effectpos*stage->ss->wind, curWindBlowVect, drawpoint); - RB_EffectSurfaceSprite(drawpoint, width, height, (byte)light, (byte)(alpha*255.0f), stage->ss->fxDuration, stage->ss->facing); - } - else - { - RB_EffectSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0f), stage->ss->fxDuration, stage->ss->facing); + VectorMA(curpoint, effectpos * stage->ss->wind, curWindBlowVect, drawpoint); + RB_EffectSurfaceSprite(drawpoint, width, height, (byte)light, (byte)(alpha * 255.0f), stage->ss->fxDuration, stage->ss->facing); + } else { + RB_EffectSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0f), stage->ss->fxDuration, stage->ss->facing); } totalsurfsprites++; @@ -1433,64 +1228,51 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t } } -extern void R_WorldToLocal (vec3_t world, vec3_t localVec) ; +extern void R_WorldToLocal(vec3_t world, vec3_t localVec); extern float preTransEntMatrix[16], invEntMatrix[16]; extern void R_InvertMatrix(float *sourcemat, float *destmat); -void RB_DrawSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ - uint32_t glbits=stage->stateBits; +void RB_DrawSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { + uint32_t glbits = stage->stateBits; R_SurfaceSpriteFrameUpdate(); // // Check fog // - if ( tess.fogNum && tess.shader->fogPass && r_drawfog->value) - { + if (tess.fogNum && tess.shader->fogPass && r_drawfog->value) { SSUsingFog = qtrue; SQuickSprite.StartGroup(&stage->bundle[0], glbits, tess.fogNum); - } - else - { + } else { SSUsingFog = qfalse; SQuickSprite.StartGroup(&stage->bundle[0], glbits); } // Special provision in case the transparency is additive. - if ((glbits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) - { // Additive transparency, scale light value - SSAdditiveTransparency=qtrue; - } - else - { - SSAdditiveTransparency=qfalse; + if ((glbits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) { // Additive transparency, scale light value + SSAdditiveTransparency = qtrue; + } else { + SSAdditiveTransparency = qfalse; } - - //Check if this is a new entity transformation (incl. world entity), and update the appropriate vectors if so. - if (backEnd.currentEntity != ssLastEntityDrawn) - { - if (backEnd.currentEntity == &tr.worldEntity) - { // Drawing the world, so our job is dead-easy, in the viewparms + // Check if this is a new entity transformation (incl. world entity), and update the appropriate vectors if so. + if (backEnd.currentEntity != ssLastEntityDrawn) { + if (backEnd.currentEntity == &tr.worldEntity) { // Drawing the world, so our job is dead-easy, in the viewparms VectorCopy(backEnd.viewParms.ori.origin, ssViewOrigin); VectorCopy(backEnd.viewParms.ori.axis[1], ssViewRight); VectorCopy(backEnd.viewParms.ori.axis[2], ssViewUp); - } - else - { // Drawing an entity, so we need to transform the viewparms to the model's coordinate system -// R_WorldPointToEntity (backEnd.viewParms.ori.origin, ssViewOrigin); - R_WorldNormalToEntity (backEnd.viewParms.ori.axis[1], ssViewRight); - R_WorldNormalToEntity (backEnd.viewParms.ori.axis[2], ssViewUp); + } else { // Drawing an entity, so we need to transform the viewparms to the model's coordinate system + // R_WorldPointToEntity (backEnd.viewParms.ori.origin, ssViewOrigin); + R_WorldNormalToEntity(backEnd.viewParms.ori.axis[1], ssViewRight); + R_WorldNormalToEntity(backEnd.viewParms.ori.axis[2], ssViewUp); VectorCopy(backEnd.ori.viewOrigin, ssViewOrigin); -// R_WorldToLocal(backEnd.viewParms.ori.axis[1], ssViewRight); -// R_WorldToLocal(backEnd.viewParms.ori.axis[2], ssViewUp); + // R_WorldToLocal(backEnd.viewParms.ori.axis[1], ssViewRight); + // R_WorldToLocal(backEnd.viewParms.ori.axis[2], ssViewUp); } ssLastEntityDrawn = backEnd.currentEntity; } - switch(stage->ss->surfaceSpriteType) - { + switch (stage->ss->surfaceSpriteType) { case SURFSPRITE_FLATTENED: case SURFSPRITE_VERTICAL: RB_DrawVerticalSurfaceSprites(stage, input); @@ -1508,4 +1290,3 @@ void RB_DrawSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) sssurfaces++; } - diff --git a/code/rd-vanilla/tr_world.cpp b/code/rd-vanilla/tr_world.cpp index 4a472e2487..402457fad7 100644 --- a/code/rd-vanilla/tr_world.cpp +++ b/code/rd-vanilla/tr_world.cpp @@ -33,12 +33,12 @@ Returns true if the grid is completely culled away. Also sets the clipped hint bit in tess ================= */ -static qboolean R_CullTriSurf( srfTriangles_t *cv ) { - int boxCull; +static qboolean R_CullTriSurf(srfTriangles_t *cv) { + int boxCull; - boxCull = R_CullLocalBox( cv->bounds ); + boxCull = R_CullLocalBox(cv->bounds); - if ( boxCull == CULL_OUT ) { + if (boxCull == CULL_OUT) { return qtrue; } return qfalse; @@ -52,57 +52,47 @@ Returns true if the grid is completely culled away. Also sets the clipped hint bit in tess ================= */ -static qboolean R_CullGrid( srfGridMesh_t *cv ) { - int boxCull; - int sphereCull; +static qboolean R_CullGrid(srfGridMesh_t *cv) { + int boxCull; + int sphereCull; - if ( r_nocurves->integer ) { + if (r_nocurves->integer) { return qtrue; } - if ( tr.currentEntityNum != REFENTITYNUM_WORLD ) { - sphereCull = R_CullLocalPointAndRadius( cv->localOrigin, cv->meshRadius ); + if (tr.currentEntityNum != REFENTITYNUM_WORLD) { + sphereCull = R_CullLocalPointAndRadius(cv->localOrigin, cv->meshRadius); } else { - sphereCull = R_CullPointAndRadius( cv->localOrigin, cv->meshRadius ); + sphereCull = R_CullPointAndRadius(cv->localOrigin, cv->meshRadius); } boxCull = CULL_OUT; // check for trivial reject - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_patch_out++; return qtrue; } // check bounding box if necessary - else if ( sphereCull == CULL_CLIP ) - { + else if (sphereCull == CULL_CLIP) { tr.pc.c_sphere_cull_patch_clip++; - boxCull = R_CullLocalBox( cv->meshBounds ); + boxCull = R_CullLocalBox(cv->meshBounds); - if ( boxCull == CULL_OUT ) - { + if (boxCull == CULL_OUT) { tr.pc.c_box_cull_patch_out++; return qtrue; - } - else if ( boxCull == CULL_IN ) - { + } else if (boxCull == CULL_IN) { tr.pc.c_box_cull_patch_in++; - } - else - { + } else { tr.pc.c_box_cull_patch_clip++; } - } - else - { + } else { tr.pc.c_sphere_cull_patch_in++; } return qfalse; } - /* ================ R_CullSurface @@ -113,47 +103,47 @@ added to the sorting list. This will also allow mirrors on both sides of a model without recursion. ================ */ -static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { +static qboolean R_CullSurface(surfaceType_t *surface, shader_t *shader) { srfSurfaceFace_t *sface; - float d; + float d; - if ( r_nocull->integer==1 ) { + if (r_nocull->integer == 1) { return qfalse; } - if ( *surface == SF_GRID ) { - return R_CullGrid( (srfGridMesh_t *)surface ); + if (*surface == SF_GRID) { + return R_CullGrid((srfGridMesh_t *)surface); } - if ( *surface == SF_TRIANGLES ) { - return R_CullTriSurf( (srfTriangles_t *)surface ); + if (*surface == SF_TRIANGLES) { + return R_CullTriSurf((srfTriangles_t *)surface); } - if ( *surface != SF_FACE ) { + if (*surface != SF_FACE) { return qfalse; } - if ( shader->cullType == CT_TWO_SIDED ) { + if (shader->cullType == CT_TWO_SIDED) { return qfalse; } // face culling - if ( !r_facePlaneCull->integer ) { + if (!r_facePlaneCull->integer) { return qfalse; } - sface = ( srfSurfaceFace_t * ) surface; - d = DotProduct (tr.ori.viewOrigin, sface->plane.normal); + sface = (srfSurfaceFace_t *)surface; + d = DotProduct(tr.ori.viewOrigin, sface->plane.normal); // don't cull exactly on the plane, because there are levels of rounding // through the BSP, ICD, and hardware that may cause pixel gaps if an // epsilon isn't allowed here - if ( shader->cullType == CT_FRONT_SIDED ) { - if ( d < sface->plane.dist - 8 ) { + if (shader->cullType == CT_FRONT_SIDED) { + if (d < sface->plane.dist - 8) { return qtrue; } } else { - if ( d > sface->plane.dist + 8 ) { + if (d > sface->plane.dist + 8) { return qtrue; } } @@ -161,24 +151,24 @@ static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { return qfalse; } -static int R_DlightFace( srfSurfaceFace_t *face, int dlightBits ) { - float d; - int i; - dlight_t *dl; +static int R_DlightFace(srfSurfaceFace_t *face, int dlightBits) { + float d; + int i; + dlight_t *dl; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - d = DotProduct( dl->origin, face->plane.normal ) - face->plane.dist; - if ( !VectorCompare(face->plane.normal, vec3_origin) && (d < -dl->radius || d > dl->radius) ) { + d = DotProduct(dl->origin, face->plane.normal) - face->plane.dist; + if (!VectorCompare(face->plane.normal, vec3_origin) && (d < -dl->radius || d > dl->radius)) { // dlight doesn't reach the plane - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } - if ( !dlightBits ) { + if (!dlightBits) { tr.pc.c_dlightSurfacesCulled++; } @@ -186,27 +176,24 @@ static int R_DlightFace( srfSurfaceFace_t *face, int dlightBits ) { return dlightBits; } -static int R_DlightGrid( srfGridMesh_t *grid, int dlightBits ) { - int i; - dlight_t *dl; +static int R_DlightGrid(srfGridMesh_t *grid, int dlightBits) { + int i; + dlight_t *dl; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - if ( dl->origin[0] - dl->radius > grid->meshBounds[1][0] - || dl->origin[0] + dl->radius < grid->meshBounds[0][0] - || dl->origin[1] - dl->radius > grid->meshBounds[1][1] - || dl->origin[1] + dl->radius < grid->meshBounds[0][1] - || dl->origin[2] - dl->radius > grid->meshBounds[1][2] - || dl->origin[2] + dl->radius < grid->meshBounds[0][2] ) { + if (dl->origin[0] - dl->radius > grid->meshBounds[1][0] || dl->origin[0] + dl->radius < grid->meshBounds[0][0] || + dl->origin[1] - dl->radius > grid->meshBounds[1][1] || dl->origin[1] + dl->radius < grid->meshBounds[0][1] || + dl->origin[2] - dl->radius > grid->meshBounds[1][2] || dl->origin[2] + dl->radius < grid->meshBounds[0][2]) { // dlight doesn't reach the bounds - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } - if ( !dlightBits ) { + if (!dlightBits) { tr.pc.c_dlightSurfacesCulled++; } @@ -214,7 +201,7 @@ static int R_DlightGrid( srfGridMesh_t *grid, int dlightBits ) { return dlightBits; } -static int R_DlightTrisurf( srfTriangles_t *surf, int dlightBits ) { +static int R_DlightTrisurf(srfTriangles_t *surf, int dlightBits) { // FIXME: more dlight culling to trisurfs... surf->dlightBits = dlightBits; return dlightBits; @@ -256,18 +243,18 @@ that is touched by one or more dlights, so try to throw out more dlights if possible. ==================== */ -static int R_DlightSurface( msurface_t *surf, int dlightBits ) { - if ( *surf->data == SF_FACE ) { - dlightBits = R_DlightFace( (srfSurfaceFace_t *)surf->data, dlightBits ); - } else if ( *surf->data == SF_GRID ) { - dlightBits = R_DlightGrid( (srfGridMesh_t *)surf->data, dlightBits ); - } else if ( *surf->data == SF_TRIANGLES ) { - dlightBits = R_DlightTrisurf( (srfTriangles_t *)surf->data, dlightBits ); +static int R_DlightSurface(msurface_t *surf, int dlightBits) { + if (*surf->data == SF_FACE) { + dlightBits = R_DlightFace((srfSurfaceFace_t *)surf->data, dlightBits); + } else if (*surf->data == SF_GRID) { + dlightBits = R_DlightGrid((srfGridMesh_t *)surf->data, dlightBits); + } else if (*surf->data == SF_TRIANGLES) { + dlightBits = R_DlightTrisurf((srfTriangles_t *)surf->data, dlightBits); } else { dlightBits = 0; } - if ( dlightBits ) { + if (dlightBits) { tr.pc.c_dlightSurfaces++; } @@ -279,31 +266,24 @@ static int R_DlightSurface( msurface_t *surf, int dlightBits ) { R_AddWorldSurface ====================== */ -static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noViewCount = qfalse ) { +static void R_AddWorldSurface(msurface_t *surf, int dlightBits, qboolean noViewCount = qfalse) { /* if ( surf->viewCount == tr.viewCount ) { return; // already in this view } */ - //rww - changed this to be like sof2mp's so RMG will look right. - //Will this affect anything that is non-rmg? + // rww - changed this to be like sof2mp's so RMG will look right. + // Will this affect anything that is non-rmg? - if (!noViewCount) - { - if ( surf->viewCount == tr.viewCount ) - { + if (!noViewCount) { + if (surf->viewCount == tr.viewCount) { // already in this view, but lets make sure all the dlight bits are set - if ( *surf->data == SF_FACE ) - { + if (*surf->data == SF_FACE) { ((srfSurfaceFace_t *)surf->data)->dlightBits |= dlightBits; - } - else if ( *surf->data == SF_GRID ) - { + } else if (*surf->data == SF_GRID) { ((srfGridMesh_t *)surf->data)->dlightBits |= dlightBits; - } - else if ( *surf->data == SF_TRIANGLES ) - { + } else if (*surf->data == SF_TRIANGLES) { ((srfTriangles_t *)surf->data)->dlightBits |= dlightBits; } return; @@ -312,21 +292,21 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView // FIXME: bmodel fog? } -// surf->viewCount = tr.viewCount; + // surf->viewCount = tr.viewCount; // FIXME: bmodel fog? // try to cull before dlighting or adding - if ( R_CullSurface( surf->data, surf->shader ) ) { + if (R_CullSurface(surf->data, surf->shader)) { return; } // check for dlighting - if ( dlightBits ) { - dlightBits = R_DlightSurface( surf, dlightBits ); - dlightBits = ( dlightBits != 0 ); + if (dlightBits) { + dlightBits = R_DlightSurface(surf, dlightBits); + dlightBits = (dlightBits != 0); } - R_AddDrawSurf( surf->data, surf->shader, surf->fogIndex, dlightBits ); + R_AddDrawSurf(surf->data, surf->shader, surf->fogIndex, dlightBits); } /* @@ -342,82 +322,76 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView R_AddBrushModelSurfaces ================= */ -void R_AddBrushModelSurfaces ( trRefEntity_t *ent ) { - bmodel_t *bmodel; - int clip; - model_t *pModel; - int i; +void R_AddBrushModelSurfaces(trRefEntity_t *ent) { + bmodel_t *bmodel; + int clip; + model_t *pModel; + int i; - pModel = R_GetModelByHandle( ent->e.hModel ); + pModel = R_GetModelByHandle(ent->e.hModel); bmodel = pModel->bmodel; - clip = R_CullLocalBox( bmodel->bounds ); - if ( clip == CULL_OUT ) { + clip = R_CullLocalBox(bmodel->bounds); + if (clip == CULL_OUT) { return; } - if(pModel->bspInstance) - { + if (pModel->bspInstance) { R_SetupEntityLighting(&tr.refdef, ent); } - R_DlightBmodel( bmodel, qfalse ); + R_DlightBmodel(bmodel, qfalse); - for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { - R_AddWorldSurface( bmodel->firstSurface + i, tr.currentEntity->dlightBits, qtrue ); + for (i = 0; i < bmodel->numSurfaces; i++) { + R_AddWorldSurface(bmodel->firstSurface + i, tr.currentEntity->dlightBits, qtrue); } } -float GetQuadArea( vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4 ) -{ - vec3_t vec1, vec2, dis1, dis2; +float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) { + vec3_t vec1, vec2, dis1, dis2; // Get area of tri1 - VectorSubtract( v1, v2, vec1 ); - VectorSubtract( v1, v4, vec2 ); - CrossProduct( vec1, vec2, dis1 ); - VectorScale( dis1, 0.25f, dis1 ); + VectorSubtract(v1, v2, vec1); + VectorSubtract(v1, v4, vec2); + CrossProduct(vec1, vec2, dis1); + VectorScale(dis1, 0.25f, dis1); // Get area of tri2 - VectorSubtract( v3, v2, vec1 ); - VectorSubtract( v3, v4, vec2 ); - CrossProduct( vec1, vec2, dis2 ); - VectorScale( dis2, 0.25f, dis2 ); + VectorSubtract(v3, v2, vec1); + VectorSubtract(v3, v4, vec2); + CrossProduct(vec1, vec2, dis2); + VectorScale(dis2, 0.25f, dis2); // Return addition of disSqr of each tri area - return ( dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + - dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2] ); + return (dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2]); } -void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) -{ - msurface_t *surfs; - srfSurfaceFace_t *face; - bmodel_t *bmodel; - model_t *pModel; - int i; +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { + msurface_t *surfs; + srfSurfaceFace_t *face; + bmodel_t *bmodel; + model_t *pModel; + int i; // Not sure if we really need to track the best two candidates - int maxDist[2]={0,0}; - int maxIndx[2]={0,0}; - int dist = 0; - float dot1, dot2; + int maxDist[2] = {0, 0}; + int maxIndx[2] = {0, 0}; + int dist = 0; + float dot1, dot2; - pModel = R_GetModelByHandle( bmodelIndex ); + pModel = R_GetModelByHandle(bmodelIndex); bmodel = pModel->bmodel; // Loop through all surfaces on the brush and find the best two candidates - for ( i = 0 ; i < bmodel->numSurfaces; i++ ) - { + for (i = 0; i < bmodel->numSurfaces; i++) { surfs = bmodel->firstSurface + i; - face = ( srfSurfaceFace_t *)surfs->data; + face = (srfSurfaceFace_t *)surfs->data; // It seems that the safest way to handle this is by finding the area of the faces - dist = GetQuadArea( face->points[0], face->points[1], face->points[2], face->points[3] ); + dist = GetQuadArea(face->points[0], face->points[1], face->points[2], face->points[3]); // Check against the highest max - if ( dist > maxDist[0] ) - { + if (dist > maxDist[0]) { // Shuffle our current maxes down maxDist[1] = maxDist[0]; maxIndx[1] = maxIndx[0]; @@ -426,8 +400,7 @@ void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) maxIndx[0] = i; } // Check against the second highest max - else if ( dist >= maxDist[1] ) - { + else if (dist >= maxDist[1]) { // just stomp the old maxDist[1] = dist; maxIndx[1] = i; @@ -436,33 +409,27 @@ void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) // Hopefully we've found two best case candidates. Now we should see which of these faces the viewer surfs = bmodel->firstSurface + maxIndx[0]; - face = ( srfSurfaceFace_t *)surfs->data; - dot1 = DotProduct( face->plane.normal, tr.refdef.viewaxis[0] ); + face = (srfSurfaceFace_t *)surfs->data; + dot1 = DotProduct(face->plane.normal, tr.refdef.viewaxis[0]); surfs = bmodel->firstSurface + maxIndx[1]; - face = ( srfSurfaceFace_t *)surfs->data; - dot2 = DotProduct( face->plane.normal, tr.refdef.viewaxis[0] ); + face = (srfSurfaceFace_t *)surfs->data; + dot2 = DotProduct(face->plane.normal, tr.refdef.viewaxis[0]); - if ( dot2 < dot1 && dot2 < 0.0f ) - { + if (dot2 < dot1 && dot2 < 0.0f) { i = maxIndx[1]; // use the second face - } - else if ( dot1 < dot2 && dot1 < 0.0f ) - { + } else if (dot1 < dot2 && dot1 < 0.0f) { i = maxIndx[0]; // use the first face - } - else - { // Possibly only have one face, so may as well use the first face, which also should be the best one - //i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen + } else { // Possibly only have one face, so may as well use the first face, which also should be the best one + // i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen i = maxIndx[0]; // use the first face } surfs = bmodel->firstSurface + i; - face = ( srfSurfaceFace_t *)surfs->data; + face = (srfSurfaceFace_t *)surfs->data; - for ( int t = 0; t < 4; t++ ) - { - VectorCopy( face->points[t], verts[t] ); + for (int t = 0; t < 4; t++) { + VectorCopy(face->points[t], verts[t]); } } @@ -474,16 +441,15 @@ void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) ============================================================= */ - /* ================ R_RecursiveWorldNode ================ */ -static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) { +static void R_RecursiveWorldNode(mnode_t *node, int planeBits, int dlightBits) { do { - int newDlights[2]; + int newDlights[2]; // if the node wasn't marked as potentially visible, exit if (node->visframe != tr.visCount) { @@ -493,130 +459,124 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) // if the bounding volume is outside the frustum, nothing // inside can be visible OPTIMIZE: don't do this all the way to leafs? - if ( r_nocull->integer!=1 ) { - int r; + if (r_nocull->integer != 1) { + int r; - if ( planeBits & 1 ) { + if (planeBits & 1) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[0]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~1; // all descendants will also be in front + if (r == 1) { + planeBits &= ~1; // all descendants will also be in front } } - if ( planeBits & 2 ) { + if (planeBits & 2) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[1]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~2; // all descendants will also be in front + if (r == 1) { + planeBits &= ~2; // all descendants will also be in front } } - if ( planeBits & 4 ) { + if (planeBits & 4) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[2]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~4; // all descendants will also be in front + if (r == 1) { + planeBits &= ~4; // all descendants will also be in front } } - if ( planeBits & 8 ) { + if (planeBits & 8) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[3]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~8; // all descendants will also be in front + if (r == 1) { + planeBits &= ~8; // all descendants will also be in front } } - if ( planeBits & 16 ) { + if (planeBits & 16) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[4]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~16; // all descendants will also be in front + if (r == 1) { + planeBits &= ~16; // all descendants will also be in front } } - } - if ( node->contents != -1 ) { + if (node->contents != -1) { break; } // determine which dlights are needed - if ( r_nocull->integer!=2 ) - { + if (r_nocull->integer != 2) { newDlights[0] = 0; newDlights[1] = 0; - if ( dlightBits ) - { - int i; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) - { - dlight_t *dl; - float dist; - - if ( dlightBits & ( 1 << i ) ) { + if (dlightBits) { + int i; + for (i = 0; i < tr.refdef.num_dlights; i++) { + dlight_t *dl; + float dist; + + if (dlightBits & (1 << i)) { dl = &tr.refdef.dlights[i]; - dist = DotProduct( dl->origin, node->plane->normal ) - node->plane->dist; + dist = DotProduct(dl->origin, node->plane->normal) - node->plane->dist; - if ( dist > -dl->radius ) { - newDlights[0] |= ( 1 << i ); + if (dist > -dl->radius) { + newDlights[0] |= (1 << i); } - if ( dist < dl->radius ) { - newDlights[1] |= ( 1 << i ); + if (dist < dl->radius) { + newDlights[1] |= (1 << i); } } } } - } - else - { + } else { newDlights[0] = dlightBits; newDlights[1] = dlightBits; } // recurse down the children, front side first - R_RecursiveWorldNode (node->children[0], planeBits, newDlights[0] ); + R_RecursiveWorldNode(node->children[0], planeBits, newDlights[0]); // tail recurse node = node->children[1]; dlightBits = newDlights[1]; - } while ( 1 ); + } while (1); { // leaf node, so add mark surfaces - int c; - msurface_t *surf, **mark; + int c; + msurface_t *surf, **mark; tr.pc.c_leafs++; // add to z buffer bounds - if ( node->mins[0] < tr.viewParms.visBounds[0][0] ) { + if (node->mins[0] < tr.viewParms.visBounds[0][0]) { tr.viewParms.visBounds[0][0] = node->mins[0]; } - if ( node->mins[1] < tr.viewParms.visBounds[0][1] ) { + if (node->mins[1] < tr.viewParms.visBounds[0][1]) { tr.viewParms.visBounds[0][1] = node->mins[1]; } - if ( node->mins[2] < tr.viewParms.visBounds[0][2] ) { + if (node->mins[2] < tr.viewParms.visBounds[0][2]) { tr.viewParms.visBounds[0][2] = node->mins[2]; } - if ( node->maxs[0] > tr.viewParms.visBounds[1][0] ) { + if (node->maxs[0] > tr.viewParms.visBounds[1][0]) { tr.viewParms.visBounds[1][0] = node->maxs[0]; } - if ( node->maxs[1] > tr.viewParms.visBounds[1][1] ) { + if (node->maxs[1] > tr.viewParms.visBounds[1][1]) { tr.viewParms.visBounds[1][1] = node->maxs[1]; } - if ( node->maxs[2] > tr.viewParms.visBounds[1][2] ) { + if (node->maxs[2] > tr.viewParms.visBounds[1][2]) { tr.viewParms.visBounds[1][2] = node->maxs[2]; } @@ -627,11 +587,10 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) // the surface may have already been added if it // spans multiple leafs surf = *mark; - R_AddWorldSurface( surf, dlightBits ); + R_AddWorldSurface(surf, dlightBits); mark++; } } - } /* @@ -639,23 +598,23 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) R_PointInLeaf =============== */ -static mnode_t *R_PointInLeaf( vec3_t p ) { - mnode_t *node; - float d; - cplane_t *plane; +static mnode_t *R_PointInLeaf(vec3_t p) { + mnode_t *node; + float d; + cplane_t *plane; - if ( !tr.world ) { - Com_Error (ERR_DROP, "R_PointInLeaf: bad model"); + if (!tr.world) { + Com_Error(ERR_DROP, "R_PointInLeaf: bad model"); } node = tr.world->nodes; - while( 1 ) { + while (1) { if (node->contents != -1) { break; } plane = node->plane; - d = DotProduct (p,plane->normal) - plane->dist; + d = DotProduct(p, plane->normal) - plane->dist; if (d > 0) { node = node->children[0]; } else { @@ -671,8 +630,8 @@ static mnode_t *R_PointInLeaf( vec3_t p ) { R_ClusterPVS ============== */ -static const byte *R_ClusterPVS (int cluster) { - if (!tr.world || !tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters ) { +static const byte *R_ClusterPVS(int cluster) { + if (!tr.world || !tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters) { return tr.world->novis; } @@ -685,15 +644,15 @@ R_inPVS ================= */ -qboolean R_inPVS( vec3_t p1, vec3_t p2 ) { +qboolean R_inPVS(vec3_t p1, vec3_t p2) { mnode_t *leaf; - byte *vis; + byte *vis; - leaf = R_PointInLeaf( p1 ); - vis = ri.CM_ClusterPVS( leaf->cluster ); - leaf = R_PointInLeaf( p2 ); + leaf = R_PointInLeaf(p1); + vis = ri.CM_ClusterPVS(leaf->cluster); + leaf = R_PointInLeaf(p2); - if ( !(vis[leaf->cluster>>3] & (1<<(leaf->cluster&7))) ) { + if (!(vis[leaf->cluster >> 3] & (1 << (leaf->cluster & 7)))) { return qfalse; } return qtrue; @@ -707,43 +666,42 @@ Mark the leaves and nodes that are in the PVS for the current cluster =============== */ -static void R_MarkLeaves (void) { - const byte *vis; - mnode_t *leaf, *parent; - int i; - int cluster; +static void R_MarkLeaves(void) { + const byte *vis; + mnode_t *leaf, *parent; + int i; + int cluster; // lockpvs lets designers walk around to determine the // extent of the current pvs - if ( r_lockpvs->integer ) { + if (r_lockpvs->integer) { return; } // current viewcluster - leaf = R_PointInLeaf( tr.viewParms.pvsOrigin ); + leaf = R_PointInLeaf(tr.viewParms.pvsOrigin); cluster = leaf->cluster; // if the cluster is the same and the area visibility matrix // hasn't changed, we don't need to mark everything again // if r_showcluster was just turned on, remark everything - if ( tr.viewCluster == cluster && !tr.refdef.areamaskModified - && !r_showcluster->modified ) { + if (tr.viewCluster == cluster && !tr.refdef.areamaskModified && !r_showcluster->modified) { return; } - if ( r_showcluster->modified || r_showcluster->integer ) { + if (r_showcluster->modified || r_showcluster->integer) { r_showcluster->modified = qfalse; - if ( r_showcluster->integer ) { - ri.Printf( PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area ); + if (r_showcluster->integer) { + ri.Printf(PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area); } } tr.visCount++; tr.viewCluster = cluster; - if ( r_novis->integer || tr.viewCluster == -1 ) { - for (i=0 ; inumnodes ; i++) { + if (r_novis->integer || tr.viewCluster == -1) { + for (i = 0; i < tr.world->numnodes; i++) { if (tr.world->nodes[i].contents != CONTENTS_SOLID) { tr.world->nodes[i].visframe = tr.visCount; } @@ -751,22 +709,22 @@ static void R_MarkLeaves (void) { return; } - vis = R_ClusterPVS (tr.viewCluster); + vis = R_ClusterPVS(tr.viewCluster); - for (i=0,leaf=tr.world->nodes ; inumnodes ; i++, leaf++) { + for (i = 0, leaf = tr.world->nodes; i < tr.world->numnodes; i++, leaf++) { cluster = leaf->cluster; - if ( cluster < 0 || cluster >= tr.world->numClusters ) { + if (cluster < 0 || cluster >= tr.world->numClusters) { continue; } // check general pvs - if ( !(vis[cluster>>3] & (1<<(cluster&7))) ) { + if (!(vis[cluster >> 3] & (1 << (cluster & 7)))) { continue; } // check for door connection - if ( (tr.refdef.areamask[leaf->area>>3] & (1<<(leaf->area&7)) ) ) { - continue; // not visible + if ((tr.refdef.areamask[leaf->area >> 3] & (1 << (leaf->area & 7)))) { + continue; // not visible } parent = leaf; @@ -784,12 +742,12 @@ static void R_MarkLeaves (void) { R_AddWorldSurfaces ============= */ -void R_AddWorldSurfaces (void) { - if ( !r_drawworld->integer ) { +void R_AddWorldSurfaces(void) { + if (!r_drawworld->integer) { return; } - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return; } @@ -797,15 +755,15 @@ void R_AddWorldSurfaces (void) { tr.shiftedEntityNum = tr.currentEntityNum << QSORT_REFENTITYNUM_SHIFT; // determine which leaves are in the PVS / areamask - R_MarkLeaves (); + R_MarkLeaves(); // clear out the visible min/max - ClearBounds( tr.viewParms.visBounds[0], tr.viewParms.visBounds[1] ); + ClearBounds(tr.viewParms.visBounds[0], tr.viewParms.visBounds[1]); // perform frustum culling and add all the potentially visible surfaces - if ( tr.refdef.num_dlights > 32 ) { - tr.refdef.num_dlights = 32 ; + if (tr.refdef.num_dlights > 32) { + tr.refdef.num_dlights = 32; } - R_RecursiveWorldNode( tr.world->nodes, 31, ( 1 << tr.refdef.num_dlights ) - 1 ); + R_RecursiveWorldNode(tr.world->nodes, 31, (1 << tr.refdef.num_dlights) - 1); } diff --git a/code/server/sv_ccmds.cpp b/code/server/sv_ccmds.cpp index 67b079ae02..b4bebf295e 100644 --- a/code/server/sv_ccmds.cpp +++ b/code/server/sv_ccmds.cpp @@ -30,7 +30,6 @@ along with this program; if not, see . #include "../win32/AutoVersion.h" - /* =============================================================================== @@ -45,187 +44,120 @@ qboolean qbLoadTransition = qfalse; //========================================================= // don't call this directly, it should only be called from SV_Map_f() or SV_MapTransition_f() // -static bool SV_Map_( ForceReload_e eForceReload ) -{ - char *map = NULL; - char expanded[MAX_QPATH] = {0}; +static bool SV_Map_(ForceReload_e eForceReload) { + char *map = NULL; + char expanded[MAX_QPATH] = {0}; map = Cmd_Argv(1); - if ( !*map ) { - Com_Printf ("no map specified\n"); + if (!*map) { + Com_Printf("no map specified\n"); return false; } // make sure the level exists before trying to change, so that // a typo at the server console won't end the game - if (strchr (map, '\\') ) { - Com_Printf ("Can't have mapnames with a \\\n"); + if (strchr(map, '\\')) { + Com_Printf("Can't have mapnames with a \\\n"); return false; } - Com_sprintf (expanded, sizeof(expanded), "maps/%s.bsp", map); + Com_sprintf(expanded, sizeof(expanded), "maps/%s.bsp", map); - if ( FS_ReadFile (expanded, NULL) == -1 ) { - Com_Printf ("Can't find map %s\n", expanded); - extern cvar_t *com_buildScript; - if (com_buildScript && com_buildScript->integer) - {//yes, it's happened, someone deleted a map during my build... - Com_Error( ERR_FATAL, "Can't find map %s\n", expanded ); + if (FS_ReadFile(expanded, NULL) == -1) { + Com_Printf("Can't find map %s\n", expanded); + extern cvar_t *com_buildScript; + if (com_buildScript && com_buildScript->integer) { // yes, it's happened, someone deleted a map during my build... + Com_Error(ERR_FATAL, "Can't find map %s\n", expanded); } return false; } - if (map[0]!='_') - { + if (map[0] != '_') { SG_WipeSavegame("auto"); } - SV_SpawnServer( map, eForceReload, qtrue ); // start up the map + SV_SpawnServer(map, eForceReload, qtrue); // start up the map return true; } - - // Save out some player data for later restore if this is a spawn point with KEEP_PREV (spawnflags&1) set... // // (now also called by auto-save code to setup the cvars correctly -void SV_Player_EndOfLevelSave(void) -{ - int i; +void SV_Player_EndOfLevelSave(void) { + int i; // I could just call GetClientState() but that's in sv_bot.cpp, and I'm not sure if that's going to be deleted for // the single player build, so here's the guts again... // - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player - - if (cl - && - cl->gentity && cl->gentity->client // crash fix for voy4->brig transition when you kill Foster. - // Shouldn't happen, but does sometimes... - ) - { - Cvar_Set( sCVARNAME_PLAYERSAVE, ""); // default to blank - -// clientSnapshot_t* pFrame = &cl->frames[cl->netchan.outgoingSequence & PACKET_MASK]; - playerState_t* pState = cl->gentity->client; - const char *s2; + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + + if (cl && cl->gentity && cl->gentity->client // crash fix for voy4->brig transition when you kill Foster. + // Shouldn't happen, but does sometimes... + ) { + Cvar_Set(sCVARNAME_PLAYERSAVE, ""); // default to blank + + // clientSnapshot_t* pFrame = &cl->frames[cl->netchan.outgoingSequence & PACKET_MASK]; + playerState_t *pState = cl->gentity->client; + const char *s2; const char *s; #ifdef JK2_MODE - s = va("%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %i", - pState->stats[STAT_HEALTH], - pState->stats[STAT_ARMOR], - pState->stats[STAT_WEAPONS], - pState->stats[STAT_ITEMS], - pState->weapon, - pState->weaponstate, - pState->batteryCharge, - pState->viewangles[0], - pState->viewangles[1], - pState->viewangles[2], - pState->forcePowersKnown, - pState->forcePower, - pState->saberActive, - pState->saberAnimLevel, - pState->saberLockEnemy, - pState->saberLockTime - ); + s = va("%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %i", pState->stats[STAT_HEALTH], pState->stats[STAT_ARMOR], pState->stats[STAT_WEAPONS], + pState->stats[STAT_ITEMS], pState->weapon, pState->weaponstate, pState->batteryCharge, pState->viewangles[0], pState->viewangles[1], + pState->viewangles[2], pState->forcePowersKnown, pState->forcePower, pState->saberActive, pState->saberAnimLevel, pState->saberLockEnemy, + pState->saberLockTime); #else - // |general info |-force powers |-saber 1 |-saber 2 |-general saber - s = va("%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %s %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %s %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i", - pState->stats[STAT_HEALTH], - pState->stats[STAT_ARMOR], - pState->stats[STAT_WEAPONS], - pState->stats[STAT_ITEMS], - pState->weapon, - pState->weaponstate, - pState->batteryCharge, - pState->viewangles[0], - pState->viewangles[1], - pState->viewangles[2], - //force power data - pState->forcePowersKnown, - pState->forcePower, - pState->forcePowerMax, - pState->forcePowerRegenRate, - pState->forcePowerRegenAmount, - //saber 1 data - pState->saber[0].name, - pState->saber[0].blade[0].active, - pState->saber[0].blade[1].active, - pState->saber[0].blade[2].active, - pState->saber[0].blade[3].active, - pState->saber[0].blade[4].active, - pState->saber[0].blade[5].active, - pState->saber[0].blade[6].active, - pState->saber[0].blade[7].active, - pState->saber[0].blade[0].color, - pState->saber[0].blade[1].color, - pState->saber[0].blade[2].color, - pState->saber[0].blade[3].color, - pState->saber[0].blade[4].color, - pState->saber[0].blade[5].color, - pState->saber[0].blade[6].color, - pState->saber[0].blade[7].color, - //saber 2 data - pState->saber[1].name, - pState->saber[1].blade[0].active, - pState->saber[1].blade[1].active, - pState->saber[1].blade[2].active, - pState->saber[1].blade[3].active, - pState->saber[1].blade[4].active, - pState->saber[1].blade[5].active, - pState->saber[1].blade[6].active, - pState->saber[1].blade[7].active, - pState->saber[1].blade[0].color, - pState->saber[1].blade[1].color, - pState->saber[1].blade[2].color, - pState->saber[1].blade[3].color, - pState->saber[1].blade[4].color, - pState->saber[1].blade[5].color, - pState->saber[1].blade[6].color, - pState->saber[1].blade[7].color, - //general saber data - pState->saberStylesKnown, - pState->saberAnimLevel, - pState->saberLockEnemy, - pState->saberLockTime - ); + // |general info |-force powers |-saber 1 |-saber 2 |-general saber + s = va("%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %s %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %s %i %i %i %i %i %i %i %i %i %i %i %i %i %i " + "%i %i %i %i %i %i", + pState->stats[STAT_HEALTH], pState->stats[STAT_ARMOR], pState->stats[STAT_WEAPONS], pState->stats[STAT_ITEMS], pState->weapon, + pState->weaponstate, pState->batteryCharge, pState->viewangles[0], pState->viewangles[1], pState->viewangles[2], + // force power data + pState->forcePowersKnown, pState->forcePower, pState->forcePowerMax, pState->forcePowerRegenRate, pState->forcePowerRegenAmount, + // saber 1 data + pState->saber[0].name, pState->saber[0].blade[0].active, pState->saber[0].blade[1].active, pState->saber[0].blade[2].active, + pState->saber[0].blade[3].active, pState->saber[0].blade[4].active, pState->saber[0].blade[5].active, pState->saber[0].blade[6].active, + pState->saber[0].blade[7].active, pState->saber[0].blade[0].color, pState->saber[0].blade[1].color, pState->saber[0].blade[2].color, + pState->saber[0].blade[3].color, pState->saber[0].blade[4].color, pState->saber[0].blade[5].color, pState->saber[0].blade[6].color, + pState->saber[0].blade[7].color, + // saber 2 data + pState->saber[1].name, pState->saber[1].blade[0].active, pState->saber[1].blade[1].active, pState->saber[1].blade[2].active, + pState->saber[1].blade[3].active, pState->saber[1].blade[4].active, pState->saber[1].blade[5].active, pState->saber[1].blade[6].active, + pState->saber[1].blade[7].active, pState->saber[1].blade[0].color, pState->saber[1].blade[1].color, pState->saber[1].blade[2].color, + pState->saber[1].blade[3].color, pState->saber[1].blade[4].color, pState->saber[1].blade[5].color, pState->saber[1].blade[6].color, + pState->saber[1].blade[7].color, + // general saber data + pState->saberStylesKnown, pState->saberAnimLevel, pState->saberLockEnemy, pState->saberLockTime); #endif - Cvar_Set( sCVARNAME_PLAYERSAVE, s ); + Cvar_Set(sCVARNAME_PLAYERSAVE, s); - //ammo + // ammo s2 = ""; - for (i=0;i< AMMO_MAX; i++) - { - s2 = va("%s %i",s2, pState->ammo[i]); + for (i = 0; i < AMMO_MAX; i++) { + s2 = va("%s %i", s2, pState->ammo[i]); } - Cvar_Set( "playerammo", s2 ); + Cvar_Set("playerammo", s2); - //inventory + // inventory s2 = ""; - for (i=0;i< INV_MAX; i++) - { - s2 = va("%s %i",s2, pState->inventory[i]); + for (i = 0; i < INV_MAX; i++) { + s2 = va("%s %i", s2, pState->inventory[i]); } - Cvar_Set( "playerinv", s2 ); + Cvar_Set("playerinv", s2); // the new JK2 stuff - force powers, etc... // s2 = ""; - for (i=0;i< NUM_FORCE_POWERS; i++) - { - s2 = va("%s %i",s2, pState->forcePowerLevel[i]); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + s2 = va("%s %i", s2, pState->forcePowerLevel[i]); } - Cvar_Set( "playerfplvl", s2 ); + Cvar_Set("playerfplvl", s2); } } - // Restart the server on a different map // -static void SV_MapTransition_f(void) -{ - const char *spawntarget; +static void SV_MapTransition_f(void) { + const char *spawntarget; #ifdef JK2_MODE SCR_PrecacheScreenshot(); @@ -233,16 +165,13 @@ static void SV_MapTransition_f(void) SV_Player_EndOfLevelSave(); spawntarget = Cmd_Argv(2); - if ( *spawntarget != '\0' ) - { - Cvar_Set( "spawntarget", spawntarget ); - } - else - { - Cvar_Set( "spawntarget", "" ); + if (*spawntarget != '\0') { + Cvar_Set("spawntarget", spawntarget); + } else { + Cvar_Set("spawntarget", ""); } - SV_Map_( eForceReload_NOTHING ); + SV_Map_(eForceReload_NOTHING); } /* @@ -256,42 +185,40 @@ player weapons/ammo/etc from the previous level that you haven't really exited ( #ifdef JK2_MODE extern void SCR_UnprecacheScreenshot(); #endif -static void SV_Map_f( void ) -{ - Cvar_Set( sCVARNAME_PLAYERSAVE, ""); - Cvar_Set( "spawntarget", "" ); +static void SV_Map_f(void) { + Cvar_Set(sCVARNAME_PLAYERSAVE, ""); + Cvar_Set("spawntarget", ""); Cvar_Set("tier_storyinfo", "0"); Cvar_Set("tiers_complete", ""); #ifdef JK2_MODE SCR_UnprecacheScreenshot(); #endif - ForceReload_e eForceReload = eForceReload_NOTHING; // default for normal load + ForceReload_e eForceReload = eForceReload_NOTHING; // default for normal load - char *cmd = Cmd_Argv( 0 ); - if ( !Q_stricmp( cmd, "devmapbsp") ) + char *cmd = Cmd_Argv(0); + if (!Q_stricmp(cmd, "devmapbsp")) eForceReload = eForceReload_BSP; - else if ( !Q_stricmp( cmd, "devmapmdl") ) + else if (!Q_stricmp(cmd, "devmapmdl")) eForceReload = eForceReload_MODELS; - else if ( !Q_stricmp( cmd, "devmapall") ) + else if (!Q_stricmp(cmd, "devmapall")) eForceReload = eForceReload_ALL; - qboolean cheat = (qboolean)(!Q_stricmpn( cmd, "devmap", 6 ) ); + qboolean cheat = (qboolean)(!Q_stricmpn(cmd, "devmap", 6)); // retain old cheat state - if ( !cheat && Cvar_VariableIntegerValue( "helpUsObi" ) ) + if (!cheat && Cvar_VariableIntegerValue("helpUsObi")) cheat = qtrue; - if (SV_Map_( eForceReload )) - { + if (SV_Map_(eForceReload)) { // set the cheat value // if the level was started with "map ", then // cheats will not be allowed. If started with "devmap " // then cheats will be allowed - Cvar_Set( "helpUsObi", cheat ? "1" : "0" ); + Cvar_Set("helpUsObi", cheat ? "1" : "0"); } #ifdef JK2_MODE - Cvar_Set( "cg_missionstatusscreen", "0" ); + Cvar_Set("cg_missionstatusscreen", "0"); #endif } @@ -300,13 +227,12 @@ static void SV_Map_f( void ) SV_LoadTransition_f ================== */ -void SV_LoadTransition_f(void) -{ - const char *map; - const char *spawntarget; +void SV_LoadTransition_f(void) { + const char *map; + const char *spawntarget; map = Cmd_Argv(1); - if ( !*map ) { + if (!*map) { return; } @@ -317,38 +243,34 @@ void SV_LoadTransition_f(void) #endif SV_Player_EndOfLevelSave(); - //Save the full current state of the current map so we can return to it later - SG_WriteSavegame( va("hub/%s", sv_mapname->string), qfalse ); + // Save the full current state of the current map so we can return to it later + SG_WriteSavegame(va("hub/%s", sv_mapname->string), qfalse); - //set the spawntarget if there is one + // set the spawntarget if there is one spawntarget = Cmd_Argv(2); - if ( *spawntarget != '\0' ) - { - Cvar_Set( "spawntarget", spawntarget ); - } - else - { - Cvar_Set( "spawntarget", "" ); + if (*spawntarget != '\0') { + Cvar_Set("spawntarget", spawntarget); + } else { + Cvar_Set("spawntarget", ""); } - if ( !SV_TryLoadTransition( map ) ) - {//couldn't load a savegame - SV_Map_( eForceReload_NOTHING ); + if (!SV_TryLoadTransition(map)) { // couldn't load a savegame + SV_Map_(eForceReload_NOTHING); } qbLoadTransition = qfalse; } //=============================================================== -char *ivtos( const vec3_t v ) { - static int index; - static char str[8][32]; - char *s; +char *ivtos(const vec3_t v) { + static int index; + static char str[8][32]; + char *s; // use an array so that multiple vtos won't collide s = str[index]; - index = (index + 1)&7; + index = (index + 1) & 7; - Com_sprintf (s, 32, "( %i %i %i )", (int)v[0], (int)v[1], (int)v[2]); + Com_sprintf(s, 32, "( %i %i %i )", (int)v[0], (int)v[1], (int)v[2]); return s; } @@ -358,18 +280,18 @@ char *ivtos( const vec3_t v ) { SV_Status_f ================ */ -static void SV_Status_f( void ) { - client_t *cl; +static void SV_Status_f(void) { + client_t *cl; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } cl = &svs.clients[0]; - if ( !cl ) { + if (!cl) { Com_Printf("Server is not running.\n"); return; } @@ -384,15 +306,15 @@ static void SV_Status_f( void ) { #define STATUS_OS "Unknown" #endif - Com_Printf( "name : %s^7\n", cl->name ); - Com_Printf( "score : %i\n", cl->gentity->client->persistant[PERS_SCORE] ); - Com_Printf( "version : %s %s %i\n", STATUS_OS, VERSION_STRING_DOTTED, PROTOCOL_VERSION ); + Com_Printf("name : %s^7\n", cl->name); + Com_Printf("score : %i\n", cl->gentity->client->persistant[PERS_SCORE]); + Com_Printf("version : %s %s %i\n", STATUS_OS, VERSION_STRING_DOTTED, PROTOCOL_VERSION); #ifdef JK2_MODE - Com_Printf( "game : Jedi Outcast %s\n", FS_GetCurrentGameDir() ); + Com_Printf("game : Jedi Outcast %s\n", FS_GetCurrentGameDir()); #else - Com_Printf( "game : Jedi Academy %s\n", FS_GetCurrentGameDir() ); + Com_Printf("game : Jedi Academy %s\n", FS_GetCurrentGameDir()); #endif - Com_Printf( "map : %s at %s\n", sv_mapname->string, ivtos( cl->gentity->client->origin ) ); + Com_Printf("map : %s at %s\n", sv_mapname->string, ivtos(cl->gentity->client->origin)); } /* @@ -402,12 +324,11 @@ SV_Serverinfo_f Examine the serverinfo string =========== */ -static void SV_Serverinfo_f( void ) { - Com_Printf ("Server info settings:\n"); - Info_Print ( Cvar_InfoString( CVAR_SERVERINFO ) ); +static void SV_Serverinfo_f(void) { + Com_Printf("Server info settings:\n"); + Info_Print(Cvar_InfoString(CVAR_SERVERINFO)); } - /* =========== SV_Systeminfo_f @@ -415,12 +336,11 @@ SV_Systeminfo_f Examine or change the serverinfo string =========== */ -static void SV_Systeminfo_f( void ) { - Com_Printf ("System info settings:\n"); - Info_Print ( Cvar_InfoString( CVAR_SYSTEMINFO ) ); +static void SV_Systeminfo_f(void) { + Com_Printf("System info settings:\n"); + Info_Print(Cvar_InfoString(CVAR_SYSTEMINFO)); } - /* =========== SV_DumpUser_f @@ -428,29 +348,29 @@ SV_DumpUser_f Examine all a users info strings FIXME: move to game =========== */ -static void SV_DumpUser_f( void ) { - client_t *cl; +static void SV_DumpUser_f(void) { + client_t *cl; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 1 ) { - Com_Printf ("Usage: info\n"); + if (Cmd_Argc() != 1) { + Com_Printf("Usage: info\n"); return; } cl = &svs.clients[0]; - if ( !cl->state ) { + if (!cl->state) { Com_Printf("Client is not active\n"); return; } - Com_Printf( "userinfo\n" ); - Com_Printf( "--------\n" ); - Info_Print( cl->userinfo ); + Com_Printf("userinfo\n"); + Com_Printf("--------\n"); + Info_Print(cl->userinfo); } //=========================================================== @@ -460,9 +380,9 @@ static void SV_DumpUser_f( void ) { SV_CompleteMapName ================== */ -static void SV_CompleteMapName( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "maps", "bsp", qtrue, qfalse ); +static void SV_CompleteMapName(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("maps", "bsp", qtrue, qfalse); } /* @@ -470,9 +390,9 @@ static void SV_CompleteMapName( char *args, int argNum ) { SV_CompleteMapName ================== */ -static void SV_CompleteSaveName( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "saves", "sav", qtrue, qtrue ); +static void SV_CompleteSaveName(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("saves", "sav", qtrue, qtrue); } /* @@ -480,42 +400,42 @@ static void SV_CompleteSaveName( char *args, int argNum ) { SV_AddOperatorCommands ================== */ -void SV_AddOperatorCommands( void ) { - static qboolean initialized; +void SV_AddOperatorCommands(void) { + static qboolean initialized; - if ( initialized ) { + if (initialized) { return; } initialized = qtrue; - Cmd_AddCommand ("status", SV_Status_f); - Cmd_AddCommand ("serverinfo", SV_Serverinfo_f); - Cmd_AddCommand ("systeminfo", SV_Systeminfo_f); - Cmd_AddCommand ("dumpuser", SV_DumpUser_f); - Cmd_AddCommand ("sectorlist", SV_SectorList_f); - Cmd_AddCommand ("map", SV_Map_f); - Cmd_SetCommandCompletionFunc( "map", SV_CompleteMapName ); - Cmd_AddCommand ("devmap", SV_Map_f); - Cmd_SetCommandCompletionFunc( "devmap", SV_CompleteMapName ); - Cmd_AddCommand ("devmapbsp", SV_Map_f); - Cmd_SetCommandCompletionFunc( "devmapbsp", SV_CompleteMapName ); - Cmd_AddCommand ("devmapmdl", SV_Map_f); - Cmd_SetCommandCompletionFunc( "devmapmdl", SV_CompleteMapName ); - Cmd_AddCommand ("devmapsnd", SV_Map_f); - Cmd_SetCommandCompletionFunc( "devmapsnd", SV_CompleteMapName ); - Cmd_AddCommand ("devmapall", SV_Map_f); - Cmd_SetCommandCompletionFunc( "devmapall", SV_CompleteMapName ); - Cmd_AddCommand ("maptransition", SV_MapTransition_f); - Cmd_AddCommand ("load", SV_LoadGame_f); - Cmd_SetCommandCompletionFunc( "load", SV_CompleteSaveName ); - Cmd_AddCommand ("loadtransition", SV_LoadTransition_f); - Cmd_AddCommand ("save", SV_SaveGame_f); - Cmd_AddCommand ("wipe", SV_WipeGame_f); - -//#ifdef _DEBUG -// extern void UI_Dump_f(void); -// Cmd_AddCommand ("ui_dump", UI_Dump_f); -//#endif + Cmd_AddCommand("status", SV_Status_f); + Cmd_AddCommand("serverinfo", SV_Serverinfo_f); + Cmd_AddCommand("systeminfo", SV_Systeminfo_f); + Cmd_AddCommand("dumpuser", SV_DumpUser_f); + Cmd_AddCommand("sectorlist", SV_SectorList_f); + Cmd_AddCommand("map", SV_Map_f); + Cmd_SetCommandCompletionFunc("map", SV_CompleteMapName); + Cmd_AddCommand("devmap", SV_Map_f); + Cmd_SetCommandCompletionFunc("devmap", SV_CompleteMapName); + Cmd_AddCommand("devmapbsp", SV_Map_f); + Cmd_SetCommandCompletionFunc("devmapbsp", SV_CompleteMapName); + Cmd_AddCommand("devmapmdl", SV_Map_f); + Cmd_SetCommandCompletionFunc("devmapmdl", SV_CompleteMapName); + Cmd_AddCommand("devmapsnd", SV_Map_f); + Cmd_SetCommandCompletionFunc("devmapsnd", SV_CompleteMapName); + Cmd_AddCommand("devmapall", SV_Map_f); + Cmd_SetCommandCompletionFunc("devmapall", SV_CompleteMapName); + Cmd_AddCommand("maptransition", SV_MapTransition_f); + Cmd_AddCommand("load", SV_LoadGame_f); + Cmd_SetCommandCompletionFunc("load", SV_CompleteSaveName); + Cmd_AddCommand("loadtransition", SV_LoadTransition_f); + Cmd_AddCommand("save", SV_SaveGame_f); + Cmd_AddCommand("wipe", SV_WipeGame_f); + + //#ifdef _DEBUG + // extern void UI_Dump_f(void); + // Cmd_AddCommand ("ui_dump", UI_Dump_f); + //#endif } /* @@ -523,7 +443,7 @@ void SV_AddOperatorCommands( void ) { SV_RemoveOperatorCommands ================== */ -void SV_RemoveOperatorCommands( void ) { +void SV_RemoveOperatorCommands(void) { #if 0 // removing these won't let the server start again Cmd_RemoveCommand ("status"); @@ -535,4 +455,3 @@ void SV_RemoveOperatorCommands( void ) { Cmd_RemoveCommand ("sectorlist"); #endif } - diff --git a/code/server/sv_client.cpp b/code/server/sv_client.cpp index 8e948c0758..230935fb45 100644 --- a/code/server/sv_client.cpp +++ b/code/server/sv_client.cpp @@ -34,70 +34,63 @@ SV_DirectConnect A "connect" OOB command has been received ================== */ -void SV_DirectConnect( netadr_t from ) { - char userinfo[MAX_INFO_STRING]; - int i; - client_t *cl, *newcl; - client_t temp; - gentity_t *ent; - int clientNum; - int version; - int qport; - //int challenge; - char *denied; - - Com_DPrintf ("SVC_DirectConnect ()\n"); - - Q_strncpyz( userinfo, Cmd_Argv(1), sizeof(userinfo) ); - - version = atoi( Info_ValueForKey( userinfo, "protocol" ) ); - if ( version != PROTOCOL_VERSION ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\nServer uses protocol version %i.\n", PROTOCOL_VERSION ); - Com_DPrintf (" rejected connect from version %i\n", version); +void SV_DirectConnect(netadr_t from) { + char userinfo[MAX_INFO_STRING]; + int i; + client_t *cl, *newcl; + client_t temp; + gentity_t *ent; + int clientNum; + int version; + int qport; + // int challenge; + char *denied; + + Com_DPrintf("SVC_DirectConnect ()\n"); + + Q_strncpyz(userinfo, Cmd_Argv(1), sizeof(userinfo)); + + version = atoi(Info_ValueForKey(userinfo, "protocol")); + if (version != PROTOCOL_VERSION) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nServer uses protocol version %i.\n", PROTOCOL_VERSION); + Com_DPrintf(" rejected connect from version %i\n", version); return; } - qport = atoi( Info_ValueForKey( userinfo, "qport" ) ); + qport = atoi(Info_ValueForKey(userinfo, "qport")); - //challenge = atoi( Info_ValueForKey( userinfo, "challenge" ) ); + // challenge = atoi( Info_ValueForKey( userinfo, "challenge" ) ); // see if the challenge is valid (local clients don't need to challenge) - if ( !NET_IsLocalAddress (from) ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\nNo challenge for address.\n" ); + if (!NET_IsLocalAddress(from)) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nNo challenge for address.\n"); return; } else { // force the "ip" info key to "localhost" - Info_SetValueForKey( userinfo, "ip", "localhost" ); + Info_SetValueForKey(userinfo, "ip", "localhost"); } newcl = &temp; - memset (newcl, 0, sizeof(client_t)); + memset(newcl, 0, sizeof(client_t)); // if there is already a slot for this ip, reuse it - for (i=0,cl=svs.clients ; i < 1 ; i++,cl++) - { - if ( cl->state == CS_FREE ) { + for (i = 0, cl = svs.clients; i < 1; i++, cl++) { + if (cl->state == CS_FREE) { continue; } - if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) - && ( cl->netchan.qport == qport - || from.port == cl->netchan.remoteAddress.port ) ) - { - if (( sv.time - cl->lastConnectTime) - < (sv_reconnectlimit->integer * 1000)) - { - Com_DPrintf ("%s:reconnect rejected : too soon\n", NET_AdrToString (from)); + if (NET_CompareBaseAdr(from, cl->netchan.remoteAddress) && (cl->netchan.qport == qport || from.port == cl->netchan.remoteAddress.port)) { + if ((sv.time - cl->lastConnectTime) < (sv_reconnectlimit->integer * 1000)) { + Com_DPrintf("%s:reconnect rejected : too soon\n", NET_AdrToString(from)); return; } - Com_Printf ("%s:reconnect\n", NET_AdrToString (from)); + Com_Printf("%s:reconnect\n", NET_AdrToString(from)); newcl = cl; goto gotnewcl; } } - newcl = NULL; - for ( i = 0; i < 1 ; i++ ) { + for (i = 0; i < 1; i++) { cl = &svs.clients[i]; if (cl->state == CS_FREE) { newcl = cl; @@ -105,9 +98,9 @@ void SV_DirectConnect( netadr_t from ) { } } - if ( !newcl ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\nServer is full.\n" ); - Com_DPrintf ("Rejected a connection.\n"); + if (!newcl) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nServer is full.\n"); + Com_DPrintf("Rejected a connection.\n"); return; } @@ -117,27 +110,27 @@ void SV_DirectConnect( netadr_t from ) { // this is the only place a client_t is ever initialized *newcl = temp; clientNum = newcl - svs.clients; - ent = SV_GentityNum( clientNum ); + ent = SV_GentityNum(clientNum); newcl->gentity = ent; // save the address - Netchan_Setup (NS_SERVER, &newcl->netchan , from, qport); + Netchan_Setup(NS_SERVER, &newcl->netchan, from, qport); // save the userinfo - Q_strncpyz( newcl->userinfo, userinfo, sizeof(newcl->userinfo) ); + Q_strncpyz(newcl->userinfo, userinfo, sizeof(newcl->userinfo)); // get the game a chance to reject this connection or modify the userinfo - denied = ge->ClientConnect( clientNum, qtrue, eSavedGameJustLoaded ); // firstTime = qtrue - if ( denied ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\n%s\n", denied ); - Com_DPrintf ("Game rejected a connection: %s.\n", denied); + denied = ge->ClientConnect(clientNum, qtrue, eSavedGameJustLoaded); // firstTime = qtrue + if (denied) { + NET_OutOfBandPrint(NS_SERVER, from, "print\n%s\n", denied); + Com_DPrintf("Game rejected a connection: %s.\n", denied); return; } - SV_UserinfoChanged( newcl ); + SV_UserinfoChanged(newcl); // send the connect packet to the client - NET_OutOfBandPrint( NS_SERVER, from, "connectResponse" ); + NET_OutOfBandPrint(NS_SERVER, from, "connectResponse"); newcl->state = CS_CONNECTED; newcl->lastPacketTime = sv.time; @@ -149,7 +142,6 @@ void SV_DirectConnect( netadr_t from ) { newcl->gamestateMessageNum = -1; } - /* ===================== SV_DropClient @@ -159,26 +151,26 @@ or unwillingly. This is NOT called if the entire server is quiting or crashing -- SV_FinalMessage() will handle that ===================== */ -void SV_DropClient( client_t *drop, const char *reason ) { - if ( drop->state == CS_ZOMBIE ) { - return; // already dropped +void SV_DropClient(client_t *drop, const char *reason) { + if (drop->state == CS_ZOMBIE) { + return; // already dropped } - drop->state = CS_ZOMBIE; // become free in a few seconds + drop->state = CS_ZOMBIE; // become free in a few seconds - if (drop->download) { - FS_FreeFile (drop->download); + if (drop->download) { + FS_FreeFile(drop->download); drop->download = NULL; } // call the prog function for removing a client // this will remove the body, among other things - ge->ClientDisconnect( drop - svs.clients ); + ge->ClientDisconnect(drop - svs.clients); // tell everyone why they got dropped - SV_SendServerCommand( NULL, "print \"%s %s\n\"", drop->name, reason ); + SV_SendServerCommand(NULL, "print \"%s %s\n\"", drop->name, reason); // add the disconnect command - SV_SendServerCommand( drop, "disconnect" ); + SV_SendServerCommand(drop, "disconnect"); } /* @@ -192,12 +184,12 @@ It will be resent if the client acknowledges a later message but has the wrong gamestate. ================ */ -void SV_SendClientGameState( client_t *client ) { - int start; - msg_t msg; - byte msgBuffer[MAX_MSGLEN]; +void SV_SendClientGameState(client_t *client) { + int start; + msg_t msg; + byte msgBuffer[MAX_MSGLEN]; - Com_DPrintf ("SV_SendGameState() for %s\n", client->name); + Com_DPrintf("SV_SendGameState() for %s\n", client->name); client->state = CS_PRIMED; // when we receive the first packet from the client, we will @@ -209,48 +201,47 @@ void SV_SendClientGameState( client_t *client ) { client->reliableSequence = 0; client->reliableAcknowledge = 0; - MSG_Init( &msg, msgBuffer, sizeof( msgBuffer ) ); + MSG_Init(&msg, msgBuffer, sizeof(msgBuffer)); // send the gamestate - MSG_WriteByte( &msg, svc_gamestate ); - MSG_WriteLong( &msg, client->reliableSequence ); + MSG_WriteByte(&msg, svc_gamestate); + MSG_WriteLong(&msg, client->reliableSequence); // write the configstrings - for ( start = 0 ; start < MAX_CONFIGSTRINGS ; start++ ) { + for (start = 0; start < MAX_CONFIGSTRINGS; start++) { if (sv.configstrings[start][0]) { - MSG_WriteByte( &msg, svc_configstring ); - MSG_WriteShort( &msg, start ); - MSG_WriteString( &msg, sv.configstrings[start] ); + MSG_WriteByte(&msg, svc_configstring); + MSG_WriteShort(&msg, start); + MSG_WriteString(&msg, sv.configstrings[start]); } } - MSG_WriteByte( &msg, 0 ); + MSG_WriteByte(&msg, 0); // check for overflow - if ( msg.overflowed ) { - Com_Printf ("WARNING: GameState overflowed for %s\n", client->name); + if (msg.overflowed) { + Com_Printf("WARNING: GameState overflowed for %s\n", client->name); } // deliver this to the client - SV_SendMessageToClient( &msg, client ); + SV_SendMessageToClient(&msg, client); } - /* ================== SV_ClientEnterWorld ================== */ -void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded ) { - int clientNum; - gentity_t *ent; +void SV_ClientEnterWorld(client_t *client, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded) { + int clientNum; + gentity_t *ent; - Com_DPrintf ("SV_ClientEnterWorld() from %s\n", client->name); + Com_DPrintf("SV_ClientEnterWorld() from %s\n", client->name); client->state = CS_ACTIVE; // set up the entity for the client clientNum = client - svs.clients; - ent = SV_GentityNum( clientNum ); + ent = SV_GentityNum(clientNum); ent->s.number = clientNum; client->gentity = ent; @@ -262,7 +253,7 @@ void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd, SavedGameJustLoaded_ client->cmdNum = 0; // call the game begin function - ge->ClientBegin( client - svs.clients, cmd, eSavedGameJustLoaded ); + ge->ClientBegin(client - svs.clients, cmd, eSavedGameJustLoaded); } /* @@ -273,7 +264,6 @@ CLIENT COMMAND EXECUTION ============================================================ */ - /* ================= SV_Disconnect_f @@ -281,11 +271,7 @@ SV_Disconnect_f The client is going to disconnect, so remove the connection immediately FIXME: move to game? ================= */ -static void SV_Disconnect_f( client_t *cl ) { - SV_DropClient( cl, "disconnected" ); -} - - +static void SV_Disconnect_f(client_t *cl) { SV_DropClient(cl, "disconnected"); } /* ================= @@ -294,109 +280,101 @@ SV_UserinfoChanged Pull specific info from a newly changed userinfo string into a more C friendly form. ================= */ -void SV_UserinfoChanged( client_t *cl ) { - Q_strncpyz( cl->name, Info_ValueForKey( cl->userinfo, "name" ), sizeof( cl->name ) ); -} - +void SV_UserinfoChanged(client_t *cl) { Q_strncpyz(cl->name, Info_ValueForKey(cl->userinfo, "name"), sizeof(cl->name)); } /* ================== SV_UpdateUserinfo_f ================== */ -static void SV_UpdateUserinfo_f( client_t *cl ) { - Q_strncpyz( cl->userinfo, Cmd_Argv(1), sizeof(cl->userinfo) ); +static void SV_UpdateUserinfo_f(client_t *cl) { + Q_strncpyz(cl->userinfo, Cmd_Argv(1), sizeof(cl->userinfo)); - SV_UserinfoChanged( cl ); + SV_UserinfoChanged(cl); // call prog code to allow overrides - ge->ClientUserinfoChanged( cl - svs.clients ); + ge->ClientUserinfoChanged(cl - svs.clients); } typedef struct { - const char *name; - void (*func)( client_t *cl ); + const char *name; + void (*func)(client_t *cl); } ucmd_t; -static ucmd_t ucmds[] = { - {"userinfo", SV_UpdateUserinfo_f}, - {"disconnect", SV_Disconnect_f}, +static ucmd_t ucmds[] = {{"userinfo", SV_UpdateUserinfo_f}, + {"disconnect", SV_Disconnect_f}, - {NULL, NULL} -}; + {NULL, NULL}}; /* ================== SV_ExecuteClientCommand ================== */ -void SV_ExecuteClientCommand( client_t *cl, const char *s ) { - ucmd_t *u; +void SV_ExecuteClientCommand(client_t *cl, const char *s) { + ucmd_t *u; - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); // see if it is a server level command - for (u=ucmds ; u->name ; u++) { - if (!strcmp (Cmd_Argv(0), u->name) ) { - u->func( cl ); + for (u = ucmds; u->name; u++) { + if (!strcmp(Cmd_Argv(0), u->name)) { + u->func(cl); break; } } // pass unknown strings to the game if (!u->name && sv.state == SS_GAME) { - ge->ClientCommand( cl - svs.clients ); + ge->ClientCommand(cl - svs.clients); } } -#define MAX_STRINGCMDS 8 +#define MAX_STRINGCMDS 8 /* =============== SV_ClientCommand =============== */ -static void SV_ClientCommand( client_t *cl, msg_t *msg ) { - int seq; - const char *s; +static void SV_ClientCommand(client_t *cl, msg_t *msg) { + int seq; + const char *s; - seq = MSG_ReadLong( msg ); - s = MSG_ReadString( msg ); + seq = MSG_ReadLong(msg); + s = MSG_ReadString(msg); // see if we have already executed it - if ( cl->lastClientCommand >= seq ) { + if (cl->lastClientCommand >= seq) { return; } - Com_DPrintf( "clientCommand: %s : %i : %s\n", cl->name, seq, s ); + Com_DPrintf("clientCommand: %s : %i : %s\n", cl->name, seq, s); // drop the connection if we have somehow lost commands - if ( seq > cl->lastClientCommand + 1 ) { - Com_Printf( "Client %s lost %i clientCommands\n", cl->name, - seq - cl->lastClientCommand + 1 ); + if (seq > cl->lastClientCommand + 1) { + Com_Printf("Client %s lost %i clientCommands\n", cl->name, seq - cl->lastClientCommand + 1); } - SV_ExecuteClientCommand( cl, s ); + SV_ExecuteClientCommand(cl, s); cl->lastClientCommand = seq; } - //================================================================================== - /* ================== SV_ClientThink ================== */ -void SV_ClientThink (client_t *cl, usercmd_t *cmd) { +void SV_ClientThink(client_t *cl, usercmd_t *cmd) { cl->lastUsercmd = *cmd; - if ( cl->state != CS_ACTIVE ) { - return; // may have been kicked during the last usercmd + if (cl->state != CS_ACTIVE) { + return; // may have been kicked during the last usercmd } - ge->ClientThink( cl - svs.clients, cmd ); + ge->ClientThink(cl - svs.clients, cmd); } /* @@ -411,119 +389,110 @@ On very fast clients, there may be multiple usercmd packed into each of the backup packets. ================== */ -static void SV_UserMove( client_t *cl, msg_t *msg ) { - int i, start; - int cmdNum; - int firstNum; - int cmdCount; - usercmd_t nullcmd; - usercmd_t cmds[MAX_PACKET_USERCMDS]; - usercmd_t *cmd, *oldcmd; - //int clientTime; - int serverId; - - cl->reliableAcknowledge = MSG_ReadLong( msg ); - serverId = MSG_ReadLong( msg ); - /*clientTime = */MSG_ReadLong( msg ); - cl->deltaMessage = MSG_ReadLong( msg ); +static void SV_UserMove(client_t *cl, msg_t *msg) { + int i, start; + int cmdNum; + int firstNum; + int cmdCount; + usercmd_t nullcmd; + usercmd_t cmds[MAX_PACKET_USERCMDS]; + usercmd_t *cmd, *oldcmd; + // int clientTime; + int serverId; + + cl->reliableAcknowledge = MSG_ReadLong(msg); + serverId = MSG_ReadLong(msg); + /*clientTime = */ MSG_ReadLong(msg); + cl->deltaMessage = MSG_ReadLong(msg); // cmdNum is the command number of the most recent included usercmd - cmdNum = MSG_ReadLong( msg ); - cmdCount = MSG_ReadByte( msg ); + cmdNum = MSG_ReadLong(msg); + cmdCount = MSG_ReadByte(msg); - if ( cmdCount < 1 ) { - Com_Printf( "cmdCount < 1\n" ); + if (cmdCount < 1) { + Com_Printf("cmdCount < 1\n"); return; } - if ( cmdCount > MAX_PACKET_USERCMDS ) { - Com_Printf( "cmdCount > MAX_PACKET_USERCMDS\n" ); + if (cmdCount > MAX_PACKET_USERCMDS) { + Com_Printf("cmdCount > MAX_PACKET_USERCMDS\n"); return; } - memset( &nullcmd, 0, sizeof(nullcmd) ); + memset(&nullcmd, 0, sizeof(nullcmd)); oldcmd = &nullcmd; - for ( i = 0 ; i < cmdCount ; i++ ) { + for (i = 0; i < cmdCount; i++) { cmd = &cmds[i]; - MSG_ReadDeltaUsercmd( msg, oldcmd, cmd ); + MSG_ReadDeltaUsercmd(msg, oldcmd, cmd); oldcmd = cmd; } // if this is a usercmd from a previous gamestate, // ignore it or retransmit the current gamestate - if ( serverId != sv.serverId ) { + if (serverId != sv.serverId) { // if we can tell that the client has dropped the last // gamestate we sent them, resend it - if ( cl->netchan.incomingAcknowledged > cl->gamestateMessageNum ) { - Com_DPrintf( "%s : dropped gamestate, resending\n", cl->name ); - SV_SendClientGameState( cl ); + if (cl->netchan.incomingAcknowledged > cl->gamestateMessageNum) { + Com_DPrintf("%s : dropped gamestate, resending\n", cl->name); + SV_SendClientGameState(cl); } return; } // if this is the first usercmd we have received // this gamestate, put the client into the world - if ( cl->state == CS_PRIMED ) { + if (cl->state == CS_PRIMED) { - SV_ClientEnterWorld( cl, &cmds[0], eSavedGameJustLoaded ); - if ( sv_mapname->string[0]!='_' ) - { + SV_ClientEnterWorld(cl, &cmds[0], eSavedGameJustLoaded); + if (sv_mapname->string[0] != '_') { char savename[MAX_QPATH]; - if ( eSavedGameJustLoaded == eNO ) - { - SG_WriteSavegame("auto",qtrue); - if ( Q_stricmpn(sv_mapname->string, "academy", 7) != 0) - { - Com_sprintf (savename, sizeof(savename), "auto_%s",sv_mapname->string); - SG_WriteSavegame(savename,qtrue);//can't use va becuase it's nested + if (eSavedGameJustLoaded == eNO) { + SG_WriteSavegame("auto", qtrue); + if (Q_stricmpn(sv_mapname->string, "academy", 7) != 0) { + Com_sprintf(savename, sizeof(savename), "auto_%s", sv_mapname->string); + SG_WriteSavegame(savename, qtrue); // can't use va becuase it's nested } - } - else if ( qbLoadTransition == qtrue ) - { - Com_sprintf (savename, sizeof(savename), "hub/%s", sv_mapname->string ); - SG_WriteSavegame( savename, qfalse );//save a full one - SG_WriteSavegame( "auto", qfalse );//need a copy for auto, too + } else if (qbLoadTransition == qtrue) { + Com_sprintf(savename, sizeof(savename), "hub/%s", sv_mapname->string); + SG_WriteSavegame(savename, qfalse); // save a full one + SG_WriteSavegame("auto", qfalse); // need a copy for auto, too } } eSavedGameJustLoaded = eNO; // the moves can be processed normaly } - if ( cl->state != CS_ACTIVE ) { + if (cl->state != CS_ACTIVE) { cl->deltaMessage = -1; return; } - // if there is a time gap from the last packet to this packet, // fill in with the first command in the packet // with a packetdup of 0, firstNum == cmdNum - firstNum = cmdNum - ( cmdCount - 1 ); - if ( cl->cmdNum < firstNum - 1 ) { + firstNum = cmdNum - (cmdCount - 1); + if (cl->cmdNum < firstNum - 1) { cl->droppedCommands = qtrue; - if ( sv_showloss->integer ) { - Com_Printf("Lost %i usercmds from %s\n", firstNum - 1 - cl->cmdNum, - cl->name); + if (sv_showloss->integer) { + Com_Printf("Lost %i usercmds from %s\n", firstNum - 1 - cl->cmdNum, cl->name); } - if ( cl->cmdNum < firstNum - 6 ) { - cl->cmdNum = firstNum - 6; // don't generate too many + if (cl->cmdNum < firstNum - 6) { + cl->cmdNum = firstNum - 6; // don't generate too many } - while ( cl->cmdNum < firstNum - 1 ) { + while (cl->cmdNum < firstNum - 1) { cl->cmdNum++; - SV_ClientThink( cl, &cmds[0] ); + SV_ClientThink(cl, &cmds[0]); } } // skip over any usercmd_t we have already executed - start = cl->cmdNum - ( firstNum - 1 ); - for ( i = start ; i < cmdCount ; i++ ) { - SV_ClientThink (cl, &cmds[ i ]); + start = cl->cmdNum - (firstNum - 1); + for (i = start; i < cmdCount; i++) { + SV_ClientThink(cl, &cmds[i]); } cl->cmdNum = cmdNum; - } - /* =========================================================================== @@ -539,55 +508,53 @@ SV_ExecuteClientMessage Parse a client packet =================== */ -void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) { - int c; +void SV_ExecuteClientMessage(client_t *cl, msg_t *msg) { + int c; - while( 1 ) { - if ( msg->readcount > msg->cursize ) { - SV_DropClient (cl, "had a badread"); + while (1) { + if (msg->readcount > msg->cursize) { + SV_DropClient(cl, "had a badread"); return; } - c = MSG_ReadByte( msg ); - if ( c == -1 ) { + c = MSG_ReadByte(msg); + if (c == -1) { break; } - switch( c ) { + switch (c) { default: - SV_DropClient( cl,"had an unknown command char" ); + SV_DropClient(cl, "had an unknown command char"); return; case clc_nop: break; case clc_move: - SV_UserMove( cl, msg ); + SV_UserMove(cl, msg); break; case clc_clientCommand: - SV_ClientCommand( cl, msg ); + SV_ClientCommand(cl, msg); if (cl->state == CS_ZOMBIE) { - return; // disconnect command + return; // disconnect command } break; } } } - -void SV_FreeClient(client_t *client) -{ +void SV_FreeClient(client_t *client) { int i; - if (!client) return; + if (!client) + return; - for(i=0; ireliableCommands[ i] ) { - Z_Free( client->reliableCommands[ i] ); + for (i = 0; i < MAX_RELIABLE_COMMANDS; i++) { + if (client->reliableCommands[i]) { + Z_Free(client->reliableCommands[i]); client->reliableCommands[i] = NULL; client->reliableSequence = 0; } } } - diff --git a/code/server/sv_game.cpp b/code/server/sv_game.cpp index 8cd596fbe7..91305003c5 100644 --- a/code/server/sv_game.cpp +++ b/code/server/sv_game.cpp @@ -37,7 +37,7 @@ along with this program; if not, see . Ghoul2 Insert Start */ #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif /* @@ -46,11 +46,11 @@ Ghoul2 Insert End static void *gameLibrary; -//prototypes -extern void Com_WriteCam ( const char *text ); +// prototypes +extern void Com_WriteCam(const char *text); extern void Com_FlushCamFile(); -extern int s_entityWavVol[MAX_GENTITIES]; +extern int s_entityWavVol[MAX_GENTITIES]; // these functions must be used instead of pointer arithmetic, because // the game allocates gentities with private information after the server shared part @@ -63,27 +63,27 @@ int SV_NumForGentity( gentity_t *ent ) { return num; } */ -gentity_t *SV_GentityNum( int num ) { - gentity_t *ent; +gentity_t *SV_GentityNum(int num) { + gentity_t *ent; - assert (num >=0); - ent = (gentity_t *)((byte *)ge->gentities + ge->gentitySize*(num)); + assert(num >= 0); + ent = (gentity_t *)((byte *)ge->gentities + ge->gentitySize * (num)); return ent; } -svEntity_t *SV_SvEntityForGentity( gentity_t *gEnt ) { - if ( !gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" ); +svEntity_t *SV_SvEntityForGentity(gentity_t *gEnt) { + if (!gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "SV_SvEntityForGentity: bad gEnt"); } - return &sv.svEntities[ gEnt->s.number ]; + return &sv.svEntities[gEnt->s.number]; } -gentity_t *SV_GEntityForSvEntity( svEntity_t *svEnt ) { - int num; +gentity_t *SV_GEntityForSvEntity(svEntity_t *svEnt) { + int num; num = svEnt - sv.svEntities; - return SV_GentityNum( num ); + return SV_GentityNum(num); } /* @@ -93,25 +93,24 @@ SV_GameSendServerCommand Sends a command string to a client =============== */ -void SV_GameSendServerCommand( int clientNum, const char *fmt, ... ) { - char msg[8192]; - va_list argptr; +void SV_GameSendServerCommand(int clientNum, const char *fmt, ...) { + char msg[8192]; + va_list argptr; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - if ( clientNum == -1 ) { - SV_SendServerCommand( NULL, "%s", msg ); + if (clientNum == -1) { + SV_SendServerCommand(NULL, "%s", msg); } else { - if ( clientNum < 0 || clientNum >= 1 ) { + if (clientNum < 0 || clientNum >= 1) { return; } - SV_SendServerCommand( svs.clients + clientNum, "%s", msg ); + SV_SendServerCommand(svs.clients + clientNum, "%s", msg); } } - /* =============== SV_GameDropClient @@ -119,14 +118,13 @@ SV_GameDropClient Disconnects the client with a message =============== */ -void SV_GameDropClient( int clientNum, const char *reason ) { - if ( clientNum < 0 || clientNum >= 1 ) { +void SV_GameDropClient(int clientNum, const char *reason) { + if (clientNum < 0 || clientNum >= 1) { return; } - SV_DropClient( svs.clients + clientNum, reason ); + SV_DropClient(svs.clients + clientNum, reason); } - /* ================= SV_SetBrushModel @@ -134,76 +132,62 @@ SV_SetBrushModel sets mins and maxs for inline bmodels ================= */ -void SV_SetBrushModel( gentity_t *ent, const char *name ) { - clipHandle_t h; - vec3_t mins, maxs; +void SV_SetBrushModel(gentity_t *ent, const char *name) { + clipHandle_t h; + vec3_t mins, maxs; - if (!name) - { - Com_Error( ERR_DROP, "SV_SetBrushModel: NULL model for ent number %d", ent->s.number ); + if (!name) { + Com_Error(ERR_DROP, "SV_SetBrushModel: NULL model for ent number %d", ent->s.number); } - if (name[0] == '*') - { - ent->s.modelindex = atoi( name + 1 ); + if (name[0] == '*') { + ent->s.modelindex = atoi(name + 1); - if (sv.mLocalSubBSPIndex != -1) - { + if (sv.mLocalSubBSPIndex != -1) { ent->s.modelindex += sv.mLocalSubBSPModelOffset; } - h = CM_InlineModel( ent->s.modelindex ); + h = CM_InlineModel(ent->s.modelindex); - if (sv.mLocalSubBSPIndex != -1) - { - CM_ModelBounds( SubBSP[sv.mLocalSubBSPIndex], h, mins, maxs ); - } - else - { - CM_ModelBounds( cmg, h, mins, maxs); + if (sv.mLocalSubBSPIndex != -1) { + CM_ModelBounds(SubBSP[sv.mLocalSubBSPIndex], h, mins, maxs); + } else { + CM_ModelBounds(cmg, h, mins, maxs); } - //CM_ModelBounds( h, mins, maxs ); + // CM_ModelBounds( h, mins, maxs ); - VectorCopy (mins, ent->mins); - VectorCopy (maxs, ent->maxs); + VectorCopy(mins, ent->mins); + VectorCopy(maxs, ent->maxs); ent->bmodel = qtrue; - ent->contents = CM_ModelContents( h, -1 ); - } - else if (name[0] == '#') - { + ent->contents = CM_ModelContents(h, -1); + } else if (name[0] == '#') { ent->s.modelindex = CM_LoadSubBSP(va("maps/%s.bsp", name + 1), qfalse); - CM_ModelBounds( SubBSP[CM_FindSubBSP(ent->s.modelindex)], ent->s.modelindex, mins, maxs ); + CM_ModelBounds(SubBSP[CM_FindSubBSP(ent->s.modelindex)], ent->s.modelindex, mins, maxs); - VectorCopy (mins, ent->mins); - VectorCopy (maxs, ent->maxs); + VectorCopy(mins, ent->mins); + VectorCopy(maxs, ent->maxs); ent->bmodel = qtrue; - //rwwNOTE: We don't ever want to set contents -1, it includes CONTENTS_LIGHTSABER. - //Lots of stuff will explode if there's a brush with CONTENTS_LIGHTSABER that isn't attached to a client owner. - //ent->contents = -1; // we don't know exactly what is in the brushes - h = CM_InlineModel( ent->s.modelindex ); - ent->contents = CM_ModelContents( h, CM_FindSubBSP(ent->s.modelindex) ); - // ent->contents = CONTENTS_SOLID; - } - else - { - Com_Error( ERR_DROP, "SV_SetBrushModel: %s isn't a brush model (ent %d)", name, ent->s.number ); + // rwwNOTE: We don't ever want to set contents -1, it includes CONTENTS_LIGHTSABER. + // Lots of stuff will explode if there's a brush with CONTENTS_LIGHTSABER that isn't attached to a client owner. + // ent->contents = -1; // we don't know exactly what is in the brushes + h = CM_InlineModel(ent->s.modelindex); + ent->contents = CM_ModelContents(h, CM_FindSubBSP(ent->s.modelindex)); + // ent->contents = CONTENTS_SOLID; + } else { + Com_Error(ERR_DROP, "SV_SetBrushModel: %s isn't a brush model (ent %d)", name, ent->s.number); } } -const char *SV_SetActiveSubBSP(int index) -{ - if (index >= 0) - { +const char *SV_SetActiveSubBSP(int index) { + if (index >= 0) { sv.mLocalSubBSPIndex = CM_FindSubBSP(index); sv.mLocalSubBSPModelOffset = index; - sv.mLocalSubBSPEntityParsePoint = CM_SubBSPEntityString (sv.mLocalSubBSPIndex); + sv.mLocalSubBSPEntityParsePoint = CM_SubBSPEntityString(sv.mLocalSubBSPIndex); return sv.mLocalSubBSPEntityParsePoint; - } - else - { + } else { sv.mLocalSubBSPIndex = -1; } @@ -217,46 +201,42 @@ SV_inPVS Also checks portalareas so that doors block sight ================= */ -qboolean SV_inPVS (const vec3_t p1, const vec3_t p2) -{ - int leafnum; - int cluster; - int area1, area2; - byte *mask; - int start=0; - - if ( com_speeds->integer ) { - start = Sys_Milliseconds (); +qboolean SV_inPVS(const vec3_t p1, const vec3_t p2) { + int leafnum; + int cluster; + int area1, area2; + byte *mask; + int start = 0; + + if (com_speeds->integer) { + start = Sys_Milliseconds(); } - leafnum = CM_PointLeafnum (p1); - cluster = CM_LeafCluster (leafnum); - area1 = CM_LeafArea (leafnum); - mask = CM_ClusterPVS (cluster); - - leafnum = CM_PointLeafnum (p2); - cluster = CM_LeafCluster (leafnum); - area2 = CM_LeafArea (leafnum); - if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) ) - { - if ( com_speeds->integer ) { - timeInPVSCheck += Sys_Milliseconds () - start; + leafnum = CM_PointLeafnum(p1); + cluster = CM_LeafCluster(leafnum); + area1 = CM_LeafArea(leafnum); + mask = CM_ClusterPVS(cluster); + + leafnum = CM_PointLeafnum(p2); + cluster = CM_LeafCluster(leafnum); + area2 = CM_LeafArea(leafnum); + if (mask && (!(mask[cluster >> 3] & (1 << (cluster & 7))))) { + if (com_speeds->integer) { + timeInPVSCheck += Sys_Milliseconds() - start; } return qfalse; } - if (!CM_AreasConnected (area1, area2)) - { + if (!CM_AreasConnected(area1, area2)) { timeInPVSCheck += Sys_Milliseconds() - start; - return qfalse; // a door blocks sight + return qfalse; // a door blocks sight } - if ( com_speeds->integer ) { + if (com_speeds->integer) { timeInPVSCheck += Sys_Milliseconds() - start; } return qtrue; } - /* ================= SV_inPVSIgnorePortals @@ -264,47 +244,44 @@ SV_inPVSIgnorePortals Does NOT check portalareas ================= */ -qboolean SV_inPVSIgnorePortals( const vec3_t p1, const vec3_t p2) -{ - int leafnum; - int cluster; - byte *mask; - int start=0; - - if ( com_speeds->integer ) { - start = Sys_Milliseconds (); +qboolean SV_inPVSIgnorePortals(const vec3_t p1, const vec3_t p2) { + int leafnum; + int cluster; + byte *mask; + int start = 0; + + if (com_speeds->integer) { + start = Sys_Milliseconds(); } - leafnum = CM_PointLeafnum (p1); - cluster = CM_LeafCluster (leafnum); - mask = CM_ClusterPVS (cluster); + leafnum = CM_PointLeafnum(p1); + cluster = CM_LeafCluster(leafnum); + mask = CM_ClusterPVS(cluster); - leafnum = CM_PointLeafnum (p2); - cluster = CM_LeafCluster (leafnum); + leafnum = CM_PointLeafnum(p2); + cluster = CM_LeafCluster(leafnum); - if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) ) - { - if ( com_speeds->integer ) { + if (mask && (!(mask[cluster >> 3] & (1 << (cluster & 7))))) { + if (com_speeds->integer) { timeInPVSCheck += Sys_Milliseconds() - start; } return qfalse; } - if ( com_speeds->integer ) { + if (com_speeds->integer) { timeInPVSCheck += Sys_Milliseconds() - start; } return qtrue; } - /* ======================== SV_AdjustAreaPortalState ======================== */ -void SV_AdjustAreaPortalState( gentity_t *ent, qboolean open ) { +void SV_AdjustAreaPortalState(gentity_t *ent, qboolean open) { #ifndef JK2_MODE - if ( !(ent->contents & CONTENTS_OPAQUE) ) { + if (!(ent->contents & CONTENTS_OPAQUE)) { #ifndef FINAL_BUILD // Com_Printf( "INFO: entity number %d not opaque: not affecting area portal!\n", ent->s.number ); #endif @@ -312,78 +289,65 @@ void SV_AdjustAreaPortalState( gentity_t *ent, qboolean open ) { } #endif - svEntity_t *svEnt; + svEntity_t *svEnt; - svEnt = SV_SvEntityForGentity( ent ); - if ( svEnt->areanum2 == -1 ) { + svEnt = SV_SvEntityForGentity(ent); + if (svEnt->areanum2 == -1) { return; } - CM_AdjustAreaPortalState( svEnt->areanum, svEnt->areanum2, open ); + CM_AdjustAreaPortalState(svEnt->areanum, svEnt->areanum2, open); } - /* ================== SV_GameAreaEntities ================== */ -qboolean SV_EntityContact( const vec3_t mins, const vec3_t maxs, const gentity_t *gEnt ) { - const float *origin, *angles; - clipHandle_t ch; - trace_t trace; +qboolean SV_EntityContact(const vec3_t mins, const vec3_t maxs, const gentity_t *gEnt) { + const float *origin, *angles; + clipHandle_t ch; + trace_t trace; // check for exact collision origin = gEnt->currentOrigin; angles = gEnt->currentAngles; - ch = SV_ClipHandleForEntity( gEnt ); - CM_TransformedBoxTrace ( &trace, vec3_origin, vec3_origin, mins, maxs, - ch, -1, origin, angles ); + ch = SV_ClipHandleForEntity(gEnt); + CM_TransformedBoxTrace(&trace, vec3_origin, vec3_origin, mins, maxs, ch, -1, origin, angles); return trace.startsolid; } - /* =============== SV_GetServerinfo =============== */ -void SV_GetServerinfo( char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetServerinfo: bufferSize == %i", bufferSize ); +void SV_GetServerinfo(char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetServerinfo: bufferSize == %i", bufferSize); } - Q_strncpyz( buffer, Cvar_InfoString( CVAR_SERVERINFO ), bufferSize ); + Q_strncpyz(buffer, Cvar_InfoString(CVAR_SERVERINFO), bufferSize); } -qboolean SV_GetEntityToken( char *buffer, int bufferSize ) -{ - char *s; +qboolean SV_GetEntityToken(char *buffer, int bufferSize) { + char *s; - if (sv.mLocalSubBSPIndex == -1) - { - s = COM_Parse( (const char **)&sv.entityParsePoint ); - Q_strncpyz( buffer, s, bufferSize ); - if ( !sv.entityParsePoint && !s[0] ) - { + if (sv.mLocalSubBSPIndex == -1) { + s = COM_Parse((const char **)&sv.entityParsePoint); + Q_strncpyz(buffer, s, bufferSize); + if (!sv.entityParsePoint && !s[0]) { return qfalse; - } - else - { + } else { return qtrue; } - } - else - { - s = COM_Parse( (const char **)&sv.mLocalSubBSPEntityParsePoint); - Q_strncpyz( buffer, s, bufferSize ); - if ( !sv.mLocalSubBSPEntityParsePoint && !s[0] ) - { + } else { + s = COM_Parse((const char **)&sv.mLocalSubBSPEntityParsePoint); + Q_strncpyz(buffer, s, bufferSize); + if (!sv.mLocalSubBSPEntityParsePoint && !s[0]) { return qfalse; - } - else - { + } else { return qtrue; } } @@ -399,16 +363,16 @@ Called when either the entire server is being killed, or it is changing to a different game directory. =============== */ -void SV_ShutdownGameProgs (qboolean shutdownCin) { +void SV_ShutdownGameProgs(qboolean shutdownCin) { if (!ge) { return; } - ge->Shutdown (); + ge->Shutdown(); SCR_StopCinematic(); - CL_ShutdownCGame(); //we have cgame burried in here. + CL_ShutdownCGame(); // we have cgame burried in here. - Sys_UnloadDll( gameLibrary ); + Sys_UnloadDll(gameLibrary); ge = NULL; cgvm.entryPoint = 0; @@ -416,467 +380,251 @@ void SV_ShutdownGameProgs (qboolean shutdownCin) { // this is a compile-helper function since Z_Malloc can now become a macro with __LINE__ etc // -static void *G_ZMalloc_Helper( int iSize, memtag_t eTag, qboolean bZeroit) -{ - return Z_Malloc( iSize, eTag, bZeroit ); -} +static void *G_ZMalloc_Helper(int iSize, memtag_t eTag, qboolean bZeroit) { return Z_Malloc(iSize, eTag, bZeroit); } -static int SV_G2API_AddBolt( CGhoul2Info *ghlInfo, const char *boneName ) -{ - return re.G2API_AddBolt( ghlInfo, boneName ); -} +static int SV_G2API_AddBolt(CGhoul2Info *ghlInfo, const char *boneName) { return re.G2API_AddBolt(ghlInfo, boneName); } -static int SV_G2API_AddBoltSurfNum( CGhoul2Info *ghlInfo, const int surfIndex ) -{ - return re.G2API_AddBoltSurfNum( ghlInfo, surfIndex ); -} +static int SV_G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) { return re.G2API_AddBoltSurfNum(ghlInfo, surfIndex); } -static int SV_G2API_AddSurface( CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ - return re.G2API_AddSurface( ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod ); +static int SV_G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { + return re.G2API_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); } -static void SV_G2API_AnimateG2Models( CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params ) -{ - re.G2API_AnimateG2Models( ghoul2, AcurrentTime, params ); +static void SV_G2API_AnimateG2Models(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) { + re.G2API_AnimateG2Models(ghoul2, AcurrentTime, params); } -static qboolean SV_G2API_AttachEnt( int *boltInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum ) -{ - return re.G2API_AttachEnt( boltInfo, ghlInfoTo, toBoltIndex, entNum, toModelNum ); +static qboolean SV_G2API_AttachEnt(int *boltInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum) { + return re.G2API_AttachEnt(boltInfo, ghlInfoTo, toBoltIndex, entNum, toModelNum); } -static qboolean SV_G2API_AttachG2Model( CGhoul2Info *ghlInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int toModel ) -{ - return re.G2API_AttachG2Model( ghlInfo, ghlInfoTo, toBoltIndex, toModel ); +static qboolean SV_G2API_AttachG2Model(CGhoul2Info *ghlInfo, CGhoul2Info *ghlInfoTo, int toBoltIndex, int toModel) { + return re.G2API_AttachG2Model(ghlInfo, ghlInfoTo, toBoltIndex, toModel); } -static void SV_G2API_CleanGhoul2Models( CGhoul2Info_v &ghoul2 ) -{ - return re.G2API_CleanGhoul2Models( ghoul2 ); -} +static void SV_G2API_CleanGhoul2Models(CGhoul2Info_v &ghoul2) { return re.G2API_CleanGhoul2Models(ghoul2); } -static void SV_G2API_CollisionDetect( - CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int AframeNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, CMiniHeap *miniHeap, - EG2_Collision eG2TraceType, int useLod, float fRadius ) -{ - re.G2API_CollisionDetect( collRecMap, ghoul2, angles, position, AframeNumber, - entNum, rayStart, rayEnd, scale, miniHeap, eG2TraceType, useLod, fRadius ); +static void SV_G2API_CollisionDetect(CCollisionRecord *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int AframeNumber, + int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, CMiniHeap *miniHeap, EG2_Collision eG2TraceType, int useLod, + float fRadius) { + re.G2API_CollisionDetect(collRecMap, ghoul2, angles, position, AframeNumber, entNum, rayStart, rayEnd, scale, miniHeap, eG2TraceType, useLod, fRadius); } -static void SV_G2API_CopyGhoul2Instance( CGhoul2Info_v &ghoul2From, CGhoul2Info_v &ghoul2To, int modelIndex ) -{ - re.G2API_CopyGhoul2Instance( ghoul2From, ghoul2To, modelIndex ); +static void SV_G2API_CopyGhoul2Instance(CGhoul2Info_v &ghoul2From, CGhoul2Info_v &ghoul2To, int modelIndex) { + re.G2API_CopyGhoul2Instance(ghoul2From, ghoul2To, modelIndex); } -static void SV_G2API_DetachEnt( int *boltInfo ) -{ - re.G2API_DetachEnt( boltInfo ); -} +static void SV_G2API_DetachEnt(int *boltInfo) { re.G2API_DetachEnt(boltInfo); } -static qboolean SV_G2API_DetachG2Model( CGhoul2Info *ghlInfo ) -{ - return re.G2API_DetachG2Model( ghlInfo ); -} -static qboolean SV_G2API_GetAnimFileName( CGhoul2Info *ghlInfo, char **filename ) -{ - return re.G2API_GetAnimFileName( ghlInfo, filename ); -} +static qboolean SV_G2API_DetachG2Model(CGhoul2Info *ghlInfo) { return re.G2API_DetachG2Model(ghlInfo); } +static qboolean SV_G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) { return re.G2API_GetAnimFileName(ghlInfo, filename); } -static char* SV_G2API_GetAnimFileNameIndex( qhandle_t modelIndex ) -{ - return re.G2API_GetAnimFileNameIndex( modelIndex ); -} +static char *SV_G2API_GetAnimFileNameIndex(qhandle_t modelIndex) { return re.G2API_GetAnimFileNameIndex(modelIndex); } -static char* SV_G2API_GetAnimFileInternalNameIndex( qhandle_t modelIndex ) -{ - return re.G2API_GetAnimFileInternalNameIndex( modelIndex ); -} +static char *SV_G2API_GetAnimFileInternalNameIndex(qhandle_t modelIndex) { return re.G2API_GetAnimFileInternalNameIndex(modelIndex); } -static int SV_G2API_GetAnimIndex( CGhoul2Info *ghlInfo ) -{ - return re.G2API_GetAnimIndex( ghlInfo ); -} +static int SV_G2API_GetAnimIndex(CGhoul2Info *ghlInfo) { return re.G2API_GetAnimIndex(ghlInfo); } -static qboolean SV_G2API_GetAnimRange( CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame ) -{ - return re.G2API_GetAnimRange( ghlInfo, boneName, startFrame, endFrame ); +static qboolean SV_G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) { + return re.G2API_GetAnimRange(ghlInfo, boneName, startFrame, endFrame); } -static qboolean SV_G2API_GetAnimRangeIndex( CGhoul2Info *ghlInfo, const int boneIndex, int *startFrame, int *endFrame ) -{ - return re.G2API_GetAnimRangeIndex( ghlInfo, boneIndex, startFrame, endFrame ); +static qboolean SV_G2API_GetAnimRangeIndex(CGhoul2Info *ghlInfo, const int boneIndex, int *startFrame, int *endFrame) { + return re.G2API_GetAnimRangeIndex(ghlInfo, boneIndex, startFrame, endFrame); } -static qboolean SV_G2API_GetBoneAnim( - CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList ) -{ - return re.G2API_GetBoneAnim( ghlInfo, boneName, AcurrentTime, currentFrame, - startFrame, endFrame, flags, animSpeed, modelList ); +static qboolean SV_G2API_GetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime, float *currentFrame, int *startFrame, int *endFrame, + int *flags, float *animSpeed, int *modelList) { + return re.G2API_GetBoneAnim(ghlInfo, boneName, AcurrentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList); } -static qboolean SV_G2API_GetBoneAnimIndex(CGhoul2Info *ghlInfo, const int iBoneIndex, const int AcurrentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList) -{ - return re.G2API_GetBoneAnimIndex( ghlInfo, iBoneIndex, AcurrentTime, currentFrame, - startFrame, endFrame, flags, animSpeed, modelList ); +static qboolean SV_G2API_GetBoneAnimIndex(CGhoul2Info *ghlInfo, const int iBoneIndex, const int AcurrentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *animSpeed, int *modelList) { + return re.G2API_GetBoneAnimIndex(ghlInfo, iBoneIndex, AcurrentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList); } -static int SV_G2API_GetBoneIndex( CGhoul2Info *ghlInfo, const char *boneName, qboolean bAddIfNotFound ) -{ - return re.G2API_GetBoneIndex( ghlInfo, boneName, bAddIfNotFound ); +static int SV_G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName, qboolean bAddIfNotFound) { + return re.G2API_GetBoneIndex(ghlInfo, boneName, bAddIfNotFound); } -static qboolean SV_G2API_GetBoltMatrix( - CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int AframeNum, qhandle_t *modelList, const vec3_t scale ) -{ - return re.G2API_GetBoltMatrix(ghoul2, modelIndex, boltIndex, matrix, angles, - position, AframeNum, modelList, scale ); +static qboolean SV_G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int AframeNum, qhandle_t *modelList, const vec3_t scale) { + return re.G2API_GetBoltMatrix(ghoul2, modelIndex, boltIndex, matrix, angles, position, AframeNum, modelList, scale); } -static int SV_G2API_GetGhoul2ModelFlags( CGhoul2Info *ghlInfo ) -{ - return re.G2API_GetGhoul2ModelFlags( ghlInfo ); -} +static int SV_G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) { return re.G2API_GetGhoul2ModelFlags(ghlInfo); } -static char* SV_G2API_GetGLAName( CGhoul2Info *ghlInfo ) -{ - return re.G2API_GetGLAName( ghlInfo ); -} +static char *SV_G2API_GetGLAName(CGhoul2Info *ghlInfo) { return re.G2API_GetGLAName(ghlInfo); } -static int SV_G2API_GetParentSurface( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_GetParentSurface( ghlInfo, index ); -} +static int SV_G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { return re.G2API_GetParentSurface(ghlInfo, index); } -static qboolean SV_G2API_GetRagBonePos( - CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) -{ - return re.G2API_GetRagBonePos( ghoul2, boneName, pos, entAngles, entPos, entScale ); +static qboolean SV_G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { + return re.G2API_GetRagBonePos(ghoul2, boneName, pos, entAngles, entPos, entScale); } -static int SV_G2API_GetSurfaceIndex( CGhoul2Info *ghlInfo, const char *surfaceName ) -{ - return re.G2API_GetSurfaceIndex( ghlInfo, surfaceName ); -} +static int SV_G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { return re.G2API_GetSurfaceIndex(ghlInfo, surfaceName); } -static char* SV_G2API_GetSurfaceName( CGhoul2Info *ghlInfo, int surfNumber ) -{ - return re.G2API_GetSurfaceName( ghlInfo, surfNumber ); -} +static char *SV_G2API_GetSurfaceName(CGhoul2Info *ghlInfo, int surfNumber) { return re.G2API_GetSurfaceName(ghlInfo, surfNumber); } -static int SV_G2API_GetSurfaceRenderStatus( CGhoul2Info *ghlInfo, const char *surfaceName ) -{ - return re.G2API_GetSurfaceRenderStatus( ghlInfo, surfaceName ); -} +static int SV_G2API_GetSurfaceRenderStatus(CGhoul2Info *ghlInfo, const char *surfaceName) { return re.G2API_GetSurfaceRenderStatus(ghlInfo, surfaceName); } -static void SV_G2API_GiveMeVectorFromMatrix( mdxaBone_t &boltMatrix, Eorientations flags, vec3_t &vec ) -{ - re.G2API_GiveMeVectorFromMatrix( boltMatrix, flags, vec ); +static void SV_G2API_GiveMeVectorFromMatrix(mdxaBone_t &boltMatrix, Eorientations flags, vec3_t &vec) { + re.G2API_GiveMeVectorFromMatrix(boltMatrix, flags, vec); } -static qboolean SV_G2API_HaveWeGhoul2Models( CGhoul2Info_v &ghoul2 ) -{ - return re.G2API_HaveWeGhoul2Models( ghoul2 ); -} +static qboolean SV_G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) { return re.G2API_HaveWeGhoul2Models(ghoul2); } -static qboolean SV_G2API_IKMove( CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params ) -{ - return re.G2API_IKMove( ghoul2, time, params ); -} +static qboolean SV_G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { return re.G2API_IKMove(ghoul2, time, params); } -static int SV_G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int modelIndex, - qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias) -{ - return re.G2API_InitGhoul2Model( ghoul2, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias ); +static int SV_G2API_InitGhoul2Model(CGhoul2Info_v &ghoul2, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { + return re.G2API_InitGhoul2Model(ghoul2, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } -static qboolean SV_G2API_IsPaused( CGhoul2Info *ghlInfo, const char *boneName ) -{ - return re.G2API_IsPaused( ghlInfo, boneName ); -} +static qboolean SV_G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) { return re.G2API_IsPaused(ghlInfo, boneName); } -static void SV_G2API_ListBones( CGhoul2Info *ghlInfo, int frame ) -{ - return re.G2API_ListBones( ghlInfo, frame ); -} +static void SV_G2API_ListBones(CGhoul2Info *ghlInfo, int frame) { return re.G2API_ListBones(ghlInfo, frame); } -static void SV_G2API_ListSurfaces( CGhoul2Info *ghlInfo ) -{ - return re.G2API_ListSurfaces( ghlInfo ); -} +static void SV_G2API_ListSurfaces(CGhoul2Info *ghlInfo) { return re.G2API_ListSurfaces(ghlInfo); } -static void SV_G2API_LoadGhoul2Models( CGhoul2Info_v &ghoul2, char *buffer ) -{ - return re.G2API_LoadGhoul2Models( ghoul2, buffer ); -} +static void SV_G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) { return re.G2API_LoadGhoul2Models(ghoul2, buffer); } -static void SV_G2API_LoadSaveCodeDestructGhoul2Info( CGhoul2Info_v &ghoul2 ) -{ - return re.G2API_LoadSaveCodeDestructGhoul2Info( ghoul2 ); -} +static void SV_G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) { return re.G2API_LoadSaveCodeDestructGhoul2Info(ghoul2); } -static qboolean SV_G2API_PauseBoneAnim( CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime ) -{ - return re.G2API_PauseBoneAnim( ghlInfo, boneName, AcurrentTime ); +static qboolean SV_G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int AcurrentTime) { + return re.G2API_PauseBoneAnim(ghlInfo, boneName, AcurrentTime); } -static qboolean SV_G2API_PauseBoneAnimIndex( CGhoul2Info *ghlInfo, const int boneIndex, const int AcurrentTime ) -{ - return re.G2API_PauseBoneAnimIndex( ghlInfo, boneIndex, AcurrentTime ); +static qboolean SV_G2API_PauseBoneAnimIndex(CGhoul2Info *ghlInfo, const int boneIndex, const int AcurrentTime) { + return re.G2API_PauseBoneAnimIndex(ghlInfo, boneIndex, AcurrentTime); } -static qhandle_t SV_G2API_PrecacheGhoul2Model( const char *fileName ) -{ - return re.G2API_PrecacheGhoul2Model( fileName ); -} +static qhandle_t SV_G2API_PrecacheGhoul2Model(const char *fileName) { return re.G2API_PrecacheGhoul2Model(fileName); } -static qboolean SV_G2API_RagEffectorGoal( CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos ) -{ - return re.G2API_RagEffectorGoal( ghoul2, boneName, pos ); -} +static qboolean SV_G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) { return re.G2API_RagEffectorGoal(ghoul2, boneName, pos); } -static qboolean SV_G2API_RagEffectorKick( CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity ) -{ - return re.G2API_RagEffectorKick( ghoul2, boneName, velocity ); +static qboolean SV_G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) { + return re.G2API_RagEffectorKick(ghoul2, boneName, velocity); } -static qboolean SV_G2API_RagForceSolve( CGhoul2Info_v &ghoul2, qboolean force ) -{ - return re.G2API_RagForceSolve( ghoul2, force ); -} +static qboolean SV_G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) { return re.G2API_RagForceSolve(ghoul2, force); } -static qboolean SV_G2API_RagPCJConstraint( CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max ) -{ - return re.G2API_RagPCJConstraint( ghoul2, boneName, min, max ); +static qboolean SV_G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) { + return re.G2API_RagPCJConstraint(ghoul2, boneName, min, max); } -static qboolean SV_G2API_RagPCJGradientSpeed( CGhoul2Info_v &ghoul2, const char *boneName, const float speed ) -{ - return re.G2API_RagPCJGradientSpeed( ghoul2, boneName, speed ); +static qboolean SV_G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) { + return re.G2API_RagPCJGradientSpeed(ghoul2, boneName, speed); } -static qboolean SV_G2API_RemoveBolt( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_RemoveBolt( ghlInfo, index ); -} +static qboolean SV_G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) { return re.G2API_RemoveBolt(ghlInfo, index); } -static qboolean SV_G2API_RemoveBone( CGhoul2Info *ghlInfo, const char *boneName ) -{ - return re.G2API_RemoveBone( ghlInfo, boneName ); -} +static qboolean SV_G2API_RemoveBone(CGhoul2Info *ghlInfo, const char *boneName) { return re.G2API_RemoveBone(ghlInfo, boneName); } -static qboolean SV_G2API_RemoveGhoul2Model( CGhoul2Info_v &ghlInfo, const int modelIndex ) -{ - return re.G2API_RemoveGhoul2Model( ghlInfo, modelIndex ); -} +static qboolean SV_G2API_RemoveGhoul2Model(CGhoul2Info_v &ghlInfo, const int modelIndex) { return re.G2API_RemoveGhoul2Model(ghlInfo, modelIndex); } -static qboolean SV_G2API_RemoveSurface( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_RemoveSurface( ghlInfo, index ); -} +static qboolean SV_G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) { return re.G2API_RemoveSurface(ghlInfo, index); } -static void SV_G2API_SaveGhoul2Models( CGhoul2Info_v &ghoul2 ) -{ - return re.G2API_SaveGhoul2Models( ghoul2 ); -} +static void SV_G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2) { return re.G2API_SaveGhoul2Models(ghoul2); } -static qboolean SV_G2API_SetAnimIndex( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_SetAnimIndex( ghlInfo, index ); -} +static qboolean SV_G2API_SetAnimIndex(CGhoul2Info *ghlInfo, const int index) { return re.G2API_SetAnimIndex(ghlInfo, index); } -static qboolean SV_G2API_SetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int startFrame, const int endFrame, - const int flags, const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) -{ - return re.G2API_SetBoneAnim( ghlInfo, boneName, startFrame, endFrame, flags, - animSpeed, AcurrentTime, setFrame, blendTime ); +static qboolean SV_G2API_SetBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) { + return re.G2API_SetBoneAnim(ghlInfo, boneName, startFrame, endFrame, flags, animSpeed, AcurrentTime, setFrame, blendTime); } -static qboolean SV_G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int startFrame, const int endFrame, - const int flags, const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) -{ - return re.G2API_SetBoneAnimIndex( ghlInfo, index, startFrame, endFrame, flags, - animSpeed, AcurrentTime, setFrame, blendTime ); +static qboolean SV_G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int AcurrentTime, const float setFrame, const int blendTime) { + return re.G2API_SetBoneAnimIndex(ghlInfo, index, startFrame, endFrame, flags, animSpeed, AcurrentTime, setFrame, blendTime); } -static qboolean SV_G2API_SetBoneAngles(CGhoul2Info *ghlInfo, const char *boneName, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, qhandle_t *modelList, - int blendTime, int AcurrentTime) -{ - return re.G2API_SetBoneAngles( ghlInfo, boneName, angles, flags, up, left, forward, - modelList, blendTime, AcurrentTime ); +static qboolean SV_G2API_SetBoneAngles(CGhoul2Info *ghlInfo, const char *boneName, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, int blendTime, int AcurrentTime) { + return re.G2API_SetBoneAngles(ghlInfo, boneName, angles, flags, up, left, forward, modelList, blendTime, AcurrentTime); } -static qboolean SV_G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, - const Eorientations yaw, const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, - int blendTime, int AcurrentTime) -{ - return re.G2API_SetBoneAnglesIndex( ghlInfo, index, angles, flags, yaw, pitch, roll, - modelList, blendTime, AcurrentTime ); +static qboolean SV_G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, int blendTime, int AcurrentTime) { + return re.G2API_SetBoneAnglesIndex(ghlInfo, index, angles, flags, yaw, pitch, roll, modelList, blendTime, AcurrentTime); } -static qboolean SV_G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int AcurrentTime) -{ - return re.G2API_SetBoneAnglesMatrix( ghlInfo, boneName, matrix, flags, modelList, blendTime, AcurrentTime ); +static qboolean SV_G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + int blendTime, int AcurrentTime) { + return re.G2API_SetBoneAnglesMatrix(ghlInfo, boneName, matrix, flags, modelList, blendTime, AcurrentTime); } -static qboolean SV_G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blandeTime, int AcurrentTime) -{ - return re.G2API_SetBoneAnglesMatrixIndex( ghlInfo, index, matrix, flags, modelList, blandeTime, AcurrentTime ); +static qboolean SV_G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + int blandeTime, int AcurrentTime) { + return re.G2API_SetBoneAnglesMatrixIndex(ghlInfo, index, matrix, flags, modelList, blandeTime, AcurrentTime); } -static qboolean SV_G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, - sharedSetBoneIKStateParams_t *params) -{ - return re.G2API_SetBoneIKState( ghoul2, time, boneName, ikState, params ); +static qboolean SV_G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + return re.G2API_SetBoneIKState(ghoul2, time, boneName, ikState, params); } -static qboolean SV_G2API_SetGhoul2ModelFlags( CGhoul2Info *ghlInfo, const int flags ) -{ - return re.G2API_SetGhoul2ModelFlags( ghlInfo, flags ); -} +static qboolean SV_G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) { return re.G2API_SetGhoul2ModelFlags(ghlInfo, flags); } -static qboolean SV_G2API_SetLodBias( CGhoul2Info *ghlInfo, int lodBias ) -{ - return re.G2API_SetLodBias( ghlInfo, lodBias ); -} +static qboolean SV_G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) { return re.G2API_SetLodBias(ghlInfo, lodBias); } -static qboolean SV_G2API_SetNewOrigin( CGhoul2Info *ghlInfo, const int boltIndex ) -{ - return re.G2API_SetNewOrigin( ghlInfo, boltIndex ); -} +static qboolean SV_G2API_SetNewOrigin(CGhoul2Info *ghlInfo, const int boltIndex) { return re.G2API_SetNewOrigin(ghlInfo, boltIndex); } -static void SV_G2API_SetRagDoll( CGhoul2Info_v &ghoul2, CRagDollParams *parms ) -{ - return re.G2API_SetRagDoll( ghoul2, parms ); -} +static void SV_G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms) { return re.G2API_SetRagDoll(ghoul2, parms); } -static qboolean SV_G2API_SetRootSurface( CGhoul2Info_v &ghlInfo, const int modelIndex, const char *surfaceName ) -{ - return re.G2API_SetRootSurface( ghlInfo, modelIndex, surfaceName ); +static qboolean SV_G2API_SetRootSurface(CGhoul2Info_v &ghlInfo, const int modelIndex, const char *surfaceName) { + return re.G2API_SetRootSurface(ghlInfo, modelIndex, surfaceName); } -static qboolean SV_G2API_SetShader( CGhoul2Info *ghlInfo, qhandle_t customShader ) -{ - return re.G2API_SetShader( ghlInfo, customShader ); -} +static qboolean SV_G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) { return re.G2API_SetShader(ghlInfo, customShader); } -static qboolean SV_G2API_SetSkin( CGhoul2Info *ghlInfo, qhandle_t customSkin, qhandle_t renderSkin ) -{ - return re.G2API_SetSkin( ghlInfo, customSkin, renderSkin ); -} +static qboolean SV_G2API_SetSkin(CGhoul2Info *ghlInfo, qhandle_t customSkin, qhandle_t renderSkin) { return re.G2API_SetSkin(ghlInfo, customSkin, renderSkin); } -static qboolean SV_G2API_SetSurfaceOnOff( CGhoul2Info *ghlInfo, const char *surfaceName, const int flags ) -{ - return re.G2API_SetSurfaceOnOff( ghlInfo, surfaceName, flags ); +static qboolean SV_G2API_SetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName, const int flags) { + return re.G2API_SetSurfaceOnOff(ghlInfo, surfaceName, flags); } -static qboolean SV_G2API_StopBoneAnim( CGhoul2Info *ghlInfo, const char *boneName ) -{ - return re.G2API_StopBoneAnim( ghlInfo, boneName ); -} +static qboolean SV_G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) { return re.G2API_StopBoneAnim(ghlInfo, boneName); } -static qboolean SV_G2API_StopBoneAnimIndex( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_StopBoneAnimIndex( ghlInfo, index ); -} +static qboolean SV_G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) { return re.G2API_StopBoneAnimIndex(ghlInfo, index); } -static qboolean SV_G2API_StopBoneAngles( CGhoul2Info *ghlInfo, const char *boneName ) -{ - return re.G2API_StopBoneAngles( ghlInfo, boneName ); -} +static qboolean SV_G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) { return re.G2API_StopBoneAngles(ghlInfo, boneName); } -static qboolean SV_G2API_StopBoneAnglesIndex( CGhoul2Info *ghlInfo, const int index ) -{ - return re.G2API_StopBoneAnglesIndex( ghlInfo, index ); -} +static qboolean SV_G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) { return re.G2API_StopBoneAnglesIndex(ghlInfo, index); } #ifdef _G2_GORE -static void SV_G2API_AddSkinGore( CGhoul2Info_v &ghoul2, SSkinGoreData &gore ) -{ - return re.G2API_AddSkinGore( ghoul2, gore ); -} +static void SV_G2API_AddSkinGore(CGhoul2Info_v &ghoul2, SSkinGoreData &gore) { return re.G2API_AddSkinGore(ghoul2, gore); } -static void SV_G2API_ClearSkinGore( CGhoul2Info_v &ghoul2 ) -{ - return re.G2API_ClearSkinGore( ghoul2 ); -} +static void SV_G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { return re.G2API_ClearSkinGore(ghoul2); } #else -static void SV_G2API_AddSkinGore( - CGhoul2Info_v &ghoul2, - SSkinGoreData &gore) -{ - static_cast(ghoul2); - static_cast(gore); +static void SV_G2API_AddSkinGore(CGhoul2Info_v &ghoul2, SSkinGoreData &gore) { + static_cast(ghoul2); + static_cast(gore); } -static void SV_G2API_ClearSkinGore( - CGhoul2Info_v &ghoul2) -{ - static_cast(ghoul2); -} +static void SV_G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { static_cast(ghoul2); } #endif -static IGhoul2InfoArray& SV_TheGhoul2InfoArray( void ) -{ - return re.TheGhoul2InfoArray(); -} +static IGhoul2InfoArray &SV_TheGhoul2InfoArray(void) { return re.TheGhoul2InfoArray(); } -static qhandle_t SV_RE_RegisterSkin( const char *name ) -{ - return re.RegisterSkin( name ); -} +static qhandle_t SV_RE_RegisterSkin(const char *name) { return re.RegisterSkin(name); } -static int SV_RE_GetAnimationCFG( const char *psCFGFilename, char *psDest, int iDestSize ) -{ - return re.GetAnimationCFG( psCFGFilename, psDest, iDestSize ); -} +static int SV_RE_GetAnimationCFG(const char *psCFGFilename, char *psDest, int iDestSize) { return re.GetAnimationCFG(psCFGFilename, psDest, iDestSize); } -static bool SV_WE_GetWindVector( vec3_t windVector, vec3_t atPoint ) -{ - return re.GetWindVector( windVector, atPoint ); -} +static bool SV_WE_GetWindVector(vec3_t windVector, vec3_t atPoint) { return re.GetWindVector(windVector, atPoint); } -static bool SV_WE_GetWindGusting( vec3_t atpoint ) -{ - return re.GetWindGusting( atpoint ); -} +static bool SV_WE_GetWindGusting(vec3_t atpoint) { return re.GetWindGusting(atpoint); } -static bool SV_WE_IsOutside( vec3_t pos ) -{ - return re.IsOutside( pos ); -} +static bool SV_WE_IsOutside(vec3_t pos) { return re.IsOutside(pos); } -static float SV_WE_IsOutsideCausingPain( vec3_t pos ) -{ - return re.IsOutsideCausingPain( pos ); -} +static float SV_WE_IsOutsideCausingPain(vec3_t pos) { return re.IsOutsideCausingPain(pos); } -static float SV_WE_GetChanceOfSaberFizz( void ) -{ - return re.GetChanceOfSaberFizz(); -} +static float SV_WE_GetChanceOfSaberFizz(void) { return re.GetChanceOfSaberFizz(); } -static bool SV_WE_IsShaking( vec3_t pos ) -{ - return re.IsShaking( pos ); -} +static bool SV_WE_IsShaking(vec3_t pos) { return re.IsShaking(pos); } -static void SV_WE_AddWeatherZone( vec3_t mins, vec3_t maxs ) -{ - return re.AddWeatherZone( mins, maxs ); -} +static void SV_WE_AddWeatherZone(vec3_t mins, vec3_t maxs) { return re.AddWeatherZone(mins, maxs); } -static bool SV_WE_SetTempGlobalFogColor( vec3_t color ) -{ - return re.SetTempGlobalFogColor( color ); -} +static bool SV_WE_SetTempGlobalFogColor(vec3_t color) { return re.SetTempGlobalFogColor(color); } /* =============== @@ -885,13 +633,13 @@ SV_InitGameProgs Init the game subsystem for a new map =============== */ -void SV_InitGameProgs (void) { - game_import_t import; - int i; +void SV_InitGameProgs(void) { + game_import_t import; + int i; // unload anything we have now - if ( ge ) { - SV_ShutdownGameProgs (qtrue); + if (ge) { + SV_ShutdownGameProgs(qtrue); } // load a new game dll @@ -906,7 +654,6 @@ void SV_InitGameProgs (void) { import.SendServerCommand = SV_GameSendServerCommand; - import.linkentity = SV_LinkEntity; import.unlinkentity = SV_UnlinkEntity; import.EntitiesInBox = SV_AreaEntities; @@ -1029,7 +776,7 @@ void SV_InitGameProgs (void) { import.G2API_RagForceSolve = SV_G2API_RagForceSolve; import.G2API_SetBoneIKState = SV_G2API_SetBoneIKState; - import.G2API_IKMove = SV_G2API_IKMove; + import.G2API_IKMove = SV_G2API_IKMove; import.G2API_AddSkinGore = SV_G2API_AddSkinGore; import.G2API_ClearSkinGore = SV_G2API_ClearSkinGore; @@ -1039,10 +786,10 @@ void SV_InitGameProgs (void) { import.RE_RegisterSkin = SV_RE_RegisterSkin; import.RE_GetAnimationCFG = SV_RE_GetAnimationCFG; - import.WE_GetWindVector = SV_WE_GetWindVector; + import.WE_GetWindVector = SV_WE_GetWindVector; import.WE_GetWindGusting = SV_WE_GetWindGusting; - import.WE_IsOutside = SV_WE_IsOutside; - import.WE_IsOutsideCausingPain = SV_WE_IsOutsideCausingPain; + import.WE_IsOutside = SV_WE_IsOutside; + import.WE_IsOutsideCausingPain = SV_WE_IsOutsideCausingPain; import.WE_GetChanceOfSaberFizz = SV_WE_GetChanceOfSaberFizz; import.WE_IsShaking = SV_WE_IsShaking; import.WE_AddWeatherZone = SV_WE_AddWeatherZone; @@ -1055,46 +802,42 @@ void SV_InitGameProgs (void) { #endif GetGameAPIProc *GetGameAPI; - gameLibrary = Sys_LoadSPGameDll( gamename, &GetGameAPI ); - if ( !gameLibrary ) - Com_Error( ERR_DROP, "Failed to load %s library", gamename ); - - ge = (game_export_t *)GetGameAPI( &import ); - if (!ge) - { - Sys_UnloadDll( gameLibrary ); - Com_Error( ERR_DROP, "Failed to load %s library", gamename ); + gameLibrary = Sys_LoadSPGameDll(gamename, &GetGameAPI); + if (!gameLibrary) + Com_Error(ERR_DROP, "Failed to load %s library", gamename); + + ge = (game_export_t *)GetGameAPI(&import); + if (!ge) { + Sys_UnloadDll(gameLibrary); + Com_Error(ERR_DROP, "Failed to load %s library", gamename); } - if (ge->apiversion != GAME_API_VERSION) - { + if (ge->apiversion != GAME_API_VERSION) { int apiVersion = ge->apiversion; - Sys_UnloadDll( gameLibrary ); - Com_Error (ERR_DROP, "game is version %i, not %i", apiVersion, GAME_API_VERSION); + Sys_UnloadDll(gameLibrary); + Com_Error(ERR_DROP, "game is version %i, not %i", apiVersion, GAME_API_VERSION); } - //hook up the client while we're here - if ( !CL_InitCGameVM( gameLibrary ) ) - { - Sys_UnloadDll( gameLibrary ); - Com_Error ( ERR_DROP, "Failed to load client game functions" ); + // hook up the client while we're here + if (!CL_InitCGameVM(gameLibrary)) { + Sys_UnloadDll(gameLibrary); + Com_Error(ERR_DROP, "Failed to load client game functions"); } sv.entityParsePoint = CM_EntityString(); // use the current msec count for a random seed Z_TagFree(TAG_G_ALLOC); - ge->Init( sv_mapname->string, sv_spawntarget->string, sv_mapChecksum->integer, CM_EntityString(), sv.time, com_frameTime, Com_Milliseconds(), eSavedGameJustLoaded, qbLoadTransition ); + ge->Init(sv_mapname->string, sv_spawntarget->string, sv_mapChecksum->integer, CM_EntityString(), sv.time, com_frameTime, Com_Milliseconds(), + eSavedGameJustLoaded, qbLoadTransition); // clear all gentity pointers that might still be set from // a previous level - for ( i = 0 ; i < 1 ; i++ ) { + for (i = 0; i < 1; i++) { svs.clients[i].gentity = NULL; } } - - /* ==================== SV_GameCommand @@ -1102,11 +845,10 @@ SV_GameCommand See if the current console command is claimed by the game ==================== */ -qboolean SV_GameCommand( void ) { - if ( sv.state != SS_GAME ) { +qboolean SV_GameCommand(void) { + if (sv.state != SS_GAME) { return qfalse; } return ge->ConsoleCommand(); } - diff --git a/code/server/sv_init.cpp b/code/server/sv_init.cpp index c9dd488088..6b02c22898 100644 --- a/code/server/sv_init.cpp +++ b/code/server/sv_init.cpp @@ -23,114 +23,107 @@ along with this program; if not, see . #include "../server/exe_headers.h" -#include "../client/snd_music.h" // didn't want to put this in snd_local because of rebuild times etc. +#include "../client/snd_music.h" // didn't want to put this in snd_local because of rebuild times etc. #include "server.h" -#if !defined (MINIHEAP_H_INC) - #include "../qcommon/MiniHeap.h" +#if !defined(MINIHEAP_H_INC) +#include "../qcommon/MiniHeap.h" #endif void CM_CleanLeafCache(void); -extern void SV_FreeClient(client_t*); +extern void SV_FreeClient(client_t *); CMiniHeap *G2VertSpaceServer = NULL; /* Ghoul2 Insert End */ - /* =============== SV_SetConfigstring =============== */ -void SV_SetConfigstring (int index, const char *val) { - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error (ERR_DROP, "SV_SetConfigstring: bad index %i\n", index); +void SV_SetConfigstring(int index, const char *val) { + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "SV_SetConfigstring: bad index %i\n", index); } - if ( !val ) { + if (!val) { val = ""; } // don't bother broadcasting an update if no change - if ( !strcmp( val, sv.configstrings[ index ] ) ) { + if (!strcmp(val, sv.configstrings[index])) { return; } // change the string in sv - Z_Free( sv.configstrings[index] ); - sv.configstrings[index] = CopyString( val ); + Z_Free(sv.configstrings[index]); + sv.configstrings[index] = CopyString(val); // send it to all the clients if we aren't // spawning a new server - if ( sv.state == SS_GAME ) { - SV_SendServerCommand( NULL, "cs %i \"%s\"\n", index, val ); + if (sv.state == SS_GAME) { + SV_SendServerCommand(NULL, "cs %i \"%s\"\n", index, val); } } - - /* =============== SV_GetConfigstring =============== */ -void SV_GetConfigstring( int index, char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetConfigstring: bufferSize == %i", bufferSize ); +void SV_GetConfigstring(int index, char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetConfigstring: bufferSize == %i", bufferSize); } - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error (ERR_DROP, "SV_GetConfigstring: bad index %i\n", index); + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "SV_GetConfigstring: bad index %i\n", index); } - if ( !sv.configstrings[index] ) { + if (!sv.configstrings[index]) { buffer[0] = 0; return; } - Q_strncpyz( buffer, sv.configstrings[index], bufferSize ); + Q_strncpyz(buffer, sv.configstrings[index], bufferSize); } - /* =============== SV_SetUserinfo =============== */ -void SV_SetUserinfo( int index, const char *val ) { - if ( index < 0 || index >= 1 ) { - Com_Error (ERR_DROP, "SV_SetUserinfo: bad index %i\n", index); +void SV_SetUserinfo(int index, const char *val) { + if (index < 0 || index >= 1) { + Com_Error(ERR_DROP, "SV_SetUserinfo: bad index %i\n", index); } - if ( !val ) { + if (!val) { val = ""; } - Q_strncpyz( svs.clients[ index ].userinfo, val, sizeof( svs.clients[ index ].userinfo ) ); + Q_strncpyz(svs.clients[index].userinfo, val, sizeof(svs.clients[index].userinfo)); } - - /* =============== SV_GetUserinfo =============== */ -void SV_GetUserinfo( int index, char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetUserinfo: bufferSize == %i", bufferSize ); +void SV_GetUserinfo(int index, char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetUserinfo: bufferSize == %i", bufferSize); } - if ( index < 0 || index >= 1 ) { - Com_Error (ERR_DROP, "SV_GetUserinfo: bad index %i\n", index); + if (index < 0 || index >= 1) { + Com_Error(ERR_DROP, "SV_GetUserinfo: bad index %i\n", index); } - Q_strncpyz( buffer, svs.clients[ index ].userinfo, bufferSize ); + Q_strncpyz(buffer, svs.clients[index].userinfo, bufferSize); } - /* ================ SV_CreateBaseline @@ -140,11 +133,11 @@ to the clients -- only the fields that differ from the baseline will be transmitted ================ */ -void SV_CreateBaseline( void ) { - gentity_t *svent; - int entnum; +void SV_CreateBaseline(void) { + gentity_t *svent; + int entnum; - for ( entnum = 0; entnum < ge->num_entities ; entnum++ ) { + for (entnum = 0; entnum < ge->num_entities; entnum++) { svent = SV_GentityNum(entnum); if (!svent->inuse) { continue; @@ -161,9 +154,6 @@ void SV_CreateBaseline( void ) { } } - - - /* =============== SV_Startup @@ -171,16 +161,16 @@ SV_Startup Called when a game is about to begin =============== */ -void SV_Startup( void ) { - if ( svs.initialized ) { - Com_Error( ERR_FATAL, "SV_Startup: svs.initialized" ); +void SV_Startup(void) { + if (svs.initialized) { + Com_Error(ERR_FATAL, "SV_Startup: svs.initialized"); } - svs.clients = (struct client_s *) Z_Malloc ( sizeof(client_t) * 1, TAG_CLIENTS, qtrue ); + svs.clients = (struct client_s *)Z_Malloc(sizeof(client_t) * 1, TAG_CLIENTS, qtrue); svs.numSnapshotEntities = 2 * 4 * 64; svs.initialized = qtrue; - Cvar_Set( "sv_running", "1" ); + Cvar_Set("sv_running", "1"); } qboolean CM_SameMap(const char *server); @@ -194,26 +184,23 @@ Change the server to a new map, taking all connected clients along with it. ================ */ -void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bAllowScreenDissolve ) -{ - int i; - int checksum; - - re.RegisterMedia_LevelLoadBegin( server, eForceReload, bAllowScreenDissolve ); +void SV_SpawnServer(const char *server, ForceReload_e eForceReload, qboolean bAllowScreenDissolve) { + int i; + int checksum; + re.RegisterMedia_LevelLoadBegin(server, eForceReload, bAllowScreenDissolve); - Cvar_SetValue( "cl_paused", 0 ); - Cvar_Set( "timescale", "1" );//jic we were skipping + Cvar_SetValue("cl_paused", 0); + Cvar_Set("timescale", "1"); // jic we were skipping // shut down the existing game if it is running SV_ShutdownGameProgs(qtrue); - Com_Printf ("------ Server Initialization ------\n%s\n", com_version->string); - Com_Printf ("Server: %s\n",server); + Com_Printf("------ Server Initialization ------\n%s\n", com_version->string); + Com_Printf("Server: %s\n", server); // Moved up from below to help reduce fragmentation - if (svs.snapshotEntities) - { + if (svs.snapshotEntities) { Z_Free(svs.snapshotEntities); svs.snapshotEntities = NULL; } @@ -221,8 +208,7 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA // don't let sound stutter and dump all stuff on the hunk CL_MapLoading(); - if (!CM_SameMap(server)) - { //rww - only clear if not loading the same map + if (!CM_SameMap(server)) { // rww - only clear if not loading the same map CM_ClearMap(); } @@ -233,9 +219,9 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA // wipe the entire per-level structure // Also moved up, trying to do all freeing before new allocs - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( sv.configstrings[i] ) { - Z_Free( sv.configstrings[i] ); + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (sv.configstrings[i]) { + Z_Free(sv.configstrings[i]); sv.configstrings[i] = NULL; } } @@ -245,19 +231,19 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA // allocations begin! Cvar_Defrag(); -/* - This is useful for debugging memory fragmentation. Please don't - remove it. -*/ + /* + This is useful for debugging memory fragmentation. Please don't + remove it. + */ // init client structures and svs.numSnapshotEntities // This is moved down quite a bit, but should be safe. And keeps // svs.clients right at the beginning of memory - if ( !Cvar_VariableIntegerValue("sv_running") ) { + if (!Cvar_VariableIntegerValue("sv_running")) { SV_Startup(); } - // clear out those shaders, images and Models + // clear out those shaders, images and Models /*R_InitImages(); R_InitShaders(); R_ModelInit();*/ @@ -265,42 +251,40 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA re.SVModelInit(); // allocate the snapshot entities - svs.snapshotEntities = (entityState_t *) Z_Malloc (sizeof(entityState_t)*svs.numSnapshotEntities, TAG_CLIENTS, qtrue ); + svs.snapshotEntities = (entityState_t *)Z_Malloc(sizeof(entityState_t) * svs.numSnapshotEntities, TAG_CLIENTS, qtrue); Music_SetLevelName(server); // toggle the server bit so clients can detect that a // server has changed -//!@ svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT; + //!@ svs.snapFlagServerBit ^= SNAPFLAG_SERVERCOUNT; // set nextmap to the same map, but it may be overriden // by the game startup or another console command - Cvar_Set( "nextmap", va("map %s", server) ); - - - memset (&sv, 0, sizeof(sv)); + Cvar_Set("nextmap", va("map %s", server)); + memset(&sv, 0, sizeof(sv)); - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { sv.configstrings[i] = CopyString(""); } sv.time = 1000; - re.G2API_SetTime(sv.time,G2T_SV_TIME); + re.G2API_SetTime(sv.time, G2T_SV_TIME); - CM_LoadMap( va("maps/%s.bsp", server), qfalse, &checksum, qfalse ); + CM_LoadMap(va("maps/%s.bsp", server), qfalse, &checksum, qfalse); // set serverinfo visible name - Cvar_Set( "mapname", server ); + Cvar_Set("mapname", server); - Cvar_Set( "sv_mapChecksum", va("%i",checksum) ); + Cvar_Set("sv_mapChecksum", va("%i", checksum)); // serverid should be different each time sv.serverId = com_frameTime; - Cvar_Set( "sv_serverid", va("%i", sv.serverId ) ); + Cvar_Set("sv_serverid", va("%i", sv.serverId)); // clear physics interaction links - SV_ClearWorld (); + SV_ClearWorld(); // media configstring setting should be done during // the loading stage, so connected clients don't have @@ -311,33 +295,33 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA SV_InitGameProgs(); // run a few frames to allow everything to settle - for ( i = 0 ;i < 4 ; i++ ) { - ge->RunFrame( sv.time ); + for (i = 0; i < 4; i++) { + ge->RunFrame(sv.time); sv.time += 100; - re.G2API_SetTime(sv.time,G2T_SV_TIME); + re.G2API_SetTime(sv.time, G2T_SV_TIME); } #ifndef JK2_MODE ge->ConnectNavs(sv_mapname->string, sv_mapChecksum->integer); #endif // create a baseline for more efficient communications - SV_CreateBaseline (); + SV_CreateBaseline(); - for (i=0 ; i<1 ; i++) { + for (i = 0; i < 1; i++) { // clear all time counters, because we have reset sv.time svs.clients[i].lastPacketTime = 0; svs.clients[i].lastConnectTime = 0; // send the new gamestate to all connected clients if (svs.clients[i].state >= CS_CONNECTED) { - char *denied; + char *denied; // connect the client again - denied = ge->ClientConnect( i, qfalse, eNO/*qfalse*/ ); // firstTime = qfalse, qbFromSavedGame - if ( denied ) { + denied = ge->ClientConnect(i, qfalse, eNO /*qfalse*/); // firstTime = qfalse, qbFromSavedGame + if (denied) { // this generally shouldn't happen, because the client // was connected before the level change - SV_DropClient( &svs.clients[i], denied ); + SV_DropClient(&svs.clients[i], denied); } else { svs.clients[i].state = CS_CONNECTED; // when we get the next packet from a connected client, @@ -347,16 +331,15 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA } // run another frame to allow things to look at all connected clients - ge->RunFrame( sv.time ); + ge->RunFrame(sv.time); sv.time += 100; - re.G2API_SetTime(sv.time,G2T_SV_TIME); - + re.G2API_SetTime(sv.time, G2T_SV_TIME); // save systeminfo and serverinfo strings - SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString( CVAR_SYSTEMINFO ) ); + SV_SetConfigstring(CS_SYSTEMINFO, Cvar_InfoString(CVAR_SYSTEMINFO)); cvar_modifiedFlags &= ~CVAR_SYSTEMINFO; - SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) ); + SV_SetConfigstring(CS_SERVERINFO, Cvar_InfoString(CVAR_SERVERINFO)); cvar_modifiedFlags &= ~CVAR_SERVERINFO; // any media configstring setting now should issue a warning @@ -369,11 +352,11 @@ void SV_SpawnServer( const char *server, ForceReload_e eForceReload, qboolean bA Z_Validate(); Z_Validate(); - Com_Printf ("-----------------------------------\n"); + Com_Printf("-----------------------------------\n"); } #define G2_VERT_SPACE_SIZE 256 -#define G2_MINIHEAP_SIZE G2_VERT_SPACE_SIZE*1024 +#define G2_MINIHEAP_SIZE G2_VERT_SPACE_SIZE * 1024 /* =============== @@ -382,30 +365,30 @@ SV_Init Only called at main exe startup, not for each game =============== */ -void SV_Init (void) { - SV_AddOperatorCommands (); +void SV_Init(void) { + SV_AddOperatorCommands(); // serverinfo vars - Cvar_Get ("protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_ROM); - sv_mapname = Cvar_Get ("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM); + Cvar_Get("protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_ROM); + sv_mapname = Cvar_Get("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM); // systeminfo - Cvar_Get ("helpUsObi", "0", CVAR_SYSTEMINFO ); - sv_serverid = Cvar_Get ("sv_serverid", "0", CVAR_SYSTEMINFO | CVAR_ROM ); + Cvar_Get("helpUsObi", "0", CVAR_SYSTEMINFO); + sv_serverid = Cvar_Get("sv_serverid", "0", CVAR_SYSTEMINFO | CVAR_ROM); // server vars - sv_fps = Cvar_Get ("sv_fps", "20", CVAR_TEMP ); - sv_timeout = Cvar_Get ("sv_timeout", "120", CVAR_TEMP ); - sv_zombietime = Cvar_Get ("sv_zombietime", "2", CVAR_TEMP ); - Cvar_Get ("nextmap", "", CVAR_TEMP ); - sv_spawntarget = Cvar_Get ("spawntarget", "", 0 ); - - sv_reconnectlimit = Cvar_Get ("sv_reconnectlimit", "3", 0); - sv_showloss = Cvar_Get ("sv_showloss", "0", 0); - sv_killserver = Cvar_Get ("sv_killserver", "0", 0); - sv_mapChecksum = Cvar_Get ("sv_mapChecksum", "", CVAR_ROM); - sv_testsave = Cvar_Get ("sv_testsave", "0", 0); - sv_compress_saved_games = Cvar_Get ("sv_compress_saved_games", "1", 0); + sv_fps = Cvar_Get("sv_fps", "20", CVAR_TEMP); + sv_timeout = Cvar_Get("sv_timeout", "120", CVAR_TEMP); + sv_zombietime = Cvar_Get("sv_zombietime", "2", CVAR_TEMP); + Cvar_Get("nextmap", "", CVAR_TEMP); + sv_spawntarget = Cvar_Get("spawntarget", "", 0); + + sv_reconnectlimit = Cvar_Get("sv_reconnectlimit", "3", 0); + sv_showloss = Cvar_Get("sv_showloss", "0", 0); + sv_killserver = Cvar_Get("sv_killserver", "0", 0); + sv_mapChecksum = Cvar_Get("sv_mapChecksum", "", CVAR_ROM); + sv_testsave = Cvar_Get("sv_testsave", "0", 0); + sv_compress_saved_games = Cvar_Get("sv_compress_saved_games", "1", 0); // Only allocated once, no point in moving it around and fragmenting // create a heap for Ghoul2 to use for game side model vertex transforms used in collision detection @@ -415,7 +398,6 @@ void SV_Init (void) { } } - /* ================== SV_FinalMessage @@ -426,20 +408,19 @@ not just stuck on the outgoing message list, because the server is going to totally exit after returning from this function. ================== */ -void SV_FinalMessage( const char *message ) { +void SV_FinalMessage(const char *message) { client_t *cl = svs.clients; - SV_SendServerCommand( NULL, "print \"%s\"", message ); - SV_SendServerCommand( NULL, "disconnect" ); + SV_SendServerCommand(NULL, "print \"%s\"", message); + SV_SendServerCommand(NULL, "disconnect"); // send it twice, ignoring rate - if ( cl->state >= CS_CONNECTED ) { - SV_SendClientSnapshot( cl ); - SV_SendClientSnapshot( cl ); + if (cl->state >= CS_CONNECTED) { + SV_SendClientSnapshot(cl); + SV_SendClientSnapshot(cl); } } - /* ================ SV_Shutdown @@ -448,49 +429,47 @@ Called when each game quits, before Sys_Quit or Sys_Error ================ */ -void SV_Shutdown( const char *finalmsg ) { +void SV_Shutdown(const char *finalmsg) { int i; - if ( !com_sv_running || !com_sv_running->integer ) { + if (!com_sv_running || !com_sv_running->integer) { return; } - //Com_Printf( "----- Server Shutdown -----\n" ); + // Com_Printf( "----- Server Shutdown -----\n" ); - if ( svs.clients && !com_errorEntered ) { - SV_FinalMessage( finalmsg ); + if (svs.clients && !com_errorEntered) { + SV_FinalMessage(finalmsg); } SV_RemoveOperatorCommands(); SV_ShutdownGameProgs(qfalse); - if (svs.snapshotEntities) - { + if (svs.snapshotEntities) { Z_Free(svs.snapshotEntities); svs.snapshotEntities = NULL; } - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( sv.configstrings[i] ) { - Z_Free( sv.configstrings[i] ); + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (sv.configstrings[i]) { + Z_Free(sv.configstrings[i]); } } // free current level - memset( &sv, 0, sizeof( sv ) ); + memset(&sv, 0, sizeof(sv)); // free server static data - if ( svs.clients ) { + if (svs.clients) { SV_FreeClient(svs.clients); - Z_Free( svs.clients ); + Z_Free(svs.clients); } - memset( &svs, 0, sizeof( svs ) ); + memset(&svs, 0, sizeof(svs)); // Ensure we free any memory used by the leaf cache. CM_CleanLeafCache(); - Cvar_Set( "sv_running", "0" ); + Cvar_Set("sv_running", "0"); - //Com_Printf( "---------------------------\n" ); + // Com_Printf( "---------------------------\n" ); } - diff --git a/code/server/sv_main.cpp b/code/server/sv_main.cpp index 88d41de144..4356fd6624 100644 --- a/code/server/sv_main.cpp +++ b/code/server/sv_main.cpp @@ -27,29 +27,29 @@ along with this program; if not, see . /* Ghoul2 Insert Start */ -#if !defined (MINIHEAP_H_INC) - #include "../qcommon/MiniHeap.h" +#if !defined(MINIHEAP_H_INC) +#include "../qcommon/MiniHeap.h" #endif /* Ghoul2 Insert End */ -serverStatic_t svs; // persistant server info -server_t sv; // local server -game_export_t *ge; - -cvar_t *sv_fps; // time rate for running non-clients -cvar_t *sv_timeout; // seconds without any message -cvar_t *sv_zombietime; // seconds to sink messages after disconnect -cvar_t *sv_reconnectlimit; // minimum seconds between connect messages -cvar_t *sv_showloss; // report when usercmds are lost -cvar_t *sv_killserver; // menu system can set to 1 to shut server down -cvar_t *sv_mapname; -cvar_t *sv_spawntarget; -cvar_t *sv_mapChecksum; -cvar_t *sv_serverid; -cvar_t *sv_testsave; // Run the savegame enumeration every game frame -cvar_t *sv_compress_saved_games; // compress the saved games on the way out (only affect saver, loader can read both) +serverStatic_t svs; // persistant server info +server_t sv; // local server +game_export_t *ge; + +cvar_t *sv_fps; // time rate for running non-clients +cvar_t *sv_timeout; // seconds without any message +cvar_t *sv_zombietime; // seconds to sink messages after disconnect +cvar_t *sv_reconnectlimit; // minimum seconds between connect messages +cvar_t *sv_showloss; // report when usercmds are lost +cvar_t *sv_killserver; // menu system can set to 1 to shut server down +cvar_t *sv_mapname; +cvar_t *sv_spawntarget; +cvar_t *sv_mapChecksum; +cvar_t *sv_serverid; +cvar_t *sv_testsave; // Run the savegame enumeration every game frame +cvar_t *sv_compress_saved_games; // compress the saved games on the way out (only affect saver, loader can read both) /* ============================================================================= @@ -66,13 +66,13 @@ SV_ExpandNewlines Converts newlines to "\n" so a line prints nicer =============== */ -char *SV_ExpandNewlines( char *in ) { - static char string[1024]; - size_t l; +char *SV_ExpandNewlines(char *in) { + static char string[1024]; + size_t l; l = 0; - while ( *in && l < sizeof(string) - 3 ) { - if ( *in == '\n' ) { + while (*in && l < sizeof(string) - 3) { + if (*in == '\n') { string[l++] = '\\'; string[l++] = 'n'; } else { @@ -93,24 +93,23 @@ The given command will be transmitted to the client, and is guaranteed to not have future snapshot_t executed before it is executed ====================== */ -void SV_AddServerCommand( client_t *client, const char *cmd ) { - int index; +void SV_AddServerCommand(client_t *client, const char *cmd) { + int index; // if we would be losing an old command that hasn't been acknowledged, // we must drop the connection - if ( client->reliableSequence - client->reliableAcknowledge > MAX_RELIABLE_COMMANDS ) { - SV_DropClient( client, "Server command overflow" ); + if (client->reliableSequence - client->reliableAcknowledge > MAX_RELIABLE_COMMANDS) { + SV_DropClient(client, "Server command overflow"); return; } client->reliableSequence++; - index = client->reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 ); - if ( client->reliableCommands[ index ] ) { - Z_Free( client->reliableCommands[ index ] ); + index = client->reliableSequence & (MAX_RELIABLE_COMMANDS - 1); + if (client->reliableCommands[index]) { + Z_Free(client->reliableCommands[index]); } - client->reliableCommands[ index ] = CopyString( cmd ); + client->reliableCommands[index] = CopyString(cmd); } - /* ================= SV_SendServerCommand @@ -121,41 +120,39 @@ A NULL client will broadcast to all clients ================= */ void SV_SendServerCommand(client_t *cl, const char *fmt, ...) { - va_list argptr; - byte message[MAX_MSGLEN]; - client_t *client; - int j; + va_list argptr; + byte message[MAX_MSGLEN]; + client_t *client; + int j; message[0] = svc_serverCommand; - va_start (argptr,fmt); - Q_vsnprintf( (char *)message+1, sizeof(message)-1, fmt, argptr ); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf((char *)message + 1, sizeof(message) - 1, fmt, argptr); + va_end(argptr); // Fix to http://aluigi.altervista.org/adv/q3msgboom-adv.txt // The actual cause of the bug is probably further downstream // and should maybe be addressed later, but this certainly // fixes the problem for now - if ( strlen ((char *)message+1) > 1022 ) { + if (strlen((char *)message + 1) > 1022) { return; } - if ( cl != NULL ) { - SV_AddServerCommand( cl, (char *)message ); + if (cl != NULL) { + SV_AddServerCommand(cl, (char *)message); return; } // send the data to all relevent clients - for (j = 0, client = svs.clients; j < 1 ; j++, client++) { - if ( client->state < CS_PRIMED ) { + for (j = 0, client = svs.clients; j < 1; j++, client++) { + if (client->state < CS_PRIMED) { continue; } - SV_AddServerCommand( client, (char *)message ); + SV_AddServerCommand(client, (char *)message); } } - - /* ============================================================================== @@ -173,44 +170,44 @@ and all connected players. Used for getting detailed information after the simple info query. ================ */ -void SVC_Status( netadr_t from ) { - char player[1024]; - char status[MAX_MSGLEN]; - int i; - client_t *cl; - int statusLength; - int playerLength; - int score; - char infostring[MAX_INFO_STRING]; - - strcpy( infostring, Cvar_InfoString( CVAR_SERVERINFO ) ); +void SVC_Status(netadr_t from) { + char player[1024]; + char status[MAX_MSGLEN]; + int i; + client_t *cl; + int statusLength; + int playerLength; + int score; + char infostring[MAX_INFO_STRING]; + + strcpy(infostring, Cvar_InfoString(CVAR_SERVERINFO)); // echo back the parameter to status. so servers can use it as a challenge // to prevent timed spoofed reply packets that add ghost servers - Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) ); + Info_SetValueForKey(infostring, "challenge", Cmd_Argv(1)); status[0] = 0; statusLength = 0; - for (i=0 ; i < 1 ; i++) { + for (i = 0; i < 1; i++) { cl = &svs.clients[i]; - if ( cl->state >= CS_CONNECTED ) { - if ( cl->gentity && cl->gentity->client ) { + if (cl->state >= CS_CONNECTED) { + if (cl->gentity && cl->gentity->client) { score = cl->gentity->client->persistant[PERS_SCORE]; } else { score = 0; } - Com_sprintf( player, sizeof( player ), "%i %i \"%s\"\n", score, cl->name ); + Com_sprintf(player, sizeof(player), "%i %i \"%s\"\n", score, cl->name); playerLength = strlen(player); - if (statusLength + playerLength >= (int)sizeof(status) ) { - break; // can't hold any more + if (statusLength + playerLength >= (int)sizeof(status)) { + break; // can't hold any more } - strcpy (status + statusLength, player); + strcpy(status + statusLength, player); statusLength += playerLength; } } - NET_OutOfBandPrint( NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status ); + NET_OutOfBandPrint(NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status); } /* @@ -221,13 +218,13 @@ Responds with a short info message that should be enough to determine if a user is interested in a server to do a full status ================ */ -static void SVC_Info( netadr_t from ) { - int i, count; - char infostring[MAX_INFO_STRING]; +static void SVC_Info(netadr_t from) { + int i, count; + char infostring[MAX_INFO_STRING]; count = 0; - for ( i = 0 ; i < 1 ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = 0; i < 1; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { count++; } } @@ -236,18 +233,17 @@ static void SVC_Info( netadr_t from ) { // echo back the parameter to status. so servers can use it as a challenge // to prevent timed spoofed reply packets that add ghost servers - Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) ); + Info_SetValueForKey(infostring, "challenge", Cmd_Argv(1)); - Info_SetValueForKey( infostring, "protocol", va("%i", PROTOCOL_VERSION) ); - //Info_SetValueForKey( infostring, "hostname", sv_hostname->string ); - Info_SetValueForKey( infostring, "mapname", sv_mapname->string ); - Info_SetValueForKey( infostring, "clients", va("%i", count) ); - Info_SetValueForKey( infostring, "sv_maxclients", va("%i", 1) ); + Info_SetValueForKey(infostring, "protocol", va("%i", PROTOCOL_VERSION)); + // Info_SetValueForKey( infostring, "hostname", sv_hostname->string ); + Info_SetValueForKey(infostring, "mapname", sv_mapname->string); + Info_SetValueForKey(infostring, "clients", va("%i", count)); + Info_SetValueForKey(infostring, "sv_maxclients", va("%i", 1)); - NET_OutOfBandPrint( NS_SERVER, from, "infoResponse\n%s", infostring ); + NET_OutOfBandPrint(NS_SERVER, from, "infoResponse\n%s", infostring); } - /* ================= SV_ConnectionlessPacket @@ -258,37 +254,35 @@ Clients that are in the game can still send connectionless packets. ================= */ -static void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) { - char *s; - const char *c; +static void SV_ConnectionlessPacket(netadr_t from, msg_t *msg) { + char *s; + const char *c; - MSG_BeginReading( msg ); - MSG_ReadLong( msg ); // skip the -1 marker + MSG_BeginReading(msg); + MSG_ReadLong(msg); // skip the -1 marker - s = MSG_ReadStringLine( msg ); + s = MSG_ReadStringLine(msg); - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); c = Cmd_Argv(0); - Com_DPrintf ("SV packet %s : %s\n", NET_AdrToString(from), c); - - if (!strcmp(c,"getstatus")) { - SVC_Status( from ); - } else if (!strcmp(c,"getinfo")) { - SVC_Info( from ); - } else if (!strcmp(c,"connect")) { - SV_DirectConnect( from ); - } else if (!strcmp(c,"disconnect")) { + Com_DPrintf("SV packet %s : %s\n", NET_AdrToString(from), c); + + if (!strcmp(c, "getstatus")) { + SVC_Status(from); + } else if (!strcmp(c, "getinfo")) { + SVC_Info(from); + } else if (!strcmp(c, "connect")) { + SV_DirectConnect(from); + } else if (!strcmp(c, "disconnect")) { // if a client starts up a local server, we may see some spurious // server disconnect messages when their new server sees our final // sequenced messages to the old client } else { - Com_DPrintf ("bad connectionless packet from %s:\n%s\n" - , NET_AdrToString (from), s); + Com_DPrintf("bad connectionless packet from %s:\n%s\n", NET_AdrToString(from), s); } } - //============================================================================ /* @@ -296,30 +290,30 @@ static void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) { SV_ReadPackets ================= */ -void SV_PacketEvent( netadr_t from, msg_t *msg ) { - int i; - client_t *cl; - int qport; +void SV_PacketEvent(netadr_t from, msg_t *msg) { + int i; + client_t *cl; + int qport; // check for connectionless packet (0xffffffff) first - if ( msg->cursize >= 4 && *(int *)msg->data == -1) { - SV_ConnectionlessPacket( from, msg ); + if (msg->cursize >= 4 && *(int *)msg->data == -1) { + SV_ConnectionlessPacket(from, msg); return; } // read the qport out of the message so we can fix up // stupid address translating routers - MSG_BeginReading( msg ); - MSG_ReadLong( msg ); // sequence number - MSG_ReadLong( msg ); // sequence number - qport = MSG_ReadShort( msg ) & 0xffff; + MSG_BeginReading(msg); + MSG_ReadLong(msg); // sequence number + MSG_ReadLong(msg); // sequence number + qport = MSG_ReadShort(msg) & 0xffff; // find which client the message is from - for (i=0, cl=svs.clients ; i < 1 ; i++,cl++) { + for (i = 0, cl = svs.clients; i < 1; i++, cl++) { if (cl->state == CS_FREE) { continue; } - if ( !NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) ) { + if (!NET_CompareBaseAdr(from, cl->netchan.remoteAddress)) { continue; } // it is possible to have multiple clients from a single IP @@ -332,7 +326,7 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // some address translating routers periodically change UDP // port assignments if (cl->netchan.remoteAddress.port != from.port) { - Com_Printf( "SV_ReadPackets: fixing up a translated port\n" ); + Com_Printf("SV_ReadPackets: fixing up a translated port\n"); cl->netchan.remoteAddress.port = from.port; } @@ -342,10 +336,9 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // to make sure they don't need to retransmit the final // reliable message, but they don't do any other processing if (cl->state != CS_ZOMBIE) { - cl->lastPacketTime = sv.time; // don't timeout - cl->frames[ cl->netchan.incomingAcknowledged & PACKET_MASK ] - .messageAcked = sv.time; - SV_ExecuteClientMessage( cl, msg ); + cl->lastPacketTime = sv.time; // don't timeout + cl->frames[cl->netchan.incomingAcknowledged & PACKET_MASK].messageAcked = sv.time; + SV_ExecuteClientMessage(cl, msg); } } return; @@ -353,36 +346,35 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // if we received a sequenced packet from an address we don't reckognize, // send an out of band disconnect packet to it - NET_OutOfBandPrint( NS_SERVER, from, "disconnect" ); + NET_OutOfBandPrint(NS_SERVER, from, "disconnect"); } // If a packet has not been received from a client for timeout->integer seconds, drop the conneciton. // Server time is used instead of realtime to avoid dropping the local client while debugging. // When a client is normally dropped, the client_t goes into a zombie state for a few seconds to make sure any final // reliable message gets resent if necessary -void SV_CheckTimeouts( void ) { +void SV_CheckTimeouts(void) { client_t *cl = svs.clients; int droppoint = sv.time - 1000 * sv_timeout->integer; int zombiepoint = sv.time - 1000 * sv_zombietime->integer; // message times may be wrong across a changelevel - if ( cl->lastPacketTime > sv.time ) + if (cl->lastPacketTime > sv.time) cl->lastPacketTime = sv.time; - if ( cl->state == CS_ZOMBIE && cl->lastPacketTime < zombiepoint ) { - cl->state = CS_FREE; // can now be reused + if (cl->state == CS_ZOMBIE && cl->lastPacketTime < zombiepoint) { + cl->state = CS_FREE; // can now be reused return; } - if ( cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint ) { + if (cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint) { // wait several frames so a debugger session doesn't cause a timeout - if ( ++cl->timeoutCount > 5 ) { - SV_DropClient( cl, "timed out" ); + if (++cl->timeoutCount > 5) { + SV_DropClient(cl, "timed out"); cl->state = CS_FREE; // don't bother with zombie state } - } - else + } else cl->timeoutCount = 0; } @@ -391,8 +383,8 @@ void SV_CheckTimeouts( void ) { SV_CheckPaused ================== */ -qboolean SV_CheckPaused( void ) { - if ( !cl_paused->integer ) { +qboolean SV_CheckPaused(void) { + if (!cl_paused->integer) { return qfalse; } @@ -418,7 +410,6 @@ We will keep track of this here: */ - /* ================== SV_Frame @@ -427,53 +418,51 @@ Player movement occurs as a result of packet events, which happen before SV_Frame is called ================== */ -extern cvar_t *cl_newClock; -void SV_Frame( int msec,float fractionMsec ) { - int frameMsec; - int startTime=0; +extern cvar_t *cl_newClock; +void SV_Frame(int msec, float fractionMsec) { + int frameMsec; + int startTime = 0; // the menu kills the server with this cvar - if ( sv_killserver->integer ) { - SV_Shutdown ("Server was killed.\n"); - Cvar_Set( "sv_killserver", "0" ); + if (sv_killserver->integer) { + SV_Shutdown("Server was killed.\n"); + Cvar_Set("sv_killserver", "0"); return; } - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return; } - extern void SE_CheckForLanguageUpdates(void); - SE_CheckForLanguageUpdates(); // will fast-return else load different language if menu changed it + extern void SE_CheckForLanguageUpdates(void); + SE_CheckForLanguageUpdates(); // will fast-return else load different language if menu changed it // allow pause if only the local client is connected - if ( SV_CheckPaused() ) { + if (SV_CheckPaused()) { return; } // go ahead and let time slip if the server really hitched badly - if ( msec > 1000 ) { - Com_DPrintf( "SV_Frame: Truncating msec of %i to 1000\n", msec ); + if (msec > 1000) { + Com_DPrintf("SV_Frame: Truncating msec of %i to 1000\n", msec); msec = 1000; } // if it isn't time for the next frame, do nothing - if ( sv_fps->integer < 1 ) { - Cvar_Set( "sv_fps", "10" ); + if (sv_fps->integer < 1) { + Cvar_Set("sv_fps", "10"); } - frameMsec = 1000 / sv_fps->integer ; + frameMsec = 1000 / sv_fps->integer; sv.timeResidual += msec; - sv.timeResidualFraction+=fractionMsec; - if (sv.timeResidualFraction>=1.0f) - { - sv.timeResidualFraction-=1.0f; - if (cl_newClock&&cl_newClock->integer) - { + sv.timeResidualFraction += fractionMsec; + if (sv.timeResidualFraction >= 1.0f) { + sv.timeResidualFraction -= 1.0f; + if (cl_newClock && cl_newClock->integer) { sv.timeResidual++; } } - if ( sv.timeResidual < frameMsec ) { + if (sv.timeResidual < frameMsec) { return; } @@ -481,50 +470,49 @@ void SV_Frame( int msec,float fractionMsec ) { // level, which will force the time back to zero, rather // than checking for negative time wraparound everywhere. // 2giga-milliseconds = 23 days, so it won't be too often - if ( sv.time > 0x70000000 ) { - SV_Shutdown( "Restarting server due to time wrapping" ); + if (sv.time > 0x70000000) { + SV_Shutdown("Restarting server due to time wrapping"); Com_Printf("You win. if you can play this long and not die, you deserve to win.\n"); return; } // update infostrings if anything has been changed - if ( cvar_modifiedFlags & CVAR_SERVERINFO ) { - SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) ); + if (cvar_modifiedFlags & CVAR_SERVERINFO) { + SV_SetConfigstring(CS_SERVERINFO, Cvar_InfoString(CVAR_SERVERINFO)); cvar_modifiedFlags &= ~CVAR_SERVERINFO; } - if ( cvar_modifiedFlags & CVAR_SYSTEMINFO ) { - SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString( CVAR_SYSTEMINFO ) ); + if (cvar_modifiedFlags & CVAR_SYSTEMINFO) { + SV_SetConfigstring(CS_SYSTEMINFO, Cvar_InfoString(CVAR_SYSTEMINFO)); cvar_modifiedFlags &= ~CVAR_SYSTEMINFO; } - if ( com_speeds->integer ) { - startTime = Sys_Milliseconds (); + if (com_speeds->integer) { + startTime = Sys_Milliseconds(); } -// SV_BotFrame( sv.time ); + // SV_BotFrame( sv.time ); // run the game simulation in chunks - while ( sv.timeResidual >= frameMsec ) { + while (sv.timeResidual >= frameMsec) { sv.timeResidual -= frameMsec; sv.time += frameMsec; - re.G2API_SetTime(sv.time,G2T_SV_TIME); + re.G2API_SetTime(sv.time, G2T_SV_TIME); // let everything in the world think and move - ge->RunFrame( sv.time ); + ge->RunFrame(sv.time); } - if ( com_speeds->integer ) { - time_game = Sys_Milliseconds () - startTime; + if (com_speeds->integer) { + time_game = Sys_Milliseconds() - startTime; } - SG_TestSave(); // returns immediately if not active, used for fake-save-every-cycle to test (mainly) Icarus disk code + SG_TestSave(); // returns immediately if not active, used for fake-save-every-cycle to test (mainly) Icarus disk code // check timeouts SV_CheckTimeouts(); // send messages back to the clients - SV_SendClientMessages (); + SV_SendClientMessages(); } //============================================================================ - diff --git a/code/server/sv_savegame.cpp b/code/server/sv_savegame.cpp index 3a230b541f..4de40a3222 100644 --- a/code/server/sv_savegame.cpp +++ b/code/server/sv_savegame.cpp @@ -27,8 +27,8 @@ along with this program; if not, see . #define JPEG_IMAGE_QUALITY 95 //#define USE_LAST_SAVE_FROM_THIS_MAP // enable this if you want to use the last explicity-loaded savegame from this map - // when respawning after dying, else it'll just load "auto" regardless - // (EF1 behaviour). I should maybe time/date check them though? +// when respawning after dying, else it'll just load "auto" regardless +// (EF1 behaviour). I should maybe time/date check them though? #include "server.h" #include "../qcommon/stringed_ingame.h" @@ -41,16 +41,15 @@ along with this program; if not, see . #include "qcommon/ojk_saved_game.h" #include "qcommon/ojk_saved_game_helper.h" - -static char saveGameComment[iSG_COMMENT_SIZE]; +static char saveGameComment[iSG_COMMENT_SIZE]; //#define SG_PROFILE // enable for debug save stats if you want -int giSaveGameVersion; // filled in when a savegame file is opened +int giSaveGameVersion; // filled in when a savegame file is opened SavedGameJustLoaded_e eSavedGameJustLoaded = eNO; -char sLastSaveFileLoaded[MAX_QPATH]={0}; +char sLastSaveFileLoaded[MAX_QPATH] = {0}; #ifdef JK2_MODE #define iSG_MAPCMD_SIZE (MAX_TOKEN_CHARS) @@ -60,68 +59,52 @@ char sLastSaveFileLoaded[MAX_QPATH]={0}; static char *SG_GetSaveGameMapName(const char *psPathlessBaseName); - #ifdef SG_PROFILE -class CChid -{ -private: - int m_iCount; - int m_iSize; -public: - CChid() - { +class CChid { + private: + int m_iCount; + int m_iSize; + + public: + CChid() { m_iCount = 0; m_iSize = 0; } - void Add(int iLength) - { + void Add(int iLength) { m_iCount++; m_iSize += iLength; } - int GetCount() - { - return m_iCount; - } - int GetSize() - { - return m_iSize; - } + int GetCount() { return m_iCount; } + int GetSize() { return m_iSize; } }; typedef map CChidInfo_t; -CChidInfo_t save_info; +CChidInfo_t save_info; #endif -static const char *GetString_FailedToOpenSaveGame(const char *psFilename, qboolean bOpen) -{ +static const char *GetString_FailedToOpenSaveGame(const char *psFilename, qboolean bOpen) { static char sTemp[256]; - strcpy(sTemp,S_COLOR_RED); + strcpy(sTemp, S_COLOR_RED); #ifdef JK2_MODE const char *psReference = bOpen ? "MENUS3_FAILED_TO_OPEN_SAVEGAME" : "MENUS3_FAILED_TO_CREATE_SAVEGAME"; #else const char *psReference = bOpen ? "MENUS_FAILED_TO_OPEN_SAVEGAME" : "MENUS3_FAILED_TO_CREATE_SAVEGAME"; #endif - Q_strncpyz(sTemp + strlen(sTemp), va( SE_GetString(psReference), psFilename),sizeof(sTemp)); - strcat(sTemp,"\n"); + Q_strncpyz(sTemp + strlen(sTemp), va(SE_GetString(psReference), psFilename), sizeof(sTemp)); + strcat(sTemp, "\n"); return sTemp; } -void SG_WipeSavegame( - const char* psPathlessBaseName) -{ - ojk::SavedGame::remove( - psPathlessBaseName); -} +void SG_WipeSavegame(const char *psPathlessBaseName) { ojk::SavedGame::remove(psPathlessBaseName); } // called from the ERR_DROP stuff just in case the error occured during loading of a saved game, because if // we didn't do this then we'd run out of quake file handles after the 8th load fail... // -void SG_Shutdown() -{ - ojk::SavedGame& saved_game = ojk::SavedGame::get_instance(); +void SG_Shutdown() { + ojk::SavedGame &saved_game = ojk::SavedGame::get_instance(); saved_game.close(); @@ -135,202 +118,173 @@ void SG_Shutdown() gbAlreadyDoingLoad = qfalse; } -void SV_WipeGame_f(void) -{ - if (Cmd_Argc() != 2) - { - Com_Printf (S_COLOR_RED "USAGE: wipe \n"); +void SV_WipeGame_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf(S_COLOR_RED "USAGE: wipe \n"); return; } - if (!Q_stricmp (Cmd_Argv(1), "auto") ) - { - Com_Printf (S_COLOR_RED "Can't wipe 'auto'\n"); + if (!Q_stricmp(Cmd_Argv(1), "auto")) { + Com_Printf(S_COLOR_RED "Can't wipe 'auto'\n"); return; } SG_WipeSavegame(Cmd_Argv(1)); -// Com_Printf("%s has been wiped\n", Cmd_Argv(1)); // wurde gelöscht in german, but we've only got one string -// Com_Printf("Ok\n"); // no localization of this + // Com_Printf("%s has been wiped\n", Cmd_Argv(1)); // wurde gelöscht in german, but we've only got one string + // Com_Printf("Ok\n"); // no localization of this } /* // Store given string in saveGameComment for later use when game is // actually saved */ -void SG_StoreSaveGameComment(const char *sComment) -{ - memmove(saveGameComment,sComment,iSG_COMMENT_SIZE); -} +void SG_StoreSaveGameComment(const char *sComment) { memmove(saveGameComment, sComment, iSG_COMMENT_SIZE); } -qboolean SV_TryLoadTransition( const char *mapname ) -{ - char *psFilename = va( "hub/%s", mapname ); +qboolean SV_TryLoadTransition(const char *mapname) { + char *psFilename = va("hub/%s", mapname); - Com_Printf (S_COLOR_CYAN "Restoring game \"%s\"...\n", psFilename); + Com_Printf(S_COLOR_CYAN "Restoring game \"%s\"...\n", psFilename); - if ( !SG_ReadSavegame( psFilename ) ) - {//couldn't load a savegame + if (!SG_ReadSavegame(psFilename)) { // couldn't load a savegame return qfalse; } #ifdef JK2_MODE - Com_Printf (S_COLOR_CYAN "Done.\n"); + Com_Printf(S_COLOR_CYAN "Done.\n"); #else - Com_Printf (S_COLOR_CYAN "%s.\n",SE_GetString("MENUS_DONE")); + Com_Printf(S_COLOR_CYAN "%s.\n", SE_GetString("MENUS_DONE")); #endif return qtrue; } qboolean gbAlreadyDoingLoad = qfalse; -void SV_LoadGame_f(void) -{ - if (gbAlreadyDoingLoad) - { - Com_DPrintf ("( Already loading, ignoring extra 'load' commands... )\n"); +void SV_LoadGame_f(void) { + if (gbAlreadyDoingLoad) { + Com_DPrintf("( Already loading, ignoring extra 'load' commands... )\n"); return; } -// // check server is running -// // -// if ( !com_sv_running->integer ) -// { -// Com_Printf( "Server is not running\n" ); -// return; -// } + // // check server is running + // // + // if ( !com_sv_running->integer ) + // { + // Com_Printf( "Server is not running\n" ); + // return; + // } - if (Cmd_Argc() != 2) - { - Com_Printf ("USAGE: load \n"); + if (Cmd_Argc() != 2) { + Com_Printf("USAGE: load \n"); return; } const char *psFilename = Cmd_Argv(1); - if (strstr (psFilename, "..") || strstr (psFilename, "/") || strstr (psFilename, "\\") ) - { - Com_Printf (S_COLOR_RED "Bad loadgame name.\n"); + if (strstr(psFilename, "..") || strstr(psFilename, "/") || strstr(psFilename, "\\")) { + Com_Printf(S_COLOR_RED "Bad loadgame name.\n"); return; } - if (!Q_stricmp (psFilename, "current")) - { - Com_Printf (S_COLOR_RED "Can't load from \"current\"\n"); + if (!Q_stricmp(psFilename, "current")) { + Com_Printf(S_COLOR_RED "Can't load from \"current\"\n"); return; } // special case, if doing a respawn then check that the available auto-save (if any) is from the same map // as we're currently on (if in a map at all), if so, load that "auto", else re-load the last-loaded file... // - if (!Q_stricmp(psFilename, "*respawn")) - { - psFilename = "auto"; // default to standard respawn behaviour + if (!Q_stricmp(psFilename, "*respawn")) { + psFilename = "auto"; // default to standard respawn behaviour // see if there's a last-loaded file to even check against as regards loading... // - if ( sLastSaveFileLoaded[0] ) - { + if (sLastSaveFileLoaded[0]) { const char *psServerInfo = sv.configstrings[CS_SERVERINFO]; - const char *psMapName = Info_ValueForKey( psServerInfo, "mapname" ); + const char *psMapName = Info_ValueForKey(psServerInfo, "mapname"); char *psMapNameOfAutoSave = SG_GetSaveGameMapName("auto"); - if ( !Q_stricmp(psMapName,"_brig") ) - {//if you're in the brig and there is no autosave, load the last loaded savegame - if ( !psMapNameOfAutoSave ) - { + if (!Q_stricmp(psMapName, "_brig")) { // if you're in the brig and there is no autosave, load the last loaded savegame + if (!psMapNameOfAutoSave) { psFilename = sLastSaveFileLoaded; } - } - else - { + } else { #ifdef USE_LAST_SAVE_FROM_THIS_MAP // if the map name within the name of the last save file we explicitly loaded is the same // as the current map, then use that... // char *psMapNameOfLastSaveFileLoaded = SG_GetSaveGameMapName(sLastSaveFileLoaded); - if (!Q_stricmp(psMapName,psMapNameOfLastSaveFileLoaded))) + if (!Q_stricmp(psMapName, psMapNameOfLastSaveFileLoaded))) { psFilename = sLastSaveFileLoaded; } else #endif - if (!(psMapName && psMapNameOfAutoSave && !Q_stricmp(psMapName,psMapNameOfAutoSave))) - { + if (!(psMapName && psMapNameOfAutoSave && !Q_stricmp(psMapName, psMapNameOfAutoSave))) { // either there's no auto file, or it's from a different map to the one we've just died on... // psFilename = sLastSaveFileLoaded; } } } - //default will continue to load auto + // default will continue to load auto } #ifdef JK2_MODE - Com_Printf (S_COLOR_CYAN "Loading game \"%s\"...\n", psFilename); + Com_Printf(S_COLOR_CYAN "Loading game \"%s\"...\n", psFilename); #else - Com_Printf (S_COLOR_CYAN "%s\n",va(SE_GetString("MENUS_LOADING_MAPNAME"), psFilename)); + Com_Printf(S_COLOR_CYAN "%s\n", va(SE_GetString("MENUS_LOADING_MAPNAME"), psFilename)); #endif gbAlreadyDoingLoad = qtrue; if (!SG_ReadSavegame(psFilename)) { gbAlreadyDoingLoad = qfalse; // do NOT do this here now, need to wait until client spawn, unless the load failed. - } else - { + } else { #ifdef JK2_MODE - Com_Printf (S_COLOR_CYAN "Done.\n"); + Com_Printf(S_COLOR_CYAN "Done.\n"); #else - Com_Printf (S_COLOR_CYAN "%s.\n",SE_GetString("MENUS_DONE")); + Com_Printf(S_COLOR_CYAN "%s.\n", SE_GetString("MENUS_DONE")); #endif } } qboolean SG_GameAllowedToSaveHere(qboolean inCamera); - -//JLF notes +// JLF notes // save game will be in charge of creating a new directory -void SV_SaveGame_f(void) -{ +void SV_SaveGame_f(void) { // check server is running // - if ( !com_sv_running->integer ) - { - Com_Printf( S_COLOR_RED "Server is not running\n" ); + if (!com_sv_running->integer) { + Com_Printf(S_COLOR_RED "Server is not running\n"); return; } - if (sv.state != SS_GAME) - { - Com_Printf (S_COLOR_RED "You must be in a game to save.\n"); + if (sv.state != SS_GAME) { + Com_Printf(S_COLOR_RED "You must be in a game to save.\n"); return; } // check args... // - if ( Cmd_Argc() != 2 ) - { - Com_Printf( "USAGE: save \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("USAGE: save \n"); return; } - - if (svs.clients[0].frames[svs.clients[0].netchan.outgoingSequence & PACKET_MASK].ps.stats[STAT_HEALTH] <= 0) - { + if (svs.clients[0].frames[svs.clients[0].netchan.outgoingSequence & PACKET_MASK].ps.stats[STAT_HEALTH] <= 0) { #ifdef JK2_MODE - Com_Printf (S_COLOR_RED "\nCan't savegame while dead!\n"); + Com_Printf(S_COLOR_RED "\nCan't savegame while dead!\n"); #else - Com_Printf (S_COLOR_RED "\n%s\n", SE_GetString("SP_INGAME_CANT_SAVE_DEAD")); + Com_Printf(S_COLOR_RED "\n%s\n", SE_GetString("SP_INGAME_CANT_SAVE_DEAD")); #endif return; } - //this check catches deaths even the instant you die, like during a slo-mo death! - gentity_t *svent; + // this check catches deaths even the instant you die, like during a slo-mo death! + gentity_t *svent; svent = SV_GentityNum(0); - if (svent->client->stats[STAT_HEALTH]<=0) - { + if (svent->client->stats[STAT_HEALTH] <= 0) { #ifdef JK2_MODE - Com_Printf (S_COLOR_RED "\nCan't savegame while dead!\n"); + Com_Printf(S_COLOR_RED "\nCan't savegame while dead!\n"); #else - Com_Printf (S_COLOR_RED "\n%s\n", SE_GetString("SP_INGAME_CANT_SAVE_DEAD")); + Com_Printf(S_COLOR_RED "\n%s\n", SE_GetString("SP_INGAME_CANT_SAVE_DEAD")); #endif return; } @@ -340,173 +294,138 @@ void SV_SaveGame_f(void) Q_strncpyz(filename, psFilename, sizeof(filename)); - if (!Q_stricmp (filename, "current")) - { - Com_Printf (S_COLOR_RED "Can't save to 'current'\n"); + if (!Q_stricmp(filename, "current")) { + Com_Printf(S_COLOR_RED "Can't save to 'current'\n"); return; } - if (strstr (filename, "..") || strstr (filename, "/") || strstr (filename, "\\") ) - { - Com_Printf (S_COLOR_RED "Bad savegame name.\n"); + if (strstr(filename, "..") || strstr(filename, "/") || strstr(filename, "\\")) { + Com_Printf(S_COLOR_RED "Bad savegame name.\n"); return; } - if (!SG_GameAllowedToSaveHere(qfalse)) //full check - return; // this prevents people saving via quick-save now during cinematics. + if (!SG_GameAllowedToSaveHere(qfalse)) // full check + return; // this prevents people saving via quick-save now during cinematics. #ifdef JK2_MODE - if ( !Q_stricmp (filename, "quik*") || !Q_stricmp (filename, "auto*") ) - { + if (!Q_stricmp(filename, "quik*") || !Q_stricmp(filename, "auto*")) { SCR_PrecacheScreenshot(); - if ( filename[4]=='*' ) - filename[4]=0; //remove the * - SG_StoreSaveGameComment(""); // clear previous comment/description, which will force time/date comment. + if (filename[4] == '*') + filename[4] = 0; // remove the * + SG_StoreSaveGameComment(""); // clear previous comment/description, which will force time/date comment. } #else - if ( !Q_stricmp (filename, "auto") ) - { - SG_StoreSaveGameComment(""); // clear previous comment/description, which will force time/date comment. + if (!Q_stricmp(filename, "auto")) { + SG_StoreSaveGameComment(""); // clear previous comment/description, which will force time/date comment. } #endif #ifdef JK2_MODE - Com_Printf (S_COLOR_CYAN "Saving game \"%s\"...\n", filename); + Com_Printf(S_COLOR_CYAN "Saving game \"%s\"...\n", filename); #else - Com_Printf (S_COLOR_CYAN "%s \"%s\"...\n", SE_GetString("CON_TEXT_SAVING_GAME"), filename); + Com_Printf(S_COLOR_CYAN "%s \"%s\"...\n", SE_GetString("CON_TEXT_SAVING_GAME"), filename); #endif - if (SG_WriteSavegame(filename, qfalse)) - { + if (SG_WriteSavegame(filename, qfalse)) { #ifdef JK2_MODE - Com_Printf (S_COLOR_CYAN "Done.\n"); + Com_Printf(S_COLOR_CYAN "Done.\n"); #else - Com_Printf (S_COLOR_CYAN "%s.\n",SE_GetString("MENUS_DONE")); + Com_Printf(S_COLOR_CYAN "%s.\n", SE_GetString("MENUS_DONE")); #endif - } - else - { + } else { #ifdef JK2_MODE - Com_Printf (S_COLOR_RED "Failed.\n"); + Com_Printf(S_COLOR_RED "Failed.\n"); #else - Com_Printf (S_COLOR_RED "%s.\n",SE_GetString("MENUS_FAILED_TO_OPEN_SAVEGAME")); + Com_Printf(S_COLOR_RED "%s.\n", SE_GetString("MENUS_FAILED_TO_OPEN_SAVEGAME")); #endif } } - - //--------------- -static void WriteGame(qboolean autosave) -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +static void WriteGame(qboolean autosave) { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - saved_game.write_chunk( - INT_ID('G', 'A', 'M', 'E'), - autosave); + saved_game.write_chunk(INT_ID('G', 'A', 'M', 'E'), autosave); - if (autosave) - { + if (autosave) { // write out player ammo level, health, etc... // extern void SV_Player_EndOfLevelSave(void); - SV_Player_EndOfLevelSave(); // this sets up the various cvars needed, so we can then write them to disk + SV_Player_EndOfLevelSave(); // this sets up the various cvars needed, so we can then write them to disk // char s[MAX_STRING_CHARS]; // write health/armour etc... // - memset(s,0,sizeof(s)); - Cvar_VariableStringBuffer( sCVARNAME_PLAYERSAVE, s, sizeof(s) ); + memset(s, 0, sizeof(s)); + Cvar_VariableStringBuffer(sCVARNAME_PLAYERSAVE, s, sizeof(s)); - saved_game.write_chunk( - INT_ID('C', 'V', 'S', 'V'), - s); + saved_game.write_chunk(INT_ID('C', 'V', 'S', 'V'), s); // write ammo... // - memset(s,0,sizeof(s)); - Cvar_VariableStringBuffer( "playerammo", s, sizeof(s) ); + memset(s, 0, sizeof(s)); + Cvar_VariableStringBuffer("playerammo", s, sizeof(s)); - saved_game.write_chunk( - INT_ID('A', 'M', 'M', 'O'), - s); + saved_game.write_chunk(INT_ID('A', 'M', 'M', 'O'), s); // write inventory... // - memset(s,0,sizeof(s)); - Cvar_VariableStringBuffer( "playerinv", s, sizeof(s) ); + memset(s, 0, sizeof(s)); + Cvar_VariableStringBuffer("playerinv", s, sizeof(s)); - saved_game.write_chunk( - INT_ID('I', 'V', 'T', 'Y'), - s); + saved_game.write_chunk(INT_ID('I', 'V', 'T', 'Y'), s); // the new JK2 stuff - force powers, etc... // - memset(s,0,sizeof(s)); - Cvar_VariableStringBuffer( "playerfplvl", s, sizeof(s) ); + memset(s, 0, sizeof(s)); + Cvar_VariableStringBuffer("playerfplvl", s, sizeof(s)); - saved_game.write_chunk( - INT_ID('F', 'P', 'L', 'V'), - s); + saved_game.write_chunk(INT_ID('F', 'P', 'L', 'V'), s); } } -static qboolean ReadGame (void) -{ +static qboolean ReadGame(void) { qboolean qbAutoSave = qfalse; - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - saved_game.read_chunk( - INT_ID('G', 'A', 'M', 'E'), - qbAutoSave); + saved_game.read_chunk(INT_ID('G', 'A', 'M', 'E'), qbAutoSave); - if (qbAutoSave) - { - char s[MAX_STRING_CHARS]={0}; + if (qbAutoSave) { + char s[MAX_STRING_CHARS] = {0}; // read health/armour etc... // - memset(s,0,sizeof(s)); + memset(s, 0, sizeof(s)); - saved_game.read_chunk( - INT_ID('C', 'V', 'S', 'V'), - s); + saved_game.read_chunk(INT_ID('C', 'V', 'S', 'V'), s); - Cvar_Set( sCVARNAME_PLAYERSAVE, s ); + Cvar_Set(sCVARNAME_PLAYERSAVE, s); // read ammo... // - memset(s,0,sizeof(s)); + memset(s, 0, sizeof(s)); - saved_game.read_chunk( - INT_ID('A', 'M', 'M', 'O'), - s); + saved_game.read_chunk(INT_ID('A', 'M', 'M', 'O'), s); - Cvar_Set( "playerammo", s); + Cvar_Set("playerammo", s); // read inventory... // - memset(s,0,sizeof(s)); + memset(s, 0, sizeof(s)); - saved_game.read_chunk( - INT_ID('I', 'V', 'T', 'Y'), - s); + saved_game.read_chunk(INT_ID('I', 'V', 'T', 'Y'), s); - Cvar_Set( "playerinv", s); + Cvar_Set("playerinv", s); // read force powers... // - memset(s,0,sizeof(s)); + memset(s, 0, sizeof(s)); - saved_game.read_chunk( - INT_ID('F', 'P', 'L', 'V'), - s); + saved_game.read_chunk(INT_ID('F', 'P', 'L', 'V'), s); - Cvar_Set( "playerfplvl", s ); + Cvar_Set("playerfplvl", s); } return qbAutoSave; @@ -514,26 +433,22 @@ static qboolean ReadGame (void) //--------------- - // write all CVAR_SAVEGAME cvars // these will be things like model, name, ... // -extern cvar_t *cvar_vars; // I know this is really unpleasant, but I need access for scanning/writing latched cvars during save games +extern cvar_t *cvar_vars; // I know this is really unpleasant, but I need access for scanning/writing latched cvars during save games -void SG_WriteCvars(void) -{ - cvar_t *var; - int iCount = 0; +void SG_WriteCvars(void) { + cvar_t *var; + int iCount = 0; - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); // count the cvars... // - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { #ifdef JK2_MODE - if (!(var->flags & (CVAR_SAVEGAME|CVAR_USERINFO))) + if (!(var->flags & (CVAR_SAVEGAME | CVAR_USERINFO))) #else if (!(var->flags & CVAR_SAVEGAME)) #endif @@ -545,16 +460,13 @@ void SG_WriteCvars(void) // store count... // - saved_game.write_chunk( - INT_ID('C', 'V', 'C', 'N'), - iCount); + saved_game.write_chunk(INT_ID('C', 'V', 'C', 'N'), iCount); // write 'em... // - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { #ifdef JK2_MODE - if (!(var->flags & (CVAR_SAVEGAME|CVAR_USERINFO))) + if (!(var->flags & (CVAR_SAVEGAME | CVAR_USERINFO))) #else if (!(var->flags & CVAR_SAVEGAME)) #endif @@ -562,107 +474,73 @@ void SG_WriteCvars(void) continue; } - saved_game.write_chunk( - INT_ID('C', 'V', 'A', 'R'), - var->name, - static_cast(strlen(var->name) + 1)); + saved_game.write_chunk(INT_ID('C', 'V', 'A', 'R'), var->name, static_cast(strlen(var->name) + 1)); - saved_game.write_chunk( - INT_ID('V', 'A', 'L', 'U'), - var->string, - static_cast(strlen(var->string) + 1)); + saved_game.write_chunk(INT_ID('V', 'A', 'L', 'U'), var->string, static_cast(strlen(var->string) + 1)); } } -void SG_ReadCvars() -{ +void SG_ReadCvars() { int iCount = 0; std::string psName; - const char* psValue; + const char *psValue; - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - saved_game.read_chunk( - INT_ID('C', 'V', 'C', 'N'), - iCount); + saved_game.read_chunk(INT_ID('C', 'V', 'C', 'N'), iCount); - for (int i = 0; i < iCount; ++i) - { - saved_game.read_chunk( - INT_ID('C', 'V', 'A', 'R')); + for (int i = 0; i < iCount; ++i) { + saved_game.read_chunk(INT_ID('C', 'V', 'A', 'R')); - psName = reinterpret_cast( - saved_game.get_buffer_data()); + psName = reinterpret_cast(saved_game.get_buffer_data()); + saved_game.read_chunk(INT_ID('V', 'A', 'L', 'U')); - saved_game.read_chunk( - INT_ID('V', 'A', 'L', 'U')); - - psValue = reinterpret_cast( - saved_game.get_buffer_data()); + psValue = reinterpret_cast(saved_game.get_buffer_data()); ::Cvar_Set(psName.c_str(), psValue); } } -void SG_WriteServerConfigStrings() -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +void SG_WriteServerConfigStrings() { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); int iCount = 0; - int i; // not in FOR statement in case compiler goes weird by reg-optimising it then failing to get the address later + int i; // not in FOR statement in case compiler goes weird by reg-optimising it then failing to get the address later // count how many non-blank server strings there are... // - for ( i=0; i + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (i != CS_SYSTEMINFO) { + if (sv.configstrings[i] && strlen(sv.configstrings[i])) // paranoia... { iCount++; } } } - saved_game.write_chunk( - INT_ID('C', 'S', 'C', 'N'), - iCount); + saved_game.write_chunk(INT_ID('C', 'S', 'C', 'N'), iCount); // now write 'em... // - for (i=0; i( - INT_ID('C', 'S', 'I', 'N'), - i); - - saved_game.write_chunk( - INT_ID('C', 'S', 'D', 'A'), - ::sv.configstrings[i], - static_cast(strlen(::sv.configstrings[i]) + 1)); + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (i != CS_SYSTEMINFO) { + if (sv.configstrings[i] && strlen(sv.configstrings[i])) { + saved_game.write_chunk(INT_ID('C', 'S', 'I', 'N'), i); + + saved_game.write_chunk(INT_ID('C', 'S', 'D', 'A'), ::sv.configstrings[i], static_cast(strlen(::sv.configstrings[i]) + 1)); } } } } -void SG_ReadServerConfigStrings( void ) -{ +void SG_ReadServerConfigStrings(void) { // trash the whole table... // - for (int i=0; i( - INT_ID('C', 'S', 'C', 'N'), - iCount); + saved_game.read_chunk(INT_ID('C', 'S', 'C', 'N'), iCount); - Com_DPrintf( "Reading %d configstrings...\n",iCount); + Com_DPrintf("Reading %d configstrings...\n", iCount); - for (int i = 0; i( - INT_ID('C', 'S', 'I', 'N'), - iIndex); + saved_game.read_chunk(INT_ID('C', 'S', 'I', 'N'), iIndex); - saved_game.read_chunk( - INT_ID('C', 'S', 'D', 'A')); + saved_game.read_chunk(INT_ID('C', 'S', 'D', 'A')); - psName = reinterpret_cast( - saved_game.get_buffer_data()); + psName = reinterpret_cast(saved_game.get_buffer_data()); - Com_DPrintf( "Cfg str %d = %s\n",iIndex, psName); + Com_DPrintf("Cfg str %d = %s\n", iIndex, psName); - //sv.configstrings[iIndex] = psName; + // sv.configstrings[iIndex] = psName; SV_SetConfigstring(iIndex, psName); } } -static unsigned int SG_UnixTimestamp ( const time_t& t ) -{ - return static_cast(t); -} +static unsigned int SG_UnixTimestamp(const time_t &t) { return static_cast(t); } -static void SG_WriteComment(qboolean qbAutosave, const char *psMapName) -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +static void SG_WriteComment(qboolean qbAutosave, const char *psMapName) { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); - char sComment[iSG_COMMENT_SIZE]; + char sComment[iSG_COMMENT_SIZE]; - if ( qbAutosave || !*saveGameComment) - { - Com_sprintf( sComment, sizeof(sComment), "---> %s", psMapName ); - } - else - { - Q_strncpyz(sComment,saveGameComment, sizeof(sComment)); + if (qbAutosave || !*saveGameComment) { + Com_sprintf(sComment, sizeof(sComment), "---> %s", psMapName); + } else { + Q_strncpyz(sComment, saveGameComment, sizeof(sComment)); } - saved_game.write_chunk( - INT_ID('C', 'O', 'M', 'M'), - sComment); + saved_game.write_chunk(INT_ID('C', 'O', 'M', 'M'), sComment); // Add Date/Time/Map stamp - unsigned int timestamp = SG_UnixTimestamp (time (NULL)); + unsigned int timestamp = SG_UnixTimestamp(time(NULL)); - saved_game.write_chunk( - INT_ID('C', 'M', 'T', 'M'), - timestamp); + saved_game.write_chunk(INT_ID('C', 'M', 'T', 'M'), timestamp); Com_DPrintf("Saving: current (%s)\n", sComment); } -static time_t SG_GetTime ( unsigned int timestamp ) -{ - return static_cast(timestamp); -} +static time_t SG_GetTime(unsigned int timestamp) { return static_cast(timestamp); } // Test to see if the given file name is in the save game directory // then grab the comment if it's there // -int SG_GetSaveGameComment( - const char* psPathlessBaseName, - char* sComment, - char* sMapName) -{ +int SG_GetSaveGameComment(const char *psPathlessBaseName, char *sComment, char *sMapName) { int ret = 0; - ojk::SavedGame& saved_game = ojk::SavedGame::get_instance(); + ojk::SavedGame &saved_game = ojk::SavedGame::get_instance(); - ojk::SavedGameHelper sgh( - &ojk::SavedGame::get_instance()); + ojk::SavedGameHelper sgh(&ojk::SavedGame::get_instance()); - if (!saved_game.open( - psPathlessBaseName)) - { + if (!saved_game.open(psPathlessBaseName)) { return 0; } @@ -768,22 +616,13 @@ int SG_GetSaveGameComment( // Read description // - is_succeed = sgh.try_read_chunk( - INT_ID('C', 'O', 'M', 'M')); + is_succeed = sgh.try_read_chunk(INT_ID('C', 'O', 'M', 'M')); - if (is_succeed) - { - if (sComment) - { - if (sgh.get_buffer_size() == iSG_COMMENT_SIZE) - { - std::uninitialized_copy_n( - static_cast(sgh.get_buffer_data()), - iSG_COMMENT_SIZE, - sComment); - } - else - { + if (is_succeed) { + if (sComment) { + if (sgh.get_buffer_size() == iSG_COMMENT_SIZE) { + std::uninitialized_copy_n(static_cast(sgh.get_buffer_data()), iSG_COMMENT_SIZE, sComment); + } else { sComment[0] = '\0'; } } @@ -793,18 +632,13 @@ int SG_GetSaveGameComment( // time_t tFileTime = ::SG_GetTime(0); - if (is_succeed) - { + if (is_succeed) { unsigned int fileTime = 0; - is_succeed = sgh.try_read_chunk( - INT_ID('C', 'M', 'T', 'M'), - fileTime); + is_succeed = sgh.try_read_chunk(INT_ID('C', 'M', 'T', 'M'), fileTime); - if (is_succeed) - { - tFileTime = ::SG_GetTime( - fileTime); + if (is_succeed) { + tFileTime = ::SG_GetTime(fileTime); } } @@ -812,42 +646,27 @@ int SG_GetSaveGameComment( // Read screenshot // - if (is_succeed) - { + if (is_succeed) { size_t iScreenShotLength; - is_succeed = sgh.try_read_chunk( - INT_ID('S', 'H', 'L', 'N'), - iScreenShotLength); + is_succeed = sgh.try_read_chunk(INT_ID('S', 'H', 'L', 'N'), iScreenShotLength); } - if (is_succeed) - { - is_succeed = sgh.try_read_chunk( - INT_ID('S', 'H', 'O', 'T')); + if (is_succeed) { + is_succeed = sgh.try_read_chunk(INT_ID('S', 'H', 'O', 'T')); } #endif // Read mapname // - if (is_succeed) - { - is_succeed = sgh.try_read_chunk( - INT_ID('M', 'P', 'C', 'M')); - - if (is_succeed) - { - if (sMapName) - { - if (sgh.get_buffer_size() == iSG_MAPCMD_SIZE) - { - std::uninitialized_copy_n( - static_cast(sgh.get_buffer_data()), - iSG_MAPCMD_SIZE, - sMapName); - } - else - { + if (is_succeed) { + is_succeed = sgh.try_read_chunk(INT_ID('M', 'P', 'C', 'M')); + + if (is_succeed) { + if (sMapName) { + if (sgh.get_buffer_size() == iSG_MAPCMD_SIZE) { + std::uninitialized_copy_n(static_cast(sgh.get_buffer_data()), iSG_MAPCMD_SIZE, sMapName); + } else { sMapName[0] = '\0'; } } @@ -861,118 +680,81 @@ int SG_GetSaveGameComment( return ret; } - // read the mapname field from the supplied savegame file // // returns NULL if not found // -static char *SG_GetSaveGameMapName(const char *psPathlessBaseName) -{ - static char sMapName[iSG_MAPCMD_SIZE]={0}; +static char *SG_GetSaveGameMapName(const char *psPathlessBaseName) { + static char sMapName[iSG_MAPCMD_SIZE] = {0}; char *psReturn = NULL; - if (SG_GetSaveGameComment(psPathlessBaseName, NULL, sMapName)) - { + if (SG_GetSaveGameComment(psPathlessBaseName, NULL, sMapName)) { psReturn = sMapName; } return psReturn; } - // pass in qtrue to set as loading screen, else pass in pvDest to read it into there... // #ifdef JK2_MODE -static bool SG_ReadScreenshot( - bool set_as_loading_screen, - void* screenshot_ptr) -{ +static bool SG_ReadScreenshot(bool set_as_loading_screen, void *screenshot_ptr) { bool is_succeed = true; - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); // get JPG screenshot data length... // size_t screenshot_length = 0; - is_succeed = saved_game.try_read_chunk( - INT_ID('S', 'H', 'L', 'N'), - screenshot_length); + is_succeed = saved_game.try_read_chunk(INT_ID('S', 'H', 'L', 'N'), screenshot_length); // // alloc enough space plus extra 4K for sloppy JPG-decode reader to not do memory access violation... // - byte* jpeg_data = nullptr; + byte *jpeg_data = nullptr; - if (is_succeed) - { - jpeg_data = static_cast(::Z_Malloc( - static_cast(screenshot_length + 4096), - TAG_TEMP_WORKSPACE, - qfalse)); + if (is_succeed) { + jpeg_data = static_cast(::Z_Malloc(static_cast(screenshot_length + 4096), TAG_TEMP_WORKSPACE, qfalse)); } // // now read the JPG data... // - if (is_succeed) - { - is_succeed = saved_game.try_read_chunk( - INT_ID('S', 'H', 'O', 'T'), - jpeg_data, - static_cast(screenshot_length)); + if (is_succeed) { + is_succeed = saved_game.try_read_chunk(INT_ID('S', 'H', 'O', 'T'), jpeg_data, static_cast(screenshot_length)); } // // decompress JPG data... // - byte* image = NULL; + byte *image = NULL; int width; int height; - if (is_succeed) - { - ::re.LoadJPGFromBuffer( - jpeg_data, - screenshot_length, - &image, - &width, - &height); + if (is_succeed) { + ::re.LoadJPGFromBuffer(jpeg_data, screenshot_length, &image, &width, &height); // // if the loaded image is the same size as the game is expecting, then copy it to supplied arg (if present)... // - if (width == SG_SCR_WIDTH && height == SG_SCR_HEIGHT) - { - if (screenshot_ptr) - { - ::memcpy( - screenshot_ptr, - image, - SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); + if (width == SG_SCR_WIDTH && height == SG_SCR_HEIGHT) { + if (screenshot_ptr) { + ::memcpy(screenshot_ptr, image, SG_SCR_WIDTH * SG_SCR_HEIGHT * 4); } - if (set_as_loading_screen) - { - ::SCR_SetScreenshot( - image, - SG_SCR_WIDTH, - SG_SCR_HEIGHT); + if (set_as_loading_screen) { + ::SCR_SetScreenshot(image, SG_SCR_WIDTH, SG_SCR_HEIGHT); } - } - else - { + } else { is_succeed = false; } } - if (jpeg_data) - { + if (jpeg_data) { ::Z_Free(jpeg_data); } - if (image) - { + if (image) { ::Z_Free(image); } @@ -980,41 +762,29 @@ static bool SG_ReadScreenshot( } // Gets the savegame screenshot // -qboolean SG_GetSaveImage( - const char* base_name, - void* image_ptr) -{ - if (!base_name) - { +qboolean SG_GetSaveImage(const char *base_name, void *image_ptr) { + if (!base_name) { return qfalse; } - ojk::SavedGame& saved_game = ojk::SavedGame::get_instance(); + ojk::SavedGame &saved_game = ojk::SavedGame::get_instance(); - if (!saved_game.open(base_name)) - { + if (!saved_game.open(base_name)) { return qfalse; } bool is_succeed = true; - ojk::SavedGameHelper sgh( - &saved_game); + ojk::SavedGameHelper sgh(&saved_game); - is_succeed = sgh.try_read_chunk( - INT_ID('C', 'O', 'M', 'M')); + is_succeed = sgh.try_read_chunk(INT_ID('C', 'O', 'M', 'M')); - if (is_succeed) - { - is_succeed = sgh.try_read_chunk( - INT_ID('C', 'M', 'T', 'M')); + if (is_succeed) { + is_succeed = sgh.try_read_chunk(INT_ID('C', 'M', 'T', 'M')); } - if (is_succeed) - { - is_succeed = SG_ReadScreenshot( - false, - image_ptr); + if (is_succeed) { + is_succeed = SG_ReadScreenshot(false, image_ptr); } saved_game.close(); @@ -1022,33 +792,26 @@ qboolean SG_GetSaveImage( return is_succeed ? qtrue : qfalse; } - -static void SG_WriteScreenshot(qboolean qbAutosave, const char *psMapName) -{ - ojk::SavedGameHelper saved_game( - &ojk::SavedGame::get_instance()); +static void SG_WriteScreenshot(qboolean qbAutosave, const char *psMapName) { + ojk::SavedGameHelper saved_game(&ojk::SavedGame::get_instance()); byte *pbRawScreenShot = NULL; byte *byBlank = NULL; - if( qbAutosave ) - { + if (qbAutosave) { // try to read a levelshot (any valid TGA/JPG etc named the same as the map)... // int iWidth = SG_SCR_WIDTH; - int iHeight= SG_SCR_HEIGHT; - const size_t bySize = SG_SCR_WIDTH * SG_SCR_HEIGHT * 4; + int iHeight = SG_SCR_HEIGHT; + const size_t bySize = SG_SCR_WIDTH * SG_SCR_HEIGHT * 4; byte *src, *dst; byBlank = new byte[bySize]; - pbRawScreenShot = SCR_TempRawImage_ReadFromFile(va("levelshots/%s.tga",psMapName), &iWidth, &iHeight, byBlank, qtrue); // qtrue = vert flip + pbRawScreenShot = SCR_TempRawImage_ReadFromFile(va("levelshots/%s.tga", psMapName), &iWidth, &iHeight, byBlank, qtrue); // qtrue = vert flip - if (pbRawScreenShot) - { - for (int y = 0; y < iHeight; y++) - { - for (int x = 0; x < iWidth; x++) - { + if (pbRawScreenShot) { + for (int y = 0; y < iHeight; y++) { + for (int x = 0; x < iWidth; x++) { src = pbRawScreenShot + 4 * (y * iWidth + x); dst = pbRawScreenShot + 3 * (y * iWidth + x); dst[0] = src[0]; @@ -1059,15 +822,13 @@ static void SG_WriteScreenshot(qboolean qbAutosave, const char *psMapName) } } - if (!pbRawScreenShot) - { + if (!pbRawScreenShot) { pbRawScreenShot = SCR_GetScreenshot(0); } - size_t iJPGDataSize = 0; size_t bufSize = SG_SCR_WIDTH * SG_SCR_HEIGHT * 3; - byte *pJPGData = (byte *)Z_Malloc( static_cast(bufSize), TAG_TEMP_WORKSPACE, qfalse, 4 ); + byte *pJPGData = (byte *)Z_Malloc(static_cast(bufSize), TAG_TEMP_WORKSPACE, qfalse, 4); #ifdef JK2_MODE bool flip_vertical = true; @@ -1075,64 +836,51 @@ static void SG_WriteScreenshot(qboolean qbAutosave, const char *psMapName) bool flip_vertical = false; #endif // JK2_MODE - iJPGDataSize = re.SaveJPGToBuffer(pJPGData, bufSize, JPEG_IMAGE_QUALITY, SG_SCR_WIDTH, SG_SCR_HEIGHT, pbRawScreenShot, 0, flip_vertical ); - if ( qbAutosave ) + iJPGDataSize = re.SaveJPGToBuffer(pJPGData, bufSize, JPEG_IMAGE_QUALITY, SG_SCR_WIDTH, SG_SCR_HEIGHT, pbRawScreenShot, 0, flip_vertical); + if (qbAutosave) delete[] byBlank; - saved_game.write_chunk( - INT_ID('S', 'H', 'L', 'N'), - iJPGDataSize); + saved_game.write_chunk(INT_ID('S', 'H', 'L', 'N'), iJPGDataSize); - saved_game.write_chunk( - INT_ID('S', 'H', 'O', 'T'), - pJPGData, - static_cast(iJPGDataSize)); + saved_game.write_chunk(INT_ID('S', 'H', 'O', 'T'), pJPGData, static_cast(iJPGDataSize)); Z_Free(pJPGData); SCR_TempRawImage_CleanUp(); } #endif - -qboolean SG_GameAllowedToSaveHere(qboolean inCamera) -{ +qboolean SG_GameAllowedToSaveHere(qboolean inCamera) { if (!inCamera) { - if ( !com_sv_running || !com_sv_running->integer ) - { - return qfalse; // Com_Printf( S_COLOR_RED "Server is not running\n" ); + if (!com_sv_running || !com_sv_running->integer) { + return qfalse; // Com_Printf( S_COLOR_RED "Server is not running\n" ); } - if (CL_IsRunningInGameCinematic()) - { - return qfalse; //nope, not during a video + if (CL_IsRunningInGameCinematic()) { + return qfalse; // nope, not during a video } - if (sv.state != SS_GAME) - { - return qfalse; // Com_Printf (S_COLOR_RED "You must be in a game to save.\n"); + if (sv.state != SS_GAME) { + return qfalse; // Com_Printf (S_COLOR_RED "You must be in a game to save.\n"); } - //No savegames from "_" maps - if ( !sv_mapname || (sv_mapname->string != NULL && sv_mapname->string[0] == '_') ) - { - return qfalse; // Com_Printf (S_COLOR_RED "Cannot save on holodeck or brig.\n"); + // No savegames from "_" maps + if (!sv_mapname || (sv_mapname->string != NULL && sv_mapname->string[0] == '_')) { + return qfalse; // Com_Printf (S_COLOR_RED "Cannot save on holodeck or brig.\n"); } - if (svs.clients[0].frames[svs.clients[0].netchan.outgoingSequence & PACKET_MASK].ps.stats[STAT_HEALTH] <= 0) - { - return qfalse; // Com_Printf (S_COLOR_RED "\nCan't savegame while dead!\n"); + if (svs.clients[0].frames[svs.clients[0].netchan.outgoingSequence & PACKET_MASK].ps.stats[STAT_HEALTH] <= 0) { + return qfalse; // Com_Printf (S_COLOR_RED "\nCan't savegame while dead!\n"); } } if (!ge) - return inCamera; // only happens when called to test if inCamera + return inCamera; // only happens when called to test if inCamera return ge->GameAllowedToSaveHere(); } -qboolean SG_WriteSavegame(const char *psPathlessBaseName, qboolean qbAutosave) -{ - if (!qbAutosave && !SG_GameAllowedToSaveHere(qfalse)) //full check - return qfalse; // this prevents people saving via quick-save now during cinematics +qboolean SG_WriteSavegame(const char *psPathlessBaseName, qboolean qbAutosave) { + if (!qbAutosave && !SG_GameAllowedToSaveHere(qfalse)) // full check + return qfalse; // this prevents people saving via quick-save now during cinematics int iPrevTestSave = sv_testsave->integer; sv_testsave->integer = 0; @@ -1140,161 +888,120 @@ qboolean SG_WriteSavegame(const char *psPathlessBaseName, qboolean qbAutosave) // Write out server data... // const char *psServerInfo = sv.configstrings[CS_SERVERINFO]; - const char *psMapName = Info_ValueForKey( psServerInfo, "mapname" ); -//JLF + const char *psMapName = Info_ValueForKey(psServerInfo, "mapname"); +// JLF #ifdef JK2_MODE - if ( !strcmp("quik",psPathlessBaseName)) + if (!strcmp("quik", psPathlessBaseName)) #else - if ( !strcmp("quick",psPathlessBaseName)) + if (!strcmp("quick", psPathlessBaseName)) #endif { - SG_StoreSaveGameComment(va("--> %s <--",psMapName)); + SG_StoreSaveGameComment(va("--> %s <--", psMapName)); } - ojk::SavedGame& saved_game = ojk::SavedGame::get_instance(); + ojk::SavedGame &saved_game = ojk::SavedGame::get_instance(); - if(!saved_game.create( "current" )) - { - Com_Printf (GetString_FailedToOpenSaveGame("current",qfalse));//S_COLOR_RED "Failed to create savegame\n"); - SG_WipeSavegame( "current" ); + if (!saved_game.create("current")) { + Com_Printf(GetString_FailedToOpenSaveGame("current", qfalse)); // S_COLOR_RED "Failed to create savegame\n"); + SG_WipeSavegame("current"); sv_testsave->integer = iPrevTestSave; return qfalse; } -//END JLF + // END JLF - ojk::SavedGameHelper sgh( - &saved_game); + ojk::SavedGameHelper sgh(&saved_game); - char sMapCmd[iSG_MAPCMD_SIZE]={0}; - Q_strncpyz( sMapCmd,psMapName, sizeof(sMapCmd)); // need as array rather than ptr because const strlen needed for MPCM chunk + char sMapCmd[iSG_MAPCMD_SIZE] = {0}; + Q_strncpyz(sMapCmd, psMapName, sizeof(sMapCmd)); // need as array rather than ptr because const strlen needed for MPCM chunk SG_WriteComment(qbAutosave, sMapCmd); #ifdef JK2_MODE SG_WriteScreenshot(qbAutosave, sMapCmd); #endif - sgh.write_chunk( - INT_ID('M', 'P', 'C', 'M'), - sMapCmd); + sgh.write_chunk(INT_ID('M', 'P', 'C', 'M'), sMapCmd); SG_WriteCvars(); - WriteGame (qbAutosave); + WriteGame(qbAutosave); // Write out all the level data... // - if (!qbAutosave) - { - sgh.write_chunk( - INT_ID('T', 'I', 'M', 'E'), - ::sv.time); + if (!qbAutosave) { + sgh.write_chunk(INT_ID('T', 'I', 'M', 'E'), ::sv.time); - sgh.write_chunk( - INT_ID('T', 'I', 'M', 'R'), - ::sv.timeResidual); + sgh.write_chunk(INT_ID('T', 'I', 'M', 'R'), ::sv.timeResidual); CM_WritePortalState(); SG_WriteServerConfigStrings(); } - ge->WriteLevel(qbAutosave); // always done now, but ent saver only does player if auto + ge->WriteLevel(qbAutosave); // always done now, but ent saver only does player if auto bool is_write_failed = saved_game.is_failed(); saved_game.close(); - if (is_write_failed) - { - Com_Printf (GetString_FailedToOpenSaveGame("current",qfalse));//S_COLOR_RED "Failed to write savegame!\n"); - SG_WipeSavegame( "current" ); + if (is_write_failed) { + Com_Printf(GetString_FailedToOpenSaveGame("current", qfalse)); // S_COLOR_RED "Failed to write savegame!\n"); + SG_WipeSavegame("current"); sv_testsave->integer = iPrevTestSave; return qfalse; } - ojk::SavedGame::rename( - "current", - psPathlessBaseName); + ojk::SavedGame::rename("current", psPathlessBaseName); sv_testsave->integer = iPrevTestSave; return qtrue; } -qboolean SG_ReadSavegame( - const char* psPathlessBaseName) -{ +qboolean SG_ReadSavegame(const char *psPathlessBaseName) { char sComment[iSG_COMMENT_SIZE]; char sMapCmd[iSG_MAPCMD_SIZE]; #ifdef JK2_MODE - Cvar_Set( - "cg_missionstatusscreen", - "0"); + Cvar_Set("cg_missionstatusscreen", "0"); #endif - ojk::SavedGame& saved_game = ojk::SavedGame::get_instance(); + ojk::SavedGame &saved_game = ojk::SavedGame::get_instance(); - ojk::SavedGameHelper sgh( - &saved_game); + ojk::SavedGameHelper sgh(&saved_game); const int iPrevTestSave = ::sv_testsave->integer; - ojk::ScopeGuard scope_guard( - [&]() - { - ::sv_testsave->integer = 0; - }, + ojk::ScopeGuard scope_guard([&]() { ::sv_testsave->integer = 0; }, - [&]() - { - saved_game.close(); - - ::sv_testsave->integer = iPrevTestSave; - } - ); + [&]() { + saved_game.close(); + ::sv_testsave->integer = iPrevTestSave; + }); - if (!saved_game.open(psPathlessBaseName)) - { - //S_COLOR_RED "Failed to open savegame \"%s\"\n", psPathlessBaseName); - ::Com_Printf( - ::GetString_FailedToOpenSaveGame( - psPathlessBaseName, - qtrue)); + if (!saved_game.open(psPathlessBaseName)) { + // S_COLOR_RED "Failed to open savegame \"%s\"\n", psPathlessBaseName); + ::Com_Printf(::GetString_FailedToOpenSaveGame(psPathlessBaseName, qtrue)); return qfalse; } // this check isn't really necessary, but it reminds me that these two strings may actually be the same physical one. // - if (psPathlessBaseName != sLastSaveFileLoaded) - { - ::Q_strncpyz( - ::sLastSaveFileLoaded, - psPathlessBaseName, - sizeof(sLastSaveFileLoaded)); + if (psPathlessBaseName != sLastSaveFileLoaded) { + ::Q_strncpyz(::sLastSaveFileLoaded, psPathlessBaseName, sizeof(sLastSaveFileLoaded)); } // Read in all the server data... // - sgh.read_chunk( - INT_ID('C', 'O', 'M', 'M'), - sComment); + sgh.read_chunk(INT_ID('C', 'O', 'M', 'M'), sComment); - ::Com_DPrintf( - "Reading: %s\n", - sComment); + ::Com_DPrintf("Reading: %s\n", sComment); - sgh.read_chunk( - INT_ID('C', 'M', 'T', 'M')); + sgh.read_chunk(INT_ID('C', 'M', 'T', 'M')); #ifdef JK2_MODE - ::SG_ReadScreenshot( - true, - nullptr); + ::SG_ReadScreenshot(true, nullptr); #endif - sgh.read_chunk( - INT_ID('M', 'P', 'C', 'M'), - sMapCmd); + sgh.read_chunk(INT_ID('M', 'P', 'C', 'M'), sMapCmd); ::SG_ReadCvars(); @@ -1304,39 +1011,27 @@ qboolean SG_ReadSavegame( ::eSavedGameJustLoaded = (qbAutosave ? eAUTO : eFULL); // note that this also trashes the whole G_Alloc pool as well (of course) - ::SV_SpawnServer( - sMapCmd, - eForceReload_NOTHING, - (::eSavedGameJustLoaded != eFULL ? qtrue : qfalse)); + ::SV_SpawnServer(sMapCmd, eForceReload_NOTHING, (::eSavedGameJustLoaded != eFULL ? qtrue : qfalse)); // read in all the level data... // - if (!qbAutosave) - { - sgh.read_chunk( - INT_ID('T', 'I', 'M', 'E'), - ::sv.time); + if (!qbAutosave) { + sgh.read_chunk(INT_ID('T', 'I', 'M', 'E'), ::sv.time); - sgh.read_chunk( - INT_ID('T', 'I', 'M', 'R'), - ::sv.timeResidual); + sgh.read_chunk(INT_ID('T', 'I', 'M', 'R'), ::sv.timeResidual); ::CM_ReadPortalState(); ::SG_ReadServerConfigStrings(); } // always done now, but ent reader only does player if auto - ::ge->ReadLevel( - qbAutosave, - qbLoadTransition); + ::ge->ReadLevel(qbAutosave, qbLoadTransition); return qtrue; } -void SG_TestSave(void) -{ - if (sv_testsave->integer && sv.state == SS_GAME) - { +void SG_TestSave(void) { + if (sv_testsave->integer && sv.state == SS_GAME) { WriteGame(qfalse); ge->WriteLevel(qfalse); } diff --git a/code/server/sv_snapshot.cpp b/code/server/sv_snapshot.cpp index 149a0eb3d9..49411070b4 100644 --- a/code/server/sv_snapshot.cpp +++ b/code/server/sv_snapshot.cpp @@ -55,14 +55,14 @@ SV_EmitPacketEntities Writes a delta update of an entityState_t list to the message. ============= */ -static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) { - entityState_t *oldent, *newent; - int oldindex, newindex; - int oldnum, newnum; - int from_num_entities; +static void SV_EmitPacketEntities(clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg) { + entityState_t *oldent, *newent; + int oldindex, newindex; + int oldnum, newnum; + int from_num_entities; // generate the delta update - if ( !from ) { + if (!from) { from_num_entities = 0; } else { from_num_entities = from->num_entities; @@ -74,22 +74,22 @@ static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, oldindex = 0; const int num2Send = to->num_entities >= svs.numSnapshotEntities ? svs.numSnapshotEntities : to->num_entities; - while ( newindex < num2Send || oldindex < from_num_entities ) { - if ( newindex >= num2Send ) { + while (newindex < num2Send || oldindex < from_num_entities) { + if (newindex >= num2Send) { newnum = 9999; } else { - newent = &svs.snapshotEntities[(to->first_entity+newindex) % svs.numSnapshotEntities]; + newent = &svs.snapshotEntities[(to->first_entity + newindex) % svs.numSnapshotEntities]; newnum = newent->number; } - if ( oldindex >= from_num_entities ) { + if (oldindex >= from_num_entities) { oldnum = 9999; } else { - oldent = &svs.snapshotEntities[(from->first_entity+oldindex) % svs.numSnapshotEntities]; + oldent = &svs.snapshotEntities[(from->first_entity + oldindex) % svs.numSnapshotEntities]; oldnum = oldent->number; } - if ( newnum == oldnum ) { + if (newnum == oldnum) { // delta update from old position // because the force parm is qfalse, this will not result // in any bytes being emited if the entity has not changed at all @@ -99,101 +99,97 @@ static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, continue; } - if ( newnum < oldnum ) { + if (newnum < oldnum) { // this is a new entity, send it from the baseline - MSG_WriteEntity (msg, newent, 0); + MSG_WriteEntity(msg, newent, 0); newindex++; continue; } - if ( newnum > oldnum ) { + if (newnum > oldnum) { // the old entity isn't present in the new message - if(oldent) { - MSG_WriteEntity (msg, NULL, oldent->number); + if (oldent) { + MSG_WriteEntity(msg, NULL, oldent->number); } oldindex++; continue; } } - MSG_WriteBits( msg, (MAX_GENTITIES-1), GENTITYNUM_BITS ); // end of packetentities + MSG_WriteBits(msg, (MAX_GENTITIES - 1), GENTITYNUM_BITS); // end of packetentities } - - /* ================== SV_WriteSnapshotToClient ================== */ -static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) { - clientSnapshot_t *frame, *oldframe; - int lastframe; - int snapFlags; +static void SV_WriteSnapshotToClient(client_t *client, msg_t *msg) { + clientSnapshot_t *frame, *oldframe; + int lastframe; + int snapFlags; // this is the snapshot we are creating - frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ]; + frame = &client->frames[client->netchan.outgoingSequence & PACKET_MASK]; // try to use a previous frame as the source for delta compressing the snapshot - if ( client->deltaMessage <= 0 || client->state != CS_ACTIVE ) { + if (client->deltaMessage <= 0 || client->state != CS_ACTIVE) { // client is asking for a retransmit oldframe = NULL; lastframe = 0; - } else if ( client->netchan.outgoingSequence - client->deltaMessage - >= (PACKET_BACKUP - 3) ) { + } else if (client->netchan.outgoingSequence - client->deltaMessage >= (PACKET_BACKUP - 3)) { // client hasn't gotten a good message through in a long time - Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name); + Com_DPrintf("%s: Delta request from out of date packet.\n", client->name); oldframe = NULL; lastframe = 0; } else { // we have a valid snapshot to delta from - oldframe = &client->frames[ client->deltaMessage & PACKET_MASK ]; + oldframe = &client->frames[client->deltaMessage & PACKET_MASK]; lastframe = client->netchan.outgoingSequence - client->deltaMessage; // the snapshot's entities may still have rolled off the buffer, though - if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) { - Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name); + if (oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities) { + Com_DPrintf("%s: Delta request from out of date entities.\n", client->name); oldframe = NULL; lastframe = 0; } } - MSG_WriteByte (msg, svc_snapshot); + MSG_WriteByte(msg, svc_snapshot); // let the client know which reliable clientCommands we have received - MSG_WriteLong( msg, client->lastClientCommand ); + MSG_WriteLong(msg, client->lastClientCommand); // send over the current server time so the client can drift // its view of time to try to match - MSG_WriteLong (msg, sv.time); + MSG_WriteLong(msg, sv.time); // we must write a message number, because recorded demos won't have // the same network message sequences - MSG_WriteLong (msg, client->netchan.outgoingSequence ); - MSG_WriteByte (msg, lastframe); // what we are delta'ing from - MSG_WriteLong (msg, client->cmdNum); // we have executed up to here + MSG_WriteLong(msg, client->netchan.outgoingSequence); + MSG_WriteByte(msg, lastframe); // what we are delta'ing from + MSG_WriteLong(msg, client->cmdNum); // we have executed up to here snapFlags = client->droppedCommands << 1; client->droppedCommands = qfalse; - MSG_WriteByte (msg, snapFlags); + MSG_WriteByte(msg, snapFlags); // send over the areabits - MSG_WriteByte (msg, frame->areabytes); - MSG_WriteData (msg, frame->areabits, frame->areabytes); + MSG_WriteByte(msg, frame->areabytes); + MSG_WriteData(msg, frame->areabits, frame->areabytes); // delta encode the playerstate - if ( oldframe ) { - MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps ); + if (oldframe) { + MSG_WriteDeltaPlayerstate(msg, &oldframe->ps, &frame->ps); } else { - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->ps); } // delta encode the entities - SV_EmitPacketEntities (oldframe, frame, msg); + SV_EmitPacketEntities(oldframe, frame, msg); } - /* ================== SV_UpdateServerCommandsToClient @@ -201,14 +197,14 @@ SV_UpdateServerCommandsToClient (re)send all server commands the client hasn't acknowledged yet ================== */ -static void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) { - int i; +static void SV_UpdateServerCommandsToClient(client_t *client, msg_t *msg) { + int i; // write any unacknowledged serverCommands - for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) { - MSG_WriteByte( msg, svc_serverCommand ); - MSG_WriteLong( msg, i ); - MSG_WriteString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] ); + for (i = client->reliableAcknowledge + 1; i <= client->reliableSequence; i++) { + MSG_WriteByte(msg, svc_serverCommand); + MSG_WriteLong(msg, i); + MSG_WriteString(msg, client->reliableCommands[i & (MAX_RELIABLE_COMMANDS - 1)]); } } @@ -220,10 +216,10 @@ Build a client snapshot structure ============================================================================= */ -#define MAX_SNAPSHOT_ENTITIES 1024 +#define MAX_SNAPSHOT_ENTITIES 1024 typedef struct { - int numSnapshotEntities; - int snapshotEntities[MAX_SNAPSHOT_ENTITIES]; + int numSnapshotEntities; + int snapshotEntities[MAX_SNAPSHOT_ENTITIES]; } snapshotEntityNumbers_t; /* @@ -231,102 +227,91 @@ typedef struct { SV_QsortEntityNumbers ======================= */ -static int SV_QsortEntityNumbers( const void *a, const void *b ) { - int *ea, *eb; +static int SV_QsortEntityNumbers(const void *a, const void *b) { + int *ea, *eb; ea = (int *)a; eb = (int *)b; - if ( *ea == *eb ) { - Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" ); + if (*ea == *eb) { + Com_Error(ERR_DROP, "SV_QsortEntityStates: duplicated entity"); } - if ( *ea < *eb ) { + if (*ea < *eb) { return -1; } return 1; } - /* =============== SV_AddEntToSnapshot =============== */ -static void SV_AddEntToSnapshot( svEntity_t *svEnt, gentity_t *gEnt, snapshotEntityNumbers_t *eNums ) { +static void SV_AddEntToSnapshot(svEntity_t *svEnt, gentity_t *gEnt, snapshotEntityNumbers_t *eNums) { // if we have already added this entity to this snapshot, don't add again - if ( svEnt->snapshotCounter == sv.snapshotCounter ) { + if (svEnt->snapshotCounter == sv.snapshotCounter) { return; } svEnt->snapshotCounter = sv.snapshotCounter; // if we are full, silently discard entities - if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) { + if (eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES) { return; } - if (sv.snapshotCounter &1 && eNums->numSnapshotEntities == svs.numSnapshotEntities-1) - { //we're full, and about to wrap around and stomp ents, so half the time send the first set without stomping. + if (sv.snapshotCounter & 1 && + eNums->numSnapshotEntities == + svs.numSnapshotEntities - 1) { // we're full, and about to wrap around and stomp ents, so half the time send the first set without stomping. return; } - eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number; + eNums->snapshotEntities[eNums->numSnapshotEntities] = gEnt->s.number; eNums->numSnapshotEntities++; } -//rww - bg_public.h won't cooperate in here -#define EF_PERMANENT 0x00080000 - -float sv_sightRangeForLevel[6] = -{ - 0,//FORCE_LEVEL_0 - 1024.f, //FORCE_LEVEL_1 - 2048.0f,//FORCE_LEVEL_2 - 4096.0f,//FORCE_LEVEL_3 - 4096.0f,//FORCE_LEVEL_4 - 4096.0f//FORCE_LEVEL_5 +// rww - bg_public.h won't cooperate in here +#define EF_PERMANENT 0x00080000 + +float sv_sightRangeForLevel[6] = { + 0, // FORCE_LEVEL_0 + 1024.f, // FORCE_LEVEL_1 + 2048.0f, // FORCE_LEVEL_2 + 4096.0f, // FORCE_LEVEL_3 + 4096.0f, // FORCE_LEVEL_4 + 4096.0f // FORCE_LEVEL_5 }; -qboolean SV_PlayerCanSeeEnt( gentity_t *ent, int sightLevel ) -{//return true if this ent is in view - //NOTE: this is similar to the func CG_PlayerCanSeeCent in cg_players +qboolean SV_PlayerCanSeeEnt(gentity_t *ent, int sightLevel) { // return true if this ent is in view + // NOTE: this is similar to the func CG_PlayerCanSeeCent in cg_players vec3_t viewOrg, viewAngles, viewFwd, dir2Ent; - if ( !ent ) - { + if (!ent) { return qfalse; } - if ( VM_Call( CG_CAMERA_POS, viewOrg)) - { - if ( VM_Call( CG_CAMERA_ANG, viewAngles)) - { - float dot = 0.25f;//1.0f; + if (VM_Call(CG_CAMERA_POS, viewOrg)) { + if (VM_Call(CG_CAMERA_ANG, viewAngles)) { + float dot = 0.25f; // 1.0f; float range = sv_sightRangeForLevel[sightLevel]; - VectorSubtract( ent->currentOrigin, viewOrg, dir2Ent ); - float entDist = VectorNormalize( dir2Ent ); + VectorSubtract(ent->currentOrigin, viewOrg, dir2Ent); + float entDist = VectorNormalize(dir2Ent); - if ( (ent->s.eFlags&EF_FORCE_VISIBLE) ) - {//no dist check on them? - } - else - { - if ( entDist < 128.0f ) - {//can always see them if they're really close + if ((ent->s.eFlags & EF_FORCE_VISIBLE)) { // no dist check on them? + } else { + if (entDist < 128.0f) { // can always see them if they're really close return qtrue; } - if ( entDist > range ) - {//too far away to see them + if (entDist > range) { // too far away to see them return qfalse; } } - dot += (0.99f-dot)*entDist/range;//the farther away they are, the more in front they have to be + dot += (0.99f - dot) * entDist / range; // the farther away they are, the more in front they have to be - AngleVectors( viewAngles, viewFwd, NULL, NULL ); - if ( DotProduct( viewFwd, dir2Ent ) < dot ) - { + AngleVectors(viewAngles, viewFwd, NULL, NULL); + if (DotProduct(viewFwd, dir2Ent) < dot) { return qfalse; } return qtrue; @@ -339,14 +324,13 @@ qboolean SV_PlayerCanSeeEnt( gentity_t *ent, int sightLevel ) SV_AddEntitiesVisibleFromPoint =============== */ -static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *frame, - snapshotEntityNumbers_t *eNums, qboolean portal ) { - int e, i; - gentity_t *ent; - svEntity_t *svEnt; - int l; - int clientarea, clientcluster; - int leafnum; +static void SV_AddEntitiesVisibleFromPoint(vec3_t origin, clientSnapshot_t *frame, snapshotEntityNumbers_t *eNums, qboolean portal) { + int e, i; + gentity_t *ent; + svEntity_t *svEnt; + int l; + int clientarea, clientcluster; + int leafnum; const byte *clientpvs; const byte *bitvector; #ifndef JK2_MODE @@ -356,83 +340,77 @@ static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *fra // during an error shutdown message we may need to transmit // the shutdown message after the server has shutdown, so // specfically check for it - if ( !sv.state ) { + if (!sv.state) { return; } - leafnum = CM_PointLeafnum (origin); - clientarea = CM_LeafArea (leafnum); - clientcluster = CM_LeafCluster (leafnum); + leafnum = CM_PointLeafnum(origin); + clientarea = CM_LeafArea(leafnum); + clientcluster = CM_LeafCluster(leafnum); // calculate the visible areas - frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea ); + frame->areabytes = CM_WriteAreaBits(frame->areabits, clientarea); - clientpvs = CM_ClusterPVS (clientcluster); + clientpvs = CM_ClusterPVS(clientcluster); #ifndef JK2_MODE - if ( !portal ) - {//not if this if through a portal...??? James said to do this... - if ( (frame->ps.forcePowersActive&(1<ps.forcePowersActive & (1 << FP_SEE))) { sightOn = qtrue; } } #endif // !JK2_MODE - for ( e = 0 ; e < ge->num_entities ; e++ ) { + for (e = 0; e < ge->num_entities; e++) { ent = SV_GentityNum(e); if (!ent->inuse) { continue; } - if (ent->s.eFlags & EF_PERMANENT) - { // he's permanent, so don't send him down! + if (ent->s.eFlags & EF_PERMANENT) { // he's permanent, so don't send him down! continue; } if (ent->s.number != e) { - Com_DPrintf ("FIXING ENT->S.NUMBER!!!\n"); + Com_DPrintf("FIXING ENT->S.NUMBER!!!\n"); ent->s.number = e; } // never send entities that aren't linked in - if ( !ent->linked ) { + if (!ent->linked) { continue; } // entities can be flagged to explicitly not be sent to the client - if ( ent->svFlags & SVF_NOCLIENT ) { + if (ent->svFlags & SVF_NOCLIENT) { continue; } - svEnt = SV_SvEntityForGentity( ent ); + svEnt = SV_SvEntityForGentity(ent); // don't double add an entity through portals - if ( svEnt->snapshotCounter == sv.snapshotCounter ) { + if (svEnt->snapshotCounter == sv.snapshotCounter) { continue; } // broadcast entities are always sent, and so is the main player so we don't see noclip weirdness - if ( ent->svFlags & SVF_BROADCAST || !e) { - SV_AddEntToSnapshot( svEnt, ent, eNums ); + if (ent->svFlags & SVF_BROADCAST || !e) { + SV_AddEntToSnapshot(svEnt, ent, eNums); continue; } #ifndef JK2_MODE - if (ent->s.isPortalEnt) - { //rww - portal entities are always sent as well - SV_AddEntToSnapshot( svEnt, ent, eNums ); + if (ent->s.isPortalEnt) { // rww - portal entities are always sent as well + SV_AddEntToSnapshot(svEnt, ent, eNums); continue; } #endif // !JK2_MODE #ifndef JK2_MODE - if ( sightOn ) - {//force sight is on, sees through portals, so draw them always if in radius - if ( SV_PlayerCanSeeEnt( ent, frame->ps.forcePowerLevel[FP_SEE] ) ) - {//entity is visible - SV_AddEntToSnapshot( svEnt, ent, eNums ); + if (sightOn) { // force sight is on, sees through portals, so draw them always if in radius + if (SV_PlayerCanSeeEnt(ent, frame->ps.forcePowerLevel[FP_SEE])) { // entity is visible + SV_AddEntToSnapshot(svEnt, ent, eNums); continue; } } @@ -440,40 +418,40 @@ static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *fra // ignore if not touching a PV leaf // check area - if ( !CM_AreasConnected( clientarea, svEnt->areanum ) ) { + if (!CM_AreasConnected(clientarea, svEnt->areanum)) { // doors can legally straddle two areas, so // we may need to check another one - if ( !CM_AreasConnected( clientarea, svEnt->areanum2 ) ) { - continue; // blocked by a door + if (!CM_AreasConnected(clientarea, svEnt->areanum2)) { + continue; // blocked by a door } } bitvector = clientpvs; // check individual leafs - if ( !svEnt->numClusters ) { + if (!svEnt->numClusters) { continue; } l = 0; - for ( i=0 ; i < svEnt->numClusters ; i++ ) { + for (i = 0; i < svEnt->numClusters; i++) { l = svEnt->clusternums[i]; - if ( bitvector[l >> 3] & (1 << (l&7) ) ) { + if (bitvector[l >> 3] & (1 << (l & 7))) { break; } } // if we haven't found it to be visible, // check overflow clusters that coudln't be stored - if ( i == svEnt->numClusters ) { - if ( svEnt->lastCluster ) { - for ( ; l <= svEnt->lastCluster ; l++ ) { - if ( bitvector[l >> 3] & (1 << (l&7) ) ) { + if (i == svEnt->numClusters) { + if (svEnt->lastCluster) { + for (; l <= svEnt->lastCluster; l++) { + if (bitvector[l >> 3] & (1 << (l & 7))) { break; } } - if ( l == svEnt->lastCluster ) { - continue; // not visible + if (l == svEnt->lastCluster) { + continue; // not visible } } else { continue; @@ -481,11 +459,11 @@ static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *fra } // add it - SV_AddEntToSnapshot( svEnt, ent, eNums ); + SV_AddEntToSnapshot(svEnt, ent, eNums); // if its a portal entity, add everything visible from its camera position - if ( ent->svFlags & SVF_PORTAL ) { - SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue ); + if (ent->svFlags & SVF_PORTAL) { + SV_AddEntitiesVisibleFromPoint(ent->s.origin2, frame, eNums, qtrue); } } } @@ -503,27 +481,27 @@ currently doesn't. For viewing through other player's eyes, clent can be something other than client->gentity ============= */ -static clientSnapshot_t *SV_BuildClientSnapshot( client_t *client ) { - vec3_t org; - clientSnapshot_t *frame; - snapshotEntityNumbers_t entityNumbers; - int i; - gentity_t *ent; - entityState_t *state; - gentity_t *clent; +static clientSnapshot_t *SV_BuildClientSnapshot(client_t *client) { + vec3_t org; + clientSnapshot_t *frame; + snapshotEntityNumbers_t entityNumbers; + int i; + gentity_t *ent; + entityState_t *state; + gentity_t *clent; // bump the counter used to prevent double adding sv.snapshotCounter++; // this is the frame we are creating - frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ]; + frame = &client->frames[client->netchan.outgoingSequence & PACKET_MASK]; // clear everything in this snapshot entityNumbers.numSnapshotEntities = 0; - memset( frame->areabits, 0, sizeof( frame->areabits ) ); + memset(frame->areabits, 0, sizeof(frame->areabits)); clent = client->gentity; - if ( !clent ) { + if (!clent) { return frame; } @@ -532,51 +510,47 @@ static clientSnapshot_t *SV_BuildClientSnapshot( client_t *client ) { // this stops the main client entity playerstate from being sent across, which has the effect of breaking // looping sounds for the main client. So I took it out. -/* { - int clientNum; - svEntity_t *svEnt; - clientNum = frame->ps.clientNum; - if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" ); + /* { + int clientNum; + svEntity_t *svEnt; + clientNum = frame->ps.clientNum; + if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) { + Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" ); + } + svEnt = &sv.svEntities[ clientNum ]; + // never send client's own entity, because it can + // be regenerated from the playerstate + svEnt->snapshotCounter = sv.snapshotCounter; } - svEnt = &sv.svEntities[ clientNum ]; - // never send client's own entity, because it can - // be regenerated from the playerstate - svEnt->snapshotCounter = sv.snapshotCounter; - } -*/ + */ // find the client's viewpoint - //if in camera mode use camera position instead - if ( VM_Call( CG_CAMERA_POS, org)) - { - //org[2] += clent->client->viewheight; - } - else - { - VectorCopy( clent->client->origin, org ); + // if in camera mode use camera position instead + if (VM_Call(CG_CAMERA_POS, org)) { + // org[2] += clent->client->viewheight; + } else { + VectorCopy(clent->client->origin, org); org[2] += clent->client->viewheight; -//============ + //============ // need to account for lean, or areaportal doors don't draw properly... -slc - if (frame->ps.leanofs != 0) - { - vec3_t right; - //add leaning offset + if (frame->ps.leanofs != 0) { + vec3_t right; + // add leaning offset vec3_t v3ViewAngles; VectorCopy(clent->client->viewangles, v3ViewAngles); - v3ViewAngles[2] += (float)frame->ps.leanofs/2; + v3ViewAngles[2] += (float)frame->ps.leanofs / 2; AngleVectors(v3ViewAngles, NULL, right, NULL); VectorMA(org, (float)frame->ps.leanofs, right, org); } -//============ + //============ } - VectorCopy( org, frame->ps.serverViewOrg ); - VectorCopy( org, clent->client->serverViewOrg ); + VectorCopy(org, frame->ps.serverViewOrg); + VectorCopy(org, clent->client->serverViewOrg); // add all the entities directly visible to the eye, which // may include portal entities that merge other viewpoints - SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse ); + SV_AddEntitiesVisibleFromPoint(org, frame, &entityNumbers, qfalse); /* //was in here for debugging- print list of all entities in snapshot when you go over the limit if ( entityNumbers.numSnapshotEntities >= 256 ) @@ -601,19 +575,18 @@ static clientSnapshot_t *SV_BuildClientSnapshot( client_t *client ) { // in the list which will need to be resorted for the delta compression // to work correctly. This also catches the error condition // of an entity being included twice. - qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities, - sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers ); + qsort(entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities, sizeof(entityNumbers.snapshotEntities[0]), SV_QsortEntityNumbers); // now that all viewpoint's areabits have been OR'd together, invert // all of them to make it a mask vector, which is what the renderer wants - for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) { + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { ((int *)frame->areabits)[i] = ((int *)frame->areabits)[i] ^ -1; } // copy the entity states out frame->num_entities = 0; frame->first_entity = svs.nextSnapshotEntities; - for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) { + for (i = 0; i < entityNumbers.numSnapshotEntities; i++) { ent = SV_GentityNum(entityNumbers.snapshotEntities[i]); state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities]; *state = ent->s; @@ -624,7 +597,6 @@ static clientSnapshot_t *SV_BuildClientSnapshot( client_t *client ) { return frame; } - /* ======================= SV_SendMessageToClient @@ -632,14 +604,14 @@ SV_SendMessageToClient Called by SV_SendClientSnapshot and SV_SendClientGameState ======================= */ -#define HEADER_RATE_BYTES 48 // include our header, IP header, and some overhead -void SV_SendMessageToClient( msg_t *msg, client_t *client ) { +#define HEADER_RATE_BYTES 48 // include our header, IP header, and some overhead +void SV_SendMessageToClient(msg_t *msg, client_t *client) { // record information about the message client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSize = msg->cursize; client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageSent = sv.time; // send the datagram - Netchan_Transmit( &client->netchan, msg->cursize, msg->data ); + Netchan_Transmit(&client->netchan, msg->cursize, msg->data); } /* @@ -650,12 +622,12 @@ This is just an empty message so that we can tell if the client dropped the gamestate that went out before ======================= */ -void SV_SendClientEmptyMessage( client_t *client ) { - msg_t msg; - byte buffer[10]; +void SV_SendClientEmptyMessage(client_t *client) { + msg_t msg; + byte buffer[10]; - MSG_Init( &msg, buffer, sizeof( buffer ) ); - SV_SendMessageToClient( &msg, client ); + MSG_Init(&msg, buffer, sizeof(buffer)); + SV_SendMessageToClient(&msg, client); } /* @@ -663,62 +635,60 @@ void SV_SendClientEmptyMessage( client_t *client ) { SV_SendClientSnapshot ======================= */ -void SV_SendClientSnapshot( client_t *client ) { - byte msg_buf[MAX_MSGLEN]; - msg_t msg; +void SV_SendClientSnapshot(client_t *client) { + byte msg_buf[MAX_MSGLEN]; + msg_t msg; // build the snapshot - SV_BuildClientSnapshot( client ); + SV_BuildClientSnapshot(client); // bots need to have their snapshots build, but // the query them directly without needing to be sent - if ( client->gentity && client->gentity->svFlags & SVF_BOT ) { + if (client->gentity && client->gentity->svFlags & SVF_BOT) { return; } - MSG_Init (&msg, msg_buf, sizeof(msg_buf)); + MSG_Init(&msg, msg_buf, sizeof(msg_buf)); msg.allowoverflow = qtrue; // (re)send any reliable server commands - SV_UpdateServerCommandsToClient( client, &msg ); + SV_UpdateServerCommandsToClient(client, &msg); // send over all the relevant entityState_t // and the playerState_t - SV_WriteSnapshotToClient( client, &msg ); + SV_WriteSnapshotToClient(client, &msg); // check for overflow - if ( msg.overflowed ) { - Com_Printf ("WARNING: msg overflowed for %s\n", client->name); - MSG_Clear (&msg); + if (msg.overflowed) { + Com_Printf("WARNING: msg overflowed for %s\n", client->name); + MSG_Clear(&msg); } - SV_SendMessageToClient( &msg, client ); + SV_SendMessageToClient(&msg, client); } - /* ======================= SV_SendClientMessages ======================= */ -void SV_SendClientMessages( void ) { - int i; - client_t *c; +void SV_SendClientMessages(void) { + int i; + client_t *c; // send a message to each connected client - for (i=0, c = svs.clients ; i < 1 ; i++, c++) { + for (i = 0, c = svs.clients; i < 1; i++, c++) { if (!c->state) { - continue; // not connected + continue; // not connected } - if ( c->state != CS_ACTIVE ) { - if ( c->state != CS_ZOMBIE ) { - SV_SendClientEmptyMessage( c ); + if (c->state != CS_ACTIVE) { + if (c->state != CS_ZOMBIE) { + SV_SendClientEmptyMessage(c); } continue; } - SV_SendClientSnapshot( c ); + SV_SendClientSnapshot(c); } } - diff --git a/code/server/sv_world.cpp b/code/server/sv_world.cpp index be960b5286..6fd3c6bdd5 100644 --- a/code/server/sv_world.cpp +++ b/code/server/sv_world.cpp @@ -26,28 +26,28 @@ along with this program; if not, see . #include "../server/exe_headers.h" #include "../qcommon/cm_local.h" - /* +/* Ghoul2 Insert Start */ #if !defined(GHOUL2_SHARED_H_INC) - #include "../game/ghoul2_shared.h" //for CGhoul2Info_v +#include "../game/ghoul2_shared.h" //for CGhoul2Info_v #endif #if !defined(G2_H_INC) - #include "../ghoul2/G2.h" +#include "../ghoul2/G2.h" #endif -#if !defined (MINIHEAP_H_INC) - #include "../qcommon/MiniHeap.h" +#if !defined(MINIHEAP_H_INC) +#include "../qcommon/MiniHeap.h" #endif #ifdef _DEBUG - #include +#include #endif //_DEBUG /* Ghoul2 Insert End */ -#if 0 //G2_SUPERSIZEDBBOX is not being used +#if 0 // G2_SUPERSIZEDBBOX is not being used static const float superSizedAdd=64.0f; #endif @@ -60,18 +60,16 @@ given entity. If the entity is a bsp model, the headnode will be returned, otherwise a custom box tree will be constructed. ================ */ -clipHandle_t SV_ClipHandleForEntity( const gentity_t *ent ) { - if ( ent->bmodel ) { +clipHandle_t SV_ClipHandleForEntity(const gentity_t *ent) { + if (ent->bmodel) { // explicit hulls in the BSP model - return CM_InlineModel( ent->s.modelindex ); + return CM_InlineModel(ent->s.modelindex); } // create a temp tree from bounding box sizes - return CM_TempBoxModel( ent->mins, ent->maxs );//, ent->contents ); + return CM_TempBoxModel(ent->mins, ent->maxs); //, ent->contents ); } - - /* =============================================================================== @@ -86,17 +84,17 @@ them, which prevents having to deal with multiple fragments of a single entity. */ typedef struct worldSector_s { - int axis; // -1 = leaf node - float dist; - struct worldSector_s *children[2]; - svEntity_t *entities; + int axis; // -1 = leaf node + float dist; + struct worldSector_s *children[2]; + svEntity_t *entities; } worldSector_t; -#define AREA_DEPTH 8 -#define AREA_NODES 1024 +#define AREA_DEPTH 8 +#define AREA_NODES 1024 -worldSector_t sv_worldSectors[AREA_NODES]; -int sv_numworldSectors; +worldSector_t sv_worldSectors[AREA_NODES]; +int sv_numworldSectors; /* =============== @@ -105,10 +103,10 @@ SV_CreateworldSector Builds a uniformly subdivided tree for the given world size =============== */ -worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { - worldSector_t *anode; - vec3_t size; - vec3_t mins1, maxs1, mins2, maxs2; +worldSector_t *SV_CreateworldSector(int depth, vec3_t mins, vec3_t maxs) { + worldSector_t *anode; + vec3_t size; + vec3_t mins1, maxs1, mins2, maxs2; anode = &sv_worldSectors[sv_numworldSectors]; sv_numworldSectors++; @@ -119,7 +117,7 @@ worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { return anode; } - VectorSubtract (maxs, mins, size); + VectorSubtract(maxs, mins, size); if (size[0] > size[1]) { anode->axis = 0; } else { @@ -127,15 +125,15 @@ worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { } anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]); - VectorCopy (mins, mins1); - VectorCopy (mins, mins2); - VectorCopy (maxs, maxs1); - VectorCopy (maxs, maxs2); + VectorCopy(mins, mins1); + VectorCopy(mins, mins2); + VectorCopy(maxs, maxs1); + VectorCopy(maxs, maxs2); maxs1[anode->axis] = mins2[anode->axis] = anode->dist; - anode->children[0] = SV_CreateworldSector (depth+1, mins2, maxs2); - anode->children[1] = SV_CreateworldSector (depth+1, mins1, maxs1); + anode->children[0] = SV_CreateworldSector(depth + 1, mins2, maxs2); + anode->children[1] = SV_CreateworldSector(depth + 1, mins1, maxs1); return anode; } @@ -146,117 +144,115 @@ SV_ClearWorld =============== */ -void SV_ClearWorld( void ) { - clipHandle_t h; - vec3_t mins, maxs; +void SV_ClearWorld(void) { + clipHandle_t h; + vec3_t mins, maxs; - memset( sv_worldSectors, 0, sizeof(sv_worldSectors) ); + memset(sv_worldSectors, 0, sizeof(sv_worldSectors)); sv_numworldSectors = 0; // get world map bounds - h = CM_InlineModel( 0 ); - CM_ModelBounds( cmg, h, mins, maxs ); - SV_CreateworldSector( 0, mins, maxs ); + h = CM_InlineModel(0); + CM_ModelBounds(cmg, h, mins, maxs); + SV_CreateworldSector(0, mins, maxs); } - /* =============== SV_UnlinkEntity =============== */ -void SV_UnlinkEntity( gentity_t *gEnt ) { - svEntity_t *ent; - svEntity_t *scan; - worldSector_t *ws; +void SV_UnlinkEntity(gentity_t *gEnt) { + svEntity_t *ent; + svEntity_t *scan; + worldSector_t *ws; // this should never be called with a freed entity - if ( !gEnt->inuse ) { + if (!gEnt->inuse) { return; } - ent = SV_SvEntityForGentity( gEnt ); + ent = SV_SvEntityForGentity(gEnt); gEnt->linked = qfalse; ws = ent->worldSector; - if ( !ws ) { - return; // not linked in anywhere + if (!ws) { + return; // not linked in anywhere } ent->worldSector = NULL; - if ( ws->entities == ent ) { + if (ws->entities == ent) { ws->entities = ent->nextEntityInWorldSector; return; } - for ( scan = ws->entities ; scan ; scan = scan->nextEntityInWorldSector ) { - if ( scan->nextEntityInWorldSector == ent ) { + for (scan = ws->entities; scan; scan = scan->nextEntityInWorldSector) { + if (scan->nextEntityInWorldSector == ent) { scan->nextEntityInWorldSector = ent->nextEntityInWorldSector; return; } } - Com_Printf( "WARNING: SV_UnlinkEntity: not found in worldSector\n" ); + Com_Printf("WARNING: SV_UnlinkEntity: not found in worldSector\n"); } - /* =============== SV_LinkEntity =============== */ -#define MAX_TOTAL_ENT_LEAFS 128 -void SV_LinkEntity( gentity_t *gEnt ) { - worldSector_t *node; - int leafs[MAX_TOTAL_ENT_LEAFS]; - int cluster; - int num_leafs; - int i, j, k; - int area; - int lastLeaf; - float *origin, *angles; - svEntity_t *ent; +#define MAX_TOTAL_ENT_LEAFS 128 +void SV_LinkEntity(gentity_t *gEnt) { + worldSector_t *node; + int leafs[MAX_TOTAL_ENT_LEAFS]; + int cluster; + int num_leafs; + int i, j, k; + int area; + int lastLeaf; + float *origin, *angles; + svEntity_t *ent; // this should never be called with a freed entity - if ( !gEnt->inuse ) { + if (!gEnt->inuse) { return; } - ent = SV_SvEntityForGentity( gEnt ); + ent = SV_SvEntityForGentity(gEnt); - if ( ent->worldSector ) { - SV_UnlinkEntity( gEnt ); // unlink from old position + if (ent->worldSector) { + SV_UnlinkEntity(gEnt); // unlink from old position } // encode the size into the entityState_t for client prediction - if ( gEnt->bmodel ) { - gEnt->s.solid = SOLID_BMODEL; // a solid_box will never create this value - } else if ( gEnt->contents & ( CONTENTS_SOLID | CONTENTS_BODY ) ) { + if (gEnt->bmodel) { + gEnt->s.solid = SOLID_BMODEL; // a solid_box will never create this value + } else if (gEnt->contents & (CONTENTS_SOLID | CONTENTS_BODY)) { // assume that x/y are equal and symetric i = gEnt->maxs[0]; - if (i<1) + if (i < 1) i = 1; - if (i>255) + if (i > 255) i = 255; // z is not symetric j = (-gEnt->mins[2]); - if (j<1) + if (j < 1) j = 1; - if (j>255) + if (j > 255) j = 255; // and z maxs can be negative... - k = (gEnt->maxs[2]+32); - if (k<1) + k = (gEnt->maxs[2] + 32); + if (k < 1) k = 1; - if (k>255) + if (k > 255) k = 255; - gEnt->s.solid = (k<<16) | (j<<8) | i; + gEnt->s.solid = (k << 16) | (j << 8) | i; } else { gEnt->s.solid = 0; } @@ -266,20 +262,19 @@ void SV_LinkEntity( gentity_t *gEnt ) { angles = gEnt->currentAngles; // set the abs box - if ( gEnt->bmodel && (angles[0] || angles[1] || angles[2]) ) - { // expand for rotation - float max; - int i; + if (gEnt->bmodel && (angles[0] || angles[1] || angles[2])) { // expand for rotation + float max; + int i; - max = RadiusFromBounds( gEnt->mins, gEnt->maxs ); - for (i=0 ; i<3 ; i++) { + max = RadiusFromBounds(gEnt->mins, gEnt->maxs); + for (i = 0; i < 3; i++) { gEnt->absmin[i] = origin[i] - max; gEnt->absmax[i] = origin[i] + max; } } else { // normal - VectorAdd (origin, gEnt->mins, gEnt->absmin); - VectorAdd (origin, gEnt->maxs, gEnt->absmax); + VectorAdd(origin, gEnt->mins, gEnt->absmin); + VectorAdd(origin, gEnt->maxs, gEnt->absmax); } // because movement is clipped an epsilon away from an actual edge, @@ -297,27 +292,23 @@ void SV_LinkEntity( gentity_t *gEnt ) { ent->areanum = -1; ent->areanum2 = -1; - //get all leafs, including solids - num_leafs = CM_BoxLeafnums( gEnt->absmin, gEnt->absmax, - leafs, MAX_TOTAL_ENT_LEAFS, &lastLeaf ); + // get all leafs, including solids + num_leafs = CM_BoxLeafnums(gEnt->absmin, gEnt->absmax, leafs, MAX_TOTAL_ENT_LEAFS, &lastLeaf); // if none of the leafs were inside the map, the // entity is outside the world and can be considered unlinked - if ( !num_leafs ) { + if (!num_leafs) { return; } // set areas, even from clusters that don't fit in the entity array - for (i=0 ; iareanum != -1 && ent->areanum != area) { if (ent->areanum2 != -1 && ent->areanum2 != area && sv.state == SS_LOADING) { - Com_DPrintf ("Object %i touching 3 areas at %f %f %f\n", - gEnt->s.number, - gEnt->absmin[0], gEnt->absmin[1], gEnt->absmin[2]); + Com_DPrintf("Object %i touching 3 areas at %f %f %f\n", gEnt->s.number, gEnt->absmin[0], gEnt->absmin[1], gEnt->absmin[2]); } ent->areanum2 = area; } else { @@ -328,33 +319,32 @@ void SV_LinkEntity( gentity_t *gEnt ) { // store as many explicit clusters as we can ent->numClusters = 0; - for (i=0 ; i < num_leafs ; i++) { - cluster = CM_LeafCluster( leafs[i] ); - if ( cluster != -1 ) { + for (i = 0; i < num_leafs; i++) { + cluster = CM_LeafCluster(leafs[i]); + if (cluster != -1) { ent->clusternums[ent->numClusters++] = cluster; - if ( ent->numClusters == MAX_ENT_CLUSTERS ) { - break; + if (ent->numClusters == MAX_ENT_CLUSTERS) { + break; } } } // store off a last cluster if we need to - if ( i != num_leafs ) { - ent->lastCluster = CM_LeafCluster( lastLeaf ); + if (i != num_leafs) { + ent->lastCluster = CM_LeafCluster(lastLeaf); } // find the first world sector node that the ent's box crosses node = sv_worldSectors; - while (1) - { + while (1) { if (node->axis == -1) break; - if ( gEnt->absmin[node->axis] > node->dist) + if (gEnt->absmin[node->axis] > node->dist) node = node->children[0]; - else if ( gEnt->absmax[node->axis] < node->dist) + else if (gEnt->absmax[node->axis] < node->dist) node = node->children[1]; else - break; // crosses the node + break; // crosses the node } // link it in @@ -376,39 +366,34 @@ bounds. This does NOT mean that they actually touch in the case of bmodels. */ typedef struct { - const float *mins; - const float *maxs; - gentity_t **list; - int count, maxcount; + const float *mins; + const float *maxs; + gentity_t **list; + int count, maxcount; } areaParms_t; - /* ==================== SV_AreaEntities_r ==================== */ -void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { - svEntity_t *check, *next; - gentity_t *gcheck; +void SV_AreaEntities_r(worldSector_t *node, areaParms_t *ap) { + svEntity_t *check, *next; + gentity_t *gcheck; - for ( check = node->entities ; check ; check = next ) { + for (check = node->entities; check; check = next) { next = check->nextEntityInWorldSector; - gcheck = SV_GEntityForSvEntity( check ); + gcheck = SV_GEntityForSvEntity(check); - if ( gcheck->absmin[0] > ap->maxs[0] - || gcheck->absmin[1] > ap->maxs[1] - || gcheck->absmin[2] > ap->maxs[2] - || gcheck->absmax[0] < ap->mins[0] - || gcheck->absmax[1] < ap->mins[1] - || gcheck->absmax[2] < ap->mins[2]) { + if (gcheck->absmin[0] > ap->maxs[0] || gcheck->absmin[1] > ap->maxs[1] || gcheck->absmin[2] > ap->maxs[2] || gcheck->absmax[0] < ap->mins[0] || + gcheck->absmax[1] < ap->mins[1] || gcheck->absmax[2] < ap->mins[2]) { continue; } - if ( ap->count == ap->maxcount ) { - Com_DPrintf ("SV_AreaEntities: reached maxcount (%d)\n",ap->maxcount); + if (ap->count == ap->maxcount) { + Com_DPrintf("SV_AreaEntities: reached maxcount (%d)\n", ap->maxcount); return; } @@ -417,15 +402,15 @@ void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { } if (node->axis == -1) { - return; // terminal node + return; // terminal node } // recurse down both sides - if ( ap->maxs[node->axis] > node->dist ) { - SV_AreaEntities_r ( node->children[0], ap ); + if (ap->maxs[node->axis] > node->dist) { + SV_AreaEntities_r(node->children[0], ap); } - if ( ap->mins[node->axis] < node->dist ) { - SV_AreaEntities_r ( node->children[1], ap ); + if (ap->mins[node->axis] < node->dist) { + SV_AreaEntities_r(node->children[1], ap); } } @@ -434,8 +419,8 @@ void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { SV_AreaEntities ================ */ -int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, gentity_t **elist, int maxcount ) { - areaParms_t ap; +int SV_AreaEntities(const vec3_t mins, const vec3_t maxs, gentity_t **elist, int maxcount) { + areaParms_t ap; ap.mins = mins; ap.maxs = maxs; @@ -443,7 +428,7 @@ int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, gentity_t **elist, in ap.count = 0; ap.maxcount = maxcount; - SV_AreaEntities_r( sv_worldSectors, &ap ); + SV_AreaEntities_r(sv_worldSectors, &ap); return ap.count; } @@ -455,199 +440,186 @@ SV_SectorList_f */ #if 1 -void SV_SectorList_f( void ) { - int i, c; - worldSector_t *sec; - svEntity_t *ent; +void SV_SectorList_f(void) { + int i, c; + worldSector_t *sec; + svEntity_t *ent; - for ( i = 0 ; i < AREA_NODES ; i++ ) { + for (i = 0; i < AREA_NODES; i++) { sec = &sv_worldSectors[i]; c = 0; - for ( ent = sec->entities ; ent ; ent = ent->nextEntityInWorldSector ) { + for (ent = sec->entities; ent; ent = ent->nextEntityInWorldSector) { c++; } - Com_Printf( "sector %i: %i entities\n", i, c ); + Com_Printf("sector %i: %i entities\n", i, c); } } #else -#pragma warning (push, 3) //go back down to 3 for the stl include +#pragma warning(push, 3) // go back down to 3 for the stl include #include #include -#pragma warning (pop) +#pragma warning(pop) -class CBBox -{ -public: +class CBBox { + public: float mMins[3]; float mMaxs[3]; - CBBox(vec3_t mins,vec3_t maxs) - { - VectorCopy(mins,mMins); - VectorCopy(maxs,mMaxs); + CBBox(vec3_t mins, vec3_t maxs) { + VectorCopy(mins, mMins); + VectorCopy(maxs, mMaxs); } }; -static multimap > > entStats; +static multimap>> entStats; -void SV_AreaEntitiesTree( worldSector_t *node, areaParms_t *ap, int level ) -{ - svEntity_t *check, *next; - gentity_t *gcheck; - int count; - list bblist; +void SV_AreaEntitiesTree(worldSector_t *node, areaParms_t *ap, int level) { + svEntity_t *check, *next; + gentity_t *gcheck; + int count; + list bblist; count = 0; - for ( check = node->entities ; check ; check = next ) - { + for (check = node->entities; check; check = next) { next = check->nextEntityInWorldSector; - gcheck = SV_GEntityForSvEntity( check ); + gcheck = SV_GEntityForSvEntity(check); - CBBox bBox(gcheck->absmin,gcheck->absmax); + CBBox bBox(gcheck->absmin, gcheck->absmax); bblist.push_back(bBox); count++; } - entStats.insert(pair > >(level,pair >(count,bblist))); - if (node->axis == -1) - { - return; // terminal node + entStats.insert(pair>>(level, pair>(count, bblist))); + if (node->axis == -1) { + return; // terminal node } // recurse down both sides - SV_AreaEntitiesTree ( node->children[0], ap, level+1 ); - SV_AreaEntitiesTree ( node->children[1], ap, level+1 ); + SV_AreaEntitiesTree(node->children[0], ap, level + 1); + SV_AreaEntitiesTree(node->children[1], ap, level + 1); } -void SV_SectorList_f( void ) -{ - areaParms_t ap; +void SV_SectorList_f(void) { + areaParms_t ap; -// ap.mins = mins; -// ap.maxs = maxs; -// ap.list = list; -// ap.count = 0; -// ap.maxcount = maxcount; + // ap.mins = mins; + // ap.maxs = maxs; + // ap.list = list; + // ap.count = 0; + // ap.maxcount = maxcount; entStats.clear(); - SV_AreaEntitiesTree(sv_worldSectors,&ap,0); + SV_AreaEntitiesTree(sv_worldSectors, &ap, 0); char mess[1000]; - multimap > >::iterator j; - for(j=entStats.begin();j!=entStats.end();j++) - { - sprintf(mess,"**************************************************\n"); + multimap>>::iterator j; + for (j = entStats.begin(); j != entStats.end(); j++) { + sprintf(mess, "**************************************************\n"); Sleep(5); OutputDebugString(mess); - sprintf(mess,"level=%i, count=%i\n",(*j).first,(*j).second.first); + sprintf(mess, "level=%i, count=%i\n", (*j).first, (*j).second.first); Sleep(5); OutputDebugString(mess); list::iterator k; - for(k=(*j).second.second.begin();k!=(*j).second.second.end();k++) - { - sprintf(mess,"mins=%f %f %f, maxs=%f %f %f\n", - (*k).mMins[0],(*k).mMins[1],(*k).mMins[2],(*k).mMaxs[0],(*k).mMaxs[1],(*k).mMaxs[2]); + for (k = (*j).second.second.begin(); k != (*j).second.second.end(); k++) { + sprintf(mess, "mins=%f %f %f, maxs=%f %f %f\n", (*k).mMins[0], (*k).mMins[1], (*k).mMins[2], (*k).mMaxs[0], (*k).mMaxs[1], (*k).mMaxs[2]); OutputDebugString(mess); } } - } #endif //=========================================================================== - typedef struct { - vec3_t boxmins, boxmaxs;// enclose the test object along entire move - const float *mins; - const float *maxs; // size of the moving object -/* -Ghoul2 Insert Start -*/ - vec3_t start; -/* -Ghoul2 Insert End -*/ - vec3_t end; - int passEntityNum; - int contentmask; -/* -Ghoul2 Insert Start -*/ - EG2_Collision eG2TraceType; - int useLod; - trace_t trace; // make sure nothing goes under here for Ghoul2 collision purposes -/* -Ghoul2 Insert End -*/ + vec3_t boxmins, boxmaxs; // enclose the test object along entire move + const float *mins; + const float *maxs; // size of the moving object + /* + Ghoul2 Insert Start + */ + vec3_t start; + /* + Ghoul2 Insert End + */ + vec3_t end; + int passEntityNum; + int contentmask; + /* + Ghoul2 Insert Start + */ + EG2_Collision eG2TraceType; + int useLod; + trace_t trace; // make sure nothing goes under here for Ghoul2 collision purposes + /* + Ghoul2 Insert End + */ } moveclip_t; - /* ==================== SV_ClipMoveToEntities ==================== */ -void SV_ClipMoveToEntities( moveclip_t *clip ) { - int i, num; - gentity_t *touchlist[MAX_GENTITIES], *touch, *owner; - trace_t trace, oldTrace; - clipHandle_t clipHandle; - const float *origin, *angles; +void SV_ClipMoveToEntities(moveclip_t *clip) { + int i, num; + gentity_t *touchlist[MAX_GENTITIES], *touch, *owner; + trace_t trace, oldTrace; + clipHandle_t clipHandle; + const float *origin, *angles; - num = SV_AreaEntities( clip->boxmins, clip->boxmaxs, touchlist, MAX_GENTITIES); + num = SV_AreaEntities(clip->boxmins, clip->boxmaxs, touchlist, MAX_GENTITIES); - if ( clip->passEntityNum != ENTITYNUM_NONE ) { - owner = ( SV_GentityNum( clip->passEntityNum ) )->owner; + if (clip->passEntityNum != ENTITYNUM_NONE) { + owner = (SV_GentityNum(clip->passEntityNum))->owner; } else { owner = NULL; } - for ( i=0 ; itrace.allsolid) { return; } touch = touchlist[i]; // see if we should ignore this entity - if ( clip->passEntityNum != ENTITYNUM_NONE ) { + if (clip->passEntityNum != ENTITYNUM_NONE) { if (touch->s.number == clip->passEntityNum) { continue; // don't clip against the pass entity } if (touch->owner && touch->owner->s.number == clip->passEntityNum) { - continue; // don't clip against own missiles + continue; // don't clip against own missiles } - if ( owner == touch) { - continue; // don't clip against owner + if (owner == touch) { + continue; // don't clip against owner } - if ( owner && touch->owner == owner) { - continue; // don't clip against other missiles from our owner + if (owner && touch->owner == owner) { + continue; // don't clip against other missiles from our owner } } // if it doesn't have any brushes of a type we // are looking for, ignore it - if ( ! ( clip->contentmask & touch->contents ) ) { + if (!(clip->contentmask & touch->contents)) { continue; } // might intersect, so do an exact clip - clipHandle = SV_ClipHandleForEntity (touch); + clipHandle = SV_ClipHandleForEntity(touch); origin = touch->currentOrigin; angles = touch->currentAngles; - - if ( !touch->bmodel ) { - angles = vec3_origin; // boxes don't rotate + if (!touch->bmodel) { + angles = vec3_origin; // boxes don't rotate } -#if 0 //G2_SUPERSIZEDBBOX is not being used +#if 0 // G2_SUPERSIZEDBBOX is not being used bool shrinkBox=true; if (clip->eG2TraceType != G2_SUPERSIZEDBBOX) @@ -677,153 +649,127 @@ void SV_ClipMoveToEntities( moveclip_t *clip ) { { #ifdef __MACOS__ // compiler bug with const - CM_TransformedBoxTrace ( &trace, (float *)clip->start, (float *)clip->end, - (float *)clip->mins, (float *)clip->maxs, clipHandle, clip->contentmask, - origin, angles); + CM_TransformedBoxTrace(&trace, (float *)clip->start, (float *)clip->end, (float *)clip->mins, (float *)clip->maxs, clipHandle, clip->contentmask, + origin, angles); #else - CM_TransformedBoxTrace ( &trace, clip->start, clip->end, - clip->mins, clip->maxs, clipHandle, clip->contentmask, - origin, angles); + CM_TransformedBoxTrace(&trace, clip->start, clip->end, clip->mins, clip->maxs, clipHandle, clip->contentmask, origin, angles); #endif - //FIXME: when startsolid in another ent, doesn't return correct entityNum - //ALSO: 2 players can be standing next to each other and this function will - //think they're in each other!!! + // FIXME: when startsolid in another ent, doesn't return correct entityNum + // ALSO: 2 players can be standing next to each other and this function will + // think they're in each other!!! } oldTrace = clip->trace; - if ( trace.allsolid ) - { - if(!clip->trace.allsolid) - {//We didn't come in here all solid, so set the clip->trace's entityNum + if (trace.allsolid) { + if (!clip->trace.allsolid) { // We didn't come in here all solid, so set the clip->trace's entityNum clip->trace.entityNum = touch->s.number; } clip->trace.allsolid = qtrue; trace.entityNum = touch->s.number; - } - else if ( trace.startsolid ) - { - if(!clip->trace.startsolid) - {//We didn't come in here starting solid, so set the clip->trace's entityNum + } else if (trace.startsolid) { + if (!clip->trace.startsolid) { // We didn't come in here starting solid, so set the clip->trace's entityNum clip->trace.entityNum = touch->s.number; } clip->trace.startsolid = qtrue; trace.entityNum = touch->s.number; } - if ( trace.fraction < clip->trace.fraction ) - { - qboolean oldStart; + if (trace.fraction < clip->trace.fraction) { + qboolean oldStart; // make sure we keep a startsolid from a previous trace oldStart = clip->trace.startsolid; trace.entityNum = touch->s.number; clip->trace = trace; - if ( oldStart ) - { + if (oldStart) { clip->trace.startsolid = qtrue; } } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // decide if we should do the ghoul2 collision detection right here - if ((trace.entityNum == touch->s.number) && (clip->eG2TraceType != G2_NOCOLLIDE)) - { + if ((trace.entityNum == touch->s.number) && (clip->eG2TraceType != G2_NOCOLLIDE)) { // do we actually have a ghoul2 model here? - if (touch->ghoul2.size() && !(touch->contents & CONTENTS_LIGHTSABER)) - { - int oldTraceRecSize = 0; - int newTraceRecSize = 0; - int z; + if (touch->ghoul2.size() && !(touch->contents & CONTENTS_LIGHTSABER)) { + int oldTraceRecSize = 0; + int newTraceRecSize = 0; + int z; // we have to do this because sometimes you may hit a model's bounding box, but not actually penetrate the Ghoul2 Models polygons // this is, needless to say, not good. So we must check to see if we did actually hit the model, and if not, reset the trace stuff // to what it was to begin with // set our trace record size - for (z=0;ztrace.G2CollisionMap[z].mEntityNum != -1) - { + for (z = 0; z < MAX_G2_COLLISIONS; z++) { + if (clip->trace.G2CollisionMap[z].mEntityNum != -1) { oldTraceRecSize++; } } // if we are looking at an entity then use the player state to get it's angles and origin from float radius; -#if 0 //G2_SUPERSIZEDBBOX is not being used +#if 0 // G2_SUPERSIZEDBBOX is not being used if (clip->eG2TraceType == G2_SUPERSIZEDBBOX) { radius=(clip->maxs[0]-clip->mins[0]-2.0f*superSizedAdd)/2.0f; } else #endif - { - radius=(clip->maxs[0]-clip->mins[0])/2.0f; - } - if (touch->client) - { + { radius = (clip->maxs[0] - clip->mins[0]) / 2.0f; } + if (touch->client) { vec3_t world_angles; - world_angles[PITCH] = 0; - //legs do not *always* point toward the viewangles! - //world_angles[YAW] = touch->client->viewangles[YAW]; - world_angles[YAW] = touch->client->legsYaw; - world_angles[ROLL] = 0; + world_angles[PITCH] = 0; + // legs do not *always* point toward the viewangles! + // world_angles[YAW] = touch->client->viewangles[YAW]; + world_angles[YAW] = touch->client->legsYaw; + world_angles[ROLL] = 0; - re.G2API_CollisionDetect(clip->trace.G2CollisionMap, touch->ghoul2, - world_angles, touch->client->origin, sv.time, touch->s.number, clip->start, clip->end, touch->s.modelScale, G2VertSpaceServer, clip->eG2TraceType, clip->useLod,radius); + re.G2API_CollisionDetect(clip->trace.G2CollisionMap, touch->ghoul2, world_angles, touch->client->origin, sv.time, touch->s.number, + clip->start, clip->end, touch->s.modelScale, G2VertSpaceServer, clip->eG2TraceType, clip->useLod, radius); } // no, so use the normal entity state - else - { - //use the correct origin and angles! is this right now? - re.G2API_CollisionDetect(clip->trace.G2CollisionMap, touch->ghoul2, - touch->currentAngles, touch->currentOrigin, sv.time, touch->s.number, clip->start, clip->end, touch->s.modelScale, G2VertSpaceServer, clip->eG2TraceType, clip->useLod,radius); + else { + // use the correct origin and angles! is this right now? + re.G2API_CollisionDetect(clip->trace.G2CollisionMap, touch->ghoul2, touch->currentAngles, touch->currentOrigin, sv.time, touch->s.number, + clip->start, clip->end, touch->s.modelScale, G2VertSpaceServer, clip->eG2TraceType, clip->useLod, radius); } // set our new trace record size - for (z=0;ztrace.G2CollisionMap[z].mEntityNum != -1) - { + for (z = 0; z < MAX_G2_COLLISIONS; z++) { + if (clip->trace.G2CollisionMap[z].mEntityNum != -1) { newTraceRecSize++; } } // did we actually touch this model? If not, lets reset this ent as being hit.. - if (newTraceRecSize == oldTraceRecSize) - { + if (newTraceRecSize == oldTraceRecSize) { clip->trace = oldTrace; - } - else//this trace was valid, so copy the best collision into quake trace place info + } else // this trace was valid, so copy the best collision into quake trace place info { - for (z=0;ztrace.G2CollisionMap[z].mEntityNum==touch->s.number) - { + for (z = 0; z < MAX_G2_COLLISIONS; z++) { + if (clip->trace.G2CollisionMap[z].mEntityNum == touch->s.number) { clip->trace.plane.normal[0] = clip->trace.G2CollisionMap[z].mCollisionNormal[0]; clip->trace.plane.normal[1] = clip->trace.G2CollisionMap[z].mCollisionNormal[1]; clip->trace.plane.normal[2] = clip->trace.G2CollisionMap[z].mCollisionNormal[2]; break; } } - assert(ztrace.plane.normal)>0.1f); + assert(z < MAX_G2_COLLISIONS); // hmm well ah, weird + assert(VectorLength(clip->trace.plane.normal) > 0.1f); } } } -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert End + */ } } - /* ================== SV_Trace @@ -835,71 +781,71 @@ passEntityNum and entities owned by passEntityNum are explicitly not checked. /* Ghoul2 Insert Start */ -void SV_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) { +void SV_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, + const EG2_Collision eG2TraceType, const int useLod) { /* Ghoul2 Insert End */ #ifdef _DEBUG - assert( !Q_isnan(start[0])&&!Q_isnan(start[1])&&!Q_isnan(start[2])&&!Q_isnan(end[0])&&!Q_isnan(end[1])&&!Q_isnan(end[2])); -#endif// _DEBUG + assert(!Q_isnan(start[0]) && !Q_isnan(start[1]) && !Q_isnan(start[2]) && !Q_isnan(end[0]) && !Q_isnan(end[1]) && !Q_isnan(end[2])); +#endif // _DEBUG - moveclip_t clip; - int i; -// int startMS, endMS; - float world_frac; + moveclip_t clip; + int i; + // int startMS, endMS; + float world_frac; /* startMS = Sys_Milliseconds (); numTraces++; */ - if ( !mins ) { + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } - memset ( &clip, 0, sizeof ( moveclip_t ) - sizeof(clip.trace.G2CollisionMap )); + memset(&clip, 0, sizeof(moveclip_t) - sizeof(clip.trace.G2CollisionMap)); // clip to world - //NOTE: this will stop not only on static architecture but also entity brushes such as - //doors, etc. This prevents us from being able to shorten the trace so that we can - //ignore all ents past this endpoint... perhaps need to check the entityNum in this - //BoxTrace or have it not clip against entity brushes here. - CM_BoxTrace( &clip.trace, start, end, mins, maxs, 0, contentmask ); + // NOTE: this will stop not only on static architecture but also entity brushes such as + // doors, etc. This prevents us from being able to shorten the trace so that we can + // ignore all ents past this endpoint... perhaps need to check the entityNum in this + // BoxTrace or have it not clip against entity brushes here. + CM_BoxTrace(&clip.trace, start, end, mins, maxs, 0, contentmask); clip.trace.entityNum = clip.trace.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; - if ( clip.trace.fraction == 0 ) - {// blocked immediately by the world + if (clip.trace.fraction == 0) { // blocked immediately by the world *results = clip.trace; -// goto addtime; + // goto addtime; return; } clip.contentmask = contentmask; -/* -Ghoul2 Insert Start -*/ - VectorCopy( start, clip.start ); + /* + Ghoul2 Insert Start + */ + VectorCopy(start, clip.start); clip.eG2TraceType = eG2TraceType; clip.useLod = useLod; -/* -Ghoul2 Insert End -*/ - //Shorten the trace to the size of the trace until it hit the world - VectorCopy( clip.trace.endpos, clip.end ); - //remember the current completion fraction + /* + Ghoul2 Insert End + */ + // Shorten the trace to the size of the trace until it hit the world + VectorCopy(clip.trace.endpos, clip.end); + // remember the current completion fraction world_frac = clip.trace.fraction; - //set the fraction back to 1.0 for the trace vs. entities + // set the fraction back to 1.0 for the trace vs. entities clip.trace.fraction = 1.0f; - //VectorCopy( end, clip.end ); - // create the bounding box of the entire move - // we can limit it to the part of the move not - // already clipped off by the world, which can be - // a significant savings for line of sight and shot traces + // VectorCopy( end, clip.end ); + // create the bounding box of the entire move + // we can limit it to the part of the move not + // already clipped off by the world, which can be + // a significant savings for line of sight and shot traces clip.passEntityNum = passEntityNum; -#if 0 //G2_SUPERSIZEDBBOX is not being used +#if 0 // G2_SUPERSIZEDBBOX is not being used vec3_t superMin; vec3_t superMax; // prison, in boscobel @@ -920,8 +866,8 @@ Ghoul2 Insert End clip.maxs = maxs; } - for ( i=0 ; i<3 ; i++ ) { - if ( end[i] > start[i] ) { + for (i = 0; i < 3; i++) { + if (end[i] > start[i]) { clip.boxmins[i] = clip.start[i] + clip.mins[i] - 1; clip.boxmaxs[i] = clip.end[i] + clip.maxs[i] + 1; } else { @@ -931,53 +877,49 @@ Ghoul2 Insert End } // clip to other solid entities - SV_ClipMoveToEntities ( &clip ); + SV_ClipMoveToEntities(&clip); - //scale the trace back down by the previous fraction + // scale the trace back down by the previous fraction clip.trace.fraction *= world_frac; *results = clip.trace; -/* -addtime: - endMS = Sys_Milliseconds (); + /* + addtime: + endMS = Sys_Milliseconds (); - timeInTrace += endMS - startMS; -*/ + timeInTrace += endMS - startMS; + */ } - - /* ============= SV_PointContents ============= */ -int SV_PointContents( const vec3_t p, int passEntityNum ) { - gentity_t *touch[MAX_GENTITIES], *hit; - int i, num; - int contents, c2; - clipHandle_t clipHandle; +int SV_PointContents(const vec3_t p, int passEntityNum) { + gentity_t *touch[MAX_GENTITIES], *hit; + int i, num; + int contents, c2; + clipHandle_t clipHandle; // get base contents from world - contents = CM_PointContents( p, 0 ); + contents = CM_PointContents(p, 0); // or in contents from all the other entities - num = SV_AreaEntities( p, p, touch, MAX_GENTITIES ); + num = SV_AreaEntities(p, p, touch, MAX_GENTITIES); - for ( i=0 ; is.number == passEntityNum ) { + if (hit->s.number == passEntityNum) { continue; } // might intersect, so do an exact clip - clipHandle = SV_ClipHandleForEntity( hit ); + clipHandle = SV_ClipHandleForEntity(hit); - c2 = CM_TransformedPointContents (p, clipHandle, hit->s.origin, hit->s.angles); + c2 = CM_TransformedPointContents(p, clipHandle, hit->s.origin, hit->s.angles); contents |= c2; } return contents; } - - diff --git a/code/ui/gameinfo.cpp b/code/ui/gameinfo.cpp index e7d59b1f73..970bff8066 100644 --- a/code/ui/gameinfo.cpp +++ b/code/ui/gameinfo.cpp @@ -32,7 +32,7 @@ along with this program; if not, see . weaponData_t weaponData[WP_NUM_WEAPONS]; ammoData_t ammoData[AMMO_MAX]; -extern void WP_LoadWeaponParms (void); +extern void WP_LoadWeaponParms(void); // // Initialization - Read in files and parse into infos @@ -43,7 +43,4 @@ extern void WP_LoadWeaponParms (void); GI_Init =============== */ -void GI_Init( gameinfo_import_t *import ) { - - WP_LoadWeaponParms (); -} +void GI_Init(gameinfo_import_t *import) { WP_LoadWeaponParms(); } diff --git a/code/ui/ui_atoms.cpp b/code/ui/ui_atoms.cpp index 69ccfb6e3b..8b987a4346 100644 --- a/code/ui/ui_atoms.cpp +++ b/code/ui/ui_atoms.cpp @@ -33,29 +33,26 @@ along with this program; if not, see . #include "gameinfo.h" #include "../qcommon/stv_version.h" -uiimport_t ui; -uiStatic_t uis; +uiimport_t ui; +uiStatic_t uis; -//externs -static void UI_LoadMenu_f( void ); -static void UI_SaveMenu_f( void ); - -//locals +// externs +static void UI_LoadMenu_f(void); +static void UI_SaveMenu_f(void); +// locals /* ================= UI_ForceMenuOff ================= */ -void UI_ForceMenuOff (void) -{ - ui.Key_SetCatcher( ui.Key_GetCatcher() & ~KEYCATCH_UI ); +void UI_ForceMenuOff(void) { + ui.Key_SetCatcher(ui.Key_GetCatcher() & ~KEYCATCH_UI); ui.Key_ClearStates(); - ui.Cvar_Set( "cl_paused", "0" ); + ui.Cvar_Set("cl_paused", "0"); } - /* ================= UI_SetActiveMenu - @@ -63,84 +60,75 @@ UI_SetActiveMenu - ================= */ -void UI_SetActiveMenu( const char* menuname,const char *menuID ) -{ +void UI_SetActiveMenu(const char *menuname, const char *menuID) { // this should be the ONLY way the menu system is brought up (besides the UI_ConsoleCommand below) - if (cls.state != CA_DISCONNECTED && !ui.SG_GameAllowedToSaveHere(qtrue)) //don't check full sytem, only if incamera + if (cls.state != CA_DISCONNECTED && !ui.SG_GameAllowedToSaveHere(qtrue)) // don't check full sytem, only if incamera { return; } - if ( !menuname ) { + if (!menuname) { UI_ForceMenuOff(); return; } - //make sure force-speed and slowmodeath doesn't slow down menus - NOTE: they should reset the timescale when the game un-pauses - Cvar_SetValue( "timescale", 1.0f ); + // make sure force-speed and slowmodeath doesn't slow down menus - NOTE: they should reset the timescale when the game un-pauses + Cvar_SetValue("timescale", 1.0f); UI_Cursor_Show(qtrue); // enusure minumum menu data is cached Menu_Cache(); - if ( Q_stricmp (menuname, "mainMenu") == 0 ) - { + if (Q_stricmp(menuname, "mainMenu") == 0) { UI_MainMenu(); return; } - if ( Q_stricmp (menuname, "ingame") == 0 ) - { - ui.Cvar_Set( "cl_paused", "1" ); + if (Q_stricmp(menuname, "ingame") == 0) { + ui.Cvar_Set("cl_paused", "1"); UI_InGameMenu(menuID); return; } - if ( Q_stricmp (menuname, "datapad") == 0 ) - { - ui.Cvar_Set( "cl_paused", "1" ); + if (Q_stricmp(menuname, "datapad") == 0) { + ui.Cvar_Set("cl_paused", "1"); UI_DataPadMenu(); return; } #ifndef JK2_MODE - if ( Q_stricmp (menuname, "missionfailed_menu") == 0 ) - { + if (Q_stricmp(menuname, "missionfailed_menu") == 0) { Menus_CloseAll(); Menus_ActivateByName("missionfailed_menu"); - ui.Key_SetCatcher( KEYCATCH_UI ); + ui.Key_SetCatcher(KEYCATCH_UI); return; } #endif } - /* ================= UI_Argv ================= */ -static char *UI_Argv( int arg ) -{ - static char buffer[MAX_STRING_CHARS]; +static char *UI_Argv(int arg) { + static char buffer[MAX_STRING_CHARS]; - ui.Argv( arg, buffer, sizeof( buffer ) ); + ui.Argv(arg, buffer, sizeof(buffer)); return buffer; } - /* ================= UI_Cvar_VariableString ================= */ -char *UI_Cvar_VariableString( const char *var_name ) -{ - static char buffer[MAX_STRING_CHARS]; +char *UI_Cvar_VariableString(const char *var_name) { + static char buffer[MAX_STRING_CHARS]; - ui.Cvar_VariableStringBuffer( var_name, buffer, sizeof( buffer ) ); + ui.Cvar_VariableStringBuffer(var_name, buffer, sizeof(buffer)); return buffer; } @@ -150,20 +138,17 @@ char *UI_Cvar_VariableString( const char *var_name ) UI_Cache ================= */ -static void UI_Cache_f( void ) -{ +static void UI_Cache_f(void) { Menu_Cache(); #ifndef JK2_MODE -extern const char *lukeForceStatusSounds[]; -extern const char *kyleForceStatusSounds[]; - for (int index = 0; index < 5; index++) - { + extern const char *lukeForceStatusSounds[]; + extern const char *kyleForceStatusSounds[]; + for (int index = 0; index < 5; index++) { DC->registerSound(lukeForceStatusSounds[index], qfalse); DC->registerSound(kyleForceStatusSounds[index], qfalse); } - for (int index = 1; index <= 18; index++) - { - DC->registerSound(va("sound/chars/storyinfo/%d",index), qfalse); + for (int index = 1; index <= 18; index++) { + DC->registerSound(va("sound/chars/storyinfo/%d", index), qfalse); } trap_S_RegisterSound("sound/chars/kyle/04kyk001.mp3", qfalse); trap_S_RegisterSound("sound/chars/kyle/05kyk001.mp3", qfalse); @@ -182,64 +167,56 @@ extern const char *kyleForceStatusSounds[]; trap_S_RegisterSound("sound/chars/protocol/16pro001.mp3", qfalse); trap_S_RegisterSound("sound/chars/wedge/13wea001.mp3", qfalse); - Menus_ActivateByName("ingameMissionSelect1"); Menus_ActivateByName("ingameMissionSelect2"); Menus_ActivateByName("ingameMissionSelect3"); #endif } - /* ================= UI_ConsoleCommand ================= */ #ifndef JK2_MODE -void UI_Load(void); //in UI_main.cpp +void UI_Load(void); // in UI_main.cpp #endif -qboolean UI_ConsoleCommand( void ) -{ - char *cmd; +qboolean UI_ConsoleCommand(void) { + char *cmd; - if (!ui.SG_GameAllowedToSaveHere(qtrue)) //only check if incamera + if (!ui.SG_GameAllowedToSaveHere(qtrue)) // only check if incamera { return qfalse; } - cmd = UI_Argv( 0 ); + cmd = UI_Argv(0); // ensure minimum menu data is available Menu_Cache(); - if ( Q_stricmp (cmd, "ui_cache") == 0 ) - { + if (Q_stricmp(cmd, "ui_cache") == 0) { UI_Cache_f(); return qtrue; } - if ( Q_stricmp (cmd, "levelselect") == 0 ) - { + if (Q_stricmp(cmd, "levelselect") == 0) { UI_LoadMenu_f(); return qtrue; } - if ( Q_stricmp (cmd, "ui_teamOrders") == 0 ) - { + if (Q_stricmp(cmd, "ui_teamOrders") == 0) { UI_SaveMenu_f(); return qtrue; } - if ( Q_stricmp (cmd, "ui_report") == 0 ) - { + if (Q_stricmp(cmd, "ui_report") == 0) { UI_Report(); return qtrue; } #ifndef JK2_MODE - if ( Q_stricmp (cmd, "ui_load") == 0 ) - { + if (Q_stricmp(cmd, "ui_load") == 0) { UI_Load(); return qtrue; } @@ -248,70 +225,66 @@ qboolean UI_ConsoleCommand( void ) return qfalse; } - /* ================= UI_Init ================= */ -void UI_Init( int apiVersion, uiimport_t *uiimport, qboolean inGameLoad ) -{ +void UI_Init(int apiVersion, uiimport_t *uiimport, qboolean inGameLoad) { ui = *uiimport; - if ( apiVersion != UI_API_VERSION ) { - ui.Error( ERR_FATAL, "Bad UI_API_VERSION: expected %i, got %i\n", UI_API_VERSION, apiVersion ); + if (apiVersion != UI_API_VERSION) { + ui.Error(ERR_FATAL, "Bad UI_API_VERSION: expected %i, got %i\n", UI_API_VERSION, apiVersion); } // get static data (glconfig, media) - ui.GetGlconfig( &uis.glconfig ); + ui.GetGlconfig(&uis.glconfig); - uis.scaley = uis.glconfig.vidHeight * (1.0/480.0); - uis.scalex = uis.glconfig.vidWidth * (1.0/640.0); + uis.scaley = uis.glconfig.vidHeight * (1.0 / 480.0); + uis.scalex = uis.glconfig.vidWidth * (1.0 / 640.0); - Menu_Cache( ); + Menu_Cache(); - ui.Cvar_Create( "cg_drawCrosshair", "1", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_marks", "1", CVAR_ARCHIVE ); - ui.Cvar_Create ("s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); + ui.Cvar_Create("cg_drawCrosshair", "1", CVAR_ARCHIVE); + ui.Cvar_Create("cg_marks", "1", CVAR_ARCHIVE); + ui.Cvar_Create("s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); #ifndef JK2_MODE - ui.Cvar_Create( "g_char_model", "jedi_tf", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_skin_head", "head_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_skin_torso", "torso_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_skin_legs", "lower_a1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_color_red", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_color_green", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_char_color_blue", "255", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_saber_type", "single", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_saber", "single_1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_saber2", "", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_saber_color", "yellow", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - ui.Cvar_Create( "g_saber2_color", "yellow", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - - ui.Cvar_Create( "ui_forcepower_inc", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - ui.Cvar_Create( "tier_storyinfo", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - ui.Cvar_Create( "tiers_complete", "", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - ui.Cvar_Create( "ui_prisonerobj_currtotal", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - ui.Cvar_Create( "ui_prisonerobj_mintotal", "0", CVAR_ROM|CVAR_SAVEGAME|CVAR_NORESTART); - - ui.Cvar_Create( "g_dismemberment", "3", CVAR_ARCHIVE );//0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head - ui.Cvar_Create( "cg_gunAutoFirst", "1", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE ); - ui.Cvar_Create( "g_subtitles", "0", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_marks", "1", CVAR_ARCHIVE ); - ui.Cvar_Create( "d_slowmodeath", "3", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_shadows", "1", CVAR_ARCHIVE ); - - ui.Cvar_Create( "cg_runpitch", "0.002", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_runroll", "0.005", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_bobup", "0.005", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_bobpitch", "0.002", CVAR_ARCHIVE ); - ui.Cvar_Create( "cg_bobroll", "0.002", CVAR_ARCHIVE ); - - ui.Cvar_Create( "ui_disableWeaponSway", "0", CVAR_ARCHIVE ); + ui.Cvar_Create("g_char_model", "jedi_tf", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_skin_head", "head_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_skin_torso", "torso_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_skin_legs", "lower_a1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_color_red", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_color_green", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_char_color_blue", "255", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_saber_type", "single", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_saber", "single_1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_saber2", "", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_saber_color", "yellow", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("g_saber2_color", "yellow", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + + ui.Cvar_Create("ui_forcepower_inc", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("tier_storyinfo", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("tiers_complete", "", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("ui_prisonerobj_currtotal", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + ui.Cvar_Create("ui_prisonerobj_mintotal", "0", CVAR_ROM | CVAR_SAVEGAME | CVAR_NORESTART); + + ui.Cvar_Create("g_dismemberment", "3", CVAR_ARCHIVE); // 0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head + ui.Cvar_Create("cg_gunAutoFirst", "1", CVAR_ARCHIVE); + ui.Cvar_Create("cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE); + ui.Cvar_Create("g_subtitles", "0", CVAR_ARCHIVE); + ui.Cvar_Create("cg_marks", "1", CVAR_ARCHIVE); + ui.Cvar_Create("d_slowmodeath", "3", CVAR_ARCHIVE); + ui.Cvar_Create("cg_shadows", "1", CVAR_ARCHIVE); + + ui.Cvar_Create("cg_runpitch", "0.002", CVAR_ARCHIVE); + ui.Cvar_Create("cg_runroll", "0.005", CVAR_ARCHIVE); + ui.Cvar_Create("cg_bobup", "0.005", CVAR_ARCHIVE); + ui.Cvar_Create("cg_bobpitch", "0.002", CVAR_ARCHIVE); + ui.Cvar_Create("cg_bobroll", "0.002", CVAR_ARCHIVE); + + ui.Cvar_Create("ui_disableWeaponSway", "0", CVAR_ARCHIVE); #endif - - _UI_Init(inGameLoad); } @@ -320,48 +293,43 @@ void UI_Init( int apiVersion, uiimport_t *uiimport, qboolean inGameLoad ) UI_DrawNamedPic ================= */ -void UI_DrawNamedPic( float x, float y, float width, float height, const char *picname ) -{ - qhandle_t hShader; +void UI_DrawNamedPic(float x, float y, float width, float height, const char *picname) { + qhandle_t hShader; - hShader = ui.R_RegisterShaderNoMip( picname ); - ui.R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); + hShader = ui.R_RegisterShaderNoMip(picname); + ui.R_DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } - /* ================ UI_DrawHandlePic ================= */ -void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader ) -{ - float s0; - float s1; - float t0; - float t1; - - if( w < 0 ) { // flip about horizontal - w = -w; +void UI_DrawHandlePic(float x, float y, float w, float h, qhandle_t hShader) { + float s0; + float s1; + float t0; + float t1; + + if (w < 0) { // flip about horizontal + w = -w; s0 = 1; s1 = 0; - } - else { + } else { s0 = 0; s1 = 1; } - if( h < 0 ) { // flip about vertical - h = -h; + if (h < 0) { // flip about vertical + h = -h; t0 = 1; t1 = 0; - } - else { + } else { t0 = 0; t1 = 1; } - ui.R_DrawStretchPic( x, y, w, h, s0, t0, s1, t1, hShader ); + ui.R_DrawStretchPic(x, y, w, h, s0, t0, s1, t1, hShader); } /* @@ -371,13 +339,12 @@ UI_FillRect Coordinates are 640*480 virtual values ================= */ -void UI_FillRect( float x, float y, float width, float height, const float *color ) -{ - ui.R_SetColor( color ); +void UI_FillRect(float x, float y, float width, float height, const float *color) { + ui.R_SetColor(color); - ui.R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, uis.whiteShader ); + ui.R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, uis.whiteShader); - ui.R_SetColor( NULL ); + ui.R_SetColor(NULL); } /* @@ -385,20 +352,15 @@ void UI_FillRect( float x, float y, float width, float height, const float *colo UI_UpdateScreen ================= */ -void UI_UpdateScreen( void ) -{ - ui.UpdateScreen(); -} - +void UI_UpdateScreen(void) { ui.UpdateScreen(); } /* =============== UI_LoadMenu_f =============== */ -static void UI_LoadMenu_f( void ) -{ - trap_Key_SetCatcher( KEYCATCH_UI ); +static void UI_LoadMenu_f(void) { + trap_Key_SetCatcher(KEYCATCH_UI); Menus_ActivateByName("ingameloadMenu"); } @@ -407,17 +369,15 @@ static void UI_LoadMenu_f( void ) UI_SaveMenu_f =============== */ -static void UI_SaveMenu_f( void ) -{ +static void UI_SaveMenu_f(void) { #ifdef JK2_MODE ui.PrecacheScreenshot(); #endif - trap_Key_SetCatcher( KEYCATCH_UI ); + trap_Key_SetCatcher(KEYCATCH_UI); Menus_ActivateByName("ingamesaveMenu"); } - //-------------------------------------------- /* @@ -425,10 +385,7 @@ static void UI_SaveMenu_f( void ) UI_SetColor ================= */ -void UI_SetColor( const float *rgba ) -{ - trap_R_SetColor( rgba ); -} +void UI_SetColor(const float *rgba) { trap_R_SetColor(rgba); } /*int registeredFontCount = 0; #define MAX_FONTS 6 @@ -441,14 +398,11 @@ UI_RegisterFont ================= */ -int UI_RegisterFont(const char *fontName) -{ +int UI_RegisterFont(const char *fontName) { int iFontIndex = ui.R_RegisterFont(fontName); - if (iFontIndex == 0) - { - iFontIndex = ui.R_RegisterFont("ergoec"); // fall back + if (iFontIndex == 0) { + iFontIndex = ui.R_RegisterFont("ergoec"); // fall back } return iFontIndex; } - diff --git a/code/ui/ui_connect.cpp b/code/ui/ui_connect.cpp index 1aa6ea2c7b..9f60a75245 100644 --- a/code/ui/ui_connect.cpp +++ b/code/ui/ui_connect.cpp @@ -33,8 +33,8 @@ CONNECTION SCREEN =============================================================================== */ -char connectionDialogString[1024]; -char connectionMessageString[1024]; +char connectionDialogString[1024]; +char connectionMessageString[1024]; #ifdef JK2_MODE /* @@ -42,10 +42,7 @@ char connectionMessageString[1024]; UI_DrawThumbNail ================= */ -void UI_DrawThumbNail( float x, float y, float w, float h, byte *pic ) -{ - ui.DrawStretchRaw( x, y, w, h, SG_SCR_WIDTH, SG_SCR_HEIGHT, pic, 0, qtrue ); -} +void UI_DrawThumbNail(float x, float y, float w, float h, byte *pic) { ui.DrawStretchRaw(x, y, w, h, SG_SCR_WIDTH, SG_SCR_HEIGHT, pic, 0, qtrue); } #endif /* @@ -55,7 +52,7 @@ UI_DrawConnect ======================== */ -void UI_DrawConnect( const char *servername, const char *updateInfoString ) { +void UI_DrawConnect(const char *servername, const char *updateInfoString) { #if 0 // if connecting to a local host, don't draw anything before the // gamestate message. This allows cinematics to start seamlessly @@ -70,27 +67,24 @@ void UI_DrawConnect( const char *servername, const char *updateInfoString ) { qboolean qValid; byte *levelPic = SCR_GetScreenshot(&qValid); // draw the dialog background - if (!qValid) - { - UI_DrawHandlePic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader ); - } - else { - UI_DrawThumbNail(0,0, SCREEN_WIDTH, SCREEN_HEIGHT, levelPic ); + if (!qValid) { + UI_DrawHandlePic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader); + } else { + UI_DrawThumbNail(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelPic); } #else - UI_DrawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader ); + UI_DrawHandlePic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, uis.menuBackShader); #endif } - /* ======================== UI_UpdateConnectionString ======================== */ -void UI_UpdateConnectionString( const char *string ) { - Q_strncpyz( connectionDialogString, string, sizeof( connectionDialogString ) ); +void UI_UpdateConnectionString(const char *string) { + Q_strncpyz(connectionDialogString, string, sizeof(connectionDialogString)); UI_UpdateScreen(); } @@ -100,14 +94,14 @@ UI_UpdateConnectionMessageString ======================== */ -void UI_UpdateConnectionMessageString( char *string ) { - char *s; +void UI_UpdateConnectionMessageString(char *string) { + char *s; - Q_strncpyz( connectionMessageString, string, sizeof( connectionMessageString ) ); + Q_strncpyz(connectionMessageString, string, sizeof(connectionMessageString)); // strip \n - s = strstr( connectionMessageString, "\n" ); - if ( s ) { + s = strstr(connectionMessageString, "\n"); + if (s) { *s = 0; } UI_UpdateScreen(); @@ -118,13 +112,9 @@ void UI_UpdateConnectionMessageString( char *string ) { UI_KeyConnect =================== */ -void UI_KeyConnect( int key ) -{ - if ( key == A_ESCAPE ) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" ); +void UI_KeyConnect(int key) { + if (key == A_ESCAPE) { + ui.Cmd_ExecuteText(EXEC_APPEND, "disconnect\n"); return; } } - - diff --git a/code/ui/ui_main.cpp b/code/ui/ui_main.cpp index b6d4fed156..83947e2bf3 100644 --- a/code/ui/ui_main.cpp +++ b/code/ui/ui_main.cpp @@ -44,331 +44,297 @@ USER INTERFACE MAIN #include "../game/bg_public.h" #include "../game/anims.h" -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; #include "../qcommon/stringed_ingame.h" #include "../qcommon/stv_version.h" #include "../qcommon/q_shared.h" -extern qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ); -extern qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name ); -extern qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ); -extern qboolean UI_SaberModelForSaber( const char *saberName, char *saberModel ); -extern qboolean UI_SaberSkinForSaber( const char *saberName, char *saberSkin ); -extern void UI_SaberAttachToChar( itemDef_t *item ); +extern qboolean ItemParse_model_g2anim_go(itemDef_t *item, const char *animName); +extern qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name); +extern qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName); +extern qboolean UI_SaberModelForSaber(const char *saberName, char *saberModel); +extern qboolean UI_SaberSkinForSaber(const char *saberName, char *saberSkin); +extern void UI_SaberAttachToChar(itemDef_t *item); extern qboolean PC_Script_Parse(const char **out); #define LISTBUFSIZE 10240 -static struct -{ - char listBuf[LISTBUFSIZE]; // The list of file names read in +static struct { + char listBuf[LISTBUFSIZE]; // The list of file names read in // For scrolling through file names - int currentLine; // Index to currentSaveFileComments[] currently highlighted - int saveFileCnt; // Number of save files read in + int currentLine; // Index to currentSaveFileComments[] currently highlighted + int saveFileCnt; // Number of save files read in - int awaitingSave; // Flag to see if user wants to overwrite a game. + int awaitingSave; // Flag to see if user wants to overwrite a game. - char *savegameMap; - int savegameFromFlag; + char *savegameMap; + int savegameFromFlag; } s_savegame; -#define MAX_SAVELOADFILES 100 -#define MAX_SAVELOADNAME 32 +#define MAX_SAVELOADFILES 100 +#define MAX_SAVELOADNAME 32 #ifdef JK2_MODE byte screenShotBuf[SG_SCR_WIDTH * SG_SCR_HEIGHT * 4]; #endif -typedef struct -{ - char *currentSaveFileName; // file name of savegame - char currentSaveFileComments[iSG_COMMENT_SIZE]; // file comment - char currentSaveFileDateTimeString[iSG_COMMENT_SIZE]; // file time and date +typedef struct { + char *currentSaveFileName; // file name of savegame + char currentSaveFileComments[iSG_COMMENT_SIZE]; // file comment + char currentSaveFileDateTimeString[iSG_COMMENT_SIZE]; // file time and date time_t currentSaveFileDateTime; - char currentSaveFileMap[MAX_TOKEN_CHARS]; // map save game is from + char currentSaveFileMap[MAX_TOKEN_CHARS]; // map save game is from } savedata_t; static savedata_t s_savedata[MAX_SAVELOADFILES]; -void UI_SetActiveMenu( const char* menuname,const char *menuID ); -void ReadSaveDirectory (void); +void UI_SetActiveMenu(const char *menuname, const char *menuID); +void ReadSaveDirectory(void); void Item_RunScript(itemDef_t *item, const char *s); qboolean Item_SetFocus(itemDef_t *item, float x, float y); -qboolean Asset_Parse(char **buffer); -menuDef_t *Menus_FindByName(const char *p); -void Menus_HideItems(const char *menuName); -int Text_Height(const char *text, float scale, int iFontIndex ); -int Text_Width(const char *text, float scale, int iFontIndex ); -void _UI_DrawTopBottom(float x, float y, float w, float h, float size); -void _UI_DrawSides(float x, float y, float w, float h, float size); -void UI_CheckVid1Data(const char *menuTo,const char *warningMenuName); -void UI_GetVideoSetup ( void ); -void UI_UpdateVideoSetup ( void ); -static void UI_UpdateCharacterCvars ( void ); -static void UI_GetCharacterCvars ( void ); -static void UI_UpdateSaberCvars ( void ); -static void UI_GetSaberCvars ( void ); -static void UI_ResetSaberCvars ( void ); -static void UI_InitAllocForcePowers ( const char *forceName ); -static void UI_AffectForcePowerLevel ( const char *forceName ); -static void UI_ShowForceLevelDesc ( const char *forceName ); -static void UI_ResetForceLevels ( void ); -static void UI_ClearWeapons ( void ); -static void UI_GiveWeapon ( const int weaponIndex ); -static void UI_EquipWeapon ( const int weaponIndex ); -static void UI_LoadMissionSelectMenu( const char *cvarName ); -static void UI_AddWeaponSelection ( const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName,const char *litIconItemName, const char *hexBackground, const char *soundfile ); -static void UI_AddThrowWeaponSelection ( const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName,const char *litIconItemName, const char *hexBackground, const char *soundfile ); -static void UI_RemoveWeaponSelection ( const int weaponIndex ); -static void UI_RemoveThrowWeaponSelection ( void ); -static void UI_HighLightWeaponSelection ( const int selectionslot ); -static void UI_NormalWeaponSelection ( const int selectionslot ); -static void UI_NormalThrowSelection ( void ); -static void UI_HighLightThrowSelection( void ); -static void UI_ClearInventory ( void ); -static void UI_GiveInventory ( const int itemIndex, const int amount ); -static void UI_ForcePowerWeaponsButton(qboolean activeFlag); -static void UI_UpdateCharacterSkin( void ); -static void UI_UpdateCharacter( qboolean changedModel ); -static void UI_UpdateSaberType( void ); -static void UI_UpdateSaberHilt( qboolean secondSaber ); -//static void UI_UpdateSaberColor( qboolean secondSaber ); -static void UI_InitWeaponSelect( void ); -static void UI_WeaponHelpActive( void ); +qboolean Asset_Parse(char **buffer); +menuDef_t *Menus_FindByName(const char *p); +void Menus_HideItems(const char *menuName); +int Text_Height(const char *text, float scale, int iFontIndex); +int Text_Width(const char *text, float scale, int iFontIndex); +void _UI_DrawTopBottom(float x, float y, float w, float h, float size); +void _UI_DrawSides(float x, float y, float w, float h, float size); +void UI_CheckVid1Data(const char *menuTo, const char *warningMenuName); +void UI_GetVideoSetup(void); +void UI_UpdateVideoSetup(void); +static void UI_UpdateCharacterCvars(void); +static void UI_GetCharacterCvars(void); +static void UI_UpdateSaberCvars(void); +static void UI_GetSaberCvars(void); +static void UI_ResetSaberCvars(void); +static void UI_InitAllocForcePowers(const char *forceName); +static void UI_AffectForcePowerLevel(const char *forceName); +static void UI_ShowForceLevelDesc(const char *forceName); +static void UI_ResetForceLevels(void); +static void UI_ClearWeapons(void); +static void UI_GiveWeapon(const int weaponIndex); +static void UI_EquipWeapon(const int weaponIndex); +static void UI_LoadMissionSelectMenu(const char *cvarName); +static void UI_AddWeaponSelection(const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName, const char *litIconItemName, + const char *hexBackground, const char *soundfile); +static void UI_AddThrowWeaponSelection(const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName, const char *litIconItemName, + const char *hexBackground, const char *soundfile); +static void UI_RemoveWeaponSelection(const int weaponIndex); +static void UI_RemoveThrowWeaponSelection(void); +static void UI_HighLightWeaponSelection(const int selectionslot); +static void UI_NormalWeaponSelection(const int selectionslot); +static void UI_NormalThrowSelection(void); +static void UI_HighLightThrowSelection(void); +static void UI_ClearInventory(void); +static void UI_GiveInventory(const int itemIndex, const int amount); +static void UI_ForcePowerWeaponsButton(qboolean activeFlag); +static void UI_UpdateCharacterSkin(void); +static void UI_UpdateCharacter(qboolean changedModel); +static void UI_UpdateSaberType(void); +static void UI_UpdateSaberHilt(qboolean secondSaber); +// static void UI_UpdateSaberColor( qboolean secondSaber ); +static void UI_InitWeaponSelect(void); +static void UI_WeaponHelpActive(void); #ifndef JK2_MODE -static void UI_UpdateFightingStyle ( void ); -static void UI_UpdateFightingStyleChoices ( void ); -static void UI_CalcForceStatus(void); +static void UI_UpdateFightingStyle(void); +static void UI_UpdateFightingStyleChoices(void); +static void UI_CalcForceStatus(void); #endif // !JK2_MODE -static void UI_DecrementForcePowerLevel( void ); -static void UI_DecrementCurrentForcePower ( void ); -static void UI_ShutdownForceHelp( void ); -static void UI_ForceHelpActive( void ); +static void UI_DecrementForcePowerLevel(void); +static void UI_DecrementCurrentForcePower(void); +static void UI_ShutdownForceHelp(void); +static void UI_ForceHelpActive(void); #ifndef JK2_MODE -static void UI_DemoSetForceLevels( void ); +static void UI_DemoSetForceLevels(void); #endif // !JK2_MODE -static void UI_RecordForceLevels( void ); -static void UI_RecordWeapons( void ); -static void UI_ResetCharacterListBoxes( void ); - +static void UI_RecordForceLevels(void); +static void UI_RecordWeapons(void); +static void UI_ResetCharacterListBoxes(void); -void UI_LoadMenus(const char *menuFile, qboolean reset); -static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle, int iFontIndex); +void UI_LoadMenus(const char *menuFile, qboolean reset); +static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, + float scale, vec4_t color, qhandle_t shader, int textStyle, int iFontIndex); static qboolean UI_OwnerDrawVisible(int flags); -int UI_OwnerDrawWidth(int ownerDraw, float scale); -static void UI_Update(const char *name); -void UI_UpdateCvars( void ); -void UI_ResetDefaults( void ); -void UI_AdjustSaveGameListBox( int currentLine ); +int UI_OwnerDrawWidth(int ownerDraw, float scale); +static void UI_Update(const char *name); +void UI_UpdateCvars(void); +void UI_ResetDefaults(void); +void UI_AdjustSaveGameListBox(int currentLine); -void Menus_CloseByName(const char *p); +void Menus_CloseByName(const char *p); // Movedata Sounds -enum -{ - MDS_NONE = 0, - MDS_FORCE_JUMP, - MDS_ROLL, - MDS_SABER, - MDS_MOVE_SOUNDS_MAX -}; +enum { MDS_NONE = 0, MDS_FORCE_JUMP, MDS_ROLL, MDS_SABER, MDS_MOVE_SOUNDS_MAX }; -enum -{ - MD_ACROBATICS = 0, - MD_SINGLE_FAST, - MD_SINGLE_MEDIUM, - MD_SINGLE_STRONG, - MD_DUAL_SABERS, - MD_SABER_STAFF, - MD_MOVE_TITLE_MAX -}; +enum { MD_ACROBATICS = 0, MD_SINGLE_FAST, MD_SINGLE_MEDIUM, MD_SINGLE_STRONG, MD_DUAL_SABERS, MD_SABER_STAFF, MD_MOVE_TITLE_MAX }; // Some hard coded badness // At some point maybe this should be externalized to a .dat file -const char *datapadMoveTitleData[MD_MOVE_TITLE_MAX] = -{ -"@MENUS_ACROBATICS", -"@MENUS_SINGLE_FAST", -"@MENUS_SINGLE_MEDIUM", -"@MENUS_SINGLE_STRONG", -"@MENUS_DUAL_SABERS", -"@MENUS_SABER_STAFF", +const char *datapadMoveTitleData[MD_MOVE_TITLE_MAX] = { + "@MENUS_ACROBATICS", "@MENUS_SINGLE_FAST", "@MENUS_SINGLE_MEDIUM", "@MENUS_SINGLE_STRONG", "@MENUS_DUAL_SABERS", "@MENUS_SABER_STAFF", }; -const char *datapadMoveTitleBaseAnims[MD_MOVE_TITLE_MAX] = -{ -"BOTH_RUN1", -"BOTH_SABERFAST_STANCE", -"BOTH_STAND2", -"BOTH_SABERSLOW_STANCE", -"BOTH_SABERDUAL_STANCE", -"BOTH_SABERSTAFF_STANCE", +const char *datapadMoveTitleBaseAnims[MD_MOVE_TITLE_MAX] = { + "BOTH_RUN1", "BOTH_SABERFAST_STANCE", "BOTH_STAND2", "BOTH_SABERSLOW_STANCE", "BOTH_SABERDUAL_STANCE", "BOTH_SABERSTAFF_STANCE", }; #define MAX_MOVES 16 -typedef struct -{ - const char *title; - const char *desc; - const char *anim; - short sound; +typedef struct { + const char *title; + const char *desc; + const char *anim; + short sound; } datpadmovedata_t; -static datpadmovedata_t datapadMoveData[MD_MOVE_TITLE_MAX][MAX_MOVES] = -{ -{ -// Acrobatics -{ "@MENUS_FORCE_JUMP1", "@MENUS_FORCE_JUMP1_DESC", "BOTH_FORCEJUMP1", MDS_FORCE_JUMP }, -{ "@MENUS_FORCE_FLIP", "@MENUS_FORCE_FLIP_DESC", "BOTH_FLIP_F", MDS_FORCE_JUMP }, -{ "@MENUS_ROLL", "@MENUS_ROLL_DESC", "BOTH_ROLL_F", MDS_ROLL }, -{ "@MENUS_BACKFLIP_OFF_WALL", "@MENUS_BACKFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_BACK1", MDS_FORCE_JUMP }, -{ "@MENUS_SIDEFLIP_OFF_WALL", "@MENUS_SIDEFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_WALL_RUN", "@MENUS_WALL_RUN_DESC", "BOTH_WALL_RUN_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_LONG_JUMP", "@MENUS_LONG_JUMP_DESC", "BOTH_FORCELONGLEAP_START", MDS_FORCE_JUMP }, -{ "@MENUS_WALL_GRAB_JUMP", "@MENUS_WALL_GRAB_JUMP_DESC", "BOTH_FORCEWALLREBOUND_FORWARD",MDS_FORCE_JUMP }, -{ "@MENUS_RUN_UP_WALL_BACKFLIP", "@MENUS_RUN_UP_WALL_BACKFLIP_DESC", "BOTH_FORCEWALLRUNFLIP_START", MDS_FORCE_JUMP }, -{ "@MENUS_JUMPUP_FROM_KNOCKDOWN", "@MENUS_JUMPUP_FROM_KNOCKDOWN_DESC","BOTH_KNOCKDOWN3", MDS_NONE }, -{ "@MENUS_JUMPKICK_FROM_KNOCKDOWN", "@MENUS_JUMPKICK_FROM_KNOCKDOWN_DESC","BOTH_KNOCKDOWN2", MDS_NONE }, -{ "@MENUS_ROLL_FROM_KNOCKDOWN", "@MENUS_ROLL_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN1", MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -}, - -{ -//Single Saber, Fast Style -{ "@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER }, -{ "@MENUS_LUNGE_ATTACK", "@MENUS_LUNGE_ATTACK_DESC", "BOTH_LUNGE2_B__T_", MDS_SABER }, -{ "@MENUS_FORCE_PULL_IMPALE", "@MENUS_FORCE_PULL_IMPALE_DESC", "BOTH_PULL_IMPALE_STAB", MDS_SABER }, -{ "@MENUS_FAST_ATTACK_KATA", "@MENUS_FAST_ATTACK_KATA_DESC", "BOTH_A1_SPECIAL", MDS_SABER }, -{ "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, -{ "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -}, - -{ -//Single Saber, Medium Style -{ "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, -{ "@MENUS_FLIP_ATTACK", "@MENUS_FLIP_ATTACK_DESC", "BOTH_JUMPFLIPSLASHDOWN1", MDS_FORCE_JUMP }, -{ "@MENUS_FORCE_PULL_SLASH", "@MENUS_FORCE_PULL_SLASH_DESC", "BOTH_PULL_IMPALE_SWING", MDS_SABER }, -{ "@MENUS_MEDIUM_ATTACK_KATA", "@MENUS_MEDIUM_ATTACK_KATA_DESC", "BOTH_A2_SPECIAL", MDS_SABER }, -{ "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, -{ "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -}, - -{ -//Single Saber, Strong Style -{ "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, -{ "@MENUS_JUMP_ATTACK", "@MENUS_JUMP_ATTACK_DESC", "BOTH_FORCELEAP2_T__B_", MDS_FORCE_JUMP }, -{ "@MENUS_FORCE_PULL_SLASH", "@MENUS_FORCE_PULL_SLASH_DESC", "BOTH_PULL_IMPALE_SWING", MDS_SABER }, -{ "@MENUS_STRONG_ATTACK_KATA", "@MENUS_STRONG_ATTACK_KATA_DESC", "BOTH_A3_SPECIAL", MDS_SABER }, -{ "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, -{ "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -}, - -{ -//Dual Sabers -{ "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, -{ "@MENUS_FLIP_FORWARD_ATTACK", "@MENUS_FLIP_FORWARD_ATTACK_DESC", "BOTH_JUMPATTACK6", MDS_FORCE_JUMP }, -{ "@MENUS_DUAL_SABERS_TWIRL", "@MENUS_DUAL_SABERS_TWIRL_DESC", "BOTH_SPINATTACK6", MDS_SABER }, -{ "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_DUAL", MDS_FORCE_JUMP }, -{ "@MENUS_DUAL_SABER_BARRIER", "@MENUS_DUAL_SABER_BARRIER_DESC", "BOTH_A6_SABERPROTECT", MDS_SABER }, -{ "@MENUS_DUAL_STAB_FRONT_BACK", "@MENUS_DUAL_STAB_FRONT_BACK_DESC", "BOTH_A6_FB", MDS_SABER }, -{ "@MENUS_DUAL_STAB_LEFT_RIGHT", "@MENUS_DUAL_STAB_LEFT_RIGHT_DESC", "BOTH_A6_LR", MDS_SABER }, -{ "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, -{ "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB_DESC", "BOTH_ROLL_STAB", MDS_SABER }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -}, - -{ -// Saber Staff -{ "@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER }, -{ "@MENUS_BACK_FLIP_ATTACK", "@MENUS_BACK_FLIP_ATTACK_DESC", "BOTH_JUMPATTACK7", MDS_FORCE_JUMP }, -{ "@MENUS_SABER_STAFF_TWIRL", "@MENUS_SABER_STAFF_TWIRL_DESC", "BOTH_SPINATTACK7", MDS_SABER }, -{ "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_STAFF", MDS_FORCE_JUMP }, -{ "@MENUS_SPINNING_KATA", "@MENUS_SPINNING_KATA_DESC", "BOTH_A7_SOULCAL", MDS_SABER }, -{ "@MENUS_KICK1", "@MENUS_KICK1_DESC", "BOTH_A7_KICK_F", MDS_FORCE_JUMP }, -{ "@MENUS_JUMP_KICK", "@MENUS_JUMP_KICK_DESC", "BOTH_A7_KICK_F_AIR", MDS_FORCE_JUMP }, -{ "@MENUS_SPLIT_KICK", "@MENUS_SPLIT_KICK_DESC", "BOTH_A7_KICK_RL", MDS_FORCE_JUMP }, -{ "@MENUS_SPIN_KICK", "@MENUS_SPIN_KICK_DESC", "BOTH_A7_KICK_S", MDS_FORCE_JUMP }, -{ "@MENUS_FLIP_KICK", "@MENUS_FLIP_KICK_DESC", "BOTH_A7_KICK_BF", MDS_FORCE_JUMP }, -{ "@MENUS_BUTTERFLY_ATTACK", "@MENUS_BUTTERFLY_ATTACK_DESC", "BOTH_BUTTERFLY_FR1", MDS_SABER }, -{ "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -{ NULL, NULL, 0, MDS_NONE }, -} -}; - - -static int gamecodetoui[] = {4,2,3,0,5,1,6}; +static datpadmovedata_t datapadMoveData[MD_MOVE_TITLE_MAX][MAX_MOVES] = { + { + // Acrobatics + {"@MENUS_FORCE_JUMP1", "@MENUS_FORCE_JUMP1_DESC", "BOTH_FORCEJUMP1", MDS_FORCE_JUMP}, + {"@MENUS_FORCE_FLIP", "@MENUS_FORCE_FLIP_DESC", "BOTH_FLIP_F", MDS_FORCE_JUMP}, + {"@MENUS_ROLL", "@MENUS_ROLL_DESC", "BOTH_ROLL_F", MDS_ROLL}, + {"@MENUS_BACKFLIP_OFF_WALL", "@MENUS_BACKFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_BACK1", MDS_FORCE_JUMP}, + {"@MENUS_SIDEFLIP_OFF_WALL", "@MENUS_SIDEFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_WALL_RUN", "@MENUS_WALL_RUN_DESC", "BOTH_WALL_RUN_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_LONG_JUMP", "@MENUS_LONG_JUMP_DESC", "BOTH_FORCELONGLEAP_START", MDS_FORCE_JUMP}, + {"@MENUS_WALL_GRAB_JUMP", "@MENUS_WALL_GRAB_JUMP_DESC", "BOTH_FORCEWALLREBOUND_FORWARD", MDS_FORCE_JUMP}, + {"@MENUS_RUN_UP_WALL_BACKFLIP", "@MENUS_RUN_UP_WALL_BACKFLIP_DESC", "BOTH_FORCEWALLRUNFLIP_START", MDS_FORCE_JUMP}, + {"@MENUS_JUMPUP_FROM_KNOCKDOWN", "@MENUS_JUMPUP_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN3", MDS_NONE}, + {"@MENUS_JUMPKICK_FROM_KNOCKDOWN", "@MENUS_JUMPKICK_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN2", MDS_NONE}, + {"@MENUS_ROLL_FROM_KNOCKDOWN", "@MENUS_ROLL_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN1", MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }, + + { + // Single Saber, Fast Style + {"@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER}, + {"@MENUS_LUNGE_ATTACK", "@MENUS_LUNGE_ATTACK_DESC", "BOTH_LUNGE2_B__T_", MDS_SABER}, + {"@MENUS_FORCE_PULL_IMPALE", "@MENUS_FORCE_PULL_IMPALE_DESC", "BOTH_PULL_IMPALE_STAB", MDS_SABER}, + {"@MENUS_FAST_ATTACK_KATA", "@MENUS_FAST_ATTACK_KATA_DESC", "BOTH_A1_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }, + + { + // Single Saber, Medium Style + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_FLIP_ATTACK", "@MENUS_FLIP_ATTACK_DESC", "BOTH_JUMPFLIPSLASHDOWN1", MDS_FORCE_JUMP}, + {"@MENUS_FORCE_PULL_SLASH", "@MENUS_FORCE_PULL_SLASH_DESC", "BOTH_PULL_IMPALE_SWING", MDS_SABER}, + {"@MENUS_MEDIUM_ATTACK_KATA", "@MENUS_MEDIUM_ATTACK_KATA_DESC", "BOTH_A2_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }, + + { + // Single Saber, Strong Style + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_JUMP_ATTACK", "@MENUS_JUMP_ATTACK_DESC", "BOTH_FORCELEAP2_T__B_", MDS_FORCE_JUMP}, + {"@MENUS_FORCE_PULL_SLASH", "@MENUS_FORCE_PULL_SLASH_DESC", "BOTH_PULL_IMPALE_SWING", MDS_SABER}, + {"@MENUS_STRONG_ATTACK_KATA", "@MENUS_STRONG_ATTACK_KATA_DESC", "BOTH_A3_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }, + + { + // Dual Sabers + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_FLIP_FORWARD_ATTACK", "@MENUS_FLIP_FORWARD_ATTACK_DESC", "BOTH_JUMPATTACK6", MDS_FORCE_JUMP}, + {"@MENUS_DUAL_SABERS_TWIRL", "@MENUS_DUAL_SABERS_TWIRL_DESC", "BOTH_SPINATTACK6", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_DUAL", MDS_FORCE_JUMP}, + {"@MENUS_DUAL_SABER_BARRIER", "@MENUS_DUAL_SABER_BARRIER_DESC", "BOTH_A6_SABERPROTECT", MDS_SABER}, + {"@MENUS_DUAL_STAB_FRONT_BACK", "@MENUS_DUAL_STAB_FRONT_BACK_DESC", "BOTH_A6_FB", MDS_SABER}, + {"@MENUS_DUAL_STAB_LEFT_RIGHT", "@MENUS_DUAL_STAB_LEFT_RIGHT_DESC", "BOTH_A6_LR", MDS_SABER}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }, + + { + // Saber Staff + {"@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER}, + {"@MENUS_BACK_FLIP_ATTACK", "@MENUS_BACK_FLIP_ATTACK_DESC", "BOTH_JUMPATTACK7", MDS_FORCE_JUMP}, + {"@MENUS_SABER_STAFF_TWIRL", "@MENUS_SABER_STAFF_TWIRL_DESC", "BOTH_SPINATTACK7", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_STAFF", MDS_FORCE_JUMP}, + {"@MENUS_SPINNING_KATA", "@MENUS_SPINNING_KATA_DESC", "BOTH_A7_SOULCAL", MDS_SABER}, + {"@MENUS_KICK1", "@MENUS_KICK1_DESC", "BOTH_A7_KICK_F", MDS_FORCE_JUMP}, + {"@MENUS_JUMP_KICK", "@MENUS_JUMP_KICK_DESC", "BOTH_A7_KICK_F_AIR", MDS_FORCE_JUMP}, + {"@MENUS_SPLIT_KICK", "@MENUS_SPLIT_KICK_DESC", "BOTH_A7_KICK_RL", MDS_FORCE_JUMP}, + {"@MENUS_SPIN_KICK", "@MENUS_SPIN_KICK_DESC", "BOTH_A7_KICK_S", MDS_FORCE_JUMP}, + {"@MENUS_FLIP_KICK", "@MENUS_FLIP_KICK_DESC", "BOTH_A7_KICK_BF", MDS_FORCE_JUMP}, + {"@MENUS_BUTTERFLY_ATTACK", "@MENUS_BUTTERFLY_ATTACK_DESC", "BOTH_BUTTERFLY_FR1", MDS_SABER}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + {NULL, NULL, 0, MDS_NONE}, + }}; + +static int gamecodetoui[] = {4, 2, 3, 0, 5, 1, 6}; uiInfo_t uiInfo; -static void UI_RegisterCvars( void ); +static void UI_RegisterCvars(void); void UI_Load(void); -static int UI_GetScreenshotFormatForString( const char *str ) { - if ( !Q_stricmp(str, "jpg") || !Q_stricmp(str, "jpeg") ) +static int UI_GetScreenshotFormatForString(const char *str) { + if (!Q_stricmp(str, "jpg") || !Q_stricmp(str, "jpeg")) return SSF_JPEG; - else if ( !Q_stricmp(str, "tga") ) + else if (!Q_stricmp(str, "tga")) return SSF_TGA; - else if ( !Q_stricmp(str, "png") ) + else if (!Q_stricmp(str, "png")) return SSF_PNG; else return -1; } -static const char *UI_GetScreenshotFormatString( int format ) -{ - switch ( format ) - { +static const char *UI_GetScreenshotFormatString(int format) { + switch (format) { default: case SSF_JPEG: return "jpg"; @@ -380,122 +346,109 @@ static const char *UI_GetScreenshotFormatString( int format ) } typedef struct cvarTable_s { - vmCvar_t *vmCvar; - const char *cvarName; - const char *defaultString; - void (*update)( void ); - uint32_t cvarFlags; + vmCvar_t *vmCvar; + const char *cvarName; + const char *defaultString; + void (*update)(void); + uint32_t cvarFlags; } cvarTable_t; -vmCvar_t ui_menuFiles; -vmCvar_t ui_hudFiles; - -vmCvar_t ui_char_anim; -vmCvar_t ui_char_model; -vmCvar_t ui_char_skin_head; -vmCvar_t ui_char_skin_torso; -vmCvar_t ui_char_skin_legs; -vmCvar_t ui_saber_type; -vmCvar_t ui_saber; -vmCvar_t ui_saber2; -vmCvar_t ui_saber_color; -vmCvar_t ui_saber2_color; -vmCvar_t ui_char_color_red; -vmCvar_t ui_char_color_green; -vmCvar_t ui_char_color_blue; -vmCvar_t ui_PrecacheModels; -vmCvar_t ui_screenshotType; - -static void UI_UpdateScreenshot( void ) -{ +vmCvar_t ui_menuFiles; +vmCvar_t ui_hudFiles; + +vmCvar_t ui_char_anim; +vmCvar_t ui_char_model; +vmCvar_t ui_char_skin_head; +vmCvar_t ui_char_skin_torso; +vmCvar_t ui_char_skin_legs; +vmCvar_t ui_saber_type; +vmCvar_t ui_saber; +vmCvar_t ui_saber2; +vmCvar_t ui_saber_color; +vmCvar_t ui_saber2_color; +vmCvar_t ui_char_color_red; +vmCvar_t ui_char_color_green; +vmCvar_t ui_char_color_blue; +vmCvar_t ui_PrecacheModels; +vmCvar_t ui_screenshotType; + +static void UI_UpdateScreenshot(void) { qboolean changed = qfalse; // check some things - if ( ui_screenshotType.string[0] && isalpha( ui_screenshotType.string[0] ) ) - { - int ssf = UI_GetScreenshotFormatForString( ui_screenshotType.string ); - if ( ssf == -1 ) - { - ui.Printf( "UI Screenshot Format Type '%s' unrecognised, defaulting to JPEG\n", ui_screenshotType.string ); + if (ui_screenshotType.string[0] && isalpha(ui_screenshotType.string[0])) { + int ssf = UI_GetScreenshotFormatForString(ui_screenshotType.string); + if (ssf == -1) { + ui.Printf("UI Screenshot Format Type '%s' unrecognised, defaulting to JPEG\n", ui_screenshotType.string); uiInfo.uiDC.screenshotFormat = SSF_JPEG; changed = qtrue; - } - else + } else uiInfo.uiDC.screenshotFormat = ssf; - } - else if ( ui_screenshotType.integer < SSF_JPEG || ui_screenshotType.integer > SSF_PNG ) - { - ui.Printf( "ui_screenshotType %i is out of range, defaulting to 0 (JPEG)\n", ui_screenshotType.integer ); + } else if (ui_screenshotType.integer < SSF_JPEG || ui_screenshotType.integer > SSF_PNG) { + ui.Printf("ui_screenshotType %i is out of range, defaulting to 0 (JPEG)\n", ui_screenshotType.integer); uiInfo.uiDC.screenshotFormat = SSF_JPEG; changed = qtrue; - } - else { - uiInfo.uiDC.screenshotFormat = atoi( ui_screenshotType.string ); + } else { + uiInfo.uiDC.screenshotFormat = atoi(ui_screenshotType.string); changed = qtrue; } - if ( changed ) { - Cvar_Set( "ui_screenshotType", UI_GetScreenshotFormatString( uiInfo.uiDC.screenshotFormat ) ); - Cvar_Update( &ui_screenshotType ); + if (changed) { + Cvar_Set("ui_screenshotType", UI_GetScreenshotFormatString(uiInfo.uiDC.screenshotFormat)); + Cvar_Update(&ui_screenshotType); } } -static cvarTable_t cvarTable[] = -{ - { &ui_menuFiles, "ui_menuFiles", "ui/menus.txt", NULL, CVAR_ARCHIVE }, +static cvarTable_t cvarTable[] = {{&ui_menuFiles, "ui_menuFiles", "ui/menus.txt", NULL, CVAR_ARCHIVE}, #ifdef JK2_MODE - { &ui_hudFiles, "cg_hudFiles", "ui/jk2hud.txt", NULL, CVAR_ARCHIVE}, + {&ui_hudFiles, "cg_hudFiles", "ui/jk2hud.txt", NULL, CVAR_ARCHIVE}, #else - { &ui_hudFiles, "cg_hudFiles", "ui/jahud.txt", NULL, CVAR_ARCHIVE}, + {&ui_hudFiles, "cg_hudFiles", "ui/jahud.txt", NULL, CVAR_ARCHIVE}, #endif - { &ui_char_anim, "ui_char_anim", "BOTH_WALK1", NULL, 0}, + {&ui_char_anim, "ui_char_anim", "BOTH_WALK1", NULL, 0}, - { &ui_char_model, "ui_char_model", "", NULL, 0}, //these are filled in by the "g_*" versions on load - { &ui_char_skin_head, "ui_char_skin_head", "", NULL, 0}, //the "g_*" versions are initialized in UI_Init, ui_atoms.cpp - { &ui_char_skin_torso, "ui_char_skin_torso", "", NULL, 0}, - { &ui_char_skin_legs, "ui_char_skin_legs", "", NULL, 0}, + {&ui_char_model, "ui_char_model", "", NULL, 0}, // these are filled in by the "g_*" versions on load + {&ui_char_skin_head, "ui_char_skin_head", "", NULL, 0}, // the "g_*" versions are initialized in UI_Init, ui_atoms.cpp + {&ui_char_skin_torso, "ui_char_skin_torso", "", NULL, 0}, + {&ui_char_skin_legs, "ui_char_skin_legs", "", NULL, 0}, - { &ui_saber_type, "ui_saber_type", "", NULL, 0}, - { &ui_saber, "ui_saber", "", NULL, 0}, - { &ui_saber2, "ui_saber2", "", NULL, 0}, - { &ui_saber_color, "ui_saber_color", "", NULL, 0}, - { &ui_saber2_color, "ui_saber2_color", "", NULL, 0}, + {&ui_saber_type, "ui_saber_type", "", NULL, 0}, + {&ui_saber, "ui_saber", "", NULL, 0}, + {&ui_saber2, "ui_saber2", "", NULL, 0}, + {&ui_saber_color, "ui_saber_color", "", NULL, 0}, + {&ui_saber2_color, "ui_saber2_color", "", NULL, 0}, - { &ui_char_color_red, "ui_char_color_red", "", NULL, 0}, - { &ui_char_color_green, "ui_char_color_green", "", NULL, 0}, - { &ui_char_color_blue, "ui_char_color_blue", "", NULL, 0}, + {&ui_char_color_red, "ui_char_color_red", "", NULL, 0}, + {&ui_char_color_green, "ui_char_color_green", "", NULL, 0}, + {&ui_char_color_blue, "ui_char_color_blue", "", NULL, 0}, - { &ui_PrecacheModels, "ui_PrecacheModels", "1", NULL, CVAR_ARCHIVE}, + {&ui_PrecacheModels, "ui_PrecacheModels", "1", NULL, CVAR_ARCHIVE}, - { &ui_screenshotType, "ui_screenshotType", "jpg", UI_UpdateScreenshot, CVAR_ARCHIVE } -}; + {&ui_screenshotType, "ui_screenshotType", "jpg", UI_UpdateScreenshot, CVAR_ARCHIVE}}; #define FP_UPDATED_NONE -1 #define NOWEAPON -1 -static const size_t cvarTableSize = ARRAY_LEN( cvarTable ); +static const size_t cvarTableSize = ARRAY_LEN(cvarTable); void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, int iMaxPixelWidth, int style, int iFontIndex); -int Key_GetCatcher( void ); +int Key_GetCatcher(void); -#define UI_FPS_FRAMES 4 -void _UI_Refresh( int realtime ) -{ +#define UI_FPS_FRAMES 4 +void _UI_Refresh(int realtime) { static int index; - static int previousTimes[UI_FPS_FRAMES]; + static int previousTimes[UI_FPS_FRAMES]; - if ( !( Key_GetCatcher() & KEYCATCH_UI ) ) - { + if (!(Key_GetCatcher() & KEYCATCH_UI)) { return; } extern void SE_CheckForLanguageUpdates(void); SE_CheckForLanguageUpdates(); - if ( Menus_AnyFullScreenVisible() ) - {//if not in full screen, don't mess with ghoul2 - //rww - ghoul2 needs to know what time it is even if the client/server are not running - //FIXME: this screws up the game when you go back to the game... + if (Menus_AnyFullScreenVisible()) { // if not in full screen, don't mess with ghoul2 + // rww - ghoul2 needs to know what time it is even if the client/server are not running + // FIXME: this screws up the game when you go back to the game... re.G2API_SetTime(realtime, 0); re.G2API_SetTime(realtime, 1); } @@ -505,17 +458,14 @@ void _UI_Refresh( int realtime ) previousTimes[index % UI_FPS_FRAMES] = uiInfo.uiDC.frameTime; index++; - if ( index > UI_FPS_FRAMES ) - { + if (index > UI_FPS_FRAMES) { int i, total; // average multiple frames together to smooth changes out a bit total = 0; - for ( i = 0 ; i < UI_FPS_FRAMES ; i++ ) - { + for (i = 0; i < UI_FPS_FRAMES; i++) { total += previousTimes[i]; } - if ( !total ) - { + if (!total) { total = 1; } uiInfo.uiDC.FPS = 1000 * UI_FPS_FRAMES / total; @@ -523,25 +473,22 @@ void _UI_Refresh( int realtime ) UI_UpdateCvars(); - if (Menu_Count() > 0) - { + if (Menu_Count() > 0) { // paint all the menus Menu_PaintAll(); // refresh server browser list -// UI_DoServerRefresh(); + // UI_DoServerRefresh(); // refresh server status -// UI_BuildServerStatus(qfalse); + // UI_BuildServerStatus(qfalse); // refresh find player list -// UI_BuildFindPlayerList(qfalse); + // UI_BuildFindPlayerList(qfalse); } // draw cursor - UI_SetColor( NULL ); - if (Menu_Count() > 0) - { - if (uiInfo.uiDC.cursorShow == qtrue) - { - UI_DrawHandlePic( uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory, 48, 48, uiInfo.uiDC.Assets.cursor); + UI_SetColor(NULL); + if (Menu_Count() > 0) { + if (uiInfo.uiDC.cursorShow == qtrue) { + UI_DrawHandlePic(uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory, 48, 48, uiInfo.uiDC.Assets.cursor); } } } @@ -554,19 +501,19 @@ UI_LoadMods =============== */ static void UI_LoadMods() { - int numdirs; - char dirlist[MODSBUFSIZE]; - char *dirptr; - char *descptr; - int i; - int dirlen; + int numdirs; + char dirlist[MODSBUFSIZE]; + char *dirptr; + char *descptr; + int i; + int dirlen; uiInfo.modCount = 0; - numdirs = FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) ); - dirptr = dirlist; - for( i = 0; i < numdirs; i++ ) { - dirlen = strlen( dirptr ) + 1; + numdirs = FS_GetFileList("$modlist", "", dirlist, sizeof(dirlist)); + dirptr = dirlist; + for (i = 0; i < numdirs; i++) { + dirlen = strlen(dirptr) + 1; descptr = dirptr + dirlen; uiInfo.modList[uiInfo.modCount].modName = String_Alloc(dirptr); uiInfo.modList[uiInfo.modCount].modDescr = String_Alloc(descptr); @@ -586,13 +533,11 @@ This is the only way control passes into the module. This must be the very first function compiled into the .qvm file ================ */ -extern "C" Q_EXPORT intptr_t QDECL vmMain( int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11 ) -{ +extern "C" Q_EXPORT intptr_t QDECL vmMain(int command, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, + int arg10, int arg11) { return 0; } - - /* ================ Text_PaintChar @@ -616,146 +561,122 @@ Text_Paint */ // iMaxPixelWidth is 0 here for no limit (but gets converted to -1), else max printable pixel width relative to start pos // -void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, int iMaxPixelWidth, int style, int iFontIndex) -{ - if (iFontIndex == 0) - { +void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, int iMaxPixelWidth, int style, int iFontIndex) { + if (iFontIndex == 0) { iFontIndex = uiInfo.uiDC.Assets.qhMediumFont; } // kludge.. convert JK2 menu styles to SOF2 printstring ctrl codes... // int iStyleOR = 0; - switch (style) - { -// case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text -// case ITEM_TEXTSTYLE_BLINK: iStyleOR = STYLE_BLINK;break; // JK2 fast blinking - case ITEM_TEXTSTYLE_PULSE: iStyleOR = STYLE_BLINK;break; // JK2 slow pulsing - case ITEM_TEXTSTYLE_SHADOWED: iStyleOR = STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_OUTLINED: iStyleOR = STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_OUTLINESHADOWED: iStyleOR = STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_SHADOWEDMORE: iStyleOR = STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - } - - ui.R_Font_DrawString( x, // int ox - y, // int oy - text, // const char *text - color, // paletteRGBA_c c - iStyleOR | iFontIndex, // const int iFontHandle - !iMaxPixelWidth?-1:iMaxPixelWidth, // iMaxPixelWidth (-1 = none) - scale // const float scale = 1.0f - ); + switch (style) { + // case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text + // case ITEM_TEXTSTYLE_BLINK: iStyleOR = STYLE_BLINK;break; // JK2 fast blinking + case ITEM_TEXTSTYLE_PULSE: + iStyleOR = STYLE_BLINK; + break; // JK2 slow pulsing + case ITEM_TEXTSTYLE_SHADOWED: + iStyleOR = STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_OUTLINED: + iStyleOR = STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_OUTLINESHADOWED: + iStyleOR = STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_SHADOWEDMORE: + iStyleOR = STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + } + + ui.R_Font_DrawString(x, // int ox + y, // int oy + text, // const char *text + color, // paletteRGBA_c c + iStyleOR | iFontIndex, // const int iFontHandle + !iMaxPixelWidth ? -1 : iMaxPixelWidth, // iMaxPixelWidth (-1 = none) + scale // const float scale = 1.0f + ); } - /* ================ Text_PaintWithCursor ================ */ // iMaxPixelWidth is 0 here for no-limit -void Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int iMaxPixelWidth, int style, int iFontIndex) -{ +void Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int iMaxPixelWidth, int style, + int iFontIndex) { Text_Paint(x, y, scale, color, text, iMaxPixelWidth, style, iFontIndex); // now print the cursor as well... // char sTemp[1024]; - int iCopyCount = iMaxPixelWidth > 0 ? Q_min( (int)strlen( text ), iMaxPixelWidth ) : (int)strlen( text ); - iCopyCount = Q_min(iCopyCount, cursorPos); - iCopyCount = Q_min(iCopyCount,(int)sizeof(sTemp)); + int iCopyCount = iMaxPixelWidth > 0 ? Q_min((int)strlen(text), iMaxPixelWidth) : (int)strlen(text); + iCopyCount = Q_min(iCopyCount, cursorPos); + iCopyCount = Q_min(iCopyCount, (int)sizeof(sTemp)); // copy text into temp buffer for pixel measure... // - strncpy(sTemp,text,iCopyCount); - sTemp[iCopyCount] = '\0'; + strncpy(sTemp, text, iCopyCount); + sTemp[iCopyCount] = '\0'; - int iNextXpos = ui.R_Font_StrLenPixels(sTemp, iFontIndex, scale ); + int iNextXpos = ui.R_Font_StrLenPixels(sTemp, iFontIndex, scale); - Text_Paint(x+iNextXpos, y, scale, color, va("%c",cursor), iMaxPixelWidth, style|ITEM_TEXTSTYLE_BLINK, iFontIndex); + Text_Paint(x + iNextXpos, y, scale, color, va("%c", cursor), iMaxPixelWidth, style | ITEM_TEXTSTYLE_BLINK, iFontIndex); } - -const char *UI_FeederItemText(float feederID, int index, int column, qhandle_t *handle) -{ +const char *UI_FeederItemText(float feederID, int index, int column, qhandle_t *handle) { *handle = -1; - if (feederID == FEEDER_SAVEGAMES) - { - if (column==0) - { + if (feederID == FEEDER_SAVEGAMES) { + if (column == 0) { return s_savedata[index].currentSaveFileComments; - } - else - { + } else { return s_savedata[index].currentSaveFileDateTimeString; } - } - else if (feederID == FEEDER_MOVES) - { + } else if (feederID == FEEDER_MOVES) { return datapadMoveData[uiInfo.movesTitleIndex][index].title; - } - else if (feederID == FEEDER_MOVES_TITLES) - { + } else if (feederID == FEEDER_MOVES_TITLES) { return datapadMoveTitleData[index]; - } - else if (feederID == FEEDER_PLAYER_SPECIES) - { - if (index >= 0 && index < uiInfo.playerSpeciesCount) - { + } else if (feederID == FEEDER_PLAYER_SPECIES) { + if (index >= 0 && index < uiInfo.playerSpeciesCount) { return uiInfo.playerSpecies[index].Name; } - } - else if (feederID == FEEDER_LANGUAGES) - { + } else if (feederID == FEEDER_LANGUAGES) { #ifdef JK2_MODE // FIXME return NULL; #else - return SE_GetLanguageName( index ); + return SE_GetLanguageName(index); #endif - } - else if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { - *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { + *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name; } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { - *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { + *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name; } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { - *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { + *handle = ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name; } - } - else if (feederID == FEEDER_COLORCHOICES) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { - *handle = ui.R_RegisterShaderNoMip( uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); + } else if (feederID == FEEDER_COLORCHOICES) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { + *handle = ui.R_RegisterShaderNoMip(uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader; } - } - else if (feederID == FEEDER_MODS) - { - if (index >= 0 && index < uiInfo.modCount) - { - if (uiInfo.modList[index].modDescr && *uiInfo.modList[index].modDescr) - { + } else if (feederID == FEEDER_MODS) { + if (index >= 0 && index < uiInfo.modCount) { + if (uiInfo.modList[index].modDescr && *uiInfo.modList[index].modDescr) { return uiInfo.modList[index].modDescr; - } - else - { + } else { return uiInfo.modList[index].modName; } } @@ -764,78 +685,65 @@ const char *UI_FeederItemText(float feederID, int index, int column, qhandle_t * return ""; } -qhandle_t UI_FeederItemImage(float feederID, int index) -{ - if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadIcons[index]; - return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); +qhandle_t UI_FeederItemImage(float feederID, int index) { + if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadIcons[index]; + return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoIcons[index]; - return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoIcons[index]; + return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegIcons[index]; - return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegIcons[index]; + return ui.R_RegisterShaderNoMip(va("models/players/%s/icon_%s.jpg", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); } - } - else if (feederID == FEEDER_COLORCHOICES) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { - return ui.R_RegisterShaderNoMip( uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); + } else if (feederID == FEEDER_COLORCHOICES) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { + return ui.R_RegisterShaderNoMip(uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); } } -/* else if (feederID == FEEDER_ALLMAPS || feederID == FEEDER_MAPS) - { - int actual; - UI_SelectedMap(index, &actual); - index = actual; - if (index >= 0 && index < uiInfo.mapCount) + /* else if (feederID == FEEDER_ALLMAPS || feederID == FEEDER_MAPS) { - if (uiInfo.mapList[index].levelShot == -1) + int actual; + UI_SelectedMap(index, &actual); + index = actual; + if (index >= 0 && index < uiInfo.mapCount) { - uiInfo.mapList[index].levelShot = trap_R_RegisterShaderNoMip(uiInfo.mapList[index].imageName); + if (uiInfo.mapList[index].levelShot == -1) + { + uiInfo.mapList[index].levelShot = trap_R_RegisterShaderNoMip(uiInfo.mapList[index].imageName); + } + return uiInfo.mapList[index].levelShot; } - return uiInfo.mapList[index].levelShot; } - } -*/ + */ return 0; } - /* ================= CreateNextSaveName ================= */ -static int CreateNextSaveName(char *fileName) -{ +static int CreateNextSaveName(char *fileName) { int i; // Loop through all the save games and look for the first open name - for (i=0;i0) && ((s_savegame.currentLine+1) == s_savegame.saveFileCnt) ) - { + if ((s_savegame.currentLine > 0) && ((s_savegame.currentLine + 1) == s_savegame.saveFileCnt)) { s_savegame.currentLine--; // yeah this is a pretty bad hack // adjust cursor position of listbox so correct item is highlighted - UI_AdjustSaveGameListBox( s_savegame.currentLine ); + UI_AdjustSaveGameListBox(s_savegame.currentLine); } -// ReadSaveDirectory(); //refresh - s_savegame.saveFileCnt = -1; //force a refresh at drawtime - + // ReadSaveDirectory(); //refresh + s_savegame.saveFileCnt = -1; // force a refresh at drawtime } - } - else if (Q_stricmp(name, "savegame") == 0) - { + } else if (Q_stricmp(name, "savegame") == 0) { char fileName[MAX_SAVELOADNAME]; char description[64]; // Create a new save game -// if ( !s_savedata[s_savegame.currentLine].currentSaveFileName) // No line was chosen + // if ( !s_savedata[s_savegame.currentLine].currentSaveFileName) // No line was chosen { - CreateNextSaveName(fileName); // Get a name to save to + CreateNextSaveName(fileName); // Get a name to save to } -// else // Overwrite a current save game? Ask first. + // else // Overwrite a current save game? Ask first. { -// s_savegame.yes.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; -// s_savegame.no.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; + // s_savegame.yes.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; + // s_savegame.no.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; -// strcpy(fileName,s_savedata[s_savegame.currentLine].currentSaveFileName); -// s_savegame.awaitingSave = qtrue; -// s_savegame.deletegame.generic.flags = QMF_GRAYED; // Turn off delete button -// break; + // strcpy(fileName,s_savedata[s_savegame.currentLine].currentSaveFileName); + // s_savegame.awaitingSave = qtrue; + // s_savegame.deletegame.generic.flags = QMF_GRAYED; // Turn off delete button + // break; } // Save description line - ui.Cvar_VariableStringBuffer("ui_gameDesc",description,sizeof(description)); + ui.Cvar_VariableStringBuffer("ui_gameDesc", description, sizeof(description)); ui.SG_StoreSaveGameComment(description); - ui.Cmd_ExecuteText( EXEC_APPEND, va("save %s\n", fileName)); - s_savegame.saveFileCnt = -1; //force a refresh the next time around - } - else if (Q_stricmp(name, "LoadMods") == 0) - { + ui.Cmd_ExecuteText(EXEC_APPEND, va("save %s\n", fileName)); + s_savegame.saveFileCnt = -1; // force a refresh the next time around + } else if (Q_stricmp(name, "LoadMods") == 0) { UI_LoadMods(); - } - else if (Q_stricmp(name, "RunMod") == 0) - { - if (uiInfo.modList[uiInfo.modIndex].modName) - { - Cvar_Set( "fs_game", uiInfo.modList[uiInfo.modIndex].modName); - extern void FS_Restart( void ); + } else if (Q_stricmp(name, "RunMod") == 0) { + if (uiInfo.modList[uiInfo.modIndex].modName) { + Cvar_Set("fs_game", uiInfo.modList[uiInfo.modIndex].modName); + extern void FS_Restart(void); FS_Restart(); - Cbuf_ExecuteText( EXEC_APPEND, "vid_restart;" ); + Cbuf_ExecuteText(EXEC_APPEND, "vid_restart;"); } - } - else if (Q_stricmp(name, "Quit") == 0) - { - Cbuf_ExecuteText( EXEC_NOW, "quit"); - } - else if (Q_stricmp(name, "Controls") == 0) - { - Cvar_Set( "cl_paused", "1" ); - trap_Key_SetCatcher( KEYCATCH_UI ); + } else if (Q_stricmp(name, "Quit") == 0) { + Cbuf_ExecuteText(EXEC_NOW, "quit"); + } else if (Q_stricmp(name, "Controls") == 0) { + Cvar_Set("cl_paused", "1"); + trap_Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("setup_menu2"); - } - else if (Q_stricmp(name, "Leave") == 0) - { - Cbuf_ExecuteText( EXEC_APPEND, "disconnect\n" ); - trap_Key_SetCatcher( KEYCATCH_UI ); + } else if (Q_stricmp(name, "Leave") == 0) { + Cbuf_ExecuteText(EXEC_APPEND, "disconnect\n"); + trap_Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); - //Menus_ActivateByName("mainMenu"); - } - else if (Q_stricmp(name, "getvideosetup") == 0) - { - UI_GetVideoSetup ( ); - } - else if (Q_stricmp(name, "updatevideosetup") == 0) - { - UI_UpdateVideoSetup ( ); - } - else if (Q_stricmp(name, "nextDataPadForcePower") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpforcenext\n"); - } - else if (Q_stricmp(name, "prevDataPadForcePower") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpforceprev\n"); - } - else if (Q_stricmp(name, "nextDataPadWeapon") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpweapnext\n"); - } - else if (Q_stricmp(name, "prevDataPadWeapon") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpweapprev\n"); - } - else if (Q_stricmp(name, "nextDataPadInventory") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpinvnext\n"); - } - else if (Q_stricmp(name, "prevDataPadInventory") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "dpinvprev\n"); - } - else if (Q_stricmp(name, "checkvid1data") == 0) // Warn user data has changed before leaving screen? + // Menus_ActivateByName("mainMenu"); + } else if (Q_stricmp(name, "getvideosetup") == 0) { + UI_GetVideoSetup(); + } else if (Q_stricmp(name, "updatevideosetup") == 0) { + UI_UpdateVideoSetup(); + } else if (Q_stricmp(name, "nextDataPadForcePower") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpforcenext\n"); + } else if (Q_stricmp(name, "prevDataPadForcePower") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpforceprev\n"); + } else if (Q_stricmp(name, "nextDataPadWeapon") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpweapnext\n"); + } else if (Q_stricmp(name, "prevDataPadWeapon") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpweapprev\n"); + } else if (Q_stricmp(name, "nextDataPadInventory") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpinvnext\n"); + } else if (Q_stricmp(name, "prevDataPadInventory") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "dpinvprev\n"); + } else if (Q_stricmp(name, "checkvid1data") == 0) // Warn user data has changed before leaving screen? { String_Parse(args, &menuName); String_Parse(args, &warningMenuName); - UI_CheckVid1Data(menuName,warningMenuName); - } - else if (Q_stricmp(name, "startgame") == 0) - { + UI_CheckVid1Data(menuName, warningMenuName); + } else if (Q_stricmp(name, "startgame") == 0) { Menus_CloseAll(); #ifdef JK2_MODE - ui.Cmd_ExecuteText( EXEC_APPEND, "map kejim_post\n" ); + ui.Cmd_ExecuteText(EXEC_APPEND, "map kejim_post\n"); #else - ui.Cmd_ExecuteText( EXEC_APPEND, "map yavin1\n"); + ui.Cmd_ExecuteText(EXEC_APPEND, "map yavin1\n"); #endif - } - else if (Q_stricmp(name, "startmap") == 0) - { + } else if (Q_stricmp(name, "startmap") == 0) { Menus_CloseAll(); String_Parse(args, &mapName); - ui.Cmd_ExecuteText( EXEC_APPEND, va("maptransition %s\n",mapName)); - } - else if (Q_stricmp(name, "closeingame") == 0) - { - trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI ); + ui.Cmd_ExecuteText(EXEC_APPEND, va("maptransition %s\n", mapName)); + } else if (Q_stricmp(name, "closeingame") == 0) { + trap_Key_SetCatcher(trap_Key_GetCatcher() & ~KEYCATCH_UI); trap_Key_ClearStates(); - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); Menus_CloseAll(); - if (1 == Cvar_VariableIntegerValue("ui_missionfailed")) - { + if (1 == Cvar_VariableIntegerValue("ui_missionfailed")) { Menus_ActivateByName("missionfailed_menu"); - ui.Key_SetCatcher( KEYCATCH_UI ); - } - else - { + ui.Key_SetCatcher(KEYCATCH_UI); + } else { Menus_ActivateByName("mainhud"); } - } - else if (Q_stricmp(name, "closedatapad") == 0) - { - trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI ); + } else if (Q_stricmp(name, "closedatapad") == 0) { + trap_Key_SetCatcher(trap_Key_GetCatcher() & ~KEYCATCH_UI); trap_Key_ClearStates(); - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); Menus_CloseAll(); Menus_ActivateByName("mainhud"); - Cvar_Set( "cg_updatedDataPadForcePower1", "0" ); - Cvar_Set( "cg_updatedDataPadForcePower2", "0" ); - Cvar_Set( "cg_updatedDataPadForcePower3", "0" ); - Cvar_Set( "cg_updatedDataPadObjective", "0" ); - } - else if (Q_stricmp(name, "closesabermenu") == 0) - { + Cvar_Set("cg_updatedDataPadForcePower1", "0"); + Cvar_Set("cg_updatedDataPadForcePower2", "0"); + Cvar_Set("cg_updatedDataPadForcePower3", "0"); + Cvar_Set("cg_updatedDataPadObjective", "0"); + } else if (Q_stricmp(name, "closesabermenu") == 0) { // if we're in the saber menu when creating a character, close this down - if( !Cvar_VariableIntegerValue( "saber_menu" ) ) - { - Menus_CloseByName( "saberMenu" ); - Menus_OpenByName( "characterMenu" ); + if (!Cvar_VariableIntegerValue("saber_menu")) { + Menus_CloseByName("saberMenu"); + Menus_OpenByName("characterMenu"); } - } - else if (Q_stricmp(name, "clearmouseover") == 0) - { + } else if (Q_stricmp(name, "clearmouseover") == 0) { itemDef_t *item; menuDef_t *menu = Menu_GetFocused(); - if (menu) - { + if (menu) { const char *itemName; String_Parse(args, &itemName); - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, itemName); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, itemName); + if (item) { item->window.flags &= ~WINDOW_MOUSEOVER; } } - } - else if (Q_stricmp(name, "setMovesListDefault") == 0) - { + } else if (Q_stricmp(name, "setMovesListDefault") == 0) { uiInfo.movesTitleIndex = 2; - } - else if (Q_stricmp(name, "resetMovesDesc") == 0) - { + } else if (Q_stricmp(name, "resetMovesDesc") == 0) { menuDef_t *menu = Menu_GetFocused(); itemDef_t *item; - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName(menu, "item_desc"); - if (item) - { - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + if (menu) { + item = (itemDef_s *)Menu_FindItemByName(menu, "item_desc"); + if (item) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = 0; listPtr->startPos = 0; } @@ -1153,30 +982,25 @@ static qboolean UI_RunMenuScript ( const char **args ) } } - } - else if (Q_stricmp(name, "resetMovesList") == 0) - { + } else if (Q_stricmp(name, "resetMovesList") == 0) { menuDef_t *menu; menu = Menus_FindByName("datapadMovesMenu"); - //update saber models - if (menu) - { + // update saber models + if (menu) { itemDef_t *item; - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { - UI_SaberAttachToChar( item ); + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { + UI_SaberAttachToChar(item); } } - Cvar_Set( "ui_move_desc", " " ); + Cvar_Set("ui_move_desc", " "); } -// else if (Q_stricmp(name, "setanisotropicmax") == 0) -// { -// r_ext_texture_filter_anisotropic->value; -// } - else if (Q_stricmp(name, "setMoveCharacter") == 0) - { + // else if (Q_stricmp(name, "setanisotropicmax") == 0) + // { + // r_ext_texture_filter_anisotropic->value; + // } + else if (Q_stricmp(name, "setMoveCharacter") == 0) { itemDef_t *item; menuDef_t *menu; modelDef_t *modelPtr; @@ -1189,393 +1013,271 @@ static qboolean UI_RunMenuScript ( const char **args ) menu = Menus_FindByName("datapadMovesMenu"); - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { - modelPtr = (modelDef_t*)item->typeData; - if (modelPtr) - { + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { + modelPtr = (modelDef_t *)item->typeData; + if (modelPtr) { uiInfo.movesBaseAnim = datapadMoveTitleBaseAnims[uiInfo.movesTitleIndex]; - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); - uiInfo.moveAnimTime = 0 ; + uiInfo.moveAnimTime = 0; DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); - Com_sprintf( skin, sizeof( skin ), "models/players/%s/|%s|%s|%s", - Cvar_VariableString ( "g_char_model"), - Cvar_VariableString ( "g_char_skin_head"), - Cvar_VariableString ( "g_char_skin_torso"), - Cvar_VariableString ( "g_char_skin_legs") - ); - - ItemParse_model_g2skin_go( item, skin ); - UI_SaberAttachToChar( item ); + Com_sprintf(skin, sizeof(skin), "models/players/%s/|%s|%s|%s", Cvar_VariableString("g_char_model"), + Cvar_VariableString("g_char_skin_head"), Cvar_VariableString("g_char_skin_torso"), Cvar_VariableString("g_char_skin_legs")); + + ItemParse_model_g2skin_go(item, skin); + UI_SaberAttachToChar(item); } } } - } - else if (Q_stricmp(name, "glCustom") == 0) - { + } else if (Q_stricmp(name, "glCustom") == 0) { Cvar_Set("ui_r_glCustom", "4"); - } - else if (Q_stricmp(name, "character") == 0) - { - UI_UpdateCharacter( qfalse ); - } - else if (Q_stricmp(name, "characterchanged") == 0) - { - UI_UpdateCharacter( qtrue ); - } - else if (Q_stricmp(name, "char_skin") == 0) - { + } else if (Q_stricmp(name, "character") == 0) { + UI_UpdateCharacter(qfalse); + } else if (Q_stricmp(name, "characterchanged") == 0) { + UI_UpdateCharacter(qtrue); + } else if (Q_stricmp(name, "char_skin") == 0) { UI_UpdateCharacterSkin(); - } - else if (Q_stricmp(name, "saber_type") == 0) - { + } else if (Q_stricmp(name, "saber_type") == 0) { UI_UpdateSaberType(); - } - else if (Q_stricmp(name, "saber_hilt") == 0) - { - UI_UpdateSaberHilt( qfalse ); - } - else if (Q_stricmp(name, "saber_color") == 0) - { -// UI_UpdateSaberColor( qfalse ); - } - else if (Q_stricmp(name, "saber2_hilt") == 0) - { - UI_UpdateSaberHilt( qtrue ); - } - else if (Q_stricmp(name, "saber2_color") == 0) - { -// UI_UpdateSaberColor( qtrue ); - } - else if (Q_stricmp(name, "updatecharcvars") == 0) - { + } else if (Q_stricmp(name, "saber_hilt") == 0) { + UI_UpdateSaberHilt(qfalse); + } else if (Q_stricmp(name, "saber_color") == 0) { + // UI_UpdateSaberColor( qfalse ); + } else if (Q_stricmp(name, "saber2_hilt") == 0) { + UI_UpdateSaberHilt(qtrue); + } else if (Q_stricmp(name, "saber2_color") == 0) { + // UI_UpdateSaberColor( qtrue ); + } else if (Q_stricmp(name, "updatecharcvars") == 0) { UI_UpdateCharacterCvars(); - } - else if (Q_stricmp(name, "getcharcvars") == 0) - { + } else if (Q_stricmp(name, "getcharcvars") == 0) { UI_GetCharacterCvars(); - } - else if (Q_stricmp(name, "updatesabercvars") == 0) - { + } else if (Q_stricmp(name, "updatesabercvars") == 0) { UI_UpdateSaberCvars(); - } - else if (Q_stricmp(name, "getsabercvars") == 0) - { + } else if (Q_stricmp(name, "getsabercvars") == 0) { UI_GetSaberCvars(); - } - else if (Q_stricmp(name, "resetsabercvardefaults") == 0) - { + } else if (Q_stricmp(name, "resetsabercvardefaults") == 0) { // NOTE : ONLY do this if saber menu is set properly (ie. first time we enter this menu) - if( !Cvar_VariableIntegerValue( "saber_menu" ) ) - { + if (!Cvar_VariableIntegerValue("saber_menu")) { UI_ResetSaberCvars(); } - } + } #ifndef JK2_MODE - else if (Q_stricmp(name, "updatefightingstylechoices") == 0) - { + else if (Q_stricmp(name, "updatefightingstylechoices") == 0) { UI_UpdateFightingStyleChoices(); } #endif // !JK2_MODE - else if (Q_stricmp(name, "initallocforcepower") == 0) - { + else if (Q_stricmp(name, "initallocforcepower") == 0) { const char *forceName; String_Parse(args, &forceName); UI_InitAllocForcePowers(forceName); - } - else if (Q_stricmp(name, "affectforcepowerlevel") == 0) - { + } else if (Q_stricmp(name, "affectforcepowerlevel") == 0) { const char *forceName; String_Parse(args, &forceName); UI_AffectForcePowerLevel(forceName); - } - else if (Q_stricmp(name, "decrementcurrentforcepower") == 0) - { + } else if (Q_stricmp(name, "decrementcurrentforcepower") == 0) { UI_DecrementCurrentForcePower(); - } - else if (Q_stricmp(name, "shutdownforcehelp") == 0) - { + } else if (Q_stricmp(name, "shutdownforcehelp") == 0) { UI_ShutdownForceHelp(); - } - else if (Q_stricmp(name, "forcehelpactive") == 0) - { + } else if (Q_stricmp(name, "forcehelpactive") == 0) { UI_ForceHelpActive(); } #ifndef JK2_MODE - else if (Q_stricmp(name, "demosetforcelevels") == 0) - { + else if (Q_stricmp(name, "demosetforcelevels") == 0) { UI_DemoSetForceLevels(); } #endif // !JK2_MODE - else if (Q_stricmp(name, "recordforcelevels") == 0) - { + else if (Q_stricmp(name, "recordforcelevels") == 0) { UI_RecordForceLevels(); - } - else if (Q_stricmp(name, "recordweapons") == 0) - { + } else if (Q_stricmp(name, "recordweapons") == 0) { UI_RecordWeapons(); - } - else if (Q_stricmp(name, "showforceleveldesc") == 0) - { + } else if (Q_stricmp(name, "showforceleveldesc") == 0) { const char *forceName; String_Parse(args, &forceName); UI_ShowForceLevelDesc(forceName); - } - else if (Q_stricmp(name, "resetforcelevels") == 0) - { + } else if (Q_stricmp(name, "resetforcelevels") == 0) { UI_ResetForceLevels(); - } - else if (Q_stricmp(name, "weaponhelpactive") == 0) - { + } else if (Q_stricmp(name, "weaponhelpactive") == 0) { UI_WeaponHelpActive(); } // initialize weapon selection screen - else if (Q_stricmp(name, "initweaponselect") == 0) - { + else if (Q_stricmp(name, "initweaponselect") == 0) { UI_InitWeaponSelect(); - } - else if (Q_stricmp(name, "clearweapons") == 0) - { + } else if (Q_stricmp(name, "clearweapons") == 0) { UI_ClearWeapons(); - } - else if (Q_stricmp(name, "stopgamesounds") == 0) - { + } else if (Q_stricmp(name, "stopgamesounds") == 0) { trap_S_StopSounds(); - } - else if (Q_stricmp(name, "loadmissionselectmenu") == 0) - { + } else if (Q_stricmp(name, "loadmissionselectmenu") == 0) { const char *cvarName; String_Parse(args, &cvarName); - if (cvarName) - { + if (cvarName) { UI_LoadMissionSelectMenu(cvarName); } } #ifndef JK2_MODE - else if (Q_stricmp(name, "calcforcestatus") == 0) - { + else if (Q_stricmp(name, "calcforcestatus") == 0) { UI_CalcForceStatus(); } #endif // !JK2_MODE - else if (Q_stricmp(name, "giveweapon") == 0) - { + else if (Q_stricmp(name, "giveweapon") == 0) { const char *weaponIndex; String_Parse(args, &weaponIndex); UI_GiveWeapon(atoi(weaponIndex)); - } - else if (Q_stricmp(name, "equipweapon") == 0) - { + } else if (Q_stricmp(name, "equipweapon") == 0) { const char *weaponIndex; String_Parse(args, &weaponIndex); UI_EquipWeapon(atoi(weaponIndex)); - } - else if (Q_stricmp(name, "addweaponselection") == 0) - { + } else if (Q_stricmp(name, "addweaponselection") == 0) { const char *weaponIndex; String_Parse(args, &weaponIndex); - if (!weaponIndex) - { + if (!weaponIndex) { return qfalse; } const char *ammoIndex; String_Parse(args, &ammoIndex); - if (!ammoIndex) - { + if (!ammoIndex) { return qfalse; } const char *ammoAmount; String_Parse(args, &ammoAmount); - if (!ammoAmount) - { + if (!ammoAmount) { return qfalse; } const char *itemName; String_Parse(args, &itemName); - if (!itemName) - { + if (!itemName) { return qfalse; } const char *litItemName; String_Parse(args, &litItemName); - if (!litItemName) - { + if (!litItemName) { return qfalse; } const char *backgroundName; String_Parse(args, &backgroundName); - if (!backgroundName) - { + if (!backgroundName) { return qfalse; } const char *soundfile = NULL; String_Parse(args, &soundfile); - UI_AddWeaponSelection(atoi(weaponIndex),atoi(ammoIndex),atoi(ammoAmount),itemName,litItemName, backgroundName, soundfile); - } - else if (Q_stricmp(name, "addthrowweaponselection") == 0) - { + UI_AddWeaponSelection(atoi(weaponIndex), atoi(ammoIndex), atoi(ammoAmount), itemName, litItemName, backgroundName, soundfile); + } else if (Q_stricmp(name, "addthrowweaponselection") == 0) { const char *weaponIndex; String_Parse(args, &weaponIndex); - if (!weaponIndex) - { + if (!weaponIndex) { return qfalse; } const char *ammoIndex; String_Parse(args, &ammoIndex); - if (!ammoIndex) - { + if (!ammoIndex) { return qfalse; } const char *ammoAmount; String_Parse(args, &ammoAmount); - if (!ammoAmount) - { + if (!ammoAmount) { return qfalse; } const char *itemName; String_Parse(args, &itemName); - if (!itemName) - { + if (!itemName) { return qfalse; } const char *litItemName; String_Parse(args, &litItemName); - if (!litItemName) - { + if (!litItemName) { return qfalse; } const char *backgroundName; String_Parse(args, &backgroundName); - if (!backgroundName) - { + if (!backgroundName) { return qfalse; } const char *soundfile; String_Parse(args, &soundfile); - UI_AddThrowWeaponSelection(atoi(weaponIndex),atoi(ammoIndex),atoi(ammoAmount),itemName,litItemName,backgroundName, soundfile); - } - else if (Q_stricmp(name, "removeweaponselection") == 0) - { + UI_AddThrowWeaponSelection(atoi(weaponIndex), atoi(ammoIndex), atoi(ammoAmount), itemName, litItemName, backgroundName, soundfile); + } else if (Q_stricmp(name, "removeweaponselection") == 0) { const char *weaponIndex; String_Parse(args, &weaponIndex); - if (weaponIndex) - { + if (weaponIndex) { UI_RemoveWeaponSelection(atoi(weaponIndex)); } - } - else if (Q_stricmp(name, "removethrowweaponselection") == 0) - { + } else if (Q_stricmp(name, "removethrowweaponselection") == 0) { UI_RemoveThrowWeaponSelection(); - } - else if (Q_stricmp(name, "normalthrowselection") == 0) - { + } else if (Q_stricmp(name, "normalthrowselection") == 0) { UI_NormalThrowSelection(); - } - else if (Q_stricmp(name, "highlightthrowselection") == 0) - { + } else if (Q_stricmp(name, "highlightthrowselection") == 0) { UI_HighLightThrowSelection(); - } - else if (Q_stricmp(name, "normalweaponselection") == 0) - { + } else if (Q_stricmp(name, "normalweaponselection") == 0) { const char *slotIndex; String_Parse(args, &slotIndex); - if (!slotIndex) - { + if (!slotIndex) { return qfalse; } UI_NormalWeaponSelection(atoi(slotIndex)); - } - else if (Q_stricmp(name, "highlightweaponselection") == 0) - { + } else if (Q_stricmp(name, "highlightweaponselection") == 0) { const char *slotIndex; String_Parse(args, &slotIndex); - if (!slotIndex) - { + if (!slotIndex) { return qfalse; } UI_HighLightWeaponSelection(atoi(slotIndex)); - } - else if (Q_stricmp(name, "clearinventory") == 0) - { + } else if (Q_stricmp(name, "clearinventory") == 0) { UI_ClearInventory(); - } - else if (Q_stricmp(name, "giveinventory") == 0) - { - const char *inventoryIndex,*amount; + } else if (Q_stricmp(name, "giveinventory") == 0) { + const char *inventoryIndex, *amount; String_Parse(args, &inventoryIndex); String_Parse(args, &amount); - UI_GiveInventory(atoi(inventoryIndex),atoi(amount)); + UI_GiveInventory(atoi(inventoryIndex), atoi(amount)); } #ifndef JK2_MODE - else if (Q_stricmp(name, "updatefightingstyle") == 0) - { + else if (Q_stricmp(name, "updatefightingstyle") == 0) { UI_UpdateFightingStyle(); } #endif // !JK2_MODE - else if (Q_stricmp(name, "update") == 0) - { - if (String_Parse(args, &name2)) - { + else if (Q_stricmp(name, "update") == 0) { + if (String_Parse(args, &name2)) { UI_Update(name2); - } - else - { + } else { Com_Printf("update missing cmd\n"); } - } - else if (Q_stricmp(name, "load_quick") == 0) - { + } else if (Q_stricmp(name, "load_quick") == 0) { #ifdef JK2_MODE - ui.Cmd_ExecuteText(EXEC_APPEND,"load quik\n"); + ui.Cmd_ExecuteText(EXEC_APPEND, "load quik\n"); #else - ui.Cmd_ExecuteText(EXEC_APPEND,"load quick\n"); + ui.Cmd_ExecuteText(EXEC_APPEND, "load quick\n"); #endif - } - else if (Q_stricmp(name, "load_auto") == 0) - { - ui.Cmd_ExecuteText(EXEC_APPEND,"load *respawn\n"); //death menu, might load a saved game instead if they just loaded on this map - } - else if (Q_stricmp(name, "decrementforcepowerlevel") == 0) - { + } else if (Q_stricmp(name, "load_auto") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "load *respawn\n"); // death menu, might load a saved game instead if they just loaded on this map + } else if (Q_stricmp(name, "decrementforcepowerlevel") == 0) { UI_DecrementForcePowerLevel(); - } - else if (Q_stricmp(name, "getmousepitch") == 0) - { + } else if (Q_stricmp(name, "getmousepitch") == 0) { Cvar_Set("ui_mousePitch", (trap_Cvar_VariableValue("m_pitch") >= 0) ? "0" : "1"); - } - else if (Q_stricmp(name, "resetcharacterlistboxes") == 0) - { + } else if (Q_stricmp(name, "resetcharacterlistboxes") == 0) { UI_ResetCharacterListBoxes(); - } - else if ( Q_stricmp( name, "LaunchMP" ) == 0 ) - { + } else if (Q_stricmp(name, "LaunchMP") == 0) { // TODO for MAC_PORT, will only be valid for non-JK2 mode - } - else - { + } else { Com_Printf("unknown UI script %s\n", name); } } @@ -1588,154 +1290,107 @@ static qboolean UI_RunMenuScript ( const char **args ) UI_GetValue ================= */ -static float UI_GetValue(int ownerDraw) -{ - return 0; -} +static float UI_GetValue(int ownerDraw) { return 0; } -//Force Warnings -enum -{ - FW_VERY_LIGHT = 0, - FW_SEMI_LIGHT, - FW_NEUTRAL, - FW_SEMI_DARK, - FW_VERY_DARK -}; +// Force Warnings +enum { FW_VERY_LIGHT = 0, FW_SEMI_LIGHT, FW_NEUTRAL, FW_SEMI_DARK, FW_VERY_DARK }; -const char *lukeForceStatusSounds[] = -{ -"sound/chars/luke/misc/MLUK_03.mp3", // Very Light -"sound/chars/luke/misc/MLUK_04.mp3", // Semi Light -"sound/chars/luke/misc/MLUK_05.mp3", // Neutral -"sound/chars/luke/misc/MLUK_01.mp3", // Semi dark -"sound/chars/luke/misc/MLUK_02.mp3", // Very dark +const char *lukeForceStatusSounds[] = { + "sound/chars/luke/misc/MLUK_03.mp3", // Very Light + "sound/chars/luke/misc/MLUK_04.mp3", // Semi Light + "sound/chars/luke/misc/MLUK_05.mp3", // Neutral + "sound/chars/luke/misc/MLUK_01.mp3", // Semi dark + "sound/chars/luke/misc/MLUK_02.mp3", // Very dark }; -const char *kyleForceStatusSounds[] = -{ -"sound/chars/kyle/misc/MKYK_05.mp3", // Very Light -"sound/chars/kyle/misc/MKYK_04.mp3", // Semi Light -"sound/chars/kyle/misc/MKYK_03.mp3", // Neutral -"sound/chars/kyle/misc/MKYK_01.mp3", // Semi dark -"sound/chars/kyle/misc/MKYK_02.mp3", // Very dark +const char *kyleForceStatusSounds[] = { + "sound/chars/kyle/misc/MKYK_05.mp3", // Very Light + "sound/chars/kyle/misc/MKYK_04.mp3", // Semi Light + "sound/chars/kyle/misc/MKYK_03.mp3", // Neutral + "sound/chars/kyle/misc/MKYK_01.mp3", // Semi dark + "sound/chars/kyle/misc/MKYK_02.mp3", // Very dark }; - #ifndef JK2_MODE -static void UI_CalcForceStatus(void) -{ - float lightSide,darkSide,total; - short who, index=FW_VERY_LIGHT; - qboolean lukeFlag=qtrue; - float percent; - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player - char value[256]; - - if (!cl) - { +static void UI_CalcForceStatus(void) { + float lightSide, darkSide, total; + short who, index = FW_VERY_LIGHT; + qboolean lukeFlag = qtrue; + float percent; + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + char value[256]; + + if (!cl) { return; } - playerState_t* pState = cl->gentity->client; + playerState_t *pState = cl->gentity->client; - if (!cl->gentity || !cl->gentity->client) - { + if (!cl->gentity || !cl->gentity->client) { return; } memset(value, 0, sizeof(value)); - lightSide = pState->forcePowerLevel[FP_HEAL] + - pState->forcePowerLevel[FP_TELEPATHY] + - pState->forcePowerLevel[FP_PROTECT] + - pState->forcePowerLevel[FP_ABSORB]; + lightSide = + pState->forcePowerLevel[FP_HEAL] + pState->forcePowerLevel[FP_TELEPATHY] + pState->forcePowerLevel[FP_PROTECT] + pState->forcePowerLevel[FP_ABSORB]; - darkSide = pState->forcePowerLevel[FP_GRIP] + - pState->forcePowerLevel[FP_LIGHTNING] + - pState->forcePowerLevel[FP_RAGE] + - pState->forcePowerLevel[FP_DRAIN]; + darkSide = pState->forcePowerLevel[FP_GRIP] + pState->forcePowerLevel[FP_LIGHTNING] + pState->forcePowerLevel[FP_RAGE] + pState->forcePowerLevel[FP_DRAIN]; total = lightSide + darkSide; percent = lightSide / total; - who = Q_irand( 0, 100 ); - if (percent >= 0.90f) // 90 - 100% + who = Q_irand(0, 100); + if (percent >= 0.90f) // 90 - 100% { index = FW_VERY_LIGHT; - if (who <50) - { - strcpy(value,"vlk"); // Very light Kyle + if (who < 50) { + strcpy(value, "vlk"); // Very light Kyle lukeFlag = qfalse; - } - else - { - strcpy(value,"vll"); // Very light Luke + } else { + strcpy(value, "vll"); // Very light Luke } - } - else if (percent > 0.60f ) - { + } else if (percent > 0.60f) { index = FW_SEMI_LIGHT; - if ( who<50 ) - { - strcpy(value,"slk"); // Semi-light Kyle + if (who < 50) { + strcpy(value, "slk"); // Semi-light Kyle lukeFlag = qfalse; + } else { + strcpy(value, "sll"); // Semi-light light Luke } - else - { - strcpy(value,"sll"); // Semi-light light Luke - } - } - else if (percent > 0.40f ) - { + } else if (percent > 0.40f) { index = FW_NEUTRAL; - if ( who<50 ) - { - strcpy(value,"ntk"); // Neutral Kyle + if (who < 50) { + strcpy(value, "ntk"); // Neutral Kyle lukeFlag = qfalse; + } else { + strcpy(value, "ntl"); // Netural Luke } - else - { - strcpy(value,"ntl"); // Netural Luke - } - } - else if (percent > 0.10f ) - { + } else if (percent > 0.10f) { index = FW_SEMI_DARK; - if ( who<50 ) - { - strcpy(value,"sdk"); // Semi-dark Kyle + if (who < 50) { + strcpy(value, "sdk"); // Semi-dark Kyle lukeFlag = qfalse; + } else { + strcpy(value, "sdl"); // Semi-Dark Luke } - else - { - strcpy(value,"sdl"); // Semi-Dark Luke - } - } - else - { + } else { index = FW_VERY_DARK; - if ( who<50 ) - { - strcpy(value,"vdk"); // Very dark Kyle + if (who < 50) { + strcpy(value, "vdk"); // Very dark Kyle lukeFlag = qfalse; - } - else - { - strcpy(value,"vdl"); // Very Dark Luke + } else { + strcpy(value, "vdl"); // Very Dark Luke } } - Cvar_Set("ui_forcestatus", value ); + Cvar_Set("ui_forcestatus", value); - if (lukeFlag) - { - DC->startLocalSound(DC->registerSound(lukeForceStatusSounds[index], qfalse), CHAN_VOICE ); - } - else - { - DC->startLocalSound(DC->registerSound(kyleForceStatusSounds[index], qfalse), CHAN_VOICE ); + if (lukeFlag) { + DC->startLocalSound(DC->registerSound(lukeForceStatusSounds[index], qfalse), CHAN_VOICE); + } else { + DC->startLocalSound(DC->registerSound(kyleForceStatusSounds[index], qfalse), CHAN_VOICE); } } #endif // !JK2_MODE @@ -1745,59 +1400,48 @@ static void UI_CalcForceStatus(void) UI_StopCinematic ================= */ -static void UI_StopCinematic(int handle) -{ - if (handle >= 0) - { +static void UI_StopCinematic(int handle) { + if (handle >= 0) { trap_CIN_StopCinematic(handle); - } - else - { + } else { handle = abs(handle); - if (handle == UI_MAPCINEMATIC) - { + if (handle == UI_MAPCINEMATIC) { // FIXME - BOB do we need this? -// if (uiInfo.mapList[ui_currentMap.integer].cinematic >= 0) -// { -// trap_CIN_StopCinematic(uiInfo.mapList[ui_currentMap.integer].cinematic); -// uiInfo.mapList[ui_currentMap.integer].cinematic = -1; -// } - } - else if (handle == UI_NETMAPCINEMATIC) - { + // if (uiInfo.mapList[ui_currentMap.integer].cinematic >= 0) + // { + // trap_CIN_StopCinematic(uiInfo.mapList[ui_currentMap.integer].cinematic); + // uiInfo.mapList[ui_currentMap.integer].cinematic = -1; + // } + } else if (handle == UI_NETMAPCINEMATIC) { // FIXME - BOB do we need this? -// if (uiInfo.serverStatus.currentServerCinematic >= 0) -// { -// trap_CIN_StopCinematic(uiInfo.serverStatus.currentServerCinematic); -// uiInfo.serverStatus.currentServerCinematic = -1; -// } - } - else if (handle == UI_CLANCINEMATIC) - { + // if (uiInfo.serverStatus.currentServerCinematic >= 0) + // { + // trap_CIN_StopCinematic(uiInfo.serverStatus.currentServerCinematic); + // uiInfo.serverStatus.currentServerCinematic = -1; + // } + } else if (handle == UI_CLANCINEMATIC) { // FIXME - BOB do we need this? -// int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); -// if (i >= 0 && i < uiInfo.teamCount) -// { -// if (uiInfo.teamList[i].cinematic >= 0) -// { -// trap_CIN_StopCinematic(uiInfo.teamList[i].cinematic); -// uiInfo.teamList[i].cinematic = -1; -// } -// } + // int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); + // if (i >= 0 && i < uiInfo.teamCount) + // { + // if (uiInfo.teamList[i].cinematic >= 0) + // { + // trap_CIN_StopCinematic(uiInfo.teamList[i].cinematic); + // uiInfo.teamList[i].cinematic = -1; + // } + // } } } } -static void UI_HandleLoadSelection() -{ - Cvar_Set("ui_SelectionOK", va("%d",(s_savegame.currentLine < s_savegame.saveFileCnt)) ); +static void UI_HandleLoadSelection() { + Cvar_Set("ui_SelectionOK", va("%d", (s_savegame.currentLine < s_savegame.saveFileCnt))); if (s_savegame.currentLine >= s_savegame.saveFileCnt) return; #ifdef JK2_MODE - Cvar_Set("ui_gameDesc", s_savedata[s_savegame.currentLine].currentSaveFileComments ); // set comment + Cvar_Set("ui_gameDesc", s_savedata[s_savegame.currentLine].currentSaveFileComments); // set comment - if (!ui.SG_GetSaveImage(s_savedata[s_savegame.currentLine].currentSaveFileName, &screenShotBuf)) - { - memset( screenShotBuf,0,(SG_SCR_WIDTH * SG_SCR_HEIGHT * 4)); + if (!ui.SG_GetSaveImage(s_savedata[s_savegame.currentLine].currentSaveFileName, &screenShotBuf)) { + memset(screenShotBuf, 0, (SG_SCR_WIDTH * SG_SCR_HEIGHT * 4)); } #endif } @@ -1807,13 +1451,10 @@ static void UI_HandleLoadSelection() UI_FeederCount ================= */ -static int UI_FeederCount(float feederID) -{ - if (feederID == FEEDER_SAVEGAMES ) - { - if (s_savegame.saveFileCnt == -1) - { - ReadSaveDirectory(); //refresh +static int UI_FeederCount(float feederID) { + if (feederID == FEEDER_SAVEGAMES) { + if (s_savegame.saveFileCnt == -1) { + ReadSaveDirectory(); // refresh UI_HandleLoadSelection(); #ifndef JK2_MODE UI_AdjustSaveGameListBox(s_savegame.currentLine); @@ -1822,50 +1463,31 @@ static int UI_FeederCount(float feederID) return s_savegame.saveFileCnt; } // count number of moves for the current title - else if (feederID == FEEDER_MOVES) - { - int count=0,i; + else if (feederID == FEEDER_MOVES) { + int count = 0, i; - for (i=0;itypeData; - if (modelPtr) - { - if (datapadMoveData[uiInfo.movesTitleIndex][index].anim) - { - ItemParse_model_g2anim_go( item, datapadMoveData[uiInfo.movesTitleIndex][index].anim ); + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { + modelPtr = (modelDef_t *)item->typeData; + if (modelPtr) { + if (datapadMoveData[uiInfo.movesTitleIndex][index].anim) { + ItemParse_model_g2anim_go(item, datapadMoveData[uiInfo.movesTitleIndex][index].anim); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; // Play sound for anim - if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_FORCE_JUMP) - { - DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL ); - } - else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_ROLL) - { - DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveRollSound, CHAN_LOCAL ); - } - else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_SABER) - { + if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_FORCE_JUMP) { + DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL); + } else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_ROLL) { + DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveRollSound, CHAN_LOCAL); + } else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_SABER) { // Randomly choose one sound - int soundI = Q_irand( 1, 6 ); + int soundI = Q_irand(1, 6); sfxHandle_t *soundPtr; soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound1; - if (soundI == 2) - { + if (soundI == 2) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound2; - } - else if (soundI == 3) - { + } else if (soundI == 3) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound3; - } - else if (soundI == 4) - { + } else if (soundI == 4) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound4; - } - else if (soundI == 5) - { + } else if (soundI == 5) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound5; - } - else if (soundI == 6) - { + } else if (soundI == 6) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound6; } - DC->startLocalSound(*soundPtr, CHAN_LOCAL ); + DC->startLocalSound(*soundPtr, CHAN_LOCAL); } - if (datapadMoveData[uiInfo.movesTitleIndex][index].desc) - { - Cvar_Set( "ui_move_desc", datapadMoveData[uiInfo.movesTitleIndex][index].desc); + if (datapadMoveData[uiInfo.movesTitleIndex][index].desc) { + Cvar_Set("ui_move_desc", datapadMoveData[uiInfo.movesTitleIndex][index].desc); } - Com_sprintf( skin, sizeof( skin ), "models/players/%s/|%s|%s|%s", - Cvar_VariableString ( "g_char_model"), - Cvar_VariableString ( "g_char_skin_head"), - Cvar_VariableString ( "g_char_skin_torso"), - Cvar_VariableString ( "g_char_skin_legs") - ); - - ItemParse_model_g2skin_go( item, skin ); + Com_sprintf(skin, sizeof(skin), "models/players/%s/|%s|%s|%s", Cvar_VariableString("g_char_model"), + Cvar_VariableString("g_char_skin_head"), Cvar_VariableString("g_char_skin_torso"), Cvar_VariableString("g_char_skin_legs")); + ItemParse_model_g2skin_go(item, skin); } } } } - } - else if (feederID == FEEDER_MOVES_TITLES) - { + } else if (feederID == FEEDER_MOVES_TITLES) { itemDef_t *item; menuDef_t *menu; modelDef_t *modelPtr; @@ -1976,89 +1568,64 @@ static void UI_FeederSelection(float feederID, int index, itemDef_t *item) uiInfo.movesBaseAnim = datapadMoveTitleBaseAnims[uiInfo.movesTitleIndex]; menu = Menus_FindByName("datapadMovesMenu"); - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { - modelPtr = (modelDef_t*)item->typeData; - if (modelPtr) - { - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { + modelPtr = (modelDef_t *)item->typeData; + if (modelPtr) { + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); } } } - } - else if (feederID == FEEDER_MODS) - { + } else if (feederID == FEEDER_MODS) { uiInfo.modIndex = index; - } - else if (feederID == FEEDER_PLAYER_SPECIES) - { - if (index >= 0 && index < uiInfo.playerSpeciesCount) - { + } else if (feederID == FEEDER_PLAYER_SPECIES) { + if (index >= 0 && index < uiInfo.playerSpeciesCount) { uiInfo.playerSpeciesIndex = index; } - } - else if (feederID == FEEDER_LANGUAGES) - { + } else if (feederID == FEEDER_LANGUAGES) { uiInfo.languageCountIndex = index; - } - else if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name); } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { Cvar_Set("ui_char_skin_torso", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name); } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { Cvar_Set("ui_char_skin_legs", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name); } - } - else if (feederID == FEEDER_COLORCHOICES) - { -extern void Item_RunScript(itemDef_t *item, const char *s); //from ui_shared; - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { + } else if (feederID == FEEDER_COLORCHOICES) { + extern void Item_RunScript(itemDef_t * item, const char *s); // from ui_shared; + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { Item_RunScript(item, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].actionText); } } -/* else if (feederID == FEEDER_CINEMATICS) - { - uiInfo.movieIndex = index; - if (uiInfo.previewMovie >= 0) + /* else if (feederID == FEEDER_CINEMATICS) { - trap_CIN_StopCinematic(uiInfo.previewMovie); + uiInfo.movieIndex = index; + if (uiInfo.previewMovie >= 0) + { + trap_CIN_StopCinematic(uiInfo.previewMovie); + } + uiInfo.previewMovie = -1; } - uiInfo.previewMovie = -1; - } - else if (feederID == FEEDER_DEMOS) - { - uiInfo.demoIndex = index; - } -*/ + else if (feederID == FEEDER_DEMOS) + { + uiInfo.demoIndex = index; + } + */ } -void Key_KeynumToStringBuf( int keynum, char *buf, int buflen ); -void Key_GetBindingBuf( int keynum, char *buf, int buflen ); +void Key_KeynumToStringBuf(int keynum, char *buf, int buflen); +void Key_GetBindingBuf(int keynum, char *buf, int buflen); -static qboolean UI_Crosshair_HandleKey(int flags, float *special, int key) -{ - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { - if (key == A_MOUSE2) - { +static qboolean UI_Crosshair_HandleKey(int flags, float *special, int key) { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { + if (key == A_MOUSE2) { uiInfo.currentCrosshair--; } else { uiInfo.currentCrosshair++; @@ -2075,218 +1642,186 @@ static qboolean UI_Crosshair_HandleKey(int flags, float *special, int key) return qfalse; } +static qboolean UI_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) { -static qboolean UI_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) -{ - - switch (ownerDraw) - { - case UI_CROSSHAIR: - UI_Crosshair_HandleKey(flags, special, key); - break; - default: - break; + switch (ownerDraw) { + case UI_CROSSHAIR: + UI_Crosshair_HandleKey(flags, special, key); + break; + default: + break; } - return qfalse; + return qfalse; } -//unfortunately we cannot rely on any game/cgame module code to do our animation stuff, -//because the ui can be loaded while the game/cgame are not loaded. So we're going to recreate what we need here. +// unfortunately we cannot rely on any game/cgame module code to do our animation stuff, +// because the ui can be loaded while the game/cgame are not loaded. So we're going to recreate what we need here. #undef MAX_ANIM_FILES #define MAX_ANIM_FILES 4 -class ui_animFileSet_t -{ -public: - char filename[MAX_QPATH]; - animation_t animations[MAX_ANIMATIONS]; +class ui_animFileSet_t { + public: + char filename[MAX_QPATH]; + animation_t animations[MAX_ANIMATIONS]; }; // ui_animFileSet_t -static ui_animFileSet_t ui_knownAnimFileSets[MAX_ANIM_FILES]; +static ui_animFileSet_t ui_knownAnimFileSets[MAX_ANIM_FILES]; -int ui_numKnownAnimFileSets; +int ui_numKnownAnimFileSets; -qboolean UI_ParseAnimationFile( const char *af_filename ) -{ - const char *text_p; - int len; - int i; - const char *token; - float fps; - char text[80000]; - int animNum; - animation_t *animations = ui_knownAnimFileSets[ui_numKnownAnimFileSets].animations; +qboolean UI_ParseAnimationFile(const char *af_filename) { + const char *text_p; + int len; + int i; + const char *token; + float fps; + char text[80000]; + int animNum; + animation_t *animations = ui_knownAnimFileSets[ui_numKnownAnimFileSets].animations; len = re.GetAnimationCFG(af_filename, text, sizeof(text)); - if ( len <= 0 ) - { + if (len <= 0) { return qfalse; } - if ( len >= (int)(sizeof( text ) - 1) ) - { - Com_Error( ERR_FATAL, "UI_ParseAnimationFile: File %s too long\n (%d > %d)", af_filename, len, sizeof( text ) - 1); + if (len >= (int)(sizeof(text) - 1)) { + Com_Error(ERR_FATAL, "UI_ParseAnimationFile: File %s too long\n (%d > %d)", af_filename, len, sizeof(text) - 1); return qfalse; } // parse the text text_p = text; - //FIXME: have some way of playing anims backwards... negative numFrames? + // FIXME: have some way of playing anims backwards... negative numFrames? - //initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 - for(i = 0; i < MAX_ANIMATIONS; i++) - { + // initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 + for (i = 0; i < MAX_ANIMATIONS; i++) { animations[i].firstFrame = 0; animations[i].numFrames = 0; animations[i].loopFrames = -1; animations[i].frameLerp = 100; -// animations[i].initialLerp = 100; + // animations[i].initialLerp = 100; } // read information for each frame COM_BeginParseSession(); - while(1) - { - token = COM_Parse( &text_p ); + while (1) { + token = COM_Parse(&text_p); - if ( !token || !token[0]) - { + if (!token || !token[0]) { break; } animNum = GetIDForString(animTable, token); - if(animNum == -1) - { + if (animNum == -1) { //#ifndef FINAL_BUILD #ifdef _DEBUG - if (strcmp(token,"ROOT")) - { - Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, af_filename); + if (strcmp(token, "ROOT")) { + Com_Printf(S_COLOR_RED "WARNING: Unknown token %s in %s\n", token, af_filename); } #endif - while (token[0]) - { - token = COM_ParseExt( &text_p, qfalse ); //returns empty string when next token is EOL + while (token[0]) { + token = COM_ParseExt(&text_p, qfalse); // returns empty string when next token is EOL } continue; } - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].firstFrame = atoi( token ); + animations[animNum].firstFrame = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].numFrames = atoi( token ); + animations[animNum].numFrames = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].loopFrames = atoi( token ); + animations[animNum].loopFrames = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - fps = atof( token ); - if ( fps == 0 ) - { - fps = 1;//Don't allow divide by zero error + fps = atof(token); + if (fps == 0) { + fps = 1; // Don't allow divide by zero error } - if ( fps < 0 ) - {//backwards + if (fps < 0) { // backwards animations[animNum].frameLerp = floor(1000.0f / fps); - } - else - { + } else { animations[animNum].frameLerp = ceil(1000.0f / fps); } -// animations[animNum].initialLerp = ceil(1000.0f / fabs(fps)); + // animations[animNum].initialLerp = ceil(1000.0f / fabs(fps)); } COM_EndParseSession(); return qtrue; } -qboolean UI_ParseAnimFileSet( const char *animCFG, int *animFileIndex ) -{ //Not going to bother parsing the sound config here. - char afilename[MAX_QPATH]; - char strippedName[MAX_QPATH]; - int i; - char *slash; +qboolean UI_ParseAnimFileSet(const char *animCFG, int *animFileIndex) { // Not going to bother parsing the sound config here. + char afilename[MAX_QPATH]; + char strippedName[MAX_QPATH]; + int i; + char *slash; - Q_strncpyz( strippedName, animCFG, sizeof(strippedName)); - slash = strrchr( strippedName, '/' ); - if ( slash ) - { + Q_strncpyz(strippedName, animCFG, sizeof(strippedName)); + slash = strrchr(strippedName, '/'); + if (slash) { // truncate modelName to find just the dir not the extension *slash = 0; } - //if this anims file was loaded before, don't parse it again, just point to the correct table of info - for ( i = 0; i < ui_numKnownAnimFileSets; i++ ) - { - if ( Q_stricmp(ui_knownAnimFileSets[i].filename, strippedName ) == 0 ) - { + // if this anims file was loaded before, don't parse it again, just point to the correct table of info + for (i = 0; i < ui_numKnownAnimFileSets; i++) { + if (Q_stricmp(ui_knownAnimFileSets[i].filename, strippedName) == 0) { *animFileIndex = i; return qtrue; } } - if ( ui_numKnownAnimFileSets == MAX_ANIM_FILES ) - {//TOO MANY! - for (i = 0; i < MAX_ANIM_FILES; i++) - { + if (ui_numKnownAnimFileSets == MAX_ANIM_FILES) { // TOO MANY! + for (i = 0; i < MAX_ANIM_FILES; i++) { Com_Printf("animfile[%d]: %s\n", i, ui_knownAnimFileSets[i].filename); } - Com_Error( ERR_FATAL, "UI_ParseAnimFileSet: %d == MAX_ANIM_FILES == %d", ui_numKnownAnimFileSets, MAX_ANIM_FILES); + Com_Error(ERR_FATAL, "UI_ParseAnimFileSet: %d == MAX_ANIM_FILES == %d", ui_numKnownAnimFileSets, MAX_ANIM_FILES); } - //Okay, time to parse in a new one - Q_strncpyz( ui_knownAnimFileSets[ui_numKnownAnimFileSets].filename, strippedName, sizeof( ui_knownAnimFileSets[ui_numKnownAnimFileSets].filename ) ); + // Okay, time to parse in a new one + Q_strncpyz(ui_knownAnimFileSets[ui_numKnownAnimFileSets].filename, strippedName, sizeof(ui_knownAnimFileSets[ui_numKnownAnimFileSets].filename)); // Load and parse animations.cfg file - Com_sprintf( afilename, sizeof( afilename ), "%s/animation.cfg", strippedName ); - if ( !UI_ParseAnimationFile( afilename ) ) - { + Com_sprintf(afilename, sizeof(afilename), "%s/animation.cfg", strippedName); + if (!UI_ParseAnimationFile(afilename)) { *animFileIndex = -1; return qfalse; } - //set index and increment + // set index and increment *animFileIndex = ui_numKnownAnimFileSets++; return qtrue; } -int UI_G2SetAnim(CGhoul2Info *ghlInfo, const char *boneName, int animNum, const qboolean freeze) -{ - int animIndex,blendTime; +int UI_G2SetAnim(CGhoul2Info *ghlInfo, const char *boneName, int animNum, const qboolean freeze) { + int animIndex, blendTime; char *GLAName; GLAName = re.G2API_GetGLAName(ghlInfo); - if (!GLAName || !GLAName[0]) - { + if (!GLAName || !GLAName[0]) { return 0; } UI_ParseAnimFileSet(GLAName, &animIndex); - if (animIndex != -1) - { + if (animIndex != -1) { animation_t *anim = &ui_knownAnimFileSets[animIndex].animations[animNum]; - if (anim->numFrames <= 0) - { + if (anim->numFrames <= 0) { return 0; } int sFrame = anim->firstFrame; @@ -2298,37 +1833,29 @@ int UI_G2SetAnim(CGhoul2Info *ghlInfo, const char *boneName, int animNum, const blendTime = 150; // Freeze anim if it's not looping, special hack for datapad moves menu - if (freeze) - { - if (anim->loopFrames == -1) - { + if (freeze) { + if (anim->loopFrames == -1) { flags = BONE_ANIM_OVERRIDE_FREEZE; - } - else - { + } else { flags = BONE_ANIM_OVERRIDE_LOOP; } - } - else if (anim->loopFrames != -1) - { + } else if (anim->loopFrames != -1) { flags = BONE_ANIM_OVERRIDE_LOOP; } flags |= BONE_ANIM_BLEND; blendTime = 150; - re.G2API_SetBoneAnim(ghlInfo, boneName, sFrame, eFrame, flags, animSpeed, time, -1, blendTime); - return ((anim->frameLerp * (anim->numFrames-2))); + return ((anim->frameLerp * (anim->numFrames - 2))); } return 0; } -static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t &species) -{ - const char *token; - const char *p; +static qboolean UI_ParseColorData(char *buf, playerSpeciesInfo_t &species) { + const char *token; + const char *p; p = buf; COM_BeginParseSession(); @@ -2336,48 +1863,42 @@ static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t &species) species.ColorMax = 16; species.Color = (playerColor_t *)malloc(species.ColorMax * sizeof(playerColor_t)); - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); //looking for the shader - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); // looking for the shader + if (token[0] == 0) { + COM_EndParseSession(); return (qboolean)(species.ColorCount != 0); } - if (species.ColorCount >= species.ColorMax) - { + if (species.ColorCount >= species.ColorMax) { species.ColorMax *= 2; species.Color = (playerColor_t *)realloc(species.Color, species.ColorMax * sizeof(playerColor_t)); } memset(&species.Color[species.ColorCount], 0, sizeof(playerColor_t)); - Q_strncpyz( species.Color[species.ColorCount].shader, token, MAX_QPATH ); + Q_strncpyz(species.Color[species.ColorCount].shader, token, MAX_QPATH); - token = COM_ParseExt( &p, qtrue ); //looking for action block { - if ( token[0] != '{' ) - { - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); // looking for action block { + if (token[0] != '{') { + COM_EndParseSession(); return qfalse; } - token = COM_ParseExt( &p, qtrue ); //looking for action commands - while (token[0] != '}') - { - if ( token[0] == 0) - { //EOF - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); // looking for action commands + while (token[0] != '}') { + if (token[0] == 0) { // EOF + COM_EndParseSession(); return qfalse; } Q_strcat(species.Color[species.ColorCount].actionText, ACTION_BUFFER_SIZE, token); Q_strcat(species.Color[species.ColorCount].actionText, ACTION_BUFFER_SIZE, " "); - token = COM_ParseExt( &p, qtrue ); //looking for action commands or final } + token = COM_ParseExt(&p, qtrue); // looking for action commands or final } } - species.ColorCount++; //next color please + species.ColorCount++; // next color please } - COM_EndParseSession( ); - return qtrue;//never get here + COM_EndParseSession(); + return qtrue; // never get here } /* @@ -2386,36 +1907,31 @@ bIsImageFile builds path and scans for valid image extentions ================= */ -static qboolean IsImageFile(const char* dirptr, const char* skinname, qboolean building) -{ +static qboolean IsImageFile(const char *dirptr, const char *skinname, qboolean building) { char fpath[MAX_QPATH]; int f; - Com_sprintf(fpath, MAX_QPATH, "models/players/%s/icon_%s.jpg", dirptr, skinname); ui.FS_FOpenFile(fpath, &f, FS_READ); - if (!f) - { //not there, try png + if (!f) { // not there, try png Com_sprintf(fpath, MAX_QPATH, "models/players/%s/icon_%s.png", dirptr, skinname); ui.FS_FOpenFile(fpath, &f, FS_READ); } - if (!f) - { //not there, try tga + if (!f) { // not there, try tga Com_sprintf(fpath, MAX_QPATH, "models/players/%s/icon_%s.tga", dirptr, skinname); ui.FS_FOpenFile(fpath, &f, FS_READ); } - if (f) - { + if (f) { ui.FS_FCloseFile(f); - if ( building ) ui.R_RegisterShaderNoMip(fpath); + if (building) + ui.R_RegisterShaderNoMip(fpath); return qtrue; } return qfalse; } -static void UI_FreeSpecies( playerSpeciesInfo_t *species ) -{ +static void UI_FreeSpecies(playerSpeciesInfo_t *species) { free(species->SkinHead); free(species->SkinTorso); free(species->SkinLeg); @@ -2423,16 +1939,14 @@ static void UI_FreeSpecies( playerSpeciesInfo_t *species ) memset(species, 0, sizeof(playerSpeciesInfo_t)); } -void UI_FreeAllSpecies( void ) -{ +void UI_FreeAllSpecies(void) { int i; - for (i = 0; i < uiInfo.playerSpeciesCount; i++) - { + for (i = 0; i < uiInfo.playerSpeciesCount; i++) { UI_FreeSpecies(&uiInfo.playerSpecies[i]); } free(uiInfo.playerSpecies); - + uiInfo.playerSpeciesCount = 0; uiInfo.playerSpecies = NULL; } @@ -2442,25 +1956,23 @@ void UI_FreeAllSpecies( void ) PlayerModel_BuildList ================= */ -static void UI_BuildPlayerModel_List( qboolean inGameLoad ) -{ +static void UI_BuildPlayerModel_List(qboolean inGameLoad) { static const size_t DIR_LIST_SIZE = 16384; - int numdirs; - size_t dirListSize = DIR_LIST_SIZE; - char stackDirList[8192]; - char *dirlist; - char* dirptr; - int dirlen; - int i; + int numdirs; + size_t dirListSize = DIR_LIST_SIZE; + char stackDirList[8192]; + char *dirlist; + char *dirptr; + int dirlen; + int i; const int building = Cvar_VariableIntegerValue("com_buildscript"); dirlist = (char *)malloc(DIR_LIST_SIZE); - if ( !dirlist ) - { + if (!dirlist) { Com_Printf(S_COLOR_YELLOW "WARNING: Failed to allocate %u bytes of memory for player model " - "directory list. Using stack allocated buffer of %u bytes instead.", - DIR_LIST_SIZE, sizeof(stackDirList)); + "directory list. Using stack allocated buffer of %u bytes instead.", + DIR_LIST_SIZE, sizeof(stackDirList)); dirlist = stackDirList; dirListSize = sizeof(stackDirList); @@ -2472,35 +1984,30 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) uiInfo.playerSpecies = (playerSpeciesInfo_t *)malloc(uiInfo.playerSpeciesMax * sizeof(playerSpeciesInfo_t)); // iterate directory of all player models - numdirs = ui.FS_GetFileList("models/players", "/", dirlist, dirListSize ); - dirptr = dirlist; - for (i=0; i= uiInfo.playerSpeciesMax) - { + // record this species + if (uiInfo.playerSpeciesCount >= uiInfo.playerSpeciesMax) { uiInfo.playerSpeciesMax *= 2; - uiInfo.playerSpecies = (playerSpeciesInfo_t *)realloc(uiInfo.playerSpecies, uiInfo.playerSpeciesMax*sizeof(playerSpeciesInfo_t)); + uiInfo.playerSpecies = (playerSpeciesInfo_t *)realloc(uiInfo.playerSpecies, uiInfo.playerSpeciesMax * sizeof(playerSpeciesInfo_t)); } species = &uiInfo.playerSpecies[uiInfo.playerSpeciesCount]; memset(species, 0, sizeof(playerSpeciesInfo_t)); - Q_strncpyz( species->Name, dirptr, MAX_QPATH ); + Q_strncpyz(species->Name, dirptr, MAX_QPATH); - if (!UI_ParseColorData(buffer.data(),*species)) - { - ui.Printf( "UI_BuildPlayerModel_List: Errors parsing '%s'\n", fpath ); + if (!UI_ParseColorData(buffer.data(), *species)) { + ui.Printf("UI_BuildPlayerModel_List: Errors parsing '%s'\n", fpath); } species->SkinHeadMax = 8; @@ -2533,84 +2038,71 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) species->SkinTorso = (skinName_t *)malloc(species->SkinTorsoMax * sizeof(skinName_t)); species->SkinLeg = (skinName_t *)malloc(species->SkinLegMax * sizeof(skinName_t)); - int j; - char skinname[64]; - int numfiles; - int iSkinParts=0; - - numfiles = ui.FS_GetFileList( va("models/players/%s",dirptr), ".skin", filelist, sizeof(filelist) ); - fileptr = filelist; - for (j=0; jSkinHeadCount >= species->SkinHeadMax) - { + if (IsImageFile(dirptr, skinname, (qboolean)(building != 0))) { // if it exists + if (Q_stricmpn(skinname, "head_", 5) == 0) { + if (species->SkinHeadCount >= species->SkinHeadMax) { species->SkinHeadMax *= 2; - species->SkinHead = (skinName_t *)realloc(species->SkinHead, species->SkinHeadMax*sizeof(skinName_t)); + species->SkinHead = (skinName_t *)realloc(species->SkinHead, species->SkinHeadMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinHead[species->SkinHeadCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<0; - } else - if (Q_stricmpn(skinname,"torso_",6) == 0) - { - if (species->SkinTorsoCount >= species->SkinTorsoMax) - { + iSkinParts |= 1 << 0; + } else if (Q_stricmpn(skinname, "torso_", 6) == 0) { + if (species->SkinTorsoCount >= species->SkinTorsoMax) { species->SkinTorsoMax *= 2; - species->SkinTorso = (skinName_t *)realloc(species->SkinTorso, species->SkinTorsoMax*sizeof(skinName_t)); + species->SkinTorso = (skinName_t *)realloc(species->SkinTorso, species->SkinTorsoMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinTorso[species->SkinTorsoCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<1; - } else - if (Q_stricmpn(skinname,"lower_",6) == 0) - { - if (species->SkinLegCount >= species->SkinLegMax) - { + iSkinParts |= 1 << 1; + } else if (Q_stricmpn(skinname, "lower_", 6) == 0) { + if (species->SkinLegCount >= species->SkinLegMax) { species->SkinLegMax *= 2; - species->SkinLeg = (skinName_t *)realloc(species->SkinLeg, species->SkinLegMax*sizeof(skinName_t)); + species->SkinLeg = (skinName_t *)realloc(species->SkinLeg, species->SkinLegMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinLeg[species->SkinLegCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<2; + iSkinParts |= 1 << 2; } - } } - if (iSkinParts != 7) - { //didn't get a skin for each, then skip this model. + if (iSkinParts != 7) { // didn't get a skin for each, then skip this model. UI_FreeSpecies(species); continue; } uiInfo.playerSpeciesCount++; - if (!inGameLoad && ui_PrecacheModels.integer) - { + if (!inGameLoad && ui_PrecacheModels.integer) { CGhoul2Info_v ghoul2; - Com_sprintf( fpath, sizeof( fpath ), "models/players/%s/model.glm", dirptr ); + Com_sprintf(fpath, sizeof(fpath), "models/players/%s/model.glm", dirptr); int g2Model = DC->g2_InitGhoul2Model(ghoul2, fpath, 0, 0, 0, 0, 0); - if (g2Model >= 0) - { - DC->g2_RemoveGhoul2Model( ghoul2, 0 ); + if (g2Model >= 0) { + DC->g2_RemoveGhoul2Model(ghoul2, 0); } } } } - if ( dirlist != stackDirList ) - { + if (dirlist != stackDirList) { free(dirlist); } } @@ -2620,27 +2112,22 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) UI_Shutdown ================= */ -void UI_Shutdown( void ) -{ - UI_FreeAllSpecies(); -} +void UI_Shutdown(void) { UI_FreeAllSpecies(); } /* ================= UI_Init ================= */ -void _UI_Init( qboolean inGameLoad ) -{ +void _UI_Init(qboolean inGameLoad) { // Get the list of possible languages #ifndef JK2_MODE - uiInfo.languageCount = SE_GetNumLanguages(); // this does a dir scan, so use carefully + uiInfo.languageCount = SE_GetNumLanguages(); // this does a dir scan, so use carefully #else // sod it, parse every menu strip file until we find a gap in the sequence... // - for (int i=0; i<10; i++) - { - if (!ui.SP_Register(va("menus%d",i), /*SP_REGISTER_REQUIRED|*/SP_REGISTER_MENU)) + for (int i = 0; i < 10; i++) { + if (!ui.SP_Register(va("menus%d", i), /*SP_REGISTER_REQUIRED|*/ SP_REGISTER_MENU)) break; } #endif @@ -2652,65 +2139,62 @@ void _UI_Init( qboolean inGameLoad ) UI_InitMemory(); // cache redundant calulations - trap_GetGlconfig( &uiInfo.uiDC.glconfig ); + trap_GetGlconfig(&uiInfo.uiDC.glconfig); // for 640x480 virtualized screen - uiInfo.uiDC.yscale = uiInfo.uiDC.glconfig.vidHeight * (1.0/480.0); - uiInfo.uiDC.xscale = uiInfo.uiDC.glconfig.vidWidth * (1.0/640.0); - if ( uiInfo.uiDC.glconfig.vidWidth * 480 > uiInfo.uiDC.glconfig.vidHeight * 640 ) - { + uiInfo.uiDC.yscale = uiInfo.uiDC.glconfig.vidHeight * (1.0 / 480.0); + uiInfo.uiDC.xscale = uiInfo.uiDC.glconfig.vidWidth * (1.0 / 640.0); + if (uiInfo.uiDC.glconfig.vidWidth * 480 > uiInfo.uiDC.glconfig.vidHeight * 640) { // wide screen - uiInfo.uiDC.bias = 0.5 * ( uiInfo.uiDC.glconfig.vidWidth - ( uiInfo.uiDC.glconfig.vidHeight * (640.0/480.0) ) ); - } - else - { + uiInfo.uiDC.bias = 0.5 * (uiInfo.uiDC.glconfig.vidWidth - (uiInfo.uiDC.glconfig.vidHeight * (640.0 / 480.0))); + } else { // no wide screen uiInfo.uiDC.bias = 0; } Init_Display(&uiInfo.uiDC); - uiInfo.uiDC.drawText = &Text_Paint; - uiInfo.uiDC.drawHandlePic = &UI_DrawHandlePic; - uiInfo.uiDC.drawRect = &_UI_DrawRect; - uiInfo.uiDC.drawSides = &_UI_DrawSides; - uiInfo.uiDC.drawTextWithCursor = &Text_PaintWithCursor; - uiInfo.uiDC.executeText = &Cbuf_ExecuteText; - uiInfo.uiDC.drawTopBottom = &_UI_DrawTopBottom; - uiInfo.uiDC.feederCount = &UI_FeederCount; - uiInfo.uiDC.feederSelection = &UI_FeederSelection; - uiInfo.uiDC.fillRect = &UI_FillRect; - uiInfo.uiDC.getBindingBuf = &Key_GetBindingBuf; - uiInfo.uiDC.getCVarString = Cvar_VariableStringBuffer; - uiInfo.uiDC.getCVarValue = trap_Cvar_VariableValue; - uiInfo.uiDC.getOverstrikeMode = &trap_Key_GetOverstrikeMode; - uiInfo.uiDC.getValue = &UI_GetValue; - uiInfo.uiDC.keynumToStringBuf = &Key_KeynumToStringBuf; - uiInfo.uiDC.modelBounds = &trap_R_ModelBounds; - uiInfo.uiDC.ownerDrawVisible = &UI_OwnerDrawVisible; - uiInfo.uiDC.ownerDrawWidth = &UI_OwnerDrawWidth; - uiInfo.uiDC.ownerDrawItem = &UI_OwnerDraw; - uiInfo.uiDC.Print = &Com_Printf; - uiInfo.uiDC.registerSound = &trap_S_RegisterSound; - uiInfo.uiDC.registerModel = ui.R_RegisterModel; - uiInfo.uiDC.clearScene = &trap_R_ClearScene; + uiInfo.uiDC.drawText = &Text_Paint; + uiInfo.uiDC.drawHandlePic = &UI_DrawHandlePic; + uiInfo.uiDC.drawRect = &_UI_DrawRect; + uiInfo.uiDC.drawSides = &_UI_DrawSides; + uiInfo.uiDC.drawTextWithCursor = &Text_PaintWithCursor; + uiInfo.uiDC.executeText = &Cbuf_ExecuteText; + uiInfo.uiDC.drawTopBottom = &_UI_DrawTopBottom; + uiInfo.uiDC.feederCount = &UI_FeederCount; + uiInfo.uiDC.feederSelection = &UI_FeederSelection; + uiInfo.uiDC.fillRect = &UI_FillRect; + uiInfo.uiDC.getBindingBuf = &Key_GetBindingBuf; + uiInfo.uiDC.getCVarString = Cvar_VariableStringBuffer; + uiInfo.uiDC.getCVarValue = trap_Cvar_VariableValue; + uiInfo.uiDC.getOverstrikeMode = &trap_Key_GetOverstrikeMode; + uiInfo.uiDC.getValue = &UI_GetValue; + uiInfo.uiDC.keynumToStringBuf = &Key_KeynumToStringBuf; + uiInfo.uiDC.modelBounds = &trap_R_ModelBounds; + uiInfo.uiDC.ownerDrawVisible = &UI_OwnerDrawVisible; + uiInfo.uiDC.ownerDrawWidth = &UI_OwnerDrawWidth; + uiInfo.uiDC.ownerDrawItem = &UI_OwnerDraw; + uiInfo.uiDC.Print = &Com_Printf; + uiInfo.uiDC.registerSound = &trap_S_RegisterSound; + uiInfo.uiDC.registerModel = ui.R_RegisterModel; + uiInfo.uiDC.clearScene = &trap_R_ClearScene; uiInfo.uiDC.addRefEntityToScene = &trap_R_AddRefEntityToScene; - uiInfo.uiDC.renderScene = &trap_R_RenderScene; - uiInfo.uiDC.runScript = &UI_RunMenuScript; - uiInfo.uiDC.deferScript = &UI_DeferMenuScript; - uiInfo.uiDC.setBinding = &trap_Key_SetBinding; - uiInfo.uiDC.setColor = &UI_SetColor; - uiInfo.uiDC.setCVar = Cvar_Set; - uiInfo.uiDC.setOverstrikeMode = &trap_Key_SetOverstrikeMode; - uiInfo.uiDC.startLocalSound = &trap_S_StartLocalSound; - uiInfo.uiDC.stopCinematic = &UI_StopCinematic; - uiInfo.uiDC.textHeight = &Text_Height; - uiInfo.uiDC.textWidth = &Text_Width; - uiInfo.uiDC.feederItemImage = &UI_FeederItemImage; - uiInfo.uiDC.feederItemText = &UI_FeederItemText; - uiInfo.uiDC.ownerDrawHandleKey = &UI_OwnerDrawHandleKey; - - uiInfo.uiDC.registerSkin = re.RegisterSkin; + uiInfo.uiDC.renderScene = &trap_R_RenderScene; + uiInfo.uiDC.runScript = &UI_RunMenuScript; + uiInfo.uiDC.deferScript = &UI_DeferMenuScript; + uiInfo.uiDC.setBinding = &trap_Key_SetBinding; + uiInfo.uiDC.setColor = &UI_SetColor; + uiInfo.uiDC.setCVar = Cvar_Set; + uiInfo.uiDC.setOverstrikeMode = &trap_Key_SetOverstrikeMode; + uiInfo.uiDC.startLocalSound = &trap_S_StartLocalSound; + uiInfo.uiDC.stopCinematic = &UI_StopCinematic; + uiInfo.uiDC.textHeight = &Text_Height; + uiInfo.uiDC.textWidth = &Text_Width; + uiInfo.uiDC.feederItemImage = &UI_FeederItemImage; + uiInfo.uiDC.feederItemText = &UI_FeederItemText; + uiInfo.uiDC.ownerDrawHandleKey = &UI_OwnerDrawHandleKey; + + uiInfo.uiDC.registerSkin = re.RegisterSkin; uiInfo.uiDC.g2_SetSkin = re.G2API_SetSkin; uiInfo.uiDC.g2_SetBoneAnim = re.G2API_SetBoneAnim; @@ -2729,17 +2213,14 @@ void _UI_Init( qboolean inGameLoad ) const char *menuSet = UI_Cvar_VariableString("ui_menuFiles"); - if (menuSet == NULL || menuSet[0] == '\0') - { + if (menuSet == NULL || menuSet[0] == '\0') { menuSet = "ui/menus.txt"; } #ifndef JK2_MODE - if (inGameLoad) - { + if (inGameLoad) { UI_LoadMenus("ui/ingame.txt", qtrue); - } - else + } else #endif { UI_LoadMenus(menuSet, qtrue); @@ -2747,24 +2228,23 @@ void _UI_Init( qboolean inGameLoad ) Menus_CloseAll(); - uiInfo.uiDC.whiteShader = ui.R_RegisterShaderNoMip( "white" ); + uiInfo.uiDC.whiteShader = ui.R_RegisterShaderNoMip("white"); AssetCache(); uis.debugMode = qfalse; // sets defaults for ui temp cvars - uiInfo.effectsColor = (int)trap_Cvar_VariableValue("color")-1; - if (uiInfo.effectsColor < 0) - { + uiInfo.effectsColor = (int)trap_Cvar_VariableValue("color") - 1; + if (uiInfo.effectsColor < 0) { uiInfo.effectsColor = 0; } uiInfo.effectsColor = gamecodetoui[uiInfo.effectsColor]; uiInfo.currentCrosshair = (int)trap_Cvar_VariableValue("cg_drawCrosshair"); Cvar_Set("ui_mousePitch", (trap_Cvar_VariableValue("m_pitch") >= 0) ? "0" : "1"); - Cvar_Set("cg_endcredits", "0"); // Reset value - Cvar_Set("ui_missionfailed","0"); // reset + Cvar_Set("cg_endcredits", "0"); // Reset value + Cvar_Set("ui_missionfailed", "0"); // reset uiInfo.forcePowerUpdated = FP_UPDATED_NONE; uiInfo.selectedWeapon1 = NOWEAPON; @@ -2774,10 +2254,9 @@ void _UI_Init( qboolean inGameLoad ) uiInfo.uiDC.Assets.nullSound = trap_S_RegisterSound("sound/null", qfalse); #ifndef JK2_MODE - //FIXME hack to prevent error in jk2 by disabling + // FIXME hack to prevent error in jk2 by disabling trap_S_RegisterSound("sound/interface/weapon_deselect", qfalse); #endif - } /* @@ -2785,14 +2264,13 @@ void _UI_Init( qboolean inGameLoad ) UI_RegisterCvars ================= */ -static void UI_RegisterCvars( void ) -{ +static void UI_RegisterCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=cvarTable; ivmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); - if ( cv->update ) + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); + if (cv->update) cv->update(); } } @@ -2802,70 +2280,55 @@ static void UI_RegisterCvars( void ) UI_ParseMenu ================= */ -void UI_ParseMenu(const char *menuFile) -{ - char *buffer,*holdBuffer,*token2; +void UI_ParseMenu(const char *menuFile) { + char *buffer, *holdBuffer, *token2; int len; -// pc_token_t token; + // pc_token_t token; - //Com_DPrintf("Parsing menu file: %s\n", menuFile); - len = PC_StartParseSession(menuFile,&buffer); + // Com_DPrintf("Parsing menu file: %s\n", menuFile); + len = PC_StartParseSession(menuFile, &buffer); holdBuffer = buffer; - if (len<=0) - { + if (len <= 0) { Com_Printf("UI_ParseMenu: Unable to load menu %s\n", menuFile); return; } - while ( 1 ) - { + while (1) { token2 = PC_ParseExt(); - if (!*token2) - { - break; - } -/* - if ( menuCount == MAX_MENUS ) - { - PC_ParseWarning("Too many menus!"); + if (!*token2) { break; } -*/ - if ( *token2 == '{') - { + /* + if ( menuCount == MAX_MENUS ) + { + PC_ParseWarning("Too many menus!"); + break; + } + */ + if (*token2 == '{') { continue; - } - else if ( *token2 == '}' ) - { + } else if (*token2 == '}') { break; - } - else if (Q_stricmp(token2, "assetGlobalDef") == 0) - { - if (Asset_Parse(&holdBuffer)) - { + } else if (Q_stricmp(token2, "assetGlobalDef") == 0) { + if (Asset_Parse(&holdBuffer)) { continue; - } - else - { + } else { break; } - } - else if (Q_stricmp(token2, "menudef") == 0) - { + } else if (Q_stricmp(token2, "menudef") == 0) { // start a new menu Menu_New(holdBuffer); continue; } - PC_ParseWarning(va("Invalid keyword '%s'",token2)); + PC_ParseWarning(va("Invalid keyword '%s'", token2)); } PC_EndParseSession(buffer); - } /* @@ -2874,42 +2337,35 @@ Load_Menu Load current menu file ================= */ -qboolean Load_Menu(const char **holdBuffer) -{ - const char *token2; +qboolean Load_Menu(const char **holdBuffer) { + const char *token2; - token2 = COM_ParseExt( holdBuffer, qtrue ); + token2 = COM_ParseExt(holdBuffer, qtrue); - if (!token2[0]) - { + if (!token2[0]) { return qfalse; } - if (*token2 != '{') - { + if (*token2 != '{') { return qfalse; } - while ( 1 ) - { - token2 = COM_ParseExt( holdBuffer, qtrue ); + while (1) { + token2 = COM_ParseExt(holdBuffer, qtrue); - if ((!token2) || (token2 == 0)) - { + if ((!token2) || (token2 == 0)) { return qfalse; } - if ( *token2 == '}' ) - { + if (*token2 == '}') { return qtrue; } -//#ifdef _DEBUG -// extern void UI_Debug_AddMenuFilePath(const char *); -// UI_Debug_AddMenuFilePath(token2); -//#endif + //#ifdef _DEBUG + // extern void UI_Debug_AddMenuFilePath(const char *); + // UI_Debug_AddMenuFilePath(token2); + //#endif UI_ParseMenu(token2); - } return qfalse; } @@ -2920,10 +2376,9 @@ UI_LoadMenus Load all menus based on the files listed in the data file in menuFile (default "ui/menus.txt") ================= */ -void UI_LoadMenus(const char *menuFile, qboolean reset) -{ -// pc_token_t token; -// int handle; +void UI_LoadMenus(const char *menuFile, qboolean reset) { + // pc_token_t token; + // int handle; int start; char *buffer; @@ -2932,58 +2387,45 @@ void UI_LoadMenus(const char *menuFile, qboolean reset) start = Sys_Milliseconds(); - len = ui.FS_ReadFile(menuFile,(void **) &buffer); + len = ui.FS_ReadFile(menuFile, (void **)&buffer); - if (len<1) - { - Com_Printf( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) ); - len = ui.FS_ReadFile("ui/menus.txt",(void **) &buffer); + if (len < 1) { + Com_Printf(va(S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile)); + len = ui.FS_ReadFile("ui/menus.txt", (void **)&buffer); - if (len<1) - { - Com_Error( ERR_FATAL, "%s", va("default menu file not found: ui/menus.txt, unable to continue!\n", menuFile )); + if (len < 1) { + Com_Error(ERR_FATAL, "%s", va("default menu file not found: ui/menus.txt, unable to continue!\n", menuFile)); return; } } - if (reset) - { + if (reset) { Menu_Reset(); } - const char *token2; + const char *token2; holdBuffer = buffer; COM_BeginParseSession(); - while ( 1 ) - { - token2 = COM_ParseExt( &holdBuffer, qtrue ); - if (!*token2) - { + while (1) { + token2 = COM_ParseExt(&holdBuffer, qtrue); + if (!*token2) { break; } - if( *token2 == 0 || *token2 == '}') // End of the menus file + if (*token2 == 0 || *token2 == '}') // End of the menus file { break; } - if (*token2 == '{') - { - continue; - } - else if (Q_stricmp(token2, "loadmenu") == 0) - { - if (Load_Menu(&holdBuffer)) - { + if (*token2 == '{') { + continue; + } else if (Q_stricmp(token2, "loadmenu") == 0) { + if (Load_Menu(&holdBuffer)) { continue; - } - else - { + } else { break; } - } - else - { + } else { Com_Printf("Unknown keyword '%s' in menus file %s\n", token2, menuFile); } } @@ -2991,7 +2433,7 @@ void UI_LoadMenus(const char *menuFile, qboolean reset) Com_Printf("UI menu load time = %d milli seconds\n", Sys_Milliseconds() - start); - ui.FS_FreeFile( buffer ); //let go of the buffer + ui.FS_FreeFile(buffer); // let go of the buffer } /* @@ -2999,33 +2441,26 @@ void UI_LoadMenus(const char *menuFile, qboolean reset) UI_Load ================= */ -void UI_Load(void) -{ +void UI_Load(void) { const char *menuSet; char lastName[1024]; menuDef_t *menu = Menu_GetFocused(); - if (menu && menu->window.name) - { + if (menu && menu->window.name) { strcpy(lastName, menu->window.name); - } - else - { + } else { lastName[0] = 0; } #ifndef JK2_MODE - if (uiInfo.inGameLoad) - { - menuSet= "ui/ingame.txt"; - } - else + if (uiInfo.inGameLoad) { + menuSet = "ui/ingame.txt"; + } else #endif { - menuSet= UI_Cvar_VariableString("ui_menuFiles"); + menuSet = UI_Cvar_VariableString("ui_menuFiles"); } - if (menuSet == NULL || menuSet[0] == '\0') - { + if (menuSet == NULL || menuSet[0] == '\0') { menuSet = "ui/menus.txt"; } @@ -3041,62 +2476,52 @@ void UI_Load(void) Asset_Parse ================= */ -qboolean Asset_Parse(char **buffer) -{ - char *token; - const char *tempStr; - int pointSize; +qboolean Asset_Parse(char **buffer) { + char *token; + const char *tempStr; + int pointSize; token = PC_ParseExt(); - if (!token) - { + if (!token) { return qfalse; } - if (*token != '{') - { + if (*token != '{') { return qfalse; } - while ( 1 ) - { + while (1) { token = PC_ParseExt(); - if (!token) - { + if (!token) { return qfalse; } - if (*token == '}') - { + if (*token == '}') { return qtrue; } // fonts - if (Q_stricmp(token, "smallFont") == 0) //legacy, really it only matters which order they are registered + if (Q_stricmp(token, "smallFont") == 0) // legacy, really it only matters which order they are registered { - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'smallFont'"); return qfalse; } UI_RegisterFont(tempStr); - //not used anymore - if (PC_ParseInt(&pointSize)) - { -// PC_ParseWarning("Bad 2nd parameter for keyword 'smallFont'"); + // not used anymore + if (PC_ParseInt(&pointSize)) { + // PC_ParseWarning("Bad 2nd parameter for keyword 'smallFont'"); } continue; } - if (Q_stricmp(token, "mediumFont") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "mediumFont") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'font'"); return qfalse; } @@ -3104,52 +2529,44 @@ qboolean Asset_Parse(char **buffer) uiInfo.uiDC.Assets.qhMediumFont = UI_RegisterFont(tempStr); uiInfo.uiDC.Assets.fontRegistered = qtrue; - //not used - if (PC_ParseInt(&pointSize)) - { -// PC_ParseWarning("Bad 2nd parameter for keyword 'font'"); + // not used + if (PC_ParseInt(&pointSize)) { + // PC_ParseWarning("Bad 2nd parameter for keyword 'font'"); } continue; } - if (Q_stricmp(token, "bigFont") == 0) //legacy + if (Q_stricmp(token, "bigFont") == 0) // legacy { - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'bigFont'"); return qfalse; } UI_RegisterFont(tempStr); - if (PC_ParseInt(&pointSize)) - { -// PC_ParseWarning("Bad 2nd parameter for keyword 'bigFont'"); + if (PC_ParseInt(&pointSize)) { + // PC_ParseWarning("Bad 2nd parameter for keyword 'bigFont'"); } continue; } #ifdef JK2_MODE - if (Q_stricmp(token, "stripedFile") == 0) - { - if (!PC_ParseStringMem((const char **) &tempStr)) - { + if (Q_stricmp(token, "stripedFile") == 0) { + if (!PC_ParseStringMem((const char **)&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'stripedFile'"); return qfalse; } char sTemp[1024]; - Q_strncpyz( sTemp, tempStr, sizeof(sTemp) ); - if (!ui.SP_Register(sTemp, /*SP_REGISTER_REQUIRED|*/SP_REGISTER_MENU)) - { - PC_ParseWarning(va("(.SP file \"%s\" not found)",sTemp)); - //return qfalse; // hmmm... dunno about this, don't want to break scripts for just missing subtitles - } - else - { -// extern void AddMenuPackageRetryKey(const char *); -// AddMenuPackageRetryKey(sTemp); + Q_strncpyz(sTemp, tempStr, sizeof(sTemp)); + if (!ui.SP_Register(sTemp, /*SP_REGISTER_REQUIRED|*/ SP_REGISTER_MENU)) { + PC_ParseWarning(va("(.SP file \"%s\" not found)", sTemp)); + // return qfalse; // hmmm... dunno about this, don't want to break scripts for just missing subtitles + } else { + // extern void AddMenuPackageRetryKey(const char *); + // AddMenuPackageRetryKey(sTemp); } continue; @@ -3157,10 +2574,8 @@ qboolean Asset_Parse(char **buffer) #endif // gradientbar - if (Q_stricmp(token, "gradientbar") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "gradientbar") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'gradientbar'"); return qfalse; } @@ -3169,242 +2584,199 @@ qboolean Asset_Parse(char **buffer) } // enterMenuSound - if (Q_stricmp(token, "menuEnterSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "menuEnterSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'menuEnterSound'"); return qfalse; } - uiInfo.uiDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.menuEnterSound = trap_S_RegisterSound(tempStr, qfalse); continue; } // exitMenuSound - if (Q_stricmp(token, "menuExitSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "menuExitSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'menuExitSound'"); return qfalse; } - uiInfo.uiDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.menuExitSound = trap_S_RegisterSound(tempStr, qfalse); continue; } // itemFocusSound - if (Q_stricmp(token, "itemFocusSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "itemFocusSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'itemFocusSound'"); return qfalse; } - uiInfo.uiDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.itemFocusSound = trap_S_RegisterSound(tempStr, qfalse); continue; } // menuBuzzSound - if (Q_stricmp(token, "menuBuzzSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "menuBuzzSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'menuBuzzSound'"); return qfalse; } - uiInfo.uiDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.menuBuzzSound = trap_S_RegisterSound(tempStr, qfalse); continue; } // Chose a force power from the ingame force allocation screen (the one where you get to allocate a force power point) - if (Q_stricmp(token, "forceChosenSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "forceChosenSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'forceChosenSound'"); return qfalse; } - uiInfo.uiDC.Assets.forceChosenSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.forceChosenSound = trap_S_RegisterSound(tempStr, qfalse); continue; } - // Unchose a force power from the ingame force allocation screen (the one where you get to allocate a force power point) - if (Q_stricmp(token, "forceUnchosenSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "forceUnchosenSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'forceUnchosenSound'"); return qfalse; } - uiInfo.uiDC.Assets.forceUnchosenSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.forceUnchosenSound = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveRollSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveRollSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveRollSound'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveRollSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveRollSound = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveJumpSound") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveJumpSound") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveRoll'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveJumpSound = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveJumpSound = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound1") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound1") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound1'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound1 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound1 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound2") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound2") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound2'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound2 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound2 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound3") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound3") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound3'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound3 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound3 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound4") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound4") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound4'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound4 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound4 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound5") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound5") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound5'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound5 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound5 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "datapadmoveSaberSound6") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "datapadmoveSaberSound6") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'datapadmoveSaberSound6'"); return qfalse; } - uiInfo.uiDC.Assets.datapadmoveSaberSound6 = trap_S_RegisterSound( tempStr, qfalse ); + uiInfo.uiDC.Assets.datapadmoveSaberSound6 = trap_S_RegisterSound(tempStr, qfalse); continue; } - if (Q_stricmp(token, "cursor") == 0) - { - if (PC_ParseString(&tempStr)) - { + if (Q_stricmp(token, "cursor") == 0) { + if (PC_ParseString(&tempStr)) { PC_ParseWarning("Bad 1st parameter for keyword 'cursor'"); return qfalse; } - uiInfo.uiDC.Assets.cursor = ui.R_RegisterShaderNoMip( tempStr); + uiInfo.uiDC.Assets.cursor = ui.R_RegisterShaderNoMip(tempStr); continue; } - if (Q_stricmp(token, "fadeClamp") == 0) - { - if (PC_ParseFloat(&uiInfo.uiDC.Assets.fadeClamp)) - { + if (Q_stricmp(token, "fadeClamp") == 0) { + if (PC_ParseFloat(&uiInfo.uiDC.Assets.fadeClamp)) { PC_ParseWarning("Bad 1st parameter for keyword 'fadeClamp'"); return qfalse; } continue; } - if (Q_stricmp(token, "fadeCycle") == 0) - { - if (PC_ParseInt(&uiInfo.uiDC.Assets.fadeCycle)) - { + if (Q_stricmp(token, "fadeCycle") == 0) { + if (PC_ParseInt(&uiInfo.uiDC.Assets.fadeCycle)) { PC_ParseWarning("Bad 1st parameter for keyword 'fadeCycle'"); return qfalse; } continue; } - if (Q_stricmp(token, "fadeAmount") == 0) - { - if (PC_ParseFloat(&uiInfo.uiDC.Assets.fadeAmount)) - { + if (Q_stricmp(token, "fadeAmount") == 0) { + if (PC_ParseFloat(&uiInfo.uiDC.Assets.fadeAmount)) { PC_ParseWarning("Bad 1st parameter for keyword 'fadeAmount'"); return qfalse; } continue; } - if (Q_stricmp(token, "shadowX") == 0) - { - if (PC_ParseFloat(&uiInfo.uiDC.Assets.shadowX)) - { + if (Q_stricmp(token, "shadowX") == 0) { + if (PC_ParseFloat(&uiInfo.uiDC.Assets.shadowX)) { PC_ParseWarning("Bad 1st parameter for keyword 'shadowX'"); return qfalse; } continue; } - if (Q_stricmp(token, "shadowY") == 0) - { - if (PC_ParseFloat(&uiInfo.uiDC.Assets.shadowY)) - { + if (Q_stricmp(token, "shadowY") == 0) { + if (PC_ParseFloat(&uiInfo.uiDC.Assets.shadowY)) { PC_ParseWarning("Bad 1st parameter for keyword 'shadowY'"); return qfalse; } continue; } - if (Q_stricmp(token, "shadowColor") == 0) - { - if (PC_ParseColor(&uiInfo.uiDC.Assets.shadowColor)) - { + if (Q_stricmp(token, "shadowColor") == 0) { + if (PC_ParseColor(&uiInfo.uiDC.Assets.shadowColor)) { PC_ParseWarning("Bad 1st parameter for keyword 'shadowColor'"); return qfalse; } @@ -3413,17 +2785,13 @@ qboolean Asset_Parse(char **buffer) } // precaching various sound files used in the menus - if (Q_stricmp(token, "precacheSound") == 0) - { - if (PC_Script_Parse(&tempStr)) - { + if (Q_stricmp(token, "precacheSound") == 0) { + if (PC_Script_Parse(&tempStr)) { char *soundFile; - do - { + do { soundFile = COM_ParseExt(&tempStr, qfalse); if (soundFile[0] != 0 && soundFile[0] != ';') { - if (!trap_S_RegisterSound( soundFile, qfalse )) - { + if (!trap_S_RegisterSound(soundFile, qfalse)) { PC_ParseWarning("Can't locate precache sound"); } } @@ -3433,7 +2801,7 @@ qboolean Asset_Parse(char **buffer) } } - PC_ParseWarning(va("Invalid keyword '%s'",token)); + PC_ParseWarning(va("Invalid keyword '%s'", token)); return qfalse; } @@ -3442,169 +2810,144 @@ qboolean Asset_Parse(char **buffer) UI_Update ================= */ -static void UI_Update(const char *name) -{ - int val = trap_Cvar_VariableValue(name); +static void UI_Update(const char *name) { + int val = trap_Cvar_VariableValue(name); - - if (Q_stricmp(name, "s_khz") == 0) - { - ui.Cmd_ExecuteText( EXEC_APPEND, "snd_restart\n" ); + if (Q_stricmp(name, "s_khz") == 0) { + ui.Cmd_ExecuteText(EXEC_APPEND, "snd_restart\n"); return; } - if (Q_stricmp(name, "ui_SetName") == 0) - { - Cvar_Set( "name", UI_Cvar_VariableString("ui_Name")); - } - else if (Q_stricmp(name, "ui_GetName") == 0) - { - Cvar_Set( "ui_Name", UI_Cvar_VariableString("name")); - } - else if (Q_stricmp(name, "ui_r_colorbits") == 0) - { - switch (val) - { - case 0: - Cvar_SetValue( "ui_r_depthbits", 0 ); - break; + if (Q_stricmp(name, "ui_SetName") == 0) { + Cvar_Set("name", UI_Cvar_VariableString("ui_Name")); + } else if (Q_stricmp(name, "ui_GetName") == 0) { + Cvar_Set("ui_Name", UI_Cvar_VariableString("name")); + } else if (Q_stricmp(name, "ui_r_colorbits") == 0) { + switch (val) { + case 0: + Cvar_SetValue("ui_r_depthbits", 0); + break; - case 16: - Cvar_SetValue( "ui_r_depthbits", 16 ); - break; + case 16: + Cvar_SetValue("ui_r_depthbits", 16); + break; - case 32: - Cvar_SetValue( "ui_r_depthbits", 24 ); - break; + case 32: + Cvar_SetValue("ui_r_depthbits", 24); + break; } - } - else if (Q_stricmp(name, "ui_r_lodbias") == 0) - { - switch (val) - { - case 0: - Cvar_SetValue( "ui_r_subdivisions", 4 ); - break; - case 1: - Cvar_SetValue( "ui_r_subdivisions", 12 ); - break; + } else if (Q_stricmp(name, "ui_r_lodbias") == 0) { + switch (val) { + case 0: + Cvar_SetValue("ui_r_subdivisions", 4); + break; + case 1: + Cvar_SetValue("ui_r_subdivisions", 12); + break; - case 2: - Cvar_SetValue( "ui_r_subdivisions", 20 ); - break; + case 2: + Cvar_SetValue("ui_r_subdivisions", 20); + break; } - } - else if (Q_stricmp(name, "ui_r_glCustom") == 0) - { - switch (val) - { - case 0: // high quality - - Cvar_SetValue( "ui_r_fullScreen", 1 ); - Cvar_SetValue( "ui_r_subdivisions", 4 ); - Cvar_SetValue( "ui_r_lodbias", 0 ); - Cvar_SetValue( "ui_r_colorbits", 32 ); - Cvar_SetValue( "ui_r_depthbits", 24 ); - Cvar_SetValue( "ui_r_picmip", 0 ); - Cvar_SetValue( "ui_r_mode", 4 ); - Cvar_SetValue( "ui_r_texturebits", 32 ); - Cvar_SetValue( "ui_r_fastSky", 0 ); - Cvar_SetValue( "ui_r_inGameVideo", 1 ); - //Cvar_SetValue( "ui_cg_shadows", 2 );//stencil - Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" ); - break; + } else if (Q_stricmp(name, "ui_r_glCustom") == 0) { + switch (val) { + case 0: // high quality + + Cvar_SetValue("ui_r_fullScreen", 1); + Cvar_SetValue("ui_r_subdivisions", 4); + Cvar_SetValue("ui_r_lodbias", 0); + Cvar_SetValue("ui_r_colorbits", 32); + Cvar_SetValue("ui_r_depthbits", 24); + Cvar_SetValue("ui_r_picmip", 0); + Cvar_SetValue("ui_r_mode", 4); + Cvar_SetValue("ui_r_texturebits", 32); + Cvar_SetValue("ui_r_fastSky", 0); + Cvar_SetValue("ui_r_inGameVideo", 1); + // Cvar_SetValue( "ui_cg_shadows", 2 );//stencil + Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR"); + break; - case 1: // normal - Cvar_SetValue( "ui_r_fullScreen", 1 ); - Cvar_SetValue( "ui_r_subdivisions", 4 ); - Cvar_SetValue( "ui_r_lodbias", 0 ); - Cvar_SetValue( "ui_r_colorbits", 0 ); - Cvar_SetValue( "ui_r_depthbits", 24 ); - Cvar_SetValue( "ui_r_picmip", 1 ); - Cvar_SetValue( "ui_r_mode", 3 ); - Cvar_SetValue( "ui_r_texturebits", 0 ); - Cvar_SetValue( "ui_r_fastSky", 0 ); - Cvar_SetValue( "ui_r_inGameVideo", 1 ); - //Cvar_SetValue( "ui_cg_shadows", 2 ); - Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" ); - break; + case 1: // normal + Cvar_SetValue("ui_r_fullScreen", 1); + Cvar_SetValue("ui_r_subdivisions", 4); + Cvar_SetValue("ui_r_lodbias", 0); + Cvar_SetValue("ui_r_colorbits", 0); + Cvar_SetValue("ui_r_depthbits", 24); + Cvar_SetValue("ui_r_picmip", 1); + Cvar_SetValue("ui_r_mode", 3); + Cvar_SetValue("ui_r_texturebits", 0); + Cvar_SetValue("ui_r_fastSky", 0); + Cvar_SetValue("ui_r_inGameVideo", 1); + // Cvar_SetValue( "ui_cg_shadows", 2 ); + Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR"); + break; - case 2: // fast - - Cvar_SetValue( "ui_r_fullScreen", 1 ); - Cvar_SetValue( "ui_r_subdivisions", 12 ); - Cvar_SetValue( "ui_r_lodbias", 1 ); - Cvar_SetValue( "ui_r_colorbits", 0 ); - Cvar_SetValue( "ui_r_depthbits", 0 ); - Cvar_SetValue( "ui_r_picmip", 2 ); - Cvar_SetValue( "ui_r_mode", 3 ); - Cvar_SetValue( "ui_r_texturebits", 0 ); - Cvar_SetValue( "ui_r_fastSky", 1 ); - Cvar_SetValue( "ui_r_inGameVideo", 0 ); - //Cvar_SetValue( "ui_cg_shadows", 1 ); - Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" ); - break; + case 2: // fast + + Cvar_SetValue("ui_r_fullScreen", 1); + Cvar_SetValue("ui_r_subdivisions", 12); + Cvar_SetValue("ui_r_lodbias", 1); + Cvar_SetValue("ui_r_colorbits", 0); + Cvar_SetValue("ui_r_depthbits", 0); + Cvar_SetValue("ui_r_picmip", 2); + Cvar_SetValue("ui_r_mode", 3); + Cvar_SetValue("ui_r_texturebits", 0); + Cvar_SetValue("ui_r_fastSky", 1); + Cvar_SetValue("ui_r_inGameVideo", 0); + // Cvar_SetValue( "ui_cg_shadows", 1 ); + Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST"); + break; - case 3: // fastest - - Cvar_SetValue( "ui_r_fullScreen", 1 ); - Cvar_SetValue( "ui_r_subdivisions", 20 ); - Cvar_SetValue( "ui_r_lodbias", 2 ); - Cvar_SetValue( "ui_r_colorbits", 16 ); - Cvar_SetValue( "ui_r_depthbits", 16 ); - Cvar_SetValue( "ui_r_mode", 3 ); - Cvar_SetValue( "ui_r_picmip", 3 ); - Cvar_SetValue( "ui_r_texturebits", 16 ); - Cvar_SetValue( "ui_r_fastSky", 1 ); - Cvar_SetValue( "ui_r_inGameVideo", 0 ); - //Cvar_SetValue( "ui_cg_shadows", 0 ); - Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" ); + case 3: // fastest + + Cvar_SetValue("ui_r_fullScreen", 1); + Cvar_SetValue("ui_r_subdivisions", 20); + Cvar_SetValue("ui_r_lodbias", 2); + Cvar_SetValue("ui_r_colorbits", 16); + Cvar_SetValue("ui_r_depthbits", 16); + Cvar_SetValue("ui_r_mode", 3); + Cvar_SetValue("ui_r_picmip", 3); + Cvar_SetValue("ui_r_texturebits", 16); + Cvar_SetValue("ui_r_fastSky", 1); + Cvar_SetValue("ui_r_inGameVideo", 0); + // Cvar_SetValue( "ui_cg_shadows", 0 ); + Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST"); break; } - } - else if (Q_stricmp(name, "ui_mousePitch") == 0) - { - if (val == 0) - { - Cvar_SetValue( "m_pitch", 0.022f ); - } - else - { - Cvar_SetValue( "m_pitch", -0.022f ); + } else if (Q_stricmp(name, "ui_mousePitch") == 0) { + if (val == 0) { + Cvar_SetValue("m_pitch", 0.022f); + } else { + Cvar_SetValue("m_pitch", -0.022f); } - } - else - {//failure!! + } else { // failure!! Com_Printf("unknown UI script UPDATE %s\n", name); } } -#define ASSET_SCROLLBAR "gfx/menus/scrollbar.tga" -#define ASSET_SCROLLBAR_ARROWDOWN "gfx/menus/scrollbar_arrow_dwn_a.tga" -#define ASSET_SCROLLBAR_ARROWUP "gfx/menus/scrollbar_arrow_up_a.tga" -#define ASSET_SCROLLBAR_ARROWLEFT "gfx/menus/scrollbar_arrow_left.tga" -#define ASSET_SCROLLBAR_ARROWRIGHT "gfx/menus/scrollbar_arrow_right.tga" -#define ASSET_SCROLL_THUMB "gfx/menus/scrollbar_thumb.tga" - +#define ASSET_SCROLLBAR "gfx/menus/scrollbar.tga" +#define ASSET_SCROLLBAR_ARROWDOWN "gfx/menus/scrollbar_arrow_dwn_a.tga" +#define ASSET_SCROLLBAR_ARROWUP "gfx/menus/scrollbar_arrow_up_a.tga" +#define ASSET_SCROLLBAR_ARROWLEFT "gfx/menus/scrollbar_arrow_left.tga" +#define ASSET_SCROLLBAR_ARROWRIGHT "gfx/menus/scrollbar_arrow_right.tga" +#define ASSET_SCROLL_THUMB "gfx/menus/scrollbar_thumb.tga" /* ================= AssetCache ================= */ -void AssetCache(void) -{ -// int n; - uiInfo.uiDC.Assets.scrollBar = ui.R_RegisterShaderNoMip( ASSET_SCROLLBAR ); - uiInfo.uiDC.Assets.scrollBarArrowDown = ui.R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWDOWN ); - uiInfo.uiDC.Assets.scrollBarArrowUp = ui.R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWUP ); - uiInfo.uiDC.Assets.scrollBarArrowLeft = ui.R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWLEFT ); - uiInfo.uiDC.Assets.scrollBarArrowRight = ui.R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWRIGHT ); - uiInfo.uiDC.Assets.scrollBarThumb = ui.R_RegisterShaderNoMip( ASSET_SCROLL_THUMB ); - - uiInfo.uiDC.Assets.sliderBar = ui.R_RegisterShaderNoMip( "menu/new/slider" ); - uiInfo.uiDC.Assets.sliderThumb = ui.R_RegisterShaderNoMip( "menu/new/sliderthumb"); - +void AssetCache(void) { + // int n; + uiInfo.uiDC.Assets.scrollBar = ui.R_RegisterShaderNoMip(ASSET_SCROLLBAR); + uiInfo.uiDC.Assets.scrollBarArrowDown = ui.R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWDOWN); + uiInfo.uiDC.Assets.scrollBarArrowUp = ui.R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWUP); + uiInfo.uiDC.Assets.scrollBarArrowLeft = ui.R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWLEFT); + uiInfo.uiDC.Assets.scrollBarArrowRight = ui.R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWRIGHT); + uiInfo.uiDC.Assets.scrollBarThumb = ui.R_RegisterShaderNoMip(ASSET_SCROLL_THUMB); + + uiInfo.uiDC.Assets.sliderBar = ui.R_RegisterShaderNoMip("menu/new/slider"); + uiInfo.uiDC.Assets.sliderThumb = ui.R_RegisterShaderNoMip("menu/new/sliderthumb"); /* for( n = 0; n < NUM_CROSSHAIRS; n++ ) @@ -3619,11 +2962,10 @@ void AssetCache(void) _UI_DrawSides ================= */ -void _UI_DrawSides(float x, float y, float w, float h, float size) -{ +void _UI_DrawSides(float x, float y, float w, float h, float size) { size *= uiInfo.uiDC.xscale; - trap_R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap_R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap_R_DrawStretchPic(x, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap_R_DrawStretchPic(x + w - size, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } /* @@ -3631,11 +2973,10 @@ void _UI_DrawSides(float x, float y, float w, float h, float size) _UI_DrawTopBottom ================= */ -void _UI_DrawTopBottom(float x, float y, float w, float h, float size) -{ +void _UI_DrawTopBottom(float x, float y, float w, float h, float size) { size *= uiInfo.uiDC.yscale; - trap_R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap_R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap_R_DrawStretchPic(x, y, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap_R_DrawStretchPic(x, y + h - size, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } /* ================ @@ -3644,14 +2985,13 @@ UI_DrawRect Coordinates are 640*480 virtual values ================= */ -void _UI_DrawRect( float x, float y, float width, float height, float size, const float *color ) -{ - trap_R_SetColor( color ); +void _UI_DrawRect(float x, float y, float width, float height, float size, const float *color) { + trap_R_SetColor(color); _UI_DrawTopBottom(x, y, width, height, size); _UI_DrawSides(x, y, width, height, size); - trap_R_SetColor( NULL ); + trap_R_SetColor(NULL); } /* @@ -3659,17 +2999,16 @@ void _UI_DrawRect( float x, float y, float width, float height, float size, cons UI_UpdateCvars ================= */ -void UI_UpdateCvars( void ) -{ +void UI_UpdateCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=cvarTable; ivmCvar ) { + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + if (cv->vmCvar) { int modCount = cv->vmCvar->modificationCount; - Cvar_Update( cv->vmCvar ); - if ( cv->vmCvar->modificationCount != modCount ) { - if ( cv->update ) + Cvar_Update(cv->vmCvar); + if (cv->vmCvar->modificationCount != modCount) { + if (cv->update) cv->update(); } } @@ -3681,10 +3020,9 @@ void UI_UpdateCvars( void ) UI_DrawEffects ================= */ -static void UI_DrawEffects(rectDef_t *rect, float scale, vec4_t color) -{ - UI_DrawHandlePic( rect->x, rect->y - 14, 128, 8, 0/*uiInfo.uiDC.Assets.fxBasePic*/ ); - UI_DrawHandlePic( rect->x + uiInfo.effectsColor * 16 + 8, rect->y - 16, 16, 12, 0/*uiInfo.uiDC.Assets.fxPic[uiInfo.effectsColor]*/ ); +static void UI_DrawEffects(rectDef_t *rect, float scale, vec4_t color) { + UI_DrawHandlePic(rect->x, rect->y - 14, 128, 8, 0 /*uiInfo.uiDC.Assets.fxBasePic*/); + UI_DrawHandlePic(rect->x + uiInfo.effectsColor * 16 + 8, rect->y - 16, 16, 12, 0 /*uiInfo.uiDC.Assets.fxPic[uiInfo.effectsColor]*/); } /* @@ -3692,8 +3030,7 @@ static void UI_DrawEffects(rectDef_t *rect, float scale, vec4_t color) UI_Version ================= */ -static void UI_Version(rectDef_t *rect, float scale, vec4_t color, int iFontIndex) -{ +static void UI_Version(rectDef_t *rect, float scale, vec4_t color, int iFontIndex) { int width; width = DC->textWidth(Q3_VERSION, scale, 0); @@ -3706,19 +3043,15 @@ static void UI_Version(rectDef_t *rect, float scale, vec4_t color, int iFontInde UI_DrawKeyBindStatus ================= */ -static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iFontIndex) -{ - if (Display_KeyBindPending()) - { +static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iFontIndex) { + if (Display_KeyBindPending()) { #ifdef JK2_MODE Text_Paint(rect->x, rect->y, scale, color, ui.SP_GetStringTextString("MENUS_WAITINGFORKEY"), 0, textStyle, iFontIndex); #else Text_Paint(rect->x, rect->y, scale, color, SE_GetString("MENUS_WAITINGFORKEY"), 0, textStyle, iFontIndex); #endif - } - else - { -// Text_Paint(rect->x, rect->y, scale, color, ui.SP_GetStringTextString("MENUS_ENTERTOCHANGE"), 0, textStyle, iFontIndex); + } else { + // Text_Paint(rect->x, rect->y, scale, color, ui.SP_GetStringTextString("MENUS_ENTERTOCHANGE"), 0, textStyle, iFontIndex); } } @@ -3727,45 +3060,45 @@ static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int UI_DrawKeyBindStatus ================= */ -static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iFontIndex) -{ +static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iFontIndex) { #define MAX_LINES 64 char buff[4096]; - char * eptr = buff; + char *eptr = buff; const char *lines[MAX_LINES]; - int y, numLines=0, i=0; + int y, numLines = 0, i = 0; y = rect->y; - Text_Paint(rect->x, y, scale, color, va("GL_VENDOR: %s",uiInfo.uiDC.glconfig.vendor_string), rect->w, textStyle, iFontIndex); + Text_Paint(rect->x, y, scale, color, va("GL_VENDOR: %s", uiInfo.uiDC.glconfig.vendor_string), rect->w, textStyle, iFontIndex); y += 15; - Text_Paint(rect->x, y, scale, color, va("GL_VERSION: %s: %s", uiInfo.uiDC.glconfig.version_string,uiInfo.uiDC.glconfig.renderer_string), rect->w, textStyle, iFontIndex); + Text_Paint(rect->x, y, scale, color, va("GL_VERSION: %s: %s", uiInfo.uiDC.glconfig.version_string, uiInfo.uiDC.glconfig.renderer_string), rect->w, + textStyle, iFontIndex); y += 15; Text_Paint(rect->x, y, scale, color, "GL_PIXELFORMAT:", rect->w, textStyle, iFontIndex); y += 15; - Text_Paint(rect->x, y, scale, color, va ("Color(%d-bits) Z(%d-bits) stencil(%d-bits)",uiInfo.uiDC.glconfig.colorBits, uiInfo.uiDC.glconfig.depthBits, uiInfo.uiDC.glconfig.stencilBits), rect->w, textStyle, iFontIndex); + Text_Paint( + rect->x, y, scale, color, + va("Color(%d-bits) Z(%d-bits) stencil(%d-bits)", uiInfo.uiDC.glconfig.colorBits, uiInfo.uiDC.glconfig.depthBits, uiInfo.uiDC.glconfig.stencilBits), + rect->w, textStyle, iFontIndex); y += 15; // build null terminated extension strings Q_strncpyz(buff, uiInfo.uiDC.glconfig.extensions_string, sizeof(buff)); - int testy=y-16; - while ( testy <= rect->y + rect->h && *eptr && (numLines < MAX_LINES) ) - { - while ( *eptr && *eptr == ' ' ) + int testy = y - 16; + while (testy <= rect->y + rect->h && *eptr && (numLines < MAX_LINES)) { + while (*eptr && *eptr == ' ') *eptr++ = '\0'; // track start of valid string - if (*eptr && *eptr != ' ') - { + if (*eptr && *eptr != ' ') { lines[numLines++] = eptr; - testy+=16; + testy += 16; } - while ( *eptr && *eptr != ' ' ) + while (*eptr && *eptr != ' ') eptr++; } numLines--; - while (i < numLines) - { + while (i < numLines) { Text_Paint(rect->x, y, scale, color, lines[i++], rect->w, textStyle, iFontIndex); y += 16; } @@ -3795,22 +3128,21 @@ static void UI_DataPad_ForcePowers(rectDef_t *rect, float scale, vec4_t color, i */ static void UI_DrawCrosshair(rectDef_t *rect, float scale, vec4_t color) { - trap_R_SetColor( color ); + trap_R_SetColor(color); if (uiInfo.currentCrosshair < 0 || uiInfo.currentCrosshair >= NUM_CROSSHAIRS) { uiInfo.currentCrosshair = 0; } - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.uiDC.Assets.crosshairShader[uiInfo.currentCrosshair]); - trap_R_SetColor( NULL ); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.uiDC.Assets.crosshairShader[uiInfo.currentCrosshair]); + trap_R_SetColor(NULL); } - /* ================= UI_OwnerDraw ================= */ -static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle, int iFontIndex) -{ +static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, + float scale, vec4_t color, qhandle_t shader, int textStyle, int iFontIndex) { rectDef_t rect; rect.x = x + text_x; @@ -3818,81 +3150,74 @@ static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float rect.w = w; rect.h = h; - switch (ownerDraw) - { - case UI_EFFECTS: - UI_DrawEffects(&rect, scale, color); - break; - case UI_VERSION: - UI_Version(&rect, scale, color, iFontIndex); - break; + switch (ownerDraw) { + case UI_EFFECTS: + UI_DrawEffects(&rect, scale, color); + break; + case UI_VERSION: + UI_Version(&rect, scale, color, iFontIndex); + break; - case UI_DATAPAD_MISSION: - ui.Draw_DataPad(DP_HUD); - ui.Draw_DataPad(DP_OBJECTIVES); - break; + case UI_DATAPAD_MISSION: + ui.Draw_DataPad(DP_HUD); + ui.Draw_DataPad(DP_OBJECTIVES); + break; - case UI_DATAPAD_WEAPONS: - ui.Draw_DataPad(DP_HUD); - ui.Draw_DataPad(DP_WEAPONS); - break; + case UI_DATAPAD_WEAPONS: + ui.Draw_DataPad(DP_HUD); + ui.Draw_DataPad(DP_WEAPONS); + break; - case UI_DATAPAD_INVENTORY: - ui.Draw_DataPad(DP_HUD); - ui.Draw_DataPad(DP_INVENTORY); - break; + case UI_DATAPAD_INVENTORY: + ui.Draw_DataPad(DP_HUD); + ui.Draw_DataPad(DP_INVENTORY); + break; - case UI_DATAPAD_FORCEPOWERS: - ui.Draw_DataPad(DP_HUD); - ui.Draw_DataPad(DP_FORCEPOWERS); - break; + case UI_DATAPAD_FORCEPOWERS: + ui.Draw_DataPad(DP_HUD); + ui.Draw_DataPad(DP_FORCEPOWERS); + break; - case UI_ALLMAPS_SELECTION://saved game thumbnail + case UI_ALLMAPS_SELECTION: // saved game thumbnail - int levelshot; - levelshot = ui.R_RegisterShaderNoMip( va( "levelshots/%s", s_savedata[s_savegame.currentLine].currentSaveFileMap ) ); + int levelshot; + levelshot = ui.R_RegisterShaderNoMip(va("levelshots/%s", s_savedata[s_savegame.currentLine].currentSaveFileMap)); #ifdef JK2_MODE - if (screenShotBuf[0]) - { - ui.DrawStretchRaw( x, y, w, h, SG_SCR_WIDTH, SG_SCR_HEIGHT, screenShotBuf, 0, qtrue ); - } - else + if (screenShotBuf[0]) { + ui.DrawStretchRaw(x, y, w, h, SG_SCR_WIDTH, SG_SCR_HEIGHT, screenShotBuf, 0, qtrue); + } else #endif - if (levelshot) - { - ui.R_DrawStretchPic( x, y, w, h, 0, 0, 1, 1, levelshot ); - } - else - { - UI_DrawHandlePic(x, y, w, h, uis.menuBackShader); - } + if (levelshot) { + ui.R_DrawStretchPic(x, y, w, h, 0, 0, 1, 1, levelshot); + } else { + UI_DrawHandlePic(x, y, w, h, uis.menuBackShader); + } - ui.R_Font_DrawString( x, // int ox - y+h, // int oy - s_savedata[s_savegame.currentLine].currentSaveFileMap, // const char *text - color, // paletteRGBA_c c - iFontIndex, // const int iFontHandle - w,//-1, // iMaxPixelWidth (-1 = none) - scale // const float scale = 1.0f - ); - break; - case UI_PREVIEWCINEMATIC: - // FIXME BOB - make this work? -// UI_DrawPreviewCinematic(&rect, scale, color); - break; - case UI_CROSSHAIR: - UI_DrawCrosshair(&rect, scale, color); - break; - case UI_GLINFO: - UI_DrawGLInfo(&rect,scale, color, textStyle, iFontIndex); - break; - case UI_KEYBINDSTATUS: - UI_DrawKeyBindStatus(&rect,scale, color, textStyle, iFontIndex); - break; - default: - break; + ui.R_Font_DrawString(x, // int ox + y + h, // int oy + s_savedata[s_savegame.currentLine].currentSaveFileMap, // const char *text + color, // paletteRGBA_c c + iFontIndex, // const int iFontHandle + w, //-1, // iMaxPixelWidth (-1 = none) + scale // const float scale = 1.0f + ); + break; + case UI_PREVIEWCINEMATIC: + // FIXME BOB - make this work? + // UI_DrawPreviewCinematic(&rect, scale, color); + break; + case UI_CROSSHAIR: + UI_DrawCrosshair(&rect, scale, color); + break; + case UI_GLINFO: + UI_DrawGLInfo(&rect, scale, color, textStyle, iFontIndex); + break; + case UI_KEYBINDSTATUS: + UI_DrawKeyBindStatus(&rect, scale, color, textStyle, iFontIndex); + break; + default: + break; } - } /* @@ -3900,22 +3225,21 @@ static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float UI_OwnerDrawVisible ================= */ -static qboolean UI_OwnerDrawVisible(int flags) -{ +static qboolean UI_OwnerDrawVisible(int flags) { qboolean vis = qtrue; - while (flags) - { -/* if (flags & UI_SHOW_DEMOAVAILABLE) + while (flags) { + /* if (flags & UI_SHOW_DEMOAVAILABLE) + { + if (!uiInfo.demoAvailable) + { + vis = qfalse; + } + flags &= ~UI_SHOW_DEMOAVAILABLE; + } + else + */ { - if (!uiInfo.demoAvailable) - { - vis = qfalse; - } - flags &= ~UI_SHOW_DEMOAVAILABLE; - } - else -*/ { flags = 0; } } @@ -3927,12 +3251,10 @@ static qboolean UI_OwnerDrawVisible(int flags) Text_Width ================= */ -int Text_Width(const char *text, float scale, int iFontIndex) -{ +int Text_Width(const char *text, float scale, int iFontIndex) { // temp code until Bob retro-fits all menus to have font specifiers... // - if ( iFontIndex == 0 ) - { + if (iFontIndex == 0) { iFontIndex = uiInfo.uiDC.Assets.qhMediumFont; } return ui.R_Font_StrLenPixels(text, iFontIndex, scale); @@ -3943,40 +3265,33 @@ int Text_Width(const char *text, float scale, int iFontIndex) UI_OwnerDrawWidth ================= */ -int UI_OwnerDrawWidth(int ownerDraw, float scale) -{ -// int i, h, value; -// const char *text; +int UI_OwnerDrawWidth(int ownerDraw, float scale) { + // int i, h, value; + // const char *text; const char *s = NULL; - - switch (ownerDraw) - { + switch (ownerDraw) { case UI_KEYBINDSTATUS: - if (Display_KeyBindPending()) - { + if (Display_KeyBindPending()) { #ifdef JK2_MODE s = ui.SP_GetStringTextString("MENUS_WAITINGFORKEY"); #else s = SE_GetString("MENUS_WAITINGFORKEY"); #endif - } - else - { -// s = ui.SP_GetStringTextString("MENUS_ENTERTOCHANGE"); + } else { + // s = ui.SP_GetStringTextString("MENUS_ENTERTOCHANGE"); } break; - // FIXME BOB -// case UI_SERVERREFRESHDATE: -// s = UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)); -// break; - default: - break; + // FIXME BOB + // case UI_SERVERREFRESHDATE: + // s = UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)); + // break; + default: + break; } - if (s) - { + if (s) { return Text_Width(s, scale, 0); } return 0; @@ -3987,54 +3302,42 @@ int UI_OwnerDrawWidth(int ownerDraw, float scale) Text_Height ================= */ -int Text_Height(const char *text, float scale, int iFontIndex) -{ +int Text_Height(const char *text, float scale, int iFontIndex) { // temp until Bob retro-fits all menu files with font specifiers... // - if ( iFontIndex == 0 ) - { + if (iFontIndex == 0) { iFontIndex = uiInfo.uiDC.Assets.qhMediumFont; } return ui.R_Font_HeightPixels(iFontIndex, scale); } - /* ================= UI_MouseEvent ================= */ -//JLFMOUSE CALLED EACH FRAME IN UI -void _UI_MouseEvent( int dx, int dy ) -{ +// JLFMOUSE CALLED EACH FRAME IN UI +void _UI_MouseEvent(int dx, int dy) { // update mouse screen position uiInfo.uiDC.cursorx += dx; - if (uiInfo.uiDC.cursorx < 0) - { + if (uiInfo.uiDC.cursorx < 0) { uiInfo.uiDC.cursorx = 0; - } - else if (uiInfo.uiDC.cursorx > SCREEN_WIDTH) - { + } else if (uiInfo.uiDC.cursorx > SCREEN_WIDTH) { uiInfo.uiDC.cursorx = SCREEN_WIDTH; } uiInfo.uiDC.cursory += dy; - if (uiInfo.uiDC.cursory < 0) - { + if (uiInfo.uiDC.cursory < 0) { uiInfo.uiDC.cursory = 0; - } - else if (uiInfo.uiDC.cursory > SCREEN_HEIGHT) - { + } else if (uiInfo.uiDC.cursory > SCREEN_HEIGHT) { uiInfo.uiDC.cursory = SCREEN_HEIGHT; } - if (Menu_Count() > 0) - { - //menuDef_t *menu = Menu_GetFocused(); - //Menu_HandleMouseMove(menu, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); + if (Menu_Count() > 0) { + // menuDef_t *menu = Menu_GetFocused(); + // Menu_HandleMouseMove(menu, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); Display_MouseMove(NULL, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); } - } /* @@ -4042,34 +3345,26 @@ void _UI_MouseEvent( int dx, int dy ) UI_KeyEvent ================= */ -void _UI_KeyEvent( int key, qboolean down ) -{ -/* extern qboolean SwallowBadNumLockedKPKey( int iKey ); - if (SwallowBadNumLockedKPKey(key)){ - return; - } -*/ +void _UI_KeyEvent(int key, qboolean down) { + /* extern qboolean SwallowBadNumLockedKPKey( int iKey ); + if (SwallowBadNumLockedKPKey(key)){ + return; + } + */ - if (Menu_Count() > 0) - { + if (Menu_Count() > 0) { menuDef_t *menu = Menu_GetFocused(); - if (menu) - { - //DemoEnd(); - if (key == A_ESCAPE && down && !Menus_AnyFullScreenVisible() && !(menu->window.flags & WINDOW_IGNORE_ESCAPE)) - { + if (menu) { + // DemoEnd(); + if (key == A_ESCAPE && down && !Menus_AnyFullScreenVisible() && !(menu->window.flags & WINDOW_IGNORE_ESCAPE)) { Menus_CloseAll(); + } else { + Menu_HandleKey(menu, key, down); } - else - { - Menu_HandleKey(menu, key, down ); - } - } - else - { - trap_Key_SetCatcher( trap_Key_GetCatcher() & ~KEYCATCH_UI ); + } else { + trap_Key_SetCatcher(trap_Key_GetCatcher() & ~KEYCATCH_UI); trap_Key_ClearStates(); - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } } } @@ -4079,41 +3374,29 @@ void _UI_KeyEvent( int key, qboolean down ) UI_Report ================= */ -void UI_Report(void) -{ - String_Report(); -} - - +void UI_Report(void) { String_Report(); } /* ================= UI_DataPadMenu ================= */ -void UI_DataPadMenu(void) -{ - int newForcePower,newObjective; +void UI_DataPadMenu(void) { + int newForcePower, newObjective; Menus_CloseByName("mainhud"); newForcePower = (int)trap_Cvar_VariableValue("cg_updatedDataPadForcePower1"); newObjective = (int)trap_Cvar_VariableValue("cg_updatedDataPadObjective"); - if (newForcePower) - { + if (newForcePower) { Menus_ActivateByName("datapadForcePowersMenu"); - } - else if (newObjective) - { + } else if (newObjective) { Menus_ActivateByName("datapadMissionMenu"); - } - else - { + } else { Menus_ActivateByName("datapadMissionMenu"); } - ui.Key_SetCatcher( KEYCATCH_UI ); - + ui.Key_SetCatcher(KEYCATCH_UI); } /* @@ -4121,28 +3404,21 @@ void UI_DataPadMenu(void) UI_InGameMenu ================= */ -void UI_InGameMenu(const char*menuID) -{ +void UI_InGameMenu(const char *menuID) { #ifdef JK2_MODE ui.PrecacheScreenshot(); #endif Menus_CloseByName("mainhud"); - if (menuID) - { + if (menuID) { Menus_ActivateByName(menuID); - } - else - { + } else { Menus_ActivateByName("ingameMainMenu"); } - ui.Key_SetCatcher( KEYCATCH_UI ); + ui.Key_SetCatcher(KEYCATCH_UI); } -qboolean _UI_IsFullscreen( void ) -{ - return Menus_AnyFullScreenVisible(); -} +qboolean _UI_IsFullscreen(void) { return Menus_AnyFullScreenVisible(); } /* ======================================================================= @@ -4152,7 +3428,6 @@ MAIN MENU ======================================================================= */ - /* =============== UI_MainMenu @@ -4162,17 +3437,15 @@ so make sure that the attract loop server is down and that local cinematics are killed =============== */ -void UI_MainMenu(void) -{ +void UI_MainMenu(void) { char buf[256]; - ui.Cvar_Set("sv_killserver", "1"); // let the demo server know it should shut down + ui.Cvar_Set("sv_killserver", "1"); // let the demo server know it should shut down - ui.Key_SetCatcher( KEYCATCH_UI ); + ui.Key_SetCatcher(KEYCATCH_UI); menuDef_t *m = Menus_ActivateByName("mainMenu"); - if (!m) - { //wha? try again - UI_LoadMenus("ui/menus.txt",qfalse); + if (!m) { // wha? try again + UI_LoadMenus("ui/menus.txt", qfalse); } ui.Cvar_VariableStringBuffer("com_errorMessage", buf, sizeof(buf)); if (strlen(buf)) { @@ -4180,18 +3453,16 @@ void UI_MainMenu(void) } } - /* ================= Menu_Cache ================= */ -void Menu_Cache( void ) -{ - uis.cursor = ui.R_RegisterShaderNoMip( "menu/new/crosshairb"); +void Menu_Cache(void) { + uis.cursor = ui.R_RegisterShaderNoMip("menu/new/crosshairb"); // Common menu graphics - uis.whiteShader = ui.R_RegisterShader( "white" ); - uis.menuBackShader = ui.R_RegisterShaderNoMip( "menu/art/unknownmap" ); + uis.whiteShader = ui.R_RegisterShader("white"); + uis.menuBackShader = ui.R_RegisterShaderNoMip("menu/art/unknownmap"); } /* @@ -4203,26 +3474,25 @@ their real counterparts. This is to create a interface which allows you to discard your changes if you did something you didnt want ================= */ -void UI_UpdateVideoSetup ( void ) -{ - Cvar_Set ( "r_mode", Cvar_VariableString ( "ui_r_mode" ) ); - Cvar_Set ( "r_fullscreen", Cvar_VariableString ( "ui_r_fullscreen" ) ); - Cvar_Set ( "r_colorbits", Cvar_VariableString ( "ui_r_colorbits" ) ); - Cvar_Set ( "r_lodbias", Cvar_VariableString ( "ui_r_lodbias" ) ); - Cvar_Set ( "r_picmip", Cvar_VariableString ( "ui_r_picmip" ) ); - Cvar_Set ( "r_texturebits", Cvar_VariableString ( "ui_r_texturebits" ) ); - Cvar_Set ( "r_texturemode", Cvar_VariableString ( "ui_r_texturemode" ) ); - Cvar_Set ( "r_detailtextures", Cvar_VariableString ( "ui_r_detailtextures" ) ); - Cvar_Set ( "r_ext_compress_textures", Cvar_VariableString ( "ui_r_ext_compress_textures" ) ); - Cvar_Set ( "r_depthbits", Cvar_VariableString ( "ui_r_depthbits" ) ); - Cvar_Set ( "r_subdivisions", Cvar_VariableString ( "ui_r_subdivisions" ) ); - Cvar_Set ( "r_fastSky", Cvar_VariableString ( "ui_r_fastSky" ) ); - Cvar_Set ( "r_inGameVideo", Cvar_VariableString ( "ui_r_inGameVideo" ) ); - Cvar_Set ( "r_allowExtensions", Cvar_VariableString ( "ui_r_allowExtensions" ) ); -// Cvar_Set ( "cg_shadows", Cvar_VariableString ( "ui_cg_shadows" ) ); - Cvar_Set ( "ui_r_modified", "0" ); - - Cbuf_ExecuteText( EXEC_APPEND, "vid_restart;" ); +void UI_UpdateVideoSetup(void) { + Cvar_Set("r_mode", Cvar_VariableString("ui_r_mode")); + Cvar_Set("r_fullscreen", Cvar_VariableString("ui_r_fullscreen")); + Cvar_Set("r_colorbits", Cvar_VariableString("ui_r_colorbits")); + Cvar_Set("r_lodbias", Cvar_VariableString("ui_r_lodbias")); + Cvar_Set("r_picmip", Cvar_VariableString("ui_r_picmip")); + Cvar_Set("r_texturebits", Cvar_VariableString("ui_r_texturebits")); + Cvar_Set("r_texturemode", Cvar_VariableString("ui_r_texturemode")); + Cvar_Set("r_detailtextures", Cvar_VariableString("ui_r_detailtextures")); + Cvar_Set("r_ext_compress_textures", Cvar_VariableString("ui_r_ext_compress_textures")); + Cvar_Set("r_depthbits", Cvar_VariableString("ui_r_depthbits")); + Cvar_Set("r_subdivisions", Cvar_VariableString("ui_r_subdivisions")); + Cvar_Set("r_fastSky", Cvar_VariableString("ui_r_fastSky")); + Cvar_Set("r_inGameVideo", Cvar_VariableString("ui_r_inGameVideo")); + Cvar_Set("r_allowExtensions", Cvar_VariableString("ui_r_allowExtensions")); + // Cvar_Set ( "cg_shadows", Cvar_VariableString ( "ui_cg_shadows" ) ); + Cvar_Set("ui_r_modified", "0"); + + Cbuf_ExecuteText(EXEC_APPEND, "vid_restart;"); } /* @@ -4233,56 +3503,53 @@ Retrieves the current actual video settings into the temporary user interface versions of the cvars. ================= */ -void UI_GetVideoSetup ( void ) -{ - Cvar_Register ( NULL, "ui_r_glCustom", "4", CVAR_ARCHIVE ); +void UI_GetVideoSetup(void) { + Cvar_Register(NULL, "ui_r_glCustom", "4", CVAR_ARCHIVE); // Make sure the cvars are registered as read only. - Cvar_Register ( NULL, "ui_r_mode", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_fullscreen", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_colorbits", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_lodbias", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_picmip", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_texturebits", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_texturemode", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_detailtextures", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_ext_compress_textures", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_depthbits", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_subdivisions", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_fastSky", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_inGameVideo", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_allowExtensions", "0", CVAR_ROM ); -// Cvar_Register ( NULL, "ui_cg_shadows", "0", CVAR_ROM ); - Cvar_Register ( NULL, "ui_r_modified", "0", CVAR_ROM ); + Cvar_Register(NULL, "ui_r_mode", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_fullscreen", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_colorbits", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_lodbias", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_picmip", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_texturebits", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_texturemode", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_detailtextures", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_ext_compress_textures", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_depthbits", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_subdivisions", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_fastSky", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_inGameVideo", "0", CVAR_ROM); + Cvar_Register(NULL, "ui_r_allowExtensions", "0", CVAR_ROM); + // Cvar_Register ( NULL, "ui_cg_shadows", "0", CVAR_ROM ); + Cvar_Register(NULL, "ui_r_modified", "0", CVAR_ROM); // Copy over the real video cvars into their temporary counterparts - Cvar_Set ( "ui_r_mode", Cvar_VariableString ( "r_mode" ) ); - Cvar_Set ( "ui_r_colorbits", Cvar_VariableString ( "r_colorbits" ) ); - Cvar_Set ( "ui_r_fullscreen", Cvar_VariableString ( "r_fullscreen" ) ); - Cvar_Set ( "ui_r_lodbias", Cvar_VariableString ( "r_lodbias" ) ); - Cvar_Set ( "ui_r_picmip", Cvar_VariableString ( "r_picmip" ) ); - Cvar_Set ( "ui_r_texturebits", Cvar_VariableString ( "r_texturebits" ) ); - Cvar_Set ( "ui_r_texturemode", Cvar_VariableString ( "r_texturemode" ) ); - Cvar_Set ( "ui_r_detailtextures", Cvar_VariableString ( "r_detailtextures" ) ); - Cvar_Set ( "ui_r_ext_compress_textures", Cvar_VariableString ( "r_ext_compress_textures" ) ); - Cvar_Set ( "ui_r_depthbits", Cvar_VariableString ( "r_depthbits" ) ); - Cvar_Set ( "ui_r_subdivisions", Cvar_VariableString ( "r_subdivisions" ) ); - Cvar_Set ( "ui_r_fastSky", Cvar_VariableString ( "r_fastSky" ) ); - Cvar_Set ( "ui_r_inGameVideo", Cvar_VariableString ( "r_inGameVideo" ) ); - Cvar_Set ( "ui_r_allowExtensions", Cvar_VariableString ( "r_allowExtensions" ) ); -// Cvar_Set ( "ui_cg_shadows", Cvar_VariableString ( "cg_shadows" ) ); - Cvar_Set ( "ui_r_modified", "0" ); + Cvar_Set("ui_r_mode", Cvar_VariableString("r_mode")); + Cvar_Set("ui_r_colorbits", Cvar_VariableString("r_colorbits")); + Cvar_Set("ui_r_fullscreen", Cvar_VariableString("r_fullscreen")); + Cvar_Set("ui_r_lodbias", Cvar_VariableString("r_lodbias")); + Cvar_Set("ui_r_picmip", Cvar_VariableString("r_picmip")); + Cvar_Set("ui_r_texturebits", Cvar_VariableString("r_texturebits")); + Cvar_Set("ui_r_texturemode", Cvar_VariableString("r_texturemode")); + Cvar_Set("ui_r_detailtextures", Cvar_VariableString("r_detailtextures")); + Cvar_Set("ui_r_ext_compress_textures", Cvar_VariableString("r_ext_compress_textures")); + Cvar_Set("ui_r_depthbits", Cvar_VariableString("r_depthbits")); + Cvar_Set("ui_r_subdivisions", Cvar_VariableString("r_subdivisions")); + Cvar_Set("ui_r_fastSky", Cvar_VariableString("r_fastSky")); + Cvar_Set("ui_r_inGameVideo", Cvar_VariableString("r_inGameVideo")); + Cvar_Set("ui_r_allowExtensions", Cvar_VariableString("r_allowExtensions")); + // Cvar_Set ( "ui_cg_shadows", Cvar_VariableString ( "cg_shadows" ) ); + Cvar_Set("ui_r_modified", "0"); } -static void UI_SetSexandSoundForModel(const char* char_model) -{ - int f,i; - char soundpath[MAX_QPATH]; - qboolean isFemale = qfalse; +static void UI_SetSexandSoundForModel(const char *char_model) { + int f, i; + char soundpath[MAX_QPATH]; + qboolean isFemale = qfalse; i = ui.FS_FOpenFile(va("models/players/%s/sounds.cfg", char_model), &f, FS_READ); - if ( !f ) - {//no? oh bother. + if (!f) { // no? oh bother. Cvar_Reset("snd"); Cvar_Reset("sex"); return; @@ -4292,10 +3559,8 @@ static void UI_SetSexandSoundForModel(const char* char_model) ui.FS_Read(&soundpath, i, f); - while (i >= 0 && soundpath[i] != '\n') - { - if (soundpath[i] == 'f') - { + while (i >= 0 && soundpath[i] != '\n') { + if (soundpath[i] == 'f') { isFemale = qtrue; soundpath[i] = 0; } @@ -4305,163 +3570,127 @@ static void UI_SetSexandSoundForModel(const char* char_model) i = 0; - while (soundpath[i] && soundpath[i] != '\r' && soundpath[i] != '\n') - { + while (soundpath[i] && soundpath[i] != '\r' && soundpath[i] != '\n') { i++; } soundpath[i] = 0; ui.FS_FCloseFile(f); - Cvar_Set ( "snd", soundpath); - if (isFemale) - { - Cvar_Set ( "sex", "f"); - } - else - { - Cvar_Set ( "sex", "m"); + Cvar_Set("snd", soundpath); + if (isFemale) { + Cvar_Set("sex", "f"); + } else { + Cvar_Set("sex", "m"); } } -static void UI_UpdateCharacterCvars ( void ) -{ - const char *char_model = Cvar_VariableString ( "ui_char_model" ); +static void UI_UpdateCharacterCvars(void) { + const char *char_model = Cvar_VariableString("ui_char_model"); UI_SetSexandSoundForModel(char_model); - Cvar_Set ( "g_char_model", char_model ); - Cvar_Set ( "g_char_skin_head", Cvar_VariableString ( "ui_char_skin_head" ) ); - Cvar_Set ( "g_char_skin_torso", Cvar_VariableString ( "ui_char_skin_torso" ) ); - Cvar_Set ( "g_char_skin_legs", Cvar_VariableString ( "ui_char_skin_legs" ) ); - Cvar_Set ( "g_char_color_red", Cvar_VariableString ( "ui_char_color_red" ) ); - Cvar_Set ( "g_char_color_green", Cvar_VariableString ( "ui_char_color_green" ) ); - Cvar_Set ( "g_char_color_blue", Cvar_VariableString ( "ui_char_color_blue" ) ); + Cvar_Set("g_char_model", char_model); + Cvar_Set("g_char_skin_head", Cvar_VariableString("ui_char_skin_head")); + Cvar_Set("g_char_skin_torso", Cvar_VariableString("ui_char_skin_torso")); + Cvar_Set("g_char_skin_legs", Cvar_VariableString("ui_char_skin_legs")); + Cvar_Set("g_char_color_red", Cvar_VariableString("ui_char_color_red")); + Cvar_Set("g_char_color_green", Cvar_VariableString("ui_char_color_green")); + Cvar_Set("g_char_color_blue", Cvar_VariableString("ui_char_color_blue")); } -static void UI_GetCharacterCvars ( void ) -{ - Cvar_Set ( "ui_char_skin_head", Cvar_VariableString ( "g_char_skin_head" ) ); - Cvar_Set ( "ui_char_skin_torso", Cvar_VariableString ( "g_char_skin_torso" ) ); - Cvar_Set ( "ui_char_skin_legs", Cvar_VariableString ( "g_char_skin_legs" ) ); - Cvar_Set ( "ui_char_color_red", Cvar_VariableString ( "g_char_color_red" ) ); - Cvar_Set ( "ui_char_color_green", Cvar_VariableString ( "g_char_color_green" ) ); - Cvar_Set ( "ui_char_color_blue", Cvar_VariableString ( "g_char_color_blue" ) ); +static void UI_GetCharacterCvars(void) { + Cvar_Set("ui_char_skin_head", Cvar_VariableString("g_char_skin_head")); + Cvar_Set("ui_char_skin_torso", Cvar_VariableString("g_char_skin_torso")); + Cvar_Set("ui_char_skin_legs", Cvar_VariableString("g_char_skin_legs")); + Cvar_Set("ui_char_color_red", Cvar_VariableString("g_char_color_red")); + Cvar_Set("ui_char_color_green", Cvar_VariableString("g_char_color_green")); + Cvar_Set("ui_char_color_blue", Cvar_VariableString("g_char_color_blue")); - const char* model = Cvar_VariableString ( "g_char_model" ); - Cvar_Set ( "ui_char_model", model ); + const char *model = Cvar_VariableString("g_char_model"); + Cvar_Set("ui_char_model", model); - for (int i = 0; i < uiInfo.playerSpeciesCount; i++) - { - if ( !Q_stricmp(model, uiInfo.playerSpecies[i].Name) ) - { + for (int i = 0; i < uiInfo.playerSpeciesCount; i++) { + if (!Q_stricmp(model, uiInfo.playerSpecies[i].Name)) { uiInfo.playerSpeciesIndex = i; } } } -static void UI_UpdateSaberCvars ( void ) -{ - Cvar_Set ( "g_saber_type", Cvar_VariableString ( "ui_saber_type" ) ); - Cvar_Set ( "g_saber", Cvar_VariableString ( "ui_saber" ) ); - Cvar_Set ( "g_saber2", Cvar_VariableString ( "ui_saber2" ) ); - Cvar_Set ( "g_saber_color", Cvar_VariableString ( "ui_saber_color" ) ); - Cvar_Set ( "g_saber2_color", Cvar_VariableString ( "ui_saber2_color" ) ); +static void UI_UpdateSaberCvars(void) { + Cvar_Set("g_saber_type", Cvar_VariableString("ui_saber_type")); + Cvar_Set("g_saber", Cvar_VariableString("ui_saber")); + Cvar_Set("g_saber2", Cvar_VariableString("ui_saber2")); + Cvar_Set("g_saber_color", Cvar_VariableString("ui_saber_color")); + Cvar_Set("g_saber2_color", Cvar_VariableString("ui_saber2_color")); } #ifndef JK2_MODE -static void UI_UpdateFightingStyleChoices ( void ) -{ +static void UI_UpdateFightingStyleChoices(void) { // - if (!Q_stricmp("staff",Cvar_VariableString ( "ui_saber_type" ))) - { - Cvar_Set ( "ui_fightingstylesallowed", "0" ); - Cvar_Set ( "ui_newfightingstyle", "4" ); // SS_STAFF - } - else if (!Q_stricmp("dual",Cvar_VariableString ( "ui_saber_type" ))) - { - Cvar_Set ( "ui_fightingstylesallowed", "0" ); - Cvar_Set ( "ui_newfightingstyle", "3" ); // SS_DUAL - } - else - { + if (!Q_stricmp("staff", Cvar_VariableString("ui_saber_type"))) { + Cvar_Set("ui_fightingstylesallowed", "0"); + Cvar_Set("ui_newfightingstyle", "4"); // SS_STAFF + } else if (!Q_stricmp("dual", Cvar_VariableString("ui_saber_type"))) { + Cvar_Set("ui_fightingstylesallowed", "0"); + Cvar_Set("ui_newfightingstyle", "3"); // SS_DUAL + } else { // Get player state - client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - playerState_t *pState; + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + playerState_t *pState; - if (cl && cl->gentity && cl->gentity->client) - { + if (cl && cl->gentity && cl->gentity->client) { pState = cl->gentity->client; - // Knows Fast style? - if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_FAST)) { // And Medium? - if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_MEDIUM)) { + Cvar_Set("ui_fightingstylesallowed", "6"); // Has FAST and MEDIUM, so can only choose STRONG + Cvar_Set("ui_newfightingstyle", "2"); // STRONG + } else { + Cvar_Set("ui_fightingstylesallowed", "1"); // Has FAST, so can choose from MEDIUM and STRONG + Cvar_Set("ui_newfightingstyle", "1"); // MEDIUM } } // Knows Medium style? - else if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_MEDIUM)) { // And Strong? - if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_STRONG)) { + Cvar_Set("ui_fightingstylesallowed", "4"); // Has MEDIUM and STRONG, so can only choose FAST + Cvar_Set("ui_newfightingstyle", "0"); // FAST + } else { + Cvar_Set("ui_fightingstylesallowed", "2"); // Has MEDIUM, so can choose from FAST and STRONG + Cvar_Set("ui_newfightingstyle", "0"); // FAST } } // Knows Strong style? - else if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_STRONG)) { // And Fast - if (pState->saberStylesKnown & (1<saberStylesKnown & (1 << SS_FAST)) { + Cvar_Set("ui_fightingstylesallowed", "5"); // Has STRONG and FAST, so can only take MEDIUM + Cvar_Set("ui_newfightingstyle", "1"); // MEDIUM + } else { + Cvar_Set("ui_fightingstylesallowed", "3"); // Has STRONG, so can choose from FAST and MEDIUM + Cvar_Set("ui_newfightingstyle", "1"); // MEDIUM } - } - else // They have nothing, which should not happen + } else // They have nothing, which should not happen { - Cvar_Set ( "ui_currentfightingstyle", "1" ); // Default MEDIUM - Cvar_Set ( "ui_newfightingstyle", "0" ); // FAST?? - Cvar_Set ( "ui_fightingstylesallowed", "0" ); // Default to no new styles allowed + Cvar_Set("ui_currentfightingstyle", "1"); // Default MEDIUM + Cvar_Set("ui_newfightingstyle", "0"); // FAST?? + Cvar_Set("ui_fightingstylesallowed", "0"); // Default to no new styles allowed } // Determine current style - if (pState->saberAnimLevel == SS_FAST) - { - Cvar_Set ( "ui_currentfightingstyle", "0" ); // FAST - } - else if (pState->saberAnimLevel == SS_STRONG) - { - Cvar_Set ( "ui_currentfightingstyle", "2" ); // STRONG + if (pState->saberAnimLevel == SS_FAST) { + Cvar_Set("ui_currentfightingstyle", "0"); // FAST + } else if (pState->saberAnimLevel == SS_STRONG) { + Cvar_Set("ui_currentfightingstyle", "2"); // STRONG + } else { + Cvar_Set("ui_currentfightingstyle", "1"); // default MEDIUM } - else - { - Cvar_Set ( "ui_currentfightingstyle", "1" ); // default MEDIUM - } - } - else // No client so this must be first time + } else // No client so this must be first time { - Cvar_Set ( "ui_currentfightingstyle", "1" ); // Default to MEDIUM - Cvar_Set ( "ui_fightingstylesallowed", "0" ); // Default to no new styles allowed - Cvar_Set ( "ui_newfightingstyle", "1" ); // MEDIUM + Cvar_Set("ui_currentfightingstyle", "1"); // Default to MEDIUM + Cvar_Set("ui_fightingstylesallowed", "0"); // Default to no new styles allowed + Cvar_Set("ui_newfightingstyle", "1"); // MEDIUM } } } @@ -4470,124 +3699,110 @@ static void UI_UpdateFightingStyleChoices ( void ) #define MAX_POWER_ENUMS 16 typedef struct { - const char *title; - short powerEnum; + const char *title; + short powerEnum; } powerEnum_t; -static powerEnum_t powerEnums[MAX_POWER_ENUMS] = -{ +static powerEnum_t powerEnums[MAX_POWER_ENUMS] = { #ifndef JK2_MODE - { "absorb", FP_ABSORB }, + {"absorb", FP_ABSORB}, #endif // !JK2_MODE - { "heal", FP_HEAL }, - { "mindtrick", FP_TELEPATHY }, + {"heal", FP_HEAL}, + {"mindtrick", FP_TELEPATHY}, #ifndef JK2_MODE - { "protect", FP_PROTECT }, + {"protect", FP_PROTECT}, #endif // !JK2_MODE - // Core powers - { "jump", FP_LEVITATION }, - { "pull", FP_PULL }, - { "push", FP_PUSH }, + // Core powers + {"jump", FP_LEVITATION}, + {"pull", FP_PULL}, + {"push", FP_PUSH}, #ifndef JK2_MODE - { "sense", FP_SEE }, + {"sense", FP_SEE}, #endif // !JK2_MODE - { "speed", FP_SPEED }, - { "sabdef", FP_SABER_DEFENSE }, - { "saboff", FP_SABER_OFFENSE }, - { "sabthrow", FP_SABERTHROW }, + {"speed", FP_SPEED}, + {"sabdef", FP_SABER_DEFENSE}, + {"saboff", FP_SABER_OFFENSE}, + {"sabthrow", FP_SABERTHROW}, - // Dark powers +// Dark powers #ifndef JK2_MODE - { "drain", FP_DRAIN }, + {"drain", FP_DRAIN}, #endif // !JK2_MODE - { "grip", FP_GRIP }, - { "lightning", FP_LIGHTNING }, + {"grip", FP_GRIP}, + {"lightning", FP_LIGHTNING}, #ifndef JK2_MODE - { "rage", FP_RAGE }, + {"rage", FP_RAGE}, #endif // !JK2_MODE }; - // Find the index to the Force Power in powerEnum array -static qboolean UI_GetForcePowerIndex ( const char *forceName, short *forcePowerI ) -{ +static qboolean UI_GetForcePowerIndex(const char *forceName, short *forcePowerI) { int i; // Find a match for the forceName passed in - for (i=0;igentity->client; + if (cl) { + playerState_t *pState = cl->gentity->client; forcelevel = pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]; - } - else - { + } else { forcelevel = uiInfo.forcePowerLevel[powerEnums[forcePowerI].powerEnum]; } char itemName[128]; - Com_sprintf (itemName, sizeof(itemName), "%s_hexpic", powerEnums[forcePowerI].title); - item = (itemDef_s *) Menu_FindItemByName(menu, itemName); + Com_sprintf(itemName, sizeof(itemName), "%s_hexpic", powerEnums[forcePowerI].title); + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); - if (item) - { + if (item) { char itemGraphic[128]; - Com_sprintf (itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d",forcelevel >= 4 ? 3 : forcelevel); + Com_sprintf(itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d", forcelevel >= 4 ? 3 : forcelevel); item->window.background = ui.R_RegisterShaderNoMip(itemGraphic); // If maxed out on power - don't allow update - if (forcelevel>=3) - { - Com_sprintf (itemName, sizeof(itemName), "%s_fbutton", powerEnums[forcePowerI].title); - item = (itemDef_s *) Menu_FindItemByName(menu, itemName); - if (item) - { - item->action = 0; //you are bad, no action for you! - item->descText = 0; //no desc either! + if (forcelevel >= 3) { + Com_sprintf(itemName, sizeof(itemName), "%s_fbutton", powerEnums[forcePowerI].title); + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); + if (item) { + item->action = 0; // you are bad, no action for you! + item->descText = 0; // no desc either! } } } @@ -4597,153 +3812,116 @@ static void UI_InitAllocForcePowers ( const char *forceName ) } // Flip flop between being able to see the text showing the Force Point has or hasn't been allocated (Used by Force Power Allocation screen) -static void UI_SetPowerTitleText ( qboolean showAllocated ) -{ - menuDef_t *menu; - itemDef_t *item; +static void UI_SetPowerTitleText(qboolean showAllocated) { + menuDef_t *menu; + itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - if (showAllocated) - { + if (showAllocated) { // Show the text saying the force point has been allocated - item = (itemDef_s *) Menu_FindItemByName(menu, "allocated_text"); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, "allocated_text"); + if (item) { item->window.flags |= WINDOW_VISIBLE; } // Hide text saying the force point needs to be allocated - item = (itemDef_s *) Menu_FindItemByName(menu, "allocate_text"); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, "allocate_text"); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } - } - else - { + } else { // Hide the text saying the force point has been allocated - item = (itemDef_s *) Menu_FindItemByName(menu, "allocated_text"); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, "allocated_text"); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } // Show text saying the force point needs to be allocated - item = (itemDef_s *) Menu_FindItemByName(menu, "allocate_text"); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, "allocate_text"); + if (item) { item->window.flags |= WINDOW_VISIBLE; } } } #ifndef JK2_MODE -static int UI_CountForcePowers( void ) { +static int UI_CountForcePowers(void) { const client_t *cl = &svs.clients[0]; - if ( cl && cl->gentity ) { + if (cl && cl->gentity) { const playerState_t *ps = cl->gentity->client; - return ps->forcePowerLevel[FP_HEAL] + - ps->forcePowerLevel[FP_TELEPATHY] + - ps->forcePowerLevel[FP_PROTECT] + - ps->forcePowerLevel[FP_ABSORB] + - ps->forcePowerLevel[FP_GRIP] + - ps->forcePowerLevel[FP_LIGHTNING] + - ps->forcePowerLevel[FP_RAGE] + - ps->forcePowerLevel[FP_DRAIN]; - } - else { - return uiInfo.forcePowerLevel[FP_HEAL] + - uiInfo.forcePowerLevel[FP_TELEPATHY] + - uiInfo.forcePowerLevel[FP_PROTECT] + - uiInfo.forcePowerLevel[FP_ABSORB] + - uiInfo.forcePowerLevel[FP_GRIP] + - uiInfo.forcePowerLevel[FP_LIGHTNING] + - uiInfo.forcePowerLevel[FP_RAGE] + - uiInfo.forcePowerLevel[FP_DRAIN]; + return ps->forcePowerLevel[FP_HEAL] + ps->forcePowerLevel[FP_TELEPATHY] + ps->forcePowerLevel[FP_PROTECT] + ps->forcePowerLevel[FP_ABSORB] + + ps->forcePowerLevel[FP_GRIP] + ps->forcePowerLevel[FP_LIGHTNING] + ps->forcePowerLevel[FP_RAGE] + ps->forcePowerLevel[FP_DRAIN]; + } else { + return uiInfo.forcePowerLevel[FP_HEAL] + uiInfo.forcePowerLevel[FP_TELEPATHY] + uiInfo.forcePowerLevel[FP_PROTECT] + uiInfo.forcePowerLevel[FP_ABSORB] + + uiInfo.forcePowerLevel[FP_GRIP] + uiInfo.forcePowerLevel[FP_LIGHTNING] + uiInfo.forcePowerLevel[FP_RAGE] + uiInfo.forcePowerLevel[FP_DRAIN]; } } #endif //. Find weapons button and make active/inactive (Used by Force Power Allocation screen) -static void UI_ForcePowerWeaponsButton(qboolean activeFlag) -{ - menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu +static void UI_ForcePowerWeaponsButton(qboolean activeFlag) { + menuDef_t *menu; + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } #ifndef JK2_MODE if (!activeFlag) { // total light and dark powers are at maximum level 3 ( 3 levels * ( 4ls + 4ds ) = 24 ) - if ( UI_CountForcePowers() >= 24 ) + if (UI_CountForcePowers() >= 24) activeFlag = qtrue; } #endif // Find weaponsbutton - itemDef_t *item; - item = (itemDef_s *) Menu_FindItemByName(menu, "weaponbutton"); - if (item) - { + itemDef_t *item; + item = (itemDef_s *)Menu_FindItemByName(menu, "weaponbutton"); + if (item) { // Make it active - if (activeFlag) - { + if (activeFlag) { item->window.flags &= ~WINDOW_INACTIVE; - } - else - { + } else { item->window.flags |= WINDOW_INACTIVE; } } } -void UI_SetItemColor(itemDef_t *item,const char *itemname,const char *name,vec4_t color); +void UI_SetItemColor(itemDef_t *item, const char *itemname, const char *name, vec4_t color); -static void UI_SetHexPicLevel( const menuDef_t *menu,const int forcePowerI,const int powerLevel, const qboolean goldFlag ) -{ +static void UI_SetHexPicLevel(const menuDef_t *menu, const int forcePowerI, const int powerLevel, const qboolean goldFlag) { char itemName[128]; - itemDef_t *item; + itemDef_t *item; // Find proper hex picture on menu - Com_sprintf (itemName, sizeof(itemName), "%s_hexpic", powerEnums[forcePowerI].title); - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, itemName); + Com_sprintf(itemName, sizeof(itemName), "%s_hexpic", powerEnums[forcePowerI].title); + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, itemName); // Now give it the proper hex graphic - if (item) - { + if (item) { char itemGraphic[128]; - if (goldFlag) - { - Com_sprintf (itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d_gold",powerLevel >= 4 ? 3 : powerLevel); - } - else - { - Com_sprintf (itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d",powerLevel >= 4 ? 3 : powerLevel); + if (goldFlag) { + Com_sprintf(itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d_gold", powerLevel >= 4 ? 3 : powerLevel); + } else { + Com_sprintf(itemGraphic, sizeof(itemGraphic), "gfx/menus/hex_pattern_%d", powerLevel >= 4 ? 3 : powerLevel); } item->window.background = ui.R_RegisterShaderNoMip(itemGraphic); - Com_sprintf (itemName, sizeof(itemName), "%s_fbutton", powerEnums[forcePowerI].title); - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *)menu, itemName); - if (item) - { - if (goldFlag) - { + Com_sprintf(itemName, sizeof(itemName), "%s_fbutton", powerEnums[forcePowerI].title); + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, itemName); + if (item) { + if (goldFlag) { // Change description text to tell player they can decrement the force point item->descText = "@MENUS_REMOVEFP"; - } - else - { + } else { // Change description text to tell player they can increment the force point item->descText = "@MENUS_ADDFP"; } @@ -4751,141 +3929,126 @@ static void UI_SetHexPicLevel( const menuDef_t *menu,const int forcePowerI,const } } -void UI_SetItemVisible(menuDef_t *menu,const char *itemname,qboolean visible); +void UI_SetItemVisible(menuDef_t *menu, const char *itemname, qboolean visible); // if this is the first time into the force power allocation screen, show the INSTRUCTION screen -static void UI_ForceHelpActive( void ) -{ - int tier_storyinfo = Cvar_VariableIntegerValue( "tier_storyinfo" ); +static void UI_ForceHelpActive(void) { + int tier_storyinfo = Cvar_VariableIntegerValue("tier_storyinfo"); // First time, show instructions - if (tier_storyinfo==1) - { -// Menus_OpenByName("ingameForceHelp"); + if (tier_storyinfo == 1) { + // Menus_OpenByName("ingameForceHelp"); Menus_ActivateByName("ingameForceHelp"); } } #ifndef JK2_MODE // Set the force levels depending on the level chosen -static void UI_DemoSetForceLevels( void ) -{ - menuDef_t *menu; +static void UI_DemoSetForceLevels(void) { + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - char buffer[MAX_STRING_CHARS]; + char buffer[MAX_STRING_CHARS]; - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player - playerState_t* pState = NULL; - if( cl ) - { + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + playerState_t *pState = NULL; + if (cl) { pState = cl->gentity->client; } - ui.Cvar_VariableStringBuffer( "ui_demo_level", buffer, sizeof(buffer)); - if( Q_stricmp( buffer, "t1_sour")==0 ) - {// NOTE : always set the uiInfo powers + ui.Cvar_VariableStringBuffer("ui_demo_level", buffer, sizeof(buffer)); + if (Q_stricmp(buffer, "t1_sour") == 0) { // NOTE : always set the uiInfo powers // level 1 in all core powers - uiInfo.forcePowerLevel[FP_LEVITATION]=1; - uiInfo.forcePowerLevel[FP_SPEED]=1; - uiInfo.forcePowerLevel[FP_PUSH]=1; - uiInfo.forcePowerLevel[FP_PULL]=1; - uiInfo.forcePowerLevel[FP_SEE]=1; - uiInfo.forcePowerLevel[FP_SABER_OFFENSE]=1; - uiInfo.forcePowerLevel[FP_SABER_DEFENSE]=1; - uiInfo.forcePowerLevel[FP_SABERTHROW]=1; + uiInfo.forcePowerLevel[FP_LEVITATION] = 1; + uiInfo.forcePowerLevel[FP_SPEED] = 1; + uiInfo.forcePowerLevel[FP_PUSH] = 1; + uiInfo.forcePowerLevel[FP_PULL] = 1; + uiInfo.forcePowerLevel[FP_SEE] = 1; + uiInfo.forcePowerLevel[FP_SABER_OFFENSE] = 1; + uiInfo.forcePowerLevel[FP_SABER_DEFENSE] = 1; + uiInfo.forcePowerLevel[FP_SABERTHROW] = 1; // plus these extras - uiInfo.forcePowerLevel[FP_HEAL]=1; - uiInfo.forcePowerLevel[FP_TELEPATHY]=1; - uiInfo.forcePowerLevel[FP_GRIP]=1; + uiInfo.forcePowerLevel[FP_HEAL] = 1; + uiInfo.forcePowerLevel[FP_TELEPATHY] = 1; + uiInfo.forcePowerLevel[FP_GRIP] = 1; // and set the rest to zero - uiInfo.forcePowerLevel[FP_ABSORB]=0; - uiInfo.forcePowerLevel[FP_PROTECT]=0; - uiInfo.forcePowerLevel[FP_DRAIN]=0; - uiInfo.forcePowerLevel[FP_LIGHTNING]=0; - uiInfo.forcePowerLevel[FP_RAGE]=0; - } - else - { + uiInfo.forcePowerLevel[FP_ABSORB] = 0; + uiInfo.forcePowerLevel[FP_PROTECT] = 0; + uiInfo.forcePowerLevel[FP_DRAIN] = 0; + uiInfo.forcePowerLevel[FP_LIGHTNING] = 0; + uiInfo.forcePowerLevel[FP_RAGE] = 0; + } else { // level 3 in all core powers - uiInfo.forcePowerLevel[FP_LEVITATION]=3; - uiInfo.forcePowerLevel[FP_SPEED]=3; - uiInfo.forcePowerLevel[FP_PUSH]=3; - uiInfo.forcePowerLevel[FP_PULL]=3; - uiInfo.forcePowerLevel[FP_SEE]=3; - uiInfo.forcePowerLevel[FP_SABER_OFFENSE]=3; - uiInfo.forcePowerLevel[FP_SABER_DEFENSE]=3; - uiInfo.forcePowerLevel[FP_SABERTHROW]=3; + uiInfo.forcePowerLevel[FP_LEVITATION] = 3; + uiInfo.forcePowerLevel[FP_SPEED] = 3; + uiInfo.forcePowerLevel[FP_PUSH] = 3; + uiInfo.forcePowerLevel[FP_PULL] = 3; + uiInfo.forcePowerLevel[FP_SEE] = 3; + uiInfo.forcePowerLevel[FP_SABER_OFFENSE] = 3; + uiInfo.forcePowerLevel[FP_SABER_DEFENSE] = 3; + uiInfo.forcePowerLevel[FP_SABERTHROW] = 3; // plus these extras - uiInfo.forcePowerLevel[FP_HEAL]=1; - uiInfo.forcePowerLevel[FP_TELEPATHY]=1; - uiInfo.forcePowerLevel[FP_GRIP]=2; - uiInfo.forcePowerLevel[FP_LIGHTNING]=1; - uiInfo.forcePowerLevel[FP_PROTECT]=1; + uiInfo.forcePowerLevel[FP_HEAL] = 1; + uiInfo.forcePowerLevel[FP_TELEPATHY] = 1; + uiInfo.forcePowerLevel[FP_GRIP] = 2; + uiInfo.forcePowerLevel[FP_LIGHTNING] = 1; + uiInfo.forcePowerLevel[FP_PROTECT] = 1; // and set the rest to zero - uiInfo.forcePowerLevel[FP_ABSORB]=0; - uiInfo.forcePowerLevel[FP_DRAIN]=0; - uiInfo.forcePowerLevel[FP_RAGE]=0; + uiInfo.forcePowerLevel[FP_ABSORB] = 0; + uiInfo.forcePowerLevel[FP_DRAIN] = 0; + uiInfo.forcePowerLevel[FP_RAGE] = 0; } - if (pState) - {//i am carrying over from a previous level, so get the increased power! (non-core only) + if (pState) { // i am carrying over from a previous level, so get the increased power! (non-core only) uiInfo.forcePowerLevel[FP_HEAL] = Q_max(pState->forcePowerLevel[FP_HEAL], uiInfo.forcePowerLevel[FP_HEAL]); - uiInfo.forcePowerLevel[FP_TELEPATHY]=Q_max(pState->forcePowerLevel[FP_TELEPATHY], uiInfo.forcePowerLevel[FP_TELEPATHY]); - uiInfo.forcePowerLevel[FP_GRIP]=Q_max(pState->forcePowerLevel[FP_GRIP], uiInfo.forcePowerLevel[FP_GRIP]); - uiInfo.forcePowerLevel[FP_LIGHTNING]=Q_max(pState->forcePowerLevel[FP_LIGHTNING], uiInfo.forcePowerLevel[FP_LIGHTNING]); - uiInfo.forcePowerLevel[FP_PROTECT]=Q_max(pState->forcePowerLevel[FP_PROTECT], uiInfo.forcePowerLevel[FP_PROTECT]); + uiInfo.forcePowerLevel[FP_TELEPATHY] = Q_max(pState->forcePowerLevel[FP_TELEPATHY], uiInfo.forcePowerLevel[FP_TELEPATHY]); + uiInfo.forcePowerLevel[FP_GRIP] = Q_max(pState->forcePowerLevel[FP_GRIP], uiInfo.forcePowerLevel[FP_GRIP]); + uiInfo.forcePowerLevel[FP_LIGHTNING] = Q_max(pState->forcePowerLevel[FP_LIGHTNING], uiInfo.forcePowerLevel[FP_LIGHTNING]); + uiInfo.forcePowerLevel[FP_PROTECT] = Q_max(pState->forcePowerLevel[FP_PROTECT], uiInfo.forcePowerLevel[FP_PROTECT]); - uiInfo.forcePowerLevel[FP_ABSORB]=Q_max(pState->forcePowerLevel[FP_ABSORB], uiInfo.forcePowerLevel[FP_ABSORB]); - uiInfo.forcePowerLevel[FP_DRAIN]=Q_max(pState->forcePowerLevel[FP_DRAIN], uiInfo.forcePowerLevel[FP_DRAIN]); - uiInfo.forcePowerLevel[FP_RAGE]=Q_max(pState->forcePowerLevel[FP_RAGE], uiInfo.forcePowerLevel[FP_RAGE]); + uiInfo.forcePowerLevel[FP_ABSORB] = Q_max(pState->forcePowerLevel[FP_ABSORB], uiInfo.forcePowerLevel[FP_ABSORB]); + uiInfo.forcePowerLevel[FP_DRAIN] = Q_max(pState->forcePowerLevel[FP_DRAIN], uiInfo.forcePowerLevel[FP_DRAIN]); + uiInfo.forcePowerLevel[FP_RAGE] = Q_max(pState->forcePowerLevel[FP_RAGE], uiInfo.forcePowerLevel[FP_RAGE]); } } #endif // !JK2_MODE // record the force levels into a cvar so when restoring player from map transition // the force levels are set up correctly -static void UI_RecordForceLevels( void ) -{ - menuDef_t *menu; +static void UI_RecordForceLevels(void) { + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } const char *s2 = ""; int i; - for (i=0;i< NUM_FORCE_POWERS; i++) - { - s2 = va("%s %i",s2, uiInfo.forcePowerLevel[i]); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + s2 = va("%s %i", s2, uiInfo.forcePowerLevel[i]); } - Cvar_Set( "demo_playerfplvl", s2 ); - + Cvar_Set("demo_playerfplvl", s2); } // record the weapons into a cvar so when restoring player from map transition // the force levels are set up correctly -static void UI_RecordWeapons( void ) -{ - menuDef_t *menu; +static void UI_RecordWeapons(void) { + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } @@ -4893,422 +4056,355 @@ static void UI_RecordWeapons( void ) int wpns = 0; // always add blaster and saber - wpns |= (1<window.flags |= WINDOW_HASFOCUS; - if (item->onFocus) - { + if (item->onFocus) { Item_RunScript(item, item->onFocus); } } // In upgrade mode so just turn the deallocate button on - else - { - UI_SetItemVisible(menu,"force_icon",qtrue); - UI_SetItemVisible(menu,"force_desc",qtrue); - UI_SetItemVisible(menu,"deallocate_fbutton",qtrue); + else { + UI_SetItemVisible(menu, "force_icon", qtrue); + UI_SetItemVisible(menu, "force_desc", qtrue); + UI_SetItemVisible(menu, "deallocate_fbutton", qtrue); - item = (itemDef_s *) Menu_FindItemByName(menu, va("%s_fbutton",powerEnums[uiInfo.forcePowerUpdated].title)); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, va("%s_fbutton", powerEnums[uiInfo.forcePowerUpdated].title)); + if (item) { item->window.flags |= WINDOW_HASFOCUS; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - playerState_t* pState = cl->gentity->client; - + playerState_t *pState = cl->gentity->client; - if (uiInfo.forcePowerUpdated == FP_UPDATED_NONE) - { + if (uiInfo.forcePowerUpdated == FP_UPDATED_NONE) { return; } // Update level description - Com_sprintf ( - itemName, - sizeof(itemName), - "%s_level%ddesc", - powerEnums[uiInfo.forcePowerUpdated].title, - pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum] - ); - - item = (itemDef_s *) Menu_FindItemByName(menu, itemName); - if (item) - { + Com_sprintf(itemName, sizeof(itemName), "%s_level%ddesc", powerEnums[uiInfo.forcePowerUpdated].title, + pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]); + + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); + if (item) { item->window.flags |= WINDOW_VISIBLE; } } // If one was a chosen force power, high light it again. - if (uiInfo.forcePowerUpdated>FP_UPDATED_NONE) - { + if (uiInfo.forcePowerUpdated > FP_UPDATED_NONE) { char itemhexName[128]; char itemiconName[128]; - vec4_t color2 = { 1.0f, 1.0f, 1.0f, 1.0f}; + vec4_t color2 = {1.0f, 1.0f, 1.0f, 1.0f}; - Com_sprintf (itemhexName, sizeof(itemhexName), "%s_hexpic", powerEnums[uiInfo.forcePowerUpdated].title); - Com_sprintf (itemiconName, sizeof(itemiconName), "%s_iconpic", powerEnums[uiInfo.forcePowerUpdated].title); + Com_sprintf(itemhexName, sizeof(itemhexName), "%s_hexpic", powerEnums[uiInfo.forcePowerUpdated].title); + Com_sprintf(itemiconName, sizeof(itemiconName), "%s_iconpic", powerEnums[uiInfo.forcePowerUpdated].title); - UI_SetItemColor(item,itemhexName,"forecolor",color2); - UI_SetItemColor(item,itemiconName,"forecolor",color2); - } - else - { + UI_SetItemColor(item, itemhexName, "forecolor", color2); + UI_SetItemColor(item, itemiconName, "forecolor", color2); + } else { // Un-grey-out all icons - UI_SetItemColor(item,"hexpic","forecolor",color); - UI_SetItemColor(item,"iconpic","forecolor",color); + UI_SetItemColor(item, "hexpic", "forecolor", color); + UI_SetItemColor(item, "iconpic", "forecolor", color); } } // Decrement force power level (Used by Force Power Allocation screen) -static void UI_DecrementCurrentForcePower ( void ) -{ - menuDef_t *menu; - itemDef_t *item; +static void UI_DecrementCurrentForcePower(void) { + menuDef_t *menu; + itemDef_t *item; short i; - vec4_t color = { 0.65f, 0.65f, 0.65f, 1.0f}; + vec4_t color = {0.65f, 0.65f, 0.65f, 1.0f}; char itemName[128]; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player - playerState_t* pState = NULL; + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + playerState_t *pState = NULL; int forcelevel; - if( cl ) - { + if (cl) { pState = cl->gentity->client; forcelevel = pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]; - } - else - { + } else { forcelevel = uiInfo.forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]; } - if (uiInfo.forcePowerUpdated == FP_UPDATED_NONE) - { + if (uiInfo.forcePowerUpdated == FP_UPDATED_NONE) { return; } - DC->startLocalSound(uiInfo.uiDC.Assets.forceUnchosenSound, CHAN_AUTO ); + DC->startLocalSound(uiInfo.uiDC.Assets.forceUnchosenSound, CHAN_AUTO); - if (forcelevel>0) - { - if( pState ) - { - pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]--; // Decrement it + if (forcelevel > 0) { + if (pState) { + pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]--; // Decrement it forcelevel = pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]; // Turn off power if level is 0 - if (pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]<1) - { - pState->forcePowersKnown &= ~( 1 << powerEnums[uiInfo.forcePowerUpdated].powerEnum ); + if (pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum] < 1) { + pState->forcePowersKnown &= ~(1 << powerEnums[uiInfo.forcePowerUpdated].powerEnum); } - } - else - { - uiInfo.forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]--; // Decrement it + } else { + uiInfo.forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]--; // Decrement it forcelevel = uiInfo.forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]; } } - UI_SetHexPicLevel( menu,uiInfo.forcePowerUpdated,forcelevel,qfalse ); + UI_SetHexPicLevel(menu, uiInfo.forcePowerUpdated, forcelevel, qfalse); - UI_ShowForceLevelDesc ( powerEnums[uiInfo.forcePowerUpdated].title ); + UI_ShowForceLevelDesc(powerEnums[uiInfo.forcePowerUpdated].title); // We just decremented a field so turn all buttons back on // Make it so all buttons can be clicked - for (i=0;iwindow.flags |= WINDOW_VISIBLE; } } // Show point has not been allocated - UI_SetPowerTitleText( qfalse); + UI_SetPowerTitleText(qfalse); // Make weapons button inactive UI_ForcePowerWeaponsButton(qfalse); // Hide the deallocate button - item = (itemDef_s *) Menu_FindItemByName(menu, "deallocate_fbutton"); - if (item) - { - item->window.flags &= ~WINDOW_VISIBLE; // + item = (itemDef_s *)Menu_FindItemByName(menu, "deallocate_fbutton"); + if (item) { + item->window.flags &= ~WINDOW_VISIBLE; // // Un-grey-out all icons - UI_SetItemColor(item,"hexpic","forecolor",color); - UI_SetItemColor(item,"iconpic","forecolor",color); + UI_SetItemColor(item, "hexpic", "forecolor", color); + UI_SetItemColor(item, "iconpic", "forecolor", color); } - item = (itemDef_s *) Menu_FindItemByName(menu, va("%s_fbutton",powerEnums[uiInfo.forcePowerUpdated].title)); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, va("%s_fbutton", powerEnums[uiInfo.forcePowerUpdated].title)); + if (item) { item->window.flags |= WINDOW_HASFOCUS; } - uiInfo.forcePowerUpdated = FP_UPDATED_NONE; // It's as if nothing happened. + uiInfo.forcePowerUpdated = FP_UPDATED_NONE; // It's as if nothing happened. } - void Item_MouseEnter(itemDef_t *item, float x, float y); // Try to increment force power level (Used by Force Power Allocation screen) -static void UI_AffectForcePowerLevel ( const char *forceName ) -{ - short forcePowerI=0,i; - menuDef_t *menu; - itemDef_t *item; +static void UI_AffectForcePowerLevel(const char *forceName) { + short forcePowerI = 0, i; + menuDef_t *menu; + itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - if (!UI_GetForcePowerIndex ( forceName, &forcePowerI )) - { + if (!UI_GetForcePowerIndex(forceName, &forcePowerI)) { return; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player - playerState_t* pState = NULL; - int forcelevel; - if( cl ) - { + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + playerState_t *pState = NULL; + int forcelevel; + if (cl) { pState = cl->gentity->client; forcelevel = pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]; - } - else - { + } else { forcelevel = uiInfo.forcePowerLevel[powerEnums[forcePowerI].powerEnum]; } - - if (forcelevel>2) - { // Too big, can't be incremented + if (forcelevel > 2) { // Too big, can't be incremented return; } // Increment power level. - DC->startLocalSound(uiInfo.uiDC.Assets.forceChosenSound, CHAN_AUTO ); + DC->startLocalSound(uiInfo.uiDC.Assets.forceChosenSound, CHAN_AUTO); - uiInfo.forcePowerUpdated = forcePowerI; // Remember which power was updated + uiInfo.forcePowerUpdated = forcePowerI; // Remember which power was updated - if( pState ) - { - pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]++; // Increment it - pState->forcePowersKnown |= ( 1 << powerEnums[forcePowerI].powerEnum ); + if (pState) { + pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]++; // Increment it + pState->forcePowersKnown |= (1 << powerEnums[forcePowerI].powerEnum); forcelevel = pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]; - } - else - { - uiInfo.forcePowerLevel[powerEnums[forcePowerI].powerEnum]++; // Increment it + } else { + uiInfo.forcePowerLevel[powerEnums[forcePowerI].powerEnum]++; // Increment it forcelevel = uiInfo.forcePowerLevel[powerEnums[forcePowerI].powerEnum]; } - UI_SetHexPicLevel( menu,uiInfo.forcePowerUpdated,forcelevel,qtrue ); + UI_SetHexPicLevel(menu, uiInfo.forcePowerUpdated, forcelevel, qtrue); - UI_ShowForceLevelDesc ( forceName ); + UI_ShowForceLevelDesc(forceName); // A field was updated, so make it so others can't be - if (uiInfo.forcePowerUpdated>FP_UPDATED_NONE) - { - vec4_t color = { 0.25f, 0.25f, 0.25f, 1.0f}; + if (uiInfo.forcePowerUpdated > FP_UPDATED_NONE) { + vec4_t color = {0.25f, 0.25f, 0.25f, 1.0f}; char itemName[128]; // Make it so none of the other buttons can be clicked - for (i=0;iwindow.flags &= ~WINDOW_VISIBLE; } } // Show point has been allocated - UI_SetPowerTitleText ( qtrue ); + UI_SetPowerTitleText(qtrue); // Make weapons button active UI_ForcePowerWeaponsButton(qtrue); // Make user_info - Cvar_Set ( "ui_forcepower_inc", va("%d",uiInfo.forcePowerUpdated) ); + Cvar_Set("ui_forcepower_inc", va("%d", uiInfo.forcePowerUpdated)); // Just grab an item to hand it to the function. - item = (itemDef_s *) Menu_FindItemByName(menu, "deallocate_fbutton"); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, "deallocate_fbutton"); + if (item) { // Show all icons as greyed-out - UI_SetItemColor(item,"hexpic","forecolor",color); - UI_SetItemColor(item,"iconpic","forecolor",color); + UI_SetItemColor(item, "hexpic", "forecolor", color); + UI_SetItemColor(item, "iconpic", "forecolor", color); item->window.flags |= WINDOW_HASFOCUS; } } - } -static void UI_DecrementForcePowerLevel( void ) -{ - int forcePowerI = Cvar_VariableIntegerValue( "ui_forcepower_inc" ); +static void UI_DecrementForcePowerLevel(void) { + int forcePowerI = Cvar_VariableIntegerValue("ui_forcepower_inc"); // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - playerState_t* pState = cl->gentity->client; - - pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]--; // Decrement it + playerState_t *pState = cl->gentity->client; + pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]--; // Decrement it } // Show force level description that matches current player level (Used by Force Power Allocation screen) -static void UI_ShowForceLevelDesc ( const char *forceName ) -{ - short forcePowerI=0; - menuDef_t *menu; - itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu +static void UI_ShowForceLevelDesc(const char *forceName) { + short forcePowerI = 0; + menuDef_t *menu; + itemDef_t *item; + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - - if (!UI_GetForcePowerIndex ( forceName, &forcePowerI )) - { + if (!UI_GetForcePowerIndex(forceName, &forcePowerI)) { return; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - playerState_t* pState = cl->gentity->client; + playerState_t *pState = cl->gentity->client; char itemName[128]; // Update level description - Com_sprintf ( - itemName, - sizeof(itemName), - "%s_level%ddesc", - powerEnums[forcePowerI].title, - pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum] - ); + Com_sprintf(itemName, sizeof(itemName), "%s_level%ddesc", powerEnums[forcePowerI].title, pState->forcePowerLevel[powerEnums[forcePowerI].powerEnum]); - item = (itemDef_s *) Menu_FindItemByName(menu, itemName); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); + if (item) { item->window.flags |= WINDOW_VISIBLE; } - } // Reset force level powers screen to what it was before player upgraded them (Used by Force Power Allocation screen) -static void UI_ResetForceLevels ( void ) -{ +static void UI_ResetForceLevels(void) { // What force ppower had the point added to it? - if (uiInfo.forcePowerUpdated!=FP_UPDATED_NONE) - { + if (uiInfo.forcePowerUpdated != FP_UPDATED_NONE) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - playerState_t* pState = cl->gentity->client; + playerState_t *pState = cl->gentity->client; // Decrement that power pState->forcePowerLevel[powerEnums[uiInfo.forcePowerUpdated].powerEnum]--; - menuDef_t *menu; - itemDef_t *item; + menuDef_t *menu; + itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } @@ -5316,22 +4412,20 @@ static void UI_ResetForceLevels ( void ) char itemName[128]; // Make it so all buttons can be clicked - for (i=0;iwindow.flags |= WINDOW_VISIBLE; } } - UI_SetPowerTitleText( qfalse ); + UI_SetPowerTitleText(qfalse); - Com_sprintf (itemName, sizeof(itemName), "%s_fbutton", powerEnums[uiInfo.forcePowerUpdated].title); - item = (itemDef_s *) Menu_FindItemByName(menu, itemName); - if (item) - { + Com_sprintf(itemName, sizeof(itemName), "%s_fbutton", powerEnums[uiInfo.forcePowerUpdated].title); + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); + if (item) { // Change description text to tell player they can increment the force point item->descText = "@MENUS_ADDFP"; } @@ -5342,56 +4436,42 @@ static void UI_ResetForceLevels ( void ) UI_ForcePowerWeaponsButton(qfalse); } - #ifndef JK2_MODE // Set the Players known saber style -static void UI_UpdateFightingStyle ( void ) -{ - playerState_t *pState; - int fightingStyle,saberStyle; +static void UI_UpdateFightingStyle(void) { + playerState_t *pState; + int fightingStyle, saberStyle; + fightingStyle = Cvar_VariableIntegerValue("ui_newfightingstyle"); - fightingStyle = Cvar_VariableIntegerValue( "ui_newfightingstyle" ); - - if (fightingStyle == 1) - { + if (fightingStyle == 1) { saberStyle = SS_MEDIUM; - } - else if (fightingStyle == 2) - { + } else if (fightingStyle == 2) { saberStyle = SS_STRONG; - } - else if (fightingStyle == 3) - { + } else if (fightingStyle == 3) { saberStyle = SS_DUAL; - } - else if (fightingStyle == 4) - { + } else if (fightingStyle == 4) { saberStyle = SS_STAFF; - } - else // 0 is Fast + } else // 0 is Fast { saberStyle = SS_FAST; } // Get player state - client_t *cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player // No client, get out - if (cl && cl->gentity && cl->gentity->client) - { + if (cl && cl->gentity && cl->gentity->client) { pState = cl->gentity->client; - pState->saberStylesKnown |= (1<saberStylesKnown |= (1 << saberStyle); + } else // Must be at the beginning of the game so the client hasn't been created, shove data in a cvar { - Cvar_Set ( "g_fighting_style", va("%d",saberStyle) ); + Cvar_Set("g_fighting_style", va("%d", saberStyle)); } } #endif // !JK2_MODE -static void UI_ResetCharacterListBoxes( void ) -{ +static void UI_ResetCharacterListBoxes(void) { itemDef_t *item; menuDef_t *menu; @@ -5399,48 +4479,38 @@ static void UI_ResetCharacterListBoxes( void ) menu = Menus_FindByName("characterMenu"); - - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "headlistbox"); - if (item) - { - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "headlistbox"); + if (item) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "torsolistbox"); - if (item) - { - listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "torsolistbox"); + if (item) { + listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "lowerlistbox"); - if (item) - { - listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "lowerlistbox"); + if (item) { + listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "colorbox"); - if (item) - { - listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "colorbox"); + if (item) { + listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; @@ -5448,77 +4518,64 @@ static void UI_ResetCharacterListBoxes( void ) } } -static void UI_ClearInventory ( void ) -{ +static void UI_ClearInventory(void) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; // Clear out inventory for the player int i; - for (i=0;iinventory[i] = 0; } } } -static void UI_GiveInventory ( const int itemIndex, const int amount ) -{ +static void UI_GiveInventory(const int itemIndex, const int amount) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if (itemIndex < MAX_INVENTORY) - { - pState->inventory[itemIndex]=amount; + if (itemIndex < MAX_INVENTORY) { + pState->inventory[itemIndex] = amount; } } - } //. Find weapons allocation screen BEGIN button and make active/inactive -static void UI_WeaponAllocBeginButton(qboolean activeFlag) -{ - menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu +static void UI_WeaponAllocBeginButton(qboolean activeFlag) { + menuDef_t *menu; + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - int weap = Cvar_VariableIntegerValue( "weapon_menu" ); + int weap = Cvar_VariableIntegerValue("weapon_menu"); // Find begin button - itemDef_t *item; + itemDef_t *item; item = Menu_GetMatchingItemByNumber(menu, weap, "beginmission"); - if (item) - { + if (item) { // Make it active - if (activeFlag) - { + if (activeFlag) { item->window.flags &= ~WINDOW_INACTIVE; - } - else - { + } else { item->window.flags |= WINDOW_INACTIVE; } } @@ -5526,330 +4583,273 @@ static void UI_WeaponAllocBeginButton(qboolean activeFlag) // If we have both weapons and the throwable weapon, turn on the begin mission button, // otherwise, turn it off -static void UI_WeaponsSelectionsComplete( void ) -{ +static void UI_WeaponsSelectionsComplete(void) { // We need two weapons and one throwable - if (( uiInfo.selectedWeapon1 != NOWEAPON ) && - ( uiInfo.selectedWeapon2 != NOWEAPON ) && - ( uiInfo.selectedThrowWeapon != NOWEAPON )) - { - UI_WeaponAllocBeginButton(qtrue); // Turn it on - } - else - { - UI_WeaponAllocBeginButton(qfalse); // Turn it off + if ((uiInfo.selectedWeapon1 != NOWEAPON) && (uiInfo.selectedWeapon2 != NOWEAPON) && (uiInfo.selectedThrowWeapon != NOWEAPON)) { + UI_WeaponAllocBeginButton(qtrue); // Turn it on + } else { + UI_WeaponAllocBeginButton(qfalse); // Turn it off } } // if this is the first time into the weapon allocation screen, show the INSTRUCTION screen -static void UI_WeaponHelpActive( void ) -{ - int tier_storyinfo = Cvar_VariableIntegerValue( "tier_storyinfo" ); - menuDef_t *menu; +static void UI_WeaponHelpActive(void) { + int tier_storyinfo = Cvar_VariableIntegerValue("tier_storyinfo"); + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } // First time, show instructions - if (tier_storyinfo==1) - { - UI_SetItemVisible(menu,"weapon_button",qfalse); + if (tier_storyinfo == 1) { + UI_SetItemVisible(menu, "weapon_button", qfalse); - UI_SetItemVisible(menu,"inst_stuff",qtrue); + UI_SetItemVisible(menu, "inst_stuff", qtrue); } // just act like normal - else - { - UI_SetItemVisible(menu,"weapon_button",qtrue); + else { + UI_SetItemVisible(menu, "weapon_button", qtrue); - UI_SetItemVisible(menu,"inst_stuff",qfalse); + UI_SetItemVisible(menu, "inst_stuff", qfalse); } } -static void UI_InitWeaponSelect( void ) -{ +static void UI_InitWeaponSelect(void) { UI_WeaponAllocBeginButton(qfalse); uiInfo.selectedWeapon1 = NOWEAPON; uiInfo.selectedWeapon2 = NOWEAPON; uiInfo.selectedThrowWeapon = NOWEAPON; } -static void UI_ClearWeapons ( void ) -{ +static void UI_ClearWeapons(void) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; // Clear out any weapons for the player - pState->stats[ STAT_WEAPONS ] = 0; + pState->stats[STAT_WEAPONS] = 0; pState->weapon = WP_NONE; - } - } -static void UI_GiveWeapon ( const int weaponIndex ) -{ +static void UI_GiveWeapon(const int weaponIndex) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if (weaponIndexstats[ STAT_WEAPONS ] |= ( 1 << weaponIndex ); + if (weaponIndex < WP_NUM_WEAPONS) { + pState->stats[STAT_WEAPONS] |= (1 << weaponIndex); } } } -static void UI_EquipWeapon ( const int weaponIndex ) -{ +static void UI_EquipWeapon(const int weaponIndex) { // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player - if (!cl) // No client, get out + if (!cl) // No client, get out { return; } - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if (weaponIndexweapon = weaponIndex; - //force it to change - //CG_ChangeWeapon( wp ); + // force it to change + // CG_ChangeWeapon( wp ); } } } -static void UI_LoadMissionSelectMenu( const char *cvarName ) -{ +static void UI_LoadMissionSelectMenu(const char *cvarName) { int holdLevel = (int)trap_Cvar_VariableValue(cvarName); // Figure out which tier menu to load - if ((holdLevel > 0) && (holdLevel < 5)) - { - UI_LoadMenus("ui/tier1.txt",qfalse); + if ((holdLevel > 0) && (holdLevel < 5)) { + UI_LoadMenus("ui/tier1.txt", qfalse); Menus_CloseByName("ingameMissionSelect1"); - } - else if ((holdLevel > 6) && (holdLevel < 10)) - { - UI_LoadMenus("ui/tier2.txt",qfalse); + } else if ((holdLevel > 6) && (holdLevel < 10)) { + UI_LoadMenus("ui/tier2.txt", qfalse); Menus_CloseByName("ingameMissionSelect2"); - } - else if ((holdLevel > 11) && (holdLevel < 15)) - { - UI_LoadMenus("ui/tier3.txt",qfalse); + } else if ((holdLevel > 11) && (holdLevel < 15)) { + UI_LoadMenus("ui/tier3.txt", qfalse); Menus_CloseByName("ingameMissionSelect3"); } - } // Update the player weapons with the chosen weapon -static void UI_AddWeaponSelection ( const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName,const char *litIconItemName, const char *hexBackground, const char *soundfile ) -{ - itemDef_s *item, *iconItem,*litIconItem; - menuDef_t *menu; +static void UI_AddWeaponSelection(const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName, const char *litIconItemName, + const char *hexBackground, const char *soundfile) { + itemDef_s *item, *iconItem, *litIconItem; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - iconItem = (itemDef_s *) Menu_FindItemByName(menu, iconItemName ); - litIconItem = (itemDef_s *) Menu_FindItemByName(menu, litIconItemName ); + iconItem = (itemDef_s *)Menu_FindItemByName(menu, iconItemName); + litIconItem = (itemDef_s *)Menu_FindItemByName(menu, litIconItemName); const char *chosenItemName, *chosenButtonName; // has this weapon already been chosen? - if (weaponIndex == uiInfo.selectedWeapon1) - { - UI_RemoveWeaponSelection ( 1 ); + if (weaponIndex == uiInfo.selectedWeapon1) { + UI_RemoveWeaponSelection(1); return; - } - else if (weaponIndex == uiInfo.selectedWeapon2) - { - UI_RemoveWeaponSelection ( 2 ); + } else if (weaponIndex == uiInfo.selectedWeapon2) { + UI_RemoveWeaponSelection(2); return; } // See if either slot is empty - if ( uiInfo.selectedWeapon1 == NOWEAPON ) - { + if (uiInfo.selectedWeapon1 == NOWEAPON) { chosenItemName = "chosenweapon1_icon"; chosenButtonName = "chosenweapon1_button"; uiInfo.selectedWeapon1 = weaponIndex; uiInfo.selectedWeapon1AmmoIndex = ammoIndex; - memcpy( uiInfo.selectedWeapon1ItemName,hexBackground,sizeof(uiInfo.selectedWeapon1ItemName)); + memcpy(uiInfo.selectedWeapon1ItemName, hexBackground, sizeof(uiInfo.selectedWeapon1ItemName)); - //Save the lit and unlit icons for the selected weapon slot + // Save the lit and unlit icons for the selected weapon slot uiInfo.litWeapon1Icon = litIconItem->window.background; uiInfo.unlitWeapon1Icon = iconItem->window.background; uiInfo.weapon1ItemButton = uiInfo.runScriptItem; uiInfo.weapon1ItemButton->descText = "@MENUS_CLICKREMOVE"; - } - else if ( uiInfo.selectedWeapon2 == NOWEAPON ) - { + } else if (uiInfo.selectedWeapon2 == NOWEAPON) { chosenItemName = "chosenweapon2_icon"; chosenButtonName = "chosenweapon2_button"; uiInfo.selectedWeapon2 = weaponIndex; uiInfo.selectedWeapon2AmmoIndex = ammoIndex; - memcpy( uiInfo.selectedWeapon2ItemName,hexBackground,sizeof(uiInfo.selectedWeapon2ItemName)); + memcpy(uiInfo.selectedWeapon2ItemName, hexBackground, sizeof(uiInfo.selectedWeapon2ItemName)); - //Save the lit and unlit icons for the selected weapon slot + // Save the lit and unlit icons for the selected weapon slot uiInfo.litWeapon2Icon = litIconItem->window.background; uiInfo.unlitWeapon2Icon = iconItem->window.background; uiInfo.weapon2ItemButton = uiInfo.runScriptItem; uiInfo.weapon2ItemButton->descText = "@MENUS_CLICKREMOVE"; - } - else // Both slots are used, can't add it. + } else // Both slots are used, can't add it. { return; } - item = (itemDef_s *) Menu_FindItemByName(menu, chosenItemName ); - if ((item) && (iconItem)) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenItemName); + if ((item) && (iconItem)) { item->window.background = iconItem->window.background; item->window.flags |= WINDOW_VISIBLE; } // Turn on chosenweapon button so player can unchoose the weapon - item = (itemDef_s *) Menu_FindItemByName(menu, chosenButtonName ); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenButtonName); + if (item) { item->window.background = iconItem->window.background; item->window.flags |= WINDOW_VISIBLE; } // Switch hex background to be 'on' - item = (itemDef_s *) Menu_FindItemByName(menu, hexBackground ); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, hexBackground); + if (item) { item->window.foreColor[0] = 0; item->window.foreColor[1] = 1; item->window.foreColor[2] = 0; item->window.foreColor[3] = 1; - } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player // NOTE : this UIScript can now be run from outside the game, so don't // return out here, just skip this part - if (cl) - { + if (cl) { // Add weapon - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if ((weaponIndex>0) && (weaponIndexstats[ STAT_WEAPONS ] |= ( 1 << weaponIndex ); + if ((weaponIndex > 0) && (weaponIndex < WP_NUM_WEAPONS)) { + pState->stats[STAT_WEAPONS] |= (1 << weaponIndex); } // Give them ammo too - if ((ammoIndex>0) && (ammoIndexammo[ ammoIndex ] = ammoAmount; + if ((ammoIndex > 0) && (ammoIndex < AMMO_MAX)) { + pState->ammo[ammoIndex] = ammoAmount; } } } - if( soundfile ) - { - DC->startLocalSound(DC->registerSound(soundfile, qfalse), CHAN_LOCAL ); + if (soundfile) { + DC->startLocalSound(DC->registerSound(soundfile, qfalse), CHAN_LOCAL); } - UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off - - + UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off } - // Update the player weapons with the chosen weapon -static void UI_RemoveWeaponSelection ( const int weaponSelectionIndex ) -{ - itemDef_s *item; - menuDef_t *menu; - const char *chosenItemName, *chosenButtonName,*background; - int ammoIndex,weaponIndex; +static void UI_RemoveWeaponSelection(const int weaponSelectionIndex) { + itemDef_s *item; + menuDef_t *menu; + const char *chosenItemName, *chosenButtonName, *background; + int ammoIndex, weaponIndex; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu // Which item has it? - if ( weaponSelectionIndex == 1 ) - { + if (weaponSelectionIndex == 1) { chosenItemName = "chosenweapon1_icon"; chosenButtonName = "chosenweapon1_button"; background = uiInfo.selectedWeapon1ItemName; ammoIndex = uiInfo.selectedWeapon1AmmoIndex; weaponIndex = uiInfo.selectedWeapon1; - if (uiInfo.weapon1ItemButton) - { + if (uiInfo.weapon1ItemButton) { uiInfo.weapon1ItemButton->descText = "@MENUS_CLICKSELECT"; uiInfo.weapon1ItemButton = NULL; } - } - else if ( weaponSelectionIndex == 2 ) - { + } else if (weaponSelectionIndex == 2) { chosenItemName = "chosenweapon2_icon"; chosenButtonName = "chosenweapon2_button"; background = uiInfo.selectedWeapon2ItemName; ammoIndex = uiInfo.selectedWeapon2AmmoIndex; weaponIndex = uiInfo.selectedWeapon2; - if (uiInfo.weapon2ItemButton) - { + if (uiInfo.weapon2ItemButton) { uiInfo.weapon2ItemButton->descText = "@MENUS_CLICKSELECT"; uiInfo.weapon2ItemButton = NULL; } - } - else - { + } else { return; } // Reset background of upper icon - item = (itemDef_s *) Menu_FindItemByName( menu, background ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, background); + if (item) { item->window.foreColor[0] = 0.0f; item->window.foreColor[1] = 0.5f; item->window.foreColor[2] = 0.0f; @@ -5857,157 +4857,130 @@ static void UI_RemoveWeaponSelection ( const int weaponSelectionIndex ) } // Hide it icon - item = (itemDef_s *) Menu_FindItemByName( menu, chosenItemName ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenItemName); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } // Hide button - item = (itemDef_s *) Menu_FindItemByName( menu, chosenButtonName ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenButtonName); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player // NOTE : this UIScript can now be run from outside the game, so don't // return out here, just skip this part - if (cl) // No client, get out + if (cl) // No client, get out { // Remove weapon - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if ((weaponIndex>0) && (weaponIndexstats[ STAT_WEAPONS ] &= ~( 1 << weaponIndex ); + if ((weaponIndex > 0) && (weaponIndex < WP_NUM_WEAPONS)) { + pState->stats[STAT_WEAPONS] &= ~(1 << weaponIndex); } // Remove ammo too - if ((ammoIndex>0) && (ammoIndexammo[ ammoIndex ] = 0; + if ((ammoIndex > 0) && (ammoIndex < AMMO_MAX)) { // But don't take it away if the other weapon is using that ammo + if (uiInfo.selectedWeapon1AmmoIndex != uiInfo.selectedWeapon2AmmoIndex) { + pState->ammo[ammoIndex] = 0; } } } - } // Now do a little clean up - if ( weaponSelectionIndex == 1 ) - { + if (weaponSelectionIndex == 1) { uiInfo.selectedWeapon1 = NOWEAPON; - memset(uiInfo.selectedWeapon1ItemName,0,sizeof(uiInfo.selectedWeapon1ItemName)); + memset(uiInfo.selectedWeapon1ItemName, 0, sizeof(uiInfo.selectedWeapon1ItemName)); uiInfo.selectedWeapon1AmmoIndex = 0; - } - else if ( weaponSelectionIndex == 2 ) - { + } else if (weaponSelectionIndex == 2) { uiInfo.selectedWeapon2 = NOWEAPON; - memset(uiInfo.selectedWeapon2ItemName,0,sizeof(uiInfo.selectedWeapon2ItemName)); + memset(uiInfo.selectedWeapon2ItemName, 0, sizeof(uiInfo.selectedWeapon2ItemName)); uiInfo.selectedWeapon2AmmoIndex = 0; } #ifndef JK2_MODE - //FIXME hack to prevent error in jk2 by disabling - DC->startLocalSound(DC->registerSound("sound/interface/weapon_deselect.mp3", qfalse), CHAN_LOCAL ); + // FIXME hack to prevent error in jk2 by disabling + DC->startLocalSound(DC->registerSound("sound/interface/weapon_deselect.mp3", qfalse), CHAN_LOCAL); #endif - UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off - - + UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off } -static void UI_NormalWeaponSelection ( const int selectionslot ) -{ - itemDef_s *item; - menuDef_t *menu; +static void UI_NormalWeaponSelection(const int selectionslot) { + itemDef_s *item; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + menu = Menu_GetFocused(); // Get current menu + if (!menu) { return; } - if (selectionslot == 1) - { - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenweapon1_icon" ); - if (item) - { + if (selectionslot == 1) { + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenweapon1_icon"); + if (item) { item->window.background = uiInfo.unlitWeapon1Icon; } } - if (selectionslot == 2) - { - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenweapon2_icon" ); - if (item) - { + if (selectionslot == 2) { + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenweapon2_icon"); + if (item) { item->window.background = uiInfo.unlitWeapon2Icon; } } } -static void UI_HighLightWeaponSelection ( const int selectionslot ) -{ - itemDef_s *item; - menuDef_t *menu; +static void UI_HighLightWeaponSelection(const int selectionslot) { + itemDef_s *item; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + menu = Menu_GetFocused(); // Get current menu + if (!menu) { return; } - if (selectionslot == 1) - { - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenweapon1_icon" ); - if (item) - { + if (selectionslot == 1) { + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenweapon1_icon"); + if (item) { item->window.background = uiInfo.litWeapon1Icon; } } - if (selectionslot == 2) - { - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenweapon2_icon" ); - if (item) - { + if (selectionslot == 2) { + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenweapon2_icon"); + if (item) { item->window.background = uiInfo.litWeapon2Icon; } } } // Update the player throwable weapons (okay it's a bad description) with the chosen weapon -static void UI_AddThrowWeaponSelection ( const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName,const char *litIconItemName, const char *hexBackground, const char *soundfile ) -{ - itemDef_s *item, *iconItem,*litIconItem; - menuDef_t *menu; +static void UI_AddThrowWeaponSelection(const int weaponIndex, const int ammoIndex, const int ammoAmount, const char *iconItemName, const char *litIconItemName, + const char *hexBackground, const char *soundfile) { + itemDef_s *item, *iconItem, *litIconItem; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - iconItem = (itemDef_s *) Menu_FindItemByName(menu, iconItemName ); - litIconItem = (itemDef_s *) Menu_FindItemByName(menu, litIconItemName ); + iconItem = (itemDef_s *)Menu_FindItemByName(menu, iconItemName); + litIconItem = (itemDef_s *)Menu_FindItemByName(menu, litIconItemName); const char *chosenItemName, *chosenButtonName; // Has a throw weapon already been chosen? - if (uiInfo.selectedThrowWeapon!=NOWEAPON) - { + if (uiInfo.selectedThrowWeapon != NOWEAPON) { // Clicked on the selected throwable weapon - if (uiInfo.selectedThrowWeapon==weaponIndex) - { // Deselect it + if (uiInfo.selectedThrowWeapon == weaponIndex) { // Deselect it UI_RemoveThrowWeaponSelection(); } return; @@ -6019,91 +4992,78 @@ static void UI_AddThrowWeaponSelection ( const int weaponIndex, const int ammoIn uiInfo.selectedThrowWeaponAmmoIndex = ammoIndex; uiInfo.weaponThrowButton = uiInfo.runScriptItem; - if (uiInfo.weaponThrowButton) - { + if (uiInfo.weaponThrowButton) { uiInfo.weaponThrowButton->descText = "@MENUS_CLICKREMOVE"; } - memcpy( uiInfo.selectedThrowWeaponItemName,hexBackground,sizeof(uiInfo.selectedWeapon1ItemName)); + memcpy(uiInfo.selectedThrowWeaponItemName, hexBackground, sizeof(uiInfo.selectedWeapon1ItemName)); - //Save the lit and unlit icons for the selected weapon slot + // Save the lit and unlit icons for the selected weapon slot uiInfo.litThrowableIcon = litIconItem->window.background; uiInfo.unlitThrowableIcon = iconItem->window.background; - item = (itemDef_s *) Menu_FindItemByName(menu, chosenItemName ); - if ((item) && (iconItem)) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenItemName); + if ((item) && (iconItem)) { item->window.background = iconItem->window.background; item->window.flags |= WINDOW_VISIBLE; } // Turn on throwchosenweapon button so player can unchoose the weapon - item = (itemDef_s *) Menu_FindItemByName(menu, chosenButtonName ); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenButtonName); + if (item) { item->window.background = iconItem->window.background; item->window.flags |= WINDOW_VISIBLE; } // Switch hex background to be 'on' - item = (itemDef_s *) Menu_FindItemByName(menu, hexBackground ); - if (item) - { + item = (itemDef_s *)Menu_FindItemByName(menu, hexBackground); + if (item) { item->window.foreColor[0] = 0.0f; item->window.foreColor[1] = 0.0f; item->window.foreColor[2] = 1.0f; item->window.foreColor[3] = 1.0f; - } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player // NOTE : this UIScript can now be run from outside the game, so don't // return out here, just skip this part - if (cl) // No client, get out + if (cl) // No client, get out { // Add weapon - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if ((weaponIndex>0) && (weaponIndexstats[ STAT_WEAPONS ] |= ( 1 << weaponIndex ); + if ((weaponIndex > 0) && (weaponIndex < WP_NUM_WEAPONS)) { + pState->stats[STAT_WEAPONS] |= (1 << weaponIndex); } // Give them ammo too - if ((ammoIndex>0) && (ammoIndexammo[ ammoIndex ] = ammoAmount; + if ((ammoIndex > 0) && (ammoIndex < AMMO_MAX)) { + pState->ammo[ammoIndex] = ammoAmount; } } } - if( soundfile ) - { - DC->startLocalSound(DC->registerSound(soundfile, qfalse), CHAN_LOCAL ); + if (soundfile) { + DC->startLocalSound(DC->registerSound(soundfile, qfalse), CHAN_LOCAL); } - UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off - + UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off } - // Update the player weapons with the chosen throw weapon -static void UI_RemoveThrowWeaponSelection ( void ) -{ - itemDef_s *item; - menuDef_t *menu; - const char *chosenItemName, *chosenButtonName,*background; +static void UI_RemoveThrowWeaponSelection(void) { + itemDef_s *item; + menuDef_t *menu; + const char *chosenItemName, *chosenButtonName, *background; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu // Weapon not chosen - if ( uiInfo.selectedThrowWeapon == NOWEAPON ) - { + if (uiInfo.selectedThrowWeapon == NOWEAPON) { return; } @@ -6112,9 +5072,8 @@ static void UI_RemoveThrowWeaponSelection ( void ) background = uiInfo.selectedThrowWeaponItemName; // Reset background of upper icon - item = (itemDef_s *) Menu_FindItemByName( menu, background ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, background); + if (item) { item->window.foreColor[0] = 0.0f; item->window.foreColor[1] = 0.0f; item->window.foreColor[2] = 0.5f; @@ -6122,180 +5081,154 @@ static void UI_RemoveThrowWeaponSelection ( void ) } // Hide it icon - item = (itemDef_s *) Menu_FindItemByName( menu, chosenItemName ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenItemName); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } // Hide button - item = (itemDef_s *) Menu_FindItemByName( menu, chosenButtonName ); - if ( item ) - { + item = (itemDef_s *)Menu_FindItemByName(menu, chosenButtonName); + if (item) { item->window.flags &= ~WINDOW_VISIBLE; } // Get player state - client_t* cl = &svs.clients[0]; // 0 because only ever us as a player + client_t *cl = &svs.clients[0]; // 0 because only ever us as a player // NOTE : this UIScript can now be run from outside the game, so don't // return out here, just skip this part - if (cl) // No client, get out + if (cl) // No client, get out { // Remove weapon - if (cl->gentity && cl->gentity->client) - { - playerState_t* pState = cl->gentity->client; + if (cl->gentity && cl->gentity->client) { + playerState_t *pState = cl->gentity->client; - if ((uiInfo.selectedThrowWeapon>0) && (uiInfo.selectedThrowWeaponstats[ STAT_WEAPONS ] &= ~( 1 << uiInfo.selectedThrowWeapon ); + if ((uiInfo.selectedThrowWeapon > 0) && (uiInfo.selectedThrowWeapon < WP_NUM_WEAPONS)) { + pState->stats[STAT_WEAPONS] &= ~(1 << uiInfo.selectedThrowWeapon); } // Remove ammo too - if ((uiInfo.selectedThrowWeaponAmmoIndex>0) && (uiInfo.selectedThrowWeaponAmmoIndexammo[ uiInfo.selectedThrowWeaponAmmoIndex ] = 0; + if ((uiInfo.selectedThrowWeaponAmmoIndex > 0) && (uiInfo.selectedThrowWeaponAmmoIndex < AMMO_MAX)) { + pState->ammo[uiInfo.selectedThrowWeaponAmmoIndex] = 0; } - } } // Now do a little clean up uiInfo.selectedThrowWeapon = NOWEAPON; - memset(uiInfo.selectedThrowWeaponItemName,0,sizeof(uiInfo.selectedThrowWeaponItemName)); + memset(uiInfo.selectedThrowWeaponItemName, 0, sizeof(uiInfo.selectedThrowWeaponItemName)); uiInfo.selectedThrowWeaponAmmoIndex = 0; - if (uiInfo.weaponThrowButton) - { + if (uiInfo.weaponThrowButton) { uiInfo.weaponThrowButton->descText = "@MENUS_CLICKSELECT"; uiInfo.weaponThrowButton = NULL; } #ifndef JK2_MODE - //FIXME hack to prevent error in jk2 by disabling - DC->startLocalSound(DC->registerSound("sound/interface/weapon_deselect.mp3", qfalse), CHAN_LOCAL ); + // FIXME hack to prevent error in jk2 by disabling + DC->startLocalSound(DC->registerSound("sound/interface/weapon_deselect.mp3", qfalse), CHAN_LOCAL); #endif - UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off - + UI_WeaponsSelectionsComplete(); // Test to see if the mission begin button should turn on or off } -static void UI_NormalThrowSelection ( void ) -{ - itemDef_s *item; - menuDef_t *menu; +static void UI_NormalThrowSelection(void) { + itemDef_s *item; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + menu = Menu_GetFocused(); // Get current menu + if (!menu) { return; } - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenthrowweapon_icon" ); + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenthrowweapon_icon"); item->window.background = uiInfo.unlitThrowableIcon; } -static void UI_HighLightThrowSelection ( void ) -{ - itemDef_s *item; - menuDef_t *menu; +static void UI_HighLightThrowSelection(void) { + itemDef_s *item; + menuDef_t *menu; - menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + menu = Menu_GetFocused(); // Get current menu + if (!menu) { return; } - item = (itemDef_s *) Menu_FindItemByName( menu, "chosenthrowweapon_icon" ); + item = (itemDef_s *)Menu_FindItemByName(menu, "chosenthrowweapon_icon"); item->window.background = uiInfo.litThrowableIcon; } -static void UI_GetSaberCvars ( void ) -{ - Cvar_Set ( "ui_saber_type", Cvar_VariableString ( "g_saber_type" ) ); - Cvar_Set ( "ui_saber", Cvar_VariableString ( "g_saber" ) ); - Cvar_Set ( "ui_saber2", Cvar_VariableString ( "g_saber2" ) ); - Cvar_Set ( "ui_saber_color", Cvar_VariableString ( "g_saber_color" ) ); - Cvar_Set ( "ui_saber2_color", Cvar_VariableString ( "g_saber2_color" ) ); - - Cvar_Set ( "ui_newfightingstyle", "0"); +static void UI_GetSaberCvars(void) { + Cvar_Set("ui_saber_type", Cvar_VariableString("g_saber_type")); + Cvar_Set("ui_saber", Cvar_VariableString("g_saber")); + Cvar_Set("ui_saber2", Cvar_VariableString("g_saber2")); + Cvar_Set("ui_saber_color", Cvar_VariableString("g_saber_color")); + Cvar_Set("ui_saber2_color", Cvar_VariableString("g_saber2_color")); + Cvar_Set("ui_newfightingstyle", "0"); } -static void UI_ResetSaberCvars ( void ) -{ - Cvar_Set ( "g_saber_type", "single" ); - Cvar_Set ( "g_saber", "single_1" ); - Cvar_Set ( "g_saber2", "" ); +static void UI_ResetSaberCvars(void) { + Cvar_Set("g_saber_type", "single"); + Cvar_Set("g_saber", "single_1"); + Cvar_Set("g_saber2", ""); - Cvar_Set ( "ui_saber_type", "single" ); - Cvar_Set ( "ui_saber", "single_1" ); - Cvar_Set ( "ui_saber2", "" ); + Cvar_Set("ui_saber_type", "single"); + Cvar_Set("ui_saber", "single_1"); + Cvar_Set("ui_saber2", ""); } -extern qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name ); -extern qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ); -static void UI_UpdateCharacterSkin( void ) -{ +extern qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name); +extern qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName); +static void UI_UpdateCharacterSkin(void) { menuDef_t *menu; itemDef_t *item; char skin[MAX_QPATH]; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - item = (itemDef_s *) Menu_FindItemByName(menu, "character"); + item = (itemDef_s *)Menu_FindItemByName(menu, "character"); - if (!item) - { - Com_Error( ERR_FATAL, "UI_UpdateCharacterSkin: Could not find item (character) in menu (%s)", menu->window.name); + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateCharacterSkin: Could not find item (character) in menu (%s)", menu->window.name); } - Com_sprintf( skin, sizeof( skin ), "models/players/%s/|%s|%s|%s", - Cvar_VariableString ( "ui_char_model"), - Cvar_VariableString ( "ui_char_skin_head"), - Cvar_VariableString ( "ui_char_skin_torso"), - Cvar_VariableString ( "ui_char_skin_legs") - ); + Com_sprintf(skin, sizeof(skin), "models/players/%s/|%s|%s|%s", Cvar_VariableString("ui_char_model"), Cvar_VariableString("ui_char_skin_head"), + Cvar_VariableString("ui_char_skin_torso"), Cvar_VariableString("ui_char_skin_legs")); - ItemParse_model_g2skin_go( item, skin ); + ItemParse_model_g2skin_go(item, skin); } -static void UI_UpdateCharacter( qboolean changedModel ) -{ +static void UI_UpdateCharacter(qboolean changedModel) { menuDef_t *menu; itemDef_t *item; char modelPath[MAX_QPATH]; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - item = (itemDef_s *) Menu_FindItemByName(menu, "character"); + item = (itemDef_s *)Menu_FindItemByName(menu, "character"); - if (!item) - { - Com_Error( ERR_FATAL, "UI_UpdateCharacter: Could not find item (character) in menu (%s)", menu->window.name); + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateCharacter: Could not find item (character) in menu (%s)", menu->window.name); } - ItemParse_model_g2anim_go( item, ui_char_anim.string ); + ItemParse_model_g2anim_go(item, ui_char_anim.string); - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", Cvar_VariableString ( "ui_char_model" ) ); - ItemParse_asset_model_go( item, modelPath ); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", Cvar_VariableString("ui_char_model")); + ItemParse_asset_model_go(item, modelPath); - if ( changedModel ) - {//set all skins to first skin since we don't know you always have all skins - //FIXME: could try to keep the same spot in each list as you swtich models - UI_FeederSelection(FEEDER_PLAYER_SKIN_HEAD, 0, item); //fixme, this is not really the right item!! + if (changedModel) { // set all skins to first skin since we don't know you always have all skins + // FIXME: could try to keep the same spot in each list as you swtich models + UI_FeederSelection(FEEDER_PLAYER_SKIN_HEAD, 0, item); // fixme, this is not really the right item!! UI_FeederSelection(FEEDER_PLAYER_SKIN_TORSO, 0, item); UI_FeederSelection(FEEDER_PLAYER_SKIN_LEGS, 0, item); UI_FeederSelection(FEEDER_COLORCHOICES, 0, item); @@ -6303,65 +5236,52 @@ static void UI_UpdateCharacter( qboolean changedModel ) UI_UpdateCharacterSkin(); } -void UI_UpdateSaberType( void ) -{ +void UI_UpdateSaberType(void) { char sType[MAX_QPATH]; - DC->getCVarString( "ui_saber_type", sType, sizeof(sType) ); - if ( Q_stricmp( "single", sType ) == 0 || - Q_stricmp( "staff", sType ) == 0 ) - { - DC->setCVar( "ui_saber2", "" ); + DC->getCVarString("ui_saber_type", sType, sizeof(sType)); + if (Q_stricmp("single", sType) == 0 || Q_stricmp("staff", sType) == 0) { + DC->setCVar("ui_saber2", ""); } } -static void UI_UpdateSaberHilt( qboolean secondSaber ) -{ +static void UI_UpdateSaberHilt(qboolean secondSaber) { menuDef_t *menu; itemDef_t *item; char model[MAX_QPATH]; char modelPath[MAX_QPATH]; char skinPath[MAX_QPATH]; - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { + if (!menu) { return; } const char *itemName; const char *saberCvarName; - if ( secondSaber ) - { + if (secondSaber) { itemName = "saber2"; saberCvarName = "ui_saber2"; - } - else - { + } else { itemName = "saber"; saberCvarName = "ui_saber"; } - item = (itemDef_s *) Menu_FindItemByName(menu, itemName ); + item = (itemDef_s *)Menu_FindItemByName(menu, itemName); - if(!item) - { - Com_Error( ERR_FATAL, "UI_UpdateSaberHilt: Could not find item (%s) in menu (%s)", itemName, menu->window.name); - } - DC->getCVarString( saberCvarName, model, sizeof(model) ); - //read this from the sabers.cfg - if ( UI_SaberModelForSaber( model, modelPath ) ) - {//successfully found a model - ItemParse_asset_model_go( item, modelPath );//set the model - //get the customSkin, if any - //COM_StripExtension( modelPath, skinPath, sizeof(skinPath) ); - //COM_DefaultExtension( skinPath, sizeof( skinPath ), ".skin" ); - if ( UI_SaberSkinForSaber( model, skinPath ) ) - { - ItemParse_model_g2skin_go( item, skinPath );//apply the skin - } - else - { - ItemParse_model_g2skin_go( item, NULL );//apply the skin + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateSaberHilt: Could not find item (%s) in menu (%s)", itemName, menu->window.name); + } + DC->getCVarString(saberCvarName, model, sizeof(model)); + // read this from the sabers.cfg + if (UI_SaberModelForSaber(model, modelPath)) { // successfully found a model + ItemParse_asset_model_go(item, modelPath); // set the model + // get the customSkin, if any + // COM_StripExtension( modelPath, skinPath, sizeof(skinPath) ); + // COM_DefaultExtension( skinPath, sizeof( skinPath ), ".skin" ); + if (UI_SaberSkinForSaber(model, skinPath)) { + ItemParse_model_g2skin_go(item, skinPath); // apply the skin + } else { + ItemParse_model_g2skin_go(item, NULL); // apply the skin } } } @@ -6385,48 +5305,40 @@ char GoToMenu[1024]; Menus_SaveGoToMenu ================= */ -void Menus_SaveGoToMenu(const char *menuTo) -{ - memcpy(GoToMenu, menuTo, sizeof(GoToMenu)); -} +void Menus_SaveGoToMenu(const char *menuTo) { memcpy(GoToMenu, menuTo, sizeof(GoToMenu)); } /* ================= UI_CheckVid1Data ================= */ -void UI_CheckVid1Data(const char *menuTo,const char *warningMenuName) -{ +void UI_CheckVid1Data(const char *menuTo, const char *warningMenuName) { menuDef_t *menu; itemDef_t *applyChanges; - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { - Com_Printf(S_COLOR_YELLOW"WARNING: No videoMenu was found. Video data could not be checked\n"); + if (!menu) { + Com_Printf(S_COLOR_YELLOW "WARNING: No videoMenu was found. Video data could not be checked\n"); return; } - applyChanges = (itemDef_s *) Menu_FindItemByName(menu, "applyChanges"); + applyChanges = (itemDef_s *)Menu_FindItemByName(menu, "applyChanges"); - if (!applyChanges) - { -// Menus_CloseAll(); + if (!applyChanges) { + // Menus_CloseAll(); Menus_OpenByName(menuTo); return; } - if ((applyChanges->window.flags & WINDOW_VISIBLE)) // Is the APPLY CHANGES button active? - { -// Menus_SaveGoToMenu(menuTo); // Save menu you're going to -// Menus_HideItems(menu->window.name); // HIDE videMenu in case you have to come back - Menus_OpenByName(warningMenuName); // Give warning - } - else + if ((applyChanges->window.flags & WINDOW_VISIBLE)) // Is the APPLY CHANGES button active? { -// Menus_CloseAll(); -// Menus_OpenByName(menuTo); + // Menus_SaveGoToMenu(menuTo); // Save menu you're going to + // Menus_HideItems(menu->window.name); // HIDE videMenu in case you have to come back + Menus_OpenByName(warningMenuName); // Give warning + } else { + // Menus_CloseAll(); + // Menus_OpenByName(menuTo); } } @@ -6435,12 +5347,11 @@ void UI_CheckVid1Data(const char *menuTo,const char *warningMenuName) UI_ResetDefaults ================= */ -void UI_ResetDefaults( void ) -{ - ui.Cmd_ExecuteText( EXEC_APPEND, "cvar_restart\n"); +void UI_ResetDefaults(void) { + ui.Cmd_ExecuteText(EXEC_APPEND, "cvar_restart\n"); Controls_SetDefaults(); - ui.Cmd_ExecuteText( EXEC_APPEND, "exec default.cfg\n"); - ui.Cmd_ExecuteText( EXEC_APPEND, "vid_restart\n" ); + ui.Cmd_ExecuteText(EXEC_APPEND, "exec default.cfg\n"); + ui.Cmd_ExecuteText(EXEC_APPEND, "vid_restart\n"); } /* @@ -6448,18 +5359,14 @@ void UI_ResetDefaults( void ) UI_SortSaveGames ======================= */ -static int UI_SortSaveGames( const void *A, const void *B ) -{ +static int UI_SortSaveGames(const void *A, const void *B) { - const int &a = ((savedata_t*)A)->currentSaveFileDateTime; - const int &b = ((savedata_t*)B)->currentSaveFileDateTime; + const int &a = ((savedata_t *)A)->currentSaveFileDateTime; + const int &b = ((savedata_t *)B)->currentSaveFileDateTime; - if (a > b) - { + if (a > b) { return -1; - } - else - { + } else { return (a < b); } } @@ -6471,33 +5378,27 @@ UI_AdjustSaveGameListBox */ // Yeah I could get fired for this... in a world of good and bad, this is bad // I wish we passed in the menu item to RunScript(), oh well... -void UI_AdjustSaveGameListBox( int currentLine ) -{ +void UI_AdjustSaveGameListBox(int currentLine) { menuDef_t *menu; itemDef_t *item; // could be in either the ingame or shell load menu (I know, I know it's bad) menu = Menus_FindByName("loadgameMenu"); - if( !menu ) - { + if (!menu) { menu = Menus_FindByName("ingameloadMenu"); } - if (menu) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, "loadgamelist"); - if (item) - { - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; - if( listPtr ) - { + if (menu) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, "loadgamelist"); + if (item) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; + if (listPtr) { listPtr->cursorPos = currentLine; } item->cursorPos = currentLine; } } - } /* @@ -6505,64 +5406,56 @@ void UI_AdjustSaveGameListBox( int currentLine ) ReadSaveDirectory ================= */ -//JLFSAVEGAME MPNOTUSED -void ReadSaveDirectory (void) -{ - int i; - char *holdChar; - int len; - int fileCnt; +// JLFSAVEGAME MPNOTUSED +void ReadSaveDirectory(void) { + int i; + char *holdChar; + int len; + int fileCnt; // Clear out save data - memset(s_savedata,0,sizeof(s_savedata)); + memset(s_savedata, 0, sizeof(s_savedata)); s_savegame.saveFileCnt = 0; - Cvar_Set("ui_gameDesc", "" ); // Blank out comment - Cvar_Set("ui_SelectionOK", "0" ); + Cvar_Set("ui_gameDesc", ""); // Blank out comment + Cvar_Set("ui_SelectionOK", "0"); #ifdef JK2_MODE - memset( screenShotBuf,0,(SG_SCR_WIDTH * SG_SCR_HEIGHT * 4)); //blank out sshot + memset(screenShotBuf, 0, (SG_SCR_WIDTH * SG_SCR_HEIGHT * 4)); // blank out sshot #endif - // Get everything in saves directory - fileCnt = ui.FS_GetFileList("saves", ".sav", s_savegame.listBuf, LISTBUFSIZE ); + fileCnt = ui.FS_GetFileList("saves", ".sav", s_savegame.listBuf, LISTBUFSIZE); - Cvar_Set("ui_ResumeOK", "0" ); + Cvar_Set("ui_ResumeOK", "0"); holdChar = s_savegame.listBuf; - for ( i = 0; i < fileCnt; i++ ) - { + for (i = 0; i < fileCnt; i++) { // strip extension - len = strlen( holdChar ); - holdChar[len-4] = '\0'; + len = strlen(holdChar); + holdChar[len - 4] = '\0'; - if ( Q_stricmp("current",holdChar)!=0 ) - { + if (Q_stricmp("current", holdChar) != 0) { time_t result; - if (Q_stricmp("auto",holdChar)==0) - { - Cvar_Set("ui_ResumeOK", "1" ); - } - else - { // Is this a valid file??? & Get comment of file - result = ui.SG_GetSaveGameComment(holdChar, s_savedata[s_savegame.saveFileCnt].currentSaveFileComments, s_savedata[s_savegame.saveFileCnt].currentSaveFileMap); + if (Q_stricmp("auto", holdChar) == 0) { + Cvar_Set("ui_ResumeOK", "1"); + } else { // Is this a valid file??? & Get comment of file + result = ui.SG_GetSaveGameComment(holdChar, s_savedata[s_savegame.saveFileCnt].currentSaveFileComments, + s_savedata[s_savegame.saveFileCnt].currentSaveFileMap); if (result != 0) // ignore Bad save game { s_savedata[s_savegame.saveFileCnt].currentSaveFileName = holdChar; s_savedata[s_savegame.saveFileCnt].currentSaveFileDateTime = result; struct tm *localTime; - localTime = localtime( &result ); - strcpy(s_savedata[s_savegame.saveFileCnt].currentSaveFileDateTimeString,asctime( localTime ) ); + localTime = localtime(&result); + strcpy(s_savedata[s_savegame.saveFileCnt].currentSaveFileDateTimeString, asctime(localTime)); s_savegame.saveFileCnt++; - if (s_savegame.saveFileCnt == MAX_SAVELOADFILES) - { + if (s_savegame.saveFileCnt == MAX_SAVELOADFILES) { break; } } } } - holdChar += len + 1; //move to next item + holdChar += len + 1; // move to next item } - qsort( s_savedata, s_savegame.saveFileCnt, sizeof(savedata_t), UI_SortSaveGames ); - + qsort(s_savedata, s_savegame.saveFileCnt, sizeof(savedata_t), UI_SortSaveGames); } diff --git a/code/ui/ui_saber.cpp b/code/ui/ui_saber.cpp index 9da09ca3cb..a1498ac695 100644 --- a/code/ui/ui_saber.cpp +++ b/code/ui/ui_saber.cpp @@ -36,8 +36,8 @@ USER INTERFACE SABER LOADING & DISPLAY CODE #include "../ghoul2/G2.h" #define MAX_SABER_DATA_SIZE 0x80000 -char SaberParms[MAX_SABER_DATA_SIZE]; -qboolean ui_saber_parms_parsed = qfalse; +char SaberParms[MAX_SABER_DATA_SIZE]; +qboolean ui_saber_parms_parsed = qfalse; static qhandle_t redSaberGlowShader; static qhandle_t redSaberCoreShader; @@ -51,207 +51,162 @@ static qhandle_t blueSaberGlowShader; static qhandle_t blueSaberCoreShader; static qhandle_t purpleSaberGlowShader; static qhandle_t purpleSaberCoreShader; -void UI_CacheSaberGlowGraphics( void ) -{//FIXME: these get fucked by vid_restarts - redSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/red_glow" ); - redSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/red_line" ); - orangeSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/orange_glow" ); - orangeSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/orange_line" ); - yellowSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/yellow_glow" ); - yellowSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/yellow_line" ); - greenSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/green_glow" ); - greenSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/green_line" ); - blueSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/blue_glow" ); - blueSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/blue_line" ); - purpleSaberGlowShader = re.RegisterShader( "gfx/effects/sabers/purple_glow" ); - purpleSaberCoreShader = re.RegisterShader( "gfx/effects/sabers/purple_line" ); +void UI_CacheSaberGlowGraphics(void) { // FIXME: these get fucked by vid_restarts + redSaberGlowShader = re.RegisterShader("gfx/effects/sabers/red_glow"); + redSaberCoreShader = re.RegisterShader("gfx/effects/sabers/red_line"); + orangeSaberGlowShader = re.RegisterShader("gfx/effects/sabers/orange_glow"); + orangeSaberCoreShader = re.RegisterShader("gfx/effects/sabers/orange_line"); + yellowSaberGlowShader = re.RegisterShader("gfx/effects/sabers/yellow_glow"); + yellowSaberCoreShader = re.RegisterShader("gfx/effects/sabers/yellow_line"); + greenSaberGlowShader = re.RegisterShader("gfx/effects/sabers/green_glow"); + greenSaberCoreShader = re.RegisterShader("gfx/effects/sabers/green_line"); + blueSaberGlowShader = re.RegisterShader("gfx/effects/sabers/blue_glow"); + blueSaberCoreShader = re.RegisterShader("gfx/effects/sabers/blue_line"); + purpleSaberGlowShader = re.RegisterShader("gfx/effects/sabers/purple_glow"); + purpleSaberCoreShader = re.RegisterShader("gfx/effects/sabers/purple_line"); } -qboolean UI_ParseLiteral( const char **data, const char *string ) -{ - const char *token; +qboolean UI_ParseLiteral(const char **data, const char *string) { + const char *token; - token = COM_ParseExt( data, qtrue ); - if ( token[0] == 0 ) - { - ui.Printf( "unexpected EOF\n" ); + token = COM_ParseExt(data, qtrue); + if (token[0] == 0) { + ui.Printf("unexpected EOF\n"); return qtrue; } - if ( Q_stricmp( token, string ) ) - { - ui.Printf( "required string '%s' missing\n", string ); + if (Q_stricmp(token, string)) { + ui.Printf("required string '%s' missing\n", string); return qtrue; } return qfalse; } -qboolean UI_SaberParseParm( const char *saberName, const char *parmname, char *saberData ) -{ - const char *token; - const char *value; - const char *p; +qboolean UI_SaberParseParm(const char *saberName, const char *parmname, char *saberData) { + const char *token; + const char *value; + const char *p; - if ( !saberName || !saberName[0] ) - { + if (!saberName || !saberName[0]) { return qfalse; } - //try to parse it out + // try to parse it out p = SaberParms; COM_BeginParseSession(); // look for the right saber - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, saberName ) ) - { + if (!Q_stricmp(token, saberName)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return qfalse; } - if ( UI_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (UI_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return qfalse; } // parse the saber info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - ui.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", saberName ); - COM_EndParseSession( ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + ui.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", saberName); + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - if ( !Q_stricmp( token, parmname ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, parmname)) { + if (COM_ParseString(&p, &value)) { continue; } - strcpy( saberData, value ); - COM_EndParseSession( ); + strcpy(saberData, value); + COM_EndParseSession(); return qtrue; } - SkipRestOfLine( &p ); + SkipRestOfLine(&p); continue; } - COM_EndParseSession( ); + COM_EndParseSession(); return qfalse; } -qboolean UI_SaberProperNameForSaber( const char *saberName, char *saberProperName ) -{ - return UI_SaberParseParm( saberName, "name", saberProperName ); -} +qboolean UI_SaberProperNameForSaber(const char *saberName, char *saberProperName) { return UI_SaberParseParm(saberName, "name", saberProperName); } -qboolean UI_SaberModelForSaber( const char *saberName, char *saberModel ) -{ - return UI_SaberParseParm( saberName, "saberModel", saberModel ); -} +qboolean UI_SaberModelForSaber(const char *saberName, char *saberModel) { return UI_SaberParseParm(saberName, "saberModel", saberModel); } -qboolean UI_SaberSkinForSaber( const char *saberName, char *saberSkin ) -{ - return UI_SaberParseParm( saberName, "customSkin", saberSkin ); -} +qboolean UI_SaberSkinForSaber(const char *saberName, char *saberSkin) { return UI_SaberParseParm(saberName, "customSkin", saberSkin); } -qboolean UI_SaberTypeForSaber( const char *saberName, char *saberType ) -{ - return UI_SaberParseParm( saberName, "saberType", saberType ); -} +qboolean UI_SaberTypeForSaber(const char *saberName, char *saberType) { return UI_SaberParseParm(saberName, "saberType", saberType); } -int UI_SaberNumBladesForSaber( const char *saberName ) -{ - char numBladesString[8]={0}; - UI_SaberParseParm( saberName, "numBlades", numBladesString ); - int numBlades = atoi( numBladesString ); - if ( numBlades < 1 ) - { +int UI_SaberNumBladesForSaber(const char *saberName) { + char numBladesString[8] = {0}; + UI_SaberParseParm(saberName, "numBlades", numBladesString); + int numBlades = atoi(numBladesString); + if (numBlades < 1) { numBlades = 1; - } - else if ( numBlades > 8 ) - { + } else if (numBlades > 8) { numBlades = 8; } return numBlades; } -qboolean UI_SaberShouldDrawBlade( const char *saberName, int bladeNum ) -{ +qboolean UI_SaberShouldDrawBlade(const char *saberName, int bladeNum) { int bladeStyle2Start = 0, noBlade = 0; - char bladeStyle2StartString[8]={0}; - char noBladeString[8]={0}; - UI_SaberParseParm( saberName, "bladeStyle2Start", bladeStyle2StartString ); - if ( bladeStyle2StartString[0] ) - { - bladeStyle2Start = atoi( bladeStyle2StartString ); - } - if ( bladeStyle2Start - && bladeNum >= bladeStyle2Start ) - {//use second blade style - UI_SaberParseParm( saberName, "noBlade2", noBladeString ); - if ( noBladeString[0] ) - { - noBlade = atoi( noBladeString ); + char bladeStyle2StartString[8] = {0}; + char noBladeString[8] = {0}; + UI_SaberParseParm(saberName, "bladeStyle2Start", bladeStyle2StartString); + if (bladeStyle2StartString[0]) { + bladeStyle2Start = atoi(bladeStyle2StartString); + } + if (bladeStyle2Start && bladeNum >= bladeStyle2Start) { // use second blade style + UI_SaberParseParm(saberName, "noBlade2", noBladeString); + if (noBladeString[0]) { + noBlade = atoi(noBladeString); } - } - else - {//use first blade style - UI_SaberParseParm( saberName, "noBlade", noBladeString ); - if ( noBladeString[0] ) - { - noBlade = atoi( noBladeString ); + } else { // use first blade style + UI_SaberParseParm(saberName, "noBlade", noBladeString); + if (noBladeString[0]) { + noBlade = atoi(noBladeString); } } - return ((qboolean)(noBlade==0)); + return ((qboolean)(noBlade == 0)); } -float UI_SaberBladeLengthForSaber( const char *saberName, int bladeNum ) -{ - char lengthString[8]={0}; - float length = 40.0f; - UI_SaberParseParm( saberName, "saberLength", lengthString ); - if ( lengthString[0] ) - { - length = atof( lengthString ); - if ( length < 0.0f ) - { +float UI_SaberBladeLengthForSaber(const char *saberName, int bladeNum) { + char lengthString[8] = {0}; + float length = 40.0f; + UI_SaberParseParm(saberName, "saberLength", lengthString); + if (lengthString[0]) { + length = atof(lengthString); + if (length < 0.0f) { length = 0.0f; } } - UI_SaberParseParm( saberName, va("saberLength%d", bladeNum+1), lengthString ); - if ( lengthString[0] ) - { - length = atof( lengthString ); - if ( length < 0.0f ) - { + UI_SaberParseParm(saberName, va("saberLength%d", bladeNum + 1), lengthString); + if (lengthString[0]) { + length = atof(lengthString); + if (length < 0.0f) { length = 0.0f; } } @@ -259,26 +214,21 @@ float UI_SaberBladeLengthForSaber( const char *saberName, int bladeNum ) return length; } -float UI_SaberBladeRadiusForSaber( const char *saberName, int bladeNum ) -{ - char radiusString[8]={0}; - float radius = 3.0f; - UI_SaberParseParm( saberName, "saberRadius", radiusString ); - if ( radiusString[0] ) - { - radius = atof( radiusString ); - if ( radius < 0.0f ) - { +float UI_SaberBladeRadiusForSaber(const char *saberName, int bladeNum) { + char radiusString[8] = {0}; + float radius = 3.0f; + UI_SaberParseParm(saberName, "saberRadius", radiusString); + if (radiusString[0]) { + radius = atof(radiusString); + if (radius < 0.0f) { radius = 0.0f; } } - UI_SaberParseParm( saberName, va("saberRadius%d", bladeNum+1), radiusString ); - if ( radiusString[0] ) - { - radius = atof( radiusString ); - if ( radius < 0.0f ) - { + UI_SaberParseParm(saberName, va("saberRadius%d", bladeNum + 1), radiusString); + if (radiusString[0]) { + radius = atof(radiusString); + if (radius < 0.0f) { radius = 0.0f; } } @@ -286,51 +236,45 @@ float UI_SaberBladeRadiusForSaber( const char *saberName, int bladeNum ) return radius; } -void UI_SaberLoadParms( void ) -{ - int len, totallen, saberExtFNLen, fileCnt, i; - char *buffer, *holdChar, *marker; - char saberExtensionListBuf[2048]; // The list of file names read in +void UI_SaberLoadParms(void) { + int len, totallen, saberExtFNLen, fileCnt, i; + char *buffer, *holdChar, *marker; + char saberExtensionListBuf[2048]; // The list of file names read in - //ui.Printf( "UI Parsing *.sab saber definitions\n" ); + // ui.Printf( "UI Parsing *.sab saber definitions\n" ); ui_saber_parms_parsed = qtrue; UI_CacheSaberGlowGraphics(); - //set where to store the first one + // set where to store the first one totallen = 0; marker = SaberParms; marker[0] = '\0'; - //now load in the sabers - fileCnt = ui.FS_GetFileList("ext_data/sabers", ".sab", saberExtensionListBuf, sizeof(saberExtensionListBuf) ); + // now load in the sabers + fileCnt = ui.FS_GetFileList("ext_data/sabers", ".sab", saberExtensionListBuf, sizeof(saberExtensionListBuf)); holdChar = saberExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += saberExtFNLen + 1 ) - { - saberExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += saberExtFNLen + 1) { + saberExtFNLen = strlen(holdChar); - len = ui.FS_ReadFile( va( "ext_data/sabers/%s", holdChar), (void **) &buffer ); + len = ui.FS_ReadFile(va("ext_data/sabers/%s", holdChar), (void **)&buffer); - if ( len == -1 ) - { - ui.Printf( "UI_SaberLoadParms: error reading %s\n", holdChar ); - } - else - { - if ( totallen && *(marker-1) == '}' ) - {//don't let it end on a } because that should be a stand-alone token - strcat( marker, " " ); + if (len == -1) { + ui.Printf("UI_SaberLoadParms: error reading %s\n", holdChar); + } else { + if (totallen && *(marker - 1) == '}') { // don't let it end on a } because that should be a stand-alone token + strcat(marker, " "); totallen++; marker++; } - len = COM_Compress( buffer ); + len = COM_Compress(buffer); - if ( totallen + len >= MAX_SABER_DATA_SIZE ) { - Com_Error( ERR_FATAL, "UI_SaberLoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar ); + if (totallen + len >= MAX_SABER_DATA_SIZE) { + Com_Error(ERR_FATAL, "UI_SaberLoadParms: ran out of space before reading %s\n(you must make the .npc files smaller)", holdChar); } - strcat( marker, buffer ); - ui.FS_FreeFile( buffer ); + strcat(marker, buffer); + ui.FS_FreeFile(buffer); totallen += len; marker += len; @@ -338,54 +282,51 @@ void UI_SaberLoadParms( void ) } } -void UI_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color ) -{ - vec3_t mid, rgb={1,1,1}; - qhandle_t blade = 0, glow = 0; +void UI_DoSaber(vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color) { + vec3_t mid, rgb = {1, 1, 1}; + qhandle_t blade = 0, glow = 0; refEntity_t saber; float radiusmult; - if ( length < 0.5f ) - { + if (length < 0.5f) { // if the thing is so short, just forget even adding me. return; } // Find the midpoint of the saber for lighting purposes - VectorMA( origin, length * 0.5f, dir, mid ); + VectorMA(origin, length * 0.5f, dir, mid); - switch( color ) - { - case SABER_RED: - glow = redSaberGlowShader; - blade = redSaberCoreShader; - VectorSet( rgb, 1.0f, 0.2f, 0.2f ); - break; - case SABER_ORANGE: - glow = orangeSaberGlowShader; - blade = orangeSaberCoreShader; - VectorSet( rgb, 1.0f, 0.5f, 0.1f ); - break; - case SABER_YELLOW: - glow = yellowSaberGlowShader; - blade = yellowSaberCoreShader; - VectorSet( rgb, 1.0f, 1.0f, 0.2f ); - break; - case SABER_GREEN: - glow = greenSaberGlowShader; - blade = greenSaberCoreShader; - VectorSet( rgb, 0.2f, 1.0f, 0.2f ); - break; - case SABER_BLUE: - glow = blueSaberGlowShader; - blade = blueSaberCoreShader; - VectorSet( rgb, 0.2f, 0.4f, 1.0f ); - break; - case SABER_PURPLE: - glow = purpleSaberGlowShader; - blade = purpleSaberCoreShader; - VectorSet( rgb, 0.9f, 0.2f, 1.0f ); - break; + switch (color) { + case SABER_RED: + glow = redSaberGlowShader; + blade = redSaberCoreShader; + VectorSet(rgb, 1.0f, 0.2f, 0.2f); + break; + case SABER_ORANGE: + glow = orangeSaberGlowShader; + blade = orangeSaberCoreShader; + VectorSet(rgb, 1.0f, 0.5f, 0.1f); + break; + case SABER_YELLOW: + glow = yellowSaberGlowShader; + blade = yellowSaberCoreShader; + VectorSet(rgb, 1.0f, 1.0f, 0.2f); + break; + case SABER_GREEN: + glow = greenSaberGlowShader; + blade = greenSaberCoreShader; + VectorSet(rgb, 0.2f, 1.0f, 0.2f); + break; + case SABER_BLUE: + glow = blueSaberGlowShader; + blade = blueSaberCoreShader; + VectorSet(rgb, 0.2f, 0.4f, 1.0f); + break; + case SABER_PURPLE: + glow = purpleSaberGlowShader; + blade = purpleSaberCoreShader; + VectorSet(rgb, 0.9f, 0.2f, 1.0f); + break; } // always add a light because sabers cast a nice glow before they slice you in half!! or something... @@ -396,7 +337,7 @@ void UI_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float } */ - memset( &saber, 0, sizeof( refEntity_t )); + memset(&saber, 0, sizeof(refEntity_t)); // Saber glow is it's own ref type because it uses a ton of sprites, otherwise it would eat up too many // refEnts to do each glow blob individually @@ -404,453 +345,379 @@ void UI_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float // Jeff, I did this because I foolishly wished to have a bright halo as the saber is unleashed. // It's not quite what I'd hoped tho. If you have any ideas, go for it! --Pat - if (length < lengthMax ) - { - radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. - } - else - { + if (length < lengthMax) { + radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. + } else { radiusmult = 1.0; } float radiusRange = radius * 0.075f; - float radiusStart = radius-radiusRange; + float radiusStart = radius - radiusRange; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; - //saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - - VectorCopy( origin, saber.origin ); - VectorCopy( dir, saber.axis[0] ); + VectorCopy(origin, saber.origin); + VectorCopy(dir, saber.axis[0]); saber.reType = RT_SABER_GLOW; saber.customShader = glow; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; - //saber.renderfx = rfx; + // saber.renderfx = rfx; - DC->addRefEntityToScene( &saber ); + DC->addRefEntityToScene(&saber); // Do the hot core - VectorMA( origin, length, dir, saber.origin ); - VectorMA( origin, -1, dir, saber.oldorigin ); + VectorMA(origin, length, dir, saber.origin); + VectorMA(origin, -1, dir, saber.oldorigin); saber.customShader = blade; saber.reType = RT_LINE; - radiusStart = radius/3.0f; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; -// saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + radiusStart = radius / 3.0f; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - DC->addRefEntityToScene( &saber ); + DC->addRefEntityToScene(&saber); } -saber_colors_t TranslateSaberColor( const char *name ) -{ - if ( !Q_stricmp( name, "red" ) ) - { +saber_colors_t TranslateSaberColor(const char *name) { + if (!Q_stricmp(name, "red")) { return SABER_RED; } - if ( !Q_stricmp( name, "orange" ) ) - { + if (!Q_stricmp(name, "orange")) { return SABER_ORANGE; } - if ( !Q_stricmp( name, "yellow" ) ) - { + if (!Q_stricmp(name, "yellow")) { return SABER_YELLOW; } - if ( !Q_stricmp( name, "green" ) ) - { + if (!Q_stricmp(name, "green")) { return SABER_GREEN; } - if ( !Q_stricmp( name, "blue" ) ) - { + if (!Q_stricmp(name, "blue")) { return SABER_BLUE; } - if ( !Q_stricmp( name, "purple" ) ) - { + if (!Q_stricmp(name, "purple")) { return SABER_PURPLE; } - if ( !Q_stricmp( name, "random" ) ) - { - return ((saber_colors_t)(Q_irand( SABER_ORANGE, SABER_PURPLE ))); + if (!Q_stricmp(name, "random")) { + return ((saber_colors_t)(Q_irand(SABER_ORANGE, SABER_PURPLE))); } return SABER_BLUE; } -saberType_t TranslateSaberType( const char *name ) -{ - if ( !Q_stricmp( name, "SABER_SINGLE" ) ) - { +saberType_t TranslateSaberType(const char *name) { + if (!Q_stricmp(name, "SABER_SINGLE")) { return SABER_SINGLE; } - if ( !Q_stricmp( name, "SABER_STAFF" ) ) - { + if (!Q_stricmp(name, "SABER_STAFF")) { return SABER_STAFF; } - if ( !Q_stricmp( name, "SABER_BROAD" ) ) - { + if (!Q_stricmp(name, "SABER_BROAD")) { return SABER_BROAD; } - if ( !Q_stricmp( name, "SABER_PRONG" ) ) - { + if (!Q_stricmp(name, "SABER_PRONG")) { return SABER_PRONG; } - if ( !Q_stricmp( name, "SABER_DAGGER" ) ) - { + if (!Q_stricmp(name, "SABER_DAGGER")) { return SABER_DAGGER; } - if ( !Q_stricmp( name, "SABER_ARC" ) ) - { + if (!Q_stricmp(name, "SABER_ARC")) { return SABER_ARC; } - if ( !Q_stricmp( name, "SABER_SAI" ) ) - { + if (!Q_stricmp(name, "SABER_SAI")) { return SABER_SAI; } - if ( !Q_stricmp( name, "SABER_CLAW" ) ) - { + if (!Q_stricmp(name, "SABER_CLAW")) { return SABER_CLAW; } - if ( !Q_stricmp( name, "SABER_LANCE" ) ) - { + if (!Q_stricmp(name, "SABER_LANCE")) { return SABER_LANCE; } - if ( !Q_stricmp( name, "SABER_STAR" ) ) - { + if (!Q_stricmp(name, "SABER_STAR")) { return SABER_STAR; } - if ( !Q_stricmp( name, "SABER_TRIDENT" ) ) - { + if (!Q_stricmp(name, "SABER_TRIDENT")) { return SABER_TRIDENT; } - if ( !Q_stricmp( name, "SABER_SITH_SWORD" ) ) - { + if (!Q_stricmp(name, "SABER_SITH_SWORD")) { return SABER_SITH_SWORD; } return SABER_SINGLE; } -void UI_SaberDrawBlade( itemDef_t *item, char *saberName, int saberModel, saberType_t saberType, vec3_t origin, float curYaw, int bladeNum ) -{ +void UI_SaberDrawBlade(itemDef_t *item, char *saberName, int saberModel, saberType_t saberType, vec3_t origin, float curYaw, int bladeNum) { char bladeColorString[MAX_QPATH]; - vec3_t angles={0}; + vec3_t angles = {0}; - if ( item->flags&(ITF_ISANYSABER) && item->flags&(ITF_ISCHARACTER) ) - { //it's bolted to a dude! + if (item->flags & (ITF_ISANYSABER) && item->flags & (ITF_ISCHARACTER)) { // it's bolted to a dude! angles[YAW] = curYaw; - } - else - { + } else { angles[PITCH] = curYaw; angles[ROLL] = 90; } - if ( saberModel >= item->ghoul2.size() ) - {//uhh... invalid index! + if (saberModel >= item->ghoul2.size()) { // uhh... invalid index! return; } - if ( (item->flags&ITF_ISSABER) && saberModel < 2 ) - { - DC->getCVarString( "ui_saber_color", bladeColorString, sizeof(bladeColorString) ); - } - else//if ( item->flags&ITF_ISSABER2 ) - presumed + if ((item->flags & ITF_ISSABER) && saberModel < 2) { + DC->getCVarString("ui_saber_color", bladeColorString, sizeof(bladeColorString)); + } else // if ( item->flags&ITF_ISSABER2 ) - presumed { - DC->getCVarString( "ui_saber2_color", bladeColorString, sizeof(bladeColorString) ); + DC->getCVarString("ui_saber2_color", bladeColorString, sizeof(bladeColorString)); } - saber_colors_t bladeColor = TranslateSaberColor( bladeColorString ); + saber_colors_t bladeColor = TranslateSaberColor(bladeColorString); - float bladeLength = UI_SaberBladeLengthForSaber( saberName, bladeNum ); - float bladeRadius = UI_SaberBladeRadiusForSaber( saberName, bladeNum ); - vec3_t bladeOrigin={0}; - vec3_t axis[3]={}; - mdxaBone_t boltMatrix; + float bladeLength = UI_SaberBladeLengthForSaber(saberName, bladeNum); + float bladeRadius = UI_SaberBladeRadiusForSaber(saberName, bladeNum); + vec3_t bladeOrigin = {0}; + vec3_t axis[3] = {}; + mdxaBone_t boltMatrix; qboolean tagHack = qfalse; - char *tagName = va( "*blade%d", bladeNum+1 ); - int bolt = DC->g2_AddBolt( &item->ghoul2[saberModel], tagName ); + char *tagName = va("*blade%d", bladeNum + 1); + int bolt = DC->g2_AddBolt(&item->ghoul2[saberModel], tagName); - if ( bolt == -1 ) - { + if (bolt == -1) { tagHack = qtrue; - //hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models - bolt = DC->g2_AddBolt( &item->ghoul2[saberModel], "*flash" ); - if ( bolt == -1 ) - {//no tag_flash either?!! + // hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models + bolt = DC->g2_AddBolt(&item->ghoul2[saberModel], "*flash"); + if (bolt == -1) { // no tag_flash either?!! bolt = 0; } } - DC->g2_GetBoltMatrix( item->ghoul2, saberModel, bolt, &boltMatrix, angles, origin, uiInfo.uiDC.realTime, NULL, vec3_origin );//NULL was cgs.model_draw + DC->g2_GetBoltMatrix(item->ghoul2, saberModel, bolt, &boltMatrix, angles, origin, uiInfo.uiDC.realTime, NULL, vec3_origin); // NULL was cgs.model_draw // work the matrix axis stuff into the original axis and origins used. DC->g2_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, bladeOrigin); - DC->g2_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis[0]);//front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) - DC->g2_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, axis[1]);//right - DC->g2_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, axis[2]);//up + DC->g2_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis[0]); // front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) + DC->g2_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, axis[1]); // right + DC->g2_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Z, axis[2]); // up float scale = DC->xscale; - if ( tagHack ) - { - switch ( saberType ) - { + if (tagHack) { + switch (saberType) { case SABER_SINGLE: case SABER_DAGGER: case SABER_LANCE: break; case SABER_STAFF: - if ( bladeNum == 1 ) - { - VectorScale( axis[0], -1, axis[0] ); - VectorMA( bladeOrigin, 16*scale, axis[0], bladeOrigin ); + if (bladeNum == 1) { + VectorScale(axis[0], -1, axis[0]); + VectorMA(bladeOrigin, 16 * scale, axis[0], bladeOrigin); } break; case SABER_BROAD: - if ( bladeNum == 0 ) - { - VectorMA( bladeOrigin, -1*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, 1*scale, axis[1], bladeOrigin ); + if (bladeNum == 0) { + VectorMA(bladeOrigin, -1 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 1) { + VectorMA(bladeOrigin, 1 * scale, axis[1], bladeOrigin); } break; case SABER_PRONG: - if ( bladeNum == 0 ) - { - VectorMA( bladeOrigin, -3*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, 3*scale, axis[1], bladeOrigin ); + if (bladeNum == 0) { + VectorMA(bladeOrigin, -3 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 1) { + VectorMA(bladeOrigin, 3 * scale, axis[1], bladeOrigin); } break; case SABER_ARC: - VectorSubtract( axis[1], axis[2], axis[1] ); - VectorNormalize( axis[1] ); - switch ( bladeNum ) - { + VectorSubtract(axis[1], axis[2], axis[1]); + VectorNormalize(axis[1]); + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], 0.75f, axis[0] ); - VectorScale( axis[1], 0.25f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], 0.75f, axis[0]); + VectorScale(axis[1], 0.25f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 1: - VectorScale( axis[0], 0.25f, axis[0] ); - VectorScale( axis[1], 0.75f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorScale(axis[0], 0.25f, axis[0]); + VectorScale(axis[1], 0.75f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 2: - VectorMA( bladeOrigin, -8*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -0.25f, axis[0] ); - VectorScale( axis[1], 0.75f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, -8 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -0.25f, axis[0]); + VectorScale(axis[1], 0.75f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 3: - VectorMA( bladeOrigin, -16*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -0.75f, axis[0] ); - VectorScale( axis[1], 0.25f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, -16 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -0.75f, axis[0]); + VectorScale(axis[1], 0.25f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; } break; case SABER_SAI: - if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, -3*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 2 ) - { - VectorMA( bladeOrigin, 3*scale, axis[1], bladeOrigin ); + if (bladeNum == 1) { + VectorMA(bladeOrigin, -3 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 2) { + VectorMA(bladeOrigin, 3 * scale, axis[1], bladeOrigin); } break; case SABER_CLAW: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); break; case 1: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[1], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[1], bladeOrigin); break; case 2: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); - VectorMA( bladeOrigin, -2*scale, axis[1], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); + VectorMA(bladeOrigin, -2 * scale, axis[1], bladeOrigin); break; } break; case SABER_STAR: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 1: - VectorScale( axis[0], 0.33f, axis[0] ); - VectorScale( axis[2], 0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], 0.33f, axis[0]); + VectorScale(axis[2], 0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 2: - VectorScale( axis[0], -0.33f, axis[0] ); - VectorScale( axis[2], 0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -0.33f, axis[0]); + VectorScale(axis[2], 0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 3: - VectorScale( axis[0], -1, axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -1, axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 4: - VectorScale( axis[0], -0.33f, axis[0] ); - VectorScale( axis[2], -0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -0.33f, axis[0]); + VectorScale(axis[2], -0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 5: - VectorScale( axis[0], 0.33f, axis[0] ); - VectorScale( axis[2], -0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], 0.33f, axis[0]); + VectorScale(axis[2], -0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; } break; case SABER_TRIDENT: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 1: - VectorMA( bladeOrigin, -6*scale, axis[1], bladeOrigin ); - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, -6 * scale, axis[1], bladeOrigin); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 2: - VectorMA( bladeOrigin, 6*scale, axis[1], bladeOrigin ); - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 6 * scale, axis[1], bladeOrigin); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 3: - VectorMA( bladeOrigin, -32*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -1, axis[0] ); + VectorMA(bladeOrigin, -32 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -1, axis[0]); break; } break; case SABER_SITH_SWORD: - //no blade + // no blade break; default: break; } } - if ( saberType == SABER_SITH_SWORD ) - {//draw no blade + if (saberType == SABER_SITH_SWORD) { // draw no blade return; } - UI_DoSaber( bladeOrigin, axis[0], bladeLength, bladeLength, bladeRadius, bladeColor ); + UI_DoSaber(bladeOrigin, axis[0], bladeLength, bladeLength, bladeRadius, bladeColor); } -extern qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name ); -extern qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ); -void UI_GetSaberForMenu( char *saber, int saberNum ) -{ - char saberTypeString[MAX_QPATH]={0}; +extern qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name); +extern qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName); +void UI_GetSaberForMenu(char *saber, int saberNum) { + char saberTypeString[MAX_QPATH] = {0}; saberType_t saberType = SABER_NONE; - if ( saberNum == 0 ) - { - DC->getCVarString( "g_saber", saber, MAX_QPATH ); + if (saberNum == 0) { + DC->getCVarString("g_saber", saber, MAX_QPATH); + } else { + DC->getCVarString("g_saber2", saber, MAX_QPATH); } - else - { - DC->getCVarString( "g_saber2", saber, MAX_QPATH ); - } - //read this from the sabers.cfg - UI_SaberTypeForSaber( saber, saberTypeString ); - if ( saberTypeString[0] ) - { - saberType = TranslateSaberType( saberTypeString ); + // read this from the sabers.cfg + UI_SaberTypeForSaber(saber, saberTypeString); + if (saberTypeString[0]) { + saberType = TranslateSaberType(saberTypeString); } - switch ( uiInfo.movesTitleIndex ) - { - case 0://MD_ACROBATICS: + switch (uiInfo.movesTitleIndex) { + case 0: // MD_ACROBATICS: break; - case 1://MD_SINGLE_FAST: - case 2://MD_SINGLE_MEDIUM: - case 3://MD_SINGLE_STRONG: - if ( saberType != SABER_SINGLE ) - { - Q_strncpyz(saber,"single_1",MAX_QPATH); + case 1: // MD_SINGLE_FAST: + case 2: // MD_SINGLE_MEDIUM: + case 3: // MD_SINGLE_STRONG: + if (saberType != SABER_SINGLE) { + Q_strncpyz(saber, "single_1", MAX_QPATH); } break; - case 4://MD_DUAL_SABERS: - if ( saberType != SABER_SINGLE ) - { - Q_strncpyz(saber,"single_1",MAX_QPATH); + case 4: // MD_DUAL_SABERS: + if (saberType != SABER_SINGLE) { + Q_strncpyz(saber, "single_1", MAX_QPATH); } break; - case 5://MD_SABER_STAFF: - if ( saberType == SABER_SINGLE || saberType == SABER_NONE ) - { - Q_strncpyz(saber,"dual_1",MAX_QPATH); + case 5: // MD_SABER_STAFF: + if (saberType == SABER_SINGLE || saberType == SABER_NONE) { + Q_strncpyz(saber, "dual_1", MAX_QPATH); } break; } - } -void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, float curYaw ) -{ - //NOTE: only allows one saber type in view at a time +void UI_SaberDrawBlades(itemDef_t *item, vec3_t origin, float curYaw) { + // NOTE: only allows one saber type in view at a time char saber[MAX_QPATH]; int saberNum = 0; int saberModel = 0; - int numSabers = 1; + int numSabers = 1; - if ( (item->flags&ITF_ISCHARACTER)//hacked sabermoves sabers in character's hand - && uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/ ) - { + if ((item->flags & ITF_ISCHARACTER) // hacked sabermoves sabers in character's hand + && uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/) { numSabers = 2; } - for ( saberNum = 0; saberNum < numSabers; saberNum++ ) - { - if ( (item->flags&ITF_ISCHARACTER) )//hacked sabermoves sabers in character's hand + for (saberNum = 0; saberNum < numSabers; saberNum++) { + if ((item->flags & ITF_ISCHARACTER)) // hacked sabermoves sabers in character's hand { - UI_GetSaberForMenu( saber, saberNum ); + UI_GetSaberForMenu(saber, saberNum); saberModel = saberNum + 1; - } - else if ( (item->flags&ITF_ISSABER) ) - { - DC->getCVarString( "ui_saber", saber, sizeof(saber) ); + } else if ((item->flags & ITF_ISSABER)) { + DC->getCVarString("ui_saber", saber, sizeof(saber)); saberModel = 0; - } - else if ( (item->flags&ITF_ISSABER2) ) - { - DC->getCVarString( "ui_saber2", saber, sizeof(saber) ); + } else if ((item->flags & ITF_ISSABER2)) { + DC->getCVarString("ui_saber2", saber, sizeof(saber)); saberModel = 0; - } - else - { + } else { return; } - if ( saber[0] ) - { - int numBlades = UI_SaberNumBladesForSaber( saber ); - if ( numBlades ) - {//okay, here we go, time to draw each blade... - char saberTypeString[MAX_QPATH]={0}; - UI_SaberTypeForSaber( saber, saberTypeString ); - saberType_t saberType = TranslateSaberType( saberTypeString ); - for ( int curBlade = 0; curBlade < numBlades; curBlade++ ) - { - if ( UI_SaberShouldDrawBlade( saber, curBlade ) ) - { - UI_SaberDrawBlade( item, saber, saberModel, saberType, origin, curYaw, curBlade ); + if (saber[0]) { + int numBlades = UI_SaberNumBladesForSaber(saber); + if (numBlades) { // okay, here we go, time to draw each blade... + char saberTypeString[MAX_QPATH] = {0}; + UI_SaberTypeForSaber(saber, saberTypeString); + saberType_t saberType = TranslateSaberType(saberTypeString); + for (int curBlade = 0; curBlade < numBlades; curBlade++) { + if (UI_SaberShouldDrawBlade(saber, curBlade)) { + UI_SaberDrawBlade(item, saber, saberModel, saberType, origin, curYaw, curBlade); } } } @@ -858,56 +725,43 @@ void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, float curYaw ) } } -void UI_SaberAttachToChar( itemDef_t *item ) -{ - int numSabers = 1; - int saberNum = 0; +void UI_SaberAttachToChar(itemDef_t *item) { + int numSabers = 1; + int saberNum = 0; - if ( item->ghoul2.size() > 2 && item->ghoul2[2].mModelindex >=0 ) - {//remove any extra models + if (item->ghoul2.size() > 2 && item->ghoul2[2].mModelindex >= 0) { // remove any extra models DC->g2_RemoveGhoul2Model(item->ghoul2, 2); } - if ( item->ghoul2.size() > 1 && item->ghoul2[1].mModelindex >=0) - {//remove any extra models + if (item->ghoul2.size() > 1 && item->ghoul2[1].mModelindex >= 0) { // remove any extra models DC->g2_RemoveGhoul2Model(item->ghoul2, 1); } - if ( uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/ ) - { + if (uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/) { numSabers = 2; } - for ( saberNum = 0; saberNum < numSabers; saberNum++ ) - { - //bolt sabers + for (saberNum = 0; saberNum < numSabers; saberNum++) { + // bolt sabers char modelPath[MAX_QPATH]; char skinPath[MAX_QPATH]; char saber[MAX_QPATH]; - UI_GetSaberForMenu( saber, saberNum ); + UI_GetSaberForMenu(saber, saberNum); - if ( UI_SaberModelForSaber( saber, modelPath ) ) - {//successfully found a model - int g2Saber = DC->g2_InitGhoul2Model(item->ghoul2, modelPath, 0, 0, 0, 0, 0); //add the model - if (g2Saber) - { - //get the customSkin, if any - if ( UI_SaberSkinForSaber( saber, skinPath ) ) - { + if (UI_SaberModelForSaber(saber, modelPath)) { // successfully found a model + int g2Saber = DC->g2_InitGhoul2Model(item->ghoul2, modelPath, 0, 0, 0, 0, 0); // add the model + if (g2Saber) { + // get the customSkin, if any + if (UI_SaberSkinForSaber(saber, skinPath)) { int g2skin = DC->registerSkin(skinPath); - DC->g2_SetSkin( &item->ghoul2[g2Saber], 0, g2skin );//this is going to set the surfs on/off matching the skin file - } - else - { - DC->g2_SetSkin( &item->ghoul2[g2Saber], -1, 0 );//turn off custom skin + DC->g2_SetSkin(&item->ghoul2[g2Saber], 0, g2skin); // this is going to set the surfs on/off matching the skin file + } else { + DC->g2_SetSkin(&item->ghoul2[g2Saber], -1, 0); // turn off custom skin } int boltNum; - if ( saberNum == 0 ) - { + if (saberNum == 0) { boltNum = DC->g2_AddBolt(&item->ghoul2[0], "*r_hand"); - } - else - { + } else { boltNum = DC->g2_AddBolt(&item->ghoul2[0], "*l_hand"); } re.G2API_AttachG2Model(&item->ghoul2[g2Saber], &item->ghoul2[0], boltNum, 0); diff --git a/code/ui/ui_shared.cpp b/code/ui/ui_shared.cpp index 0306ba6c72..157074d7bf 100644 --- a/code/ui/ui_shared.cpp +++ b/code/ui/ui_shared.cpp @@ -30,7 +30,7 @@ along with this program; if not, see . #include "ui_local.h" -//rww - added for ui ghoul2 models +// rww - added for ui ghoul2 models #define UI_SHARED_CPP #include "../game/anims.h" @@ -41,67 +41,67 @@ along with this program; if not, see . #include "qcommon/stringed_ingame.h" -void UI_LoadMenus(const char *menuFile, qboolean reset); - -extern vmCvar_t ui_char_color_red; -extern vmCvar_t ui_char_color_green; -extern vmCvar_t ui_char_color_blue; - -void *UI_Alloc( int size ); - -void Controls_GetConfig( void ); -void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount); -void Item_Init(itemDef_t *item); -void Item_InitControls(itemDef_t *item); -qboolean Item_Parse(itemDef_t *item); -void Item_RunScript(itemDef_t *item, const char *s); -void Item_SetupKeywordHash(void); -void Item_Text_AutoWrapped_Paint(itemDef_t *item); -void Item_UpdatePosition(itemDef_t *item); -void Item_ValidateTypeData(itemDef_t *item); -void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t); -itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p); -itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char *name); -void Menu_Paint(menuDef_t *menu, qboolean forcePaint); -void Menu_SetupKeywordHash(void); -void Menus_ShowItems(const char *menuName); -qboolean ParseRect(const char **p, rectDef_t *r); -const char *String_Alloc(const char *p); -void ToWindowCoords(float *x, float *y, windowDef_t *window); -void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle); -int Item_ListBox_ThumbDrawPosition(itemDef_t *item); -int Item_ListBox_ThumbPosition(itemDef_t *item); -int Item_ListBox_MaxScroll(itemDef_t *item); -static qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) ; -static qboolean Item_Paint(itemDef_t *item, qboolean bDraw); -int Item_TextScroll_ThumbDrawPosition ( itemDef_t *item ); -static void Item_TextScroll_BuildLines ( itemDef_t* item ); - -//static qboolean debugMode = qfalse; +void UI_LoadMenus(const char *menuFile, qboolean reset); + +extern vmCvar_t ui_char_color_red; +extern vmCvar_t ui_char_color_green; +extern vmCvar_t ui_char_color_blue; + +void *UI_Alloc(int size); + +void Controls_GetConfig(void); +void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount); +void Item_Init(itemDef_t *item); +void Item_InitControls(itemDef_t *item); +qboolean Item_Parse(itemDef_t *item); +void Item_RunScript(itemDef_t *item, const char *s); +void Item_SetupKeywordHash(void); +void Item_Text_AutoWrapped_Paint(itemDef_t *item); +void Item_UpdatePosition(itemDef_t *item); +void Item_ValidateTypeData(itemDef_t *item); +void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t); +itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p); +itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char *name); +void Menu_Paint(menuDef_t *menu, qboolean forcePaint); +void Menu_SetupKeywordHash(void); +void Menus_ShowItems(const char *menuName); +qboolean ParseRect(const char **p, rectDef_t *r); +const char *String_Alloc(const char *p); +void ToWindowCoords(float *x, float *y, windowDef_t *window); +void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle); +int Item_ListBox_ThumbDrawPosition(itemDef_t *item); +int Item_ListBox_ThumbPosition(itemDef_t *item); +int Item_ListBox_MaxScroll(itemDef_t *item); +static qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y); +static qboolean Item_Paint(itemDef_t *item, qboolean bDraw); +int Item_TextScroll_ThumbDrawPosition(itemDef_t *item); +static void Item_TextScroll_BuildLines(itemDef_t *item); + +// static qboolean debugMode = qfalse; static qboolean g_waitingForKey = qfalse; static qboolean g_editingField = qfalse; static itemDef_t *g_bindItem = NULL; static itemDef_t *g_editItem = NULL; -static itemDef_t *itemCapture = NULL; // item that has the mouse captured ( if any ) +static itemDef_t *itemCapture = NULL; // item that has the mouse captured ( if any ) #define DOUBLE_CLICK_DELAY 300 static int lastListBoxClickTime = 0; -static void (*captureFunc) (void *p) = NULL; +static void (*captureFunc)(void *p) = NULL; static void *captureData = NULL; -//const char defaultString[10] = {"default"}; +// const char defaultString[10] = {"default"}; #ifdef CGAME -#define MEM_POOL_SIZE (128 * 1024) +#define MEM_POOL_SIZE (128 * 1024) #else -#define MEM_POOL_SIZE (4 * 1024 * 1024) +#define MEM_POOL_SIZE (4 * 1024 * 1024) #endif -#define SCROLL_TIME_START 500 -#define SCROLL_TIME_ADJUST 150 -#define SCROLL_TIME_ADJUSTOFFSET 40 -#define SCROLL_TIME_FLOOR 20 +#define SCROLL_TIME_START 500 +#define SCROLL_TIME_ADJUST 150 +#define SCROLL_TIME_ADJUSTOFFSET 40 +#define SCROLL_TIME_FLOOR 20 typedef struct scrollInfo_s { int nextScrollTime; @@ -116,13 +116,13 @@ typedef struct scrollInfo_s { static scrollInfo_t scrollInfo; -static char memoryPool[MEM_POOL_SIZE]; -static int allocPoint, outOfMemory; +static char memoryPool[MEM_POOL_SIZE]; +static int allocPoint, outOfMemory; displayContextDef_t *DC = NULL; -menuDef_t Menus[MAX_MENUS]; // defined menus -int menuCount = 0; // how many +menuDef_t Menus[MAX_MENUS]; // defined menus +int menuCount = 0; // how many menuDef_t *menuStack[MAX_OPEN_MENUS]; int openMenuCount = 0; @@ -140,51 +140,22 @@ typedef struct stringDef_s { static int strHandleCount = 0; static stringDef_t *strHandle[HASH_TABLE_SIZE]; -typedef struct itemFlagsDef_s { +typedef struct itemFlagsDef_s { const char *string; int value; -} itemFlagsDef_t; - -itemFlagsDef_t itemFlags [] = { - { "WINDOW_INACTIVE", WINDOW_INACTIVE }, - { NULL, 0 } -}; - -const char *styles [] = { -"WINDOW_STYLE_EMPTY", -"WINDOW_STYLE_FILLED", -"WINDOW_STYLE_GRADIENT", -"WINDOW_STYLE_SHADER", -"WINDOW_STYLE_TEAMCOLOR", -"WINDOW_STYLE_CINEMATIC", -NULL -}; - -const char *types [] = { -"ITEM_TYPE_TEXT", -"ITEM_TYPE_BUTTON", -"ITEM_TYPE_RADIOBUTTON", -"ITEM_TYPE_CHECKBOX", -"ITEM_TYPE_EDITFIELD", -"ITEM_TYPE_COMBO", -"ITEM_TYPE_LISTBOX", -"ITEM_TYPE_MODEL", -"ITEM_TYPE_OWNERDRAW", -"ITEM_TYPE_NUMERICFIELD", -"ITEM_TYPE_SLIDER", -"ITEM_TYPE_YESNO", -"ITEM_TYPE_MULTI", -"ITEM_TYPE_BIND", -"ITEM_TYPE_TEXTSCROLL", -NULL -}; - -const char *alignment [] = { -"ITEM_ALIGN_LEFT", -"ITEM_ALIGN_CENTER", -"ITEM_ALIGN_RIGHT", -NULL -}; +} itemFlagsDef_t; + +itemFlagsDef_t itemFlags[] = {{"WINDOW_INACTIVE", WINDOW_INACTIVE}, {NULL, 0}}; + +const char *styles[] = { + "WINDOW_STYLE_EMPTY", "WINDOW_STYLE_FILLED", "WINDOW_STYLE_GRADIENT", "WINDOW_STYLE_SHADER", "WINDOW_STYLE_TEAMCOLOR", "WINDOW_STYLE_CINEMATIC", NULL}; + +const char *types[] = {"ITEM_TYPE_TEXT", "ITEM_TYPE_BUTTON", "ITEM_TYPE_RADIOBUTTON", "ITEM_TYPE_CHECKBOX", + "ITEM_TYPE_EDITFIELD", "ITEM_TYPE_COMBO", "ITEM_TYPE_LISTBOX", "ITEM_TYPE_MODEL", + "ITEM_TYPE_OWNERDRAW", "ITEM_TYPE_NUMERICFIELD", "ITEM_TYPE_SLIDER", "ITEM_TYPE_YESNO", + "ITEM_TYPE_MULTI", "ITEM_TYPE_BIND", "ITEM_TYPE_TEXTSCROLL", NULL}; + +const char *alignment[] = {"ITEM_ALIGN_LEFT", "ITEM_ALIGN_CENTER", "ITEM_ALIGN_RIGHT", NULL}; /* ================== @@ -193,10 +164,7 @@ Init_Display Initializes the display with a structure to all the drawing routines ================== */ -void Init_Display(displayContextDef_t *dc) -{ - DC = dc; -} +void Init_Display(displayContextDef_t *dc) { DC = dc; } /* ================== @@ -206,8 +174,7 @@ Initializes a window structure ( windowDef_t ) with defaults ================== */ -void Window_Init(Window *w) -{ +void Window_Init(Window *w) { memset(w, 0, sizeof(windowDef_t)); w->borderSize = 1; w->foreColor[0] = w->foreColor[1] = w->foreColor[2] = w->foreColor[3] = 1.0; @@ -219,16 +186,15 @@ void Window_Init(Window *w) PC_SourceError ================= */ -void PC_SourceError(int handle, char *format, ...) -{ +void PC_SourceError(int handle, char *format, ...) { int line; char filename[128]; va_list argptr; static char string[4096]; - va_start (argptr, format); - Q_vsnprintf (string, sizeof(string), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(string, sizeof(string), format, argptr); + va_end(argptr); filename[0] = '\0'; line = 0; @@ -236,24 +202,21 @@ void PC_SourceError(int handle, char *format, ...) Com_Printf(S_COLOR_RED "ERROR: %s, line %d: %s\n", filename, line, string); } - /* ================= PC_ParseStringMem ================= */ -qboolean PC_ParseStringMem(const char **out) -{ +qboolean PC_ParseStringMem(const char **out) { const char *temp; - if (PC_ParseString(&temp)) - { + if (PC_ParseString(&temp)) { return qfalse; } *(out) = String_Alloc(temp); - return qtrue; + return qtrue; } /* @@ -261,16 +224,11 @@ qboolean PC_ParseStringMem(const char **out) PC_ParseRect ================= */ -qboolean PC_ParseRect(rectDef_t *r) -{ - if (!PC_ParseFloat(&r->x)) - { - if (!PC_ParseFloat(&r->y)) - { - if (!PC_ParseFloat(&r->w)) - { - if (!PC_ParseFloat(&r->h)) - { +qboolean PC_ParseRect(rectDef_t *r) { + if (!PC_ParseFloat(&r->x)) { + if (!PC_ParseFloat(&r->y)) { + if (!PC_ParseFloat(&r->w)) { + if (!PC_ParseFloat(&r->h)) { return qtrue; } } @@ -279,53 +237,44 @@ qboolean PC_ParseRect(rectDef_t *r) return qfalse; } - /* ================= PC_Script_Parse ================= */ -qboolean PC_Script_Parse(const char **out) -{ +qboolean PC_Script_Parse(const char **out) { char script[4096]; -// pc_token_t token; + // pc_token_t token; char *token2; - script[0]=0; + script[0] = 0; // scripts start with { and have ; separated command lists.. commands are command, arg.. // basically we want everything between the { } as it will be interpreted at run time token2 = PC_ParseExt(); - if (!token2) - { + if (!token2) { return qfalse; } - if (*token2 !='{') - { - return qfalse; + if (*token2 != '{') { + return qfalse; } - while ( 1 ) - { + while (1) { token2 = PC_ParseExt(); - if (!token2) - { + if (!token2) { return qfalse; } - if (*token2 =='}') // End of the script? + if (*token2 == '}') // End of the script? { *out = String_Alloc(script); return qtrue; } - if (*(token2 +1) != '\0') - { + if (*(token2 + 1) != '\0') { Q_strcat(script, sizeof(script), va("\"%s\"", token2)); - } - else - { + } else { Q_strcat(script, sizeof(script), token2); } Q_strcat(script, sizeof(script), " "); @@ -341,43 +290,37 @@ qboolean PC_Script_Parse(const char **out) MenuParse_font ================= */ -qboolean MenuParse_font( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_font(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_ParseStringMem(&menu->font)) - { + if (!PC_ParseStringMem(&menu->font)) { return qfalse; } - if (!DC->Assets.fontRegistered) - { + if (!DC->Assets.fontRegistered) { DC->Assets.qhMediumFont = DC->registerFont(menu->font); DC->Assets.fontRegistered = qtrue; } return qtrue; } - /* ================= MenuParse_name ================= */ -qboolean MenuParse_name(itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_name(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_ParseStringMem((const char **) &menu->window.name)) - { + if (!PC_ParseStringMem((const char **)&menu->window.name)) { return qfalse; } -// if (Q_stricmp(menu->window.name, "main") == 0) -// { - // default main as having focus -// menu->window.flags |= WINDOW_HASFOCUS; -// } + // if (Q_stricmp(menu->window.name, "main") == 0) + // { + // default main as having focus + // menu->window.flags |= WINDOW_HASFOCUS; + // } return qtrue; } @@ -387,12 +330,10 @@ MenuParse_fullscreen ================= */ -qboolean MenuParse_fullscreen( itemDef_t *item ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fullscreen(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt((int *) &menu->fullScreen)) - { + if (PC_ParseInt((int *)&menu->fullScreen)) { return qfalse; } return qtrue; @@ -404,12 +345,10 @@ MenuParse_rect ================= */ -qboolean MenuParse_rect( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_rect(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_ParseRect(&menu->window.rect)) - { + if (!PC_ParseRect(&menu->window.rect)) { return qfalse; } return qtrue; @@ -420,53 +359,44 @@ qboolean MenuParse_rect( itemDef_t *item) MenuParse_style ================= */ -qboolean MenuParse_style( itemDef_t *item) -{ - int i; - const char *tempStr; - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_style(itemDef_t *item) { + int i; + const char *tempStr; + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (styles[i]) - { - if (Q_stricmp(tempStr,styles[i])==0) - { + i = 0; + while (styles[i]) { + if (Q_stricmp(tempStr, styles[i]) == 0) { menu->window.style = i; break; } i++; } - if (styles[i] == NULL) - { - PC_ParseWarning(va("Unknown menu style value '%s'",tempStr)); + if (styles[i] == NULL) { + PC_ParseWarning(va("Unknown menu style value '%s'", tempStr)); } return qtrue; } - /* ================= MenuParse_visible ================= */ -qboolean MenuParse_visible( itemDef_t *item ) -{ +qboolean MenuParse_visible(itemDef_t *item) { int i; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&i)) - { + if (PC_ParseInt(&i)) { return qfalse; } - if (i) - { + if (i) { menu->window.flags |= WINDOW_VISIBLE; } return qtrue; @@ -477,18 +407,15 @@ qboolean MenuParse_visible( itemDef_t *item ) MenuParse_ignoreescape ================= */ -qboolean MenuParse_ignoreescape( itemDef_t *item ) -{ +qboolean MenuParse_ignoreescape(itemDef_t *item) { int i; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&i)) - { + if (PC_ParseInt(&i)) { return qfalse; } - if (i) - { + if (i) { menu->window.flags |= WINDOW_IGNORE_ESCAPE; } return qtrue; @@ -499,12 +426,10 @@ qboolean MenuParse_ignoreescape( itemDef_t *item ) MenuParse_onOpen ================= */ -qboolean MenuParse_onOpen( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onOpen(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Script_Parse(&menu->onOpen)) - { + if (!PC_Script_Parse(&menu->onOpen)) { return qfalse; } return qtrue; @@ -515,63 +440,53 @@ qboolean MenuParse_onOpen( itemDef_t *item) MenuParse_onClose ================= */ -qboolean MenuParse_onClose( itemDef_t *item ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onClose(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Script_Parse(&menu->onClose)) - { + if (!PC_Script_Parse(&menu->onClose)) { return qfalse; } return qtrue; } -//JLFACCEPT MPMOVED +// JLFACCEPT MPMOVED /* ================= MenuParse_onAccept ================= */ -qboolean MenuParse_onAccept( itemDef_t *item ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onAccept(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Script_Parse(&menu->onAccept)) - { + if (!PC_Script_Parse(&menu->onAccept)) { return qfalse; } return qtrue; } - /* ================= MenuParse_onESC ================= */ -qboolean MenuParse_onESC( itemDef_t *item ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onESC(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Script_Parse(&menu->onESC)) - { + if (!PC_Script_Parse(&menu->onESC)) { return qfalse; } return qtrue; } - /* ================= MenuParse_border ================= */ -qboolean MenuParse_border( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_border(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->window.border)) - { + if (PC_ParseInt(&menu->window.border)) { return qfalse; } return qtrue; @@ -582,12 +497,10 @@ qboolean MenuParse_border( itemDef_t *item) MenuParse_borderSize ================= */ -qboolean MenuParse_borderSize( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_borderSize(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseFloat(&menu->window.borderSize)) - { + if (PC_ParseFloat(&menu->window.borderSize)) { return qfalse; } return qtrue; @@ -598,19 +511,16 @@ qboolean MenuParse_borderSize( itemDef_t *item) MenuParse_backcolor ================= */ -qboolean MenuParse_backcolor( itemDef_t *item ) -{ +qboolean MenuParse_backcolor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - menu->window.backColor[i] = f; + menu->window.backColor[i] = f; } return qtrue; } @@ -620,24 +530,20 @@ qboolean MenuParse_backcolor( itemDef_t *item ) MenuParse_forecolor ================= */ -qboolean MenuParse_forecolor( itemDef_t *item) -{ +qboolean MenuParse_forecolor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - if (f < 0) - { //special case for player color + if (f < 0) { // special case for player color menu->window.flags |= WINDOW_PLAYERCOLOR; return qtrue; } - menu->window.foreColor[i] = f; + menu->window.foreColor[i] = f; menu->window.flags |= WINDOW_FORECOLORSET; } return qtrue; @@ -648,19 +554,16 @@ qboolean MenuParse_forecolor( itemDef_t *item) MenuParse_bordercolor ================= */ -qboolean MenuParse_bordercolor( itemDef_t *item ) -{ +qboolean MenuParse_bordercolor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - menu->window.borderColor[i] = f; + menu->window.borderColor[i] = f; } return qtrue; } @@ -670,72 +573,59 @@ qboolean MenuParse_bordercolor( itemDef_t *item ) MenuParse_focuscolor ================= */ -qboolean MenuParse_focuscolor( itemDef_t *item) -{ +qboolean MenuParse_focuscolor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - menu->focusColor[i] = f; + menu->focusColor[i] = f; } return qtrue; } - /* ================= MenuParse_focuscolor ================= */ -qboolean MenuParse_appearanceIncrement( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_appearanceIncrement(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseFloat(&menu->appearanceIncrement)) - { + if (PC_ParseFloat(&menu->appearanceIncrement)) { return qfalse; } return qtrue; } - - /* ================= MenuParse_descAlignment ================= */ -qboolean MenuParse_descAlignment( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descAlignment(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; const char *tempStr; - int i; + int i; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (alignment[i]) - { - if (Q_stricmp(tempStr,alignment[i])==0) - { + i = 0; + while (alignment[i]) { + if (Q_stricmp(tempStr, alignment[i]) == 0) { menu->descAlignment = i; break; } i++; } - if (alignment[i] == NULL) - { - PC_ParseWarning(va("Unknown desc alignment value '%s'",tempStr)); + if (alignment[i] == NULL) { + PC_ParseWarning(va("Unknown desc alignment value '%s'", tempStr)); } return qtrue; @@ -746,12 +636,10 @@ qboolean MenuParse_descAlignment( itemDef_t *item) MenuParse_descTextStyle ================= */ -qboolean MenuParse_descTextStyle( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descTextStyle(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->descTextStyle)) - { + if (PC_ParseInt(&menu->descTextStyle)) { return qfalse; } return qtrue; @@ -761,12 +649,10 @@ qboolean MenuParse_descTextStyle( itemDef_t *item) MenuParse_descX ================= */ -qboolean MenuParse_descX( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descX(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->descX)) - { + if (PC_ParseInt(&menu->descX)) { return qfalse; } return qtrue; @@ -777,29 +663,24 @@ qboolean MenuParse_descX( itemDef_t *item) MenuParse_descY ================= */ -qboolean MenuParse_descY( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descY(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->descY)) - { + if (PC_ParseInt(&menu->descY)) { return qfalse; } return qtrue; } - /* ================= MenuParse_descScale ================= */ -qboolean MenuParse_descScale( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descScale(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseFloat(&menu->descScale)) - { + if (PC_ParseFloat(&menu->descScale)) { return qfalse; } return qtrue; @@ -810,19 +691,16 @@ qboolean MenuParse_descScale( itemDef_t *item) MenuParse_descColor ================= */ -qboolean MenuParse_descColor( itemDef_t *item) -{ +qboolean MenuParse_descColor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - menu->descColor[i] = f; + menu->descColor[i] = f; } return qtrue; } @@ -832,35 +710,29 @@ qboolean MenuParse_descColor( itemDef_t *item) MenuParse_disablecolor ================= */ -qboolean MenuParse_disablecolor( itemDef_t *item) -{ +qboolean MenuParse_disablecolor(itemDef_t *item) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - menu->disableColor[i] = f; + menu->disableColor[i] = f; } return qtrue; } - /* ================= MenuParse_outlinecolor ================= */ -qboolean MenuParse_outlinecolor( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_outlinecolor(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseColor(&menu->window.outlineColor)) - { + if (PC_ParseColor(&menu->window.outlineColor)) { return qfalse; } return qtrue; @@ -871,13 +743,11 @@ qboolean MenuParse_outlinecolor( itemDef_t *item) MenuParse_background ================= */ -qboolean MenuParse_background( itemDef_t *item) -{ +qboolean MenuParse_background(itemDef_t *item) { const char *buff; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseString(&buff)) - { + if (PC_ParseString(&buff)) { return qfalse; } @@ -890,12 +760,10 @@ qboolean MenuParse_background( itemDef_t *item) MenuParse_cinematic ================= */ -qboolean MenuParse_cinematic( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_cinematic(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_ParseStringMem((const char **) &menu->window.cinematicName)) - { + if (!PC_ParseStringMem((const char **)&menu->window.cinematicName)) { return qfalse; } return qtrue; @@ -906,13 +774,11 @@ qboolean MenuParse_cinematic( itemDef_t *item) MenuParse_ownerdrawFlag ================= */ -qboolean MenuParse_ownerdrawFlag( itemDef_t *item) -{ +qboolean MenuParse_ownerdrawFlag(itemDef_t *item) { int i; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&i)) - { + if (PC_ParseInt(&i)) { return qfalse; } menu->window.ownerDrawFlags |= i; @@ -924,39 +790,33 @@ qboolean MenuParse_ownerdrawFlag( itemDef_t *item) MenuParse_ownerdraw ================= */ -qboolean MenuParse_ownerdraw( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_ownerdraw(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->window.ownerDraw)) - { + if (PC_ParseInt(&menu->window.ownerDraw)) { return qfalse; } return qtrue; } - /* ================= MenuParse_popup ================= */ -qboolean MenuParse_popup( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_popup(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; menu->window.flags |= WINDOW_POPUP; return qtrue; } - /* ================= MenuParse_outOfBounds ================= */ -qboolean MenuParse_outOfBounds( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_outOfBounds(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; menu->window.flags |= WINDOW_OOB_CLICK; return qtrue; @@ -967,12 +827,10 @@ qboolean MenuParse_outOfBounds( itemDef_t *item) MenuParse_soundLoop ================= */ -qboolean MenuParse_soundLoop( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_soundLoop(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_ParseStringMem((const char **) &menu->soundName)) - { + if (!PC_ParseStringMem((const char **)&menu->soundName)) { return qfalse; } return qtrue; @@ -983,12 +841,10 @@ qboolean MenuParse_soundLoop( itemDef_t *item) MenuParse_fadeClamp ================ */ -qboolean MenuParse_fadeClamp( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeClamp(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseFloat(&menu->fadeClamp)) - { + if (PC_ParseFloat(&menu->fadeClamp)) { return qfalse; } return qtrue; @@ -999,29 +855,24 @@ qboolean MenuParse_fadeClamp( itemDef_t *item) MenuParse_fadeAmount ================ */ -qboolean MenuParse_fadeAmount( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeAmount(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseFloat(&menu->fadeAmount)) - { + if (PC_ParseFloat(&menu->fadeAmount)) { return qfalse; } return qtrue; } - /* ================ MenuParse_fadeCycle ================ */ -qboolean MenuParse_fadeCycle( itemDef_t *item) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeCycle(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; - if (PC_ParseInt(&menu->fadeCycle)) - { + if (PC_ParseInt(&menu->fadeCycle)) { return qfalse; } return qtrue; @@ -1033,48 +884,44 @@ Item_ApplyHacks Hacks to fix issues with Team Arena menu scripts =============== */ -static void Item_ApplyHacks( itemDef_t *item ) { -#if !defined(_WIN32) || ( defined(_WIN32) && defined(idx64) ) +static void Item_ApplyHacks(itemDef_t *item) { +#if !defined(_WIN32) || (defined(_WIN32) && defined(idx64)) // Fix length of favorite address in createfavorite.menu - if ( item->type == ITEM_TYPE_MULTI && item->cvar && !Q_stricmp( item->cvar, "s_UseOpenAL" ) ) { - if( item->parent ) - { + if (item->type == ITEM_TYPE_MULTI && item->cvar && !Q_stricmp(item->cvar, "s_UseOpenAL")) { + if (item->parent) { menuDef_t *parent = (menuDef_t *)item->parent; - VectorSet4( parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f ); + VectorSet4(parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f); item->disabled = qtrue; // Just in case it had focus item->window.flags &= ~WINDOW_MOUSEOVER; - Com_Printf( "Disabling eax field because current platform does not support EAX.\n"); + Com_Printf("Disabling eax field because current platform does not support EAX.\n"); } } - - if ( item->type == ITEM_TYPE_TEXT && item->window.name && !Q_stricmp( item->window.name, "eax_icon") && item->cvarTest && !Q_stricmp( item->cvarTest, "s_UseOpenAL" ) && item->enableCvar && (item->cvarFlags & CVAR_HIDE) ) { - if( item->parent ) - { + + if (item->type == ITEM_TYPE_TEXT && item->window.name && !Q_stricmp(item->window.name, "eax_icon") && item->cvarTest && + !Q_stricmp(item->cvarTest, "s_UseOpenAL") && item->enableCvar && (item->cvarFlags & CVAR_HIDE)) { + if (item->parent) { menuDef_t *parent = (menuDef_t *)item->parent; - VectorSet4( parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f ); + VectorSet4(parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f); item->disabled = item->disabledHidden = qtrue; // Just in case it had focus item->window.flags &= ~WINDOW_MOUSEOVER; - Com_Printf( "Hiding eax_icon object because current platform does not support EAX.\n"); + Com_Printf("Hiding eax_icon object because current platform does not support EAX.\n"); } } #endif - if ( item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp( item->window.name, "sound_quality") ) { + if (item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp(item->window.name, "sound_quality")) { multiDef_t *multiPtr = (multiDef_t *)item->typeData; int i; qboolean found = qfalse; - for( i = 0; i < multiPtr->count; i++ ) - { - if ( multiPtr->cvarValue[i] == 44 ) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->cvarValue[i] == 44) { found = qtrue; break; } } - if ( !found && multiPtr->count < MAX_MULTI_CVARS ) - { + if (!found && multiPtr->count < MAX_MULTI_CVARS) { #ifdef JK2_MODE multiPtr->cvarList[multiPtr->count] = String_Alloc("@MENUS0_VERY_HIGH"); #else @@ -1082,24 +929,21 @@ static void Item_ApplyHacks( itemDef_t *item ) { #endif multiPtr->cvarValue[multiPtr->count] = 44; multiPtr->count++; - Com_Printf( "Extended sound quality field to contain very high option.\n"); + Com_Printf("Extended sound quality field to contain very high option.\n"); } } - - if ( item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp( item->window.name, "voice") && item->cvar && !Q_stricmp( item->cvar, "g_subtitles" ) ) { + + if (item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp(item->window.name, "voice") && item->cvar && !Q_stricmp(item->cvar, "g_subtitles")) { multiDef_t *multiPtr = (multiDef_t *)item->typeData; int i; qboolean found = qfalse; - for( i = 0; i < multiPtr->count; i++ ) - { - if ( multiPtr->cvarValue[i] == 1 ) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->cvarValue[i] == 1) { found = qtrue; break; } } - if ( !found && multiPtr->count < MAX_MULTI_CVARS ) - { + if (!found && multiPtr->count < MAX_MULTI_CVARS) { #ifdef JK2_MODE multiPtr->cvarList[multiPtr->count] = String_Alloc("@MENUS3_ALL_VOICEOVERS"); #else @@ -1107,15 +951,14 @@ static void Item_ApplyHacks( itemDef_t *item ) { #endif multiPtr->cvarValue[multiPtr->count] = 1; multiPtr->count++; - Com_Printf( "Extended subtitles field to contain all voiceovers option.\n"); + Com_Printf("Extended subtitles field to contain all voiceovers option.\n"); } } #ifdef JK2_MODE - if ( item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp( item->window.name, "video_mode") && item->cvar && !Q_stricmp( item->cvar, "r_ext_texture_filter_anisotropic" ) ) { - { - memset(item->typeData, 0, sizeof(multiDef_t)); - } + if (item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp(item->window.name, "video_mode") && item->cvar && + !Q_stricmp(item->cvar, "r_ext_texture_filter_anisotropic")) { + { memset(item->typeData, 0, sizeof(multiDef_t)); } editFieldDef_t *editPtr = NULL; item->cvarFlags = CVAR_DISABLE; @@ -1127,7 +970,7 @@ static void Item_ApplyHacks( itemDef_t *item ) { editPtr->minVal = 0.5f; editPtr->maxVal = cls.glconfig.maxTextureFilterAnisotropy; editPtr->defVal = 1.0f; - Com_Printf( "Converted anisotropic filter field to slider.\n"); + Com_Printf("Converted anisotropic filter field to slider.\n"); } #endif } @@ -1137,79 +980,164 @@ static void Item_ApplyHacks( itemDef_t *item ) { MenuParse_itemDef ================ */ -qboolean MenuParse_itemDef( itemDef_t *item ) -{ - menuDef_t *menu = (menuDef_t*)item; - if (menu->itemCount < MAX_MENUITEMS) - { - itemDef_t *newItem = menu->items[menu->itemCount] = (struct itemDef_s *) UI_Alloc(sizeof(itemDef_t)); +qboolean MenuParse_itemDef(itemDef_t *item) { + menuDef_t *menu = (menuDef_t *)item; + if (menu->itemCount < MAX_MENUITEMS) { + itemDef_t *newItem = menu->items[menu->itemCount] = (struct itemDef_s *)UI_Alloc(sizeof(itemDef_t)); Item_Init(newItem); - if (!Item_Parse(newItem)) - { + if (!Item_Parse(newItem)) { return qfalse; } - Item_InitControls( newItem ); + Item_InitControls(newItem); newItem->parent = menu->items[menu->itemCount]->parent = menu; menu->itemCount++; - Item_ApplyHacks( newItem ); - } - else - { + Item_ApplyHacks(newItem); + } else { PC_ParseWarning(va("Exceeded item/menu max of %d", MAX_MENUITEMS)); } return qtrue; } -#define KEYWORDHASH_SIZE 512 +#define KEYWORDHASH_SIZE 512 -typedef struct keywordHash_s -{ - const char *keyword; - qboolean (*func)(itemDef_t *item); - struct keywordHash_s *next; +typedef struct keywordHash_s { + const char *keyword; + qboolean (*func)(itemDef_t *item); + struct keywordHash_s *next; } keywordHash_t; -keywordHash_t menuParseKeywords[] = { - {"appearanceIncrement", MenuParse_appearanceIncrement}, - {"backcolor", MenuParse_backcolor, }, - {"background", MenuParse_background, }, - {"border", MenuParse_border, }, - {"bordercolor", MenuParse_bordercolor, }, - {"borderSize", MenuParse_borderSize, }, - {"cinematic", MenuParse_cinematic, }, - {"descAlignment", MenuParse_descAlignment }, - {"descTextStyle", MenuParse_descTextStyle }, - {"desccolor", MenuParse_descColor }, - {"descX", MenuParse_descX }, - {"descY", MenuParse_descY }, - {"descScale", MenuParse_descScale }, - {"disablecolor", MenuParse_disablecolor, }, - {"fadeClamp", MenuParse_fadeClamp, }, - {"fadeCycle", MenuParse_fadeCycle, }, - {"fadeAmount", MenuParse_fadeAmount, }, - {"focuscolor", MenuParse_focuscolor, }, - {"font", MenuParse_font, }, - {"forecolor", MenuParse_forecolor, }, - {"fullscreen", MenuParse_fullscreen, }, - {"itemDef", MenuParse_itemDef, }, - {"name", MenuParse_name, }, - {"onClose", MenuParse_onClose, }, -//JLFACCEPT MPMOVED - {"onAccept", MenuParse_onAccept, }, - {"onESC", MenuParse_onESC, }, - {"onOpen", MenuParse_onOpen, }, - {"outlinecolor", MenuParse_outlinecolor, }, - {"outOfBoundsClick", MenuParse_outOfBounds, }, - {"ownerdraw", MenuParse_ownerdraw, }, - {"ownerdrawFlag", MenuParse_ownerdrawFlag,}, - {"popup", MenuParse_popup, }, - {"rect", MenuParse_rect, }, - {"soundLoop", MenuParse_soundLoop, }, - {"style", MenuParse_style, }, - {"visible", MenuParse_visible, }, - {"ignoreescape", MenuParse_ignoreescape, }, - {NULL, NULL, } -}; +keywordHash_t menuParseKeywords[] = {{"appearanceIncrement", MenuParse_appearanceIncrement}, + { + "backcolor", + MenuParse_backcolor, + }, + { + "background", + MenuParse_background, + }, + { + "border", + MenuParse_border, + }, + { + "bordercolor", + MenuParse_bordercolor, + }, + { + "borderSize", + MenuParse_borderSize, + }, + { + "cinematic", + MenuParse_cinematic, + }, + {"descAlignment", MenuParse_descAlignment}, + {"descTextStyle", MenuParse_descTextStyle}, + {"desccolor", MenuParse_descColor}, + {"descX", MenuParse_descX}, + {"descY", MenuParse_descY}, + {"descScale", MenuParse_descScale}, + { + "disablecolor", + MenuParse_disablecolor, + }, + { + "fadeClamp", + MenuParse_fadeClamp, + }, + { + "fadeCycle", + MenuParse_fadeCycle, + }, + { + "fadeAmount", + MenuParse_fadeAmount, + }, + { + "focuscolor", + MenuParse_focuscolor, + }, + { + "font", + MenuParse_font, + }, + { + "forecolor", + MenuParse_forecolor, + }, + { + "fullscreen", + MenuParse_fullscreen, + }, + { + "itemDef", + MenuParse_itemDef, + }, + { + "name", + MenuParse_name, + }, + { + "onClose", + MenuParse_onClose, + }, + // JLFACCEPT MPMOVED + { + "onAccept", + MenuParse_onAccept, + }, + { + "onESC", + MenuParse_onESC, + }, + { + "onOpen", + MenuParse_onOpen, + }, + { + "outlinecolor", + MenuParse_outlinecolor, + }, + { + "outOfBoundsClick", + MenuParse_outOfBounds, + }, + { + "ownerdraw", + MenuParse_ownerdraw, + }, + { + "ownerdrawFlag", + MenuParse_ownerdrawFlag, + }, + { + "popup", + MenuParse_popup, + }, + { + "rect", + MenuParse_rect, + }, + { + "soundLoop", + MenuParse_soundLoop, + }, + { + "style", + MenuParse_style, + }, + { + "visible", + MenuParse_visible, + }, + { + "ignoreescape", + MenuParse_ignoreescape, + }, + { + NULL, + NULL, + }}; keywordHash_t *menuParseKeywordHash[KEYWORDHASH_SIZE]; @@ -1218,8 +1146,7 @@ keywordHash_t *menuParseKeywordHash[KEYWORDHASH_SIZE]; KeywordHash_Key ================ */ -int KeywordHash_Key(const char *keyword) -{ +int KeywordHash_Key(const char *keyword) { int hash, i; hash = 0; @@ -1229,7 +1156,7 @@ int KeywordHash_Key(const char *keyword) else hash += keyword[i] * (119 + i); } - hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE-1); + hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE - 1); return hash; } @@ -1238,8 +1165,7 @@ int KeywordHash_Key(const char *keyword) KeywordHash_Add ================ */ -void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) -{ +void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) { int hash; hash = KeywordHash_Key(key->keyword); @@ -1252,14 +1178,12 @@ void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) KeywordHash_Find =============== */ -keywordHash_t *KeywordHash_Find(keywordHash_t *table[], const char *keyword) -{ +keywordHash_t *KeywordHash_Find(keywordHash_t *table[], const char *keyword) { keywordHash_t *key; int hash; hash = KeywordHash_Key(keyword); - for (key = table[hash]; key; key = key->next) - { + for (key = table[hash]; key; key = key->next) { if (!Q_stricmp(key->keyword, keyword)) return key; } @@ -1273,21 +1197,19 @@ hashForString return a hash value for the string ================ */ -static unsigned hashForString(const char *str) -{ - int i; - unsigned hash; - char letter; +static unsigned hashForString(const char *str) { + int i; + unsigned hash; + char letter; hash = 0; i = 0; - while (str[i] != '\0') - { + while (str[i] != '\0') { letter = tolower((unsigned char)str[i]); - hash += (unsigned)(letter)*(i + 119); + hash += (unsigned)(letter) * (i + 119); i++; } - hash &= (HASH_TABLE_SIZE-1); + hash &= (HASH_TABLE_SIZE - 1); return hash; } @@ -1296,65 +1218,53 @@ static unsigned hashForString(const char *str) String_Alloc ================= */ -const char *String_Alloc(const char *p) -{ +const char *String_Alloc(const char *p) { int len; unsigned hash; stringDef_t *str, *last; static const char *staticNULL = ""; - if (p == NULL) - { + if (p == NULL) { return NULL; } - if (*p == 0) - { + if (*p == 0) { return staticNULL; } hash = hashForString(p); str = strHandle[hash]; - while (str) - { - if (strcmp(p, str->str) == 0) - { + while (str) { + if (strcmp(p, str->str) == 0) { return str->str; } str = str->next; } len = strlen(p); - if (len + strPoolIndex + 1 < STRING_POOL_SIZE) - { + if (len + strPoolIndex + 1 < STRING_POOL_SIZE) { int ph = strPoolIndex; strcpy(&strPool[strPoolIndex], p); strPoolIndex += len + 1; str = strHandle[hash]; last = str; - while (last && last->next) - { + while (last && last->next) { last = last->next; } - str = (stringDef_s *) UI_Alloc( sizeof(stringDef_t)); + str = (stringDef_s *)UI_Alloc(sizeof(stringDef_t)); str->next = NULL; str->str = &strPool[ph]; - if (last) - { + if (last) { last->next = str; - } - else - { + } else { strHandle[hash] = str; } return &strPool[ph]; - } - else - { + } else { Com_Printf("WARNING: Ran out of strPool space\n"); } @@ -1366,8 +1276,7 @@ const char *String_Alloc(const char *p) String_Report ================= */ -void String_Report(void) -{ +void String_Report(void) { float f; Com_Printf("Memory/String Pool Info\n"); Com_Printf("----------------\n"); @@ -1386,12 +1295,10 @@ void String_Report(void) String_Init ================= */ -void String_Init(void) -{ +void String_Init(void) { int i; - for (i = 0; i < HASH_TABLE_SIZE; i++) - { + for (i = 0; i < HASH_TABLE_SIZE; i++) { strHandle[i] = 0; } @@ -1401,14 +1308,11 @@ void String_Init(void) Item_SetupKeywordHash(); Menu_SetupKeywordHash(); - if (DC && DC->getBindingBuf) - { + if (DC && DC->getBindingBuf) { Controls_GetConfig(); } } - - //--------------------------------------------------------------------------------------------------------- // Memory //--------------------------------------------------------------------------------------------------------- @@ -1418,15 +1322,12 @@ void String_Init(void) UI_Alloc =============== */ -void *UI_Alloc( int size ) -{ - char *p; +void *UI_Alloc(int size) { + char *p; - if ( allocPoint + size > MEM_POOL_SIZE ) - { + if (allocPoint + size > MEM_POOL_SIZE) { outOfMemory = qtrue; - if (DC->Print) - { + if (DC->Print) { DC->Print("UI_Alloc: Failure. Out of memory!\n"); } return NULL; @@ -1434,7 +1335,7 @@ void *UI_Alloc( int size ) p = &memoryPool[allocPoint]; - allocPoint += ( size + 15 ) & ~15; + allocPoint += (size + 15) & ~15; return p; } @@ -1444,33 +1345,27 @@ void *UI_Alloc( int size ) UI_InitMemory =============== */ -void UI_InitMemory( void ) -{ +void UI_InitMemory(void) { allocPoint = 0; outOfMemory = qfalse; } - /* =============== Menu_ItemsMatchingGroup =============== */ -int Menu_ItemsMatchingGroup(menuDef_t *menu, const char *name) -{ +int Menu_ItemsMatchingGroup(menuDef_t *menu, const char *name) { int i; int count = 0; - for (i = 0; i < menu->itemCount; i++) - { - if ((!menu->items[i]->window.name) && (!menu->items[i]->window.group)) - { - Com_Printf(S_COLOR_YELLOW"WARNING: item has neither name or group\n"); + for (i = 0; i < menu->itemCount; i++) { + if ((!menu->items[i]->window.name) && (!menu->items[i]->window.group)) { + Com_Printf(S_COLOR_YELLOW "WARNING: item has neither name or group\n"); continue; } - if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) - { + if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) { count++; } } @@ -1483,16 +1378,12 @@ int Menu_ItemsMatchingGroup(menuDef_t *menu, const char *name) Menu_GetMatchingItemByNumber =============== */ -itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char *name) -{ +itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char *name) { int i; int count = 0; - for (i = 0; i < menu->itemCount; i++) - { - if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) - { - if (count == index) - { + for (i = 0; i < menu->itemCount; i++) { + if (Q_stricmp(menu->items[i]->window.name, name) == 0 || (menu->items[i]->window.group && Q_stricmp(menu->items[i]->window.group, name) == 0)) { + if (count == index) { return menu->items[i]; } count++; @@ -1506,23 +1397,17 @@ itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char * Menu_FadeItemByName =============== */ -void Menu_FadeItemByName(menuDef_t *menu, const char *p, qboolean fadeOut) -{ +void Menu_FadeItemByName(menuDef_t *menu, const char *p, qboolean fadeOut) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if (fadeOut) - { + if (item != NULL) { + if (fadeOut) { item->window.flags |= (WINDOW_FADINGOUT | WINDOW_VISIBLE); item->window.flags &= ~WINDOW_FADINGIN; - } - else - { + } else { item->window.flags |= (WINDOW_VISIBLE | WINDOW_FADINGIN); item->window.flags &= ~WINDOW_FADINGOUT; } @@ -1535,34 +1420,26 @@ void Menu_FadeItemByName(menuDef_t *menu, const char *p, qboolean fadeOut) Menu_ShowItemByName =============== */ -void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow) -{ +void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow) { itemDef_t *item; int i; int count; count = Menu_ItemsMatchingGroup(menu, p); - if (!count) - { - Com_Printf(S_COLOR_YELLOW"WARNING: Menu_ShowItemByName - unable to locate any items named: \"%s\"\n",p); + if (!count) { + Com_Printf(S_COLOR_YELLOW "WARNING: Menu_ShowItemByName - unable to locate any items named: \"%s\"\n", p); } - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if (bShow) - { + if (item != NULL) { + if (bShow) { item->window.flags |= WINDOW_VISIBLE; - } - else - { + } else { item->window.flags &= ~(WINDOW_VISIBLE | WINDOW_HASFOCUS); // stop cinematics playing in the window - if (item->window.cinematic >= 0) - { + if (item->window.cinematic >= 0) { DC->stopCinematic(item->window.cinematic); item->window.cinematic = -1; } @@ -1576,15 +1453,12 @@ void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow) Menu_GetFocused =============== */ -menuDef_t *Menu_GetFocused(void) -{ +menuDef_t *Menu_GetFocused(void) { int i; - for (i = 0; i < menuCount; i++) - { - if ((Menus[i].window.flags & WINDOW_HASFOCUS) && (Menus[i].window.flags & WINDOW_VISIBLE)) - { - return &Menus[i]; + for (i = 0; i < menuCount; i++) { + if ((Menus[i].window.flags & WINDOW_HASFOCUS) && (Menus[i].window.flags & WINDOW_VISIBLE)) { + return &Menus[i]; } } @@ -1596,23 +1470,17 @@ menuDef_t *Menu_GetFocused(void) Menus_OpenByName =============== */ -void Menus_OpenByName(const char *p) -{ - Menus_ActivateByName(p); -} +void Menus_OpenByName(const char *p) { Menus_ActivateByName(p); } /* =============== Menus_FindByName =============== */ -menuDef_t *Menus_FindByName(const char *p) -{ +menuDef_t *Menus_FindByName(const char *p) { int i; - for (i = 0; i < menuCount; i++) - { - if (Q_stricmp(Menus[i].window.name, p) == 0) - { + for (i = 0; i < menuCount; i++) { + if (Q_stricmp(Menus[i].window.name, p) == 0) { return &Menus[i]; } } @@ -1624,10 +1492,8 @@ menuDef_t *Menus_FindByName(const char *p) Menu_RunCloseScript =============== */ -static void Menu_RunCloseScript(menuDef_t *menu) -{ - if (menu && menu->window.flags & WINDOW_VISIBLE && menu->onClose) - { +static void Menu_RunCloseScript(menuDef_t *menu) { + if (menu && menu->window.flags & WINDOW_VISIBLE && menu->onClose) { itemDef_t item; item.parent = menu; Item_RunScript(&item, menu->onClose); @@ -1639,17 +1505,15 @@ static void Menu_RunCloseScript(menuDef_t *menu) Item_ActivateByName =============== */ -void Item_ActivateByName(const char *menuName,const char *itemName) -{ +void Item_ActivateByName(const char *menuName, const char *itemName) { itemDef_t *item; menuDef_t *menu; menu = Menus_FindByName(menuName); - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) menu, itemName); + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)menu, itemName); - if (item != NULL) - { + if (item != NULL) { item->window.flags &= ~WINDOW_INACTIVE; } } @@ -1659,13 +1523,11 @@ void Item_ActivateByName(const char *menuName,const char *itemName) Menus_CloseByName =============== */ -void Menus_CloseByName(const char *p) -{ +void Menus_CloseByName(const char *p) { menuDef_t *menu = Menus_FindByName(p); // If the menu wasnt found just exit - if (menu == NULL) - { + if (menu == NULL) { return; } @@ -1673,12 +1535,10 @@ void Menus_CloseByName(const char *p) Menu_RunCloseScript(menu); // If this window had the focus then take it away - if ( menu->window.flags & WINDOW_HASFOCUS ) - { + if (menu->window.flags & WINDOW_HASFOCUS) { // If there is something still in the open menu list then // set it to have focus now - if ( openMenuCount ) - { + if (openMenuCount) { // Subtract one from the open menu count to prepare to // remove the top menu from the list openMenuCount -= 1; @@ -1700,18 +1560,14 @@ void Menus_CloseByName(const char *p) Menu_FindItemByName =============== */ -itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p) -{ +itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p) { int i; - if (menu == NULL || p == NULL) - { + if (menu == NULL || p == NULL) { return NULL; } - for (i = 0; i < menu->itemCount; i++) - { - if (Q_stricmp(p, menu->items[i]->window.name) == 0) - { + for (i = 0; i < menu->itemCount; i++) { + if (Q_stricmp(p, menu->items[i]->window.name) == 0) { return menu->items[i]; } } @@ -1724,23 +1580,18 @@ itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p) Menu_ClearFocus ================= */ -itemDef_t *Menu_ClearFocus(menuDef_t *menu) -{ +itemDef_t *Menu_ClearFocus(menuDef_t *menu) { int i; itemDef_t *ret = NULL; - if (menu == NULL) - { + if (menu == NULL) { return NULL; } - for (i = 0; i < menu->itemCount; i++) - { - if (menu->items[i]->window.flags & WINDOW_HASFOCUS) - { + for (i = 0; i < menu->itemCount; i++) { + if (menu->items[i]->window.flags & WINDOW_HASFOCUS) { ret = menu->items[i]; menu->items[i]->window.flags &= ~WINDOW_HASFOCUS; - if (menu->items[i]->leaveFocus) - { + if (menu->items[i]->leaveFocus) { Item_RunScript(menu->items[i], menu->items[i]->leaveFocus); } } @@ -1749,87 +1600,70 @@ itemDef_t *Menu_ClearFocus(menuDef_t *menu) } // Set all the items within a given menu, with the given itemName, to the given shader -void Menu_SetItemBackground(const menuDef_t *menu,const char *itemName, const char *background) -{ - itemDef_t *item; - int j, count; +void Menu_SetItemBackground(const menuDef_t *menu, const char *itemName, const char *background) { + itemDef_t *item; + int j, count; - if (!menu) // No menu??? + if (!menu) // No menu??? { return; } - count = Menu_ItemsMatchingGroup( (menuDef_t *) menu, itemName); + count = Menu_ItemsMatchingGroup((menuDef_t *)menu, itemName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( (menuDef_t *) menu, j, itemName); - if (item != NULL) - { -// item->window.background = DC->registerShaderNoMip(background); + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber((menuDef_t *)menu, j, itemName); + if (item != NULL) { + // item->window.background = DC->registerShaderNoMip(background); item->window.background = ui.R_RegisterShaderNoMip(background); } } } // Set all the items within a given menu, with the given itemName, to the given text -void Menu_SetItemText(const menuDef_t *menu,const char *itemName, const char *text) -{ - itemDef_t *item; - int j, count; +void Menu_SetItemText(const menuDef_t *menu, const char *itemName, const char *text) { + itemDef_t *item; + int j, count; - if (!menu) // No menu??? + if (!menu) // No menu??? { return; } - count = Menu_ItemsMatchingGroup( (menuDef_t *) menu, itemName); + count = Menu_ItemsMatchingGroup((menuDef_t *)menu, itemName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( (menuDef_t *) menu, j, itemName); - if (item != NULL) - { - if (text[0] == '*') - { - item->cvar = text+1; + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber((menuDef_t *)menu, j, itemName); + if (item != NULL) { + if (text[0] == '*') { + item->cvar = text + 1; // Just copying what was in ItemParse_cvar() - if ( item->typeData) - { + if (item->typeData) { editFieldDef_t *editPtr; - editPtr = (editFieldDef_t*)item->typeData; + editPtr = (editFieldDef_t *)item->typeData; editPtr->minVal = -1; editPtr->maxVal = -1; editPtr->defVal = -1; } - } - else - { - if (item->type == ITEM_TYPE_TEXTSCROLL ) - { + } else { + if (item->type == ITEM_TYPE_TEXTSCROLL) { char cvartext[1024]; - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; - if ( scrollPtr ) - { + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; + if (scrollPtr) { scrollPtr->startPos = 0; scrollPtr->endPos = 0; } - if (item->cvar) - { + if (item->cvar) { DC->getCVarString(item->cvar, cvartext, sizeof(cvartext)); item->text = cvartext; - } - else - { - item->text = (char *) text; + } else { + item->text = (char *)text; } - Item_TextScroll_BuildLines ( item ); - } - else - { - item->text = (char *) text; + Item_TextScroll_BuildLines(item); + } else { + item->text = (char *)text; } } } @@ -1841,19 +1675,15 @@ void Menu_SetItemText(const menuDef_t *menu,const char *itemName, const char *te Menu_TransitionItemByName ================= */ -void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t *rectFrom, const rectDef_t *rectTo, int time, float amt) -{ +void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t *rectFrom, const rectDef_t *rectTo, int time, float amt) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if (!rectFrom) - { - rectFrom = &item->window.rect; //if there are more than one of these with the same name, they'll all use the FIRST one's FROM. + if (item != NULL) { + if (!rectFrom) { + rectFrom = &item->window.rect; // if there are more than one of these with the same name, they'll all use the FIRST one's FROM. } item->window.flags |= (WINDOW_INTRANSITION | WINDOW_VISIBLE); item->window.offsetTime = time; @@ -1873,25 +1703,20 @@ void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t * Menu_TransitionItemByName ================= */ -//JLF MOVED +// JLF MOVED #define _TRANS3 #ifdef _TRANS3 -void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx, const float miny, const float minz, - const float maxx, const float maxy, const float maxz, const float fovtx, const float fovty, - const int time, const float amt) -{ +void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx, const float miny, const float minz, const float maxx, const float maxy, + const float maxz, const float fovtx, const float fovty, const int time, const float amt) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - modelDef_t * modelptr; - for (i = 0; i < count; i++) - { + modelDef_t *modelptr; + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if ( item->type == ITEM_TYPE_MODEL) - { - modelptr = (modelDef_t*)item->typeData; + if (item != NULL) { + if (item->type == ITEM_TYPE_MODEL) { + modelptr = (modelDef_t *)item->typeData; item->window.flags |= (WINDOW_INTRANSITIONMODEL | WINDOW_VISIBLE); item->window.offsetTime = time; @@ -1900,14 +1725,14 @@ void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); VectorSet(modelptr->g2mins2, minx, miny, minz); -// //modelptr->g2maxs2.x= maxx; -// modelptr->g2maxs2.y= maxy; -// modelptr->g2maxs2.z= maxz; -// modelptr->g2mins2.x= minx; -// modelptr->g2mins2.y= miny; -// modelptr->g2mins2.z= minz; + // //modelptr->g2maxs2.x= maxx; + // modelptr->g2maxs2.y= maxy; + // modelptr->g2maxs2.z= maxz; + // modelptr->g2mins2.x= minx; + // modelptr->g2mins2.y= miny; + // modelptr->g2mins2.z= minz; -// VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); + // VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); modelptr->g2maxsEffect[0] = abs(modelptr->g2maxs2[0] - modelptr->g2maxs[0]) / amt; modelptr->g2maxsEffect[1] = abs(modelptr->g2maxs2[1] - modelptr->g2maxs[1]) / amt; @@ -1917,35 +1742,27 @@ void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx modelptr->g2minsEffect[1] = abs(modelptr->g2mins2[1] - modelptr->g2mins[1]) / amt; modelptr->g2minsEffect[2] = abs(modelptr->g2mins2[2] - modelptr->g2mins[2]) / amt; - modelptr->fov_Effectx = abs(modelptr->fov_x2 - modelptr->fov_x) / amt; modelptr->fov_Effecty = abs(modelptr->fov_y2 - modelptr->fov_y) / amt; } - } } } #endif - - - /* ================= Menu_OrbitItemByName ================= */ -void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, float cx, float cy, int time) -{ +void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, float cx, float cy, int time) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { + if (item != NULL) { item->window.flags |= (WINDOW_ORBITING | WINDOW_VISIBLE); item->window.offsetTime = time; item->window.rectEffects.x = cx; @@ -1957,18 +1774,15 @@ void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, floa } } -void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) -{ - int j,count; +void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) { + int j, count; itemDef_t *itemFound; count = Menu_ItemsMatchingGroup(menu, name); // Loop through all items that have this name - for (j = 0; j < count; j++) - { - itemFound = Menu_GetMatchingItemByNumber( menu, j, name); - if (itemFound != NULL) - { + for (j = 0; j < count; j++) { + itemFound = Menu_GetMatchingItemByNumber(menu, j, name); + if (itemFound != NULL) { itemFound->disabled = disableFlag; // Just in case it had focus itemFound->window.flags &= ~WINDOW_MOUSEOVER; @@ -1981,16 +1795,11 @@ void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) Rect_Parse ================= */ -qboolean Rect_Parse(const char **p, rectDef_t *r) -{ - if (!COM_ParseFloat(p, &r->x)) - { - if (!COM_ParseFloat(p, &r->y)) - { - if (!COM_ParseFloat(p, &r->w)) - { - if (!COM_ParseFloat(p, &r->h)) - { +qboolean Rect_Parse(const char **p, rectDef_t *r) { + if (!COM_ParseFloat(p, &r->x)) { + if (!COM_ParseFloat(p, &r->y)) { + if (!COM_ParseFloat(p, &r->w)) { + if (!COM_ParseFloat(p, &r->h)) { return qtrue; } } @@ -1999,33 +1808,27 @@ qboolean Rect_Parse(const char **p, rectDef_t *r) return qfalse; } -qboolean Script_SetItemRect(itemDef_t *item, const char **args) -{ +qboolean Script_SetItemRect(itemDef_t *item, const char **args) { const char *itemname; rectDef_t *out; rectDef_t rect; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &itemname)) - { + if (String_Parse(args, &itemname)) { itemDef_t *item2; int j; - int count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, itemname); + int count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, itemname); - if (!Rect_Parse(args, &rect)) - { + if (!Rect_Parse(args, &rect)) { return qtrue; } - for (j = 0; j < count; j++) - { - item2 = Menu_GetMatchingItemByNumber((menuDef_t *) item->parent, j, itemname); - if (item2 != NULL) - { + for (j = 0; j < count; j++) { + item2 = Menu_GetMatchingItemByNumber((menuDef_t *)item->parent, j, itemname); + if (item2 != NULL) { out = &item2->window.rect; - if (out) - { + if (out) { item2->window.rect.x = rect.x; item2->window.rect.y = rect.y; item2->window.rect.w = rect.w; @@ -2042,15 +1845,13 @@ qboolean Script_SetItemRect(itemDef_t *item, const char **args) Script_SetItemBackground ================= */ -qboolean Script_SetItemBackground(itemDef_t *item, const char **args) -{ +qboolean Script_SetItemBackground(itemDef_t *item, const char **args) { const char *itemName; const char *name; // expecting name of shader - if (String_Parse(args, &itemName) && String_Parse(args, &name)) - { - Menu_SetItemBackground((menuDef_t *) item->parent, itemName, name); + if (String_Parse(args, &itemName) && String_Parse(args, &name)) { + Menu_SetItemBackground((menuDef_t *)item->parent, itemName, name); } return qtrue; } @@ -2060,15 +1861,13 @@ qboolean Script_SetItemBackground(itemDef_t *item, const char **args) Script_SetItemText ================= */ -qboolean Script_SetItemText(itemDef_t *item, const char **args) -{ +qboolean Script_SetItemText(itemDef_t *item, const char **args) { const char *itemName; const char *text; // expecting text - if (String_Parse(args, &itemName) && String_Parse(args, &text)) - { - Menu_SetItemText((menuDef_t *) item->parent, itemName, text); + if (String_Parse(args, &itemName) && String_Parse(args, &text)) { + Menu_SetItemText((menuDef_t *)item->parent, itemName, text); } return qtrue; } @@ -2078,12 +1877,10 @@ qboolean Script_SetItemText(itemDef_t *item, const char **args) Script_FadeIn ================= */ -qboolean Script_FadeIn(itemDef_t *item, const char **args) -{ +qboolean Script_FadeIn(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_FadeItemByName((menuDef_t *) item->parent, name, qfalse); + if (String_Parse(args, &name)) { + Menu_FadeItemByName((menuDef_t *)item->parent, name, qfalse); } return qtrue; @@ -2094,12 +1891,10 @@ qboolean Script_FadeIn(itemDef_t *item, const char **args) Script_FadeOut ================= */ -qboolean Script_FadeOut(itemDef_t *item, const char **args) -{ +qboolean Script_FadeOut(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_FadeItemByName((menuDef_t *) item->parent, name, qtrue); + if (String_Parse(args, &name)) { + Menu_FadeItemByName((menuDef_t *)item->parent, name, qtrue); } return qtrue; @@ -2110,47 +1905,38 @@ qboolean Script_FadeOut(itemDef_t *item, const char **args) Script_Show ================= */ -qboolean Script_Show(itemDef_t *item, const char **args) -{ +qboolean Script_Show(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_ShowItemByName((menuDef_t *) item->parent, name, qtrue); + if (String_Parse(args, &name)) { + Menu_ShowItemByName((menuDef_t *)item->parent, name, qtrue); } return qtrue; } - - /* ================= Script_ShowMenu ================= */ -qboolean Script_ShowMenu(itemDef_t *item, const char **args) -{ +qboolean Script_ShowMenu(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { Menus_ShowItems(name); } return qtrue; } - /* ================= Script_Hide ================= */ -qboolean Script_Hide(itemDef_t *item, const char **args) -{ +qboolean Script_Hide(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_ShowItemByName((menuDef_t *) item->parent, name, qfalse); + if (String_Parse(args, &name)) { + Menu_ShowItemByName((menuDef_t *)item->parent, name, qfalse); } return qtrue; @@ -2161,39 +1947,29 @@ qboolean Script_Hide(itemDef_t *item, const char **args) Script_SetColor ================= */ -qboolean Script_SetColor(itemDef_t *item, const char **args) -{ +qboolean Script_SetColor(itemDef_t *item, const char **args) { const char *name; int i; float f; vec4_t *out; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { out = NULL; - if (Q_stricmp(name, "backcolor") == 0) - { + if (Q_stricmp(name, "backcolor") == 0) { out = &item->window.backColor; item->window.flags |= WINDOW_BACKCOLORSET; - } - else if (Q_stricmp(name, "forecolor") == 0) - { + } else if (Q_stricmp(name, "forecolor") == 0) { out = &item->window.foreColor; item->window.flags |= WINDOW_FORECOLORSET; - } - else if (Q_stricmp(name, "bordercolor") == 0) - { + } else if (Q_stricmp(name, "bordercolor") == 0) { out = &item->window.borderColor; } - if (out) - { - for (i = 0; i < 4; i++) - { -// if (!Float_Parse(args, &f)) - if (COM_ParseFloat( args, &f)) - { + if (out) { + for (i = 0; i < 4; i++) { + // if (!Float_Parse(args, &f)) + if (COM_ParseFloat(args, &f)) { return qtrue; } (*out)[i] = f; @@ -2209,40 +1985,31 @@ qboolean Script_SetColor(itemDef_t *item, const char **args) Script_Open ================= */ -qboolean Script_Open(itemDef_t *item, const char **args) -{ +qboolean Script_Open(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { Menus_OpenByName(name); } return qtrue; } -qboolean Script_OpenGoToMenu(itemDef_t *item, const char **args) -{ - Menus_OpenByName(GoToMenu); // Give warning +qboolean Script_OpenGoToMenu(itemDef_t *item, const char **args) { + Menus_OpenByName(GoToMenu); // Give warning return qtrue; } - /* ================= Script_Close ================= */ -qboolean Script_Close(itemDef_t *item, const char **args) -{ +qboolean Script_Close(itemDef_t *item, const char **args) { const char *name; - if (String_Parse(args, &name)) - { - if (Q_stricmp(name, "all") == 0) - { + if (String_Parse(args, &name)) { + if (Q_stricmp(name, "all") == 0) { Menus_CloseAll(); - } - else - { + } else { Menus_CloseByName(name); } } @@ -2255,15 +2022,12 @@ qboolean Script_Close(itemDef_t *item, const char **args) Script_Activate ================= */ -qboolean Script_Activate(itemDef_t *item, const char **args) -{ +qboolean Script_Activate(itemDef_t *item, const char **args) { const char *name, *menu; - if (String_Parse(args, &menu)) - { - if (String_Parse(args, &name)) - { - Item_ActivateByName(menu,name); + if (String_Parse(args, &menu)) { + if (String_Parse(args, &name)) { + Item_ActivateByName(menu, name); } } @@ -2275,12 +2039,10 @@ qboolean Script_Activate(itemDef_t *item, const char **args) Script_SetBackground ================= */ -qboolean Script_SetBackground(itemDef_t *item, const char **args) -{ +qboolean Script_SetBackground(itemDef_t *item, const char **args) { const char *name; // expecting name to set asset to - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { item->window.background = DC->registerShaderNoMip(name); } @@ -2292,15 +2054,12 @@ qboolean Script_SetBackground(itemDef_t *item, const char **args) Script_SetAsset ================= */ -qboolean Script_SetAsset(itemDef_t *item, const char **args) -{ +qboolean Script_SetAsset(itemDef_t *item, const char **args) { const char *name; // expecting name to set asset to - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { // check for a model - if (item->type == ITEM_TYPE_MODEL) - { + if (item->type == ITEM_TYPE_MODEL) { } } @@ -2312,28 +2071,23 @@ qboolean Script_SetAsset(itemDef_t *item, const char **args) Script_SetFocus ================= */ -qboolean Script_SetFocus(itemDef_t *item, const char **args) -{ +qboolean Script_SetFocus(itemDef_t *item, const char **args) { const char *name; itemDef_t *focusItem; - if (String_Parse(args, &name)) - { - focusItem = (itemDef_s *) Menu_FindItemByName((menuDef_t *) item->parent, name); - if (focusItem && !(focusItem->window.flags & WINDOW_DECORATION) && !(focusItem->window.flags & WINDOW_HASFOCUS)) - { - Menu_ClearFocus((menuDef_t *) item->parent); -//JLF + if (String_Parse(args, &name)) { + focusItem = (itemDef_s *)Menu_FindItemByName((menuDef_t *)item->parent, name); + if (focusItem && !(focusItem->window.flags & WINDOW_DECORATION) && !(focusItem->window.flags & WINDOW_HASFOCUS)) { + Menu_ClearFocus((menuDef_t *)item->parent); + // JLF focusItem->window.flags |= WINDOW_HASFOCUS; -//END JLF + // END JLF - if (focusItem->onFocus) - { + if (focusItem->onFocus) { Item_RunScript(focusItem, focusItem->onFocus); } - if (DC->Assets.itemFocusSound) - { - DC->startLocalSound( DC->Assets.itemFocusSound, CHAN_LOCAL_SOUND ); + if (DC->Assets.itemFocusSound) { + DC->startLocalSound(DC->Assets.itemFocusSound, CHAN_LOCAL_SOUND); } } } @@ -2341,22 +2095,18 @@ qboolean Script_SetFocus(itemDef_t *item, const char **args) return qtrue; } - /* ================= Script_SetItemFlag ================= */ -qboolean Script_SetItemFlag(itemDef_t *item, const char **args) -{ - const char *itemName,*number; +qboolean Script_SetItemFlag(itemDef_t *item, const char **args) { + const char *itemName, *number; - if (String_Parse(args, &itemName)) - { - item = (itemDef_s *) Menu_FindItemByName((menuDef_t *) item->parent, itemName); + if (String_Parse(args, &itemName)) { + item = (itemDef_s *)Menu_FindItemByName((menuDef_t *)item->parent, itemName); - if (String_Parse(args, &number)) - { + if (String_Parse(args, &number)) { int amount = atoi(number); item->window.flags |= amount; } @@ -2365,60 +2115,44 @@ qboolean Script_SetItemFlag(itemDef_t *item, const char **args) return qtrue; } -void UI_SetItemVisible(menuDef_t *menu,const char *itemname,qboolean visible) -{ +void UI_SetItemVisible(menuDef_t *menu, const char *itemname, qboolean visible) { itemDef_t *item; int j; int count = Menu_ItemsMatchingGroup(menu, itemname); - for (j = 0; j < count; j++) - { + for (j = 0; j < count; j++) { item = Menu_GetMatchingItemByNumber(menu, j, itemname); - if (item != NULL) - { - if (visible==qtrue) - { + if (item != NULL) { + if (visible == qtrue) { item->window.flags |= WINDOW_VISIBLE; - } - else - { + } else { item->window.flags &= ~WINDOW_VISIBLE; } } } } -void UI_SetItemColor(itemDef_t *item,const char *itemname,const char *name,vec4_t color) -{ +void UI_SetItemColor(itemDef_t *item, const char *itemname, const char *name, vec4_t color) { itemDef_t *item2; - int i,j; + int i, j; vec4_t *out; - int count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, itemname); + int count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, itemname); - for (j = 0; j < count; j++) - { - item2 = Menu_GetMatchingItemByNumber((menuDef_t *) item->parent, j, itemname); - if (item2 != NULL) - { + for (j = 0; j < count; j++) { + item2 = Menu_GetMatchingItemByNumber((menuDef_t *)item->parent, j, itemname); + if (item2 != NULL) { out = NULL; - if (Q_stricmp(name, "backcolor") == 0) - { + if (Q_stricmp(name, "backcolor") == 0) { out = &item2->window.backColor; - } - else if (Q_stricmp(name, "forecolor") == 0) - { + } else if (Q_stricmp(name, "forecolor") == 0) { out = &item2->window.foreColor; item2->window.flags |= WINDOW_FORECOLORSET; - } - else if (Q_stricmp(name, "bordercolor") == 0) - { + } else if (Q_stricmp(name, "bordercolor") == 0) { out = &item2->window.borderColor; } - if (out) - { - for (i = 0; i < 4; i++) - { + if (out) { + for (i = 0; i < 4; i++) { (*out)[i] = color[i]; } } @@ -2431,22 +2165,18 @@ void UI_SetItemColor(itemDef_t *item,const char *itemname,const char *name,vec4_ Script_SetItemColor ================= */ -qboolean Script_SetItemColor(itemDef_t *item, const char **args) -{ +qboolean Script_SetItemColor(itemDef_t *item, const char **args) { const char *itemname; const char *name; vec4_t color; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &itemname) && String_Parse(args, &name)) - { - if (COM_ParseVec4(args, &color)) - { + if (String_Parse(args, &itemname) && String_Parse(args, &name)) { + if (COM_ParseVec4(args, &color)) { return qtrue; } - UI_SetItemColor(item,itemname,name,color); - + UI_SetItemColor(item, itemname, name, color); } return qtrue; @@ -2460,16 +2190,14 @@ Defers the rest of the script based on the defer condition. The deferred portion of the script can later be run with the "rundeferred" ================= */ -qboolean Script_Defer ( itemDef_t* item, const char **args ) -{ +qboolean Script_Defer(itemDef_t *item, const char **args) { // Should the script be deferred? - if ( DC->deferScript ( args ) ) - { + if (DC->deferScript(args)) { // Need the item the script was being run on uiInfo.deferredScriptItem = item; // Save the rest of the script - Q_strncpyz ( uiInfo.deferredScript, *args, MAX_DEFERRED_SCRIPT ); + Q_strncpyz(uiInfo.deferredScript, *args, MAX_DEFERRED_SCRIPT); // No more running return qfalse; @@ -2487,16 +2215,14 @@ Runs the last deferred script, there can only be one script deferred at a time so be careful of recursion ================= */ -qboolean Script_RunDeferred ( itemDef_t* item, const char **args ) -{ +qboolean Script_RunDeferred(itemDef_t *item, const char **args) { // Make sure there is something to run. - if ( !uiInfo.deferredScript[0] || !uiInfo.deferredScriptItem ) - { + if (!uiInfo.deferredScript[0] || !uiInfo.deferredScriptItem) { return qtrue; } // Run the deferred script now - Item_RunScript ( uiInfo.deferredScriptItem, uiInfo.deferredScript ); + Item_RunScript(uiInfo.deferredScriptItem, uiInfo.deferredScript); return qtrue; } @@ -2508,19 +2234,15 @@ Script_Delay Delays the rest of the script for the specified amount of time ================= */ -qboolean Script_Delay ( itemDef_t* item, const char **args ) -{ +qboolean Script_Delay(itemDef_t *item, const char **args) { int time; - if (Int_Parse(args, &time)) - { + if (Int_Parse(args, &time)) { item->window.flags |= WINDOW_SCRIPTWAITING; - item->window.delayTime = DC->realTime + time; // Flag to set delay time on next paint - item->window.delayedScript = (char *)*args; // Copy current location, we'll resume executing here later - } - else - { - Com_Printf(S_COLOR_YELLOW"WARNING: Script_Delay: error parsing\n" ); + item->window.delayTime = DC->realTime + time; // Flag to set delay time on next paint + item->window.delayedScript = (char *)*args; // Copy current location, we'll resume executing here later + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Delay: error parsing\n"); } // Stop running @@ -2534,29 +2256,23 @@ Script_Transition transition rtvscr 321 0 202 264 415 0 202 264 20 25 ================= */ -qboolean Script_Transition(itemDef_t *item, const char **args) -{ +qboolean Script_Transition(itemDef_t *item, const char **args) { const char *name; rectDef_t rectFrom, rectTo; int time; float amt; - if (String_Parse(args, &name)) - { - if ( ParseRect(args, &rectFrom) && ParseRect(args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat(args, &amt)) - { - Menu_TransitionItemByName((menuDef_t *) item->parent, name, &rectFrom, &rectTo, time, amt); - } - else - { - Com_Printf(S_COLOR_YELLOW"WARNING: Script_Transition: error parsing '%s'\n", name ); + if (String_Parse(args, &name)) { + if (ParseRect(args, &rectFrom) && ParseRect(args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat(args, &amt)) { + Menu_TransitionItemByName((menuDef_t *)item->parent, name, &rectFrom, &rectTo, time, amt); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Transition: error parsing '%s'\n", name); } } return qtrue; } - /* ================= Script_Transition2 @@ -2565,22 +2281,17 @@ uses current origin instead of specifing a starting origin transition2 lfvscr 25 0 202 264 20 25 ================= */ -qboolean Script_Transition2(itemDef_t *item, const char **args) -{ +qboolean Script_Transition2(itemDef_t *item, const char **args) { const char *name; rectDef_t rectTo; int time; float amt; - if (String_Parse(args, &name)) - { - if ( ParseRect(args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat(args, &amt)) - { - Menu_TransitionItemByName((menuDef_t *) item->parent, name, 0, &rectTo, time, amt); - } - else - { - Com_Printf(S_COLOR_YELLOW"WARNING: Script_Transition2: error parsing '%s'\n", name ); + if (String_Parse(args, &name)) { + if (ParseRect(args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat(args, &amt)) { + Menu_TransitionItemByName((menuDef_t *)item->parent, name, 0, &rectTo, time, amt); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name); } } @@ -2600,54 +2311,38 @@ uses current origin instead of specifing a starting origin transition3 lfvscr (min extent) (max extent) (fovx,y) 20 25 ================= */ -qboolean Script_Transition3(itemDef_t *item, const char **args) -{ +qboolean Script_Transition3(itemDef_t *item, const char **args) { const char *name = NULL; const char *value = NULL; float minx, miny, minz, maxx, maxy, maxz, fovtx, fovty; int time; float amt; - if (String_Parse(args, &name)) - { - if (String_Parse( args, &value)) - { + if (String_Parse(args, &name)) { + if (String_Parse(args, &value)) { minx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { miny = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { minz = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxy = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxz = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { fovtx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { fovty = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { time = atoi(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { amt = atof(value); - //set up the variables - Menu_Transition3ItemByName((menuDef_t *) item->parent, - name, - minx, miny, minz, - maxx, maxy, maxz, - fovtx, fovty, - time, amt); + // set up the variables + Menu_Transition3ItemByName((menuDef_t *)item->parent, name, minx, miny, minz, maxx, maxy, maxz, fovtx, fovty, + time, amt); return qtrue; } @@ -2661,100 +2356,80 @@ qboolean Script_Transition3(itemDef_t *item, const char **args) } } } - if ( name ) { - Com_Printf( S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name ); + if (name) { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name); } return qtrue; } #endif - -//only works on some feeders -int GetCurrentFeederIndex(itemDef_t * item) -{ +// only works on some feeders +int GetCurrentFeederIndex(itemDef_t *item) { float feederID = item->special; - const char * name; + const char *name; int i, max; - if (feederID == FEEDER_PLAYER_SPECIES) - { + if (feederID == FEEDER_PLAYER_SPECIES) { return uiInfo.playerSpeciesIndex; } - if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { + if (feederID == FEEDER_PLAYER_SKIN_HEAD) { name = Cvar_VariableString("ui_char_skin_head"); max = uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount; - for ( i = 0; i < max ; i++) - { - if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[i].name)) - { + for (i = 0; i < max; i++) { + if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[i].name)) { return i; } - // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); + // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); } return -1; - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { name = Cvar_VariableString("ui_char_skin_torso"); max = uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount; - for ( i = 0; i < max ; i++) - { - if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[i].name)) - { + for (i = 0; i < max; i++) { + if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[i].name)) { return i; } - // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); + // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); } return -1; - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { name = Cvar_VariableString("ui_char_skin_legs"); max = uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount; - for ( i = 0; i < max ; i++) - { - if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[i].name)) - { + for (i = 0; i < max; i++) { + if (!Q_stricmp(name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[i].name)) { return i; } - // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); + // Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadNames[index]); } return -1; - - // if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - // { - // Cvar_Set("ui_char_skin_legs", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegNames[index]); - // } + // if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) + // { + // Cvar_Set("ui_char_skin_legs", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegNames[index]); + // } } - - else if (feederID == FEEDER_COLORCHOICES) - { - extern void Item_RunScript(itemDef_t *item, const char *s); //from ui_shared; + else if (feederID == FEEDER_COLORCHOICES) { + extern void Item_RunScript(itemDef_t * item, const char *s); // from ui_shared; int currR, currG, currB, newR, newG, newB; - currR = Cvar_VariableIntegerValue( "ui_char_color_red"); - currG = Cvar_VariableIntegerValue( "ui_char_color_green"); - currB = Cvar_VariableIntegerValue( "ui_char_color_blue"); + currR = Cvar_VariableIntegerValue("ui_char_color_red"); + currG = Cvar_VariableIntegerValue("ui_char_color_green"); + currB = Cvar_VariableIntegerValue("ui_char_color_blue"); max = uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount; - for ( i = 0; i < max ; i++) - { + for (i = 0; i < max; i++) { Item_RunScript(item, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[i].actionText); - newR = Cvar_VariableIntegerValue( "ui_char_color_red"); - newG = Cvar_VariableIntegerValue( "ui_char_color_green"); - newB = Cvar_VariableIntegerValue( "ui_char_color_blue"); - if ( currR == newR && currG == newG && currB == newB) + newR = Cvar_VariableIntegerValue("ui_char_color_red"); + newG = Cvar_VariableIntegerValue("ui_char_color_green"); + newB = Cvar_VariableIntegerValue("ui_char_color_blue"); + if (currR == newR && currG == newG && currB == newB) return i; } return -1; - - -//JLF junk copied code + // JLF junk copied code /* extern void Item_RunScript(itemDef_t *item, const char *s); //from ui_shared; name = Cvar_VariableString("ui_char_skin_legs"); @@ -2776,57 +2451,41 @@ extern void Item_RunScript(itemDef_t *item, const char *s); //from ui_shared; */ } return -1; - } - - - - - - - - -qboolean Script_IncrementFeeder(itemDef_t * item, const char ** args) -{ +qboolean Script_IncrementFeeder(itemDef_t *item, const char **args) { int feedercount = uiInfo.uiDC.feederCount(item->special); int value = GetCurrentFeederIndex(item); value++; - if ( value >= feedercount) + if (value >= feedercount) value = 0; DC->feederSelection(item->special, value, item); return qtrue; } -qboolean Script_DecrementFeeder(itemDef_t * item, const char ** args) -{ +qboolean Script_DecrementFeeder(itemDef_t *item, const char **args) { int feedercount = uiInfo.uiDC.feederCount(item->special); int value = GetCurrentFeederIndex(item); value--; - if ( value < 0) - value = feedercount-1; + if (value < 0) + value = feedercount - 1; DC->feederSelection(item->special, value, item); return qtrue; } - /* ================= Script_SetCvar ================= */ -qboolean Script_SetCvar(itemDef_t *item, const char **args) -{ +qboolean Script_SetCvar(itemDef_t *item, const char **args) { const char *cvar, *val; - if (String_Parse(args, &cvar) && String_Parse(args, &val)) - { - if(!Q_stricmp(val,"(NULL)")) - { + if (String_Parse(args, &cvar) && String_Parse(args, &val)) { + if (!Q_stricmp(val, "(NULL)")) { DC->setCVar(cvar, ""); - } - else { + } else { DC->setCVar(cvar, val); } } @@ -2839,11 +2498,9 @@ qboolean Script_SetCvar(itemDef_t *item, const char **args) Script_Exec ================= */ -qboolean Script_Exec ( itemDef_t *item, const char **args) -{ +qboolean Script_Exec(itemDef_t *item, const char **args) { const char *val; - if (String_Parse(args, &val)) - { + if (String_Parse(args, &val)) { DC->executeText(EXEC_APPEND, va("%s ; ", val)); } @@ -2855,12 +2512,10 @@ qboolean Script_Exec ( itemDef_t *item, const char **args) Script_Play ================= */ -static qboolean Script_Play(itemDef_t *item, const char **args) -{ +static qboolean Script_Play(itemDef_t *item, const char **args) { const char *val; - if (String_Parse(args, &val)) - { - DC->startLocalSound(DC->registerSound(val, qfalse), CHAN_AUTO ); + if (String_Parse(args, &val)) { + DC->startLocalSound(DC->registerSound(val, qfalse), CHAN_AUTO); } return qtrue; @@ -2871,12 +2526,10 @@ static qboolean Script_Play(itemDef_t *item, const char **args) Script_PlayVoice ================= */ -static qboolean Script_PlayVoice(itemDef_t *item, const char **args) -{ +static qboolean Script_PlayVoice(itemDef_t *item, const char **args) { const char *val; - if (String_Parse(args, &val)) - { - DC->startLocalSound(DC->registerSound(val, qfalse), CHAN_VOICE ); + if (String_Parse(args, &val)) { + DC->startLocalSound(DC->registerSound(val, qfalse), CHAN_VOICE); } return qtrue; @@ -2887,9 +2540,8 @@ static qboolean Script_PlayVoice(itemDef_t *item, const char **args) Script_StopVoice ================= */ -static qboolean Script_StopVoice(itemDef_t *item, const char **args) -{ - DC->startLocalSound(uiInfo.uiDC.Assets.nullSound, CHAN_VOICE ); +static qboolean Script_StopVoice(itemDef_t *item, const char **args) { + DC->startLocalSound(uiInfo.uiDC.Assets.nullSound, CHAN_VOICE); return qtrue; } @@ -2919,72 +2571,63 @@ qboolean Script_playLooped(itemDef_t *item, const char **args) Script_Orbit ================= */ -qboolean Script_Orbit(itemDef_t *item, const char **args) -{ +qboolean Script_Orbit(itemDef_t *item, const char **args) { const char *name; float cx, cy, x, y; int time; - if (String_Parse(args, &name)) - { -// if ( Float_Parse(args, &x) && Float_Parse(args, &y) && Float_Parse(args, &cx) && Float_Parse(args, &cy) && Int_Parse(args, &time) ) - if ( !COM_ParseFloat(args, &x) && !COM_ParseFloat(args, &y) && !COM_ParseFloat(args, &cx) && !COM_ParseFloat(args, &cy) && Int_Parse(args, &time) ) - { - Menu_OrbitItemByName((menuDef_t *) item->parent, name, x, y, cx, cy, time); - } - } - - return qtrue; -} - - -commandDef_t commandList[] = -{ - {"activate", &Script_Activate}, // menu - {"close", &Script_Close}, // menu - {"exec", &Script_Exec}, // group/name - {"fadein", &Script_FadeIn}, // group/name - {"fadeout", &Script_FadeOut}, // group/name - {"hide", &Script_Hide}, // group/name - {"open", &Script_Open}, // menu - {"openGoToMenu", &Script_OpenGoToMenu}, // - {"orbit", &Script_Orbit}, // group/name - {"play", &Script_Play}, // group/name - {"playVoice", &Script_PlayVoice}, // group/name - {"stopVoice", &Script_StopVoice}, // group/name -// {"playlooped", &Script_playLooped}, // group/name - {"setasset", &Script_SetAsset}, // works on this - {"setbackground", &Script_SetBackground}, // works on this - {"setcolor", &Script_SetColor}, // works on this - {"setcvar", &Script_SetCvar}, // group/name - {"setfocus", &Script_SetFocus}, // sets this background color to team color - {"setitemcolor", &Script_SetItemColor}, // group/name - {"setitemflag", &Script_SetItemFlag}, // name - {"show", &Script_Show}, // group/name - {"showMenu", &Script_ShowMenu}, // menu - {"transition", &Script_Transition}, // group/name - {"transition2", &Script_Transition2}, // group/name - {"setitembackground", &Script_SetItemBackground}, // group/name - {"setitemtext", &Script_SetItemText}, // group/name - {"setitemrect", &Script_SetItemRect}, // group/name - {"defer", &Script_Defer}, // - {"rundeferred", &Script_RunDeferred}, // - {"delay", &Script_Delay}, // works on this (script) - {"transition3", &Script_Transition3}, // model exclusive transition - {"incrementfeeder", &Script_IncrementFeeder}, - {"decrementfeeder", &Script_DecrementFeeder} -}; + if (String_Parse(args, &name)) { + // if ( Float_Parse(args, &x) && Float_Parse(args, &y) && Float_Parse(args, &cx) && Float_Parse(args, &cy) && Int_Parse(args, &time) ) + if (!COM_ParseFloat(args, &x) && !COM_ParseFloat(args, &y) && !COM_ParseFloat(args, &cx) && !COM_ParseFloat(args, &cy) && Int_Parse(args, &time)) { + Menu_OrbitItemByName((menuDef_t *)item->parent, name, x, y, cx, cy, time); + } + } + + return qtrue; +} + +commandDef_t commandList[] = {{"activate", &Script_Activate}, // menu + {"close", &Script_Close}, // menu + {"exec", &Script_Exec}, // group/name + {"fadein", &Script_FadeIn}, // group/name + {"fadeout", &Script_FadeOut}, // group/name + {"hide", &Script_Hide}, // group/name + {"open", &Script_Open}, // menu + {"openGoToMenu", &Script_OpenGoToMenu}, // + {"orbit", &Script_Orbit}, // group/name + {"play", &Script_Play}, // group/name + {"playVoice", &Script_PlayVoice}, // group/name + {"stopVoice", &Script_StopVoice}, // group/name + // {"playlooped", &Script_playLooped}, // group/name + {"setasset", &Script_SetAsset}, // works on this + {"setbackground", &Script_SetBackground}, // works on this + {"setcolor", &Script_SetColor}, // works on this + {"setcvar", &Script_SetCvar}, // group/name + {"setfocus", &Script_SetFocus}, // sets this background color to team color + {"setitemcolor", &Script_SetItemColor}, // group/name + {"setitemflag", &Script_SetItemFlag}, // name + {"show", &Script_Show}, // group/name + {"showMenu", &Script_ShowMenu}, // menu + {"transition", &Script_Transition}, // group/name + {"transition2", &Script_Transition2}, // group/name + {"setitembackground", &Script_SetItemBackground}, // group/name + {"setitemtext", &Script_SetItemText}, // group/name + {"setitemrect", &Script_SetItemRect}, // group/name + {"defer", &Script_Defer}, // + {"rundeferred", &Script_RunDeferred}, // + {"delay", &Script_Delay}, // works on this (script) + {"transition3", &Script_Transition3}, // model exclusive transition + {"incrementfeeder", &Script_IncrementFeeder}, + {"decrementfeeder", &Script_DecrementFeeder}}; int scriptCommandCount = sizeof(commandList) / sizeof(commandDef_t); - /* =============== Item_Init =============== */ -void Item_Init(itemDef_t *item) -{ +void Item_Init(itemDef_t *item) { memset(item, 0, sizeof(itemDef_t)); item->textscale = 0.55f; Window_Init(&item->window); @@ -2995,54 +2638,37 @@ void Item_Init(itemDef_t *item) Item_Multi_Setting =============== */ -const char *Item_Multi_Setting(itemDef_t *item) -{ +const char *Item_Multi_Setting(itemDef_t *item) { char buff[1024]; float value = 0; int i; - multiDef_t *multiPtr = (multiDef_t*)item->typeData; - if (multiPtr) - { - if (multiPtr->strDef) - { - if (item->cvar) - { - DC->getCVarString(item->cvar, buff, sizeof(buff)); + multiDef_t *multiPtr = (multiDef_t *)item->typeData; + if (multiPtr) { + if (multiPtr->strDef) { + if (item->cvar) { + DC->getCVarString(item->cvar, buff, sizeof(buff)); + } else { } - else - { - - } - } - else - { - if (item->cvar) // Was a cvar given? + } else { + if (item->cvar) // Was a cvar given? { value = DC->getCVarValue(item->cvar); - } - else - { + } else { value = item->value; } } - for (i = 0; i < multiPtr->count; i++) - { - if (multiPtr->strDef) - { - if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->strDef) { + if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) { return multiPtr->cvarList[i]; } - } - else - { - if (multiPtr->cvarValue[i] == value) - { + } else { + if (multiPtr->cvarValue[i] == value) { return multiPtr->cvarList[i]; - } - } - } + } + } + } } #ifdef JK2_MODE @@ -3062,56 +2688,52 @@ ItemParse_name name =============== */ -qboolean ItemParse_name( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **)&item->window.name)) - { +qboolean ItemParse_name(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->window.name)) { return qfalse; } return qtrue; } -int MenuFontToReal( int menuFontIndex ) -{ +int MenuFontToReal(int menuFontIndex) { // Default fonts from a clean installation - switch ( menuFontIndex ) { - case 1: return UI_RegisterFont( "aurabesh" ); - case 2: return UI_RegisterFont( "ergoec" ); - case 3: return UI_RegisterFont( "anewhope" ); - case 4: return UI_RegisterFont( "arialnb" ); + switch (menuFontIndex) { + case 1: + return UI_RegisterFont("aurabesh"); + case 2: + return UI_RegisterFont("ergoec"); + case 3: + return UI_RegisterFont("anewhope"); + case 4: + return UI_RegisterFont("arialnb"); - default: - return DC->Assets.qhMediumFont; + default: + return DC->Assets.qhMediumFont; } } -qboolean ItemParse_font( itemDef_t *item ) -{ - if (PC_ParseInt(&item->font)) - { +qboolean ItemParse_font(itemDef_t *item) { + if (PC_ParseInt(&item->font)) { return qfalse; } // Translate to real font - item->font = MenuFontToReal( item->font ); + item->font = MenuFontToReal(item->font); return qtrue; } - /* =============== ItemParse_focusSound name =============== */ -qboolean ItemParse_focusSound( itemDef_t *item) -{ +qboolean ItemParse_focusSound(itemDef_t *item) { const char *temp; - if (PC_ParseString(&temp)) - { + if (PC_ParseString(&temp)) { return qfalse; } item->focusSound = DC->registerSound(temp, qfalse); @@ -3124,16 +2746,14 @@ ItemParse_text text =============== */ -qboolean ItemParse_text( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **) &item->text)) - { +qboolean ItemParse_text(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->text)) { return qfalse; } -//#ifdef _DEBUG -// UI_Debug_EnterReference("TEXT", item->text); -//#endif + //#ifdef _DEBUG + // UI_Debug_EnterReference("TEXT", item->text); + //#endif return qtrue; } @@ -3144,16 +2764,14 @@ ItemParse_descText text =============== */ -qboolean ItemParse_descText( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **) &item->descText)) - { +qboolean ItemParse_descText(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->descText)) { return qfalse; } -//#ifdef _DEBUG -// UI_Debug_EnterReference("DESC", item->descText); -//#endif + //#ifdef _DEBUG + // UI_Debug_EnterReference("DESC", item->descText); + //#endif return qtrue; } @@ -3164,16 +2782,14 @@ ItemParse_text text =============== */ -qboolean ItemParse_text2( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **) &item->text2)) - { +qboolean ItemParse_text2(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->text2)) { return qfalse; } -//#ifdef _DEBUG -// UI_Debug_EnterReference("TXT2", item->text2); -//#endif + //#ifdef _DEBUG + // UI_Debug_EnterReference("TXT2", item->text2); + //#endif return qtrue; } @@ -3184,10 +2800,8 @@ ItemParse_group group =============== */ -qboolean ItemParse_group( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **)&item->window.group)) - { +qboolean ItemParse_group(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->window.group)) { return qfalse; } @@ -3200,62 +2814,49 @@ ItemParse_asset_model asset_model =============== */ -qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name ) -{ +qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (!Q_stricmp(&name[strlen(name) - 4], ".glm")) - { //it's a ghoul2 model then - if ( item->ghoul2.size() && item->ghoul2[0].mModelindex >= 0) - { - DC->g2_RemoveGhoul2Model( item->ghoul2, 0 ); + if (!Q_stricmp(&name[strlen(name) - 4], ".glm")) { // it's a ghoul2 model then + if (item->ghoul2.size() && item->ghoul2[0].mModelindex >= 0) { + DC->g2_RemoveGhoul2Model(item->ghoul2, 0); item->flags &= ~ITF_G2VALID; } int g2Model = DC->g2_InitGhoul2Model(item->ghoul2, name, 0, 0, 0, 0, 0); - if (g2Model >= 0) - { + if (g2Model >= 0) { item->flags |= ITF_G2VALID; - if (modelPtr->g2anim) - { //does the menu request this model be playing an animation? + if (modelPtr->g2anim) { // does the menu request this model be playing an animation? DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qfalse); } - if ( modelPtr->g2skin ) - { - DC->g2_SetSkin( &item->ghoul2[0], 0, modelPtr->g2skin );//this is going to set the surfs on/off matching the skin file + if (modelPtr->g2skin) { + DC->g2_SetSkin(&item->ghoul2[0], 0, modelPtr->g2skin); // this is going to set the surfs on/off matching the skin file } } - } - else if(!(item->asset)) - { //guess it's just an md3 + } else if (!(item->asset)) { // guess it's just an md3 item->asset = DC->registerModel(name); item->flags &= ~ITF_G2VALID; } return qtrue; } -qboolean ItemParse_asset_model( itemDef_t *item ) -{ +qboolean ItemParse_asset_model(itemDef_t *item) { const char *temp; Item_ValidateTypeData(item); - if (PC_ParseString(&temp)) - { + if (PC_ParseString(&temp)) { return qfalse; } char modelPath[MAX_QPATH]; - if (!Q_stricmp(temp,"ui_char_model") ) - { - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", Cvar_VariableString ( "g_char_model" ) ); - } - else - { - Com_sprintf( modelPath, sizeof( modelPath ), temp); + if (!Q_stricmp(temp, "ui_char_model")) { + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", Cvar_VariableString("g_char_model")); + } else { + Com_sprintf(modelPath, sizeof(modelPath), temp); } - return (ItemParse_asset_model_go( item, modelPath )); + return (ItemParse_asset_model_go(item, modelPath)); } /* @@ -3264,12 +2865,10 @@ ItemParse_asset_model asset_shader =============== */ -qboolean ItemParse_asset_shader( itemDef_t *item) -{ +qboolean ItemParse_asset_shader(itemDef_t *item) { const char *temp; - if (PC_ParseString(&temp)) - { + if (PC_ParseString(&temp)) { return qfalse; } item->asset = DC->registerShaderNoMip(temp); @@ -3282,18 +2881,14 @@ ItemParse_asset_model model_origin =============== */ -qboolean ItemParse_model_origin( itemDef_t *item) -{ +qboolean ItemParse_model_origin(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (PC_ParseFloat(&modelPtr->origin[0])) - { - if (PC_ParseFloat(&modelPtr->origin[1])) - { - if (PC_ParseFloat(&modelPtr->origin[2])) - { + if (PC_ParseFloat(&modelPtr->origin[0])) { + if (PC_ParseFloat(&modelPtr->origin[1])) { + if (PC_ParseFloat(&modelPtr->origin[2])) { return qtrue; } } @@ -3307,14 +2902,12 @@ ItemParse_model_fovx model_fovx =============== */ -qboolean ItemParse_model_fovx( itemDef_t *item) -{ +qboolean ItemParse_model_fovx(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (PC_ParseFloat(&modelPtr->fov_x)) - { + if (PC_ParseFloat(&modelPtr->fov_x)) { return qfalse; } return qtrue; @@ -3326,14 +2919,12 @@ ItemParse_model_fovy model_fovy =============== */ -qboolean ItemParse_model_fovy( itemDef_t *item) -{ +qboolean ItemParse_model_fovy(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (PC_ParseFloat(&modelPtr->fov_y)) - { + if (PC_ParseFloat(&modelPtr->fov_y)) { return qfalse; } return qtrue; @@ -3345,14 +2936,12 @@ ItemParse_model_rotation model_rotation =============== */ -qboolean ItemParse_model_rotation( itemDef_t *item) -{ +qboolean ItemParse_model_rotation(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (PC_ParseInt(&modelPtr->rotationSpeed)) - { + if (PC_ParseInt(&modelPtr->rotationSpeed)) { return qfalse; } return qtrue; @@ -3364,24 +2953,22 @@ ItemParse_model_angle model_angle =============== */ -qboolean ItemParse_model_angle( itemDef_t *item) -{ +qboolean ItemParse_model_angle(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (PC_ParseInt(&modelPtr->angle)) - { + if (PC_ParseInt(&modelPtr->angle)) { return qfalse; } return qtrue; } // model_g2mins -qboolean ItemParse_model_g2mins( itemDef_t *item ) { +qboolean ItemParse_model_g2mins(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; if (!PC_ParseFloat(&modelPtr->g2mins[0])) { if (!PC_ParseFloat(&modelPtr->g2mins[1])) { @@ -3394,10 +2981,10 @@ qboolean ItemParse_model_g2mins( itemDef_t *item ) { } // model_g2maxs -qboolean ItemParse_model_g2maxs( itemDef_t *item ) { +qboolean ItemParse_model_g2maxs(itemDef_t *item) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; if (!PC_ParseFloat(&modelPtr->g2maxs[0])) { if (!PC_ParseFloat(&modelPtr->g2maxs[1])) { @@ -3410,58 +2997,50 @@ qboolean ItemParse_model_g2maxs( itemDef_t *item ) { } // model_g2skin -qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ) -{ +qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName) { modelDef_t *modelPtr; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (!skinName || !skinName[0]) - { //it was parsed cor~rectly so still return true. + if (!skinName || !skinName[0]) { // it was parsed cor~rectly so still return true. modelPtr->g2skin = 0; - DC->g2_SetSkin( &item->ghoul2[0], -1, 0 );//turn off custom skin + DC->g2_SetSkin(&item->ghoul2[0], -1, 0); // turn off custom skin return qtrue; } modelPtr->g2skin = DC->registerSkin(skinName); - if ( item->ghoul2.IsValid() ) - { - DC->g2_SetSkin( &item->ghoul2[0], 0, modelPtr->g2skin );//this is going to set the surfs on/off matching the skin file + if (item->ghoul2.IsValid()) { + DC->g2_SetSkin(&item->ghoul2[0], 0, modelPtr->g2skin); // this is going to set the surfs on/off matching the skin file } return qtrue; } -qboolean ItemParse_model_g2skin( itemDef_t *item ) -{ +qboolean ItemParse_model_g2skin(itemDef_t *item) { const char *skinName; if (PC_ParseString(&skinName)) { return qfalse; } - return (ItemParse_model_g2skin_go( item, skinName )); + return (ItemParse_model_g2skin_go(item, skinName)); } // model_g2anim -qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ) -{ +qboolean ItemParse_model_g2anim_go(itemDef_t *item, const char *animName) { modelDef_t *modelPtr; int i = 0; Item_ValidateTypeData(item); - modelPtr = (modelDef_t*)item->typeData; + modelPtr = (modelDef_t *)item->typeData; - if (!animName || !animName[0]) - { //it was parsed correctly so still return true. + if (!animName || !animName[0]) { // it was parsed correctly so still return true. return qtrue; } - while (i < MAX_ANIMATIONS) - { - if (!Q_stricmp(animName, animTable[i].name)) - { //found it + while (i < MAX_ANIMATIONS) { + if (!Q_stricmp(animName, animTable[i].name)) { // found it modelPtr->g2anim = animTable[i].id; return qtrue; } @@ -3472,14 +3051,14 @@ qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ) return qtrue; } -qboolean ItemParse_model_g2anim( itemDef_t *item ) { +qboolean ItemParse_model_g2anim(itemDef_t *item) { const char *animName; if (PC_ParseString(&animName)) { return qfalse; } - return ItemParse_model_g2anim_go( item, animName ); + return ItemParse_model_g2anim_go(item, animName); } /* @@ -3488,10 +3067,8 @@ ItemParse_rect rect =============== */ -qboolean ItemParse_rect( itemDef_t *item) -{ - if (!PC_ParseRect(&item->window.rectClient)) - { +qboolean ItemParse_rect(itemDef_t *item) { + if (!PC_ParseRect(&item->window.rectClient)) { return qfalse; } @@ -3504,66 +3081,55 @@ ItemParse_flag flag =============== */ -qboolean ItemParse_flag( itemDef_t *item) -{ - int i; - const char *tempStr; +qboolean ItemParse_flag(itemDef_t *item) { + int i; + const char *tempStr; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (itemFlags[i].string) - { - if (Q_stricmp(tempStr,itemFlags[i].string)==0) - { + i = 0; + while (itemFlags[i].string) { + if (Q_stricmp(tempStr, itemFlags[i].string) == 0) { item->window.flags |= itemFlags[i].value; break; } i++; } - if (itemFlags[i].string == NULL) - { - PC_ParseWarning(va("Unknown item flag value '%s'",tempStr)); + if (itemFlags[i].string == NULL) { + PC_ParseWarning(va("Unknown item flag value '%s'", tempStr)); } return qtrue; } - /* =============== ItemParse_style style =============== */ -qboolean ItemParse_style( itemDef_t *item) -{ - int i; - const char *tempStr; +qboolean ItemParse_style(itemDef_t *item) { + int i; + const char *tempStr; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (styles[i]) - { - if (Q_stricmp(tempStr,styles[i])==0) - { + i = 0; + while (styles[i]) { + if (Q_stricmp(tempStr, styles[i]) == 0) { item->window.style = i; break; } i++; } - if (styles[i] == NULL) - { - PC_ParseWarning(va("Unknown item style value '%s'",tempStr)); + if (styles[i] == NULL) { + PC_ParseWarning(va("Unknown item style value '%s'", tempStr)); } return qtrue; @@ -3575,8 +3141,7 @@ ItemParse_decoration decoration =============== */ -qboolean ItemParse_decoration( itemDef_t *item ) -{ +qboolean ItemParse_decoration(itemDef_t *item) { item->window.flags |= WINDOW_DECORATION; return qtrue; } @@ -3587,14 +3152,12 @@ ItemParse_notselectable notselectable =============== */ -qboolean ItemParse_notselectable( itemDef_t *item ) -{ +qboolean ItemParse_notselectable(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - listPtr = (listBoxDef_t*)item->typeData; + listPtr = (listBoxDef_t *)item->typeData; - if (item->type == ITEM_TYPE_LISTBOX && listPtr) - { + if (item->type == ITEM_TYPE_LISTBOX && listPtr) { listPtr->notselectable = qtrue; } return qtrue; @@ -3606,92 +3169,76 @@ ItemParse_scrollhidden scrollhidden =============== */ -qboolean ItemParse_scrollhidden( itemDef_t *item ) -{ +qboolean ItemParse_scrollhidden(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - listPtr = (listBoxDef_t*)item->typeData; + listPtr = (listBoxDef_t *)item->typeData; - if (item->type == ITEM_TYPE_LISTBOX && listPtr) - { + if (item->type == ITEM_TYPE_LISTBOX && listPtr) { listPtr->scrollhidden = qtrue; } return qtrue; } - /* =============== ItemParse_wrapped manually wrapped =============== */ -qboolean ItemParse_wrapped( itemDef_t *item ) -{ +qboolean ItemParse_wrapped(itemDef_t *item) { item->window.flags |= WINDOW_WRAPPED; return qtrue; } - /* =============== ItemParse_autowrapped auto wrapped =============== */ -qboolean ItemParse_autowrapped( itemDef_t *item) -{ +qboolean ItemParse_autowrapped(itemDef_t *item) { item->window.flags |= WINDOW_AUTOWRAPPED; return qtrue; } - /* =============== ItemParse_horizontalscroll horizontalscroll =============== */ -qboolean ItemParse_horizontalscroll( itemDef_t *item ) -{ +qboolean ItemParse_horizontalscroll(itemDef_t *item) { item->window.flags |= WINDOW_HORIZONTAL; return qtrue; } - /* =============== ItemParse_type type =============== */ -qboolean ItemParse_type( itemDef_t *item ) -{ - int i; - const char *tempStr; +qboolean ItemParse_type(itemDef_t *item) { + int i; + const char *tempStr; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (types[i]) - { - if (Q_stricmp(tempStr,types[i])==0) - { + i = 0; + while (types[i]) { + if (Q_stricmp(tempStr, types[i]) == 0) { item->type = i; break; } i++; } - if (types[i] == NULL) - { - PC_ParseWarning(va("Unknown item type value '%s'",tempStr)); - } - else - { + if (types[i] == NULL) { + PC_ParseWarning(va("Unknown item type value '%s'", tempStr)); + } else { Item_ValidateTypeData(item); } return qtrue; @@ -3704,18 +3251,15 @@ ItemParse_elementwidth uses textalignx for storage =============== */ -qboolean ItemParse_elementwidth( itemDef_t *item ) -{ +qboolean ItemParse_elementwidth(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - listPtr = (listBoxDef_t*)item->typeData; - if (PC_ParseFloat(&listPtr->elementWidth)) - { + listPtr = (listBoxDef_t *)item->typeData; + if (PC_ParseFloat(&listPtr->elementWidth)) { return qfalse; } return qtrue; - } /* @@ -3725,14 +3269,12 @@ ItemParse_elementheight uses textaligny for storage =============== */ -qboolean ItemParse_elementheight( itemDef_t *item ) -{ +qboolean ItemParse_elementheight(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - listPtr = (listBoxDef_t*)item->typeData; - if (PC_ParseFloat(&listPtr->elementHeight)) - { + listPtr = (listBoxDef_t *)item->typeData; + if (PC_ParseFloat(&listPtr->elementHeight)) { return qfalse; } return qtrue; @@ -3744,10 +3286,8 @@ ItemParse_feeder feeder =============== */ -qboolean ItemParse_feeder( itemDef_t *item ) -{ - if (PC_ParseFloat( &item->special)) - { +qboolean ItemParse_feeder(itemDef_t *item) { + if (PC_ParseFloat(&item->special)) { return qfalse; } return qtrue; @@ -3760,19 +3300,16 @@ ItemParse_elementtype uses textstyle for storage =============== */ -qboolean ItemParse_elementtype( itemDef_t *item ) -{ +qboolean ItemParse_elementtype(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - listPtr = (listBoxDef_t*)item->typeData; - if (PC_ParseInt(&listPtr->elementStyle)) - { + listPtr = (listBoxDef_t *)item->typeData; + if (PC_ParseInt(&listPtr->elementStyle)) { return qfalse; } return qtrue; @@ -3784,43 +3321,33 @@ ItemParse_columns columns sets a number of columns and an x pos and width per.. =============== */ -qboolean ItemParse_columns( itemDef_t *item) -{ +qboolean ItemParse_columns(itemDef_t *item) { int num, i; listBoxDef_t *listPtr; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - listPtr = (listBoxDef_t*)item->typeData; - if (!PC_ParseInt(&num)) - { - if (num > MAX_LB_COLUMNS) - { + listPtr = (listBoxDef_t *)item->typeData; + if (!PC_ParseInt(&num)) { + if (num > MAX_LB_COLUMNS) { num = MAX_LB_COLUMNS; } listPtr->numColumns = num; - for (i = 0; i < num; i++) - { + for (i = 0; i < num; i++) { int pos, width, maxChars; - if (!PC_ParseInt(&pos) && !PC_ParseInt(&width) && !PC_ParseInt(&maxChars)) - { + if (!PC_ParseInt(&pos) && !PC_ParseInt(&width) && !PC_ParseInt(&maxChars)) { listPtr->columnInfo[i].pos = pos; listPtr->columnInfo[i].width = width; listPtr->columnInfo[i].maxChars = maxChars; - } - else - { + } else { return qfalse; } } - } - else - { + } else { return qfalse; } @@ -3832,10 +3359,8 @@ qboolean ItemParse_columns( itemDef_t *item) ItemParse_border =============== */ -qboolean ItemParse_border( itemDef_t *item) -{ - if (PC_ParseInt(&item->window.border)) - { +qboolean ItemParse_border(itemDef_t *item) { + if (PC_ParseInt(&item->window.border)) { return qfalse; } @@ -3847,10 +3372,8 @@ qboolean ItemParse_border( itemDef_t *item) ItemParse_bordersize =============== */ -qboolean ItemParse_bordersize( itemDef_t *item ) -{ - if (PC_ParseFloat(&item->window.borderSize)) - { +qboolean ItemParse_bordersize(itemDef_t *item) { + if (PC_ParseFloat(&item->window.borderSize)) { return qfalse; } return qtrue; @@ -3861,16 +3384,13 @@ qboolean ItemParse_bordersize( itemDef_t *item ) ItemParse_visible =============== */ -qboolean ItemParse_visible( itemDef_t *item) -{ +qboolean ItemParse_visible(itemDef_t *item) { int i; - if (PC_ParseInt(&i)) - { + if (PC_ParseInt(&i)) { return qfalse; } - if (i) - { + if (i) { item->window.flags |= WINDOW_VISIBLE; } return qtrue; @@ -3881,10 +3401,8 @@ qboolean ItemParse_visible( itemDef_t *item) ItemParse_ownerdraw =============== */ -qboolean ItemParse_ownerdraw( itemDef_t *item) -{ - if (PC_ParseInt(&item->window.ownerDraw)) - { +qboolean ItemParse_ownerdraw(itemDef_t *item) { + if (PC_ParseInt(&item->window.ownerDraw)) { return qfalse; } item->type = ITEM_TYPE_OWNERDRAW; @@ -3896,10 +3414,8 @@ qboolean ItemParse_ownerdraw( itemDef_t *item) ItemParse_align =============== */ -qboolean ItemParse_align( itemDef_t *item) -{ - if (PC_ParseInt(&item->alignment)) - { +qboolean ItemParse_align(itemDef_t *item) { + if (PC_ParseInt(&item->alignment)) { return qfalse; } return qtrue; @@ -3910,49 +3426,40 @@ qboolean ItemParse_align( itemDef_t *item) ItemParse_align =============== */ -qboolean ItemParse_Appearance_slot( itemDef_t *item) -{ - if (PC_ParseInt(&item->appearanceSlot)) - { +qboolean ItemParse_Appearance_slot(itemDef_t *item) { + if (PC_ParseInt(&item->appearanceSlot)) { return qfalse; } return qtrue; } - /* =============== ItemParse_textalign =============== */ -qboolean ItemParse_textalign( itemDef_t *item ) -{ +qboolean ItemParse_textalign(itemDef_t *item) { const char *tempStr; - int i; + int i; - if (PC_ParseString(&tempStr)) - { + if (PC_ParseString(&tempStr)) { return qfalse; } - i=0; - while (alignment[i]) - { - if (Q_stricmp(tempStr,alignment[i])==0) - { + i = 0; + while (alignment[i]) { + if (Q_stricmp(tempStr, alignment[i]) == 0) { item->textalignment = i; break; } i++; } - if (alignment[i] == NULL) - { - PC_ParseWarning(va("Unknown text alignment value '%s'",tempStr)); + if (alignment[i] == NULL) { + PC_ParseWarning(va("Unknown text alignment value '%s'", tempStr)); } return qtrue; - } /* @@ -3960,10 +3467,8 @@ qboolean ItemParse_textalign( itemDef_t *item ) ItemParse_text2alignx =============== */ -qboolean ItemParse_text2alignx( itemDef_t *item) -{ - if (PC_ParseFloat(&item->text2alignx)) - { +qboolean ItemParse_text2alignx(itemDef_t *item) { + if (PC_ParseFloat(&item->text2alignx)) { return qfalse; } return qtrue; @@ -3974,10 +3479,8 @@ qboolean ItemParse_text2alignx( itemDef_t *item) ItemParse_text2aligny =============== */ -qboolean ItemParse_text2aligny( itemDef_t *item) -{ - if (PC_ParseFloat(&item->text2aligny)) - { +qboolean ItemParse_text2aligny(itemDef_t *item) { + if (PC_ParseFloat(&item->text2aligny)) { return qfalse; } return qtrue; @@ -3988,10 +3491,8 @@ qboolean ItemParse_text2aligny( itemDef_t *item) ItemParse_textalignx =============== */ -qboolean ItemParse_textalignx( itemDef_t *item) -{ - if (PC_ParseFloat(&item->textalignx)) - { +qboolean ItemParse_textalignx(itemDef_t *item) { + if (PC_ParseFloat(&item->textalignx)) { return qfalse; } return qtrue; @@ -4002,10 +3503,8 @@ qboolean ItemParse_textalignx( itemDef_t *item) ItemParse_textaligny =============== */ -qboolean ItemParse_textaligny( itemDef_t *item) -{ - if (PC_ParseFloat(&item->textaligny)) - { +qboolean ItemParse_textaligny(itemDef_t *item) { + if (PC_ParseFloat(&item->textaligny)) { return qfalse; } return qtrue; @@ -4016,10 +3515,8 @@ qboolean ItemParse_textaligny( itemDef_t *item) ItemParse_textscale =============== */ -qboolean ItemParse_textscale( itemDef_t *item ) -{ - if (PC_ParseFloat(&item->textscale)) - { +qboolean ItemParse_textscale(itemDef_t *item) { + if (PC_ParseFloat(&item->textscale)) { return qfalse; } return qtrue; @@ -4030,25 +3527,20 @@ qboolean ItemParse_textscale( itemDef_t *item ) ItemParse_textstyle =============== */ -qboolean ItemParse_textstyle( itemDef_t *item) -{ - if (PC_ParseInt(&item->textStyle)) - { +qboolean ItemParse_textstyle(itemDef_t *item) { + if (PC_ParseInt(&item->textStyle)) { return qfalse; } return qtrue; } - /* =============== ItemParse_invertyesno =============== */ -qboolean ItemParse_invertyesno( itemDef_t *item) -{ - if (PC_ParseInt(&item->invertYesNo)) - { +qboolean ItemParse_invertyesno(itemDef_t *item) { + if (PC_ParseInt(&item->invertYesNo)) { return qfalse; } return qtrue; @@ -4059,33 +3551,27 @@ qboolean ItemParse_invertyesno( itemDef_t *item) ItemParse_xoffset (used for yes/no and multi) =============== */ -qboolean ItemParse_xoffset( itemDef_t *item) -{ - if (PC_ParseInt(&item->xoffset)) - { +qboolean ItemParse_xoffset(itemDef_t *item) { + if (PC_ParseInt(&item->xoffset)) { return qfalse; } return qtrue; } - /* =============== ItemParse_backcolor =============== */ -qboolean ItemParse_backcolor( itemDef_t *item) -{ +qboolean ItemParse_backcolor(itemDef_t *item) { int i; float f; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - item->window.backColor[i] = f; + item->window.backColor[i] = f; } return qtrue; } @@ -4095,23 +3581,19 @@ qboolean ItemParse_backcolor( itemDef_t *item) ItemParse_forecolor =============== */ -qboolean ItemParse_forecolor( itemDef_t *item) -{ +qboolean ItemParse_forecolor(itemDef_t *item) { int i; float f; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - if (f < 0) - { //special case for player color + if (f < 0) { // special case for player color item->window.flags |= WINDOW_PLAYERCOLOR; return qtrue; } - item->window.foreColor[i] = f; + item->window.foreColor[i] = f; item->window.flags |= WINDOW_FORECOLORSET; } return qtrue; @@ -4122,18 +3604,15 @@ qboolean ItemParse_forecolor( itemDef_t *item) ItemParse_bordercolor =============== */ -qboolean ItemParse_bordercolor( itemDef_t *item) -{ +qboolean ItemParse_bordercolor(itemDef_t *item) { int i; float f; - for (i = 0; i < 4; i++) - { - if (PC_ParseFloat(&f)) - { + for (i = 0; i < 4; i++) { + if (PC_ParseFloat(&f)) { return qfalse; } - item->window.borderColor[i] = f; + item->window.borderColor[i] = f; } return qtrue; } @@ -4143,10 +3622,8 @@ qboolean ItemParse_bordercolor( itemDef_t *item) ItemParse_outlinecolor =============== */ -qboolean ItemParse_outlinecolor( itemDef_t *item) -{ - if (PC_ParseColor(&item->window.outlineColor)) - { +qboolean ItemParse_outlinecolor(itemDef_t *item) { + if (PC_ParseColor(&item->window.outlineColor)) { return qfalse; } return qtrue; @@ -4157,12 +3634,10 @@ qboolean ItemParse_outlinecolor( itemDef_t *item) ItemParse_background =============== */ -qboolean ItemParse_background( itemDef_t *item) -{ +qboolean ItemParse_background(itemDef_t *item) { const char *temp; - if (PC_ParseString(&temp)) - { + if (PC_ParseString(&temp)) { return qfalse; } item->window.background = ui.R_RegisterShaderNoMip(temp); @@ -4174,10 +3649,8 @@ qboolean ItemParse_background( itemDef_t *item) ItemParse_cinematic =============== */ -qboolean ItemParse_cinematic( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **) &item->window.cinematicName)) - { +qboolean ItemParse_cinematic(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->window.cinematicName)) { return qfalse; } return qtrue; @@ -4188,20 +3661,17 @@ qboolean ItemParse_cinematic( itemDef_t *item) ItemParse_doubleClick =============== */ -qboolean ItemParse_doubleClick( itemDef_t *item) -{ +qboolean ItemParse_doubleClick(itemDef_t *item) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - listPtr = (listBoxDef_t*)item->typeData; + listPtr = (listBoxDef_t *)item->typeData; - if (!PC_Script_Parse(&listPtr->doubleClick)) - { + if (!PC_Script_Parse(&listPtr->doubleClick)) { return qfalse; } return qtrue; @@ -4212,10 +3682,8 @@ qboolean ItemParse_doubleClick( itemDef_t *item) ItemParse_onFocus =============== */ -qboolean ItemParse_onFocus( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->onFocus)) - { +qboolean ItemParse_onFocus(itemDef_t *item) { + if (!PC_Script_Parse(&item->onFocus)) { return qfalse; } return qtrue; @@ -4226,10 +3694,8 @@ qboolean ItemParse_onFocus( itemDef_t *item) ItemParse_leaveFocus =============== */ -qboolean ItemParse_leaveFocus( itemDef_t *item ) -{ - if (!PC_Script_Parse(&item->leaveFocus)) - { +qboolean ItemParse_leaveFocus(itemDef_t *item) { + if (!PC_Script_Parse(&item->leaveFocus)) { return qfalse; } return qtrue; @@ -4240,10 +3706,8 @@ qboolean ItemParse_leaveFocus( itemDef_t *item ) ItemParse_mouseEnter =============== */ -qboolean ItemParse_mouseEnter( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->mouseEnter)) - { +qboolean ItemParse_mouseEnter(itemDef_t *item) { + if (!PC_Script_Parse(&item->mouseEnter)) { return qfalse; } return qtrue; @@ -4254,10 +3718,8 @@ qboolean ItemParse_mouseEnter( itemDef_t *item) ItemParse_mouseExit =============== */ -qboolean ItemParse_mouseExit( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->mouseExit)) - { +qboolean ItemParse_mouseExit(itemDef_t *item) { + if (!PC_Script_Parse(&item->mouseExit)) { return qfalse; } return qtrue; @@ -4268,10 +3730,8 @@ qboolean ItemParse_mouseExit( itemDef_t *item) ItemParse_mouseEnterText =============== */ -qboolean ItemParse_mouseEnterText( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->mouseEnterText)) - { +qboolean ItemParse_mouseEnterText(itemDef_t *item) { + if (!PC_Script_Parse(&item->mouseEnterText)) { return qfalse; } return qtrue; @@ -4282,41 +3742,33 @@ qboolean ItemParse_mouseEnterText( itemDef_t *item) ItemParse_mouseExitText =============== */ -qboolean ItemParse_mouseExitText( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->mouseExitText)) - { +qboolean ItemParse_mouseExitText(itemDef_t *item) { + if (!PC_Script_Parse(&item->mouseExitText)) { return qfalse; } return qtrue; } - /* =============== ItemParse_accept =============== */ -qboolean ItemParse_accept( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->accept)) - { +qboolean ItemParse_accept(itemDef_t *item) { + if (!PC_Script_Parse(&item->accept)) { return qfalse; } return qtrue; } - -//JLFDPADSCRIPT +// JLFDPADSCRIPT /* =============== ItemParse_selectionNext =============== */ -qboolean ItemParse_selectionNext( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->selectionNext)) - { +qboolean ItemParse_selectionNext(itemDef_t *item) { + if (!PC_Script_Parse(&item->selectionNext)) { return qfalse; } return qtrue; @@ -4327,45 +3779,33 @@ qboolean ItemParse_selectionNext( itemDef_t *item) ItemParse_selectionPrev =============== */ -qboolean ItemParse_selectionPrev( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->selectionPrev)) - { +qboolean ItemParse_selectionPrev(itemDef_t *item) { + if (!PC_Script_Parse(&item->selectionPrev)) { return qfalse; } return qtrue; } // END JLFDPADSCRIPT - - - - - /* =============== ItemParse_action =============== */ -qboolean ItemParse_action( itemDef_t *item) -{ - if (!PC_Script_Parse(&item->action)) - { +qboolean ItemParse_action(itemDef_t *item) { + if (!PC_Script_Parse(&item->action)) { return qfalse; } return qtrue; } - /* =============== ItemParse_special =============== */ -qboolean ItemParse_special( itemDef_t *item) -{ - if (PC_ParseFloat(&item->special)) - { +qboolean ItemParse_special(itemDef_t *item) { + if (PC_ParseFloat(&item->special)) { return qfalse; } return qtrue; @@ -4376,10 +3816,8 @@ qboolean ItemParse_special( itemDef_t *item) ItemParse_cvarTest =============== */ -qboolean ItemParse_cvarTest( itemDef_t *item) -{ - if (!PC_ParseStringMem((const char **) &item->cvarTest)) - { +qboolean ItemParse_cvarTest(itemDef_t *item) { + if (!PC_ParseStringMem((const char **)&item->cvarTest)) { return qfalse; } return qtrue; @@ -4390,32 +3828,28 @@ qboolean ItemParse_cvarTest( itemDef_t *item) ItemParse_cvar =============== */ -qboolean ItemParse_cvar( itemDef_t *item) -{ +qboolean ItemParse_cvar(itemDef_t *item) { editFieldDef_t *editPtr; Item_ValidateTypeData(item); - if (!PC_ParseStringMem(&item->cvar)) - { + if (!PC_ParseStringMem(&item->cvar)) { return qfalse; } - if ( item->typeData) - { - switch ( item->type ) - { - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_SLIDER: - case ITEM_TYPE_TEXT: - case ITEM_TYPE_TEXTSCROLL: - editPtr = (editFieldDef_t*)item->typeData; - editPtr->minVal = -1; - editPtr->maxVal = -1; - editPtr->defVal = -1; - break; + if (item->typeData) { + switch (item->type) { + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_SLIDER: + case ITEM_TYPE_TEXT: + case ITEM_TYPE_TEXTSCROLL: + editPtr = (editFieldDef_t *)item->typeData; + editPtr->minVal = -1; + editPtr->maxVal = -1; + editPtr->defVal = -1; + break; } } return qtrue; @@ -4426,22 +3860,19 @@ qboolean ItemParse_cvar( itemDef_t *item) ItemParse_maxChars =============== */ -qboolean ItemParse_maxChars( itemDef_t *item) -{ +qboolean ItemParse_maxChars(itemDef_t *item) { editFieldDef_t *editPtr; int maxChars; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - if (PC_ParseInt(&maxChars)) - { + if (PC_ParseInt(&maxChars)) { return qfalse; } - editPtr = (editFieldDef_t*)item->typeData; + editPtr = (editFieldDef_t *)item->typeData; editPtr->maxChars = maxChars; return qtrue; } @@ -4451,44 +3882,37 @@ qboolean ItemParse_maxChars( itemDef_t *item) ItemParse_maxPaintChars =============== */ -qboolean ItemParse_maxPaintChars( itemDef_t *item) -{ +qboolean ItemParse_maxPaintChars(itemDef_t *item) { editFieldDef_t *editPtr; int maxChars; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - if (PC_ParseInt(&maxChars)) - { + if (PC_ParseInt(&maxChars)) { return qfalse; } - editPtr = (editFieldDef_t*)item->typeData; + editPtr = (editFieldDef_t *)item->typeData; editPtr->maxPaintChars = maxChars; return qtrue; } - -qboolean ItemParse_lineHeight( itemDef_t *item) -{ +qboolean ItemParse_lineHeight(itemDef_t *item) { textScrollDef_t *scrollPtr; - int height; + int height; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - if (PC_ParseInt(&height)) - { + if (PC_ParseInt(&height)) { return qfalse; } - scrollPtr = (textScrollDef_t*)item->typeData; + scrollPtr = (textScrollDef_t *)item->typeData; scrollPtr->lineHeight = height; return qtrue; @@ -4499,24 +3923,18 @@ qboolean ItemParse_lineHeight( itemDef_t *item) ItemParse_cvarFloat =============== */ -qboolean ItemParse_cvarFloat( itemDef_t *item) -{ +qboolean ItemParse_cvarFloat(itemDef_t *item) { editFieldDef_t *editPtr; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - editPtr = (editFieldDef_t*)item->typeData; - if (PC_ParseStringMem((const char **) &item->cvar) && - !PC_ParseFloat(&editPtr->defVal) && - !PC_ParseFloat(&editPtr->minVal) && - !PC_ParseFloat(&editPtr->maxVal)) - { - if (!Q_stricmp(item->cvar,"r_ext_texture_filter_anisotropic")) - {//hehe, hook up the correct max value here. - editPtr->maxVal=cls.glconfig.maxTextureFilterAnisotropy; + editPtr = (editFieldDef_t *)item->typeData; + if (PC_ParseStringMem((const char **)&item->cvar) && !PC_ParseFloat(&editPtr->defVal) && !PC_ParseFloat(&editPtr->minVal) && + !PC_ParseFloat(&editPtr->maxVal)) { + if (!Q_stricmp(item->cvar, "r_ext_texture_filter_anisotropic")) { // hehe, hook up the correct max value here. + editPtr->maxVal = cls.glconfig.maxTextureFilterAnisotropy; } return qtrue; } @@ -4529,85 +3947,69 @@ qboolean ItemParse_cvarFloat( itemDef_t *item) ItemParse_cvarStrList =============== */ -qboolean ItemParse_cvarStrList( itemDef_t *item) -{ - const char *token; +qboolean ItemParse_cvarStrList(itemDef_t *item) { + const char *token; multiDef_t *multiPtr; int pass; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - multiPtr = (multiDef_t*)item->typeData; + multiPtr = (multiDef_t *)item->typeData; multiPtr->count = 0; multiPtr->strDef = qtrue; - if (PC_ParseString(&token)) - { + if (PC_ParseString(&token)) { return qfalse; } - if (!Q_stricmp(token,"feeder") && item->special == FEEDER_PLAYER_SPECIES) - { - for (; multiPtr->count < uiInfo.playerSpeciesCount; multiPtr->count++) - { - multiPtr->cvarList[multiPtr->count] = String_Alloc(Q_strupr(va("@MENUS_%s",uiInfo.playerSpecies[multiPtr->count].Name ))); //look up translation - multiPtr->cvarStr[multiPtr->count] = uiInfo.playerSpecies[multiPtr->count].Name; //value + if (!Q_stricmp(token, "feeder") && item->special == FEEDER_PLAYER_SPECIES) { + for (; multiPtr->count < uiInfo.playerSpeciesCount; multiPtr->count++) { + multiPtr->cvarList[multiPtr->count] = String_Alloc(Q_strupr(va("@MENUS_%s", uiInfo.playerSpecies[multiPtr->count].Name))); // look up translation + multiPtr->cvarStr[multiPtr->count] = uiInfo.playerSpecies[multiPtr->count].Name; // value } return qtrue; } // languages - if (!Q_stricmp(token,"feeder") && item->special == FEEDER_LANGUAGES) - { - for (; multiPtr->count < uiInfo.languageCount; multiPtr->count++) - { + if (!Q_stricmp(token, "feeder") && item->special == FEEDER_LANGUAGES) { + for (; multiPtr->count < uiInfo.languageCount; multiPtr->count++) { // The displayed text multiPtr->cvarList[multiPtr->count] = "@MENUS_MYLANGUAGE"; // The cvar value that goes into se_language #ifndef JK2_MODE // FIXME - multiPtr->cvarStr[multiPtr->count] = SE_GetLanguageName(multiPtr->count); + multiPtr->cvarStr[multiPtr->count] = SE_GetLanguageName(multiPtr->count); #endif } return qtrue; } - if (*token != '{') - { + if (*token != '{') { return qfalse; } pass = 0; - while ( 1 ) - { - if (!PC_ParseStringMem(&token)) - { + while (1) { + if (!PC_ParseStringMem(&token)) { PC_ParseWarning("end of file inside menu item\n"); return qfalse; } - if (*token == '}') - { + if (*token == '}') { return qtrue; } - if (*token == ',' || *token == ';') - { + if (*token == ',' || *token == ';') { continue; } - if (pass == 0) - { + if (pass == 0) { multiPtr->cvarList[multiPtr->count] = token; pass = 1; - } - else - { + } else { multiPtr->cvarStr[multiPtr->count] = token; pass = 0; multiPtr->count++; - if (multiPtr->count >= MAX_MULTI_CVARS) - { + if (multiPtr->count >= MAX_MULTI_CVARS) { return qfalse; } } @@ -4621,81 +4023,64 @@ qboolean ItemParse_cvarStrList( itemDef_t *item) ItemParse_cvarFloatList =============== */ -qboolean ItemParse_cvarFloatList( itemDef_t *item) -{ - const char *token; - multiDef_t *multiPtr; +qboolean ItemParse_cvarFloatList(itemDef_t *item) { + const char *token; + multiDef_t *multiPtr; Item_ValidateTypeData(item); - if (!item->typeData) - { + if (!item->typeData) { return qfalse; } - multiPtr = (multiDef_t*)item->typeData; + multiPtr = (multiDef_t *)item->typeData; multiPtr->count = 0; multiPtr->strDef = qfalse; - if (PC_ParseString(&token)) - { + if (PC_ParseString(&token)) { return qfalse; } - if (*token != '{') - { + if (*token != '{') { return qfalse; } - while ( 1 ) - { - if (!PC_ParseStringMem(&token)) - { + while (1) { + if (!PC_ParseStringMem(&token)) { PC_ParseWarning("end of file inside menu item\n"); return qfalse; } - if (*token == '}') - { + if (*token == '}') { return qtrue; } - if (*token == ',' || *token == ';') - { + if (*token == ',' || *token == ';') { continue; } - multiPtr->cvarList[multiPtr->count] = token; //a StringAlloc ptr - if (PC_ParseFloat(&multiPtr->cvarValue[multiPtr->count])) - { + multiPtr->cvarList[multiPtr->count] = token; // a StringAlloc ptr + if (PC_ParseFloat(&multiPtr->cvarValue[multiPtr->count])) { return qfalse; } multiPtr->count++; - if (multiPtr->count >= MAX_MULTI_CVARS) - { + if (multiPtr->count >= MAX_MULTI_CVARS) { return qfalse; } - } return qfalse; } - /* =============== ItemParse_addColorRange =============== */ -qboolean ItemParse_addColorRange( itemDef_t *item) -{ +qboolean ItemParse_addColorRange(itemDef_t *item) { colorRangeDef_t color; - if (PC_ParseFloat(&color.low) && - PC_ParseFloat(&color.high) && - PC_ParseColor(&color.color) ) - { + if (PC_ParseFloat(&color.low) && PC_ParseFloat(&color.high) && PC_ParseColor(&color.color)) { - if (item->numColors < MAX_COLOR_RANGES) - { + if (item->numColors < MAX_COLOR_RANGES) { memcpy(&item->colorRanges[item->numColors], &color, sizeof(color)); item->numColors++; } @@ -4709,11 +4094,9 @@ qboolean ItemParse_addColorRange( itemDef_t *item) ItemParse_ownerdrawFlag =============== */ -qboolean ItemParse_ownerdrawFlag( itemDef_t *item ) -{ +qboolean ItemParse_ownerdrawFlag(itemDef_t *item) { int i; - if (PC_ParseInt(&i)) - { + if (PC_ParseInt(&i)) { return qfalse; } item->window.ownerDrawFlags |= i; @@ -4725,10 +4108,8 @@ qboolean ItemParse_ownerdrawFlag( itemDef_t *item ) ItemParse_enableCvar =============== */ -qboolean ItemParse_enableCvar( itemDef_t *item) -{ - if (PC_Script_Parse(&item->enableCvar)) - { +qboolean ItemParse_enableCvar(itemDef_t *item) { + if (PC_Script_Parse(&item->enableCvar)) { item->cvarFlags = CVAR_ENABLE; return qtrue; } @@ -4740,10 +4121,8 @@ qboolean ItemParse_enableCvar( itemDef_t *item) ItemParse_disableCvar =============== */ -qboolean ItemParse_disableCvar( itemDef_t *item ) -{ - if (PC_Script_Parse(&item->enableCvar)) - { +qboolean ItemParse_disableCvar(itemDef_t *item) { + if (PC_Script_Parse(&item->enableCvar)) { item->cvarFlags = CVAR_DISABLE; return qtrue; } @@ -4755,10 +4134,8 @@ qboolean ItemParse_disableCvar( itemDef_t *item ) ItemParse_showCvar =============== */ -qboolean ItemParse_showCvar( itemDef_t *item ) -{ - if (PC_Script_Parse(&item->enableCvar)) - { +qboolean ItemParse_showCvar(itemDef_t *item) { + if (PC_Script_Parse(&item->enableCvar)) { item->cvarFlags = CVAR_SHOW; return qtrue; } @@ -4770,10 +4147,8 @@ qboolean ItemParse_showCvar( itemDef_t *item ) ItemParse_hideCvar =============== */ -qboolean ItemParse_hideCvar( itemDef_t *item ) -{ - if (PC_Script_Parse(&item->enableCvar)) - { +qboolean ItemParse_hideCvar(itemDef_t *item) { + if (PC_Script_Parse(&item->enableCvar)) { item->cvarFlags = CVAR_HIDE; return qtrue; } @@ -4785,9 +4160,8 @@ qboolean ItemParse_hideCvar( itemDef_t *item ) ItemParse_cvarsubstring =============== */ -qboolean ItemParse_cvarsubstring( itemDef_t *item ) -{ - assert(item->cvarFlags); //need something set first, then we or in our flag. +qboolean ItemParse_cvarsubstring(itemDef_t *item) { + assert(item->cvarFlags); // need something set first, then we or in our flag. item->cvarFlags |= CVAR_SUBSTRING; return qtrue; } @@ -4797,56 +4171,39 @@ qboolean ItemParse_cvarsubstring( itemDef_t *item ) Item_ValidateTypeData =============== */ -void Item_ValidateTypeData(itemDef_t *item) -{ - if (item->typeData) - { +void Item_ValidateTypeData(itemDef_t *item) { + if (item->typeData) { return; } - if (item->type == ITEM_TYPE_LISTBOX) - { + if (item->type == ITEM_TYPE_LISTBOX) { item->typeData = UI_Alloc(sizeof(listBoxDef_t)); memset(item->typeData, 0, sizeof(listBoxDef_t)); - } - else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_BIND || item->type == ITEM_TYPE_SLIDER || item->type == ITEM_TYPE_TEXT) - { + } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_BIND || + item->type == ITEM_TYPE_SLIDER || item->type == ITEM_TYPE_TEXT) { item->typeData = UI_Alloc(sizeof(editFieldDef_t)); memset(item->typeData, 0, sizeof(editFieldDef_t)); - if (item->type == ITEM_TYPE_EDITFIELD) - { - if (!((editFieldDef_t *) item->typeData)->maxPaintChars) - { - ((editFieldDef_t *) item->typeData)->maxPaintChars = MAX_EDITFIELD; + if (item->type == ITEM_TYPE_EDITFIELD) { + if (!((editFieldDef_t *)item->typeData)->maxPaintChars) { + ((editFieldDef_t *)item->typeData)->maxPaintChars = MAX_EDITFIELD; } } - } - else if (item->type == ITEM_TYPE_MULTI) - { + } else if (item->type == ITEM_TYPE_MULTI) { item->typeData = UI_Alloc(sizeof(multiDef_t)); - } - else if (item->type == ITEM_TYPE_MODEL) - { + } else if (item->type == ITEM_TYPE_MODEL) { item->typeData = UI_Alloc(sizeof(modelDef_t)); memset(item->typeData, 0, sizeof(modelDef_t)); - } - else if (item->type == ITEM_TYPE_TEXTSCROLL ) - { + } else if (item->type == ITEM_TYPE_TEXTSCROLL) { item->typeData = UI_Alloc(sizeof(textScrollDef_t)); } } -qboolean ItemParse_isCharacter( itemDef_t *item ) -{ +qboolean ItemParse_isCharacter(itemDef_t *item) { int i; - if ( !PC_ParseInt(&i) ) - { - if ( i ) - { + if (!PC_ParseInt(&i)) { + if (i) { item->flags |= ITF_ISCHARACTER; - } - else - { + } else { item->flags &= ~ITF_ISCHARACTER; } return qtrue; @@ -4854,25 +4211,19 @@ qboolean ItemParse_isCharacter( itemDef_t *item ) return qfalse; } -qboolean ItemParse_isSaber( itemDef_t *item ) -{ -extern void UI_SaberLoadParms( void ); -extern qboolean ui_saber_parms_parsed; -extern void UI_CacheSaberGlowGraphics( void ); - int i; - if ( !PC_ParseInt(&i) ) - { - if ( i ) - { +qboolean ItemParse_isSaber(itemDef_t *item) { + extern void UI_SaberLoadParms(void); + extern qboolean ui_saber_parms_parsed; + extern void UI_CacheSaberGlowGraphics(void); + int i; + if (!PC_ParseInt(&i)) { + if (i) { item->flags |= ITF_ISSABER; UI_CacheSaberGlowGraphics(); - if ( !ui_saber_parms_parsed ) - { + if (!ui_saber_parms_parsed) { UI_SaberLoadParms(); } - } - else - { + } else { item->flags &= ~ITF_ISSABER; } return qtrue; @@ -4880,25 +4231,19 @@ extern void UI_CacheSaberGlowGraphics( void ); return qfalse; } -qboolean ItemParse_isSaber2( itemDef_t *item ) -{ -extern void UI_SaberLoadParms( void ); -extern qboolean ui_saber_parms_parsed; -extern void UI_CacheSaberGlowGraphics( void ); - int i; - if ( !PC_ParseInt(&i) ) - { - if ( i ) - { +qboolean ItemParse_isSaber2(itemDef_t *item) { + extern void UI_SaberLoadParms(void); + extern qboolean ui_saber_parms_parsed; + extern void UI_CacheSaberGlowGraphics(void); + int i; + if (!PC_ParseInt(&i)) { + if (i) { item->flags |= ITF_ISSABER2; UI_CacheSaberGlowGraphics(); - if ( !ui_saber_parms_parsed ) - { + if (!ui_saber_parms_parsed) { UI_SaberLoadParms(); } - } - else - { + } else { item->flags &= ~ITF_ISSABER2; } return qtrue; @@ -4906,102 +4251,329 @@ extern void UI_CacheSaberGlowGraphics( void ); return qfalse; } -keywordHash_t itemParseKeywords[] = { - {"accept", ItemParse_accept, }, - {"selectNext", ItemParse_selectionNext, }, - {"selectPrev", ItemParse_selectionPrev, }, - {"action", ItemParse_action, }, - {"addColorRange", ItemParse_addColorRange, }, - {"align", ItemParse_align, }, - {"appearance_slot", ItemParse_Appearance_slot, }, - {"asset_model", ItemParse_asset_model, }, - {"asset_shader", ItemParse_asset_shader, }, - {"isCharacter", ItemParse_isCharacter, }, - {"isSaber", ItemParse_isSaber, }, - {"isSaber2", ItemParse_isSaber2, }, - {"autowrapped", ItemParse_autowrapped, }, - {"backcolor", ItemParse_backcolor, }, - {"background", ItemParse_background, }, - {"border", ItemParse_border, }, - {"bordercolor", ItemParse_bordercolor, }, - {"bordersize", ItemParse_bordersize, }, - {"cinematic", ItemParse_cinematic, }, - {"columns", ItemParse_columns, }, - {"cvar", ItemParse_cvar, }, - {"cvarFloat", ItemParse_cvarFloat, }, - {"cvarFloatList", ItemParse_cvarFloatList, }, - {"cvarSubString", ItemParse_cvarsubstring }, - {"cvarStrList", ItemParse_cvarStrList, }, - {"cvarTest", ItemParse_cvarTest, }, - {"decoration", ItemParse_decoration, }, - {"desctext", ItemParse_descText }, - {"disableCvar", ItemParse_disableCvar, }, - {"doubleclick", ItemParse_doubleClick, }, - {"elementheight", ItemParse_elementheight, }, - {"elementtype", ItemParse_elementtype, }, - {"elementwidth", ItemParse_elementwidth, }, - {"enableCvar", ItemParse_enableCvar, }, - {"feeder", ItemParse_feeder, }, - {"flag", ItemParse_flag, }, - {"focusSound", ItemParse_focusSound, }, - {"font", ItemParse_font, }, - {"forecolor", ItemParse_forecolor, }, - {"group", ItemParse_group, }, - {"hideCvar", ItemParse_hideCvar, }, - {"horizontalscroll",ItemParse_horizontalscroll, }, - {"leaveFocus", ItemParse_leaveFocus, }, - {"maxChars", ItemParse_maxChars, }, - {"maxPaintChars", ItemParse_maxPaintChars, }, - {"model_angle", ItemParse_model_angle, }, - {"model_fovx", ItemParse_model_fovx, }, - {"model_fovy", ItemParse_model_fovy, }, - {"model_origin", ItemParse_model_origin, }, - {"model_rotation", ItemParse_model_rotation, }, - //rww - g2 begin - {"model_g2mins", ItemParse_model_g2mins, }, - {"model_g2maxs", ItemParse_model_g2maxs, }, - {"model_g2skin", ItemParse_model_g2skin, }, - {"model_g2anim", ItemParse_model_g2anim, }, - //rww - g2 end - {"mouseEnter", ItemParse_mouseEnter, }, - {"mouseEnterText", ItemParse_mouseEnterText, }, - {"mouseExit", ItemParse_mouseExit, }, - {"mouseExitText", ItemParse_mouseExitText, }, - {"name", ItemParse_name }, - {"notselectable", ItemParse_notselectable, }, -//JLF - {"scrollhidden", ItemParse_scrollhidden, }, -//JLF END - {"onFocus", ItemParse_onFocus, }, - {"outlinecolor", ItemParse_outlinecolor, }, - {"ownerdraw", ItemParse_ownerdraw, }, - {"ownerdrawFlag", ItemParse_ownerdrawFlag, }, - {"rect", ItemParse_rect, }, - {"showCvar", ItemParse_showCvar, }, - {"special", ItemParse_special, }, - {"style", ItemParse_style, }, - {"text", ItemParse_text }, - {"text2", ItemParse_text2 }, - {"text2alignx", ItemParse_text2alignx, }, - {"text2aligny", ItemParse_text2aligny, }, - {"textalign", ItemParse_textalign, }, - {"textalignx", ItemParse_textalignx, }, - {"textaligny", ItemParse_textaligny, }, - {"textscale", ItemParse_textscale, }, - {"textstyle", ItemParse_textstyle, }, - {"type", ItemParse_type, }, - {"visible", ItemParse_visible, }, - {"wrapped", ItemParse_wrapped, }, - {"invertyesno", ItemParse_invertyesno }, - {"xoffset", ItemParse_xoffset },//for yes/no and multi - - - - // Text scroll specific - {"lineHeight", ItemParse_lineHeight, NULL }, - - {NULL, NULL, } -}; +keywordHash_t itemParseKeywords[] = {{ + "accept", + ItemParse_accept, + }, + { + "selectNext", + ItemParse_selectionNext, + }, + { + "selectPrev", + ItemParse_selectionPrev, + }, + { + "action", + ItemParse_action, + }, + { + "addColorRange", + ItemParse_addColorRange, + }, + { + "align", + ItemParse_align, + }, + { + "appearance_slot", + ItemParse_Appearance_slot, + }, + { + "asset_model", + ItemParse_asset_model, + }, + { + "asset_shader", + ItemParse_asset_shader, + }, + { + "isCharacter", + ItemParse_isCharacter, + }, + { + "isSaber", + ItemParse_isSaber, + }, + { + "isSaber2", + ItemParse_isSaber2, + }, + { + "autowrapped", + ItemParse_autowrapped, + }, + { + "backcolor", + ItemParse_backcolor, + }, + { + "background", + ItemParse_background, + }, + { + "border", + ItemParse_border, + }, + { + "bordercolor", + ItemParse_bordercolor, + }, + { + "bordersize", + ItemParse_bordersize, + }, + { + "cinematic", + ItemParse_cinematic, + }, + { + "columns", + ItemParse_columns, + }, + { + "cvar", + ItemParse_cvar, + }, + { + "cvarFloat", + ItemParse_cvarFloat, + }, + { + "cvarFloatList", + ItemParse_cvarFloatList, + }, + {"cvarSubString", ItemParse_cvarsubstring}, + { + "cvarStrList", + ItemParse_cvarStrList, + }, + { + "cvarTest", + ItemParse_cvarTest, + }, + { + "decoration", + ItemParse_decoration, + }, + {"desctext", ItemParse_descText}, + { + "disableCvar", + ItemParse_disableCvar, + }, + { + "doubleclick", + ItemParse_doubleClick, + }, + { + "elementheight", + ItemParse_elementheight, + }, + { + "elementtype", + ItemParse_elementtype, + }, + { + "elementwidth", + ItemParse_elementwidth, + }, + { + "enableCvar", + ItemParse_enableCvar, + }, + { + "feeder", + ItemParse_feeder, + }, + { + "flag", + ItemParse_flag, + }, + { + "focusSound", + ItemParse_focusSound, + }, + { + "font", + ItemParse_font, + }, + { + "forecolor", + ItemParse_forecolor, + }, + { + "group", + ItemParse_group, + }, + { + "hideCvar", + ItemParse_hideCvar, + }, + { + "horizontalscroll", + ItemParse_horizontalscroll, + }, + { + "leaveFocus", + ItemParse_leaveFocus, + }, + { + "maxChars", + ItemParse_maxChars, + }, + { + "maxPaintChars", + ItemParse_maxPaintChars, + }, + { + "model_angle", + ItemParse_model_angle, + }, + { + "model_fovx", + ItemParse_model_fovx, + }, + { + "model_fovy", + ItemParse_model_fovy, + }, + { + "model_origin", + ItemParse_model_origin, + }, + { + "model_rotation", + ItemParse_model_rotation, + }, + // rww - g2 begin + { + "model_g2mins", + ItemParse_model_g2mins, + }, + { + "model_g2maxs", + ItemParse_model_g2maxs, + }, + { + "model_g2skin", + ItemParse_model_g2skin, + }, + { + "model_g2anim", + ItemParse_model_g2anim, + }, + // rww - g2 end + { + "mouseEnter", + ItemParse_mouseEnter, + }, + { + "mouseEnterText", + ItemParse_mouseEnterText, + }, + { + "mouseExit", + ItemParse_mouseExit, + }, + { + "mouseExitText", + ItemParse_mouseExitText, + }, + {"name", ItemParse_name}, + { + "notselectable", + ItemParse_notselectable, + }, + // JLF + { + "scrollhidden", + ItemParse_scrollhidden, + }, + // JLF END + { + "onFocus", + ItemParse_onFocus, + }, + { + "outlinecolor", + ItemParse_outlinecolor, + }, + { + "ownerdraw", + ItemParse_ownerdraw, + }, + { + "ownerdrawFlag", + ItemParse_ownerdrawFlag, + }, + { + "rect", + ItemParse_rect, + }, + { + "showCvar", + ItemParse_showCvar, + }, + { + "special", + ItemParse_special, + }, + { + "style", + ItemParse_style, + }, + {"text", ItemParse_text}, + {"text2", ItemParse_text2}, + { + "text2alignx", + ItemParse_text2alignx, + }, + { + "text2aligny", + ItemParse_text2aligny, + }, + { + "textalign", + ItemParse_textalign, + }, + { + "textalignx", + ItemParse_textalignx, + }, + { + "textaligny", + ItemParse_textaligny, + }, + { + "textscale", + ItemParse_textscale, + }, + { + "textstyle", + ItemParse_textstyle, + }, + { + "type", + ItemParse_type, + }, + { + "visible", + ItemParse_visible, + }, + { + "wrapped", + ItemParse_wrapped, + }, + {"invertyesno", ItemParse_invertyesno}, + {"xoffset", ItemParse_xoffset}, // for yes/no and multi + + // Text scroll specific + {"lineHeight", ItemParse_lineHeight, NULL}, + + { + NULL, + NULL, + }}; keywordHash_t *itemParseKeywordHash[KEYWORDHASH_SIZE]; @@ -5010,85 +4582,72 @@ keywordHash_t *itemParseKeywordHash[KEYWORDHASH_SIZE]; Item_SetupKeywordHash =============== */ -void Item_SetupKeywordHash(void) -{ +void Item_SetupKeywordHash(void) { int i; memset(itemParseKeywordHash, 0, sizeof(itemParseKeywordHash)); - for (i = 0; itemParseKeywords[i].keyword; i++) - { + for (i = 0; itemParseKeywords[i].keyword; i++) { KeywordHash_Add(itemParseKeywordHash, &itemParseKeywords[i]); } } - /* =============== Item_Parse =============== */ -qboolean Item_Parse(itemDef_t *item) -{ +qboolean Item_Parse(itemDef_t *item) { keywordHash_t *key; const char *token; - - if (PC_ParseString(&token)) - { + if (PC_ParseString(&token)) { return qfalse; } - if (*token != '{') - { + if (*token != '{') { return qfalse; } - while ( 1 ) - { - if (PC_ParseString(&token)) - { + while (1) { + if (PC_ParseString(&token)) { PC_ParseWarning("End of file inside menu item"); return qfalse; } - if (*token == '}') - { -/* if (!item->window.name) - { - item->window.name = defaultString; - Com_Printf(S_COLOR_YELLOW"WARNING: Menu item has no name\n"); - } + if (*token == '}') { + /* if (!item->window.name) + { + item->window.name = defaultString; + Com_Printf(S_COLOR_YELLOW"WARNING: Menu item has no name\n"); + } - if (!item->window.group) - { - item->window.group = defaultString; - Com_Printf(S_COLOR_YELLOW"WARNING: Menu item has no group\n"); - } -*/ + if (!item->window.group) + { + item->window.group = defaultString; + Com_Printf(S_COLOR_YELLOW"WARNING: Menu item has no group\n"); + } + */ return qtrue; } - key = (keywordHash_s *) KeywordHash_Find(itemParseKeywordHash, token); - if (!key) - { + key = (keywordHash_s *)KeywordHash_Find(itemParseKeywordHash, token); + if (!key) { PC_ParseWarning(va("Unknown item keyword '%s'", token)); continue; } - if ( !key->func(item) ) - { + if (!key->func(item)) { PC_ParseWarning(va("Couldn't parse item keyword '%s'", token)); return qfalse; } } } -static void Item_TextScroll_BuildLines ( itemDef_t* item ) -{ +static void Item_TextScroll_BuildLines(itemDef_t *item) { // new asian-aware line breaker... (pasted from elsewhere late @ night, hence aliasing-vars ;-) // - textScrollDef_t* scrollPtr = (textScrollDef_t*) item->typeData; - const char *psText = item->text; // for copy/paste ease + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; + const char *psText = item->text; // for copy/paste ease int iBoxWidth = item->window.rect.w - SCROLLBAR_SIZE - 10; // this could probably be simplified now, but it was converted from something else I didn't originally write, @@ -5097,19 +4656,18 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) const char *psCurrentTextReadPos; const char *psReadPosAtLineStart; const char *psBestLineBreakSrcPos; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) qboolean bIsTrailingPunctuation; unsigned int uiLetter; - if (!psText) - { + if (!psText) { return; } - if (*psText == '@') // string reference + if (*psText == '@') // string reference { -// trap_SP_GetStringTextString( &psText[1], text, sizeof(text)); - psText = SE_GetString( &psText[1] ); + // trap_SP_GetStringTextString( &psText[1], text, sizeof(text)); + psText = SE_GetString(&psText[1]); } psCurrentTextReadPos = psText; @@ -5117,18 +4675,16 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) psBestLineBreakSrcPos = psCurrentTextReadPos; scrollPtr->iLineCount = 0; - memset((char*)scrollPtr->pLines,0,sizeof(scrollPtr->pLines)); + memset((char *)scrollPtr->pLines, 0, sizeof(scrollPtr->pLines)); - while (*psCurrentTextReadPos && (scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES) ) - { - char sLineForDisplay[2048]; // ott + while (*psCurrentTextReadPos && (scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES)) { + char sLineForDisplay[2048]; // ott // construct a line... // psCurrentTextReadPos = psReadPosAtLineStart; sLineForDisplay[0] = '\0'; - while ( *psCurrentTextReadPos ) - { + while (*psCurrentTextReadPos) { int iAdvanceCount; psLastGood_s = psCurrentTextReadPos; @@ -5139,49 +4695,37 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) // concat onto string so far... // - if (uiLetter == 32 && sLineForDisplay[0] == '\0') - { + if (uiLetter == 32 && sLineForDisplay[0] == '\0') { psReadPosAtLineStart++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - sLineForDisplay[ strlen(sLineForDisplay)-1 ] = '\0'; // kill the CR + sLineForDisplay[strlen(sLineForDisplay) - 1] = '\0'; // kill the CR psReadPosAtLineStart = psCurrentTextReadPos; psBestLineBreakSrcPos = psCurrentTextReadPos; // hack it to fit in with this code... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc ( sLineForDisplay ); - break; // print this line - } - else - if ( DC->textWidth( sLineForDisplay, item->textscale, item->font ) >= iBoxWidth ) - { + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); + break; // print this line + } else if (DC->textWidth(sLineForDisplay, item->textscale, item->font) >= iBoxWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !ui.Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !ui.Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == psReadPosAtLineStart) - { + } else { + if (psBestLineBreakSrcPos == psReadPosAtLineStart) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -5189,34 +4733,32 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - sLineForDisplay[ psBestLineBreakSrcPos - psReadPosAtLineStart ] = '\0'; + sLineForDisplay[psBestLineBreakSrcPos - psReadPosAtLineStart] = '\0'; psReadPosAtLineStart = psCurrentTextReadPos = psBestLineBreakSrcPos; // hack it to fit in with this code... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc( sLineForDisplay ); - break; // print this line + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); + break; // print this line } } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !ui.Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !ui.Language_UsesSpaces())) { psBestLineBreakSrcPos = psCurrentTextReadPos; } } /// arrgghh, this is gettng horrible now... // - if (scrollPtr->pLines[ scrollPtr->iLineCount ] == NULL && strlen(sLineForDisplay)) - { + if (scrollPtr->pLines[scrollPtr->iLineCount] == NULL && strlen(sLineForDisplay)) { // then this is the last line and we've just run out of text, no CR, no overflow etc... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc( sLineForDisplay ); + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); } scrollPtr->iLineCount++; @@ -5229,18 +4771,14 @@ Item_InitControls init's special control types =============== */ -void Item_InitControls(itemDef_t *item) -{ - if (item == NULL) - { +void Item_InitControls(itemDef_t *item) { + if (item == NULL) { return; } - if (item->type == ITEM_TYPE_LISTBOX) - { - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; + if (item->type == ITEM_TYPE_LISTBOX) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; item->cursorPos = 0; - if (listPtr) - { + if (listPtr) { listPtr->cursorPos = 0; listPtr->startPos = 0; listPtr->endPos = 0; @@ -5254,18 +4792,14 @@ void Item_InitControls(itemDef_t *item) Int_Parse ================= */ -qboolean Int_Parse(const char **p, int *i) -{ - char *token; +qboolean Int_Parse(const char **p, int *i) { + char *token; token = COM_ParseExt(p, qfalse); - if (token && token[0] != 0) - { + if (token && token[0] != 0) { *i = atoi(token); return qtrue; - } - else - { + } else { return qfalse; } } @@ -5275,13 +4809,11 @@ qboolean Int_Parse(const char **p, int *i) String_Parse ================= */ -qboolean String_Parse(const char **p, const char **out) -{ +qboolean String_Parse(const char **p, const char **out) { char *token; token = COM_ParseExt(p, qfalse); - if (token && token[0] != 0) - { + if (token && token[0] != 0) { *out = String_Alloc(token); return (qboolean)(*out != NULL); } @@ -5293,39 +4825,31 @@ qboolean String_Parse(const char **p, const char **out) Item_RunScript =============== */ -void Item_RunScript(itemDef_t *item, const char *s) -{ +void Item_RunScript(itemDef_t *item, const char *s) { const char *p; int i; qboolean bRan; uiInfo.runScriptItem = item; - if (item && s && s[0]) - { + if (item && s && s[0]) { p = s; COM_BeginParseSession(); - while (1) - { + while (1) { const char *command; // expect command then arguments, ; ends command, NULL ends script - if (!String_Parse(&p, &command)) - { + if (!String_Parse(&p, &command)) { break; } - if (command[0] == ';' && command[1] == '\0') - { + if (command[0] == ';' && command[1] == '\0') { continue; } bRan = qfalse; - for (i = 0; i < scriptCommandCount; i++) - { - if (Q_stricmp(command, commandList[i].name) == 0) - { - if ( !(commandList[i].handler(item, &p)) ) - { + for (i = 0; i < scriptCommandCount; i++) { + if (Q_stricmp(command, commandList[i].name) == 0) { + if (!(commandList[i].handler(item, &p))) { COM_EndParseSession(); return; } @@ -5335,11 +4859,9 @@ void Item_RunScript(itemDef_t *item, const char *s) } } // not in our auto list, pass to handler - if (!bRan) - { + if (!bRan) { // Allow any script command to fail - if ( !DC->runScript(&p) ) - { + if (!DC->runScript(&p)) { break; } } @@ -5348,104 +4870,82 @@ void Item_RunScript(itemDef_t *item, const char *s) } } - /* =============== Menu_SetupKeywordHash =============== */ -void Menu_SetupKeywordHash(void) -{ +void Menu_SetupKeywordHash(void) { int i; memset(menuParseKeywordHash, 0, sizeof(menuParseKeywordHash)); - for (i = 0; menuParseKeywords[i].keyword; i++) - { + for (i = 0; menuParseKeywords[i].keyword; i++) { KeywordHash_Add(menuParseKeywordHash, &menuParseKeywords[i]); } } - /* =============== Menus_ActivateByName =============== */ void Menu_HandleMouseMove(menuDef_t *menu, float x, float y); -menuDef_t *Menus_ActivateByName(const char *p) -{ +menuDef_t *Menus_ActivateByName(const char *p) { int i; menuDef_t *m = NULL; menuDef_t *focus = Menu_GetFocused(); - for (i = 0; i < menuCount; i++) - { + for (i = 0; i < menuCount; i++) { // Look for the name in the current list of windows - if (Q_stricmp(Menus[i].window.name, p) == 0) - { + if (Q_stricmp(Menus[i].window.name, p) == 0) { m = &Menus[i]; Menus_Activate(m); - if (openMenuCount < MAX_OPEN_MENUS && focus != NULL) - { + if (openMenuCount < MAX_OPEN_MENUS && focus != NULL) { menuStack[openMenuCount++] = focus; } - } - else - { + } else { Menus[i].window.flags &= ~WINDOW_HASFOCUS; } } - if (!m) - { // A hack so we don't have to load all three mission menus before we know what tier we're on - if (!Q_stricmp( p, "ingameMissionSelect1" ) ) - { - UI_LoadMenus("ui/tier1.txt",qfalse); + if (!m) { // A hack so we don't have to load all three mission menus before we know what tier we're on + if (!Q_stricmp(p, "ingameMissionSelect1")) { + UI_LoadMenus("ui/tier1.txt", qfalse); Menus_CloseAll(); Menus_OpenByName("ingameMissionSelect1"); - } - else if (!Q_stricmp( p, "ingameMissionSelect2" ) ) - { - UI_LoadMenus("ui/tier2.txt",qfalse); + } else if (!Q_stricmp(p, "ingameMissionSelect2")) { + UI_LoadMenus("ui/tier2.txt", qfalse); Menus_CloseAll(); Menus_OpenByName("ingameMissionSelect2"); - } - else if (!Q_stricmp( p, "ingameMissionSelect3" ) ) - { - UI_LoadMenus("ui/tier3.txt",qfalse); + } else if (!Q_stricmp(p, "ingameMissionSelect3")) { + UI_LoadMenus("ui/tier3.txt", qfalse); Menus_CloseAll(); Menus_OpenByName("ingameMissionSelect3"); - } - else - { - Com_Printf(S_COLOR_YELLOW"WARNING: Menus_ActivateByName: Unable to find menu \"%s\"\n",p); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: Menus_ActivateByName: Unable to find menu \"%s\"\n", p); } } // First time, show force select instructions - if (!Q_stricmp( p, "ingameForceSelect" ) ) - { - int tier_storyinfo = Cvar_VariableIntegerValue( "tier_storyinfo" ); + if (!Q_stricmp(p, "ingameForceSelect")) { + int tier_storyinfo = Cvar_VariableIntegerValue("tier_storyinfo"); - if (tier_storyinfo==1) - { + if (tier_storyinfo == 1) { Menus_OpenByName("ingameForceHelp"); } } // First time, show weapons select instructions - if (!Q_stricmp( p, "ingameWpnSelect" ) ) - { - int tier_storyinfo = Cvar_VariableIntegerValue( "tier_storyinfo" ); + if (!Q_stricmp(p, "ingameWpnSelect")) { + int tier_storyinfo = Cvar_VariableIntegerValue("tier_storyinfo"); - if (tier_storyinfo==1) - { + if (tier_storyinfo == 1) { Menus_OpenByName("ingameWpnSelectHelp"); } } // Want to handle a mouse move on the new menu in case your already over an item - Menu_HandleMouseMove ( m, DC->cursorx, DC->cursory ); + Menu_HandleMouseMove(m, DC->cursorx, DC->cursory); return m; } @@ -5455,18 +4955,16 @@ menuDef_t *Menus_ActivateByName(const char *p) Menus_Activate =============== */ -void Menus_Activate(menuDef_t *menu) -{ +void Menus_Activate(menuDef_t *menu) { menu->window.flags |= (WINDOW_HASFOCUS | WINDOW_VISIBLE); - if (menu->onOpen) - { + if (menu->onOpen) { itemDef_t item; item.parent = menu; - item.window.flags = 0; //err, item is fake here, but we want a valid flag before calling runscript + item.window.flags = 0; // err, item is fake here, but we want a valid flag before calling runscript Item_RunScript(&item, menu->onOpen); - if (item.window.flags & WINDOW_SCRIPTWAITING) //in case runscript set waiting, copy it up to the menu + if (item.window.flags & WINDOW_SCRIPTWAITING) // in case runscript set waiting, copy it up to the menu { menu->window.flags |= WINDOW_SCRIPTWAITING; menu->window.delayedScript = item.window.delayedScript; @@ -5474,97 +4972,94 @@ void Menus_Activate(menuDef_t *menu) } } -// menu->appearanceTime = DC->realTime + 1000; + // menu->appearanceTime = DC->realTime + 1000; menu->appearanceTime = 0; menu->appearanceCnt = 0; - } -static const char *g_bindCommands[] = { - "+altattack", - "+attack", - "+back", +static const char *g_bindCommands[] = {"+altattack", + "+attack", + "+back", #ifndef JK2_MODE - "+force_drain", + "+force_drain", #endif - "+force_grip", - "+force_lightning", - "+forward", - "+left", - "+lookdown", - "+lookup", - "+mlook", - "+movedown", - "+moveleft", - "+moveright", - "+moveup", - "+right", - "+speed", - "+strafe", - "+use", - "+useforce", - "centerview", - "cg_thirdperson !", - "datapad", - "exitview", + "+force_grip", + "+force_lightning", + "+forward", + "+left", + "+lookdown", + "+lookup", + "+mlook", + "+movedown", + "+moveleft", + "+moveright", + "+moveup", + "+right", + "+speed", + "+strafe", + "+use", + "+useforce", + "centerview", + "cg_thirdperson !", + "datapad", + "exitview", #ifndef JK2_MODE - "force_absorb", + "force_absorb", #endif - "force_distract", - "force_heal", + "force_distract", + "force_heal", #ifndef JK2_MODE - "force_protect", + "force_protect", #endif - "force_pull", + "force_pull", #ifndef JK2_MODE - "force_rage", - "force_sight", + "force_rage", + "force_sight", #endif - "force_speed", - "force_throw", - "forcenext", - "forceprev", - "invnext", - "invprev", - "invuse", - "load auto", + "force_speed", + "force_throw", + "forcenext", + "forceprev", + "invnext", + "invprev", + "invuse", + "load auto", #ifdef JK2_MODE - "load quik", + "load quik", #else - "load quick", + "load quick", #endif - "saberAttackCycle", + "saberAttackCycle", #ifdef JK2_MODE - "save quik*", + "save quik*", #else - "save quick", + "save quick", #endif - "taunt", - "uimenu ingameloadmenu", - "uimenu ingamesavemenu", - "use_bacta", - "use_electrobinoculars", - "use_lightamp_goggles", - "use_seeker", - "use_sentry", - "weapnext", - "weapon 0", - "weapon 1", - "weapon 10", - "weapon 11", - "weapon 12", - "weapon 13", - "weapon 2", - "weapon 3", - "weapon 4", - "weapon 5", - "weapon 6", - "weapon 7", - "weapon 8", - "weapon 9", - "weapprev", - "zoom" -}; + "taunt", + "uimenu ingameloadmenu", + "uimenu ingamesavemenu", + "use_bacta", + "use_electrobinoculars", + "use_lightamp_goggles", + "use_seeker", + "use_sentry", + "weapnext", + "weapon 0", + "weapon 1", + "weapon 10", + "weapon 11", + "weapon 12", + "weapon 13", + "weapon 2", + "weapon 3", + "weapon 4", + "weapon 5", + "weapon 6", + "weapon 7", + "weapon 8", + "weapon 9", + "weapprev", + "zoom"}; #define g_bindCount ARRAY_LEN(g_bindCommands) @@ -5575,21 +5070,20 @@ static int g_bindKeys[g_bindCount][2]; Controls_GetKeyAssignment ================= */ -static void Controls_GetKeyAssignment( const char *command, int *twokeys ) -{ - int count; - int j; - char b[256]; +static void Controls_GetKeyAssignment(const char *command, int *twokeys) { + int count; + int j; + char b[256]; twokeys[0] = twokeys[1] = -1; count = 0; - for ( j=0; jgetBindingBuf( j, b, sizeof( b ) ); - if ( *b && !Q_stricmp( b, command ) ) { + for (j = 0; j < MAX_KEYS; j++) { + DC->getBindingBuf(j, b, sizeof(b)); + if (*b && !Q_stricmp(b, command)) { twokeys[count] = j; count++; - if ( count == 2 ) + if (count == 2) break; } } @@ -5600,31 +5094,26 @@ static void Controls_GetKeyAssignment( const char *command, int *twokeys ) Controls_GetConfig ================= */ -void Controls_GetConfig( void ) -{ - size_t i; +void Controls_GetConfig(void) { + size_t i; // iterate each command, get its numeric binding - for ( i = 0; i < g_bindCount; i++ ) - Controls_GetKeyAssignment( g_bindCommands[i], g_bindKeys[i] ); + for (i = 0; i < g_bindCount; i++) + Controls_GetKeyAssignment(g_bindCommands[i], g_bindKeys[i]); } - /* =============== Item_SetScreenCoords =============== */ -void Item_SetScreenCoords(itemDef_t *item, float x, float y) -{ +void Item_SetScreenCoords(itemDef_t *item, float x, float y) { - if (item == NULL) - { + if (item == NULL) { return; } - if (item->window.border != 0) - { + if (item->window.border != 0) { x += item->window.borderSize; y += item->window.borderSize; } @@ -5638,38 +5127,30 @@ void Item_SetScreenCoords(itemDef_t *item, float x, float y) item->textRect.w = 0; item->textRect.h = 0; - switch ( item->type) - { - case ITEM_TYPE_TEXTSCROLL: - { - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; - if ( scrollPtr ) - { - scrollPtr->startPos = 0; - scrollPtr->endPos = 0; - } + switch (item->type) { + case ITEM_TYPE_TEXTSCROLL: { + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; + if (scrollPtr) { + scrollPtr->startPos = 0; + scrollPtr->endPos = 0; + } - Item_TextScroll_BuildLines ( item ); + Item_TextScroll_BuildLines(item); - break; - } + break; + } } } - -static void Menu_FreeGhoulItems(menuDef_t *menu) -{ - int i,j; - for (i = 0; i < menu->itemCount; i++) - { - for (j=0; j < menu->items[i]->ghoul2.size(); j++) - { - if ( menu->items[i]->ghoul2[j].mModelindex >= 0) - { - DC->g2_RemoveGhoul2Model( menu->items[i]->ghoul2, j ); +static void Menu_FreeGhoulItems(menuDef_t *menu) { + int i, j; + for (i = 0; i < menu->itemCount; i++) { + for (j = 0; j < menu->items[i]->ghoul2.size(); j++) { + if (menu->items[i]->ghoul2[j].mModelindex >= 0) { + DC->g2_RemoveGhoul2Model(menu->items[i]->ghoul2, j); } } - (menu->items[i]->ghoul2).clear(); //clear is the public Free so i can actually remove this slot + (menu->items[i]->ghoul2).clear(); // clear is the public Free so i can actually remove this slot } } /* @@ -5677,14 +5158,12 @@ static void Menu_FreeGhoulItems(menuDef_t *menu) Menu_Reset =============== */ -void Menu_Reset(void) -{ - //FIXME iterate menus to destoy G2 assets. +void Menu_Reset(void) { + // FIXME iterate menus to destoy G2 assets. int i; - for (i = 0; i < menuCount; i++) - { - Menu_FreeGhoulItems( &Menus[i] ); + for (i = 0; i < menuCount; i++) { + Menu_FreeGhoulItems(&Menus[i]); } menuCount = 0; @@ -5695,28 +5174,24 @@ void Menu_Reset(void) Menu_UpdatePosition =============== */ -void Menu_UpdatePosition(menuDef_t *menu) -{ - int i; - float x, y; +void Menu_UpdatePosition(menuDef_t *menu) { + int i; + float x, y; - if (menu == NULL) - { - return; - } + if (menu == NULL) { + return; + } - x = menu->window.rect.x; - y = menu->window.rect.y; - if (menu->window.border != 0) - { - x += menu->window.borderSize; - y += menu->window.borderSize; - } + x = menu->window.rect.x; + y = menu->window.rect.y; + if (menu->window.border != 0) { + x += menu->window.borderSize; + y += menu->window.borderSize; + } - for (i = 0; i < menu->itemCount; i++) - { - Item_SetScreenCoords(menu->items[i], x, y); - } + for (i = 0; i < menu->itemCount; i++) { + Item_SetScreenCoords(menu->items[i], x, y); + } } /* @@ -5724,15 +5199,12 @@ void Menu_UpdatePosition(menuDef_t *menu) Menu_PostParse =============== */ -void Menu_PostParse(menuDef_t *menu) -{ - if (menu == NULL) - { +void Menu_PostParse(menuDef_t *menu) { + if (menu == NULL) { return; } - if (menu->fullScreen) - { + if (menu->fullScreen) { menu->window.rect.x = 0; menu->window.rect.y = 0; menu->window.rect.w = 640; @@ -5746,15 +5218,13 @@ void Menu_PostParse(menuDef_t *menu) Menu_Init =============== */ -void Menu_Init(menuDef_t *menu) -{ +void Menu_Init(menuDef_t *menu) { memset(menu, 0, sizeof(menuDef_t)); menu->cursorItem = -1; UI_Cursor_Show(qtrue); - if (DC) - { + if (DC) { menu->fadeAmount = DC->Assets.fadeAmount; menu->fadeClamp = DC->Assets.fadeClamp; menu->fadeCycle = DC->Assets.fadeCycle; @@ -5768,44 +5238,37 @@ void Menu_Init(menuDef_t *menu) Menu_Parse =============== */ -qboolean Menu_Parse(char *inbuffer, menuDef_t *menu) -{ -// pc_token_t token; +qboolean Menu_Parse(char *inbuffer, menuDef_t *menu) { + // pc_token_t token; keywordHash_t *key; - char *token2; - char * buffer; - bool nest= false; + char *token2; + char *buffer; + bool nest = false; buffer = inbuffer; token2 = PC_ParseExt(); - if (!token2) - { + if (!token2) { return qfalse; } - if (*token2 != '{') - { + if (*token2 != '{') { PC_ParseWarning("Misplaced {"); return qfalse; } - while ( 1 ) - { + while (1) { token2 = PC_ParseExt(); - if (!token2) - { + if (!token2) { PC_ParseWarning("End of file inside menu."); return qfalse; } - if (*token2 == '}') - { + if (*token2 == '}') { return qtrue; } - if (nest && (*token2 == 0)) - { + if (nest && (*token2 == 0)) { PC_EndParseSession(buffer); nest = false; @@ -5813,15 +5276,13 @@ qboolean Menu_Parse(char *inbuffer, menuDef_t *menu) } key = KeywordHash_Find(menuParseKeywordHash, token2); - if (!key) - { - PC_ParseWarning(va("Unknown menu keyword %s",token2)); + if (!key) { + PC_ParseWarning(va("Unknown menu keyword %s", token2)); continue; } - if ( !key->func((itemDef_t*)menu) ) - { - PC_ParseWarning(va("Couldn't parse menu keyword %s as %s",token2, key->keyword)); + if (!key->func((itemDef_t *)menu)) { + PC_ParseWarning(va("Couldn't parse menu keyword %s as %s", token2, key->keyword)); return qfalse; } } @@ -5832,15 +5293,12 @@ qboolean Menu_Parse(char *inbuffer, menuDef_t *menu) Menu_New =============== */ -void Menu_New(char *buffer) -{ +void Menu_New(char *buffer) { menuDef_t *menu = &Menus[menuCount]; - if (menuCount < MAX_MENUS) - { + if (menuCount < MAX_MENUS) { Menu_Init(menu); - if (Menu_Parse(buffer, menu)) - { + if (Menu_Parse(buffer, menu)) { Menu_PostParse(menu); menuCount++; } @@ -5852,13 +5310,11 @@ void Menu_New(char *buffer) Menus_CloseAll =============== */ -void Menus_CloseAll(void) -{ +void Menus_CloseAll(void) { int i; - for (i = 0; i < menuCount; i++) - { - Menu_RunCloseScript ( &Menus[i] ); + for (i = 0; i < menuCount; i++) { + Menu_RunCloseScript(&Menus[i]); Menus[i].window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); } @@ -5872,19 +5328,17 @@ PC_StartParseSession =============== */ -int PC_StartParseSession(const char *fileName,char **buffer) -{ - int len; +int PC_StartParseSession(const char *fileName, char **buffer) { + int len; // Try to open file and read it in. - len = ui.FS_ReadFile( fileName,(void **) buffer ); + len = ui.FS_ReadFile(fileName, (void **)buffer); // Not there? - if ( len>0 ) - { + if (len > 0) { COM_BeginParseSession(); - Q_strncpyz(parseData[parseDataCount].fileName, fileName, sizeof (parseData[0].fileName)); + Q_strncpyz(parseData[parseDataCount].fileName, fileName, sizeof(parseData[0].fileName)); parseData[parseDataCount].bufferStart = *buffer; parseData[parseDataCount].bufferCurrent = *buffer; } @@ -5897,10 +5351,9 @@ int PC_StartParseSession(const char *fileName,char **buffer) PC_EndParseSession =============== */ -void PC_EndParseSession(char *buffer) -{ +void PC_EndParseSession(char *buffer) { COM_EndParseSession(); - ui.FS_FreeFile( buffer ); //let go of the buffer + ui.FS_FreeFile(buffer); // let go of the buffer } /* @@ -5908,92 +5361,77 @@ void PC_EndParseSession(char *buffer) PC_ParseWarning =============== */ -void PC_ParseWarning(const char *message) -{ - ui.Printf(S_COLOR_YELLOW "WARNING: %s Line #%d of File '%s'\n", message,parseData[parseDataCount].com_lines,parseData[parseDataCount].fileName); +void PC_ParseWarning(const char *message) { + ui.Printf(S_COLOR_YELLOW "WARNING: %s Line #%d of File '%s'\n", message, parseData[parseDataCount].com_lines, parseData[parseDataCount].fileName); } -char *PC_ParseExt(void) -{ - if(parseDataCount < 0) +char *PC_ParseExt(void) { + if (parseDataCount < 0) Com_Error(ERR_FATAL, "PC_ParseExt: parseDataCount < 0 (be sure to call PC_StartParseSession!)"); return (COM_ParseExt(&parseData[parseDataCount].bufferCurrent, qtrue)); } -qboolean PC_ParseString(const char **string) -{ - int hold; +qboolean PC_ParseString(const char **string) { + int hold; - if(parseDataCount < 0) + if (parseDataCount < 0) Com_Error(ERR_FATAL, "PC_ParseString: parseDataCount < 0 (be sure to call PC_StartParseSession!)"); - hold = COM_ParseString(&parseData[parseDataCount].bufferCurrent,string); + hold = COM_ParseString(&parseData[parseDataCount].bufferCurrent, string); - while (hold==0 && **string == 0) - { - hold = COM_ParseString(&parseData[parseDataCount].bufferCurrent,string); + while (hold == 0 && **string == 0) { + hold = COM_ParseString(&parseData[parseDataCount].bufferCurrent, string); } return (qboolean)(hold != 0); } -qboolean PC_ParseInt(int *number) -{ - if(parseDataCount < 0) +qboolean PC_ParseInt(int *number) { + if (parseDataCount < 0) Com_Error(ERR_FATAL, "PC_ParseInt: parseDataCount < 0 (be sure to call PC_StartParseSession!)"); - return(COM_ParseInt(&parseData[parseDataCount].bufferCurrent,number)); + return (COM_ParseInt(&parseData[parseDataCount].bufferCurrent, number)); } -qboolean PC_ParseFloat(float *number) -{ - if(parseDataCount < 0) +qboolean PC_ParseFloat(float *number) { + if (parseDataCount < 0) Com_Error(ERR_FATAL, "PC_ParseFloat: parseDataCount < 0 (be sure to call PC_StartParseSession!)"); - return(COM_ParseFloat(&parseData[parseDataCount].bufferCurrent,number)); + return (COM_ParseFloat(&parseData[parseDataCount].bufferCurrent, number)); } -qboolean PC_ParseColor(vec4_t *color) -{ - if(parseDataCount < 0) +qboolean PC_ParseColor(vec4_t *color) { + if (parseDataCount < 0) Com_Error(ERR_FATAL, "PC_ParseColor: parseDataCount < 0 (be sure to call PC_StartParseSession!)"); - return(COM_ParseVec4(&parseData[parseDataCount].bufferCurrent, color)); + return (COM_ParseVec4(&parseData[parseDataCount].bufferCurrent, color)); } - /* ================= Menu_Count ================= */ -int Menu_Count(void) -{ - return menuCount; -} +int Menu_Count(void) { return menuCount; } /* ================= Menu_PaintAll ================= */ -void Menu_PaintAll(void) -{ +void Menu_PaintAll(void) { int i; - if (captureFunc) - { + if (captureFunc) { captureFunc(captureData); } - for (i = 0; i < menuCount; i++) - { + for (i = 0; i < menuCount; i++) { Menu_Paint(&Menus[i], qfalse); } - if (uis.debugMode) - { + if (uis.debugMode) { vec4_t v = {1, 1, 1, 1}; - DC->drawText(5, 25, .75, v, va("(%d,%d)",DC->cursorx,DC->cursory), 0, 0, DC->Assets.qhMediumFont); + DC->drawText(5, 25, .75, v, va("(%d,%d)", DC->cursorx, DC->cursory), 0, 0, DC->Assets.qhMediumFont); DC->drawText(5, 10, .75, v, va("fps: %f", DC->FPS), 0, 0, DC->Assets.qhMediumFont); } } @@ -6003,28 +5441,23 @@ void Menu_PaintAll(void) Menu_Paint ================= */ -void Menu_Paint(menuDef_t *menu, qboolean forcePaint) -{ +void Menu_Paint(menuDef_t *menu, qboolean forcePaint) { int i; - if (menu == NULL) - { + if (menu == NULL) { return; } - if (menu->window.flags & WINDOW_SCRIPTWAITING) - { - if (DC->realTime > menu->window.delayTime) - { // Time has elapsed, resume running whatever script we saved + if (menu->window.flags & WINDOW_SCRIPTWAITING) { + if (DC->realTime > menu->window.delayTime) { // Time has elapsed, resume running whatever script we saved itemDef_t item; item.parent = menu; - item.window.flags = 0; //clear before calling RunScript + item.window.flags = 0; // clear before calling RunScript menu->window.flags &= ~WINDOW_SCRIPTWAITING; Item_RunScript(&item, menu->window.delayedScript); // Could have hit another delay. Need to hoist from fake item - if (item.window.flags & WINDOW_SCRIPTWAITING) - { + if (item.window.flags & WINDOW_SCRIPTWAITING) { menu->window.flags |= WINDOW_SCRIPTWAITING; menu->window.delayedScript = item.window.delayedScript; menu->window.delayTime = item.window.delayTime; @@ -6032,78 +5465,66 @@ void Menu_Paint(menuDef_t *menu, qboolean forcePaint) } } - if (!(menu->window.flags & WINDOW_VISIBLE) && !forcePaint) - { + if (!(menu->window.flags & WINDOW_VISIBLE) && !forcePaint) { return; } -// if (menu->window.ownerDrawFlags && DC->ownerDrawVisible && !DC->ownerDrawVisible(menu->window.ownerDrawFlags)) -// { -// return; -// } + // if (menu->window.ownerDrawFlags && DC->ownerDrawVisible && !DC->ownerDrawVisible(menu->window.ownerDrawFlags)) + // { + // return; + // } - if (forcePaint) - { + if (forcePaint) { menu->window.flags |= WINDOW_FORCED; } // draw the background if necessary - if (menu->fullScreen) - { + if (menu->fullScreen) { - vec4_t color; + vec4_t color; color[0] = menu->window.backColor[0]; color[1] = menu->window.backColor[1]; color[2] = menu->window.backColor[2]; color[3] = menu->window.backColor[3]; - ui.R_SetColor( color); + ui.R_SetColor(color); - if (menu->window.background==0) // No background shader given? Make it blank + if (menu->window.background == 0) // No background shader given? Make it blank { menu->window.background = uis.whiteShader; } - DC->drawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, menu->window.background ); - } - else if (menu->window.background) - { + DC->drawHandlePic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, menu->window.background); + } else if (menu->window.background) { // this allows a background shader without being full screen - //UI_DrawHandlePic(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, menu->backgroundShader); + // UI_DrawHandlePic(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, menu->backgroundShader); } // paint the background and or border - Window_Paint(&menu->window, menu->fadeAmount, menu->fadeClamp, menu->fadeCycle ); + Window_Paint(&menu->window, menu->fadeAmount, menu->fadeClamp, menu->fadeCycle); // Loop through all items for the menu and paint them int iSlotsVisible = 0; - for (i = 0; i < menu->itemCount; i++) - { - if (!menu->items[i]->appearanceSlot) - { + for (i = 0; i < menu->itemCount; i++) { + if (!menu->items[i]->appearanceSlot) { Item_Paint(menu->items[i], qtrue); - } - else // Timed order of appearance + } else // Timed order of appearance { - if (Item_Paint(menu->items[i], qfalse) ) - { - iSlotsVisible++; //It would paint + if (Item_Paint(menu->items[i], qfalse)) { + iSlotsVisible++; // It would paint } - if (menu->items[i]->appearanceSlot<=menu->appearanceCnt) - { + if (menu->items[i]->appearanceSlot <= menu->appearanceCnt) { Item_Paint(menu->items[i], qtrue); } } } - if (iSlotsVisible && menu->appearanceTime < DC->realTime && menu->appearanceCnt < menu->itemCount) // Time to show another item + if (iSlotsVisible && menu->appearanceTime < DC->realTime && menu->appearanceCnt < menu->itemCount) // Time to show another item { menu->appearanceTime = DC->realTime + menu->appearanceIncrement; menu->appearanceCnt++; } - - if (uis.debugMode) - { + if (uis.debugMode) { vec4_t color; color[0] = color[2] = color[3] = 1; color[1] = 0; @@ -6116,20 +5537,16 @@ void Menu_Paint(menuDef_t *menu, qboolean forcePaint) Item_EnableShowViaCvar ================= */ -qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) -{ - if (item && item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) - { +qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) { + if (item && item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) { char script[1024]; const char *p; char buff[1024]; - if (item->cvarFlags & CVAR_SUBSTRING) - { + if (item->cvarFlags & CVAR_SUBSTRING) { const char *val; p = item->enableCvar; COM_BeginParseSession(); - if (!String_Parse(&p, &val)) - {//strip the quotes off + if (!String_Parse(&p, &val)) { // strip the quotes off COM_EndParseSession(); return (item->cvarFlags & flag) ? qfalse : qtrue; } @@ -6138,43 +5555,33 @@ qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) Q_strncpyz(buff, val, sizeof(buff)); DC->getCVarString(item->cvarTest, script, sizeof(script)); p = script; - } - else - { + } else { DC->getCVarString(item->cvarTest, buff, sizeof(buff)); Q_strncpyz(script, item->enableCvar, sizeof(script)); p = script; } COM_BeginParseSession(); - while (1) - { + while (1) { const char *val; // expect value then ; or NULL, NULL ends list - if (!String_Parse(&p, &val)) - { + if (!String_Parse(&p, &val)) { COM_EndParseSession(); return (item->cvarFlags & flag) ? qfalse : qtrue; } - if (val[0] == ';' && val[1] == '\0') - { + if (val[0] == ';' && val[1] == '\0') { continue; } // enable it if any of the values are true - if (item->cvarFlags & flag) - { - if (Q_stricmp(buff, val) == 0) - { + if (item->cvarFlags & flag) { + if (Q_stricmp(buff, val) == 0) { COM_EndParseSession(); return qtrue; } - } - else - { + } else { // disable it if any of the values are true - if (Q_stricmp(buff, val) == 0) - { + if (Q_stricmp(buff, val) == 0) { COM_EndParseSession(); return qfalse; } @@ -6186,10 +5593,8 @@ qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) return qtrue; } -bool HasStringLanguageChanged ( const itemDef_t *item ) -{ - if ( !item->text || item->text[0] == '\0' ) - { +bool HasStringLanguageChanged(const itemDef_t *item) { + if (!item->text || item->text[0] == '\0') { return false; } @@ -6208,12 +5613,10 @@ bool HasStringLanguageChanged ( const itemDef_t *item ) Item_SetTextExtents ================= */ -void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *text) -{ +void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *text) { const char *textPtr = (text) ? text : item->text; - if (textPtr == NULL ) - { + if (textPtr == NULL) { return; } @@ -6221,20 +5624,14 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t *height = item->textRect.h; // keeps us from computing the widths and heights more than once - if (*width == 0 || - (item->type == ITEM_TYPE_OWNERDRAW && item->textalignment == ITEM_ALIGN_CENTER) || - HasStringLanguageChanged (item)) - { + if (*width == 0 || (item->type == ITEM_TYPE_OWNERDRAW && item->textalignment == ITEM_ALIGN_CENTER) || HasStringLanguageChanged(item)) { int originalWidth; originalWidth = DC->textWidth(textPtr, item->textscale, item->font); - if (item->type == ITEM_TYPE_OWNERDRAW && (item->textalignment == ITEM_ALIGN_CENTER || item->textalignment == ITEM_ALIGN_RIGHT)) - { + if (item->type == ITEM_TYPE_OWNERDRAW && (item->textalignment == ITEM_ALIGN_CENTER || item->textalignment == ITEM_ALIGN_RIGHT)) { originalWidth += DC->ownerDrawWidth(item->window.ownerDraw, item->textscale); - } - else if (item->type == ITEM_TYPE_EDITFIELD && item->textalignment == ITEM_ALIGN_CENTER && item->cvar) - { + } else if (item->type == ITEM_TYPE_EDITFIELD && item->textalignment == ITEM_ALIGN_CENTER && item->cvar) { char buff[256]; DC->getCVarString(item->cvar, buff, 256); originalWidth += DC->textWidth(buff, item->textscale, item->font); @@ -6247,22 +5644,19 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t item->textRect.h = *height; item->textRect.x = item->textalignx; item->textRect.y = item->textaligny; - if (item->textalignment == ITEM_ALIGN_RIGHT) - { + if (item->textalignment == ITEM_ALIGN_RIGHT) { item->textRect.x = item->textalignx - originalWidth; - } - else if (item->textalignment == ITEM_ALIGN_CENTER) - { + } else if (item->textalignment == ITEM_ALIGN_CENTER) { item->textRect.x = item->textalignx - originalWidth / 2; } ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window); #ifdef JK2_MODE - if(item->text && item->text[0]=='@') + if (item->text && item->text[0] == '@') item->asset = sp_language->modificationCount; #else - if (item->text && item->text[0]=='@' )//string package - item->asset = se_language->modificationCount; //mark language + if (item->text && item->text[0] == '@') // string package + item->asset = se_language->modificationCount; // mark language #endif } } @@ -6272,51 +5666,45 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t Item_TextColor ================= */ -void Item_TextColor(itemDef_t *item, vec4_t *newColor) -{ +void Item_TextColor(itemDef_t *item, vec4_t *newColor) { vec4_t lowLight; - const vec4_t greyColor = { .5, .5, .5, 1}; - menuDef_t *parent = (menuDef_t*)item->parent; + const vec4_t greyColor = {.5, .5, .5, 1}; + menuDef_t *parent = (menuDef_t *)item->parent; Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount); - if ( !(item->type == ITEM_TYPE_TEXT && item->window.flags & WINDOW_AUTOWRAPPED) && item->window.flags & WINDOW_HASFOCUS) - { + if (!(item->type == ITEM_TYPE_TEXT && item->window.flags & WINDOW_AUTOWRAPPED) && item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,*newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } -/* else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) - { - lowLight[0] = 0.8 * item->window.foreColor[0]; - lowLight[1] = 0.8 * item->window.foreColor[1]; - lowLight[2] = 0.8 * item->window.foreColor[2]; - lowLight[3] = 0.8 * item->window.foreColor[3]; - LerpColor(item->window.foreColor,lowLight,*newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR)); + LerpColor(parent->focusColor, lowLight, *newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } -*/ else - { + /* else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) + { + lowLight[0] = 0.8 * item->window.foreColor[0]; + lowLight[1] = 0.8 * item->window.foreColor[1]; + lowLight[2] = 0.8 * item->window.foreColor[2]; + lowLight[3] = 0.8 * item->window.foreColor[3]; + LerpColor(item->window.foreColor,lowLight,*newColor,0.5+0.5*sin(DC->realTime / PULSE_DIVISOR)); + } + */ + else { memcpy(newColor, &item->window.foreColor, sizeof(vec4_t)); } - if (item->disabled) - { + if (item->disabled) { memcpy(newColor, &parent->disableColor, sizeof(vec4_t)); } // items can be enabled and disabled based on cvars - if (item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) - { - if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) - { + if (item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) { + if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) { memcpy(newColor, &parent->disableColor, sizeof(vec4_t)); } } - if (item->window.flags & WINDOW_INACTIVE) - { + if (item->window.flags & WINDOW_INACTIVE) { memcpy(newColor, &greyColor, sizeof(vec4_t)); } } @@ -6326,8 +5714,7 @@ void Item_TextColor(itemDef_t *item, vec4_t *newColor) Item_Text_Wrapped_Paint ================= */ -void Item_Text_Wrapped_Paint(itemDef_t *item) -{ +void Item_Text_Wrapped_Paint(itemDef_t *item) { char text[1024]; const char *p, *start, *textPtr; char buff[1024]; @@ -6338,29 +5725,22 @@ void Item_Text_Wrapped_Paint(itemDef_t *item) // now paint the text and/or any optional images // default to left - if (item->text == NULL) - { - if (item->cvar == NULL) - { + if (item->text == NULL) { + if (item->cvar == NULL) { return; - } - else - { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else - { + } else { textPtr = item->text; } - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - textPtr = SE_GetString( &textPtr[1] ); + textPtr = SE_GetString(&textPtr[1]); } - if (*textPtr == '\0') - { + if (*textPtr == '\0') { return; } @@ -6371,92 +5751,80 @@ void Item_Text_Wrapped_Paint(itemDef_t *item) y = item->textRect.y; start = textPtr; p = strchr(textPtr, '\r'); - while (p && *p) - { - strncpy(buff, start, p-start+1); - buff[p-start] = '\0'; + while (p && *p) { + strncpy(buff, start, p - start + 1); + buff[p - start] = '\0'; DC->drawText(x, y, item->textscale, color, buff, 0, item->textStyle, item->font); y += height + 5; start += p - start + 1; - p = strchr(p+1, '\r'); + p = strchr(p + 1, '\r'); } DC->drawText(x, y, item->textscale, color, start, 0, item->textStyle, item->font); } - /* ================= Menu_Paint ================= */ -void Item_Text_Paint(itemDef_t *item) -{ +void Item_Text_Paint(itemDef_t *item) { char text[1024]; const char *textPtr; int height, width; vec4_t color; - if (item->window.flags & WINDOW_WRAPPED) - { + if (item->window.flags & WINDOW_WRAPPED) { Item_Text_Wrapped_Paint(item); return; } - if (item->window.flags & WINDOW_AUTOWRAPPED) - { + if (item->window.flags & WINDOW_AUTOWRAPPED) { Item_Text_AutoWrapped_Paint(item); return; } - if (item->text == NULL) - { - if (item->cvar == NULL) - { + if (item->text == NULL) { + if (item->cvar == NULL) { return; - } - else - { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else - { + } else { textPtr = item->text; } #ifdef JK2_MODE - if (*textPtr == '@') - { + if (*textPtr == '@') { textPtr = JK2SP_GetStringTextString(&textPtr[1]); } #else - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - textPtr = SE_GetString( &textPtr[1] ); + textPtr = SE_GetString(&textPtr[1]); } #endif // this needs to go here as it sets extents for cvar types as well Item_SetTextExtents(item, &width, &height, textPtr); - if (*textPtr == '\0') - { + if (*textPtr == '\0') { return; } Item_TextColor(item, &color); DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, textPtr, 0, item->textStyle, item->font); - if (item->text2) // Is there a second line of text? + if (item->text2) // Is there a second line of text? { textPtr = item->text2; - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - textPtr = SE_GetString( &textPtr[1] ); + textPtr = SE_GetString(&textPtr[1]); } Item_TextColor(item, &color); - DC->drawText(item->textRect.x + item->text2alignx, item->textRect.y + item->text2aligny, item->textscale, color, textPtr, 0, item->textStyle, item->font); + DC->drawText(item->textRect.x + item->text2alignx, item->textRect.y + item->text2aligny, item->textscale, color, textPtr, 0, item->textStyle, + item->font); } } @@ -6466,29 +5834,25 @@ Item_UpdatePosition ================= */ // FIXME: consolidate this with nearby stuff -void Item_UpdatePosition(itemDef_t *item) -{ +void Item_UpdatePosition(itemDef_t *item) { float x, y; menuDef_t *menu; - if (item == NULL || item->parent == NULL) - { + if (item == NULL || item->parent == NULL) { return; } - menu = (menuDef_t *) item->parent; + menu = (menuDef_t *)item->parent; x = menu->window.rect.x; y = menu->window.rect.y; - if (menu->window.border != 0) - { + if (menu->window.border != 0) { x += menu->window.borderSize; y += menu->window.borderSize; } Item_SetScreenCoords(item, x, y); - } /* @@ -6496,71 +5860,62 @@ void Item_UpdatePosition(itemDef_t *item) Item_TextField_Paint ================= */ -void Item_TextField_Paint(itemDef_t *item) -{ +void Item_TextField_Paint(itemDef_t *item) { char buff[1024]; vec4_t newColor, lowLight; int offset; - menuDef_t *parent = (menuDef_t*)item->parent; - editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData; + menuDef_t *parent = (menuDef_t *)item->parent; + editFieldDef_t *editPtr = (editFieldDef_t *)item->typeData; Item_Text_Paint(item); buff[0] = '\0'; - if (item->cvar) - { + if (item->cvar) { DC->getCVarString(item->cvar, buff, sizeof(buff)); } - if (item->window.flags & WINDOW_HASFOCUS) - { + if (item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } - else - { + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else { memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t)); } - offset = 8;//(item->text && *item->text) ? 8 : 0; - if (item->window.flags & WINDOW_HASFOCUS && g_editingField) - { + offset = 8; //(item->text && *item->text) ? 8 : 0; + if (item->window.flags & WINDOW_HASFOCUS && g_editingField) { char cursor = DC->getOverstrikeMode() ? '_' : '|'; - DC->drawTextWithCursor(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, item->cursorPos - editPtr->paintOffset , cursor, /*editPtr->maxPaintChars*/ item->window.rect.w, item->textStyle, item->font); - } - else - { - DC->drawText(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, /*editPtr->maxPaintChars*/ item->window.rect.w, item->textStyle, item->font); + DC->drawTextWithCursor(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, + item->cursorPos - editPtr->paintOffset, cursor, /*editPtr->maxPaintChars*/ item->window.rect.w, item->textStyle, item->font); + } else { + DC->drawText(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, + /*editPtr->maxPaintChars*/ item->window.rect.w, item->textStyle, item->font); } } -void Item_TextScroll_Paint(itemDef_t *item) -{ +void Item_TextScroll_Paint(itemDef_t *item) { char cvartext[1024]; float x, y, size, count, thumb; - int i; - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; + int i; + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; size = item->window.rect.h - 2; // Re-arranged this function. Previous version had a plethora of bugs. // Still a little iffy - BTO (VV) - if (item->cvar) - { + if (item->cvar) { DC->getCVarString(item->cvar, cvartext, sizeof(cvartext)); item->text = cvartext; } - Item_TextScroll_BuildLines ( item ); + Item_TextScroll_BuildLines(item); count = scrollPtr->iLineCount; // Draw scroll bar if text goes beyond bottom - if (( scrollPtr->iLineCount * scrollPtr->lineHeight ) > size) - { + if ((scrollPtr->iLineCount * scrollPtr->lineHeight) > size) { // draw scrollbar to right side of the window x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE - 1; y = item->window.rect.y + 1; @@ -6569,14 +5924,13 @@ void Item_TextScroll_Paint(itemDef_t *item) scrollPtr->endPos = scrollPtr->startPos; size = item->window.rect.h - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size+1, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size + 1, DC->Assets.scrollBar); y += size - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowDown); // thumb thumb = Item_TextScroll_ThumbDrawPosition(item); - if (thumb > y - SCROLLBAR_SIZE - 1) - { + if (thumb > y - SCROLLBAR_SIZE - 1) { thumb = y - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(x, thumb, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); @@ -6584,25 +5938,21 @@ void Item_TextScroll_Paint(itemDef_t *item) // adjust size for item painting size = item->window.rect.h - 2; - x = item->window.rect.x + item->textalignx + 1; - y = item->window.rect.y + item->textaligny + 1; - + x = item->window.rect.x + item->textalignx + 1; + y = item->window.rect.y + item->textaligny + 1; - for (i = scrollPtr->startPos; i < count; i++) - { + for (i = scrollPtr->startPos; i < count; i++) { const char *text; text = scrollPtr->pLines[i]; - if (!text) - { + if (!text) { continue; } DC->drawText(x + 4, y, item->textscale, item->window.foreColor, text, 0, item->textStyle, item->font); size -= scrollPtr->lineHeight; - if (size < scrollPtr->lineHeight) - { + if (size < scrollPtr->lineHeight) { scrollPtr->drawPadding = scrollPtr->lineHeight - size; break; } @@ -6618,13 +5968,12 @@ Item_ListBox_Paint ================= */ -void Item_ListBox_Paint(itemDef_t *item) -{ +void Item_ListBox_Paint(itemDef_t *item) { float x, y, size; int count, i, thumb; qhandle_t image; qhandle_t optionalImage; - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; // the listbox is horizontal or vertical and has a fixed size scroll bar going either direction // elements are enumerated from the DC and either text or image handles are acquired from the DC as well @@ -6632,102 +5981,83 @@ void Item_ListBox_Paint(itemDef_t *item) // there is no clipping available so only the last completely visible item is painted count = DC->feederCount(item->special); - if (listPtr->startPos > (count?count-1:count)) - {//probably changed feeders, so reset + if (listPtr->startPos > (count ? count - 1 : count)) { // probably changed feeders, so reset listPtr->startPos = 0; } - if (item->cursorPos > (count?count-1:count)) - {//probably changed feeders, so reset + if (item->cursorPos > (count ? count - 1 : count)) { // probably changed feeders, so reset item->cursorPos = 0; } // default is vertical if horizontal flag is not here - if (item->window.flags & WINDOW_HORIZONTAL) - { -//JLF new variable (code just indented) - if (!listPtr->scrollhidden) - { + if (item->window.flags & WINDOW_HORIZONTAL) { + // JLF new variable (code just indented) + if (!listPtr->scrollhidden) { // draw scrollbar in bottom of the window // bar - if (Item_ListBox_MaxScroll(item) > 0) - { + if (Item_ListBox_MaxScroll(item) > 0) { x = item->window.rect.x + 1; y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowLeft); x += SCROLLBAR_SIZE - 1; size = item->window.rect.w - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, size+1, SCROLLBAR_SIZE, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, size + 1, SCROLLBAR_SIZE, DC->Assets.scrollBar); x += size - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowRight); // thumb - thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item); - if (thumb > x - SCROLLBAR_SIZE - 1) - { + thumb = Item_ListBox_ThumbDrawPosition(item); // Item_ListBox_ThumbPosition(item); + if (thumb > x - SCROLLBAR_SIZE - 1) { thumb = x - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(thumb, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); - } - else if (listPtr->startPos > 0) - { + } else if (listPtr->startPos > 0) { listPtr->startPos = 0; } } -//JLF end + // JLF end // listPtr->endPos = listPtr->startPos; size = item->window.rect.w - 2; // items // size contains max available space - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { // fit = 0; x = item->window.rect.x + 1; y = item->window.rect.y + 1; - for (i = listPtr->startPos; i < count; i++) - { + for (i = listPtr->startPos; i < count; i++) { // always draw at least one // which may overdraw the box if it is too small for the element image = DC->feederItemImage(item->special, i); - if (image) - { - if (item->window.flags & WINDOW_PLAYERCOLOR) - { - vec4_t color; - color[0] = ui_char_color_red.integer/255.0f; - color[1] = ui_char_color_green.integer/255.0f; - color[2] = ui_char_color_blue.integer/255.0f; + if (image) { + if (item->window.flags & WINDOW_PLAYERCOLOR) { + vec4_t color; + color[0] = ui_char_color_red.integer / 255.0f; + color[1] = ui_char_color_green.integer / 255.0f; + color[2] = ui_char_color_blue.integer / 255.0f; color[3] = 1; ui.R_SetColor(color); } - DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); + DC->drawHandlePic(x + 1, y + 1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); } - if (i == item->cursorPos) - { - DC->drawRect(x, y, listPtr->elementWidth-1, listPtr->elementHeight-1, item->window.borderSize, item->window.borderColor); + if (i == item->cursorPos) { + DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor); } size -= listPtr->elementWidth; - if (size < listPtr->elementWidth) - { - listPtr->drawPadding = size; //listPtr->elementWidth - size; + if (size < listPtr->elementWidth) { + listPtr->drawPadding = size; // listPtr->elementWidth - size; break; } x += listPtr->elementWidth; listPtr->endPos++; // fit++; } - } - else - { + } else { // } - } - else - { -//JLF new variable (code idented with if) - if (!listPtr->scrollhidden) - { + } else { + // JLF new variable (code idented with if) + if (!listPtr->scrollhidden) { // draw scrollbar to right side of the window x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE - 1; y = item->window.rect.y + 1; @@ -6736,126 +6066,102 @@ void Item_ListBox_Paint(itemDef_t *item) listPtr->endPos = listPtr->startPos; size = item->window.rect.h - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size+1, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size + 1, DC->Assets.scrollBar); y += size - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowDown); // thumb - thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item); - if (thumb > y - SCROLLBAR_SIZE - 1) - { + thumb = Item_ListBox_ThumbDrawPosition(item); // Item_ListBox_ThumbPosition(item); + if (thumb > y - SCROLLBAR_SIZE - 1) { thumb = y - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(x, thumb, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); } -//JLF end - // adjust size for item painting + // JLF end + // adjust size for item painting size = item->window.rect.h - 2; - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { // fit = 0; x = item->window.rect.x + 1; y = item->window.rect.y + 1; - for (i = listPtr->startPos; i < count; i++) - { + for (i = listPtr->startPos; i < count; i++) { // always draw at least one // which may overdraw the box if it is too small for the element image = DC->feederItemImage(item->special, i); - if (image) - { - DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); + if (image) { + DC->drawHandlePic(x + 1, y + 1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); } - if (i == item->cursorPos) - { + if (i == item->cursorPos) { DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor); } listPtr->endPos++; size -= listPtr->elementHeight; - if (size < listPtr->elementHeight) - { + if (size < listPtr->elementHeight) { listPtr->drawPadding = listPtr->elementHeight - size; break; } y += listPtr->elementHeight; // fit++; } - } - else - { + } else { x = item->window.rect.x + 1; y = item->window.rect.y + 1 - listPtr->elementHeight; i = listPtr->startPos; - for (; i < count; i++) - { + for (; i < count; i++) { const char *text; // always draw at least one // which may overdraw the box if it is too small for the element - if (listPtr->numColumns > 0) - { + if (listPtr->numColumns > 0) { int j; - for (j = 0; j < listPtr->numColumns; j++) - { + for (j = 0; j < listPtr->numColumns; j++) { text = DC->feederItemText(item->special, i, j, &optionalImage); - if (text[0]=='@') - { - text = SE_GetString( &text[1] ); + if (text[0] == '@') { + text = SE_GetString(&text[1]); } - if (optionalImage >= 0) - { - DC->drawHandlePic(x + 4 + listPtr->columnInfo[j].pos, y - 1 + listPtr->elementHeight / 2, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); - } - else if (text) - { - vec4_t *color; - menuDef_t *parent = (menuDef_t*)item->parent; + if (optionalImage >= 0) { + DC->drawHandlePic(x + 4 + listPtr->columnInfo[j].pos, y - 1 + listPtr->elementHeight / 2, listPtr->columnInfo[j].width, + listPtr->columnInfo[j].width, optionalImage); + } else if (text) { + vec4_t *color; + menuDef_t *parent = (menuDef_t *)item->parent; // Use focus color is it has focus. - if (i == item->cursorPos) - { + if (i == item->cursorPos) { color = &parent->focusColor; - } - else - { + } else { color = &item->window.foreColor; } - int textyOffset; textyOffset = 0; - DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight+ textyOffset, item->textscale, *color, text, listPtr->columnInfo[j].maxChars, item->textStyle, item->font); + DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight + textyOffset, item->textscale, *color, text, + listPtr->columnInfo[j].maxChars, item->textStyle, item->font); } } - } - else - { + } else { text = DC->feederItemText(item->special, i, 0, &optionalImage); - if (optionalImage >= 0) - { - //DC->drawHandlePic(x + 4 + listPtr->elementHeight, y, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); - } - else if (text) - { + if (optionalImage >= 0) { + // DC->drawHandlePic(x + 4 + listPtr->elementHeight, y, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); + } else if (text) { DC->drawText(x + 4, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, item->textStyle, item->font); } - } // The chosen text - if (i == item->cursorPos) - { - DC->fillRect(x + 2, y + listPtr->elementHeight + 2, item->window.rect.w - SCROLLBAR_SIZE - 4, listPtr->elementHeight+2, item->window.outlineColor); + if (i == item->cursorPos) { + DC->fillRect(x + 2, y + listPtr->elementHeight + 2, item->window.rect.w - SCROLLBAR_SIZE - 4, listPtr->elementHeight + 2, + item->window.outlineColor); } size -= listPtr->elementHeight; - if (size < listPtr->elementHeight) - { + if (size < listPtr->elementHeight) { listPtr->drawPadding = listPtr->elementHeight - size; break; } @@ -6872,12 +6178,12 @@ void Item_ListBox_Paint(itemDef_t *item) BindingIDFromName ================= */ -int BindingIDFromName( const char *name ) { +int BindingIDFromName(const char *name) { size_t i; // iterate each command, set its default binding - for ( i = 0; i < g_bindCount; i++ ) { - if ( !Q_stricmp( name, g_bindCommands[i] ) ) + for (i = 0; i < g_bindCount; i++) { + if (!Q_stricmp(name, g_bindCommands[i])) return i; } return -1; @@ -6890,43 +6196,42 @@ char g_nameBind[96]; BindingFromName ================= */ -void BindingFromName( const char *cvar ) { - size_t i; - int b1, b2; - char sOR[32]; +void BindingFromName(const char *cvar) { + size_t i; + int b1, b2; + char sOR[32]; // iterate each command, set its default binding - for ( i=0; i < g_bindCount; i++ ) { - if ( !Q_stricmp(cvar, g_bindCommands[i] ) ) { + for (i = 0; i < g_bindCount; i++) { + if (!Q_stricmp(cvar, g_bindCommands[i])) { b2 = g_bindKeys[i][1]; b1 = g_bindKeys[i][0]; - if ( b1 == -1 ) + if (b1 == -1) break; - if ( b2 != -1 ) { + if (b2 != -1) { char keyname[2][32]; - DC->keynumToStringBuf( b1, keyname[0], sizeof( keyname[0] ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(keyname[0]); - DC->keynumToStringBuf( b2, keyname[1], sizeof( keyname[1] ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(keyname[1]); + DC->keynumToStringBuf(b1, keyname[0], sizeof(keyname[0])); + // do NOT do this or it corrupts asian text!!! Q_strupr(keyname[0]); + DC->keynumToStringBuf(b2, keyname[1], sizeof(keyname[1])); + // do NOT do this or it corrupts asian text!!! Q_strupr(keyname[1]); #ifdef JK2_MODE - Q_strncpyz( sOR, ui.SP_GetStringTextString( "MENUS3_KEYBIND_OR" ), sizeof(sOR) ); + Q_strncpyz(sOR, ui.SP_GetStringTextString("MENUS3_KEYBIND_OR"), sizeof(sOR)); #else - Q_strncpyz( sOR, SE_GetString( "MENUS_KEYBIND_OR" ), sizeof(sOR) ); + Q_strncpyz(sOR, SE_GetString("MENUS_KEYBIND_OR"), sizeof(sOR)); #endif - Com_sprintf( g_nameBind, sizeof( g_nameBind ), "%s %s %s", keyname[0], sOR, keyname[1] ); - } - else { - DC->keynumToStringBuf( b1, g_nameBind, sizeof( g_nameBind ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(g_nameBind); + Com_sprintf(g_nameBind, sizeof(g_nameBind), "%s %s %s", keyname[0], sOR, keyname[1]); + } else { + DC->keynumToStringBuf(b1, g_nameBind, sizeof(g_nameBind)); + // do NOT do this or it corrupts asian text!!! Q_strupr(g_nameBind); } return; } } - Q_strncpyz( g_nameBind, "???", sizeof( g_nameBind ) ); + Q_strncpyz(g_nameBind, "???", sizeof(g_nameBind)); } /* @@ -6934,96 +6239,81 @@ void BindingFromName( const char *cvar ) { Item_Bind_Paint ================= */ -void Item_Bind_Paint(itemDef_t *item) -{ - vec4_t newColor, lowLight; - float value,textScale,textWidth; - int maxChars = 0, textHeight,yAdj,startingXPos; +void Item_Bind_Paint(itemDef_t *item) { + vec4_t newColor, lowLight; + float value, textScale, textWidth; + int maxChars = 0, textHeight, yAdj, startingXPos; - menuDef_t *parent = (menuDef_t*)item->parent; - editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData; + menuDef_t *parent = (menuDef_t *)item->parent; + editFieldDef_t *editPtr = (editFieldDef_t *)item->typeData; - if (editPtr) - { + if (editPtr) { maxChars = editPtr->maxPaintChars; } value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0; - if (item->window.flags & WINDOW_HASFOCUS) - { - if (g_bindItem == item) - { + if (item->window.flags & WINDOW_HASFOCUS) { + if (g_bindItem == item) { lowLight[0] = 0.8f * 1.0f; lowLight[1] = 0.8f * 0.0f; lowLight[2] = 0.8f * 0.0f; lowLight[3] = 0.8f * 1.0f; - } - else - { + } else { lowLight[0] = 0.8f * parent->focusColor[0]; lowLight[1] = 0.8f * parent->focusColor[1]; lowLight[2] = 0.8f * parent->focusColor[2]; lowLight[3] = 0.8f * parent->focusColor[3]; } - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } - else - { - Item_TextColor( item,&newColor); + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else { + Item_TextColor(item, &newColor); } - if (item->text) - { + if (item->text) { Item_Text_Paint(item); BindingFromName(item->cvar); // If the text runs past the limit bring the scale down until it fits. textScale = item->textscale; - textWidth = DC->textWidth(g_nameBind,(float) textScale, uiInfo.uiDC.Assets.qhMediumFont); + textWidth = DC->textWidth(g_nameBind, (float)textScale, uiInfo.uiDC.Assets.qhMediumFont); startingXPos = (item->textRect.x + item->textRect.w + 8); - while ((startingXPos + textWidth) >= SCREEN_WIDTH) - { + while ((startingXPos + textWidth) >= SCREEN_WIDTH) { textScale -= .05f; - textWidth = DC->textWidth(g_nameBind,(float) textScale, uiInfo.uiDC.Assets.qhMediumFont); + textWidth = DC->textWidth(g_nameBind, (float)textScale, uiInfo.uiDC.Assets.qhMediumFont); } // Try to adjust it's y placement if the scale has changed. yAdj = 0; - if (textScale != item->textscale) - { + if (textScale != item->textscale) { textHeight = DC->textHeight(g_nameBind, item->textscale, uiInfo.uiDC.Assets.qhMediumFont); yAdj = textHeight - DC->textHeight(g_nameBind, textScale, uiInfo.uiDC.Assets.qhMediumFont); } - DC->drawText(startingXPos, item->textRect.y + yAdj, textScale, newColor, g_nameBind, maxChars/*item->textRect.w*/, item->textStyle, item->font); - } - else - { - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "FIXME 1" : "FIXME 0", maxChars/*item->textRect.w*/, item->textStyle, item->font); + DC->drawText(startingXPos, item->textRect.y + yAdj, textScale, newColor, g_nameBind, maxChars /*item->textRect.w*/, item->textStyle, item->font); + } else { + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "FIXME 1" : "FIXME 0", maxChars /*item->textRect.w*/, + item->textStyle, item->font); } } -void UI_ScaleModelAxis(refEntity_t *ent) +void UI_ScaleModelAxis(refEntity_t *ent) -{ // scale the model should we need to - if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) - { - VectorScale( ent->axis[0], ent->modelScale[0] , ent->axis[0] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) - { - VectorScale( ent->axis[1], ent->modelScale[1] , ent->axis[1] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) - { - VectorScale( ent->axis[2], ent->modelScale[2] , ent->axis[2] ); - ent->nonNormalizedAxes = qtrue; - } +{ // scale the model should we need to + if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) { + VectorScale(ent->axis[0], ent->modelScale[0], ent->axis[0]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) { + VectorScale(ent->axis[1], ent->modelScale[1], ent->axis[1]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) { + VectorScale(ent->axis[2], ent->modelScale[2], ent->axis[2]); + ent->nonNormalizedAxes = qtrue; + } } /* @@ -7032,89 +6322,83 @@ Item_Model_Paint ================= */ -extern int s_entityWavVol[MAX_GENTITIES]; //from snd_dma.cpp -void UI_TalkingHead(itemDef_t *item) -{ -// static int facial_blink = DC->realTime + Q_flrand(4000.0, 8000.0); +extern int s_entityWavVol[MAX_GENTITIES]; // from snd_dma.cpp +void UI_TalkingHead(itemDef_t *item) { + // static int facial_blink = DC->realTime + Q_flrand(4000.0, 8000.0); static int facial_timer = DC->realTime + Q_flrand(10000.0, 30000.0); -// static animNumber_t facial_anim = FACE_ALERT; + // static animNumber_t facial_anim = FACE_ALERT; int anim = -1; - //are we blinking? -/* if (facial_blink < 0) - { // yes, check if we are we done blinking ? - if (-(facial_blink) < DC->realTime) - { // yes, so reset blink timer - facial_blink = DC->realTime + Q_flrand(4000.0, 8000.0); - CG_G2SetHeadBlink( cent, qfalse ); //stop the blink + // are we blinking? + /* if (facial_blink < 0) + { // yes, check if we are we done blinking ? + if (-(facial_blink) < DC->realTime) + { // yes, so reset blink timer + facial_blink = DC->realTime + Q_flrand(4000.0, 8000.0); + CG_G2SetHeadBlink( cent, qfalse ); //stop the blink + } } - } - else // no we aren't blinking - { - if (facial_blink < DC->realTime)// but should we start ? + else // no we aren't blinking { - CG_G2SetHeadBlink( cent, qtrue ); - if (facial_blink == 1) - {//requested to stay shut by SET_FACEEYESCLOSED - facial_blink = -(DC->realTime + 99999999.0f);// set blink timer - } - else + if (facial_blink < DC->realTime)// but should we start ? { - facial_blink = -(DC->realTime + 300.0f);// set blink timer + CG_G2SetHeadBlink( cent, qtrue ); + if (facial_blink == 1) + {//requested to stay shut by SET_FACEEYESCLOSED + facial_blink = -(DC->realTime + 99999999.0f);// set blink timer + } + else + { + facial_blink = -(DC->realTime + 300.0f);// set blink timer + } } } - } -*/ + */ - if (s_entityWavVol[0] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused + if (s_entityWavVol[0] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused { - anim = FACE_TALK1 + s_entityWavVol[0]-1; - if( anim > FACE_TALK4 ) - { + anim = FACE_TALK1 + s_entityWavVol[0] - 1; + if (anim > FACE_TALK4) { anim = FACE_TALK4; } // reset timers so we don't start right away after talking facial_timer = DC->realTime + Q_flrand(2000.0, 7000.0); - } - else if (s_entityWavVol[0] == -1) - {// talking, but silent + } else if (s_entityWavVol[0] == -1) { // talking, but silent anim = FACE_TALK0; // reset timers so we don't start right away after talking facial_timer = DC->realTime + Q_flrand(2000.0, 7000.0); } -/* else if (s_entityWavVol[0] == 0) //don't anim if in a slient part of speech - {//not talking - if (facial_timer < 0) // are animating ? - { //yes - if (-(facial_timer) < DC->realTime)// are we done animating ? - { // yes, reset timer - facial_timer = DC->realTime + Q_flrand(10000.0, 30000.0); - } - else - { // not yet, so choose anim - anim = facial_anim; + /* else if (s_entityWavVol[0] == 0) //don't anim if in a slient part of speech + {//not talking + if (facial_timer < 0) // are animating ? + { //yes + if (-(facial_timer) < DC->realTime)// are we done animating ? + { // yes, reset timer + facial_timer = DC->realTime + Q_flrand(10000.0, 30000.0); + } + else + { // not yet, so choose anim + anim = facial_anim; + } } - } - else // no we aren't animating - { // but should we start ? - if (facial_timer < DC->realTime) - {//yes - facial_anim = FACE_ALERT + Q_irand(0,2); //alert, smile, frown - // set aux timer - facial_timer = -(DC->realTime + 2000.0); - anim = facial_anim; + else // no we aren't animating + { // but should we start ? + if (facial_timer < DC->realTime) + {//yes + facial_anim = FACE_ALERT + Q_irand(0,2); //alert, smile, frown + // set aux timer + facial_timer = -(DC->realTime + 2000.0); + anim = facial_anim; + } } - } - }//talking -*/ - if (facial_timer < DC->realTime) - {//restart the base anim -// modelDef_t *modelPtr = (modelDef_t*)item->typeData; - //ItemParse_model_g2anim_go( item, "BOTH_STAND5IDLE1" ); -// facial_timer = DC->realTime + Q_flrand(2000.0, 7000.0) + DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); + }//talking + */ + if (facial_timer < DC->realTime) { // restart the base anim + // modelDef_t *modelPtr = (modelDef_t*)item->typeData; + // ItemParse_model_g2anim_go( item, "BOTH_STAND5IDLE1" ); + // facial_timer = DC->realTime + Q_flrand(2000.0, 7000.0) + DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); } - if (anim != -1) - { + if (anim != -1) { DC->g2hilev_SetAnim(&item->ghoul2[0], "face", anim, qfalse); } } @@ -7124,65 +6408,60 @@ void UI_TalkingHead(itemDef_t *item) Item_Model_Paint ================= */ -extern void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, float curYaw ); +extern void UI_SaberDrawBlades(itemDef_t *item, vec3_t origin, float curYaw); -void Item_Model_Paint(itemDef_t *item) -{ +void Item_Model_Paint(itemDef_t *item) { float x, y, w, h; refdef_t refdef; - refEntity_t ent; - vec3_t mins, maxs, origin; - vec3_t angles; - const modelDef_t *modelPtr = (modelDef_t*)item->typeData; + refEntity_t ent; + vec3_t mins, maxs, origin; + vec3_t angles; + const modelDef_t *modelPtr = (modelDef_t *)item->typeData; - if (modelPtr == NULL) - { + if (modelPtr == NULL) { return; } // Fuck all the logic --eez #ifdef JK2_MODE // setup the refdef - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); - x = item->window.rect.x+1; - y = item->window.rect.y+1; - w = item->window.rect.w-2; - h = item->window.rect.h-2; + AxisClear(refdef.viewaxis); + x = item->window.rect.x + 1; + y = item->window.rect.y + 1; + w = item->window.rect.w - 2; + h = item->window.rect.h - 2; refdef.x = x * DC->xscale; refdef.y = y * DC->yscale; refdef.width = w * DC->xscale; refdef.height = h * DC->yscale; - DC->modelBounds( item->asset, mins, maxs ); + DC->modelBounds(item->asset, mins, maxs); - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); // calculate distance so the model nearly fills the box - if (qtrue) - { - float len = 0.5 * ( maxs[2] - mins[2] ); - origin[0] = len / 0.268; // len / tan( fov/2 ) - //origin[0] = len / tan(w/2); - } - else - { + if (qtrue) { + float len = 0.5 * (maxs[2] - mins[2]); + origin[0] = len / 0.268; // len / tan( fov/2 ) + // origin[0] = len / tan(w/2); + } else { origin[0] = item->textscale; } // WTF..? --eez - //refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : w; - //refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : h; + // refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : w; + // refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : h; refdef.fov_x = 45; refdef.fov_y = 45; - //refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f); - //xx = refdef.width / tan( refdef.fov_x / 360 * M_PI ); - //refdef.fov_y = atan2( refdef.height, xx ); - //refdef.fov_y *= ( 360 / M_PI ); + // refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f); + // xx = refdef.width / tan( refdef.fov_x / 360 * M_PI ); + // refdef.fov_y = atan2( refdef.height, xx ); + // refdef.fov_y *= ( 360 / M_PI ); DC->clearScene(); @@ -7190,94 +6469,90 @@ void Item_Model_Paint(itemDef_t *item) // add the model - memset( &ent, 0, sizeof(ent) ); + memset(&ent, 0, sizeof(ent)); - //adjust = 5.0 * sin( (float)uis.realtime / 500 ); - //adjust = 360 % (int)((float)uis.realtime / 1000); - //VectorSet( angles, 0, 0, 1 ); + // adjust = 5.0 * sin( (float)uis.realtime / 500 ); + // adjust = 360 % (int)((float)uis.realtime / 1000); + // VectorSet( angles, 0, 0, 1 ); // use item storage to track -/* - if (modelPtr->rotationSpeed) - { - if (DC->realTime > item->window.nextTime) + /* + if (modelPtr->rotationSpeed) { - item->window.nextTime = DC->realTime + modelPtr->rotationSpeed; - modelPtr->angle = (int)(modelPtr->angle + 1) % 360; + if (DC->realTime > item->window.nextTime) + { + item->window.nextTime = DC->realTime + modelPtr->rotationSpeed; + modelPtr->angle = (int)(modelPtr->angle + 1) % 360; + } } - } - VectorSet( angles, 0, modelPtr->angle, 0 ); -*/ - VectorSet( angles, 0, (float)(refdef.time/20.0f), 0); + VectorSet( angles, 0, modelPtr->angle, 0 ); + */ + VectorSet(angles, 0, (float)(refdef.time / 20.0f), 0); - AnglesToAxis( angles, ent.axis ); + AnglesToAxis(angles, ent.axis); ent.hModel = item->asset; - VectorCopy( origin, ent.origin ); - VectorCopy( ent.origin, ent.oldorigin ); + VectorCopy(origin, ent.origin); + VectorCopy(ent.origin, ent.oldorigin); // Set up lighting - VectorCopy( refdef.vieworg, ent.lightingOrigin ); + VectorCopy(refdef.vieworg, ent.lightingOrigin); ent.renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW; - DC->addRefEntityToScene( &ent ); - DC->renderScene( &refdef ); + DC->addRefEntityToScene(&ent); + DC->renderScene(&refdef); #else // a moves datapad anim is playing - if (uiInfo.moveAnimTime && (uiInfo.moveAnimTime < uiInfo.uiDC.realTime)) - { + if (uiInfo.moveAnimTime && (uiInfo.moveAnimTime < uiInfo.uiDC.realTime)) { modelDef_t *modelPtr; - modelPtr = (modelDef_t*)item->typeData; - if (modelPtr) - { - //HACKHACKHACK: check for any multi-part anim sequences, and play the next anim, if needbe - switch( modelPtr->g2anim ) - { + modelPtr = (modelDef_t *)item->typeData; + if (modelPtr) { + // HACKHACKHACK: check for any multi-part anim sequences, and play the next anim, if needbe + switch (modelPtr->g2anim) { case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEJUMP1: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCEINAIR1].name ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCEINAIR1].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); - if ( !uiInfo.moveAnimTime ) - { + if (!uiInfo.moveAnimTime) { uiInfo.moveAnimTime = 500; } uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCEINAIR1: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCELAND1].name ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCELAND1].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCEWALLRUNFLIP_START: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCEWALLRUNFLIP_END].name ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCEWALLRUNFLIP_END].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCELONGLEAP_START: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCELONGLEAP_LAND].name ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCELONGLEAP_LAND].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN3://on front - into force getup - DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCE_GETUP_F1].name ); + case BOTH_KNOCKDOWN3: // on front - into force getup + DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCE_GETUP_F1].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN2://on back - kick forward getup - DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_GETUP_BROLL_F].name ); + case BOTH_KNOCKDOWN2: // on back - kick forward getup + DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveJumpSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_GETUP_BROLL_F].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN1://on back - roll-away - DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveRollSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_GETUP_BROLL_R].name ); + case BOTH_KNOCKDOWN1: // on back - roll-away + DC->startLocalSound(uiInfo.uiDC.Assets.datapadmoveRollSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_GETUP_BROLL_R].name); uiInfo.moveAnimTime = DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; default: - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim, qtrue); uiInfo.moveAnimTime = 0; break; @@ -7286,47 +6561,42 @@ void Item_Model_Paint(itemDef_t *item) } // setup the refdef - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); - x = item->window.rect.x+1; - y = item->window.rect.y+1; - w = item->window.rect.w-2; - h = item->window.rect.h-2; + AxisClear(refdef.viewaxis); + x = item->window.rect.x + 1; + y = item->window.rect.y + 1; + w = item->window.rect.w - 2; + h = item->window.rect.h - 2; refdef.x = x * DC->xscale; refdef.y = y * DC->yscale; refdef.width = w * DC->xscale; refdef.height = h * DC->yscale; - if (item->flags&ITF_G2VALID) - { //ghoul2 models don't have bounds, so we have to parse them. + if (item->flags & ITF_G2VALID) { // ghoul2 models don't have bounds, so we have to parse them. VectorCopy(modelPtr->g2mins, mins); VectorCopy(modelPtr->g2maxs, maxs); - if (!mins[0] && !mins[1] && !mins[2] && - !maxs[0] && !maxs[1] && !maxs[2]) - { //we'll use defaults then I suppose. + if (!mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]) { // we'll use defaults then I suppose. VectorSet(mins, -16, -16, -24); VectorSet(maxs, 16, 16, 32); } - } - else - { - DC->modelBounds( item->asset, mins, maxs ); + } else { + DC->modelBounds(item->asset, mins, maxs); } - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : (int)((float)refdef.width / 640.0f * 90.0f); - refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : atan2( refdef.height, refdef.width / tan( refdef.fov_x / 360 * M_PI ) ) * ( 360 / M_PI ); + refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : atan2(refdef.height, refdef.width / tan(refdef.fov_x / 360 * M_PI)) * (360 / M_PI); -// refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : refdef.width; -// refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : refdef.height; + // refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : refdef.width; + // refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : refdef.height; // calculate distance so the model nearly fills the box - float len = 0.5 * ( maxs[2] - mins[2] ); + float len = 0.5 * (maxs[2] - mins[2]); origin[0] = len / 0.268; DC->clearScene(); @@ -7335,60 +6605,50 @@ void Item_Model_Paint(itemDef_t *item) // add the model - memset( &ent, 0, sizeof(ent) ); + memset(&ent, 0, sizeof(ent)); // use item storage to track float curYaw = modelPtr->angle; - if (modelPtr->rotationSpeed) - { - curYaw += (float)refdef.time/modelPtr->rotationSpeed; - } - if ( item->flags&ITF_ISANYSABER && !(item->flags&ITF_ISCHARACTER) ) - {//hack to put saber on it's side - VectorSet( angles, curYaw, 0, 90 ); + if (modelPtr->rotationSpeed) { + curYaw += (float)refdef.time / modelPtr->rotationSpeed; } - else - { - VectorSet( angles, 0, curYaw, 0 ); + if (item->flags & ITF_ISANYSABER && !(item->flags & ITF_ISCHARACTER)) { // hack to put saber on it's side + VectorSet(angles, curYaw, 0, 90); + } else { + VectorSet(angles, 0, curYaw, 0); } + AnglesToAxis(angles, ent.axis); - AnglesToAxis( angles, ent.axis ); - - if (item->flags&ITF_G2VALID) - { + if (item->flags & ITF_G2VALID) { ent.ghoul2 = &item->ghoul2; ent.radius = 1000; ent.customSkin = modelPtr->g2skin; - if ( (item->flags&ITF_ISCHARACTER) ) - { + if ((item->flags & ITF_ISCHARACTER)) { ent.shaderRGBA[0] = ui_char_color_red.integer; ent.shaderRGBA[1] = ui_char_color_green.integer; ent.shaderRGBA[2] = ui_char_color_blue.integer; ent.shaderRGBA[3] = 255; UI_TalkingHead(item); } - if ( item->flags&ITF_ISANYSABER ) - {//UGH, draw the saber blade! - UI_SaberDrawBlades( item, origin, curYaw ); + if (item->flags & ITF_ISANYSABER) { // UGH, draw the saber blade! + UI_SaberDrawBlades(item, origin, curYaw); } - } - else - { + } else { ent.hModel = item->asset; } - VectorCopy( origin, ent.origin ); - VectorCopy( ent.origin, ent.oldorigin ); + VectorCopy(origin, ent.origin); + VectorCopy(ent.origin, ent.oldorigin); // Set up lighting - //VectorCopy( refdef.vieworg, ent.lightingOrigin ); + // VectorCopy( refdef.vieworg, ent.lightingOrigin ); ent.renderfx = RF_NOSHADOW; - ui.R_AddLightToScene(refdef.vieworg, 500, 1, 1, 1); //fixme: specify in menu file! + ui.R_AddLightToScene(refdef.vieworg, 500, 1, 1, 1); // fixme: specify in menu file! - DC->addRefEntityToScene( &ent ); - DC->renderScene( &refdef ); + DC->addRefEntityToScene(&ent); + DC->renderScene(&refdef); #endif } @@ -7397,89 +6657,79 @@ void Item_Model_Paint(itemDef_t *item) Item_OwnerDraw_Paint ================= */ -void Item_OwnerDraw_Paint(itemDef_t *item) -{ +void Item_OwnerDraw_Paint(itemDef_t *item) { menuDef_t *parent; - if (item == NULL) - { + if (item == NULL) { return; } - parent = (menuDef_t*)item->parent; + parent = (menuDef_t *)item->parent; - if (DC->ownerDrawItem) - { + if (DC->ownerDrawItem) { vec4_t color, lowLight; Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount); memcpy(&color, &item->window.foreColor, sizeof(color)); - if (item->numColors > 0 && DC->getValue) - { + if (item->numColors > 0 && DC->getValue) { // if the value is within one of the ranges then set color to that, otherwise leave at default int i; float f = DC->getValue(item->window.ownerDraw); - for (i = 0; i < item->numColors; i++) - { - if (f >= item->colorRanges[i].low && f <= item->colorRanges[i].high) - { + for (i = 0; i < item->numColors; i++) { + if (f >= item->colorRanges[i].low && f <= item->colorRanges[i].high) { memcpy(&color, &item->colorRanges[i].color, sizeof(color)); break; } } } - if (item->window.flags & WINDOW_HASFOCUS) - { + if (item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,color,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } - else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) - { + LerpColor(parent->focusColor, lowLight, color, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime / BLINK_DIVISOR) & 1)) { lowLight[0] = 0.8 * item->window.foreColor[0]; lowLight[1] = 0.8 * item->window.foreColor[1]; lowLight[2] = 0.8 * item->window.foreColor[2]; lowLight[3] = 0.8 * item->window.foreColor[3]; - LerpColor(item->window.foreColor,lowLight,color,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); + LerpColor(item->window.foreColor, lowLight, color, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } - if ( item->disabled ) - memcpy( color, parent->disableColor, sizeof( vec4_t ) ); + if (item->disabled) + memcpy(color, parent->disableColor, sizeof(vec4_t)); - if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) - { + if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) { memcpy(color, parent->disableColor, sizeof(vec4_t)); } - if (item->text) - { + if (item->text) { Item_Text_Paint(item); // +8 is an offset kludge to properly align owner draw items that have text combined with them - DC->ownerDrawItem(item->textRect.x + item->textRect.w + 8, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle, item->font ); - } - else - { - DC->ownerDrawItem(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->textalignx, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle, item->font ); + DC->ownerDrawItem(item->textRect.x + item->textRect.w + 8, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, + item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, + item->window.background, item->textStyle, item->font); + } else { + DC->ownerDrawItem(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->textalignx, item->textaligny, + item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, + item->window.background, item->textStyle, item->font); } } } -void Item_YesNo_Paint(itemDef_t *item) -{ +void Item_YesNo_Paint(itemDef_t *item) { vec4_t color; float value; value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0; #ifdef JK2_MODE - const char *psYes = ui.SP_GetStringTextString( "MENUS0_YES" ); - const char *psNo = ui.SP_GetStringTextString( "MENUS0_NO" ); + const char *psYes = ui.SP_GetStringTextString("MENUS0_YES"); + const char *psNo = ui.SP_GetStringTextString("MENUS0_NO"); #else - const char *psYes = SE_GetString( "MENUS_YES" ); - const char *psNo = SE_GetString( "MENUS_NO" ); + const char *psYes = SE_GetString("MENUS_YES"); + const char *psNo = SE_GetString("MENUS_NO"); #endif const char *yesnovalue; @@ -7489,16 +6739,12 @@ void Item_YesNo_Paint(itemDef_t *item) yesnovalue = (value != 0) ? psYes : psNo; Item_TextColor(item, &color); - if (item->text) - { + if (item->text) { Item_Text_Paint(item); DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, yesnovalue, 0, item->textStyle, item->font); + } else { + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, yesnovalue, 0, item->textStyle, item->font); } - else - { - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, yesnovalue , 0, item->textStyle, item->font); - } - } /* @@ -7506,59 +6752,49 @@ void Item_YesNo_Paint(itemDef_t *item) Item_Multi_Paint ================= */ -void Item_Multi_Paint(itemDef_t *item) -{ +void Item_Multi_Paint(itemDef_t *item) { vec4_t color; const char *text = ""; text = Item_Multi_Setting(item); - if (*text == '@') // string reference + if (*text == '@') // string reference { - text = SE_GetString( &text[1] ); + text = SE_GetString(&text[1]); } Item_TextColor(item, &color); - if (item->text) - { + if (item->text) { Item_Text_Paint(item); DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, text, 0, item->textStyle, item->font); - } - else - { -//JLF added xoffset - DC->drawText(item->textRect.x +item->xoffset, item->textRect.y, item->textscale, color, text, 0, item->textStyle, item->font); + } else { + // JLF added xoffset + DC->drawText(item->textRect.x + item->xoffset, item->textRect.y, item->textscale, color, text, 0, item->textStyle, item->font); } } -int Item_TextScroll_MaxScroll ( itemDef_t *item ) -{ - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; +int Item_TextScroll_MaxScroll(itemDef_t *item) { + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; int count = scrollPtr->iLineCount; - int max = count - (int)(item->window.rect.h / scrollPtr->lineHeight) + 1; + int max = count - (int)(item->window.rect.h / scrollPtr->lineHeight) + 1; - if (max < 0) - { + if (max < 0) { return 0; } return max; } -int Item_TextScroll_ThumbPosition ( itemDef_t *item ) -{ +int Item_TextScroll_ThumbPosition(itemDef_t *item) { float max, pos, size; - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; - max = Item_TextScroll_MaxScroll ( item ); + max = Item_TextScroll_MaxScroll(item); size = item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; - if (max > 0) - { - pos = (size-SCROLLBAR_SIZE) / (float) max; - } - else - { + if (max > 0) { + pos = (size - SCROLLBAR_SIZE) / (float)max; + } else { pos = 0; } @@ -7567,18 +6803,15 @@ int Item_TextScroll_ThumbPosition ( itemDef_t *item ) return item->window.rect.y + 1 + SCROLLBAR_SIZE + pos; } -int Item_TextScroll_ThumbDrawPosition ( itemDef_t *item ) -{ +int Item_TextScroll_ThumbDrawPosition(itemDef_t *item) { int min, max; - if (itemCapture == item) - { + if (itemCapture == item) { min = item->window.rect.y + SCROLLBAR_SIZE + 1; - max = item->window.rect.y + item->window.rect.h - 2*SCROLLBAR_SIZE - 1; + max = item->window.rect.y + item->window.rect.h - 2 * SCROLLBAR_SIZE - 1; - if (DC->cursory >= min + SCROLLBAR_SIZE/2 && DC->cursory <= max + SCROLLBAR_SIZE/2) - { - return DC->cursory - SCROLLBAR_SIZE/2; + if (DC->cursory >= min + SCROLLBAR_SIZE / 2 && DC->cursory <= max + SCROLLBAR_SIZE / 2) { + return DC->cursory - SCROLLBAR_SIZE / 2; } return Item_TextScroll_ThumbPosition(item); @@ -7587,60 +6820,52 @@ int Item_TextScroll_ThumbDrawPosition ( itemDef_t *item ) return Item_TextScroll_ThumbPosition(item); } -int Item_TextScroll_OverLB ( itemDef_t *item, float x, float y ) -{ - rectDef_t r; +int Item_TextScroll_OverLB(itemDef_t *item, float x, float y) { + rectDef_t r; textScrollDef_t *scrollPtr; - int thumbstart; + int thumbstart; - scrollPtr = (textScrollDef_t*)item->typeData; + scrollPtr = (textScrollDef_t *)item->typeData; // Scroll bar isn't drawing so ignore this input - if ((( scrollPtr->iLineCount * scrollPtr->lineHeight ) <= (item->window.rect.h - 2)) && (item->type == ITEM_TYPE_TEXTSCROLL)) - { + if (((scrollPtr->iLineCount * scrollPtr->lineHeight) <= (item->window.rect.h - 2)) && (item->type == ITEM_TYPE_TEXTSCROLL)) { return 0; } r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; r.y = item->window.rect.y; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } thumbstart = Item_TextScroll_ThumbPosition(item); r.y = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.y = item->window.rect.y + SCROLLBAR_SIZE; r.h = thumbstart - r.y; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.y = thumbstart + SCROLLBAR_SIZE; r.h = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } return 0; } -void Item_TextScroll_MouseEnter (itemDef_t *item, float x, float y) -{ +void Item_TextScroll_MouseEnter(itemDef_t *item, float x, float y) { item->window.flags &= ~(WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN); item->window.flags |= Item_TextScroll_OverLB(item, x, y); } @@ -7650,41 +6875,28 @@ void Item_TextScroll_MouseEnter (itemDef_t *item, float x, float y) Item_Slider_ThumbPosition ================= */ -int Item_ListBox_ThumbDrawPosition(itemDef_t *item) -{ +int Item_ListBox_ThumbDrawPosition(itemDef_t *item) { int min, max; - if (itemCapture == item) - { - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (itemCapture == item) { + if (item->window.flags & WINDOW_HORIZONTAL) { min = item->window.rect.x + SCROLLBAR_SIZE + 1; - max = item->window.rect.x + item->window.rect.w - 2*SCROLLBAR_SIZE - 1; - if (DC->cursorx >= min + SCROLLBAR_SIZE/2 && DC->cursorx <= max + SCROLLBAR_SIZE/2) - { - return DC->cursorx - SCROLLBAR_SIZE/2; - } - else - { + max = item->window.rect.x + item->window.rect.w - 2 * SCROLLBAR_SIZE - 1; + if (DC->cursorx >= min + SCROLLBAR_SIZE / 2 && DC->cursorx <= max + SCROLLBAR_SIZE / 2) { + return DC->cursorx - SCROLLBAR_SIZE / 2; + } else { return Item_ListBox_ThumbPosition(item); } - } - else - { + } else { min = item->window.rect.y + SCROLLBAR_SIZE + 1; - max = item->window.rect.y + item->window.rect.h - 2*SCROLLBAR_SIZE - 1; - if (DC->cursory >= min + SCROLLBAR_SIZE/2 && DC->cursory <= max + SCROLLBAR_SIZE/2) - { - return DC->cursory - SCROLLBAR_SIZE/2; - } - else - { + max = item->window.rect.y + item->window.rect.h - 2 * SCROLLBAR_SIZE - 1; + if (DC->cursory >= min + SCROLLBAR_SIZE / 2 && DC->cursory <= max + SCROLLBAR_SIZE / 2) { + return DC->cursory - SCROLLBAR_SIZE / 2; + } else { return Item_ListBox_ThumbPosition(item); } } - } - else - { + } else { return Item_ListBox_ThumbPosition(item); } } @@ -7694,44 +6906,36 @@ int Item_ListBox_ThumbDrawPosition(itemDef_t *item) Item_Slider_ThumbPosition ================= */ -float Item_Slider_ThumbPosition(itemDef_t *item) -{ +float Item_Slider_ThumbPosition(itemDef_t *item) { float value, range, x; - editFieldDef_t *editDef = (editFieldDef_t *) item->typeData; + editFieldDef_t *editDef = (editFieldDef_t *)item->typeData; - if (item->text) - { + if (item->text) { x = item->textRect.x + item->textRect.w + 8; - } - else - { + } else { x = item->window.rect.x; } - if (!editDef || !item->cvar) - { + if (!editDef || !item->cvar) { return x; } value = DC->getCVarValue(item->cvar); - if (value < editDef->minVal) - { + if (value < editDef->minVal) { value = editDef->minVal; - } - else if (value > editDef->maxVal) - { + } else if (value > editDef->maxVal) { value = editDef->maxVal; } range = editDef->maxVal - editDef->minVal; value -= editDef->minVal; value /= range; - //value /= (editDef->maxVal - editDef->minVal); + // value /= (editDef->maxVal - editDef->minVal); value *= SLIDER_WIDTH; x += value; // vm fuckage - //x = x + (((float)value / editDef->maxVal) * SLIDER_WIDTH); + // x = x + (((float)value / editDef->maxVal) * SLIDER_WIDTH); return x; } @@ -7740,42 +6944,34 @@ float Item_Slider_ThumbPosition(itemDef_t *item) Item_Slider_Paint ================= */ -void Item_Slider_Paint(itemDef_t *item) -{ +void Item_Slider_Paint(itemDef_t *item) { vec4_t newColor, lowLight; float x, y; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; - if (item->window.flags & WINDOW_HASFOCUS) - { + if (item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } - else - { + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else { memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t)); } y = item->window.rect.y; - if (item->text) - { + if (item->text) { Item_Text_Paint(item); x = item->textRect.x + item->textRect.w + 8; - } - else - { + } else { x = item->window.rect.x; } DC->setColor(newColor); - DC->drawHandlePic( x, y+2, SLIDER_WIDTH, SLIDER_HEIGHT, DC->Assets.sliderBar ); + DC->drawHandlePic(x, y + 2, SLIDER_WIDTH, SLIDER_HEIGHT, DC->Assets.sliderBar); x = Item_Slider_ThumbPosition(item); -// DC->drawHandlePic( x - (SLIDER_THUMB_WIDTH / 2), y - 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb ); - DC->drawHandlePic( x - (SLIDER_THUMB_WIDTH / 2), y+2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb ); - + // DC->drawHandlePic( x - (SLIDER_THUMB_WIDTH / 2), y - 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb ); + DC->drawHandlePic(x - (SLIDER_THUMB_WIDTH / 2), y + 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb); } /* @@ -7783,34 +6979,28 @@ void Item_Slider_Paint(itemDef_t *item) Item_Paint ================= */ -static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) -{ - int xPos,textWidth; +static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) { + int xPos, textWidth; vec4_t red; menuDef_t *parent; red[0] = red[3] = 1; red[1] = red[2] = 0; - if (item == NULL) - { + if (item == NULL) { return qfalse; } - parent = (menuDef_t*)item->parent; + parent = (menuDef_t *)item->parent; - if (item->window.flags & WINDOW_SCRIPTWAITING) - { - if (DC->realTime > item->window.delayTime) - { // Time has elapsed, resume running whatever script we saved + if (item->window.flags & WINDOW_SCRIPTWAITING) { + if (DC->realTime > item->window.delayTime) { // Time has elapsed, resume running whatever script we saved item->window.flags &= ~WINDOW_SCRIPTWAITING; Item_RunScript(item, item->window.delayedScript); } } - if (item->window.flags & WINDOW_ORBITING) - { - if (DC->realTime > item->window.nextTime) - { + if (item->window.flags & WINDOW_ORBITING) { + if (DC->realTime > item->window.nextTime) { float rx, ry, a, c, s, w, h; item->window.nextTime = DC->realTime + item->window.offsetTime; // translate @@ -7818,123 +7008,87 @@ static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) h = item->window.rectClient.h / 2; rx = item->window.rectClient.x + w - item->window.rectEffects.x; ry = item->window.rectClient.y + h - item->window.rectEffects.y; - a = (float) (3 * M_PI / 180); - c = cos(a); + a = (float)(3 * M_PI / 180); + c = cos(a); s = sin(a); item->window.rectClient.x = (rx * c - ry * s) + item->window.rectEffects.x - w; item->window.rectClient.y = (rx * s + ry * c) + item->window.rectEffects.y - h; Item_UpdatePosition(item); - } } - - if (item->window.flags & WINDOW_INTRANSITION) - { - if (DC->realTime > item->window.nextTime) - { + if (item->window.flags & WINDOW_INTRANSITION) { + if (DC->realTime > item->window.nextTime) { int done = 0; item->window.nextTime = DC->realTime + item->window.offsetTime; // transition the x,y - if (item->window.rectClient.x == item->window.rectEffects.x) - { + if (item->window.rectClient.x == item->window.rectEffects.x) { done++; - } - else - { - if (item->window.rectClient.x < item->window.rectEffects.x) - { + } else { + if (item->window.rectClient.x < item->window.rectEffects.x) { item->window.rectClient.x += item->window.rectEffects2.x; - if (item->window.rectClient.x > item->window.rectEffects.x) - { + if (item->window.rectClient.x > item->window.rectEffects.x) { item->window.rectClient.x = item->window.rectEffects.x; done++; } - } - else - { + } else { item->window.rectClient.x -= item->window.rectEffects2.x; - if (item->window.rectClient.x < item->window.rectEffects.x) - { + if (item->window.rectClient.x < item->window.rectEffects.x) { item->window.rectClient.x = item->window.rectEffects.x; done++; } } } - if (item->window.rectClient.y == item->window.rectEffects.y) - { + if (item->window.rectClient.y == item->window.rectEffects.y) { done++; - } - else - { - if (item->window.rectClient.y < item->window.rectEffects.y) - { + } else { + if (item->window.rectClient.y < item->window.rectEffects.y) { item->window.rectClient.y += item->window.rectEffects2.y; - if (item->window.rectClient.y > item->window.rectEffects.y) - { + if (item->window.rectClient.y > item->window.rectEffects.y) { item->window.rectClient.y = item->window.rectEffects.y; done++; } - } - else - { + } else { item->window.rectClient.y -= item->window.rectEffects2.y; - if (item->window.rectClient.y < item->window.rectEffects.y) - { + if (item->window.rectClient.y < item->window.rectEffects.y) { item->window.rectClient.y = item->window.rectEffects.y; done++; } } } - if (item->window.rectClient.w == item->window.rectEffects.w) - { + if (item->window.rectClient.w == item->window.rectEffects.w) { done++; - } - else - { - if (item->window.rectClient.w < item->window.rectEffects.w) - { + } else { + if (item->window.rectClient.w < item->window.rectEffects.w) { item->window.rectClient.w += item->window.rectEffects2.w; - if (item->window.rectClient.w > item->window.rectEffects.w) - { + if (item->window.rectClient.w > item->window.rectEffects.w) { item->window.rectClient.w = item->window.rectEffects.w; done++; } - } - else - { + } else { item->window.rectClient.w -= item->window.rectEffects2.w; - if (item->window.rectClient.w < item->window.rectEffects.w) - { + if (item->window.rectClient.w < item->window.rectEffects.w) { item->window.rectClient.w = item->window.rectEffects.w; done++; } } } - if (item->window.rectClient.h == item->window.rectEffects.h) - { + if (item->window.rectClient.h == item->window.rectEffects.h) { done++; - } - else - { - if (item->window.rectClient.h < item->window.rectEffects.h) - { + } else { + if (item->window.rectClient.h < item->window.rectEffects.h) { item->window.rectClient.h += item->window.rectEffects2.h; - if (item->window.rectClient.h > item->window.rectEffects.h) - { + if (item->window.rectClient.h > item->window.rectEffects.h) { item->window.rectClient.h = item->window.rectEffects.h; done++; } - } - else - { + } else { item->window.rectClient.h -= item->window.rectEffects2.h; - if (item->window.rectClient.h < item->window.rectEffects.h) - { + if (item->window.rectClient.h < item->window.rectEffects.h) { item->window.rectClient.h = item->window.rectEffects.h; done++; } @@ -7943,330 +7097,239 @@ static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) Item_UpdatePosition(item); - if (done == 4) - { + if (done == 4) { item->window.flags &= ~WINDOW_INTRANSITION; } - } } #ifdef _TRANS3 -//JLF begin model transition stuff - if (item->window.flags & WINDOW_INTRANSITIONMODEL) - { - if ( item->type == ITEM_TYPE_MODEL) - { -//fields ing modelptr -// vec3_t g2mins2, g2maxs2, g2minsEffect, g2maxsEffect; -// float fov_x2, fov_y2, fov_Effectx, fov_Effecty; + // JLF begin model transition stuff + if (item->window.flags & WINDOW_INTRANSITIONMODEL) { + if (item->type == ITEM_TYPE_MODEL) { + // fields ing modelptr + // vec3_t g2mins2, g2maxs2, g2minsEffect, g2maxsEffect; + // float fov_x2, fov_y2, fov_Effectx, fov_Effecty; - modelDef_t * modelptr = (modelDef_t *)item->typeData; + modelDef_t *modelptr = (modelDef_t *)item->typeData; - if (DC->realTime > item->window.nextTime) - { + if (DC->realTime > item->window.nextTime) { int done = 0; item->window.nextTime = DC->realTime + item->window.offsetTime; - -// transition the x,y,z max - if (modelptr->g2maxs[0] == modelptr->g2maxs2[0]) - { + // transition the x,y,z max + if (modelptr->g2maxs[0] == modelptr->g2maxs2[0]) { done++; - } - else - { - if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) - { + } else { + if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) { modelptr->g2maxs[0] += modelptr->g2maxsEffect[0]; - if (modelptr->g2maxs[0] > modelptr->g2maxs2[0]) - { + if (modelptr->g2maxs[0] > modelptr->g2maxs2[0]) { modelptr->g2maxs[0] = modelptr->g2maxs2[0]; done++; } - } - else - { + } else { modelptr->g2maxs[0] -= modelptr->g2maxsEffect[0]; - if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) - { + if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) { modelptr->g2maxs[0] = modelptr->g2maxs2[0]; done++; } } } -//y - if (modelptr->g2maxs[1] == modelptr->g2maxs2[1]) - { + // y + if (modelptr->g2maxs[1] == modelptr->g2maxs2[1]) { done++; - } - else - { - if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) - { + } else { + if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) { modelptr->g2maxs[1] += modelptr->g2maxsEffect[1]; - if (modelptr->g2maxs[1] > modelptr->g2maxs2[1]) - { + if (modelptr->g2maxs[1] > modelptr->g2maxs2[1]) { modelptr->g2maxs[1] = modelptr->g2maxs2[1]; done++; } - } - else - { + } else { modelptr->g2maxs[1] -= modelptr->g2maxsEffect[1]; - if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) - { + if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) { modelptr->g2maxs[1] = modelptr->g2maxs2[1]; done++; } } } + // z -//z - - if (modelptr->g2maxs[2] == modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] == modelptr->g2maxs2[2]) { done++; - } - else - { - if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) - { + } else { + if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) { modelptr->g2maxs[2] += modelptr->g2maxsEffect[2]; - if (modelptr->g2maxs[2] > modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] > modelptr->g2maxs2[2]) { modelptr->g2maxs[2] = modelptr->g2maxs2[2]; done++; } - } - else - { + } else { modelptr->g2maxs[2] -= modelptr->g2maxsEffect[2]; - if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) { modelptr->g2maxs[2] = modelptr->g2maxs2[2]; done++; } } } -// transition the x,y,z min - if (modelptr->g2mins[0] == modelptr->g2mins2[0]) - { + // transition the x,y,z min + if (modelptr->g2mins[0] == modelptr->g2mins2[0]) { done++; - } - else - { - if (modelptr->g2mins[0] < modelptr->g2mins2[0]) - { + } else { + if (modelptr->g2mins[0] < modelptr->g2mins2[0]) { modelptr->g2mins[0] += modelptr->g2minsEffect[0]; - if (modelptr->g2mins[0] > modelptr->g2mins2[0]) - { + if (modelptr->g2mins[0] > modelptr->g2mins2[0]) { modelptr->g2mins[0] = modelptr->g2mins2[0]; done++; } - } - else - { + } else { modelptr->g2mins[0] -= modelptr->g2minsEffect[0]; - if (modelptr->g2mins[0] < modelptr->g2mins2[0]) - { + if (modelptr->g2mins[0] < modelptr->g2mins2[0]) { modelptr->g2mins[0] = modelptr->g2mins2[0]; done++; } } } -//y - if (modelptr->g2mins[1] == modelptr->g2mins2[1]) - { + // y + if (modelptr->g2mins[1] == modelptr->g2mins2[1]) { done++; - } - else - { - if (modelptr->g2mins[1] < modelptr->g2mins2[1]) - { + } else { + if (modelptr->g2mins[1] < modelptr->g2mins2[1]) { modelptr->g2mins[1] += modelptr->g2minsEffect[1]; - if (modelptr->g2mins[1] > modelptr->g2mins2[1]) - { + if (modelptr->g2mins[1] > modelptr->g2mins2[1]) { modelptr->g2mins[1] = modelptr->g2mins2[1]; done++; } - } - else - { + } else { modelptr->g2mins[1] -= modelptr->g2minsEffect[1]; - if (modelptr->g2mins[1] < modelptr->g2mins2[1]) - { + if (modelptr->g2mins[1] < modelptr->g2mins2[1]) { modelptr->g2mins[1] = modelptr->g2mins2[1]; done++; } } } + // z -//z - - if (modelptr->g2mins[2] == modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] == modelptr->g2mins2[2]) { done++; - } - else - { - if (modelptr->g2mins[2] < modelptr->g2mins2[2]) - { + } else { + if (modelptr->g2mins[2] < modelptr->g2mins2[2]) { modelptr->g2mins[2] += modelptr->g2minsEffect[2]; - if (modelptr->g2mins[2] > modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] > modelptr->g2mins2[2]) { modelptr->g2mins[2] = modelptr->g2mins2[2]; done++; } - } - else - { + } else { modelptr->g2mins[2] -= modelptr->g2minsEffect[2]; - if (modelptr->g2mins[2] < modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] < modelptr->g2mins2[2]) { modelptr->g2mins[2] = modelptr->g2mins2[2]; done++; } } } - - -//fovx - if (modelptr->fov_x == modelptr->fov_x2) - { + // fovx + if (modelptr->fov_x == modelptr->fov_x2) { done++; - } - else - { - if (modelptr->fov_x < modelptr->fov_x2) - { + } else { + if (modelptr->fov_x < modelptr->fov_x2) { modelptr->fov_x += modelptr->fov_Effectx; - if (modelptr->fov_x > modelptr->fov_x2) - { + if (modelptr->fov_x > modelptr->fov_x2) { modelptr->fov_x = modelptr->fov_x2; done++; } - } - else - { + } else { modelptr->fov_x -= modelptr->fov_Effectx; - if (modelptr->fov_x < modelptr->fov_x2) - { + if (modelptr->fov_x < modelptr->fov_x2) { modelptr->fov_x = modelptr->fov_x2; done++; } } } -//fovy - if (modelptr->fov_y == modelptr->fov_y2) - { + // fovy + if (modelptr->fov_y == modelptr->fov_y2) { done++; - } - else - { - if (modelptr->fov_y < modelptr->fov_y2) - { + } else { + if (modelptr->fov_y < modelptr->fov_y2) { modelptr->fov_y += modelptr->fov_Effecty; - if (modelptr->fov_y > modelptr->fov_y2) - { + if (modelptr->fov_y > modelptr->fov_y2) { modelptr->fov_y = modelptr->fov_y2; done++; } - } - else - { + } else { modelptr->fov_y -= modelptr->fov_Effecty; - if (modelptr->fov_y < modelptr->fov_y2) - { + if (modelptr->fov_y < modelptr->fov_y2) { modelptr->fov_y = modelptr->fov_y2; done++; } } } - if (done == 5) - { + if (done == 5) { item->window.flags &= ~WINDOW_INTRANSITIONMODEL; } - } } } #endif -//JLF end transition stuff for models + // JLF end transition stuff for models - if (item->window.ownerDrawFlags && DC->ownerDrawVisible) - { - if (!DC->ownerDrawVisible(item->window.ownerDrawFlags)) - { + if (item->window.ownerDrawFlags && DC->ownerDrawVisible) { + if (!DC->ownerDrawVisible(item->window.ownerDrawFlags)) { item->window.flags &= ~WINDOW_VISIBLE; - } - else - { + } else { item->window.flags |= WINDOW_VISIBLE; } } - if (item->disabled && item->disabledHidden) - { + if (item->disabled && item->disabledHidden) { return qfalse; } - if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE)) - { - if (!Item_EnableShowViaCvar(item, CVAR_SHOW)) - { + if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE)) { + if (!Item_EnableShowViaCvar(item, CVAR_SHOW)) { return qfalse; } } - - if (item->window.flags & WINDOW_TIMEDVISIBLE) - { - + if (item->window.flags & WINDOW_TIMEDVISIBLE) { } - if (!(item->window.flags & WINDOW_VISIBLE)) - { + if (!(item->window.flags & WINDOW_VISIBLE)) { return qfalse; } - if (!bDraw) - { + if (!bDraw) { return qtrue; } - //okay to paint - //JLFMOUSE + // okay to paint + // JLFMOUSE - if (item->window.flags & WINDOW_MOUSEOVER) - { - if (item->descText && !Display_KeyBindPending()) - { + if (item->window.flags & WINDOW_MOUSEOVER) { + if (item->descText && !Display_KeyBindPending()) { // Make DOUBLY sure that this item should have desctext. // NOTE : we can't just check the mouse position on this, what if we TABBED // to the current menu item -- in that case our mouse isn't over the item. // Removing the WINDOW_MOUSEOVER flag just prevents the item's OnExit script from running - // if (!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - // { // It isn't something that should, because it isn't live anymore. - // item->window.flags &= ~WINDOW_MOUSEOVER; - // } - // else + // if (!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) + // { // It isn't something that should, because it isn't live anymore. + // item->window.flags &= ~WINDOW_MOUSEOVER; + // } + // else - //END JLFMOUSE + // END JLFMOUSE // items can be enabled and disabled based on cvars - if( !(item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) ) - { // Draw the desctext + if (!(item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE))) { // Draw the desctext const char *textPtr = item->descText; - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - textPtr = SE_GetString( &textPtr[1] ); + textPtr = SE_GetString(&textPtr[1]); } vec4_t color = {1, 1, 1, 1}; @@ -8274,46 +7337,39 @@ static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) float fDescScale = parent->descScale ? parent->descScale : 1; float fDescScaleCopy = fDescScale; - while (1) - { + while (1) { // FIXME - add some type of parameter in the menu file like descfont to specify the font for the descriptions for this menu. - textWidth = DC->textWidth(textPtr, fDescScale, MenuFontToReal(4)); // item->font); + textWidth = DC->textWidth(textPtr, fDescScale, MenuFontToReal(4)); // item->font); - if (parent->descAlignment == ITEM_ALIGN_RIGHT) - { - xPos = parent->descX - textWidth; // Right justify - } - else if (parent->descAlignment == ITEM_ALIGN_CENTER) - { - xPos = parent->descX - (textWidth/2); // Center justify - } - else // Left justify + if (parent->descAlignment == ITEM_ALIGN_RIGHT) { + xPos = parent->descX - textWidth; // Right justify + } else if (parent->descAlignment == ITEM_ALIGN_CENTER) { + xPos = parent->descX - (textWidth / 2); // Center justify + } else // Left justify { xPos = parent->descX; } - if (parent->descAlignment == ITEM_ALIGN_CENTER) - { + if (parent->descAlignment == ITEM_ALIGN_CENTER) { // only this one will auto-shrink the scale until we eventually fit... // - if (xPos + textWidth > (SCREEN_WIDTH-4)) { + if (xPos + textWidth > (SCREEN_WIDTH - 4)) { fDescScale -= 0.001f; continue; } } - // Try to adjust it's y placement if the scale has changed... // int iYadj = 0; - if (fDescScale != fDescScaleCopy) - { + if (fDescScale != fDescScaleCopy) { int iOriginalTextHeight = DC->textHeight(textPtr, fDescScaleCopy, uiInfo.uiDC.Assets.qhMediumFont); iYadj = iOriginalTextHeight - DC->textHeight(textPtr, fDescScale, uiInfo.uiDC.Assets.qhMediumFont); } // FIXME - add some type of parameter in the menu file like descfont to specify the font for the descriptions for this menu. - DC->drawText(xPos, parent->descY + iYadj, fDescScale, parent->descColor, textPtr, 0, parent->descTextStyle, MenuFontToReal(4)); //item->font); + DC->drawText(xPos, parent->descY + iYadj, fDescScale, parent->descColor, textPtr, 0, parent->descTextStyle, + MenuFontToReal(4)); // item->font); break; } } @@ -8321,68 +7377,60 @@ static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) } // paint the rect first.. - Window_Paint(&item->window, parent->fadeAmount , parent->fadeClamp, parent->fadeCycle); + Window_Paint(&item->window, parent->fadeAmount, parent->fadeClamp, parent->fadeCycle); // Print a box showing the extents of the rectangle, when in debug mode - if (uis.debugMode) - { + if (uis.debugMode) { vec4_t color; color[1] = color[3] = 1; color[0] = color[2] = 0; - DC->drawRect( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - 1, - color); + DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, color); } - //DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, red); + // DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, red); - switch (item->type) - { - case ITEM_TYPE_OWNERDRAW: - Item_OwnerDraw_Paint(item); - break; + switch (item->type) { + case ITEM_TYPE_OWNERDRAW: + Item_OwnerDraw_Paint(item); + break; - case ITEM_TYPE_TEXT: - case ITEM_TYPE_BUTTON: - Item_Text_Paint(item); - break; - case ITEM_TYPE_RADIOBUTTON: - break; - case ITEM_TYPE_CHECKBOX: - break; - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - Item_TextField_Paint(item); - break; - case ITEM_TYPE_COMBO: - break; - case ITEM_TYPE_LISTBOX: - Item_ListBox_Paint(item); - break; - case ITEM_TYPE_TEXTSCROLL: - Item_TextScroll_Paint ( item ); - break; - case ITEM_TYPE_MODEL: - Item_Model_Paint(item); - break; - case ITEM_TYPE_YESNO: - Item_YesNo_Paint(item); - break; - case ITEM_TYPE_MULTI: - Item_Multi_Paint(item); - break; - case ITEM_TYPE_BIND: - Item_Bind_Paint(item); - break; - case ITEM_TYPE_SLIDER: - Item_Slider_Paint(item); - break; - default: - break; + case ITEM_TYPE_TEXT: + case ITEM_TYPE_BUTTON: + Item_Text_Paint(item); + break; + case ITEM_TYPE_RADIOBUTTON: + break; + case ITEM_TYPE_CHECKBOX: + break; + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + Item_TextField_Paint(item); + break; + case ITEM_TYPE_COMBO: + break; + case ITEM_TYPE_LISTBOX: + Item_ListBox_Paint(item); + break; + case ITEM_TYPE_TEXTSCROLL: + Item_TextScroll_Paint(item); + break; + case ITEM_TYPE_MODEL: + Item_Model_Paint(item); + break; + case ITEM_TYPE_YESNO: + Item_YesNo_Paint(item); + break; + case ITEM_TYPE_MULTI: + Item_Multi_Paint(item); + break; + case ITEM_TYPE_BIND: + Item_Bind_Paint(item); + break; + case ITEM_TYPE_SLIDER: + Item_Slider_Paint(item); + break; + default: + break; } return qtrue; } @@ -8392,20 +7440,15 @@ static qboolean Item_Paint(itemDef_t *item, qboolean bDraw) LerpColor ================= */ -void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t) -{ +void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t) { int i; // lerp and clamp each component - for (i=0; i<4; i++) - { - c[i] = a[i] + t*(b[i]-a[i]); - if (c[i] < 0) - { + for (i = 0; i < 4; i++) { + c[i] = a[i] + t * (b[i] - a[i]); + if (c[i] < 0) { c[i] = 0; - } - else if (c[i] > 1.0) - { + } else if (c[i] > 1.0) { c[i] = 1.0; } } @@ -8416,29 +7459,20 @@ void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t) Fade ================= */ -void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount) -{ - if (*flags & (WINDOW_FADINGOUT | WINDOW_FADINGIN)) - { - if (DC->realTime > *nextTime) - { +void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount) { + if (*flags & (WINDOW_FADINGOUT | WINDOW_FADINGIN)) { + if (DC->realTime > *nextTime) { *nextTime = DC->realTime + offsetTime; - if (*flags & WINDOW_FADINGOUT) - { + if (*flags & WINDOW_FADINGOUT) { *f -= fadeAmount; - if (bFlags && *f <= 0.0) - { + if (bFlags && *f <= 0.0) { *flags &= ~(WINDOW_FADINGOUT | WINDOW_VISIBLE); } - } - else - { + } else { *f += fadeAmount; - if (*f >= clamp) - { - *f = clamp; - if (bFlags) - { + if (*f >= clamp) { + *f = clamp; + if (bFlags) { *flags &= ~WINDOW_FADINGIN; } } @@ -8452,12 +7486,11 @@ void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboo GradientBar_Paint ================= */ -void GradientBar_Paint(rectDef_t *rect, vec4_t color) -{ +void GradientBar_Paint(rectDef_t *rect, vec4_t color) { // gradient bar takes two paints - DC->setColor( color ); + DC->setColor(color); DC->drawHandlePic(rect->x, rect->y, rect->w, rect->h, DC->Assets.gradientBar); - DC->setColor( NULL ); + DC->setColor(NULL); } /* @@ -8465,111 +7498,83 @@ void GradientBar_Paint(rectDef_t *rect, vec4_t color) Window_Paint ================= */ -void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle) -{ - //float bordersize = 0; +void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle) { + // float bordersize = 0; vec4_t color; rectDef_t fillRect = w->rect; - if (uis.debugMode) - { + if (uis.debugMode) { color[0] = color[1] = color[2] = color[3] = 1; DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, 1, color); } - if (w == NULL || (w->style == 0 && w->border == 0)) - { + if (w == NULL || (w->style == 0 && w->border == 0)) { return; } - if (w->border != 0) - { + if (w->border != 0) { fillRect.x += w->borderSize; fillRect.y += w->borderSize; fillRect.w -= w->borderSize + 1; fillRect.h -= w->borderSize + 1; } - if (w->style == WINDOW_STYLE_FILLED) - { + if (w->style == WINDOW_STYLE_FILLED) { // box, but possible a shader that needs filled - if (w->background) - { + if (w->background) { Fade(&w->flags, &w->backColor[3], fadeClamp, &w->nextTime, fadeCycle, qtrue, fadeAmount); DC->setColor(w->backColor); DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background); DC->setColor(NULL); - } - else - { + } else { DC->fillRect(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->backColor); } - } - else if (w->style == WINDOW_STYLE_GRADIENT) - { + } else if (w->style == WINDOW_STYLE_GRADIENT) { GradientBar_Paint(&fillRect, w->backColor); // gradient bar - } - else if (w->style == WINDOW_STYLE_SHADER) - { - if (w->flags & WINDOW_PLAYERCOLOR) - { - vec4_t color; - color[0] = ui_char_color_red.integer/255.0f; - color[1] = ui_char_color_green.integer/255.0f; - color[2] = ui_char_color_blue.integer/255.0f; + } else if (w->style == WINDOW_STYLE_SHADER) { + if (w->flags & WINDOW_PLAYERCOLOR) { + vec4_t color; + color[0] = ui_char_color_red.integer / 255.0f; + color[1] = ui_char_color_green.integer / 255.0f; + color[2] = ui_char_color_blue.integer / 255.0f; color[3] = 1; ui.R_SetColor(color); - } - else if (w->flags & WINDOW_FORECOLORSET) - { + } else if (w->flags & WINDOW_FORECOLORSET) { DC->setColor(w->foreColor); } DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background); DC->setColor(NULL); } - if (w->border == WINDOW_BORDER_FULL) - { + if (w->border == WINDOW_BORDER_FULL) { // full // HACK HACK HACK - if (w->style == WINDOW_STYLE_TEAMCOLOR) - { - if (color[0] > 0) - { + if (w->style == WINDOW_STYLE_TEAMCOLOR) { + if (color[0] > 0) { // red color[0] = 1; color[1] = color[2] = .5; - } - else - { + } else { color[2] = 1; color[0] = color[1] = .5; } color[3] = 1; DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, color); - } - else - { + } else { DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, w->borderColor); } - } - else if (w->border == WINDOW_BORDER_HORZ) - { + } else if (w->border == WINDOW_BORDER_HORZ) { // top/bottom DC->setColor(w->borderColor); DC->drawTopBottom(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize); - DC->setColor( NULL ); - } - else if (w->border == WINDOW_BORDER_VERT) - { + DC->setColor(NULL); + } else if (w->border == WINDOW_BORDER_VERT) { // left right DC->setColor(w->borderColor); DC->drawSides(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize); - DC->setColor( NULL ); - } - else if (w->border == WINDOW_BORDER_KCGRADIENT) - { + DC->setColor(NULL); + } else if (w->border == WINDOW_BORDER_KCGRADIENT) { // this is just two gradient bars along each horz edge rectDef_t r = w->rect; r.h = w->borderSize; @@ -8584,20 +7589,15 @@ void Window_Paint(Window *w, float fadeAmount, float fadeClamp, float fadeCycle) Display_KeyBindPending ================= */ -qboolean Display_KeyBindPending(void) -{ - return g_waitingForKey; -} +qboolean Display_KeyBindPending(void) { return g_waitingForKey; } /* ================= ToWindowCoords ================= */ -void ToWindowCoords(float *x, float *y, windowDef_t *window) -{ - if (window->border != 0) - { +void ToWindowCoords(float *x, float *y, windowDef_t *window) { + if (window->border != 0) { *x += window->borderSize; *y += window->borderSize; } @@ -8610,8 +7610,7 @@ void ToWindowCoords(float *x, float *y, windowDef_t *window) Item_Text_AutoWrapped_Paint ================= */ -void Item_Text_AutoWrapped_Paint(itemDef_t *item) -{ +void Item_Text_AutoWrapped_Paint(itemDef_t *item) { char text[1024]; const char *p, *textPtr, *newLinePtr; char buff[1024]; @@ -8622,35 +7621,27 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) textWidth = 0; newLinePtr = NULL; - if (item->text == NULL) - { - if (item->cvar == NULL) - { + if (item->text == NULL) { + if (item->cvar == NULL) { return; - } - else - { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else - { + } else { textPtr = item->text; } - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - textPtr = SE_GetString( &textPtr[1] ); + textPtr = SE_GetString(&textPtr[1]); } - if (*textPtr == '\0') - { + if (*textPtr == '\0') { return; } Item_TextColor(item, &color); - //Item_SetTextExtents(item, &width, &height, textPtr); - if (item->value == 0) - { + // Item_SetTextExtents(item, &width, &height, textPtr); + if (item->value == 0) { item->value = (int)(0.5 + (float)DC->textWidth(textPtr, item->textscale, item->font) / item->window.rect.w); } height = DC->textHeight(textPtr, item->textscale, item->font); @@ -8663,59 +7654,46 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) newLineWidth = 0; p = textPtr; int line = 1; - while (1) //findmeste (this will break widechar languages)! + while (1) // findmeste (this will break widechar languages)! { - if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\0') - { + if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\0') { newLine = len; - newLinePtr = p+1; + newLinePtr = p + 1; newLineWidth = textWidth; } textWidth = DC->textWidth(buff, item->textscale, 0); - if ( (newLine && textWidth >= item->window.rect.w - item->textalignx) || *p == '\n' || *p == '\0') - { - if (line > item->cursorPos) //scroll - { - if (len) - { - if (item->textalignment == ITEM_ALIGN_LEFT) - { - item->textRect.x = item->textalignx; - } - else if (item->textalignment == ITEM_ALIGN_RIGHT) - { - item->textRect.x = item->textalignx - newLineWidth; + if ((newLine && textWidth >= item->window.rect.w - item->textalignx) || *p == '\n' || *p == '\0') { + if (line > item->cursorPos) // scroll + { + if (len) { + if (item->textalignment == ITEM_ALIGN_LEFT) { + item->textRect.x = item->textalignx; + } else if (item->textalignment == ITEM_ALIGN_RIGHT) { + item->textRect.x = item->textalignx - newLineWidth; + } else if (item->textalignment == ITEM_ALIGN_CENTER) { + item->textRect.x = item->textalignx - newLineWidth / 2; + } + item->textRect.y = y; + ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window); + // + buff[newLine] = '\0'; + + if (*p && y + height + 4 > item->window.rect.h - height) { + item->special = 1; + strcat(buff, "..."); // uhh, let's render some ellipses + } + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, buff, 0, item->textStyle, item->font); } - else if (item->textalignment == ITEM_ALIGN_CENTER) - { - item->textRect.x = item->textalignx - newLineWidth / 2; - } - item->textRect.y = y; - ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window); - // - buff[newLine] = '\0'; - - if ( *p && y + height + 4 > item->window.rect.h - height) - { - item->special = 1; - strcat(buff,"...");//uhh, let's render some ellipses - } - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, buff, 0, item->textStyle, item->font); - } y += height + 4; - if ( y > item->window.rect.h - height) - {//reached the bottom of the box, so stop + if (y > item->window.rect.h - height) { // reached the bottom of the box, so stop break; } len = 0; - } - else - { - strcpy(buff,"..."); + } else { + strcpy(buff, "..."); len = 3; } - if (*p == '\0') - { //end of string + if (*p == '\0') { // end of string break; } p = newLinePtr; @@ -8734,18 +7712,14 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) Rect_ContainsPoint ================= */ -static qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) -{ - //JLF ignore mouse pointer location -// return true; +static qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) { + // JLF ignore mouse pointer location + // return true; // END JLF - if (rect) - { -// if ((x > rect->x) && (x < (rect->x + rect->w)) && (y > rect->y) && (y < (rect->y + rect->h))) - if ((x > rect->x) && (x < (rect->x + rect->w))) - { - if ((y > rect->y) && (y < (rect->y + rect->h))) - { + if (rect) { + // if ((x > rect->x) && (x < (rect->x + rect->w)) && (y > rect->y) && (y < (rect->y + rect->h))) + if ((x > rect->x) && (x < (rect->x + rect->w))) { + if ((y > rect->y) && (y < (rect->y + rect->h))) { return qtrue; } } @@ -8753,44 +7727,36 @@ static qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) return qfalse; } -qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qboolean force) -{ - textScrollDef_t *scrollPtr = (textScrollDef_t*)item->typeData; - int max; - int viewmax; +qboolean Item_TextScroll_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) { + textScrollDef_t *scrollPtr = (textScrollDef_t *)item->typeData; + int max; + int viewmax; - if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) - { + if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) { max = Item_TextScroll_MaxScroll(item); viewmax = (item->window.rect.h / scrollPtr->lineHeight); - if ( key == A_CURSOR_UP || key == A_KP_8 ) - { + if (key == A_CURSOR_UP || key == A_KP_8) { scrollPtr->startPos--; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } return qtrue; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 ) - { + if (key == A_CURSOR_DOWN || key == A_KP_2) { scrollPtr->startPos++; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } return qtrue; } - //Raz: Added - if ( key == A_MWHEELUP ) - { + // Raz: Added + if (key == A_MWHEELUP) { scrollPtr->startPos--; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -8798,11 +7764,9 @@ qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qb Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qtrue; } - if ( key == A_MWHEELDOWN ) - { + if (key == A_MWHEELDOWN) { scrollPtr->startPos++; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -8812,78 +7776,58 @@ qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qb } // mouse hit - if (key == A_MOUSE1 || key == A_MOUSE2) - { - if (item->window.flags & WINDOW_LB_LEFTARROW) - { + if (key == A_MOUSE1 || key == A_MOUSE2) { + if (item->window.flags & WINDOW_LB_LEFTARROW) { scrollPtr->startPos--; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_RIGHTARROW) - { + } else if (item->window.flags & WINDOW_LB_RIGHTARROW) { // one down scrollPtr->startPos++; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_PGUP) - { + } else if (item->window.flags & WINDOW_LB_PGUP) { // page up scrollPtr->startPos -= viewmax; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_PGDN) - { + } else if (item->window.flags & WINDOW_LB_PGDN) { // page down scrollPtr->startPos += viewmax; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_THUMB) - { + } else if (item->window.flags & WINDOW_LB_THUMB) { // Display_SetCaptureItem(item); } return qtrue; } - if ( key == A_HOME || key == A_KP_7) - { + if (key == A_HOME || key == A_KP_7) { // home scrollPtr->startPos = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) - { + if (key == A_END || key == A_KP_1) { // end scrollPtr->startPos = max; return qtrue; } - if (key == A_PAGE_UP || key == A_KP_9 ) - { + if (key == A_PAGE_UP || key == A_KP_9) { scrollPtr->startPos -= viewmax; - if (scrollPtr->startPos < 0) - { - scrollPtr->startPos = 0; + if (scrollPtr->startPos < 0) { + scrollPtr->startPos = 0; } return qtrue; } - if ( key == A_PAGE_DOWN || key == A_KP_3 ) - { + if (key == A_PAGE_DOWN || key == A_KP_3) { scrollPtr->startPos += viewmax; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } return qtrue; @@ -8898,23 +7842,18 @@ qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qb Item_ListBox_MaxScroll ================= */ -int Item_ListBox_MaxScroll(itemDef_t *item) -{ - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; +int Item_ListBox_MaxScroll(itemDef_t *item) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; int count = DC->feederCount(item->special); int max; - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (item->window.flags & WINDOW_HORIZONTAL) { max = count - (item->window.rect.w / listPtr->elementWidth) + 1; - } - else - { + } else { max = count - (item->window.rect.h / listPtr->elementHeight) + 1; } - if (max < 0) - { + if (max < 0) { return 0; } return max; @@ -8925,35 +7864,26 @@ int Item_ListBox_MaxScroll(itemDef_t *item) Item_ListBox_ThumbPosition ================= */ -int Item_ListBox_ThumbPosition(itemDef_t *item) -{ +int Item_ListBox_ThumbPosition(itemDef_t *item) { float max, pos, size; - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; max = Item_ListBox_MaxScroll(item); if (item->window.flags & WINDOW_HORIZONTAL) { size = item->window.rect.w - (SCROLLBAR_SIZE * 2) - 2; - if (max > 0) - { - pos = (size-SCROLLBAR_SIZE) / (float) max; - } - else - { + if (max > 0) { + pos = (size - SCROLLBAR_SIZE) / (float)max; + } else { pos = 0; } pos *= listPtr->startPos; return item->window.rect.x + 1 + SCROLLBAR_SIZE + pos; - } - else - { + } else { size = item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; - if (max > 0) - { - pos = (size-SCROLLBAR_SIZE) / (float) max; - } - else - { + if (max > 0) { + pos = (size - SCROLLBAR_SIZE) / (float)max; + } else { pos = 0; } pos *= listPtr->startPos; @@ -8966,77 +7896,63 @@ int Item_ListBox_ThumbPosition(itemDef_t *item) Item_ListBox_OverLB ================= */ -int Item_ListBox_OverLB(itemDef_t *item, float x, float y) -{ +int Item_ListBox_OverLB(itemDef_t *item, float x, float y) { rectDef_t r; int thumbstart; - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (item->window.flags & WINDOW_HORIZONTAL) { // check if on left arrow r.x = item->window.rect.x; r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } // check if on right arrow r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } // check if on thumb thumbstart = Item_ListBox_ThumbPosition(item); r.x = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.x = item->window.rect.x + SCROLLBAR_SIZE; r.w = thumbstart - r.x; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.x = thumbstart + SCROLLBAR_SIZE; r.w = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } - } - else - { + } else { r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; r.y = item->window.rect.y; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } thumbstart = Item_ListBox_ThumbPosition(item); r.y = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.y = item->window.rect.y + SCROLLBAR_SIZE; r.h = thumbstart - r.y; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.y = thumbstart + SCROLLBAR_SIZE; r.h = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } } @@ -9048,51 +7964,39 @@ int Item_ListBox_OverLB(itemDef_t *item, float x, float y) Item_ListBox_MouseEnter ================= */ -void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y) -{ +void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y) { rectDef_t r; - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; item->window.flags &= ~(WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN); item->window.flags |= Item_ListBox_OverLB(item, x, y); - if (item->window.flags & WINDOW_HORIZONTAL) - { - if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) - { + if (item->window.flags & WINDOW_HORIZONTAL) { + if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) { // check for selection hit as we have exausted buttons and thumb - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { r.x = item->window.rect.x; r.y = item->window.rect.y; r.h = item->window.rect.h - SCROLLBAR_SIZE; r.w = item->window.rect.w - listPtr->drawPadding; - if (Rect_ContainsPoint(&r, x, y)) - { - listPtr->cursorPos = (int)((x - r.x) / listPtr->elementWidth) + listPtr->startPos; - if (listPtr->cursorPos > listPtr->endPos) - { + if (Rect_ContainsPoint(&r, x, y)) { + listPtr->cursorPos = (int)((x - r.x) / listPtr->elementWidth) + listPtr->startPos; + if (listPtr->cursorPos > listPtr->endPos) { listPtr->cursorPos = listPtr->endPos; } } - } - else - { + } else { // text hit.. } } - } - else if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) - { + } else if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) { r.x = item->window.rect.x; r.y = item->window.rect.y; r.w = item->window.rect.w - SCROLLBAR_SIZE; r.h = item->window.rect.h - listPtr->drawPadding; - if (Rect_ContainsPoint(&r, x, y)) - { - listPtr->cursorPos = (int)((y - 2 - r.y) / listPtr->elementHeight) + listPtr->startPos; - if (listPtr->cursorPos > listPtr->endPos) - { + if (Rect_ContainsPoint(&r, x, y)) { + listPtr->cursorPos = (int)((y - 2 - r.y) / listPtr->elementHeight) + listPtr->startPos; + if (listPtr->cursorPos > listPtr->endPos) { listPtr->cursorPos = listPtr->endPos; } } @@ -9104,168 +8008,134 @@ void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y) Item_MouseEnter ================= */ -void Item_MouseEnter(itemDef_t *item, float x, float y) -{ +void Item_MouseEnter(itemDef_t *item, float x, float y) { rectDef_t r; - //JLFMOUSE - if (item) - { + // JLFMOUSE + if (item) { r = item->textRect; -// r.y -= r.h; // NOt sure why this is here, but I commented it out. + // r.y -= r.h; // NOt sure why this is here, but I commented it out. // in the text rect? // items can be enabled and disabled - if (item->disabled) - { + if (item->disabled) { return; } // items can be enabled and disabled based on cvars - if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) - { + if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) { return; } - if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) - { + if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) { return; } -//JLFMOUSE - if (Rect_ContainsPoint(&r, x, y)) - { - if (!(item->window.flags & WINDOW_MOUSEOVERTEXT)) - { + // JLFMOUSE + if (Rect_ContainsPoint(&r, x, y)) { + if (!(item->window.flags & WINDOW_MOUSEOVERTEXT)) { Item_RunScript(item, item->mouseEnterText); item->window.flags |= WINDOW_MOUSEOVERTEXT; } - if (!(item->window.flags & WINDOW_MOUSEOVER)) - { + if (!(item->window.flags & WINDOW_MOUSEOVER)) { Item_RunScript(item, item->mouseEnter); item->window.flags |= WINDOW_MOUSEOVER; } - } - else - { + } else { // not in the text rect - if (item->window.flags & WINDOW_MOUSEOVERTEXT) - { + if (item->window.flags & WINDOW_MOUSEOVERTEXT) { // if we were Item_RunScript(item, item->mouseExitText); item->window.flags &= ~WINDOW_MOUSEOVERTEXT; } - if (!(item->window.flags & WINDOW_MOUSEOVER)) - { + if (!(item->window.flags & WINDOW_MOUSEOVER)) { Item_RunScript(item, item->mouseEnter); item->window.flags |= WINDOW_MOUSEOVER; } - if (item->type == ITEM_TYPE_LISTBOX) - { + if (item->type == ITEM_TYPE_LISTBOX) { Item_ListBox_MouseEnter(item, x, y); - } - else if ( item->type == ITEM_TYPE_TEXTSCROLL ) - { - Item_TextScroll_MouseEnter ( item, x, y ); + } else if (item->type == ITEM_TYPE_TEXTSCROLL) { + Item_TextScroll_MouseEnter(item, x, y); } } } } - - /* ================= Item_SetFocus ================= */ // will optionaly set focus to this item -qboolean Item_SetFocus(itemDef_t *item, float x, float y) -{ +qboolean Item_SetFocus(itemDef_t *item, float x, float y) { int i; itemDef_t *oldFocus; sfxHandle_t *sfx = &DC->Assets.itemFocusSound; qboolean playSound = qfalse; // sanity check, non-null, not a decoration and does not already have the focus - if (item == NULL || item->window.flags & WINDOW_DECORATION || item->window.flags & WINDOW_HASFOCUS || !(item->window.flags & WINDOW_VISIBLE) || (item->window.flags & WINDOW_INACTIVE)) - { + if (item == NULL || item->window.flags & WINDOW_DECORATION || item->window.flags & WINDOW_HASFOCUS || !(item->window.flags & WINDOW_VISIBLE) || + (item->window.flags & WINDOW_INACTIVE)) { return qfalse; } - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; // items can be enabled and disabled - if (item->disabled) - { + if (item->disabled) { return qfalse; } // items can be enabled and disabled based on cvars - if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) - { + if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) { return qfalse; } - if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) - { + if (item->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(item, CVAR_SHOW)) { return qfalse; } - oldFocus = Menu_ClearFocus((menuDef_t *) item->parent); + oldFocus = Menu_ClearFocus((menuDef_t *)item->parent); - if (item->type == ITEM_TYPE_TEXT) - { + if (item->type == ITEM_TYPE_TEXT) { rectDef_t r; r = item->textRect; - //r.y -= r.h; -//JLFMOUSE - if (Rect_ContainsPoint(&r, x, y)) - { + // r.y -= r.h; + // JLFMOUSE + if (Rect_ContainsPoint(&r, x, y)) { item->window.flags |= WINDOW_HASFOCUS; - if (item->focusSound) - { + if (item->focusSound) { sfx = &item->focusSound; } playSound = qtrue; - } - else + } else { - if (oldFocus) - { + if (oldFocus) { oldFocus->window.flags |= WINDOW_HASFOCUS; - if (oldFocus->onFocus) - { + if (oldFocus->onFocus) { Item_RunScript(oldFocus, oldFocus->onFocus); } } } - } - else - { - item->window.flags |= WINDOW_HASFOCUS; - if (item->onFocus) - { + } else { + item->window.flags |= WINDOW_HASFOCUS; + if (item->onFocus) { Item_RunScript(item, item->onFocus); } - if (item->focusSound) - { + if (item->focusSound) { sfx = &item->focusSound; } playSound = qtrue; } - if (playSound && sfx) - { - DC->startLocalSound( *sfx, CHAN_LOCAL_SOUND ); + if (playSound && sfx) { + DC->startLocalSound(*sfx, CHAN_LOCAL_SOUND); } - for (i = 0; i < parent->itemCount; i++) - { - if (parent->items[i] == item) - { + for (i = 0; i < parent->itemCount; i++) { + if (parent->items[i] == item) { parent->cursorItem = i; break; } @@ -9274,28 +8144,21 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) return qtrue; } - /* ================= IsVisible ================= */ -qboolean IsVisible(int flags) -{ - return (qboolean)((flags & WINDOW_VISIBLE && !(flags & WINDOW_FADINGOUT)) != 0); -} +qboolean IsVisible(int flags) { return (qboolean)((flags & WINDOW_VISIBLE && !(flags & WINDOW_FADINGOUT)) != 0); } /* ================= Item_MouseLeave ================= */ -void Item_MouseLeave(itemDef_t *item) -{ - if (item) - { - if (item->window.flags & WINDOW_MOUSEOVERTEXT) - { +void Item_MouseLeave(itemDef_t *item) { + if (item) { + if (item->window.flags & WINDOW_MOUSEOVERTEXT) { Item_RunScript(item, item->mouseExitText); item->window.flags &= ~WINDOW_MOUSEOVERTEXT; } @@ -9309,16 +8172,11 @@ void Item_MouseLeave(itemDef_t *item) Item_SetMouseOver ================= */ -void Item_SetMouseOver(itemDef_t *item, qboolean focus) -{ - if (item) - { - if (focus) - { +void Item_SetMouseOver(itemDef_t *item, qboolean focus) { + if (item) { + if (focus) { item->window.flags |= WINDOW_MOUSEOVER; - } - else - { + } else { item->window.flags &= ~WINDOW_MOUSEOVER; } } @@ -9329,98 +8187,79 @@ void Item_SetMouseOver(itemDef_t *item, qboolean focus) Menu_HandleMouseMove ================= */ -void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) -{ +void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) { int i, pass; qboolean focusSet = qfalse; itemDef_t *overItem; - if (menu == NULL) - { + if (menu == NULL) { return; } - if (!(menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) - { + if (!(menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { return; } - if (itemCapture) - { - //Item_MouseMove(itemCapture, x, y); + if (itemCapture) { + // Item_MouseMove(itemCapture, x, y); return; } - if (g_waitingForKey || g_editingField) - { + if (g_waitingForKey || g_editingField) { return; } // FIXME: this is the whole issue of focus vs. mouse over.. // need a better overall solution as i don't like going through everything twice - for (pass = 0; pass < 2; pass++) - { - for (i = 0; i < menu->itemCount; i++) - { + for (pass = 0; pass < 2; pass++) { + for (i = 0; i < menu->itemCount; i++) { // turn off focus each item // menu->items[i].window.flags &= ~WINDOW_HASFOCUS; - if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) - { + if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { continue; } - if (menu->items[i]->window.flags & WINDOW_INACTIVE) - { + if (menu->items[i]->window.flags & WINDOW_INACTIVE) { continue; } - if (menu->items[i]->disabled) - { + if (menu->items[i]->disabled) { continue; } // items can be enabled and disabled based on cvars - if (menu->items[i]->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_ENABLE)) - { + if (menu->items[i]->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_ENABLE)) { continue; } - if (menu->items[i]->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_SHOW)) - { + if (menu->items[i]->cvarFlags & (CVAR_SHOW | CVAR_HIDE) && !Item_EnableShowViaCvar(menu->items[i], CVAR_SHOW)) { continue; } - if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) - { - if (pass == 1) - { + if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { + if (pass == 1) { overItem = menu->items[i]; - if (overItem->type == ITEM_TYPE_TEXT && overItem->text) - { - if (!Rect_ContainsPoint(&overItem->window.rect, x, y)) - { + if (overItem->type == ITEM_TYPE_TEXT && overItem->text) { + if (!Rect_ContainsPoint(&overItem->window.rect, x, y)) { continue; } } // if we are over an item - if (IsVisible(overItem->window.flags)) - { + if (IsVisible(overItem->window.flags)) { // different one Item_MouseEnter(overItem, x, y); // Item_SetMouseOver(overItem, qtrue); // if item is not a decoration see if it can take focus - if (!focusSet) - { + if (!focusSet) { focusSet = Item_SetFocus(overItem, x, y); } } } - } else if (menu->items[i]->window.flags & WINDOW_MOUSEOVER) - { + } else if (menu->items[i]->window.flags & WINDOW_MOUSEOVER) { Item_MouseLeave(menu->items[i]); Item_SetMouseOver(menu->items[i], qfalse); } @@ -9433,35 +8272,28 @@ void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) Display_MouseMove ================= */ -qboolean Display_MouseMove(void *p, int x, int y) -{ +qboolean Display_MouseMove(void *p, int x, int y) { int i; - menuDef_t *menu = (menuDef_t *) p; + menuDef_t *menu = (menuDef_t *)p; - if (menu == NULL) - { - menu = Menu_GetFocused(); - if (menu) - { - if (menu->window.flags & WINDOW_POPUP) - { + if (menu == NULL) { + menu = Menu_GetFocused(); + if (menu) { + if (menu->window.flags & WINDOW_POPUP) { Menu_HandleMouseMove(menu, x, y); return qtrue; } } - for (i = 0; i < menuCount; i++) - { + for (i = 0; i < menuCount; i++) { Menu_HandleMouseMove(&Menus[i], x, y); } - } - else - { + } else { menu->window.rect.x += x; menu->window.rect.y += y; Menu_UpdatePosition(menu); } - return qtrue; + return qtrue; } /* @@ -9469,17 +8301,13 @@ qboolean Display_MouseMove(void *p, int x, int y) Menus_AnyFullScreenVisible ================= */ -qboolean Menus_AnyFullScreenVisible(void) -{ +qboolean Menus_AnyFullScreenVisible(void) { int i; - for (i = 0; i < menuCount; i++) - { - if (Menus[i].window.flags & WINDOW_VISIBLE && Menus[i].fullScreen) - { + for (i = 0; i < menuCount; i++) { + if (Menus[i].window.flags & WINDOW_VISIBLE && Menus[i].fullScreen) { return qtrue; } - } return qfalse; } @@ -9489,41 +8317,36 @@ qboolean Menus_AnyFullScreenVisible(void) Controls_SetConfig ================= */ -void Controls_SetConfig( void ) -{ - size_t i; +void Controls_SetConfig(void) { + size_t i; // iterate each command, get its numeric binding - for ( i=0; isetBinding( g_bindKeys[i][0], g_bindCommands[i] ); + for (i = 0; i < g_bindCount; i++) { + if (g_bindKeys[i][0] != -1) { + DC->setBinding(g_bindKeys[i][0], g_bindCommands[i]); - if ( g_bindKeys[i][1] != -1 ) - DC->setBinding( g_bindKeys[i][1], g_bindCommands[i] ); + if (g_bindKeys[i][1] != -1) + DC->setBinding(g_bindKeys[i][1], g_bindCommands[i]); } } } -void Controls_SetDefaults( void ) -{ - size_t i; +void Controls_SetDefaults(void) { + size_t i; - for ( i=0; iparent; - for (i=0;iitemCount;++i) - { - if (menu->items[i] == item) - { + menu = (menuDef_t *)item->parent; + for (i = 0; i < menu->itemCount; ++i) { + if (menu->items[i] == item) { continue; } @@ -9536,133 +8359,113 @@ void Item_Bind_Ungrey(itemDef_t *item) Item_Bind_HandleKey ================= */ -qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) -{ - int id; - int i; +qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) { + int id; + int i; menuDef_t *menu; - if (key == A_MOUSE1 && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && !g_waitingForKey) - { - if (down) - { + if (key == A_MOUSE1 && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && !g_waitingForKey) { + if (down) { g_waitingForKey = qtrue; g_bindItem = item; // Set all others in the menu to grey - menu = (menuDef_t *) item->parent; - for (i=0;iitemCount;++i) - { - if (menu->items[i] == item) - { + menu = (menuDef_t *)item->parent; + for (i = 0; i < menu->itemCount; ++i) { + if (menu->items[i] == item) { continue; } menu->items[i]->window.flags |= WINDOW_INACTIVE; } - } return qtrue; - } - else if (key == A_ENTER && !g_waitingForKey) - { - if (down) - { + } else if (key == A_ENTER && !g_waitingForKey) { + if (down) { g_waitingForKey = qtrue; g_bindItem = item; // Set all others in the menu to grey - menu = (menuDef_t *) item->parent; - for (i=0;iitemCount;++i) - { - if (menu->items[i] == item) - { + menu = (menuDef_t *)item->parent; + for (i = 0; i < menu->itemCount; ++i) { + if (menu->items[i] == item) { continue; } menu->items[i]->window.flags |= WINDOW_INACTIVE; } - } return qtrue; - } - else - { - if (!g_waitingForKey || g_bindItem == NULL) - { + } else { + if (!g_waitingForKey || g_bindItem == NULL) { return qfalse; } - if (key & K_CHAR_FLAG) - { + if (key & K_CHAR_FLAG) { return qtrue; } - switch (key) - { - case A_ESCAPE: - g_waitingForKey = qfalse; - Item_Bind_Ungrey(item); - return qtrue; + switch (key) { + case A_ESCAPE: + g_waitingForKey = qfalse; + Item_Bind_Ungrey(item); + return qtrue; - case A_BACKSPACE: - id = BindingIDFromName(item->cvar); - if ( id != -1 ) - { - if ( g_bindKeys[id][0] != -1 ) - DC->setBinding( g_bindKeys[id][0], "" ); + case A_BACKSPACE: + id = BindingIDFromName(item->cvar); + if (id != -1) { + if (g_bindKeys[id][0] != -1) + DC->setBinding(g_bindKeys[id][0], ""); - if ( g_bindKeys[id][1] != -1 ) - DC->setBinding( g_bindKeys[id][1], "" ); + if (g_bindKeys[id][1] != -1) + DC->setBinding(g_bindKeys[id][1], ""); - g_bindKeys[id][0] = -1; - g_bindKeys[id][1] = -1; - } - Controls_SetConfig(); - g_waitingForKey = qfalse; - g_bindItem = NULL; - Item_Bind_Ungrey(item); - return qtrue; - break; - case '`': - return qtrue; + g_bindKeys[id][0] = -1; + g_bindKeys[id][1] = -1; + } + Controls_SetConfig(); + g_waitingForKey = qfalse; + g_bindItem = NULL; + Item_Bind_Ungrey(item); + return qtrue; + break; + case '`': + return qtrue; } } // Is the same key being bound to something else? - if ( key != -1 ) { - size_t b; + if (key != -1) { + size_t b; - for ( b=0; bcvar ); + id = BindingIDFromName(item->cvar); - if ( id != -1 ) { - if ( key == -1 ) { - if ( g_bindKeys[id][0] != -1 ) { - DC->setBinding( g_bindKeys[id][0], "" ); + if (id != -1) { + if (key == -1) { + if (g_bindKeys[id][0] != -1) { + DC->setBinding(g_bindKeys[id][0], ""); g_bindKeys[id][0] = -1; } - if ( g_bindKeys[id][1] != -1 ) { - DC->setBinding( g_bindKeys[id][1], "" ); + if (g_bindKeys[id][1] != -1) { + DC->setBinding(g_bindKeys[id][1], ""); g_bindKeys[id][1] = -1; } - } - else if ( g_bindKeys[id][0] == -1 ) + } else if (g_bindKeys[id][0] == -1) g_bindKeys[id][0] = key; - else if ( g_bindKeys[id][0] != key && g_bindKeys[id][1] == -1 ) + else if (g_bindKeys[id][0] != key && g_bindKeys[id][1] == -1) g_bindKeys[id][1] = key; else { - DC->setBinding( g_bindKeys[id][0], "" ); - DC->setBinding( g_bindKeys[id][1], "" ); + DC->setBinding(g_bindKeys[id][0], ""); + DC->setBinding(g_bindKeys[id][1], ""); g_bindKeys[id][0] = key; g_bindKeys[id][1] = -1; } @@ -9680,31 +8483,25 @@ qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) Menu_SetNextCursorItem ================= */ -itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu) -{ +itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu) { qboolean wrapped = qfalse; int oldCursor = menu->cursorItem; - - if (menu->cursorItem == -1) - { + if (menu->cursorItem == -1) { menu->cursorItem = 0; wrapped = qtrue; } - while (menu->cursorItem < menu->itemCount) - { + while (menu->cursorItem < menu->itemCount) { menu->cursorItem++; - if (menu->cursorItem >= menu->itemCount && !wrapped) - { - wrapped = qtrue; - menu->cursorItem = 0; + if (menu->cursorItem >= menu->itemCount && !wrapped) { + wrapped = qtrue; + menu->cursorItem = 0; } - if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) - { + if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) { Menu_HandleMouseMove(menu, menu->items[menu->cursorItem]->window.rect.x + 1, menu->items[menu->cursorItem]->window.rect.y + 1); return menu->items[menu->cursorItem]; } @@ -9719,111 +8516,88 @@ itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu) Menu_SetPrevCursorItem ================= */ -itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu) -{ +itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu) { qboolean wrapped = qfalse; int oldCursor = menu->cursorItem; - if (menu->cursorItem < 0) - { - menu->cursorItem = menu->itemCount-1; + if (menu->cursorItem < 0) { + menu->cursorItem = menu->itemCount - 1; wrapped = qtrue; } - while (menu->cursorItem > -1) - { + while (menu->cursorItem > -1) { menu->cursorItem--; - if (menu->cursorItem < 0 ) - { - if (wrapped) - { + if (menu->cursorItem < 0) { + if (wrapped) { break; } wrapped = qtrue; - menu->cursorItem = menu->itemCount -1; + menu->cursorItem = menu->itemCount - 1; } - if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) - { + if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) { Menu_HandleMouseMove(menu, menu->items[menu->cursorItem]->window.rect.x + 1, menu->items[menu->cursorItem]->window.rect.y + 1); return menu->items[menu->cursorItem]; } } menu->cursorItem = oldCursor; return NULL; - } /* ================= Item_TextField_HandleKey ================= */ -qboolean Item_TextField_HandleKey(itemDef_t *item, int key) -{ +qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { char buff[1024]; int len; itemDef_t *newItem = NULL; - editFieldDef_t *editPtr = (editFieldDef_t*)item->typeData; + editFieldDef_t *editPtr = (editFieldDef_t *)item->typeData; - if (item->cvar) - { + if (item->cvar) { memset(buff, 0, sizeof(buff)); DC->getCVarString(item->cvar, buff, sizeof(buff)); len = strlen(buff); - if (editPtr->maxChars && len > editPtr->maxChars) - { + if (editPtr->maxChars && len > editPtr->maxChars) { len = editPtr->maxChars; } - if ( key & K_CHAR_FLAG ) - { + if (key & K_CHAR_FLAG) { key &= ~K_CHAR_FLAG; - - if (key == 'h' - 'a' + 1 ) - { // ctrl-h is backspace - if ( item->cursorPos > 0 ) - { - memmove( &buff[item->cursorPos - 1], &buff[item->cursorPos], len + 1 - item->cursorPos); + if (key == 'h' - 'a' + 1) { // ctrl-h is backspace + if (item->cursorPos > 0) { + memmove(&buff[item->cursorPos - 1], &buff[item->cursorPos], len + 1 - item->cursorPos); item->cursorPos--; - if (item->cursorPos < editPtr->paintOffset) - { + if (item->cursorPos < editPtr->paintOffset) { editPtr->paintOffset--; } } DC->setCVar(item->cvar, buff); - return qtrue; + return qtrue; } // // ignore any non printable chars // - if ( key < 32 || !item->cvar) - { - return qtrue; - } + if (key < 32 || !item->cvar) { + return qtrue; + } - if (item->type == ITEM_TYPE_NUMERICFIELD) - { - if (key < '0' || key > '9') - { + if (item->type == ITEM_TYPE_NUMERICFIELD) { + if (key < '0' || key > '9') { return qfalse; } } - if (!DC->getOverstrikeMode()) - { - if (( len == MAX_EDITFIELD - 1 ) || (editPtr->maxChars && len >= editPtr->maxChars)) - { + if (!DC->getOverstrikeMode()) { + if ((len == MAX_EDITFIELD - 1) || (editPtr->maxChars && len >= editPtr->maxChars)) { return qtrue; } - memmove( &buff[item->cursorPos + 1], &buff[item->cursorPos], len + 1 - item->cursorPos ); - } - else - { - if (editPtr->maxChars && item->cursorPos >= editPtr->maxChars) - { + memmove(&buff[item->cursorPos + 1], &buff[item->cursorPos], len + 1 - item->cursorPos); + } else { + if (editPtr->maxChars && item->cursorPos >= editPtr->maxChars) { return qtrue; } } @@ -9832,117 +8606,93 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) DC->setCVar(item->cvar, buff); - if (item->cursorPos < len + 1) - { + if (item->cursorPos < len + 1) { item->cursorPos++; - if (editPtr->maxPaintChars && item->cursorPos > editPtr->maxPaintChars) - { + if (editPtr->maxPaintChars && item->cursorPos > editPtr->maxPaintChars) { editPtr->paintOffset++; } } - } - else - { + } else { - if ( key == A_DELETE || key == A_KP_PERIOD ) - { - if ( item->cursorPos < len ) - { - memmove( buff + item->cursorPos, buff + item->cursorPos + 1, len - item->cursorPos); + if (key == A_DELETE || key == A_KP_PERIOD) { + if (item->cursorPos < len) { + memmove(buff + item->cursorPos, buff + item->cursorPos + 1, len - item->cursorPos); DC->setCVar(item->cvar, buff); } return qtrue; } - if ( key == A_CURSOR_RIGHT || key == A_KP_6 ) - { - if (editPtr->maxPaintChars && item->cursorPos >= editPtr->maxPaintChars && item->cursorPos < len) - { + if (key == A_CURSOR_RIGHT || key == A_KP_6) { + if (editPtr->maxPaintChars && item->cursorPos >= editPtr->maxPaintChars && item->cursorPos < len) { item->cursorPos++; editPtr->paintOffset++; return qtrue; } - if (item->cursorPos < len) - { + if (item->cursorPos < len) { item->cursorPos++; } return qtrue; } - if ( key == A_CURSOR_LEFT|| key == A_KP_4 ) - { - if ( item->cursorPos > 0 ) - { + if (key == A_CURSOR_LEFT || key == A_KP_4) { + if (item->cursorPos > 0) { item->cursorPos--; } - if (item->cursorPos < editPtr->paintOffset) - { + if (item->cursorPos < editPtr->paintOffset) { editPtr->paintOffset--; } return qtrue; } - if ( key == A_HOME || key == A_KP_7) - { + if (key == A_HOME || key == A_KP_7) { item->cursorPos = 0; editPtr->paintOffset = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) - { + if (key == A_END || key == A_KP_1) { item->cursorPos = len; - if(item->cursorPos > editPtr->maxPaintChars) - { + if (item->cursorPos > editPtr->maxPaintChars) { editPtr->paintOffset = len - editPtr->maxPaintChars; } return qtrue; } - if ( key == A_INSERT || key == A_KP_0 ) - { + if (key == A_INSERT || key == A_KP_0) { DC->setOverstrikeMode((qboolean)(!DC->getOverstrikeMode())); return qtrue; } } - if (key == A_TAB || key == A_CURSOR_DOWN || key == A_KP_2) - { - newItem = Menu_SetNextCursorItem((menuDef_t *) item->parent); - if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) - { + if (key == A_TAB || key == A_CURSOR_DOWN || key == A_KP_2) { + newItem = Menu_SetNextCursorItem((menuDef_t *)item->parent); + if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) { g_editItem = newItem; } } - if (key == A_CURSOR_UP || key == A_KP_8) - { - newItem = Menu_SetPrevCursorItem((menuDef_t *) item->parent); - if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) - { + if (key == A_CURSOR_UP || key == A_KP_8) { + newItem = Menu_SetPrevCursorItem((menuDef_t *)item->parent); + if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) { g_editItem = newItem; } } - if ( key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE) - { + if (key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE) { return qfalse; } return qtrue; } return qfalse; - } -static void Scroll_TextScroll_AutoFunc (void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; +static void Scroll_TextScroll_AutoFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; - if (DC->realTime > si->nextScrollTime) - { + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -9950,40 +8700,33 @@ static void Scroll_TextScroll_AutoFunc (void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } } -static void Scroll_TextScroll_ThumbFunc(void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; - rectDef_t r; - int pos; - int max; +static void Scroll_TextScroll_ThumbFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; + rectDef_t r; + int pos; + int max; - textScrollDef_t *scrollPtr = (textScrollDef_t*)si->item->typeData; + textScrollDef_t *scrollPtr = (textScrollDef_t *)si->item->typeData; - if (DC->cursory != si->yStart) - { + if (DC->cursory != si->yStart) { r.x = si->item->window.rect.x + si->item->window.rect.w - SCROLLBAR_SIZE - 1; r.y = si->item->window.rect.y + SCROLLBAR_SIZE + 1; - r.h = si->item->window.rect.h - (SCROLLBAR_SIZE*2) - 2; + r.h = si->item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; r.w = SCROLLBAR_SIZE; max = Item_TextScroll_MaxScroll(si->item); // - pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * max / (r.h - SCROLLBAR_SIZE); - if (pos < 0) - { + pos = (DC->cursory - r.y - SCROLLBAR_SIZE / 2) * max / (r.h - SCROLLBAR_SIZE); + if (pos < 0) { pos = 0; - } - else if (pos > max) - { + } else if (pos > max) { pos = max; } @@ -9991,8 +8734,7 @@ static void Scroll_TextScroll_ThumbFunc(void *p) si->yStart = DC->cursory; } - if (DC->realTime > si->nextScrollTime) - { + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -10000,11 +8742,9 @@ static void Scroll_TextScroll_ThumbFunc(void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } @@ -10015,44 +8755,31 @@ static void Scroll_TextScroll_ThumbFunc(void *p) Menu_OverActiveItem ================= */ -static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) -{ - if (menu && menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED)) - { - if (Rect_ContainsPoint(&menu->window.rect, x, y)) - { +static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) { + if (menu && menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED)) { + if (Rect_ContainsPoint(&menu->window.rect, x, y)) { int i; - for (i = 0; i < menu->itemCount; i++) - { - // turn off focus each item - // menu->items[i].window.flags &= ~WINDOW_HASFOCUS; + for (i = 0; i < menu->itemCount; i++) { + // turn off focus each item + // menu->items[i].window.flags &= ~WINDOW_HASFOCUS; - if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) - { + if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { continue; } - if (menu->items[i]->window.flags & WINDOW_DECORATION) - { + if (menu->items[i]->window.flags & WINDOW_DECORATION) { continue; } - if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) - { + if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { itemDef_t *overItem = menu->items[i]; - if (overItem->type == ITEM_TYPE_TEXT && overItem->text) - { - if (Rect_ContainsPoint(&overItem->window.rect, x, y)) - { + if (overItem->type == ITEM_TYPE_TEXT && overItem->text) { + if (Rect_ContainsPoint(&overItem->window.rect, x, y)) { return qtrue; - } - else - { + } else { continue; } - } - else - { + } else { return qtrue; } } @@ -10067,14 +8794,11 @@ static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) Display_VisibleMenuCount ================= */ -int Display_VisibleMenuCount(void) -{ +int Display_VisibleMenuCount(void) { int i, count; count = 0; - for (i = 0; i < menuCount; i++) - { - if (Menus[i].window.flags & (WINDOW_FORCED | WINDOW_VISIBLE)) - { + for (i = 0; i < menuCount; i++) { + if (Menus[i].window.flags & (WINDOW_FORCED | WINDOW_VISIBLE)) { count++; } } @@ -10086,10 +8810,8 @@ int Display_VisibleMenuCount(void) Window_CloseCinematic ================= */ -static void Window_CloseCinematic(windowDef_t *window) -{ - if (window->style == WINDOW_STYLE_CINEMATIC && window->cinematic >= 0) - { +static void Window_CloseCinematic(windowDef_t *window) { + if (window->style == WINDOW_STYLE_CINEMATIC && window->cinematic >= 0) { DC->stopCinematic(window->cinematic); window->cinematic = -1; } @@ -10099,18 +8821,14 @@ static void Window_CloseCinematic(windowDef_t *window) Menu_CloseCinematics ================= */ -static void Menu_CloseCinematics(menuDef_t *menu) -{ - if (menu) - { +static void Menu_CloseCinematics(menuDef_t *menu) { + if (menu) { int i; Window_CloseCinematic(&menu->window); - for (i = 0; i < menu->itemCount; i++) - { + for (i = 0; i < menu->itemCount; i++) { Window_CloseCinematic(&menu->items[i]->window); - if (menu->items[i]->type == ITEM_TYPE_OWNERDRAW) - { - DC->stopCinematic(0-menu->items[i]->window.ownerDraw); + if (menu->items[i]->type == ITEM_TYPE_OWNERDRAW) { + DC->stopCinematic(0 - menu->items[i]->window.ownerDraw); } } } @@ -10121,11 +8839,9 @@ static void Menu_CloseCinematics(menuDef_t *menu) Display_CloseCinematics ================= */ -static void Display_CloseCinematics() -{ +static void Display_CloseCinematics() { int i; - for (i = 0; i < menuCount; i++) - { + for (i = 0; i < menuCount; i++) { Menu_CloseCinematics(&Menus[i]); } } @@ -10135,36 +8851,29 @@ static void Display_CloseCinematics() Menus_HandleOOBClick ================= */ -void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) -{ - if (menu) - { +void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) { + if (menu) { int i; // basically the behaviour we are looking for is if there are windows in the stack.. see if // the cursor is within any of them.. if not close them otherwise activate them and pass the // key on.. force a mouse move to activate focus and script stuff - if (down && menu->window.flags & WINDOW_OOB_CLICK) - { + if (down && menu->window.flags & WINDOW_OOB_CLICK) { Menu_RunCloseScript(menu); menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); } - for (i = 0; i < menuCount; i++) - { - if (Menu_OverActiveItem(&Menus[i], DC->cursorx, DC->cursory)) - { + for (i = 0; i < menuCount; i++) { + if (Menu_OverActiveItem(&Menus[i], DC->cursorx, DC->cursory)) { Menu_RunCloseScript(menu); menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); - // Menus_Activate(&Menus[i]); + // Menus_Activate(&Menus[i]); Menu_HandleMouseMove(&Menus[i], DC->cursorx, DC->cursory); Menu_HandleKey(&Menus[i], key, down); } } - if (Display_VisibleMenuCount() == 0) - { - if (DC->Pause) - { + if (Display_VisibleMenuCount() == 0) { + if (DC->Pause) { DC->Pause(qfalse); } } @@ -10177,169 +8886,127 @@ void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) Item_StopCapture ================= */ -void Item_StopCapture(itemDef_t *item) -{ - -} +void Item_StopCapture(itemDef_t *item) {} /* ================= Item_ListBox_HandleKey ================= */ -qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) -{ - listBoxDef_t *listPtr = (listBoxDef_t*)item->typeData; +qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) { + listBoxDef_t *listPtr = (listBoxDef_t *)item->typeData; int count = DC->feederCount(item->special); int max, viewmax; - if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) - { + if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) { max = Item_ListBox_MaxScroll(item); - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (item->window.flags & WINDOW_HORIZONTAL) { viewmax = (item->window.rect.w / listPtr->elementWidth); - if ( key == A_CURSOR_LEFT || key == A_KP_4 ) - { - if (!listPtr->notselectable) - { + if (key == A_CURSOR_LEFT || key == A_KP_4) { + if (!listPtr->notselectable) { listPtr->cursorPos--; - if (listPtr->cursorPos < 0) - { + if (listPtr->cursorPos < 0) { listPtr->cursorPos = 0; } - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos--; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; } } return qtrue; } - if ( key == A_CURSOR_RIGHT || key == A_KP_6 ) - { - if (!listPtr->notselectable) - { + if (key == A_CURSOR_RIGHT || key == A_KP_6) { + if (!listPtr->notselectable) { listPtr->cursorPos++; - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= count) - { - listPtr->cursorPos = count-1; + if (listPtr->cursorPos >= count) { + listPtr->cursorPos = count - 1; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos++; - if (listPtr->startPos >= count) - { - listPtr->startPos = count-1; + if (listPtr->startPos >= count) { + listPtr->startPos = count - 1; } } return qtrue; } - } - else - { + } else { viewmax = (item->window.rect.h / listPtr->elementHeight); - if ( key == A_CURSOR_UP || key == A_KP_8 ) - { - if (!listPtr->notselectable) - { + if (key == A_CURSOR_UP || key == A_KP_8) { + if (!listPtr->notselectable) { listPtr->cursorPos--; - if (listPtr->cursorPos < 0) - { + if (listPtr->cursorPos < 0) { listPtr->cursorPos = 0; } - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos--; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; } } return qtrue; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 ) - { - if (!listPtr->notselectable) - { + if (key == A_CURSOR_DOWN || key == A_KP_2) { + if (!listPtr->notselectable) { listPtr->cursorPos++; - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= count) - { - listPtr->cursorPos = count-1; + if (listPtr->cursorPos >= count) { + listPtr->cursorPos = count - 1; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos++; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; } } return qtrue; } - //Raz: Added - if ( key == A_MWHEELUP ) - { + // Raz: Added + if (key == A_MWHEELUP) { listPtr->startPos -= ((int)item->special == FEEDER_Q3HEADS) ? viewmax : 1; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -10347,11 +9014,9 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qtrue; } - if ( key == A_MWHEELDOWN ) - { + if (key == A_MWHEELDOWN) { listPtr->startPos += ((int)item->special == FEEDER_Q3HEADS) ? viewmax : 1; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -10361,52 +9026,35 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } } // mouse hit - if (key == A_MOUSE1 || key == A_MOUSE2) - { - if (item->window.flags & WINDOW_LB_LEFTARROW) - { - listPtr->startPos--; - if (listPtr->startPos < 0) - { + if (key == A_MOUSE1 || key == A_MOUSE2) { + if (item->window.flags & WINDOW_LB_LEFTARROW) { + listPtr->startPos--; + if (listPtr->startPos < 0) { listPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_RIGHTARROW) - { + } else if (item->window.flags & WINDOW_LB_RIGHTARROW) { // one down listPtr->startPos++; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_PGUP) - { + } else if (item->window.flags & WINDOW_LB_PGUP) { // page up listPtr->startPos -= viewmax; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_PGDN) - { + } else if (item->window.flags & WINDOW_LB_PGDN) { // page down listPtr->startPos += viewmax; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_THUMB) - { + } else if (item->window.flags & WINDOW_LB_THUMB) { // Display_SetCaptureItem(item); - } - else - { + } else { // select an item - if (DC->realTime < lastListBoxClickTime && listPtr->doubleClick) - { + if (DC->realTime < lastListBoxClickTime && listPtr->doubleClick) { Item_RunScript(item, listPtr->doubleClick); } lastListBoxClickTime = DC->realTime + DOUBLE_CLICK_DELAY; @@ -10415,75 +9063,57 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } return qtrue; } - if ( key == A_HOME || key == A_KP_7) - { + if (key == A_HOME || key == A_KP_7) { // home listPtr->startPos = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) - { + if (key == A_END || key == A_KP_1) { // end listPtr->startPos = max; return qtrue; } - if (key == A_PAGE_UP || key == A_KP_9 ) - { + if (key == A_PAGE_UP || key == A_KP_9) { // page up - if (!listPtr->notselectable) - { + if (!listPtr->notselectable) { listPtr->cursorPos -= viewmax; - if (listPtr->cursorPos < 0) - { + if (listPtr->cursorPos < 0) { listPtr->cursorPos = 0; } - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos -= viewmax; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; } } return qtrue; } - if ( key == A_PAGE_DOWN || key == A_KP_3 ) - { + if (key == A_PAGE_DOWN || key == A_KP_3) { // page down - if (!listPtr->notselectable) - { + if (!listPtr->notselectable) { listPtr->cursorPos += viewmax; - if (listPtr->cursorPos < listPtr->startPos) - { + if (listPtr->cursorPos < listPtr->startPos) { listPtr->startPos = listPtr->cursorPos; } - if (listPtr->cursorPos >= count) - { - listPtr->cursorPos = count-1; + if (listPtr->cursorPos >= count) { + listPtr->cursorPos = count - 1; } - if (listPtr->cursorPos >= listPtr->startPos + viewmax) - { + if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, item); - } - else - { + } else { listPtr->startPos += viewmax; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; } } @@ -10498,11 +9128,9 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea Scroll_ListBox_AutoFunc ================= */ -static void Scroll_ListBox_AutoFunc(void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; - if (DC->realTime > si->nextScrollTime) - { +static void Scroll_ListBox_AutoFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -10510,11 +9138,9 @@ static void Scroll_ListBox_AutoFunc(void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } @@ -10525,61 +9151,49 @@ static void Scroll_ListBox_AutoFunc(void *p) Scroll_ListBox_ThumbFunc ================= */ -static void Scroll_ListBox_ThumbFunc(void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; +static void Scroll_ListBox_ThumbFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; rectDef_t r; int pos, max; - listBoxDef_t *listPtr = (listBoxDef_t*)si->item->typeData; - if (si->item->window.flags & WINDOW_HORIZONTAL) - { - if (DC->cursorx == si->xStart) - { + listBoxDef_t *listPtr = (listBoxDef_t *)si->item->typeData; + if (si->item->window.flags & WINDOW_HORIZONTAL) { + if (DC->cursorx == si->xStart) { return; } r.x = si->item->window.rect.x + SCROLLBAR_SIZE + 1; r.y = si->item->window.rect.y + si->item->window.rect.h - SCROLLBAR_SIZE - 1; r.h = SCROLLBAR_SIZE; - r.w = si->item->window.rect.w - (SCROLLBAR_SIZE*2) - 2; + r.w = si->item->window.rect.w - (SCROLLBAR_SIZE * 2) - 2; max = Item_ListBox_MaxScroll(si->item); // - pos = (DC->cursorx - r.x - SCROLLBAR_SIZE/2) * max / (r.w - SCROLLBAR_SIZE); - if (pos < 0) - { + pos = (DC->cursorx - r.x - SCROLLBAR_SIZE / 2) * max / (r.w - SCROLLBAR_SIZE); + if (pos < 0) { pos = 0; - } - else if (pos > max) - { + } else if (pos > max) { pos = max; } listPtr->startPos = pos; si->xStart = DC->cursorx; - } - else if (DC->cursory != si->yStart) - { + } else if (DC->cursory != si->yStart) { r.x = si->item->window.rect.x + si->item->window.rect.w - SCROLLBAR_SIZE - 1; r.y = si->item->window.rect.y + SCROLLBAR_SIZE + 1; - r.h = si->item->window.rect.h - (SCROLLBAR_SIZE*2) - 2; + r.h = si->item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; r.w = SCROLLBAR_SIZE; max = Item_ListBox_MaxScroll(si->item); // - pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * max / (r.h - SCROLLBAR_SIZE); - if (pos < 0) - { + pos = (DC->cursory - r.y - SCROLLBAR_SIZE / 2) * max / (r.h - SCROLLBAR_SIZE); + if (pos < 0) { pos = 0; - } - else if (pos > max) - { + } else if (pos > max) { pos = max; } listPtr->startPos = pos; si->yStart = DC->cursory; } - if (DC->realTime > si->nextScrollTime) - { + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -10587,11 +9201,9 @@ static void Scroll_ListBox_ThumbFunc(void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } @@ -10602,8 +9214,7 @@ static void Scroll_ListBox_ThumbFunc(void *p) Item_Slider_OverSlider ================= */ -int Item_Slider_OverSlider(itemDef_t *item, float x, float y) -{ +int Item_Slider_OverSlider(itemDef_t *item, float x, float y) { rectDef_t r; r.x = Item_Slider_ThumbPosition(item) - (SLIDER_THUMB_WIDTH / 2); @@ -10611,8 +9222,7 @@ int Item_Slider_OverSlider(itemDef_t *item, float x, float y) r.w = SLIDER_THUMB_WIDTH; r.h = SLIDER_THUMB_HEIGHT; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } return 0; @@ -10623,29 +9233,22 @@ int Item_Slider_OverSlider(itemDef_t *item, float x, float y) Scroll_Slider_ThumbFunc ================= */ -static void Scroll_Slider_ThumbFunc(void *p) -{ +static void Scroll_Slider_ThumbFunc(void *p) { float x, value, cursorx; - scrollInfo_t *si = (scrollInfo_t*)p; - editFieldDef_t *editDef = (struct editFieldDef_s *) si->item->typeData; + scrollInfo_t *si = (scrollInfo_t *)p; + editFieldDef_t *editDef = (struct editFieldDef_s *)si->item->typeData; - if (si->item->text) - { + if (si->item->text) { x = si->item->textRect.x + si->item->textRect.w + 8; - } - else - { + } else { x = si->item->window.rect.x; } cursorx = DC->cursorx; - if (cursorx < x) - { + if (cursorx < x) { cursorx = x; - } - else if (cursorx > x + SLIDER_WIDTH) - { + } else if (cursorx > x + SLIDER_WIDTH) { cursorx = x + SLIDER_WIDTH; } value = cursorx - x; @@ -10659,83 +9262,72 @@ static void Scroll_Slider_ThumbFunc(void *p) Item_StartCapture ================= */ -void Item_StartCapture(itemDef_t *item, int key) -{ +void Item_StartCapture(itemDef_t *item, int key) { int flags; - switch (item->type) - { - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - - case ITEM_TYPE_LISTBOX: - { - flags = Item_ListBox_OverLB(item, DC->cursorx, DC->cursory); - if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) - { - scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; - scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - scrollInfo.adjustValue = SCROLL_TIME_START; - scrollInfo.scrollKey = key; - scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; - scrollInfo.item = item; - captureData = &scrollInfo; - captureFunc = &Scroll_ListBox_AutoFunc; - itemCapture = item; - } - else if (flags & WINDOW_LB_THUMB) - { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_ListBox_ThumbFunc; - itemCapture = item; - } - break; + switch (item->type) { + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + + case ITEM_TYPE_LISTBOX: { + flags = Item_ListBox_OverLB(item, DC->cursorx, DC->cursory); + if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) { + scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; + scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; + scrollInfo.adjustValue = SCROLL_TIME_START; + scrollInfo.scrollKey = key; + scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; + scrollInfo.item = item; + captureData = &scrollInfo; + captureFunc = &Scroll_ListBox_AutoFunc; + itemCapture = item; + } else if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_ListBox_ThumbFunc; + itemCapture = item; } + break; + } - case ITEM_TYPE_TEXTSCROLL: - flags = Item_TextScroll_OverLB (item, DC->cursorx, DC->cursory); - if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) - { - scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; - scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - scrollInfo.adjustValue = SCROLL_TIME_START; - scrollInfo.scrollKey = key; - scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; - scrollInfo.item = item; - captureData = &scrollInfo; - captureFunc = &Scroll_TextScroll_AutoFunc; - itemCapture = item; - } - else if (flags & WINDOW_LB_THUMB) - { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_TextScroll_ThumbFunc; - itemCapture = item; - } - break; + case ITEM_TYPE_TEXTSCROLL: + flags = Item_TextScroll_OverLB(item, DC->cursorx, DC->cursory); + if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) { + scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; + scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; + scrollInfo.adjustValue = SCROLL_TIME_START; + scrollInfo.scrollKey = key; + scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; + scrollInfo.item = item; + captureData = &scrollInfo; + captureFunc = &Scroll_TextScroll_AutoFunc; + itemCapture = item; + } else if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_TextScroll_ThumbFunc; + itemCapture = item; + } + break; - case ITEM_TYPE_SLIDER: - { - flags = Item_Slider_OverSlider(item, DC->cursorx, DC->cursory); - if (flags & WINDOW_LB_THUMB) - { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_Slider_ThumbFunc; - itemCapture = item; - } - break; + case ITEM_TYPE_SLIDER: { + flags = Item_Slider_OverSlider(item, DC->cursorx, DC->cursory); + if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_Slider_ThumbFunc; + itemCapture = item; } + break; + } } } @@ -10744,19 +9336,15 @@ void Item_StartCapture(itemDef_t *item, int key) Item_YesNo_HandleKey ================= */ -qboolean Item_YesNo_HandleKey(itemDef_t *item, int key) -{ - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) - { - if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) - { +qboolean Item_YesNo_HandleKey(itemDef_t *item, int key) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) { + if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { DC->setCVar(item->cvar, va("%i", !DC->getCVarValue(item->cvar))); return qtrue; } } return qfalse; - } /* @@ -10764,39 +9352,28 @@ qboolean Item_YesNo_HandleKey(itemDef_t *item, int key) Item_Multi_FindCvarByValue ================= */ -int Item_Multi_FindCvarByValue(itemDef_t *item) -{ +int Item_Multi_FindCvarByValue(itemDef_t *item) { char buff[1024]; float value = 0; int i; - multiDef_t *multiPtr = (multiDef_t*)item->typeData; - if (multiPtr) - { - if (multiPtr->strDef) - { + multiDef_t *multiPtr = (multiDef_t *)item->typeData; + if (multiPtr) { + if (multiPtr->strDef) { DC->getCVarString(item->cvar, buff, sizeof(buff)); - } - else - { + } else { value = DC->getCVarValue(item->cvar); } - for (i = 0; i < multiPtr->count; i++) - { - if (multiPtr->strDef) - { - if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->strDef) { + if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) { + return i; + } + } else { + if (multiPtr->cvarValue[i] == value) { return i; } } - else - { - if (multiPtr->cvarValue[i] == value) - { - return i; - } - } - } + } } return 0; } @@ -10806,30 +9383,24 @@ int Item_Multi_FindCvarByValue(itemDef_t *item) Item_Multi_CountSettings ================= */ -int Item_Multi_CountSettings(itemDef_t *item) -{ - multiDef_t *multiPtr = (multiDef_t*)item->typeData; - if (multiPtr == NULL) - { +int Item_Multi_CountSettings(itemDef_t *item) { + multiDef_t *multiPtr = (multiDef_t *)item->typeData; + if (multiPtr == NULL) { return 0; } return multiPtr->count; } - - /* ================= Item_OwnerDraw_HandleKey ================= */ -qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) -{ - if (item && DC->ownerDrawHandleKey) - { +qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) { + if (item && DC->ownerDrawHandleKey) { return DC->ownerDrawHandleKey(item->window.ownerDraw, item->window.ownerDrawFlags, &item->special, key); - } - return qfalse; + } + return qfalse; } /* @@ -10837,27 +9408,19 @@ qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) Item_Text_HandleKey ================= */ -qboolean Item_Text_HandleKey(itemDef_t *item, int key) -{ +qboolean Item_Text_HandleKey(itemDef_t *item, int key) { if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_AUTOWRAPPED) - { - if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) - { - if (key == A_MOUSE2) - { + if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { + if (key == A_MOUSE2) { item->cursorPos--; - if ( item->cursorPos < 0 ) - { + if (item->cursorPos < 0) { item->cursorPos = 0; } - } - else if (item->special) - { + } else if (item->special) { item->cursorPos++; - if ( item->cursorPos >= item->value ) - { + if (item->cursorPos >= item->value) { item->cursorPos = 0; } } @@ -10868,88 +9431,63 @@ qboolean Item_Text_HandleKey(itemDef_t *item, int key) return qfalse; } - /* ================= Item_Multi_HandleKey ================= */ -qboolean Item_Multi_HandleKey(itemDef_t *item, int key) -{ - multiDef_t *multiPtr = (multiDef_t*)item->typeData; - if (multiPtr) - { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS) - { - //Raz: Scroll on multi buttons! +qboolean Item_Multi_HandleKey(itemDef_t *item, int key) { + multiDef_t *multiPtr = (multiDef_t *)item->typeData; + if (multiPtr) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS) { + // Raz: Scroll on multi buttons! if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3 || key == A_MWHEELDOWN || key == A_MWHEELUP) - //if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) + // if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { - if (item->cvar) - { + if (item->cvar) { int current = Item_Multi_FindCvarByValue(item); int max = Item_Multi_CountSettings(item); - if (key == A_MOUSE2 || key == A_MWHEELDOWN) - { + if (key == A_MOUSE2 || key == A_MWHEELDOWN) { current--; - if ( current < 0 ) - { - current = max-1; + if (current < 0) { + current = max - 1; } - } - else - { + } else { current++; - if ( current >= max ) - { + if (current >= max) { current = 0; } } - if (multiPtr->strDef) - { + if (multiPtr->strDef) { DC->setCVar(item->cvar, multiPtr->cvarStr[current]); - } - else - { + } else { float value = multiPtr->cvarValue[current]; - if (((float)((int) value)) == value) - { - DC->setCVar(item->cvar, va("%i", (int) value )); - } - else - { - DC->setCVar(item->cvar, va("%f", value )); + if (((float)((int)value)) == value) { + DC->setCVar(item->cvar, va("%i", (int)value)); + } else { + DC->setCVar(item->cvar, va("%f", value)); } } - if (item->special) - {//its a feeder? + if (item->special) { // its a feeder? DC->feederSelection(item->special, current, item); } - } - else - { + } else { int max = Item_Multi_CountSettings(item); - if (key == A_MOUSE2 || key == A_MWHEELDOWN) - { + if (key == A_MOUSE2 || key == A_MWHEELDOWN) { item->value--; - if ( item->value < 0 ) - { + if (item->value < 0) { item->value = max; } - } - else - { + } else { item->value++; - if ( item->value >= max ) - { + if (item->value >= max) { item->value = 0; } } - if (item->special) - {//its a feeder? + if (item->special) { // its a feeder? DC->feederSelection(item->special, item->value, item); } } @@ -10966,29 +9504,22 @@ qboolean Item_Multi_HandleKey(itemDef_t *item, int key) Item_Slider_HandleKey ================= */ -qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) -{ - //DC->Print("slider handle key\n"); -//JLF MPMOVED +qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) { + // DC->Print("slider handle key\n"); + // JLF MPMOVED float x, value, width, work; - if (item->window.flags & WINDOW_HASFOCUS && item->cvar && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { + if (item->window.flags & WINDOW_HASFOCUS && item->cvar && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { - if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) - { - editFieldDef_t *editDef = (editFieldDef_s *) item->typeData; - if (editDef) - { + if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { + editFieldDef_t *editDef = (editFieldDef_s *)item->typeData; + if (editDef) { rectDef_t testRect; width = SLIDER_WIDTH; - if (item->text) - { + if (item->text) { x = item->textRect.x + item->textRect.w + 8; - } - else - { + } else { x = item->window.rect.x; } @@ -10996,11 +9527,10 @@ qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) testRect.x = x; value = (float)SLIDER_THUMB_WIDTH / 2; testRect.x -= value; - //DC->Print("slider x: %f\n", testRect.x); + // DC->Print("slider x: %f\n", testRect.x); testRect.w = (SLIDER_WIDTH + (float)SLIDER_THUMB_WIDTH / 2); - //DC->Print("slider w: %f\n", testRect.w); - if (Rect_ContainsPoint(&testRect, DC->cursorx, DC->cursory)) - { + // DC->Print("slider w: %f\n", testRect.w); + if (Rect_ContainsPoint(&testRect, DC->cursorx, DC->cursory)) { work = DC->cursorx - x; value = work / width; value *= (editDef->maxVal - editDef->minVal); @@ -11014,7 +9544,7 @@ qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) } } - //DC->Print("slider handle key exit\n"); + // DC->Print("slider handle key exit\n"); return qfalse; } @@ -11023,145 +9553,126 @@ qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) Item_HandleKey ================= */ -qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) -{ +qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) { - if (itemCapture) - { + if (itemCapture) { Item_StopCapture(itemCapture); itemCapture = NULL; captureFunc = NULL; captureData = NULL; - } - else - { - if (down && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) - { + } else { + if (down && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) { Item_StartCapture(item, key); } } - if (!down) - { + if (!down) { return qfalse; } - switch (item->type) - { - case ITEM_TYPE_BUTTON: - return qfalse; - break; - case ITEM_TYPE_RADIOBUTTON: - return qfalse; - break; - case ITEM_TYPE_CHECKBOX: - return qfalse; - break; - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - //return Item_TextField_HandleKey(item, key); - return qfalse; - break; - case ITEM_TYPE_COMBO: - return qfalse; - break; - case ITEM_TYPE_LISTBOX: - return Item_ListBox_HandleKey(item, key, down, qfalse); - break; - case ITEM_TYPE_TEXTSCROLL: - return Item_TextScroll_HandleKey(item, key, down, qfalse); - break; - case ITEM_TYPE_YESNO: - return Item_YesNo_HandleKey(item, key); - break; - case ITEM_TYPE_MULTI: - return Item_Multi_HandleKey(item, key); - break; - case ITEM_TYPE_OWNERDRAW: - return Item_OwnerDraw_HandleKey(item, key); - break; - case ITEM_TYPE_BIND: - return Item_Bind_HandleKey(item, key, down); - break; - case ITEM_TYPE_SLIDER: - return Item_Slider_HandleKey(item, key, down); - break; -//JLF MPMOVED - case ITEM_TYPE_TEXT: - return Item_Text_HandleKey(item, key); - break; - default: - return qfalse; + switch (item->type) { + case ITEM_TYPE_BUTTON: + return qfalse; + break; + case ITEM_TYPE_RADIOBUTTON: + return qfalse; + break; + case ITEM_TYPE_CHECKBOX: + return qfalse; + break; + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + // return Item_TextField_HandleKey(item, key); + return qfalse; + break; + case ITEM_TYPE_COMBO: + return qfalse; + break; + case ITEM_TYPE_LISTBOX: + return Item_ListBox_HandleKey(item, key, down, qfalse); + break; + case ITEM_TYPE_TEXTSCROLL: + return Item_TextScroll_HandleKey(item, key, down, qfalse); + break; + case ITEM_TYPE_YESNO: + return Item_YesNo_HandleKey(item, key); + break; + case ITEM_TYPE_MULTI: + return Item_Multi_HandleKey(item, key); + break; + case ITEM_TYPE_OWNERDRAW: + return Item_OwnerDraw_HandleKey(item, key); + break; + case ITEM_TYPE_BIND: + return Item_Bind_HandleKey(item, key, down); + break; + case ITEM_TYPE_SLIDER: + return Item_Slider_HandleKey(item, key, down); + break; + // JLF MPMOVED + case ITEM_TYPE_TEXT: + return Item_Text_HandleKey(item, key); + break; + default: + return qfalse; break; } - //return qfalse; + // return qfalse; } - - -//JLFACCEPT MPMOVED +// JLFACCEPT MPMOVED /* ----------------------------------------- Item_HandleAccept If Item has an accept script, run it. ------------------------------------------- */ -qboolean Item_HandleAccept(itemDef_t * item) -{ - if (item->accept) - { +qboolean Item_HandleAccept(itemDef_t *item) { + if (item->accept) { Item_RunScript(item, item->accept); return qtrue; } return qfalse; } - -//JLFDPADSCRIPT MPMOVED +// JLFDPADSCRIPT MPMOVED /* ----------------------------------------- Item_HandleSelectionNext If Item has an selectionNext script, run it. ------------------------------------------- */ -qboolean Item_HandleSelectionNext(itemDef_t * item) -{ - if (item->selectionNext) - { +qboolean Item_HandleSelectionNext(itemDef_t *item) { + if (item->selectionNext) { Item_RunScript(item, item->selectionNext); return qtrue; } return qfalse; } -//JLFDPADSCRIPT MPMOVED +// JLFDPADSCRIPT MPMOVED /* ----------------------------------------- Item_HandleSelectionPrev If Item has an selectionPrev script, run it. ------------------------------------------- */ -qboolean Item_HandleSelectionPrev(itemDef_t * item) -{ - if (item->selectionPrev) - { +qboolean Item_HandleSelectionPrev(itemDef_t *item) { + if (item->selectionPrev) { Item_RunScript(item, item->selectionPrev); return qtrue; } return qfalse; } - /* ================= Item_Action ================= */ -void Item_Action(itemDef_t *item) -{ - if (item) - { +void Item_Action(itemDef_t *item) { + if (item) { Item_RunScript(item, item->action); } } @@ -11171,59 +9682,47 @@ void Item_Action(itemDef_t *item) Menu_HandleKey ================= */ -void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) -{ +void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { int i; itemDef_t *item = NULL; qboolean inHandler = qfalse; - if (inHandler) - { + if (inHandler) { return; } inHandler = qtrue; - if (g_waitingForKey && down) - { + if (g_waitingForKey && down) { Item_Bind_HandleKey(g_bindItem, key, down); inHandler = qfalse; return; } - if (g_editingField && down) - { - if (!Item_TextField_HandleKey(g_editItem, key)) - { + if (g_editingField && down) { + if (!Item_TextField_HandleKey(g_editItem, key)) { g_editingField = qfalse; g_editItem = NULL; inHandler = qfalse; return; - } - else if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3) - { + } else if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3) { g_editingField = qfalse; g_editItem = NULL; Display_MouseMove(NULL, DC->cursorx, DC->cursory); - } - else if (key == A_TAB || key == A_CURSOR_UP || key == A_CURSOR_DOWN) - { + } else if (key == A_TAB || key == A_CURSOR_UP || key == A_CURSOR_DOWN) { return; } } - if (menu == NULL) - { + if (menu == NULL) { inHandler = qfalse; return; } - //JLFMOUSE MPMOVED - // see if the mouse is within the window bounds and if so is this a mouse click - if (down && !(menu->window.flags & WINDOW_POPUP) && !Rect_ContainsPoint(&menu->window.rect, DC->cursorx, DC->cursory)) - { + // JLFMOUSE MPMOVED + // see if the mouse is within the window bounds and if so is this a mouse click + if (down && !(menu->window.flags & WINDOW_POPUP) && !Rect_ContainsPoint(&menu->window.rect, DC->cursorx, DC->cursory)) { static qboolean inHandleKey = qfalse; - if (!inHandleKey && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) - { + if (!inHandleKey && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) { inHandleKey = qtrue; Menus_HandleOOBClick(menu, key, down); inHandleKey = qfalse; @@ -11233,227 +9732,188 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) } // get the item with focus - for (i = 0; i < menu->itemCount; i++) - { - if (menu->items[i]->window.flags & WINDOW_HASFOCUS) - { + for (i = 0; i < menu->itemCount; i++) { + if (menu->items[i]->window.flags & WINDOW_HASFOCUS) { item = menu->items[i]; break; } } // Ignore if disabled - if (item && item->disabled) - { + if (item && item->disabled) { return; } - if (item != NULL) - { + if (item != NULL) { if (Item_HandleKey(item, key, down)) -//JLFLISTBOX + // JLFLISTBOX { // It is possible for an item to be disable after Item_HandleKey is run (like in Voice Chat) - if (!item->disabled) - { + if (!item->disabled) { Item_Action(item); } inHandler = qfalse; return; } - } - if (!down) - { + if (!down) { inHandler = qfalse; return; } // Special Data Pad key handling (gotta love the datapad) - if (!(key & K_CHAR_FLAG) ) - { //only check keys not chars - char b[256]; - DC->getBindingBuf( key, b, 256 ); - if (Q_stricmp(b,"datapad") == 0) // They hit the datapad key again. + if (!(key & K_CHAR_FLAG)) { // only check keys not chars + char b[256]; + DC->getBindingBuf(key, b, 256); + if (Q_stricmp(b, "datapad") == 0) // They hit the datapad key again. { - if (( Q_stricmp(menu->window.name,"datapadMissionMenu") == 0) || - (Q_stricmp(menu->window.name,"datapadWeaponsMenu") == 0) || - (Q_stricmp(menu->window.name,"datapadForcePowersMenu") == 0) || - (Q_stricmp(menu->window.name,"datapadInventoryMenu") == 0)) - { - key = A_ESCAPE; //pop on outta here + if ((Q_stricmp(menu->window.name, "datapadMissionMenu") == 0) || (Q_stricmp(menu->window.name, "datapadWeaponsMenu") == 0) || + (Q_stricmp(menu->window.name, "datapadForcePowersMenu") == 0) || (Q_stricmp(menu->window.name, "datapadInventoryMenu") == 0)) { + key = A_ESCAPE; // pop on outta here } } } // default handling - switch ( key ) - { - case A_F11: - if (DC->getCVarValue("developer")) - { - uis.debugMode = (qboolean)!uis.debugMode; - } - break; + switch (key) { + case A_F11: + if (DC->getCVarValue("developer")) { + uis.debugMode = (qboolean)!uis.debugMode; + } + break; - case A_F12: - if (DC->getCVarValue("developer")) - { - switch ( DC->screenshotFormat ) - { - case SSF_JPEG: - DC->executeText(EXEC_APPEND, "screenshot\n"); - break; - case SSF_TGA: - DC->executeText(EXEC_APPEND, "screenshot_tga\n"); - break; - case SSF_PNG: - DC->executeText(EXEC_APPEND, "screenshot_png\n"); - break; - default: - if (DC->Print) { - DC->Print(S_COLOR_YELLOW "Menu_HandleKey[F12]: Unknown screenshot format assigned! This should not happen.\n"); - } - break; + case A_F12: + if (DC->getCVarValue("developer")) { + switch (DC->screenshotFormat) { + case SSF_JPEG: + DC->executeText(EXEC_APPEND, "screenshot\n"); + break; + case SSF_TGA: + DC->executeText(EXEC_APPEND, "screenshot_tga\n"); + break; + case SSF_PNG: + DC->executeText(EXEC_APPEND, "screenshot_png\n"); + break; + default: + if (DC->Print) { + DC->Print(S_COLOR_YELLOW "Menu_HandleKey[F12]: Unknown screenshot format assigned! This should not happen.\n"); } + break; } - break; - case A_KP_8: - case A_CURSOR_UP: - Menu_SetPrevCursorItem(menu); - break; - + } + break; + case A_KP_8: + case A_CURSOR_UP: + Menu_SetPrevCursorItem(menu); + break; - case A_ESCAPE: - if (!g_waitingForKey && menu->onESC) - { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onESC); - } - break; - case A_TAB: - case A_KP_2: - case A_CURSOR_DOWN: - Menu_SetNextCursorItem(menu); - break; + case A_ESCAPE: + if (!g_waitingForKey && menu->onESC) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onESC); + } + break; + case A_TAB: + case A_KP_2: + case A_CURSOR_DOWN: + Menu_SetNextCursorItem(menu); + break; - case A_MOUSE1: - case A_MOUSE2: - if (item) - { - if (item->type == ITEM_TYPE_TEXT) - { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { - if ( item->action ) - Item_Action(item); - else - { - if (menu->onAccept) - { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onAccept); - } + case A_MOUSE1: + case A_MOUSE2: + if (item) { + if (item->type == ITEM_TYPE_TEXT) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { + if (item->action) + Item_Action(item); + else { + if (menu->onAccept) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onAccept); } - } } - else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) - { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { - item->cursorPos = 0; - g_editingField = qtrue; - g_editItem = item; - //DC->setOverstrikeMode(qtrue); - } + } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { + item->cursorPos = 0; + g_editingField = qtrue; + g_editItem = item; + // DC->setOverstrikeMode(qtrue); } -//JLFACCEPT -// add new types here as needed -/* Notes: - Most controls will use the dpad to move through the selection possibilies. Buttons are the only exception. - Buttons will be assumed to all be on one menu together. If the start or A button is pressed on a control focus, that - means that the menu is accepted and move onto the next menu. If the start or A button is pressed on a button focus it - should just process the action and not support the accept functionality. -*/ -//JLFACCEPT - else if ( item->type == ITEM_TYPE_MULTI || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_SLIDER) - { - - if (Item_HandleAccept(item)) - { - //Item processed it overriding the menu processing - return; - } - else if (menu->onAccept) - { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onAccept); - } - - + } + // JLFACCEPT + // add new types here as needed + /* Notes: + Most controls will use the dpad to move through the selection possibilies. Buttons are the only exception. + Buttons will be assumed to all be on one menu together. If the start or A button is pressed on a control focus, that + means that the menu is accepted and move onto the next menu. If the start or A button is pressed on a button focus it + should just process the action and not support the accept functionality. + */ + // JLFACCEPT + else if (item->type == ITEM_TYPE_MULTI || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_SLIDER) { + + if (Item_HandleAccept(item)) { + // Item processed it overriding the menu processing + return; + } else if (menu->onAccept) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onAccept); } -//END JLFACCEPT - else - { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { - Item_Action(item); - } - } } - else if (menu->onAccept) - { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onAccept); - } - break; - case A_JOY0: - case A_JOY1: - case A_JOY2: - case A_JOY3: - case A_JOY4: - case A_AUX0: - case A_AUX1: - case A_AUX2: - case A_AUX3: - case A_AUX4: - case A_AUX5: - case A_AUX6: - case A_AUX7: - case A_AUX8: - case A_AUX9: - case A_AUX10: - case A_AUX11: - case A_AUX12: - case A_AUX13: - case A_AUX14: - case A_AUX15: - case A_AUX16: - break; - case A_KP_ENTER: - case A_ENTER: - if (item) - { - if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) - { - item->cursorPos = 0; - g_editingField = qtrue; - g_editItem = item; - //DC->setOverstrikeMode(qtrue); - } - else - { - Item_Action(item); + // END JLFACCEPT + else { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { + Item_Action(item); } } - break; + } else if (menu->onAccept) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onAccept); + } + break; + + case A_JOY0: + case A_JOY1: + case A_JOY2: + case A_JOY3: + case A_JOY4: + case A_AUX0: + case A_AUX1: + case A_AUX2: + case A_AUX3: + case A_AUX4: + case A_AUX5: + case A_AUX6: + case A_AUX7: + case A_AUX8: + case A_AUX9: + case A_AUX10: + case A_AUX11: + case A_AUX12: + case A_AUX13: + case A_AUX14: + case A_AUX15: + case A_AUX16: + break; + case A_KP_ENTER: + case A_ENTER: + if (item) { + if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { + item->cursorPos = 0; + g_editingField = qtrue; + g_editItem = item; + // DC->setOverstrikeMode(qtrue); + } else { + Item_Action(item); + } + } + break; } inHandler = qfalse; } @@ -11463,16 +9923,11 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) ParseRect ================= */ -qboolean ParseRect(const char **p, rectDef_t *r) -{ - if (!COM_ParseFloat(p, &r->x)) - { - if (!COM_ParseFloat(p, &r->y)) - { - if (!COM_ParseFloat(p, &r->w)) - { - if (!COM_ParseFloat(p, &r->h)) - { +qboolean ParseRect(const char **p, rectDef_t *r) { + if (!COM_ParseFloat(p, &r->x)) { + if (!COM_ParseFloat(p, &r->y)) { + if (!COM_ParseFloat(p, &r->w)) { + if (!COM_ParseFloat(p, &r->h)) { return qtrue; } } @@ -11481,29 +9936,25 @@ qboolean ParseRect(const char **p, rectDef_t *r) return qfalse; } - /* ================= Menus_HideItems ================= */ -void Menus_HideItems(const char *menuName) -{ - menuDef_t *menu; - int i; +void Menus_HideItems(const char *menuName) { + menuDef_t *menu; + int i; - menu =Menus_FindByName(menuName); // Get menu + menu = Menus_FindByName(menuName); // Get menu - if (!menu) - { - Com_Printf(S_COLOR_YELLOW"WARNING: No menu was found. Could not hide items.\n"); + if (!menu) { + Com_Printf(S_COLOR_YELLOW "WARNING: No menu was found. Could not hide items.\n"); return; } menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); - for (i = 0; i < menu->itemCount; i++) - { + for (i = 0; i < menu->itemCount; i++) { menu->items[i]->cvarFlags = CVAR_HIDE; } } @@ -11513,23 +9964,20 @@ void Menus_HideItems(const char *menuName) Menus_ShowItems ================= */ -void Menus_ShowItems(const char *menuName) -{ - menuDef_t *menu; - int i; +void Menus_ShowItems(const char *menuName) { + menuDef_t *menu; + int i; - menu =Menus_FindByName(menuName); // Get menu + menu = Menus_FindByName(menuName); // Get menu - if (!menu) - { - Com_Printf(S_COLOR_YELLOW"WARNING: No menu was found. Could not show items.\n"); + if (!menu) { + Com_Printf(S_COLOR_YELLOW "WARNING: No menu was found. Could not show items.\n"); return; } menu->window.flags |= (WINDOW_HASFOCUS | WINDOW_VISIBLE); - for (i = 0; i < menu->itemCount; i++) - { + for (i = 0; i < menu->itemCount; i++) { menu->items[i]->cvarFlags = CVAR_SHOW; } } @@ -11539,12 +9987,10 @@ void Menus_ShowItems(const char *menuName) UI_Cursor_Show ================= */ -void UI_Cursor_Show(qboolean flag) -{ +void UI_Cursor_Show(qboolean flag) { DC->cursorShow = flag; - if ((DC->cursorShow != qtrue) && (DC->cursorShow != qfalse)) - { + if ((DC->cursorShow != qtrue) && (DC->cursorShow != qfalse)) { DC->cursorShow = qtrue; } } diff --git a/code/ui/ui_syscalls.cpp b/code/ui/ui_syscalls.cpp index a6a00b30ae..ad5887eaa8 100644 --- a/code/ui/ui_syscalls.cpp +++ b/code/ui/ui_syscalls.cpp @@ -25,100 +25,59 @@ along with this program; if not, see . #include "ui_local.h" -float trap_Cvar_VariableValue( const char *var_name ) -{ - return Cvar_VariableValue( var_name ); -} - +float trap_Cvar_VariableValue(const char *var_name) { return Cvar_VariableValue(var_name); } -void trap_R_ClearScene( void ) -{ - ui.R_ClearScene(); -} +void trap_R_ClearScene(void) { ui.R_ClearScene(); } -void trap_R_AddRefEntityToScene( const refEntity_t *re ) -{ - ui.R_AddRefEntityToScene(re); -} +void trap_R_AddRefEntityToScene(const refEntity_t *re) { ui.R_AddRefEntityToScene(re); } -void trap_R_RenderScene( const refdef_t *fd ) -{ -// syscall( UI_R_RENDERSCENE, fd ); +void trap_R_RenderScene(const refdef_t *fd) { + // syscall( UI_R_RENDERSCENE, fd ); ui.R_RenderScene(fd); } -void trap_R_SetColor( const float *rgba ) -{ -// syscall( UI_R_SETCOLOR, rgba ); -// re.SetColor( rgba ); +void trap_R_SetColor(const float *rgba) { + // syscall( UI_R_SETCOLOR, rgba ); + // re.SetColor( rgba ); ui.R_SetColor(rgba); } -void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ) -{ -// syscall( UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader ); -// re.DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); - - ui.R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); +void trap_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + // syscall( UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + //hShader ); re.DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); + ui.R_DrawStretchPic(x, y, w, h, s1, t1, s2, t2, hShader); } -void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) -{ -// syscall( UI_R_MODELBOUNDS, model, mins, maxs ); +void trap_R_ModelBounds(clipHandle_t model, vec3_t mins, vec3_t maxs) { + // syscall( UI_R_MODELBOUNDS, model, mins, maxs ); ui.R_ModelBounds(model, mins, maxs); } -void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) -{ -// syscall( UI_S_STARTLOCALSOUND, sfx, channelNum ); - S_StartLocalSound( sfx, channelNum ); +void trap_S_StartLocalSound(sfxHandle_t sfx, int channelNum) { + // syscall( UI_S_STARTLOCALSOUND, sfx, channelNum ); + S_StartLocalSound(sfx, channelNum); } +void trap_S_StopSounds(void) { S_StopSounds(); } -void trap_S_StopSounds( void ) -{ - S_StopSounds( ); -} +sfxHandle_t trap_S_RegisterSound(const char *sample, qboolean compressed) { return S_RegisterSound(sample); } -sfxHandle_t trap_S_RegisterSound( const char *sample, qboolean compressed ) -{ - return S_RegisterSound(sample); -} +void trap_Key_SetBinding(int keynum, const char *binding) { Key_SetBinding(keynum, binding); } -void trap_Key_SetBinding( int keynum, const char *binding ) -{ - Key_SetBinding( keynum, binding); -} +qboolean trap_Key_GetOverstrikeMode(void) { return Key_GetOverstrikeMode(); } -qboolean trap_Key_GetOverstrikeMode( void ) -{ - return Key_GetOverstrikeMode(); -} +void trap_Key_SetOverstrikeMode(qboolean state) { Key_SetOverstrikeMode(state); } -void trap_Key_SetOverstrikeMode( qboolean state ) -{ - Key_SetOverstrikeMode( state ); -} +void trap_Key_ClearStates(void) { Key_ClearStates(); } -void trap_Key_ClearStates( void ) -{ - Key_ClearStates(); -} +int Key_GetCatcher(void); -int Key_GetCatcher( void ); +int trap_Key_GetCatcher(void) { return Key_GetCatcher(); } -int trap_Key_GetCatcher( void ) -{ - return Key_GetCatcher(); -} +void Key_SetCatcher(int catcher); -void Key_SetCatcher( int catcher ); - -void trap_Key_SetCatcher( int catcher ) -{ - Key_SetCatcher( catcher ); -} +void trap_Key_SetCatcher(int catcher) { Key_SetCatcher(catcher); } /* void trap_GetClipboardData( char *buf, int bufsize ) { syscall( UI_GETCLIPBOARDDATA, buf, bufsize ); @@ -129,25 +88,22 @@ void trap_GetClientState( uiClientState_t *state ) { } */ -void CL_GetGlconfig( glconfig_t *glconfig ); +void CL_GetGlconfig(glconfig_t *glconfig); -void trap_GetGlconfig( glconfig_t *glconfig ) -{ -// syscall( UI_GETGLCONFIG, glconfig ); - CL_GetGlconfig( glconfig ); +void trap_GetGlconfig(glconfig_t *glconfig) { + // syscall( UI_GETGLCONFIG, glconfig ); + CL_GetGlconfig(glconfig); } // this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate) -int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile) { -// return syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); - return CIN_PlayCinematic( arg0, xpos, ypos, width, height, bits, psAudioFile ); +int trap_CIN_PlayCinematic(const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile) { + // return syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); + return CIN_PlayCinematic(arg0, xpos, ypos, width, height, bits, psAudioFile); } // stops playing the cinematic and ends it. should always return FMV_EOF // cinematics must be stopped in reverse order of when they are started -int trap_CIN_StopCinematic(int handle) -{ -// return syscall(UI_CIN_STOPCINEMATIC, handle); +int trap_CIN_StopCinematic(int handle) { + // return syscall(UI_CIN_STOPCINEMATIC, handle); return CIN_StopCinematic(handle); } - diff --git a/codeJK2/cgame/FX_ATSTMain.cpp b/codeJK2/cgame/FX_ATSTMain.cpp index ffeda539dc..f06e927d31 100644 --- a/codeJK2/cgame/FX_ATSTMain.cpp +++ b/codeJK2/cgame/FX_ATSTMain.cpp @@ -26,20 +26,16 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* --------------------------- FX_ATSTMainProjectileThink --------------------------- */ -void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -47,19 +43,17 @@ void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *wea // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 30 ) - { - if ( dif < 0 ) - { + if (dif < 30) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 30.0f ) * 0.95f + 0.05f; + float scale = (dif / 30.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "atst/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/shot", cent->lerpOrigin, forward); } /* @@ -67,25 +61,18 @@ void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *wea FX_ATSTMainHitWall --------------------------- */ -void FX_ATSTMainHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "atst/wall_impact", origin, normal ); -} +void FX_ATSTMainHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("atst/wall_impact", origin, normal); } /* --------------------------- FX_ATSTMainHitPlayer --------------------------- */ -void FX_ATSTMainHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - theFxScheduler.PlayEffect( "atst/flesh_impact", origin, normal ); - } - else - { - theFxScheduler.PlayEffect( "atst/droid_impact", origin, normal ); +void FX_ATSTMainHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + theFxScheduler.PlayEffect("atst/flesh_impact", origin, normal); + } else { + theFxScheduler.PlayEffect("atst/droid_impact", origin, normal); } } @@ -94,16 +81,14 @@ void FX_ATSTMainHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_ATSTSideAltProjectileThink --------------------------- */ -void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTSideAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "atst/side_alt_shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/side_alt_shot", cent->lerpOrigin, forward); } /* @@ -111,14 +96,12 @@ void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s * FX_ATSTSideMainProjectileThink --------------------------- */ -void FX_ATSTSideMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ATSTSideMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "atst/side_main_shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("atst/side_main_shot", cent->lerpOrigin, forward); } diff --git a/codeJK2/cgame/FX_Blaster.cpp b/codeJK2/cgame/FX_Blaster.cpp index 1e2b81419f..7d98f5c2fc 100644 --- a/codeJK2/cgame/FX_Blaster.cpp +++ b/codeJK2/cgame/FX_Blaster.cpp @@ -31,14 +31,11 @@ FX_BlasterProjectileThink ------------------------- */ -void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BlasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -46,25 +43,20 @@ void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weap // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0 ) - { - theFxScheduler.PlayEffect( "blaster/NPCshot", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( cgs.effects.blasterShotEffect, cent->lerpOrigin, forward ); + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0) { + theFxScheduler.PlayEffect("blaster/NPCshot", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect(cgs.effects.blasterShotEffect, cent->lerpOrigin, forward); } } @@ -73,27 +65,20 @@ void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weap FX_BlasterAltFireThink ------------------------- */ -void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ - FX_BlasterProjectileThink( cent, weapon ); -} +void FX_BlasterAltFireThink(centity_t *cent, const struct weaponInfo_s *weapon) { FX_BlasterProjectileThink(cent, weapon); } /* ------------------------- FX_BlasterWeaponHitWall ------------------------- */ -void FX_BlasterWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.blasterWallImpactEffect, origin, normal ); -} +void FX_BlasterWeaponHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.blasterWallImpactEffect, origin, normal); } /* ------------------------- FX_BlasterWeaponHitPlayer ------------------------- */ -void FX_BlasterWeaponHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.blasterFleshImpactEffect, origin, normal ); +void FX_BlasterWeaponHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + theFxScheduler.PlayEffect(cgs.effects.blasterFleshImpactEffect, origin, normal); } diff --git a/codeJK2/cgame/FX_Bowcaster.cpp b/codeJK2/cgame/FX_Bowcaster.cpp index 56b65da764..0dbea27c66 100644 --- a/codeJK2/cgame/FX_Bowcaster.cpp +++ b/codeJK2/cgame/FX_Bowcaster.cpp @@ -32,14 +32,11 @@ FX_BowcasterProjectileThink --------------------------- */ -void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BowcasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -47,19 +44,17 @@ void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *we // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward); } /* @@ -68,10 +63,7 @@ FX_BowcasterHitWall --------------------------- */ -void FX_BowcasterHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.bowcasterImpactEffect, origin, normal ); -} +void FX_BowcasterHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.bowcasterImpactEffect, origin, normal); } /* --------------------------- @@ -79,7 +71,4 @@ FX_BowcasterHitPlayer --------------------------- */ -void FX_BowcasterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bowcasterImpactEffect, origin, normal ); -} \ No newline at end of file +void FX_BowcasterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bowcasterImpactEffect, origin, normal); } \ No newline at end of file diff --git a/codeJK2/cgame/FX_BryarPistol.cpp b/codeJK2/cgame/FX_BryarPistol.cpp index f1956377bd..286a329ac5 100644 --- a/codeJK2/cgame/FX_BryarPistol.cpp +++ b/codeJK2/cgame/FX_BryarPistol.cpp @@ -34,14 +34,11 @@ along with this program; if not, see . FX_BryarProjectileThink ------------------------- */ -void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -49,25 +46,20 @@ void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0 ) - { - theFxScheduler.PlayEffect( "bryar/NPCshot", cent->lerpOrigin, forward ); - } - else - { - theFxScheduler.PlayEffect( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward ); + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number > 0) { + theFxScheduler.PlayEffect("bryar/NPCshot", cent->lerpOrigin, forward); + } else { + theFxScheduler.PlayEffect(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward); } } @@ -76,21 +68,14 @@ void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo FX_BryarHitWall ------------------------- */ -void FX_BryarHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect, origin, normal ); -} +void FX_BryarHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect, origin, normal); } /* ------------------------- FX_BryarHitPlayer ------------------------- */ -void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarFleshImpactEffect, origin, normal ); -} - +void FX_BryarHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bryarFleshImpactEffect, origin, normal); } /* ------------------------- @@ -101,14 +86,11 @@ void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_BryarAltProjectileThink ------------------------- */ -void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -116,26 +98,23 @@ void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *we // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } // see if we have some sort of extra charge going on - for ( int t = 1; t < cent->gent->count; t++ ) - { + for (int t = 1; t < cent->gent->count; t++) { // just add ourselves over, and over, and over when we are charged - theFxScheduler.PlayEffect( cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward); } - theFxScheduler.PlayEffect( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward); } /* @@ -143,22 +122,20 @@ void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_BryarAltHitWall ------------------------- */ -void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) -{ - switch( power ) - { +void FX_BryarAltHitWall(vec3_t origin, vec3_t normal, int power) { + switch (power) { case 4: case 5: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect3, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect3, origin, normal); break; case 2: case 3: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect2, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect2, origin, normal); break; default: - theFxScheduler.PlayEffect( cgs.effects.bryarWallImpactEffect, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bryarWallImpactEffect, origin, normal); break; } } @@ -168,7 +145,4 @@ void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) FX_BryarAltHitPlayer ------------------------- */ -void FX_BryarAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( cgs.effects.bryarFleshImpactEffect, origin, normal ); -} +void FX_BryarAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect(cgs.effects.bryarFleshImpactEffect, origin, normal); } diff --git a/codeJK2/cgame/FX_DEMP2.cpp b/codeJK2/cgame/FX_DEMP2.cpp index d0c44789f5..cfa6f95712 100644 --- a/codeJK2/cgame/FX_DEMP2.cpp +++ b/codeJK2/cgame/FX_DEMP2.cpp @@ -33,18 +33,16 @@ FX_DEMP2_ProjectileThink --------------------------- */ -void FX_DEMP2_ProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_DEMP2_ProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } -// theFxScheduler.PlayEffect( "demp2/shot", cent->lerpOrigin, forward ); -// theFxScheduler.PlayEffect( "demp2/shot2", cent->lerpOrigin, forward ); - theFxScheduler.PlayEffect( "demp2/projectile", cent->lerpOrigin, forward ); + // theFxScheduler.PlayEffect( "demp2/shot", cent->lerpOrigin, forward ); + // theFxScheduler.PlayEffect( "demp2/shot2", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("demp2/projectile", cent->lerpOrigin, forward); } /* @@ -53,10 +51,7 @@ FX_DEMP2_HitWall --------------------------- */ -void FX_DEMP2_HitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "demp2/wall_impact", origin, normal ); -} +void FX_DEMP2_HitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("demp2/wall_impact", origin, normal); } /* --------------------------- @@ -64,10 +59,7 @@ FX_DEMP2_HitPlayer --------------------------- */ -void FX_DEMP2_HitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "demp2/flesh_impact", origin, normal ); -} +void FX_DEMP2_HitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect("demp2/flesh_impact", origin, normal); } /* --------------------------- @@ -75,37 +67,34 @@ FX_DEMP2_AltProjectileThink --------------------------- */ -void FX_DEMP2_AltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_DEMP2_AltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "demp2/projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("demp2/projectile", cent->lerpOrigin, forward); } //--------------------------------------------- -void FX_DEMP2_AltDetonate( vec3_t org, float size ) -{ - localEntity_t *ex; +void FX_DEMP2_AltDetonate(vec3_t org, float size) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_FADE_SCALE_MODEL; - memset( &ex->refEntity, 0, sizeof( refEntity_t )); + memset(&ex->refEntity, 0, sizeof(refEntity_t)); ex->refEntity.renderfx |= RF_VOLUMETRIC; ex->startTime = cg.time; ex->endTime = ex->startTime + 1300; - + ex->radius = size; - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/demp2shell" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/demp2shell"); + + ex->refEntity.hModel = cgi_R_RegisterModel("models/items/sphere.md3"); + VectorCopy(org, ex->refEntity.origin); - ex->refEntity.hModel = cgi_R_RegisterModel( "models/items/sphere.md3" ); - VectorCopy( org, ex->refEntity.origin ); - ex->color[0] = ex->color[1] = ex->color[2] = 255.0f; } diff --git a/codeJK2/cgame/FX_Disruptor.cpp b/codeJK2/cgame/FX_Disruptor.cpp index a141bcf025..e0cf88f87e 100644 --- a/codeJK2/cgame/FX_Disruptor.cpp +++ b/codeJK2/cgame/FX_Disruptor.cpp @@ -26,70 +26,55 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* --------------------------- FX_DisruptorMainShot --------------------------- */ -static vec3_t WHITE ={1.0f,1.0f,1.0f}; - -void FX_DisruptorMainShot( vec3_t start, vec3_t end ) -{ - FX_AddLine( start, end, 0.1f, 4.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 120, cgi_R_RegisterShader( "gfx/effects/redLine" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); -} +static vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +void FX_DisruptorMainShot(vec3_t start, vec3_t end) { + FX_AddLine(start, end, 0.1f, 4.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 120, cgi_R_RegisterShader("gfx/effects/redLine"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); +} /* --------------------------- FX_DisruptorAltShot --------------------------- */ -void FX_DisruptorAltShot( vec3_t start, vec3_t end, qboolean fullCharge ) -{ - FX_AddLine( start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, cgi_R_RegisterShader( "gfx/effects/redLine" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); - - if ( fullCharge ) - { - vec3_t YELLER={0.8f,0.7f,0.0f}; +void FX_DisruptorAltShot(vec3_t start, vec3_t end, qboolean fullCharge) { + FX_AddLine(start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, cgi_R_RegisterShader("gfx/effects/redLine"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); + + if (fullCharge) { + vec3_t YELLER = {0.8f, 0.7f, 0.0f}; // add some beef - FX_AddLine( start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - YELLER, YELLER, 0.0f, - 150, cgi_R_RegisterShader( "gfx/misc/whiteline2" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + FX_AddLine(start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, YELLER, YELLER, 0.0f, 150, cgi_R_RegisterShader("gfx/misc/whiteline2"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } } - /* --------------------------- FX_DisruptorAltShot --------------------------- */ -void FX_DisruptorAltMiss( vec3_t origin, vec3_t normal ) -{ +void FX_DisruptorAltMiss(vec3_t origin, vec3_t normal) { vec3_t pos, c1, c2; - VectorMA( origin, 4.0f, normal, c1 ); - VectorCopy( c1, c2 ); + VectorMA(origin, 4.0f, normal, c1); + VectorCopy(c1, c2); c1[2] += 4; c2[2] += 12; - - VectorAdd( origin, normal, pos ); + + VectorAdd(origin, normal, pos); pos[2] += 28; - FX_AddBezier( origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, cgi_R_RegisterShader( "gfx/effects/smokeTrail" ), FX_ALPHA_WAVE ); + FX_AddBezier(origin, pos, c1, vec3_origin, c2, vec3_origin, 6.0f, 6.0f, 0.0f, 0.0f, 0.2f, 0.5f, WHITE, WHITE, 0.0f, 4000, + cgi_R_RegisterShader("gfx/effects/smokeTrail"), FX_ALPHA_WAVE); - theFxScheduler.PlayEffect( "disruptor/alt_miss", origin, normal ); + theFxScheduler.PlayEffect("disruptor/alt_miss", origin, normal); } \ No newline at end of file diff --git a/codeJK2/cgame/FX_Emplaced.cpp b/codeJK2/cgame/FX_Emplaced.cpp index 1015036184..8b31f0d8d7 100644 --- a/codeJK2/cgame/FX_Emplaced.cpp +++ b/codeJK2/cgame/FX_Emplaced.cpp @@ -32,14 +32,11 @@ FX_EmplacedProjectileThink --------------------------- */ -void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_EmplacedProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -47,27 +44,22 @@ void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *wea // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - if ( cent->gent && cent->gent->owner && cent->gent->owner->activator && cent->gent->owner->activator->s.number > 0 ) - { + if (cent->gent && cent->gent->owner && cent->gent->owner->activator && cent->gent->owner->activator->s.number > 0) { // NPC's do short shot - theFxScheduler.PlayEffect( "emplaced/shotNPC", cent->lerpOrigin, forward ); - } - else - { + theFxScheduler.PlayEffect("emplaced/shotNPC", cent->lerpOrigin, forward); + } else { // players do long shot - theFxScheduler.PlayEffect( "emplaced/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("emplaced/shot", cent->lerpOrigin, forward); } } @@ -77,10 +69,7 @@ FX_EmplacedHitWall --------------------------- */ -void FX_EmplacedHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "emplaced/wall_impact", origin, normal ); -} +void FX_EmplacedHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("emplaced/wall_impact", origin, normal); } /* --------------------------- @@ -88,14 +77,11 @@ FX_TurretProjectileThink --------------------------- */ -void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_TurretProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->gent->s.pos.trDelta, forward ) == 0.0f ) - { - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->gent->s.pos.trDelta, forward) == 0.0f) { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } } @@ -103,17 +89,15 @@ void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo // hack the scale of the forward vector if we were just fired or bounced...this will shorten up the tail for a split second so tails don't clip so harshly int dif = cg.time - cent->gent->s.pos.trTime; - if ( dif < 75 ) - { - if ( dif < 0 ) - { + if (dif < 75) { + if (dif < 0) { dif = 0; } - float scale = ( dif / 75.0f ) * 0.95f + 0.05f; + float scale = (dif / 75.0f) * 0.95f + 0.05f; - VectorScale( forward, scale, forward ); + VectorScale(forward, scale, forward); } - theFxScheduler.PlayEffect( "turret/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("turret/shot", cent->lerpOrigin, forward); } \ No newline at end of file diff --git a/codeJK2/cgame/FX_Flechette.cpp b/codeJK2/cgame/FX_Flechette.cpp index 7e6e65ed22..0adb2f3565 100644 --- a/codeJK2/cgame/FX_Flechette.cpp +++ b/codeJK2/cgame/FX_Flechette.cpp @@ -32,18 +32,16 @@ FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - EvaluateTrajectoryDelta( ¢->gent->s.pos, cg.time, forward ); + EvaluateTrajectoryDelta(¢->gent->s.pos, cg.time, forward); - if ( VectorNormalize( forward ) == 0.0f ) - { + if (VectorNormalize(forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward); } /* @@ -51,26 +49,22 @@ void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_FlechetteWeaponHitWall ------------------------- */ -void FX_FlechetteWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( cgs.effects.flechetteShotDeathEffect, origin, normal ); -} +void FX_FlechetteWeaponHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect(cgs.effects.flechetteShotDeathEffect, origin, normal); } /* ------------------------- FX_BlasterWeaponHitPlayer ------------------------- */ -void FX_FlechetteWeaponHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ -// if ( humanoid ) -// { - theFxScheduler.PlayEffect( cgs.effects.flechetteFleshImpactEffect, origin, normal ); -// } -// else -// { -// theFxScheduler.PlayEffect( "blaster/droid_impact", origin, normal ); -// } +void FX_FlechetteWeaponHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + // if ( humanoid ) + // { + theFxScheduler.PlayEffect(cgs.effects.flechetteFleshImpactEffect, origin, normal); + // } + // else + // { + // theFxScheduler.PlayEffect( "blaster/droid_impact", origin, normal ); + // } } /* @@ -79,14 +73,12 @@ FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect(cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward); } \ No newline at end of file diff --git a/codeJK2/cgame/FX_HeavyRepeater.cpp b/codeJK2/cgame/FX_HeavyRepeater.cpp index 46683d3a1a..ed4cadc6e9 100644 --- a/codeJK2/cgame/FX_HeavyRepeater.cpp +++ b/codeJK2/cgame/FX_HeavyRepeater.cpp @@ -31,16 +31,14 @@ FX_RepeaterProjectileThink --------------------------- */ -void FX_RepeaterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "repeater/projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("repeater/projectile", cent->lerpOrigin, forward); } /* @@ -49,10 +47,7 @@ FX_RepeaterHitWall ------------------------ */ -void FX_RepeaterHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "repeater/wall_impact", origin, normal ); -} +void FX_RepeaterHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("repeater/wall_impact", origin, normal); } /* ------------------------ @@ -60,10 +55,9 @@ FX_RepeaterHitPlayer ------------------------ */ -void FX_RepeaterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "repeater/wall_impact", origin, normal ); -// theFxScheduler.PlayEffect( "repeater/flesh_impact", origin, normal ); +void FX_RepeaterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + theFxScheduler.PlayEffect("repeater/wall_impact", origin, normal); + // theFxScheduler.PlayEffect( "repeater/flesh_impact", origin, normal ); } /* @@ -72,17 +66,15 @@ FX_RepeaterAltProjectileThink ----------------------------- */ -void FX_RepeaterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); -// theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("repeater/alt_projectile", cent->lerpOrigin, forward); + // theFxScheduler.PlayEffect( "repeater/alt_projectile", cent->lerpOrigin, forward ); } /* @@ -91,10 +83,9 @@ FX_RepeaterAltHitWall ------------------------ */ -void FX_RepeaterAltHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "repeater/concussion", origin, normal ); -// theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); +void FX_RepeaterAltHitWall(vec3_t origin, vec3_t normal) { + theFxScheduler.PlayEffect("repeater/concussion", origin, normal); + // theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); } /* @@ -103,8 +94,7 @@ FX_RepeaterAltHitPlayer ------------------------ */ -void FX_RepeaterAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "repeater/concussion", origin ); -// theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); +void FX_RepeaterAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + theFxScheduler.PlayEffect("repeater/concussion", origin); + // theFxScheduler.PlayEffect( "repeater/alt_wall_impact2", origin, normal ); } \ No newline at end of file diff --git a/codeJK2/cgame/FX_RocketLauncher.cpp b/codeJK2/cgame/FX_RocketLauncher.cpp index a938857376..ee6a8195ac 100644 --- a/codeJK2/cgame/FX_RocketLauncher.cpp +++ b/codeJK2/cgame/FX_RocketLauncher.cpp @@ -32,16 +32,14 @@ FX_RocketProjectileThink --------------------------- */ -void FX_RocketProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "rocket/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("rocket/shot", cent->lerpOrigin, forward); } /* @@ -50,10 +48,7 @@ FX_RocketHitWall --------------------------- */ -void FX_RocketHitWall( vec3_t origin, vec3_t normal ) -{ - theFxScheduler.PlayEffect( "rocket/explosion", origin, normal ); -} +void FX_RocketHitWall(vec3_t origin, vec3_t normal) { theFxScheduler.PlayEffect("rocket/explosion", origin, normal); } /* --------------------------- @@ -61,10 +56,7 @@ FX_RocketHitPlayer --------------------------- */ -void FX_RocketHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - theFxScheduler.PlayEffect( "rocket/explosion", origin, normal ); -} +void FX_RocketHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { theFxScheduler.PlayEffect("rocket/explosion", origin, normal); } /* --------------------------- @@ -72,14 +64,12 @@ FX_RocketAltProjectileThink --------------------------- */ -void FX_RocketAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - theFxScheduler.PlayEffect( "rocket/shot", cent->lerpOrigin, forward ); + theFxScheduler.PlayEffect("rocket/shot", cent->lerpOrigin, forward); } diff --git a/codeJK2/cgame/FxPrimitives.cpp b/codeJK2/cgame/FxPrimitives.cpp index 9cda3a5991..7bdfd175ea 100644 --- a/codeJK2/cgame/FxPrimitives.cpp +++ b/codeJK2/cgame/FxPrimitives.cpp @@ -21,7 +21,7 @@ along with this program; if not, see . */ #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #include "cg_media.h" @@ -34,21 +34,16 @@ extern int mTails; // Helper function //------------------------- -void ClampVec( vec3_t dat, byte *res ) -{ +void ClampVec(vec3_t dat, byte *res) { int r; // clamp all vec values, then multiply the normalized values by 255 to maximize the result - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { r = Q_ftol(dat[i] * 255.0f); - if ( r < 0 ) - { + if (r < 0) { r = 0; - } - else if ( r > 255 ) - { + } else if (r > 255) { r = 255; } @@ -56,28 +51,22 @@ void ClampVec( vec3_t dat, byte *res ) } } -void GetOrigin( int clientID, vec3_t org ) -{ - if ( clientID >=0 ) - { +void GetOrigin(int clientID, vec3_t org) { + if (clientID >= 0) { centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - VectorCopy( cent->gent->client->renderInfo.muzzlePoint, org ); + if (cent && cent->gent && cent->gent->client) { + VectorCopy(cent->gent->client->renderInfo.muzzlePoint, org); } } } -void GetDir( int clientID, vec3_t org ) -{ - if ( clientID >=0 ) - { +void GetDir(int clientID, vec3_t org) { + if (clientID >= 0) { centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - VectorCopy( cent->gent->client->renderInfo.muzzleDir, org ); + if (cent && cent->gent && cent->gent->client) { + VectorCopy(cent->gent->client->renderInfo.muzzleDir, org); } } } @@ -88,46 +77,40 @@ void GetDir( int clientID, vec3_t org ) // //-------------------------- - //-------------------------- // // Derived Particle Class // //-------------------------- -void CParticle::Die() -{ - if ( mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT) ) - { - vec3_t norm; +void CParticle::Die() { + if (mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT)) { + vec3_t norm; // Man, this just seems so, like, uncool and stuff... - VectorSet( norm, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); - VectorNormalize( norm ); + VectorSet(norm, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); + VectorNormalize(norm); - theFxScheduler.PlayEffect( mDeathFxID, mOrigin1, norm ); + theFxScheduler.PlayEffect(mDeathFxID, mOrigin1, norm); } } //---------------------------- -bool CParticle::Cull() -{ - vec3_t dir; +bool CParticle::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 16 * 16 ) - { + if (len < 16 * 16) { return true; } @@ -135,17 +118,15 @@ bool CParticle::Cull() } //---------------------------- -void CParticle::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CParticle::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); - theFxHelper.AddFxToScene( &mRefEnt ); + VectorCopy(mOrigin1, mRefEnt.origin); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mParticles++; @@ -154,69 +135,62 @@ void CParticle::Draw() //---------------------------- // Update //---------------------------- -bool CParticle::Update() -{ +bool CParticle::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t dir, org = { 0.0f }; - vec3_t realVel, realAccel; - float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + vec3_t dir, org = {0.0f}; + vec3_t realVel, realAccel; + float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // Get our current position and direction - GetOrigin( mClientID, org ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, org); + GetDir(mClientID, dir); vec3_t ang, ax[3]; - vectoangles( dir, ang ); - AngleVectors( ang, ax[0], ax[1], ax[2] ); -// VectorCopy( dir, ax[0] ); + vectoangles(dir, ang); + AngleVectors(ang, ax[0], ax[1], ax[2]); + // VectorCopy( dir, ax[0] ); -// CrossProduct( up, ax[0], ax[1] ); -// VectorNormalize( ax[1] ); -// CrossProduct( ax[0], ax[1], ax[2] ); + // CrossProduct( up, ax[0], ax[1] ); + // VectorNormalize( ax[1] ); + // CrossProduct( ax[0], ax[1], ax[2] ); - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); // calc the real velocity and accel vectors - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); realVel[2] += 0.5f * mGravity * time; - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); + VectorMA(org, time, realVel, mOrigin1); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull()) - { + if (!Cull()) { UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -231,96 +205,81 @@ bool CParticle::Update() //---------------------------- // Update Origin //---------------------------- -bool CParticle::UpdateOrigin() -{ - vec3_t new_origin; -// float ftime, time2; +bool CParticle::UpdateOrigin() { + vec3_t new_origin; + // float ftime, time2; UpdateVelocity(); // Calc the time differences -// ftime = theFxHelper.mFrameTime * 0.001f; - //time2 = ftime * ftime * 0.5f; -// time2=0; + // ftime = theFxHelper.mFrameTime * 0.001f; + // time2 = ftime * ftime * 0.5f; + // time2=0; // Predict the new position - new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0];// + time2 * mVel[0]; - new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1];// + time2 * mVel[1]; - new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2];// + time2 * mVel[2]; + new_origin[0] = mOrigin1[0] + theFxHelper.mFloatFrameTime * mVel[0]; // + time2 * mVel[0]; + new_origin[1] = mOrigin1[1] + theFxHelper.mFloatFrameTime * mVel[1]; // + time2 * mVel[1]; + new_origin[2] = mOrigin1[2] + theFxHelper.mFloatFrameTime * mVel[2]; // + time2 * mVel[2]; // Only perform physics if this object is tagged to do so - if ( (mFlags & FX_APPLY_PHYSICS) ) - { + if ((mFlags & FX_APPLY_PHYSICS)) { bool solid; - if ( mFlags & FX_EXPENSIVE_PHYSICS ) - { + if (mFlags & FX_EXPENSIVE_PHYSICS) { solid = true; // by setting this to true, we force a real trace to happen - } - else - { + } else { // if this returns solid, we need to do a trace - solid = !!(CG_PointContents( new_origin, ENTITYNUM_WORLD ) & ( MASK_SHOT | CONTENTS_WATER )); + solid = !!(CG_PointContents(new_origin, ENTITYNUM_WORLD) & (MASK_SHOT | CONTENTS_WATER)); } - if ( solid ) - { - trace_t trace; - float dot; + if (solid) { + trace_t trace; + float dot; - if ( mFlags & FX_USE_BBOX ) - { - theFxHelper.Trace( &trace, mOrigin1, mMin, mMax, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) ); - } - else - { - theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, new_origin, -1, ( MASK_SHOT | CONTENTS_WATER ) ); + if (mFlags & FX_USE_BBOX) { + theFxHelper.Trace(&trace, mOrigin1, mMin, mMax, new_origin, -1, (MASK_SHOT | CONTENTS_WATER)); + } else { + theFxHelper.Trace(&trace, mOrigin1, NULL, NULL, new_origin, -1, (MASK_SHOT | CONTENTS_WATER)); } - if ( trace.startsolid || trace.allsolid || trace.fraction == 1.0) - { - } - else - { + if (trace.startsolid || trace.allsolid || trace.fraction == 1.0) { + } else { // Hit something - if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT )) - { - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal ); + if (mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT)) { + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, trace.plane.normal); } - if ( mFlags & FX_KILL_ON_IMPACT ) - { + if (mFlags & FX_KILL_ON_IMPACT) { // time to die return false; } - VectorMA( mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel ); + VectorMA(mVel, theFxHelper.mFloatFrameTime * trace.fraction, mAccel, mVel); - dot = DotProduct( mVel, trace.plane.normal ); + dot = DotProduct(mVel, trace.plane.normal); - VectorMA( mVel, -2 * dot, trace.plane.normal, mVel ); + VectorMA(mVel, -2 * dot, trace.plane.normal, mVel); - VectorScale( mVel, mElasticity, mVel ); + VectorScale(mVel, mElasticity, mVel); // If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid // doing expensive operations when they aren't needed - if ( trace.plane.normal[2] > 0 && mVel[2] < 4 ) - { - VectorClear( mVel ); - VectorClear( mAccel ); + if (trace.plane.normal[2] > 0 && mVel[2] < 4) { + VectorClear(mVel); + VectorClear(mAccel); - mFlags &= ~(FX_APPLY_PHYSICS|FX_IMPACT_RUNS_FX); + mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX); } // Set the origin to the exact impact point - VectorCopy( trace.endpos, mOrigin1 ); + VectorCopy(trace.endpos, mOrigin1); return true; } } } // No physics were done to this object, move it - VectorCopy( new_origin, mOrigin1 ); + VectorCopy(new_origin, mOrigin1); return true; } @@ -328,72 +287,51 @@ bool CParticle::UpdateOrigin() //---------------------------- // Update Size //---------------------------- -void CParticle::UpdateSize() -{ +void CParticle::UpdateSize() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) - / (float)(mTimeEnd - mSizeParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSizeParm - theFxHelper.mTime) - / (float)(mSizeParm - mTimeStart); - } - else - { + perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if (( mFlags & FX_SIZE_RAND )) - { + if ((mFlags & FX_SIZE_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -404,144 +342,102 @@ void CParticle::UpdateSize() //---------------------------- // Update RGB //---------------------------- -void CParticle::UpdateRGB() -{ +void CParticle::UpdateRGB() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) - / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) - / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mRGBParm - theFxHelper.mTime) - / (float)(mRGBParm - mTimeStart); - } - else - { + perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if (( mFlags & FX_RGB_LINEAR )) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if (( mFlags & FX_RGB_RAND )) - { + if ((mFlags & FX_RGB_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); - VectorMA( res, (1.0f - perc1), mRGBEnd, mRefEnt.angles ); // angles is a temp storage, will get clamped to a byte in the UpdateAlpha section + VectorScale(mRGBStart, perc1, res); + VectorMA(res, (1.0f - perc1), mRGBEnd, mRefEnt.angles); // angles is a temp storage, will get clamped to a byte in the UpdateAlpha section } - //---------------------------- // Update Alpha //---------------------------- -void CParticle::UpdateAlpha() -{ +void CParticle::UpdateAlpha() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_NONLINEAR ) - { - if ( theFxHelper.mTime > mAlphaParm ) - { + if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_NONLINEAR) { + if (theFxHelper.mTime > mAlphaParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) - / (float)(mTimeEnd - mAlphaParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) / (float)(mTimeEnd - mAlphaParm); } - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mAlphaParm ); - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_CLAMP ) - { - if ( theFxHelper.mTime < mAlphaParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mAlphaParm); + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_CLAMP) { + if (theFxHelper.mTime < mAlphaParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mAlphaParm - theFxHelper.mTime) - / (float)(mAlphaParm - mTimeStart); - } - else - { + perc2 = (float)(mAlphaParm - theFxHelper.mTime) / (float)(mAlphaParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_ALPHA_LINEAR ) - { + if (mFlags & FX_ALPHA_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } @@ -550,33 +446,26 @@ void CParticle::UpdateAlpha() perc1 = (mAlphaStart * perc1) + (mAlphaEnd * (1.0f - perc1)); // We should be in the right range, but clamp to ensure - if ( perc1 < 0.0f ) - { + if (perc1 < 0.0f) { perc1 = 0.0f; - } - else if ( perc1 > 1.0f ) - { + } else if (perc1 > 1.0f) { perc1 = 1.0f; } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( (mFlags & FX_ALPHA_RAND) ) - { + if ((mFlags & FX_ALPHA_RAND)) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } - if ( mFlags & FX_USE_ALPHA ) - { + if (mFlags & FX_USE_ALPHA) { // should use this when using art that has an alpha channel - ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) ); - mRefEnt.shaderRGBA[3] = (byte)(perc1 * 0xff); - } - else - { + ClampVec(mRefEnt.angles, (byte *)(&mRefEnt.shaderRGBA)); + mRefEnt.shaderRGBA[3] = (byte)(perc1 * 0xff); + } else { // Modulate the rgb fields by the alpha value to do the fade, works fine for additive blending - VectorScale( mRefEnt.angles, perc1, mRefEnt.angles ); - ClampVec( mRefEnt.angles, (byte*)(&mRefEnt.shaderRGBA) ); + VectorScale(mRefEnt.angles, perc1, mRefEnt.angles); + ClampVec(mRefEnt.angles, (byte *)(&mRefEnt.shaderRGBA)); } } @@ -586,26 +475,22 @@ void CParticle::UpdateAlpha() // //-------------------------------- - //---------------------------- -bool COrientedParticle::Cull() -{ - vec3_t dir; +bool COrientedParticle::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 24 * 24 ) - { + if (len < 24 * 24) { return true; } @@ -613,18 +498,16 @@ bool COrientedParticle::Cull() } //---------------------------- -void COrientedParticle::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void COrientedParticle::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mNormal, mRefEnt.axis[0] ); - theFxHelper.AddFxToScene( &mRefEnt ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mNormal, mRefEnt.axis[0]); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mOParticles++; @@ -633,22 +516,18 @@ void COrientedParticle::Draw() //---------------------------- // Update //---------------------------- -bool COrientedParticle::Update() -{ +bool COrientedParticle::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull()) - { + if (!Cull()) { UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -660,7 +539,6 @@ bool COrientedParticle::Update() return true; } - //---------------------------- // // Derived Line Class @@ -668,63 +546,53 @@ bool COrientedParticle::Update() //---------------------------- //---------------------------- -void CLine::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CLine::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mLines++; } //---------------------------- -bool CLine::Update() -{ +bool CLine::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // we are somehow not bolted even though the flag is on? return false; } - vec3_t dir = { 0.0f }, end; - trace_t trace; + vec3_t dir = {0.0f}, end; + trace_t trace; // Get our current position and direction - GetOrigin( mClientID, mOrigin1 ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, mOrigin1); + GetDir(mClientID, dir); - if ( mFlags & FX_APPLY_PHYSICS ) - { - VectorMA( mOrigin1, 2048, dir, end ); + if (mFlags & FX_APPLY_PHYSICS) { + VectorMA(mOrigin1, 2048, dir, end); - theFxHelper.Trace( &trace, mOrigin1, NULL, NULL, end, mClientID, MASK_SHOT ); + theFxHelper.Trace(&trace, mOrigin1, NULL, NULL, end, mClientID, MASK_SHOT); - VectorCopy( trace.endpos, mOrigin2 ); + VectorCopy(trace.endpos, mOrigin2); - if ( mImpactFxID > 0 ) - { - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal ); + if (mImpactFxID > 0) { + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, trace.plane.normal); } - } - else - { - VectorMA( mOrigin1, mOrgOffset[0], dir, mOrigin2 ); + } else { + VectorMA(mOrigin1, mOrgOffset[0], dir, mOrigin2); } } @@ -737,58 +605,49 @@ bool CLine::Update() return true; } - //---------------------------- // // Derived Electricity Class // //---------------------------- -void CElectricity::Initialize() -{ +void CElectricity::Initialize() { mRefEnt.frame = Q_flrand(0.0f, 1.0f) * 1265536; mRefEnt.endTime = cg.time + (mTimeEnd - mTimeStart); - if ( mFlags & FX_DEPTH_HACK ) - { + if (mFlags & FX_DEPTH_HACK) { mRefEnt.renderfx |= RF_DEPTHHACK; } - if ( mFlags & FX_BRANCH ) - { + if (mFlags & FX_BRANCH) { mRefEnt.renderfx |= RF_FORKED; } - if ( mFlags & FX_TAPER ) - { + if (mFlags & FX_TAPER) { mRefEnt.renderfx |= RF_TAPERED; } - if ( mFlags & FX_GROW ) - { + if (mFlags & FX_GROW) { mRefEnt.renderfx |= RF_GROW; } } //---------------------------- -void CElectricity::Draw() -{ - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); +void CElectricity::Draw() { + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); mRefEnt.angles[0] = mChaos; mRefEnt.angles[1] = mTimeEnd - mTimeStart; - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mLines++; // NOT REALLY A LINE! } //---------------------------- -bool CElectricity::Update() -{ +bool CElectricity::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } @@ -801,22 +660,19 @@ bool CElectricity::Update() return true; } - //---------------------------- // // Derived Tail Class // //---------------------------- -bool CTail::Cull() -{ - vec3_t dir; +bool CTail::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } @@ -824,88 +680,79 @@ bool CTail::Cull() } //---------------------------- -void CTail::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CTail::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; mTails++; } //---------------------------- -bool CTail::Update() -{ +bool CTail::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( !fx_freeze.integer ) - { - VectorCopy( mOrigin1, mOldOrigin ); + if (!fx_freeze.integer) { + VectorCopy(mOrigin1, mOldOrigin); } - if ( mFlags & FX_RELATIVE ) - { - if ( mClientID < 0 || mClientID >= ENTITYNUM_WORLD ) - { + if (mFlags & FX_RELATIVE) { + if (mClientID < 0 || mClientID >= ENTITYNUM_WORLD) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - vec3_t dir, org = { 0.0f }; -// vec3_t right, up; - vec3_t realVel, realAccel; + vec3_t dir, org = {0.0f}; + // vec3_t right, up; + vec3_t realVel, realAccel; // Get our current position and direction - GetOrigin( mClientID, org ); - GetDir( mClientID, dir ); + GetOrigin(mClientID, org); + GetDir(mClientID, dir); vec3_t ang, ax[3]; - vectoangles( dir, ang ); - AngleVectors( ang, ax[0], ax[1], ax[2] ); + vectoangles(dir, ang); + AngleVectors(ang, ax[0], ax[1], ax[2]); - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); // calc the real velocity and accel vectors - // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra work - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra + // work + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleration. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, (theFxHelper.mTime - mTimeStart) * 0.001f, realAccel, realVel ); + VectorMA(realVel, (theFxHelper.mTime - mTimeStart) * 0.001f, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, (theFxHelper.mTime - mTimeStart) * 0.001f, realVel, mOrigin1 ); + VectorMA(org, (theFxHelper.mTime - mTimeStart) * 0.001f, realVel, mOrigin1); // Just calc an old point some time in the past, doesn't really matter when - VectorMA( org, ((theFxHelper.mTime - mTimeStart) - 3) * 0.001f, realVel, mOldOrigin ); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + VectorMA(org, ((theFxHelper.mTime - mTimeStart) - 3) * 0.001f, realVel, mOldOrigin); + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull() ) - { + if (!Cull()) { UpdateSize(); UpdateLength(); UpdateRGB(); @@ -920,72 +767,51 @@ bool CTail::Update() } //---------------------------- -void CTail::UpdateLength() -{ +void CTail::UpdateLength() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_NONLINEAR ) - { - if ( theFxHelper.mTime > mLengthParm ) - { + if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_NONLINEAR) { + if (theFxHelper.mTime > mLengthParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) - / (float)(mTimeEnd - mLengthParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) / (float)(mTimeEnd - mLengthParm); } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mLengthParm ); - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_CLAMP ) - { - if ( theFxHelper.mTime < mLengthParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mLengthParm); + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_CLAMP) { + if (theFxHelper.mTime < mLengthParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mLengthParm - theFxHelper.mTime) - / (float)(mLengthParm - mTimeStart); - } - else - { + perc2 = (float)(mLengthParm - theFxHelper.mTime) / (float)(mLengthParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_LENGTH_RAND ) - { + if (mFlags & FX_LENGTH_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -994,37 +820,33 @@ void CTail::UpdateLength() } //---------------------------- -void CTail::CalcNewEndpoint() -{ +void CTail::CalcNewEndpoint() { vec3_t temp; // FIXME: Hmmm, this looks dumb when physics are on and a bounce happens - VectorSubtract( mOldOrigin, mOrigin1, temp ); + VectorSubtract(mOldOrigin, mOrigin1, temp); // I wish we didn't have to do a VectorNormalize every frame..... - VectorNormalize( temp ); + VectorNormalize(temp); - VectorMA( mOrigin1, mLength, temp, mRefEnt.oldorigin ); + VectorMA(mOrigin1, mLength, temp, mRefEnt.oldorigin); } - //---------------------------- // // Derived Cylinder Class // //---------------------------- -void CCylinder::Draw() -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CCylinder::Draw() { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorMA( mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorMA(mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } @@ -1032,72 +854,51 @@ void CCylinder::Draw() //---------------------------- // Update Size2 //---------------------------- -void CCylinder::UpdateSize2() -{ +void CCylinder::UpdateSize2() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_NONLINEAR ) - { - if ( theFxHelper.mTime > mSize2Parm ) - { + if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_NONLINEAR) { + if (theFxHelper.mTime > mSize2Parm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) - / (float)(mTimeEnd - mSize2Parm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) / (float)(mTimeEnd - mSize2Parm); } - if ( (mFlags & FX_SIZE2_LINEAR) ) - { + if ((mFlags & FX_SIZE2_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSize2Parm ); - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_CLAMP ) - { - if ( theFxHelper.mTime < mSize2Parm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSize2Parm); + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_CLAMP) { + if (theFxHelper.mTime < mSize2Parm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSize2Parm - theFxHelper.mTime) - / (float)(mSize2Parm - mTimeStart); - } - else - { + perc2 = (float)(mSize2Parm - theFxHelper.mTime) / (float)(mSize2Parm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE2_RAND ) - { + if (mFlags & FX_SIZE2_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -1106,11 +907,9 @@ void CCylinder::UpdateSize2() } //---------------------------- -bool CCylinder::Update() -{ +bool CCylinder::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } @@ -1125,7 +924,6 @@ bool CCylinder::Update() return true; } - //---------------------------- // // Derived Emitter Class @@ -1135,34 +933,29 @@ bool CCylinder::Update() //---------------------------- // Draw //---------------------------- -void CEmitter::Draw() -{ +void CEmitter::Draw() { // Emitters don't draw themselves, but they may need to add an attached model - if ( mFlags & FX_ATTACHED_MODEL ) - { + if (mFlags & FX_ATTACHED_MODEL) { mRefEnt.nonNormalizedAxes = qtrue; - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); // ensure that we are sized - for ( int i = 0; i < 3; i++ ) - { - VectorScale( mRefEnt.axis[i], mRefEnt.radius, mRefEnt.axis[i] ); + for (int i = 0; i < 3; i++) { + VectorScale(mRefEnt.axis[i], mRefEnt.radius, mRefEnt.axis[i]); } - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); } // If we are emitting effects, we had better be careful because just calling it every cgame frame could // either choke up the effects system on a fast machine, or look really nasty on a low end one. - if ( mFlags & FX_EMIT_FX ) - { - vec3_t org, v; - float ftime, time2, - step; - int i, t, dif; + if (mFlags & FX_EMIT_FX) { + vec3_t org, v; + float ftime, time2, step; + int i, t, dif; -#define TRAIL_RATE 8 // we "think" at about a 60hz rate +#define TRAIL_RATE 8 // we "think" at about a 60hz rate // Pick a target step distance and square it step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance; @@ -1170,71 +963,59 @@ void CEmitter::Draw() dif = 0; - for ( t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE ) - { + for (t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE) { dif += TRAIL_RATE; // ?Not sure if it's better to update this before or after updating the origin - VectorMA( mOldVelocity, dif * 0.001f, mAccel, v ); + VectorMA(mOldVelocity, dif * 0.001f, mAccel, v); // Calc the time differences ftime = dif * 0.001f; time2 = ftime * ftime * 0.5f; // Predict the new position - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { org[i] = mOldOrigin[i] + ftime * v[i] + time2 * v[i]; } // Only perform physics if this object is tagged to do so - if ( (mFlags & FX_APPLY_PHYSICS) ) - { + if ((mFlags & FX_APPLY_PHYSICS)) { bool solid; - if ( mFlags & FX_EXPENSIVE_PHYSICS ) - { + if (mFlags & FX_EXPENSIVE_PHYSICS) { solid = true; // by setting this to true, we force a real trace to happen - } - else - { + } else { // if this returns solid, we need to do a trace - solid = !!(CG_PointContents( org, ENTITYNUM_WORLD ) & MASK_SHOT); + solid = !!(CG_PointContents(org, ENTITYNUM_WORLD) & MASK_SHOT); } - if ( solid ) - { - trace_t trace; + if (solid) { + trace_t trace; - if ( mFlags & FX_USE_BBOX ) - { - theFxHelper.Trace( &trace, mOldOrigin, mMin, mMax, org, -1, MASK_SHOT ); - } - else - { - theFxHelper.Trace( &trace, mOldOrigin, NULL, NULL, org, -1, MASK_SHOT ); + if (mFlags & FX_USE_BBOX) { + theFxHelper.Trace(&trace, mOldOrigin, mMin, mMax, org, -1, MASK_SHOT); + } else { + theFxHelper.Trace(&trace, mOldOrigin, NULL, NULL, org, -1, MASK_SHOT); } // Hit something - if ( trace.fraction < 1.0f || trace.startsolid || trace.allsolid ) - { + if (trace.fraction < 1.0f || trace.startsolid || trace.allsolid) { return; } } } // Is it time to draw an effect? - if ( DistanceSquared( org, mOldOrigin ) >= step ) - { + if (DistanceSquared(org, mOldOrigin) >= step) { // Pick a new target step distance and square it step = mDensity + Q_flrand(-1.0f, 1.0f) * mVariance; step *= step; // We met the step criteria so, we should add in the effect - theFxScheduler.PlayEffect( mEmitterFxID, org, mRefEnt.axis ); + theFxScheduler.PlayEffect(mEmitterFxID, org, mRefEnt.axis); - VectorCopy( org, mOldOrigin ); - VectorCopy( v, mOldVelocity ); + VectorCopy(org, mOldOrigin); + VectorCopy(v, mOldVelocity); dif = 0; mOldTime = t; } @@ -1245,35 +1026,31 @@ void CEmitter::Draw() } //---------------------------- -bool CEmitter::Update() -{ +bool CEmitter::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } // Use this to track if we've stopped moving - VectorCopy( mOrigin1, mOldOrigin ); - VectorCopy( mVel, mOldVelocity ); + VectorCopy(mOrigin1, mOldOrigin); + VectorCopy(mVel, mOldVelocity); - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } // If the thing is no longer moving, kill the angle delta, but don't do it too quickly or it will // look very artificial. Don't do it too slowly or it will look like there is no friction. - if ( VectorCompare( mOldOrigin, mOrigin1 )) - { - VectorScale( mAngleDelta, 0.7f, mAngleDelta ); + if (VectorCompare(mOldOrigin, mOrigin1)) { + VectorScale(mAngleDelta, 0.7f, mAngleDelta); } UpdateAngles(); UpdateSize(); -// UpdateRGB(); // had wanted to do something slick whereby an emitted effect could somehow inherit these -// UpdateAlpha(); // values, but it's not a priority right now. + // UpdateRGB(); // had wanted to do something slick whereby an emitted effect could somehow inherit these + // UpdateAlpha(); // values, but it's not a priority right now. Draw(); @@ -1281,13 +1058,12 @@ bool CEmitter::Update() } //---------------------------- -void CEmitter::UpdateAngles() -{ - VectorMA( mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, mAngles ); // was 0.001f, but then you really have to jack up the delta to even notice anything - AnglesToAxis( mAngles, mRefEnt.axis ); +void CEmitter::UpdateAngles() { + VectorMA(mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, + mAngles); // was 0.001f, but then you really have to jack up the delta to even notice anything + AnglesToAxis(mAngles, mRefEnt.axis); } - //-------------------------- // // Derived Light Class @@ -1296,11 +1072,9 @@ void CEmitter::UpdateAngles() //---------------------------- // Update //---------------------------- -bool CLight::Update() -{ +bool CLight::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } @@ -1315,72 +1089,51 @@ bool CLight::Update() //---------------------------- // Update Size //---------------------------- -void CLight::UpdateSize() -{ +void CLight::UpdateSize() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) - / (float)(mTimeEnd - mTimeStart); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) - / (float)(mTimeEnd - mSizeParm); + perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mSizeParm - theFxHelper.mTime) - / (float)(mSizeParm - mTimeStart); - } - else - { + perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE_RAND ) - { + if (mFlags & FX_SIZE_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } @@ -1391,120 +1144,97 @@ void CLight::UpdateSize() //---------------------------- // Update RGB //---------------------------- -void CLight::UpdateRGB() -{ +void CLight::UpdateRGB() { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) - / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) - / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * (float)cos(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * (float)cos((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = (float)(mRGBParm - theFxHelper.mTime) - / (float)(mRGBParm - mTimeStart); - } - else - { + perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_RGB_RAND ) - { + if (mFlags & FX_RGB_RAND) { // Random simply modulates the existing value perc1 = Q_flrand(0.0f, 1.0f) * perc1; } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); + VectorScale(mRGBStart, perc1, res); - mRefEnt.lightingOrigin[0] = res[0] + ( 1.0f - perc1 ) * mRGBEnd[0]; - mRefEnt.lightingOrigin[1] = res[1] + ( 1.0f - perc1 ) * mRGBEnd[1]; - mRefEnt.lightingOrigin[2] = res[2] + ( 1.0f - perc1 ) * mRGBEnd[2]; + mRefEnt.lightingOrigin[0] = res[0] + (1.0f - perc1) * mRGBEnd[0]; + mRefEnt.lightingOrigin[1] = res[1] + (1.0f - perc1) * mRGBEnd[1]; + mRefEnt.lightingOrigin[2] = res[2] + (1.0f - perc1) * mRGBEnd[2]; } - //-------------------------- // // Derived Trail Class // //-------------------------- -#define NEW_MUZZLE 0 -#define NEW_TIP 1 -#define OLD_TIP 2 -#define OLD_MUZZLE 3 +#define NEW_MUZZLE 0 +#define NEW_TIP 1 +#define OLD_TIP 2 +#define OLD_MUZZLE 3 //---------------------------- -void CTrail::Draw() -{ - polyVert_t verts[3]; -// vec3_t color; +void CTrail::Draw() { + polyVert_t verts[3]; + // vec3_t color; // build the first tri out of the new muzzle...new tip...old muzzle - VectorCopy( mVerts[NEW_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[2].xyz ); + VectorCopy(mVerts[NEW_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[2].xyz); -// VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[NEW_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[NEW_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[NEW_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[NEW_MUZZLE].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[1].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[1].modulate[2] = mVerts[NEW_TIP].rgb[2]; verts[1].modulate[3] = mVerts[NEW_TIP].alpha; -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[2].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[2].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[2].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; @@ -1518,26 +1248,26 @@ void CTrail::Draw() verts[2].st[1] = mVerts[OLD_MUZZLE].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); // build the second tri out of the old muzzle...old tip...new tip - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[OLD_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[2].xyz ); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[OLD_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[2].xyz); -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[OLD_MUZZLE].alpha; -// VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); + // VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[OLD_TIP].rgb[0]; verts[1].modulate[1] = mVerts[OLD_TIP].rgb[1]; verts[1].modulate[2] = mVerts[OLD_TIP].rgb[2]; verts[0].modulate[3] = mVerts[OLD_TIP].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[2].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[2].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[2].modulate[2] = mVerts[NEW_TIP].rgb[2]; @@ -1551,7 +1281,7 @@ void CTrail::Draw() verts[2].st[1] = mVerts[NEW_TIP].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); drawnFx++; } @@ -1559,32 +1289,28 @@ void CTrail::Draw() //---------------------------- // Update //---------------------------- -bool CTrail::Update() -{ +bool CTrail::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } float perc = (float)(mTimeEnd - theFxHelper.mTime) / (float)(mTimeEnd - mTimeStart); - for ( int t = 0; t < 4; t++ ) - { -// mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); -// if ( mVerts[t].curAlpha < 0.0f ) -// { -// mVerts[t].curAlpha = 0.0f; -// } - -// VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); -// VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); - mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * ( 1.0f - perc ); - if ( mVerts[t].curST[0] > 1.0f ) - { + for (int t = 0; t < 4; t++) { + // mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); + // if ( mVerts[t].curAlpha < 0.0f ) + // { + // mVerts[t].curAlpha = 0.0f; + // } + + // VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); + // VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); + mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * (1.0f - perc); + if (mVerts[t].curST[0] > 1.0f) { mVerts[t].curST[0] = 1.0f; } - mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * ( 1.0f - perc ); + mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * (1.0f - perc); } Draw(); @@ -1592,30 +1318,26 @@ bool CTrail::Update() return true; } - //-------------------------- // // Derived Poly Class // //-------------------------- -bool CPoly::Cull() -{ - vec3_t dir; +bool CPoly::Cull() { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, cg.refdef.vieworg, dir ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( cg.refdef.viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(cg.refdef.viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < 24 * 24 ) - { + if (len < 24 * 24) { return true; } @@ -1623,14 +1345,12 @@ bool CPoly::Cull() } //---------------------------- -void CPoly::Draw() -{ - polyVert_t verts[MAX_CPOLY_VERTS]; +void CPoly::Draw() { + polyVert_t verts[MAX_CPOLY_VERTS]; - for ( int i = 0; i < mCount; i++ ) - { + for (int i = 0; i < mCount; i++) { // Add our midpoint and vert offset to get the actual vertex - VectorAdd( mOrigin1, mOrg[i], verts[i].xyz ); + VectorAdd(mOrigin1, mOrg[i], verts[i].xyz); // Assign the same color to each vert verts[i].modulate[0] = mRefEnt.shaderRGBA[0]; @@ -1639,36 +1359,35 @@ void CPoly::Draw() verts[i].modulate[3] = mRefEnt.shaderRGBA[3]; // Copy the ST coords - VectorCopy2( mST[i], verts[i].st ); + VectorCopy2(mST[i], verts[i].st); } // Add this poly - theFxHelper.AddPolyToScene( mRefEnt.customShader, mCount, verts ); + theFxHelper.AddPolyToScene(mRefEnt.customShader, mCount, verts); drawnFx++; } //---------------------------- -void CPoly::CalcRotateMatrix() -{ - float cosX, cosZ; - float sinX, sinZ; - float rad; +void CPoly::CalcRotateMatrix() { + float cosX, cosZ; + float sinX, sinZ; + float rad; // rotate around Z - rad = DEG2RAD( mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f ); - cosZ = cos( rad ); - sinZ = sin( rad ); + rad = DEG2RAD(mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f); + cosZ = cos(rad); + sinZ = sin(rad); // rotate around X - rad = DEG2RAD( mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f ); - cosX = cos( rad ); - sinX = sin( rad ); - -/*Pitch - aroundx Yaw - around z -1 0 0 c -s 0 -0 c -s s c 0 -0 s c 0 0 1 -*/ + rad = DEG2RAD(mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f); + cosX = cos(rad); + sinX = sin(rad); + + /*Pitch - aroundx Yaw - around z + 1 0 0 c -s 0 + 0 c -s s c 0 + 0 s c 0 0 1 + */ mRot[0][0] = cosZ; mRot[1][0] = -sinZ; mRot[2][0] = 0; @@ -1678,70 +1397,60 @@ void CPoly::CalcRotateMatrix() mRot[0][2] = sinX * sinZ; mRot[1][2] = sinX * cosZ; mRot[2][2] = cosX; -/* -// ROLL is not supported unless anyone complains, if it needs to be added, use this format -Roll - - c 0 s - 0 1 0 --s 0 c -*/ + /* + // ROLL is not supported unless anyone complains, if it needs to be added, use this format + Roll + + c 0 s + 0 1 0 + -s 0 c + */ mLastFrameTime = theFxHelper.mFrameTime; } //-------------------------------- -void CPoly::Rotate() -{ - vec3_t temp[MAX_CPOLY_VERTS]; - float dif = fabs( (double)(mLastFrameTime - theFxHelper.mFrameTime) ); +void CPoly::Rotate() { + vec3_t temp[MAX_CPOLY_VERTS]; + float dif = fabs((double)(mLastFrameTime - theFxHelper.mFrameTime)); // Very generous check with frameTimes - if ( dif > 0.5f * mLastFrameTime ) - { + if (dif > 0.5f * mLastFrameTime) { CalcRotateMatrix(); } // Multiply our rotation matrix by each of the offset verts to get their new position - for ( int i = 0; i < mCount; i++ ) - { - VectorRotate( mOrg[i], mRot, temp[i] ); - VectorCopy( temp[i], mOrg[i] ); + for (int i = 0; i < mCount; i++) { + VectorRotate(mOrg[i], mRot, temp[i]); + VectorCopy(temp[i], mOrg[i]); } } //---------------------------- // Update //---------------------------- -bool CPoly::Update() -{ - vec3_t mOldOrigin = { 0.0f }; +bool CPoly::Update() { + vec3_t mOldOrigin = {0.0f}; // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } // If our timestamp hasn't exired yet, we won't even consider doing any kind of motion - if ( theFxHelper.mTime > mTimeStamp ) - { - VectorCopy( mOrigin1, mOldOrigin ); + if (theFxHelper.mTime > mTimeStamp) { + VectorCopy(mOrigin1, mOldOrigin); - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } } - if ( !Cull() ) - { + if (!Cull()) { // only rotate when our start timestamp has expired - if ( theFxHelper.mTime > mTimeStamp ) - { + if (theFxHelper.mTime > mTimeStamp) { // Only rotate whilst moving - if ( !VectorCompare( mOldOrigin, mOrigin1 )) - { + if (!VectorCompare(mOldOrigin, mOrigin1)) { Rotate(); } } @@ -1756,32 +1465,28 @@ bool CPoly::Update() } //---------------------------- -void CPoly::PolyInit() -{ - if ( mCount < 3 ) - { +void CPoly::PolyInit() { + if (mCount < 3) { return; } - int i; - vec3_t org={0,0,0}; + int i; + vec3_t org = {0, 0, 0}; // Find our midpoint - for ( i = 0; i < mCount; i++ ) - { - VectorAdd( org, mOrg[i], org ); + for (i = 0; i < mCount; i++) { + VectorAdd(org, mOrg[i], org); } - VectorScale( org, (float)(1.0f / mCount), org ); + VectorScale(org, (float)(1.0f / mCount), org); // now store our midpoint for physics purposes - VectorCopy( org, mOrigin1 ); + VectorCopy(org, mOrigin1); // Now we process the passed in points and make it so that they aren't actually the point... // rather, they are the offset from mOrigin1. - for ( i = 0; i < mCount; i++ ) - { - VectorSubtract( mOrg[i], mOrigin1, mOrg[i] ); + for (i = 0; i < mCount; i++) { + VectorSubtract(mOrg[i], mOrigin1, mOrg[i]); } CalcRotateMatrix(); @@ -1795,15 +1500,13 @@ Bezier curve line ------------------------- */ //---------------------------- -bool CBezier::Update( void ) -{ - float ftime, time2; +bool CBezier::Update(void) { + float ftime, time2; ftime = cg.frametime * 0.001f; time2 = ftime * ftime * 0.5f; - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { mControl1[i] = mControl1[i] + ftime * mControl1Vel[i] + time2 * mControl1Vel[i]; mControl2[i] = mControl2[i] + ftime * mControl2Vel[i] + time2 * mControl2Vel[i]; } @@ -1818,49 +1521,44 @@ bool CBezier::Update( void ) } //---------------------------- -inline void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texcoord2 ) -{ - vec3_t lineDir, cross, viewDir; - static vec3_t lastEnd[2]; - polyVert_t verts[4]; - float scale; - - VectorSubtract( end, start, lineDir ); - VectorSubtract( end, cg.refdef.vieworg, viewDir ); - CrossProduct( lineDir, viewDir, cross ); - VectorNormalize( cross ); +inline void CBezier::DrawSegment(vec3_t start, vec3_t end, float texcoord1, float texcoord2) { + vec3_t lineDir, cross, viewDir; + static vec3_t lastEnd[2]; + polyVert_t verts[4]; + float scale; + + VectorSubtract(end, start, lineDir); + VectorSubtract(end, cg.refdef.vieworg, viewDir); + CrossProduct(lineDir, viewDir, cross); + VectorNormalize(cross); scale = mRefEnt.radius * 0.5f; - //Construct the oriented quad - if ( mInit ) - { - VectorCopy( lastEnd[0], verts[0].xyz ); - VectorCopy( lastEnd[1], verts[1].xyz ); - } - else - { - VectorMA( start, -scale, cross, verts[0].xyz ); - VectorMA( start, scale, cross, verts[1].xyz ); + // Construct the oriented quad + if (mInit) { + VectorCopy(lastEnd[0], verts[0].xyz); + VectorCopy(lastEnd[1], verts[1].xyz); + } else { + VectorMA(start, -scale, cross, verts[0].xyz); + VectorMA(start, scale, cross, verts[1].xyz); } verts[0].st[0] = 0.0f; verts[0].st[1] = texcoord1; - verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[0].modulate[3] = mRefEnt.shaderRGBA[3]; verts[1].st[0] = 1.0f; verts[1].st[1] = texcoord1; - verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[1].modulate[3] = mRefEnt.shaderRGBA[3]; - if ( texcoord1 == 0.0f ) - { + if (texcoord1 == 0.0f) { verts[0].modulate[0] = 0; verts[0].modulate[1] = 0; verts[0].modulate[2] = 0; @@ -1871,83 +1569,80 @@ inline void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, flo verts[1].modulate[3] = 0; } - VectorMA( end, scale, cross, verts[2].xyz ); + VectorMA(end, scale, cross, verts[2].xyz); verts[2].st[0] = 1.0f; verts[2].st[1] = texcoord2; - verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[2].modulate[3] = mRefEnt.shaderRGBA[3]; - VectorMA( end, -scale, cross, verts[3].xyz ); + VectorMA(end, -scale, cross, verts[3].xyz); verts[3].st[0] = 0.0f; verts[3].st[1] = texcoord2; - verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[3].modulate[3] = mRefEnt.shaderRGBA[3]; - cgi_R_AddPolyToScene( mRefEnt.customShader, 4, verts ); + cgi_R_AddPolyToScene(mRefEnt.customShader, 4, verts); - VectorCopy( verts[2].xyz, lastEnd[1] ); - VectorCopy( verts[3].xyz, lastEnd[0] ); + VectorCopy(verts[2].xyz, lastEnd[1]); + VectorCopy(verts[3].xyz, lastEnd[0]); mInit = true; } -const float BEZIER_RESOLUTION = 16.0f; +const float BEZIER_RESOLUTION = 16.0f; //---------------------------- -void CBezier::Draw( void ) -{ - vec3_t pos, old_pos; - float mu, mum1; - float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; - int i; +void CBezier::Draw(void) { + vec3_t pos, old_pos; + float mu, mum1; + float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; + int i; - VectorCopy( mOrigin1, old_pos ); + VectorCopy(mOrigin1, old_pos); - mInit = false; //Signify a new batch for vert gluing + mInit = false; // Signify a new batch for vert gluing // Calculate the texture coords so the texture can stretch along the whole bezier -// if ( mFlags & FXF_WRAP ) -// { -// tex = m_stScale / 1.0f; -// } + // if ( mFlags & FXF_WRAP ) + // { + // tex = m_stScale / 1.0f; + // } float mum13, mu3, group1, group2; tc1 = 0.0f; - for ( mu = incr; mu <= 1.0f; mu += incr ) - { - //Four point curve - mum1 = 1 - mu; - mum13 = mum1 * mum1 * mum1; - mu3 = mu * mu * mu; - group1 = 3 * mu * mum1 * mum1; - group2 = 3 * mu * mu *mum1; - - for ( i = 0; i < 3; i++ ) - { + for (mu = incr; mu <= 1.0f; mu += incr) { + // Four point curve + mum1 = 1 - mu; + mum13 = mum1 * mum1 * mum1; + mu3 = mu * mu * mu; + group1 = 3 * mu * mum1 * mum1; + group2 = 3 * mu * mu * mum1; + + for (i = 0; i < 3; i++) { pos[i] = mum13 * mOrigin1[i] + group1 * mControl1[i] + group2 * mControl2[i] + mu3 * mOrigin2[i]; } -// if ( m_flags & FXF_WRAP ) -// { - tc2 = mu * tex; -// } -// else -// { -// // Texture will get mapped onto each segement -// tc1 = 0.0f; -// tc2 = 1.0f; -// } - - //Draw it - DrawSegment( old_pos, pos, tc1, tc2 ); - - VectorCopy( pos, old_pos ); + // if ( m_flags & FXF_WRAP ) + // { + tc2 = mu * tex; + // } + // else + // { + // // Texture will get mapped onto each segement + // tc1 = 0.0f; + // tc2 = 1.0f; + // } + + // Draw it + DrawSegment(old_pos, pos, tc1, tc2); + + VectorCopy(pos, old_pos); tc1 = tc2; } @@ -1964,8 +1659,7 @@ Full screen flash */ //---------------------------- -bool CFlash::Update( void ) -{ +bool CFlash::Update(void) { UpdateRGB(); Draw(); @@ -1973,48 +1667,39 @@ bool CFlash::Update( void ) } //---------------------------- -void CFlash::Init( void ) -{ - vec3_t dif; - float mod = 1.0f, dis; +void CFlash::Init(void) { + vec3_t dif; + float mod = 1.0f, dis; - VectorSubtract( mOrigin1, cg.refdef.vieworg, dif ); - dis = VectorNormalize( dif ); + VectorSubtract(mOrigin1, cg.refdef.vieworg, dif); + dis = VectorNormalize(dif); - mod = DotProduct( dif, cg.refdef.viewaxis[0] ); + mod = DotProduct(dif, cg.refdef.viewaxis[0]); - if ( dis > 600 || ( mod < 0.5f && dis > 100 )) - { + if (dis > 600 || (mod < 0.5f && dis > 100)) { mod = 0.0f; - } - else if ( mod < 0.5f && dis <= 100 ) - { + } else if (mod < 0.5f && dis <= 100) { mod += 1.1f; } mod *= (1.0f - ((dis * dis) / (600.0f * 600.0f))); - VectorScale( mRGBStart, mod, mRGBStart ); - VectorScale( mRGBEnd, mod, mRGBEnd ); + VectorScale(mRGBStart, mod, mRGBStart); + VectorScale(mRGBEnd, mod, mRGBEnd); } //---------------------------- -void CFlash::Draw( void ) -{ - // Interestingly, if znear is set > than this, then the flash - // doesn't appear at all. - const float FLASH_DISTANCE_FROM_VIEWER = 8.0f; +void CFlash::Draw(void) { + // Interestingly, if znear is set > than this, then the flash + // doesn't appear at all. + const float FLASH_DISTANCE_FROM_VIEWER = 8.0f; mRefEnt.reType = RT_SPRITE; - for ( int i = 0; i < 3; i++ ) - { - if ( mRefEnt.lightingOrigin[i] > 1.0f ) - { + for (int i = 0; i < 3; i++) { + if (mRefEnt.lightingOrigin[i] > 1.0f) { mRefEnt.lightingOrigin[i] = 1.0f; - } - else if ( mRefEnt.lightingOrigin[i] < 0.0f ) - { + } else if (mRefEnt.lightingOrigin[i] < 0.0f) { mRefEnt.lightingOrigin[i] = 0.0f; } } @@ -2023,13 +1708,13 @@ void CFlash::Draw( void ) mRefEnt.shaderRGBA[2] = mRefEnt.lightingOrigin[2] * 255; mRefEnt.shaderRGBA[3] = 255; - VectorCopy( cg.refdef.vieworg, mRefEnt.origin ); - VectorMA( mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, cg.refdef.viewaxis[0], mRefEnt.origin ); + VectorCopy(cg.refdef.vieworg, mRefEnt.origin); + VectorMA(mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, cg.refdef.viewaxis[0], mRefEnt.origin); - // This is assuming that the screen is wider than it is tall. - mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan (DEG2RAD (cg.refdef.fov_x * 0.5f)); + // This is assuming that the screen is wider than it is tall. + mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan(DEG2RAD(cg.refdef.fov_x * 0.5f)); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } diff --git a/codeJK2/cgame/FxScheduler.cpp b/codeJK2/cgame/FxScheduler.cpp index fd4f9cef1c..ca9aff638a 100644 --- a/codeJK2/cgame/FxScheduler.cpp +++ b/codeJK2/cgame/FxScheduler.cpp @@ -21,19 +21,19 @@ along with this program; if not, see . */ #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #if !defined(GHOUL2_SHARED_H_INC) - #include "../game/ghoul2_shared.h" //for CGhoul2Info_v +#include "../game/ghoul2_shared.h" //for CGhoul2Info_v #endif #if !defined(G2_H_INC) - #include "../../code/ghoul2/G2.h" +#include "../../code/ghoul2/G2.h" #endif #if !defined(__Q_SHARED_H) - #include "../game/q_shared.h" +#include "../game/q_shared.h" #endif #include "cg_media.h" @@ -41,37 +41,29 @@ along with this program; if not, see . #include "qcommon/safe/string.h" #include - -CFxScheduler theFxScheduler; +CFxScheduler theFxScheduler; //----------------------------------------------------------- -void CMediaHandles::operator=(const CMediaHandles &that ) -{ +void CMediaHandles::operator=(const CMediaHandles &that) { mMediaList.clear(); - for ( size_t i = 0; i < that.mMediaList.size(); i++ ) - { - mMediaList.push_back( that.mMediaList[i] ); + for (size_t i = 0; i < that.mMediaList.size(); i++) { + mMediaList.push_back(that.mMediaList[i]); } } //------------------------------------------------------ -CFxScheduler::CFxScheduler() -{ - memset( &mEffectTemplates, 0, sizeof( mEffectTemplates )); -} +CFxScheduler::CFxScheduler() { memset(&mEffectTemplates, 0, sizeof(mEffectTemplates)); } //----------------------------------------------------------- -void SEffectTemplate::operator=(const SEffectTemplate &that) -{ +void SEffectTemplate::operator=(const SEffectTemplate &that) { mCopy = true; - Q_strncpyz( mEffectName, that.mEffectName, sizeof(mEffectName) ); + Q_strncpyz(mEffectName, that.mEffectName, sizeof(mEffectName)); mPrimitiveCount = that.mPrimitiveCount; - for( int i = 0; i < mPrimitiveCount; i++ ) - { + for (int i = 0; i < mPrimitiveCount; i++) { mPrimitives[i] = new CPrimitiveTemplate; *(mPrimitives[i]) = *(that.mPrimitives[i]); // Mark use as a copy so that we know that we should be chucked when used up @@ -90,40 +82,33 @@ void SEffectTemplate::operator=(const SEffectTemplate &that) // None // //------------------------------------------------------ -void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) -{ - int i, j; - TScheduledEffect::iterator itr, next; +void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) { + int i, j; + TScheduledEffect::iterator itr, next; // Ditch any scheduled effects itr = mFxSchedule.begin(); - while ( itr != mFxSchedule.end() ) - { + while (itr != mFxSchedule.end()) { next = itr; ++next; - mScheduledEffectsPool.Free (*itr); + mScheduledEffectsPool.Free(*itr); mFxSchedule.erase(itr); itr = next; } - if (bRemoveTemplates) - { + if (bRemoveTemplates) { // Ditch any effect templates - for ( i = 1; i < FX_MAX_EFFECTS; i++ ) - { - if ( i == idToPreserve) - { + for (i = 1; i < FX_MAX_EFFECTS; i++) { + if (i == idToPreserve) { continue; } - if ( mEffectTemplates[i].mInUse ) - { + if (mEffectTemplates[i].mInUse) { // Ditch the primitives - for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) - { + for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) { delete mEffectTemplates[i].mPrimitives[j]; } } @@ -131,21 +116,16 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= mEffectTemplates[i].mInUse = false; } - if (idToPreserve == 0) - { + if (idToPreserve == 0) { mEffectIDs.clear(); - } - else - { + } else { // Clear the effect names, but first get the name of the effect to preserve, // and restore it after clearing. fxString_t str; TEffectID::iterator iter; - for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) - { - if ((*iter).second == idToPreserve) - { + for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) { + if ((*iter).second == idToPreserve) { str = (*iter).first; break; } @@ -169,80 +149,67 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= // Return: // int handle to the effect //------------------------------------------------------ -int CFxScheduler::RegisterEffect( const char *path, bool bHasCorrectPath /*= false*/ ) -{ +int CFxScheduler::RegisterEffect(const char *path, bool bHasCorrectPath /*= false*/) { // Dealing with file names: // File names can come from two places - the editor, in which case we should use the given // path as is, and the effect file, in which case we should add the correct path and extension. // In either case we create a stripped file name to use for naming effects. // - // FIXME: this could maybe be a cstring_view, if mEffectIDs were to use a transparent comparator, but those were only added in C++14, which we don't support yet (sigh) + // FIXME: this could maybe be a cstring_view, if mEffectIDs were to use a transparent comparator, but those were only added in C++14, which we don't support + // yet (sigh) char filenameNoExt[MAX_QPATH]; // Get an extension stripped version of the file - if (bHasCorrectPath) - { + if (bHasCorrectPath) { // FIXME: this is basically COM_SkipPath, except it also accepts '\\' instead of '/' const char *last = path, *p = path; - while (*p != '\0') - { - if ((*p == '/') || (*p == '\\')) - { + while (*p != '\0') { + if ((*p == '/') || (*p == '\\')) { last = p + 1; } p++; } - COM_StripExtension( last, filenameNoExt, sizeof( filenameNoExt ) ); - } - else - { - COM_StripExtension( path, filenameNoExt, sizeof( filenameNoExt ) ); + COM_StripExtension(last, filenameNoExt, sizeof(filenameNoExt)); + } else { + COM_StripExtension(path, filenameNoExt, sizeof(filenameNoExt)); } // see if the specified file is already registered. If it is, just return the id of that file TEffectID::iterator itr; - itr = mEffectIDs.find( filenameNoExt ); + itr = mEffectIDs.find(filenameNoExt); - if ( itr != mEffectIDs.end() ) - { + if (itr != mEffectIDs.end()) { return (*itr).second; } - char correctFilenameBuffer[MAX_QPATH]; - const char *pfile; - if (bHasCorrectPath) - { + char correctFilenameBuffer[MAX_QPATH]; + const char *pfile; + if (bHasCorrectPath) { pfile = path; - } - else - { + } else { // Add on our extension and prepend the file with the default path - Com_sprintf( correctFilenameBuffer, sizeof( correctFilenameBuffer ), "%s/%s.efx", FX_FILE_PATH, filenameNoExt ); + Com_sprintf(correctFilenameBuffer, sizeof(correctFilenameBuffer), "%s/%s.efx", FX_FILE_PATH, filenameNoExt); pfile = correctFilenameBuffer; } // Let the generic parser process the whole file - CGenericParser2 parser; - if( !parser.Parse( pfile ) ) - { - if( !parser.ValidFile() ) - { - theFxHelper.Print( "RegisterEffect: INVALID file: %s\n", pfile ); + CGenericParser2 parser; + if (!parser.Parse(pfile)) { + if (!parser.ValidFile()) { + theFxHelper.Print("RegisterEffect: INVALID file: %s\n", pfile); } return false; - if( parser.ValidFile() ) - { + if (parser.ValidFile()) { return false; } } // Lets convert the effect file into something that we can work with - return ParseEffect( filenameNoExt, parser.GetBaseParseGroup() ); + return ParseEffect(filenameNoExt, parser.GetBaseParseGroup()); } - //------------------------------------------------------ // ParseEffect // Starts at ground zero, using each group header to @@ -257,51 +224,37 @@ int CFxScheduler::RegisterEffect( const char *path, bool bHasCorrectPath /*= fal // int handle of the effect //------------------------------------------------------ -int CFxScheduler::ParseEffect( const char *file, const CGPGroup& base ) -{ +int CFxScheduler::ParseEffect(const char *file, const CGPGroup &base) { int handle; - SEffectTemplate* effect = GetNewEffectTemplate( &handle, file ); + SEffectTemplate *effect = GetNewEffectTemplate(&handle, file); - if ( !handle || !effect ) - { + if (!handle || !effect) { // failure return 0; } - for( const auto& primitiveGroup : base.GetSubGroups() ) - { - static std::map< gsl::cstring_span, EPrimType, Q::CStringViewILess > primitiveTypes{ - { CSTRING_VIEW( "particle" ), Particle }, - { CSTRING_VIEW( "line" ), Line }, - { CSTRING_VIEW( "tail" ), Tail }, - { CSTRING_VIEW( "sound" ), Sound }, - { CSTRING_VIEW( "cylinder" ), Cylinder }, - { CSTRING_VIEW( "electricity" ), Electricity }, - { CSTRING_VIEW( "emitter" ), Emitter }, - { CSTRING_VIEW( "decal" ), Decal }, - { CSTRING_VIEW( "orientedparticle" ), OrientedParticle }, - { CSTRING_VIEW( "fxrunner" ), FxRunner }, - { CSTRING_VIEW( "light" ), Light }, - { CSTRING_VIEW( "cameraShake" ), CameraShake }, - { CSTRING_VIEW( "flash" ), ScreenFlash } - }; - auto pos = primitiveTypes.find( primitiveGroup.GetName() ); - if( pos != primitiveTypes.end() ) - { + for (const auto &primitiveGroup : base.GetSubGroups()) { + static std::map primitiveTypes{ + {CSTRING_VIEW("particle"), Particle}, {CSTRING_VIEW("line"), Line}, {CSTRING_VIEW("tail"), Tail}, + {CSTRING_VIEW("sound"), Sound}, {CSTRING_VIEW("cylinder"), Cylinder}, {CSTRING_VIEW("electricity"), Electricity}, + {CSTRING_VIEW("emitter"), Emitter}, {CSTRING_VIEW("decal"), Decal}, {CSTRING_VIEW("orientedparticle"), OrientedParticle}, + {CSTRING_VIEW("fxrunner"), FxRunner}, {CSTRING_VIEW("light"), Light}, {CSTRING_VIEW("cameraShake"), CameraShake}, + {CSTRING_VIEW("flash"), ScreenFlash}}; + auto pos = primitiveTypes.find(primitiveGroup.GetName()); + if (pos != primitiveTypes.end()) { CPrimitiveTemplate *prim = new CPrimitiveTemplate; prim->mType = pos->second; - prim->ParsePrimitive( primitiveGroup ); + prim->ParsePrimitive(primitiveGroup); // Add our primitive template to the effect list - AddPrimitiveToEffect( effect, prim ); + AddPrimitiveToEffect(effect, prim); } } return handle; } - //------------------------------------------------------ // AddPrimitiveToEffect // Takes a primitive and attaches it to the effect. @@ -313,16 +266,12 @@ int CFxScheduler::ParseEffect( const char *file, const CGPGroup& base ) // Return: // None //------------------------------------------------------ -void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate *prim ) -{ +void CFxScheduler::AddPrimitiveToEffect(SEffectTemplate *fx, CPrimitiveTemplate *prim) { int ct = fx->mPrimitiveCount; - if ( ct >= FX_MAX_EFFECT_COMPONENTS ) - { - theFxHelper.Print( "FxScheduler: Error--too many primitives in an effect\n" ); - } - else - { + if (ct >= FX_MAX_EFFECT_COMPONENTS) { + theFxHelper.Print("FxScheduler: Error--too many primitives in an effect\n"); + } else { fx->mPrimitives[ct] = prim; fx->mPrimitiveCount++; } @@ -340,25 +289,21 @@ void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate // Return: // the id of the added effect template //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) -{ +SEffectTemplate *CFxScheduler::GetNewEffectTemplate(int *id, const char *file) { SEffectTemplate *effect; // wanted zero to be a bogus effect ID, so we just skip it. - for ( int i = 1; i < FX_MAX_EFFECTS; i++ ) - { + for (int i = 1; i < FX_MAX_EFFECTS; i++) { effect = &mEffectTemplates[i]; - if ( !effect->mInUse ) - { + if (!effect->mInUse) { *id = i; - memset( effect, 0, sizeof( SEffectTemplate )); + memset(effect, 0, sizeof(SEffectTemplate)); // If we are a copy, we really won't have a name that we care about saving for later - if ( file ) - { + if (file) { mEffectIDs[file] = i; - Q_strncpyz( effect->mEffectName, file, sizeof(effect->mEffectName) ); + Q_strncpyz(effect->mEffectName, file, sizeof(effect->mEffectName)); } effect->mInUse = true; @@ -366,7 +311,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) } } - theFxHelper.Print( "FxScheduler: Error--reached max effects\n" ); + theFxHelper.Print("FxScheduler: Error--reached max effects\n"); *id = 0; return nullptr; } @@ -384,10 +329,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) -{ - return ( GetEffectCopy( mEffectIDs[file], newHandle ) ); -} +SEffectTemplate *CFxScheduler::GetEffectCopy(const char *file, int *newHandle) { return (GetEffectCopy(mEffectIDs[file], newHandle)); } //------------------------------------------------------ // GetEffectCopy @@ -402,28 +344,24 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) -{ - if ( fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS || !mEffectTemplates[fxHandle].mInUse ) - { +SEffectTemplate *CFxScheduler::GetEffectCopy(int fxHandle, int *newHandle) { + if (fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS || !mEffectTemplates[fxHandle].mInUse) { // Didn't even request a valid effect to copy!!! - theFxHelper.Print( "FxScheduler: Bad effect file copy request\n" ); + theFxHelper.Print("FxScheduler: Bad effect file copy request\n"); *newHandle = 0; return 0; } // never get a copy when time is frozen - if ( fx_freeze.integer ) - { + if (fx_freeze.integer) { return 0; } // Copies shouldn't have names, otherwise they could trash our stl map used for getting ID from name - SEffectTemplate *copy = GetNewEffectTemplate( newHandle, NULL ); + SEffectTemplate *copy = GetNewEffectTemplate(newHandle, NULL); - if ( copy && *newHandle ) - { + if (copy && *newHandle) { // do the effect copy and mark us as what we are *copy = mEffectTemplates[fxHandle]; copy->mCopy = true; @@ -448,17 +386,13 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) // Return: // the pointer to the desired primitive //------------------------------------------------------ -CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, const char *componentName ) -{ - if ( !effectCopy || !effectCopy->mInUse ) - { +CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy(SEffectTemplate *effectCopy, const char *componentName) { + if (!effectCopy || !effectCopy->mInUse) { return NULL; } - for ( int i = 0; i < effectCopy->mPrimitiveCount; i++ ) - { - if ( !Q_stricmp( effectCopy->mPrimitives[i]->mName, componentName )) - { + for (int i = 0; i < effectCopy->mPrimitiveCount; i++) { + if (!Q_stricmp(effectCopy->mPrimitives[i]->mName, componentName)) { // we found a match, so return it return effectCopy->mPrimitives[i]; } @@ -469,14 +403,12 @@ CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, } //------------------------------------------------------ -static void ReportPlayEffectError(int id) -{ +static void ReportPlayEffectError(int id) { #ifdef _DEBUG - theFxHelper.Print( "CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id ); + theFxHelper.Print("CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id); #endif } - //------------------------------------------------------ // PlayEffect // Handles scheduling an effect so all the components @@ -489,15 +421,14 @@ static void ReportPlayEffectError(int id) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin ) -{ - vec3_t axis[3]; +void CFxScheduler::PlayEffect(int id, vec3_t origin) { + vec3_t axis[3]; - VectorSet( axis[0], 0, 0, 1 ); - VectorSet( axis[1], 1, 0, 0 ); - VectorSet( axis[2], 0, 1, 0 ); + VectorSet(axis[0], 0, 0, 1); + VectorSet(axis[1], 1, 0, 0); + VectorSet(axis[2], 0, 1, 0); - PlayEffect( id, origin, axis ); + PlayEffect(id, origin, axis); } //------------------------------------------------------ @@ -512,15 +443,14 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin ) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward ) -{ - vec3_t axis[3]; +void CFxScheduler::PlayEffect(int id, vec3_t origin, vec3_t forward) { + vec3_t axis[3]; // Take the forward vector and create two arbitrary but perpendicular vectors - VectorCopy( forward, axis[0] ); - MakeNormalVectors( forward, axis[1], axis[2] ); + VectorCopy(forward, axis[0]); + MakeNormalVectors(forward, axis[1], axis[2]); - PlayEffect( id, origin, axis ); + PlayEffect(id, origin, axis); } //------------------------------------------------------ @@ -536,29 +466,26 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward ) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); // This is a horribly dumb thing to have to do, but QuakeIII might not have calc'd the lerpOrigin // for the entity we may be trying to bolt onto. We like having the correct origin, so we are // forced to call this function.... - if ( entNum != -1 ) - { - CG_CalcEntityLerpPositions( &cg_entities[entNum] ); + if (entNum != -1) { + CG_CalcEntityLerpPositions(&cg_entities[entNum]); } #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile); } #endif - PlayEffect( mEffectIDs[sfile], origin, axis, boltInfo, entNum ); + PlayEffect(mEffectIDs[sfile], origin, axis, boltInfo, entNum); } //------------------------------------------------------ @@ -574,30 +501,27 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t axis[3], // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, int clientID ) -{ - char sfile[MAX_QPATH]; - int id; +void CFxScheduler::PlayEffect(const char *file, int clientID) { + char sfile[MAX_QPATH]; + int id; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); id = mEffectIDs[sfile]; #ifndef FINAL_BUILD - if ( id == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (id == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif - SEffectTemplate *fx; - CPrimitiveTemplate *prim; - int i = 0; - int count = 0, delay = 0; - float factor = 0.0f; + SEffectTemplate *fx; + CPrimitiveTemplate *prim; + int i = 0; + int count = 0, delay = 0; + float factor = 0.0f; - if ( id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse ) - { + if (id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse) { // Now you've done it! ReportPlayEffectError(id); return; @@ -609,48 +533,37 @@ void CFxScheduler::PlayEffect( const char *file, int clientID ) fx = &mEffectTemplates[id]; // Loop through the primitives and schedule each bit - for ( i = 0; i < fx->mPrimitiveCount; i++ ) - { + for (i = 0; i < fx->mPrimitiveCount; i++) { prim = fx->mPrimitives[i]; count = prim->mSpawnCount.GetRoundedVal(); - if ( prim->mCopy ) - { + if (prim->mCopy) { // If we are a copy, we need to store a "how many references count" so that we // can keep the primitive template around for the correct amount of time. prim->mRefCount = count; } - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { factor = abs(prim->mSpawnDelay.GetMax() - prim->mSpawnDelay.GetMin()) / (float)count; } // Schedule the random number of bits - for ( int t = 0; t < count; t++ ) - { - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + for (int t = 0; t < count; t++) { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { delay = t * factor; - } - else - { + } else { delay = prim->mSpawnDelay.GetVal(); } // if the delay is so small, we may as well just create this bit right now - if ( delay < 1 ) - { - CreateEffect( prim, clientID, -delay ); - } - else - { - SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); + if (delay < 1) { + CreateEffect(prim, clientID, -delay); + } else { + SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); - if ( sfx == NULL ) - { - Com_Error (ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); + if (sfx == NULL) { + Com_Error(ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); return; } @@ -658,14 +571,13 @@ void CFxScheduler::PlayEffect( const char *file, int clientID ) sfx->mpTemplate = prim; sfx->mClientID = clientID; - mFxSchedule.push_front( sfx ); + mFxSchedule.push_front(sfx); } } } // We track effect templates and primitive templates separately. - if ( fx->mCopy ) - { + if (fx->mCopy) { // We don't use dynamic memory allocation, so just mark us as dead fx->mInUse = false; } @@ -684,127 +596,105 @@ void CFxScheduler::PlayEffect( const char *file, int clientID ) // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay ) -{ - vec3_t sRGB, eRGB; - vec3_t vel, accel; - vec3_t org; - int flags = 0; +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, int clientID, int delay) { + vec3_t sRGB, eRGB; + vec3_t vel, accel; + vec3_t org; + int flags = 0; // Origin calculations -- completely ignores most things //------------------------------------- - VectorSet( org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal() ); + VectorSet(org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal()); // handle RGB color - if ( fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP ) - { + if (fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP) { float perc = Q_flrand(0.0f, 1.0f); - VectorSet( sRGB, fx->mRedStart.GetVal( perc ), fx->mGreenStart.GetVal( perc ), fx->mBlueStart.GetVal( perc ) ); - VectorSet( eRGB, fx->mRedEnd.GetVal( perc ), fx->mGreenEnd.GetVal( perc ), fx->mBlueEnd.GetVal( perc ) ); - } - else - { - VectorSet( sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal() ); - VectorSet( eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal() ); + VectorSet(sRGB, fx->mRedStart.GetVal(perc), fx->mGreenStart.GetVal(perc), fx->mBlueStart.GetVal(perc)); + VectorSet(eRGB, fx->mRedEnd.GetVal(perc), fx->mGreenEnd.GetVal(perc), fx->mBlueEnd.GetVal(perc)); + } else { + VectorSet(sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal()); + VectorSet(eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal()); } // NOTE: This completely disregards a few specialty flags. - VectorSet( vel, fx->mVelX.GetVal( ), fx->mVelY.GetVal( ), fx->mVelZ.GetVal( ) ); - VectorSet( accel, fx->mAccelX.GetVal( ), fx->mAccelY.GetVal( ), fx->mAccelZ.GetVal( ) ); + VectorSet(vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal()); + VectorSet(accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal()); // If depth hack ISN'T already on, then turn it on. Otherwise, we treat a pre-existing depth_hack flag as NOT being depth_hack. // This is done because muzzle flash fx files are shared amongst all shooters, but for the player we need to do depth hack in first person.... - if ( !( fx->mFlags & FX_DEPTH_HACK ) && !cg.renderingThirdPerson ) // hack! + if (!(fx->mFlags & FX_DEPTH_HACK) && !cg.renderingThirdPerson) // hack! { flags = fx->mFlags | FX_RELATIVE | FX_DEPTH_HACK; - } - else - { + } else { flags = (fx->mFlags | FX_RELATIVE) & ~FX_DEPTH_HACK; } // We only support particles for now //------------------------ - switch( fx->mType ) - { + switch (fx->mType) { //--------- case Particle: - //--------- + //--------- - FX_AddParticle( clientID, org, vel, accel, fx->mGravity.GetVal(), - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags ); + FX_AddParticle(clientID, org, vel, accel, fx->mGravity.GetVal(), fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), + fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), + fx->mRotationDelta.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags); break; //--------- case Line: - //--------- + //--------- - FX_AddLine( clientID, org, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), flags ); + FX_AddLine(clientID, org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), flags); break; //--------- case Tail: - //--------- + //--------- - FX_AddTail( clientID, org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags ); + FX_AddTail(clientID, org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mLengthStart.GetVal(), + fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, + fx->mRGBParm.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), + fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags); break; - //--------- case Sound: - //--------- + //--------- // bolted sounds actually play on the client.... - theFxHelper.PlaySound( NULL, clientID, CHAN_WEAPON, fx->mMediaHandles.GetHandle() ); + theFxHelper.PlaySound(NULL, clientID, CHAN_WEAPON, fx->mMediaHandles.GetHandle()); break; //--------- case Light: - //--------- + //--------- // don't much care if the light stays bolted...so just add it. - if ( clientID >= 0 && clientID < ENTITYNUM_WORLD ) - { + if (clientID >= 0 && clientID < ENTITYNUM_WORLD) { // ..um, ok..... centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - FX_AddLight( cent->gent->client->renderInfo.muzzlePoint, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mFlags ); + if (cent && cent->gent && cent->gent->client) { + FX_AddLight(cent->gent->client->renderInfo.muzzlePoint, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), sRGB, eRGB, + fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mFlags); } } break; //--------- case CameraShake: - //--------- + //--------- - if ( clientID >= 0 && clientID < ENTITYNUM_WORLD ) - { + if (clientID >= 0 && clientID < ENTITYNUM_WORLD) { // ..um, ok..... centity_t *cent = &cg_entities[clientID]; - if ( cent && cent->gent && cent->gent->client ) - { - theFxHelper.CameraShake( cent->gent->currentOrigin, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal() ); + if (cent && cent->gent && cent->gent->client) { + theFxHelper.CameraShake(cent->gent->currentOrigin, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal()); } } break; @@ -814,12 +704,10 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay } // Track when we need to clean ourselves up if we are a copy - if ( fx->mCopy ) - { + if (fx->mCopy) { fx->mRefCount--; - if ( fx->mRefCount <= 0 ) - { + if (fx->mRefCount <= 0) { delete fx; } } @@ -838,37 +726,33 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, int clientID, int delay // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum ) -{ - SEffectTemplate *fx; - CPrimitiveTemplate *prim; - int i = 0; - int count = 0, delay = 0; - float factor = 0.0f; - bool forceScheduling = false; - - if ( id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse ) - { +void CFxScheduler::PlayEffect(int id, vec3_t origin, vec3_t axis[3], const int boltInfo, const int entNum) { + SEffectTemplate *fx; + CPrimitiveTemplate *prim; + int i = 0; + int count = 0, delay = 0; + float factor = 0.0f; + bool forceScheduling = false; + + if (id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse) { // Now you've done it! ReportPlayEffectError(id); return; } // Don't bother scheduling the effect if the system is currently frozen - if ( fx_freeze.integer ) - { + if (fx_freeze.integer) { return; } - int modelNum = 0, boltNum = 0; - int entityNum = entNum; + int modelNum = 0, boltNum = 0; + int entityNum = entNum; - if ( boltInfo > 0 ) - { + if (boltInfo > 0) { // extract the wraith ID from the bolt info - modelNum = ( boltInfo >> MODEL_SHIFT ) & MODEL_AND; - boltNum = ( boltInfo >> BOLT_SHIFT ) & BOLT_AND; - entityNum = ( boltInfo >> ENTITY_SHIFT ) & ENTITY_AND; + modelNum = (boltInfo >> MODEL_SHIFT) & MODEL_AND; + boltNum = (boltInfo >> BOLT_SHIFT) & BOLT_AND; + entityNum = (boltInfo >> ENTITY_SHIFT) & ENTITY_AND; // We always force ghoul bolted objects to be scheduled so that they don't play right away. forceScheduling = true; @@ -878,13 +762,11 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int fx = &mEffectTemplates[id]; // Loop through the primitives and schedule each bit - for ( i = 0; i < fx->mPrimitiveCount; i++ ) - { + for (i = 0; i < fx->mPrimitiveCount; i++) { prim = fx->mPrimitives[i]; - if ( prim->mCullRange ) - { - if ( DistanceSquared( origin, cg.refdef.vieworg ) > prim->mCullRange ) // cull range has already been squared + if (prim->mCullRange) { + if (DistanceSquared(origin, cg.refdef.vieworg) > prim->mCullRange) // cull range has already been squared { // is too far away, so don't add this primitive group continue; @@ -893,50 +775,37 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int count = prim->mSpawnCount.GetRoundedVal(); - if ( prim->mCopy ) - { + if (prim->mCopy) { // If we are a copy, we need to store a "how many references count" so that we // can keep the primitive template around for the correct amount of time. prim->mRefCount = count; } - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { factor = abs(prim->mSpawnDelay.GetMax() - prim->mSpawnDelay.GetMin()) / (float)count; } // Schedule the random number of bits - for ( int t = 0; t < count; t++ ) - { - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + for (int t = 0; t < count; t++) { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { delay = t * factor; - } - else - { + } else { delay = prim->mSpawnDelay.GetVal(); } // if the delay is so small, we may as well just create this bit right now - if ( delay < 1 && !forceScheduling ) - { - if ( boltInfo == -1 && entNum != -1 ) - { + if (delay < 1 && !forceScheduling) { + if (boltInfo == -1 && entNum != -1) { // Find out where the entity currently is - CreateEffect( prim, cg_entities[entNum].lerpOrigin, axis, -delay ); - } - else - { - CreateEffect( prim, origin, axis, -delay ); + CreateEffect(prim, cg_entities[entNum].lerpOrigin, axis, -delay); + } else { + CreateEffect(prim, origin, axis, -delay); } - } - else - { - SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); + } else { + SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); - if ( sfx == NULL ) - { - Com_Error (ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); + if (sfx == NULL) { + Com_Error(ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); return; } @@ -944,38 +813,29 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int sfx->mpTemplate = prim; sfx->mClientID = -1; - if ( boltInfo == -1 ) - { - if ( entNum == -1 ) - { + if (boltInfo == -1) { + if (entNum == -1) { // we aren't bolting, so make sure the spawn system knows this by putting -1's in these fields sfx->mBoltNum = -1; sfx->mEntNum = -1; sfx->mModelNum = 0; - if ( origin ) - { - VectorCopy( origin, sfx->mOrigin ); - } - else - { - VectorClear( sfx->mOrigin ); + if (origin) { + VectorCopy(origin, sfx->mOrigin); + } else { + VectorClear(sfx->mOrigin); } - AxisCopy( axis, sfx->mAxis ); - } - else - { + AxisCopy(axis, sfx->mAxis); + } else { // we are doing bolting onto the origin of the entity, so use a cheaper method sfx->mBoltNum = -1; sfx->mEntNum = entityNum; sfx->mModelNum = 0; - AxisCopy( axis, sfx->mAxis ); + AxisCopy(axis, sfx->mAxis); } - } - else - { + } else { // we are bolting, so store the extra info sfx->mBoltNum = boltNum; sfx->mEntNum = entityNum; @@ -985,14 +845,13 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int sfx->mStartTime++; } - mFxSchedule.push_front( sfx ); + mFxSchedule.push_front(sfx); } } } // We track effect templates and primitive templates separately. - if ( fx->mCopy ) - { + if (fx->mCopy) { // We don't use dynamic memory allocation, so just mark us as dead fx->mInUse = false; } @@ -1010,19 +869,17 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t axis[3], const int // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); - PlayEffect( mEffectIDs[sfile], origin ); + PlayEffect(mEffectIDs[sfile], origin); #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif } @@ -1039,19 +896,17 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin ) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, vec3_t forward) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof(sfile) ); + COM_StripExtension(file, sfile, sizeof(sfile)); - PlayEffect( mEffectIDs[sfile], origin, forward ); + PlayEffect(mEffectIDs[sfile], origin, forward); #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", file); } #endif } @@ -1068,61 +923,44 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward ) // Return: // none //------------------------------------------------------ -void CFxScheduler::AddScheduledEffects( void ) -{ - TScheduledEffect::iterator itr, next; - vec3_t origin; - vec3_t axis[3]; - int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; - qboolean doesBoltExist = qfalse; - - for ( itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */ ) - { +void CFxScheduler::AddScheduledEffects(void) { + TScheduledEffect::iterator itr, next; + vec3_t origin; + vec3_t axis[3]; + int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; + qboolean doesBoltExist = qfalse; + + for (itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */) { SScheduledEffect *effect = *itr; - if ( effect->mStartTime <= theFxHelper.mTime ) - { - if ( effect->mClientID >= 0 ) - { - CreateEffect( effect->mpTemplate, effect->mClientID, - theFxHelper.mTime - effect->mStartTime ); - } - else if (effect->mBoltNum == -1) - {// ok, are we spawning a bolt on effect or a normal one? - if ( effect->mEntNum != -1 ) - { + if (effect->mStartTime <= theFxHelper.mTime) { + if (effect->mClientID >= 0) { + CreateEffect(effect->mpTemplate, effect->mClientID, theFxHelper.mTime - effect->mStartTime); + } else if (effect->mBoltNum == -1) { // ok, are we spawning a bolt on effect or a normal one? + if (effect->mEntNum != -1) { // Find out where the entity currently is - CreateEffect( effect->mpTemplate, - cg_entities[effect->mEntNum].lerpOrigin, effect->mAxis, - theFxHelper.mTime - effect->mStartTime ); - } - else - { - CreateEffect( effect->mpTemplate, - effect->mOrigin, effect->mAxis, - theFxHelper.mTime - effect->mStartTime ); + CreateEffect(effect->mpTemplate, cg_entities[effect->mEntNum].lerpOrigin, effect->mAxis, theFxHelper.mTime - effect->mStartTime); + } else { + CreateEffect(effect->mpTemplate, effect->mOrigin, effect->mAxis, theFxHelper.mTime - effect->mStartTime); } - } - else - { + } else { - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - doesBoltExist=qfalse; + doesBoltExist = qfalse; // do we need to go and re-get the bolt matrix again? Since it takes time lets try and do it only once - if ((effect->mModelNum != oldModelNum) || (effect->mEntNum != oldEntNum) || (effect->mBoltNum != oldBoltIndex)) - { - if (cg_entities[effect->mEntNum].gent->ghoul2.IsValid()) - { - if (effect->mModelNum>=0&&effect->mModelNummEntNum].gent->ghoul2.size()) - { - if (cg_entities[effect->mEntNum].gent->ghoul2[effect->mModelNum].mModelindex>=0) - { + if ((effect->mModelNum != oldModelNum) || (effect->mEntNum != oldEntNum) || (effect->mBoltNum != oldBoltIndex)) { + if (cg_entities[effect->mEntNum].gent->ghoul2.IsValid()) { + if (effect->mModelNum >= 0 && effect->mModelNum < cg_entities[effect->mEntNum].gent->ghoul2.size()) { + if (cg_entities[effect->mEntNum].gent->ghoul2[effect->mModelNum].mModelindex >= 0) { // go away and get me the bolt position for this frame please - doesBoltExist = gi.G2API_GetBoltMatrix(cg_entities[effect->mEntNum].gent->ghoul2, effect->mModelNum, effect->mBoltNum, &boltMatrix, cg_entities[effect->mEntNum].lerpAngles, cg_entities[effect->mEntNum].lerpOrigin, cg.time, cgs.model_draw, cg_entities[effect->mEntNum].currentState.modelScale); + doesBoltExist = + gi.G2API_GetBoltMatrix(cg_entities[effect->mEntNum].gent->ghoul2, effect->mModelNum, effect->mBoltNum, &boltMatrix, + cg_entities[effect->mEntNum].lerpAngles, cg_entities[effect->mEntNum].lerpOrigin, cg.time, + cgs.model_draw, cg_entities[effect->mEntNum].currentState.modelScale); // set up the axis and origin we need for the actual effect spawning - origin[0] = boltMatrix.matrix[0][3]; + origin[0] = boltMatrix.matrix[0][3]; origin[1] = boltMatrix.matrix[1][3]; origin[2] = boltMatrix.matrix[2][3]; @@ -1147,19 +985,14 @@ void CFxScheduler::AddScheduledEffects( void ) } // only do this if we found the bolt - if (doesBoltExist) - { - CreateEffect( effect->mpTemplate, - origin, axis, - theFxHelper.mTime - effect->mStartTime ); + if (doesBoltExist) { + CreateEffect(effect->mpTemplate, origin, axis, theFxHelper.mTime - effect->mStartTime); } } - mScheduledEffectsPool.Free( effect ); - itr = mFxSchedule.erase( itr ); - } - else - { + mScheduledEffectsPool.Free(effect); + itr = mFxSchedule.erase(itr); + } else { ++itr; } } @@ -1181,122 +1014,100 @@ void CFxScheduler::AddScheduledEffects( void ) // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, vec3_t axis[3], int lateTime ) -{ - vec3_t org, org2, temp, - vel, accel, - sRGB, eRGB, - ang, angDelta, - ax[3]; - trace_t tr; - int emitterModel; +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, const vec3_t origin, vec3_t axis[3], int lateTime) { + vec3_t org, org2, temp, vel, accel, sRGB, eRGB, ang, angDelta, ax[3]; + trace_t tr; + int emitterModel; // We may modify the axis, so make a work copy - AxisCopy( axis, ax ); + AxisCopy(axis, ax); - if( fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD ) - { - RotatePointAroundVector( ax[1], ax[0], axis[1], Q_flrand(0.0f, 1.0f)*360.0f ); - CrossProduct( ax[0], ax[1], ax[2] ); + if (fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD) { + RotatePointAroundVector(ax[1], ax[0], axis[1], Q_flrand(0.0f, 1.0f) * 360.0f); + CrossProduct(ax[0], ax[1], ax[2]); } // Origin calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_CHEAP_ORG_CALC ) - { // let's take the easy way out - VectorSet( org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal() ); - } - else - { // time for some extra work - VectorScale( ax[0], fx->mOrigin1X.GetVal(), org ); - VectorMA( org, fx->mOrigin1Y.GetVal(), ax[1], org ); - VectorMA( org, fx->mOrigin1Z.GetVal(), ax[2], org ); + if (fx->mSpawnFlags & FX_CHEAP_ORG_CALC) { // let's take the easy way out + VectorSet(org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal()); + } else { // time for some extra work + VectorScale(ax[0], fx->mOrigin1X.GetVal(), org); + VectorMA(org, fx->mOrigin1Y.GetVal(), ax[1], org); + VectorMA(org, fx->mOrigin1Z.GetVal(), ax[2], org); } // We always add our calculated offset to the passed in origin... - VectorAdd( org, origin, org ); + VectorAdd(org, origin, org); // Now, we may need to calc a point on a sphere/ellipsoid/cylinder/disk and add that to it //---------------------------------------------------------------- - if ( fx->mSpawnFlags & FX_ORG_ON_SPHERE ) - { + if (fx->mSpawnFlags & FX_ORG_ON_SPHERE) { float x, y; float width, height; - x = DEG2RAD( Q_flrand(0.0f, 1.0f) * 360.0f ); - y = DEG2RAD( Q_flrand(0.0f, 1.0f) * 180.0f ); + x = DEG2RAD(Q_flrand(0.0f, 1.0f) * 360.0f); + y = DEG2RAD(Q_flrand(0.0f, 1.0f) * 180.0f); width = fx->mRadius.GetVal(); height = fx->mHeight.GetVal(); // calculate point on ellipse - VectorSet( temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height ); // sinx * siny, cosx * siny, cosy - VectorAdd( org, temp, org ); + VectorSet(temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height); // sinx * siny, cosx * siny, cosy + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); - MakeNormalVectors( ax[0], ax[1], ax[2] ); + VectorNormalize2(temp, ax[0]); + MakeNormalVectors(ax[0], ax[1], ax[2]); } - } - else if ( fx->mSpawnFlags & FX_ORG_ON_CYLINDER ) - { - vec3_t pt; + } else if (fx->mSpawnFlags & FX_ORG_ON_CYLINDER) { + vec3_t pt; // set up our point, then rotate around the current direction to. Make unrotated cylinder centered around 0,0,0 - VectorScale( ax[1], fx->mRadius.GetVal(), pt ); - VectorMA( pt, Q_flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt ); - RotatePointAroundVector( temp, ax[0], pt, Q_flrand(0.0f, 1.0f) * 360.0f ); + VectorScale(ax[1], fx->mRadius.GetVal(), pt); + VectorMA(pt, Q_flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt); + RotatePointAroundVector(temp, ax[0], pt, Q_flrand(0.0f, 1.0f) * 360.0f); - VectorAdd( org, temp, org ); + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { - vec3_t up={0,0,1}; + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { + vec3_t up = {0, 0, 1}; // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); + VectorNormalize2(temp, ax[0]); - if ( ax[0][2] == 1.0f ) - { + if (ax[0][2] == 1.0f) { // readjust up - VectorSet( up, 0, 1, 0 ); + VectorSet(up, 0, 1, 0); } - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); } } // There are only a few types that really use velocity and acceleration, so do extra work for those types //-------------------------------------------------------------------------------------------------------- - if ( fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter ) - { + if (fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter) { // Velocity calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE ) - { - VectorSet( vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal() ); - } - else - { // bah, do some extra work to coerce it - VectorScale( ax[0], fx->mVelX.GetVal(), vel ); - VectorMA( vel, fx->mVelY.GetVal(), ax[1], vel ); - VectorMA( vel, fx->mVelZ.GetVal(), ax[2], vel ); + if (fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE) { + VectorSet(vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal()); + } else { // bah, do some extra work to coerce it + VectorScale(ax[0], fx->mVelX.GetVal(), vel); + VectorMA(vel, fx->mVelY.GetVal(), ax[1], vel); + VectorMA(vel, fx->mVelZ.GetVal(), ax[2], vel); } // Acceleration calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE ) - { - VectorSet( accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal() ); - } - else - { - VectorScale( ax[0], fx->mAccelX.GetVal(), accel ); - VectorMA( accel, fx->mAccelY.GetVal(), ax[1], accel ); - VectorMA( accel, fx->mAccelZ.GetVal(), ax[2], accel ); + if (fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE) { + VectorSet(accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal()); + } else { + VectorScale(ax[0], fx->mAccelX.GetVal(), accel); + VectorMA(accel, fx->mAccelY.GetVal(), ax[1], accel); + VectorMA(accel, fx->mAccelZ.GetVal(), ax[2], accel); } // Gravity is completely decoupled from acceleration since it is __always__ absolute @@ -1305,17 +1116,15 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve // There may be a lag between when the effect should be created and when it actually gets created. // Since we know what the discrepancy is, we can attempt to compensate... - if ( lateTime > 0 ) - { + if (lateTime > 0) { // Calc the time differences float ftime = lateTime * 0.001f; float time2 = ftime * ftime * 0.5f; - VectorMA( vel, ftime, accel, vel ); + VectorMA(vel, ftime, accel, vel); // Predict the new position - for ( int i = 0 ; i < 3 ; i++ ) - { + for (int i = 0; i < 3; i++) { org[i] = org[i] + ftime * vel[i] + time2 * vel[i]; } } @@ -1323,253 +1132,193 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve // Line type primitives work with an origin2, so do the extra work for them //-------------------------------------------------------------------------- - if ( fx->mType == Line || fx->mType == Electricity ) - { + if (fx->mType == Line || fx->mType == Electricity) { // We may have to do a trace to find our endpoint - if ( fx->mSpawnFlags & FX_ORG2_FROM_TRACE ) - { - VectorMA( org, FX_MAX_TRACE_DIST, ax[0], temp ); + if (fx->mSpawnFlags & FX_ORG2_FROM_TRACE) { + VectorMA(org, FX_MAX_TRACE_DIST, ax[0], temp); - if ( fx->mSpawnFlags & FX_ORG2_IS_OFFSET ) - { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much + if (fx->mSpawnFlags & FX_ORG2_IS_OFFSET) { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much // we also do this pre-trace as opposed to post trace since we may have to render an impact effect // and we will want the normal at the exact endpos... - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); - VectorAdd( org2, temp, temp ); - } - else - { // I can only imagine a few cases where you might want to do this... - VectorMA( temp, fx->mOrigin2X.GetVal(), ax[0], temp ); - VectorMA( temp, fx->mOrigin2Y.GetVal(), ax[1], temp ); - VectorMA( temp, fx->mOrigin2Z.GetVal(), ax[2], temp ); + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + VectorAdd(org2, temp, temp); + } else { // I can only imagine a few cases where you might want to do this... + VectorMA(temp, fx->mOrigin2X.GetVal(), ax[0], temp); + VectorMA(temp, fx->mOrigin2Y.GetVal(), ax[1], temp); + VectorMA(temp, fx->mOrigin2Z.GetVal(), ax[2], temp); } } - theFxHelper.Trace( &tr, org, NULL, NULL, temp, -1, CONTENTS_SOLID | CONTENTS_SHOTCLIP );//MASK_SHOT ); + theFxHelper.Trace(&tr, org, NULL, NULL, temp, -1, CONTENTS_SOLID | CONTENTS_SHOTCLIP); // MASK_SHOT ); - if ( tr.startsolid || tr.allsolid ) - { - VectorCopy( org, org2 ); // this is not a very good solution - } - else - { - VectorCopy( tr.endpos, org2 ); + if (tr.startsolid || tr.allsolid) { + VectorCopy(org, org2); // this is not a very good solution + } else { + VectorCopy(tr.endpos, org2); } - if ( fx->mSpawnFlags & FX_TRACE_IMPACT_FX ) - { - PlayEffect( fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal ); - } - } - else - { - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); + if (fx->mSpawnFlags & FX_TRACE_IMPACT_FX) { + PlayEffect(fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal); } - else - { - VectorScale( ax[0], fx->mOrigin2X.GetVal(), org2 ); - VectorMA( org2, fx->mOrigin2Y.GetVal(), ax[1], org2 ); - VectorMA( org2, fx->mOrigin2Z.GetVal(), ax[2], org2 ); - - VectorAdd( org2, origin, org2 ); + } else { + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + } else { + VectorScale(ax[0], fx->mOrigin2X.GetVal(), org2); + VectorMA(org2, fx->mOrigin2Y.GetVal(), ax[1], org2); + VectorMA(org2, fx->mOrigin2Z.GetVal(), ax[2], org2); + + VectorAdd(org2, origin, org2); } - } } // end special org2 types // handle RGB color, but only for types that will use it //--------------------------------------------------------------------------- - if ( fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake ) - { - if ( fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP ) - { + if (fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake) { + if (fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP) { float perc = Q_flrand(0.0f, 1.0f); - VectorSet( sRGB, fx->mRedStart.GetVal( perc ), fx->mGreenStart.GetVal( perc ), fx->mBlueStart.GetVal( perc ) ); - VectorSet( eRGB, fx->mRedEnd.GetVal( perc ), fx->mGreenEnd.GetVal( perc ), fx->mBlueEnd.GetVal( perc ) ); - } - else - { - VectorSet( sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal() ); - VectorSet( eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal() ); + VectorSet(sRGB, fx->mRedStart.GetVal(perc), fx->mGreenStart.GetVal(perc), fx->mBlueStart.GetVal(perc)); + VectorSet(eRGB, fx->mRedEnd.GetVal(perc), fx->mGreenEnd.GetVal(perc), fx->mBlueEnd.GetVal(perc)); + } else { + VectorSet(sRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal()); + VectorSet(eRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal()); } } // Now create the appropriate effect entity //------------------------ - switch( fx->mType ) - { + switch (fx->mType) { //--------- case Particle: - //--------- + //--------- - FX_AddParticle( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddParticle(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), + fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), fx->mFlags); break; //--------- case Line: - //--------- + //--------- - FX_AddLine( org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddLine(org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags); break; //--------- case Tail: - //--------- + //--------- - FX_AddTail( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddTail(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), + fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), + fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), fx->mFlags); break; //---------------- case Electricity: - //---------------- + //---------------- - FX_AddElectricity( org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mElasticity.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddElectricity(org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mElasticity.GetVal(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), fx->mFlags); break; //--------- case Cylinder: - //--------- + //--------- - FX_AddCylinder( org, ax[0], - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mSize2Start.GetVal(), fx->mSize2End.GetVal(), fx->mSize2Parm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddCylinder(org, ax[0], fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mSize2Start.GetVal(), fx->mSize2End.GetVal(), + fx->mSize2Parm.GetVal(), fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), + fx->mFlags); break; //--------- case Emitter: - //--------- + //--------- // for chunk angles, you don't really need much control over the end result...you just want variation.. - VectorSet( ang, - fx->mAngle1.GetVal(), - fx->mAngle2.GetVal(), - fx->mAngle3.GetVal() ); + VectorSet(ang, fx->mAngle1.GetVal(), fx->mAngle2.GetVal(), fx->mAngle3.GetVal()); - vectoangles( ax[0], temp ); - VectorAdd( ang, temp, ang ); + vectoangles(ax[0], temp); + VectorAdd(ang, temp, ang); - VectorSet( angDelta, - fx->mAngle1Delta.GetVal(), - fx->mAngle2Delta.GetVal(), - fx->mAngle3Delta.GetVal() ); + VectorSet(angDelta, fx->mAngle1Delta.GetVal(), fx->mAngle2Delta.GetVal(), fx->mAngle3Delta.GetVal()); emitterModel = fx->mMediaHandles.GetHandle(); - FX_AddEmitter( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - ang, angDelta, - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mEmitterFxHandles.GetHandle(), - fx->mDensity.GetVal(), fx->mVariance.GetVal(), - fx->mLife.GetVal(), emitterModel, fx->mFlags ); + FX_AddEmitter(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), ang, angDelta, fx->mMin, fx->mMax, fx->mElasticity.GetVal(), + fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mEmitterFxHandles.GetHandle(), fx->mDensity.GetVal(), + fx->mVariance.GetVal(), fx->mLife.GetVal(), emitterModel, fx->mFlags); break; //--------- case Decal: - //--------- + //--------- // I'm calling this function ( at least for now ) because it handles projecting // the decal mark onto the surfaces properly. This is especially important for large marks. // The downside is that it's much less flexible.... - CG_ImpactMark( fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), - sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), - qtrue, fx->mSizeStart.GetVal(), qfalse ); + CG_ImpactMark(fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), qtrue, + fx->mSizeStart.GetVal(), qfalse); break; //------------------- case OrientedParticle: - //------------------- + //------------------- - FX_AddOrientedParticle( org, ax[0], vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddOrientedParticle(org, ax[0], vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), + fx->mRotationDelta.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags); break; //--------- case Sound: - //--------- + //--------- - if ( fx->mSpawnFlags & FX_SND_LESS_ATTENUATION ) - { - theFxHelper.PlaySound( org, ENTITYNUM_NONE, CHAN_LESS_ATTEN, fx->mMediaHandles.GetHandle() ); - } - else - { - theFxHelper.PlaySound( org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle() ); + if (fx->mSpawnFlags & FX_SND_LESS_ATTENUATION) { + theFxHelper.PlaySound(org, ENTITYNUM_NONE, CHAN_LESS_ATTEN, fx->mMediaHandles.GetHandle()); + } else { + theFxHelper.PlaySound(org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle()); } break; //--------- case FxRunner: - //--------- + //--------- - PlayEffect( fx->mPlayFxHandles.GetHandle(), org, ax ); + PlayEffect(fx->mPlayFxHandles.GetHandle(), org, ax); break; //--------- case Light: - //--------- + //--------- - FX_AddLight( org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mFlags ); + FX_AddLight(org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), + fx->mFlags); break; //--------- case CameraShake: - //--------- + //--------- // It calculates how intense the shake should be based on how close you are to the origin you pass in here // elasticity is actually the intensity...radius is the distance in which the shake will have some effect // life is how long the effect lasts. - theFxHelper.CameraShake( org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal() ); + theFxHelper.CameraShake(org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal()); break; //-------------- case ScreenFlash: - //-------------- + //-------------- - FX_AddFlash( org, - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags ); + FX_AddFlash(org, sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), fx->mFlags); break; default: @@ -1577,12 +1326,10 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ve } // Track when we need to clean ourselves up if we are a copy - if ( fx->mCopy ) - { + if (fx->mCopy) { fx->mRefCount--; - if ( fx->mRefCount <= 0 ) - { + if (fx->mRefCount <= 0) { delete fx; } } diff --git a/codeJK2/cgame/FxSystem.cpp b/codeJK2/cgame/FxSystem.cpp index d4a47ffd0f..3cc552ee33 100644 --- a/codeJK2/cgame/FxSystem.cpp +++ b/codeJK2/cgame/FxSystem.cpp @@ -21,54 +21,47 @@ along with this program; if not, see . */ #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif -extern vmCvar_t fx_debug; -extern vmCvar_t fx_freeze; +extern vmCvar_t fx_debug; +extern vmCvar_t fx_freeze; -extern void CG_ExplosionEffects( vec3_t origin, float intensity, int radius, int time ); +extern void CG_ExplosionEffects(vec3_t origin, float intensity, int radius, int time); // Stuff for the FxHelper //------------------------------------------------------ -void SFxHelper::Init() -{ +void SFxHelper::Init() { mTime = 0; mOldTime = 0; mTimeFrozen = false; } //------------------------------------------------------ -void SFxHelper::Print( const char *msg, ... ) -{ +void SFxHelper::Print(const char *msg, ...) { #ifndef FINAL_BUILD - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start( argptr, msg ); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end( argptr ); - - gi.Printf( text ); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); + + gi.Printf(text); #endif } //------------------------------------------------------ -void SFxHelper::AdjustTime( int frameTime ) -{ - if ( fx_freeze.integer || ( frameTime <= 0 )) - { +void SFxHelper::AdjustTime(int frameTime) { + if (fx_freeze.integer || (frameTime <= 0)) { // Allow no time progression when we are paused. mFrameTime = 0; mFloatFrameTime = 0.0f; - } - else - { - if ( !cg_paused.integer ) - { - if ( frameTime > 1500 ) // hack + } else { + if (!cg_paused.integer) { + if (frameTime > 1500) // hack { frameTime = 200; } @@ -81,79 +74,50 @@ void SFxHelper::AdjustTime( int frameTime ) } //------------------------------------------------------ -int SFxHelper::OpenFile( const char *file, fileHandle_t *fh, int mode ) -{ -// char path[256]; +int SFxHelper::OpenFile(const char *file, fileHandle_t *fh, int mode) { + // char path[256]; -// sprintf( path, "%s/%s", FX_FILE_PATH, file ); - return cgi_FS_FOpenFile( file, fh, FS_READ ); + // sprintf( path, "%s/%s", FX_FILE_PATH, file ); + return cgi_FS_FOpenFile(file, fh, FS_READ); } //------------------------------------------------------ -int SFxHelper::ReadFile( void *data, int len, fileHandle_t fh ) -{ - return cgi_FS_Read( data, len, fh ); -} +int SFxHelper::ReadFile(void *data, int len, fileHandle_t fh) { return cgi_FS_Read(data, len, fh); } //------------------------------------------------------ -void SFxHelper::CloseFile( fileHandle_t fh ) -{ - cgi_FS_FCloseFile( fh ); -} +void SFxHelper::CloseFile(fileHandle_t fh) { cgi_FS_FCloseFile(fh); } //------------------------------------------------------ -void SFxHelper::PlaySound( vec3_t org, int entityNum, int entchannel, int sfxHandle ) -{ - cgi_S_StartSound( org, entityNum, entchannel, sfxHandle ); -} +void SFxHelper::PlaySound(vec3_t org, int entityNum, int entchannel, int sfxHandle) { cgi_S_StartSound(org, entityNum, entchannel, sfxHandle); } //------------------------------------------------------ -void SFxHelper::Trace( trace_t *tr, vec3_t start, vec3_t min, vec3_t max, - vec3_t end, int skipEntNum, int flags ) -{ - CG_Trace( tr, start, min, max, end, skipEntNum, flags ); +void SFxHelper::Trace(trace_t *tr, vec3_t start, vec3_t min, vec3_t max, vec3_t end, int skipEntNum, int flags) { + CG_Trace(tr, start, min, max, end, skipEntNum, flags); } //------------------------------------------------------ -void SFxHelper::AddFxToScene( refEntity_t *ent ) -{ - cgi_R_AddRefEntityToScene( ent ); -} +void SFxHelper::AddFxToScene(refEntity_t *ent) { cgi_R_AddRefEntityToScene(ent); } //------------------------------------------------------ -int SFxHelper::RegisterShader( const gsl::cstring_span& shader ) -{ +int SFxHelper::RegisterShader(const gsl::cstring_span &shader) { // TODO: it would be nice to change the ABI here to allow for passing of string views - return cgi_R_RegisterShader( std::string( shader.begin(), shader.end() ).c_str() ); + return cgi_R_RegisterShader(std::string(shader.begin(), shader.end()).c_str()); } //------------------------------------------------------ -int SFxHelper::RegisterSound( const gsl::cstring_span& sound ) -{ +int SFxHelper::RegisterSound(const gsl::cstring_span &sound) { // TODO: it would be nice to change the ABI here to allow for passing of string views - return cgi_S_RegisterSound( std::string( sound.begin(), sound.end() ).c_str() ); + return cgi_S_RegisterSound(std::string(sound.begin(), sound.end()).c_str()); } //------------------------------------------------------ -int SFxHelper::RegisterModel( const gsl::cstring_span& model ) -{ - return cgi_R_RegisterModel( std::string( model.begin(), model.end() ).c_str() ); -} +int SFxHelper::RegisterModel(const gsl::cstring_span &model) { return cgi_R_RegisterModel(std::string(model.begin(), model.end()).c_str()); } //------------------------------------------------------ -void SFxHelper::AddLightToScene( vec3_t org, float radius, float red, float green, float blue ) -{ - cgi_R_AddLightToScene( org, radius, red, green, blue ); -} +void SFxHelper::AddLightToScene(vec3_t org, float radius, float red, float green, float blue) { cgi_R_AddLightToScene(org, radius, red, green, blue); } //------------------------------------------------------ -void SFxHelper::AddPolyToScene( int shader, int count, polyVert_t *verts ) -{ - cgi_R_AddPolyToScene( shader, count, verts ); -} +void SFxHelper::AddPolyToScene(int shader, int count, polyVert_t *verts) { cgi_R_AddPolyToScene(shader, count, verts); } //------------------------------------------------------ -void SFxHelper::CameraShake( vec3_t origin, float intensity, int radius, int time ) -{ - CG_ExplosionEffects( origin, intensity, radius, time ); -} \ No newline at end of file +void SFxHelper::CameraShake(vec3_t origin, float intensity, int radius, int time) { CG_ExplosionEffects(origin, intensity, radius, time); } \ No newline at end of file diff --git a/codeJK2/cgame/FxTemplate.cpp b/codeJK2/cgame/FxTemplate.cpp index 7e06a808fb..768af76086 100644 --- a/codeJK2/cgame/FxTemplate.cpp +++ b/codeJK2/cgame/FxTemplate.cpp @@ -21,7 +21,7 @@ along with this program; if not, see . */ #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif #include "../game/genericparser2.h" @@ -39,8 +39,7 @@ along with this program; if not, see . // Return: // none //------------------------------------------------------ -CPrimitiveTemplate::CPrimitiveTemplate() -{ +CPrimitiveTemplate::CPrimitiveTemplate() { // We never start out as a copy or with a name mCopy = false; mName[0] = 0; @@ -48,132 +47,131 @@ CPrimitiveTemplate::CPrimitiveTemplate() mFlags = mSpawnFlags = 0; - mLife.SetRange( 1.0f, 1.0f ); - mSpawnCount.SetRange( 1.0f, 1.0f ); - mRadius.SetRange( 1.0f, 1.0f ); - mHeight.SetRange( 1.0f, 1.0f ); + mLife.SetRange(1.0f, 1.0f); + mSpawnCount.SetRange(1.0f, 1.0f); + mRadius.SetRange(1.0f, 1.0f); + mHeight.SetRange(1.0f, 1.0f); - VectorSet( mMin, 0.0f, 0.0f, 0.0f ); - VectorSet( mMax, 0.0f, 0.0f, 0.0f ); + VectorSet(mMin, 0.0f, 0.0f, 0.0f); + VectorSet(mMax, 0.0f, 0.0f, 0.0f); - mRedStart.SetRange( 1.0f, 1.0f ); - mGreenStart.SetRange( 1.0f, 1.0f ); - mBlueStart.SetRange( 1.0f, 1.0f ); + mRedStart.SetRange(1.0f, 1.0f); + mGreenStart.SetRange(1.0f, 1.0f); + mBlueStart.SetRange(1.0f, 1.0f); - mRedEnd.SetRange( 1.0f, 1.0f ); - mGreenEnd.SetRange( 1.0f, 1.0f ); - mBlueEnd.SetRange( 1.0f, 1.0f ); + mRedEnd.SetRange(1.0f, 1.0f); + mGreenEnd.SetRange(1.0f, 1.0f); + mBlueEnd.SetRange(1.0f, 1.0f); - mAlphaStart.SetRange( 1.0f, 1.0f ); - mAlphaEnd.SetRange( 1.0f, 1.0f ); + mAlphaStart.SetRange(1.0f, 1.0f); + mAlphaEnd.SetRange(1.0f, 1.0f); - mSizeStart.SetRange( 1.0f, 1.0f ); - mSizeEnd.SetRange( 1.0f, 1.0f ); + mSizeStart.SetRange(1.0f, 1.0f); + mSizeEnd.SetRange(1.0f, 1.0f); - mSize2Start.SetRange( 1.0f, 1.0f ); - mSize2End.SetRange( 1.0f, 1.0f ); + mSize2Start.SetRange(1.0f, 1.0f); + mSize2End.SetRange(1.0f, 1.0f); - mLengthStart.SetRange( 1.0f, 1.0f ); - mLengthEnd.SetRange( 1.0f, 1.0f ); + mLengthStart.SetRange(1.0f, 1.0f); + mLengthEnd.SetRange(1.0f, 1.0f); - mTexCoordS.SetRange( 1.0f, 1.0f ); - mTexCoordT.SetRange( 1.0f, 1.0f ); + mTexCoordS.SetRange(1.0f, 1.0f); + mTexCoordT.SetRange(1.0f, 1.0f); - mVariance.SetRange( 1.0f, 1.0f ); - mDensity.SetRange( 10.0f, 10.0f );// default this high so it doesn't do bad things + mVariance.SetRange(1.0f, 1.0f); + mDensity.SetRange(10.0f, 10.0f); // default this high so it doesn't do bad things } //----------------------------------------------------------- -void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) -{ +void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) { // I'm assuming that doing a memcpy wouldn't work here // If you are looking at this and know a better way to do this, please tell me. - Q_strncpyz( mName, that.mName, sizeof(mName) ); + Q_strncpyz(mName, that.mName, sizeof(mName)); - mType = that.mType; + mType = that.mType; - mSpawnDelay = that.mSpawnDelay; - mSpawnCount = that.mSpawnCount; - mLife = that.mLife; - mCullRange = that.mCullRange; + mSpawnDelay = that.mSpawnDelay; + mSpawnCount = that.mSpawnCount; + mLife = that.mLife; + mCullRange = that.mCullRange; - mMediaHandles = that.mMediaHandles; - mImpactFxHandles = that.mImpactFxHandles; - mDeathFxHandles = that.mDeathFxHandles; - mEmitterFxHandles = that.mEmitterFxHandles; - mPlayFxHandles = that.mPlayFxHandles; + mMediaHandles = that.mMediaHandles; + mImpactFxHandles = that.mImpactFxHandles; + mDeathFxHandles = that.mDeathFxHandles; + mEmitterFxHandles = that.mEmitterFxHandles; + mPlayFxHandles = that.mPlayFxHandles; - mFlags = that.mFlags; - mSpawnFlags = that.mSpawnFlags; + mFlags = that.mFlags; + mSpawnFlags = that.mSpawnFlags; - VectorCopy( that.mMin, mMin ); - VectorCopy( that.mMax, mMax ); + VectorCopy(that.mMin, mMin); + VectorCopy(that.mMax, mMax); - mOrigin1X = that.mOrigin1X; - mOrigin1Y = that.mOrigin1Y; - mOrigin1Z = that.mOrigin1Z; + mOrigin1X = that.mOrigin1X; + mOrigin1Y = that.mOrigin1Y; + mOrigin1Z = that.mOrigin1Z; - mOrigin2X = that.mOrigin2X; - mOrigin2Y = that.mOrigin2Y; - mOrigin2Z = that.mOrigin2Z; + mOrigin2X = that.mOrigin2X; + mOrigin2Y = that.mOrigin2Y; + mOrigin2Z = that.mOrigin2Z; - mRadius = that.mRadius; - mHeight = that.mHeight; + mRadius = that.mRadius; + mHeight = that.mHeight; - mRotation = that.mRotation; - mRotationDelta = that.mRotationDelta; + mRotation = that.mRotation; + mRotationDelta = that.mRotationDelta; - mAngle1 = that.mAngle1; - mAngle2 = that.mAngle2; - mAngle3 = that.mAngle3; + mAngle1 = that.mAngle1; + mAngle2 = that.mAngle2; + mAngle3 = that.mAngle3; - mAngle1Delta = that.mAngle1Delta; - mAngle2Delta = that.mAngle2Delta; - mAngle3Delta = that.mAngle3Delta; + mAngle1Delta = that.mAngle1Delta; + mAngle2Delta = that.mAngle2Delta; + mAngle3Delta = that.mAngle3Delta; - mVelX = that.mVelX; - mVelY = that.mVelY; - mVelZ = that.mVelZ; + mVelX = that.mVelX; + mVelY = that.mVelY; + mVelZ = that.mVelZ; - mAccelX = that.mAccelX; - mAccelY = that.mAccelY; - mAccelZ = that.mAccelZ; + mAccelX = that.mAccelX; + mAccelY = that.mAccelY; + mAccelZ = that.mAccelZ; - mGravity = that.mGravity; + mGravity = that.mGravity; - mDensity = that.mDensity; - mVariance = that.mVariance; + mDensity = that.mDensity; + mVariance = that.mVariance; - mRedStart = that.mRedStart; - mGreenStart = that.mGreenStart; - mBlueStart = that.mBlueStart; + mRedStart = that.mRedStart; + mGreenStart = that.mGreenStart; + mBlueStart = that.mBlueStart; - mRedEnd = that.mRedEnd; - mGreenEnd = that.mGreenEnd; - mBlueEnd = that.mBlueEnd; + mRedEnd = that.mRedEnd; + mGreenEnd = that.mGreenEnd; + mBlueEnd = that.mBlueEnd; - mRGBParm = that.mRGBParm; + mRGBParm = that.mRGBParm; - mAlphaStart = that.mAlphaStart; - mAlphaEnd = that.mAlphaEnd; - mAlphaParm = that.mAlphaParm; + mAlphaStart = that.mAlphaStart; + mAlphaEnd = that.mAlphaEnd; + mAlphaParm = that.mAlphaParm; - mSizeStart = that.mSizeStart; - mSizeEnd = that.mSizeEnd; - mSizeParm = that.mSizeParm; + mSizeStart = that.mSizeStart; + mSizeEnd = that.mSizeEnd; + mSizeParm = that.mSizeParm; - mSize2Start = that.mSize2Start; - mSize2End = that.mSize2End; - mSize2Parm = that.mSize2Parm; + mSize2Start = that.mSize2Start; + mSize2End = that.mSize2End; + mSize2Parm = that.mSize2Parm; - mLengthStart = that.mLengthStart; - mLengthEnd = that.mLengthEnd; - mLengthParm = that.mLengthParm; + mLengthStart = that.mLengthStart; + mLengthEnd = that.mLengthEnd; + mLengthParm = that.mLengthParm; - mTexCoordS = that.mTexCoordS; - mTexCoordT = that.mTexCoordT; + mTexCoordS = that.mTexCoordS; + mTexCoordT = that.mTexCoordT; - mElasticity = that.mElasticity; + mElasticity = that.mElasticity; } //------------------------------------------------------ @@ -189,24 +187,19 @@ void CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFloat( const gsl::cstring_span& val, float& min, float& max ) -{ +bool CPrimitiveTemplate::ParseFloat(const gsl::cstring_span &val, float &min, float &max) { // attempt to read out the values - int v = Q::sscanf( val, min, max ); + int v = Q::sscanf(val, min, max); - if ( v == 0 ) - { // nothing was there, failure + if (v == 0) { // nothing was there, failure return false; - } - else if ( v == 1 ) - { // only one field entered, this is ok, but we should copy min into max + } else if (v == 1) { // only one field entered, this is ok, but we should copy min into max max = min; } return true; } - //------------------------------------------------------ // ParseVector // Removes up to six values from a passed in string and @@ -220,60 +213,44 @@ bool CPrimitiveTemplate::ParseFloat( const gsl::cstring_span& val, float& min, f // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVector( const gsl::cstring_span& val, vec3_t min, vec3_t max ) -{ +bool CPrimitiveTemplate::ParseVector(const gsl::cstring_span &val, vec3_t min, vec3_t max) { // we don't allow passing in a null - if ( min == nullptr || max == nullptr ) - { + if (min == nullptr || max == nullptr) { return false; } // attempt to read out our values - int v = Q::sscanf( val, min[0], min[1], min[2], max[0], max[1], max[2] ); + int v = Q::sscanf(val, min[0], min[1], min[2], max[0], max[1], max[2]); // Check for completeness - if ( v < 3 || v == 4 || v == 5 ) - { // not a complete value + if (v < 3 || v == 4 || v == 5) { // not a complete value return false; - } - else if ( v == 3 ) - { // only a min was entered, so copy the result into max - VectorCopy( min, max ); + } else if (v == 3) { // only a min was entered, so copy the result into max + VectorCopy(min, max); } return true; } -namespace detail -{ - // calls Q::sscanf with the elements of the given array as arguments +namespace detail { +// calls Q::sscanf with the elements of the given array as arguments - template< std::size_t remaining > - struct ScanStrings - { - template< std::size_t count, typename... Args > - static int call( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr, Args&... args ) - { - return ScanStrings< remaining - 1 >::call( val, arr, arr[ remaining - 1 ], args... ); - } - }; +template struct ScanStrings { + template static int call(const gsl::cstring_span &val, std::array &arr, Args &...args) { + return ScanStrings::call(val, arr, arr[remaining - 1], args...); + } +}; - template<> - struct ScanStrings< 0 > - { - template< std::size_t count, typename... Args > - static int call( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr, Args&... args ) - { - return Q::sscanf( val, args... ); - } - }; -} +template <> struct ScanStrings<0> { + template static int call(const gsl::cstring_span &val, std::array &arr, Args &...args) { + return Q::sscanf(val, args...); + } +}; +} // namespace detail -template< std::size_t count > -static gsl::span< gsl::cstring_span > scanStrings( const gsl::cstring_span& val, std::array< gsl::cstring_span, count >& arr ) -{ - int numParsed = detail::ScanStrings< count >::call( val, arr ); - return{ arr.data(), arr.data() + numParsed }; +template static gsl::span scanStrings(const gsl::cstring_span &val, std::array &arr) { + int numParsed = detail::ScanStrings::call(val, arr); + return {arr.data(), arr.data() + numParsed}; } //------------------------------------------------------ @@ -289,34 +266,26 @@ static gsl::span< gsl::cstring_span > scanStrings( const gsl::cstring_span& val, // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGroupFlags( const gsl::cstring_span& val, int& flags ) -{ +bool CPrimitiveTemplate::ParseGroupFlags(const gsl::cstring_span &val, int &flags) { // For a sub group, really you probably only have one or two flags set - std::array< gsl::cstring_span, 4 > flag; + std::array flag; - const auto availableFlag = scanStrings( val, flag ); + const auto availableFlag = scanStrings(val, flag); // Clear out the flags field, then convert the flag string to an actual value ( use generic flags ) flags = 0; bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "linear" ), FX_LINEAR }, - { CSTRING_VIEW( "nonlinear" ), FX_NONLINEAR }, - { CSTRING_VIEW( "wave" ), FX_WAVE }, - { CSTRING_VIEW( "random" ), FX_RAND }, - { CSTRING_VIEW( "clamp" ), FX_CLAMP }, + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("linear"), FX_LINEAR}, {CSTRING_VIEW("nonlinear"), FX_NONLINEAR}, {CSTRING_VIEW("wave"), FX_WAVE}, + {CSTRING_VIEW("random"), FX_RAND}, {CSTRING_VIEW("clamp"), FX_CLAMP}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { ok = false; - } - else - { + } else { flags |= pos->second; } } @@ -334,13 +303,11 @@ bool CPrimitiveTemplate::ParseGroupFlags( const gsl::cstring_span& val, int& fla // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMin( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseMin(const gsl::cstring_span &val) { vec3_t min; - if ( ParseVector( val, min, min ) == true ) - { - VectorCopy( min, mMin ); + if (ParseVector(val, min, min) == true) { + VectorCopy(min, mMin); // We assume that if a min is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -360,13 +327,11 @@ bool CPrimitiveTemplate::ParseMin( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMax( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseMax(const gsl::cstring_span &val) { vec3_t max; - if ( ParseVector( val, max, max ) == true ) - { - VectorCopy( max, mMax ); + if (ParseVector(val, max, max) == true) { + VectorCopy(max, mMax); // We assume that if a max is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -386,13 +351,11 @@ bool CPrimitiveTemplate::ParseMax( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLife( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLife(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLife.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLife.SetRange(min, max); return true; } @@ -409,13 +372,11 @@ bool CPrimitiveTemplate::ParseLife( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDelay( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseDelay(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSpawnDelay.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSpawnDelay.SetRange(min, max); return true; } @@ -432,13 +393,11 @@ bool CPrimitiveTemplate::ParseDelay( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseCount( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseCount(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSpawnCount.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSpawnCount.SetRange(min, max); return true; } @@ -455,17 +414,15 @@ bool CPrimitiveTemplate::ParseCount( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseElasticity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseElasticity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mElasticity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mElasticity.SetRange(min, max); // We assume that if elasticity is set that we are using physics, but don't assume we are // using a bounding box unless a min/max are explicitly set -// mFlags |= FX_APPLY_PHYSICS; + // mFlags |= FX_APPLY_PHYSICS; return true; } @@ -482,15 +439,13 @@ bool CPrimitiveTemplate::ParseElasticity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin1( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseOrigin1(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin1X.SetRange( min[0], max[0] ); - mOrigin1Y.SetRange( min[1], max[1] ); - mOrigin1Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin1X.SetRange(min[0], max[0]); + mOrigin1Y.SetRange(min[1], max[1]); + mOrigin1Z.SetRange(min[2], max[2]); return true; } @@ -507,15 +462,13 @@ bool CPrimitiveTemplate::ParseOrigin1( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin2( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseOrigin2(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin2X.SetRange( min[0], max[0] ); - mOrigin2Y.SetRange( min[1], max[1] ); - mOrigin2Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin2X.SetRange(min[0], max[0]); + mOrigin2Y.SetRange(min[1], max[1]); + mOrigin2Z.SetRange(min[2], max[2]); return true; } @@ -532,13 +485,11 @@ bool CPrimitiveTemplate::ParseOrigin2( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRadius( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRadius(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mRadius.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mRadius.SetRange(min, max); return true; } @@ -555,13 +506,11 @@ bool CPrimitiveTemplate::ParseRadius( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseHeight( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseHeight(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mHeight.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mHeight.SetRange(min, max); return true; } @@ -578,13 +527,11 @@ bool CPrimitiveTemplate::ParseHeight( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotation( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRotation(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == qtrue ) - { - mRotation.SetRange( min, max ); + if (ParseFloat(val, min, max) == qtrue) { + mRotation.SetRange(min, max); return true; } @@ -601,13 +548,11 @@ bool CPrimitiveTemplate::ParseRotation( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotationDelta( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRotationDelta(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == qtrue ) - { - mRotationDelta.SetRange( min, max ); + if (ParseFloat(val, min, max) == qtrue) { + mRotationDelta.SetRange(min, max); return true; } @@ -624,15 +569,13 @@ bool CPrimitiveTemplate::ParseRotationDelta( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngle( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAngle(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1.SetRange( min[0], max[0] ); - mAngle2.SetRange( min[1], max[1] ); - mAngle3.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1.SetRange(min[0], max[0]); + mAngle2.SetRange(min[1], max[1]); + mAngle3.SetRange(min[2], max[2]); return true; } @@ -649,15 +592,13 @@ bool CPrimitiveTemplate::ParseAngle( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngleDelta( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAngleDelta(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1Delta.SetRange( min[0], max[0] ); - mAngle2Delta.SetRange( min[1], max[1] ); - mAngle3Delta.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1Delta.SetRange(min[0], max[0]); + mAngle2Delta.SetRange(min[1], max[1]); + mAngle3Delta.SetRange(min[2], max[2]); return true; } @@ -674,15 +615,13 @@ bool CPrimitiveTemplate::ParseAngleDelta( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVelocity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseVelocity(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mVelX.SetRange( min[0], max[0] ); - mVelY.SetRange( min[1], max[1] ); - mVelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mVelX.SetRange(min[0], max[0]); + mVelY.SetRange(min[1], max[1]); + mVelZ.SetRange(min[2], max[2]); return true; } @@ -700,37 +639,32 @@ bool CPrimitiveTemplate::ParseVelocity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseFlags(const gsl::cstring_span &val) { // For a primitive, really you probably only have two or less flags set - std::array< gsl::cstring_span, 7 > flag; - - const auto availableFlag = scanStrings( val, flag ); - - bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "useModel" ), FX_ATTACHED_MODEL }, - { CSTRING_VIEW( "useBBox" ), FX_USE_BBOX }, - { CSTRING_VIEW( "usePhysics" ), FX_APPLY_PHYSICS }, - { CSTRING_VIEW( "expensivePhysics" ), FX_EXPENSIVE_PHYSICS }, - { CSTRING_VIEW( "impactKills" ), FX_KILL_ON_IMPACT }, - { CSTRING_VIEW( "impactFx" ), FX_IMPACT_RUNS_FX }, - { CSTRING_VIEW( "deathFx" ), FX_DEATH_RUNS_FX }, - { CSTRING_VIEW( "useAlpha" ), FX_USE_ALPHA }, - { CSTRING_VIEW( "emitFx" ), FX_EMIT_FX }, - { CSTRING_VIEW( "depthHack" ), FX_DEPTH_HACK }, - { CSTRING_VIEW( "setShaderTime" ), FX_SET_SHADER_TIME }, + std::array flag; + + const auto availableFlag = scanStrings(val, flag); + + bool ok = true; + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("useModel"), FX_ATTACHED_MODEL}, + {CSTRING_VIEW("useBBox"), FX_USE_BBOX}, + {CSTRING_VIEW("usePhysics"), FX_APPLY_PHYSICS}, + {CSTRING_VIEW("expensivePhysics"), FX_EXPENSIVE_PHYSICS}, + {CSTRING_VIEW("impactKills"), FX_KILL_ON_IMPACT}, + {CSTRING_VIEW("impactFx"), FX_IMPACT_RUNS_FX}, + {CSTRING_VIEW("deathFx"), FX_DEATH_RUNS_FX}, + {CSTRING_VIEW("useAlpha"), FX_USE_ALPHA}, + {CSTRING_VIEW("emitFx"), FX_EMIT_FX}, + {CSTRING_VIEW("depthHack"), FX_DEPTH_HACK}, + {CSTRING_VIEW("setShaderTime"), FX_SET_SHADER_TIME}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { // we have badness going on, but continue on in case there are any valid fields in here + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { // we have badness going on, but continue on in case there are any valid fields in here ok = false; - } - else - { + } else { mFlags |= pos->second; } } @@ -749,39 +683,34 @@ bool CPrimitiveTemplate::ParseFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSpawnFlags( const gsl::cstring_span& val ) -{ - std::array< gsl::cstring_span, 7 > flag; +bool CPrimitiveTemplate::ParseSpawnFlags(const gsl::cstring_span &val) { + std::array flag; // For a primitive, really you probably only have two or less flags set - const auto availableFlag = scanStrings( val, flag ); + const auto availableFlag = scanStrings(val, flag); bool ok = true; - for( auto& cur : availableFlag ) - { - static StringViewIMap< int > flagNames{ - { CSTRING_VIEW( "org2fromTrace" ), FX_ORG2_FROM_TRACE }, - { CSTRING_VIEW( "traceImpactFx" ), FX_TRACE_IMPACT_FX }, - { CSTRING_VIEW( "org2isOffset" ), FX_ORG2_IS_OFFSET }, - { CSTRING_VIEW( "cheapOrgCalc" ), FX_CHEAP_ORG_CALC }, - { CSTRING_VIEW( "cheapOrg2Calc" ), FX_CHEAP_ORG2_CALC }, - { CSTRING_VIEW( "absoluteVel" ), FX_VEL_IS_ABSOLUTE }, - { CSTRING_VIEW( "absoluteAccel" ), FX_ACCEL_IS_ABSOLUTE }, - { CSTRING_VIEW( "orgOnSphere" ), FX_ORG_ON_SPHERE }, - { CSTRING_VIEW( "orgOnCylinder" ), FX_ORG_ON_CYLINDER }, - { CSTRING_VIEW( "axisFromSphere" ), FX_AXIS_FROM_SPHERE }, - { CSTRING_VIEW( "randrotaroundfwd" ), FX_RAND_ROT_AROUND_FWD }, - { CSTRING_VIEW( "evenDistribution" ), FX_EVEN_DISTRIBUTION }, - { CSTRING_VIEW( "rgbComponentInterpolation" ), FX_RGB_COMPONENT_INTERP }, - { CSTRING_VIEW( "lessAttenuation" ), FX_SND_LESS_ATTENUATION }, + for (auto &cur : availableFlag) { + static StringViewIMap flagNames{ + {CSTRING_VIEW("org2fromTrace"), FX_ORG2_FROM_TRACE}, + {CSTRING_VIEW("traceImpactFx"), FX_TRACE_IMPACT_FX}, + {CSTRING_VIEW("org2isOffset"), FX_ORG2_IS_OFFSET}, + {CSTRING_VIEW("cheapOrgCalc"), FX_CHEAP_ORG_CALC}, + {CSTRING_VIEW("cheapOrg2Calc"), FX_CHEAP_ORG2_CALC}, + {CSTRING_VIEW("absoluteVel"), FX_VEL_IS_ABSOLUTE}, + {CSTRING_VIEW("absoluteAccel"), FX_ACCEL_IS_ABSOLUTE}, + {CSTRING_VIEW("orgOnSphere"), FX_ORG_ON_SPHERE}, + {CSTRING_VIEW("orgOnCylinder"), FX_ORG_ON_CYLINDER}, + {CSTRING_VIEW("axisFromSphere"), FX_AXIS_FROM_SPHERE}, + {CSTRING_VIEW("randrotaroundfwd"), FX_RAND_ROT_AROUND_FWD}, + {CSTRING_VIEW("evenDistribution"), FX_EVEN_DISTRIBUTION}, + {CSTRING_VIEW("rgbComponentInterpolation"), FX_RGB_COMPONENT_INTERP}, + {CSTRING_VIEW("lessAttenuation"), FX_SND_LESS_ATTENUATION}, }; - auto pos = flagNames.find( cur ); - if( pos == flagNames.end() ) - { + auto pos = flagNames.find(cur); + if (pos == flagNames.end()) { ok = false; - } - else - { + } else { mSpawnFlags |= pos->second; } } @@ -799,15 +728,13 @@ bool CPrimitiveTemplate::ParseSpawnFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAcceleration( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAcceleration(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAccelX.SetRange( min[0], max[0] ); - mAccelY.SetRange( min[1], max[1] ); - mAccelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAccelX.SetRange(min[0], max[0]); + mAccelY.SetRange(min[1], max[1]); + mAccelZ.SetRange(min[2], max[2]); return true; } @@ -824,13 +751,11 @@ bool CPrimitiveTemplate::ParseAcceleration( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGravity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseGravity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mGravity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mGravity.SetRange(min, max); return true; } @@ -849,13 +774,11 @@ bool CPrimitiveTemplate::ParseGravity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDensity( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseDensity(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mDensity.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mDensity.SetRange(min, max); return true; } @@ -875,13 +798,11 @@ bool CPrimitiveTemplate::ParseDensity( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVariance( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseVariance(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mVariance.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mVariance.SetRange(min, max); return true; } @@ -898,15 +819,13 @@ bool CPrimitiveTemplate::ParseVariance( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBStart(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedStart.SetRange( min[0], max[0] ); - mGreenStart.SetRange( min[1], max[1] ); - mBlueStart.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedStart.SetRange(min[0], max[0]); + mGreenStart.SetRange(min[1], max[1]); + mBlueStart.SetRange(min[2], max[2]); return true; } @@ -923,15 +842,13 @@ bool CPrimitiveTemplate::ParseRGBStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBEnd(const gsl::cstring_span &val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedEnd.SetRange( min[0], max[0] ); - mGreenEnd.SetRange( min[1], max[1] ); - mBlueEnd.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedEnd.SetRange(min[0], max[0]); + mGreenEnd.SetRange(min[1], max[1]); + mBlueEnd.SetRange(min[2], max[2]); return true; } @@ -948,13 +865,11 @@ bool CPrimitiveTemplate::ParseRGBEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mRGBParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mRGBParm.SetRange(min, max); return true; } @@ -971,14 +886,12 @@ bool CPrimitiveTemplate::ParseRGBParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseRGBFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_RGB_SHIFT ); + mFlags |= (flags << FX_RGB_SHIFT); return true; } @@ -995,13 +908,11 @@ bool CPrimitiveTemplate::ParseRGBFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaStart.SetRange(min, max); return true; } @@ -1018,13 +929,11 @@ bool CPrimitiveTemplate::ParseAlphaStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaEnd.SetRange(min, max); return true; } @@ -1041,13 +950,11 @@ bool CPrimitiveTemplate::ParseAlphaEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mAlphaParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mAlphaParm.SetRange(min, max); return true; } @@ -1064,14 +971,12 @@ bool CPrimitiveTemplate::ParseAlphaParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseAlphaFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_ALPHA_SHIFT ); + mFlags |= (flags << FX_ALPHA_SHIFT); return true; } @@ -1088,13 +993,11 @@ bool CPrimitiveTemplate::ParseAlphaFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeStart.SetRange(min, max); return true; } @@ -1111,13 +1014,11 @@ bool CPrimitiveTemplate::ParseSizeStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeEnd.SetRange(min, max); return true; } @@ -1134,13 +1035,11 @@ bool CPrimitiveTemplate::ParseSizeEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSizeParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSizeParm.SetRange(min, max); return true; } @@ -1157,14 +1056,12 @@ bool CPrimitiveTemplate::ParseSizeParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSizeFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE_SHIFT ); + mFlags |= (flags << FX_SIZE_SHIFT); return true; } @@ -1181,13 +1078,11 @@ bool CPrimitiveTemplate::ParseSizeFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Start( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Start(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2Start.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2Start.SetRange(min, max); return true; } @@ -1204,13 +1099,11 @@ bool CPrimitiveTemplate::ParseSize2Start( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2End( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2End(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2End.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2End.SetRange(min, max); return true; } @@ -1227,13 +1120,11 @@ bool CPrimitiveTemplate::ParseSize2End( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Parm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Parm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mSize2Parm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mSize2Parm.SetRange(min, max); return true; } @@ -1250,14 +1141,12 @@ bool CPrimitiveTemplate::ParseSize2Parm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Flags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseSize2Flags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE2_SHIFT ); + mFlags |= (flags << FX_SIZE2_SHIFT); return true; } @@ -1274,13 +1163,11 @@ bool CPrimitiveTemplate::ParseSize2Flags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthStart( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthStart(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthStart.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthStart.SetRange(min, max); return true; } @@ -1297,13 +1184,11 @@ bool CPrimitiveTemplate::ParseLengthStart( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthEnd( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthEnd(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthEnd.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthEnd.SetRange(min, max); return true; } @@ -1320,13 +1205,11 @@ bool CPrimitiveTemplate::ParseLengthEnd( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthParm( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthParm(const gsl::cstring_span &val) { float min, max; - if ( ParseFloat( val, min, max ) == true ) - { - mLengthParm.SetRange( min, max ); + if (ParseFloat(val, min, max) == true) { + mLengthParm.SetRange(min, max); return true; } @@ -1343,14 +1226,12 @@ bool CPrimitiveTemplate::ParseLengthParm( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthFlags( const gsl::cstring_span& val ) -{ +bool CPrimitiveTemplate::ParseLengthFlags(const gsl::cstring_span &val) { int flags; - if ( ParseGroupFlags( val, flags ) == true ) - { + if (ParseGroupFlags(val, flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_LENGTH_SHIFT ); + mFlags |= (flags << FX_LENGTH_SHIFT); return true; } @@ -1367,22 +1248,18 @@ bool CPrimitiveTemplate::ParseLengthFlags( const gsl::cstring_span& val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseShaders( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseShaders(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterShader( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterShader(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseShaders called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseShaders called with an empty list!\n"); return false; } return true; @@ -1398,22 +1275,18 @@ bool CPrimitiveTemplate::ParseShaders( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSounds( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseSounds(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterSound( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterSound(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseSounds called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseSounds called with an empty list!\n"); return false; } return true; @@ -1429,52 +1302,42 @@ bool CPrimitiveTemplate::ParseSounds( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseModels( const CGPProperty& grp ) -{ +bool CPrimitiveTemplate::ParseModels(const CGPProperty &grp) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; - int handle = theFxHelper.RegisterModel( value ); - mMediaHandles.AddHandle( handle ); + int handle = theFxHelper.RegisterModel(value); + mMediaHandles.AddHandle(handle); } } - if( !any ) - { + if (!any) { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseModels called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseModels called with an empty list!\n"); return false; } mFlags |= FX_ATTACHED_MODEL; return true; } -static bool ParseFX( const CGPProperty& grp, CFxScheduler& scheduler, CMediaHandles& handles, SFxHelper& helper, int& flags, int successFlags, gsl::czstring loadError, gsl::czstring emptyError ) -{ +static bool ParseFX(const CGPProperty &grp, CFxScheduler &scheduler, CMediaHandles &handles, SFxHelper &helper, int &flags, int successFlags, + gsl::czstring loadError, gsl::czstring emptyError) { bool any = false; - for( auto& value : grp.GetValues() ) - { - if( !value.empty() ) - { + for (auto &value : grp.GetValues()) { + if (!value.empty()) { any = true; // TODO: string_view parameter - int handle = scheduler.RegisterEffect( std::string( value.begin(), value.end() ).c_str() ); - if( handle ) - { - handles.AddHandle( handle ); + int handle = scheduler.RegisterEffect(std::string(value.begin(), value.end()).c_str()); + if (handle) { + handles.AddHandle(handle); flags |= successFlags; - } - else - { - helper.Print( "%s", loadError ); + } else { + helper.Print("%s", loadError); } } } - if( !any ) - { - helper.Print( "%s", emptyError ); + if (!any) { + helper.Print("%s", emptyError); } return any; } @@ -1489,15 +1352,9 @@ static bool ParseFX( const CGPProperty& grp, CFxScheduler& scheduler, CMediaHand // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseImpactFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mImpactFxHandles, theFxHelper, - mFlags, FX_IMPACT_RUNS_FX | FX_APPLY_PHYSICS, - "FxTemplate: Impact effect file not found.\n", - "CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseImpactFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mImpactFxHandles, theFxHelper, mFlags, FX_IMPACT_RUNS_FX | FX_APPLY_PHYSICS, + "FxTemplate: Impact effect file not found.\n", "CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1510,15 +1367,9 @@ bool CPrimitiveTemplate::ParseImpactFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDeathFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mDeathFxHandles, theFxHelper, - mFlags, FX_DEATH_RUNS_FX, - "FxTemplate: Death effect file not found.\n", - "CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseDeathFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mDeathFxHandles, theFxHelper, mFlags, FX_DEATH_RUNS_FX, "FxTemplate: Death effect file not found.\n", + "CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1531,15 +1382,9 @@ bool CPrimitiveTemplate::ParseDeathFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseEmitterFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mEmitterFxHandles, theFxHelper, - mFlags, FX_EMIT_FX, - "FxTemplate: Emitter effect file not found.\n", - "CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParseEmitterFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mEmitterFxHandles, theFxHelper, mFlags, FX_EMIT_FX, "FxTemplate: Emitter effect file not found.\n", + "CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n"); } //------------------------------------------------------ @@ -1552,30 +1397,19 @@ bool CPrimitiveTemplate::ParseEmitterFxStrings( const CGPProperty& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePlayFxStrings( const CGPProperty& grp ) -{ - return ParseFX( - grp, - theFxScheduler, mPlayFxHandles, theFxHelper, - mFlags, 0, - "FxTemplate: Effect file not found.\n", - "CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n" - ); +bool CPrimitiveTemplate::ParsePlayFxStrings(const CGPProperty &grp) { + return ParseFX(grp, theFxScheduler, mPlayFxHandles, theFxHelper, mFlags, 0, "FxTemplate: Effect file not found.\n", + "CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n"); } -bool CPrimitiveTemplate::ParseGroup( const CGPGroup& grp, const StringViewIMap< ParseMethod >& parseMethods, gsl::czstring name ) -{ - for( auto& cur : grp.GetProperties() ) - { - auto pos = parseMethods.find( cur.GetName() ); - if( pos == parseMethods.end() ) - { - theFxHelper.Print( "Unknown key parsing %s group!", name ); - } - else - { +bool CPrimitiveTemplate::ParseGroup(const CGPGroup &grp, const StringViewIMap &parseMethods, gsl::czstring name) { + for (auto &cur : grp.GetProperties()) { + auto pos = parseMethods.find(cur.GetName()); + if (pos == parseMethods.end()) { + theFxHelper.Print("Unknown key parsing %s group!", name); + } else { ParseMethod method = pos->second; - ( this->*method )( cur.GetTopValue() ); + (this->*method)(cur.GetTopValue()); } } return true; @@ -1592,20 +1426,17 @@ bool CPrimitiveTemplate::ParseGroup( const CGPGroup& grp, const StringViewIMap< // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGB( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseRGBStart }, +bool CPrimitiveTemplate::ParseRGB(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseRGBStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseRGBEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseRGBEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseRGBParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseRGBParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseRGBParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseRGBParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseRGBFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseRGBFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseRGBFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseRGBFlags}, }; - return ParseGroup( grp, parseMethods, "RGB" ); + return ParseGroup(grp, parseMethods, "RGB"); } //------------------------------------------------------ @@ -1619,20 +1450,17 @@ bool CPrimitiveTemplate::ParseRGB( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlpha( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseAlphaStart }, +bool CPrimitiveTemplate::ParseAlpha(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseAlphaStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseAlphaEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseAlphaEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseAlphaParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseAlphaParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseAlphaParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseAlphaParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseAlphaFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseAlphaFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseAlphaFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseAlphaFlags}, }; - return ParseGroup( grp, parseMethods, "Alpha" ); + return ParseGroup(grp, parseMethods, "Alpha"); } //------------------------------------------------------ @@ -1646,20 +1474,17 @@ bool CPrimitiveTemplate::ParseAlpha( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseSizeStart }, +bool CPrimitiveTemplate::ParseSize(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseSizeStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseSizeEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseSizeEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseSizeParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseSizeParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseSizeParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseSizeParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseSizeFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseSizeFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseSizeFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseSizeFlags}, }; - return ParseGroup( grp, parseMethods, "Size" ); + return ParseGroup(grp, parseMethods, "Size"); } //------------------------------------------------------ @@ -1673,20 +1498,17 @@ bool CPrimitiveTemplate::ParseSize( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseSize2Start }, +bool CPrimitiveTemplate::ParseSize2(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseSize2Start}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseSize2End }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseSize2End}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseSize2Parm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseSize2Parm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseSize2Parm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseSize2Parm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseSize2Flags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseSize2Flags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseSize2Flags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseSize2Flags}, }; - return ParseGroup( grp, parseMethods, "Size2" ); + return ParseGroup(grp, parseMethods, "Size2"); } //------------------------------------------------------ @@ -1700,143 +1522,123 @@ bool CPrimitiveTemplate::ParseSize2( const CGPGroup& grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLength( const CGPGroup& grp ) -{ - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "start" ), &CPrimitiveTemplate::ParseLengthStart }, +bool CPrimitiveTemplate::ParseLength(const CGPGroup &grp) { + static StringViewIMap parseMethods{ + {CSTRING_VIEW("start"), &CPrimitiveTemplate::ParseLengthStart}, - { CSTRING_VIEW( "end" ), &CPrimitiveTemplate::ParseLengthEnd }, + {CSTRING_VIEW("end"), &CPrimitiveTemplate::ParseLengthEnd}, - { CSTRING_VIEW( "parm" ), &CPrimitiveTemplate::ParseLengthParm }, - { CSTRING_VIEW( "parms" ), &CPrimitiveTemplate::ParseLengthParm }, + {CSTRING_VIEW("parm"), &CPrimitiveTemplate::ParseLengthParm}, {CSTRING_VIEW("parms"), &CPrimitiveTemplate::ParseLengthParm}, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseLengthFlags }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseLengthFlags }, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseLengthFlags}, {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseLengthFlags}, }; - return ParseGroup( grp, parseMethods, "Length" ); + return ParseGroup(grp, parseMethods, "Length"); } - // Parse a primitive, apply defaults first, grab any base level // key pairs, then process any sub groups we may contain. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePrimitive( const CGPGroup& grp ) -{ +bool CPrimitiveTemplate::ParsePrimitive(const CGPGroup &grp) { // Property - for( auto& prop : grp.GetProperties() ) - { + for (auto &prop : grp.GetProperties()) { // Single Value Parsing { - static StringViewIMap< ParseMethod > parseMethods{ - { CSTRING_VIEW( "count" ), &CPrimitiveTemplate::ParseCount }, - { CSTRING_VIEW( "life" ), &CPrimitiveTemplate::ParseLife }, - { CSTRING_VIEW( "delay" ), &CPrimitiveTemplate::ParseDelay }, - { CSTRING_VIEW( "bounce" ), &CPrimitiveTemplate::ParseElasticity }, - { CSTRING_VIEW( "intensity" ), &CPrimitiveTemplate::ParseElasticity }, - { CSTRING_VIEW( "min" ), &CPrimitiveTemplate::ParseMin }, - { CSTRING_VIEW( "max" ), &CPrimitiveTemplate::ParseMax }, - { CSTRING_VIEW( "angle" ), &CPrimitiveTemplate::ParseAngle }, - { CSTRING_VIEW( "angles" ), &CPrimitiveTemplate::ParseAngle }, - { CSTRING_VIEW( "angleDelta" ), &CPrimitiveTemplate::ParseAngleDelta }, - { CSTRING_VIEW( "velocity" ), &CPrimitiveTemplate::ParseVelocity }, - { CSTRING_VIEW( "vel" ), &CPrimitiveTemplate::ParseVelocity }, - { CSTRING_VIEW( "acceleration" ), &CPrimitiveTemplate::ParseAcceleration }, - { CSTRING_VIEW( "accel" ), &CPrimitiveTemplate::ParseAcceleration }, - { CSTRING_VIEW( "gravity" ), &CPrimitiveTemplate::ParseGravity }, - { CSTRING_VIEW( "density" ), &CPrimitiveTemplate::ParseDensity }, - { CSTRING_VIEW( "variance" ), &CPrimitiveTemplate::ParseVariance }, - { CSTRING_VIEW( "origin" ), &CPrimitiveTemplate::ParseOrigin1 }, - { CSTRING_VIEW( "origin2" ), &CPrimitiveTemplate::ParseOrigin2 }, - { CSTRING_VIEW( "radius" ), &CPrimitiveTemplate::ParseRadius }, - { CSTRING_VIEW( "height" ), &CPrimitiveTemplate::ParseHeight }, - { CSTRING_VIEW( "rotation" ), &CPrimitiveTemplate::ParseRotation }, - { CSTRING_VIEW( "rotationDelta" ), &CPrimitiveTemplate::ParseRotationDelta }, - { CSTRING_VIEW( "flags" ), &CPrimitiveTemplate::ParseFlags }, - { CSTRING_VIEW( "flag" ), &CPrimitiveTemplate::ParseFlags }, - { CSTRING_VIEW( "spawnFlags" ), &CPrimitiveTemplate::ParseSpawnFlags }, - { CSTRING_VIEW( "spawnFlag" ), &CPrimitiveTemplate::ParseSpawnFlags }, + static StringViewIMap parseMethods{ + {CSTRING_VIEW("count"), &CPrimitiveTemplate::ParseCount}, + {CSTRING_VIEW("life"), &CPrimitiveTemplate::ParseLife}, + {CSTRING_VIEW("delay"), &CPrimitiveTemplate::ParseDelay}, + {CSTRING_VIEW("bounce"), &CPrimitiveTemplate::ParseElasticity}, + {CSTRING_VIEW("intensity"), &CPrimitiveTemplate::ParseElasticity}, + {CSTRING_VIEW("min"), &CPrimitiveTemplate::ParseMin}, + {CSTRING_VIEW("max"), &CPrimitiveTemplate::ParseMax}, + {CSTRING_VIEW("angle"), &CPrimitiveTemplate::ParseAngle}, + {CSTRING_VIEW("angles"), &CPrimitiveTemplate::ParseAngle}, + {CSTRING_VIEW("angleDelta"), &CPrimitiveTemplate::ParseAngleDelta}, + {CSTRING_VIEW("velocity"), &CPrimitiveTemplate::ParseVelocity}, + {CSTRING_VIEW("vel"), &CPrimitiveTemplate::ParseVelocity}, + {CSTRING_VIEW("acceleration"), &CPrimitiveTemplate::ParseAcceleration}, + {CSTRING_VIEW("accel"), &CPrimitiveTemplate::ParseAcceleration}, + {CSTRING_VIEW("gravity"), &CPrimitiveTemplate::ParseGravity}, + {CSTRING_VIEW("density"), &CPrimitiveTemplate::ParseDensity}, + {CSTRING_VIEW("variance"), &CPrimitiveTemplate::ParseVariance}, + {CSTRING_VIEW("origin"), &CPrimitiveTemplate::ParseOrigin1}, + {CSTRING_VIEW("origin2"), &CPrimitiveTemplate::ParseOrigin2}, + {CSTRING_VIEW("radius"), &CPrimitiveTemplate::ParseRadius}, + {CSTRING_VIEW("height"), &CPrimitiveTemplate::ParseHeight}, + {CSTRING_VIEW("rotation"), &CPrimitiveTemplate::ParseRotation}, + {CSTRING_VIEW("rotationDelta"), &CPrimitiveTemplate::ParseRotationDelta}, + {CSTRING_VIEW("flags"), &CPrimitiveTemplate::ParseFlags}, + {CSTRING_VIEW("flag"), &CPrimitiveTemplate::ParseFlags}, + {CSTRING_VIEW("spawnFlags"), &CPrimitiveTemplate::ParseSpawnFlags}, + {CSTRING_VIEW("spawnFlag"), &CPrimitiveTemplate::ParseSpawnFlags}, }; - auto pos = parseMethods.find( prop.GetName() ); - if( pos != parseMethods.end() ) - { + auto pos = parseMethods.find(prop.GetName()); + if (pos != parseMethods.end()) { ParseMethod method = pos->second; - ( this->*method )( prop.GetTopValue() ); + (this->*method)(prop.GetTopValue()); continue; } } // Property Parsing { - using PropertyParseMethod = bool( CPrimitiveTemplate::* )( const CGPProperty& ); - static StringViewIMap< PropertyParseMethod > parseMethods{ - { CSTRING_VIEW( "shaders" ), &CPrimitiveTemplate::ParseShaders }, - { CSTRING_VIEW( "shader" ), &CPrimitiveTemplate::ParseShaders }, - { CSTRING_VIEW( "models" ), &CPrimitiveTemplate::ParseModels }, - { CSTRING_VIEW( "model" ), &CPrimitiveTemplate::ParseModels }, - { CSTRING_VIEW( "sounds" ), &CPrimitiveTemplate::ParseSounds }, - { CSTRING_VIEW( "sound" ), &CPrimitiveTemplate::ParseSounds }, - { CSTRING_VIEW( "impactfx" ), &CPrimitiveTemplate::ParseImpactFxStrings }, - { CSTRING_VIEW( "deathfx" ), &CPrimitiveTemplate::ParseDeathFxStrings }, - { CSTRING_VIEW( "emitfx" ), &CPrimitiveTemplate::ParseEmitterFxStrings }, - { CSTRING_VIEW( "playfx" ), &CPrimitiveTemplate::ParsePlayFxStrings }, + using PropertyParseMethod = bool (CPrimitiveTemplate::*)(const CGPProperty &); + static StringViewIMap parseMethods{ + {CSTRING_VIEW("shaders"), &CPrimitiveTemplate::ParseShaders}, + {CSTRING_VIEW("shader"), &CPrimitiveTemplate::ParseShaders}, + {CSTRING_VIEW("models"), &CPrimitiveTemplate::ParseModels}, + {CSTRING_VIEW("model"), &CPrimitiveTemplate::ParseModels}, + {CSTRING_VIEW("sounds"), &CPrimitiveTemplate::ParseSounds}, + {CSTRING_VIEW("sound"), &CPrimitiveTemplate::ParseSounds}, + {CSTRING_VIEW("impactfx"), &CPrimitiveTemplate::ParseImpactFxStrings}, + {CSTRING_VIEW("deathfx"), &CPrimitiveTemplate::ParseDeathFxStrings}, + {CSTRING_VIEW("emitfx"), &CPrimitiveTemplate::ParseEmitterFxStrings}, + {CSTRING_VIEW("playfx"), &CPrimitiveTemplate::ParsePlayFxStrings}, }; - auto pos = parseMethods.find( prop.GetName() ); - if( pos != parseMethods.end() ) - { + auto pos = parseMethods.find(prop.GetName()); + if (pos != parseMethods.end()) { PropertyParseMethod method = pos->second; - ( this->*method )( prop ); + (this->*method)(prop); continue; } } // Special Cases - if( Q::stricmp( prop.GetName(), CSTRING_VIEW( "cullrange" ) ) == Q::Ordering::EQ ) - { - mCullRange = Q::svtoi( prop.GetTopValue() ); + if (Q::stricmp(prop.GetName(), CSTRING_VIEW("cullrange")) == Q::Ordering::EQ) { + mCullRange = Q::svtoi(prop.GetTopValue()); mCullRange *= mCullRange; // Square - } - else if( Q::stricmp( prop.GetName(), CSTRING_VIEW( "name" ) ) == Q::Ordering::EQ ) - { - if( !prop.GetTopValue().empty() ) - { + } else if (Q::stricmp(prop.GetName(), CSTRING_VIEW("name")) == Q::Ordering::EQ) { + if (!prop.GetTopValue().empty()) { // just stash the descriptive name of the primitive - std::size_t len = std::min< std::size_t >( prop.GetTopValue().size(), FX_MAX_PRIM_NAME - 1 ); + std::size_t len = std::min(prop.GetTopValue().size(), FX_MAX_PRIM_NAME - 1); auto begin = prop.GetTopValue().begin(); - std::copy( begin, begin + len, &mName[ 0 ] ); - mName[ len ] = '\0'; + std::copy(begin, begin + len, &mName[0]); + mName[len] = '\0'; } } // Error - else - { - theFxHelper.Print( "Unknown key parsing an effect primitive!\n" ); + else { + theFxHelper.Print("Unknown key parsing an effect primitive!\n"); } } - for( auto& subGrp : grp.GetSubGroups() ) - { - using GroupParseMethod = bool ( CPrimitiveTemplate::* )( const CGPGroup& ); - static StringViewIMap< GroupParseMethod > parseMethods{ - { CSTRING_VIEW( "rgb" ), &CPrimitiveTemplate::ParseRGB }, + for (auto &subGrp : grp.GetSubGroups()) { + using GroupParseMethod = bool (CPrimitiveTemplate::*)(const CGPGroup &); + static StringViewIMap parseMethods{ + {CSTRING_VIEW("rgb"), &CPrimitiveTemplate::ParseRGB}, - { CSTRING_VIEW( "alpha" ), &CPrimitiveTemplate::ParseAlpha }, + {CSTRING_VIEW("alpha"), &CPrimitiveTemplate::ParseAlpha}, - { CSTRING_VIEW( "size" ), &CPrimitiveTemplate::ParseSize }, - { CSTRING_VIEW( "width" ), &CPrimitiveTemplate::ParseSize }, + {CSTRING_VIEW("size"), &CPrimitiveTemplate::ParseSize}, {CSTRING_VIEW("width"), &CPrimitiveTemplate::ParseSize}, - { CSTRING_VIEW( "size2" ), &CPrimitiveTemplate::ParseSize2 }, - { CSTRING_VIEW( "width2" ), &CPrimitiveTemplate::ParseSize2 }, + {CSTRING_VIEW("size2"), &CPrimitiveTemplate::ParseSize2}, {CSTRING_VIEW("width2"), &CPrimitiveTemplate::ParseSize2}, - { CSTRING_VIEW( "length" ), &CPrimitiveTemplate::ParseLength }, - { CSTRING_VIEW( "height" ), &CPrimitiveTemplate::ParseLength }, + {CSTRING_VIEW("length"), &CPrimitiveTemplate::ParseLength}, {CSTRING_VIEW("height"), &CPrimitiveTemplate::ParseLength}, }; - auto pos = parseMethods.find( subGrp.GetName() ); - if( pos == parseMethods.end() ) - { - theFxHelper.Print( "Unknown group key parsing a particle!\n" ); - } - else - { + auto pos = parseMethods.find(subGrp.GetName()); + if (pos == parseMethods.end()) { + theFxHelper.Print("Unknown group key parsing a particle!\n"); + } else { GroupParseMethod method = pos->second; - ( this->*method )( subGrp ); + (this->*method)(subGrp); } } return true; diff --git a/codeJK2/cgame/FxUtil.cpp b/codeJK2/cgame/FxUtil.cpp index 8df8097c86..1dc1f1952d 100644 --- a/codeJK2/cgame/FxUtil.cpp +++ b/codeJK2/cgame/FxUtil.cpp @@ -21,45 +21,40 @@ along with this program; if not, see . */ #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif -vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +vec3_t WHITE = {1.0f, 1.0f, 1.0f}; - -struct SEffectList -{ +struct SEffectList { CEffect *mEffect; - int mKillTime; + int mKillTime; }; -#define PI 3.14159f +#define PI 3.14159f -SEffectList effectList[MAX_EFFECTS]; -SEffectList *nextValidEffect; -SFxHelper theFxHelper; +SEffectList effectList[MAX_EFFECTS]; +SEffectList *nextValidEffect; +SFxHelper theFxHelper; -int activeFx = 0; -int mMax = 0; -int mMaxTime = 0; -int drawnFx; -int mParticles; -int mOParticles; -int mLines; -int mTails; -qboolean fxInitialized = qfalse; +int activeFx = 0; +int mMax = 0; +int mMaxTime = 0; +int drawnFx; +int mParticles; +int mOParticles; +int mLines; +int mTails; +qboolean fxInitialized = qfalse; //------------------------- // FX_Free // // Frees all FX //------------------------- -bool FX_Free( void ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +bool FX_Free(void) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -77,12 +72,9 @@ bool FX_Free( void ) // // Frees all active FX but leaves the templates //------------------------- -void FX_Stop( void ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +void FX_Stop(void) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -99,14 +91,11 @@ void FX_Stop( void ) // // Preps system for use //------------------------- -int FX_Init( void ) -{ - if ( fxInitialized == qfalse ) - { +int FX_Init(void) { + if (fxInitialized == qfalse) { fxInitialized = qtrue; - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { + for (int i = 0; i < MAX_EFFECTS; i++) { effectList[i].mEffect = 0; } } @@ -122,12 +111,10 @@ int FX_Init( void ) return true; } - //------------------------- // FX_FreeMember //------------------------- -static void FX_FreeMember( SEffectList *obj ) -{ +static void FX_FreeMember(SEffectList *obj) { obj->mEffect->Die(); delete obj->mEffect; obj->mEffect = 0; @@ -138,7 +125,6 @@ static void FX_FreeMember( SEffectList *obj ) activeFx--; } - //------------------------- // FX_GetValidEffect // @@ -147,58 +133,48 @@ static void FX_FreeMember( SEffectList *obj ) // Note - in the editor, this function may return NULL, indicating that all // effects are being stopped. //------------------------- -static SEffectList *FX_GetValidEffect() -{ - if ( nextValidEffect->mEffect == 0 ) - { +static SEffectList *FX_GetValidEffect() { + if (nextValidEffect->mEffect == 0) { return nextValidEffect; } - int i; - SEffectList *ef; + int i; + SEffectList *ef; // Blah..plow through the list till we find something that is currently untainted - for ( i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++ ) - { - if ( ef->mEffect == 0 ) - { + for (i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++) { + if (ef->mEffect == 0) { return ef; } } // report the error. #ifndef FINAL_BUILD - theFxHelper.Print( "FX system out of effects\n" ); + theFxHelper.Print("FX system out of effects\n"); #endif // Hmmm.. just trashing the first effect in the list is a poor approach - FX_FreeMember( &effectList[0] ); + FX_FreeMember(&effectList[0]); // Recursive call return FX_GetValidEffect(); } - //------------------------- // FX_ActiveFx // // Returns whether these are any active or scheduled effects //------------------------- -bool FX_ActiveFx(void) -{ - return ((activeFx > 0) || (theFxScheduler.NumScheduledFx() > 0)); -} - +bool FX_ActiveFx(void) { return ((activeFx > 0) || (theFxScheduler.NumScheduledFx() > 0)); } //------------------------- // FX_Add // // Adds all fx to the view //------------------------- -void FX_Add( void ) -{ - int i; - SEffectList *ef; +void FX_Add(void) { + int i; + SEffectList *ef; drawnFx = 0; mParticles = 0; @@ -207,168 +183,117 @@ void FX_Add( void ) mTails = 0; // Blah....plow through the whole dang list. - for ( i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++ ) - { - if ( ef->mEffect != 0 ) - { + for (i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++) { + if (ef->mEffect != 0) { // Effect is active - if ( theFxHelper.mTime > ef->mKillTime ) - { + if (theFxHelper.mTime > ef->mKillTime) { // Clean up old effects, calling any death effects as needed // this flag just has to be cleared otherwise death effects might not happen correctly - ef->mEffect->ClearFlags( FX_KILL_ON_IMPACT ); - FX_FreeMember( ef ); - } - else - { - if ( ef->mEffect->Update() == false ) - { + ef->mEffect->ClearFlags(FX_KILL_ON_IMPACT); + FX_FreeMember(ef); + } else { + if (ef->mEffect->Update() == false) { // We've been marked for death - FX_FreeMember( ef ); + FX_FreeMember(ef); continue; } } } } - if ( fx_debug.integer ) - { - if ( theFxHelper.mTime > mMaxTime ) - { + if (fx_debug.integer) { + if (theFxHelper.mTime > mMaxTime) { // decay pretty harshly when we do it mMax *= 0.9f; mMaxTime = theFxHelper.mTime + 200; // decay 5 times a second if we haven't set a new max } - if ( activeFx > mMax ) - { + if (activeFx > mMax) { // but we can never be less that the current activeFx count mMax = activeFx; mMaxTime = theFxHelper.mTime + 4000; // since we just increased the max, hold it for at least 4 seconds } // Particles - if ( mParticles > 500 ) - { - theFxHelper.Print( ">Particles ^1%4i ", mParticles ); - } - else if ( mParticles > 250 ) - { - theFxHelper.Print( ">Particles ^3%4i ", mParticles ); - } - else - { - theFxHelper.Print( ">Particles %4i ", mParticles ); + if (mParticles > 500) { + theFxHelper.Print(">Particles ^1%4i ", mParticles); + } else if (mParticles > 250) { + theFxHelper.Print(">Particles ^3%4i ", mParticles); + } else { + theFxHelper.Print(">Particles %4i ", mParticles); } // Lines - if ( mLines > 500 ) - { - theFxHelper.Print( ">Lines ^1%4i\n", mLines ); - } - else if ( mLines > 250 ) - { - theFxHelper.Print( ">Lines ^3%4i\n", mLines ); - } - else - { - theFxHelper.Print( ">Lines %4i\n", mLines ); + if (mLines > 500) { + theFxHelper.Print(">Lines ^1%4i\n", mLines); + } else if (mLines > 250) { + theFxHelper.Print(">Lines ^3%4i\n", mLines); + } else { + theFxHelper.Print(">Lines %4i\n", mLines); } // OParticles - if ( mOParticles > 500 ) - { - theFxHelper.Print( ">OParticles ^1%4i ", mOParticles ); - } - else if ( mOParticles > 250 ) - { - theFxHelper.Print( ">OParticles ^3%4i ", mOParticles ); - } - else - { - theFxHelper.Print( ">OParticles %4i ", mOParticles ); + if (mOParticles > 500) { + theFxHelper.Print(">OParticles ^1%4i ", mOParticles); + } else if (mOParticles > 250) { + theFxHelper.Print(">OParticles ^3%4i ", mOParticles); + } else { + theFxHelper.Print(">OParticles %4i ", mOParticles); } // Tails - if ( mTails > 400 ) - { - theFxHelper.Print( ">Tails ^1%4i\n", mTails ); - } - else if ( mTails > 200 ) - { - theFxHelper.Print( ">Tails ^3%4i\n", mTails ); - } - else - { - theFxHelper.Print( ">Tails %4i\n", mTails ); + if (mTails > 400) { + theFxHelper.Print(">Tails ^1%4i\n", mTails); + } else if (mTails > 200) { + theFxHelper.Print(">Tails ^3%4i\n", mTails); + } else { + theFxHelper.Print(">Tails %4i\n", mTails); } // Active - if ( activeFx > 600 ) - { - theFxHelper.Print( ">Active ^1%4i ", activeFx ); - } - else if ( activeFx > 400 ) - { - theFxHelper.Print( ">Active ^3%4i ", activeFx ); - } - else - { - theFxHelper.Print( ">Active %4i ", activeFx ); + if (activeFx > 600) { + theFxHelper.Print(">Active ^1%4i ", activeFx); + } else if (activeFx > 400) { + theFxHelper.Print(">Active ^3%4i ", activeFx); + } else { + theFxHelper.Print(">Active %4i ", activeFx); } // Drawn - if ( drawnFx > 600 ) - { - theFxHelper.Print( ">Drawn ^1%4i ", drawnFx ); - } - else if ( drawnFx > 400 ) - { - theFxHelper.Print( ">Drawn ^3%4i ", drawnFx ); - } - else - { - theFxHelper.Print( ">Drawn %4i ", drawnFx ); + if (drawnFx > 600) { + theFxHelper.Print(">Drawn ^1%4i ", drawnFx); + } else if (drawnFx > 400) { + theFxHelper.Print(">Drawn ^3%4i ", drawnFx); + } else { + theFxHelper.Print(">Drawn %4i ", drawnFx); } // Max - if ( mMax > 600 ) - { - theFxHelper.Print( ">Max ^1%4i ", mMax ); - } - else if ( mMax > 400 ) - { - theFxHelper.Print( ">Max ^3%4i ", mMax ); - } - else - { - theFxHelper.Print( ">Max %4i ", mMax ); + if (mMax > 600) { + theFxHelper.Print(">Max ^1%4i ", mMax); + } else if (mMax > 400) { + theFxHelper.Print(">Max ^3%4i ", mMax); + } else { + theFxHelper.Print(">Max %4i ", mMax); } // Scheduled - if ( theFxScheduler.NumScheduledFx() > 100 ) - { - theFxHelper.Print( ">Scheduled ^1%4i\n", theFxScheduler.NumScheduledFx() ); - } - else if ( theFxScheduler.NumScheduledFx() > 50 ) - { - theFxHelper.Print( ">Scheduled ^3%4i\n", theFxScheduler.NumScheduledFx() ); - } - else - { - theFxHelper.Print( ">Scheduled %4i\n", theFxScheduler.NumScheduledFx() ); + if (theFxScheduler.NumScheduledFx() > 100) { + theFxHelper.Print(">Scheduled ^1%4i\n", theFxScheduler.NumScheduledFx()); + } else if (theFxScheduler.NumScheduledFx() > 50) { + theFxHelper.Print(">Scheduled ^3%4i\n", theFxScheduler.NumScheduledFx()); + } else { + theFxHelper.Print(">Scheduled %4i\n", theFxScheduler.NumScheduledFx()); } } } - //------------------------- // FX_AddPrimitive // // Note - in the editor, this function may change *pEffect to NULL, indicating that // all effects are being stopped. //------------------------- -void FX_AddPrimitive( CEffect **pEffect, int killTime ) -{ +void FX_AddPrimitive(CEffect **pEffect, int killTime) { SEffectList *item = FX_GetValidEffect(); item->mEffect = *pEffect; @@ -377,86 +302,69 @@ void FX_AddPrimitive( CEffect **pEffect, int killTime ) activeFx++; // Stash these in the primitive so it has easy access to the vals - (*pEffect)->SetTimeStart( theFxHelper.mTime ); - (*pEffect)->SetTimeEnd( theFxHelper.mTime + killTime ); + (*pEffect)->SetTimeStart(theFxHelper.mTime); + (*pEffect)->SetTimeEnd(theFxHelper.mTime + killTime); } - //------------------------- // FX_AddParticle //------------------------- -CParticle *FX_AddParticle( const vec3_t org, const vec3_t vel, const vec3_t accel, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - const vec3_t sRGB, const vec3_t eRGB, float rgbParm, - float rotation, float rotationDelta, - const vec3_t min, const vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CParticle *FX_AddParticle(const vec3_t org, const vec3_t vel, const vec3_t accel, float size1, float size2, float sizeParm, float alpha1, float alpha2, + float alphaParm, const vec3_t sRGB, const vec3_t eRGB, float rgbParm, float rotation, float rotationDelta, const vec3_t min, + const vec3_t max, float elasticity, int deathID, int impactID, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CParticle *fx = new CParticle; - if ( fx ) - { - fx->SetOrigin1( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); - - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); + + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -466,78 +374,63 @@ CParticle *FX_AddParticle( const vec3_t org, const vec3_t vel, const vec3_t acce //------------------------- // FX_AddParticle //------------------------- -CParticle *FX_AddParticle( int clientID, const vec3_t org, const vec3_t vel, const vec3_t accel, float gravity, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - const vec3_t rgb1, const vec3_t rgb2, float rgbParm, - float rotation, float rotationDelta, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CParticle *FX_AddParticle(int clientID, const vec3_t org, const vec3_t vel, const vec3_t accel, float gravity, float size1, float size2, float sizeParm, + float alpha1, float alpha2, float alphaParm, const vec3_t rgb1, const vec3_t rgb2, float rgbParm, float rotation, float rotationDelta, + int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CParticle *fx = new CParticle; - if ( fx ) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); - fx->SetGravity( gravity ); + if (fx) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetVel(vel); + fx->SetAccel(accel); + fx->SetGravity(gravity); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( 0.0f ); - fx->SetMin( NULL ); - fx->SetMax( NULL ); - fx->SetClient( clientID ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(0.0f); + fx->SetMin(NULL); + fx->SetMax(NULL); + fx->SetClient(clientID); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -546,144 +439,115 @@ CParticle *FX_AddParticle( int clientID, const vec3_t org, const vec3_t vel, con //------------------------- // FX_AddLine //------------------------- -CLine *FX_AddLine( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CLine *FX_AddLine(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, + float rgbParm, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CLine *fx = new CLine; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + fx->SetOrigin1(start); + fx->SetOrigin2(end); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddLine //------------------------- -CLine *FX_AddLine( int clientID, vec3_t start, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int impactFX_id, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CLine *FX_AddLine(int clientID, vec3_t start, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, + float rgbParm, int killTime, qhandle_t shader, int impactFX_id, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CLine *fx = new CLine; - if ( fx ) - { - fx->SetOrgOffset( start ); - fx->SetOrigin1( NULL ); + if (fx) { + fx->SetOrgOffset(start); + fx->SetOrigin1(NULL); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetClient( clientID ); - fx->SetImpactFxID( impactFX_id ); + fx->SetSTScale(1.0f, 1.0f); + fx->SetClient(clientID); + fx->SetImpactFxID(impactFX_id); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -693,169 +557,133 @@ CLine *FX_AddLine( int clientID, vec3_t start, float size1, float size2, float s //------------------------- // FX_AddElectricity //------------------------- -CElectricity *FX_AddElectricity( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - float chaos, int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CElectricity *FX_AddElectricity(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, + vec3_t eRGB, float rgbParm, float chaos, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CElectricity *fx = new CElectricity; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + fx->SetOrigin1(start); + fx->SetOrigin2(end); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); - fx->SetChaos( chaos ); + fx->SetShader(shader); + fx->SetFlags(flags); + fx->SetChaos(chaos); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL? - if ( fx ) - { - fx->Initialize(); + if (fx) { + fx->Initialize(); } } return fx; } - //------------------------- // FX_AddTail //------------------------- -CTail *FX_AddTail( vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CTail *FX_AddTail(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float length1, float length2, float lengthParm, float alpha1, + float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, vec3_t min, vec3_t max, float elasticity, int deathID, int impactID, + int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CTail *fx = new CTail; - if ( fx ) - { - fx->SetOrigin1( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Length---------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetSTScale(1.0f, 1.0f); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -865,93 +693,73 @@ CTail *FX_AddTail( vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddTail //------------------------- -CTail *FX_AddTail( int clientID, vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CTail *FX_AddTail(int clientID, vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float length1, float length2, float lengthParm, + float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CTail *fx = new CTail; - if ( fx ) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Length---------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); - - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - fx->SetClient( clientID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); + + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetSTScale(1.0f, 1.0f); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + fx->SetClient(clientID); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -961,96 +769,74 @@ CTail *FX_AddTail( int clientID, vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddCylinder //------------------------- -CCylinder *FX_AddCylinder( vec3_t start, vec3_t normal, - float size1s, float size1e, float sizeParm, - float size2s, float size2e, float size2Parm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CCylinder *FX_AddCylinder(vec3_t start, vec3_t normal, float size1s, float size1e, float sizeParm, float size2s, float size2e, float size2Parm, float length1, + float length2, float lengthParm, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, int killTime, + qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CCylinder *fx = new CCylinder; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetNormal( normal ); + if (fx) { + fx->SetOrigin1(start); + fx->SetNormal(normal); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size1---------------- - fx->SetSizeStart( size1s ); - fx->SetSizeEnd( size1e ); + fx->SetSizeStart(size1s); + fx->SetSizeEnd(size1e); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Size2---------------- - fx->SetSize2Start( size2s ); - fx->SetSize2End( size2e ); + fx->SetSize2Start(size2s); + fx->SetSize2End(size2e); - if (( flags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { - fx->SetSize2Parm( size2Parm * PI * 0.001f ); - } - else if ( flags & FX_SIZE2_PARM_MASK ) - { - fx->SetSize2Parm( size2Parm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { + fx->SetSize2Parm(size2Parm * PI * 0.001f); + } else if (flags & FX_SIZE2_PARM_MASK) { + fx->SetSize2Parm(size2Parm * 0.01f * killTime + theFxHelper.mTime); } // Length1--------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1059,87 +845,69 @@ CCylinder *FX_AddCylinder( vec3_t start, vec3_t normal, //------------------------- // FX_AddEmitter //------------------------- -CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t angs, vec3_t deltaAngs, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, int emitterID, - float density, float variance, - int killTime, qhandle_t model, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CEmitter *FX_AddEmitter(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, + vec3_t rgb1, vec3_t rgb2, float rgbParm, vec3_t angs, vec3_t deltaAngs, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int emitterID, float density, float variance, int killTime, qhandle_t model, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CEmitter *fx = new CEmitter; - if ( fx ) - { - fx->SetOrigin1( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); - - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetAngles( angs ); - fx->SetAngleDelta( deltaAngs ); - fx->SetFlags( flags ); - fx->SetModel( model ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - fx->SetEmitterFxID( emitterID ); - fx->SetDensity( density ); - fx->SetVariance( variance ); - fx->SetOldTime( theFxHelper.mTime ); - - fx->SetLastOrg( org ); - fx->SetLastVel( vel ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); + + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetAngles(angs); + fx->SetAngleDelta(deltaAngs); + fx->SetFlags(flags); + fx->SetModel(model); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + fx->SetEmitterFxID(emitterID); + fx->SetDensity(density); + fx->SetVariance(variance); + fx->SetOldTime(theFxHelper.mTime); + + fx->SetLastOrg(org); + fx->SetLastVel(vel); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } @@ -1149,289 +917,227 @@ CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddLight //------------------------- -CLight *FX_AddLight( vec3_t org, float size1, float size2, float sizeParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CLight *FX_AddLight(vec3_t org, float size1, float size2, float sizeParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, int killTime, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CLight *fx = new CLight; - if ( fx ) - { - fx->SetOrigin1( org ); + if (fx) { + fx->SetOrigin1(org); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; - } - //------------------------- // FX_AddOrientedParticle //------------------------- -COrientedParticle *FX_AddOrientedParticle( vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - float rotation, float rotationDelta, - vec3_t min, vec3_t max, float bounce, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +COrientedParticle *FX_AddOrientedParticle(vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, + float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, float rotation, float rotationDelta, + vec3_t min, vec3_t max, float bounce, int deathID, int impactID, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } COrientedParticle *fx = new COrientedParticle; - if ( fx ) - { - fx->SetOrigin1( org ); - fx->SetNormal( norm ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + if (fx) { + fx->SetOrigin1(org); + fx->SetNormal(norm); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); - - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); + + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddPoly //------------------------- -CPoly *FX_AddPoly( vec3_t *verts, vec2_t *st, int numVerts, - vec3_t vel, vec3_t accel, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t rotationDelta, float bounce, int motionDelay, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 || !verts ) - { // disallow adding effects when the system is paused or the user doesn't pass in a vert array +CPoly *FX_AddPoly(vec3_t *verts, vec2_t *st, int numVerts, vec3_t vel, vec3_t accel, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, + float rgbParm, vec3_t rotationDelta, float bounce, int motionDelay, int killTime, qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1 || !verts) { // disallow adding effects when the system is paused or the user doesn't pass in a vert array return 0; } CPoly *fx = new CPoly; - if ( fx ) - { + if (fx) { // Do a cheesy copy of the verts and texture coords into our own structure - for ( int i = 0; i < numVerts; i++ ) - { - VectorCopy( verts[i], fx->mOrg[i] ); - VectorCopy2( st[i], fx->mST[i] ); + for (int i = 0; i < numVerts; i++) { + VectorCopy(verts[i], fx->mOrg[i]); + VectorCopy2(st[i], fx->mST[i]); } - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRot( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMotionTimeStamp( motionDelay ); - fx->SetNumVerts( numVerts ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRot(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMotionTimeStamp(motionDelay); + fx->SetNumVerts(numVerts); // Now that we've set our data up, let's process it into a useful format fx->PolyInit(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL } return fx; } - //------------------------- // FX_AddBezier //------------------------- -CBezier *FX_AddBezier( const vec3_t start, const vec3_t end, - const vec3_t control1, const vec3_t control1Vel, - const vec3_t control2, const vec3_t control2Vel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - const vec3_t sRGB, const vec3_t eRGB, const float rgbParm, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CBezier *FX_AddBezier(const vec3_t start, const vec3_t end, const vec3_t control1, const vec3_t control1Vel, const vec3_t control2, const vec3_t control2Vel, + float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, const vec3_t sRGB, const vec3_t eRGB, + const float rgbParm, int killTime, qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CBezier *fx = new CBezier; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + fx->SetOrigin1(start); + fx->SetOrigin2(end); - fx->SetControlPoints( control1, control2 ); - fx->SetControlVel( control1Vel, control2Vel ); + fx->SetControlPoints(control1, control2); + fx->SetControlVel(control1Vel, control2Vel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1440,68 +1146,61 @@ CBezier *FX_AddBezier( const vec3_t start, const vec3_t end, //------------------------- // FX_AddFlash //------------------------- -CFlash *FX_AddFlash( vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags = 0 ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CFlash *FX_AddFlash(vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int flags = 0) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CFlash *fx = new CFlash; - if ( fx ) - { - fx->SetOrigin1( origin ); + if (fx) { + fx->SetOrigin1(origin); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } -/* // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + /* // Alpha---------------- + fx->SetAlphaStart( alpha1 ); + fx->SetAlphaEnd( alpha2 ); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); - } + if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) + { + fx->SetAlphaParm( alphaParm * PI * 0.001f ); + } + else if ( flags & FX_ALPHA_PARM_MASK ) + { + fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + } - // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + // Size---------------- + fx->SetSizeStart( size1 ); + fx->SetSizeEnd( size2 ); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } -*/ - fx->SetShader( shader ); - fx->SetFlags( flags ); + if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) + { + fx->SetSizeParm( sizeParm * PI * 0.001f ); + } + else if ( flags & FX_SIZE_PARM_MASK ) + { + fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + } + */ + fx->SetShader(shader); + fx->SetFlags(flags); + + // fx->SetSTScale( 1.0f, 1.0f ); -// fx->SetSTScale( 1.0f, 1.0f ); - fx->Init(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1509,7 +1208,7 @@ CFlash *FX_AddFlash( vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, //------------------------------------------------------- // Functions for limited backward compatibility with EF. -// These calls can be used for simple programmatic +// These calls can be used for simple programmatic // effects, temp effects or debug graphics. // Note that this is not an all-inclusive list of // fx add functions from EF, nor are the calls guaranteed @@ -1517,76 +1216,33 @@ CFlash *FX_AddFlash( vec3_t origin, vec3_t sRGB, vec3_t eRGB, float rgbParm, //------------------------------------------------------- //--------------------------------------------------- -void FX_AddSprite( vec3_t origin, vec3_t vel, vec3_t accel, - float scale, float dscale, - float sAlpha, float eAlpha, - float rotation, float bounce, - int life, qhandle_t shader, int flags ) -{ - FX_AddParticle( origin, vel, accel, scale, scale, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - WHITE, WHITE, 0, - rotation, 0, - vec3_origin, vec3_origin, bounce, - 0, 0, - life, shader, flags ); +void FX_AddSprite(vec3_t origin, vec3_t vel, vec3_t accel, float scale, float dscale, float sAlpha, float eAlpha, float rotation, float bounce, int life, + qhandle_t shader, int flags) { + FX_AddParticle(origin, vel, accel, scale, scale, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, WHITE, WHITE, 0, rotation, 0, vec3_origin, vec3_origin, bounce, 0, 0, + life, shader, flags); } //--------------------------------------------------- -void FX_AddSprite( vec3_t origin, vec3_t vel, vec3_t accel, - float scale, float dscale, - float sAlpha, float eAlpha, - vec3_t sRGB, vec3_t eRGB, - float rotation, float bounce, - int life, qhandle_t shader, int flags ) -{ - FX_AddParticle( origin, vel, accel, scale, scale, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - sRGB, eRGB, 0, - rotation, 0, - vec3_origin, vec3_origin, bounce, - 0, 0, - life, shader, flags ); +void FX_AddSprite(vec3_t origin, vec3_t vel, vec3_t accel, float scale, float dscale, float sAlpha, float eAlpha, vec3_t sRGB, vec3_t eRGB, float rotation, + float bounce, int life, qhandle_t shader, int flags) { + FX_AddParticle(origin, vel, accel, scale, scale, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, sRGB, eRGB, 0, rotation, 0, vec3_origin, vec3_origin, bounce, 0, 0, + life, shader, flags); } //--------------------------------------------------- -void FX_AddLine( vec3_t start, vec3_t end, float stScale, - float width, float dwidth, - float sAlpha, float eAlpha, - int life, qhandle_t shader, int flags ) -{ - FX_AddLine( start, end, width, width, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - WHITE, WHITE, 0, - life, shader, 0 ); +void FX_AddLine(vec3_t start, vec3_t end, float stScale, float width, float dwidth, float sAlpha, float eAlpha, int life, qhandle_t shader, int flags) { + FX_AddLine(start, end, width, width, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, WHITE, WHITE, 0, life, shader, 0); } //--------------------------------------------------- -void FX_AddLine( vec3_t start, vec3_t end, float stScale, - float width, float dwidth, - float sAlpha, float eAlpha, - vec3_t sRGB, vec3_t eRGB, - int life, qhandle_t shader, int flags ) -{ - FX_AddLine( start, end, width, width, 0, - sAlpha, eAlpha, FX_ALPHA_LINEAR, - sRGB, eRGB, 0, - life, shader, 0 ); +void FX_AddLine(vec3_t start, vec3_t end, float stScale, float width, float dwidth, float sAlpha, float eAlpha, vec3_t sRGB, vec3_t eRGB, int life, + qhandle_t shader, int flags) { + FX_AddLine(start, end, width, width, 0, sAlpha, eAlpha, FX_ALPHA_LINEAR, sRGB, eRGB, 0, life, shader, 0); } //--------------------------------------------------- -void FX_AddQuad( vec3_t origin, vec3_t normal, - vec3_t vel, vec3_t accel, - float sradius, float eradius, - float salpha, float ealpha, - vec3_t sRGB, vec3_t eRGB, - float rotation, int life, qhandle_t shader, int flags ) -{ - FX_AddOrientedParticle( origin, normal, vel, accel, - sradius, eradius, 0.0f, - salpha, ealpha, 0.0f, - sRGB, eRGB, 0.0f, - rotation, 0.0f, - NULL, NULL, 0.0f, 0, 0, life, - shader, 0 ); +void FX_AddQuad(vec3_t origin, vec3_t normal, vec3_t vel, vec3_t accel, float sradius, float eradius, float salpha, float ealpha, vec3_t sRGB, vec3_t eRGB, + float rotation, int life, qhandle_t shader, int flags) { + FX_AddOrientedParticle(origin, normal, vel, accel, sradius, eradius, 0.0f, salpha, ealpha, 0.0f, sRGB, eRGB, 0.0f, rotation, 0.0f, NULL, NULL, 0.0f, 0, 0, + life, shader, 0); } diff --git a/codeJK2/cgame/cg_camera.cpp b/codeJK2/cgame/cg_camera.cpp index 5abb11956a..a8194a9f58 100644 --- a/codeJK2/cgame/cg_camera.cpp +++ b/codeJK2/cgame/cg_camera.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//Client camera controls for cinematics +// Client camera controls for cinematics #include "cg_local.h" @@ -28,18 +28,18 @@ along with this program; if not, see . #include "../game/g_roff.h" -bool in_camera = false; -camera_t client_camera={}; -extern qboolean player_locked; +bool in_camera = false; +camera_t client_camera = {}; +extern qboolean player_locked; -extern gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match); -extern void G_UseTargets (gentity_t *ent, gentity_t *activator); -void CGCam_FollowDisable( void ); -void CGCam_TrackDisable( void ); -void CGCam_Distance( float distance, qboolean initLerp ); -void CGCam_DistanceDisable( void ); -extern qboolean CG_CalcFOVFromX( float fov_x ); -extern void WP_SaberCatch( gentity_t *self, gentity_t *saber, qboolean switchToSaber ); +extern gentity_t *G_Find(gentity_t *from, int fieldofs, const char *match); +extern void G_UseTargets(gentity_t *ent, gentity_t *activator); +void CGCam_FollowDisable(void); +void CGCam_TrackDisable(void); +void CGCam_Distance(float distance, qboolean initLerp); +void CGCam_DistanceDisable(void); +extern qboolean CG_CalcFOVFromX(float fov_x); +extern void WP_SaberCatch(gentity_t *self, gentity_t *saber, qboolean switchToSaber); /* TODO: @@ -59,12 +59,10 @@ CGCam_Init ------------------------- */ -void CGCam_Init( void ) -{ +void CGCam_Init(void) { extern qboolean qbVidRestartOccured; - if (!qbVidRestartOccured) - { - memset( &client_camera, 0, sizeof ( camera_t ) ); + if (!qbVidRestartOccured) { + memset(&client_camera, 0, sizeof(camera_t)); } } @@ -74,55 +72,48 @@ CGCam_Enable ------------------------- */ extern void CG_CalcVrect(void); -void CGCam_Enable( void ) -{ +void CGCam_Enable(void) { client_camera.bar_alpha = 0.0f; client_camera.bar_time = cg.time; client_camera.bar_alpha_source = 0.0f; client_camera.bar_alpha_dest = 1.0f; - + client_camera.bar_height_source = 0.0f; - client_camera.bar_height_dest = 480/10; + client_camera.bar_height_dest = 480 / 10; client_camera.bar_height = 0.0f; client_camera.info_state |= CAMERA_BAR_FADING; - client_camera.FOV = CAMERA_DEFAULT_FOV; - client_camera.FOV2 = CAMERA_DEFAULT_FOV; + client_camera.FOV = CAMERA_DEFAULT_FOV; + client_camera.FOV2 = CAMERA_DEFAULT_FOV; in_camera = true; client_camera.next_roff_time = 0; - if ( g_entities[0].inuse && g_entities[0].client ) - { - //Player zero not allowed to do anything - VectorClear( g_entities[0].client->ps.velocity ); + if (g_entities[0].inuse && g_entities[0].client) { + // Player zero not allowed to do anything + VectorClear(g_entities[0].client->ps.velocity); g_entities[0].contents = 0; - if ( cg.zoomMode ) - { + if (cg.zoomMode) { // need to shut off some form of zooming cg.zoomMode = 0; } - if ( g_entities[0].client->ps.saberInFlight && g_entities[0].client->ps.saberActive ) - {//saber is out + if (g_entities[0].client->ps.saberInFlight && g_entities[0].client->ps.saberActive) { // saber is out gentity_t *saberent = &g_entities[g_entities[0].client->ps.saberEntityNum]; - if ( saberent ) - { - WP_SaberCatch( &g_entities[0], saberent, qfalse ); + if (saberent) { + WP_SaberCatch(&g_entities[0], saberent, qfalse); } } - for ( int i = 0; i < NUM_FORCE_POWERS; i++ ) - {//deactivate any active force powers + for (int i = 0; i < NUM_FORCE_POWERS; i++) { // deactivate any active force powers g_entities[0].client->ps.forcePowerDuration[i] = 0; -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); - if ( g_entities[0].client->ps.forcePowerDuration[i] || (g_entities[0].client->ps.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerStop( &g_entities[0], (forcePowers_t)i ); + extern void WP_ForcePowerStop(gentity_t * self, forcePowers_t forcePower); + if (g_entities[0].client->ps.forcePowerDuration[i] || (g_entities[0].client->ps.forcePowersActive & (1 << i))) { + WP_ForcePowerStop(&g_entities[0], (forcePowers_t)i); } } } @@ -133,8 +124,7 @@ CGCam_Disable ------------------------- */ -void CGCam_Disable( void ) -{ +void CGCam_Disable(void) { in_camera = false; client_camera.bar_alpha = 1.0f; @@ -142,21 +132,19 @@ void CGCam_Disable( void ) client_camera.bar_alpha_source = 1.0f; client_camera.bar_alpha_dest = 0.0f; - - client_camera.bar_height_source = 480/10; + + client_camera.bar_height_source = 480 / 10; client_camera.bar_height_dest = 0.0f; client_camera.info_state |= CAMERA_BAR_FADING; - if ( g_entities[0].inuse && g_entities[0].client ) - { - g_entities[0].contents = CONTENTS_BODY;//MASK_PLAYERSOLID; + if (g_entities[0].inuse && g_entities[0].client) { + g_entities[0].contents = CONTENTS_BODY; // MASK_PLAYERSOLID; } - gi.SendServerCommand( 0, "cts"); + gi.SendServerCommand(0, "cts"); - if ( cg_skippingcin.integer ) - {//We're skipping the cinematic and it's over now + if (cg_skippingcin.integer) { // We're skipping the cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } @@ -168,10 +156,9 @@ CGCam_SetPosition ------------------------- */ -void CGCam_SetPosition( vec3_t org ) -{ - VectorCopy( org, client_camera.origin ); - VectorCopy( client_camera.origin, cg.refdef.vieworg ); +void CGCam_SetPosition(vec3_t org) { + VectorCopy(org, client_camera.origin); + VectorCopy(client_camera.origin, cg.refdef.vieworg); } /* @@ -180,27 +167,24 @@ CGCam_Move ------------------------- */ -void CGCam_Move( vec3_t dest, float duration ) -{ - if ( client_camera.info_state & CAMERA_ROFFING ) - { +void CGCam_Move(vec3_t dest, float duration) { + if (client_camera.info_state & CAMERA_ROFFING) { client_camera.info_state &= ~CAMERA_ROFFING; } CGCam_TrackDisable(); CGCam_DistanceDisable(); - if ( !duration ) - { + if (!duration) { client_camera.info_state &= ~CAMERA_MOVING; - CGCam_SetPosition( dest ); + CGCam_SetPosition(dest); return; } client_camera.info_state |= CAMERA_MOVING; - VectorCopy( dest, client_camera.origin2 ); - + VectorCopy(dest, client_camera.origin2); + client_camera.move_duration = duration; client_camera.move_time = cg.time; } @@ -211,10 +195,9 @@ CGCam_SetAngles ------------------------- */ -void CGCam_SetAngles( vec3_t ang ) -{ - VectorCopy( ang, client_camera.angles ); - VectorCopy(client_camera.angles, cg.refdefViewAngles ); +void CGCam_SetAngles(vec3_t ang) { + VectorCopy(ang, client_camera.angles); + VectorCopy(client_camera.angles, cg.refdefViewAngles); } /* @@ -223,84 +206,60 @@ CGCam_Pan ------------------------- */ -void CGCam_Pan( vec3_t dest, vec3_t panDirection, float duration ) -{ - //vec3_t panDirection = {0, 0, 0}; - int i; - float delta1 , delta2; +void CGCam_Pan(vec3_t dest, vec3_t panDirection, float duration) { + // vec3_t panDirection = {0, 0, 0}; + int i; + float delta1, delta2; CGCam_FollowDisable(); CGCam_DistanceDisable(); - if ( !duration ) - { - CGCam_SetAngles( dest ); + if (!duration) { + CGCam_SetAngles(dest); client_camera.info_state &= ~CAMERA_PANNING; return; } - //FIXME: make the dest an absolute value, and pass in a - //panDirection as well. If a panDirection's axis value is - //zero, find the shortest difference for that axis. - //Store the delta in client_camera.angles2. - for( i = 0; i < 3; i++ ) - { - dest[i] = AngleNormalize360( dest[i] ); - delta1 = dest[i] - AngleNormalize360( client_camera.angles[i] ); - if ( delta1 < 0 ) - { + // FIXME: make the dest an absolute value, and pass in a + // panDirection as well. If a panDirection's axis value is + // zero, find the shortest difference for that axis. + // Store the delta in client_camera.angles2. + for (i = 0; i < 3; i++) { + dest[i] = AngleNormalize360(dest[i]); + delta1 = dest[i] - AngleNormalize360(client_camera.angles[i]); + if (delta1 < 0) { delta2 = delta1 + 360; - } - else - { + } else { delta2 = delta1 - 360; } - if ( !panDirection[i] ) - {//Didn't specify a direction, pick shortest - if( fabs(delta1) < fabs(delta2) ) - { + if (!panDirection[i]) { // Didn't specify a direction, pick shortest + if (fabs(delta1) < fabs(delta2)) { client_camera.angles2[i] = delta1; - } - else - { + } else { client_camera.angles2[i] = delta2; } - } - else if ( panDirection[i] < 0 ) - { - if( delta1 < 0 ) - { + } else if (panDirection[i] < 0) { + if (delta1 < 0) { client_camera.angles2[i] = delta1; - } - else if( delta1 > 0 ) - { + } else if (delta1 > 0) { client_camera.angles2[i] = delta2; - } - else - {//exact + } else { // exact client_camera.angles2[i] = 0; } - } - else if ( panDirection[i] > 0 ) - { - if( delta1 > 0 ) - { + } else if (panDirection[i] > 0) { + if (delta1 > 0) { client_camera.angles2[i] = delta1; - } - else if( delta1 < 0 ) - { + } else if (delta1 < 0) { client_camera.angles2[i] = delta2; - } - else - {//exact + } else { // exact client_camera.angles2[i] = 0; } } } - //VectorCopy( dest, client_camera.angles2 ); + // VectorCopy( dest, client_camera.angles2 ); client_camera.info_state |= CAMERA_PANNING; - + client_camera.pan_duration = duration; client_camera.pan_time = cg.time; } @@ -311,10 +270,7 @@ CGCam_SetRoll ------------------------- */ -void CGCam_SetRoll( float roll ) -{ - client_camera.angles[2] = roll; -} +void CGCam_SetRoll(float roll) { client_camera.angles[2] = roll; } /* ------------------------- @@ -322,20 +278,18 @@ CGCam_Roll ------------------------- */ -void CGCam_Roll( float dest, float duration ) -{ - if ( !duration ) - { - CGCam_SetRoll( dest ); +void CGCam_Roll(float dest, float duration) { + if (!duration) { + CGCam_SetRoll(dest); return; } - //FIXME/NOTE: this will override current panning!!! + // FIXME/NOTE: this will override current panning!!! client_camera.info_state |= CAMERA_PANNING; - - VectorCopy( client_camera.angles, client_camera.angles2 ); - client_camera.angles2[2] = AngleDelta( dest, client_camera.angles[2] ); - + + VectorCopy(client_camera.angles, client_camera.angles2); + client_camera.angles2[2] = AngleDelta(dest, client_camera.angles[2]); + client_camera.pan_duration = duration; client_camera.pan_time = cg.time; } @@ -346,10 +300,7 @@ CGCam_SetFOV ------------------------- */ -void CGCam_SetFOV( float FOV ) -{ - client_camera.FOV = FOV; -} +void CGCam_SetFOV(float FOV) { client_camera.FOV = FOV; } /* ------------------------- @@ -357,17 +308,15 @@ CGCam_Zoom ------------------------- */ -void CGCam_Zoom( float FOV, float duration ) -{ - if ( !duration ) - { - CGCam_SetFOV( FOV ); +void CGCam_Zoom(float FOV, float duration) { + if (!duration) { + CGCam_SetFOV(FOV); return; } client_camera.info_state |= CAMERA_ZOOMING; - client_camera.FOV_time = cg.time; - client_camera.FOV2 = FOV; + client_camera.FOV_time = cg.time; + client_camera.FOV2 = FOV; client_camera.FOV_duration = duration; } @@ -378,12 +327,11 @@ CGCam_Fade ------------------------- */ -void CGCam_SetFade( vec4_t dest ) -{//Instant completion +void CGCam_SetFade(vec4_t dest) { // Instant completion client_camera.info_state &= ~CAMERA_FADING; client_camera.fade_duration = 0; - VectorCopy4( dest, client_camera.fade_source ); - VectorCopy4( dest, client_camera.fade_color ); + VectorCopy4(dest, client_camera.fade_source); + VectorCopy4(dest, client_camera.fade_color); } /* @@ -392,16 +340,14 @@ CGCam_Fade ------------------------- */ -void CGCam_Fade( vec4_t source, vec4_t dest, float duration ) -{ - if ( !duration ) - { - CGCam_SetFade( dest ); +void CGCam_Fade(vec4_t source, vec4_t dest, float duration) { + if (!duration) { + CGCam_SetFade(dest); return; } - VectorCopy4( source, client_camera.fade_source ); - VectorCopy4( dest, client_camera.fade_dest ); + VectorCopy4(source, client_camera.fade_source); + VectorCopy4(dest, client_camera.fade_dest); client_camera.fade_duration = duration; client_camera.fade_time = cg.time; @@ -409,72 +355,57 @@ void CGCam_Fade( vec4_t source, vec4_t dest, float duration ) client_camera.info_state |= CAMERA_FADING; } -void CGCam_FollowDisable( void ) -{ +void CGCam_FollowDisable(void) { client_camera.info_state &= ~CAMERA_FOLLOWING; client_camera.cameraGroup[0] = 0; client_camera.cameraGroupZOfs = 0; client_camera.cameraGroupTag[0] = 0; } -void CGCam_TrackDisable( void ) -{ +void CGCam_TrackDisable(void) { client_camera.info_state &= ~CAMERA_TRACKING; client_camera.trackEntNum = ENTITYNUM_WORLD; } -void CGCam_DistanceDisable( void ) -{ - client_camera.distance = 0; -} +void CGCam_DistanceDisable(void) { client_camera.distance = 0; } /* ------------------------- CGCam_Follow ------------------------- */ -void CGCam_Follow( const char *cameraGroup, float speed, float initLerp ) -{ - //Clear any previous +void CGCam_Follow(const char *cameraGroup, float speed, float initLerp) { + // Clear any previous CGCam_FollowDisable(); - if(!cameraGroup || !cameraGroup[0]) - { + if (!cameraGroup || !cameraGroup[0]) { return; } - if ( Q_stricmp("none", (char *)cameraGroup) == 0 ) - {//Turn off all aiming + if (Q_stricmp("none", (char *)cameraGroup) == 0) { // Turn off all aiming return; } - - if ( Q_stricmp("NULL", (char *)cameraGroup) == 0 ) - {//Turn off all aiming + + if (Q_stricmp("NULL", (char *)cameraGroup) == 0) { // Turn off all aiming return; } - //NOTE: if this interrupts a pan before it's done, need to copy the cg.refdef.viewAngles to the camera.angles! + // NOTE: if this interrupts a pan before it's done, need to copy the cg.refdef.viewAngles to the camera.angles! client_camera.info_state |= CAMERA_FOLLOWING; client_camera.info_state &= ~CAMERA_PANNING; - //NULL terminate last char in case they type a name too long - Q_strncpyz( client_camera.cameraGroup, cameraGroup, sizeof( client_camera.cameraGroup ) ); + // NULL terminate last char in case they type a name too long + Q_strncpyz(client_camera.cameraGroup, cameraGroup, sizeof(client_camera.cameraGroup)); - if ( speed ) - { + if (speed) { client_camera.followSpeed = speed; - } - else - { + } else { client_camera.followSpeed = 100.0f; } - if ( initLerp ) - { + if (initLerp) { client_camera.followInitLerp = qtrue; - } - else - { + } else { client_camera.followInitLerp = qfalse; } } @@ -490,8 +421,7 @@ Q3_CameraAutoAim ------------------------- */ -void CG_CameraAutoAim( const char *name ) -{ +void CG_CameraAutoAim(const char *name) { /* gentity_t *aimEnt = NULL; @@ -523,25 +453,22 @@ void CG_CameraAutoAim( const char *name ) CGCam_Track ------------------------- */ -//void CGCam_Track( char *trackName, float speed, float duration ) -void CGCam_Track( const char *trackName, float speed, float initLerp ) -{ - gentity_t *trackEnt = NULL; +// void CGCam_Track( char *trackName, float speed, float duration ) +void CGCam_Track(const char *trackName, float speed, float initLerp) { + gentity_t *trackEnt = NULL; CGCam_TrackDisable(); - if(Q_stricmp("none", (char *)trackName) == 0) - {//turn off tracking + if (Q_stricmp("none", (char *)trackName) == 0) { // turn off tracking return; } - //NOTE: if this interrupts a move before it's done, need to copy the cg.refdef.vieworg to the camera.origin! - //This will find a path_corner now, not a misc_camera_track + // NOTE: if this interrupts a move before it's done, need to copy the cg.refdef.vieworg to the camera.origin! + // This will find a path_corner now, not a misc_camera_track trackEnt = G_Find(NULL, FOFS(targetname), (char *)trackName); - if ( !trackEnt ) - { - gi.Printf(S_COLOR_RED"ERROR: %s camera track target not found\n", trackName); + if (!trackEnt) { + gi.Printf(S_COLOR_RED "ERROR: %s camera track target not found\n", trackName); return; } @@ -549,16 +476,13 @@ void CGCam_Track( const char *trackName, float speed, float initLerp ) client_camera.info_state &= ~CAMERA_MOVING; client_camera.trackEntNum = trackEnt->s.number; - client_camera.initSpeed = speed/10.0f; + client_camera.initSpeed = speed / 10.0f; client_camera.speed = speed; client_camera.nextTrackEntUpdateTime = cg.time; - if ( initLerp ) - { + if (initLerp) { client_camera.trackInitLerp = qtrue; - } - else - { + } else { client_camera.trackInitLerp = qfalse; } /* @@ -567,27 +491,24 @@ void CGCam_Track( const char *trackName, float speed, float initLerp ) } */ - //Set a moveDir - VectorSubtract( trackEnt->currentOrigin, client_camera.origin, client_camera.moveDir ); + // Set a moveDir + VectorSubtract(trackEnt->currentOrigin, client_camera.origin, client_camera.moveDir); - if ( !client_camera.trackInitLerp ) - {//want to snap to first position - //Snap to trackEnt's origin - VectorCopy( trackEnt->currentOrigin, client_camera.origin ); + if (!client_camera.trackInitLerp) { // want to snap to first position + // Snap to trackEnt's origin + VectorCopy(trackEnt->currentOrigin, client_camera.origin); - //Set new moveDir if trackEnt has a next path_corner - //Possible that track has no next point, in which case we won't be moving anyway - if ( trackEnt->target && trackEnt->target[0] ) - { - gentity_t *newTrackEnt = G_Find( NULL, FOFS(targetname), trackEnt->target ); - if ( newTrackEnt ) - { - VectorSubtract( newTrackEnt->currentOrigin, client_camera.origin, client_camera.moveDir ); + // Set new moveDir if trackEnt has a next path_corner + // Possible that track has no next point, in which case we won't be moving anyway + if (trackEnt->target && trackEnt->target[0]) { + gentity_t *newTrackEnt = G_Find(NULL, FOFS(targetname), trackEnt->target); + if (newTrackEnt) { + VectorSubtract(newTrackEnt->currentOrigin, client_camera.origin, client_camera.moveDir); } } } - VectorNormalize( client_camera.moveDir ); + VectorNormalize(client_camera.moveDir); } /* @@ -603,8 +524,7 @@ Q3_CameraAutoTrack ------------------------- */ -void CG_CameraAutoTrack( const char *name ) -{ +void CG_CameraAutoTrack(const char *name) { /* gentity_t *trackEnt = NULL; @@ -637,36 +557,28 @@ CGCam_Distance ------------------------- */ -void CGCam_Distance( float distance, float initLerp ) -{ +void CGCam_Distance(float distance, float initLerp) { client_camera.distance = distance; - if ( initLerp ) - { + if (initLerp) { client_camera.distanceInitLerp = qtrue; - } - else - { + } else { client_camera.distanceInitLerp = qfalse; } } //======================================================================================== +void CGCam_FollowUpdate(void) { + vec3_t center, dir, cameraAngles, vec, focus[MAX_CAMERA_GROUP_SUBJECTS]; // No more than 16 subjects in a cameraGroup + gentity_t *from = NULL; + centity_t *fromCent = NULL; + int num_subjects = 0, i; + qboolean focused = qfalse; -void CGCam_FollowUpdate ( void ) -{ - vec3_t center, dir, cameraAngles, vec, focus[MAX_CAMERA_GROUP_SUBJECTS];//No more than 16 subjects in a cameraGroup - gentity_t *from = NULL; - centity_t *fromCent = NULL; - int num_subjects = 0, i; - qboolean focused = qfalse; - - if ( client_camera.cameraGroup[0] ) - { - //Stay centered in my cameraGroup, if I have one - while( NULL != (from = G_Find(from, FOFS(cameraGroup), client_camera.cameraGroup))) - { + if (client_camera.cameraGroup[0]) { + // Stay centered in my cameraGroup, if I have one + while (NULL != (from = G_Find(from, FOFS(cameraGroup), client_camera.cameraGroup))) { /* if ( from->s.number == client_camera.aimEntNum ) {//This is the misc_camera_focus, we'll be removing this ent altogether eventually @@ -674,93 +586,80 @@ void CGCam_FollowUpdate ( void ) } */ - if ( num_subjects >= MAX_CAMERA_GROUP_SUBJECTS ) - { - gi.Printf(S_COLOR_RED"ERROR: Too many subjects in shot composition %s\n", client_camera.cameraGroup); + if (num_subjects >= MAX_CAMERA_GROUP_SUBJECTS) { + gi.Printf(S_COLOR_RED "ERROR: Too many subjects in shot composition %s\n", client_camera.cameraGroup); break; } fromCent = &cg_entities[from->s.number]; - if ( !fromCent ) - { + if (!fromCent) { continue; } focused = qfalse; - if ( from->client && client_camera.cameraGroupTag[0] && fromCent->gent->ghoul2.size() ) - { - int newBolt = gi.G2API_AddBolt( &fromCent->gent->ghoul2[from->playerModel], client_camera.cameraGroupTag ); - if ( newBolt != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t fromAngles = {0,from->client->ps.legsYaw,0}; + if (from->client && client_camera.cameraGroupTag[0] && fromCent->gent->ghoul2.size()) { + int newBolt = gi.G2API_AddBolt(&fromCent->gent->ghoul2[from->playerModel], client_camera.cameraGroupTag); + if (newBolt != -1) { + mdxaBone_t boltMatrix; + vec3_t fromAngles = {0, from->client->ps.legsYaw, 0}; - gi.G2API_GetBoltMatrix( fromCent->gent->ghoul2, from->playerModel, newBolt, &boltMatrix, fromAngles, fromCent->lerpOrigin, cg.time, cgs.model_draw, fromCent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, focus[num_subjects] ); + gi.G2API_GetBoltMatrix(fromCent->gent->ghoul2, from->playerModel, newBolt, &boltMatrix, fromAngles, fromCent->lerpOrigin, cg.time, + cgs.model_draw, fromCent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, focus[num_subjects]); focused = qtrue; } } - if ( !focused ) - { - if ( from->s.pos.trType != TR_STATIONARY ) -// if ( from->s.pos.trType == TR_INTERPOLATE ) - {//use interpolated origin? - if ( !VectorCompare( vec3_origin, fromCent->lerpOrigin ) ) - {//hunh? Somehow we've never seen this gentity on the client, so there is no lerpOrigin, so cheat over to the game and use the currentOrigin - VectorCopy( from->currentOrigin, focus[num_subjects] ); + if (!focused) { + if (from->s.pos.trType != TR_STATIONARY) + // if ( from->s.pos.trType == TR_INTERPOLATE ) + { // use interpolated origin? + if (!VectorCompare(vec3_origin, fromCent->lerpOrigin)) { // hunh? Somehow we've never seen this gentity on the client, so there is no + // lerpOrigin, so cheat over to the game and use the currentOrigin + VectorCopy(from->currentOrigin, focus[num_subjects]); + } else { + VectorCopy(fromCent->lerpOrigin, focus[num_subjects]); } - else - { - VectorCopy( fromCent->lerpOrigin, focus[num_subjects] ); - } - } - else - { + } else { VectorCopy(from->currentOrigin, focus[num_subjects]); - } - //FIXME: make a list here of their s.numbers instead so we can do other stuff with the list below - if ( from->client ) - {//Track to their eyes - FIXME: maybe go off a tag? - //FIXME: - //Based on FOV and distance to subject from camera, pick the point that - //keeps eyes 3/4 up from bottom of screen... what about bars? + } + // FIXME: make a list here of their s.numbers instead so we can do other stuff with the list below + if (from->client) { // Track to their eyes - FIXME: maybe go off a tag? + // FIXME: + // Based on FOV and distance to subject from camera, pick the point that + // keeps eyes 3/4 up from bottom of screen... what about bars? focus[num_subjects][2] += from->client->ps.viewheight; } } - if ( client_camera.cameraGroupZOfs ) - { + if (client_camera.cameraGroupZOfs) { focus[num_subjects][2] += client_camera.cameraGroupZOfs; } num_subjects++; } - if ( !num_subjects ) // Bad cameragroup + if (!num_subjects) // Bad cameragroup { #ifndef FINAL_BUILD - gi.Printf(S_COLOR_RED"ERROR: Camera Focus unable to locate cameragroup: %s\n", client_camera.cameraGroup); + gi.Printf(S_COLOR_RED "ERROR: Camera Focus unable to locate cameragroup: %s\n", client_camera.cameraGroup); #endif return; } - //Now average all points - VectorCopy( focus[0], center ); - for( i = 1; i < num_subjects; i++ ) - { - VectorAdd( focus[i], center, center ); + // Now average all points + VectorCopy(focus[0], center); + for (i = 1; i < num_subjects; i++) { + VectorAdd(focus[i], center, center); } - VectorScale( center, 1.0f/((float)num_subjects), center ); - } - else - { + VectorScale(center, 1.0f / ((float)num_subjects), center); + } else { return; } - //Need to set a speed to keep a distance from - //the subject- fixme: only do this if have a distance - //set - VectorSubtract( client_camera.subjectPos, center, vec ); - client_camera.subjectSpeed = VectorLengthSquared( vec ) * 100.0f / cg.frametime; + // Need to set a speed to keep a distance from + // the subject- fixme: only do this if have a distance + // set + VectorSubtract(client_camera.subjectPos, center, vec); + client_camera.subjectSpeed = VectorLengthSquared(vec) * 100.0f / cg.frametime; /* if ( !cg_skippingcin.integer ) @@ -768,232 +667,183 @@ void CGCam_FollowUpdate ( void ) Com_Printf( S_COLOR_RED"org: %s\n", vtos(center) ); } */ - VectorCopy( center, client_camera.subjectPos ); + VectorCopy(center, client_camera.subjectPos); - VectorSubtract( center, cg.refdef.vieworg, dir );//can't use client_camera.origin because it's not updated until the end of the move. + VectorSubtract(center, cg.refdef.vieworg, dir); // can't use client_camera.origin because it's not updated until the end of the move. - //Get desired angle + // Get desired angle vectoangles(dir, cameraAngles); - - if ( client_camera.followInitLerp ) - {//Lerping - float frac = cg.frametime/100.0f * client_camera.followSpeed/100.f; - for( i = 0; i < 3; i++ ) - { - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); - cameraAngles[i] = AngleNormalize180( client_camera.angles[i] + frac * AngleNormalize180(cameraAngles[i] - client_camera.angles[i]) ); - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); + + if (client_camera.followInitLerp) { // Lerping + float frac = cg.frametime / 100.0f * client_camera.followSpeed / 100.f; + for (i = 0; i < 3; i++) { + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); + cameraAngles[i] = AngleNormalize180(client_camera.angles[i] + frac * AngleNormalize180(cameraAngles[i] - client_camera.angles[i])); + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); } #if 0 Com_Printf( "%s\n", vtos(cameraAngles) ); #endif - } - else - {//Snapping, should do this first time if follow_lerp_to_start_duration is zero - //will lerp from this point on + } else { // Snapping, should do this first time if follow_lerp_to_start_duration is zero + // will lerp from this point on client_camera.followInitLerp = qtrue; - for( i = 0; i < 3; i++ ) - {//normalize so that when we start lerping, it doesn't freak out - cameraAngles[i] = AngleNormalize180( cameraAngles[i] ); + for (i = 0; i < 3; i++) { // normalize so that when we start lerping, it doesn't freak out + cameraAngles[i] = AngleNormalize180(cameraAngles[i]); } - //So tracker doesn't move right away thinking the first angle change - //is the subject moving... FIXME: shouldn't set this until lerp done OR snapped? + // So tracker doesn't move right away thinking the first angle change + // is the subject moving... FIXME: shouldn't set this until lerp done OR snapped? client_camera.subjectSpeed = 0; } - //Point camera to lerp angles + // Point camera to lerp angles /* if ( !cg_skippingcin.integer ) { Com_Printf( "ang: %s\n", vtos(cameraAngles) ); } */ - VectorCopy( cameraAngles, client_camera.angles ); + VectorCopy(cameraAngles, client_camera.angles); } -void CGCam_TrackEntUpdate ( void ) -{//FIXME: only do every 100 ms - gentity_t *trackEnt = NULL; - gentity_t *newTrackEnt = NULL; - qboolean reached = qfalse; - vec3_t vec; - float dist; +void CGCam_TrackEntUpdate(void) { // FIXME: only do every 100 ms + gentity_t *trackEnt = NULL; + gentity_t *newTrackEnt = NULL; + qboolean reached = qfalse; + vec3_t vec; + float dist; - if ( client_camera.trackEntNum >= 0 && client_camera.trackEntNum < ENTITYNUM_WORLD ) - {//We're already heading to a path_corner + if (client_camera.trackEntNum >= 0 && client_camera.trackEntNum < ENTITYNUM_WORLD) { // We're already heading to a path_corner trackEnt = &g_entities[client_camera.trackEntNum]; - VectorSubtract( trackEnt->currentOrigin, client_camera.origin, vec ); - dist = VectorLengthSquared( vec ); - if ( dist < 256 )//16 squared - {//FIXME: who should be doing the using here? - G_UseTargets( trackEnt, trackEnt ); + VectorSubtract(trackEnt->currentOrigin, client_camera.origin, vec); + dist = VectorLengthSquared(vec); + if (dist < 256) // 16 squared + { // FIXME: who should be doing the using here? + G_UseTargets(trackEnt, trackEnt); reached = qtrue; } } - - if ( trackEnt && reached ) - { - - if ( trackEnt->target && trackEnt->target[0] ) - {//Find our next path_corner - newTrackEnt = G_Find( NULL, FOFS(targetname), trackEnt->target ); - if ( newTrackEnt ) - { - if ( newTrackEnt->radius < 0 ) - {//Don't bother trying to maintain a radius + + if (trackEnt && reached) { + + if (trackEnt->target && trackEnt->target[0]) { // Find our next path_corner + newTrackEnt = G_Find(NULL, FOFS(targetname), trackEnt->target); + if (newTrackEnt) { + if (newTrackEnt->radius < 0) { // Don't bother trying to maintain a radius client_camera.distance = 0; client_camera.speed = client_camera.initSpeed; - } - else if ( newTrackEnt->radius > 0 ) - { + } else if (newTrackEnt->radius > 0) { client_camera.distance = newTrackEnt->radius; } - if ( newTrackEnt->speed < 0 ) - {//go back to our default speed + if (newTrackEnt->speed < 0) { // go back to our default speed client_camera.speed = client_camera.initSpeed; - } - else if ( newTrackEnt->speed > 0 ) - { - client_camera.speed = newTrackEnt->speed/10.0f; + } else if (newTrackEnt->speed > 0) { + client_camera.speed = newTrackEnt->speed / 10.0f; } } - } - else - {//stop thinking if this is the last one + } else { // stop thinking if this is the last one CGCam_TrackDisable(); } } - if ( newTrackEnt ) - {//Update will lerp this - client_camera.info_state |= CAMERA_TRACKING; - client_camera.trackEntNum = newTrackEnt->s.number; - VectorCopy( newTrackEnt->currentOrigin, client_camera.trackToOrg ); + if (newTrackEnt) { // Update will lerp this + client_camera.info_state |= CAMERA_TRACKING; + client_camera.trackEntNum = newTrackEnt->s.number; + VectorCopy(newTrackEnt->currentOrigin, client_camera.trackToOrg); } client_camera.nextTrackEntUpdateTime = cg.time + 100; } -void CGCam_TrackUpdate ( void ) -{ - vec3_t goalVec, curVec, trackPos, vec; - float goalDist, dist; - //qboolean slowDown = qfalse; +void CGCam_TrackUpdate(void) { + vec3_t goalVec, curVec, trackPos, vec; + float goalDist, dist; + // qboolean slowDown = qfalse; - if ( client_camera.nextTrackEntUpdateTime <= cg.time ) - { + if (client_camera.nextTrackEntUpdateTime <= cg.time) { CGCam_TrackEntUpdate(); } - VectorSubtract( client_camera.trackToOrg, client_camera.origin, goalVec ); - goalDist = VectorNormalize( goalVec ); - if ( goalDist > 100 ) - { + VectorSubtract(client_camera.trackToOrg, client_camera.origin, goalVec); + goalDist = VectorNormalize(goalVec); + if (goalDist > 100) { goalDist = 100; - } - else if ( goalDist < 10 ) - { + } else if (goalDist < 10) { goalDist = 10; } - if ( client_camera.distance && client_camera.info_state & CAMERA_FOLLOWING ) - { - float adjust = 0.0f, desiredSpeed = 0.0f; - float dot; + if (client_camera.distance && client_camera.info_state & CAMERA_FOLLOWING) { + float adjust = 0.0f, desiredSpeed = 0.0f; + float dot; - if ( !client_camera.distanceInitLerp ) - { - VectorSubtract( client_camera.origin, client_camera.subjectPos, vec ); - VectorNormalize( vec ); - //FIXME: use client_camera.moveDir here? - VectorMA( client_camera.subjectPos, client_camera.distance, vec, client_camera.origin ); - //Snap to first time only + if (!client_camera.distanceInitLerp) { + VectorSubtract(client_camera.origin, client_camera.subjectPos, vec); + VectorNormalize(vec); + // FIXME: use client_camera.moveDir here? + VectorMA(client_camera.subjectPos, client_camera.distance, vec, client_camera.origin); + // Snap to first time only client_camera.distanceInitLerp = qtrue; return; - } - else if ( client_camera.subjectSpeed > 0.05f ) - {//Don't start moving until subject moves - VectorSubtract( client_camera.subjectPos, client_camera.origin, vec ); + } else if (client_camera.subjectSpeed > 0.05f) { // Don't start moving until subject moves + VectorSubtract(client_camera.subjectPos, client_camera.origin, vec); dist = VectorNormalize(vec); dot = DotProduct(goalVec, vec); - if ( dist > client_camera.distance ) - {//too far away - if ( dot > 0 ) - {//Camera is moving toward the subject - adjust = (dist - client_camera.distance);//Speed up - } - else if ( dot < 0 ) - {//Camera is moving away from the subject - adjust = (dist - client_camera.distance) * -1.0f;//Slow down - } - } - else if ( dist < client_camera.distance ) - {//too close - if(dot > 0) - {//Camera is moving toward the subject - adjust = (client_camera.distance - dist) * -1.0f;//Slow down + if (dist > client_camera.distance) { // too far away + if (dot > 0) { // Camera is moving toward the subject + adjust = (dist - client_camera.distance); // Speed up + } else if (dot < 0) { // Camera is moving away from the subject + adjust = (dist - client_camera.distance) * -1.0f; // Slow down } - else if(dot < 0) - {//Camera is moving away from the subject - adjust = (client_camera.distance - dist);//Speed up + } else if (dist < client_camera.distance) { // too close + if (dot > 0) { // Camera is moving toward the subject + adjust = (client_camera.distance - dist) * -1.0f; // Slow down + } else if (dot < 0) { // Camera is moving away from the subject + adjust = (client_camera.distance - dist); // Speed up } } - - //Speed of the focus + our error - //desiredSpeed = aimCent->gent->speed + (adjust * cg.frametime/100.0f);//cg.frameInterpolation); - desiredSpeed = (adjust);// * cg.frametime/100.0f);//cg.frameInterpolation); - - //self->moveInfo.speed = desiredSpeed; - - //Don't change speeds faster than 10 every 10th of a second - float max_allowed_accel = MAX_ACCEL_PER_FRAME * (cg.frametime/100.0f); - - if ( !client_camera.subjectSpeed ) - {//full stop + + // Speed of the focus + our error + // desiredSpeed = aimCent->gent->speed + (adjust * cg.frametime/100.0f);//cg.frameInterpolation); + desiredSpeed = (adjust); // * cg.frametime/100.0f);//cg.frameInterpolation); + + // self->moveInfo.speed = desiredSpeed; + + // Don't change speeds faster than 10 every 10th of a second + float max_allowed_accel = MAX_ACCEL_PER_FRAME * (cg.frametime / 100.0f); + + if (!client_camera.subjectSpeed) { // full stop client_camera.speed = desiredSpeed; - } - else if ( client_camera.speed - desiredSpeed > max_allowed_accel ) - {//new speed much slower, slow down at max accel + } else if (client_camera.speed - desiredSpeed > max_allowed_accel) { // new speed much slower, slow down at max accel client_camera.speed -= max_allowed_accel; - } - else if ( desiredSpeed - client_camera.speed > max_allowed_accel ) - {//new speed much faster, speed up at max accel + } else if (desiredSpeed - client_camera.speed > max_allowed_accel) { // new speed much faster, speed up at max accel client_camera.speed += max_allowed_accel; - } - else - {//remember this speed + } else { // remember this speed client_camera.speed = desiredSpeed; } - //Com_Printf("Speed: %4.2f (%4.2f)\n", self->moveInfo.speed, aimCent->gent->speed); + // Com_Printf("Speed: %4.2f (%4.2f)\n", self->moveInfo.speed, aimCent->gent->speed); } + } else { + // slowDown = qtrue; } - else - { - //slowDown = qtrue; - } - - //FIXME: this probably isn't right, round it out more - VectorScale( goalVec, cg.frametime/100.0f, goalVec ); - VectorScale( client_camera.moveDir, (100.0f - cg.frametime)/100.0f, curVec ); - VectorAdd( goalVec, curVec, client_camera.moveDir ); - VectorNormalize( client_camera.moveDir ); + // FIXME: this probably isn't right, round it out more + VectorScale(goalVec, cg.frametime / 100.0f, goalVec); + VectorScale(client_camera.moveDir, (100.0f - cg.frametime) / 100.0f, curVec); + VectorAdd(goalVec, curVec, client_camera.moveDir); + VectorNormalize(client_camera.moveDir); /*if(slowDown) { VectorMA( client_camera.origin, client_camera.speed * goalDist/100.0f * cg.frametime/100.0f, client_camera.moveDir, trackPos ); } else*/ - { - VectorMA( client_camera.origin, client_camera.speed * cg.frametime/100.0f , client_camera.moveDir, trackPos ); - } + { VectorMA(client_camera.origin, client_camera.speed * cg.frametime / 100.0f, client_camera.moveDir, trackPos); } - //FIXME: Implement - //Need to find point on camera's path that is closest to the desired distance from subject - //OR: Need to intelligently pick this desired distance based on framing... - VectorCopy( trackPos, client_camera.origin ); + // FIXME: Implement + // Need to find point on camera's path that is closest to the desired distance from subject + // OR: Need to intelligently pick this desired distance based on framing... + VectorCopy(trackPos, client_camera.origin); } //========================================================================================= @@ -1004,18 +854,18 @@ CGCam_UpdateBarFade ------------------------- */ -void CGCam_UpdateBarFade( void ) -{ - if ( client_camera.bar_time + BAR_DURATION < cg.time ) - { +void CGCam_UpdateBarFade(void) { + if (client_camera.bar_time + BAR_DURATION < cg.time) { client_camera.bar_alpha = client_camera.bar_alpha_dest; client_camera.info_state &= ~CAMERA_BAR_FADING; client_camera.bar_height = client_camera.bar_height_dest; - } - else - { - client_camera.bar_alpha = client_camera.bar_alpha_source + ( ( client_camera.bar_alpha_dest - client_camera.bar_alpha_source ) / BAR_DURATION ) * ( cg.time - client_camera.bar_time );; - client_camera.bar_height = client_camera.bar_height_source + ( ( client_camera.bar_height_dest - client_camera.bar_height_source ) / BAR_DURATION ) * ( cg.time - client_camera.bar_time );; + } else { + client_camera.bar_alpha = client_camera.bar_alpha_source + + ((client_camera.bar_alpha_dest - client_camera.bar_alpha_source) / BAR_DURATION) * (cg.time - client_camera.bar_time); + ; + client_camera.bar_height = client_camera.bar_height_source + + ((client_camera.bar_height_dest - client_camera.bar_height_source) / BAR_DURATION) * (cg.time - client_camera.bar_time); + ; } } @@ -1025,20 +875,16 @@ CGCam_UpdateFade ------------------------- */ -void CGCam_UpdateFade( void ) -{ - if ( client_camera.info_state & CAMERA_FADING ) - { - if ( client_camera.fade_time + client_camera.fade_duration < cg.time ) - { - VectorCopy4( client_camera.fade_dest, client_camera.fade_color ); +void CGCam_UpdateFade(void) { + if (client_camera.info_state & CAMERA_FADING) { + if (client_camera.fade_time + client_camera.fade_duration < cg.time) { + VectorCopy4(client_camera.fade_dest, client_camera.fade_color); client_camera.info_state &= ~CAMERA_FADING; - } - else - { - for ( int i = 0; i < 4; i++ ) - { - client_camera.fade_color[i] = client_camera.fade_source[i] + (( ( client_camera.fade_dest[i] - client_camera.fade_source[i] ) ) / client_camera.fade_duration ) * ( cg.time - client_camera.fade_time ); + } else { + for (int i = 0; i < 4; i++) { + client_camera.fade_color[i] = + client_camera.fade_source[i] + + (((client_camera.fade_dest[i] - client_camera.fade_source[i])) / client_camera.fade_duration) * (cg.time - client_camera.fade_time); } } } @@ -1048,132 +894,102 @@ void CGCam_UpdateFade( void ) CGCam_Update ------------------------- */ -static void CGCam_Roff( void ); +static void CGCam_Roff(void); -void CGCam_Update( void ) -{ - int i; - qboolean checkFollow = qfalse; - qboolean checkTrack = qfalse; +void CGCam_Update(void) { + int i; + qboolean checkFollow = qfalse; + qboolean checkTrack = qfalse; // Apply new roff data to the camera as needed - if ( client_camera.info_state & CAMERA_ROFFING ) - { + if (client_camera.info_state & CAMERA_ROFFING) { CGCam_Roff(); } - //Check for a zoom - if ( client_camera.info_state & CAMERA_ZOOMING ) - { - float actualFOV_X; + // Check for a zoom + if (client_camera.info_state & CAMERA_ZOOMING) { + float actualFOV_X; - if ( client_camera.FOV_time + client_camera.FOV_duration < cg.time ) - { + if (client_camera.FOV_time + client_camera.FOV_duration < cg.time) { actualFOV_X = client_camera.FOV = client_camera.FOV2; client_camera.info_state &= ~CAMERA_ZOOMING; + } else { + actualFOV_X = client_camera.FOV + (((client_camera.FOV2 - client_camera.FOV)) / client_camera.FOV_duration) * (cg.time - client_camera.FOV_time); } - else - { - actualFOV_X = client_camera.FOV + (( ( client_camera.FOV2 - client_camera.FOV ) ) / client_camera.FOV_duration ) * ( cg.time - client_camera.FOV_time ); - } - CG_CalcFOVFromX( actualFOV_X ); - } - else - { - CG_CalcFOVFromX( client_camera.FOV ); + CG_CalcFOVFromX(actualFOV_X); + } else { + CG_CalcFOVFromX(client_camera.FOV); } - //Check for roffing angles - if ( (client_camera.info_state & CAMERA_ROFFING) && !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - for ( i = 0; i < 3; i++ ) - { - cg.refdefViewAngles[i] = client_camera.angles[i] + ( client_camera.angles2[i] / client_camera.pan_duration ) * ( cg.time - client_camera.pan_time ); + // Check for roffing angles + if ((client_camera.info_state & CAMERA_ROFFING) && !(client_camera.info_state & CAMERA_FOLLOWING)) { + for (i = 0; i < 3; i++) { + cg.refdefViewAngles[i] = client_camera.angles[i] + (client_camera.angles2[i] / client_camera.pan_duration) * (cg.time - client_camera.pan_time); } - } - else if ( client_camera.info_state & CAMERA_PANNING ) - { - //Note: does not actually change the camera's angles until the pan time is done! - if ( client_camera.pan_time + client_camera.pan_duration < cg.time ) - {//finished panning - for ( i = 0; i < 3; i++ ) - { - client_camera.angles[i] = AngleNormalize360( ( client_camera.angles[i] + client_camera.angles2[i] ) ); + } else if (client_camera.info_state & CAMERA_PANNING) { + // Note: does not actually change the camera's angles until the pan time is done! + if (client_camera.pan_time + client_camera.pan_duration < cg.time) { // finished panning + for (i = 0; i < 3; i++) { + client_camera.angles[i] = AngleNormalize360((client_camera.angles[i] + client_camera.angles2[i])); } client_camera.info_state &= ~CAMERA_PANNING; - VectorCopy(client_camera.angles, cg.refdefViewAngles ); - } - else - {//still panning - for ( i = 0; i < 3; i++ ) - { - //NOTE: does not store the resultant angle in client_camera.angles until pan is done - cg.refdefViewAngles[i] = client_camera.angles[i] + ( client_camera.angles2[i] / client_camera.pan_duration ) * ( cg.time - client_camera.pan_time ); + VectorCopy(client_camera.angles, cg.refdefViewAngles); + } else { // still panning + for (i = 0; i < 3; i++) { + // NOTE: does not store the resultant angle in client_camera.angles until pan is done + cg.refdefViewAngles[i] = client_camera.angles[i] + (client_camera.angles2[i] / client_camera.pan_duration) * (cg.time - client_camera.pan_time); } } - } - else - { + } else { checkFollow = qtrue; } - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); - //Check for movement - if ( client_camera.info_state & CAMERA_MOVING ) - { - //NOTE: does not actually move the camera until the movement time is done! - if ( client_camera.move_time + client_camera.move_duration < cg.time ) - { - VectorCopy( client_camera.origin2, client_camera.origin ); + // Check for movement + if (client_camera.info_state & CAMERA_MOVING) { + // NOTE: does not actually move the camera until the movement time is done! + if (client_camera.move_time + client_camera.move_duration < cg.time) { + VectorCopy(client_camera.origin2, client_camera.origin); client_camera.info_state &= ~CAMERA_MOVING; - VectorCopy( client_camera.origin, cg.refdef.vieworg ); - } - else - { - for ( i = 0; i < 3; i++ ) - { - cg.refdef.vieworg[i] = client_camera.origin[i] + (( ( client_camera.origin2[i] - client_camera.origin[i] ) ) / client_camera.move_duration ) * ( cg.time - client_camera.move_time ); + VectorCopy(client_camera.origin, cg.refdef.vieworg); + } else { + for (i = 0; i < 3; i++) { + cg.refdef.vieworg[i] = client_camera.origin[i] + (((client_camera.origin2[i] - client_camera.origin[i])) / client_camera.move_duration) * + (cg.time - client_camera.move_time); } } - } - else - { + } else { checkTrack = qtrue; } - if ( checkFollow ) - { - if ( client_camera.info_state & CAMERA_FOLLOWING ) - {//This needs to be done after camera movement + if (checkFollow) { + if (client_camera.info_state & CAMERA_FOLLOWING) { // This needs to be done after camera movement CGCam_FollowUpdate(); } - VectorCopy(client_camera.angles, cg.refdefViewAngles ); + VectorCopy(client_camera.angles, cg.refdefViewAngles); } - if ( checkTrack ) - { - if ( client_camera.info_state & CAMERA_TRACKING ) - {//This has to run AFTER Follow if the camera is following a cameraGroup + if (checkTrack) { + if (client_camera.info_state & CAMERA_TRACKING) { // This has to run AFTER Follow if the camera is following a cameraGroup CGCam_TrackUpdate(); } - VectorCopy( client_camera.origin, cg.refdef.vieworg ); + VectorCopy(client_camera.origin, cg.refdef.vieworg); } - //Bar fading - if ( client_camera.info_state & CAMERA_BAR_FADING ) - { + // Bar fading + if (client_camera.info_state & CAMERA_BAR_FADING) { CGCam_UpdateBarFade(); } - //Normal fading - separate call because can finish after camera is disabled + // Normal fading - separate call because can finish after camera is disabled CGCam_UpdateFade(); - //Update shaking if there's any - //CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); - CGCam_UpdateShake( cg.refdef.vieworg, cg.refdefViewAngles ); + // Update shaking if there's any + // CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); + CGCam_UpdateShake(cg.refdef.vieworg, cg.refdefViewAngles); } /* @@ -1182,27 +998,25 @@ CGCam_DrawWideScreen ------------------------- */ -void CGCam_DrawWideScreen( void ) -{ - vec4_t modulate; +void CGCam_DrawWideScreen(void) { + vec4_t modulate; - //Only draw if visible - if ( client_camera.bar_alpha ) - { + // Only draw if visible + if (client_camera.bar_alpha) { CGCam_UpdateBarFade(); modulate[0] = modulate[1] = modulate[2] = 0.0f; modulate[3] = client_camera.bar_alpha; - - CG_FillRect( cg.refdef.x, cg.refdef.y, 640, client_camera.bar_height, modulate ); - CG_FillRect( cg.refdef.x, cg.refdef.y + 480 - client_camera.bar_height, 640, client_camera.bar_height, modulate ); + + CG_FillRect(cg.refdef.x, cg.refdef.y, 640, client_camera.bar_height, modulate); + CG_FillRect(cg.refdef.x, cg.refdef.y + 480 - client_camera.bar_height, 640, client_camera.bar_height, modulate); } - //NOTENOTE: Camera always draws the fades unless the alpha is 0 - if ( client_camera.fade_color[3] == 0.0f ) + // NOTENOTE: Camera always draws the fades unless the alpha is 0 + if (client_camera.fade_color[3] == 0.0f) return; - CG_FillRect( cg.refdef.x, cg.refdef.y, 640, 480, client_camera.fade_color ); + CG_FillRect(cg.refdef.x, cg.refdef.y, 640, 480, client_camera.fade_color); } /* @@ -1210,8 +1024,7 @@ void CGCam_DrawWideScreen( void ) CGCam_RenderScene ------------------------- */ -void CGCam_RenderScene( void ) -{ +void CGCam_RenderScene(void) { CGCam_Update(); CG_CalcVrect(); } @@ -1222,9 +1035,8 @@ CGCam_Shake ------------------------- */ -void CGCam_Shake( float intensity, int duration ) -{ - if ( intensity > MAX_SHAKE_INTENSITY ) +void CGCam_Shake(float intensity, int duration) { + if (intensity > MAX_SHAKE_INTENSITY) intensity = MAX_SHAKE_INTENSITY; client_camera.shake_intensity = intensity; @@ -1240,52 +1052,48 @@ This doesn't actually affect the camera's info, but passed information instead ------------------------- */ -void CGCam_UpdateShake( vec3_t origin, vec3_t angles ) -{ - vec3_t moveDir; +void CGCam_UpdateShake(vec3_t origin, vec3_t angles) { + vec3_t moveDir; int i; - float intensity_scale, intensity; + float intensity_scale, intensity; - if ( client_camera.shake_duration <= 0 ) + if (client_camera.shake_duration <= 0) return; - if ( cg.time > ( client_camera.shake_start + client_camera.shake_duration ) ) - { + if (cg.time > (client_camera.shake_start + client_camera.shake_duration)) { client_camera.shake_intensity = 0; client_camera.shake_duration = 0; client_camera.shake_start = 0; return; } - //intensity_scale now also takes into account FOV with 90.0 as normal - intensity_scale = 1.0f - ( (float) ( cg.time - client_camera.shake_start ) / (float) client_camera.shake_duration ) * (((client_camera.FOV+client_camera.FOV2)/2.0f)/90.0f); + // intensity_scale now also takes into account FOV with 90.0 as normal + intensity_scale = 1.0f - ((float)(cg.time - client_camera.shake_start) / (float)client_camera.shake_duration) * + (((client_camera.FOV + client_camera.FOV2) / 2.0f) / 90.0f); intensity = client_camera.shake_intensity * intensity_scale; - for ( i = 0; i < 3; i++ ) - { - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (i = 0; i < 3; i++) { + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); } - //FIXME: Lerp + // FIXME: Lerp - //Move the camera - VectorAdd( origin, moveDir, origin ); + // Move the camera + VectorAdd(origin, moveDir, origin); - for ( i=0; i < 2; i++ ) // Don't do ROLL - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (i = 0; i < 2; i++) // Don't do ROLL + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); - //FIXME: Lerp + // FIXME: Lerp - //Move the angles - VectorAdd( angles, moveDir, angles ); + // Move the angles + VectorAdd(angles, moveDir, angles); } -void CGCam_Smooth( float intensity, int duration ) -{ - client_camera.smooth_active=false; // means smooth_origin and angles are valid - if ( intensity>1.0f||intensity==0.0f||duration<1) - { +void CGCam_Smooth(float intensity, int duration) { + client_camera.smooth_active = false; // means smooth_origin and angles are valid + if (intensity > 1.0f || intensity == 0.0f || duration < 1) { client_camera.info_state &= ~CAMERA_SMOOTHING; return; } @@ -1295,31 +1103,25 @@ void CGCam_Smooth( float intensity, int duration ) client_camera.smooth_start = cg.time; } -void CGCam_UpdateSmooth( vec3_t origin, vec3_t angles ) -{ - if (!(client_camera.info_state&CAMERA_SMOOTHING)||cg.time > ( client_camera.smooth_start + client_camera.smooth_duration )) - { +void CGCam_UpdateSmooth(vec3_t origin, vec3_t angles) { + if (!(client_camera.info_state & CAMERA_SMOOTHING) || cg.time > (client_camera.smooth_start + client_camera.smooth_duration)) { client_camera.info_state &= ~CAMERA_SMOOTHING; return; } - if (!client_camera.smooth_active) - { - client_camera.smooth_active=true; - VectorCopy(origin,client_camera.smooth_origin); + if (!client_camera.smooth_active) { + client_camera.smooth_active = true; + VectorCopy(origin, client_camera.smooth_origin); return; } - float factor=client_camera.smooth_intensity; - if (client_camera.smooth_duration>200&&cg.time > ( client_camera.smooth_start + client_camera.smooth_duration-100 )) - { - factor+=(1.0f-client_camera.smooth_intensity)* - (100.0f-(client_camera.smooth_start + client_camera.smooth_duration-cg.time))/100.0f; + float factor = client_camera.smooth_intensity; + if (client_camera.smooth_duration > 200 && cg.time > (client_camera.smooth_start + client_camera.smooth_duration - 100)) { + factor += (1.0f - client_camera.smooth_intensity) * (100.0f - (client_camera.smooth_start + client_camera.smooth_duration - cg.time)) / 100.0f; } int i; - for (i=0;i<3;i++) - { - client_camera.smooth_origin[i]*=(1.0f-factor); - client_camera.smooth_origin[i]+=factor*origin[i]; - origin[i]=client_camera.smooth_origin[i]; + for (i = 0; i < 3; i++) { + client_camera.smooth_origin[i] *= (1.0f - factor); + client_camera.smooth_origin[i] += factor * origin[i]; + origin[i] = client_camera.smooth_origin[i]; } } /* @@ -1331,28 +1133,26 @@ a rof file ------------------------- */ -void CGCam_StartRoff( char *roff ) -{ +void CGCam_StartRoff(char *roff) { CGCam_FollowDisable(); CGCam_TrackDisable(); - // Set up the roff state info..we'll hijack the moving and panning code until told otherwise + // Set up the roff state info..we'll hijack the moving and panning code until told otherwise // ...CAMERA_FOLLOWING would be a case that could override this.. client_camera.info_state |= CAMERA_MOVING; client_camera.info_state |= CAMERA_PANNING; - if ( !G_LoadRoff( roff ) ) - { + if (!G_LoadRoff(roff)) { // The load failed so don't turn on the roff playback... - Com_Printf( S_COLOR_RED"ROFF camera playback failed\n" ); + Com_Printf(S_COLOR_RED "ROFF camera playback failed\n"); return; }; client_camera.info_state |= CAMERA_ROFFING; - Q_strncpyz(client_camera.sRoff,roff,sizeof(client_camera.sRoff)); + Q_strncpyz(client_camera.sRoff, roff, sizeof(client_camera.sRoff)); client_camera.roff_frame = 0; - client_camera.next_roff_time = cg.time; // I can work right away + client_camera.next_roff_time = cg.time; // I can work right away } /* @@ -1363,8 +1163,7 @@ Stops camera rof ------------------------- */ -static void CGCam_StopRoff( void ) -{ +static void CGCam_StopRoff(void) { // Clear the roff flag client_camera.info_state &= ~CAMERA_ROFFING; client_camera.info_state &= ~CAMERA_MOVING; @@ -1374,7 +1173,7 @@ static void CGCam_StopRoff( void ) ------------------------------------------------------ CGCam_Roff -Applies the sampled roff data to the camera and does +Applies the sampled roff data to the camera and does the lerping itself...this is done because the current camera interpolation doesn't seem to work all that great when you are adjusting the camera org and angles @@ -1382,92 +1181,78 @@ so often...or maybe I'm just on crack. ------------------------------------------------------ */ -static void CGCam_Roff( void ) -{ - while ( client_camera.next_roff_time <= cg.time ) - { +static void CGCam_Roff(void) { + while (client_camera.next_roff_time <= cg.time) { - int roff_id; + int roff_id; - // Make sure that the roff is cached - roff_id = G_LoadRoff( client_camera.sRoff ); + // Make sure that the roff is cached + roff_id = G_LoadRoff(client_camera.sRoff); - if ( !roff_id ) - { - return; - } + if (!roff_id) { + return; + } - roff_list_t *roff = &roffs[ roff_id - 1 ]; + roff_list_t *roff = &roffs[roff_id - 1]; - vec3_t org, ang; + vec3_t org, ang; - if ( roff->type == 2 ) - { - move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ client_camera.roff_frame ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); - } - else - { - move_rotate_t *data = &((move_rotate_t *)roff->data)[ client_camera.roff_frame ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); - } + if (roff->type == 2) { + move_rotate2_t *data = &((move_rotate2_t *)roff->data)[client_camera.roff_frame]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); + } else { + move_rotate_t *data = &((move_rotate_t *)roff->data)[client_camera.roff_frame]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); + } - // Yeah, um, I guess this just has to be negated? - ang[PITCH] = -ang[PITCH]; - ang[ROLL] = -ang[ROLL]; - // might need to to yaw as well. need a test... + // Yeah, um, I guess this just has to be negated? + ang[PITCH] = -ang[PITCH]; + ang[ROLL] = -ang[ROLL]; + // might need to to yaw as well. need a test... #ifdef _DEBUG - if ( cg_developer.integer ) - { - Com_Printf( S_COLOR_GREEN"CamROFF : o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", - org[0], org[1], org[2], - ang[0], ang[1], ang[2] ); - } + if (cg_developer.integer) { + Com_Printf(S_COLOR_GREEN "CamROFF : o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", org[0], org[1], org[2], ang[0], ang[1], ang[2]); + } #endif - if ( client_camera.roff_frame ) - { - // Don't mess with angles if we are following - if ( !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - VectorAdd( client_camera.angles, client_camera.angles2, client_camera.angles ); + if (client_camera.roff_frame) { + // Don't mess with angles if we are following + if (!(client_camera.info_state & CAMERA_FOLLOWING)) { + VectorAdd(client_camera.angles, client_camera.angles2, client_camera.angles); + } + + VectorCopy(client_camera.origin2, client_camera.origin); } - VectorCopy( client_camera.origin2, client_camera.origin ); - } + // Don't mess with angles if we are following + if (!(client_camera.info_state & CAMERA_FOLLOWING)) { + VectorCopy(ang, client_camera.angles2); + client_camera.pan_time = cg.time; + client_camera.pan_duration = roff->mFrameTime; + } - // Don't mess with angles if we are following - if ( !(client_camera.info_state & CAMERA_FOLLOWING) ) - { - VectorCopy( ang, client_camera.angles2 ); - client_camera.pan_time = cg.time; - client_camera.pan_duration = roff->mFrameTime; - } + VectorAdd(client_camera.origin, org, client_camera.origin2); - VectorAdd( client_camera.origin, org, client_camera.origin2 ); + client_camera.move_time = cg.time; + client_camera.move_duration = roff->mFrameTime; - client_camera.move_time = cg.time; - client_camera.move_duration = roff->mFrameTime; + if (++client_camera.roff_frame >= roff->frames) { + CGCam_StopRoff(); + return; + } - if ( ++client_camera.roff_frame >= roff->frames ) - { - CGCam_StopRoff(); - return; + // Check back in frameTime to get the next roff entry + client_camera.next_roff_time += roff->mFrameTime; } - - // Check back in frameTime to get the next roff entry - client_camera.next_roff_time += roff->mFrameTime; - } } -void CMD_CGCam_Disable( void ) -{ - vec4_t fade = {0, 0, 0, 0}; +void CMD_CGCam_Disable(void) { + vec4_t fade = {0, 0, 0, 0}; CGCam_Disable(); - CGCam_SetFade( fade ); + CGCam_SetFade(fade); player_locked = qfalse; } diff --git a/codeJK2/cgame/cg_consolecmds.cpp b/codeJK2/cgame/cg_consolecmds.cpp index 6a67a67b55..f7fd896802 100644 --- a/codeJK2/cgame/cg_consolecmds.cpp +++ b/codeJK2/cgame/cg_consolecmds.cpp @@ -25,15 +25,15 @@ along with this program; if not, see . // executed by a key binding #include "cg_local.h" -#include "cg_media.h" //just for cgs.... +#include "cg_media.h" //just for cgs.... -void CG_TargetCommand_f( void ); -extern qboolean player_locked; -extern void CMD_CGCam_Disable( void ); -void CG_NextInventory_f( void ); -void CG_PrevInventory_f( void ); -void CG_NextForcePower_f( void ); -void CG_PrevForcePower_f( void ); +void CG_TargetCommand_f(void); +extern qboolean player_locked; +extern void CMD_CGCam_Disable(void); +void CG_NextInventory_f(void); +void CG_PrevInventory_f(void); +void CG_NextForcePower_f(void); +void CG_PrevForcePower_f(void); /* ================= @@ -41,17 +41,17 @@ CG_TargetCommand_f ================= */ -void CG_TargetCommand_f( void ) { - int targetNum; - char test[4]; +void CG_TargetCommand_f(void) { + int targetNum; + char test[4]; targetNum = CG_CrosshairPlayer(); - if ( targetNum == -1 ) { + if (targetNum == -1) { return; } - cgi_Argv( 1, test, 4 ); - cgi_SendClientCommand( va( "gc %i %i", targetNum, atoi( test ) ) ); + cgi_Argv(1, test, 4); + cgi_SendClientCommand(va("gc %i %i", targetNum, atoi(test))); } /* @@ -61,56 +61,49 @@ CG_Viewpos_f Debugging command to print the current position ============= */ -static void CG_Viewpos_f (void) { - CG_Printf ("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], - (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], - (int)cg.refdefViewAngles[YAW]); +static void CG_Viewpos_f(void) { + CG_Printf("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], + (int)cg.refdefViewAngles[YAW]); } -void CG_WriteCam_f (void) -{ - char text[1024]; - const char *targetname; - static int numCams; +void CG_WriteCam_f(void) { + char text[1024]; + const char *targetname; + static int numCams; numCams++; - + targetname = CG_Argv(1); - if( !targetname || !targetname[0] ) - { + if (!targetname || !targetname[0]) { targetname = "nameme!"; } - CG_Printf( "Camera #%d ('%s') written to: ", numCams, targetname ); - Com_sprintf( text, sizeof(text), "//entity %d\n{\n\"classname\" \"ref_tag\"\n\"targetname\" \"%s\"\n\"origin\" \"%i %i %i\"\n\"angles\" \"%i %i %i\"\n\"fov\" \"%i\"\n}\n", numCams, targetname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], (int)cg.refdefViewAngles[0], (int)cg.refdefViewAngles[1], (int)cg.refdefViewAngles[2], cg_fov.integer ); - gi.WriteCam( text ); + CG_Printf("Camera #%d ('%s') written to: ", numCams, targetname); + Com_sprintf(text, sizeof(text), + "//entity %d\n{\n\"classname\" \"ref_tag\"\n\"targetname\" \"%s\"\n\"origin\" \"%i %i %i\"\n\"angles\" \"%i %i %i\"\n\"fov\" \"%i\"\n}\n", + numCams, targetname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], (int)cg.refdefViewAngles[0], + (int)cg.refdefViewAngles[1], (int)cg.refdefViewAngles[2], cg_fov.integer); + gi.WriteCam(text); } -void Lock_Disable ( void ) -{ - player_locked = qfalse; -} +void Lock_Disable(void) { player_locked = qfalse; } -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp -void CG_ToggleBinoculars( void ) -{ - if ( in_camera || !cg.snap ) - { +void CG_ToggleBinoculars(void) { + if (in_camera || !cg.snap) { return; } - if ( cg.zoomMode == 0 || cg.zoomMode >= 2 ) // not zoomed or currently zoomed with the disruptor or LA goggles + if (cg.zoomMode == 0 || cg.zoomMode >= 2) // not zoomed or currently zoomed with the disruptor or LA goggles { - if ( (cg.snap->ps.saberActive && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) - {//can't select binoculars when throwing saber - //FIXME: indicate this to the player + if ((cg.snap->ps.saberActive && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) { // can't select binoculars when throwing saber + // FIXME: indicate this to the player return; } - if ( cg.snap->ps.viewEntity || ( cg_entities[cg.snap->ps.clientNum].currentState.eFlags & ( EF_LOCKED_TO_WEAPON | EF_IN_ATST ))) - { + if (cg.snap->ps.viewEntity || (cg_entities[cg.snap->ps.clientNum].currentState.eFlags & (EF_LOCKED_TO_WEAPON | EF_IN_ATST))) { // can't zoom when you have a viewEntity or driving an atst or in an emplaced gun return; } @@ -118,130 +111,111 @@ void CG_ToggleBinoculars( void ) cg.zoomMode = 1; cg.zoomLocked = qfalse; - if ( cg.snap->ps.batteryCharge ) - { + if (cg.snap->ps.batteryCharge) { // when you have batteries, you can actually zoom in cg_zoomFov = 40.0f; - } - else if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + } else if (cg.overrides.active & CG_OVERRIDE_FOV) { cg_zoomFov = cg.overrides.fov; - } - else - { + } else { cg_zoomFov = cg_fov.value; } - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart ); - } - else - { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart); + } else { cg.zoomMode = 0; cg.zoomTime = cg.time; - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd ); + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd); } } -void CG_ToggleLAGoggles( void ) -{ - if ( in_camera || !cg.snap) - { +void CG_ToggleLAGoggles(void) { + if (in_camera || !cg.snap) { return; } - if ( cg.zoomMode == 0 || cg.zoomMode < 3 ) // not zoomed or currently zoomed with the disruptor or regular binoculars + if (cg.zoomMode == 0 || cg.zoomMode < 3) // not zoomed or currently zoomed with the disruptor or regular binoculars { - if ( (cg.snap->ps.saberActive && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - {//can't select binoculars when throwing saber - //FIXME: indicate this to the player + if ((cg.snap->ps.saberActive && cg.snap->ps.saberInFlight) || cg.snap->ps.stats[STAT_HEALTH] <= 0) { // can't select binoculars when throwing saber + // FIXME: indicate this to the player return; } - if ( cg.snap->ps.viewEntity || ( cg_entities[cg.snap->ps.clientNum].currentState.eFlags & ( EF_LOCKED_TO_WEAPON | EF_IN_ATST ))) - { + if (cg.snap->ps.viewEntity || (cg_entities[cg.snap->ps.clientNum].currentState.eFlags & (EF_LOCKED_TO_WEAPON | EF_IN_ATST))) { // can't zoom when you have a viewEntity or driving an atst or in an emplaced gun return; } cg.zoomMode = 3; cg.zoomLocked = qfalse; - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + if (cg.overrides.active & CG_OVERRIDE_FOV) { cg_zoomFov = cg.overrides.fov; - } - else - { + } else { cg_zoomFov = cg_fov.value; // does not zoom!! } - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart ); - } - else - { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart); + } else { cg.zoomMode = 0; cg.zoomTime = cg.time; - cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd ); + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd); } } -void CG_LoadHud_f( void) -{ +void CG_LoadHud_f(void) { const char *hudSet = cg_hudFiles.string; - if ( hudSet[0] == '\0' ) + if (hudSet[0] == '\0') hudSet = "ui/jk2hud.txt"; CG_LoadMenus(hudSet); } typedef struct { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } consoleCommand_t; -int cmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((consoleCommand_t*)b)->cmd ); -} +int cmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((consoleCommand_t *)b)->cmd); } /* This array MUST be sorted correctly by alphabetical name field */ -static consoleCommand_t commands[] = { - { "cam_disable", CMD_CGCam_Disable }, //gets out of camera mode for debuggin - { "cam_enable", CGCam_Enable }, //gets into camera mode for precise camera placement - { "dpforcenext", CG_DPNextForcePower_f }, - { "dpforceprev", CG_DPPrevForcePower_f }, - { "dpinvnext", CG_DPNextInventory_f }, - { "dpinvprev", CG_DPPrevInventory_f }, - { "dpweapnext", CG_DPNextWeapon_f }, - { "dpweapprev", CG_DPPrevWeapon_f }, - { "forcenext", CG_NextForcePower_f }, - { "forceprev", CG_PrevForcePower_f }, - { "invnext", CG_NextInventory_f }, - { "invprev", CG_PrevInventory_f }, - { "la_zoom", CG_ToggleLAGoggles }, - { "loadhud", CG_LoadHud_f }, - { "lock_disable", Lock_Disable }, //player can move now - { "nextframe", CG_TestModelNextFrame_f }, - { "nextskin", CG_TestModelNextSkin_f }, - { "prevframe", CG_TestModelPrevFrame_f }, - { "prevskin", CG_TestModelPrevSkin_f }, - { "tcmd", CG_TargetCommand_f }, - { "testG2Model", CG_TestG2Model_f}, - { "testanglespost", CG_TestModelSetAnglespost_f}, - { "testanglespre", CG_TestModelSetAnglespre_f}, - { "testanimate", CG_TestModelAnimate_f}, - { "testgun", CG_TestGun_f }, - { "testlistbones", CG_ListModelBones_f}, - { "testlistsurfaces", CG_ListModelSurfaces_f}, - { "testmodel", CG_TestModel_f }, - { "testsurface", CG_TestModelSurfaceOnOff_f }, - { "viewpos", CG_Viewpos_f }, - { "weapnext", CG_NextWeapon_f }, - { "weapon", CG_Weapon_f }, - { "weapprev", CG_PrevWeapon_f }, - { "writecam", CG_WriteCam_f }, - { "zoom", CG_ToggleBinoculars }, +static consoleCommand_t commands[] = { + {"cam_disable", CMD_CGCam_Disable}, // gets out of camera mode for debuggin + {"cam_enable", CGCam_Enable}, // gets into camera mode for precise camera placement + {"dpforcenext", CG_DPNextForcePower_f}, + {"dpforceprev", CG_DPPrevForcePower_f}, + {"dpinvnext", CG_DPNextInventory_f}, + {"dpinvprev", CG_DPPrevInventory_f}, + {"dpweapnext", CG_DPNextWeapon_f}, + {"dpweapprev", CG_DPPrevWeapon_f}, + {"forcenext", CG_NextForcePower_f}, + {"forceprev", CG_PrevForcePower_f}, + {"invnext", CG_NextInventory_f}, + {"invprev", CG_PrevInventory_f}, + {"la_zoom", CG_ToggleLAGoggles}, + {"loadhud", CG_LoadHud_f}, + {"lock_disable", Lock_Disable}, // player can move now + {"nextframe", CG_TestModelNextFrame_f}, + {"nextskin", CG_TestModelNextSkin_f}, + {"prevframe", CG_TestModelPrevFrame_f}, + {"prevskin", CG_TestModelPrevSkin_f}, + {"tcmd", CG_TargetCommand_f}, + {"testG2Model", CG_TestG2Model_f}, + {"testanglespost", CG_TestModelSetAnglespost_f}, + {"testanglespre", CG_TestModelSetAnglespre_f}, + {"testanimate", CG_TestModelAnimate_f}, + {"testgun", CG_TestGun_f}, + {"testlistbones", CG_ListModelBones_f}, + {"testlistsurfaces", CG_ListModelSurfaces_f}, + {"testmodel", CG_TestModel_f}, + {"testsurface", CG_TestModelSurfaceOnOff_f}, + {"viewpos", CG_Viewpos_f}, + {"weapnext", CG_NextWeapon_f}, + {"weapon", CG_Weapon_f}, + {"weapprev", CG_PrevWeapon_f}, + {"writecam", CG_WriteCam_f}, + {"zoom", CG_ToggleBinoculars}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -251,54 +225,52 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -qboolean CG_ConsoleCommand( void ) { - consoleCommand_t *command = NULL; +qboolean CG_ConsoleCommand(void) { + consoleCommand_t *command = NULL; - command = (consoleCommand_t *)Q_LinearSearch( CG_Argv( 0 ), commands, numCommands, sizeof( commands[0] ), cmdcmp ); + command = (consoleCommand_t *)Q_LinearSearch(CG_Argv(0), commands, numCommands, sizeof(commands[0]), cmdcmp); - if ( !command ) + if (!command) return qfalse; command->func(); return qtrue; } -static const char *gcmds[] = { - "entitylist", - "difficulty", - "force_distract", - "force_grip", - "force_heal", - "force_pull", - "force_speed", - "force_throw", - "give", - "god", - "invuse", - "kill", - "nav", - "noclip", - "notarget", - "npc", - "playerteam", - "runscript", - "saberAttackCycle", - "saberColor", - "secrets", - "setForceAll", - "setSaberAll", - "setobjective", - "setviewpos", - "taunt", - "undying", - "use_bacta", - "use_electrobinoculars", - "use_lightamp_goggles", - "use_seeker", - "use_sentry", - "viewobjective" -}; -static const size_t numgcmds = ARRAY_LEN( gcmds ); +static const char *gcmds[] = {"entitylist", + "difficulty", + "force_distract", + "force_grip", + "force_heal", + "force_pull", + "force_speed", + "force_throw", + "give", + "god", + "invuse", + "kill", + "nav", + "noclip", + "notarget", + "npc", + "playerteam", + "runscript", + "saberAttackCycle", + "saberColor", + "secrets", + "setForceAll", + "setSaberAll", + "setobjective", + "setviewpos", + "taunt", + "undying", + "use_bacta", + "use_electrobinoculars", + "use_lightamp_goggles", + "use_seeker", + "use_sentry", + "viewobjective"}; +static const size_t numgcmds = ARRAY_LEN(gcmds); /* ================= @@ -308,16 +280,16 @@ Let the client system know about all of our commands so it can perform tab completion ================= */ -void CG_InitConsoleCommands( void ) { +void CG_InitConsoleCommands(void) { size_t i; - for ( i = 0 ; i < numCommands ; i++ ) - cgi_AddCommand( commands[i].cmd ); + for (i = 0; i < numCommands; i++) + cgi_AddCommand(commands[i].cmd); // // the game server will interpret these commands, which will be automatically // forwarded to the server after they are not recognized locally // - for( i = 0; i < numgcmds; i++ ) - cgi_AddCommand( gcmds[i] ); + for (i = 0; i < numgcmds; i++) + cgi_AddCommand(gcmds[i]); } diff --git a/codeJK2/cgame/cg_credits.cpp b/codeJK2/cgame/cg_credits.cpp index 4ffde22e99..8251f4b9d4 100644 --- a/codeJK2/cgame/cg_credits.cpp +++ b/codeJK2/cgame/cg_credits.cpp @@ -27,11 +27,9 @@ along with this program; if not, see . #include "cg_local.h" #include "cg_media.h" - -#define fCARD_FADESECONDS 1.0f // fade up time, also fade down time -#define fCARD_SUSTAINSECONDS 2.0f // hold time before fade down -#define fLINE_SECONDTOSCROLLUP 15.0f // how long one line takes to scroll up the screen - +#define fCARD_FADESECONDS 1.0f // fade up time, also fade down time +#define fCARD_SUSTAINSECONDS 2.0f // hold time before fade down +#define fLINE_SECONDTOSCROLLUP 15.0f // how long one line takes to scroll up the screen #define MAX_LINE_BYTES 2048 @@ -39,167 +37,133 @@ qhandle_t ghFontHandle = 0; float gfFontScale = 1.0f; vec4_t gv4Color = {0}; -struct StringAndSize_t -{ +struct StringAndSize_t { int iStrLenPixels; std::string str; - StringAndSize_t() - { + StringAndSize_t() { iStrLenPixels = -1; str = ""; } - StringAndSize_t(const char *psString) - { + StringAndSize_t(const char *psString) { iStrLenPixels = -1; str = psString; } - StringAndSize_t & operator = (const char *psString) - { + StringAndSize_t &operator=(const char *psString) { iStrLenPixels = -1; str = psString; return *this; } - const char *c_str(void) - { - return str.c_str(); - } + const char *c_str(void) { return str.c_str(); } - int GetPixelLength(void) - { - if (iStrLenPixels == -1) - { + int GetPixelLength(void) { + if (iStrLenPixels == -1) { iStrLenPixels = cgi_R_Font_StrLenPixels(str.c_str(), ghFontHandle, gfFontScale); } return iStrLenPixels; } - bool IsEmpty(void) - { - return str.empty(); - } + bool IsEmpty(void) { return str.empty(); } }; -struct CreditCard_t -{ - int iTime; - StringAndSize_t strTitle; +struct CreditCard_t { + int iTime; + StringAndSize_t strTitle; std::vector vstrText; - CreditCard_t() - { - iTime = -1; // flag "not set yet" + CreditCard_t() { + iTime = -1; // flag "not set yet" } }; -struct CreditLine_t -{ - int iLine; - StringAndSize_t strText; +struct CreditLine_t { + int iLine; + StringAndSize_t strText; std::vector vstrText; - bool bDotted; + bool bDotted; }; -typedef std::list CreditLines_t; -typedef std::list CreditCards_t; +typedef std::list CreditLines_t; +typedef std::list CreditCards_t; -struct CreditData_t -{ - int iStartTime; +struct CreditData_t { + int iStartTime; CreditCards_t CreditCards; CreditLines_t CreditLines; - qboolean Running(void) - { - return (qboolean)(CreditCards.size() || CreditLines.size()); - } + qboolean Running(void) { return (qboolean)(CreditCards.size() || CreditLines.size()); } }; CreditData_t CreditData; - -static const char *Capitalize( const char *psTest ) -{ +static const char *Capitalize(const char *psTest) { static char sTemp[MAX_LINE_BYTES]; Q_strncpyz(sTemp, psTest, sizeof(sTemp)); - - if (!cgi_Language_IsAsian()) - { - Q_strupr(sTemp); // capitalise titles (if not asian!!!!) + + if (!cgi_Language_IsAsian()) { + Q_strupr(sTemp); // capitalise titles (if not asian!!!!) } return sTemp; } -static bool CountsAsWhiteSpaceForCaps( char c ) -{ - return !!(isspace(c) || c == '-' || c == '.' || c == '(' || c == ')'); -} -static const char *UpperCaseFirstLettersOnly( const char *psTest ) -{ +static bool CountsAsWhiteSpaceForCaps(char c) { return !!(isspace(c) || c == '-' || c == '.' || c == '(' || c == ')'); } +static const char *UpperCaseFirstLettersOnly(const char *psTest) { static char sTemp[MAX_LINE_BYTES]; Q_strncpyz(sTemp, psTest, sizeof(sTemp)); - - if (!cgi_Language_IsAsian()) - { + + if (!cgi_Language_IsAsian()) { Q_strlwr(sTemp); char *p = sTemp; - while (*p) - { - while (*p && CountsAsWhiteSpaceForCaps(*p)) p++;//(isspace(*p) || *p == '-' || *p == '.')) p++; // also copes with hyphenated names (awkward gits) - if (*p) - { + while (*p) { + while (*p && CountsAsWhiteSpaceForCaps(*p)) + p++; //(isspace(*p) || *p == '-' || *p == '.')) p++; // also copes with hyphenated names (awkward gits) + if (*p) { *p = toupper(*p); - while (*p && !CountsAsWhiteSpaceForCaps(*p)) p++; // cope with hyphenated names and initials (awkward gits) + while (*p && !CountsAsWhiteSpaceForCaps(*p)) + p++; // cope with hyphenated names and initials (awkward gits) } } } // now restore any weird stuff... // - char *p = strstr(sTemp," Mc"); // eg "Mcfarrell" should be "McFarrell" - if (p && isalpha(p[3])) - { + char *p = strstr(sTemp, " Mc"); // eg "Mcfarrell" should be "McFarrell" + if (p && isalpha(p[3])) { p[3] = toupper(p[3]); } - p = strstr(sTemp," O'"); // eg "O'flaherty" should be "O'Flaherty" - if (p && isalpha(p[3])) - { + p = strstr(sTemp, " O'"); // eg "O'flaherty" should be "O'Flaherty" + if (p && isalpha(p[3])) { p[3] = toupper(p[3]); } - p = strstr(sTemp,"Lucasarts"); - if (p) - { - p[5] = 'A'; // capitalise the 'A' in LucasArts (jeez...) + p = strstr(sTemp, "Lucasarts"); + if (p) { + p[5] = 'A'; // capitalise the 'A' in LucasArts (jeez...) } return sTemp; } -static const char *GetSubString(std::string &strResult) -{ +static const char *GetSubString(std::string &strResult) { static char sTemp[MAX_LINE_BYTES]; if (!strlen(strResult.c_str())) return NULL; - - Q_strncpyz(sTemp,strResult.c_str(),sizeof(sTemp)); - char *psSemiColon = strchr(sTemp,';'); - if ( psSemiColon) - { - *psSemiColon = '\0'; + Q_strncpyz(sTemp, strResult.c_str(), sizeof(sTemp)); - strResult.erase(0,(psSemiColon-sTemp)+1); - } - else - { + char *psSemiColon = strchr(sTemp, ';'); + if (psSemiColon) { + *psSemiColon = '\0'; + + strResult.erase(0, (psSemiColon - sTemp) + 1); + } else { // no semicolon found, probably last entry? (though i think even those have them on, oh well) // strResult.erase(); @@ -210,59 +174,51 @@ static const char *GetSubString(std::string &strResult) // sort entries by their last name (starts at back of string and moves forward until start or just before whitespace) // ... -static bool SortBySurname(const StringAndSize_t &str1, const StringAndSize_t &str2) -{ +static bool SortBySurname(const StringAndSize_t &str1, const StringAndSize_t &str2) { std::string::const_reverse_iterator rstart1 = std::find_if(str1.str.rbegin(), str1.str.rend(), isspace); std::string::const_reverse_iterator rstart2 = std::find_if(str2.str.rbegin(), str2.str.rend(), isspace); - return Q_stricmp(&*rstart1.base(), &*rstart2.base()) < 0; } - - -void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color ) -{ +void CG_Credits_Init(const char *psStripReference, vec4_t *pv4Color) { // could make these into parameters later, but for now... // ghFontHandle = cgs.media.qhFontMedium; gfFontScale = 1.0f; - memcpy(gv4Color,pv4Color,sizeof(gv4Color)); // memcpy so we can poke into alpha channel + memcpy(gv4Color, pv4Color, sizeof(gv4Color)); // memcpy so we can poke into alpha channel // first, ask the strlen of the final string... - // - int iStrLen = cgi_SP_GetStringTextString( psStripReference, NULL, 0 ); - if (!iStrLen) - { + // + int iStrLen = cgi_SP_GetStringTextString(psStripReference, NULL, 0); + if (!iStrLen) { #ifndef FINAL_BUILD Com_Printf("WARNING: CG_Credits_Init(): invalid text key :'%s'\n", psStripReference); #endif - return; + return; } // // malloc space to hold it... // - char *psMallocText = (char *) cgi_Z_Malloc( iStrLen+1, TAG_TEMP_WORKSPACE ); + char *psMallocText = (char *)cgi_Z_Malloc(iStrLen + 1, TAG_TEMP_WORKSPACE); // // now get the string... - // - iStrLen = cgi_SP_GetStringTextString( psStripReference, psMallocText, iStrLen+1 ); - //ensure we found a match - if (!iStrLen) - { - assert(0); // should never get here now, but wtf? + // + iStrLen = cgi_SP_GetStringTextString(psStripReference, psMallocText, iStrLen + 1); + // ensure we found a match + if (!iStrLen) { + assert(0); // should never get here now, but wtf? cgi_Z_Free(psMallocText); #ifndef FINAL_BUILD Com_Printf("WARNING: CG_Credits_Init(): invalid text key :'%s'\n", psStripReference); #endif - return; + return; } // read whole string in and process as cards, lines etc... // - typedef enum - { + typedef enum { eNothing = 0, eLine, eDotEntry, @@ -275,198 +231,151 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color ) qboolean bCardsFinished = qfalse; int iLineNumber = 0; const char *psTextParse = psMallocText; - while (*psTextParse != '\0') - { + while (*psTextParse != '\0') { // read a line... - // + // char sLine[MAX_LINE_BYTES]; - sLine[0]='\0'; + sLine[0] = '\0'; qboolean bWasCommand = qtrue; - while (1) - { + while (1) { qboolean bIsTrailingPunctuation; unsigned int uiLetter = cgi_AnyLanguage_ReadCharFromString(&psTextParse, &bIsTrailingPunctuation); // concat onto string so far... // - if (uiLetter == 32 && sLine[0] == '\0') - { - continue; // unless it's a space at the start of a line, in which case ignore it. + if (uiLetter == 32 && sLine[0] == '\0') { + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter == '\n' || uiLetter == '\0' ) - { + if (uiLetter == '\n' || uiLetter == '\0') { // have we got a command word?... // - if (!Q_stricmpn(sLine,"(#",2)) - { + if (!Q_stricmpn(sLine, "(#", 2)) { // yep... // - if (!Q_stricmp(sLine, "(#CARD)")) - { - if (!bCardsFinished) - { + if (!Q_stricmp(sLine, "(#CARD)")) { + if (!bCardsFinished) { eMode = eCard; - } - else - { - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW "CG_Credits_Init(): No current support for cards after scroll!\n" ); - #endif + } else { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "CG_Credits_Init(): No current support for cards after scroll!\n"); +#endif eMode = eNothing; } break; - } - else - if (!Q_stricmp(sLine, "(#TITLE)")) - { + } else if (!Q_stricmp(sLine, "(#TITLE)")) { eMode = eTitle; bCardsFinished = qtrue; break; - } - else - if (!Q_stricmp(sLine, "(#LINE)")) - { + } else if (!Q_stricmp(sLine, "(#LINE)")) { eMode = eLine; bCardsFinished = qtrue; break; - } - else - if (!Q_stricmp(sLine, "(#DOTENTRY)")) - { + } else if (!Q_stricmp(sLine, "(#DOTENTRY)")) { eMode = eDotEntry; bCardsFinished = qtrue; break; - } - else - { - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW "CG_Credits_Init(): bad keyword \"%s\"!\n", sLine ); - #endif + } else { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "CG_Credits_Init(): bad keyword \"%s\"!\n", sLine); +#endif eMode = eNothing; } - } - else - { + } else { // I guess not... // bWasCommand = qfalse; break; } - } - else - { + } else { // must be a letter... // - if (uiLetter > 255) - { - Q_strcat(sLine, sizeof(sLine), va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLine, sizeof(sLine), va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(sLine, sizeof(sLine), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLine, sizeof(sLine), va("%c", uiLetter & 0xFF)); } } } // command?... // - if (bWasCommand) - { + if (bWasCommand) { // this'll just be a mode change, so ignore... // - } - else - { + } else { // else we've got some text to display... // - switch (eMode) - { - case eNothing: break; - case eLine: - { - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber++; - CreditLine.strText = sLine; - - CreditData.CreditLines.push_back( CreditLine ); - } + switch (eMode) { + case eNothing: break; - - case eDotEntry: - { - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber; - CreditLine.bDotted = true; - - std::string strResult(sLine); - const char *p; - while ((p=GetSubString(strResult)) != NULL) - { - if (CreditLine.strText.IsEmpty()) - { - CreditLine.strText = p; - } - else - { - CreditLine.vstrText.push_back( UpperCaseFirstLettersOnly(p) ); - } + case eLine: { + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber++; + CreditLine.strText = sLine; + + CreditData.CreditLines.push_back(CreditLine); + } break; + + case eDotEntry: { + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber; + CreditLine.bDotted = true; + + std::string strResult(sLine); + const char *p; + while ((p = GetSubString(strResult)) != NULL) { + if (CreditLine.strText.IsEmpty()) { + CreditLine.strText = p; + } else { + CreditLine.vstrText.push_back(UpperCaseFirstLettersOnly(p)); } + } - if (!CreditLine.strText.IsEmpty() && CreditLine.vstrText.size()) - { - // sort entries RHS dotted entries by alpha... - // - std::sort( CreditLine.vstrText.begin(), CreditLine.vstrText.end(), SortBySurname ); + if (!CreditLine.strText.IsEmpty() && CreditLine.vstrText.size()) { + // sort entries RHS dotted entries by alpha... + // + std::sort(CreditLine.vstrText.begin(), CreditLine.vstrText.end(), SortBySurname); - CreditData.CreditLines.push_back( CreditLine ); - iLineNumber += CreditLine.vstrText.size(); - } + CreditData.CreditLines.push_back(CreditLine); + iLineNumber += CreditLine.vstrText.size(); } - break; + } break; - case eTitle: - { - iLineNumber++; // leading blank line + case eTitle: { + iLineNumber++; // leading blank line - CreditLine_t CreditLine; - CreditLine.iLine = iLineNumber++; - CreditLine.strText = Capitalize(sLine); + CreditLine_t CreditLine; + CreditLine.iLine = iLineNumber++; + CreditLine.strText = Capitalize(sLine); - CreditData.CreditLines.push_back( CreditLine ); + CreditData.CreditLines.push_back(CreditLine); - iLineNumber++; // trailing blank line - break; - } - case eCard: - { - CreditCard_t CreditCard; - - std::string strResult(sLine); - const char *p; - while ((p=GetSubString(strResult)) != NULL) - { - if (CreditCard.strTitle.IsEmpty()) - { - CreditCard.strTitle = Capitalize( p ); - } - else - { - CreditCard.vstrText.push_back( UpperCaseFirstLettersOnly( p ) ); - } + iLineNumber++; // trailing blank line + break; + } + case eCard: { + CreditCard_t CreditCard; + + std::string strResult(sLine); + const char *p; + while ((p = GetSubString(strResult)) != NULL) { + if (CreditCard.strTitle.IsEmpty()) { + CreditCard.strTitle = Capitalize(p); + } else { + CreditCard.vstrText.push_back(UpperCaseFirstLettersOnly(p)); } + } - if (!CreditCard.strTitle.IsEmpty()) - { - // sort entries by alpha... - // - std::sort( CreditCard.vstrText.begin(), CreditCard.vstrText.end(), SortBySurname ); + if (!CreditCard.strTitle.IsEmpty()) { + // sort entries by alpha... + // + std::sort(CreditCard.vstrText.begin(), CreditCard.vstrText.end(), SortBySurname); - CreditData.CreditCards.push_back(CreditCard); - } + CreditData.CreditCards.push_back(CreditCard); } - break; - default: + } break; + default: break; } } @@ -476,31 +385,24 @@ void CG_Credits_Init( const char *psStripReference, vec4_t *pv4Color ) CreditData.iStartTime = cg.time; } -qboolean CG_Credits_Running( void ) -{ - return CreditData.Running(); -} +qboolean CG_Credits_Running(void) { return CreditData.Running(); } // returns qtrue if still drawing... // -qboolean CG_Credits_Draw( void ) -{ - if ( CG_Credits_Running() ) - { - const int iFontHeight = (int) (1.5f * (float) cgi_R_Font_HeightPixels(ghFontHandle, gfFontScale)); // taiwanese & japanese need 1.5 fontheight spacing +qboolean CG_Credits_Draw(void) { + if (CG_Credits_Running()) { + const int iFontHeight = (int)(1.5f * (float)cgi_R_Font_HeightPixels(ghFontHandle, gfFontScale)); // taiwanese & japanese need 1.5 fontheight spacing -// cgi_R_SetColor( *gpv4Color ); + // cgi_R_SetColor( *gpv4Color ); // display cards first... // - if (CreditData.CreditCards.size()) - { + if (CreditData.CreditCards.size()) { // grab first card off the list (we know there's at least one here, so...) // CreditCard_t &CreditCard = (*CreditData.CreditCards.begin()); - if (CreditCard.iTime == -1) - { + if (CreditCard.iTime == -1) { // onceonly time init... // CreditCard.iTime = cg.time; @@ -509,65 +411,56 @@ qboolean CG_Credits_Draw( void ) // play with the alpha channel for fade up/down... // const float fMilliSecondsElapsed = cg.time - CreditCard.iTime; - const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; - if (fSecondsElapsed < fCARD_FADESECONDS) - { + const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; + if (fSecondsElapsed < fCARD_FADESECONDS) { // fading up... // gv4Color[3] = fSecondsElapsed / fCARD_FADESECONDS; -// OutputDebugString(va("fade up: %f\n",gv4Color[3])); - } - else - if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS) - { + // OutputDebugString(va("fade up: %f\n",gv4Color[3])); + } else if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS) { // fading down... // const float fFadeDownSeconds = fSecondsElapsed - (fCARD_FADESECONDS + fCARD_SUSTAINSECONDS); gv4Color[3] = 1.0f - (fFadeDownSeconds / fCARD_FADESECONDS); -// OutputDebugString(va("fade dw: %f\n",gv4Color[3])); - } - else - { + // OutputDebugString(va("fade dw: %f\n",gv4Color[3])); + } else { gv4Color[3] = 1.0f; -// OutputDebugString(va("normal: %f\n",gv4Color[3])); + // OutputDebugString(va("normal: %f\n",gv4Color[3])); } if (gv4Color[3] < 0.0f) - gv4Color[3] = 0.0f; // ... otherwise numbers that have dipped slightly -ve flash up fullbright after fade down + gv4Color[3] = 0.0f; // ... otherwise numbers that have dipped slightly -ve flash up fullbright after fade down // // how many lines is it? // - int iLines = CreditCard.vstrText.size() + 2; // +2 for title itself & one seperator line + int iLines = CreditCard.vstrText.size() + 2; // +2 for title itself & one seperator line // - int iYpos = (SCREEN_HEIGHT - (iLines * iFontHeight))/2; + int iYpos = (SCREEN_HEIGHT - (iLines * iFontHeight)) / 2; // // draw it, title first... // int iWidth = CreditCard.strTitle.GetPixelLength(); - int iXpos = (SCREEN_WIDTH - iWidth)/2; + int iXpos = (SCREEN_WIDTH - iWidth) / 2; cgi_R_Font_DrawString(iXpos, iYpos, CreditCard.strTitle.c_str(), gv4Color, ghFontHandle, -1, gfFontScale); // - iYpos += iFontHeight*2; // skip blank line then move to main pos + iYpos += iFontHeight * 2; // skip blank line then move to main pos // - for (size_t i=0; i fCARD_FADESECONDS + fCARD_SUSTAINSECONDS + fCARD_FADESECONDS) - { + if (fSecondsElapsed > fCARD_FADESECONDS + fCARD_SUSTAINSECONDS + fCARD_FADESECONDS) { // yep, so erase the first entry (which will trigger the next one to be initialised on re-entry)... // - CreditData.CreditCards.erase( CreditData.CreditCards.begin() ); + CreditData.CreditCards.erase(CreditData.CreditCards.begin()); - if (!CreditData.CreditCards.size()) - { + if (!CreditData.CreditCards.size()) { // all cards gone, so re-init timer for lines... // CreditData.iStartTime = cg.time; @@ -575,46 +468,38 @@ qboolean CG_Credits_Draw( void ) } // return qtrue; - } - else - { + } else { // doing scroll text... // - if (CreditData.CreditLines.size()) - { + if (CreditData.CreditLines.size()) { // process all lines... // const float fMilliSecondsElapsed = cg.time - CreditData.iStartTime; - const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; + const float fSecondsElapsed = fMilliSecondsElapsed / 1000.0f; bool bEraseOccured = false; - for (CreditLines_t::iterator it = CreditData.CreditLines.begin(); it != CreditData.CreditLines.end(); bEraseOccured ? it : ++it) - { + for (CreditLines_t::iterator it = CreditData.CreditLines.begin(); it != CreditData.CreditLines.end(); bEraseOccured ? it : ++it) { CreditLine_t &CreditLine = (*it); bEraseOccured = false; static const float fPixelsPerSecond = ((float)SCREEN_HEIGHT / fLINE_SECONDTOSCROLLUP); int iYpos = SCREEN_HEIGHT + (CreditLine.iLine * iFontHeight); - iYpos-= (int) (fPixelsPerSecond * fSecondsElapsed); + iYpos -= (int)(fPixelsPerSecond * fSecondsElapsed); - int iTextLinesThisItem = Q_max( (int)CreditLine.vstrText.size(), 1); - if (iYpos + (iTextLinesThisItem * iFontHeight) < 0) - { + int iTextLinesThisItem = Q_max((int)CreditLine.vstrText.size(), 1); + if (iYpos + (iTextLinesThisItem * iFontHeight) < 0) { // scrolled off top of screen, so erase it... // - it = CreditData.CreditLines.erase( it ); + it = CreditData.CreditLines.erase(it); bEraseOccured = true; - } - else - if (iYpos < SCREEN_HEIGHT) - { + } else if (iYpos < SCREEN_HEIGHT) { // onscreen, so print it... // - bool bIsDotted = !!CreditLine.vstrText.size(); // eg "STUNTS ...................... MR ED" + bool bIsDotted = !!CreditLine.vstrText.size(); // eg "STUNTS ...................... MR ED" int iWidth = CreditLine.strText.GetPixelLength(); - int iXpos = bIsDotted ? 4 : (SCREEN_WIDTH - iWidth)/2; + int iXpos = bIsDotted ? 4 : (SCREEN_WIDTH - iWidth) / 2; gv4Color[3] = 1.0f; @@ -622,11 +507,10 @@ qboolean CG_Credits_Draw( void ) // now print any dotted members... // - for (size_t i=0; i. #include "../game/objectives.h" void CG_DrawIconBackground(void); -void CG_DrawMissionInformation( void ); -void CG_DrawInventorySelect( void ); -void CG_DrawForceSelect( void ); +void CG_DrawMissionInformation(void); +void CG_DrawInventorySelect(void); +void CG_DrawForceSelect(void); qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y); qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y); extern float g_crosshairEntDist; @@ -46,39 +46,38 @@ extern int g_rocketLockEntNum; extern int g_rocketLockTime; extern int g_rocketSlackTime; -vec3_t vfwd; -vec3_t vright; -vec3_t vup; -vec3_t vfwd_n; -vec3_t vright_n; -vec3_t vup_n; -int infoStringCount; +vec3_t vfwd; +vec3_t vright; +vec3_t vup; +vec3_t vfwd_n; +vec3_t vright_n; +vec3_t vup_n; +int infoStringCount; //=============================================================== - /* ================ CG_Draw3DModel ================ */ -static void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, qhandle_t skin, vec3_t origin, vec3_t angles ) { - refdef_t refdef; - refEntity_t ent; +static void CG_Draw3DModel(float x, float y, float w, float h, qhandle_t model, qhandle_t skin, vec3_t origin, vec3_t angles) { + refdef_t refdef; + refEntity_t ent; - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); - memset( &ent, 0, sizeof( ent ) ); - AnglesToAxis( angles, ent.axis ); - VectorCopy( origin, ent.origin ); + memset(&ent, 0, sizeof(ent)); + AnglesToAxis(angles, ent.axis); + VectorCopy(origin, ent.origin); ent.hModel = model; ent.customSkin = skin; - ent.renderfx = RF_NOSHADOW; // no stencil shadows + ent.renderfx = RF_NOSHADOW; // no stencil shadows refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); + AxisClear(refdef.viewaxis); refdef.fov_x = 30; refdef.fov_y = 30; @@ -91,8 +90,8 @@ static void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, refdef.time = cg.time; cgi_R_ClearScene(); - cgi_R_AddRefEntityToScene( &ent ); - cgi_R_RenderScene( &refdef ); + cgi_R_AddRefEntityToScene(&ent); + cgi_R_RenderScene(&refdef); } /* @@ -102,26 +101,22 @@ CG_DrawHead Used for both the status bar and the scoreboard ================ */ -void CG_DrawHead( float x, float y, float w, float h, int speaker_i, vec3_t headAngles ) -{ - qhandle_t hm = 0; - qhandle_t hs = 0; - float len; - vec3_t origin; - vec3_t mins, maxs; - gentity_t *ent; - qboolean extensions = qfalse; - int talking = 0; - - //If the talking ent is actually on the level, use his info - if ( cg.gameTextEntNum != -1 && cg.gameTextEntNum < ENTITYNUM_WORLD ) - { +void CG_DrawHead(float x, float y, float w, float h, int speaker_i, vec3_t headAngles) { + qhandle_t hm = 0; + qhandle_t hs = 0; + float len; + vec3_t origin; + vec3_t mins, maxs; + gentity_t *ent; + qboolean extensions = qfalse; + int talking = 0; + + // If the talking ent is actually on the level, use his info + if (cg.gameTextEntNum != -1 && cg.gameTextEntNum < ENTITYNUM_WORLD) { ent = &g_entities[cg.gameTextEntNum]; - if ( ent && ent->client ) - { + if (ent && ent->client) { hm = ent->client->clientInfo.headModel; - if ( hm ) - { + if (hm) { hs = ent->client->clientInfo.headSkin; extensions = ent->client->clientInfo.extensions; talking = gi.VoiceVolume[ent->s.number]; @@ -129,35 +124,32 @@ void CG_DrawHead( float x, float y, float w, float h, int speaker_i, vec3_t head } } - if ( !hm ) - { + if (!hm) { return; } - if ( !talking ) - {//no sound playing, don't display the head any more + if (!talking) { // no sound playing, don't display the head any more cg.gameNextTextTime = cg.time; return; } - //add talking anim - if ( extensions && talking > 0 ) - { + // add talking anim + if (extensions && talking > 0) { hs = hs + talking; } // offset the origin y and z to center the head - cgi_R_ModelBounds( hm, mins, maxs ); + cgi_R_ModelBounds(hm, mins, maxs); - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); // calculate distance so the head nearly fills the box // assume heads are taller than wide - len = 0.7 * ( maxs[2] - mins[2] ); - origin[0] = len / 0.268; // len / tan( fov/2 ) + len = 0.7 * (maxs[2] - mins[2]); + origin[0] = len / 0.268; // len / tan( fov/2 ) - CG_Draw3DModel( x, y, w, h, hm, hs, origin, headAngles ); + CG_Draw3DModel(x, y, w, h, hm, hs, origin, headAngles); } /* @@ -166,69 +158,64 @@ CG_DrawTalk ================ */ -static void CG_DrawTalk(centity_t *cent) -{ - float size; - vec3_t angles; -// int totalLines,y,i; - vec4_t color; +static void CG_DrawTalk(centity_t *cent) { + float size; + vec3_t angles; + // int totalLines,y,i; + vec4_t color; - if ( cg.gameNextTextTime > cg.time) - { + if (cg.gameNextTextTime > cg.time) { color[0] = colorTable[CT_BLACK][0]; color[1] = colorTable[CT_BLACK][1]; color[2] = colorTable[CT_BLACK][2]; color[3] = 0.350F; - cgi_R_SetColor(color); // Background - CG_DrawPic( 5, 27, 50, 64, cgs.media.ammoslider ); + cgi_R_SetColor(color); // Background + CG_DrawPic(5, 27, 50, 64, cgs.media.ammoslider); cgi_R_SetColor(colorTable[CT_LTPURPLE1]); - CG_DrawPic( 5, 6, 128, 64, cgs.media.talkingtop ); -/* - totalLines = cg.scrollTextLines - cg.gameTextCurrentLine; + CG_DrawPic(5, 6, 128, 64, cgs.media.talkingtop); + /* + totalLines = cg.scrollTextLines - cg.gameTextCurrentLine; - y = 6; - CG_DrawPic( 55, y, 16, 16, cgs.media.bracketlu ); - CG_DrawPic( 616, y, 16, 16, cgs.media.bracketru ); + y = 6; + CG_DrawPic( 55, y, 16, 16, cgs.media.bracketlu ); + CG_DrawPic( 616, y, 16, 16, cgs.media.bracketru ); - for (i=1;i cg.time ) - { - if (!((cg.time / 600 ) & 1)) - { - if (!cg.messageLitActive) - { - cgi_S_StartSound( NULL, 0, CHAN_AUTO, cgs.media.messageLitSound ); + if (cg.missionInfoFlashTime > cg.time) { + if (!((cg.time / 600) & 1)) { + if (!cg.messageLitActive) { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.messageLitSound); cg.messageLitActive = qtrue; } cgi_R_SetColor(colorTable[CT_HUD_RED]); - CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOn); - } - else - { + CG_DrawPic(x + 33, y + 41, 16, 16, cgs.media.messageLitOn); + } else { cg.messageLitActive = qfalse; } } cgi_R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( x + 33,y + 41, 16,16, cgs.media.messageLitOff); - + CG_DrawPic(x + 33, y + 41, 16, 16, cgs.media.messageLitOff); } /* @@ -280,57 +259,44 @@ static void CG_DrawMessageLit(centity_t *cent,int x,int y) CG_DrawForcePower ================ */ -static void CG_DrawForcePower(centity_t *cent,int x,int y) -{ - int i; - vec4_t calcColor; - float value,extra=0,inc,percent; +static void CG_DrawForcePower(centity_t *cent, int x, int y) { + int i; + vec4_t calcColor; + float value, extra = 0, inc, percent; - if ( !cent->gent->client->ps.forcePowersKnown ) - { + if (!cent->gent->client->ps.forcePowersKnown) { return; } - inc = (float) cent->gent->client->ps.forcePowerMax / MAX_TICS; + inc = (float)cent->gent->client->ps.forcePowerMax / MAX_TICS; value = cent->gent->client->ps.forcePower; - if ( value > cent->gent->client->ps.forcePowerMax ) - {//supercharged with force + if (value > cent->gent->client->ps.forcePowerMax) { // supercharged with force extra = value - cent->gent->client->ps.forcePowerMax; value = cent->gent->client->ps.forcePowerMax; } - for (i=MAX_TICS-1;i>=0;i--) - { - if ( extra ) - {//supercharged + for (i = MAX_TICS - 1; i >= 0; i--) { + if (extra) { // supercharged memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - percent = 0.75f + (sin( cg.time * 0.005f )*((extra/cent->gent->client->ps.forcePowerMax)*0.25f)); + percent = 0.75f + (sin(cg.time * 0.005f) * ((extra / cent->gent->client->ps.forcePowerMax) * 0.25f)); calcColor[0] *= percent; calcColor[1] *= percent; calcColor[2] *= percent; - } - else if ( value <= 0 ) // partial tic + } else if (value <= 0) // partial tic { memcpy(calcColor, colorTable[CT_BLACK], sizeof(vec4_t)); - } - else if (value < inc) // partial tic + } else if (value < inc) // partial tic { memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t)); percent = value / inc; calcColor[0] *= percent; calcColor[1] *= percent; calcColor[2] *= percent; - } - else - { + } else { memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t)); } - cgi_R_SetColor( calcColor); - CG_DrawPic( x + forceTicPos[i].x, - y + forceTicPos[i].y, - forceTicPos[i].width, - forceTicPos[i].height, - forceTicPos[i].tic ); + cgi_R_SetColor(calcColor); + CG_DrawPic(x + forceTicPos[i].x, y + forceTicPos[i].y, forceTicPos[i].width, forceTicPos[i].height, forceTicPos[i].tic); value -= inc; } @@ -341,133 +307,105 @@ static void CG_DrawForcePower(centity_t *cent,int x,int y) CG_DrawAmmo ================ */ -static void CG_DrawAmmo(centity_t *cent,int x,int y) -{ - playerState_t *ps; - int numColor_i; - int i; - vec4_t calcColor; - float value,inc,percent; +static void CG_DrawAmmo(centity_t *cent, int x, int y) { + playerState_t *ps; + int numColor_i; + int i; + vec4_t calcColor; + float value, inc, percent; ps = &cg.snap->ps; - if (!cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon == WP_STUN_BATON ) - { + if (cent->currentState.weapon == WP_STUN_BATON) { return; } - if ( cent->currentState.weapon == WP_SABER && cent->gent ) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); + if (cent->currentState.weapon == WP_SABER && cent->gent) { + cgi_R_SetColor(colorTable[CT_WHITE]); - if ( !cg.saberAnimLevelPending && cent->gent->client ) - {//uninitialized after a loadgame, cheat across and get it + if (!cg.saberAnimLevelPending && cent->gent->client) { // uninitialized after a loadgame, cheat across and get it cg.saberAnimLevelPending = cent->gent->client->ps.saberAnimLevel; } // don't need to draw ammo, but we will draw the current saber style in this window - switch ( cg.saberAnimLevelPending ) - { - case 1://FORCE_LEVEL_1: - case 5://FORCE_LEVEL_5://Tavion - CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleFast ); + switch (cg.saberAnimLevelPending) { + case 1: // FORCE_LEVEL_1: + case 5: // FORCE_LEVEL_5://Tavion + CG_DrawPic(x, y, 80, 40, cgs.media.HUDSaberStyleFast); break; - case 2://FORCE_LEVEL_2: - CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleMed ); + case 2: // FORCE_LEVEL_2: + CG_DrawPic(x, y, 80, 40, cgs.media.HUDSaberStyleMed); break; - case 3://FORCE_LEVEL_3: - case 4://FORCE_LEVEL_4://Desann - CG_DrawPic( x, y, 80, 40, cgs.media.HUDSaberStyleStrong ); + case 3: // FORCE_LEVEL_3: + case 4: // FORCE_LEVEL_4://Desann + CG_DrawPic(x, y, 80, 40, cgs.media.HUDSaberStyleStrong); break; } return; - } - else - { + } else { value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; } - if (value < 0) // No ammo + if (value < 0) // No ammo { return; } - // // ammo // - if (cg.oldammo < value) - { + if (cg.oldammo < value) { cg.oldAmmoTime = cg.time + 200; } cg.oldammo = value; // Firing or reloading? - if (( cg.predicted_player_state.weaponstate == WEAPON_FIRING - && cg.predicted_player_state.weaponTime > 100 )) - { + if ((cg.predicted_player_state.weaponstate == WEAPON_FIRING && cg.predicted_player_state.weaponTime > 100)) { numColor_i = CT_LTGREY; - } - else - { - if ( value > 0 ) - { - if (cg.oldAmmoTime > cg.time) - { + } else { + if (value > 0) { + if (cg.oldAmmoTime > cg.time) { numColor_i = CT_YELLOW; - } - else - { + } else { numColor_i = CT_HUD_ORANGE; } - } - else - { + } else { numColor_i = CT_RED; } } - cgi_R_SetColor( colorTable[numColor_i] ); - CG_DrawNumField(x + 29, y + 26, 3, value, 6, 12, NUM_FONT_SMALL,qfalse); + cgi_R_SetColor(colorTable[numColor_i]); + CG_DrawNumField(x + 29, y + 26, 3, value, 6, 12, NUM_FONT_SMALL, qfalse); - inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_TICS; - value =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; + inc = (float)ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_TICS; + value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; - for (i=MAX_TICS-1;i>=0;i--) - { + for (i = MAX_TICS - 1; i >= 0; i--) { - if (value <= 0) // partial tic + if (value <= 0) // partial tic { memcpy(calcColor, colorTable[CT_BLACK], sizeof(vec4_t)); - } - else if (value < inc) // partial tic + } else if (value < inc) // partial tic { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); percent = value / inc; calcColor[0] *= percent; calcColor[1] *= percent; calcColor[2] *= percent; - } - else - { + } else { memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } - cgi_R_SetColor( calcColor); - CG_DrawPic( x + ammoTicPos[i].x, - y + ammoTicPos[i].y, - ammoTicPos[i].width, - ammoTicPos[i].height, - ammoTicPos[i].tic ); + cgi_R_SetColor(calcColor); + CG_DrawPic(x + ammoTicPos[i].x, y + ammoTicPos[i].y, ammoTicPos[i].width, ammoTicPos[i].height, ammoTicPos[i].tic); value -= inc; } - } /* @@ -475,11 +413,10 @@ static void CG_DrawAmmo(centity_t *cent,int x,int y) CG_DrawHUDLeftFrame1 ================ */ -static void CG_DrawHUDLeftFrame1(int x,int y) -{ +static void CG_DrawHUDLeftFrame1(int x, int y) { // Inner gray wire frame - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDInnerLeft ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDInnerLeft); } /* @@ -487,44 +424,39 @@ static void CG_DrawHUDLeftFrame1(int x,int y) CG_DrawHUDLeftFrame2 ================ */ -static void CG_DrawHUDLeftFrame2(int x,int y) -{ +static void CG_DrawHUDLeftFrame2(int x, int y) { // Inner gray wire frame - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDLeftFrame ); // Metal frame + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDLeftFrame); // Metal frame } /* ================ CG_DrawHealth ================ */ -static void CG_DrawHealth(int x,int y) -{ +static void CG_DrawHealth(int x, int y) { vec4_t calcColor; - float healthPercent; - playerState_t *ps; + float healthPercent; + playerState_t *ps; ps = &cg.snap->ps; memcpy(calcColor, colorTable[CT_HUD_RED], sizeof(vec4_t)); - healthPercent = (float) ps->stats[STAT_HEALTH]/ps->stats[STAT_MAX_HEALTH]; + healthPercent = (float)ps->stats[STAT_HEALTH] / ps->stats[STAT_MAX_HEALTH]; calcColor[0] *= healthPercent; calcColor[1] *= healthPercent; calcColor[2] *= healthPercent; - cgi_R_SetColor( calcColor); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDHealth ); + cgi_R_SetColor(calcColor); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDHealth); // Draw the ticks - if (cg.HUDHealthFlag) - { - cgi_R_SetColor( colorTable[CT_HUD_RED] ); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDHealthTic ); + if (cg.HUDHealthFlag) { + cgi_R_SetColor(colorTable[CT_HUD_RED]); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDHealthTic); } - cgi_R_SetColor( colorTable[CT_HUD_RED] ); - CG_DrawNumField (x + 16, y + 40, 3, ps->stats[STAT_HEALTH], 6, 12, - NUM_FONT_SMALL,qtrue); - + cgi_R_SetColor(colorTable[CT_HUD_RED]); + CG_DrawNumField(x + 16, y + 40, 3, ps->stats[STAT_HEALTH], 6, 12, NUM_FONT_SMALL, qtrue); } /* @@ -532,110 +464,97 @@ static void CG_DrawHealth(int x,int y) CG_DrawArmor ================ */ -static void CG_DrawArmor(int x,int y) -{ +static void CG_DrawArmor(int x, int y) { vec4_t calcColor; - float armorPercent,hold; - playerState_t *ps; + float armorPercent, hold; + playerState_t *ps; ps = &cg.snap->ps; // Outer Armor circular memcpy(calcColor, colorTable[CT_HUD_GREEN], sizeof(vec4_t)); - hold = ps->stats[STAT_ARMOR]-(ps->stats[STAT_MAX_HEALTH]/2); - armorPercent = (float) hold/(ps->stats[STAT_MAX_HEALTH]/2); - if (armorPercent <0) - { + hold = ps->stats[STAT_ARMOR] - (ps->stats[STAT_MAX_HEALTH] / 2); + armorPercent = (float)hold / (ps->stats[STAT_MAX_HEALTH] / 2); + if (armorPercent < 0) { armorPercent = 0; } calcColor[0] *= armorPercent; calcColor[1] *= armorPercent; calcColor[2] *= armorPercent; - cgi_R_SetColor( calcColor); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmor1 ); + cgi_R_SetColor(calcColor); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDArmor1); // Inner Armor circular - if (armorPercent>0) - { + if (armorPercent > 0) { armorPercent = 1; - } - else - { - armorPercent = (float) ps->stats[STAT_ARMOR]/(ps->stats[STAT_MAX_HEALTH]/2); + } else { + armorPercent = (float)ps->stats[STAT_ARMOR] / (ps->stats[STAT_MAX_HEALTH] / 2); } memcpy(calcColor, colorTable[CT_HUD_GREEN], sizeof(vec4_t)); calcColor[0] *= armorPercent; calcColor[1] *= armorPercent; calcColor[2] *= armorPercent; - cgi_R_SetColor( calcColor); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmor2 ); // Inner Armor circular -/* - if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC - { - // Make tic flash if inner armor is at 50% (25% of full armor) - if (armorPercent<.5) // Do whatever the flash timer says - { - if (cg.HUDTickFlashTime < cg.time) // Flip at the same time - { - cg.HUDTickFlashTime = cg.time + 100; - if (cg.HUDArmorFlag) - { - cg.HUDArmorFlag = qfalse; - } - else - { - cg.HUDArmorFlag = qtrue; - } - } - } - else - { - cg.HUDArmorFlag=qtrue; - } - } - else // No armor? Don't show it. - { - cg.HUDArmorFlag=qfalse; - } - - if (cg.HUDArmorFlag) - { - cgi_R_SetColor( colorTable[CT_HUD_GREEN] ); - CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmorTic ); - } -*/ - cgi_R_SetColor( colorTable[CT_HUD_GREEN] ); - CG_DrawNumField (x + 16 + 14, y + 40 + 14, 3, ps->stats[STAT_ARMOR], 6, 12, - NUM_FONT_SMALL,qfalse); - + cgi_R_SetColor(calcColor); + CG_DrawPic(x, y, 80, 80, cgs.media.HUDArmor2); // Inner Armor circular + /* + if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC + { + // Make tic flash if inner armor is at 50% (25% of full armor) + if (armorPercent<.5) // Do whatever the flash timer says + { + if (cg.HUDTickFlashTime < cg.time) // Flip at the same time + { + cg.HUDTickFlashTime = cg.time + 100; + if (cg.HUDArmorFlag) + { + cg.HUDArmorFlag = qfalse; + } + else + { + cg.HUDArmorFlag = qtrue; + } + } + } + else + { + cg.HUDArmorFlag=qtrue; + } + } + else // No armor? Don't show it. + { + cg.HUDArmorFlag=qfalse; + } + + if (cg.HUDArmorFlag) + { + cgi_R_SetColor( colorTable[CT_HUD_GREEN] ); + CG_DrawPic( x, y, 80, 80, cgs.media.HUDArmorTic ); + } + */ + cgi_R_SetColor(colorTable[CT_HUD_GREEN]); + CG_DrawNumField(x + 16 + 14, y + 40 + 14, 3, ps->stats[STAT_ARMOR], 6, 12, NUM_FONT_SMALL, qfalse); } //----------------------------------------------------- -static qboolean CG_DrawCustomHealthHud( centity_t *cent ) -{ - float health = 0; - vec4_t color; +static qboolean CG_DrawCustomHealthHud(centity_t *cent) { + float health = 0; + vec4_t color; - if (( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { + if ((cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { // DRAW emplaced HUD color[0] = color[1] = color[2] = 0.0f; color[3] = 0.3f; - cgi_R_SetColor( color ); - CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(14, 480 - 50, 94, 32, cgs.media.whiteShader); // NOTE: this looks ugly - if ( cent->gent && cent->gent->owner ) - { - if (( cent->gent->owner->flags & FL_GODMODE )) - { + if (cent->gent && cent->gent->owner) { + if ((cent->gent->owner->flags & FL_GODMODE)) { // chair is in godmode, so render the health of the player instead health = cent->gent->health / (float)cent->gent->max_health; - } - else - { + } else { // render the chair health health = cent->gent->owner->health / (float)cent->gent->owner->max_health; } @@ -644,66 +563,60 @@ static qboolean CG_DrawCustomHealthHud( centity_t *cent ) color[0] = 1.0f; color[3] = 0.5f; - cgi_R_SetColor( color ); - CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(18, 480 - 41, 87 * health, 19, cgs.media.whiteShader); - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); return qfalse; // drew this hud, so don't draw the player one - } - else if (( cent->currentState.eFlags & EF_IN_ATST )) - { + } else if ((cent->currentState.eFlags & EF_IN_ATST)) { // we are an ATST... color[0] = color[1] = color[2] = 0.0f; color[3] = 0.3f; - cgi_R_SetColor( color ); - CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(14, 480 - 50, 94, 32, cgs.media.whiteShader); // we just calc the display value from the sum of health and armor - if ( g_entities[cg.snap->ps.viewEntity].activator ) // ensure we can look back to the atst_drivable to get the max health + if (g_entities[cg.snap->ps.viewEntity].activator) // ensure we can look back to the atst_drivable to get the max health { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR] ) / - (float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health ); - } - else - { - health = ( g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / - (float)(g_entities[cg.snap->ps.viewEntity].max_health + 800 ); // hacked max armor since we don't have an activator...should never happen + health = (g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / + (float)(g_entities[cg.snap->ps.viewEntity].max_health + g_entities[cg.snap->ps.viewEntity].activator->max_health); + } else { + health = (g_entities[cg.snap->ps.viewEntity].health + g_entities[cg.snap->ps.viewEntity].client->ps.stats[STAT_ARMOR]) / + (float)(g_entities[cg.snap->ps.viewEntity].max_health + 800); // hacked max armor since we don't have an activator...should never happen } color[1] = 0.25f; // blue-green color[2] = 1.0f; color[3] = 0.5f; - cgi_R_SetColor( color ); - CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(18, 480 - 41, 87 * health, 19, cgs.media.whiteShader); - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(2, 480 - 64, 128, 64, cgs.media.emplacedHealthBarShader); return qfalse; // drew this hud, so don't draw the player one - } - else if ( cg.snap->ps.viewEntity && ( g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD )) - { + } else if (cg.snap->ps.viewEntity && (g_entities[cg.snap->ps.viewEntity].dflags & DAMAGE_CUSTOM_HUD)) { // if we've gotten this far, we are assuming that we are a misc_panel_turret color[0] = color[1] = color[2] = 0.0f; color[3] = 0.3f; - cgi_R_SetColor( color ); - CG_DrawPic( 14, 480 - 50, 94, 32, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(14, 480 - 50, 94, 32, cgs.media.whiteShader); health = g_entities[cg.snap->ps.viewEntity].health / (float)g_entities[cg.snap->ps.viewEntity].max_health; color[1] = 1.0f; color[3] = 0.5f; - cgi_R_SetColor( color ); - CG_DrawPic( 18, 480 - 41, 87 * health, 19, cgs.media.whiteShader ); + cgi_R_SetColor(color); + CG_DrawPic(18, 480 - 41, 87 * health, 19, cgs.media.whiteShader); - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 2, 480 - 64, 128, 64, cgs.media.ladyLuckHealthShader ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(2, 480 - 64, 128, 64, cgs.media.ladyLuckHealthShader); return qfalse; // drew this hud, so don't draw the player one } @@ -712,29 +625,24 @@ static qboolean CG_DrawCustomHealthHud( centity_t *cent ) } //-------------------------------------- -static void CG_DrawBatteryCharge( void ) -{ - if ( cg.batteryChargeTime > cg.time ) - { +static void CG_DrawBatteryCharge(void) { + if (cg.batteryChargeTime > cg.time) { vec4_t color; // FIXME: drawing it here will overwrite zoom masks...find a better place - if ( cg.batteryChargeTime < cg.time + 1000 ) - { + if (cg.batteryChargeTime < cg.time + 1000) { // fading out for the last second color[0] = color[1] = color[2] = 1.0f; color[3] = (cg.batteryChargeTime - cg.time) / 1000.0f; - } - else - { + } else { // draw full color[0] = color[1] = color[2] = color[3] = 1.0f; } - cgi_R_SetColor( color ); + cgi_R_SetColor(color); // batteries were just charged - CG_DrawPic( 605, 295, 24, 32, cgs.media.batteryChargeShader ); + CG_DrawPic(605, 295, 24, 32, cgs.media.batteryChargeShader); } } @@ -743,58 +651,50 @@ static void CG_DrawBatteryCharge( void ) CG_DrawHUD ================ */ -extern void *cgi_UI_GetMenuByName( const char *menu ); -extern void cgi_UI_Menu_Paint( void *menu, qboolean force ); -static void CG_DrawHUD( centity_t *cent ) -{ - int x,y,value; - - if (cgi_UI_GetMenuInfo("lefthud",&x,&y)) - { +extern void *cgi_UI_GetMenuByName(const char *menu); +extern void cgi_UI_Menu_Paint(void *menu, qboolean force); +static void CG_DrawHUD(centity_t *cent) { + int x, y, value; + + if (cgi_UI_GetMenuInfo("lefthud", &x, &y)) { // Draw all the HUD elements --eez - cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "lefthud" ), qtrue ); + cgi_UI_Menu_Paint(cgi_UI_GetMenuByName("lefthud"), qtrue); // Draw armor & health values - if ( cg_draw2D.integer == 2 ) - { - CG_DrawSmallStringColor(x+5, y - 60,va("Armor:%d",cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN] ); - CG_DrawSmallStringColor(x+5, y - 40,va("Health:%d",cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN] ); + if (cg_draw2D.integer == 2) { + CG_DrawSmallStringColor(x + 5, y - 60, va("Armor:%d", cg.snap->ps.stats[STAT_ARMOR]), colorTable[CT_HUD_GREEN]); + CG_DrawSmallStringColor(x + 5, y - 40, va("Health:%d", cg.snap->ps.stats[STAT_HEALTH]), colorTable[CT_HUD_GREEN]); } - CG_DrawHUDLeftFrame1(x,y); - CG_DrawArmor(x,y); - CG_DrawHealth(x,y); - CG_DrawHUDLeftFrame2(x,y); + CG_DrawHUDLeftFrame1(x, y); + CG_DrawArmor(x, y); + CG_DrawHealth(x, y); + CG_DrawHUDLeftFrame2(x, y); } - if (cgi_UI_GetMenuInfo("righthud",&x,&y)) - { + if (cgi_UI_GetMenuInfo("righthud", &x, &y)) { // Draw all the HUD elements --eez - cgi_UI_Menu_Paint( cgi_UI_GetMenuByName( "righthud" ), qtrue ); + cgi_UI_Menu_Paint(cgi_UI_GetMenuByName("righthud"), qtrue); // Draw armor & health values - if ( cg_draw2D.integer == 2 ) - { - if ( cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent ) - { + if (cg_draw2D.integer == 2) { + if (cent->currentState.weapon != WP_SABER && cent->currentState.weapon != WP_STUN_BATON && cent->gent) { // Bob, just didn't want the ammo text drawing when the saber or the stun baton is the current weapon...change it back if this is wrong. value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; -// value = cent->gent->client->ps.forcePower; - CG_DrawSmallStringColor(x, y - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] ); + // value = cent->gent->client->ps.forcePower; + CG_DrawSmallStringColor(x, y - 60, va("Ammo:%d", value), colorTable[CT_HUD_GREEN]); + } else { + // value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; } - else - { -// value = cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; - } -// CG_DrawSmallStringColor(x, y - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] ); - CG_DrawSmallStringColor(x, y - 40,va("Force:%d",cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN] ); + // CG_DrawSmallStringColor(x, y - 60,va("Ammo:%d",value), colorTable[CT_HUD_GREEN] ); + CG_DrawSmallStringColor(x, y - 40, va("Force:%d", cent->gent->client->ps.forcePower), colorTable[CT_HUD_GREEN]); } - CG_DrawHUDRightFrame1(x,y); - CG_DrawForcePower(cent,x,y); - CG_DrawAmmo(cent,x,y); - CG_DrawMessageLit(cent,x,y); - CG_DrawHUDRightFrame2(x,y); + CG_DrawHUDRightFrame1(x, y); + CG_DrawForcePower(cent, x, y); + CG_DrawAmmo(cent, x, y); + CG_DrawMessageLit(cent, x, y); + CG_DrawHUDRightFrame2(x, y); } } @@ -803,17 +703,16 @@ static void CG_DrawHUD( centity_t *cent ) CG_ClearDataPadCvars ================ */ -void CG_ClearDataPadCvars( void ) -{ - cg_updatedDataPadForcePower1.integer = 0; //don't wait for the cvar-refresh. - cg_updatedDataPadForcePower2.integer = 0; //don't wait for the cvar-refresh. - cg_updatedDataPadForcePower3.integer = 0; //don't wait for the cvar-refresh. - cgi_Cvar_Set( "cg_updatedDataPadForcePower1", "0" ); - cgi_Cvar_Set( "cg_updatedDataPadForcePower2", "0" ); - cgi_Cvar_Set( "cg_updatedDataPadForcePower3", "0" ); - - cg_updatedDataPadObjective.integer = 0; //don't wait for the cvar-refresh. - cgi_Cvar_Set( "cg_updatedDataPadObjective", "0" ); +void CG_ClearDataPadCvars(void) { + cg_updatedDataPadForcePower1.integer = 0; // don't wait for the cvar-refresh. + cg_updatedDataPadForcePower2.integer = 0; // don't wait for the cvar-refresh. + cg_updatedDataPadForcePower3.integer = 0; // don't wait for the cvar-refresh. + cgi_Cvar_Set("cg_updatedDataPadForcePower1", "0"); + cgi_Cvar_Set("cg_updatedDataPadForcePower2", "0"); + cgi_Cvar_Set("cg_updatedDataPadForcePower3", "0"); + + cg_updatedDataPadObjective.integer = 0; // don't wait for the cvar-refresh. + cgi_Cvar_Set("cg_updatedDataPadObjective", "0"); } /* @@ -821,96 +720,84 @@ void CG_ClearDataPadCvars( void ) CG_DrawDataPadHUD ================ */ -void CG_DrawDataPadHUD( centity_t *cent ) -{ - int x,y; +void CG_DrawDataPadHUD(centity_t *cent) { + int x, y; x = 34; y = 286; - CG_DrawHUDLeftFrame1(x,y); - CG_DrawArmor(x,y); - CG_DrawHealth(x,y); + CG_DrawHUDLeftFrame1(x, y); + CG_DrawArmor(x, y); + CG_DrawHealth(x, y); x = 526; - if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer))) - { + if ((missionInfo_Updated) && ((cg_updatedDataPadForcePower1.integer) || (cg_updatedDataPadObjective.integer))) { // Stop flashing light cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; // Set which force power to show. - // cg_updatedDataPadForcePower is set from Q3_Interface, because force powers would only be given + // cg_updatedDataPadForcePower is set from Q3_Interface, because force powers would only be given // from a script. - if (cg_updatedDataPadForcePower1.integer) - { + if (cg_updatedDataPadForcePower1.integer) { cg.DataPadforcepowerSelect = cg_updatedDataPadForcePower1.integer - 1; // Not pretty, I know - if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) - { //duh - cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS-1; - } - else if (cg.DataPadforcepowerSelect<0) - { - cg.DataPadforcepowerSelect=0; + if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) { // duh + cg.DataPadforcepowerSelect = MAX_DPSHOWPOWERS - 1; + } else if (cg.DataPadforcepowerSelect < 0) { + cg.DataPadforcepowerSelect = 0; } } -// CG_ClearDataPadCvars(); + // CG_ClearDataPadCvars(); } - CG_DrawHUDRightFrame1(x,y); - CG_DrawForcePower(cent,x,y); - CG_DrawAmmo(cent,x,y); - CG_DrawMessageLit(cent,x,y); - - cgi_R_SetColor( colorTable[CT_WHITE]); - CG_DrawPic( 0, 0, 640, 480, cgs.media.dataPadFrame ); + CG_DrawHUDRightFrame1(x, y); + CG_DrawForcePower(cent, x, y); + CG_DrawAmmo(cent, x, y); + CG_DrawMessageLit(cent, x, y); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(0, 0, 640, 480, cgs.media.dataPadFrame); } //------------------------ // CG_DrawZoomMask //------------------------ -static void CG_DrawBinocularNumbers( qboolean power ) -{ +static void CG_DrawBinocularNumbers(qboolean power) { vec4_t color1; - cgi_R_SetColor( colorTable[CT_BLACK]); - CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_BLACK]); + CG_DrawPic(212, 367, 200, 40, cgs.media.whiteShader); - if ( power ) - { + if (power) { // Numbers should be kind of greenish color1[0] = 0.2f; color1[1] = 0.4f; color1[2] = 0.2f; color1[3] = 0.3f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); // Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked // up with a bunch of magic numbers..... int val = ((int)((cg.refdefViewAngles[YAW] + 180) / 10)) * 10; float off = (cg.refdefViewAngles[YAW] + 180) - val; - for ( int i = -10; i < 30; i += 10 ) - { + for (int i = -10; i < 30; i += 10) { val -= 10; - if ( val < 0 ) - { + if (val < 0) { val += 360; } // we only want to draw the very far left one some of the time, if it's too far to the left it will poke outside the mask. - if (( off > 3.0f && i == -10 ) || i > -10 ) - { + if ((off > 3.0f && i == -10) || i > -10) { // draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like - CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue ); - CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader ); + CG_DrawNumField(155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue); + CG_DrawPic(245 + (i - 1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader); } } - CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay ); + CG_DrawPic(212, 367, 200, 28, cgs.media.binocularOverlay); } } @@ -920,283 +807,254 @@ CG_DrawZoomMask ================ */ -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp -static void CG_DrawZoomMask( void ) -{ - vec4_t color1; - centity_t *cent; - float level; - static qboolean flip = qtrue; - float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage - qboolean power = qfalse; +static void CG_DrawZoomMask(void) { + vec4_t color1; + centity_t *cent; + float level; + static qboolean flip = qtrue; + float charge = cg.snap->ps.batteryCharge / (float)MAX_BATTERIES; // convert charge to a percentage + qboolean power = qfalse; cent = &cg_entities[0]; - if ( charge > 0.0f ) - { + if (charge > 0.0f) { power = qtrue; } //------------- // Binoculars //-------------------------------- - if ( cg.zoomMode == 1 ) - { - CG_RegisterItemVisuals( ITM_BINOCULARS_PICKUP ); + if (cg.zoomMode == 1) { + CG_RegisterItemVisuals(ITM_BINOCULARS_PICKUP); // zoom level level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } // Using a magic number to convert the zoom level to scale amount level *= 162.0f; - if ( power ) - { + if (power) { // draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(34, 48, 570, 362, cgs.media.binocularStatic); } - - CG_DrawBinocularNumbers( power ); + + CG_DrawBinocularNumbers(power); // Black out the area behind the battery display - cgi_R_SetColor( colorTable[CT_DKGREY]); - CG_DrawPic( 50, 389, 161, 16, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_DKGREY]); + CG_DrawPic(50, 389, 161, 16, cgs.media.whiteShader); - if ( power ) - { - color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; + if (power) { + color1[0] = sin(cg.time * 0.01f) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle ); + CG_DrawPic(82, 94, 16, 16, cgs.media.binocularCircle); } - CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask ); + CG_DrawPic(0, 0, 640, 480, cgs.media.binocularMask); - if ( power ) - { + if (power) { // Flickery color color1[0] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[1] = 0.8f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[2] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.1f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); - - CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow ); - } - else - { + cgi_R_SetColor(color1); + + CG_DrawPic(4, 282 - level, 16, 16, cgs.media.binocularArrow); + } else { // No power color color1[0] = 0.15f; color1[1] = 0.15f; color1[2] = 0.15f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); } // The top triangle bit randomly flips when the power is on - if ( flip && power ) - { - CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri ); - } - else - { - CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri ); + if (flip && power) { + CG_DrawPic(330, 60, -26, -30, cgs.media.binocularTri); + } else { + CG_DrawPic(307, 40, 26, 30, cgs.media.binocularTri); } - if ( Q_flrand(0.0f, 1.0f) > 0.98f && ( cg.time & 1024 )) - { + if (Q_flrand(0.0f, 1.0f) > 0.98f && (cg.time & 1024)) { flip = (qboolean)!flip; } - if ( power ) - { - color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); + if (power) { + color1[0] = 1.0f * (charge < 0.2f ? !!(cg.time & 256) : 1); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.2f; - cgi_R_SetColor( color1 ); - CG_DrawPic( 60, 394.5f, charge * 141, 5, cgs.media.whiteShader ); + cgi_R_SetColor(color1); + CG_DrawPic(60, 394.5f, charge * 141, 5, cgs.media.whiteShader); } } //------------ - // Disruptor + // Disruptor //-------------------------------- - else if ( cg.zoomMode == 2 ) - { + else if (cg.zoomMode == 2) { level = (float)(80.0f - cg_zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } - // Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork. + // Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork. level *= 103.0f; // Draw target mask - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(0, 0, 640, 480, cgs.media.disruptorMask); // apparently 99.0f is the full zoom level - if ( level >= 99 ) - { + if (level >= 99) { // Fully zoomed, so make the rotating insert pulse - color1[0] = 1.0f; + color1[0] = 1.0f; color1[1] = 1.0f; color1[2] = 1.0f; - color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f; + color1[3] = 0.7f + sin(cg.time * 0.01f) * 0.3f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); } // Draw rotating insert - CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert ); + CG_DrawRotatePic2(320, 240, 640, 480, -level, cgs.media.disruptorInsert); float cx, cy; float max; max = cg_entities[0].gent->client->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max; - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } - color1[0] = (1.0f - max) * 2.0f; + color1[0] = (1.0f - max) * 2.0f; color1[1] = max * 1.5f; color1[2] = 0.0f; color1[3] = 1.0f; // If we are low on ammo, make us flash - if ( max < 0.15f && ( cg.time & 512 )) - { - VectorClear( color1 ); + if (max < 0.15f && (cg.time & 512)) { + VectorClear(color1); } - if ( color1[0] > 1.0f ) - { + if (color1[0] > 1.0f) { color1[0] = 1.0f; } - if ( color1[1] > 1.0f ) - { + if (color1[1] > 1.0f) { color1[1] = 1.0f; } - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); max *= 58.0f; - for ( float i = 18.5f; i <= 18.5f + max; i+= 3 ) // going from 15 to 45 degrees, with 5 degree increments + for (float i = 18.5f; i <= 18.5f + max; i += 3) // going from 15 to 45 degrees, with 5 degree increments { - cx = 320 + sin( (i+90.0f)/57.296f ) * 190; - cy = 240 + cos( (i+90.0f)/57.296f ) * 190; + cx = 320 + sin((i + 90.0f) / 57.296f) * 190; + cy = 240 + cos((i + 90.0f) / 57.296f) * 190; - CG_DrawRotatePic2( cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick ); + CG_DrawRotatePic2(cx, cy, 12, 24, 90 - i, cgs.media.disruptorInsertTick); } // FIXME: doesn't know about ammo!! which is bad because it draws charge beyond what ammo you may have.. - if ( cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT ) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); + if (cg_entities[0].gent->client->ps.weaponstate == WEAPON_CHARGING_ALT) { + cgi_R_SetColor(colorTable[CT_WHITE]); // draw the charge level - max = ( cg.time - cg_entities[0].gent->client->ps.weaponChargeTime ) / ( 150.0f * 10.0f ); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed. + max = (cg.time - cg_entities[0].gent->client->ps.weaponChargeTime) / + (150.0f * 10.0f); // bad hardcodedness 150 is disruptor charge unit and 10 is max charge units allowed. - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } - CG_DrawPic2( 257, 435, 134 * max, 34, 0,0,max,1,cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" )); + CG_DrawPic2(257, 435, 134 * max, 34, 0, 0, max, 1, cgi_R_RegisterShaderNoMip("gfx/2d/crop_charge")); } } //----------- // Light Amp //-------------------------------- - else if ( cg.zoomMode == 3 ) - { - CG_RegisterItemVisuals( ITM_LA_GOGGLES_PICKUP ); + else if (cg.zoomMode == 3) { + CG_RegisterItemVisuals(ITM_LA_GOGGLES_PICKUP); - if ( power ) - { - cgi_R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 34, 29, 580, 410, cgs.media.laGogglesStatic ); + if (power) { + cgi_R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(34, 29, 580, 410, cgs.media.laGogglesStatic); - CG_DrawPic( 570, 140, 12, 160, cgs.media.laGogglesSideBit ); - - float light = (128-cent->gent->lightLevel) * 0.5f; + CG_DrawPic(570, 140, 12, 160, cgs.media.laGogglesSideBit); - if ( light < -81 ) // saber can really jack up local light levels....?magic number?? + float light = (128 - cent->gent->lightLevel) * 0.5f; + + if (light < -81) // saber can really jack up local light levels....?magic number?? { light = -81; } float pos1 = 220 + light; - float pos2 = 220 + cos( cg.time * 0.0004f + light * 0.05f ) * 40 + sin( cg.time * 0.0013f + 1 ) * 20 + sin( cg.time * 0.0021f ) * 5; + float pos2 = 220 + cos(cg.time * 0.0004f + light * 0.05f) * 40 + sin(cg.time * 0.0013f + 1) * 20 + sin(cg.time * 0.0021f) * 5; // Flickery color color1[0] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[1] = 0.8f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[2] = 0.7f + Q_flrand(-1.0f, 1.0f) * 0.2f; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 565, pos1, 22, 8, cgs.media.laGogglesBracket ); - CG_DrawPic( 558, pos2, 14, 5, cgs.media.laGogglesArrow ); + CG_DrawPic(565, pos1, 22, 8, cgs.media.laGogglesBracket); + CG_DrawPic(558, pos2, 14, 5, cgs.media.laGogglesArrow); } // Black out the area behind the battery display - cgi_R_SetColor( colorTable[CT_DKGREY]); - CG_DrawPic( 236, 357, 164, 16, cgs.media.whiteShader ); + cgi_R_SetColor(colorTable[CT_DKGREY]); + CG_DrawPic(236, 357, 164, 16, cgs.media.whiteShader); - if ( power ) - { + if (power) { // Power bar - color1[0] = 1.0f * ( charge < 0.2f ? !!(cg.time & 256) : 1 ); + color1[0] = 1.0f * (charge < 0.2f ? !!(cg.time & 256) : 1); color1[1] = charge * color1[0]; color1[2] = 0.0f; color1[3] = 0.4f; - cgi_R_SetColor( color1 ); - CG_DrawPic( 247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader ); + cgi_R_SetColor(color1); + CG_DrawPic(247.0f, 362.5f, charge * 143.0f, 6, cgs.media.whiteShader); // pulsing dot bit - color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; + color1[0] = sin(cg.time * 0.01f) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; - cgi_R_SetColor( color1 ); + cgi_R_SetColor(color1); - CG_DrawPic( 65, 94, 16, 16, cgs.media.binocularCircle ); + CG_DrawPic(65, 94, 16, 16, cgs.media.binocularCircle); } - - CG_DrawPic( 0, 0, 640, 480, cgs.media.laGogglesMask ); + + CG_DrawPic(0, 0, 640, 480, cgs.media.laGogglesMask); } } @@ -1206,20 +1064,18 @@ CG_DrawStats ================ */ -static void CG_DrawStats( void ) -{ - centity_t *cent; +static void CG_DrawStats(void) { + centity_t *cent; - if ( cg_drawStatus.integer == 0 ) { + if (cg_drawStatus.integer == 0) { return; } cent = &cg_entities[cg.snap->ps.clientNum]; - if ((cg.snap->ps.viewEntity>0&&cg.snap->ps.viewEntityps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { // MIGHT try and draw a custom hud if it wants... - CG_DrawCustomHealthHud( cent ); + CG_DrawCustomHealthHud(cent); return; } @@ -1227,74 +1083,63 @@ static void CG_DrawStats( void ) qboolean drawHud = qtrue; - if ( cent && cent->gent ) - { - drawHud = CG_DrawCustomHealthHud( cent ); + if (cent && cent->gent) { + drawHud = CG_DrawCustomHealthHud(cent); } - if (( drawHud ) && ( cg_drawHUD.integer )) - { - CG_DrawHUD( cent ); + if ((drawHud) && (cg_drawHUD.integer)) { + CG_DrawHUD(cent); } CG_DrawTalk(cent); } - /* =================== CG_DrawPickupItem =================== */ -static void CG_DrawPickupItem( void ) { - int value; - float *fadeColor; +static void CG_DrawPickupItem(void) { + int value; + float *fadeColor; value = cg.itemPickup; - if ( value && cg_items[ value ].icon != -1 ) - { - fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 ); - if ( fadeColor ) - { - CG_RegisterItemVisuals( value ); - cgi_R_SetColor( fadeColor ); - CG_DrawPic( 573, 340, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon ); - //CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] ); - //CG_DrawProportionalString( ICON_SIZE + 16, 398, + if (value && cg_items[value].icon != -1) { + fadeColor = CG_FadeColor(cg.itemPickupTime, 3000); + if (fadeColor) { + CG_RegisterItemVisuals(value); + cgi_R_SetColor(fadeColor); + CG_DrawPic(573, 340, ICON_SIZE, ICON_SIZE, cg_items[value].icon); + // CG_DrawBigString( ICON_SIZE + 16, 398, bg_itemlist[ value ].classname, fadeColor[0] ); + // CG_DrawProportionalString( ICON_SIZE + 16, 398, // bg_itemlist[ value ].classname, CG_SMALLFONT,fadeColor ); - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } } } -void CMD_CGCam_Disable( void ); +void CMD_CGCam_Disable(void); /* =================== CG_DrawPickupItem =================== */ -void CG_DrawCredits(void) -{ - if (!cg.creditsStart) - { +void CG_DrawCredits(void) { + if (!cg.creditsStart) { // cg.creditsStart = qtrue; - cgi_SP_Register("CREDITS", qfalse); // do not keep around after level + cgi_SP_Register("CREDITS", qfalse); // do not keep around after level CG_Credits_Init("CREDITS_RAVEN", &colorTable[CT_ICON_BLUE]); - if ( cg_skippingcin.integer ) - {//Were skipping a cinematic and it's over now + if (cg_skippingcin.integer) { // Were skipping a cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } } - - if (cg.creditsStart) - { - if ( !CG_Credits_Running() ) - { - cgi_Cvar_Set( "cg_endcredits", "0" ); + if (cg.creditsStart) { + if (!CG_Credits_Running()) { + cgi_Cvar_Set("cg_endcredits", "0"); CMD_CGCam_Disable(); cgi_SendConsoleCommand("set nextmap disconnect ; cinematic outcast\n"); } @@ -1309,177 +1154,138 @@ CROSSHAIR ================================================================================ */ - /* ================= CG_DrawCrosshair ================= */ -static void CG_DrawCrosshair( vec3_t worldPoint ) -{ - float w, h; - qhandle_t hShader; - qboolean corona = qfalse; - vec4_t ecolor; - float f; - float x, y; - - if ( !cg_drawCrosshair.integer ) - { +static void CG_DrawCrosshair(vec3_t worldPoint) { + float w, h; + qhandle_t hShader; + qboolean corona = qfalse; + vec4_t ecolor; + float f; + float x, y; + + if (!cg_drawCrosshair.integer) { return; } - if ( cg.zoomMode > 0 && cg.zoomMode < 3 ) - { - //not while scoped + if (cg.zoomMode > 0 && cg.zoomMode < 3) { + // not while scoped return; } - //set color based on what kind of ent is under crosshair - if ( g_crosshairEntNum >= ENTITYNUM_WORLD ) - { + // set color based on what kind of ent is under crosshair + if (g_crosshairEntNum >= ENTITYNUM_WORLD) { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; - } - else if ( cg_forceCrosshair && cg_crosshairForceHint.integer ) - { + } else if (cg_forceCrosshair && cg_crosshairForceHint.integer) { ecolor[0] = 0.2f; ecolor[1] = 0.5f; ecolor[2] = 1.0f; corona = qtrue; - } - else if ( cg_crosshairIdentifyTarget.integer ) - { + } else if (cg_crosshairIdentifyTarget.integer) { gentity_t *crossEnt = &g_entities[g_crosshairEntNum]; - if ( crossEnt->client ) - { - if ( crossEnt->client->ps.powerups[PW_CLOAKED] ) - {//cloaked don't show up - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B - } - else if ( crossEnt->client->playerTeam == TEAM_PLAYER ) - { - //Allies are green - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else if ( crossEnt->client->playerTeam == TEAM_NEUTRAL ) - { + if (crossEnt->client) { + if (crossEnt->client->ps.powerups[PW_CLOAKED]) { // cloaked don't show up + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B + } else if (crossEnt->client->playerTeam == TEAM_PLAYER) { + // Allies are green + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else if (crossEnt->client->playerTeam == TEAM_NEUTRAL) { // NOTE: was yellow, but making it white unless they really decide they want to see colors - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B - } - else - { - //Enemies are red - ecolor[0] = 1.0f;//R - ecolor[1] = 0.1f;//G - ecolor[2] = 0.1f;//B + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B + } else { + // Enemies are red + ecolor[0] = 1.0f; // R + ecolor[1] = 0.1f; // G + ecolor[2] = 0.1f; // B } - } - else if ( crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags&SVF_NONNPC_ENEMY) ) - { + } else if (crossEnt->s.weapon == WP_TURRET && (crossEnt->svFlags & SVF_NONNPC_ENEMY)) { // a turret - if ( crossEnt->noDamageTeam == TEAM_PLAYER ) - { + if (crossEnt->noDamageTeam == TEAM_PLAYER) { // mine are green - ecolor[0] = 0.0;//R - ecolor[1] = 1.0;//G - ecolor[2] = 0.0;//B - } - else - { + ecolor[0] = 0.0; // R + ecolor[1] = 1.0; // G + ecolor[2] = 0.0; // B + } else { // hostile ones are red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B } - } - else if ( crossEnt->s.weapon == WP_TRIP_MINE ) - { + } else if (crossEnt->s.weapon == WP_TRIP_MINE) { // tripmines are red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B - } - else - { - VectorCopy( crossEnt->startRGBA, ecolor ); + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B + } else { + VectorCopy(crossEnt->startRGBA, ecolor); - if ( !ecolor[0] && !ecolor[1] && !ecolor[2] ) - { + if (!ecolor[0] && !ecolor[1] && !ecolor[2]) { // We don't want a black crosshair, so use white since it will show up better - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 1.0f;//B + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B } } - } - else // cg_crosshairIdentifyTarget is not on, so make it white + } else // cg_crosshairIdentifyTarget is not on, so make it white { ecolor[0] = ecolor[1] = ecolor[2] = 1.0f; } ecolor[3] = 1.0; - cgi_R_SetColor( ecolor ); + cgi_R_SetColor(ecolor); - if ( cg.forceCrosshairStartTime ) - { + if (cg.forceCrosshairStartTime) { // both of these calcs will fade the corona in one direction - if ( cg.forceCrosshairEndTime ) - { + if (cg.forceCrosshairEndTime) { ecolor[3] = (cg.time - cg.forceCrosshairEndTime) / 500.0f; - } - else - { + } else { ecolor[3] = (cg.time - cg.forceCrosshairStartTime) / 300.0f; } - // clamp - if ( ecolor[3] < 0 ) - { + // clamp + if (ecolor[3] < 0) { ecolor[3] = 0; - } - else if ( ecolor[3] > 1.0f ) - { + } else if (ecolor[3] > 1.0f) { ecolor[3] = 1.0f; } - if ( !cg.forceCrosshairEndTime ) - { + if (!cg.forceCrosshairEndTime) { // but for the other direction, we'll need to reverse it ecolor[3] = 1.0f - ecolor[3]; } } - if ( corona ) // we are pointing at a crosshair item + if (corona) // we are pointing at a crosshair item { - if ( !cg.forceCrosshairStartTime ) - { + if (!cg.forceCrosshairStartTime) { // must have just happened because we are not fading in yet...start it now cg.forceCrosshairStartTime = cg.time; cg.forceCrosshairEndTime = 0; } - if ( cg.forceCrosshairEndTime ) - { + if (cg.forceCrosshairEndTime) { // must have just gone over a force thing again...and we were in the process of fading out. Set fade in level to the level where the fade left off - cg.forceCrosshairStartTime = cg.time - ( 1.0f - ecolor[3] ) * 300.0f; + cg.forceCrosshairStartTime = cg.time - (1.0f - ecolor[3]) * 300.0f; cg.forceCrosshairEndTime = 0; } - } - else // not pointing at a crosshair item + } else // not pointing at a crosshair item { - if ( cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime ) // were currently fading in + if (cg.forceCrosshairStartTime && !cg.forceCrosshairEndTime) // were currently fading in { // must fade back out, but we will have to set the fadeout time to be equal to the current level of faded-in-edness cg.forceCrosshairEndTime = cg.time - ecolor[3] * 500.0f; } - if ( cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f ) // not pointing at anything and fade out is totally done + if (cg.forceCrosshairEndTime && cg.time - cg.forceCrosshairEndTime > 500.0f) // not pointing at anything and fade out is totally done { // reset everything cg.forceCrosshairStartTime = 0; @@ -1491,65 +1297,49 @@ static void CG_DrawCrosshair( vec3_t worldPoint ) // pulse the size of the crosshair when picking up items f = cg.time - cg.itemPickupBlendTime; - if ( f > 0 && f < ITEM_BLOB_TIME ) { + if (f > 0 && f < ITEM_BLOB_TIME) { f /= ITEM_BLOB_TIME; - w *= ( 1 + f ); - h *= ( 1 + f ); + w *= (1 + f); + h *= (1 + f); } - if ( worldPoint && VectorLength( worldPoint ) ) - { - if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) ) - {//off screen, don't draw it - cgi_R_SetColor( NULL ); + if (worldPoint && VectorLength(worldPoint)) { + if (!CG_WorldCoordToScreenCoordFloat(worldPoint, &x, &y)) { // off screen, don't draw it + cgi_R_SetColor(NULL); return; } - x -= 320;//???? - y -= 240;//???? - } - else - { + x -= 320; //???? + y -= 240; //???? + } else { x = cg_crosshairX.integer; y = cg_crosshairY.integer; } - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) - { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (!Q_stricmp("misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname)) { // draws a custom crosshair that is twice as large as normal - cgi_R_DrawStretchPic( x + cg.refdef.x + 320 - w, - y + cg.refdef.y + 240 - h, - w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader ); - + cgi_R_DrawStretchPic(x + cg.refdef.x + 320 - w, y + cg.refdef.y + 240 - h, w * 2, h * 2, 0, 0, 1, 1, cgs.media.turretCrossHairShader); } - } - else - { - hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ]; + } else { + hShader = cgs.media.crosshairShader[cg_drawCrosshair.integer % NUM_CROSSHAIRS]; - cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w), - y + cg.refdef.y + 0.5 * (480 - h), - w, h, 0, 0, 1, 1, hShader ); + cgi_R_DrawStretchPic(x + cg.refdef.x + 0.5 * (640 - w), y + cg.refdef.y + 0.5 * (480 - h), w, h, 0, 0, 1, 1, hShader); } - if ( cg.forceCrosshairStartTime && cg_crosshairForceHint.integer ) // drawing extra bits + if (cg.forceCrosshairStartTime && cg_crosshairForceHint.integer) // drawing extra bits { - ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color + ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * (sin(cg.time * 0.001f) * 0.08f + 0.35f); // don't draw full color ecolor[3] = 1.0f; - cgi_R_SetColor( ecolor ); + cgi_R_SetColor(ecolor); w *= 2.0f; h *= 2.0f; - cgi_R_DrawStretchPic( x + cg.refdef.x + 0.5f * ( 640 - w ), y + cg.refdef.y + 0.5f * ( 480 - h ), - w, h, - 0, 0, 1, 1, - cgs.media.forceCoronaShader ); + cgi_R_DrawStretchPic(x + cg.refdef.x + 0.5f * (640 - w), y + cg.refdef.y + 0.5f * (480 - h), w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader); } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -1557,36 +1347,35 @@ qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) Take any world coord and convert it to a 2D virtual 640x480 screen coord */ -qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) -{ - vec3_t trans; - float xc, yc; - float px, py; - float z; +qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { + vec3_t trans; + float xc, yc; + float px, py; + float z; - px = tan(cg.refdef.fov_x * (M_PI / 360) ); - py = tan(cg.refdef.fov_y * (M_PI / 360) ); + px = tan(cg.refdef.fov_x * (M_PI / 360)); + py = tan(cg.refdef.fov_y * (M_PI / 360)); - VectorSubtract(worldCoord, cg.refdef.vieworg, trans); + VectorSubtract(worldCoord, cg.refdef.vieworg, trans); - xc = 640 / 2.0; - yc = 480 / 2.0; + xc = 640 / 2.0; + yc = 480 / 2.0; // z = how far is the object in our forward direction - z = DotProduct(trans, cg.refdef.viewaxis[0]); - if (z <= 0.001) - return qfalse; + z = DotProduct(trans, cg.refdef.viewaxis[0]); + if (z <= 0.001) + return qfalse; - *x = xc - DotProduct(trans, cg.refdef.viewaxis[1])*xc/(z*px); - *y = yc - DotProduct(trans, cg.refdef.viewaxis[2])*yc/(z*py); + *x = xc - DotProduct(trans, cg.refdef.viewaxis[1]) * xc / (z * px); + *y = yc - DotProduct(trans, cg.refdef.viewaxis[2]) * yc / (z * py); - return qtrue; + return qtrue; } -qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { +qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) { float xF, yF; - if ( CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ) ) { + if (CG_WorldCoordToScreenCoordFloat(worldCoord, &xF, &yF)) { *x = (int)xF; *y = (int)yF; return qtrue; @@ -1597,74 +1386,62 @@ qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { // I'm keeping the rocket tracking code separate for now since I may want to do different logic...but it still uses trace info from scanCrosshairEnt //----------------------------------------- -static void CG_ScanForRocketLock( void ) +static void CG_ScanForRocketLock(void) //----------------------------------------- { - gentity_t *traceEnt; + gentity_t *traceEnt; static qboolean tempLock = qfalse; // this will break if anything else uses this locking code ( other than the player ) traceEnt = &g_entities[g_crosshairEntNum]; - if ( !traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET ) || !traceEnt->health - || ( traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED] )) - { + if (!traceEnt || g_crosshairEntNum <= 0 || g_crosshairEntNum >= ENTITYNUM_WORLD || (!traceEnt->client && traceEnt->s.weapon != WP_TURRET) || + !traceEnt->health || (traceEnt && traceEnt->client && traceEnt->client->ps.powerups[PW_CLOAKED])) { // see how much locking we have - int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); + int dif = (cg.time - g_rocketLockTime) / (1200.0f / 8.0f); - // 8 is full locking....also if we just traced onto the world, + // 8 is full locking....also if we just traced onto the world, // give them 1/2 second of slop before dropping the lock - if ( dif < 8 && g_rocketSlackTime + 500 < cg.time ) - { + if (dif < 8 && g_rocketSlackTime + 500 < cg.time) { // didn't have a full lock and not in grace period, so drop the lock g_rocketLockTime = 0; g_rocketSlackTime = 0; tempLock = qfalse; } - if ( g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD ) - { + if (g_rocketSlackTime + 500 >= cg.time && g_rocketLockEntNum < ENTITYNUM_WORLD) { // were locked onto an ent, aren't right now.....but still within the slop grace period // keep the current lock amount g_rocketLockTime += cg.frametime; } - if ( !tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8 ) - { + if (!tempLock && g_rocketLockEntNum < ENTITYNUM_WORLD && dif >= 8) { tempLock = qtrue; - if ( g_rocketLockTime + 1200 < cg.time ) - { + if (g_rocketLockTime + 1200 < cg.time) { g_rocketLockTime = cg.time - 1200; // doh, hacking the time so the targetting still gets drawn full } - } + } // keep locking to this thing for one second after it gets out of view - if ( g_rocketLockTime + 2000.0f < cg.time ) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms + if (g_rocketLockTime + 2000.0f < cg.time) // since time was hacked above, I'm compensating so that 2000ms is really only 1000ms { // too bad, you had your chance g_rocketLockEntNum = ENTITYNUM_NONE; g_rocketSlackTime = 0; g_rocketLockTime = 0; } - } - else - { + } else { tempLock = qfalse; - if ( g_rocketLockEntNum >= ENTITYNUM_WORLD ) - { - if ( g_rocketSlackTime + 500 < cg.time ) - { + if (g_rocketLockEntNum >= ENTITYNUM_WORLD) { + if (g_rocketSlackTime + 500 < cg.time) { // we just locked onto something, start the lock at the current time g_rocketLockEntNum = g_crosshairEntNum; g_rocketLockTime = cg.time; g_rocketSlackTime = cg.time; } - } - else - { - if ( g_rocketLockEntNum != g_crosshairEntNum ) - { + } else { + if (g_rocketLockEntNum != g_crosshairEntNum) { g_rocketLockTime = cg.time; } @@ -1681,97 +1458,78 @@ CG_ScanForCrosshairEntity ================= */ extern float forcePushPullRadius[]; -static void CG_ScanForCrosshairEntity( qboolean scanAll ) -{ - trace_t trace; - gentity_t *traceEnt = NULL; - vec3_t start, end; - int content; - int ignoreEnt = cg.snap->ps.clientNum; +static void CG_ScanForCrosshairEntity(qboolean scanAll) { + trace_t trace; + gentity_t *traceEnt = NULL; + vec3_t start, end; + int content; + int ignoreEnt = cg.snap->ps.clientNum; - //FIXME: debounce this to about 10fps? + // FIXME: debounce this to about 10fps? cg_forceCrosshair = qfalse; - if ( cg_entities[0].gent && cg_entities[0].gent->client ) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer && - {//try to check for force-affectable stuff first + if (cg_entities[0].gent && cg_entities[0].gent->client) // <-Mike said it should always do this //if (cg_crosshairForceHint.integer && + { // try to check for force-affectable stuff first vec3_t d_f, d_rt, d_up; - VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); - VectorMA( start, 2048, d_f, end );//4028 is max for mind trick + VectorCopy(g_entities[0].client->renderInfo.eyePoint, start); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); + VectorMA(start, 2048, d_f, end); // 4028 is max for mind trick - //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. - gi.trace( &trace, start, vec3_origin, vec3_origin, end, - ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... + // YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. + gi.trace(&trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE | CONTENTS_SHOTCLIP | CONTENTS_BODY | CONTENTS_ITEM, G2_NOCOLLIDE, + 10); // ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, + // could just remove their body earlier too... - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit something + if (trace.entityNum < ENTITYNUM_WORLD) { // hit something traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt ) - { + if (traceEnt) { // Check for mind trickable-guys - if ( traceEnt->client ) - {//is a client - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK]) ) - {//I have the ability to mind-trick and he is alive and he has a mind trick script - //NOTE: no need to check range since it's always 2048 + if (traceEnt->client) { // is a client + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_TELEPATHY] && traceEnt->health > 0 && + VALIDSTRING(traceEnt->behaviorSet[BSET_MINDTRICK])) { // I have the ability to mind-trick and he is alive and he has a mind trick script + // NOTE: no need to check range since it's always 2048 cg_forceCrosshair = qtrue; } } // No? Check for force-push/pullable doors and func_statics - else if ( traceEnt->s.eType == ET_MOVER ) - {//hit a mover - if ( !Q_stricmp( "func_door", traceEnt->classname ) ) - {//it's a func_door - if ( traceEnt->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/ ) - {//it's force-usable - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//player has push or pull + else if (traceEnt->s.eType == ET_MOVER) { // hit a mover + if (!Q_stricmp("func_door", traceEnt->classname)) { // it's a func_door + if (traceEnt->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/) { // it's force-usable + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] || + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // player has push or pull float maxRange; - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//use the better range + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; - } - else - {//use the better range + } else { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( maxRange >= trace.fraction * 2048 ) - {//actually close enough to use one of our force powers on it + if (maxRange >= trace.fraction * 2048) { // actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } } } - } - else if ( !Q_stricmp( "func_static", traceEnt->classname ) ) - {//it's a func_static - if ( (traceEnt->spawnflags & 1/*F_PUSH*/) && (traceEnt->spawnflags & 2/*F_PULL*/) ) - {//push or pullable + } else if (!Q_stricmp("func_static", traceEnt->classname)) { // it's a func_static + if ((traceEnt->spawnflags & 1 /*F_PUSH*/) && (traceEnt->spawnflags & 2 /*F_PULL*/)) { // push or pullable float maxRange; - if ( cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH] ) - {//use the better range + if (cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL] > + cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]) { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]]; - } - else - {//use the better range + } else { // use the better range maxRange = forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( maxRange >= trace.fraction * 2048 ) - {//actually close enough to use one of our force powers on it + if (maxRange >= trace.fraction * 2048) { // actually close enough to use one of our force powers on it cg_forceCrosshair = qtrue; } - } - else if ( (traceEnt->spawnflags & 1/*F_PUSH*/) ) - {//pushable only - if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= trace.fraction * 2048 ) - {//actually close enough to use force push on it + } else if ((traceEnt->spawnflags & 1 /*F_PUSH*/)) { // pushable only + if (forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PUSH]] >= + trace.fraction * 2048) { // actually close enough to use force push on it cg_forceCrosshair = qtrue; } - } - else if ( (traceEnt->spawnflags & 2/*F_PULL*/) ) - {//pullable only - if ( forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= trace.fraction * 2048 ) - {//actually close enough to use force pull on it + } else if ((traceEnt->spawnflags & 2 /*F_PULL*/)) { // pullable only + if (forcePushPullRadius[cg_entities[0].gent->client->ps.forcePowerLevel[FP_PULL]] >= + trace.fraction * 2048) { // actually close enough to use force pull on it cg_forceCrosshair = qtrue; } } @@ -1780,61 +1538,47 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) } } } - if ( !cg_forceCrosshair ) - { - if ( cg_dynamicCrosshair.integer ) - {//100% accurate + if (!cg_forceCrosshair) { + if (cg_dynamicCrosshair.integer) { // 100% accurate vec3_t d_f, d_rt, d_up; - if ( cg.snap->ps.weapon == WP_NONE || - cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON ) - { - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in camera ent view + if (cg.snap->ps.weapon == WP_NONE || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_STUN_BATON) { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in camera ent view ignoreEnt = cg.snap->ps.viewEntity; - if ( g_entities[cg.snap->ps.viewEntity].client ) - { - VectorCopy( g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start ); - } - else - { - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start ); + if (g_entities[cg.snap->ps.viewEntity].client) { + VectorCopy(g_entities[cg.snap->ps.viewEntity].client->renderInfo.eyePoint, start); + } else { + VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpOrigin, start); } - AngleVectors( cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up ); - } - else - { - VectorCopy( g_entities[0].client->renderInfo.eyePoint, start ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); + AngleVectors(cg_entities[cg.snap->ps.viewEntity].lerpAngles, d_f, d_rt, d_up); + } else { + VectorCopy(g_entities[0].client->renderInfo.eyePoint, start); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); } + } else { + extern void CalcMuzzlePoint(gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in); + AngleVectors(cg_entities[0].lerpAngles, d_f, d_rt, d_up); + CalcMuzzlePoint(&g_entities[0], d_f, d_rt, d_up, start, 0); } - else - { - extern void CalcMuzzlePoint( gentity_t *const ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint, float lead_in ); - AngleVectors( cg_entities[0].lerpAngles, d_f, d_rt, d_up ); - CalcMuzzlePoint( &g_entities[0], d_f, d_rt, d_up, start , 0 ); - } - //VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start ); - //FIXME: increase this? Increase when zoom in? - VectorMA( start, 4096, d_f, end );//was 8192 - } - else - {//old way - VectorCopy( cg.refdef.vieworg, start ); - //FIXME: increase this? Increase when zoom in? - VectorMA( start, 4096, cg.refdef.viewaxis[0], end );//was 8192 - } - //YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. - gi.trace( &trace, start, vec3_origin, vec3_origin, end, - ignoreEnt, MASK_OPAQUE|CONTENTS_SHOTCLIP|CONTENTS_BODY|CONTENTS_ITEM, G2_NOCOLLIDE, 10 );// ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, could just remove their body earlier too... + // VectorCopy( g_entities[0].client->renderInfo.muzzlePoint, start ); + // FIXME: increase this? Increase when zoom in? + VectorMA(start, 4096, d_f, end); // was 8192 + } else { // old way + VectorCopy(cg.refdef.vieworg, start); + // FIXME: increase this? Increase when zoom in? + VectorMA(start, 4096, cg.refdef.viewaxis[0], end); // was 8192 + } + // YES! This is very very bad... but it works! James made me do it. Really, he did. Blame James. + gi.trace(&trace, start, vec3_origin, vec3_origin, end, ignoreEnt, MASK_OPAQUE | CONTENTS_SHOTCLIP | CONTENTS_BODY | CONTENTS_ITEM, G2_NOCOLLIDE, + 10); // ); took out CONTENTS_SOLID| so you can target people through glass.... took out CONTENTS_CORPSE so disintegrated guys aren't shown, + // could just remove their body earlier too... /* - CG_Trace( &trace, start, vec3_origin, vec3_origin, end, + CG_Trace( &trace, start, vec3_origin, vec3_origin, end, cg.snap->ps.clientNum, MASK_PLAYERSOLID|CONTENTS_CORPSE|CONTENTS_ITEM ); */ - //FIXME: pick up corpses - if ( trace.startsolid || trace.allsolid ) - { - // trace should not be allowed to pick up anything if it started solid. I tried actually moving the trace start back, which also worked, + // FIXME: pick up corpses + if (trace.startsolid || trace.allsolid) { + // trace should not be allowed to pick up anything if it started solid. I tried actually moving the trace start back, which also worked, // but the dynamic cursor drawing caused it to render around the clip of the gun when I pushed the blaster all the way into a wall. // It looked quite horrible...but, if this is bad for some reason that I don't know trace.entityNum = ENTITYNUM_NONE; @@ -1842,69 +1586,55 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) traceEnt = &g_entities[trace.entityNum]; } - // if the object is "dead", don't show it -/* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 ) - { - cg.crosshairClientNum = 0; - return; - } -*/ - //draw crosshair at endpoint - CG_DrawCrosshair( trace.endpos ); + /* if ( cg.crosshairClientNum && g_entities[cg.crosshairClientNum].health <= 0 ) + { + cg.crosshairClientNum = 0; + return; + } + */ + // draw crosshair at endpoint + CG_DrawCrosshair(trace.endpos); g_crosshairEntNum = trace.entityNum; - g_crosshairEntDist = 4096*trace.fraction; + g_crosshairEntDist = 4096 * trace.fraction; - if ( !traceEnt ) - { - //not looking at anything + if (!traceEnt) { + // not looking at anything g_crosshairSameEntTime = 0; g_crosshairEntTime = 0; - } - else - {//looking at a valid ent - //store the distance - if ( trace.entityNum != g_crosshairEntNum ) - {//new crosshair ent + } else { // looking at a valid ent + // store the distance + if (trace.entityNum != g_crosshairEntNum) { // new crosshair ent g_crosshairSameEntTime = 0; - } - else if ( g_crosshairEntDist < 256 ) - {//close enough to start counting how long you've been looking + } else if (g_crosshairEntDist < 256) { // close enough to start counting how long you've been looking g_crosshairSameEntTime += cg.frametime; } - //remember the last time you looked at the person + // remember the last time you looked at the person g_crosshairEntTime = cg.time; } - if ( !traceEnt || (traceEnt->s.eFlags & EF_NO_TED) ) - { - if ( traceEnt && scanAll ) - { - } - else - { + if (!traceEnt || (traceEnt->s.eFlags & EF_NO_TED)) { + if (traceEnt && scanAll) { + } else { return; } } // if the player is in fog, don't show it - content = cgi_CM_PointContents( trace.endpos, 0 ); - if ( content & CONTENTS_FOG ) - { + content = cgi_CM_PointContents(trace.endpos, 0); + if (content & CONTENTS_FOG) { return; } // if the player is cloaked, don't show it - if ( cg_entities[ trace.entityNum ].currentState.powerups & ( 1 << PW_CLOAKED )) - { + if (cg_entities[trace.entityNum].currentState.powerups & (1 << PW_CLOAKED)) { return; } // update the fade timer - if ( cg.crosshairClientNum != trace.entityNum ) - { + if (cg.crosshairClientNum != trace.entityNum) { infoStringCount = 0; } @@ -1912,163 +1642,135 @@ static void CG_ScanForCrosshairEntity( qboolean scanAll ) cg.crosshairClientTime = cg.time; } - /* ===================== CG_DrawCrosshairNames ===================== */ -static void CG_DrawCrosshairNames( void ) -{ - qboolean scanAll = qfalse; - centity_t *player = &cg_entities[0]; +static void CG_DrawCrosshairNames(void) { + qboolean scanAll = qfalse; + centity_t *player = &cg_entities[0]; - if ( cg_dynamicCrosshair.integer ) - { + if (cg_dynamicCrosshair.integer) { // still need to scan for dynamic crosshair - CG_ScanForCrosshairEntity( scanAll ); + CG_ScanForCrosshairEntity(scanAll); return; } - if ( !player->gent ) - { + if (!player->gent) { return; } - if ( !player->gent->client ) - { + if (!player->gent->client) { return; } // scan the known entities to see if the crosshair is sighted on one // This is currently being called by the rocket tracking code, so we don't necessarily want to do duplicate traces :) - CG_ScanForCrosshairEntity( scanAll ); + CG_ScanForCrosshairEntity(scanAll); } //-------------------------------------------------------------- -static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) +static void CG_DrawRocketLocking(int lockEntNum, int lockTime) //-------------------------------------------------------------- { gentity_t *gent = &g_entities[lockEntNum]; - if ( !gent ) - { + if (!gent) { return; } - int cx, cy; - vec3_t org; - static int oldDif = 0; + int cx, cy; + vec3_t org; + static int oldDif = 0; - VectorCopy( gent->currentOrigin, org ); + VectorCopy(gent->currentOrigin, org); org[2] += (gent->mins[2] + gent->maxs[2]) * 0.5f; - if ( CG_WorldCoordToScreenCoord( org, &cx, &cy )) - { + if (CG_WorldCoordToScreenCoord(org, &cx, &cy)) { // we care about distance from enemy to eye, so this is good enough - float sz = Distance( gent->currentOrigin, cg.refdef.vieworg ) / 1024.0f; - - if ( cg.zoomMode > 0 ) - { - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { - sz -= ( cg.overrides.fov - cg_zoomFov ) / 80.0f; - } - else - { - sz -= ( cg_fov.value - cg_zoomFov ) / 80.0f; + float sz = Distance(gent->currentOrigin, cg.refdef.vieworg) / 1024.0f; + + if (cg.zoomMode > 0) { + if (cg.overrides.active & CG_OVERRIDE_FOV) { + sz -= (cg.overrides.fov - cg_zoomFov) / 80.0f; + } else { + sz -= (cg_fov.value - cg_zoomFov) / 80.0f; } } - if ( sz > 1.0f ) - { + if (sz > 1.0f) { sz = 1.0f; - } - else if ( sz < 0.0f ) - { + } else if (sz < 0.0f) { sz = 0.0f; } sz = (1.0f - sz) * (1.0f - sz) * 32 + 6; - vec4_t color={0.0f,0.0f,0.0f,0.0f}; + vec4_t color = {0.0f, 0.0f, 0.0f, 0.0f}; cy += sz * 0.5f; - + // well now, take our current lock time and divide that by 8 wedge slices to get the current lock amount - int dif = ( cg.time - g_rocketLockTime ) / ( 1200.0f / 8.0f ); + int dif = (cg.time - g_rocketLockTime) / (1200.0f / 8.0f); - if ( dif < 0 ) - { + if (dif < 0) { oldDif = 0; return; - } - else if ( dif > 8 ) - { + } else if (dif > 8) { dif = 8; } // do sounds - if ( oldDif != dif ) - { - if ( dif == 8 ) - { - cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" )); - } - else - { - cgi_S_StartSound( org, 0, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" )); + if (oldDif != dif) { + if (dif == 8) { + cgi_S_StartSound(org, 0, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/rocket/lock.wav")); + } else { + cgi_S_StartSound(org, 0, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/rocket/tick.wav")); } } oldDif = dif; - for ( int i = 0; i < dif; i++ ) - { + for (int i = 0; i < dif; i++) { color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; color[3] = 0.1f * i + 0.2f; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); // our slices are offset by about 45 degrees. - CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" )); + CG_DrawRotatePic(cx - sz, cy - sz, sz, sz, i * 45.0f, cgi_R_RegisterShaderNoMip("gfx/2d/wedge")); } // we are locked and loaded baby - if ( dif == 8 ) - { - color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f; + if (dif == 8) { + color[0] = color[1] = color[2] = sin(cg.time * 0.05f) * 0.5f + 0.5f; color[3] = 1.0f; // this art is additive, so the alpha value does nothing - cgi_R_SetColor( color ); + cgi_R_SetColor(color); - CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip( "gfx/2d/lock" )); + CG_DrawPic(cx - sz, cy - sz * 2, sz * 2, sz * 2, cgi_R_RegisterShaderNoMip("gfx/2d/lock")); } } } //------------------------------------ -static void CG_RunRocketLocking( void ) +static void CG_RunRocketLocking(void) //------------------------------------ { - centity_t *player = &cg_entities[0]; + centity_t *player = &cg_entities[0]; // Only bother with this when the player is holding down the alt-fire button of the rocket launcher - if ( player->currentState.weapon == WP_ROCKET_LAUNCHER ) - { - if ( player->currentState.eFlags & EF_ALT_FIRING ) - { + if (player->currentState.weapon == WP_ROCKET_LAUNCHER) { + if (player->currentState.eFlags & EF_ALT_FIRING) { CG_ScanForRocketLock(); - if ( g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0 ) - { - CG_DrawRocketLocking( g_rocketLockEntNum, g_rocketLockTime ); + if (g_rocketLockEntNum > 0 && g_rocketLockEntNum < ENTITYNUM_WORLD && g_rocketLockTime > 0) { + CG_DrawRocketLocking(g_rocketLockEntNum, g_rocketLockTime); } - } - else - { + } else { // disengage any residual locking g_rocketLockEntNum = ENTITYNUM_WORLD; g_rocketLockTime = 0; @@ -2081,42 +1783,37 @@ static void CG_RunRocketLocking( void ) CG_DrawIntermission ================= */ -static void CG_DrawIntermission( void ) { - CG_DrawScoreboard(); -} - +static void CG_DrawIntermission(void) { CG_DrawScoreboard(); } /* ================== CG_DrawSnapshot ================== */ -static float CG_DrawSnapshot( float y ) { - char *s; - int w; +static float CG_DrawSnapshot(float y) { + char *s; + int w; - s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime, - cg.latestSnapshotNum, cgs.serverCommandSequence ); + s = va("time:%i snap:%i cmd:%i", cg.snap->serverTime, cg.latestSnapshotNum, cgs.serverCommandSequence); - w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); + cgi_R_Font_DrawString(635 - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } - /* ================== CG_DrawFPS ================== */ -#define FPS_FRAMES 16 -static float CG_DrawFPS( float y ) { - char *s; +#define FPS_FRAMES 16 +static float CG_DrawFPS(float y) { + char *s; static unsigned short previousTimes[FPS_FRAMES]; static unsigned short index; - static int previous, lastupdate; - int t, i, fps, total; + static int previous, lastupdate; + int t, i, fps, total; unsigned short frameTime; // don't use serverTime, because that will be drifting to @@ -2124,7 +1821,7 @@ static float CG_DrawFPS( float y ) { t = cgi_Milliseconds(); frameTime = t - previous; previous = t; - if (t - lastupdate > 50) //don't sample faster than this + if (t - lastupdate > 50) // don't sample faster than this { lastupdate = t; previousTimes[index % FPS_FRAMES] = frameTime; @@ -2132,17 +1829,17 @@ static float CG_DrawFPS( float y ) { } // average multiple frames together to smooth changes out a bit total = 0; - for ( i = 0 ; i < FPS_FRAMES ; i++ ) { + for (i = 0; i < FPS_FRAMES; i++) { total += previousTimes[i]; } - if ( !total ) { + if (!total) { total = 1; } fps = 1000 * FPS_FRAMES / total; - s = va( "%ifps", fps ); - const int w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + s = va("%ifps", fps); + const int w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); + cgi_R_Font_DrawString(635 - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } @@ -2152,10 +1849,10 @@ static float CG_DrawFPS( float y ) { CG_DrawTimer ================= */ -static float CG_DrawTimer( float y ) { - char *s; - int w; - int mins, seconds, tens; +static float CG_DrawTimer(float y) { + char *s; + int w; + int mins, seconds, tens; seconds = cg.time / 1000; mins = seconds / 60; @@ -2163,83 +1860,72 @@ static float CG_DrawTimer( float y ) { tens = seconds / 10; seconds -= tens * 10; - s = va( "%i:%i%i", mins, tens, seconds ); + s = va("%i:%i%i", mins, tens, seconds); - w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString(635 - w, y+2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + w = cgi_R_Font_StrLenPixels(s, cgs.media.qhFontMedium, 1.0f); + cgi_R_Font_DrawString(635 - w, y + 2, s, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); return y + BIGCHAR_HEIGHT + 10; } - /* ================= CG_DrawAmmoWarning ================= */ -static void CG_DrawAmmoWarning( void ) { - char text[1024]={0}; - int w; +static void CG_DrawAmmoWarning(void) { + char text[1024] = {0}; + int w; - if ( cg_drawAmmoWarning.integer == 0 ) { + if (cg_drawAmmoWarning.integer == 0) { return; } - if ( !cg.lowAmmoWarning ) { + if (!cg.lowAmmoWarning) { return; } - if ( weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE ) - {//doesn't use ammo, so no warning + if (weaponData[cg.snap->ps.weapon].ammoIndex == AMMO_NONE) { // doesn't use ammo, so no warning return; } - if ( cg.lowAmmoWarning == 2 ) { - cgi_SP_GetStringTextString( "INGAME_INSUFFICIENTENERGY", text, sizeof(text) ); + if (cg.lowAmmoWarning == 2) { + cgi_SP_GetStringTextString("INGAME_INSUFFICIENTENERGY", text, sizeof(text)); } else { return; - //s = "LOW AMMO WARNING"; + // s = "LOW AMMO WARNING"; } - w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - cgi_R_Font_DrawString(320 - w/2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + cgi_R_Font_DrawString(320 - w / 2, 64, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); } //--------------------------------------- -static qboolean CG_RenderingFromMiscCamera() -{ - //centity_t *cent; +static qboolean CG_RenderingFromMiscCamera() { + // centity_t *cent; - //cent = &cg_entities[cg.snap->ps.clientNum]; + // cent = &cg_entities[cg.snap->ps.clientNum]; - if ( cg.snap->ps.viewEntity > 0 && - cg.snap->ps.viewEntity < ENTITYNUM_WORLD )// cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity) + if (cg.snap->ps.viewEntity > 0 && + cg.snap->ps.viewEntity < ENTITYNUM_WORLD) // cent && cent->gent && cent->gent->client && cent->gent->client->ps.viewEntity) { // Only check viewEntities - if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname )) - { + if (!Q_stricmp("misc_camera", g_entities[cg.snap->ps.viewEntity].classname)) { // Only doing a misc_camera, so check health. - if ( g_entities[cg.snap->ps.viewEntity].health > 0 ) - { - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/workingCamera" )); - } - else - { - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/brokenCamera" )); + if (g_entities[cg.snap->ps.viewEntity].health > 0) { + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/workingCamera")); + } else { + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/brokenCamera")); } // don't render other 2d stuff return qtrue; - } - else if ( !Q_stricmp( "misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname )) - { + } else if (!Q_stricmp("misc_panel_turret", g_entities[cg.snap->ps.viewEntity].classname)) { // could do a panel turret screen overlay...this is a cheesy placeholder - CG_DrawPic( 30, 90, 128, 300, cgs.media.turretComputerOverlayShader ); - CG_DrawPic( 610, 90, -128, 300, cgs.media.turretComputerOverlayShader ); - } - else - { + CG_DrawPic(30, 90, 128, 300, cgs.media.turretComputerOverlayShader); + CG_DrawPic(610, 90, -128, 300, cgs.media.turretComputerOverlayShader); + } else { // FIXME: make sure that this assumption is correct...because I'm assuming that I must be a droid. - CG_DrawPic( 0, 0, 640, 480, cgi_R_RegisterShader( "gfx/2d/droid_view" )); + CG_DrawPic(0, 0, 640, 480, cgi_R_RegisterShader("gfx/2d/droid_view")); } } @@ -2252,35 +1938,29 @@ static qboolean CG_RenderingFromMiscCamera() CG_Draw2D ================= */ -extern void CG_SaberClashFlare( void ); -static void CG_Draw2D( void ) -{ - char text[1024]={0}; - int w,y_pos; +extern void CG_SaberClashFlare(void); +static void CG_Draw2D(void) { + char text[1024] = {0}; + int w, y_pos; centity_t *cent = &cg_entities[cg.snap->ps.clientNum]; // if we are taking a levelshot for the menu, don't draw anything - if ( cg.levelShot ) - { + if (cg.levelShot) { return; } - if ( cg_draw2D.integer == 0 ) - { + if (cg_draw2D.integer == 0) { return; } - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) - { + if (cg.snap->ps.pm_type == PM_INTERMISSION) { CG_DrawIntermission(); return; } - if (cg_endcredits.integer) - { - if (!CG_Credits_Draw()) - { - CG_DrawCredits(); // will probably get rid of this soon + if (cg_endcredits.integer) { + if (!CG_Credits_Draw()) { + CG_DrawCredits(); // will probably get rid of this soon } } @@ -2289,51 +1969,45 @@ static void CG_Draw2D( void ) CG_DrawBatteryCharge(); // Draw this before the text so that any text won't get clipped off - if ( !in_camera ) - { + if (!in_camera) { CG_DrawZoomMask(); } CG_DrawScrollText(); - CG_DrawCaptionText(); + CG_DrawCaptionText(); - if ( in_camera ) - {//still draw the saber clash flare, but nothing else + if (in_camera) { // still draw the saber clash flare, but nothing else CG_SaberClashFlare(); return; } - if ( CG_RenderingFromMiscCamera()) - { + if (CG_RenderingFromMiscCamera()) { // purposely doing an early out when in a misc_camera, change it if needed. - + // allowing center print when in camera mode, probably just an alpha thing - dmv CG_DrawCenterString(); return; } // don't draw any status if dead - if ( cg.snap->ps.stats[STAT_HEALTH] > 0 ) - { - if ( !(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON |EF_IN_ATST))) - { + if (cg.snap->ps.stats[STAT_HEALTH] > 0) { + if (!(cent->gent && cent->gent->s.eFlags & (EF_LOCKED_TO_WEAPON | EF_IN_ATST))) { CG_DrawIconBackground(); } CG_DrawWeaponSelect(); - if ( cg.zoomMode == 0 ) - { + if (cg.zoomMode == 0) { CG_DrawStats(); } CG_DrawAmmoWarning(); - //CROSSHAIR is now done from the crosshair ent trace - //if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person draws its own crosshair + // CROSSHAIR is now done from the crosshair ent trace + // if ( !cg.renderingThirdPerson && !cg_dynamicCrosshair.integer ) // disruptor draws it's own crosshair artwork; binocs draw nothing; third person + // draws its own crosshair //{ // CG_DrawCrosshair( NULL ); - //} - + // } CG_DrawCrosshairNames(); @@ -2349,45 +2023,42 @@ static void CG_Draw2D( void ) float y = 0; if (cg_drawSnapshot.integer) { - y=CG_DrawSnapshot(y); - } + y = CG_DrawSnapshot(y); + } if (cg_drawFPS.integer) { - y=CG_DrawFPS(y); - } + y = CG_DrawFPS(y); + } if (cg_drawTimer.integer) { - y=CG_DrawTimer(y); + y = CG_DrawTimer(y); } // don't draw center string if scoreboard is up - if ( !CG_DrawScoreboard() ) { + if (!CG_DrawScoreboard()) { CG_DrawCenterString(); } - if (missionInfo_Updated) - { - if (cg.predicted_player_state.pm_type != PM_DEAD) - { + if (missionInfo_Updated) { + if (cg.predicted_player_state.pm_type != PM_DEAD) { // Was a objective given? -/* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer)) - { - // How long has the game been running? If within 15 seconds of starting, throw up the datapad. - if (cg.dataPadLevelStartTime>cg.time) - { - // Make it pop up - if (!in_camera) - { - cgi_SendConsoleCommand( "datapad" ); - cg.dataPadLevelStartTime=cg.time; //and don't do it again this level! - } - } - } -*/ - if (!cg.missionInfoFlashTime) - { - cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer; + /* if ((cg_updatedDataPadForcePower.integer) || (cg_updatedDataPadObjective.integer)) + { + // How long has the game been running? If within 15 seconds of starting, throw up the datapad. + if (cg.dataPadLevelStartTime>cg.time) + { + // Make it pop up + if (!in_camera) + { + cgi_SendConsoleCommand( "datapad" ); + cg.dataPadLevelStartTime=cg.time; //and don't do it again this level! + } + } + } + */ + if (!cg.missionInfoFlashTime) { + cg.missionInfoFlashTime = cg.time + cg_missionInfoFlashTime.integer; } - if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it. + if (cg.missionInfoFlashTime < cg.time) // Time's up. They didn't read it. { cg.missionInfoFlashTime = 0; missionInfo_Updated = qfalse; @@ -2395,51 +2066,45 @@ static void CG_Draw2D( void ) CG_ClearDataPadCvars(); } - cgi_SP_GetStringTextString( "INGAME_DATAPAD_UPDATED", text, sizeof(text) ); + cgi_SP_GetStringTextString("INGAME_DATAPAD_UPDATED", text, sizeof(text)); int x_pos = 0; - y_pos = (SCREEN_HEIGHT/2)+80; - if ( cg_missionInfoCentered.integer ) - { - w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f); - x_pos = (SCREEN_WIDTH/2)-(w/2); + y_pos = (SCREEN_HEIGHT / 2) + 80; + if (cg_missionInfoCentered.integer) { + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + x_pos = (SCREEN_WIDTH / 2) - (w / 2); } - cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); - if (cg_updatedDataPadForcePower1.integer) - { + if (cg_updatedDataPadForcePower1.integer) { y_pos += 25; - cgi_SP_GetStringTextString("INGAME_NEW_FORCE_POWER_INFO", text, sizeof(text) ); - if ( cg_missionInfoCentered.integer ) - { - w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f); - x_pos = (SCREEN_WIDTH/2)-(w/2); + cgi_SP_GetStringTextString("INGAME_NEW_FORCE_POWER_INFO", text, sizeof(text)); + if (cg_missionInfoCentered.integer) { + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + x_pos = (SCREEN_WIDTH / 2) - (w / 2); } - cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); } - if (cg_updatedDataPadObjective.integer) - { + if (cg_updatedDataPadObjective.integer) { y_pos += 25; - cgi_SP_GetStringTextString( "INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text) ); - if ( cg_missionInfoCentered.integer ) - { - w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontSmall, 1.0f); - x_pos = (SCREEN_WIDTH/2)-(w/2); + cgi_SP_GetStringTextString("INGAME_NEW_OBJECTIVE_INFO", text, sizeof(text)); + if (cg_missionInfoCentered.integer) { + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + x_pos = (SCREEN_WIDTH / 2) - (w / 2); } - cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x_pos, y_pos, text, colorTable[CT_LTRED1], cgs.media.qhFontMedium, -1, 1.0f); } - // if (cent->gent->client->sess.missionObjectivesShown<3) - // { -// CG_DrawProportionalString((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2) + 20, ingame_text[IGT_MISSIONINFO_UPDATED2], -// CG_PULSE | CG_CENTER| CG_SMALLFONT, colorTable[CT_LTRED1] ); - // } + // if (cent->gent->client->sess.missionObjectivesShown<3) + // { + // CG_DrawProportionalString((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2) + 20, ingame_text[IGT_MISSIONINFO_UPDATED2], + // CG_PULSE | CG_CENTER| CG_SMALLFONT, colorTable[CT_LTRED1] ); + // } } } } - /* ===================== CG_DrawActive @@ -2447,26 +2112,26 @@ CG_DrawActive Perform all drawing needed to completely fill the screen ===================== */ -void CG_DrawActive( stereoFrame_t stereoView ) { - float separation; - vec3_t baseOrg; +void CG_DrawActive(stereoFrame_t stereoView) { + float separation; + vec3_t baseOrg; // optionally draw the info screen instead - if ( !cg.snap ) { + if (!cg.snap) { CG_DrawInformation(); return; } - //FIXME: these globals done once at start of frame for various funcs - AngleVectors (cg.refdefViewAngles, vfwd, vright, vup); - VectorCopy( vfwd, vfwd_n ); - VectorCopy( vright, vright_n ); - VectorCopy( vup, vup_n ); - VectorNormalize( vfwd_n ); - VectorNormalize( vright_n ); - VectorNormalize( vup_n ); + // FIXME: these globals done once at start of frame for various funcs + AngleVectors(cg.refdefViewAngles, vfwd, vright, vup); + VectorCopy(vfwd, vfwd_n); + VectorCopy(vright, vright_n); + VectorCopy(vup, vup_n); + VectorNormalize(vfwd_n); + VectorNormalize(vright_n); + VectorNormalize(vup_n); - switch ( stereoView ) { + switch (stereoView) { case STEREO_CENTER: separation = 0; break; @@ -2478,34 +2143,31 @@ void CG_DrawActive( stereoFrame_t stereoView ) { break; default: separation = 0; - CG_Error( "CG_DrawActive: Undefined stereoView" ); + CG_Error("CG_DrawActive: Undefined stereoView"); } - // clear around the rendered view if sized down CG_TileClear(); // offset vieworg appropriately if we're doing stereo separation - VectorCopy( cg.refdef.vieworg, baseOrg ); - if ( separation != 0 ) { - VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg ); + VectorCopy(cg.refdef.vieworg, baseOrg); + if (separation != 0) { + VectorMA(cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg); } - if ( cg.zoomMode == 3 && cg.snap->ps.batteryCharge ) // doing the Light amp goggles thing + if (cg.zoomMode == 3 && cg.snap->ps.batteryCharge) // doing the Light amp goggles thing { cgi_R_LAGoggles(); } // draw 3D view - cgi_R_RenderScene( &cg.refdef ); + cgi_R_RenderScene(&cg.refdef); // restore original viewpoint if running stereo - if ( separation != 0 ) { - VectorCopy( baseOrg, cg.refdef.vieworg ); + if (separation != 0) { + VectorCopy(baseOrg, cg.refdef.vieworg); } // draw status bar and other floating elements CG_Draw2D(); - } - diff --git a/codeJK2/cgame/cg_drawtools.cpp b/codeJK2/cgame/cg_drawtools.cpp index badda5920b..2d50836c05 100644 --- a/codeJK2/cgame/cg_drawtools.cpp +++ b/codeJK2/cgame/cg_drawtools.cpp @@ -31,13 +31,12 @@ CG_FillRect Coordinates are 640*480 virtual values ================= */ -void CG_FillRect( float x, float y, float width, float height, const float *color ) { - cgi_R_SetColor( color ); - cgi_R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); - cgi_R_SetColor( NULL ); +void CG_FillRect(float x, float y, float width, float height, const float *color) { + cgi_R_SetColor(color); + cgi_R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); + cgi_R_SetColor(NULL); } - /* ================ CG_Scissor @@ -45,13 +44,7 @@ CG_Scissor Coordinates are 640*480 virtual values ================= */ -void CG_Scissor( float x, float y, float width, float height) -{ - - cgi_R_Scissor( x, y, width, height); - -} - +void CG_Scissor(float x, float y, float width, float height) { cgi_R_Scissor(x, y, width, height); } /* ================ @@ -61,9 +54,7 @@ Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ -void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { - cgi_R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); -} +void CG_DrawPic(float x, float y, float width, float height, qhandle_t hShader) { cgi_R_DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } /* ================ @@ -74,9 +65,8 @@ A width of 0 will draw with the original image width Can also specify the exact texture coordinates ================= */ -void CG_DrawPic2( float x, float y, float width, float height, float s1, float t1, float s2, float t2, qhandle_t hShader ) -{ - cgi_R_DrawStretchPic( x, y, width, height, s1, t1, s2, t2, hShader ); +void CG_DrawPic2(float x, float y, float width, float height, float s1, float t1, float s2, float t2, qhandle_t hShader) { + cgi_R_DrawStretchPic(x, y, width, height, s1, t1, s2, t2, hShader); } /* @@ -88,8 +78,8 @@ A width of 0 will draw with the original image width rotates around the upper right corner of the passed in point ================= */ -void CG_DrawRotatePic( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - cgi_R_DrawRotatePic( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic(float x, float y, float width, float height, float angle, qhandle_t hShader) { + cgi_R_DrawRotatePic(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -101,8 +91,8 @@ A width of 0 will draw with the original image width Actually rotates around the center point of the passed in coordinates ================= */ -void CG_DrawRotatePic2( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - cgi_R_DrawRotatePic2( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic2(float x, float y, float width, float height, float angle, qhandle_t hShader) { + cgi_R_DrawRotatePic2(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -112,15 +102,15 @@ CG_DrawChar Coordinates and size in 640*480 virtual screen size =============== */ -void CG_DrawChar( int x, int y, int width, int height, int ch ) { +void CG_DrawChar(int x, int y, int width, int height, int ch) { int row, col; float frow, fcol; float size; - float ax, ay, aw, ah; + float ax, ay, aw, ah; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } @@ -129,32 +119,29 @@ void CG_DrawChar( int x, int y, int width, int height, int ch ) { aw = width; ah = height; - row = ch>>4; - col = ch&15; -/* - frow = row*0.0625; - fcol = col*0.0625; - size = 0.0625; - - cgi_R_DrawStretchPic( ax, ay, aw, ah, - fcol, frow, - fcol + size, frow + size, - cgs.media.charsetShader ); -*/ + row = ch >> 4; + col = ch & 15; + /* + frow = row*0.0625; + fcol = col*0.0625; + size = 0.0625; + + cgi_R_DrawStretchPic( ax, ay, aw, ah, + fcol, frow, + fcol + size, frow + size, + cgs.media.charsetShader ); + */ float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - cgi_R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, - cgs.media.charsetShader ); - + cgi_R_DrawStretchPic(ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader); } - /* ================== CG_DrawStringExt @@ -165,25 +152,24 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, - qboolean forceColor, qboolean shadow, int charWidth, int charHeight ) { - vec4_t color; - const char *s; - int xx; +void CG_DrawStringExt(int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight) { + vec4_t color; + const char *s; + int xx; // draw the drop shadow if (shadow) { color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); s = string; xx = x; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; continue; } - CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s ); + CG_DrawChar(xx + 2, y + 2, charWidth, charHeight, *s); xx += charWidth; s++; } @@ -192,28 +178,25 @@ void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, // draw the colored text s = string; xx = x; - cgi_R_SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + cgi_R_SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - cgi_R_SetColor( color ); + cgi_R_SetColor(color); } s += 2; continue; } - CG_DrawChar( xx, y, charWidth, charHeight, *s ); + CG_DrawChar(xx, y, charWidth, charHeight, *s); xx += charWidth; s++; } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - -void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) { - CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT ); -} +void CG_DrawSmallStringColor(int x, int y, const char *s, vec4_t color) { CG_DrawStringExt(x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT); } /* ================= @@ -222,12 +205,12 @@ CG_DrawStrlen Returns character count, skiping color escape codes ================= */ -int CG_DrawStrlen( const char *str ) { +int CG_DrawStrlen(const char *str) { const char *s = str; int count = 0; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; } else { count++; @@ -246,18 +229,16 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) { - float s1, t1, s2, t2; - - s1 = x/64.0; - t1 = y/64.0; - s2 = (x+w)/64.0; - t2 = (y+h)/64.0; - cgi_R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); +static void CG_TileClearBox(int x, int y, int w, int h, qhandle_t hShader) { + float s1, t1, s2, t2; + + s1 = x / 64.0; + t1 = y / 64.0; + s2 = (x + w) / 64.0; + t2 = (y + h) / 64.0; + cgi_R_DrawStretchPic(x, y, w, h, s1, t1, s2, t2, hShader); } - - /* ============== CG_TileClear @@ -265,60 +246,57 @@ CG_TileClear Clear around a sized down screen ============== */ -void CG_TileClear( void ) { - int top, bottom, left, right; - int w, h; +void CG_TileClear(void) { + int top, bottom, left, right; + int w, h; w = cgs.glconfig.vidWidth; h = cgs.glconfig.vidHeight; - if ( cg.refdef.x == 0 && cg.refdef.y == 0 && - cg.refdef.width == w && cg.refdef.height == h ) { - return; // full screen rendering + if (cg.refdef.x == 0 && cg.refdef.y == 0 && cg.refdef.width == w && cg.refdef.height == h) { + return; // full screen rendering } top = cg.refdef.y; - bottom = top + cg.refdef.height-1; + bottom = top + cg.refdef.height - 1; left = cg.refdef.x; - right = left + cg.refdef.width-1; + right = left + cg.refdef.width - 1; // clear above view screen - CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader ); + CG_TileClearBox(0, 0, w, top, cgs.media.backTileShader); // clear below view screen - CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader ); + CG_TileClearBox(0, bottom, w, h - bottom, cgs.media.backTileShader); // clear left of view screen - CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(0, top, left, bottom - top + 1, cgs.media.backTileShader); // clear right of view screen - CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(right, top, w - right, bottom - top + 1, cgs.media.backTileShader); } - - /* ================ CG_FadeColor ================ */ -float *CG_FadeColor( int startMsec, int totalMsec ) { - static vec4_t color; - int t; +float *CG_FadeColor(int startMsec, int totalMsec) { + static vec4_t color; + int t; - if ( startMsec == 0 ) { + if (startMsec == 0) { return NULL; } t = cg.time - startMsec; - if ( t >= totalMsec ) { + if (t >= totalMsec) { return NULL; } // fade out - if ( totalMsec - t < FADE_TIME ) { - color[3] = ( totalMsec - t ) * 1.0/FADE_TIME; + if (totalMsec - t < FADE_TIME) { + color[3] = (totalMsec - t) * 1.0 / FADE_TIME; } else { color[3] = 1.0; } @@ -335,12 +313,11 @@ Take x,y positions as if 640 x 480 and scales them to the proper resolution ============== */ -void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charHeight,int style,qboolean zeroFill) -{ - char num[16], *ptr; - int l; - int frame; - int xWidth; +void CG_DrawNumField(int x, int y, int width, int value, int charWidth, int charHeight, int style, qboolean zeroFill) { + char num[16], *ptr; + int l; + int frame; + int xWidth; if (width < 1) { return; @@ -351,7 +328,7 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH width = 5; } - switch ( width ) { + switch (width) { case 1: value = value > 9 ? 9 : value; value = value < 0 ? 0 : value; @@ -370,71 +347,63 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH break; } - Com_sprintf (num, sizeof(num), "%i", value); + Com_sprintf(num, sizeof(num), "%i", value); l = strlen(num); if (l > width) l = width; // FIXME: Might need to do something different for the chunky font?? - switch(style) - { + switch (style) { case NUM_FONT_SMALL: xWidth = charWidth; break; case NUM_FONT_CHUNKY: - xWidth = (charWidth/1.2f) + 2; + xWidth = (charWidth / 1.2f) + 2; break; default: case NUM_FONT_BIG: - xWidth = (charWidth/2) + 7;//(charWidth/6); + xWidth = (charWidth / 2) + 7; //(charWidth/6); break; } - if ( zeroFill ) - { - for (int i = 0; i < (width - l); i++ ) - { - switch(style) - { + if (zeroFill) { + for (int i = 0; i < (width - l); i++) { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[0]); break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[0]); break; } x += 2 + (xWidth); } - } - else - { - x += 2 + (xWidth)*(width - l); + } else { + x += 2 + (xWidth) * (width - l); } ptr = num; - while (*ptr && l) - { + while (*ptr && l) { if (*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - switch(style) - { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[frame] ); - x++; // For a one line gap + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[frame]); + x++; // For a one line gap break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[frame]); break; } @@ -442,7 +411,6 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH ptr++; l--; } - } /* @@ -450,8 +418,7 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH CG_DrawProportionalString ================= */ -void CG_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) -{ - //assert(!style);//call this directly if you need style (OR it into the font handle) - cgi_R_Font_DrawString (x, y, str, color, cgs.media.qhFontMedium, -1, 1.0f); +void CG_DrawProportionalString(int x, int y, const char *str, int style, vec4_t color) { + // assert(!style);//call this directly if you need style (OR it into the font handle) + cgi_R_Font_DrawString(x, y, str, color, cgs.media.qhFontMedium, -1, 1.0f); } \ No newline at end of file diff --git a/codeJK2/cgame/cg_effects.cpp b/codeJK2/cgame/cg_effects.cpp index eb2dd990d6..cbff7707ad 100644 --- a/codeJK2/cgame/cg_effects.cpp +++ b/codeJK2/cgame/cg_effects.cpp @@ -27,10 +27,10 @@ along with this program; if not, see . #include "cg_media.h" #if !defined(FX_SCHEDULER_H_INC) - #include "FxScheduler.h" +#include "FxScheduler.h" #endif -//void DoBolt( vec3_t m_origin, vec3_t m_origin2, float m_scale, float m_deviation ); +// void DoBolt( vec3_t m_origin, vec3_t m_origin2, float m_scale, float m_deviation ); /* ==================== @@ -38,7 +38,7 @@ CG_MakeExplosion ==================== */ /* -localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, +localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, qhandle_t hModel, int numFrames, qhandle_t shader, int msec, qboolean isSprite, float scale, int flags ) { @@ -56,7 +56,7 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, ex = CG_AllocLocalEntity(); if ( isSprite ) { - ex->leType = LE_SPRITE_EXPLOSION; + ex->leType = LE_SPRITE_EXPLOSION; ex->refEntity.rotation = rand() % 360; ex->radius = scale; VectorScale( dir, 16, tmpVec ); @@ -81,7 +81,7 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, ex->startTime = cg.time - offset; ex->endTime = ex->startTime + msec; - + // bias the time so all shader effects start correctly ex->refEntity.shaderTime = ex->startTime / 1000.0f; @@ -108,7 +108,7 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, } */ // When calling this version, just pass in a zero for the flags -//localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, +// localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, // qhandle_t hModel, int numFrames, qhandle_t shader, // int msec, qboolean isSprite, float scale ) { // return CG_MakeExplosion( origin, dir, hModel, numFrames, shader, msec, isSprite, scale, 0 ); @@ -119,27 +119,26 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, CG_AddTempLight ==================== */ -localEntity_t *CG_AddTempLight( vec3_t origin, float scale, vec3_t color, int msec ) -{ - localEntity_t *ex; +localEntity_t *CG_AddTempLight(vec3_t origin, float scale, vec3_t color, int msec) { + localEntity_t *ex; - if ( msec <= 0 ) { - CG_Error( "CG_AddTempLight: msec = %i", msec ); + if (msec <= 0) { + CG_Error("CG_AddTempLight: msec = %i", msec); } ex = CG_AllocLocalEntity(); - ex->leType = LE_LIGHT; + ex->leType = LE_LIGHT; ex->startTime = cg.time; ex->endTime = ex->startTime + msec; - + // set origin - VectorCopy ( origin, ex->refEntity.origin); - VectorCopy ( origin, ex->refEntity.oldorigin ); + VectorCopy(origin, ex->refEntity.origin); + VectorCopy(origin, ex->refEntity.oldorigin); - VectorCopy( color, ex->lightColor ); - ex->light = scale; + VectorCopy(color, ex->lightColor); + ex->light = scale; return ex; } @@ -153,29 +152,27 @@ intensity ranges from 1 (minor tremble) to 16 (major quake) ------------------------- */ -void CG_ExplosionEffects( vec3_t origin, float intensity, int radius, int time ) -{ - //FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s +void CG_ExplosionEffects(vec3_t origin, float intensity, int radius, int time) { + // FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s - vec3_t dir; - float dist, intensityScale; - float realIntensity; + vec3_t dir; + float dist, intensityScale; + float realIntensity; - VectorSubtract( cg.refdef.vieworg, origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(cg.refdef.vieworg, origin, dir); + dist = VectorNormalize(dir); - //Use the dir to add kick to the explosion + // Use the dir to add kick to the explosion - if ( dist > radius ) + if (dist > radius) return; - intensityScale = 1 - ( dist / (float) radius ); + intensityScale = 1 - (dist / (float)radius); realIntensity = intensity * intensityScale; - CGCam_Shake( realIntensity, time ); + CGCam_Shake(realIntensity, time); } - /* ------------------------- CG_SurfaceExplosion @@ -201,9 +198,9 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak //Sparks numSparks = 16 + (Q_flrand(0.0f, 1.0f) * 16.0f); - + for ( i = 0; i < numSparks; i++ ) - { + { scale = 0.25f + (Q_flrand(0.0f, 1.0f) * 2.0f); dscale = -scale*0.5; @@ -233,20 +230,21 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak for ( i = 0; i < 4; i++ ) { - VectorSet( temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[2] + (Q_flrand(0.0f, 1.0f) * 4.0f) ); - VectorSet( temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[2] + (Q_flrand(-1.0f, 1.0f) * 8.0f) ); + VectorSet( temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[2] + (Q_flrand(0.0f, 1.0f) +* 4.0f) ); VectorSet( temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[2] + (Q_flrand(-1.0f, 1.0f) +* 8.0f) ); FX_AddSprite( temp_org, - temp_vel, - NULL, - 64.0f + (Q_flrand(0.0f, 1.0f) * 32.0f), - 16.0f, - 1.0f, + temp_vel, + NULL, + 64.0f + (Q_flrand(0.0f, 1.0f) * 32.0f), + 16.0f, + 1.0f, 0.0f, 20.0f + (Q_flrand(-1.0f, 1.0f) * 90.0f), 0.5f, - 1500.0f, - cgs.media.smokeShader, FXF_USE_ALPHA_CHAN ); + 1500.0f, + cgs.media.smokeShader, FXF_USE_ALPHA_CHAN ); } //Core of the explosion @@ -256,14 +254,14 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak VectorNormalize( direction ); //Tag the last one with a light - le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, radius * 0.02f + (Q_flrand(0.0f, 1.0f) * 0.3f) ); - le->light = 150; - VectorSet( le->lightColor, 0.9f, 0.8f, 0.5f ); + le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, radius * 0.02f + (Q_flrand(0.0f, 1.0f) +* 0.3f) ); le->light = 150; VectorSet( le->lightColor, 0.9f, 0.8f, 0.5f ); for ( i = 0; i < NUM_EXPLOSIONS-1; i ++) { - VectorSet( new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)) ); - le = CG_MakeExplosion( new_org, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, radius * 0.05f + (Q_flrand(-1.0f, 1.0f) *0.3f) ); + VectorSet( new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * +8))*Q_flrand(-1.0f, 1.0f)), (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)) ); le = CG_MakeExplosion( new_org, direction, +cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, radius * 0.05f + (Q_flrand(-1.0f, 1.0f) *0.3f) ); } //Shake the camera @@ -291,18 +289,16 @@ Adds an explosion to a misc model breakables ------------------------- */ -void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ) -{ - int ct = 13; - float r; - vec3_t org, mid, dir; - char *effect = NULL, *effect2 = NULL; +void CG_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType) { + int ct = 13; + float r; + vec3_t org, mid, dir; + char *effect = NULL, *effect2 = NULL; - VectorAdd( mins, maxs, mid ); - VectorScale( mid, 0.5f, mid ); + VectorAdd(mins, maxs, mid); + VectorScale(mid, 0.5f, mid); - switch( chunkType ) - { + switch (chunkType) { case MAT_GLASS: effect = "chunks/glassbreak"; ct = 5; @@ -333,12 +329,11 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk ct = 20; effect = "chunks/ropebreak"; break; - case MAT_WHITE_METAL: //not sure what this crap is really supposed to be.. + case MAT_WHITE_METAL: // not sure what this crap is really supposed to be.. case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: - switch( size ) - { + switch (size) { case 2: effect = "chunks/rockbreaklg"; break; @@ -351,42 +346,35 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk break; } - if ( !effect ) - { + if (!effect) { return; } ct += 7 * size; // FIXME: real precache .. VERify that these need to be here...don't think they would because the effects should be registered in g_breakable - theFxScheduler.RegisterEffect( effect ); + theFxScheduler.RegisterEffect(effect); - if ( effect2 ) - { + if (effect2) { // FIXME: real precache - theFxScheduler.RegisterEffect( effect2 ); + theFxScheduler.RegisterEffect(effect2); } // spawn chunk roughly in the bbox of the thing.. - for ( int i = 0; i < ct; i++ ) - { - for( int j = 0; j < 3; j++ ) - { + for (int i = 0; i < ct; i++) { + for (int j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - org[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + org[j] = (r * mins[j] + (1 - r) * maxs[j]); } // shoot effect away from center - VectorSubtract( org, mid, dir ); - VectorNormalize( dir ); + VectorSubtract(org, mid, dir); + VectorNormalize(dir); - if ( effect2 && ( rand() & 1 )) - { - theFxScheduler.PlayEffect( effect2, org, dir ); - } - else - { - theFxScheduler.PlayEffect( effect, org, dir ); + if (effect2 && (rand() & 1)) { + theFxScheduler.PlayEffect(effect2, org, dir); + } else { + theFxScheduler.PlayEffect(effect, org, dir); } } } @@ -399,126 +387,115 @@ Fun chunk spewer ------------------------- */ -void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale ) -{ - localEntity_t *le; - refEntity_t *re; - vec3_t dir; - int i, j, k; - int chunkModel = 0; - leBounceSound_t bounce = LEBS_NONE; - float r, speedMod = 1.0f; - qboolean chunk = qfalse; - - if ( chunkType == MAT_NONE ) - { +void CG_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale) { + localEntity_t *le; + refEntity_t *re; + vec3_t dir; + int i, j, k; + int chunkModel = 0; + leBounceSound_t bounce = LEBS_NONE; + float r, speedMod = 1.0f; + qboolean chunk = qfalse; + + if (chunkType == MAT_NONE) { // Well, we should do nothing return; } - // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with effects instead of models - switch( chunkType ) - { + // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with + // effects instead of models + switch (chunkType) { case MAT_GLASS: - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); return; break; case MAT_GRATE1: - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.grateSound ); + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.grateSound); return; break; - case MAT_ELECTRICAL:// (sparks) - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound (va("sound/ambience/spark%d.wav", Q_irand(1, 6))) ); + case MAT_ELECTRICAL: // (sparks) + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgi_S_RegisterSound(va("sound/ambience/spark%d.wav", Q_irand(1, 6)))); return; break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: - case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.rockBreakSound ); + case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.rockBreakSound); bounce = LEBS_ROCK; speedMod = 0.5f; // rock blows up less break; case MAT_GLASS_METAL: - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); // FIXME: should probably have a custom sound + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); // FIXME: should probably have a custom sound bounce = LEBS_METAL; break; case MAT_CRATE1: case MAT_CRATE2: - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0,1)] ); + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0, 1)]); break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: - case MAT_ELEC_METAL:// FIXME: maybe have its own sound? - cgi_S_StartSound( NULL, owner, CHAN_BODY, cgs.media.chunkSound ); + case MAT_ELEC_METAL: // FIXME: maybe have its own sound? + cgi_S_StartSound(NULL, owner, CHAN_BODY, cgs.media.chunkSound); bounce = LEBS_METAL; speedMod = 0.8f; // metal blows up a bit more break; case MAT_ROPE: -// cgi_S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound( "" )); FIXME: needs a sound + // cgi_S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound( "" )); FIXME: needs a sound return; default: break; } - if ( baseScale <= 0.0f ) - { + if (baseScale <= 0.0f) { baseScale = 1.0f; } // Chunks - for( i = 0; i < numChunks; i++ ) - { - if ( customChunk > 0 ) - { + for (i = 0; i < numChunks; i++) { + if (customChunk > 0) { // Try to use a custom chunk. - if ( cgs.model_draw[customChunk] ) - { + if (cgs.model_draw[customChunk]) { chunk = qtrue; chunkModel = cgs.model_draw[customChunk]; } } - if ( !chunk ) - { + if (!chunk) { // No custom chunk. Pick a random chunk type at run-time so we don't get the same chunks - switch( chunkType ) - { - case MAT_METAL2: //bluegrey + switch (chunkType) { + case MAT_METAL2: // bluegrey chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; break; - case MAT_GREY_STONE://gray + case MAT_GREY_STONE: // gray chunkModel = cgs.media.chunkModels[CHUNK_ROCK1][Q_irand(0, 3)]; break; - case MAT_LT_STONE: //tan + case MAT_LT_STONE: // tan chunkModel = cgs.media.chunkModels[CHUNK_ROCK2][Q_irand(0, 3)]; break; - case MAT_DRK_STONE://brown + case MAT_DRK_STONE: // brown chunkModel = cgs.media.chunkModels[CHUNK_ROCK3][Q_irand(0, 3)]; break; case MAT_WHITE_METAL: chunkModel = cgs.media.chunkModels[CHUNK_WHITE_METAL][Q_irand(0, 3)]; break; - case MAT_CRATE1://yellow multi-colored crate chunks + case MAT_CRATE1: // yellow multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE1][Q_irand(0, 3)]; break; - case MAT_CRATE2://red multi-colored crate chunks + case MAT_CRATE2: // red multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE2][Q_irand(0, 3)]; break; case MAT_ELEC_METAL: case MAT_GLASS_METAL: - case MAT_METAL://grey + case MAT_METAL: // grey chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; break; case MAT_METAL3: - if ( rand() & 1 ) - { + if (rand() & 1) { chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; - } - else - { + } else { chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; } break; @@ -528,8 +505,7 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins } // It wouldn't look good to throw a bunch of RGB axis models...so make sure we have something to work with. - if ( chunkModel ) - { + if (chunkModel) { le = CG_AllocLocalEntity(); re = &le->refEntity; @@ -538,26 +514,25 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins le->endTime = cg.time + 1300 + Q_flrand(0.0f, 1.0f) * 900; // spawn chunk roughly in the bbox of the thing...bias towards center in case thing blowing up doesn't complete fill its bbox. - for( j = 0; j < 3; j++ ) - { + for (j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - re->origin[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + re->origin[j] = (r * mins[j] + (1 - r) * maxs[j]); } - VectorCopy( re->origin, le->pos.trBase ); + VectorCopy(re->origin, le->pos.trBase); // Move out from center of thing, otherwise you can end up things moving across the brush in an undesirable direction. Visually looks wrong - VectorSubtract( re->origin, origin, dir ); - VectorNormalize( dir ); - VectorScale( dir, Q_flrand( speed * 0.5f, speed * 1.25f ) * speedMod, le->pos.trDelta ); + VectorSubtract(re->origin, origin, dir); + VectorNormalize(dir); + VectorScale(dir, Q_flrand(speed * 0.5f, speed * 1.25f) * speedMod, le->pos.trDelta); // Angular Velocity - VectorSet( le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360 ); + VectorSet(le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360); le->angles.trDelta[0] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[1] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[2] = 0; // don't do roll - VectorScale( le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta ); + VectorScale(le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta); le->pos.trType = TR_GRAVITY; le->angles.trType = TR_LINEAR; @@ -565,55 +540,50 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins le->bounceFactor = 0.2f + Q_flrand(0.0f, 1.0f) * 0.2f; le->leFlags |= LEF_TUMBLE; le->ownerGentNum = owner; - le->leBounceSoundType = bounce; + le->leBounceSoundType = bounce; // Make sure that we have the desired start size set - le->radius = Q_flrand( baseScale * 0.75f, baseScale * 1.25f ); + le->radius = Q_flrand(baseScale * 0.75f, baseScale * 1.25f); re->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, re->axis ); // could do an angles to axis, but this is cheaper and works ok - for( k = 0; k < 3; k++ ) - { - VectorScale( re->axis[k], le->radius, re->axis[k] ); + AxisCopy(axisDefault, re->axis); // could do an angles to axis, but this is cheaper and works ok + for (k = 0; k < 3; k++) { + VectorScale(re->axis[k], le->radius, re->axis[k]); } } } } -void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int radius ) -{ - localEntity_t *le; - refEntity_t *re; +void CG_TestLine(vec3_t start, vec3_t end, int time, unsigned int color, int radius) { + localEntity_t *le; + refEntity_t *re; le = CG_AllocLocalEntity(); le->leType = LE_LINE; le->startTime = cg.time; le->endTime = cg.time + time; - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + le->lifeRate = 1.0 / (le->endTime - le->startTime); re = &le->refEntity; - VectorCopy( start, re->origin ); - VectorCopy( end, re->oldorigin); + VectorCopy(start, re->origin); + VectorCopy(end, re->oldorigin); re->shaderTime = cg.time / 1000.0f; re->reType = RT_LINE; - re->radius = 0.5*radius; - re->customShader = cgs.media.whiteShader; //trap_R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); + re->radius = 0.5 * radius; + re->customShader = cgs.media.whiteShader; // trap_R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); re->shaderTexCoord[0] = re->shaderTexCoord[1] = 1.0f; - if (color==0) - { + if (color == 0) { re->shaderRGBA[0] = re->shaderRGBA[1] = re->shaderRGBA[2] = re->shaderRGBA[3] = 0xff; - } - else - { + } else { re->shaderRGBA[0] = color & 0xff; color >>= 8; re->shaderRGBA[1] = color & 0xff; color >>= 8; re->shaderRGBA[2] = color & 0xff; -// color >>= 8; -// re->shaderRGBA[3] = color & 0xff; + // color >>= 8; + // re->shaderRGBA[3] = color & 0xff; re->shaderRGBA[3] = 0xff; } @@ -626,303 +596,259 @@ void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int ra // //---------------------------- -// Since we have shared verts when we tesselate the glass sheet, it helps to have a +// Since we have shared verts when we tesselate the glass sheet, it helps to have a // random offset table set up up front...so that we can have more random looking breaks. -static float offX[20][20], - offZ[20][20]; +static float offX[20][20], offZ[20][20]; -static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], bool stick, int time, vec3_t dmgDir ) -{ - float bounce; - vec3_t rotDelta; - vec3_t vel, accel; - vec3_t rgb1; +static void CG_DoGlassQuad(vec3_t p[4], vec2_t uv[4], bool stick, int time, vec3_t dmgDir) { + float bounce; + vec3_t rotDelta; + vec3_t vel, accel; + vec3_t rgb1; - VectorSet( vel, Q_flrand(-1.0f, 1.0f) * 12, Q_flrand(-1.0f, 1.0f) * 12, -1 ); + VectorSet(vel, Q_flrand(-1.0f, 1.0f) * 12, Q_flrand(-1.0f, 1.0f) * 12, -1); - if ( !stick ) - { + if (!stick) { // We aren't a motion delayed chunk, so let us move quickly - VectorMA( vel, 0.3f, dmgDir, vel ); + VectorMA(vel, 0.3f, dmgDir, vel); } // Set up acceleration due to gravity, 800 is standard QuakeIII gravity, so let's use something close - VectorSet( accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f ) ); + VectorSet(accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f)); - VectorSet( rgb1, 1.0f, 1.0f, 1.0f ); + VectorSet(rgb1, 1.0f, 1.0f, 1.0f); // Being glass, we don't want to bounce much bounce = Q_flrand(0.0f, 1.0f) * 0.2f + 0.15f; // Set up our random rotate, we only do PITCH and YAW, not ROLL. This is something like degrees per second - VectorSet( rotDelta, Q_flrand(-1.0f, 1.0f) * 40.0f, Q_flrand(-1.0f, 1.0f) * 40.0f, 0.0f ); - - CPoly *pol = FX_AddPoly(p, uv, 4, // verts, ST, vertCount - vel, accel, // motion - 0.15f, 0.0f, 85.0f, // alpha start, alpha end, alpha parm ( begin alpha fade when 85% of life is complete ) - rgb1, rgb1, 0.0f, // rgb start, rgb end, rgb parm ( not used ) - rotDelta, bounce, time, // rotation amount, bounce, and time to delay motion for ( zero if no delay ); - 3500 + Q_flrand(0.0f, 1.0f) * 1000, // life - cgi_R_RegisterShader( "gfx/misc/test_crackle" ), - FX_APPLY_PHYSICS | FX_ALPHA_NONLINEAR | FX_USE_ALPHA ); - - if ( Q_flrand(0.0f, 1.0f) > 0.95f && pol ) - { - pol->AddFlags( FX_IMPACT_RUNS_FX | FX_KILL_ON_IMPACT ); - pol->SetImpactFxID( theFxScheduler.RegisterEffect( "glass_impact" )); + VectorSet(rotDelta, Q_flrand(-1.0f, 1.0f) * 40.0f, Q_flrand(-1.0f, 1.0f) * 40.0f, 0.0f); + + CPoly *pol = FX_AddPoly(p, uv, 4, // verts, ST, vertCount + vel, accel, // motion + 0.15f, 0.0f, 85.0f, // alpha start, alpha end, alpha parm ( begin alpha fade when 85% of life is complete ) + rgb1, rgb1, 0.0f, // rgb start, rgb end, rgb parm ( not used ) + rotDelta, bounce, time, // rotation amount, bounce, and time to delay motion for ( zero if no delay ); + 3500 + Q_flrand(0.0f, 1.0f) * 1000, // life + cgi_R_RegisterShader("gfx/misc/test_crackle"), FX_APPLY_PHYSICS | FX_ALPHA_NONLINEAR | FX_USE_ALPHA); + + if (Q_flrand(0.0f, 1.0f) > 0.95f && pol) { + pol->AddFlags(FX_IMPACT_RUNS_FX | FX_KILL_ON_IMPACT); + pol->SetImpactFxID(theFxScheduler.RegisterEffect("glass_impact")); } } -static void CG_CalcBiLerp( vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4] ) -{ - vec3_t temp; +static void CG_CalcBiLerp(vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4]) { + vec3_t temp; // Nasty crap - VectorScale( verts[0], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[1], subVerts[0] ); - VectorScale( subVerts[0], 1.0f - uv[0][1], temp ); - VectorScale( verts[3], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[2], subVerts[0] ); - VectorMA( temp, uv[0][1], subVerts[0], subVerts[0] ); - - VectorScale( verts[0], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[1], subVerts[1] ); - VectorScale( subVerts[1], 1.0f - uv[1][1], temp ); - VectorScale( verts[3], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[2], subVerts[1] ); - VectorMA( temp, uv[1][1], subVerts[1], subVerts[1] ); - - VectorScale( verts[0], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[1], subVerts[2] ); - VectorScale( subVerts[2], 1.0f - uv[2][1], temp ); - VectorScale( verts[3], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[2], subVerts[2] ); - VectorMA( temp, uv[2][1], subVerts[2], subVerts[2] ); - - VectorScale( verts[0], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[1], subVerts[3] ); - VectorScale( subVerts[3], 1.0f - uv[3][1], temp ); - VectorScale( verts[3], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[2], subVerts[3] ); - VectorMA( temp, uv[3][1], subVerts[3], subVerts[3] ); + VectorScale(verts[0], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[1], subVerts[0]); + VectorScale(subVerts[0], 1.0f - uv[0][1], temp); + VectorScale(verts[3], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[2], subVerts[0]); + VectorMA(temp, uv[0][1], subVerts[0], subVerts[0]); + + VectorScale(verts[0], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[1], subVerts[1]); + VectorScale(subVerts[1], 1.0f - uv[1][1], temp); + VectorScale(verts[3], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[2], subVerts[1]); + VectorMA(temp, uv[1][1], subVerts[1], subVerts[1]); + + VectorScale(verts[0], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[1], subVerts[2]); + VectorScale(subVerts[2], 1.0f - uv[2][1], temp); + VectorScale(verts[3], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[2], subVerts[2]); + VectorMA(temp, uv[2][1], subVerts[2], subVerts[2]); + + VectorScale(verts[0], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[1], subVerts[3]); + VectorScale(subVerts[3], 1.0f - uv[3][1], temp); + VectorScale(verts[3], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[2], subVerts[3]); + VectorMA(temp, uv[3][1], subVerts[3], subVerts[3]); } // bilinear -//f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. - - -static void CG_CalcHeightWidth( vec3_t verts[4], float *height, float *width ) -{ - vec3_t dir1, dir2, cross; - - VectorSubtract( verts[3], verts[0], dir1 ); // v - VectorSubtract( verts[1], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v +// f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. + +static void CG_CalcHeightWidth(vec3_t verts[4], float *height, float *width) { + vec3_t dir1, dir2, cross; + + VectorSubtract(verts[3], verts[0], dir1); // v + VectorSubtract(verts[1], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width += VectorNormalize(cross) / VectorNormalize(dir1); // v *width *= 0.5f; - VectorSubtract( verts[1], verts[0], dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[3], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v + VectorSubtract(verts[1], verts[0], dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[3], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height += VectorNormalize(cross) / VectorNormalize(dir1); // v *height *= 0.5f; } -//Consider a line in 3D with position vector "a" and direction vector "v" and -// let "p" be the position vector of an arbitrary point in 3D -//dist = len( crossprod(p-a,v) ) / len(v); +// Consider a line in 3D with position vector "a" and direction vector "v" and +// let "p" be the position vector of an arbitrary point in 3D +// dist = len( crossprod(p-a,v) ) / len(v); -void CG_InitGlass( void ) -{ +void CG_InitGlass(void) { int i, t; // Build a table first, so that we can do a more unpredictable crack scheme // do it once, up front to save a bit of time. - for ( i = 0; i < 20; i++ ) - { - for ( t = 0; t < 20; t++ ) - { + for (i = 0; i < 20; i++) { + for (t = 0; t < 20; t++) { offX[t][i] = Q_flrand(-1.0f, 1.0f) * 0.03f; offZ[i][t] = Q_flrand(-1.0f, 1.0f) * 0.03f; } } } -#define TIME_DECAY_SLOW 0.1f -#define TIME_DECAY_MED 0.04f -#define TIME_DECAY_FAST 0.009f +#define TIME_DECAY_SLOW 0.1f +#define TIME_DECAY_MED 0.04f +#define TIME_DECAY_FAST 0.009f -void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius ) -{ - int i, t; - int mxHeight, mxWidth; - float height, width; - float stepWidth, stepHeight; - float timeDecay; - float x, z; - float xx, zz; - int time = 0; - bool stick = true; - vec3_t subVerts[4]; - vec2_t biPoints[4]; +void CG_DoGlass(vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius) { + int i, t; + int mxHeight, mxWidth; + float height, width; + float stepWidth, stepHeight; + float timeDecay; + float x, z; + float xx, zz; + int time = 0; + bool stick = true; + vec3_t subVerts[4]; + vec2_t biPoints[4]; // To do a smarter tesselation, we should figure out the relative height and width of the brush face, // then use this to pick a lod value from 1-3 in each axis. This will give us 1-9 lod levels, which will // hopefully be sufficient. - CG_CalcHeightWidth( verts, &height, &width ); + CG_CalcHeightWidth(verts, &height, &width); - cgi_S_StartSound( dmgPt, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/glassbreak1.wav")); + cgi_S_StartSound(dmgPt, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/glassbreak1.wav")); // Pick "LOD" for height - if ( height < 100 ) - { + if (height < 100) { stepHeight = 0.2f; mxHeight = 5; timeDecay = TIME_DECAY_SLOW; } -/* else if ( height > 220 ) // was originally mxHeight = 20....but removing this whole section because it causes huge number of chunks...which is bad - { - stepHeight = 0.075f; - mxHeight = 15; - timeDecay = TIME_DECAY_FAST; - }*/ - else - { + /* else if ( height > 220 ) // was originally mxHeight = 20....but removing this whole section because it causes huge number of chunks...which is bad + { + stepHeight = 0.075f; + mxHeight = 15; + timeDecay = TIME_DECAY_FAST; + }*/ + else { stepHeight = 0.1f; mxHeight = 10; timeDecay = TIME_DECAY_MED; } // Pick "LOD" for width - if ( width < 100 ) - { + if (width < 100) { stepWidth = 0.2f; mxWidth = 5; - timeDecay = ( timeDecay + TIME_DECAY_SLOW ) * 0.5f; + timeDecay = (timeDecay + TIME_DECAY_SLOW) * 0.5f; } -/* else if ( width > 220 ) // don't do this because it causes too much chug with large glass panes...especially when more than one pane can be broken at a time - { - stepWidth = 0.075f; - mxWidth = 15; - timeDecay = ( timeDecay + TIME_DECAY_FAST ) * 0.5f; - }*/ - else - { + /* else if ( width > 220 ) // don't do this because it causes too much chug with large glass panes...especially when more than one pane can be broken at a + time + { + stepWidth = 0.075f; + mxWidth = 15; + timeDecay = ( timeDecay + TIME_DECAY_FAST ) * 0.5f; + }*/ + else { stepWidth = 0.1f; mxWidth = 10; - timeDecay = ( timeDecay + TIME_DECAY_MED ) * 0.5f; + timeDecay = (timeDecay + TIME_DECAY_MED) * 0.5f; } - for ( z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++ ) - { - for ( x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++ ) - { + for (z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++) { + for (x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++) { // This is nasty..we do this because we don't want to add a random offset on the edge of the glass brush // ...but we do in the center, otherwise the breaking scheme looks way too orderly - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i][t]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[0], xx, zz ); + VectorSet2(biPoints[0], xx, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i][t + 1]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t + 1][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[1], xx + stepWidth, zz ); + VectorSet2(biPoints[1], xx + stepWidth, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i + 1][t + 1]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t + 1][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[2], xx + stepWidth, zz + stepHeight); + VectorSet2(biPoints[2], xx + stepWidth, zz + stepHeight); - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i + 1][t]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[3], xx, zz + stepHeight ); + VectorSet2(biPoints[3], xx, zz + stepHeight); + + CG_CalcBiLerp(verts, subVerts, biPoints); + + float dif = DistanceSquared(subVerts[0], dmgPt) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; - CG_CalcBiLerp( verts, subVerts, biPoints ); - - float dif = DistanceSquared( subVerts[0], dmgPt ) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; - // If we decrease dif, we are increasing the impact area, making it more likely to blow out large holes dif -= dmgRadius * dmgRadius; - if ( dif > 1 ) - { + if (dif > 1) { stick = true; time = dif + Q_flrand(0.0f, 1.0f) * 200; - } - else - { + } else { stick = false; time = 0; } - CG_DoGlassQuad( subVerts, biPoints, stick, time, dmgDir ); + CG_DoGlassQuad(subVerts, biPoints, stick, time, dmgDir); } } } @@ -967,49 +893,44 @@ CG_Seeker } */ //------------------------------------------------------------------------------------------ -void CG_DrawTargetBeam( vec3_t start, vec3_t end, vec3_t norm, const char *beamFx, const char *impactFx ) -{ - int handle = 0; - vec3_t dir; - SEffectTemplate *temp; +void CG_DrawTargetBeam(vec3_t start, vec3_t end, vec3_t norm, const char *beamFx, const char *impactFx) { + int handle = 0; + vec3_t dir; + SEffectTemplate *temp; // overriding the effect, so give us a copy first - temp = theFxScheduler.GetEffectCopy( beamFx, &handle ); + temp = theFxScheduler.GetEffectCopy(beamFx, &handle); - VectorSubtract( start, end, dir ); - VectorNormalize( dir ); + VectorSubtract(start, end, dir); + VectorNormalize(dir); - if ( temp ) - { + if (temp) { // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "beam" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "beam"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( end[0], end[0] ); - prim->mOrigin2Y.SetRange( end[1], end[1] ); - prim->mOrigin2Z.SetRange( end[2], end[2] ); + prim->mOrigin2X.SetRange(end[0], end[0]); + prim->mOrigin2Y.SetRange(end[1], end[1]); + prim->mOrigin2Z.SetRange(end[2], end[2]); // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "glow" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "glow"); // glow is not required - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( end[0], end[0] ); - prim->mOrigin2Y.SetRange( end[1], end[1] ); - prim->mOrigin2Z.SetRange( end[2], end[2] ); + prim->mOrigin2X.SetRange(end[0], end[0]); + prim->mOrigin2Y.SetRange(end[1], end[1]); + prim->mOrigin2Z.SetRange(end[2], end[2]); } // play the modified effect - theFxScheduler.PlayEffect( handle, start, dir ); + theFxScheduler.PlayEffect(handle, start, dir); } } - if ( impactFx ) - { - theFxScheduler.PlayEffect( impactFx, end, norm ); + if (impactFx) { + theFxScheduler.PlayEffect(impactFx, end, norm); } } diff --git a/codeJK2/cgame/cg_ents.cpp b/codeJK2/cgame/cg_ents.cpp index 7fcb0c6f0d..20bac3e4c1 100644 --- a/codeJK2/cgame/cg_ents.cpp +++ b/codeJK2/cgame/cg_ents.cpp @@ -30,9 +30,9 @@ along with this program; if not, see . #include "FxScheduler.h" #include "../game/wp_saber.h" -extern void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles); -extern void CG_CheckSaberInWater( centity_t *cent, centity_t *scent, int modelIndex, vec3_t origin, vec3_t angles ); -extern void CG_ForcePushBlur( const vec3_t org ); +extern void CG_AddSaberBlade(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles); +extern void CG_CheckSaberInWater(centity_t *cent, centity_t *scent, int modelIndex, vec3_t origin, vec3_t angles); +extern void CG_ForcePushBlur(const vec3_t org); /* ====================== @@ -42,24 +42,21 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName ) { - int i; - orientation_t lerped; - +void CG_PositionEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName) { + int i; + orientation_t lerped; + // lerp the tag - cgi_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0f - parent->backlerp, tagName ); + cgi_R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0f - parent->backlerp, tagName); // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } // had to cast away the const to avoid compiler problems... - MatrixMultiply( lerped.axis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(lerped.axis, ((refEntity_t *)parent)->axis, entity->axis); entity->backlerp = parent->backlerp; } @@ -71,37 +68,31 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName, orientation_t *tagOrient ) { - int i; - orientation_t lerped; - vec3_t tempAxis[3]; +void CG_PositionRotatedEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName, orientation_t *tagOrient) { + int i; + orientation_t lerped; + vec3_t tempAxis[3]; // lerp the tag - cgi_R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0f - parent->backlerp, tagName ); + cgi_R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0f - parent->backlerp, tagName); - if ( tagOrient ) - { - VectorCopy( lerped.origin, tagOrient->origin ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorCopy( lerped.axis[i], tagOrient->axis[i] ); + if (tagOrient) { + VectorCopy(lerped.origin, tagOrient->origin); + for (i = 0; i < 3; i++) { + VectorCopy(lerped.axis[i], tagOrient->axis[i]); } } // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } - MatrixMultiply( entity->axis, lerped.axis, tempAxis ); - MatrixMultiply( tempAxis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(entity->axis, lerped.axis, tempAxis); + MatrixMultiply(tempAxis, ((refEntity_t *)parent)->axis, entity->axis); } - - /* ========================================================================== @@ -117,18 +108,18 @@ CG_SetEntitySoundPosition Also called by event processing code ====================== */ -vec3_t *CG_SetEntitySoundPosition( centity_t *cent ) { +vec3_t *CG_SetEntitySoundPosition(centity_t *cent) { static vec3_t v3Return; - if ( cent->currentState.solid == SOLID_BMODEL ) { - vec3_t origin; - float *v; + if (cent->currentState.solid == SOLID_BMODEL) { + vec3_t origin; + float *v; - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, origin ); - cgi_S_UpdateEntityPosition( cent->currentState.number, origin ); + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, origin); + cgi_S_UpdateEntityPosition(cent->currentState.number, origin); VectorCopy(origin, v3Return); } else { - cgi_S_UpdateEntityPosition( cent->currentState.number, cent->lerpOrigin ); + cgi_S_UpdateEntityPosition(cent->currentState.number, cent->lerpOrigin); VectorCopy(cent->lerpOrigin, v3Return); } @@ -142,90 +133,80 @@ CG_EntityEffects Add continuous entity effects, like local entity emission and lighting ================== */ -static void CG_EntityEffects( centity_t *cent ) { +static void CG_EntityEffects(centity_t *cent) { // update sound origins vec3_t v3Origin; - VectorCopy(*CG_SetEntitySoundPosition( cent ),v3Origin); + VectorCopy(*CG_SetEntitySoundPosition(cent), v3Origin); // add loop sound - if ( cent->currentState.loopSound ) - { - - sfxHandle_t sfx = ( cent->currentState.eType == ET_MOVER ) ? cent->currentState.loopSound : cgs.sound_precache[ cent->currentState.loopSound ]; + if (cent->currentState.loopSound) { - cgi_S_AddLoopingSound( cent->currentState.number, v3Origin/*cent->lerpOrigin*/, vec3_origin, sfx ); + sfxHandle_t sfx = (cent->currentState.eType == ET_MOVER) ? cent->currentState.loopSound : cgs.sound_precache[cent->currentState.loopSound]; + + cgi_S_AddLoopingSound(cent->currentState.number, v3Origin /*cent->lerpOrigin*/, vec3_origin, sfx); } // constant light glow - if ( cent->currentState.constantLight ) { - int cl; - float i, r, g, b; + if (cent->currentState.constantLight) { + int cl; + float i, r, g, b; cl = cent->currentState.constantLight; - r = (float) (cl & 0xFF) / 255.0; - g = (float) ((cl >> 8) & 0xFF) / 255.0; - b = (float) ((cl >> 16) & 0xFF) / 255.0; - i = (float) ((cl >> 24) & 0xFF) * 4.0; - cgi_R_AddLightToScene( cent->lerpOrigin, i, r, g, b ); + r = (float)(cl & 0xFF) / 255.0; + g = (float)((cl >> 8) & 0xFF) / 255.0; + b = (float)((cl >> 16) & 0xFF) / 255.0; + i = (float)((cl >> 24) & 0xFF) * 4.0; + cgi_R_AddLightToScene(cent->lerpOrigin, i, r, g, b); } } -void CG_AddRefEntWithTransportEffect ( centity_t *cent, refEntity_t *ent ) -{ +void CG_AddRefEntWithTransportEffect(centity_t *cent, refEntity_t *ent) { // We are a normal thing.... - cgi_R_AddRefEntityToScene (ent); + cgi_R_AddRefEntityToScene(ent); - if ( ent->renderfx & RF_PULSATE && cent->gent->owner && cent->gent->owner->health && - !cent->gent->owner->s.number && cent->gent->owner->client && //only for player - cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && - cent->currentState.saberActive == qfalse ) - { + if (ent->renderfx & RF_PULSATE && cent->gent->owner && cent->gent->owner->health && !cent->gent->owner->s.number && + cent->gent->owner->client && // only for player + cent->gent->owner->client->ps.saberEntityState == SES_RETURNING && cent->currentState.saberActive == qfalse) { // if we are the saber and we have been dropped, do a glow so it can be spotted easier - float wv; - vec3_t org; + float wv; + vec3_t org; - ent->customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); + ent->customShader = cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); ent->renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.003f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.003f) * 0.08f + 0.1f; ent->shaderRGBA[0] = wv * 255; ent->shaderRGBA[1] = wv * 255; ent->shaderRGBA[2] = wv * 0; - cgi_R_AddRefEntityToScene (ent); + cgi_R_AddRefEntityToScene(ent); - for ( int i = -4; i < 10; i += 1 ) - { - VectorMA( ent->origin, -i, ent->axis[2], org ); + for (int i = -4; i < 10; i += 1) { + VectorMA(ent->origin, -i, ent->axis[2], org); - FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + FX_AddSprite(org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000); } - if ( cent->gent->owner->s.weapon == WP_SABER ) - {//he's still controlling me - FX_AddSprite( cent->gent->owner->client->renderInfo.handRPoint, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + if (cent->gent->owner->s.weapon == WP_SABER) { // he's still controlling me + FX_AddSprite(cent->gent->owner->client->renderInfo.handRPoint, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, + 0x08000000); } } } - /* Ghoul2 Insert Start */ // Copy the ghoul2 data into the ref ent correctly -void CG_SetGhoul2Info( refEntity_t *ent, centity_t *cent) -{ +void CG_SetGhoul2Info(refEntity_t *ent, centity_t *cent) { ent->ghoul2 = ¢->gent->ghoul2; - VectorCopy( cent->currentState.modelScale, ent->modelScale); + VectorCopy(cent->currentState.modelScale, ent->modelScale); ent->radius = cent->currentState.radius; - VectorCopy (cent->lerpAngles, ent->angles); + VectorCopy(cent->lerpAngles, ent->angles); } - - // create 8 new points on screen around a model so we can see it's bounding box -void CG_CreateBBRefEnts(entityState_t *s1, vec3_t origin ) -{ -#if 0 //loadsavecrash _DEBUG +void CG_CreateBBRefEnts(entityState_t *s1, vec3_t origin) { +#if 0 // loadsavecrash _DEBUG refEntity_t point[8]; int i; vec3_t angles = {0,0,0}; @@ -289,57 +270,54 @@ void CG_CreateBBRefEnts(entityState_t *s1, vec3_t origin ) } // write in the axis and stuff -void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) -{ - // extract the wraith ID from the bolt info +void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) { + // extract the wraith ID from the bolt info int modelNum = cent->currentState.boltInfo >> MODEL_SHIFT; modelNum &= MODEL_AND; - int boltNum = cent->currentState.boltInfo >> BOLT_SHIFT; + int boltNum = cent->currentState.boltInfo >> BOLT_SHIFT; boltNum &= BOLT_AND; - int entNum = cent->currentState.boltInfo >> ENTITY_SHIFT; + int entNum = cent->currentState.boltInfo >> ENTITY_SHIFT; entNum &= ENTITY_AND; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - // go away and get me the bolt position for this frame please - gi.G2API_GetBoltMatrix(cent->gent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, cg.time, cgs.model_draw, cent->currentState.modelScale); + // go away and get me the bolt position for this frame please + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, + cg.time, cgs.model_draw, cent->currentState.modelScale); // set up the axis and origin we need for the actual effect spawning - ent->origin[0] = boltMatrix.matrix[0][3]; - ent->origin[1] = boltMatrix.matrix[1][3]; - ent->origin[2] = boltMatrix.matrix[2][3]; + ent->origin[0] = boltMatrix.matrix[0][3]; + ent->origin[1] = boltMatrix.matrix[1][3]; + ent->origin[2] = boltMatrix.matrix[2][3]; - ent->axis[0][0] = boltMatrix.matrix[0][0]; - ent->axis[0][1] = boltMatrix.matrix[1][0]; - ent->axis[0][2] = boltMatrix.matrix[2][0]; + ent->axis[0][0] = boltMatrix.matrix[0][0]; + ent->axis[0][1] = boltMatrix.matrix[1][0]; + ent->axis[0][2] = boltMatrix.matrix[2][0]; - ent->axis[1][0] = boltMatrix.matrix[0][1]; - ent->axis[1][1] = boltMatrix.matrix[1][1]; - ent->axis[1][2] = boltMatrix.matrix[2][1]; + ent->axis[1][0] = boltMatrix.matrix[0][1]; + ent->axis[1][1] = boltMatrix.matrix[1][1]; + ent->axis[1][2] = boltMatrix.matrix[2][1]; - ent->axis[2][0] = boltMatrix.matrix[0][2]; - ent->axis[2][1] = boltMatrix.matrix[1][2]; - ent->axis[2][2] = boltMatrix.matrix[2][2]; + ent->axis[2][0] = boltMatrix.matrix[0][2]; + ent->axis[2][1] = boltMatrix.matrix[1][2]; + ent->axis[2][2] = boltMatrix.matrix[2][2]; } -void ScaleModelAxis(refEntity_t *ent) +void ScaleModelAxis(refEntity_t *ent) -{ // scale the model should we need to - if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) - { - VectorScale( ent->axis[0], ent->modelScale[0] , ent->axis[0] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) - { - VectorScale( ent->axis[1], ent->modelScale[1] , ent->axis[1] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) - { - VectorScale( ent->axis[2], ent->modelScale[2] , ent->axis[2] ); - ent->nonNormalizedAxes = qtrue; - } +{ // scale the model should we need to + if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) { + VectorScale(ent->axis[0], ent->modelScale[0], ent->axis[0]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) { + VectorScale(ent->axis[1], ent->modelScale[1], ent->axis[1]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) { + VectorScale(ent->axis[2], ent->modelScale[2], ent->axis[2]); + ent->nonNormalizedAxes = qtrue; + } } /* Ghoul2 Insert End @@ -350,267 +328,215 @@ Ghoul2 Insert End CG_General ================== */ -extern int CG_SaberHumSoundForEnt( gentity_t *gent ); -static void CG_General( centity_t *cent ) -{ - refEntity_t ent; - entityState_t *s1; +extern int CG_SaberHumSoundForEnt(gentity_t *gent); +static void CG_General(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // if set to invisible, skip - if (!s1->modelindex && !cent->gent->ghoul2.IsValid() ) { + if (!s1->modelindex && !cent->gent->ghoul2.IsValid()) { return; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if ( s1->eFlags & EF_NODRAW ) - { + if (s1->eFlags & EF_NODRAW) { // If you don't like it doing NODRAW, then don't set the flag return; } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); // set frame - if ( s1->eFlags & EF_SHADER_ANIM ) - { + if (s1->eFlags & EF_SHADER_ANIM) { // Deliberately setting it up so that shader anim will completely override any kind of model animation frame setting. - ent.renderfx|=RF_SETANIMINDEX; + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - } - else if ( s1->eFlags & EF_ANIM_ONCE ) - { - //s1->frame++; - //ent.frame = s1->frame; + } else if (s1->eFlags & EF_ANIM_ONCE) { + // s1->frame++; + // ent.frame = s1->frame; ent.frame = cent->gent->s.frame; - ent.renderfx|=RF_CAP_FRAMES; - } - else if ( s1->eFlags & EF_ANIM_ALLFAST ) - { + ent.renderfx |= RF_CAP_FRAMES; + } else if (s1->eFlags & EF_ANIM_ALLFAST) { ent.frame = (cg.time / 100); - ent.renderfx|=RF_WRAP_FRAMES; - } - else - { + ent.renderfx |= RF_WRAP_FRAMES; + } else { ent.frame = s1->frame; } ent.oldframe = ent.frame; ent.backlerp = 0; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); ent.hModel = cgs.model_draw[s1->modelindex]; - if ( s1->eFlags & EF_AUTO_SIZE && cent->gent ) - { - cgi_R_ModelBounds( ent.hModel, cent->gent->mins, cent->gent->maxs ); - //Only do this once + if (s1->eFlags & EF_AUTO_SIZE && cent->gent) { + cgi_R_ModelBounds(ent.hModel, cent->gent->mins, cent->gent->maxs); + // Only do this once cent->gent->s.eFlags &= ~EF_AUTO_SIZE; } // player model - if (s1->number == cg.snap->ps.clientNum) - { - ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors + if (s1->number == cg.snap->ps.clientNum) { + ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // are we bolted to a Ghoul2 model? - if (s1->boltInfo) - { + if (s1->boltInfo) { G2_BoltToGhoul2Model(cent, &ent); - } - else - { + } else { //------------------------------------------------------- // Start of chair //------------------------------------------------------- - if ( cent->gent->s.weapon == WP_EMPLACED_GUN || ( cent->gent->activator && cent->gent->activator->owner && - cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON )) - { - vec3_t temp; + if (cent->gent->s.weapon == WP_EMPLACED_GUN || + (cent->gent->activator && cent->gent->activator->owner && cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON)) { + vec3_t temp; - if ( cent->gent->health <= 0 && cent->gent->e_ThinkFunc == thinkF_NULL ) - { - ent.customShader = cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg" ); + if (cent->gent->health <= 0 && cent->gent->e_ThinkFunc == thinkF_NULL) { + ent.customShader = cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg"); - VectorSet( temp, 0, 0, 1 ); + VectorSet(temp, 0, 0, 1); // add a big scorch mark under the gun - CG_ImpactMark( cgs.media.scavMarkShader, cent->lerpOrigin, temp, - 0, 1,1,1, 1.0f, qfalse, 92, qtrue ); - CG_ImpactMark( cgs.media.scavMarkShader, cent->lerpOrigin, temp, - 90, 1,1,1, 1.0f, qfalse, 48, qtrue ); - } - else - { - VectorSet( temp, 0, 0, 1 ); + CG_ImpactMark(cgs.media.scavMarkShader, cent->lerpOrigin, temp, 0, 1, 1, 1, 1.0f, qfalse, 92, qtrue); + CG_ImpactMark(cgs.media.scavMarkShader, cent->lerpOrigin, temp, 90, 1, 1, 1, 1.0f, qfalse, 48, qtrue); + } else { + VectorSet(temp, 0, 0, 1); - if ( !( cent->gent->svFlags & SVF_INACTIVE )) - { - ent.customShader = cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_on" ); + if (!(cent->gent->svFlags & SVF_INACTIVE)) { + ent.customShader = cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_on"); } // shadow under the gun - CG_ImpactMark( cgs.media.shadowMarkShader, cent->lerpOrigin, temp, - 0, 1,1,1, 1.0f, qfalse, 32, qtrue ); + CG_ImpactMark(cgs.media.shadowMarkShader, cent->lerpOrigin, temp, 0, 1, 1, 1, 1.0f, qfalse, 32, qtrue); } } - if ( cent->gent->activator && cent->gent->activator->owner && - cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON && - cent->gent->activator->owner->s.number == cent->currentState.number ) // gun number must be same as current entities number + if (cent->gent->activator && cent->gent->activator->owner && cent->gent->activator->s.eFlags & EF_LOCKED_TO_WEAPON && + cent->gent->activator->owner->s.number == cent->currentState.number) // gun number must be same as current entities number { centity_t *cc = &cg_entities[cent->gent->activator->s.number]; -const weaponData_t *wData = NULL; + const weaponData_t *wData = NULL; - if ( cc->currentState.weapon ) - { + if (cc->currentState.weapon) { wData = &weaponData[cc->currentState.weapon]; } - if ( !( cc->currentState.eFlags & EF_FIRING ) && !( cc->currentState.eFlags & EF_ALT_FIRING )) - { + if (!(cc->currentState.eFlags & EF_FIRING) && !(cc->currentState.eFlags & EF_ALT_FIRING)) { // not animating..pausing was leaving the barrels in a bad state - gi.G2API_PauseBoneAnim( ¢->gent->ghoul2[cent->gent->playerModel], "model_root", cg.time ); + gi.G2API_PauseBoneAnim(¢->gent->ghoul2[cent->gent->playerModel], "model_root", cg.time); -// gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, -// 0, 0, BONE_ANIM_OVERRIDE, 1.0f, cg.time ); + // gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, + // 0, 0, BONE_ANIM_OVERRIDE, 1.0f, cg.time ); } // get alternating muzzle end bolts - int bolt = cent->gent->handRBolt; - mdxaBone_t boltMatrix; + int bolt = cent->gent->handRBolt; + mdxaBone_t boltMatrix; - if ( !cc->gent->fxID ) - { + if (!cc->gent->fxID) { bolt = cent->gent->handLBolt; } - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, 0, bolt, - &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, 0, bolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // store the muzzle point and direction so that we can fire in the right direction - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cc->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, cc->gent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cc->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, cc->gent->client->renderInfo.muzzleDir); cc->gent->client->renderInfo.mPCalcTime = cg.time; // HACK: adding in muzzle flashes - if ( cc->muzzleFlashTime > 0 && wData ) - { + if (cc->muzzleFlashTime > 0 && wData) { const char *effect = NULL; cc->muzzleFlashTime = 0; // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cc->currentState.eFlags & EF_ALT_FIRING ) - { + if (cc->currentState.eFlags & EF_ALT_FIRING) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if ( cc->currentState.eFlags & EF_FIRING || cc->currentState.eFlags & EF_ALT_FIRING ) - { - gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, - 0, 3, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); - - if ( effect ) - { + if (cc->currentState.eFlags & EF_FIRING || cc->currentState.eFlags & EF_ALT_FIRING) { + gi.G2API_SetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, 0, 3, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, + cg.time, -1, -1); + + if (effect) { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cc->gent->client->renderInfo.muzzlePoint, - cc->gent->client->renderInfo.muzzleDir ); + theFxScheduler.PlayEffect(effect, cc->gent->client->renderInfo.muzzlePoint, cc->gent->client->renderInfo.muzzleDir); } } } - VectorCopy( cent->gent->s.apos.trBase, cent->lerpAngles ); + VectorCopy(cent->gent->s.apos.trBase, cent->lerpAngles); } //------------------------------------------------------- // End of chair //------------------------------------------------------- - AnglesToAxis( cent->lerpAngles, ent.axis ); + AnglesToAxis(cent->lerpAngles, ent.axis); } ScaleModelAxis(&ent); - if (cent->gent->ghoul2.size()) - { - if ( s1->weapon == WP_SABER && cent->gent && cent->gent->owner && cent->gent->owner->inuse ) - {//flying lightsaber - //FIXME: better way to tell what it is would be nice - if ( cent->gent->classname && !Q_stricmp( "limb", cent->gent->classname ) ) - {//limb, just add blade - if ( cent->gent->owner->client ) - { - if ( cent->gent->owner->client->ps.saberLength > 0 ) - { - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], NULL, ent.renderfx, - cent->gent->weaponModel, cent->lerpOrigin, cent->lerpAngles ); - } - else if ( cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER ) - { - CG_CheckSaberInWater( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], cent->gent->weaponModel, - cent->lerpOrigin, cent->lerpAngles ); + if (cent->gent->ghoul2.size()) { + if (s1->weapon == WP_SABER && cent->gent && cent->gent->owner && cent->gent->owner->inuse) { // flying lightsaber + // FIXME: better way to tell what it is would be nice + if (cent->gent->classname && !Q_stricmp("limb", cent->gent->classname)) { // limb, just add blade + if (cent->gent->owner->client) { + if (cent->gent->owner->client->ps.saberLength > 0) { + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], NULL, ent.renderfx, + cent->gent->weaponModel, cent->lerpOrigin, cent->lerpAngles); + } else if (cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER) { + CG_CheckSaberInWater(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], cent->gent->weaponModel, + cent->lerpOrigin, cent->lerpAngles); } } - } - else - {//thrown saber - //light? sound? - if ( cent->gent->owner->client && cg_entities[cent->currentState.otherEntityNum].currentState.saberActive ) - {//saber is in-flight and active, play a sound on it - if ( cent->gent->owner->client->ps.saberEntityState == SES_RETURNING ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, vec3_origin, - CG_SaberHumSoundForEnt( cent->gent->owner ) ); - } - else - { + } else { // thrown saber + // light? sound? + if (cent->gent->owner->client && + cg_entities[cent->currentState.otherEntityNum].currentState.saberActive) { // saber is in-flight and active, play a sound on it + if (cent->gent->owner->client->ps.saberEntityState == SES_RETURNING) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, CG_SaberHumSoundForEnt(cent->gent->owner)); + } else { int spinSound; - switch ( cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW] ) - { + switch (cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW]) { case FORCE_LEVEL_1: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; case FORCE_LEVEL_2: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; default: case FORCE_LEVEL_3: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; } - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, - vec3_origin, spinSound ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, spinSound); /* if ( cg_weapons[WP_SABER].missileSound ) { @@ -619,62 +545,44 @@ const weaponData_t *wData = NULL; */ } } - if ( cent->gent->owner->client ) - { - if ( cent->gent->owner->client->ps.saberLength > 0 ) - {//only add the blade if it's on - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], NULL, ent.renderfx, - 0, cent->lerpOrigin, cent->lerpAngles ); - } - else if ( cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER ) - { - CG_CheckSaberInWater( &cg_entities[cent->gent->owner->s.number], - &cg_entities[cent->gent->s.number], 0, cent->lerpOrigin, - cent->lerpAngles ); + if (cent->gent->owner->client) { + if (cent->gent->owner->client->ps.saberLength > 0) { // only add the blade if it's on + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], NULL, ent.renderfx, 0, cent->lerpOrigin, + cent->lerpAngles); + } else if (cent->gent->owner->client->ps.saberEventFlags & SEF_INWATER) { + CG_CheckSaberInWater(&cg_entities[cent->gent->owner->s.number], &cg_entities[cent->gent->s.number], 0, cent->lerpOrigin, + cent->lerpAngles); } } - if ( cent->gent->owner->health ) - { - //make sure we can always be seen + if (cent->gent->owner->health) { + // make sure we can always be seen ent.renderfx |= RF_PULSATE; } } } - } - else - { - if ( s1->weapon == WP_SABER && cent->gent && cent->gent->owner ) - {//flying lightsaber - //light? sound? - if ( cent->gent->owner->client && cent->currentState.saberActive ) - {//saber is in-flight and active, play a sound on it - if ( cent->gent->owner->client->ps.saberEntityState == SES_RETURNING ) - { - if ( cg_weapons[WP_SABER].firingSound ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, vec3_origin, cg_weapons[WP_SABER].firingSound ); + } else { + if (s1->weapon == WP_SABER && cent->gent && cent->gent->owner) { // flying lightsaber + // light? sound? + if (cent->gent->owner->client && cent->currentState.saberActive) { // saber is in-flight and active, play a sound on it + if (cent->gent->owner->client->ps.saberEntityState == SES_RETURNING) { + if (cg_weapons[WP_SABER].firingSound) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, cg_weapons[WP_SABER].firingSound); } - } - else - { + } else { int spinSound; - switch ( cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW] ) - { + switch (cent->gent->owner->client->ps.forcePowerLevel[FP_SABERTHROW]) { case FORCE_LEVEL_1: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; case FORCE_LEVEL_2: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; default: case FORCE_LEVEL_3: - spinSound = cgi_S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + spinSound = cgi_S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; } - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, - vec3_origin, spinSound ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, spinSound); /* if ( cg_weapons[WP_SABER].missileSound ) { @@ -683,142 +591,126 @@ const weaponData_t *wData = NULL; */ } } - CG_AddSaberBlade( &cg_entities[cent->gent->owner->s.number], - NULL, &ent, ent.renderfx, 0, NULL, NULL ); + CG_AddSaberBlade(&cg_entities[cent->gent->owner->s.number], NULL, &ent, ent.renderfx, 0, NULL, NULL); - if ( cent->gent->owner->health ) - { - //make sure we can always be seen + if (cent->gent->owner->health) { + // make sure we can always be seen ent.renderfx |= RF_PULSATE; } } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if ( cent->gent && cent->gent->forcePushTime > cg.time ) - {//FIXME: if I'm a rather large model, this will look kind of stupid... - CG_ForcePushBlur( cent->lerpOrigin ); + if (cent->gent && cent->gent->forcePushTime > cg.time) { // FIXME: if I'm a rather large model, this will look kind of stupid... + CG_ForcePushBlur(cent->lerpOrigin); } - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); - if ( cent->gent->health <= 0 && cent->gent->s.weapon == WP_EMPLACED_GUN && cent->gent->e_ThinkFunc ) - { + if (cent->gent->health <= 0 && cent->gent->s.weapon == WP_EMPLACED_GUN && cent->gent->e_ThinkFunc) { // make the gun pulse red to warn about it exploding - float val = (1.0f - (float)(cent->gent->nextthink - cg.time) / 3200.0f ) * 0.3f; + float val = (1.0f - (float)(cent->gent->nextthink - cg.time) / 3200.0f) * 0.3f; - ent.customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite" ); - ent.shaderRGBA[0] = (sin( cg.time * 0.04f ) * val * 0.4f + val) * 255; + ent.customShader = cgi_R_RegisterShader("gfx/effects/solidWhite"); + ent.shaderRGBA[0] = (sin(cg.time * 0.04f) * val * 0.4f + val) * 255; ent.shaderRGBA[1] = ent.shaderRGBA[2] = 0; ent.renderfx |= RF_RGB_TINT; - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - if (cg_debugBB.integer) - { + if (cg_debugBB.integer) { CG_CreateBBRefEnts(s1, cent->lerpOrigin); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ //-------------------------- - if ( s1->eFlags & EF_FIRING && cent->gent->inuse ) - { - //special code for adding the beam to the attached tripwire mine - vec3_t beamOrg; - int handle = 0; - SEffectTemplate *temp; + if (s1->eFlags & EF_FIRING && cent->gent->inuse) { + // special code for adding the beam to the attached tripwire mine + vec3_t beamOrg; + int handle = 0; + SEffectTemplate *temp; - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward // overriding the effect, so give us a copy first - temp = theFxScheduler.GetEffectCopy( "tripMine/laser", &handle ); + temp = theFxScheduler.GetEffectCopy("tripMine/laser", &handle); - if ( temp ) - { + if (temp) { // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "line1" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "line1"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the endpoint - prim->mOrigin2X.SetRange( cent->gent->pos4[0], cent->gent->pos4[0] ); - prim->mOrigin2Y.SetRange( cent->gent->pos4[1], cent->gent->pos4[1] ); - prim->mOrigin2Z.SetRange( cent->gent->pos4[2], cent->gent->pos4[2] ); + prim->mOrigin2X.SetRange(cent->gent->pos4[0], cent->gent->pos4[0]); + prim->mOrigin2Y.SetRange(cent->gent->pos4[1], cent->gent->pos4[1]); + prim->mOrigin2Z.SetRange(cent->gent->pos4[2], cent->gent->pos4[2]); // have a copy, so get the line element out of there - CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy( temp, "line2" ); + CPrimitiveTemplate *prim = theFxScheduler.GetPrimitiveCopy(temp, "line2"); - if ( prim ) - { + if (prim) { // we have the primitive, so modify the cent->gent->pos3point - prim->mOrigin2X.SetRange( cent->gent->pos4[0], cent->gent->pos4[0] ); - prim->mOrigin2Y.SetRange( cent->gent->pos4[1], cent->gent->pos4[1] ); - prim->mOrigin2Z.SetRange( cent->gent->pos4[2], cent->gent->pos4[2] ); + prim->mOrigin2X.SetRange(cent->gent->pos4[0], cent->gent->pos4[0]); + prim->mOrigin2Y.SetRange(cent->gent->pos4[1], cent->gent->pos4[1]); + prim->mOrigin2Z.SetRange(cent->gent->pos4[2], cent->gent->pos4[2]); // play the modified effect - theFxScheduler.PlayEffect( handle, beamOrg, ent.axis[0] ); + theFxScheduler.PlayEffect(handle, beamOrg, ent.axis[0]); } } } - theFxScheduler.PlayEffect( "tripMine/laserImpactGlow", cent->gent->pos4, ent.axis[0] ); + theFxScheduler.PlayEffect("tripMine/laserImpactGlow", cent->gent->pos4, ent.axis[0]); } + if (s1->eFlags & EF_PROX_TRIP) { + // special code for adding the glow end to proximity tripmine + vec3_t beamOrg; - if ( s1->eFlags & EF_PROX_TRIP ) - { - //special code for adding the glow end to proximity tripmine - vec3_t beamOrg; - - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward - theFxScheduler.PlayEffect( "tripMine/glowBit", beamOrg, ent.axis[0] ); + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward + theFxScheduler.PlayEffect("tripMine/glowBit", beamOrg, ent.axis[0]); } - if ( s1->eFlags & EF_ALT_FIRING ) - { + if (s1->eFlags & EF_ALT_FIRING) { // hack for the spotlight - vec3_t org, axis[3], dir; + vec3_t org, axis[3], dir; - AngleVectors( cent->lerpAngles, dir, NULL, NULL ); + AngleVectors(cent->lerpAngles, dir, NULL, NULL); - CG_GetTagWorldPosition( &ent, "tag_flash", org, axis ); + CG_GetTagWorldPosition(&ent, "tag_flash", org, axis); - theFxScheduler.PlayEffect( "env/light_cone", org, axis[0] ); + theFxScheduler.PlayEffect("env/light_cone", org, axis[0]); - VectorMA( cent->lerpOrigin, cent->gent->radius - 5, dir, org ); // stay a bit back from the impact point...this may not be enough? + VectorMA(cent->lerpOrigin, cent->gent->radius - 5, dir, org); // stay a bit back from the impact point...this may not be enough? - cgi_R_AddLightToScene( org, 225, 1.0f, 1.0f, 1.0f ); + cgi_R_AddLightToScene(org, 225, 1.0f, 1.0f, 1.0f); } //----------------------------------------------------------- - if ( cent->gent->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED )) - { + if (cent->gent->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED)) { // Dumb assumption, but I guess we must be a shielded ion_cannon?? We should probably verify // if it's an ion_cannon that's Heavy Weapon only, we don't want to make it shielded do we...? - if ( (!strcmp( "misc_ion_cannon", cent->gent->classname )) && (cent->gent->flags & FL_SHIELDED )) - { + if ((!strcmp("misc_ion_cannon", cent->gent->classname)) && (cent->gent->flags & FL_SHIELDED)) { // must be doing "pain"....er, impact - if ( cent->gent->painDebounceTime > cg.time ) - { - float t = (float)(cent->gent->painDebounceTime - cg.time ) / 1000.0f; + if (cent->gent->painDebounceTime > cg.time) { + float t = (float)(cent->gent->painDebounceTime - cg.time) / 1000.0f; // Only display when we have damage - if ( t >= 0.0f && t <= 1.0f ) - { + if (t >= 0.0f && t <= 1.0f) { t *= Q_flrand(0.0f, 1.0f); ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = 255.0f * t; ent.shaderRGBA[3] = 255; ent.renderfx &= ~RF_ALPHA_FADE; ent.renderfx |= RF_RGB_TINT; - ent.customShader = cgi_R_RegisterShader( "gfx/misc/ion_shield" ); - - cgi_R_AddRefEntityToScene( &ent ); + ent.customShader = cgi_R_RegisterShader("gfx/misc/ion_shield"); + + cgi_R_AddRefEntityToScene(&ent); } } } @@ -832,16 +724,16 @@ CG_Speaker Speaker entities can automatically play sounds ================== */ -static void CG_Speaker( centity_t *cent ) { - if ( ! cent->currentState.clientNum ) { // FIXME: use something other than clientNum... - return; // not auto triggering +static void CG_Speaker(centity_t *cent) { + if (!cent->currentState.clientNum) { // FIXME: use something other than clientNum... + return; // not auto triggering } - if ( cg.time < cent->miscTime ) { + if (cg.time < cent->miscTime) { return; } - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.sound_precache[cent->currentState.eventParm] ); + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_ITEM, cgs.sound_precache[cent->currentState.eventParm]); // ent->s.frame = ent->wait * 10; // ent->s.clientNum = ent->random * 10; @@ -853,45 +745,40 @@ static void CG_Speaker( centity_t *cent ) { CG_Item ================== */ -static void CG_Item( centity_t *cent ) -{ - refEntity_t ent; - entityState_t *es; - gitem_t *item; -// int msec; -// float frac; - float scale; +static void CG_Item(centity_t *cent) { + refEntity_t ent; + entityState_t *es; + gitem_t *item; + // int msec; + // float frac; + float scale; es = ¢->currentState; - if ( es->modelindex >= bg_numItems ) - { - CG_Error( "Bad item index %i on entity", es->modelindex ); + if (es->modelindex >= bg_numItems) { + CG_Error("Bad item index %i on entity", es->modelindex); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // if set to invisible, skip - if ( (!es->modelindex && !cent->gent->ghoul2.IsValid() ) || ( es->eFlags & EF_NODRAW ) ) - { + if ((!es->modelindex && !cent->gent->ghoul2.IsValid()) || (es->eFlags & EF_NODRAW)) { return; } -/* -Ghoul2 Insert End -*/ - if ( cent->gent && !cent->gent->inuse ) - { + /* + Ghoul2 Insert End + */ + if (cent->gent && !cent->gent->inuse) { // Yeah, I know....items were being freed on touch, but it could still get here and draw incorrectly... return; } - item = &bg_itemlist[ es->modelindex ]; + item = &bg_itemlist[es->modelindex]; - if ( cg_simpleItems.integer ) - { - memset( &ent, 0, sizeof( ent ) ); + if (cg_simpleItems.integer) { + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); ent.radius = 14; ent.customShader = cg_items[es->modelindex].icon; ent.shaderRGBA[0] = 255; @@ -902,121 +789,112 @@ Ghoul2 Insert End return; } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); // items bob up and down continuously - if( item->giType == IT_HOLOCRON ) - { + if (item->giType == IT_HOLOCRON) { scale = 0.005f + cent->currentState.number * 0.00001f; - cent->lerpOrigin[2] += (float)(4 + cos( ( cg.time + 1000 ) * scale ) * 3)+8; // just raised them up a bit + cent->lerpOrigin[2] += (float)(4 + cos((cg.time + 1000) * scale) * 3) + 8; // just raised them up a bit } - - // autorotate at one of two speeds -// if ( item->giType == IT_HEALTH ) { -// VectorCopy( cg.autoAnglesFast, cent->lerpAngles ); -// AxisCopy( cg.autoAxisFast, ent.axis ); -// } else { - if( item->giType == IT_HOLOCRON ) - { - VectorCopy( cg.autoAngles, cent->lerpAngles ); - AxisCopy( cg.autoAxis, ent.axis ); + // if ( item->giType == IT_HEALTH ) { + // VectorCopy( cg.autoAnglesFast, cent->lerpAngles ); + // AxisCopy( cg.autoAxisFast, ent.axis ); + // } else { + if (item->giType == IT_HOLOCRON) { + VectorCopy(cg.autoAngles, cent->lerpAngles); + AxisCopy(cg.autoAxis, ent.axis); } - // the weapons have their origin where they attatch to player // models, so we need to offset them or they will rotate // eccentricly -// if ( item->giType == IT_WEAPON ) { -// weaponInfo_t *wi; -// -// wi = &cg_weapons[item->giTag]; -// cent->lerpOrigin[0] -= -// wi->weaponMidpoint[0] * ent.axis[0][0] + -// wi->weaponMidpoint[1] * ent.axis[1][0] + -// wi->weaponMidpoint[2] * ent.axis[2][0]; -// cent->lerpOrigin[1] -= -// wi->weaponMidpoint[0] * ent.axis[0][1] + -// wi->weaponMidpoint[1] * ent.axis[1][1] + -// wi->weaponMidpoint[2] * ent.axis[2][1]; -// cent->lerpOrigin[2] -= -// wi->weaponMidpoint[0] * ent.axis[0][2] + -// wi->weaponMidpoint[1] * ent.axis[1][2] + -// wi->weaponMidpoint[2] * ent.axis[2][2]; - -// cent->lerpOrigin[2] += 8; // an extra height boost -// } + // if ( item->giType == IT_WEAPON ) { + // weaponInfo_t *wi; + // + // wi = &cg_weapons[item->giTag]; + // cent->lerpOrigin[0] -= + // wi->weaponMidpoint[0] * ent.axis[0][0] + + // wi->weaponMidpoint[1] * ent.axis[1][0] + + // wi->weaponMidpoint[2] * ent.axis[2][0]; + // cent->lerpOrigin[1] -= + // wi->weaponMidpoint[0] * ent.axis[0][1] + + // wi->weaponMidpoint[1] * ent.axis[1][1] + + // wi->weaponMidpoint[2] * ent.axis[2][1]; + // cent->lerpOrigin[2] -= + // wi->weaponMidpoint[0] * ent.axis[0][2] + + // wi->weaponMidpoint[1] * ent.axis[1][2] + + // wi->weaponMidpoint[2] * ent.axis[2][2]; + + // cent->lerpOrigin[2] += 8; // an extra height boost + // } vec3_t spinAngles; - //AxisClear( ent.axis ); - VectorCopy( cent->gent->s.angles, spinAngles ); + // AxisClear( ent.axis ); + VectorCopy(cent->gent->s.angles, spinAngles); ent.hModel = cg_items[es->modelindex].models; -/* -Ghoul2 Insert Start -*/ - CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert Start + */ + CG_SetGhoul2Info(&ent, cent); + /* + Ghoul2 Insert End + */ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); ent.nonNormalizedAxes = qfalse; // lovely...this is for weapons that should be oriented vertically. For weapons lockers and such. - if ( cent->gent->spawnflags & 16 ) - { //VectorClear( spinAngles ); + if (cent->gent->spawnflags & 16) { // VectorClear( spinAngles ); spinAngles[PITCH] -= 75; } - - if( item->giType != IT_HOLOCRON ) - { - AnglesToAxis( spinAngles, ent.axis ); + + if (item->giType != IT_HOLOCRON) { + AnglesToAxis(spinAngles, ent.axis); } // items without glow textures need to keep a minimum light value // so they are always visible -/* if (( item->giType == IT_WEAPON ) || ( item->giType == IT_ARMOR )) - { - ent.renderfx |= RF_MINLIGHT; - } -*/ + /* if (( item->giType == IT_WEAPON ) || ( item->giType == IT_ARMOR )) + { + ent.renderfx |= RF_MINLIGHT; + } + */ // increase the size of the weapons when they are presented as items -// if ( item->giType == IT_WEAPON ) { -// VectorScale( ent.axis[0], 1.5f, ent.axis[0] ); -// VectorScale( ent.axis[1], 1.5f, ent.axis[1] ); -// VectorScale( ent.axis[2], 1.5f, ent.axis[2] ); -// ent.nonNormalizedAxes = qtrue; -// } + // if ( item->giType == IT_WEAPON ) { + // VectorScale( ent.axis[0], 1.5f, ent.axis[0] ); + // VectorScale( ent.axis[1], 1.5f, ent.axis[1] ); + // VectorScale( ent.axis[2], 1.5f, ent.axis[2] ); + // ent.nonNormalizedAxes = qtrue; + // } // add to refresh list cgi_R_AddRefEntityToScene(&ent); - if ( item->giType == IT_WEAPON && item->giTag == WP_SABER ) - { + if (item->giType == IT_WEAPON && item->giTag == WP_SABER) { // saber pickup item needs to be more visible - float wv; - vec3_t org; + float wv; + vec3_t org; - ent.customShader = cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); + ent.customShader = cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); ent.renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.002f ) * 0.08f + 0.2f; + wv = sin(cg.time * 0.002f) * 0.08f + 0.2f; ent.shaderRGBA[0] = ent.shaderRGBA[1] = wv * 255; ent.shaderRGBA[2] = 0; cgi_R_AddRefEntityToScene(&ent); - for ( int i = -4; i < 10; i += 1 ) - { - VectorMA( ent.origin, -i, ent.axis[2], org ); + for (int i = -4; i < 10; i += 1) { + VectorMA(ent.origin, -i, ent.axis[2], org); - FX_AddSprite( org, NULL, NULL, 10.0f, 10.0f, wv * 0.5f, wv * 0.5f, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000 ); + FX_AddSprite(org, NULL, NULL, 10.0f, 10.0f, wv * 0.5f, wv * 0.5f, 0.0f, 0.0f, 1.0f, cgs.media.yellowDroppedSaberShader, 0x08000000); } // THIS light looks crappy...maybe it should just be removed... - cgi_R_AddLightToScene( ent.origin, wv * 350 + 180, 1.0f, 1.0f, 0.0f ); + cgi_R_AddLightToScene(ent.origin, wv * 350 + 180, 1.0f, 1.0f, 0.0f); } } @@ -1027,118 +905,108 @@ Ghoul2 Insert End CG_Missile =============== */ -static void CG_Missile( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; - const weaponInfo_t *weapon; - const weaponData_t *wData; +static void CG_Missile(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; + const weaponInfo_t *weapon; + const weaponData_t *wData; - if ( !cent->gent->inuse ) + if (!cent->gent->inuse) return; s1 = ¢->currentState; - if ( s1->weapon >= WP_NUM_WEAPONS ) { + if (s1->weapon >= WP_NUM_WEAPONS) { s1->weapon = 0; } weapon = &cg_weapons[s1->weapon]; wData = &weaponData[s1->weapon]; - if ( s1->pos.trType != TR_INTERPOLATE ) - { + if (s1->pos.trType != TR_INTERPOLATE) { // calculate the axis - VectorCopy( s1->angles, cent->lerpAngles ); + VectorCopy(s1->angles, cent->lerpAngles); } - if ( cent->gent->alt_fire ) - { + if (cent->gent->alt_fire) { // add trails - if ( weapon->alt_missileTrailFunc ) - weapon->alt_missileTrailFunc( cent, weapon ); + if (weapon->alt_missileTrailFunc) + weapon->alt_missileTrailFunc(cent, weapon); // add dynamic light - if ( wData->alt_missileDlight ) - cgi_R_AddLightToScene(cent->lerpOrigin, wData->alt_missileDlight, - wData->alt_missileDlightColor[0], wData->alt_missileDlightColor[1], wData->alt_missileDlightColor[2] ); + if (wData->alt_missileDlight) + cgi_R_AddLightToScene(cent->lerpOrigin, wData->alt_missileDlight, wData->alt_missileDlightColor[0], wData->alt_missileDlightColor[1], + wData->alt_missileDlightColor[2]); // add missile sound - if ( weapon->alt_missileSound ) - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->alt_missileSound ); + if (weapon->alt_missileSound) + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->alt_missileSound); - //Don't draw something without a model - if ( weapon->alt_missileModel == NULL_HANDLE ) + // Don't draw something without a model + if (weapon->alt_missileModel == NULL_HANDLE) return; - } - else - { + } else { // add trails - if ( weapon->missileTrailFunc ) - weapon->missileTrailFunc( cent, weapon ); + if (weapon->missileTrailFunc) + weapon->missileTrailFunc(cent, weapon); // add dynamic light - if ( wData->missileDlight ) - cgi_R_AddLightToScene(cent->lerpOrigin, wData->missileDlight, - wData->missileDlightColor[0], wData->missileDlightColor[1], wData->missileDlightColor[2] ); + if (wData->missileDlight) + cgi_R_AddLightToScene(cent->lerpOrigin, wData->missileDlight, wData->missileDlightColor[0], wData->missileDlightColor[1], + wData->missileDlightColor[2]); // add missile sound - if ( weapon->missileSound ) - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->missileSound ); + if (weapon->missileSound) + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->missileSound); - //Don't draw something without a model - if ( weapon->missileModel == NULL_HANDLE ) + // Don't draw something without a model + if (weapon->missileModel == NULL_HANDLE) return; } // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); -/* -Ghoul2 Insert Start -*/ - CG_SetGhoul2Info(&ent, cent); + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + /* + Ghoul2 Insert Start + */ + CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // flicker between two skins ent.skinNum = cg.clientFrame & 1; - ent.renderfx = /*weapon->missileRenderfx | */RF_NOSHADOW; + ent.renderfx = /*weapon->missileRenderfx | */ RF_NOSHADOW; - if ( cent->gent->alt_fire ) + if (cent->gent->alt_fire) ent.hModel = weapon->alt_missileModel; else ent.hModel = weapon->missileModel; // spin as it moves - if ( s1->apos.trType != TR_INTERPOLATE ) - { + if (s1->apos.trType != TR_INTERPOLATE) { // convert direction of travel into axis - if ( VectorNormalize2( s1->pos.trDelta, ent.axis[0] ) == 0 ) { + if (VectorNormalize2(s1->pos.trDelta, ent.axis[0]) == 0) { ent.axis[0][2] = 1; } - if ( s1->pos.trType != TR_STATIONARY ) - { - if ( s1->eFlags & EF_MISSILE_STICK ) - RotateAroundDirection( ent.axis, cg.time * 0.5f );//Did this so regular missiles don't get broken + if (s1->pos.trType != TR_STATIONARY) { + if (s1->eFlags & EF_MISSILE_STICK) + RotateAroundDirection(ent.axis, cg.time * 0.5f); // Did this so regular missiles don't get broken else - RotateAroundDirection( ent.axis, cg.time * 0.25f );//JFM:FLOAT FIX - } - else - { - if ( s1->eFlags & EF_MISSILE_STICK ) - RotateAroundDirection( ent.axis, (float)s1->pos.trTime * 0.5f ); + RotateAroundDirection(ent.axis, cg.time * 0.25f); // JFM:FLOAT FIX + } else { + if (s1->eFlags & EF_MISSILE_STICK) + RotateAroundDirection(ent.axis, (float)s1->pos.trTime * 0.5f); else - RotateAroundDirection( ent.axis, (float)s1->time ); + RotateAroundDirection(ent.axis, (float)s1->time); } - } - else - { - AnglesToAxis( cent->lerpAngles, ent.axis ); + } else { + AnglesToAxis(cent->lerpAngles, ent.axis); } // add to refresh list, possibly with quad glow - CG_AddRefEntityWithPowerups( &ent, s1->powerups, NULL ); + CG_AddRefEntityWithPowerups(&ent, s1->powerups, NULL); } /* @@ -1147,109 +1015,98 @@ CG_Mover =============== */ -#define DOOR_OPENING 1 -#define DOOR_CLOSING 2 -#define DOOR_OPEN 3 -#define DOOR_CLOSED 4 +#define DOOR_OPENING 1 +#define DOOR_CLOSING 2 +#define DOOR_OPEN 3 +#define DOOR_CLOSED 4 -static void CG_Mover( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Mover(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - //FIXME: why are these always 0, 0, 0???! - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); - AnglesToAxis( cent->lerpAngles, ent.axis ); -/* -Ghoul2 Insert Start -*/ + memset(&ent, 0, sizeof(ent)); + // FIXME: why are these always 0, 0, 0???! + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + AnglesToAxis(cent->lerpAngles, ent.axis); + /* + Ghoul2 Insert Start + */ - CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + CG_SetGhoul2Info(&ent, cent); + /* + Ghoul2 Insert End + */ ent.renderfx = RF_NOSHADOW; // flicker between two skins (FIXME?) - ent.skinNum = ( cg.time >> 6 ) & 1; + ent.skinNum = (cg.time >> 6) & 1; // get the model, either as a bmodel or a modelindex - if ( s1->solid == SOLID_BMODEL ) { + if (s1->solid == SOLID_BMODEL) { ent.hModel = cgs.inlineDrawModel[s1->modelindex]; } else { ent.hModel = cgs.model_draw[s1->modelindex]; } // If there isn't an hModel for this mover, an RGB axis model will get drawn. - if ( !ent.hModel ) - { + if (!ent.hModel) { return; } - if ( cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM ) - { + if (cent->currentState.eFlags & EF_DISABLE_SHADER_ANIM) { // by setting the shader time to the current time, we can force an animating shader to not animate ent.shaderTime = cg.time * 0.001f; } // add the secondary model - if ( s1->solid == SOLID_BMODEL && s1->modelindex2 ) - { -// vec3_t org; - if ( !(s1->eFlags & EF_NODRAW) ) - { + if (s1->solid == SOLID_BMODEL && s1->modelindex2) { + // vec3_t org; + if (!(s1->eFlags & EF_NODRAW)) { // add to refresh list - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); } -/* // Um, this does not interpolate nicely? Not sure why it was here.... - VectorAdd(cent->gent->absmin, cent->gent->absmax, org); - VectorScale(org, 0.5, org); - VectorCopy( org, ent.origin); - VectorCopy( org, ent.oldorigin); -*/ + /* // Um, this does not interpolate nicely? Not sure why it was here.... + VectorAdd(cent->gent->absmin, cent->gent->absmax, org); + VectorScale(org, 0.5, org); + VectorCopy( org, ent.origin); + VectorCopy( org, ent.oldorigin); + */ ent.hModel = cgs.model_draw[s1->modelindex2]; } // I changed it to always do it because nodraw seemed like it should actually do what it says. Be aware that if you change this, // the movers for the shooting gallery on doom_detention will break. - if ( (s1->eFlags & EF_NODRAW) ) - { + if ((s1->eFlags & EF_NODRAW)) { return; } - //fall through and render the hModel or... + // fall through and render the hModel or... - //We're a normal model being moved, animate our model + // We're a normal model being moved, animate our model ent.skinNum = 0; - if ( s1->eFlags & EF_ANIM_ONCE ) - {//FIXME: needs to anim at once per 100 ms + if (s1->eFlags & EF_ANIM_ONCE) { // FIXME: needs to anim at once per 100 ms ent.frame = cent->gent->s.frame; - ent.renderfx|=RF_CAP_FRAMES; - } - else if ( s1->eFlags & EF_ANIM_ALLFAST ) - { + ent.renderfx |= RF_CAP_FRAMES; + } else if (s1->eFlags & EF_ANIM_ALLFAST) { ent.frame = (cg.time / 100); - ent.renderfx|=RF_WRAP_FRAMES; - } - else - { + ent.renderfx |= RF_WRAP_FRAMES; + } else { ent.frame = s1->frame; } - if ( s1->eFlags & EF_SHADER_ANIM ) - { - ent.renderfx|=RF_SETANIMINDEX; + if (s1->eFlags & EF_SHADER_ANIM) { + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - //ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames + // ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames } // add to refresh list - CG_AddRefEntWithTransportEffect( cent, &ent ); + CG_AddRefEntWithTransportEffect(cent, &ent); } /* @@ -1259,51 +1116,44 @@ CG_Beam Also called as an event =============== */ -void CG_Beam( centity_t *cent, int color ) { - refEntity_t ent; - entityState_t *s1; +void CG_Beam(centity_t *cent, int color) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( s1->pos.trBase, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - AxisClear( ent.axis ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(s1->pos.trBase, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + AxisClear(ent.axis); ent.reType = RT_BEAM; ent.skinNum = color; ent.renderfx = RF_NOSHADOW; -/* -Ghoul2 Insert Start -*/ - CG_SetGhoul2Info(&ent, cent); + /* + Ghoul2 Insert Start + */ + CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // add to refresh list cgi_R_AddRefEntityToScene(&ent); } -static vec2_t st[] = -{ - { 0.0f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } -}; +static vec2_t st[] = {{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}}; -void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) -{ - vec3_t point[4], rot={0,0,0}; - int vec[3]; - int axis, i; +void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha) { + vec3_t point[4], rot = {0, 0, 0}; + int vec[3]; + int axis, i; - for ( axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++ ) - { - for ( i = 0; i < 3; i++ ) - { - if ( vec[i] > 2 ) - { + for (axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++) { + for (i = 0; i < 3; i++) { + if (vec[i] > 2) { vec[i] = 0; } } @@ -1316,38 +1166,30 @@ void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) point[2][vec[1]] = maxs[vec[1]]; point[2][vec[2]] = maxs[vec[2]]; - + point[3][vec[1]] = maxs[vec[1]]; point[3][vec[2]] = mins[vec[2]]; //- face point[0][vec[0]] = point[1][vec[0]] = point[2][vec[0]] = point[3][vec[0]] = mins[vec[0]]; - FX_AddPoly( point, st, 4, NULL, NULL, alpha, alpha, 0.0f, - color, color, 0.0f, rot, 0.0f, 0.0f, - 100, cgs.media.solidWhiteShader, 0 ); + FX_AddPoly(point, st, 4, NULL, NULL, alpha, alpha, 0.0f, color, color, 0.0f, rot, 0.0f, 0.0f, 100, cgs.media.solidWhiteShader, 0); //+ face point[0][vec[0]] = point[1][vec[0]] = point[2][vec[0]] = point[3][vec[0]] = maxs[vec[0]]; - FX_AddPoly( point, st, 4, NULL, NULL, alpha, alpha, 0.0f, - color, color, 0.0f, rot, 0.0f, 0.0f, - 100, cgs.media.solidWhiteShader, 0 ); + FX_AddPoly(point, st, 4, NULL, NULL, alpha, alpha, 0.0f, color, color, 0.0f, rot, 0.0f, 0.0f, 100, cgs.media.solidWhiteShader, 0); } } -void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ) -{ - vec3_t point1, point2, point3, point4; - int vec[3]; - int axis, i; +void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha) { + vec3_t point1, point2, point3, point4; + int vec[3]; + int axis, i; - for ( axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++ ) - { - for ( i = 0; i < 3; i++ ) - { - if ( vec[i] > 2 ) - { + for (axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++) { + for (i = 0; i < 3; i++) { + if (vec[i] > 2) { vec[i] = 0; } } @@ -1360,30 +1202,29 @@ void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, flo point3[vec[1]] = maxs[vec[1]]; point3[vec[2]] = maxs[vec[2]]; - + point4[vec[1]] = maxs[vec[1]]; point4[vec[2]] = mins[vec[2]]; //- face point1[vec[0]] = point2[vec[0]] = point3[vec[0]] = point4[vec[0]] = mins[vec[0]]; - CG_TestLine( point1, point2, time, color, 1 ); - CG_TestLine( point2, point3, time, color, 1 ); - CG_TestLine( point1, point4, time, color, 1 ); - CG_TestLine( point4, point3, time, color, 1 ); + CG_TestLine(point1, point2, time, color, 1); + CG_TestLine(point2, point3, time, color, 1); + CG_TestLine(point1, point4, time, color, 1); + CG_TestLine(point4, point3, time, color, 1); //+ face point1[vec[0]] = point2[vec[0]] = point3[vec[0]] = point4[vec[0]] = maxs[vec[0]]; - CG_TestLine( point1, point2, time, color, 1 ); - CG_TestLine( point2, point3, time, color, 1 ); - CG_TestLine( point1, point4, time, color, 1 ); - CG_TestLine( point4, point1, time, color, 1 ); + CG_TestLine(point1, point2, time, color, 1); + CG_TestLine(point2, point3, time, color, 1); + CG_TestLine(point1, point4, time, color, 1); + CG_TestLine(point4, point1, time, color, 1); } } -void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) -{ +void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha) { /*FX_AddLine( start, end, 1.0f, @@ -1391,8 +1232,8 @@ void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) 1.0f, alpha, alpha, - color, - color, + color, + color, 100.0f, cgs.media.whiteShader );*/ } @@ -1402,47 +1243,45 @@ void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) CG_Portal =============== */ -static void CG_Portal( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Portal(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; - //FIXME: this tends to give a bad axis[1], perhaps we - //should just do the VectorSubtraction here rather than - //on the game side. Would also allow camera to follow - //a moving target. + // FIXME: this tends to give a bad axis[1], perhaps we + // should just do the VectorSubtraction here rather than + // on the game side. Would also allow camera to follow + // a moving target. // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - ByteToDir( s1->eventParm, ent.axis[0] ); - PerpendicularVector( ent.axis[1], ent.axis[0] ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + ByteToDir(s1->eventParm, ent.axis[0]); + PerpendicularVector(ent.axis[1], ent.axis[0]); // negating this tends to get the directions like they want // we really should have a camera roll value - VectorSubtract( vec3_origin, ent.axis[1], ent.axis[1] ); + VectorSubtract(vec3_origin, ent.axis[1], ent.axis[1]); - CrossProduct( ent.axis[0], ent.axis[1], ent.axis[2] ); + CrossProduct(ent.axis[0], ent.axis[1], ent.axis[2]); ent.reType = RT_PORTALSURFACE; - ent.frame = s1->frame; // rotation speed - ent.skinNum = (int)(s1->clientNum/256.0 * 360); // roll offset - -/* -Ghoul2 Insert Start -*/ - CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + ent.frame = s1->frame; // rotation speed + ent.skinNum = (int)(s1->clientNum / 256.0 * 360); // roll offset + /* + Ghoul2 Insert Start + */ + CG_SetGhoul2Info(&ent, cent); + /* + Ghoul2 Insert End + */ // add to refresh list cgi_R_AddRefEntityToScene(&ent); } - /* ========================= CG_AdjustPositionForMover @@ -1450,33 +1289,32 @@ CG_AdjustPositionForMover Also called by client movement prediction code ========================= */ -void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int atTime, vec3_t out ) { - centity_t *cent; - vec3_t oldOrigin, origin, deltaOrigin; -// vec3_t oldAngles, angles, deltaAngles; +void CG_AdjustPositionForMover(const vec3_t in, int moverNum, int atTime, vec3_t out) { + centity_t *cent; + vec3_t oldOrigin, origin, deltaOrigin; + // vec3_t oldAngles, angles, deltaAngles; - if ( moverNum <= 0 ) { - VectorCopy( in, out ); + if (moverNum <= 0) { + VectorCopy(in, out); return; } - cent = &cg_entities[ moverNum ]; - if ( cent->currentState.eType != ET_MOVER ) { - VectorCopy( in, out ); + cent = &cg_entities[moverNum]; + if (cent->currentState.eType != ET_MOVER) { + VectorCopy(in, out); return; } - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, oldOrigin ); -// EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, oldAngles ); - - EvaluateTrajectory( ¢->currentState.pos, atTime, origin ); -// EvaluateTrajectory( ¢->currentState.apos, atTime, angles ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, oldOrigin); + // EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, oldAngles ); - VectorSubtract( origin, oldOrigin, deltaOrigin ); -// VectorSubtract( angles, oldAngles, deltaAngles ); + EvaluateTrajectory(¢->currentState.pos, atTime, origin); + // EvaluateTrajectory( ¢->currentState.apos, atTime, angles ); + VectorSubtract(origin, oldOrigin, deltaOrigin); + // VectorSubtract( angles, oldAngles, deltaAngles ); - VectorAdd( in, deltaOrigin, out ); + VectorAdd(in, deltaOrigin, out); // FIXME: origin change when on a rotating object } @@ -1486,48 +1324,45 @@ CG_CalcEntityLerpPositions =============== */ -extern char *vtos( const vec3_t v ); +extern char *vtos(const vec3_t v); #if 1 -void CG_CalcEntityLerpPositions( centity_t *cent ) { - if ( cent->currentState.number == cg.snap->ps.clientNum) - { +void CG_CalcEntityLerpPositions(centity_t *cent) { + if (cent->currentState.number == cg.snap->ps.clientNum) { // if the player, take position from prediction - VectorCopy( cg.predicted_player_state.origin, cent->lerpOrigin ); - VectorCopy( cg.predicted_player_state.viewangles, cent->lerpAngles ); -/* -Ghoul2 Insert Start -*/ -// LerpBoneAngleOverrides(cent); -/* -Ghoul2 Insert End -*/ + VectorCopy(cg.predicted_player_state.origin, cent->lerpOrigin); + VectorCopy(cg.predicted_player_state.viewangles, cent->lerpAngles); + /* + Ghoul2 Insert Start + */ + // LerpBoneAngleOverrides(cent); + /* + Ghoul2 Insert End + */ return; } - - //FIXME: prediction on clients in timescale results in jerky positional translation - if ( cent->interpolate ) - { + + // FIXME: prediction on clients in timescale results in jerky positional translation + if (cent->interpolate) { // if the entity has a valid next state, interpolate a value between the frames // unless it is a mover with a known start and stop - vec3_t current, next; - float f; + vec3_t current, next; + float f; // it would be an internal error to find an entity that interpolates without // a snapshot ahead of the current one - if ( cg.nextSnap == NULL ) { - CG_Error( "CG_AddCEntity: cg.nextSnap == NULL" ); + if (cg.nextSnap == NULL) { + CG_Error("CG_AddCEntity: cg.nextSnap == NULL"); } f = cg.frameInterpolation; - if ( cent->currentState.apos.trType == TR_INTERPOLATE ) - { - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.apos, cg.nextSnap->serverTime, next ); + if (cent->currentState.apos.trType == TR_INTERPOLATE) { + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.apos, cg.nextSnap->serverTime, next); - cent->lerpAngles[0] = LerpAngle( current[0], next[0], f ); - cent->lerpAngles[1] = LerpAngle( current[1], next[1], f ); - cent->lerpAngles[2] = LerpAngle( current[2], next[2], f ); + cent->lerpAngles[0] = LerpAngle(current[0], next[0], f); + cent->lerpAngles[1] = LerpAngle(current[1], next[1], f); + cent->lerpAngles[2] = LerpAngle(current[2], next[2], f); /* if(cent->gent && cent->currentState.eFlags & EF_NPC && !VectorCompare(current, next)) @@ -1535,9 +1370,9 @@ Ghoul2 Insert End Com_Printf("%s last/next/lerp apos %s/%s/%s, f = %4.2f\n", cent->gent->script_targetname, vtos(current), vtos(next), vtos(cent->lerpAngles), f); } */ - /* - Ghoul2 Insert Start - */ + /* + Ghoul2 Insert Start + */ // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent /* if (cent->gent->ghoul2.size()) @@ -1545,20 +1380,19 @@ Ghoul2 Insert End LerpBoneAngleOverrides(cent); } */ - /* - Ghoul2 Insert End - */ + /* + Ghoul2 Insert End + */ } - if ( cent->currentState.pos.trType == TR_INTERPOLATE ) - { + if (cent->currentState.pos.trType == TR_INTERPOLATE) { // this will linearize a sine or parabolic curve, but it is important // to not extrapolate player positions if more recent data is available - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.pos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.pos, cg.nextSnap->serverTime, next); - cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] ); - cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] ); - cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] ); + cent->lerpOrigin[0] = current[0] + f * (next[0] - current[0]); + cent->lerpOrigin[1] = current[1] + f * (next[1] - current[1]); + cent->lerpOrigin[2] = current[2] + f * (next[2] - current[2]); /* if ( cent->gent && cent->currentState.eFlags & EF_NPC ) @@ -1566,18 +1400,14 @@ Ghoul2 Insert End Com_Printf("%s last/next/lerp pos %s/%s/%s, f = %4.2f\n", cent->gent->script_targetname, vtos(current), vtos(next), vtos(cent->lerpOrigin), f); } */ - return;//FIXME: should this be outside this if? + return; // FIXME: should this be outside this if? } - } - else - { - if ( cent->currentState.apos.trType == TR_INTERPOLATE ) - { - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, cent->lerpAngles ); + } else { + if (cent->currentState.apos.trType == TR_INTERPOLATE) { + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, cent->lerpAngles); } - if ( cent->currentState.pos.trType == TR_INTERPOLATE ) - { - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); + if (cent->currentState.pos.trType == TR_INTERPOLATE) { + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); /* if(cent->gent && cent->currentState.eFlags & EF_NPC ) { @@ -1587,7 +1417,7 @@ Ghoul2 Insert End return; } } - + // FIXME: if it's blocked, it wigs out, draws it in a predicted spot, but never // makes it there - we need to predict it in the right place if this is happens... @@ -1596,115 +1426,88 @@ Ghoul2 Insert End { gentity_t *ent = &g_entities[cent->currentState.number]; - if ( ent && ent->inuse) - { - if ( ent->s.eFlags & EF_BLOCKED_MOVER || ent->s.pos.trType == TR_STATIONARY ) - {//this mover has stopped moving and is going to wig out if we predict it - //based on last frame's info- cut across the network and use the currentOrigin - VectorCopy( ent->currentOrigin, cent->lerpOrigin ); + if (ent && ent->inuse) { + if (ent->s.eFlags & EF_BLOCKED_MOVER || + ent->s.pos.trType == TR_STATIONARY) { // this mover has stopped moving and is going to wig out if we predict it + // based on last frame's info- cut across the network and use the currentOrigin + VectorCopy(ent->currentOrigin, cent->lerpOrigin); posData = NULL; - } - else - { + } else { posData = &ent->s.pos; } } } - if ( posData ) - { - EvaluateTrajectory( posData, cg.time, cent->lerpOrigin ); + if (posData) { + EvaluateTrajectory(posData, cg.time, cent->lerpOrigin); } // FIXME: this will stomp an apos trType of TR_INTERPOLATE!! - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); // adjust for riding a mover - CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin ); -/* -Ghoul2 Insert Start -*/ - // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent + CG_AdjustPositionForMover(cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin); + /* + Ghoul2 Insert Start + */ + // now the nasty stuff - this will interpolate all ghoul2 models bone angle overrides per model attached to this cent /* if (cent->gent->ghoul2.size()) { LerpBoneAngleOverrides(cent); } */ -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // FIXME: perform general error decay? } #else -void CG_CalcEntityLerpPositions( centity_t *cent ) -{ - if ( cent->currentState.number == cg.snap->ps.clientNum) - { +void CG_CalcEntityLerpPositions(centity_t *cent) { + if (cent->currentState.number == cg.snap->ps.clientNum) { // if the player, take position from prediction - VectorCopy( cg.predicted_player_state.origin, cent->lerpOrigin ); - VectorCopy( cg.predicted_player_state.viewangles, cent->lerpAngles ); -OutputDebugString(va("b=(%6.2f,%6.2f,%6.2f)\n",cent->lerpOrigin[0],cent->lerpOrigin[1],cent->lerpOrigin[2])); + VectorCopy(cg.predicted_player_state.origin, cent->lerpOrigin); + VectorCopy(cg.predicted_player_state.viewangles, cent->lerpAngles); + OutputDebugString(va("b=(%6.2f,%6.2f,%6.2f)\n", cent->lerpOrigin[0], cent->lerpOrigin[1], cent->lerpOrigin[2])); return; } - -if (cent->currentState.number != cg.snap->ps.clientNum&¢->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE) -{ - if (cent->interpolate) - { -OutputDebugString(va("[%3d] interp %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", - cent->currentState.number, - cg.frameInterpolation, - cg.time, - cg.snap->serverTime, - cg.nextSnap->serverTime, - cent->currentState.pos.trBase[0], - cent->nextState.pos.trBase[0])); - } - else - { -OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", - cent->currentState.number, - cg.frameInterpolation, - cg.time, - cg.snap->serverTime, - 0, - cent->currentState.pos.trBase[0], - 0.0f)); + if (cent->currentState.number != cg.snap->ps.clientNum && cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE) { + if (cent->interpolate) { + OutputDebugString(va("[%3d] interp %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", cent->currentState.number, cg.frameInterpolation, + cg.time, cg.snap->serverTime, cg.nextSnap->serverTime, cent->currentState.pos.trBase[0], cent->nextState.pos.trBase[0])); + } else { + OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f nb=%6.2f\n", cent->currentState.number, cg.frameInterpolation, + cg.time, cg.snap->serverTime, 0, cent->currentState.pos.trBase[0], 0.0f)); + } } -} - //FIXME: prediction on clients in timescale results in jerky positional translation - if (cent->interpolate && - (cent->currentState.number == cg.snap->ps.clientNum || - cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE ) ) - { - vec3_t current, next; - float f; + // FIXME: prediction on clients in timescale results in jerky positional translation + if (cent->interpolate && (cent->currentState.number == cg.snap->ps.clientNum || cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE)) { + vec3_t current, next; + float f; // it would be an internal error to find an entity that interpolates without // a snapshot ahead of the current one - if ( cg.nextSnap == NULL ) - { - CG_Error( "CG_AddCEntity: cg.nextSnap == NULL" ); + if (cg.nextSnap == NULL) { + CG_Error("CG_AddCEntity: cg.nextSnap == NULL"); } f = cg.frameInterpolation; - EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.apos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.apos, cg.nextSnap->serverTime, next); - cent->lerpAngles[0] = LerpAngle( current[0], next[0], f ); - cent->lerpAngles[1] = LerpAngle( current[1], next[1], f ); - cent->lerpAngles[2] = LerpAngle( current[2], next[2], f ); + cent->lerpAngles[0] = LerpAngle(current[0], next[0], f); + cent->lerpAngles[1] = LerpAngle(current[1], next[1], f); + cent->lerpAngles[2] = LerpAngle(current[2], next[2], f); - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, current ); - EvaluateTrajectory( ¢->nextState.pos, cg.nextSnap->serverTime, next ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, current); + EvaluateTrajectory(¢->nextState.pos, cg.nextSnap->serverTime, next); - cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] ); - cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] ); - cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] ); + cent->lerpOrigin[0] = current[0] + f * (next[0] - current[0]); + cent->lerpOrigin[1] = current[1] + f * (next[1] - current[1]); + cent->lerpOrigin[2] = current[2] + f * (next[2] - current[2]); return; } // just use the current frame and evaluate as best we can @@ -1712,29 +1515,24 @@ OutputDebugString(va("[%3d] nonext %4.2f t=%6d st = %6d nst = %6d b=%6.2f { gentity_t *ent = &g_entities[cent->currentState.number]; - if ( ent && ent->inuse) - { - if ( ent->s.eFlags & EF_BLOCKED_MOVER || ent->s.pos.trType == TR_STATIONARY ) - {//this mover has stopped moving and is going to wig out if we predict it - //based on last frame's info- cut across the network and use the currentOrigin - VectorCopy( ent->currentOrigin, cent->lerpOrigin ); + if (ent && ent->inuse) { + if (ent->s.eFlags & EF_BLOCKED_MOVER || + ent->s.pos.trType == TR_STATIONARY) { // this mover has stopped moving and is going to wig out if we predict it + // based on last frame's info- cut across the network and use the currentOrigin + VectorCopy(ent->currentOrigin, cent->lerpOrigin); posData = NULL; - } - else - { + } else { posData = &ent->s.pos; - EvaluateTrajectory(&ent->s.pos,cg.time, cent->lerpOrigin ); + EvaluateTrajectory(&ent->s.pos, cg.time, cent->lerpOrigin); } - } - else - { - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); + } else { + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); } } - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); // adjust for riding a mover - CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin ); + CG_AdjustPositionForMover(cent->lerpOrigin, cent->currentState.groundEntityNum, cg.time, cent->lerpOrigin); } #endif /* @@ -1743,9 +1541,8 @@ CG_AddLocalSet =============== */ -static void CG_AddLocalSet( centity_t *cent ) -{ - cent->gent->setTime = cgi_S_AddLocalSet( cent->gent->soundSet, cg.refdef.vieworg, cent->lerpOrigin, cent->gent->s.number, cent->gent->setTime ); +static void CG_AddLocalSet(centity_t *cent) { + cent->gent->setTime = cgi_S_AddLocalSet(cent->gent->soundSet, cg.refdef.vieworg, cent->lerpOrigin, cent->gent->s.number, cent->gent->setTime); } /* @@ -1754,93 +1551,76 @@ CAS_GetBModelSound ------------------------- */ -sfxHandle_t CAS_GetBModelSound( const char *name, int stage ) -{ - return cgi_AS_GetBModelSound( name, stage ); -} +sfxHandle_t CAS_GetBModelSound(const char *name, int stage) { return cgi_AS_GetBModelSound(name, stage); } -void CG_DLightThink ( centity_t *cent ) -{ - if(cent->gent) - { - float tDelta = cg.time - cent->gent->painDebounceTime; - float percentage = ( tDelta/((float)cent->gent->speed) ); - vec3_t org; - vec4_t currentRGBA; - gentity_t *owner = NULL; - int i; - - if ( percentage >= 1.0f ) - {//We hit the end +void CG_DLightThink(centity_t *cent) { + if (cent->gent) { + float tDelta = cg.time - cent->gent->painDebounceTime; + float percentage = (tDelta / ((float)cent->gent->speed)); + vec3_t org; + vec4_t currentRGBA; + gentity_t *owner = NULL; + int i; + + if (percentage >= 1.0f) { // We hit the end percentage = 1.0f; - switch( cent->gent->pushDebounceTime ) - { - case 0://Fading from start to final - if ( cent->gent->spawnflags & 8 ) - {//PULSER - if ( tDelta - cent->gent->speed - cent->gent->wait >= 0 ) - {//Time to start fading down + switch (cent->gent->pushDebounceTime) { + case 0: // Fading from start to final + if (cent->gent->spawnflags & 8) { // PULSER + if (tDelta - cent->gent->speed - cent->gent->wait >= 0) { // Time to start fading down cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 1; percentage = 0.0f; } - } - else - {//Stick on startRGBA + } else { // Stick on startRGBA percentage = 0.0f; } break; - case 1://Fading from final to start - if ( tDelta - cent->gent->speed - cent->gent->radius >= 0 ) - {//Time to start fading up + case 1: // Fading from final to start + if (tDelta - cent->gent->speed - cent->gent->radius >= 0) { // Time to start fading up cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 0; percentage = 0.0f; } break; - case 2://Fading from 0 intensity to start intensity - //Time to start fading from start to final + case 2: // Fading from 0 intensity to start intensity + // Time to start fading from start to final cent->gent->painDebounceTime = cg.time; cent->gent->pushDebounceTime = 0; percentage = 0.0f; break; - case 3://Fading from current intensity to 0 intensity - //Time to turn off + case 3: // Fading from current intensity to 0 intensity + // Time to turn off cent->gent->misc_dlight_active = qfalse; cent->gent->e_clThinkFunc = clThinkF_NULL; cent->gent->s.eType = ET_GENERAL; cent->gent->svFlags &= ~SVF_BROADCAST; - return; + return; break; default: break; } } - switch( cent->gent->pushDebounceTime ) - { - case 0://Fading from start to final - for ( i = 0; i < 4; i++ ) - { - currentRGBA[i] = cent->gent->startRGBA[i] + ( (cent->gent->finalRGBA[i] - cent->gent->startRGBA[i]) * percentage ); + switch (cent->gent->pushDebounceTime) { + case 0: // Fading from start to final + for (i = 0; i < 4; i++) { + currentRGBA[i] = cent->gent->startRGBA[i] + ((cent->gent->finalRGBA[i] - cent->gent->startRGBA[i]) * percentage); } break; - case 1://Fading from final to start - for ( i = 0; i < 4; i++ ) - { - currentRGBA[i] = cent->gent->finalRGBA[i] + ( (cent->gent->startRGBA[i] - cent->gent->finalRGBA[i]) * percentage ); + case 1: // Fading from final to start + for (i = 0; i < 4; i++) { + currentRGBA[i] = cent->gent->finalRGBA[i] + ((cent->gent->startRGBA[i] - cent->gent->finalRGBA[i]) * percentage); } break; - case 2://Fading from 0 intensity to start - for ( i = 0; i < 3; i++ ) - { + case 2: // Fading from 0 intensity to start + for (i = 0; i < 3; i++) { currentRGBA[i] = cent->gent->startRGBA[i]; } currentRGBA[3] = cent->gent->startRGBA[3] * percentage; break; - case 3://Fading from current intensity to 0 - for ( i = 0; i < 3; i++ ) - {//FIXME: use last + case 3: // Fading from current intensity to 0 + for (i = 0; i < 3; i++) { // FIXME: use last currentRGBA[i] = cent->gent->startRGBA[i]; } currentRGBA[3] = cent->gent->startRGBA[3] - (cent->gent->startRGBA[3] * percentage); @@ -1850,197 +1630,158 @@ void CG_DLightThink ( centity_t *cent ) break; } - if ( cent->gent->owner ) - { + if (cent->gent->owner) { owner = cent->gent->owner; - } - else - { + } else { owner = cent->gent; } - if ( owner->s.pos.trType == TR_INTERPOLATE ) - { - VectorCopy( cg_entities[owner->s.number].lerpOrigin, org ); - } - else - { - VectorCopy( owner->currentOrigin, org ); + if (owner->s.pos.trType == TR_INTERPOLATE) { + VectorCopy(cg_entities[owner->s.number].lerpOrigin, org); + } else { + VectorCopy(owner->currentOrigin, org); } - cgi_R_AddLightToScene(org, currentRGBA[3]*10, currentRGBA[0], currentRGBA[1], currentRGBA[2] ); + cgi_R_AddLightToScene(org, currentRGBA[3] * 10, currentRGBA[0], currentRGBA[1], currentRGBA[2]); } } -void CG_Limb ( centity_t *cent ) -{//first time we're drawn, remove us from the owner ent - if ( cent->gent && cent->gent->owner && cent->gent->owner->ghoul2.size() ) - { - gentity_t *owner = cent->gent->owner; - if ( cent->gent->aimDebounceTime ) - {//done with dismemberment, just waiting to mark owner dismemberable again - if ( cent->gent->aimDebounceTime > cg.time ) - {//still waiting +void CG_Limb(centity_t *cent) { // first time we're drawn, remove us from the owner ent + if (cent->gent && cent->gent->owner && cent->gent->owner->ghoul2.size()) { + gentity_t *owner = cent->gent->owner; + if (cent->gent->aimDebounceTime) { // done with dismemberment, just waiting to mark owner dismemberable again + if (cent->gent->aimDebounceTime > cg.time) { // still waiting return; } - //done! + // done! owner->client->dismembered = qfalse; - //done! + // done! cent->gent->e_clThinkFunc = clThinkF_NULL; - } - else - { -extern cvar_t *g_dismemberment; -extern cvar_t *g_saberRealisticCombat; - //3) turn off w/descendants that surf in original model - if ( cent->gent->target )//stubTagName ) - {//add smoke to cap surf, spawn effect - int newBolt = gi.G2API_AddBolt( &owner->ghoul2[owner->playerModel], cent->gent->target ); - if ( newBolt != -1 ) - { - G_PlayEffect( "blaster/smoke_bolton", owner->playerModel, newBolt, owner->s.number ); + } else { + extern cvar_t *g_dismemberment; + extern cvar_t *g_saberRealisticCombat; + // 3) turn off w/descendants that surf in original model + if (cent->gent->target) // stubTagName ) + { // add smoke to cap surf, spawn effect + int newBolt = gi.G2API_AddBolt(&owner->ghoul2[owner->playerModel], cent->gent->target); + if (newBolt != -1) { + G_PlayEffect("blaster/smoke_bolton", owner->playerModel, newBolt, owner->s.number); } } - if ( cent->gent->target2 )//limbName - {//turn the limb off - gi.G2API_SetSurfaceOnOff( &owner->ghoul2[owner->playerModel], cent->gent->target2, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS + if (cent->gent->target2) // limbName + { // turn the limb off + gi.G2API_SetSurfaceOnOff(&owner->ghoul2[owner->playerModel], cent->gent->target2, 0x00000100); // G2SURFACEFLAG_NODESCENDANTS } - if ( cent->gent->target3 )//stubCapName ) - {//turn on caps - gi.G2API_SetSurfaceOnOff( &owner->ghoul2[owner->playerModel], cent->gent->target3, 0 ); + if (cent->gent->target3) // stubCapName ) + { // turn on caps + gi.G2API_SetSurfaceOnOff(&owner->ghoul2[owner->playerModel], cent->gent->target3, 0); } - if ( owner->weaponModel >= 0 ) - {//the corpse hasn't dropped their weapon - if ( cent->gent->count == BOTH_DISMEMBER_RARM || cent->gent->count == BOTH_DISMEMBER_TORSO1 )//&& ent->s.weapon == WP_SABER && ent->weaponModel != -1 ) - {//FIXME: is this first check needed with this lower one? - gi.G2API_RemoveGhoul2Model( owner->ghoul2, owner->weaponModel ); + if (owner->weaponModel >= 0) { // the corpse hasn't dropped their weapon + if (cent->gent->count == BOTH_DISMEMBER_RARM || + cent->gent->count == BOTH_DISMEMBER_TORSO1) //&& ent->s.weapon == WP_SABER && ent->weaponModel != -1 ) + { // FIXME: is this first check needed with this lower one? + gi.G2API_RemoveGhoul2Model(owner->ghoul2, owner->weaponModel); owner->weaponModel = -1; } } - if ( owner->client->NPC_class == CLASS_PROTOCOL - || g_dismemberment->integer >= 11381138 - || g_saberRealisticCombat->integer ) - { - //wait 100ms before allowing owner to be dismembered again + if (owner->client->NPC_class == CLASS_PROTOCOL || g_dismemberment->integer >= 11381138 || g_saberRealisticCombat->integer) { + // wait 100ms before allowing owner to be dismembered again cent->gent->aimDebounceTime = cg.time + 100; return; - } - else - { - //done! + } else { + // done! cent->gent->e_clThinkFunc = clThinkF_NULL; } } } } -qboolean MatrixMode = qfalse; -void CG_MatrixEffect ( centity_t *cent ) -{ - float MATRIX_EFFECT_TIME = 1000.0f; - //VectorCopy( cent->lerpOrigin, cg.refdef.vieworg ); +qboolean MatrixMode = qfalse; +void CG_MatrixEffect(centity_t *cent) { + float MATRIX_EFFECT_TIME = 1000.0f; + // VectorCopy( cent->lerpOrigin, cg.refdef.vieworg ); float totalElapsedTime = (float)(cg.time - cent->currentState.time); float elapsedTime = totalElapsedTime; - if ( totalElapsedTime > cent->currentState.eventParm //MATRIX_EFFECT_TIME - || (cent->currentState.weapon&&g_entities[cent->currentState.otherEntityNum].client&&g_entities[cent->currentState.otherEntityNum].client->ps.groundEntityNum!=ENTITYNUM_NONE) - || cg.missionStatusShow ) - {//time is up or this is a falling spin and they hit the ground or mission end screen is up - cg.overrides.active &= ~(/*CG_OVERRIDE_3RD_PERSON_ENT|*/CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_ANG|CG_OVERRIDE_3RD_PERSON_POF); - //cg.overrides.thirdPersonEntity = 0; + if (totalElapsedTime > cent->currentState.eventParm // MATRIX_EFFECT_TIME + || (cent->currentState.weapon && g_entities[cent->currentState.otherEntityNum].client && + g_entities[cent->currentState.otherEntityNum].client->ps.groundEntityNum != ENTITYNUM_NONE) || + cg.missionStatusShow) { // time is up or this is a falling spin and they hit the ground or mission end screen is up + cg.overrides.active &= ~(/*CG_OVERRIDE_3RD_PERSON_ENT|*/ CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_ANG | CG_OVERRIDE_3RD_PERSON_POF); + // cg.overrides.thirdPersonEntity = 0; cg.overrides.thirdPersonAngle = 0; cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonRange = 0; - cgi_Cvar_Set( "timescale", "1.0" ); + cgi_Cvar_Set("timescale", "1.0"); MatrixMode = qfalse; cent->gent->e_clThinkFunc = clThinkF_NULL; return; - } - else - { - while ( elapsedTime > MATRIX_EFFECT_TIME ) - { + } else { + while (elapsedTime > MATRIX_EFFECT_TIME) { elapsedTime -= MATRIX_EFFECT_TIME; } } - + MatrixMode = qtrue; - //FIXME: move the position towards them and back? - //cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ENT; - //cg.overrides.thirdPersonEntity = cent->currentState.otherEntityNum; + // FIXME: move the position towards them and back? + // cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ENT; + // cg.overrides.thirdPersonEntity = cent->currentState.otherEntityNum; - //rotate + // rotate cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_ANG; - cg.overrides.thirdPersonAngle = 360.0f*elapsedTime/MATRIX_EFFECT_TIME; + cg.overrides.thirdPersonAngle = 360.0f * elapsedTime / MATRIX_EFFECT_TIME; - if ( !cent->currentState.weapon ) - {//go ahead and do all the slowdown and vert bob stuff - //slowdown - float timescale = (elapsedTime/MATRIX_EFFECT_TIME); - if ( timescale < 0.01f ) - { + if (!cent->currentState.weapon) { // go ahead and do all the slowdown and vert bob stuff + // slowdown + float timescale = (elapsedTime / MATRIX_EFFECT_TIME); + if (timescale < 0.01f) { timescale = 0.01f; } - cgi_Cvar_Set( "timescale", va("%4.2f",timescale) ); + cgi_Cvar_Set("timescale", va("%4.2f", timescale)); - //pitch - //dip - FIXME: use pitchOffet? + // pitch + // dip - FIXME: use pitchOffet? cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_POF; cg.overrides.thirdPersonPitchOffset = cg_thirdPersonPitchOffset.value; - if ( elapsedTime < MATRIX_EFFECT_TIME*0.33f ) - { - cg.overrides.thirdPersonPitchOffset -= 30.0f*elapsedTime/(MATRIX_EFFECT_TIME*0.33); - } - else if ( elapsedTime > MATRIX_EFFECT_TIME*0.66f ) - { - cg.overrides.thirdPersonPitchOffset -= 30.0f*(MATRIX_EFFECT_TIME-elapsedTime)/(MATRIX_EFFECT_TIME*0.33); - } - else - { + if (elapsedTime < MATRIX_EFFECT_TIME * 0.33f) { + cg.overrides.thirdPersonPitchOffset -= 30.0f * elapsedTime / (MATRIX_EFFECT_TIME * 0.33); + } else if (elapsedTime > MATRIX_EFFECT_TIME * 0.66f) { + cg.overrides.thirdPersonPitchOffset -= 30.0f * (MATRIX_EFFECT_TIME - elapsedTime) / (MATRIX_EFFECT_TIME * 0.33); + } else { cg.overrides.thirdPersonPitchOffset -= 30.0f; } - //pull back + // pull back cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = cg_thirdPersonRange.value; - if ( elapsedTime < MATRIX_EFFECT_TIME*0.33 ) - { - cg.overrides.thirdPersonRange += 80.0f*elapsedTime/(MATRIX_EFFECT_TIME*0.33); - } - else if ( elapsedTime > MATRIX_EFFECT_TIME*0.66 ) - { - cg.overrides.thirdPersonRange += 80.0f*(MATRIX_EFFECT_TIME-elapsedTime)/(MATRIX_EFFECT_TIME*0.33); - } - else - { + if (elapsedTime < MATRIX_EFFECT_TIME * 0.33) { + cg.overrides.thirdPersonRange += 80.0f * elapsedTime / (MATRIX_EFFECT_TIME * 0.33); + } else if (elapsedTime > MATRIX_EFFECT_TIME * 0.66) { + cg.overrides.thirdPersonRange += 80.0f * (MATRIX_EFFECT_TIME - elapsedTime) / (MATRIX_EFFECT_TIME * 0.33); + } else { cg.overrides.thirdPersonRange += 80.0f; } - } - else - {//FIXME: if they're on the ground, stop spinning and stop timescale - //FIXME: if they go to the menu, restore timescale - cgi_Cvar_Set( "timescale", "0.25f" ); + } else { // FIXME: if they're on the ground, stop spinning and stop timescale + // FIXME: if they go to the menu, restore timescale + cgi_Cvar_Set("timescale", "0.25f"); } } -static void CG_Think ( centity_t *cent ) -{ - if(!cent->gent) - { +static void CG_Think(centity_t *cent) { + if (!cent->gent) { return; } - CEntity_ThinkFunc(cent); // cent->gent->clThink(cent); + CEntity_ThinkFunc(cent); // cent->gent->clThink(cent); } -static void CG_Clouds( centity_t *cent ) -{ - refEntity_t ent; +static void CG_Clouds(centity_t *cent) { + refEntity_t ent; // create the render entity - memset( &ent, 0, sizeof( ent )); + memset(&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = ent.shaderRGBA[3] = 255; @@ -2049,22 +1790,20 @@ static void CG_Clouds( centity_t *cent ) ent.reType = RT_CLOUDS; - if ( cent->gent->spawnflags & 1 ) // TUBE type, the one with a hole in the middle + if (cent->gent->spawnflags & 1) // TUBE type, the one with a hole in the middle { ent.rotation = cent->gent->random; - ent.renderfx = RF_GROW;// tube flag + ent.renderfx = RF_GROW; // tube flag } - if ( cent->gent->spawnflags & 2 ) // ALT type, uses a different shader - { - ent.customShader = cgi_R_RegisterShader( "gfx/world/haze2" ); - } - else + if (cent->gent->spawnflags & 2) // ALT type, uses a different shader { - ent.customShader = cgi_R_RegisterShader( "gfx/world/haze" ); + ent.customShader = cgi_R_RegisterShader("gfx/world/haze2"); + } else { + ent.customShader = cgi_R_RegisterShader("gfx/world/haze"); } - - cgi_R_AddRefEntityToScene( &ent ); + + cgi_R_AddRefEntityToScene(&ent); } /* @@ -2073,85 +1812,80 @@ CG_AddCEntity =============== */ -static void CG_AddCEntity( centity_t *cent ) -{ +static void CG_AddCEntity(centity_t *cent) { // event-only entities will have been dealt with already - if ( cent->currentState.eType >= ET_EVENTS ) { + if (cent->currentState.eType >= ET_EVENTS) { return; } - //we must have restarted the game - if (!cent->gent) - { + // we must have restarted the game + if (!cent->gent) { return; } // calculate the current origin - CG_CalcEntityLerpPositions( cent ); + CG_CalcEntityLerpPositions(cent); // add automatic effects - CG_EntityEffects( cent ); + CG_EntityEffects(cent); // add local sound set if any - if ( cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] && cent->currentState.eType != ET_MOVER ) - { - CG_AddLocalSet( cent ); + if (cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] && cent->currentState.eType != ET_MOVER) { + CG_AddLocalSet(cent); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // do this before we copy the data to refEnts - if (cent->gent->ghoul2.IsValid()) - { + if (cent->gent->ghoul2.IsValid()) { trap_G2_SetGhoul2ModelIndexes(cent->gent->ghoul2, cgs.model_draw, cgs.skins); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - switch ( cent->currentState.eType ) { + switch (cent->currentState.eType) { default: - CG_Error( "Bad entity type: %i\n", cent->currentState.eType ); + CG_Error("Bad entity type: %i\n", cent->currentState.eType); break; case ET_INVISIBLE: case ET_PUSH_TRIGGER: case ET_TELEPORT_TRIGGER: break; case ET_GENERAL: - CG_General( cent ); + CG_General(cent); break; case ET_PLAYER: - CG_Player( cent ); + CG_Player(cent); break; case ET_ITEM: - CG_Item( cent ); + CG_Item(cent); break; case ET_MISSILE: - CG_Missile( cent ); + CG_Missile(cent); break; case ET_MOVER: - CG_Mover( cent ); + CG_Mover(cent); break; case ET_BEAM: - CG_Beam( cent, 0 ); + CG_Beam(cent, 0); break; case ET_PORTAL: - CG_Portal( cent ); + CG_Portal(cent); break; case ET_SPEAKER: - if ( cent->gent && cent->gent->soundSet && cent->gent->soundSet[0] ) - { + if (cent->gent && cent->gent->soundSet && cent->gent->soundSet[0]) { break; } - CG_Speaker( cent ); + CG_Speaker(cent); break; case ET_THINKER: - CG_General( cent ); - CG_Think( cent ); + CG_General(cent); + CG_Think(cent); break; case ET_CLOUD: // dumb - CG_Clouds( cent ); + CG_Clouds(cent); break; } } @@ -2162,63 +1896,56 @@ CG_AddPacketEntities =============== */ -void CG_AddPacketEntities( void ) { - int num; - centity_t *cent; - playerState_t *ps; +void CG_AddPacketEntities(void) { + int num; + centity_t *cent; + playerState_t *ps; // set cg.frameInterpolation - if ( cg.nextSnap ) - { - int delta; + if (cg.nextSnap) { + int delta; delta = (cg.nextSnap->serverTime - cg.snap->serverTime); - if ( delta == 0 ) - { + if (delta == 0) { cg.frameInterpolation = 0; - } - else - { - cg.frameInterpolation = (float)( cg.time - cg.snap->serverTime ) / delta; + } else { + cg.frameInterpolation = (float)(cg.time - cg.snap->serverTime) / delta; } -//OutputDebugString(va("interp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,cg.nextSnap->serverTime,cg.snap->serverTime)); - } - else - { - cg.frameInterpolation = 0; // actually, it should never be used, because - // no entities should be marked as interpolating -//OutputDebugString(va("noterp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,0,cg.snap->serverTime)); + // OutputDebugString(va("interp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,cg.nextSnap->serverTime,cg.snap->serverTime)); + } else { + cg.frameInterpolation = 0; // actually, it should never be used, because + // no entities should be marked as interpolating + // OutputDebugString(va("noterp %4.2f ct=%6d nt=%6d st=%6d\n",cg.frameInterpolation,cg.time,0,cg.snap->serverTime)); } // the auto-rotating items will all have the same axis cg.autoAngles[0] = 0; - cg.autoAngles[1] = ( cg.time & 2047 ) * 360 / 2048.0f; + cg.autoAngles[1] = (cg.time & 2047) * 360 / 2048.0f; cg.autoAngles[2] = 0; cg.autoAnglesFast[0] = 0; - cg.autoAnglesFast[1] = ( cg.time & 1023 ) * 360 / 1024.0f; + cg.autoAnglesFast[1] = (cg.time & 1023) * 360 / 1024.0f; cg.autoAnglesFast[2] = 0; - AnglesToAxis( cg.autoAngles, cg.autoAxis ); - AnglesToAxis( cg.autoAnglesFast, cg.autoAxisFast ); + AnglesToAxis(cg.autoAngles, cg.autoAxis); + AnglesToAxis(cg.autoAnglesFast, cg.autoAxisFast); // generate and add the entity from the playerstate ps = &cg.predicted_player_state; - PlayerStateToEntityState( ps, &cg_entities[ ps->clientNum ].currentState ); -// cent = &cg_entities[ ps->clientNum ]; // not needed now that player is in the snap packet -// CG_AddCEntity( cent ); // + PlayerStateToEntityState(ps, &cg_entities[ps->clientNum].currentState); + // cent = &cg_entities[ ps->clientNum ]; // not needed now that player is in the snap packet + // CG_AddCEntity( cent ); // // add each entity sent over by the server - for ( num = 0 ; num < cg.snap->numEntities ; num++ ) { - cent = &cg_entities[ cg.snap->entities[ num ].number ]; - CG_AddCEntity( cent ); + for (num = 0; num < cg.snap->numEntities; num++) { + cent = &cg_entities[cg.snap->entities[num].number]; + CG_AddCEntity(cent); } } -//rww - This function is not currently called. Use it as the client-side ROFF -//callback once that's implemented fully. -void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) -{ +// rww - This function is not currently called. Use it as the client-side ROFF +// callback once that's implemented fully. +void CG_ROFF_NotetrackCallback(centity_t *cent, const char *notetrack) { int i = 0, r = 0, objectID = 0, anglesGathered = 0, posoffsetGathered = 0; char type[256]; char argument[512]; @@ -2228,49 +1955,42 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) int addlArgs = 0; vec3_t parsedAngles, parsedOffset, useAngles, useOrigin, forward, right, up; - if (!cent || !notetrack) - { + if (!cent || !notetrack) { return; } - //notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; + // notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (notetrack[i] != ' ') - { //didn't pass in a valid notetrack type, or forgot the argument for it + if (notetrack[i] != ' ') { // didn't pass in a valid notetrack type, or forgot the argument for it return; } i++; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { argument[r] = notetrack[i]; r++; i++; } argument[r] = '\0'; - if (!r) - { + if (!r) { return; } - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -2278,33 +1998,28 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "effect") == 0) - { - if (!addlArgs) - { - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (strcmp(type, "effect") == 0) { + if (!addlArgs) { + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); goto defaultoffsetposition; } i = 0; - while (posoffsetGathered < 3) - { + while (posoffsetGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') - { + while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') { t[r] = addlArg[i]; r++; i++; } t[r] = '\0'; i++; - if (!r) - { //failure.. - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (!r) { // failure.. + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); i = 0; goto defaultoffsetposition; @@ -2313,33 +2028,27 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) posoffsetGathered++; } - if (posoffsetGathered < 3) - { + if (posoffsetGathered < 3) { Q_strncpyz(errMsg, "Offset position argument for 'effect' type is invalid.", sizeof(errMsg)); goto functionend; } i--; - if (addlArg[i] != ' ') - { + if (addlArg[i] != ' ') { addlArgs = 0; } -defaultoffsetposition: + defaultoffsetposition: objectID = theFxScheduler.RegisterEffect(argument); - if (objectID) - { - if (addlArgs) - { //if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE + if (objectID) { + if (addlArgs) { // if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE i++; - while (anglesGathered < 3) - { + while (anglesGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '-') - { + while (addlArg[i] && addlArg[i] != '-') { t[r] = addlArg[i]; r++; i++; @@ -2347,8 +2056,7 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) t[r] = '\0'; i++; - if (!r) - { //failed to get a new part of the vector + if (!r) { // failed to get a new part of the vector anglesGathered = 0; break; } @@ -2357,17 +2065,12 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) anglesGathered++; } - if (anglesGathered) - { + if (anglesGathered) { VectorCopy(parsedAngles, useAngles); - } - else - { //failed to parse angles from the extra argument provided.. + } else { // failed to parse angles from the extra argument provided.. VectorCopy(cent->lerpAngles, useAngles); } - } - else - { //if no constant angles, play in direction entity is facing + } else { // if no constant angles, play in direction entity is facing VectorCopy(cent->lerpAngles, useAngles); } @@ -2375,42 +2078,34 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) VectorCopy(cent->lerpOrigin, useOrigin); - //forward - useOrigin[0] += forward[0]*parsedOffset[0]; - useOrigin[1] += forward[1]*parsedOffset[0]; - useOrigin[2] += forward[2]*parsedOffset[0]; + // forward + useOrigin[0] += forward[0] * parsedOffset[0]; + useOrigin[1] += forward[1] * parsedOffset[0]; + useOrigin[2] += forward[2] * parsedOffset[0]; - //right - useOrigin[0] += right[0]*parsedOffset[1]; - useOrigin[1] += right[1]*parsedOffset[1]; - useOrigin[2] += right[2]*parsedOffset[1]; + // right + useOrigin[0] += right[0] * parsedOffset[1]; + useOrigin[1] += right[1] * parsedOffset[1]; + useOrigin[2] += right[2] * parsedOffset[1]; - //up - useOrigin[0] += up[0]*parsedOffset[2]; - useOrigin[1] += up[1]*parsedOffset[2]; - useOrigin[2] += up[2]*parsedOffset[2]; + // up + useOrigin[0] += up[0] * parsedOffset[2]; + useOrigin[1] += up[1] * parsedOffset[2]; + useOrigin[2] += up[2] * parsedOffset[2]; theFxScheduler.PlayEffect(objectID, useOrigin, useAngles); } - } - else if (strcmp(type, "sound") == 0) - { + } else if (strcmp(type, "sound") == 0) { objectID = cgi_S_RegisterSound(argument); cgi_S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_BODY, objectID); - } - else if (strcmp(type, "loop") == 0) - { //handled server-side + } else if (strcmp(type, "loop") == 0) { // handled server-side return; } - //else if ... - else - { - if (type[0]) - { + // else if ... + else { + if (type[0]) { Com_Printf("^3Warning: \"%s\" is an invalid ROFF notetrack function\n", type); - } - else - { + } else { Com_Printf("^3Warning: Notetrack is missing function and/or arguments\n"); } } diff --git a/codeJK2/cgame/cg_event.cpp b/codeJK2/cgame/cg_event.cpp index cf050a3cc0..bdd933a22f 100644 --- a/codeJK2/cgame/cg_event.cpp +++ b/codeJK2/cgame/cg_event.cpp @@ -29,57 +29,56 @@ along with this program; if not, see . #include "../game/anims.h" -extern void CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ); +extern void CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet); //========================================================================== -qboolean CG_IsFemale( const char *infostring ) { - const char *sex; +qboolean CG_IsFemale(const char *infostring) { + const char *sex; - sex = Info_ValueForKey( infostring, "s" ); + sex = Info_ValueForKey(infostring, "s"); if (sex[0] == 'f' || sex[0] == 'F') return qtrue; return qfalse; } -const char *CG_PlaceString( int rank ) { - static char str[64]; - char *s, *t; +const char *CG_PlaceString(int rank) { + static char str[64]; + char *s, *t; - if ( rank & RANK_TIED_FLAG ) { + if (rank & RANK_TIED_FLAG) { rank &= ~RANK_TIED_FLAG; t = "Tied for "; } else { t = ""; } - if ( rank == 1 ) { - s = "\03341st\0337"; // draw in blue - } else if ( rank == 2 ) { - s = "\03312nd\0337"; // draw in red - } else if ( rank == 3 ) { - s = "\03333rd\0337"; // draw in yellow - } else if ( rank == 11 ) { + if (rank == 1) { + s = "\03341st\0337"; // draw in blue + } else if (rank == 2) { + s = "\03312nd\0337"; // draw in red + } else if (rank == 3) { + s = "\03333rd\0337"; // draw in yellow + } else if (rank == 11) { s = "11th"; - } else if ( rank == 12 ) { + } else if (rank == 12) { s = "12th"; - } else if ( rank == 13 ) { + } else if (rank == 13) { s = "13th"; - } else if ( rank % 10 == 1 ) { + } else if (rank % 10 == 1) { s = va("%ist", rank); - } else if ( rank % 10 == 2 ) { + } else if (rank % 10 == 2) { s = va("%ind", rank); - } else if ( rank % 10 == 3 ) { + } else if (rank % 10 == 3) { s = va("%ird", rank); } else { s = va("%ith", rank); } - Com_sprintf( str, sizeof( str ), "%s%s", t, s ); + Com_sprintf(str, sizeof(str), "%s%s", t, s); return str; } - /* ================ CG_ItemPickup @@ -87,31 +86,26 @@ CG_ItemPickup A new item was picked up this frame ================ */ -void CG_ItemPickup( int itemNum, qboolean bHadItem ) { +void CG_ItemPickup(int itemNum, qboolean bHadItem) { cg.itemPickup = itemNum; cg.itemPickupTime = cg.time; cg.itemPickupBlendTime = cg.time; - if (bg_itemlist[itemNum].classname && bg_itemlist[itemNum].classname[0]) - { + if (bg_itemlist[itemNum].classname && bg_itemlist[itemNum].classname[0]) { char text[1024], data[1024]; - if (cgi_SP_GetStringTextString("INGAME_PICKUPLINE",text, sizeof(text)) ) - { - if ( cgi_SP_GetStringTextString( va("INGAME_%s",bg_itemlist[itemNum].classname ), data, sizeof( data ))) - { - Com_Printf("%s %s\n", text, data ); + if (cgi_SP_GetStringTextString("INGAME_PICKUPLINE", text, sizeof(text))) { + if (cgi_SP_GetStringTextString(va("INGAME_%s", bg_itemlist[itemNum].classname), data, sizeof(data))) { + Com_Printf("%s %s\n", text, data); } } } // see if it should be the grabbed weapon - if ( bg_itemlist[itemNum].giType == IT_WEAPON ) - { + if (bg_itemlist[itemNum].giType == IT_WEAPON) { const int nCurWpn = cg.predicted_player_state.weapon; const int nNewWpn = bg_itemlist[itemNum].giTag; - if ( nCurWpn == WP_SABER || bHadItem) - {//never switch away from the saber! + if (nCurWpn == WP_SABER || bHadItem) { // never switch away from the saber! return; } @@ -124,37 +118,25 @@ void CG_ItemPickup( int itemNum, qboolean bHadItem ) { // NOTE: automatically switching to any weapon you pick up is stupid and annoying and we won't do it. // - if ( nNewWpn == WP_SABER ) - {//always switch to saber + if (nNewWpn == WP_SABER) { // always switch to saber SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; - } - else if (0 == cg_autoswitch.integer) - { + } else if (0 == cg_autoswitch.integer) { // don't switch - } - else if (1 == cg_autoswitch.integer) - { + } else if (1 == cg_autoswitch.integer) { // safe switching - if ( (nNewWpn > nCurWpn) && - !(nNewWpn == WP_DET_PACK) && - !(nNewWpn == WP_TRIP_MINE) && - !(nNewWpn == WP_THERMAL) && - !(nNewWpn == WP_ROCKET_LAUNCHER) ) - { + if ((nNewWpn > nCurWpn) && !(nNewWpn == WP_DET_PACK) && !(nNewWpn == WP_TRIP_MINE) && !(nNewWpn == WP_THERMAL) && + !(nNewWpn == WP_ROCKET_LAUNCHER)) { // switch to new wpn -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; } - } - else if (2 == cg_autoswitch.integer) - { + } else if (2 == cg_autoswitch.integer) { // best - if (nNewWpn > nCurWpn) - { + if (nNewWpn > nCurWpn) { // switch to new wpn -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); cg.weaponSelect = nNewWpn; } @@ -162,23 +144,20 @@ void CG_ItemPickup( int itemNum, qboolean bHadItem ) { } } - /* =============== UseItem =============== */ -extern void CG_ToggleBinoculars( void ); -extern void CG_ToggleLAGoggles( void ); +extern void CG_ToggleBinoculars(void); +extern void CG_ToggleLAGoggles(void); -void UseItem(int itemNum) -{ - centity_t *cent; +void UseItem(int itemNum) { + centity_t *cent; cent = &cg_entities[cg.snap->ps.clientNum]; - switch ( itemNum ) - { + switch (itemNum) { case INV_ELECTROBINOCULARS: CG_ToggleBinoculars(); break; @@ -186,14 +165,12 @@ void UseItem(int itemNum) CG_ToggleLAGoggles(); break; case INV_GOODIE_KEY: - if (cent->gent->client->ps.inventory[INV_GOODIE_KEY]) - { + if (cent->gent->client->ps.inventory[INV_GOODIE_KEY]) { cent->gent->client->ps.inventory[INV_GOODIE_KEY]--; } break; case INV_SECURITY_KEY: - if (cent->gent->client->ps.inventory[INV_SECURITY_KEY]) - { + if (cent->gent->client->ps.inventory[INV_SECURITY_KEY]) { cent->gent->client->ps.inventory[INV_SECURITY_KEY]--; } break; @@ -205,10 +182,9 @@ void UseItem(int itemNum) CG_UseForce =============== */ -static void CG_UseForce( centity_t *cent ) -{ - //FIXME: sound or graphic change or something? - //actual force power action is on game/pm side +static void CG_UseForce(centity_t *cent) { + // FIXME: sound or graphic change or something? + // actual force power action is on game/pm side } /* @@ -216,35 +192,28 @@ static void CG_UseForce( centity_t *cent ) CG_UseItem =============== */ -static void CG_UseItem( centity_t *cent ) -{ - int itemNum; +static void CG_UseItem(centity_t *cent) { + int itemNum; entityState_t *es; es = ¢->currentState; itemNum = cg.inventorySelect; - if ( itemNum < 0 || itemNum > INV_MAX ) - { + if (itemNum < 0 || itemNum > INV_MAX) { itemNum = 0; } // print a message if the local player - if ( es->number == cg.snap->ps.clientNum ) - { - if ( !itemNum ) - { -// CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); - } - else - { -// item = BG_FindItemForHoldable( itemNum ); -// CG_CenterPrint( va("Use %s", item->pickup_name), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + if (es->number == cg.snap->ps.clientNum) { + if (!itemNum) { + // CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + } else { + // item = BG_FindItemForHoldable( itemNum ); + // CG_CenterPrint( va("Use %s", item->pickup_name), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); } } UseItem(itemNum); - } /* @@ -254,230 +223,220 @@ CG_EntityEvent An entity has an event value ============== */ -#define DEBUGNAME(x) if(cg_debugEvents.integer){CG_Printf(x"\n");} -void CG_EntityEvent( centity_t *cent, vec3_t position ) { - entityState_t *es; - int event; - vec3_t axis[3]; - const char *s, *s2; - int clientNum; - //clientInfo_t *ci; +#define DEBUGNAME(x) \ + if (cg_debugEvents.integer) { \ + CG_Printf(x "\n"); \ + } +void CG_EntityEvent(centity_t *cent, vec3_t position) { + entityState_t *es; + int event; + vec3_t axis[3]; + const char *s, *s2; + int clientNum; + // clientInfo_t *ci; es = ¢->currentState; event = es->event & ~EV_EVENT_BITS; - if ( cg_debugEvents.integer ) { - CG_Printf( "ent:%3i event:%3i ", es->number, event ); + if (cg_debugEvents.integer) { + CG_Printf("ent:%3i event:%3i ", es->number, event); } - if ( !event ) { + if (!event) { DEBUGNAME("ZEROEVENT"); return; } - if ( !cent->gent )//|| !cent->gent->client ) + if (!cent->gent) //|| !cent->gent->client ) { return; } - //ci = ¢->gent->client->clientInfo; + // ci = ¢->gent->client->clientInfo; clientNum = cent->gent->s.number; - switch ( event ) { + switch (event) { // // movement generated events // case EV_FOOTSTEP: DEBUGNAME("EV_FOOTSTEP"); if (cg_footsteps.integer) { - if ( cent->gent && cent->gent->s.number == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) - {//Everyone else has keyframed footsteps in animsounds.cfg - cgi_S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_NORMAL ][rand()&3] ); + if (cent->gent && cent->gent->s.number == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) + { // Everyone else has keyframed footsteps in animsounds.cfg + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_NORMAL][rand() & 3]); } } break; case EV_FOOTSTEP_METAL: DEBUGNAME("EV_FOOTSTEP_METAL"); - if (cg_footsteps.integer) - { - if ( cent->gent && cent->gent->s.number == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) - {//Everyone else has keyframed footsteps in animsounds.cfg - cgi_S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.footsteps[ FOOTSTEP_METAL ][rand()&3] ); + if (cg_footsteps.integer) { + if (cent->gent && cent->gent->s.number == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) + { // Everyone else has keyframed footsteps in animsounds.cfg + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_METAL][rand() & 3]); } } break; case EV_FOOTSPLASH: DEBUGNAME("EV_FOOTSPLASH"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SPLASH][rand() & 3]); } break; case EV_FOOTWADE: DEBUGNAME("EV_FOOTWADE"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_WADE ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_WADE][rand() & 3]); } break; case EV_SWIM: DEBUGNAME("EV_SWIM"); if (cg_footsteps.integer) { - cgi_S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_SWIM ][rand()&3] ); + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SWIM][rand() & 3]); } break; - case EV_FALL_SHORT: DEBUGNAME("EV_FALL_SHORT"); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); - if ( clientNum == cg.predicted_player_state.clientNum ) { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -8; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_FALL_MEDIUM: DEBUGNAME("EV_FALL_MEDIUM"); // use normal pain sound - - if ( g_entities[es->number].health <= 0 ) - {//dead - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); - } - else if ( g_entities[es->number].s.weapon == WP_SABER ) - {//jedi - CG_TryPlayCustomSound( NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC ); - } - else - {//still alive - CG_TryPlayCustomSound( NULL, es->number, CHAN_BODY, "*pain100.wav", CS_BASIC ); - } - if ( clientNum == cg.predicted_player_state.clientNum ) { + if (g_entities[es->number].health <= 0) { // dead + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + } else if (g_entities[es->number].s.weapon == WP_SABER) { // jedi + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC); + } else { // still alive + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*pain100.wav", CS_BASIC); + } + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -16; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_FALL_FAR: DEBUGNAME("EV_FALL_FAR"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC ); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, cgs.media.landSound ); - cent->pe.painTime = cg.time; // don't play a pain sound right after this - if ( clientNum == cg.predicted_player_state.clientNum ) { + CG_TryPlayCustomSound(NULL, es->number, CHAN_BODY, "*land1.wav", CS_BASIC); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); + cent->pe.painTime = cg.time; // don't play a pain sound right after this + if (clientNum == cg.predicted_player_state.clientNum) { // smooth landing z changes cg.landChange = -24; cg.landTime = cg.time; } - //FIXME: maybe kick up some dust? + // FIXME: maybe kick up some dust? break; case EV_STEP_4: case EV_STEP_8: case EV_STEP_12: - case EV_STEP_16: // smooth out step up transitions + case EV_STEP_16: // smooth out step up transitions DEBUGNAME("EV_STEP"); - { - float oldStep; - int delta; - int step; - - if ( clientNum != cg.predicted_player_state.clientNum ) { - break; - } - // if we are interpolating, we don't need to smooth steps - if ( cg_timescale.value >= 1.0f ) { - break; - } - // check for stepping up before a previous step is completed - delta = cg.time - cg.stepTime; - if (delta < STEP_TIME) { - oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; - } else { - oldStep = 0; - } + float oldStep; + int delta; + int step; + + if (clientNum != cg.predicted_player_state.clientNum) { + break; + } + // if we are interpolating, we don't need to smooth steps + if (cg_timescale.value >= 1.0f) { + break; + } + // check for stepping up before a previous step is completed + delta = cg.time - cg.stepTime; + if (delta < STEP_TIME) { + oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; + } else { + oldStep = 0; + } - // add this amount - step = 4 * (event - EV_STEP_4 + 1 ); - cg.stepChange = oldStep + step; - if ( cg.stepChange > MAX_STEP_CHANGE ) { - cg.stepChange = MAX_STEP_CHANGE; + // add this amount + step = 4 * (event - EV_STEP_4 + 1); + cg.stepChange = oldStep + step; + if (cg.stepChange > MAX_STEP_CHANGE) { + cg.stepChange = MAX_STEP_CHANGE; + } + cg.stepTime = cg.time; + break; } - cg.stepTime = cg.time; - break; - } case EV_JUMP: DEBUGNAME("EV_JUMP"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC );//CHAN_VOICE + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC); // CHAN_VOICE break; case EV_ROLL: DEBUGNAME("EV_ROLL"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC );//CHAN_VOICE - cgi_S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.rollSound );//CHAN_AUTO - //FIXME: need some sort of body impact on ground sound and maybe kick up some dust? + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*jump1.wav", CS_BASIC); // CHAN_VOICE + cgi_S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.rollSound); // CHAN_AUTO + // FIXME: need some sort of body impact on ground sound and maybe kick up some dust? break; case EV_WATER_TOUCH: DEBUGNAME("EV_WATER_TOUCH"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrInSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrInSound); break; case EV_WATER_LEAVE: DEBUGNAME("EV_WATER_LEAVE"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound); break; case EV_WATER_UNDER: DEBUGNAME("EV_WATER_UNDER"); - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound); break; case EV_WATER_CLEAR: DEBUGNAME("EV_WATER_CLEAR"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*gasp.wav", CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*gasp.wav", CS_BASIC); break; case EV_WATER_GURP1: case EV_WATER_GURP2: DEBUGNAME("EV_WATER_GURPx"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, va("*gurp%d.wav",event-EV_WATER_GURP1+1), CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, va("*gurp%d.wav", event - EV_WATER_GURP1 + 1), CS_BASIC); break; case EV_WATER_DROWN: DEBUGNAME("EV_WATER_DROWN"); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*drown.wav", CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, "*drown.wav", CS_BASIC); break; case EV_ITEM_PICKUP: DEBUGNAME("EV_ITEM_PICKUP"); { - gitem_t *item; - int index; + gitem_t *item; + int index; qboolean bHadItem = qfalse; - index = es->eventParm; // player predicted + index = es->eventParm; // player predicted - if ( (char)index < 0 ) - { + if ((char)index < 0) { index = -(char)index; bHadItem = qtrue; } - if ( index >= bg_numItems ) { + if (index >= bg_numItems) { break; } - item = &bg_itemlist[ index ]; - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( item->pickup_sound ) ); + item = &bg_itemlist[index]; + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound(item->pickup_sound)); // show icon and name on status bar - if ( es->number == cg.snap->ps.clientNum ) { - CG_ItemPickup( index, bHadItem ); + if (es->number == cg.snap->ps.clientNum) { + CG_ItemPickup(index, bHadItem); } } break; @@ -487,84 +446,79 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // case EV_NOAMMO: DEBUGNAME("EV_NOAMMO"); - //cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); - if ( es->number == cg.snap->ps.clientNum ) { + // cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); + if (es->number == cg.snap->ps.clientNum) { CG_OutOfAmmoChange(); } break; case EV_CHANGE_WEAPON: DEBUGNAME("EV_CHANGE_WEAPON"); - if ( es->weapon == WP_SABER ) - { + if (es->weapon == WP_SABER) { /* if ( !cent->gent || !cent->gent->client || (cent->currentState.saberInFlight == qfalse && cent->currentState.saberActive == qtrue) ) { cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" ) ); } */ - if ( cent->gent && cent->gent->client ) - { - //if ( cent->gent->client->ps.saberInFlight ) - {//if it's not in flight or lying around, turn it off! + if (cent->gent && cent->gent->client) { + // if ( cent->gent->client->ps.saberInFlight ) + { // if it's not in flight or lying around, turn it off! cent->currentState.saberActive = qfalse; } } } // FIXME: if it happens that you don't want the saber to play the switch sounds, feel free to modify this bit. - if ( weaponData[cg.weaponSelect].selectSnd[0] ) - { + if (weaponData[cg.weaponSelect].selectSnd[0]) { // custom select sound - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound( weaponData[cg.weaponSelect].selectSnd )); - } - else - { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgi_S_RegisterSound(weaponData[cg.weaponSelect].selectSnd)); + } else { // generic sound - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.selectSound ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.selectSound); } break; case EV_FIRE_WEAPON: DEBUGNAME("EV_FIRE_WEAPON"); - CG_FireWeapon( cent, qfalse ); + CG_FireWeapon(cent, qfalse); break; case EV_ALT_FIRE: DEBUGNAME("EV_ALT_FIRE"); - CG_FireWeapon( cent, qtrue ); + CG_FireWeapon(cent, qtrue); break; case EV_DISRUPTOR_MAIN_SHOT: DEBUGNAME("EV_DISRUPTOR_MAIN_SHOT"); - FX_DisruptorMainShot( cent->currentState.origin2, cent->lerpOrigin ); + FX_DisruptorMainShot(cent->currentState.origin2, cent->lerpOrigin); break; case EV_DISRUPTOR_SNIPER_SHOT: DEBUGNAME("EV_DISRUPTOR_SNIPER_SHOT"); - FX_DisruptorAltShot( cent->currentState.origin2, cent->lerpOrigin, cent->gent->alt_fire ); + FX_DisruptorAltShot(cent->currentState.origin2, cent->lerpOrigin, cent->gent->alt_fire); break; case EV_DISRUPTOR_SNIPER_MISS: DEBUGNAME("EV_DISRUPTOR_SNIPER_MISS"); - FX_DisruptorAltMiss( cent->lerpOrigin, cent->gent->pos1 ); + FX_DisruptorAltMiss(cent->lerpOrigin, cent->gent->pos1); break; case EV_DEMP2_ALT_IMPACT: - FX_DEMP2_AltDetonate( cent->lerpOrigin, es->eventParm ); + FX_DEMP2_AltDetonate(cent->lerpOrigin, es->eventParm); break; -// case EV_POWERUP_SEEKER_FIRE: -// DEBUGNAME("EV_POWERUP_SEEKER_FIRE"); -// CG_FireSeeker( cent ); -// break; + // case EV_POWERUP_SEEKER_FIRE: + // DEBUGNAME("EV_POWERUP_SEEKER_FIRE"); + // CG_FireSeeker( cent ); + // break; case EV_POWERUP_BATTLESUIT: DEBUGNAME("EV_POWERUP_BATTLESUIT"); - if ( es->number == cg.snap->ps.clientNum ) { + if (es->number == cg.snap->ps.clientNum) { cg.powerupActive = PW_BATTLESUIT; cg.powerupTime = cg.time; } - //cgi_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.invulnoProtectSound ); + // cgi_S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.invulnoProtectSound ); break; //================================================================= @@ -574,187 +528,168 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // case EV_REPLICATOR: DEBUGNAME("EV_REPLICATOR"); -// FX_Replicator( cent, position ); + // FX_Replicator( cent, position ); break; case EV_BATTERIES_CHARGED: cg.batteryChargeTime = cg.time + 3000; - cgi_S_StartSound( (float*)vec3_origin, es->number, CHAN_AUTO, cgs.media.batteryChargeSound ); - break; - - case EV_DISINTEGRATION: - { - DEBUGNAME("EV_DISINTEGRATION"); - qboolean makeNotSolid = qfalse; - int disintPW = es->eventParm; - int disintEffect = 0; - int disintLength = 0; - qhandle_t disintSound1 = NULL_HANDLE; - qhandle_t disintSound2 = NULL_HANDLE; - - switch( disintPW ) - { - case PW_DISRUPTION:// sniper rifle - disintEffect = EF_DISINTEGRATION;//ef_ - disintSound1 = cgs.media.disintegrateSound;//with scream - disintSound2 = cgs.media.disintegrate2Sound;//no scream - disintLength = 2000; - makeNotSolid = qtrue; - break; -/* case PW_SHOCKED:// arc welder - disintEffect = EF_DISINT_1;//ef_ - disintSound1 = NULL;//with scream - disintSound2 = NULL;//no scream - disintSound3 = NULL;//with inhuman scream - disintLength = 4000; - break; -*/ - default: - return; - break; - } + cgi_S_StartSound((float *)vec3_origin, es->number, CHAN_AUTO, cgs.media.batteryChargeSound); + break; + + case EV_DISINTEGRATION: { + DEBUGNAME("EV_DISINTEGRATION"); + qboolean makeNotSolid = qfalse; + int disintPW = es->eventParm; + int disintEffect = 0; + int disintLength = 0; + qhandle_t disintSound1 = NULL_HANDLE; + qhandle_t disintSound2 = NULL_HANDLE; + + switch (disintPW) { + case PW_DISRUPTION: // sniper rifle + disintEffect = EF_DISINTEGRATION; // ef_ + disintSound1 = cgs.media.disintegrateSound; // with scream + disintSound2 = cgs.media.disintegrate2Sound; // no scream + disintLength = 2000; + makeNotSolid = qtrue; + break; + /* case PW_SHOCKED:// arc welder + disintEffect = EF_DISINT_1;//ef_ + disintSound1 = NULL;//with scream + disintSound2 = NULL;//no scream + disintSound3 = NULL;//with inhuman scream + disintLength = 4000; + break; + */ + default: + return; + break; + } - if ( cent->gent->owner ) - { - cent->gent->owner->fx_time = cg.time; - if ( cent->gent->owner->client ) - { - if ( disintSound1 && disintSound2 ) - {//play an extra sound - // listed all the non-humanoids, because there's a lot more humanoids - class_t npc_class = cent->gent->owner->client->NPC_class; - if( npc_class != CLASS_ATST && npc_class != CLASS_GONK && - npc_class != CLASS_INTERROGATOR && npc_class != CLASS_MARK1 && - npc_class != CLASS_MARK2 && npc_class != CLASS_MOUSE && - npc_class != CLASS_PROBE && npc_class != CLASS_PROTOCOL && - npc_class != CLASS_R2D2 && npc_class != CLASS_R5D2 && - npc_class != CLASS_SEEKER && npc_class != CLASS_SENTRY) - {//Only the humanoids scream - cgi_S_StartSound ( NULL, cent->gent->owner->s.number, CHAN_VOICE, disintSound1 ); - } - // no more forge or 8472 + if (cent->gent->owner) { + cent->gent->owner->fx_time = cg.time; + if (cent->gent->owner->client) { + if (disintSound1 && disintSound2) { // play an extra sound + // listed all the non-humanoids, because there's a lot more humanoids + class_t npc_class = cent->gent->owner->client->NPC_class; + if (npc_class != CLASS_ATST && npc_class != CLASS_GONK && npc_class != CLASS_INTERROGATOR && npc_class != CLASS_MARK1 && + npc_class != CLASS_MARK2 && npc_class != CLASS_MOUSE && npc_class != CLASS_PROBE && npc_class != CLASS_PROTOCOL && + npc_class != CLASS_R2D2 && npc_class != CLASS_R5D2 && npc_class != CLASS_SEEKER && + npc_class != CLASS_SENTRY) { // Only the humanoids scream + cgi_S_StartSound(NULL, cent->gent->owner->s.number, CHAN_VOICE, disintSound1); + } + // no more forge or 8472 // else if ( cent->gent->owner->client->playerTeam == TEAM_FORGE || // cent->gent->owner->client->playerTeam == TEAM_8472 ) // { // cgi_S_StartSound ( NULL, cent->gent->s.number, CHAN_VOICE, disintSound3 ); // } - else - { - cgi_S_StartSound ( NULL, cent->gent->s.number, CHAN_AUTO, disintSound2 ); - } - } - cent->gent->owner->s.powerups |= ( 1 << disintPW ); - cent->gent->owner->client->ps.powerups[disintPW] = cg.time + disintLength; - - // Things that are being disintegrated should probably not be solid... - if ( makeNotSolid && cent->gent->owner->client->playerTeam != TEAM_NEUTRAL ) - { - cent->gent->contents = CONTENTS_NONE; + else { + cgi_S_StartSound(NULL, cent->gent->s.number, CHAN_AUTO, disintSound2); } } - else - { - cent->gent->owner->s.eFlags = disintEffect;//FIXME: |= ? - cent->gent->owner->delay = cg.time + disintLength; + cent->gent->owner->s.powerups |= (1 << disintPW); + cent->gent->owner->client->ps.powerups[disintPW] = cg.time + disintLength; + + // Things that are being disintegrated should probably not be solid... + if (makeNotSolid && cent->gent->owner->client->playerTeam != TEAM_NEUTRAL) { + cent->gent->contents = CONTENTS_NONE; } + } else { + cent->gent->owner->s.eFlags = disintEffect; // FIXME: |= ? + cent->gent->owner->delay = cg.time + disintLength; } } - break; + } break; // This does not necessarily have to be from a grenade... case EV_GRENADE_BOUNCE: DEBUGNAME("EV_GRENADE_BOUNCE"); - CG_BounceEffect( cent, es->weapon, position, cent->gent->pos1 ); + CG_BounceEffect(cent, es->weapon, position, cent->gent->pos1); break; - // - // missile impacts - // + // + // missile impacts + // case EV_MISSILE_STICK: DEBUGNAME("EV_MISSILE_STICK"); - CG_MissileStick( cent, es->weapon, position ); + CG_MissileStick(cent, es->weapon, position); break; case EV_MISSILE_HIT: DEBUGNAME("EV_MISSILE_HIT"); - CG_MissileHitPlayer( cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire ); + CG_MissileHitPlayer(cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire); break; case EV_MISSILE_MISS: DEBUGNAME("EV_MISSILE_MISS"); - CG_MissileHitWall( cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire ); + CG_MissileHitWall(cent, es->weapon, position, cent->gent->pos1, cent->gent->alt_fire); break; case EV_BMODEL_SOUND: DEBUGNAME("EV_BMODEL_SOUND"); - cgi_S_StartSound( NULL, es->number, CHAN_AUTO, es->eventParm ); + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, es->eventParm); break; case EV_GENERAL_SOUND: DEBUGNAME("EV_GENERAL_SOUND"); - if ( cgs.sound_precache[ es->eventParm ] ) - { - cgi_S_StartSound (NULL, es->number, CHAN_AUTO, cgs.sound_precache[ es->eventParm ] ); - } - else - { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, s, CS_BASIC ); + if (cgs.sound_precache[es->eventParm]) { + cgi_S_StartSound(NULL, es->number, CHAN_AUTO, cgs.sound_precache[es->eventParm]); + } else { + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + CG_TryPlayCustomSound(NULL, es->number, CHAN_AUTO, s, CS_BASIC); } break; - case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes + case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes DEBUGNAME("EV_GLOBAL_SOUND"); - if ( cgs.sound_precache[ es->eventParm ] ) { - cgi_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[ es->eventParm ] ); + if (cgs.sound_precache[es->eventParm]) { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.sound_precache[es->eventParm]); } else { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - CG_TryPlayCustomSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, s, CS_BASIC ); + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + CG_TryPlayCustomSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, s, CS_BASIC); } break; case EV_DRUGGED: DEBUGNAME("EV_DRUGGED"); - if ( cent->gent && cent->gent->owner && cent->gent->owner->s.number == 0 ) - { - // Only allow setting up the wonky vision on the player..do it for 10 seconds...must be synchronized with calcs done in cg_view. Just search for cg.wonkyTime to find 'em. + if (cent->gent && cent->gent->owner && cent->gent->owner->s.number == 0) { + // Only allow setting up the wonky vision on the player..do it for 10 seconds...must be synchronized with calcs done in cg_view. Just search for + // cg.wonkyTime to find 'em. cg.wonkyTime = cg.time + 10000; } break; - case EV_PAIN: - { - char *snd; + case EV_PAIN: { + char *snd; const int health = es->eventParm; - if ( cent->gent && cent->gent->NPC && (cent->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT) ) - { + if (cent->gent && cent->gent->NPC && (cent->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { return; } - //FIXME: don't do this if we're falling to our deaths... + // FIXME: don't do this if we're falling to our deaths... DEBUGNAME("EV_PAIN"); // don't do more than two pain sounds a second - if ( cg.time - cent->pe.painTime < 500 ) { + if (cg.time - cent->pe.painTime < 500) { return; } - if ( health < 25 ) { + if (health < 25) { snd = "*pain100.wav"; - } else if ( health < 50 ) { + } else if (health < 50) { snd = "*pain75.wav"; - } else if ( health < 75 ) { + } else if (health < 75) { snd = "*pain50.wav"; } else { snd = "*pain25.wav"; } - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, snd, CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, snd, CS_BASIC); // save pain time for programitic twitch animation cent->pe.painTime = cg.time; cent->pe.painDirection ^= 1; - } - break; + } break; case EV_DEATH1: case EV_DEATH2: @@ -766,123 +701,112 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { return; } */ - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*death%i.wav", event - EV_DEATH1 + 1), CS_BASIC ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*death%i.wav", event - EV_DEATH1 + 1), CS_BASIC); break; // Called by the FxRunner entity...usually for Environmental FX Events case EV_PLAY_EFFECT: DEBUGNAME("EV_PLAY_EFFECT"); - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); -// Ghoul2 Insert Start - if (es->boltInfo != 0) - { - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, es->boltInfo, -1 ); - } - else - { - VectorCopy( cent->gent->pos3, axis[0] ); - VectorCopy( cent->gent->pos4, axis[1] ); - CrossProduct( axis[0], axis[1], axis[2] ); + s = CG_ConfigString(CS_EFFECTS + es->eventParm); + // Ghoul2 Insert Start + if (es->boltInfo != 0) { + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, es->boltInfo, -1); + } else { + VectorCopy(cent->gent->pos3, axis[0]); + VectorCopy(cent->gent->pos4, axis[1]); + CrossProduct(axis[0], axis[1], axis[2]); // the entNum the effect may be attached to - if ( es->otherEntityNum ) - { - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, -1, es->otherEntityNum ); - } - else - { - theFxScheduler.PlayEffect( s, cent->lerpOrigin, axis, -1, -1 ); + if (es->otherEntityNum) { + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, -1, es->otherEntityNum); + } else { + theFxScheduler.PlayEffect(s, cent->lerpOrigin, axis, -1, -1); } } -// Ghoul2 Insert End + // Ghoul2 Insert End break; // play an effect bolted onto a muzzle case EV_PLAY_MUZZLE_EFFECT: DEBUGNAME("EV_PLAY_MUZZLE_EFFECT"); - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); + s = CG_ConfigString(CS_EFFECTS + es->eventParm); - theFxScheduler.PlayEffect( s, es->otherEntityNum ); + theFxScheduler.PlayEffect(s, es->otherEntityNum); break; case EV_TARGET_BEAM_DRAW: DEBUGNAME("EV_TARGET_BEAM_DRAW"); - if ( cent->gent ) - { - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); + if (cent->gent) { + s = CG_ConfigString(CS_EFFECTS + es->eventParm); - if ( s && s[0] ) - { - if ( cent->gent->delay ) - { - s2 = CG_ConfigString( CS_EFFECTS + cent->gent->delay ); - } - else - { + if (s && s[0]) { + if (cent->gent->delay) { + s2 = CG_ConfigString(CS_EFFECTS + cent->gent->delay); + } else { s2 = NULL; } - CG_DrawTargetBeam( cent->lerpOrigin, cent->gent->s.origin2, cent->gent->pos1, s, s2 ); - } -/* else - { - int gack = 0; // this is bad if it get's here + CG_DrawTargetBeam(cent->lerpOrigin, cent->gent->s.origin2, cent->gent->pos1, s, s2); } -*/ + /* else + { + int gack = 0; // this is bad if it get's here + } + */ } break; - case EV_ANGER1: //Say when acquire an enemy when didn't have one before + case EV_ANGER1: // Say when acquire an enemy when didn't have one before case EV_ANGER2: case EV_ANGER3: DEBUGNAME("EV_ANGERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT); break; - case EV_VICTORY1: //Say when killed an enemy + case EV_VICTORY1: // Say when killed an enemy case EV_VICTORY2: case EV_VICTORY3: DEBUGNAME("EV_VICTORYx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT); break; - case EV_CONFUSE1: //Say when confused + case EV_CONFUSE1: // Say when confused case EV_CONFUSE2: case EV_CONFUSE3: DEBUGNAME("EV_CONFUSEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT); break; - case EV_PUSHED1: //Say when pushed + case EV_PUSHED1: // Say when pushed case EV_PUSHED2: case EV_PUSHED3: DEBUGNAME("EV_PUSHEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT); break; - case EV_CHOKE1: //Say when choking + case EV_CHOKE1: // Say when choking case EV_CHOKE2: case EV_CHOKE3: DEBUGNAME("EV_CHOKEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT); break; - case EV_FFWARN: //Warn ally to stop shooting you + case EV_FFWARN: // Warn ally to stop shooting you DEBUGNAME("EV_FFWARN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT); break; - case EV_FFTURN: //Turn on ally after being shot by them + case EV_FFTURN: // Turn on ally after being shot by them DEBUGNAME("EV_FFTURN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT); break; - //extra sounds for ST + // extra sounds for ST case EV_CHASE1: case EV_CHASE2: case EV_CHASE3: DEBUGNAME("EV_CHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA); break; case EV_COVER1: case EV_COVER2: @@ -890,7 +814,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_COVER4: case EV_COVER5: DEBUGNAME("EV_COVERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA); break; case EV_DETECTED1: case EV_DETECTED2: @@ -898,46 +822,46 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DETECTED4: case EV_DETECTED5: DEBUGNAME("EV_DETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA); break; case EV_GIVEUP1: case EV_GIVEUP2: case EV_GIVEUP3: case EV_GIVEUP4: DEBUGNAME("EV_GIVEUPx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA); break; case EV_LOOK1: case EV_LOOK2: DEBUGNAME("EV_LOOKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA); break; case EV_LOST1: DEBUGNAME("EV_LOST1"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*lost1.wav", CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*lost1.wav", CS_EXTRA); break; case EV_OUTFLANK1: case EV_OUTFLANK2: DEBUGNAME("EV_OUTFLANKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA); break; case EV_ESCAPING1: case EV_ESCAPING2: case EV_ESCAPING3: DEBUGNAME("EV_ESCAPINGx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA); break; case EV_SIGHT1: case EV_SIGHT2: case EV_SIGHT3: DEBUGNAME("EV_SIGHTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA); break; case EV_SOUND1: case EV_SOUND2: case EV_SOUND3: DEBUGNAME("EV_SOUNDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA); break; case EV_SUSPICIOUS1: case EV_SUSPICIOUS2: @@ -945,89 +869,89 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SUSPICIOUS4: case EV_SUSPICIOUS5: DEBUGNAME("EV_SUSPICIOUSx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA); break; - //extra sounds for Jedi + // extra sounds for Jedi case EV_COMBAT1: case EV_COMBAT2: case EV_COMBAT3: DEBUGNAME("EV_COMBATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI); break; case EV_JDETECTED1: case EV_JDETECTED2: case EV_JDETECTED3: DEBUGNAME("EV_JDETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI); break; case EV_TAUNT1: case EV_TAUNT2: case EV_TAUNT3: DEBUGNAME("EV_TAUNTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI); break; case EV_JCHASE1: case EV_JCHASE2: case EV_JCHASE3: DEBUGNAME("EV_JCHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI); break; case EV_JLOST1: case EV_JLOST2: case EV_JLOST3: DEBUGNAME("EV_JLOSTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI); break; case EV_DEFLECT1: case EV_DEFLECT2: case EV_DEFLECT3: DEBUGNAME("EV_DEFLECTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI); break; case EV_GLOAT1: case EV_GLOAT2: case EV_GLOAT3: DEBUGNAME("EV_GLOATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI); break; case EV_PUSHFAIL: DEBUGNAME("EV_PUSHFAIL"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*pushfail.wav", CS_JEDI ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*pushfail.wav", CS_JEDI); break; case EV_USE_FORCE: DEBUGNAME("EV_USE_FORCEITEM"); - CG_UseForce( cent ); + CG_UseForce(cent); break; case EV_USE_ITEM: DEBUGNAME("EV_USE_ITEM"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_INV_BINOCULARS: DEBUGNAME("EV_USE_INV_BINOCULARS"); - UseItem(INV_ELECTROBINOCULARS ); + UseItem(INV_ELECTROBINOCULARS); break; case EV_USE_INV_BACTA: DEBUGNAME("EV_USE_INV_BACTA"); - UseItem(INV_BACTA_CANISTER ); + UseItem(INV_BACTA_CANISTER); break; case EV_USE_INV_SEEKER: DEBUGNAME("EV_USE_INV_SEEKER"); - UseItem(INV_SEEKER ); + UseItem(INV_SEEKER); break; case EV_USE_INV_LIGHTAMP_GOGGLES: DEBUGNAME("EV_USE_INV_LIGHTAMP_GOGGLES"); - UseItem(INV_LIGHTAMP_GOGGLES ); + UseItem(INV_LIGHTAMP_GOGGLES); break; case EV_USE_INV_SENTRY: DEBUGNAME("EV_USE_INV_SENTRY"); - UseItem(INV_SENTRY ); + UseItem(INV_SENTRY); break; case EV_DEBUG_LINE: @@ -1037,43 +961,40 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { default: DEBUGNAME("UNKNOWN"); - CG_Error( "Unknown event: %i", event ); + CG_Error("Unknown event: %i", event); break; } - } - /* ============== CG_CheckEvents ============== */ -void CG_CheckEvents( centity_t *cent ) { +void CG_CheckEvents(centity_t *cent) { // check for event-only entities - if ( cent->currentState.eType > ET_EVENTS ) { - if ( cent->previousEvent ) { - return; // already fired + if (cent->currentState.eType > ET_EVENTS) { + if (cent->previousEvent) { + return; // already fired } cent->previousEvent = 1; cent->currentState.event = cent->currentState.eType - ET_EVENTS; } else { // check for events riding with another entity - if ( cent->currentState.event == cent->previousEvent ) { + if (cent->currentState.event == cent->previousEvent) { return; } cent->previousEvent = cent->currentState.event; - if ( ( cent->currentState.event & ~EV_EVENT_BITS ) == 0 ) { + if ((cent->currentState.event & ~EV_EVENT_BITS) == 0) { return; } } // calculate the position at exactly the frame time - EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); - CG_SetEntitySoundPosition( cent ); + EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); + CG_SetEntitySoundPosition(cent); - CG_EntityEvent( cent, cent->lerpOrigin ); + CG_EntityEvent(cent, cent->lerpOrigin); } - diff --git a/codeJK2/cgame/cg_info.cpp b/codeJK2/cgame/cg_info.cpp index e8a6b5be5d..f268c3aacc 100644 --- a/codeJK2/cgame/cg_info.cpp +++ b/codeJK2/cgame/cg_info.cpp @@ -28,20 +28,9 @@ along with this program; if not, see . static const int missionYpos = 79; -const char *showLoadPowersName[] = -{ - "INGAME_HEAL2", - "INGAME_JUMP2", - "INGAME_SPEED2", - "INGAME_PUSH2", - "INGAME_PULL2", - "INGAME_MINDTRICK2", - "INGAME_GRIP2", - "INGAME_LIGHTNING2", - "INGAME_SABER_THROW2", - "INGAME_SABER_OFFENSE2", - "INGAME_SABER_DEFENSE2", - NULL, +const char *showLoadPowersName[] = { + "INGAME_HEAL2", "INGAME_JUMP2", "INGAME_SPEED2", "INGAME_PUSH2", "INGAME_PULL2", "INGAME_MINDTRICK2", + "INGAME_GRIP2", "INGAME_LIGHTNING2", "INGAME_SABER_THROW2", "INGAME_SABER_OFFENSE2", "INGAME_SABER_DEFENSE2", NULL, }; // Hack to see if the graphics objectives have been printed. @@ -52,79 +41,70 @@ int obj_graphics[4]; MissionPrint_Line ==================== */ -static void MissionPrint_Line(const int color, const int objectIndex, int &missionYcnt) -{ - char *str,*strBegin; - int y,pixelLen,charLen; - char holdText[1024] ; +static void MissionPrint_Line(const int color, const int objectIndex, int &missionYcnt) { + char *str, *strBegin; + int y, pixelLen, charLen; + char holdText[1024]; char finalText[2048]; - qhandle_t graphic; + qhandle_t graphic; - int iYPixelsPerLine = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f) * (cgi_Language_IsAsian() ? 1.2f : 1.0f ); + int iYPixelsPerLine = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f) * (cgi_Language_IsAsian() ? 1.2f : 1.0f); - cgi_SP_GetStringText( PACKAGE_OBJECTIVES<<8|objectIndex , finalText, sizeof(finalText) ); + cgi_SP_GetStringText(PACKAGE_OBJECTIVES << 8 | objectIndex, finalText, sizeof(finalText)); pixelLen = cgi_R_Font_StrLenPixels(finalText, cgs.media.qhFontMedium, 1.0f); str = finalText; -/* CG_DisplayBoxedText(70,50,500,300,finalText, - cgs.media.qhFontSmall, - 1.0f, - colorTable[color] - ); -*/ - if (pixelLen < 500) // One shot - small enough to print entirely on one line + /* CG_DisplayBoxedText(70,50,500,300,finalText, + cgs.media.qhFontSmall, + 1.0f, + colorTable[color] + ); + */ + if (pixelLen < 500) // One shot - small enough to print entirely on one line { - y =missionYpos + (iYPixelsPerLine * (missionYcnt)); - if (obj_graphics[0]) - { + y = missionYpos + (iYPixelsPerLine * (missionYcnt)); + if (obj_graphics[0]) { y += 32 + 4; } - if (obj_graphics[1]) - { + if (obj_graphics[1]) { y += 32 + 4; } - if (obj_graphics[2]) - { + if (obj_graphics[2]) { y += 32 + 4; } - //CG_DrawProportionalString(108, y,str, CG_SMALLFONT, colorTable[color] ); - cgi_R_Font_DrawString (108, y, str, colorTable[color], cgs.media.qhFontMedium, -1, 1.0f); + // CG_DrawProportionalString(108, y,str, CG_SMALLFONT, colorTable[color] ); + cgi_R_Font_DrawString(108, y, str, colorTable[color], cgs.media.qhFontMedium, -1, 1.0f); ++missionYcnt; } // Text is too long, break into lines. - else - { + else { char holdText2[2]; pixelLen = 0; charLen = 0; holdText2[1] = '\0'; strBegin = str; - while( *str ) - { + while (*str) { holdText2[0] = *str; pixelLen += cgi_R_Font_StrLenPixels(holdText2, cgs.media.qhFontMedium, 1.0f); pixelLen += 2; // For kerning ++charLen; - if (pixelLen > 500 ) - { //Reached max length of this line - //step back until we find a space - while ((charLen) && (*str != ' ' )) - { + if (pixelLen > 500) { // Reached max length of this line + // step back until we find a space + while ((charLen) && (*str != ' ')) { --str; --charLen; } - if (*str==' ') - { - ++str; // To get past space + if (*str == ' ') { + ++str; // To get past space } - Q_strncpyz( holdText, strBegin, charLen); + Q_strncpyz(holdText, strBegin, charLen); holdText[charLen] = '\0'; strBegin = str; pixelLen = 0; @@ -132,65 +112,51 @@ static void MissionPrint_Line(const int color, const int objectIndex, int &missi y = missionYpos + (iYPixelsPerLine * missionYcnt); - CG_DrawProportionalString(108, y, holdText, CG_SMALLFONT, colorTable[color] ); + CG_DrawProportionalString(108, y, holdText, CG_SMALLFONT, colorTable[color]); ++missionYcnt; - } - else if (*(str+1) == '\0') - { + } else if (*(str + 1) == '\0') { ++charLen; y = missionYpos + (iYPixelsPerLine * missionYcnt); - Q_strncpyz( holdText, strBegin, charLen); - CG_DrawProportionalString(108, y, holdText, CG_SMALLFONT, colorTable[color] ); + Q_strncpyz(holdText, strBegin, charLen); + CG_DrawProportionalString(108, y, holdText, CG_SMALLFONT, colorTable[color]); ++missionYcnt; break; } - ++str; - - - } + ++str; + } } // Special case hack - if (objectIndex == DOOM_COMM_OBJ4) - { + if (objectIndex == DOOM_COMM_OBJ4) { y = missionYpos + (iYPixelsPerLine * missionYcnt); graphic = cgi_R_RegisterShaderNoMip("textures/system/securitycode"); - CG_DrawPic( 320 - (128/2), y+8, 128, 32, graphic ); + CG_DrawPic(320 - (128 / 2), y + 8, 128, 32, graphic); obj_graphics[0] = qtrue; - } - else if (objectIndex == KEJIM_POST_OBJ3) - { + } else if (objectIndex == KEJIM_POST_OBJ3) { y = missionYpos + (iYPixelsPerLine * missionYcnt); graphic = cgi_R_RegisterShaderNoMip("textures/system/securitycode_red"); - CG_DrawPic( 320 - (32/2), y+8, 32, 32, graphic ); + CG_DrawPic(320 - (32 / 2), y + 8, 32, 32, graphic); obj_graphics[1] = qtrue; - } - else if (objectIndex == KEJIM_POST_OBJ4) - { - y =missionYpos + (iYPixelsPerLine * missionYcnt); - if (obj_graphics[1]) - { + } else if (objectIndex == KEJIM_POST_OBJ4) { + y = missionYpos + (iYPixelsPerLine * missionYcnt); + if (obj_graphics[1]) { y += 32 + 4; } graphic = cgi_R_RegisterShaderNoMip("textures/system/securitycode_green"); - CG_DrawPic( 320 - (32/2), y+8, 32, 32, graphic ); + CG_DrawPic(320 - (32 / 2), y + 8, 32, 32, graphic); obj_graphics[2] = qtrue; - } - else if (objectIndex == KEJIM_POST_OBJ5) - { - y =missionYpos + (iYPixelsPerLine * missionYcnt); - if (obj_graphics[1]) - { + } else if (objectIndex == KEJIM_POST_OBJ5) { + y = missionYpos + (iYPixelsPerLine * missionYcnt); + if (obj_graphics[1]) { y += 32 + 4; } - if (obj_graphics[2]) - { + if (obj_graphics[2]) { y += 32 + 4; } graphic = cgi_R_RegisterShaderNoMip("textures/system/securitycode_blue"); - CG_DrawPic( 320 - (32/2), y+8, 32, 32, graphic ); + CG_DrawPic(320 - (32 / 2), y + 8, 32, 32, graphic); obj_graphics[3] = qtrue; } } @@ -200,18 +166,17 @@ static void MissionPrint_Line(const int color, const int objectIndex, int &missi MissionInformation_Draw ==================== */ -void MissionInformation_Draw( centity_t *cent ) -{ - int i,totalY; - int iYPixelsPerLine = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f) * (cgi_Language_IsAsian() ? 1.2f : 1.0f ); +void MissionInformation_Draw(centity_t *cent) { + int i, totalY; + int iYPixelsPerLine = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f) * (cgi_Language_IsAsian() ? 1.2f : 1.0f); - missionInfo_Updated = qfalse; // This will stop the text from flashing + missionInfo_Updated = qfalse; // This will stop the text from flashing cg.missionInfoFlashTime = 0; // Frame - char text[1024]={0}; - cgi_SP_GetStringTextString( "INGAME_OBJECTIVES", text, sizeof(text) ); - cgi_R_Font_DrawString (96, missionYpos-23, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); + char text[1024] = {0}; + cgi_SP_GetStringTextString("INGAME_OBJECTIVES", text, sizeof(text)); + cgi_R_Font_DrawString(96, missionYpos - 23, text, colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); int missionYcnt = 0; @@ -219,43 +184,35 @@ void MissionInformation_Draw( centity_t *cent ) // Print active objectives cgi_R_SetColor(colorTable[CT_BLUE3]); - for (i=0;igent->client->sess.mission_objectives[i].display) - { - totalY = missionYpos + (iYPixelsPerLine * (missionYcnt))+(iYPixelsPerLine/2); - if (obj_graphics[0]) - { + for (i = 0; i < MAX_OBJECTIVES; ++i) { + if (cent->gent->client->sess.mission_objectives[i].display) { + totalY = missionYpos + (iYPixelsPerLine * (missionYcnt)) + (iYPixelsPerLine / 2); + if (obj_graphics[0]) { totalY += 32 + 4; } - if (obj_graphics[1]) - { + if (obj_graphics[1]) { totalY += 32 + 4; } - if (obj_graphics[2]) - { + if (obj_graphics[2]) { totalY += 32 + 4; } - if (obj_graphics[3]) - { + if (obj_graphics[3]) { totalY += 32 + 4; } // OBJECTIVE_STAT_PENDING - CG_DrawPic( 88, totalY, 16, 16, cgs.media.messageObjCircle); // Circle in front - if (cent->gent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_SUCCEEDED) - { - CG_DrawPic( 88, totalY, 16, 16, cgs.media.messageLitOn); // Center Dot + CG_DrawPic(88, totalY, 16, 16, cgs.media.messageObjCircle); // Circle in front + if (cent->gent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_SUCCEEDED) { + CG_DrawPic(88, totalY, 16, 16, cgs.media.messageLitOn); // Center Dot } - MissionPrint_Line(CT_BLUE3, i, missionYcnt ); + MissionPrint_Line(CT_BLUE3, i, missionYcnt); } } - if (!missionYcnt) - { - cgi_SP_GetStringTextString( "INGAME_OBJNONE", text, sizeof(text) ); -// CG_DrawProportionalString(108, missionYpos, text, CG_SMALLFONT, colorTable[CT_LTBLUE1] ); - cgi_R_Font_DrawString (108, missionYpos, text, colorTable[CT_LTBLUE1], cgs.media.qhFontMedium, -1, 1.0f); + if (!missionYcnt) { + cgi_SP_GetStringTextString("INGAME_OBJNONE", text, sizeof(text)); + // CG_DrawProportionalString(108, missionYpos, text, CG_SMALLFONT, colorTable[CT_LTBLUE1] ); + cgi_R_Font_DrawString(108, missionYpos, text, colorTable[CT_LTBLUE1], cgs.media.qhFontMedium, -1, 1.0f); } } @@ -272,7 +229,7 @@ static void CG_DrawForceCount( const int force, int x, float *y, const int pad,q sscanf( s, "%d",&val ); - if ((val<1) || (val> NUM_FORCE_POWERS)) + if ((val<1) || (val> NUM_FORCE_POWERS)) { return; } @@ -293,7 +250,7 @@ static void CG_DrawForceCount( const int force, int x, float *y, const int pad,q for ( int i = 0; i < val; i++ ) { - CG_DrawPic( x - iconSize - i * (iconSize + 10) , *y, iconSize, iconSize, force_icons[force] ); + CG_DrawPic( x - iconSize - i * (iconSize + 10) , *y, iconSize, iconSize, force_icons[force] ); } } @@ -333,9 +290,9 @@ static void CG_LoadScreen_PersonalInfo(void) CG_DrawForceCount( FP_SABERTHROW, x, &y, pad,&hasForcePowers ); CG_DrawForceCount( FP_SABER_OFFENSE, x, &y, pad,&hasForcePowers ); CG_DrawForceCount( FP_SABER_DEFENSE, x, &y, pad,&hasForcePowers ); - + if (hasForcePowers) - { + { cgi_SP_GetStringTextString( "INGAME_CURRENTFORCEPOWERS", text, sizeof(text) ); CG_DrawProportionalString( 200, 65, text, CG_CENTER | CG_BIGFONT, colorTable[CT_WHITE] ); } @@ -351,16 +308,15 @@ static void CG_LoadScreen_PersonalInfo(void) } */ -static void CG_LoadBar(void) -{ +static void CG_LoadBar(void) { const int numticks = 9, tickwidth = 40, tickheight = 8; const int tickpadx = 20, tickpady = 12; const int capwidth = 8; - const int barwidth = numticks*tickwidth+tickpadx*2+capwidth*2, barleft = ((640-barwidth)/2); - const int barheight = tickheight + tickpady*2, bartop = 480-barheight; - const int capleft = barleft+tickpadx, tickleft = capleft+capwidth, ticktop = bartop+tickpady; + const int barwidth = numticks * tickwidth + tickpadx * 2 + capwidth * 2, barleft = ((640 - barwidth) / 2); + const int barheight = tickheight + tickpady * 2, bartop = 480 - barheight; + const int capleft = barleft + tickpadx, tickleft = capleft + capwidth, ticktop = bartop + tickpady; - cgi_R_SetColor( colorTable[CT_WHITE]); + cgi_R_SetColor(colorTable[CT_WHITE]); // Draw background CG_DrawPic(barleft, bartop, barwidth, barheight, cgs.media.levelLoad); @@ -368,10 +324,10 @@ static void CG_LoadBar(void) CG_DrawPic(tickleft, ticktop, -capwidth, tickheight, cgs.media.loadTickCap); // Draw bar - CG_DrawPic(tickleft, ticktop, tickwidth*cg.loadLCARSStage, tickheight, cgs.media.loadTick); + CG_DrawPic(tickleft, ticktop, tickwidth * cg.loadLCARSStage, tickheight, cgs.media.loadTick); // Draw right cap - CG_DrawPic(tickleft+tickwidth*cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadTickCap); + CG_DrawPic(tickleft + tickwidth * cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadTickCap); } /* @@ -382,65 +338,59 @@ Draw all the status / pacifier stuff during level loading overylays UI_DrawConnectText from ui_connect.cpp ==================== */ -void CG_DrawInformation( void ) { - int y; - +void CG_DrawInformation(void) { + int y; // draw the dialog background - const char *info = CG_ConfigString( CS_SERVERINFO ); - const char *s = Info_ValueForKey( info, "mapname" ); - qhandle_t levelshot; + const char *info = CG_ConfigString(CS_SERVERINFO); + const char *s = Info_ValueForKey(info, "mapname"); + qhandle_t levelshot; - if (!strcmp(s,"bespin_undercity")) // this map has no levelshot - levelshot = cgi_R_RegisterShaderNoMip( "levelshots/kejim_post" ); + if (!strcmp(s, "bespin_undercity")) // this map has no levelshot + levelshot = cgi_R_RegisterShaderNoMip("levelshots/kejim_post"); else - levelshot = cgi_R_RegisterShaderNoMip( va( "levelshots/%s", s ) ); + levelshot = cgi_R_RegisterShaderNoMip(va("levelshots/%s", s)); if (!levelshot) { - levelshot = cgi_R_RegisterShaderNoMip( "menu/art/unknownmap" ); + levelshot = cgi_R_RegisterShaderNoMip("menu/art/unknownmap"); } - extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; // hack! (hey, it's the last week of coding, ok? + extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; // hack! (hey, it's the last week of coding, ok? #ifdef JK2_MODE - if ( !levelshot || g_eSavedGameJustLoaded == eFULL ) - { + if (!levelshot || g_eSavedGameJustLoaded == eFULL) { // keep whatever's in the screen buffer so far (either the last ingame rendered-image (eg for maptransition) // or the screenshot built-in to a loaded save game... // - cgi_R_DrawScreenShot( 0, 0, 640, 480 ); + cgi_R_DrawScreenShot(0, 0, 640, 480); } else #endif { // put up the pre-defined levelshot for this map... // - cgi_R_SetColor( NULL ); - CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot ); + cgi_R_SetColor(NULL); + CG_DrawPic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot); } - if ( g_eSavedGameJustLoaded != eFULL && !strcmp(s,"kejim_post") )//special case for first map! + if (g_eSavedGameJustLoaded != eFULL && !strcmp(s, "kejim_post")) // special case for first map! { - char text[1024]={0}; - cgi_SP_GetStringTextString( "INGAME_ALONGTIME", text, sizeof(text) ); + char text[1024] = {0}; + cgi_SP_GetStringTextString("INGAME_ALONGTIME", text, sizeof(text)); - int w = cgi_R_Font_StrLenPixels(text,cgs.media.qhFontMedium, 1.0f); - cgi_R_Font_DrawString((320)-(w/2), 140, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontMedium, -1, 1.0f); - } - else - if (cg_missionstatusscreen.integer ) - { + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.0f); + cgi_R_Font_DrawString((320) - (w / 2), 140, text, colorTable[CT_ICON_BLUE], cgs.media.qhFontMedium, -1, 1.0f); + } else if (cg_missionstatusscreen.integer) { CG_MissionCompletion(); } CG_LoadBar(); - // the first 150 rows are reserved for the client connection // screen to write into - if ( cg.processedSnapshotNum == 0 ) { + if (cg.processedSnapshotNum == 0) { // still loading // print the current item being loaded #ifndef NDEBUG - cgi_R_Font_DrawString( 48, 398, va("LOADING ... %s",cg.infoScreenText),colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f ); + cgi_R_Font_DrawString(48, 398, va("LOADING ... %s", cg.infoScreenText), colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 1.0f); #endif } @@ -448,21 +398,16 @@ void CG_DrawInformation( void ) { y = 20; // map-specific message (long map name) - s = CG_ConfigString( CS_MESSAGE ); - - if ( s[0] ) - { - if (s[0] == '@') - { - char text[1024]={0}; - cgi_SP_GetStringTextString( s+1, text, sizeof(text) ); - cgi_R_Font_DrawString( 15, y, va("\"%s\"",text),colorTable[CT_WHITE],cgs.media.qhFontMedium, -1, 1.0f ); - } - else - { - cgi_R_Font_DrawString( 15, y, va("\"%s\"",s),colorTable[CT_WHITE],cgs.media.qhFontMedium, -1, 1.0f ); + s = CG_ConfigString(CS_MESSAGE); + + if (s[0]) { + if (s[0] == '@') { + char text[1024] = {0}; + cgi_SP_GetStringTextString(s + 1, text, sizeof(text)); + cgi_R_Font_DrawString(15, y, va("\"%s\"", text), colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); + } else { + cgi_R_Font_DrawString(15, y, va("\"%s\"", s), colorTable[CT_WHITE], cgs.media.qhFontMedium, -1, 1.0f); } y += 20; } } - diff --git a/codeJK2/cgame/cg_lights.cpp b/codeJK2/cgame/cg_lights.cpp index 7def0f4009..68ecdff1db 100644 --- a/codeJK2/cgame/cg_lights.cpp +++ b/codeJK2/cgame/cg_lights.cpp @@ -23,29 +23,27 @@ along with this program; if not, see . #include "cg_local.h" typedef struct clightstyle_s { - int length; - color4ub_t value; - color4ub_t map[MAX_QPATH]; + int length; + color4ub_t value; + color4ub_t map[MAX_QPATH]; } clightstyle_t; -static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; -static int lastofs; +static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; +static int lastofs; /* ================ FX_ClearLightStyles ================ */ -void CG_ClearLightStyles (void) -{ - int i; +void CG_ClearLightStyles(void) { + int i; - memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); + memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); lastofs = -1; - for(i=0;ivalue; - if (!ls->length) - { + if (!ls->length) { ls->value[0] = ls->value[1] = ls->value[2] = ls->value[3] = 255; - } - else if (ls->length == 1) - { + } else if (ls->length == 1) { ls->value[0] = ls->map[0][0]; ls->value[1] = ls->map[0][1]; ls->value[2] = ls->map[0][2]; - ls->value[3] = 255; //ls->map[0][3]; - } - else - { - ls->value[0] = ls->map[ofs%ls->length][0]; - ls->value[1] = ls->map[ofs%ls->length][1]; - ls->value[2] = ls->map[ofs%ls->length][2]; - ls->value[3] = 255; //ls->map[ofs%ls->length][3]; + ls->value[3] = 255; // ls->map[0][3]; + } else { + ls->value[0] = ls->map[ofs % ls->length][0]; + ls->value[1] = ls->map[ofs % ls->length][1]; + ls->value[2] = ls->map[ofs % ls->length][2]; + ls->value[3] = 255; // ls->map[ofs%ls->length][3]; } - trap_R_SetLightStyle( i, ba->i ); + trap_R_SetLightStyle(i, ba->i); } } -void CG_SetLightstyle (int i) -{ - const char *s; - int j, k; +void CG_SetLightstyle(int i) { + const char *s; + int j, k; - s = CG_ConfigString( i+CS_LIGHT_STYLES ); - j = strlen (s); - if (j >= MAX_QPATH) - { - Com_Error (ERR_DROP, "svc_lightstyle length=%i", j); + s = CG_ConfigString(i + CS_LIGHT_STYLES); + j = strlen(s); + if (j >= MAX_QPATH) { + Com_Error(ERR_DROP, "svc_lightstyle length=%i", j); } - cl_lightstyle[(i/3)].length = j; - for (k=0 ; k. #include "cg_local.h" #include "cg_media.h" -#define MAX_LOCAL_ENTITIES 512 -localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; -localEntity_t cg_activeLocalEntities; // double linked list -localEntity_t *cg_freeLocalEntities; // single linked list +#define MAX_LOCAL_ENTITIES 512 +localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; +localEntity_t cg_activeLocalEntities; // double linked list +localEntity_t *cg_freeLocalEntities; // single linked list /* =================== @@ -39,27 +39,26 @@ This is called at startup and for tournement restarts =================== */ -void CG_InitLocalEntities( void ) { - int i; +void CG_InitLocalEntities(void) { + int i; - memset( cg_localEntities, 0, sizeof( cg_localEntities ) ); + memset(cg_localEntities, 0, sizeof(cg_localEntities)); cg_activeLocalEntities.next = &cg_activeLocalEntities; cg_activeLocalEntities.prev = &cg_activeLocalEntities; cg_freeLocalEntities = cg_localEntities; - for ( i = 0 ; i < MAX_LOCAL_ENTITIES - 1 ; i++ ) { - cg_localEntities[i].next = &cg_localEntities[i+1]; + for (i = 0; i < MAX_LOCAL_ENTITIES - 1; i++) { + cg_localEntities[i].next = &cg_localEntities[i + 1]; } } - /* ================== CG_FreeLocalEntity ================== */ -void CG_FreeLocalEntity( localEntity_t *le ) { - if ( !le->prev ) { - CG_Error( "CG_FreeLocalEntity: not active" ); +void CG_FreeLocalEntity(localEntity_t *le) { + if (!le->prev) { + CG_Error("CG_FreeLocalEntity: not active"); } // remove from the doubly linked active list @@ -78,19 +77,19 @@ CG_AllocLocalEntity Will allways succeed, even if it requires freeing an old active entity =================== */ -localEntity_t *CG_AllocLocalEntity( void ) { - localEntity_t *le; +localEntity_t *CG_AllocLocalEntity(void) { + localEntity_t *le; - if ( !cg_freeLocalEntities ) { + if (!cg_freeLocalEntities) { // no free entities, so free the one at the end of the chain // remove the oldest active entity - CG_FreeLocalEntity( cg_activeLocalEntities.prev ); + CG_FreeLocalEntity(cg_activeLocalEntities.prev); } le = cg_freeLocalEntities; cg_freeLocalEntities = cg_freeLocalEntities->next; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->next = cg_activeLocalEntities.next; @@ -101,7 +100,6 @@ localEntity_t *CG_AllocLocalEntity( void ) { return le; } - /* ==================================================================================== @@ -113,76 +111,64 @@ or generates more localentities along a trail. ==================================================================================== */ - /* ================ CG_FragmentBounceSound ================ */ -void CG_FragmentBounceSound( localEntity_t *le, trace_t *trace ) -{ +void CG_FragmentBounceSound(localEntity_t *le, trace_t *trace) { // half the fragments will make a bounce sounds - if ( rand() & 1 ) - { - sfxHandle_t s = 0; + if (rand() & 1) { + sfxHandle_t s = 0; - switch( le->leBounceSoundType ) - { + switch (le->leBounceSoundType) { case LEBS_ROCK: - s = cgs.media.rockBounceSound[Q_irand(0,1)]; + s = cgs.media.rockBounceSound[Q_irand(0, 1)]; break; case LEBS_METAL: - s = cgs.media.metalBounceSound[Q_irand(0,1)];// FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... + s = cgs.media.metalBounceSound[Q_irand(0, 1)]; // FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... break; default: break; } - if ( s ) - { - cgi_S_StartSound( trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s ); + if (s) { + cgi_S_StartSound(trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s); } // bouncers only make the sound once... // FIXME: arbitrary...change if it bugs you le->leBounceSoundType = LEBS_NONE; - } - else if ( rand() & 1 ) - { + } else if (rand() & 1) { // we may end up bouncing again, but each bounce reduces the chance of playing the sound again or they may make a lot of noise when they settle // FIXME: maybe just always do this?? le->leBounceSoundType = LEBS_NONE; } } - /* ================ CG_ReflectVelocity ================ */ -void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) -{ - vec3_t velocity; - float dot; - int hitTime; +void CG_ReflectVelocity(localEntity_t *le, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane hitTime = cg.time - cg.frametime + cg.frametime * trace->fraction; - EvaluateTrajectoryDelta( &le->pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, le->pos.trDelta ); + EvaluateTrajectoryDelta(&le->pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, le->pos.trDelta); - VectorScale( le->pos.trDelta, le->bounceFactor, le->pos.trDelta ); + VectorScale(le->pos.trDelta, le->bounceFactor, le->pos.trDelta); - VectorCopy( trace->endpos, le->pos.trBase ); + VectorCopy(trace->endpos, le->pos.trBase); le->pos.trTime = cg.time; // check for stop, making sure that even on low FPS systems it doesn't bobble - if ( trace->allsolid || - ( trace->plane.normal[2] > 0 && - ( le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2] ) ) ) - { + if (trace->allsolid || (trace->plane.normal[2] > 0 && (le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2]))) { le->pos.trType = TR_STATIONARY; } } @@ -192,63 +178,57 @@ void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) CG_AddFragment ================ */ -void CG_AddFragment( localEntity_t *le ) -{ - vec3_t newOrigin; - trace_t trace; +void CG_AddFragment(localEntity_t *le) { + vec3_t newOrigin; + trace_t trace; // used to sink into the ground, but it looks better to maybe just fade them out - int t; - + int t; + t = le->endTime - cg.time; - if ( t < FRAG_FADE_TIME ) - { + if (t < FRAG_FADE_TIME) { le->refEntity.renderfx |= RF_ALPHA_FADE; le->refEntity.shaderRGBA[0] = le->refEntity.shaderRGBA[1] = le->refEntity.shaderRGBA[2] = 255; le->refEntity.shaderRGBA[3] = ((float)t / FRAG_FADE_TIME) * 255.0f; } - if ( le->pos.trType == TR_STATIONARY ) - { - if ( !(cgi_CM_PointContents( le->refEntity.origin, 0 ) & CONTENTS_SOLID )) - { + if (le->pos.trType == TR_STATIONARY) { + if (!(cgi_CM_PointContents(le->refEntity.origin, 0) & CONTENTS_SOLID)) { // thing is no longer in solid, so let gravity take it back - VectorCopy( le->refEntity.origin, le->pos.trBase ); - VectorClear( le->pos.trDelta ); + VectorCopy(le->refEntity.origin, le->pos.trBase); + VectorClear(le->pos.trDelta); le->pos.trTime = cg.time; le->pos.trType = TR_GRAVITY; } - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); return; } // calculate new position - EvaluateTrajectory( &le->pos, cg.time, newOrigin ); + EvaluateTrajectory(&le->pos, cg.time, newOrigin); le->refEntity.renderfx |= RF_LIGHTING_ORIGIN; - VectorCopy( newOrigin, le->refEntity.lightingOrigin ); - + VectorCopy(newOrigin, le->refEntity.lightingOrigin); + // trace a line from previous position to new position - CG_Trace( &trace, le->refEntity.origin, NULL, NULL, newOrigin, le->ownerGentNum, CONTENTS_SOLID ); - if ( trace.fraction == 1.0 ) { + CG_Trace(&trace, le->refEntity.origin, NULL, NULL, newOrigin, le->ownerGentNum, CONTENTS_SOLID); + if (trace.fraction == 1.0) { // still in free fall - VectorCopy( newOrigin, le->refEntity.origin ); + VectorCopy(newOrigin, le->refEntity.origin); - if ( le->leFlags & LEF_TUMBLE ) { + if (le->leFlags & LEF_TUMBLE) { vec3_t angles; - EvaluateTrajectory( &le->angles, cg.time, angles ); - AnglesToAxis( angles, le->refEntity.axis ); - for(int k = 0; k < 3; k++) - { + EvaluateTrajectory(&le->angles, cg.time, angles); + AnglesToAxis(angles, le->refEntity.axis); + for (int k = 0; k < 3; k++) { VectorScale(le->refEntity.axis[k], le->radius, le->refEntity.axis[k]); } - } - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); return; } @@ -256,20 +236,19 @@ void CG_AddFragment( localEntity_t *le ) // if it is in a nodrop zone, remove it // this keeps gibs from waiting at the bottom of pits of death // and floating levels - if ( cgi_CM_PointContents( trace.endpos, 0 ) & CONTENTS_NODROP ) - { - CG_FreeLocalEntity( le ); + if (cgi_CM_PointContents(trace.endpos, 0) & CONTENTS_NODROP) { + CG_FreeLocalEntity(le); return; } // do a bouncy sound - CG_FragmentBounceSound( le, &trace ); + CG_FragmentBounceSound(le, &trace); // reflect the velocity on the trace plane - CG_ReflectVelocity( le, &trace ); - //FIXME: if LEF_TUMBLE, change avelocity too? + CG_ReflectVelocity(le, &trace); + // FIXME: if LEF_TUMBLE, change avelocity too? - cgi_R_AddRefEntityToScene( &le->refEntity ); + cgi_R_AddRefEntityToScene(&le->refEntity); } /* @@ -284,32 +263,29 @@ These only do simple scaling or modulation before passing to the renderer /* ** CG_AddTeleporterEffect */ -void CG_AddTeleporterEffect( localEntity_t *le ) { +void CG_AddTeleporterEffect(localEntity_t *le) { refEntity_t *re; float c; re = &le->refEntity; - c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime ); + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); - re->shaderRGBA[0] = - re->shaderRGBA[1] = - re->shaderRGBA[2] = - re->shaderRGBA[3] = 0xff * c; + re->shaderRGBA[0] = re->shaderRGBA[1] = re->shaderRGBA[2] = re->shaderRGBA[3] = 0xff * c; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* ** CG_AddFadeRGB */ -void CG_AddFadeRGB( localEntity_t *le ) { +void CG_AddFadeRGB(localEntity_t *le) { refEntity_t *re; float c; re = &le->refEntity; - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; c *= 0xff; re->shaderRGBA[0] = le->color[0] * c; @@ -317,7 +293,7 @@ void CG_AddFadeRGB( localEntity_t *le ) { re->shaderRGBA[2] = le->color[2] * c; re->shaderRGBA[3] = le->color[3] * c; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* @@ -325,37 +301,37 @@ void CG_AddFadeRGB( localEntity_t *le ) { CG_AddPuff ================== */ -static void CG_AddPuff( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddPuff(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; // fade / grow time - c = ( le->endTime - cg.time ) / (float)( le->endTime - le->startTime ); + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); re->shaderRGBA[0] = le->color[0] * c; re->shaderRGBA[1] = le->color[1] * c; re->shaderRGBA[2] = le->color[2] * c; - if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) { - re->radius = le->radius * ( 1.0 - c ) + 8; + if (!(le->leFlags & LEF_PUFF_DONT_SCALE)) { + re->radius = le->radius * (1.0 - c) + 8; } - EvaluateTrajectory( &le->pos, cg.time, re->origin ); + EvaluateTrajectory(&le->pos, cg.time, re->origin); // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } /* @@ -363,71 +339,63 @@ static void CG_AddPuff( localEntity_t *le ) { CG_AddLocalLight ================ */ -static void CG_AddLocalLight( localEntity_t *le ) -{ +static void CG_AddLocalLight(localEntity_t *le) { // There should be a light if this is being used, but hey... - if ( le->light ) - { - float light; + if (le->light) { + float light; - light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime ); + light = (float)(cg.time - le->startTime) / (le->endTime - le->startTime); - if ( light < 0.5 ) - { + if (light < 0.5) { light = 1.0; - } - else - { - light = 1.0 - ( light - 0.5 ) * 2; + } else { + light = 1.0 - (light - 0.5) * 2; } light = le->light * light; - cgi_R_AddLightToScene( le->refEntity.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] ); + cgi_R_AddLightToScene(le->refEntity.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2]); } } //--------------------------------------------------- -static void CG_AddFadeModel( localEntity_t *le ) -{ - refEntity_t *ent = &le->refEntity; +static void CG_AddFadeModel(localEntity_t *le) { + refEntity_t *ent = &le->refEntity; - if ( cg.time < le->startTime ) - { - CG_FreeLocalEntity( le ); + if (cg.time < le->startTime) { + CG_FreeLocalEntity(le); return; } - float frac = 1.0f - ((float)( cg.time - le->startTime )/(float)( le->endTime - le->startTime )); + float frac = 1.0f - ((float)(cg.time - le->startTime) / (float)(le->endTime - le->startTime)); ent->shaderRGBA[0] = le->color[0] * frac; ent->shaderRGBA[1] = le->color[1] * frac; ent->shaderRGBA[2] = le->color[2] * frac; ent->shaderRGBA[3] = le->color[3] * frac; - EvaluateTrajectory( &le->pos, cg.time, ent->origin ); + EvaluateTrajectory(&le->pos, cg.time, ent->origin); // add the entity - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } // NOTE: this is 100% for the demp2 alt-fire effect, so changes to the visual effect will affect game side demp2 code //--------------------------------------------------- -static void CG_AddFadeScaleModel( localEntity_t *le ) -{ - refEntity_t *ent = &le->refEntity; +static void CG_AddFadeScaleModel(localEntity_t *le) { + refEntity_t *ent = &le->refEntity; - float frac = ( cg.time - le->startTime )/((float)( le->endTime - le->startTime )); + float frac = (cg.time - le->startTime) / ((float)(le->endTime - le->startTime)); frac *= frac * frac; // yes, this is completely ridiculous...but it causes the shell to grow slowly then "explode" at the end ent->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, ent->axis ); + AxisCopy(axisDefault, ent->axis); - VectorScale( ent->axis[0], le->radius * frac, ent->axis[0] ); - VectorScale( ent->axis[1], le->radius * frac, ent->axis[1] ); - VectorScale( ent->axis[2], le->radius * 0.5f * frac, ent->axis[2] ); + VectorScale(ent->axis[0], le->radius * frac, ent->axis[0]); + VectorScale(ent->axis[1], le->radius * frac, ent->axis[1]); + VectorScale(ent->axis[2], le->radius * 0.5f * frac, ent->axis[2]); frac = 1.0f - frac; @@ -437,89 +405,85 @@ static void CG_AddFadeScaleModel( localEntity_t *le ) ent->shaderRGBA[3] = le->color[3] * frac; // add the entity - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } // create a quad that doesn't use a refEnt. Currently only for use with the DebugNav drawing so it doesn't have to use fx //------------------------------------------ -static void CG_AddQuad( localEntity_t *le ) -{ - polyVert_t verts[4]; +static void CG_AddQuad(localEntity_t *le) { + polyVert_t verts[4]; - VectorCopy( le->refEntity.origin, verts[0].xyz ); + VectorCopy(le->refEntity.origin, verts[0].xyz); verts[0].xyz[0] -= le->radius; verts[0].xyz[1] -= le->radius; verts[0].st[0] = 0; verts[0].st[1] = 0; - for ( int i = 0; i < 4; i++ ) - { + for (int i = 0; i < 4; i++) { verts[i].modulate[0] = le->color[0]; verts[i].modulate[1] = le->color[1]; verts[i].modulate[2] = le->color[2]; verts[i].modulate[3] = le->color[3]; } - VectorCopy( le->refEntity.origin, verts[1].xyz ); + VectorCopy(le->refEntity.origin, verts[1].xyz); verts[1].xyz[0] -= le->radius; verts[1].xyz[1] += le->radius; verts[1].st[0] = 0; verts[1].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[2].xyz ); + VectorCopy(le->refEntity.origin, verts[2].xyz); verts[2].xyz[0] += le->radius; verts[2].xyz[1] += le->radius; verts[2].st[0] = 1; verts[2].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[3].xyz ); + VectorCopy(le->refEntity.origin, verts[3].xyz); verts[3].xyz[0] += le->radius; verts[3].xyz[1] -= le->radius; verts[3].st[0] = 1; verts[3].st[1] = 0; - cgi_R_AddPolyToScene( le->refEntity.customShader, 4, verts ); + cgi_R_AddPolyToScene(le->refEntity.customShader, 4, verts); } // create a sprite that doesn't use a refEnt. Currently only for use with the DebugNav drawing so it doesn't have to use fx //------------------------------------------ -static void CG_AddSprite( localEntity_t *le ) -{ - polyVert_t verts[4]; +static void CG_AddSprite(localEntity_t *le) { + polyVert_t verts[4]; - VectorCopy( le->refEntity.origin, verts[0].xyz ); - VectorMA( verts[0].xyz, -le->radius, cg.refdef.viewaxis[2], verts[0].xyz ); - VectorMA( verts[0].xyz, -le->radius, cg.refdef.viewaxis[1], verts[0].xyz ); + VectorCopy(le->refEntity.origin, verts[0].xyz); + VectorMA(verts[0].xyz, -le->radius, cg.refdef.viewaxis[2], verts[0].xyz); + VectorMA(verts[0].xyz, -le->radius, cg.refdef.viewaxis[1], verts[0].xyz); verts[0].st[0] = 0; verts[0].st[1] = 0; - for ( int i = 0; i < 4; i++ ) - { + for (int i = 0; i < 4; i++) { verts[i].modulate[0] = le->color[0]; verts[i].modulate[1] = le->color[1]; verts[i].modulate[2] = le->color[2]; verts[i].modulate[3] = le->color[3]; } - VectorCopy( le->refEntity.origin, verts[1].xyz ); - VectorMA( verts[1].xyz, -le->radius, cg.refdef.viewaxis[2], verts[1].xyz ); - VectorMA( verts[1].xyz, le->radius, cg.refdef.viewaxis[1], verts[1].xyz ); + VectorCopy(le->refEntity.origin, verts[1].xyz); + VectorMA(verts[1].xyz, -le->radius, cg.refdef.viewaxis[2], verts[1].xyz); + VectorMA(verts[1].xyz, le->radius, cg.refdef.viewaxis[1], verts[1].xyz); verts[1].st[0] = 0; verts[1].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[2].xyz ); - VectorMA( verts[2].xyz, le->radius, cg.refdef.viewaxis[2], verts[2].xyz ); - VectorMA( verts[2].xyz, le->radius, cg.refdef.viewaxis[1], verts[2].xyz ); + VectorCopy(le->refEntity.origin, verts[2].xyz); + VectorMA(verts[2].xyz, le->radius, cg.refdef.viewaxis[2], verts[2].xyz); + VectorMA(verts[2].xyz, le->radius, cg.refdef.viewaxis[1], verts[2].xyz); verts[2].st[0] = 1; verts[2].st[1] = 1; - VectorCopy( le->refEntity.origin, verts[3].xyz ); - VectorMA( verts[3].xyz, le->radius, cg.refdef.viewaxis[2], verts[3].xyz ); - VectorMA( verts[3].xyz, -le->radius, cg.refdef.viewaxis[1], verts[3].xyz ); + VectorCopy(le->refEntity.origin, verts[3].xyz); + VectorMA(verts[3].xyz, le->radius, cg.refdef.viewaxis[2], verts[3].xyz); + VectorMA(verts[3].xyz, -le->radius, cg.refdef.viewaxis[1], verts[3].xyz); verts[3].st[0] = 1; verts[3].st[1] = 0; - cgi_R_AddPolyToScene( le->refEntity.customShader, 4, verts ); + cgi_R_AddPolyToScene(le->refEntity.customShader, 4, verts); } /* @@ -529,15 +493,14 @@ CG_AddLine for beams and the like. =================== */ -void CG_AddLine( localEntity_t *le ) -{ - refEntity_t *re; +void CG_AddLine(localEntity_t *le) { + refEntity_t *re; re = &le->refEntity; re->reType = RT_LINE; - cgi_R_AddRefEntityToScene( re ); + cgi_R_AddRefEntityToScene(re); } //============================================================================== @@ -548,69 +511,64 @@ CG_AddLocalEntities =================== */ -void CG_AddLocalEntities( void ) -{ - localEntity_t *le, *next; +void CG_AddLocalEntities(void) { + localEntity_t *le, *next; // walk the list backwards, so any new local entities generated // (trails, marks, etc) will be present this frame le = cg_activeLocalEntities.prev; - for ( ; le != &cg_activeLocalEntities ; le = next ) { + for (; le != &cg_activeLocalEntities; le = next) { // grab next now, so if the local entity is freed we // still have it next = le->prev; - if ( cg.time >= le->endTime ) { - CG_FreeLocalEntity( le ); + if (cg.time >= le->endTime) { + CG_FreeLocalEntity(le); continue; } - switch ( le->leType ) { + switch (le->leType) { default: - CG_Error( "Bad leType: %i", le->leType ); + CG_Error("Bad leType: %i", le->leType); break; case LE_MARK: break; case LE_FADE_MODEL: - CG_AddFadeModel( le ); + CG_AddFadeModel(le); break; case LE_FADE_SCALE_MODEL: - CG_AddFadeScaleModel( le ); + CG_AddFadeScaleModel(le); break; case LE_FRAGMENT: - CG_AddFragment( le ); + CG_AddFragment(le); break; case LE_PUFF: - CG_AddPuff( le ); + CG_AddPuff(le); break; - case LE_FADE_RGB: // teleporters, railtrails - CG_AddFadeRGB( le ); + case LE_FADE_RGB: // teleporters, railtrails + CG_AddFadeRGB(le); break; case LE_LIGHT: - CG_AddLocalLight( le ); + CG_AddLocalLight(le); break; - case LE_LINE: // oriented lines for FX - CG_AddLine( le ); + case LE_LINE: // oriented lines for FX + CG_AddLine(le); break; // Use for debug only case LE_QUAD: - CG_AddQuad( le ); + CG_AddQuad(le); break; case LE_SPRITE: - CG_AddSprite( le ); + CG_AddSprite(le); } } } - - - - diff --git a/codeJK2/cgame/cg_main.cpp b/codeJK2/cgame/cg_main.cpp index 9be003e9a9..eece9ac092 100644 --- a/codeJK2/cgame/cg_main.cpp +++ b/codeJK2/cgame/cg_main.cpp @@ -30,25 +30,23 @@ along with this program; if not, see . #include "../../code/qcommon/sstring.h" #include "../code/qcommon/ojk_saved_game_helper.h" -//NOTENOTE: Be sure to change the mirrored code in g_shared.h -typedef std::map< sstring_t, unsigned char, std::less > namePrecache_m; -extern namePrecache_m *as_preCacheMap; -extern void CG_RegisterNPCCustomSounds( clientInfo_t *ci ); -extern qboolean G_AddSexToMunroString ( char *string, qboolean qDoBoth ); -extern void CG_RegisterNPCEffects( team_t team ); -extern qboolean G_ParseAnimFileSet( const char *filename, const char *animCFG, int *animFileIndex ); -extern void CG_DrawDataPadInventorySelect( void ); - -void CG_Init( int serverCommandSequence ); -qboolean CG_ConsoleCommand( void ); -void CG_Shutdown( void ); -int CG_GetCameraPos( vec3_t camerapos ); +// NOTENOTE: Be sure to change the mirrored code in g_shared.h +typedef std::map> namePrecache_m; +extern namePrecache_m *as_preCacheMap; +extern void CG_RegisterNPCCustomSounds(clientInfo_t *ci); +extern qboolean G_AddSexToMunroString(char *string, qboolean qDoBoth); +extern void CG_RegisterNPCEffects(team_t team); +extern qboolean G_ParseAnimFileSet(const char *filename, const char *animCFG, int *animFileIndex); +extern void CG_DrawDataPadInventorySelect(void); + +void CG_Init(int serverCommandSequence); +qboolean CG_ConsoleCommand(void); +void CG_Shutdown(void); +int CG_GetCameraPos(vec3_t camerapos); void UseItem(int itemNum); -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color); +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color); -#define NUM_CHUNKS 6 +#define NUM_CHUNKS 6 /* Ghoul2 Insert Start */ @@ -62,38 +60,22 @@ void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount); Ghoul2 Insert End */ - void CG_LoadHudMenu(void); int inv_icons[INV_MAX]; -const char *inv_names[] = -{ -"ELECTROBINOCULARS", -"BACTA CANISTER", -"SEEKER", -"LIGHT AMP GOGGLES", -"ASSAULT SENTRY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"GOODIE KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", -"SECURITY KEY", +const char *inv_names[] = { + "ELECTROBINOCULARS", "BACTA CANISTER", "SEEKER", "LIGHT AMP GOGGLES", "ASSAULT SENTRY", "GOODIE KEY", "GOODIE KEY", "GOODIE KEY", + "GOODIE KEY", "GOODIE KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", "SECURITY KEY", }; -int force_icons[NUM_FORCE_POWERS]; +int force_icons[NUM_FORCE_POWERS]; - -int cgi_UI_GetMenuInfo(char *menuFile,int *x,int *y); -void CG_DrawDataPadHUD( centity_t *cent ); -void MissionInformation_Draw( centity_t *cent ); +int cgi_UI_GetMenuInfo(char *menuFile, int *x, int *y); +void CG_DrawDataPadHUD(centity_t *cent); +void MissionInformation_Draw(centity_t *cent); void CG_DrawIconBackground(void); void CG_DrawDataPadIconBackground(int backgroundType); -void CG_DrawDataPadWeaponSelect( void ); -void CG_DrawDataPadForceSelect( void ); +void CG_DrawDataPadWeaponSelect(void); +void CG_DrawDataPadForceSelect(void); /* ================ @@ -103,12 +85,13 @@ This is the only way control passes into the cgame module. This must be the very first function compiled into the .q3vm file ================ */ -extern "C" Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7 ) { - centity_t *cent; +extern "C" Q_EXPORT intptr_t vmMain(int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, + intptr_t arg7) { + centity_t *cent; - switch ( command ) { + switch (command) { case CG_INIT: - CG_Init( arg0 ); + CG_Init(arg0); return 0; case CG_SHUTDOWN: CG_Shutdown(); @@ -116,15 +99,15 @@ extern "C" Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, case CG_CONSOLE_COMMAND: return CG_ConsoleCommand(); case CG_DRAW_ACTIVE_FRAME: - CG_DrawActiveFrame( arg0, (stereoFrame_t) arg1 ); + CG_DrawActiveFrame(arg0, (stereoFrame_t)arg1); return 0; case CG_CROSSHAIR_PLAYER: return CG_CrosshairPlayer(); case CG_CAMERA_POS: - return CG_GetCameraPos( (float*)arg0); -/* -Ghoul2 Insert Start -*/ + return CG_GetCameraPos((float *)arg0); + /* + Ghoul2 Insert Start + */ case CG_RESIZE_G2: CG_ResizeG2((CGhoul2Info_v *)arg0, arg1); return 0; @@ -141,42 +124,37 @@ Ghoul2 Insert Start CG_ResizeG2TempBone((mdxaBone_v *)arg0, arg1); return 0; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ case CG_DRAW_DATAPAD_HUD: - if (cg.snap) - { + if (cg.snap) { cent = &cg_entities[cg.snap->ps.clientNum]; CG_DrawDataPadHUD(cent); } return 0; case CG_DRAW_DATAPAD_OBJECTIVES: - if (cg.snap) - { + if (cg.snap) { cent = &cg_entities[cg.snap->ps.clientNum]; MissionInformation_Draw(cent); } return 0; case CG_DRAW_DATAPAD_WEAPONS: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_WEAPONS); CG_DrawDataPadWeaponSelect(); } return 0; case CG_DRAW_DATAPAD_INVENTORY: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_INVENTORY); CG_DrawDataPadInventorySelect(); } return 0; case CG_DRAW_DATAPAD_FORCEPOWERS: - if (cg.snap) - { + if (cg.snap) { CG_DrawDataPadIconBackground(ICON_FORCE); CG_DrawDataPadForceSelect(); } @@ -189,270 +167,254 @@ Ghoul2 Insert End Ghoul2 Insert Start */ -void CG_ResizeG2Bolt(boltInfo_v *bolt, int newCount) -{ - bolt->resize(newCount); -} +void CG_ResizeG2Bolt(boltInfo_v *bolt, int newCount) { bolt->resize(newCount); } -void CG_ResizeG2Surface(surfaceInfo_v *surface, int newCount) -{ - surface->resize(newCount); -} +void CG_ResizeG2Surface(surfaceInfo_v *surface, int newCount) { surface->resize(newCount); } -void CG_ResizeG2Bone(boneInfo_v *bone, int newCount) -{ - bone->resize(newCount); -} +void CG_ResizeG2Bone(boneInfo_v *bone, int newCount) { bone->resize(newCount); } -void CG_ResizeG2(CGhoul2Info_v *ghoul2, int newCount) -{ - ghoul2->resize(newCount); -} +void CG_ResizeG2(CGhoul2Info_v *ghoul2, int newCount) { ghoul2->resize(newCount); } -void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount) -{ - tempBone->resize(newCount); -} +void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount) { tempBone->resize(newCount); } /* Ghoul2 Insert End */ -cg_t cg; -cgs_t cgs; -centity_t cg_entities[MAX_GENTITIES]; -weaponInfo_t cg_weapons[MAX_WEAPONS]; -itemInfo_t cg_items[MAX_ITEMS]; +cg_t cg; +cgs_t cgs; +centity_t cg_entities[MAX_GENTITIES]; +weaponInfo_t cg_weapons[MAX_WEAPONS]; +itemInfo_t cg_items[MAX_ITEMS]; typedef struct { - qboolean registered; // Has the player picked it up - qboolean active; // Is it the chosen inventory item - int count; // Count of items. - char description[128]; + qboolean registered; // Has the player picked it up + qboolean active; // Is it the chosen inventory item + int count; // Count of items. + char description[128]; } inventoryInfo_t; -inventoryInfo_t cg_inventory[INV_MAX]; - - -vmCvar_t cg_centertime; -vmCvar_t cg_runpitch; -vmCvar_t cg_runroll; -vmCvar_t cg_bobup; -vmCvar_t cg_bobpitch; -vmCvar_t cg_bobroll; -vmCvar_t cg_swingSpeed; -vmCvar_t cg_shadows; -vmCvar_t cg_paused; -vmCvar_t cg_drawTimer; -vmCvar_t cg_drawFPS; -vmCvar_t cg_drawSnapshot; -vmCvar_t cg_drawAmmoWarning; -vmCvar_t cg_drawCrosshair; -vmCvar_t cg_crosshairIdentifyTarget; -vmCvar_t cg_dynamicCrosshair; -vmCvar_t cg_crosshairForceHint; -vmCvar_t cg_crosshairX; -vmCvar_t cg_crosshairY; -vmCvar_t cg_crosshairSize; -vmCvar_t cg_draw2D; -vmCvar_t cg_drawStatus; -vmCvar_t cg_drawHUD; -vmCvar_t cg_animSpeed; -vmCvar_t cg_debugAnim; -vmCvar_t cg_debugSaber; -vmCvar_t cg_debugPosition; -vmCvar_t cg_debugEvents; -vmCvar_t cg_errorDecay; -vmCvar_t cg_noPlayerAnims; -vmCvar_t cg_footsteps; -vmCvar_t cg_addMarks; -vmCvar_t cg_drawGun; -vmCvar_t cg_gun_frame; -vmCvar_t cg_gun_x; -vmCvar_t cg_gun_y; -vmCvar_t cg_gun_z; -vmCvar_t cg_fovViewmodel; -vmCvar_t cg_fovViewmodelAdjust; -vmCvar_t cg_autoswitch; -vmCvar_t cg_simpleItems; -vmCvar_t cg_fov; -vmCvar_t cg_fovAspectAdjust; -vmCvar_t cg_missionstatusscreen; -vmCvar_t cg_endcredits; -vmCvar_t cg_updatedDataPadForcePower1; -vmCvar_t cg_updatedDataPadForcePower2; -vmCvar_t cg_updatedDataPadForcePower3; -vmCvar_t cg_updatedDataPadObjective; - -vmCvar_t cg_thirdPerson; -vmCvar_t cg_thirdPersonRange; -vmCvar_t cg_thirdPersonMaxRange; -vmCvar_t cg_thirdPersonAngle; -vmCvar_t cg_thirdPersonPitchOffset; -vmCvar_t cg_thirdPersonVertOffset; -vmCvar_t cg_thirdPersonCameraDamp; -vmCvar_t cg_thirdPersonTargetDamp; -vmCvar_t cg_saberAutoThird; -vmCvar_t cg_gunAutoFirst; - -vmCvar_t cg_thirdPersonAlpha; -vmCvar_t cg_thirdPersonAutoAlpha; -vmCvar_t cg_thirdPersonHorzOffset; - -vmCvar_t cg_stereoSeparation; -vmCvar_t cg_developer; -vmCvar_t cg_timescale; -vmCvar_t cg_skippingcin; - -vmCvar_t cg_pano; -vmCvar_t cg_panoNumShots; - -vmCvar_t fx_freeze; -vmCvar_t fx_debug; - -vmCvar_t cg_missionInfoCentered; -vmCvar_t cg_missionInfoFlashTime; -vmCvar_t cg_hudFiles; +inventoryInfo_t cg_inventory[INV_MAX]; + +vmCvar_t cg_centertime; +vmCvar_t cg_runpitch; +vmCvar_t cg_runroll; +vmCvar_t cg_bobup; +vmCvar_t cg_bobpitch; +vmCvar_t cg_bobroll; +vmCvar_t cg_swingSpeed; +vmCvar_t cg_shadows; +vmCvar_t cg_paused; +vmCvar_t cg_drawTimer; +vmCvar_t cg_drawFPS; +vmCvar_t cg_drawSnapshot; +vmCvar_t cg_drawAmmoWarning; +vmCvar_t cg_drawCrosshair; +vmCvar_t cg_crosshairIdentifyTarget; +vmCvar_t cg_dynamicCrosshair; +vmCvar_t cg_crosshairForceHint; +vmCvar_t cg_crosshairX; +vmCvar_t cg_crosshairY; +vmCvar_t cg_crosshairSize; +vmCvar_t cg_draw2D; +vmCvar_t cg_drawStatus; +vmCvar_t cg_drawHUD; +vmCvar_t cg_animSpeed; +vmCvar_t cg_debugAnim; +vmCvar_t cg_debugSaber; +vmCvar_t cg_debugPosition; +vmCvar_t cg_debugEvents; +vmCvar_t cg_errorDecay; +vmCvar_t cg_noPlayerAnims; +vmCvar_t cg_footsteps; +vmCvar_t cg_addMarks; +vmCvar_t cg_drawGun; +vmCvar_t cg_gun_frame; +vmCvar_t cg_gun_x; +vmCvar_t cg_gun_y; +vmCvar_t cg_gun_z; +vmCvar_t cg_fovViewmodel; +vmCvar_t cg_fovViewmodelAdjust; +vmCvar_t cg_autoswitch; +vmCvar_t cg_simpleItems; +vmCvar_t cg_fov; +vmCvar_t cg_fovAspectAdjust; +vmCvar_t cg_missionstatusscreen; +vmCvar_t cg_endcredits; +vmCvar_t cg_updatedDataPadForcePower1; +vmCvar_t cg_updatedDataPadForcePower2; +vmCvar_t cg_updatedDataPadForcePower3; +vmCvar_t cg_updatedDataPadObjective; + +vmCvar_t cg_thirdPerson; +vmCvar_t cg_thirdPersonRange; +vmCvar_t cg_thirdPersonMaxRange; +vmCvar_t cg_thirdPersonAngle; +vmCvar_t cg_thirdPersonPitchOffset; +vmCvar_t cg_thirdPersonVertOffset; +vmCvar_t cg_thirdPersonCameraDamp; +vmCvar_t cg_thirdPersonTargetDamp; +vmCvar_t cg_saberAutoThird; +vmCvar_t cg_gunAutoFirst; + +vmCvar_t cg_thirdPersonAlpha; +vmCvar_t cg_thirdPersonAutoAlpha; +vmCvar_t cg_thirdPersonHorzOffset; + +vmCvar_t cg_stereoSeparation; +vmCvar_t cg_developer; +vmCvar_t cg_timescale; +vmCvar_t cg_skippingcin; + +vmCvar_t cg_pano; +vmCvar_t cg_panoNumShots; + +vmCvar_t fx_freeze; +vmCvar_t fx_debug; + +vmCvar_t cg_missionInfoCentered; +vmCvar_t cg_missionInfoFlashTime; +vmCvar_t cg_hudFiles; /* Ghoul2 Insert Start */ -vmCvar_t cg_debugBB; +vmCvar_t cg_debugBB; /* Ghoul2 Insert End */ -vmCvar_t cg_VariantSoundCap; // 0 = no capping, else cap to (n) max (typically just 1, but allows more) -vmCvar_t cg_turnAnims; -vmCvar_t cg_motionBoneComp; -vmCvar_t cg_reliableAnimSounds; +vmCvar_t cg_VariantSoundCap; // 0 = no capping, else cap to (n) max (typically just 1, but allows more) +vmCvar_t cg_turnAnims; +vmCvar_t cg_motionBoneComp; +vmCvar_t cg_reliableAnimSounds; -vmCvar_t cg_smoothPlayerPos; -vmCvar_t cg_smoothPlayerPlat; -vmCvar_t cg_smoothPlayerPlatAccel; +vmCvar_t cg_smoothPlayerPos; +vmCvar_t cg_smoothPlayerPlat; +vmCvar_t cg_smoothPlayerPlatAccel; typedef struct { - vmCvar_t *vmCvar; - const char *cvarName; - const char *defaultString; - int cvarFlags; + vmCvar_t *vmCvar; + const char *cvarName; + const char *defaultString; + int cvarFlags; } cvarTable_t; static cvarTable_t cvarTable[] = { - { &cg_autoswitch, "cg_autoswitch", "1", CVAR_ARCHIVE }, - { &cg_drawGun, "cg_drawGun", "1", CVAR_ARCHIVE }, - { &cg_fov, "cg_fov", "80", CVAR_ARCHIVE }, - { &cg_fovAspectAdjust, "cg_fovAspectAdjust", "0", CVAR_ARCHIVE }, - { &cg_stereoSeparation, "cg_stereoSeparation", "0.4", CVAR_ARCHIVE }, - { &cg_shadows, "cg_shadows", "1", CVAR_ARCHIVE }, - - { &cg_draw2D, "cg_draw2D", "1", CVAR_ARCHIVE }, - { &cg_drawStatus, "cg_drawStatus", "1", CVAR_ARCHIVE }, - { &cg_drawHUD, "cg_drawHUD", "1", 0 }, - { &cg_drawTimer, "cg_drawTimer", "0", CVAR_ARCHIVE }, - { &cg_drawFPS, "cg_drawFPS", "0", CVAR_ARCHIVE }, - { &cg_drawSnapshot, "cg_drawSnapshot", "0", CVAR_ARCHIVE }, - { &cg_drawAmmoWarning, "cg_drawAmmoWarning", "1", CVAR_ARCHIVE }, - { &cg_drawCrosshair, "cg_drawCrosshair", "1", CVAR_ARCHIVE }, - { &cg_dynamicCrosshair, "cg_dynamicCrosshair", "1", CVAR_ARCHIVE }, - { &cg_crosshairIdentifyTarget, "cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE }, - { &cg_crosshairForceHint, "cg_crosshairForceHint", "1", CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART }, - { &cg_missionstatusscreen, "cg_missionstatusscreen", "0", CVAR_ROM}, - { &cg_endcredits, "cg_endcredits", "0", 0}, - { &cg_updatedDataPadForcePower1, "cg_updatedDataPadForcePower1", "0", 0}, - { &cg_updatedDataPadForcePower2, "cg_updatedDataPadForcePower2", "0", 0}, - { &cg_updatedDataPadForcePower3, "cg_updatedDataPadForcePower3", "0", 0}, - { &cg_updatedDataPadObjective, "cg_updatedDataPadObjective", "0", 0}, - - { &cg_crosshairSize, "cg_crosshairSize", "24", CVAR_ARCHIVE }, - { &cg_crosshairX, "cg_crosshairX", "0", CVAR_ARCHIVE }, - { &cg_crosshairY, "cg_crosshairY", "0", CVAR_ARCHIVE }, - { &cg_simpleItems, "cg_simpleItems", "0", CVAR_ARCHIVE }, - { &cg_addMarks, "cg_marks", "1", CVAR_ARCHIVE }, - - { &cg_gun_frame, "gun_frame", "0", CVAR_CHEAT }, - { &cg_gun_x, "cg_gunX", "0", CVAR_CHEAT }, - { &cg_gun_y, "cg_gunY", "0", CVAR_CHEAT }, - { &cg_gun_z, "cg_gunZ", "0", CVAR_CHEAT }, - { &cg_centertime, "cg_centertime", "3", CVAR_CHEAT }, - { &cg_fovViewmodel, "cg_fovViewModel", "0", CVAR_ARCHIVE }, - { &cg_fovViewmodelAdjust, "cg_fovViewmodelAdjust", "1", CVAR_ARCHIVE }, - - { &cg_runpitch, "cg_runpitch", "0.002", CVAR_ARCHIVE}, - { &cg_runroll, "cg_runroll", "0.005", CVAR_ARCHIVE }, - { &cg_bobup , "cg_bobup", "0.005", CVAR_ARCHIVE }, - { &cg_bobpitch, "cg_bobpitch", "0.002", CVAR_ARCHIVE }, - { &cg_bobroll, "cg_bobroll", "0.002", CVAR_ARCHIVE }, - - { &cg_swingSpeed, "cg_swingSpeed", "0.3", CVAR_CHEAT }, - { &cg_animSpeed, "cg_animspeed", "1", CVAR_CHEAT }, - { &cg_debugAnim, "cg_debuganim", "0", CVAR_CHEAT }, - { &cg_debugSaber, "cg_debugsaber", "0", CVAR_CHEAT }, - { &cg_debugPosition, "cg_debugposition", "0", CVAR_CHEAT }, - { &cg_debugEvents, "cg_debugevents", "0", CVAR_CHEAT }, - { &cg_errorDecay, "cg_errordecay", "100", 0 }, - { &cg_noPlayerAnims, "cg_noplayeranims", "0", CVAR_CHEAT }, - { &cg_footsteps, "cg_footsteps", "1", CVAR_CHEAT }, - - { &cg_thirdPerson, "cg_thirdPerson", "0", CVAR_SAVEGAME }, - { &cg_thirdPersonRange, "cg_thirdPersonRange", "80", CVAR_ARCHIVE }, - { &cg_thirdPersonMaxRange, "cg_thirdPersonMaxRange", "150", 0 }, - { &cg_thirdPersonAngle, "cg_thirdPersonAngle", "0", 0 }, - { &cg_thirdPersonPitchOffset, "cg_thirdPersonPitchOffset", "0", 0 }, - { &cg_thirdPersonVertOffset, "cg_thirdPersonVertOffset", "16", 0}, - { &cg_thirdPersonCameraDamp, "cg_thirdPersonCameraDamp", "0.3", 0}, - { &cg_thirdPersonTargetDamp, "cg_thirdPersonTargetDamp", "0.5", 0}, - - { &cg_thirdPersonHorzOffset, "cg_thirdPersonHorzOffset", "0", 0}, - { &cg_thirdPersonAlpha, "cg_thirdPersonAlpha", "1.0", CVAR_CHEAT }, - { &cg_thirdPersonAutoAlpha, "cg_thirdPersonAutoAlpha", "0", 0 }, - - { &cg_saberAutoThird, "cg_saberAutoThird", "1", CVAR_ARCHIVE }, - { &cg_gunAutoFirst, "cg_gunAutoFirst", "1", CVAR_ARCHIVE }, - - { &cg_pano, "pano", "0", 0 }, - { &cg_panoNumShots, "panoNumShots", "10", 0 }, - - { &fx_freeze, "fx_freeze", "0", 0 }, - { &fx_debug, "fx_debug", "0", 0 }, + {&cg_autoswitch, "cg_autoswitch", "1", CVAR_ARCHIVE}, + {&cg_drawGun, "cg_drawGun", "1", CVAR_ARCHIVE}, + {&cg_fov, "cg_fov", "80", CVAR_ARCHIVE}, + {&cg_fovAspectAdjust, "cg_fovAspectAdjust", "0", CVAR_ARCHIVE}, + {&cg_stereoSeparation, "cg_stereoSeparation", "0.4", CVAR_ARCHIVE}, + {&cg_shadows, "cg_shadows", "1", CVAR_ARCHIVE}, + + {&cg_draw2D, "cg_draw2D", "1", CVAR_ARCHIVE}, + {&cg_drawStatus, "cg_drawStatus", "1", CVAR_ARCHIVE}, + {&cg_drawHUD, "cg_drawHUD", "1", 0}, + {&cg_drawTimer, "cg_drawTimer", "0", CVAR_ARCHIVE}, + {&cg_drawFPS, "cg_drawFPS", "0", CVAR_ARCHIVE}, + {&cg_drawSnapshot, "cg_drawSnapshot", "0", CVAR_ARCHIVE}, + {&cg_drawAmmoWarning, "cg_drawAmmoWarning", "1", CVAR_ARCHIVE}, + {&cg_drawCrosshair, "cg_drawCrosshair", "1", CVAR_ARCHIVE}, + {&cg_dynamicCrosshair, "cg_dynamicCrosshair", "1", CVAR_ARCHIVE}, + {&cg_crosshairIdentifyTarget, "cg_crosshairIdentifyTarget", "1", CVAR_ARCHIVE}, + {&cg_crosshairForceHint, "cg_crosshairForceHint", "1", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART}, + {&cg_missionstatusscreen, "cg_missionstatusscreen", "0", CVAR_ROM}, + {&cg_endcredits, "cg_endcredits", "0", 0}, + {&cg_updatedDataPadForcePower1, "cg_updatedDataPadForcePower1", "0", 0}, + {&cg_updatedDataPadForcePower2, "cg_updatedDataPadForcePower2", "0", 0}, + {&cg_updatedDataPadForcePower3, "cg_updatedDataPadForcePower3", "0", 0}, + {&cg_updatedDataPadObjective, "cg_updatedDataPadObjective", "0", 0}, + + {&cg_crosshairSize, "cg_crosshairSize", "24", CVAR_ARCHIVE}, + {&cg_crosshairX, "cg_crosshairX", "0", CVAR_ARCHIVE}, + {&cg_crosshairY, "cg_crosshairY", "0", CVAR_ARCHIVE}, + {&cg_simpleItems, "cg_simpleItems", "0", CVAR_ARCHIVE}, + {&cg_addMarks, "cg_marks", "1", CVAR_ARCHIVE}, + + {&cg_gun_frame, "gun_frame", "0", CVAR_CHEAT}, + {&cg_gun_x, "cg_gunX", "0", CVAR_CHEAT}, + {&cg_gun_y, "cg_gunY", "0", CVAR_CHEAT}, + {&cg_gun_z, "cg_gunZ", "0", CVAR_CHEAT}, + {&cg_centertime, "cg_centertime", "3", CVAR_CHEAT}, + {&cg_fovViewmodel, "cg_fovViewModel", "0", CVAR_ARCHIVE}, + {&cg_fovViewmodelAdjust, "cg_fovViewmodelAdjust", "1", CVAR_ARCHIVE}, + + {&cg_runpitch, "cg_runpitch", "0.002", CVAR_ARCHIVE}, + {&cg_runroll, "cg_runroll", "0.005", CVAR_ARCHIVE}, + {&cg_bobup, "cg_bobup", "0.005", CVAR_ARCHIVE}, + {&cg_bobpitch, "cg_bobpitch", "0.002", CVAR_ARCHIVE}, + {&cg_bobroll, "cg_bobroll", "0.002", CVAR_ARCHIVE}, + + {&cg_swingSpeed, "cg_swingSpeed", "0.3", CVAR_CHEAT}, + {&cg_animSpeed, "cg_animspeed", "1", CVAR_CHEAT}, + {&cg_debugAnim, "cg_debuganim", "0", CVAR_CHEAT}, + {&cg_debugSaber, "cg_debugsaber", "0", CVAR_CHEAT}, + {&cg_debugPosition, "cg_debugposition", "0", CVAR_CHEAT}, + {&cg_debugEvents, "cg_debugevents", "0", CVAR_CHEAT}, + {&cg_errorDecay, "cg_errordecay", "100", 0}, + {&cg_noPlayerAnims, "cg_noplayeranims", "0", CVAR_CHEAT}, + {&cg_footsteps, "cg_footsteps", "1", CVAR_CHEAT}, + + {&cg_thirdPerson, "cg_thirdPerson", "0", CVAR_SAVEGAME}, + {&cg_thirdPersonRange, "cg_thirdPersonRange", "80", CVAR_ARCHIVE}, + {&cg_thirdPersonMaxRange, "cg_thirdPersonMaxRange", "150", 0}, + {&cg_thirdPersonAngle, "cg_thirdPersonAngle", "0", 0}, + {&cg_thirdPersonPitchOffset, "cg_thirdPersonPitchOffset", "0", 0}, + {&cg_thirdPersonVertOffset, "cg_thirdPersonVertOffset", "16", 0}, + {&cg_thirdPersonCameraDamp, "cg_thirdPersonCameraDamp", "0.3", 0}, + {&cg_thirdPersonTargetDamp, "cg_thirdPersonTargetDamp", "0.5", 0}, + + {&cg_thirdPersonHorzOffset, "cg_thirdPersonHorzOffset", "0", 0}, + {&cg_thirdPersonAlpha, "cg_thirdPersonAlpha", "1.0", CVAR_CHEAT}, + {&cg_thirdPersonAutoAlpha, "cg_thirdPersonAutoAlpha", "0", 0}, + + {&cg_saberAutoThird, "cg_saberAutoThird", "1", CVAR_ARCHIVE}, + {&cg_gunAutoFirst, "cg_gunAutoFirst", "1", CVAR_ARCHIVE}, + + {&cg_pano, "pano", "0", 0}, + {&cg_panoNumShots, "panoNumShots", "10", 0}, + + {&fx_freeze, "fx_freeze", "0", 0}, + {&fx_debug, "fx_debug", "0", 0}, // the following variables are created in other parts of the system, // but we also reference them here - { &cg_paused, "cl_paused", "0", CVAR_ROM }, - { &cg_developer, "developer", "", 0 }, - { &cg_timescale, "timescale", "1", 0 }, - { &cg_skippingcin, "skippingCinematic", "0", CVAR_ROM}, - { &cg_missionInfoCentered, "cg_missionInfoCentered", "1", CVAR_ARCHIVE }, - { &cg_missionInfoFlashTime, "cg_missionInfoFlashTime", "10000", 0 }, - { &cg_hudFiles, "cg_hudFiles", "ui/jk2hud.txt", CVAR_ARCHIVE}, -/* -Ghoul2 Insert Start -*/ - { &cg_debugBB, "debugBB", "0", 0}, -/* -Ghoul2 Insert End -*/ - { &cg_VariantSoundCap, "cg_VariantSoundCap", "0", 0 }, - { &cg_turnAnims, "cg_turnAnims", "0", 0 }, - { &cg_motionBoneComp, "cg_motionBoneComp", "2", 0 }, - { &cg_reliableAnimSounds, "cg_reliableAnimSounds", "1", CVAR_ARCHIVE }, - { &cg_smoothPlayerPos, "cg_smoothPlayerPos", "0.5", 0}, - { &cg_smoothPlayerPlat, "cg_smoothPlayerPlat", "0.75", 0}, - { &cg_smoothPlayerPlatAccel, "cg_smoothPlayerPlatAccel", "3.25", 0}, + {&cg_paused, "cl_paused", "0", CVAR_ROM}, + {&cg_developer, "developer", "", 0}, + {&cg_timescale, "timescale", "1", 0}, + {&cg_skippingcin, "skippingCinematic", "0", CVAR_ROM}, + {&cg_missionInfoCentered, "cg_missionInfoCentered", "1", CVAR_ARCHIVE}, + {&cg_missionInfoFlashTime, "cg_missionInfoFlashTime", "10000", 0}, + {&cg_hudFiles, "cg_hudFiles", "ui/jk2hud.txt", CVAR_ARCHIVE}, + /* + Ghoul2 Insert Start + */ + {&cg_debugBB, "debugBB", "0", 0}, + /* + Ghoul2 Insert End + */ + {&cg_VariantSoundCap, "cg_VariantSoundCap", "0", 0}, + {&cg_turnAnims, "cg_turnAnims", "0", 0}, + {&cg_motionBoneComp, "cg_motionBoneComp", "2", 0}, + {&cg_reliableAnimSounds, "cg_reliableAnimSounds", "1", CVAR_ARCHIVE}, + {&cg_smoothPlayerPos, "cg_smoothPlayerPos", "0.5", 0}, + {&cg_smoothPlayerPlat, "cg_smoothPlayerPlat", "0.75", 0}, + {&cg_smoothPlayerPlatAccel, "cg_smoothPlayerPlatAccel", "3.25", 0}, }; -static const size_t cvarTableSize = ARRAY_LEN( cvarTable ); +static const size_t cvarTableSize = ARRAY_LEN(cvarTable); /* ================= CG_RegisterCvars ================= */ -void CG_RegisterCvars( void ) { - size_t i; - cvarTable_t *cv; +void CG_RegisterCvars(void) { + size_t i; + cvarTable_t *cv; - for ( i=0, cv=cvarTable; ivmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + cgi_Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); } } @@ -461,44 +423,38 @@ void CG_RegisterCvars( void ) { CG_UpdateCvars ================= */ -void CG_UpdateCvars( void ) { - size_t i; - cvarTable_t *cv; +void CG_UpdateCvars(void) { + size_t i; + cvarTable_t *cv; - for ( i=0, cv=cvarTable; ivmCvar ) { - cgi_Cvar_Update( cv->vmCvar ); + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + if (cv->vmCvar) { + cgi_Cvar_Update(cv->vmCvar); } } } -int CG_CrosshairPlayer( void ) -{ - if ( cg.time > ( cg.crosshairClientTime + 1000 ) ) - { +int CG_CrosshairPlayer(void) { + if (cg.time > (cg.crosshairClientTime + 1000)) { return -1; } return cg.crosshairClientNum; } - -int CG_GetCameraPos( vec3_t camerapos ) { - if ( in_camera) { +int CG_GetCameraPos(vec3_t camerapos) { + if (in_camera) { VectorCopy(client_camera.origin, camerapos); return 1; - } - else if ( cg_entities[0].gent && cg_entities[0].gent->client && cg_entities[0].gent->client->ps.viewEntity > 0 && cg_entities[0].gent->client->ps.viewEntity < ENTITYNUM_WORLD ) - //else if ( cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view - if ( g_entities[cg_entities[0].gent->client->ps.viewEntity].client && cg.renderingThirdPerson ) - { - VectorCopy( g_entities[cg_entities[0].gent->client->ps.viewEntity].client->renderInfo.eyePoint, camerapos ); - } - else - { - VectorCopy( g_entities[cg_entities[0].gent->client->ps.viewEntity].currentOrigin, camerapos ); + } else if (cg_entities[0].gent && cg_entities[0].gent->client && cg_entities[0].gent->client->ps.viewEntity > 0 && + cg_entities[0].gent->client->ps.viewEntity < ENTITYNUM_WORLD) + // else if ( cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) + { // in an entity camera view + if (g_entities[cg_entities[0].gent->client->ps.viewEntity].client && cg.renderingThirdPerson) { + VectorCopy(g_entities[cg_entities[0].gent->client->ps.viewEntity].client->renderInfo.eyePoint, camerapos); + } else { + VectorCopy(g_entities[cg_entities[0].gent->client->ps.viewEntity].currentOrigin, camerapos); } - //VectorCopy( cg_entities[cg_entities[0].gent->client->ps.viewEntity].lerpOrigin, camerapos ); + // VectorCopy( cg_entities[cg_entities[0].gent->client->ps.viewEntity].lerpOrigin, camerapos ); /* if ( g_entities[cg.snap->ps.viewEntity].client && cg.renderingThirdPerson ) { @@ -510,58 +466,53 @@ int CG_GetCameraPos( vec3_t camerapos ) { } */ return 1; - } - else if ( cg.renderingThirdPerson ) - {//in third person - //FIXME: what about hacks that render in third person regardless of this value? - VectorCopy( cg.refdef.vieworg, camerapos ); + } else if (cg.renderingThirdPerson) { // in third person + // FIXME: what about hacks that render in third person regardless of this value? + VectorCopy(cg.refdef.vieworg, camerapos); return 1; - } - else if (cg.snap && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//implied: !cg.renderingThirdPerson - {//first person saber hack - VectorCopy( cg.refdef.vieworg, camerapos ); + } else if (cg.snap && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // implied: !cg.renderingThirdPerson + { // first person saber hack + VectorCopy(cg.refdef.vieworg, camerapos); return 1; } return 0; } -void CG_Printf( const char *msg, ... ) { - va_list argptr; - char text[1024]; +void CG_Printf(const char *msg, ...) { + va_list argptr; + char text[1024]; - va_start (argptr, msg); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end (argptr); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - cgi_Printf( text ); + cgi_Printf(text); } -NORETURN void CG_Error( const char *msg, ... ) { - va_list argptr; - char text[1024]; +NORETURN void CG_Error(const char *msg, ...) { + va_list argptr; + char text[1024]; - va_start (argptr, msg); - Q_vsnprintf (text, sizeof(text), msg, argptr); - va_end (argptr); + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - cgi_Error( text ); + cgi_Error(text); } - /* ================ CG_Argv ================ */ -const char *CG_Argv( int arg ) { - static char buffer[MAX_STRING_CHARS]; +const char *CG_Argv(int arg) { + static char buffer[MAX_STRING_CHARS]; - cgi_Argv( arg, buffer, sizeof( buffer ) ); + cgi_Argv(arg, buffer, sizeof(buffer)); return buffer; } - //======================================================================== /* @@ -571,17 +522,16 @@ CG_RegisterItemSounds The server says this item is used on this level ================= */ -void CG_RegisterItemSounds( int itemNum ) { - gitem_t *item; - char data[MAX_QPATH]; - char *s, *start; - int len; +void CG_RegisterItemSounds(int itemNum) { + gitem_t *item; + char data[MAX_QPATH]; + char *s, *start; + int len; - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - if (item->pickup_sound) - { - cgi_S_RegisterSound( item->pickup_sound ); + if (item->pickup_sound) { + cgi_S_RegisterSound(item->pickup_sound); } // parse the space seperated precache string for other media @@ -595,20 +545,19 @@ void CG_RegisterItemSounds( int itemNum ) { s++; } - len = s-start; + len = s - start; if (len >= MAX_QPATH || len < 5) { - CG_Error( "PrecacheItem: %s has bad precache string", - item->classname); + CG_Error("PrecacheItem: %s has bad precache string", item->classname); return; } - memcpy (data, start, len); + memcpy(data, start, len); data[len] = 0; - if ( *s ) { + if (*s) { s++; } - if ( !strcmp(data+len-3, "wav" )) { - cgi_S_RegisterSound( data ); + if (!strcmp(data + len - 3, "wav")) { + cgi_S_RegisterSound(data); } } } @@ -619,30 +568,24 @@ CG_LoadingString ====================== */ -void CG_LoadingString( const char *s ) { - Q_strncpyz( cg.infoScreenText, s, sizeof( cg.infoScreenText ) ); +void CG_LoadingString(const char *s) { + Q_strncpyz(cg.infoScreenText, s, sizeof(cg.infoScreenText)); cgi_UpdateScreen(); } +static void CG_AS_Register(void) { + CG_LoadingString("ambient sound sets"); -static void CG_AS_Register(void) -{ - CG_LoadingString( "ambient sound sets" ); - - //Load the ambient sets + // Load the ambient sets - cgi_AS_AddPrecacheEntry( "#clear" ); // ;-) - //FIXME: Don't ask... I had to get around a really nasty MS error in the templates with this... - namePrecache_m::iterator pi; - STL_ITERATE( pi, (*as_preCacheMap) ) - { - cgi_AS_AddPrecacheEntry( ((*pi).first).c_str() ); - } + cgi_AS_AddPrecacheEntry("#clear"); // ;-) + // FIXME: Don't ask... I had to get around a really nasty MS error in the templates with this... + namePrecache_m::iterator pi; + STL_ITERATE(pi, (*as_preCacheMap)) { cgi_AS_AddPrecacheEntry(((*pi).first).c_str()); } cgi_AS_ParseSets(); } - /* ================= CG_RegisterSounds @@ -650,112 +593,112 @@ CG_RegisterSounds called during a precache command ================= */ -static void CG_RegisterSounds( void ) { - int i; - char name[MAX_QPATH]; - const char *soundName; +static void CG_RegisterSounds(void) { + int i; + char name[MAX_QPATH]; + const char *soundName; CG_AS_Register(); - CG_LoadingString( "general sounds" ); + CG_LoadingString("general sounds"); - //FIXME: add to cg.media? - cgi_S_RegisterSound( "sound/player/fallsplat.wav" ); + // FIXME: add to cg.media? + cgi_S_RegisterSound("sound/player/fallsplat.wav"); - cgs.media.selectSound = cgi_S_RegisterSound( "sound/weapons/change.wav" ); - cgs.media.selectSound2 = cgi_S_RegisterSound( "sound/interface/button1.wav" ); -// cgs.media.useNothingSound = cgi_S_RegisterSound( "sound/items/use_nothing.wav" ); + cgs.media.selectSound = cgi_S_RegisterSound("sound/weapons/change.wav"); + cgs.media.selectSound2 = cgi_S_RegisterSound("sound/interface/button1.wav"); + // cgs.media.useNothingSound = cgi_S_RegisterSound( "sound/items/use_nothing.wav" ); - cgs.media.noAmmoSound = cgi_S_RegisterSound( "sound/weapons/noammo.wav" ); -// cgs.media.talkSound = cgi_S_RegisterSound( "sound/interface/communicator.wav" ); - cgs.media.landSound = cgi_S_RegisterSound( "sound/player/land1.wav"); - cgs.media.rollSound = cgi_S_RegisterSound( "sound/player/roll1.wav"); + cgs.media.noAmmoSound = cgi_S_RegisterSound("sound/weapons/noammo.wav"); + // cgs.media.talkSound = cgi_S_RegisterSound( "sound/interface/communicator.wav" ); + cgs.media.landSound = cgi_S_RegisterSound("sound/player/land1.wav"); + cgs.media.rollSound = cgi_S_RegisterSound("sound/player/roll1.wav"); - cgs.media.overchargeFastSound = cgi_S_RegisterSound("sound/weapons/overchargeFast.wav" ); - cgs.media.overchargeSlowSound = cgi_S_RegisterSound("sound/weapons/overchargeSlow.wav" ); - cgs.media.overchargeLoopSound = cgi_S_RegisterSound("sound/weapons/overchargeLoop.wav"); - cgs.media.overchargeEndSound = cgi_S_RegisterSound("sound/weapons/overchargeEnd.wav"); + cgs.media.overchargeFastSound = cgi_S_RegisterSound("sound/weapons/overchargeFast.wav"); + cgs.media.overchargeSlowSound = cgi_S_RegisterSound("sound/weapons/overchargeSlow.wav"); + cgs.media.overchargeLoopSound = cgi_S_RegisterSound("sound/weapons/overchargeLoop.wav"); + cgs.media.overchargeEndSound = cgi_S_RegisterSound("sound/weapons/overchargeEnd.wav"); - cgs.media.batteryChargeSound = cgi_S_RegisterSound( "sound/interface/pickup_battery.wav" ); + cgs.media.batteryChargeSound = cgi_S_RegisterSound("sound/interface/pickup_battery.wav"); -// cgs.media.tedTextSound = cgi_S_RegisterSound( "sound/interface/tedtext.wav" ); - cgs.media.messageLitSound = cgi_S_RegisterSound( "sound/interface/update" ); + // cgs.media.tedTextSound = cgi_S_RegisterSound( "sound/interface/tedtext.wav" ); + cgs.media.messageLitSound = cgi_S_RegisterSound("sound/interface/update"); cg.messageLitActive = qfalse; -// cgs.media.interfaceSnd1 = cgi_S_RegisterSound( "sound/interface/button4.wav" ); -// cgs.media.interfaceSnd2 = cgi_S_RegisterSound( "sound/interface/button2.wav" ); -// cgs.media.interfaceSnd3 = cgi_S_RegisterSound( "sound/interface/button1.wav" ); + // cgs.media.interfaceSnd1 = cgi_S_RegisterSound( "sound/interface/button4.wav" ); + // cgs.media.interfaceSnd2 = cgi_S_RegisterSound( "sound/interface/button2.wav" ); + // cgs.media.interfaceSnd3 = cgi_S_RegisterSound( "sound/interface/button1.wav" ); - cgs.media.watrInSound = cgi_S_RegisterSound ("sound/player/watr_in.wav"); - cgs.media.watrOutSound = cgi_S_RegisterSound ("sound/player/watr_out.wav"); - cgs.media.watrUnSound = cgi_S_RegisterSound ("sound/player/watr_un.wav"); + cgs.media.watrInSound = cgi_S_RegisterSound("sound/player/watr_in.wav"); + cgs.media.watrOutSound = cgi_S_RegisterSound("sound/player/watr_out.wav"); + cgs.media.watrUnSound = cgi_S_RegisterSound("sound/player/watr_un.wav"); // Zoom - cgs.media.zoomStart = cgi_S_RegisterSound( "sound/interface/zoomstart.wav" ); - cgs.media.zoomLoop = cgi_S_RegisterSound( "sound/interface/zoomloop.wav" ); - cgs.media.zoomEnd = cgi_S_RegisterSound( "sound/interface/zoomend.wav" ); + cgs.media.zoomStart = cgi_S_RegisterSound("sound/interface/zoomstart.wav"); + cgs.media.zoomLoop = cgi_S_RegisterSound("sound/interface/zoomloop.wav"); + cgs.media.zoomEnd = cgi_S_RegisterSound("sound/interface/zoomend.wav"); - cgi_S_RegisterSound( "sound/chars/turret/startup.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/shutdown.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/ping.wav" ); - cgi_S_RegisterSound( "sound/chars/turret/move.wav" ); - cgi_S_RegisterSound( "sound/player/use_sentry" ); - cgi_R_RegisterModel( "models/items/psgun.glm" ); - theFxScheduler.RegisterEffect( "turret/explode" ); - theFxScheduler.RegisterEffect( "spark_exp_nosnd" ); + cgi_S_RegisterSound("sound/chars/turret/startup.wav"); + cgi_S_RegisterSound("sound/chars/turret/shutdown.wav"); + cgi_S_RegisterSound("sound/chars/turret/ping.wav"); + cgi_S_RegisterSound("sound/chars/turret/move.wav"); + cgi_S_RegisterSound("sound/player/use_sentry"); + cgi_R_RegisterModel("models/items/psgun.glm"); + theFxScheduler.RegisterEffect("turret/explode"); + theFxScheduler.RegisterEffect("spark_exp_nosnd"); - for (i=0 ; i<4 ; i++) { - Com_sprintf (name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_NORMAL][i] = cgi_S_RegisterSound (name); + for (i = 0; i < 4; i++) { + Com_sprintf(name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_NORMAL][i] = cgi_S_RegisterSound(name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_METAL][i] = cgi_S_RegisterSound (name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_METAL][i] = cgi_S_RegisterSound(name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SPLASH][i] = cgi_S_RegisterSound (name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SPLASH][i] = cgi_S_RegisterSound(name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WADE][i] = cgi_S_RegisterSound (name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WADE][i] = cgi_S_RegisterSound(name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SWIM][i] = cgi_S_RegisterSound (name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SWIM][i] = cgi_S_RegisterSound(name); // should these always be registered?? - Com_sprintf (name, sizeof(name), "sound/player/footsteps/boot%i.wav", i+1); - cgi_S_RegisterSound (name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/boot%i.wav", i + 1); + cgi_S_RegisterSound(name); } - theFxScheduler.RegisterEffect( "water_impact" ); + theFxScheduler.RegisterEffect("water_impact"); cg.loadLCARSStage = 1; - CG_LoadingString( "item sounds" ); + CG_LoadingString("item sounds"); // only register the items that the server says we need - char items[MAX_ITEMS+1]; - //Raz: Fixed buffer overflow + char items[MAX_ITEMS + 1]; + // Raz: Fixed buffer overflow Q_strncpyz(items, CG_ConfigString(CS_ITEMS), sizeof(items)); - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( items[ i ] == '1' ) //even with sound pooling, don't clutter it for low end machines + for (i = 1; i < bg_numItems; i++) { + if (items[i] == '1') // even with sound pooling, don't clutter it for low end machines { - CG_RegisterItemSounds( i ); + CG_RegisterItemSounds(i); } } cg.loadLCARSStage = 2; - CG_LoadingString( "preregistered sounds" ); + CG_LoadingString("preregistered sounds"); - for ( i = 1 ; i < MAX_SOUNDS ; i++ ) { - soundName = CG_ConfigString( CS_SOUNDS+i ); - if ( !soundName[0] ) { + for (i = 1; i < MAX_SOUNDS; i++) { + soundName = CG_ConfigString(CS_SOUNDS + i); + if (!soundName[0]) { break; } - if ( soundName[0] == '*' ) { - continue; // custom sound + if (soundName[0] == '*') { + continue; // custom sound } - if (i&31) { - CG_LoadingString( soundName ); + if (i & 31) { + CG_LoadingString(soundName); } - cgs.sound_precache[i] = cgi_S_RegisterSound( soundName ); + cgs.sound_precache[i] = cgi_S_RegisterSound(soundName); } } @@ -767,26 +710,21 @@ CLIENT INFO ============================================================================= */ -qhandle_t CG_RegisterHeadSkin( const char *headModelName, const char *headSkinName, qboolean *extensions ) -{ - char hfilename[MAX_QPATH]; - qhandle_t headSkin; +qhandle_t CG_RegisterHeadSkin(const char *headModelName, const char *headSkinName, qboolean *extensions) { + char hfilename[MAX_QPATH]; + qhandle_t headSkin; - Com_sprintf( hfilename, sizeof( hfilename ), "models/players/%s/head_%s.skin", headModelName, headSkinName ); - headSkin = cgi_R_RegisterSkin( hfilename ); - if ( headSkin < 0 ) - { //have extensions + Com_sprintf(hfilename, sizeof(hfilename), "models/players/%s/head_%s.skin", headModelName, headSkinName); + headSkin = cgi_R_RegisterSkin(hfilename); + if (headSkin < 0) { // have extensions *extensions = qtrue; headSkin = -headSkin; - } - else - { - *extensions = qfalse; //just to be sure. + } else { + *extensions = qfalse; // just to be sure. } - if ( !headSkin ) - { - Com_Printf( "Failed to load skin file: %s : %s\n", headModelName, headSkinName ); + if (!headSkin) { + Com_Printf("Failed to load skin file: %s : %s\n", headModelName, headSkinName); } return headSkin; } @@ -796,50 +734,42 @@ qhandle_t CG_RegisterHeadSkin( const char *headModelName, const char *headSkinNa CG_RegisterClientSkin ========================== */ -qboolean CG_RegisterClientSkin( clientInfo_t *ci, - const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName) -{ - char hfilename[MAX_QPATH]; - char tfilename[MAX_QPATH]; - char lfilename[MAX_QPATH]; +qboolean CG_RegisterClientSkin(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, const char *torsoSkinName, + const char *legsModelName, const char *legsSkinName) { + char hfilename[MAX_QPATH]; + char tfilename[MAX_QPATH]; + char lfilename[MAX_QPATH]; - Com_sprintf( lfilename, sizeof( lfilename ), "models/players/%s/lower_%s.skin", legsModelName, legsSkinName ); - ci->legsSkin = cgi_R_RegisterSkin( lfilename ); + Com_sprintf(lfilename, sizeof(lfilename), "models/players/%s/lower_%s.skin", legsModelName, legsSkinName); + ci->legsSkin = cgi_R_RegisterSkin(lfilename); - if ( !ci->legsSkin ) - { -// Com_Printf( "Failed to load skin file: %s : %s\n", legsModelName, legsSkinName ); - //return qfalse; + if (!ci->legsSkin) { + // Com_Printf( "Failed to load skin file: %s : %s\n", legsModelName, legsSkinName ); + // return qfalse; } - if(torsoModelName && torsoSkinName && torsoModelName[0] && torsoSkinName[0]) - { - Com_sprintf( tfilename, sizeof( tfilename ), "models/players/%s/upper_%s.skin", torsoModelName, torsoSkinName ); - ci->torsoSkin = cgi_R_RegisterSkin( tfilename ); + if (torsoModelName && torsoSkinName && torsoModelName[0] && torsoSkinName[0]) { + Com_sprintf(tfilename, sizeof(tfilename), "models/players/%s/upper_%s.skin", torsoModelName, torsoSkinName); + ci->torsoSkin = cgi_R_RegisterSkin(tfilename); - if ( !ci->torsoSkin ) - { - Com_Printf( "Failed to load skin file: %s : %s\n", torsoModelName, torsoSkinName ); + if (!ci->torsoSkin) { + Com_Printf("Failed to load skin file: %s : %s\n", torsoModelName, torsoSkinName); return qfalse; } } - if(headModelName && headSkinName && headModelName[0] && headSkinName[0]) - { - Com_sprintf( hfilename, sizeof( hfilename ), "models/players/%s/head_%s.skin", headModelName, headSkinName ); - ci->headSkin = cgi_R_RegisterSkin( hfilename ); - if (ci->headSkin <0) { //have extensions + if (headModelName && headSkinName && headModelName[0] && headSkinName[0]) { + Com_sprintf(hfilename, sizeof(hfilename), "models/players/%s/head_%s.skin", headModelName, headSkinName); + ci->headSkin = cgi_R_RegisterSkin(hfilename); + if (ci->headSkin < 0) { // have extensions ci->extensions = qtrue; ci->headSkin = -ci->headSkin; } else { - ci->extensions = qfalse; //just to be sure. + ci->extensions = qfalse; // just to be sure. } - if ( !ci->headSkin ) - { - Com_Printf( "Failed to load skin file: %s : %s\n", headModelName, headSkinName ); + if (!ci->headSkin) { + Com_Printf("Failed to load skin file: %s : %s\n", headModelName, headSkinName); return qfalse; } } @@ -852,173 +782,135 @@ qboolean CG_RegisterClientSkin( clientInfo_t *ci, CG_RegisterClientModelname ========================== */ -qboolean CG_RegisterClientModelname( clientInfo_t *ci, - const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName ) -{ +qboolean CG_RegisterClientModelname(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, + const char *torsoSkinName, const char *legsModelName, const char *legsSkinName) { /* Ghoul2 Insert Start */ #if 1 - char filename[MAX_QPATH]; + char filename[MAX_QPATH]; - - if ( !legsModelName || !legsModelName[0] ) - { + if (!legsModelName || !legsModelName[0]) { return qtrue; } - Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.mdr", legsModelName ); - ci->legsModel = cgi_R_RegisterModel( filename ); - if ( !ci->legsModel ) - {//he's not skeletal, try the old way - Com_sprintf( filename, sizeof( filename ), "models/players/%s/lower.md3", legsModelName ); - ci->legsModel = cgi_R_RegisterModel( filename ); - if ( !ci->legsModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + Com_sprintf(filename, sizeof(filename), "models/players/%s/lower.mdr", legsModelName); + ci->legsModel = cgi_R_RegisterModel(filename); + if (!ci->legsModel) { // he's not skeletal, try the old way + Com_sprintf(filename, sizeof(filename), "models/players/%s/lower.md3", legsModelName); + ci->legsModel = cgi_R_RegisterModel(filename); + if (!ci->legsModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } } - if(torsoModelName && torsoModelName[0]) - {//You are trying to set one - Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.mdr", torsoModelName ); - ci->torsoModel = cgi_R_RegisterModel( filename ); - if ( !ci->torsoModel ) - {//he's not skeletal, try the old way - Com_sprintf( filename, sizeof( filename ), "models/players/%s/upper.md3", torsoModelName ); - ci->torsoModel = cgi_R_RegisterModel( filename ); - if ( !ci->torsoModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + if (torsoModelName && torsoModelName[0]) { // You are trying to set one + Com_sprintf(filename, sizeof(filename), "models/players/%s/upper.mdr", torsoModelName); + ci->torsoModel = cgi_R_RegisterModel(filename); + if (!ci->torsoModel) { // he's not skeletal, try the old way + Com_sprintf(filename, sizeof(filename), "models/players/%s/upper.md3", torsoModelName); + ci->torsoModel = cgi_R_RegisterModel(filename); + if (!ci->torsoModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } } - } - else - { + } else { ci->torsoModel = 0; } - if(headModelName && headModelName[0]) - {//You are trying to set one - Com_sprintf( filename, sizeof( filename ), "models/players/%s/head.md3", headModelName ); - ci->headModel = cgi_R_RegisterModel( filename ); - if ( !ci->headModel ) - { - Com_Printf( S_COLOR_RED"Failed to load model file %s\n", filename ); + if (headModelName && headModelName[0]) { // You are trying to set one + Com_sprintf(filename, sizeof(filename), "models/players/%s/head.md3", headModelName); + ci->headModel = cgi_R_RegisterModel(filename); + if (!ci->headModel) { + Com_Printf(S_COLOR_RED "Failed to load model file %s\n", filename); return qfalse; } - } - else - { + } else { ci->headModel = 0; } - // if any skins failed to load, return failure - if ( !CG_RegisterClientSkin( ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName ) ) - { - //Com_Printf( "Failed to load skin file: %s : %s/%s : %s/%s : %s\n", headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName ); + if (!CG_RegisterClientSkin(ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName)) { + // Com_Printf( "Failed to load skin file: %s : %s/%s : %s/%s : %s\n", headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, + // legsSkinName ); return qfalse; } - //FIXME: for now, uses the legs model dir for anim cfg, but should we set this in some sort of NPCs.cfg? - // load the animation file set - if ( !G_ParseAnimFileSet( legsModelName, legsModelName, &ci->animFileIndex ) ) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/%s\n", legsModelName ); + // FIXME: for now, uses the legs model dir for anim cfg, but should we set this in some sort of NPCs.cfg? + // load the animation file set + if (!G_ParseAnimFileSet(legsModelName, legsModelName, &ci->animFileIndex)) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/%s\n", legsModelName); return qfalse; } #endif -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ return qtrue; } +void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) { + char *slash; + char headModelName[MAX_QPATH]; + char torsoModelName[MAX_QPATH]; + char legsModelName[MAX_QPATH]; + char headSkinName[MAX_QPATH]; + char torsoSkinName[MAX_QPATH]; + char legsSkinName[MAX_QPATH]; -void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) -{ - char *slash; - char headModelName[MAX_QPATH]; - char torsoModelName[MAX_QPATH]; - char legsModelName[MAX_QPATH]; - char headSkinName[MAX_QPATH]; - char torsoSkinName[MAX_QPATH]; - char legsSkinName[MAX_QPATH]; - - if(!ri->legsModelName[0]) - {//Must have at LEAST a legs model + if (!ri->legsModelName[0]) { // Must have at LEAST a legs model return; } - Q_strncpyz( legsModelName, ri->legsModelName, sizeof( legsModelName ) ); - //Legs skin - slash = strchr( legsModelName, '/' ); - if ( !slash ) - { + Q_strncpyz(legsModelName, ri->legsModelName, sizeof(legsModelName)); + // Legs skin + slash = strchr(legsModelName, '/'); + if (!slash) { // modelName didn not include a skin name - Q_strncpyz( legsSkinName, "default", sizeof( legsSkinName ) ); - } - else - { - Q_strncpyz( legsSkinName, slash + 1, sizeof( legsSkinName ) ); + Q_strncpyz(legsSkinName, "default", sizeof(legsSkinName)); + } else { + Q_strncpyz(legsSkinName, slash + 1, sizeof(legsSkinName)); // truncate modelName *slash = 0; } - if(ri->torsoModelName[0]) - { - Q_strncpyz( torsoModelName, ri->torsoModelName, sizeof( torsoModelName ) ); - //Torso skin - slash = strchr( torsoModelName, '/' ); - if ( !slash ) - { + if (ri->torsoModelName[0]) { + Q_strncpyz(torsoModelName, ri->torsoModelName, sizeof(torsoModelName)); + // Torso skin + slash = strchr(torsoModelName, '/'); + if (!slash) { // modelName didn't include a skin name - Q_strncpyz( torsoSkinName, "default", sizeof( torsoSkinName ) ); - } - else - { - Q_strncpyz( torsoSkinName, slash + 1, sizeof( torsoSkinName ) ); + Q_strncpyz(torsoSkinName, "default", sizeof(torsoSkinName)); + } else { + Q_strncpyz(torsoSkinName, slash + 1, sizeof(torsoSkinName)); // truncate modelName *slash = 0; } - } - else - { + } else { torsoModelName[0] = 0; } - //Head - if(ri->headModelName[0]) - { - Q_strncpyz( headModelName, ri->headModelName, sizeof( headModelName ) ); - //Head skin - slash = strchr( headModelName, '/' ); - if ( !slash ) - { + // Head + if (ri->headModelName[0]) { + Q_strncpyz(headModelName, ri->headModelName, sizeof(headModelName)); + // Head skin + slash = strchr(headModelName, '/'); + if (!slash) { // modelName didn not include a skin name - Q_strncpyz( headSkinName, "default", sizeof( headSkinName ) ); - } - else - { - Q_strncpyz( headSkinName, slash + 1, sizeof( headSkinName ) ); + Q_strncpyz(headSkinName, "default", sizeof(headSkinName)); + } else { + Q_strncpyz(headSkinName, slash + 1, sizeof(headSkinName)); // truncate modelName *slash = 0; } - } - else - { + } else { headModelName[0] = 0; } - if ( !CG_RegisterClientModelname( ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName) ) - { - if ( !CG_RegisterClientModelname( ci, DEFAULT_HEADMODEL, "default", DEFAULT_TORSOMODEL, "default", DEFAULT_LEGSMODEL, "default" ) ) - { - CG_Error( "DEFAULT_MODELS failed to register"); + if (!CG_RegisterClientModelname(ci, headModelName, headSkinName, torsoModelName, torsoSkinName, legsModelName, legsSkinName)) { + if (!CG_RegisterClientModelname(ci, DEFAULT_HEADMODEL, "default", DEFAULT_TORSOMODEL, "default", DEFAULT_LEGSMODEL, "default")) { + CG_Error("DEFAULT_MODELS failed to register"); } } } @@ -1030,38 +922,33 @@ void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri) // and any shader, model, or sound // files an effect may use. //------------------------------------- -extern void CG_InitGlass( void ); -extern void cgi_R_WorldEffectCommand( const char *command ); +extern void CG_InitGlass(void); +extern void cgi_R_WorldEffectCommand(const char *command); -static void CG_RegisterEffects( void ) -{ - char *effectName; - int i; +static void CG_RegisterEffects(void) { + char *effectName; + int i; // Register external effects - for ( i = 1 ; i < MAX_FX ; i++ ) - { - effectName = ( char *)CG_ConfigString( CS_EFFECTS + i ); + for (i = 1; i < MAX_FX; i++) { + effectName = (char *)CG_ConfigString(CS_EFFECTS + i); - if ( !effectName[0] ) - { + if (!effectName[0]) { break; } - theFxScheduler.RegisterEffect( (const char*)effectName ); + theFxScheduler.RegisterEffect((const char *)effectName); } // Start world effects - for ( i = 1 ; i < MAX_WORLD_FX ; i++ ) - { - effectName = ( char *)CG_ConfigString( CS_WORLD_FX + i ); + for (i = 1; i < MAX_WORLD_FX; i++) { + effectName = (char *)CG_ConfigString(CS_WORLD_FX + i); - if ( !effectName[0] ) - { + if (!effectName[0]) { break; } - cgi_R_WorldEffectCommand( effectName ); + cgi_R_WorldEffectCommand(effectName); } // Set up the glass effects mini-system. @@ -1075,26 +962,22 @@ Only call if clientInfo->infoValid is not true For players and NPCs to register their models */ -void CG_RegisterClientModels (int entityNum) -{ - gentity_t *ent; +void CG_RegisterClientModels(int entityNum) { + gentity_t *ent; - if(entityNum < 0 || entityNum > ENTITYNUM_WORLD) - { + if (entityNum < 0 || entityNum > ENTITYNUM_WORLD) { return; } ent = &g_entities[entityNum]; - if(!ent->client) - { + if (!ent->client) { return; } ent->client->clientInfo.infoValid = qtrue; - if ( ent->playerModel != -1 && ent->ghoul2.size() ) - { + if (ent->playerModel != -1 && ent->ghoul2.size()) { return; } @@ -1102,54 +985,38 @@ void CG_RegisterClientModels (int entityNum) ent->client->clientInfo.infoValid = qtrue; - if(entityNum < MAX_CLIENTS) - { + if (entityNum < MAX_CLIENTS) { memcpy(&cgs.clientinfo[entityNum], &ent->client->clientInfo, sizeof(clientInfo_t)); } } //=================================================================================== -forceTicPos_t forceTicPos[] = -{ - { 11, 41, 20, 10, "gfx/hud/force_tick1", NULL_HANDLE }, // Left Top - { 12, 45, 20, 10, "gfx/hud/force_tick2", NULL_HANDLE }, - { 14, 49, 20, 10, "gfx/hud/force_tick3", NULL_HANDLE }, - { 17, 52, 20, 10, "gfx/hud/force_tick4", NULL_HANDLE }, - { 22, 55, 10, 10, "gfx/hud/force_tick5", NULL_HANDLE }, - { 28, 57, 10, 20, "gfx/hud/force_tick6", NULL_HANDLE }, - { 34, 59, 10, 10, "gfx/hud/force_tick7", NULL_HANDLE }, // Left bottom - - { 46, 59, -10, 10, "gfx/hud/force_tick7", NULL_HANDLE }, // Right bottom - { 52, 57, -10, 20, "gfx/hud/force_tick6", NULL_HANDLE }, - { 58, 55, -10, 10, "gfx/hud/force_tick5", NULL_HANDLE }, - { 63, 52, -20, 10, "gfx/hud/force_tick4", NULL_HANDLE }, - { 66, 49, -20, 10, "gfx/hud/force_tick3", NULL_HANDLE }, - { 68, 45, -20, 10, "gfx/hud/force_tick2", NULL_HANDLE }, - { 69, 41, -20, 10, "gfx/hud/force_tick1", NULL_HANDLE }, // Right top -}; +forceTicPos_t forceTicPos[] = { + {11, 41, 20, 10, "gfx/hud/force_tick1", NULL_HANDLE}, // Left Top + {12, 45, 20, 10, "gfx/hud/force_tick2", NULL_HANDLE}, {14, 49, 20, 10, "gfx/hud/force_tick3", NULL_HANDLE}, + {17, 52, 20, 10, "gfx/hud/force_tick4", NULL_HANDLE}, {22, 55, 10, 10, "gfx/hud/force_tick5", NULL_HANDLE}, + {28, 57, 10, 20, "gfx/hud/force_tick6", NULL_HANDLE}, {34, 59, 10, 10, "gfx/hud/force_tick7", NULL_HANDLE}, // Left bottom -forceTicPos_t ammoTicPos[] = -{ - { 12, 34, 10, 10, "gfx/hud/ammo_tick7-l", NULL_HANDLE }, // Bottom - { 13, 28, 10, 10, "gfx/hud/ammo_tick6-l", NULL_HANDLE }, - { 15, 23, 10, 10, "gfx/hud/ammo_tick5-l", NULL_HANDLE }, - { 19, 19, 10, 10, "gfx/hud/ammo_tick4-l", NULL_HANDLE }, - { 23, 15, 10, 10, "gfx/hud/ammo_tick3-l", NULL_HANDLE }, - { 29, 12, 10, 10, "gfx/hud/ammo_tick2-l", NULL_HANDLE }, - { 34, 11, 10, 10, "gfx/hud/ammo_tick1-l", NULL_HANDLE }, - - { 47, 11, -10, 10, "gfx/hud/ammo_tick1-r", NULL_HANDLE }, - { 52, 12, -10, 10, "gfx/hud/ammo_tick2-r", NULL_HANDLE }, - { 58, 15, -10, 10, "gfx/hud/ammo_tick3-r", NULL_HANDLE }, - { 62, 19, -10, 10, "gfx/hud/ammo_tick4-r", NULL_HANDLE }, - { 66, 23, -10, 10, "gfx/hud/ammo_tick5-r", NULL_HANDLE }, - { 68, 28, -10, 10, "gfx/hud/ammo_tick6-r", NULL_HANDLE }, - { 69, 34, -10, 10, "gfx/hud/ammo_tick7-r", NULL_HANDLE }, + {46, 59, -10, 10, "gfx/hud/force_tick7", NULL_HANDLE}, // Right bottom + {52, 57, -10, 20, "gfx/hud/force_tick6", NULL_HANDLE}, {58, 55, -10, 10, "gfx/hud/force_tick5", NULL_HANDLE}, + {63, 52, -20, 10, "gfx/hud/force_tick4", NULL_HANDLE}, {66, 49, -20, 10, "gfx/hud/force_tick3", NULL_HANDLE}, + {68, 45, -20, 10, "gfx/hud/force_tick2", NULL_HANDLE}, {69, 41, -20, 10, "gfx/hud/force_tick1", NULL_HANDLE}, // Right top }; +forceTicPos_t ammoTicPos[] = { + {12, 34, 10, 10, "gfx/hud/ammo_tick7-l", NULL_HANDLE}, // Bottom + {13, 28, 10, 10, "gfx/hud/ammo_tick6-l", NULL_HANDLE}, {15, 23, 10, 10, "gfx/hud/ammo_tick5-l", NULL_HANDLE}, + {19, 19, 10, 10, "gfx/hud/ammo_tick4-l", NULL_HANDLE}, {23, 15, 10, 10, "gfx/hud/ammo_tick3-l", NULL_HANDLE}, + {29, 12, 10, 10, "gfx/hud/ammo_tick2-l", NULL_HANDLE}, {34, 11, 10, 10, "gfx/hud/ammo_tick1-l", NULL_HANDLE}, -extern void NPC_Precache ( gentity_t *spawner ); + {47, 11, -10, 10, "gfx/hud/ammo_tick1-r", NULL_HANDLE}, {52, 12, -10, 10, "gfx/hud/ammo_tick2-r", NULL_HANDLE}, + {58, 15, -10, 10, "gfx/hud/ammo_tick3-r", NULL_HANDLE}, {62, 19, -10, 10, "gfx/hud/ammo_tick4-r", NULL_HANDLE}, + {66, 23, -10, 10, "gfx/hud/ammo_tick5-r", NULL_HANDLE}, {68, 28, -10, 10, "gfx/hud/ammo_tick6-r", NULL_HANDLE}, + {69, 34, -10, 10, "gfx/hud/ammo_tick7-r", NULL_HANDLE}, +}; + +extern void NPC_Precache(gentity_t *spawner); qboolean NPCsPrecached = qfalse; /* ================= @@ -1159,321 +1026,280 @@ Call before entering a new level, or after changing renderers This function may execute for a couple of minutes with a slow disk. ================= */ -static void CG_RegisterGraphics( void ) { - int i; - char items[MAX_ITEMS+1]; - static char *sb_nums[11] = { - "gfx/2d/numbers/zero", - "gfx/2d/numbers/one", - "gfx/2d/numbers/two", - "gfx/2d/numbers/three", - "gfx/2d/numbers/four", - "gfx/2d/numbers/five", - "gfx/2d/numbers/six", - "gfx/2d/numbers/seven", - "gfx/2d/numbers/eight", - "gfx/2d/numbers/nine", - "gfx/2d/numbers/minus", +static void CG_RegisterGraphics(void) { + int i; + char items[MAX_ITEMS + 1]; + static char *sb_nums[11] = { + "gfx/2d/numbers/zero", "gfx/2d/numbers/one", "gfx/2d/numbers/two", "gfx/2d/numbers/three", "gfx/2d/numbers/four", "gfx/2d/numbers/five", + "gfx/2d/numbers/six", "gfx/2d/numbers/seven", "gfx/2d/numbers/eight", "gfx/2d/numbers/nine", "gfx/2d/numbers/minus", }; - static char *sb_t_nums[11] = { - "gfx/2d/numbers/t_zero", - "gfx/2d/numbers/t_one", - "gfx/2d/numbers/t_two", - "gfx/2d/numbers/t_three", - "gfx/2d/numbers/t_four", - "gfx/2d/numbers/t_five", - "gfx/2d/numbers/t_six", - "gfx/2d/numbers/t_seven", - "gfx/2d/numbers/t_eight", - "gfx/2d/numbers/t_nine", - "gfx/2d/numbers/t_minus", + static char *sb_t_nums[11] = { + "gfx/2d/numbers/t_zero", "gfx/2d/numbers/t_one", "gfx/2d/numbers/t_two", "gfx/2d/numbers/t_three", + "gfx/2d/numbers/t_four", "gfx/2d/numbers/t_five", "gfx/2d/numbers/t_six", "gfx/2d/numbers/t_seven", + "gfx/2d/numbers/t_eight", "gfx/2d/numbers/t_nine", "gfx/2d/numbers/t_minus", }; - static char *sb_c_nums[11] = { - "gfx/2d/numbers/c_zero", - "gfx/2d/numbers/c_one", - "gfx/2d/numbers/c_two", - "gfx/2d/numbers/c_three", - "gfx/2d/numbers/c_four", - "gfx/2d/numbers/c_five", - "gfx/2d/numbers/c_six", - "gfx/2d/numbers/c_seven", - "gfx/2d/numbers/c_eight", - "gfx/2d/numbers/c_nine", + static char *sb_c_nums[11] = { + "gfx/2d/numbers/c_zero", "gfx/2d/numbers/c_one", "gfx/2d/numbers/c_two", "gfx/2d/numbers/c_three", "gfx/2d/numbers/c_four", + "gfx/2d/numbers/c_five", "gfx/2d/numbers/c_six", "gfx/2d/numbers/c_seven", "gfx/2d/numbers/c_eight", "gfx/2d/numbers/c_nine", "gfx/2d/numbers/t_minus", //????? }; // Clean, then register...rinse...repeat... - CG_LoadingString( "effects" ); + CG_LoadingString("effects"); FX_Init(); CG_RegisterEffects(); // clear any references to old media - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); cgi_R_ClearScene(); cg.loadLCARSStage = 3; - CG_LoadingString( cgs.mapname ); + CG_LoadingString(cgs.mapname); - cgi_R_LoadWorldMap( cgs.mapname ); + cgi_R_LoadWorldMap(cgs.mapname); cg.loadLCARSStage = 4; - CG_LoadingString( "game media shaders" ); + CG_LoadingString("game media shaders"); - for ( i=0; i < 11; i++ ) - { - cgs.media.numberShaders[i] = cgi_R_RegisterShaderNoMip( sb_nums[i] ); - cgs.media.smallnumberShaders[i] = cgi_R_RegisterShaderNoMip( sb_t_nums[i] ); - cgs.media.chunkyNumberShaders[i] = cgi_R_RegisterShaderNoMip( sb_c_nums[i] ); + for (i = 0; i < 11; i++) { + cgs.media.numberShaders[i] = cgi_R_RegisterShaderNoMip(sb_nums[i]); + cgs.media.smallnumberShaders[i] = cgi_R_RegisterShaderNoMip(sb_t_nums[i]); + cgs.media.chunkyNumberShaders[i] = cgi_R_RegisterShaderNoMip(sb_c_nums[i]); } // FIXME: conditionally do this?? Something must be wrong with inventory item caching..? - cgi_R_RegisterModel( "models/items/remote.md3" ); + cgi_R_RegisterModel("models/items/remote.md3"); - cgs.media.explosionModel = cgi_R_RegisterModel ( "models/weaphits/explosion.md3" ); - cgs.media.surfaceExplosionShader = cgi_R_RegisterShader( "surfaceExplosion" ); + cgs.media.explosionModel = cgi_R_RegisterModel("models/weaphits/explosion.md3"); + cgs.media.surfaceExplosionShader = cgi_R_RegisterShader("surfaceExplosion"); - cgs.media.solidWhiteShader = cgi_R_RegisterShader( "gfx/effects/solidWhite" ); + cgs.media.solidWhiteShader = cgi_R_RegisterShader("gfx/effects/solidWhite"); - //on players - cgs.media.personalShieldShader = cgi_R_RegisterShader( "gfx/misc/personalshield" ); - cgs.media.cloakedShader = cgi_R_RegisterShader( "gfx/effects/cloakedShader" ); - cgi_R_RegisterShader( "gfx/misc/ion_shield" ); + // on players + cgs.media.personalShieldShader = cgi_R_RegisterShader("gfx/misc/personalshield"); + cgs.media.cloakedShader = cgi_R_RegisterShader("gfx/effects/cloakedShader"); + cgi_R_RegisterShader("gfx/misc/ion_shield"); - cgs.media.boltShader = cgi_R_RegisterShader( "gfx/misc/blueLine" ); + cgs.media.boltShader = cgi_R_RegisterShader("gfx/misc/blueLine"); // FIXME: do these conditionally - cgi_R_RegisterShader( "gfx/2d/workingCamera" ); - cgi_R_RegisterShader( "gfx/2d/brokenCamera" ); - cgi_R_RegisterShader( "gfx/effects/irid_shield" ); // for galak, but he doesn't have his own weapon so I can't register the shader there. - - //interface - for ( i = 0 ; i < NUM_CROSSHAIRS ; i++ ) { - cgs.media.crosshairShader[i] = cgi_R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a'+i) ); - } - cgs.media.backTileShader = cgi_R_RegisterShader( "gfx/2d/backtile" ); - cgs.media.noammoShader = cgi_R_RegisterShaderNoMip( "gfx/hud/noammo"); - cgs.media.weaponIconBackground = cgi_R_RegisterShaderNoMip( "gfx/hud/background"); - cgs.media.weaponProngsOn = cgi_R_RegisterShaderNoMip( "gfx/hud/prong_on_w"); - cgs.media.weaponProngsOff = cgi_R_RegisterShaderNoMip( "gfx/hud/prong_off"); - cgs.media.forceProngsOn = cgi_R_RegisterShaderNoMip( "gfx/hud/prong_on_f"); - cgs.media.forceIconBackground = cgi_R_RegisterShaderNoMip( "gfx/hud/background_f"); - cgs.media.inventoryIconBackground= cgi_R_RegisterShaderNoMip( "gfx/hud/background_i"); - cgs.media.inventoryProngsOn = cgi_R_RegisterShaderNoMip( "gfx/hud/prong_on_i"); - cgs.media.dataPadFrame = cgi_R_RegisterShaderNoMip( "gfx/hud/datapad2"); + cgi_R_RegisterShader("gfx/2d/workingCamera"); + cgi_R_RegisterShader("gfx/2d/brokenCamera"); + cgi_R_RegisterShader("gfx/effects/irid_shield"); // for galak, but he doesn't have his own weapon so I can't register the shader there. + + // interface + for (i = 0; i < NUM_CROSSHAIRS; i++) { + cgs.media.crosshairShader[i] = cgi_R_RegisterShaderNoMip(va("gfx/2d/crosshair%c", 'a' + i)); + } + cgs.media.backTileShader = cgi_R_RegisterShader("gfx/2d/backtile"); + cgs.media.noammoShader = cgi_R_RegisterShaderNoMip("gfx/hud/noammo"); + cgs.media.weaponIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background"); + cgs.media.weaponProngsOn = cgi_R_RegisterShaderNoMip("gfx/hud/prong_on_w"); + cgs.media.weaponProngsOff = cgi_R_RegisterShaderNoMip("gfx/hud/prong_off"); + cgs.media.forceProngsOn = cgi_R_RegisterShaderNoMip("gfx/hud/prong_on_f"); + cgs.media.forceIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background_f"); + cgs.media.inventoryIconBackground = cgi_R_RegisterShaderNoMip("gfx/hud/background_i"); + cgs.media.inventoryProngsOn = cgi_R_RegisterShaderNoMip("gfx/hud/prong_on_i"); + cgs.media.dataPadFrame = cgi_R_RegisterShaderNoMip("gfx/hud/datapad2"); cg.loadLCARSStage = 5; - CG_LoadingString( "game media models" ); + CG_LoadingString("game media models"); // Chunk models - //FIXME: jfm:? bother to conditionally load these if an ent has this material type? - for ( i = 0; i < NUM_CHUNK_MODELS; i++ ) - { - cgs.media.chunkModels[CHUNK_METAL2][i] = cgi_R_RegisterModel( va( "models/chunks/metal/metal1_%i.md3", i+1 ) ); //_ /switched\ _ - cgs.media.chunkModels[CHUNK_METAL1][i] = cgi_R_RegisterModel( va( "models/chunks/metal/metal2_%i.md3", i+1 ) ); // \switched/ - cgs.media.chunkModels[CHUNK_ROCK1][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK2][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK3][i] = cgi_R_RegisterModel( va( "models/chunks/rock/rock3_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE1][i] = cgi_R_RegisterModel( va( "models/chunks/crate/crate1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE2][i] = cgi_R_RegisterModel( va( "models/chunks/crate/crate2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = cgi_R_RegisterModel( va( "models/chunks/metal/wmetal1_%i.md3", i+1 ) ); - } - - cgs.media.chunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glasslcar"); - cgs.media.grateSound = cgi_S_RegisterSound( "sound/effects/grate_destroy" ); - cgs.media.rockBreakSound = cgi_S_RegisterSound("sound/effects/wall_smash"); - cgs.media.rockBounceSound[0] = cgi_S_RegisterSound("sound/effects/stone_bounce"); - cgs.media.rockBounceSound[1] = cgi_S_RegisterSound("sound/effects/stone_bounce2"); - cgs.media.metalBounceSound[0] = cgi_S_RegisterSound("sound/effects/metal_bounce"); - cgs.media.metalBounceSound[1] = cgi_S_RegisterSound("sound/effects/metal_bounce2"); - cgs.media.glassChunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glassbreak1"); - cgs.media.crateBreakSound[0] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust1" ); - cgs.media.crateBreakSound[1] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust2" ); - - cgs.media.weaponbox = cgi_R_RegisterShaderNoMip( "gfx/interface/weapon_box"); - - //Models & Shaders - cgs.media.damageBlendBlobShader = cgi_R_RegisterShader( "gfx/misc/borgeyeflare" ); + // FIXME: jfm:? bother to conditionally load these if an ent has this material type? + for (i = 0; i < NUM_CHUNK_MODELS; i++) { + cgs.media.chunkModels[CHUNK_METAL2][i] = cgi_R_RegisterModel(va("models/chunks/metal/metal1_%i.md3", i + 1)); //_ /switched\ _ + cgs.media.chunkModels[CHUNK_METAL1][i] = cgi_R_RegisterModel(va("models/chunks/metal/metal2_%i.md3", i + 1)); // \switched/ + cgs.media.chunkModels[CHUNK_ROCK1][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK2][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK3][i] = cgi_R_RegisterModel(va("models/chunks/rock/rock3_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE1][i] = cgi_R_RegisterModel(va("models/chunks/crate/crate1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE2][i] = cgi_R_RegisterModel(va("models/chunks/crate/crate2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = cgi_R_RegisterModel(va("models/chunks/metal/wmetal1_%i.md3", i + 1)); + } + + cgs.media.chunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glasslcar"); + cgs.media.grateSound = cgi_S_RegisterSound("sound/effects/grate_destroy"); + cgs.media.rockBreakSound = cgi_S_RegisterSound("sound/effects/wall_smash"); + cgs.media.rockBounceSound[0] = cgi_S_RegisterSound("sound/effects/stone_bounce"); + cgs.media.rockBounceSound[1] = cgi_S_RegisterSound("sound/effects/stone_bounce2"); + cgs.media.metalBounceSound[0] = cgi_S_RegisterSound("sound/effects/metal_bounce"); + cgs.media.metalBounceSound[1] = cgi_S_RegisterSound("sound/effects/metal_bounce2"); + cgs.media.glassChunkSound = cgi_S_RegisterSound("sound/weapons/explosions/glassbreak1"); + cgs.media.crateBreakSound[0] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust1"); + cgs.media.crateBreakSound[1] = cgi_S_RegisterSound("sound/weapons/explosions/crateBust2"); + + cgs.media.weaponbox = cgi_R_RegisterShaderNoMip("gfx/interface/weapon_box"); + + // Models & Shaders + cgs.media.damageBlendBlobShader = cgi_R_RegisterShader("gfx/misc/borgeyeflare"); cg.loadLCARSStage = 6; -// cgs.media.HUDLeftFrame= cgi_R_RegisterShaderNoMip( "gfx/hud/hudleftframe" ); - cgs.media.HUDLeftFrame= cgi_R_RegisterShaderNoMip( "gfx/hud/static_test" ); - cgs.media.HUDInnerLeft = cgi_R_RegisterShaderNoMip( "gfx/hud/hudleft_innerframe" ); - cgs.media.HUDArmor1= cgi_R_RegisterShaderNoMip( "gfx/hud/armor1" ); - cgs.media.HUDArmor2= cgi_R_RegisterShaderNoMip( "gfx/hud/armor2" ); - cgs.media.HUDHealth= cgi_R_RegisterShaderNoMip( "gfx/hud/health" ); - cgs.media.HUDHealthTic= cgi_R_RegisterShaderNoMip( "gfx/hud/health_tic" ); -// cgs.media.HUDArmorTic= cgi_R_RegisterShaderNoMip( "gfx/hud/armor_tic" ); + // cgs.media.HUDLeftFrame= cgi_R_RegisterShaderNoMip( "gfx/hud/hudleftframe" ); + cgs.media.HUDLeftFrame = cgi_R_RegisterShaderNoMip("gfx/hud/static_test"); + cgs.media.HUDInnerLeft = cgi_R_RegisterShaderNoMip("gfx/hud/hudleft_innerframe"); + cgs.media.HUDArmor1 = cgi_R_RegisterShaderNoMip("gfx/hud/armor1"); + cgs.media.HUDArmor2 = cgi_R_RegisterShaderNoMip("gfx/hud/armor2"); + cgs.media.HUDHealth = cgi_R_RegisterShaderNoMip("gfx/hud/health"); + cgs.media.HUDHealthTic = cgi_R_RegisterShaderNoMip("gfx/hud/health_tic"); + // cgs.media.HUDArmorTic= cgi_R_RegisterShaderNoMip( "gfx/hud/armor_tic" ); - cgs.media.HUDRightFrame= cgi_R_RegisterShaderNoMip( "gfx/hud/hudrightframe" ); - cgs.media.HUDInnerRight = cgi_R_RegisterShaderNoMip( "gfx/hud/hudright_innerframe" ); + cgs.media.HUDRightFrame = cgi_R_RegisterShaderNoMip("gfx/hud/hudrightframe"); + cgs.media.HUDInnerRight = cgi_R_RegisterShaderNoMip("gfx/hud/hudright_innerframe"); - cgs.media.messageLitOn = cgi_R_RegisterShaderNoMip( "gfx/hud/message_on" ); - cgs.media.messageLitOff = cgi_R_RegisterShaderNoMip( "gfx/hud/message_off" ); - cgs.media.messageObjCircle = cgi_R_RegisterShaderNoMip( "gfx/hud/objective_circle" ); + cgs.media.messageLitOn = cgi_R_RegisterShaderNoMip("gfx/hud/message_on"); + cgs.media.messageLitOff = cgi_R_RegisterShaderNoMip("gfx/hud/message_off"); + cgs.media.messageObjCircle = cgi_R_RegisterShaderNoMip("gfx/hud/objective_circle"); - cgs.media.DPForcePowerOverlay = cgi_R_RegisterShader( "gfx/hud/force_swirl" ); + cgs.media.DPForcePowerOverlay = cgi_R_RegisterShader("gfx/hud/force_swirl"); // battery charge shader when using a gonk - cgs.media.batteryChargeShader = cgi_R_RegisterShader( "gfx/2d/battery" ); - cgi_R_RegisterShader( "gfx/2d/droid_view" ); + cgs.media.batteryChargeShader = cgi_R_RegisterShader("gfx/2d/battery"); + cgi_R_RegisterShader("gfx/2d/droid_view"); // Load force tics - for (i=0;iclientInfo.infoValid) - //We presume this + for (i = 0; i < ENTITYNUM_WORLD; i++) { + if (g_entities[i].inuse) { + if (g_entities[i].client) { + // if(!g_entities[i].client->clientInfo.infoValid) + // We presume this { - CG_LoadingString( va("client %s", g_entities[i].client->clientInfo.name ) ); + CG_LoadingString(va("client %s", g_entities[i].client->clientInfo.name)); CG_RegisterClientModels(i); - if ( i != 0 ) - {//Client weapons already precached - CG_RegisterWeapon( g_entities[i].client->ps.weapon ); - CG_RegisterNPCCustomSounds( &g_entities[i].client->clientInfo ); - CG_RegisterNPCEffects( g_entities[i].client->playerTeam ); + if (i != 0) { // Client weapons already precached + CG_RegisterWeapon(g_entities[i].client->ps.weapon); + CG_RegisterNPCCustomSounds(&g_entities[i].client->clientInfo); + CG_RegisterNPCEffects(g_entities[i].client->playerTeam); } } - } - else if ( g_entities[i].svFlags & SVF_NPC_PRECACHE && g_entities[i].NPC_type && g_entities[i].NPC_type[0] ) - {//Precache the NPC_type - //FIXME: make sure we didn't precache this NPC_type already - CG_LoadingString( va("NPC %s", g_entities[i].NPC_type ) ); - NPC_Precache( &g_entities[i] ); + } else if (g_entities[i].svFlags & SVF_NPC_PRECACHE && g_entities[i].NPC_type && g_entities[i].NPC_type[0]) { // Precache the NPC_type + // FIXME: make sure we didn't precache this NPC_type already + CG_LoadingString(va("NPC %s", g_entities[i].NPC_type)); + NPC_Precache(&g_entities[i]); } } } - cg.loadLCARSStage = 9; NPCsPrecached = qtrue; - extern cvar_t *com_buildScript; + extern cvar_t *com_buildScript; if (com_buildScript->integer) { - cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ); - cgi_R_RegisterShader( "gfx/misc/nav_line" ); - cgi_R_RegisterShader( "gfx/misc/nav_arrow" ); - cgi_R_RegisterShader( "gfx/misc/nav_node" ); + cgi_R_RegisterShader("gfx/misc/nav_cpoint"); + cgi_R_RegisterShader("gfx/misc/nav_line"); + cgi_R_RegisterShader("gfx/misc/nav_arrow"); + cgi_R_RegisterShader("gfx/misc/nav_node"); } } @@ -1484,21 +1310,19 @@ Ghoul2 Insert End CG_ConfigString ================= */ -const char *CG_ConfigString( int index ) { - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - CG_Error( "CG_ConfigString: bad index: %i", index ); +const char *CG_ConfigString(int index) { + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + CG_Error("CG_ConfigString: bad index: %i", index); } - return cgs.gameState.stringData + cgs.gameState.stringOffsets[ index ]; + return cgs.gameState.stringData + cgs.gameState.stringOffsets[index]; } //================================================================== -void CG_LinkCentsToGents(void) -{ - int i; +void CG_LinkCentsToGents(void) { + int i; - for(i = 0; i < MAX_GENTITIES; i++) - { + for (i = 0; i < MAX_GENTITIES; i++) { cg_entities[i].gent = &g_entities[i]; } } @@ -1509,18 +1333,18 @@ CG_StartMusic ====================== */ -void CG_StartMusic( qboolean bForceStart ) { - const char *s; - char parm1[MAX_QPATH], parm2[MAX_QPATH]; +void CG_StartMusic(qboolean bForceStart) { + const char *s; + char parm1[MAX_QPATH], parm2[MAX_QPATH]; // start the background music - s = (char *)CG_ConfigString( CS_MUSIC ); + s = (char *)CG_ConfigString(CS_MUSIC); COM_BeginParseSession(); - Q_strncpyz( parm1, COM_Parse( &s ), sizeof( parm1 ) ); - Q_strncpyz( parm2, COM_Parse( &s ), sizeof( parm2 ) ); + Q_strncpyz(parm1, COM_Parse(&s), sizeof(parm1)); + Q_strncpyz(parm2, COM_Parse(&s), sizeof(parm2)); COM_EndParseSession(); - cgi_S_StartBackgroundTrack( parm1, parm2, (qboolean)!bForceStart ); + cgi_S_StartBackgroundTrack(parm1, parm2, (qboolean)!bForceStart); } /* @@ -1531,103 +1355,97 @@ Displays the info screen while loading media ====================== */ -int iCGResetCount=0; +int iCGResetCount = 0; qboolean qbVidRestartOccured = qfalse; //=================== -qboolean gbUseTheseValuesFromLoadSave = qfalse; // MUST default to this +qboolean gbUseTheseValuesFromLoadSave = qfalse; // MUST default to this int gi_cg_forcepowerSelect; int gi_cg_inventorySelect; //=================== - -static void CG_GameStateReceived( void ) { +static void CG_GameStateReceived(void) { // clear everything - extern void CG_ClearAnimSndCache( void ); - CG_ClearAnimSndCache(); // else sound handles wrong after vid_restart + extern void CG_ClearAnimSndCache(void); + CG_ClearAnimSndCache(); // else sound handles wrong after vid_restart qbVidRestartOccured = qtrue; iCGResetCount++; - if (iCGResetCount == 1) // this will only equal 1 first time, after each vid_restart it just gets higher. + if (iCGResetCount == 1) // this will only equal 1 first time, after each vid_restart it just gets higher. { // This non-clear is so the user can vid_restart during scrolling text without losing it. qbVidRestartOccured = qfalse; } - if (!qbVidRestartOccured) - { -/* -Ghoul2 Insert Start -*/ + if (!qbVidRestartOccured) { + /* + Ghoul2 Insert Start + */ -// this is a No-No now we have stl vector classes in here. -// memset( &cg, 0, sizeof( cg ) ); + // this is a No-No now we have stl vector classes in here. + // memset( &cg, 0, sizeof( cg ) ); CG_Init_CG(); -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert End + */ } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// memset( cg_entities, 0, sizeof(cg_entities) ); + // memset( cg_entities, 0, sizeof(cg_entities) ); CG_Init_CGents(); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - memset( cg_weapons, 0, sizeof(cg_weapons) ); - memset( cg_items, 0, sizeof(cg_items) ); + memset(cg_weapons, 0, sizeof(cg_weapons)); + memset(cg_items, 0, sizeof(cg_items)); CG_LinkCentsToGents(); cg.weaponSelect = WP_BRYAR_PISTOL; cg.forcepowerSelect = FP_HEAL; - if (gbUseTheseValuesFromLoadSave) - { - gbUseTheseValuesFromLoadSave = qfalse; // ack + if (gbUseTheseValuesFromLoadSave) { + gbUseTheseValuesFromLoadSave = qfalse; // ack cg.forcepowerSelect = gi_cg_forcepowerSelect; - cg.inventorySelect = gi_cg_inventorySelect; + cg.inventorySelect = gi_cg_inventorySelect; } - // get the rendering configuration from the client system - cgi_GetGlconfig( &cgs.glconfig ); + cgi_GetGlconfig(&cgs.glconfig); -/* cgs.charScale = cgs.glconfig.vidHeight * (1.0/480.0); - if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) { - // wide screen - cgs.bias = 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * (640.0/480.0) ) ); - } - else { - // no wide screen - cgs.bias = 0; - } -*/ + /* cgs.charScale = cgs.glconfig.vidHeight * (1.0/480.0); + if ( cgs.glconfig.vidWidth * 480 > cgs.glconfig.vidHeight * 640 ) { + // wide screen + cgs.bias = 0.5 * ( cgs.glconfig.vidWidth - ( cgs.glconfig.vidHeight * (640.0/480.0) ) ); + } + else { + // no wide screen + cgs.bias = 0; + } + */ // get the gamestate from the client system - cgi_GetGameState( &cgs.gameState ); + cgi_GetGameState(&cgs.gameState); CG_ParseServerinfo(); // load the new map - cgs.media.levelLoad = cgi_R_RegisterShaderNoMip( "gfx/hud/mp_levelload" ); - CG_LoadingString( "collision map" ); + cgs.media.levelLoad = cgi_R_RegisterShaderNoMip("gfx/hud/mp_levelload"); + CG_LoadingString("collision map"); - cgi_CM_LoadMap( cgs.mapname, qfalse ); + cgi_CM_LoadMap(cgs.mapname, qfalse); CG_RegisterSounds(); CG_RegisterGraphics(); + // jfm: moved down to preinit + // CG_InitLocalEntities(); + // CG_InitMarkPolys(); - //jfm: moved down to preinit -// CG_InitLocalEntities(); -// CG_InitMarkPolys(); - - CG_StartMusic( qfalse ); + CG_StartMusic(qfalse); // remove the last loading update cg.infoScreenText[0] = 0; @@ -1635,35 +1453,22 @@ Ghoul2 Insert End CGCam_Init(); CG_ClearLightStyles(); - } -void CG_WriteTheEvilCGHackStuff(void) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void CG_WriteTheEvilCGHackStuff(void) { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('F', 'P', 'S', 'L'), - ::cg.forcepowerSelect); + saved_game.write_chunk(INT_ID('F', 'P', 'S', 'L'), ::cg.forcepowerSelect); - saved_game.write_chunk( - INT_ID('I', 'V', 'S', 'L'), - ::cg.inventorySelect); + saved_game.write_chunk(INT_ID('I', 'V', 'S', 'L'), ::cg.inventorySelect); } -void CG_ReadTheEvilCGHackStuff(void) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void CG_ReadTheEvilCGHackStuff(void) { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('F', 'P', 'S', 'L'), - ::gi_cg_forcepowerSelect); + saved_game.read_chunk(INT_ID('F', 'P', 'S', 'L'), ::gi_cg_forcepowerSelect); - saved_game.read_chunk( - INT_ID('I', 'V', 'S', 'L'), - ::gi_cg_inventorySelect); + saved_game.read_chunk(INT_ID('I', 'V', 'S', 'L'), ::gi_cg_inventorySelect); gbUseTheseValuesFromLoadSave = qtrue; } @@ -1673,22 +1478,15 @@ Ghoul2 Insert Start */ // initialise the cg_entities structure - take into account the ghoul2 stl stuff in the active snap shots -void CG_Init_CG(void) -{ - memset( &cg, 0, sizeof(cg)); -} +void CG_Init_CG(void) { memset(&cg, 0, sizeof(cg)); } // initialise the cg_entities structure - take into account the ghoul2 stl stuff -void CG_Init_CGents(void) -{ - memset( cg_entities, 0, sizeof(cg_entities) ); -} +void CG_Init_CGents(void) { memset(cg_entities, 0, sizeof(cg_entities)); } /* Ghoul2 Insert End */ - /* ================= CG_PreInit @@ -1697,23 +1495,23 @@ Called when DLL loads (after subsystem restart, but before gamestate is received ================= */ void CG_PreInit() { -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// this is a No-No now we have stl vector classes in here. -// memset( &cg, 0, sizeof( cg ) ); + // this is a No-No now we have stl vector classes in here. + // memset( &cg, 0, sizeof( cg ) ); CG_Init_CG(); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - memset( &cgs, 0, sizeof( cgs ) ); + memset(&cgs, 0, sizeof(cgs)); iCGResetCount = 0; CG_RegisterCvars(); -//moved from CG_GameStateReceived because it's loaded sooner now + // moved from CG_GameStateReceived because it's loaded sooner now CG_InitLocalEntities(); CG_InitMarkPolys(); @@ -1726,52 +1524,41 @@ CG_Init Called after every level change or subsystem restart ================= */ -void CG_Init( int serverCommandSequence ) { +void CG_Init(int serverCommandSequence) { cgs.serverCommandSequence = serverCommandSequence; - cgi_Cvar_Set( "cg_drawHUD", "1" ); + cgi_Cvar_Set("cg_drawHUD", "1"); // fonts... // cgs.media.charsetShader = cgi_R_RegisterShaderNoMip("gfx/2d/charsgrid_med"); cgs.media.qhFontSmall = cgi_R_RegisterFont("ocr_a"); - cgs.media.qhFontMedium= cgi_R_RegisterFont("ergoec"); + cgs.media.qhFontMedium = cgi_R_RegisterFont("ergoec"); - cgs.media.whiteShader = cgi_R_RegisterShader( "white" ); - cgs.media.loadTick = cgi_R_RegisterShaderNoMip( "gfx/hud/load_tick" ); - cgs.media.loadTickCap = cgi_R_RegisterShaderNoMip( "gfx/hud/load_tick_cap" ); + cgs.media.whiteShader = cgi_R_RegisterShader("white"); + cgs.media.loadTick = cgi_R_RegisterShaderNoMip("gfx/hud/load_tick"); + cgs.media.loadTickCap = cgi_R_RegisterShaderNoMip("gfx/hud/load_tick_cap"); - static char *force_icon_files[NUM_FORCE_POWERS] = - { - "gfx/hud/f_icon_heal", - "gfx/hud/f_icon_levitation", - "gfx/hud/f_icon_speed", - "gfx/hud/f_icon_push", - "gfx/hud/f_icon_pull", - "gfx/hud/f_icon_telepathy", - "gfx/hud/f_icon_grip", - "gfx/hud/f_icon_l1", - "gfx/hud/f_icon_saber_throw", - "gfx/hud/f_icon_saber_defend", - "gfx/hud/f_icon_saber_attack", + static char *force_icon_files[NUM_FORCE_POWERS] = { + "gfx/hud/f_icon_heal", "gfx/hud/f_icon_levitation", "gfx/hud/f_icon_speed", "gfx/hud/f_icon_push", + "gfx/hud/f_icon_pull", "gfx/hud/f_icon_telepathy", "gfx/hud/f_icon_grip", "gfx/hud/f_icon_l1", + "gfx/hud/f_icon_saber_throw", "gfx/hud/f_icon_saber_defend", "gfx/hud/f_icon_saber_attack", }; // Precache inventory icons - for ( int i=0;ileType = LE_SPRITE; ex->startTime = cg.time; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_node" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_node"); - float scale = 16.0f; + float scale = 16.0f; - switch ( type ) - { + switch (type) { case NODE_NORMAL: ex->color[0] = 255; ex->color[1] = 0; @@ -1854,9 +1637,8 @@ CG_DrawRadius ------------------------- */ -void CG_DrawRadius( vec3_t origin, unsigned int radius, int type ) -{ - localEntity_t *ex; +void CG_DrawRadius(vec3_t origin, unsigned int radius, int type) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); @@ -1864,12 +1646,11 @@ void CG_DrawRadius( vec3_t origin, unsigned int radius, int type ) ex->radius = radius; ex->startTime = cg.time; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_radius" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_radius"); - switch ( type ) - { + switch (type) { case NODE_NORMAL: ex->color[0] = 255; ex->color[1] = 0; @@ -1902,39 +1683,31 @@ CG_DrawEdge ------------------------- */ -void CG_DrawEdge( vec3_t start, vec3_t end, int type ) -{ - switch ( type ) - { +void CG_DrawEdge(vec3_t start, vec3_t end, int type) { + switch (type) { case EDGE_PATH: - FX_AddLine( start, end, 4.0f, 4.0f, 0.0f, 1.0f, 1.0f, 51, cgi_R_RegisterShader( "gfx/misc/nav_arrow" ), 0 ); + FX_AddLine(start, end, 4.0f, 4.0f, 0.0f, 1.0f, 1.0f, 51, cgi_R_RegisterShader("gfx/misc/nav_arrow"), 0); break; case EDGE_NORMAL: - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); break; - case EDGE_BLOCKED: - { - vec3_t color = { 255, 255, 0 }; + case EDGE_BLOCKED: { + vec3_t color = {255, 255, 0}; - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_FAILED: - { - vec3_t color = { 255, 0, 0 }; + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_FAILED: { + vec3_t color = {255, 0, 0}; - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; - case EDGE_MOVEDIR: - { - vec3_t color = { 0, 255, 0 }; + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; + case EDGE_MOVEDIR: { + vec3_t color = {0, 255, 0}; - FX_AddLine( start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader( "gfx/misc/nav_line" ), 0 ); - } - break; + FX_AddLine(start, end, 8.0f, 4.0f, 0.0f, 0.5f, 0.5f, color, color, 51, cgi_R_RegisterShader("gfx/misc/nav_line"), 0); + } break; default: break; } @@ -1946,9 +1719,8 @@ CG_DrawCombatPoint ------------------------- */ -void CG_DrawCombatPoint( vec3_t origin, int type ) -{ - localEntity_t *ex; +void CG_DrawCombatPoint(vec3_t origin, int type) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); @@ -1956,23 +1728,23 @@ void CG_DrawCombatPoint( vec3_t origin, int type ) ex->startTime = cg.time; ex->radius = 8; ex->endTime = ex->startTime + 51; - VectorCopy( origin, ex->refEntity.origin ); + VectorCopy(origin, ex->refEntity.origin); - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/misc/nav_cpoint"); ex->color[0] = 0; ex->color[1] = 255; ex->color[2] = 255; -/* - switch( type ) - { - case 0: //FIXME: To shut up the compiler warning (more will be added here later of course) - default: - FX_AddSprite( origin, NULL, NULL, 8.0f, 0.0f, 1.0f, 1.0f, color, color, 0.0f, 0.0f, 51, cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ) ); - break; - } -*/ + /* + switch( type ) + { + case 0: //FIXME: To shut up the compiler warning (more will be added here later of course) + default: + FX_AddSprite( origin, NULL, NULL, 8.0f, 0.0f, 1.0f, 1.0f, color, color, 0.0f, 0.0f, 51, cgi_R_RegisterShader( "gfx/misc/nav_cpoint" ) ); + break; + } + */ } /* @@ -1981,215 +1753,185 @@ CG_DrawAlert ------------------------- */ -void CG_DrawAlert( vec3_t origin, float rating ) -{ - vec3_t drawPos; +void CG_DrawAlert(vec3_t origin, float rating) { + vec3_t drawPos; - VectorCopy( origin, drawPos ); + VectorCopy(origin, drawPos); drawPos[2] += 48; - vec3_t startRGB; + vec3_t startRGB; - //Fades from green at 0, to red at 1 + // Fades from green at 0, to red at 1 startRGB[0] = rating; startRGB[1] = 1 - rating; startRGB[2] = 0; - FX_AddSprite( drawPos, NULL, NULL, 16, 0.0f, 1.0f, 1.0f, startRGB, startRGB, 0, 0, 50, cgs.media.whiteShader ); + FX_AddSprite(drawPos, NULL, NULL, 16, 0.0f, 1.0f, 1.0f, startRGB, startRGB, 0, 0, 50, cgs.media.whiteShader); } - -#define MAX_MENUDEFFILE 4096 +#define MAX_MENUDEFFILE 4096 // // ============================== // new hud stuff ( mission pack ) // ============================== // -qboolean CG_Asset_Parse(const char **p) -{ +qboolean CG_Asset_Parse(const char **p) { const char *token; const char *tempStr; int pointSize; token = COM_ParseExt(p, qtrue); - if (!token) - { + if (!token) { return qfalse; } - if (Q_stricmp(token, "{") != 0) - { + if (Q_stricmp(token, "{") != 0) { return qfalse; } - while ( 1 ) - { + while (1) { token = COM_ParseExt(p, qtrue); - if (!token) - { + if (!token) { return qfalse; } - if (Q_stricmp(token, "}") == 0) - { + if (Q_stricmp(token, "}") == 0) { return qtrue; } // font - if (Q_stricmp(token, "font") == 0) - { -/* - int pointSize; + if (Q_stricmp(token, "font") == 0) { + /* + int pointSize; - cgi_UI_Parse_String(tempStr); - cgi_UI_Parse_Int(&pointSize); + cgi_UI_Parse_String(tempStr); + cgi_UI_Parse_Int(&pointSize); - if (!tempStr || !pointSize) - { - return qfalse; - } -*/ -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.textFont); + if (!tempStr || !pointSize) + { + return qfalse; + } + */ + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.textFont); continue; } // smallFont - if (Q_stricmp(token, "smallFont") == 0) - { - if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) - { + if (Q_stricmp(token, "smallFont") == 0) { + if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) { return qfalse; } -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.smallFont); continue; } // font - if (Q_stricmp(token, "bigfont") == 0) - { + if (Q_stricmp(token, "bigfont") == 0) { int pointSize; - if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) - { + if (!COM_ParseString(p, &tempStr) || !COM_ParseInt(p, &pointSize)) { return qfalse; } -// cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.bigFont); + // cgDC.registerFont(tempStr, pointSize, &cgDC.Assets.bigFont); continue; } // gradientbar - if (Q_stricmp(token, "gradientbar") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "gradientbar") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr); + // cgDC.Assets.gradientBar = trap_R_RegisterShaderNoMip(tempStr); continue; } // enterMenuSound - if (Q_stricmp(token, "menuEnterSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuEnterSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuEnterSound = trap_S_RegisterSound( tempStr ); continue; } // exitMenuSound - if (Q_stricmp(token, "menuExitSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuExitSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuExitSound = trap_S_RegisterSound( tempStr ); continue; } // itemFocusSound - if (Q_stricmp(token, "itemFocusSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "itemFocusSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.itemFocusSound = trap_S_RegisterSound( tempStr ); continue; } // menuBuzzSound - if (Q_stricmp(token, "menuBuzzSound") == 0) - { - if (!COM_ParseString(p, &tempStr)) - { + if (Q_stricmp(token, "menuBuzzSound") == 0) { + if (!COM_ParseString(p, &tempStr)) { return qfalse; } -// cgDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr ); + // cgDC.Assets.menuBuzzSound = trap_S_RegisterSound( tempStr ); continue; } - if (Q_stricmp(token, "cursor") == 0) - { -// if (!COM_ParseString(p, &cgDC.Assets.cursorStr)) -// { -// return qfalse; -// } -// cgDC.Assets.cursor = trap_R_RegisterShaderNoMip( cgDC.Assets.cursorStr); + if (Q_stricmp(token, "cursor") == 0) { + // if (!COM_ParseString(p, &cgDC.Assets.cursorStr)) + // { + // return qfalse; + // } + // cgDC.Assets.cursor = trap_R_RegisterShaderNoMip( cgDC.Assets.cursorStr); continue; } - if (Q_stricmp(token, "fadeClamp") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.fadeClamp)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeClamp") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.fadeClamp)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "fadeCycle") == 0) - { -// if (!COM_ParseInt(p, &cgDC.Assets.fadeCycle)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeCycle") == 0) { + // if (!COM_ParseInt(p, &cgDC.Assets.fadeCycle)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "fadeAmount") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.fadeAmount)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "fadeAmount") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.fadeAmount)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowX") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.shadowX)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "shadowX") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.shadowX)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowY") == 0) - { -// if (!COM_ParseFloat(p, &cgDC.Assets.shadowY)) -// { -// return qfalse; -// } + if (Q_stricmp(token, "shadowY") == 0) { + // if (!COM_ParseFloat(p, &cgDC.Assets.shadowY)) + // { + // return qfalse; + // } continue; } - if (Q_stricmp(token, "shadowColor") == 0) - { + if (Q_stricmp(token, "shadowColor") == 0) { /* if (!PC_Color_Parse(handle, &cgDC.Assets.shadowColor)) { @@ -2210,60 +1952,54 @@ void cgi_UI_EndParseSession(char *buf); CG_ParseMenu(); ================= */ -void CG_ParseMenu(const char *menuFile) -{ - char *token; - int result; - char *buf,*p; +void CG_ParseMenu(const char *menuFile) { + char *token; + int result; + char *buf, *p; Com_Printf("Parsing menu file: %s\n", menuFile); - result = cgi_UI_StartParseSession((char *) menuFile,&buf); + result = cgi_UI_StartParseSession((char *)menuFile, &buf); - if (!result) - { + if (!result) { Com_Printf("Unable to load hud menu file: %s. Using default ui/testhud.menu.\n", menuFile); - result = cgi_UI_StartParseSession("ui/testhud.menu",&buf); - if (!result) - { + result = cgi_UI_StartParseSession("ui/testhud.menu", &buf); + if (!result) { Com_Printf("Unable to load default ui/testhud.menu.\n"); return; } } p = buf; - while ( 1 ) - { + while (1) { cgi_UI_ParseExt(&token); - if(!token) - { + if (!token) { // NULL checking is the best kind of checking --eez Com_Error(ERR_FATAL, "cgi_UI_ParseExt: NULL token parameter"); } - if (!*token) // All done? + if (!*token) // All done? { break; } - //if ( Q_stricmp( token, "{" ) ) { + // if ( Q_stricmp( token, "{" ) ) { // Com_Printf( "Missing { in menu file\n" ); // break; - //} + // } - //if ( menuCount == MAX_MENUS ) { + // if ( menuCount == MAX_MENUS ) { // Com_Printf( "Too many menus!\n" ); // break; - //} + // } -// if ( *token == '}' ) -// { -// break; -// } + // if ( *token == '}' ) + // { + // break; + // } - if (Q_stricmp(token, "assetGlobalDef") == 0) - { + if (Q_stricmp(token, "assetGlobalDef") == 0) { /* if (CG_Asset_Parse(handle)) { @@ -2276,16 +2012,13 @@ void CG_ParseMenu(const char *menuFile) */ } - - if (Q_stricmp(token, "menudef") == 0) - { + if (Q_stricmp(token, "menudef") == 0) { // start a new menu cgi_UI_Menu_New(p); } } cgi_UI_EndParseSession(buf); - } /* @@ -2294,29 +2027,24 @@ CG_Load_Menu(); ================= */ -qboolean CG_Load_Menu( const char **p) -{ +qboolean CG_Load_Menu(const char **p) { const char *token; token = COM_ParseExt(p, qtrue); - if (token[0] != '{') - { + if (token[0] != '{') { return qfalse; } - while ( 1 ) - { + while (1) { token = COM_ParseExt(p, qtrue); - if (Q_stricmp(token, "}") == 0) - { + if (Q_stricmp(token, "}") == 0) { return qtrue; } - if ( !token || token[0] == 0 ) - { + if (!token || token[0] == 0) { return qfalse; } @@ -2331,67 +2059,56 @@ CG_LoadMenus(); ================= */ -void CG_LoadMenus(const char *menuFile) -{ - const char *token; - const char *p; - int len, start; - fileHandle_t f; +void CG_LoadMenus(const char *menuFile) { + const char *token; + const char *p; + int len, start; + fileHandle_t f; static char buf[MAX_MENUDEFFILE]; start = cgi_Milliseconds(); - len = cgi_FS_FOpenFile( menuFile, &f, FS_READ ); - if ( !f ) - { - //cgi_Error( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) ); // what. this would not run - cgi_Printf( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) ); // the rest at all.. --eez - len = cgi_FS_FOpenFile( "ui/jk2hud.txt", &f, FS_READ ); - if (!f) - { - cgi_Error( va( S_COLOR_RED "default menu file not found: ui/hud.txt, unable to continue!\n", menuFile ) ); + len = cgi_FS_FOpenFile(menuFile, &f, FS_READ); + if (!f) { + // cgi_Error( va( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ) ); // what. this would not run + cgi_Printf(va(S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile)); // the rest at all.. --eez + len = cgi_FS_FOpenFile("ui/jk2hud.txt", &f, FS_READ); + if (!f) { + cgi_Error(va(S_COLOR_RED "default menu file not found: ui/hud.txt, unable to continue!\n", menuFile)); } } - if ( len >= MAX_MENUDEFFILE ) - { - cgi_FS_FCloseFile( f ); - cgi_Error( va( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE ) ); + if (len >= MAX_MENUDEFFILE) { + cgi_FS_FCloseFile(f); + cgi_Error(va(S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE)); return; } - cgi_FS_Read( buf, len, f ); + cgi_FS_Read(buf, len, f); buf[len] = 0; - cgi_FS_FCloseFile( f ); + cgi_FS_FCloseFile(f); -// COM_Compress(buf); + // COM_Compress(buf); -// cgi_UI_Menu_Reset(); + // cgi_UI_Menu_Reset(); p = buf; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if( !token || token[0] == 0 || token[0] == '}') - { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token || token[0] == 0 || token[0] == '}') { break; } - if ( Q_stricmp( token, "}" ) == 0 ) - { + if (Q_stricmp(token, "}") == 0) { break; } - if (Q_stricmp(token, "loadmenu") == 0) - { - if (CG_Load_Menu(&p)) - { + if (Q_stricmp(token, "loadmenu") == 0) { + if (CG_Load_Menu(&p)) { continue; - } - else - { + } else { break; } } @@ -2407,69 +2124,66 @@ CG_LoadHudMenu(); ================= */ -void CG_LoadHudMenu(void) -{ +void CG_LoadHudMenu(void) { const char *hudSet; -/* - cgDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip; - cgDC.setColor = &trap_R_SetColor; - cgDC.drawHandlePic = &CG_DrawPic; - cgDC.drawStretchPic = &trap_R_DrawStretchPic; - cgDC.drawText = &CG_Text_Paint; - cgDC.textWidth = &CG_Text_Width; - cgDC.textHeight = &CG_Text_Height; - cgDC.registerModel = &trap_R_RegisterModel; - cgDC.modelBounds = &trap_R_ModelBounds; - cgDC.fillRect = &CG_FillRect; - cgDC.drawRect = &CG_DrawRect; - cgDC.drawSides = &CG_DrawSides; - cgDC.drawTopBottom = &CG_DrawTopBottom; - cgDC.clearScene = &trap_R_ClearScene; - cgDC.addRefEntityToScene = &trap_R_AddRefEntityToScene; - cgDC.renderScene = &trap_R_RenderScene; - cgDC.registerFont = &trap_R_RegisterFont; - cgDC.ownerDrawItem = &CG_OwnerDraw; - cgDC.getValue = &CG_GetValue; - cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; - cgDC.runScript = &CG_RunMenuScript; - cgDC.getTeamColor = &CG_GetTeamColor; - cgDC.setCVar = trap_Cvar_Set; - cgDC.getCVarString = trap_Cvar_VariableStringBuffer; - cgDC.getCVarValue = CG_Cvar_Get; - cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; - cgDC.startLocalSound = &trap_S_StartLocalSound; - cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; - cgDC.feederCount = &CG_FeederCount; - cgDC.feederItemImage = &CG_FeederItemImage; - cgDC.feederItemText = &CG_FeederItemText; - cgDC.feederSelection = &CG_FeederSelection; - cgDC.Error = &Com_Error; - cgDC.Print = &Com_Printf; - cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; - cgDC.registerSound = &trap_S_RegisterSound; - cgDC.startBackgroundTrack = &trap_S_StartBackgroundTrack; - cgDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack; - cgDC.playCinematic = &CG_PlayCinematic; - cgDC.stopCinematic = &CG_StopCinematic; - cgDC.drawCinematic = &CG_DrawCinematic; - cgDC.runCinematicFrame = &CG_RunCinematicFrame; -*/ -// Init_Display(&cgDC); - -// cgi_UI_String_Init(); - -// cgi_UI_Menu_Reset(); + /* + cgDC.registerShaderNoMip = &trap_R_RegisterShaderNoMip; + cgDC.setColor = &trap_R_SetColor; + cgDC.drawHandlePic = &CG_DrawPic; + cgDC.drawStretchPic = &trap_R_DrawStretchPic; + cgDC.drawText = &CG_Text_Paint; + cgDC.textWidth = &CG_Text_Width; + cgDC.textHeight = &CG_Text_Height; + cgDC.registerModel = &trap_R_RegisterModel; + cgDC.modelBounds = &trap_R_ModelBounds; + cgDC.fillRect = &CG_FillRect; + cgDC.drawRect = &CG_DrawRect; + cgDC.drawSides = &CG_DrawSides; + cgDC.drawTopBottom = &CG_DrawTopBottom; + cgDC.clearScene = &trap_R_ClearScene; + cgDC.addRefEntityToScene = &trap_R_AddRefEntityToScene; + cgDC.renderScene = &trap_R_RenderScene; + cgDC.registerFont = &trap_R_RegisterFont; + cgDC.ownerDrawItem = &CG_OwnerDraw; + cgDC.getValue = &CG_GetValue; + cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; + cgDC.runScript = &CG_RunMenuScript; + cgDC.getTeamColor = &CG_GetTeamColor; + cgDC.setCVar = trap_Cvar_Set; + cgDC.getCVarString = trap_Cvar_VariableStringBuffer; + cgDC.getCVarValue = CG_Cvar_Get; + cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; + cgDC.startLocalSound = &trap_S_StartLocalSound; + cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; + cgDC.feederCount = &CG_FeederCount; + cgDC.feederItemImage = &CG_FeederItemImage; + cgDC.feederItemText = &CG_FeederItemText; + cgDC.feederSelection = &CG_FeederSelection; + cgDC.Error = &Com_Error; + cgDC.Print = &Com_Printf; + cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; + cgDC.registerSound = &trap_S_RegisterSound; + cgDC.startBackgroundTrack = &trap_S_StartBackgroundTrack; + cgDC.stopBackgroundTrack = &trap_S_StopBackgroundTrack; + cgDC.playCinematic = &CG_PlayCinematic; + cgDC.stopCinematic = &CG_StopCinematic; + cgDC.drawCinematic = &CG_DrawCinematic; + cgDC.runCinematicFrame = &CG_RunCinematicFrame; + */ + // Init_Display(&cgDC); + + // cgi_UI_String_Init(); + + // cgi_UI_Menu_Reset(); hudSet = cg_hudFiles.string; - if (hudSet[0] == '\0') - { + if (hudSet[0] == '\0') { hudSet = "ui/jk2hud.txt"; } CG_LoadMenus(hudSet); } - /* ============================================================================== @@ -2483,9 +2197,8 @@ INVENTORY SELECTION CG_InventorySelectable =============== */ -static qboolean CG_InventorySelectable( int index) -{ - if (cg.snap->ps.inventory[index]) // Is there any in the inventory? +static qboolean CG_InventorySelectable(int index) { + if (cg.snap->ps.inventory[index]) // Is there any in the inventory? { return qtrue; } @@ -2493,23 +2206,19 @@ static qboolean CG_InventorySelectable( int index) return qfalse; } - /* =============== SetInventoryTime =============== */ -static void SetInventoryTime(void) -{ +static void SetInventoryTime(void) { if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD - ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD + ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD { cg.weaponSelectTime = 0; cg.forcepowerSelectTime = 0; cg.inventorySelectTime = cg.time + 130.0f; - } - else - { + } else { cg.inventorySelectTime = cg.time; } } @@ -2519,28 +2228,23 @@ static void SetInventoryTime(void) CG_DPPrevInventory_f =============== */ -void CG_DPPrevInventory_f( void ) -{ - int i; +void CG_DPPrevInventory_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } const int original = cg.DataPadInventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.DataPadInventorySelect--; - if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) - { + if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) { cg.DataPadInventorySelect = (INV_MAX - 1); } - if ( CG_InventorySelectable( cg.DataPadInventorySelect ) ) - { + if (CG_InventorySelectable(cg.DataPadInventorySelect)) { return; } } @@ -2552,28 +2256,23 @@ void CG_DPPrevInventory_f( void ) CG_DPNextInventory_f =============== */ -void CG_DPNextInventory_f( void ) -{ - int i; +void CG_DPNextInventory_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } const int original = cg.DataPadInventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.DataPadInventorySelect++; - if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) - { + if ((cg.DataPadInventorySelect < INV_ELECTROBINOCULARS) || (cg.DataPadInventorySelect >= INV_MAX)) { cg.DataPadInventorySelect = INV_ELECTROBINOCULARS; } - if ( CG_InventorySelectable( cg.DataPadInventorySelect ) && (inv_icons[cg.DataPadInventorySelect])) - { + if (CG_InventorySelectable(cg.DataPadInventorySelect) && (inv_icons[cg.DataPadInventorySelect])) { return; } } @@ -2586,38 +2285,32 @@ void CG_DPNextInventory_f( void ) CG_NextInventory_f =============== */ -void CG_NextInventory_f( void ) -{ - int i; - float *color; +void CG_NextInventory_f(void) { + int i; + float *color; - if ( !cg.snap ) - { + if (!cg.snap) { return; } // The first time it's been hit so just show inventory but don't advance in inventory. - color = CG_FadeColor( cg.inventorySelectTime, WEAPON_SELECT_TIME ); - if ( !color ) - { + color = CG_FadeColor(cg.inventorySelectTime, WEAPON_SELECT_TIME); + if (!color) { SetInventoryTime(); return; } const int original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.inventorySelect++; - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = INV_ELECTROBINOCULARS; } - if ( CG_InventorySelectable( cg.inventorySelect ) && (inv_icons[cg.inventorySelect])) - { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + if (CG_InventorySelectable(cg.inventorySelect) && (inv_icons[cg.inventorySelect])) { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); SetInventoryTime(); return; } @@ -2640,38 +2333,32 @@ this func was moved to Cmd_UseInventory_f in g_cmds.cpp CG_PrevInventory_f =============== */ -void CG_PrevInventory_f( void ) -{ - int i; - float *color; +void CG_PrevInventory_f(void) { + int i; + float *color; - if ( !cg.snap ) - { + if (!cg.snap) { return; } // The first time it's been hit so just show inventory but don't advance in inventory. - color = CG_FadeColor( cg.inventorySelectTime, WEAPON_SELECT_TIME ); - if ( !color ) - { + color = CG_FadeColor(cg.inventorySelectTime, WEAPON_SELECT_TIME); + if (!color) { SetInventoryTime(); return; } const int original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { + for (i = 0; i < INV_MAX; i++) { cg.inventorySelect--; - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = (INV_MAX - 1); } - if ( CG_InventorySelectable( cg.inventorySelect ) && (inv_icons[cg.inventorySelect])) - { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + if (CG_InventorySelectable(cg.inventorySelect) && (inv_icons[cg.inventorySelect])) { + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); SetInventoryTime(); return; } @@ -2680,49 +2367,47 @@ void CG_PrevInventory_f( void ) cg.inventorySelect = original; } - /* =================== FindInventoryItemTag =================== */ -gitem_t *FindInventoryItemTag(int tag) -{ - int i; +gitem_t *FindInventoryItemTag(int tag) { + int i; -/* if (!Q_stricmp(tokenStr,"INV_ELECTROBINOCULARS") - { - tag = INV_ELECTROBINOCULARS; - } - else if (!Q_stricmp(tokenStr,"INV_BACTA_CANISTER") - { - tag = INV_BACTA_CANISTER; - } - else if (!Q_stricmp(tokenStr,"INV_SEEKER") - { - tag = INV_SEEKER; - } - else if (!Q_stricmp(tokenStr,"INV_LIGHTAMP_GOGGLES") - { - tag = INV_LIGHTAMP_GOGGLES; - } - else if (!Q_stricmp(tokenStr,"INV_SENTRY") - { - tag = INV_SENTRY; - } - else if (!Q_stricmp(tokenStr,"INV_GOODIE_KEY") - { - tag = INV_GOODIE_KEY; - } - else if (!Q_stricmp(tokenStr,"INV_SECURITY_KEY") - { - tag = INV_SECURITY_KEY; - } -*/ + /* if (!Q_stricmp(tokenStr,"INV_ELECTROBINOCULARS") + { + tag = INV_ELECTROBINOCULARS; + } + else if (!Q_stricmp(tokenStr,"INV_BACTA_CANISTER") + { + tag = INV_BACTA_CANISTER; + } + else if (!Q_stricmp(tokenStr,"INV_SEEKER") + { + tag = INV_SEEKER; + } + else if (!Q_stricmp(tokenStr,"INV_LIGHTAMP_GOGGLES") + { + tag = INV_LIGHTAMP_GOGGLES; + } + else if (!Q_stricmp(tokenStr,"INV_SENTRY") + { + tag = INV_SENTRY; + } + else if (!Q_stricmp(tokenStr,"INV_GOODIE_KEY") + { + tag = INV_GOODIE_KEY; + } + else if (!Q_stricmp(tokenStr,"INV_SECURITY_KEY") + { + tag = INV_SECURITY_KEY; + } + */ - for ( i = 1 ; i < bg_numItems ; i++ ) - { - if ( bg_itemlist[i].giTag == tag && bg_itemlist[i].giType == IT_HOLDABLE ) // I guess giTag's aren't unique amongst items..must also make sure it's a holdable + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giTag == tag && + bg_itemlist[i].giType == IT_HOLDABLE) // I guess giTag's aren't unique amongst items..must also make sure it's a holdable { return &bg_itemlist[i]; } @@ -2731,42 +2416,36 @@ gitem_t *FindInventoryItemTag(int tag) return (0); } - - - /* =================== CG_DrawInventorySelect =================== */ -void CG_DrawInventorySelect( void ) -{ - int i; - int sideMax,holdCount,iconCnt; - int smallIconSize,bigIconSize; - int sideLeftIconCnt,sideRightIconCnt; - int count; - int holdX,x,y,pad; - //int height; -// int tag; - float addX; - vec4_t textColor = { .312f, .75f, .621f, 1.0f }; - char text[1024]={0}; +void CG_DrawInventorySelect(void) { + int i; + int sideMax, holdCount, iconCnt; + int smallIconSize, bigIconSize; + int sideLeftIconCnt, sideRightIconCnt; + int count; + int holdX, x, y, pad; + // int height; + // int tag; + float addX; + vec4_t textColor = {.312f, .75f, .621f, 1.0f}; + char text[1024] = {0}; // don't display if dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )) - { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } - if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)ps.stats[ STAT_ITEMS ]; + // const int bits = cg.snap->ps.stats[ STAT_ITEMS ]; // count the number of items owned count = 0; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if (CG_InventorySelectable(i) && inv_icons[i]) - { + for (i = 0; i < INV_MAX; i++) { + if (CG_InventorySelectable(i) && inv_icons[i]) { count++; } } - if (!count) - { - cgi_SP_GetStringTextString("INGAME_EMPTY_INV",text, sizeof(text) ); - int w = cgi_R_Font_StrLenPixels( text, cgs.media.qhFontSmall, 1.0f ); - x = ( SCREEN_WIDTH - w ) / 2; + if (!count) { + cgi_SP_GetStringTextString("INGAME_EMPTY_INV", text, sizeof(text)); + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + x = (SCREEN_WIDTH - w) / 2; CG_DrawProportionalString(x, y2 + 22, text, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.inventorySelect - 1; - if (i<0) - { - i = INV_MAX-1; + if (i < 0) { + i = INV_MAX - 1; } smallIconSize = 40; @@ -2831,194 +2504,161 @@ void CG_DrawInventorySelect( void ) // Left side ICONS // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; - for (iconCnt=0;iconCntps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; - if (inv_icons[cg.inventorySelect]) - { + // height = bigIconSize * cg.iconHUDPercent; + if (inv_icons[cg.inventorySelect]) { cgi_R_SetColor(NULL); - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, inv_icons[cg.inventorySelect] ); - addX = (float) bigIconSize * .75; + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, inv_icons[cg.inventorySelect]); + addX = (float)bigIconSize * .75; cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField ((x-(bigIconSize/2)) + addX, y, 2, cg.snap->ps.inventory[cg.inventorySelect], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField((x - (bigIconSize / 2)) + addX, y, 2, cg.snap->ps.inventory[cg.inventorySelect], 6, 12, NUM_FONT_SMALL, qfalse); - if (inv_names[cg.inventorySelect]) - { + if (inv_names[cg.inventorySelect]) { // FIXME: This is ONLY a temp solution, the icon stuff, etc, should all just use items.dat for everything - gitem_t *item = FindInventoryItemTag( cg.inventorySelect ); + gitem_t *item = FindInventoryItemTag(cg.inventorySelect); - if ( item && item->classname && item->classname[0] ) - { + if (item && item->classname && item->classname[0]) { char itemName[256], data[1024]; // FIXME: do these really need to be this large?? does it matter? - sprintf( itemName, "INGAME_%s", item->classname ); + sprintf(itemName, "INGAME_%s", item->classname); - if ( cgi_SP_GetStringTextString( itemName, data, sizeof( data ))) - { - int w = cgi_R_Font_StrLenPixels( data, cgs.media.qhFontSmall, 1.0f ); - int x = ( SCREEN_WIDTH - w ) / 2; + if (cgi_SP_GetStringTextString(itemName, data, sizeof(data))) { + int w = cgi_R_Font_StrLenPixels(data, cgs.media.qhFontSmall, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; - cgi_R_Font_DrawString( x, (SCREEN_HEIGHT - 24), data, textColor, cgs.media.qhFontSmall, -1, 1.0f); + cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24), data, textColor, cgs.media.qhFontSmall, -1, 1.0f); } } -// if (tag) -// { -// CG_DrawProportionalString(320, y + 53, inv_names[cg.inventorySelect], CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); -// CG_DrawProportionalString(320, y + 53, bg_itemlist[i].pickup_name, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); -// } + // if (tag) + // { + // CG_DrawProportionalString(320, y + 53, inv_names[cg.inventorySelect], CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); + // CG_DrawProportionalString(320, y + 53, bg_itemlist[i].pickup_name, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); + // } } } i = cg.inventorySelect + 1; - if (i> INV_MAX-1) - { + if (i > INV_MAX - 1) { i = 0; } // Right side ICONS // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCnt INV_MAX-1) - { + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; + for (iconCnt = 0; iconCnt < sideRightIconCnt; i++) { + if (i > INV_MAX - 1) { i = 0; } - if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) - { + if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (inv_icons[i]) - { + if (inv_icons[i]) { cgi_R_SetColor(NULL); - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, inv_icons[i] ); + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, inv_icons[i]); cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField (holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char *text); +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text); -char *inventoryDesc[15] = -{ -"NEURO_SAAV_DESC", -"BACTA_DESC", -"INQUISITOR_DESC", -"LA_GOGGLES_DESC", -"PORTABLE_SENTRY_DESC", -"GOODIE_KEY_DESC", -"SECURITY_KEY_DP_DESC", +char *inventoryDesc[15] = { + "NEURO_SAAV_DESC", "BACTA_DESC", "INQUISITOR_DESC", "LA_GOGGLES_DESC", "PORTABLE_SENTRY_DESC", "GOODIE_KEY_DESC", "SECURITY_KEY_DP_DESC", }; - /* =================== CG_DrawDataPadInventorySelect =================== */ -void CG_DrawDataPadInventorySelect( void ) -{ - int i; - int sideMax,holdCount,iconCnt; - int smallIconSize,bigIconSize; - int sideLeftIconCnt,sideRightIconCnt; - int count; - int holdX,x,y,pad; - //int height; - float addX; - char text[1024]={0}; - vec4_t textColor = { .312f, .75f, .621f, 1.0f }; - +void CG_DrawDataPadInventorySelect(void) { + int i; + int sideMax, holdCount, iconCnt; + int smallIconSize, bigIconSize; + int sideLeftIconCnt, sideRightIconCnt; + int count; + int holdX, x, y, pad; + // int height; + float addX; + char text[1024] = {0}; + vec4_t textColor = {.312f, .75f, .621f, 1.0f}; // count the number of items owned count = 0; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if (CG_InventorySelectable(i) && inv_icons[i]) - { + for (i = 0; i < INV_MAX; i++) { + if (CG_InventorySelectable(i) && inv_icons[i]) { count++; } } - - if (!count) - { - cgi_SP_GetStringTextString("INGAME_EMPTY_INV",text, sizeof(text) ); - int w = cgi_R_Font_StrLenPixels( text, cgs.media.qhFontSmall, 1.0f ); - x = ( SCREEN_WIDTH - w ) / 2; + if (!count) { + cgi_SP_GetStringTextString("INGAME_EMPTY_INV", text, sizeof(text)); + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + x = (SCREEN_WIDTH - w) / 2; CG_DrawProportionalString(x, 300 + 22, text, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } -// char buffer[256]; -// cgi_UI_GetItemText("datapadInventoryMenu",va("invdesc%d",cg.DataPadInventorySelect+1),buffer); + // char buffer[256]; + // cgi_UI_GetItemText("datapadInventoryMenu",va("invdesc%d",cg.DataPadInventorySelect+1),buffer); i = cg.DataPadInventorySelect - 1; - if (i<0) - { - i = INV_MAX-1; + if (i < 0) { + i = INV_MAX - 1; } smallIconSize = 40; @@ -3030,114 +2670,94 @@ void CG_DrawDataPadInventorySelect( void ) // Left side ICONS // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; - for (iconCnt=0;iconCntps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; - if (inv_icons[cg.DataPadInventorySelect]) - { + // height = bigIconSize * cg.iconHUDPercent; + if (inv_icons[cg.DataPadInventorySelect]) { cgi_R_SetColor(NULL); - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, inv_icons[cg.DataPadInventorySelect] ); - addX = (float) bigIconSize * .75; + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, inv_icons[cg.DataPadInventorySelect]); + addX = (float)bigIconSize * .75; cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField ((x-(bigIconSize/2)) + addX, y, 2, cg.snap->ps.inventory[cg.DataPadInventorySelect], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField((x - (bigIconSize / 2)) + addX, y, 2, cg.snap->ps.inventory[cg.DataPadInventorySelect], 6, 12, NUM_FONT_SMALL, qfalse); - if (inv_names[cg.DataPadInventorySelect]) - { + if (inv_names[cg.DataPadInventorySelect]) { // FIXME :this has to use the bg_itemlist pickup name -// tag = FindInventoryItemTag(cg.inventorySelect); + // tag = FindInventoryItemTag(cg.inventorySelect); -// if (tag) -// { -// CG_DrawProportionalString(320, y + 53, inv_names[cg.inventorySelect], CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); -// CG_DrawProportionalString(320, y + 53, bg_itemlist[i].pickup_name, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); -// } + // if (tag) + // { + // CG_DrawProportionalString(320, y + 53, inv_names[cg.inventorySelect], CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); + // CG_DrawProportionalString(320, y + 53, bg_itemlist[i].pickup_name, CG_CENTER | CG_SMALLFONT, colorTable[CT_ICON_BLUE]); + // } } } i = cg.DataPadInventorySelect + 1; - if (i> INV_MAX-1) - { + if (i > INV_MAX - 1) { i = 0; } // Right side ICONS // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; - addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCnt INV_MAX-1) - { + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + addX = (float)smallIconSize * .75; + for (iconCnt = 0; iconCnt < sideRightIconCnt; i++) { + if (i > INV_MAX - 1) { i = 0; } - if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) - { + if ((!CG_InventorySelectable(i)) || (!inv_icons[i])) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (inv_icons[i]) - { + if (inv_icons[i]) { cgi_R_SetColor(NULL); - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, inv_icons[i] ); + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, inv_icons[i]); cgi_R_SetColor(colorTable[CT_ICON_BLUE]); - CG_DrawNumField (holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, - NUM_FONT_SMALL,qfalse); + CG_DrawNumField(holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL, qfalse); - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } // draw the weapon description - x= 40; - y= 70; + x = 40; + y = 70; - if ((cg.DataPadInventorySelect>=0) && (cg.DataPadInventorySelect<13)) - { - cgi_SP_GetStringTextString( va("INGAME_%s",inventoryDesc[cg.DataPadInventorySelect]), text, sizeof(text) ); + if ((cg.DataPadInventorySelect >= 0) && (cg.DataPadInventorySelect < 13)) { + cgi_SP_GetStringTextString(va("INGAME_%s", inventoryDesc[cg.DataPadInventorySelect]), text, sizeof(text)); - if (text[0]) - { - CG_DisplayBoxedText(70,50,500,300,text, - cgs.media.qhFontSmall, - 0.7f, - textColor - ); + if (text[0]) { + CG_DisplayBoxedText(70, 50, 500, 300, text, cgs.media.qhFontSmall, 0.7f, textColor); } } } @@ -3147,55 +2767,25 @@ void CG_DrawDataPadInventorySelect( void ) SetForcePowerTime =============== */ -void SetForcePowerTime(void) -{ - if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD - ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Inventory HUD was currently active to just swap it out with Force HUD +void SetForcePowerTime(void) { + if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Weapon HUD was currently active to just swap it out with Force HUD + ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Inventory HUD was currently active to just swap it out with Force HUD { cg.weaponSelectTime = 0; cg.inventorySelectTime = 0; cg.forcepowerSelectTime = cg.time + 130.0f; - } - else - { + } else { cg.forcepowerSelectTime = cg.time; } } -int showPowers[MAX_SHOWPOWERS] = -{ - FP_HEAL, - FP_SPEED, - FP_PUSH, - FP_PULL, - FP_TELEPATHY, - FP_GRIP, - FP_LIGHTNING -}; -char *showPowersName[MAX_SHOWPOWERS] = -{ - "HEAL2", - "SPEED2", - "PUSH2", - "PULL2", - "MINDTRICK2", - "GRIP2", - "LIGHTNING2", +int showPowers[MAX_SHOWPOWERS] = {FP_HEAL, FP_SPEED, FP_PUSH, FP_PULL, FP_TELEPATHY, FP_GRIP, FP_LIGHTNING}; +char *showPowersName[MAX_SHOWPOWERS] = { + "HEAL2", "SPEED2", "PUSH2", "PULL2", "MINDTRICK2", "GRIP2", "LIGHTNING2", }; -int showDataPadPowers[MAX_DPSHOWPOWERS] = -{ - FP_HEAL, - FP_LEVITATION, - FP_SPEED, - FP_PUSH, - FP_PULL, - FP_TELEPATHY, - FP_GRIP, - FP_LIGHTNING, - FP_SABERTHROW, - FP_SABER_DEFENSE, - FP_SABER_OFFENSE, +int showDataPadPowers[MAX_DPSHOWPOWERS] = { + FP_HEAL, FP_LEVITATION, FP_SPEED, FP_PUSH, FP_PULL, FP_TELEPATHY, FP_GRIP, FP_LIGHTNING, FP_SABERTHROW, FP_SABER_DEFENSE, FP_SABER_OFFENSE, }; /*char *showDataPadPowersName[MAX_DPSHOWPOWERS] = @@ -3219,14 +2809,13 @@ int showDataPadPowers[MAX_DPSHOWPOWERS] = ForcePower_Valid =============== */ -qboolean ForcePower_Valid(int index) -{ - gentity_t *player = &g_entities[0]; +qboolean ForcePower_Valid(int index) { + gentity_t *player = &g_entities[0]; - assert (MAX_SHOWPOWERS == ( sizeof(showPowers)/sizeof(showPowers[0]) )); - assert (index < MAX_SHOWPOWERS ); //is this a valid index? + assert(MAX_SHOWPOWERS == (sizeof(showPowers) / sizeof(showPowers[0]))); + assert(index < MAX_SHOWPOWERS); // is this a valid index? if (player->client->ps.forcePowersKnown & (1 << showPowers[index]) && - player->client->ps.forcePowerLevel[showPowers[index]]) // Does he have the force power? + player->client->ps.forcePowerLevel[showPowers[index]]) // Does he have the force power? { return qtrue; } @@ -3239,36 +2828,31 @@ qboolean ForcePower_Valid(int index) CG_NextForcePower_f =============== */ -void CG_NextForcePower_f( void ) -{ - int i; +void CG_NextForcePower_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } SetForcePowerTime(); - if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) - { + if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) { return; } const int original = cg.forcepowerSelect; - for ( i = 0; i < MAX_SHOWPOWERS; i++ ) - { + for (i = 0; i < MAX_SHOWPOWERS; i++) { cg.forcepowerSelect++; - if (cg.forcepowerSelect >= MAX_SHOWPOWERS) - { + if (cg.forcepowerSelect >= MAX_SHOWPOWERS) { cg.forcepowerSelect = 0; } - if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? + if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); return; } } @@ -3281,41 +2865,35 @@ void CG_NextForcePower_f( void ) CG_PrevForcePower_f =============== */ -void CG_PrevForcePower_f( void ) -{ - int i; +void CG_PrevForcePower_f(void) { + int i; - if ( !cg.snap ) - { + if (!cg.snap) { return; } SetForcePowerTime(); - if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) - { + if ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) < cg.time) { return; } const int original = cg.forcepowerSelect; - for ( i = 0; i < MAX_SHOWPOWERS; i++ ) - { + for (i = 0; i < MAX_SHOWPOWERS; i++) { cg.forcepowerSelect--; - if (cg.forcepowerSelect < 0) - { + if (cg.forcepowerSelect < 0) { cg.forcepowerSelect = MAX_SHOWPOWERS - 1; } - if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? + if (ForcePower_Valid(cg.forcepowerSelect)) // Does he have the force power? { - cgi_S_StartSound (NULL, 0, CHAN_AUTO, cgs.media.selectSound2 ); + cgi_S_StartSound(NULL, 0, CHAN_AUTO, cgs.media.selectSound2); return; } } - cg.forcepowerSelect = original; } @@ -3324,24 +2902,21 @@ void CG_PrevForcePower_f( void ) CG_DrawForceSelect =================== */ -void CG_DrawForceSelect( void ) -{ - int i; - int count; - int smallIconSize,bigIconSize; - int holdX,x,y,pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; - char text[1024]={0}; - +void CG_DrawForceSelect(void) { + int i; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + char text[1024] = {0}; // don't display if dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD )) - { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0 || (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } - if ((cg.forcepowerSelectTime+WEAPON_SELECT_TIME) (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } @@ -3402,77 +2973,67 @@ void CG_DrawForceSelect( void ) y = 425; i = cg.forcepowerSelect - 1; - if (i < 0) - { - i = MAX_SHOWPOWERS-1; + if (i < 0) { + i = MAX_SHOWPOWERS - 1; } cgi_R_SetColor(NULL); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i < 0) - { - i = MAX_SHOWPOWERS-1; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 0) { + i = MAX_SHOWPOWERS - 1; } - if (!ForcePower_Valid(i)) // Does he have this power? + if (!ForcePower_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showPowers[i]]) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, force_icons[showPowers[i]] ); - holdX -= (smallIconSize+pad); + if (force_icons[showPowers[i]]) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, force_icons[showPowers[i]]); + holdX -= (smallIconSize + pad); } } // Current Center Icon - if (force_icons[showPowers[cg.forcepowerSelect]]) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)), bigIconSize, bigIconSize, force_icons[showPowers[cg.forcepowerSelect]] ); //only cache the icon for display + if (force_icons[showPowers[cg.forcepowerSelect]]) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)), bigIconSize, bigIconSize, + force_icons[showPowers[cg.forcepowerSelect]]); // only cache the icon for display } - i = cg.forcepowerSelect + 1; - if (i>=MAX_SHOWPOWERS) - { + if (i >= MAX_SHOWPOWERS) { i = 0; } // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>=MAX_SHOWPOWERS) - { + holdX = x + (bigIconSize / 2) + pad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i >= MAX_SHOWPOWERS) { i = 0; } - if (!ForcePower_Valid(i)) // Does he have this power? + if (!ForcePower_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showPowers[i]]) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, force_icons[showPowers[i]] ); //only cache the icon for display - holdX += (smallIconSize+pad); + if (force_icons[showPowers[i]]) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, force_icons[showPowers[i]]); // only cache the icon for display + holdX += (smallIconSize + pad); } } // This only a temp solution. - if (cgi_SP_GetStringTextString( va("INGAME_%s",showPowersName[cg.forcepowerSelect]), text, sizeof(text) )) - { - int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - int x = ( SCREEN_WIDTH - w ) / 2; - cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24), text, colorTable[CT_ICON_BLUE], cgs.media.qhFontSmall, -1, 1.0f); + if (cgi_SP_GetStringTextString(va("INGAME_%s", showPowersName[cg.forcepowerSelect]), text, sizeof(text))) { + int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + int x = (SCREEN_WIDTH - w) / 2; + cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24), text, colorTable[CT_ICON_BLUE], cgs.media.qhFontSmall, -1, 1.0f); } } @@ -3481,13 +3042,12 @@ void CG_DrawForceSelect( void ) ForcePowerDataPad_Valid =============== */ -qboolean ForcePowerDataPad_Valid(int index) -{ - gentity_t *player = &g_entities[0]; +qboolean ForcePowerDataPad_Valid(int index) { + gentity_t *player = &g_entities[0]; - assert (index < MAX_DPSHOWPOWERS); + assert(index < MAX_DPSHOWPOWERS); if (player->client->ps.forcePowersKnown & (1 << showDataPadPowers[index]) && - player->client->ps.forcePowerLevel[showDataPadPowers[index]]) // Does he have the force power? + player->client->ps.forcePowerLevel[showDataPadPowers[index]]) // Does he have the force power? { return qtrue; } @@ -3500,28 +3060,24 @@ qboolean ForcePowerDataPad_Valid(int index) CG_DPNextForcePower_f =============== */ -void CG_DPNextForcePower_f( void ) -{ - int i; - int original; +void CG_DPNextForcePower_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } original = cg.DataPadforcepowerSelect; - for ( i = 0; i= MAX_DPSHOWPOWERS) - { + if (cg.DataPadforcepowerSelect >= MAX_DPSHOWPOWERS) { cg.DataPadforcepowerSelect = 0; } - if (ForcePowerDataPad_Valid(cg.DataPadforcepowerSelect)) // Does he have the force power? + if (ForcePowerDataPad_Valid(cg.DataPadforcepowerSelect)) // Does he have the force power? { return; } @@ -3535,95 +3091,53 @@ void CG_DPNextForcePower_f( void ) CG_DPPrevForcePower_f =============== */ -void CG_DPPrevForcePower_f( void ) -{ - int i; - int original; +void CG_DPPrevForcePower_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } original = cg.DataPadforcepowerSelect; - for ( i = 0; i (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } - smallIconSize = 30; bigIconSize = 60; pad = 8; @@ -3694,127 +3201,101 @@ void CG_DrawDataPadForceSelect( void ) y = 310; i = cg.DataPadforcepowerSelect - 1; - if (i < 0) - { - i = MAX_DPSHOWPOWERS-1; + if (i < 0) { + i = MAX_DPSHOWPOWERS - 1; } cgi_R_SetColor(NULL); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i < 0) - { - i = MAX_DPSHOWPOWERS-1; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 0) { + i = MAX_DPSHOWPOWERS - 1; } - if (!ForcePowerDataPad_Valid(i)) // Does he have this power? + if (!ForcePowerDataPad_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showDataPadPowers[i]]) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]] ); + if (force_icons[showDataPadPowers[i]]) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]]); } // A new force power - if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay ); + if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay); } - if (force_icons[showDataPadPowers[i]]) - { - holdX -= (smallIconSize+pad); + if (force_icons[showDataPadPowers[i]]) { + holdX -= (smallIconSize + pad); } } // Current Center Icon - if (force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]) - { + if (force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]) { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)), bigIconSize, bigIconSize, force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]] ); //only cache the icon for display + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)), bigIconSize, bigIconSize, + force_icons[showDataPadPowers[cg.DataPadforcepowerSelect]]); // only cache the icon for display // New force power if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect])) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)), bigIconSize, bigIconSize, cgs.media.DPForcePowerOverlay ); + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[cg.DataPadforcepowerSelect])) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)), bigIconSize, bigIconSize, cgs.media.DPForcePowerOverlay); } } - i = cg.DataPadforcepowerSelect + 1; - if (i>=MAX_DPSHOWPOWERS) - { + if (i >= MAX_DPSHOWPOWERS) { i = 0; } // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>=MAX_DPSHOWPOWERS) - { + holdX = x + (bigIconSize / 2) + pad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i >= MAX_DPSHOWPOWERS) { i = 0; } - if (!ForcePowerDataPad_Valid(i)) // Does he have this power? + if (!ForcePowerDataPad_Valid(i)) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (force_icons[showDataPadPowers[i]]) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]] ); //only cache the icon for display + if (force_icons[showDataPadPowers[i]]) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, force_icons[showDataPadPowers[i]]); // only cache the icon for display } // A new force power - if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || - ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) - { - CG_DrawPic( holdX, y, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay ); //only cache the icon for display + if (((cg_updatedDataPadForcePower1.integer - 1) == showDataPadPowers[i]) || ((cg_updatedDataPadForcePower2.integer - 1) == showDataPadPowers[i]) || + ((cg_updatedDataPadForcePower3.integer - 1) == showDataPadPowers[i])) { + CG_DrawPic(holdX, y, smallIconSize, smallIconSize, cgs.media.DPForcePowerOverlay); // only cache the icon for display } - if (force_icons[showDataPadPowers[i]]) - { - holdX += (smallIconSize+pad); + if (force_icons[showDataPadPowers[i]]) { + holdX += (smallIconSize + pad); } } - cgi_SP_GetStringTextString( va("INGAME_%s",forcepowerDesc[cg.DataPadforcepowerSelect]), text, sizeof(text) ); + cgi_SP_GetStringTextString(va("INGAME_%s", forcepowerDesc[cg.DataPadforcepowerSelect]), text, sizeof(text)); - if (player->client->ps.forcePowerLevel[cg.DataPadforcepowerSelect]==1) - { - cgi_SP_GetStringTextString( va("INGAME_%s",forcepowerLvl1Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); - } - else if (player->client->ps.forcePowerLevel[cg.DataPadforcepowerSelect]==2) - { - cgi_SP_GetStringTextString( va("INGAME_%s",forcepowerLvl2Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); - } - else - { - cgi_SP_GetStringTextString( va("INGAME_%s",forcepowerLvl3Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2) ); + if (player->client->ps.forcePowerLevel[cg.DataPadforcepowerSelect] == 1) { + cgi_SP_GetStringTextString(va("INGAME_%s", forcepowerLvl1Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); + } else if (player->client->ps.forcePowerLevel[cg.DataPadforcepowerSelect] == 2) { + cgi_SP_GetStringTextString(va("INGAME_%s", forcepowerLvl2Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); + } else { + cgi_SP_GetStringTextString(va("INGAME_%s", forcepowerLvl3Desc[cg.DataPadforcepowerSelect]), text2, sizeof(text2)); } - if (text[0]) - { + if (text[0]) { - CG_DisplayBoxedText(70,50,500,300,va("%s%s",text,text2), - cgs.media.qhFontSmall, - 0.7f, - colorTable[CT_ICON_BLUE] - ); + CG_DisplayBoxedText(70, 50, 500, 300, va("%s%s", text, text2), cgs.media.qhFontSmall, 0.7f, colorTable[CT_ICON_BLUE]); } } @@ -3842,7 +3323,3 @@ static void CG_RunCinematicFrame(int handle) { } #pragma warning ( default : 4505) */ - - - - diff --git a/codeJK2/cgame/cg_marks.cpp b/codeJK2/cgame/cg_marks.cpp index f4bcfa8da3..1bcd6ba390 100644 --- a/codeJK2/cgame/cg_marks.cpp +++ b/codeJK2/cgame/cg_marks.cpp @@ -34,10 +34,9 @@ MARK POLYS =================================================================== */ - -markPoly_t cg_activeMarkPolys; // double linked list -markPoly_t *cg_freeMarkPolys; // single linked list -markPoly_t cg_markPolys[MAX_MARK_POLYS]; +markPoly_t cg_activeMarkPolys; // double linked list +markPoly_t *cg_freeMarkPolys; // single linked list +markPoly_t cg_markPolys[MAX_MARK_POLYS]; /* =================== @@ -46,28 +45,27 @@ CG_InitMarkPolys This is called at startup and for tournement restarts =================== */ -void CG_InitMarkPolys( void ) { - int i; +void CG_InitMarkPolys(void) { + int i; - memset( cg_markPolys, 0, sizeof(cg_markPolys) ); + memset(cg_markPolys, 0, sizeof(cg_markPolys)); cg_activeMarkPolys.nextMark = &cg_activeMarkPolys; cg_activeMarkPolys.prevMark = &cg_activeMarkPolys; cg_freeMarkPolys = cg_markPolys; - for ( i = 0 ; i < MAX_MARK_POLYS - 1 ; i++ ) { - cg_markPolys[i].nextMark = &cg_markPolys[i+1]; + for (i = 0; i < MAX_MARK_POLYS - 1; i++) { + cg_markPolys[i].nextMark = &cg_markPolys[i + 1]; } } - /* ================== CG_FreeMarkPoly ================== */ -void CG_FreeMarkPoly( markPoly_t *le ) { - if ( !le->prevMark ) { - CG_Error( "CG_FreeLocalEntity: not active" ); +void CG_FreeMarkPoly(markPoly_t *le) { + if (!le->prevMark) { + CG_Error("CG_FreeLocalEntity: not active"); } // remove from the doubly linked active list @@ -86,23 +84,23 @@ CG_AllocMark Will allways succeed, even if it requires freeing an old active mark =================== */ -markPoly_t *CG_AllocMark( void ) { - markPoly_t *le; +markPoly_t *CG_AllocMark(void) { + markPoly_t *le; int time; - if ( !cg_freeMarkPolys ) { + if (!cg_freeMarkPolys) { // no free entities, so free the one at the end of the chain // remove the oldest active entity time = cg_activeMarkPolys.prevMark->time; while (cg_activeMarkPolys.prevMark && time == cg_activeMarkPolys.prevMark->time) { - CG_FreeMarkPoly( cg_activeMarkPolys.prevMark ); + CG_FreeMarkPoly(cg_activeMarkPolys.prevMark); } } le = cg_freeMarkPolys; cg_freeMarkPolys = cg_freeMarkPolys->nextMark; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->nextMark = cg_activeMarkPolys.nextMark; @@ -112,8 +110,6 @@ markPoly_t *CG_AllocMark( void ) { return le; } - - /* ================= CG_ImpactMark @@ -125,40 +121,39 @@ temporary marks will not be stored or randomly oriented, but immediately passed to the renderer. ================= */ -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 - -void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, - float orientation, float red, float green, float blue, float alpha, - qboolean alphaFade, float radius, qboolean temporary ) { - vec3_t axis[3]; - float texCoordScale; - vec3_t originalPoints[4]; - byte colors[4]; - int i, j; - int numFragments; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - vec3_t markPoints[MAX_MARK_POINTS]; - vec3_t projection; - - if ( !cg_addMarks.integer ) { +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 + +void CG_ImpactMark(qhandle_t markShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, + qboolean alphaFade, float radius, qboolean temporary) { + vec3_t axis[3]; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j; + int numFragments; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; + vec3_t markPoints[MAX_MARK_POINTS]; + vec3_t projection; + + if (!cg_addMarks.integer) { return; } - if ( radius <= 0 ) { - CG_Error( "CG_ImpactMark called with <= 0 radius" ); + if (radius <= 0) { + CG_Error("CG_ImpactMark called with <= 0 radius"); } // create the texture axis - VectorNormalize2( dir, axis[0] ); - PerpendicularVector( axis[1], axis[0] ); - RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); - CrossProduct( axis[0], axis[2], axis[1] ); + VectorNormalize2(dir, axis[0]); + PerpendicularVector(axis[1], axis[0]); + RotatePointAroundVector(axis[2], axis[0], axis[1], orientation); + CrossProduct(axis[0], axis[2], axis[1]); texCoordScale = 0.5 * 1.0 / radius; // create the full polygon - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; @@ -166,42 +161,40 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, } // get the fragments - VectorScale( dir, -20, projection ); - numFragments = cgi_CM_MarkFragments( 4, (const float (*)[3])originalPoints, - projection, MAX_MARK_POINTS, markPoints[0], - MAX_MARK_FRAGMENTS, markFragments ); + VectorScale(dir, -20, projection); + numFragments = cgi_CM_MarkFragments(4, (const float(*)[3])originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); colors[0] = red * 255; colors[1] = green * 255; colors[2] = blue * 255; colors[3] = alpha * 255; - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) { - polyVert_t *v; - polyVert_t verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; // we have an upper limit on the complexity of polygons // that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) { - vec3_t delta; + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { + vec3_t delta; - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); - VectorSubtract( v->xyz, origin, delta ); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale; - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale; - for ( int k = 0; k < 4; k++ ) { + VectorSubtract(v->xyz, origin, delta); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * texCoordScale; + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * texCoordScale; + for (int k = 0; k < 4; k++) { v->modulate[k] = colors[k]; } } // if it is a temporary (shadow) mark, add it immediately and forget about it - if ( temporary ) { - cgi_R_AddPolyToScene( markShader, mf->numPoints, verts ); + if (temporary) { + cgi_R_AddPolyToScene(markShader, mf->numPoints, verts); continue; } @@ -211,56 +204,54 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, mark->alphaFade = alphaFade; mark->markShader = markShader; mark->poly.numVerts = mf->numPoints; - mark->color[0] = colors[0];//red; - mark->color[1] = colors[1];//green; - mark->color[2] = colors[2];//blue; - mark->color[3] = colors[3];//alpha; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + mark->color[0] = colors[0]; // red; + mark->color[1] = colors[1]; // green; + mark->color[2] = colors[2]; // blue; + mark->color[3] = colors[3]; // alpha; + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); } } - /* =============== CG_AddMarks =============== */ -#define MARK_TOTAL_TIME 10000 -#define MARK_FADE_TIME 1000 +#define MARK_TOTAL_TIME 10000 +#define MARK_FADE_TIME 1000 -void CG_AddMarks( void ) { - int j; - markPoly_t *mp, *next; - int t; - int fade; +void CG_AddMarks(void) { + int j; + markPoly_t *mp, *next; + int t; + int fade; - if ( !cg_addMarks.integer ) { + if (!cg_addMarks.integer) { return; } mp = cg_activeMarkPolys.nextMark; - for ( ; mp != &cg_activeMarkPolys ; mp = next ) { + for (; mp != &cg_activeMarkPolys; mp = next) { // grab next now, so if the local entity is freed we // still have it next = mp->nextMark; // see if it is time to completely remove it - if ( cg.time > mp->time + MARK_TOTAL_TIME ) { - CG_FreeMarkPoly( mp ); + if (cg.time > mp->time + MARK_TOTAL_TIME) { + CG_FreeMarkPoly(mp); continue; } // fade out the energy bursts - if ( mp->markShader == cgs.media.phaserMarkShader ) - { + if (mp->markShader == cgs.media.phaserMarkShader) { - fade = 450 - 450 * ( (cg.time - mp->time ) / 3000.0 ); - if ( fade < 255 ) { - if ( fade < 0 ) { + fade = 450 - 450 * ((cg.time - mp->time) / 3000.0); + if (fade < 255) { + if (fade < 0) { fade = 0; } - if ( mp->verts[0].modulate[0] != 0 ) { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + if (mp->verts[0].modulate[0] != 0) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0] * fade; mp->verts[j].modulate[1] = mp->color[1] * fade; mp->verts[j].modulate[2] = mp->color[2] * fade; @@ -271,34 +262,28 @@ void CG_AddMarks( void ) { // fade all marks out with time t = mp->time + MARK_TOTAL_TIME - cg.time; - if ( t < MARK_FADE_TIME ) { + if (t < MARK_FADE_TIME) { fade = 255 * t / MARK_FADE_TIME; - if ( mp->alphaFade ) { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + if (mp->alphaFade) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[3] = fade; } - } - else - { + } else { float f = (float)t / MARK_FADE_TIME; - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0] * f; mp->verts[j].modulate[1] = mp->color[1] * f; mp->verts[j].modulate[2] = mp->color[2] * f; } } - } - else - { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + } else { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0]; mp->verts[j].modulate[1] = mp->color[1]; mp->verts[j].modulate[2] = mp->color[2]; } } - - cgi_R_AddPolyToScene( mp->markShader, mp->poly.numVerts, mp->verts ); + cgi_R_AddPolyToScene(mp->markShader, mp->poly.numVerts, mp->verts); } } - diff --git a/codeJK2/cgame/cg_players.cpp b/codeJK2/cgame/cg_players.cpp index 904aea6663..b40ae3840c 100644 --- a/codeJK2/cgame/cg_players.cpp +++ b/codeJK2/cgame/cg_players.cpp @@ -24,18 +24,17 @@ along with this program; if not, see . #include "cg_local.h" #include "../game/g_local.h" #include "../game/b_local.h" -#define CG_PLAYERS_CPP +#define CG_PLAYERS_CPP #include "cg_media.h" #include "FxScheduler.h" #include "../game/ghoul2_shared.h" #include "../game/anims.h" #include "../game/wp_saber.h" -#define LOOK_SWING_SCALE 0.5 +#define LOOK_SWING_SCALE 0.5 #include "animtable.h" - /* player entities generate a great deal of information from implicit ques @@ -43,176 +42,92 @@ taken from the entityState_t */ -qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *headModelName, const char *headSkinName, - const char *torsoModelName, const char *torsoSkinName, - const char *legsModelName, const char *legsSkinName ); - -void CG_PlayerAnimSounds( int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum ); -extern void BG_G2SetBoneAngles( centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, qhandle_t *modelList ); -extern void FX_BorgDeathSparkParticles( vec3_t origin, vec3_t angles, vec3_t vel, vec3_t user ); -extern int PM_GetTurnAnim( gentity_t *gent, int anim ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InRoll( playerState_t *ps ); - -//Basic set of custom sounds that everyone needs -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customBasicSoundNames[MAX_CUSTOM_BASIC_SOUNDS] = -{ - "*death1.wav", - "*death2.wav", - "*death3.wav", - "*jump1.wav", - "*pain25.wav", - "*pain50.wav", - "*pain75.wav", - "*pain100.wav", - "*gurp1.wav", - "*gurp2.wav", - "*drown.wav", - "*gasp.wav", - "*land1.wav", - "*falling1.wav", +qboolean CG_RegisterClientModelname(clientInfo_t *ci, const char *headModelName, const char *headSkinName, const char *torsoModelName, + const char *torsoSkinName, const char *legsModelName, const char *legsSkinName); + +void CG_PlayerAnimSounds(int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum); +extern void BG_G2SetBoneAngles(centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList); +extern void FX_BorgDeathSparkParticles(vec3_t origin, vec3_t angles, vec3_t vel, vec3_t user); +extern int PM_GetTurnAnim(gentity_t *gent, int anim); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InRoll(playerState_t *ps); + +// Basic set of custom sounds that everyone needs +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customBasicSoundNames[MAX_CUSTOM_BASIC_SOUNDS] = { + "*death1.wav", "*death2.wav", "*death3.wav", "*jump1.wav", "*pain25.wav", "*pain50.wav", "*pain75.wav", + "*pain100.wav", "*gurp1.wav", "*gurp2.wav", "*drown.wav", "*gasp.wav", "*land1.wav", "*falling1.wav", }; -//Used as a supplement to the basic set for enemies and hazard team -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = -{ - "*anger1.wav", //Say when acquire an enemy when didn't have one before - "*anger2.wav", - "*anger3.wav", - "*victory1.wav", //Say when killed an enemy - "*victory2.wav", - "*victory3.wav", - "*confuse1.wav", //Say when confused - "*confuse2.wav", - "*confuse3.wav", - "*pushed1.wav", //Say when force-pushed - "*pushed2.wav", - "*pushed3.wav", - "*choke1.wav", - "*choke2.wav", - "*choke3.wav", - "*ffwarn.wav", - "*ffturn.wav", +// Used as a supplement to the basic set for enemies and hazard team +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = { + "*anger1.wav", // Say when acquire an enemy when didn't have one before + "*anger2.wav", "*anger3.wav", + "*victory1.wav", // Say when killed an enemy + "*victory2.wav", "*victory3.wav", + "*confuse1.wav", // Say when confused + "*confuse2.wav", "*confuse3.wav", + "*pushed1.wav", // Say when force-pushed + "*pushed2.wav", "*pushed3.wav", "*choke1.wav", "*choke2.wav", "*choke3.wav", "*ffwarn.wav", "*ffturn.wav", }; -//Used as a supplement to the basic set for stormtroopers -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = -{ - "*chase1.wav", - "*chase2.wav", - "*chase3.wav", - "*cover1.wav", - "*cover2.wav", - "*cover3.wav", - "*cover4.wav", - "*cover5.wav", - "*detected1.wav", - "*detected2.wav", - "*detected3.wav", - "*detected4.wav", - "*detected5.wav", - "*lost1.wav", - "*outflank1.wav", - "*outflank2.wav", - "*escaping1.wav", - "*escaping2.wav", - "*escaping3.wav", - "*giveup1.wav", - "*giveup2.wav", - "*giveup3.wav", - "*giveup4.wav", - "*look1.wav", - "*look2.wav", - "*sight1.wav", - "*sight2.wav", - "*sight3.wav", - "*sound1.wav", - "*sound2.wav", - "*sound3.wav", - "*suspicious1.wav", - "*suspicious2.wav", - "*suspicious3.wav", - "*suspicious4.wav", - "*suspicious5.wav", +// Used as a supplement to the basic set for stormtroopers +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = { + "*chase1.wav", "*chase2.wav", "*chase3.wav", "*cover1.wav", "*cover2.wav", "*cover3.wav", "*cover4.wav", "*cover5.wav", + "*detected1.wav", "*detected2.wav", "*detected3.wav", "*detected4.wav", "*detected5.wav", "*lost1.wav", "*outflank1.wav", "*outflank2.wav", + "*escaping1.wav", "*escaping2.wav", "*escaping3.wav", "*giveup1.wav", "*giveup2.wav", "*giveup3.wav", "*giveup4.wav", "*look1.wav", + "*look2.wav", "*sight1.wav", "*sight2.wav", "*sight3.wav", "*sound1.wav", "*sound2.wav", "*sound3.wav", "*suspicious1.wav", + "*suspicious2.wav", "*suspicious3.wav", "*suspicious4.wav", "*suspicious5.wav", }; -//Used as a supplement to the basic set for jedi -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = -{ - "*combat1.wav", - "*combat2.wav", - "*combat3.wav", - "*jdetected1.wav", - "*jdetected2.wav", - "*jdetected3.wav", - "*taunt1.wav", - "*taunt2.wav", - "*taunt3.wav", - "*jchase1.wav", - "*jchase2.wav", - "*jchase3.wav", - "*jlost1.wav", - "*jlost2.wav", - "*jlost3.wav", - "*deflect1.wav", - "*deflect2.wav", - "*deflect3.wav", - "*gloat1.wav", - "*gloat2.wav", - "*gloat3.wav", - "*pushfail.wav", +// Used as a supplement to the basic set for jedi +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = { + "*combat1.wav", "*combat2.wav", "*combat3.wav", "*jdetected1.wav", "*jdetected2.wav", "*jdetected3.wav", "*taunt1.wav", "*taunt2.wav", + "*taunt3.wav", "*jchase1.wav", "*jchase2.wav", "*jchase3.wav", "*jlost1.wav", "*jlost2.wav", "*jlost3.wav", "*deflect1.wav", + "*deflect2.wav", "*deflect3.wav", "*gloat1.wav", "*gloat2.wav", "*gloat3.wav", "*pushfail.wav", }; - // done at registration time only... // // cuts down on sound-variant registration for low end machines, // eg *gloat1.wav (plus...2,...3) can be capped to all be just *gloat1.wav // -static const char *GetCustomSound_VariantCapped(const char *ppsTable[], int iEntryNum, qboolean bForceVariant1) -{ - extern vmCvar_t cg_VariantSoundCap; +static const char *GetCustomSound_VariantCapped(const char *ppsTable[], int iEntryNum, qboolean bForceVariant1) { + extern vmCvar_t cg_VariantSoundCap; -// const int iVariantCap = 2; // test + // const int iVariantCap = 2; // test const int &iVariantCap = cg_VariantSoundCap.integer; - if (iVariantCap || bForceVariant1) - { - char *p = (char *)strchr(ppsTable[iEntryNum],'.'); - if (p && p-2 > ppsTable[iEntryNum] && isdigit(p[-1]) && !isdigit(p[-2])) - { - int iThisVariant = p[-1]-'0'; + if (iVariantCap || bForceVariant1) { + char *p = (char *)strchr(ppsTable[iEntryNum], '.'); + if (p && p - 2 > ppsTable[iEntryNum] && isdigit(p[-1]) && !isdigit(p[-2])) { + int iThisVariant = p[-1] - '0'; - if (iThisVariant > iVariantCap || bForceVariant1) - { + if (iThisVariant > iVariantCap || bForceVariant1) { // ok, let's not load this variant, so pick a random one below the cap value... // - for (int i=0; i<2; i++) // 1st pass, choose random, 2nd pass (if random not in list), choose xxx1, else fall through... + for (int i = 0; i < 2; i++) // 1st pass, choose random, 2nd pass (if random not in list), choose xxx1, else fall through... { char sName[MAX_QPATH]; Q_strncpyz(sName, ppsTable[iEntryNum], sizeof(sName)); - p = strchr(sName,'.'); - if (p) - { + p = strchr(sName, '.'); + if (p) { *p = '\0'; - sName[strlen(sName)-1] = '\0'; // strip the digit + sName[strlen(sName) - 1] = '\0'; // strip the digit - int iRandom = bForceVariant1 ? 1 : (!i ? Q_irand(1,iVariantCap) : 1); + int iRandom = bForceVariant1 ? 1 : (!i ? Q_irand(1, iVariantCap) : 1); - strcat(sName,va("%d.wav",iRandom)); + strcat(sName, va("%d.wav", iRandom)); // does this exist in the entries before the original one?... // - for (int iScanNum=0; iScanNumclientInfo; + // ci = &g_entities[0].client->clientInfo; ci = &cgs.clientinfo[entityNum]; - } - else - { + } else { ci = &g_entities[entityNum].client->clientInfo; } - //FIXME: if the sound you want to play could not be found, pick another from the same - //general grouping? ie: if you want ff_2c and there is none, try ff_2b or ff_2a... - switch ( customSoundSet ) - { + // FIXME: if the sound you want to play could not be found, pick another from the same + // general grouping? ie: if you want ff_2c and there is none, try ff_2b or ff_2a... + switch (customSoundSet) { case CS_BASIC: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customBasicSoundNames[i] ) ) - { + if (ci) { + for (i = 0; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customBasicSoundNames[i])) { return ci->sounds[i]; } } @@ -311,92 +209,72 @@ static sfxHandle_t CG_CustomSound( int entityNum, const char *soundName, int cus break; case CS_COMBAT: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customCombatSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customCombatSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS]; } } } break; case CS_EXTRA: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customExtraSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customExtraSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS]; } } } break; case CS_JEDI: // There should always be a clientInfo structure if there is a client, but just make sure... - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customJediSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS]; + if (ci) { + for (i = 0; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customJediSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS]; } } } break; default: - //no set specified, search all - if ( ci ) - { - for ( i = 0 ; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customBasicSoundNames[i] ) ) - { + // no set specified, search all + if (ci) { + for (i = 0; i < MAX_CUSTOM_BASIC_SOUNDS && cg_customBasicSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customBasicSoundNames[i])) { return ci->sounds[i]; } } - for ( i = 0 ; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customCombatSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_COMBAT_SOUNDS && cg_customCombatSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customCombatSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS]; } } - for ( i = 0 ; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customExtraSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_EXTRA_SOUNDS && cg_customExtraSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customExtraSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS]; } } - for ( i = 0 ; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i] ; i++ ) - { - if ( !Q_stricmp( soundName, cg_customJediSoundNames[i] ) ) - { - return ci->sounds[i+MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS]; + for (i = 0; i < MAX_CUSTOM_JEDI_SOUNDS && cg_customJediSoundNames[i]; i++) { + if (!Q_stricmp(soundName, cg_customJediSoundNames[i])) { + return ci->sounds[i + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS]; } } } break; } - CG_Error( "Unknown custom sound: %s", soundName ); + CG_Error("Unknown custom sound: %s", soundName); return 0; } -void CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ) -{ - sfxHandle_t soundIndex = CG_CustomSound( entityNum, soundName, customSoundSet ); - if ( !soundIndex ) - { +void CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet) { + sfxHandle_t soundIndex = CG_CustomSound(entityNum, soundName, customSoundSet); + if (!soundIndex) { return; } - cgi_S_StartSound( origin, entityNum, channel, soundIndex ); + cgi_S_StartSound(origin, entityNum, channel, soundIndex); } /* ====================== @@ -405,75 +283,66 @@ CG_NewClientinfo For player only, NPCs get them through NPC_stats and G_ModelIndex ====================== */ -void CG_NewClientinfo( int clientNum ) -{ +void CG_NewClientinfo(int clientNum) { clientInfo_t *ci; - const char *configstring; - const char *v; -// const char *s; -// int i; + const char *configstring; + const char *v; + // const char *s; + // int i; - configstring = CG_ConfigString( clientNum + CS_PLAYERS ); + configstring = CG_ConfigString(clientNum + CS_PLAYERS); - if ( !configstring[0] ) - { - return; // player just left + if (!configstring[0]) { + return; // player just left } - //ci = &cgs.clientinfo[clientNum]; - if ( !(g_entities[clientNum].client) ) - { + // ci = &cgs.clientinfo[clientNum]; + if (!(g_entities[clientNum].client)) { return; } ci = &g_entities[clientNum].client->clientInfo; // isolate the player's name v = Info_ValueForKey(configstring, "n"); - Q_strncpyz( ci->name, v, sizeof( ci->name ) ); + Q_strncpyz(ci->name, v, sizeof(ci->name)); // handicap - v = Info_ValueForKey( configstring, "hc" ); - ci->handicap = atoi( v ); + v = Info_ValueForKey(configstring, "hc"); + ci->handicap = atoi(v); // team - v = Info_ValueForKey( configstring, "t" ); - ci->team = (team_t) atoi( v ); + v = Info_ValueForKey(configstring, "t"); + ci->team = (team_t)atoi(v); // legsModel - v = Info_ValueForKey( configstring, "legsModel" ); + v = Info_ValueForKey(configstring, "legsModel"); - Q_strncpyz(g_entities[clientNum].client->renderInfo.legsModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.legsModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.legsModelName, v, sizeof(g_entities[clientNum].client->renderInfo.legsModelName)); // torsoModel - v = Info_ValueForKey( configstring, "torsoModel" ); + v = Info_ValueForKey(configstring, "torsoModel"); - Q_strncpyz(g_entities[clientNum].client->renderInfo.torsoModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.torsoModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.torsoModelName, v, sizeof(g_entities[clientNum].client->renderInfo.torsoModelName)); // headModel - v = Info_ValueForKey( configstring, "headModel" ); + v = Info_ValueForKey(configstring, "headModel"); - Q_strncpyz(g_entities[clientNum].client->renderInfo.headModelName, v, - sizeof( g_entities[clientNum].client->renderInfo.headModelName)); + Q_strncpyz(g_entities[clientNum].client->renderInfo.headModelName, v, sizeof(g_entities[clientNum].client->renderInfo.headModelName)); // sounds - cvar_t *sex = gi.cvar( "sex", "male", 0 ); - if ( Q_stricmp("female", sex->string ) == 0 ) - { + cvar_t *sex = gi.cvar("sex", "male", 0); + if (Q_stricmp("female", sex->string) == 0) { ci->customBasicSoundDir = "kyla"; - } - else - { + } else { ci->customBasicSoundDir = "kyle"; } - //player uses only the basic custom sound set, not the combat or extra + // player uses only the basic custom sound set, not the combat or extra CG_RegisterCustomSounds(ci, - 0, // int iSoundEntryBase, - MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, - cg_customBasicSoundNames, // const char *ppsTable[], - ci->customBasicSoundDir // const char *psDir - ); + 0, // int iSoundEntryBase, + MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, + cg_customBasicSoundNames, // const char *ppsTable[], + ci->customBasicSoundDir // const char *psDir + ); ci->infoValid = qfalse; } @@ -481,51 +350,46 @@ void CG_NewClientinfo( int clientNum ) /* CG_RegisterNPCCustomSounds */ -void CG_RegisterNPCCustomSounds( clientInfo_t *ci ) -{ -// const char *s; -// int i; +void CG_RegisterNPCCustomSounds(clientInfo_t *ci) { + // const char *s; + // int i; // sounds - if ( ci->customBasicSoundDir && ci->customBasicSoundDir[0] ) - { + if (ci->customBasicSoundDir && ci->customBasicSoundDir[0]) { CG_RegisterCustomSounds(ci, - 0, // int iSoundEntryBase, - MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, - cg_customBasicSoundNames, // const char *ppsTable[], - ci->customBasicSoundDir // const char *psDir - ); + 0, // int iSoundEntryBase, + MAX_CUSTOM_BASIC_SOUNDS, // int iTableEntries, + cg_customBasicSoundNames, // const char *ppsTable[], + ci->customBasicSoundDir // const char *psDir + ); } - if ( ci->customCombatSoundDir && ci->customCombatSoundDir[0] ) - { + if (ci->customCombatSoundDir && ci->customCombatSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, - cg_customCombatSoundNames, // const char *ppsTable[], - ci->customCombatSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_COMBAT_SOUNDS, // int iTableEntries, + cg_customCombatSoundNames, // const char *ppsTable[], + ci->customCombatSoundDir // const char *psDir + ); } - if ( ci->customExtraSoundDir && ci->customExtraSoundDir[0] ) - { + if (ci->customExtraSoundDir && ci->customExtraSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_EXTRA_SOUNDS, // int iTableEntries, - cg_customExtraSoundNames, // const char *ppsTable[], - ci->customExtraSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_EXTRA_SOUNDS, // int iTableEntries, + cg_customExtraSoundNames, // const char *ppsTable[], + ci->customExtraSoundDir // const char *psDir + ); } - if ( ci->customJediSoundDir && ci->customJediSoundDir[0] ) - { + if (ci->customJediSoundDir && ci->customJediSoundDir[0]) { CG_RegisterCustomSounds(ci, - MAX_CUSTOM_BASIC_SOUNDS+MAX_CUSTOM_COMBAT_SOUNDS+MAX_CUSTOM_EXTRA_SOUNDS, // int iSoundEntryBase, - MAX_CUSTOM_JEDI_SOUNDS, // int iTableEntries, - cg_customJediSoundNames, // const char *ppsTable[], - ci->customJediSoundDir // const char *psDir - ); + MAX_CUSTOM_BASIC_SOUNDS + MAX_CUSTOM_COMBAT_SOUNDS + MAX_CUSTOM_EXTRA_SOUNDS, // int iSoundEntryBase, + MAX_CUSTOM_JEDI_SOUNDS, // int iTableEntries, + cg_customJediSoundNames, // const char *ppsTable[], + ci->customJediSoundDir // const char *psDir + ); } } @@ -538,10 +402,8 @@ void CG_RegisterNPCEffects( team_t team ) of NPC's spawn, death and other miscellaneous effects. NOT WEAPON EFFECTS, as those are taken care of in CG_RegisterWeapon */ -void CG_RegisterNPCEffects( team_t team ) -{ - switch( team ) - { +void CG_RegisterNPCEffects(team_t team) { + switch (team) { case TEAM_ENEMY: break; @@ -565,83 +427,71 @@ PLAYER ANIMATION ============================================================================= */ -qboolean ValidAnimFileIndex ( int index ) -{ - if ( index < 0 || index >= level.numKnownAnimFileSets ) - { - Com_Printf( S_COLOR_RED "Bad animFileIndex: %d\n", index ); +qboolean ValidAnimFileIndex(int index) { + if (index < 0 || index >= level.numKnownAnimFileSets) { + Com_Printf(S_COLOR_RED "Bad animFileIndex: %d\n", index); return qfalse; } return qtrue; } - - -void ParseAnimationSndBlock(const char *asb_filename, animsounds_t *animSounds, animation_t *animations, int *i,const char **text_p) -{ - const char *token; - char soundString[MAX_QPATH]; - int lowestVal, highestVal; - int animNum, num, n; +void ParseAnimationSndBlock(const char *asb_filename, animsounds_t *animSounds, animation_t *animations, int *i, const char **text_p) { + const char *token; + char soundString[MAX_QPATH]; + int lowestVal, highestVal; + int animNum, num, n; // get past starting bracket - while(1) - { - token = COM_Parse( text_p ); - if ( !Q_stricmp( token, "{" ) ) - { + while (1) { + token = COM_Parse(text_p); + if (!Q_stricmp(token, "{")) { break; } } - animSounds += *i; + animSounds += *i; // read information for each frame - while ( 1 ) - { - if (*i >= MAX_ANIM_SOUNDS) - { - CG_Error( "ParseAnimationSndBlock: animation number >= MAX_ANIM_SOUNDS(%i)", MAX_ANIM_SOUNDS ); + while (1) { + if (*i >= MAX_ANIM_SOUNDS) { + CG_Error("ParseAnimationSndBlock: animation number >= MAX_ANIM_SOUNDS(%i)", MAX_ANIM_SOUNDS); } // Get base frame of sequence - token = COM_Parse( text_p ); - if ( !token || !token[0]) - { + token = COM_Parse(text_p); + if (!token || !token[0]) { break; } - if ( !Q_stricmp( token, "}" ) ) // At end of block + if (!Q_stricmp(token, "}")) // At end of block { break; } - //Compare to same table as animations used + // Compare to same table as animations used // so we don't have to use actual numbers for animation first frames, // just need offsets. - //This way when animation numbers change, this table won't have to be updated, + // This way when animation numbers change, this table won't have to be updated, // at least not much. animNum = GetIDForString(animTable, token); - if(animNum == -1) - {//Unrecognized ANIM ENUM name, or we're skipping this line, keep going till you get a good one - Com_Printf(S_COLOR_YELLOW"WARNING: Unknown token %s in animSound file %s\n", token, asb_filename ); + if (animNum == -1) { // Unrecognized ANIM ENUM name, or we're skipping this line, keep going till you get a good one + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown token %s in animSound file %s\n", token, asb_filename); continue; } - if ( animations[animNum].numFrames == 0 ) - {//we don't use this anim - //Com_Printf(S_COLOR_YELLOW"WARNING: %s animsounds.cfg: anim %s not used by this model\n", filename, token); + if (animations[animNum].numFrames == 0) { // we don't use this anim + // Com_Printf(S_COLOR_YELLOW"WARNING: %s animsounds.cfg: anim %s not used by this model\n", filename, token); // Get offset to frame within sequence - token = COM_Parse( text_p ); - //get soundstring - token = COM_Parse( text_p ); - //get lowest value - token = COM_Parse( text_p ); - //get highest value - token = COM_Parse( text_p ); - //get probability - token = COM_Parse( text_p ); + token = COM_Parse(text_p); + // get soundstring + token = COM_Parse(text_p); + // get lowest value + token = COM_Parse(text_p); + // get highest value + token = COM_Parse(text_p); + // get probability + token = COM_Parse(text_p); continue; } @@ -649,70 +499,59 @@ void ParseAnimationSndBlock(const char *asb_filename, animsounds_t *animSounds, animSounds->keyFrame = animations[animNum].firstFrame; // Get offset to frame within sequence - token = COM_Parse( text_p ); - if ( !token ) - { + token = COM_Parse(text_p); + if (!token) { break; } - animSounds->keyFrame += atoi( token ); + animSounds->keyFrame += atoi(token); - //get soundstring - token = COM_Parse( text_p ); - if ( !token ) - { + // get soundstring + token = COM_Parse(text_p); + if (!token) { break; } Q_strncpyz(soundString, token, sizeof(soundString)); - //get lowest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get lowest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - lowestVal = atoi( token ); + lowestVal = atoi(token); - //get highest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get highest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - highestVal = atoi( token ); + highestVal = atoi(token); - //Now precache all the sounds - //NOTE: If we can be assured sequential handles, we can store sound indices + // Now precache all the sounds + // NOTE: If we can be assured sequential handles, we can store sound indices // instead of strings, unfortunately, if these sounds were previously // registered, we cannot be guaranteed sequential indices. Thus an array - if(lowestVal && highestVal) - { - for ( n = lowestVal, num = 0; n <= highestVal && num < MAX_RANDOM_ANIMSOUNDS; n++, num++ ) - { - animSounds->soundIndex[num] = G_SoundIndex( va( soundString, n ) );//cgi_S_RegisterSound + if (lowestVal && highestVal) { + for (n = lowestVal, num = 0; n <= highestVal && num < MAX_RANDOM_ANIMSOUNDS; n++, num++) { + animSounds->soundIndex[num] = G_SoundIndex(va(soundString, n)); // cgi_S_RegisterSound } animSounds->numRandomAnimSounds = num - 1; - } - else - { - animSounds->soundIndex[0] = G_SoundIndex( va( soundString ) );//cgi_S_RegisterSound + } else { + animSounds->soundIndex[0] = G_SoundIndex(va(soundString)); // cgi_S_RegisterSound #ifndef FINAL_BUILD - if ( !animSounds->soundIndex[0] ) - {//couldn't register it - file not found - Com_Printf( S_COLOR_RED "ParseAnimationSndBlock: sound %s does not exist (animsound.cfg %s)!\n", soundString, asb_filename ); + if (!animSounds->soundIndex[0]) { // couldn't register it - file not found + Com_Printf(S_COLOR_RED "ParseAnimationSndBlock: sound %s does not exist (animsound.cfg %s)!\n", soundString, asb_filename); } #endif animSounds->numRandomAnimSounds = 0; } - - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animSounds->probability = atoi( token ); + animSounds->probability = atoi(token); ++animSounds; ++*i; } @@ -725,10 +564,9 @@ CG_ClearAnimSndCache resets all the soundcache so that a vid restart will recache them ====================== */ -void CG_ClearAnimSndCache( void ) -{ +void CG_ClearAnimSndCache(void) { int i; - for (i=0; i < level.numKnownAnimFileSets; i++) { + for (i = 0; i < level.numKnownAnimFileSets; i++) { level.knownAnimFileSets[i].soundsCached = qfalse; } } @@ -744,119 +582,108 @@ This file's presence is not required ====================== */ -void CG_ParseAnimationSndFile( const char *as_filename, int animFileIndex ) -{ - const char *text_p; - int len; - const char *token; - char text[20000]; - char sfilename[MAX_QPATH]; - fileHandle_t f; - int i, j, upper_i, lower_i; +void CG_ParseAnimationSndFile(const char *as_filename, int animFileIndex) { + const char *text_p; + int len; + const char *token; + char text[20000]; + char sfilename[MAX_QPATH]; + fileHandle_t f; + int i, j, upper_i, lower_i; assert(animFileIndex < MAX_ANIM_FILES); - animsounds_t *legsAnimSnds = level.knownAnimFileSets[animFileIndex].legsAnimSnds; - animsounds_t *torsoAnimSnds = level.knownAnimFileSets[animFileIndex].torsoAnimSnds; - animation_t *animations = level.knownAnimFileSets[animFileIndex].animations; + animsounds_t *legsAnimSnds = level.knownAnimFileSets[animFileIndex].legsAnimSnds; + animsounds_t *torsoAnimSnds = level.knownAnimFileSets[animFileIndex].torsoAnimSnds; + animation_t *animations = level.knownAnimFileSets[animFileIndex].animations; - if ( level.knownAnimFileSets[animFileIndex].soundsCached ) - {//already cached this one + if (level.knownAnimFileSets[animFileIndex].soundsCached) { // already cached this one return; } - //Mark this anim set so that we know we tried to load he sounds, don't care if the load failed + // Mark this anim set so that we know we tried to load he sounds, don't care if the load failed level.knownAnimFileSets[animFileIndex].soundsCached = qtrue; // Load and parse animSounds.cfg file - Com_sprintf( sfilename, sizeof( sfilename ), "models/players/%s/animsounds.cfg", as_filename ); + Com_sprintf(sfilename, sizeof(sfilename), "models/players/%s/animsounds.cfg", as_filename); - //initialize anim sound array - for(i = 0; i < MAX_ANIM_SOUNDS; i++) - { + // initialize anim sound array + for (i = 0; i < MAX_ANIM_SOUNDS; i++) { torsoAnimSnds[i].numRandomAnimSounds = 0; legsAnimSnds[i].numRandomAnimSounds = 0; - for(j = 0; j < MAX_RANDOM_ANIMSOUNDS; j++) - { + for (j = 0; j < MAX_RANDOM_ANIMSOUNDS; j++) { torsoAnimSnds[i].soundIndex[j] = -1; legsAnimSnds[i].soundIndex[j] = -1; } } // load the file - len = cgi_FS_FOpenFile( sfilename, &f, FS_READ ); - if ( len <= 0 ) - {//no file + len = cgi_FS_FOpenFile(sfilename, &f, FS_READ); + if (len <= 0) { // no file return; } - if ( len >= (int)sizeof( text ) - 1 ) - { - cgi_FS_FCloseFile( f ); - CG_Printf( "File %s too long\n", sfilename ); + if (len >= (int)sizeof(text) - 1) { + cgi_FS_FCloseFile(f); + CG_Printf("File %s too long\n", sfilename); return; } - cgi_FS_Read( text, len, f ); + cgi_FS_Read(text, len, f); text[len] = 0; - cgi_FS_FCloseFile( f ); + cgi_FS_FCloseFile(f); // parse the text text_p = text; - upper_i =0; - lower_i =0; + upper_i = 0; + lower_i = 0; // read information for batches of sounds (UPPER or LOWER) COM_BeginParseSession(); - while ( 1 ) - { + while (1) { // Get base frame of sequence - token = COM_Parse( &text_p ); - if ( !token || !token[0] ) - { + token = COM_Parse(&text_p); + if (!token || !token[0]) { break; } - if ( !Q_stricmp(token,"UPPERSOUNDS") ) // A batch of upper sounds + if (!Q_stricmp(token, "UPPERSOUNDS")) // A batch of upper sounds { - ParseAnimationSndBlock( as_filename, torsoAnimSnds, animations, &upper_i, &text_p ); + ParseAnimationSndBlock(as_filename, torsoAnimSnds, animations, &upper_i, &text_p); } - else if ( !Q_stricmp(token,"LOWERSOUNDS") ) // A batch of lower sounds + else if (!Q_stricmp(token, "LOWERSOUNDS")) // A batch of lower sounds { - ParseAnimationSndBlock( as_filename, legsAnimSnds, animations, &lower_i, &text_p ); + ParseAnimationSndBlock(as_filename, legsAnimSnds, animations, &lower_i, &text_p); } } - COM_EndParseSession( ); + COM_EndParseSession(); } /* =============== CG_SetLerpFrameAnimation =============== */ -void CG_SetLerpFrameAnimation( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation ) -{ - animation_t *anim; +void CG_SetLerpFrameAnimation(clientInfo_t *ci, lerpFrame_t *lf, int newAnimation) { + animation_t *anim; - if ( newAnimation < 0 || newAnimation >= MAX_ANIMATIONS ) - { + if (newAnimation < 0 || newAnimation >= MAX_ANIMATIONS) { #ifdef FINAL_BUILD newAnimation = 0; #else - CG_Error( "Bad animation number: %i", newAnimation ); + CG_Error("Bad animation number: %i", newAnimation); #endif } lf->animationNumber = newAnimation; - if ( !ValidAnimFileIndex( ci->animFileIndex ) ) - { + if (!ValidAnimFileIndex(ci->animFileIndex)) { #ifdef FINAL_BUILD ci->animFileIndex = 0; #else - CG_Error( "Bad animFileIndex: %i", ci->animFileIndex ); + CG_Error("Bad animFileIndex: %i", ci->animFileIndex); #endif } - anim = &level.knownAnimFileSets[ci->animFileIndex].animations[ newAnimation ]; + anim = &level.knownAnimFileSets[ci->animFileIndex].animations[newAnimation]; lf->animation = anim; lf->animationTime = lf->frameTime + anim->initialLerp; @@ -870,40 +697,36 @@ Sets cg.snap, cg.oldFrame, and cg.backlerp cg.time should be between oldFrameTime and frameTime after exit =============== */ -qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float fpsMod, int entNum ) { - int f, animFrameTime; - animation_t *anim; - qboolean newFrame = qfalse; +qboolean CG_RunLerpFrame(clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float fpsMod, int entNum) { + int f, animFrameTime; + animation_t *anim; + qboolean newFrame = qfalse; - if(fpsMod > 2 || fpsMod < 0.5) - {//should have been set right + if (fpsMod > 2 || fpsMod < 0.5) { // should have been set right fpsMod = 1.0f; } // debugging tool to get no animations - if ( cg_animSpeed.integer == 0 ) - { + if (cg_animSpeed.integer == 0) { lf->oldFrame = lf->frame = lf->backlerp = 0; return qfalse; } // see if the animation sequence is switching - //FIXME: allow multiple-frame overlapped lerping between sequences? - Possibly last 3 of last seq and first 3 of next seq? - if ( newAnimation != lf->animationNumber || !lf->animation ) - { - CG_SetLerpFrameAnimation( ci, lf, newAnimation ); + // FIXME: allow multiple-frame overlapped lerping between sequences? - Possibly last 3 of last seq and first 3 of next seq? + if (newAnimation != lf->animationNumber || !lf->animation) { + CG_SetLerpFrameAnimation(ci, lf, newAnimation); } // if we have passed the current frame, move it to // oldFrame and calculate a new frame - if ( cg.time >= lf->frameTime ) - { + if (cg.time >= lf->frameTime) { lf->oldFrame = lf->frame; lf->oldFrameTime = lf->frameTime; // get the next frame based on the animation anim = lf->animation; - //Do we need to speed up or slow down the anim? + // Do we need to speed up or slow down the anim? /*if(fpsMod != 1.0) {//Note! despite it's name, a higher fpsMod slows down the anim, a lower one speeds it up animFrameTime = ceil(lf->frameTime * fpsMod); @@ -912,44 +735,33 @@ qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, f { animFrameTime = fabs((double)anim->frameLerp); - //special hack for player to ensure quick weapon change - if ( entNum == 0 ) - { - if ( lf->animationNumber == TORSO_DROPWEAP1 || lf->animationNumber == TORSO_RAISEWEAP1 ) - { + // special hack for player to ensure quick weapon change + if (entNum == 0) { + if (lf->animationNumber == TORSO_DROPWEAP1 || lf->animationNumber == TORSO_RAISEWEAP1) { animFrameTime = 50; } } } - if ( cg.time < lf->animationTime ) - { - lf->frameTime = lf->animationTime; // initial lerp - } - else - { + if (cg.time < lf->animationTime) { + lf->frameTime = lf->animationTime; // initial lerp + } else { lf->frameTime = lf->oldFrameTime + animFrameTime; } - f = ( lf->frameTime - lf->animationTime ) / animFrameTime; - if ( f >= anim->numFrames ) - {//Reached the end of the anim - //FIXME: Need to set a flag here to TASK_COMPLETE + f = (lf->frameTime - lf->animationTime) / animFrameTime; + if (f >= anim->numFrames) { // Reached the end of the anim + // FIXME: Need to set a flag here to TASK_COMPLETE f -= anim->numFrames; - if ( anim->loopFrames != -1 ) //Before 0 meant no loop + if (anim->loopFrames != -1) // Before 0 meant no loop { - if(anim->numFrames - anim->loopFrames == 0) - { + if (anim->numFrames - anim->loopFrames == 0) { f %= anim->numFrames; - } - else - { + } else { f %= (anim->numFrames - anim->loopFrames); } f += anim->loopFrames; - } - else - { + } else { f = anim->numFrames - 1; // the animation is stuck at the end, so it // can immediately transition to another sequence @@ -957,61 +769,47 @@ qboolean CG_RunLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, f } } - if ( anim->frameLerp < 0 ) - { + if (anim->frameLerp < 0) { lf->frame = anim->firstFrame + anim->numFrames - 1 - f; - } - else - { + } else { lf->frame = anim->firstFrame + f; } - if ( cg.time > lf->frameTime ) - { + if (cg.time > lf->frameTime) { lf->frameTime = cg.time; } newFrame = qtrue; } - if ( lf->frameTime > cg.time + 200 ) - { + if (lf->frameTime > cg.time + 200) { lf->frameTime = cg.time; } - if ( lf->oldFrameTime > cg.time ) - { + if (lf->oldFrameTime > cg.time) { lf->oldFrameTime = cg.time; } // calculate current lerp value - if ( lf->frameTime == lf->oldFrameTime ) - { + if (lf->frameTime == lf->oldFrameTime) { lf->backlerp = 0; - } - else - { - lf->backlerp = 1.0 - (float)( cg.time - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime ); + } else { + lf->backlerp = 1.0 - (float)(cg.time - lf->oldFrameTime) / (lf->frameTime - lf->oldFrameTime); } return newFrame; } - /* =============== CG_ClearLerpFrame =============== */ -void CG_ClearLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int animationNumber ) -{ +void CG_ClearLerpFrame(clientInfo_t *ci, lerpFrame_t *lf, int animationNumber) { lf->frameTime = lf->oldFrameTime = cg.time; - CG_SetLerpFrameAnimation( ci, lf, animationNumber ); - if ( lf->animation->frameLerp < 0 ) - {//Plays backwards + CG_SetLerpFrameAnimation(ci, lf, animationNumber); + if (lf->animation->frameLerp < 0) { // Plays backwards lf->oldFrame = lf->frame = (lf->animation->firstFrame + lf->animation->numFrames); - } - else - { + } else { lf->oldFrame = lf->frame = lf->animation->firstFrame; } } @@ -1021,199 +819,151 @@ void CG_ClearLerpFrame( clientInfo_t *ci, lerpFrame_t *lf, int animationNumber ) CG_PlayerAnimation =============== */ -void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, - int *torsoOld, int *torso, float *torsoBackLerp ) { - clientInfo_t *ci; - int legsAnim; - int legsTurnAnim = -1; - qboolean newLegsFrame = qfalse; - qboolean newTorsoFrame = qfalse; - - if ( cg_noPlayerAnims.integer ) { +void CG_PlayerAnimation(centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, int *torsoOld, int *torso, float *torsoBackLerp) { + clientInfo_t *ci; + int legsAnim; + int legsTurnAnim = -1; + qboolean newLegsFrame = qfalse; + qboolean newTorsoFrame = qfalse; + + if (cg_noPlayerAnims.integer) { *legsOld = *legs = *torsoOld = *torso = 0; return; } ci = ¢->gent->client->clientInfo; - //Changed this from cent->currentState.legsAnim to cent->gent->client->ps.legsAnim because it was screwing up our timers when we've just changed anims while turning + // Changed this from cent->currentState.legsAnim to cent->gent->client->ps.legsAnim because it was screwing up our timers when we've just changed anims + // while turning legsAnim = cent->gent->client->ps.legsAnim; // do the shuffle turn frames locally (MAN this is an Fugly-ass hack!) - if ( cent->pe.legs.yawing ) - { - legsTurnAnim = PM_GetTurnAnim( cent->gent, legsAnim ); + if (cent->pe.legs.yawing) { + legsTurnAnim = PM_GetTurnAnim(cent->gent, legsAnim); } - if ( legsTurnAnim != -1 ) - { - newLegsFrame = CG_RunLerpFrame( ci, ¢->pe.legs, legsTurnAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number ); - //This line doesn't seem to serve any useful purpose, rather it - //breaks things since any task waiting for a lower anim to complete - //never will finish if this happens!!! - //cent->gent->client->ps.legsAnimTimer = 0; - } - else - { - newLegsFrame = CG_RunLerpFrame( ci, ¢->pe.legs, legsAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); + if (legsTurnAnim != -1) { + newLegsFrame = CG_RunLerpFrame(ci, ¢->pe.legs, legsTurnAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); + // This line doesn't seem to serve any useful purpose, rather it + // breaks things since any task waiting for a lower anim to complete + // never will finish if this happens!!! + // cent->gent->client->ps.legsAnimTimer = 0; + } else { + newLegsFrame = CG_RunLerpFrame(ci, ¢->pe.legs, legsAnim, cent->gent->client->renderInfo.legsFpsMod, cent->gent->s.number); } *legsOld = cent->pe.legs.oldFrame; *legs = cent->pe.legs.frame; *legsBackLerp = cent->pe.legs.backlerp; - if( newLegsFrame ) - { - if ( ValidAnimFileIndex( ci->animFileIndex ) ) - { - CG_PlayerAnimSounds( ci->animFileIndex, qfalse, cent->pe.legs.frame, cent->pe.legs.frame, cent->currentState.number ); + if (newLegsFrame) { + if (ValidAnimFileIndex(ci->animFileIndex)) { + CG_PlayerAnimSounds(ci->animFileIndex, qfalse, cent->pe.legs.frame, cent->pe.legs.frame, cent->currentState.number); } } - newTorsoFrame = CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); + newTorsoFrame = CG_RunLerpFrame(ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number); *torsoOld = cent->pe.torso.oldFrame; *torso = cent->pe.torso.frame; *torsoBackLerp = cent->pe.torso.backlerp; - if( newTorsoFrame ) - { - if ( ValidAnimFileIndex( ci->animFileIndex ) ) - { - CG_PlayerAnimSounds(ci->animFileIndex, qtrue, cent->pe.torso.frame, cent->pe.torso.frame, cent->currentState.number ); + if (newTorsoFrame) { + if (ValidAnimFileIndex(ci->animFileIndex)) { + CG_PlayerAnimSounds(ci->animFileIndex, qtrue, cent->pe.torso.frame, cent->pe.torso.frame, cent->currentState.number); } } } - /* void CG_PlayerAnimSounds( int animFileIndex, qboolean torso, int oldFrame, int frame, const vec3_t org, int entNum ) play any keyframed sounds - only when start a new frame This func is called once for legs and once for torso */ -extern int PM_LegsAnimForFrame( gentity_t *ent, int legsFrame ); -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -void CG_PlayerAnimSounds( int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum ) -{ - int i; - int holdSnd = -1; - int firstFrame = 0, lastFrame = 0; - qboolean playSound = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; +extern int PM_LegsAnimForFrame(gentity_t *ent, int legsFrame); +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +void CG_PlayerAnimSounds(int animFileIndex, qboolean torso, int oldFrame, int frame, int entNum) { + int i; + int holdSnd = -1; + int firstFrame = 0, lastFrame = 0; + qboolean playSound = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; animsounds_t *animSounds = NULL; - if ( torso ) - { + if (torso) { animSounds = level.knownAnimFileSets[animFileIndex].torsoAnimSnds; - } - else - { + } else { animSounds = level.knownAnimFileSets[animFileIndex].legsAnimSnds; } - if ( fabs((double)oldFrame-frame) > 1 && cg_reliableAnimSounds.integer ) - {//given a range, see if keyFrame falls in that range + if (fabs((double)oldFrame - frame) > 1 && cg_reliableAnimSounds.integer) { // given a range, see if keyFrame falls in that range int oldAnim, anim; - if ( torso ) - { - if ( cg_reliableAnimSounds.integer > 1 ) - {//more precise, slower - oldAnim = PM_TorsoAnimForFrame( &g_entities[entNum], oldFrame ); - anim = PM_TorsoAnimForFrame( &g_entities[entNum], frame ); - } - else - {//less precise, but faster + if (torso) { + if (cg_reliableAnimSounds.integer > 1) { // more precise, slower + oldAnim = PM_TorsoAnimForFrame(&g_entities[entNum], oldFrame); + anim = PM_TorsoAnimForFrame(&g_entities[entNum], frame); + } else { // less precise, but faster oldAnim = cg_entities[entNum].currentState.torsoAnim; anim = cg_entities[entNum].nextState.torsoAnim; } - } - else - { - if ( cg_reliableAnimSounds.integer > 1 ) - {//more precise, slower - oldAnim = PM_LegsAnimForFrame( &g_entities[entNum], oldFrame ); - anim = PM_LegsAnimForFrame( &g_entities[entNum], frame ); - } - else - {//less precise, but faster + } else { + if (cg_reliableAnimSounds.integer > 1) { // more precise, slower + oldAnim = PM_LegsAnimForFrame(&g_entities[entNum], oldFrame); + anim = PM_LegsAnimForFrame(&g_entities[entNum], frame); + } else { // less precise, but faster oldAnim = cg_entities[entNum].currentState.legsAnim; anim = cg_entities[entNum].nextState.legsAnim; } } - if ( anim != oldAnim ) - {//not in same anim + if (anim != oldAnim) { // not in same anim inSameAnim = qfalse; - //FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... - } - else - {//still in same anim, check for looping anim + // FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... + } else { // still in same anim, check for looping anim inSameAnim = qtrue; animation_t *animation = &level.knownAnimFileSets[animFileIndex].animations[anim]; animBackward = (qboolean)(animation->frameLerp < 0); - if ( animation->loopFrames != -1 ) - {//a looping anim! + if (animation->loopFrames != -1) { // a looping anim! loopAnim = qtrue; firstFrame = animation->firstFrame; - lastFrame = animation->firstFrame+animation->numFrames; + lastFrame = animation->firstFrame + animation->numFrames; } } } - if ( entNum == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) - {//player in first person view does not play any keyframed sounds + if (entNum == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) + { // player in first person view does not play any keyframed sounds return; } // Check for anim sound - for (i=0;i 1 && cg_reliableAnimSounds.integer ) - {//given a range, see if keyFrame falls in that range - if ( inSameAnim ) - {//if changed anims altogether, sorry, the sound is lost - if ( fabs((double)oldFrame-animSounds[i].keyFrame) <= 3 - || fabs((double)frame-animSounds[i].keyFrame) <= 3 ) - {//must be at least close to the keyframe - if ( animBackward ) - {//animation plays backwards - if ( oldFrame > animSounds[i].keyFrame && frame < animSounds[i].keyFrame ) - {//old to new passed through keyframe + } else if (fabs((double)oldFrame - frame) > 1 && cg_reliableAnimSounds.integer) { // given a range, see if keyFrame falls in that range + if (inSameAnim) { // if changed anims altogether, sorry, the sound is lost + if (fabs((double)oldFrame - animSounds[i].keyFrame) <= 3 || + fabs((double)frame - animSounds[i].keyFrame) <= 3) { // must be at least close to the keyframe + if (animBackward) { // animation plays backwards + if (oldFrame > animSounds[i].keyFrame && frame < animSounds[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animSounds[i].keyFrame >= firstFrame && animSounds[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame > animSounds[i].keyFrame - && frame > oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animSounds[i].keyFrame >= firstFrame && animSounds[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame > animSounds[i].keyFrame && frame > oldFrame) { // old to new passed through keyframe match = qtrue; } } } - } - else - {//anim plays forwards - if ( oldFrame < animSounds[i].keyFrame && frame > animSounds[i].keyFrame ) - {//old to new passed through keyframe + } else { // anim plays forwards + if (oldFrame < animSounds[i].keyFrame && frame > animSounds[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animSounds[i].keyFrame >= firstFrame && animSounds[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame < animSounds[i].keyFrame - && frame < oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animSounds[i].keyFrame >= firstFrame && animSounds[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame < animSounds[i].keyFrame && frame < oldFrame) { // old to new passed through keyframe match = qtrue; } } @@ -1222,18 +972,15 @@ void CG_PlayerAnimSounds( int animFileIndex, qboolean torso, int oldFrame, int f } } } - if ( match ) - { + if (match) { // are there variations on the sound? - holdSnd = animSounds[i].soundIndex[ Q_irand( 0, animSounds[i].numRandomAnimSounds ) ]; + holdSnd = animSounds[i].soundIndex[Q_irand(0, animSounds[i].numRandomAnimSounds)]; // Determine probability of playing sound - if (!animSounds[i].probability) // 100% + if (!animSounds[i].probability) // 100% { playSound = qtrue; - } - else if (animSounds[i].probability > Q_irand(0, 99) ) - { + } else if (animSounds[i].probability > Q_irand(0, 99)) { playSound = qtrue; } break; @@ -1241,55 +988,47 @@ void CG_PlayerAnimSounds( int animFileIndex, qboolean torso, int oldFrame, int f } // Play sound - if (holdSnd != -1 && playSound) - { - if (holdSnd != 0) // 0 = default sound, ie file was missing + if (holdSnd != -1 && playSound) { + if (holdSnd != 0) // 0 = default sound, ie file was missing { - //FIXME: allow customSounds in here *... - if ( cgs.sound_precache[ holdSnd ] ) - { - cgi_S_StartSound( NULL, entNum, CHAN_AUTO, cgs.sound_precache[holdSnd ] ); - } - else - { + // FIXME: allow customSounds in here *... + if (cgs.sound_precache[holdSnd]) { + cgi_S_StartSound(NULL, entNum, CHAN_AUTO, cgs.sound_precache[holdSnd]); + } else { holdSnd = 0; } } - } } -void CGG2_AnimSounds( centity_t *cent ) -{ - if ( !cent || !cent->gent || !cent->gent->client) - { +void CGG2_AnimSounds(centity_t *cent) { + if (!cent || !cent->gent || !cent->gent->client) { return; } - assert(cent->gent->playerModel>=0&¢->gent->playerModelgent->ghoul2.size()); - if ( ValidAnimFileIndex( cent->gent->client->clientInfo.animFileIndex ) ) - { - int junk, curFrame=0; - float currentFrame=0, animSpeed; + assert(cent->gent->playerModel >= 0 && cent->gent->playerModel < cent->gent->ghoul2.size()); + if (ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) { + int junk, curFrame = 0; + float currentFrame = 0, animSpeed; - if (cent->gent->rootBone>=0&&gi.G2API_GetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, cg.time, ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw )) - { + if (cent->gent->rootBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->rootBone, cg.time, ¤tFrame, + &junk, &junk, &junk, &animSpeed, cgs.model_draw)) { // the above may have failed, not sure what to do about it, current frame will be zero in that case - curFrame = floor( currentFrame ); + curFrame = floor(currentFrame); } - if ( curFrame != cent->gent->client->renderInfo.legsFrame ) - { - CG_PlayerAnimSounds( cent->gent->client->clientInfo.animFileIndex, qfalse, cent->gent->client->renderInfo.legsFrame, curFrame, cent->currentState.clientNum ); + if (curFrame != cent->gent->client->renderInfo.legsFrame) { + CG_PlayerAnimSounds(cent->gent->client->clientInfo.animFileIndex, qfalse, cent->gent->client->renderInfo.legsFrame, curFrame, + cent->currentState.clientNum); } cent->gent->client->renderInfo.legsFrame = curFrame; cent->pe.legs.frame = curFrame; - if (cent->gent->lowerLumbarBone>=0&& gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw ) ) - { - curFrame = floor( currentFrame ); + if (cent->gent->lowerLumbarBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, + ¤tFrame, &junk, &junk, &junk, &animSpeed, cgs.model_draw)) { + curFrame = floor(currentFrame); } - if ( curFrame != cent->gent->client->renderInfo.torsoFrame ) - { - CG_PlayerAnimSounds( cent->gent->client->clientInfo.animFileIndex, qtrue, cent->gent->client->renderInfo.torsoFrame, curFrame, cent->currentState.clientNum ); + if (curFrame != cent->gent->client->renderInfo.torsoFrame) { + CG_PlayerAnimSounds(cent->gent->client->clientInfo.animFileIndex, qtrue, cent->gent->client->renderInfo.torsoFrame, curFrame, + cent->currentState.clientNum); } cent->gent->client->renderInfo.torsoFrame = curFrame; cent->pe.torso.frame = curFrame; @@ -1309,91 +1048,65 @@ CG_UpdateAngleClamp Turn curAngle toward destAngle at angleSpeed, but stay within clampMin and Max ================== */ -void CG_UpdateAngleClamp( float destAngle, float clampMin, float clampMax, float angleSpeed, float *curAngle, float normalAngle) -{ - float swing; - float move; - float scale; - float actualSpeed; +void CG_UpdateAngleClamp(float destAngle, float clampMin, float clampMax, float angleSpeed, float *curAngle, float normalAngle) { + float swing; + float move; + float scale; + float actualSpeed; - swing = AngleSubtract( destAngle, *curAngle ); + swing = AngleSubtract(destAngle, *curAngle); - if(swing == 0) - {//Don't have to turn + if (swing == 0) { // Don't have to turn return; } // modify the angleSpeed depending on the delta // so it doesn't seem so linear - scale = fabs( swing ); - if (swing > 0) - { - if ( swing < clampMax * 0.25 ) - {//Pretty small way to go + scale = fabs(swing); + if (swing > 0) { + if (swing < clampMax * 0.25) { // Pretty small way to go scale = 0.25; - } - else if ( swing > clampMax * 2.0 ) - {//Way out of our range + } else if (swing > clampMax * 2.0) { // Way out of our range scale = 2.0; + } else { // Scale it smoothly + scale = swing / clampMax; } - else - {//Scale it smoothly - scale = swing/clampMax; - } - } - else// if (swing < 0) + } else // if (swing < 0) { - if ( swing > clampMin * 0.25 ) - {//Pretty small way to go + if (swing > clampMin * 0.25) { // Pretty small way to go scale = 0.5; - } - else if ( swing < clampMin * 2.0 ) - {//Way out of our range + } else if (swing < clampMin * 2.0) { // Way out of our range scale = 2.0; - } - else - {//Scale it smoothly - scale = swing/clampMin; + } else { // Scale it smoothly + scale = swing / clampMin; } } actualSpeed = scale * angleSpeed; // swing towards the destination angle - if ( swing >= 0 ) - { + if (swing >= 0) { move = cg.frametime * actualSpeed; - if ( move >= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move >= swing) { // our turnspeed is so fast, no need to swing, just match *curAngle = destAngle; + } else { + *curAngle = AngleNormalize360(*curAngle + move); } - else - { - *curAngle = AngleNormalize360( *curAngle + move ); - } - } - else if ( swing < 0 ) - { + } else if (swing < 0) { move = cg.frametime * -actualSpeed; - if ( move <= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move <= swing) { // our turnspeed is so fast, no need to swing, just match *curAngle = destAngle; - } - else - { - *curAngle = AngleNormalize180( *curAngle + move ); + } else { + *curAngle = AngleNormalize180(*curAngle + move); } } - swing = AngleSubtract( *curAngle, normalAngle ); + swing = AngleSubtract(*curAngle, normalAngle); // clamp to no more than normalAngle + tolerance - if ( swing > clampMax ) - { - *curAngle = AngleNormalize180( normalAngle + clampMax ); - } - else if ( swing < clampMin ) - { - *curAngle = AngleNormalize180( normalAngle + clampMin ); + if (swing > clampMax) { + *curAngle = AngleNormalize180(normalAngle + clampMax); + } else if (swing < clampMin) { + *curAngle = AngleNormalize180(normalAngle + clampMin); } } /* @@ -1413,107 +1126,77 @@ CG_SwingAngles locked mode (Don't turn unless you exceed the swing/clamp tolerance) ================== */ -void CG_SwingAngles( float destAngle, - float swingTolMin, float swingTolMax, - float clampMin, float clampMax, - float angleSpeed, float *curAngle, - qboolean *turning ) -{ - float swing; - float move; - float scale; +void CG_SwingAngles(float destAngle, float swingTolMin, float swingTolMax, float clampMin, float clampMax, float angleSpeed, float *curAngle, + qboolean *turning) { + float swing; + float move; + float scale; - swing = AngleSubtract( destAngle, *curAngle ); + swing = AngleSubtract(destAngle, *curAngle); - if(swing == 0) - {//Don't have to turn + if (swing == 0) { // Don't have to turn *turning = qfalse; - } - else - { + } else { *turning = qtrue; } - //If we're not turning, then we're done - if ( *turning == qfalse) + // If we're not turning, then we're done + if (*turning == qfalse) return; // modify the angleSpeed depending on the delta // so it doesn't seem so linear - scale = fabs( swing ); + scale = fabs(swing); - if (swing > 0) - { - if ( clampMax <= 0 ) - { + if (swing > 0) { + if (clampMax <= 0) { *curAngle = destAngle; return; } - if ( swing < swingTolMax * 0.5 ) - {//Pretty small way to go + if (swing < swingTolMax * 0.5) { // Pretty small way to go scale = 0.5; - } - else if ( scale < swingTolMax ) - {//More than halfway to go + } else if (scale < swingTolMax) { // More than halfway to go scale = 1.0; - } - else - {//Way out of our range + } else { // Way out of our range scale = 2.0; } - } - else// if (swing < 0) + } else // if (swing < 0) { - if ( clampMin >= 0 ) - { + if (clampMin >= 0) { *curAngle = destAngle; return; } - if ( swing > swingTolMin * 0.5 ) - {//Pretty small way to go + if (swing > swingTolMin * 0.5) { // Pretty small way to go scale = 0.5; - } - else if ( scale > swingTolMin ) - {//More than halfway to go + } else if (scale > swingTolMin) { // More than halfway to go scale = 1.0; - } - else - {//Way out of our range + } else { // Way out of our range scale = 2.0; } } // swing towards the destination angle - if ( swing >= 0 ) - { + if (swing >= 0) { move = cg.frametime * scale * angleSpeed; - if ( move >= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move >= swing) { // our turnspeed is so fast, no need to swing, just match move = swing; } - *curAngle = AngleNormalize360( *curAngle + move ); - } - else if ( swing < 0 ) - { + *curAngle = AngleNormalize360(*curAngle + move); + } else if (swing < 0) { move = cg.frametime * scale * -angleSpeed; - if ( move <= swing ) - {//our turnspeed is so fast, no need to swing, just match + if (move <= swing) { // our turnspeed is so fast, no need to swing, just match move = swing; } - *curAngle = AngleNormalize360( *curAngle + move ); + *curAngle = AngleNormalize360(*curAngle + move); } - // clamp to no more than tolerance - if ( swing > clampMax ) - { - *curAngle = AngleNormalize360( destAngle - (clampMax - 1) ); - } - else if ( swing < clampMin ) - { - *curAngle = AngleNormalize360( destAngle + (-clampMin - 1) ); + if (swing > clampMax) { + *curAngle = AngleNormalize360(destAngle - (clampMax - 1)); + } else if (swing < clampMin) { + *curAngle = AngleNormalize360(destAngle + (-clampMin - 1)); } } @@ -1541,7 +1224,7 @@ static void CG_AddPainTwitch( centity_t *cent, vec3_t torsoAngles ) { } } */ -//FIXME: Don't do this, use tag_eye instead? +// FIXME: Don't do this, use tag_eye instead? //-------------------------------------------------------------- /* float CG_EyePointOfsForRace[RACE_HOLOGRAM+1][2] = @@ -1567,92 +1250,73 @@ float CG_EyePointOfsForRace[RACE_HOLOGRAM+1][2] = 4, 8//RACE_HOLOGRAM }; */ -#define LOOK_DEFAULT_SPEED 0.15f -#define LOOK_TALKING_SPEED 0.15f +#define LOOK_DEFAULT_SPEED 0.15f +#define LOOK_TALKING_SPEED 0.15f -static qboolean CG_CheckLookTarget( centity_t *cent, vec3_t lookAngles, float *lookingSpeed ) -{ - if ( !cent->gent->ghoul2.size() ) - { - if ( !cent->gent->client->clientInfo.torsoModel || !cent->gent->client->clientInfo.headModel ) - { +static qboolean CG_CheckLookTarget(centity_t *cent, vec3_t lookAngles, float *lookingSpeed) { + if (!cent->gent->ghoul2.size()) { + if (!cent->gent->client->clientInfo.torsoModel || !cent->gent->client->clientInfo.headModel) { return qfalse; } } - //FIXME: also clamp the lookAngles based on the clamp + the existing difference between + // FIXME: also clamp the lookAngles based on the clamp + the existing difference between // headAngles and torsoAngles? But often the tag_torso is straight but the torso itself // is deformed to not face straight... sigh... - //Now calc head angle to lookTarget, if any - if ( cent->gent->client->renderInfo.lookTarget >= 0 && cent->gent->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - { - vec3_t lookDir, lookOrg = { 0.0f }, eyeOrg; - if ( cent->gent->client->renderInfo.lookMode == LM_ENT ) - { - centity_t *lookCent = &cg_entities[cent->gent->client->renderInfo.lookTarget]; - if ( lookCent && lookCent->gent ) - { - if ( lookCent->gent != cent->gent->enemy ) - {//We turn heads faster than headbob speed, but not as fast as if watching an enemy + // Now calc head angle to lookTarget, if any + if (cent->gent->client->renderInfo.lookTarget >= 0 && cent->gent->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { + vec3_t lookDir, lookOrg = {0.0f}, eyeOrg; + if (cent->gent->client->renderInfo.lookMode == LM_ENT) { + centity_t *lookCent = &cg_entities[cent->gent->client->renderInfo.lookTarget]; + if (lookCent && lookCent->gent) { + if (lookCent->gent != cent->gent->enemy) { // We turn heads faster than headbob speed, but not as fast as if watching an enemy *lookingSpeed = LOOK_DEFAULT_SPEED; } - //FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? - - if ( cent->gent->client->renderInfo.lookTarget == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) - {//Special case- use cg.refdef.vieworg if looking at player and not in third person view - VectorCopy( cg.refdef.vieworg, lookOrg ); - } - else if ( lookCent->gent->client ) - { - VectorCopy( lookCent->gent->client->renderInfo.eyePoint, lookOrg ); - } - else if ( lookCent->gent->s.pos.trType == TR_INTERPOLATE ) - { - VectorCopy( lookCent->lerpOrigin, lookOrg ); - } - else if ( lookCent->gent->inuse && !VectorCompare( lookCent->gent->currentOrigin, vec3_origin ) ) - { - VectorCopy( lookCent->gent->currentOrigin, lookOrg ); - } - else - {//at origin of world + // FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? + + if (cent->gent->client->renderInfo.lookTarget == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) + { // Special case- use cg.refdef.vieworg if looking at player and not in third person view + VectorCopy(cg.refdef.vieworg, lookOrg); + } else if (lookCent->gent->client) { + VectorCopy(lookCent->gent->client->renderInfo.eyePoint, lookOrg); + } else if (lookCent->gent->s.pos.trType == TR_INTERPOLATE) { + VectorCopy(lookCent->lerpOrigin, lookOrg); + } else if (lookCent->gent->inuse && !VectorCompare(lookCent->gent->currentOrigin, vec3_origin)) { + VectorCopy(lookCent->gent->currentOrigin, lookOrg); + } else { // at origin of world return qfalse; } - //Look in dir of lookTarget + // Look in dir of lookTarget } - } - else if ( cent->gent->client->renderInfo.lookMode == LM_INTEREST && cent->gent->client->renderInfo.lookTarget > -1 && cent->gent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS ) - { - VectorCopy( level.interestPoints[cent->gent->client->renderInfo.lookTarget].origin, lookOrg ); - } - else - { + } else if (cent->gent->client->renderInfo.lookMode == LM_INTEREST && cent->gent->client->renderInfo.lookTarget > -1 && + cent->gent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS) { + VectorCopy(level.interestPoints[cent->gent->client->renderInfo.lookTarget].origin, lookOrg); + } else { return qfalse; } - VectorCopy( cent->gent->client->renderInfo.eyePoint, eyeOrg ); + VectorCopy(cent->gent->client->renderInfo.eyePoint, eyeOrg); - VectorSubtract( lookOrg, eyeOrg, lookDir ); + VectorSubtract(lookOrg, eyeOrg, lookDir); #if 1 - vectoangles( lookDir, lookAngles ); + vectoangles(lookDir, lookAngles); #else - //FIXME: get the angle of the head tag and account for that when finding the lookAngles- + // FIXME: get the angle of the head tag and account for that when finding the lookAngles- // so if they're lying on their back we get an accurate lookAngle... - vec3_t headDirs[3]; - vec3_t finalDir; + vec3_t headDirs[3]; + vec3_t finalDir; - AnglesToAxis( cent->gent->client->renderInfo.headAngles, headDirs ); - VectorRotate( lookDir, headDirs, finalDir ); - vectoangles( finalDir, lookAngles ); + AnglesToAxis(cent->gent->client->renderInfo.headAngles, headDirs); + VectorRotate(lookDir, headDirs, finalDir); + vectoangles(finalDir, lookAngles); #endif - for ( int i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize180( lookAngles[i] ); - cent->gent->client->renderInfo.eyeAngles[i] = AngleNormalize180( cent->gent->client->renderInfo.eyeAngles[i] ); + for (int i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize180(lookAngles[i]); + cent->gent->client->renderInfo.eyeAngles[i] = AngleNormalize180(cent->gent->client->renderInfo.eyeAngles[i]); } - AnglesSubtract( lookAngles, cent->gent->client->renderInfo.eyeAngles, lookAngles ); + AnglesSubtract(lookAngles, cent->gent->client->renderInfo.eyeAngles, lookAngles); return qtrue; } @@ -1664,50 +1328,42 @@ static qboolean CG_CheckLookTarget( centity_t *cent, vec3_t lookAngles, float *l CG_AddHeadBob ================= */ -static qboolean CG_AddHeadBob( centity_t *cent, vec3_t addTo ) -{ - renderInfo_t *renderInfo = ¢->gent->client->renderInfo; - const int volume = gi.VoiceVolume[cent->gent->s.clientNum]; - const int volChange = volume - renderInfo->lastVoiceVolume;//was *3 because voice fromLA was too low - int i; +static qboolean CG_AddHeadBob(centity_t *cent, vec3_t addTo) { + renderInfo_t *renderInfo = ¢->gent->client->renderInfo; + const int volume = gi.VoiceVolume[cent->gent->s.clientNum]; + const int volChange = volume - renderInfo->lastVoiceVolume; // was *3 because voice fromLA was too low + int i; renderInfo->lastVoiceVolume = volume; - if ( !volume ) - { + if (!volume) { // Not talking, set our target to be the normal head position - VectorClear( renderInfo->targetHeadBobAngles ); + VectorClear(renderInfo->targetHeadBobAngles); - if ( VectorLengthSquared( renderInfo->headBobAngles ) < 1.0f ) - { + if (VectorLengthSquared(renderInfo->headBobAngles) < 1.0f) { // We are close enough to being back to our normal head position, so we are done for now return qfalse; } - } - else if ( volChange > 2 ) - { + } else if (volChange > 2) { // a big positive change in volume - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { // Move our head angle target a bit - renderInfo->targetHeadBobAngles[i] += Q_flrand( -1.0 * volChange, 1.0 * volChange ); + renderInfo->targetHeadBobAngles[i] += Q_flrand(-1.0 * volChange, 1.0 * volChange); // Clamp so we don't get too out of hand - if ( renderInfo->targetHeadBobAngles[i] > 7.0f ) + if (renderInfo->targetHeadBobAngles[i] > 7.0f) renderInfo->targetHeadBobAngles[i] = 7.0f; - if ( renderInfo->targetHeadBobAngles[i] < -7.0f ) + if (renderInfo->targetHeadBobAngles[i] < -7.0f) renderInfo->targetHeadBobAngles[i] = -7.0f; } } - for ( i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { // Always try to move head angles towards our target - renderInfo->headBobAngles[i] += ( renderInfo->targetHeadBobAngles[i] - renderInfo->headBobAngles[i] ) * ( cg.frametime / 150.0f ); - if ( addTo ) - { - addTo[i] = AngleNormalize180( addTo[i] + AngleNormalize180( renderInfo->headBobAngles[i] ) ); + renderInfo->headBobAngles[i] += (renderInfo->targetHeadBobAngles[i] - renderInfo->headBobAngles[i]) * (cg.frametime / 150.0f); + if (addTo) { + addTo[i] = AngleNormalize180(addTo[i] + AngleNormalize180(renderInfo->headBobAngles[i])); } } @@ -1715,266 +1371,205 @@ static qboolean CG_AddHeadBob( centity_t *cent, vec3_t addTo ) return qtrue; } -extern float vectoyaw( const vec3_t vec ); -qboolean CG_PlayerLegsYawFromMovement( centity_t *cent, const vec3_t velocity, float *yaw, float fwdAngle, float swingTolMin, float swingTolMax, qboolean alwaysFace ) -{ +extern float vectoyaw(const vec3_t vec); +qboolean CG_PlayerLegsYawFromMovement(centity_t *cent, const vec3_t velocity, float *yaw, float fwdAngle, float swingTolMin, float swingTolMax, + qboolean alwaysFace) { float newAddAngle, angleDiff, turnRate = 10, addAngle = 0; - //figure out what the offset, if any, should be - if ( velocity[0] || velocity[1] ) - { - float moveYaw; - moveYaw = vectoyaw( velocity ); - addAngle = AngleDelta( cent->lerpAngles[YAW], moveYaw )*-1; - if ( addAngle > 150 || addAngle < -150 ) - { + // figure out what the offset, if any, should be + if (velocity[0] || velocity[1]) { + float moveYaw; + moveYaw = vectoyaw(velocity); + addAngle = AngleDelta(cent->lerpAngles[YAW], moveYaw) * -1; + if (addAngle > 150 || addAngle < -150) { addAngle = 0; - } - else - { - //FIXME: use actual swing/clamp tolerances - if ( addAngle > swingTolMax ) - { + } else { + // FIXME: use actual swing/clamp tolerances + if (addAngle > swingTolMax) { addAngle = swingTolMax; - } - else if ( addAngle < swingTolMin ) - { + } else if (addAngle < swingTolMin) { addAngle = swingTolMin; } - if ( cent->gent->client->ps.pm_flags&PMF_BACKWARDS_RUN ) - { + if (cent->gent->client->ps.pm_flags & PMF_BACKWARDS_RUN) { addAngle *= -1; } turnRate = 5; } + } else if (!alwaysFace) { + return qfalse; } - else if ( !alwaysFace ) - { - return qfalse; - } - if ( cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED) ) - {//using force speed - //scale up the turning speed + if (cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { // using force speed + // scale up the turning speed turnRate /= cg_timescale.value; } - //lerp the legs angle to the new angle - angleDiff = AngleDelta( cent->pe.legs.yawAngle, (*yaw+addAngle) ); - newAddAngle = angleDiff*cg.frameInterpolation*-1; - if ( fabs(newAddAngle) > fabs(angleDiff) ) - { - newAddAngle = angleDiff*-1; + // lerp the legs angle to the new angle + angleDiff = AngleDelta(cent->pe.legs.yawAngle, (*yaw + addAngle)); + newAddAngle = angleDiff * cg.frameInterpolation * -1; + if (fabs(newAddAngle) > fabs(angleDiff)) { + newAddAngle = angleDiff * -1; } - if ( newAddAngle > turnRate ) - { + if (newAddAngle > turnRate) { newAddAngle = turnRate; - } - else if ( newAddAngle < -turnRate ) - { + } else if (newAddAngle < -turnRate) { newAddAngle = -turnRate; } *yaw = cent->pe.legs.yawAngle + newAddAngle; - //Now clamp - angleDiff = AngleDelta( fwdAngle, *yaw ); - if ( angleDiff > swingTolMax ) - { + // Now clamp + angleDiff = AngleDelta(fwdAngle, *yaw); + if (angleDiff > swingTolMax) { *yaw = fwdAngle - swingTolMax; - } - else if ( angleDiff < swingTolMin ) - { + } else if (angleDiff < swingTolMin) { *yaw = fwdAngle - swingTolMin; } return qtrue; } -void CG_ATSTLegsYaw( centity_t *cent, vec3_t trailingLegsAngles ) -{ +void CG_ATSTLegsYaw(centity_t *cent, vec3_t trailingLegsAngles) { float ATSTLegsYaw = cent->lerpAngles[YAW]; - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &ATSTLegsYaw, cent->lerpAngles[YAW], -60, 60, qtrue ); + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &ATSTLegsYaw, cent->lerpAngles[YAW], -60, 60, qtrue); float legAngleDiff = AngleNormalize180(ATSTLegsYaw) - AngleNormalize180(cent->pe.legs.yawAngle); int legsAnim = cent->currentState.legsAnim; qboolean moving = (qboolean)(!VectorCompare(cent->gent->client->ps.velocity, vec3_origin)); - if ( moving || legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 || fabs(legAngleDiff) > 45 ) - {//moving or turning or beyond the turn allowance - if ( legsAnim == BOTH_STAND1 && !moving ) - {//standing - if ( legAngleDiff > 0 ) - { - NPC_SetAnim( cent->gent, SETANIM_LEGS, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( cent->gent, SETANIM_LEGS, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0 ); + if (moving || legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 || fabs(legAngleDiff) > 45) { // moving or turning or beyond the turn allowance + if (legsAnim == BOTH_STAND1 && !moving) { // standing + if (legAngleDiff > 0) { + NPC_SetAnim(cent->gent, SETANIM_LEGS, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(cent->gent, SETANIM_LEGS, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0); cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; - } - else if ( legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1 ) - {//turning - legAngleDiff = AngleSubtract( ATSTLegsYaw, cent->gent->client->renderInfo.legsYaw ); + } else if (legsAnim == BOTH_TURN_LEFT1 || legsAnim == BOTH_TURN_RIGHT1) { // turning + legAngleDiff = AngleSubtract(ATSTLegsYaw, cent->gent->client->renderInfo.legsYaw); float add = 0; - if ( legAngleDiff > 50 ) - { + if (legAngleDiff > 50) { cent->pe.legs.yawAngle += legAngleDiff - 50; - } - else if ( legAngleDiff < -50 ) - { + } else if (legAngleDiff < -50) { cent->pe.legs.yawAngle += legAngleDiff + 50; } - float animLength = PM_AnimLength( cent->gent->client->clientInfo.animFileIndex, (animNumber_t)legsAnim ); - legAngleDiff *= ( animLength - cent->gent->client->ps.legsAnimTimer)/animLength; - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle+legAngleDiff+add, 0 ); - if ( !cent->gent->client->ps.legsAnimTimer ) - {//FIXME: if start turning in the middle of this, our legs pop back to the old cent->pe.legs.yawAngle... + float animLength = PM_AnimLength(cent->gent->client->clientInfo.animFileIndex, (animNumber_t)legsAnim); + legAngleDiff *= (animLength - cent->gent->client->ps.legsAnimTimer) / animLength; + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle + legAngleDiff + add, 0); + if (!cent->gent->client->ps.legsAnimTimer) { // FIXME: if start turning in the middle of this, our legs pop back to the old + // cent->pe.legs.yawAngle... cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; } - } - else - {//moving - legAngleDiff = AngleSubtract( ATSTLegsYaw, cent->pe.legs.yawAngle ); - //FIXME: framerate dependant!!! - if ( legAngleDiff > 50 ) - { + } else { // moving + legAngleDiff = AngleSubtract(ATSTLegsYaw, cent->pe.legs.yawAngle); + // FIXME: framerate dependant!!! + if (legAngleDiff > 50) { legAngleDiff -= 50; - } - else if ( legAngleDiff > 5 ) - { + } else if (legAngleDiff > 5) { legAngleDiff = 5; - } - else if ( legAngleDiff < -50 ) - { + } else if (legAngleDiff < -50) { legAngleDiff += 50; - } - else if ( legAngleDiff < -5 ) - { + } else if (legAngleDiff < -5) { legAngleDiff = -5; } legAngleDiff *= cg.frameInterpolation; - VectorSet( trailingLegsAngles, 0, AngleNormalize180(cent->pe.legs.yawAngle + legAngleDiff), 0 ); + VectorSet(trailingLegsAngles, 0, AngleNormalize180(cent->pe.legs.yawAngle + legAngleDiff), 0); cent->gent->client->renderInfo.legsYaw = trailingLegsAngles[YAW]; } cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = trailingLegsAngles[YAW]; cent->pe.legs.yawing = qtrue; - } - else - { - VectorSet( trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0 ); + } else { + VectorSet(trailingLegsAngles, 0, cent->pe.legs.yawAngle, 0); cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = trailingLegsAngles[YAW]; cent->pe.legs.yawing = qfalse; } return; } -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -void CG_G2ClientSpineAngles( centity_t *cent, vec3_t viewAngles, const vec3_t angles, vec3_t thoracicAngles, vec3_t ulAngles, vec3_t llAngles ) -{ +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +void CG_G2ClientSpineAngles(centity_t *cent, vec3_t viewAngles, const vec3_t angles, vec3_t thoracicAngles, vec3_t ulAngles, vec3_t llAngles) { cent->pe.torso.pitchAngle = viewAngles[PITCH]; - viewAngles[YAW] = AngleDelta( cent->lerpAngles[YAW], angles[YAW] ); + viewAngles[YAW] = AngleDelta(cent->lerpAngles[YAW], angles[YAW]); cent->pe.torso.yawAngle = viewAngles[YAW]; - if ( cg_motionBoneComp.integer - && !PM_FlippingAnim( cent->currentState.legsAnim ) - && !PM_SpinningSaberAnim( cent->currentState.legsAnim ) - && !PM_SpinningSaberAnim( cent->currentState.torsoAnim ) - && cent->currentState.legsAnim != cent->currentState.torsoAnim )//NOTE: presumes your legs & torso are on the same frame, though they *should* be because PM_SetAnimFinal tries to keep them in synch - {//FIXME: no need to do this if legs and torso on are same frame - //adjust for motion offset - mdxaBone_t boltMatrix; - vec3_t motionFwd, motionAngles; - - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->motionBolt, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, motionFwd ); - vectoangles( motionFwd, motionAngles ); - if ( cg_motionBoneComp.integer > 1 ) - {//do roll, too + if (cg_motionBoneComp.integer && !PM_FlippingAnim(cent->currentState.legsAnim) && !PM_SpinningSaberAnim(cent->currentState.legsAnim) && + !PM_SpinningSaberAnim(cent->currentState.torsoAnim) && + cent->currentState.legsAnim != cent->currentState.torsoAnim) // NOTE: presumes your legs & torso are on the same frame, though they *should* be because + // PM_SetAnimFinal tries to keep them in synch + { // FIXME: no need to do this if legs and torso on are same frame + // adjust for motion offset + mdxaBone_t boltMatrix; + vec3_t motionFwd, motionAngles; + + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->motionBolt, &boltMatrix, vec3_origin, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, motionFwd); + vectoangles(motionFwd, motionAngles); + if (cg_motionBoneComp.integer > 1) { // do roll, too vec3_t motionRt, tempAng; - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, motionRt ); - vectoangles( motionRt, tempAng ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, motionRt); + vectoangles(motionRt, tempAng); motionAngles[ROLL] = -tempAng[PITCH]; } - for ( int ang = 0; ang < 3; ang++ ) - { - viewAngles[ang] = AngleNormalize180( viewAngles[ang] - AngleNormalize180( motionAngles[ang] ) ); + for (int ang = 0; ang < 3; ang++) { + viewAngles[ang] = AngleNormalize180(viewAngles[ang] - AngleNormalize180(motionAngles[ang])); } } - //distribute the angles differently up the spine - //NOTE: each of these distributions must add up to 1.0f - thoracicAngles[PITCH] = viewAngles[PITCH]*0.20f; - llAngles[PITCH] = viewAngles[PITCH]*0.40f; - ulAngles[PITCH] = viewAngles[PITCH]*0.40f; + // distribute the angles differently up the spine + // NOTE: each of these distributions must add up to 1.0f + thoracicAngles[PITCH] = viewAngles[PITCH] * 0.20f; + llAngles[PITCH] = viewAngles[PITCH] * 0.40f; + ulAngles[PITCH] = viewAngles[PITCH] * 0.40f; - thoracicAngles[YAW] = viewAngles[YAW]*0.20f; - ulAngles[YAW] = viewAngles[YAW]*0.35f; - llAngles[YAW] = viewAngles[YAW]*0.45f; + thoracicAngles[YAW] = viewAngles[YAW] * 0.20f; + ulAngles[YAW] = viewAngles[YAW] * 0.35f; + llAngles[YAW] = viewAngles[YAW] * 0.45f; - thoracicAngles[ROLL] = viewAngles[ROLL]*0.20f; - ulAngles[ROLL] = viewAngles[ROLL]*0.35f; - llAngles[ROLL] = viewAngles[ROLL]*0.45f; + thoracicAngles[ROLL] = viewAngles[ROLL] * 0.20f; + ulAngles[ROLL] = viewAngles[ROLL] * 0.35f; + llAngles[ROLL] = viewAngles[ROLL] * 0.45f; - //thoracic is added modified again by neckAngle calculations, so don't set it until then - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + // thoracic is added modified again by neckAngle calculations, so don't set it until then + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); } -void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, vec3_t headClampMinAngles, vec3_t headClampMaxAngles ) -{ - vec3_t lA; - VectorCopy( lookAngles, lA ); - //clamp the headangles (which should now be relative to the cervical (neck) angles - if ( lA[PITCH] < headClampMinAngles[PITCH] ) - { +void CG_G2ClientNeckAngles(centity_t *cent, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, vec3_t headClampMinAngles, + vec3_t headClampMaxAngles) { + vec3_t lA; + VectorCopy(lookAngles, lA); + // clamp the headangles (which should now be relative to the cervical (neck) angles + if (lA[PITCH] < headClampMinAngles[PITCH]) { lA[PITCH] = headClampMinAngles[PITCH]; - } - else if ( lA[PITCH] > headClampMaxAngles[PITCH] ) - { + } else if (lA[PITCH] > headClampMaxAngles[PITCH]) { lA[PITCH] = headClampMaxAngles[PITCH]; } - if ( lA[YAW] < headClampMinAngles[YAW] ) - { + if (lA[YAW] < headClampMinAngles[YAW]) { lA[YAW] = headClampMinAngles[YAW]; - } - else if ( lA[YAW] > headClampMaxAngles[YAW] ) - { + } else if (lA[YAW] > headClampMaxAngles[YAW]) { lA[YAW] = headClampMaxAngles[YAW]; } - if ( lA[ROLL] < headClampMinAngles[ROLL] ) - { + if (lA[ROLL] < headClampMinAngles[ROLL]) { lA[ROLL] = headClampMinAngles[ROLL]; - } - else if ( lA[ROLL] > headClampMaxAngles[ROLL] ) - { + } else if (lA[ROLL] > headClampMaxAngles[ROLL]) { lA[ROLL] = headClampMaxAngles[ROLL]; } - //split it up between the neck and cranium - if ( thoracicAngles[PITCH] ) - {//already been set above, blend them + // split it up between the neck and cranium + if (thoracicAngles[PITCH]) { // already been set above, blend them thoracicAngles[PITCH] = (thoracicAngles[PITCH] + (lA[PITCH] * 0.4)) * 0.5f; - } - else - { + } else { thoracicAngles[PITCH] = lA[PITCH] * 0.4; } - if ( thoracicAngles[YAW] ) - {//already been set above, blend them + if (thoracicAngles[YAW]) { // already been set above, blend them thoracicAngles[YAW] = (thoracicAngles[YAW] + (lA[YAW] * 0.1)) * 0.5f; - } - else - { + } else { thoracicAngles[YAW] = lA[YAW] * 0.1; } - if ( thoracicAngles[ROLL] ) - {//already been set above, blend them + if (thoracicAngles[ROLL]) { // already been set above, blend them thoracicAngles[ROLL] = (thoracicAngles[ROLL] + (lA[ROLL] * 0.1)) * 0.5f; - } - else - { + } else { thoracicAngles[ROLL] = lA[ROLL] * 0.1; } @@ -1986,66 +1581,53 @@ void CG_G2ClientNeckAngles( centity_t *cent, const vec3_t lookAngles, vec3_t hea headAngles[YAW] = lA[YAW] * 0.6; headAngles[ROLL] = lA[ROLL] * 0.6; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, headAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, neckAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); } -void CG_UpdateLookAngles( centity_t *cent, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, float maxRoll ) -{ - if ( !cent || !cent->gent || !cent->gent->client ) - { +void CG_UpdateLookAngles(centity_t *cent, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, + float maxRoll) { + if (!cent || !cent->gent || !cent->gent->client) { return; } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { - //clamp so don't get "Exorcist" effect - if ( lookAngles[PITCH] > maxPitch ) - { + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { + // clamp so don't get "Exorcist" effect + if (lookAngles[PITCH] > maxPitch) { lookAngles[PITCH] = maxPitch; - } - else if ( lookAngles[PITCH] < minPitch ) - { + } else if (lookAngles[PITCH] < minPitch) { lookAngles[PITCH] = minPitch; } - if ( lookAngles[YAW] > maxYaw ) - { + if (lookAngles[YAW] > maxYaw) { lookAngles[YAW] = maxYaw; - } - else if ( lookAngles[YAW] < minYaw ) - { + } else if (lookAngles[YAW] < minYaw) { lookAngles[YAW] = minYaw; } - if ( lookAngles[ROLL] > maxRoll ) - { + if (lookAngles[ROLL] > maxRoll) { lookAngles[ROLL] = maxRoll; - } - else if ( lookAngles[ROLL] < minRoll ) - { + } else if (lookAngles[ROLL] < minRoll) { lookAngles[ROLL] = minRoll; } - //slowly lerp to this new value - //Remember last headAngles - vec3_t oldLookAngles; - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles ); + // slowly lerp to this new value + // Remember last headAngles + vec3_t oldLookAngles; + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles); vec3_t lookAnglesDiff; - VectorSubtract( lookAngles, oldLookAngles, lookAnglesDiff ); + VectorSubtract(lookAngles, oldLookAngles, lookAnglesDiff); - for ( int ang = 0; ang < 3; ang++ ) - { - lookAnglesDiff[ang] = AngleNormalize180( lookAnglesDiff[ang] ); + for (int ang = 0; ang < 3; ang++) { + lookAnglesDiff[ang] = AngleNormalize180(lookAnglesDiff[ang]); } - if( VectorLengthSquared( lookAnglesDiff ) ) - { - lookAngles[PITCH] = AngleNormalize180( oldLookAngles[PITCH]+(lookAnglesDiff[PITCH]*cg.frameInterpolation*lookSpeed) ); - lookAngles[YAW] = AngleNormalize180( oldLookAngles[YAW]+(lookAnglesDiff[YAW]*cg.frameInterpolation*lookSpeed) ); - lookAngles[ROLL] = AngleNormalize180( oldLookAngles[ROLL]+(lookAnglesDiff[ROLL]*cg.frameInterpolation*lookSpeed) ); + if (VectorLengthSquared(lookAnglesDiff)) { + lookAngles[PITCH] = AngleNormalize180(oldLookAngles[PITCH] + (lookAnglesDiff[PITCH] * cg.frameInterpolation * lookSpeed)); + lookAngles[YAW] = AngleNormalize180(oldLookAngles[YAW] + (lookAnglesDiff[YAW] * cg.frameInterpolation * lookSpeed)); + lookAngles[ROLL] = AngleNormalize180(oldLookAngles[ROLL] + (lookAnglesDiff[ROLL] * cg.frameInterpolation * lookSpeed)); } } - //Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); + // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); } /* @@ -2063,15 +1645,14 @@ Handles seperate torso motion =============== */ -extern int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ); -extern float PM_GetTimeScaleMod( gentity_t *gent ); -void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) -{ - vec3_t headAngles, neckAngles, chestAngles, thoracicAngles = {0,0,0};//legsAngles, torsoAngles, - vec3_t ulAngles, llAngles; - //float speed; - //vec3_t velocity; - vec3_t lookAngles, viewAngles; +extern int PM_TurnAnimForLegsAnim(gentity_t *gent, int anim); +extern float PM_GetTimeScaleMod(gentity_t *gent); +void CG_G2PlayerAngles(centity_t *cent, vec3_t legs[3], vec3_t angles) { + vec3_t headAngles, neckAngles, chestAngles, thoracicAngles = {0, 0, 0}; // legsAngles, torsoAngles, + vec3_t ulAngles, llAngles; + // float speed; + // vec3_t velocity; + vec3_t lookAngles, viewAngles; /* float headYawClampMin, headYawClampMax; float headPitchClampMin, headPitchClampMax; @@ -2082,456 +1663,377 @@ void CG_G2PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t angles ) float legsYawSwingTolMin, legsYawSwingTolMax; float yawSpeed, maxYawSpeed, lookingSpeed; */ - float lookAngleSpeed = LOOK_TALKING_SPEED;//shut up the compiler - //float swing, scale; - //int i; - qboolean looking = qfalse, talking = qfalse; + float lookAngleSpeed = LOOK_TALKING_SPEED; // shut up the compiler + // float swing, scale; + // int i; + qboolean looking = qfalse, talking = qfalse; // Dead entity - if ( cent->gent && cent->gent->health <= 0 ) - { - if ( cent->gent->hipsBone != -1 ) - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + if (cent->gent && cent->gent->health <= 0) { + if (cent->gent->hipsBone != -1) { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->cervicalBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); cent->pe.torso.pitchAngle = 0; cent->pe.torso.yawAngle = 0; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->upperLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->lowerLumbarBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); cent->pe.legs.pitchAngle = angles[0]; cent->pe.legs.yawAngle = angles[1]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[1]; } - AnglesToAxis( angles, legs ); + AnglesToAxis(angles, legs); return; } - if ( cent->gent && cent->gent->client - && (cent->gent->client->NPC_class != CLASS_GONK ) - && (cent->gent->client->NPC_class != CLASS_INTERROGATOR) - && (cent->gent->client->NPC_class != CLASS_SENTRY) - && (cent->gent->client->NPC_class != CLASS_PROBE ) - && (cent->gent->client->NPC_class != CLASS_R2D2 ) - && (cent->gent->client->NPC_class != CLASS_R5D2) - && (cent->gent->client->NPC_class != CLASS_ATST||!cent->gent->s.number) ) - {// If we are rendering third person, we should just force the player body to always fully face + if (cent->gent && cent->gent->client && (cent->gent->client->NPC_class != CLASS_GONK) && (cent->gent->client->NPC_class != CLASS_INTERROGATOR) && + (cent->gent->client->NPC_class != CLASS_SENTRY) && (cent->gent->client->NPC_class != CLASS_PROBE) && (cent->gent->client->NPC_class != CLASS_R2D2) && + (cent->gent->client->NPC_class != CLASS_R5D2) && + (cent->gent->client->NPC_class != CLASS_ATST || + !cent->gent->s.number)) { // If we are rendering third person, we should just force the player body to always fully face // whatever way they are looking, otherwise, you can end up with gun shots coming off of the // gun at angles that just look really wrong. - //NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso - //should pitch *some* when looking up and down... - VectorCopy( cent->lerpAngles, angles ); + // NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso + // should pitch *some* when looking up and down... + VectorCopy(cent->lerpAngles, angles); angles[PITCH] = 0; - if ( cent->gent->client ) - { - if ( cent->gent->client->NPC_class != CLASS_ATST ) - { - //FIXME: use actual swing/clamp tolerances? - if ( cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_InRoll( ¢->gent->client->ps ) ) - {//on the ground - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); - } - else - {//face legs to front - CG_PlayerLegsYawFromMovement( cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); + if (cent->gent->client) { + if (cent->gent->client->NPC_class != CLASS_ATST) { + // FIXME: use actual swing/clamp tolerances? + if (cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_InRoll(¢->gent->client->ps)) { // on the ground + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); + } else { // face legs to front + CG_PlayerLegsYawFromMovement(cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); } } } - //VectorClear( viewAngles ); - VectorCopy( cent->lerpAngles, viewAngles ); + // VectorClear( viewAngles ); + VectorCopy(cent->lerpAngles, viewAngles); viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); - // if ( cent->gent && !Q_stricmp( "atst", cent->gent->NPC_type ) ) - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { + // if ( cent->gent && !Q_stricmp( "atst", cent->gent->NPC_type ) ) + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { lookAngles[YAW] = 0; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - VectorCopy( viewAngles, lookAngles ); - } - else - { - if ( cg_turnAnims.integer && !in_camera && cent->gent->hipsBone >= 0 ) - { - //override the hips bone with a turn anim when turning - //and clear it when we're not... does blend from and to parent actually work? + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + VectorCopy(viewAngles, lookAngles); + } else { + if (cg_turnAnims.integer && !in_camera && cent->gent->hipsBone >= 0) { + // override the hips bone with a turn anim when turning + // and clear it when we're not... does blend from and to parent actually work? int startFrame, endFrame; - const qboolean animatingHips = gi.G2API_GetAnimRangeIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, &startFrame, &endFrame ); - - //FIXME: make legs lag behind when turning in place, only play turn anim when legs have to catch up - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); - } - else if ( VectorCompare( vec3_origin, cent->gent->client->ps.velocity ) ) - {//FIXME: because of LegsYawFromMovement, we play the turnAnims when we stop running, which looks really bad. - int turnAnim = PM_TurnAnimForLegsAnim( cent->gent, cent->gent->client->ps.legsAnim ); - if ( turnAnim != -1 && cent->gent->health > 0 ) - { + const qboolean animatingHips = + gi.G2API_GetAnimRangeIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, &startFrame, &endFrame); + + // FIXME: make legs lag behind when turning in place, only play turn anim when legs have to catch up + if (angles[YAW] == cent->pe.legs.yawAngle) { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); + } else if (VectorCompare(vec3_origin, cent->gent->client->ps.velocity)) { // FIXME: because of LegsYawFromMovement, we play the turnAnims when + // we stop running, which looks really bad. + int turnAnim = PM_TurnAnimForLegsAnim(cent->gent, cent->gent->client->ps.legsAnim); + if (turnAnim != -1 && cent->gent->health > 0) { animation_t *animations = level.knownAnimFileSets[cent->gent->client->clientInfo.animFileIndex].animations; - if ( !animatingHips || ( animations[turnAnim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again + if (!animatingHips || + (animations[turnAnim].firstFrame != startFrame)) // only set the anim if we aren't going to do the same animation again { - float animSpeed = 50.0f / animations[turnAnim].frameLerp * PM_GetTimeScaleMod( cent->gent ); + float animSpeed = 50.0f / animations[turnAnim].frameLerp * PM_GetTimeScaleMod(cent->gent); - gi.G2API_SetBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, - animations[turnAnim].firstFrame, animations[turnAnim].firstFrame+animations[turnAnim].numFrames, - BONE_ANIM_OVERRIDE_LOOP/*|BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND*/, animSpeed, cg.time, -1, 100 ); + gi.G2API_SetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone, animations[turnAnim].firstFrame, + animations[turnAnim].firstFrame + animations[turnAnim].numFrames, + BONE_ANIM_OVERRIDE_LOOP /*|BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND*/, animSpeed, cg.time, -1, 100); } + } else { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } - else - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); - } - } - else - { - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + } else { + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); } } - CG_G2ClientSpineAngles( cent, viewAngles, angles, thoracicAngles, ulAngles, llAngles ); + CG_G2ClientSpineAngles(cent, viewAngles, angles, thoracicAngles, ulAngles, llAngles); } - vec3_t trailingLegsAngles; - if ( cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - CG_ATSTLegsYaw( cent, trailingLegsAngles ); - AnglesToAxis( trailingLegsAngles, legs ); + vec3_t trailingLegsAngles; + if (cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + CG_ATSTLegsYaw(cent, trailingLegsAngles); + AnglesToAxis(trailingLegsAngles, legs); angles[YAW] = trailingLegsAngles[YAW]; - } - else - { + } else { - //set the legs.yawing field so we play the turning anim when turning in place - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { + // set the legs.yawing field so we play the turning anim when turning in place + if (angles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = angles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[YAW]; } - if ( cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED && cent->gent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { - vec3_t centFwd, centRt; + if (cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED && cent->gent->client->ps.groundEntityNum == ENTITYNUM_NONE) { + vec3_t centFwd, centRt; - AngleVectors( cent->lerpAngles, centFwd, centRt, NULL ); - angles[PITCH] = AngleNormalize180( DotProduct( cent->gent->client->ps.velocity, centFwd )/2 ); - if ( angles[PITCH] > 90 ) - { + AngleVectors(cent->lerpAngles, centFwd, centRt, NULL); + angles[PITCH] = AngleNormalize180(DotProduct(cent->gent->client->ps.velocity, centFwd) / 2); + if (angles[PITCH] > 90) { angles[PITCH] = 90; - } - else if ( angles[PITCH] < -90 ) - { + } else if (angles[PITCH] < -90) { angles[PITCH] = -90; } - angles[ROLL] = AngleNormalize180( DotProduct( cent->gent->client->ps.velocity, centRt )/10 ); - if ( angles[ROLL] > 90 ) - { + angles[ROLL] = AngleNormalize180(DotProduct(cent->gent->client->ps.velocity, centRt) / 10); + if (angles[ROLL] > 90) { angles[ROLL] = 90; - } - else if ( angles[ROLL] < -90 ) - { + } else if (angles[ROLL] < -90) { angles[ROLL] = -90; } } - AnglesToAxis( angles, legs ); + AnglesToAxis(angles, legs); } - //clamp relative to forward of cervical bone! - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { + // clamp relative to forward of cervical bone! + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { looking = qfalse; - VectorCopy( vec3_origin, chestAngles ); - } - else - { - //look at lookTarget! - float lookingSpeed = 0.3f; - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); - //Now add head bob when talking - talking = CG_AddHeadBob( cent, lookAngles ); - - //NOTE: previously, lookAngleSpeed was always 0.25f for the player - //Figure out how fast head should be turning - if ( cent->pe.torso.yawing || cent->pe.torso.pitching ) - {//If torso is turning, we want to turn head just as fast - if ( cent->gent->NPC ) - { - lookAngleSpeed = cent->gent->NPC->stats.yawSpeed/150;//about 0.33 normally - } - else - { + VectorCopy(vec3_origin, chestAngles); + } else { + // look at lookTarget! + float lookingSpeed = 0.3f; + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); + // Now add head bob when talking + talking = CG_AddHeadBob(cent, lookAngles); + + // NOTE: previously, lookAngleSpeed was always 0.25f for the player + // Figure out how fast head should be turning + if (cent->pe.torso.yawing || cent->pe.torso.pitching) { // If torso is turning, we want to turn head just as fast + if (cent->gent->NPC) { + lookAngleSpeed = cent->gent->NPC->stats.yawSpeed / 150; // about 0.33 normally + } else { lookAngleSpeed = cg_swingSpeed.value; } - } - else if ( talking ) - {//Slow for head bobbing + } else if (talking) { // Slow for head bobbing lookAngleSpeed = LOOK_TALKING_SPEED; - } - else if ( looking ) - {//Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary + } else if (looking) { // Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary lookAngleSpeed = lookingSpeed; - } - else if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - {//Not looking, not talking, head is returning from a talking head bob, use talking speed + } else if (cent->gent->client->renderInfo.lookingDebounceTime > + cg.time) { // Not looking, not talking, head is returning from a talking head bob, use talking speed lookAngleSpeed = LOOK_TALKING_SPEED; } - if ( looking || talking ) - {//want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) - //we should have a relative look angle, normalized to 180 + if (looking || talking) { // want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) + // we should have a relative look angle, normalized to 180 cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; - } - else - { - //still have a relative look angle from above + } else { + // still have a relative look angle from above } - CG_UpdateLookAngles( cent, lookAngles, lookAngleSpeed, -50.0f, 50.0f, -70.0f, 70.0f, -30.0f, 30.0f ); + CG_UpdateLookAngles(cent, lookAngles, lookAngleSpeed, -50.0f, 50.0f, -70.0f, 70.0f, -30.0f, 30.0f); } - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - VectorCopy( cent->lerpAngles, lookAngles ); + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[0] = lookAngles[2] = 0; lookAngles[YAW] -= trailingLegsAngles[YAW]; - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - } - else - { - vec3_t headClampMinAngles = {-25,-55,-10}, headClampMaxAngles = {50,50,10}; - CG_G2ClientNeckAngles( cent, lookAngles, headAngles, neckAngles, thoracicAngles, headClampMinAngles, headClampMaxAngles ); + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); + } else { + vec3_t headClampMinAngles = {-25, -55, -10}, headClampMaxAngles = {50, 50, 10}; + CG_G2ClientNeckAngles(cent, lookAngles, headAngles, neckAngles, thoracicAngles, headClampMinAngles, headClampMaxAngles); } return; } // All other entities - else if ( cent->gent && cent->gent->client ) - { - if ( (cent->gent->client->NPC_class == CLASS_PROBE ) - || (cent->gent->client->NPC_class == CLASS_R2D2 ) - || (cent->gent->client->NPC_class == CLASS_R5D2) - || (cent->gent->client->NPC_class == CLASS_ATST) ) - { - VectorCopy( cent->lerpAngles, angles ); + else if (cent->gent && cent->gent->client) { + if ((cent->gent->client->NPC_class == CLASS_PROBE) || (cent->gent->client->NPC_class == CLASS_R2D2) || (cent->gent->client->NPC_class == CLASS_R5D2) || + (cent->gent->client->NPC_class == CLASS_ATST)) { + VectorCopy(cent->lerpAngles, angles); angles[PITCH] = 0; - //FIXME: use actual swing/clamp tolerances? - if ( cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); - } - else - {//face legs to front - CG_PlayerLegsYawFromMovement( cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue ); + // FIXME: use actual swing/clamp tolerances? + if (cent->gent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on the ground + CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); + } else { // face legs to front + CG_PlayerLegsYawFromMovement(cent, vec3_origin, &angles[YAW], cent->lerpAngles[YAW], -60, 60, qtrue); } - VectorCopy( cent->lerpAngles, viewAngles ); -// viewAngles[YAW] = viewAngles[ROLL] = 0; + VectorCopy(cent->lerpAngles, viewAngles); + // viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); lookAngles[1] = 0; - if ( cent->gent->client->NPC_class == CLASS_ATST ) - {//body pitch - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT,POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + if (cent->gent->client->NPC_class == CLASS_ATST) { // body pitch + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.model_draw); } - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); - vec3_t trailingLegsAngles; - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) - { - CG_ATSTLegsYaw( cent, trailingLegsAngles ); - AnglesToAxis( trailingLegsAngles, legs ); - } - else - { - //FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place - if ( angles[YAW] == cent->pe.legs.yawAngle ) - { + vec3_t trailingLegsAngles; + if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) { + CG_ATSTLegsYaw(cent, trailingLegsAngles); + AnglesToAxis(trailingLegsAngles, legs); + } else { + // FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in + // place + if (angles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = angles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = angles[YAW]; } - AnglesToAxis( angles, legs ); - } - -// if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) -// { -// looking = qfalse; -// } -// else - { //look at lookTarget! - //FIXME: snaps to side when lets go of lookTarget... ? - float lookingSpeed = 0.3f; - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); - lookAngles[PITCH] = lookAngles[ROLL] = 0;//droids can't pitch or roll their heads - if ( looking ) - {//want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) + AnglesToAxis(angles, legs); + } + + // if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST ) + // { + // looking = qfalse; + // } + // else + { // look at lookTarget! + // FIXME: snaps to side when lets go of lookTarget... ? + float lookingSpeed = 0.3f; + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); + lookAngles[PITCH] = lookAngles[ROLL] = 0; // droids can't pitch or roll their heads + if (looking) { // want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; } } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { //adjust for current body orientation + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { // adjust for current body orientation lookAngles[YAW] -= cent->pe.torso.yawAngle; lookAngles[YAW] -= cent->pe.legs.yawAngle; - //normalize - lookAngles[YAW] = AngleNormalize180( lookAngles[YAW] ); - - //slowly lerp to this new value - //Remember last headAngles - vec3_t oldLookAngles; - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles ); - if( VectorCompare( oldLookAngles, lookAngles ) == qfalse ) - { - //FIXME: This clamp goes off viewAngles, - //but really should go off the tag_torso's axis[0] angles, no? - lookAngles[YAW] = oldLookAngles[YAW]+(lookAngles[YAW]-oldLookAngles[YAW])*cg.frameInterpolation*0.25; + // normalize + lookAngles[YAW] = AngleNormalize180(lookAngles[YAW]); + + // slowly lerp to this new value + // Remember last headAngles + vec3_t oldLookAngles; + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, oldLookAngles); + if (VectorCompare(oldLookAngles, lookAngles) == qfalse) { + // FIXME: This clamp goes off viewAngles, + // but really should go off the tag_torso's axis[0] angles, no? + lookAngles[YAW] = oldLookAngles[YAW] + (lookAngles[YAW] - oldLookAngles[YAW]) * cg.frameInterpolation * 0.25; } - //Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); + // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); + } else { // Remember current lookAngles next time + VectorCopy(lookAngles, cent->gent->client->renderInfo.lastHeadAngles); } - else - {//Remember current lookAngles next time - VectorCopy( lookAngles, cent->gent->client->renderInfo.lastHeadAngles ); - } - if ( cent->gent->client->NPC_class == CLASS_ATST ) - { - VectorCopy( cent->lerpAngles, lookAngles ); + if (cent->gent->client->NPC_class == CLASS_ATST) { + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[0] = lookAngles[2] = 0; lookAngles[YAW] -= trailingLegsAngles[YAW]; - } - else - { + } else { lookAngles[PITCH] = lookAngles[ROLL] = 0; lookAngles[YAW] -= cent->pe.legs.yawAngle; } - BG_G2SetBoneAngles( cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - //return; - } - else//if ( (cent->gent->client->NPC_class == CLASS_GONK ) || (cent->gent->client->NPC_class == CLASS_INTERROGATOR) || (cent->gent->client->NPC_class == CLASS_SENTRY) ) + BG_G2SetBoneAngles(cent, cent->gent, cent->gent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + // return; + } else // if ( (cent->gent->client->NPC_class == CLASS_GONK ) || (cent->gent->client->NPC_class == CLASS_INTERROGATOR) || (cent->gent->client->NPC_class + // == CLASS_SENTRY) ) { - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); cent->pe.torso.pitchAngle = 0; cent->pe.torso.yawAngle = 0; cent->pe.legs.pitchAngle = angles[0]; cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = angles[1]; - AnglesToAxis( angles, legs ); - //return; + AnglesToAxis(angles, legs); + // return; } } } -void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t head[3] ) -{ - vec3_t legsAngles, torsoAngles, headAngles; - vec3_t lookAngles, viewAngles; - float headYawClampMin, headYawClampMax; - float headPitchClampMin, headPitchClampMax; - float torsoYawSwingTolMin, torsoYawSwingTolMax; - float torsoYawClampMin, torsoYawClampMax; - float torsoPitchSwingTolMin, torsoPitchSwingTolMax; - float torsoPitchClampMin, torsoPitchClampMax; - float legsYawSwingTolMin, legsYawSwingTolMax; - float maxYawSpeed, yawSpeed, lookingSpeed; - float lookAngleSpeed = LOOK_TALKING_SPEED;//shut up the compiler - float swing, scale; - int i; - qboolean looking = qfalse, talking = qfalse; +void CG_PlayerAngles(centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t head[3]) { + vec3_t legsAngles, torsoAngles, headAngles; + vec3_t lookAngles, viewAngles; + float headYawClampMin, headYawClampMax; + float headPitchClampMin, headPitchClampMax; + float torsoYawSwingTolMin, torsoYawSwingTolMax; + float torsoYawClampMin, torsoYawClampMax; + float torsoPitchSwingTolMin, torsoPitchSwingTolMax; + float torsoPitchClampMin, torsoPitchClampMax; + float legsYawSwingTolMin, legsYawSwingTolMax; + float maxYawSpeed, yawSpeed, lookingSpeed; + float lookAngleSpeed = LOOK_TALKING_SPEED; // shut up the compiler + float swing, scale; + int i; + qboolean looking = qfalse, talking = qfalse; - if ( cg.renderingThirdPerson && cent->gent && cent->gent->s.number == 0 ) - { + if (cg.renderingThirdPerson && cent->gent && cent->gent->s.number == 0) { // If we are rendering third person, we should just force the player body to always fully face // whatever way they are looking, otherwise, you can end up with gun shots coming off of the // gun at angles that just look really wrong. - //NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso - //should pitch *some* when looking up and down... + // NOTENOTE: shots are coming out of the gun at ridiculous angles. The head & torso + // should pitch *some* when looking up and down... - //VectorClear( viewAngles ); - VectorCopy( cent->lerpAngles, viewAngles ); + // VectorClear( viewAngles ); + VectorCopy(cent->lerpAngles, viewAngles); viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - AnglesToAxis( viewAngles, head ); + AnglesToAxis(viewAngles, head); viewAngles[PITCH] *= 0.75; cent->pe.torso.pitchAngle = viewAngles[PITCH]; cent->pe.torso.yawAngle = viewAngles[YAW]; - AnglesToAxis( viewAngles, torso ); + AnglesToAxis(viewAngles, torso); - VectorCopy( cent->lerpAngles, lookAngles ); + VectorCopy(cent->lerpAngles, lookAngles); lookAngles[PITCH] = 0; - //FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place - if ( lookAngles[YAW] == cent->pe.legs.yawAngle ) - { + // FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place + if (lookAngles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } - if ( cent->gent->client->ps.velocity[0] || cent->gent->client->ps.velocity[1] ) - { - float moveYaw; - moveYaw = vectoyaw( cent->gent->client->ps.velocity ); - lookAngles[YAW] = cent->lerpAngles[YAW] + AngleDelta( cent->lerpAngles[YAW], moveYaw ); + if (cent->gent->client->ps.velocity[0] || cent->gent->client->ps.velocity[1]) { + float moveYaw; + moveYaw = vectoyaw(cent->gent->client->ps.velocity); + lookAngles[YAW] = cent->lerpAngles[YAW] + AngleDelta(cent->lerpAngles[YAW], moveYaw); } cent->pe.legs.yawAngle = lookAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = lookAngles[YAW]; } - AnglesToAxis( lookAngles, legs ); + AnglesToAxis(lookAngles, legs); return; } - if(cent->currentState.eFlags & EF_NPC) - { + if (cent->currentState.eFlags & EF_NPC) { headYawClampMin = -cent->gent->client->renderInfo.headYawRangeLeft; headYawClampMax = cent->gent->client->renderInfo.headYawRangeRight; - //These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles + // These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles headPitchClampMin = -cent->gent->client->renderInfo.headPitchRangeUp; headPitchClampMax = cent->gent->client->renderInfo.headPitchRangeDown; torsoYawSwingTolMin = headYawClampMin * 0.3; torsoYawSwingTolMax = headYawClampMax * 0.3; torsoPitchSwingTolMin = headPitchClampMin * 0.5; - torsoPitchSwingTolMax = headPitchClampMax * 0.5; + torsoPitchSwingTolMax = headPitchClampMax * 0.5; torsoYawClampMin = -cent->gent->client->renderInfo.torsoYawRangeLeft; torsoYawClampMax = cent->gent->client->renderInfo.torsoYawRangeRight; torsoPitchClampMin = -cent->gent->client->renderInfo.torsoPitchRangeUp; @@ -2540,26 +2042,17 @@ void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t h legsYawSwingTolMin = torsoYawClampMin * 0.5; legsYawSwingTolMax = torsoYawClampMax * 0.5; - if ( cent->gent && cent->gent->next_roff_time && cent->gent->next_roff_time >= cg.time ) - {//Following a roff, body must keep up with head, yaw-wise - headYawClampMin = - headYawClampMax = - torsoYawSwingTolMin = - torsoYawSwingTolMax = - torsoYawClampMin = - torsoYawClampMax = - legsYawSwingTolMin = - legsYawSwingTolMax = 0; + if (cent->gent && cent->gent->next_roff_time && cent->gent->next_roff_time >= cg.time) { // Following a roff, body must keep up with head, yaw-wise + headYawClampMin = headYawClampMax = torsoYawSwingTolMin = torsoYawSwingTolMax = torsoYawClampMin = torsoYawClampMax = legsYawSwingTolMin = + legsYawSwingTolMax = 0; } - yawSpeed = maxYawSpeed = cent->gent->NPC->stats.yawSpeed/150;//about 0.33 normally - } - else - { + yawSpeed = maxYawSpeed = cent->gent->NPC->stats.yawSpeed / 150; // about 0.33 normally + } else { headYawClampMin = -70; headYawClampMax = 70; - //These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles + // These next two are only used for a calc below- this clamp is done in PM_UpdateViewAngles headPitchClampMin = -90; headPitchClampMax = 90; @@ -2578,70 +2071,56 @@ void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t h yawSpeed = maxYawSpeed = cg_swingSpeed.value; } - if(yawSpeed <= 0) - {//Just in case - yawSpeed = 0.5f; //was 0.33 + if (yawSpeed <= 0) { // Just in case + yawSpeed = 0.5f; // was 0.33 } lookingSpeed = yawSpeed; - VectorCopy( cent->lerpAngles, headAngles ); - headAngles[YAW] = AngleNormalize360( headAngles[YAW] ); - VectorClear( legsAngles ); - VectorClear( torsoAngles ); + VectorCopy(cent->lerpAngles, headAngles); + headAngles[YAW] = AngleNormalize360(headAngles[YAW]); + VectorClear(legsAngles); + VectorClear(torsoAngles); // --------- yaw ------------- - //Clamp and swing the legs + // Clamp and swing the legs legsAngles[YAW] = headAngles[YAW]; - if(cent->gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) - { + if (cent->gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) { cent->gent->client->renderInfo.legsYaw = cent->pe.legs.yawAngle = cent->gent->client->renderInfo.lockYaw; cent->pe.legs.yawing = qfalse; legsAngles[YAW] = cent->pe.legs.yawAngle; - } - else - { + } else { qboolean alwaysFace = qfalse; - if ( cent->gent && cent->gent->health > 0 ) - { - if ( cent->gent->enemy ) - { + if (cent->gent && cent->gent->health > 0) { + if (cent->gent->enemy) { alwaysFace = qtrue; } - if ( CG_PlayerLegsYawFromMovement( cent, cent->gent->client->ps.velocity, &legsAngles[YAW], headAngles[YAW], torsoYawClampMin, torsoYawClampMax, alwaysFace ) ) - { - if ( legsAngles[YAW] == cent->pe.legs.yawAngle ) - { + if (CG_PlayerLegsYawFromMovement(cent, cent->gent->client->ps.velocity, &legsAngles[YAW], headAngles[YAW], torsoYawClampMin, torsoYawClampMax, + alwaysFace)) { + if (legsAngles[YAW] == cent->pe.legs.yawAngle) { cent->pe.legs.yawing = qfalse; - } - else - { + } else { cent->pe.legs.yawing = qtrue; } cent->pe.legs.yawAngle = legsAngles[YAW]; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } - } - else - { - CG_SwingAngles( legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, ¢->pe.legs.yawing ); + } else { + CG_SwingAngles(legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, + ¢->pe.legs.yawAngle, ¢->pe.legs.yawing); legsAngles[YAW] = cent->pe.legs.yawAngle; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } } - } - else - { - CG_SwingAngles( legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, ¢->pe.legs.yawing ); + } else { + CG_SwingAngles(legsAngles[YAW], legsYawSwingTolMin, legsYawSwingTolMax, torsoYawClampMin, torsoYawClampMax, maxYawSpeed, ¢->pe.legs.yawAngle, + ¢->pe.legs.yawing); legsAngles[YAW] = cent->pe.legs.yawAngle; - if ( cent->gent->client ) - { + if (cent->gent->client) { cent->gent->client->renderInfo.legsYaw = legsAngles[YAW]; } } @@ -2657,229 +2136,209 @@ void CG_PlayerAngles( centity_t *cent, vec3_t legs[3], vec3_t torso[3], vec3_t h // torso // If applicable, swing the lower parts to catch up with the head - CG_SwingAngles( headAngles[YAW], torsoYawSwingTolMin, torsoYawSwingTolMax, headYawClampMin, headYawClampMax, yawSpeed, ¢->pe.torso.yawAngle, ¢->pe.torso.yawing); + CG_SwingAngles(headAngles[YAW], torsoYawSwingTolMin, torsoYawSwingTolMax, headYawClampMin, headYawClampMax, yawSpeed, ¢->pe.torso.yawAngle, + ¢->pe.torso.yawing); torsoAngles[YAW] = cent->pe.torso.yawAngle; // ---------- pitch ----------- - //As the body twists to its extents, the back tends to arch backwards - + // As the body twists to its extents, the back tends to arch backwards float dest; // only show a fraction of the pitch angle in the torso - if ( headAngles[PITCH] > 180 ) - { + if (headAngles[PITCH] > 180) { dest = (-360 + headAngles[PITCH]) * 0.75; - } - else - { + } else { dest = headAngles[PITCH] * 0.75; } - CG_SwingAngles( dest, torsoPitchSwingTolMin, torsoPitchSwingTolMax, torsoPitchClampMin, torsoPitchClampMax, 0.1f, ¢->pe.torso.pitchAngle, ¢->pe.torso.pitching ); + CG_SwingAngles(dest, torsoPitchSwingTolMin, torsoPitchSwingTolMax, torsoPitchClampMin, torsoPitchClampMax, 0.1f, ¢->pe.torso.pitchAngle, + ¢->pe.torso.pitching); torsoAngles[PITCH] = cent->pe.torso.pitchAngle; // --------- roll ------------- // pain twitch - FIXME: don't do this if you have no head (like droids?) // Maybe need to have clamp angles for roll as well as pitch and yaw? - //CG_AddPainTwitch( cent, torsoAngles ); + // CG_AddPainTwitch( cent, torsoAngles ); //----------- Special head looking --------------- - //FIXME: to clamp the head angles, figure out tag_head's offset from tag_torso and add + // FIXME: to clamp the head angles, figure out tag_head's offset from tag_torso and add // that to whatever offset we're getting here... so turning the head in an // anim that also turns the head doesn't allow the head to turn out of range. - //Start with straight ahead - VectorCopy( headAngles, viewAngles ); - VectorCopy( headAngles, lookAngles ); + // Start with straight ahead + VectorCopy(headAngles, viewAngles); + VectorCopy(headAngles, lookAngles); - //Remember last headAngles - VectorCopy( cent->gent->client->renderInfo.lastHeadAngles, headAngles ); + // Remember last headAngles + VectorCopy(cent->gent->client->renderInfo.lastHeadAngles, headAngles); - //See if we're looking at someone/thing - looking = CG_CheckLookTarget( cent, lookAngles, &lookingSpeed ); + // See if we're looking at someone/thing + looking = CG_CheckLookTarget(cent, lookAngles, &lookingSpeed); - //Now add head bob when talking - if ( cent->gent->client->clientInfo.extensions ) - { - talking = CG_AddHeadBob( cent, lookAngles ); + // Now add head bob when talking + if (cent->gent->client->clientInfo.extensions) { + talking = CG_AddHeadBob(cent, lookAngles); } - //Figure out how fast head should be turning - if ( cent->pe.torso.yawing || cent->pe.torso.pitching ) - {//If torso is turning, we want to turn head just as fast + // Figure out how fast head should be turning + if (cent->pe.torso.yawing || cent->pe.torso.pitching) { // If torso is turning, we want to turn head just as fast lookAngleSpeed = yawSpeed; - } - else if ( talking ) - {//Slow for head bobbing + } else if (talking) { // Slow for head bobbing lookAngleSpeed = LOOK_TALKING_SPEED; - } - else if ( looking ) - {//Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary + } else if (looking) { // Not talking, set it up for looking at enemy, CheckLookTarget will scale it down if neccessary lookAngleSpeed = lookingSpeed; - } - else if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - {//Not looking, not talking, head is returning from a talking head bob, use talking speed + } else if (cent->gent->client->renderInfo.lookingDebounceTime > + cg.time) { // Not looking, not talking, head is returning from a talking head bob, use talking speed lookAngleSpeed = LOOK_TALKING_SPEED; } - if ( looking || talking ) - {//Keep this type of looking for a second after stopped looking + if (looking || talking) { // Keep this type of looking for a second after stopped looking cent->gent->client->renderInfo.lookingDebounceTime = cg.time + 1000; } - if ( cent->gent->client->renderInfo.lookingDebounceTime > cg.time ) - { - //Calc our actual desired head angles - for ( i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize360( cent->gent->client->renderInfo.headBobAngles[i] + lookAngles[i] ); + if (cent->gent->client->renderInfo.lookingDebounceTime > cg.time) { + // Calc our actual desired head angles + for (i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize360(cent->gent->client->renderInfo.headBobAngles[i] + lookAngles[i]); } - if( VectorCompare( headAngles, lookAngles ) == qfalse ) - { - //FIXME: This clamp goes off viewAngles, - //but really should go off the tag_torso's axis[0] angles, no? - CG_UpdateAngleClamp( lookAngles[PITCH], headPitchClampMin/1.25, headPitchClampMax/1.25, lookAngleSpeed, &headAngles[PITCH], viewAngles[PITCH] ); - CG_UpdateAngleClamp( lookAngles[YAW], headYawClampMin/1.25, headYawClampMax/1.25, lookAngleSpeed, &headAngles[YAW], viewAngles[YAW] ); - CG_UpdateAngleClamp( lookAngles[ROLL], -10, 10, lookAngleSpeed, &headAngles[ROLL], viewAngles[ROLL] ); + if (VectorCompare(headAngles, lookAngles) == qfalse) { + // FIXME: This clamp goes off viewAngles, + // but really should go off the tag_torso's axis[0] angles, no? + CG_UpdateAngleClamp(lookAngles[PITCH], headPitchClampMin / 1.25, headPitchClampMax / 1.25, lookAngleSpeed, &headAngles[PITCH], viewAngles[PITCH]); + CG_UpdateAngleClamp(lookAngles[YAW], headYawClampMin / 1.25, headYawClampMax / 1.25, lookAngleSpeed, &headAngles[YAW], viewAngles[YAW]); + CG_UpdateAngleClamp(lookAngles[ROLL], -10, 10, lookAngleSpeed, &headAngles[ROLL], viewAngles[ROLL]); } - if ( !cent->gent->enemy || cent->gent->enemy->s.number != cent->gent->client->renderInfo.lookTarget ) - { - //NOTE: Hacky, yes, I know, but necc. - //We want to turn the body to follow the lookTarget - //ONLY IF WE DON'T HAVE AN ENEMY OR OUR ENEMY IS NOT OUR LOOKTARGET - //This is the piece of code that was making the enemies not face where - //they were actually aiming. + if (!cent->gent->enemy || cent->gent->enemy->s.number != cent->gent->client->renderInfo.lookTarget) { + // NOTE: Hacky, yes, I know, but necc. + // We want to turn the body to follow the lookTarget + // ONLY IF WE DON'T HAVE AN ENEMY OR OUR ENEMY IS NOT OUR LOOKTARGET + // This is the piece of code that was making the enemies not face where + // they were actually aiming. - //Yaw change - swing = AngleSubtract( legsAngles[YAW], headAngles[YAW] ); - scale = fabs( swing ) / ( torsoYawClampMax + 0.01 ); //NOTENOTE: Some ents have a clamp of 0, which is bad for division + // Yaw change + swing = AngleSubtract(legsAngles[YAW], headAngles[YAW]); + scale = fabs(swing) / (torsoYawClampMax + 0.01); // NOTENOTE: Some ents have a clamp of 0, which is bad for division scale *= LOOK_SWING_SCALE; - torsoAngles[YAW] = legsAngles[YAW] - ( swing * scale ); + torsoAngles[YAW] = legsAngles[YAW] - (swing * scale); - //Pitch change - swing = AngleSubtract( legsAngles[PITCH], headAngles[PITCH] ); - scale = fabs( swing ) / ( torsoPitchClampMax + 0.01 ); //NOTENOTE: Some ents have a clamp of 0, which is bad for division + // Pitch change + swing = AngleSubtract(legsAngles[PITCH], headAngles[PITCH]); + scale = fabs(swing) / (torsoPitchClampMax + 0.01); // NOTENOTE: Some ents have a clamp of 0, which is bad for division scale *= LOOK_SWING_SCALE; - torsoAngles[PITCH] = legsAngles[PITCH] - ( swing * scale ); + torsoAngles[PITCH] = legsAngles[PITCH] - (swing * scale); } - } - else - {//Look straight ahead - VectorCopy( viewAngles, headAngles ); + } else { // Look straight ahead + VectorCopy(viewAngles, headAngles); } - //Remember current headAngles next time - VectorCopy( headAngles, cent->gent->client->renderInfo.lastHeadAngles ); + // Remember current headAngles next time + VectorCopy(headAngles, cent->gent->client->renderInfo.lastHeadAngles); //------------------------------------------------------------- // pull the angles back out of the hierarchial chain - AnglesSubtract( headAngles, torsoAngles, headAngles ); - AnglesSubtract( torsoAngles, legsAngles, torsoAngles ); - AnglesToAxis( legsAngles, legs ); - AnglesToAxis( torsoAngles, torso ); - AnglesToAxis( headAngles, head ); + AnglesSubtract(headAngles, torsoAngles, headAngles); + AnglesSubtract(torsoAngles, legsAngles, torsoAngles); + AnglesToAxis(legsAngles, legs); + AnglesToAxis(torsoAngles, torso); + AnglesToAxis(headAngles, head); } - //========================================================================== - /* =============== CG_TrailItem =============== */ -void CG_TrailItem( centity_t *cent, qhandle_t hModel ) { - refEntity_t ent; - vec3_t angles; - vec3_t axis[3]; +void CG_TrailItem(centity_t *cent, qhandle_t hModel) { + refEntity_t ent; + vec3_t angles; + vec3_t axis[3]; - VectorCopy( cent->lerpAngles, angles ); + VectorCopy(cent->lerpAngles, angles); angles[PITCH] = 0; angles[ROLL] = 0; - AnglesToAxis( angles, axis ); + AnglesToAxis(angles, axis); - memset( &ent, 0, sizeof( ent ) ); - VectorMA( cent->lerpOrigin, -24, axis[0], ent.origin ); + memset(&ent, 0, sizeof(ent)); + VectorMA(cent->lerpOrigin, -24, axis[0], ent.origin); ent.origin[2] += 20; - VectorScale( cg.autoAxis[0], 0.75, ent.axis[0] ); - VectorScale( cg.autoAxis[1], 0.75, ent.axis[1] ); - VectorScale( cg.autoAxis[2], 0.75, ent.axis[2] ); + VectorScale(cg.autoAxis[0], 0.75, ent.axis[0]); + VectorScale(cg.autoAxis[1], 0.75, ent.axis[1]); + VectorScale(cg.autoAxis[2], 0.75, ent.axis[2]); ent.hModel = hModel; - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } - /* =============== CG_PlayerPowerups =============== */ -extern void CG_Seeker( centity_t *cent ); -void CG_PlayerPowerups( centity_t *cent ) -{ - if ( !cent->currentState.powerups ) { +extern void CG_Seeker(centity_t *cent); +void CG_PlayerPowerups(centity_t *cent) { + if (!cent->currentState.powerups) { return; } -/* + /* - // quad gives a dlight - if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) { - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); - } + // quad gives a dlight + if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) { + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); + } - // redflag - if ( cent->currentState.powerups & ( 1 << PW_REDFLAG ) ) { - CG_TrailItem( cent, cgs.media.redFlagModel ); - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1, 0.2, 0.2 ); - } + // redflag + if ( cent->currentState.powerups & ( 1 << PW_REDFLAG ) ) { + CG_TrailItem( cent, cgs.media.redFlagModel ); + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1, 0.2, 0.2 ); + } - // blueflag - if ( cent->currentState.powerups & ( 1 << PW_BLUEFLAG ) ) { - CG_TrailItem( cent, cgs.media.blueFlagModel ); - cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); - } -*/ + // blueflag + if ( cent->currentState.powerups & ( 1 << PW_BLUEFLAG ) ) { + CG_TrailItem( cent, cgs.media.blueFlagModel ); + cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2, 0.2, 1 ); + } + */ // invul gives a dlight -// if ( cent->currentState.powerups & ( 1 << PW_BATTLESUIT ) ) -// { -// cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.8f, 0.8f, 0.2f ); -// } + // if ( cent->currentState.powerups & ( 1 << PW_BATTLESUIT ) ) + // { + // cgi_R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.8f, 0.8f, 0.2f ); + // } // seeker coolness -/* if ( cent->currentState.powerups & ( 1 << PW_SEEKER ) ) - { -// CG_Seeker(cent); - }*/ + /* if ( cent->currentState.powerups & ( 1 << PW_SEEKER ) ) + { + // CG_Seeker(cent); + }*/ } -#define SHADOW_DISTANCE 128 -static qboolean _PlayerShadow( const vec3_t origin, const float orientation, float *const shadowPlane, const float radius ) { - vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; - trace_t trace; - float alpha; +#define SHADOW_DISTANCE 128 +static qboolean _PlayerShadow(const vec3_t origin, const float orientation, float *const shadowPlane, const float radius) { + vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; + trace_t trace; + float alpha; // send a trace down from the player to the ground - VectorCopy( origin, end ); + VectorCopy(origin, end); end[2] -= SHADOW_DISTANCE; - cgi_CM_BoxTrace( &trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID ); + cgi_CM_BoxTrace(&trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID); // no shadow if too high - if ( trace.fraction == 1.0 || (trace.startsolid && trace.allsolid) ) { + if (trace.fraction == 1.0 || (trace.startsolid && trace.allsolid)) { return qfalse; } *shadowPlane = trace.endpos[2] + 1; - if ( cg_shadows.integer != 1 ) { // no mark for stencil or projection shadows + if (cg_shadows.integer != 1) { // no mark for stencil or projection shadows return qtrue; } @@ -2888,8 +2347,7 @@ static qboolean _PlayerShadow( const vec3_t origin, const float orientation, flo // add the mark as a temporary, so it goes directly to the renderer // without taking a spot in the cg_marks array - CG_ImpactMark( cgs.media.shadowMarkShader, trace.endpos, trace.plane.normal, - orientation, 1,1,1,alpha, qfalse, radius, qtrue ); + CG_ImpactMark(cgs.media.shadowMarkShader, trace.endpos, trace.plane.normal, orientation, 1, 1, 1, alpha, qfalse, radius, qtrue); return qtrue; } @@ -2903,116 +2361,99 @@ Returns the Z component of the surface being shadowed should it return a full plane instead of a Z? =============== */ -static qboolean CG_PlayerShadow( centity_t *const cent, float *const shadowPlane ) { +static qboolean CG_PlayerShadow(centity_t *const cent, float *const shadowPlane) { *shadowPlane = 0; - if ( cg_shadows.integer == 0 ) { + if (cg_shadows.integer == 0) { return qfalse; } // no shadows when cloaked - if ( cent->currentState.powerups & ( 1 << PW_CLOAKED )) - { + if (cent->currentState.powerups & (1 << PW_CLOAKED)) { return qfalse; } - if (cent->gent->client->NPC_class == CLASS_ATST) - { + if (cent->gent->client->NPC_class == CLASS_ATST) { qboolean bShadowed; - mdxaBone_t boltMatrix; - vec3_t tempAngles,sideOrigin; - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; - - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 30; //fudge up a bit for coplaner + mdxaBone_t boltMatrix; + vec3_t tempAngles, sideOrigin; + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; + + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 30; // fudge up a bit for coplaner bShadowed = _PlayerShadow(sideOrigin, 0, shadowPlane, 28); - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 30; //fudge up a bit for coplaner + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 30; // fudge up a bit for coplaner bShadowed = (qboolean)(_PlayerShadow(sideOrigin, 0, shadowPlane, 28) || bShadowed); bShadowed = (qboolean)(_PlayerShadow(cent->lerpOrigin, cent->pe.legs.yawAngle, shadowPlane, 64) || bShadowed); return bShadowed; - } - else - { + } else { return _PlayerShadow(cent->lerpOrigin, cent->pe.legs.yawAngle, shadowPlane, 16); } - } -void _PlayerSplash( const vec3_t origin, const vec3_t velocity, const float radius, const int maxUp ) -{ - static vec3_t WHITE={1,1,1}; - vec3_t start, end; - trace_t trace; - int contents; +void _PlayerSplash(const vec3_t origin, const vec3_t velocity, const float radius, const int maxUp) { + static vec3_t WHITE = {1, 1, 1}; + vec3_t start, end; + trace_t trace; + int contents; - VectorCopy( origin, end ); + VectorCopy(origin, end); end[2] -= 24; // if the feet aren't in liquid, don't make a mark // this won't handle moving water brushes, but they wouldn't draw right anyway... - contents = cgi_CM_PointContents( end, 0 ); - if ( !( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) ) - { + contents = cgi_CM_PointContents(end, 0); + if (!(contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { return; } - VectorCopy( origin, start ); - if ( maxUp < 32 ) - {//our head may actually be lower than 32 above our origin + VectorCopy(origin, start); + if (maxUp < 32) { // our head may actually be lower than 32 above our origin start[2] += maxUp; - } - else - { + } else { start[2] += 32; } // if the head isn't out of liquid, don't make a mark - contents = cgi_CM_PointContents( start, 0 ); - if ( contents & ( CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) - { + contents = cgi_CM_PointContents(start, 0); + if (contents & (CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { return; } // trace down to find the surface - cgi_CM_BoxTrace( &trace, start, end, NULL, NULL, 0, ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ); + cgi_CM_BoxTrace(&trace, start, end, NULL, NULL, 0, (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)); - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { return; } - VectorCopy( trace.endpos, end ); + VectorCopy(trace.endpos, end); end[0] += Q_flrand(-1.0f, 1.0f) * 3.0f; end[1] += Q_flrand(-1.0f, 1.0f) * 3.0f; - end[2] += 1.0f; //fudge up + end[2] += 1.0f; // fudge up - int t = VectorLengthSquared( velocity ); + int t = VectorLengthSquared(velocity); - if ( t > 8192 ) // oh, magic number + if (t > 8192) // oh, magic number { t = 8192; } - float alpha = ( t / 8192.0f ) * 0.6f + 0.2f; + float alpha = (t / 8192.0f) * 0.6f + 0.2f; - FX_AddOrientedParticle( end, trace.plane.normal, NULL, NULL, - 6.0f, radius + Q_flrand(0.0f, 1.0f) * 48.0f, 0, - alpha, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - Q_flrand(0.0f, 1.0f) * 360, Q_flrand(-1.0f, 1.0f) * 6.0f, NULL, NULL, 0.0f, 0 ,0, 1200, - cgs.media.wakeMarkShader, FX_ALPHA_LINEAR | FX_SIZE_LINEAR ); + FX_AddOrientedParticle(end, trace.plane.normal, NULL, NULL, 6.0f, radius + Q_flrand(0.0f, 1.0f) * 48.0f, 0, alpha, 0.0f, 0.0f, WHITE, WHITE, 0.0f, + Q_flrand(0.0f, 1.0f) * 360, Q_flrand(-1.0f, 1.0f) * 6.0f, NULL, NULL, 0.0f, 0, 0, 1200, cgs.media.wakeMarkShader, + FX_ALPHA_LINEAR | FX_SIZE_LINEAR); } /* @@ -3022,47 +2463,39 @@ CG_PlayerSplash Draw a mark at the water surface =============== */ -void CG_PlayerSplash( centity_t *cent ) -{ - if ( !cg_shadows.integer ) - { +void CG_PlayerSplash(centity_t *cent) { + if (!cg_shadows.integer) { return; } - if ( cent->gent && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { gclient_t *cl = cent->gent->client; - if ( cent->gent->disconnectDebounceTime < cg.time ) // can't do these expanding ripples all the time + if (cent->gent->disconnectDebounceTime < cg.time) // can't do these expanding ripples all the time { - if ( cl->NPC_class == CLASS_ATST ) - { - mdxaBone_t boltMatrix; - vec3_t tempAngles, sideOrigin; - - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; - - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 22; //fudge up a bit for coplaner - _PlayerSplash( sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2] ); - - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 22; //fudge up a bit for coplaner - - _PlayerSplash( sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2] ); - } - else - { + if (cl->NPC_class == CLASS_ATST) { + mdxaBone_t boltMatrix; + vec3_t tempAngles, sideOrigin; + + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; + + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 22; // fudge up a bit for coplaner + _PlayerSplash(sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2]); + + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 22; // fudge up a bit for coplaner + + _PlayerSplash(sideOrigin, cl->ps.velocity, 42, cent->gent->maxs[2]); + } else { // player splash mark - _PlayerSplash( cent->lerpOrigin, cl->ps.velocity, 36, cl->renderInfo.eyePoint[2] - cent->lerpOrigin[2] + 5 ); + _PlayerSplash(cent->lerpOrigin, cl->ps.velocity, 36, cl->renderInfo.eyePoint[2] - cent->lerpOrigin[2] + 5); } cent->gent->disconnectDebounceTime = cg.time + 125 + Q_flrand(0.0f, 1.0f) * 50.0f; @@ -3070,89 +2503,84 @@ void CG_PlayerSplash( centity_t *cent ) } } - /* =============== CG_LightningBolt =============== */ -void CG_LightningBolt( centity_t *cent, vec3_t origin ) -{ +void CG_LightningBolt(centity_t *cent, vec3_t origin) { // FIXME: This sound also plays when the weapon first fires which causes little sputtering sounds..not exactly cool // Must be currently firing - if ( !( cent->currentState.eFlags & EF_FIRING ) ) + if (!(cent->currentState.eFlags & EF_FIRING)) return; - //Must be a durational weapon -// if ( cent->currentState.weapon == WP_DEMP2 && cent->currentState.eFlags & EF_ALT_FIRING ) -// { /*nothing*/ } -// else - { - return; - } + // Must be a durational weapon + // if ( cent->currentState.weapon == WP_DEMP2 && cent->currentState.eFlags & EF_ALT_FIRING ) + // { /*nothing*/ } + // else + { return; } -/* trace_t trace; - gentity_t *traceEnt; - vec3_t end, forward, org, angs; - qboolean spark = qfalse, impact = qtrue;//, weak = qfalse; + /* trace_t trace; + gentity_t *traceEnt; + vec3_t end, forward, org, angs; + qboolean spark = qfalse, impact = qtrue;//, weak = qfalse; - // for lightning weapons coming from the player, it had better hit the crosshairs or else.. - if ( cent->gent->s.number ) - { - VectorCopy( origin, org ); - } - else - { - VectorCopy( cg.refdef.vieworg, org ); - } + // for lightning weapons coming from the player, it had better hit the crosshairs or else.. + if ( cent->gent->s.number ) + { + VectorCopy( origin, org ); + } + else + { + VectorCopy( cg.refdef.vieworg, org ); + } - // Find the impact point of the beam - VectorCopy( cent->lerpAngles, angs ); + // Find the impact point of the beam + VectorCopy( cent->lerpAngles, angs ); - AngleVectors( angs, forward, NULL, NULL ); + AngleVectors( angs, forward, NULL, NULL ); - VectorMA( org, weaponData[cent->currentState.weapon].range, forward, end ); + VectorMA( org, weaponData[cent->currentState.weapon].range, forward, end ); - CG_Trace( &trace, org, vec3_origin, vec3_origin, end, cent->currentState.number, MASK_SHOT ); - traceEnt = &g_entities[ trace.entityNum ]; + CG_Trace( &trace, org, vec3_origin, vec3_origin, end, cent->currentState.number, MASK_SHOT ); + traceEnt = &g_entities[ trace.entityNum ]; - // Make sparking be a bit less frame-rate dependent..also never add sparking when we hit a surface with a NOIMPACT flag - if ( cent->gent->fx_time < cg.time && !(trace.surfaceFlags & SURF_NOIMPACT )) - { - spark = qtrue; - cent->gent->fx_time = cg.time + Q_flrand(0.0f, 1.0f) * 100 + 100; - } + // Make sparking be a bit less frame-rate dependent..also never add sparking when we hit a surface with a NOIMPACT flag + if ( cent->gent->fx_time < cg.time && !(trace.surfaceFlags & SURF_NOIMPACT )) + { + spark = qtrue; + cent->gent->fx_time = cg.time + Q_flrand(0.0f, 1.0f) * 100 + 100; + } - // Don't draw certain kinds of impacts when it hits a player and such..or when we hit a surface with a NOIMPACT flag - if ( (traceEnt->takedamage && traceEnt->client) || (trace.surfaceFlags & SURF_NOIMPACT) ) - { - impact = qfalse; - } + // Don't draw certain kinds of impacts when it hits a player and such..or when we hit a surface with a NOIMPACT flag + if ( (traceEnt->takedamage && traceEnt->client) || (trace.surfaceFlags & SURF_NOIMPACT) ) + { + impact = qfalse; + } - // Add in the effect - switch ( cent->currentState.weapon ) - { - case WP_DEMP2: -// vec3_t org; + // Add in the effect + switch ( cent->currentState.weapon ) + { + case WP_DEMP2: + // vec3_t org; -extern void FX_DEMP2_AltBeam( vec3_t start, vec3_t end, vec3_t normal, //qboolean spark, - vec3_t targ1, vec3_t targ2 ); + extern void FX_DEMP2_AltBeam( vec3_t start, vec3_t end, vec3_t normal, //qboolean spark, + vec3_t targ1, vec3_t targ2 ); - // Move the beam back a bit to help cover up the poly edges on the fire beam -// VectorMA( origin, -4, forward, org ); -// FIXME: Looks and works like ASS, so don't let people see it until it improves - FX_DEMP2_AltBeam( origin, trace.endpos, trace.plane.normal, cent->gent->pos1, cent->gent->pos2 ); - break; + // Move the beam back a bit to help cover up the poly edges on the fire beam + // VectorMA( origin, -4, forward, org ); + // FIXME: Looks and works like ASS, so don't let people see it until it improves + FX_DEMP2_AltBeam( origin, trace.endpos, trace.plane.normal, cent->gent->pos1, cent->gent->pos2 ); + break; - } - */ + } + */ } //------------------------------------------- -void CG_ForcePushBlur( const vec3_t org ) -{ - localEntity_t *ex; +void CG_ForcePushBlur(const vec3_t org) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -3160,15 +2588,15 @@ void CG_ForcePushBlur( const vec3_t org ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], 55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], 55, ex->pos.trDelta); ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/forcePush"); ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -3177,183 +2605,152 @@ void CG_ForcePushBlur( const vec3_t org ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], -55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], -55, ex->pos.trDelta); ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; - ex->refEntity.customShader = cgi_R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = cgi_R_RegisterShader("gfx/effects/forcePush"); } -static void CG_ForcePushBodyBlur( centity_t *cent, const vec3_t origin, vec3_t tempAngles ) -{ +static void CG_ForcePushBodyBlur(centity_t *cent, const vec3_t origin, vec3_t tempAngles) { vec3_t fxOrg; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Head blur - CG_ForcePushBlur( cent->gent->client->renderInfo.eyePoint ); + CG_ForcePushBlur(cent->gent->client->renderInfo.eyePoint); // Do a torso based blur - if (cent->gent->torsoBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->torsoBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->torsoBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->torsoBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->handRBolt>=0) - { + if (cent->gent->handRBolt >= 0) { // Do a right-hand based blur - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->handLBolt>=0) - { + if (cent->gent->handLBolt >= 0) { // Do a left-hand based blur - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } // Do the knees - if (cent->gent->kneeLBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->kneeLBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->kneeRBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->kneeRBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->kneeRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->elbowLBolt>=0) - { + if (cent->gent->elbowLBolt >= 0) { // Do the elbows - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowLBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowLBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } - if (cent->gent->elbowRBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowRBolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - CG_ForcePushBlur( fxOrg ); + if (cent->gent->elbowRBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->elbowRBolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + CG_ForcePushBlur(fxOrg); } } -static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t tempAngles ) -{ +static void CG_ForceElectrocution(centity_t *cent, const vec3_t origin, vec3_t tempAngles) { // Undoing for now, at least this code should compile if I ( or anyone else ) decides to work on this effect - qboolean found = qfalse; - vec3_t fxOrg, fxOrg2, dir; - vec3_t rgb = {1.0f,1.0f,1.0f}; - mdxaBone_t boltMatrix; + qboolean found = qfalse; + vec3_t fxOrg, fxOrg2, dir; + vec3_t rgb = {1.0f, 1.0f, 1.0f}; + mdxaBone_t boltMatrix; - int bolt=-1; - int iter=0; + int bolt = -1; + int iter = 0; // Pick a random start point - while (bolt<0) - { + while (bolt < 0) { int test; - if (iter>5) - { - test=iter-5; - } - else - { - test=Q_irand(0,6); + if (iter > 5) { + test = iter - 5; + } else { + test = Q_irand(0, 6); } - switch(test) - { + switch (test) { case 0: // Right Elbow - bolt=cent->gent->elbowRBolt; + bolt = cent->gent->elbowRBolt; break; case 1: // Left Hand - bolt=cent->gent->handLBolt; + bolt = cent->gent->handLBolt; break; case 2: // Right hand - bolt=cent->gent->handRBolt; + bolt = cent->gent->handRBolt; break; case 3: // Left Foot - bolt=cent->gent->footLBolt; + bolt = cent->gent->footLBolt; break; case 4: // Right foot - bolt=cent->gent->footRBolt; + bolt = cent->gent->footRBolt; break; case 5: // Torso - bolt=cent->gent->torsoBolt; + bolt = cent->gent->torsoBolt; break; case 6: default: // Left Elbow - bolt=cent->gent->elbowLBolt; + bolt = cent->gent->elbowLBolt; break; } - if (++iter==20) + if (++iter == 20) break; } - if (bolt>=0) - { - found = gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.model_draw, cent->currentState.modelScale); + if (bolt >= 0) { + found = gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); } // Make sure that it's safe to even try and get these values out of the Matrix, otherwise the values could be garbage - if ( found ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_X, dir ); - } - else - { - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + if (found) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, dir); + } else { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); } // Add some fudge, makes us not normalized, but that isn't really important dir[0] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[1] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[2] += Q_flrand(-1.0f, 1.0f) * 0.4f; - } - else - { + } else { // Just use the lerp Origin and a random direction - VectorCopy( cent->lerpOrigin, fxOrg ); - VectorSet( dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f) ); // Not normalized, but who cares. - if ( cent->gent && cent->gent->client ) - { - switch ( cent->gent->client->NPC_class ) - { + VectorCopy(cent->lerpOrigin, fxOrg); + VectorSet(dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); // Not normalized, but who cares. + if (cent->gent && cent->gent->client) { + switch (cent->gent->client->NPC_class) { case CLASS_PROBE: fxOrg[2] += 50; break; @@ -3369,19 +2766,15 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t } } - VectorMA( fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2 ); + VectorMA(fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2); - trace_t tr; + trace_t tr; - CG_Trace( &tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID ); + CG_Trace(&tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f ) - { - FX_AddElectricity( fxOrg, tr.endpos, - 1.5f, 4.0f, 0.0f, - 1.0f, 0.5f, 0.0f, - rgb, rgb, 0.0f, - 5.5f, Q_flrand(0.0f, 1.0f) * 50 + 100, cgs.media.boltShader, FX_ALPHA_LINEAR | FX_SIZE_LINEAR | FX_BRANCH | FX_GROW | FX_TAPER ); + if (tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f) { + FX_AddElectricity(fxOrg, tr.endpos, 1.5f, 4.0f, 0.0f, 1.0f, 0.5f, 0.0f, rgb, rgb, 0.0f, 5.5f, Q_flrand(0.0f, 1.0f) * 50 + 100, cgs.media.boltShader, + FX_ALPHA_LINEAR | FX_SIZE_LINEAR | FX_BRANCH | FX_GROW | FX_TAPER); } } /* @@ -3391,84 +2784,72 @@ CG_AddRefEntityWithPowerups Adds a piece with modifications or duplications for powerups =============== */ -void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cent ) -{ - if ( !cent ) - { - cgi_R_AddRefEntityToScene( ent ); +void CG_AddRefEntityWithPowerups(refEntity_t *ent, int powerups, centity_t *cent) { + if (!cent) { + cgi_R_AddRefEntityToScene(ent); return; } - gentity_t *gent = cent->gent; - if ( !gent ) - { - cgi_R_AddRefEntityToScene( ent ); + gentity_t *gent = cent->gent; + if (!gent) { + cgi_R_AddRefEntityToScene(ent); return; } - if ( gent->client->ps.powerups[PW_DISRUPTION] < cg.time ) - {//disruptor - if (( powerups & ( 1 << PW_DISRUPTION ))) - { - //stop drawing him after this effect + if (gent->client->ps.powerups[PW_DISRUPTION] < cg.time) { // disruptor + if ((powerups & (1 << PW_DISRUPTION))) { + // stop drawing him after this effect gent->client->ps.eFlags |= EF_NODRAW; return; } } -// if ( gent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 ) -// { -// centity_t *cent = &cg_entities[gent->s.number]; -// cgi_S_AddLoopingSound( 0, cent->lerpOrigin, vec3_origin, cgs.media.overchargeLoopSound ); -// } + // if ( gent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 ) + // { + // centity_t *cent = &cg_entities[gent->s.number]; + // cgi_S_AddLoopingSound( 0, cent->lerpOrigin, vec3_origin, cgs.media.overchargeLoopSound ); + // } // If certain states are active, we don't want to add in the regular body - if ( !gent->client->ps.powerups[PW_CLOAKED] && - !gent->client->ps.powerups[PW_UNCLOAKING] && - !gent->client->ps.powerups[PW_DISRUPTION] ) - { - cgi_R_AddRefEntityToScene( ent ); + if (!gent->client->ps.powerups[PW_CLOAKED] && !gent->client->ps.powerups[PW_UNCLOAKING] && !gent->client->ps.powerups[PW_DISRUPTION]) { + cgi_R_AddRefEntityToScene(ent); } // Disruptor Gun Alt-fire - if ( gent->client->ps.powerups[PW_DISRUPTION] ) - { + if (gent->client->ps.powerups[PW_DISRUPTION]) { // I guess when something dies, it looks like pos1 gets set to the impact point on death, we can do fun stuff with this vec3_t tempAng; - VectorSubtract( gent->pos1, ent->origin, ent->oldorigin ); - //er, adjust this to get the proper position in model space... account for yaw - float tempLength = VectorNormalize( ent->oldorigin ); - vectoangles( ent->oldorigin, tempAng ); + VectorSubtract(gent->pos1, ent->origin, ent->oldorigin); + // er, adjust this to get the proper position in model space... account for yaw + float tempLength = VectorNormalize(ent->oldorigin); + vectoangles(ent->oldorigin, tempAng); tempAng[YAW] -= gent->client->ps.viewangles[YAW]; - AngleVectors( tempAng, ent->oldorigin, NULL, NULL ); - VectorScale( ent->oldorigin, tempLength, ent->oldorigin ); + AngleVectors(tempAng, ent->oldorigin, NULL, NULL); + VectorScale(ent->oldorigin, tempLength, ent->oldorigin); ent->endTime = gent->fx_time; ent->renderfx |= (RF_DISINTEGRATE2); - ent->customShader = cgi_R_RegisterShader( "gfx/effects/burn" ); - cgi_R_AddRefEntityToScene( ent ); + ent->customShader = cgi_R_RegisterShader("gfx/effects/burn"); + cgi_R_AddRefEntityToScene(ent); ent->renderfx &= ~(RF_DISINTEGRATE2); ent->renderfx |= (RF_DISINTEGRATE1); ent->customShader = 0; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); - if ( cg.time - ent->endTime < 1000 && (cg_timescale.value * cg_timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f ) - { + if (cg.time - ent->endTime < 1000 && (cg_timescale.value * cg_timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f) { vec3_t fxOrg; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, gent->playerModel, gent->torsoBolt, - &boltMatrix, gent->currentAngles, ent->origin, cg.time, - cgs.model_draw, gent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, fxOrg ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, gent->playerModel, gent->torsoBolt, &boltMatrix, gent->currentAngles, ent->origin, cg.time, + cgs.model_draw, gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, fxOrg); - VectorMA( fxOrg, -18, cg.refdef.viewaxis[0], fxOrg ); + VectorMA(fxOrg, -18, cg.refdef.viewaxis[0], fxOrg); fxOrg[2] += Q_flrand(-1.0f, 1.0f) * 20; - theFxScheduler.PlayEffect( "disruptor/death_smoke", fxOrg ); + theFxScheduler.PlayEffect("disruptor/death_smoke", fxOrg); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - theFxScheduler.PlayEffect( "disruptor/death_smoke", fxOrg ); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + theFxScheduler.PlayEffect("disruptor/death_smoke", fxOrg); } } } @@ -3476,91 +2857,79 @@ void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cen // Cloaking & Uncloaking Technology //---------------------------------------- - if (( powerups & ( 1 << PW_UNCLOAKING ))) - {//in the middle of cloaking + if ((powerups & (1 << PW_UNCLOAKING))) { // in the middle of cloaking float perc = (float)(gent->client->ps.powerups[PW_UNCLOAKING] - cg.time) / 2000.0f; - if (( powerups & ( 1 << PW_CLOAKED ))) - {//actually cloaking, so reverse it + if ((powerups & (1 << PW_CLOAKED))) { // actually cloaking, so reverse it perc = 1.0f - perc; } - if ( perc >= 0.0f && perc <= 1.0f ) - { + if (perc >= 0.0f && perc <= 1.0f) { ent->renderfx &= ~RF_ALPHA_FADE; ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255.0f * perc; ent->shaderRGBA[3] = 0; ent->customShader = cgs.media.cloakedShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255; ent->shaderRGBA[3] = 255 * (1.0f - perc); // let model alpha in - ent->customShader = 0; // use regular skin + ent->customShader = 0; // use regular skin ent->renderfx &= ~RF_RGB_TINT; ent->renderfx |= RF_ALPHA_FADE; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } - } - else if (( powerups & ( 1 << PW_CLOAKED ))) - {//fully cloaked - ent->renderfx = 0;//&= ~(RF_RGB_TINT|RF_ALPHA_FADE); + } else if ((powerups & (1 << PW_CLOAKED))) { // fully cloaked + ent->renderfx = 0; //&= ~(RF_RGB_TINT|RF_ALPHA_FADE); ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = ent->shaderRGBA[3] = 255; ent->customShader = cgs.media.cloakedShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } // Electricity //------------------------------------------------ - if ( (powerups & ( 1 << PW_SHOCKED )) ) - { - int dif = gent->client->ps.powerups[PW_SHOCKED] - cg.time; + if ((powerups & (1 << PW_SHOCKED))) { + int dif = gent->client->ps.powerups[PW_SHOCKED] - cg.time; - if ( dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f ) - { + if (dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f) { // fade out over the last 500 ms int brightness = 255; - if ( dif < 500 ) - { - brightness = floor((dif - 500.0f) / 500.0f * 255.0f ); + if (dif < 500) { + brightness = floor((dif - 500.0f) / 500.0f * 255.0f); } ent->renderfx |= RF_RGB_TINT; ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = brightness; ent->shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { ent->customShader = cgs.media.electricBodyShader; - } - else - { + } else { ent->customShader = cgs.media.electricBody2Shader; } - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); - if ( Q_flrand(0.0f, 1.0f) > 0.9f ) - cgi_S_StartSound ( ent->origin, gent->s.number, CHAN_AUTO, cgi_S_RegisterSound( "sound/effects/energy_crackle.wav" ) ); + if (Q_flrand(0.0f, 1.0f) > 0.9f) + cgi_S_StartSound(ent->origin, gent->s.number, CHAN_AUTO, cgi_S_RegisterSound("sound/effects/energy_crackle.wav")); } } // FORCE speed does blur trails //------------------------------------------------------ - if ( gent->client->ps.forcePowersActive & (1 << FP_SPEED) - && (gent->s.number || cg.renderingThirdPerson) ) // looks dumb doing this with first peron mode on + if (gent->client->ps.forcePowersActive & (1 << FP_SPEED) && (gent->s.number || cg.renderingThirdPerson)) // looks dumb doing this with first peron mode on { - localEntity_t *ex; + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_FADE_MODEL; - memcpy( &ex->refEntity, ent, sizeof( refEntity_t )); + memcpy(&ex->refEntity, ent, sizeof(refEntity_t)); ex->refEntity.renderfx |= RF_ALPHA_FADE; ex->startTime = cg.time; ex->endTime = ex->startTime + 75; - VectorCopy( ex->refEntity.origin, ex->pos.trBase ); - VectorClear( ex->pos.trDelta ); + VectorCopy(ex->refEntity.origin, ex->pos.trBase); + VectorClear(ex->pos.trDelta); ex->color[0] = ex->color[1] = ex->color[2] = 255.0f; ex->color[3] = 50.0f; @@ -3568,135 +2937,121 @@ void CG_AddRefEntityWithPowerups( refEntity_t *ent, int powerups, centity_t *cen // Personal Shields //------------------------ - if ( powerups & ( 1 << PW_BATTLESUIT )) - { + if (powerups & (1 << PW_BATTLESUIT)) { float diff = gent->client->ps.powerups[PW_BATTLESUIT] - cg.time; float t; - if ( diff > 0 ) - { - t = 1.0f - ( diff / (ARMOR_EFFECT_TIME * 2.0f)); + if (diff > 0) { + t = 1.0f - (diff / (ARMOR_EFFECT_TIME * 2.0f)); // Only display when we have damage - if ( t < 0.0f || t > 1.0f ) - { - } - else - { + if (t < 0.0f || t > 1.0f) { + } else { ent->shaderRGBA[0] = ent->shaderRGBA[1] = ent->shaderRGBA[2] = 255.0f * t; ent->shaderRGBA[3] = 255; ent->renderfx &= ~RF_ALPHA_FADE; ent->renderfx |= RF_RGB_TINT; ent->customShader = cgs.media.personalShieldShader; - cgi_R_AddRefEntityToScene( ent ); + cgi_R_AddRefEntityToScene(ent); } } } // Galak Mech shield bubble //------------------------------------------------------ - if ( powerups & ( 1 << PW_GALAK_SHIELD )) - { + if (powerups & (1 << PW_GALAK_SHIELD)) { refEntity_t tent; - memset( &tent, 0, sizeof( refEntity_t )); + memset(&tent, 0, sizeof(refEntity_t)); tent.reType = RT_LATHE; // Setting up the 2d control points, these get swept around to make a 3D lathed model - VectorSet2( tent.axis[0], 0.5, 0 ); // start point of curve - VectorSet2( tent.axis[1], 50, 85 ); // control point 1 - VectorSet2( tent.axis[2], 135, -100 ); // control point 2 - VectorSet2( tent.oldorigin, 0, -90 ); // end point of curve + VectorSet2(tent.axis[0], 0.5, 0); // start point of curve + VectorSet2(tent.axis[1], 50, 85); // control point 1 + VectorSet2(tent.axis[2], 135, -100); // control point 2 + VectorSet2(tent.oldorigin, 0, -90); // end point of curve - if ( gent->client->poisonTime && gent->client->poisonTime + 1000 > cg.time ) - { - VectorCopy( gent->pos4, tent.lightingOrigin ); + if (gent->client->poisonTime && gent->client->poisonTime + 1000 > cg.time) { + VectorCopy(gent->pos4, tent.lightingOrigin); tent.frame = gent->client->poisonTime; } - mdxaBone_t boltMatrix; - vec3_t angles = {0,gent->client->ps.legsYaw,0}; + mdxaBone_t boltMatrix; + vec3_t angles = {0, gent->client->ps.legsYaw, 0}; - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, gent->playerModel, gent->genericBolt1, &boltMatrix, angles, cent->lerpOrigin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tent.origin );// pass in the emitter origin here + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, gent->playerModel, gent->genericBolt1, &boltMatrix, angles, cent->lerpOrigin, cg.time, cgs.model_draw, + cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tent.origin); // pass in the emitter origin here - tent.endTime = gent->fx_time + 1000; // if you want the shell to build around the guy, pass in a time that is 1000ms after the start of the turn-on-effect - tent.customShader = cgi_R_RegisterShader( "gfx/effects/irid_shield" ); + tent.endTime = + gent->fx_time + 1000; // if you want the shell to build around the guy, pass in a time that is 1000ms after the start of the turn-on-effect + tent.customShader = cgi_R_RegisterShader("gfx/effects/irid_shield"); - cgi_R_AddRefEntityToScene( &tent ); + cgi_R_AddRefEntityToScene(&tent); } // Invincibility -- effect needs work //------------------------------------------------------ - if ( powerups & ( 1 << PW_INVINCIBLE )) - { - theFxScheduler.PlayEffect( cgs.effects.forceInvincibility, cent->lerpOrigin ); + if (powerups & (1 << PW_INVINCIBLE)) { + theFxScheduler.PlayEffect(cgs.effects.forceInvincibility, cent->lerpOrigin); } // Healing -- could use some work....maybe also make it NOT be framerate dependant //------------------------------------------------------ -/* if ( powerups & ( 1 << PW_HEALING )) - { - vec3_t axis[3]; + /* if ( powerups & ( 1 << PW_HEALING )) + { + vec3_t axis[3]; - AngleVectors( cent->gent->client->renderInfo.eyeAngles, axis[0], axis[1], axis[2] ); + AngleVectors( cent->gent->client->renderInfo.eyeAngles, axis[0], axis[1], axis[2] ); - theFxScheduler.PlayEffect( cgs.effects.forceHeal, cent->gent->client->renderInfo.eyePoint, axis ); - } -*/ + theFxScheduler.PlayEffect( cgs.effects.forceHeal, cent->gent->client->renderInfo.eyePoint, axis ); + } + */ // Push Blur - if ( gent->forcePushTime > cg.time && gi.G2API_HaveWeGhoul2Models( cent->gent->ghoul2 ) ) - { - CG_ForcePushBlur( ent->origin ); + if (gent->forcePushTime > cg.time && gi.G2API_HaveWeGhoul2Models(cent->gent->ghoul2)) { + CG_ForcePushBlur(ent->origin); } } - /* ------------------------- CG_G2SetHeadBlink ------------------------- */ -static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) -{ - if ( !cent ) - { +static void CG_G2SetHeadBlink(centity_t *cent, qboolean bStart) { + if (!cent) { return; } gentity_t *gent = cent->gent; - //FIXME: get these boneIndices game-side and pass it down? - //FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 - const int hLeye = gi.G2API_GetBoneIndex( &gent->ghoul2[0], "leye", qtrue ); - if (hLeye == -1) - { + // FIXME: get these boneIndices game-side and pass it down? + // FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 + const int hLeye = gi.G2API_GetBoneIndex(&gent->ghoul2[0], "leye", qtrue); + if (hLeye == -1) { return; } - vec3_t desiredAngles = {0}; + vec3_t desiredAngles = {0}; int blendTime = 80; qboolean bWink = qfalse; - if (bStart) - { + if (bStart) { desiredAngles[YAW] = -50; - if ( !in_camera && Q_flrand(0.0f, 1.0f) > 0.95f ) - { + if (!in_camera && Q_flrand(0.0f, 1.0f) > 0.95f) { bWink = qtrue; - blendTime /=3; + blendTime /= 3; } } - gi.G2API_SetBoneAnglesIndex( &gent->ghoul2[gent->playerModel], hLeye, desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); - const int hReye = gi.G2API_GetBoneIndex( &gent->ghoul2[0], "reye", qtrue ); - if (hReye == -1) - { + gi.G2API_SetBoneAnglesIndex(&gent->ghoul2[gent->playerModel], hLeye, desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + blendTime, cg.time); + const int hReye = gi.G2API_GetBoneIndex(&gent->ghoul2[0], "reye", qtrue); + if (hReye == -1) { return; } if (!bWink) - gi.G2API_SetBoneAnglesIndex( &gent->ghoul2[gent->playerModel], hReye, desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); + gi.G2API_SetBoneAnglesIndex(&gent->ghoul2[gent->playerModel], hReye, desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + blendTime, cg.time); } /* @@ -3704,148 +3059,117 @@ static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) CG_G2SetHeadAnims ------------------------- */ -static void CG_G2SetHeadAnim( centity_t *cent, int anim ) -{ - gentity_t *gent = cent->gent; +static void CG_G2SetHeadAnim(centity_t *cent, int anim) { + gentity_t *gent = cent->gent; const int blendTime = 50; const animation_t *animations = level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations; - int animFlags = BONE_ANIM_OVERRIDE ;//| BONE_ANIM_BLEND; + int animFlags = BONE_ANIM_OVERRIDE; //| BONE_ANIM_BLEND; // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). -// float timeScaleMod = (cg_timescale.value&&gent&&gent->s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); + // int startFrame, endFrame; + // const qboolean animatingHead = gi.G2API_GetAnimRangeIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); -// if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, - firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); - } + // if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again + { gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); } } -qboolean CG_G2PlayerHeadAnims( centity_t *cent ) -{ - if(!ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) - { +qboolean CG_G2PlayerHeadAnims(centity_t *cent) { + if (!ValidAnimFileIndex(cent->gent->client->clientInfo.animFileIndex)) { return qfalse; } - if (cent->gent->faceBone == BONE_INDEX_INVALID) - { // i don't have a face + if (cent->gent->faceBone == BONE_INDEX_INVALID) { // i don't have a face return qfalse; } int anim = -1; - if ( cent->gent->health <= 0 ) - {//Dead people close their eyes and don't make faces! + if (cent->gent->health <= 0) { // Dead people close their eyes and don't make faces! anim = FACE_DEAD; - } - else - { - if (!cent->gent->client->facial_blink) - { // set the timers + } else { + if (!cent->gent->client->facial_blink) { // set the timers cent->gent->client->facial_blink = cg.time + Q_flrand(4000.0, 8000.0); cent->gent->client->facial_frown = cg.time + Q_flrand(6000.0, 10000.0); cent->gent->client->facial_aux = cg.time + Q_flrand(6000.0, 10000.0); } - //are we blinking? - if (cent->gent->client->facial_blink < 0) - { // yes, check if we are we done blinking ? - if (-(cent->gent->client->facial_blink) < cg.time) - { // yes, so reset blink timer + // are we blinking? + if (cent->gent->client->facial_blink < 0) { // yes, check if we are we done blinking ? + if (-(cent->gent->client->facial_blink) < cg.time) { // yes, so reset blink timer cent->gent->client->facial_blink = cg.time + Q_flrand(4000.0, 8000.0); - CG_G2SetHeadBlink( cent, qfalse ); //stop the blink + CG_G2SetHeadBlink(cent, qfalse); // stop the blink } - } - else // no we aren't blinking + } else // no we aren't blinking { - if (cent->gent->client->facial_blink < cg.time)// but should we start ? + if (cent->gent->client->facial_blink < cg.time) // but should we start ? { - CG_G2SetHeadBlink( cent, qtrue ); - if (cent->gent->client->facial_blink == 1) - {//requested to stay shut by SET_FACEEYESCLOSED - cent->gent->client->facial_blink = -(cg.time + 99999999.0f);// set blink timer - } - else - { - cent->gent->client->facial_blink = -(cg.time + 300.0f);// set blink timer + CG_G2SetHeadBlink(cent, qtrue); + if (cent->gent->client->facial_blink == 1) { // requested to stay shut by SET_FACEEYESCLOSED + cent->gent->client->facial_blink = -(cg.time + 99999999.0f); // set blink timer + } else { + cent->gent->client->facial_blink = -(cg.time + 300.0f); // set blink timer } } } - - if (gi.VoiceVolume[cent->gent->s.clientNum] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused + if (gi.VoiceVolume[cent->gent->s.clientNum] > 0) // if we aren't talking, then it will be 0, -1 for talking but paused { - anim = FACE_TALK1 + gi.VoiceVolume[cent->gent->s.clientNum] -1; - } - else if (gi.VoiceVolume[cent->gent->s.clientNum] == 0) //don't do aux if in a slient part of speech - {//not talking - if (cent->gent->client->facial_aux < 0) // are we auxing ? - { //yes - if (-(cent->gent->client->facial_aux) < cg.time)// are we done auxing ? - { // yes, reset aux timer + anim = FACE_TALK1 + gi.VoiceVolume[cent->gent->s.clientNum] - 1; + } else if (gi.VoiceVolume[cent->gent->s.clientNum] == 0) // don't do aux if in a slient part of speech + { // not talking + if (cent->gent->client->facial_aux < 0) // are we auxing ? + { // yes + if (-(cent->gent->client->facial_aux) < cg.time) // are we done auxing ? + { // yes, reset aux timer cent->gent->client->facial_aux = cg.time + Q_flrand(7000.0, 10000.0); - } - else - { // not yet, so choose aux + } else { // not yet, so choose aux anim = FACE_ALERT; } - } - else // no we aren't auxing - { // but should we start ? - if (cent->gent->client->facial_aux < cg.time) - {//yes + } else // no we aren't auxing + { // but should we start ? + if (cent->gent->client->facial_aux < cg.time) { // yes anim = FACE_ALERT; // set aux timer cent->gent->client->facial_aux = -(cg.time + 2000.0); } } - if (anim != -1) //we we are auxing, see if we should override with a frown + if (anim != -1) // we we are auxing, see if we should override with a frown { - if (cent->gent->client->facial_frown < 0)// are we frowning ? - { // yes, - if (-(cent->gent->client->facial_frown) < cg.time)//are we done frowning ? - { // yes, reset frown timer + if (cent->gent->client->facial_frown < 0) // are we frowning ? + { // yes, + if (-(cent->gent->client->facial_frown) < cg.time) // are we done frowning ? + { // yes, reset frown timer cent->gent->client->facial_frown = cg.time + Q_flrand(7000.0, 10000.0); - } - else - { // not yet, so choose frown + } else { // not yet, so choose frown anim = FACE_FROWN; } - } - else// no we aren't frowning - { // but should we start ? - if (cent->gent->client->facial_frown < cg.time) - { + } else // no we aren't frowning + { // but should we start ? + if (cent->gent->client->facial_frown < cg.time) { anim = FACE_FROWN; // set frown timer cent->gent->client->facial_frown = -(cg.time + 2000.0); @@ -3853,11 +3177,10 @@ qboolean CG_G2PlayerHeadAnims( centity_t *cent ) } } - }//talking - }//dead - if (anim != -1) - { - CG_G2SetHeadAnim( cent, anim ); + } // talking + } // dead + if (anim != -1) { + CG_G2SetHeadAnim(cent, anim); return qtrue; } return qfalse; @@ -3868,151 +3191,127 @@ qboolean CG_G2PlayerHeadAnims( centity_t *cent ) CG_PlayerHeadExtension ------------------------- */ -int CG_PlayerHeadExtension( centity_t *cent, refEntity_t *head ) -{ - clientInfo_t *ci = ¢->gent->client->clientInfo;; +int CG_PlayerHeadExtension(centity_t *cent, refEntity_t *head) { + clientInfo_t *ci = ¢->gent->client->clientInfo; + ; // if we have facial texture extensions, go get the sound override and add it to the face skin // if we aren't talking, then it will be 0 - if (ci->extensions && (gi.VoiceVolume[cent->gent->s.clientNum] > 0)) - {//FIXME: When talking, look at talkTarget, if any - //ALSO: When talking, add a head bob/movement on syllables - when gi.VoiceVolume[] changes drastically - - if ( cent->gent->health <= 0 ) - {//Dead people close their eyes and don't make faces! They also tell no tales... BUM BUM BAHHHHHHH! - //Make them always blink and frown - head->customSkin = ci->headSkin + 3; - return qtrue; - } - - head->customSkin = ci->headSkin + 4+gi.VoiceVolume[cent->gent->s.clientNum]; - //reset the frown and blink timers - } - else - // ok, we have facial extensions, but we aren't speaking. Lets decide if we need to frown or blink - if (ci->extensions) - { - int add_in = 0; + if (ci->extensions && (gi.VoiceVolume[cent->gent->s.clientNum] > 0)) { // FIXME: When talking, look at talkTarget, if any + // ALSO: When talking, add a head bob/movement on syllables - when gi.VoiceVolume[] changes drastically - // deal with blink first - - //Dead people close their eyes and don't make faces! They also tell no tales... BUM BUM BAHHHHHHH! - if ( cent->gent->health <= 0 ) - { - //Make them always blink and frown + if (cent->gent->health <= 0) { // Dead people close their eyes and don't make faces! They also tell no tales... BUM BUM BAHHHHHHH! + // Make them always blink and frown head->customSkin = ci->headSkin + 3; return qtrue; } - if (!cent->gent->client->facial_blink) - { // reset blink timer - cent->gent->client->facial_blink = cg.time + Q_flrand(3000.0, 5000.0); - cent->gent->client->facial_frown = cg.time + Q_flrand(6000.0, 10000.0); - cent->gent->client->facial_aux = cg.time + Q_flrand(6000.0, 10000.0); - } + head->customSkin = ci->headSkin + 4 + gi.VoiceVolume[cent->gent->s.clientNum]; + // reset the frown and blink timers + } else + // ok, we have facial extensions, but we aren't speaking. Lets decide if we need to frown or blink + if (ci->extensions) { + int add_in = 0; + // deal with blink first - // now deal with auxing - // are we frowning ? - if (cent->gent->client->facial_aux < 0) - { - // are we done frowning ? - if (-(cent->gent->client->facial_aux) < cg.time) - { - // reset frown timer - cent->gent->client->facial_aux = cg.time + Q_flrand(6000.0, 10000.0); - } - else - { - // yes so set offset to frown - add_in = 4; - } - } - // no we aren't frowning - else - { - // but should we start ? - if (cent->gent->client->facial_aux < cg.time) - { - add_in = 4; - // set blink timer - cent->gent->client->facial_aux = -(cg.time + 3000.0); + // Dead people close their eyes and don't make faces! They also tell no tales... BUM BUM BAHHHHHHH! + if (cent->gent->health <= 0) { + // Make them always blink and frown + head->customSkin = ci->headSkin + 3; + return qtrue; } - } - // now, if we aren't auxing - lets see if we should be blinking or frowning - if (!add_in) - { - if( gi.VoiceVolume[cent->gent->s.clientNum] == -1 ) - {//then we're talking and don't want to use blinking normal frames, force open eyes. - add_in = 0; - // reset blink timer + if (!cent->gent->client->facial_blink) { // reset blink timer cent->gent->client->facial_blink = cg.time + Q_flrand(3000.0, 5000.0); + cent->gent->client->facial_frown = cg.time + Q_flrand(6000.0, 10000.0); + cent->gent->client->facial_aux = cg.time + Q_flrand(6000.0, 10000.0); } - // are we blinking ? - else if (cent->gent->client->facial_blink < 0) - { - // yes so set offset to blink - add_in = 1; - - // are we done blinking ? - if (-(cent->gent->client->facial_blink) < cg.time) - { - add_in = 0; - // reset blink timer - cent->gent->client->facial_blink = cg.time + Q_flrand(3000.0, 5000.0); + // now deal with auxing + // are we frowning ? + if (cent->gent->client->facial_aux < 0) { + // are we done frowning ? + if (-(cent->gent->client->facial_aux) < cg.time) { + // reset frown timer + cent->gent->client->facial_aux = cg.time + Q_flrand(6000.0, 10000.0); + } else { + // yes so set offset to frown + add_in = 4; } } - // no we aren't blinking - else - { + // no we aren't frowning + else { // but should we start ? - if (cent->gent->client->facial_blink < cg.time) - { - add_in = 1; + if (cent->gent->client->facial_aux < cg.time) { + add_in = 4; // set blink timer - cent->gent->client->facial_blink = -(cg.time + 200.0); + cent->gent->client->facial_aux = -(cg.time + 3000.0); } } - // now deal with frowning - // are we frowning ? - if (cent->gent->client->facial_frown < 0) - { + // now, if we aren't auxing - lets see if we should be blinking or frowning + if (!add_in) { + if (gi.VoiceVolume[cent->gent->s.clientNum] == -1) { // then we're talking and don't want to use blinking normal frames, force open eyes. + add_in = 0; + // reset blink timer + cent->gent->client->facial_blink = cg.time + Q_flrand(3000.0, 5000.0); + } + // are we blinking ? + else if (cent->gent->client->facial_blink < 0) { - // yes so set offset to frown - add_in += 2; + // yes so set offset to blink + add_in = 1; - // are we done frowning ? - if (-(cent->gent->client->facial_frown) < cg.time) - { - add_in -= 2; - // reset frown timer - cent->gent->client->facial_frown = cg.time + Q_flrand(6000.0, 10000.0); + // are we done blinking ? + if (-(cent->gent->client->facial_blink) < cg.time) { + add_in = 0; + // reset blink timer + cent->gent->client->facial_blink = cg.time + Q_flrand(3000.0, 5000.0); + } } - } - // no we aren't frowning - else - { - // but should we start ? - if (cent->gent->client->facial_frown < cg.time) - { + // no we aren't blinking + else { + // but should we start ? + if (cent->gent->client->facial_blink < cg.time) { + add_in = 1; + // set blink timer + cent->gent->client->facial_blink = -(cg.time + 200.0); + } + } + + // now deal with frowning + // are we frowning ? + if (cent->gent->client->facial_frown < 0) { + + // yes so set offset to frown add_in += 2; - // set blink timer - cent->gent->client->facial_frown = -(cg.time + 3000.0); + + // are we done frowning ? + if (-(cent->gent->client->facial_frown) < cg.time) { + add_in -= 2; + // reset frown timer + cent->gent->client->facial_frown = cg.time + Q_flrand(6000.0, 10000.0); + } + } + // no we aren't frowning + else { + // but should we start ? + if (cent->gent->client->facial_frown < cg.time) { + add_in += 2; + // set blink timer + cent->gent->client->facial_frown = -(cg.time + 3000.0); + } } } - } - // add in whatever we should - head->customSkin = ci->headSkin + add_in; - } - // at this point, we don't have any facial extensions, so who cares ? - else - { - head->customSkin = ci->headSkin; - } + // add in whatever we should + head->customSkin = ci->headSkin + add_in; + } + // at this point, we don't have any facial extensions, so who cares ? + else { + head->customSkin = ci->headSkin; + } return qtrue; } @@ -4022,23 +3321,19 @@ int CG_PlayerHeadExtension( centity_t *cent, refEntity_t *head ) // // Can pass in NULL for the axis //-------------------------------------------------------------- -void CG_GetTagWorldPosition( refEntity_t *model, char *tag, vec3_t pos, vec3_t axis[3] ) -{ - orientation_t orientation; +void CG_GetTagWorldPosition(refEntity_t *model, char *tag, vec3_t pos, vec3_t axis[3]) { + orientation_t orientation; // Get the requested tag - cgi_R_LerpTag( &orientation, model->hModel, model->oldframe, model->frame, - 1.0f - model->backlerp, tag ); + cgi_R_LerpTag(&orientation, model->hModel, model->oldframe, model->frame, 1.0f - model->backlerp, tag); - VectorCopy( model->origin, pos ); - for ( int i = 0 ; i < 3 ; i++ ) - { - VectorMA( pos, orientation.origin[i], model->axis[i], pos ); + VectorCopy(model->origin, pos); + for (int i = 0; i < 3; i++) { + VectorMA(pos, orientation.origin[i], model->axis[i], pos); } - if ( axis ) - { - MatrixMultiply( orientation.axis, model->axis, axis ); + if (axis) { + MatrixMultiply(orientation.axis, model->axis, axis); } } @@ -4050,58 +3345,45 @@ CG_GetPlayerLightLevel ------------------------- */ -void CG_GetPlayerLightLevel( centity_t *cent ) -{ - vec3_t ambient={0}, directed, lightDir; +void CG_GetPlayerLightLevel(centity_t *cent) { + vec3_t ambient = {0}, directed, lightDir; - //Poll the renderer for the light level - if ( cent->currentState.clientNum == cg.snap->ps.clientNum ) - {//hAX0R + // Poll the renderer for the light level + if (cent->currentState.clientNum == cg.snap->ps.clientNum) { // hAX0R ambient[0] = 666; } - cgi_R_GetLighting( cent->lerpOrigin, ambient, directed, lightDir ); + cgi_R_GetLighting(cent->lerpOrigin, ambient, directed, lightDir); - //Get the maximum value for the player + // Get the maximum value for the player cent->gent->lightLevel = directed[0]; - if ( directed[1] > cent->gent->lightLevel ) + if (directed[1] > cent->gent->lightLevel) cent->gent->lightLevel = directed[1]; - if ( directed[2] > cent->gent->lightLevel ) + if (directed[2] > cent->gent->lightLevel) cent->gent->lightLevel = directed[2]; - if ( cent->gent->client->ps.weapon == WP_SABER && cent->gent->client->ps.saberLength > 0 ) - { - cent->gent->lightLevel += (cent->gent->client->ps.saberLength/cent->gent->client->ps.saberLengthMax)*200; + if (cent->gent->client->ps.weapon == WP_SABER && cent->gent->client->ps.saberLength > 0) { + cent->gent->lightLevel += (cent->gent->client->ps.saberLength / cent->gent->client->ps.saberLengthMax) * 200; } } -int CG_SaberHumSoundForEnt( gentity_t *gent ) -{ - //now: based on saber type and npc, pick correct hum sound - int saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ); - if ( gent && gent->client ) - { - if ( gent->client->NPC_class == CLASS_DESANN ) - {//desann - saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum2.wav" ); - } - else if ( gent->client->NPC_class == CLASS_LUKE ) - {//luke - saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum5.wav" ); - } - else if ( gent->client->NPC_class == CLASS_KYLE ) - {//Kyle NPC and player - saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum4.wav" ); - } - else if ( gent->client->playerTeam == TEAM_ENEMY )//NPC_class == CLASS_TAVION ) - {//reborn, shadowtroopers, tavion - saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum3.wav" ); - } - else - {//allies - //use default - //saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ); +int CG_SaberHumSoundForEnt(gentity_t *gent) { + // now: based on saber type and npc, pick correct hum sound + int saberHumSound = cgi_S_RegisterSound("sound/weapons/saber/saberhum1.wav"); + if (gent && gent->client) { + if (gent->client->NPC_class == CLASS_DESANN) { // desann + saberHumSound = cgi_S_RegisterSound("sound/weapons/saber/saberhum2.wav"); + } else if (gent->client->NPC_class == CLASS_LUKE) { // luke + saberHumSound = cgi_S_RegisterSound("sound/weapons/saber/saberhum5.wav"); + } else if (gent->client->NPC_class == CLASS_KYLE) { // Kyle NPC and player + saberHumSound = cgi_S_RegisterSound("sound/weapons/saber/saberhum4.wav"); + } else if (gent->client->playerTeam == TEAM_ENEMY) // NPC_class == CLASS_TAVION ) + { // reborn, shadowtroopers, tavion + saberHumSound = cgi_S_RegisterSound("sound/weapons/saber/saberhum3.wav"); + } else { // allies + // use default + // saberHumSound = cgi_S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ); } } return saberHumSound; @@ -4113,41 +3395,28 @@ CG_StopWeaponSounds Stops any weapon sounds as needed =============== */ -void CG_StopWeaponSounds( centity_t *cent ) -{ - qboolean weak = qfalse; - weaponInfo_t *weapon = &cg_weapons[ cent->currentState.weapon ]; +void CG_StopWeaponSounds(centity_t *cent) { + qboolean weak = qfalse; + weaponInfo_t *weapon = &cg_weapons[cent->currentState.weapon]; - if ( cent->currentState.weapon == WP_SABER ) - { - if ( cent->gent && cent->gent->client && ( cent->currentState.saberInFlight || !cent->gent->client->ps.saberActive/*!cent->currentState.saberActive*/ ) ) - { + if (cent->currentState.weapon == WP_SABER) { + if (cent->gent && cent->gent->client && (cent->currentState.saberInFlight || !cent->gent->client->ps.saberActive /*!cent->currentState.saberActive*/)) { return; } - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - CG_SaberHumSoundForEnt( &g_entities[cent->currentState.clientNum] ) ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, CG_SaberHumSoundForEnt(&g_entities[cent->currentState.clientNum])); return; } - if ( cent->currentState.weapon == WP_STUN_BATON ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - weapon->firingSound ); + if (cent->currentState.weapon == WP_STUN_BATON) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); return; } - if ( !( cent->currentState.eFlags & EF_FIRING ) ) - { - if ( cent->pe.lightningFiring ) - { - if ( weapon->stopSound ) - { - cgi_S_StartSound( cent->lerpOrigin, cent->currentState.number, CHAN_WEAPON, weapon->stopSound ); + if (!(cent->currentState.eFlags & EF_FIRING)) { + if (cent->pe.lightningFiring) { + if (weapon->stopSound) { + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_WEAPON, weapon->stopSound); } cent->pe.lightningFiring = qfalse; @@ -4155,92 +3424,82 @@ void CG_StopWeaponSounds( centity_t *cent ) return; } - if ( cent->gent && cent->gent->client ) - { - if ( cent->gent->client->ps.ammo[AMMO_FORCE] < 1 ) + if (cent->gent && cent->gent->client) { + if (cent->gent->client->ps.ammo[AMMO_FORCE] < 1) weak = qtrue; } - if ( cent->currentState.eFlags & EF_ALT_FIRING && !weak ) - { - if ( weapon->altFiringSound ) - { - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->altFiringSound ); + if (cent->currentState.eFlags & EF_ALT_FIRING && !weak) { + if (weapon->altFiringSound) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->altFiringSound); } cent->pe.lightningFiring = qtrue; - } - else if ( cent->currentState.eFlags & EF_FIRING ) - { + } else if (cent->currentState.eFlags & EF_FIRING) { cent->pe.lightningFiring = qtrue; - if ( weapon->firingSound ) - { + if (weapon->firingSound) { // Weak phaser sound should stutter - if ( weak && (rand() & 1) ) + if (weak && (rand() & 1)) return; - cgi_S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound ); + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); } } } - //--------------- SABER STUFF -------- -extern void CG_Smoke( vec3_t origin, vec3_t dir, float radius, float speed, qhandle_t shader, int flags); +extern void CG_Smoke(vec3_t origin, vec3_t dir, float radius, float speed, qhandle_t shader, int flags); -void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, saber_colors_t color, int rfx ) -{ - vec3_t mid, rgb={1,1,1}; - qhandle_t blade = 0, glow = 0; +void CG_DoSaber(vec3_t origin, vec3_t dir, float length, float lengthMax, saber_colors_t color, int rfx) { + vec3_t mid, rgb = {1, 1, 1}; + qhandle_t blade = 0, glow = 0; refEntity_t saber; float radiusmult; - if ( length < 0.5f ) - { + if (length < 0.5f) { // if the thing is so short, just forget even adding me. return; } // Find the midpoint of the saber for lighting purposes - VectorMA( origin, length * 0.5f, dir, mid ); + VectorMA(origin, length * 0.5f, dir, mid); - switch( color ) - { - case SABER_RED: - glow = cgs.media.redSaberGlowShader; - blade = cgs.media.redSaberCoreShader; - VectorSet( rgb, 1.0f, 0.2f, 0.2f ); - break; - case SABER_ORANGE: - glow = cgs.media.orangeSaberGlowShader; - blade = cgs.media.orangeSaberCoreShader; - VectorSet( rgb, 1.0f, 0.5f, 0.1f ); - break; - case SABER_YELLOW: - glow = cgs.media.yellowSaberGlowShader; - blade = cgs.media.yellowSaberCoreShader; - VectorSet( rgb, 1.0f, 1.0f, 0.2f ); - break; - case SABER_GREEN: - glow = cgs.media.greenSaberGlowShader; - blade = cgs.media.greenSaberCoreShader; - VectorSet( rgb, 0.2f, 1.0f, 0.2f ); - break; - case SABER_BLUE: - glow = cgs.media.blueSaberGlowShader; - blade = cgs.media.blueSaberCoreShader; - VectorSet( rgb, 0.2f, 0.4f, 1.0f ); - break; - case SABER_PURPLE: - glow = cgs.media.purpleSaberGlowShader; - blade = cgs.media.purpleSaberCoreShader; - VectorSet( rgb, 0.9f, 0.2f, 1.0f ); - break; + switch (color) { + case SABER_RED: + glow = cgs.media.redSaberGlowShader; + blade = cgs.media.redSaberCoreShader; + VectorSet(rgb, 1.0f, 0.2f, 0.2f); + break; + case SABER_ORANGE: + glow = cgs.media.orangeSaberGlowShader; + blade = cgs.media.orangeSaberCoreShader; + VectorSet(rgb, 1.0f, 0.5f, 0.1f); + break; + case SABER_YELLOW: + glow = cgs.media.yellowSaberGlowShader; + blade = cgs.media.yellowSaberCoreShader; + VectorSet(rgb, 1.0f, 1.0f, 0.2f); + break; + case SABER_GREEN: + glow = cgs.media.greenSaberGlowShader; + blade = cgs.media.greenSaberCoreShader; + VectorSet(rgb, 0.2f, 1.0f, 0.2f); + break; + case SABER_BLUE: + glow = cgs.media.blueSaberGlowShader; + blade = cgs.media.blueSaberCoreShader; + VectorSet(rgb, 0.2f, 0.4f, 1.0f); + break; + case SABER_PURPLE: + glow = cgs.media.purpleSaberGlowShader; + blade = cgs.media.purpleSaberCoreShader; + VectorSet(rgb, 0.9f, 0.2f, 1.0f); + break; } // always add a light because sabers cast a nice glow before they slice you in half!! or something... - cgi_R_AddLightToScene( mid, (length*2.0f) + (Q_flrand(0.0f, 1.0f)*8.0f), rgb[0], rgb[1], rgb[2] ); + cgi_R_AddLightToScene(mid, (length * 2.0f) + (Q_flrand(0.0f, 1.0f) * 8.0f), rgb[0], rgb[1], rgb[2]); - memset( &saber, 0, sizeof( refEntity_t )); + memset(&saber, 0, sizeof(refEntity_t)); // Saber glow is it's own ref type because it uses a ton of sprites, otherwise it would eat up too many // refEnts to do each glow blob individually @@ -4248,101 +3507,89 @@ void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, saber // Jeff, I did this because I foolishly wished to have a bright halo as the saber is unleashed. // It's not quite what I'd hoped tho. If you have any ideas, go for it! --Pat - if (length < lengthMax ) - { - radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. - } - else - { + if (length < lengthMax) { + radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. + } else { radiusmult = 1.0; } + saber.radius = (2.8 + Q_flrand(-1.0f, 1.0f) * 0.2f) * radiusmult; - saber.radius = (2.8 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - - - VectorCopy( origin, saber.origin ); - VectorCopy( dir, saber.axis[0] ); + VectorCopy(origin, saber.origin); + VectorCopy(dir, saber.axis[0]); saber.reType = RT_SABER_GLOW; saber.customShader = glow; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; saber.renderfx = rfx; - cgi_R_AddRefEntityToScene( &saber ); + cgi_R_AddRefEntityToScene(&saber); // Do the hot core - VectorMA( origin, length, dir, saber.origin ); - VectorMA( origin, -1, dir, saber.oldorigin ); + VectorMA(origin, length, dir, saber.origin); + VectorMA(origin, -1, dir, saber.oldorigin); saber.customShader = blade; saber.reType = RT_LINE; - saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f) * radiusmult; - cgi_R_AddRefEntityToScene( &saber ); + cgi_R_AddRefEntityToScene(&saber); } -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 extern markPoly_t *CG_AllocMark(); -void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) -{ -// byte colors[4]; - int i, j, numFragments; - vec3_t axis[3], originalPoints[4], mid; - vec3_t markPoints[MAX_MARK_POINTS], projection; - polyVert_t *v, verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - - if ( !cg_addMarks.integer ) { +void CG_CreateSaberMarks(vec3_t start, vec3_t end, vec3_t normal) { + // byte colors[4]; + int i, j, numFragments; + vec3_t axis[3], originalPoints[4], mid; + vec3_t markPoints[MAX_MARK_POINTS], projection; + polyVert_t *v, verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; + + if (!cg_addMarks.integer) { return; } - float radius = 0.65f; + float radius = 0.65f; - VectorSubtract( end, start, axis[1] ); - VectorNormalize( axis[1] ); + VectorSubtract(end, start, axis[1]); + VectorNormalize(axis[1]); // create the texture axis - VectorCopy( normal, axis[0] ); - CrossProduct( axis[1], axis[0], axis[2] ); + VectorCopy(normal, axis[0]); + CrossProduct(axis[1], axis[0], axis[2]); // create the full polygon that we'll project - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { originalPoints[0][i] = start[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = end[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = end[i] + radius * axis[1][i] + radius * axis[2][i]; originalPoints[3][i] = start[i] - radius * axis[1][i] + radius * axis[2][i]; } - VectorScale( normal, -1, projection ); + VectorScale(normal, -1, projection); // get the fragments - numFragments = cgi_CM_MarkFragments( 4, (const float (*)[3])originalPoints, - projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments ); - + numFragments = cgi_CM_MarkFragments(4, (const float(*)[3])originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) - { + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { // we have an upper limit on the complexity of polygons that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) - { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) - { + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { vec3_t delta; // Set up our texture coords, this may need some work - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); - VectorAdd( end, start, mid ); - VectorScale( mid, 0.5f, mid ); - VectorSubtract( v->xyz, mid, delta ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); + VectorAdd(end, start, mid); + VectorScale(mid, 0.5f, mid); + VectorSubtract(v->xyz, mid, delta); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); } // save it persistantly, do burn first @@ -4352,93 +3599,79 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) mark->markShader = cgs.media.rivetMarkShader; mark->poly.numVerts = mf->numPoints; mark->color[0] = mark->color[1] = mark->color[2] = mark->color[3] = 255; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); // And now do a glow pass // by moving the start time back, we can hack it to fade out way before the burn does mark = CG_AllocMark(); mark->time = cg.time - 8500; mark->alphaFade = qfalse; - mark->markShader = cgi_R_RegisterShader("gfx/effects/saberDamageGlow" ); + mark->markShader = cgi_R_RegisterShader("gfx/effects/saberDamageGlow"); mark->poly.numVerts = mf->numPoints; mark->color[0] = 215 + Q_flrand(0.0f, 1.0f) * 40.0f; mark->color[1] = 96 + Q_flrand(0.0f, 1.0f) * 32.0f; - mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f)*15.0f; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f) * 15.0f; + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); } } -extern void FX_AddPrimitive( CEffect **effect, int killTime ); +extern void FX_AddPrimitive(CEffect **effect, int killTime); //------------------------------------------------------- -void CG_CheckSaberInWater( centity_t *cent, centity_t *scent, int modelIndex, vec3_t origin, vec3_t angles ) -{ +void CG_CheckSaberInWater(centity_t *cent, centity_t *scent, int modelIndex, vec3_t origin, vec3_t angles) { gclient_t *client = cent->gent->client; - vec3_t saberOrg; - if ( !client ) - { + vec3_t saberOrg; + if (!client) { return; } - if ( !scent || - modelIndex == -1 || - scent->gent->ghoul2.size() <= modelIndex || - scent->gent->ghoul2[modelIndex].mModelindex == -1 ) - { + if (!scent || modelIndex == -1 || scent->gent->ghoul2.size() <= modelIndex || scent->gent->ghoul2[modelIndex].mModelindex == -1) { return; } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, saberOrg ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, saberOrg); - int contents = gi.pointcontents( saberOrg, cent->currentState.clientNum ); - if ( (contents&CONTENTS_WATER) || (contents&CONTENTS_SLIME) ) - {//still in water + int contents = gi.pointcontents(saberOrg, cent->currentState.clientNum); + if ((contents & CONTENTS_WATER) || (contents & CONTENTS_SLIME)) { // still in water client->ps.saberEventFlags |= SEF_INWATER; return; } - //not in water + // not in water client->ps.saberEventFlags &= ~SEF_INWATER; } -void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles) -{ - vec3_t org_, end,//org_future, - axis_[3] = {{0,0,0}, {0,0,0}, {0,0,0}};//, axis_future[3]={{0,0,0}, {0,0,0}, {0,0,0}}; // shut the compiler up - trace_t trace; - float length; +void CG_AddSaberBlade(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, vec3_t origin, vec3_t angles) { + vec3_t org_, end, // org_future, + axis_[3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; //, axis_future[3]={{0,0,0}, {0,0,0}, {0,0,0}}; // shut the compiler up + trace_t trace; + float length; gclient_t *client = cent->gent->client; - if ( !client ) - { + if (!client) { return; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// if (scent->gent->ghoul2.size()) - if(1) - { - if ( !scent || - modelIndex == -1 || - scent->gent->ghoul2.size() <= modelIndex || - scent->gent->ghoul2[modelIndex].mModelindex == -1 ) - { + // if (scent->gent->ghoul2.size()) + if (1) { + if (!scent || modelIndex == -1 || scent->gent->ghoul2.size() <= modelIndex || scent->gent->ghoul2[modelIndex].mModelindex == -1) { return; } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, angles, origin, cg.time, cgs.model_draw, scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_); - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_[0]);//was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_[0]); // was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful - //Now figure out where this info will be next frame + // Now figure out where this info will be next frame /* { vec3_t futureOrigin, futureAngles, orgDiff, angDiff; @@ -4463,153 +3696,127 @@ Ghoul2 Insert Start } // figure out where the actual model muzzle will be after next server frame. - gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, futureAngles, futureOrigin, futuretime, cgs.model_draw, scent->currentState.modelScale); + gi.G2API_GetBoltMatrix(scent->gent->ghoul2, modelIndex, 0, &boltMatrix, futureAngles, futureOrigin, futuretime, cgs.model_draw, + scent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org_future); - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_future[0]);//was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_X, axis_future[0]);//was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' + awful } */ - } - else - { - CG_GetTagWorldPosition( saber, "tag_flash", org_, axis_ ); + } else { + CG_GetTagWorldPosition(saber, "tag_flash", org_, axis_); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - //store where saber is this frame - VectorCopy( org_, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( axis_[0], cent->gent->client->renderInfo.muzzleDir ); + // store where saber is this frame + VectorCopy(org_, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(axis_[0], cent->gent->client->renderInfo.muzzleDir); cent->gent->client->renderInfo.mPCalcTime = cg.time; - //length for purposes of rendering and marks trace will be longer than blade so we don't damage past a wall's surface - if ( cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax ) - { - if ( cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax - 8 ) - { + // length for purposes of rendering and marks trace will be longer than blade so we don't damage past a wall's surface + if (cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax) { + if (cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax - 8) { length = cent->gent->client->ps.saberLength + 8; - } - else - { + } else { length = cent->gent->client->ps.saberLengthMax; } - } - else - { + } else { length = cent->gent->client->ps.saberLength; } - VectorMA( org_, length, axis_[0], end ); + VectorMA(org_, length, axis_[0], end); // Now store where the saber will be after next frame. - //VectorCopy(org_future, cent->gent->client->renderInfo.muzzlePointNext); - //VectorCopy(axis_future[0], cent->gent->client->renderInfo.muzzleDirNext); + // VectorCopy(org_future, cent->gent->client->renderInfo.muzzlePointNext); + // VectorCopy(axis_future[0], cent->gent->client->renderInfo.muzzleDirNext); - VectorAdd( end, axis_[0], end ); + VectorAdd(end, axis_[0], end); // If the saber is in flight we shouldn't trace from the player to the muzzle point - if ( cent->currentState.saberInFlight ) - { + if (cent->currentState.saberInFlight) { trace.fraction = 1.0f; - } - else - { - gi.trace( &trace, cent->lerpOrigin, NULL, NULL, cent->gent->client->renderInfo.muzzlePoint, cent->currentState.number, CONTENTS_SOLID, G2_NOCOLLIDE, 0 ); + } else { + gi.trace(&trace, cent->lerpOrigin, NULL, NULL, cent->gent->client->renderInfo.muzzlePoint, cent->currentState.number, CONTENTS_SOLID, G2_NOCOLLIDE, 0); } - if ( trace.fraction < 1.0f ) - { + if (trace.fraction < 1.0f) { // Saber is on the other side of a wall cent->gent->client->ps.saberLength = 0.1f; cent->gent->client->ps.saberEventFlags &= ~SEF_INWATER; - } - else - { - for ( int i = 0; i < 1; i++ )//was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad if we hit a corner, blade is still 8 longer than hit + } else { + for (int i = 0; i < 1; i++) // was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad + // if we hit a corner, blade is still 8 longer than hit { - if ( i ) - {//tracing from end to base - //cgi_CM_BoxTrace( &trace, end, org_, NULL, NULL, 0, MASK_SHOT ); - gi.trace( &trace, end, NULL, NULL, org_, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0 ); - } - else - {//tracing from base to end - //cgi_CM_BoxTrace( &trace, end, org_, NULL, NULL, 0, MASK_SHOT ); - gi.trace( &trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID|CONTENTS_WATER|CONTENTS_SLIME, G2_NOCOLLIDE, 0 ); + if (i) { // tracing from end to base + // cgi_CM_BoxTrace( &trace, end, org_, NULL, NULL, 0, MASK_SHOT ); + gi.trace(&trace, end, NULL, NULL, org_, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + } else { // tracing from base to end + // cgi_CM_BoxTrace( &trace, end, org_, NULL, NULL, 0, MASK_SHOT ); + gi.trace(&trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID | CONTENTS_WATER | CONTENTS_SLIME, G2_NOCOLLIDE, 0); } - if ( trace.fraction < 1.0f ) - { - if ( (trace.contents&CONTENTS_WATER) || (trace.contents&CONTENTS_SLIME) ) - { + if (trace.fraction < 1.0f) { + if ((trace.contents & CONTENTS_WATER) || (trace.contents & CONTENTS_SLIME)) { /* if ( !(cent->gent->client->ps.saberEventFlags&SEF_INWATER) ) { } */ - if ( !Q_irand( 0, 10 ) ) - {//FIXME: don't do this this way.... :) - vec3_t spot; - VectorCopy( trace.endpos, spot ); + if (!Q_irand(0, 10)) { // FIXME: don't do this this way.... :) + vec3_t spot; + VectorCopy(trace.endpos, spot); spot[2] += 4; - G_PlayEffect( "saber/boil", spot ); - cgi_S_StartSound ( spot, -1, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/hitwater.wav" ) ); + G_PlayEffect("saber/boil", spot); + cgi_S_StartSound(spot, -1, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/saber/hitwater.wav")); } - //cent->gent->client->ps.saberEventFlags |= SEF_INWATER; - //don't do other trace + // cent->gent->client->ps.saberEventFlags |= SEF_INWATER; + // don't do other trace i = 1; - } - else - { - theFxScheduler.PlayEffect( "spark", trace.endpos, trace.plane.normal ); + } else { + theFxScheduler.PlayEffect("spark", trace.endpos, trace.plane.normal); // All I need is a bool to mark whether I have a previous point to work with. //....come up with something better.. - if ( client->saberTrail.haveOldPos[i] ) - { - if ( trace.entityNum == ENTITYNUM_WORLD ) - {//only put marks on architecture + if (client->saberTrail.haveOldPos[i]) { + if (trace.entityNum == ENTITYNUM_WORLD) { // only put marks on architecture // Let's do some cool burn/glowing mark bits!!! - CG_CreateSaberMarks( client->saberTrail.oldPos[i], trace.endpos, trace.plane.normal ); + CG_CreateSaberMarks(client->saberTrail.oldPos[i], trace.endpos, trace.plane.normal); - //make a sound - if ( cg.time - cent->gent->client->ps.saberHitWallSoundDebounceTime >= 100 ) - {//ugh, need to have a real sound debouncer... or do this game-side + // make a sound + if (cg.time - cent->gent->client->ps.saberHitWallSoundDebounceTime >= + 100) { // ugh, need to have a real sound debouncer... or do this game-side cent->gent->client->ps.saberHitWallSoundDebounceTime = cg.time; - cgi_S_StartSound ( cent->lerpOrigin, cent->currentState.clientNum, CHAN_ITEM, cgi_S_RegisterSound( va ( "sound/weapons/saber/saberhitwall%d.wav", Q_irand( 1, 3 ) ) ) ); + cgi_S_StartSound(cent->lerpOrigin, cent->currentState.clientNum, CHAN_ITEM, + cgi_S_RegisterSound(va("sound/weapons/saber/saberhitwall%d.wav", Q_irand(1, 3)))); } } - } - else - { + } else { // if we impact next frame, we'll mark a slash mark client->saberTrail.haveOldPos[i] = qtrue; } } // stash point so we can connect-the-dots later - VectorCopy( trace.endpos, client->saberTrail.oldPos[i] ); - VectorCopy( trace.plane.normal, client->saberTrail.oldNormal[i] ); - - if ( !i ) - { - //Now that we don't let the blade go through walls, we need to shorten the blade when it hits one - cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLength * trace.fraction;//this will stop damage from going through walls - if ( cent->gent->client->ps.saberLength <= 0.1f ) - {//SIGH... hack so it doesn't play the saber turn-on sound that plays when you first turn the saber on (assumed when saber is active but length is zero) - cent->gent->client->ps.saberLength = 0.1f;//FIXME: may go through walls still?? + VectorCopy(trace.endpos, client->saberTrail.oldPos[i]); + VectorCopy(trace.plane.normal, client->saberTrail.oldNormal[i]); + + if (!i) { + // Now that we don't let the blade go through walls, we need to shorten the blade when it hits one + cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLength * trace.fraction; // this will stop damage from going through walls + if (cent->gent->client->ps.saberLength <= 0.1f) { // SIGH... hack so it doesn't play the saber turn-on sound that plays when you first turn + // the saber on (assumed when saber is active but length is zero) + cent->gent->client->ps.saberLength = 0.1f; // FIXME: may go through walls still?? } - //FIXME: should probably re-extend instantly, not use the "turning-on" growth rate + // FIXME: should probably re-extend instantly, not use the "turning-on" growth rate } - } - else - { + } else { cent->gent->client->ps.saberEventFlags &= ~SEF_INWATER; - if ( client->saberTrail.haveOldPos[i] ) - { + if (client->saberTrail.haveOldPos[i]) { // Hmmm, no impact this frame, but we have an old point // Let's put the mark there, we should use an endcap mark to close the line, but we // can probably just get away with a round mark - //CG_ImpactMark( cgs.media.rivetMarkShader, client->saberTrail.oldPos[i], client->saberTrail.oldNormal[i], + // CG_ImpactMark( cgs.media.rivetMarkShader, client->saberTrail.oldPos[i], client->saberTrail.oldNormal[i], // 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); } @@ -4619,67 +3826,64 @@ Ghoul2 Insert End } } - saberTrail_t *saberTrail = &client->saberTrail; + saberTrail_t *saberTrail = &client->saberTrail; -#define SABER_TRAIL_TIME 40.0f +#define SABER_TRAIL_TIME 40.0f // if we happen to be timescaled or running in a high framerate situation, we don't want to flood // the system with very small trail slices...but perhaps doing it by distance would yield better results? - if ( saberTrail->lastTime > cg.time ) - {//after a pause, cg.time jumps ahead in time for one frame - //and lastTime gets set to that and will freak out, so, since - //it's never valid for saberTrail->lastTime to be > cg.time, - //cap it to cg.time here + if (saberTrail->lastTime > cg.time) { // after a pause, cg.time jumps ahead in time for one frame + // and lastTime gets set to that and will freak out, so, since + // it's never valid for saberTrail->lastTime to be > cg.time, + // cap it to cg.time here saberTrail->lastTime = cg.time; } - if ( cg.time > saberTrail->lastTime + 2 && saberTrail->inAction ) // 2ms + if (cg.time > saberTrail->lastTime + 2 && saberTrail->inAction) // 2ms { - if ( saberTrail->inAction && cg.time < saberTrail->lastTime + 300 ) // if we have a stale segment, don't draw until we have a fresh one + if (saberTrail->inAction && cg.time < saberTrail->lastTime + 300) // if we have a stale segment, don't draw until we have a fresh one { - vec3_t rgb1={255,255,255}; + vec3_t rgb1 = {255, 255, 255}; - switch( client->ps.saberColor ) - { - case SABER_RED: - VectorSet( rgb1, 255.0f, 0.0f, 0.0f ); - break; - case SABER_ORANGE: - VectorSet( rgb1, 255.0f, 64.0f, 0.0f ); - break; - case SABER_YELLOW: - VectorSet( rgb1, 255.0f, 255.0f, 0.0f ); - break; - case SABER_GREEN: - VectorSet( rgb1, 0.0f, 255.0f, 0.0f ); - break; - case SABER_BLUE: - VectorSet( rgb1, 0.0f, 64.0f, 255.0f ); - break; - case SABER_PURPLE: - VectorSet( rgb1, 220.0f, 0.0f, 255.0f ); - break; + switch (client->ps.saberColor) { + case SABER_RED: + VectorSet(rgb1, 255.0f, 0.0f, 0.0f); + break; + case SABER_ORANGE: + VectorSet(rgb1, 255.0f, 64.0f, 0.0f); + break; + case SABER_YELLOW: + VectorSet(rgb1, 255.0f, 255.0f, 0.0f); + break; + case SABER_GREEN: + VectorSet(rgb1, 0.0f, 255.0f, 0.0f); + break; + case SABER_BLUE: + VectorSet(rgb1, 0.0f, 64.0f, 255.0f); + break; + case SABER_PURPLE: + VectorSet(rgb1, 220.0f, 0.0f, 255.0f); + break; } float diff = cg.time - saberTrail->lastTime; // I'm not sure that clipping this is really the best idea - if ( diff <= SABER_TRAIL_TIME * 2 ) - { - float oldAlpha = 1.0f - ( diff / SABER_TRAIL_TIME ); + if (diff <= SABER_TRAIL_TIME * 2) { + float oldAlpha = 1.0f - (diff / SABER_TRAIL_TIME); // build a quad CTrail *fx = new CTrail; // Go from new muzzle to new end...then to old end...back down to old muzzle...finally // connect back to the new muzzle...this is our trail quad - VectorCopy( org_, fx->mVerts[0].origin ); - VectorMA( end, 3.0f, axis_[0], fx->mVerts[1].origin ); + VectorCopy(org_, fx->mVerts[0].origin); + VectorMA(end, 3.0f, axis_[0], fx->mVerts[1].origin); - VectorCopy( saberTrail->tip, fx->mVerts[2].origin ); - VectorCopy( saberTrail->base, fx->mVerts[3].origin ); + VectorCopy(saberTrail->tip, fx->mVerts[2].origin); + VectorCopy(saberTrail->base, fx->mVerts[3].origin); // New muzzle - VectorCopy( rgb1, fx->mVerts[0].rgb ); + VectorCopy(rgb1, fx->mVerts[0].rgb); fx->mVerts[0].alpha = 255.0f; fx->mVerts[0].ST[0] = 0.0f; @@ -4688,7 +3892,7 @@ Ghoul2 Insert End fx->mVerts[0].destST[1] = 0.99f; // new tip - VectorCopy( rgb1, fx->mVerts[1].rgb ); + VectorCopy(rgb1, fx->mVerts[1].rgb); fx->mVerts[1].alpha = 255.0f; fx->mVerts[1].ST[0] = 0.0f; @@ -4697,7 +3901,7 @@ Ghoul2 Insert End fx->mVerts[1].destST[1] = 0.0f; // old tip - VectorCopy( rgb1, fx->mVerts[2].rgb ); + VectorCopy(rgb1, fx->mVerts[2].rgb); fx->mVerts[2].alpha = 255.0f; fx->mVerts[2].ST[0] = 0.99f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -4706,7 +3910,7 @@ Ghoul2 Insert End fx->mVerts[2].destST[1] = 0.0f; // old muzzle - VectorCopy( rgb1, fx->mVerts[3].rgb ); + VectorCopy(rgb1, fx->mVerts[3].rgb); fx->mVerts[3].alpha = 255.0f; fx->mVerts[3].ST[0] = 0.99f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -4715,20 +3919,20 @@ Ghoul2 Insert End fx->mVerts[3].destST[1] = 0.99f; fx->mShader = cgs.media.saberBlurShader; -// fx->SetFlags( FX_USE_ALPHA ); - FX_AddPrimitive( (CEffect**)&fx, SABER_TRAIL_TIME ); + // fx->SetFlags( FX_USE_ALPHA ); + FX_AddPrimitive((CEffect **)&fx, SABER_TRAIL_TIME); } } // we must always do this, even if we aren't active..otherwise we won't know where to pick up from - VectorCopy( org_, saberTrail->base ); - VectorMA( end, 3.0f, axis_[0], saberTrail->tip ); + VectorCopy(org_, saberTrail->base); + VectorMA(end, 3.0f, axis_[0], saberTrail->tip); saberTrail->lastTime = cg.time; } // Pass in the renderfx flags attached to the saber weapon model...this is done so that saber glows // will get rendered properly in a mirror...not sure if this is necessary?? - CG_DoSaber( org_, axis_[0], length, client->ps.saberLengthMax, client->ps.saberColor, renderfx ); + CG_DoSaber(org_, axis_[0], length, client->ps.saberLengthMax, client->ps.saberColor, renderfx); } //--------------- END SABER STUFF -------- @@ -4778,120 +3982,106 @@ CG_Player =============== */ -extern qboolean G_ControlledByPlayer( gentity_t *self ); -void CG_Player( centity_t *cent ) { - clientInfo_t *ci; - qboolean shadow, staticScale = qfalse; - float shadowPlane; - const weaponData_t *wData = NULL; +extern qboolean G_ControlledByPlayer(gentity_t *self); +void CG_Player(centity_t *cent) { + clientInfo_t *ci; + qboolean shadow, staticScale = qfalse; + float shadowPlane; + const weaponData_t *wData = NULL; calcedMp = qfalse; - if ( cent->currentState.eFlags & EF_NODRAW ) - { + if (cent->currentState.eFlags & EF_NODRAW) { return; } - //FIXME: make sure this thing has a gent and client - if(!cent->gent) - { + // FIXME: make sure this thing has a gent and client + if (!cent->gent) { return; } - if(!cent->gent->client) - { + if (!cent->gent->client) { return; } - //Get the player's light level for stealth calculations - CG_GetPlayerLightLevel( cent ); + // Get the player's light level for stealth calculations + CG_GetPlayerLightLevel(cent); - if ((in_camera) && !(cent->currentState.eFlags & EF_NPC)) // If player in camera then no need for shadow + if ((in_camera) && !(cent->currentState.eFlags & EF_NPC)) // If player in camera then no need for shadow { return; } - if(cent->currentState.number == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) + if (cent->currentState.number == 0 && !cg.renderingThirdPerson) //! cg_thirdPerson.integer ) { calcedMp = qtrue; } ci = ¢->gent->client->clientInfo; - if ( !ci->infoValid ) - { + if (!ci->infoValid) { return; } - if ( cent->currentState.vehicleModel != 0 ) - {//Using an alternate (md3 for now) model - refEntity_t ent; - vec3_t tempAngles = {0, 0, 0}, velocity = {0, 0, 0}; - float speed; - memset (&ent, 0, sizeof(ent)); + if (cent->currentState.vehicleModel != 0) { // Using an alternate (md3 for now) model + refEntity_t ent; + vec3_t tempAngles = {0, 0, 0}, velocity = {0, 0, 0}; + float speed; + memset(&ent, 0, sizeof(ent)); - if ( !cg.renderingThirdPerson ) - { - gi.SendConsoleCommand( "cg_thirdperson 1\n" ); + if (!cg.renderingThirdPerson) { + gi.SendConsoleCommand("cg_thirdperson 1\n"); return; } ent.renderfx = 0; - if ( cent->currentState.number == cg.snap->ps.clientNum ) - {//player - if ( !cg.renderingThirdPerson ) - { - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + if (cent->currentState.number == cg.snap->ps.clientNum) { // player + if (!cg.renderingThirdPerson) { + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } } // add the shadow - shadow = CG_PlayerShadow( cent, &shadowPlane ); + shadow = CG_PlayerShadow(cent, &shadowPlane); - if ( (cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow) ) - { + if ((cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow)) { ent.renderfx |= RF_SHADOW_PLANE; } - ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all - if ( cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT ) - { - ent.renderfx |= RF_MORELIGHT; //bigger than normal min light + ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + if (cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT) { + ent.renderfx |= RF_MORELIGHT; // bigger than normal min light } - VectorCopy( cent->lerpOrigin, ent.origin ); - VectorCopy( cent->lerpOrigin, ent.oldorigin ); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); - VectorSet( tempAngles, 0, cent->lerpAngles[1], 0 ); - VectorCopy( tempAngles, cg.refdefViewAngles ); + VectorSet(tempAngles, 0, cent->lerpAngles[1], 0); + VectorCopy(tempAngles, cg.refdefViewAngles); tempAngles[0] = cent->lerpAngles[0]; - if ( tempAngles[0] > 30 ) - { + if (tempAngles[0] > 30) { tempAngles[0] = 30; - } - else if ( tempAngles[0] < -30 ) - { + } else if (tempAngles[0] < -30) { tempAngles[0] = -30; } - //FIXME: roll - VectorCopy( cent->gent->client->ps.velocity, velocity ); - speed = VectorNormalize( velocity ); + // FIXME: roll + VectorCopy(cent->gent->client->ps.velocity, velocity); + speed = VectorNormalize(velocity); - if ( speed ) - { - vec3_t rt; - float side; + if (speed) { + vec3_t rt; + float side; // Magic number fun! Speed is used for banking, so modulate the speed by a sine wave - speed *= sin( (cg.frametime + 200 ) * 0.003 ); + speed *= sin((cg.frametime + 200) * 0.003); // Clamp to prevent harsh rolling - if ( speed > 60 ) + if (speed > 60) speed = 60; - AngleVectors( tempAngles, NULL, rt, NULL ); - side = speed * DotProduct( velocity, rt ); + AngleVectors(tempAngles, NULL, rt, NULL); + side = speed * DotProduct(velocity, rt); tempAngles[2] -= side; } /* @@ -4906,19 +4096,20 @@ void CG_Player( centity_t *cent ) { } */ - AnglesToAxis( tempAngles, ent.axis ); - ScaleModelAxis( &ent ); + AnglesToAxis(tempAngles, ent.axis); + ScaleModelAxis(&ent); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.lightingOrigin); - //FIXME: what if it's a G2 model? + // FIXME: what if it's a G2 model? /* if ghoul model { gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); cent->gent->client->renderInfo.mPCalcTime = cg.time; - gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); // update where we think the head is, and where the eyes point gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.eyePoint); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tempAxis);//was POSITIVE_X @@ -4927,363 +4118,299 @@ void CG_Player( centity_t *cent ) { else */ { - //FIXME: properly generate muzzlePoint - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.muzzlePoint ); - AngleVectors( cent->lerpAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL ); + // FIXME: properly generate muzzlePoint + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.muzzlePoint); + AngleVectors(cent->lerpAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL); cent->gent->client->renderInfo.mPCalcTime = cg.time; - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles ); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles); ent.hModel = cgs.model_draw[cent->currentState.vehicleModel]; } - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); return; } - if ( cent->currentState.weapon ) - { + if (cent->currentState.weapon) { wData = &weaponData[cent->currentState.weapon]; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // do this if we are a ghoul2 model if (cent->gent->ghoul2.size()) -// if (1) + // if (1) { - refEntity_t ent; - vec3_t tempAngles; - memset (&ent, 0, sizeof(ent)); + refEntity_t ent; + vec3_t tempAngles; + memset(&ent, 0, sizeof(ent)); - //FIXME: if at all possible, do all our sets before our gets to do only *1* G2 skeleton transform per render frame + // FIXME: if at all possible, do all our sets before our gets to do only *1* G2 skeleton transform per render frame CG_SetGhoul2Info(&ent, cent); // Weapon sounds may need to be stopped, so check now - CG_StopWeaponSounds( cent ); + CG_StopWeaponSounds(cent); // add powerups floating behind the player - CG_PlayerPowerups( cent ); + CG_PlayerPowerups(cent); // add the shadow - shadow = CG_PlayerShadow( cent, &shadowPlane ); + shadow = CG_PlayerShadow(cent, &shadowPlane); // add a water splash if partially in and out of water - CG_PlayerSplash( cent ); + CG_PlayerSplash(cent); // get the player model information ent.renderfx = 0; - if ( !cg.renderingThirdPerson || cg.zoomMode ) - {//in first person or zoomed in - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) - {//no viewentity - if ( cent->currentState.number == cg.snap->ps.clientNum ) - {//I am the player - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + if (!cg.renderingThirdPerson || cg.zoomMode) { // in first person or zoomed in + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // no viewentity + if (cent->currentState.number == cg.snap->ps.clientNum) { // I am the player + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } } - } - else if ( cent->currentState.number == cg.snap->ps.viewEntity ) - {//I am the view entity - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using first person saber test or, if so, not using saber - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + } else if (cent->currentState.number == cg.snap->ps.viewEntity) { // I am the view entity + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using first person saber test or, if so, not using saber + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } } } - if ( cent->gent->client->ps.powerups[PW_DISINT_2] > cg.time ) - {//ghost! - ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors + if (cent->gent->client->ps.powerups[PW_DISINT_2] > cg.time) { // ghost! + ent.renderfx = RF_THIRD_PERSON; // only draw in mirrors } - if ( (cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow) ) - { + if ((cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow)) { ent.renderfx |= RF_SHADOW_PLANE; } ent.shadowPlane = shadowPlane; - ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all - if ( cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT ) - { - ent.renderfx |= RF_MORELIGHT; //bigger than normal min light + ent.renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + if (cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT) { + ent.renderfx |= RF_MORELIGHT; // bigger than normal min light } - CG_RegisterWeapon( cent->currentState.weapon ); + CG_RegisterWeapon(cent->currentState.weapon); -//--------------- - if ( cent->currentState.eFlags & EF_LOCKED_TO_WEAPON && cent->gent && cent->gent->health > 0 && cent->gent->owner ) - { - centity_t *chair = &cg_entities[cent->gent->owner->s.number]; - if ( chair && chair->gent ) - { - vec3_t temp; - mdxaBone_t boltMatrix; + //--------------- + if (cent->currentState.eFlags & EF_LOCKED_TO_WEAPON && cent->gent && cent->gent->health > 0 && cent->gent->owner) { + centity_t *chair = &cg_entities[cent->gent->owner->s.number]; + if (chair && chair->gent) { + vec3_t temp; + mdxaBone_t boltMatrix; // We'll set the turret yaw directly - VectorClear( chair->gent->s.apos.trBase ); - VectorClear( temp ); + VectorClear(chair->gent->s.apos.trBase); + VectorClear(temp); chair->gent->s.apos.trBase[YAW] = cent->lerpAngles[YAW]; temp[PITCH] = -cent->lerpAngles[PITCH]; cent->lerpAngles[ROLL] = 0; - //NOTE: call this so it updates on the server and client - BG_G2SetBoneAngles( chair, chair->gent, chair->gent->lowerLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, cgs.model_draw ); - //gi.G2API_SetBoneAngles( &chair->gent->ghoul2[0], "swivel_bone", temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, cgs.model_draw ); - VectorCopy( temp, chair->gent->lastAngles ); + // NOTE: call this so it updates on the server and client + BG_G2SetBoneAngles(chair, chair->gent, chair->gent->lowerLumbarBone, temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, + cgs.model_draw); + // gi.G2API_SetBoneAngles( &chair->gent->ghoul2[0], "swivel_bone", temp, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, + // cgs.model_draw ); + VectorCopy(temp, chair->gent->lastAngles); - gi.G2API_StopBoneAnimIndex( ¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone ); + gi.G2API_StopBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->hipsBone); // Getting the seat bolt here - gi.G2API_GetBoltMatrix( chair->gent->ghoul2, chair->gent->playerModel, chair->gent->headBolt, - &boltMatrix, chair->gent->s.apos.trBase, chair->gent->currentOrigin, cg.time, - cgs.model_draw, chair->currentState.modelScale ); + gi.G2API_GetBoltMatrix(chair->gent->ghoul2, chair->gent->playerModel, chair->gent->headBolt, &boltMatrix, chair->gent->s.apos.trBase, + chair->gent->currentOrigin, cg.time, cgs.model_draw, chair->currentState.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent.origin ); - VectorCopy( ent.origin, chair->gent->pos2 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, chair->gent->pos3 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, chair->gent->pos4 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent.origin); + VectorCopy(ent.origin, chair->gent->pos2); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, chair->gent->pos3); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, chair->gent->pos4); - VectorCopy( ent.origin, ent.oldorigin ); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); // FIXME: Mike claims that hacking the eyepoint will make them shoot at me.......so, // we move up from the seat bolt and store off that point. - // VectorMA( ent.origin, -20, chair->gent->pos3, cent->gent->client->renderInfo.eyePoint ); - // VectorMA( cent->gent->client->renderInfo.eyePoint, 40, chair->gent->pos4, cent->gent->client->renderInfo.eyePoint ); + // VectorMA( ent.origin, -20, chair->gent->pos3, cent->gent->client->renderInfo.eyePoint ); + // VectorMA( cent->gent->client->renderInfo.eyePoint, 40, chair->gent->pos4, cent->gent->client->renderInfo.eyePoint ); - AnglesToAxis( cent->lerpAngles, ent.axis ); - VectorCopy( cent->lerpAngles, tempAngles);//tempAngles is needed a lot below + AnglesToAxis(cent->lerpAngles, ent.axis); + VectorCopy(cent->lerpAngles, tempAngles); // tempAngles is needed a lot below } - } - else - { -//--------------- - CG_G2PlayerAngles( cent, ent.axis, tempAngles); - //Deal with facial expressions - CG_G2PlayerHeadAnims( cent ); + } else { + //--------------- + CG_G2PlayerAngles(cent, ent.axis, tempAngles); + // Deal with facial expressions + CG_G2PlayerHeadAnims(cent); - VectorCopy( cent->lerpOrigin, ent.origin); - if (ent.modelScale[2] && ent.modelScale[2] != 1.0f) - { + VectorCopy(cent->lerpOrigin, ent.origin); + if (ent.modelScale[2] && ent.modelScale[2] != 1.0f) { ent.origin[2] += 24 * (ent.modelScale[2] - 1); } - VectorCopy( ent.origin, ent.oldorigin); - VectorCopy( ent.origin, ent.lightingOrigin ); + VectorCopy(ent.origin, ent.oldorigin); + VectorCopy(ent.origin, ent.lightingOrigin); } - if ( cent->gent && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { cent->gent->client->ps.legsYaw = tempAngles[YAW]; } ScaleModelAxis(&ent); -extern vmCvar_t cg_thirdPersonAlpha; + extern vmCvar_t cg_thirdPersonAlpha; - if ( (cent->gent->s.number == 0 || G_ControlledByPlayer( cent->gent )) ) - { + if ((cent->gent->s.number == 0 || G_ControlledByPlayer(cent->gent))) { float alpha = 1.0f; - if ( (cg.overrides.active&CG_OVERRIDE_3RD_PERSON_APH) ) - { + if ((cg.overrides.active & CG_OVERRIDE_3RD_PERSON_APH)) { alpha = cg.overrides.thirdPersonAlpha; - } - else - { + } else { alpha = cg_thirdPersonAlpha.value; } - if ( alpha < 1.0f ) - { + if (alpha < 1.0f) { ent.renderfx |= RF_ALPHA_FADE; ent.shaderRGBA[3] = (unsigned char)(alpha * 255.0f); } } - if ( !cg.renderingThirdPerson - && ( cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE ) - && !cent->gent->s.number ) - {// Yeah um, this needs to not do this quite this way - ent.customSkin = cgi_R_RegisterSkin( "models/players/kyle/model_fpls2.skin" ); //precached in g_client.cpp - //turn on arm caps - gi.G2API_SetSurfaceOnOff( ¢->gent->ghoul2[cent->gent->playerModel], "r_arm_cap_torso_off", 0 ); - gi.G2API_SetSurfaceOnOff( ¢->gent->ghoul2[cent->gent->playerModel], "l_arm_cap_torso_off", 0 ); - } - else - { + if (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) && + !cent->gent->s.number) { // Yeah um, this needs to not do this quite this way + ent.customSkin = cgi_R_RegisterSkin("models/players/kyle/model_fpls2.skin"); // precached in g_client.cpp + // turn on arm caps + gi.G2API_SetSurfaceOnOff(¢->gent->ghoul2[cent->gent->playerModel], "r_arm_cap_torso_off", 0); + gi.G2API_SetSurfaceOnOff(¢->gent->ghoul2[cent->gent->playerModel], "l_arm_cap_torso_off", 0); + } else { ent.customSkin = 0; - //turn off arm caps - gi.G2API_SetSurfaceOnOff( ¢->gent->ghoul2[cent->gent->playerModel], "r_arm_cap_torso_off", 0x00000002 ); - gi.G2API_SetSurfaceOnOff( ¢->gent->ghoul2[cent->gent->playerModel], "l_arm_cap_torso_off", 0x00000002 ); + // turn off arm caps + gi.G2API_SetSurfaceOnOff(¢->gent->ghoul2[cent->gent->playerModel], "r_arm_cap_torso_off", 0x00000002); + gi.G2API_SetSurfaceOnOff(¢->gent->ghoul2[cent->gent->playerModel], "l_arm_cap_torso_off", 0x00000002); } // We want to be able to do cool full-body type effects - CG_AddRefEntityWithPowerups( &ent, cent->currentState.powerups, cent ); + CG_AddRefEntityWithPowerups(&ent, cent->currentState.powerups, cent); - if ( cg_debugBB.integer) - { + if (cg_debugBB.integer) { CG_CreateBBRefEnts(¢->currentState, ent.origin); } - //Initialize all these to *some* valid data - VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.handRPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.handLPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.footRPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.footLPoint ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.torsoPoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.crotchPoint ); - if ( cent->currentState.number != 0 - || cg.renderingThirdPerson - || cg.snap->ps.stats[STAT_HEALTH] <= 0 - || ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//First person saber - ) - {//in some third person mode or NPC - //we don't override thes in pure 1st person because they will be set before this func - VectorCopy( ent.origin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles ); - if ( !cent->gent->client->ps.saberInFlight ) - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( ent.axis[0], cent->gent->client->renderInfo.muzzleDir ); - } - } - //now try to get the right data - - mdxaBone_t boltMatrix; - vec3_t tempAxis, G2Angles = {0, tempAngles[YAW], 0}; - - if ( cent->gent->handRBolt != -1 ) - { - //Get handRPoint - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.handRPoint ); - } - if ( cent->gent->handLBolt != -1 ) - { - //always get handLPoint too...? - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.handLPoint ); - } - if ( cent->gent->footLBolt != -1 ) - { - //get the feet - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.footLPoint ); - } - - if ( cent->gent->footRBolt != -1 ) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, - &boltMatrix, G2Angles, ent.origin, cg.time, - cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.footRPoint ); - } - - //Handle saber - if ( cent->gent && cent->gent->client && ( cent->currentState.weapon == WP_SABER || cent->currentState.saberInFlight ) && cent->gent->client->NPC_class != CLASS_ATST ) - {//FIXME: somehow saberactive is getting lost over the network - if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { + // Initialize all these to *some* valid data + VectorCopy(ent.origin, cent->gent->client->renderInfo.headPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.handRPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.handLPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.footRPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.footLPoint); + VectorCopy(ent.origin, cent->gent->client->renderInfo.torsoPoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles); + VectorCopy(ent.origin, cent->gent->client->renderInfo.crotchPoint); + if (cent->currentState.number != 0 || cg.renderingThirdPerson || cg.snap->ps.stats[STAT_HEALTH] <= 0 || + (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // First person saber + ) { // in some third person mode or NPC + // we don't override thes in pure 1st person because they will be set before this func + VectorCopy(ent.origin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles); + if (!cent->gent->client->ps.saberInFlight) { + VectorCopy(ent.origin, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(ent.axis[0], cent->gent->client->renderInfo.muzzleDir); + } + } + // now try to get the right data + + mdxaBone_t boltMatrix; + vec3_t tempAxis, G2Angles = {0, tempAngles[YAW], 0}; + + if (cent->gent->handRBolt != -1) { + // Get handRPoint + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handRBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.handRPoint); + } + if (cent->gent->handLBolt != -1) { + // always get handLPoint too...? + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->handLBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.handLPoint); + } + if (cent->gent->footLBolt != -1) { + // get the feet + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footLBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.footLPoint); + } + + if (cent->gent->footRBolt != -1) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->footRBolt, &boltMatrix, G2Angles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.footRPoint); + } + + // Handle saber + if (cent->gent && cent->gent->client && (cent->currentState.weapon == WP_SABER || cent->currentState.saberInFlight) && + cent->gent->client->NPC_class != CLASS_ATST) { // FIXME: somehow saberactive is getting lost over the network + if (cent->gent->client->ps.saberEventFlags & SEF_INWATER) { cent->gent->client->ps.saberActive = qfalse; } - if ( /*!cent->currentState.saberActive ||*/ !cent->gent->client->ps.saberActive || cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax )//hack around network lag for now - {//saber is off - if ( cent->gent->client->ps.saberLength > 0 ) - { - if ( cent->gent->client->ps.stats[STAT_HEALTH] <= 0 ) - {//dead, didn't actively turn it off - cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax/10 * cg.frametime/100; - } - else - {//actively turned it off, shrink faster - cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax/10 * cg.frametime/100; + if (/*!cent->currentState.saberActive ||*/ !cent->gent->client->ps.saberActive || + cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax) // hack around network lag for now + { // saber is off + if (cent->gent->client->ps.saberLength > 0) { + if (cent->gent->client->ps.stats[STAT_HEALTH] <= 0) { // dead, didn't actively turn it off + cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax / 10 * cg.frametime / 100; + } else { // actively turned it off, shrink faster + cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax / 10 * cg.frametime / 100; } } - } - else if ( cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax ) - {//saber is on - if ( !cent->gent->client->ps.saberLength ) - { + } else if (cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax) { // saber is on + if (!cent->gent->client->ps.saberLength) { qhandle_t saberOnSound; - if ( cent->gent->client->playerTeam == TEAM_PLAYER ) - { - saberOnSound = cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ); - } - else - { - saberOnSound = cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_on.wav" ); + if (cent->gent->client->playerTeam == TEAM_PLAYER) { + saberOnSound = cgi_S_RegisterSound("sound/weapons/saber/saberon.wav"); + } else { + saberOnSound = cgi_S_RegisterSound("sound/weapons/saber/enemy_saber_on.wav"); } - if ( !cent->gent->client->ps.weaponTime ) - {//make us play the turn on anim + if (!cent->gent->client->ps.weaponTime) { // make us play the turn on anim cent->gent->client->ps.weaponstate = WEAPON_RAISING; cent->gent->client->ps.weaponTime = 250; } - if ( cent->currentState.saberInFlight ) - {//play it on the saber - cgi_S_UpdateEntityPosition( cent->gent->client->ps.saberEntityNum, g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, saberOnSound ); - } - else - { - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_AUTO, saberOnSound ); + if (cent->currentState.saberInFlight) { // play it on the saber + cgi_S_UpdateEntityPosition(cent->gent->client->ps.saberEntityNum, g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin); + cgi_S_StartSound(NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, saberOnSound); + } else { + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, saberOnSound); } } - if ( cg.frametime > 0 ) - { - cent->gent->client->ps.saberLength += cent->gent->client->ps.saberLengthMax/10 * cg.frametime/100;//= saberLengthMax; + if (cg.frametime > 0) { + cent->gent->client->ps.saberLength += cent->gent->client->ps.saberLengthMax / 10 * cg.frametime / 100; //= saberLengthMax; } - if ( cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax ) - { + if (cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax) { cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLengthMax; } } - if ( cent->gent->client->ps.saberLength > 0 ) - { - if ( !cent->currentState.saberInFlight )//&& cent->currentState.saberActive) - {//holding the saber in-hand -// CGhoul2Info *currentModel = ¢->gent->ghoul2[1]; -// CGhoul2Info *nextModel = ¢->gent->ghoul2[1]; - //FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 - //FIXME: use an actual surfaceIndex? - if ( !gi.G2API_GetSurfaceRenderStatus( ¢->gent->ghoul2[cent->gent->playerModel], "r_hand" ) )//surf is still on + if (cent->gent->client->ps.saberLength > 0) { + if (!cent->currentState.saberInFlight) //&& cent->currentState.saberActive) + { // holding the saber in-hand + // CGhoul2Info *currentModel = ¢->gent->ghoul2[1]; + // CGhoul2Info *nextModel = ¢->gent->ghoul2[1]; + // FIXME: need a version of this that *doesn't* need the mFileName in the ghoul2 + // FIXME: use an actual surfaceIndex? + if (!gi.G2API_GetSurfaceRenderStatus(¢->gent->ghoul2[cent->gent->playerModel], "r_hand")) // surf is still on { - CG_AddSaberBlade( cent, cent, NULL, ent.renderfx, cent->gent->weaponModel, ent.origin, tempAngles); - }//else, the limb will draw the blade itself - }//in-flight saber draws it's own blade - } - else - { - if ( cent->gent->client->ps.saberLength < 0 ) - { + CG_AddSaberBlade(cent, cent, NULL, ent.renderfx, cent->gent->weaponModel, ent.origin, tempAngles); + } // else, the limb will draw the blade itself + } // in-flight saber draws it's own blade + } else { + if (cent->gent->client->ps.saberLength < 0) { cent->gent->client->ps.saberLength = 0; } - //if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { - CG_CheckSaberInWater( cent, cent, cent->gent->weaponModel, ent.origin, tempAngles ); - } + // if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) + { CG_CheckSaberInWater(cent, cent, cent->gent->weaponModel, ent.origin, tempAngles); } } - if ( cent->currentState.weapon == WP_SABER && (cent->gent->client->ps.saberLength > 0 || cent->currentState.saberInFlight) ) - { + if (cent->currentState.weapon == WP_SABER && (cent->gent->client->ps.saberLength > 0 || cent->currentState.saberInFlight)) { calcedMp = qtrue; } } - if ( cent->currentState.number != 0 - || cg.renderingThirdPerson - || cg.snap->ps.stats[STAT_HEALTH] <= 0 - || ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) )//First person saber - ) - {//if NPC, third person, or dead, unless using saber - //Get eyePoint & eyeAngles + if (cent->currentState.number != 0 || cg.renderingThirdPerson || cg.snap->ps.stats[STAT_HEALTH] <= 0 || + (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) // First person saber + ) { // if NPC, third person, or dead, unless using saber + // Get eyePoint & eyeAngles /* if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD @@ -5294,219 +4421,175 @@ extern vmCvar_t cg_thirdPersonAlpha; VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); } else - */if ( cent->gent->headBolt == -1 ) - {//no headBolt - VectorCopy( ent.origin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( tempAngles, cent->gent->client->renderInfo.eyeAngles ); - VectorCopy( ent.origin, cent->gent->client->renderInfo.headPoint ); - } - else - { - //FIXME: if head is missing, we should let the dismembered head set our eyePoint... - gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + */ + if (cent->gent->headBolt == -1) { // no headBolt + VectorCopy(ent.origin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(tempAngles, cent->gent->client->renderInfo.eyeAngles); + VectorCopy(ent.origin, cent->gent->client->renderInfo.headPoint); + } else { + // FIXME: if head is missing, we should let the dismembered head set our eyePoint... + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->headBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.eyePoint); - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tempAxis); - vectoangles( tempAxis, cent->gent->client->renderInfo.eyeAngles ); - //estimate where the neck would be... - gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis);//go down to find neck - VectorMA( cent->gent->client->renderInfo.eyePoint, 8, tempAxis, cent->gent->client->renderInfo.headPoint ); - } - //Get torsoPoint & torsoAngles - if (cent->gent->chestBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->chestBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.torsoPoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Z, tempAxis ); - vectoangles( tempAxis, cent->gent->client->renderInfo.torsoAngles ); - } - else - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.torsoPoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tempAxis); + vectoangles(tempAxis, cent->gent->client->renderInfo.eyeAngles); + // estimate where the neck would be... + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis); // go down to find neck + VectorMA(cent->gent->client->renderInfo.eyePoint, 8, tempAxis, cent->gent->client->renderInfo.headPoint); + } + // Get torsoPoint & torsoAngles + if (cent->gent->chestBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->chestBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.torsoPoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Z, tempAxis); + vectoangles(tempAxis, cent->gent->client->renderInfo.torsoAngles); + } else { + VectorCopy(ent.origin, cent->gent->client->renderInfo.torsoPoint); VectorClear(cent->gent->client->renderInfo.torsoAngles); } - //get crotchPoint - if (cent->gent->crotchBolt>=0) - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.crotchPoint ); - } - else - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.crotchPoint); + // get crotchPoint + if (cent->gent->crotchBolt >= 0) { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, cent->gent->crotchBolt, &boltMatrix, tempAngles, ent.origin, cg.time, + cgs.model_draw, cent->currentState.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.crotchPoint); + } else { + VectorCopy(ent.origin, cent->gent->client->renderInfo.crotchPoint); } - if( !calcedMp ) - { - if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_ATST) - {//FIXME: different for the three different weapon positions - mdxaBone_t boltMatrix; - int bolt; - entityState_t *es; + if (!calcedMp) { + if (cent->gent && cent->gent->client && + cent->gent->client->NPC_class == CLASS_ATST) { // FIXME: different for the three different weapon positions + mdxaBone_t boltMatrix; + int bolt; + entityState_t *es; es = ¢->currentState; // figure out where the actual model muzzle is - if (es->weapon == WP_ATST_MAIN) - { - if ( !es->number ) - {//player, just use left one, I guess - if ( cent->gent->alt_fire ) - { + if (es->weapon == WP_ATST_MAIN) { + if (!es->number) { // player, just use left one, I guess + if (cent->gent->alt_fire) { bolt = cent->gent->handRBolt; - } - else - { + } else { bolt = cent->gent->handLBolt; } - } - else if (cent->gent->count > 0) - { + } else if (cent->gent->count > 0) { cent->gent->count = 0; bolt = cent->gent->handLBolt; - } - else - { + } else { cent->gent->count = 1; bolt = cent->gent->handRBolt; } - } - else // ATST SIDE weapons + } else // ATST SIDE weapons { - if ( cent->gent->alt_fire) - { + if (cent->gent->alt_fire) { bolt = cent->gent->genericBolt2; - } - else - { + } else { bolt = cent->gent->genericBolt1; } } - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); - } - else if ( cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_GALAKMECH ) - { + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); + } else if (cent->gent && cent->gent->client && cent->gent->client->NPC_class == CLASS_GALAKMECH) { int bolt = -1; - if ( cent->gent->lockCount ) - {//using the big laser beam + if (cent->gent->lockCount) { // using the big laser beam bolt = cent->gent->handLBolt; - } - else//repeater + } else // repeater { - if ( cent->gent->alt_fire ) - {//fire from the lower barrel (not that anyone will ever notice this, but...) + if (cent->gent->alt_fire) { // fire from the lower barrel (not that anyone will ever notice this, but...) bolt = cent->gent->genericBolt3; - } - else - { + } else { bolt = cent->gent->handRBolt; } } - if ( bolt == -1 ) - { - VectorCopy( ent.origin, cent->gent->client->renderInfo.muzzlePoint ); - AngleVectors( tempAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL ); - } - else - { - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + if (bolt == -1) { + VectorCopy(ent.origin, cent->gent->client->renderInfo.muzzlePoint); + AngleVectors(tempAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL); + } else { + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->playerModel, bolt, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); } - } - else if (( cent->gent->weaponModel != -1) && - ( cent->gent->ghoul2.size() > cent->gent->weaponModel ) && - ( cent->gent->ghoul2[cent->gent->weaponModel].mModelindex != -1)) - { - mdxaBone_t boltMatrix; + } else if ((cent->gent->weaponModel != -1) && (cent->gent->ghoul2.size() > cent->gent->weaponModel) && + (cent->gent->ghoul2[cent->gent->weaponModel].mModelindex != -1)) { + mdxaBone_t boltMatrix; // figure out where the actual model muzzle is - gi.G2API_GetBoltMatrix( cent->gent->ghoul2, cent->gent->weaponModel, 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, cent->currentState.modelScale ); + gi.G2API_GetBoltMatrix(cent->gent->ghoul2, cent->gent->weaponModel, 0, &boltMatrix, tempAngles, ent.origin, cg.time, cgs.model_draw, + cent->currentState.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir ); - } - else - { - VectorCopy( cent->gent->client->renderInfo.eyePoint, cent->gent->client->renderInfo.muzzlePoint ); - AngleVectors( cent->gent->client->renderInfo.eyeAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, cent->gent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, cent->gent->client->renderInfo.muzzleDir); + } else { + VectorCopy(cent->gent->client->renderInfo.eyePoint, cent->gent->client->renderInfo.muzzlePoint); + AngleVectors(cent->gent->client->renderInfo.eyeAngles, cent->gent->client->renderInfo.muzzleDir, NULL, NULL); } cent->gent->client->renderInfo.mPCalcTime = cg.time; } // Pick the right effect for the type of weapon we are, defaults to no effect unless explicitly specified - if ( cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { + if (cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { const char *effect = NULL; - cent->muzzleFlashTime = 0; + cent->muzzleFlashTime = 0; // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cent->altFire ) - { + if (cent->altFire) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect ) - { - if ( cent->gent && cent->gent->NPC ) - { - theFxScheduler.PlayEffect( effect, cent->gent->client->renderInfo.muzzlePoint, - cent->gent->client->renderInfo.muzzleDir ); - } - else - { + if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect) { + if (cent->gent && cent->gent->NPC) { + theFxScheduler.PlayEffect(effect, cent->gent->client->renderInfo.muzzlePoint, cent->gent->client->renderInfo.muzzleDir); + } else { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cent->currentState.clientNum ); + theFxScheduler.PlayEffect(effect, cent->currentState.clientNum); } } } - //play special force effects - if ( cent->gent->NPC && ( cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time) ) - {// we are currently confused, so play an effect at the headBolt position - theFxScheduler.PlayEffect( cgs.effects.forceConfusion, cent->gent->client->renderInfo.eyePoint ); + // play special force effects + if (cent->gent->NPC && (cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || + cent->gent->NPC->controlledTime > cg.time)) { // we are currently confused, so play an effect at the headBolt position + theFxScheduler.PlayEffect(cgs.effects.forceConfusion, cent->gent->client->renderInfo.eyePoint); } - if ( cent->gent->client && cent->gent->forcePushTime > cg.time ) - {//being pushed - CG_ForcePushBodyBlur( cent, ent.origin, tempAngles ); + if (cent->gent->client && cent->gent->forcePushTime > cg.time) { // being pushed + CG_ForcePushBodyBlur(cent, ent.origin, tempAngles); } - if ( cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time || (cent->gent->client->ps.forcePowersActive & (1<gent->client->renderInfo.handLPoint ); + if (cent->gent->client->ps.powerups[PW_FORCE_PUSH] > cg.time || + (cent->gent->client->ps.forcePowersActive & (1 << FP_GRIP))) { // doing the pushing/gripping + CG_ForcePushBlur(cent->gent->client->renderInfo.handLPoint); } - if ( cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED ) - {//being gripped - CG_ForcePushBlur( cent->gent->client->renderInfo.headPoint ); + if (cent->gent->client->ps.eFlags & EF_FORCE_GRIPPED) { // being gripped + CG_ForcePushBlur(cent->gent->client->renderInfo.headPoint); } - if ( cent->gent->client && cent->gent->client->ps.powerups[PW_SHOCKED] > cg.time ) - {//being electrocuted - CG_ForceElectrocution( cent, ent.origin, tempAngles ); + if (cent->gent->client && cent->gent->client->ps.powerups[PW_SHOCKED] > cg.time) { // being electrocuted + CG_ForceElectrocution(cent, ent.origin, tempAngles); } - if ( cent->gent->client->ps.forcePowersActive&(1<gent->client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // doing the electrocuting vec3_t tAng, fxDir; - VectorCopy( cent->lerpAngles, tAng ); + VectorCopy(cent->lerpAngles, tAng); /* if ( cent->currentState.number ) { @@ -5517,486 +4600,411 @@ extern vmCvar_t cg_thirdPersonAlpha; VectorSet( tAng, tempAngles[0]+cent->pe.torso.pitchAngle, tempAngles[1]+cent->pe.torso.yawAngle, 0 ); } */ - if ( cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t fxAxis[3]; - AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handLPoint, fxAxis ); - } - else - {//line - AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceLightning, cent->gent->client->renderInfo.handLPoint, fxDir ); + if (cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t fxAxis[3]; + AnglesToAxis(tAng, fxAxis); + theFxScheduler.PlayEffect(cgs.effects.forceLightningWide, cent->gent->client->renderInfo.handLPoint, fxAxis); + } else { // line + AngleVectors(tAng, fxDir, NULL, NULL); + theFxScheduler.PlayEffect(cgs.effects.forceLightning, cent->gent->client->renderInfo.handLPoint, fxDir); } } } - //As good a place as any, I suppose, to do this keyframed sound thing - CGG2_AnimSounds( cent ); - //setup old system for gun to look at - //CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); - if ( cent->gent && cent->gent->client && cent->gent->client->ps.weapon == WP_SABER ) - { - if ( cg_timescale.value < 1.0f && (cent->gent->client->ps.forcePowersActive&(1<gent->client->ps.saberDamageDebounceTime - cg.time > wait ) - {//when you unpause the game with force speed on, the time gets *really* wiggy... + // As good a place as any, I suppose, to do this keyframed sound thing + CGG2_AnimSounds(cent); + // setup old system for gun to look at + // CG_RunLerpFrame( ci, ¢->pe.torso, cent->gent->client->ps.torsoAnim, cent->gent->client->renderInfo.torsoFpsMod, cent->gent->s.number ); + if (cent->gent && cent->gent->client && cent->gent->client->ps.weapon == WP_SABER) { + if (cg_timescale.value < 1.0f && (cent->gent->client->ps.forcePowersActive & (1 << FP_SPEED))) { + int wait = floor((float)FRAMETIME / 2.0f); + // sanity check + if (cent->gent->client->ps.saberDamageDebounceTime - cg.time > + wait) { // when you unpause the game with force speed on, the time gets *really* wiggy... cent->gent->client->ps.saberDamageDebounceTime = cg.time + wait; } - if ( cent->gent->client->ps.saberDamageDebounceTime <= cg.time ) - { -extern void WP_SaberDamageTrace( gentity_t *ent ); -extern void WP_SaberUpdateOldBladeData( gentity_t *ent ); - WP_SaberDamageTrace( cent->gent ); - WP_SaberUpdateOldBladeData( cent->gent ); - cent->gent->client->ps.saberDamageDebounceTime = cg.time + floor((float)wait*cg_timescale.value); + if (cent->gent->client->ps.saberDamageDebounceTime <= cg.time) { + extern void WP_SaberDamageTrace(gentity_t * ent); + extern void WP_SaberUpdateOldBladeData(gentity_t * ent); + WP_SaberDamageTrace(cent->gent); + WP_SaberUpdateOldBladeData(cent->gent); + cent->gent->client->ps.saberDamageDebounceTime = cg.time + floor((float)wait * cg_timescale.value); } } } - } - else - { - refEntity_t legs; - refEntity_t torso; - refEntity_t head; - refEntity_t gun; - refEntity_t flash; - refEntity_t flashlight; - int renderfx, i; - const weaponInfo_t *weapon; - + } else { + refEntity_t legs; + refEntity_t torso; + refEntity_t head; + refEntity_t gun; + refEntity_t flash; + refEntity_t flashlight; + int renderfx, i; + const weaponInfo_t *weapon; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - memset( &legs, 0, sizeof(legs) ); - memset( &torso, 0, sizeof(torso) ); - memset( &head, 0, sizeof(head) ); - memset( &gun, 0, sizeof(gun) ); - memset( &flash, 0, sizeof(flash) ); - memset( &flashlight, 0, sizeof(flashlight) ); + memset(&legs, 0, sizeof(legs)); + memset(&torso, 0, sizeof(torso)); + memset(&head, 0, sizeof(head)); + memset(&gun, 0, sizeof(gun)); + memset(&flash, 0, sizeof(flash)); + memset(&flashlight, 0, sizeof(flashlight)); - // Weapon sounds may need to be stopped, so check now - CG_StopWeaponSounds( cent ); + // Weapon sounds may need to be stopped, so check now + CG_StopWeaponSounds(cent); - //FIXME: pass in the axis/angles offset between the tag_torso and the tag_head? - // get the rotation information - CG_PlayerAngles( cent, legs.axis, torso.axis, head.axis ); - if ( cent->gent && cent->gent->client ) - { - cent->gent->client->ps.legsYaw = cent->lerpAngles[YAW]; - } + // FIXME: pass in the axis/angles offset between the tag_torso and the tag_head? + // get the rotation information + CG_PlayerAngles(cent, legs.axis, torso.axis, head.axis); + if (cent->gent && cent->gent->client) { + cent->gent->client->ps.legsYaw = cent->lerpAngles[YAW]; + } - // get the animation state (after rotation, to allow feet shuffle) - // NB: Also plays keyframed animSounds (Bob- hope you dont mind, I was here late and at about 5:30 Am i needed to do something to keep me awake and i figured you wouldn't mind- you might want to check it, though, to make sure I wasn't smoking crack and missed something important, it is pretty late and I'm getting pretty close to being up for 24 hours here, so i wouldn't doubt if I might have messed something up, but i tested it and it looked right.... noticed in old code base i was doing it wrong too, whic h explains why I was getting so many damn sounds all the time! I had to lower the probabilities because it seemed like i was getting way too many sounds, and that was the problem! Well, should be fixed now I think...) - CG_PlayerAnimation( cent, &legs.oldframe, &legs.frame, &legs.backlerp, - &torso.oldframe, &torso.frame, &torso.backlerp ); + // get the animation state (after rotation, to allow feet shuffle) + // NB: Also plays keyframed animSounds (Bob- hope you dont mind, I was here late and at about 5:30 Am i needed to do something to keep me awake and i + // figured you wouldn't mind- you might want to check it, though, to make sure I wasn't smoking crack and missed something important, it is pretty late + // and I'm getting pretty close to being up for 24 hours here, so i wouldn't doubt if I might have messed something up, but i tested it and it looked + // right.... noticed in old code base i was doing it wrong too, whic h explains why I was getting so many damn sounds all the time! I had to + // lower the probabilities because it seemed like i was getting way too many sounds, and that was the problem! Well, should be fixed now I think...) + CG_PlayerAnimation(cent, &legs.oldframe, &legs.frame, &legs.backlerp, &torso.oldframe, &torso.frame, &torso.backlerp); - cent->gent->client->renderInfo.legsFrame = cent->pe.legs.frame; - cent->gent->client->renderInfo.torsoFrame = cent->pe.torso.frame; + cent->gent->client->renderInfo.legsFrame = cent->pe.legs.frame; + cent->gent->client->renderInfo.torsoFrame = cent->pe.torso.frame; - // add powerups floating behind the player - CG_PlayerPowerups( cent ); + // add powerups floating behind the player + CG_PlayerPowerups(cent); - // add the shadow - shadow = CG_PlayerShadow( cent, &shadowPlane ); + // add the shadow + shadow = CG_PlayerShadow(cent, &shadowPlane); - // add a water splash if partially in and out of water - CG_PlayerSplash( cent ); + // add a water splash if partially in and out of water + CG_PlayerSplash(cent); - // get the player model information - renderfx = 0; - if ( !cg.renderingThirdPerson || cg.zoomMode ) - { - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) - {//no viewentity - if ( cent->currentState.number == cg.snap->ps.clientNum ) - {//I am the player - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - renderfx = RF_THIRD_PERSON; // only draw in mirrors + // get the player model information + renderfx = 0; + if (!cg.renderingThirdPerson || cg.zoomMode) { + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // no viewentity + if (cent->currentState.number == cg.snap->ps.clientNum) { // I am the player + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + renderfx = RF_THIRD_PERSON; // only draw in mirrors + } + } + } else if (cent->currentState.number == cg.snap->ps.viewEntity) { // I am the view entity + if (cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE) { // not using saber or fists + renderfx = RF_THIRD_PERSON; // only draw in mirrors } } } - else if ( cent->currentState.number == cg.snap->ps.viewEntity ) - {//I am the view entity - if ( cg.snap->ps.weapon != WP_SABER && cg.snap->ps.weapon != WP_MELEE ) - {//not using saber or fists - renderfx = RF_THIRD_PERSON; // only draw in mirrors - } - } - } - - if ( (cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow) ) - { - renderfx |= RF_SHADOW_PLANE; - } - renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all - if ( cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT ) - { - renderfx |= RF_MORELIGHT; //bigger than normal min light - } - - if ( cent->gent && cent->gent->client ) - { - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.headPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.handRPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.handLPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.footRPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.footLPoint ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.torsoPoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.crotchPoint ); - } - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && cg.snap->ps.viewEntity == cent->currentState.clientNum ) - {//player is in an entity camera view, ME - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint ); - VectorCopy( cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles ); - VectorCopy( cent->lerpOrigin, cent->gent->client->renderInfo.headPoint ); - } - // - // add the legs - // - legs.hModel = ci->legsModel; - legs.customSkin = ci->legsSkin; - - VectorCopy( cent->lerpOrigin, legs.origin ); - - //Scale applied to a refEnt will apply to any models attached to it... - //This seems to copy the scale to every piece attached, kinda cool, but doesn't - //allow the body to be scaled up without scaling a bolt on or whatnot... - //Only apply scale if it's not 100% scale... - if(cent->currentState.modelScale[0] != 0.0f) - { - VectorScale( legs.axis[0], cent->currentState.modelScale[0], legs.axis[0] ); - legs.nonNormalizedAxes = qtrue; - } - if(cent->currentState.modelScale[1] != 0.0f) - { - VectorScale( legs.axis[1], cent->currentState.modelScale[1], legs.axis[1] ); - legs.nonNormalizedAxes = qtrue; - } - - if(cent->currentState.modelScale[2] != 0.0f) - { - VectorScale( legs.axis[2], cent->currentState.modelScale[2], legs.axis[2] ); - legs.nonNormalizedAxes = qtrue; - if ( !staticScale ) - { - //FIXME:? need to know actual height of leg model bottom to origin, not hardcoded - legs.origin[2] += 24 * (cent->currentState.modelScale[2] - 1); + if ((cg_shadows.integer == 2) || (cg_shadows.integer == 3 && shadow)) { + renderfx |= RF_SHADOW_PLANE; + } + renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + if (cent->gent->NPC && cent->gent->NPC->scriptFlags & SCF_MORELIGHT) { + renderfx |= RF_MORELIGHT; // bigger than normal min light } - } - - VectorCopy( legs.origin, legs.lightingOrigin ); - legs.shadowPlane = shadowPlane; - legs.renderfx = renderfx; - VectorCopy (legs.origin, legs.oldorigin); // don't positionally lerp at all - CG_AddRefEntityWithPowerups( &legs, cent->currentState.powerups, cent ); + if (cent->gent && cent->gent->client) { + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.headPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.handRPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.handLPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.footRPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.footLPoint); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.torsoPoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.torsoAngles); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.crotchPoint); + } + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && + cg.snap->ps.viewEntity == cent->currentState.clientNum) { // player is in an entity camera view, ME + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.eyePoint); + VectorCopy(cent->lerpAngles, cent->gent->client->renderInfo.eyeAngles); + VectorCopy(cent->lerpOrigin, cent->gent->client->renderInfo.headPoint); + } + // + // add the legs + // + legs.hModel = ci->legsModel; + legs.customSkin = ci->legsSkin; - // if the model failed, allow the default nullmodel to be displayed - if (!legs.hModel) - { - return; - } + VectorCopy(cent->lerpOrigin, legs.origin); - // - // add the torso - // - torso.hModel = ci->torsoModel; - if (torso.hModel) - { - orientation_t tag_torso; + // Scale applied to a refEnt will apply to any models attached to it... + // This seems to copy the scale to every piece attached, kinda cool, but doesn't + // allow the body to be scaled up without scaling a bolt on or whatnot... + // Only apply scale if it's not 100% scale... + if (cent->currentState.modelScale[0] != 0.0f) { + VectorScale(legs.axis[0], cent->currentState.modelScale[0], legs.axis[0]); + legs.nonNormalizedAxes = qtrue; + } - torso.customSkin = ci->torsoSkin; + if (cent->currentState.modelScale[1] != 0.0f) { + VectorScale(legs.axis[1], cent->currentState.modelScale[1], legs.axis[1]); + legs.nonNormalizedAxes = qtrue; + } - VectorCopy( cent->lerpOrigin, torso.lightingOrigin ); + if (cent->currentState.modelScale[2] != 0.0f) { + VectorScale(legs.axis[2], cent->currentState.modelScale[2], legs.axis[2]); + legs.nonNormalizedAxes = qtrue; + if (!staticScale) { + // FIXME:? need to know actual height of leg model bottom to origin, not hardcoded + legs.origin[2] += 24 * (cent->currentState.modelScale[2] - 1); + } + } - CG_PositionRotatedEntityOnTag( &torso, &legs, legs.hModel, "tag_torso", &tag_torso ); - VectorCopy( torso.origin, cent->gent->client->renderInfo.torsoPoint ); - vectoangles( tag_torso.axis[0], cent->gent->client->renderInfo.torsoAngles ); + VectorCopy(legs.origin, legs.lightingOrigin); + legs.shadowPlane = shadowPlane; + legs.renderfx = renderfx; + VectorCopy(legs.origin, legs.oldorigin); // don't positionally lerp at all - torso.shadowPlane = shadowPlane; - torso.renderfx = renderfx; + CG_AddRefEntityWithPowerups(&legs, cent->currentState.powerups, cent); - CG_AddRefEntityWithPowerups( &torso, cent->currentState.powerups, cent ); + // if the model failed, allow the default nullmodel to be displayed + if (!legs.hModel) { + return; + } // - // add the head + // add the torso // - head.hModel = ci->headModel; - if (head.hModel) - { - orientation_t tag_head; + torso.hModel = ci->torsoModel; + if (torso.hModel) { + orientation_t tag_torso; - //Deal with facial expressions - CG_PlayerHeadExtension( cent, &head ); + torso.customSkin = ci->torsoSkin; - VectorCopy( cent->lerpOrigin, head.lightingOrigin ); + VectorCopy(cent->lerpOrigin, torso.lightingOrigin); - CG_PositionRotatedEntityOnTag( &head, &torso, torso.hModel, "tag_head", &tag_head ); - VectorCopy( head.origin, cent->gent->client->renderInfo.headPoint ); - vectoangles( tag_head.axis[0], cent->gent->client->renderInfo.headAngles ); + CG_PositionRotatedEntityOnTag(&torso, &legs, legs.hModel, "tag_torso", &tag_torso); + VectorCopy(torso.origin, cent->gent->client->renderInfo.torsoPoint); + vectoangles(tag_torso.axis[0], cent->gent->client->renderInfo.torsoAngles); - head.shadowPlane = shadowPlane; - head.renderfx = renderfx; + torso.shadowPlane = shadowPlane; + torso.renderfx = renderfx; - CG_AddRefEntityWithPowerups( &head, cent->currentState.powerups, cent ); + CG_AddRefEntityWithPowerups(&torso, cent->currentState.powerups, cent); - if ( cent->gent && cent->gent->NPC && ( cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time) ) - { - // we are currently confused, so play an effect - theFxScheduler.PlayEffect( cgs.effects.forceConfusion, head.origin ); - } + // + // add the head + // + head.hModel = ci->headModel; + if (head.hModel) { + orientation_t tag_head; - if ( !calcedMp ) - {//First person player's eyePoint and eyeAngles should be copies from cg.refdef... - //Calc this client's eyepoint - VectorCopy( head.origin, cent->gent->client->renderInfo.eyePoint ); - // race is gone, eyepoint should refer to the tag/bolt on the model... if this breaks something let me know - dmv - // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][1]*scaleFactor[2], head.axis[2], cent->gent->client->renderInfo.eyePoint );//up - // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][0]*scaleFactor[0], head.axis[0], cent->gent->client->renderInfo.eyePoint );//forward - //Calc this client's eyeAngles - vectoangles( head.axis[0], cent->gent->client->renderInfo.eyeAngles ); - } - } - else - { - VectorCopy( torso.origin, cent->gent->client->renderInfo.eyePoint ); - cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; - vectoangles( torso.axis[0], cent->gent->client->renderInfo.eyeAngles ); - } + // Deal with facial expressions + CG_PlayerHeadExtension(cent, &head); - // - // add the gun - // - CG_RegisterWeapon( cent->currentState.weapon ); - weapon = &cg_weapons[cent->currentState.weapon]; + VectorCopy(cent->lerpOrigin, head.lightingOrigin); - gun.hModel = weapon->weaponWorldModel; - if (gun.hModel) - { - qboolean drawGun = qtrue; - //FIXME: allow scale, animation and angle offsets - VectorCopy( cent->lerpOrigin, gun.lightingOrigin ); + CG_PositionRotatedEntityOnTag(&head, &torso, torso.hModel, "tag_head", &tag_head); + VectorCopy(head.origin, cent->gent->client->renderInfo.headPoint); + vectoangles(tag_head.axis[0], cent->gent->client->renderInfo.headAngles); - //FIXME: allow it to be put anywhere and move this out of if(torso.hModel) - //Will have to call CG_PositionRotatedEntityOnTag + head.shadowPlane = shadowPlane; + head.renderfx = renderfx; - CG_PositionEntityOnTag( &gun, &torso, torso.hModel, "tag_weapon"); + CG_AddRefEntityWithPowerups(&head, cent->currentState.powerups, cent); -//--------------------- start saber hacks + if (cent->gent && cent->gent->NPC && + (cent->gent->NPC->confusionTime > cg.time || cent->gent->NPC->charmedTime > cg.time || cent->gent->NPC->controlledTime > cg.time)) { + // we are currently confused, so play an effect + theFxScheduler.PlayEffect(cgs.effects.forceConfusion, head.origin); + } - if ( cent->gent && cent->gent->client && ( cent->currentState.weapon == WP_SABER || cent->currentState.saberInFlight ) ) - { - if ( !cent->gent->client->ps.saberActive )//!cent->currentState.saberActive ) - {//saber is off - if ( cent->gent->client->ps.saberLength > 0 ) - { - if ( cent->gent->client->ps.stats[STAT_HEALTH] <= 0 ) - {//dead, didn't actively turn it off - cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax/10 * cg.frametime/100; + if (!calcedMp) { // First person player's eyePoint and eyeAngles should be copies from cg.refdef... + // Calc this client's eyepoint + VectorCopy(head.origin, cent->gent->client->renderInfo.eyePoint); + // race is gone, eyepoint should refer to the tag/bolt on the model... if this breaks something let me know - dmv + // VectorMA( cent->gent->client->renderInfo.eyePoint, CG_EyePointOfsForRace[cent->gent->client->race][1]*scaleFactor[2], head.axis[2], + //cent->gent->client->renderInfo.eyePoint );//up VectorMA( cent->gent->client->renderInfo.eyePoint, + //CG_EyePointOfsForRace[cent->gent->client->race][0]*scaleFactor[0], head.axis[0], cent->gent->client->renderInfo.eyePoint );//forward Calc + // this client's eyeAngles + vectoangles(head.axis[0], cent->gent->client->renderInfo.eyeAngles); + } + } else { + VectorCopy(torso.origin, cent->gent->client->renderInfo.eyePoint); + cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; + vectoangles(torso.axis[0], cent->gent->client->renderInfo.eyeAngles); + } + + // + // add the gun + // + CG_RegisterWeapon(cent->currentState.weapon); + weapon = &cg_weapons[cent->currentState.weapon]; + + gun.hModel = weapon->weaponWorldModel; + if (gun.hModel) { + qboolean drawGun = qtrue; + // FIXME: allow scale, animation and angle offsets + VectorCopy(cent->lerpOrigin, gun.lightingOrigin); + + // FIXME: allow it to be put anywhere and move this out of if(torso.hModel) + // Will have to call CG_PositionRotatedEntityOnTag + + CG_PositionEntityOnTag(&gun, &torso, torso.hModel, "tag_weapon"); + + //--------------------- start saber hacks + + if (cent->gent && cent->gent->client && (cent->currentState.weapon == WP_SABER || cent->currentState.saberInFlight)) { + if (!cent->gent->client->ps.saberActive) //! cent->currentState.saberActive ) + { // saber is off + if (cent->gent->client->ps.saberLength > 0) { + if (cent->gent->client->ps.stats[STAT_HEALTH] <= 0) { // dead, didn't actively turn it off + cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax / 10 * cg.frametime / 100; + } else { // actively turned it off, shrink faster + cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax / 3 * cg.frametime / 100; + } } - else - {//actively turned it off, shrink faster - cent->gent->client->ps.saberLength -= cent->gent->client->ps.saberLengthMax/3 * cg.frametime/100; + if (cent->gent->client->ps.saberLength < 0) { + cent->gent->client->ps.saberLength = 0; } - } - if ( cent->gent->client->ps.saberLength < 0 ) - { - cent->gent->client->ps.saberLength = 0; - } - } - else if ( cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax ) - {//saber is on - if ( !cent->gent->client->ps.saberLength ) - { - if ( cent->currentState.saberInFlight ) - {//play it on the saber - cgi_S_UpdateEntityPosition( cent->gent->client->ps.saberEntityNum, g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ) ); + } else if (cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax) { // saber is on + if (!cent->gent->client->ps.saberLength) { + if (cent->currentState.saberInFlight) { // play it on the saber + cgi_S_UpdateEntityPosition(cent->gent->client->ps.saberEntityNum, + g_entities[cent->gent->client->ps.saberEntityNum].currentOrigin); + cgi_S_StartSound(NULL, cent->gent->client->ps.saberEntityNum, CHAN_AUTO, + cgi_S_RegisterSound("sound/weapons/saber/saberon.wav")); + } else { + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/saber/saberon.wav")); + } } - else - { - cgi_S_StartSound (NULL, cent->currentState.number, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ) ); + cent->gent->client->ps.saberLength += cent->gent->client->ps.saberLengthMax / 6 * cg.frametime / 100; //= saberLengthMax; + if (cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax) { + cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLengthMax; } } - cent->gent->client->ps.saberLength += cent->gent->client->ps.saberLengthMax/6 * cg.frametime/100;//= saberLengthMax; - if ( cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax ) - { - cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLengthMax; - } - } - if ( cent->currentState.saberInFlight ) - {//not holding the saber in-hand - drawGun = qfalse; - } - if ( cent->gent->client->ps.saberLength > 0 ) - { - if ( !cent->currentState.saberInFlight ) - {//holding the saber in-hand - CG_AddSaberBlade( cent, cent, &gun, renderfx, 0, NULL, NULL ); - calcedMp = qtrue; + if (cent->currentState.saberInFlight) { // not holding the saber in-hand + drawGun = qfalse; } - } - else - { - //if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) - { - CG_CheckSaberInWater( cent, cent, 0, NULL, NULL ); + if (cent->gent->client->ps.saberLength > 0) { + if (!cent->currentState.saberInFlight) { // holding the saber in-hand + CG_AddSaberBlade(cent, cent, &gun, renderfx, 0, NULL, NULL); + calcedMp = qtrue; + } + } else { + // if ( cent->gent->client->ps.saberEventFlags&SEF_INWATER ) + { CG_CheckSaberInWater(cent, cent, 0, NULL, NULL); } } } - } -//--------------------- end saber hacks + //--------------------- end saber hacks - gun.shadowPlane = shadowPlane; - gun.renderfx = renderfx; + gun.shadowPlane = shadowPlane; + gun.renderfx = renderfx; - if ( drawGun ) - { - CG_AddRefEntityWithPowerups( &gun, - (cent->currentState.powerups & ((1<currentState.powerups & ((1 << PW_CLOAKED) | (1 << PW_BATTLESUIT))), cent); + } - // - // add the flash (even if invisible) - // + // + // add the flash (even if invisible) + // - // impulse flash - if ( cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - { - int effect = 0; + // impulse flash + if (cent->muzzleFlashTime > 0 && wData && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { + int effect = 0; - cent->muzzleFlashTime = 0; + cent->muzzleFlashTime = 0; - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); - // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffectID ) - { - effect = wData->mMuzzleEffectID; - } + // Try and get a default muzzle so we have one to fall back on + if (wData->mMuzzleEffectID) { + effect = wData->mMuzzleEffectID; + } - if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { - // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffectID ) - { - effect = wData->mAltMuzzleEffectID; + if (cent->currentState.eFlags & EF_ALT_FIRING) { + // We're alt-firing, so see if we need to override with a custom alt-fire effect + if (wData->mAltMuzzleEffectID) { + effect = wData->mAltMuzzleEffectID; + } } - } - if (( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) && effect ) - { - vec3_t up={0,0,1}, ax[3]; + if ((cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING) && effect) { + vec3_t up = {0, 0, 1}, ax[3]; - VectorCopy( flash.axis[0], ax[0] ); + VectorCopy(flash.axis[0], ax[0]); - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); - if (( cent->gent && cent->gent->NPC ) || cg.renderingThirdPerson ) - { - theFxScheduler.PlayEffect( effect, flash.origin, ax ); - } - else - { - // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, flash.origin, ax ); + if ((cent->gent && cent->gent->NPC) || cg.renderingThirdPerson) { + theFxScheduler.PlayEffect(effect, flash.origin, ax); + } else { + // We got an effect and we're firing, so let 'er rip. + theFxScheduler.PlayEffect(effect, flash.origin, ax); + } } } - } - if ( !calcedMp && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON )) - {// Set the muzzle point - orientation_t orientation; + if (!calcedMp && !(cent->currentState.eFlags & EF_LOCKED_TO_WEAPON)) { // Set the muzzle point + orientation_t orientation; - cgi_R_LerpTag( &orientation, weapon->weaponModel, gun.oldframe, gun.frame, - 1.0f - gun.backlerp, "tag_flash" ); - - // FIXME: allow origin offsets along tag? - VectorCopy( gun.origin, cent->gent->client->renderInfo.muzzlePoint ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorMA( cent->gent->client->renderInfo.muzzlePoint, orientation.origin[i], gun.axis[i], cent->gent->client->renderInfo.muzzlePoint ); - } -// VectorCopy( gun.axis[0], cent->gent->client->renderInfo.muzzleDir ); -// VectorAdd( gun.axis[0], orientation.axis[0], cent->gent->client->renderInfo.muzzleDir ); -// VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); + cgi_R_LerpTag(&orientation, weapon->weaponModel, gun.oldframe, gun.frame, 1.0f - gun.backlerp, "tag_flash"); + // FIXME: allow origin offsets along tag? + VectorCopy(gun.origin, cent->gent->client->renderInfo.muzzlePoint); + for (i = 0; i < 3; i++) { + VectorMA(cent->gent->client->renderInfo.muzzlePoint, orientation.origin[i], gun.axis[i], cent->gent->client->renderInfo.muzzlePoint); + } + // VectorCopy( gun.axis[0], cent->gent->client->renderInfo.muzzleDir ); + // VectorAdd( gun.axis[0], orientation.axis[0], cent->gent->client->renderInfo.muzzleDir ); + // VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); - cent->gent->client->renderInfo.mPCalcTime = cg.time; - // Weapon wasn't firing anymore, so ditch any weapon associated looping sounds. - //cent->gent->s.loopSound = 0; + cent->gent->client->renderInfo.mPCalcTime = cg.time; + // Weapon wasn't firing anymore, so ditch any weapon associated looping sounds. + // cent->gent->s.loopSound = 0; + } } + } else { + VectorCopy(legs.origin, cent->gent->client->renderInfo.eyePoint); + cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; + vectoangles(legs.axis[0], cent->gent->client->renderInfo.eyeAngles); } } - else - { - VectorCopy( legs.origin, cent->gent->client->renderInfo.eyePoint ); - cent->gent->client->renderInfo.eyePoint[2] += cent->gent->maxs[2] - 4; - vectoangles( legs.axis[0], cent->gent->client->renderInfo.eyeAngles ); - } - } - - //FIXME: for debug, allow to draw a cone of the NPC's FOV... - if ( cent->currentState.number == 0 && cg.renderingThirdPerson ) - { + // FIXME: for debug, allow to draw a cone of the NPC's FOV... + if (cent->currentState.number == 0 && cg.renderingThirdPerson) { playerState_t *ps = &cg.predicted_player_state; - if (( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL ) - || ( ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING ) - || ( ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT )) - { - int shader = 0; - float val = 0.0f, scale = 1.0f; - vec3_t WHITE = {1.0f,1.0f,1.0f}; + if ((ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL) || (ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING) || + (ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT)) { + int shader = 0; + float val = 0.0f, scale = 1.0f; + vec3_t WHITE = {1.0f, 1.0f, 1.0f}; - if ( ps->weapon == WP_BRYAR_PISTOL ) - { + if (ps->weapon == WP_BRYAR_PISTOL) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/bryarFrontFlash" ); - } - else if ( ps->weapon == WP_BOWCASTER ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/bryarFrontFlash"); + } else if (ps->weapon == WP_BOWCASTER) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/greenFrontFlash" ); - } - else if ( ps->weapon == WP_DEMP2 ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/greenFrontFlash"); + } else if (ps->weapon == WP_DEMP2) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/misc/lightningFlash" ); + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/misc/lightningFlash"); scale = 1.75f; } - if ( val < 0.0f ) - { + if (val < 0.0f) { val = 0.0f; - } - else if ( val > 1.0f ) - { + } else if (val > 1.0f) { val = 1.0f; - CGCam_Shake( 0.1f, 100 ); - } - else - { - CGCam_Shake( val * val * 0.3f, 100 ); + CGCam_Shake(0.1f, 100); + } else { + CGCam_Shake(val * val * 0.3f, 100); } val += Q_flrand(0.0f, 1.0f) * 0.5f; - FX_AddSprite( cent->gent->client->renderInfo.muzzlePoint, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA ); + FX_AddSprite(cent->gent->client->renderInfo.muzzlePoint, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, + 0.0f, 1.0f, shader, FX_USE_ALPHA); } } } @@ -6013,45 +5021,40 @@ FIXME: We do not need to do this, we can remember the last anim and frame they w on and coontinue from there. =============== */ -void CG_ResetPlayerEntity( centity_t *cent ) { - cent->errorTime = -99999; // guarantee no error decay added +void CG_ResetPlayerEntity(centity_t *cent) { + cent->errorTime = -99999; // guarantee no error decay added cent->extrapolated = qfalse; - if ( cent->gent && cent->gent->ghoul2.size() ) - { - if ( cent->currentState.clientNum < MAX_CLIENTS ) - { - CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], ¢->pe.legs, cent->currentState.legsAnim ); - CG_ClearLerpFrame( &cgs.clientinfo[ cent->currentState.clientNum ], ¢->pe.torso, cent->currentState.torsoAnim ); - } - else if ( cent->gent && cent->gent->client ) - { - CG_ClearLerpFrame( ¢->gent->client->clientInfo, ¢->pe.legs, cent->currentState.legsAnim ); - CG_ClearLerpFrame( ¢->gent->client->clientInfo, ¢->pe.torso, cent->currentState.torsoAnim ); + if (cent->gent && cent->gent->ghoul2.size()) { + if (cent->currentState.clientNum < MAX_CLIENTS) { + CG_ClearLerpFrame(&cgs.clientinfo[cent->currentState.clientNum], ¢->pe.legs, cent->currentState.legsAnim); + CG_ClearLerpFrame(&cgs.clientinfo[cent->currentState.clientNum], ¢->pe.torso, cent->currentState.torsoAnim); + } else if (cent->gent && cent->gent->client) { + CG_ClearLerpFrame(¢->gent->client->clientInfo, ¢->pe.legs, cent->currentState.legsAnim); + CG_ClearLerpFrame(¢->gent->client->clientInfo, ¢->pe.torso, cent->currentState.torsoAnim); } } - //else???? + // else???? - EvaluateTrajectory( ¢->currentState.pos, cg.time, cent->lerpOrigin ); - EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + EvaluateTrajectory(¢->currentState.pos, cg.time, cent->lerpOrigin); + EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); - VectorCopy( cent->lerpOrigin, cent->rawOrigin ); - VectorCopy( cent->lerpAngles, cent->rawAngles ); + VectorCopy(cent->lerpOrigin, cent->rawOrigin); + VectorCopy(cent->lerpAngles, cent->rawAngles); - memset( ¢->pe.legs, 0, sizeof( cent->pe.legs ) ); + memset(¢->pe.legs, 0, sizeof(cent->pe.legs)); cent->pe.legs.yawAngle = cent->rawAngles[YAW]; cent->pe.legs.yawing = qfalse; cent->pe.legs.pitchAngle = 0; cent->pe.legs.pitching = qfalse; - memset( ¢->pe.torso, 0, sizeof( cent->pe.legs ) ); + memset(¢->pe.torso, 0, sizeof(cent->pe.legs)); cent->pe.torso.yawAngle = cent->rawAngles[YAW]; cent->pe.torso.yawing = qfalse; cent->pe.torso.pitchAngle = cent->rawAngles[PITCH]; cent->pe.torso.pitching = qfalse; - if ( cg_debugPosition.integer ) { - CG_Printf("%i ResetPlayerEntity yaw=%i\n", cent->currentState.number, cent->pe.torso.yawAngle ); + if (cg_debugPosition.integer) { + CG_Printf("%i ResetPlayerEntity yaw=%i\n", cent->currentState.number, cent->pe.torso.yawAngle); } } - diff --git a/codeJK2/cgame/cg_playerstate.cpp b/codeJK2/cgame/cg_playerstate.cpp index 3491570df2..26b84a35c4 100644 --- a/codeJK2/cgame/cg_playerstate.cpp +++ b/codeJK2/cgame/cg_playerstate.cpp @@ -36,12 +36,11 @@ CG_CheckAmmo If the ammo has gone low enough to generate the warning, play a sound ============== */ -void CG_CheckAmmo( void ) -{ -// int i; - int total; - int previous; -// int weapons; +void CG_CheckAmmo(void) { + // int i; + int total; + int previous; + // int weapons; #if 0 @@ -78,8 +77,7 @@ void CG_CheckAmmo( void ) #endif // Don't bother drawing the ammo warning when have no weapon selected - if ( cg.weaponSelect == WP_NONE ) - { + if (cg.weaponSelect == WP_NONE) { return; } @@ -91,21 +89,19 @@ void CG_CheckAmmo( void ) return; } - previous = cg.lowAmmoWarning; - if (!total) // We're completely freak'in out! + if (!total) // We're completely freak'in out! { cg.lowAmmoWarning = 2; - } - else // Got a little left + } else // Got a little left { cg.lowAmmoWarning = 1; } // play a sound on transitions - if ( cg.lowAmmoWarning != previous ) { - cgi_S_StartLocalSound( cgs.media.noAmmoSound, CHAN_LOCAL_SOUND ); //"sound/weapons/noammo.wav" + if (cg.lowAmmoWarning != previous) { + cgi_S_StartLocalSound(cgs.media.noAmmoSound, CHAN_LOCAL_SOUND); //"sound/weapons/noammo.wav" } } @@ -114,22 +110,22 @@ void CG_CheckAmmo( void ) CG_DamageFeedback ============== */ -void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { - float left, front, up; - float kick; - int health; - float scale; - vec3_t dir; - vec3_t angles; - float dist; - float yaw, pitch; - - //FIXME: Based on MOD, do different kinds of damage effects, +void CG_DamageFeedback(int yawByte, int pitchByte, int damage) { + float left, front, up; + float kick; + int health; + float scale; + vec3_t dir; + vec3_t angles; + float dist; + float yaw, pitch; + + // FIXME: Based on MOD, do different kinds of damage effects, // for example, Borg damage could progressively tint screen green and raise FOV? // the lower on health you are, the greater the view kick will be health = cg.snap->ps.stats[STAT_HEALTH]; - if ( health < 40 ) { + if (health < 40) { scale = 1; } else { scale = 40.0 / health; @@ -142,7 +138,7 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { kick = 10; // if yaw and pitch are both 255, make the damage always centered (falling, etc) - if ( yawByte == 255 && pitchByte == 255 ) { + if (yawByte == 255 && pitchByte == 255) { cg.damageX = 0; cg.damageY = 0; cg.v_dmg_roll = 0; @@ -156,26 +152,26 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { angles[YAW] = yaw; angles[ROLL] = 0; - AngleVectors( angles, dir, NULL, NULL ); - VectorSubtract( vec3_origin, dir, dir ); + AngleVectors(angles, dir, NULL, NULL); + VectorSubtract(vec3_origin, dir, dir); - front = DotProduct (dir, cg.refdef.viewaxis[0] ); - left = DotProduct (dir, cg.refdef.viewaxis[1] ); - up = DotProduct (dir, cg.refdef.viewaxis[2] ); + front = DotProduct(dir, cg.refdef.viewaxis[0]); + left = DotProduct(dir, cg.refdef.viewaxis[1]); + up = DotProduct(dir, cg.refdef.viewaxis[2]); dir[0] = front; dir[1] = left; dir[2] = 0; - dist = VectorLength( dir ); - if ( dist < 0.1 ) { + dist = VectorLength(dir); + if (dist < 0.1) { dist = 0.1f; } cg.v_dmg_roll = kick * left; - + cg.v_dmg_pitch = -kick * front; - if ( front <= 0.1 ) { + if (front <= 0.1) { front = 0.1f; } cg.damageX = -left / front; @@ -183,22 +179,22 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { } // clamp the position - if ( cg.damageX > 1.0 ) { + if (cg.damageX > 1.0) { cg.damageX = 1.0; } - if ( cg.damageX < - 1.0 ) { + if (cg.damageX < -1.0) { cg.damageX = -1.0; } - if ( cg.damageY > 1.0 ) { + if (cg.damageY > 1.0) { cg.damageY = 1.0; } - if ( cg.damageY < - 1.0 ) { + if (cg.damageY < -1.0) { cg.damageY = -1.0; } // don't let the screen flashes vary as much - if ( kick > 10 ) { + if (kick > 10) { kick = 10; } cg.damageValue = kick; @@ -206,9 +202,6 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { cg.damageTime = cg.snap->serverTime; } - - - /* ================ CG_Respawn @@ -216,29 +209,28 @@ CG_Respawn A respawn happened this snapshot ================ */ -void CG_Respawn( void ) { +void CG_Respawn(void) { // no error decay on player movement cg.thisFrameTeleport = qtrue; // display weapons available -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); // select the weapon the server says we are using cg.weaponSelect = cg.snap->ps.weapon; } - /* ============== CG_CheckPlayerstateEvents ============== */ -void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { - int i; - int event; - centity_t *cent; +void CG_CheckPlayerstateEvents(playerState_t *ps, playerState_t *ops) { + int i; + int event; + centity_t *cent; #if 0 if ( ps->externalEvent && ps->externalEvent != ops->externalEvent ) { @@ -249,15 +241,14 @@ void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { } #endif - for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) { - if ( ps->events[i & (MAX_PS_EVENTS-1)] != ops->events[i & (MAX_PS_EVENTS-1)] - || i >= ops->eventSequence ) { - event = ps->events[ i & (MAX_PS_EVENTS-1) ]; + for (i = ps->eventSequence - MAX_PS_EVENTS; i < ps->eventSequence; i++) { + if (ps->events[i & (MAX_PS_EVENTS - 1)] != ops->events[i & (MAX_PS_EVENTS - 1)] || i >= ops->eventSequence) { + event = ps->events[i & (MAX_PS_EVENTS - 1)]; - cent = &cg_entities[ ps->clientNum ]; + cent = &cg_entities[ps->clientNum]; cent->currentState.event = event; - cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ]; - CG_EntityEvent( cent, cent->lerpOrigin ); + cent->currentState.eventParm = ps->eventParms[i & (MAX_PS_EVENTS - 1)]; + CG_EntityEvent(cent, cent->lerpOrigin); } } } @@ -327,28 +318,28 @@ CG_TransitionPlayerState =============== */ -void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) { +void CG_TransitionPlayerState(playerState_t *ps, playerState_t *ops) { // teleporting - if ( ( ps->eFlags ^ ops->eFlags ) & EF_TELEPORT_BIT ) { + if ((ps->eFlags ^ ops->eFlags) & EF_TELEPORT_BIT) { cg.thisFrameTeleport = qtrue; } else { cg.thisFrameTeleport = qfalse; } // check for changing follow mode - if ( ps->clientNum != ops->clientNum ) { + if (ps->clientNum != ops->clientNum) { cg.thisFrameTeleport = qtrue; // make sure we don't get any unwanted transition effects *ops = *ps; } // damage events (player is getting wounded) - if ( ps->damageEvent != ops->damageEvent && ps->damageCount ) { - CG_DamageFeedback( ps->damageYaw, ps->damagePitch, ps->damageCount ); + if (ps->damageEvent != ops->damageEvent && ps->damageCount) { + CG_DamageFeedback(ps->damageYaw, ps->damagePitch, ps->damageCount); } // respawning - if ( ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT] ) { + if (ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT]) { CG_Respawn(); } @@ -356,17 +347,14 @@ void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) { CG_CheckAmmo(); // run events - CG_CheckPlayerstateEvents( ps, ops ); + CG_CheckPlayerstateEvents(ps, ops); // smooth the ducking viewheight change - if ( ps->viewheight != ops->viewheight ) - { - if ( !cg.nextFrameTeleport ) - {//when we crouch/uncrouch in mid-air, our viewhieght doesn't actually change in - //absolute world coordinates, just locally. + if (ps->viewheight != ops->viewheight) { + if (!cg.nextFrameTeleport) { // when we crouch/uncrouch in mid-air, our viewhieght doesn't actually change in + // absolute world coordinates, just locally. cg.duckChange = ps->viewheight - ops->viewheight; cg.duckTime = cg.time; } } } - diff --git a/codeJK2/cgame/cg_predict.cpp b/codeJK2/cgame/cg_predict.cpp index 6c92ef4d85..7ddfd79676 100644 --- a/codeJK2/cgame/cg_predict.cpp +++ b/codeJK2/cgame/cg_predict.cpp @@ -29,10 +29,10 @@ along with this program; if not, see . #include "../game/g_local.h" #include "cg_media.h" -static pmove_t cg_pmove; +static pmove_t cg_pmove; -static int cg_numSolidEntities; -static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; +static int cg_numSolidEntities; +static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; /* ==================== @@ -43,26 +43,21 @@ of the entities that are actually solid, to make for more efficient collision detection ==================== */ -void CG_BuildSolidList( void ) -{ - int i; - centity_t *cent; +void CG_BuildSolidList(void) { + int i; + centity_t *cent; cg_numSolidEntities = 0; - if(!cg.snap) - { + if (!cg.snap) { return; } - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) - { - if ( cg.snap->entities[ i ].number < ENTITYNUM_WORLD ) - { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + if (cg.snap->entities[i].number < ENTITYNUM_WORLD) { + cent = &cg_entities[cg.snap->entities[i].number]; - if ( cent->gent != NULL && cent->gent->s.solid ) - { + if (cent->gent != NULL && cent->gent->s.solid) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; } @@ -76,60 +71,57 @@ CG_ClipMoveToEntities ==================== */ -void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask, trace_t *tr ) { - int i, x, zd, zu; - trace_t trace; - entityState_t *ent; - clipHandle_t cmodel; - vec3_t bmins, bmaxs; - vec3_t origin, angles; - centity_t *cent; - - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; +void CG_ClipMoveToEntities(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask, trace_t *tr) { + int i, x, zd, zu; + trace_t trace; + entityState_t *ent; + clipHandle_t cmodel; + vec3_t bmins, bmaxs; + vec3_t origin, angles; + centity_t *cent; + + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == skipNumber ) { + if (ent->number == skipNumber) { continue; } - if ( ent->eType == ET_PUSH_TRIGGER ) { + if (ent->eType == ET_PUSH_TRIGGER) { continue; } - if ( ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_TELEPORT_TRIGGER) { continue; } - if ( ent->solid == SOLID_BMODEL ) { + if (ent->solid == SOLID_BMODEL) { // special value for bmodel - cmodel = cgi_CM_InlineModel( ent->modelindex ); - VectorCopy( cent->lerpAngles, angles ); + cmodel = cgi_CM_InlineModel(ent->modelindex); + VectorCopy(cent->lerpAngles, angles); - //Hmm... this would cause traces against brush movers to snap at 20fps (as with the third person camera)... - //Let's use the lerpOrigin for now and see if it breaks anything... - //EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, origin ); - VectorCopy( cent->lerpOrigin, origin ); + // Hmm... this would cause traces against brush movers to snap at 20fps (as with the third person camera)... + // Let's use the lerpOrigin for now and see if it breaks anything... + // EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, origin ); + VectorCopy(cent->lerpOrigin, origin); } else { // encoded bbox x = (ent->solid & 255); - zd = ((ent->solid>>8) & 255); - zu = ((ent->solid>>16) & 255) - 32; + zd = ((ent->solid >> 8) & 255); + zu = ((ent->solid >> 16) & 255) - 32; bmins[0] = bmins[1] = -x; bmaxs[0] = bmaxs[1] = x; bmins[2] = -zd; bmaxs[2] = zu; - cmodel = cgi_CM_TempBoxModel( bmins, bmaxs );//, cent->gent->contents ); - VectorCopy( vec3_origin, angles ); - VectorCopy( cent->lerpOrigin, origin ); + cmodel = cgi_CM_TempBoxModel(bmins, bmaxs); //, cent->gent->contents ); + VectorCopy(vec3_origin, angles); + VectorCopy(cent->lerpOrigin, origin); } - - cgi_CM_TransformedBoxTrace ( &trace, start, end, - mins, maxs, cmodel, mask, origin, angles); + cgi_CM_TransformedBoxTrace(&trace, start, end, mins, maxs, cmodel, mask, origin, angles); if (trace.allsolid || trace.fraction < tr->fraction) { trace.entityNum = ent->number; @@ -137,7 +129,7 @@ void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t } else if (trace.startsolid) { tr->startsolid = qtrue; } - if ( tr->allsolid ) { + if (tr->allsolid) { return; } } @@ -148,14 +140,14 @@ void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t CG_Trace ================ */ -void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - const int skipNumber, const int mask, const EG2_Collision eG2TraceType/*=G2_NOCOLLIDE*/, const int useLod/*=0*/) { - trace_t t; +void CG_Trace(trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int skipNumber, const int mask, + const EG2_Collision eG2TraceType /*=G2_NOCOLLIDE*/, const int useLod /*=0*/) { + trace_t t; - cgi_CM_BoxTrace ( &t, start, end, mins, maxs, 0, mask); + cgi_CM_BoxTrace(&t, start, end, mins, maxs, 0, mask); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models - CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t); + CG_ClipMoveToEntities(start, mins, maxs, end, skipNumber, mask, &t); *result = t; } @@ -165,21 +157,21 @@ void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec CG_PointContents ================ */ -int CG_PointContents( const vec3_t point, int passEntityNum ) { - int i; - entityState_t *ent; - centity_t *cent; +int CG_PointContents(const vec3_t point, int passEntityNum) { + int i; + entityState_t *ent; + centity_t *cent; clipHandle_t cmodel; - int contents; + int contents; - contents = cgi_CM_PointContents (point, 0); + contents = cgi_CM_PointContents(point, 0); - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == passEntityNum ) { + if (ent->number == passEntityNum) { continue; } @@ -187,98 +179,80 @@ int CG_PointContents( const vec3_t point, int passEntityNum ) { continue; } - cmodel = cgi_CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = cgi_CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - contents |= cgi_CM_TransformedPointContents( point, cmodel, ent->origin, ent->angles ); + contents |= cgi_CM_TransformedPointContents(point, cmodel, ent->origin, ent->angles); } return contents; } - -void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ) -{ - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD || overrideViewEnt ) - {//don't clamp angles when looking through a viewEntity - for( int i = 0; i < 3; i++ ) - { +void CG_SetClientViewAngles(vec3_t angles, qboolean overrideViewEnt) { + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD || overrideViewEnt) { // don't clamp angles when looking through a viewEntity + for (int i = 0; i < 3; i++) { cg.predicted_player_state.viewangles[PITCH] = angles[i]; cg.predicted_player_state.delta_angles[i] = 0; cg.snap->ps.viewangles[PITCH] = angles[i]; cg.snap->ps.delta_angles[i] = 0; g_entities[0].client->pers.cmd_angles[i] = ANGLE2SHORT(angles[i]); } - cgi_SetUserCmdAngles( angles[PITCH], angles[YAW], angles[ROLL] ); + cgi_SetUserCmdAngles(angles[PITCH], angles[YAW], angles[ROLL]); } } -extern qboolean PM_AdjustAnglesToGripper( gentity_t *gent, usercmd_t *cmd ); -extern qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); -extern qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ); -extern qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ); -extern qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ); -qboolean CG_CheckModifyUCmd( usercmd_t *cmd, vec3_t viewangles ) -{ +extern qboolean PM_AdjustAnglesToGripper(gentity_t *gent, usercmd_t *cmd); +extern qboolean PM_AdjustAngleForWallRun(gentity_t *ent, usercmd_t *ucmd, qboolean doMove); +extern qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly); +extern qboolean PM_AdjustAnglesForBackAttack(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForSaberLock(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForKnockdown(gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly); +extern qboolean G_CheckClampUcmd(gentity_t *ent, usercmd_t *ucmd); +qboolean CG_CheckModifyUCmd(usercmd_t *cmd, vec3_t viewangles) { qboolean overridAngles = qfalse; - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//controlling something else - memset( cmd, 0, sizeof( usercmd_t ) ); + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // controlling something else + memset(cmd, 0, sizeof(usercmd_t)); /* //to keep pointing in same dir, need to set cmd.angles cmd->angles[PITCH] = ANGLE2SHORT( cg.snap->ps.viewangles[PITCH] ) - cg.snap->ps.delta_angles[PITCH]; cmd->angles[YAW] = ANGLE2SHORT( cg.snap->ps.viewangles[YAW] ) - cg.snap->ps.delta_angles[YAW]; cmd->angles[ROLL] = 0; */ - VectorCopy( g_entities[0].pos4, viewangles ); + VectorCopy(g_entities[0].pos4, viewangles); overridAngles = qtrue; - //CG_SetClientViewAngles( g_entities[cg.snap->ps.viewEntity].client->ps.viewangles, qtrue ); - } - else if ( cg.snap->ps.vehicleModel != 0 ) - {//in vehicle flight mode - float speed = VectorLength( cg.snap->ps.velocity ); - if ( !speed || cg.snap->ps.groundEntityNum != ENTITYNUM_NONE ) - { + // CG_SetClientViewAngles( g_entities[cg.snap->ps.viewEntity].client->ps.viewangles, qtrue ); + } else if (cg.snap->ps.vehicleModel != 0) { // in vehicle flight mode + float speed = VectorLength(cg.snap->ps.velocity); + if (!speed || cg.snap->ps.groundEntityNum != ENTITYNUM_NONE) { cmd->rightmove = 0; cmd->angles[PITCH] = 0; - cmd->angles[YAW] = ANGLE2SHORT( cg.snap->ps.viewangles[YAW] ) - cg.snap->ps.delta_angles[YAW]; - CG_SetClientViewAngles( cg.snap->ps.viewangles, qfalse ); + cmd->angles[YAW] = ANGLE2SHORT(cg.snap->ps.viewangles[YAW]) - cg.snap->ps.delta_angles[YAW]; + CG_SetClientViewAngles(cg.snap->ps.viewangles, qfalse); } } - if ( g_entities[0].inuse && g_entities[0].client ) - { - if ( !PM_AdjustAnglesToGripper( &g_entities[0], cmd ) ) - { - if ( PM_AdjustAnglesForSpinningFlip( &g_entities[0], cmd, qtrue ) ) - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + if (g_entities[0].inuse && g_entities[0].client) { + if (!PM_AdjustAnglesToGripper(&g_entities[0], cmd)) { + if (PM_AdjustAnglesForSpinningFlip(&g_entities[0], cmd, qtrue)) { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } - } - else - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + } else { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } - if ( G_CheckClampUcmd( &g_entities[0], cmd ) ) - { - CG_SetClientViewAngles( g_entities[0].client->ps.viewangles, qfalse ); - if ( viewangles ) - { - VectorCopy( g_entities[0].client->ps.viewangles, viewangles ); + if (G_CheckClampUcmd(&g_entities[0], cmd)) { + CG_SetClientViewAngles(g_entities[0].client->ps.viewangles, qfalse); + if (viewangles) { + VectorCopy(g_entities[0].client->ps.viewangles, viewangles); overridAngles = qtrue; } } @@ -286,26 +260,17 @@ qboolean CG_CheckModifyUCmd( usercmd_t *cmd, vec3_t viewangles ) return overridAngles; } -qboolean CG_OnMovingPlat( playerState_t *ps ) -{ - if ( ps->groundEntityNum != ENTITYNUM_NONE ) - { +qboolean CG_OnMovingPlat(playerState_t *ps) { + if (ps->groundEntityNum != ENTITYNUM_NONE) { entityState_t *es = &cg_entities[ps->groundEntityNum].currentState; - if ( es->eType == ET_MOVER ) - {//on a mover - if ( es->pos.trType != TR_STATIONARY ) - { - if ( es->pos.trType != TR_LINEAR_STOP && es->pos.trType != TR_NONLINEAR_STOP ) - {//a constant mover - if ( !VectorCompare( vec3_origin, es->pos.trDelta ) ) - {//is moving + if (es->eType == ET_MOVER) { // on a mover + if (es->pos.trType != TR_STATIONARY) { + if (es->pos.trType != TR_LINEAR_STOP && es->pos.trType != TR_NONLINEAR_STOP) { // a constant mover + if (!VectorCompare(vec3_origin, es->pos.trDelta)) { // is moving return qtrue; } - } - else - {//a linear-stop mover - if ( es->pos.trTime+es->pos.trDuration > cg.time ) - {//still moving + } else { // a linear-stop mover + if (es->pos.trTime + es->pos.trDuration > cg.time) { // still moving return qtrue; } } @@ -322,141 +287,112 @@ Generates cg.predicted_player_state by interpolating between cg.snap->player_state and cg.nextFrame->player_state ======================== */ -void CG_InterpolatePlayerState( qboolean grabAngles ) { - float f; - int i; - playerState_t *out; - snapshot_t *prev, *next; - qboolean skip = qfalse; - vec3_t oldOrg; +void CG_InterpolatePlayerState(qboolean grabAngles) { + float f; + int i; + playerState_t *out; + snapshot_t *prev, *next; + qboolean skip = qfalse; + vec3_t oldOrg; out = &cg.predicted_player_state; prev = cg.snap; next = cg.nextSnap; - VectorCopy(out->origin,oldOrg); + VectorCopy(out->origin, oldOrg); *out = cg.snap->ps; // if we are still allowing local input, short circuit the view angles - if ( grabAngles ) { - usercmd_t cmd; - int cmdNum; + if (grabAngles) { + usercmd_t cmd; + int cmdNum; cmdNum = cgi_GetCurrentCmdNumber(); - cgi_GetUserCmd( cmdNum, &cmd ); + cgi_GetUserCmd(cmdNum, &cmd); - skip = CG_CheckModifyUCmd( &cmd, out->viewangles ); + skip = CG_CheckModifyUCmd(&cmd, out->viewangles); - if ( !skip ) - { - //NULL so that it doesn't execute a block of code that must be run from game - PM_UpdateViewAngles( out, &cmd, NULL ); + if (!skip) { + // NULL so that it doesn't execute a block of code that must be run from game + PM_UpdateViewAngles(out, &cmd, NULL); } } // if the next frame is a teleport, we can't lerp to it - if ( cg.nextFrameTeleport ) - { + if (cg.nextFrameTeleport) { return; } - if (!( !next || next->serverTime <= prev->serverTime ) ) - { + if (!(!next || next->serverTime <= prev->serverTime)) { + + f = (float)(cg.time - prev->serverTime) / (next->serverTime - prev->serverTime); - f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime ); - i = next->ps.bobCycle; - if ( i < prev->ps.bobCycle ) - { - i += 256; // handle wraparound + if (i < prev->ps.bobCycle) { + i += 256; // handle wraparound } - out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle ); + out->bobCycle = prev->ps.bobCycle + f * (i - prev->ps.bobCycle); - for ( i = 0 ; i < 3 ; i++ ) - { - out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i] ); - if ( !grabAngles ) - { - out->viewangles[i] = LerpAngle( - prev->ps.viewangles[i], next->ps.viewangles[i], f ); + for (i = 0; i < 3; i++) { + out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i]); + if (!grabAngles) { + out->viewangles[i] = LerpAngle(prev->ps.viewangles[i], next->ps.viewangles[i], f); } - out->velocity[i] = prev->ps.velocity[i] + - f * (next->ps.velocity[i] - prev->ps.velocity[i] ); + out->velocity[i] = prev->ps.velocity[i] + f * (next->ps.velocity[i] - prev->ps.velocity[i]); } } - bool onPlat=false; - centity_t *pent=0; - if (out->groundEntityNum>0) - { - pent=&cg_entities[out->groundEntityNum]; - if (pent->currentState.eType == ET_MOVER ) + bool onPlat = false; + centity_t *pent = 0; + if (out->groundEntityNum > 0) { + pent = &cg_entities[out->groundEntityNum]; + if (pent->currentState.eType == ET_MOVER) { - onPlat=true; + onPlat = true; } } - if ( - cg.validPPS && - cg_smoothPlayerPos.value>0.0f && - cg_smoothPlayerPos.value<1.0f && - !onPlat - ) - { + if (cg.validPPS && cg_smoothPlayerPos.value > 0.0f && cg_smoothPlayerPos.value < 1.0f && !onPlat) { // 0 = no smoothing, 1 = no movement - for (i=0;i<3;i++) - { - out->origin[i]=cg_smoothPlayerPos.value*(oldOrg[i]-out->origin[i])+out->origin[i]; + for (i = 0; i < 3; i++) { + out->origin[i] = cg_smoothPlayerPos.value * (oldOrg[i] - out->origin[i]) + out->origin[i]; } - } - else if (onPlat&&cg_smoothPlayerPlat.value>0.0f&&cg_smoothPlayerPlat.value<1.0f) - { -// if (cg.frametime<150) -// { + } else if (onPlat && cg_smoothPlayerPlat.value > 0.0f && cg_smoothPlayerPlat.value < 1.0f) { + // if (cg.frametime<150) + // { assert(pent); - vec3_t p1,p2,vel; + vec3_t p1, p2, vel; float lerpTime; - - EvaluateTrajectory( &pent->currentState.pos,cg.snap->serverTime, p1 ); - if ( cg.nextSnap &&cg.nextSnap->serverTime > cg.snap->serverTime) - { - EvaluateTrajectory( &pent->nextState.pos,cg.nextSnap->serverTime, p2 ); - lerpTime=float(cg.nextSnap->serverTime - cg.snap->serverTime); - } - else - { - EvaluateTrajectory( &pent->currentState.pos,cg.snap->serverTime+50, p2 ); - lerpTime=50.0f; + EvaluateTrajectory(&pent->currentState.pos, cg.snap->serverTime, p1); + if (cg.nextSnap && cg.nextSnap->serverTime > cg.snap->serverTime) { + EvaluateTrajectory(&pent->nextState.pos, cg.nextSnap->serverTime, p2); + lerpTime = float(cg.nextSnap->serverTime - cg.snap->serverTime); + } else { + EvaluateTrajectory(&pent->currentState.pos, cg.snap->serverTime + 50, p2); + lerpTime = 50.0f; } - float accel=cg_smoothPlayerPlatAccel.value*cg.frametime/lerpTime; + float accel = cg_smoothPlayerPlatAccel.value * cg.frametime / lerpTime; - if (accel>20.0f) - { - accel=20.0f; + if (accel > 20.0f) { + accel = 20.0f; } - for (i=0;i<3;i++) - { - vel[i]=accel*(p2[i]-p1[i]); + for (i = 0; i < 3; i++) { + vel[i] = accel * (p2[i] - p1[i]); } - VectorAdd(out->origin,vel,out->origin); + VectorAdd(out->origin, vel, out->origin); - if (cg.validPPS && - cg_smoothPlayerPlat.value>0.0f && - cg_smoothPlayerPlat.value<1.0f - ) - { + if (cg.validPPS && cg_smoothPlayerPlat.value > 0.0f && cg_smoothPlayerPlat.value < 1.0f) { // 0 = no smoothing, 1 = no movement - for (i=0;i<3;i++) - { - out->origin[i]=cg_smoothPlayerPlat.value*(oldOrg[i]-out->origin[i])+out->origin[i]; + for (i = 0; i < 3; i++) { + out->origin[i] = cg_smoothPlayerPlat.value * (oldOrg[i] - out->origin[i]) + out->origin[i]; } } -// } + // } } } @@ -465,26 +401,26 @@ void CG_InterpolatePlayerState( qboolean grabAngles ) { CG_TouchItem =================== */ -void CG_TouchItem( centity_t *cent ) { - gitem_t *item; +void CG_TouchItem(centity_t *cent) { + gitem_t *item; // never pick an item up twice in a prediction - if ( cent->miscTime == cg.time ) { + if (cent->miscTime == cg.time) { return; } - if ( !BG_PlayerTouchesItem( &cg.predicted_player_state, ¢->currentState, cg.time ) ) { + if (!BG_PlayerTouchesItem(&cg.predicted_player_state, ¢->currentState, cg.time)) { return; } - if ( !BG_CanItemBeGrabbed( ¢->currentState, &cg.predicted_player_state ) ) { - return; // can't hold it + if (!BG_CanItemBeGrabbed(¢->currentState, &cg.predicted_player_state)) { + return; // can't hold it } - item = &bg_itemlist[ cent->currentState.modelindex ]; + item = &bg_itemlist[cent->currentState.modelindex]; // grab it - AddEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.modelindex , &cg.predicted_player_state); + AddEventToPlayerstate(EV_ITEM_PICKUP, cent->currentState.modelindex, &cg.predicted_player_state); // remove it from the frame so it won't be drawn cent->currentState.eFlags |= EF_NODRAW; @@ -493,16 +429,15 @@ void CG_TouchItem( centity_t *cent ) { cent->miscTime = cg.time; // if its a weapon, give them some predicted ammo so the autoswitch will work - if ( item->giType == IT_WEAPON ) { + if (item->giType == IT_WEAPON) { int ammotype = weaponData[item->giTag].ammoIndex; - cg.predicted_player_state.stats[ STAT_WEAPONS ] |= 1 << item->giTag; - if ( !cg.predicted_player_state.ammo[ ammotype] ) { - cg.predicted_player_state.ammo[ ammotype ] = 1; + cg.predicted_player_state.stats[STAT_WEAPONS] |= 1 << item->giTag; + if (!cg.predicted_player_state.ammo[ammotype]) { + cg.predicted_player_state.ammo[ammotype] = 1; } } } - /* ========================= CG_TouchTriggerPrediction @@ -511,68 +446,66 @@ Predict push triggers and items Only called for the last command ========================= */ -void CG_TouchTriggerPrediction( void ) { - int i; - trace_t trace; - entityState_t *ent; +void CG_TouchTriggerPrediction(void) { + int i; + trace_t trace; + entityState_t *ent; clipHandle_t cmodel; - centity_t *cent; - qboolean spectator; + centity_t *cent; + qboolean spectator; // dead clients don't activate triggers - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 ) { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0) { return; } - spectator = (qboolean)( cg.predicted_player_state.pm_type == PM_SPECTATOR ); + spectator = (qboolean)(cg.predicted_player_state.pm_type == PM_SPECTATOR); - if ( cg.predicted_player_state.pm_type != PM_NORMAL && !spectator ) { + if (cg.predicted_player_state.pm_type != PM_NORMAL && !spectator) { return; } - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; ent = ¢->currentState; - if ( ent->eType == ET_ITEM && !spectator ) { - CG_TouchItem( cent ); + if (ent->eType == ET_ITEM && !spectator) { + CG_TouchItem(cent); continue; } - if ( ent->eType != ET_PUSH_TRIGGER && ent->eType != ET_TELEPORT_TRIGGER ) { + if (ent->eType != ET_PUSH_TRIGGER && ent->eType != ET_TELEPORT_TRIGGER) { continue; } - if ( ent->solid != SOLID_BMODEL ) { + if (ent->solid != SOLID_BMODEL) { continue; } - cmodel = cgi_CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = cgi_CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - cgi_CM_BoxTrace( &trace, cg.predicted_player_state.origin, cg.predicted_player_state.origin, - cg_pmove.mins, cg_pmove.maxs, cmodel, -1 ); + cgi_CM_BoxTrace(&trace, cg.predicted_player_state.origin, cg.predicted_player_state.origin, cg_pmove.mins, cg_pmove.maxs, cmodel, -1); - if ( !trace.startsolid ) { + if (!trace.startsolid) { continue; } - if ( ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_TELEPORT_TRIGGER) { cg.hyperspace = qtrue; } else { // we hit this push trigger - if ( spectator ) { + if (spectator) { continue; } - VectorCopy( ent->origin2, cg.predicted_player_state.velocity ); + VectorCopy(ent->origin2, cg.predicted_player_state.velocity); } } } - /* ================= CG_PredictPlayerState @@ -595,23 +528,22 @@ We detect prediction errors and allow them to be decayed off over several frames to ease the jerk. ================= */ -extern qboolean player_locked; -void CG_PredictPlayerState( void ) { - int cmdNum, current; - playerState_t oldPlayerState; +extern qboolean player_locked; +void CG_PredictPlayerState(void) { + int cmdNum, current; + playerState_t oldPlayerState; - cg.hyperspace = qfalse; // will be set if touching a trigger_teleport + cg.hyperspace = qfalse; // will be set if touching a trigger_teleport // if this is the first frame we must guarantee // predicted_player_state is valid even if there is some // other error condition - if ( !cg.validPPS ) { + if (!cg.validPPS) { cg.validPPS = qtrue; cg.predicted_player_state = cg.snap->ps; } - - if ( 1 )//cg_timescale.value >= 1.0f ) + if (1) // cg_timescale.value >= 1.0f ) { // demo playback just copies the moves /* @@ -622,18 +554,18 @@ void CG_PredictPlayerState( void ) { */ // non-predicting local movement will grab the latest angles - CG_InterpolatePlayerState( qtrue ); + CG_InterpolatePlayerState(qtrue); return; } // prepare for pmove - //FIXME: is this bad??? + // FIXME: is this bad??? cg_pmove.gent = NULL; cg_pmove.ps = &cg.predicted_player_state; cg_pmove.trace = CG_Trace; cg_pmove.pointcontents = CG_PointContents; cg_pmove.tracemask = MASK_PLAYERSOLID; - cg_pmove.noFootsteps = qfalse;//( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; + cg_pmove.noFootsteps = qfalse; //( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; // save the state before the pmove so we can detect transitions oldPlayerState = cg.predicted_player_state; @@ -642,16 +574,16 @@ void CG_PredictPlayerState( void ) { cmdNum = cg.snap->cmdNum; current = cgi_GetCurrentCmdNumber(); - if ( current - cmdNum >= CMD_BACKUP ) { - return; + if (current - cmdNum >= CMD_BACKUP) { + return; } // get the most recent information we have cg.predicted_player_state = cg.snap->ps; // we should always be predicting at least one frame - if ( cmdNum >= current ) { - return; + if (cmdNum >= current) { + return; } // run cmds @@ -661,36 +593,35 @@ void CG_PredictPlayerState( void ) { // from the snapshot, but on a wan we will have // to predict several commands to get to the point // we want to compare - if ( cmdNum == current - 1 ) { - vec3_t delta; - float len; + if (cmdNum == current - 1) { + vec3_t delta; + float len; - if ( cg.thisFrameTeleport ) { + if (cg.thisFrameTeleport) { // a teleport will not cause an error decay - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); cg.thisFrameTeleport = qfalse; } else { - vec3_t adjusted; - CG_AdjustPositionForMover( cg.predicted_player_state.origin, - cg.predicted_player_state.groundEntityNum, cg.oldTime, adjusted ); + vec3_t adjusted; + CG_AdjustPositionForMover(cg.predicted_player_state.origin, cg.predicted_player_state.groundEntityNum, cg.oldTime, adjusted); - VectorSubtract( oldPlayerState.origin, adjusted, delta ); - len = VectorLength( delta ); - if ( len > 0.1 ) { - if ( cg_errorDecay.integer ) { - int t; - float f; + VectorSubtract(oldPlayerState.origin, adjusted, delta); + len = VectorLength(delta); + if (len > 0.1) { + if (cg_errorDecay.integer) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f < 0 ) { + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f < 0) { f = 0; } - VectorScale( cg.predictedError, f, cg.predictedError ); + VectorScale(cg.predictedError, f, cg.predictedError); } else { - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); } - VectorAdd( delta, cg.predictedError, cg.predictedError ); + VectorAdd(delta, cg.predictedError, cg.predictedError); cg.predictedErrorTime = cg.oldTime; } } @@ -701,38 +632,32 @@ void CG_PredictPlayerState( void ) { // this should never happen, because we check ranges at // the top of the function cmdNum++; - if ( !cgi_GetUserCmd( cmdNum, &cg_pmove.cmd ) ) { + if (!cgi_GetUserCmd(cmdNum, &cg_pmove.cmd)) { break; } - gentity_t *ent = &g_entities[0];//cheating and dirty, I know, but this is a SP game so prediction can cheat - if ( player_locked || - (ent && !ent->s.number&&ent->aimDebounceTime>level.time) || - (ent && ent->client && ent->client->ps.pm_time && (ent->client->ps.pm_flags&PMF_TIME_KNOCKBACK)) || - (ent && ent->forcePushTime > level.time) ) - {//lock out player control unless dead - //VectorClear( cg_pmove.cmd.angles ); + gentity_t *ent = &g_entities[0]; // cheating and dirty, I know, but this is a SP game so prediction can cheat + if (player_locked || (ent && !ent->s.number && ent->aimDebounceTime > level.time) || + (ent && ent->client && ent->client->ps.pm_time && (ent->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) || + (ent && ent->forcePushTime > level.time)) { // lock out player control unless dead + // VectorClear( cg_pmove.cmd.angles ); cg_pmove.cmd.forwardmove = 0; cg_pmove.cmd.rightmove = 0; cg_pmove.cmd.buttons = 0; cg_pmove.cmd.upmove = 0; } - CG_CheckModifyUCmd( &cg_pmove.cmd, NULL ); - //FIXME: prediction on clients in timescale results in jerky positional translation - Pmove( &cg_pmove ); - + CG_CheckModifyUCmd(&cg_pmove.cmd, NULL); + // FIXME: prediction on clients in timescale results in jerky positional translation + Pmove(&cg_pmove); + // add push trigger movement effects CG_TouchTriggerPrediction(); - } while ( cmdNum < current ); + } while (cmdNum < current); // adjust for the movement of the groundentity - CG_AdjustPositionForMover( cg.predicted_player_state.origin, - cg.predicted_player_state.groundEntityNum, - cg.time, cg.predicted_player_state.origin ); + CG_AdjustPositionForMover(cg.predicted_player_state.origin, cg.predicted_player_state.groundEntityNum, cg.time, cg.predicted_player_state.origin); // fire events and other transition triggered things - CG_TransitionPlayerState( &cg.predicted_player_state, &oldPlayerState ); + CG_TransitionPlayerState(&cg.predicted_player_state, &oldPlayerState); } - - diff --git a/codeJK2/cgame/cg_scoreboard.cpp b/codeJK2/cgame/cg_scoreboard.cpp index 27fb1acb30..0d268be989 100644 --- a/codeJK2/cgame/cg_scoreboard.cpp +++ b/codeJK2/cgame/cg_scoreboard.cpp @@ -26,8 +26,7 @@ along with this program; if not, see . #include "../game/objectives.h" #include "../game/b_local.h" -#define SCOREBOARD_WIDTH (26*BIGCHAR_WIDTH) - +#define SCOREBOARD_WIDTH (26 * BIGCHAR_WIDTH) /* static void Scoreboard_Draw( void ) @@ -61,7 +60,7 @@ static void Scoreboard_Draw( void ) CG_DrawPic(120, 100, 18, 12, cgs.media.whiteShader); // Middle Top CG_DrawPic(120, 353, 18, 4, cgs.media.whiteShader); // Middle Bottom - + CG_DrawPic(130,357, 482, 18, cgs.media.whiteShader); // Bottom // Left side box @@ -81,259 +80,259 @@ static void Scoreboard_Draw( void ) } */ - - /* ================= CG_MissionFailed ================= */ int statusTextIndex = -1; -void CG_MissionFailed(void) -{ - char text[1024]={0}; +void CG_MissionFailed(void) { + char text[1024] = {0}; int w; int y = 230; - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED", text, sizeof(text) ); - - w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); - cgi_R_Font_DrawString(320 - w/2, y, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); - - switch (statusTextIndex) - { - case -1: //Our HERO DIED!!! - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_KYLE", text, sizeof(text) ); - break; - case MISSIONFAILED_JAN: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_JAN", text, sizeof(text) ); - break; - case MISSIONFAILED_LUKE: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_LUKE", text, sizeof(text) ); - break; - case MISSIONFAILED_LANDO: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_LANDO", text, sizeof(text) ); - break; - case MISSIONFAILED_R5D2: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_R5D2", text, sizeof(text) ); - break; - case MISSIONFAILED_WARDEN: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_WARDEN", text, sizeof(text) ); - break; - case MISSIONFAILED_PRISONERS: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_PRISONERS", text, sizeof(text) ); - break; - case MISSIONFAILED_EMPLACEDGUNS: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_EMPLACEDGUNS", text, sizeof(text) ); - break; - case MISSIONFAILED_LADYLUCK: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_LADYLUCK", text, sizeof(text) ); - break; - case MISSIONFAILED_KYLECAPTURE: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_KYLECAPTURE", text, sizeof(text) ); - break; - case MISSIONFAILED_TOOMANYALLIESDIED: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_TOOMANYALLIESDIED", text, sizeof(text) ); - break; - default: - cgi_SP_GetStringTextString( "INGAME_MISSIONFAILED_UNKNOWN", text, sizeof(text) ); - break; + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED", text, sizeof(text)); + + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); + cgi_R_Font_DrawString(320 - w / 2, y, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); + + switch (statusTextIndex) { + case -1: // Our HERO DIED!!! + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_KYLE", text, sizeof(text)); + break; + case MISSIONFAILED_JAN: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_JAN", text, sizeof(text)); + break; + case MISSIONFAILED_LUKE: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_LUKE", text, sizeof(text)); + break; + case MISSIONFAILED_LANDO: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_LANDO", text, sizeof(text)); + break; + case MISSIONFAILED_R5D2: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_R5D2", text, sizeof(text)); + break; + case MISSIONFAILED_WARDEN: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_WARDEN", text, sizeof(text)); + break; + case MISSIONFAILED_PRISONERS: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_PRISONERS", text, sizeof(text)); + break; + case MISSIONFAILED_EMPLACEDGUNS: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_EMPLACEDGUNS", text, sizeof(text)); + break; + case MISSIONFAILED_LADYLUCK: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_LADYLUCK", text, sizeof(text)); + break; + case MISSIONFAILED_KYLECAPTURE: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_KYLECAPTURE", text, sizeof(text)); + break; + case MISSIONFAILED_TOOMANYALLIESDIED: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_TOOMANYALLIESDIED", text, sizeof(text)); + break; + default: + cgi_SP_GetStringTextString("INGAME_MISSIONFAILED_UNKNOWN", text, sizeof(text)); + break; } - w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); - cgi_R_Font_DrawString(320 - w/2, y+30, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); - - cgi_SP_GetStringTextString( "INGAME_RELOADMISSION", text, sizeof(text) ); - w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - cgi_R_Font_DrawString(320 - w/2, 450, text, colorTable[CT_CYAN], cgs.media.qhFontSmall, -1, 1.0f); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); + cgi_R_Font_DrawString(320 - w / 2, y + 30, text, colorTable[CT_HUD_RED], cgs.media.qhFontMedium, -1, 1.2f); + cgi_SP_GetStringTextString("INGAME_RELOADMISSION", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); + cgi_R_Font_DrawString(320 - w / 2, 450, text, colorTable[CT_CYAN], cgs.media.qhFontSmall, -1, 1.0f); } - /* ================= CG_MissionCompletion ================= */ -void CG_MissionCompletion(void) -{ - char text[1024]={0}; - int w,x,y; +void CG_MissionCompletion(void) { + char text[1024] = {0}; + int w, x, y; const int pad = 18; - cgi_SP_GetStringTextString( "INGAME_MISSIONCOMPLETION", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); - cgi_R_Font_DrawString(320 - w/2, 53, text, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.2f); + cgi_SP_GetStringTextString("INGAME_MISSIONCOMPLETION", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontMedium, 1.2f); + cgi_R_Font_DrawString(320 - w / 2, 53, text, colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.2f); x = 75; - y =86; - cgi_SP_GetStringTextString( "INGAME_SECRETAREAS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_SP_GetStringTextString( "INGAME_SECRETAREAS_OF", text, sizeof(text) ); - cgi_R_Font_DrawString(x+w, y, va("%d %s %d", - cg_entities[0].gent->client->sess.missionStats.secretsFound, - text, - cg_entities[0].gent->client->sess.missionStats.totalSecrets - ), - colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_ENEMIESKILLED", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + y = 86; + cgi_SP_GetStringTextString("INGAME_SECRETAREAS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_SP_GetStringTextString("INGAME_SECRETAREAS_OF", text, sizeof(text)); + cgi_R_Font_DrawString( + x + w, y, + va("%d %s %d", cg_entities[0].gent->client->sess.missionStats.secretsFound, text, cg_entities[0].gent->client->sess.missionStats.totalSecrets), + colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_ENEMIESKILLED", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w,y, va("%d",cg_entities[0].gent->client->sess.missionStats.enemiesKilled), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.enemiesKilled), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); /* cgi_SP_GetStringTextString( "INGAME_SECRETAREAS_OF", text, sizeof(text) ); cgi_R_Font_DrawString(x+w,y, va("%d %s %d", cg_entities[0].gent->client->sess.missionStats.enemiesKilled, text, cg_entities[0].gent->client->sess.missionStats.enemiesSpawned - ), + ), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); */ - y +=pad; - y +=pad; - cgi_SP_GetStringTextString( "INGAME_FAVORITEWEAPON", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + y += pad; + y += pad; + cgi_SP_GetStringTextString("INGAME_FAVORITEWEAPON", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - - int wpn=0,i; + + int wpn = 0, i; int max_wpn = cg_entities[0].gent->client->sess.missionStats.weaponUsed[0]; - for (i = 1; iclient->sess.missionStats.weaponUsed[i] > max_wpn) - { + for (i = 1; i < WP_NUM_WEAPONS; i++) { + if (cg_entities[0].gent->client->sess.missionStats.weaponUsed[i] > max_wpn) { max_wpn = cg_entities[0].gent->client->sess.missionStats.weaponUsed[i]; wpn = i; } } - if ( wpn ) - { - gitem_t *wItem= FindItemForWeapon( (weapon_t)wpn); - cgi_SP_GetStringTextString( va("INGAME_%s",wItem->classname ), text, sizeof( text )); - // cgi_R_Font_DrawString(x+w, y, va("%d",wpn), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, text, colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); + if (wpn) { + gitem_t *wItem = FindItemForWeapon((weapon_t)wpn); + cgi_SP_GetStringTextString(va("INGAME_%s", wItem->classname), text, sizeof(text)); + // cgi_R_Font_DrawString(x+w, y, va("%d",wpn), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, text, colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); } - x = 334+70; + x = 334 + 70; y = 86; - cgi_SP_GetStringTextString( "INGAME_SHOTSFIRED", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_SP_GetStringTextString("INGAME_SHOTSFIRED", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.shotsFired), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.shotsFired), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - y +=pad; - cgi_SP_GetStringTextString( "INGAME_HITS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + y += pad; + cgi_SP_GetStringTextString("INGAME_HITS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.hits), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.hits), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - y +=pad; - cgi_SP_GetStringTextString( "INGAME_ACCURACY", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + y += pad; + cgi_SP_GetStringTextString("INGAME_ACCURACY", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - const float percent = cg_entities[0].gent->client->sess.missionStats.shotsFired? 100.0f * (float)cg_entities[0].gent->client->sess.missionStats.hits / cg_entities[0].gent->client->sess.missionStats.shotsFired : 0; - cgi_R_Font_DrawString(x+w, y, va("%.2f%%",percent), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); + const float percent = cg_entities[0].gent->client->sess.missionStats.shotsFired + ? 100.0f * (float)cg_entities[0].gent->client->sess.missionStats.hits / cg_entities[0].gent->client->sess.missionStats.shotsFired + : 0; + cgi_R_Font_DrawString(x + w, y, va("%.2f%%", percent), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - if ( cg_entities[0].gent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0 ) - { - return; //don't have saber yet, so don't print any stats + if (cg_entities[0].gent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0) { + return; // don't have saber yet, so don't print any stats } -//first column, FORCE POWERS - y =180; - cgi_SP_GetStringTextString( "INGAME_FORCEUSE", text, sizeof(text) ); + // first column, FORCE POWERS + y = 180; + cgi_SP_GetStringTextString("INGAME_FORCEUSE", text, sizeof(text)); cgi_R_Font_DrawString(x, y, text, colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - y +=pad; - cgi_SP_GetStringTextString( "INGAME_HEAL", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_HEAL]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_SPEED", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_SPEED]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_PULL", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_PULL]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_PUSH", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_PUSH]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString("INGAME_MINDTRICK", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_TELEPATHY]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_GRIP", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_GRIP]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_LIGHTNING", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_LIGHTNING]), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - -//second column, LIGHT SABER + y += pad; + cgi_SP_GetStringTextString("INGAME_HEAL", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_HEAL]), colorTable[CT_WHITE], cgs.media.qhFontSmall, + -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_SPEED", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_SPEED]), colorTable[CT_WHITE], cgs.media.qhFontSmall, + -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_PULL", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_PULL]), colorTable[CT_WHITE], cgs.media.qhFontSmall, + -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_PUSH", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_PUSH]), colorTable[CT_WHITE], cgs.media.qhFontSmall, + -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_MINDTRICK", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_TELEPATHY]), colorTable[CT_WHITE], + cgs.media.qhFontSmall, -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_GRIP", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_GRIP]), colorTable[CT_WHITE], cgs.media.qhFontSmall, + -1, 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_LIGHTNING", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.forceUsed[FP_LIGHTNING]), colorTable[CT_WHITE], + cgs.media.qhFontSmall, -1, 0.8f); + + // second column, LIGHT SABER y = 180; x = 140; - cgi_SP_GetStringTextString( "INGAME_LIGHTSABERUSE", text, sizeof(text) ); + cgi_SP_GetStringTextString("INGAME_LIGHTSABERUSE", text, sizeof(text)); cgi_R_Font_DrawString(x, y, text, colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - y +=pad; - cgi_SP_GetStringTextString( "INGAME_THROWN", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.saberThrownCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_BLOCKS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.saberBlocksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_LEGATTACKS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.legAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_ARMATTACKS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.armAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_BODYATTACKS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.torsoAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); - - y +=pad; - cgi_SP_GetStringTextString( "INGAME_OTHERATTACKS", text, sizeof(text) ); -w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); - cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); - cgi_R_Font_DrawString(x+w, y, va("%d",cg_entities[0].gent->client->sess.missionStats.otherAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, 0.8f); -} + y += pad; + cgi_SP_GetStringTextString("INGAME_THROWN", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.saberThrownCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); + y += pad; + cgi_SP_GetStringTextString("INGAME_BLOCKS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.saberBlocksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_LEGATTACKS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.legAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_ARMATTACKS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.armAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_BODYATTACKS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.torsoAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); + + y += pad; + cgi_SP_GetStringTextString("INGAME_OTHERATTACKS", text, sizeof(text)); + w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 0.8f); + cgi_R_Font_DrawString(x, y, text, colorTable[CT_LTGOLD1], cgs.media.qhFontSmall, -1, 0.8f); + cgi_R_Font_DrawString(x + w, y, va("%d", cg_entities[0].gent->client->sess.missionStats.otherAttacksCnt), colorTable[CT_WHITE], cgs.media.qhFontSmall, -1, + 0.8f); +} /* ================= @@ -343,18 +342,14 @@ Draw the normal in-game scoreboard return value is bool to NOT draw centerstring ================= */ -qboolean CG_DrawScoreboard( void ) -{ +qboolean CG_DrawScoreboard(void) { // don't draw anything if the menu is up - if ( cg_paused.integer ) - { + if (cg_paused.integer) { return qfalse; } // Character is either dead, or a script has brought up the screen - if (((cg.predicted_player_state.pm_type == PM_DEAD) && (cg.missionStatusDeadTime < level.time)) - || (cg.missionStatusShow)) - { + if (((cg.predicted_player_state.pm_type == PM_DEAD) && (cg.missionStatusDeadTime < level.time)) || (cg.missionStatusShow)) { CG_MissionFailed(); return qtrue; } @@ -362,9 +357,6 @@ qboolean CG_DrawScoreboard( void ) return qfalse; } -void ScoreBoardReset(void) -{ -} +void ScoreBoardReset(void) {} //================================================================================ - diff --git a/codeJK2/cgame/cg_servercmds.cpp b/codeJK2/cgame/cg_servercmds.cpp index b5c4d3226e..69f9140f3c 100644 --- a/codeJK2/cgame/cg_servercmds.cpp +++ b/codeJK2/cgame/cg_servercmds.cpp @@ -27,7 +27,6 @@ along with this program; if not, see . #include "cg_media.h" #include "FxScheduler.h" - /* ================ CG_ParseServerinfo @@ -36,244 +35,197 @@ This is called explicitly when the gamestate is first received, and whenever the server updates any serverinfo flagged cvars ================ */ -void CG_ParseServerinfo( void ) { - const char *info; - const char *mapname; - - info = CG_ConfigString( CS_SERVERINFO ); - cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) ); - cgs.teamflags = atoi( Info_ValueForKey( info, "teamflags" ) ); - cgs.timelimit = atoi( Info_ValueForKey( info, "timelimit" ) ); +void CG_ParseServerinfo(void) { + const char *info; + const char *mapname; + + info = CG_ConfigString(CS_SERVERINFO); + cgs.dmflags = atoi(Info_ValueForKey(info, "dmflags")); + cgs.teamflags = atoi(Info_ValueForKey(info, "teamflags")); + cgs.timelimit = atoi(Info_ValueForKey(info, "timelimit")); cgs.maxclients = 1; - mapname = Info_ValueForKey( info, "mapname" ); - Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname ); - const char *p = strrchr(mapname,'/'); - Q_strncpyz( cgs.stripLevelName[0], p?p+1:mapname, sizeof(cgs.stripLevelName[0]) ); - Q_strupr( cgs.stripLevelName[0] ); - for (int i=1; i= CS_MODELS && num < CS_MODELS+MAX_MODELS ) { - cgs.model_draw[ num-CS_MODELS ] = cgi_R_RegisterModel( str ); -// OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); -// GHOUL2 Insert start - } else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) { - cgs.skins[ num-CS_CHARSKINS ] = cgi_R_RegisterSkin( str ); -// Ghoul2 Insert end - } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) { - if ( str[0] != '*' ) { - cgs.sound_precache[ num-CS_SOUNDS] = cgi_S_RegisterSound( str ); + } else if (num >= CS_MODELS && num < CS_MODELS + MAX_MODELS) { + cgs.model_draw[num - CS_MODELS] = cgi_R_RegisterModel(str); + // OutputDebugString(va("### CG_ConfigStringModified(): cgs.model_draw[%d] = \"%s\"\n",num-CS_MODELS,str)); + // GHOUL2 Insert start + } else if (num >= CS_CHARSKINS && num < CS_CHARSKINS + MAX_CHARSKINS) { + cgs.skins[num - CS_CHARSKINS] = cgi_R_RegisterSkin(str); + // Ghoul2 Insert end + } else if (num >= CS_SOUNDS && num < CS_SOUNDS + MAX_SOUNDS) { + if (str[0] != '*') { + cgs.sound_precache[num - CS_SOUNDS] = cgi_S_RegisterSound(str); } - } - else if ( num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX ) - { - theFxScheduler.RegisterEffect( str ); - } - else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) { - CG_NewClientinfo( num - CS_PLAYERS ); - CG_RegisterClientModels( num - CS_PLAYERS ); - } - else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES*3)) - { + } else if (num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX) { + theFxScheduler.RegisterEffect(str); + } else if (num >= CS_PLAYERS && num < CS_PLAYERS + MAX_CLIENTS) { + CG_NewClientinfo(num - CS_PLAYERS); + CG_RegisterClientModels(num - CS_PLAYERS); + } else if (num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES * 3)) { CG_SetLightstyle(num - CS_LIGHT_STYLES); - } - else if ( num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX ) - { - cgi_R_WorldEffectCommand( str ); + } else if (num >= CS_WORLD_FX && num < CS_WORLD_FX + MAX_WORLD_FX) { + cgi_R_WorldEffectCommand(str); } } -static void CG_CenterPrint_f( void ) { - CG_CenterPrint( CG_Argv( 1 ), SCREEN_HEIGHT * 0.25 ); -} +static void CG_CenterPrint_f(void) { CG_CenterPrint(CG_Argv(1), SCREEN_HEIGHT * 0.25); } -static void CG_Print_f( void ) { - CG_Printf( "%s", CG_Argv( 1 ) ); -} +static void CG_Print_f(void) { CG_Printf("%s", CG_Argv(1)); } -static void CG_CaptionText_f( void ) { - sfxHandle_t sound = (sfxHandle_t)atoi( CG_Argv( 2 ) ); +static void CG_CaptionText_f(void) { + sfxHandle_t sound = (sfxHandle_t)atoi(CG_Argv(2)); - CG_CaptionText( CG_Argv( 1 ), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND ); + CG_CaptionText(CG_Argv(1), sound >= 0 && sound < MAX_SOUNDS ? cgs.sound_precache[sound] : NULL_SOUND); } -static void CG_ScrollText_f( void ) { - CG_ScrollText( CG_Argv( 1 ), SCREEN_WIDTH - 16 ); -} +static void CG_ScrollText_f(void) { CG_ScrollText(CG_Argv(1), SCREEN_WIDTH - 16); } -static void CG_LCARSText_f( void ) { - CG_Printf( "CG_LCARSText() being called. Tell Ste\n" "String: \"%s\"\n", CG_Argv( 1 ) ); +static void CG_LCARSText_f(void) { + CG_Printf("CG_LCARSText() being called. Tell Ste\n" + "String: \"%s\"\n", + CG_Argv(1)); } -static void CG_ClientLevelShot_f( void ) { +static void CG_ClientLevelShot_f(void) { // clientLevelShot is sent before taking a special screenshot for // the menu system during development cg.levelShot = qtrue; } typedef struct serverCommand_s { - const char *cmd; - void( *func )(void); + const char *cmd; + void (*func)(void); } serverCommand_t; -static int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((serverCommand_t*)b)->cmd ); -} +static int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((serverCommand_t *)b)->cmd); } /* This array MUST be sorted correctly by alphabetical name field */ -static serverCommand_t commands[] = { - { "chat", CG_Print_f }, - { "clientLevelShot", CG_ClientLevelShot_f }, - { "cp", CG_CenterPrint_f }, - { "cs", CG_ConfigStringModified }, - { "ct", CG_CaptionText_f }, - { "cts", CG_CaptionTextStop }, - { "lt", CG_LCARSText_f }, - { "print", CG_Print_f }, - { "st", CG_ScrollText_f }, +static serverCommand_t commands[] = { + {"chat", CG_Print_f}, {"clientLevelShot", CG_ClientLevelShot_f}, + {"cp", CG_CenterPrint_f}, {"cs", CG_ConfigStringModified}, + {"ct", CG_CaptionText_f}, {"cts", CG_CaptionTextStop}, + {"lt", CG_LCARSText_f}, {"print", CG_Print_f}, + {"st", CG_ScrollText_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -283,26 +235,25 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -static void CG_ServerCommand( void ) { - const char *cmd = CG_Argv( 0 ); - serverCommand_t *command = NULL; +static void CG_ServerCommand(void) { + const char *cmd = CG_Argv(0); + serverCommand_t *command = NULL; - if ( !cmd[0] ) { + if (!cmd[0]) { // server claimed the command return; } - command = (serverCommand_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp ); + command = (serverCommand_t *)Q_LinearSearch(cmd, commands, numCommands, sizeof(commands[0]), svcmdcmp); - if ( command ) { + if (command) { command->func(); return; } - CG_Printf( "Unknown client game command: %s\n", cmd ); + CG_Printf("Unknown client game command: %s\n", cmd); } - /* ==================== CG_ExecuteNewServerCommands @@ -311,9 +262,9 @@ Execute all of the server commands that were received along with this this snapshot. ==================== */ -void CG_ExecuteNewServerCommands( int latestSequence ) { - while ( cgs.serverCommandSequence < latestSequence ) { - if ( cgi_GetServerCommand( ++cgs.serverCommandSequence ) ) { +void CG_ExecuteNewServerCommands(int latestSequence) { + while (cgs.serverCommandSequence < latestSequence) { + if (cgi_GetServerCommand(++cgs.serverCommandSequence)) { CG_ServerCommand(); } } diff --git a/codeJK2/cgame/cg_snapshot.cpp b/codeJK2/cgame/cg_snapshot.cpp index 586c25548f..14d14e7f7b 100644 --- a/codeJK2/cgame/cg_snapshot.cpp +++ b/codeJK2/cgame/cg_snapshot.cpp @@ -30,17 +30,17 @@ along with this program; if not, see . CG_ResetEntity ================== */ -void CG_ResetEntity( centity_t *cent ) { +void CG_ResetEntity(centity_t *cent) { // if an event is set, assume it is new enough to use // if the event had timed out, it would have been cleared cent->previousEvent = 0; cent->trailTime = cg.snap->serverTime; - VectorCopy (cent->currentState.origin, cent->lerpOrigin); - VectorCopy (cent->currentState.angles, cent->lerpAngles); - if ( cent->currentState.eType == ET_PLAYER ) { - CG_ResetPlayerEntity( cent ); + VectorCopy(cent->currentState.origin, cent->lerpOrigin); + VectorCopy(cent->currentState.angles, cent->lerpAngles); + if (cent->currentState.eType == ET_PLAYER) { + CG_ResetPlayerEntity(cent); } } @@ -51,64 +51,62 @@ CG_TransitionEntity cent->nextState is moved to cent->currentState and events are fired =============== */ -void CG_TransitionEntity( centity_t *cent ) { +void CG_TransitionEntity(centity_t *cent) { cent->currentState = cent->nextState; cent->currentValid = qtrue; // reset if the entity wasn't in the last frame or was teleported - if ( !cent->interpolate ) { - CG_ResetEntity( cent ); + if (!cent->interpolate) { + CG_ResetEntity(cent); } // clear the next state. if will be set by the next CG_SetNextSnap cent->interpolate = qfalse; // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } - /* ================== CG_SetInitialSnapshot This will only happen on the very first snapshot, or -on tourney restarts. All other times will use +on tourney restarts. All other times will use CG_TransitionSnapshot instead. ================== */ -void CG_SetInitialSnapshot( snapshot_t *snap ) { - int i; - centity_t *cent; - entityState_t *state; +void CG_SetInitialSnapshot(snapshot_t *snap) { + int i; + centity_t *cent; + entityState_t *state; cg.snap = snap; // sort out solid entities - //CG_BuildSolidList(); + // CG_BuildSolidList(); - CG_ExecuteNewServerCommands( snap->serverCommandSequence ); + CG_ExecuteNewServerCommands(snap->serverCommandSequence); // set our local weapon selection pointer to // what the server has indicated the current weapon is CG_Respawn(); - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - state = &cg.snap->entities[ i ]; - cent = &cg_entities[ state->number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + state = &cg.snap->entities[i]; + cent = &cg_entities[state->number]; cent->currentState = *state; cent->interpolate = qfalse; cent->currentValid = qtrue; - CG_ResetEntity( cent ); + CG_ResetEntity(cent); // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } } - /* =================== CG_TransitionSnapshot @@ -116,24 +114,24 @@ CG_TransitionSnapshot The transition point from snap to nextSnap has passed =================== */ -void CG_TransitionSnapshot( void ) { - centity_t *cent; - snapshot_t *oldFrame; - int i; +void CG_TransitionSnapshot(void) { + centity_t *cent; + snapshot_t *oldFrame; + int i; - if ( !cg.snap ) { - CG_Error( "CG_TransitionSnapshot: NULL cg.snap" ); + if (!cg.snap) { + CG_Error("CG_TransitionSnapshot: NULL cg.snap"); } - if ( !cg.nextSnap ) { - CG_Error( "CG_TransitionSnapshot: NULL cg.nextSnap" ); + if (!cg.nextSnap) { + CG_Error("CG_TransitionSnapshot: NULL cg.nextSnap"); } // execute any server string commands before transitioning entities - CG_ExecuteNewServerCommands( cg.nextSnap->serverCommandSequence ); + CG_ExecuteNewServerCommands(cg.nextSnap->serverCommandSequence); // clear the currentValid flag for all entities in the existing snapshot - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; cent->currentValid = qfalse; } @@ -142,32 +140,29 @@ void CG_TransitionSnapshot( void ) { cg.snap = cg.nextSnap; // sort out solid entities - //CG_BuildSolidList(); + // CG_BuildSolidList(); - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) - { - if ( 1 )//cg.snap->entities[ i ].number != 0 ) // I guess the player adds his/her events elsewhere, so doing this also gives us double events for the player! + for (i = 0; i < cg.snap->numEntities; i++) { + if (1) // cg.snap->entities[ i ].number != 0 ) // I guess the player adds his/her events elsewhere, so doing this also gives us double events for the + // player! { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; - CG_TransitionEntity( cent ); + cent = &cg_entities[cg.snap->entities[i].number]; + CG_TransitionEntity(cent); } } cg.nextSnap = NULL; // check for playerstate transition events - if ( oldFrame ) { + if (oldFrame) { // if we are not doing client side movement prediction for any // reason, then the client events and view changes will be issued now - if ( cg_timescale.value >= 1.0f ) - { - CG_TransitionPlayerState( &cg.snap->ps, &oldFrame->ps ); + if (cg_timescale.value >= 1.0f) { + CG_TransitionPlayerState(&cg.snap->ps, &oldFrame->ps); } } - } - /* =============== CG_SetEntityNextState @@ -176,25 +171,23 @@ Determine if the entity can be interpolated between the states present in cg.snap and cg,nextSnap =============== */ -void CG_SetEntityNextState( centity_t *cent, entityState_t *state ) { +void CG_SetEntityNextState(centity_t *cent, entityState_t *state) { cent->nextState = *state; // since we can't interpolate ghoul2 stuff from one frame to another, I'm just going to copy the ghoul2 info directly into the current state now -// CGhoul2Info *currentModel = &state->ghoul2[1]; -// cent->gent->ghoul2 = state->ghoul2; -// CGhoul2Info *newModel = ¢->gent->ghoul2[1]; - + // CGhoul2Info *currentModel = &state->ghoul2[1]; + // cent->gent->ghoul2 = state->ghoul2; + // CGhoul2Info *newModel = ¢->gent->ghoul2[1]; // if this frame is a teleport, or the entity wasn't in the // previous frame, don't interpolate - if ( !cent->currentValid || ( ( cent->currentState.eFlags ^ state->eFlags ) & EF_TELEPORT_BIT ) ) { + if (!cent->currentValid || ((cent->currentState.eFlags ^ state->eFlags) & EF_TELEPORT_BIT)) { cent->interpolate = qfalse; } else { cent->interpolate = qtrue; } } - /* =================== CG_SetNextSnap @@ -202,29 +195,28 @@ CG_SetNextSnap A new snapshot has just been read in from the client system. =================== */ -void CG_SetNextSnap( snapshot_t *snap ) { - int num; - entityState_t *es; - centity_t *cent; +void CG_SetNextSnap(snapshot_t *snap) { + int num; + entityState_t *es; + centity_t *cent; cg.nextSnap = snap; // check for extrapolation errors - for ( num = 0 ; num < snap->numEntities ; num++ ) { + for (num = 0; num < snap->numEntities; num++) { es = &snap->entities[num]; - cent = &cg_entities[ es->number ]; - CG_SetEntityNextState( cent, es ); + cent = &cg_entities[es->number]; + CG_SetEntityNextState(cent, es); } // if the next frame is a teleport for the playerstate, - if ( cg.snap && ( ( snap->ps.eFlags ^ cg.snap->ps.eFlags ) & EF_TELEPORT_BIT ) ) { + if (cg.snap && ((snap->ps.eFlags ^ cg.snap->ps.eFlags) & EF_TELEPORT_BIT)) { cg.nextFrameTeleport = qtrue; } else { cg.nextFrameTeleport = qfalse; } } - /* ======================== CG_ReadNextSnapshot @@ -235,13 +227,13 @@ times if the client system fails to return a valid snapshot. ======================== */ -snapshot_t *CG_ReadNextSnapshot( void ) { - qboolean r; - snapshot_t *dest; +snapshot_t *CG_ReadNextSnapshot(void) { + qboolean r; + snapshot_t *dest; - while ( cg.processedSnapshotNum < cg.latestSnapshotNum ) { + while (cg.processedSnapshotNum < cg.latestSnapshotNum) { // decide which of the two slots to load it into - if ( cg.snap == &cg.activeSnapshots[0] ) { + if (cg.snap == &cg.activeSnapshots[0]) { dest = &cg.activeSnapshots[1]; } else { dest = &cg.activeSnapshots[0]; @@ -249,10 +241,10 @@ snapshot_t *CG_ReadNextSnapshot( void ) { // try to read the snapshot from the client system cg.processedSnapshotNum++; - r = cgi_GetSnapshot( cg.processedSnapshotNum, dest ); + r = cgi_GetSnapshot(cg.processedSnapshotNum, dest); // if it succeeded, return - if ( r ) { + if (r) { return dest; } @@ -262,7 +254,7 @@ snapshot_t *CG_ReadNextSnapshot( void ) { // buffer in the client system. // record as a dropped packet -// CG_AddLagometerSnapshotInfo( NULL ); + // CG_AddLagometerSnapshotInfo( NULL ); // If there are additional snapshots, continue trying to // read them. @@ -281,25 +273,24 @@ require a reload of all the media ================= */ extern void CG_LinkCentsToGents(void); -void CG_RestartLevel( void ) { - int snapshotNum; - int r; +void CG_RestartLevel(void) { + int snapshotNum; + int r; snapshotNum = cg.processedSnapshotNum; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// memset( cg_entities, 0, sizeof( cg_entities ) ); + // memset( cg_entities, 0, sizeof( cg_entities ) ); CG_Init_CGents(); -// this is a No-No now we have stl vector classes in here. -// memset( &cg, 0, sizeof( cg ) ); + // this is a No-No now we have stl vector classes in here. + // memset( &cg, 0, sizeof( cg ) ); CG_Init_CG(); -/* -Ghoul2 Insert End -*/ - + /* + Ghoul2 Insert End + */ CG_LinkCentsToGents(); CG_InitLocalEntities(); @@ -308,16 +299,15 @@ Ghoul2 Insert End // regrab the first snapshot of the restart cg.processedSnapshotNum = snapshotNum; - r = cgi_GetSnapshot( cg.processedSnapshotNum, &cg.activeSnapshots[0] ); - if ( !r ) { - CG_Error( "cgi_GetSnapshot failed on restart" ); + r = cgi_GetSnapshot(cg.processedSnapshotNum, &cg.activeSnapshots[0]); + if (!r) { + CG_Error("cgi_GetSnapshot failed on restart"); } - CG_SetInitialSnapshot( &cg.activeSnapshots[0] ); + CG_SetInitialSnapshot(&cg.activeSnapshots[0]); cg.time = cg.snap->serverTime; } - /* ============ CG_ProcessSnapshots @@ -337,16 +327,16 @@ of an interpolating one) ============ */ -void CG_ProcessSnapshots( void ) { - snapshot_t *snap; - int n; +void CG_ProcessSnapshots(void) { + snapshot_t *snap; + int n; // see what the latest snapshot the client system has is - cgi_GetCurrentSnapshotNumber( &n, &cg.latestSnapshotTime ); - if ( n != cg.latestSnapshotNum ) { - if ( n < cg.latestSnapshotNum ) { + cgi_GetCurrentSnapshotNumber(&n, &cg.latestSnapshotTime); + if (n != cg.latestSnapshotNum) { + if (n < cg.latestSnapshotNum) { // this should never happen - CG_Error( "CG_ProcessSnapshots: n < cg.latestSnapshotNum" ); + CG_Error("CG_ProcessSnapshots: n < cg.latestSnapshotNum"); } cg.latestSnapshotNum = n; } @@ -354,16 +344,16 @@ void CG_ProcessSnapshots( void ) { // If we have yet to receive a snapshot, check for it. // Once we have gotten the first snapshot, cg.snap will // always have valid data for the rest of the game - if ( !cg.snap ) { + if (!cg.snap) { snap = CG_ReadNextSnapshot(); - if ( !snap ) { + if (!snap) { // we can't continue until we get a snapshot return; } // set our weapon selection to what // the playerstate is currently using - CG_SetInitialSnapshot( snap ); + CG_SetInitialSnapshot(snap); } // loop until we either have a valid nextSnap with a serverTime @@ -371,58 +361,54 @@ void CG_ProcessSnapshots( void ) { // out of available snapshots do { // if we don't have a nextframe, try and read a new one in - if ( !cg.nextSnap ) { + if (!cg.nextSnap) { snap = CG_ReadNextSnapshot(); // if we still don't have a nextframe, we will just have to // extrapolate - if ( !snap ) { + if (!snap) { break; } - CG_SetNextSnap( snap ); + CG_SetNextSnap(snap); // if time went backwards, we have a level restart - if ( cg.nextSnap->serverTime < cg.snap->serverTime ) { + if (cg.nextSnap->serverTime < cg.snap->serverTime) { // restart the level CG_RestartLevel(); - continue; // we might also get a nextsnap + continue; // we might also get a nextsnap } } // if our time is < nextFrame's, we have a nice interpolating state - if ( cg.time < cg.nextSnap->serverTime ) { + if (cg.time < cg.nextSnap->serverTime) { break; } // we have passed the transition from nextFrame to frame CG_TransitionSnapshot(); - } while ( 1 ); + } while (1); - if ( cg.snap->serverTime > cg.time ) - { - cg.time=cg.snap->serverTime; + if (cg.snap->serverTime > cg.time) { + cg.time = cg.snap->serverTime; #if _DEBUG Com_Printf("CG_ProcessSnapshots: cg.snap->serverTime > cg.time"); #endif - } - if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) - { - cg.time=cg.nextSnap->serverTime-1; + if (cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time) { + cg.time = cg.nextSnap->serverTime - 1; #if _DEBUG Com_Printf("CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time"); #endif } // assert our valid conditions upon exiting - if ( cg.snap == NULL ) { - CG_Error( "CG_ProcessSnapshots: cg.snap == NULL" ); + if (cg.snap == NULL) { + CG_Error("CG_ProcessSnapshots: cg.snap == NULL"); } - if ( cg.snap->serverTime > cg.time ) { - CG_Error( "CG_ProcessSnapshots: cg.snap->serverTime > cg.time" ); + if (cg.snap->serverTime > cg.time) { + CG_Error("CG_ProcessSnapshots: cg.snap->serverTime > cg.time"); } - if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) { - CG_Error( "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time" ); + if (cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time) { + CG_Error("CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time"); } } - diff --git a/codeJK2/cgame/cg_syscalls.cpp b/codeJK2/cgame/cg_syscalls.cpp index d4e637c845..94bf7c5f79 100644 --- a/codeJK2/cgame/cg_syscalls.cpp +++ b/codeJK2/cgame/cg_syscalls.cpp @@ -25,523 +25,308 @@ along with this program; if not, see . // this file is only included when building a dll -//prototypes +// prototypes extern void CG_PreInit(); -static intptr_t (QDECL *Q_syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; +static intptr_t(QDECL *Q_syscall)(intptr_t arg, ...) = (intptr_t(QDECL *)(intptr_t, ...)) - 1; -extern "C" Q_EXPORT void QDECL dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg, ... ) ) { +extern "C" Q_EXPORT void QDECL dllEntry(intptr_t(QDECL *syscallptr)(intptr_t arg, ...)) { Q_syscall = syscallptr; CG_PreInit(); } -inline int PASSFLOAT( float x ) { +inline int PASSFLOAT(float x) { byteAlias_t fi; fi.f = x; return fi.i; } -void cgi_Printf( const char *fmt ) { - Q_syscall( CG_PRINT, fmt ); -} +void cgi_Printf(const char *fmt) { Q_syscall(CG_PRINT, fmt); } -NORETURN void cgi_Error( const char *fmt ) { - Q_syscall( CG_ERROR, fmt ); +NORETURN void cgi_Error(const char *fmt) { + Q_syscall(CG_ERROR, fmt); // shut up GCC warning about returning functions, because we know better exit(1); } -int cgi_Milliseconds( void ) { - return Q_syscall( CG_MILLISECONDS ); -} +int cgi_Milliseconds(void) { return Q_syscall(CG_MILLISECONDS); } -void cgi_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags ) { - Q_syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags ); +void cgi_Cvar_Register(vmCvar_t *vmCvar, const char *varName, const char *defaultValue, int flags) { + Q_syscall(CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags); } -void cgi_Cvar_Update( vmCvar_t *vmCvar ) { - Q_syscall( CG_CVAR_UPDATE, vmCvar ); -} +void cgi_Cvar_Update(vmCvar_t *vmCvar) { Q_syscall(CG_CVAR_UPDATE, vmCvar); } -void cgi_Cvar_Set( const char *var_name, const char *value ) { - Q_syscall( CG_CVAR_SET, var_name, value ); -} +void cgi_Cvar_Set(const char *var_name, const char *value) { Q_syscall(CG_CVAR_SET, var_name, value); } -int cgi_Argc( void ) { - return Q_syscall( CG_ARGC ); -} +int cgi_Argc(void) { return Q_syscall(CG_ARGC); } -void cgi_Argv( int n, char *buffer, int bufferLength ) { - Q_syscall( CG_ARGV, n, buffer, bufferLength ); -} +void cgi_Argv(int n, char *buffer, int bufferLength) { Q_syscall(CG_ARGV, n, buffer, bufferLength); } -void cgi_Args( char *buffer, int bufferLength ) { - Q_syscall( CG_ARGS, buffer, bufferLength ); -} +void cgi_Args(char *buffer, int bufferLength) { Q_syscall(CG_ARGS, buffer, bufferLength); } -int cgi_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - return Q_syscall( CG_FS_FOPENFILE, qpath, f, mode ); -} +int cgi_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode) { return Q_syscall(CG_FS_FOPENFILE, qpath, f, mode); } -int cgi_FS_Read( void *buffer, int len, fileHandle_t f ) { - return Q_syscall( CG_FS_READ, buffer, len, f ); -} +int cgi_FS_Read(void *buffer, int len, fileHandle_t f) { return Q_syscall(CG_FS_READ, buffer, len, f); } -int cgi_FS_Write( const void *buffer, int len, fileHandle_t f ) { - return Q_syscall( CG_FS_WRITE, buffer, len, f ); -} +int cgi_FS_Write(const void *buffer, int len, fileHandle_t f) { return Q_syscall(CG_FS_WRITE, buffer, len, f); } -void cgi_FS_FCloseFile( fileHandle_t f ) { - Q_syscall( CG_FS_FCLOSEFILE, f ); -} +void cgi_FS_FCloseFile(fileHandle_t f) { Q_syscall(CG_FS_FCLOSEFILE, f); } -void cgi_SendConsoleCommand( const char *text ) { - Q_syscall( CG_SENDCONSOLECOMMAND, text ); -} +void cgi_SendConsoleCommand(const char *text) { Q_syscall(CG_SENDCONSOLECOMMAND, text); } -void cgi_AddCommand( const char *cmdName ) { - Q_syscall( CG_ADDCOMMAND, cmdName ); -} +void cgi_AddCommand(const char *cmdName) { Q_syscall(CG_ADDCOMMAND, cmdName); } -void cgi_SendClientCommand( const char *s ) { - Q_syscall( CG_SENDCLIENTCOMMAND, s ); -} +void cgi_SendClientCommand(const char *s) { Q_syscall(CG_SENDCLIENTCOMMAND, s); } -void cgi_UpdateScreen( void ) { - Q_syscall( CG_UPDATESCREEN ); -} +void cgi_UpdateScreen(void) { Q_syscall(CG_UPDATESCREEN); } -void cgi_CM_LoadMap( const char *mapname, qboolean subBSP ) { - Q_syscall( CG_CM_LOADMAP, mapname, subBSP ); -} +void cgi_CM_LoadMap(const char *mapname, qboolean subBSP) { Q_syscall(CG_CM_LOADMAP, mapname, subBSP); } -int cgi_CM_NumInlineModels( void ) { - return Q_syscall( CG_CM_NUMINLINEMODELS ); -} +int cgi_CM_NumInlineModels(void) { return Q_syscall(CG_CM_NUMINLINEMODELS); } -clipHandle_t cgi_CM_InlineModel( int index ) { - return Q_syscall( CG_CM_INLINEMODEL, index ); -} +clipHandle_t cgi_CM_InlineModel(int index) { return Q_syscall(CG_CM_INLINEMODEL, index); } -clipHandle_t cgi_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) {//, const int contents ) { - return Q_syscall( CG_CM_TEMPBOXMODEL, mins, maxs );//, contents ); +clipHandle_t cgi_CM_TempBoxModel(const vec3_t mins, const vec3_t maxs) { //, const int contents ) { + return Q_syscall(CG_CM_TEMPBOXMODEL, mins, maxs); //, contents ); } -int cgi_CM_PointContents( const vec3_t p, clipHandle_t model ) { - return Q_syscall( CG_CM_POINTCONTENTS, p, model ); -} +int cgi_CM_PointContents(const vec3_t p, clipHandle_t model) { return Q_syscall(CG_CM_POINTCONTENTS, p, model); } -int cgi_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) { - return Q_syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles ); +int cgi_CM_TransformedPointContents(const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { + return Q_syscall(CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles); } -void cgi_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask ) { - Q_syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask ); +void cgi_CM_BoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask) { + Q_syscall(CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask); } -void cgi_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask, - const vec3_t origin, const vec3_t angles ) { - Q_syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles ); +void cgi_CM_TransformedBoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, + const vec3_t origin, const vec3_t angles) { + Q_syscall(CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles); } -int cgi_CM_MarkFragments( int numPoints, const vec3_t *points, - const vec3_t projection, - int maxPoints, vec3_t pointBuffer, - int maxFragments, markFragment_t *fragmentBuffer ) { - return Q_syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer ); +int cgi_CM_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + return Q_syscall(CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer); } -void cgi_CM_SnapPVS(vec3_t origin,byte *buffer) -{ - Q_syscall(CG_CM_SNAPPVS,origin,buffer); -} +void cgi_CM_SnapPVS(vec3_t origin, byte *buffer) { Q_syscall(CG_CM_SNAPPVS, origin, buffer); } -void cgi_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) { - Q_syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx ); -} +void cgi_S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx) { Q_syscall(CG_S_STARTSOUND, origin, entityNum, entchannel, sfx); } -void cgi_AS_ParseSets( void ) { - Q_syscall( CG_AS_PARSESETS ); -} +void cgi_AS_ParseSets(void) { Q_syscall(CG_AS_PARSESETS); } -void cgi_AS_AddPrecacheEntry( const char *name ) { - Q_syscall( CG_AS_ADDENTRY, name ); -} +void cgi_AS_AddPrecacheEntry(const char *name) { Q_syscall(CG_AS_ADDENTRY, name); } -void cgi_S_UpdateAmbientSet( const char *name, vec3_t origin ) { - Q_syscall( CG_S_UPDATEAMBIENTSET, name, origin ); -} +void cgi_S_UpdateAmbientSet(const char *name, vec3_t origin) { Q_syscall(CG_S_UPDATEAMBIENTSET, name, origin); } -int cgi_S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ) { - return Q_syscall( CG_S_ADDLOCALSET, name, listener_origin, origin, entID, time ); +int cgi_S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time) { + return Q_syscall(CG_S_ADDLOCALSET, name, listener_origin, origin, entID, time); } -sfxHandle_t cgi_AS_GetBModelSound( const char *name, int stage ) { - return Q_syscall( CG_AS_GETBMODELSOUND, name, stage ); -} +sfxHandle_t cgi_AS_GetBModelSound(const char *name, int stage) { return Q_syscall(CG_AS_GETBMODELSOUND, name, stage); } -void cgi_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) { - Q_syscall( CG_S_STARTLOCALSOUND, sfx, channelNum ); -} +void cgi_S_StartLocalSound(sfxHandle_t sfx, int channelNum) { Q_syscall(CG_S_STARTLOCALSOUND, sfx, channelNum); } -void cgi_S_ClearLoopingSounds( void ) { - Q_syscall( CG_S_CLEARLOOPINGSOUNDS ); -} +void cgi_S_ClearLoopingSounds(void) { Q_syscall(CG_S_CLEARLOOPINGSOUNDS); } -void cgi_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx, soundChannel_t chan ) { - Q_syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx, chan ); +void cgi_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx, soundChannel_t chan) { + Q_syscall(CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx, chan); } -void cgi_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) { - Q_syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin ); -} +void cgi_S_UpdateEntityPosition(int entityNum, const vec3_t origin) { Q_syscall(CG_S_UPDATEENTITYPOSITION, entityNum, origin); } -void cgi_S_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], qboolean inwater ) { - Q_syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater ); +void cgi_S_Respatialize(int entityNum, const vec3_t origin, vec3_t axis[3], qboolean inwater) { + Q_syscall(CG_S_RESPATIALIZE, entityNum, origin, axis, inwater); } -sfxHandle_t cgi_S_RegisterSound( const char *sample ) { - return Q_syscall( CG_S_REGISTERSOUND, sample ); -} +sfxHandle_t cgi_S_RegisterSound(const char *sample) { return Q_syscall(CG_S_REGISTERSOUND, sample); } -void cgi_S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bForceStart ) { - Q_syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop, bForceStart ); -} +void cgi_S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bForceStart) { Q_syscall(CG_S_STARTBACKGROUNDTRACK, intro, loop, bForceStart); } -float cgi_S_GetSampleLength( sfxHandle_t sfx ) { - return Q_syscall( CG_S_GETSAMPLELENGTH, sfx); -} +float cgi_S_GetSampleLength(sfxHandle_t sfx) { return Q_syscall(CG_S_GETSAMPLELENGTH, sfx); } -void cgi_R_LoadWorldMap( const char *mapname ) { - Q_syscall( CG_R_LOADWORLDMAP, mapname ); -} +void cgi_R_LoadWorldMap(const char *mapname) { Q_syscall(CG_R_LOADWORLDMAP, mapname); } -qhandle_t cgi_R_RegisterModel( const char *name ) { - return Q_syscall( CG_R_REGISTERMODEL, name ); -} +qhandle_t cgi_R_RegisterModel(const char *name) { return Q_syscall(CG_R_REGISTERMODEL, name); } -qhandle_t cgi_R_RegisterSkin( const char *name ) { - return Q_syscall( CG_R_REGISTERSKIN, name ); -} +qhandle_t cgi_R_RegisterSkin(const char *name) { return Q_syscall(CG_R_REGISTERSKIN, name); } -qhandle_t cgi_R_RegisterShader( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADER, name ); -} +qhandle_t cgi_R_RegisterShader(const char *name) { return Q_syscall(CG_R_REGISTERSHADER, name); } -qhandle_t cgi_R_RegisterShaderNoMip( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADERNOMIP, name ); -} +qhandle_t cgi_R_RegisterShaderNoMip(const char *name) { return Q_syscall(CG_R_REGISTERSHADERNOMIP, name); } -qhandle_t cgi_R_RegisterFont( const char *name ) { - return Q_syscall( CG_R_REGISTERFONT, name ); -} +qhandle_t cgi_R_RegisterFont(const char *name) { return Q_syscall(CG_R_REGISTERFONT, name); } int cgi_R_Font_StrLenPixels(const char *text, const int iFontIndex, const float scale /*= 1.0f*/) { - return Q_syscall( CG_R_FONTSTRLENPIXELS, text, iFontIndex, PASSFLOAT(scale) ) ; + return Q_syscall(CG_R_FONTSTRLENPIXELS, text, iFontIndex, PASSFLOAT(scale)); } -int cgi_R_Font_StrLenChars(const char *text) { - return Q_syscall( CG_R_FONTSTRLENCHARS, text ) ; -} +int cgi_R_Font_StrLenChars(const char *text) { return Q_syscall(CG_R_FONTSTRLENCHARS, text); } -int cgi_R_Font_HeightPixels(const int iFontIndex, const float scale /*= 1.0f*/) { - return Q_syscall( CG_R_FONTHEIGHTPIXELS, iFontIndex, PASSFLOAT(scale) ); -} +int cgi_R_Font_HeightPixels(const int iFontIndex, const float scale /*= 1.0f*/) { return Q_syscall(CG_R_FONTHEIGHTPIXELS, iFontIndex, PASSFLOAT(scale)); } -qboolean cgi_Language_IsAsian( void ) -{ - return (qboolean)Q_syscall( CG_LANGUAGE_ISASIAN ); -} +qboolean cgi_Language_IsAsian(void) { return (qboolean)Q_syscall(CG_LANGUAGE_ISASIAN); } -qboolean cgi_Language_UsesSpaces(void) -{ - return (qboolean)Q_syscall( CG_LANGUAGE_USESSPACES ); -} +qboolean cgi_Language_UsesSpaces(void) { return (qboolean)Q_syscall(CG_LANGUAGE_USESSPACES); } -unsigned int cgi_AnyLanguage_ReadCharFromString( const char **ppText, qboolean *pbIsTrailingPunctuation /* = NULL */ ) -{ +unsigned int cgi_AnyLanguage_ReadCharFromString(const char **ppText, qboolean *pbIsTrailingPunctuation /* = NULL */) { int dummy; - return Q_syscall( CG_ANYLANGUAGE_READFROMSTRING2, ppText, &dummy, pbIsTrailingPunctuation ); + return Q_syscall(CG_ANYLANGUAGE_READFROMSTRING2, ppText, &dummy, pbIsTrailingPunctuation); } -unsigned int cgi_AnyLanguage_ReadCharFromString( const char **ppText, int *ppos, qboolean *pbIsTrailingPunctuation /* = NULL */ ) -{ - return Q_syscall( CG_ANYLANGUAGE_READFROMSTRING, ppText, ppos, pbIsTrailingPunctuation ); +unsigned int cgi_AnyLanguage_ReadCharFromString(const char **ppText, int *ppos, qboolean *pbIsTrailingPunctuation /* = NULL */) { + return Q_syscall(CG_ANYLANGUAGE_READFROMSTRING, ppText, ppos, pbIsTrailingPunctuation); } void cgi_R_Font_DrawString(int ox, int oy, const char *text, const float *rgba, const int setIndex, int iMaxPixelWidth, const float scale /*= 1.0f*/) { - Q_syscall (CG_R_FONTDRAWSTRING, ox, oy, text, rgba, setIndex, iMaxPixelWidth, PASSFLOAT(scale) ); + Q_syscall(CG_R_FONTDRAWSTRING, ox, oy, text, rgba, setIndex, iMaxPixelWidth, PASSFLOAT(scale)); } -void cgi_R_ClearScene( void ) { - Q_syscall( CG_R_CLEARSCENE ); -} +void cgi_R_ClearScene(void) { Q_syscall(CG_R_CLEARSCENE); } -void cgi_R_AddRefEntityToScene( const refEntity_t *re ) { - Q_syscall( CG_R_ADDREFENTITYTOSCENE, re ); -} +void cgi_R_AddRefEntityToScene(const refEntity_t *re) { Q_syscall(CG_R_ADDREFENTITYTOSCENE, re); } -void cgi_R_GetLighting( const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t ligthDir ) { - Q_syscall( CG_R_GETLIGHTING, origin, ambientLight, directedLight, ligthDir ); +void cgi_R_GetLighting(const vec3_t origin, vec3_t ambientLight, vec3_t directedLight, vec3_t ligthDir) { + Q_syscall(CG_R_GETLIGHTING, origin, ambientLight, directedLight, ligthDir); } -void cgi_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) { - Q_syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts ); -} +void cgi_R_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts) { Q_syscall(CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts); } -void cgi_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - Q_syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) ); +void cgi_R_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + Q_syscall(CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b)); } -void cgi_R_RenderScene( const refdef_t *fd ) { - Q_syscall( CG_R_RENDERSCENE, fd ); -} +void cgi_R_RenderScene(const refdef_t *fd) { Q_syscall(CG_R_RENDERSCENE, fd); } -void cgi_R_SetColor( const float *rgba ) { - Q_syscall( CG_R_SETCOLOR, rgba ); -} +void cgi_R_SetColor(const float *rgba) { Q_syscall(CG_R_SETCOLOR, rgba); } -void cgi_R_DrawStretchPic( float x, float y, float w, float h, - float s1, float t1, float s2, float t2, qhandle_t hShader ) { - Q_syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader ); +void cgi_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + Q_syscall(CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader); } -void cgi_R_DrawScreenShot( float x, float y, float w, float h){ - Q_syscall( CG_R_DRAWSCREENSHOT, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h) ); -} +void cgi_R_DrawScreenShot(float x, float y, float w, float h) { Q_syscall(CG_R_DRAWSCREENSHOT, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h)); } -void cgi_R_ModelBounds( qhandle_t model, vec3_t mins, vec3_t maxs ) { - Q_syscall( CG_R_MODELBOUNDS, model, mins, maxs ); -} +void cgi_R_ModelBounds(qhandle_t model, vec3_t mins, vec3_t maxs) { Q_syscall(CG_R_MODELBOUNDS, model, mins, maxs); } -void cgi_R_LerpTag( orientation_t *tag, qhandle_t mod, int startFrame, int endFrame, - float frac, const char *tagName ) { - Q_syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName ); +void cgi_R_LerpTag(orientation_t *tag, qhandle_t mod, int startFrame, int endFrame, float frac, const char *tagName) { + Q_syscall(CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName); } -void cgi_R_DrawRotatePic( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) -{ - Q_syscall( CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); +void cgi_R_DrawRotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } -void cgi_R_DrawRotatePic2( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) -{ - Q_syscall( CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); +void cgi_R_DrawRotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } -void cgi_R_LAGoggles( void ) -{ - Q_syscall( CG_R_LA_GOGGLES ); -} +void cgi_R_LAGoggles(void) { Q_syscall(CG_R_LA_GOGGLES); } -void cgi_R_Scissor( float x, float y, float w, float h) -{ - Q_syscall( CG_R_SCISSOR, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h)); -} +void cgi_R_Scissor(float x, float y, float w, float h) { Q_syscall(CG_R_SCISSOR, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h)); } -void cgi_GetGlconfig( glconfig_t *glconfig ) { - Q_syscall( CG_GETGLCONFIG, glconfig ); -} +void cgi_GetGlconfig(glconfig_t *glconfig) { Q_syscall(CG_GETGLCONFIG, glconfig); } -void cgi_GetGameState( gameState_t *gamestate ) { - Q_syscall( CG_GETGAMESTATE, gamestate ); -} +void cgi_GetGameState(gameState_t *gamestate) { Q_syscall(CG_GETGAMESTATE, gamestate); } -void cgi_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { - Q_syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime ); -} +void cgi_GetCurrentSnapshotNumber(int *snapshotNumber, int *serverTime) { Q_syscall(CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime); } -qboolean cgi_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { - return (qboolean)Q_syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot ); -} +qboolean cgi_GetSnapshot(int snapshotNumber, snapshot_t *snapshot) { return (qboolean)Q_syscall(CG_GETSNAPSHOT, snapshotNumber, snapshot); } -qboolean cgi_GetServerCommand( int serverCommandNumber ) { - return (qboolean)Q_syscall( CG_GETSERVERCOMMAND, serverCommandNumber ); -} +qboolean cgi_GetServerCommand(int serverCommandNumber) { return (qboolean)Q_syscall(CG_GETSERVERCOMMAND, serverCommandNumber); } -int cgi_GetCurrentCmdNumber( void ) { - return Q_syscall( CG_GETCURRENTCMDNUMBER ); -} +int cgi_GetCurrentCmdNumber(void) { return Q_syscall(CG_GETCURRENTCMDNUMBER); } -qboolean cgi_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { - return (qboolean)Q_syscall( CG_GETUSERCMD, cmdNumber, ucmd ); -} +qboolean cgi_GetUserCmd(int cmdNumber, usercmd_t *ucmd) { return (qboolean)Q_syscall(CG_GETUSERCMD, cmdNumber, ucmd); } -void cgi_SetUserCmdValue( int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride ) { - Q_syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride) ); +void cgi_SetUserCmdValue(int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride) { + Q_syscall(CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride)); } -void cgi_SetUserCmdAngles( float pitchOverride, float yawOverride, float rollOverride ) { - Q_syscall( CG_SETUSERCMDANGLES, PASSFLOAT(pitchOverride), PASSFLOAT(yawOverride), PASSFLOAT(rollOverride) ); +void cgi_SetUserCmdAngles(float pitchOverride, float yawOverride, float rollOverride) { + Q_syscall(CG_SETUSERCMDANGLES, PASSFLOAT(pitchOverride), PASSFLOAT(yawOverride), PASSFLOAT(rollOverride)); } /* Ghoul2 Insert Start */ // CG Specific API calls -void trap_G2_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) -{ - Q_syscall( CG_G2_SETMODELS, &ghoul2, modelList, skinList); +void trap_G2_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + Q_syscall(CG_G2_SETMODELS, &ghoul2, modelList, skinList); } /* Ghoul2 Insert End */ -void trap_Com_SetOrgAngles(vec3_t org,vec3_t angles) -{ - Q_syscall(COM_SETORGANGLES,org,angles); -} +void trap_Com_SetOrgAngles(vec3_t org, vec3_t angles) { Q_syscall(COM_SETORGANGLES, org, angles); } -void trap_R_GetLightStyle(int style, color4ub_t color) -{ - Q_syscall(CG_R_GET_LIGHT_STYLE, style, color); -} +void trap_R_GetLightStyle(int style, color4ub_t color) { Q_syscall(CG_R_GET_LIGHT_STYLE, style, color); } -void trap_R_SetLightStyle(int style, int color) -{ - Q_syscall(CG_R_SET_LIGHT_STYLE, style, color); -} +void trap_R_SetLightStyle(int style, int color) { Q_syscall(CG_R_SET_LIGHT_STYLE, style, color); } -void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal ) -{ - Q_syscall( CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal ); -} +void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { Q_syscall(CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal); } -void cgi_R_WorldEffectCommand( const char *command ) -{ - Q_syscall( CG_R_WORLD_EFFECT_COMMAND, command ); -} +void cgi_R_WorldEffectCommand(const char *command) { Q_syscall(CG_R_WORLD_EFFECT_COMMAND, command); } // this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate) -int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile /* = NULL */) { - return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); +int trap_CIN_PlayCinematic(const char *arg0, int xpos, int ypos, int width, int height, int bits, const char *psAudioFile /* = NULL */) { + return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits, psAudioFile); } - + // stops playing the cinematic and ends it. should always return FMV_EOF // cinematics must be stopped in reverse order of when they are started -e_status trap_CIN_StopCinematic(int handle) { - return (e_status) Q_syscall(CG_CIN_STOPCINEMATIC, handle); -} - +e_status trap_CIN_StopCinematic(int handle) { return (e_status)Q_syscall(CG_CIN_STOPCINEMATIC, handle); } // will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached. -e_status trap_CIN_RunCinematic (int handle) { - return (e_status) Q_syscall(CG_CIN_RUNCINEMATIC, handle); -} - +e_status trap_CIN_RunCinematic(int handle) { return (e_status)Q_syscall(CG_CIN_RUNCINEMATIC, handle); } // draws the current frame -void trap_CIN_DrawCinematic (int handle) { - Q_syscall(CG_CIN_DRAWCINEMATIC, handle); -} - +void trap_CIN_DrawCinematic(int handle) { Q_syscall(CG_CIN_DRAWCINEMATIC, handle); } // allows you to resize the animation dynamically -void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) { - Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); -} +void trap_CIN_SetExtents(int handle, int x, int y, int w, int h) { Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); } -void *cgi_Z_Malloc( int size, int tag ) -{ - return (void *)Q_syscall(CG_Z_MALLOC,size,tag); -} +void *cgi_Z_Malloc(int size, int tag) { return (void *)Q_syscall(CG_Z_MALLOC, size, tag); } -void cgi_Z_Free( void *ptr ) -{ - Q_syscall(CG_Z_FREE,ptr); -} +void cgi_Z_Free(void *ptr) { Q_syscall(CG_Z_FREE, ptr); } -void cgi_UI_Menu_Reset(void) -{ - Q_syscall(CG_UI_MENU_RESET); -} +void cgi_UI_Menu_Reset(void) { Q_syscall(CG_UI_MENU_RESET); } -void cgi_UI_Menu_New(char *buf) -{ - Q_syscall(CG_UI_MENU_NEW,buf); -} +void cgi_UI_Menu_New(char *buf) { Q_syscall(CG_UI_MENU_NEW, buf); } -void cgi_UI_Parse_Int(int *value) -{ - Q_syscall(CG_UI_PARSE_INT,value); -} +void cgi_UI_Parse_Int(int *value) { Q_syscall(CG_UI_PARSE_INT, value); } -void cgi_UI_Parse_String(char *buf) -{ - Q_syscall(CG_UI_PARSE_STRING,buf); -} +void cgi_UI_Parse_String(char *buf) { Q_syscall(CG_UI_PARSE_STRING, buf); } -void cgi_UI_Parse_Float(float *value) -{ - Q_syscall(CG_UI_PARSE_FLOAT,value); -} +void cgi_UI_Parse_Float(float *value) { Q_syscall(CG_UI_PARSE_FLOAT, value); } -int cgi_UI_StartParseSession(char *menuFile,char **buf) -{ - return(int) Q_syscall(CG_UI_STARTPARSESESSION,menuFile,buf); -} +int cgi_UI_StartParseSession(char *menuFile, char **buf) { return (int)Q_syscall(CG_UI_STARTPARSESESSION, menuFile, buf); } -void cgi_UI_EndParseSession(char *buf) -{ - Q_syscall(CG_UI_ENDPARSESESSION,buf); -} +void cgi_UI_EndParseSession(char *buf) { Q_syscall(CG_UI_ENDPARSESESSION, buf); } -void cgi_UI_ParseExt(char **token) -{ - Q_syscall(CG_UI_PARSEEXT,token); -} +void cgi_UI_ParseExt(char **token) { Q_syscall(CG_UI_PARSEEXT, token); } -void cgi_UI_MenuPaintAll(void) -{ - Q_syscall(CG_UI_MENUPAINT_ALL); -} +void cgi_UI_MenuPaintAll(void) { Q_syscall(CG_UI_MENUPAINT_ALL); } -void cgi_UI_String_Init(void) -{ - Q_syscall(CG_UI_STRING_INIT); -} +void cgi_UI_String_Init(void) { Q_syscall(CG_UI_STRING_INIT); } -int cgi_UI_GetMenuInfo(char *menuFile,int *x,int *y) -{ - return(int) Q_syscall(CG_UI_GETMENUINFO,menuFile,x,y); -} +int cgi_UI_GetMenuInfo(char *menuFile, int *x, int *y) { return (int)Q_syscall(CG_UI_GETMENUINFO, menuFile, x, y); } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char* text) -{ - return(int) Q_syscall(CG_UI_GETITEMTEXT,menuFile,itemName,text); -} +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text) { return (int)Q_syscall(CG_UI_GETITEMTEXT, menuFile, itemName, text); } -int cgi_SP_Register(const char *text, qboolean persist ) -{ - return Q_syscall( CG_SP_REGISTER, text, persist ); -} +int cgi_SP_Register(const char *text, qboolean persist) { return Q_syscall(CG_SP_REGISTER, text, persist); } -int cgi_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) -{ - return Q_syscall( CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength ); -} +int cgi_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) { return Q_syscall(CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength); } -int cgi_SP_GetStringText(int ID, char *buffer, int bufferLength) -{ - return Q_syscall( CG_SP_GETSTRINGTEXT, ID, buffer, bufferLength ); -} +int cgi_SP_GetStringText(int ID, char *buffer, int bufferLength) { return Q_syscall(CG_SP_GETSTRINGTEXT, ID, buffer, bufferLength); } /* OpenJK Add Since the modules are incompatible, might as well break base compat even further amirite? */ -void *cgi_UI_GetMenuByName( const char *menu ) -{ - return (void *)Q_syscall( CG_OPENJK_GETMENU_BYNAME, menu ); -} +void *cgi_UI_GetMenuByName(const char *menu) { return (void *)Q_syscall(CG_OPENJK_GETMENU_BYNAME, menu); } -void cgi_UI_Menu_Paint( void *menu, qboolean force ) -{ - Q_syscall( CG_OPENJK_MENU_PAINT, menu, force ); -} +void cgi_UI_Menu_Paint(void *menu, qboolean force) { Q_syscall(CG_OPENJK_MENU_PAINT, menu, force); } diff --git a/codeJK2/cgame/cg_text.cpp b/codeJK2/cgame/cg_text.cpp index c69f3aed5b..e04ff652ec 100644 --- a/codeJK2/cgame/cg_text.cpp +++ b/codeJK2/cgame/cg_text.cpp @@ -24,25 +24,20 @@ along with this program; if not, see . #include "cg_local.h" #include "cg_media.h" +// int precacheWav_i; // Current high index of precacheWav array +// precacheWav_t precacheWav[MAX_PRECACHEWAV]; -//int precacheWav_i; // Current high index of precacheWav array -//precacheWav_t precacheWav[MAX_PRECACHEWAV]; - - -//int precacheText_i; // Current high index of precacheText array -//precacheText_t precacheText[MAX_PRECACHETEXT]; - +// int precacheText_i; // Current high index of precacheText array +// precacheText_t precacheText[MAX_PRECACHETEXT]; extern vec4_t textcolor_caption; extern vec4_t textcolor_center; extern vec4_t textcolor_scroll; +#define GAMETEXT_X_START 75.0f +#define GAMETEXT_X_END 600.0f -#define GAMETEXT_X_START 75.0f -#define GAMETEXT_X_END 600.0f - -#define MAX_NUM_GAMELINES 4 - +#define MAX_NUM_GAMELINES 4 // display text in a supplied box, start at top left and going down by however many pixels I feel like internally, // return value is NULL if all fitted, else char * of next char to continue from that didn't fit. @@ -51,20 +46,18 @@ extern vec4_t textcolor_scroll; // // ( if you get the same char * returned as what you passed in, then none of it fitted at all (box too small) ) // -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color) -{ - cgi_R_SetColor( v4Color ); +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color) { + cgi_R_SetColor(v4Color); // Setup a reasonable vertical spacing (taiwanese & japanese need 1.5 fontheight, so use that for all)... // - const int iFontHeight = cgi_R_Font_HeightPixels(iFontHandle, fScale); - const int iFontHeightAdvance = (int) (1.5f * (float) iFontHeight); - int iYpos = iBoxY; // start print pos + const int iFontHeight = cgi_R_Font_HeightPixels(iFontHandle, fScale); + const int iFontHeightAdvance = (int)(1.5f * (float)iFontHeight); + int iYpos = iBoxY; // start print pos // findmeste // test stuff, remove later -// psText = "Ãɨô­ôº¸³Õ¤h¤w¸g¦w¥þ¤F¡A§Ú¤]§â©Ò¦³µo²{³ø§iµ¹¡u°Ó©±¡v¡C«Ü¤£©¯¦a¡A·ç¤hĵ§½¦³¨Ç¥Õèµo²{¤F¤@¨Çª¬ªp¡A·Ç³Æ¦b¾÷³õ¶e®·¨È¾ú¦è¡E¯Ç§J·ç±o¡CÂ¥L°°¸Ë¦¨¥~¥æ¨Ã¸`¡A¬ï¹L¤F¼h¼h¨¾³Æ¡C²{¦bÂ¥L´¤¦³¤H½è¡A¨Ã¥B«Â¯Ù­n´²¼½¯f¬r¡C®Ú¾Ú³Ì·psCurrentTextReadPosªº³ø§i¡A¯Ç§J·ç±oÂ¥H¤Î¥LªºÄҦäw¸g§¹¥þ¦û¾Ú¤F¾÷³õ¡C§Ú¨ü©R¨Ó°l®·¯Ç§J·ç±oÂ¥H¤Î±ÃÂ¥X©Ò¦³¤H½è¡C³o¨Ã¤£®e©ö¡C"; + // psText = + //"Ãɨô­ôº¸³Õ¤h¤w¸g¦w¥þ¤F¡A§Ú¤]§â©Ò¦³µo²{³ø§iµ¹¡u°Ó©±¡v¡C«Ü¤£©¯¦a¡A·ç¤hĵ§½¦³¨Ç¥Õèµo²{¤F¤@¨Çª¬ªp¡A·Ç³Æ¦b¾÷³õ¶e®·¨È¾ú¦è¡E¯Ç§J·ç±o¡CÂ¥L°°¸Ë¦¨¥~¥æ¨Ã¸`¡A¬ï¹L¤F¼h¼h¨¾³Æ¡C²{¦bÂ¥L´¤¦³¤H½è¡A¨Ã¥B«Â¯Ù­n´²¼½¯f¬r¡C®Ú¾Ú³Ì·psCurrentTextReadPosªº³ø§i¡A¯Ç§J·ç±oÂ¥H¤Î¥LªºÄҦäw¸g§¹¥þ¦û¾Ú¤F¾÷³õ¡C§Ú¨ü©R¨Ó°l®·¯Ç§J·ç±oÂ¥H¤Î±ÃÂ¥X©Ò¦³¤H½è¡C³o¨Ã¤£®e©ö¡C"; // this could probably be simplified now, but it was converted from something else I didn't originally write, // and it works anyway so wtf... @@ -72,17 +65,15 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei const char *psCurrentTextReadPos = psText; const char *psReadPosAtLineStart = psCurrentTextReadPos; const char *psBestLineBreakSrcPos = psCurrentTextReadPos; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) - while( *psCurrentTextReadPos && (iYpos + iFontHeight < (iBoxY + iBoxHeight)) ) - { - char sLineForDisplay[2048]; // ott + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + while (*psCurrentTextReadPos && (iYpos + iFontHeight < (iBoxY + iBoxHeight))) { + char sLineForDisplay[2048]; // ott // construct a line... // psCurrentTextReadPos = psReadPosAtLineStart; sLineForDisplay[0] = '\0'; - while ( *psCurrentTextReadPos ) - { + while (*psCurrentTextReadPos) { psLastGood_s = psCurrentTextReadPos; // read letter... @@ -92,45 +83,33 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // concat onto string so far... // - if (uiLetter == 32 && sLineForDisplay[0] == '\0') - { + if (uiLetter == 32 && sLineForDisplay[0] == '\0') { psReadPosAtLineStart++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - sLineForDisplay[ strlen(sLineForDisplay)-1 ] = '\0'; // kill the CR + sLineForDisplay[strlen(sLineForDisplay) - 1] = '\0'; // kill the CR psReadPosAtLineStart = psCurrentTextReadPos; psBestLineBreakSrcPos = psCurrentTextReadPos; - break; // print this line - } - else - if ( cgi_R_Font_StrLenPixels(sLineForDisplay, iFontHandle, fScale) >= iBoxWidth ) - { + break; // print this line + } else if (cgi_R_Font_StrLenPixels(sLineForDisplay, iFontHandle, fScale) >= iBoxWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == psReadPosAtLineStart) - { + } else { + if (psBestLineBreakSrcPos == psReadPosAtLineStart) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -138,19 +117,18 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // normally). On the other hand I suppose it'psCurrentTextReadPos entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - sLineForDisplay[ psBestLineBreakSrcPos - psReadPosAtLineStart ] = '\0'; + sLineForDisplay[psBestLineBreakSrcPos - psReadPosAtLineStart] = '\0'; psReadPosAtLineStart = psCurrentTextReadPos = psBestLineBreakSrcPos; - break; // print this line + break; // print this line } } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) { psBestLineBreakSrcPos = psCurrentTextReadPos; } } @@ -162,16 +140,13 @@ const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHei // and echo to console in dev mode... // - if ( cg_developer.integer ) - { -// Com_Printf( "%psCurrentTextReadPos\n", sLineForDisplay ); + if (cg_developer.integer) { + // Com_Printf( "%psCurrentTextReadPos\n", sLineForDisplay ); } } return psReadPosAtLineStart; } - - /* =============================================================================== @@ -179,33 +154,26 @@ CAPTION TEXT =============================================================================== */ -void CG_CaptionTextStop(void) -{ - cg.captionTextTime = 0; -} +void CG_CaptionTextStop(void) { cg.captionTextTime = 0; } // try and get the correct StripEd text (with retry) for a given reference... // // returns 0 if failed, else strlen... // -static int cg_SP_GetStringTextStringWithRetry( const char *psReference, char *psDest, int iSizeofDest ) -{ +static int cg_SP_GetStringTextStringWithRetry(const char *psReference, char *psDest, int iSizeofDest) { int iReturn; - if (psReference[0] == '#') - { + if (psReference[0] == '#') { // then we know the striped package name is already built in, so do NOT try prepending anything else... // - return cgi_SP_GetStringTextString( va("%s",psReference+1), psDest, iSizeofDest ); + return cgi_SP_GetStringTextString(va("%s", psReference + 1), psDest, iSizeofDest); } - for (int i=0; i 255) - { - Q_strcat(cg.captionText[i],sizeof(cg.captionText[i]),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(cg.captionText[i],sizeof(cg.captionText[i]),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(cg.captionText[i], sizeof(cg.captionText[i]), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(cg.captionText[i], sizeof(cg.captionText[i]), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - cg.captionText[i][ strlen(cg.captionText[i])-1 ] = '\0'; // kill the CR + cg.captionText[i][strlen(cg.captionText[i]) - 1] = '\0'; // kill the CR i++; holds = s; psBestLineBreakSrcPos = s; cg.scrollTextLines++; - } - else - if ( cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale) >= SCREEN_WIDTH) - { + } else if (cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale) >= SCREEN_WIDTH) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !cgi_Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == holds) - { + } else { + if (psBestLineBreakSrcPos == holds) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -347,10 +298,10 @@ void CG_CaptionText( const char *str, int sound ) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - cg.captionText[i][ psBestLineBreakSrcPos - holds ] = '\0'; + cg.captionText[i][psBestLineBreakSrcPos - holds] = '\0'; holds = s = psBestLineBreakSrcPos; i++; cg.scrollTextLines++; @@ -359,102 +310,85 @@ void CG_CaptionText( const char *str, int sound ) // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !cgi_Language_UsesSpaces())) { psBestLineBreakSrcPos = s; } } - // calc the length of time to hold each 2 lines of text on the screen.... presumably this works? // holdTime = strlen(cg.captionText[0]); - if (cg.scrollTextLines > 1) - { - holdTime += strlen(cg.captionText[1]); // strlen is also good for MBCS in this instance, since it's for timing + if (cg.scrollTextLines > 1) { + holdTime += strlen(cg.captionText[1]); // strlen is also good for MBCS in this instance, since it's for timing } cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime); - cg.scrollTextTime = 0; // No scrolling during captions + cg.scrollTextTime = 0; // No scrolling during captions - //Echo to console in dev mode - if ( cg_developer.integer ) - { - Com_Printf( "%s\n", cg.captionText[0] ); // ste: was [i], but surely sentence 0 is more useful than last? + // Echo to console in dev mode + if (cg_developer.integer) { + Com_Printf("%s\n", cg.captionText[0]); // ste: was [i], but surely sentence 0 is more useful than last? } } +void CG_DrawCaptionText(void) { + int i; + int x, y, w; + int holdTime; -void CG_DrawCaptionText(void) -{ - int i; - int x, y, w; - int holdTime; - - if ( !cg.captionTextTime ) - { + if (!cg.captionTextTime) { return; } const float fFontScale = cgi_Language_IsAsian() ? 0.8f : 1.0f; - if (cg_skippingcin.integer != 0) - { + if (cg_skippingcin.integer != 0) { cg.captionTextTime = 0; return; } - if ( cg.captionNextTextTime < cg.time ) - { + if (cg.captionNextTextTime < cg.time) { cg.captionTextCurrentLine += 2; - if (cg.captionTextCurrentLine >= cg.scrollTextLines) - { + if (cg.captionTextCurrentLine >= cg.scrollTextLines) { cg.captionTextTime = 0; return; - } - else - { + } else { holdTime = strlen(cg.captionText[cg.captionTextCurrentLine]); - if (cg.scrollTextLines >= cg.captionTextCurrentLine) - { + if (cg.scrollTextLines >= cg.captionTextCurrentLine) { // ( strlen is also good for MBCS in this instance, since it's for timing -ste) // holdTime += strlen(cg.captionText[cg.captionTextCurrentLine + 1]); } - cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime);//50); + cg.captionNextTextTime = cg.time + (holdTime * cg.captionLetterTime); // 50); } } // Give a color if one wasn't given - if((textcolor_caption[0] == 0) && (textcolor_caption[1] == 0) && - (textcolor_caption[2] == 0) && (textcolor_caption[3] == 0)) - { - VectorCopy4( colorTable[CT_WHITE], textcolor_caption ); + if ((textcolor_caption[0] == 0) && (textcolor_caption[1] == 0) && (textcolor_caption[2] == 0) && (textcolor_caption[3] == 0)) { + VectorCopy4(colorTable[CT_WHITE], textcolor_caption); } cgi_R_SetColor(textcolor_caption); // Set Y of the first line (varies if only printing one line of text) // (this all works, please don't mess with it) - const int fontHeight = (int) ((cgi_Language_IsAsian() ? 1.4f : 1.0f) * (float) cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, fFontScale)); - const bool bPrinting2Lines = !!(cg.captionText[ cg.captionTextCurrentLine+1 ][0]); - y = cg.captionTextY - ( (float)fontHeight * (bPrinting2Lines ? 1 : 0.5f)); // captionTextY was a centered Y pos, not a top one + const int fontHeight = (int)((cgi_Language_IsAsian() ? 1.4f : 1.0f) * (float)cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, fFontScale)); + const bool bPrinting2Lines = !!(cg.captionText[cg.captionTextCurrentLine + 1][0]); + y = cg.captionTextY - ((float)fontHeight * (bPrinting2Lines ? 1 : 0.5f)); // captionTextY was a centered Y pos, not a top one y -= cgi_Language_IsAsian() ? 0 : 4; - for (i= cg.captionTextCurrentLine;i< cg.captionTextCurrentLine + 2;++i) - { + for (i = cg.captionTextCurrentLine; i < cg.captionTextCurrentLine + 2; ++i) { w = cgi_R_Font_StrLenPixels(cg.captionText[i], cgs.media.qhFontMedium, fFontScale); - if (w) - { - x = (SCREEN_WIDTH-w) / 2; + if (w) { + x = (SCREEN_WIDTH - w) / 2; cgi_R_Font_DrawString(x, y, cg.captionText[i], textcolor_caption, cgs.media.qhFontMedium, -1, fFontScale); y += fontHeight; } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -470,40 +404,37 @@ CG_ScrollText - split text up into seperate lines */ int giScrollTextPixelWidth = SCREEN_WIDTH; -void CG_ScrollText( const char *str, int iPixelWidth ) -{ - const char *s,*holds; - int i;//, len;//, numChars; +void CG_ScrollText(const char *str, int iPixelWidth) { + const char *s, *holds; + int i; //, len;//, numChars; giScrollTextPixelWidth = iPixelWidth; // first, ask the strlen of the final string... // - i = cgi_SP_GetStringTextString( str, NULL, 0 ); + i = cgi_SP_GetStringTextString(str, NULL, 0); - //ensure we found a match - if (!i) - { + // ensure we found a match + if (!i) { #ifndef FINAL_BUILD - Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n",str); + Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n", str); #endif return; } // // malloc space to hold it... // - char *psText = (char *) cgi_Z_Malloc( i+1, TAG_TEMP_WORKSPACE ); + char *psText = (char *)cgi_Z_Malloc(i + 1, TAG_TEMP_WORKSPACE); // // now get the string... // - i = cgi_SP_GetStringTextString( str, psText, i+1 ); - //ensure we found a match - if (!i) - { - assert(0); // should never get here now, but wtf? + i = cgi_SP_GetStringTextString(str, psText, i + 1); + // ensure we found a match + if (!i) { + assert(0); // should never get here now, but wtf? cgi_Z_Free(psText); #ifndef FINAL_BUILD - Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n",str); + Com_Printf("WARNING: CG_ScrollText given invalid text key :'%s'\n", str); #endif return; } @@ -517,9 +448,8 @@ void CG_ScrollText( const char *str, int iPixelWidth ) holds = s; const char *psBestLineBreakSrcPos = s; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) - while( *s ) - { + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + while (*s) { psLastGood_s = s; // read letter... @@ -529,49 +459,38 @@ void CG_ScrollText( const char *str, int iPixelWidth ) // concat onto string so far... // - if (uiLetter == 32 && cg.printText[i][0] == '\0') - { + if (uiLetter == 32 && cg.printText[i][0] == '\0') { holds++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(cg.printText[i],sizeof(cg.printText[i]),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(cg.printText[i],sizeof(cg.printText[i]),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(cg.printText[i], sizeof(cg.printText[i]), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(cg.printText[i], sizeof(cg.printText[i]), va("%c", uiLetter & 0xFF)); } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ') - { + if (bIsTrailingPunctuation || uiLetter == ' ') { psBestLineBreakSrcPos = s; } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - cg.printText[i][ strlen(cg.printText[i])-1 ] = '\0'; // kill the CR + cg.printText[i][strlen(cg.printText[i]) - 1] = '\0'; // kill the CR i++; - assert (i < (int)ARRAY_LEN( cg.printText ) ); - if (i >= (int)ARRAY_LEN( cg.printText ) ) - { + assert(i < (int)ARRAY_LEN(cg.printText)); + if (i >= (int)ARRAY_LEN(cg.printText)) { break; } holds = s; cg.scrollTextLines++; - } - else - if ( cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f) >= iPixelWidth) - { + } else if (cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f) >= iPixelWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (psBestLineBreakSrcPos == holds) - { + if (psBestLineBreakSrcPos == holds) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -579,77 +498,69 @@ void CG_ScrollText( const char *str, int iPixelWidth ) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - cg.printText[i][ psBestLineBreakSrcPos - holds ] = '\0'; + cg.printText[i][psBestLineBreakSrcPos - holds] = '\0'; holds = s = psBestLineBreakSrcPos; i++; - assert( i < (int)ARRAY_LEN( cg.printText ) ); + assert(i < (int)ARRAY_LEN(cg.printText)); cg.scrollTextLines++; } } - cg.captionTextTime = 0; // No captions during scrolling + cg.captionTextTime = 0; // No captions during scrolling cgi_Z_Free(psText); } - // draws using [textcolor_scroll]... // -#define SCROLL_LPM (1/50.0) // 1 line per 50 ms -void CG_DrawScrollText(void) -{ - int i; - int x,y; - const int fontHeight = (int) (1.5f * (float) cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f)); // taiwanese & japanese need 1.5 fontheight spacing - - if ( !cg.scrollTextTime ) - { +#define SCROLL_LPM (1 / 50.0) // 1 line per 50 ms +void CG_DrawScrollText(void) { + int i; + int x, y; + const int fontHeight = (int)(1.5f * (float)cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f)); // taiwanese & japanese need 1.5 fontheight spacing + + if (!cg.scrollTextTime) { return; } - cgi_R_SetColor( textcolor_scroll ); + cgi_R_SetColor(textcolor_scroll); y = cg.printTextY - (cg.time - cg.scrollTextTime) * SCROLL_LPM; -// cgi_R_Font_DrawString(320, 200, va("Scrolltext printing @ %d",y), colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); + // cgi_R_Font_DrawString(320, 200, va("Scrolltext printing @ %d",y), colorTable[CT_LTGOLD1], cgs.media.qhFontMedium, -1, 1.0f); // See if text has finished scrolling off screen - if ((y + cg.scrollTextLines * fontHeight) < 1) - { + if ((y + cg.scrollTextLines * fontHeight) < 1) { cg.scrollTextTime = 0; return; } - for (i=0;i SCREEN_HEIGHT) - { + else if (y > SCREEN_HEIGHT) { break; } -// w = cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f); -// if (w) + // w = cgi_R_Font_StrLenPixels(cg.printText[i], cgs.media.qhFontMedium, 1.0f); + // if (w) { x = (SCREEN_WIDTH - giScrollTextPixelWidth) / 2; - cgi_R_Font_DrawString(x,y, cg.printText[i], textcolor_scroll, cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x, y, cg.printText[i], textcolor_scroll, cgs.media.qhFontMedium, -1, 1.0f); y += fontHeight; } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - /* =============================================================================== @@ -658,7 +569,6 @@ CENTER PRINTING =============================================================================== */ - /* ============== CG_CenterPrint @@ -667,25 +577,21 @@ Called for important messages that should stay in the center of the screen for a few moments ============== */ -void CG_CenterPrint( const char *str, int y) { - char *s; +void CG_CenterPrint(const char *str, int y) { + char *s; // Find text to match the str given - if (*str == '@') - { + if (*str == '@') { int i; - i = cgi_SP_GetStringTextString( str+1, cg.centerPrint, sizeof(cg.centerPrint) ); + i = cgi_SP_GetStringTextString(str + 1, cg.centerPrint, sizeof(cg.centerPrint)); - if (!i) - { - Com_Printf (S_COLOR_RED"CG_CenterPrint: cannot find reference '%s' in StringPackage!\n",str); - Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); + if (!i) { + Com_Printf(S_COLOR_RED "CG_CenterPrint: cannot find reference '%s' in StringPackage!\n", str); + Q_strncpyz(cg.centerPrint, str, sizeof(cg.centerPrint)); } - } - else - { - Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); + } else { + Q_strncpyz(cg.centerPrint, str, sizeof(cg.centerPrint)); } cg.centerPrintTime = cg.time; @@ -694,40 +600,35 @@ void CG_CenterPrint( const char *str, int y) { // count the number of lines for centering cg.centerPrintLines = 1; s = cg.centerPrint; - while( *s ) { + while (*s) { if (*s == '\n') cg.centerPrintLines++; s++; } - } - /* =================== CG_DrawCenterString =================== */ -void CG_DrawCenterString( void ) -{ - char *start; - int l; - int x, y, w; - float *color; - - if ( !cg.centerPrintTime ) { +void CG_DrawCenterString(void) { + char *start; + int l; + int x, y, w; + float *color; + + if (!cg.centerPrintTime) { return; } - color = CG_FadeColor( cg.centerPrintTime, 1000 * cg_centertime.value ); - if ( !color ) { + color = CG_FadeColor(cg.centerPrintTime, 1000 * cg_centertime.value); + if (!color) { return; } - if((textcolor_center[0] == 0) && (textcolor_center[1] == 0) && - (textcolor_center[2] == 0) && (textcolor_center[3] == 0)) - { - VectorCopy4( colorTable[CT_WHITE], textcolor_center ); + if ((textcolor_center[0] == 0) && (textcolor_center[1] == 0) && (textcolor_center[2] == 0) && (textcolor_center[3] == 0)) { + VectorCopy4(colorTable[CT_WHITE], textcolor_center); } start = cg.centerPrint; @@ -735,25 +636,22 @@ void CG_DrawCenterString( void ) const int fontHeight = cgi_R_Font_HeightPixels(cgs.media.qhFontMedium, 1.0f); y = cg.centerPrintY - (cg.centerPrintLines * fontHeight) / 2; - while ( 1 ) { + while (1) { char linebuffer[1024]; // this is kind of unpleasant when dealing with MBCS, but... // const char *psString = start; int iOutIndex = 0; - for ( l = 0; l < (int)sizeof(linebuffer)-1; l++ ) { + for (l = 0; l < (int)sizeof(linebuffer) - 1; l++) { unsigned int uiLetter = cgi_AnyLanguage_ReadCharFromString(&psString, 0); - if (!uiLetter || uiLetter == '\n'){ + if (!uiLetter || uiLetter == '\n') { break; } - if (uiLetter > 255) - { + if (uiLetter > 255) { linebuffer[iOutIndex++] = uiLetter >> 8; linebuffer[iOutIndex++] = uiLetter & 0xFF; - } - else - { + } else { linebuffer[iOutIndex++] = uiLetter & 0xFF; } } @@ -761,19 +659,18 @@ void CG_DrawCenterString( void ) w = cgi_R_Font_StrLenPixels(linebuffer, cgs.media.qhFontMedium, 1.0f); - x = ( SCREEN_WIDTH - w ) / 2; + x = (SCREEN_WIDTH - w) / 2; - cgi_R_Font_DrawString(x,y,linebuffer, textcolor_center, cgs.media.qhFontMedium, -1, 1.0f); + cgi_R_Font_DrawString(x, y, linebuffer, textcolor_center, cgs.media.qhFontMedium, -1, 1.0f); y += fontHeight; - while ( *start && ( *start != '\n' ) ) { + while (*start && (*start != '\n')) { start++; } - if ( !*start ) { + if (!*start) { break; } start++; } - } diff --git a/codeJK2/cgame/cg_view.cpp b/codeJK2/cgame/cg_view.cpp index e3dcdd650d..ae20dda86c 100644 --- a/codeJK2/cgame/cg_view.cpp +++ b/codeJK2/cgame/cg_view.cpp @@ -32,12 +32,12 @@ along with this program; if not, see . #include "../game/g_functions.h" #define MASK_CAMERACLIP (MASK_SOLID) -#define CAMERA_SIZE 4 +#define CAMERA_SIZE 4 float cg_zoomFov; //#define CG_CAM_ABOVE 2 -extern qboolean CG_OnMovingPlat( playerState_t *ps ); +extern qboolean CG_OnMovingPlat(playerState_t *ps); /* ============================================================================= @@ -49,7 +49,7 @@ enhanced into a single model testing facility. Model viewing can begin with either "testmodel " or "testgun ". -The names must be the full pathname after the basedir, like +The names must be the full pathname after the basedir, like "models/weapons/v_launch/tris.md3" or "players/male/tris.md3" Testmodel will create a fake entity 100 units in front of the current view @@ -86,122 +86,110 @@ Creates an entity in front of the current position, which can then be moved around ================= */ -void CG_TestG2Model_f (void) { - vec3_t angles; +void CG_TestG2Model_f(void) { + vec3_t angles; CGhoul2Info_v *ghoul2; - memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) ); + memset(&cg.testModelEntity, 0, sizeof(cg.testModelEntity)); ghoul2 = new CGhoul2Info_v; cg.testModelEntity.ghoul2 = ghoul2; - if ( cgi_Argc() < 2 ) { + if (cgi_Argc() < 2) { return; } - Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH ); - cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + Q_strncpyz(cg.testModelName, CG_Argv(1), MAX_QPATH); + cg.testModelEntity.hModel = cgi_R_RegisterModel(cg.testModelName); - cg.testModel = gi.G2API_InitGhoul2Model( *((CGhoul2Info_v *)cg.testModelEntity.ghoul2), cg.testModelName, cg.testModelEntity.hModel, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + cg.testModel = + gi.G2API_InitGhoul2Model(*((CGhoul2Info_v *)cg.testModelEntity.ghoul2), cg.testModelName, cg.testModelEntity.hModel, NULL_HANDLE, NULL_HANDLE, 0, 0); cg.testModelEntity.radius = 100.0f; - if ( cgi_Argc() == 3 ) { - cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) ); + if (cgi_Argc() == 3) { + cg.testModelEntity.backlerp = atof(CG_Argv(2)); cg.testModelEntity.frame = 1; cg.testModelEntity.oldframe = 0; } - if (! cg.testModelEntity.hModel ) { - CG_Printf( "Can't register model\n" ); + if (!cg.testModelEntity.hModel) { + CG_Printf("Can't register model\n"); return; } - VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin ); + VectorMA(cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin); angles[PITCH] = 0; angles[YAW] = 180 + cg.refdefViewAngles[1]; angles[ROLL] = 0; - AnglesToAxis( angles, cg.testModelEntity.axis ); + AnglesToAxis(angles, cg.testModelEntity.axis); cg.testGun = qfalse; } -void CG_ListModelSurfaces_f (void) -{ - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); +void CG_ListModelSurfaces_f(void) { + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); - gi.G2API_ListSurfaces(&ghoul2[cg.testModel]); + gi.G2API_ListSurfaces(&ghoul2[cg.testModel]); } - -void CG_ListModelBones_f (void) -{ - // test to see if we got enough args - if ( cgi_Argc() < 2 ) - { +void CG_ListModelBones_f(void) { + // test to see if we got enough args + if (cgi_Argc() < 2) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); gi.G2API_ListBones(&ghoul2[cg.testModel], atoi(CG_Argv(1))); } -void CG_TestModelSurfaceOnOff_f(void) -{ +void CG_TestModelSurfaceOnOff_f(void) { // test to see if we got enough args - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); gi.G2API_SetSurfaceOnOff(&ghoul2[cg.testModel], CG_Argv(1), atoi(CG_Argv(2))); } -void CG_TestModelSetAnglespre_f(void) -{ - vec3_t angles; +void CG_TestModelSetAnglespre_f(void) { + vec3_t angles; - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); - angles[0] = atof(CG_Argv(2)); - angles[1] = atof(CG_Argv(3)); + angles[0] = atof(CG_Argv(2)); + angles[1] = atof(CG_Argv(3)); angles[2] = atof(CG_Argv(4)); gi.G2API_SetBoneAngles(&ghoul2[cg.testModel], CG_Argv(1), angles, BONE_ANGLES_PREMULT, POSITIVE_X, POSITIVE_Z, POSITIVE_Y, NULL, 0, 0); } -void CG_TestModelSetAnglespost_f(void) -{ - vec3_t angles; +void CG_TestModelSetAnglespost_f(void) { + vec3_t angles; - if ( cgi_Argc() < 3 ) - { + if (cgi_Argc() < 3) { return; } - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); - angles[0] = atof(CG_Argv(2)); - angles[1] = atof(CG_Argv(3)); + angles[0] = atof(CG_Argv(2)); + angles[1] = atof(CG_Argv(3)); angles[2] = atof(CG_Argv(4)); gi.G2API_SetBoneAngles(&ghoul2[cg.testModel], CG_Argv(1), angles, BONE_ANGLES_POSTMULT, POSITIVE_X, POSITIVE_Z, POSITIVE_Y, NULL, 0, 0); } -void CG_TestModelAnimate_f(void) -{ - char boneName[100]; - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); +void CG_TestModelAnimate_f(void) { + char boneName[100]; + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)cg.testModelEntity.ghoul2); Q_strncpyz(boneName, CG_Argv(1), sizeof(boneName)); gi.G2API_SetBoneAnim(&ghoul2[cg.testModel], boneName, atoi(CG_Argv(2)), atoi(CG_Argv(3)), BONE_ANIM_OVERRIDE_LOOP, atof(CG_Argv(4)), cg.time, -1, -1); - } /* Ghoul2 Insert End */ - /* ================= CG_TestModel_f @@ -210,34 +198,34 @@ Creates an entity in front of the current position, which can then be moved around ================= */ -void CG_TestModel_f (void) { - vec3_t angles; +void CG_TestModel_f(void) { + vec3_t angles; - memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) ); - if ( cgi_Argc() < 2 ) { + memset(&cg.testModelEntity, 0, sizeof(cg.testModelEntity)); + if (cgi_Argc() < 2) { return; } - Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH ); - cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + Q_strncpyz(cg.testModelName, CG_Argv(1), MAX_QPATH); + cg.testModelEntity.hModel = cgi_R_RegisterModel(cg.testModelName); - if ( cgi_Argc() == 3 ) { - cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) ); + if (cgi_Argc() == 3) { + cg.testModelEntity.backlerp = atof(CG_Argv(2)); cg.testModelEntity.frame = 1; cg.testModelEntity.oldframe = 0; } - if (! cg.testModelEntity.hModel ) { - CG_Printf( "Can't register model\n" ); + if (!cg.testModelEntity.hModel) { + CG_Printf("Can't register model\n"); return; } - VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin ); + VectorMA(cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin); angles[PITCH] = 0; angles[YAW] = 180 + cg.refdefViewAngles[1]; angles[ROLL] = 0; - AnglesToAxis( angles, cg.testModelEntity.axis ); + AnglesToAxis(angles, cg.testModelEntity.axis); cg.testGun = qfalse; } @@ -248,72 +236,68 @@ CG_TestGun_f Replaces the current view weapon with the given model ================= */ -void CG_TestGun_f (void) { +void CG_TestGun_f(void) { CG_TestModel_f(); cg.testGun = qtrue; cg.testModelEntity.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON; } - -void CG_TestModelNextFrame_f (void) { +void CG_TestModelNextFrame_f(void) { cg.testModelEntity.frame++; - CG_Printf( "frame %i\n", cg.testModelEntity.frame ); + CG_Printf("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelPrevFrame_f (void) { +void CG_TestModelPrevFrame_f(void) { cg.testModelEntity.frame--; - if ( cg.testModelEntity.frame < 0 ) { + if (cg.testModelEntity.frame < 0) { cg.testModelEntity.frame = 0; } - CG_Printf( "frame %i\n", cg.testModelEntity.frame ); + CG_Printf("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelNextSkin_f (void) { +void CG_TestModelNextSkin_f(void) { cg.testModelEntity.skinNum++; - CG_Printf( "skin %i\n", cg.testModelEntity.skinNum ); + CG_Printf("skin %i\n", cg.testModelEntity.skinNum); } -void CG_TestModelPrevSkin_f (void) { +void CG_TestModelPrevSkin_f(void) { cg.testModelEntity.skinNum--; - if ( cg.testModelEntity.skinNum < 0 ) { + if (cg.testModelEntity.skinNum < 0) { cg.testModelEntity.skinNum = 0; } - CG_Printf( "skin %i\n", cg.testModelEntity.skinNum ); + CG_Printf("skin %i\n", cg.testModelEntity.skinNum); } -static void CG_AddTestModel (void) { - int i; +static void CG_AddTestModel(void) { + int i; - // re-register the model, because the level may have changed -/* cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); - if (! cg.testModelEntity.hModel ) { - CG_Printf ("Can't register model\n"); - return; - } -*/ + // re-register the model, because the level may have changed + /* cg.testModelEntity.hModel = cgi_R_RegisterModel( cg.testModelName ); + if (! cg.testModelEntity.hModel ) { + CG_Printf ("Can't register model\n"); + return; + } + */ // if testing a gun, set the origin reletive to the view origin - if ( cg.testGun ) { - VectorCopy( cg.refdef.vieworg, cg.testModelEntity.origin ); - VectorCopy( cg.refdef.viewaxis[0], cg.testModelEntity.axis[0] ); - VectorCopy( cg.refdef.viewaxis[1], cg.testModelEntity.axis[1] ); - VectorCopy( cg.refdef.viewaxis[2], cg.testModelEntity.axis[2] ); + if (cg.testGun) { + VectorCopy(cg.refdef.vieworg, cg.testModelEntity.origin); + VectorCopy(cg.refdef.viewaxis[0], cg.testModelEntity.axis[0]); + VectorCopy(cg.refdef.viewaxis[1], cg.testModelEntity.axis[1]); + VectorCopy(cg.refdef.viewaxis[2], cg.testModelEntity.axis[2]); // allow the position to be adjusted - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { cg.testModelEntity.origin[i] += cg.refdef.viewaxis[0][i] * cg_gun_x.value; cg.testModelEntity.origin[i] += cg.refdef.viewaxis[1][i] * cg_gun_y.value; cg.testModelEntity.origin[i] += cg.refdef.viewaxis[2][i] * cg_gun_z.value; } } - cgi_R_AddRefEntityToScene( &cg.testModelEntity ); + cgi_R_AddRefEntityToScene(&cg.testModelEntity); } - - //============================================================================ - /* ================= CG_CalcVrect @@ -321,8 +305,8 @@ CG_CalcVrect Sets the coordinates of the rendered window ================= */ -void CG_CalcVrect (void) { - const int size = 100; +void CG_CalcVrect(void) { + const int size = 100; cg.refdef.width = cgs.glconfig.vidWidth * size * 0.01; cg.refdef.width &= ~1; @@ -336,22 +320,22 @@ void CG_CalcVrect (void) { //============================================================================== //============================================================================== -#define CAMERA_DAMP_INTERVAL 50 +#define CAMERA_DAMP_INTERVAL 50 -#define CAMERA_CROUCH_NUDGE 6 +#define CAMERA_CROUCH_NUDGE 6 -static vec3_t cameramins = { -CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE }; -static vec3_t cameramaxs = { CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE }; -vec3_t camerafwd, cameraup, camerahorizdir; +static vec3_t cameramins = {-CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE}; +static vec3_t cameramaxs = {CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE}; +vec3_t camerafwd, cameraup, camerahorizdir; -vec3_t cameraFocusAngles, cameraFocusLoc; -vec3_t cameraIdealTarget, cameraIdealLoc; -vec3_t cameraCurTarget={0,0,0}, cameraCurLoc={0,0,0}; -vec3_t cameraOldLoc={0,0,0}, cameraNewLoc={0,0,0}; -int cameraLastFrame=0; +vec3_t cameraFocusAngles, cameraFocusLoc; +vec3_t cameraIdealTarget, cameraIdealLoc; +vec3_t cameraCurTarget = {0, 0, 0}, cameraCurLoc = {0, 0, 0}; +vec3_t cameraOldLoc = {0, 0, 0}, cameraNewLoc = {0, 0, 0}; +int cameraLastFrame = 0; -float cameraLastYaw=0; -float cameraStiffFactor=0.0f; +float cameraLastYaw = 0; +float cameraStiffFactor = 0.0f; /* =============== @@ -366,130 +350,97 @@ cg.refdefViewAngles =============== */ - + /* =============== CG_CalcIdealThirdPersonViewTarget =============== */ -static void CG_CalcIdealThirdPersonViewTarget(void) -{ +static void CG_CalcIdealThirdPersonViewTarget(void) { // Initialize IdealTarget qboolean usesViewEntity = (qboolean)(cg.snap->ps.viewEntity && cg.snap->ps.viewEntity < ENTITYNUM_WORLD); VectorCopy(cg.refdef.vieworg, cameraFocusLoc); - if ( usesViewEntity ) - { + if (usesViewEntity) { gentity_t *gent = &g_entities[cg.snap->ps.viewEntity]; - if ( gent->client && (gent->client->NPC_class == CLASS_GONK - || gent->client->NPC_class == CLASS_INTERROGATOR - || gent->client->NPC_class == CLASS_SENTRY - || gent->client->NPC_class == CLASS_PROBE - || gent->client->NPC_class == CLASS_MOUSE - || gent->client->NPC_class == CLASS_R2D2 - || gent->client->NPC_class == CLASS_R5D2) ) - { // Droids use a generic offset + if (gent->client && (gent->client->NPC_class == CLASS_GONK || gent->client->NPC_class == CLASS_INTERROGATOR || + gent->client->NPC_class == CLASS_SENTRY || gent->client->NPC_class == CLASS_PROBE || gent->client->NPC_class == CLASS_MOUSE || + gent->client->NPC_class == CLASS_R2D2 || gent->client->NPC_class == CLASS_R5D2)) { // Droids use a generic offset cameraFocusLoc[2] += 4; - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); return; } - if( gent->client->ps.pm_flags & PMF_DUCKED ) - { // sort of a nasty hack in order to get this to work. Don't tell Ensiform, or I'll have to kill him. --eez - cameraFocusLoc[2] -= CAMERA_CROUCH_NUDGE*4; + if (gent->client->ps.pm_flags & PMF_DUCKED) { // sort of a nasty hack in order to get this to work. Don't tell Ensiform, or I'll have to kill him. --eez + cameraFocusLoc[2] -= CAMERA_CROUCH_NUDGE * 4; } } // Add in the new viewheight cameraFocusLoc[2] += cg.predicted_player_state.viewheight; - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_VOF ) - { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_VOF) { // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += cg.overrides.thirdPersonVertOffset; - //VectorMA(cameraFocusLoc, cg.overrides.thirdPersonVertOffset, cameraup, cameraIdealTarget); - } - else - { + // VectorMA(cameraFocusLoc, cg.overrides.thirdPersonVertOffset, cameraup, cameraIdealTarget); + } else { // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += cg_thirdPersonVertOffset.value; - //VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); + // VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); } // Now, if the player is crouching, do a little special tweak. The problem is that the player's head is way out of his bbox. - if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - { // Nudge to focus location up a tad. + if (cg.predicted_player_state.pm_flags & PMF_DUCKED) { // Nudge to focus location up a tad. vec3_t nudgepos; trace_t trace; VectorCopy(cameraFocusLoc, nudgepos); - nudgepos[2]+=CAMERA_CROUCH_NUDGE; + nudgepos[2] += CAMERA_CROUCH_NUDGE; CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, nudgepos, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction < 1.0) - { + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraFocusLoc); - } - else - { + } else { VectorCopy(nudgepos, cameraFocusLoc); } } } - - /* =============== CG_CalcIdealThirdPersonViewLocation =============== */ -static void CG_CalcIdealThirdPersonViewLocation(void) -{ - gentity_t *player = &g_entities[0]; - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_RNG ) - { +static void CG_CalcIdealThirdPersonViewLocation(void) { + gentity_t *player = &g_entities[0]; + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_RNG) { VectorMA(cameraIdealTarget, -(cg.overrides.thirdPersonRange), camerafwd, cameraIdealLoc); - } - else - { + } else { VectorMA(cameraIdealTarget, -(cg_thirdPersonRange.value), camerafwd, cameraIdealLoc); } - if ( cg.renderingThirdPerson && (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] ) - { + if (cg.renderingThirdPerson && (cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && player->client->ps.forcePowerDuration[FP_SPEED]) { float timeLeft = player->client->ps.forcePowerDuration[FP_SPEED] - cg.time; - float length = FORCE_SPEED_DURATION*forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; + float length = FORCE_SPEED_DURATION * forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; float amt = forceSpeedRangeMod[player->client->ps.forcePowerLevel[FP_SPEED]]; - if ( timeLeft < 500 ) - {//start going back - VectorMA(cameraIdealLoc, (timeLeft)/500*amt, camerafwd, cameraIdealLoc); - } - else if ( length - timeLeft < 1000 ) - {//start zooming in - VectorMA(cameraIdealLoc, (length - timeLeft)/1000*amt, camerafwd, cameraIdealLoc); - } - else - { + if (timeLeft < 500) { // start going back + VectorMA(cameraIdealLoc, (timeLeft) / 500 * amt, camerafwd, cameraIdealLoc); + } else if (length - timeLeft < 1000) { // start zooming in + VectorMA(cameraIdealLoc, (length - timeLeft) / 1000 * amt, camerafwd, cameraIdealLoc); + } else { VectorMA(cameraIdealLoc, amt, camerafwd, cameraIdealLoc); } } } - - -static void CG_ResetThirdPersonViewDamp(void) -{ +static void CG_ResetThirdPersonViewDamp(void) { trace_t trace; // Cap the pitch within reasonable limits - if (cameraFocusAngles[PITCH] > 89.0) - { + if (cameraFocusAngles[PITCH] > 89.0) { cameraFocusAngles[PITCH] = 89.0; - } - else if (cameraFocusAngles[PITCH] < -89.0) - { + } else if (cameraFocusAngles[PITCH] < -89.0) { cameraFocusAngles[PITCH] = -89.0; } @@ -507,15 +458,13 @@ static void CG_ResetThirdPersonViewDamp(void) // First thing we do is trace from the first person viewpoint out to the new target location. CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } // Now we trace from the new target location to the new view location, to make sure there is nothing in the way. CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurLoc); } @@ -525,38 +474,34 @@ static void CG_ResetThirdPersonViewDamp(void) } // This is called every frame. -static void CG_UpdateThirdPersonTargetDamp(void) -{ +static void CG_UpdateThirdPersonTargetDamp(void) { trace_t trace; - vec3_t targetdiff; - float dampfactor, dtime, ratio; + vec3_t targetdiff; + float dampfactor, dtime, ratio; // Set the cameraIdealTarget // Automatically get the ideal target, to avoid jittering. CG_CalcIdealThirdPersonViewTarget(); - if ( CG_OnMovingPlat( &cg.snap->ps ) ) - {//if moving on a plat, camera is *tight* + if (CG_OnMovingPlat(&cg.snap->ps)) { // if moving on a plat, camera is *tight* VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=1.0)//||cg.thisFrameTeleport) - { // No damping. + } else if (cg_thirdPersonTargetDamp.value >= 1.0) //||cg.thisFrameTeleport) + { // No damping. VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=0.0) - { + } else if (cg_thirdPersonTargetDamp.value >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealTarget, cameraCurTarget, targetdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/cg_timescale.value) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / cg_timescale.value) * + (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". - // Note that since there are a finite number of "practical" delta millisecond values possible, + // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. ratio = pow(dampfactor, dtime); - + // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealTarget, -ratio, targetdiff, cameraCurTarget); ///////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -566,8 +511,7 @@ static void CG_UpdateThirdPersonTargetDamp(void) // First thing we do is trace from the first person viewpoint out to the new target location. CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if (trace.fraction < 1.0) - { + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } @@ -579,94 +523,84 @@ static void CG_UpdateThirdPersonTargetDamp(void) // This can be called every interval, at the user's discretion. static int camWaterAdjust = 0; -static void CG_UpdateThirdPersonCameraDamp(void) -{ +static void CG_UpdateThirdPersonCameraDamp(void) { trace_t trace; - vec3_t locdiff; + vec3_t locdiff; float dampfactor, dtime, ratio; // Set the cameraIdealLoc CG_CalcIdealThirdPersonViewLocation(); - - + // First thing we do is calculate the appropriate damping factor for the camera. - dampfactor=0.0f; - if ( CG_OnMovingPlat( &cg.snap->ps ) ) - {//if moving on a plat, camera is *tight* - dampfactor=1.0f; - } - else if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_CDP ) - { - if ( cg.overrides.thirdPersonCameraDamp != 0.0f ) - { + dampfactor = 0.0f; + if (CG_OnMovingPlat(&cg.snap->ps)) { // if moving on a plat, camera is *tight* + dampfactor = 1.0f; + } else if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_CDP) { + if (cg.overrides.thirdPersonCameraDamp != 0.0f) { double pitch; // Note that the camera pitch has already been capped off to 89. pitch = Q_fabs(cameraFocusAngles[PITCH]); // The higher the pitch, the larger the factor, so as you look up, it damps a lot less. - pitch /= 89.0; - dampfactor = (1.0-cg.overrides.thirdPersonCameraDamp)*(pitch*pitch); + pitch /= 89.0; + dampfactor = (1.0 - cg.overrides.thirdPersonCameraDamp) * (pitch * pitch); dampfactor += cg.overrides.thirdPersonCameraDamp; } - } - else if ( cg_thirdPersonCameraDamp.value != 0.0f ) - { + } else if (cg_thirdPersonCameraDamp.value != 0.0f) { double pitch; // Note that the camera pitch has already been capped off to 89. pitch = Q_fabs(cameraFocusAngles[PITCH]); // The higher the pitch, the larger the factor, so as you look up, it damps a lot less. - pitch /= 89.0; - dampfactor = (1.0-cg_thirdPersonCameraDamp.value)*(pitch*pitch); + pitch /= 89.0; + dampfactor = (1.0 - cg_thirdPersonCameraDamp.value) * (pitch * pitch); dampfactor += cg_thirdPersonCameraDamp.value; // Now we also multiply in the stiff factor, so that faster yaw changes are stiffer. - if (cameraStiffFactor > 0.0f) - { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. - dampfactor += (1.0-dampfactor)*cameraStiffFactor; + if (cameraStiffFactor > + 0.0f) { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. + dampfactor += (1.0 - dampfactor) * cameraStiffFactor; } } - if (dampfactor>=1.0)//||cg.thisFrameTeleport) - { // No damping. + if (dampfactor >= 1.0) //||cg.thisFrameTeleport) + { // No damping. VectorCopy(cameraIdealLoc, cameraCurLoc); - } - else if (dampfactor>=0.0) - { + } else if (dampfactor >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealLoc, cameraCurLoc, locdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-dampfactor; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/cg_timescale.value) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - dampfactor; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / cg_timescale.value) * + (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". - // Note that since there are a finite number of "practical" delta millisecond values possible, + // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. ratio = pow(dampfactor, dtime); - + // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealLoc, -ratio, locdiff, cameraCurLoc); ///////////////////////////////////////////////////////////////////////////////////////////////////////// } // Now we trace from the first person viewpoint to the new view location, to make sure there is nothing in the way between the user and the camera... -// CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + // CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); // (OLD) Now we trace from the new target location to the new view location, to make sure there is nothing in the way. - CG_Trace( &trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if ( trace.fraction < 1.0f ) - { - VectorCopy( trace.endpos, cameraCurLoc ); + CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); + if (trace.fraction < 1.0f) { + VectorCopy(trace.endpos, cameraCurLoc); // We didn't trace all the way back, so push down the target accordingly. -// VectorSubtract(cameraCurTarget, cameraFocusLoc, locdiff); -// VectorMA(cameraFocusLoc, trace.fraction, locdiff, cameraCurTarget); + // VectorSubtract(cameraCurTarget, cameraFocusLoc, locdiff); + // VectorMA(cameraFocusLoc, trace.fraction, locdiff, cameraCurTarget); - //FIXME: when the trace hits movers, it gets very very jaggy... ? + // FIXME: when the trace hits movers, it gets very very jaggy... ? /* //this doesn't actually help any if ( trace.entityNum != ENTITYNUM_WORLD ) @@ -692,18 +626,14 @@ static void CG_UpdateThirdPersonCameraDamp(void) // however two full volume traces each frame is a bit scary to think about. } - - - /* =============== CG_OffsetThirdPersonView =============== */ -extern qboolean MatrixMode; -static void CG_OffsetThirdPersonView( void ) -{ +extern qboolean MatrixMode; +static void CG_OffsetThirdPersonView(void) { vec3_t diff; float deltayaw; @@ -711,98 +641,70 @@ static void CG_OffsetThirdPersonView( void ) cameraStiffFactor = 0.0; // Set camera viewing direction. - VectorCopy( cg.refdefViewAngles, cameraFocusAngles ); + VectorCopy(cg.refdefViewAngles, cameraFocusAngles); // if dead, look at killer - if ( cg.predicted_player_state.stats[STAT_HEALTH] <= 0 ) - { - if ( MatrixMode ) - { - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG ) - { + if (cg.predicted_player_state.stats[STAT_HEALTH] <= 0) { + if (MatrixMode) { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG) { cameraFocusAngles[YAW] += cg.overrides.thirdPersonAngle; - } - else - { + } else { cameraFocusAngles[YAW] = cg.predicted_player_state.stats[STAT_DEAD_YAW]; cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; } - } - else - { + } else { cameraFocusAngles[YAW] = cg.predicted_player_state.stats[STAT_DEAD_YAW]; } - } - else - { // Add in the third Person Angle. - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG ) - { + } else { // Add in the third Person Angle. + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG) { cameraFocusAngles[YAW] += cg.overrides.thirdPersonAngle; - } - else - { + } else { cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; } - if ( cg.overrides.active & CG_OVERRIDE_3RD_PERSON_POF ) - { + if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_POF) { cameraFocusAngles[PITCH] += cg.overrides.thirdPersonPitchOffset; - } - else - { + } else { cameraFocusAngles[PITCH] += cg_thirdPersonPitchOffset.value; } } - if ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) ) - {// First person saber + if (!cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE)) { // First person saber // FIXME: use something network-friendly - vec3_t org, viewDir; - VectorCopy( cg_entities[0].gent->client->renderInfo.eyePoint, org ); - float blend = 1.0f - fabs(cg.refdefViewAngles[PITCH])/90.0f; - AngleVectors( cg.refdefViewAngles, viewDir, NULL, NULL ); - VectorMA( org, -8, viewDir, org ); - VectorScale( org, 1.0f - blend, org ); - VectorMA( org, blend, cg.refdef.vieworg, cg.refdef.vieworg ); + vec3_t org, viewDir; + VectorCopy(cg_entities[0].gent->client->renderInfo.eyePoint, org); + float blend = 1.0f - fabs(cg.refdefViewAngles[PITCH]) / 90.0f; + AngleVectors(cg.refdefViewAngles, viewDir, NULL, NULL); + VectorMA(org, -8, viewDir, org); + VectorScale(org, 1.0f - blend, org); + VectorMA(org, blend, cg.refdef.vieworg, cg.refdef.vieworg); return; } // The next thing to do is to see if we need to calculate a new camera target location. // If we went back in time for some reason, or if we just started, reset the sample. - if (cameraLastFrame == 0 || cameraLastFrame > cg.time) - { + if (cameraLastFrame == 0 || cameraLastFrame > cg.time) { CG_ResetThirdPersonViewDamp(); - } - else - { + } else { // Cap the pitch within reasonable limits - if (cameraFocusAngles[PITCH] > 89.0) - { + if (cameraFocusAngles[PITCH] > 89.0) { cameraFocusAngles[PITCH] = 89.0; - } - else if (cameraFocusAngles[PITCH] < -89.0) - { + } else if (cameraFocusAngles[PITCH] < -89.0) { cameraFocusAngles[PITCH] = -89.0; } AngleVectors(cameraFocusAngles, camerafwd, NULL, cameraup); deltayaw = fabs(cameraFocusAngles[YAW] - cameraLastYaw); - if (deltayaw > 180.0f) - { // Normalize this angle so that it is between 0 and 180. + if (deltayaw > 180.0f) { // Normalize this angle so that it is between 0 and 180. deltayaw = fabs(deltayaw - 360.0f); } - cameraStiffFactor = deltayaw / (float)(cg.time-cameraLastFrame); - if (cameraStiffFactor < 1.0) - { + cameraStiffFactor = deltayaw / (float)(cg.time - cameraLastFrame); + if (cameraStiffFactor < 1.0) { cameraStiffFactor = 0.0; - } - else if (cameraStiffFactor > 2.5) - { + } else if (cameraStiffFactor > 2.5) { cameraStiffFactor = 0.75; - } - else - { // 1 to 2 scales from 0.0 to 0.5 - cameraStiffFactor = (cameraStiffFactor-1.0f)*0.5f; + } else { // 1 to 2 scales from 0.0 to 0.5 + cameraStiffFactor = (cameraStiffFactor - 1.0f) * 0.5f; } cameraLastYaw = cameraFocusAngles[YAW]; @@ -816,35 +718,30 @@ static void CG_OffsetThirdPersonView( void ) // We must now take the angle taken from the camera target and location. VectorSubtract(cameraCurTarget, cameraCurLoc, diff); - //Com_Printf( "%s\n", vtos(diff) ); + // Com_Printf( "%s\n", vtos(diff) ); float dist = VectorNormalize(diff); - if ( dist < 1.0f ) - {//must be hitting something, need some value to calc angles, so use cam forward - VectorCopy( camerafwd, diff ); + if (dist < 1.0f) { // must be hitting something, need some value to calc angles, so use cam forward + VectorCopy(camerafwd, diff); } vectoangles(diff, cg.refdefViewAngles); // Temp: just move the camera to the side a bit extern vmCvar_t cg_thirdPersonHorzOffset; - if ( cg_thirdPersonHorzOffset.value != 0.0f ) - { - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); - VectorMA( cameraCurLoc, cg_thirdPersonHorzOffset.value, cg.refdef.viewaxis[1], cameraCurLoc ); + if (cg_thirdPersonHorzOffset.value != 0.0f) { + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); + VectorMA(cameraCurLoc, cg_thirdPersonHorzOffset.value, cg.refdef.viewaxis[1], cameraCurLoc); } // ...and of course we should copy the new view location to the proper spot too. VectorCopy(cameraCurLoc, cg.refdef.vieworg); - //if we hit the water, do a last-minute adjustment - if ( camWaterAdjust ) - { + // if we hit the water, do a last-minute adjustment + if (camWaterAdjust) { cg.refdef.vieworg[2] += camWaterAdjust; } - cameraLastFrame=cg.time; + cameraLastFrame = cg.time; } - - /* =============== CG_OffsetThirdPersonView @@ -937,7 +834,7 @@ static void CG_OffsetThirdPersonOverheadView( void ) { VectorCopy( cg.refdef.vieworg, view ); - // Move straight up from the player, making sure to always go at least the min camera height, + // Move straight up from the player, making sure to always go at least the min camera height, // otherwise, the camera will clip into the head of the player. float tpRange = cg.overrides.thirdPersonRange ? cg.overrides.thirdPersonRange : cg_thirdPersonRange.value; if ( tpRange < MIN_CAMERA_HEIGHT ) @@ -963,17 +860,17 @@ static void CG_OffsetThirdPersonOverheadView( void ) { angs[PITCH] = MAX_CAMERA_PITCH; } - // Convert our new desired camera angles and store them where they will get used by the engine + // Convert our new desired camera angles and store them where they will get used by the engine // when setting up the actual camera view. AnglesToAxis( angs, cg.refdef.viewaxis ); cg.refdefViewAngles[PITCH] = 0; g_entities[0].client->ps.delta_angles[PITCH] = 0; - + // Trace a ray from the origin to the viewpoint to make sure the view isn't // in a solid block. CG_Trace( &trace, cg.refdef.vieworg, mins, maxs, view, cg.predicted_player_state.clientNum, MASK_CAMERACLIP); - if ( trace.fraction != 1.0 ) + if ( trace.fraction != 1.0 ) { VectorCopy( trace.endpos, cg.refdef.vieworg ); } @@ -984,14 +881,13 @@ static void CG_OffsetThirdPersonOverheadView( void ) { } */ // this causes a compiler bug on mac MrC compiler -static void CG_StepOffset( void ) { - int timeDelta; - +static void CG_StepOffset(void) { + int timeDelta; + // smooth out stair climbing timeDelta = cg.time - cg.stepTime; - if ( timeDelta < STEP_TIME ) { - cg.refdef.vieworg[2] -= cg.stepChange - * (STEP_TIME - timeDelta) / STEP_TIME; + if (timeDelta < STEP_TIME) { + cg.refdef.vieworg[2] -= cg.stepChange * (STEP_TIME - timeDelta) / STEP_TIME; } } @@ -1001,22 +897,22 @@ CG_OffsetFirstPersonView =============== */ -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern int PM_AnimLength( int index, animNumber_t anim ); -static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { - float *origin; - float *angles; - float bob; - float ratio; - float delta; - float speed; - float f; - vec3_t predictedVelocity; - int timeDelta; - - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern int PM_AnimLength(int index, animNumber_t anim); +static void CG_OffsetFirstPersonView(qboolean firstPersonSaber) { + float *origin; + float *angles; + float bob; + float ratio; + float delta; + float speed; + float f; + vec3_t predictedVelocity; + int timeDelta; + + if (cg.snap->ps.pm_type == PM_INTERMISSION) { return; } @@ -1024,8 +920,7 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { angles = cg.refdefViewAngles; // if dead, fix the angle and don't add any kick - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { angles[ROLL] = 40; angles[PITCH] = -15; angles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW]; @@ -1033,38 +928,33 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { return; } - if ( g_entities[0].client && PM_InKnockDown( &g_entities[0].client->ps ) ) - { - float perc, animLen = (float)PM_AnimLength( g_entities[0].client->clientInfo.animFileIndex, (animNumber_t)g_entities[0].client->ps.legsAnim ); - if ( PM_InGetUp( &g_entities[0].client->ps ) || PM_InForceGetUp( &g_entities[0].client->ps ) ) - {//start righting the view - perc = (float)g_entities[0].client->ps.legsAnimTimer/animLen*2; - } - else - {//tilt the view - perc = (animLen-g_entities[0].client->ps.legsAnimTimer)/animLen*2; + if (g_entities[0].client && PM_InKnockDown(&g_entities[0].client->ps)) { + float perc, animLen = (float)PM_AnimLength(g_entities[0].client->clientInfo.animFileIndex, (animNumber_t)g_entities[0].client->ps.legsAnim); + if (PM_InGetUp(&g_entities[0].client->ps) || PM_InForceGetUp(&g_entities[0].client->ps)) { // start righting the view + perc = (float)g_entities[0].client->ps.legsAnimTimer / animLen * 2; + } else { // tilt the view + perc = (animLen - g_entities[0].client->ps.legsAnimTimer) / animLen * 2; } - if ( perc > 1.0f ) - { + if (perc > 1.0f) { perc = 1.0f; } - angles[ROLL] = perc*40; - angles[PITCH] = perc*-15; + angles[ROLL] = perc * 40; + angles[PITCH] = perc * -15; } // add angles based on weapon kick - VectorAdd (angles, cg.kick_angles, angles); + VectorAdd(angles, cg.kick_angles, angles); // add angles based on damage kick - if ( cg.damageTime ) { + if (cg.damageTime) { ratio = cg.time - cg.damageTime; - if ( ratio < DAMAGE_DEFLECT_TIME ) { + if (ratio < DAMAGE_DEFLECT_TIME) { ratio /= DAMAGE_DEFLECT_TIME; angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } else { - ratio = 1.0 - ( ratio - DAMAGE_DEFLECT_TIME ) / DAMAGE_RETURN_TIME; - if ( ratio > 0 ) { + ratio = 1.0 - (ratio - DAMAGE_DEFLECT_TIME) / DAMAGE_RETURN_TIME; + if (ratio > 0) { angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } @@ -1080,12 +970,12 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { #endif // add angles based on velocity - VectorCopy( cg.predicted_player_state.velocity, predictedVelocity ); + VectorCopy(cg.predicted_player_state.velocity, predictedVelocity); - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[0]); + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[0]); angles[PITCH] += delta * cg_runpitch.value; - - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[1]); + + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[1]); angles[ROLL] -= delta * cg_runroll.value; // add angles based on bob @@ -1095,42 +985,35 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { delta = cg.bobfracsin * cg_bobpitch.value * speed; if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - delta *= 3; // crouching + delta *= 3; // crouching angles[PITCH] += delta; delta = cg.bobfracsin * cg_bobroll.value * speed; if (cg.predicted_player_state.pm_flags & PMF_DUCKED) - delta *= 3; // crouching accentuates roll + delta *= 3; // crouching accentuates roll if (cg.bobcycle & 1) delta = -delta; angles[ROLL] += delta; -//=================================== + //=================================== - if ( !firstPersonSaber )//First person saber + if (!firstPersonSaber) // First person saber { // add view height - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if ( g_entities[cg.snap->ps.viewEntity].inuse && - g_entities[cg.snap->ps.viewEntity].client && - g_entities[cg.snap->ps.viewEntity].client->ps.viewheight ) - { + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (g_entities[cg.snap->ps.viewEntity].inuse && g_entities[cg.snap->ps.viewEntity].client && + g_entities[cg.snap->ps.viewEntity].client->ps.viewheight) { origin[2] += g_entities[cg.snap->ps.viewEntity].client->ps.viewheight; + } else { + origin[2] += 4; //??? } - else - { - origin[2] += 4;//??? - } - } - else - { + } else { origin[2] += cg.predicted_player_state.viewheight; } } // smooth out duck height changes timeDelta = cg.time - cg.duckTime; - if ( timeDelta < DUCK_TIME) { + if (timeDelta < DUCK_TIME) { cg.refdef.vieworg[2] -= cg.duckChange * (DUCK_TIME - timeDelta) / DUCK_TIME; } @@ -1142,27 +1025,25 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { origin[2] += bob; - // add fall height delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { + if (delta < LAND_DEFLECT_TIME) { f = delta / LAND_DEFLECT_TIME; cg.refdef.vieworg[2] += cg.landChange * f; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { delta -= LAND_DEFLECT_TIME; - f = 1.0 - ( delta / LAND_RETURN_TIME ); + f = 1.0 - (delta / LAND_RETURN_TIME); cg.refdef.vieworg[2] += cg.landChange * f; } // add step offset CG_StepOffset(); - if(cg.snap->ps.leanofs != 0) - { - vec3_t right; - //add leaning offset - //FIXME: when crouching, this bounces up and down?! - cg.refdefViewAngles[2] += (float)cg.snap->ps.leanofs/2; + if (cg.snap->ps.leanofs != 0) { + vec3_t right; + // add leaning offset + // FIXME: when crouching, this bounces up and down?! + cg.refdefViewAngles[2] += (float)cg.snap->ps.leanofs / 2; AngleVectors(cg.refdefViewAngles, NULL, right, NULL); VectorMA(cg.refdef.vieworg, (float)cg.snap->ps.leanofs, right, cg.refdef.vieworg); } @@ -1170,7 +1051,7 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { // pivot the eye based on a neck length #if 0 { -#define NECK_LENGTH 8 +#define NECK_LENGTH 8 vec3_t forward, up; cg.refdef.vieworg[2] -= NECK_LENGTH; @@ -1184,7 +1065,7 @@ static void CG_OffsetFirstPersonView( qboolean firstPersonSaber ) { //====================================================================== /* void CG_ZoomDown_f( void ) - { + { // Ignore zoom requests when yer paused if ( cg_paused.integer || in_camera ) { @@ -1218,9 +1099,9 @@ void CG_ZoomDown_f( void ) cgi_S_StartSound( cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.zoomEnd ); } } - + void CG_ZoomUp_f( void ) - { + { // Ignore zoom requests when yer paused if ( cg_paused.integer || in_camera ) { @@ -1241,62 +1122,59 @@ CG_CalcFovFromX Calcs Y FOV from given X FOV ==================== */ -#define WAVE_AMPLITUDE 1 -#define WAVE_FREQUENCY 0.4 +#define WAVE_AMPLITUDE 1 +#define WAVE_FREQUENCY 0.4 -qboolean CG_CalcFOVFromX( float fov_x ) -{ - float x; - float fov_y; - qboolean inwater; +qboolean CG_CalcFOVFromX(float fov_x) { + float x; + float fov_y; + qboolean inwater; - if ( cg_fovAspectAdjust.integer ) { + if (cg_fovAspectAdjust.integer) { // Based on LordHavoc's code for Darkplaces // http://www.quakeworld.nu/forum/topic/53/what-does-your-qw-look-like/page/30 const float baseAspect = 0.75f; // 3/4 - const float aspect = (float)cgs.glconfig.vidWidth/(float)cgs.glconfig.vidHeight; + const float aspect = (float)cgs.glconfig.vidWidth / (float)cgs.glconfig.vidHeight; const float desiredFov = fov_x; - fov_x = atan( tan( desiredFov*M_PI / 360.0f ) * baseAspect*aspect )*360.0f / M_PI; + fov_x = atan(tan(desiredFov * M_PI / 360.0f) * baseAspect * aspect) * 360.0f / M_PI; } - x = cg.refdef.width / tan( fov_x / 360 * M_PI ); - fov_y = atan2( cg.refdef.height, x ); + x = cg.refdef.width / tan(fov_x / 360 * M_PI); + fov_y = atan2(cg.refdef.height, x); fov_y = fov_y * 360 / M_PI; // there's a problem with this, it only takes the leafbrushes into account, not the entity brushes, - // so if you give slime/water etc properties to a func_door area brush in order to move the whole water + // so if you give slime/water etc properties to a func_door area brush in order to move the whole water // level up/down this doesn't take into account the door position, so warps the view the whole time // whether the water is up or not. Fortunately there's only one slime area in Trek that you can be under, // so lose it... #if 1 // warp if underwater - float phase; - float v; - int contents; - contents = CG_PointContents( cg.refdef.vieworg, -1 ); - if ( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ){ + float phase; + float v; + int contents; + contents = CG_PointContents(cg.refdef.vieworg, -1); + if (contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - v = WAVE_AMPLITUDE * sin( phase ); + v = WAVE_AMPLITUDE * sin(phase); fov_x += v; fov_y -= v; inwater = qtrue; - } - else { + } else { inwater = qfalse; } #else - //inwater = qfalse; + // inwater = qfalse; #endif // see if we are drugged by an interrogator. We muck with the FOV here, a bit later, after viewangles are calc'ed, I muck with those too. - if ( cg.wonkyTime > 0 && cg.wonkyTime > cg.time ) - { + if (cg.wonkyTime > 0 && cg.wonkyTime > cg.time) { float perc = (float)(cg.wonkyTime - cg.time) / 10000.0f; // goes for 10 seconds - fov_x += ( 25.0f * perc ); - fov_y -= ( cos( cg.time * 0.0008f ) * 5.0f * perc ); + fov_x += (25.0f * perc); + fov_y -= (cos(cg.time * 0.0008f) * 5.0f * perc); } // set it @@ -1306,24 +1184,18 @@ qboolean CG_CalcFOVFromX( float fov_x ) return (inwater); } -float CG_ForceSpeedFOV( void ) -{ - gentity_t *player = &g_entities[0]; +float CG_ForceSpeedFOV(void) { + gentity_t *player = &g_entities[0]; float fov; float timeLeft = player->client->ps.forcePowerDuration[FP_SPEED] - cg.time; - float length = FORCE_SPEED_DURATION*forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; + float length = FORCE_SPEED_DURATION * forceSpeedValue[player->client->ps.forcePowerLevel[FP_SPEED]]; float amt = forceSpeedFOVMod[player->client->ps.forcePowerLevel[FP_SPEED]]; - if ( timeLeft < 500 ) - {//start going back - fov = cg_fov.value + (timeLeft)/500*amt; - } - else if ( length - timeLeft < 1000 ) - {//start zooming in - fov = cg_fov.value + (length - timeLeft)/1000*amt; - } - else - {//stay at this FOV - fov = cg_fov.value+amt; + if (timeLeft < 500) { // start going back + fov = cg_fov.value + (timeLeft) / 500 * amt; + } else if (length - timeLeft < 1000) { // start zooming in + fov = cg_fov.value + (length - timeLeft) / 1000 * amt; + } else { // stay at this FOV + fov = cg_fov.value + amt; } return fov; } @@ -1334,170 +1206,138 @@ CG_CalcFov Fixed fov at intermissions, otherwise account for fov variable and zooms. ==================== */ -//extern float g_fov; -static qboolean CG_CalcFov( void ) { - float fov_x; - float f; - gentity_t *player = &g_entities[0]; +// extern float g_fov; +static qboolean CG_CalcFov(void) { + float fov_x; + float f; + gentity_t *player = &g_entities[0]; - if ( cg.predicted_player_state.pm_type == PM_INTERMISSION ) { + if (cg.predicted_player_state.pm_type == PM_INTERMISSION) { // if in intermission, use a fixed value fov_x = 80; - } - else if ( cg.snap - && cg.snap->ps.viewEntity > 0 - && cg.snap->ps.viewEntity < ENTITYNUM_WORLD - && (!cg.renderingThirdPerson || g_entities[cg.snap->ps.viewEntity].e_DieFunc == dieF_camera_die) ) - { + } else if (cg.snap && cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && + (!cg.renderingThirdPerson || g_entities[cg.snap->ps.viewEntity].e_DieFunc == dieF_camera_die)) { // if in entity camera view, use a special FOV - if ( g_entities[cg.snap->ps.viewEntity].inuse && - g_entities[cg.snap->ps.viewEntity].NPC ) - {//FIXME: looks bad when take over a jedi... but never really do that, do we? + if (g_entities[cg.snap->ps.viewEntity].inuse && + g_entities[cg.snap->ps.viewEntity].NPC) { // FIXME: looks bad when take over a jedi... but never really do that, do we? fov_x = g_entities[cg.snap->ps.viewEntity].NPC->stats.hfov; - //sanity-cap? - if ( fov_x > 120 ) - { + // sanity-cap? + if (fov_x > 120) { fov_x = 120; - } - else if ( fov_x < 10 ) - { + } else if (fov_x < 10) { fov_x = 10; } - } - else - { - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + } else { + if (cg.overrides.active & CG_OVERRIDE_FOV) { fov_x = cg.overrides.fov; - } - else - { - fov_x = 120;//FIXME: read from the NPC's fov stats? + } else { + fov_x = 120; // FIXME: read from the NPC's fov stats? } } - } - else if ( (!cg.zoomMode || cg.zoomMode > 2) && (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] )//cg.renderingThirdPerson && + } else if ((!cg.zoomMode || cg.zoomMode > 2) && (cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && + player->client->ps.forcePowerDuration[FP_SPEED]) // cg.renderingThirdPerson && { fov_x = CG_ForceSpeedFOV(); } else { // user selectable - if ( cg.overrides.active & CG_OVERRIDE_FOV ) - { + if (cg.overrides.active & CG_OVERRIDE_FOV) { fov_x = cg.overrides.fov; - } - else - { + } else { fov_x = cg_fov.value; } - if ( fov_x < 1 ) { + if (fov_x < 1) { fov_x = 1; - } else if ( fov_x > 160 ) { + } else if (fov_x > 160) { fov_x = 160; } // Disable zooming when in third person - if ( cg.zoomMode && cg.zoomMode < 3 )//&& !cg.renderingThirdPerson ) // light amp goggles do none of the zoom silliness + if (cg.zoomMode && cg.zoomMode < 3) //&& !cg.renderingThirdPerson ) // light amp goggles do none of the zoom silliness { - if ( !cg.zoomLocked ) - { - if ( cg.zoomMode == 1 ) - { + if (!cg.zoomLocked) { + if (cg.zoomMode == 1) { // binoculars zooming either in or out cg_zoomFov += cg.zoomDir * cg.frametime * 0.05f; - } - else - { + } else { // disruptor zooming in faster cg_zoomFov -= cg.frametime * 0.075f; } // Clamp zoomFov - float actualFOV = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - if ( cg_zoomFov < MAX_ZOOM_FOV ) - { + float actualFOV = (cg.overrides.active & CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + if (cg_zoomFov < MAX_ZOOM_FOV) { cg_zoomFov = MAX_ZOOM_FOV; - } - else if ( cg_zoomFov > actualFOV ) - { + } else if (cg_zoomFov > actualFOV) { cg_zoomFov = actualFOV; - } - else - {//still zooming + } else { // still zooming static int zoomSoundTime = 0; - if ( zoomSoundTime < cg.time ) - { + if (zoomSoundTime < cg.time) { sfxHandle_t snd; - - if ( cg.zoomMode == 1 ) - { + + if (cg.zoomMode == 1) { snd = cgs.media.zoomLoop; - } - else - { + } else { snd = cgs.media.disruptorZoomLoop; } // huh? This could probably just be added as a looping sound?? - cgi_S_StartSound( cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_LOCAL, snd ); - zoomSoundTime = cg.time + 150; + cgi_S_StartSound(cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_LOCAL, snd); + zoomSoundTime = cg.time + 150; } } } fov_x = cg_zoomFov; } else { - f = ( cg.time - cg.zoomTime ) / ZOOM_OUT_TIME; - if ( f <= 1.0 ) { - fov_x = cg_zoomFov + f * ( fov_x - cg_zoomFov ); + f = (cg.time - cg.zoomTime) / ZOOM_OUT_TIME; + if (f <= 1.0) { + fov_x = cg_zoomFov + f * (fov_x - cg_zoomFov); } } } -// g_fov = fov_x; - return ( CG_CalcFOVFromX( fov_x ) ); + // g_fov = fov_x; + return (CG_CalcFOVFromX(fov_x)); } - - /* =============== CG_DamageBlendBlob =============== */ -static void CG_DamageBlendBlob( void ) -{ - int t; - int maxTime; - refEntity_t ent; +static void CG_DamageBlendBlob(void) { + int t; + int maxTime; + refEntity_t ent; - if ( !cg.damageValue ) { + if (!cg.damageValue) { return; } maxTime = DAMAGE_TIME; t = cg.time - cg.damageTime; - if ( t <= 0 || t >= maxTime ) { + if (t <= 0 || t >= maxTime) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; ent.renderfx = RF_FIRST_PERSON; - VectorMA( cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin ); - VectorMA( ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin ); - VectorMA( ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin ); + VectorMA(cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin); + VectorMA(ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin); + VectorMA(ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin); - ent.radius = cg.damageValue * 3 * ( 1.0 - ((float)t / maxTime) ); + ent.radius = cg.damageValue * 3 * (1.0 - ((float)t / maxTime)); ent.customShader = cgs.media.damageBlendBlobShader; - ent.shaderRGBA[0] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[1] = 50 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[2] = 50 * ( 1.0 - ((float)t / maxTime) ); + ent.shaderRGBA[0] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[1] = 50 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[2] = 50 * (1.0 - ((float)t / maxTime)); ent.shaderRGBA[3] = 255; - cgi_R_AddRefEntityToScene( &ent ); + cgi_R_AddRefEntityToScene(&ent); } /* @@ -1508,56 +1348,49 @@ CG_SaberClashFlare extern int g_saberFlashTime; extern vec3_t g_saberFlashPos; extern qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y); -void CG_SaberClashFlare( void ) -{ - int t, maxTime = 150; +void CG_SaberClashFlare(void) { + int t, maxTime = 150; t = cg.time - g_saberFlashTime; - if ( t <= 0 || t >= maxTime ) - { + if (t <= 0 || t >= maxTime) { return; } vec3_t dif; // Don't do clashes for things that are behind us - VectorSubtract( g_saberFlashPos, cg.refdef.vieworg, dif ); + VectorSubtract(g_saberFlashPos, cg.refdef.vieworg, dif); - if ( DotProduct( dif, cg.refdef.viewaxis[0] ) < 0.2 ) - { + if (DotProduct(dif, cg.refdef.viewaxis[0]) < 0.2) { return; } trace_t tr; - CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, g_saberFlashPos, -1, CONTENTS_SOLID ); + CG_Trace(&tr, cg.refdef.vieworg, NULL, NULL, g_saberFlashPos, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f ) - { + if (tr.fraction < 1.0f) { return; } vec3_t color; - int x,y; - float v, len = VectorNormalize( dif ); + int x, y; + float v, len = VectorNormalize(dif); // clamp to a known range - if ( len > 800 ) - { + if (len > 800) { len = 800; } - v = ( 1.0f - ((float)t / maxTime )) * ((1.0f - ( len / 800.0f )) * 2.0f + 0.35f); + v = (1.0f - ((float)t / maxTime)) * ((1.0f - (len / 800.0f)) * 2.0f + 0.35f); - CG_WorldCoordToScreenCoord( g_saberFlashPos, &x, &y ); + CG_WorldCoordToScreenCoord(g_saberFlashPos, &x, &y); - VectorSet( color, 0.8f, 0.8f, 0.8f ); - cgi_R_SetColor( color ); + VectorSet(color, 0.8f, 0.8f, 0.8f); + cgi_R_SetColor(color); - CG_DrawPic( x - ( v * 300 ), y - ( v * 300 ), - v * 600, v * 600, - cgi_R_RegisterShader( "gfx/effects/saberFlare" )); + CG_DrawPic(x - (v * 300), y - (v * 300), v * 600, v * 600, cgi_R_RegisterShader("gfx/effects/saberFlare")); } /* @@ -1567,51 +1400,42 @@ CG_CalcViewValues Sets cg.refdef view values =============== */ -static qboolean CG_CalcViewValues( void ) { - playerState_t *ps; - qboolean viewEntIsCam = qfalse; - //extern vec3_t cgRefdefVieworg; +static qboolean CG_CalcViewValues(void) { + playerState_t *ps; + qboolean viewEntIsCam = qfalse; + // extern vec3_t cgRefdefVieworg; - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); // calculate size of 3D view CG_CalcVrect(); - if( cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - { - if( g_entities[cg.snap->ps.viewEntity].client && g_entities[cg.snap->ps.viewEntity].NPC ) - { + if (cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { + if (g_entities[cg.snap->ps.viewEntity].client && g_entities[cg.snap->ps.viewEntity].NPC) { ps = &g_entities[cg.snap->ps.viewEntity].client->ps; - } - else - { + } else { ps = &cg.predicted_player_state; viewEntIsCam = qtrue; } - } - else - { + } else { ps = &cg.predicted_player_state; } #ifndef FINAL_BUILD - trap_Com_SetOrgAngles(ps->origin,ps->viewangles); + trap_Com_SetOrgAngles(ps->origin, ps->viewangles); #endif // intermission view - if ( ps->pm_type == PM_INTERMISSION ) { - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + if (ps->pm_type == PM_INTERMISSION) { + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); return CG_CalcFov(); } - cg.bobcycle = ( ps->bobCycle & 128 ) >> 7; - cg.bobfracsin = fabs( sin( ( ps->bobCycle & 127 ) / 127.0 * M_PI ) ); - cg.xyspeed = sqrt( ps->velocity[0] * ps->velocity[0] + - ps->velocity[1] * ps->velocity[1] ); - + cg.bobcycle = (ps->bobCycle & 128) >> 7; + cg.bobfracsin = fabs(sin((ps->bobCycle & 127) / 127.0 * M_PI)); + cg.xyspeed = sqrt(ps->velocity[0] * ps->velocity[0] + ps->velocity[1] * ps->velocity[1]); - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in an entity camera view /* if ( g_entities[cg.snap->ps.viewEntity].client && cg.renderingThirdPerson ) { @@ -1619,121 +1443,99 @@ static qboolean CG_CalcViewValues( void ) { } else */ - { - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpOrigin, cg.refdef.vieworg ); - } - VectorCopy( cg_entities[cg.snap->ps.viewEntity].lerpAngles, cg.refdefViewAngles ); - if ( !Q_stricmp( "misc_camera", g_entities[cg.snap->ps.viewEntity].classname ) || g_entities[cg.snap->ps.viewEntity].s.weapon == WP_TURRET ) - { + { VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpOrigin, cg.refdef.vieworg); } + VectorCopy(cg_entities[cg.snap->ps.viewEntity].lerpAngles, cg.refdefViewAngles); + if (!Q_stricmp("misc_camera", g_entities[cg.snap->ps.viewEntity].classname) || g_entities[cg.snap->ps.viewEntity].s.weapon == WP_TURRET) { viewEntIsCam = qtrue; } - } - else if ( cg.renderingThirdPerson && !cg.zoomMode && (cg.overrides.active&CG_OVERRIDE_3RD_PERSON_ENT) ) - {//different center, same angle - VectorCopy( cg_entities[cg.overrides.thirdPersonEntity].lerpOrigin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); - } - else - {//player's center and angles - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdefViewAngles ); + } else if (cg.renderingThirdPerson && !cg.zoomMode && (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ENT)) { // different center, same angle + VectorCopy(cg_entities[cg.overrides.thirdPersonEntity].lerpOrigin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); + } else { // player's center and angles + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdefViewAngles); } // add error decay - if ( cg_errorDecay.value > 0 ) { - int t; - float f; + if (cg_errorDecay.value > 0) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f > 0 && f < 1 ) { - VectorMA( cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg ); + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f > 0 && f < 1) { + VectorMA(cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg); } else { cg.predictedErrorTime = 0; } } - if ( (cg.renderingThirdPerson||cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) - && !cg.zoomMode - && !viewEntIsCam ) - { + if ((cg.renderingThirdPerson || cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) && !cg.zoomMode && !viewEntIsCam) { // back away from character -// if ( cg_thirdPerson.integer == CG_CAM_ABOVE) -// { ` -// CG_OffsetThirdPersonOverheadView(); -// } -// else -// { + // if ( cg_thirdPerson.integer == CG_CAM_ABOVE) + // { ` + // CG_OffsetThirdPersonOverheadView(); + // } + // else + // { // First person saber - if ( !cg.renderingThirdPerson ) - { - if ( cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE ) - { + if (!cg.renderingThirdPerson) { + if (cg.snap->ps.weapon == WP_SABER || cg.snap->ps.weapon == WP_MELEE) { vec3_t dir; - CG_OffsetFirstPersonView( qtrue ); + CG_OffsetFirstPersonView(qtrue); cg.refdef.vieworg[2] += 32; - AngleVectors( cg.refdefViewAngles, dir, NULL, NULL ); - VectorMA( cg.refdef.vieworg, -2, dir, cg.refdef.vieworg ); + AngleVectors(cg.refdefViewAngles, dir, NULL, NULL); + VectorMA(cg.refdef.vieworg, -2, dir, cg.refdef.vieworg); } } CG_OffsetThirdPersonView(); -// } - } - else - { + // } + } else { // offset for local bobbing and kicks - CG_OffsetFirstPersonView( qfalse ); - centity_t *playerCent = &cg_entities[0]; - if ( playerCent && playerCent->gent && playerCent->gent->client ) - { - VectorCopy( cg.refdef.vieworg, playerCent->gent->client->renderInfo.eyePoint ); - VectorCopy( cg.refdefViewAngles, playerCent->gent->client->renderInfo.eyeAngles ); - if ( cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD ) - {//in an entity camera view - if ( cg_entities[cg.snap->ps.viewEntity].gent->client ) - {//looking through a client's eyes - VectorCopy( cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyePoint ); - VectorCopy( cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyeAngles ); - } - else - {//looking through a regular ent's eyes - VectorCopy( cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].lerpOrigin ); - VectorCopy( cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].lerpAngles ); + CG_OffsetFirstPersonView(qfalse); + centity_t *playerCent = &cg_entities[0]; + if (playerCent && playerCent->gent && playerCent->gent->client) { + VectorCopy(cg.refdef.vieworg, playerCent->gent->client->renderInfo.eyePoint); + VectorCopy(cg.refdefViewAngles, playerCent->gent->client->renderInfo.eyeAngles); + if (cg.snap->ps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD) { // in an entity camera view + if (cg_entities[cg.snap->ps.viewEntity].gent->client) { // looking through a client's eyes + VectorCopy(cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyePoint); + VectorCopy(cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].gent->client->renderInfo.eyeAngles); + } else { // looking through a regular ent's eyes + VectorCopy(cg.refdef.vieworg, cg_entities[cg.snap->ps.viewEntity].lerpOrigin); + VectorCopy(cg.refdefViewAngles, cg_entities[cg.snap->ps.viewEntity].lerpAngles); } } - VectorCopy( playerCent->gent->client->renderInfo.eyePoint, playerCent->gent->client->renderInfo.headPoint ); - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) - {//not in entity cam + VectorCopy(playerCent->gent->client->renderInfo.eyePoint, playerCent->gent->client->renderInfo.headPoint); + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { // not in entity cam playerCent->gent->client->renderInfo.headPoint[2] -= 8; } } } - //VectorCopy( cg.refdef.vieworg, cgRefdefVieworg ); - // shake the camera if necessary - CGCam_UpdateSmooth( cg.refdef.vieworg, cg.refdefViewAngles ); - CGCam_UpdateShake( cg.refdef.vieworg, cg.refdefViewAngles ); + // VectorCopy( cg.refdef.vieworg, cgRefdefVieworg ); + // shake the camera if necessary + CGCam_UpdateSmooth(cg.refdef.vieworg, cg.refdefViewAngles); + CGCam_UpdateShake(cg.refdef.vieworg, cg.refdefViewAngles); /* if ( in_camera ) { - Com_Printf( "%s %s\n", vtos(client_camera.origin), vtos(cg.refdef.vieworg) ); + Com_Printf( "%s %s\n", vtos(client_camera.origin), vtos(cg.refdef.vieworg) ); } */ // see if we are drugged by an interrogator. We muck with the angles here, just a bit earlier, we mucked with the FOV - if ( cg.wonkyTime > 0 && cg.wonkyTime > cg.time ) - { + if (cg.wonkyTime > 0 && cg.wonkyTime > cg.time) { float perc = (float)(cg.wonkyTime - cg.time) / 10000.0f; // goes for 10 seconds - cg.refdefViewAngles[ROLL] += ( sin( cg.time * 0.0004f ) * 7.0f * perc ); - cg.refdefViewAngles[PITCH] += ( 26.0f * perc + sin( cg.time * 0.0011f ) * 3.0f * perc ); + cg.refdefViewAngles[ROLL] += (sin(cg.time * 0.0004f) * 7.0f * perc); + cg.refdefViewAngles[PITCH] += (26.0f * perc + sin(cg.time * 0.0011f) * 3.0f * perc); } - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); - if ( cg.hyperspace ) - { + if (cg.hyperspace) { cg.refdef.rdflags |= RDF_NOWORLDMODEL | RDF_HYPERSPACE; } @@ -1741,66 +1543,57 @@ static qboolean CG_CalcViewValues( void ) { return CG_CalcFov(); } - /* ===================== CG_PowerupTimerSounds ===================== */ -static void CG_PowerupTimerSounds( void ) -{ - int i, time; - +static void CG_PowerupTimerSounds(void) { + int i, time; + // powerup timers going away - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) - { + for (i = 0; i < MAX_POWERUPS; i++) { time = cg.snap->ps.powerups[i]; - if ( time > 0 && time < cg.time ) - { + if (time > 0 && time < cg.time) { // add any special powerup expiration sounds here -// switch( i ) -// { -// case PW_WEAPON_OVERCHARGE: -// cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.overchargeEndSound ); -// break; -// } + // switch( i ) + // { + // case PW_WEAPON_OVERCHARGE: + // cgi_S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.overchargeEndSound ); + // break; + // } } } } //---------------------------- -void CG_RunEmplacedWeapon() -{ - gentity_t *player = &g_entities[0], - *gun = player->owner; +void CG_RunEmplacedWeapon() { + gentity_t *player = &g_entities[0], *gun = player->owner; // Override the camera when we are locked onto the gun. - if ( player && gun && ( player->s.eFlags & EF_LOCKED_TO_WEAPON )) - { -// float dist = -1; // default distance behind gun + if (player && gun && (player->s.eFlags & EF_LOCKED_TO_WEAPON)) { + // float dist = -1; // default distance behind gun // don't let the player try and change this cg.renderingThirdPerson = qtrue; -// cg.refdefViewAngles[PITCH] += cg.overrides.thirdPersonPitchOffset? cg.overrides.thirdPersonPitchOffset: cg_thirdPersonPitchOffset.value; -// cg.refdefViewAngles[YAW] += cg.overrides.thirdPersonAngle ? cg.overrides.thirdPersonAngle : cg_thirdPersonAngle.value;; + // cg.refdefViewAngles[PITCH] += cg.overrides.thirdPersonPitchOffset? cg.overrides.thirdPersonPitchOffset: cg_thirdPersonPitchOffset.value; + // cg.refdefViewAngles[YAW] += cg.overrides.thirdPersonAngle ? cg.overrides.thirdPersonAngle : cg_thirdPersonAngle.value;; - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); // Slide in behind the gun. -// if ( gun->delay + 500 > cg.time ) -// { -// dist -= (( gun->delay + 500 ) - cg.time ) * 0.02f; -// } - - VectorCopy( gun->pos2, cg.refdef.vieworg ); - VectorMA( cg.refdef.vieworg, -20.0f, gun->pos3, cg.refdef.vieworg ); - if ( cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) - { - VectorMA( cg.refdef.vieworg, 35.0f, gun->pos4, cg.refdef.vieworg ); + // if ( gun->delay + 500 > cg.time ) + // { + // dist -= (( gun->delay + 500 ) - cg.time ) * 0.02f; + // } + + VectorCopy(gun->pos2, cg.refdef.vieworg); + VectorMA(cg.refdef.vieworg, -20.0f, gun->pos3, cg.refdef.vieworg); + if (cg.snap->ps.viewEntity <= 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD) { + VectorMA(cg.refdef.vieworg, 35.0f, gun->pos4, cg.refdef.vieworg); } - } } @@ -1813,11 +1606,11 @@ CG_DrawActiveFrame Generates and draws a game scene and status information at the given time. ================= */ -extern void CG_BuildSolidList( void ); -void cgi_CM_SnapPVS(vec3_t origin,byte *buffer); -extern vec3_t serverViewOrg; -void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { - qboolean inwater = qfalse; +extern void CG_BuildSolidList(void); +void cgi_CM_SnapPVS(vec3_t origin, byte *buffer); +extern vec3_t serverViewOrg; +void CG_DrawActiveFrame(int serverTime, stereoFrame_t stereoView) { + qboolean inwater = qfalse; cg.time = serverTime; @@ -1826,12 +1619,11 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { // if we are only updating the screen as a loading // pacifier, don't even try to read snapshots - if ( cg.infoScreenText[0] != 0 ) { + if (cg.infoScreenText[0] != 0) { CG_DrawInformation(); return; } - CG_RunLightStyles(); // any looped sounds will be respecified as entities @@ -1847,49 +1639,45 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView ) { CG_ProcessSnapshots(); // if we haven't received any snapshots yet, all // we can draw is the information screen - if ( !cg.snap ) { + if (!cg.snap) { CG_DrawInformation(); return; } // make sure the lagometerSample and frame timing isn't done twice when in stereo - if ( stereoView != STEREO_RIGHT ) { + if (stereoView != STEREO_RIGHT) { cg.frametime = cg.time - cg.oldTime; cg.oldTime = cg.time; } // Make sure the helper has the updated time - theFxHelper.AdjustTime( cg.frametime ); + theFxHelper.AdjustTime(cg.frametime); // let the client system know what our weapon and zoom settings are - //FIXME: should really send forcePowersActive over network onto cg.snap->ps... - float speed = cg.refdef.fov_y / 75.0 * ((cg_entities[0].gent->client->ps.forcePowersActive&(1<ps... + float speed = cg.refdef.fov_y / 75.0 * ((cg_entities[0].gent->client->ps.forcePowersActive & (1 << FP_SPEED)) ? 1.0f : cg_timescale.value); -//FIXME: junk code, BUG:168 + // FIXME: junk code, BUG:168 -static bool wasForceSpeed=false; -bool isForceSpeed=cg_entities[0].gent->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_SPEED) ? true : false; + if (isForceSpeed && !wasForceSpeed) { + CGCam_Smooth(0.75f, 5000); + } + wasForceSpeed = isForceSpeed; -// + // float mPitchOverride = 0.0f; float mYawOverride = 0.0f; - if ( cg.snap->ps.clientNum == 0 ) - {//pointless check, but.. - if ( cg_entities[0].gent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.clientNum == 0) { // pointless check, but.. + if (cg_entities[0].gent->s.eFlags & EF_LOCKED_TO_WEAPON) { speed *= 0.25f; } - if ( cg_entities[0].gent->s.eFlags & EF_IN_ATST ) - { + if (cg_entities[0].gent->s.eFlags & EF_IN_ATST) { mPitchOverride = 0.01f; mYawOverride = 0.0075f; } } - cgi_SetUserCmdValue( cg.weaponSelect, speed, mPitchOverride, mYawOverride ); + cgi_SetUserCmdValue(cg.weaponSelect, speed, mPitchOverride, mYawOverride); // this counter will be bumped for every valid scene we generate cg.clientFrame++; @@ -1898,26 +1686,19 @@ wasForceSpeed=isForceSpeed; CG_PredictPlayerState(); // decide on third person view - cg.renderingThirdPerson = (qboolean)( - cg_thirdPerson.integer || - (cg.snap->ps.stats[STAT_HEALTH] <= 0) || - (g_entities[0].client && - g_entities[0].client->NPC_class == CLASS_ATST)); + cg.renderingThirdPerson = + (qboolean)(cg_thirdPerson.integer || (cg.snap->ps.stats[STAT_HEALTH] <= 0) || (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST)); - if ( cg.zoomMode ) - { + if (cg.zoomMode) { // zoomed characters should never do third person stuff?? cg.renderingThirdPerson = qfalse; } - if ( in_camera ) - { + if (in_camera) { // The camera takes over the view - CGCam_RenderScene(); - } - else - { - //Finish any fading that was happening + CGCam_RenderScene(); + } else { + // Finish any fading that was happening CGCam_UpdateFade(); // build cg.refdef inwater = CG_CalcViewValues(); @@ -1927,39 +1708,33 @@ wasForceSpeed=isForceSpeed; CG_RunEmplacedWeapon(); // first person blend blobs, done after AnglesToAxis - if ( !cg.renderingThirdPerson ) { - CG_DamageBlendBlob(); + if (!cg.renderingThirdPerson) { + CG_DamageBlendBlob(); } // build the render lists - if ( !cg.hyperspace ) { - CG_AddPacketEntities(); // adter calcViewValues, so predicted player state is correct + if (!cg.hyperspace) { + CG_AddPacketEntities(); // adter calcViewValues, so predicted player state is correct CG_AddMarks(); CG_AddLocalEntities(); } - //check for opaque water - if ( 1 ) - { - vec3_t camTest; - VectorCopy( cg.refdef.vieworg, camTest ); + // check for opaque water + if (1) { + vec3_t camTest; + VectorCopy(cg.refdef.vieworg, camTest); camTest[2] += 6; - if ( !(CG_PointContents( camTest, 0 )&CONTENTS_SOLID) && !gi.inPVS( cg.refdef.vieworg, camTest ) ) - {//crossed visible line into another room + if (!(CG_PointContents(camTest, 0) & CONTENTS_SOLID) && !gi.inPVS(cg.refdef.vieworg, camTest)) { // crossed visible line into another room cg.refdef.vieworg[2] -= 6; - //cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); - } - else - { - VectorCopy( cg.refdef.vieworg, camTest ); + // cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); + } else { + VectorCopy(cg.refdef.vieworg, camTest); camTest[2] -= 6; - if ( !(CG_PointContents( camTest, 0 )&CONTENTS_SOLID) && !gi.inPVS( cg.refdef.vieworg, camTest ) ) - { + if (!(CG_PointContents(camTest, 0) & CONTENTS_SOLID) && !gi.inPVS(cg.refdef.vieworg, camTest)) { cg.refdef.vieworg[2] += 6; - //cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); - } - else //if ( inwater ) - {//extra-special hack... sometimes when crouched in water with first person lightsaber, your PVS is wrong??? + // cgi_CM_SnapPVS(cg.refdef.vieworg,cg.snap->areamask); + } else // if ( inwater ) + { // extra-special hack... sometimes when crouched in water with first person lightsaber, your PVS is wrong??? /* if ( !cg.renderingThirdPerson && (cg.snap->ps.weapon == WP_SABER||cg.snap->ps.weapon == WP_MELEE) ) {//pseudo first-person for saber and fists @@ -1969,60 +1744,52 @@ wasForceSpeed=isForceSpeed; } } } - //FIXME: first person crouch-uncrouch STILL FUCKS UP THE AREAMASK!!! - //if ( !VectorCompare2( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) && !gi.inPVS( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) ) - {//actual view org and server's view org don't match and aren't same PVS, rebuild the areamask - //Com_Printf( S_COLOR_RED"%s != %s\n", vtos(cg.refdef.vieworg), vtos(cg.snap->ps.serverViewOrg) ); - cgi_CM_SnapPVS( cg.refdef.vieworg, cg.snap->areamask ); + // FIXME: first person crouch-uncrouch STILL FUCKS UP THE AREAMASK!!! + // if ( !VectorCompare2( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) && !gi.inPVS( cg.refdef.vieworg, cg.snap->ps.serverViewOrg ) ) + { // actual view org and server's view org don't match and aren't same PVS, rebuild the areamask + // Com_Printf( S_COLOR_RED"%s != %s\n", vtos(cg.refdef.vieworg), vtos(cg.snap->ps.serverViewOrg) ); + cgi_CM_SnapPVS(cg.refdef.vieworg, cg.snap->areamask); } // Don't draw the in-view weapon when in camera mode - if ( !in_camera - && !cg_pano.integer - && cg.snap->ps.weapon != WP_SABER - && ( cg.snap->ps.viewEntity == 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD ) ) - { - CG_AddViewWeapon( &cg.predicted_player_state ); - } - else if( cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && - g_entities[cg.snap->ps.viewEntity].client) - { - CG_AddViewWeapon( &g_entities[cg.snap->ps.viewEntity ].client->ps ); // HAX - because I wanted to --eez + if (!in_camera && !cg_pano.integer && cg.snap->ps.weapon != WP_SABER && (cg.snap->ps.viewEntity == 0 || cg.snap->ps.viewEntity >= ENTITYNUM_WORLD)) { + CG_AddViewWeapon(&cg.predicted_player_state); + } else if (cg.snap->ps.viewEntity != 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD && g_entities[cg.snap->ps.viewEntity].client) { + CG_AddViewWeapon(&g_entities[cg.snap->ps.viewEntity].client->ps); // HAX - because I wanted to --eez } - if ( !cg.hyperspace ) - { - //Add all effects - theFxScheduler.AddScheduledEffects( ); + if (!cg.hyperspace) { + // Add all effects + theFxScheduler.AddScheduledEffects(); } // finish up the rest of the refdef - if ( cg.testModelEntity.hModel ) { + if (cg.testModelEntity.hModel) { CG_AddTestModel(); } - + cg.refdef.time = cg.time; - memcpy( cg.refdef.areamask, cg.snap->areamask, sizeof( cg.refdef.areamask ) ); + memcpy(cg.refdef.areamask, cg.snap->areamask, sizeof(cg.refdef.areamask)); // update audio positions - //This is done from the vieworg to get origin for non-attenuated sounds - cgi_S_UpdateAmbientSet( CG_ConfigString( CS_AMBIENT_SET ), cg.refdef.vieworg ); - //NOTE: if we want to make you be able to hear far away sounds with electrobinoculars, add the hacked-in positional offset here (base on fov) - cgi_S_Respatialize( cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater ); + // This is done from the vieworg to get origin for non-attenuated sounds + cgi_S_UpdateAmbientSet(CG_ConfigString(CS_AMBIENT_SET), cg.refdef.vieworg); + // NOTE: if we want to make you be able to hear far away sounds with electrobinoculars, add the hacked-in positional offset here (base on fov) + cgi_S_Respatialize(cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater); // warning sounds when powerup is wearing off CG_PowerupTimerSounds(); - if ( cg_pano.integer ) { // let's grab a panorama! - cg.levelShot = qtrue; //hide the 2d - VectorClear(cg.refdefViewAngles); - cg.refdefViewAngles[YAW] = -360 * cg_pano.integer/cg_panoNumShots.integer; //choose angle - AnglesToAxis( cg.refdefViewAngles, cg.refdef.viewaxis ); - CG_DrawActive( stereoView ); + if (cg_pano.integer) { // let's grab a panorama! + cg.levelShot = qtrue; // hide the 2d + VectorClear(cg.refdefViewAngles); + cg.refdefViewAngles[YAW] = -360 * cg_pano.integer / cg_panoNumShots.integer; // choose angle + AnglesToAxis(cg.refdefViewAngles, cg.refdef.viewaxis); + CG_DrawActive(stereoView); cg.levelShot = qfalse; - } else { + } else { // actually issue the rendering calls - CG_DrawActive( stereoView ); + CG_DrawActive(stereoView); } /* if ( in_camera && !cg_skippingcin.integer ) @@ -2031,4 +1798,3 @@ wasForceSpeed=isForceSpeed; } */ } - diff --git a/codeJK2/cgame/cg_weapons.cpp b/codeJK2/cgame/cg_weapons.cpp index 6bfbbd5a85..e999ec65b8 100644 --- a/codeJK2/cgame/cg_weapons.cpp +++ b/codeJK2/cgame/cg_weapons.cpp @@ -28,14 +28,12 @@ along with this program; if not, see . #include "../game/g_local.h" #include "../game/anims.h" -extern void CG_LightningBolt( centity_t *cent, vec3_t origin ); +extern void CG_LightningBolt(centity_t *cent, vec3_t origin); -#define PHASER_HOLDFRAME 2 -int cgi_UI_GetMenuInfo(char *menuFile,int *x,int *y); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, - const char *psText, int iFontHandle, float fScale, - const vec4_t v4Color); +#define PHASER_HOLDFRAME 2 +int cgi_UI_GetMenuInfo(char *menuFile, int *x, int *y); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +const char *CG_DisplayBoxedText(int iBoxX, int iBoxY, int iBoxWidth, int iBoxHeight, const char *psText, int iFontHandle, float fScale, const vec4_t v4Color); /* ================= @@ -44,490 +42,468 @@ CG_RegisterWeapon The server says this item is used on this level ================= */ -void CG_RegisterWeapon( int weaponNum ) { - weaponInfo_t *weaponInfo; - gitem_t *item, *ammo; - char path[MAX_QPATH]; - vec3_t mins, maxs; - int i; +void CG_RegisterWeapon(int weaponNum) { + weaponInfo_t *weaponInfo; + gitem_t *item, *ammo; + char path[MAX_QPATH]; + vec3_t mins, maxs; + int i; weaponInfo = &cg_weapons[weaponNum]; // error checking - if ( weaponNum == 0 ) { + if (weaponNum == 0) { return; } - if ( weaponNum >= WP_NUM_WEAPONS ) { + if (weaponNum >= WP_NUM_WEAPONS) { return; } - if ( weaponInfo->registered ) { + if (weaponInfo->registered) { return; } // clear out the memory we use - memset( weaponInfo, 0, sizeof( *weaponInfo ) ); + memset(weaponInfo, 0, sizeof(*weaponInfo)); weaponInfo->registered = qtrue; // find the weapon in the item list - for ( item = bg_itemlist + 1 ; item->classname ; item++ ) { - if ( item->giType == IT_WEAPON && item->giTag == weaponNum ) { + for (item = bg_itemlist + 1; item->classname; item++) { + if (item->giType == IT_WEAPON && item->giTag == weaponNum) { weaponInfo->item = item; break; } } // if we couldn't find which weapon this is, give us an error - if ( !item->classname ) { - CG_Error( "Couldn't find item for weapon %s\nNeed to update Items.dat!", weaponData[weaponNum].classname); + if (!item->classname) { + CG_Error("Couldn't find item for weapon %s\nNeed to update Items.dat!", weaponData[weaponNum].classname); } - CG_RegisterItemVisuals( item - bg_itemlist ); + CG_RegisterItemVisuals(item - bg_itemlist); // set up in view weapon model - weaponInfo->weaponModel = cgi_R_RegisterModel( weaponData[weaponNum].weaponMdl ); - {//in case the weaponmodel isn't _w, precache the _w.glm + weaponInfo->weaponModel = cgi_R_RegisterModel(weaponData[weaponNum].weaponMdl); + { // in case the weaponmodel isn't _w, precache the _w.glm char weaponModel[64]; - Q_strncpyz (weaponModel, weaponData[weaponNum].weaponMdl, sizeof(weaponModel)); - if (char *spot = strstr(weaponModel, ".md3") ) - { + Q_strncpyz(weaponModel, weaponData[weaponNum].weaponMdl, sizeof(weaponModel)); + if (char *spot = strstr(weaponModel, ".md3")) { *spot = 0; - spot = strstr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on - if (!spot) - { - Q_strcat (weaponModel, sizeof(weaponModel), "_w"); + spot = strstr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on + if (!spot) { + Q_strcat(weaponModel, sizeof(weaponModel), "_w"); } - Q_strcat (weaponModel, sizeof(weaponModel), ".glm"); //and change to ghoul2 + Q_strcat(weaponModel, sizeof(weaponModel), ".glm"); // and change to ghoul2 } - gi.G2API_PrecacheGhoul2Model( weaponModel ); // correct way is item->world_model + gi.G2API_PrecacheGhoul2Model(weaponModel); // correct way is item->world_model } - if ( weaponInfo->weaponModel == NULL_HANDLE ) - { - CG_Error( "Couldn't find weapon model %s\n", weaponData[weaponNum].classname); + if (weaponInfo->weaponModel == NULL_HANDLE) { + CG_Error("Couldn't find weapon model %s\n", weaponData[weaponNum].classname); return; } // calc midpoint for rotation - cgi_R_ModelBounds( weaponInfo->weaponModel, mins, maxs ); - for ( i = 0 ; i < 3 ; i++ ) { - weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * ( maxs[i] - mins[i] ); + cgi_R_ModelBounds(weaponInfo->weaponModel, mins, maxs); + for (i = 0; i < 3; i++) { + weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * (maxs[i] - mins[i]); } // setup the shader we will use for the icon - if (weaponData[weaponNum].weaponIcon[0]) - { - weaponInfo->weaponIcon = cgi_R_RegisterShaderNoMip( weaponData[weaponNum].weaponIcon); - weaponInfo->weaponIconNoAmmo = cgi_R_RegisterShaderNoMip( va("%s_na",weaponData[weaponNum].weaponIcon)); + if (weaponData[weaponNum].weaponIcon[0]) { + weaponInfo->weaponIcon = cgi_R_RegisterShaderNoMip(weaponData[weaponNum].weaponIcon); + weaponInfo->weaponIconNoAmmo = cgi_R_RegisterShaderNoMip(va("%s_na", weaponData[weaponNum].weaponIcon)); } - for ( ammo = bg_itemlist + 1 ; ammo->classname ; ammo++ ) { - if ( ammo->giType == IT_AMMO && ammo->giTag == weaponData[weaponNum].ammoIndex) { + for (ammo = bg_itemlist + 1; ammo->classname; ammo++) { + if (ammo->giType == IT_AMMO && ammo->giTag == weaponData[weaponNum].ammoIndex) { break; } } - if ( ammo->classname && ammo->world_model ) { - weaponInfo->ammoModel = cgi_R_RegisterModel( ammo->world_model ); + if (ammo->classname && ammo->world_model) { + weaponInfo->ammoModel = cgi_R_RegisterModel(ammo->world_model); } - for (i=0; i< weaponData[weaponNum].numBarrels; i++) { - Q_strncpyz( path, weaponData[weaponNum].weaponMdl, sizeof(path) ); - COM_StripExtension( path, path, sizeof(path) ); - if (i) - { - //char crap[50]; - //Com_sprintf(crap, sizeof(crap), "_barrel%d.md3", i+1 ); - //strcat ( path, crap ); - Q_strcat( path, sizeof(path), va("_barrel%d.md3", i+1) ); - } - else - Q_strcat( path, sizeof(path), "_barrel.md3" ); - weaponInfo->barrelModel[i] = cgi_R_RegisterModel( path ); + for (i = 0; i < weaponData[weaponNum].numBarrels; i++) { + Q_strncpyz(path, weaponData[weaponNum].weaponMdl, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + if (i) { + // char crap[50]; + // Com_sprintf(crap, sizeof(crap), "_barrel%d.md3", i+1 ); + // strcat ( path, crap ); + Q_strcat(path, sizeof(path), va("_barrel%d.md3", i + 1)); + } else + Q_strcat(path, sizeof(path), "_barrel.md3"); + weaponInfo->barrelModel[i] = cgi_R_RegisterModel(path); } - // set up the world model for the weapon - weaponInfo->weaponWorldModel = cgi_R_RegisterModel( item->world_model ); - if ( !weaponInfo->weaponWorldModel) { + weaponInfo->weaponWorldModel = cgi_R_RegisterModel(item->world_model); + if (!weaponInfo->weaponWorldModel) { weaponInfo->weaponWorldModel = weaponInfo->weaponModel; } // set up the hand that holds the in view weapon - assuming we have one - Q_strncpyz( path, weaponData[weaponNum].weaponMdl, sizeof(path) ); - COM_StripExtension( path, path, sizeof(path) ); - Q_strcat( path, sizeof(path), "_hand.md3" ); - weaponInfo->handsModel = cgi_R_RegisterModel( path ); + Q_strncpyz(path, weaponData[weaponNum].weaponMdl, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + Q_strcat(path, sizeof(path), "_hand.md3"); + weaponInfo->handsModel = cgi_R_RegisterModel(path); - if ( !weaponInfo->handsModel ) { - weaponInfo->handsModel = cgi_R_RegisterModel( "models/weapons2/briar_pistol/briar_pistol_hand.md3" ); + if (!weaponInfo->handsModel) { + weaponInfo->handsModel = cgi_R_RegisterModel("models/weapons2/briar_pistol/briar_pistol_hand.md3"); } // register the sounds for the weapon if (weaponData[weaponNum].firingSnd[0]) { - weaponInfo->firingSound = cgi_S_RegisterSound( weaponData[weaponNum].firingSnd ); + weaponInfo->firingSound = cgi_S_RegisterSound(weaponData[weaponNum].firingSnd); } if (weaponData[weaponNum].altFiringSnd[0]) { - weaponInfo->altFiringSound = cgi_S_RegisterSound( weaponData[weaponNum].altFiringSnd ); + weaponInfo->altFiringSound = cgi_S_RegisterSound(weaponData[weaponNum].altFiringSnd); } if (weaponData[weaponNum].stopSnd[0]) { - weaponInfo->stopSound = cgi_S_RegisterSound( weaponData[weaponNum].stopSnd ); + weaponInfo->stopSound = cgi_S_RegisterSound(weaponData[weaponNum].stopSnd); } if (weaponData[weaponNum].chargeSnd[0]) { - weaponInfo->chargeSound = cgi_S_RegisterSound( weaponData[weaponNum].chargeSnd ); + weaponInfo->chargeSound = cgi_S_RegisterSound(weaponData[weaponNum].chargeSnd); } if (weaponData[weaponNum].altChargeSnd[0]) { - weaponInfo->altChargeSound = cgi_S_RegisterSound( weaponData[weaponNum].altChargeSnd ); + weaponInfo->altChargeSound = cgi_S_RegisterSound(weaponData[weaponNum].altChargeSnd); } if (weaponData[weaponNum].selectSnd[0]) { - weaponInfo->selectSound = cgi_S_RegisterSound( weaponData[weaponNum].selectSnd ); + weaponInfo->selectSound = cgi_S_RegisterSound(weaponData[weaponNum].selectSnd); } // give us missile models if we should - if (weaponData[weaponNum].missileMdl[0]) { - weaponInfo->missileModel = cgi_R_RegisterModel(weaponData[weaponNum].missileMdl ); + if (weaponData[weaponNum].missileMdl[0]) { + weaponInfo->missileModel = cgi_R_RegisterModel(weaponData[weaponNum].missileMdl); } - if (weaponData[weaponNum].alt_missileMdl[0]) { - weaponInfo->alt_missileModel = cgi_R_RegisterModel(weaponData[weaponNum].alt_missileMdl ); + if (weaponData[weaponNum].alt_missileMdl[0]) { + weaponInfo->alt_missileModel = cgi_R_RegisterModel(weaponData[weaponNum].alt_missileMdl); } if (weaponData[weaponNum].missileSound[0]) { - weaponInfo->missileSound = cgi_S_RegisterSound( weaponData[weaponNum].missileSound ); + weaponInfo->missileSound = cgi_S_RegisterSound(weaponData[weaponNum].missileSound); } if (weaponData[weaponNum].alt_missileSound[0]) { - weaponInfo->alt_missileSound = cgi_S_RegisterSound( weaponData[weaponNum].alt_missileSound ); + weaponInfo->alt_missileSound = cgi_S_RegisterSound(weaponData[weaponNum].alt_missileSound); } if (weaponData[weaponNum].missileHitSound[0]) { - weaponInfo->missileHitSound = cgi_S_RegisterSound( weaponData[weaponNum].missileHitSound ); + weaponInfo->missileHitSound = cgi_S_RegisterSound(weaponData[weaponNum].missileHitSound); } if (weaponData[weaponNum].altmissileHitSound[0]) { - weaponInfo->altmissileHitSound = cgi_S_RegisterSound( weaponData[weaponNum].altmissileHitSound ); + weaponInfo->altmissileHitSound = cgi_S_RegisterSound(weaponData[weaponNum].altmissileHitSound); } - if ( weaponData[weaponNum].mMuzzleEffect[0] ) - { - weaponData[weaponNum].mMuzzleEffectID = theFxScheduler.RegisterEffect( weaponData[weaponNum].mMuzzleEffect ); + if (weaponData[weaponNum].mMuzzleEffect[0]) { + weaponData[weaponNum].mMuzzleEffectID = theFxScheduler.RegisterEffect(weaponData[weaponNum].mMuzzleEffect); } - if ( weaponData[weaponNum].mAltMuzzleEffect[0] ) - { - weaponData[weaponNum].mAltMuzzleEffectID = theFxScheduler.RegisterEffect( weaponData[weaponNum].mAltMuzzleEffect ); + if (weaponData[weaponNum].mAltMuzzleEffect[0]) { + weaponData[weaponNum].mAltMuzzleEffectID = theFxScheduler.RegisterEffect(weaponData[weaponNum].mAltMuzzleEffect); } - //fixme: don't really need to copy these, should just use directly - // give ourselves the functions if we can - if (weaponData[weaponNum].func) - { - weaponInfo->missileTrailFunc = (void (QDECL *)(struct centity_s *,const struct weaponInfo_s *))weaponData[weaponNum].func; + // fixme: don't really need to copy these, should just use directly + // give ourselves the functions if we can + if (weaponData[weaponNum].func) { + weaponInfo->missileTrailFunc = (void(QDECL *)(struct centity_s *, const struct weaponInfo_s *))weaponData[weaponNum].func; } - if (weaponData[weaponNum].altfunc) - { - weaponInfo->alt_missileTrailFunc = (void (QDECL *)(struct centity_s *,const struct weaponInfo_s *))weaponData[weaponNum].altfunc; + if (weaponData[weaponNum].altfunc) { + weaponInfo->alt_missileTrailFunc = (void(QDECL *)(struct centity_s *, const struct weaponInfo_s *))weaponData[weaponNum].altfunc; } - switch ( weaponNum ) //extra client only stuff + switch (weaponNum) // extra client only stuff { case WP_SABER: - //saber/force FX - theFxScheduler.RegisterEffect( "spark" ); - theFxScheduler.RegisterEffect( "blood_sparks" ); - theFxScheduler.RegisterEffect( "force_touch" ); - theFxScheduler.RegisterEffect( "saber_block" ); - theFxScheduler.RegisterEffect( "saber_cut" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); - theFxScheduler.RegisterEffect( "saber/fizz" ); - theFxScheduler.RegisterEffect( "saber/boil" ); - - cgs.effects.forceHeal = theFxScheduler.RegisterEffect( "force/heal" ); - cgs.effects.forceInvincibility = theFxScheduler.RegisterEffect( "force/invin" ); - cgs.effects.forceConfusion = theFxScheduler.RegisterEffect( "force/confusion" ); - cgs.effects.forceLightning = theFxScheduler.RegisterEffect( "force/lightning" ); - cgs.effects.forceLightningWide = theFxScheduler.RegisterEffect( "force/lightningwide" ); - - cgs.media.HUDSaberStyleFast = cgi_R_RegisterShader( "gfx/hud/saber_stylesFast" ); - cgs.media.HUDSaberStyleMed = cgi_R_RegisterShader( "gfx/hud/saber_stylesMed" ); - cgs.media.HUDSaberStyleStrong = cgi_R_RegisterShader( "gfx/hud/saber_stylesStrong" ); - - //saber sounds - cgi_S_RegisterSound( "sound/weapons/saber/saberon.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_on.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberonquick.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberoff.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/enemy_saber_off.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberbounce%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhit%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhitwall%d.wav", i ) ); - } - for ( i = 1; i < 10; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberblock%d.wav", i ) ); - } - for ( i = 1; i < 6; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhum%d.wav", i ) ); - } - for ( i = 1; i < 10; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberhup%d.wav", i ) ); - } - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/saberspin%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/saber/saber_catch.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/bounce%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/saber/hitwater.wav" ); - cgi_S_RegisterSound( "sound/weapons/saber/boiling.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/saber/rainfizz%d.wav", i ) ); - } - - //force sounds - cgi_S_RegisterSound( "sound/weapons/force/heal.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/speed.mp3" ); - cgi_S_RegisterSound( "sound/weapons/force/speedloop.mp3" ); - for ( i = 1; i < 5; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d.mp3", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/force/lightning.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/lightning2.wav" ); - for ( i = 1; i < 4; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/lightninghit%d.wav", i ) ); - } - cgi_S_RegisterSound( "sound/weapons/force/push.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/pull.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/jump.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/jumpbuild.wav" ); - cgi_S_RegisterSound( "sound/weapons/force/grip.mp3" ); - - //saber graphics - cgs.media.saberBlurShader = cgi_R_RegisterShader("gfx/effects/sabers/saberBlur"); - cgs.media.yellowDroppedSaberShader = cgi_R_RegisterShader("gfx/effects/yellow_glow"); - cgi_R_RegisterShader( "gfx/effects/saberDamageGlow" ); - cgi_R_RegisterShader( "gfx/effects/solidWhite_cull" ); - cgi_R_RegisterShader( "gfx/effects/forcePush" ); - cgi_R_RegisterShader( "gfx/effects/saberFlare" ); - cgs.media.redSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/red_glow" ); - cgs.media.redSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/red_line" ); - cgs.media.orangeSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/orange_glow" ); - cgs.media.orangeSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/orange_line" ); - cgs.media.yellowSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/yellow_glow" ); - cgs.media.yellowSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/yellow_line" ); - cgs.media.greenSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/green_glow" ); - cgs.media.greenSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/green_line" ); - cgs.media.blueSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/blue_glow" ); - cgs.media.blueSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/blue_line" ); - cgs.media.purpleSaberGlowShader = cgi_R_RegisterShader( "gfx/effects/sabers/purple_glow" ); - cgs.media.purpleSaberCoreShader = cgi_R_RegisterShader( "gfx/effects/sabers/purple_line" ); - - cgs.media.forceCoronaShader = cgi_R_RegisterShaderNoMip( "gfx/hud/force_swirl" ); + // saber/force FX + theFxScheduler.RegisterEffect("spark"); + theFxScheduler.RegisterEffect("blood_sparks"); + theFxScheduler.RegisterEffect("force_touch"); + theFxScheduler.RegisterEffect("saber_block"); + theFxScheduler.RegisterEffect("saber_cut"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); + theFxScheduler.RegisterEffect("saber/fizz"); + theFxScheduler.RegisterEffect("saber/boil"); + + cgs.effects.forceHeal = theFxScheduler.RegisterEffect("force/heal"); + cgs.effects.forceInvincibility = theFxScheduler.RegisterEffect("force/invin"); + cgs.effects.forceConfusion = theFxScheduler.RegisterEffect("force/confusion"); + cgs.effects.forceLightning = theFxScheduler.RegisterEffect("force/lightning"); + cgs.effects.forceLightningWide = theFxScheduler.RegisterEffect("force/lightningwide"); + + cgs.media.HUDSaberStyleFast = cgi_R_RegisterShader("gfx/hud/saber_stylesFast"); + cgs.media.HUDSaberStyleMed = cgi_R_RegisterShader("gfx/hud/saber_stylesMed"); + cgs.media.HUDSaberStyleStrong = cgi_R_RegisterShader("gfx/hud/saber_stylesStrong"); + + // saber sounds + cgi_S_RegisterSound("sound/weapons/saber/saberon.wav"); + cgi_S_RegisterSound("sound/weapons/saber/enemy_saber_on.wav"); + cgi_S_RegisterSound("sound/weapons/saber/saberonquick.wav"); + cgi_S_RegisterSound("sound/weapons/saber/saberoff.wav"); + cgi_S_RegisterSound("sound/weapons/saber/enemy_saber_off.wav"); + cgi_S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); + cgi_S_RegisterSound("sound/weapons/saber/saberoffquick.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberbounce%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhit%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhitwall%d.wav", i)); + } + for (i = 1; i < 10; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberblock%d.wav", i)); + } + for (i = 1; i < 6; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhum%d.wav", i)); + } + for (i = 1; i < 10; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberhup%d.wav", i)); + } + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/saberspin%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/saber/saber_catch.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/bounce%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/saber/hitwater.wav"); + cgi_S_RegisterSound("sound/weapons/saber/boiling.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/saber/rainfizz%d.wav", i)); + } + + // force sounds + cgi_S_RegisterSound("sound/weapons/force/heal.mp3"); + cgi_S_RegisterSound("sound/weapons/force/speed.mp3"); + cgi_S_RegisterSound("sound/weapons/force/speedloop.mp3"); + for (i = 1; i < 5; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/heal%d.mp3", i)); + } + cgi_S_RegisterSound("sound/weapons/force/lightning.wav"); + cgi_S_RegisterSound("sound/weapons/force/lightning2.wav"); + for (i = 1; i < 4; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/lightninghit%d.wav", i)); + } + cgi_S_RegisterSound("sound/weapons/force/push.wav"); + cgi_S_RegisterSound("sound/weapons/force/pull.wav"); + cgi_S_RegisterSound("sound/weapons/force/jump.wav"); + cgi_S_RegisterSound("sound/weapons/force/jumpbuild.wav"); + cgi_S_RegisterSound("sound/weapons/force/grip.mp3"); + + // saber graphics + cgs.media.saberBlurShader = cgi_R_RegisterShader("gfx/effects/sabers/saberBlur"); + cgs.media.yellowDroppedSaberShader = cgi_R_RegisterShader("gfx/effects/yellow_glow"); + cgi_R_RegisterShader("gfx/effects/saberDamageGlow"); + cgi_R_RegisterShader("gfx/effects/solidWhite_cull"); + cgi_R_RegisterShader("gfx/effects/forcePush"); + cgi_R_RegisterShader("gfx/effects/saberFlare"); + cgs.media.redSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/red_glow"); + cgs.media.redSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/red_line"); + cgs.media.orangeSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/orange_glow"); + cgs.media.orangeSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/orange_line"); + cgs.media.yellowSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/yellow_glow"); + cgs.media.yellowSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/yellow_line"); + cgs.media.greenSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/green_glow"); + cgs.media.greenSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/green_line"); + cgs.media.blueSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/blue_glow"); + cgs.media.blueSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/blue_line"); + cgs.media.purpleSaberGlowShader = cgi_R_RegisterShader("gfx/effects/sabers/purple_glow"); + cgs.media.purpleSaberCoreShader = cgi_R_RegisterShader("gfx/effects/sabers/purple_line"); + + cgs.media.forceCoronaShader = cgi_R_RegisterShaderNoMip("gfx/hud/force_swirl"); break; case WP_BRYAR_PISTOL: - cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect( "bryar/shot" ); - theFxScheduler.RegisterEffect( "bryar/NPCshot" ); - cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect( "bryar/crackleShot" ); - cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect( "bryar/wall_impact" ); - cgs.effects.bryarWallImpactEffect2 = theFxScheduler.RegisterEffect( "bryar/wall_impact2" ); - cgs.effects.bryarWallImpactEffect3 = theFxScheduler.RegisterEffect( "bryar/wall_impact3" ); - cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect( "bryar/flesh_impact" ); + cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect("bryar/shot"); + theFxScheduler.RegisterEffect("bryar/NPCshot"); + cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect("bryar/crackleShot"); + cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect("bryar/wall_impact"); + cgs.effects.bryarWallImpactEffect2 = theFxScheduler.RegisterEffect("bryar/wall_impact2"); + cgs.effects.bryarWallImpactEffect3 = theFxScheduler.RegisterEffect("bryar/wall_impact3"); + cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect("bryar/flesh_impact"); // Note....these are temp shared effects - theFxScheduler.RegisterEffect( "blaster/deflect" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); // note: this will be called game side + theFxScheduler.RegisterEffect("blaster/deflect"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); // note: this will be called game side break; case WP_BLASTER: - cgs.effects.blasterShotEffect = theFxScheduler.RegisterEffect( "blaster/shot" ); - theFxScheduler.RegisterEffect( "blaster/NPCshot" ); -// cgs.effects.blasterOverchargeEffect = theFxScheduler.RegisterEffect( "blaster/overcharge" ); - cgs.effects.blasterWallImpactEffect = theFxScheduler.RegisterEffect( "blaster/wall_impact" ); - cgs.effects.blasterFleshImpactEffect = theFxScheduler.RegisterEffect( "blaster/flesh_impact" ); - theFxScheduler.RegisterEffect( "blaster/deflect" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); // note: this will be called game side + cgs.effects.blasterShotEffect = theFxScheduler.RegisterEffect("blaster/shot"); + theFxScheduler.RegisterEffect("blaster/NPCshot"); + // cgs.effects.blasterOverchargeEffect = theFxScheduler.RegisterEffect( "blaster/overcharge" ); + cgs.effects.blasterWallImpactEffect = theFxScheduler.RegisterEffect("blaster/wall_impact"); + cgs.effects.blasterFleshImpactEffect = theFxScheduler.RegisterEffect("blaster/flesh_impact"); + theFxScheduler.RegisterEffect("blaster/deflect"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); // note: this will be called game side break; case WP_DISRUPTOR: - theFxScheduler.RegisterEffect( "disruptor/wall_impact" ); - theFxScheduler.RegisterEffect( "disruptor/flesh_impact" ); - theFxScheduler.RegisterEffect( "disruptor/alt_miss" ); - theFxScheduler.RegisterEffect( "disruptor/alt_hit" ); - theFxScheduler.RegisterEffect( "disruptor/line_cap" ); - theFxScheduler.RegisterEffect( "disruptor/death_smoke" ); + theFxScheduler.RegisterEffect("disruptor/wall_impact"); + theFxScheduler.RegisterEffect("disruptor/flesh_impact"); + theFxScheduler.RegisterEffect("disruptor/alt_miss"); + theFxScheduler.RegisterEffect("disruptor/alt_hit"); + theFxScheduler.RegisterEffect("disruptor/line_cap"); + theFxScheduler.RegisterEffect("disruptor/death_smoke"); - cgi_R_RegisterShader( "gfx/effects/redLine" ); - cgi_R_RegisterShader( "gfx/misc/whiteline2" ); - cgi_R_RegisterShader( "gfx/effects/smokeTrail" ); - cgi_R_RegisterShader( "gfx/effects/burn" ); + cgi_R_RegisterShader("gfx/effects/redLine"); + cgi_R_RegisterShader("gfx/misc/whiteline2"); + cgi_R_RegisterShader("gfx/effects/smokeTrail"); + cgi_R_RegisterShader("gfx/effects/burn"); - cgi_R_RegisterShaderNoMip( "gfx/2d/crop_charge" ); + cgi_R_RegisterShaderNoMip("gfx/2d/crop_charge"); // zoom sounds - cgi_S_RegisterSound( "sound/weapons/disruptor/zoomstart.wav" ); - cgi_S_RegisterSound( "sound/weapons/disruptor/zoomend.wav" ); - cgs.media.disruptorZoomLoop = cgi_S_RegisterSound( "sound/weapons/disruptor/zoomloop.wav" ); + cgi_S_RegisterSound("sound/weapons/disruptor/zoomstart.wav"); + cgi_S_RegisterSound("sound/weapons/disruptor/zoomend.wav"); + cgs.media.disruptorZoomLoop = cgi_S_RegisterSound("sound/weapons/disruptor/zoomloop.wav"); // Disruptor gun zoom interface - cgs.media.disruptorMask = cgi_R_RegisterShader( "gfx/2d/cropCircle2"); - cgs.media.disruptorInsert = cgi_R_RegisterShader( "gfx/2d/cropCircle"); - cgs.media.disruptorLight = cgi_R_RegisterShader( "gfx/2d/cropCircleGlow" ); - cgs.media.disruptorInsertTick = cgi_R_RegisterShader( "gfx/2d/insertTick" ); + cgs.media.disruptorMask = cgi_R_RegisterShader("gfx/2d/cropCircle2"); + cgs.media.disruptorInsert = cgi_R_RegisterShader("gfx/2d/cropCircle"); + cgs.media.disruptorLight = cgi_R_RegisterShader("gfx/2d/cropCircleGlow"); + cgs.media.disruptorInsertTick = cgi_R_RegisterShader("gfx/2d/insertTick"); break; case WP_BOWCASTER: - cgs.effects.bowcasterShotEffect = theFxScheduler.RegisterEffect( "bowcaster/shot" ); - cgs.effects.bowcasterBounceEffect = theFxScheduler.RegisterEffect( "bowcaster/bounce" ); - cgs.effects.bowcasterImpactEffect = theFxScheduler.RegisterEffect( "bowcaster/explosion" ); - theFxScheduler.RegisterEffect( "bowcaster/deflect" ); + cgs.effects.bowcasterShotEffect = theFxScheduler.RegisterEffect("bowcaster/shot"); + cgs.effects.bowcasterBounceEffect = theFxScheduler.RegisterEffect("bowcaster/bounce"); + cgs.effects.bowcasterImpactEffect = theFxScheduler.RegisterEffect("bowcaster/explosion"); + theFxScheduler.RegisterEffect("bowcaster/deflect"); break; case WP_REPEATER: - theFxScheduler.RegisterEffect( "repeater/muzzle_smoke" ); - theFxScheduler.RegisterEffect( "repeater/projectile" ); - theFxScheduler.RegisterEffect( "repeater/alt_projectile" ); - theFxScheduler.RegisterEffect( "repeater/wall_impact" ); -// theFxScheduler.RegisterEffect( "repeater/alt_wall_impact2" ); -// theFxScheduler.RegisterEffect( "repeater/flesh_impact" ); - theFxScheduler.RegisterEffect( "repeater/concussion" ); + theFxScheduler.RegisterEffect("repeater/muzzle_smoke"); + theFxScheduler.RegisterEffect("repeater/projectile"); + theFxScheduler.RegisterEffect("repeater/alt_projectile"); + theFxScheduler.RegisterEffect("repeater/wall_impact"); + // theFxScheduler.RegisterEffect( "repeater/alt_wall_impact2" ); + // theFxScheduler.RegisterEffect( "repeater/flesh_impact" ); + theFxScheduler.RegisterEffect("repeater/concussion"); break; case WP_DEMP2: - theFxScheduler.RegisterEffect( "demp2/projectile" ); - theFxScheduler.RegisterEffect( "demp2/wall_impact" ); - theFxScheduler.RegisterEffect( "demp2/flesh_impact" ); - theFxScheduler.RegisterEffect( "demp2/altDetonate" ); - cgi_R_RegisterModel( "models/items/sphere.md3" ); - cgi_R_RegisterShader( "gfx/effects/demp2shell" ); + theFxScheduler.RegisterEffect("demp2/projectile"); + theFxScheduler.RegisterEffect("demp2/wall_impact"); + theFxScheduler.RegisterEffect("demp2/flesh_impact"); + theFxScheduler.RegisterEffect("demp2/altDetonate"); + cgi_R_RegisterModel("models/items/sphere.md3"); + cgi_R_RegisterShader("gfx/effects/demp2shell"); break; case WP_ATST_MAIN: - theFxScheduler.RegisterEffect( "atst/shot" ); - theFxScheduler.RegisterEffect( "atst/wall_impact" ); - theFxScheduler.RegisterEffect( "atst/flesh_impact" ); - theFxScheduler.RegisterEffect( "atst/droid_impact" ); + theFxScheduler.RegisterEffect("atst/shot"); + theFxScheduler.RegisterEffect("atst/wall_impact"); + theFxScheduler.RegisterEffect("atst/flesh_impact"); + theFxScheduler.RegisterEffect("atst/droid_impact"); break; case WP_ATST_SIDE: // For the ALT fire - theFxScheduler.RegisterEffect( "atst/side_alt_shot" ); - theFxScheduler.RegisterEffect( "atst/side_alt_explosion" ); + theFxScheduler.RegisterEffect("atst/side_alt_shot"); + theFxScheduler.RegisterEffect("atst/side_alt_explosion"); // For the regular fire - theFxScheduler.RegisterEffect( "atst/side_main_shot" ); - theFxScheduler.RegisterEffect( "atst/side_main_impact" ); + theFxScheduler.RegisterEffect("atst/side_main_shot"); + theFxScheduler.RegisterEffect("atst/side_main_impact"); break; case WP_FLECHETTE: - cgs.effects.flechetteShotEffect = theFxScheduler.RegisterEffect( "flechette/shot" ); - cgs.effects.flechetteAltShotEffect = theFxScheduler.RegisterEffect( "flechette/alt_shot" ); - cgs.effects.flechetteShotDeathEffect = theFxScheduler.RegisterEffect( "flechette/wall_impact" ); // shot death - cgs.effects.flechetteFleshImpactEffect = theFxScheduler.RegisterEffect( "flechette/flesh_impact" ); - cgs.effects.flechetteRicochetEffect = theFxScheduler.RegisterEffect( "flechette/ricochet" ); - -// theFxScheduler.RegisterEffect( "flechette/explosion" ); - theFxScheduler.RegisterEffect( "flechette/alt_blow" ); + cgs.effects.flechetteShotEffect = theFxScheduler.RegisterEffect("flechette/shot"); + cgs.effects.flechetteAltShotEffect = theFxScheduler.RegisterEffect("flechette/alt_shot"); + cgs.effects.flechetteShotDeathEffect = theFxScheduler.RegisterEffect("flechette/wall_impact"); // shot death + cgs.effects.flechetteFleshImpactEffect = theFxScheduler.RegisterEffect("flechette/flesh_impact"); + cgs.effects.flechetteRicochetEffect = theFxScheduler.RegisterEffect("flechette/ricochet"); + + // theFxScheduler.RegisterEffect( "flechette/explosion" ); + theFxScheduler.RegisterEffect("flechette/alt_blow"); break; case WP_ROCKET_LAUNCHER: - theFxScheduler.RegisterEffect( "rocket/shot" ); - theFxScheduler.RegisterEffect( "rocket/explosion" ); + theFxScheduler.RegisterEffect("rocket/shot"); + theFxScheduler.RegisterEffect("rocket/explosion"); - cgi_R_RegisterShaderNoMip( "gfx/2d/wedge" ); - cgi_R_RegisterShaderNoMip( "gfx/2d/lock" ); + cgi_R_RegisterShaderNoMip("gfx/2d/wedge"); + cgi_R_RegisterShaderNoMip("gfx/2d/lock"); - cgi_S_RegisterSound( "sound/weapons/rocket/lock.wav" ); - cgi_S_RegisterSound( "sound/weapons/rocket/tick.wav" ); + cgi_S_RegisterSound("sound/weapons/rocket/lock.wav"); + cgi_S_RegisterSound("sound/weapons/rocket/tick.wav"); break; case WP_THERMAL: - cgs.media.grenadeBounce1 = cgi_S_RegisterSound( "sound/weapons/thermal/bounce1.wav" ); - cgs.media.grenadeBounce2 = cgi_S_RegisterSound( "sound/weapons/thermal/bounce2.wav" ); + cgs.media.grenadeBounce1 = cgi_S_RegisterSound("sound/weapons/thermal/bounce1.wav"); + cgs.media.grenadeBounce2 = cgi_S_RegisterSound("sound/weapons/thermal/bounce2.wav"); - cgi_S_RegisterSound( "sound/weapons/thermal/thermloop.wav" ); - cgi_S_RegisterSound( "sound/weapons/thermal/warning.wav" ); - theFxScheduler.RegisterEffect( "thermal/explosion" ); - theFxScheduler.RegisterEffect( "thermal/shockwave" ); + cgi_S_RegisterSound("sound/weapons/thermal/thermloop.wav"); + cgi_S_RegisterSound("sound/weapons/thermal/warning.wav"); + theFxScheduler.RegisterEffect("thermal/explosion"); + theFxScheduler.RegisterEffect("thermal/shockwave"); break; case WP_TRIP_MINE: - theFxScheduler.RegisterEffect( "tripMine/explosion" ); - theFxScheduler.RegisterEffect( "tripMine/laser" ); - theFxScheduler.RegisterEffect( "tripMine/laserImpactGlow" ); - theFxScheduler.RegisterEffect( "tripMine/glowBit" ); - - cgs.media.tripMineStickSound = cgi_S_RegisterSound( "sound/weapons/laser_trap/stick.wav" ); - cgi_S_RegisterSound( "sound/weapons/laser_trap/warning.wav" ); - cgi_S_RegisterSound( "sound/weapons/laser_trap/hum_loop.wav" ); + theFxScheduler.RegisterEffect("tripMine/explosion"); + theFxScheduler.RegisterEffect("tripMine/laser"); + theFxScheduler.RegisterEffect("tripMine/laserImpactGlow"); + theFxScheduler.RegisterEffect("tripMine/glowBit"); + + cgs.media.tripMineStickSound = cgi_S_RegisterSound("sound/weapons/laser_trap/stick.wav"); + cgi_S_RegisterSound("sound/weapons/laser_trap/warning.wav"); + cgi_S_RegisterSound("sound/weapons/laser_trap/hum_loop.wav"); break; case WP_DET_PACK: - theFxScheduler.RegisterEffect( "detpack/explosion.efx" ); + theFxScheduler.RegisterEffect("detpack/explosion.efx"); - cgs.media.detPackStickSound = cgi_S_RegisterSound( "sound/weapons/detpack/stick.wav" ); - cgi_R_RegisterModel( "models/weapons2/detpack/detpack.md3" ); - cgi_S_RegisterSound( "sound/weapons/detpack/warning.wav" ); - cgi_S_RegisterSound( "sound/weapons/explosions/explode5.wav" ); + cgs.media.detPackStickSound = cgi_S_RegisterSound("sound/weapons/detpack/stick.wav"); + cgi_R_RegisterModel("models/weapons2/detpack/detpack.md3"); + cgi_S_RegisterSound("sound/weapons/detpack/warning.wav"); + cgi_S_RegisterSound("sound/weapons/explosions/explode5.wav"); break; case WP_EMPLACED_GUN: - theFxScheduler.RegisterEffect( "emplaced/shot" ); - theFxScheduler.RegisterEffect( "emplaced/shotNPC" ); - theFxScheduler.RegisterEffect( "emplaced/wall_impact" ); - cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg" ); - cgi_R_RegisterShader( "models/map_objects/imp_mine/turret_chair_on" ); - - cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip( "gfx/hud/atst_health_frame" ); - cgs.media.ladyLuckHealthShader = cgi_R_RegisterShaderNoMip( "gfx/hud/ladyluck_health_frame" ); - cgs.media.turretComputerOverlayShader = cgi_R_RegisterShaderNoMip( "gfx/hud/generic_target" ); - cgs.media.turretCrossHairShader = cgi_R_RegisterShaderNoMip( "gfx/2d/panel_crosshair" ); + theFxScheduler.RegisterEffect("emplaced/shot"); + theFxScheduler.RegisterEffect("emplaced/shotNPC"); + theFxScheduler.RegisterEffect("emplaced/wall_impact"); + cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg"); + cgi_R_RegisterShader("models/map_objects/imp_mine/turret_chair_on"); + + cgs.media.emplacedHealthBarShader = cgi_R_RegisterShaderNoMip("gfx/hud/atst_health_frame"); + cgs.media.ladyLuckHealthShader = cgi_R_RegisterShaderNoMip("gfx/hud/ladyluck_health_frame"); + cgs.media.turretComputerOverlayShader = cgi_R_RegisterShaderNoMip("gfx/hud/generic_target"); + cgs.media.turretCrossHairShader = cgi_R_RegisterShaderNoMip("gfx/2d/panel_crosshair"); break; case WP_MELEE: - //TEMP - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); + // TEMP + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); break; case WP_STUN_BATON: - cgi_R_RegisterShader( "gfx/effects/stunPass" ); - theFxScheduler.RegisterEffect( "stunBaton/flesh_impact" ); - //TEMP - cgi_S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - cgi_S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); - cgi_S_RegisterSound( "sound/weapons/baton/fire" ); + cgi_R_RegisterShader("gfx/effects/stunPass"); + theFxScheduler.RegisterEffect("stunBaton/flesh_impact"); + // TEMP + cgi_S_RegisterSound("sound/weapons/melee/punch1.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch2.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch3.mp3"); + cgi_S_RegisterSound("sound/weapons/melee/punch4.mp3"); + cgi_S_RegisterSound("sound/weapons/baton/fire"); break; case WP_TURRET: - theFxScheduler.RegisterEffect( "turret/shot" ); - theFxScheduler.RegisterEffect( "turret/wall_impact" ); - theFxScheduler.RegisterEffect( "turret/flesh_impact" ); + theFxScheduler.RegisterEffect("turret/shot"); + theFxScheduler.RegisterEffect("turret/wall_impact"); + theFxScheduler.RegisterEffect("turret/flesh_impact"); break; case WP_BLASTER_PISTOL: // enemy version - cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect( "bryar/shot" ); - cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect( "bryar/crackleShot" ); - cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect( "bryar/wall_impact" ); - cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect( "bryar/flesh_impact" ); + cgs.effects.bryarShotEffect = theFxScheduler.RegisterEffect("bryar/shot"); + cgs.effects.bryarPowerupShotEffect = theFxScheduler.RegisterEffect("bryar/crackleShot"); + cgs.effects.bryarWallImpactEffect = theFxScheduler.RegisterEffect("bryar/wall_impact"); + cgs.effects.bryarFleshImpactEffect = theFxScheduler.RegisterEffect("bryar/flesh_impact"); // Note....these are temp shared effects - theFxScheduler.RegisterEffect( "blaster/deflect" ); - theFxScheduler.RegisterEffect( "blaster/smoke_bolton" ); // note: this will be called game side + theFxScheduler.RegisterEffect("blaster/deflect"); + theFxScheduler.RegisterEffect("blaster/smoke_bolton"); // note: this will be called game side break; } } @@ -539,102 +515,91 @@ CG_RegisterItemVisuals The server says this item is used on this level ================= */ -void CG_RegisterItemVisuals( int itemNum ) { - itemInfo_t *itemInfo; - gitem_t *item; +void CG_RegisterItemVisuals(int itemNum) { + itemInfo_t *itemInfo; + gitem_t *item; - itemInfo = &cg_items[ itemNum ]; - if ( itemInfo->registered ) { + itemInfo = &cg_items[itemNum]; + if (itemInfo->registered) { return; } - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - memset( itemInfo, 0, sizeof( *itemInfo ) ); + memset(itemInfo, 0, sizeof(*itemInfo)); itemInfo->registered = qtrue; - itemInfo->models = cgi_R_RegisterModel( item->world_model ); + itemInfo->models = cgi_R_RegisterModel(item->world_model); - if ( item->icon && item->icon[0] ) - { - itemInfo->icon = cgi_R_RegisterShaderNoMip( item->icon ); - } - else - { + if (item->icon && item->icon[0]) { + itemInfo->icon = cgi_R_RegisterShaderNoMip(item->icon); + } else { itemInfo->icon = -1; } - if ( item->giType == IT_WEAPON ) - { - CG_RegisterWeapon( item->giTag ); + if (item->giType == IT_WEAPON) { + CG_RegisterWeapon(item->giTag); } // some ammo types are actually the weapon, like in the case of explosives - if ( item->giType == IT_AMMO ) - { - switch( item->giTag ) - { + if (item->giType == IT_AMMO) { + switch (item->giTag) { case AMMO_THERMAL: - CG_RegisterWeapon( WP_THERMAL ); + CG_RegisterWeapon(WP_THERMAL); break; case AMMO_TRIPMINE: - CG_RegisterWeapon( WP_TRIP_MINE ); + CG_RegisterWeapon(WP_TRIP_MINE); break; case AMMO_DETPACK: - CG_RegisterWeapon( WP_DET_PACK ); + CG_RegisterWeapon(WP_DET_PACK); break; } } - - if ( item->giType == IT_HOLDABLE ) - { + if (item->giType == IT_HOLDABLE) { // This should be set up to actually work. - switch( item->giTag ) - { + switch (item->giTag) { case INV_SEEKER: cgi_S_RegisterSound("sound/chars/seeker/misc/fire.wav"); - cgi_S_RegisterSound( "sound/chars/seeker/misc/hiss.wav"); - theFxScheduler.RegisterEffect( "env/small_explode"); + cgi_S_RegisterSound("sound/chars/seeker/misc/hiss.wav"); + theFxScheduler.RegisterEffect("env/small_explode"); - CG_RegisterWeapon( WP_BLASTER ); + CG_RegisterWeapon(WP_BLASTER); break; case INV_SENTRY: - CG_RegisterWeapon( WP_TURRET ); - cgi_S_RegisterSound( "sound/player/use_sentry" ); + CG_RegisterWeapon(WP_TURRET); + cgi_S_RegisterSound("sound/player/use_sentry"); break; case INV_ELECTROBINOCULARS: // Binocular interface - cgs.media.binocularCircle = cgi_R_RegisterShader( "gfx/2d/binCircle" ); - cgs.media.binocularMask = cgi_R_RegisterShader( "gfx/2d/binMask" ); - cgs.media.binocularArrow = cgi_R_RegisterShader( "gfx/2d/binSideArrow" ); - cgs.media.binocularTri = cgi_R_RegisterShader( "gfx/2d/binTopTri" ); - cgs.media.binocularStatic = cgi_R_RegisterShader( "gfx/2d/binocularWindow" ); - cgs.media.binocularOverlay = cgi_R_RegisterShader( "gfx/2d/binocularNumOverlay" ); + cgs.media.binocularCircle = cgi_R_RegisterShader("gfx/2d/binCircle"); + cgs.media.binocularMask = cgi_R_RegisterShader("gfx/2d/binMask"); + cgs.media.binocularArrow = cgi_R_RegisterShader("gfx/2d/binSideArrow"); + cgs.media.binocularTri = cgi_R_RegisterShader("gfx/2d/binTopTri"); + cgs.media.binocularStatic = cgi_R_RegisterShader("gfx/2d/binocularWindow"); + cgs.media.binocularOverlay = cgi_R_RegisterShader("gfx/2d/binocularNumOverlay"); break; case INV_LIGHTAMP_GOGGLES: // LA Goggles Shaders - cgs.media.laGogglesStatic = cgi_R_RegisterShader( "gfx/2d/lagogglesWindow" ); - cgs.media.laGogglesMask = cgi_R_RegisterShader( "gfx/2d/amp_mask" ); - cgs.media.laGogglesSideBit = cgi_R_RegisterShader( "gfx/2d/side_bit" ); - cgs.media.laGogglesBracket = cgi_R_RegisterShader( "gfx/2d/bracket" ); - cgs.media.laGogglesArrow = cgi_R_RegisterShader( "gfx/2d/bracket2" ); + cgs.media.laGogglesStatic = cgi_R_RegisterShader("gfx/2d/lagogglesWindow"); + cgs.media.laGogglesMask = cgi_R_RegisterShader("gfx/2d/amp_mask"); + cgs.media.laGogglesSideBit = cgi_R_RegisterShader("gfx/2d/side_bit"); + cgs.media.laGogglesBracket = cgi_R_RegisterShader("gfx/2d/bracket"); + cgs.media.laGogglesArrow = cgi_R_RegisterShader("gfx/2d/bracket2"); break; case INV_BACTA_CANISTER: - for ( int i = 1; i < 5; i++ ) - { - cgi_S_RegisterSound( va( "sound/weapons/force/heal%d.mp3", i )); + for (int i = 1; i < 5; i++) { + cgi_S_RegisterSound(va("sound/weapons/force/heal%d.mp3", i)); } break; } } } - /* ======================================================================================== @@ -656,19 +621,16 @@ the weapon hand animation has 3 anims, if the torso anim does not match these lengths, it will not animate correctly! ================= */ -extern qboolean ValidAnimFileIndex ( int index ); -int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, int weaponNum, int firing ) -{ +extern qboolean ValidAnimFileIndex(int index); +int CG_MapTorsoToWeaponFrame(const clientInfo_t *ci, int frame, int animNum, int weaponNum, int firing) { // we should use the animNum to map a weapon frame instead of relying on the torso frame - if ( !ValidAnimFileIndex( ci->animFileIndex ) ) - { + if (!ValidAnimFileIndex(ci->animFileIndex)) { return 0; } animation_t *animations = level.knownAnimFileSets[ci->animFileIndex].animations; - int ret=0; + int ret = 0; - switch( animNum ) - { + switch (animNum) { case TORSO_WEAPONREADY1: case TORSO_WEAPONREADY2: case TORSO_WEAPONREADY3: @@ -685,24 +647,18 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in break; case TORSO_DROPWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5) { ret = frame - animations[animNum].firstFrame + 6; - } - else - { -// assert(0); + } else { + // assert(0); } break; case TORSO_RAISEWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4) { ret = frame - animations[animNum].firstFrame + 6 + 5; - } - else - { -// assert(0); + } else { + // assert(0); } break; @@ -710,13 +666,10 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in case BOTH_ATTACK2: case BOTH_ATTACK3: case BOTH_ATTACK4: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6 ) - { - ret = 1 + ( frame - animations[animNum].firstFrame ); - } - else - { -// assert(0); + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6) { + ret = 1 + (frame - animations[animNum].firstFrame); + } else { + // assert(0); } break; default: @@ -731,17 +684,16 @@ int CG_MapTorsoToWeaponFrame( const clientInfo_t *ci, int frame, int animNum, in CG_CalculateWeaponPosition ============== */ -void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) -{ - float scale; - int delta; - float fracsin; +void CG_CalculateWeaponPosition(vec3_t origin, vec3_t angles) { + float scale; + int delta; + float fracsin; - VectorCopy( cg.refdef.vieworg, origin ); - VectorCopy( cg.refdefViewAngles, angles ); + VectorCopy(cg.refdef.vieworg, origin); + VectorCopy(cg.refdefViewAngles, angles); // on odd legs, invert some angles - if ( cg.bobcycle & 1 ) { + if (cg.bobcycle & 1) { scale = -cg.xyspeed; } else { scale = cg.xyspeed; @@ -754,11 +706,10 @@ void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) // drop the weapon when landing delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { - origin[2] += cg.landChange*0.25 * delta / LAND_DEFLECT_TIME; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { - origin[2] += cg.landChange*0.25 * - (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; + if (delta < LAND_DEFLECT_TIME) { + origin[2] += cg.landChange * 0.25 * delta / LAND_DEFLECT_TIME; + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { + origin[2] += cg.landChange * 0.25 * (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; } #if 0 @@ -772,11 +723,11 @@ void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) #endif // idle drift - scale = /*cg.xyspeed + */40; - fracsin = sin( cg.time * 0.001 ); + scale = /*cg.xyspeed + */ 40; + fracsin = sin(cg.time * 0.001); angles[ROLL] += scale * fracsin * 0.01; angles[YAW] += scale * fracsin * 0.01; - angles[PITCH] += (scale * 0.5f ) * fracsin * 0.01; + angles[PITCH] += (scale * 0.5f) * fracsin * 0.01; } /* @@ -817,64 +768,51 @@ static float CG_MachinegunSpinAngle( centity_t *cent ) { Ghoul2 Insert Start */ // set up the appropriate ghoul2 info to a refent -void CG_SetGhoul2InfoRef( refEntity_t *ent, refEntity_t *s1) -{ +void CG_SetGhoul2InfoRef(refEntity_t *ent, refEntity_t *s1) { ent->ghoul2 = s1->ghoul2; - VectorCopy( s1->modelScale, ent->modelScale); + VectorCopy(s1->modelScale, ent->modelScale); ent->radius = s1->radius; - VectorCopy( s1->angles, ent->angles); + VectorCopy(s1->angles, ent->angles); } - //-------------------------------------------------------------------------- -static void CG_DoMuzzleFlash( centity_t *cent, vec3_t org, vec3_t dir, weaponData_t *wData ) -{ +static void CG_DoMuzzleFlash(centity_t *cent, vec3_t org, vec3_t dir, weaponData_t *wData) { // Handle muzzle flashes, really this could just be a qboolean instead of a time....... - if ( cent->muzzleFlashTime > 0 ) - { - cent->muzzleFlashTime = 0; + if (cent->muzzleFlashTime > 0) { + cent->muzzleFlashTime = 0; const char *effect = NULL; -// CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + // CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); // Try and get a default muzzle so we have one to fall back on - if ( wData->mMuzzleEffect[0] ) - { + if (wData->mMuzzleEffect[0]) { effect = &wData->mMuzzleEffect[0]; } - if ( cent->altFire ) - { + if (cent->altFire) { // We're alt-firing, so see if we need to override with a custom alt-fire effect - if ( wData->mAltMuzzleEffect[0] ) - { + if (wData->mAltMuzzleEffect[0]) { effect = &wData->mAltMuzzleEffect[0]; } } - if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect ) - { - vec3_t up={0,0,1}, ax[3]; + if (/*( cent->currentState.eFlags & EF_FIRING || cent->currentState.eFlags & EF_ALT_FIRING ) &&*/ effect) { + vec3_t up = {0, 0, 1}, ax[3]; - VectorCopy( dir, ax[0] ); + VectorCopy(dir, ax[0]); - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); - if (( cent->gent && cent->gent->NPC ) || cg.renderingThirdPerson ) - { - theFxScheduler.PlayEffect( effect, org, dir ); - } - else - { + if ((cent->gent && cent->gent->NPC) || cg.renderingThirdPerson) { + theFxScheduler.PlayEffect(effect, org, dir); + } else { // We got an effect and we're firing, so let 'er rip. - theFxScheduler.PlayEffect( effect, cent->currentState.clientNum ); + theFxScheduler.PlayEffect(effect, cent->currentState.clientNum); } } - } - else - { -// CG_PositionRotatedEntityOnTag( &flash, &gun, weapon->weaponModel, "tag_flash", NULL); + } else { + // CG_PositionRotatedEntityOnTag( &flash, &gun, weapon->weaponModel, "tag_flash", NULL); } } @@ -889,20 +827,19 @@ CG_AddViewWeapon Add the weapon, and flash for the player's view ============== */ -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -extern float CG_ForceSpeedFOV( void ); - -void CG_AddViewWeapon( playerState_t *ps ) -{ - refEntity_t hand; - refEntity_t gun; - refEntity_t flash; - vec3_t angles; - const weaponInfo_t *weapon; - weaponData_t *wData; - centity_t *cent; - float fovOffset, leanOffset; - float cgFov = (cg_fovViewmodel.integer) ? cg_fovViewmodel.integer : cg_fov.integer; +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +extern float CG_ForceSpeedFOV(void); + +void CG_AddViewWeapon(playerState_t *ps) { + refEntity_t hand; + refEntity_t gun; + refEntity_t flash; + vec3_t angles; + const weaponInfo_t *weapon; + weaponData_t *wData; + centity_t *cent; + float fovOffset, leanOffset; + float cgFov = (cg_fovViewmodel.integer) ? cg_fovViewmodel.integer : cg_fov.integer; int i; if (cgFov < 1) @@ -911,338 +848,287 @@ void CG_AddViewWeapon( playerState_t *ps ) cgFov = 130; // no gun if in third person view - if ( cg.renderingThirdPerson ) + if (cg.renderingThirdPerson) return; - if ( ps->pm_type == PM_INTERMISSION ) + if (ps->pm_type == PM_INTERMISSION) return; cent = &cg_entities[ps->clientNum]; - if ( ps->eFlags & EF_LOCKED_TO_WEAPON ) - { + if (ps->eFlags & EF_LOCKED_TO_WEAPON) { return; } - if ( cent->gent && cent->gent->client && cent->gent->client->ps.forcePowersActive&(1<gent && cent->gent->client && cent->gent->client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // doing the electrocuting vec3_t tAng, fxDir, temp; - VectorSet( tAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); + VectorSet(tAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0); - VectorCopy( cent->gent->client->renderInfo.handLPoint, temp ); - VectorMA( temp, -5, cg.refdef.viewaxis[0], temp ); - if ( cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t fxAxis[3]; - AnglesToAxis( tAng, fxAxis ); - theFxScheduler.PlayEffect( cgs.effects.forceLightningWide, temp, fxAxis ); - } - else - {//line - AngleVectors( tAng, fxDir, NULL, NULL ); - theFxScheduler.PlayEffect( cgs.effects.forceLightning, temp, fxDir ); + VectorCopy(cent->gent->client->renderInfo.handLPoint, temp); + VectorMA(temp, -5, cg.refdef.viewaxis[0], temp); + if (cent->gent->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t fxAxis[3]; + AnglesToAxis(tAng, fxAxis); + theFxScheduler.PlayEffect(cgs.effects.forceLightningWide, temp, fxAxis); + } else { // line + AngleVectors(tAng, fxDir, NULL, NULL); + theFxScheduler.PlayEffect(cgs.effects.forceLightning, temp, fxDir); } } // allow the gun to be completely removed - if ( !cg_drawGun.integer || cg.zoomMode ) - { - vec3_t origin; + if (!cg_drawGun.integer || cg.zoomMode) { + vec3_t origin; // special hack for lightning guns... - VectorCopy( cg.refdef.vieworg, origin ); - VectorMA( origin, -10, cg.refdef.viewaxis[2], origin ); - VectorMA( origin, 16, cg.refdef.viewaxis[0], origin ); -// Doesn't look like we'll have lightning style guns. Clean this crap up when we are sure about this. -// CG_LightningBolt( cent, origin ); + VectorCopy(cg.refdef.vieworg, origin); + VectorMA(origin, -10, cg.refdef.viewaxis[2], origin); + VectorMA(origin, 16, cg.refdef.viewaxis[0], origin); + // Doesn't look like we'll have lightning style guns. Clean this crap up when we are sure about this. + // CG_LightningBolt( cent, origin ); // We should still do muzzle flashes though... - CG_RegisterWeapon( ps->weapon ); + CG_RegisterWeapon(ps->weapon); weapon = &cg_weapons[ps->weapon]; - wData = &weaponData[ps->weapon]; + wData = &weaponData[ps->weapon]; - CG_DoMuzzleFlash( cent, origin, cg.refdef.viewaxis[0], wData ); + CG_DoMuzzleFlash(cent, origin, cg.refdef.viewaxis[0], wData); // If we don't update this, the muzzle flash point won't even be updated properly - VectorCopy( origin, cent->gent->client->renderInfo.muzzlePoint ); - VectorCopy( cg.refdef.viewaxis[0], cent->gent->client->renderInfo.muzzleDir ); + VectorCopy(origin, cent->gent->client->renderInfo.muzzlePoint); + VectorCopy(cg.refdef.viewaxis[0], cent->gent->client->renderInfo.muzzleDir); cent->gent->client->renderInfo.mPCalcTime = cg.time; return; } // don't draw if testing a gun model - if ( cg.testGun ) - { + if (cg.testGun) { return; } // drop gun lower at higher fov float actualFOV; - gentity_t *player = &g_entities[0]; - if ( (cg.snap->ps.forcePowersActive&(1<client->ps.forcePowerDuration[FP_SPEED] )//cg.renderingThirdPerson && + gentity_t *player = &g_entities[0]; + if ((cg.snap->ps.forcePowersActive & (1 << FP_SPEED)) && player->client->ps.forcePowerDuration[FP_SPEED]) // cg.renderingThirdPerson && { actualFOV = CG_ForceSpeedFOV(); actualFOV = (cg_fovViewmodel.integer) ? actualFOV + (cg_fovViewmodel.integer - cg_fov.integer) : actualFOV; - } - else - { - actualFOV = (cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + } else { + actualFOV = (cg.overrides.active & CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; } - if ( cg_fovViewmodelAdjust.integer && actualFOV > 80 ) - { - fovOffset = -0.1 * ( actualFOV - 80 ); - } - else - { + if (cg_fovViewmodelAdjust.integer && actualFOV > 80) { + fovOffset = -0.1 * (actualFOV - 80); + } else { fovOffset = 0; } - if ( ps->leanofs != 0 ) - { - //add leaning offset + if (ps->leanofs != 0) { + // add leaning offset leanOffset = ps->leanofs * 0.25f; fovOffset += fabs((double)ps->leanofs) * -0.1f; - } - else - { + } else { leanOffset = 0; } - CG_RegisterWeapon( ps->weapon ); + CG_RegisterWeapon(ps->weapon); weapon = &cg_weapons[ps->weapon]; - wData = &weaponData[ps->weapon]; + wData = &weaponData[ps->weapon]; - memset (&hand, 0, sizeof(hand)); + memset(&hand, 0, sizeof(hand)); - if ( ps->weapon == WP_STUN_BATON ) - { - cgi_S_AddLoopingSound( cent->currentState.number, - cent->lerpOrigin, - vec3_origin, - weapon->firingSound ); + if (ps->weapon == WP_STUN_BATON) { + cgi_S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); } - if ( ps->weapon == WP_NONE ) - { + if (ps->weapon == WP_NONE) { return; } // set up gun position - CG_CalculateWeaponPosition( hand.origin, angles ); + CG_CalculateWeaponPosition(hand.origin, angles); - VectorMA( hand.origin, cg_gun_x.value, cg.refdef.viewaxis[0], hand.origin ); - VectorMA( hand.origin, (cg_gun_y.value+leanOffset), cg.refdef.viewaxis[1], hand.origin ); - VectorMA( hand.origin, (cg_gun_z.value+fovOffset), cg.refdef.viewaxis[2], hand.origin ); + VectorMA(hand.origin, cg_gun_x.value, cg.refdef.viewaxis[0], hand.origin); + VectorMA(hand.origin, (cg_gun_y.value + leanOffset), cg.refdef.viewaxis[1], hand.origin); + VectorMA(hand.origin, (cg_gun_z.value + fovOffset), cg.refdef.viewaxis[2], hand.origin); - AnglesToAxis( angles, hand.axis ); + AnglesToAxis(angles, hand.axis); - if ( cg_fovViewmodel.integer ) - { - float fracDistFOV = tanf( cg.refdef.fov_x * ( M_PI/180 ) * 0.5f ); - float fracWeapFOV = ( 1.0f / fracDistFOV ) * tanf( cgFov * ( M_PI/180 ) * 0.5f ); - VectorScale( hand.axis[0], fracWeapFOV, hand.axis[0] ); + if (cg_fovViewmodel.integer) { + float fracDistFOV = tanf(cg.refdef.fov_x * (M_PI / 180) * 0.5f); + float fracWeapFOV = (1.0f / fracDistFOV) * tanf(cgFov * (M_PI / 180) * 0.5f); + VectorScale(hand.axis[0], fracWeapFOV, hand.axis[0]); } // map torso animations to weapon animations - if ( cg_gun_frame.integer ) - { + if (cg_gun_frame.integer) { // development tool hand.frame = hand.oldframe = cg_gun_frame.integer; hand.backlerp = 0; - } - else - { + } else { // get clientinfo for animation map - const clientInfo_t *ci = ¢->gent->client->clientInfo; - int torsoAnim = cent->gent->client->ps.torsoAnim;//pe.torso.animationNumber; + const clientInfo_t *ci = ¢->gent->client->clientInfo; + int torsoAnim = cent->gent->client->ps.torsoAnim; // pe.torso.animationNumber; float currentFrame; - int startFrame,endFrame,flags; + int startFrame, endFrame, flags; float animSpeed; - if (cent->gent->lowerLumbarBone>=0&& gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed,0) ) - { - hand.oldframe = CG_MapTorsoToWeaponFrame( ci,floor(currentFrame), torsoAnim, cent->currentState.weapon, ( cent->currentState.eFlags & EF_FIRING ) ); - hand.frame = CG_MapTorsoToWeaponFrame( ci,ceil(currentFrame), torsoAnim, cent->currentState.weapon, ( cent->currentState.eFlags & EF_FIRING ) ); - hand.backlerp=1.0f-(currentFrame-floor(currentFrame)); - if ( cg_debugAnim.integer == 1 && cent->currentState.clientNum == 0 ) - { - Com_Printf( "Torso frame %d to %d makes Weapon frame %d to %d\n", cent->pe.torso.oldFrame, cent->pe.torso.frame, hand.oldframe, hand.frame ); + if (cent->gent->lowerLumbarBone >= 0 && gi.G2API_GetBoneAnimIndex(¢->gent->ghoul2[cent->gent->playerModel], cent->gent->lowerLumbarBone, cg.time, + ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, 0)) { + hand.oldframe = CG_MapTorsoToWeaponFrame(ci, floor(currentFrame), torsoAnim, cent->currentState.weapon, (cent->currentState.eFlags & EF_FIRING)); + hand.frame = CG_MapTorsoToWeaponFrame(ci, ceil(currentFrame), torsoAnim, cent->currentState.weapon, (cent->currentState.eFlags & EF_FIRING)); + hand.backlerp = 1.0f - (currentFrame - floor(currentFrame)); + if (cg_debugAnim.integer == 1 && cent->currentState.clientNum == 0) { + Com_Printf("Torso frame %d to %d makes Weapon frame %d to %d\n", cent->pe.torso.oldFrame, cent->pe.torso.frame, hand.oldframe, hand.frame); } - } - else - { -// assert(0); // no idea what to do here - hand.oldframe=0; - hand.frame=0; - hand.backlerp=0.0f; + } else { + // assert(0); // no idea what to do here + hand.oldframe = 0; + hand.frame = 0; + hand.backlerp = 0.0f; } } // add the weapon - memset (&gun, 0, sizeof(gun)); + memset(&gun, 0, sizeof(gun)); gun.hModel = weapon->weaponModel; - if (!gun.hModel) - { + if (!gun.hModel) { return; } - AnglesToAxis( angles, gun.axis ); - CG_PositionEntityOnTag( &gun, &hand, weapon->handsModel, "tag_weapon"); + AnglesToAxis(angles, gun.axis); + CG_PositionEntityOnTag(&gun, &hand, weapon->handsModel, "tag_weapon"); gun.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON; -//--------- + //--------- // OK, we are making an assumption here that if we have the phaser that it is always on.... - //FIXME: if saberInFlight, need to draw empty hand guiding it - if ( cent->gent && cent->gent->client && cent->currentState.weapon == WP_SABER ) - { + // FIXME: if saberInFlight, need to draw empty hand guiding it + if (cent->gent && cent->gent->client && cent->currentState.weapon == WP_SABER) { vec3_t org_, axis_[3]; - CG_GetTagWorldPosition( &gun, "tag_flash", org_, axis_ ); - if ( cent->gent->client->ps.saberActive && cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax ) - { - cent->gent->client->ps.saberLength += cg.frametime*0.03; - if ( cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax ) - { + CG_GetTagWorldPosition(&gun, "tag_flash", org_, axis_); + if (cent->gent->client->ps.saberActive && cent->gent->client->ps.saberLength < cent->gent->client->ps.saberLengthMax) { + cent->gent->client->ps.saberLength += cg.frametime * 0.03; + if (cent->gent->client->ps.saberLength > cent->gent->client->ps.saberLengthMax) { cent->gent->client->ps.saberLength = cent->gent->client->ps.saberLengthMax; } } -// FX_Saber( org_, axis_[0], cent->gent->client->ps.saberLength, 2.0 + Q_flrand(-1.0f, 1.0f) * 0.2f, cent->gent->client->ps.saberColor ); - VectorCopy( axis_[0], cent->gent->client->renderInfo.muzzleDir ); + // FX_Saber( org_, axis_[0], cent->gent->client->ps.saberLength, 2.0 + Q_flrand(-1.0f, 1.0f) * 0.2f, cent->gent->client->ps.saberColor ); + VectorCopy(axis_[0], cent->gent->client->renderInfo.muzzleDir); } -//--------- + //--------- -// CG_AddRefEntityWithPowerups( &gun, cent->currentState.powerups, cent->gent ); - cgi_R_AddRefEntityToScene( &gun ); + // CG_AddRefEntityWithPowerups( &gun, cent->currentState.powerups, cent->gent ); + cgi_R_AddRefEntityToScene(&gun); -/* if ( ps->weapon == WP_STUN_BATON ) - { - gun.shaderRGBA[0] = gun.shaderRGBA[1] = gun.shaderRGBA[2] = 25; + /* if ( ps->weapon == WP_STUN_BATON ) + { + gun.shaderRGBA[0] = gun.shaderRGBA[1] = gun.shaderRGBA[2] = 25; - gun.customShader = cgi_R_RegisterShader( "gfx/effects/stunPass" ); - gun.renderfx = RF_RGB_TINT | RF_FIRST_PERSON | RF_DEPTHHACK; - cgi_R_AddRefEntityToScene( &gun ); - } -*/ + gun.customShader = cgi_R_RegisterShader( "gfx/effects/stunPass" ); + gun.renderfx = RF_RGB_TINT | RF_FIRST_PERSON | RF_DEPTHHACK; + cgi_R_AddRefEntityToScene( &gun ); + } + */ // add the spinning barrel[s] - for (i = 0; (i < wData->numBarrels); i++) - { - refEntity_t barrel; - memset( &barrel, 0, sizeof( barrel ) ); + for (i = 0; (i < wData->numBarrels); i++) { + refEntity_t barrel; + memset(&barrel, 0, sizeof(barrel)); barrel.hModel = weapon->barrelModel[i]; - //VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); - //barrel.shadowPlane = parent->shadowPlane; + // VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); + // barrel.shadowPlane = parent->shadowPlane; barrel.renderfx = gun.renderfx; angles[YAW] = 0; angles[PITCH] = 0; -// if ( ps->weapon == WP_TETRION_DISRUPTOR) { -// angles[ROLL] = CG_MachinegunSpinAngle( cent ); -// } else { - angles[ROLL] = 0;//CG_MachinegunSpinAngle( cent ); -// } - - AnglesToAxis( angles, barrel.axis ); - if (!i) - { - CG_PositionRotatedEntityOnTag( &barrel, &hand, weapon->handsModel, "tag_barrel", NULL ); - } else - { - CG_PositionRotatedEntityOnTag( &barrel, &hand, weapon->handsModel, va("tag_barrel%d",i+1), NULL ); + // if ( ps->weapon == WP_TETRION_DISRUPTOR) { + // angles[ROLL] = CG_MachinegunSpinAngle( cent ); + // } else { + angles[ROLL] = 0; // CG_MachinegunSpinAngle( cent ); + // } + + AnglesToAxis(angles, barrel.axis); + if (!i) { + CG_PositionRotatedEntityOnTag(&barrel, &hand, weapon->handsModel, "tag_barrel", NULL); + } else { + CG_PositionRotatedEntityOnTag(&barrel, &hand, weapon->handsModel, va("tag_barrel%d", i + 1), NULL); } - cgi_R_AddRefEntityToScene( &barrel ); + cgi_R_AddRefEntityToScene(&barrel); } - memset (&flash, 0, sizeof(flash)); + memset(&flash, 0, sizeof(flash)); // Seems like we should always do this in case we have an animating muzzle flash....that way we can always store the correct muzzle dir, etc. - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); - CG_DoMuzzleFlash( cent, flash.origin, flash.axis[0], wData ); + CG_DoMuzzleFlash(cent, flash.origin, flash.axis[0], wData); - if ( cent->gent && cent->gent->client ) - { + if (cent->gent && cent->gent->client) { VectorCopy(flash.origin, cent->gent->client->renderInfo.muzzlePoint); VectorCopy(flash.axis[0], cent->gent->client->renderInfo.muzzleDir); -// VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); + // VectorNormalize( cent->gent->client->renderInfo.muzzleDir ); cent->gent->client->renderInfo.mPCalcTime = cg.time; - CG_LightningBolt( cent, flash.origin ); + CG_LightningBolt(cent, flash.origin); } // Do special charge bits //----------------------- - if (( ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL ) - || ( ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING ) - || ( ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT )) - { - int shader = 0; - float val = 0.0f, scale = 1.0f; - vec3_t WHITE = {1.0f,1.0f,1.0f}; + if ((ps->weaponstate == WEAPON_CHARGING_ALT && ps->weapon == WP_BRYAR_PISTOL) || (ps->weapon == WP_BOWCASTER && ps->weaponstate == WEAPON_CHARGING) || + (ps->weapon == WP_DEMP2 && ps->weaponstate == WEAPON_CHARGING_ALT)) { + int shader = 0; + float val = 0.0f, scale = 1.0f; + vec3_t WHITE = {1.0f, 1.0f, 1.0f}; - if ( ps->weapon == WP_BRYAR_PISTOL ) - { + if (ps->weapon == WP_BRYAR_PISTOL) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/bryarFrontFlash" ); - } - else if ( ps->weapon == WP_BOWCASTER ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/bryarFrontFlash"); + } else if (ps->weapon == WP_BOWCASTER) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/effects/greenFrontFlash" ); - } - else if ( ps->weapon == WP_DEMP2 ) - { + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/effects/greenFrontFlash"); + } else if (ps->weapon == WP_DEMP2) { // Hardcoded max charge time of 1 second - val = ( cg.time - ps->weaponChargeTime ) * 0.001f; - shader = cgi_R_RegisterShader( "gfx/misc/lightningFlash" ); + val = (cg.time - ps->weaponChargeTime) * 0.001f; + shader = cgi_R_RegisterShader("gfx/misc/lightningFlash"); scale = 1.75f; } - if ( val < 0.0f ) - { + if (val < 0.0f) { val = 0.0f; - } - else if ( val > 1.0f ) - { + } else if (val > 1.0f) { val = 1.0f; - CGCam_Shake( 0.1f, 100 ); - } - else - { - CGCam_Shake( val * val * 0.3f, 100 ); + CGCam_Shake(0.1f, 100); + } else { + CGCam_Shake(val * val * 0.3f, 100); } val += Q_flrand(0.0f, 1.0f) * 0.5f; - FX_AddSprite( flash.origin, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA | FX_DEPTH_HACK ); + FX_AddSprite(flash.origin, NULL, NULL, 3.0f * val * scale, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, + FX_USE_ALPHA | FX_DEPTH_HACK); } // Check if the heavy repeater is finishing up a sustained burst //------------------------------- - if ( ps->weapon == WP_REPEATER && ps->weaponstate == WEAPON_FIRING ) - { - if ( cent->gent && cent->gent->client && cent->gent->client->ps.weaponstate != WEAPON_FIRING ) - { - int ct = 0; + if (ps->weapon == WP_REPEATER && ps->weaponstate == WEAPON_FIRING) { + if (cent->gent && cent->gent->client && cent->gent->client->ps.weaponstate != WEAPON_FIRING) { + int ct = 0; // the more continuous shots we've got, the more smoke we spawn - if ( cent->gent->client->ps.weaponShotCount > 60 ) { + if (cent->gent->client->ps.weaponShotCount > 60) { ct = 5; - } - else if ( cent->gent->client->ps.weaponShotCount > 35 ) { + } else if (cent->gent->client->ps.weaponShotCount > 35) { ct = 3; - } - else if ( cent->gent->client->ps.weaponShotCount > 15 ) { + } else if (cent->gent->client->ps.weaponShotCount > 15) { ct = 1; } - for ( i = 0; i < ct; i++ ) - { - theFxScheduler.PlayEffect( "repeater/muzzle_smoke", cent->currentState.clientNum ); + for (i = 0; i < ct; i++) { + theFxScheduler.PlayEffect("repeater/muzzle_smoke", cent->currentState.clientNum); } cent->gent->client->ps.weaponShotCount = 0; @@ -1263,31 +1149,24 @@ WEAPON SELECTION CG_WeaponCheck =================== */ -int CG_WeaponCheck( int weaponIndex ) -{ - int value; +int CG_WeaponCheck(int weaponIndex) { + int value; - if ( weaponIndex == WP_SABER || weaponIndex == WP_STUN_BATON ) - { + if (weaponIndex == WP_SABER || weaponIndex == WP_STUN_BATON) { return qtrue; } - value = weaponData[weaponIndex].energyPerShot < weaponData[weaponIndex].altEnergyPerShot - ? weaponData[weaponIndex].energyPerShot - : weaponData[weaponIndex].altEnergyPerShot; + value = weaponData[weaponIndex].energyPerShot < weaponData[weaponIndex].altEnergyPerShot ? weaponData[weaponIndex].energyPerShot + : weaponData[weaponIndex].altEnergyPerShot; - if( !cg.snap ) - { + if (!cg.snap) { return qfalse; } // check how much energy(ammo) it takes to fire this weapon against how much ammo we have - if ( value > cg.snap->ps.ammo[weaponData[weaponIndex].ammoIndex] ) - { + if (value > cg.snap->ps.ammo[weaponData[weaponIndex].ammoIndex]) { value = qfalse; - } - else - { + } else { value = qtrue; } @@ -1299,223 +1178,178 @@ int CG_WeaponCheck( int weaponIndex ) CG_DrawIconBackground =================== */ -void CG_DrawIconBackground(void) -{ - int height,xAdd,x2,y2,t; - int prongLeftX,prongRightX; - qhandle_t background; +void CG_DrawIconBackground(void) { + int height, xAdd, x2, y2, t; + int prongLeftX, prongRightX; + qhandle_t background; - if (( cg.zoomMode != 0 ) || !( cg_drawHUD.integer )) - { + if ((cg.zoomMode != 0) || !(cg_drawHUD.integer)) { return; } - if ((cg.snap->ps.viewEntity>0&&cg.snap->ps.viewEntityps.viewEntity > 0 && cg.snap->ps.viewEntity < ENTITYNUM_WORLD)) { return; } - - if (!cgi_UI_GetMenuInfo("iconbackground",&x2,&y2)) - { + if (!cgi_UI_GetMenuInfo("iconbackground", &x2, &y2)) { return; } - prongLeftX =x2+37; - prongRightX =x2+544; + prongLeftX = x2 + 37; + prongRightX = x2 + 544; - if (((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_INVENTORY)) // Display inventory background? + if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || (cgs.media.currentBackground == ICON_INVENTORY)) // Display inventory background? { background = cgs.media.inventoryIconBackground; - } - else if (((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) || (cgs.media.currentBackground == ICON_WEAPONS)) // Display weapon background? + } else if (((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) || (cgs.media.currentBackground == ICON_WEAPONS)) // Display weapon background? { background = cgs.media.weaponIconBackground; - } - else // Display force background? + } else // Display force background? { background = cgs.media.forceIconBackground; } - if ((cg.iconSelectTime+WEAPON_SELECT_TIME)1) - { + if (cg.iconHUDPercent > 1) { cg.iconHUDActive = qtrue; - cg.iconHUDPercent=1; + cg.iconHUDPercent = 1; + } else if (cg.iconHUDPercent < 0) { + cg.iconHUDPercent = 0; } - else if (cg.iconHUDPercent<0) - { - cg.iconHUDPercent=0; - } - } - else - { - cg.iconHUDPercent=1; + } else { + cg.iconHUDPercent = 1; } - cgi_R_SetColor( colorTable[CT_WHITE] ); - height = (int) (60.0f*cg.iconHUDPercent); - CG_DrawPic( x2+60, y2+30, 460, -height, background); // Top half - CG_DrawPic( x2+60, y2+30-2,460, height, background); // Bottom half - + cgi_R_SetColor(colorTable[CT_WHITE]); + height = (int)(60.0f * cg.iconHUDPercent); + CG_DrawPic(x2 + 60, y2 + 30, 460, -height, background); // Top half + CG_DrawPic(x2 + 60, y2 + 30 - 2, 460, height, background); // Bottom half // And now for the prongs - if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) - { + if ((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) { cgs.media.currentBackground = ICON_INVENTORY; background = cgs.media.inventoryProngsOn; - } - else if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) - { + } else if ((cg.weaponSelectTime + WEAPON_SELECT_TIME) > cg.time) { cgs.media.currentBackground = ICON_WEAPONS; background = cgs.media.weaponProngsOn; - } - else - { + } else { cgs.media.currentBackground = ICON_FORCE; background = cgs.media.forceProngsOn; } - // Side Prongs - cgi_R_SetColor( colorTable[CT_WHITE]); - xAdd = (int) 8*cg.iconHUDPercent; - CG_DrawPic( prongLeftX+xAdd, y2-10, 40, 80, background); - CG_DrawPic( prongRightX-xAdd, y2-10, -40, 80, background); + cgi_R_SetColor(colorTable[CT_WHITE]); + xAdd = (int)8 * cg.iconHUDPercent; + CG_DrawPic(prongLeftX + xAdd, y2 - 10, 40, 80, background); + CG_DrawPic(prongRightX - xAdd, y2 - 10, -40, 80, background); } -int cgi_UI_GetItemText(char *menuFile,char *itemName, char *text); +int cgi_UI_GetItemText(char *menuFile, char *itemName, char *text); -char *weaponDesc[13] = -{ -"SABER_DESC", -"BLASTER_PISTOL_DESC", -"BLASTER_RIFLE_DESC", -"DISRUPTOR_RIFLE_DESC", -"BOWCASTER_DESC", -"HEAVYREPEATER_DESC", -"DEMP2_DESC", -"FLECHETTE_DESC", -"MERR_SONN_DESC", -"THERMAL_DETONATOR_DESC", -"TRIP_MINE_DESC", -"DET_PACK_DESC", -"STUN_BATON_DESC", +char *weaponDesc[13] = { + "SABER_DESC", "BLASTER_PISTOL_DESC", "BLASTER_RIFLE_DESC", "DISRUPTOR_RIFLE_DESC", "BOWCASTER_DESC", "HEAVYREPEATER_DESC", "DEMP2_DESC", + "FLECHETTE_DESC", "MERR_SONN_DESC", "THERMAL_DETONATOR_DESC", "TRIP_MINE_DESC", "DET_PACK_DESC", "STUN_BATON_DESC", }; - /* =================== CG_DrawDataPadWeaponSelect =================== */ -void CG_DrawDataPadWeaponSelect( void ) -{ - int i; - int bits; - int count; - int smallIconSize,bigIconSize; - int holdX,x,y,pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; - vec4_t calcColor; - char text[1024]={0}; - vec4_t textColor = { .875f, .718f, .121f, 1.0f }; +void CG_DrawDataPadWeaponSelect(void) { + int i; + int bits; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + vec4_t calcColor; + char text[1024] = {0}; + vec4_t textColor = {.875f, .718f, .121f, 1.0f}; // showing weapon select clears pickup item display, but not the blend blob cg.itemPickupTime = 0; - bits = cg.snap->ps.stats[ STAT_WEAPONS ]; + bits = cg.snap->ps.stats[STAT_WEAPONS]; // count the number of weapons owned count = 0; - for ( i = 1 ; i < 16 ; i++ ) - { - if ( bits & ( 1 << i ) ) - { + for (i = 1; i < 16; i++) { + if (bits & (1 << i)) { count++; } } - if (count == 0) // If no weapons, don't display + if (count == 0) // If no weapons, don't display { return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } // This seems to be a problem is datapad comes up too early - if (cg.DataPadWeaponSelectMAX_PLAYER_WEAPONS) - { + } else if (cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { cg.DataPadWeaponSelect = MAX_PLAYER_WEAPONS; } i = cg.DataPadWeaponSelect - 1; - if (i<1) - { + if (i < 1) { i = 13; } @@ -1529,138 +1363,115 @@ void CG_DrawDataPadWeaponSelect( void ) // Background memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); calcColor[3] = .60f; - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Left side ICONS - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i<1) - { + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 1) { i = 13; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; + // height = bigIconSize * cg.iconHUDPercent; cgi_R_SetColor(NULL); -// char buffer[256]; -// cgi_UI_GetItemText("datapadWeaponsMenu",va("weapondesc%d",cg.DataPadWeaponSelect+1),buffer); + // char buffer[256]; + // cgi_UI_GetItemText("datapadWeaponsMenu",va("weapondesc%d",cg.DataPadWeaponSelect+1),buffer); - if (weaponData[cg.DataPadWeaponSelect].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( cg.DataPadWeaponSelect ); + if (weaponData[cg.DataPadWeaponSelect].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(cg.DataPadWeaponSelect); weaponInfo = &cg_weapons[cg.DataPadWeaponSelect]; - if (!CG_WeaponCheck(cg.DataPadWeaponSelect)) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(cg.DataPadWeaponSelect)) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, weaponInfo->weaponIcon); } } i = cg.DataPadWeaponSelect + 1; - if (i> 13) - { + if (i > 13) { i = 1; } // Right side ICONS // Work forwards from current icon - cgi_R_SetColor( calcColor); - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>13) - { + cgi_R_SetColor(calcColor); + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i > 13) { i = 1; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; // No ammo for this weapon? - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } // draw the weapon description - x= 40; - y= 70; + x = 40; + y = 70; - cgi_SP_GetStringTextString( va("INGAME_%s",weaponDesc[cg.DataPadWeaponSelect-1]), text, sizeof(text) ); + cgi_SP_GetStringTextString(va("INGAME_%s", weaponDesc[cg.DataPadWeaponSelect - 1]), text, sizeof(text)); - if (text[0]) - { - CG_DisplayBoxedText(70,50,500,300,text, - cgs.media.qhFontSmall, - 0.7f, - textColor - ); - } - -/* CG_DisplayBoxedText(70,50,500,300,weaponDesc[cg.DataPadWeaponSelect-1], - cgs.media.qhFontSmall, - 0.7f, - colorTable[CT_WHITE] - ); -*/ + if (text[0]) { + CG_DisplayBoxedText(70, 50, 500, 300, text, cgs.media.qhFontSmall, 0.7f, textColor); + } + + /* CG_DisplayBoxedText(70,50,500,300,weaponDesc[cg.DataPadWeaponSelect-1], + cgs.media.qhFontSmall, + 0.7f, + colorTable[CT_WHITE] + ); + */ - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } /* @@ -1668,118 +1479,110 @@ void CG_DrawDataPadWeaponSelect( void ) CG_DrawDataPadIconBackground =================== */ -void CG_DrawDataPadIconBackground(int backgroundType) -{ - int height,xAdd,x2,y2; - int prongLeftX,prongRightX; - qhandle_t background; +void CG_DrawDataPadIconBackground(int backgroundType) { + int height, xAdd, x2, y2; + int prongLeftX, prongRightX; + qhandle_t background; x2 = 0; y2 = 295; - prongLeftX =x2+97; - prongRightX =x2+544; + prongLeftX = x2 + 97; + prongRightX = x2 + 544; - if (backgroundType == ICON_INVENTORY) // Display inventory background? + if (backgroundType == ICON_INVENTORY) // Display inventory background? { background = cgs.media.inventoryIconBackground; - } - else if (backgroundType == ICON_WEAPONS) // Display weapon background? + } else if (backgroundType == ICON_WEAPONS) // Display weapon background? { background = cgs.media.weaponIconBackground; - } - else // Display force background? + } else // Display force background? { background = cgs.media.forceIconBackground; } -/* if ((cg.iconDataPadSelectTime+WEAPON_SELECT_TIME)1) + prongLeftX = x2 + 97; + prongRightX = x2 + 544; + /* + if (!cg.iconDataPadHUDActive) { - cg.iconDataPadHUDActive = qtrue; - cg.iconDataPadHUDPercent=1; + t = cg.time - cg.iconDataPadSelectTime; + cg.iconDataPadHUDPercent = t/ 130.0f; + + // Calc how far into opening sequence we are + if (cg.iconDataPadHUDPercent>1) + { + cg.iconDataPadHUDActive = qtrue; + cg.iconDataPadHUDPercent=1; + } + else if (cg.iconDataPadHUDPercent<0) + { + cg.iconDataPadHUDPercent=0; + } } - else if (cg.iconDataPadHUDPercent<0) + else { - cg.iconDataPadHUDPercent=0; + cg.iconDataPadHUDPercent=1; } - } - else - { - cg.iconDataPadHUDPercent=1; - } -*/ - cgi_R_SetColor( colorTable[CT_WHITE] ); -// height = (int) (60.0f*cg.iconDataPadHUDPercent); - height = (int) 60.0f; - CG_DrawPic( x2+110, y2+30, 410, -height, background); // Top half - CG_DrawPic( x2+110, y2+30-2,410, height, background); // Bottom half + */ + cgi_R_SetColor(colorTable[CT_WHITE]); + // height = (int) (60.0f*cg.iconDataPadHUDPercent); + height = (int)60.0f; + CG_DrawPic(x2 + 110, y2 + 30, 410, -height, background); // Top half + CG_DrawPic(x2 + 110, y2 + 30 - 2, 410, height, background); // Bottom half // And now for the prongs - if (backgroundType==ICON_INVENTORY) - { + if (backgroundType == ICON_INVENTORY) { cgs.media.currentDataPadIconBackground = ICON_INVENTORY; background = cgs.media.inventoryProngsOn; - } - else if (backgroundType==ICON_WEAPONS) - { + } else if (backgroundType == ICON_WEAPONS) { cgs.media.currentDataPadIconBackground = ICON_WEAPONS; background = cgs.media.weaponProngsOn; - } - else - { + } else { cgs.media.currentDataPadIconBackground = ICON_FORCE; background = cgs.media.forceProngsOn; } // Side Prongs - cgi_R_SetColor( colorTable[CT_WHITE]); -// xAdd = (int) 8*cg.iconDataPadHUDPercent; - xAdd = (int) 8; - CG_DrawPic( prongLeftX+xAdd, y2-10, 40, 80, background); - CG_DrawPic( prongRightX-xAdd, y2-10, -40, 80, background); + cgi_R_SetColor(colorTable[CT_WHITE]); + // xAdd = (int) 8*cg.iconDataPadHUDPercent; + xAdd = (int)8; + CG_DrawPic(prongLeftX + xAdd, y2 - 10, 40, 80, background); + CG_DrawPic(prongRightX - xAdd, y2 - 10, -40, 80, background); } /* @@ -1787,18 +1590,15 @@ void CG_DrawDataPadIconBackground(int backgroundType) SetWeaponSelectTime =============== */ -void SetWeaponSelectTime(void) -{ +void SetWeaponSelectTime(void) { - if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Inventory HUD was currently active to just swap it out with Force HUD - ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD + if (((cg.inventorySelectTime + WEAPON_SELECT_TIME) > cg.time) || // The Inventory HUD was currently active to just swap it out with Force HUD + ((cg.forcepowerSelectTime + WEAPON_SELECT_TIME) > cg.time)) // The Force HUD was currently active to just swap it out with Force HUD { cg.inventorySelectTime = 0; cg.forcepowerSelectTime = 0; cg.weaponSelectTime = cg.time + 130.0f; - } - else - { + } else { cg.weaponSelectTime = cg.time; } } @@ -1808,80 +1608,72 @@ void SetWeaponSelectTime(void) CG_DrawWeaponSelect =================== */ -void CG_DrawWeaponSelect( void ) -{ - int i; - int bits; - int count; - int smallIconSize,bigIconSize; - int holdX,x,y,x2,y2,pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; - //int height; - vec4_t calcColor; - vec4_t textColor = { .875f, .718f, .121f, 1.0f }; - - if (!cgi_UI_GetMenuInfo("weaponselecthud",&x2,&y2)) - { +void CG_DrawWeaponSelect(void) { + int i; + int bits; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, x2, y2, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + // int height; + vec4_t calcColor; + vec4_t textColor = {.875f, .718f, .121f, 1.0f}; + + if (!cgi_UI_GetMenuInfo("weaponselecthud", &x2, &y2)) { return; } - if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)ps.stats[ STAT_WEAPONS ]; + bits = cg.snap->ps.stats[STAT_WEAPONS]; // count the number of weapons owned count = 0; - for ( i = 1 ; i < 16 ; i++ ) - { - if ( bits & ( 1 << i ) ) - { + for (i = 1; i < 16; i++) { + if (bits & (1 << i)) { count++; } } - if (count == 0) // If no weapons, don't display + if (count == 0) // If no weapons, don't display { return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.weaponSelect - 1; - if (i<1) - { + if (i < 1) { i = 13; } @@ -1895,167 +1687,138 @@ void CG_DrawWeaponSelect( void ) // Background memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); calcColor[3] = .60f; - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Left side ICONS - cgi_R_SetColor( calcColor); + cgi_R_SetColor(calcColor); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - //height = smallIconSize * cg.iconHUDPercent; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * cg.iconHUDPercent; - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i<1) - { + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 1) { i = 13; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - //height = bigIconSize * cg.iconHUDPercent; + // height = bigIconSize * cg.iconHUDPercent; cgi_R_SetColor(NULL); - if (weaponData[cg.weaponSelect].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( cg.weaponSelect ); + if (weaponData[cg.weaponSelect].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(cg.weaponSelect); weaponInfo = &cg_weapons[cg.weaponSelect]; - if (!CG_WeaponCheck(cg.weaponSelect)) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(cg.weaponSelect)) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, weaponInfo->weaponIcon); } } i = cg.weaponSelect + 1; - if (i> 13) - { + if (i > 13) { i = 1; } // Right side ICONS // Work forwards from current icon - cgi_R_SetColor( calcColor); - holdX = x + (bigIconSize/2) + pad; - //height = smallIconSize * cg.iconHUDPercent; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>13) - { + cgi_R_SetColor(calcColor); + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i > 13) { i = 1; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (weaponData[i].weaponIcon[0]) - { - weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); + if (weaponData[i].weaponIcon[0]) { + weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); weaponInfo = &cg_weapons[i]; // No ammo for this weapon? - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo ); - } - else - { - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, weaponInfo->weaponIcon ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIconNoAmmo); + } else { + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, weaponInfo->weaponIcon); } - - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } - gitem_t *item = cg_weapons[ cg.weaponSelect ].item; + gitem_t *item = cg_weapons[cg.weaponSelect].item; // draw the selected name - if ( item && item->classname && item->classname[0] ) - { + if (item && item->classname && item->classname[0]) { char text[1024]; - if ( cgi_SP_GetStringTextString( va("INGAME_%s",item->classname), text, sizeof( text ))) - { + if (cgi_SP_GetStringTextString(va("INGAME_%s", item->classname), text, sizeof(text))) { int w = cgi_R_Font_StrLenPixels(text, cgs.media.qhFontSmall, 1.0f); - int x = ( SCREEN_WIDTH - w ) / 2; + int x = (SCREEN_WIDTH - w) / 2; cgi_R_Font_DrawString(x, (SCREEN_HEIGHT - 24), text, textColor, cgs.media.qhFontSmall, -1, 1.0f); } } - cgi_R_SetColor( NULL ); + cgi_R_SetColor(NULL); } - /* =============== CG_WeaponSelectable =============== */ -qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) -{ - int usage_for_weap; +qboolean CG_WeaponSelectable(int i, int original, qboolean dpMode) { + int usage_for_weap; - if (i > MAX_PLAYER_WEAPONS) - { + if (i > MAX_PLAYER_WEAPONS) { #ifndef FINAL_BUILD - Com_Printf("CG_WeaponSelectable() passed illegal index of %d!\n",i); + Com_Printf("CG_WeaponSelectable() passed illegal index of %d!\n", i); #endif return qfalse; } - if ( cg.weaponSelectTime + 200 > cg.time ) - {//TEMP standard weapon cycle debounce for E3 because G2 can't keep up with fast weapon changes + if (cg.weaponSelectTime + 200 > cg.time) { // TEMP standard weapon cycle debounce for E3 because G2 can't keep up with fast weapon changes return qfalse; } - //FIXME: this doesn't work below, can still cycle too fast! - if ( original == WP_SABER && cg.weaponSelectTime + 500 > cg.time ) - {//when sqitch to lightsaber, have to stay there for at least half a second! + // FIXME: this doesn't work below, can still cycle too fast! + if (original == WP_SABER && cg.weaponSelectTime + 500 > cg.time) { // when sqitch to lightsaber, have to stay there for at least half a second! return qfalse; } - if (( weaponData[i].ammoIndex != AMMO_NONE ) && !dpMode ) - {//weapon uses ammo, see if we have any - usage_for_weap = weaponData[i].energyPerShot < weaponData[i].altEnergyPerShot - ? weaponData[i].energyPerShot - : weaponData[i].altEnergyPerShot; + if ((weaponData[i].ammoIndex != AMMO_NONE) && !dpMode) { // weapon uses ammo, see if we have any + usage_for_weap = weaponData[i].energyPerShot < weaponData[i].altEnergyPerShot ? weaponData[i].energyPerShot : weaponData[i].altEnergyPerShot; - if ( cg.snap->ps.ammo[weaponData[i].ammoIndex] - usage_for_weap < 0 ) - { - if ( i != WP_DET_PACK ) // detpack can be switched to...should possibly check if there are any stuck to a wall somewhere? + if (cg.snap->ps.ammo[weaponData[i].ammoIndex] - usage_for_weap < 0) { + if (i != WP_DET_PACK) // detpack can be switched to...should possibly check if there are any stuck to a wall somewhere? { // This weapon doesn't have enough ammo to shoot either the main or the alt-fire return qfalse; @@ -2063,8 +1826,7 @@ qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) } } - if (!(cg.snap->ps.stats[ STAT_WEAPONS ] & ( 1 << i ))) - { + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << i))) { // Don't have this weapon to start with. return qfalse; } @@ -2072,44 +1834,30 @@ qboolean CG_WeaponSelectable( int i, int original, qboolean dpMode ) return qtrue; } -void CG_ToggleATSTWeapon( void ) -{ - if ( cg.weaponSelect == WP_ATST_MAIN ) - { +void CG_ToggleATSTWeapon(void) { + if (cg.weaponSelect == WP_ATST_MAIN) { cg.weaponSelect = WP_ATST_SIDE; - } - else - { + } else { cg.weaponSelect = WP_ATST_MAIN; } -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); } -void CG_PlayerLockedWeaponSpeech( int jumping ) -{ -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); +void CG_PlayerLockedWeaponSpeech(int jumping) { + extern qboolean Q3_TaskIDPending(gentity_t * ent, taskID_t taskType); static int speechDebounceTime = 0; - if ( !in_camera ) - {//not in a cinematic - if ( speechDebounceTime < cg.time ) - {//spoke more than 3 seconds ago - if ( !Q3_TaskIDPending( &g_entities[0], TID_CHAN_VOICE ) ) - {//not waiting on a scripted sound to finish - if( !jumping ) - { - if( Q_flrand(0.0f, 1.0f) > 0.5 ) - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/09kyk015.wav" )); - } - else - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/09kyk016.wav" )); + if (!in_camera) { // not in a cinematic + if (speechDebounceTime < cg.time) { // spoke more than 3 seconds ago + if (!Q3_TaskIDPending(&g_entities[0], TID_CHAN_VOICE)) { // not waiting on a scripted sound to finish + if (!jumping) { + if (Q_flrand(0.0f, 1.0f) > 0.5) { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/09kyk015.wav")); + } else { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/09kyk016.wav")); } - } - else - { - G_SoundOnEnt( player, CHAN_VOICE, va( "sound/chars/kyle/16kyk007.wav" )); + } else { + G_SoundOnEnt(player, CHAN_VOICE, va("sound/chars/kyle/16kyk007.wav")); } speechDebounceTime = cg.time + 3000; } @@ -2121,11 +1869,11 @@ extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); CG_NextWeapon_f =============== */ -void CG_NextWeapon_f( void ) { - int i; - int original; +void CG_NextWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2134,48 +1882,41 @@ void CG_NextWeapon_f( void ) { } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } original = cg.weaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { cg.weaponSelect++; - if ( cg.weaponSelect < FIRST_WEAPON || cg.weaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.weaponSelect < FIRST_WEAPON || cg.weaponSelect > MAX_PLAYER_WEAPONS) { cg.weaponSelect = FIRST_WEAPON; } - if ( CG_WeaponSelectable( cg.weaponSelect, original, qfalse ) ) - { -// cg.weaponSelectTime = cg.time; + if (CG_WeaponSelectable(cg.weaponSelect, original, qfalse)) { + // cg.weaponSelectTime = cg.time; SetWeaponSelectTime(); return; } @@ -2189,11 +1930,11 @@ void CG_NextWeapon_f( void ) { CG_DPNextWeapon_f =============== */ -void CG_DPNextWeapon_f( void ) { - int i; - int original; +void CG_DPNextWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2204,16 +1945,14 @@ void CG_DPNextWeapon_f( void ) { original = cg.DataPadWeaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { cg.DataPadWeaponSelect++; - if ( cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { cg.DataPadWeaponSelect = FIRST_WEAPON; } - if ( CG_WeaponSelectable( cg.DataPadWeaponSelect, original, qtrue ) ) - { + if (CG_WeaponSelectable(cg.DataPadWeaponSelect, original, qtrue)) { return; } } @@ -2226,13 +1965,11 @@ void CG_DPNextWeapon_f( void ) { CG_DPPrevWeapon_f =============== */ -void CG_DPPrevWeapon_f( void ) -{ - int i; - int original; +void CG_DPPrevWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) - { + if (!cg.snap) { return; } @@ -2245,16 +1982,13 @@ void CG_DPPrevWeapon_f( void ) original = cg.DataPadWeaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) - { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { cg.DataPadWeaponSelect--; - if ( cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) - { + if (cg.DataPadWeaponSelect < FIRST_WEAPON || cg.DataPadWeaponSelect > MAX_PLAYER_WEAPONS) { cg.DataPadWeaponSelect = MAX_PLAYER_WEAPONS; } - if ( CG_WeaponSelectable( cg.DataPadWeaponSelect, original, qtrue ) ) - { + if (CG_WeaponSelectable(cg.DataPadWeaponSelect, original, qtrue)) { return; } } @@ -2267,11 +2001,11 @@ void CG_DPPrevWeapon_f( void ) CG_PrevWeapon_f =============== */ -void CG_PrevWeapon_f( void ) { - int i; - int original; +void CG_PrevWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2280,47 +2014,41 @@ void CG_PrevWeapon_f( void ) { } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } original = cg.weaponSelect; - for ( i = 0 ; i <= MAX_PLAYER_WEAPONS ; i++ ) { + for (i = 0; i <= MAX_PLAYER_WEAPONS; i++) { cg.weaponSelect--; - if ( cg.weaponSelect < FIRST_WEAPON || cg.weaponSelect > MAX_PLAYER_WEAPONS) { + if (cg.weaponSelect < FIRST_WEAPON || cg.weaponSelect > MAX_PLAYER_WEAPONS) { cg.weaponSelect = MAX_PLAYER_WEAPONS; } - if ( CG_WeaponSelectable( cg.weaponSelect, original, qfalse ) ) - { + if (CG_WeaponSelectable(cg.weaponSelect, original, qfalse)) { SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; return; } } @@ -2333,46 +2061,38 @@ void CG_ChangeWeapon( int num ) Meant to be called from the normal game, so checks the game-side weapon inventory data */ -void CG_ChangeWeapon( int num ) -{ - gentity_t *player = &g_entities[0]; +void CG_ChangeWeapon(int num) { + gentity_t *player = &g_entities[0]; - if ( num < WP_NONE || num >= WP_NUM_WEAPONS ) - { + if (num < WP_NONE || num >= WP_NUM_WEAPONS) { return; } - if( player->flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (player->flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if ( player->client != NULL && !(player->client->ps.stats[STAT_WEAPONS] & ( 1 << num )) ) - { - return; // don't have the weapon + if (player->client != NULL && !(player->client->ps.stats[STAT_WEAPONS] & (1 << num))) { + return; // don't have the weapon } // because we don't have an empty hand model for the thermal, don't allow selecting that weapon if it has no ammo - if ( num == WP_THERMAL ) - { - if ( cg.snap->ps.ammo[AMMO_THERMAL] <= 0 ) - { + if (num == WP_THERMAL) { + if (cg.snap->ps.ammo[AMMO_THERMAL] <= 0) { return; } } // because we don't have an empty hand model for the thermal, don't allow selecting that weapon if it has no ammo - if ( num == WP_TRIP_MINE ) - { - if ( cg.snap->ps.ammo[AMMO_TRIPMINE] <= 0 ) - { + if (num == WP_TRIP_MINE) { + if (cg.snap->ps.ammo[AMMO_TRIPMINE] <= 0) { return; } } SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; cg.weaponSelect = num; } @@ -2381,16 +2101,14 @@ void CG_ChangeWeapon( int num ) CG_Weapon_f =============== */ -void CG_Weapon_f( void ) -{ - int num; +void CG_Weapon_f(void) { + int num; - if ( cg.weaponSelectTime + 200 > cg.time ) - { + if (cg.weaponSelectTime + 200 > cg.time) { return; } - if ( !cg.snap ) { + if (!cg.snap) { return; } /* @@ -2399,102 +2117,82 @@ void CG_Weapon_f( void ) } */ - if( g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS ) - { - CG_PlayerLockedWeaponSpeech( qfalse ); + if (g_entities[0].flags & FL_LOCK_PLAYER_WEAPONS) { + CG_PlayerLockedWeaponSpeech(qfalse); return; } - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } - if ( cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (cg.snap->ps.eFlags & EF_LOCKED_TO_WEAPON) { // can't do any sort of weapon switching when in the emplaced gun return; } - if ( cg.snap->ps.viewEntity ) - { + if (cg.snap->ps.viewEntity) { // yeah, probably need a better check here - if ( g_entities[cg.snap->ps.viewEntity].client && ( g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 - || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE )) - { + if (g_entities[cg.snap->ps.viewEntity].client && + (g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R5D2 || g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_R2D2 || + g_entities[cg.snap->ps.viewEntity].client->NPC_class == CLASS_MOUSE)) { return; } } - num = atoi( CG_Argv( 1 ) ); + num = atoi(CG_Argv(1)); - if ( num < WP_NONE || num >= WP_NUM_WEAPONS ) { + if (num < WP_NONE || num >= WP_NUM_WEAPONS) { return; } - if ( num == WP_SABER ) - {//lightsaber - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - {//don't have saber, try stun baton + if (num == WP_SABER) { // lightsaber + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { // don't have saber, try stun baton num = WP_STUN_BATON; - } - else if ( num == cg.snap->ps.weapon ) - {//already have it up, let's try to toggle it - if ( !in_camera ) - {//player can't activate/deactivate saber when in a cinematic - //can't toggle it if not holding it and not controlling it or dead - if ( cg.predicted_player_state.stats[STAT_HEALTH] > 0 && (!cg_entities[0].currentState.saberInFlight || (&g_entities[cg_entities[0].gent->client->ps.saberEntityNum] != NULL && g_entities[cg_entities[0].gent->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR) ) ) - {//it's either in-hand or it's under telekinetic control - if ( cg_entities[0].currentState.saberActive ) - { + } else if (num == cg.snap->ps.weapon) { // already have it up, let's try to toggle it + if (!in_camera) { // player can't activate/deactivate saber when in a cinematic + // can't toggle it if not holding it and not controlling it or dead + if (cg.predicted_player_state.stats[STAT_HEALTH] > 0 && + (!cg_entities[0].currentState.saberInFlight || (&g_entities[cg_entities[0].gent->client->ps.saberEntityNum] != NULL && + g_entities[cg_entities[0].gent->client->ps.saberEntityNum].s.pos.trType == + TR_LINEAR))) { // it's either in-hand or it's under telekinetic control + if (cg_entities[0].currentState.saberActive) { cg_entities[0].gent->client->ps.saberActive = qfalse; - if ( cg_entities[0].currentState.saberInFlight ) - {//play it on the saber - cgi_S_UpdateEntityPosition( cg_entities[0].gent->client->ps.saberEntityNum, g_entities[cg_entities[0].gent->client->ps.saberEntityNum].currentOrigin ); - cgi_S_StartSound (NULL, cg_entities[0].gent->client->ps.saberEntityNum, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberoff.wav" ) ); - } - else - { - cgi_S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgi_S_RegisterSound( "sound/weapons/saber/saberoff.wav" ) ); + if (cg_entities[0].currentState.saberInFlight) { // play it on the saber + cgi_S_UpdateEntityPosition(cg_entities[0].gent->client->ps.saberEntityNum, + g_entities[cg_entities[0].gent->client->ps.saberEntityNum].currentOrigin); + cgi_S_StartSound(NULL, cg_entities[0].gent->client->ps.saberEntityNum, CHAN_AUTO, + cgi_S_RegisterSound("sound/weapons/saber/saberoff.wav")); + } else { + cgi_S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgi_S_RegisterSound("sound/weapons/saber/saberoff.wav")); } - } - else - { + } else { cg_entities[0].gent->client->ps.saberActive = qtrue; } } } } - } - else if ( num >= WP_THERMAL && num <= WP_DET_PACK ) // these weapons cycle + } else if (num >= WP_THERMAL && num <= WP_DET_PACK) // these weapons cycle { int weap, i = 0; - if ( cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK ) - { + if (cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK) { // already in cycle range so start with next cycle item weap = cg.snap->ps.weapon + 1; - } - else - { + } else { // not in cycle range, so start with thermal detonator weap = WP_THERMAL; } // prevent an endless loop - while ( i <= 4 ) - { - if ( weap > WP_DET_PACK ) - { + while (i <= 4) { + if (weap > WP_DET_PACK) { weap = WP_THERMAL; } - if ( cg.snap->ps.ammo[weaponData[weap].ammoIndex] > 0 || weap == WP_DET_PACK ) - { - if ( CG_WeaponSelectable( weap, cg.snap->ps.weapon, qfalse ) ) - { + if (cg.snap->ps.ammo[weaponData[weap].ammoIndex] > 0 || weap == WP_DET_PACK) { + if (CG_WeaponSelectable(weap, cg.snap->ps.weapon, qfalse)) { num = weap; break; } @@ -2505,12 +2203,12 @@ void CG_Weapon_f( void ) } } - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) { - return; // don't have the weapon + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { + return; // don't have the weapon } SetWeaponSelectTime(); -// cg.weaponSelectTime = cg.time; + // cg.weaponSelectTime = cg.time; cg.weaponSelect = num; } @@ -2521,46 +2219,37 @@ CG_OutOfAmmoChange The current weapon has just run out of ammo =================== */ -void CG_OutOfAmmoChange( void ) { - int i; - int original; +void CG_OutOfAmmoChange(void) { + int i; + int original; - if ( cg.weaponSelectTime + 200 > cg.time ) + if (cg.weaponSelectTime + 200 > cg.time) return; - if( g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST ) - { + if (g_entities[0].client && g_entities[0].client->NPC_class == CLASS_ATST) { CG_ToggleATSTWeapon(); return; } original = cg.weaponSelect; - for ( i = WP_ROCKET_LAUNCHER; i > 0 ; i-- ) - { + for (i = WP_ROCKET_LAUNCHER; i > 0; i--) { // We don't want the emplaced, melee, or explosive devices here - if ( original != i && CG_WeaponSelectable( i, original, qfalse ) ) - { + if (original != i && CG_WeaponSelectable(i, original, qfalse)) { SetWeaponSelectTime(); cg.weaponSelect = i; break; } } - if ( cg_autoswitch.integer != 1 ) - { + if (cg_autoswitch.integer != 1) { // didn't have that, so try these. Start with thermal... - for ( i = WP_THERMAL; i <= WP_DET_PACK; i++ ) - { + for (i = WP_THERMAL; i <= WP_DET_PACK; i++) { // We don't want the emplaced, or melee here - if ( original != i && CG_WeaponSelectable( i, original, qfalse ) ) - { - if ( i == WP_DET_PACK && cg.snap->ps.ammo[weaponData[i].ammoIndex] <= 0 ) - { + if (original != i && CG_WeaponSelectable(i, original, qfalse)) { + if (i == WP_DET_PACK && cg.snap->ps.ammo[weaponData[i].ammoIndex] <= 0) { // crap, no point in switching to this - } - else - { + } else { SetWeaponSelectTime(); cg.weaponSelect = i; break; @@ -2570,15 +2259,12 @@ void CG_OutOfAmmoChange( void ) { } // try stun baton as a last ditch effort - if ( CG_WeaponSelectable( WP_STUN_BATON, original, qfalse )) - { + if (CG_WeaponSelectable(WP_STUN_BATON, original, qfalse)) { SetWeaponSelectTime(); cg.weaponSelect = WP_STUN_BATON; } } - - /* =================================================================================================== @@ -2594,20 +2280,19 @@ CG_FireWeapon Caused by an EV_FIRE_WEAPON event ================ */ -void CG_FireWeapon( centity_t *cent, qboolean alt_fire ) -{ +void CG_FireWeapon(centity_t *cent, qboolean alt_fire) { entityState_t *ent; - //weaponInfo_t *weap; + // weaponInfo_t *weap; ent = ¢->currentState; - if ( ent->weapon == WP_NONE ) { + if (ent->weapon == WP_NONE) { return; } - if ( ent->weapon >= WP_NUM_WEAPONS ) { - CG_Error( "CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS" ); + if (ent->weapon >= WP_NUM_WEAPONS) { + CG_Error("CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS"); return; } - //weap = &cg_weapons[ ent->weapon ]; + // weap = &cg_weapons[ ent->weapon ]; // mark the entity as muzzle flashing, so when it is added it will // append the flash to the weapon model @@ -2615,64 +2300,62 @@ void CG_FireWeapon( centity_t *cent, qboolean alt_fire ) cent->altFire = alt_fire; // lightning type guns only does this this on initial press - if ( ent->weapon == WP_SABER ) - { - if ( cent->pe.lightningFiring ) - { -/* if ( ent->weapon == WP_DREADNOUGHT ) - { - cgi_FF_EnsureFX( fffx_Laser3 ); - } -*/ + if (ent->weapon == WP_SABER) { + if (cent->pe.lightningFiring) { + /* if ( ent->weapon == WP_DREADNOUGHT ) + { + cgi_FF_EnsureFX( fffx_Laser3 ); + } + */ return; } } // Do overcharge sound that get's added to the top -/* if (( ent->powerups & ( 1<powerups & ( 1<weapon ) + if ( alt_fire ) { - case WP_THERMAL: - case WP_DET_PACK: - case WP_TRIP_MINE: - case WP_ROCKET_LAUNCHER: - case WP_FLECHETTE: - // these weapon fires don't overcharge - break; - - case WP_BLASTER: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); - break; - - default: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); - break; + switch( ent->weapon ) + { + case WP_THERMAL: + case WP_DET_PACK: + case WP_TRIP_MINE: + case WP_ROCKET_LAUNCHER: + case WP_FLECHETTE: + // these weapon fires don't overcharge + break; + + case WP_BLASTER: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); + break; + + default: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); + break; + } } - } - else - { - switch( ent->weapon ) + else { - case WP_THERMAL: - case WP_DET_PACK: - case WP_TRIP_MINE: - case WP_ROCKET_LAUNCHER: - // these weapon fires don't overcharge - break; - - case WP_REPEATER: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); - break; - - default: - cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); - break; + switch( ent->weapon ) + { + case WP_THERMAL: + case WP_DET_PACK: + case WP_TRIP_MINE: + case WP_ROCKET_LAUNCHER: + // these weapon fires don't overcharge + break; + + case WP_REPEATER: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeFastSound ); + break; + + default: + cgi_S_StartSound( NULL, ent->number, CHAN_AUTO, cgs.media.overchargeSlowSound ); + break; + } } - } - }*/ + }*/ } /* @@ -2682,44 +2365,41 @@ CG_BounceEffect Caused by an EV_BOUNCE | EV_BOUNCE_HALF event ================= */ -void CG_BounceEffect( centity_t *cent, int weapon, vec3_t origin, vec3_t normal ) -{ - switch( weapon ) - { +void CG_BounceEffect(centity_t *cent, int weapon, vec3_t origin, vec3_t normal) { + switch (weapon) { case WP_THERMAL: - if ( rand() & 1 ) { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1 ); + if (rand() & 1) { + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1); } else { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2 ); + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2); } break; case WP_BOWCASTER: - theFxScheduler.PlayEffect( cgs.effects.bowcasterBounceEffect, origin, normal ); + theFxScheduler.PlayEffect(cgs.effects.bowcasterBounceEffect, origin, normal); break; case WP_FLECHETTE: - theFxScheduler.PlayEffect( "flechette/ricochet", origin, normal ); + theFxScheduler.PlayEffect("flechette/ricochet", origin, normal); break; default: - if ( rand() & 1 ) { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1 ); + if (rand() & 1) { + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce1); } else { - cgi_S_StartSound( origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2 ); + cgi_S_StartSound(origin, ENTITYNUM_WORLD, CHAN_AUTO, cgs.media.grenadeBounce2); } break; } } //---------------------------------------------------------------------- -void CG_MissileStick( centity_t *cent, int weapon, vec3_t position ) +void CG_MissileStick(centity_t *cent, int weapon, vec3_t position) //---------------------------------------------------------------------- { sfxHandle_t snd = 0; - switch( weapon ) - { + switch (weapon) { case WP_FLECHETTE: snd = cgs.media.flechetteStickSound; break; @@ -2733,9 +2413,8 @@ void CG_MissileStick( centity_t *cent, int weapon, vec3_t position ) break; } - if ( snd ) - { - cgi_S_StartSound( NULL, cent->currentState.number, CHAN_AUTO, snd ); + if (snd) { + cgi_S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, snd); } } @@ -2746,108 +2425,90 @@ CG_MissileHitWall Caused by an EV_MISSILE_MISS event, or directly by local bullet tracing ================= */ -void CG_MissileHitWall( centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire ) -{ +void CG_MissileHitWall(centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire) { int parm; - switch( weapon ) - { + switch (weapon) { case WP_BRYAR_PISTOL: - if ( altFire ) - { + if (altFire) { parm = 0; - if ( cent->gent ) - { + if (cent->gent) { parm += cent->gent->count; } - FX_BryarAltHitWall( origin, dir, parm ); - } - else - { - FX_BryarHitWall( origin, dir ); + FX_BryarAltHitWall(origin, dir, parm); + } else { + FX_BryarHitWall(origin, dir); } break; case WP_BLASTER: - FX_BlasterWeaponHitWall( origin, dir ); + FX_BlasterWeaponHitWall(origin, dir); break; case WP_BOWCASTER: - FX_BowcasterHitWall( origin, dir ); + FX_BowcasterHitWall(origin, dir); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitWall( origin, dir ); - } - else - { - FX_RepeaterHitWall( origin, dir ); + if (altFire) { + FX_RepeaterAltHitWall(origin, dir); + } else { + FX_RepeaterHitWall(origin, dir); } break; case WP_DEMP2: - if ( altFire ) - { - } - else - { - FX_DEMP2_HitWall( origin, dir ); + if (altFire) { + } else { + FX_DEMP2_HitWall(origin, dir); } break; case WP_FLECHETTE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "flechette/alt_blow", origin, dir ); - } - else - { - FX_FlechetteWeaponHitWall( origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("flechette/alt_blow", origin, dir); + } else { + FX_FlechetteWeaponHitWall(origin, dir); } break; case WP_ROCKET_LAUNCHER: - FX_RocketHitWall( origin, dir ); + FX_RocketHitWall(origin, dir); break; case WP_THERMAL: - theFxScheduler.PlayEffect( "thermal/explosion", origin, dir ); - theFxScheduler.PlayEffect( "thermal/shockwave", origin ); + theFxScheduler.PlayEffect("thermal/explosion", origin, dir); + theFxScheduler.PlayEffect("thermal/shockwave", origin); break; case WP_EMPLACED_GUN: - FX_EmplacedHitWall( origin, dir ); + FX_EmplacedHitWall(origin, dir); break; case WP_ATST_MAIN: - FX_ATSTMainHitWall( origin, dir ); + FX_ATSTMainHitWall(origin, dir); break; case WP_ATST_SIDE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "atst/side_alt_explosion", origin, dir ); - } - else - { - theFxScheduler.PlayEffect( "atst/side_main_impact", origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("atst/side_alt_explosion", origin, dir); + } else { + theFxScheduler.PlayEffect("atst/side_main_impact", origin, dir); } break; case WP_TRIP_MINE: - theFxScheduler.PlayEffect( "tripmine/explosion", origin, dir ); + theFxScheduler.PlayEffect("tripmine/explosion", origin, dir); break; case WP_DET_PACK: - theFxScheduler.PlayEffect( "detpack/explosion", origin, dir ); + theFxScheduler.PlayEffect("detpack/explosion", origin, dir); break; case WP_TURRET: - theFxScheduler.PlayEffect( "turret/wall_impact", origin, dir ); + theFxScheduler.PlayEffect("turret/wall_impact", origin, dir); break; } } @@ -2858,122 +2519,102 @@ CG_MissileHitPlayer ------------------------- */ -void CG_MissileHitPlayer( centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire ) -{ +void CG_MissileHitPlayer(centity_t *cent, int weapon, vec3_t origin, vec3_t dir, qboolean altFire) { gentity_t *other = NULL; - qboolean humanoid = qtrue; + qboolean humanoid = qtrue; - if ( cent->gent ) - { + if (cent->gent) { other = &g_entities[cent->gent->s.otherEntityNum]; - if( other->client ) - { - class_t npc_class = other->client->NPC_class; + if (other->client) { + class_t npc_class = other->client->NPC_class; // check for all droids, maybe check for certain monsters if they're considered non-humanoid..? - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { humanoid = qfalse; } } } - switch( weapon ) - { + switch (weapon) { case WP_BRYAR_PISTOL: - if ( altFire ) - { - FX_BryarAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_BryarHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_BryarAltHitPlayer(origin, dir, humanoid); + } else { + FX_BryarHitPlayer(origin, dir, humanoid); } break; case WP_BLASTER: - FX_BlasterWeaponHitPlayer( origin, dir, humanoid ); + FX_BlasterWeaponHitPlayer(origin, dir, humanoid); break; case WP_BOWCASTER: - FX_BowcasterHitPlayer( origin, dir, humanoid ); + FX_BowcasterHitPlayer(origin, dir, humanoid); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_RepeaterHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_RepeaterAltHitPlayer(origin, dir, humanoid); + } else { + FX_RepeaterHitPlayer(origin, dir, humanoid); } break; case WP_DEMP2: - if ( !altFire ) - { - FX_DEMP2_HitPlayer( origin, dir, humanoid ); + if (!altFire) { + FX_DEMP2_HitPlayer(origin, dir, humanoid); } // Do a full body effect here for some more feedback - if ( other && other->client ) - { - other->s.powerups |= ( 1 << PW_SHOCKED ); + if (other && other->client) { + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = cg.time + 1000; } break; case WP_FLECHETTE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "flechette/alt_blow", origin, dir ); - } - else - { - FX_FlechetteWeaponHitPlayer( origin, dir, humanoid ); + if (altFire) { + theFxScheduler.PlayEffect("flechette/alt_blow", origin, dir); + } else { + FX_FlechetteWeaponHitPlayer(origin, dir, humanoid); } break; case WP_ROCKET_LAUNCHER: - FX_RocketHitPlayer( origin, dir, humanoid ); + FX_RocketHitPlayer(origin, dir, humanoid); break; case WP_THERMAL: - theFxScheduler.PlayEffect( "thermal/explosion", origin, dir ); - theFxScheduler.PlayEffect( "thermal/shockwave", origin ); + theFxScheduler.PlayEffect("thermal/explosion", origin, dir); + theFxScheduler.PlayEffect("thermal/shockwave", origin); break; case WP_EMPLACED_GUN: - FX_EmplacedHitWall( origin, dir ); + FX_EmplacedHitWall(origin, dir); break; case WP_TRIP_MINE: - theFxScheduler.PlayEffect( "tripmine/explosion", origin, dir ); + theFxScheduler.PlayEffect("tripmine/explosion", origin, dir); break; case WP_DET_PACK: - theFxScheduler.PlayEffect( "detpack/explosion", origin, dir ); + theFxScheduler.PlayEffect("detpack/explosion", origin, dir); break; case WP_TURRET: - theFxScheduler.PlayEffect( "turret/flesh_impact", origin, dir ); + theFxScheduler.PlayEffect("turret/flesh_impact", origin, dir); break; case WP_ATST_MAIN: - FX_EmplacedHitWall( origin, dir ); + FX_EmplacedHitWall(origin, dir); break; case WP_ATST_SIDE: - if ( altFire ) - { - theFxScheduler.PlayEffect( "atst/side_alt_explosion", origin, dir ); - } - else - { - theFxScheduler.PlayEffect( "atst/side_main_impact", origin, dir ); + if (altFire) { + theFxScheduler.PlayEffect("atst/side_alt_explosion", origin, dir); + } else { + theFxScheduler.PlayEffect("atst/side_main_impact", origin, dir); } break; } diff --git a/codeJK2/game/AI_Atst.cpp b/codeJK2/game/AI_Atst.cpp index 952e8b4aa5..111430f463 100644 --- a/codeJK2/game/AI_Atst.cpp +++ b/codeJK2/game/AI_Atst.cpp @@ -21,59 +21,53 @@ along with this program; if not, see . */ #include "g_headers.h" - -#include "b_local.h" +#include "b_local.h" -#define MIN_MELEE_RANGE 640 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 640 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define TURN_OFF 0x00000100//G2SURFACEFLAG_NODESCENDANTS +#define TURN_OFF 0x00000100 // G2SURFACEFLAG_NODESCENDANTS #define LEFT_ARM_HEALTH 40 #define RIGHT_ARM_HEALTH 40 -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); /* ------------------------- NPC_ATST_Precache ------------------------- */ -void NPC_ATST_Precache(void) -{ - G_SoundIndex( "sound/chars/atst/atst_damaged1" ); - G_SoundIndex( "sound/chars/atst/atst_damaged2" ); - - RegisterItem( FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon - - G_EffectIndex( "env/med_explode2" ); -// G_EffectIndex( "smaller_chunks" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "droidexplosion1" ); +void NPC_ATST_Precache(void) { + G_SoundIndex("sound/chars/atst/atst_damaged1"); + G_SoundIndex("sound/chars/atst/atst_damaged2"); + + RegisterItem(FindItemForWeapon(WP_ATST_MAIN)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_BOWCASTER)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_ROCKET_LAUNCHER)); // precache the weapon + + G_EffectIndex("env/med_explode2"); + // G_EffectIndex( "smaller_chunks" ); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("droidexplosion1"); } //----------------------------------------------------------------- -static void ATST_PlayEffect( gentity_t *self, const int boltID, const char *fx ) -{ - if ( boltID >=0 && fx && fx[0] ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +static void ATST_PlayEffect(gentity_t *self, const int boltID, const char *fx) { + if (boltID >= 0 && fx && fx[0]) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - boltID, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, boltID, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( fx, org, dir ); + G_PlayEffect(fx, org, dir); } } @@ -85,47 +79,38 @@ Called by NPC's and player in an ATST ------------------------- */ -void G_ATSTCheckPain( gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ +void G_ATSTCheckPain(gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { int newBolt; - - if ( rand() & 1 ) - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1" ); - } - else - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2" ); + + if (rand() & 1) { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1"); + } else { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2"); } - if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) - { - if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? + if ((hitLoc == HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { + if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash3" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt1, self->s.number); - ATST_PlayEffect( self, self->genericBolt1, "env/med_explode2" ); - G_PlayEffect( "blaster/smoke_bolton", self->playerModel, newBolt, self->s.number); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash3"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt1, self->s.number); + ATST_PlayEffect(self, self->genericBolt1, "env/med_explode2"); + G_PlayEffect("blaster/smoke_bolton", self->playerModel, newBolt, self->s.number); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_light_blaster_cann", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_light_blaster_cann", TURN_OFF); } - } - else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? + } else if ((hitLoc == HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash4" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); - ATST_PlayEffect( self, self->genericBolt2, "env/med_explode2" ); - G_PlayEffect( "blaster/smoke_bolton", self->playerModel, newBolt, self->s.number); + if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash4"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); + ATST_PlayEffect(self, self->genericBolt2, "env/med_explode2"); + G_PlayEffect("blaster/smoke_bolton", self->playerModel, newBolt, self->s.number); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_concussion_charger", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_concussion_charger", TURN_OFF); } } } @@ -134,10 +119,9 @@ void G_ATSTCheckPain( gentity_t *self, gentity_t *other, vec3_t point, int damag NPC_ATST_Pain ------------------------- */ -void NPC_ATST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - G_ATSTCheckPain( self, other, point, damage, mod, hitLoc ); - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_ATST_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + G_ATSTCheckPain(self, other, point, damage, mod, hitLoc); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -145,18 +129,15 @@ void NPC_ATST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec ATST_Hunt -------------------------` */ -void ATST_Hunt( qboolean visible, qboolean advance ) -{ +void ATST_Hunt(qboolean visible, qboolean advance) { - if ( NPCInfo->goalEntity == NULL ) - {//hunt + if (NPCInfo->goalEntity == NULL) { // hunt NPCInfo->goalEntity = NPC->enemy; } NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); - + NPC_MoveToGoal(qtrue); } /* @@ -164,26 +145,21 @@ void ATST_Hunt( qboolean visible, qboolean advance ) ATST_Ranged ------------------------- */ -void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) -{ +void ATST_Ranged(qboolean visible, qboolean advance, qboolean altAttack) { - if ( TIMER_Done( NPC, "atkDelay" ) && visible ) // Attack? + if (TIMER_Done(NPC, "atkDelay") && visible) // Attack? { - TIMER_Set( NPC, "atkDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPC, "atkDelay", Q_irand(500, 3000)); - if (altAttack) - { - ucmd.buttons |= BUTTON_ATTACK|BUTTON_ALT_ATTACK; - } - else - { + if (altAttack) { + ucmd.buttons |= BUTTON_ATTACK | BUTTON_ALT_ATTACK; + } else { ucmd.buttons |= BUTTON_ATTACK; } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); } } @@ -192,83 +168,72 @@ void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) ATST_Attack ------------------------- */ -void ATST_Attack( void ) -{ - qboolean altAttack=qfalse; - int blasterTest,chargerTest,weapon; +void ATST_Attack(void) { + qboolean altAttack = qfalse; + int blasterTest, chargerTest, weapon; - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; return; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + distance_e distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); return; } } // Decide what type of attack to do - switch ( distRate ) - { + switch (distRate) { case DIST_MELEE: - NPC_ChangeWeapon( WP_ATST_MAIN ); + NPC_ChangeWeapon(WP_ATST_MAIN); break; case DIST_LONG: - NPC_ChangeWeapon( WP_ATST_SIDE ); + NPC_ChangeWeapon(WP_ATST_SIDE); // See if the side weapons are there - blasterTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head_light_blaster_cann" ); - chargerTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head_concussion_charger" ); + blasterTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head_light_blaster_cann"); + chargerTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head_concussion_charger"); // It has both side weapons - if (!(blasterTest & TURN_OFF) && !(chargerTest & TURN_OFF)) - { - weapon = Q_irand( 0, 1); // 0 is blaster, 1 is charger (ALT SIDE) + if (!(blasterTest & TURN_OFF) && !(chargerTest & TURN_OFF)) { + weapon = Q_irand(0, 1); // 0 is blaster, 1 is charger (ALT SIDE) - if (weapon) // Fire charger + if (weapon) // Fire charger { altAttack = qtrue; - } - else - { + } else { altAttack = qfalse; } - } - else if (!(blasterTest & TURN_OFF)) // Blaster is on + } else if (!(blasterTest & TURN_OFF)) // Blaster is on { altAttack = qfalse; - } - else if (!(chargerTest & TURN_OFF)) // Blaster is on + } else if (!(chargerTest & TURN_OFF)) // Blaster is on { altAttack = qtrue; - } - else - { - NPC_ChangeWeapon( WP_NONE ); + } else { + NPC_ChangeWeapon(WP_NONE); } break; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - ATST_Ranged( visible, advance,altAttack ); + ATST_Ranged(visible, advance, altAttack); } /* @@ -276,25 +241,20 @@ void ATST_Attack( void ) ATST_Patrol ------------------------- */ -void ATST_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void ATST_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } } - } /* @@ -302,12 +262,11 @@ void ATST_Patrol( void ) ATST_Idle ------------------------- */ -void ATST_Idle( void ) -{ +void ATST_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); } /* @@ -315,22 +274,15 @@ void ATST_Idle( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSATST_Default( void ) -{ - if ( NPC->enemy ) - { - if( (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) ) - { +void NPC_BSATST_Default(void) { + if (NPC->enemy) { + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { NPCInfo->goalEntity = NPC->enemy; } ATST_Attack(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ATST_Patrol(); - } - else - { + } else { ATST_Idle(); } } diff --git a/codeJK2/game/AI_Default.cpp b/codeJK2/game/AI_Default.cpp index 55ddda93c3..df66b31407 100644 --- a/codeJK2/game/AI_Default.cpp +++ b/codeJK2/game/AI_Default.cpp @@ -25,9 +25,9 @@ along with this program; if not, see . #include "Q3_Interface.h" //#include "anims.h" -//extern int PM_AnimLength( int index, animNumber_t anim ); -//extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -//extern int PM_AnimLength( int index, animNumber_t anim ); +// extern int PM_AnimLength( int index, animNumber_t anim ); +// extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); +// extern int PM_AnimLength( int index, animNumber_t anim ); //#define MAX_IDLE_ANIMS 8 extern int g_crosshairEntNum; @@ -37,23 +37,20 @@ void NPC_LostEnemyDecideChase(void) We lost our enemy and want to drop him but see if we should chase him if we are in the proper bState */ -void NPC_LostEnemyDecideChase(void) -{ - switch( NPCInfo->behaviorState ) - { +void NPC_LostEnemyDecideChase(void) { + switch (NPCInfo->behaviorState) { case BS_HUNT_AND_KILL: - //We were chasing him and lost him, so try to find him - if ( NPC->enemy == NPCInfo->goalEntity && NPC->enemy->lastWaypoint != WAYPOINT_NONE ) - {//Remember his last valid Wp, then check it out - //FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? - NPC_BSSearchStart( NPC->enemy->lastWaypoint, BS_SEARCH ); + // We were chasing him and lost him, so try to find him + if (NPC->enemy == NPCInfo->goalEntity && NPC->enemy->lastWaypoint != WAYPOINT_NONE) { // Remember his last valid Wp, then check it out + // FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? + NPC_BSSearchStart(NPC->enemy->lastWaypoint, BS_SEARCH); } - //If he's not our goalEntity, we're running somewhere else, so lose him + // If he's not our goalEntity, we're running somewhere else, so lose him break; default: break; } - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); } /* ------------------------- @@ -61,99 +58,86 @@ NPC_StandIdle ------------------------- */ -void NPC_StandIdle( void ) -{ -/* - //Must be done with any other animations - if ( NPC->client->ps.legsAnimTimer != 0 ) - return; +void NPC_StandIdle(void) { + /* + //Must be done with any other animations + if ( NPC->client->ps.legsAnimTimer != 0 ) + return; - //Not ready to do another one - if ( TIMER_Done( NPC, "idleAnim" ) == false ) - return; + //Not ready to do another one + if ( TIMER_Done( NPC, "idleAnim" ) == false ) + return; - int anim = NPC->client->ps.legsAnim; + int anim = NPC->client->ps.legsAnim; - if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) - return; + if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) + return; - //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly - int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; + //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly + int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; - //Must have at least one random idle animation - //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay - if ( PM_HasAnimation( NPC, baseSeq ) == false ) - return; + //Must have at least one random idle animation + //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay + if ( PM_HasAnimation( NPC, baseSeq ) == false ) + return; - int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); + int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); - //FIXME: Technically this could never complete.. but that's not really too likely - while( 1 ) - { - if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) - break; + //FIXME: Technically this could never complete.. but that's not really too likely + while( 1 ) + { + if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) + break; - newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); - } - - //Start that animation going - NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - - int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); + newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); + } - //Don't do this again for a random amount of time - TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); -*/ + //Start that animation going + NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + + int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); + + //Don't do this again for a random amount of time + TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); + */ } -qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) -{ - qboolean attack_ok = qfalse; - qboolean duck_ok = qfalse; - qboolean faced = qfalse; - float attack_scale = 1.0; - - //First see if we're hurt bad- if so, duck - //FIXME: if even when ducked, we can shoot someone, we should. - //Maybe is can be shot even when ducked, we should run away to the nearest cover? - if ( canDuck ) - { - if ( NPC->health < 20 ) - { - // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) - if( Q_flrand(0.0f, 1.0f) ) - { +qboolean NPC_StandTrackAndShoot(gentity_t *NPC, qboolean canDuck) { + qboolean attack_ok = qfalse; + qboolean duck_ok = qfalse; + qboolean faced = qfalse; + float attack_scale = 1.0; + + // First see if we're hurt bad- if so, duck + // FIXME: if even when ducked, we can shoot someone, we should. + // Maybe is can be shot even when ducked, we should run away to the nearest cover? + if (canDuck) { + if (NPC->health < 20) { + // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) + if (Q_flrand(0.0f, 1.0f)) { duck_ok = qtrue; } - } - else if ( NPC->health < 40 ) - { -// if ( NPC->svFlags&SVF_HEALING ) -// {//Medic is on the way, get down! -// duck_ok = qtrue; -// } + } else if (NPC->health < 40) { + // if ( NPC->svFlags&SVF_HEALING ) + // {//Medic is on the way, get down! + // duck_ok = qtrue; + // } } } - //NPC_CheckEnemy( qtrue, qfalse ); + // NPC_CheckEnemy( qtrue, qfalse ); - if ( !duck_ok ) - {//made this whole part a function call - attack_ok = NPC_CheckCanAttack( attack_scale, qtrue ); + if (!duck_ok) { // made this whole part a function call + attack_ok = NPC_CheckCanAttack(attack_scale, qtrue); faced = qtrue; } - if ( canDuck && (duck_ok || (!attack_ok && client->fireDelay == 0)) && ucmd.upmove != -127 ) - {//if we didn't attack check to duck if we're not already - if( !duck_ok ) - { - if ( NPC->enemy->client ) - { - if ( NPC->enemy->enemy == NPC ) - { - if ( NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? + if (canDuck && (duck_ok || (!attack_ok && client->fireDelay == 0)) && ucmd.upmove != -127) { // if we didn't attack check to duck if we're not already + if (!duck_ok) { + if (NPC->enemy->client) { + if (NPC->enemy->enemy == NPC) { + if (NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? { duck_ok = qtrue; } @@ -162,85 +146,67 @@ qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) } } - if ( duck_ok ) - {//duck and don't shoot + if (duck_ok) { // duck and don't shoot attack_ok = qfalse; ucmd.upmove = -127; - NPCInfo->duckDebounceTime = level.time + 1000;//duck for a full second + NPCInfo->duckDebounceTime = level.time + 1000; // duck for a full second } } return faced; } - -void NPC_BSIdle( void ) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSIdle(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - if ( ( ucmd.forwardmove == 0 ) && ( ucmd.rightmove == 0 ) && ( ucmd.upmove == 0 ) ) - { -// NPC_StandIdle(); + if ((ucmd.forwardmove == 0) && (ucmd.rightmove == 0) && (ucmd.upmove == 0)) { + // NPC_StandIdle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); ucmd.buttons |= BUTTON_WALKING; } -void NPC_BSRun (void) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSRun(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSStandGuard (void) -{ - //FIXME: Use Snapshot info - if ( NPC->enemy == NULL ) - {//Possible to pick one up by being shot - if( Q_flrand(0.0f, 1.0f) < 0.5 ) - { - if(NPC->client->enemyTeam) - { - gentity_t *newenemy = NPC_PickEnemy( - NPC, NPC->client->enemyTeam, - (qboolean)(NPC->cantHitEnemyCounter < 10), - (qboolean)(NPC->client->enemyTeam == TEAM_PLAYER), - qtrue); - //only checks for vis if couldn't hit last enemy - if(newenemy) - { - G_SetEnemy( NPC, newenemy ); +void NPC_BSStandGuard(void) { + // FIXME: Use Snapshot info + if (NPC->enemy == NULL) { // Possible to pick one up by being shot + if (Q_flrand(0.0f, 1.0f) < 0.5) { + if (NPC->client->enemyTeam) { + gentity_t *newenemy = NPC_PickEnemy(NPC, NPC->client->enemyTeam, (qboolean)(NPC->cantHitEnemyCounter < 10), + (qboolean)(NPC->client->enemyTeam == TEAM_PLAYER), qtrue); + // only checks for vis if couldn't hit last enemy + if (newenemy) { + G_SetEnemy(NPC, newenemy); } } } } - if ( NPC->enemy != NULL ) - { - if( NPCInfo->tempBehavior == BS_STAND_GUARD ) - { + if (NPC->enemy != NULL) { + if (NPCInfo->tempBehavior == BS_STAND_GUARD) { NPCInfo->tempBehavior = BS_DEFAULT; } - - if( NPCInfo->behaviorState == BS_STAND_GUARD ) - { + + if (NPCInfo->behaviorState == BS_STAND_GUARD) { NPCInfo->behaviorState = BS_STAND_AND_SHOOT; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -249,92 +215,77 @@ NPC_BSHuntAndKill ------------------------- */ -void NPC_BSHuntAndKill( void ) -{ - qboolean turned = qfalse; - vec3_t vec; - float enemyDist; - visibility_t oEVis; - int curAnim; - - NPC_CheckEnemy( (qboolean)(NPCInfo->tempBehavior != BS_HUNT_AND_KILL), qfalse );//don't find new enemy if this is tempbehav - - if ( NPC->enemy ) - { - oEVis = enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|//CHECK_PVS| - if(enemyVisibility > VIS_PVS) - { - if ( !NPC_EnemyTooFar( NPC->enemy, 0, qtrue ) ) - {//Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for info on whether ot not to turn later - NPC_CheckCanAttack( 1.0, qfalse ); +void NPC_BSHuntAndKill(void) { + qboolean turned = qfalse; + vec3_t vec; + float enemyDist; + visibility_t oEVis; + int curAnim; + + NPC_CheckEnemy((qboolean)(NPCInfo->tempBehavior != BS_HUNT_AND_KILL), qfalse); // don't find new enemy if this is tempbehav + + if (NPC->enemy) { + oEVis = enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|//CHECK_PVS| + if (enemyVisibility > VIS_PVS) { + if (!NPC_EnemyTooFar(NPC->enemy, 0, qtrue)) { // Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for + // info on whether ot not to turn later + NPC_CheckCanAttack(1.0, qfalse); turned = qtrue; } } curAnim = NPC->client->ps.legsAnim; - if(curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 ) - {//Don't move toward enemy if we're in a full-body attack anim - //FIXME, use IdealDistance to determin if we need to close distance + if (curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && + curAnim != BOTH_MELEE2) { // Don't move toward enemy if we're in a full-body attack anim + // FIXME, use IdealDistance to determin if we need to close distance VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); enemyDist = VectorLength(vec); - if( enemyDist > 48 && ((enemyDist*1.5)*(enemyDist*1.5) >= NPC_MaxDistSquaredForWeapon() || - oEVis != VIS_SHOOT || - //!(ucmd.buttons & BUTTON_ATTACK) || - enemyDist > IdealDistance(NPC)*3 ) ) - {//We should close in? + if (enemyDist > 48 && ((enemyDist * 1.5) * (enemyDist * 1.5) >= NPC_MaxDistSquaredForWeapon() || oEVis != VIS_SHOOT || + //!(ucmd.buttons & BUTTON_ATTACK) || + enemyDist > IdealDistance(NPC) * 3)) { // We should close in? NPCInfo->goalEntity = NPC->enemy; - NPC_MoveToGoal( qtrue ); - } - else if(enemyDist < IdealDistance(NPC)) - {//We should back off? - //if(ucmd.buttons & BUTTON_ATTACK) + NPC_MoveToGoal(qtrue); + } else if (enemyDist < IdealDistance(NPC)) { // We should back off? + // if(ucmd.buttons & BUTTON_ATTACK) { NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); ucmd.forwardmove *= -1; ucmd.rightmove *= -1; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); ucmd.buttons |= BUTTON_WALKING; } - }//otherwise, stay where we are + } // otherwise, stay where we are } - } - else - {//ok, stand guard until we find an enemy - if( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { + } else { // ok, stand guard until we find an enemy + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } return; } - if(!turned) - { + if (!turned) { NPC_UpdateAngles(qtrue, qtrue); } } -void NPC_BSStandAndShoot (void) -{ - //FIXME: - //When our numbers outnumber enemies 3 to 1, or only one of them, - //go into hunt and kill mode +void NPC_BSStandAndShoot(void) { + // FIXME: + // When our numbers outnumber enemies 3 to 1, or only one of them, + // go into hunt and kill mode - //FIXME: - //When they're all dead, go to some script or wander off to sickbay? - - if(NPC->client->playerTeam && NPC->client->enemyTeam) - { - //FIXME: don't realize this right away- or else enemies show up and we're standing around + // FIXME: + // When they're all dead, go to some script or wander off to sickbay? + + if (NPC->client->playerTeam && NPC->client->enemyTeam) { + // FIXME: don't realize this right away- or else enemies show up and we're standing around /* if( teamNumbers[NPC->enemyTeam] == 0 ) {//ok, stand guard until we find another enemy @@ -382,37 +333,30 @@ void NPC_BSStandAndShoot (void) } NPC_CheckEnemy(qtrue, qfalse); - - if(NPCInfo->duckDebounceTime > level.time && NPC->client->ps.weapon != WP_SABER ) - { + + if (NPCInfo->duckDebounceTime > level.time && NPC->client->ps.weapon != WP_SABER) { ucmd.upmove = -127; - if(NPC->enemy) - { + if (NPC->enemy) { NPC_CheckCanAttack(1.0, qtrue); } - return; + return; } - if(NPC->enemy) - { - if(!NPC_StandTrackAndShoot( NPC, qtrue )) - {//That func didn't update our angles + if (NPC->enemy) { + if (!NPC_StandTrackAndShoot(NPC, qtrue)) { // That func didn't update our angles NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); } - } - else - { + } else { NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); -// NPC_BSIdle();//only moves if we have a goal + // NPC_BSIdle();//only moves if we have a goal } } -void NPC_BSRunAndShoot (void) -{ +void NPC_BSRunAndShoot(void) { /*if(NPC->playerTeam && NPC->enemyTeam) { //FIXME: don't realize this right away- or else enemies show up and we're standing around @@ -426,130 +370,112 @@ void NPC_BSRunAndShoot (void) } }*/ - //NOTE: are we sure we want ALL run and shoot people to move this way? - //Shouldn't it check to see if we have an enemy and our enemy is our goal?! - //Moved that check into NPC_MoveToGoal - //NPCInfo->combatMove = qtrue; + // NOTE: are we sure we want ALL run and shoot people to move this way? + // Shouldn't it check to see if we have an enemy and our enemy is our goal?! + // Moved that check into NPC_MoveToGoal + // NPCInfo->combatMove = qtrue; - NPC_CheckEnemy( qtrue, qfalse ); - - if ( NPCInfo->duckDebounceTime > level.time ) // && NPCInfo->hidingGoal ) + NPC_CheckEnemy(qtrue, qfalse); + + if (NPCInfo->duckDebounceTime > level.time) // && NPCInfo->hidingGoal ) { ucmd.upmove = -127; - if ( NPC->enemy ) - { - NPC_CheckCanAttack( 1.0, qfalse ); + if (NPC->enemy) { + NPC_CheckCanAttack(1.0, qfalse); } - return; + return; } - if ( NPC->enemy ) - { + if (NPC->enemy) { int monitor = NPC->cantHitEnemyCounter; - NPC_StandTrackAndShoot( NPC, qfalse );//(NPCInfo->hidingGoal != NULL) ); + NPC_StandTrackAndShoot(NPC, qfalse); //(NPCInfo->hidingGoal != NULL) ); - if ( !(ucmd.buttons & BUTTON_ATTACK) && ucmd.upmove >= 0 && NPC->cantHitEnemyCounter > monitor ) - {//not crouching and not firing - vec3_t vec; + if (!(ucmd.buttons & BUTTON_ATTACK) && ucmd.upmove >= 0 && NPC->cantHitEnemyCounter > monitor) { // not crouching and not firing + vec3_t vec; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, vec ); + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); vec[2] = 0; - if ( VectorLength( vec ) > 128 || NPC->cantHitEnemyCounter >= 10 ) - {//run at enemy if too far away - //The cantHitEnemyCounter getting high has other repercussions - //100 (10 seconds) will make you try to pick a new enemy... - //But we're chasing, so we clamp it at 50 here - if ( NPC->cantHitEnemyCounter > 60 ) - { + if (VectorLength(vec) > 128 || NPC->cantHitEnemyCounter >= 10) { // run at enemy if too far away + // The cantHitEnemyCounter getting high has other repercussions + // 100 (10 seconds) will make you try to pick a new enemy... + // But we're chasing, so we clamp it at 50 here + if (NPC->cantHitEnemyCounter > 60) { NPC->cantHitEnemyCounter = 60; } - - if ( NPC->cantHitEnemyCounter >= (NPCInfo->stats.aggression+1) * 10 ) - { + + if (NPC->cantHitEnemyCounter >= (NPCInfo->stats.aggression + 1) * 10) { NPC_LostEnemyDecideChase(); } - //chase and face + // chase and face ucmd.angles[YAW] = 0; ucmd.angles[PITCH] = 0; NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - //NAV_ClearLastRoute(NPC); - NPC_MoveToGoal( qtrue ); + // NAV_ClearLastRoute(NPC); + NPC_MoveToGoal(qtrue); NPC_UpdateAngles(qtrue, qtrue); + } else { + // FIXME: this could happen if they're just on the other side + // of a thin wall or something else blocking out shot. That + // would make us just stand there and not go around it... + // but maybe it's okay- might look like we're waiting for + // him to come out...? + // Current solution: runs around if cantHitEnemyCounter gets + // to 10 (1 second). } - else - { - //FIXME: this could happen if they're just on the other side - //of a thin wall or something else blocking out shot. That - //would make us just stand there and not go around it... - //but maybe it's okay- might look like we're waiting for - //him to come out...? - //Current solution: runs around if cantHitEnemyCounter gets - //to 10 (1 second). - } - } - else - {//Clear the can't hit enemy counter here + } else { // Clear the can't hit enemy counter here NPC->cantHitEnemyCounter = 0; } - } - else - { - if ( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + } else { + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCInfo->tempBehavior = BS_DEFAULT; return; } -// NPC_BSRun();//only moves if we have a goal + // NPC_BSRun();//only moves if we have a goal } } -//Simply turn until facing desired angles -void NPC_BSFace (void) -{ - //FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? - //Once this is over, it snaps back to what it was facing before- WHY??? - if( NPC_UpdateAngles ( qtrue, qtrue ) ) - { - Q3_TaskIDComplete( NPC, TID_BSTATE ); - +// Simply turn until facing desired angles +void NPC_BSFace(void) { + // FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? + // Once this is over, it snaps back to what it was facing before- WHY??? + if (NPC_UpdateAngles(qtrue, qtrue)) { + Q3_TaskIDComplete(NPC, TID_BSTATE); + NPCInfo->desiredYaw = client->ps.viewangles[YAW]; NPCInfo->desiredPitch = client->ps.viewangles[PITCH]; - NPCInfo->aimTime = 0;//ok to turn normally now + NPCInfo->aimTime = 0; // ok to turn normally now } } -void NPC_BSPointShoot (qboolean shoot) -{//FIXME: doesn't check for clear shot... - vec3_t muzzle, dir, angles, org; +void NPC_BSPointShoot(qboolean shoot) { // FIXME: doesn't check for clear shot... + vec3_t muzzle, dir, angles, org; - if ( !NPC->enemy || !NPC->enemy->inuse || (NPC->enemy->NPC && NPC->enemy->health <= 0) ) - {//FIXME: should still keep shooting for a second or two after they actually die... - Q3_TaskIDComplete( NPC, TID_BSTATE ); + if (!NPC->enemy || !NPC->enemy->inuse || + (NPC->enemy->NPC && NPC->enemy->health <= 0)) { // FIXME: should still keep shooting for a second or two after they actually die... + Q3_TaskIDComplete(NPC, TID_BSTATE); goto finished; return; } CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - CalcEntitySpot(NPC->enemy, SPOT_HEAD, org);//Was spot_org - //Head is a little high, so let's aim for the chest: - if ( NPC->enemy->client ) - { - org[2] -= 12;//NOTE: is this enough? + CalcEntitySpot(NPC->enemy, SPOT_HEAD, org); // Was spot_org + // Head is a little high, so let's aim for the chest: + if (NPC->enemy->client) { + org[2] -= 12; // NOTE: is this enough? } VectorSubtract(org, muzzle, dir); vectoangles(dir, angles); - switch( NPC->client->ps.weapon ) - { + switch (NPC->client->ps.weapon) { case WP_NONE: case WP_MELEE: case WP_SABER: - //don't do any pitch change if not holding a firing weapon + // don't do any pitch change if not holding a firing weapon break; default: NPCInfo->desiredPitch = NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); @@ -558,23 +484,18 @@ void NPC_BSPointShoot (qboolean shoot) NPCInfo->desiredYaw = NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); - if ( NPC_UpdateAngles ( qtrue, qtrue ) ) - {//FIXME: if angles clamped, this may never work! - //NPCInfo->shotTime = NPC->attackDebounceTime = 0; + if (NPC_UpdateAngles(qtrue, qtrue)) { // FIXME: if angles clamped, this may never work! + // NPCInfo->shotTime = NPC->attackDebounceTime = 0; - if ( shoot ) - {//FIXME: needs to hold this down if using a weapon that requires it, like phaser... + if (shoot) { // FIXME: needs to hold this down if using a weapon that requires it, like phaser... ucmd.buttons |= BUTTON_ATTACK; } - - if ( !shoot || !(NPC->svFlags & SVF_LOCKEDENEMY) ) - {//If locked_enemy is on, dont complete until it is destroyed... - Q3_TaskIDComplete( NPC, TID_BSTATE ); + + if (!shoot || !(NPC->svFlags & SVF_LOCKEDENEMY)) { // If locked_enemy is on, dont complete until it is destroyed... + Q3_TaskIDComplete(NPC, TID_BSTATE); goto finished; } - } - else if ( shoot && (NPC->svFlags & SVF_LOCKEDENEMY) ) - {//shooting them till their dead, not aiming right at them yet... + } else if (shoot && (NPC->svFlags & SVF_LOCKEDENEMY)) { // shooting them till their dead, not aiming right at them yet... /* qboolean movingTarget = qfalse; @@ -593,61 +514,53 @@ void NPC_BSPointShoot (qboolean shoot) if (movingTarget ) */ { - float dist = VectorLength( dir ); - float yawMiss, yawMissAllow = NPC->enemy->maxs[0]; - float pitchMiss, pitchMissAllow = (NPC->enemy->maxs[2] - NPC->enemy->mins[2])/2; - - if ( yawMissAllow < 8.0f ) - { + float dist = VectorLength(dir); + float yawMiss, yawMissAllow = NPC->enemy->maxs[0]; + float pitchMiss, pitchMissAllow = (NPC->enemy->maxs[2] - NPC->enemy->mins[2]) / 2; + + if (yawMissAllow < 8.0f) { yawMissAllow = 8.0f; } - if ( pitchMissAllow < 8.0f ) - { + if (pitchMissAllow < 8.0f) { pitchMissAllow = 8.0f; } - yawMiss = tan(DEG2RAD(AngleDelta ( NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw ))) * dist; - pitchMiss = tan(DEG2RAD(AngleDelta ( NPC->client->ps.viewangles[PITCH], NPCInfo->desiredPitch))) * dist; + yawMiss = tan(DEG2RAD(AngleDelta(NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw))) * dist; + pitchMiss = tan(DEG2RAD(AngleDelta(NPC->client->ps.viewangles[PITCH], NPCInfo->desiredPitch))) * dist; - if ( yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss ) - { + if (yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss) { ucmd.buttons |= BUTTON_ATTACK; } } } - + return; - + finished: NPCInfo->desiredYaw = client->ps.viewangles[YAW]; NPCInfo->desiredPitch = client->ps.viewangles[PITCH]; - NPCInfo->aimTime = 0;//ok to turn normally now + NPCInfo->aimTime = 0; // ok to turn normally now } /* void NPC_BSMove(void) Move in a direction, face another */ -void NPC_BSMove(void) -{ - gentity_t *goal = NULL; +void NPC_BSMove(void) { + gentity_t *goal = NULL; NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - { + if (NPC->enemy) { NPC_CheckCanAttack(1.0, qfalse); - } - else - { + } else { NPC_UpdateAngles(qtrue, qtrue); } goal = UpdateGoal(); - if(goal) - { -// NPCInfo->moveToGoalMod = 1.0; + if (goal) { + // NPCInfo->moveToGoalMod = 1.0; NPC_SlideMoveToGoal(); } @@ -658,14 +571,12 @@ void NPC_BSShoot(void) Move in a direction, face another */ -void NPC_BSShoot(void) -{ -// NPC_BSMove(); +void NPC_BSShoot(void) { + // NPC_BSMove(); enemyVisibility = VIS_SHOOT; - if ( client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING ) - { + if (client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING) { client->ps.weaponstate = WEAPON_READY; } @@ -673,28 +584,25 @@ void NPC_BSShoot(void) } /* -void NPC_BSPatrol( void ) +void NPC_BSPatrol( void ) Same as idle, but you look for enemies every "vigilance" using your angles, HFOV, VFOV and visrange, and listen for sounds within earshot... */ -void NPC_BSPatrol( void ) -{ - //int alertEventNum; +void NPC_BSPatrol(void) { + // int alertEventNum; - if(level.time > NPCInfo->enemyCheckDebounceTime) - { + if (level.time > NPCInfo->enemyCheckDebounceTime) { NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - {//FIXME: do anger script + if (NPC->enemy) { // FIXME: do anger script NPCInfo->behaviorState = BS_HUNT_AND_KILL; - //NPC_AngerSound(); + // NPC_AngerSound(); return; } } - //FIXME: Implement generic sound alerts + // FIXME: Implement generic sound alerts /* alertEventNum = NPC_CheckAlertEvents( qtrue, qtrue ); if( alertEventNum != -1 ) @@ -707,14 +615,13 @@ void NPC_BSPatrol( void ) */ NPCInfo->investigateSoundDebounceTime = 0; - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); ucmd.buttons |= BUTTON_WALKING; } @@ -723,251 +630,215 @@ void NPC_BSPatrol( void ) void NPC_BSDefault(void) uses various scriptflags to determine how an npc should behave */ -extern void NPC_CheckGetNewWeapon( void ); -extern void NPC_BSST_Attack( void ); - -void NPC_BSDefault( void ) -{ -// vec3_t enemyDir; -// float enemyDist; -// float shootDist; -// qboolean enemyFOV = qfalse; -// qboolean enemyShotFOV = qfalse; -// qboolean enemyPVS = qfalse; -// vec3_t enemyHead; -// vec3_t muzzle; -// qboolean enemyLOS = qfalse; -// qboolean enemyCS = qfalse; - qboolean move = qtrue; -// qboolean shoot = qfalse; - - - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); - } - - if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - if( NPC->client->ps.torsoAnim != TORSO_SURRENDER_START ) - { - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD ); - } - } - //look for a new enemy if don't have one and are allowed to look, validate current enemy if have one - NPC_CheckEnemy( (qboolean)(NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES), qfalse ); - if ( !NPC->enemy ) - {//still don't have an enemy - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//check for alert events - //FIXME: Check Alert events, see if we should investigate or just look at it - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); - - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - {//heard/saw something - if ( level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - {//was a big event - if ( level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); +extern void NPC_CheckGetNewWeapon(void); +extern void NPC_BSST_Attack(void); + +void NPC_BSDefault(void) { + // vec3_t enemyDir; + // float enemyDist; + // float shootDist; + // qboolean enemyFOV = qfalse; + // qboolean enemyShotFOV = qfalse; + // qboolean enemyPVS = qfalse; + // vec3_t enemyHead; + // vec3_t muzzle; + // qboolean enemyLOS = qfalse; + // qboolean enemyCS = qfalse; + qboolean move = qtrue; + // qboolean shoot = qfalse; + + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); + } + + if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + if (NPC->client->ps.torsoAnim != TORSO_SURRENDER_START) { + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD); + } + } + // look for a new enemy if don't have one and are allowed to look, validate current enemy if have one + NPC_CheckEnemy((qboolean)(NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES), qfalse); + if (!NPC->enemy) { // still don't have an enemy + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // check for alert events + // FIXME: Check Alert events, see if we should investigate or just look at it + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); + + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID) { // heard/saw something + if (level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { // was a big event + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && + level.alertEvents[alertEvent].owner->health >= 0 && + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); } - } - else - {//FIXME: investigate lesser events + } else { // FIXME: investigate lesser events } } - //FIXME: also check our allies' condition? + // FIXME: also check our allies' condition? } } - if ( NPC->enemy && !(NPCInfo->scriptFlags&SCF_FORCED_MARCH) ) - { + if (NPC->enemy && !(NPCInfo->scriptFlags & SCF_FORCED_MARCH)) { // just use the stormtrooper attack AI... NPC_CheckGetNewWeapon(); - if ( NPC->client->leader - && NPCInfo->goalEntity == NPC->client->leader - && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - { + if (NPC->client->leader && NPCInfo->goalEntity == NPC->client->leader && !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { NPC_ClearGoal(); } - NPC_BSST_Attack(); + NPC_BSST_Attack(); return; -/* - //have an enemy - //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); - enemyDist = VectorNormalize( enemyDir ); - enemyDist *= enemyDist; - shootDist = NPC_MaxDistSquaredForWeapon(); - - enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); - enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); - enemyPVS = gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ); - - if ( enemyPVS ) - {//in the pvs - trace_t tr; - - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); - enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); - - gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); - enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); - } - else - {//skip thr 2 traces since they would have to fail - enemyLOS = qfalse; - enemyCS = qfalse; - } - - if ( enemyCS && enemyShotFOV ) - {//can hit enemy if we want - NPC->cantHitEnemyCounter = 0; - } - else - {//can't hit - NPC->cantHitEnemyCounter++; - } + /* + //have an enemy + //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? + VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); + enemyDist = VectorNormalize( enemyDir ); + enemyDist *= enemyDist; + shootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) - {//can shoot - shoot = qtrue; - if ( NPCInfo->goalEntity == NPC->enemy ) - {//my goal is my enemy and I have a clear shot, no need to chase right now - move = qfalse; - } - } - else - {//don't shoot yet, keep chasing - shoot = qfalse; - move = qtrue; - } + enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); + enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); + enemyPVS = gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ); - //shoot decision - if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//try to shoot - if ( NPC->enemy ) - { - if ( shoot ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + if ( enemyPVS ) + {//in the pvs + trace_t tr; + + CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); + enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); + CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); + + gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); + enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); + } + else + {//skip thr 2 traces since they would have to fail + enemyLOS = qfalse; + enemyCS = qfalse; + } + + if ( enemyCS && enemyShotFOV ) + {//can hit enemy if we want + NPC->cantHitEnemyCounter = 0; + } + else + {//can't hit + NPC->cantHitEnemyCounter++; + } + + if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) + {//can shoot + shoot = qtrue; + if ( NPCInfo->goalEntity == NPC->enemy ) + {//my goal is my enemy and I have a clear shot, no need to chase right now + move = qfalse; + } + } + else + {//don't shoot yet, keep chasing + shoot = qfalse; + move = qtrue; + } + + //shoot decision + if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) + {//try to shoot + if ( NPC->enemy ) { - WeaponThink( qtrue ); + if ( shoot ) + { + if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + { + WeaponThink( qtrue ); + } + } } } - } - } - //chase decision - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//go after him - NPCInfo->goalEntity = NPC->enemy; - //FIXME: don't need to chase when have a clear shot and in range? - if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) - {//haven't been able to shoot enemy for about 6 seconds, need to do something - //FIXME: combat points? Just chase? - if ( enemyPVS ) - {//in my PVS, just pick a combat point - //FIXME: implement + //chase decision + if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + {//go after him + NPCInfo->goalEntity = NPC->enemy; + //FIXME: don't need to chase when have a clear shot and in range? + if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) + {//haven't been able to shoot enemy for about 6 seconds, need to do something + //FIXME: combat points? Just chase? + if ( enemyPVS ) + {//in my PVS, just pick a combat point + //FIXME: implement + } + else + {//just chase him + } + } + //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? } - else - {//just chase him + else if ( NPC->cantHitEnemyCounter > 60 ) + {//pick a new one + NPC_CheckEnemy( qtrue, qfalse ); } - } - //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? - } - else if ( NPC->cantHitEnemyCounter > 60 ) - {//pick a new one - NPC_CheckEnemy( qtrue, qfalse ); - } - - if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) - {//have a clear LOS to him//, but not looking at him - //Find the desired angles - vec3_t angles; - GetAnglesForDirection( muzzle, enemyHead, angles ); + if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) + {//have a clear LOS to him//, but not looking at him + //Find the desired angles + vec3_t angles; - NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); - } - */ + GetAnglesForDirection( muzzle, enemyHead, angles ); + + NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); + NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); + } + */ } - if ( UpdateGoal() ) - {//have a goal - if ( !NPC->enemy - && NPC->client->leader - && NPCInfo->goalEntity == NPC->client->leader - && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - { + if (UpdateGoal()) { // have a goal + if (!NPC->enemy && NPC->client->leader && NPCInfo->goalEntity == NPC->client->leader && !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { NPC_BSFollowLeader(); - } - else - { - //set angles - if ( (NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || NPCInfo->goalEntity != NPC->enemy ) - {//face direction of movement, NOTE: default behavior when not chasing enemy + } else { + // set angles + if ((NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || + NPCInfo->goalEntity != NPC->enemy) { // face direction of movement, NOTE: default behavior when not chasing enemy NPCInfo->combatMove = qfalse; - } - else - {//face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? - vec3_t dir, angles; + } else { // face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? + vec3_t dir, angles; NPCInfo->combatMove = qfalse; - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); + vectoangles(dir, angles); NPCInfo->desiredYaw = angles[YAW]; - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { NPCInfo->desiredPitch = angles[PITCH]; } } - //set movement - //override default walk/run behavior - //NOTE: redundant, done in NPC_ApplyScriptFlags - if ( NPCInfo->scriptFlags & SCF_RUNNING ) - { + // set movement + // override default walk/run behavior + // NOTE: redundant, done in NPC_ApplyScriptFlags + if (NPCInfo->scriptFlags & SCF_RUNNING) { ucmd.buttons &= ~BUTTON_WALKING; - } - else if ( NPCInfo->scriptFlags & SCF_WALKING ) - { + } else if (NPCInfo->scriptFlags & SCF_WALKING) { ucmd.buttons |= BUTTON_WALKING; - } - else if ( NPCInfo->goalEntity == NPC->enemy ) - { + } else if (NPCInfo->goalEntity == NPC->enemy) { ucmd.buttons &= ~BUTTON_WALKING; - } - else - { + } else { ucmd.buttons |= BUTTON_WALKING; } - if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - if ( g_crosshairEntNum != NPC->s.number ) - {//don't walk if player isn't aiming at me + if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + if (g_crosshairEntNum != NPC->s.number) { // don't walk if player isn't aiming at me move = qfalse; } } - if ( move ) - { - //move toward goal - NPC_MoveToGoal( qtrue ); + if (move) { + // move toward goal + NPC_MoveToGoal(qtrue); } } - } - else if ( !NPC->enemy && NPC->client->leader ) - { + } else if (!NPC->enemy && NPC->client->leader) { NPC_BSFollowLeader(); } - //update angles - NPC_UpdateAngles( qtrue, qtrue ); + // update angles + NPC_UpdateAngles(qtrue, qtrue); } \ No newline at end of file diff --git a/codeJK2/game/AI_Droid.cpp b/codeJK2/game/AI_Droid.cpp index f911137d4b..c48be92cc1 100644 --- a/codeJK2/game/AI_Droid.cpp +++ b/codeJK2/game/AI_Droid.cpp @@ -20,46 +20,37 @@ along with this program; if not, see . =========================================================================== */ #include "g_headers.h" - + #include "b_local.h" -//static void R5D2_LookAround( void ); -float NPC_GetPainChance( gentity_t *self, int damage ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +// static void R5D2_LookAround( void ); +float NPC_GetPainChance(gentity_t *self, int damage); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; /* ------------------------- R2D2_PartsMove ------------------------- */ -void R2D2_PartsMove(void) -{ +void R2D2_PartsMove(void) { // Front 'eye' lense - if ( TIMER_Done(NPC,"eyeDelay") ) - { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); + if (TIMER_Done(NPC, "eyeDelay")) { + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); - NPC->pos1[0]+=Q_irand( -20, 20 ); // Roll - NPC->pos1[1]=Q_irand( -20, 20 ); - NPC->pos1[2]=Q_irand( -20, 20 ); + NPC->pos1[0] += Q_irand(-20, 20); // Roll + NPC->pos1[1] = Q_irand(-20, 20); + NPC->pos1[2] = Q_irand(-20, 20); - if (NPC->genericBone1) - { - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + if (NPC->genericBone1) { + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - TIMER_Set( NPC, "eyeDelay", Q_irand( 100, 1000 ) ); + TIMER_Set(NPC, "eyeDelay", Q_irand(100, 1000)); } } @@ -68,11 +59,10 @@ void R2D2_PartsMove(void) NPC_BSDroid_Idle ------------------------- */ -void Droid_Idle( void ) -{ -// VectorCopy( NPCInfo->investigateGoal, lookPos ); +void Droid_Idle(void) { + // VectorCopy( NPCInfo->investigateGoal, lookPos ); -// NPC_FacePosition( lookPos ); + // NPC_FacePosition( lookPos ); } /* @@ -80,36 +70,26 @@ void Droid_Idle( void ) R2D2_TurnAnims ------------------------- */ -void R2D2_TurnAnims ( void ) -{ +void R2D2_TurnAnims(void) { float turndelta; - int anim; + int anim; turndelta = AngleDelta(NPC->currentAngles[YAW], NPCInfo->desiredYaw); - if ((fabs(turndelta) > 20) && ((NPC->client->NPC_class == CLASS_R2D2) || (NPC->client->NPC_class == CLASS_R5D2))) - { + if ((fabs(turndelta) > 20) && ((NPC->client->NPC_class == CLASS_R2D2) || (NPC->client->NPC_class == CLASS_R5D2))) { anim = NPC->client->ps.legsAnim; - if (turndelta<0) - { - if (anim != BOTH_TURN_LEFT1) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (turndelta < 0) { + if (anim != BOTH_TURN_LEFT1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - if (anim != BOTH_TURN_RIGHT1) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + if (anim != BOTH_TURN_RIGHT1) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } /* @@ -117,69 +97,55 @@ void R2D2_TurnAnims ( void ) Droid_Patrol ------------------------- */ -void Droid_Patrol( void ) -{ +void Droid_Patrol(void) { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); - if ( NPC->client && NPC->client->NPC_class != CLASS_GONK ) - { - R2D2_PartsMove(); // Get his eye moving. + if (NPC->client && NPC->client->NPC_class != CLASS_GONK) { + R2D2_PartsMove(); // Get his eye moving. R2D2_TurnAnims(); } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); - if( NPC->client && NPC->client->NPC_class == CLASS_MOUSE ) - { - NPCInfo->desiredYaw += sin(level.time*.5) * 25; // Weaves side to side a little + if (NPC->client && NPC->client->NPC_class == CLASS_MOUSE) { + NPCInfo->desiredYaw += sin(level.time * .5) * 25; // Weaves side to side a little - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)) ); + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPC->client && NPC->client->NPC_class == CLASS_R2D2 ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)) ); + } else if (NPC->client && NPC->client->NPC_class == CLASS_R2D2) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPC->client && NPC->client->NPC_class == CLASS_R5D2 ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)) ); + } else if (NPC->client && NPC->client->NPC_class == CLASS_R5D2) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } - if( NPC->client && NPC->client->NPC_class == CLASS_GONK ) - { - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)) ); + if (NPC->client && NPC->client->NPC_class == CLASS_GONK) { + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } -// else -// { -// R5D2_LookAround(); -// } + // else + // { + // R5D2_LookAround(); + // } } - NPC_UpdateAngles( qtrue, qtrue ); - + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -187,31 +153,25 @@ void Droid_Patrol( void ) Droid_Run ------------------------- */ -void Droid_Run( void ) -{ +void Droid_Run(void) { R2D2_PartsMove(); - if ( NPCInfo->localState == LSTATE_BACKINGUP ) - { + if (NPCInfo->localState == LSTATE_BACKINGUP) { ucmd.forwardmove = -127; - NPCInfo->desiredYaw += 5; + NPCInfo->desiredYaw += 5; - NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. - } - else - { + NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. + } else { ucmd.forwardmove = 64; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { - if (NPC_MoveToGoal( qfalse )) - { - NPCInfo->desiredYaw += sin(level.time*.5) * 5; // Weaves side to side a little + // If we have somewhere to go, then do that + if (UpdateGoal()) { + if (NPC_MoveToGoal(qfalse)) { + NPCInfo->desiredYaw += sin(level.time * .5) * 5; // Weaves side to side a little } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -219,64 +179,47 @@ void Droid_Run( void ) void Droid_Spin( void ) ------------------------- */ -void Droid_Spin( void ) -{ - vec3_t dir = {0,0,1}; +void Droid_Spin(void) { + vec3_t dir = {0, 0, 1}; R2D2_TurnAnims(); - // Head is gone, spin and spark - if ( NPC->client->NPC_class == CLASS_R5D2 ) - { + if (NPC->client->NPC_class == CLASS_R5D2) { // No head? - if (gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "head" )) - { - if (TIMER_Done(NPC,"smoke") && !TIMER_Done(NPC,"droidsmoketotal")) - { - TIMER_Set( NPC, "smoke", 100); - G_PlayEffect( "droid_smoke" , NPC->currentOrigin,dir); + if (gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "head")) { + if (TIMER_Done(NPC, "smoke") && !TIMER_Done(NPC, "droidsmoketotal")) { + TIMER_Set(NPC, "smoke", 100); + G_PlayEffect("droid_smoke", NPC->currentOrigin, dir); } - if (TIMER_Done(NPC,"droidspark")) - { - TIMER_Set( NPC, "droidspark", Q_irand(100,500)); - G_PlayEffect( "spark", NPC->currentOrigin,dir); + if (TIMER_Done(NPC, "droidspark")) { + TIMER_Set(NPC, "droidspark", Q_irand(100, 500)); + G_PlayEffect("spark", NPC->currentOrigin, dir); } - ucmd.forwardmove = Q_irand( -64, 64); + ucmd.forwardmove = Q_irand(-64, 64); - if (TIMER_Done(NPC,"roam")) - { - TIMER_Set( NPC, "roam", Q_irand( 250, 1000 ) ); - NPCInfo->desiredYaw = Q_irand( 0, 360 ); // Go in random directions + if (TIMER_Done(NPC, "roam")) { + TIMER_Set(NPC, "roam", Q_irand(250, 1000)); + NPCInfo->desiredYaw = Q_irand(0, 360); // Go in random directions } - } - else - { - if (TIMER_Done(NPC,"roam")) - { + } else { + if (TIMER_Done(NPC, "roam")) { NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 40); // Spin around } } - } - else - { - if (TIMER_Done(NPC,"roam")) - { + } else { + if (TIMER_Done(NPC, "roam")) { NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 40); // Spin around } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -284,127 +227,108 @@ void Droid_Spin( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Droid_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - int anim; - float pain_chance; +void NPC_Droid_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + int anim; + float pain_chance; - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->client->NPC_class == CLASS_R5D2 ) - { - pain_chance = NPC_GetPainChance( self, damage ); + if (self->client->NPC_class == CLASS_R5D2) { + pain_chance = NPC_GetPainChance(self, damage); // Put it in pain - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { // Health is between 0-30 or was hit by a DEMP2 so pop his head - if ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { - if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE + if (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { + if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE { - if ((self->NPC->localState != LSTATE_SPINNING) && - (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head" ))) - { - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head", TURN_OFF ); + if ((self->NPC->localState != LSTATE_SPINNING) && (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head"))) { + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head", TURN_OFF); -// G_PlayEffect( "small_chunks" , self->currentOrigin ); - G_PlayEffect( "r5d2head", self->currentOrigin ); + // G_PlayEffect( "small_chunks" , self->currentOrigin ); + G_PlayEffect("r5d2head", self->currentOrigin); - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; - TIMER_Set( self, "droidsmoketotal", 5000); - TIMER_Set( self, "droidspark", 100); + TIMER_Set(self, "droidsmoketotal", 5000); + TIMER_Set(self, "droidspark", 100); self->NPC->localState = LSTATE_SPINNING; } } } // Just give him normal pain for a little while - else - { + else { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); - } + TIMER_Set(self, "roam", Q_irand(1000, 2000)); + } } - } - else if (self->client->NPC_class == CLASS_MOUSE) - { - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + } else if (self->client->NPC_class == CLASS_MOUSE) { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->localState = LSTATE_SPINNING; - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; - } - else - { + } else { self->NPC->localState = LSTATE_BACKINGUP; } self->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; - } - else if (self->client->NPC_class == CLASS_R2D2) - { + } else if (self->client->NPC_class == CLASS_R2D2) { - pain_chance = NPC_GetPainChance( self, damage ); + pain_chance = NPC_GetPainChance(self, damage); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); - } - } - else if ( self->client->NPC_class == CLASS_INTERROGATOR && ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) && other ) - { + TIMER_Set(self, "roam", Q_irand(1000, 2000)); + } + } else if (self->client->NPC_class == CLASS_INTERROGATOR && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - VectorSubtract( self->currentOrigin, other->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->currentOrigin, other->currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - NPC_Pain( self, inflictor, other, point, damage, mod); + NPC_Pain(self, inflictor, other, point, damage, mod); } - /* ------------------------- Droid_Pain ------------------------- */ -void Droid_Pain(void) -{ - if (TIMER_Done(NPC,"droidpain")) //He's done jumping around +void Droid_Pain(void) { + if (TIMER_Done(NPC, "droidpain")) // He's done jumping around { NPCInfo->localState = LSTATE_NONE; } @@ -415,18 +339,16 @@ void Droid_Pain(void) NPC_Mouse_Precache ------------------------- */ -void NPC_Mouse_Precache( void ) -{ - int i; +void NPC_Mouse_Precache(void) { + int i; - for (i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/mouse/misc/mousego%d.wav", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", i)); } - G_EffectIndex( "env/small_explode" ); - G_SoundIndex( "sound/chars/mouse/misc/death1" ); - G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + G_EffectIndex("env/small_explode"); + G_SoundIndex("sound/chars/mouse/misc/death1"); + G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); } /* @@ -434,17 +356,15 @@ void NPC_Mouse_Precache( void ) NPC_R5D2_Precache ------------------------- */ -void NPC_R5D2_Precache(void) -{ - for ( int i = 1; i < 5; i++) - { - G_SoundIndex( va( "sound/chars/r5d2/misc/r5talk%d.wav", i ) ); +void NPC_R5D2_Precache(void) { + for (int i = 1; i < 5; i++) { + G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", i)); } - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); - G_EffectIndex( "env/med_explode"); - G_EffectIndex( "droid_smoke" ); - G_EffectIndex( "r5d2head"); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); + G_EffectIndex("env/med_explode"); + G_EffectIndex("droid_smoke"); + G_EffectIndex("r5d2head"); } /* @@ -452,15 +372,13 @@ void NPC_R5D2_Precache(void) NPC_R2D2_Precache ------------------------- */ -void NPC_R2D2_Precache(void) -{ - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/r2d2/misc/r2d2talk0%d.wav", i ) ); +void NPC_R2D2_Precache(void) { + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", i)); } - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); - G_EffectIndex( "env/med_explode"); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); + G_EffectIndex("env/med_explode"); } /* @@ -468,8 +386,7 @@ void NPC_R2D2_Precache(void) NPC_Gonk_Precache ------------------------- */ -void NPC_Gonk_Precache( void ) -{ +void NPC_Gonk_Precache(void) { G_SoundIndex("sound/chars/gonk/misc/gonktalk1.wav"); G_SoundIndex("sound/chars/gonk/misc/gonktalk2.wav"); @@ -477,7 +394,7 @@ void NPC_Gonk_Precache( void ) G_SoundIndex("sound/chars/gonk/misc/death2.wav"); G_SoundIndex("sound/chars/gonk/misc/death3.wav"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("env/med_explode"); } /* @@ -485,10 +402,9 @@ void NPC_Gonk_Precache( void ) NPC_Protocol_Precache ------------------------- */ -void NPC_Protocol_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); - G_EffectIndex( "env/med_explode"); +void NPC_Protocol_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); + G_EffectIndex("env/med_explode"); } /* @@ -500,7 +416,7 @@ static void R5D2_OffsetLook( float offset, vec3_t out ) angles[YAW] += offset; AngleVectors( angles, forward, NULL, NULL ); VectorMA( NPC->currentOrigin, 64, forward, out ); - + CalcEntitySpot( NPC, SPOT_HEAD, temp ); out[2] = temp[2]; } @@ -545,28 +461,18 @@ static void R5D2_LookAround( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSDroid_Default( void ) -{ +void NPC_BSDroid_Default(void) { - if ( NPCInfo->localState == LSTATE_SPINNING ) - { + if (NPCInfo->localState == LSTATE_SPINNING) { Droid_Spin(); - } - else if ( NPCInfo->localState == LSTATE_PAIN ) - { + } else if (NPCInfo->localState == LSTATE_PAIN) { Droid_Pain(); - } - else if ( NPCInfo->localState == LSTATE_DROP ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else if (NPCInfo->localState == LSTATE_DROP) { + NPC_UpdateAngles(qtrue, qtrue); ucmd.upmove = Q_flrand(-1.0f, 1.0f) * 64; - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Droid_Patrol(); - } - else - { + } else { Droid_Run(); } } diff --git a/codeJK2/game/AI_GalakMech.cpp b/codeJK2/game/AI_GalakMech.cpp index 8d8738e6a9..9c256b580d 100644 --- a/codeJK2/game/AI_GalakMech.cpp +++ b/codeJK2/game/AI_GalakMech.cpp @@ -26,32 +26,31 @@ along with this program; if not, see . #include "anims.h" #include "wp_saber.h" -extern qboolean G_StandardHumanoid( const char *modelName ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern void NPC_AimAdjust( int change ); -extern qboolean WP_LobFire( gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, - vec3_t velocity, qboolean tracePath, int ignoreEntNum, int enemyNum, - float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_SoundAtSpot( vec3_t org, int soundIndex ); -extern void G_SoundOnEnt (gentity_t *ent, soundChannel_t channel, const char *soundPath); -extern qboolean PM_CrouchAnim( int anim ); -//extern void NPC_Mark1_Part_Explode(gentity_t *self,int bolt); - -#define MELEE_DIST_SQUARED 6400//80*80 -#define MIN_LOB_DIST_SQUARED 65536//256*256 -#define MAX_LOB_DIST_SQUARED 200704//448*448 -#define REPEATER_ALT_SIZE 3 // half of bbox size -#define GENERATOR_HEALTH 25 -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 -#define GALAK_SHIELD_HEALTH 500 - -static vec3_t shieldMins = {-60, -60, -24 }; +extern qboolean G_StandardHumanoid(const char *modelName); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern void NPC_AimAdjust(int change); +extern qboolean WP_LobFire(gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, vec3_t velocity, qboolean tracePath, + int ignoreEntNum, int enemyNum, float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_SoundAtSpot(vec3_t org, int soundIndex); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern qboolean PM_CrouchAnim(int anim); +// extern void NPC_Mark1_Part_Explode(gentity_t *self,int bolt); + +#define MELEE_DIST_SQUARED 6400 // 80*80 +#define MIN_LOB_DIST_SQUARED 65536 // 256*256 +#define MAX_LOB_DIST_SQUARED 200704 // 448*448 +#define REPEATER_ALT_SIZE 3 // half of bbox size +#define GENERATOR_HEALTH 25 +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 +#define GALAK_SHIELD_HEALTH 500 + +static vec3_t shieldMins = {-60, -60, -24}; static vec3_t shieldMaxs = {60, 60, 80}; -extern qboolean NPC_CheckPlayerTeamStealth( void ); +extern qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; @@ -59,88 +58,75 @@ static qboolean hitAlly; static qboolean faceEnemy; static qboolean AImove; static qboolean shoot; -static float enemyDist; -static vec3_t impactPos; - -void NPC_GalakMech_Precache( void ) -{ - G_SoundIndex( "sound/weapons/galak/skewerhit.wav" ); - G_SoundIndex( "sound/weapons/galak/lasercharge.wav" ); - G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); - G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ); - - G_EffectIndex( "galak/trace_beam" ); - G_EffectIndex( "galak/beam_warmup" ); -// G_EffectIndex( "small_chunks"); - G_EffectIndex( "env/med_explode2"); - G_EffectIndex( "env/small_explode2"); - G_EffectIndex( "galak/explode"); - G_EffectIndex( "blaster/smoke_bolton"); -// G_EffectIndex( "env/exp_trail_comp"); +static float enemyDist; +static vec3_t impactPos; + +void NPC_GalakMech_Precache(void) { + G_SoundIndex("sound/weapons/galak/skewerhit.wav"); + G_SoundIndex("sound/weapons/galak/lasercharge.wav"); + G_SoundIndex("sound/weapons/galak/lasercutting.wav"); + G_SoundIndex("sound/weapons/galak/laserdamage.wav"); + + G_EffectIndex("galak/trace_beam"); + G_EffectIndex("galak/beam_warmup"); + // G_EffectIndex( "small_chunks"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("env/small_explode2"); + G_EffectIndex("galak/explode"); + G_EffectIndex("blaster/smoke_bolton"); + // G_EffectIndex( "env/exp_trail_comp"); } -void NPC_GalakMech_Init( gentity_t *ent ) -{ - if (ent->NPC->behaviorState != BS_CINEMATIC) - { +void NPC_GalakMech_Init(gentity_t *ent) { + if (ent->NPC->behaviorState != BS_CINEMATIC) { ent->client->ps.stats[STAT_ARMOR] = GALAK_SHIELD_HEALTH; ent->NPC->investigateCount = ent->NPC->investigateDebounceTime = 0; - ent->flags |= FL_SHIELDED;//reflect normal shots - ent->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE;//temp, for effect + ent->flags |= FL_SHIELDED; // reflect normal shots + ent->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE; // temp, for effect ent->fx_time = level.time; - VectorSet( ent->mins, -60, -60, -24 ); - VectorSet( ent->maxs, 60, 60, 80 ); - ent->flags |= FL_NO_KNOCKBACK;//don't get pushed - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "smackTime", 0 ); - TIMER_Set( ent, "beamDelay", 0 ); - TIMER_Set( ent, "noLob", 0 ); - TIMER_Set( ent, "noRapid", 0 ); - TIMER_Set( ent, "talkDebounce", 0 ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_shield_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galakface_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galakhead_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_eyes_mouth_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_collar_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galaktorso_off", TURN_OFF ); + VectorSet(ent->mins, -60, -60, -24); + VectorSet(ent->maxs, 60, 60, 80); + ent->flags |= FL_NO_KNOCKBACK; // don't get pushed + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "smackTime", 0); + TIMER_Set(ent, "beamDelay", 0); + TIMER_Set(ent, "noLob", 0); + TIMER_Set(ent, "noRapid", 0); + TIMER_Set(ent, "talkDebounce", 0); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_shield_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galakface_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galakhead_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_eyes_mouth_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_collar_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galaktorso_off", TURN_OFF); + } else { + // gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "helmet", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_shield_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galakface_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galakhead_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_eyes_mouth_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_collar_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "torso_galaktorso_off", TURN_ON); } - else - { -// gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "helmet", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_shield_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galakface_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galakhead_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_eyes_mouth_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_collar_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "torso_galaktorso_off", TURN_ON ); - } - } //----------------------------------------------------------------- -static void GM_CreateExplosion( gentity_t *self, const int boltID, qboolean doSmall = qfalse ) -{ - if ( boltID >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; - - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - boltID, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); - - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); - - if ( doSmall ) - { - G_PlayEffect( "env/small_explode2", org, dir ); - } - else - { - G_PlayEffect( "env/med_explode2", org, dir ); +static void GM_CreateExplosion(gentity_t *self, const int boltID, qboolean doSmall = qfalse) { + if (boltID >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; + + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, boltID, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); + + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); + + if (doSmall) { + G_PlayEffect("env/small_explode2", org, dir); + } else { + G_PlayEffect("env/med_explode2", org, dir); } } } @@ -151,98 +137,82 @@ GM_Dying ------------------------- */ -void GM_Dying( gentity_t *self ) -{ - if ( level.time - self->s.time < 4000 ) - {//FIXME: need a real effect - self->s.powerups |= ( 1 << PW_SHOCKED ); +void GM_Dying(gentity_t *self) { + if (level.time - self->s.time < 4000) { // FIXME: need a real effect + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 1000; - if ( TIMER_Done( self, "dyingExplosion" ) ) - { - int newBolt; - switch ( Q_irand( 1, 14 ) ) - { + if (TIMER_Done(self, "dyingExplosion")) { + int newBolt; + switch (Q_irand(1, 14)) { // Find place to generate explosion case 1: - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_hand" )) - {//r_hand still there - GM_CreateExplosion( self, self->handRBolt, qtrue ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "r_hand", TURN_OFF ); - } - else if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm_middle" )) - {//r_arm_middle still there - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*r_arm_elbow" ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "r_arm_middle", TURN_OFF ); + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_hand")) { // r_hand still there + GM_CreateExplosion(self, self->handRBolt, qtrue); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "r_hand", TURN_OFF); + } else if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_arm_middle")) { // r_arm_middle still there + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*r_arm_elbow"); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "r_arm_middle", TURN_OFF); } break; case 2: - //FIXME: do only once? - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_hand" )) - {//l_hand still there - GM_CreateExplosion( self, self->handLBolt ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_hand", TURN_OFF ); - } - else if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm_wrist" )) - {//l_arm_wrist still there - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*l_arm_cap_l_hand" ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm_wrist", TURN_OFF ); - } - else if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm_middle" )) - {//l_arm_middle still there - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*l_arm_cap_l_hand" ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm_middle", TURN_OFF ); - } - else if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm_augment" )) - {//l_arm_augment still there - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*l_arm_elbow" ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm_augment", TURN_OFF ); + // FIXME: do only once? + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_hand")) { // l_hand still there + GM_CreateExplosion(self, self->handLBolt); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_hand", TURN_OFF); + } else if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm_wrist")) { // l_arm_wrist still there + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*l_arm_cap_l_hand"); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm_wrist", TURN_OFF); + } else if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm_middle")) { // l_arm_middle still there + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*l_arm_cap_l_hand"); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm_middle", TURN_OFF); + } else if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm_augment")) { // l_arm_augment still there + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*l_arm_elbow"); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm_augment", TURN_OFF); } break; case 3: case 4: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*hip_fr" ); - GM_CreateExplosion( self, newBolt ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*hip_fr"); + GM_CreateExplosion(self, newBolt); break; case 5: case 6: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*shldr_l" ); - GM_CreateExplosion( self, newBolt ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*shldr_l"); + GM_CreateExplosion(self, newBolt); break; case 7: case 8: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*uchest_r" ); - GM_CreateExplosion( self, newBolt ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*uchest_r"); + GM_CreateExplosion(self, newBolt); break; case 9: case 10: - GM_CreateExplosion( self, self->headBolt ); + GM_CreateExplosion(self, self->headBolt); break; case 11: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*l_leg_knee" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*l_leg_knee"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 12: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*r_leg_knee" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*r_leg_knee"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 13: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*l_leg_foot" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*l_leg_foot"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 14: - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*r_leg_foot" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*r_leg_foot"); + GM_CreateExplosion(self, newBolt, qtrue); break; } - TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1100 ) ); + TIMER_Set(self, "dyingExplosion", Q_irand(300, 1100)); } - } - else - {//one final, huge explosion - G_PlayEffect( "galak/explode", self->currentOrigin ); -// G_PlayEffect( "small_chunks", self->currentOrigin ); -// G_PlayEffect( "env/exp_trail_comp", self->currentOrigin, self->currentAngles ); + } else { // one final, huge explosion + G_PlayEffect("galak/explode", self->currentOrigin); + // G_PlayEffect( "small_chunks", self->currentOrigin ); + // G_PlayEffect( "env/exp_trail_comp", self->currentOrigin, self->currentAngles ); self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; } @@ -254,50 +224,39 @@ NPC_GM_Pain ------------------------- */ -extern void NPC_SetPainEvent( gentity_t *self ); -void NPC_GM_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->client->ps.powerups[PW_GALAK_SHIELD] == 0 ) - {//shield is currently down - //FIXME: allow for radius damage? - if ( (hitLoc==HL_GENERIC1) && (self->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH) ) - { - int newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*antenna_base" ); - if ( newBolt != -1 ) - { - GM_CreateExplosion( self, newBolt ); +extern void NPC_SetPainEvent(gentity_t *self); +void NPC_GM_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { + if (self->client->ps.powerups[PW_GALAK_SHIELD] == 0) { // shield is currently down + // FIXME: allow for radius damage? + if ((hitLoc == HL_GENERIC1) && (self->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH)) { + int newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*antenna_base"); + if (newBolt != -1) { + GM_CreateExplosion(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "torso_shield_off", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "torso_antenna", TURN_OFF ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "torso_antenna_base_cap_off", TURN_ON ); - self->client->ps.powerups[PW_GALAK_SHIELD] = 0;//temp, for effect - self->client->ps.stats[STAT_ARMOR] = 0;//no more armor - self->NPC->investigateDebounceTime = 0;//stop recharging + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "torso_shield_off", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "torso_antenna", TURN_OFF); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "torso_antenna_base_cap_off", TURN_ON); + self->client->ps.powerups[PW_GALAK_SHIELD] = 0; // temp, for effect + self->client->ps.stats[STAT_ARMOR] = 0; // no more armor + self->NPC->investigateDebounceTime = 0; // stop recharging - NPC_SetAnim( self, SETANIM_BOTH, BOTH_ALERT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( self, "attackDelay", self->client->ps.torsoAnimTimer ); - G_AddEvent( self, Q_irand( EV_DEATH1, EV_DEATH3 ), self->health ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_ALERT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(self, "attackDelay", self->client->ps.torsoAnimTimer); + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); } - } - else - {//store the point for shield impact - if ( point ) - { - VectorCopy( point, self->pos4 ); + } else { // store the point for shield impact + if (point) { + VectorCopy(point, self->pos4); self->client->poisonTime = level.time; } } - if ( !self->lockCount && !self->client->ps.torsoAnimTimer ) - {//don't interrupt laser sweep attack or other special attacks/moves - if ( self->count < 4 && self->health > 100 && hitLoc != HL_GENERIC1 ) - { - if ( self->delay < level.time ) - { + if (!self->lockCount && !self->client->ps.torsoAnimTimer) { // don't interrupt laser sweep attack or other special attacks/moves + if (self->count < 4 && self->health > 100 && hitLoc != HL_GENERIC1) { + if (self->delay < level.time) { int speech; - switch( self->count ) - { + switch (self->count) { default: case 0: speech = EV_PUSHED1; @@ -314,48 +273,34 @@ void NPC_GM_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, ve } self->count++; self->NPC->blockedSpeechDebounceTime = 0; - G_AddVoiceEvent( self, speech, Q_irand( 3000, 5000 ) ); - self->delay = level.time + Q_irand( 5000, 7000 ); + G_AddVoiceEvent(self, speech, Q_irand(3000, 5000)); + self->delay = level.time + Q_irand(5000, 7000); } + } else { + NPC_Pain(self, inflictor, attacker, point, damage, mod, hitLoc); } - else - { - NPC_Pain( self, inflictor, attacker, point, damage, mod, hitLoc ); - } - } - else if ( hitLoc == HL_GENERIC1 ) - { - NPC_SetPainEvent( self ); - self->s.powerups |= ( 1 << PW_SHOCKED ); - self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); + } else if (hitLoc == HL_GENERIC1) { + NPC_SetPainEvent(self); + self->s.powerups |= (1 << PW_SHOCKED); + self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand(500, 2500); } - if ( inflictor && inflictor->lastEnemy == self ) - {//He force-pushed my own lobfires back at me - if ( mod == MOD_REPEATER_ALT && !Q_irand( 0, 2 ) ) - { - if ( TIMER_Done( self, "noRapid" ) ) - { + if (inflictor && inflictor->lastEnemy == self) { // He force-pushed my own lobfires back at me + if (mod == MOD_REPEATER_ALT && !Q_irand(0, 2)) { + if (TIMER_Done(self, "noRapid")) { self->NPC->scriptFlags &= ~SCF_ALT_FIRE; self->alt_fire = qfalse; - TIMER_Set( self, "noLob", Q_irand( 2000, 6000 ) ); - } - else - {//hopefully this will make us fire the laser - TIMER_Set( self, "noLob", Q_irand( 1000, 2000 ) ); + TIMER_Set(self, "noLob", Q_irand(2000, 6000)); + } else { // hopefully this will make us fire the laser + TIMER_Set(self, "noLob", Q_irand(1000, 2000)); } - } - else if ( mod == MOD_REPEATER && !Q_irand( 0, 5 ) ) - { - if ( TIMER_Done( self, "noLob" ) ) - { + } else if (mod == MOD_REPEATER && !Q_irand(0, 5)) { + if (TIMER_Done(self, "noLob")) { self->NPC->scriptFlags |= SCF_ALT_FIRE; self->alt_fire = qtrue; - TIMER_Set( self, "noRapid", Q_irand( 2000, 6000 ) ); - } - else - {//hopefully this will make us fire the laser - TIMER_Set( self, "noRapid", Q_irand( 1000, 2000 ) ); + TIMER_Set(self, "noRapid", Q_irand(2000, 6000)); + } else { // hopefully this will make us fire the laser + TIMER_Set(self, "noRapid", Q_irand(1000, 2000)); } } } @@ -367,11 +312,9 @@ GM_HoldPosition ------------------------- */ -static void GM_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//don't have a script waiting for me to get to my point, okay to stop trying and stand +static void GM_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // don't have a script waiting for me to get to my point, okay to stop trying and stand NPCInfo->goalEntity = NULL; } } @@ -381,31 +324,26 @@ static void GM_HoldPosition( void ) GM_Move ------------------------- */ -static qboolean GM_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always move straight toward our goal - - qboolean moved = NPC_MoveToGoal( qtrue ); - navInfo_t info; - - //Get the move info - NAV_GetLastMove( info ); - - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPC->enemy ) - { +static qboolean GM_Move(void) { + NPCInfo->combatMove = qtrue; // always move straight toward our goal + + qboolean moved = NPC_MoveToGoal(qtrue); + navInfo_t info; + + // Get the move info + NAV_GetLastMove(info); + + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPC->enemy) { GM_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//FIXME: if we're going to a combat point, need to pick a different one - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//can't transfer movegoal or stop when a script we're running is waiting to complete + // If our move failed, then reset + if (moved == qfalse) { // FIXME: if we're going to a combat point, need to pick a different one + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // can't transfer movegoal or stop when a script we're running is waiting to complete GM_HoldPosition(); } } @@ -419,22 +357,19 @@ NPC_BSGM_Patrol ------------------------- */ -void NPC_BSGM_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGM_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -443,23 +378,20 @@ GM_CheckMoveState ------------------------- */ -static void GM_CheckMoveState( void ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//moving toward a goal that a script is waiting on, so don't stop for anything! +static void GM_CheckMoveState(void) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // moving toward a goal that a script is waiting on, so don't stop for anything! AImove = qtrue; } - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, qfalse ) || - ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) && enemyLOS && enemyDist <= 10000 ) ) - {//either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and found our enemy + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, qfalse) || + (!Q3_TaskIDPending(NPC, TID_MOVE_NAV) && enemyLOS && enemyDist <= 10000)) { // either hit our navgoal or our navgoal was not a crucial (scripted) + // one (maybe a combat point) and we're scouting and found our enemy NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels return; } } @@ -471,84 +403,68 @@ GM_CheckFireState ------------------------- */ -static void GM_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void GM_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //See if we should continue to fire on their last position - if ( !hitAlly && NPCInfo->enemyLastSeenTime > 0 ) - { - if ( level.time - NPCInfo->enemyLastSeenTime < 10000 ) - { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + // See if we should continue to fire on their last position + if (!hitAlly && NPCInfo->enemyLastSeenTime > 0) { + if (level.time - NPCInfo->enemyLastSeenTime < 10000) { + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - gi.trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - float distThreshold = 16384/*128*128*/;//default - if ( NPC->s.weapon == WP_REPEATER ) - { - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + // see if impact would be too close to me + float distThreshold = 16384 /*128*128*/; // default + if (NPC->s.weapon == WP_REPEATER) { + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } } - float dist = DistanceSquared( impactPos, muzzle ); + float dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 5000 ) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - if ( NPC->s.weapon == WP_REPEATER ) - { - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + } else if (level.time - NPCInfo->enemyLastSeenTime > 5000) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + if (NPC->s.weapon == WP_REPEATER) { + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } } - dist = DistanceSquared( impactPos, NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; faceEnemy = qfalse; @@ -559,30 +475,27 @@ static void GM_CheckFireState( void ) } } -void NPC_GM_StartLaser( void ) -{ - if ( !NPC->lockCount ) - {//haven't already started a laser attack - //warm up for the beam attack - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_RAISEWEAP2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "beamDelay", NPC->client->ps.torsoAnimTimer ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.torsoAnimTimer+3000 ); +void NPC_GM_StartLaser(void) { + if (!NPC->lockCount) { // haven't already started a laser attack + // warm up for the beam attack + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_RAISEWEAP2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "beamDelay", NPC->client->ps.torsoAnimTimer); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.torsoAnimTimer + 3000); NPC->lockCount = 1; - //turn on warmup effect - G_PlayEffect( "galak/beam_warmup", NPC->s.number ); - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/weapons/galak/lasercharge.wav" ); + // turn on warmup effect + G_PlayEffect("galak/beam_warmup", NPC->s.number); + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/weapons/galak/lasercharge.wav"); } } -void GM_StartGloat( void ) -{ +void GM_StartGloat(void) { NPC->wait = 0; - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_galakface_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_galakhead_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_eyes_mouth_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_collar_off", TURN_ON ); - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_galaktorso_off", TURN_ON ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_galakface_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_galakhead_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_eyes_mouth_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_collar_off", TURN_ON); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_galaktorso_off", TURN_ON); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer += 500; NPC->client->ps.torsoAnimTimer += 500; } @@ -592,79 +505,58 @@ NPC_BSGM_Attack ------------------------- */ -void NPC_BSGM_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGM_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //FIXME: if killed enemy, use victory anim - if ( NPC->enemy && NPC->enemy->health <= 0 - && !NPC->enemy->s.number ) - {//my enemy is dead - if ( NPC->client->ps.torsoAnim == BOTH_STAND2TO1 ) - { - if ( NPC->client->ps.torsoAnimTimer <= 500 ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // FIXME: if killed enemy, use victory anim + if (NPC->enemy && NPC->enemy->health <= 0 && !NPC->enemy->s.number) { // my enemy is dead + if (NPC->client->ps.torsoAnim == BOTH_STAND2TO1) { + if (NPC->client->ps.torsoAnimTimer <= 500) { + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer += 500; NPC->client->ps.torsoAnimTimer += 500; } - } - else if ( NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1START ) - { - if ( NPC->client->ps.torsoAnimTimer <= 500 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1STARTGESTURE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1START) { + if (NPC->client->ps.torsoAnimTimer <= 500) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1STARTGESTURE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer += 500; NPC->client->ps.torsoAnimTimer += 500; } - } - else if ( NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1STARTGESTURE ) - { - if ( NPC->client->ps.torsoAnimTimer <= 500 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1STARTGESTURE) { + if (NPC->client->ps.torsoAnimTimer <= 500) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_TRIUMPHANT1STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer += 500; NPC->client->ps.torsoAnimTimer += 500; } - } - else if ( NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1STOP ) - { - if ( NPC->client->ps.torsoAnimTimer <= 500 ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (NPC->client->ps.torsoAnim == BOTH_TRIUMPHANT1STOP) { + if (NPC->client->ps.torsoAnimTimer <= 500) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.legsAnimTimer = -1; NPC->client->ps.torsoAnimTimer = -1; } - } - else if ( NPC->wait ) - { - if ( TIMER_Done( NPC, "gloatTime" ) ) - { + } else if (NPC->wait) { + if (TIMER_Done(NPC, "gloatTime")) { GM_StartGloat(); - } - else if ( DistanceHorizontalSquared( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin ) > 4096 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + } else if (DistanceHorizontalSquared(NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin) > 4096 && + (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCInfo->goalEntity = NPC->enemy; GM_Move(); - } - else - {//got there + } else { // got there GM_StartGloat(); } } - NPC_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse || !NPC->enemy ) - { + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse || !NPC->enemy) { NPC->enemy = NULL; NPC_BSGM_Patrol(); return; @@ -675,135 +567,105 @@ void NPC_BSGM_Attack( void ) faceEnemy = qfalse; shoot = qfalse; hitAlly = qfalse; - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + VectorClear(impactPos); + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK4 || - NPC->client->ps.torsoAnim == BOTH_ATTACK5 ) - { + if (NPC->client->ps.torsoAnim == BOTH_ATTACK4 || NPC->client->ps.torsoAnim == BOTH_ATTACK5) { shoot = qfalse; - if ( TIMER_Done( NPC, "smackTime" ) && !NPCInfo->blockedDebounceTime ) - {//time to smack - //recheck enemyDist and InFront - if ( enemyDist < MELEE_DIST_SQUARED && InFront( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f ) ) - { - vec3_t smackDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, smackDir ); + if (TIMER_Done(NPC, "smackTime") && !NPCInfo->blockedDebounceTime) { // time to smack + // recheck enemyDist and InFront + if (enemyDist < MELEE_DIST_SQUARED && InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f)) { + vec3_t smackDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, smackDir); smackDir[2] += 30; - VectorNormalize( smackDir ); - //hurt them - G_Sound( NPC->enemy, G_SoundIndex( "sound/weapons/galak/skewerhit.wav" ) ); - G_Damage( NPC->enemy, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer+1)*Q_irand( 5, 10), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_CRUSH ); - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK4 ) - {//smackdown + VectorNormalize(smackDir); + // hurt them + G_Sound(NPC->enemy, G_SoundIndex("sound/weapons/galak/skewerhit.wav")); + G_Damage(NPC->enemy, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer + 1) * Q_irand(5, 10), DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, + MOD_CRUSH); + if (NPC->client->ps.torsoAnim == BOTH_ATTACK4) { // smackdown int knockAnim = BOTH_KNOCKDOWN1; - if ( PM_CrouchAnim( NPC->enemy->client->ps.legsAnim ) ) - {//knockdown from crouch + if (PM_CrouchAnim(NPC->enemy->client->ps.legsAnim)) { // knockdown from crouch knockAnim = BOTH_KNOCKDOWN4; } - //throw them + // throw them smackDir[2] = 1; - VectorNormalize( smackDir ); - G_Throw( NPC->enemy, smackDir, 50 ); - NPC_SetAnim( NPC->enemy, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//uppercut - //throw them - G_Throw( NPC->enemy, smackDir, 100 ); - //make them backflip - NPC_SetAnim( NPC->enemy, SETANIM_BOTH, BOTH_KNOCKDOWN5, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + VectorNormalize(smackDir); + G_Throw(NPC->enemy, smackDir, 50); + NPC_SetAnim(NPC->enemy, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // uppercut + // throw them + G_Throw(NPC->enemy, smackDir, 100); + // make them backflip + NPC_SetAnim(NPC->enemy, SETANIM_BOTH, BOTH_KNOCKDOWN5, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //done with the damage + // done with the damage NPCInfo->blockedDebounceTime = 1; } } - } - else if ( NPC->lockCount ) //already shooting laser - {//sometimes use the laser beam attack, but only after he's taken down our generator + } else if (NPC->lockCount) // already shooting laser + { // sometimes use the laser beam attack, but only after he's taken down our generator shoot = qfalse; - if ( NPC->lockCount == 1 ) - {//charging up - if ( TIMER_Done( NPC, "beamDelay" ) ) - {//time to start the beam + if (NPC->lockCount == 1) { // charging up + if (TIMER_Done(NPC, "beamDelay")) { // time to start the beam int laserAnim; - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { laserAnim = BOTH_ATTACK2; - } - else - { + } else { laserAnim = BOTH_ATTACK7; } - NPC_SetAnim( NPC, SETANIM_BOTH, laserAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.torsoAnimTimer + Q_irand( 1000, 3000 ) ); - //turn on beam effect + NPC_SetAnim(NPC, SETANIM_BOTH, laserAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.torsoAnimTimer + Q_irand(1000, 3000)); + // turn on beam effect NPC->lockCount = 2; - G_PlayEffect( "galak/trace_beam", NPC->s.number ); - NPC->s.loopSound = G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); - if ( !NPCInfo->coverTarg ) - {//for moving looping sound at end of trace + G_PlayEffect("galak/trace_beam", NPC->s.number); + NPC->s.loopSound = G_SoundIndex("sound/weapons/galak/lasercutting.wav"); + if (!NPCInfo->coverTarg) { // for moving looping sound at end of trace NPCInfo->coverTarg = G_Spawn(); - if ( NPCInfo->coverTarg ) - { - G_SetOrigin( NPCInfo->coverTarg, NPC->client->renderInfo.muzzlePoint ); + if (NPCInfo->coverTarg) { + G_SetOrigin(NPCInfo->coverTarg, NPC->client->renderInfo.muzzlePoint); NPCInfo->coverTarg->svFlags |= SVF_BROADCAST; - NPCInfo->coverTarg->s.loopSound = G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); + NPCInfo->coverTarg->s.loopSound = G_SoundIndex("sound/weapons/galak/lasercutting.wav"); } } } - } - else - {//in the actual attack now - if ( !NPC->client->ps.torsoAnimTimer ) - {//attack done! + } else { // in the actual attack now + if (!NPC->client->ps.torsoAnimTimer) { // attack done! NPC->lockCount = 0; - G_FreeEntity( NPCInfo->coverTarg ); + G_FreeEntity(NPCInfo->coverTarg); NPC->s.loopSound = 0; - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_DROPWEAP2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.torsoAnimTimer ); - } - else - {//attack still going - //do the trace and damage - trace_t trace; - vec3_t end, mins={-3,-3,-3}, maxs={3,3,3}; - VectorMA( NPC->client->renderInfo.muzzlePoint, 1024, NPC->client->renderInfo.muzzleDir, end ); - gi.trace( &trace, NPC->client->renderInfo.muzzlePoint, mins, maxs, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//oops, in a wall - if ( NPCInfo->coverTarg ) - { - G_SetOrigin( NPCInfo->coverTarg, NPC->client->renderInfo.muzzlePoint ); + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_DROPWEAP2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.torsoAnimTimer); + } else { // attack still going + // do the trace and damage + trace_t trace; + vec3_t end, mins = {-3, -3, -3}, maxs = {3, 3, 3}; + VectorMA(NPC->client->renderInfo.muzzlePoint, 1024, NPC->client->renderInfo.muzzleDir, end); + gi.trace(&trace, NPC->client->renderInfo.muzzlePoint, mins, maxs, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid) { // oops, in a wall + if (NPCInfo->coverTarg) { + G_SetOrigin(NPCInfo->coverTarg, NPC->client->renderInfo.muzzlePoint); } - } - else - {//clear - if ( trace.fraction < 1.0f ) - {//hit something + } else { // clear + if (trace.fraction < 1.0f) { // hit something gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && traceEnt->takedamage ) - {//damage it - G_SoundAtSpot( trace.endpos, G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ) ); - G_Damage( traceEnt, NPC, NPC, NPC->client->renderInfo.muzzleDir, trace.endpos, 10, 0, MOD_ENERGY ); + if (traceEnt && traceEnt->takedamage) { // damage it + G_SoundAtSpot(trace.endpos, G_SoundIndex("sound/weapons/galak/laserdamage.wav")); + G_Damage(traceEnt, NPC, NPC, NPC->client->renderInfo.muzzleDir, trace.endpos, 10, 0, MOD_ENERGY); } } - if ( NPCInfo->coverTarg ) - { - G_SetOrigin( NPCInfo->coverTarg, trace.endpos ); + if (NPCInfo->coverTarg) { + G_SetOrigin(NPCInfo->coverTarg, trace.endpos); } - if ( !Q_irand( 0, 5 ) ) - { - G_SoundAtSpot( trace.endpos, G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ) ); + if (!Q_irand(0, 5)) { + G_SoundAtSpot(trace.endpos, G_SoundIndex("sound/weapons/galak/laserdamage.wav")); } } } } - } - else - {//Okay, we're not in a special attack, see if we should switch weapons or start a special attack + } else { // Okay, we're not in a special attack, see if we should switch weapons or start a special attack /* - if ( NPC->s.weapon == WP_REPEATER + if ( NPC->s.weapon == WP_REPEATER && !(NPCInfo->scriptFlags & SCF_ALT_FIRE)//using rapid-fire && NPC->enemy->s.weapon == WP_SABER //enemy using saber && NPC->client && (NPC->client->ps.saberEventFlags&SEF_DEFLECTED) @@ -818,121 +680,91 @@ void NPC_BSGM_Attack( void ) } } else*/ - if ( !NPC->client->ps.powerups[PW_GALAK_SHIELD] - && enemyDist < MELEE_DIST_SQUARED - && InFront( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f ) - && G_StandardHumanoid( NPC->enemy->NPC_type ) )//within 80 and in front - {//our shield is down, and enemy within 80, if very close, use melee attack to slap away - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - //animate me + if (!NPC->client->ps.powerups[PW_GALAK_SHIELD] && enemyDist < MELEE_DIST_SQUARED && + InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f) && + G_StandardHumanoid(NPC->enemy->NPC_type)) // within 80 and in front + { // our shield is down, and enemy within 80, if very close, use melee attack to slap away + if (TIMER_Done(NPC, "attackDelay")) { + // animate me int swingAnim; - if ( NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH ) - {//generator down, use random melee - swingAnim = Q_irand( BOTH_ATTACK4, BOTH_ATTACK5 );//smackdown or uppercut - } - else - {//always knock-away - swingAnim = BOTH_ATTACK5;//uppercut + if (NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH) { // generator down, use random melee + swingAnim = Q_irand(BOTH_ATTACK4, BOTH_ATTACK5); // smackdown or uppercut + } else { // always knock-away + swingAnim = BOTH_ATTACK5; // uppercut } - //FIXME: swing sound - NPC_SetAnim( NPC, SETANIM_BOTH, swingAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.torsoAnimTimer + Q_irand( 1000, 3000 ) ); - //delay the hurt until the proper point in the anim - TIMER_Set( NPC, "smackTime", 600 ); + // FIXME: swing sound + NPC_SetAnim(NPC, SETANIM_BOTH, swingAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.torsoAnimTimer + Q_irand(1000, 3000)); + // delay the hurt until the proper point in the anim + TIMER_Set(NPC, "smackTime", 600); NPCInfo->blockedDebounceTime = 0; - //FIXME: say something? + // FIXME: say something? } - } - else if ( !NPC->lockCount && NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH - && TIMER_Done( NPC, "attackDelay" ) - && InFront( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f ) - && ((!Q_irand( 0, 10*(2-g_spskill->integer))&& enemyDist > MIN_LOB_DIST_SQUARED&& enemyDist < MAX_LOB_DIST_SQUARED) - ||(!TIMER_Done( NPC, "noLob" )&&!TIMER_Done( NPC, "noRapid" ))) - && NPC->enemy->s.weapon != WP_TURRET ) - {//sometimes use the laser beam attack, but only after he's taken down our generator + } else if (!NPC->lockCount && NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH && TIMER_Done(NPC, "attackDelay") && + InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.3f) && + ((!Q_irand(0, 10 * (2 - g_spskill->integer)) && enemyDist > MIN_LOB_DIST_SQUARED && enemyDist < MAX_LOB_DIST_SQUARED) || + (!TIMER_Done(NPC, "noLob") && !TIMER_Done(NPC, "noRapid"))) && + NPC->enemy->s.weapon != WP_TURRET) { // sometimes use the laser beam attack, but only after he's taken down our generator shoot = qfalse; NPC_GM_StartLaser(); - } - else if ( enemyDist < MIN_LOB_DIST_SQUARED - && (NPC->enemy->s.weapon != WP_TURRET || Q_stricmp( "PAS", NPC->enemy->classname )) - && TIMER_Done( NPC, "noRapid" ) )//256 - {//enemy within 256 - if ( (NPC->client->ps.weapon == WP_REPEATER) && (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + } else if (enemyDist < MIN_LOB_DIST_SQUARED && (NPC->enemy->s.weapon != WP_TURRET || Q_stricmp("PAS", NPC->enemy->classname)) && + TIMER_Done(NPC, "noRapid")) // 256 + { // enemy within 256 + if ((NPC->client->ps.weapon == WP_REPEATER) && + (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; NPC->alt_fire = qfalse; - //FIXME: use weap raise & lower anims - NPC_ChangeWeapon( WP_REPEATER ); + // FIXME: use weap raise & lower anims + NPC_ChangeWeapon(WP_REPEATER); } - } - else if ( (enemyDist > MAX_LOB_DIST_SQUARED || (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPC->enemy->classname ))) - && TIMER_Done( NPC, "noLob" ) )//448 - {//enemy more than 448 away and we are ready to try lob fire again - if ( (NPC->client->ps.weapon == WP_REPEATER) && !(NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//enemy far enough away to use lobby explosives + } else if ((enemyDist > MAX_LOB_DIST_SQUARED || (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname))) && + TIMER_Done(NPC, "noLob")) // 448 + { // enemy more than 448 away and we are ready to try lob fire again + if ((NPC->client->ps.weapon == WP_REPEATER) && !(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // enemy far enough away to use lobby explosives NPCInfo->scriptFlags |= SCF_ALT_FIRE; NPC->alt_fire = qtrue; - //FIXME: use weap raise & lower anims - NPC_ChangeWeapon( WP_REPEATER ); + // FIXME: use weap raise & lower anims + NPC_ChangeWeapon(WP_REPEATER); } } } - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { - NPCInfo->enemyLastSeenTime = level.time;//used here for aim debouncing, not always a clear LOS + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { + NPCInfo->enemyLastSeenTime = level.time; // used here for aim debouncing, not always a clear LOS enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - NPC_AimAdjust( -1 );//adjust aim worse longer we have no weapon - } - else - {//can we shoot our target? - if ( ((NPC->client->ps.weapon == WP_REPEATER && (NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist < MIN_LOB_DIST_SQUARED )//256 - { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else + if (NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + NPC_AimAdjust(-1); // adjust aim worse longer we have no weapon + } else { // can we shoot our target? + if (((NPC->client->ps.weapon == WP_REPEATER && (NPCInfo->scriptFlags & SCF_ALT_FIRE))) && enemyDist < MIN_LOB_DIST_SQUARED) // 256 { - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else { + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other breakable, so shoot anyway + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other breakable, so shoot anyway enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + NPC_AimAdjust(1); // adjust aim better longer we can see enemy + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } } } - } - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { - if ( TIMER_Done( NPC, "talkDebounce" ) && !Q_irand( 0, 10 ) ) - { - if ( NPCInfo->enemyCheckDebounceTime < 8 ) - { + } else if (gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { + if (TIMER_Done(NPC, "talkDebounce") && !Q_irand(0, 10)) { + if (NPCInfo->enemyCheckDebounceTime < 8) { int speech = -1; - switch( NPCInfo->enemyCheckDebounceTime ) - { + switch (NPCInfo->enemyCheckDebounceTime) { case 0: case 1: case 2: @@ -941,330 +773,259 @@ void NPC_BSGM_Attack( void ) case 3: case 4: case 5: - speech = EV_COVER1 + NPCInfo->enemyCheckDebounceTime-3; + speech = EV_COVER1 + NPCInfo->enemyCheckDebounceTime - 3; break; case 6: case 7: - speech = EV_ESCAPING1 + NPCInfo->enemyCheckDebounceTime-6; + speech = EV_ESCAPING1 + NPCInfo->enemyCheckDebounceTime - 6; break; } NPCInfo->enemyCheckDebounceTime++; - if ( speech != -1 ) - { - G_AddVoiceEvent( NPC, speech, Q_irand( 3000, 5000 ) ); - TIMER_Set( NPC, "talkDebounce", Q_irand( 5000, 7000 ) ); + if (speech != -1) { + G_AddVoiceEvent(NPC, speech, Q_irand(3000, 5000)); + TIMER_Set(NPC, "talkDebounce", Q_irand(5000, 7000)); } } } NPCInfo->enemyLastSeenTime = level.time; - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other breakable, so shoot anyway + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other breakable, so shoot anyway enemyCS = qtrue; - } - else - { + } else { faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } } - if ( enemyLOS ) - { + if (enemyLOS) { faceEnemy = qtrue; - } - else - { - if ( !NPCInfo->goalEntity ) - { + } else { + if (!NPCInfo->goalEntity) { NPCInfo->goalEntity = NPC->enemy; } - if ( NPCInfo->goalEntity == NPC->enemy ) - {//for now, always chase the enemy + if (NPCInfo->goalEntity == NPC->enemy) { // for now, always chase the enemy AImove = qtrue; } } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; - //NPCInfo->enemyCheckDebounceTime = level.time;//actually used here as a last actual LOS - } - else - { - if ( !NPCInfo->goalEntity ) - { + // NPCInfo->enemyCheckDebounceTime = level.time;//actually used here as a last actual LOS + } else { + if (!NPCInfo->goalEntity) { NPCInfo->goalEntity = NPC->enemy; } - if ( NPCInfo->goalEntity == NPC->enemy ) - {//for now, always chase the enemy + if (NPCInfo->goalEntity == NPC->enemy) { // for now, always chase the enemy AImove = qtrue; } } - //Check for movement to take care of + // Check for movement to take care of GM_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations GM_CheckFireState(); - if ( NPC->client->ps.weapon == WP_REPEATER && (NPCInfo->scriptFlags&SCF_ALT_FIRE) && shoot && TIMER_Done( NPC, "attackDelay" ) ) - { - vec3_t muzzle; - vec3_t angles; - vec3_t target; - vec3_t velocity = {0,0,0}; - vec3_t mins = {-REPEATER_ALT_SIZE,-REPEATER_ALT_SIZE,-REPEATER_ALT_SIZE}, maxs = {REPEATER_ALT_SIZE,REPEATER_ALT_SIZE,REPEATER_ALT_SIZE}; - - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - - VectorCopy( NPC->enemy->currentOrigin, target ); - - target[0] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCInfo->currentAim)*2); - target[1] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCInfo->currentAim)*2); - target[2] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCInfo->currentAim)*2); - - //Find the desired angles - qboolean clearshot = WP_LobFire( NPC, muzzle, target, mins, maxs, MASK_SHOT|CONTENTS_LIGHTSABER, - velocity, qtrue, NPC->s.number, NPC->enemy->s.number, - 300, 1100, 1500, qtrue ); - if ( VectorCompare( vec3_origin, velocity ) || (!clearshot&&enemyLOS&&enemyCS) ) - {//no clear lob shot and no lob shot that will hit something breakable - if ( enemyLOS && enemyCS && TIMER_Done( NPC, "noRapid" ) ) - {//have a clear straight shot, so switch to primary + if (NPC->client->ps.weapon == WP_REPEATER && (NPCInfo->scriptFlags & SCF_ALT_FIRE) && shoot && TIMER_Done(NPC, "attackDelay")) { + vec3_t muzzle; + vec3_t angles; + vec3_t target; + vec3_t velocity = {0, 0, 0}; + vec3_t mins = {-REPEATER_ALT_SIZE, -REPEATER_ALT_SIZE, -REPEATER_ALT_SIZE}, maxs = {REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE}; + + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); + + VectorCopy(NPC->enemy->currentOrigin, target); + + target[0] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCInfo->currentAim) * 2); + target[1] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCInfo->currentAim) * 2); + target[2] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCInfo->currentAim) * 2); + + // Find the desired angles + qboolean clearshot = WP_LobFire(NPC, muzzle, target, mins, maxs, MASK_SHOT | CONTENTS_LIGHTSABER, velocity, qtrue, NPC->s.number, NPC->enemy->s.number, + 300, 1100, 1500, qtrue); + if (VectorCompare(vec3_origin, velocity) || (!clearshot && enemyLOS && enemyCS)) { // no clear lob shot and no lob shot that will hit something + // breakable + if (enemyLOS && enemyCS && TIMER_Done(NPC, "noRapid")) { // have a clear straight shot, so switch to primary NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; NPC->alt_fire = qfalse; - NPC_ChangeWeapon( WP_REPEATER ); - //keep this weap for a bit - TIMER_Set( NPC, "noLob", Q_irand( 500, 1000 ) ); - } - else - { + NPC_ChangeWeapon(WP_REPEATER); + // keep this weap for a bit + TIMER_Set(NPC, "noLob", Q_irand(500, 1000)); + } else { shoot = qfalse; } - } - else - { - vectoangles( velocity, angles ); + } else { + vectoangles(velocity, angles); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); - VectorCopy( velocity, NPC->client->hiddenDir ); - NPC->client->hiddenDist = VectorNormalize ( NPC->client->hiddenDir ); + VectorCopy(velocity, NPC->client->hiddenDir); + NPC->client->hiddenDist = VectorNormalize(NPC->client->hiddenDir); } - } - else if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); + } else if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); } - if ( !TIMER_Done( NPC, "standTime" ) ) - { + if (!TIMER_Done(NPC, "standTime")) { AImove = qfalse; } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not supposed to chase my enemies - if ( NPCInfo->goalEntity == NPC->enemy ) - {//goal is my entity, so don't move + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not supposed to chase my enemies + if (NPCInfo->goalEntity == NPC->enemy) { // goal is my entity, so don't move AImove = qfalse; } } - if ( AImove && !NPC->lockCount ) - {//move toward goal - if ( NPCInfo->goalEntity - && NPC->client->ps.legsAnim != BOTH_ALERT1 - && NPC->client->ps.legsAnim != BOTH_ATTACK2 - && NPC->client->ps.legsAnim != BOTH_ATTACK4 - && NPC->client->ps.legsAnim != BOTH_ATTACK5 - && NPC->client->ps.legsAnim != BOTH_ATTACK7 ) - { + if (AImove && !NPC->lockCount) { // move toward goal + if (NPCInfo->goalEntity && NPC->client->ps.legsAnim != BOTH_ALERT1 && NPC->client->ps.legsAnim != BOTH_ATTACK2 && + NPC->client->ps.legsAnim != BOTH_ATTACK4 && NPC->client->ps.legsAnim != BOTH_ATTACK5 && NPC->client->ps.legsAnim != BOTH_ATTACK7) { AImove = GM_Move(); - } - else - { + } else { AImove = qfalse; } } - if ( !TIMER_Done( NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPC, "flee")) { // running away faceEnemy = qfalse; } - //FIXME: check scf_face_move_dir here? + // FIXME: check scf_face_move_dir here? - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( !AImove ) - {//if we haven't moved, we should look in the direction we last looked? - VectorCopy( NPC->client->ps.viewangles, NPCInfo->lastPathAngles ); + if (!faceEnemy) { // we want to face in the dir we're running + if (!AImove) { // if we haven't moved, we should look in the direction we last looked? + VectorCopy(NPC->client->ps.viewangles, NPCInfo->lastPathAngles); } - if ( AImove ) - {//don't run away and shoot + if (AImove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPC->enemy && NPC->enemy->enemy ) - { - if ( NPC->enemy->s.weapon == WP_SABER && NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPC->enemy && NPC->enemy->enemy) { + if (NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue + // blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } } } - //also: - if ( NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPC->enemy->classname ) ) - {//crush turrets - if ( G_BoundsOverlap( NPC->absmin, NPC->absmax, NPC->enemy->absmin, NPC->enemy->absmax ) ) - {//have to do this test because placed turrets are not solid to NPCs (so they don't obstruct navigation) - if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) - { + // also: + if (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname)) { // crush turrets + if (G_BoundsOverlap(NPC->absmin, NPC->absmax, NPC->enemy->absmin, + NPC->enemy->absmax)) { // have to do this test because placed turrets are not solid to NPCs (so they don't obstruct navigation) + if (NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0) { NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; - G_Damage( NPC->enemy, NPC, NPC, NULL, NPC->currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE ); - } - else - { - G_Damage( NPC->enemy, NPC, NPC, NULL, NPC->currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_CRUSH ); + G_Damage(NPC->enemy, NPC, NPC, NULL, NPC->currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE); + } else { + G_Damage(NPC->enemy, NPC, NPC, NULL, NPC->currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_CRUSH); } } - } - else if ( NPCInfo->touchedByPlayer != NULL && NPCInfo->touchedByPlayer == NPC->enemy ) - {//touched enemy - if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) - {//zap him! - //animate me - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK6, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "attackDelay", NPC->client->ps.torsoAnimTimer ); - TIMER_Set( NPC, "standTime", NPC->client->ps.legsAnimTimer ); - //FIXME: debounce this? + } else if (NPCInfo->touchedByPlayer != NULL && NPCInfo->touchedByPlayer == NPC->enemy) { // touched enemy + if (NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0) { // zap him! + // animate me + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK6, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.torsoAnimTimer); + TIMER_Set(NPC, "standTime", NPC->client->ps.legsAnimTimer); + // FIXME: debounce this? NPCInfo->touchedByPlayer = NULL; - //FIXME: some shield effect? + // FIXME: some shield effect? NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; - vec3_t smackDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, smackDir ); + vec3_t smackDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, smackDir); smackDir[2] += 30; - VectorNormalize( smackDir ); - G_Damage( NPC->enemy, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer+1)*Q_irand( 5, 10), DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE ); - //throw them - G_Throw( NPC->enemy, smackDir, 100 ); - NPC->enemy->s.powerups |= ( 1 << PW_SHOCKED ); - if ( NPC->enemy->client ) - { + VectorNormalize(smackDir); + G_Damage(NPC->enemy, NPC, NPC, smackDir, NPC->currentOrigin, (g_spskill->integer + 1) * Q_irand(5, 10), DAMAGE_NO_KNOCKBACK, MOD_ELECTROCUTE); + // throw them + G_Throw(NPC->enemy, smackDir, 100); + NPC->enemy->s.powerups |= (1 << PW_SHOCKED); + if (NPC->enemy->client) { NPC->enemy->client->ps.powerups[PW_SHOCKED] = level.time + 1000; } - //stop any attacks + // stop any attacks ucmd.buttons = 0; } } - if ( NPCInfo->movementSpeech < 3 && NPCInfo->blockedSpeechDebounceTime <= level.time ) - { - if ( NPC->enemy && NPC->enemy->health > 0 && NPC->enemy->painDebounceTime > level.time ) - { - if ( NPC->enemy->health < 50 && NPCInfo->movementSpeech == 2 ) - { - G_AddVoiceEvent( NPC, EV_ANGER2, Q_irand( 2000, 4000 ) ); + if (NPCInfo->movementSpeech < 3 && NPCInfo->blockedSpeechDebounceTime <= level.time) { + if (NPC->enemy && NPC->enemy->health > 0 && NPC->enemy->painDebounceTime > level.time) { + if (NPC->enemy->health < 50 && NPCInfo->movementSpeech == 2) { + G_AddVoiceEvent(NPC, EV_ANGER2, Q_irand(2000, 4000)); NPCInfo->movementSpeech = 3; - } - else if ( NPC->enemy->health < 75 && NPCInfo->movementSpeech == 1 ) - { - G_AddVoiceEvent( NPC, EV_ANGER1, Q_irand( 2000, 4000 ) ); + } else if (NPC->enemy->health < 75 && NPCInfo->movementSpeech == 1) { + G_AddVoiceEvent(NPC, EV_ANGER1, Q_irand(2000, 4000)); NPCInfo->movementSpeech = 2; - } - else if ( NPC->enemy->health < 100 && NPCInfo->movementSpeech == 0 ) - { - G_AddVoiceEvent( NPC, EV_ANGER3, Q_irand( 2000, 4000 ) ); + } else if (NPC->enemy->health < 100 && NPCInfo->movementSpeech == 0) { + G_AddVoiceEvent(NPC, EV_ANGER3, Q_irand(2000, 4000)); NPCInfo->movementSpeech = 1; } } } } -void NPC_BSGM_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSGM_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - - if ( NPC->client->ps.stats[STAT_ARMOR] <= 0 ) - {//armor gone - if ( !NPCInfo->investigateDebounceTime ) - {//start regenerating the armor - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_OFF ); - NPC->flags &= ~FL_SHIELDED;//no more reflections - VectorSet( NPC->mins, -20, -20, -24 ); - VectorSet( NPC->maxs, 20, 20, 64 ); + + if (NPC->client->ps.stats[STAT_ARMOR] <= 0) { // armor gone + if (!NPCInfo->investigateDebounceTime) { // start regenerating the armor + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_OFF); + NPC->flags &= ~FL_SHIELDED; // no more reflections + VectorSet(NPC->mins, -20, -20, -24); + VectorSet(NPC->maxs, 20, 20, 64); NPC->client->crouchheight = NPC->client->standheight = 64; - if ( NPC->locationDamage[HL_GENERIC1] < GENERATOR_HEALTH ) - {//still have the generator bolt-on - if ( NPCInfo->investigateCount < 12 ) - { + if (NPC->locationDamage[HL_GENERIC1] < GENERATOR_HEALTH) { // still have the generator bolt-on + if (NPCInfo->investigateCount < 12) { NPCInfo->investigateCount++; } NPCInfo->investigateDebounceTime = level.time + (NPCInfo->investigateCount * 5000); } - } - else if ( NPCInfo->investigateDebounceTime < level.time ) - {//armor regenerated, turn shield back on - //do a trace and make sure we can turn this back on? - trace_t tr; - gi.trace( &tr, NPC->currentOrigin, shieldMins, shieldMaxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( !tr.startsolid ) - { - VectorCopy( shieldMins, NPC->mins ); - VectorCopy( shieldMaxs, NPC->maxs ); + } else if (NPCInfo->investigateDebounceTime < level.time) { // armor regenerated, turn shield back on + // do a trace and make sure we can turn this back on? + trace_t tr; + gi.trace(&tr, NPC->currentOrigin, shieldMins, shieldMaxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (!tr.startsolid) { + VectorCopy(shieldMins, NPC->mins); + VectorCopy(shieldMaxs, NPC->maxs); NPC->client->crouchheight = NPC->client->standheight = shieldMaxs[2]; NPC->client->ps.stats[STAT_ARMOR] = GALAK_SHIELD_HEALTH; NPCInfo->investigateDebounceTime = 0; - NPC->flags |= FL_SHIELDED;//reflect normal shots + NPC->flags |= FL_SHIELDED; // reflect normal shots NPC->fx_time = level.time; - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_ON ); + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_ON); } } } - if ( NPC->client->ps.stats[STAT_ARMOR] > 0 ) - {//armor present - NPC->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE;//temp, for effect - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_ON ); - } - else - { - gi.G2API_SetSurfaceOnOff( &NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_OFF ); + if (NPC->client->ps.stats[STAT_ARMOR] > 0) { // armor present + NPC->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE; // temp, for effect + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_ON); + } else { + gi.G2API_SetSurfaceOnOff(&NPC->ghoul2[NPC->playerModel], "torso_shield_off", TURN_OFF); } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSGM_Patrol(); - } - else //if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSGM_Attack(); } } diff --git a/codeJK2/game/AI_Grenadier.cpp b/codeJK2/game/AI_Grenadier.cpp index 125eaf8ebd..df8e67c1ed 100644 --- a/codeJK2/game/AI_Grenadier.cpp +++ b/codeJK2/game/AI_Grenadier.cpp @@ -26,100 +26,93 @@ along with this program; if not, see . #include "anims.h" #include "g_navigator.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); -extern CNavigator navigator; +extern CNavigator navigator; -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; static qboolean faceEnemy; static qboolean AImove; static qboolean shoot; -static float enemyDist; +static float enemyDist; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Grenadier_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); +void Grenadier_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); } -void NPC_Grenadier_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Grenadier_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Grenadier_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod ) -{ +void NPC_Grenadier_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -129,11 +122,10 @@ ST_HoldPosition ------------------------- */ -static void Grenadier_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); +static void Grenadier_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); NPCInfo->goalEntity = NULL; - + /*if ( TIMER_Done( NPC, "stand" ) ) {//FIXME: what if can't shoot from this pos? TIMER_Set( NPC, "duck", Q_irand( 2000, 4000 ) ); @@ -147,52 +139,45 @@ ST_Move ------------------------- */ -static qboolean Grenadier_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always move straight toward our goal +static qboolean Grenadier_Move(void) { + NPCInfo->combatMove = qtrue; // always move straight toward our goal - qboolean moved = NPC_MoveToGoal( qtrue ); - navInfo_t info; - - //Get the move info - NAV_GetLastMove( info ); + qboolean moved = NPC_MoveToGoal(qtrue); + navInfo_t info; - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPC->enemy ) - { + // Get the move info + NAV_GetLastMove(info); + + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPC->enemy) { Grenadier_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPC->client->ps.weapon == WP_THERMAL && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + // If our move failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPC->client->ps.weapon == WP_THERMAL && NPCInfo->goalEntity && + NPCInfo->goalEntity == NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); return moved; } } - //just hang here + // just hang here Grenadier_HoldPosition(); } @@ -205,77 +190,61 @@ NPC_BSGrenadier_Patrol ------------------------- */ -void NPC_BSGrenadier_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - { + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID) { NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; - - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); - + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; + + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); + o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - - NPC_UpdateAngles( qtrue, qtrue ); + + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -284,14 +253,13 @@ void NPC_BSGrenadier_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -322,26 +290,20 @@ ST_CheckMoveState ------------------------- */ -static void Grenadier_CheckMoveState( void ) -{ - //See if we're a scout - if ( !(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//behaviorState == BS_STAND_AND_SHOOT ) +static void Grenadier_CheckMoveState(void) { + // See if we're a scout + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { AImove = qfalse; return; } } - //See if we're running away - else if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPC, "flee" ) ) - { + // See if we're running away + else if (NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPC, "flee")) { NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy = qfalse; } } @@ -357,52 +319,46 @@ static void Grenadier_CheckMoveState( void ) } */ - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature( NPC ) ) || - ( NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - { - //int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - //newSquadState = SQUAD_COVER; + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature(NPC)) || + (NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet + TIMER_Set(NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(4000, 8000)); } - if ( !NPCInfo->goalEntity ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { + if (!NPCInfo->goalEntity) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { NPCInfo->goalEntity = NPC->enemy; } } @@ -414,24 +370,21 @@ ST_CheckFireState ------------------------- */ -static void Grenadier_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void Grenadier_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //continue to fire on their last position + // continue to fire on their last position /* if ( !Q_irand( 0, 1 ) && NPCInfo->enemyLastSeenTime && level.time - NPCInfo->enemyLastSeenTime < 4000 ) { @@ -456,15 +409,13 @@ static void Grenadier_CheckFireState( void ) */ } -qboolean Grenadier_EvaluateShot( int hit ) -{ - if ( !NPC->enemy ) - { +qboolean Grenadier_EvaluateShot(int hit) { + if (!NPC->enemy) { return qfalse; } - if ( hit == NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -476,33 +427,29 @@ NPC_BSGrenadier_Attack ------------------------- */ -void NPC_BSGrenadier_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } @@ -510,75 +457,61 @@ void NPC_BSGrenadier_Attack( void ) AImove = qtrue; faceEnemy = qfalse; shoot = qfalse; - enemyDist = DistanceSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ); - - //See if we should switch to melee attack - if ( enemyDist < 16384 && (!NPC->enemy->client||NPC->enemy->client->ps.weapon != WP_SABER||!NPC->enemy->client->ps.saberActive) )//128 - {//enemy is close and not using saber - if ( NPC->client->ps.weapon == WP_THERMAL ) - {//grenadier - trace_t trace; - gi.trace ( &trace, NPC->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->enemy->currentOrigin, NPC->s.number, NPC->enemy->clipmask, G2_NOCOLLIDE, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->enemy->s.number ) ) - {//I can get right to him - //reset fire-timing variables - NPC_ChangeWeapon( WP_MELEE ); - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) - {//FIXME: should we be overriding scriptFlags? - NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES;//NPCInfo->behaviorState = BS_HUNT_AND_KILL; + enemyDist = DistanceSquared(NPC->enemy->currentOrigin, NPC->currentOrigin); + + // See if we should switch to melee attack + if (enemyDist < 16384 && (!NPC->enemy->client || NPC->enemy->client->ps.weapon != WP_SABER || !NPC->enemy->client->ps.saberActive)) // 128 + { // enemy is close and not using saber + if (NPC->client->ps.weapon == WP_THERMAL) { // grenadier + trace_t trace; + gi.trace(&trace, NPC->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->enemy->currentOrigin, NPC->s.number, NPC->enemy->clipmask, + G2_NOCOLLIDE, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->enemy->s.number)) { // I can get right to him + // reset fire-timing variables + NPC_ChangeWeapon(WP_MELEE); + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) + { // FIXME: should we be overriding scriptFlags? + NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES; // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } } } - } - else if ( enemyDist > 65536 || (NPC->enemy->client && NPC->enemy->client->ps.weapon == WP_SABER && NPC->enemy->client->ps.saberActive) )//256 - {//enemy is far or using saber - if ( NPC->client->ps.weapon == WP_MELEE && (NPC->client->ps.stats[STAT_WEAPONS]&(1< 65536 || (NPC->enemy->client && NPC->enemy->client->ps.weapon == WP_SABER && NPC->enemy->client->ps.saberActive)) // 256 + { // enemy is far or using saber + if (NPC->client->ps.weapon == WP_MELEE && (NPC->client->ps.stats[STAT_WEAPONS] & (1 << WP_THERMAL))) { // fisticuffs, make switch to thermal if have it + // reset fire-timing variables + NPC_ChangeWeapon(WP_THERMAL); } } - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_MELEE ) - { - if ( enemyDist <= 4096 && InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45 ) )//within 64 & infront + if (NPC->client->ps.weapon == WP_MELEE) { + if (enemyDist <= 4096 && InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 90, 45)) // within 64 & infront { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); enemyCS = qtrue; } - } - else if ( InFOV( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 45, 90 ) ) - {//in front of me - //can we shoot our target? - //FIXME: how accurate/necessary is this check? - int hit = NPC_ShotEntity( NPC->enemy ); + } else if (InFOV(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 45, 90)) { // in front of me + // can we shoot our target? + // FIXME: how accurate/necessary is this check? + int hit = NPC_ShotEntity(NPC->enemy); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) ) - { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - float enemyHorzDist = DistanceHorizontalSquared( NPC->enemy->currentOrigin, NPC->currentOrigin ); - if ( enemyHorzDist < 1048576 ) - {//within 1024 + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam)) { + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + float enemyHorzDist = DistanceHorizontalSquared(NPC->enemy->currentOrigin, NPC->currentOrigin); + if (enemyHorzDist < 1048576) { // within 1024 enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - } - else - { - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + } else { + NPC_AimAdjust(1); // adjust aim better longer we can see enemy } } } - } - else - { - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } else { + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } /* else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) @@ -588,103 +521,81 @@ void NPC_BSGrenadier_Attack( void ) } */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; - if ( NPC->client->ps.weapon == WP_THERMAL ) - {//don't chase and throw + if (NPC->client->ps.weapon == WP_THERMAL) { // don't chase and throw AImove = qfalse; - } - else if ( NPC->client->ps.weapon == WP_MELEE && enemyDist < (NPC->maxs[0]+NPC->enemy->maxs[0]+16)*(NPC->maxs[0]+NPC->enemy->maxs[0]+16) ) - {//close enough + } else if (NPC->client->ps.weapon == WP_MELEE && + enemyDist < (NPC->maxs[0] + NPC->enemy->maxs[0] + 16) * (NPC->maxs[0] + NPC->enemy->maxs[0] + 16)) { // close enough AImove = qfalse; } - }//this should make him chase enemy when out of range...? + } // this should make him chase enemy when out of range...? - //Check for movement to take care of + // Check for movement to take care of Grenadier_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Grenadier_CheckFireState(); - if ( AImove ) - {//move toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (AImove) { // move toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { AImove = Grenadier_Move(); - } - else - { + } else { AImove = qfalse; } } - if ( !AImove ) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!AImove) { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); } - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( AImove ) - {//don't run away and shoot + if (!faceEnemy) { // we want to face in the dir we're running + if (AImove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy ) + { // face the enemy NPC_FaceEnemy(); } - if ( NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); - TIMER_Set( NPC, "attackDelay", NPCInfo->shotTime-level.time ); + WeaponThink(qtrue); + TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime - level.time); } - } } } -void NPC_BSGrenadier_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSGrenadier_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSGrenadier_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSGrenadier_Attack(); } } diff --git a/codeJK2/game/AI_Howler.cpp b/codeJK2/game/AI_Howler.cpp index 3930b0d8b4..f970553e46 100644 --- a/codeJK2/game/AI_Howler.cpp +++ b/codeJK2/game/AI_Howler.cpp @@ -20,172 +20,144 @@ along with this program; if not, see . =========================================================================== */ #include "g_headers.h" - + #include "b_local.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 /* ------------------------- NPC_Howler_Precache ------------------------- */ -void NPC_Howler_Precache( void ) -{ -} - +void NPC_Howler_Precache(void) {} /* ------------------------- Howler_Idle ------------------------- */ -void Howler_Idle( void ) -{ -} - +void Howler_Idle(void) {} /* ------------------------- Howler_Patrol ------------------------- */ -void Howler_Patrol( void ) -{ +void Howler_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPC, "patrolTime" )) - { - TIMER_Set( NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPC, "patrolTime")) { + TIMER_Set(NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } vec3_t dif; - VectorSubtract( g_entities[0].currentOrigin, NPC->currentOrigin, dif ); + VectorSubtract(g_entities[0].currentOrigin, NPC->currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Howler_Idle(); return; } } - + /* ------------------------- Howler_Move ------------------------- */ -void Howler_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +void Howler_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - NPC_MoveToGoal( qtrue ); - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -void Howler_TryDamage( gentity_t *enemy, int damage ) -{ - vec3_t end, dir; - trace_t tr; +void Howler_TryDamage(gentity_t *enemy, int damage) { + vec3_t end, dir; + trace_t tr; - if ( !enemy ) - { + if (!enemy) { return; } - AngleVectors( NPC->client->ps.viewangles, dir, NULL, NULL ); - VectorMA( NPC->currentOrigin, MIN_DISTANCE, dir, end ); + AngleVectors(NPC->client->ps.viewangles, dir, NULL, NULL); + VectorMA(NPC->currentOrigin, MIN_DISTANCE, dir, end); // Should probably trace from the mouth, but, ah well. - gi.trace( &tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( tr.entityNum != ENTITYNUM_WORLD ) - { - G_Damage( &g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (tr.entityNum != ENTITYNUM_WORLD) { + G_Damage(&g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); } } //------------------------------ -void Howler_Attack( void ) -{ - if ( !TIMER_Exists( NPC, "attacking" )) - { +void Howler_Attack(void) { + if (!TIMER_Exists(NPC, "attacking")) { // Going to do ATTACK1 - TIMER_Set( NPC, "attacking", 1700 + Q_flrand(0.0f, 1.0f) * 200 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 1700 + Q_flrand(0.0f, 1.0f) * 200); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack_dmg", 200 ); // level two damage + TIMER_Set(NPC, "attack_dmg", 200); // level two damage } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPC, "attack_dmg", qtrue )) - { - Howler_TryDamage( NPC->enemy, 5 ); + if (TIMER_Done2(NPC, "attack_dmg", qtrue)) { + Howler_TryDamage(NPC->enemy, 5); } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); } //---------------------------------- -void Howler_Combat( void ) -{ +void Howler_Combat(void) { // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS(NPC->enemy) || UpdateGoal()) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - qboolean advance = (qboolean)( distance > MIN_DISTANCE_SQR ? qtrue : qfalse ); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR ? qtrue : qfalse); - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else { + Howler_Move(qtrue); } - else - { - Howler_Move( qtrue ); - } - } - else - { + } else { Howler_Attack(); } } @@ -195,44 +167,34 @@ void Howler_Combat( void ) NPC_Howler_Pain ------------------------- */ -void NPC_Howler_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( damage >= 10 ) - { - TIMER_Remove( self, "attacking" ); - TIMER_Set( self, "takingPain", 2900 ); +void NPC_Howler_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + if (damage >= 10) { + TIMER_Remove(self, "attacking"); + TIMER_Set(self, "takingPain", 2900); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } - /* ------------------------- NPC_BSHowler_Default ------------------------- */ -void NPC_BSHowler_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSHowler_Default(void) { + if (NPC->enemy) { Howler_Combat(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Howler_Patrol(); - } - else - { + } else { Howler_Idle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codeJK2/game/AI_ImperialProbe.cpp b/codeJK2/game/AI_ImperialProbe.cpp index a7fb3aeb2d..2f35f7a7bc 100644 --- a/codeJK2/game/AI_ImperialProbe.cpp +++ b/codeJK2/game/AI_ImperialProbe.cpp @@ -24,39 +24,30 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; - -void ImperialProbe_Idle( void ); - -void NPC_Probe_Precache(void) -{ - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/probe/misc/probetalk%d", i ) ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +extern gitem_t *FindItemForAmmo(ammo_t ammo); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; + +void ImperialProbe_Idle(void); + +void NPC_Probe_Precache(void) { + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/probe/misc/probetalk%d", i)); } - G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + G_SoundIndex("sound/chars/probe/misc/probedroidloop"); G_SoundIndex("sound/chars/probe/misc/anger1"); G_SoundIndex("sound/chars/probe/misc/fire"); - G_EffectIndex( "probehead" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "probeexplosion1"); - G_EffectIndex( "bryar/muzzle_flash" ); + G_EffectIndex("probehead"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("probeexplosion1"); + G_EffectIndex("bryar/muzzle_flash"); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL ) ); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); } /* ------------------------- @@ -64,126 +55,106 @@ Hunter_MaintainHeight ------------------------- */ -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f -void ImperialProbe_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void ImperialProbe_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference - dif = NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2]; + dif = NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > 16 ) - { - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 8) { + if (fabs(dif) > 16) { + dif = (dif < 0 ? -16 : 16); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } // Stay at a given height until we take on an enemy -/* VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 512 ); - gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); - - if ( trace.fraction != 1.0f ) - { - float length = ( trace.fraction * 512 ); + /* VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 512 ); + gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); - if ( length < 80 ) - { - ucmd.upmove = 32; - } - else if ( length > 120 ) - { - ucmd.upmove = -32; - } - else - { - if ( NPC->client->ps.velocity[2] ) + if ( trace.fraction != 1.0f ) { - NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + float length = ( trace.fraction * 512 ); - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + if ( length < 80 ) { - NPC->client->ps.velocity[2] = 0; + ucmd.upmove = 32; } - } - } - } */ + else if ( length > 120 ) + { + ucmd.upmove = -32; + } + else + { + if ( NPC->client->ps.velocity[2] ) + { + NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + + if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + { + NPC->client->ps.velocity[2] = 0; + } + } + } + } */ } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } @@ -195,29 +166,27 @@ ImperialProbe_Strafe ------------------------- */ -#define HUNTER_STRAFE_VEL 256 -#define HUNTER_STRAFE_DIS 200 -#define HUNTER_UPWARD_PUSH 32 +#define HUNTER_STRAFE_VEL 256 +#define HUNTER_STRAFE_DIS 200 +#define HUNTER_UPWARD_PUSH 32 -void ImperialProbe_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void ImperialProbe_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push NPC->client->ps.velocity[2] += HUNTER_UPWARD_PUSH; @@ -234,50 +203,44 @@ ImperialProbe_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 5 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 5 -void ImperialProbe_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void ImperialProbe_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { ImperialProbe_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } /* @@ -285,58 +248,47 @@ void ImperialProbe_Hunt( qboolean visible, qboolean advance ) ImperialProbe_FireBlaster ------------------------- */ -void ImperialProbe_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - - //FIXME: use {0, NPC->client->ps.legsYaw, 0} - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt1, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - - G_PlayEffect( "bryar/muzzle_flash", muzzle1 ); - - G_Sound( NPC, G_SoundIndex( "sound/chars/probe/misc/fire" )); - - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_CHEST, enemy_org1 ); - enemy_org1[0]+= Q_irand(0,10); - enemy_org1[1]+= Q_irand(0,10); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); +void ImperialProbe_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + + // FIXME: use {0, NPC->client->ps.legsYaw, 0} + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt1, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); + + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + + G_PlayEffect("bryar/muzzle_flash", muzzle1); + + G_Sound(NPC, G_SoundIndex("sound/chars/probe/misc/fire")); + + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_CHEST, enemy_org1); + enemy_org1[0] += Q_irand(0, 10); + enemy_org1[1] += Q_irand(0, 10); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; - if ( g_spskill->integer <= 1 ) - { + if (g_spskill->integer <= 1) { missile->damage = 5; - } - else - { + } else { missile->damage = 10; } - missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -344,37 +296,30 @@ void ImperialProbe_FireBlaster(void) ImperialProbe_Ranged ------------------------- */ -void ImperialProbe_Ranged( qboolean visible, qboolean advance ) -{ - int delay_min,delay_max; +void ImperialProbe_Ranged(qboolean visible, qboolean advance) { + int delay_min, delay_max; - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { delay_min = 500; delay_max = 3000; - } - else if ( g_spskill->integer > 1 ) - { + } else if (g_spskill->integer > 1) { delay_min = 500; delay_max = 2000; - } - else - { + } else { delay_min = 300; delay_max = 1500; } - TIMER_Set( NPC, "attackDelay", Q_irand( delay_min, delay_max ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(delay_min, delay_max)); ImperialProbe_FireBlaster(); -// ucmd.buttons |= BUTTON_ATTACK; + // ucmd.buttons |= BUTTON_ATTACK; } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); } } @@ -384,58 +329,52 @@ ImperialProbe_AttackDecision ------------------------- */ -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -void ImperialProbe_AttackDecision( void ) -{ +void ImperialProbe_AttackDecision(void) { // Always keep a good height off the ground ImperialProbe_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { ImperialProbe_Idle(); return; } - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); -// distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + // distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); return; } } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Decide what type of attack to do - ImperialProbe_Ranged( visible, advance ); + ImperialProbe_Ranged(visible, advance); } /* @@ -443,66 +382,61 @@ void ImperialProbe_AttackDecision( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Probe_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - float pain_chance; - - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); +void NPC_Probe_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + float pain_chance; + + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) // demp2 always messes them up real good + if (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) // demp2 always messes them up real good { vec3_t endPos; - trace_t trace; + trace_t trace; - VectorSet( endPos, self->currentOrigin[0], self->currentOrigin[1], self->currentOrigin[2] - 128 ); - gi.trace( &trace, self->currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + VectorSet(endPos, self->currentOrigin[0], self->currentOrigin[1], self->currentOrigin[2] - 128); + gi.trace(&trace, self->currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); - if ( trace.fraction == 1.0f || mod == MOD_DEMP2 ) // demp2 always does this + if (trace.fraction == 1.0f || mod == MOD_DEMP2) // demp2 always does this { - if (self->client->clientInfo.headModel != 0) - { + if (self->client->clientInfo.headModel != 0) { vec3_t origin; - VectorCopy(self->currentOrigin,origin); - origin[2] +=50; -// G_PlayEffect( "small_chunks", origin ); - G_PlayEffect( "probehead", origin ); - G_PlayEffect( "env/med_explode2", origin ); + VectorCopy(self->currentOrigin, origin); + origin[2] += 50; + // G_PlayEffect( "small_chunks", origin ); + G_PlayEffect("probehead", origin); + G_PlayEffect("env/med_explode2", origin); self->client->clientInfo.headModel = 0; self->NPC->stats.moveType = MT_RUNJUMP; - self->client->ps.gravity = g_gravity->value*.1; + self->client->ps.gravity = g_gravity->value * .1; } - - if ( (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other ) - { + + if ((mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - VectorSubtract( self->currentOrigin, other->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->currentOrigin, other->currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - self->s.powerups |= ( 1 << PW_SHOCKED ); + self->s.powerups |= (1 << PW_SHOCKED); self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->NPC->localState = LSTATE_DROP; - } - } - else - { - pain_chance = NPC_GetPainChance( self, damage ); + } + } else { + pain_chance = NPC_GetPainChance(self, damage); - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? + if (Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); - } + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); + } } - NPC_Pain( self, inflictor, other, point, damage, mod); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -511,8 +445,7 @@ ImperialProbe_Idle ------------------------- */ -void ImperialProbe_Idle( void ) -{ +void ImperialProbe_Idle(void) { ImperialProbe_MaintainHeight(); NPC_BSIdle(); @@ -523,44 +456,38 @@ void ImperialProbe_Idle( void ) NPC_BSImperialProbe_Patrol ------------------------- */ -void ImperialProbe_Patrol( void ) -{ +void ImperialProbe_Patrol(void) { ImperialProbe_MaintainHeight(); - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL ); + // If we have somewhere to go, then do that + if (!NPC->enemy) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); - if ( UpdateGoal() ) - { - //start loop sound once we move - NPC->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + if (UpdateGoal()) { + // start loop sound once we move + NPC->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else // He's got an enemy. Make him angry. + } else // He's got an enemy. Make him angry. { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1" ); - TIMER_Set( NPC, "angerNoise", Q_irand( 2000, 4000 ) ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL; + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1"); + TIMER_Set(NPC, "angerNoise", Q_irand(2000, 4000)); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -568,25 +495,22 @@ void ImperialProbe_Patrol( void ) ImperialProbe_Wait ------------------------- */ -void ImperialProbe_Wait(void) -{ - if ( NPCInfo->localState == LSTATE_DROP ) - { +void ImperialProbe_Wait(void) { + if (NPCInfo->localState == LSTATE_DROP) { vec3_t endPos; - trace_t trace; + trace_t trace; - NPCInfo->desiredYaw = AngleNormalize360( NPCInfo->desiredYaw + 25 ); + NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->desiredYaw + 25); - VectorSet( endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 32 ); - gi.trace( &trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + VectorSet(endPos, NPC->currentOrigin[0], NPC->currentOrigin[1], NPC->currentOrigin[2] - 32); + gi.trace(&trace, NPC->currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); - if ( trace.fraction != 1.0f ) - { - G_Damage(NPC, NPC->enemy, NPC->enemy, NULL, NULL, 2000, 0,MOD_UNKNOWN); - } + if (trace.fraction != 1.0f) { + G_Damage(NPC, NPC->enemy, NPC->enemy, NULL, NULL, 2000, 0, MOD_UNKNOWN); + } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -594,24 +518,16 @@ void ImperialProbe_Wait(void) NPC_BSImperialProbe_Default ------------------------- */ -void NPC_BSImperialProbe_Default( void ) -{ +void NPC_BSImperialProbe_Default(void) { - if ( NPC->enemy ) - { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; ImperialProbe_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ImperialProbe_Patrol(); - } - else if ( NPCInfo->localState == LSTATE_DROP ) - { + } else if (NPCInfo->localState == LSTATE_DROP) { ImperialProbe_Wait(); - } - else - { + } else { ImperialProbe_Idle(); } } diff --git a/codeJK2/game/AI_Interrogator.cpp b/codeJK2/game/AI_Interrogator.cpp index c81111f08a..4bba5d8c47 100644 --- a/codeJK2/game/AI_Interrogator.cpp +++ b/codeJK2/game/AI_Interrogator.cpp @@ -24,15 +24,14 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -void Interrogator_Idle( void ); -void DeathFX( gentity_t *ent ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -enum -{ -LSTATE_BLADESTOP=0, -LSTATE_BLADEUP, -LSTATE_BLADEDOWN, +void Interrogator_Idle(void); +void DeathFX(gentity_t *ent); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +enum { + LSTATE_BLADESTOP = 0, + LSTATE_BLADEUP, + LSTATE_BLADEDOWN, }; /* @@ -40,22 +39,20 @@ LSTATE_BLADEDOWN, NPC_Interrogator_Precache ------------------------- */ -void NPC_Interrogator_Precache(gentity_t *self) -{ - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); +void NPC_Interrogator_Precache(gentity_t *self) { + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); G_SoundIndex("sound/chars/mark1/misc/anger.wav"); - G_SoundIndex( "sound/chars/probe/misc/talk"); - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject" ); - G_SoundIndex( "sound/chars/interrogator/misc/int_droid_explo" ); - G_EffectIndex( "droidexplosion1" ); + G_SoundIndex("sound/chars/probe/misc/talk"); + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject"); + G_SoundIndex("sound/chars/interrogator/misc/int_droid_explo"); + G_EffectIndex("droidexplosion1"); } /* ------------------------- Interrogator_die ------------------------- */ -void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Interrogator_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { self->client->ps.velocity[2] = -100; /* self->locationDamage[HL_NONE] += damage; @@ -69,13 +66,13 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke */ { self->NPC->stats.moveType = MT_WALK; - self->client->ps.velocity[0] = Q_irand( -20, -10 ); - self->client->ps.velocity[1] = Q_irand( -20, -10 ); + self->client->ps.velocity[0] = Q_irand(-20, -10); + self->client->ps.velocity[1] = Q_irand(-20, -10); self->client->ps.velocity[2] = -100; } - //self->takedamage = qfalse; - //self->client->ps.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->takedamage = qfalse; + // self->client->ps.eFlags |= EF_NODRAW; + // self->contents = 0; return; } @@ -84,212 +81,178 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke Interrogator_PartsMove ------------------------- */ -void Interrogator_PartsMove(void) -{ +void Interrogator_PartsMove(void) { // Syringe - if ( TIMER_Done(NPC,"syringeDelay") ) - { - NPC->pos1[1] = AngleNormalize360( NPC->pos1[1]); - - if ((NPC->pos1[1] < 60) || (NPC->pos1[1] > 300)) - { - NPC->pos1[1]+=Q_irand( -20, 20 ); // Pitch - } - else if (NPC->pos1[1] > 180) - { - NPC->pos1[1]=Q_irand( 300, 360 ); // Pitch - } - else - { - NPC->pos1[1]=Q_irand( 0, 60 ); // Pitch + if (TIMER_Done(NPC, "syringeDelay")) { + NPC->pos1[1] = AngleNormalize360(NPC->pos1[1]); + + if ((NPC->pos1[1] < 60) || (NPC->pos1[1] > 300)) { + NPC->pos1[1] += Q_irand(-20, 20); // Pitch + } else if (NPC->pos1[1] > 180) { + NPC->pos1[1] = Q_irand(300, 360); // Pitch + } else { + NPC->pos1[1] = Q_irand(0, 60); // Pitch } - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - TIMER_Set( NPC, "syringeDelay", Q_irand( 100, 1000 ) ); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); + TIMER_Set(NPC, "syringeDelay", Q_irand(100, 1000)); } // Scalpel - if ( TIMER_Done(NPC,"scalpelDelay") ) - { + if (TIMER_Done(NPC, "scalpelDelay")) { // Change pitch - if ( NPCInfo->localState == LSTATE_BLADEDOWN ) // Blade is moving down + if (NPCInfo->localState == LSTATE_BLADEDOWN) // Blade is moving down { - NPC->pos2[0]-= 30; - if (NPC->pos2[0] < 180) - { + NPC->pos2[0] -= 30; + if (NPC->pos2[0] < 180) { NPC->pos2[0] = 180; - NPCInfo->localState = LSTATE_BLADEUP; // Make it move up + NPCInfo->localState = LSTATE_BLADEUP; // Make it move up } - } - else // Blade is coming back up + } else // Blade is coming back up { - NPC->pos2[0]+= 30; - if (NPC->pos2[0] >= 360) - { + NPC->pos2[0] += 30; + if (NPC->pos2[0] >= 360) { NPC->pos2[0] = 360; - NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down - TIMER_Set( NPC, "scalpelDelay", Q_irand( 100, 1000 ) ); + NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down + TIMER_Set(NPC, "scalpelDelay", Q_irand(100, 1000)); } } - NPC->pos2[0] = AngleNormalize360( NPC->pos2[0]); - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + NPC->pos2[0] = AngleNormalize360(NPC->pos2[0]); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } // Claw - NPC->pos3[1] += Q_irand( 10, 30 ); - NPC->pos3[1] = AngleNormalize360( NPC->pos3[1]); - gi.G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); - + NPC->pos3[1] += Q_irand(10, 30); + NPC->pos3[1] = AngleNormalize360(NPC->pos3[1]); + gi.G2API_SetBoneAnglesIndex(&NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, + 0); } -#define VELOCITY_DECAY 0.85f -#define HUNTER_UPWARD_PUSH 2 +#define VELOCITY_DECAY 0.85f +#define HUNTER_UPWARD_PUSH 2 /* ------------------------- Interrogator_MaintainHeight ------------------------- */ -void Interrogator_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void Interrogator_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; - NPC->s.loopSound = G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 16 ) - { - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 16) { + dif = (dif < 0 ? -16 : 16); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } -#define HUNTER_STRAFE_VEL 32 -#define HUNTER_STRAFE_DIS 200 +#define HUNTER_STRAFE_VEL 32 +#define HUNTER_STRAFE_DIS 200 /* ------------------------- Interrogator_Strafe ------------------------- */ -void Interrogator_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; - float dif; +void Interrogator_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; + float dif; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + 32) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + 32) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - dif = ( dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH ); + if (fabs(dif) > 8) { + dif = (dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH); } NPC->client->ps.velocity[2] += dif; - } - // Set the strafe start time + // Set the strafe start time NPC->fx_time = level.time; NPCInfo->standTime = level.time + 3000 + Q_flrand(0.0f, 1.0f) * 500; } @@ -301,88 +264,79 @@ Interrogator_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 2 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 2 -void Interrogator_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Interrogator_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; Interrogator_PartsMove(); NPC_FaceEnemy(qfalse); - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Interrogator_Strafe(); - if ( NPCInfo->standTime > level.time ) - {//successfully strafed + if (NPCInfo->standTime > level.time) { // successfully strafed return; } } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - distance = VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + distance = VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } -#define MIN_DISTANCE 64 +#define MIN_DISTANCE 64 /* ------------------------- Interrogator_Melee ------------------------- */ -void Interrogator_Melee( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Interrogator_Melee(qboolean visible, qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { // Make sure that we are within the height range before we allow any damage to happen - if ( NPC->currentOrigin[2] >= NPC->enemy->currentOrigin[2]+NPC->enemy->mins[2] && NPC->currentOrigin[2]+NPC->mins[2]+8 < NPC->enemy->currentOrigin[2]+NPC->enemy->maxs[2] ) - { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 3000 ) ); - G_Damage( NPC->enemy, NPC, NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (NPC->currentOrigin[2] >= NPC->enemy->currentOrigin[2] + NPC->enemy->mins[2] && + NPC->currentOrigin[2] + NPC->mins[2] + 8 < NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) { + TIMER_Set(NPC, "attackDelay", Q_irand(500, 3000)); + G_Damage(NPC->enemy, NPC, NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE); NPC->enemy->client->poisonDamage = 18; NPC->enemy->client->poisonTime = level.time + 1000; // Drug our enemy up and do the wonky vision thing - gentity_t *tent = G_TempEntity( NPC->enemy->currentOrigin, EV_DRUGGED ); + gentity_t *tent = G_TempEntity(NPC->enemy->currentOrigin, EV_DRUGGED); tent->owner = NPC->enemy; - G_Sound( NPC, G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject.mp3" )); + G_Sound(NPC, G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject.mp3")); } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } } @@ -391,48 +345,41 @@ void Interrogator_Melee( qboolean visible, qboolean advance ) Interrogator_Attack ------------------------- */ -void Interrogator_Attack( void ) -{ +void Interrogator_Attack(void) { // Always keep a good height off the ground Interrogator_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Interrogator_Idle(); return; } // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE*MIN_DISTANCE ); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE * MIN_DISTANCE); - if ( !visible ) - { + if (!visible) { advance = qtrue; } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (!advance) - { - Interrogator_Melee( visible, advance ); + if (!advance) { + Interrogator_Melee(visible, advance); } } @@ -441,12 +388,10 @@ void Interrogator_Attack( void ) Interrogator_Idle ------------------------- */ -void Interrogator_Idle( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav" ); - NPC_UpdateAngles( qtrue, qtrue ); +void Interrogator_Idle(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav"); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -460,17 +405,12 @@ void Interrogator_Idle( void ) NPC_BSInterrogator_Default ------------------------- */ -void NPC_BSInterrogator_Default( void ) -{ - //NPC->e_DieFunc = dieF_Interrogator_die; +void NPC_BSInterrogator_Default(void) { + // NPC->e_DieFunc = dieF_Interrogator_die; - if ( NPC->enemy ) - { + if (NPC->enemy) { Interrogator_Attack(); - } - else - { + } else { Interrogator_Idle(); } - } diff --git a/codeJK2/game/AI_Jedi.cpp b/codeJK2/game/AI_Jedi.cpp index e2a375a23e..dbd1c66e77 100644 --- a/codeJK2/game/AI_Jedi.cpp +++ b/codeJK2/game/AI_Jedi.cpp @@ -27,196 +27,165 @@ along with this program; if not, see . #include "wp_saber.h" #include "../../code/qcommon/tri_coll_test.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_StartMatrixEffect( gentity_t *ent, qboolean falling = qfalse, int length = 1000 ); -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *d_slowmodeath; - -#define MAX_VIEW_DIST 2048 -#define MAX_VIEW_SPEED 100 -#define JEDI_MAX_LIGHT_INTENSITY 64 -#define JEDI_MIN_LIGHT_THRESHOLD 10 -#define JEDI_MAX_LIGHT_THRESHOLD 50 - -#define DISTANCE_SCALE 0.25f +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_StartMatrixEffect(gentity_t *ent, qboolean falling = qfalse, int length = 1000); +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *d_slowmodeath; + +#define MAX_VIEW_DIST 2048 +#define MAX_VIEW_SPEED 100 +#define JEDI_MAX_LIGHT_INTENSITY 64 +#define JEDI_MIN_LIGHT_THRESHOLD 10 +#define JEDI_MAX_LIGHT_THRESHOLD 50 + +#define DISTANCE_SCALE 0.25f //#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.3 ) - -#define MAX_CHECK_THRESHOLD 1 - -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean NPC_CheckEnemyStealth( void ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); -extern void ForceThrow( gentity_t *self, qboolean pull ); -extern void ForceLightning( gentity_t *self ); -extern int WP_MissileBlockForBlock( int saberBlock ); -extern qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ); -extern qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); -extern void WP_KnockdownTurret( gentity_t *self, gentity_t *pas ); -//extern void WP_SaberBlock(gentity_t *saber, vec3_t hitloc); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SaberInDeflect( int move ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); - -static void Jedi_Aggression( gentity_t *self, int change ); -qboolean Jedi_WaitingAmbush( gentity_t *self ); +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.3) + +#define MAX_CHECK_THRESHOLD 1 + +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean NPC_CheckEnemyStealth(void); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern gitem_t *FindItemForAmmo(ammo_t ammo); +extern void ForceThrow(gentity_t *self, qboolean pull); +extern void ForceLightning(gentity_t *self); +extern int WP_MissileBlockForBlock(int saberBlock); +extern qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod); +extern qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); +extern void WP_KnockdownTurret(gentity_t *self, gentity_t *pas); +// extern void WP_SaberBlock(gentity_t *saber, vec3_t hitloc); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SaberInDeflect(int move); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); + +static void Jedi_Aggression(gentity_t *self, int change); +qboolean Jedi_WaitingAmbush(gentity_t *self); extern int parryDebounce[]; -static int jediSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several jedi from speaking all at once -//Local state enums -enum -{ +static int jediSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several jedi from speaking all at once +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void NPC_ShadowTrooper_Precache( void ) -{ - RegisterItem( FindItemForAmmo( AMMO_FORCE ) ); - G_SoundIndex( "sound/chars/shadowtrooper/cloak.wav" ); - G_SoundIndex( "sound/chars/shadowtrooper/decloak.wav" ); +void NPC_ShadowTrooper_Precache(void) { + RegisterItem(FindItemForAmmo(AMMO_FORCE)); + G_SoundIndex("sound/chars/shadowtrooper/cloak.wav"); + G_SoundIndex("sound/chars/shadowtrooper/decloak.wav"); } -void Jedi_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "strafeLeft", 0 ); - TIMER_Set( ent, "strafeRight", 0 ); - TIMER_Set( ent, "noStrafe", 0 ); - TIMER_Set( ent, "walking", 0 ); - TIMER_Set( ent, "taunting", 0 ); - TIMER_Set( ent, "parryTime", 0 ); - TIMER_Set( ent, "parryReCalcTime", 0 ); - TIMER_Set( ent, "forceJumpChasing", 0 ); - TIMER_Set( ent, "jumpChaseDebounce", 0 ); - TIMER_Set( ent, "moveforward", 0 ); - TIMER_Set( ent, "moveback", 0 ); - TIMER_Set( ent, "movenone", 0 ); - TIMER_Set( ent, "moveright", 0 ); - TIMER_Set( ent, "moveleft", 0 ); - TIMER_Set( ent, "movecenter", 0 ); - TIMER_Set( ent, "saberLevelDebounce", 0 ); - TIMER_Set( ent, "noRetreat", 0 ); - TIMER_Set( ent, "holdLightning", 0 ); - TIMER_Set( ent, "noturn", 0 ); +void Jedi_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "strafeLeft", 0); + TIMER_Set(ent, "strafeRight", 0); + TIMER_Set(ent, "noStrafe", 0); + TIMER_Set(ent, "walking", 0); + TIMER_Set(ent, "taunting", 0); + TIMER_Set(ent, "parryTime", 0); + TIMER_Set(ent, "parryReCalcTime", 0); + TIMER_Set(ent, "forceJumpChasing", 0); + TIMER_Set(ent, "jumpChaseDebounce", 0); + TIMER_Set(ent, "moveforward", 0); + TIMER_Set(ent, "moveback", 0); + TIMER_Set(ent, "movenone", 0); + TIMER_Set(ent, "moveright", 0); + TIMER_Set(ent, "moveleft", 0); + TIMER_Set(ent, "movecenter", 0); + TIMER_Set(ent, "saberLevelDebounce", 0); + TIMER_Set(ent, "noRetreat", 0); + TIMER_Set(ent, "holdLightning", 0); + TIMER_Set(ent, "noturn", 0); } -void Jedi_PlayBlockedPushSound( gentity_t *self ) -{ - if ( !self->s.number ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); +void Jedi_PlayBlockedPushSound(gentity_t *self) { + if (!self->s.number) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void Jedi_PlayDeflectSound( gentity_t *self ) -{ - if ( !self->s.number ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); +void Jedi_PlayDeflectSound(gentity_t *self) { + if (!self->s.number) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void NPC_Jedi_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->client && ( self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_DESANN ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE1, EV_CONFUSE3 ), 2000 ); - } - else if ( Q_irand( 0, 1 ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 2000 ); - } - else - { - G_AddVoiceEvent( self, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 2000 ); +void NPC_Jedi_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->client && (self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_DESANN)) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); + } else if (Q_irand(0, 1)) { + G_AddVoiceEvent(self, Q_irand(EV_TAUNT1, EV_TAUNT3), 2000); + } else { + G_AddVoiceEvent(self, Q_irand(EV_GLOAT1, EV_GLOAT3), 2000); } } } -void Jedi_Cloak( gentity_t *self ) -{ - if ( self && self->client ) - { - if ( !self->client->ps.powerups[PW_CLOAKED] ) - {//cloak +void Jedi_Cloak(gentity_t *self) { + if (self && self->client) { + if (!self->client->ps.powerups[PW_CLOAKED]) { // cloak self->client->ps.powerups[PW_CLOAKED] = Q3_INFINITE; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: debounce attacks? - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav" ); + // FIXME: debounce attacks? + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/cloak.wav"); } } } -void Jedi_Decloak( gentity_t *self ) -{ - if ( self && self->client ) - { - if ( self->client->ps.powerups[PW_CLOAKED] ) - {//Uncloak +void Jedi_Decloak(gentity_t *self) { + if (self && self->client) { + if (self->client->ps.powerups[PW_CLOAKED]) { // Uncloak self->client->ps.powerups[PW_CLOAKED] = 0; self->client->ps.powerups[PW_UNCLOAKING] = level.time + 2000; - //FIXME: temp sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav" ); + // FIXME: temp sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/chars/shadowtrooper/decloak.wav"); } } } -void Jedi_CheckCloak( void ) -{ - if ( NPC && NPC->client && NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - { - if ( NPC->client->ps.saberActive || - NPC->health <= 0 || - NPC->client->ps.saberInFlight || - (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) || - NPC->painDebounceTime > level.time ) - {//can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped - Jedi_Decloak( NPC ); - } - else if ( NPC->health > 0 && !NPC->client->ps.saberInFlight && !(NPC->client->ps.eFlags&EF_FORCE_GRIPPED) && NPC->painDebounceTime < level.time ) - {//still alive, have saber in hand, not taking pain and not being gripped - Jedi_Cloak( NPC ); +void Jedi_CheckCloak(void) { + if (NPC && NPC->client && NPC->client->NPC_class == CLASS_SHADOWTROOPER) { + if (NPC->client->ps.saberActive || NPC->health <= 0 || NPC->client->ps.saberInFlight || (NPC->client->ps.eFlags & EF_FORCE_GRIPPED) || + NPC->painDebounceTime > level.time) { // can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped + Jedi_Decloak(NPC); + } else if (NPC->health > 0 && !NPC->client->ps.saberInFlight && !(NPC->client->ps.eFlags & EF_FORCE_GRIPPED) && + NPC->painDebounceTime < level.time) { // still alive, have saber in hand, not taking pain and not being gripped + Jedi_Cloak(NPC); } } } @@ -225,103 +194,82 @@ void Jedi_CheckCloak( void ) AGGRESSION ========================================================================================== */ -static void Jedi_Aggression( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +static void Jedi_Aggression(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == TEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == TEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive - if ( self->client->NPC_class == CLASS_DESANN ) - { + } else { // bad guys are more aggressive + if (self->client->NPC_class == CLASS_DESANN) { upper_threshold = 20; lower_threshold = 5; - } - else - { + } else { upper_threshold = 10; lower_threshold = 3; } } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } - //Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); + // Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); } -static void Jedi_AggressionErosion( int amt ) -{ - if ( TIMER_Done( NPC, "roamTime" ) ) - {//the longer we're not alerted and have no enemy, the more our aggression goes down - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - Jedi_Aggression( NPC, amt ); +static void Jedi_AggressionErosion(int amt) { + if (TIMER_Done(NPC, "roamTime")) { // the longer we're not alerted and have no enemy, the more our aggression goes down + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + Jedi_Aggression(NPC, amt); } - if ( NPCInfo->stats.aggression < 4 || (NPCInfo->stats.aggression < 6&&NPC->client->NPC_class == CLASS_DESANN)) - {//turn off the saber - if ( NPC->client->ps.saberActive ) - { + if (NPCInfo->stats.aggression < 4 || (NPCInfo->stats.aggression < 6 && NPC->client->NPC_class == CLASS_DESANN)) { // turn off the saber + if (NPC->client->ps.saberActive) { NPC->client->ps.saberActive = qfalse; - if ( NPC->client->playerTeam == TEAM_PLAYER ) - { - G_SoundOnEnt( NPC, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav" ); - } - else - { - G_SoundOnEnt( NPC, CHAN_WEAPON, "sound/weapons/saber/enemy_saber_off.wav" ); + if (NPC->client->playerTeam == TEAM_PLAYER) { + G_SoundOnEnt(NPC, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav"); + } else { + G_SoundOnEnt(NPC, CHAN_WEAPON, "sound/weapons/saber/enemy_saber_off.wav"); } } } } -void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ) -{ +void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy) { float healthAggression; float weaponAggression; - switch( enemy->s.weapon ) - { + switch (enemy->s.weapon) { case WP_SABER: - healthAggression = (float)self->health/200.0f*6.0f; - weaponAggression = 7;//go after him + healthAggression = (float)self->health / 200.0f * 6.0f; + weaponAggression = 7; // go after him break; case WP_BLASTER: - if ( DistanceSquared( self->currentOrigin, enemy->currentOrigin ) < 65536 )//256 squared + if (DistanceSquared(self->currentOrigin, enemy->currentOrigin) < 65536) // 256 squared { - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 8;//go after him - } - else - { - healthAggression = 8.0f - ((float)self->health/200.0f*8.0f); - weaponAggression = 2;//hang back for a second + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 8; // go after him + } else { + healthAggression = 8.0f - ((float)self->health / 200.0f * 8.0f); + weaponAggression = 2; // hang back for a second } break; default: - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 6;//approach + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 6; // approach break; } - //Average these with current aggression - int newAggression = ceil( (healthAggression + weaponAggression + (float)self->NPC->stats.aggression )/3.0f); - //Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); - Jedi_Aggression( self, newAggression - self->NPC->stats.aggression ); + // Average these with current aggression + int newAggression = ceil((healthAggression + weaponAggression + (float)self->NPC->stats.aggression) / 3.0f); + // Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); + Jedi_Aggression(self, newAggression - self->NPC->stats.aggression); - //don't taunt right away - TIMER_Set( self, "chatter", Q_irand( 4000, 7000 ) ); + // don't taunt right away + TIMER_Set(self, "chatter", Q_irand(4000, 7000)); } /* @@ -330,34 +278,25 @@ SPEAKING ========================================================================================== */ -static qboolean Jedi_BattleTaunt( void ) -{ - if ( TIMER_Done( NPC, "chatter" ) - && !Q_irand( 0, 3 ) - && NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) - { +static qboolean Jedi_BattleTaunt(void) { + if (TIMER_Done(NPC, "chatter") && !Q_irand(0, 3) && NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPC->client->playerTeam] < level.time) { int event = -1; - if ( NPC->client->playerTeam == TEAM_PLAYER - && NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//a jedi fighting a jedi - training - if ( NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) - {//only trainer taunts + if (NPC->client->playerTeam == TEAM_PLAYER && NPC->enemy && NPC->enemy->client && + NPC->enemy->client->NPC_class == CLASS_JEDI) { // a jedi fighting a jedi - training + if (NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER) { // only trainer taunts event = EV_TAUNT1; } + } else { // reborn or a jedi fighting an enemy + event = Q_irand(EV_TAUNT1, EV_TAUNT3); } - else - {//reborn or a jedi fighting an enemy - event = Q_irand( EV_TAUNT1, EV_TAUNT3 ); - } - if ( event != -1 ) - { - G_AddVoiceEvent( NPC, event, 3000 ); + if (event != -1) { + G_AddVoiceEvent(NPC, event, 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 6000; - TIMER_Set( NPC, "chatter", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPC, "chatter", Q_irand(5000, 10000)); - if ( NPC->enemy && NPC->enemy->NPC && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//Have the enemy jedi say something in response when I'm done? + if (NPC->enemy && NPC->enemy->NPC && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && + NPC->enemy->client->NPC_class == CLASS_JEDI) { // Have the enemy jedi say something in response when I'm done? } return qtrue; } @@ -370,86 +309,72 @@ static qboolean Jedi_BattleTaunt( void ) MOVEMENT ========================================================================================== */ -static qboolean Jedi_ClearPathToSpot( vec3_t dest, int impactEntNum ) -{ - trace_t trace; - vec3_t mins, start, end, dir; - float dist, drop; +static qboolean Jedi_ClearPathToSpot(vec3_t dest, int impactEntNum) { + trace_t trace; + vec3_t mins, start, end, dir; + float dist, drop; - //Offset the step height - VectorSet( mins, NPC->mins[0], NPC->mins[1], NPC->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, NPC->mins[0], NPC->mins[1], NPC->mins[2] + STEPSIZE); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, dest, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, NPC->currentOrigin, mins, NPC->maxs, dest, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); - //Do a simple check - if ( trace.allsolid || trace.startsolid ) - {//inside solid + // Do a simple check + if (trace.allsolid || trace.startsolid) { // inside solid return qfalse; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum ) - {//hit what we're going after + if (trace.fraction < 1.0f) { // hit something + if (impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum) { // hit what we're going after return qtrue; - } - else - { + } else { return qfalse; } } - //otherwise, clear path in a straight line. - //Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. - VectorSubtract( dest, NPC->currentOrigin, dir ); - dist = VectorNormalize( dir ); - if ( dest[2] > NPC->currentOrigin[2] ) - {//going up, check for steps + // otherwise, clear path in a straight line. + // Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. + VectorSubtract(dest, NPC->currentOrigin, dir); + dist = VectorNormalize(dir); + if (dest[2] > NPC->currentOrigin[2]) { // going up, check for steps drop = STEPSIZE; - } - else - {//going down or level, check for moderate drops + } else { // going down or level, check for moderate drops drop = 64; } - for ( float i = NPC->maxs[0]*2; i < dist; i += NPC->maxs[0]*2 ) - {//FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? - VectorMA( NPC->currentOrigin, i, dir, start ); - VectorCopy( start, end ); + for (float i = NPC->maxs[0] * 2; i < dist; + i += NPC->maxs[0] * 2) { // FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? + VectorMA(NPC->currentOrigin, i, dir, start); + VectorCopy(start, end); end[2] -= drop; - gi.trace( &trace, start, mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 );//NPC->mins? - if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) - {//good to go + gi.trace(&trace, start, mins, NPC->maxs, end, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); // NPC->mins? + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) { // good to go continue; } - //no floor here! (or a long drop?) + // no floor here! (or a long drop?) return qfalse; } - //we made it! + // we made it! return qtrue; } -qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) -{ - vec3_t forward, right, testPos, angles, mins; - trace_t trace; - float fwdDist, rtDist; - float bottom_max = -STEPSIZE*4 - 1; - - if ( !forwardmove && !rightmove ) - {//not even moving - //gi.Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); +qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset) { + vec3_t forward, right, testPos, angles, mins; + trace_t trace; + float fwdDist, rtDist; + float bottom_max = -STEPSIZE * 4 - 1; + + if (!forwardmove && !rightmove) { // not even moving + // gi.Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); return qtrue; } - if ( ucmd.upmove > 0 || NPC->client->ps.forceJumpCharge ) - {//Going to jump - //gi.Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); + if (ucmd.upmove > 0 || NPC->client->ps.forceJumpCharge) { // Going to jump + // gi.Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); return qtrue; } - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//in the air - //gi.Printf( "%d skipping walk-cliff check (in air)\n", level.time ); + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // in the air + // gi.Printf( "%d skipping walk-cliff check (in air)\n", level.time ); return qtrue; } /* @@ -465,81 +390,71 @@ qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) } */ - //FIXME: to really do this right, we'd have to actually do a pmove to predict where we're - //going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows - //NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? - VectorCopy( NPC->mins, mins ); + // FIXME: to really do this right, we'd have to actually do a pmove to predict where we're + // going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows + // NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? + VectorCopy(NPC->mins, mins); mins[2] += STEPSIZE; angles[PITCH] = angles[ROLL] = 0; - angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); - fwdDist = ((float)forwardmove)/2.0f; - rtDist = ((float)rightmove)/2.0f; - VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); - VectorMA( testPos, rtDist, right, testPos ); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//hmm, trace started inside this brush... how do we decide if we should continue? - //FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? - if ( reset ) - { + angles[YAW] = NPC->client->ps.viewangles[YAW]; // Add ucmd.angles[YAW]? + AngleVectors(angles, forward, right, NULL); + fwdDist = ((float)forwardmove) / 2.0f; + rtDist = ((float)rightmove) / 2.0f; + VectorMA(NPC->currentOrigin, fwdDist, forward, testPos); + VectorMA(testPos, rtDist, right, testPos); + gi.trace(&trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid) { // hmm, trace started inside this brush... how do we decide if we should continue? + // FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? + if (reset) { trace.fraction = 1.0f; } - VectorCopy( testPos, trace.endpos ); - //return qtrue; + VectorCopy(testPos, trace.endpos); + // return qtrue; } - if ( trace.fraction < 0.6 ) - {//Going to bump into something very close, don't move, just turn - if ( (NPC->enemy && trace.entityNum == NPC->enemy->s.number) || (NPCInfo->goalEntity && trace.entityNum == NPCInfo->goalEntity->s.number) ) - {//okay to bump into enemy or goal - //gi.Printf( "%d bump into enemy/goal okay\n", level.time ); + if (trace.fraction < 0.6) { // Going to bump into something very close, don't move, just turn + if ((NPC->enemy && trace.entityNum == NPC->enemy->s.number) || + (NPCInfo->goalEntity && trace.entityNum == NPCInfo->goalEntity->s.number)) { // okay to bump into enemy or goal + // gi.Printf( "%d bump into enemy/goal okay\n", level.time ); return qtrue; - } - else if ( reset ) - {//actually want to screw with the ucmd - //gi.Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); + } else if (reset) { // actually want to screw with the ucmd + // gi.Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); ucmd.forwardmove = 0; ucmd.rightmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } return qfalse; } - if ( NPCInfo->goalEntity ) - { - if ( NPCInfo->goalEntity->currentOrigin[2] < NPC->currentOrigin[2] ) - {//goal is below me, okay to step off at least that far plus stepheight + if (NPCInfo->goalEntity) { + if (NPCInfo->goalEntity->currentOrigin[2] < NPC->currentOrigin[2]) { // goal is below me, okay to step off at least that far plus stepheight bottom_max += NPCInfo->goalEntity->currentOrigin[2] - NPC->currentOrigin[2]; } } - VectorCopy( trace.endpos, testPos ); + VectorCopy(trace.endpos, testPos); testPos[2] += bottom_max; - gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); - //FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? - //OR: just put NPC clip brushes on these edges (still fall through when die) + // FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? + // OR: just put NPC clip brushes on these edges (still fall through when die) - if ( trace.allsolid || trace.startsolid ) - {//Not going off a cliff - //gi.Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); + if (trace.allsolid || trace.startsolid) { // Not going off a cliff + // gi.Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); return qtrue; } - if ( trace.fraction < 1.0 ) - {//Not going off a cliff - //FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... - //gi.Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); + if (trace.fraction < 1.0) { // Not going off a cliff + // FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... + // gi.Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); return qtrue; } - //going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? - if ( reset ) - {//actually want to screw with the ucmd - //gi.Printf( "%d avoiding walk off cliff\n", level.time ); - ucmd.forwardmove *= -1.0;//= 0; - ucmd.rightmove *= -1.0;//= 0; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + // going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? + if (reset) { // actually want to screw with the ucmd + // gi.Printf( "%d avoiding walk off cliff\n", level.time ); + ucmd.forwardmove *= -1.0; //= 0; + ucmd.rightmove *= -1.0; //= 0; + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); } return qfalse; } @@ -549,9 +464,8 @@ Jedi_HoldPosition ------------------------- */ -static void Jedi_HoldPosition( void ) -{ - //NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; +static void Jedi_HoldPosition(void) { + // NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; NPCInfo->goalEntity = NULL; /* @@ -568,60 +482,49 @@ Jedi_Move ------------------------- */ -static void Jedi_Move( gentity_t *goal, qboolean retreat ) -{ +static void Jedi_Move(gentity_t *goal, qboolean retreat) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = goal; - qboolean moved = NPC_MoveToGoal( qtrue ); - navInfo_t info; + qboolean moved = NPC_MoveToGoal(qtrue); + navInfo_t info; - //FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy - if ( retreat ) - {//FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? + // FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy + if (retreat) { // FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? ucmd.forwardmove *= -1; ucmd.rightmove *= -1; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); } - //Get the move info - NAV_GetLastMove( info ); + // Get the move info + NAV_GetLastMove(info); - //If we hit our target, then stop and fire! - if ( ( info.flags & NIF_COLLISION ) && ( info.blocker == NPC->enemy ) ) - { + // If we hit our target, then stop and fire! + if ((info.flags & NIF_COLLISION) && (info.blocker == NPC->enemy)) { Jedi_HoldPosition(); } - //If our move failed, then reset - if ( moved == qfalse ) - { + // If our move failed, then reset + if (moved == qfalse) { Jedi_HoldPosition(); } } -static qboolean Jedi_Hunt( void ) -{ - //gi.Printf( "Hunting\n" ); - //if we're at all interested in fighting, go after him - if ( NPCInfo->stats.aggression > 1 ) - {//approach enemy +static qboolean Jedi_Hunt(void) { + // gi.Printf( "Hunting\n" ); + // if we're at all interested in fighting, go after him + if (NPCInfo->stats.aggression > 1) { // approach enemy NPCInfo->combatMove = qtrue; - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else - { - if ( NPCInfo->goalEntity == NULL ) - {//hunt + } else { + if (NPCInfo->goalEntity == NULL) { // hunt NPCInfo->goalEntity = NPC->enemy; } - //Jedi_Move( NPC->enemy, qfalse ); - if ( NPC_MoveToGoal( qfalse ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // Jedi_Move( NPC->enemy, qfalse ); + if (NPC_MoveToGoal(qfalse)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -647,59 +550,46 @@ static qboolean Jedi_Track( void ) } */ -static void Jedi_Retreat( void ) -{ - if ( !TIMER_Done( NPC, "noRetreat" ) ) - {//don't actually move +static void Jedi_Retreat(void) { + if (!TIMER_Done(NPC, "noRetreat")) { // don't actually move return; } - //FIXME: when retreating, we should probably see if we can retreat - //in the direction we want. If not...? Evade? - //gi.Printf( "Retreating\n" ); - Jedi_Move( NPC->enemy, qtrue ); + // FIXME: when retreating, we should probably see if we can retreat + // in the direction we want. If not...? Evade? + // gi.Printf( "Retreating\n" ); + Jedi_Move(NPC->enemy, qtrue); } -static void Jedi_Advance( void ) -{ - if ( !NPC->client->ps.saberInFlight ) - { +static void Jedi_Advance(void) { + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.saberActive = qtrue; } - //gi.Printf( "Advancing\n" ); - Jedi_Move( NPC->enemy, qfalse ); + // gi.Printf( "Advancing\n" ); + Jedi_Move(NPC->enemy, qfalse); - //TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( NPC, "duck", 0 ); + // TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); + // TIMER_Set( NPC, "duck", 0 ); } -static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) -{ - if ( !self || !self->client ) - { +static void Jedi_AdjustSaberAnimLevel(gentity_t *self, int newLevel) { + if (!self || !self->client) { return; } - //FIXME: each NPC shold have a unique pattern of behavior for the order in which they - if ( self->client->NPC_class == CLASS_TAVION ) - {//special attacks + // FIXME: each NPC shold have a unique pattern of behavior for the order in which they + if (self->client->NPC_class == CLASS_TAVION) { // special attacks self->client->ps.saberAnimLevel = FORCE_LEVEL_5; return; - } - else if ( self->client->NPC_class == CLASS_DESANN ) - {//special attacks + } else if (self->client->NPC_class == CLASS_DESANN) { // special attacks self->client->ps.saberAnimLevel = FORCE_LEVEL_4; return; } - if ( self->client->playerTeam == TEAM_ENEMY ) - { - if ( self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG ) - {//grunt and fencer always uses quick attacks + if (self->client->playerTeam == TEAM_ENEMY) { + if (self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG) { // grunt and fencer always uses quick attacks self->client->ps.saberAnimLevel = FORCE_LEVEL_1; return; } - if ( self->NPC->rank == RANK_CREWMAN - || self->NPC->rank == RANK_ENSIGN ) - {//acrobat & force-users always use medium attacks + if (self->NPC->rank == RANK_CREWMAN || self->NPC->rank == RANK_ENSIGN) { // acrobat & force-users always use medium attacks self->client->ps.saberAnimLevel = FORCE_LEVEL_2; return; } @@ -711,200 +601,136 @@ static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) } */ } - //use the different attacks, how often they switch and under what circumstances - if ( newLevel > self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] ) - {//cap it + // use the different attacks, how often they switch and under what circumstances + if (newLevel > self->client->ps.forcePowerLevel[FP_SABER_OFFENSE]) { // cap it self->client->ps.saberAnimLevel = self->client->ps.forcePowerLevel[FP_SABER_OFFENSE]; - } - else if ( newLevel < FORCE_LEVEL_1 ) - { + } else if (newLevel < FORCE_LEVEL_1) { self->client->ps.saberAnimLevel = FORCE_LEVEL_1; - } - else - {//go ahead and set it + } else { // go ahead and set it self->client->ps.saberAnimLevel = newLevel; } - if ( d_JediAI->integer ) - { - switch ( self->client->ps.saberAnimLevel ) - { + if (d_JediAI->integer) { + switch (self->client->ps.saberAnimLevel) { case FORCE_LEVEL_1: - gi.Printf( S_COLOR_GREEN"%s Saber Attack Set: fast\n", self->NPC_type ); + gi.Printf(S_COLOR_GREEN "%s Saber Attack Set: fast\n", self->NPC_type); break; case FORCE_LEVEL_2: - gi.Printf( S_COLOR_YELLOW"%s Saber Attack Set: medium\n", self->NPC_type ); + gi.Printf(S_COLOR_YELLOW "%s Saber Attack Set: medium\n", self->NPC_type); break; case FORCE_LEVEL_3: - gi.Printf( S_COLOR_RED"%s Saber Attack Set: strong\n", self->NPC_type ); + gi.Printf(S_COLOR_RED "%s Saber Attack Set: strong\n", self->NPC_type); break; } } } -static void Jedi_CheckDecreaseSaberAnimLevel( void ) -{ - if ( !NPC->client->ps.weaponTime && !(ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//not attacking - if ( TIMER_Done( NPC, "saberLevelDebounce" ) && !Q_irand( 0, 10 ) ) - { - //Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//drop - Jedi_AdjustSaberAnimLevel( NPC, Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ));//random - TIMER_Set( NPC, "saberLevelDebounce", Q_irand( 3000, 10000 ) ); +static void Jedi_CheckDecreaseSaberAnimLevel(void) { + if (!NPC->client->ps.weaponTime && !(ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // not attacking + if (TIMER_Done(NPC, "saberLevelDebounce") && !Q_irand(0, 10)) { + // Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//drop + Jedi_AdjustSaberAnimLevel(NPC, Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3)); // random + TIMER_Set(NPC, "saberLevelDebounce", Q_irand(3000, 10000)); } - } - else - { - TIMER_Set( NPC, "saberLevelDebounce", Q_irand( 1000, 5000 ) ); + } else { + TIMER_Set(NPC, "saberLevelDebounce", Q_irand(1000, 5000)); } } -static void Jedi_CombatDistance( int enemy_dist ) -{//FIXME: for many of these checks, what we really want is horizontal distance to enemy - if ( NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//when gripping, don't move +static void Jedi_CombatDistance(int enemy_dist) { // FIXME: for many of these checks, what we really want is horizontal distance to enemy + if (NPC->client->ps.forcePowersActive & (1 << FP_GRIP) && NPC->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // when gripping, don't move return; - } - else if ( !TIMER_Done( NPC, "gripping" ) ) - {//stopped gripping, clear timers just in case - TIMER_Set( NPC, "gripping", -level.time ); - TIMER_Set( NPC, "attackDelay", Q_irand( 0, 1000 ) ); + } else if (!TIMER_Done(NPC, "gripping")) { // stopped gripping, clear timers just in case + TIMER_Set(NPC, "gripping", -level.time); + TIMER_Set(NPC, "attackDelay", Q_irand(0, 1000)); } - if ( NPC->client->ps.saberInFlight && - !PM_SaberInBrokenParry( NPC->client->ps.saberMove ) - && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//maintain distance - if ( enemy_dist < NPC->client->ps.saberEntityDist ) - { + if (NPC->client->ps.saberInFlight && !PM_SaberInBrokenParry(NPC->client->ps.saberMove) && + NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // maintain distance + if (enemy_dist < NPC->client->ps.saberEntityDist) { Jedi_Retreat(); - } - else if ( enemy_dist > NPC->client->ps.saberEntityDist && enemy_dist > 100 ) - { + } else if (enemy_dist > NPC->client->ps.saberEntityDist && enemy_dist > 100) { Jedi_Advance(); } - if ( NPC->client->ps.weapon == WP_SABER //using saber - && NPC->client->ps.saberEntityState == SES_LEAVING //not returning yet - && NPC->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 //2nd or 3rd level lightsaber - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//hold it out there + if (NPC->client->ps.weapon == WP_SABER // using saber + && NPC->client->ps.saberEntityState == SES_LEAVING // not returning yet + && NPC->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 // 2nd or 3rd level lightsaber + && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // hold it out there ucmd.buttons |= BUTTON_ALT_ATTACK; - //FIXME: time limit? + // FIXME: time limit? } - } - else if ( !TIMER_Done( NPC, "taunting" ) ) - { - if ( enemy_dist <= 64 ) - {//he's getting too close + } else if (!TIMER_Done(NPC, "taunting")) { + if (enemy_dist <= 64) { // he's getting too close ucmd.buttons |= BUTTON_ATTACK; - if ( !NPC->client->ps.saberInFlight ) - { + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.saberActive = qtrue; } - TIMER_Set( NPC, "taunting", -level.time ); - } - else if ( NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoAnimTimer < 2000 ) - {//we're almost done with our special taunt - //FIXME: this doesn't always work, for some reason - if ( !NPC->client->ps.saberInFlight ) - { + TIMER_Set(NPC, "taunting", -level.time); + } else if (NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoAnimTimer < 2000) { // we're almost done with our special taunt + // FIXME: this doesn't always work, for some reason + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.saberActive = qtrue; } } - } - else if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage - if ( enemy_dist > 0 ) - {//get closer so we can hit! + } else if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage + if (enemy_dist > 0) { // get closer so we can hit! Jedi_Advance(); } - if ( enemy_dist > 128 ) - {//lost 'em + if (enemy_dist > 128) { // lost 'em NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - if ( NPC->enemy->painDebounceTime + 2000 < level.time ) - {//the window of opportunity is gone + if (NPC->enemy->painDebounceTime + 2000 < level.time) { // the window of opportunity is gone NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - //don't strafe? - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - } - else if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time - && NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not - if ( enemy_dist < 64 ) - {//FIXME: maybe just pick another enemy? + // don't strafe? + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + } else if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client->ps.saberLockTime > level.time && + NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not + if (enemy_dist < 64) { // FIXME: maybe just pick another enemy? Jedi_Retreat(); } - } - else if ( NPC->enemy->s.weapon == WP_TURRET - && !Q_stricmp( "PAS", NPC->enemy->classname ) - && NPC->enemy->s.apos.trType == TR_STATIONARY ) - { - if ( enemy_dist > forcePushPullRadius[FORCE_LEVEL_1] - 16 ) - { + } else if (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname) && NPC->enemy->s.apos.trType == TR_STATIONARY) { + if (enemy_dist > forcePushPullRadius[FORCE_LEVEL_1] - 16) { Jedi_Advance(); } - int testlevel; - if ( NPC->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1 ) - {// + int testlevel; + if (NPC->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) { // testlevel = FORCE_LEVEL_1; - } - else - { + } else { testlevel = NPC->client->ps.forcePowerLevel[FP_PUSH]; } - if ( enemy_dist < forcePushPullRadius[testlevel] - 16 ) - {//close enough to push - if ( InFront( NPC->enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 0.6f ) ) - {//knock it down - WP_KnockdownTurret( NPC, NPC->enemy ); - //do the forcethrow call just for effect - ForceThrow( NPC, qfalse ); + if (enemy_dist < forcePushPullRadius[testlevel] - 16) { // close enough to push + if (InFront(NPC->enemy->currentOrigin, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, 0.6f)) { // knock it down + WP_KnockdownTurret(NPC, NPC->enemy); + // do the forcethrow call just for effect + ForceThrow(NPC, qfalse); } } - } - else if ( enemy_dist <= 64 && (NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//can't use saber and they're in striking range - if ( !Q_irand( 0, 5 ) && InFront( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f ) ) - { - ForceThrow( NPC, qfalse ); + } else if (enemy_dist <= 64 && (NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // can't use saber and they're in striking range + if (!Q_irand(0, 5) && InFront(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, 0.2f)) { + ForceThrow(NPC, qfalse); } Jedi_Retreat(); - } - else if ( enemy_dist <= -16 ) - {//we're too damn close! + } else if (enemy_dist <= -16) { // we're too damn close! Jedi_Retreat(); - } - else if ( enemy_dist <= 0 ) - {//we're within striking range - //if we are attacking, see if we should stop - if ( NPCInfo->stats.aggression < 4 ) - {//back off and defend + } else if (enemy_dist <= 0) { // we're within striking range + // if we are attacking, see if we should stop + if (NPCInfo->stats.aggression < 4) { // back off and defend Jedi_Retreat(); } - } - else if ( enemy_dist > 256 ) - {//we're way out of range - if ( enemy_dist > 384 ) - {//FIXME: check for enemy facing away and/or moving away - if ( !Q_irand( 0, 10 ) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time ) - { - if ( NPC_ClearLOS( NPC->enemy ) ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JCHASE1, EV_JCHASE3 ), 3000 ); + } else if (enemy_dist > 256) { // we're way out of range + if (enemy_dist > 384) { // FIXME: check for enemy facing away and/or moving away + if (!Q_irand(0, 10) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time) { + if (NPC_ClearLOS(NPC->enemy)) { + G_AddVoiceEvent(NPC, Q_irand(EV_JCHASE1, EV_JCHASE3), 3000); } jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - //Unless we're totally hiding, go after him - if ( NPCInfo->stats.aggression > 0 ) - {//approach enemy + // Unless we're totally hiding, go after him + if (NPCInfo->stats.aggression > 0) { // approach enemy Jedi_Advance(); } } @@ -914,229 +740,169 @@ static void Jedi_CombatDistance( int enemy_dist ) Jedi_Retreat(); } */ - else if ( enemy_dist > 50 )//FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax - {//we're out of striking range and we are allowed to attack - //first, check some tactical force power decisions - if ( NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//They're being gripped, rush them! - if ( NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + else if (enemy_dist > 50) // FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax + { // we're out of striking range and we are allowed to attack + // first, check some tactical force power decisions + if (NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.eFlags & EF_FORCE_GRIPPED)) { // They're being gripped, rush them! + if (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - if ( NPCInfo->rank >= RANK_LT_JG - && !Q_irand( 0, 5 ) - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + if (NPCInfo->rank >= RANK_LT_JG && !Q_irand(0, 5) && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } - } - else if ( NPC->enemy && NPC->enemy->client && //valid enemy - NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saberActive && //enemy throwing saber - !NPC->client->ps.weaponTime && //I'm not busy - WP_ForcePowerAvailable( NPC, FP_GRIP, 0 ) && //I can use the power - !Q_irand( 0, 10 ) && //don't do it all the time, averages to 1 check a second - Q_irand( 0, 6 ) < g_spskill->integer && //more likely on harder diff - Q_irand( RANK_CIVILIAN, RANK_CAPTAIN ) < NPCInfo->rank )//more likely against harder enemies - {//They're throwing their saber, grip them! - //taunt - if ( TIMER_Done( NPC, "chatter" ) && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); + } else if (NPC->enemy && NPC->enemy->client && // valid enemy + NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saberActive && // enemy throwing saber + !NPC->client->ps.weaponTime && // I'm not busy + WP_ForcePowerAvailable(NPC, FP_GRIP, 0) && // I can use the power + !Q_irand(0, 10) && // don't do it all the time, averages to 1 check a second + Q_irand(0, 6) < g_spskill->integer && // more likely on harder diff + Q_irand(RANK_CIVILIAN, RANK_CAPTAIN) < NPCInfo->rank) // more likely against harder enemies + { // They're throwing their saber, grip them! + // taunt + if (TIMER_Done(NPC, "chatter") && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - TIMER_Set( NPC, "chatter", 3000 ); - } - - //grip - TIMER_Set( NPC, "gripping", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); - } - else - { - if ( NPC->enemy && NPC->enemy->client && (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + TIMER_Set(NPC, "chatter", 3000); + } + + // grip + TIMER_Set(NPC, "gripping", 3000); + TIMER_Set(NPC, "attackDelay", 3000); + } else { + if (NPC->enemy && NPC->enemy->client && + (NPC->enemy->client->ps.forcePowersActive & + (1 << FP_GRIP))) { // They're choking someone, probably an ally, run at them and do some sort of attack + if (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } } int chanceScale = 0; - if ( NPC->client->NPC_class == CLASS_DESANN ) - { + if (NPC->client->NPC_class == CLASS_DESANN) { chanceScale = 1; - } - else if ( NPCInfo->rank == RANK_ENSIGN ) - { + } else if (NPCInfo->rank == RANK_ENSIGN) { chanceScale = 2; - } - else if ( NPCInfo->rank >= RANK_LT_JG ) - { + } else if (NPCInfo->rank >= RANK_LT_JG) { chanceScale = 5; } - if ( chanceScale - && (enemy_dist > Q_irand( 100, 200 ) || (NPCInfo->scriptFlags&SCF_DONT_FIRE)) - && enemy_dist < 500 - && (Q_irand( 0, chanceScale*10 )<5 || (NPC->enemy->client && NPC->enemy->client->ps.weapon != WP_SABER && !Q_irand( 0, chanceScale ) ) ) ) - {//else, randomly try some kind of attack every now and then - if ( (NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !Q_irand( 0, 1 ) ) - { - if ( WP_ForcePowerAvailable( NPC, FP_PULL, 0 ) && !Q_irand( 0, 2 ) ) - { - //force pull the guy to me! - //FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qtrue ); - //maybe strafe too? - TIMER_Set( NPC, "duck", enemy_dist*3 ); - if ( Q_irand( 0, 1 ) ) - { + if (chanceScale && (enemy_dist > Q_irand(100, 200) || (NPCInfo->scriptFlags & SCF_DONT_FIRE)) && enemy_dist < 500 && + (Q_irand(0, chanceScale * 10) < 5 || (NPC->enemy->client && NPC->enemy->client->ps.weapon != WP_SABER && + !Q_irand(0, chanceScale)))) { // else, randomly try some kind of attack every now and then + if ((NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !Q_irand(0, 1)) { + if (WP_ForcePowerAvailable(NPC, FP_PULL, 0) && !Q_irand(0, 2)) { + // force pull the guy to me! + // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qtrue); + // maybe strafe too? + TIMER_Set(NPC, "duck", enemy_dist * 3); + if (Q_irand(0, 1)) { ucmd.buttons |= BUTTON_ATTACK; } - } - else if ( WP_ForcePowerAvailable( NPC, FP_LIGHTNING, 0 ) && Q_irand( 0, 1 ) ) - { - ForceLightning( NPC ); - if ( NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - { - NPC->client->ps.weaponTime = Q_irand( 1000, 3000+(g_spskill->integer*500) ); - TIMER_Set( NPC, "holdLightning", NPC->client->ps.weaponTime ); + } else if (WP_ForcePowerAvailable(NPC, FP_LIGHTNING, 0) && Q_irand(0, 1)) { + ForceLightning(NPC); + if (NPC->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { + NPC->client->ps.weaponTime = Q_irand(1000, 3000 + (g_spskill->integer * 500)); + TIMER_Set(NPC, "holdLightning", NPC->client->ps.weaponTime); } - TIMER_Set( NPC, "attackDelay", NPC->client->ps.weaponTime ); - } - else if ( WP_ForcePowerAvailable( NPC, FP_GRIP, 0 ) ) - { - //taunt - if ( TIMER_Done( NPC, "chatter" ) && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); + TIMER_Set(NPC, "attackDelay", NPC->client->ps.weaponTime); + } else if (WP_ForcePowerAvailable(NPC, FP_GRIP, 0)) { + // taunt + if (TIMER_Done(NPC, "chatter") && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && + NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - TIMER_Set( NPC, "chatter", 3000 ); + TIMER_Set(NPC, "chatter", 3000); } - //grip - TIMER_Set( NPC, "gripping", 3000 ); - TIMER_Set( NPC, "attackDelay", 3000 ); - } - else if ( WP_ForcePowerAvailable( NPC, FP_SABERTHROW, 0 ) - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + // grip + TIMER_Set(NPC, "gripping", 3000); + TIMER_Set(NPC, "attackDelay", 3000); + } else if (WP_ForcePowerAvailable(NPC, FP_SABERTHROW, 0) && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } - } - else if ( NPCInfo->rank >= RANK_LT_JG - && !(NPC->client->ps.forcePowersActive&(1 << FP_SPEED)) - && !(NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + } else if (NPCInfo->rank >= RANK_LT_JG && !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber ucmd.buttons |= BUTTON_ALT_ATTACK; } } - //see if we should advance now - else if ( NPCInfo->stats.aggression > 5 ) - {//approach enemy - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( enemy_dist > 200 || !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + // see if we should advance now + else if (NPCInfo->stats.aggression > 5) { // approach enemy + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (!NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (enemy_dist > 200 || !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - } - else - {//maintain this distance? - //walk? + } else { // maintain this distance? + // walk? } } - } - else - {//we're not close enough to attack, but not far enough away to be safe - if ( NPCInfo->stats.aggression < 4 ) - {//back off and defend + } else { // we're not close enough to attack, but not far enough away to be safe + if (NPCInfo->stats.aggression < 4) { // back off and defend Jedi_Retreat(); - } - else if ( NPCInfo->stats.aggression > 5 ) - {//try to get closer - if ( enemy_dist > 0 && !(NPCInfo->scriptFlags&SCF_DONT_FIRE)) - {//we're allowed to use our lightsaber, get closer - if ( TIMER_Done( NPC, "parryTime" ) || NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance + } else if (NPCInfo->stats.aggression > 5) { // try to get closer + if (enemy_dist > 0 && !(NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // we're allowed to use our lightsaber, get closer + if (TIMER_Done(NPC, "parryTime") || NPCInfo->rank > RANK_LT) { // not parrying + if (!NPC->enemy->client || NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance Jedi_Advance(); } } } - } - else - {//agression is 4 or 5... somewhere in the middle - //what do we do here? Nothing? - //Move forward and back? + } else { // agression is 4 or 5... somewhere in the middle + // what do we do here? Nothing? + // Move forward and back? } } } -static qboolean Jedi_Strafe( int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking ) -{ - if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON && NPC->enemy && NPC->enemy->painDebounceTime > level.time ) - {//don't strafe if pressing the advantage of winning a saberLock +static qboolean Jedi_Strafe(int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking) { + if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON && NPC->enemy && + NPC->enemy->painDebounceTime > level.time) { // don't strafe if pressing the advantage of winning a saberLock return qfalse; } - if ( TIMER_Done( NPC, "strafeLeft" ) && TIMER_Done( NPC, "strafeRight" ) ) - { + if (TIMER_Done(NPC, "strafeLeft") && TIMER_Done(NPC, "strafeRight")) { qboolean strafed = qfalse; - //TODO: make left/right choice a tactical decision rather than random: + // TODO: make left/right choice a tactical decision rather than random: // try to keep own back away from walls and ledges, // try to keep enemy's back to a ledge or wall // Maybe try to strafe toward designer-placed "safe spots" or "goals"? - int strafeTime = Q_irand( strafeTimeMin, strafeTimeMax ); + int strafeTime = Q_irand(strafeTimeMin, strafeTimeMax); - if ( Q_irand( 0, 1 ) ) - { - if ( NPC_MoveDirClear( ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPC, "strafeLeft", strafeTime ); + if (Q_irand(0, 1)) { + if (NPC_MoveDirClear(ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPC, "strafeLeft", strafeTime); strafed = qtrue; - } - else if ( NPC_MoveDirClear( ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPC, "strafeRight", strafeTime ); + } else if (NPC_MoveDirClear(ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPC, "strafeRight", strafeTime); strafed = qtrue; } - } - else - { - if ( NPC_MoveDirClear( ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPC, "strafeRight", strafeTime ); + } else { + if (NPC_MoveDirClear(ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPC, "strafeRight", strafeTime); strafed = qtrue; - } - else if ( NPC_MoveDirClear( ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPC, "strafeLeft", strafeTime ); + } else if (NPC_MoveDirClear(ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPC, "strafeLeft", strafeTime); strafed = qtrue; } } - if ( strafed ) - { - TIMER_Set( NPC, "noStrafe", strafeTime + Q_irand( nextStrafeTimeMin, nextStrafeTimeMax ) ); - if ( walking ) - {//should be a slow strafe - TIMER_Set( NPC, "walking", strafeTime ); + if (strafed) { + TIMER_Set(NPC, "noStrafe", strafeTime + Q_irand(nextStrafeTimeMin, nextStrafeTimeMax)); + if (walking) { // should be a slow strafe + TIMER_Set(NPC, "walking", strafeTime); } return qtrue; } @@ -1179,30 +945,24 @@ Right now used to dodge instant-hit weapons. FIXME: possibly call this for saber melee evasion and/or missile evasion? FIXME: possibly let player do this too? */ -qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ) -{ - int dodgeAnim = -1; +qboolean Jedi_DodgeEvasion(gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc) { + int dodgeAnim = -1; - if ( !self || !self->client || self->health <= 0 ) - { + if (!self || !self->client || self->health <= 0) { return qfalse; } - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//can't dodge in mid-air + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // can't dodge in mid-air return qfalse; } - if ( self->client->ps.pm_time && (self->client->ps.pm_flags&PMF_TIME_KNOCKBACK) ) - {//in some effect that stops me from moving on my own + if (self->client->ps.pm_time && (self->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) { // in some effect that stops me from moving on my own return qfalse; } - if ( self->enemy == shooter ) - {//FIXME: make it so that we are better able to dodge shots from my current enemy + if (self->enemy == shooter) { // FIXME: make it so that we are better able to dodge shots from my current enemy } - if ( self->s.number ) - {//if an NPC, check game skill setting + if (self->s.number) { // if an NPC, check game skill setting /* if ( self->client->NPC_class != CLASS_DESANN && self->client->NPC_class != CLASS_LUKE && @@ -1220,41 +980,35 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in } } */ - } - else - {//the player - if ( !WP_ForcePowerUsable( self, FP_SPEED, 0 ) ) - {//make sure we have it and have enough force power + } else { // the player + if (!WP_ForcePowerUsable(self, FP_SPEED, 0)) { // make sure we have it and have enough force power return qfalse; } - //check force speed power level to determine if I should be able to dodge it - if ( Q_irand( 1, 10 ) > self->client->ps.forcePowerLevel[FP_SPEED] ) - {//more likely to fail on lower force speed level + // check force speed power level to determine if I should be able to dodge it + if (Q_irand(1, 10) > self->client->ps.forcePowerLevel[FP_SPEED]) { // more likely to fail on lower force speed level return qfalse; } } - if ( hitLoc == HL_NONE ) - { - if ( tr ) - { - for ( int z = 0; z < MAX_G2_COLLISIONS; z++ ) - { - if ( tr->G2CollisionMap[z].mEntityNum == -1 ) - {//actually, completely break out of this for loop since nothing after this in the aray should ever be valid either - continue;//break;// + if (hitLoc == HL_NONE) { + if (tr) { + for (int z = 0; z < MAX_G2_COLLISIONS; z++) { + if (tr->G2CollisionMap[z].mEntityNum == + -1) { // actually, completely break out of this for loop since nothing after this in the aray should ever be valid either + continue; // break;// } - CCollisionRecord &coll = tr->G2CollisionMap[z]; - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &hitLoc, coll.mCollisionPosition, NULL, NULL, MOD_UNKNOWN ); - //only want the first + CCollisionRecord &coll = tr->G2CollisionMap[z]; + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &hitLoc, + coll.mCollisionPosition, NULL, NULL, MOD_UNKNOWN); + // only want the first break; } } } - switch( hitLoc ) - { + switch (hitLoc) { case HL_NONE: return qfalse; break; @@ -1264,23 +1018,17 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in case HL_LEG_RT: case HL_LEG_LT: case HL_WAIST: - if ( !self->s.number ) - {//don't force the player to jump + if (!self->s.number) { // don't force the player to jump return qfalse; - } - else - { - if ( !self->enemy ) - { - G_SetEnemy( self, shooter ); + } else { + if (!self->enemy) { + G_SetEnemy(self, shooter); } - if ( self->NPC - && ((self->NPC->scriptFlags&SCF_NO_ACROBATICS) || PM_InKnockDown( &self->client->ps ) ) ) - { + if (self->NPC && ((self->NPC->scriptFlags & SCF_NO_ACROBATICS) || PM_InKnockDown(&self->client->ps))) { return qfalse; } - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently? - WP_ForcePowerStop( self, FP_GRIP ); + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently? + WP_ForcePowerStop(self, FP_GRIP); return qtrue; } break; @@ -1299,7 +1047,7 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in break; case HL_BACK: case HL_CHEST: - dodgeAnim = Q_irand( BOTH_DODGE_FL, BOTH_DODGE_R ); + dodgeAnim = Q_irand(BOTH_DODGE_FL, BOTH_DODGE_R); break; case HL_ARM_RT: case HL_HAND_RT: @@ -1310,12 +1058,11 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in dodgeAnim = BOTH_DODGE_R; break; case HL_HEAD: - dodgeAnim = Q_irand( BOTH_DODGE_FL, BOTH_DODGE_BR ); + dodgeAnim = Q_irand(BOTH_DODGE_FL, BOTH_DODGE_BR); break; } - if ( dodgeAnim != -1 ) - { + if (dodgeAnim != -1) { /* int type = SETANIM_TORSO; if ( VectorCompare( self->client->ps.velocity, vec3_origin ) ) @@ -1323,37 +1070,30 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in type = SETANIM_BOTH; } */ - //set the dodge anim we chose - NPC_SetAnim( self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//type - //self->client->ps.torsoAnimTimer = Q_irand( 5, 40 ) * 50; - //if ( type == SETANIM_BOTH ) - { - self->client->ps.legsAnimTimer = self->client->ps.torsoAnimTimer; - } - - if ( self->s.number ) - {//NPC - //maybe force them to stop moving in this case? - self->client->ps.pm_time = self->client->ps.torsoAnimTimer + Q_irand( 100, 1000 ); + // set the dodge anim we chose + NPC_SetAnim(self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // type + // self->client->ps.torsoAnimTimer = Q_irand( 5, 40 ) * 50; + // if ( type == SETANIM_BOTH ) + { self->client->ps.legsAnimTimer = self->client->ps.torsoAnimTimer; } + + if (self->s.number) { // NPC + // maybe force them to stop moving in this case? + self->client->ps.pm_time = self->client->ps.torsoAnimTimer + Q_irand(100, 1000); self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //do force speed effect + // do force speed effect self->client->ps.forcePowersActive |= (1 << FP_SPEED); self->client->ps.forcePowerDuration[FP_SPEED] = level.time + self->client->ps.torsoAnimTimer; - //sound - G_Sound( self, G_SoundIndex( "sound/weapons/force/speed.wav" ) ); - } - else - {//player - ForceSpeed( self, 500 ); + // sound + G_Sound(self, G_SoundIndex("sound/weapons/force/speed.wav")); + } else { // player + ForceSpeed(self, 500); } - WP_ForcePowerStop( self, FP_GRIP ); - if ( !self->enemy ) - { - G_SetEnemy( self, shooter ); - if ( self->s.number ) - { - Jedi_Aggression( self, 10 ); + WP_ForcePowerStop(self, FP_GRIP); + if (!self->enemy) { + G_SetEnemy(self, shooter); + if (self->s.number) { + Jedi_Aggression(self, 10); } } return qtrue; @@ -1361,294 +1101,221 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in return qfalse; } -evasionType_t Jedi_CheckFlipEvasions( gentity_t *self, float rightdot, float zdiff ) -{ - if ( self->NPC && (self->NPC->scriptFlags&SCF_NO_ACROBATICS) ) - { +evasionType_t Jedi_CheckFlipEvasions(gentity_t *self, float rightdot, float zdiff) { + if (self->NPC && (self->NPC->scriptFlags & SCF_NO_ACROBATICS)) { return EVASION_NONE; } - //Check for: - //ARIALS/CARTWHEELS - //WALL-RUNS - //WALL-FLIPS - //FIXME: if facing a wall, do forward wall-walk-backflip - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - {//already running on a wall + // Check for: + // ARIALS/CARTWHEELS + // WALL-RUNS + // WALL-FLIPS + // FIXME: if facing a wall, do forward wall-walk-backflip + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { // already running on a wall vec3_t right, fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; - int anim = -1; + int anim = -1; - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); - float animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ); - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0 ) - {//I'm running on a wall to my left and the attack is on the left - if ( animLength - self->client->ps.legsAnimTimer > 400 - && self->client->ps.legsAnimTimer > 400 ) - {//not at the beginning or end of the anim + float animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim); + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0) { // I'm running on a wall to my left and the attack is on the left + if (animLength - self->client->ps.legsAnimTimer > 400 && self->client->ps.legsAnimTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_LEFT_FLIP; } - } - else if ( self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0 ) - {//I'm running on a wall to my right and the attack is on the right - if ( animLength - self->client->ps.legsAnimTimer > 400 - && self->client->ps.legsAnimTimer > 400 ) - {//not at the beginning or end of the anim + } else if (self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0) { // I'm running on a wall to my right and the attack is on the right + if (animLength - self->client->ps.legsAnimTimer > 400 && self->client->ps.legsAnimTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_RIGHT_FLIP; } } - if ( anim != -1 ) - {//flip off the wall! - //FIXME: check the direction we will flip towards for do-not-enter/walls/drops? - //NOTE: we presume there is still a wall there! - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + if (anim != -1) { // flip off the wall! + // FIXME: check the direction we will flip towards for do-not-enter/walls/drops? + // NOTE: we presume there is still a wall there! + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - G_AddEvent( self, EV_JUMP, 0 ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + G_AddEvent(self, EV_JUMP, 0); return EVASION_OTHER; } - } - else if ( self->client->NPC_class != CLASS_DESANN //desann doesn't do these kind of frilly acrobatics - && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) - && Q_irand( 0, 1 ) - && !PM_InRoll( &self->client->ps ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - { - vec3_t fwd, right, traceto, mins = {self->mins[0],self->mins[1],0}, maxs = {self->maxs[0],self->maxs[1],24}, fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; - trace_t trace; + } else if (self->client->NPC_class != CLASS_DESANN // desann doesn't do these kind of frilly acrobatics + && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) && Q_irand(0, 1) && !PM_InRoll(&self->client->ps) && + !PM_InKnockDown(&self->client->ps) && !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) { + vec3_t fwd, right, traceto, mins = {self->mins[0], self->mins[1], 0}, maxs = {self->maxs[0], self->maxs[1], 24}, + fwdAngles = {0, self->client->ps.viewangles[YAW], 0}; + trace_t trace; - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); int parts = SETANIM_BOTH, anim; - float speed, checkDist; + float speed, checkDist; - if ( PM_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInStart( self->client->ps.saberMove ) ) - { + if (PM_SaberInAttack(self->client->ps.saberMove) || PM_SaberInStart(self->client->ps.saberMove)) { parts = SETANIM_LEGS; } - if ( rightdot >= 0 ) - { - if ( Q_irand( 0, 1 ) ) - { + if (rightdot >= 0) { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_LEFT; - } - else - { + } else { anim = BOTH_CARTWHEEL_LEFT; } checkDist = -128; speed = -200; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_RIGHT; - } - else - { + } else { anim = BOTH_CARTWHEEL_RIGHT; } checkDist = 128; speed = 200; } - //trace in the dir that we want to go - VectorMA( self->currentOrigin, checkDist, right, traceto ); - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f ) - {//it's clear, let's do it - //FIXME: check for drops? - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.weaponTime = self->client->ps.legsAnimTimer;//don't attack again until this anim is done + // trace in the dir that we want to go + VectorMA(self->currentOrigin, checkDist, right, traceto); + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f) { // it's clear, let's do it + // FIXME: check for drops? + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.weaponTime = self->client->ps.legsAnimTimer; // don't attack again until this anim is done vec3_t fwdAngles, jumpRt; - VectorCopy( self->client->ps.viewangles, fwdAngles ); + VectorCopy(self->client->ps.viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the flip - AngleVectors( fwdAngles, NULL, jumpRt, NULL ); - VectorScale( jumpRt, speed, self->client->ps.velocity ); - self->client->ps.forceJumpCharge = 0;//so we don't play the force flip anim + // do the flip + AngleVectors(fwdAngles, NULL, jumpRt, NULL); + VectorScale(jumpRt, speed, self->client->ps.velocity); + self->client->ps.forceJumpCharge = 0; // so we don't play the force flip anim self->client->ps.velocity[2] = 200; - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height self->client->ps.pm_flags |= PMF_JUMPING; - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); - //ucmd.upmove = 0; + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); + // ucmd.upmove = 0; return EVASION_CARTWHEEL; - } - else if ( !(trace.contents&CONTENTS_BOTCLIP) ) - {//hit a wall, not a do-not-enter brush - //FIXME: before we check any of these jump-type evasions, we should check for headroom, right? - //Okay, see if we can flip *off* the wall and go the other way - vec3_t idealNormal; - VectorSubtract( self->currentOrigin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + } else if (!(trace.contents & CONTENTS_BOTCLIP)) { // hit a wall, not a do-not-enter brush + // FIXME: before we check any of these jump-type evasions, we should check for headroom, right? + // Okay, see if we can flip *off* the wall and go the other way + vec3_t idealNormal; + VectorSubtract(self->currentOrigin, traceto, idealNormal); + VectorNormalize(idealNormal); gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( (trace.entityNums.solid!=SOLID_BMODEL) || DotProduct( trace.plane.normal, idealNormal ) > 0.7f ) - {//it's a ent of some sort or it's a wall roughly facing us + if ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7f) { // it's a ent of some sort or it's a wall roughly facing us float bestCheckDist = 0; - //hmm, see if we're moving forward - if ( DotProduct( self->client->ps.velocity, fwd ) < 200 ) - {//not running forward very fast - //check to see if it's okay to move the other way - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on that side is close enough to wall-flip off of or wall-run on + // hmm, see if we're moving forward + if (DotProduct(self->client->ps.velocity, fwd) < 200) { // not running forward very fast + // check to see if it's okay to move the other way + if ((trace.fraction * checkDist) <= 32) { // wall on that side is close enough to wall-flip off of or wall-run on bestCheckDist = checkDist; checkDist *= -1.0f; - VectorMA( self->currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f ) - {//it's clear, let's do it - //FIXME: check for drops? - //turn the cartwheel into a wallflip in the other dir - if ( rightdot > 0 ) - { + VectorMA(self->currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, + G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f) { // it's clear, let's do it + // FIXME: check for drops? + // turn the cartwheel into a wallflip in the other dir + if (rightdot > 0) { anim = BOTH_WALL_FLIP_LEFT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else { anim = BOTH_WALL_FLIP_RIGHT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); return EVASION_OTHER; - } - else - {//boxed in on both sides - if ( DotProduct( self->client->ps.velocity, fwd ) < 0 ) - {//moving backwards + } else { // boxed in on both sides + if (DotProduct(self->client->ps.velocity, fwd) < 0) { // moving backwards return EVASION_NONE; } - if ( (trace.fraction*checkDist) <= 32 && (trace.fraction*checkDist) < bestCheckDist ) - { + if ((trace.fraction * checkDist) <= 32 && (trace.fraction * checkDist) < bestCheckDist) { bestCheckDist = checkDist; } } - } - else - {//too far from that wall to flip or run off it, check other side + } else { // too far from that wall to flip or run off it, check other side checkDist *= -1.0f; - VectorMA( self->currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - gi.trace( &trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on this side is close enough + VectorMA(self->currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + gi.trace(&trace, self->currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, + G2_NOCOLLIDE, 0); + if ((trace.fraction * checkDist) <= 32) { // wall on this side is close enough bestCheckDist = checkDist; - } - else - {//neither side has a wall within 32 + } else { // neither side has a wall within 32 return EVASION_NONE; } } } - //Try wall run? - if ( bestCheckDist ) - {//one of the walls was close enough to wall-run on - //FIXME: check for long enough wall and a drop at the end? - if ( bestCheckDist > 0 ) - {//it was to the right + // Try wall run? + if (bestCheckDist) { // one of the walls was close enough to wall-run on + // FIXME: check for long enough wall and a drop at the end? + if (bestCheckDist > 0) { // it was to the right anim = BOTH_WALL_RUN_RIGHT; - } - else - {//it was to the left + } else { // it was to the left anim = BOTH_WALL_RUN_LEFT; } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me int parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); return EVASION_OTHER; } - //else check for wall in front, do backflip off wall + // else check for wall in front, do backflip off wall } } } return EVASION_NONE; } -int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) -{ - if ( !self->client ) - { +int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType) { + if (!self->client) { return 0; } - if ( !self->s.number ) - {//player + if (!self->s.number) { // player return parryDebounce[self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]]; - } - else if ( self->NPC ) - { - if ( !g_saberRealisticCombat->integer - && ( g_spskill->integer == 2 || (g_spskill->integer == 1 && self->client->NPC_class == CLASS_TAVION) ) ) - { - if ( self->client->NPC_class == CLASS_TAVION ) - { + } else if (self->NPC) { + if (!g_saberRealisticCombat->integer && (g_spskill->integer == 2 || (g_spskill->integer == 1 && self->client->NPC_class == CLASS_TAVION))) { + if (self->client->NPC_class == CLASS_TAVION) { return 0; + } else { + return Q_irand(0, 150); } - else - { - return Q_irand( 0, 150 ); - } - } - else - { - int baseTime; - if ( evasionType == EVASION_DODGE ) - { + } else { + int baseTime; + if (evasionType == EVASION_DODGE) { baseTime = self->client->ps.torsoAnimTimer; - } - else if ( evasionType == EVASION_CARTWHEEL ) - { + } else if (evasionType == EVASION_CARTWHEEL) { baseTime = self->client->ps.torsoAnimTimer; - } - else if ( self->client->ps.saberInFlight ) - { - baseTime = Q_irand( 1, 3 ) * 50; - } - else - { - if ( g_saberRealisticCombat->integer ) - { + } else if (self->client->ps.saberInFlight) { + baseTime = Q_irand(1, 3) * 50; + } else { + if (g_saberRealisticCombat->integer) { baseTime = 500; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: baseTime = 500; break; @@ -1660,76 +1327,49 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) baseTime = 100; break; } - } - else - { - baseTime = 150;//500; + } else { + baseTime = 150; // 500; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: - baseTime = 200;//500; + baseTime = 200; // 500; break; case 1: - baseTime = 100;//300; + baseTime = 100; // 300; break; case 2: default: - baseTime = 50;//100; + baseTime = 50; // 100; break; } } - if ( self->client->NPC_class == CLASS_TAVION ) - {//Tavion is faster - baseTime = ceil(baseTime/2.0f); - } - else if ( self->NPC->rank >= RANK_LT_JG ) - {//fencers, bosses, shadowtroopers, luke, desann, et al use the norm - if ( Q_irand( 0, 2 ) ) - {//medium speed parry + if (self->client->NPC_class == CLASS_TAVION) { // Tavion is faster + baseTime = ceil(baseTime / 2.0f); + } else if (self->NPC->rank >= RANK_LT_JG) { // fencers, bosses, shadowtroopers, luke, desann, et al use the norm + if (Q_irand(0, 2)) { // medium speed parry baseTime = baseTime; + } else { // with the occasional fast parry + baseTime = ceil(baseTime / 2.0f); } - else - {//with the occasional fast parry - baseTime = ceil(baseTime/2.0f); - } - } - else if ( self->NPC->rank == RANK_CIVILIAN ) - {//grunts are slowest - baseTime = baseTime*Q_irand(1,3); - } - else if ( self->NPC->rank == RANK_CREWMAN ) - {//acrobats aren't so bad - if ( evasionType == EVASION_PARRY - || evasionType == EVASION_DUCK_PARRY - || evasionType == EVASION_JUMP_PARRY ) - {//slower with parries - baseTime = baseTime*Q_irand(1,2); - } - else - {//faster with acrobatics - //baseTime = baseTime; + } else if (self->NPC->rank == RANK_CIVILIAN) { // grunts are slowest + baseTime = baseTime * Q_irand(1, 3); + } else if (self->NPC->rank == RANK_CREWMAN) { // acrobats aren't so bad + if (evasionType == EVASION_PARRY || evasionType == EVASION_DUCK_PARRY || evasionType == EVASION_JUMP_PARRY) { // slower with parries + baseTime = baseTime * Q_irand(1, 2); + } else { // faster with acrobatics + // baseTime = baseTime; } + } else { // force users are kinda slow + baseTime = baseTime * Q_irand(1, 2); } - else - {//force users are kinda slow - baseTime = baseTime*Q_irand(1,2); - } - if ( evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY ) - { + if (evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY) { baseTime += 100; - } - else if ( evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY ) - { + } else if (evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY) { baseTime += 50; - } - else if ( evasionType == EVASION_OTHER ) - { + } else if (evasionType == EVASION_OTHER) { baseTime += 100; - } - else if ( evasionType == EVASION_FJUMP ) - { + } else if (evasionType == EVASION_FJUMP) { baseTime += 100; } } @@ -1740,30 +1380,24 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) return 0; } -qboolean Jedi_QuickReactions( gentity_t *self ) -{ - if ( ( self->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) || - self->client->NPC_class == CLASS_TAVION || - (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_1&&g_spskill->integer>1) || - (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_2&&g_spskill->integer>0) ) - { +qboolean Jedi_QuickReactions(gentity_t *self) { + if ((self->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER) || self->client->NPC_class == CLASS_TAVION || + (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && g_spskill->integer > 1) || + (self->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 && g_spskill->integer > 0)) { return qtrue; } return qfalse; } -qboolean Jedi_SaberBusy( gentity_t *self ) -{ - if ( self->client->ps.torsoAnimTimer > 300 - && ( (PM_SaberInAttack( self->client->ps.saberMove )&&self->client->ps.saberAnimLevel==FORCE_LEVEL_3) - || PM_SpinningSaberAnim( self->client->ps.torsoAnim ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - //|| PM_SaberInBounce( self->client->ps.saberMove ) - || PM_SaberInBrokenParry( self->client->ps.saberMove ) - //|| PM_SaberInDeflect( self->client->ps.saberMove ) - || PM_FlippingAnim( self->client->ps.torsoAnim ) - || PM_RollingAnim( self->client->ps.torsoAnim ) ) ) - {//my saber is not in a parrying position +qboolean Jedi_SaberBusy(gentity_t *self) { + if (self->client->ps.torsoAnimTimer > 300 && + ((PM_SaberInAttack(self->client->ps.saberMove) && self->client->ps.saberAnimLevel == FORCE_LEVEL_3) || + PM_SpinningSaberAnim(self->client->ps.torsoAnim) || + PM_SaberInSpecialAttack(self->client->ps.torsoAnim) + //|| PM_SaberInBounce( self->client->ps.saberMove ) + || PM_SaberInBrokenParry(self->client->ps.saberMove) + //|| PM_SaberInDeflect( self->client->ps.saberMove ) + || PM_FlippingAnim(self->client->ps.torsoAnim) || PM_RollingAnim(self->client->ps.torsoAnim))) { // my saber is not in a parrying position return qtrue; } return qfalse; @@ -1781,551 +1415,396 @@ NOTE: always blocking projectiles in this func! ------------------------- */ -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f ) -{ - vec3_t hitloc, hitdir, diff, fwdangles={0,0,0}, right; +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f) { + vec3_t hitloc, hitdir, diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - int duckChance = 0; - int dodgeAnim = -1; - qboolean saberBusy = qfalse, /*evaded = qfalse, */doDodge = qfalse; - evasionType_t evasionType = EVASION_NONE; - - //FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! - //FIXME: reborn don't block enough anymore - if ( !incoming ) - { - VectorCopy( pHitloc, hitloc ); - VectorCopy( phitDir, hitdir ); - //FIXME: maybe base this on rank some? And/or g_spskill? - if ( self->client->ps.saberInFlight ) - {//DOH! do non-saber evasion! + int duckChance = 0; + int dodgeAnim = -1; + qboolean saberBusy = qfalse, /*evaded = qfalse, */ doDodge = qfalse; + evasionType_t evasionType = EVASION_NONE; + + // FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! + // FIXME: reborn don't block enough anymore + if (!incoming) { + VectorCopy(pHitloc, hitloc); + VectorCopy(phitDir, hitdir); + // FIXME: maybe base this on rank some? And/or g_spskill? + if (self->client->ps.saberInFlight) { // DOH! do non-saber evasion! saberBusy = qtrue; + } else if (Jedi_QuickReactions( + self)) { // jedi trainer and tavion are must faster at parrying and can do it whenever they like + // Also, on medium, all level 3 people can parry any time and on hard, all level 2 or 3 people can parry any time + } else { + saberBusy = Jedi_SaberBusy(self); } - else if ( Jedi_QuickReactions( self ) ) - {//jedi trainer and tavion are must faster at parrying and can do it whenever they like - //Also, on medium, all level 3 people can parry any time and on hard, all level 2 or 3 people can parry any time - } - else - { - saberBusy = Jedi_SaberBusy( self ); + } else { + if (incoming->s.weapon == WP_SABER) { // flying lightsaber, face it! + // FIXME: for this to actually work, we'd need to call update angles too? + // Jedi_FaceEntity( self, incoming, qtrue ); } + VectorCopy(incoming->currentOrigin, hitloc); + VectorNormalize2(incoming->s.pos.trDelta, hitdir); } - else - { - if ( incoming->s.weapon == WP_SABER ) - {//flying lightsaber, face it! - //FIXME: for this to actually work, we'd need to call update angles too? - //Jedi_FaceEntity( self, incoming, qtrue ); - } - VectorCopy( incoming->currentOrigin, hitloc ); - VectorNormalize2( incoming->s.pos.trDelta, hitdir ); - } - VectorSubtract( hitloc, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(hitloc, self->client->renderInfo.eyePoint, diff); diff[2] = 0; - //VectorNormalize( diff ); + // VectorNormalize( diff ); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); - - rightdot = DotProduct(right, diff);// + Q_flrand(-0.10f,0.10f); - //totalHeight = self->client->renderInfo.eyePoint[2] - self->absmin[2]; - zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2];// + Q_irand(-6,6); - - //see if we can dodge if need-be - if ( (dist>16&&(Q_irand( 0, 2 )||saberBusy)) || self->client->ps.saberInFlight || !self->client->ps.saberActive ) - {//either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG) ) - {//acrobat or fencer or above - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE &&//on the ground - !(self->client->ps.pm_flags&PMF_DUCKED)&&cmd->upmove>=0&&TIMER_Done( self, "duck" )//not ducking - && !PM_InRoll( &self->client->ps )//not rolling - && !PM_InKnockDown( &self->client->ps )//not knocked down - && ( self->client->ps.saberInFlight || - (!PM_SaberInAttack( self->client->ps.saberMove )//not attacking - && !PM_SaberInStart( self->client->ps.saberMove )//not starting an attack - && !PM_SpinningSaberAnim( self->client->ps.torsoAnim )//not in a saber spin - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ))//not in a special attack - ) - ) - {//need to check all these because it overrides both torso and legs with the dodge + AngleVectors(fwdangles, NULL, right, NULL); + + rightdot = DotProduct(right, diff); // + Q_flrand(-0.10f,0.10f); + // totalHeight = self->client->renderInfo.eyePoint[2] - self->absmin[2]; + zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2]; // + Q_irand(-6,6); + + // see if we can dodge if need-be + if ((dist > 16 && (Q_irand(0, 2) || saberBusy)) || self->client->ps.saberInFlight || + !self->client->ps.saberActive) { // either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG)) { // acrobat or fencer or above + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && // on the ground + !(self->client->ps.pm_flags & PMF_DUCKED) && cmd->upmove >= 0 && TIMER_Done(self, "duck") // not ducking + && !PM_InRoll(&self->client->ps) // not rolling + && !PM_InKnockDown(&self->client->ps) // not knocked down + && (self->client->ps.saberInFlight || (!PM_SaberInAttack(self->client->ps.saberMove) // not attacking + && !PM_SaberInStart(self->client->ps.saberMove) // not starting an attack + && !PM_SpinningSaberAnim(self->client->ps.torsoAnim) // not in a saber spin + && !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) // not in a special attack + )) { // need to check all these because it overrides both torso and legs with the dodge doDodge = qtrue; } } } // Figure out what quadrant the block was in. - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2]-self->absmin[2],zdiff,rightdot); + if (d_JediAI->integer) { + gi.Printf("(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2] - self->absmin[2], zdiff, rightdot); } - //UL = > -1//-6 - //UR = > -6//-9 - //TOP = > +6//+4 - //FIXME: take FP_SABER_DEFENSE into account here somehow? - if ( zdiff >= -5 )//was 0 + // UL = > -1//-6 + // UR = > -6//-9 + // TOP = > +6//+4 + // FIXME: take FP_SABER_DEFENSE into account here somehow? + if (zdiff >= -5) // was 0 { - if ( incoming || !saberBusy ) - { - if ( rightdot > 12 - || (rightdot > 3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, 0.3 + if (incoming || !saberBusy) { + if (rightdot > 12 || (rightdot > 3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, 0.3 { - if ( doDodge ) - { - if ( Q_irand( 0, 1 ) ) - { + if (doDodge) { + if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FL; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BL; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI->integer ) - { - gi.Printf( "UR block\n" ); + if (d_JediAI->integer) { + gi.Printf("UR block\n"); } - } - else if ( rightdot < -12 - || (rightdot < -3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, -0.3 + } else if (rightdot < -12 || (rightdot < -3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, -0.3 { - if ( doDodge ) - { - if ( Q_irand( 0, 1 ) ) - { + if (doDodge) { + if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FR; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BR; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - ///evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + /// evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI->integer ) - { - gi.Printf( "UL block\n" ); + if (d_JediAI->integer) { + gi.Printf("UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { duckChance = 4; } - if ( d_JediAI->integer ) - { - gi.Printf( "TOP block\n" ); + if (d_JediAI->integer) { + gi.Printf("TOP block\n"); } } - //evaded = qtrue; - } - else - { - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + // evaded = qtrue; + } else { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("duck "); } } } } - //LL = -22//= -18 to -39 - //LR = -23//= -20 to -41 - else if ( zdiff > -22 )//was-15 ) + // LL = -22//= -18 to -39 + // LR = -23//= -20 to -41 + else if (zdiff > -22) // was-15 ) { - if ( 1 )//zdiff < -10 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (1) // zdiff < -10 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "duck " ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("duck "); } - } - else - {//in air! Ducking does no good + } else { // in air! Ducking does no good } } - if ( incoming || !saberBusy ) - { - if ( rightdot > 8 || (rightdot > 3 && zdiff < -11) )//was normalized, 0.2 + if (incoming || !saberBusy) { + if (rightdot > 8 || (rightdot > 3 && zdiff < -11)) // was normalized, 0.2 { - if ( doDodge ) - { + if (doDodge) { dodgeAnim = BOTH_DODGE_L; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-UR block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-UR block\n"); } - } - else if ( rightdot < -8 || (rightdot < -3 && zdiff < -11) )//was normalized, -0.2 + } else if (rightdot < -8 || (rightdot < -3 && zdiff < -11)) // was normalized, -0.2 { - if ( doDodge ) - { + if (doDodge) { dodgeAnim = BOTH_DODGE_R; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-UL block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "mid-TOP block\n" ); + if (d_JediAI->integer) { + gi.Printf("mid-TOP block\n"); } } - //evaded = qtrue; + // evaded = qtrue; } - } - else if ( saberBusy || (zdiff < -36 && ( zdiff < -44 || !Q_irand( 0, 2 ) ) ) )//was -30 and -40//2nd one was -46 - {//jump! - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//already in air, duck to pull up legs - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + } else if (saberBusy || (zdiff < -36 && (zdiff < -44 || !Q_irand(0, 2)))) // was -30 and -40//2nd one was -46 + { // jump! + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // already in air, duck to pull up legs + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "legs up\n" ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("legs up\n"); } - if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } - //evaded = qtrue; - } - } - else - {//gotta jump! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && !PM_InKnockDown( &self->client->ps ) ) - { - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently + // evaded = qtrue; + } + } else { // gotta jump! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "force jump + " ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) ) - { - if ( self == NPC ) - { + } else { // normal jump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS)) { + if (self == NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } evasionType = EVASION_JUMP; - //evaded = qtrue; - if ( d_JediAI->integer ) - { - gi.Printf( "jump + " ); + // evaded = qtrue; + if (d_JediAI->integer) { + gi.Printf("jump + "); } } - if ( self->client->NPC_class == CLASS_TAVION && !incoming && self->client->ps.groundEntityNum < ENTITYNUM_NONE && !Q_irand( 0, 2 ) ) - { - if ( !PM_SaberInAttack( self->client->ps.saberMove ) - && !PM_SaberInStart( self->client->ps.saberMove ) - && !PM_InRoll( &self->client->ps ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - {//do the butterfly! + if (self->client->NPC_class == CLASS_TAVION && !incoming && self->client->ps.groundEntityNum < ENTITYNUM_NONE && !Q_irand(0, 2)) { + if (!PM_SaberInAttack(self->client->ps.saberMove) && !PM_SaberInStart(self->client->ps.saberMove) && !PM_InRoll(&self->client->ps) && + !PM_InKnockDown(&self->client->ps) && !PM_SaberInSpecialAttack(self->client->ps.torsoAnim)) { // do the butterfly! int butterflyAnim; - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { butterflyAnim = BOTH_BUTTERFLY_LEFT; - } - else - { + } else { butterflyAnim = BOTH_BUTTERFLY_RIGHT; } evasionType = EVASION_CARTWHEEL; - NPC_SetAnim( self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.velocity[2] = 225; - self->client->ps.forceJumpZStart = self->currentOrigin[2];//so we don't take damage if we land at same height - self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - self->client->saberTrail.inAction = qtrue;//FIXME: reset this when done! - self->client->saberTrail.duration = 300;//FIXME: reset this when done! - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // so we don't take damage if we land at same height + self->client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + self->client->saberTrail.inAction = qtrue; // FIXME: reset this when done! + self->client->saberTrail.duration = 300; // FIXME: reset this when done! + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); cmd->upmove = 0; saberBusy = qtrue; - //evaded = qtrue; + // evaded = qtrue; } } } - if ( ((evasionType = Jedi_CheckFlipEvasions( self, rightdot, zdiff ))!=EVASION_NONE) ) - { - if ( d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number ) - { - G_StartMatrixEffect( self ); + if (((evasionType = Jedi_CheckFlipEvasions(self, rightdot, zdiff)) != EVASION_NONE)) { + if (d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number) { + G_StartMatrixEffect(self); } saberBusy = qtrue; - //evaded = qtrue; - } - else if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + // evaded = qtrue; + } else if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } - //evaded = qtrue; + // evaded = qtrue; } } - } - else - { - if ( incoming || !saberBusy ) - { - if ( rightdot >= 0 ) - { + } else { + if (incoming || !saberBusy) { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LR block\n" ); + if (d_JediAI->integer) { + gi.Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "LL block\n" ); + if (d_JediAI->integer) { + gi.Printf("LL block\n"); } } - if ( incoming && incoming->s.weapon == WP_SABER ) - {//thrown saber! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && !PM_InKnockDown( &self->client->ps ) ) - { - self->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently + if (incoming && incoming->s.weapon == WP_SABER) { // thrown saber! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - if ( d_JediAI->integer ) - { - gi.Printf( "force jump + " ); + if (d_JediAI->integer) { + gi.Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) ) - { - if ( self == NPC ) - { + } else { // normal jump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS)) { + if (self == NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } evasionType = EVASION_JUMP_PARRY; - if ( d_JediAI->integer ) - { - gi.Printf( "jump + " ); + if (d_JediAI->integer) { + gi.Printf("jump + "); } } } } - //evaded = qtrue; + // evaded = qtrue; } } - if ( evasionType == EVASION_NONE ) - { + if (evasionType == EVASION_NONE) { return EVASION_NONE; } - //stop taunting - TIMER_Set( self, "taunting", 0 ); - //stop gripping - TIMER_Set( self, "gripping", -level.time ); - WP_ForcePowerStop( self, FP_GRIP ); + // stop taunting + TIMER_Set(self, "taunting", 0); + // stop gripping + TIMER_Set(self, "gripping", -level.time); + WP_ForcePowerStop(self, FP_GRIP); - if ( dodgeAnim != -1 ) - {//dodged + if (dodgeAnim != -1) { // dodged evasionType = EVASION_DODGE; - NPC_SetAnim( self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - //force them to stop moving in this case + // force them to stop moving in this case self->client->ps.pm_time = self->client->ps.torsoAnimTimer; - //FIXME: maybe make a sound? Like a grunt? EV_JUMP? + // FIXME: maybe make a sound? Like a grunt? EV_JUMP? self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //dodged, not block - if ( d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number ) - { - G_StartMatrixEffect( self ); - } - } - else - { - if ( duckChance ) - { - if ( !Q_irand( 0, duckChance ) ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - if ( evasionType == EVASION_PARRY ) - { + // dodged, not block + if (d_slowmodeath->integer > 5 && self->enemy && !self->enemy->s.number) { + G_StartMatrixEffect(self); + } + } else { + if (duckChance) { + if (!Q_irand(0, duckChance)) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); + if (evasionType == EVASION_PARRY) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_DUCK; } /* @@ -2337,29 +1816,25 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } - if ( incoming ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (incoming) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } - } - //if ( self->client->ps.saberBlocked != BLOCKED_NONE ) + // if ( self->client->ps.saberBlocked != BLOCKED_NONE ) { - int parryReCalcTime = Jedi_ReCalcParryTime( self, evasionType ); - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + int parryReCalcTime = Jedi_ReCalcParryTime(self, evasionType); + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } } return evasionType; } -extern int WPDEBUG_SaberColor( saber_colors_t saberColor ); -static qboolean Jedi_SaberBlock( void ) -{ - vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir;//saberBase, +extern int WPDEBUG_SaberColor(saber_colors_t saberColor); +static qboolean Jedi_SaberBlock(void) { + vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir; // saberBase, - //FIXME: reborn don't block enough anymore + // FIXME: reborn don't block enough anymore /* //maybe do this on easy only... or only on grunt-level reborn if ( NPC->client->ps.weaponTime ) @@ -2368,13 +1843,11 @@ static qboolean Jedi_SaberBlock( void ) } */ - if ( !TIMER_Done( NPC, "parryReCalcTime" ) ) - {//can't do our own re-think of which parry to use yet + if (!TIMER_Done(NPC, "parryReCalcTime")) { // can't do our own re-think of which parry to use yet return qfalse; } - if ( NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't move the saber to another position yet + if (NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time) { // can't move the saber to another position yet return qfalse; } @@ -2386,14 +1859,13 @@ static qboolean Jedi_SaberBlock( void ) } */ - if ( NPC->enemy->health <= 0 || !NPC->enemy->client ) - {//don't keep blocking him once he's dead (or if not a client) + if (NPC->enemy->health <= 0 || !NPC->enemy->client) { // don't keep blocking him once he's dead (or if not a client) return qfalse; } /* //VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); - //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext ); - VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); + //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext + ); VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); VectorSubtract( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->renderInfo.muzzlePointOld, dir );//get the dir @@ -2432,21 +1904,20 @@ static qboolean Jedi_SaberBlock( void ) VectorCopy( tr.endpos, hitloc ); } */ - vec3_t pointDir, baseDir, tipDir, saberHitPoint, saberMins={-4,-4,-4}, saberMaxs={4,4,4}; - float pointDist, baseDirPerc; - VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); - VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); - VectorCopy( NPC->currentOrigin, top ); + vec3_t pointDir, baseDir, tipDir, saberHitPoint, saberMins = {-4, -4, -4}, saberMaxs = {4, 4, 4}; + float pointDist, baseDirPerc; + VectorMA(NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld); + VectorMA(NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip); + VectorCopy(NPC->currentOrigin, top); top[2] = NPC->absmax[2]; - VectorCopy( NPC->currentOrigin, bottom ); + VectorCopy(NPC->currentOrigin, bottom); bottom[2] = NPC->absmin[2]; - float dist = ShortestLineSegBewteen2LineSegs( NPC->enemy->client->renderInfo.muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint ); - if ( dist > NPC->maxs[0]*5 )//was *3 - {//FIXME: sometimes he reacts when you're too far away to actually hit him - if ( d_JediAI->integer ) - { - gi.Printf( S_COLOR_RED"enemy saber dist: %4.2f\n", dist ); + float dist = ShortestLineSegBewteen2LineSegs(NPC->enemy->client->renderInfo.muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint); + if (dist > NPC->maxs[0] * 5) // was *3 + { // FIXME: sometimes he reacts when you're too far away to actually hit him + if (d_JediAI->integer) { + gi.Printf(S_COLOR_RED "enemy saber dist: %4.2f\n", dist); } /* if ( dist < 300 //close @@ -2457,43 +1928,35 @@ static qboolean Jedi_SaberBlock( void ) } else */ - { - TIMER_Set( NPC, "parryTime", -1 ); - } + { TIMER_Set(NPC, "parryTime", -1); } return qfalse; } - if ( d_JediAI->integer ) - { - gi.Printf( S_COLOR_GREEN"enemy saber dist: %4.2f\n", dist ); + if (d_JediAI->integer) { + gi.Printf(S_COLOR_GREEN "enemy saber dist: %4.2f\n", dist); } - VectorSubtract( saberPoint, NPC->enemy->client->renderInfo.muzzlePoint, pointDir ); - pointDist = VectorLength( pointDir ); + VectorSubtract(saberPoint, NPC->enemy->client->renderInfo.muzzlePoint, pointDir); + pointDist = VectorLength(pointDir); - if ( NPC->enemy->client->ps.saberLength <= 0 ) - { + if (NPC->enemy->client->ps.saberLength <= 0) { baseDirPerc = 0.5f; - } - else - { - baseDirPerc = pointDist/NPC->enemy->client->ps.saberLength; - } - VectorSubtract( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->renderInfo.muzzlePointOld, baseDir ); - VectorSubtract( saberTip, saberTipOld, tipDir ); - VectorScale( baseDir, baseDirPerc, baseDir ); - VectorMA( baseDir, 1.0f-baseDirPerc, tipDir, dir ); - VectorMA( saberPoint, 200, dir, hitloc ); - - //get the actual point of impact - trace_t tr; - gi.trace( &tr, saberPoint, saberMins, saberMaxs, hitloc, NPC->enemy->s.number, CONTENTS_BODY, G2_NOCOLLIDE, 0 );//, G2_RETURNONHIT, 10 ); - if ( tr.allsolid || tr.startsolid || tr.fraction >= 1.0f ) - {//estimate - vec3_t dir2Me; - VectorSubtract( axisPoint, saberPoint, dir2Me ); - dist = VectorNormalize( dir2Me ); - if ( DotProduct( dir, dir2Me ) < 0.2f ) - {//saber is not swinging in my direction + } else { + baseDirPerc = pointDist / NPC->enemy->client->ps.saberLength; + } + VectorSubtract(NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->renderInfo.muzzlePointOld, baseDir); + VectorSubtract(saberTip, saberTipOld, tipDir); + VectorScale(baseDir, baseDirPerc, baseDir); + VectorMA(baseDir, 1.0f - baseDirPerc, tipDir, dir); + VectorMA(saberPoint, 200, dir, hitloc); + + // get the actual point of impact + trace_t tr; + gi.trace(&tr, saberPoint, saberMins, saberMaxs, hitloc, NPC->enemy->s.number, CONTENTS_BODY, G2_NOCOLLIDE, 0); //, G2_RETURNONHIT, 10 ); + if (tr.allsolid || tr.startsolid || tr.fraction >= 1.0f) { // estimate + vec3_t dir2Me; + VectorSubtract(axisPoint, saberPoint, dir2Me); + dist = VectorNormalize(dir2Me); + if (DotProduct(dir, dir2Me) < 0.2f) { // saber is not swinging in my direction /* if ( dist < 300 //close && !Jedi_QuickReactions( NPC )//quick reaction people can interrupt themselves @@ -2503,72 +1966,55 @@ static qboolean Jedi_SaberBlock( void ) } else */ - { - TIMER_Set( NPC, "parryTime", -1 ); - } + { TIMER_Set(NPC, "parryTime", -1); } return qfalse; } - ShortestLineSegBewteen2LineSegs( saberPoint, hitloc, bottom, top, saberHitPoint, hitloc ); + ShortestLineSegBewteen2LineSegs(saberPoint, hitloc, bottom, top, saberHitPoint, hitloc); /* VectorSubtract( saberPoint, axisPoint, dir ); VectorNormalize( dir ); VectorMA( axisPoint, NPC->maxs[0]*1.22, dir, hitloc ); */ - } - else - { - VectorCopy( tr.endpos, hitloc ); + } else { + VectorCopy(tr.endpos, hitloc); } - if ( d_JediAI->integer ) - { - G_DebugLine( saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor( NPC->enemy->client->ps.saberColor ), qtrue ); + if (d_JediAI->integer) { + G_DebugLine(saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor(NPC->enemy->client->ps.saberColor), qtrue); } - //FIXME: if saber is off and/or we have force speed and want to be really cocky, + // FIXME: if saber is off and/or we have force speed and want to be really cocky, // and the swing misses by some amount, we can use the dodges here... :) - evasionType_t evasionType; - if ( (evasionType=Jedi_SaberBlockGo( NPC, &ucmd, hitloc, dir, NULL, dist )) != EVASION_DODGE ) - {//we did block (not dodge) - if ( !NPC->client->ps.saberInFlight ) - {//make sure saber is on + evasionType_t evasionType; + if ((evasionType = Jedi_SaberBlockGo(NPC, &ucmd, hitloc, dir, NULL, dist)) != EVASION_DODGE) { // we did block (not dodge) + if (!NPC->client->ps.saberInFlight) { // make sure saber is on NPC->client->ps.saberActive = qtrue; } - //debounce our parry recalc time - int parryReCalcTime = Jedi_ReCalcParryTime( NPC, evasionType ); - TIMER_Set( NPC, "parryReCalcTime", Q_irand( 0, parryReCalcTime ) ); - if ( d_JediAI->integer ) - { - gi.Printf( "Keep parry choice until: %d\n", level.time + parryReCalcTime ); + // debounce our parry recalc time + int parryReCalcTime = Jedi_ReCalcParryTime(NPC, evasionType); + TIMER_Set(NPC, "parryReCalcTime", Q_irand(0, parryReCalcTime)); + if (d_JediAI->integer) { + gi.Printf("Keep parry choice until: %d\n", level.time + parryReCalcTime); } - //determine how long to hold this anim - if ( TIMER_Done( NPC, "parryTime" ) ) - { - if ( NPC->client->NPC_class == CLASS_TAVION ) - { - TIMER_Set( NPC, "parryTime", Q_irand( parryReCalcTime/2, parryReCalcTime*1.5 ) ); - } - else if ( NPCInfo->rank >= RANK_LT_JG ) - {//fencers and higher hold a parry less - TIMER_Set( NPC, "parryTime", parryReCalcTime ); - } - else - {//others hold it longer - TIMER_Set( NPC, "parryTime", Q_irand( 1, 2 )*parryReCalcTime ); + // determine how long to hold this anim + if (TIMER_Done(NPC, "parryTime")) { + if (NPC->client->NPC_class == CLASS_TAVION) { + TIMER_Set(NPC, "parryTime", Q_irand(parryReCalcTime / 2, parryReCalcTime * 1.5)); + } else if (NPCInfo->rank >= RANK_LT_JG) { // fencers and higher hold a parry less + TIMER_Set(NPC, "parryTime", parryReCalcTime); + } else { // others hold it longer + TIMER_Set(NPC, "parryTime", Q_irand(1, 2) * parryReCalcTime); } } - } - else - { + } else { int dodgeTime = NPC->client->ps.torsoAnimTimer; - if ( NPCInfo->rank > RANK_LT_COMM && NPC->client->NPC_class != CLASS_DESANN ) - {//higher-level guys can dodge faster + if (NPCInfo->rank > RANK_LT_COMM && NPC->client->NPC_class != CLASS_DESANN) { // higher-level guys can dodge faster dodgeTime -= 200; } - TIMER_Set( NPC, "parryReCalcTime", dodgeTime ); - TIMER_Set( NPC, "parryTime", dodgeTime ); + TIMER_Set(NPC, "parryReCalcTime", dodgeTime); + TIMER_Set(NPC, "parryTime", dodgeTime); } return qtrue; } @@ -2579,191 +2025,145 @@ Jedi_EvasionSaber defend if other is using saber and attacking me! ------------------------- */ -static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir ) -{ - vec3_t dirEnemy2Me; - int evasionChance = 30;//only step aside 30% if he's moving at me but not attacking - qboolean enemy_attacking = qfalse; - qboolean throwing_saber = qfalse; - qboolean shooting_lightning = qfalse; - - if ( !NPC->enemy->client ) - { +static void Jedi_EvasionSaber(vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir) { + vec3_t dirEnemy2Me; + int evasionChance = 30; // only step aside 30% if he's moving at me but not attacking + qboolean enemy_attacking = qfalse; + qboolean throwing_saber = qfalse; + qboolean shooting_lightning = qfalse; + + if (!NPC->enemy->client) { return; - } - else if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time ) - {//don't try to block/evade an enemy who is in a saberLock + } else if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->client->ps.saberLockTime > level.time) { // don't try to block/evade an enemy who is in a saberLock return; - } - else if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON && NPC->enemy->painDebounceTime > level.time ) - {//pressing the advantage of winning a saber lock + } else if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON && NPC->enemy->painDebounceTime > level.time) { // pressing the advantage of winning a saber lock return; } - if ( NPC->enemy->client->ps.saberInFlight && !TIMER_Done( NPC, "taunting" ) ) - {//if he's throwing his saber, stop taunting - TIMER_Set( NPC, "taunting", -level.time ); - if ( !NPC->client->ps.saberInFlight ) - { + if (NPC->enemy->client->ps.saberInFlight && !TIMER_Done(NPC, "taunting")) { // if he's throwing his saber, stop taunting + TIMER_Set(NPC, "taunting", -level.time); + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.saberActive = qtrue; } } - if ( TIMER_Done( NPC, "parryTime" ) ) - { - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + if (TIMER_Done(NPC, "parryTime")) { + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - { - if ( !NPC->client->ps.saberInFlight && Jedi_SaberBlock() ) - { + if (NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { + if (!NPC->client->ps.saberInFlight && Jedi_SaberBlock()) { return; } } - VectorSubtract( NPC->currentOrigin, NPC->enemy->currentOrigin, dirEnemy2Me ); - VectorNormalize( dirEnemy2Me ); + VectorSubtract(NPC->currentOrigin, NPC->enemy->currentOrigin, dirEnemy2Me); + VectorNormalize(dirEnemy2Me); - if ( NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - {//enemy is attacking + if (NPC->enemy->client->ps.weaponTime && NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { // enemy is attacking enemy_attacking = qtrue; evasionChance = 90; } - if ( (NPC->enemy->client->ps.forcePowersActive&(1<enemy->client->ps.forcePowersActive & (1 << FP_LIGHTNING))) { // enemy is shooting lightning enemy_attacking = qtrue; shooting_lightning = qtrue; evasionChance = 50; } - if ( NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE && NPC->enemy->client->ps.saberEntityState != SES_RETURNING ) - {//enemy is shooting lightning + if (NPC->enemy->client->ps.saberInFlight && NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE && + NPC->enemy->client->ps.saberEntityState != SES_RETURNING) { // enemy is shooting lightning enemy_attacking = qtrue; throwing_saber = qtrue; } - //FIXME: this needs to take skill and rank(reborn type) into account much more - if ( Q_irand( 0, 100 ) < evasionChance ) - {//check to see if he's coming at me + // FIXME: this needs to take skill and rank(reborn type) into account much more + if (Q_irand(0, 100) < evasionChance) { // check to see if he's coming at me float facingAmt; - if ( VectorCompare( enemy_movedir, vec3_origin ) || shooting_lightning || throwing_saber ) - {//he's not moving (or he's using a ranged attack), see if he's facing me - vec3_t enemy_fwd; - AngleVectors( NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL ); - facingAmt = DotProduct( enemy_fwd, dirEnemy2Me ); - } - else - {//he's moving - facingAmt = DotProduct( enemy_movedir, dirEnemy2Me ); + if (VectorCompare(enemy_movedir, vec3_origin) || shooting_lightning || + throwing_saber) { // he's not moving (or he's using a ranged attack), see if he's facing me + vec3_t enemy_fwd; + AngleVectors(NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL); + facingAmt = DotProduct(enemy_fwd, dirEnemy2Me); + } else { // he's moving + facingAmt = DotProduct(enemy_movedir, dirEnemy2Me); } - if ( Q_flrand( 0.25, 1 ) < facingAmt ) - {//coming at/facing me! + if (Q_flrand(0.25, 1) < facingAmt) { // coming at/facing me! int whichDefense = 0; - if ( NPC->client->ps.weaponTime || NPC->client->ps.saberInFlight ) - {//I'm attacking or recovering from a parry, can only try to strafe/jump right now - if ( Q_irand( 0, 10 ) < NPCInfo->stats.aggression ) - { + if (NPC->client->ps.weaponTime || NPC->client->ps.saberInFlight) { // I'm attacking or recovering from a parry, can only try to strafe/jump right + // now + if (Q_irand(0, 10) < NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - { - if ( shooting_lightning ) - {//check for lightning attack - //only valid defense is strafe and/or jump + } else { + if (shooting_lightning) { // check for lightning attack + // only valid defense is strafe and/or jump whichDefense = 100; - } - else if ( throwing_saber ) - {//he's thrown his saber! See if it's coming at me - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (throwing_saber) { // he's thrown his saber! See if it's coming at me + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[NPC->enemy->client->ps.saberEntityNum]; - VectorSubtract( NPC->currentOrigin, saber->currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( !Q_irand( 0, 3 ) ) - { - //Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); - Jedi_Aggression( NPC, 1 ); + VectorSubtract(NPC->currentOrigin, saber->currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (!Q_irand(0, 3)) { + // Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); + Jedi_Aggression(NPC, 1); } - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 100 ) - {//it's close - whichDefense = Q_irand( 3, 6 ); - } - else if ( saberDist < 200 ) - {//got some time, yet, try pushing - whichDefense = Q_irand( 0, 8 ); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 100) { // it's close + whichDefense = Q_irand(3, 6); + } else if (saberDist < 200) { // got some time, yet, try pushing + whichDefense = Q_irand(0, 8); } } } - if ( whichDefense ) - {//already chose one - } - else if ( enemy_dist > 80 || !enemy_attacking ) - {//he's pretty far, or not swinging, just strafe - if ( VectorCompare( enemy_movedir, vec3_origin ) ) - {//if he's not moving, not swinging and far enough away, no evasion necc. + if (whichDefense) { // already chose one + } else if (enemy_dist > 80 || !enemy_attacking) { // he's pretty far, or not swinging, just strafe + if (VectorCompare(enemy_movedir, vec3_origin)) { // if he's not moving, not swinging and far enough away, no evasion necc. return; } - if ( Q_irand( 0, 10 ) < NPCInfo->stats.aggression ) - { + if (Q_irand(0, 10) < NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - {//he's getting close and swinging at me - vec3_t fwd; - //see if I'm facing him - AngleVectors( NPC->client->ps.viewangles, fwd, NULL, NULL ); - if ( DotProduct( enemy_dir, fwd ) < 0.5 ) - {//I'm not really facing him, best option is to strafe - whichDefense = Q_irand( 5, 16 ); - } - else if ( enemy_dist < 56 ) - {//he's very close, maybe we should be more inclined to block or throw - whichDefense = Q_irand( NPCInfo->stats.aggression, 12 ); - } - else - { - whichDefense = Q_irand( 2, 16 ); + } else { // he's getting close and swinging at me + vec3_t fwd; + // see if I'm facing him + AngleVectors(NPC->client->ps.viewangles, fwd, NULL, NULL); + if (DotProduct(enemy_dir, fwd) < 0.5) { // I'm not really facing him, best option is to strafe + whichDefense = Q_irand(5, 16); + } else if (enemy_dist < 56) { // he's very close, maybe we should be more inclined to block or throw + whichDefense = Q_irand(NPCInfo->stats.aggression, 12); + } else { + whichDefense = Q_irand(2, 16); } } } - if ( whichDefense >= 4 && whichDefense <= 12 ) - {//would try to block - if ( NPC->client->ps.saberInFlight ) - {//can't, saber in not in hand, so fall back to strafe/jump + if (whichDefense >= 4 && whichDefense <= 12) { // would try to block + if (NPC->client->ps.saberInFlight) { // can't, saber in not in hand, so fall back to strafe/jump whichDefense = 100; } } - switch( whichDefense ) - { + switch (whichDefense) { case 0: case 1: case 2: case 3: - //use jedi force push? - //FIXME: try to do this if health low or enemy back to a cliff? - if ( (NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && TIMER_Done( NPC, "parryTime" ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qfalse ); + // use jedi force push? + // FIXME: try to do this if health low or enemy back to a cliff? + if ((NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && + TIMER_Done(NPC, "parryTime")) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qfalse); } break; case 4: @@ -2775,83 +2175,64 @@ static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t en case 10: case 11: case 12: - //try to parry the blow - //gi.Printf( "blocking\n" ); + // try to parry the blow + // gi.Printf( "blocking\n" ); Jedi_SaberBlock(); break; default: - //Evade! - //start a strafe left/right if not already - if ( !Q_irand( 0, 5 ) || !Jedi_Strafe( 300, 1000, 0, 1000, qfalse ) ) - {//certain chance they will pick an alternative evasion - //if couldn't strafe, try a different kind of evasion... - if ( shooting_lightning || throwing_saber || enemy_dist < 80 ) - { - //FIXME: force-jump+forward - jump over the guy! - if ( shooting_lightning || (!Q_irand( 0, 2 ) && NPCInfo->stats.aggression < 4 && TIMER_Done( NPC, "parryTime" ) ) ) - { - if ( (NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && Q_irand( 0, 2 ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( NPC, qfalse ); - } - else if ( (NPCInfo->rank==RANK_CREWMAN||NPCInfo->rank>RANK_LT_JG) - && !(NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && !PM_InKnockDown( &NPC->client->ps ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? + // Evade! + // start a strafe left/right if not already + if (!Q_irand(0, 5) || !Jedi_Strafe(300, 1000, 0, 1000, qfalse)) { // certain chance they will pick an alternative evasion + // if couldn't strafe, try a different kind of evasion... + if (shooting_lightning || throwing_saber || enemy_dist < 80) { + // FIXME: force-jump+forward - jump over the guy! + if (shooting_lightning || (!Q_irand(0, 2) && NPCInfo->stats.aggression < 4 && TIMER_Done(NPC, "parryTime"))) { + if ((NPCInfo->rank == RANK_ENSIGN || NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && + Q_irand(0, 2)) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(NPC, qfalse); + } else if ((NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG) && !(NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && + !PM_InKnockDown(&NPC->client->ps)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? NPC->client->ps.forceJumpCharge = 480; - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); - if ( Q_irand( 0, 2 ) ) - { + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); + if (Q_irand(0, 2)) { ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else - { + VectorClear(NPC->client->ps.moveDir); + } else { ucmd.forwardmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //FIXME: if this jump is cleared, we can't block... so pick a random lower block? - if ( Q_irand( 0, 1 ) )//FIXME: make intelligent + // FIXME: if this jump is cleared, we can't block... so pick a random lower block? + if (Q_irand(0, 1)) // FIXME: make intelligent { NPC->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { NPC->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - } - else if ( enemy_attacking ) - { + } else if (enemy_attacking) { Jedi_SaberBlock(); } } - } - else - {//strafed - if ( d_JediAI->integer ) - { - gi.Printf( "def strafe\n" ); + } else { // strafed + if (d_JediAI->integer) { + gi.Printf("def strafe\n"); } - if ( !(NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && (NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) - && !PM_InKnockDown( &NPC->client->ps ) - && !Q_irand( 0, 5 ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? + if (!(NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && (NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG) && + !PM_InKnockDown(&NPC->client->ps) && !Q_irand(0, 5)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? NPC->client->ps.forceJumpCharge = 320; - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); } } break; } - //turn off slow walking no matter what - TIMER_Set( NPC, "walking", -level.time ); - TIMER_Set( NPC, "taunting", -level.time ); + // turn off slow walking no matter what + TIMER_Set(NPC, "walking", -level.time); + TIMER_Set(NPC, "taunting", -level.time); } } } @@ -2868,82 +2249,68 @@ static qboolean Jedi_Flee( void ) } */ - /* ========================================================================================== INTERNAL AI ROUTINES ========================================================================================== */ -gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float minDot ) -{ +gentity_t *Jedi_FindEnemyInCone(gentity_t *self, gentity_t *fallback, float minDot) { vec3_t forward, mins, maxs, dir; - float dist, bestDist = Q3_INFINITE; - gentity_t *enemy = fallback; - gentity_t *check = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int e, numListedEntities; - trace_t tr; - - if ( !self->client ) - { + float dist, bestDist = Q3_INFINITE; + gentity_t *enemy = fallback; + gentity_t *check = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int e, numListedEntities; + trace_t tr; + + if (!self->client) { return enemy; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); - for ( e = 0 ; e < 3 ; e++ ) - { + for (e = 0; e < 3; e++) { mins[e] = self->currentOrigin[e] - 1024; maxs[e] = self->currentOrigin[e] + 1024; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { check = entityList[e]; - if ( check == self ) - {//me + if (check == self) { // me continue; } - if ( !(check->inuse) ) - {//freed + if (!(check->inuse)) { // freed continue; } - if ( !check->client ) - {//not a client - FIXME: what about turrets? + if (!check->client) { // not a client - FIXME: what about turrets? continue; } - if ( check->client->playerTeam != self->client->enemyTeam ) - {//not an enemy - FIXME: what about turrets? + if (check->client->playerTeam != self->client->enemyTeam) { // not an enemy - FIXME: what about turrets? continue; } - if ( check->health <= 0 ) - {//dead + if (check->health <= 0) { // dead continue; } - if ( !gi.inPVS( check->currentOrigin, self->currentOrigin ) ) - {//can't potentially see them + if (!gi.inPVS(check->currentOrigin, self->currentOrigin)) { // can't potentially see them continue; } - VectorSubtract( check->currentOrigin, self->currentOrigin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(check->currentOrigin, self->currentOrigin, dir); + dist = VectorNormalize(dir); - if ( DotProduct( dir, forward ) < minDot ) - {//not in front + if (DotProduct(dir, forward) < minDot) { // not in front continue; } - //really should have a clear LOS to this thing... - gi.trace( &tr, self->currentOrigin, vec3_origin, vec3_origin, check->currentOrigin, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != check->s.number ) - {//must have clear shot + // really should have a clear LOS to this thing... + gi.trace(&tr, self->currentOrigin, vec3_origin, vec3_origin, check->currentOrigin, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.fraction < 1.0f && tr.entityNum != check->s.number) { // must have clear shot continue; } - if ( dist < bestDist ) - {//closer than our last best one + if (dist < bestDist) { // closer than our last best one dist = bestDist; enemy = check; } @@ -2951,31 +2318,26 @@ gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float min return enemy; } -static void Jedi_SetEnemyInfo( vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction ) -{ - if ( !NPC || !NPC->enemy ) - {//no valid enemy +static void Jedi_SetEnemyInfo(vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction) { + if (!NPC || !NPC->enemy) { // no valid enemy return; } - if ( !NPC->enemy->client ) - { - VectorClear( enemy_movedir ); + if (!NPC->enemy->client) { + VectorClear(enemy_movedir); *enemy_movespeed = 0; - VectorCopy( NPC->enemy->currentOrigin, enemy_dest ); - enemy_dest[2] += NPC->enemy->mins[2] + 24;//get it's origin to a height I can work with - VectorSubtract( enemy_dest, NPC->currentOrigin, enemy_dir ); - *enemy_dist = VectorNormalize( enemy_dir );// - (NPC->client->ps.saberLengthMax + NPC->maxs[0]*1.5 + 16); - } - else - {//see where enemy is headed - VectorCopy( NPC->enemy->client->ps.velocity, enemy_movedir ); - *enemy_movespeed = VectorNormalize( enemy_movedir ); - //figure out where he'll be, say, 3 frames from now - VectorMA( NPC->enemy->currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest ); - //figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is - VectorSubtract( enemy_dest, NPC->currentOrigin, enemy_dir );//NPC->client->renderInfo.muzzlePoint - *enemy_dist = VectorNormalize( enemy_dir ) - (NPC->client->ps.saberLengthMax + NPC->maxs[0]*1.5 + 16); - //FIXME: keep a group of enemies around me and use that info to make decisions... + VectorCopy(NPC->enemy->currentOrigin, enemy_dest); + enemy_dest[2] += NPC->enemy->mins[2] + 24; // get it's origin to a height I can work with + VectorSubtract(enemy_dest, NPC->currentOrigin, enemy_dir); + *enemy_dist = VectorNormalize(enemy_dir); // - (NPC->client->ps.saberLengthMax + NPC->maxs[0]*1.5 + 16); + } else { // see where enemy is headed + VectorCopy(NPC->enemy->client->ps.velocity, enemy_movedir); + *enemy_movespeed = VectorNormalize(enemy_movedir); + // figure out where he'll be, say, 3 frames from now + VectorMA(NPC->enemy->currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest); + // figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is + VectorSubtract(enemy_dest, NPC->currentOrigin, enemy_dir); // NPC->client->renderInfo.muzzlePoint + *enemy_dist = VectorNormalize(enemy_dir) - (NPC->client->ps.saberLengthMax + NPC->maxs[0] * 1.5 + 16); + // FIXME: keep a group of enemies around me and use that info to make decisions... // For instance, if there are multiple enemies, evade more, push them away // and use medium attacks. If enemies are using blasters, switch to fast. // If one jedi enemy, use strong attacks. Use grip when fighting one or @@ -2984,42 +2346,33 @@ static void Jedi_SetEnemyInfo( vec3_t enemy_dest, vec3_t enemy_dir, float *enemy } } -static void Jedi_FaceEnemy( qboolean doPitch ) -{ - vec3_t enemy_eyes, eyes, angles; +static void Jedi_FaceEnemy(qboolean doPitch) { + vec3_t enemy_eyes, eyes, angles; - if ( NPC == NULL ) + if (NPC == NULL) return; - if ( NPC->enemy == NULL ) + if (NPC->enemy == NULL) return; - if ( NPC->client->ps.forcePowersActive & (1<client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//don't update? + if (NPC->client->ps.forcePowersActive & (1 << FP_GRIP) && NPC->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // don't update? NPCInfo->desiredPitch = NPC->client->ps.viewangles[PITCH]; NPCInfo->desiredYaw = NPC->client->ps.viewangles[YAW]; return; } - CalcEntitySpot( NPC, SPOT_HEAD, eyes ); + CalcEntitySpot(NPC, SPOT_HEAD, eyes); - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_eyes ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_eyes); - //Find the desired angles - if ( !NPC->client->ps.saberInFlight - && (NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 - || NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 - || NPC->client->ps.legsAnim == BOTH_ATTACK_BACK) - ) - {//point *away* - GetAnglesForDirection( enemy_eyes, eyes, angles ); - } - else - {//point towards him - GetAnglesForDirection( eyes, enemy_eyes, angles ); + // Find the desired angles + if (!NPC->client->ps.saberInFlight && (NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 || NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 || + NPC->client->ps.legsAnim == BOTH_ATTACK_BACK)) { // point *away* + GetAnglesForDirection(enemy_eyes, eyes, angles); + } else { // point towards him + GetAnglesForDirection(eyes, enemy_eyes, angles); } - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); /* if ( NPC->client->ps.saberBlocked == BLOCKED_UPPER_LEFT ) {//temp hack- to make up for poor coverage on left side @@ -3027,223 +2380,156 @@ static void Jedi_FaceEnemy( qboolean doPitch ) } */ - if ( doPitch ) - { - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); - if ( NPC->client->ps.saberInFlight ) - {//tilt down a little + if (doPitch) { + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); + if (NPC->client->ps.saberInFlight) { // tilt down a little NPCInfo->desiredPitch += 10; } } - //FIXME: else desiredPitch = 0? Or keep previous? + // FIXME: else desiredPitch = 0? Or keep previous? } -static void Jedi_DebounceDirectionChanges( void ) -{ - //FIXME: check these before making fwd/back & right/left decisions? - //Time-debounce changes in forward/back dir - if ( ucmd.forwardmove > 0 ) - { - if ( !TIMER_Done( NPC, "moveback" ) || !TIMER_Done( NPC, "movenone" ) ) - { +static void Jedi_DebounceDirectionChanges(void) { + // FIXME: check these before making fwd/back & right/left decisions? + // Time-debounce changes in forward/back dir + if (ucmd.forwardmove > 0) { + if (!TIMER_Done(NPC, "moveback") || !TIMER_Done(NPC, "movenone")) { ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.rightmove > 0) { ucmd.rightmove = 127; - } - else if ( ucmd.rightmove < 0 ) - { + } else if (ucmd.rightmove < 0) { ucmd.rightmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveback", -level.time ); - if ( TIMER_Done( NPC, "movenone" ) ) - { - TIMER_Set( NPC, "movenone", Q_irand( 1000, 2000 ) ); + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveback", -level.time); + if (TIMER_Done(NPC, "movenone")) { + TIMER_Set(NPC, "movenone", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPC, "moveforward")) { // FIXME: should be if it's zero? + TIMER_Set(NPC, "moveforward", Q_irand(500, 2000)); } - else if ( TIMER_Done( NPC, "moveforward" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPC, "moveforward", Q_irand( 500, 2000 ) ); - } - } - else if ( ucmd.forwardmove < 0 ) - { - if ( !TIMER_Done( NPC, "moveforward" ) || !TIMER_Done( NPC, "movenone" ) ) - { + } else if (ucmd.forwardmove < 0) { + if (!TIMER_Done(NPC, "moveforward") || !TIMER_Done(NPC, "movenone")) { ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.rightmove > 0) { ucmd.rightmove = 127; - } - else if ( ucmd.rightmove < 0 ) - { + } else if (ucmd.rightmove < 0) { ucmd.rightmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveforward", -level.time ); - if ( TIMER_Done( NPC, "movenone" ) ) - { - TIMER_Set( NPC, "movenone", Q_irand( 1000, 2000 ) ); + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveforward", -level.time); + if (TIMER_Done(NPC, "movenone")) { + TIMER_Set(NPC, "movenone", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPC, "moveback")) { // FIXME: should be if it's zero? + TIMER_Set(NPC, "moveback", Q_irand(250, 1000)); } - else if ( TIMER_Done( NPC, "moveback" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPC, "moveback", Q_irand( 250, 1000 ) ); - } - } - else if ( !TIMER_Done( NPC, "moveforward" ) ) - {//NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? + } else if (!TIMER_Done(NPC, "moveforward")) { // NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPC, "moveback" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPC, "moveback")) { // NOTE: edge checking should stop me if this is bad... ucmd.forwardmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //Time-debounce changes in right/left dir - if ( ucmd.rightmove > 0 ) - { - if ( !TIMER_Done( NPC, "moveleft" ) || !TIMER_Done( NPC, "movecenter" ) ) - { + // Time-debounce changes in right/left dir + if (ucmd.rightmove > 0) { + if (!TIMER_Done(NPC, "moveleft") || !TIMER_Done(NPC, "movecenter")) { ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.forwardmove > 0) { ucmd.forwardmove = 127; - } - else if ( ucmd.forwardmove < 0 ) - { + } else if (ucmd.forwardmove < 0) { ucmd.forwardmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveleft", -level.time ); - if ( TIMER_Done( NPC, "movecenter" ) ) - { - TIMER_Set( NPC, "movecenter", Q_irand( 1000, 2000 ) ); + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveleft", -level.time); + if (TIMER_Done(NPC, "movecenter")) { + TIMER_Set(NPC, "movecenter", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPC, "moveright")) { // FIXME: should be if it's zero? + TIMER_Set(NPC, "moveright", Q_irand(250, 1500)); } - else if ( TIMER_Done( NPC, "moveright" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPC, "moveright", Q_irand( 250, 1500 ) ); - } - } - else if ( ucmd.rightmove < 0 ) - { - if ( !TIMER_Done( NPC, "moveright" ) || !TIMER_Done( NPC, "movecenter" ) ) - { + } else if (ucmd.rightmove < 0) { + if (!TIMER_Done(NPC, "moveright") || !TIMER_Done(NPC, "movecenter")) { ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (ucmd.forwardmove > 0) { ucmd.forwardmove = 127; - } - else if ( ucmd.forwardmove < 0 ) - { + } else if (ucmd.forwardmove < 0) { ucmd.forwardmove = -127; } - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "moveright", -level.time ); - if ( TIMER_Done( NPC, "movecenter" ) ) - { - TIMER_Set( NPC, "movecenter", Q_irand( 1000, 2000 ) ); + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "moveright", -level.time); + if (TIMER_Done(NPC, "movecenter")) { + TIMER_Set(NPC, "movecenter", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPC, "moveleft")) { // FIXME: should be if it's zero? + TIMER_Set(NPC, "moveleft", Q_irand(250, 1500)); } - else if ( TIMER_Done( NPC, "moveleft" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPC, "moveleft", Q_irand( 250, 1500 ) ); - } - } - else if ( !TIMER_Done( NPC, "moveright" ) ) - {//NOTE: edge checking should stop me if this is bad... + } else if (!TIMER_Done(NPC, "moveright")) { // NOTE: edge checking should stop me if this is bad... ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPC, "moveleft" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPC, "moveleft")) { // NOTE: edge checking should stop me if this is bad... ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } -static void Jedi_TimersApply( void ) -{ - if ( !ucmd.rightmove ) - {//only if not already strafing - //FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too - if ( !TIMER_Done( NPC, "strafeLeft" ) ) - { - if ( NPCInfo->desiredYaw > NPC->client->ps.viewangles[YAW] + 60 ) - {//we want to turn left, don't apply the strafing - } - else - {//go ahead and strafe left +static void Jedi_TimersApply(void) { + if (!ucmd.rightmove) { // only if not already strafing + // FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too + if (!TIMER_Done(NPC, "strafeLeft")) { + if (NPCInfo->desiredYaw > NPC->client->ps.viewangles[YAW] + 60) { // we want to turn left, don't apply the strafing + } else { // go ahead and strafe left ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); - } - } - else if ( !TIMER_Done( NPC, "strafeRight" ) ) - { - if ( NPCInfo->desiredYaw < NPC->client->ps.viewangles[YAW] - 60 ) - {//we want to turn right, don't apply the strafing + VectorClear(NPC->client->ps.moveDir); } - else - {//go ahead and strafe left + } else if (!TIMER_Done(NPC, "strafeRight")) { + if (NPCInfo->desiredYaw < NPC->client->ps.viewangles[YAW] - 60) { // we want to turn right, don't apply the strafing + } else { // go ahead and strafe left ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } } Jedi_DebounceDirectionChanges(); - //use careful anim/slower movement if not already moving - if ( !ucmd.forwardmove && !TIMER_Done( NPC, "walking" ) ) - { + // use careful anim/slower movement if not already moving + if (!ucmd.forwardmove && !TIMER_Done(NPC, "walking")) { ucmd.buttons |= (BUTTON_WALKING); } - if ( !TIMER_Done( NPC, "taunting" ) ) - { + if (!TIMER_Done(NPC, "taunting")) { ucmd.buttons |= (BUTTON_WALKING); } - if ( !TIMER_Done( NPC, "gripping" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (!TIMER_Done(NPC, "gripping")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around ucmd.buttons |= BUTTON_FORCEGRIP; } - if ( !TIMER_Done( NPC, "holdLightning" ) ) - {//hold down the lightning key + if (!TIMER_Done(NPC, "holdLightning")) { // hold down the lightning key ucmd.buttons |= BUTTON_FORCE_LIGHTNING; } } -static void Jedi_CombatTimersUpdate( int enemy_dist ) -{ - if ( TIMER_Done( NPC, "roamTime" ) ) - { - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - //okay, now mess with agression - if ( NPC->enemy && NPC->enemy->client ) - { - switch( NPC->enemy->client->ps.weapon ) - { +static void Jedi_CombatTimersUpdate(int enemy_dist) { + if (TIMER_Done(NPC, "roamTime")) { + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + // okay, now mess with agression + if (NPC->enemy && NPC->enemy->client) { + switch (NPC->enemy->client->ps.weapon) { case WP_SABER: - //If enemy has a lightsaber, always close in - if ( !NPC->enemy->client->ps.saberActive ) - {//fool! Standing around unarmed, charge! - //Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); - Jedi_Aggression( NPC, 2 ); - } - else - { - //Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // If enemy has a lightsaber, always close in + if (!NPC->enemy->client->ps.saberActive) { // fool! Standing around unarmed, charge! + // Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); + Jedi_Aggression(NPC, 2); + } else { + // Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); + Jedi_Aggression(NPC, 1); } break; case WP_BLASTER: @@ -3254,18 +2540,16 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) case WP_DEMP2: case WP_FLECHETTE: case WP_ROCKET_LAUNCHER: - //if he has a blaster, move in when: - //They're not shooting at me - if ( NPC->enemy->attackDebounceTime < level.time ) - {//does this apply to players? - //Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // if he has a blaster, move in when: + // They're not shooting at me + if (NPC->enemy->attackDebounceTime < level.time) { // does this apply to players? + // Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); + Jedi_Aggression(NPC, 1); } - //He's closer than a dist that gives us time to deflect - if ( enemy_dist < 256 ) - { - //Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); - Jedi_Aggression( NPC, 1 ); + // He's closer than a dist that gives us time to deflect + if (enemy_dist < 256) { + // Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); + Jedi_Aggression(NPC, 1); } break; default: @@ -3274,31 +2558,23 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } - if ( TIMER_Done( NPC, "noStrafe" ) && TIMER_Done( NPC, "strafeLeft" ) && TIMER_Done( NPC, "strafeRight" ) ) - { - //FIXME: Maybe more likely to do this if aggression higher? Or some other stat? - if ( !Q_irand( 0, 4 ) ) - {//start a strafe - if ( Jedi_Strafe( 1000, 3000, 0, 4000, qtrue ) ) - { - if ( d_JediAI->integer ) - { - gi.Printf( "off strafe\n" ); + if (TIMER_Done(NPC, "noStrafe") && TIMER_Done(NPC, "strafeLeft") && TIMER_Done(NPC, "strafeRight")) { + // FIXME: Maybe more likely to do this if aggression higher? Or some other stat? + if (!Q_irand(0, 4)) { // start a strafe + if (Jedi_Strafe(1000, 3000, 0, 4000, qtrue)) { + if (d_JediAI->integer) { + gi.Printf("off strafe\n"); } } - } - else - {//postpone any strafing for a while - TIMER_Set( NPC, "noStrafe", Q_irand( 1000, 3000 ) ); + } else { // postpone any strafing for a while + TIMER_Set(NPC, "noStrafe", Q_irand(1000, 3000)); } } - if ( NPC->client->ps.saberEventFlags ) - {//some kind of saber combat event is still pending + if (NPC->client->ps.saberEventFlags) { // some kind of saber combat event is still pending int newFlags = NPC->client->ps.saberEventFlags; - if ( NPC->client->ps.saberEventFlags&SEF_PARRIED ) - {//parried - TIMER_Set( NPC, "parryTime", -1 ); + if (NPC->client->ps.saberEventFlags & SEF_PARRIED) { // parried + TIMER_Set(NPC, "parryTime", -1); /* if ( NPCInfo->rank >= RANK_LT_JG ) { @@ -3309,113 +2585,87 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } */ - if ( NPC->enemy && (!NPC->enemy->client||PM_SaberInKnockaway( NPC->enemy->client->ps.saberMove )) ) - {//advance! - Jedi_Aggression( NPC, 1 );//get closer - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) );//use a faster attack - } - else - { - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (NPC->enemy && (!NPC->enemy->client || PM_SaberInKnockaway(NPC->enemy->client->ps.saberMove))) { // advance! + Jedi_Aggression(NPC, 1); // get closer + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); // use a faster attack + } else { + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we parried\n", level.time ); - Jedi_Aggression( NPC, -1 ); + // Com_Printf( "(%d) drop agg - we parried\n", level.time ); + Jedi_Aggression(NPC, -1); } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } } - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCInfo->stats.aggression, level.time + 100 ); + if (d_JediAI->integer) { + gi.Printf("(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCInfo->stats.aggression, level.time + 100); } newFlags &= ~SEF_PARRIED; } - if ( !NPC->client->ps.weaponTime && (NPC->client->ps.saberEventFlags&SEF_HITENEMY) )//hit enemy - {//we hit our enemy last time we swung, drop our aggression - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (!NPC->client->ps.weaponTime && (NPC->client->ps.saberEventFlags & SEF_HITENEMY)) // hit enemy + { // we hit our enemy last time we swung, drop our aggression + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); - Jedi_Aggression( NPC, -1 ); - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) HIT: agg %d\n", level.time, NPCInfo->stats.aggression ); + // Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); + Jedi_Aggression(NPC, -1); + if (d_JediAI->integer) { + gi.Printf("(%d) HIT: agg %d\n", level.time, NPCInfo->stats.aggression); } - if ( !Q_irand( 0, 3 ) - && NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time - && NPC->painDebounceTime < level.time - 1000 ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 3000 ); + if (!Q_irand(0, 3) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && + NPC->painDebounceTime < level.time - 1000) { + G_AddVoiceEvent(NPC, Q_irand(EV_GLOAT1, EV_GLOAT3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - if ( !Q_irand( 0, 2 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) ); + if (!Q_irand(0, 2)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); } newFlags &= ~SEF_HITENEMY; } - if ( (NPC->client->ps.saberEventFlags&SEF_BLOCKED) ) - {//was blocked whilst attacking - if ( PM_SaberInBrokenParry( NPC->client->ps.saberMove ) - || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { - //Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); - if ( NPC->client->ps.saberInFlight ) - {//lost our saber, too!!! - Jedi_Aggression( NPC, -5 );//really really really should back off!!! - } - else - { - Jedi_Aggression( NPC, -2 );//really should back off! + if ((NPC->client->ps.saberEventFlags & SEF_BLOCKED)) { // was blocked whilst attacking + if (PM_SaberInBrokenParry(NPC->client->ps.saberMove) || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { + // Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); + if (NPC->client->ps.saberInFlight) { // lost our saber, too!!! + Jedi_Aggression(NPC, -5); // really really really should back off!!! + } else { + Jedi_Aggression(NPC, -2); // really should back off! } - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) );//use a stronger attack - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression ); + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); // use a stronger attack + if (d_JediAI->integer) { + gi.Printf("(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression); } - } - else - { - if ( !Q_irand( 0, 2 ) )//FIXME: dependant on rank/diff? + } else { + if (!Q_irand(0, 2)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); - Jedi_Aggression( NPC, -1 ); - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression ); + // Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); + Jedi_Aggression(NPC, -1); + if (d_JediAI->integer) { + gi.Printf("(%d) BLOCKED: agg %d\n", level.time, NPCInfo->stats.aggression); } } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel+1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel + 1)); } } newFlags &= ~SEF_BLOCKED; - //FIXME: based on the type of parry the enemy is doing and my skill, + // FIXME: based on the type of parry the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. } - if ( NPC->client->ps.saberEventFlags&SEF_DEFLECTED ) - {//deflected a shot + if (NPC->client->ps.saberEventFlags & SEF_DEFLECTED) { // deflected a shot newFlags &= ~SEF_DEFLECTED; - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } } - if ( NPC->client->ps.saberEventFlags&SEF_HITWALL ) - {//hit a wall + if (NPC->client->ps.saberEventFlags & SEF_HITWALL) { // hit a wall newFlags &= ~SEF_HITWALL; } - if ( NPC->client->ps.saberEventFlags&SEF_HITOBJECT ) - {//hit some other damagable object - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.saberAnimLevel-1) ); + if (NPC->client->ps.saberEventFlags & SEF_HITOBJECT) { // hit some other damagable object + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPC, (NPC->client->ps.saberAnimLevel - 1)); } newFlags &= ~SEF_HITOBJECT; } @@ -3423,158 +2673,122 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } -static void Jedi_CombatIdle( int enemy_dist ) -{ - if ( !TIMER_Done( NPC, "parryTime" ) ) - { +static void Jedi_CombatIdle(int enemy_dist) { + if (!TIMER_Done(NPC, "parryTime")) { return; } - if ( NPC->client->ps.saberInFlight ) - {//don't do this idle stuff if throwing saber + if (NPC->client->ps.saberInFlight) { // don't do this idle stuff if throwing saber return; } - //FIXME: make these distance numbers defines? - if ( enemy_dist >= 64 ) - {//FIXME: only do this if standing still? - //based on aggression, flaunt/taunt + // FIXME: make these distance numbers defines? + if (enemy_dist >= 64) { // FIXME: only do this if standing still? + // based on aggression, flaunt/taunt int chance = 20; - if ( NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - { + if (NPC->client->NPC_class == CLASS_SHADOWTROOPER) { chance = 10; } - //FIXME: possibly throw local objects at enemy? - if ( Q_irand( 2, chance ) < NPCInfo->stats.aggression ) - { - if ( TIMER_Done( NPC, "chatter" ) ) - {//FIXME: add more taunt behaviors - //FIXME: sometimes he turns it off, then turns it right back on again??? - if ( enemy_dist > 200 && NPC->client->ps.saberActive && !Q_irand( 0, 5 ) ) - {//taunt even more, turn off the saber - //FIXME: don't do this if health low? + // FIXME: possibly throw local objects at enemy? + if (Q_irand(2, chance) < NPCInfo->stats.aggression) { + if (TIMER_Done(NPC, "chatter")) { // FIXME: add more taunt behaviors + // FIXME: sometimes he turns it off, then turns it right back on again??? + if (enemy_dist > 200 && NPC->client->ps.saberActive && !Q_irand(0, 5)) { // taunt even more, turn off the saber + // FIXME: don't do this if health low? NPC->client->ps.saberActive = qfalse; - //sound - if ( NPC->client->playerTeam == TEAM_PLAYER ) - { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/weapons/saber/saberoff.wav" ); - } - else - { - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav" ); + // sound + if (NPC->client->playerTeam == TEAM_PLAYER) { + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/weapons/saber/saberoff.wav"); + } else { + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav"); } - //Don't attack for a bit + // Don't attack for a bit NPCInfo->stats.aggression = 3; - //FIXME: maybe start strafing? - //debounce this - if ( NPC->client->playerTeam != TEAM_PLAYER && !Q_irand( 0, 1 )) - { + // FIXME: maybe start strafing? + // debounce this + if (NPC->client->playerTeam != TEAM_PLAYER && !Q_irand(0, 1)) { NPC->client->ps.taunting = level.time + 100; - TIMER_Set( NPC, "chatter", Q_irand( 5000, 10000 ) ); - TIMER_Set( NPC, "taunting", 5500 ); - } - else - { + TIMER_Set(NPC, "chatter", Q_irand(5000, 10000)); + TIMER_Set(NPC, "taunting", 5500); + } else { Jedi_BattleTaunt(); - TIMER_Set( NPC, "taunting", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPC, "taunting", Q_irand(5000, 10000)); } - } - else if ( Jedi_BattleTaunt() ) - {//FIXME: pick some anims + } else if (Jedi_BattleTaunt()) { // FIXME: pick some anims } } } } } -extern qboolean PM_SaberInParry( int move ); -static qboolean Jedi_AttackDecide( int enemy_dist ) -{ - if ( NPC->enemy->client - && NPC->enemy->s.weapon == WP_SABER - && NPC->enemy->client->ps.saberLockTime > level.time - && NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not +extern qboolean PM_SaberInParry(int move); +static qboolean Jedi_AttackDecide(int enemy_dist) { + if (NPC->enemy->client && NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client->ps.saberLockTime > level.time && + NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not return qfalse; } - if ( NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage with an attack! - int chance = 0; - if ( NPC->client->NPC_class == CLASS_DESANN || NPC->client->NPC_class == CLASS_LUKE ) - {//desann and luke + if (NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage with an attack! + int chance = 0; + if (NPC->client->NPC_class == CLASS_DESANN || NPC->client->NPC_class == CLASS_LUKE) { // desann and luke chance = 20; - } - else if ( NPC->client->NPC_class == CLASS_TAVION ) - {//tavion + } else if (NPC->client->NPC_class == CLASS_TAVION) { // tavion chance = 10; - } - else if ( NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG ) - {//fencer + } else if (NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG) { // fencer chance = 5; - } - else - { + } else { chance = NPCInfo->rank; } - if ( Q_irand( 0, 30 ) < chance ) - {//based on skill with some randomness - NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON;//clear this now that we are using the opportunity - TIMER_Set( NPC, "noRetreat", Q_irand( 500, 2000 ) ); - //FIXME: check enemy_dist? + if (Q_irand(0, 30) < chance) { // based on skill with some randomness + NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; // clear this now that we are using the opportunity + TIMER_Set(NPC, "noRetreat", Q_irand(500, 2000)); + // FIXME: check enemy_dist? NPC->client->ps.weaponTime = NPCInfo->shotTime = NPC->attackDebounceTime = 0; - //NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPC->client->ps.saberBlocked = BLOCKED_NONE; - WeaponThink( qtrue ); + WeaponThink(qtrue); return qtrue; } } - if ( NPC->client->NPC_class == CLASS_TAVION || - ( NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG ) || - ( NPC->client->NPC_class == CLASS_JEDI && NPCInfo->rank == RANK_COMMANDER ) ) - {//tavion, fencers, jedi trainer are all good at following up a parry with an attack - if ( ( PM_SaberInParry( NPC->client->ps.saberMove ) || PM_SaberInKnockaway( NPC->client->ps.saberMove ) ) - && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//try to attack straight from a parry + if (NPC->client->NPC_class == CLASS_TAVION || (NPC->client->NPC_class == CLASS_REBORN && NPCInfo->rank == RANK_LT_JG) || + (NPC->client->NPC_class == CLASS_JEDI && + NPCInfo->rank == RANK_COMMANDER)) { // tavion, fencers, jedi trainer are all good at following up a parry with an attack + if ((PM_SaberInParry(NPC->client->ps.saberMove) || PM_SaberInKnockaway(NPC->client->ps.saberMove)) && + NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // try to attack straight from a parry NPC->client->ps.weaponTime = NPCInfo->shotTime = NPC->attackDebounceTime = 0; - //NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPC->client->ps.saberBlocked = BLOCKED_NONE; - Jedi_AdjustSaberAnimLevel( NPC, FORCE_LEVEL_1 );//try to follow-up with a quick attack - WeaponThink( qtrue ); + Jedi_AdjustSaberAnimLevel(NPC, FORCE_LEVEL_1); // try to follow-up with a quick attack + WeaponThink(qtrue); return qtrue; } } - //try to hit them if we can - if ( enemy_dist >= 64 ) - { + // try to hit them if we can + if (enemy_dist >= 64) { return qfalse; } - if ( !TIMER_Done( NPC, "parryTime" ) ) - { + if (!TIMER_Done(NPC, "parryTime")) { return qfalse; } - if ( (NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//not allowed to attack + if ((NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // not allowed to attack return qfalse; } - if ( !(ucmd.buttons&BUTTON_ATTACK) && !(ucmd.buttons&BUTTON_ALT_ATTACK) ) - {//not already attacking - //Try to attack - WeaponThink( qtrue ); + if (!(ucmd.buttons & BUTTON_ATTACK) && !(ucmd.buttons & BUTTON_ALT_ATTACK)) { // not already attacking + // Try to attack + WeaponThink(qtrue); } - //FIXME: Maybe try to push enemy off a ledge? + // FIXME: Maybe try to push enemy off a ledge? - //close enough to step forward + // close enough to step forward - //FIXME: an attack debounce timer other than the phaser debounce time? + // FIXME: an attack debounce timer other than the phaser debounce time? // or base it on aggression? - if ( ucmd.buttons&BUTTON_ATTACK ) - {//attacking + if (ucmd.buttons & BUTTON_ATTACK) { // attacking /* if ( enemy_dist > 32 && NPCInfo->stats.aggression >= 4 ) {//move forward if we're too far away and we're chasing him @@ -3585,28 +2799,23 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) ucmd.forwardmove = -127; } */ - //FIXME: based on the type of parry/attack the enemy is doing and my skill, + // FIXME: based on the type of parry/attack the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. - //FIXME: have this interact with/override above strafing code? - if ( !ucmd.rightmove ) - {//not already strafing - if ( !Q_irand( 0, 3 ) ) - {//25% chance of doing this - vec3_t right, dir2enemy; - - AngleVectors( NPC->currentAngles, NULL, right, NULL ); - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentAngles, dir2enemy ); - if ( DotProduct( right, dir2enemy ) > 0 ) - {//he's to my right, strafe left + // FIXME: have this interact with/override above strafing code? + if (!ucmd.rightmove) { // not already strafing + if (!Q_irand(0, 3)) { // 25% chance of doing this + vec3_t right, dir2enemy; + + AngleVectors(NPC->currentAngles, NULL, right, NULL); + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentAngles, dir2enemy); + if (DotProduct(right, dir2enemy) > 0) { // he's to my right, strafe left ucmd.rightmove = -127; - VectorClear( NPC->client->ps.moveDir ); - } - else - {//he's to my left, strafe right + VectorClear(NPC->client->ps.moveDir); + } else { // he's to my left, strafe right ucmd.rightmove = 127; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } } } @@ -3616,12 +2825,11 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) return qfalse; } -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f -static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) -{//FIXME: if land on enemy, knock him down & jump off again +static qboolean Jedi_Jump(vec3_t dest, int goalEntNum) { // FIXME: if land on enemy, knock him down & jump off again /* if ( dest[2] - NPC->currentOrigin[2] < 64 && DistanceHorizontal( NPC->currentOrigin, dest ) > 256 ) {//a pretty horizontal jump, easy to fake: @@ -3644,176 +2852,143 @@ static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) } else */ - if ( 1 ) - { - float targetDist, shotSpeed = 300, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, - vec3_t targetDir, shotVel, failCase; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, timeStep = 500, hitCount = 0, maxHits = 7; - vec3_t lastPos, testPos, bottom; - - while ( hitCount < maxHits ) - { - VectorSubtract( dest, NPC->currentOrigin, targetDir ); - targetDist = VectorNormalize( targetDir ); - - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + if (1) { + float targetDist, shotSpeed = 300, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, + vec3_t targetDir, shotVel, failCase; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, timeStep = 500, hitCount = 0, maxHits = 7; + vec3_t lastPos, testPos, bottom; + + while (hitCount < maxHits) { + VectorSubtract(dest, NPC->currentOrigin, targetDir); + targetDist = VectorNormalize(targetDir); + + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * NPC->client->ps.gravity; - if ( !hitCount ) - {//save the first one as the worst case scenario - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first one as the worst case scenario + VectorCopy(shotVel, failCase); } - if ( 1 )//tracePath ) - {//do a rough trace of the path + if (1) // tracePath ) + { // do a rough trace of the path blocked = qfalse; - VectorCopy( NPC->currentOrigin, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(NPC->currentOrigin, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( NPC->currentOrigin, lastPos ); + VectorCopy(NPC->currentOrigin, lastPos); - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? + // Trace just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - if ( testPos[2] < lastPos[2] ) - {//going down, ignore botclip - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - } - else - {//going up, check for botclip - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + if (testPos[2] < lastPos[2]) { // going down, ignore botclip + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + } else { // going up, check for botclip + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); } - if ( trace.allsolid || trace.startsolid ) - { + if (trace.allsolid || trace.startsolid) { blocked = qtrue; break; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.entityNum == goalEntNum ) - {//hit the enemy, that's perfect! - //Hmm, don't want to land on him, though... + if (trace.fraction < 1.0f) { // hit something + if (trace.entityNum == goalEntNum) { // hit the enemy, that's perfect! + // Hmm, don't want to land on him, though... break; - } - else - { - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + } else { + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush blocked = qtrue; break; } - if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, dest ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, dest) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, dest ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, dest); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; break; } } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear - if ( trace.fraction >= 1.0f ) - {//hmm, make sure we'll land on the ground... - //FIXME: do we care how far below ourselves or our dest we'll land? - VectorCopy( trace.endpos, bottom ); + if (elapsedTime == floor(travelTime)) { // reached end, all clear + if (trace.fraction >= 1.0f) { // hmm, make sure we'll land on the ground... + // FIXME: do we care how far below ourselves or our dest we'll land? + VectorCopy(trace.endpos, bottom); bottom[2] -= 128; - gi.trace( &trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f ) - {//would fall too far + gi.trace(&trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f) { // would fall too far blocked = qtrue; } } break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - shotSpeed = 300 + ((hitCount-2) * 100);//from 100 to 900 (skipping 300) - if ( hitCount >= 2 ) - {//skip 300 since that was the first value we tested + shotSpeed = 300 + ((hitCount - 2) * 100); // from 100 to 900 (skipping 300) + if (hitCount >= 2) { // skip 300 since that was the first value we tested shotSpeed += 100; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) - //NOTE: or try failcase? - VectorCopy( failCase, NPC->client->ps.velocity ); + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + // NOTE: or try failcase? + VectorCopy(failCase, NPC->client->ps.velocity); } - VectorCopy( shotVel, NPC->client->ps.velocity ); - } - else - {//a more complicated jump - vec3_t dir, p1, p2, apex; - float time, height, forward, z, xy, dist, apexHeight; + VectorCopy(shotVel, NPC->client->ps.velocity); + } else { // a more complicated jump + vec3_t dir, p1, p2, apex; + float time, height, forward, z, xy, dist, apexHeight; - if ( NPC->currentOrigin[2] > dest[2] )//NPCInfo->goalEntity->currentOrigin - { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( dest, p2 );//NPCInfo->goalEntity->currentOrigin - } - else if ( NPC->currentOrigin[2] < dest[2] )//NPCInfo->goalEntity->currentOrigin + if (NPC->currentOrigin[2] > dest[2]) // NPCInfo->goalEntity->currentOrigin { - VectorCopy( dest, p1 );//NPCInfo->goalEntity->currentOrigin - VectorCopy( NPC->currentOrigin, p2 ); - } - else + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(dest, p2); // NPCInfo->goalEntity->currentOrigin + } else if (NPC->currentOrigin[2] < dest[2]) // NPCInfo->goalEntity->currentOrigin { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( dest, p2 );//NPCInfo->goalEntity->currentOrigin + VectorCopy(dest, p1); // NPCInfo->goalEntity->currentOrigin + VectorCopy(NPC->currentOrigin, p2); + } else { + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(dest, p2); // NPCInfo->goalEntity->currentOrigin } - //z = xy*xy - VectorSubtract( p2, p1, dir ); + // z = xy*xy + VectorSubtract(p2, p1, dir); dir[2] = 0; - //Get xy and z diffs - xy = VectorNormalize( dir ); + // Get xy and z diffs + xy = VectorNormalize(dir); z = p1[2] - p2[2]; - apexHeight = APEX_HEIGHT/2; + apexHeight = APEX_HEIGHT / 2; - //Determine most desirable apex height - //FIXME: length of xy will change curve of parabola, need to account for this - //somewhere... PARA_WIDTH + // Determine most desirable apex height + // FIXME: length of xy will change curve of parabola, need to account for this + // somewhere... PARA_WIDTH /* apexHeight = (APEX_HEIGHT * PARA_WIDTH/xy) + (APEX_HEIGHT * z/128); if ( apexHeight < APEX_HEIGHT * 0.5 ) @@ -3830,75 +3005,66 @@ static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) assert(z >= 0); -// gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); + // gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); xy -= z; xy *= 0.5; assert(xy > 0); - VectorMA( p1, xy, dir, apex ); + VectorMA(p1, xy, dir, apex); apex[2] += apexHeight; VectorCopy(apex, NPC->pos1); - //Now we have the apex, aim for it + // Now we have the apex, aim for it height = apex[2] - NPC->currentOrigin[2]; - time = sqrt( height / ( .5 * NPC->client->ps.gravity ) );//was 0.5, but didn't work well for very long jumps - if ( !time ) - { - //gi.Printf( S_COLOR_RED"ERROR: no time in jump\n" ); + time = sqrt(height / (.5 * NPC->client->ps.gravity)); // was 0.5, but didn't work well for very long jumps + if (!time) { + // gi.Printf( S_COLOR_RED"ERROR: no time in jump\n" ); return qfalse; } - VectorSubtract ( apex, NPC->currentOrigin, NPC->client->ps.velocity ); + VectorSubtract(apex, NPC->currentOrigin, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 0; - dist = VectorNormalize( NPC->client->ps.velocity ); + dist = VectorNormalize(NPC->client->ps.velocity); - forward = dist / time * 1.25;//er... probably bad, but... - VectorScale( NPC->client->ps.velocity, forward, NPC->client->ps.velocity ); + forward = dist / time * 1.25; // er... probably bad, but... + VectorScale(NPC->client->ps.velocity, forward, NPC->client->ps.velocity); - //FIXME: Uh.... should we trace/EvaluateTrajectory this to make sure we have clearance and we land where we want? + // FIXME: Uh.... should we trace/EvaluateTrajectory this to make sure we have clearance and we land where we want? NPC->client->ps.velocity[2] = time * NPC->client->ps.gravity; - //gi.Printf("Jump Velocity: %4.2f, %4.2f, %4.2f\n", NPC->client->ps.velocity[0], NPC->client->ps.velocity[1], NPC->client->ps.velocity[2] ); + // gi.Printf("Jump Velocity: %4.2f, %4.2f, %4.2f\n", NPC->client->ps.velocity[0], NPC->client->ps.velocity[1], NPC->client->ps.velocity[2] ); } return qtrue; } -static qboolean Jedi_TryJump( gentity_t *goal ) -{//FIXME: never does a simple short, regular jump... - //FIXME: I need to be on ground too! - if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { +static qboolean Jedi_TryJump(gentity_t *goal) { // FIXME: never does a simple short, regular jump... + // FIXME: I need to be on ground too! + if ((NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { return qfalse; } - if ( TIMER_Done( NPC, "jumpChaseDebounce" ) ) - { - if ( (!goal->client || goal->client->ps.groundEntityNum != ENTITYNUM_NONE) ) - { - if ( !PM_InKnockDown( &NPC->client->ps ) && !PM_InRoll( &NPC->client->ps ) ) - {//enemy is on terra firma + if (TIMER_Done(NPC, "jumpChaseDebounce")) { + if ((!goal->client || goal->client->ps.groundEntityNum != ENTITYNUM_NONE)) { + if (!PM_InKnockDown(&NPC->client->ps) && !PM_InRoll(&NPC->client->ps)) { // enemy is on terra firma vec3_t goal_diff; float goal_z_diff; - VectorSubtract( goal->currentOrigin, NPC->currentOrigin, goal_diff ); + VectorSubtract(goal->currentOrigin, NPC->currentOrigin, goal_diff); goal_z_diff = goal_diff[2]; goal_diff[2] = 0; - float goal_xy_dist = VectorNormalize( goal_diff ); - if ( goal_xy_dist < 550 && goal_z_diff > -400/*was -256*/ )//for now, jedi don't take falling damage && (NPC->health > 20 || goal_z_diff > 0 ) && (NPC->health >= 100 || goal_z_diff > -128 ))//closer than @512 + float goal_xy_dist = VectorNormalize(goal_diff); + if (goal_xy_dist < 550 && goal_z_diff > -400 /*was -256*/) // for now, jedi don't take falling damage && (NPC->health > 20 || goal_z_diff > 0 ) + // && (NPC->health >= 100 || goal_z_diff > -128 ))//closer than @512 { qboolean debounce = qfalse; - if ( NPC->health < 150 && ((NPC->health < 30 && goal_z_diff < 0) || goal_z_diff < -128 ) ) - {//don't jump, just walk off... doesn't help with ledges, though + if (NPC->health < 150 && + ((NPC->health < 30 && goal_z_diff < 0) || goal_z_diff < -128)) { // don't jump, just walk off... doesn't help with ledges, though debounce = qtrue; - } - else if ( goal_z_diff < 32 && goal_xy_dist < 200 ) - {//what is their ideal jump height? + } else if (goal_z_diff < 32 && goal_xy_dist < 200) { // what is their ideal jump height? ucmd.upmove = 127; debounce = qtrue; - } - else - { + } else { /* //NO! All Jedi can jump-navigate now... if ( NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG ) @@ -3906,53 +3072,41 @@ static qboolean Jedi_TryJump( gentity_t *goal ) return qfalse; } */ - if ( goal_z_diff > 0 || goal_xy_dist > 128 ) - {//Fake a force-jump - //Screw it, just do my own calc & throw + if (goal_z_diff > 0 || goal_xy_dist > 128) { // Fake a force-jump + // Screw it, just do my own calc & throw vec3_t dest; - VectorCopy( goal->currentOrigin, dest ); - if ( goal == NPC->enemy ) - { - int sideTry = 0; - while( sideTry < 10 ) - {//FIXME: make it so it doesn't try the same spot again? - if ( Q_irand( 0, 1 ) ) - { - dest[0] += NPC->enemy->maxs[0]*1.25; - } - else - { - dest[0] += NPC->enemy->mins[0]*1.25; - } - if ( Q_irand( 0, 1 ) ) - { - dest[1] += NPC->enemy->maxs[1]*1.25; + VectorCopy(goal->currentOrigin, dest); + if (goal == NPC->enemy) { + int sideTry = 0; + while (sideTry < 10) { // FIXME: make it so it doesn't try the same spot again? + if (Q_irand(0, 1)) { + dest[0] += NPC->enemy->maxs[0] * 1.25; + } else { + dest[0] += NPC->enemy->mins[0] * 1.25; } - else - { - dest[1] += NPC->enemy->mins[1]*1.25; + if (Q_irand(0, 1)) { + dest[1] += NPC->enemy->maxs[1] * 1.25; + } else { + dest[1] += NPC->enemy->mins[1] * 1.25; } - trace_t trace; - vec3_t bottom; - VectorCopy( dest, bottom ); + trace_t trace; + vec3_t bottom; + VectorCopy(dest, bottom); bottom[2] -= 128; - gi.trace( &trace, dest, NPC->mins, NPC->maxs, bottom, goal->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.fraction < 1.0f ) - {//hit floor, okay to land here + gi.trace(&trace, dest, NPC->mins, NPC->maxs, bottom, goal->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.fraction < 1.0f) { // hit floor, okay to land here break; } sideTry++; } - if ( sideTry >= 10 ) - {//screw it, just jump right at him? - VectorCopy( goal->currentOrigin, dest ); + if (sideTry >= 10) { // screw it, just jump right at him? + VectorCopy(goal->currentOrigin, dest); } } - if ( Jedi_Jump( dest, goal->s.number ) ) - { - //gi.Printf( "(%d) pre-checked force jump\n", level.time ); + if (Jedi_Jump(dest, goal->s.number)) { + // gi.Printf( "(%d) pre-checked force jump\n", level.time ); - //FIXME: store the dir we;re going in in case something gets in the way of the jump? + // FIXME: store the dir we;re going in in case something gets in the way of the jump? //? = vectoyaw( NPC->client->ps.velocity ); /* if ( NPC->client->ps.velocity[2] < 320 ) @@ -3961,39 +3115,35 @@ static qboolean Jedi_TryJump( gentity_t *goal ) } else */ - {//FIXME: make this a function call + { // FIXME: make this a function call int jumpAnim; - //FIXME: this should be more intelligent, like the normal force jump anim logic - if ( NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG ) - {//can't do acrobatics + // FIXME: this should be more intelligent, like the normal force jump anim logic + if (NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG) { // can't do acrobatics jumpAnim = BOTH_FORCEJUMP1; - } - else - { + } else { jumpAnim = BOTH_FLIP_F; } - NPC_SetAnim( NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } NPC->client->ps.forceJumpZStart = NPC->currentOrigin[2]; NPC->client->ps.pm_flags |= PMF_JUMPING; NPC->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; - NPC->client->ps.forcePowersActive |= ( 1 << FP_LEVITATION ); - G_SoundOnEnt( NPC, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + G_SoundOnEnt(NPC, CHAN_BODY, "sound/weapons/force/jump.wav"); - TIMER_Set( NPC, "forceJumpChasing", Q_irand( 2000, 3000 ) ); + TIMER_Set(NPC, "forceJumpChasing", Q_irand(2000, 3000)); debounce = qtrue; } } } - if ( debounce ) - { - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); + if (debounce) { + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); ucmd.forwardmove = 127; - VectorClear( NPC->client->ps.moveDir ); - TIMER_Set( NPC, "duck", -level.time ); + VectorClear(NPC->client->ps.moveDir); + TIMER_Set(NPC, "duck", -level.time); return qtrue; } } @@ -4003,20 +3153,15 @@ static qboolean Jedi_TryJump( gentity_t *goal ) return qfalse; } -static qboolean Jedi_Jumping( gentity_t *goal ) -{ - if ( !TIMER_Done( NPC, "forceJumpChasing" ) && goal ) - {//force-jumping at the enemy - if ( !(NPC->client->ps.pm_flags & PMF_JUMPING )//forceJumpZStart ) - && !(NPC->client->ps.pm_flags&PMF_TRIGGER_PUSHED)) - {//landed - TIMER_Set( NPC, "forceJumpChasing", 0 ); - } - else - { - NPC_FaceEntity( goal, qtrue ); - //FIXME: push me torward where I was heading - //FIXME: if hit a ledge as soon as we jumped, we need to push toward our goal... must remember original jump dir and/or original jump dest +static qboolean Jedi_Jumping(gentity_t *goal) { + if (!TIMER_Done(NPC, "forceJumpChasing") && goal) { // force-jumping at the enemy + if (!(NPC->client->ps.pm_flags & PMF_JUMPING) // forceJumpZStart ) + && !(NPC->client->ps.pm_flags & PMF_TRIGGER_PUSHED)) { // landed + TIMER_Set(NPC, "forceJumpChasing", 0); + } else { + NPC_FaceEntity(goal, qtrue); + // FIXME: push me torward where I was heading + // FIXME: if hit a ledge as soon as we jumped, we need to push toward our goal... must remember original jump dir and/or original jump dest /* vec3_t viewangles_xy={0,0,0}, goal_dir, goal_xy_dir, forward, right; float goal_dist; @@ -4051,47 +3196,32 @@ static qboolean Jedi_Jumping( gentity_t *goal ) return qfalse; } -extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ); -static void Jedi_CheckEnemyMovement( float enemy_dist ) -{ - if ( !NPC->enemy || !NPC->enemy->client ) - { +extern void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir); +static void Jedi_CheckEnemyMovement(float enemy_dist) { + if (!NPC->enemy || !NPC->enemy->client) { return; } - if ( NPC->client->NPC_class != CLASS_TAVION - && NPC->client->NPC_class != CLASS_DESANN - && NPC->client->NPC_class != CLASS_LUKE ) - { - if ( NPC->enemy->enemy && NPC->enemy->enemy == NPC ) - {//enemy is mad at *me* - if ( NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 || - NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN ) - {//enemy is flipping over me - if ( Q_irand( 0, NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + if (NPC->client->NPC_class != CLASS_TAVION && NPC->client->NPC_class != CLASS_DESANN && NPC->client->NPC_class != CLASS_LUKE) { + if (NPC->enemy->enemy && NPC->enemy->enemy == NPC) { // enemy is mad at *me* + if (NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 || + NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN) { // enemy is flipping over me + if (Q_irand(0, NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); } - } - else if ( NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP - || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP ) - {//he's flipping off a wall - if ( NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//still in air - if ( enemy_dist < 256 ) - {//close - if ( Q_irand( 0, NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + } else if (NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 || NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT || + NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT || NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP || + NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP) { // he's flipping off a wall + if (NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE) { // still in air + if (enemy_dist < 256) { // close + if (Q_irand(0, NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... /* ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; VectorClear( NPC->client->ps.moveDir ); @@ -4103,63 +3233,52 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); TIMER_Set( NPC, "noturn", Q_irand( 200, 500 ) ); */ - //stop current movement + // stop current movement ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "noturn", Q_irand( 250, 500 )*(3-g_spskill->integer) ); + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPC, "noturn", Q_irand(250, 500) * (3 - g_spskill->integer)); vec3_t enemyFwd, dest, dir; - VectorCopy( NPC->enemy->client->ps.velocity, enemyFwd ); - VectorNormalize( enemyFwd ); - VectorMA( NPC->enemy->currentOrigin, -64, enemyFwd, dest ); - VectorSubtract( dest, NPC->currentOrigin, dir ); - if ( VectorNormalize( dir ) > 32 ) - { - G_UcmdMoveForDir( NPC, &ucmd, dir ); - } - else - { - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); + VectorCopy(NPC->enemy->client->ps.velocity, enemyFwd); + VectorNormalize(enemyFwd); + VectorMA(NPC->enemy->currentOrigin, -64, enemyFwd, dest); + VectorSubtract(dest, NPC->currentOrigin, dir); + if (VectorNormalize(dir) > 32) { + G_UcmdMoveForDir(NPC, &ucmd, dir); + } else { + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); } } } } - } - else if ( NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1 ) - {//he's stabbing backwards - if ( enemy_dist < 256 && enemy_dist > 64 ) - {//close - if ( !InFront( NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles, 0.0f ) ) - {//behind him - if ( !Q_irand( 0, NPCInfo->rank ) ) - {//be nice and stand still for him... - //stop current movement + } else if (NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1) { // he's stabbing backwards + if (enemy_dist < 256 && enemy_dist > 64) { // close + if (!InFront(NPC->currentOrigin, NPC->enemy->currentOrigin, NPC->enemy->currentAngles, 0.0f)) { // behind him + if (!Q_irand(0, NPCInfo->rank)) { // be nice and stand still for him... + // stop current movement ucmd.forwardmove = ucmd.rightmove = ucmd.upmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); NPC->client->ps.forceJumpCharge = 0; - TIMER_Set( NPC, "strafeLeft", -1 ); - TIMER_Set( NPC, "strafeRight", -1 ); - TIMER_Set( NPC, "noStrafe", Q_irand( 500, 1000 ) ); + TIMER_Set(NPC, "strafeLeft", -1); + TIMER_Set(NPC, "strafeRight", -1); + TIMER_Set(NPC, "noStrafe", Q_irand(500, 1000)); vec3_t enemyFwd, dest, dir; - AngleVectors( NPC->enemy->currentAngles, enemyFwd, NULL, NULL ); - VectorMA( NPC->enemy->currentOrigin, -32, enemyFwd, dest ); - VectorSubtract( dest, NPC->currentOrigin, dir ); - if ( VectorNormalize( dir ) > 64 ) - { - G_UcmdMoveForDir( NPC, &ucmd, dir ); - } - else - { - TIMER_Set( NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); + AngleVectors(NPC->enemy->currentAngles, enemyFwd, NULL, NULL); + VectorMA(NPC->enemy->currentOrigin, -32, enemyFwd, dest); + VectorSubtract(dest, NPC->currentOrigin, dir); + if (VectorNormalize(dir) > 64) { + G_UcmdMoveForDir(NPC, &ucmd, dir); + } else { + TIMER_Set(NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPC, "movecenter", Q_irand(500, 1000)); } } } @@ -4167,148 +3286,126 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) } } } - //FIXME: also: + // FIXME: also: // If enemy doing wall flip, keep running forward // If enemy doing back-attack and we're behind him keep running forward toward his back, don't strafe } -static void Jedi_CheckJumps( void ) -{ - if ( (NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { +static void Jedi_CheckJumps(void) { + if ((NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { NPC->client->ps.forceJumpCharge = 0; ucmd.upmove = 0; return; } - //FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb - //FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? - vec3_t jumpVel = {0,0,0}; + // FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb + // FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? + vec3_t jumpVel = {0, 0, 0}; - if ( NPC->client->ps.forceJumpCharge ) - { - //gi.Printf( "(%d) force jump\n", level.time ); - WP_GetVelocityForForceJump( NPC, jumpVel, &ucmd ); - } - else if ( ucmd.upmove > 0 ) - { - //gi.Printf( "(%d) regular jump\n", level.time ); - VectorCopy( NPC->client->ps.velocity, jumpVel ); + if (NPC->client->ps.forceJumpCharge) { + // gi.Printf( "(%d) force jump\n", level.time ); + WP_GetVelocityForForceJump(NPC, jumpVel, &ucmd); + } else if (ucmd.upmove > 0) { + // gi.Printf( "(%d) regular jump\n", level.time ); + VectorCopy(NPC->client->ps.velocity, jumpVel); jumpVel[2] = JUMP_VELOCITY; - } - else - { + } else { return; } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( !jumpVel[0] && !jumpVel[1] )//FIXME: && !ucmd.forwardmove && !ucmd.rightmove? - {//we assume a jump straight up is safe - //gi.Printf( "(%d) jump straight up is safe\n", level.time ); + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (!jumpVel[0] && !jumpVel[1]) // FIXME: && !ucmd.forwardmove && !ucmd.rightmove? + { // we assume a jump straight up is safe + // gi.Printf( "(%d) jump straight up is safe\n", level.time ); return; } - //Now predict where this is going - //in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there - trace_t trace; - trajectory_t tr; - vec3_t lastPos, testPos, bottom; - int elapsedTime; + // Now predict where this is going + // in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there + trace_t trace; + trajectory_t tr; + vec3_t lastPos, testPos, bottom; + int elapsedTime; - VectorCopy( NPC->currentOrigin, tr.trBase ); - VectorCopy( jumpVel, tr.trDelta ); + VectorCopy(NPC->currentOrigin, tr.trBase); + VectorCopy(jumpVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; - VectorCopy( NPC->currentOrigin, lastPos ); - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500 ) - { - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - //FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... - if ( testPos[2] < lastPos[2] ) - {//going down, don't check for BOTCLIP - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 );//FIXME: include CONTENTS_BOTCLIP? - } - else - {//going up, check for BOTCLIP - gi.trace( &trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - } - if ( trace.allsolid || trace.startsolid ) - {//WTF? - //FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? + VectorCopy(NPC->currentOrigin, lastPos); + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to + // apex and down? + for (elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500) { + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + // FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... + if (testPos[2] < lastPos[2]) { // going down, don't check for BOTCLIP + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); // FIXME: include CONTENTS_BOTCLIP? + } else { // going up, check for BOTCLIP + gi.trace(&trace, lastPos, NPC->mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + } + if (trace.allsolid || trace.startsolid) { // WTF? + // FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? goto jump_unsafe; return; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + if (trace.fraction < 1.0f) { // hit something + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush goto jump_unsafe; return; } - //FIXME: trace through func_glass? + // FIXME: trace through func_glass? break; } - VectorCopy( testPos, lastPos ); + VectorCopy(testPos, lastPos); } - //okay, reached end of jump, now trace down from here for a floor - VectorCopy( trace.endpos, bottom ); - if ( bottom[2] > NPC->currentOrigin[2] ) - {//only care about dist down from current height or lower + // okay, reached end of jump, now trace down from here for a floor + VectorCopy(trace.endpos, bottom); + if (bottom[2] > NPC->currentOrigin[2]) { // only care about dist down from current height or lower bottom[2] = NPC->currentOrigin[2]; - } - else if ( NPC->currentOrigin[2] - bottom[2] > 400 ) - {//whoa, long drop, don't do it! - //probably no floor at end of jump, so don't jump + } else if (NPC->currentOrigin[2] - bottom[2] > 400) { // whoa, long drop, don't do it! + // probably no floor at end of jump, so don't jump goto jump_unsafe; return; } bottom[2] -= 128; - gi.trace( &trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0f ) - {//hit ground! - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//landed on an ent + gi.trace(&trace, trace.endpos, NPC->mins, NPC->maxs, bottom, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid || trace.fraction < 1.0f) { // hit ground! + if (trace.entityNum < ENTITYNUM_WORLD) { // landed on an ent gentity_t *groundEnt = &g_entities[trace.entityNum]; - if ( groundEnt->svFlags&SVF_GLASS_BRUSH ) - {//don't land on breakable glass! + if (groundEnt->svFlags & SVF_GLASS_BRUSH) { // don't land on breakable glass! goto jump_unsafe; return; } } - //gi.Printf( "(%d) jump is safe\n", level.time ); + // gi.Printf( "(%d) jump is safe\n", level.time ); return; } jump_unsafe: - //probably no floor at end of jump, so don't jump - //gi.Printf( "(%d) unsafe jump cleared\n", level.time ); + // probably no floor at end of jump, so don't jump + // gi.Printf( "(%d) unsafe jump cleared\n", level.time ); NPC->client->ps.forceJumpCharge = 0; ucmd.upmove = 0; } -static void Jedi_Combat( void ) -{ - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - trace_t trace; +static void Jedi_Combat(void) { + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + trace_t trace; - //See where enemy will be 300 ms from now - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); + // See where enemy will be 300 ms from now + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); - if ( Jedi_Jumping( NPC->enemy ) ) - {//I'm in the middle of a jump, so just see if I should attack - Jedi_AttackDecide( enemy_dist ); + if (Jedi_Jumping(NPC->enemy)) { // I'm in the middle of a jump, so just see if I should attack + Jedi_AttackDecide(enemy_dist); return; } - if ( !(NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//not gripping - //If we can't get straight at him - if ( !Jedi_ClearPathToSpot( enemy_dest, NPC->enemy->s.number ) ) - {//hunt him down - //gi.Printf( "No Clear Path\n" ); - if ( (NPC_ClearLOS( NPC->enemy )||NPCInfo->enemyLastSeenTime>level.time-500) && NPC_FaceEnemy( qtrue ) )//( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && + if (!(NPC->client->ps.forcePowersActive & (1 << FP_GRIP)) || NPC->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // not gripping + // If we can't get straight at him + if (!Jedi_ClearPathToSpot(enemy_dest, NPC->enemy->s.number)) { // hunt him down + // gi.Printf( "No Clear Path\n" ); + if ((NPC_ClearLOS(NPC->enemy) || NPCInfo->enemyLastSeenTime > level.time - 500) && + NPC_FaceEnemy(qtrue)) //( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && { - //try to jump to him? + // try to jump to him? /* vec3_t end; VectorCopy( NPC->currentOrigin, end ); @@ -4333,142 +3430,121 @@ static void Jedi_Combat( void ) } } */ - //FIXME: about every 1 second calc a velocity, - //run a loop of traces with evaluate trajectory - //for gravity with my size, see if it makes it... - //this will also catch misacalculations that send you off ledges! - //gi.Printf( "Considering Jump\n" ); - if ( Jedi_TryJump( NPC->enemy ) ) - {//FIXME: what about jumping to his enemyLastSeenLocation? + // FIXME: about every 1 second calc a velocity, + // run a loop of traces with evaluate trajectory + // for gravity with my size, see if it makes it... + // this will also catch misacalculations that send you off ledges! + // gi.Printf( "Considering Jump\n" ); + if (Jedi_TryJump(NPC->enemy)) { // FIXME: what about jumping to his enemyLastSeenLocation? return; } } - //Check for evasion - if ( TIMER_Done( NPC, "parryTime" ) ) - {//finished parrying - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPC, "parryTime")) { // finished parrying + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( Jedi_Hunt() && !(NPCInfo->aiFlags&NPCAI_BLOCKED) )//FIXME: have to do this because they can ping-pong forever - {//can macro-navigate to him - if ( enemy_dist < 384 && !Q_irand( 0, 10 ) && NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && !NPC_ClearLOS( NPC->enemy ) ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JLOST1, EV_JLOST3 ), 3000 ); + if (Jedi_Hunt() && !(NPCInfo->aiFlags & NPCAI_BLOCKED)) // FIXME: have to do this because they can ping-pong forever + { // can macro-navigate to him + if (enemy_dist < 384 && !Q_irand(0, 10) && NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPC->client->playerTeam] < level.time && !NPC_ClearLOS(NPC->enemy)) { + G_AddVoiceEvent(NPC, Q_irand(EV_JLOST1, EV_JLOST3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } return; } - //well, try to head for his last seen location - /* - else if ( Jedi_Track() ) - { - return; - } - */ else - {//FIXME: try to find a waypoint that can see enemy, jump from there - if ( NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//try to jump to the blockedDest - gentity_t *tempGoal = G_Spawn();//ugh, this is NOT good...? - G_SetOrigin( tempGoal, NPCInfo->blockedDest ); - gi.linkentity( tempGoal ); - if ( Jedi_TryJump( tempGoal ) ) - {//going to jump to the dest - G_FreeEntity( tempGoal ); + // well, try to head for his last seen location + /* + else if ( Jedi_Track() ) + { + return; + } + */ + else { // FIXME: try to find a waypoint that can see enemy, jump from there + if (NPCInfo->aiFlags & NPCAI_BLOCKED) { // try to jump to the blockedDest + gentity_t *tempGoal = G_Spawn(); // ugh, this is NOT good...? + G_SetOrigin(tempGoal, NPCInfo->blockedDest); + gi.linkentity(tempGoal); + if (Jedi_TryJump(tempGoal)) { // going to jump to the dest + G_FreeEntity(tempGoal); return; } - G_FreeEntity( tempGoal ); + G_FreeEntity(tempGoal); } - //enemy_lost = qtrue; + // enemy_lost = qtrue; } } } - //else, we can see him or we can't track him at all + // else, we can see him or we can't track him at all - //every few seconds, decide if we should we advance or retreat? - Jedi_CombatTimersUpdate( enemy_dist ); + // every few seconds, decide if we should we advance or retreat? + Jedi_CombatTimersUpdate(enemy_dist); - //We call this even if lost enemy to keep him moving and to update the taunting behavior - //maintain a distance from enemy appropriate for our aggression level - Jedi_CombatDistance( enemy_dist ); + // We call this even if lost enemy to keep him moving and to update the taunting behavior + // maintain a distance from enemy appropriate for our aggression level + Jedi_CombatDistance(enemy_dist); - //if ( !enemy_lost ) + // if ( !enemy_lost ) { - //Update our seen enemy position - if ( !NPC->enemy->client || ( NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) ) - { - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + // Update our seen enemy position + if (!NPC->enemy->client || (NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE)) { + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); } NPCInfo->enemyLastSeenTime = level.time; } - //Turn to face the enemy - if ( TIMER_Done( NPC, "noturn" ) ) - { - Jedi_FaceEnemy( qtrue ); + // Turn to face the enemy + if (TIMER_Done(NPC, "noturn")) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - //Check for evasion - if ( TIMER_Done( NPC, "parryTime" ) ) - {//finished parrying - if ( NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPC, "parryTime")) { // finished parrying + if (NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPC->enemy->s.weapon == WP_SABER ) - { - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); - } - else - {//do we need to do any evasion for other kinds of enemies? + if (NPC->enemy->s.weapon == WP_SABER) { + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); + } else { // do we need to do any evasion for other kinds of enemies? } - //apply strafing/walking timers, etc. + // apply strafing/walking timers, etc. Jedi_TimersApply(); - if ( !NPC->client->ps.saberInFlight && (!(NPC->client->ps.forcePowersActive&(1<client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) ) - {//not throwing saber or using force grip - //see if we can attack - if ( !Jedi_AttackDecide( enemy_dist ) ) - {//we're not attacking, decide what else to do - Jedi_CombatIdle( enemy_dist ); - //FIXME: lower aggression when actually strike offensively? Or just when do damage? - } - else - {//we are attacking - //stop taunting - TIMER_Set( NPC, "taunting", -level.time ); + if (!NPC->client->ps.saberInFlight && (!(NPC->client->ps.forcePowersActive & (1 << FP_GRIP)) || + NPC->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2)) { // not throwing saber or using force grip + // see if we can attack + if (!Jedi_AttackDecide(enemy_dist)) { // we're not attacking, decide what else to do + Jedi_CombatIdle(enemy_dist); + // FIXME: lower aggression when actually strike offensively? Or just when do damage? + } else { // we are attacking + // stop taunting + TIMER_Set(NPC, "taunting", -level.time); } - } - else - { + } else { } - //Check for certain enemy special moves - Jedi_CheckEnemyMovement( enemy_dist ); - //Make sure that we don't jump off ledges over long drops + // Check for certain enemy special moves + Jedi_CheckEnemyMovement(enemy_dist); + // Make sure that we don't jump off ledges over long drops Jedi_CheckJumps(); - //Just make sure we don't strafe into walls or off cliffs - if ( !NPC_MoveDirClear( ucmd.forwardmove, ucmd.rightmove, qtrue ) ) - {//uh-oh, we are going to fall or hit something - navInfo_t info; - //Get the move info - NAV_GetLastMove( info ); - if ( !(info.flags & NIF_MACRO_NAV) ) - {//micro-navigation told us to step off a ledge, try using macronav for now - NPC_MoveToGoal( qfalse ); - } - //reset the timers. - TIMER_Set( NPC, "strafeLeft", 0 ); - TIMER_Set( NPC, "strafeRight", 0 ); + // Just make sure we don't strafe into walls or off cliffs + if (!NPC_MoveDirClear(ucmd.forwardmove, ucmd.rightmove, qtrue)) { // uh-oh, we are going to fall or hit something + navInfo_t info; + // Get the move info + NAV_GetLastMove(info); + if (!(info.flags & NIF_MACRO_NAV)) { // micro-navigation told us to step off a ledge, try using macronav for now + NPC_MoveToGoal(qfalse); + } + // reset the timers. + TIMER_Set(NPC, "strafeLeft", 0); + TIMER_Set(NPC, "strafeRight", 0); } } @@ -4484,189 +3560,150 @@ NPC_Jedi_Pain ------------------------- */ -void NPC_Jedi_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - //FIXME: base the actual aggression add/subtract on health? - //FIXME: don't do this more than once per frame? - //FIXME: when take pain, stop force gripping....? - if ( other->s.weapon == WP_SABER ) - {//back off - TIMER_Set( self, "parryTime", -1 ); - if ( self->client->NPC_class == CLASS_DESANN ) - {//less for Desann - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*50; - } - else if ( self->NPC->rank >= RANK_LT_JG ) - { - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*100;//300 - } - else +void NPC_Jedi_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + // FIXME: base the actual aggression add/subtract on health? + // FIXME: don't do this more than once per frame? + // FIXME: when take pain, stop force gripping....? + if (other->s.weapon == WP_SABER) { // back off + TIMER_Set(self, "parryTime", -1); + if (self->client->NPC_class == CLASS_DESANN) { // less for Desann + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 50; + } else if (self->NPC->rank >= RANK_LT_JG) { + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 100; // 300 + } else { + self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_spskill->integer) * 200; // 500 + } + if (!Q_irand(0, 3)) { // ouch... maybe switch up which saber power level we're using + Jedi_AdjustSaberAnimLevel(self, Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3)); + } + if (!Q_irand(0, 1)) // damage > 20 || self->health < 40 || { - self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_spskill->integer)*200;//500 + // Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); + Jedi_Aggression(self, -1); } - if ( !Q_irand( 0, 3 ) ) - {//ouch... maybe switch up which saber power level we're using - Jedi_AdjustSaberAnimLevel( self, Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ) ); - } - if ( !Q_irand( 0, 1 ) )//damage > 20 || self->health < 40 || - { - //Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); - Jedi_Aggression( self, -1 ); - } - if ( d_JediAI->integer ) - { - gi.Printf( "(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time+500 ); + if (d_JediAI->integer) { + gi.Printf("(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time + 500); } - //for testing only - // Figure out what quadrant the hit was in. - if ( d_JediAI->integer ) - { - vec3_t diff, fwdangles, right; + // for testing only + // Figure out what quadrant the hit was in. + if (d_JediAI->integer) { + vec3_t diff, fwdangles, right; - VectorSubtract( point, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(point, self->client->renderInfo.eyePoint, diff); diff[2] = 0; fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); float rightdot = DotProduct(right, diff); float zdiff = point[2] - self->client->renderInfo.eyePoint[2]; - gi.Printf( "(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2]-self->absmin[2],zdiff,rightdot); + gi.Printf("(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2] - self->absmin[2], zdiff, rightdot); } - } - else - {//attack - //Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); - Jedi_Aggression( self, 1 ); + } else { // attack + // Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); + Jedi_Aggression(self, 1); } self->NPC->enemyCheckDebounceTime = 0; - WP_ForcePowerStop( self, FP_GRIP ); + WP_ForcePowerStop(self, FP_GRIP); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } - //drop me from the ceiling if I'm on it - if ( Jedi_WaitingAmbush( self ) ) - { + // drop me from the ceiling if I'm on it + if (Jedi_WaitingAmbush(self)) { self->client->noclip = qfalse; } - if ( self->client->ps.legsAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.legsAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } -qboolean Jedi_CheckDanger( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue ); - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner - || !level.alertEvents[alertEvent].owner->client - || (level.alertEvents[alertEvent].owner!=NPC&&level.alertEvents[alertEvent].owner->client->playerTeam!=NPC->client->playerTeam) ) - {//no owner +qboolean Jedi_CheckDanger(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue); + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != NPC && level.alertEvents[alertEvent].owner->client->playerTeam != NPC->client->playerTeam)) { // no owner return qfalse; } - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } return qfalse; } extern int g_crosshairEntNum; -qboolean Jedi_CheckAmbushPlayer( void ) -{ - if ( !player || !player->client ) - { +qboolean Jedi_CheckAmbushPlayer(void) { + if (!player || !player->client) { return qfalse; } - if ( !NPC_ValidEnemy( player ) ) - { + if (!NPC_ValidEnemy(player)) { return qfalse; } - if ( NPC->client->ps.powerups[PW_CLOAKED] || g_crosshairEntNum != NPC->s.number ) - {//if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... - if ( !gi.inPVS( player->currentOrigin, NPC->currentOrigin ) ) - {//must be in same room + if (NPC->client->ps.powerups[PW_CLOAKED] || + g_crosshairEntNum != NPC->s.number) { // if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... + if (!gi.inPVS(player->currentOrigin, NPC->currentOrigin)) { // must be in same room return qfalse; - } - else - { - if ( !NPC->client->ps.powerups[PW_CLOAKED] ) - { - NPC_SetLookTarget( NPC, 0, 0 ); + } else { + if (!NPC->client->ps.powerups[PW_CLOAKED]) { + NPC_SetLookTarget(NPC, 0, 0); } } - float target_dist, zDiff = NPC->currentOrigin[2]-player->currentOrigin[2]; - if ( zDiff <= 0 || zDiff > 512 ) - {//never ambush if they're above me or way way below me + float target_dist, zDiff = NPC->currentOrigin[2] - player->currentOrigin[2]; + if (zDiff <= 0 || zDiff > 512) { // never ambush if they're above me or way way below me return qfalse; } - //If the target is this close, then wake up regardless - if ( (target_dist = DistanceHorizontalSquared( player->currentOrigin, NPC->currentOrigin )) > 4096 ) - {//closer than 64 - always ambush - if ( target_dist > 147456 ) - {//> 384, not close enough to ambush + // If the target is this close, then wake up regardless + if ((target_dist = DistanceHorizontalSquared(player->currentOrigin, NPC->currentOrigin)) > 4096) { // closer than 64 - always ambush + if (target_dist > 147456) { //> 384, not close enough to ambush return qfalse; } - //Check FOV first - if ( NPC->client->ps.powerups[PW_CLOAKED] ) - { - if ( InFOV( player, NPC, 30, 90 ) == qfalse ) - { + // Check FOV first + if (NPC->client->ps.powerups[PW_CLOAKED]) { + if (InFOV(player, NPC, 30, 90) == qfalse) { return qfalse; } - } - else - { - if ( InFOV( player, NPC, 45, 90 ) == qfalse ) - { + } else { + if (InFOV(player, NPC, 45, 90) == qfalse) { return qfalse; } } } - if ( !NPC_ClearLOS( player ) ) - { + if (!NPC_ClearLOS(player)) { return qfalse; } } - G_SetEnemy( NPC, player ); + G_SetEnemy(NPC, player); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } -void Jedi_Ambush( gentity_t *self ) -{ +void Jedi_Ambush(gentity_t *self) { self->client->noclip = qfalse; - self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + self->client->ps.pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = NPC->client->ps.torsoAnimTimer; self->client->ps.saberActive = qtrue; - Jedi_Decloak( self ); - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 1000 ); + Jedi_Decloak(self); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 1000); } -qboolean Jedi_WaitingAmbush( gentity_t *self ) -{ - if ( (self->spawnflags&JSF_AMBUSH) && self->client->noclip ) - { +qboolean Jedi_WaitingAmbush(gentity_t *self) { + if ((self->spawnflags & JSF_AMBUSH) && self->client->noclip) { return qtrue; } return qfalse; @@ -4677,63 +3714,50 @@ Jedi_Patrol ------------------------- */ -static void Jedi_Patrol( void ) -{ +static void Jedi_Patrol(void) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( Jedi_WaitingAmbush( NPC ) ) - {//hiding on the ceiling - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - {//look for enemies - if ( Jedi_CheckAmbushPlayer() || Jedi_CheckDanger() ) - {//found him! - Jedi_Ambush( NPC ); - NPC_UpdateAngles( qtrue, qtrue ); + if (Jedi_WaitingAmbush(NPC)) { // hiding on the ceiling + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { // look for enemies + if (Jedi_CheckAmbushPlayer() || Jedi_CheckDanger()) { // found him! + Jedi_Ambush(NPC); + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES )//NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//look for enemies + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) // NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + { // look for enemies gentity_t *best_enemy = NULL; - float best_enemy_dist = Q3_INFINITE; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { + float best_enemy_dist = Q3_INFINITE; + for (int i = 0; i < ENTITYNUM_WORLD; i++) { gentity_t *enemy = &g_entities[i]; - float enemy_dist; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPC->client->enemyTeam ) - { - if ( gi.inPVS( NPC->currentOrigin, enemy->currentOrigin ) ) - {//we could potentially see him - enemy_dist = DistanceSquared( NPC->currentOrigin, enemy->currentOrigin ); - if ( enemy->s.number == 0 || enemy_dist < best_enemy_dist ) - { - //if the enemy is close enough, or threw his saber, take him as the enemy - //FIXME: what if he throws a thermal detonator? - if ( enemy_dist < (220*220) || ( NPCInfo->investigateCount>= 3 && NPC->client->ps.saberActive ) ) - { - G_SetEnemy( NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + float enemy_dist; + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && enemy->client->playerTeam == NPC->client->enemyTeam) { + if (gi.inPVS(NPC->currentOrigin, enemy->currentOrigin)) { // we could potentially see him + enemy_dist = DistanceSquared(NPC->currentOrigin, enemy->currentOrigin); + if (enemy->s.number == 0 || enemy_dist < best_enemy_dist) { + // if the enemy is close enough, or threw his saber, take him as the enemy + // FIXME: what if he throws a thermal detonator? + if (enemy_dist < (220 * 220) || (NPCInfo->investigateCount >= 3 && NPC->client->ps.saberActive)) { + G_SetEnemy(NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCInfo->stats.aggression = 3; break; - } - else if ( enemy->client->ps.saberInFlight && enemy->client->ps.saberActive ) - {//threw his saber, see if it's heading toward me and close enough to consider a threat - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (enemy->client->ps.saberInFlight && + enemy->client->ps.saberActive) { // threw his saber, see if it's heading toward me and close enough to consider a threat + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[enemy->client->ps.saberEntityNum]; - VectorSubtract( NPC->currentOrigin, saber->currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 200 ) - {//incoming! - G_SetEnemy( NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + VectorSubtract(NPC->currentOrigin, saber->currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 200) { // incoming! + G_SetEnemy(NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCInfo->stats.aggression = 3; break; } @@ -4745,108 +3769,78 @@ static void Jedi_Patrol( void ) } } } - if ( !NPC->enemy ) - {//still not mad - if ( !best_enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); + if (!NPC->enemy) { // still not mad + if (!best_enemy) { + // Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); Jedi_AggressionErosion(-1); - //FIXME: what about alerts? But not if ignore alerts - } - else - {//have one to consider - if ( NPC_ClearLOS( best_enemy ) ) - {//we have a clear (of architecture) LOS to him - if ( best_enemy->s.number ) - {//just attack - G_SetEnemy( NPC, best_enemy ); + // FIXME: what about alerts? But not if ignore alerts + } else { // have one to consider + if (NPC_ClearLOS(best_enemy)) { // we have a clear (of architecture) LOS to him + if (best_enemy->s.number) { // just attack + G_SetEnemy(NPC, best_enemy); NPCInfo->stats.aggression = 3; - } - else - {//the player, toy with him - //get progressively more interested over time - if ( TIMER_Done( NPC, "watchTime" ) ) - {//we want to pick him up in stages - if ( TIMER_Get( NPC, "watchTime" ) == -1 ) - {//this is the first time, we'll ignore him for a couple seconds - TIMER_Set( NPC, "watchTime", Q_irand( 3000, 5000 ) ); + } else { // the player, toy with him + // get progressively more interested over time + if (TIMER_Done(NPC, "watchTime")) { // we want to pick him up in stages + if (TIMER_Get(NPC, "watchTime") == -1) { // this is the first time, we'll ignore him for a couple seconds + TIMER_Set(NPC, "watchTime", Q_irand(3000, 5000)); goto finish; - } - else - {//okay, we've ignored him, now start to notice him - if ( !NPCInfo->investigateCount ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_JDETECTED1, EV_JDETECTED3 ), 3000 ); + } else { // okay, we've ignored him, now start to notice him + if (!NPCInfo->investigateCount) { + G_AddVoiceEvent(NPC, Q_irand(EV_JDETECTED1, EV_JDETECTED3), 3000); } NPCInfo->investigateCount++; - TIMER_Set( NPC, "watchTime", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "watchTime", Q_irand(4000, 10000)); } } - //while we're waiting, do what we need to do - if ( best_enemy_dist < (440*440) || NPCInfo->investigateCount >= 2 ) - {//stage three: keep facing him - NPC_FaceEntity( best_enemy, qtrue ); - if ( best_enemy_dist < (330*330) ) - {//stage four: turn on the saber - if ( !NPC->client->ps.saberInFlight ) - { + // while we're waiting, do what we need to do + if (best_enemy_dist < (440 * 440) || NPCInfo->investigateCount >= 2) { // stage three: keep facing him + NPC_FaceEntity(best_enemy, qtrue); + if (best_enemy_dist < (330 * 330)) { // stage four: turn on the saber + if (!NPC->client->ps.saberInFlight) { NPC->client->ps.saberActive = qtrue; } } - } - else if ( best_enemy_dist < (550*550) || NPCInfo->investigateCount == 1 ) - {//stage two: stop and face him every now and then - if ( TIMER_Done( NPC, "watchTime" ) ) - { - NPC_FaceEntity( best_enemy, qtrue ); + } else if (best_enemy_dist < (550 * 550) || NPCInfo->investigateCount == 1) { // stage two: stop and face him every now and then + if (TIMER_Done(NPC, "watchTime")) { + NPC_FaceEntity(best_enemy, qtrue); } - } - else - {//stage one: look at him. - NPC_SetLookTarget( NPC, best_enemy->s.number, 0 ); + } else { // stage one: look at him. + NPC_SetLookTarget(NPC, best_enemy->s.number, 0); } } - } - else if ( TIMER_Done( NPC, "watchTime" ) ) - {//haven't seen him in a bit, clear the lookTarget - NPC_ClearLookTarget( NPC ); + } else if (TIMER_Done(NPC, "watchTime")) { // haven't seen him in a bit, clear the lookTarget + NPC_ClearLookTarget(NPC); } } } } finish: - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - //Jedi_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); + // Jedi_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPC->enemy ) - {//just picked one up - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (NPC->enemy) { // just picked one up + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); } } -qboolean Jedi_CanPullBackSaber( gentity_t *self ) -{ - if ( self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done( self, "parryTime" ) ) - { +qboolean Jedi_CanPullBackSaber(gentity_t *self) { + if (self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done(self, "parryTime")) { return qfalse; } - if ( self->client->NPC_class == CLASS_SHADOWTROOPER - || self->client->NPC_class == CLASS_TAVION - || self->client->NPC_class == CLASS_LUKE - || self->client->NPC_class == CLASS_DESANN ) - { + if (self->client->NPC_class == CLASS_SHADOWTROOPER || self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_LUKE || + self->client->NPC_class == CLASS_DESANN) { return qtrue; } - if ( self->painDebounceTime > level.time )//|| self->client->ps.weaponTime > 0 ) + if (self->painDebounceTime > level.time) //|| self->client->ps.weaponTime > 0 ) { return qfalse; } @@ -4858,39 +3852,33 @@ qboolean Jedi_CanPullBackSaber( gentity_t *self ) NPC_BSJedi_FollowLeader ------------------------- */ -void NPC_BSJedi_FollowLeader( void ) -{ +void NPC_BSJedi_FollowLeader(void) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( !NPC->enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); + if (!NPC->enemy) { + // Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); Jedi_AggressionErosion(-1); } - //did we drop our saber? If so, go after it! - if ( NPC->client->ps.saberInFlight ) - {//saber is not in hand - if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground, try to pick it up... - if ( Jedi_CanPullBackSaber( NPC ) ) - { - //FIXME: if it's on the ground and we just pulled it back to us, should we + // did we drop our saber? If so, go after it! + if (NPC->client->ps.saberInFlight) { // saber is not in hand + if (NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0) // player is 0 + { // + if (g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground, try to pick it up... + if (Jedi_CanPullBackSaber(NPC)) { + // FIXME: if it's on the ground and we just pulled it back to us, should we // stand still for a bit to make sure it gets to us...? // otherwise we could end up running away from it while it's on its // way back to us and we could lose it again. NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCInfo->goalEntity = &g_entities[NPC->client->ps.saberEntityNum]; ucmd.buttons |= BUTTON_ATTACK; - if ( NPC->enemy && NPC->enemy->health > 0 ) - {//get our saber back NOW! - if ( !NPC_MoveToGoal( qtrue ) )//Jedi_Move( NPCInfo->goalEntity, qfalse ); - {//can't nav to it, try jumping to it - NPC_FaceEntity( NPCInfo->goalEntity, qtrue ); - Jedi_TryJump( NPCInfo->goalEntity ); + if (NPC->enemy && NPC->enemy->health > 0) { // get our saber back NOW! + if (!NPC_MoveToGoal(qtrue)) // Jedi_Move( NPCInfo->goalEntity, qfalse ); + { // can't nav to it, try jumping to it + NPC_FaceEntity(NPCInfo->goalEntity, qtrue); + Jedi_TryJump(NPCInfo->goalEntity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } @@ -4898,141 +3886,106 @@ void NPC_BSJedi_FollowLeader( void ) } } - if ( NPCInfo->goalEntity ) - { - trace_t trace; + if (NPCInfo->goalEntity) { + trace_t trace; - if ( Jedi_Jumping( NPCInfo->goalEntity ) ) - {//in mid-jump + if (Jedi_Jumping(NPCInfo->goalEntity)) { // in mid-jump return; } - if ( !NAV_CheckAhead( NPC, NPCInfo->goalEntity->currentOrigin, trace, ( NPC->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - {//can't get straight to him - if ( NPC_ClearLOS( NPCInfo->goalEntity ) && NPC_FaceEntity( NPCInfo->goalEntity, qtrue ) ) - {//no line of sight - if ( Jedi_TryJump( NPCInfo->goalEntity ) ) - {//started a jump + if (!NAV_CheckAhead(NPC, NPCInfo->goalEntity->currentOrigin, trace, (NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { // can't get straight to him + if (NPC_ClearLOS(NPCInfo->goalEntity) && NPC_FaceEntity(NPCInfo->goalEntity, qtrue)) { // no line of sight + if (Jedi_TryJump(NPCInfo->goalEntity)) { // started a jump return; } } } - if ( NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//try to jump to the blockedDest - if ( fabs(NPCInfo->blockedDest[2]-NPC->currentOrigin[2]) > 64 ) - { - gentity_t *tempGoal = G_Spawn();//ugh, this is NOT good...? - G_SetOrigin( tempGoal, NPCInfo->blockedDest ); - gi.linkentity( tempGoal ); - TIMER_Set( NPC, "jumpChaseDebounce", -1 ); - if ( Jedi_TryJump( tempGoal ) ) - {//going to jump to the dest - G_FreeEntity( tempGoal ); + if (NPCInfo->aiFlags & NPCAI_BLOCKED) { // try to jump to the blockedDest + if (fabs(NPCInfo->blockedDest[2] - NPC->currentOrigin[2]) > 64) { + gentity_t *tempGoal = G_Spawn(); // ugh, this is NOT good...? + G_SetOrigin(tempGoal, NPCInfo->blockedDest); + gi.linkentity(tempGoal); + TIMER_Set(NPC, "jumpChaseDebounce", -1); + if (Jedi_TryJump(tempGoal)) { // going to jump to the dest + G_FreeEntity(tempGoal); return; } - G_FreeEntity( tempGoal ); + G_FreeEntity(tempGoal); } } } - //try normal movement + // try normal movement NPC_BSFollowLeader(); } - /* ------------------------- Jedi_Attack ------------------------- */ -static void Jedi_Attack( void ) -{ - //Don't do anything if we're in a pain anim - if ( NPC->painDebounceTime > level.time ) - { - if ( Q_irand( 0, 1 ) ) - { - Jedi_FaceEnemy( qtrue ); +static void Jedi_Attack(void) { + // Don't do anything if we're in a pain anim + if (NPC->painDebounceTime > level.time) { + if (Q_irand(0, 1)) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( NPC->client->ps.saberLockTime > level.time ) - { - //FIXME: maybe if I'm losing I should try to force-push out of it? Very rarely, though... - if ( NPC->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 - && NPC->client->ps.saberLockTime < level.time + 5000 - && !Q_irand( 0, 10 )) - { - ForceThrow( NPC, qfalse ); + if (NPC->client->ps.saberLockTime > level.time) { + // FIXME: maybe if I'm losing I should try to force-push out of it? Very rarely, though... + if (NPC->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && NPC->client->ps.saberLockTime < level.time + 5000 && !Q_irand(0, 10)) { + ForceThrow(NPC, qfalse); } - //based on my skill, hit attack button every other to every several frames in order to push enemy back - else - { + // based on my skill, hit attack button every other to every several frames in order to push enemy back + else { float chance; - if ( NPC->client->NPC_class == CLASS_DESANN ) - { - if ( g_spskill->integer ) - { - chance = 4.0f;//he pushes *hard* - } - else - { - chance = 3.0f;//he pushes *hard* + if (NPC->client->NPC_class == CLASS_DESANN) { + if (g_spskill->integer) { + chance = 4.0f; // he pushes *hard* + } else { + chance = 3.0f; // he pushes *hard* } - } - else if ( NPC->client->NPC_class == CLASS_TAVION ) - { - chance = 2.0f+g_spskill->value;//from 2 to 4 - } - else - {//the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard - float maxChance = (float)(RANK_LT)/2.0f+3.0f;//5? - if ( !g_spskill->value ) - { - chance = (float)(NPCInfo->rank)/2.0f; - } - else - { - chance = (float)(NPCInfo->rank)/2.0f+1.0f; + } else if (NPC->client->NPC_class == CLASS_TAVION) { + chance = 2.0f + g_spskill->value; // from 2 to 4 + } else { // the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard + float maxChance = (float)(RANK_LT) / 2.0f + 3.0f; // 5? + if (!g_spskill->value) { + chance = (float)(NPCInfo->rank) / 2.0f; + } else { + chance = (float)(NPCInfo->rank) / 2.0f + 1.0f; } - if ( chance > maxChance ) - { + if (chance > maxChance) { chance = maxChance; } } - if ( Q_flrand( -4.0f, chance ) >= 0.0f && !(NPC->client->ps.pm_flags&PMF_ATTACK_HELD) ) - { + if (Q_flrand(-4.0f, chance) >= 0.0f && !(NPC->client->ps.pm_flags & PMF_ATTACK_HELD)) { ucmd.buttons |= BUTTON_ATTACK; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - //did we drop our saber? If so, go after it! - if ( NPC->client->ps.saberInFlight ) - {//saber is not in hand - if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground, try to pick it up - if ( Jedi_CanPullBackSaber( NPC ) ) - { + // did we drop our saber? If so, go after it! + if (NPC->client->ps.saberInFlight) { // saber is not in hand + if (NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0) // player is 0 + { // + if (g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground, try to pick it up + if (Jedi_CanPullBackSaber(NPC)) { NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCInfo->goalEntity = &g_entities[NPC->client->ps.saberEntityNum]; ucmd.buttons |= BUTTON_ATTACK; - if ( NPC->enemy && NPC->enemy->health > 0 ) - {//get our saber back NOW! - Jedi_Move( NPCInfo->goalEntity, qfalse ); - NPC_UpdateAngles( qtrue, qtrue ); - if ( NPC->enemy->s.weapon == WP_SABER ) - {//be sure to continue evasion - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); + if (NPC->enemy && NPC->enemy->health > 0) { // get our saber back NOW! + Jedi_Move(NPCInfo->goalEntity, qfalse); + NPC_UpdateAngles(qtrue, qtrue); + if (NPC->enemy->s.weapon == WP_SABER) { // be sure to continue evasion + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); } return; } @@ -5040,157 +3993,132 @@ static void Jedi_Attack( void ) } } } - //see if our enemy was killed by us, gloat and turn off saber after cool down. - //FIXME: don't do this if we have other enemies to fight...? - if ( NPC->enemy ) - { - if ( NPC->enemy->health <= 0 && NPC->enemy->enemy == NPC && NPC->client->playerTeam != TEAM_PLAYER )//good guys don't gloat - {//my enemy is dead and I killed him - NPCInfo->enemyCheckDebounceTime = 0;//keep looking for others - if ( !TIMER_Done( NPC, "parryTime" ) ) - { - TIMER_Set( NPC, "parryTime", -1 ); + // see if our enemy was killed by us, gloat and turn off saber after cool down. + // FIXME: don't do this if we have other enemies to fight...? + if (NPC->enemy) { + if (NPC->enemy->health <= 0 && NPC->enemy->enemy == NPC && NPC->client->playerTeam != TEAM_PLAYER) // good guys don't gloat + { // my enemy is dead and I killed him + NPCInfo->enemyCheckDebounceTime = 0; // keep looking for others + if (!TIMER_Done(NPC, "parryTime")) { + TIMER_Set(NPC, "parryTime", -1); NPC->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( NPC->client->ps.saberActive || NPC->client->ps.saberInFlight ) - {//saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy - //FIXME: need to stop this from happening over and over again when they're blocking their victim's saber - //FIXME: turn off saber sooner so we get cool walk anim? - //Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); + if (NPC->client->ps.saberActive || + NPC->client->ps.saberInFlight) { // saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy + // FIXME: need to stop this from happening over and over again when they're blocking their victim's saber + // FIXME: turn off saber sooner so we get cool walk anim? + // Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); Jedi_AggressionErosion(-3); - if ( !NPC->client->ps.saberActive && !NPC->client->ps.saberInFlight ) - {//turned off saber (in hand), gloat - G_AddVoiceEvent( NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); + if (!NPC->client->ps.saberActive && !NPC->client->ps.saberInFlight) { // turned off saber (in hand), gloat + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); jediSpeechDebounceTime[NPC->client->playerTeam] = level.time + 3000; NPCInfo->desiredPitch = 0; NPCInfo->goalEntity = NULL; } - TIMER_Set( NPC, "gloatTime", 10000 ); + TIMER_Set(NPC, "gloatTime", 10000); } - if ( NPC->client->ps.saberActive || NPC->client->ps.saberInFlight || !TIMER_Done( NPC, "gloatTime" ) ) - {//keep walking - if ( DistanceHorizontalSquared( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin ) > 4096 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + if (NPC->client->ps.saberActive || NPC->client->ps.saberInFlight || !TIMER_Done(NPC, "gloatTime")) { // keep walking + if (DistanceHorizontalSquared(NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin) > 4096 && + (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCInfo->goalEntity = NPC->enemy; - Jedi_Move( NPC->enemy, qfalse ); + Jedi_Move(NPC->enemy, qfalse); ucmd.buttons |= BUTTON_WALKING; + } else { // got there } - else - {//got there - } - Jedi_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + Jedi_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //If we don't have an enemy, just idle - if ( NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPC->enemy->classname ) ) - { - if ( NPC->enemy->count <= 0 ) - {//it's out of ammo - if ( NPC->enemy->activator && NPC_ValidEnemy( NPC->enemy->activator ) ) - { + // If we don't have an enemy, just idle + if (NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPC->enemy->classname)) { + if (NPC->enemy->count <= 0) { // it's out of ammo + if (NPC->enemy->activator && NPC_ValidEnemy(NPC->enemy->activator)) { gentity_t *turretOwner = NPC->enemy->activator; - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, turretOwner ); - } - else - { - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); + G_SetEnemy(NPC, turretOwner); + } else { + G_ClearEnemy(NPC); } } } - NPC_CheckEnemy( qtrue, qtrue ); + NPC_CheckEnemy(qtrue, qtrue); - if ( !NPC->enemy ) - { + if (!NPC->enemy) { NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - Jedi_Patrol();//was calling Idle... why? + Jedi_Patrol(); // was calling Idle... why? return; } - //always face enemy if have one + // always face enemy if have one NPCInfo->combatMove = qtrue; - //Track the player and kill them if possible + // Track the player and kill them if possible Jedi_Combat(); - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//this is really stupid, but okay... + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // this is really stupid, but okay... ucmd.forwardmove = 0; ucmd.rightmove = 0; - if ( ucmd.upmove > 0 ) - { + if (ucmd.upmove > 0) { ucmd.upmove = 0; } NPC->client->ps.forceJumpCharge = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//don't push while in air, throws off jumps! - //FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // don't push while in air, throws off jumps! + // FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? ucmd.forwardmove = 0; ucmd.rightmove = 0; - VectorClear( NPC->client->ps.moveDir ); + VectorClear(NPC->client->ps.moveDir); } - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } - if ( PM_SaberInBrokenParry( NPC->client->ps.saberMove ) || NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - {//just make sure they don't pull their saber to them if they're being blocked + if (PM_SaberInBrokenParry(NPC->client->ps.saberMove) || + NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { // just make sure they don't pull their saber to them if they're being blocked ucmd.buttons &= ~BUTTON_ATTACK; } - if( (NPCInfo->scriptFlags&SCF_DONT_FIRE) //not allowed to attack - || ((NPC->client->ps.saberEventFlags&SEF_INWATER)&&!NPC->client->ps.saberInFlight) )//saber in water + if ((NPCInfo->scriptFlags & SCF_DONT_FIRE) // not allowed to attack + || ((NPC->client->ps.saberEventFlags & SEF_INWATER) && !NPC->client->ps.saberInFlight)) // saber in water { - ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); } - if ( NPCInfo->scriptFlags&SCF_NO_ACROBATICS ) - { + if (NPCInfo->scriptFlags & SCF_NO_ACROBATICS) { ucmd.upmove = 0; NPC->client->ps.forceJumpCharge = 0; } Jedi_CheckDecreaseSaberAnimLevel(); - if ( ucmd.buttons & BUTTON_ATTACK && NPC->client->playerTeam == TEAM_ENEMY ) - { - if ( Q_irand( 0, NPC->client->ps.saberAnimLevel ) > 0 - && Q_irand( 0, NPC->max_health+10 ) > NPC->health - && !Q_irand( 0, 3 )) - {//the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing - G_AddVoiceEvent( NPC, Q_irand( EV_COMBAT1, EV_COMBAT3 ), 1000 ); - } - } - - if ( NPC->client->NPC_class == CLASS_TAVION - || (g_spskill->integer && ( NPC->client->NPC_class == CLASS_DESANN || NPCInfo->rank >= Q_irand( RANK_CREWMAN, RANK_CAPTAIN )))) - {//Tavion will kick in force speed if the player does... - if ( NPC->enemy - && !NPC->enemy->s.number - && NPC->enemy->client - && (NPC->enemy->client->ps.forcePowersActive & (1<client->ps.forcePowersActive & (1<client->playerTeam == TEAM_ENEMY) { + if (Q_irand(0, NPC->client->ps.saberAnimLevel) > 0 && Q_irand(0, NPC->max_health + 10) > NPC->health && + !Q_irand(0, 3)) { // the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing + G_AddVoiceEvent(NPC, Q_irand(EV_COMBAT1, EV_COMBAT3), 1000); + } + } + + if (NPC->client->NPC_class == CLASS_TAVION || + (g_spskill->integer && (NPC->client->NPC_class == CLASS_DESANN || + NPCInfo->rank >= Q_irand(RANK_CREWMAN, RANK_CAPTAIN)))) { // Tavion will kick in force speed if the player does... + if (NPC->enemy && !NPC->enemy->s.number && NPC->enemy->client && (NPC->enemy->client->ps.forcePowersActive & (1 << FP_SPEED)) && + !(NPC->client->ps.forcePowersActive & (1 << FP_SPEED))) { int chance = 0; - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: chance = 9; break; @@ -5201,43 +4129,40 @@ static void Jedi_Attack( void ) chance = 1; break; } - if ( !Q_irand( 0, chance ) ) - { - ForceSpeed( NPC ); + if (!Q_irand(0, chance)) { + ForceSpeed(NPC); } } } } -void NPC_BSJedi_Default( void ) -{ +void NPC_BSJedi_Default(void) { Jedi_CheckCloak(); - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one Jedi_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy - if ( Jedi_WaitingAmbush( NPC ) ) - {//we were still waiting to drop down - must have had enemy set on me outside my AI - Jedi_Ambush( NPC ); + } else // if ( NPC->enemy ) + { // have an enemy + if (Jedi_WaitingAmbush(NPC)) { // we were still waiting to drop down - must have had enemy set on me outside my AI + Jedi_Ambush(NPC); } Jedi_Attack(); - //if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch if needbe... - if ( ((!ucmd.buttons&&!NPC->client->ps.forcePowersActive)||(NPC->enemy&&NPC->enemy->health<=0)) && NPCInfo->enemyCheckDebounceTime < level.time ) - {//not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), not using force powers and it's time to look again - //FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain their own list and we just access it? - gentity_t *sav_enemy = NPC->enemy;//FIXME: what about NPC->lastEnemy? + // if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch + // if needbe... + if (((!ucmd.buttons && !NPC->client->ps.forcePowersActive) || (NPC->enemy && NPC->enemy->health <= 0)) && + NPCInfo->enemyCheckDebounceTime < level.time) { // not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), not + // using force powers and it's time to look again + // FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when + // to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain + // their own list and we just access it? + gentity_t *sav_enemy = NPC->enemy; // FIXME: what about NPC->lastEnemy? NPC->enemy = NULL; - gentity_t *newEnemy = NPC_CheckEnemy( - (qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse ); + gentity_t *newEnemy = NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse, qfalse); NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPC->lastEnemy = NPC->enemy; - G_SetEnemy( NPC, newEnemy ); + G_SetEnemy(NPC, newEnemy); } - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 3000 ); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 3000); } } } \ No newline at end of file diff --git a/codeJK2/game/AI_Mark1.cpp b/codeJK2/game/AI_Mark1.cpp index 7c9bdaddb9..123f02f7c7 100644 --- a/codeJK2/game/AI_Mark1.cpp +++ b/codeJK2/game/AI_Mark1.cpp @@ -23,29 +23,28 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -#define LEFT_ARM_HEALTH 40 -#define RIGHT_ARM_HEALTH 40 -#define AMMO_POD_HEALTH 40 +#define LEFT_ARM_HEALTH 40 +#define RIGHT_ARM_HEALTH 40 +#define AMMO_POD_HEALTH 40 -#define BOWCASTER_VELOCITY 1300 -#define BOWCASTER_NPC_DAMAGE_EASY 12 -#define BOWCASTER_NPC_DAMAGE_NORMAL 24 -#define BOWCASTER_NPC_DAMAGE_HARD 36 -#define BOWCASTER_SIZE 2 -#define BOWCASTER_SPLASH_DAMAGE 0 -#define BOWCASTER_SPLASH_RADIUS 0 +#define BOWCASTER_VELOCITY 1300 +#define BOWCASTER_NPC_DAMAGE_EASY 12 +#define BOWCASTER_NPC_DAMAGE_NORMAL 24 +#define BOWCASTER_NPC_DAMAGE_HARD 36 +#define BOWCASTER_SIZE 2 +#define BOWCASTER_SPLASH_DAMAGE 0 +#define BOWCASTER_SPLASH_RADIUS 0 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -56,41 +55,40 @@ enum LSTATE_FIRED4, }; -qboolean NPC_CheckPlayerTeamStealth( void ); -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +qboolean NPC_CheckPlayerTeamStealth(void); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); void Mark1_BlasterAttack(qboolean advance); -void DeathFX( gentity_t *ent ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +void DeathFX(gentity_t *ent); +extern gitem_t *FindItemForAmmo(ammo_t ammo); /* ------------------------- NPC_Mark1_Precache ------------------------- */ -void NPC_Mark1_Precache(void) -{ - G_SoundIndex( "sound/chars/mark1/misc/mark1_wakeup"); - G_SoundIndex( "sound/chars/mark1/misc/shutdown"); - G_SoundIndex( "sound/chars/mark1/misc/walk"); - G_SoundIndex( "sound/chars/mark1/misc/run"); - G_SoundIndex( "sound/chars/mark1/misc/death1"); - G_SoundIndex( "sound/chars/mark1/misc/death2"); - G_SoundIndex( "sound/chars/mark1/misc/anger"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_fire"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_pain"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_explo"); - -// G_EffectIndex( "small_chunks"); - G_EffectIndex( "env/med_explode2"); - G_EffectIndex( "probeexplosion1"); - G_EffectIndex( "blaster/smoke_bolton"); - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "droidexplosion1" ); - - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( FindItemForWeapon( WP_BOWCASTER )); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); +void NPC_Mark1_Precache(void) { + G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup"); + G_SoundIndex("sound/chars/mark1/misc/shutdown"); + G_SoundIndex("sound/chars/mark1/misc/walk"); + G_SoundIndex("sound/chars/mark1/misc/run"); + G_SoundIndex("sound/chars/mark1/misc/death1"); + G_SoundIndex("sound/chars/mark1/misc/death2"); + G_SoundIndex("sound/chars/mark1/misc/anger"); + G_SoundIndex("sound/chars/mark1/misc/mark1_fire"); + G_SoundIndex("sound/chars/mark1/misc/mark1_pain"); + G_SoundIndex("sound/chars/mark1/misc/mark1_explo"); + + // G_EffectIndex( "small_chunks"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("probeexplosion1"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("droidexplosion1"); + + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(FindItemForWeapon(WP_BOWCASTER)); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); } /* @@ -98,25 +96,21 @@ void NPC_Mark1_Precache(void) NPC_Mark1_Part_Explode ------------------------- */ -void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark1_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - bolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( "env/med_explode2", org, dir ); + G_PlayEffect("env/med_explode2", org, dir); } - G_PlayEffect( "blaster/smoke_bolton", self->playerModel, bolt, self->s.number ); + G_PlayEffect("blaster/smoke_bolton", self->playerModel, bolt, self->s.number); } /* @@ -124,12 +118,11 @@ void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) Mark1_Idle ------------------------- */ -void Mark1_Idle( void ) -{ +void Mark1_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL); } /* @@ -138,32 +131,29 @@ Mark1Dead_FireRocket - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireRocket (void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,muzzle_dir; +void Mark1Dead_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, muzzle_dir; - int damage = 50; + int damage = 50; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt5, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, muzzle_dir); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - gentity_t *missile = CreateMissile( muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC ); + gentity_t *missile = CreateMissile(muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -174,7 +164,6 @@ void Mark1Dead_FireRocket (void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -183,28 +172,25 @@ Mark1Dead_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireBlaster (void) -{ - vec3_t muzzle1,muzzle_dir; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1Dead_FireBlaster(void) { + vec3_t muzzle1, muzzle_dir; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; - bolt = NPC->genericBolt1; + bolt = NPC->genericBolt1; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, muzzle_dir); - missile = CreateMissile( muzzle1, muzzle_dir, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, muzzle_dir, 1600, 10000, NPC); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -213,7 +199,6 @@ void Mark1Dead_FireBlaster (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -221,14 +206,13 @@ void Mark1Dead_FireBlaster (void) Mark1_die ------------------------- */ -void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Mark1_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { /* int anim; // Is he dead already? anim = self->client->ps.legsAnim; - if (((anim==BOTH_DEATH1) || (anim==BOTH_DEATH2)) && (self->client->ps.torsoAnimTimer==0)) + if (((anim==BOTH_DEATH1) || (anim==BOTH_DEATH2)) && (self->client->ps.torsoAnimTimer==0)) { // This is because self->health keeps getting zeroed out. HL_NONE acts as health in this case. self->locationDamage[HL_NONE] += damage; if (self->locationDamage[HL_NONE] > 50) @@ -244,16 +228,13 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } */ - G_Sound( self, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav",Q_irand( 1, 2)))); + G_Sound(self, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav", Q_irand(1, 2)))); // Choose a death anim - if (Q_irand( 1, 10) > 5) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (Q_irand(1, 10) > 5) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } @@ -262,68 +243,58 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int Mark1_dying ------------------------- */ -void Mark1_dying( gentity_t *self ) -{ - int num,newBolt; +void Mark1_dying(gentity_t *self) { + int num, newBolt; - if (self->client->ps.torsoAnimTimer>0) - { - if (TIMER_Done(self,"dyingExplosion")) - { - num = Q_irand( 1, 3); + if (self->client->ps.torsoAnimTimer > 0) { + if (TIMER_Done(self, "dyingExplosion")) { + num = Q_irand(1, 3); // Find place to generate explosion - if (num == 1) - { - num = Q_irand( 8, 10); - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*flash%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - } - else - { - num = Q_irand( 1, 6); - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",num), TURN_OFF ); + if (num == 1) { + num = Q_irand(8, 10); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*flash%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + } else { + num = Q_irand(1, 6); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*torso_tube%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_tube%d", num), TURN_OFF); } - TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1000 ) ); + TIMER_Set(self, "dyingExplosion", Q_irand(300, 1000)); } - -// int dir; -// vec3_t right; + // int dir; + // vec3_t right; // Shove to the side -// AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); -// VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); + // AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); + // VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); // See which weapons are there // Randomly fire blaster - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) // Is the blaster still on the model? + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm")) // Is the blaster still on the model? { - if (Q_irand( 1, 5) == 1) - { + if (Q_irand(1, 5) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireBlaster(); RestoreNPCGlobals(); } } // Randomly fire rocket - if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" )) // Is the rocket still on the model? + if (!gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_arm")) // Is the rocket still on the model? { - if (Q_irand( 1, 10) == 1) - { + if (Q_irand(1, 10) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireRocket(); RestoreNPCGlobals(); } } } - } /* @@ -332,69 +303,58 @@ NPC_Mark1_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark1_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - int newBolt,i,chance; - - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_Mark1_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + int newBolt, i, chance; - G_Sound( self, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); + NPC_Pain(self, inflictor, other, point, damage, mod); + + G_Sound(self, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); // Hit in the CHEST??? - if (hitLoc==HL_CHEST) - { - chance = Q_irand( 1, 4); - - if ((chance == 1) && (damage > 5)) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (hitLoc == HL_CHEST) { + chance = Q_irand(1, 4); + + if ((chance == 1) && (damage > 5)) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } // Hit in the left arm? - else if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) - { - if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? + else if ((hitLoc == HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { + if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash3" ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash3"); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm", TURN_OFF); } } // Hit in the right arm? - else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? + else if ((hitLoc == HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash4" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); - NPC_Mark1_Part_Explode( self, newBolt ); + if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash4"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "r_arm", TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "r_arm", TURN_OFF); } } // Check ammo pods - else - { - for (i=0;i<6;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + else { + for (i = 0; i < 6; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("*torso_tube%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",(i+1)), TURN_OFF ); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_tube%d", (i + 1)), TURN_OFF); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); break; } } @@ -402,12 +362,10 @@ void NPC_Mark1_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, ve } // Are both guns shot off? - if ((gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) && - (gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" ))) - { - G_Damage(self,NULL,NULL,NULL,NULL,self->health,0,MOD_UNKNOWN); + if ((gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "l_arm")) && + (gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "r_arm"))) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, 0, MOD_UNKNOWN); } - } /* @@ -416,18 +374,16 @@ Mark1_Hunt - look for enemy. -------------------------` */ -void Mark1_Hunt(void) -{ +void Mark1_Hunt(void) { - if ( NPCInfo->goalEntity == NULL ) - { + if (NPCInfo->goalEntity == NULL) { NPCInfo->goalEntity = NPC->enemy; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -436,60 +392,47 @@ Mark1_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; // Which muzzle to fire from? - if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) - { + if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) { NPCInfo->localState = LSTATE_FIRED1; - bolt = NPC->genericBolt1; - } - else if (NPCInfo->localState == LSTATE_FIRED1) - { + bolt = NPC->genericBolt1; + } else if (NPCInfo->localState == LSTATE_FIRED1) { NPCInfo->localState = LSTATE_FIRED2; - bolt = NPC->genericBolt2; - } - else if (NPCInfo->localState == LSTATE_FIRED2) - { + bolt = NPC->genericBolt2; + } else if (NPCInfo->localState == LSTATE_FIRED2) { NPCInfo->localState = LSTATE_FIRED3; - bolt = NPC->genericBolt3; - } - else - { + bolt = NPC->genericBolt3; + } else { NPCInfo->localState = LSTATE_FIRED4; - bolt = NPC->genericBolt4; + bolt = NPC->genericBolt4; } - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, forward); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -498,7 +441,6 @@ void Mark1_FireBlaster(void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -506,57 +448,47 @@ void Mark1_FireBlaster(void) Mark1_BlasterAttack ------------------------- */ -void Mark1_BlasterAttack(qboolean advance ) -{ +void Mark1_BlasterAttack(qboolean advance) { int chance; - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - chance = Q_irand( 1, 5); - + chance = Q_irand(1, 5); + NPCInfo->burstCount++; - if (NPCInfo->burstCount<3) // Too few shots this burst? + if (NPCInfo->burstCount < 3) // Too few shots this burst? { - chance = 2; // Force it to keep firing. - } - else if (NPCInfo->burstCount>12) // Too many shots fired this burst? + chance = 2; // Force it to keep firing. + } else if (NPCInfo->burstCount > 12) // Too many shots fired this burst? { NPCInfo->burstCount = 0; - chance = 1; // Force it to stop firing. + chance = 1; // Force it to stop firing. } // Stop firing. - if (chance == 1) - { + if (chance == 1) { NPCInfo->burstCount = 0; - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. - } - else - { - if (TIMER_Done( NPC, "attackDelay2" )) // Can't be shooting every frame. + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. + } else { + if (TIMER_Done(NPC, "attackDelay2")) // Can't be shooting every frame. { - TIMER_Set( NPC, "attackDelay2", Q_irand( 50, 50) ); + TIMER_Set(NPC, "attackDelay2", Q_irand(50, 50)); Mark1_FireBlaster(); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } return; } - } - else if (advance) - { - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. + } else if (advance) { + if (NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. } Mark1_Hunt(); - } - else // Make sure he's not firing. + } else // Make sure he's not firing. { - if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. + if (NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPC->client->ps.torsoAnimTimer = 0; // Just in case the firing anim is running. } } } @@ -566,37 +498,34 @@ void Mark1_BlasterAttack(qboolean advance ) Mark1_FireRocket ------------------------- */ -void Mark1_FireRocket(void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; +void Mark1_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; - int damage = 50; + int damage = 50; - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt5, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); -// G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); + // G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire" )); + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - gentity_t *missile = CreateMissile( muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC ); + gentity_t *missile = CreateMissile(muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -607,7 +536,6 @@ void Mark1_FireRocket(void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -615,16 +543,13 @@ void Mark1_FireRocket(void) Mark1_RocketAttack ------------------------- */ -void Mark1_RocketAttack( qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Mark1_RocketAttack(qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); Mark1_FireRocket(); - } - else if (advance) - { + } else if (advance) { Mark1_Hunt(); } } @@ -634,73 +559,59 @@ void Mark1_RocketAttack( qboolean advance ) Mark1_AttackDecision ------------------------- */ -void Mark1_AttackDecision( void ) -{ - int blasterTest,rocketTest; - - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); +void Mark1_AttackDecision(void) { + int blasterTest, rocketTest; + + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // Enemy is dead or he has no enemy. - if ((NPC->enemy->health<1) || ( NPC_CheckEnemyExt() == qfalse )) - { + if ((NPC->enemy->health < 1) || (NPC_CheckEnemyExt() == qfalse)) { NPC->enemy = NULL; return; } // Rate our distance to the target and visibility - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + distance_e distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { Mark1_Hunt(); return; } // See if the side weapons are there - blasterTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "l_arm" ); - rocketTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "r_arm" ); + blasterTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "l_arm"); + rocketTest = gi.G2API_GetSurfaceRenderStatus(&NPC->ghoul2[NPC->playerModel], "r_arm"); // It has both side weapons - if (!blasterTest && !rocketTest) - { - ; // So do nothing. - } - else if (blasterTest) - { + if (!blasterTest && !rocketTest) { + ; // So do nothing. + } else if (blasterTest) { distRate = DIST_LONG; - } - else if (rocketTest) - { + } else if (rocketTest) { distRate = DIST_MELEE; - } - else // It should never get here, but just in case - { + } else // It should never get here, but just in case + { NPC->health = 0; NPC->client->ps.stats[STAT_HEALTH] = 0; GEntity_DieFunc(NPC, NPC, NPC, 100, MOD_UNKNOWN); } // We can see enemy so shoot him if timers let you. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (distRate == DIST_MELEE) - { + if (distRate == DIST_MELEE) { Mark1_BlasterAttack(advance); - } - else if (distRate == DIST_LONG) - { + } else if (distRate == DIST_LONG) { Mark1_RocketAttack(advance); } } @@ -710,57 +621,45 @@ void Mark1_AttackDecision( void ) Mark1_Patrol ------------------------- */ -void Mark1_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark1_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_Sound(NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk -// if (TIMER_Done(NPC,"patrolNoise")) -// { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); -// -// TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); -// } + // randomly talk + // if (TIMER_Done(NPC,"patrolNoise")) + // { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // + // TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + // } } - } - /* ------------------------- NPC_BSMark1_Default ------------------------- */ -void NPC_BSMark1_Default( void ) -{ - //NPC->e_DieFunc = dieF_Mark1_die; +void NPC_BSMark1_Default(void) { + // NPC->e_DieFunc = dieF_Mark1_die; - if ( NPC->enemy ) - { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; Mark1_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark1_Patrol(); - } - else - { + } else { Mark1_Idle(); } } \ No newline at end of file diff --git a/codeJK2/game/AI_Mark2.cpp b/codeJK2/game/AI_Mark2.cpp index 8d37ddcccc..9c7ea8aba3 100644 --- a/codeJK2/game/AI_Mark2.cpp +++ b/codeJK2/game/AI_Mark2.cpp @@ -25,44 +25,42 @@ along with this program; if not, see . #include "g_nav.h" //#define AMMO_POD_HEALTH 40 -#define AMMO_POD_HEALTH 1 -#define TURN_OFF 0x00000100 +#define AMMO_POD_HEALTH 1 +#define TURN_OFF 0x00000100 -#define VELOCITY_DECAY 0.25 -#define MAX_DISTANCE 256 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) -#define MIN_DISTANCE 24 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define VELOCITY_DECAY 0.25 +#define MAX_DISTANCE 256 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) +#define MIN_DISTANCE 24 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +extern gitem_t *FindItemForAmmo(ammo_t ammo); -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_DROPPINGDOWN, LSTATE_DOWN, LSTATE_RISINGUP, }; -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void NPC_Mark2_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" );// blows up on death - G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_fire" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); +void NPC_Mark2_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // blows up on death + G_SoundIndex("sound/chars/mark2/misc/mark2_pain"); + G_SoundIndex("sound/chars/mark2/misc/mark2_fire"); + G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); - G_EffectIndex( "droidexplosion1" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "bryar/muzzle_flash" ); + G_EffectIndex("droidexplosion1"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( FindItemForAmmo( AMMO_POWERCELL )); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(FindItemForAmmo(AMMO_POWERCELL)); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } /* @@ -70,27 +68,23 @@ void NPC_Mark2_Precache( void ) NPC_Mark2_Part_Explode ------------------------- */ -void NPC_Mark2_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark2_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - bolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, dir); - G_PlayEffect( "env/med_explode2", org, dir ); + G_PlayEffect("env/med_explode2", org, dir); } - G_PlayEffect( "blaster/smoke_bolton", self->playerModel, bolt, self->s.number); + G_PlayEffect("blaster/smoke_bolton", self->playerModel, bolt, self->s.number); - self->count++; // Count of pods blown off + self->count++; // Count of pods blown off } /* @@ -99,35 +93,30 @@ NPC_Mark2_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark2_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - int newBolt,i; - - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_Mark2_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + int newBolt, i; - for (i=0;i<3;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + NPC_Pain(self, inflictor, other, point, damage, mod); + + for (i = 0; i < 3; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark2_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], va("torso_canister%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark2_Part_Explode(self, newBolt); } - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)), TURN_OFF ); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], va("torso_canister%d", (i + 1)), TURN_OFF); break; } } } - G_Sound( self, G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" )); + G_Sound(self, G_SoundIndex("sound/chars/mark2/misc/mark2_pain")); // If any pods were blown off, kill him - if (self->count > 0) - { - G_Damage( self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN ); + if (self->count > 0) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } } @@ -136,18 +125,16 @@ void NPC_Mark2_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, ve Mark2_Hunt ------------------------- */ -void Mark2_Hunt(void) -{ - if ( NPCInfo->goalEntity == NULL ) - { +void Mark2_Hunt(void) { + if (NPCInfo->goalEntity == NULL) { NPCInfo->goalEntity = NPC->enemy; } // Turn toward him before moving towards him. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -155,37 +142,31 @@ void Mark2_Hunt(void) Mark2_FireBlaster ------------------------- */ -void Mark2_FireBlaster(qboolean advance) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - NPC->genericBolt1, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); - - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); - - if (NPC->health) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPC->currentAngles, forward, vright, up); +void Mark2_FireBlaster(qboolean advance) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, NPC->genericBolt1, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, + (cg.time ? cg.time : level.time), NULL, NPC->s.modelScale); + + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle1); + + if (NPC->health) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPC->currentAngles, forward, vright, up); } - G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle1, forward); - G_Sound( NPC, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); + G_Sound(NPC, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -194,7 +175,6 @@ void Mark2_FireBlaster(qboolean advance) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -202,23 +182,18 @@ void Mark2_FireBlaster(qboolean advance) Mark2_BlasterAttack ------------------------- */ -void Mark2_BlasterAttack(qboolean advance) -{ - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? +void Mark2_BlasterAttack(qboolean advance) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - if (NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. + if (NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2000) ); - } - else - { - TIMER_Set( NPC, "attackDelay", Q_irand( 100, 500) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2000)); + } else { + TIMER_Set(NPC, "attackDelay", Q_irand(100, 500)); } Mark2_FireBlaster(advance); return; - } - else if (advance) - { + } else if (advance) { Mark2_Hunt(); } } @@ -228,118 +203,97 @@ void Mark2_BlasterAttack(qboolean advance) Mark2_AttackDecision ------------------------- */ -void Mark2_AttackDecision( void ) -{ - NPC_FaceEnemy( qtrue ); +void Mark2_AttackDecision(void) { + NPC_FaceEnemy(qtrue); - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // He's been ordered to get up - if (NPCInfo->localState == LSTATE_RISINGUP) - { + if (NPCInfo->localState == LSTATE_RISINGUP) { NPC->flags &= ~FL_SHIELDED; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - if ((NPC->client->ps.legsAnimTimer==0) && - NPC->client->ps.torsoAnim == BOTH_RUN1START ) - { - NPCInfo->localState = LSTATE_NONE; // He's up again. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + if ((NPC->client->ps.legsAnimTimer == 0) && NPC->client->ps.torsoAnim == BOTH_RUN1START) { + NPCInfo->localState = LSTATE_NONE; // He's up again. } return; } // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { // If he's going down or is down, make him get up - if ((NPCInfo->localState == LSTATE_DOWN) || (NPCInfo->localState == LSTATE_DROPPINGDOWN)) - { - if ( TIMER_Done( NPC, "downTime" ) ) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) + if ((NPCInfo->localState == LSTATE_DOWN) || (NPCInfo->localState == LSTATE_DROPPINGDOWN)) { + if (TIMER_Done(NPC, "downTime")) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) { NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - } - else - { + } else { Mark2_Hunt(); } return; } // He's down but he could advance if he wants to. - if ((advance) && (TIMER_Done( NPC, "downTime" )) && (NPCInfo->localState == LSTATE_DOWN)) - { + if ((advance) && (TIMER_Done(NPC, "downTime")) && (NPCInfo->localState == LSTATE_DOWN)) { NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Dropping down to shoot - if (NPCInfo->localState == LSTATE_DROPPINGDOWN) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPC, "downTime", Q_irand( 3000, 9000) ); + if (NPCInfo->localState == LSTATE_DROPPINGDOWN) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPC, "downTime", Q_irand(3000, 9000)); - if ((NPC->client->ps.legsAnimTimer==0) && NPC->client->ps.torsoAnim == BOTH_RUN1STOP ) - { + if ((NPC->client->ps.legsAnimTimer == 0) && NPC->client->ps.torsoAnim == BOTH_RUN1STOP) { NPC->flags |= FL_SHIELDED; NPCInfo->localState = LSTATE_DOWN; } } // He's down and shooting - else if (NPCInfo->localState == LSTATE_DOWN) - { -// NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles + else if (NPCInfo->localState == LSTATE_DOWN) { + // NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles Mark2_BlasterAttack(qfalse); - } - else if (TIMER_Done( NPC, "runTime" )) // Lowering down to attack. But only if he's done running at you. + } else if (TIMER_Done(NPC, "runTime")) // Lowering down to attack. But only if he's done running at you. { NPCInfo->localState = LSTATE_DROPPINGDOWN; - } - else if (advance) - { + } else if (advance) { // We can see enemy so shoot him if timer lets you. Mark2_BlasterAttack(advance); } } - /* ------------------------- Mark2_Patrol ------------------------- */ -void Mark2_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { -// G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark2_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + // G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } } @@ -349,29 +303,20 @@ void Mark2_Patrol( void ) Mark2_Idle ------------------------- */ -void Mark2_Idle( void ) -{ - NPC_BSIdle(); -} +void Mark2_Idle(void) { NPC_BSIdle(); } /* ------------------------- NPC_BSMark2_Default ------------------------- */ -void NPC_BSMark2_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSMark2_Default(void) { + if (NPC->enemy) { NPCInfo->goalEntity = NPC->enemy; Mark2_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark2_Patrol(); - } - else - { + } else { Mark2_Idle(); } } diff --git a/codeJK2/game/AI_MineMonster.cpp b/codeJK2/game/AI_MineMonster.cpp index eac149a7cb..8be7d72d6b 100644 --- a/codeJK2/game/AI_MineMonster.cpp +++ b/codeJK2/game/AI_MineMonster.cpp @@ -20,227 +20,184 @@ along with this program; if not, see . =========================================================================== */ #include "g_headers.h" - + #include "b_local.h" -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 /* ------------------------- NPC_MineMonster_Precache ------------------------- */ -void NPC_MineMonster_Precache( void ) -{ - for ( int i = 0; i < 4; i++ ) - { - G_SoundIndex( va("sound/chars/mine/misc/bite%i.wav", i+1 )); - G_SoundIndex( va("sound/chars/mine/misc/miss%i.wav", i+1 )); +void NPC_MineMonster_Precache(void) { + for (int i = 0; i < 4; i++) { + G_SoundIndex(va("sound/chars/mine/misc/bite%i.wav", i + 1)); + G_SoundIndex(va("sound/chars/mine/misc/miss%i.wav", i + 1)); } } - /* ------------------------- MineMonster_Idle ------------------------- */ -void MineMonster_Idle( void ) -{ - if ( UpdateGoal() ) - { +void MineMonster_Idle(void) { + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - /* ------------------------- MineMonster_Patrol ------------------------- */ -void MineMonster_Patrol( void ) -{ +void MineMonster_Patrol(void) { NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPC, "patrolTime" )) - { - TIMER_Set( NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPC, "patrolTime")) { + TIMER_Set(NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } vec3_t dif; - VectorSubtract( g_entities[0].currentOrigin, NPC->currentOrigin, dif ); + VectorSubtract(g_entities[0].currentOrigin, NPC->currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { MineMonster_Idle(); return; } } - + /* ------------------------- MineMonster_Move ------------------------- */ -void MineMonster_Move( qboolean visible ) -{ - if ( NPCInfo->localState != LSTATE_WAITING ) - { +void MineMonster_Move(qboolean visible) { + if (NPCInfo->localState != LSTATE_WAITING) { NPCInfo->goalEntity = NPC->enemy; - NPC_MoveToGoal( qtrue ); - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -void MineMonster_TryDamage( gentity_t *enemy, int damage ) -{ - vec3_t end, dir; - trace_t tr; +void MineMonster_TryDamage(gentity_t *enemy, int damage) { + vec3_t end, dir; + trace_t tr; - if ( !enemy ) - { + if (!enemy) { return; } - AngleVectors( NPC->client->ps.viewangles, dir, NULL, NULL ); - VectorMA( NPC->currentOrigin, MIN_DISTANCE, dir, end ); + AngleVectors(NPC->client->ps.viewangles, dir, NULL, NULL); + VectorMA(NPC->currentOrigin, MIN_DISTANCE, dir, end); // Should probably trace from the mouth, but, ah well. - gi.trace( &tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE ) - { - G_Damage( &g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - G_SoundOnEnt( NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/bite%i.wav", Q_irand(1,4))); - } - else - { - G_SoundOnEnt( NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/miss%i.wav", Q_irand(1,4))); + if (tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE) { + G_Damage(&g_entities[tr.entityNum], NPC, NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + G_SoundOnEnt(NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/bite%i.wav", Q_irand(1, 4))); + } else { + G_SoundOnEnt(NPC, CHAN_VOICE_ATTEN, va("sound/chars/mine/misc/miss%i.wav", Q_irand(1, 4))); } } //------------------------------ -void MineMonster_Attack( void ) -{ - if ( !TIMER_Exists( NPC, "attacking" )) - { +void MineMonster_Attack(void) { + if (!TIMER_Exists(NPC, "attacking")) { // usually try and play a jump attack if the player somehow got above them....or just really rarely - if ( NPC->enemy && ((NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f ) - || Q_flrand(0.0f, 1.0f) > 0.8f )) - { + if (NPC->enemy && ((NPC->enemy->currentOrigin[2] - NPC->currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f) || Q_flrand(0.0f, 1.0f) > 0.8f)) { // Going to do ATTACK4 - TIMER_Set( NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack2_dmg", 950 ); // level two damage - } - else if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - if ( Q_flrand(0.0f, 1.0f) > 0.8f ) - { + TIMER_Set(NPC, "attack2_dmg", 950); // level two damage + } else if (Q_flrand(0.0f, 1.0f) > 0.5f) { + if (Q_flrand(0.0f, 1.0f) > 0.8f) { // Going to do ATTACK3, (rare) - TIMER_Set( NPC, "attacking", 850 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 850); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack2_dmg", 400 ); // level two damage - } - else - { + TIMER_Set(NPC, "attack2_dmg", 400); // level two damage + } else { // Going to do ATTACK1 - TIMER_Set( NPC, "attacking", 850 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 850); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack1_dmg", 450 ); // level one damage + TIMER_Set(NPC, "attack1_dmg", 450); // level one damage } - } - else - { + } else { // Going to do ATTACK2 - TIMER_Set( NPC, "attacking", 1250 ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPC, "attacking", 1250); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPC, "attack1_dmg", 700 ); // level one damage + TIMER_Set(NPC, "attack1_dmg", 700); // level one damage } - } - else - { + } else { // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPC, "attack1_dmg", qtrue )) - { - MineMonster_TryDamage( NPC->enemy, 5 ); - } - else if ( TIMER_Done2( NPC, "attack2_dmg", qtrue )) - { - MineMonster_TryDamage( NPC->enemy, 10 ); + if (TIMER_Done2(NPC, "attack1_dmg", qtrue)) { + MineMonster_TryDamage(NPC->enemy, 5); + } else if (TIMER_Done2(NPC, "attack2_dmg", qtrue)) { + MineMonster_TryDamage(NPC->enemy, 10); } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPC, "attacking", qtrue ); + TIMER_Done2(NPC, "attacking", qtrue); } //---------------------------------- -void MineMonster_Combat( void ) -{ +void MineMonster_Combat(void) { // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS(NPC->enemy) || UpdateGoal()) { NPCInfo->combatMove = qtrue; NPCInfo->goalEntity = NPC->enemy; - NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - qboolean advance = (qboolean)( distance > MIN_DISTANCE_SQR ? qtrue : qfalse ); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR ? qtrue : qfalse); - if (( advance || NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPC, "takingPain", qtrue)) { NPCInfo->localState = LSTATE_CLEAR; + } else { + MineMonster_Move(qtrue); } - else - { - MineMonster_Move( qtrue ); - } - } - else - { + } else { MineMonster_Attack(); } } @@ -250,48 +207,38 @@ void MineMonster_Combat( void ) NPC_MineMonster_Pain ------------------------- */ -void NPC_MineMonster_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); +void NPC_MineMonster_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->max_health * 100.0f)); - if ( damage >= 10 ) - { - TIMER_Remove( self, "attacking" ); - TIMER_Remove( self, "attacking1_dmg" ); - TIMER_Remove( self, "attacking2_dmg" ); - TIMER_Set( self, "takingPain", 1350 ); + if (damage >= 10) { + TIMER_Remove(self, "attacking"); + TIMER_Remove(self, "attacking1_dmg"); + TIMER_Remove(self, "attacking2_dmg"); + TIMER_Set(self, "takingPain", 1350); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } - /* ------------------------- NPC_BSMineMonster_Default ------------------------- */ -void NPC_BSMineMonster_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSMineMonster_Default(void) { + if (NPC->enemy) { MineMonster_Combat(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { MineMonster_Patrol(); - } - else - { + } else { MineMonster_Idle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codeJK2/game/AI_Remote.cpp b/codeJK2/game/AI_Remote.cpp index 520ffdb65e..22a5093925 100644 --- a/codeJK2/game/AI_Remote.cpp +++ b/codeJK2/game/AI_Remote.cpp @@ -24,25 +24,22 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -void Remote_Strafe( void ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +void Remote_Strafe(void); -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f - -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, }; -void Remote_Idle( void ); +void Remote_Idle(void); -void NPC_Remote_Precache(void) -{ +void NPC_Remote_Precache(void) { G_SoundIndex("sound/chars/remote/misc/fire.wav"); - G_SoundIndex( "sound/chars/remote/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/remote/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } /* @@ -50,14 +47,13 @@ void NPC_Remote_Precache(void) NPC_Remote_Pain ------------------------- */ -void NPC_Remote_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_Remote_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Remote_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); } /* @@ -65,122 +61,103 @@ void NPC_Remote_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, v Remote_MaintainHeight ------------------------- */ -void Remote_MaintainHeight( void ) -{ - float dif; +void Remote_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPC->client->ps.velocity[2] ) - { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPC->enemy ) - { - if (TIMER_Done( NPC, "heightChange")) - { - TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPC->enemy) { + if (TIMER_Done(NPC, "heightChange")) { + TIMER_Set(NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + Q_irand( 0, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + Q_irand(0, NPC->enemy->maxs[2] + 8)) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); } dif *= 10; - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; NPC->fx_time = level.time; - G_Sound( NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + G_Sound(NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } -#define REMOTE_STRAFE_VEL 256 -#define REMOTE_STRAFE_DIS 200 -#define REMOTE_UPWARD_PUSH 32 +#define REMOTE_STRAFE_VEL 256 +#define REMOTE_STRAFE_DIS 200 +#define REMOTE_UPWARD_PUSH 32 /* ------------------------- Remote_Strafe ------------------------- */ -void Remote_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Remote_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, REMOTE_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, REMOTE_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPC->client->ps.velocity); - G_Sound( NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + G_Sound(NPC, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); // Add a slight upward push NPC->client->ps.velocity[2] += REMOTE_UPWARD_PUSH; @@ -191,83 +168,74 @@ void Remote_Strafe( void ) } } -#define REMOTE_FORWARD_BASE_SPEED 10 -#define REMOTE_FORWARD_MULTIPLIER 5 +#define REMOTE_FORWARD_BASE_SPEED 10 +#define REMOTE_FORWARD_MULTIPLIER 5 /* ------------------------- Remote_Hunt ------------------------- */ -void Remote_Hunt( qboolean visible, qboolean advance, qboolean retreat ) -{ - float distance, speed; - vec3_t forward; +void Remote_Hunt(qboolean visible, qboolean advance, qboolean retreat) { + float distance, speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Remote_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse && visible == qtrue ) + // If we don't want to advance, stop here + if (advance == qfalse && visible == qtrue) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = REMOTE_FORWARD_BASE_SPEED + REMOTE_FORWARD_MULTIPLIER * g_spskill->integer; - if ( retreat == qtrue ) - { + if (retreat == qtrue) { speed *= -1; } - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } - /* ------------------------- Remote_Fire ------------------------- */ -void Remote_Fire (void) -{ - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; - static vec3_t forward, vright, up; - gentity_t *missile; +void Remote_Fire(void) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; + static vec3_t forward, vright, up; + gentity_t *missile; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorCopy( NPC->currentOrigin, muzzle1 ); - - VectorSubtract (enemy_org1, muzzle1, delta1); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org1); + VectorCopy(NPC->currentOrigin, muzzle1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + VectorSubtract(enemy_org1, muzzle1, delta1); - missile = CreateMissile( NPC->currentOrigin, forward, 1000, 10000, NPC ); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - G_PlayEffect( "bryar/muzzle_flash", NPC->currentOrigin, forward ); + missile = CreateMissile(NPC->currentOrigin, forward, 1000, 10000, NPC); + + G_PlayEffect("bryar/muzzle_flash", NPC->currentOrigin, forward); missile->classname = "briar"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -276,7 +244,6 @@ void Remote_Fire (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -284,69 +251,61 @@ void Remote_Fire (void) Remote_Ranged ------------------------- */ -void Remote_Ranged( qboolean visible, qboolean advance, qboolean retreat ) -{ +void Remote_Ranged(qboolean visible, qboolean advance, qboolean retreat) { - if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 3000)); Remote_Fire(); } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); } } -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) /* ------------------------- Remote_Attack ------------------------- */ -void Remote_Attack( void ) -{ - if ( TIMER_Done(NPC,"spin") ) - { - TIMER_Set( NPC, "spin", Q_irand( 250, 1500 ) ); - NPCInfo->desiredYaw += Q_irand( -200, 200 ); +void Remote_Attack(void) { + if (TIMER_Done(NPC, "spin")) { + TIMER_Set(NPC, "spin", Q_irand(250, 1500)); + NPCInfo->desiredYaw += Q_irand(-200, 200); } // Always keep a good height off the ground Remote_MaintainHeight(); // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Remote_Idle(); return; } // Rate our distance to the target, and our visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); -// distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - qboolean visible = NPC_ClearLOS( NPC->enemy ); - float idealDist = MIN_DISTANCE_SQR+(MIN_DISTANCE_SQR*Q_flrand( 0, 1 )); - qboolean advance = (qboolean)(distance > idealDist*1.25); - qboolean retreat = (qboolean)(distance < idealDist*0.75); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + // distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; + qboolean visible = NPC_ClearLOS(NPC->enemy); + float idealDist = MIN_DISTANCE_SQR + (MIN_DISTANCE_SQR * Q_flrand(0, 1)); + qboolean advance = (qboolean)(distance > idealDist * 1.25); + qboolean retreat = (qboolean)(distance < idealDist * 0.75); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); return; } } - Remote_Ranged( visible, advance, retreat ); - + Remote_Ranged(visible, advance, retreat); } /* @@ -354,8 +313,7 @@ void Remote_Attack( void ) Remote_Idle ------------------------- */ -void Remote_Idle( void ) -{ +void Remote_Idle(void) { Remote_MaintainHeight(); NPC_BSIdle(); @@ -366,42 +324,32 @@ void Remote_Idle( void ) Remote_Patrol ------------------------- */ -void Remote_Patrol( void ) -{ +void Remote_Patrol(void) { Remote_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( UpdateGoal() ) - { - //start loop sound once we move + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (UpdateGoal()) { + // start loop sound once we move ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - /* ------------------------- NPC_BSRemote_Default ------------------------- */ -void NPC_BSRemote_Default( void ) -{ - if ( NPC->enemy ) - { +void NPC_BSRemote_Default(void) { + if (NPC->enemy) { Remote_Attack(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Remote_Patrol(); - } - else - { + } else { Remote_Idle(); } } \ No newline at end of file diff --git a/codeJK2/game/AI_Seeker.cpp b/codeJK2/game/AI_Seeker.cpp index e347a64234..2307b9665e 100644 --- a/codeJK2/game/AI_Seeker.cpp +++ b/codeJK2/game/AI_Seeker.cpp @@ -24,108 +24,91 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void Seeker_Strafe( void ); +void Seeker_Strafe(void); -#define VELOCITY_DECAY 0.7f +#define VELOCITY_DECAY 0.7f -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SEEKER_STRAFE_VEL 100 -#define SEEKER_STRAFE_DIS 200 -#define SEEKER_UPWARD_PUSH 32 +#define SEEKER_STRAFE_VEL 100 +#define SEEKER_STRAFE_DIS 200 +#define SEEKER_UPWARD_PUSH 32 -#define SEEKER_FORWARD_BASE_SPEED 10 -#define SEEKER_FORWARD_MULTIPLIER 2 +#define SEEKER_FORWARD_BASE_SPEED 10 +#define SEEKER_FORWARD_MULTIPLIER 2 -#define SEEKER_SEEK_RADIUS 1024 +#define SEEKER_SEEK_RADIUS 1024 //------------------------------------ -void NPC_Seeker_Precache(void) -{ +void NPC_Seeker_Precache(void) { G_SoundIndex("sound/chars/seeker/misc/fire.wav"); - G_SoundIndex( "sound/chars/seeker/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/seeker/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } //------------------------------------ -void NPC_Seeker_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( !(self->svFlags & SVF_CUSTOM_GRAVITY )) - {//void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod, int hitLoc=HL_NONE ); - G_Damage( self, NULL, NULL, (float*)vec3_origin, (float*)vec3_origin, 999, 0, MOD_FALLING ); +void NPC_Seeker_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + if (!(self->svFlags & SVF_CUSTOM_GRAVITY)) { // void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int + // damage, int dflags, int mod, int hitLoc=HL_NONE ); + G_Damage(self, NULL, NULL, (float *)vec3_origin, (float *)vec3_origin, 999, 0, MOD_FALLING); } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Seeker_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); } //------------------------------------ -void Seeker_MaintainHeight( void ) -{ - float dif; +void Seeker_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPC->enemy ) - { - if (TIMER_Done( NPC, "heightChange" )) - { - TIMER_Set( NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPC->enemy) { + if (TIMER_Done(NPC, "heightChange")) { + TIMER_Set(NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPC->enemy->currentOrigin[2] + Q_flrand( NPC->enemy->maxs[2]/2, NPC->enemy->maxs[2]+8 )) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + Q_flrand(NPC->enemy->maxs[2] / 2, NPC->enemy->maxs[2] + 8)) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } @@ -134,84 +117,74 @@ void Seeker_MaintainHeight( void ) } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } } //------------------------------------ -void Seeker_Strafe( void ) -{ - int side; - vec3_t end, right, dir; - trace_t tr; - - if ( Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client ) - { +void Seeker_Strafe(void) { + int side; + vec3_t end, right, dir; + trace_t tr; + + if (Q_flrand(0.0f, 1.0f) > 0.7f || !NPC->enemy || !NPC->enemy->client) { // Do a regular style strafe - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonably valid - side = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, SEEKER_STRAFE_DIS * side, right, end ); + side = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, SEEKER_STRAFE_DIS * side, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, SEEKER_STRAFE_VEL * side, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, SEEKER_STRAFE_VEL * side, right, NPC->client->ps.velocity); - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); // Add a slight upward push NPC->client->ps.velocity[2] += SEEKER_UPWARD_PUSH; NPCInfo->standTime = level.time + 1000 + Q_flrand(0.0f, 1.0f) * 500; } - } - else - { + } else { // Do a strafe to try and keep on the side of their enemy - AngleVectors( NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL ); + AngleVectors(NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL); // Pick a random side - side = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->enemy->currentOrigin, SEEKER_STRAFE_DIS * side, right, end ); + side = (rand() & 1) ? -1 : 1; + VectorMA(NPC->enemy->currentOrigin, SEEKER_STRAFE_DIS * side, right, end); // then add a very small bit of random in front of/behind the player action - VectorMA( end, Q_flrand(-1.0f, 1.0f) * 25, dir, end ); + VectorMA(end, Q_flrand(-1.0f, 1.0f) * 25, dir, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorSubtract( tr.endpos, NPC->currentOrigin, dir ); + if (tr.fraction > 0.9f) { + VectorSubtract(tr.endpos, NPC->currentOrigin, dir); dir[2] *= 0.25; // do less upward change - float dis = VectorNormalize( dir ); + float dis = VectorNormalize(dir); // Try to move the desired enemy side - VectorMA( NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, dis, dir, NPC->client->ps.velocity); - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); // Add a slight upward push NPC->client->ps.velocity[2] += SEEKER_UPWARD_PUSH; @@ -222,69 +195,60 @@ void Seeker_Strafe( void ) } //------------------------------------ -void Seeker_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Seeker_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Seeker_Strafe(); return; } } // If we don't want to advance, stop here - if ( advance == qfalse ) - { + if (advance == qfalse) { return; } // Only try and navigate if the player is visible - if ( visible == qfalse ) - { + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 24; // Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) - { + if (NPC_GetMoveDirection(forward, &distance) == qfalse) { return; } - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SEEKER_FORWARD_BASE_SPEED + SEEKER_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } //------------------------------------ -void Seeker_Fire( void ) -{ - vec3_t dir, enemy_org, muzzle; - gentity_t *missile; +void Seeker_Fire(void) { + vec3_t dir, enemy_org, muzzle; + gentity_t *missile; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - VectorSubtract( enemy_org, NPC->currentOrigin, dir ); - VectorNormalize( dir ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + VectorSubtract(enemy_org, NPC->currentOrigin, dir); + VectorNormalize(dir); // move a bit forward in the direction we shall shoot in so that the bolt doesn't poke out the other side of the seeker - VectorMA( NPC->currentOrigin, 15, dir, muzzle ); + VectorMA(NPC->currentOrigin, 15, dir, muzzle); - missile = CreateMissile( muzzle, dir, 1000, 10000, NPC ); + missile = CreateMissile(muzzle, dir, 1000, 10000, NPC); - G_PlayEffect( "blaster/muzzle_flash", NPC->currentOrigin, dir ); + G_PlayEffect("blaster/muzzle_flash", NPC->currentOrigin, dir); missile->classname = "blaster"; missile->s.weapon = WP_BLASTER; @@ -296,100 +260,86 @@ void Seeker_Fire( void ) } //------------------------------------ -void Seeker_Ranged( qboolean visible, qboolean advance ) -{ - if ( NPC->count > 0 ) - { - if ( TIMER_Done( NPC, "attackDelay" )) // Attack? +void Seeker_Ranged(qboolean visible, qboolean advance) { + if (NPC->count > 0) { + if (TIMER_Done(NPC, "attackDelay")) // Attack? { - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 2500 )); + TIMER_Set(NPC, "attackDelay", Q_irand(250, 2500)); Seeker_Fire(); NPC->count--; } - } - else - { + } else { // out of ammo, so let it die...give it a push up so it can fall more and blow up on impact -// NPC->client->ps.gravity = 900; -// NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; -// NPC->client->ps.velocity[2] += 16; - G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN ); + // NPC->client->ps.gravity = 900; + // NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; + // NPC->client->ps.velocity[2] += 16; + G_Damage(NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN); } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); } -} +} //------------------------------------ -void Seeker_Attack( void ) -{ +void Seeker_Attack(void) { // Always keep a good height off the ground Seeker_MaintainHeight(); // Rate our distance to the target, and our visibilty - float distance = DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); return; } } - Seeker_Ranged( visible, advance ); + Seeker_Ranged(visible, advance); } //------------------------------------ -void Seeker_FindEnemy( void ) -{ - int numFound; - float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; - vec3_t mins, maxs; - gentity_t *entityList[MAX_GENTITIES], *ent, *best = NULL; +void Seeker_FindEnemy(void) { + int numFound; + float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; + vec3_t mins, maxs; + gentity_t *entityList[MAX_GENTITIES], *ent, *best = NULL; - VectorSet( maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS); + VectorScale(maxs, -1, mins); - numFound = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numFound = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( int i = 0 ; i < numFound ; i++ ) - { + for (int i = 0; i < numFound; i++) { ent = entityList[i]; - if ( ent->s.number == NPC->s.number || !ent->client || !ent->NPC || ent->health <= 0 || !ent->inuse ) - { + if (ent->s.number == NPC->s.number || !ent->client || !ent->NPC || ent->health <= 0 || !ent->inuse) { continue; } - if ( ent->client->playerTeam == NPC->client->playerTeam || ent->client->playerTeam == TEAM_NEUTRAL ) // don't attack same team or bots + if (ent->client->playerTeam == NPC->client->playerTeam || ent->client->playerTeam == TEAM_NEUTRAL) // don't attack same team or bots { continue; } // try to find the closest visible one - if ( !NPC_ClearLOS( ent )) - { + if (!NPC_ClearLOS(ent)) { continue; } - dis = DistanceHorizontalSquared( NPC->currentOrigin, ent->currentOrigin ); + dis = DistanceHorizontalSquared(NPC->currentOrigin, ent->currentOrigin); - if ( dis <= bestDis ) - { + if (dis <= bestDis) { bestDis = dis; best = ent; } } - if ( best ) - { + if (best) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi @@ -398,72 +348,59 @@ void Seeker_FindEnemy( void ) } //------------------------------------ -void Seeker_FollowPlayer( void ) -{ +void Seeker_FollowPlayer(void) { Seeker_MaintainHeight(); - float dis = DistanceHorizontalSquared( NPC->currentOrigin, g_entities[0].currentOrigin ); - vec3_t pt, dir; - - if ( dis < MIN_DISTANCE_SQR ) - { + float dis = DistanceHorizontalSquared(NPC->currentOrigin, g_entities[0].currentOrigin); + vec3_t pt, dir; + + if (dis < MIN_DISTANCE_SQR) { // generally circle the player closely till we take an enemy..this is our target point - pt[0] = g_entities[0].currentOrigin[0] + cos( level.time * 0.001f + NPC->random ) * 56; - pt[1] = g_entities[0].currentOrigin[1] + sin( level.time * 0.001f + NPC->random ) * 56; + pt[0] = g_entities[0].currentOrigin[0] + cos(level.time * 0.001f + NPC->random) * 56; + pt[1] = g_entities[0].currentOrigin[1] + sin(level.time * 0.001f + NPC->random) * 56; pt[2] = g_entities[0].currentOrigin[2] + 40; - VectorSubtract( pt, NPC->currentOrigin, dir ); - VectorMA( NPC->client->ps.velocity, 0.8f, dir, NPC->client->ps.velocity ); - } - else - { - if ( TIMER_Done( NPC, "seekerhiss" )) - { - TIMER_Set( NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000 ); - G_Sound( NPC, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + VectorSubtract(pt, NPC->currentOrigin, dir); + VectorMA(NPC->client->ps.velocity, 0.8f, dir, NPC->client->ps.velocity); + } else { + if (TIMER_Done(NPC, "seekerhiss")) { + TIMER_Set(NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000); + G_Sound(NPC, G_SoundIndex("sound/chars/seeker/misc/hiss")); } // Hey come back! NPCInfo->goalEntity = &g_entities[0]; NPCInfo->goalRadius = 32; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); NPC->owner = &g_entities[0]; } - if ( NPCInfo->enemyCheckDebounceTime < level.time ) - { + if (NPCInfo->enemyCheckDebounceTime < level.time) { // check twice a second to find a new enemy Seeker_FindEnemy(); NPCInfo->enemyCheckDebounceTime = level.time + 500; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } //------------------------------------ -void NPC_BSSeeker_Default( void ) -{ - if ( in_camera ) - { +void NPC_BSSeeker_Default(void) { + if (in_camera) { // cameras make me commit suicide.... - G_Damage( NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN ); + G_Damage(NPC, NPC, NPC, NULL, NULL, 999, 0, MOD_UNKNOWN); } - if ( NPC->random == 0.0f ) - { + if (NPC->random == 0.0f) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi } - if ( NPC->enemy && NPC->enemy->health && NPC->enemy->inuse ) - { - if ( NPC->enemy->s.number == 0 || ( NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_SEEKER )) - { - //hacked to never take the player as an enemy, even if the player shoots at it + if (NPC->enemy && NPC->enemy->health && NPC->enemy->inuse) { + if (NPC->enemy->s.number == 0 || (NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_SEEKER)) { + // hacked to never take the player as an enemy, even if the player shoots at it NPC->enemy = NULL; - } - else - { + } else { Seeker_Attack(); return; } diff --git a/codeJK2/game/AI_Sentry.cpp b/codeJK2/game/AI_Sentry.cpp index 6d56d5163f..6a72ac8a52 100644 --- a/codeJK2/game/AI_Sentry.cpp +++ b/codeJK2/game/AI_Sentry.cpp @@ -24,25 +24,24 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); +extern gitem_t *FindItemForAmmo(ammo_t ammo); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -#define MIN_DISTANCE 256 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 256 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SENTRY_FORWARD_BASE_SPEED 10 -#define SENTRY_FORWARD_MULTIPLIER 5 +#define SENTRY_FORWARD_BASE_SPEED 10 +#define SENTRY_FORWARD_MULTIPLIER 5 -#define SENTRY_VELOCITY_DECAY 0.85f -#define SENTRY_STRAFE_VEL 256 -#define SENTRY_STRAFE_DIS 200 -#define SENTRY_UPWARD_PUSH 32 -#define SENTRY_HOVER_HEIGHT 24 +#define SENTRY_VELOCITY_DECAY 0.85f +#define SENTRY_STRAFE_VEL 256 +#define SENTRY_STRAFE_DIS 200 +#define SENTRY_UPWARD_PUSH 32 +#define SENTRY_HOVER_HEIGHT 24 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -56,24 +55,22 @@ enum NPC_Sentry_Precache ------------------------- */ -void NPC_Sentry_Precache(void) -{ - G_SoundIndex( "sound/chars/sentry/misc/sentry_explo" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_pain" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_open" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_close" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); - - for ( int i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/sentry/misc/talk%d", i ) ); +void NPC_Sentry_Precache(void) { + G_SoundIndex("sound/chars/sentry/misc/sentry_explo"); + G_SoundIndex("sound/chars/sentry/misc/sentry_pain"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_open"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_close"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); + + for (int i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/sentry/misc/talk%d", i)); } - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("env/med_explode"); - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } /* @@ -81,13 +78,12 @@ void NPC_Sentry_Precache(void) sentry_use ================ */ -void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void sentry_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); self->flags &= ~FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // self->NPC->localState = LSTATE_WAKEUP; self->NPC->localState = LSTATE_ACTIVE; } @@ -96,30 +92,28 @@ void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) NPC_Sentry_Pain ------------------------- */ -void NPC_Sentry_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - NPC_Pain( self, inflictor, other, point, damage, mod ); +void NPC_Sentry_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->burstCount = 0; - TIMER_Set( self, "attackDelay", Q_irand( 9000, 12000) ); + TIMER_Set(self, "attackDelay", Q_irand(9000, 12000)); self->flags |= FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_SoundOnEnt( self, CHAN_AUTO, "sound/chars/sentry/misc/sentry_pain" ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_SoundOnEnt(self, CHAN_AUTO, "sound/chars/sentry/misc/sentry_pain"); self->NPC->localState = LSTATE_ACTIVE; } // You got hit, go after the enemy -// if (self->NPC->localState == LSTATE_ASLEEP) -// { -// G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); -// -// self->flags &= ~FL_SHIELDED; -// NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; -// } + // if (self->NPC->localState == LSTATE_ASLEEP) + // { + // G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); + // + // self->flags &= ~FL_SHIELDED; + // NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // self->NPC->localState = LSTATE_WAKEUP; + // } } /* @@ -127,40 +121,31 @@ void NPC_Sentry_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, v Sentry_Fire ------------------------- */ -void Sentry_Fire (void) -{ - vec3_t muzzle; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Sentry_Fire(void) { + vec3_t muzzle; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; NPC->flags &= ~FL_SHIELDED; - if ( NPCInfo->localState == LSTATE_POWERING_UP ) - { - if ( TIMER_Done( NPC, "powerup" )) - { + if (NPCInfo->localState == LSTATE_POWERING_UP) { + if (TIMER_Done(NPC, "powerup")) { NPCInfo->localState = LSTATE_ATTACKING; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // can't do anything right now return; } - } - else if ( NPCInfo->localState == LSTATE_ACTIVE ) - { + } else if (NPCInfo->localState == LSTATE_ACTIVE) { NPCInfo->localState = LSTATE_POWERING_UP; - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_open" ); - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPC, "powerup", 250 ); + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_open"); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPC, "powerup", 250); return; - } - else if ( NPCInfo->localState != LSTATE_ATTACKING ) - { + } else if (NPCInfo->localState != LSTATE_ATTACKING) { // bad because we are uninitialized NPCInfo->localState = LSTATE_ACTIVE; return; @@ -168,32 +153,29 @@ void Sentry_Fire (void) // Which muzzle to fire from? int which = NPCInfo->burstCount % 3; - switch( which ) - { + switch (which) { case 0: - bolt = NPC->genericBolt1; + bolt = NPC->genericBolt1; break; case 1: - bolt = NPC->genericBolt2; + bolt = NPC->genericBolt2; break; case 2: default: - bolt = NPC->genericBolt3; + bolt = NPC->genericBolt3; } - gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, - bolt, - &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), - NULL, NPC->s.modelScale ); + gi.G2API_GetBoltMatrix(NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time ? cg.time : level.time), NULL, + NPC->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, muzzle); - AngleVectors( NPC->currentAngles, forward, vright, up ); -// G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); + AngleVectors(NPC->currentAngles, forward, vright, up); + // G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); - G_PlayEffect( "bryar/muzzle_flash", muzzle, forward ); + G_PlayEffect("bryar/muzzle_flash", muzzle, forward); - missile = CreateMissile( muzzle, forward, 1600, 10000, NPC ); + missile = CreateMissile(muzzle, forward, 1600, 10000, NPC); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -207,13 +189,10 @@ void Sentry_Fire (void) missile->damage = 5; // now scale for difficulty - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { NPC->attackDebounceTime += 200; missile->damage = 1; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { NPC->attackDebounceTime += 100; missile->damage = 3; } @@ -224,100 +203,80 @@ void Sentry_Fire (void) Sentry_MaintainHeight ------------------------- */ -void Sentry_MaintainHeight( void ) -{ - float dif; +void Sentry_MaintainHeight(void) { + float dif; - NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPC->enemy ) - { + if (NPC->enemy) { // Find the height difference - dif = (NPC->enemy->currentOrigin[2]+NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; + dif = (NPC->enemy->currentOrigin[2] + NPC->enemy->maxs[2]) - NPC->currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 8) { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + dif = (dif < 0 ? -24 : 24); } - NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2]+dif)/2; + NPC->client->ps.velocity[2] = (NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCInfo->goalEntity ) // Is there a goal? + if (NPCInfo->goalEntity) // Is there a goal? { goal = NPCInfo->goalEntity; - } - else - { + } else { goal = NPCInfo->lastGoalEntity; } - if (goal) - { + if (goal) { dif = goal->currentOrigin[2] - NPC->currentOrigin[2]; - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - ucmd.upmove = ( ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + ucmd.upmove = (ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 2) { NPC->client->ps.velocity[2] = 0; } } } } // Apply friction to Z - else if ( NPC->client->ps.velocity[2] ) - { + else if (NPC->client->ps.velocity[2]) { NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[2]) < 1) { NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPC->client->ps.velocity[0] ) - { + if (NPC->client->ps.velocity[0]) { NPC->client->ps.velocity[0] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[0]) < 1) { NPC->client->ps.velocity[0] = 0; } } - if ( NPC->client->ps.velocity[1] ) - { + if (NPC->client->ps.velocity[1]) { NPC->client->ps.velocity[1] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPC->client->ps.velocity[1]) < 1) { NPC->client->ps.velocity[1] = 0; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); } /* @@ -325,22 +284,17 @@ void Sentry_MaintainHeight( void ) Sentry_Idle ------------------------- */ -void Sentry_Idle( void ) -{ +void Sentry_Idle(void) { Sentry_MaintainHeight(); // Is he waking up? - if (NPCInfo->localState == LSTATE_WAKEUP) - { - if (NPC->client->ps.torsoAnimTimer<=0) - { + if (NPCInfo->localState == LSTATE_WAKEUP) { + if (NPC->client->ps.torsoAnimTimer <= 0) { NPCInfo->scriptFlags |= SCF_LOOK_FOR_ENEMIES; NPCInfo->burstCount = 0; } - } - else - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->flags |= FL_SHIELDED; NPC_BSIdle(); @@ -352,25 +306,23 @@ void Sentry_Idle( void ) Sentry_Strafe ------------------------- */ -void Sentry_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Sentry_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPC->currentOrigin, SENTRY_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPC->currentOrigin, SENTRY_STRAFE_DIS * dir, right, end); - gi.trace( &tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, NPC->currentOrigin, NULL, NULL, end, NPC->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPC->client->ps.velocity); // Add a slight upward push NPC->client->ps.velocity[2] += SENTRY_UPWARD_PUSH; @@ -386,45 +338,39 @@ void Sentry_Strafe( void ) Sentry_Hunt ------------------------- */ -void Sentry_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Sentry_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Sentry_Strafe(); return; } } - //If we don't want to advance, stop here - if ( !advance && visible ) + // If we don't want to advance, stop here + if (!advance && visible) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SENTRY_FORWARD_BASE_SPEED + SENTRY_FORWARD_MULTIPLIER * g_spskill->integer; - VectorMA( NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity ); + VectorMA(NPC->client->ps.velocity, speed, forward, NPC->client->ps.velocity); } /* @@ -432,35 +378,27 @@ void Sentry_Hunt( qboolean visible, qboolean advance ) Sentry_RangedAttack ------------------------- */ -void Sentry_RangedAttack( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPC, "attackDelay" ) && NPC->attackDebounceTime < level.time && visible ) // Attack? +void Sentry_RangedAttack(qboolean visible, qboolean advance) { + if (TIMER_Done(NPC, "attackDelay") && NPC->attackDebounceTime < level.time && visible) // Attack? { - if ( NPCInfo->burstCount > 6 ) - { - if ( !NPC->fly_sound_debounce_time ) - {//delay closing down to give the player an opening - NPC->fly_sound_debounce_time = level.time + Q_irand( 500, 2000 ); - } - else if ( NPC->fly_sound_debounce_time < level.time ) - { + if (NPCInfo->burstCount > 6) { + if (!NPC->fly_sound_debounce_time) { // delay closing down to give the player an opening + NPC->fly_sound_debounce_time = level.time + Q_irand(500, 2000); + } else if (NPC->fly_sound_debounce_time < level.time) { NPCInfo->localState = LSTATE_ACTIVE; NPC->fly_sound_debounce_time = NPCInfo->burstCount = 0; - TIMER_Set( NPC, "attackDelay", Q_irand( 2000, 3500) ); + TIMER_Set(NPC, "attackDelay", Q_irand(2000, 3500)); NPC->flags |= FL_SHIELDED; - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_SoundOnEnt( NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close" ); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_SoundOnEnt(NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close"); } - } - else - { + } else { Sentry_Fire(); } } - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); } } @@ -469,97 +407,85 @@ void Sentry_RangedAttack( qboolean visible, qboolean advance ) Sentry_AttackDecision ------------------------- */ -void Sentry_AttackDecision( void ) -{ +void Sentry_AttackDecision(void) { // Always keep a good height off the ground Sentry_MaintainHeight(); - NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); + NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); - //randomly talk - if ( TIMER_Done(NPC,"patrolNoise") ) - { - if (TIMER_Done(NPC,"angerNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + if (TIMER_Done(NPC, "angerNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(4000, 10000)); } } // He's dead. - if (NPC->enemy->health<1) - { + if (NPC->enemy->health < 1) { NPC->enemy = NULL; Sentry_Idle(); return; } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { + if (NPC_CheckEnemyExt() == qfalse) { Sentry_Idle(); return; } // Rate our distance to the target and visibilty - float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - qboolean visible = NPC_ClearLOS( NPC->enemy ); - qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); + float distance = (int)DistanceHorizontalSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + qboolean visible = NPC_ClearLOS(NPC->enemy); + qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); return; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - Sentry_RangedAttack( visible, advance ); + Sentry_RangedAttack(visible, advance); } -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); /* ------------------------- NPC_Sentry_Patrol ------------------------- */ -void NPC_Sentry_Patrol( void ) -{ +void NPC_Sentry_Patrol(void) { Sentry_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPC->enemy) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + // If we have somewhere to go, then do that + if (!NPC->enemy) { + if (NPC_CheckPlayerTeamStealth()) { + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( UpdateGoal() ) - { - //start loop sound once we move + if (UpdateGoal()) { + // start loop sound once we move ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPC,"patrolNoise")) - { - G_SoundOnEnt( NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPC, "patrolNoise")) { + G_SoundOnEnt(NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPC, "patrolNoise", Q_irand(2000, 4000)); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -567,24 +493,17 @@ void NPC_Sentry_Patrol( void ) NPC_BSSentry_Default ------------------------- */ -void NPC_BSSentry_Default( void ) -{ - if ( NPC->targetname ) - { +void NPC_BSSentry_Default(void) { + if (NPC->targetname) { NPC->e_UseFunc = useF_sentry_use; } - if (( NPC->enemy ) && (NPCInfo->localState != LSTATE_WAKEUP)) - { + if ((NPC->enemy) && (NPCInfo->localState != LSTATE_WAKEUP)) { // Don't attack if waking up or if no enemy Sentry_AttackDecision(); - } - else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { NPC_Sentry_Patrol(); - } - else - { + } else { Sentry_Idle(); } } diff --git a/codeJK2/game/AI_Sniper.cpp b/codeJK2/game/AI_Sniper.cpp index c76231e067..9e19ff10c2 100644 --- a/codeJK2/game/AI_Sniper.cpp +++ b/codeJK2/game/AI_Sniper.cpp @@ -26,101 +26,94 @@ along with this program; if not, see . #include "anims.h" #include "g_navigator.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean FlyingCreature(gentity_t *ent); -extern CNavigator navigator; +extern CNavigator navigator; -#define SPF_NO_HIDE 2 +#define SPF_NO_HIDE 2 -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; static qboolean faceEnemy; static qboolean AImove; static qboolean shoot; -static float enemyDist; +static float enemyDist; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Sniper_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); +void Sniper_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); } -void NPC_Sniper_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Sniper_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Sniper_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod ) -{ +void NPC_Sniper_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod ); + NPC_Pain(self, inflictor, other, point, damage, mod); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -130,11 +123,10 @@ ST_HoldPosition ------------------------- */ -static void Sniper_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); +static void Sniper_HoldPosition(void) { + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); NPCInfo->goalEntity = NULL; - + /*if ( TIMER_Done( NPC, "stand" ) ) {//FIXME: what if can't shoot from this pos? TIMER_Set( NPC, "duck", Q_irand( 2000, 4000 ) ); @@ -148,52 +140,44 @@ ST_Move ------------------------- */ -static qboolean Sniper_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always move straight toward our goal +static qboolean Sniper_Move(void) { + NPCInfo->combatMove = qtrue; // always move straight toward our goal - qboolean moved = NPC_MoveToGoal( qtrue ); - navInfo_t info; - - //Get the move info - NAV_GetLastMove( info ); + qboolean moved = NPC_MoveToGoal(qtrue); + navInfo_t info; - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPC->enemy ) - { + // Get the move info + NAV_GetLastMove(info); + + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPC->enemy) { Sniper_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + // If our move failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); return moved; } } - //just hang here + // just hang here Sniper_HoldPosition(); } @@ -206,80 +190,64 @@ NPC_BSSniper_Patrol ------------------------- */ -void NPC_BSSniper_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? +void NPC_BSSniper_Patrol(void) { // FIXME: pick up on bodies of dead buddies? NPC->count = 0; - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - { + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID) { NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( (6-NPCInfo->stats.aim)*100, (6-NPCInfo->stats.aim)*500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPC, "attackDelay", Q_irand((6 - NPCInfo->stats.aim) * 100, (6 - NPCInfo->stats.aim) * 500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - //FIXME: sound? - VectorCopy( level.alertEvents[alertEvent].position, NPCInfo->investigateGoal ); - NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + // FIXME: sound? + VectorCopy(level.alertEvents[alertEvent].position, NPCInfo->investigateGoal); + NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies flag - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; - - VectorSubtract( NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); - + if (NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies flag + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; + + VectorSubtract(NPCInfo->investigateGoal, NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); + o_yaw = NPCInfo->desiredYaw; o_pitch = NPCInfo->desiredPitch; NPCInfo->desiredYaw = angles[YAW]; NPCInfo->desiredPitch = angles[PITCH]; - - NPC_UpdateAngles( qtrue, qtrue ); + + NPC_UpdateAngles(qtrue, qtrue); NPCInfo->desiredYaw = o_yaw; NPCInfo->desiredPitch = o_pitch; @@ -288,14 +256,13 @@ void NPC_BSSniper_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -329,109 +296,90 @@ ST_CheckMoveState ------------------------- */ -static void Sniper_CheckMoveState( void ) -{ - //See if we're a scout - if ( !(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) +static void Sniper_CheckMoveState(void) { + // See if we're a scout + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCInfo->goalEntity == NPC->enemy ) - { + if (NPCInfo->goalEntity == NPC->enemy) { AImove = qfalse; return; } } - //See if we're running away - else if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPC, "flee" ) ) - { + // See if we're running away + else if (NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPC, "flee")) { NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy = qfalse; } - } - else if ( NPCInfo->squadState == SQUAD_IDLE ) - { - if ( !NPCInfo->goalEntity ) - { + } else if (NPCInfo->squadState == SQUAD_IDLE) { + if (!NPCInfo->goalEntity) { AImove = qfalse; return; } } - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature( NPC ) ) || - ( NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - { - //int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - //newSquadState = SQUAD_COVER; + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature(NPC)) || + (NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( (6-NPCInfo->stats.aim)*50, (6-NPCInfo->stats.aim)*100 ) ); //FIXME: Slant for difficulty levels, too? - //don't do something else just yet - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand((6 - NPCInfo->stats.aim) * 50, (6 - NPCInfo->stats.aim) * 100)); // FIXME: Slant for difficulty levels, too? + // don't do something else just yet + TIMER_Set(NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(4000, 8000)); } } -static void Sniper_ResolveBlockedShot( void ) -{ - if ( TIMER_Done( NPC, "duck" ) ) - {//we're not ducking - if ( TIMER_Done( NPC, "roamTime" ) ) - {//not roaming - //FIXME: try to find another spot from which to hit the enemy - if ( (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && (!NPCInfo->goalEntity || NPCInfo->goalEntity == NPC->enemy) ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); +static void Sniper_ResolveBlockedShot(void) { + if (TIMER_Done(NPC, "duck")) { // we're not ducking + if (TIMER_Done(NPC, "roamTime")) { // not roaming + // FIXME: try to find another spot from which to hit the enemy + if ((NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && (!NPCInfo->goalEntity || NPCInfo->goalEntity == NPC->enemy)) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - int cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32 ); - if ( cp == -1 && !(NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32 ); + int cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->currentOrigin, cpFlags, 32); + if (cp == -1 && !(NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = + NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, NPC->enemy->currentOrigin, CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); - TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000 ) ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + TIMER_Set(NPC, "duck", -1); + TIMER_Set(NPC, "attackDelay", Q_irand(1000, 3000)); return; } } @@ -461,181 +409,144 @@ ST_CheckFireState ------------------------- */ -static void Sniper_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void Sniper_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //continue to fire on their last position - if ( !Q_irand( 0, 1 ) && NPCInfo->enemyLastSeenTime && level.time - NPCInfo->enemyLastSeenTime < ((5-NPCInfo->stats.aim)*1000) )//FIXME: incorporate skill too? + // continue to fire on their last position + if (!Q_irand(0, 1) && NPCInfo->enemyLastSeenTime && + level.time - NPCInfo->enemyLastSeenTime < ((5 - NPCInfo->stats.aim) * 1000)) // FIXME: incorporate skill too? { - if ( !VectorCompare( vec3_origin, NPCInfo->enemyLastSeenLocation ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!VectorCompare(vec3_origin, NPCInfo->enemyLastSeenLocation)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); - VectorNormalize( dir ); + VectorNormalize(dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; - //faceEnemy = qfalse; + // faceEnemy = qfalse; } return; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 10000 ) - {//next time we see him, we'll miss few times first + } else if (level.time - NPCInfo->enemyLastSeenTime > 10000) { // next time we see him, we'll miss few times first NPC->count = 0; } } -qboolean Sniper_EvaluateShot( int hit ) -{ - if ( !NPC->enemy ) - { +qboolean Sniper_EvaluateShot(int hit) { + if (!NPC->enemy) { return qfalse; } gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPC->s.weapon == WP_EMPLACED_GUN) ) - || ( hitEnt && (hitEnt->svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && ((hitEnt->svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || NPC->s.weapon == WP_EMPLACED_GUN)) || + (hitEnt && (hitEnt->svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; } -void Sniper_FaceEnemy( void ) -{ - //FIXME: the ones behind kill holes are facing some arbitrary direction and not firing - //FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? - //FIXME: need to give designers option to make them not miss first few shots - if ( NPC->enemy ) - { - vec3_t muzzle, target, angles, forward, right, up; - //Get the positions - AngleVectors( NPC->client->ps.viewangles, forward, right, up ); - CalcMuzzlePoint( NPC, forward, right, up, muzzle, 0 ); - //CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - CalcEntitySpot( NPC->enemy, SPOT_ORIGIN, target ); - - if ( enemyDist > 65536 && NPCInfo->stats.aim < 5 )//is 256 squared, was 16384 (128*128) +void Sniper_FaceEnemy(void) { + // FIXME: the ones behind kill holes are facing some arbitrary direction and not firing + // FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? + // FIXME: need to give designers option to make them not miss first few shots + if (NPC->enemy) { + vec3_t muzzle, target, angles, forward, right, up; + // Get the positions + AngleVectors(NPC->client->ps.viewangles, forward, right, up); + CalcMuzzlePoint(NPC, forward, right, up, muzzle, 0); + // CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC->enemy, SPOT_ORIGIN, target); + + if (enemyDist > 65536 && NPCInfo->stats.aim < 5) // is 256 squared, was 16384 (128*128) { - if ( NPC->count < (5-NPCInfo->stats.aim) ) - {//miss a few times first - if ( shoot && TIMER_Done( NPC, "attackDelay" ) && level.time >= NPCInfo->shotTime ) - {//ready to fire again - qboolean aimError = qfalse; - qboolean hit = qtrue; - int tryMissCount = 0; - trace_t trace; - - GetAnglesForDirection( muzzle, target, angles ); - AngleVectors( angles, forward, right, up ); - - while ( hit && tryMissCount < 10 ) - { + if (NPC->count < (5 - NPCInfo->stats.aim)) { // miss a few times first + if (shoot && TIMER_Done(NPC, "attackDelay") && level.time >= NPCInfo->shotTime) { // ready to fire again + qboolean aimError = qfalse; + qboolean hit = qtrue; + int tryMissCount = 0; + trace_t trace; + + GetAnglesForDirection(muzzle, target, angles); + AngleVectors(angles, forward, right, up); + + while (hit && tryMissCount < 10) { tryMissCount++; - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { aimError = qtrue; - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPC->enemy->maxs[2]*Q_flrand(1.5, 4), right, target ); - } - else - { - VectorMA( target, NPC->enemy->mins[2]*Q_flrand(1.5, 4), right, target ); + if (!Q_irand(0, 1)) { + VectorMA(target, NPC->enemy->maxs[2] * Q_flrand(1.5, 4), right, target); + } else { + VectorMA(target, NPC->enemy->mins[2] * Q_flrand(1.5, 4), right, target); } } - if ( !aimError || !Q_irand( 0, 1 ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPC->enemy->maxs[2]*Q_flrand(1.5, 4), up, target ); - } - else - { - VectorMA( target, NPC->enemy->mins[2]*Q_flrand(1.5, 4), up, target ); + if (!aimError || !Q_irand(0, 1)) { + if (!Q_irand(0, 1)) { + VectorMA(target, NPC->enemy->maxs[2] * Q_flrand(1.5, 4), up, target); + } else { + VectorMA(target, NPC->enemy->mins[2] * Q_flrand(1.5, 4), up, target); } } - gi.trace( &trace, muzzle, vec3_origin, vec3_origin, target, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - hit = Sniper_EvaluateShot( trace.entityNum ); + gi.trace(&trace, muzzle, vec3_origin, vec3_origin, target, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + hit = Sniper_EvaluateShot(trace.entityNum); } NPC->count++; - } - else - { - if ( !enemyLOS ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else { + if (!enemyLOS) { + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else - {//based on distance, aim value, difficulty and enemy movement, miss - //FIXME: incorporate distance as a factor? - int missFactor = 8-(NPCInfo->stats.aim+g_spskill->integer) * 3; - if ( missFactor > ENEMY_POS_LAG_STEPS ) - { + } else { // based on distance, aim value, difficulty and enemy movement, miss + // FIXME: incorporate distance as a factor? + int missFactor = 8 - (NPCInfo->stats.aim + g_spskill->integer) * 3; + if (missFactor > ENEMY_POS_LAG_STEPS) { missFactor = ENEMY_POS_LAG_STEPS; + } else if (missFactor < 0) { //??? + missFactor = 0; } - else if ( missFactor < 0 ) - {//??? - missFactor = 0 ; - } - VectorCopy( NPCInfo->enemyLaggedPos[missFactor], target ); + VectorCopy(NPCInfo->enemyLaggedPos[missFactor], target); } - GetAnglesForDirection( muzzle, target, angles ); - } - else - { - target[2] += Q_flrand( 0, NPC->enemy->maxs[2] ); - //CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); - GetAnglesForDirection( muzzle, target, angles ); + GetAnglesForDirection(muzzle, target, angles); + } else { + target[2] += Q_flrand(0, NPC->enemy->maxs[2]); + // CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); + GetAnglesForDirection(muzzle, target, angles); } - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void Sniper_UpdateEnemyPos( void ) -{ +void Sniper_UpdateEnemyPos(void) { int index; - for ( int i = MAX_ENEMY_POS_LAG-ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL ) - { - index = i/ENEMY_POS_LAG_INTERVAL; - if ( !index ) - { - CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, NPCInfo->enemyLaggedPos[index] ); - NPCInfo->enemyLaggedPos[index][2] -= Q_flrand( 2, 16 ); - } - else - { - VectorCopy( NPCInfo->enemyLaggedPos[index-1], NPCInfo->enemyLaggedPos[index] ); + for (int i = MAX_ENEMY_POS_LAG - ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL) { + index = i / ENEMY_POS_LAG_INTERVAL; + if (!index) { + CalcEntitySpot(NPC->enemy, SPOT_HEAD_LEAN, NPCInfo->enemyLaggedPos[index]); + NPCInfo->enemyLaggedPos[index][2] -= Q_flrand(2, 16); + } else { + VectorCopy(NPCInfo->enemyLaggedPos[index - 1], NPCInfo->enemyLaggedPos[index]); } } } @@ -646,42 +557,37 @@ NPC_BSSniper_Attack ------------------------- */ -void Sniper_StartHide( void ) -{ - int duckTime = Q_irand( 2000, 5000 ); - - TIMER_Set( NPC, "duck", duckTime ); - TIMER_Set( NPC, "watch", 500 ); - TIMER_Set( NPC, "attackDelay", duckTime + Q_irand( 500, 2000 ) ); +void Sniper_StartHide(void) { + int duckTime = Q_irand(2000, 5000); + + TIMER_Set(NPC, "duck", duckTime); + TIMER_Set(NPC, "watch", 500); + TIMER_Set(NPC, "attackDelay", duckTime + Q_irand(500, 2000)); } -void NPC_BSSniper_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSSniper_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; - NPC_BSSniper_Patrol();//FIXME: or patrol? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSSniper_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } @@ -689,63 +595,56 @@ void NPC_BSSniper_Attack( void ) AImove = qtrue; faceEnemy = qfalse; shoot = qfalse; - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - if ( enemyDist < 16384 )//128 squared - {//too close, so switch to primary fire - if ( NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( NPCInfo->scriptFlags & SCF_ALT_FIRE ) - {//use primary fire - trace_t trace; - gi.trace ( &trace, NPC->enemy->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->currentOrigin, NPC->enemy->s.number, NPC->enemy->clipmask, G2_NOCOLLIDE, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->s.number ) ) - {//he can get right to me + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + if (enemyDist < 16384) // 128 squared + { // too close, so switch to primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { // use primary fire + trace_t trace; + gi.trace(&trace, NPC->enemy->currentOrigin, NPC->enemy->mins, NPC->enemy->maxs, NPC->currentOrigin, NPC->enemy->s.number, NPC->enemy->clipmask, + G2_NOCOLLIDE, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPC->s.number)) { // he can get right to me NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //FIXME: switch back if he gets far away again? + // FIXME: switch back if he gets far away again? } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } } Sniper_UpdateEnemyPos(); - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) )//|| (NPCInfo->stats.aim >= 5 && gi.inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) //|| (NPCInfo->stats.aim >= 5 && gi.inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) { NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); enemyLOS = qtrue; float maxShootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyDist < maxShootDist ) - { + if (enemyDist < maxShootDist) { vec3_t fwd, right, up, muzzle, end; - trace_t tr; - AngleVectors( NPC->client->ps.viewangles, fwd, right, up ); - CalcMuzzlePoint( NPC, fwd, right, up, muzzle, 0 ); - VectorMA( muzzle, 8192, fwd, end ); - gi.trace ( &tr, muzzle, NULL, NULL, end, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); + trace_t tr; + AngleVectors(NPC->client->ps.viewangles, fwd, right, up); + CalcMuzzlePoint(NPC, fwd, right, up, muzzle, 0); + VectorMA(muzzle, 8192, fwd, end); + gi.trace(&tr, muzzle, NULL, NULL, end, NPC->s.number, MASK_SHOT, G2_RETURNONHIT, 0); int hit = tr.entityNum; - //can we shoot our target? - if ( Sniper_EvaluateShot( hit ) ) - { + // can we shoot our target? + if (Sniper_EvaluateShot(hit)) { enemyCS = qtrue; } } @@ -758,121 +657,91 @@ void NPC_BSSniper_Attack( void ) } */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 3000 ) - {//Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds up when ducked seems to make them want to run when they uncrouch + } else if (level.time - NPCInfo->enemyLastSeenTime > 3000) { // Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds up + // when ducked seems to make them want to run when they uncrouch Sniper_ResolveBlockedShot(); } - //Check for movement to take care of + // Check for movement to take care of Sniper_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Sniper_CheckFireState(); - if ( AImove ) - {//move toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (AImove) { // move toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { AImove = Sniper_Move(); - } - else - { + } else { AImove = qfalse; } } - if ( !AImove ) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { - if ( TIMER_Done( NPC, "watch" ) ) - {//not while watching + if (!AImove) { + if (!TIMER_Done(NPC, "duck")) { + if (TIMER_Done(NPC, "watch")) { // not while watching ucmd.upmove = -127; } } - //FIXME: what about leaning? - //FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); + // FIXME: what about leaning? + // FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); } - if ( TIMER_Done( NPC, "duck" ) - && TIMER_Done( NPC, "watch" ) - && (TIMER_Get( NPC, "attackDelay" )-level.time) > 1000 - && NPC->attackDebounceTime < level.time ) - { - if ( enemyLOS && (NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - if ( NPC->fly_sound_debounce_time < level.time ) - { + if (TIMER_Done(NPC, "duck") && TIMER_Done(NPC, "watch") && (TIMER_Get(NPC, "attackDelay") - level.time) > 1000 && NPC->attackDebounceTime < level.time) { + if (enemyLOS && (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + if (NPC->fly_sound_debounce_time < level.time) { NPC->fly_sound_debounce_time = level.time + 2000; } } } - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( AImove ) - {//don't run away and shoot + if (!faceEnemy) { // we want to face in the dir we're running + if (AImove) { // don't run away and shoot NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; shoot = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy ) + { // face the enemy Sniper_FaceEnemy(); } - if ( NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - //FIXME: don't shoot right away! - if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - WeaponThink( qtrue ); - if ( ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK) ) - { - G_SoundOnEnt( NPC, CHAN_WEAPON, "sound/null.wav" ); + // FIXME: don't shoot right away! + if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + WeaponThink(qtrue); + if (ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) { + G_SoundOnEnt(NPC, CHAN_WEAPON, "sound/null.wav"); } - //took a shot, now hide - if ( !(NPC->spawnflags&SPF_NO_HIDE) && !Q_irand( 0, 1 ) ) - { - //FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover + // took a shot, now hide + if (!(NPC->spawnflags & SPF_NO_HIDE) && !Q_irand(0, 1)) { + // FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover Sniper_StartHide(); - } - else - { - TIMER_Set( NPC, "attackDelay", NPCInfo->shotTime-level.time ); + } else { + TIMER_Set(NPC, "attackDelay", NPCInfo->shotTime - level.time); } } } } -void NPC_BSSniper_Default( void ) -{ - if( !NPC->enemy ) - {//don't have an enemy, look for one +void NPC_BSSniper_Default(void) { + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSSniper_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSSniper_Attack(); } } diff --git a/codeJK2/game/AI_Stormtrooper.cpp b/codeJK2/game/AI_Stormtrooper.cpp index 8d4a2d83dd..e1ea937248 100644 --- a/codeJK2/game/AI_Stormtrooper.cpp +++ b/codeJK2/game/AI_Stormtrooper.cpp @@ -26,45 +26,45 @@ along with this program; if not, see . #include "anims.h" #include "g_navigator.h" -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ); -extern qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ); -extern void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ); -extern void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void NPC_CheckGetNewWeapon( void ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern int GetTime ( int lastTime ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); - -extern CNavigator navigator; -extern cvar_t *d_asynchronousGroupAI; - -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 -#define ST_MIN_LIGHT_THRESHOLD 30 -#define ST_MAX_LIGHT_THRESHOLD 180 -#define DISTANCE_THRESHOLD 0.075f - -#define DISTANCE_SCALE 0.35f //These first three get your base detection rating, ideally add up to 1 -#define FOV_SCALE 0.40f // -#define LIGHT_SCALE 0.25f // - -#define SPEED_SCALE 0.25f //These next two are bonuses -#define TURNING_SCALE 0.25f // - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) - -#define MIN_ROCKET_DIST_SQUARED 16384//128*128 - -qboolean NPC_CheckPlayerTeamStealth( void ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState); +extern qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum); +extern void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot); +extern void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void NPC_CheckGetNewWeapon(void); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern int GetTime(int lastTime); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); + +extern CNavigator navigator; +extern cvar_t *d_asynchronousGroupAI; + +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 +#define ST_MIN_LIGHT_THRESHOLD 30 +#define ST_MAX_LIGHT_THRESHOLD 180 +#define DISTANCE_THRESHOLD 0.075f + +#define DISTANCE_SCALE 0.35f // These first three get your base detection rating, ideally add up to 1 +#define FOV_SCALE 0.40f // +#define LIGHT_SCALE 0.25f // + +#define SPEED_SCALE 0.25f // These next two are bonuses +#define TURNING_SCALE 0.25f // + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) + +#define MIN_ROCKET_DIST_SQUARED 16384 // 128*128 + +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; @@ -73,67 +73,57 @@ static qboolean hitAlly; static qboolean faceEnemy; static qboolean AImove; static qboolean shoot; -static float enemyDist; -static vec3_t impactPos; +static float enemyDist; +static vec3_t impactPos; -int groupSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several group AI from speaking all at once +int groupSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several group AI from speaking all at once -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void ST_AggressionAdjust( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +void ST_AggressionAdjust(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == TEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == TEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive + } else { // bad guys are more aggressive upper_threshold = 10; lower_threshold = 3; } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } } -void ST_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "interrogating", 0 ); - TIMER_Set( ent, "verifyCP", 0 ); +void ST_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "interrogating", 0); + TIMER_Set(ent, "verifyCP", 0); } -enum -{ +enum { SPEECH_CHASE, SPEECH_CONFUSED, SPEECH_COVER, @@ -150,19 +140,14 @@ enum SPEECH_PUSHED }; -static void ST_Speech( gentity_t *self, int speechType, float failChance ) -{ - if ( Q_flrand(0.0f, 1.0f) < failChance ) - { +static void ST_Speech(gentity_t *self, int speechType, float failChance) { + if (Q_flrand(0.0f, 1.0f) < failChance) { return; } - if ( failChance >= 0 ) - {//a negative failChance makes it always talk - if ( self->NPC->group ) - {//group AI speech debounce timer - if ( self->NPC->group->speechDebounceTime > level.time ) - { + if (failChance >= 0) { // a negative failChance makes it always talk + if (self->NPC->group) { // group AI speech debounce timer + if (self->NPC->group->speechDebounceTime > level.time) { return; } /* @@ -174,77 +159,68 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) } } */ - } - else if ( !TIMER_Done( self, "chatter" ) ) - {//personal timer + } else if (!TIMER_Done(self, "chatter")) { // personal timer return; - } - else if ( groupSpeechDebounceTime[self->client->playerTeam] > level.time ) - {//for those not in group AI - //FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? + } else if (groupSpeechDebounceTime[self->client->playerTeam] > level.time) { // for those not in group AI + // FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? return; } } - if ( self->NPC->group ) - {//So they don't all speak at once... - //FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! - self->NPC->group->speechDebounceTime = level.time + Q_irand( 2000, 4000 ); - } - else - { - TIMER_Set( self, "chatter", Q_irand( 2000, 4000 ) ); + if (self->NPC->group) { // So they don't all speak at once... + // FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! + self->NPC->group->speechDebounceTime = level.time + Q_irand(2000, 4000); + } else { + TIMER_Set(self, "chatter", Q_irand(2000, 4000)); } - groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand( 2000, 4000 ); + groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand(2000, 4000); - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - switch( speechType ) - { + switch (speechType) { case SPEECH_CHASE: - G_AddVoiceEvent( self, Q_irand(EV_CHASE1, EV_CHASE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CHASE1, EV_CHASE3), 2000); break; case SPEECH_CONFUSED: - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); break; case SPEECH_COVER: - G_AddVoiceEvent( self, Q_irand(EV_COVER1, EV_COVER5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_COVER1, EV_COVER5), 2000); break; case SPEECH_DETECTED: - G_AddVoiceEvent( self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000); break; case SPEECH_GIVEUP: - G_AddVoiceEvent( self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000); break; case SPEECH_LOOK: - G_AddVoiceEvent( self, Q_irand(EV_LOOK1, EV_LOOK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_LOOK1, EV_LOOK2), 2000); break; case SPEECH_LOST: - G_AddVoiceEvent( self, EV_LOST1, 2000 ); + G_AddVoiceEvent(self, EV_LOST1, 2000); break; case SPEECH_OUTFLANK: - G_AddVoiceEvent( self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000); break; case SPEECH_ESCAPING: - G_AddVoiceEvent( self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000); break; case SPEECH_SIGHT: - G_AddVoiceEvent( self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000); break; case SPEECH_SOUND: - G_AddVoiceEvent( self, Q_irand(EV_SOUND1, EV_SOUND3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SOUND1, EV_SOUND3), 2000); break; case SPEECH_SUSPICIOUS: - G_AddVoiceEvent( self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000); break; case SPEECH_YELL: - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 2000); break; case SPEECH_PUSHED: - G_AddVoiceEvent( self, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); break; default: break; @@ -253,31 +229,25 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) self->NPC->blockedSpeechDebounceTime = level.time + 2000; } -void ST_MarkToCover( gentity_t *self ) -{ - if ( !self || !self->NPC ) - { +void ST_MarkToCover(gentity_t *self) { + if (!self || !self->NPC) { return; } self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "attackDelay", Q_irand( 500, 2500 ) ); - ST_AggressionAdjust( self, -3 ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + TIMER_Set(self, "attackDelay", Q_irand(500, 2500)); + ST_AggressionAdjust(self, -3); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } -void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ) -{ - if ( !self || !self->NPC ) - { +void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime) { + if (!self || !self->NPC) { return; } - G_StartFlee( self, enemy, dangerPoint, dangerLevel, minTime, maxTime ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + G_StartFlee(self, enemy, dangerPoint, dangerLevel, minTime, maxTime); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } /* @@ -286,19 +256,17 @@ NPC_ST_Pain ------------------------- */ -void NPC_ST_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ +void NPC_ST_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "hideTime", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "hideTime", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, inflictor, other, point, damage, mod, hitLoc ); + NPC_Pain(self, inflictor, other, point, damage, mod, hitLoc); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -308,18 +276,15 @@ ST_HoldPosition ------------------------- */ -static void ST_HoldPosition( void ) -{ - if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPC, "flee", -level.time ); - } - TIMER_Set( NPC, "verifyCP", Q_irand( 1000, 3000 ) );//don't look for another one for a few seconds - NPC_FreeCombatPoint( NPCInfo->combatPoint, qtrue ); - //NPCInfo->combatPoint = -1;//??? - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//don't have a script waiting for me to get to my point, okay to stop trying and stand - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); +static void ST_HoldPosition(void) { + if (NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPC, "flee", -level.time); + } + TIMER_Set(NPC, "verifyCP", Q_irand(1000, 3000)); // don't look for another one for a few seconds + NPC_FreeCombatPoint(NPCInfo->combatPoint, qtrue); + // NPCInfo->combatPoint = -1;//??? + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // don't have a script waiting for me to get to my point, okay to stop trying and stand + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT); NPCInfo->goalEntity = NULL; } @@ -330,31 +295,22 @@ static void ST_HoldPosition( void ) */ } -void NPC_ST_SayMovementSpeech( void ) -{ - if ( !NPCInfo->movementSpeech ) - { +void NPC_ST_SayMovementSpeech(void) { + if (!NPCInfo->movementSpeech) { return; } - if ( NPCInfo->group && - NPCInfo->group->commander && - NPCInfo->group->commander->client && - NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - {//imperial (commander) gives the order - ST_Speech( NPCInfo->group->commander, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance ); - } - else - {//really don't want to say this unless we can actually get there... - ST_Speech( NPC, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance ); + if (NPCInfo->group && NPCInfo->group->commander && NPCInfo->group->commander->client && NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && + !Q_irand(0, 3)) { // imperial (commander) gives the order + ST_Speech(NPCInfo->group->commander, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance); + } else { // really don't want to say this unless we can actually get there... + ST_Speech(NPC, NPCInfo->movementSpeech, NPCInfo->movementSpeechChance); } NPCInfo->movementSpeech = 0; NPCInfo->movementSpeechChance = 0.0f; } -void NPC_ST_StoreMovementSpeech( int speech, float chance ) -{ +void NPC_ST_StoreMovementSpeech(int speech, float chance) { NPCInfo->movementSpeech = speech; NPCInfo->movementSpeechChance = chance; } @@ -363,40 +319,35 @@ void NPC_ST_StoreMovementSpeech( int speech, float chance ) ST_Move ------------------------- */ -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ); -static qboolean ST_Move( void ) -{ - NPCInfo->combatMove = qtrue;//always move straight toward our goal +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other); +static qboolean ST_Move(void) { + NPCInfo->combatMove = qtrue; // always move straight toward our goal - qboolean moved = NPC_MoveToGoal( qtrue ); - navInfo_t info; + qboolean moved = NPC_MoveToGoal(qtrue); + navInfo_t info; - //Get the move info - NAV_GetLastMove( info ); + // Get the move info + NAV_GetLastMove(info); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPC->enemy ) - { + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPC->enemy) { ST_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//FIXME: if we're going to a combat point, need to pick a different one - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//can't transfer movegoal or stop when a script we're running is waiting to complete - if ( info.blocker && info.blocker->NPC && NPCInfo->group != NULL && info.blocker->NPC->group == NPCInfo->group )//(NPCInfo->aiFlags&NPCAI_BLOCKED) && NPCInfo->group != NULL ) - {//dammit, something is in our way - //see if it's one of ours - for ( int j = 0; j < NPCInfo->group->numGroup; j++ ) - { - if ( NPCInfo->group->member[j].number == NPCInfo->blockingEntNum ) - {//we're being blocked by one of our own, pass our goal onto them and I'll stand still - ST_TransferMoveGoal( NPC, &g_entities[NPCInfo->group->member[j].number] ); + // If our move failed, then reset + if (moved == qfalse) { // FIXME: if we're going to a combat point, need to pick a different one + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // can't transfer movegoal or stop when a script we're running is waiting to complete + if (info.blocker && info.blocker->NPC && NPCInfo->group != NULL && + info.blocker->NPC->group == NPCInfo->group) //(NPCInfo->aiFlags&NPCAI_BLOCKED) && NPCInfo->group != NULL ) + { // dammit, something is in our way + // see if it's one of ours + for (int j = 0; j < NPCInfo->group->numGroup; j++) { + if (NPCInfo->group->member[j].number == + NPCInfo->blockingEntNum) { // we're being blocked by one of our own, pass our goal onto them and I'll stand still + ST_TransferMoveGoal(NPC, &g_entities[NPCInfo->group->member[j].number]); break; } } @@ -404,38 +355,32 @@ static qboolean ST_Move( void ) ST_HoldPosition(); } - } - else - { - //First time you successfully move, say what it is you're doing + } else { + // First time you successfully move, say what it is you're doing NPC_ST_SayMovementSpeech(); } return moved; } - /* ------------------------- NPC_ST_SleepShuffle ------------------------- */ -static void NPC_ST_SleepShuffle( void ) -{ - //Play an awake script if we have one - if ( G_ActivateBehavior( NPC, BSET_AWAKE) ) - { +static void NPC_ST_SleepShuffle(void) { + // Play an awake script if we have one + if (G_ActivateBehavior(NPC, BSET_AWAKE)) { return; } - //Automate some movement and noise - if ( TIMER_Done( NPC, "shuffleTime" ) ) - { + // Automate some movement and noise + if (TIMER_Done(NPC, "shuffleTime")) { - //TODO: Play sleeping shuffle animation + // TODO: Play sleeping shuffle animation - //int soundIndex = Q_irand( 0, 1 ); + // int soundIndex = Q_irand( 0, 1 ); /* switch ( soundIndex ) @@ -450,16 +395,15 @@ static void NPC_ST_SleepShuffle( void ) } */ - TIMER_Set( NPC, "shuffleTime", 4000 ); - TIMER_Set( NPC, "sleepTime", 2000 ); + TIMER_Set(NPC, "shuffleTime", 4000); + TIMER_Set(NPC, "sleepTime", 2000); return; } - //They made another noise while we were stirring, see if we can see them - if ( TIMER_Done( NPC, "sleepTime" ) ) - { + // They made another noise while we were stirring, see if we can see them + if (TIMER_Done(NPC, "sleepTime")) { NPC_CheckPlayerTeamStealth(); - TIMER_Set( NPC, "sleepTime", 2000 ); + TIMER_Set(NPC, "sleepTime", 2000); } } @@ -469,24 +413,20 @@ NPC_ST_Sleep ------------------------- */ -void NPC_BSST_Sleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qfalse, qtrue );//only check sounds since we're alseep! +void NPC_BSST_Sleep(void) { + int alertEvent = NPC_CheckAlertEvents(qfalse, qtrue); // only check sounds since we're alseep! - //There is an event we heard - if ( alertEvent >= 0 ) - { - //See if it was enough to wake us up - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - if ( &g_entities[0] && g_entities[0].health > 0 ) - { - G_SetEnemy( NPC, &g_entities[0] ); + // There is an event we heard + if (alertEvent >= 0) { + // See if it was enough to wake us up + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + if (&g_entities[0] && g_entities[0].health > 0) { + G_SetEnemy(NPC, &g_entities[0]); return; } } - //Otherwise just stir a bit + // Otherwise just stir a bit NPC_ST_SleepShuffle(); return; } @@ -498,151 +438,130 @@ NPC_CheckEnemyStealth ------------------------- */ -qboolean NPC_CheckEnemyStealth( gentity_t *target ) -{ - float target_dist, minDist = 40;//any closer than 40 and we definitely notice +qboolean NPC_CheckEnemyStealth(gentity_t *target) { + float target_dist, minDist = 40; // any closer than 40 and we definitely notice - //In case we aquired one some other way - if ( NPC->enemy != NULL ) + // In case we aquired one some other way + if (NPC->enemy != NULL) return qtrue; - //Ignore notarget - if ( target->flags & FL_NOTARGET ) + // Ignore notarget + if (target->flags & FL_NOTARGET) return qfalse; - if ( target->health <= 0 ) - { + if (target->health <= 0) { return qfalse; } - if ( target->client->ps.weapon == WP_SABER && target->client->ps.saberActive && !target->client->ps.saberInFlight ) - {//if target has saber in hand and activated, we wake up even sooner even if not facing him + if (target->client->ps.weapon == WP_SABER && target->client->ps.saberActive && + !target->client->ps.saberInFlight) { // if target has saber in hand and activated, we wake up even sooner even if not facing him minDist = 100; } - //If the target is this close, then wake up regardless - if ( (target_dist = DistanceSquared( target->currentOrigin, NPC->currentOrigin )) < (minDist*minDist) && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - G_SetEnemy( NPC, target ); + // If the target is this close, then wake up regardless + if ((target_dist = DistanceSquared(target->currentOrigin, NPC->currentOrigin)) < (minDist * minDist) && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - float maxViewDist = MAX_VIEW_DIST; + float maxViewDist = MAX_VIEW_DIST; - if ( NPCInfo->stats.visrange > maxViewDist ) - {//FIXME: should we always just set maxViewDist to this? + if (NPCInfo->stats.visrange > maxViewDist) { // FIXME: should we always just set maxViewDist to this? maxViewDist = NPCInfo->stats.visrange; } - if ( target_dist > (maxViewDist*maxViewDist) ) - {//out of possible visRange + if (target_dist > (maxViewDist * maxViewDist)) { // out of possible visRange return qfalse; } - //Check FOV first - if ( InFOV( target, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Check FOV first + if (InFOV(target, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - qboolean clearLOS = ( target->client->ps.leanofs ) ? NPC_ClearLOS( target->client->renderInfo.eyePoint ) : NPC_ClearLOS( target ); + qboolean clearLOS = (target->client->ps.leanofs) ? NPC_ClearLOS(target->client->renderInfo.eyePoint) : NPC_ClearLOS(target); - //Now check for clear line of vision - if ( clearLOS ) - { - if ( target->client->NPC_class == CLASS_ATST ) - {//can't miss 'em! - G_SetEnemy( NPC, target ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // Now check for clear line of vision + if (clearLOS) { + if (target->client->NPC_class == CLASS_ATST) { // can't miss 'em! + G_SetEnemy(NPC, target); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - vec3_t targ_org = {target->currentOrigin[0],target->currentOrigin[1],target->currentOrigin[2]+target->maxs[2]-4}; - float hAngle_perc = NPC_GetHFOVPercentage( targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov ); - float vAngle_perc = NPC_GetVFOVPercentage( targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.vfov ); + vec3_t targ_org = {target->currentOrigin[0], target->currentOrigin[1], target->currentOrigin[2] + target->maxs[2] - 4}; + float hAngle_perc = NPC_GetHFOVPercentage(targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.hfov); + float vAngle_perc = NPC_GetVFOVPercentage(targ_org, NPC->client->renderInfo.eyePoint, NPC->client->renderInfo.eyeAngles, NPCInfo->stats.vfov); - //Scale them vertically some, and horizontally pretty harshly - vAngle_perc *= vAngle_perc;//( vAngle_perc * vAngle_perc ); - hAngle_perc *= ( hAngle_perc * hAngle_perc ); + // Scale them vertically some, and horizontally pretty harshly + vAngle_perc *= vAngle_perc; //( vAngle_perc * vAngle_perc ); + hAngle_perc *= (hAngle_perc * hAngle_perc); - //Cap our vertical vision severely - //if ( vAngle_perc <= 0.3f ) // was 0.5f + // Cap our vertical vision severely + // if ( vAngle_perc <= 0.3f ) // was 0.5f // return qfalse; - //Assess the player's current status - target_dist = Distance( target->currentOrigin, NPC->currentOrigin ); - - float target_speed = VectorLength( target->client->ps.velocity ); - int target_crouching = ( target->client->usercmd.upmove < 0 ); - float dist_rating = ( target_dist / maxViewDist ); - float speed_rating = ( target_speed / MAX_VIEW_SPEED ); - float turning_rating = AngleDelta( target->client->ps.viewangles[PITCH], target->lastAngles[PITCH] )/180.0f + AngleDelta( target->client->ps.viewangles[YAW], target->lastAngles[YAW] )/180.0f; - float light_level = ( target->lightLevel / MAX_LIGHT_INTENSITY ); - float FOV_perc = 1.0f - ( hAngle_perc + vAngle_perc ) * 0.5f; //FIXME: Dunno about the average... - float vis_rating = 0.0f; - - //Too dark - if ( light_level < MIN_LIGHT_THRESHOLD ) + // Assess the player's current status + target_dist = Distance(target->currentOrigin, NPC->currentOrigin); + + float target_speed = VectorLength(target->client->ps.velocity); + int target_crouching = (target->client->usercmd.upmove < 0); + float dist_rating = (target_dist / maxViewDist); + float speed_rating = (target_speed / MAX_VIEW_SPEED); + float turning_rating = AngleDelta(target->client->ps.viewangles[PITCH], target->lastAngles[PITCH]) / 180.0f + + AngleDelta(target->client->ps.viewangles[YAW], target->lastAngles[YAW]) / 180.0f; + float light_level = (target->lightLevel / MAX_LIGHT_INTENSITY); + float FOV_perc = 1.0f - (hAngle_perc + vAngle_perc) * 0.5f; // FIXME: Dunno about the average... + float vis_rating = 0.0f; + + // Too dark + if (light_level < MIN_LIGHT_THRESHOLD) return qfalse; - //Too close? - if ( dist_rating < DISTANCE_THRESHOLD ) - { - G_SetEnemy( NPC, target ); - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // Too close? + if (dist_rating < DISTANCE_THRESHOLD) { + G_SetEnemy(NPC, target); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //Out of range - if ( dist_rating > 1.0f ) + // Out of range + if (dist_rating > 1.0f) return qfalse; - //Cap our speed checks - if ( speed_rating > 1.0f ) + // Cap our speed checks + if (speed_rating > 1.0f) speed_rating = 1.0f; - - //Calculate the distance, fov and light influences + // Calculate the distance, fov and light influences //...Visibilty linearly wanes over distance - float dist_influence = DISTANCE_SCALE * ( ( 1.0f - dist_rating ) ); + float dist_influence = DISTANCE_SCALE * ((1.0f - dist_rating)); //...As the percentage out of the FOV increases, straight perception suffers on an exponential scale - float fov_influence = FOV_SCALE * ( 1.0f - FOV_perc ); + float fov_influence = FOV_SCALE * (1.0f - FOV_perc); //...Lack of light hides, abundance of light exposes - float light_influence = ( light_level - 0.5f ) * LIGHT_SCALE; - - //Calculate our base rating - float target_rating = dist_influence + fov_influence + light_influence; - - //Now award any final bonuses to this number - int contents = gi.pointcontents( targ_org, target->s.number ); - if ( contents&CONTENTS_WATER ) - { - int myContents = gi.pointcontents( NPC->client->renderInfo.eyePoint, NPC->s.number ); - if ( !(myContents&CONTENTS_WATER) ) - {//I'm not in water - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//these guys can see in in/through water pretty well - vis_rating = 0.10f;//10% bonus - } - else - { - vis_rating = 0.35f;//35% bonus + float light_influence = (light_level - 0.5f) * LIGHT_SCALE; + + // Calculate our base rating + float target_rating = dist_influence + fov_influence + light_influence; + + // Now award any final bonuses to this number + int contents = gi.pointcontents(targ_org, target->s.number); + if (contents & CONTENTS_WATER) { + int myContents = gi.pointcontents(NPC->client->renderInfo.eyePoint, NPC->s.number); + if (!(myContents & CONTENTS_WATER)) { // I'm not in water + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // these guys can see in in/through water pretty well + vis_rating = 0.10f; // 10% bonus + } else { + vis_rating = 0.35f; // 35% bonus } - } - else - {//else, if we're both in water - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//I can see him just fine - } - else - { - vis_rating = 0.15f;//15% bonus + } else { // else, if we're both in water + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // I can see him just fine + } else { + vis_rating = 0.15f; // 15% bonus } } - } - else - {//not in water - if ( contents&CONTENTS_FOG ) - { - vis_rating = 0.15f;//15% bonus + } else { // not in water + if (contents & CONTENTS_FOG) { + vis_rating = 0.15f; // 15% bonus } } @@ -651,68 +570,57 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) //...Motion draws the eye quickly target_rating += speed_rating * SPEED_SCALE; target_rating += turning_rating * TURNING_SCALE; - //FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? + // FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? //...Smaller targets are harder to indentify - if ( target_crouching ) - { - target_rating *= 0.9f; //10% bonus + if (target_crouching) { + target_rating *= 0.9f; // 10% bonus } - //If he's violated the threshold, then realize him - //float difficulty_scale = 1.0f + (2.0f-g_spskill->value);//if playing on easy, 20% harder to be seen...? + // If he's violated the threshold, then realize him + // float difficulty_scale = 1.0f + (2.0f-g_spskill->value);//if playing on easy, 20% harder to be seen...? float realize, cautious; - if ( NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//swamptroopers can see much better - realize = (float)CAUTIOUS_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; - } - else - { - realize = (float)REALIZE_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; + if (NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // swamptroopers can see much better + realize = (float)CAUTIOUS_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; + } else { + realize = (float)REALIZE_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; } - if ( target_rating > realize && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - G_SetEnemy( NPC, target ); + if (target_rating > realize && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //If he's above the caution threshold, then realize him in a few seconds unless he moves to cover - if ( target_rating > cautious && !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//FIXME: ambushing guys should never talk - if ( TIMER_Done( NPC, "enemyLastVisible" ) ) - {//If we haven't already, start the counter - int lookTime = Q_irand( 4500, 8500 ); - //NPCInfo->timeEnemyLastVisible = level.time + 2000; - TIMER_Set( NPC, "enemyLastVisible", lookTime ); - //TODO: Play a sound along the lines of, "Huh? What was that?" - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - NPC_TempLookTarget( NPC, target->s.number, lookTime, lookTime ); - //FIXME: set desired yaw and pitch towards this guy? - } - else if ( TIMER_Get( NPC, "enemyLastVisible" ) <= level.time + 500 && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) //FIXME: Is this reliable? + // If he's above the caution threshold, then realize him in a few seconds unless he moves to cover + if (target_rating > cautious && !(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // FIXME: ambushing guys should never talk + if (TIMER_Done(NPC, "enemyLastVisible")) { // If we haven't already, start the counter + int lookTime = Q_irand(4500, 8500); + // NPCInfo->timeEnemyLastVisible = level.time + 2000; + TIMER_Set(NPC, "enemyLastVisible", lookTime); + // TODO: Play a sound along the lines of, "Huh? What was that?" + ST_Speech(NPC, SPEECH_SIGHT, 0); + NPC_TempLookTarget(NPC, target->s.number, lookTime, lookTime); + // FIXME: set desired yaw and pitch towards this guy? + } else if (TIMER_Get(NPC, "enemyLastVisible") <= level.time + 500 && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) // FIXME: Is this reliable? { - if ( NPCInfo->rank < RANK_LT && !Q_irand( 0, 2 ) ) - { - int interrogateTime = Q_irand( 2000, 4000 ); - ST_Speech( NPC, SPEECH_SUSPICIOUS, 0 ); - TIMER_Set( NPC, "interrogating", interrogateTime ); - G_SetEnemy( NPC, target ); + if (NPCInfo->rank < RANK_LT && !Q_irand(0, 2)) { + int interrogateTime = Q_irand(2000, 4000); + ST_Speech(NPC, SPEECH_SUSPICIOUS, 0); + TIMER_Set(NPC, "interrogating", interrogateTime); + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", interrogateTime ); - TIMER_Set( NPC, "stand", interrogateTime ); - } - else - { - G_SetEnemy( NPC, target ); + TIMER_Set(NPC, "attackDelay", interrogateTime); + TIMER_Set(NPC, "stand", interrogateTime); + } else { + G_SetEnemy(NPC, target); NPCInfo->enemyLastSeenTime = level.time; - //FIXME: ambush guys (like those popping out of water) shouldn't delay... - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - TIMER_Set( NPC, "stand", Q_irand( 500, 2500 ) ); + // FIXME: ambush guys (like those popping out of water) shouldn't delay... + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + TIMER_Set(NPC, "stand", Q_irand(500, 2500)); } return qtrue; } @@ -724,8 +632,7 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) return qfalse; } -qboolean NPC_CheckPlayerTeamStealth( void ) -{ +qboolean NPC_CheckPlayerTeamStealth(void) { /* //NOTENOTE: For now, all stealh checks go against the player, since // he is the main focus. Squad members and rivals do not @@ -734,14 +641,12 @@ qboolean NPC_CheckPlayerTeamStealth( void ) NPC_CheckEnemyStealth( &g_entities[0] ); //Change this pointer to assess other entities */ gentity_t *enemy; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { - if(!PInUse(i)) + for (int i = 0; i < ENTITYNUM_WORLD; i++) { + if (!PInUse(i)) continue; enemy = &g_entities[i]; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPC->client->enemyTeam ) - { - if ( NPC_CheckEnemyStealth( enemy ) ) //Change this pointer to assess other entities + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && enemy->client->playerTeam == NPC->client->enemyTeam) { + if (NPC_CheckEnemyStealth(enemy)) // Change this pointer to assess other entities { return qtrue; } @@ -755,44 +660,36 @@ NPC_ST_InvestigateEvent ------------------------- */ -#define MAX_CHECK_THRESHOLD 1 +#define MAX_CHECK_THRESHOLD 1 -static qboolean NPC_ST_InvestigateEvent( int eventID, bool extraSuspicious ) -{ - //If they've given themselves away, just take them as an enemy - if ( NPCInfo->confusionTime < level.time ) - { - if ( level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { +static qboolean NPC_ST_InvestigateEvent(int eventID, bool extraSuspicious) { + // If they've given themselves away, just take them as an enemy + if (NPCInfo->confusionTime < level.time) { + if (level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam ) - {//not an enemy + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam) { // not an enemy return qfalse; } - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - //ST_Speech( NPC, SPEECH_CHARGE, 0 ); - G_SetEnemy( NPC, level.alertEvents[eventID].owner ); + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just + // let combat AI handle this... (act as if you lost him) ST_Speech( NPC, SPEECH_CHARGE, 0 ); + G_SetEnemy(NPC, level.alertEvents[eventID].owner); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - if ( level.alertEvents[eventID].type == AET_SOUND ) - {//heard him, didn't see him, stick for a bit - TIMER_Set( NPC, "roamTime", Q_irand( 500, 2500 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + if (level.alertEvents[eventID].type == AET_SOUND) { // heard him, didn't see him, stick for a bit + TIMER_Set(NPC, "roamTime", Q_irand(500, 2500)); } return qtrue; } } - //don't look at the same alert twice - if ( level.alertEvents[eventID].ID == NPCInfo->lastAlertID ) - { + // don't look at the same alert twice + if (level.alertEvents[eventID].ID == NPCInfo->lastAlertID) { return qfalse; } NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - //Must be ready to take another sound event + // Must be ready to take another sound event /* if ( NPCInfo->investigateSoundDebounceTime > level.time ) { @@ -800,114 +697,89 @@ static qboolean NPC_ST_InvestigateEvent( int eventID, bool extraSuspicious ) } */ - if ( level.alertEvents[eventID].type == AET_SIGHT ) - {//sight alert, check the light level - if ( level.alertEvents[eventID].light < Q_irand( ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD ) ) - {//below my threshhold of potentially seeing + if (level.alertEvents[eventID].type == AET_SIGHT) { // sight alert, check the light level + if (level.alertEvents[eventID].light < Q_irand(ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD)) { // below my threshhold of potentially seeing return qfalse; } } - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[eventID].position, NPCInfo->investigateGoal ); + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[eventID].position, NPCInfo->investigateGoal); - //First awareness of it - NPCInfo->investigateCount += ( extraSuspicious ) ? 2 : 1; + // First awareness of it + NPCInfo->investigateCount += (extraSuspicious) ? 2 : 1; - //Clamp the value - if ( NPCInfo->investigateCount > 4 ) + // Clamp the value + if (NPCInfo->investigateCount > 4) NPCInfo->investigateCount = 4; - //See if we should walk over and investigate - if ( level.alertEvents[eventID].level > AEL_MINOR && NPCInfo->investigateCount > 1 && (NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - //make it so they can walk right to this point and look at it rather than having to use combatPoints - if ( G_ExpandPointToBBox( NPCInfo->investigateGoal, NPC->mins, NPC->maxs, NPC->s.number, ((NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP) ) ) - {//we were able to move the investigateGoal to a point in which our bbox would fit - //drop the goal to the ground so we can get at it - vec3_t end; - trace_t trace; - VectorCopy( NPCInfo->investigateGoal, end ); - end[2] -= 512;//FIXME: not always right? What if it's even higher, somehow? - gi.trace( &trace, NPCInfo->investigateGoal, NPC->mins, NPC->maxs, end, ENTITYNUM_NONE, ((NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP), G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f ) - {//too high to even bother - //FIXME: look at them??? - } - else - { - VectorCopy( trace.endpos, NPCInfo->investigateGoal ); - NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); + // See if we should walk over and investigate + if (level.alertEvents[eventID].level > AEL_MINOR && NPCInfo->investigateCount > 1 && (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + // make it so they can walk right to this point and look at it rather than having to use combatPoints + if (G_ExpandPointToBBox( + NPCInfo->investigateGoal, NPC->mins, NPC->maxs, NPC->s.number, + ((NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP))) { // we were able to move the investigateGoal to a point in which our bbox would fit + // drop the goal to the ground so we can get at it + vec3_t end; + trace_t trace; + VectorCopy(NPCInfo->investigateGoal, end); + end[2] -= 512; // FIXME: not always right? What if it's even higher, somehow? + gi.trace(&trace, NPCInfo->investigateGoal, NPC->mins, NPC->maxs, end, ENTITYNUM_NONE, ((NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP), + G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f) { // too high to even bother + // FIXME: look at them??? + } else { + VectorCopy(trace.endpos, NPCInfo->investigateGoal); + NPC_SetMoveGoal(NPC, NPCInfo->investigateGoal, 16, qtrue); NPCInfo->localState = LSTATE_INVESTIGATE; } - } - else - { - int id = NPC_FindCombatPoint( NPCInfo->investigateGoal, NPCInfo->investigateGoal, NPCInfo->investigateGoal, CP_INVESTIGATE|CP_HAS_ROUTE, 0 ); + } else { + int id = NPC_FindCombatPoint(NPCInfo->investigateGoal, NPCInfo->investigateGoal, NPCInfo->investigateGoal, CP_INVESTIGATE | CP_HAS_ROUTE, 0); - if ( id != -1 ) - { - NPC_SetMoveGoal( NPC, level.combatPoints[id].origin, 16, qtrue, id ); + if (id != -1) { + NPC_SetMoveGoal(NPC, level.combatPoints[id].origin, 16, qtrue, id); NPCInfo->localState = LSTATE_INVESTIGATE; } } - //Say something - //FIXME: only if have others in group... these should be responses? - if ( NPCInfo->investigateDebounceTime+NPCInfo->pauseTime > level.time ) - {//was already investigating - if ( NPCInfo->group && - NPCInfo->group->commander && - NPCInfo->group->commander->client && - NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - { - ST_Speech( NPCInfo->group->commander, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds - } - else - { - ST_Speech( NPC, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds - } - } - else - { - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPC, SPEECH_SIGHT, 0 ); + // Say something + // FIXME: only if have others in group... these should be responses? + if (NPCInfo->investigateDebounceTime + NPCInfo->pauseTime > level.time) { // was already investigating + if (NPCInfo->group && NPCInfo->group->commander && NPCInfo->group->commander->client && + NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && !Q_irand(0, 3)) { + ST_Speech(NPCInfo->group->commander, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds + } else { + ST_Speech(NPC, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPC, SPEECH_SOUND, 0 ); + } else { + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPC, SPEECH_SOUND, 0); } } - //Setup the debounce info - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; - NPCInfo->investigateSoundDebounceTime = level.time + 2000; - NPCInfo->pauseTime = level.time; - } - else - {//just look? - //Say something - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPC, SPEECH_SIGHT, 0 ); - } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPC, SPEECH_SOUND, 0 ); + // Setup the debounce info + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; + NPCInfo->investigateSoundDebounceTime = level.time + 2000; + NPCInfo->pauseTime = level.time; + } else { // just look? + // Say something + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPC, SPEECH_SOUND, 0); } - //Setup the debounce info - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 1000; - NPCInfo->investigateSoundDebounceTime = level.time + 1000; - NPCInfo->pauseTime = level.time; - VectorCopy( level.alertEvents[eventID].position, NPCInfo->investigateGoal ); + // Setup the debounce info + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 1000; + NPCInfo->investigateSoundDebounceTime = level.time + 1000; + NPCInfo->pauseTime = level.time; + VectorCopy(level.alertEvents[eventID].position, NPCInfo->investigateGoal); } - if ( level.alertEvents[eventID].level >= AEL_DANGER ) - { - NPCInfo->investigateDebounceTime = Q_irand( 500, 2500 ); + if (level.alertEvents[eventID].level >= AEL_DANGER) { + NPCInfo->investigateDebounceTime = Q_irand(500, 2500); } - //Start investigating + // Start investigating NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; } @@ -918,16 +790,15 @@ ST_OffsetLook ------------------------- */ -static void ST_OffsetLook( float offset, vec3_t out ) -{ - vec3_t angles, forward, temp; +static void ST_OffsetLook(float offset, vec3_t out) { + vec3_t angles, forward, temp; - GetAnglesForDirection( NPC->currentOrigin, NPCInfo->investigateGoal, angles ); + GetAnglesForDirection(NPC->currentOrigin, NPCInfo->investigateGoal, angles); angles[YAW] += offset; - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( NPC->currentOrigin, 64, forward, out ); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(NPC->currentOrigin, 64, forward, out); - CalcEntitySpot( NPC, SPOT_HEAD, temp ); + CalcEntitySpot(NPC, SPOT_HEAD, temp); out[2] = temp[2]; } @@ -937,30 +808,25 @@ ST_LookAround ------------------------- */ -static void ST_LookAround( void ) -{ - vec3_t lookPos; - float perc = (float) ( level.time - NPCInfo->pauseTime ) / (float) NPCInfo->investigateDebounceTime; +static void ST_LookAround(void) { + vec3_t lookPos; + float perc = (float)(level.time - NPCInfo->pauseTime) / (float)NPCInfo->investigateDebounceTime; - //Keep looking at the spot - if ( perc < 0.25 ) + // Keep looking at the spot + if (perc < 0.25) { + VectorCopy(NPCInfo->investigateGoal, lookPos); + } else if (perc < 0.5f) // Look up but straight ahead { - VectorCopy( NPCInfo->investigateGoal, lookPos ); - } - else if ( perc < 0.5f ) //Look up but straight ahead + ST_OffsetLook(0.0f, lookPos); + } else if (perc < 0.75f) // Look right { - ST_OffsetLook( 0.0f, lookPos ); - } - else if ( perc < 0.75f ) //Look right - { - ST_OffsetLook( 45.0f, lookPos ); - } - else //Look left + ST_OffsetLook(45.0f, lookPos); + } else // Look left { - ST_OffsetLook( -45.0f, lookPos ); + ST_OffsetLook(-45.0f, lookPos); } - NPC_FacePosition( lookPos ); + NPC_FacePosition(lookPos); } /* @@ -969,96 +835,82 @@ NPC_BSST_Investigate ------------------------- */ -void NPC_BSST_Investigate( void ) -{ - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPC ); +void NPC_BSST_Investigate(void) { + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPC); - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( NPCInfo->confusionTime < level.time ) - { - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - //Look for an enemy - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - ST_Speech( NPC, SPEECH_DETECTED, 0 ); - NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + // Look for an enemy + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + ST_Speech(NPC, SPEECH_DETECTED, 0); + NPCInfo->tempBehavior = BS_DEFAULT; + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, NPCInfo->lastAlertID ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, NPCInfo->lastAlertID); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPCInfo->confusionTime < level.time ) - { - if ( NPC_CheckForDanger( alertEvent ) ) - {//running like hell - ST_Speech( NPC, SPEECH_COVER, 0 );//FIXME: flee sound? + // There is an event to look at + if (alertEvent >= 0) { + if (NPCInfo->confusionTime < level.time) { + if (NPC_CheckForDanger(alertEvent)) { // running like hell + ST_Speech(NPC, SPEECH_COVER, 0); // FIXME: flee sound? return; } } - if ( level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID ) - { - NPC_ST_InvestigateEvent( alertEvent, qtrue ); + if (level.alertEvents[alertEvent].ID != NPCInfo->lastAlertID) { + NPC_ST_InvestigateEvent(alertEvent, qtrue); } } } - //If we're done looking, then just return to what we were doing - if ( ( NPCInfo->investigateDebounceTime + NPCInfo->pauseTime ) < level.time ) - { + // If we're done looking, then just return to what we were doing + if ((NPCInfo->investigateDebounceTime + NPCInfo->pauseTime) < level.time) { NPCInfo->tempBehavior = BS_DEFAULT; NPCInfo->goalEntity = UpdateGoal(); - NPC_UpdateAngles( qtrue, qtrue ); - //Say something - ST_Speech( NPC, SPEECH_GIVEUP, 0 ); + NPC_UpdateAngles(qtrue, qtrue); + // Say something + ST_Speech(NPC, SPEECH_GIVEUP, 0); return; } - //FIXME: else, look for new alerts + // FIXME: else, look for new alerts - //See if we're searching for the noise's origin - if ( NPCInfo->localState == LSTATE_INVESTIGATE && (NPCInfo->goalEntity!=NULL) ) - { - //See if we're there - if ( NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 32, FlyingCreature( NPC ) ) == qfalse ) - { + // See if we're searching for the noise's origin + if (NPCInfo->localState == LSTATE_INVESTIGATE && (NPCInfo->goalEntity != NULL)) { + // See if we're there + if (NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 32, FlyingCreature(NPC)) == qfalse) { ucmd.buttons |= BUTTON_WALKING; - //Try and move there - if ( NPC_MoveToGoal( qtrue ) ) - { - //Bump our times - NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; - NPCInfo->pauseTime = level.time; + // Try and move there + if (NPC_MoveToGoal(qtrue)) { + // Bump our times + NPCInfo->investigateDebounceTime = NPCInfo->investigateCount * 5000; + NPCInfo->pauseTime = level.time; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //Otherwise we're done or have given up - //Say something - //ST_Speech( NPC, SPEECH_LOOK, 0.33f ); + // Otherwise we're done or have given up + // Say something + // ST_Speech( NPC, SPEECH_LOOK, 0.33f ); NPCInfo->localState = LSTATE_NONE; } - //Look around + // Look around ST_LookAround(); } @@ -1068,103 +920,81 @@ NPC_BSST_Patrol ------------------------- */ -void NPC_BSST_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? +void NPC_BSST_Patrol(void) { // FIXME: pick up on bodies of dead buddies? - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPC ); + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPC); - if ( NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue ); + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPC_ST_InvestigateEvent( alertEvent, qfalse ) ) - {//actually going to investigate it - NPC_UpdateAngles( qtrue, qtrue ); + // There is an event to look at + if (alertEvent >= 0) { + if (NPC_ST_InvestigateEvent(alertEvent, qfalse)) { // actually going to investigate it + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { ucmd.buttons |= BUTTON_WALKING; - //ST_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); - } - else// if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - if ( NPC->client->NPC_class != CLASS_IMPERIAL && NPC->client->NPC_class != CLASS_IMPWORKER ) - {//imperials do not look around - if ( TIMER_Done( NPC, "enemyLastVisible" ) ) - {//nothing suspicious, look around - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand( -90, 90 ); + // ST_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); + } else // if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) + { + if (NPC->client->NPC_class != CLASS_IMPERIAL && NPC->client->NPC_class != CLASS_IMPWORKER) { // imperials do not look around + if (TIMER_Done(NPC, "enemyLastVisible")) { // nothing suspicious, look around + if (!Q_irand(0, 30)) { + NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCInfo->desiredPitch = Q_irand(-20, 20); } } } } - NPC_UpdateAngles( qtrue, qtrue ); - //TEMP hack for Imperial stand anim - if ( NPC->client->NPC_class == CLASS_IMPERIAL || NPC->client->NPC_class == CLASS_IMPWORKER ) - {//hack - if ( ucmd.forwardmove || ucmd.rightmove || ucmd.upmove ) - {//moving + NPC_UpdateAngles(qtrue, qtrue); + // TEMP hack for Imperial stand anim + if (NPC->client->NPC_class == CLASS_IMPERIAL || NPC->client->NPC_class == CLASS_IMPWORKER) { // hack + if (ucmd.forwardmove || ucmd.rightmove || ucmd.upmove) { // moving - if( (!NPC->client->ps.torsoAnimTimer) || (NPC->client->ps.torsoAnim == BOTH_STAND4) ) - { - if ( (ucmd.buttons&BUTTON_WALKING) && !(NPCInfo->scriptFlags&SCF_RUNNING) ) - {//not running, only set upper anim + if ((!NPC->client->ps.torsoAnimTimer) || (NPC->client->ps.torsoAnim == BOTH_STAND4)) { + if ((ucmd.buttons & BUTTON_WALKING) && !(NPCInfo->scriptFlags & SCF_RUNNING)) { // not running, only set upper anim // No longer overrides scripted anims - NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = 200; } } - } - else - {//standing still, set both torso and legs anim + } else { // standing still, set both torso and legs anim // No longer overrides scripted anims - if( ( !NPC->client->ps.torsoAnimTimer || (NPC->client->ps.torsoAnim == BOTH_STAND4) ) && - ( !NPC->client->ps.legsAnimTimer || (NPC->client->ps.legsAnim == BOTH_STAND4) ) ) - { - NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((!NPC->client->ps.torsoAnimTimer || (NPC->client->ps.torsoAnim == BOTH_STAND4)) && + (!NPC->client->ps.legsAnimTimer || (NPC->client->ps.legsAnim == BOTH_STAND4))) { + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPC->client->ps.torsoAnimTimer = NPC->client->ps.legsAnimTimer = 200; } } - //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way - if ( NPC->client->ps.weapon != WP_NONE ) - { - ChangeWeapon( NPC, WP_NONE ); + // FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way + if (NPC->client->ps.weapon != WP_NONE) { + ChangeWeapon(NPC, WP_NONE); NPC->client->ps.weapon = WP_NONE; NPC->client->ps.weaponstate = WEAPON_READY; - if ( NPC->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( NPC->ghoul2, NPC->weaponModel ); + if (NPC->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(NPC->ghoul2, NPC->weaponModel); NPC->weaponModel = -1; } } @@ -1200,39 +1030,30 @@ ST_CheckMoveState ------------------------- */ -static void ST_CheckMoveState( void ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//moving toward a goal that a script is waiting on, so don't stop for anything! +static void ST_CheckMoveState(void) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // moving toward a goal that a script is waiting on, so don't stop for anything! AImove = qtrue; } - //See if we're a scout - else if ( NPCInfo->squadState == SQUAD_SCOUT ) - { - //If we're supposed to stay put, then stand there and fire - if ( TIMER_Done( NPC, "stick" ) == qfalse ) - { + // See if we're a scout + else if (NPCInfo->squadState == SQUAD_SCOUT) { + // If we're supposed to stay put, then stand there and fire + if (TIMER_Done(NPC, "stick") == qfalse) { AImove = qfalse; return; } - //Otherwise, if we can see our target, just shoot - if ( enemyLOS ) - { - if ( enemyCS ) - { - //if we're going after our enemy, we can stop now - if ( NPCInfo->goalEntity == NPC->enemy ) - { - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); + // Otherwise, if we can see our target, just shoot + if (enemyLOS) { + if (enemyCS) { + // if we're going after our enemy, we can stop now + if (NPCInfo->goalEntity == NPC->enemy) { + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT); AImove = qfalse; return; } } - } - else - { - //Move to find our target + } else { + // Move to find our target faceEnemy = qfalse; } @@ -1246,151 +1067,126 @@ static void ST_CheckMoveState( void ) } */ - //ucmd.buttons |= BUTTON_CAREFUL; + // ucmd.buttons |= BUTTON_CAREFUL; } - //See if we're running away - else if ( NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( NPCInfo->goalEntity ) - { + // See if we're running away + else if (NPCInfo->squadState == SQUAD_RETREAT) { + if (NPCInfo->goalEntity) { faceEnemy = qfalse; - } - else - {//um, lost our goal? Just stand and shoot, then + } else { // um, lost our goal? Just stand and shoot, then NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; } } - //see if we're heading to some other combatPoint - else if ( NPCInfo->squadState == SQUAD_TRANSITION ) - { - //ucmd.buttons |= BUTTON_CAREFUL; - if ( !NPCInfo->goalEntity ) - {//um, lost our goal? Just stand and shoot, then + // see if we're heading to some other combatPoint + else if (NPCInfo->squadState == SQUAD_TRANSITION) { + // ucmd.buttons |= BUTTON_CAREFUL; + if (!NPCInfo->goalEntity) { // um, lost our goal? Just stand and shoot, then NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; } } - //see if we're at point, duck and fire - else if ( NPCInfo->squadState == SQUAD_POINT ) - { - if ( TIMER_Done( NPC, "stick" ) ) - { - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); + // see if we're at point, duck and fire + else if (NPCInfo->squadState == SQUAD_POINT) { + if (TIMER_Done(NPC, "stick")) { + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT); return; } AImove = qfalse; return; } - //see if we're just standing around - else if ( NPCInfo->squadState == SQUAD_STAND_AND_SHOOT ) - {//from this squadState we can transition to others? + // see if we're just standing around + else if (NPCInfo->squadState == SQUAD_STAND_AND_SHOOT) { // from this squadState we can transition to others? AImove = qfalse; return; } - //see if we're hiding - else if ( NPCInfo->squadState == SQUAD_COVER ) - { - //Should we duck? + // see if we're hiding + else if (NPCInfo->squadState == SQUAD_COVER) { + // Should we duck? AImove = qfalse; return; } - //see if we're just standing around - else if ( NPCInfo->squadState == SQUAD_IDLE ) - { - if ( !NPCInfo->goalEntity ) - { + // see if we're just standing around + else if (NPCInfo->squadState == SQUAD_IDLE) { + if (!NPCInfo->goalEntity) { AImove = qfalse; return; } } //?? - else - {//invalid squadState! - } - - //See if we're moving towards a goal, not the enemy - if ( ( NPCInfo->goalEntity != NPC->enemy ) && ( NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature( NPC ) ) || - ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) && NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - {//either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and found our enemy - int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - //done fleeing, obviously - TIMER_Set( NPC, "duck", (NPC->max_health - NPC->health) * 100 ); - TIMER_Set( NPC, "hideTime", Q_irand( 3000, 7000 ) ); - TIMER_Set( NPC, "flee", -level.time ); + else { // invalid squadState! + } + + // See if we're moving towards a goal, not the enemy + if ((NPCInfo->goalEntity != NPC->enemy) && (NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, NPCInfo->goalEntity->currentOrigin, 16, FlyingCreature(NPC)) || + (!Q3_TaskIDPending(NPC, TID_MOVE_NAV) && NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && + enemyDist <= 10000)) { // either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and + // found our enemy + int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + // done fleeing, obviously + TIMER_Set(NPC, "duck", (NPC->max_health - NPC->health) * 100); + TIMER_Set(NPC, "hideTime", Q_irand(3000, 7000)); + TIMER_Set(NPC, "flee", -level.time); newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } - AI_GroupUpdateSquadstates( NPCInfo->group, NPC, newSquadState ); + AI_GroupUpdateSquadstates(NPCInfo->group, NPC, newSquadState); NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 4000 ) ); + // don't attack right away + TIMER_Set(NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet + TIMER_Set(NPC, "roamTime", Q_irand(1000, 4000)); return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPC, "roamTime", Q_irand(4000, 8000)); } } -void ST_ResolveBlockedShot( int hit ) -{ - int stuckTime; - //figure out how long we intend to stand here, max - if ( TIMER_Get( NPC, "roamTime" ) > TIMER_Get( NPC, "stick" ) ) - { - stuckTime = TIMER_Get( NPC, "roamTime" )-level.time; - } - else - { - stuckTime = TIMER_Get( NPC, "stick" )-level.time; +void ST_ResolveBlockedShot(int hit) { + int stuckTime; + // figure out how long we intend to stand here, max + if (TIMER_Get(NPC, "roamTime") > TIMER_Get(NPC, "stick")) { + stuckTime = TIMER_Get(NPC, "roamTime") - level.time; + } else { + stuckTime = TIMER_Get(NPC, "stick") - level.time; } - if ( TIMER_Done( NPC, "duck" ) ) - {//we're not ducking - if ( AI_GroupContainsEntNum( NPCInfo->group, hit ) ) - { + if (TIMER_Done(NPC, "duck")) { // we're not ducking + if (AI_GroupContainsEntNum(NPCInfo->group, hit)) { gentity_t *member = &g_entities[hit]; - if ( TIMER_Done( member, "duck" ) ) - {//they aren't ducking - if ( TIMER_Done( member, "stand" ) ) - {//they're not being forced to stand - //tell them to duck at least as long as I'm not moving - TIMER_Set( member, "duck", stuckTime ); + if (TIMER_Done(member, "duck")) { // they aren't ducking + if (TIMER_Done(member, "stand")) { // they're not being forced to stand + // tell them to duck at least as long as I'm not moving + TIMER_Set(member, "duck", stuckTime); return; } } } - } - else - {//maybe we should stand - if ( TIMER_Done( NPC, "stand" ) ) - {//stand for as long as we'll be here - TIMER_Set( NPC, "stand", stuckTime ); + } else { // maybe we should stand + if (TIMER_Done(NPC, "stand")) { // stand for as long as we'll be here + TIMER_Set(NPC, "stand", stuckTime); return; } } - //Hmm, can't resolve this by telling them to duck or telling me to stand - //We need to move! - TIMER_Set( NPC, "roamTime", -1 ); - TIMER_Set( NPC, "stick", -1 ); - TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( NPC, "attakDelay", Q_irand( 1000, 3000 ) ); + // Hmm, can't resolve this by telling them to duck or telling me to stand + // We need to move! + TIMER_Set(NPC, "roamTime", -1); + TIMER_Set(NPC, "stick", -1); + TIMER_Set(NPC, "duck", -1); + TIMER_Set(NPC, "attakDelay", Q_irand(1000, 3000)); } /* @@ -1399,122 +1195,110 @@ ST_CheckFireState ------------------------- */ -static void ST_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void ST_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCInfo->squadState == SQUAD_RETREAT || NPCInfo->squadState == SQUAD_TRANSITION || + NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //See if we should continue to fire on their last position - //!TIMER_Done( NPC, "stick" ) || - if ( !hitAlly //we're not going to hit an ally - && enemyInFOV //enemy is in our FOV //FIXME: or we don't have a clear LOS? - && NPCInfo->enemyLastSeenTime > 0 //we've seen the enemy - && NPCInfo->group //have a group - && (NPCInfo->group->numState[SQUAD_RETREAT]>0||NPCInfo->group->numState[SQUAD_TRANSITION]>0||NPCInfo->group->numState[SQUAD_SCOUT]>0) )//laying down covering fire + // See if we should continue to fire on their last position + //! TIMER_Done( NPC, "stick" ) || + if (!hitAlly // we're not going to hit an ally + && enemyInFOV // enemy is in our FOV //FIXME: or we don't have a clear LOS? + && NPCInfo->enemyLastSeenTime > 0 // we've seen the enemy + && NPCInfo->group // have a group + && (NPCInfo->group->numState[SQUAD_RETREAT] > 0 || NPCInfo->group->numState[SQUAD_TRANSITION] > 0 || + NPCInfo->group->numState[SQUAD_SCOUT] > 0)) // laying down covering fire { - if ( level.time - NPCInfo->enemyLastSeenTime < 10000 &&//we have seem the enemy in the last 10 seconds - (!NPCInfo->group || level.time - NPCInfo->group->lastSeenEnemyTime < 10000 ))//we are not in a group or the group has seen the enemy in the last 10 seconds + if (level.time - NPCInfo->enemyLastSeenTime < 10000 && // we have seem the enemy in the last 10 seconds + (!NPCInfo->group || + level.time - NPCInfo->group->lastSeenEnemyTime < 10000)) // we are not in a group or the group has seen the enemy in the last 10 seconds { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - gi.trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - float distThreshold = 16384/*128*128*/;//default - switch ( NPC->s.weapon ) - { + // see if impact would be too close to me + float distThreshold = 16384 /*128*128*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - float dist = DistanceSquared( impactPos, muzzle ); + float dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCInfo->enemyLastSeenTime > 5000 || - (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000 )) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - switch ( NPC->s.weapon ) - { + } else if (level.time - NPCInfo->enemyLastSeenTime > 5000 || + (NPCInfo->group && level.time - NPCInfo->group->lastSeenEnemyTime > 5000)) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 262144/*512*512*/; + distThreshold = 262144 /*512*512*/; break; case WP_REPEATER: - if ( NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } break; default: break; } - dist = DistanceSquared( impactPos, NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCInfo->desiredYaw = angles[YAW]; - NPCInfo->desiredPitch = angles[PITCH]; + NPCInfo->desiredYaw = angles[YAW]; + NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; faceEnemy = qfalse; - //AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); + // AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); return; } } @@ -1522,179 +1306,138 @@ static void ST_CheckFireState( void ) } } -void ST_TrackEnemy( gentity_t *self, vec3_t enemyPos ) -{ - //clear timers - TIMER_Set( self, "attackDelay", Q_irand( 1000, 2000 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint ); - //go after his last seen pos - NPC_SetMoveGoal( self, enemyPos, 16, qfalse ); +void ST_TrackEnemy(gentity_t *self, vec3_t enemyPos) { + // clear timers + TIMER_Set(self, "attackDelay", Q_irand(1000, 2000)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(500, 1500)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint); + // go after his last seen pos + NPC_SetMoveGoal(self, enemyPos, 16, qfalse); } -int ST_ApproachEnemy( gentity_t *self ) -{ - TIMER_Set( self, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 1000, 2000 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint ); - //return the relevant combat point flags - return (CP_CLEAR|CP_CLOSEST); +int ST_ApproachEnemy(gentity_t *self) { + TIMER_Set(self, "attackDelay", Q_irand(250, 500)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(1000, 2000)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint); + // return the relevant combat point flags + return (CP_CLEAR | CP_CLOSEST); } -void ST_HuntEnemy( gentity_t *self ) -{ - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack - //TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( NPC, "stick", Q_irand( 250, 1000 ) ); - TIMER_Set( NPC, "stand", -1 ); - TIMER_Set( NPC, "scoutTime", TIMER_Get( NPC, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( NPCInfo->combatPoint ); - //go directly after the enemy - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { +void ST_HuntEnemy(gentity_t *self) { + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack + // TIMER_Set( NPC, "duck", -1 ); + TIMER_Set(NPC, "stick", Q_irand(250, 1000)); + TIMER_Set(NPC, "stand", -1); + TIMER_Set(NPC, "scoutTime", TIMER_Get(NPC, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(NPCInfo->combatPoint); + // go directly after the enemy + if (NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { self->NPC->goalEntity = NPC->enemy; } } -void ST_TransferTimers( gentity_t *self, gentity_t *other ) -{ - TIMER_Set( other, "attackDelay", TIMER_Get( self, "attackDelay" )-level.time ); - TIMER_Set( other, "duck", TIMER_Get( self, "duck" )-level.time ); - TIMER_Set( other, "stick", TIMER_Get( self, "stick" )-level.time ); - TIMER_Set( other, "scoutTime", TIMER_Get( self, "scout" )-level.time ); - TIMER_Set( other, "roamTime", TIMER_Get( self, "roamTime" )-level.time ); - TIMER_Set( other, "stand", TIMER_Get( self, "stand" )-level.time ); - TIMER_Set( self, "attackDelay", -1 ); - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", -1 ); - TIMER_Set( self, "scoutTime", -1 ); - TIMER_Set( self, "roamTime", -1 ); - TIMER_Set( self, "stand", -1 ); +void ST_TransferTimers(gentity_t *self, gentity_t *other) { + TIMER_Set(other, "attackDelay", TIMER_Get(self, "attackDelay") - level.time); + TIMER_Set(other, "duck", TIMER_Get(self, "duck") - level.time); + TIMER_Set(other, "stick", TIMER_Get(self, "stick") - level.time); + TIMER_Set(other, "scoutTime", TIMER_Get(self, "scout") - level.time); + TIMER_Set(other, "roamTime", TIMER_Get(self, "roamTime") - level.time); + TIMER_Set(other, "stand", TIMER_Get(self, "stand") - level.time); + TIMER_Set(self, "attackDelay", -1); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stick", -1); + TIMER_Set(self, "scoutTime", -1); + TIMER_Set(self, "roamTime", -1); + TIMER_Set(self, "stand", -1); } -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ) -{ - if ( Q3_TaskIDPending( self, TID_MOVE_NAV ) ) - {//can't transfer movegoal when a script we're running is waiting to complete +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other) { + if (Q3_TaskIDPending(self, TID_MOVE_NAV)) { // can't transfer movegoal when a script we're running is waiting to complete return; } - if ( self->NPC->combatPoint != -1 ) - {//I've got a combatPoint I'm going to, give it to him + if (self->NPC->combatPoint != -1) { // I've got a combatPoint I'm going to, give it to him self->NPC->lastFailedCombatPoint = other->NPC->combatPoint = self->NPC->combatPoint; self->NPC->combatPoint = -1; - } - else - {//I must be going for a goal, give that to him instead - if ( self->NPC->goalEntity == self->NPC->tempGoal ) - { - NPC_SetMoveGoal( - other, self->NPC->tempGoal->currentOrigin, self->NPC->goalRadius, - ((self->NPC->tempGoal->svFlags & SVF_NAVGOAL) ? qtrue : qfalse)); - } - else - { + } else { // I must be going for a goal, give that to him instead + if (self->NPC->goalEntity == self->NPC->tempGoal) { + NPC_SetMoveGoal(other, self->NPC->tempGoal->currentOrigin, self->NPC->goalRadius, ((self->NPC->tempGoal->svFlags & SVF_NAVGOAL) ? qtrue : qfalse)); + } else { other->NPC->goalEntity = self->NPC->goalEntity; } } - //give him my squadstate - AI_GroupUpdateSquadstates( self->NPC->group, other, NPCInfo->squadState ); + // give him my squadstate + AI_GroupUpdateSquadstates(self->NPC->group, other, NPCInfo->squadState); - //give him my timers and clear mine - ST_TransferTimers( self, other ); + // give him my timers and clear mine + ST_TransferTimers(self, other); - //now make me stand around for a second or two at least - AI_GroupUpdateSquadstates( self->NPC->group, self, SQUAD_STAND_AND_SHOOT ); - TIMER_Set( self, "stand", Q_irand( 1000, 3000 ) ); + // now make me stand around for a second or two at least + AI_GroupUpdateSquadstates(self->NPC->group, self, SQUAD_STAND_AND_SHOOT); + TIMER_Set(self, "stand", Q_irand(1000, 3000)); } -int ST_GetCPFlags( void ) -{ +int ST_GetCPFlags(void) { int cpFlags = 0; - if ( NPC && NPCInfo->group ) - { - if ( NPC == NPCInfo->group->commander && NPC->client->NPC_class == CLASS_IMPERIAL ) - {//imperials hang back and give orders - if ( NPCInfo->group->numGroup > 1 && Q_irand( -3, NPCInfo->group->numGroup ) > 1 ) - {//FIXME: make sure he;s giving orders with these lines - if ( Q_irand( 0, 1 ) ) - { - ST_Speech( NPC, SPEECH_CHASE, 0.5 ); - } - else - { - ST_Speech( NPC, SPEECH_YELL, 0.5 ); + if (NPC && NPCInfo->group) { + if (NPC == NPCInfo->group->commander && NPC->client->NPC_class == CLASS_IMPERIAL) { // imperials hang back and give orders + if (NPCInfo->group->numGroup > 1 && Q_irand(-3, NPCInfo->group->numGroup) > 1) { // FIXME: make sure he;s giving orders with these lines + if (Q_irand(0, 1)) { + ST_Speech(NPC, SPEECH_CHASE, 0.5); + } else { + ST_Speech(NPC, SPEECH_YELL, 0.5); } } - cpFlags = (CP_CLEAR|CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); - } - else if ( NPCInfo->group->morale < 0 ) - {//hide - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); - } - else if ( NPCInfo->group->morale < NPCInfo->group->numGroup ) - {//morale is low for our size + cpFlags = (CP_CLEAR | CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); + } else if (NPCInfo->group->morale < 0) { // hide + cpFlags = (CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); + } else if (NPCInfo->group->morale < NPCInfo->group->numGroup) { // morale is low for our size int moraleDrop = NPCInfo->group->numGroup - NPCInfo->group->morale; - if ( moraleDrop < -6 ) - {//flee (no clear shot needed) - cpFlags = (CP_FLEE|CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < -3 ) - {//retreat (no clear shot needed) - cpFlags = (CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < 0 ) - {//cover (no clear shot needed) - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE); - } - } - else - { + if (moraleDrop < -6) { // flee (no clear shot needed) + cpFlags = (CP_FLEE | CP_RETREAT | CP_COVER | CP_AVOID | CP_SAFE); + } else if (moraleDrop < -3) { // retreat (no clear shot needed) + cpFlags = (CP_RETREAT | CP_COVER | CP_AVOID | CP_SAFE); + } else if (moraleDrop < 0) { // cover (no clear shot needed) + cpFlags = (CP_COVER | CP_AVOID | CP_SAFE); + } + } else { int moraleBoost = NPCInfo->group->morale - NPCInfo->group->numGroup; - if ( moraleBoost > 20 ) - {//charge to any one and outflank (no cover needed) - cpFlags = (CP_CLEAR|CP_FLANK|CP_APPROACH_ENEMY); - } - else if ( moraleBoost > 15 ) - {//charge to closest one (no cover needed) - cpFlags = (CP_CLEAR|CP_CLOSEST|CP_APPROACH_ENEMY); - } - else if ( moraleBoost > 10 ) - {//charge closer (no cover needed) - cpFlags = (CP_CLEAR|CP_APPROACH_ENEMY); + if (moraleBoost > 20) { // charge to any one and outflank (no cover needed) + cpFlags = (CP_CLEAR | CP_FLANK | CP_APPROACH_ENEMY); + } else if (moraleBoost > 15) { // charge to closest one (no cover needed) + cpFlags = (CP_CLEAR | CP_CLOSEST | CP_APPROACH_ENEMY); + } else if (moraleBoost > 10) { // charge closer (no cover needed) + cpFlags = (CP_CLEAR | CP_APPROACH_ENEMY); } } } - if ( !cpFlags ) - { - //at some medium level of morale - switch( Q_irand( 0, 3 ) ) - { - case 0://just take the nearest one - cpFlags = (CP_CLEAR|CP_COVER|CP_NEAREST); + if (!cpFlags) { + // at some medium level of morale + switch (Q_irand(0, 3)) { + case 0: // just take the nearest one + cpFlags = (CP_CLEAR | CP_COVER | CP_NEAREST); break; - case 1://take one closer to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_APPROACH_ENEMY); + case 1: // take one closer to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_APPROACH_ENEMY); break; - case 2://take the one closest to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_CLOSEST|CP_APPROACH_ENEMY); + case 2: // take the one closest to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_CLOSEST | CP_APPROACH_ENEMY); break; - case 3://take the one on the other side of the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); + case 3: // take the one on the other side of the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); break; } } - if ( NPC && (NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPC && (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } return cpFlags; @@ -1712,64 +1455,53 @@ FIXME: work in pairs? ------------------------- */ -void ST_Commander( void ) -{ - int i, j; - int cp, cpFlags_org, cpFlags; - AIGroupInfo_t *group = NPCInfo->group; - gentity_t *member;//, *buddy; - qboolean runner = qfalse; - qboolean enemyLost = qfalse; - qboolean enemyProtected = qfalse; - //qboolean scouting = qfalse; - int squadState; - float avoidDist; +void ST_Commander(void) { + int i, j; + int cp, cpFlags_org, cpFlags; + AIGroupInfo_t *group = NPCInfo->group; + gentity_t *member; //, *buddy; + qboolean runner = qfalse; + qboolean enemyLost = qfalse; + qboolean enemyProtected = qfalse; + // qboolean scouting = qfalse; + int squadState; + float avoidDist; group->processed = qtrue; - if ( group->enemy == NULL || group->enemy->client == NULL ) - {//hmm, no enemy...?! + if (group->enemy == NULL || group->enemy->client == NULL) { // hmm, no enemy...?! return; } - //FIXME: have this group commander check the enemy group (if any) and see if they have + // FIXME: have this group commander check the enemy group (if any) and see if they have // superior numbers. If they do, fall back rather than advance. If you have // superior numbers, advance on them. - //FIXME: find the group commander and have him occasionally give orders when there is speech - //FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left + // FIXME: find the group commander and have him occasionally give orders when there is speech + // FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left SaveNPCGlobals(); - if ( group->lastSeenEnemyTime < level.time - 180000 ) - {//dissolve the group - ST_Speech( NPC, SPEECH_LOST, 0.0f ); - group->enemy->waypoint = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - for ( i = 0; i < group->numGroup; i++ ) - { + if (group->lastSeenEnemyTime < level.time - 180000) { // dissolve the group + ST_Speech(NPC, SPEECH_LOST, 0.0f); + group->enemy->waypoint = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - SetNPCGlobals( member ); - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't break from that + SetNPCGlobals(member); + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't break from that continue; } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to move on my own + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to move on my own continue; } - //Lost enemy for three minutes? go into search mode? - G_ClearEnemy( NPC ); - NPC->waypoint = NAV_FindClosestWaypointForEnt( NPC, group->enemy->waypoint ); - if ( NPC->waypoint == WAYPOINT_NONE ) - { - NPCInfo->behaviorState = BS_DEFAULT;//BS_PATROL; - } - else if ( group->enemy->waypoint == WAYPOINT_NONE || (navigator.GetPathCost( NPC->waypoint, group->enemy->waypoint ) >= Q3_INFINITE) ) - { - NPC_BSSearchStart( NPC->waypoint, BS_SEARCH ); - } - else - { - NPC_BSSearchStart( group->enemy->waypoint, BS_SEARCH ); + // Lost enemy for three minutes? go into search mode? + G_ClearEnemy(NPC); + NPC->waypoint = NAV_FindClosestWaypointForEnt(NPC, group->enemy->waypoint); + if (NPC->waypoint == WAYPOINT_NONE) { + NPCInfo->behaviorState = BS_DEFAULT; // BS_PATROL; + } else if (group->enemy->waypoint == WAYPOINT_NONE || (navigator.GetPathCost(NPC->waypoint, group->enemy->waypoint) >= Q3_INFINITE)) { + NPC_BSSearchStart(NPC->waypoint, BS_SEARCH); + } else { + NPC_BSSearchStart(group->enemy->waypoint, BS_SEARCH); } } group->enemy = NULL; @@ -1777,8 +1509,7 @@ void ST_Commander( void ) return; } - - //See if anyone in our group is not alerted and alert them + // See if anyone in our group is not alerted and alert them /* for ( i = 0; i < group->numGroup; i++ ) { @@ -1800,140 +1531,111 @@ void ST_Commander( void ) } } */ - //Okay, everyone is mad + // Okay, everyone is mad - //see if anyone is running - if ( group->numState[SQUAD_SCOUT] > 0 || - group->numState[SQUAD_TRANSITION] > 0 || - group->numState[SQUAD_RETREAT] > 0 ) - {//someone is running + // see if anyone is running + if (group->numState[SQUAD_SCOUT] > 0 || group->numState[SQUAD_TRANSITION] > 0 || group->numState[SQUAD_RETREAT] > 0) { // someone is running runner = qtrue; } - if ( /*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && group->lastSeenEnemyTime < level.time - 30000 ) - {//no-one has seen the enemy for 30 seconds// and no-one is running after him - if ( group->commander && !Q_irand( 0, 1 ) ) - { - ST_Speech( group->commander, SPEECH_ESCAPING, 0.0f ); + if (/*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && + group->lastSeenEnemyTime < level.time - 30000) { // no-one has seen the enemy for 30 seconds// and no-one is running after him + if (group->commander && !Q_irand(0, 1)) { + ST_Speech(group->commander, SPEECH_ESCAPING, 0.0f); + } else { + ST_Speech(NPC, SPEECH_ESCAPING, 0.0f); } - else - { - ST_Speech( NPC, SPEECH_ESCAPING, 0.0f ); - } - //don't say this again + // don't say this again NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } - if ( group->lastSeenEnemyTime < level.time - 10000 ) - {//no-one has seen the enemy for at least 10 seconds! Should send a scout + if (group->lastSeenEnemyTime < level.time - 10000) { // no-one has seen the enemy for at least 10 seconds! Should send a scout enemyLost = qtrue; } - if ( group->lastClearShotTime < level.time - 5000 ) - {//no-one has had a clear shot for 5 seconds! + if (group->lastClearShotTime < level.time - 5000) { // no-one has had a clear shot for 5 seconds! enemyProtected = qtrue; } - //Go through the list: + // Go through the list: - //Everyone should try to get to a combat point if possible - int curMemberNum, lastMemberNum; - if ( d_asynchronousGroupAI->integer ) - {//do one member a turn + // Everyone should try to get to a combat point if possible + int curMemberNum, lastMemberNum; + if (d_asynchronousGroupAI->integer) { // do one member a turn group->activeMemberNum++; - if ( group->activeMemberNum >= group->numGroup ) - { + if (group->activeMemberNum >= group->numGroup) { group->activeMemberNum = 0; } curMemberNum = group->activeMemberNum; lastMemberNum = curMemberNum + 1; - } - else - { + } else { curMemberNum = 0; lastMemberNum = group->numGroup; } - for ( i = curMemberNum; i < lastMemberNum; i++ ) - { - //reset combat point flags + for (i = curMemberNum; i < lastMemberNum; i++) { + // reset combat point flags cp = -1; cpFlags = 0; squadState = SQUAD_IDLE; avoidDist = 0; - //scouting = qfalse; + // scouting = qfalse; - //get the next guy + // get the next guy member = &g_entities[group->member[i].number]; - if ( !member->enemy ) - {//don't include guys that aren't angry + if (!member->enemy) { // don't include guys that aren't angry continue; } - SetNPCGlobals( member ); + SetNPCGlobals(member); - if ( !TIMER_Done( NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPC, "flee")) { // running away continue; } - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go continue; } - if ( NPC->s.weapon == WP_NONE - && NPCInfo->goalEntity - && NPCInfo->goalEntity == NPCInfo->tempGoal - && NPCInfo->goalEntity->enemy - && NPCInfo->goalEntity->enemy->s.eType == ET_ITEM ) - {//running to pick up a gun, don't do other logic + if (NPC->s.weapon == WP_NONE && NPCInfo->goalEntity && NPCInfo->goalEntity == NPCInfo->tempGoal && NPCInfo->goalEntity->enemy && + NPCInfo->goalEntity->enemy->s.eType == ET_ITEM) { // running to pick up a gun, don't do other logic continue; } - //see if this member should start running (only if have no officer... FIXME: should always run from AEL_DANGER_GREAT?) - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { - if ( NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - ST_Speech( NPC, SPEECH_COVER, 0 ); + // see if this member should start running (only if have no officer... FIXME: should always run from AEL_DANGER_GREAT?) + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { + if (NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + ST_Speech(NPC, SPEECH_COVER, 0); continue; } } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to do combat-movement + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to do combat-movement continue; } - //check the local state - if ( NPCInfo->squadState != SQUAD_RETREAT ) - {//not already retreating - if ( NPC->client->ps.weapon == WP_NONE ) - {//weaponless, should be hiding - if ( NPCInfo->goalEntity == NULL || NPCInfo->goalEntity->enemy == NULL || NPCInfo->goalEntity->enemy->s.eType != ET_ITEM ) - {//not running after a pickup - if ( TIMER_Done( NPC, "hideTime" ) || (DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < 65536 && NPC_ClearLOS( NPC->enemy )) ) - {//done hiding or enemy near and can see us - //er, start another flee I guess? - NPC_StartFlee( NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - }//else, just hang here + // check the local state + if (NPCInfo->squadState != SQUAD_RETREAT) { // not already retreating + if (NPC->client->ps.weapon == WP_NONE) { // weaponless, should be hiding + if (NPCInfo->goalEntity == NULL || NPCInfo->goalEntity->enemy == NULL || + NPCInfo->goalEntity->enemy->s.eType != ET_ITEM) { // not running after a pickup + if (TIMER_Done(NPC, "hideTime") || (DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < 65536 && + NPC_ClearLOS(NPC->enemy))) { // done hiding or enemy near and can see us + // er, start another flee I guess? + NPC_StartFlee(NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } // else, just hang here } continue; } - if ( TIMER_Done( NPC, "roamTime" ) && TIMER_Done( NPC, "hideTime" ) && NPC->health > 10 && !gi.inPVS( group->enemy->currentOrigin, NPC->currentOrigin ) ) - {//cant even see enemy - //better go after him - cpFlags |= (CP_CLEAR|CP_COVER); - } - else if ( NPCInfo->localState == LSTATE_UNDERFIRE ) - {//we've been shot - switch( group->enemy->client->ps.weapon ) - { + if (TIMER_Done(NPC, "roamTime") && TIMER_Done(NPC, "hideTime") && NPC->health > 10 && + !gi.inPVS(group->enemy->currentOrigin, NPC->currentOrigin)) { // cant even see enemy + // better go after him + cpFlags |= (CP_CLEAR | CP_COVER); + } else if (NPCInfo->localState == LSTATE_UNDERFIRE) { // we've been shot + switch (group->enemy->client->ps.weapon) { case WP_SABER: - if ( DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < 65536 )//256 squared + if (DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < 65536) // 256 squared { - cpFlags |= (CP_AVOID_ENEMY|CP_COVER|CP_AVOID|CP_RETREAT); - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { + cpFlags |= (CP_AVOID_ENEMY | CP_COVER | CP_AVOID | CP_RETREAT); + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { squadState = SQUAD_RETREAT; } avoidDist = 256; @@ -1944,40 +1646,28 @@ void ST_Commander( void ) cpFlags |= (CP_COVER); break; } - if ( NPC->health <= 10 ) - { - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { - cpFlags |= (CP_FLEE|CP_AVOID|CP_RETREAT); + if (NPC->health <= 10) { + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { + cpFlags |= (CP_FLEE | CP_AVOID | CP_RETREAT); squadState = SQUAD_RETREAT; } } - } - else - {//not hit, see if there are other reasons we should run - if ( gi.inPVS( NPC->currentOrigin, group->enemy->currentOrigin ) ) - {//in the same room as enemy - if ( NPC->client->ps.weapon == WP_ROCKET_LAUNCHER && - DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < MIN_ROCKET_DIST_SQUARED && - NPCInfo->squadState != SQUAD_TRANSITION ) - {//too close for me to fire my weapon and I'm not already on the move - cpFlags |= (CP_AVOID_ENEMY|CP_CLEAR|CP_AVOID); + } else { // not hit, see if there are other reasons we should run + if (gi.inPVS(NPC->currentOrigin, group->enemy->currentOrigin)) { // in the same room as enemy + if (NPC->client->ps.weapon == WP_ROCKET_LAUNCHER && + DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < MIN_ROCKET_DIST_SQUARED && + NPCInfo->squadState != SQUAD_TRANSITION) { // too close for me to fire my weapon and I'm not already on the move + cpFlags |= (CP_AVOID_ENEMY | CP_CLEAR | CP_AVOID); avoidDist = 256; - } - else - { - switch( group->enemy->client->ps.weapon ) - { + } else { + switch (group->enemy->client->ps.weapon) { case WP_SABER: - if ( group->enemy->client->ps.saberLength > 0 ) - { - if ( DistanceSquared( group->enemy->currentOrigin, NPC->currentOrigin ) < 65536 ) - { - if ( TIMER_Done( NPC, "hideTime" ) ) - { - if ( NPCInfo->squadState != SQUAD_TRANSITION ) - {//not already moving: FIXME: we need to see if where we're going is good now? - cpFlags |= (CP_AVOID_ENEMY|CP_CLEAR|CP_AVOID); + if (group->enemy->client->ps.saberLength > 0) { + if (DistanceSquared(group->enemy->currentOrigin, NPC->currentOrigin) < 65536) { + if (TIMER_Done(NPC, "hideTime")) { + if (NPCInfo->squadState != + SQUAD_TRANSITION) { // not already moving: FIXME: we need to see if where we're going is good now? + cpFlags |= (CP_AVOID_ENEMY | CP_CLEAR | CP_AVOID); avoidDist = 256; } } @@ -1991,168 +1681,122 @@ void ST_Commander( void ) } } - if ( !cpFlags ) - {//okay, we have no new enemy-driven reason to run... let's use tactics now - if ( runner && NPCInfo->combatPoint != -1 ) - {//someone is running and we have a combat point already - if ( NPCInfo->squadState != SQUAD_SCOUT && - NPCInfo->squadState != SQUAD_TRANSITION && - NPCInfo->squadState != SQUAD_RETREAT ) - {//it's not us - if ( TIMER_Done( NPC, "verifyCP" ) && DistanceSquared( NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin ) > 64*64 ) - {//1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... - //uh, WTF, we're not on our combat point? - //er, try again, I guess? + if (!cpFlags) { // okay, we have no new enemy-driven reason to run... let's use tactics now + if (runner && NPCInfo->combatPoint != -1) { // someone is running and we have a combat point already + if (NPCInfo->squadState != SQUAD_SCOUT && NPCInfo->squadState != SQUAD_TRANSITION && NPCInfo->squadState != SQUAD_RETREAT) { // it's not us + if (TIMER_Done(NPC, "verifyCP") && + DistanceSquared(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin) > + 64 * 64) { // 1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... + // uh, WTF, we're not on our combat point? + // er, try again, I guess? cp = NPCInfo->combatPoint; cpFlags |= ST_GetCPFlags(); + } else { // cover them + // stop ducking + TIMER_Set(NPC, "duck", -1); + // start shooting + TIMER_Set(NPC, "attackDelay", -1); + // AI should take care of the rest - fire at enemy } - else - {//cover them - //stop ducking - TIMER_Set( NPC, "duck", -1 ); - //start shooting - TIMER_Set( NPC, "attackDelay", -1 ); - //AI should take care of the rest - fire at enemy - } - } - else - {//we're running - //see if we're blocked - if ( NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//dammit, something is in our way - //see if it's one of ours - for ( j = 0; j < group->numGroup; j++ ) - { - if ( group->member[j].number == NPCInfo->blockingEntNum ) - {//we're being blocked by one of our own, pass our goal onto them and I'll stand still - ST_TransferMoveGoal( NPC, &g_entities[group->member[j].number] ); + } else { // we're running + // see if we're blocked + if (NPCInfo->aiFlags & NPCAI_BLOCKED) { // dammit, something is in our way + // see if it's one of ours + for (j = 0; j < group->numGroup; j++) { + if (group->member[j].number == + NPCInfo->blockingEntNum) { // we're being blocked by one of our own, pass our goal onto them and I'll stand still + ST_TransferMoveGoal(NPC, &g_entities[group->member[j].number]); break; } } } - //we don't need to do anything else + // we don't need to do anything else continue; } - } - else - {//okay no-one is running, use some tactics - if ( NPCInfo->combatPoint != -1 ) - {//we have a combat point we're supposed to be running to - if ( NPCInfo->squadState != SQUAD_SCOUT && - NPCInfo->squadState != SQUAD_TRANSITION && - NPCInfo->squadState != SQUAD_RETREAT ) - {//but we're not running - if ( TIMER_Done( NPC, "verifyCP" ) ) - {//1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... - if ( DistanceSquared( NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin ) > 64*64 ) - {//uh, WTF, we're not on our combat point? - //er, try again, I guess? + } else { // okay no-one is running, use some tactics + if (NPCInfo->combatPoint != -1) { // we have a combat point we're supposed to be running to + if (NPCInfo->squadState != SQUAD_SCOUT && NPCInfo->squadState != SQUAD_TRANSITION && + NPCInfo->squadState != SQUAD_RETREAT) { // but we're not running + if (TIMER_Done(NPC, "verifyCP")) { // 1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've + // stopped running... + if (DistanceSquared(NPC->currentOrigin, level.combatPoints[NPCInfo->combatPoint].origin) > + 64 * 64) { // uh, WTF, we're not on our combat point? + // er, try again, I guess? cp = NPCInfo->combatPoint; cpFlags |= ST_GetCPFlags(); } } } } - if ( enemyLost ) - {//if no-one has seen the enemy for a while, send a scout - //ask where he went - if ( group->numState[SQUAD_SCOUT] <= 0 ) - { - //scouting = qtrue; - NPC_ST_StoreMovementSpeech( SPEECH_CHASE, 0.0f ); + if (enemyLost) { // if no-one has seen the enemy for a while, send a scout + // ask where he went + if (group->numState[SQUAD_SCOUT] <= 0) { + // scouting = qtrue; + NPC_ST_StoreMovementSpeech(SPEECH_CHASE, 0.0f); } - //Since no-one else has done this, I should be the closest one, so go after him... - ST_TrackEnemy( NPC, group->enemyLastSeenPos ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPC, SQUAD_SCOUT ); - //we're not using a cp, so we need to set runner to true right here + // Since no-one else has done this, I should be the closest one, so go after him... + ST_TrackEnemy(NPC, group->enemyLastSeenPos); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPC, SQUAD_SCOUT); + // we're not using a cp, so we need to set runner to true right here runner = qtrue; - } - else if ( enemyProtected ) - {//if no-one has a clear shot at the enemy, someone should go after him - //FIXME: if I'm in an area where no safe combat points have a clear shot at me, they don't come after me... they should anyway, though after some extra hesitation. - //ALSO: seem to give up when behind an area portal? - //since no-one else here has done this, I should be the closest one - if ( TIMER_Done( NPC, "roamTime" ) && !Q_irand( 0, group->numGroup) ) - {//only do this if we're ready to move again and we feel like it - cpFlags |= ST_ApproachEnemy( NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPC, SQUAD_SCOUT ); + } else if (enemyProtected) { // if no-one has a clear shot at the enemy, someone should go after him + // FIXME: if I'm in an area where no safe combat points have a clear shot at me, they don't come after me... they should anyway, though + // after some extra hesitation. ALSO: seem to give up when behind an area portal? since no-one else here has done this, I should be the + // closest one + if (TIMER_Done(NPC, "roamTime") && !Q_irand(0, group->numGroup)) { // only do this if we're ready to move again and we feel like it + cpFlags |= ST_ApproachEnemy(NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPC, SQUAD_SCOUT); } - } - else - {//group can see and has been shooting at the enemy - //see if we should do something fancy? - - {//we're ready to move - if ( NPCInfo->combatPoint == -1 ) - {//we're not on a combat point - if ( 1 )//!Q_irand( 0, 2 ) ) - {//we should go for a combat point + } else { // group can see and has been shooting at the enemy + // see if we should do something fancy? + + { // we're ready to move + if (NPCInfo->combatPoint == -1) { // we're not on a combat point + if (1) //! Q_irand( 0, 2 ) ) + { // we should go for a combat point cpFlags |= ST_GetCPFlags(); + } else { + TIMER_Set(NPC, "stick", Q_irand(2000, 4000)); + TIMER_Set(NPC, "roamTime", Q_irand(1000, 3000)); } - else - { - TIMER_Set( NPC, "stick", Q_irand( 2000, 4000 ) ); - TIMER_Set( NPC, "roamTime", Q_irand( 1000, 3000 ) ); - } - } - else if ( TIMER_Done( NPC, "roamTime" ) ) - {//we are already on a combat point - if ( i == 0 ) - {//we're the closest - if ( (group->morale-group->numGroup>0) && !Q_irand( 0, 4 ) ) - {//try to outflank him - cpFlags |= (CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); - } - else if ( (group->morale-group->numGroup<0) ) - {//better move! + } else if (TIMER_Done(NPC, "roamTime")) { // we are already on a combat point + if (i == 0) { // we're the closest + if ((group->morale - group->numGroup > 0) && !Q_irand(0, 4)) { // try to outflank him + cpFlags |= (CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); + } else if ((group->morale - group->numGroup < 0)) { // better move! cpFlags |= ST_GetCPFlags(); + } else { // If we're point, then get down + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + TIMER_Set(NPC, "stick", Q_irand(2000, 5000)); + // FIXME: what if we can't shoot from a ducked pos? + TIMER_Set(NPC, "duck", Q_irand(3000, 4000)); + AI_GroupUpdateSquadstates(group, NPC, SQUAD_POINT); } - else - {//If we're point, then get down - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - TIMER_Set( NPC, "stick", Q_irand( 2000, 5000 ) ); - //FIXME: what if we can't shoot from a ducked pos? - TIMER_Set( NPC, "duck", Q_irand( 3000, 4000 ) ); - AI_GroupUpdateSquadstates( group, NPC, SQUAD_POINT ); - } - } - else if ( i == group->numGroup - 1 ) - {//farthest from the enemy - if ( (group->morale-group->numGroup<0) ) - {//low morale, just hang here - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 5000 ) ); - TIMER_Set( NPC, "stick", Q_irand( 2000, 5000 ) ); - } - else if ( (group->morale-group->numGroup>0) ) - {//try to move in on the enemy - cpFlags |= ST_ApproachEnemy( NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPC, SQUAD_SCOUT ); - } - else - {//use normal decision making process + } else if (i == group->numGroup - 1) { // farthest from the enemy + if ((group->morale - group->numGroup < 0)) { // low morale, just hang here + TIMER_Set(NPC, "roamTime", Q_irand(2000, 5000)); + TIMER_Set(NPC, "stick", Q_irand(2000, 5000)); + } else if ((group->morale - group->numGroup > 0)) { // try to move in on the enemy + cpFlags |= ST_ApproachEnemy(NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPC, SQUAD_SCOUT); + } else { // use normal decision making process cpFlags |= ST_GetCPFlags(); } - } - else - {//someone in-between - if ( (group->morale-group->numGroup<0) || !Q_irand( 0, 4 ) ) - {//do something + } else { // someone in-between + if ((group->morale - group->numGroup < 0) || !Q_irand(0, 4)) { // do something cpFlags |= ST_GetCPFlags(); - } - else - { - TIMER_Set( NPC, "stick", Q_irand( 2000, 4000 ) ); - TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); + } else { + TIMER_Set(NPC, "stick", Q_irand(2000, 4000)); + TIMER_Set(NPC, "roamTime", Q_irand(2000, 4000)); } } } } - if ( !cpFlags ) - {//still not moving - //see if we should say something? + if (!cpFlags) { // still not moving + // see if we should say something? /* if ( NPC->attackDebounceTime < level.time - 2000 ) {//we, personally, haven't shot for 2 seconds @@ -2161,38 +1805,32 @@ void ST_Commander( void ) } */ - //see if we should do other fun stuff - //toy with ducking - if ( TIMER_Done( NPC, "duck" ) ) - {//not ducking - if ( TIMER_Done( NPC, "stand" ) ) - {//don't have to keep standing - if ( NPCInfo->combatPoint == -1 || (level.combatPoints[NPCInfo->combatPoint].flags&CPF_DUCK) ) - {//okay to duck here - if ( !Q_irand( 0, 3 ) ) - { - TIMER_Set( NPC, "duck", Q_irand( 1000, 3000 ) ); + // see if we should do other fun stuff + // toy with ducking + if (TIMER_Done(NPC, "duck")) { // not ducking + if (TIMER_Done(NPC, "stand")) { // don't have to keep standing + if (NPCInfo->combatPoint == -1 || (level.combatPoints[NPCInfo->combatPoint].flags & CPF_DUCK)) { // okay to duck here + if (!Q_irand(0, 3)) { + TIMER_Set(NPC, "duck", Q_irand(1000, 3000)); } } } } - //FIXME: what about CPF_LEAN? + // FIXME: what about CPF_LEAN? } } } } - //clear the local state + // clear the local state NPCInfo->localState = LSTATE_NONE; - if ( NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - //Assign combat points - if ( cpFlags ) - {//we want to run to a combat point + // Assign combat points + if (cpFlags) { // we want to run to a combat point /* if ( NPCInfo->combatPoint != -1 ) {//if we're on a combat point, we obviously don't want the one we're closest to @@ -2200,126 +1838,89 @@ void ST_Commander( void ) } */ - if ( group->enemy->client->ps.weapon == WP_SABER && group->enemy->client->ps.saberLength > 0 ) - {//we obviously want to avoid the enemy if he has a saber + if (group->enemy->client->ps.weapon == WP_SABER && + group->enemy->client->ps.saberLength > 0) { // we obviously want to avoid the enemy if he has a saber cpFlags |= CP_AVOID_ENEMY; avoidDist = 256; } - //remember what we *wanted* to do... + // remember what we *wanted* to do... cpFlags_org = cpFlags; - //now get a combat point - if ( cp == -1 ) - {//may have had sone set above - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, group->enemy->currentOrigin, cpFlags|CP_HAS_ROUTE, avoidDist, NPCInfo->lastFailedCombatPoint ); + // now get a combat point + if (cp == -1) { // may have had sone set above + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, group->enemy->currentOrigin, cpFlags | CP_HAS_ROUTE, avoidDist, + NPCInfo->lastFailedCombatPoint); } - while ( cp == -1 && cpFlags != CP_ANY ) - {//start "OR"ing out certain flags to see if we can find *any* point - if ( cpFlags & CP_INVESTIGATE ) - {//don't need to investigate + while (cp == -1 && cpFlags != CP_ANY) { // start "OR"ing out certain flags to see if we can find *any* point + if (cpFlags & CP_INVESTIGATE) { // don't need to investigate cpFlags &= ~CP_INVESTIGATE; - } - else if ( cpFlags & CP_SQUAD ) - {//don't need to stick to squads + } else if (cpFlags & CP_SQUAD) { // don't need to stick to squads cpFlags &= ~CP_SQUAD; - } - else if ( cpFlags & CP_DUCK ) - {//don't need to duck + } else if (cpFlags & CP_DUCK) { // don't need to duck cpFlags &= ~CP_DUCK; - } - else if ( cpFlags & CP_NEAREST ) - {//don't need closest one to me + } else if (cpFlags & CP_NEAREST) { // don't need closest one to me cpFlags &= ~CP_NEAREST; - } - else if ( cpFlags & CP_FLANK ) - {//don't need to flank enemy + } else if (cpFlags & CP_FLANK) { // don't need to flank enemy cpFlags &= ~CP_FLANK; - } - else if ( cpFlags & CP_SAFE ) - {//don't need one that hasn't been shot at recently + } else if (cpFlags & CP_SAFE) { // don't need one that hasn't been shot at recently cpFlags &= ~CP_SAFE; - } - else if ( cpFlags & CP_CLOSEST ) - {//don't need to get closest to enemy + } else if (cpFlags & CP_CLOSEST) { // don't need to get closest to enemy cpFlags &= ~CP_CLOSEST; - //but let's try to approach at least + // but let's try to approach at least cpFlags |= CP_APPROACH_ENEMY; - } - else if ( cpFlags & CP_APPROACH_ENEMY ) - {//don't need to approach enemy + } else if (cpFlags & CP_APPROACH_ENEMY) { // don't need to approach enemy cpFlags &= ~CP_APPROACH_ENEMY; - } - else if ( cpFlags & CP_COVER ) - {//don't need cover + } else if (cpFlags & CP_COVER) { // don't need cover cpFlags &= ~CP_COVER; - //but let's pick one that makes us duck + // but let's pick one that makes us duck cpFlags |= CP_DUCK; - } - else if ( cpFlags & CP_CLEAR ) - {//don't need a clear shot to enemy + } else if (cpFlags & CP_CLEAR) { // don't need a clear shot to enemy cpFlags &= ~CP_CLEAR; - } - else if ( cpFlags & CP_AVOID_ENEMY ) - {//don't need to avoid enemy + } else if (cpFlags & CP_AVOID_ENEMY) { // don't need to avoid enemy cpFlags &= ~CP_AVOID_ENEMY; - } - else if ( cpFlags & CP_RETREAT ) - {//don't need to retreat + } else if (cpFlags & CP_RETREAT) { // don't need to retreat cpFlags &= ~CP_RETREAT; - } - else if ( cpFlags &CP_FLEE ) - {//don't need to flee + } else if (cpFlags & CP_FLEE) { // don't need to flee cpFlags &= ~CP_FLEE; - //but at least avoid enemy and pick one that gives cover - cpFlags |= (CP_COVER|CP_AVOID_ENEMY); - } - else if ( cpFlags & CP_AVOID ) - {//okay, even pick one right by me + // but at least avoid enemy and pick one that gives cover + cpFlags |= (CP_COVER | CP_AVOID_ENEMY); + } else if (cpFlags & CP_AVOID) { // okay, even pick one right by me cpFlags &= ~CP_AVOID; - } - else - { + } else { cpFlags = CP_ANY; } - //now try again - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, group->enemy->currentOrigin, cpFlags|CP_HAS_ROUTE, avoidDist ); + // now try again + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, group->enemy->currentOrigin, cpFlags | CP_HAS_ROUTE, avoidDist); } - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - //let others know that someone is now running + // see if we got a valid one + if (cp != -1) { // found a combat point + // let others know that someone is now running runner = qtrue; - //don't change course again until we get to where we're going - TIMER_Set( NPC, "roamTime", Q3_INFINITE ); - TIMER_Set( NPC, "verifyCP", Q_irand( 1000, 3000 ) );//don't make sure you're in your CP for 1 - 3 seconds - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); - //okay, try a move right now to see if we can even get there - - //if ( ST_Move() ) - {//we actually can get to it, so okay to say you're going there. - //FIXME: Hmm... any way we can store this move info so we don't have to do it again + // don't change course again until we get to where we're going + TIMER_Set(NPC, "roamTime", Q3_INFINITE); + TIMER_Set(NPC, "verifyCP", Q_irand(1000, 3000)); // don't make sure you're in your CP for 1 - 3 seconds + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); + // okay, try a move right now to see if we can even get there + + // if ( ST_Move() ) + { // we actually can get to it, so okay to say you're going there. + // FIXME: Hmm... any way we can store this move info so we don't have to do it again // when our turn to think comes up? - //set us up so others know we're on the move - if ( squadState != SQUAD_IDLE ) - { - AI_GroupUpdateSquadstates( group, NPC, squadState ); - } - else if ( cpFlags&CP_FLEE ) - {//outright running for your life - AI_GroupUpdateSquadstates( group, NPC, SQUAD_RETREAT ); - } - else - {//any other kind of transition between combat points - AI_GroupUpdateSquadstates( group, NPC, SQUAD_TRANSITION ); + // set us up so others know we're on the move + if (squadState != SQUAD_IDLE) { + AI_GroupUpdateSquadstates(group, NPC, squadState); + } else if (cpFlags & CP_FLEE) { // outright running for your life + AI_GroupUpdateSquadstates(group, NPC, SQUAD_RETREAT); + } else { // any other kind of transition between combat points + AI_GroupUpdateSquadstates(group, NPC, SQUAD_TRANSITION); } - //unless we're trying to flee, walk slowly - if ( !(cpFlags_org&CP_FLEE) ) - { - //ucmd.buttons |= BUTTON_CAREFUL; + // unless we're trying to flee, walk slowly + if (!(cpFlags_org & CP_FLEE)) { + // ucmd.buttons |= BUTTON_CAREFUL; } /* @@ -2330,38 +1931,30 @@ void ST_Commander( void ) //group->speechDebounceTime = level.time + 5000; } //flanking: - else */if ( cpFlags & CP_FLANK ) - { - if ( group->numGroup > 1 ) - { - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); + else */ + if (cpFlags & CP_FLANK) { + if (group->numGroup > 1) { + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); } - } - else - {//okay, let's cheat - if ( group->numGroup > 1 ) - { - float dot = 1.0f; - if ( !Q_irand( 0, 3 ) ) - {//25% of the time, see if we're flanking the enemy - vec3_t eDir2Me, eDir2CP; + } else { // okay, let's cheat + if (group->numGroup > 1) { + float dot = 1.0f; + if (!Q_irand(0, 3)) { // 25% of the time, see if we're flanking the enemy + vec3_t eDir2Me, eDir2CP; - VectorSubtract( NPC->currentOrigin, group->enemy->currentOrigin, eDir2Me ); - VectorNormalize( eDir2Me ); + VectorSubtract(NPC->currentOrigin, group->enemy->currentOrigin, eDir2Me); + VectorNormalize(eDir2Me); - VectorSubtract( level.combatPoints[NPCInfo->combatPoint].origin, group->enemy->currentOrigin, eDir2CP ); - VectorNormalize( eDir2CP ); + VectorSubtract(level.combatPoints[NPCInfo->combatPoint].origin, group->enemy->currentOrigin, eDir2CP); + VectorNormalize(eDir2CP); - dot = DotProduct( eDir2Me, eDir2CP ); + dot = DotProduct(eDir2Me, eDir2CP); } - if ( dot < 0.4 ) - {//flanking! - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); - } - else if ( !Q_irand( 0, 10 ) ) - {//regular movement - NPC_ST_StoreMovementSpeech( SPEECH_YELL, 0.2f );//was SPEECH_COVER + if (dot < 0.4) { // flanking! + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); + } else if (!Q_irand(0, 10)) { // regular movement + NPC_ST_StoreMovementSpeech(SPEECH_YELL, 0.2f); // was SPEECH_COVER } } } @@ -2374,14 +1967,12 @@ void ST_Commander( void ) } } */ - }//else: nothing, a failed move should clear the combatPoint and you can try again next frame - } - else if ( NPCInfo->squadState == SQUAD_SCOUT ) - {//we couldn't find a combatPoint by the player, so just go after him directly - ST_HuntEnemy( NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPC, SQUAD_SCOUT ); - //AI should take care of rest + } // else: nothing, a failed move should clear the combatPoint and you can try again next frame + } else if (NPCInfo->squadState == SQUAD_SCOUT) { // we couldn't find a combatPoint by the player, so just go after him directly + ST_HuntEnemy(NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPC, SQUAD_SCOUT); + // AI should take care of rest } } } @@ -2396,78 +1987,61 @@ NPC_BSST_Attack ------------------------- */ -void NPC_BSST_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSST_Attack(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) //! NPC->enemy )// { NPC->enemy = NULL; - if( NPC->client->playerTeam == TEAM_PLAYER ) - { + if (NPC->client->playerTeam == TEAM_PLAYER) { NPC_BSPatrol(); - } - else - { - NPC_BSST_Patrol();//FIXME: or patrol? + } else { + NPC_BSST_Patrol(); // FIXME: or patrol? } return; } - //FIXME: put some sort of delay into the guys depending on how they saw you...? + // FIXME: put some sort of delay into the guys depending on how they saw you...? - //Get our group info - if ( TIMER_Done( NPC, "interrogating" ) ) - { - AI_GetGroup( NPC );//, 45, 512, NPC->enemy ); - } - else - { - //FIXME: when done interrogating, I should send out a team alert! + // Get our group info + if (TIMER_Done(NPC, "interrogating")) { + AI_GetGroup(NPC); //, 45, 512, NPC->enemy ); + } else { + // FIXME: when done interrogating, I should send out a team alert! } - if ( NPCInfo->group ) - {//I belong to a squad of guys - we should *always* have a group - if ( !NPCInfo->group->processed ) - {//I'm the first ent in my group, I'll make the command decisions -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS + if (NPCInfo->group) { // I belong to a squad of guys - we should *always* have a group + if (!NPCInfo->group->processed) { // I'm the first ent in my group, I'll make the command decisions +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS ST_Commander(); -#if AI_TIMERS - int commTime = GetTime ( startTime ); - if ( commTime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: Commander time: %d\n", commTime ); - } - else if ( commTime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: Commander time: %d\n", commTime ); - } - else if ( commTime > 2 ) - { - gi.Printf( S_COLOR_GREEN"Commander time: %d\n", commTime ); - } -#endif// AI_TIMERS - } - } - else if ( TIMER_Done( NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//not already fleeing, and going to run - ST_Speech( NPC, SPEECH_COVER, 0 ); - NPC_UpdateAngles( qtrue, qtrue ); +#if AI_TIMERS + int commTime = GetTime(startTime); + if (commTime > 20) { + gi.Printf(S_COLOR_RED "ERROR: Commander time: %d\n", commTime); + } else if (commTime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: Commander time: %d\n", commTime); + } else if (commTime > 2) { + gi.Printf(S_COLOR_GREEN "Commander time: %d\n", commTime); + } +#endif // AI_TIMERS + } + } else if (TIMER_Done(NPC, "flee") && + NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // not already fleeing, and going to run + ST_Speech(NPC, SPEECH_COVER, 0); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSST_Patrol();//FIXME: or patrol? + if (!NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSST_Patrol(); // FIXME: or patrol? return; } @@ -2476,254 +2050,199 @@ void NPC_BSST_Attack( void ) faceEnemy = qfalse; shoot = qfalse; hitAlly = qfalse; - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); - - vec3_t enemyDir, shootDir; - VectorSubtract( NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir ); - VectorNormalize( enemyDir ); - AngleVectors( NPC->client->ps.viewangles, shootDir, NULL, NULL ); - float dot = DotProduct( enemyDir, shootDir ); - if ( dot > 0.5f ||( enemyDist * (1.0f-dot)) < 10000 ) - {//enemy is in front of me or they're very close and not behind me + VectorClear(impactPos); + enemyDist = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); + + vec3_t enemyDir, shootDir; + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, enemyDir); + VectorNormalize(enemyDir); + AngleVectors(NPC->client->ps.viewangles, shootDir, NULL, NULL); + float dot = DotProduct(enemyDir, shootDir); + if (dot > 0.5f || (enemyDist * (1.0f - dot)) < 10000) { // enemy is in front of me or they're very close and not behind me enemyInFOV = qtrue; } - if ( enemyDist < MIN_ROCKET_DIST_SQUARED )//128 - {//enemy within 128 - if ( (NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && - (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + if (enemyDist < MIN_ROCKET_DIST_SQUARED) // 128 + { // enemy within 128 + if ((NPC->client->ps.weapon == WP_FLECHETTE || NPC->client->ps.weapon == WP_REPEATER) && + (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... + // FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( !(NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (!(NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //can we see our target? - if ( NPC_ClearLOS( NPC->enemy ) ) - { - AI_GroupUpdateEnemyLastSeen( NPCInfo->group, NPC->enemy->currentOrigin ); + // can we see our target? + if (NPC_ClearLOS(NPC->enemy)) { + AI_GroupUpdateEnemyLastSeen(NPCInfo->group, NPC->enemy->currentOrigin); NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - NPC_AimAdjust( -1 );//adjust aim worse longer we have no weapon - } - else - {//can we shoot our target? - if ( (NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist < MIN_ROCKET_DIST_SQUARED )//128*128 + if (NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + NPC_AimAdjust(-1); // adjust aim worse longer we have no weapon + } else { // can we shoot our target? + if ((NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPC->client->ps.weapon == WP_FLECHETTE && (NPCInfo->scriptFlags & SCF_ALT_FIRE))) && + enemyDist < MIN_ROCKET_DIST_SQUARED) // 128*128 { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else if ( enemyInFOV ) - {//if enemy is FOV, go ahead and check for shooting - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else if (enemyInFOV) { // if enemy is FOV, go ahead and check for shooting + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPC->s.weapon == WP_EMPLACED_GUN) ) ) - {//can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway - AI_GroupUpdateClearShotTime( NPCInfo->group ); + if (hit == NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && + ((hitEnt->svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || + NPC->s.weapon == + WP_EMPLACED_GUN))) { // can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + AI_GroupUpdateClearShotTime(NPCInfo->group); enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - ST_ResolveBlockedShot( hit ); - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + NPC_AimAdjust(1); // adjust aim better longer we can see enemy + ST_ResolveBlockedShot(hit); + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } - } - else - { - enemyCS = qfalse;//not true, but should stop us from firing + } else { + enemyCS = qfalse; // not true, but should stop us from firing } } - } - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { + } else if (gi.inPVS(NPC->enemy->currentOrigin, NPC->currentOrigin)) { NPCInfo->enemyLastSeenTime = level.time; faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } - if ( NPC->client->ps.weapon == WP_NONE ) - { + if (NPC->client->ps.weapon == WP_NONE) { faceEnemy = qfalse; shoot = qfalse; - } - else - { - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + } else { + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } } - //Check for movement to take care of + // Check for movement to take care of ST_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations ST_CheckFireState(); - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); } - if ( !(NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not supposed to chase my enemies - if ( NPCInfo->goalEntity == NPC->enemy ) - {//goal is my entity, so don't move + if (!(NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not supposed to chase my enemies + if (NPCInfo->goalEntity == NPC->enemy) { // goal is my entity, so don't move AImove = qfalse; } } - if ( NPC->client->fireDelay && NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { + if (NPC->client->fireDelay && NPC->s.weapon == WP_ROCKET_LAUNCHER) { AImove = qfalse; } - if ( AImove ) - {//move toward goal - if ( NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (AImove) { // move toward goal + if (NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { AImove = ST_Move(); - } - else - { + } else { AImove = qfalse; } } - if ( !AImove ) - { - if ( !TIMER_Done( NPC, "duck" ) ) - { + if (!AImove) { + if (!TIMER_Done(NPC, "duck")) { ucmd.upmove = -127; } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPC, "duck", -1); } - if ( !TIMER_Done( NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPC, "flee")) { // running away faceEnemy = qfalse; } - //FIXME: check scf_face_move_dir here? + // FIXME: check scf_face_move_dir here? - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( !AImove ) - {//if we haven't moved, we should look in the direction we last looked? - VectorCopy( NPC->client->ps.viewangles, NPCInfo->lastPathAngles ); + if (!faceEnemy) { // we want to face in the dir we're running + if (!AImove) { // if we haven't moved, we should look in the direction we last looked? + VectorCopy(NPC->client->ps.viewangles, NPCInfo->lastPathAngles); } NPCInfo->desiredYaw = NPCInfo->lastPathAngles[YAW]; NPCInfo->desiredPitch = 0; - NPC_UpdateAngles( qtrue, qtrue ); - if ( AImove ) - {//don't run away and shoot + NPC_UpdateAngles(qtrue, qtrue); + if (AImove) { // don't run away and shoot shoot = qfalse; } } - if ( NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPC->enemy && NPC->enemy->enemy ) - { - if ( NPC->enemy->s.weapon == WP_SABER && NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPC->enemy && NPC->enemy->enemy) { + if (NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue + // blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - //FIXME: don't shoot right away! - if ( NPC->client->fireDelay ) - { - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { - if ( !enemyLOS || !enemyCS ) - {//cancel it + // FIXME: don't shoot right away! + if (NPC->client->fireDelay) { + if (NPC->s.weapon == WP_ROCKET_LAUNCHER) { + if (!enemyLOS || !enemyCS) { // cancel it NPC->client->fireDelay = 0; - } - else - {//delay our next attempt - TIMER_Set( NPC, "attackDelay", Q_irand( 3000, 5000 ) ); + } else { // delay our next attempt + TIMER_Set(NPC, "attackDelay", Q_irand(3000, 5000)); } } - } - else if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPC, "attackDelay" ) ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + } else if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPC, "attackDelay")) { + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } - //NASTY - if ( NPC->s.weapon == WP_ROCKET_LAUNCHER - && (ucmd.buttons&BUTTON_ATTACK) - && !AImove - && g_spskill->integer > 1 - && !Q_irand( 0, 3 ) ) - {//every now and then, shoot a homing rocket + // NASTY + if (NPC->s.weapon == WP_ROCKET_LAUNCHER && (ucmd.buttons & BUTTON_ATTACK) && !AImove && g_spskill->integer > 1 && + !Q_irand(0, 3)) { // every now and then, shoot a homing rocket ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons |= BUTTON_ALT_ATTACK; - NPC->client->fireDelay = Q_irand( 1000, 2500 ); + NPC->client->fireDelay = Q_irand(1000, 2500); } } } } -void NPC_BSST_Default( void ) -{ - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSST_Default(void) { + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if( !NPC->enemy ) - {//don't have an enemy, look for one + if (!NPC->enemy) { // don't have an enemy, look for one NPC_BSST_Patrol(); - } - else //if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_CheckGetNewWeapon(); NPC_BSST_Attack(); } diff --git a/codeJK2/game/AI_Utils.cpp b/codeJK2/game/AI_Utils.cpp index 0ff327ad92..945893ec89 100644 --- a/codeJK2/game/AI_Utils.cpp +++ b/codeJK2/game/AI_Utils.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -// These utilities are meant for strictly non-player, non-team NPCs. +// These utilities are meant for strictly non-player, non-team NPCs. // These functions are in their own file because they are only intended // for use with NPCs who's logic has been overriden from the original // AI code, and who's code resides in files with the AI_ prefix. @@ -31,12 +31,12 @@ along with this program; if not, see . #include "g_nav.h" #include "g_navigator.h" -#define MAX_RADIUS_ENTS 128 -#define DEFAULT_RADIUS 45 +#define MAX_RADIUS_ENTS 128 +#define DEFAULT_RADIUS 45 -extern CNavigator navigator; -extern cvar_t *d_noGroupAI; -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ); +extern CNavigator navigator; +extern cvar_t *d_noGroupAI; +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member); /* ------------------------- @@ -44,39 +44,36 @@ AI_GetGroupSize ------------------------- */ -int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid ) -{ - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; - vec3_t mins, maxs; - int numEnts, realCount = 0; +int AI_GetGroupSize(vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid) { + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; + vec3_t mins, maxs; + int numEnts, realCount = 0; - //Setup the bbox to search in - for ( int i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (int i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( int j = 0; j < numEnts; j++ ) - { - //Validate clients - if ( radiusEnts[ j ]->client == NULL ) + // Cull this list + for (int j = 0; j < numEnts; j++) { + // Validate clients + if (radiusEnts[j]->client == NULL) continue; - //Skip the requested avoid ent if present - if ( ( avoid != NULL ) && ( radiusEnts[ j ] == avoid ) ) + // Skip the requested avoid ent if present + if ((avoid != NULL) && (radiusEnts[j] == avoid)) continue; - //Must be on the same team - if ( radiusEnts[ j ]->client->playerTeam != playerTeam ) + // Must be on the same team + if (radiusEnts[j]->client->playerTeam != playerTeam) continue; - //Must be alive - if ( radiusEnts[ j ]->health <= 0 ) + // Must be alive + if (radiusEnts[j]->health <= 0) continue; realCount++; @@ -85,31 +82,26 @@ int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *av return realCount; } -//Overload +// Overload -int AI_GetGroupSize( gentity_t *ent, int radius ) -{ - if ( ( ent == NULL ) || ( ent->client == NULL ) ) +int AI_GetGroupSize(gentity_t *ent, int radius) { + if ((ent == NULL) || (ent->client == NULL)) return -1; - return AI_GetGroupSize( ent->currentOrigin, radius, ent->client->playerTeam, ent ); + return AI_GetGroupSize(ent->currentOrigin, radius, ent->client->playerTeam, ent); } -void AI_SetClosestBuddy( AIGroupInfo_t *group ) -{ - int i, j; - int dist, bestDist; +void AI_SetClosestBuddy(AIGroupInfo_t *group) { + int i, j; + int dist, bestDist; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { group->member[i].closestBuddy = ENTITYNUM_NONE; bestDist = Q3_INFINITE; - for ( j = 0; j < group->numGroup; j++ ) - { - dist = DistanceSquared( g_entities[group->member[i].number].currentOrigin, g_entities[group->member[j].number].currentOrigin ); - if ( dist < bestDist ) - { + for (j = 0; j < group->numGroup; j++) { + dist = DistanceSquared(g_entities[group->member[i].number].currentOrigin, g_entities[group->member[j].number].currentOrigin); + if (dist < bestDist) { bestDist = dist; group->member[i].closestBuddy = group->member[j].number; } @@ -117,95 +109,71 @@ void AI_SetClosestBuddy( AIGroupInfo_t *group ) } } -void AI_SortGroupByPathCostToEnemy( AIGroupInfo_t *group ) -{ +void AI_SortGroupByPathCostToEnemy(AIGroupInfo_t *group) { AIGroupMember_t bestMembers[MAX_GROUP_MEMBERS]; - int i, j, k; - qboolean sort = qfalse; + int i, j, k; + qboolean sort = qfalse; - if ( group->enemy != NULL ) - {//FIXME: just use enemy->waypoint? - group->enemyWP = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - } - else - { + if (group->enemy != NULL) { // FIXME: just use enemy->waypoint? + group->enemyWP = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + } else { group->enemyWP = WAYPOINT_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->enemyWP == WAYPOINT_NONE ) - {//FIXME: just use member->waypoint? + for (i = 0; i < group->numGroup; i++) { + if (group->enemyWP == WAYPOINT_NONE) { // FIXME: just use member->waypoint? group->member[i].waypoint = WAYPOINT_NONE; group->member[i].pathCostToEnemy = Q3_INFINITE; - } - else - {//FIXME: just use member->waypoint? - group->member[i].waypoint = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - if ( group->member[i].waypoint != WAYPOINT_NONE ) - { - group->member[i].pathCostToEnemy = navigator.GetPathCost( group->member[i].waypoint, group->enemyWP ); - //at least one of us has a path, so do sorting + } else { // FIXME: just use member->waypoint? + group->member[i].waypoint = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + if (group->member[i].waypoint != WAYPOINT_NONE) { + group->member[i].pathCostToEnemy = navigator.GetPathCost(group->member[i].waypoint, group->enemyWP); + // at least one of us has a path, so do sorting sort = qtrue; - } - else - { + } else { group->member[i].pathCostToEnemy = Q3_INFINITE; } } } - //Now sort - if ( sort ) - { - //initialize bestMembers data - for ( j = 0; j < group->numGroup; j++ ) - { + // Now sort + if (sort) { + // initialize bestMembers data + for (j = 0; j < group->numGroup; j++) { bestMembers[j].number = ENTITYNUM_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - for ( j = 0; j < group->numGroup; j++ ) - { - if ( bestMembers[j].number != ENTITYNUM_NONE ) - {//slot occupied - if ( group->member[i].pathCostToEnemy < bestMembers[j].pathCostToEnemy ) - {//this guy has a shorter path than the one currenly in this spot, bump him and put myself in here - for ( k = group->numGroup; k > j; k++ ) - { - memcpy( &bestMembers[k], &bestMembers[k-1], sizeof( bestMembers[k] ) ); + for (i = 0; i < group->numGroup; i++) { + for (j = 0; j < group->numGroup; j++) { + if (bestMembers[j].number != ENTITYNUM_NONE) { // slot occupied + if (group->member[i].pathCostToEnemy < + bestMembers[j].pathCostToEnemy) { // this guy has a shorter path than the one currenly in this spot, bump him and put myself in here + for (k = group->numGroup; k > j; k++) { + memcpy(&bestMembers[k], &bestMembers[k - 1], sizeof(bestMembers[k])); } - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } - } - else - {//slot unoccupied, reached end of list, throw self in here - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + } else { // slot unoccupied, reached end of list, throw self in here + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } } } - //Okay, now bestMembers is a sorted list, just copy it into group->members - for ( i = 0; i < group->numGroup; i++ ) - { - memcpy( &group->member[i], &bestMembers[i], sizeof( group->member[i] ) ); + // Okay, now bestMembers is a sorted list, just copy it into group->members + for (i = 0; i < group->numGroup; i++) { + memcpy(&group->member[i], &bestMembers[i], sizeof(group->member[i])); } } } -qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those contain me already - int i, j; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup )//&& level.groups[i].enemy != NULL ) - {//check this one - for ( j = 0; j < level.groups[i].numGroup; j++ ) - { - if ( level.groups[i].member[j].number == self->s.number ) - { +qboolean AI_FindSelfInPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those contain me already + int i, j; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup) //&& level.groups[i].enemy != NULL ) + { // check this one + for (j = 0; j < level.groups[i].numGroup; j++) { + if (level.groups[i].member[j].number == self->s.number) { self->NPC->group = &level.groups[i]; return qtrue; } @@ -215,45 +183,35 @@ qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) return qfalse; } -void AI_InsertGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - //okay, you know what? Check this damn group and make sure we're not already in here! +void AI_InsertGroupMember(AIGroupInfo_t *group, gentity_t *member) { + // okay, you know what? Check this damn group and make sure we're not already in here! int i; - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - {//already in here + for (i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { // already in here break; } } - if ( i < group->numGroup ) - {//found him in group already - } - else - {//add him in + if (i < group->numGroup) { // found him in group already + } else { // add him in group->member[group->numGroup++].number = member->s.number; group->numState[member->NPC->squadState]++; } - if ( !group->commander || (member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || (member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } member->NPC->group = group; } -qboolean AI_TryJoinPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! - int i; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup - && level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) - //&& level.groups[i].enemy != NULL - && level.groups[i].enemy == self->enemy ) - {//has members, not full and has my enemy - if ( AI_ValidateGroupMember( &level.groups[i], self ) ) - {//I am a valid member for this group - AI_InsertGroupMember( &level.groups[i], self ); +qboolean +AI_TryJoinPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! + int i; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup && + level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) + //&& level.groups[i].enemy != NULL + && level.groups[i].enemy == self->enemy) { // has members, not full and has my enemy + if (AI_ValidateGroupMember(&level.groups[i], self)) { // I am a valid member for this group + AI_InsertGroupMember(&level.groups[i], self); return qtrue; } } @@ -261,157 +219,124 @@ qboolean AI_TryJoinPreviousGroup( gentity_t *self ) return qfalse; } -qboolean AI_GetNextEmptyGroup( gentity_t *self ) -{ - if ( AI_FindSelfInPreviousGroup( self ) ) - {//already in one, no need to make a new one +qboolean AI_GetNextEmptyGroup(gentity_t *self) { + if (AI_FindSelfInPreviousGroup(self)) { // already in one, no need to make a new one return qfalse; } - if ( AI_TryJoinPreviousGroup( self ) ) - {//try to just put us in one that already exists + if (AI_TryJoinPreviousGroup(self)) { // try to just put us in one that already exists return qfalse; } - - //okay, make a whole new one, then - for ( int i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup ) - {//make a new one + + // okay, make a whole new one, then + for (int i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup) { // make a new one self->NPC->group = &level.groups[i]; return qtrue; } } - //if ( i >= MAX_FRAME_GROUPS ) - {//WTF? Out of groups! + // if ( i >= MAX_FRAME_GROUPS ) + { // WTF? Out of groups! self->NPC->group = NULL; return qfalse; } } -qboolean AI_ValidateNoEnemyGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - if ( !group ) - { +qboolean AI_ValidateNoEnemyGroupMember(AIGroupInfo_t *group, gentity_t *member) { + if (!group) { return qfalse; } vec3_t center; - if ( group->commander ) - { - VectorCopy( group->commander->currentOrigin, center ); - } - else - {//hmm, just pick the first member - if ( group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD ) - { + if (group->commander) { + VectorCopy(group->commander->currentOrigin, center); + } else { // hmm, just pick the first member + if (group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD) { return qfalse; } - VectorCopy( g_entities[group->member[0].number].currentOrigin, center ); + VectorCopy(g_entities[group->member[0].number].currentOrigin, center); } - //FIXME: maybe it should be based on the center of the mass of the group, not the commander? - if ( DistanceSquared( center, member->currentOrigin ) > 147456/*384*384*/ ) - { + // FIXME: maybe it should be based on the center of the mass of the group, not the commander? + if (DistanceSquared(center, member->currentOrigin) > 147456 /*384*384*/) { return qfalse; } - if ( !gi.inPVS( member->currentOrigin, center ) ) - {//not within PVS of the group enemy + if (!gi.inPVS(member->currentOrigin, center)) { // not within PVS of the group enemy return qfalse; } return qtrue; } -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - //Validate ents - if ( member == NULL ) +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member) { + // Validate ents + if (member == NULL) return qfalse; - //Validate clients - if ( member->client == NULL ) + // Validate clients + if (member->client == NULL) return qfalse; - //Validate NPCs - if ( member->NPC == NULL ) + // Validate NPCs + if (member->NPC == NULL) return qfalse; - //must be aware - if ( member->NPC->confusionTime > level.time ) + // must be aware + if (member->NPC->confusionTime > level.time) return qfalse; - //must be allowed to join groups - if ( member->NPC->scriptFlags&SCF_NO_GROUPS ) + // must be allowed to join groups + if (member->NPC->scriptFlags & SCF_NO_GROUPS) return qfalse; - //Must not be in another group - if ( member->NPC->group != NULL && member->NPC->group != group ) - {//FIXME: if that group's enemy is mine, why not absorb that group into mine? + // Must not be in another group + if (member->NPC->group != NULL && member->NPC->group != group) { // FIXME: if that group's enemy is mine, why not absorb that group into mine? return qfalse; } - //Must be alive - if ( member->health <= 0 ) + // Must be alive + if (member->health <= 0) return qfalse; - //can't be in an emplaced gun - if( member->s.eFlags & EF_LOCKED_TO_WEAPON ) + // can't be in an emplaced gun + if (member->s.eFlags & EF_LOCKED_TO_WEAPON) return qfalse; - //Must be on the same team - if ( member->client->playerTeam != group->team ) + // Must be on the same team + if (member->client->playerTeam != group->team) return qfalse; - if ( member->client->ps.weapon == WP_SABER ||//!= self->s.weapon ) - member->client->ps.weapon == WP_THERMAL || - member->client->ps.weapon == WP_DISRUPTOR || - member->client->ps.weapon == WP_EMPLACED_GUN || - member->client->ps.weapon == WP_BOT_LASER || // Probe droid - Laser blast - member->client->ps.weapon == WP_MELEE || - member->client->ps.weapon == WP_TURRET || // turret guns - member->client->ps.weapon == WP_ATST_MAIN || - member->client->ps.weapon == WP_ATST_SIDE || - member->client->ps.weapon == WP_TIE_FIGHTER ) - {//not really a squad-type guy + if (member->client->ps.weapon == WP_SABER || //!= self->s.weapon ) + member->client->ps.weapon == WP_THERMAL || member->client->ps.weapon == WP_DISRUPTOR || member->client->ps.weapon == WP_EMPLACED_GUN || + member->client->ps.weapon == WP_BOT_LASER || // Probe droid - Laser blast + member->client->ps.weapon == WP_MELEE || member->client->ps.weapon == WP_TURRET || // turret guns + member->client->ps.weapon == WP_ATST_MAIN || member->client->ps.weapon == WP_ATST_SIDE || + member->client->ps.weapon == WP_TIE_FIGHTER) { // not really a squad-type guy return qfalse; } - if ( member->client->NPC_class == CLASS_ATST || - member->client->NPC_class == CLASS_PROBE || - member->client->NPC_class == CLASS_SEEKER || - member->client->NPC_class == CLASS_REMOTE || - member->client->NPC_class == CLASS_SENTRY || - member->client->NPC_class == CLASS_INTERROGATOR || - member->client->NPC_class == CLASS_MINEMONSTER || - member->client->NPC_class == CLASS_HOWLER || - member->client->NPC_class == CLASS_MARK1 || - member->client->NPC_class == CLASS_MARK2 ) - {//these kinds of enemies don't actually use this group AI + if (member->client->NPC_class == CLASS_ATST || member->client->NPC_class == CLASS_PROBE || member->client->NPC_class == CLASS_SEEKER || + member->client->NPC_class == CLASS_REMOTE || member->client->NPC_class == CLASS_SENTRY || member->client->NPC_class == CLASS_INTERROGATOR || + member->client->NPC_class == CLASS_MINEMONSTER || member->client->NPC_class == CLASS_HOWLER || member->client->NPC_class == CLASS_MARK1 || + member->client->NPC_class == CLASS_MARK2) { // these kinds of enemies don't actually use this group AI return qfalse; } - //should have same enemy - if ( member->enemy != group->enemy ) - { - if ( member->enemy != NULL ) - {//he's fighting someone else, leave him out + // should have same enemy + if (member->enemy != group->enemy) { + if (member->enemy != NULL) { // he's fighting someone else, leave him out return qfalse; } - if ( !gi.inPVS( member->currentOrigin, group->enemy->currentOrigin ) ) - {//not within PVS of the group enemy + if (!gi.inPVS(member->currentOrigin, group->enemy->currentOrigin)) { // not within PVS of the group enemy return qfalse; } - } - else if ( group->enemy == NULL ) - {//if the group is a patrol group, only take those within the room and radius - if ( !AI_ValidateNoEnemyGroupMember( group, member ) ) - { + } else if (group->enemy == NULL) { // if the group is a patrol group, only take those within the room and radius + if (!AI_ValidateNoEnemyGroupMember(group, member)) { return qfalse; } } - //must be actually in combat mode - if ( !TIMER_Done( member, "interrogating" ) ) + // must be actually in combat mode + if (!TIMER_Done(member, "interrogating")) return qfalse; - //FIXME: need to have a route to enemy and/or clear shot? + // FIXME: need to have a route to enemy and/or clear shot? return qtrue; } @@ -421,48 +346,41 @@ AI_GetGroup ------------------------- */ //#define MAX_WAITERS 128 -void AI_GetGroup( gentity_t *self ) -{ - int i; - gentity_t *member;//, *waiter; - //int waiters[MAX_WAITERS]; +void AI_GetGroup(gentity_t *self) { + int i; + gentity_t *member; //, *waiter; + // int waiters[MAX_WAITERS]; - if ( !self || !self->NPC ) - { + if (!self || !self->NPC) { return; } - if ( d_noGroupAI->integer ) - { + if (d_noGroupAI->integer) { self->NPC->group = NULL; return; } - if ( !self->client ) - { + if (!self->client) { self->NPC->group = NULL; return; } - if ( self->NPC->scriptFlags&SCF_NO_GROUPS ) - { + if (self->NPC->scriptFlags & SCF_NO_GROUPS) { self->NPC->group = NULL; return; } - if ( self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000 ))) - { + if (self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000))) { self->NPC->group = NULL; return; } - if ( !AI_GetNextEmptyGroup( self ) ) - {//either no more groups left or we're already in a group built earlier + if (!AI_GetNextEmptyGroup(self)) { // either no more groups left or we're already in a group built earlier return; } - //create a new one - memset( self->NPC->group, 0, sizeof( AIGroupInfo_t ) ); + // create a new one + memset(self->NPC->group, 0, sizeof(AIGroupInfo_t)); self->NPC->group->enemy = self->enemy; self->NPC->group->team = self->client->playerTeam; @@ -471,30 +389,27 @@ void AI_GetGroup( gentity_t *self ) self->NPC->group->memberValidateTime = level.time + 2000; self->NPC->group->activeMemberNum = 0; - if ( self->NPC->group->enemy ) - { + if (self->NPC->group->enemy) { self->NPC->group->lastSeenEnemyTime = level.time; self->NPC->group->lastClearShotTime = level.time; - VectorCopy( self->NPC->group->enemy->currentOrigin, self->NPC->group->enemyLastSeenPos ); + VectorCopy(self->NPC->group->enemy->currentOrigin, self->NPC->group->enemyLastSeenPos); } -// for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) - for ( i = 0; i < globals.num_entities ; i++) - { - if(!PInUse(i)) + // for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) + for (i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; member = &g_entities[i]; - if ( !AI_ValidateGroupMember( self->NPC->group, member ) ) - {//FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group + if (!AI_ValidateGroupMember( + self->NPC->group, member)) { // FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group continue; } - - //store it - AI_InsertGroupMember( self->NPC->group, member ); - if ( self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1) ) - {//full + // store it + AI_InsertGroupMember(self->NPC->group, member); + + if (self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1)) { // full break; } } @@ -506,7 +421,7 @@ void AI_GetGroup( gentity_t *self ) for ( i = 0; i < numWaiters; i++ ) { waiter = &g_entities[waiters[i]]; - + for ( j = 0; j < self->NPC->group->numGroup; j++ ) { member = &g_entities[self->NPC->group->member[j]; @@ -518,186 +433,144 @@ void AI_GetGroup( gentity_t *self ) } */ - if ( self->NPC->group->numGroup <= 0 ) - {//none in group + if (self->NPC->group->numGroup <= 0) { // none in group self->NPC->group = NULL; return; } - AI_SortGroupByPathCostToEnemy( self->NPC->group ); - AI_SetClosestBuddy( self->NPC->group ); + AI_SortGroupByPathCostToEnemy(self->NPC->group); + AI_SetClosestBuddy(self->NPC->group); } -void AI_SetNewGroupCommander( AIGroupInfo_t *group ) -{ +void AI_SetNewGroupCommander(AIGroupInfo_t *group) { gentity_t *member = NULL; group->commander = NULL; - for ( int i = 0; i < group->numGroup; i++ ) - { + for (int i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( !group->commander || (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || + (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } } } -void AI_DeleteGroupMember( AIGroupInfo_t *group, int memberNum ) -{ - if ( group->commander && group->commander->s.number == group->member[memberNum].number ) - { +void AI_DeleteGroupMember(AIGroupInfo_t *group, int memberNum) { + if (group->commander && group->commander->s.number == group->member[memberNum].number) { group->commander = NULL; } - if ( g_entities[group->member[memberNum].number].NPC ) - { + if (g_entities[group->member[memberNum].number].NPC) { g_entities[group->member[memberNum].number].NPC->group = NULL; } - for ( int i = memberNum; i < (group->numGroup-1); i++ ) - { - memcpy( &group->member[i], &group->member[i+1], sizeof( group->member[i] ) ); + for (int i = memberNum; i < (group->numGroup - 1); i++) { + memcpy(&group->member[i], &group->member[i + 1], sizeof(group->member[i])); } - if ( memberNum < group->activeMemberNum ) - { + if (memberNum < group->activeMemberNum) { group->activeMemberNum--; - if ( group->activeMemberNum < 0 ) - { + if (group->activeMemberNum < 0) { group->activeMemberNum = 0; } } group->numGroup--; - if ( group->numGroup < 0 ) - { + if (group->numGroup < 0) { group->numGroup = 0; } - AI_SetNewGroupCommander( group ); + AI_SetNewGroupCommander(group); } -void AI_DeleteSelfFromGroup( gentity_t *self ) -{ - //FIXME: if killed, keep track of how many in group killed? To affect morale? - for ( int i = 0; i < self->NPC->group->numGroup; i++ ) - { - if ( self->NPC->group->member[i].number == self->s.number ) - { - AI_DeleteGroupMember( self->NPC->group, i ); +void AI_DeleteSelfFromGroup(gentity_t *self) { + // FIXME: if killed, keep track of how many in group killed? To affect morale? + for (int i = 0; i < self->NPC->group->numGroup; i++) { + if (self->NPC->group->member[i].number == self->s.number) { + AI_DeleteGroupMember(self->NPC->group, i); return; } } } -extern void ST_AggressionAdjust( gentity_t *self, int change ); -extern void ST_MarkToCover( gentity_t *self ); -extern void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ); -void AI_GroupMemberKilled( gentity_t *self ) -{ +extern void ST_AggressionAdjust(gentity_t *self, int change); +extern void ST_MarkToCover(gentity_t *self); +extern void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime); +void AI_GroupMemberKilled(gentity_t *self) { AIGroupInfo_t *group = self->NPC->group; - gentity_t *member; - qboolean noflee = qfalse; + gentity_t *member; + qboolean noflee = qfalse; - if ( !group ) - {//what group? + if (!group) { // what group? return; } - if ( !self || !self->NPC || self->NPC->rank < RANK_ENSIGN ) - {//I'm not an officer, let's not really care for now + if (!self || !self->NPC || self->NPC->rank < RANK_ENSIGN) { // I'm not an officer, let's not really care for now return; } - //temporarily drop group morale for a few seconds + // temporarily drop group morale for a few seconds group->moraleAdjust -= self->NPC->rank; - //go through and drop aggression on my teammates (more cover, worse aim) - for ( int i = 0; i < group->numGroup; i++ ) - { + // go through and drop aggression on my teammates (more cover, worse aim) + for (int i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member == self ) - { + if (member == self) { continue; } - if ( member->NPC->rank > RANK_ENSIGN ) - {//officers do not panic + if (member->NPC->rank > RANK_ENSIGN) { // officers do not panic noflee = qtrue; - } - else - { - ST_AggressionAdjust( member, -1 ); - member->NPC->currentAim -= Q_irand( 0, 10 );//Q_irand( 0, 2);//drop their aim accuracy + } else { + ST_AggressionAdjust(member, -1); + member->NPC->currentAim -= Q_irand(0, 10); // Q_irand( 0, 2);//drop their aim accuracy } } - //okay, if I'm the group commander, make everyone else flee - if ( group->commander != self ) - {//I'm not the commander... hmm, should maybe a couple flee... maybe those near me? + // okay, if I'm the group commander, make everyone else flee + if (group->commander != self) { // I'm not the commander... hmm, should maybe a couple flee... maybe those near me? return; } - //now see if there is another of sufficient rank to keep them from fleeing - if ( !noflee ) - { + // now see if there is another of sufficient rank to keep them from fleeing + if (!noflee) { self->NPC->group->speechDebounceTime = 0; - for ( int i = 0; i < group->numGroup; i++ ) - { + for (int i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member == self ) - { + if (member == self) { continue; } - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunt - if ( group->enemy && DistanceSquared( member->currentOrigin, group->enemy->currentOrigin ) < 65536/*256*256*/ ) - {//those close to enemy run away! - ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else if ( DistanceSquared( member->currentOrigin, self->currentOrigin ) < 65536/*256*256*/ ) - {//those close to me run away! - ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else - {//else, maybe just a random chance - if ( Q_irand( 0, self->NPC->rank ) > member->NPC->rank ) - {//lower rank they are, higher rank I am, more likely they are to flee - ST_StartFlee( member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else - { - ST_MarkToCover( member ); + if (member->NPC->rank < RANK_ENSIGN) { // grunt + if (group->enemy && DistanceSquared(member->currentOrigin, group->enemy->currentOrigin) < 65536 /*256*256*/) { // those close to enemy run away! + ST_StartFlee(member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else if (DistanceSquared(member->currentOrigin, self->currentOrigin) < 65536 /*256*256*/) { // those close to me run away! + ST_StartFlee(member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else { // else, maybe just a random chance + if (Q_irand(0, self->NPC->rank) > member->NPC->rank) { // lower rank they are, higher rank I am, more likely they are to flee + ST_StartFlee(member, group->enemy, member->currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else { + ST_MarkToCover(member); } } - member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more + member->NPC->currentAim -= Q_irand(1, 15); // Q_irand( 1, 3 );//drop their aim accuracy even more } - member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more + member->NPC->currentAim -= Q_irand(1, 15); // Q_irand( 1, 3 );//drop their aim accuracy even more } } } -void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ) -{ - if ( !group ) - { +void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot) { + if (!group) { return; } group->lastSeenEnemyTime = level.time; - VectorCopy( spot, group->enemyLastSeenPos ); + VectorCopy(spot, group->enemyLastSeenPos); } -void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ) -{ - if ( !group ) - { +void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group) { + if (!group) { return; } group->lastClearShotTime = level.time; } -void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ) -{ - if ( !group ) - { +void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState) { + if (!group) { member->NPC->squadState = newSquadState; return; } - for ( int i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - { + for (int i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { group->numState[member->NPC->squadState]--; member->NPC->squadState = newSquadState; group->numState[member->NPC->squadState]++; @@ -706,63 +579,50 @@ void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int new } } -qboolean AI_RefreshGroup( AIGroupInfo_t *group ) -{ - gentity_t *member; - int i;//, j; +qboolean AI_RefreshGroup(AIGroupInfo_t *group) { + gentity_t *member; + int i; //, j; - //see if we should merge with another group - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( &level.groups[i] == group ) - { + // see if we should merge with another group + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (&level.groups[i] == group) { break; - } - else - { - if ( level.groups[i].enemy == group->enemy ) - {//2 groups with same enemy - if ( level.groups[i].numGroup+group->numGroup < (MAX_GROUP_MEMBERS - 1) ) - {//combining the members would fit in one group + } else { + if (level.groups[i].enemy == group->enemy) { // 2 groups with same enemy + if (level.groups[i].numGroup + group->numGroup < (MAX_GROUP_MEMBERS - 1)) { // combining the members would fit in one group qboolean deleteWhenDone = qtrue; - //combine the members of mine into theirs - for ( int j = 0; j < group->numGroup; j++ ) - { + // combine the members of mine into theirs + for (int j = 0; j < group->numGroup; j++) { member = &g_entities[group->member[j].number]; - if ( level.groups[i].enemy == NULL ) - {//special case for groups without enemies, must be in range - if ( !AI_ValidateNoEnemyGroupMember( &level.groups[i], member ) ) - { + if (level.groups[i].enemy == NULL) { // special case for groups without enemies, must be in range + if (!AI_ValidateNoEnemyGroupMember(&level.groups[i], member)) { deleteWhenDone = qfalse; continue; } } - //remove this member from this group - AI_DeleteGroupMember( group, j ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // remove this member from this group + AI_DeleteGroupMember(group, j); + // keep marker at same place since we deleted this guy and shifted everyone up one j--; - //add them to the earlier group - AI_InsertGroupMember( &level.groups[i], member ); + // add them to the earlier group + AI_InsertGroupMember(&level.groups[i], member); } - //return and delete this group - if ( deleteWhenDone ) - { + // return and delete this group + if (deleteWhenDone) { return qfalse; } } } } } - //clear numStates - for ( i = 0; i < NUM_SQUAD_STATES; i++ ) - { + // clear numStates + for (i = 0; i < NUM_SQUAD_STATES; i++) { group->numState[i] = 0; } - //go through group and validate each membership + // go through group and validate each membership group->commander = NULL; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { /* //this checks for duplicate copies of one member in a group for ( j = 0; j < group->numGroup; j++ ) @@ -777,43 +637,34 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } if ( j < group->numGroup ) {//found a dupe! - gi.Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, group->member[i].number ); - AI_DeleteGroupMember( group, i ); - i--; - continue; + gi.Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, group->member[i].number + ); AI_DeleteGroupMember( group, i ); i--; continue; } */ member = &g_entities[group->member[i].number]; - //Must be alive - if ( member->health <= 0 ) - { - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // Must be alive + if (member->health <= 0) { + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else if ( group->memberValidateTime < level.time && !AI_ValidateGroupMember( group, member ) ) - { - //remove this one from the group - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + } else if (group->memberValidateTime < level.time && !AI_ValidateGroupMember(group, member)) { + // remove this one from the group + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else - {//membership is valid - //keep track of squadStates + } else { // membership is valid + // keep track of squadStates group->numState[member->NPC->squadState]++; - if ( !group->commander || member->NPC->rank > group->commander->NPC->rank ) - {//keep track of highest rank + if (!group->commander || member->NPC->rank > group->commander->NPC->rank) { // keep track of highest rank group->commander = member; } } } - if ( group->memberValidateTime < level.time ) - { - group->memberValidateTime = level.time + Q_irand( 500, 2500 ); + if (group->memberValidateTime < level.time) { + group->memberValidateTime = level.time + Q_irand(500, 2500); } - //Now add any new guys as long as we're not full + // Now add any new guys as long as we're not full /* for ( i = 0, member = &g_entities[0]; i < globals.num_entities && group->numGroup < (MAX_GROUP_MEMBERS - 1); i++, member++) { @@ -831,40 +682,28 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } */ - //calc the morale of this group + // calc the morale of this group group->morale = group->moraleAdjust; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunts + if (member->NPC->rank < RANK_ENSIGN) { // grunts group->morale++; - } - else - { + } else { group->morale += member->NPC->rank; } - if ( group->commander && debugNPCAI->integer ) - { - G_DebugLine( group->commander->currentOrigin, member->currentOrigin, FRAMETIME, 0x00ff00ff, qtrue ); + if (group->commander && debugNPCAI->integer) { + G_DebugLine(group->commander->currentOrigin, member->currentOrigin, FRAMETIME, 0x00ff00ff, qtrue); } } - if ( group->enemy ) - {//modify morale based on enemy health and weapon - if ( group->enemy->health < 10 ) - { + if (group->enemy) { // modify morale based on enemy health and weapon + if (group->enemy->health < 10) { group->morale += 10; - } - else if ( group->enemy->health < 25 ) - { + } else if (group->enemy->health < 25) { group->morale += 5; - } - else if ( group->enemy->health < 50 ) - { + } else if (group->enemy->health < 50) { group->morale += 2; } - switch( group->enemy->s.weapon ) - { + switch (group->enemy->s.weapon) { case WP_SABER: group->morale -= 5; break; @@ -892,7 +731,7 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) case WP_DET_PACK: group->morale -= 10; break; - case WP_MELEE: // Any ol' melee attack + case WP_MELEE: // Any ol' melee attack group->morale += 20; break; case WP_STUN_BATON: @@ -909,56 +748,45 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) break; } } - if ( group->moraleDebounce < level.time ) - {//slowly degrade whatever moraleAdjusters we may have - if ( group->moraleAdjust > 0 ) - { + if (group->moraleDebounce < level.time) { // slowly degrade whatever moraleAdjusters we may have + if (group->moraleAdjust > 0) { group->moraleAdjust--; - } - else if ( group->moraleAdjust < 0 ) - { + } else if (group->moraleAdjust < 0) { group->moraleAdjust++; } - group->moraleDebounce = level.time + 1000;//FIXME: define? + group->moraleDebounce = level.time + 1000; // FIXME: define? } - //mark this group as not having been run this frame + // mark this group as not having been run this frame group->processed = qfalse; return (qboolean)(group->numGroup > 0); } -void AI_UpdateGroups( void ) -{ - if ( d_noGroupAI->integer ) - { +void AI_UpdateGroups(void) { + if (d_noGroupAI->integer) { return; } - //Clear all Groups - for ( int i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup || AI_RefreshGroup( &level.groups[i] ) == qfalse )//level.groups[i].enemy == NULL || + // Clear all Groups + for (int i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup || AI_RefreshGroup(&level.groups[i]) == qfalse) // level.groups[i].enemy == NULL || { - memset( &level.groups[i], 0, sizeof( level.groups[i] ) ); + memset(&level.groups[i], 0, sizeof(level.groups[i])); } } } -qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ) -{ - if ( !group ) - { +qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum) { + if (!group) { return qfalse; } - for ( int i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == entNum ) - { + for (int i = 0; i < group->numGroup; i++) { + if (group->member[i].number == entNum) { return qtrue; } } return qfalse; } -//Overload +// Overload /* void AI_GetGroup( AIGroupInfo_t &group, gentity_t *ent, int radius ) @@ -989,25 +817,22 @@ AI_CheckEnemyCollision ------------------------- */ -qboolean AI_CheckEnemyCollision( gentity_t *ent, qboolean takeEnemy ) -{ - if ( ent == NULL ) +qboolean AI_CheckEnemyCollision(gentity_t *ent, qboolean takeEnemy) { + if (ent == NULL) return qfalse; - if ( ent->svFlags & SVF_LOCKEDENEMY ) + if (ent->svFlags & SVF_LOCKEDENEMY) return qfalse; - navInfo_t info; + navInfo_t info; - NAV_GetLastMove( info ); + NAV_GetLastMove(info); - //See if we've hit something - if ( ( info.blocker ) && ( info.blocker != ent->enemy ) ) - { - if ( ( info.blocker->client ) && ( info.blocker->client->playerTeam == ent->client->enemyTeam ) ) - { - if ( takeEnemy ) - G_SetEnemy( ent, info.blocker ); + // See if we've hit something + if ((info.blocker) && (info.blocker != ent->enemy)) { + if ((info.blocker->client) && (info.blocker->client->playerTeam == ent->client->enemyTeam)) { + if (takeEnemy) + G_SetEnemy(ent, info.blocker); return qtrue; } @@ -1022,68 +847,63 @@ AI_DistributeAttack ------------------------- */ -#define MAX_RADIUS_ENTS 128 +#define MAX_RADIUS_ENTS 128 -gentity_t *AI_DistributeAttack( gentity_t *attacker, gentity_t *enemy, team_t team, int threshold ) -{ - //Don't take new targets - if ( NPC->svFlags & SVF_LOCKEDENEMY ) +gentity_t *AI_DistributeAttack(gentity_t *attacker, gentity_t *enemy, team_t team, int threshold) { + // Don't take new targets + if (NPC->svFlags & SVF_LOCKEDENEMY) return enemy; - int numSurrounding = AI_GetGroupSize( enemy->currentOrigin, 48, team, attacker ); + int numSurrounding = AI_GetGroupSize(enemy->currentOrigin, 48, team, attacker); - //First, see if we should look for the player - if ( enemy != &g_entities[0] ) - { - int aroundPlayer = AI_GetGroupSize( g_entities[0].currentOrigin, 48, team, attacker ); + // First, see if we should look for the player + if (enemy != &g_entities[0]) { + int aroundPlayer = AI_GetGroupSize(g_entities[0].currentOrigin, 48, team, attacker); - //See if we're above our threshold - if ( aroundPlayer < threshold ) - { + // See if we're above our threshold + if (aroundPlayer < threshold) { return &g_entities[0]; } } - //See if our current enemy is still ok - if ( numSurrounding < threshold ) + // See if our current enemy is still ok + if (numSurrounding < threshold) return enemy; - //Otherwise we need to take a new enemy if possible - vec3_t mins, maxs; + // Otherwise we need to take a new enemy if possible + vec3_t mins, maxs; - //Setup the bbox to search in - for ( int i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (int i = 0; i < 3; i++) { mins[i] = enemy->currentOrigin[i] - 512; maxs[i] = enemy->currentOrigin[i] + 512; } - //Get the number of entities in a given space - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; + // Get the number of entities in a given space + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; - int numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + int numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( int j = 0; j < numEnts; j++ ) - { - //Validate clients - if ( radiusEnts[ j ]->client == NULL ) + // Cull this list + for (int j = 0; j < numEnts; j++) { + // Validate clients + if (radiusEnts[j]->client == NULL) continue; - //Skip the requested avoid ent if present - if ( radiusEnts[ j ] == enemy ) + // Skip the requested avoid ent if present + if (radiusEnts[j] == enemy) continue; - //Must be on the same team - if ( radiusEnts[ j ]->client->playerTeam != enemy->client->playerTeam ) + // Must be on the same team + if (radiusEnts[j]->client->playerTeam != enemy->client->playerTeam) continue; - //Must be alive - if ( radiusEnts[ j ]->health <= 0 ) + // Must be alive + if (radiusEnts[j]->health <= 0) continue; - //Must not be overwhelmed - if ( AI_GetGroupSize( radiusEnts[j]->currentOrigin, 48, team, attacker ) > threshold ) + // Must not be overwhelmed + if (AI_GetGroupSize(radiusEnts[j]->currentOrigin, 48, team, attacker) > threshold) continue; return radiusEnts[j]; diff --git a/codeJK2/game/G_Timer.cpp b/codeJK2/game/G_Timer.cpp index b074b6a35c..daa39aa697 100644 --- a/codeJK2/game/G_Timer.cpp +++ b/codeJK2/game/G_Timer.cpp @@ -25,34 +25,29 @@ along with this program; if not, see . #include "../../code/Rufl/hstring.h" #include "../code/qcommon/ojk_saved_game_helper.h" -#define MAX_GTIMERS 16384 +#define MAX_GTIMERS 16384 -typedef struct gtimer_s -{ - hstring id; // Use handle strings, so that things work after loading +typedef struct gtimer_s { + hstring id; // Use handle strings, so that things work after loading int time; - struct gtimer_s *next; // In either free list or current list + struct gtimer_s *next; // In either free list or current list } gtimer_t; -gtimer_t g_timerPool[ MAX_GTIMERS ]; -gtimer_t *g_timers[ MAX_GENTITIES ]; +gtimer_t g_timerPool[MAX_GTIMERS]; +gtimer_t *g_timers[MAX_GENTITIES]; gtimer_t *g_timerFreeList; - -static int TIMER_GetCount(int num) -{ +static int TIMER_GetCount(int num) { gtimer_t *p = g_timers[num]; int count = 0; - while (p) - { + while (p) { count++; p = p->next; } - - return count; -} + return count; +} /* ------------------------- @@ -64,13 +59,11 @@ timer from the list and put it on the free list Doesn't do much error checking, only called below ------------------------- */ -static void TIMER_RemoveHelper( int num, gtimer_t *timer ) -{ +static void TIMER_RemoveHelper(int num, gtimer_t *timer) { gtimer_t *p = g_timers[num]; // Special case: first timer in list - if (p == timer) - { + if (p == timer) { g_timers[num] = g_timers[num]->next; p->next = g_timerFreeList; g_timerFreeList = p; @@ -78,8 +71,7 @@ static void TIMER_RemoveHelper( int num, gtimer_t *timer ) } // Find the predecessor - while (p->next != timer) - { + while (p->next != timer) { p = p->next; } @@ -90,28 +82,22 @@ static void TIMER_RemoveHelper( int num, gtimer_t *timer ) return; } - - - /* ------------------------- TIMER_Clear ------------------------- */ -void TIMER_Clear( void ) -{ +void TIMER_Clear(void) { int i; - for (i = 0; i < MAX_GENTITIES; i++) - { + for (i = 0; i < MAX_GENTITIES; i++) { g_timers[i] = NULL; } - for (i = 0; i < MAX_GTIMERS - 1; i++) - { - g_timerPool[i].next = &g_timerPool[i+1]; + for (i = 0; i < MAX_GTIMERS - 1; i++) { + g_timerPool[i].next = &g_timerPool[i + 1]; } - g_timerPool[MAX_GTIMERS-1].next = NULL; + g_timerPool[MAX_GTIMERS - 1].next = NULL; g_timerFreeList = &g_timerPool[0]; } @@ -121,22 +107,18 @@ TIMER_Clear ------------------------- */ -void TIMER_Clear( int idx ) -{ +void TIMER_Clear(int idx) { // rudimentary safety checks, might be other things to check? - if ( idx >= 0 && idx < MAX_GENTITIES ) - { + if (idx >= 0 && idx < MAX_GENTITIES) { gtimer_t *p = g_timers[idx]; // No timers at all -> do nothing - if (!p) - { + if (!p) { return; } // Find the end of this ents timer list - while (p->next) - { + while (p->next) { p = p->next; } @@ -147,69 +129,53 @@ void TIMER_Clear( int idx ) return; } } -void TIMER_Clear( gentity_t *ent ) -{ - if ( ent ) - TIMER_Clear( ent->s.number ); +void TIMER_Clear(gentity_t *ent) { + if (ent) + TIMER_Clear(ent->s.number); } - /* ------------------------- TIMER_Save ------------------------- */ -void TIMER_Save( void ) -{ - int j; - gentity_t *ent; +void TIMER_Save(void) { + int j; + gentity_t *ent; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) - { + for (j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++) { int numTimers = TIMER_GetCount(j); - if ( !ent->inuse && numTimers) - { -// Com_Printf( "WARNING: ent with timers not inuse\n" ); + if (!ent->inuse && numTimers) { + // Com_Printf( "WARNING: ent with timers not inuse\n" ); assert(numTimers); - TIMER_Clear( j ); + TIMER_Clear(j); numTimers = 0; } - //Write out the timer information - saved_game.write_chunk( - INT_ID('T', 'I', 'M', 'E'), - numTimers); - + // Write out the timer information + saved_game.write_chunk(INT_ID('T', 'I', 'M', 'E'), numTimers); + gtimer_t *p = g_timers[j]; - assert ((numTimers && p) || (!numTimers && !p)); + assert((numTimers && p) || (!numTimers && !p)); - while(p) - { - const char *timerID = p->id.c_str(); - const int length = strlen(timerID) + 1; - const int time = p->time - level.time; //convert this back to delta so we can use SET after loading + while (p) { + const char *timerID = p->id.c_str(); + const int length = strlen(timerID) + 1; + const int time = p->time - level.time; // convert this back to delta so we can use SET after loading - assert( length < 1024 );//This will cause problems when loading the timer if longer + assert(length < 1024); // This will cause problems when loading the timer if longer - //Write out the string size and data - saved_game.write_chunk( - INT_ID('T', 'S', 'L', 'N'), - length); + // Write out the string size and data + saved_game.write_chunk(INT_ID('T', 'S', 'L', 'N'), length); - saved_game.write_chunk( - INT_ID('T', 'S', 'N', 'M'), - timerID, - length); + saved_game.write_chunk(INT_ID('T', 'S', 'N', 'M'), timerID, length); - //Write out the timer data - saved_game.write_chunk( - INT_ID('T', 'D', 'T', 'A'), - time); + // Write out the timer data + saved_game.write_chunk(INT_ID('T', 'D', 'T', 'A'), time); p = p->next; } @@ -222,75 +188,57 @@ TIMER_Load ------------------------- */ -void TIMER_Load( void ) -{ +void TIMER_Load(void) { int j; - gentity_t *ent; + gentity_t *ent; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - for ( j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++ ) - { + for (j = 0, ent = &g_entities[0]; j < MAX_GENTITIES; j++, ent++) { int numTimers = 0; - saved_game.read_chunk( - INT_ID('T', 'I', 'M', 'E'), - numTimers); + saved_game.read_chunk(INT_ID('T', 'I', 'M', 'E'), numTimers); - //Make sure there's something to read - if ( numTimers == 0 ) + // Make sure there's something to read + if (numTimers == 0) continue; - //Read back all entries - for ( int i = 0; i < numTimers; i++ ) - { - int length = 0, time = 0; - char tempBuffer[1024]; // Still ugly. Setting ourselves up for 007 AUF all over again. =) + // Read back all entries + for (int i = 0; i < numTimers; i++) { + int length = 0, time = 0; + char tempBuffer[1024]; // Still ugly. Setting ourselves up for 007 AUF all over again. =) - assert (sizeof(g_timers[0]->time) == sizeof(time) );//make sure we're reading the same size as we wrote + assert(sizeof(g_timers[0]->time) == sizeof(time)); // make sure we're reading the same size as we wrote - saved_game.read_chunk( - INT_ID('T', 'S', 'L', 'N'), - length); - - if ( length >= 1024 ) { - assert( 0 ); + saved_game.read_chunk(INT_ID('T', 'S', 'L', 'N'), length); + + if (length >= 1024) { + assert(0); continue; } - //Read the id and time - saved_game.read_chunk( - INT_ID('T', 'S', 'N', 'M'), - tempBuffer, - length); + // Read the id and time + saved_game.read_chunk(INT_ID('T', 'S', 'N', 'M'), tempBuffer, length); tempBuffer[length] = '\0'; - saved_game.read_chunk( - INT_ID('T', 'D', 'T', 'A'), - time); + saved_game.read_chunk(INT_ID('T', 'D', 'T', 'A'), time); - //this is odd, we saved all the timers in the autosave, but not all the ents are spawned yet from an auto load, so skip it - if (ent->inuse) - { //Restore it + // this is odd, we saved all the timers in the autosave, but not all the ents are spawned yet from an auto load, so skip it + if (ent->inuse) { // Restore it TIMER_Set(ent, tempBuffer, time); } } } } - -static gtimer_t *TIMER_GetNew(int num, const char *identifier) -{ - assert(num < ENTITYNUM_MAX_NORMAL);//don't want timers on NONE or the WORLD +static gtimer_t *TIMER_GetNew(int num, const char *identifier) { + assert(num < ENTITYNUM_MAX_NORMAL); // don't want timers on NONE or the WORLD gtimer_t *p = g_timers[num]; // Search for an existing timer with this name - while (p) - { - if (p->id == identifier) - { // Found it + while (p) { + if (p->id == identifier) { // Found it return p; } @@ -298,8 +246,7 @@ static gtimer_t *TIMER_GetNew(int num, const char *identifier) } // No existing timer with this name was found, so grab one from the free list - if (!g_timerFreeList) - {//oh no, none free! + if (!g_timerFreeList) { // oh no, none free! assert(g_timerFreeList); return NULL; } @@ -311,25 +258,19 @@ static gtimer_t *TIMER_GetNew(int num, const char *identifier) return p; } - -gtimer_t *TIMER_GetExisting(int num, const char *identifier) -{ +gtimer_t *TIMER_GetExisting(int num, const char *identifier) { gtimer_t *p = g_timers[num]; - while (p) - { - if (p->id == identifier) - { // Found it + while (p) { + if (p->id == identifier) { // Found it return p; } p = p->next; } - - return NULL; -} - + return NULL; +} /* ------------------------- @@ -337,14 +278,12 @@ TIMER_Set ------------------------- */ -void TIMER_Set( gentity_t *ent, const char *identifier, int duration ) -{ +void TIMER_Set(gentity_t *ent, const char *identifier, int duration) { assert(ent->inuse); gtimer_t *timer = TIMER_GetNew(ent->s.number, identifier); - if (timer) - { - timer->id = identifier; + if (timer) { + timer->id = identifier; timer->time = level.time + duration; } } @@ -355,12 +294,10 @@ TIMER_Get ------------------------- */ -int TIMER_Get( gentity_t *ent, const char *identifier ) -{ +int TIMER_Get(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return -1; } @@ -373,12 +310,10 @@ TIMER_Done ------------------------- */ -qboolean TIMER_Done( gentity_t *ent, const char *identifier ) -{ +qboolean TIMER_Done(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return qtrue; } @@ -389,26 +324,23 @@ qboolean TIMER_Done( gentity_t *ent, const char *identifier ) ------------------------- TIMER_Done2 -Returns false if timer has been -started but is not done...or if +Returns false if timer has been +started but is not done...or if timer was never started ------------------------- */ -qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) -{ +qboolean TIMER_Done2(gentity_t *ent, const char *identifier, qboolean remove) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); qboolean res; - if (!timer) - { + if (!timer) { return qfalse; } res = (qboolean)(timer->time < level.time); - if (res && remove) - { + if (res && remove) { // Put it back on the free list TIMER_RemoveHelper(ent->s.number, timer); } @@ -421,12 +353,7 @@ qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) TIMER_Exists ------------------------- */ -qboolean TIMER_Exists( gentity_t *ent, const char *identifier ) -{ - return (qboolean)(TIMER_GetExisting(ent->s.number, identifier) != NULL); -} - - +qboolean TIMER_Exists(gentity_t *ent, const char *identifier) { return (qboolean)(TIMER_GetExisting(ent->s.number, identifier) != NULL); } /* ------------------------- @@ -434,12 +361,10 @@ TIMER_Remove Utility to get rid of any timer ------------------------- */ -void TIMER_Remove( gentity_t *ent, const char *identifier ) -{ +void TIMER_Remove(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return; } @@ -453,11 +378,9 @@ TIMER_Start ------------------------- */ -qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ) -{ - if ( TIMER_Done( self, identifier ) ) - { - TIMER_Set( self, identifier, duration ); +qboolean TIMER_Start(gentity_t *self, const char *identifier, int duration) { + if (TIMER_Done(self, identifier)) { + TIMER_Set(self, identifier, duration); return qtrue; } return qfalse; diff --git a/codeJK2/game/NPC.cpp b/codeJK2/game/NPC.cpp index b57d634777..2b6ea1efe3 100644 --- a/codeJK2/game/NPC.cpp +++ b/codeJK2/game/NPC.cpp @@ -34,105 +34,95 @@ along with this program; if not, see . extern vec3_t playerMins; extern vec3_t playerMaxs; -//extern void PM_SetAnimFinal(int *torsoAnim,int *legsAnim,int type,int anim,int priority,int *torsoAnimTimer,int *legsAnimTimer,gentity_t *gent); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void NPC_BSNoClip ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_ApplyRoff (void); -extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern void NPC_CheckPlayerAim ( void ); -extern void NPC_CheckAllClear ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void Mark1_dying( gentity_t *self ); -extern void NPC_BSCinematic( void ); -extern int GetTime ( int lastTime ); -extern void NPC_BSGM_Default( void ); -extern void NPC_CheckCharmed( void ); - -extern cvar_t *g_dismemberment; -extern cvar_t *g_saberRealisticCombat; - -//Local Variables -// ai debug cvars -cvar_t *debugNPCAI; // used to print out debug info about the bot AI -cvar_t *debugNPCFreeze; // set to disable bot ai and temporarily freeze them in place -cvar_t *debugNPCAimingBeam; -cvar_t *debugBreak; -cvar_t *debugNoRoam; -cvar_t *debugNPCName; -cvar_t *d_saberCombat; -cvar_t *d_JediAI; -cvar_t *d_noGroupAI; -cvar_t *d_asynchronousGroupAI; -cvar_t *d_altRoutes; -cvar_t *d_patched; -cvar_t *d_slowmodeath; - -extern qboolean stop_icarus; - -gentity_t *NPC; -gNPC_t *NPCInfo; -gclient_t *client; -usercmd_t ucmd; -visibility_t enemyVisibility; - -void NPC_SetAnim(gentity_t *ent,int type,int anim,int priority); -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); -extern void GM_Dying( gentity_t *self ); +// extern void PM_SetAnimFinal(int *torsoAnim,int *legsAnim,int type,int anim,int priority,int *torsoAnimTimer,int *legsAnimTimer,gentity_t *gent); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void NPC_BSNoClip(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_ApplyRoff(void); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern void NPC_CheckPlayerAim(void); +extern void NPC_CheckAllClear(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void Mark1_dying(gentity_t *self); +extern void NPC_BSCinematic(void); +extern int GetTime(int lastTime); +extern void NPC_BSGM_Default(void); +extern void NPC_CheckCharmed(void); + +extern cvar_t *g_dismemberment; +extern cvar_t *g_saberRealisticCombat; + +// Local Variables +// ai debug cvars +cvar_t *debugNPCAI; // used to print out debug info about the bot AI +cvar_t *debugNPCFreeze; // set to disable bot ai and temporarily freeze them in place +cvar_t *debugNPCAimingBeam; +cvar_t *debugBreak; +cvar_t *debugNoRoam; +cvar_t *debugNPCName; +cvar_t *d_saberCombat; +cvar_t *d_JediAI; +cvar_t *d_noGroupAI; +cvar_t *d_asynchronousGroupAI; +cvar_t *d_altRoutes; +cvar_t *d_patched; +cvar_t *d_slowmodeath; + +extern qboolean stop_icarus; + +gentity_t *NPC; +gNPC_t *NPCInfo; +gclient_t *client; +usercmd_t ucmd; +visibility_t enemyVisibility; + +void NPC_SetAnim(gentity_t *ent, int type, int anim, int priority); +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope); +extern void GM_Dying(gentity_t *self); extern int eventClearTime; -void CorpsePhysics( gentity_t *self ) -{ +void CorpsePhysics(gentity_t *self) { // run the bot through the server like it was a real client - memset( &ucmd, 0, sizeof( ucmd ) ); - ClientThink( self->s.number, &ucmd ); - VectorCopy( self->s.origin, self->s.origin2 ); + memset(&ucmd, 0, sizeof(ucmd)); + ClientThink(self->s.number, &ucmd); + VectorCopy(self->s.origin, self->s.origin2); - if ( self->client->NPC_class == CLASS_GALAKMECH ) - { - GM_Dying( self ); + if (self->client->NPC_class == CLASS_GALAKMECH) { + GM_Dying(self); } - //FIXME: match my pitch and roll for the slope of my groundPlane - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->flags&FL_DISINTEGRATED) ) - {//on the ground - //FIXME: check 4 corners - pitch_roll_for_slope( self, NULL ); + // FIXME: match my pitch and roll for the slope of my groundPlane + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->flags & FL_DISINTEGRATED)) { // on the ground + // FIXME: check 4 corners + pitch_roll_for_slope(self, NULL); } - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - if ( !(self->client->ps.eFlags&EF_NODRAW) ) - { - AddSightEvent( self->enemy, self->currentOrigin, 384, AEL_DISCOVERED ); + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + if (!(self->client->ps.eFlags & EF_NODRAW)) { + AddSightEvent(self->enemy, self->currentOrigin, 384, AEL_DISCOVERED); } } - if ( level.time - self->s.time > 3000 ) - {//been dead for 3 seconds - if ( g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer ) - {//can't be dismembered once dead - if ( self->client->NPC_class != CLASS_PROTOCOL ) - { + if (level.time - self->s.time > 3000) { // been dead for 3 seconds + if (g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer) { // can't be dismembered once dead + if (self->client->NPC_class != CLASS_PROTOCOL) { self->client->dismembered = qtrue; } } } - if ( level.time - self->s.time > 500 ) - {//don't turn "nonsolid" until about 1 second after actual death + if (level.time - self->s.time > 500) { // don't turn "nonsolid" until about 1 second after actual death - if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. + if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. { self->contents = CONTENTS_CORPSE; } - if ( self->message ) - { + if (self->message) { self->contents |= CONTENTS_TRIGGER; } } @@ -145,106 +135,85 @@ NPC_RemoveBody Determines when it's ok to ditch the corpse ---------------------------------------- */ -#define REMOVE_DISTANCE 128 +#define REMOVE_DISTANCE 128 #define REMOVE_DISTANCE_SQR (REMOVE_DISTANCE * REMOVE_DISTANCE) -void NPC_RemoveBody( gentity_t *self ) -{ - CorpsePhysics( self ); +void NPC_RemoveBody(gentity_t *self) { + CorpsePhysics(self); self->nextthink = level.time + FRAMETIME; - if ( self->NPC->nextBStateThink <= level.time ) - { - if( self->taskManager && !stop_icarus ) - { - self->taskManager->Update( ); + if (self->NPC->nextBStateThink <= level.time) { + if (self->taskManager && !stop_icarus) { + self->taskManager->Update(); } } self->NPC->nextBStateThink = level.time + FRAMETIME; - if ( self->message ) - {//I still have a key + if (self->message) { // I still have a key return; } // I don't consider this a hack, it's creative coding . . . // I agree, very creative... need something like this for ATST and GALAKMECH too! - if (self->client->NPC_class == CLASS_MARK1) - { - Mark1_dying( self ); + if (self->client->NPC_class == CLASS_MARK1) { + Mark1_dying(self); } // Since these blow up, remove the bounding box. - if ( self->client->NPC_class == CLASS_REMOTE - || self->client->NPC_class == CLASS_SENTRY - || self->client->NPC_class == CLASS_PROBE - || self->client->NPC_class == CLASS_INTERROGATOR - || self->client->NPC_class == CLASS_PROBE - || self->client->NPC_class == CLASS_MARK2 ) - { - if ( !self->taskManager || !self->taskManager->IsRunning() ) - { - G_FreeEntity( self ); + if (self->client->NPC_class == CLASS_REMOTE || self->client->NPC_class == CLASS_SENTRY || self->client->NPC_class == CLASS_PROBE || + self->client->NPC_class == CLASS_INTERROGATOR || self->client->NPC_class == CLASS_PROBE || self->client->NPC_class == CLASS_MARK2) { + if (!self->taskManager || !self->taskManager->IsRunning()) { + G_FreeEntity(self); } return; } - //FIXME: don't ever inflate back up? + // FIXME: don't ever inflate back up? self->maxs[2] = self->client->renderInfo.eyePoint[2] - self->currentOrigin[2] + 4; - if ( self->maxs[2] < -8 ) - { + if (self->maxs[2] < -8) { self->maxs[2] = -8; } - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//never disappears + if (self->client->NPC_class == CLASS_GALAKMECH) { // never disappears return; } - if ( self->NPC && self->NPC->timeOfDeath <= level.time ) - { + if (self->NPC && self->NPC->timeOfDeath <= level.time) { self->NPC->timeOfDeath = level.time + 1000; // Only do all of this nonsense for Scav boys ( and girls ) - /// if ( self->client->playerTeam == TEAM_SCAVENGERS || self->client->playerTeam == TEAM_KLINGON - // || self->client->playerTeam == TEAM_HIROGEN || self->client->playerTeam == TEAM_MALON ) + /// if ( self->client->playerTeam == TEAM_SCAVENGERS || self->client->playerTeam == TEAM_KLINGON + // || self->client->playerTeam == TEAM_HIROGEN || self->client->playerTeam == TEAM_MALON ) // should I check NPC_class here instead of TEAM ? - dmv - if( self->client->playerTeam == TEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL ) - { + if (self->client->playerTeam == TEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL) { self->nextthink = level.time + FRAMETIME; // try back in a second - if ( DistanceSquared( g_entities[0].currentOrigin, self->currentOrigin ) <= REMOVE_DISTANCE_SQR ) - { + if (DistanceSquared(g_entities[0].currentOrigin, self->currentOrigin) <= REMOVE_DISTANCE_SQR) { return; } - if ( (InFOV( self, &g_entities[0], 110, 90 )) ) // generous FOV check + if ((InFOV(self, &g_entities[0], 110, 90))) // generous FOV check { - if ( (NPC_ClearLOS( &g_entities[0], self->currentOrigin )) ) - { + if ((NPC_ClearLOS(&g_entities[0], self->currentOrigin))) { return; } } } - //FIXME: there are some conditions - such as heavy combat - in which we want + // FIXME: there are some conditions - such as heavy combat - in which we want // to remove the bodies... but in other cases it's just weird, like // when they're right behind you in a closed room and when they've been // placed as dead NPCs by a designer... // For now we just assume that a corpse with no enemy was // placed in the map as a corpse - if ( self->enemy ) - { - if ( !self->taskManager || !self->taskManager->IsRunning() ) - { - if ( self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD ) - { + if (self->enemy) { + if (!self->taskManager || !self->taskManager->IsRunning()) { + if (self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD) { gentity_t *saberent = &g_entities[self->client->ps.saberEntityNum]; - if ( saberent ) - { - G_FreeEntity( saberent ); + if (saberent) { + G_FreeEntity(saberent); } } - G_FreeEntity( self ); + G_FreeEntity(self); } } } @@ -258,21 +227,19 @@ Determines when it's ok to ditch the corpse ---------------------------------------- */ -int BodyRemovalPadTime( gentity_t *ent ) -{ - int time; +int BodyRemovalPadTime(gentity_t *ent) { + int time; - if ( !ent || !ent->client ) + if (!ent || !ent->client) return 0; // team no longer indicates species/race, so in this case we'd use NPC_class, but - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_MOUSE: case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_PROBE: @@ -284,18 +251,15 @@ int BodyRemovalPadTime( gentity_t *ent ) break; default: // never go away - // time = Q3_INFINITE; + // time = Q3_INFINITE; // for now I'm making default 10000 time = 10000; break; - } - return time; } - /* ---------------------------------------- NPC_RemoveBodyEffect @@ -304,19 +268,17 @@ Effect to be applied when ditching the corpse ---------------------------------------- */ -static void NPC_RemoveBodyEffect(void) -{ -// vec3_t org; -// gentity_t *tent; +static void NPC_RemoveBodyEffect(void) { + // vec3_t org; + // gentity_t *tent; - if ( !NPC || !NPC->client || (NPC->s.eFlags & EF_NODRAW) ) + if (!NPC || !NPC->client || (NPC->s.eFlags & EF_NODRAW)) return; // team no longer indicates species/race, so in this case we'd use NPC_class, but // stub code - switch(NPC->client->NPC_class) - { + switch (NPC->client->NPC_class) { case CLASS_PROBE: case CLASS_SEEKER: case CLASS_REMOTE: @@ -324,24 +286,21 @@ static void NPC_RemoveBodyEffect(void) case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_INTERROGATOR: case CLASS_ATST: // yeah, this is a little weird, but for now I'm listing all droids - // VectorCopy( NPC->currentOrigin, org ); - // org[2] -= 16; - // tent = G_TempEntity( org, EV_BOT_EXPLODE ); - // tent->owner = NPC; + // VectorCopy( NPC->currentOrigin, org ); + // org[2] -= 16; + // tent = G_TempEntity( org, EV_BOT_EXPLODE ); + // tent->owner = NPC; break; default: break; } - - } - /* ==================================================================== void pitch_roll_for_slope (edict_t *forwhom, vec3_t *slope) @@ -356,74 +315,66 @@ and returns. ==================================================================== */ -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ) -{ - vec3_t slope; - vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = { 0, 0, 0 }; - float pitch, mod, dot; +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope) { + vec3_t slope; + vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = {0, 0, 0}; + float pitch, mod, dot; - //if we don't have a slope, get one - if( !pass_slope || VectorCompare( vec3_origin, pass_slope ) ) - { + // if we don't have a slope, get one + if (!pass_slope || VectorCompare(vec3_origin, pass_slope)) { trace_t trace; - VectorCopy( forwhom->currentOrigin, startspot ); + VectorCopy(forwhom->currentOrigin, startspot); startspot[2] += forwhom->mins[2] + 4; - VectorCopy( startspot, endspot ); + VectorCopy(startspot, endspot); endspot[2] -= 300; - gi.trace( &trace, forwhom->currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); -// if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) -// forwhom.flags(-)FL_ONGROUND; + gi.trace(&trace, forwhom->currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); + // if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) + // forwhom.flags(-)FL_ONGROUND; - if ( trace.fraction >= 1.0 ) + if (trace.fraction >= 1.0) return; - if ( VectorCompare( vec3_origin, trace.plane.normal ) ) + if (VectorCompare(vec3_origin, trace.plane.normal)) return; - VectorCopy( trace.plane.normal, slope ); - } - else - { - VectorCopy( pass_slope, slope ); + VectorCopy(trace.plane.normal, slope); + } else { + VectorCopy(pass_slope, slope); } - AngleVectors( forwhom->currentAngles, ovf, ovr, NULL ); + AngleVectors(forwhom->currentAngles, ovf, ovr, NULL); - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod<0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); - if ( forwhom->client ) - { + if (forwhom->client) { forwhom->client->ps.viewangles[PITCH] = dot * pitch; - forwhom->client->ps.viewangles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->client->ps.viewangles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); float oldmins2 = forwhom->mins[2]; - forwhom->mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH])/180.0f; - //FIXME: if it gets bigger, move up - if ( oldmins2 > forwhom->mins[2] ) - {//our mins is now lower, need to move up - //FIXME: trace? + forwhom->mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH]) / 180.0f; + // FIXME: if it gets bigger, move up + if (oldmins2 > forwhom->mins[2]) { // our mins is now lower, need to move up + // FIXME: trace? forwhom->client->ps.origin[2] += (oldmins2 - forwhom->mins[2]); forwhom->currentOrigin[2] = forwhom->client->ps.origin[2]; - gi.linkentity( forwhom ); + gi.linkentity(forwhom); } - } - else - { + } else { forwhom->currentAngles[PITCH] = dot * pitch; - forwhom->currentAngles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->currentAngles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } } @@ -668,61 +619,50 @@ void NPC_PostDeathThink( void ) DeadThink ---------------------------------------- */ -static void DeadThink ( void ) -{ - trace_t trace; +static void DeadThink(void) { + trace_t trace; - //HACKHACKHACKHACKHACK - //We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only - //FIXME: don't ever inflate back up? + // HACKHACKHACKHACKHACK + // We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only + // FIXME: don't ever inflate back up? NPC->maxs[2] = NPC->client->renderInfo.eyePoint[2] - NPC->currentOrigin[2] + 4; - if ( NPC->maxs[2] < -8 ) - { + if (NPC->maxs[2] < -8) { NPC->maxs[2] = -8; } - if ( VectorCompare( NPC->client->ps.velocity, vec3_origin ) ) - {//not flying through the air - if ( NPC->mins[0] > -32 ) - { + if (VectorCompare(NPC->client->ps.velocity, vec3_origin)) { // not flying through the air + if (NPC->mins[0] > -32) { NPC->mins[0] -= 1; - gi.trace (&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid ) - { + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid) { NPC->mins[0] += 1; } } - if ( NPC->maxs[0] < 32 ) - { + if (NPC->maxs[0] < 32) { NPC->maxs[0] += 1; - gi.trace (&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid ) - { + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid) { NPC->maxs[0] -= 1; } } - if ( NPC->mins[1] > -32 ) - { + if (NPC->mins[1] > -32) { NPC->mins[1] -= 1; - gi.trace (&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid ) - { + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid) { NPC->mins[1] += 1; } } - if ( NPC->maxs[1] < 32 ) - { + if (NPC->maxs[1] < 32) { NPC->maxs[1] += 1; - gi.trace (&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid ) - { + gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, NPC->currentOrigin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid) { NPC->maxs[1] -= 1; } } } - //HACKHACKHACKHACKHACK + // HACKHACKHACKHACKHACK - //FIXME: tilt and fall off of ledges? - //NPC_PostDeathThink(); + // FIXME: tilt and fall off of ledges? + // NPC_PostDeathThink(); /* if ( !NPCInfo->timeOfDeath && NPC->client != NULL && NPCInfo != NULL ) @@ -743,38 +683,32 @@ static void DeadThink ( void ) else */ { - //death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove - if ( level.time >= NPCInfo->timeOfDeath + BodyRemovalPadTime( NPC ) ) - { - if ( NPC->client->ps.eFlags & EF_NODRAW ) - { - if ( !NPC->taskManager || !NPC->taskManager->IsRunning() ) - { + // death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove + if (level.time >= NPCInfo->timeOfDeath + BodyRemovalPadTime(NPC)) { + if (NPC->client->ps.eFlags & EF_NODRAW) { + if (!NPC->taskManager || !NPC->taskManager->IsRunning()) { NPC->e_ThinkFunc = thinkF_G_FreeEntity; NPC->nextthink = level.time + FRAMETIME; } - } - else - { + } else { // Start the body effect first, then delay 400ms before ditching the corpse NPC_RemoveBodyEffect(); - //FIXME: keep it running through physics somehow? + // FIXME: keep it running through physics somehow? NPC->e_ThinkFunc = thinkF_NPC_RemoveBody; NPC->nextthink = level.time + FRAMETIME; - // if ( NPC->client->playerTeam == TEAM_FORGE ) - // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - // else if ( NPC->client->playerTeam == TEAM_BOTS ) - class_t npc_class = NPC->client->NPC_class; + // if ( NPC->client->playerTeam == TEAM_FORGE ) + // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; + // else if ( NPC->client->playerTeam == TEAM_BOTS ) + class_t npc_class = NPC->client->NPC_class; // check for droids - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_MARK2 || npc_class == CLASS_SENTRY )//npc_class == CLASS_PROTOCOL || + if (npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_MARK2 || + npc_class == CLASS_SENTRY) // npc_class == CLASS_PROTOCOL || { NPC->client->ps.eFlags |= EF_NODRAW; NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - } - else + } else NPCInfo->timeOfDeath = level.time + FRAMETIME * 4; } return; @@ -782,21 +716,18 @@ static void DeadThink ( void ) } // If the player is on the ground and the resting position contents haven't been set yet...(BounceCount tracks the contents) - if ( NPC->bounceCount < 0 && NPC->s.groundEntityNum >= 0 ) - { + if (NPC->bounceCount < 0 && NPC->s.groundEntityNum >= 0) { // if client is in a nodrop area, make him/her nodraw - int contents = NPC->bounceCount = gi.pointcontents( NPC->currentOrigin, -1 ); + int contents = NPC->bounceCount = gi.pointcontents(NPC->currentOrigin, -1); - if ( ( contents & CONTENTS_NODROP ) ) - { + if ((contents & CONTENTS_NODROP)) { NPC->client->ps.eFlags |= EF_NODRAW; } } - CorpsePhysics( NPC ); + CorpsePhysics(NPC); } - /* =============== SetNPCGlobals @@ -804,149 +735,124 @@ SetNPCGlobals local function to set globals used throughout the AI code =============== */ -void SetNPCGlobals( gentity_t *ent ) -{ +void SetNPCGlobals(gentity_t *ent) { NPC = ent; NPCInfo = ent->NPC; client = ent->client; - memset( &ucmd, 0, sizeof( usercmd_t ) ); + memset(&ucmd, 0, sizeof(usercmd_t)); } -gentity_t *_saved_NPC; -gNPC_t *_saved_NPCInfo; -gclient_t *_saved_client; -usercmd_t _saved_ucmd; +gentity_t *_saved_NPC; +gNPC_t *_saved_NPCInfo; +gclient_t *_saved_client; +usercmd_t _saved_ucmd; -void SaveNPCGlobals() -{ +void SaveNPCGlobals() { _saved_NPC = NPC; _saved_NPCInfo = NPCInfo; _saved_client = client; - memcpy( &_saved_ucmd, &ucmd, sizeof( usercmd_t ) ); + memcpy(&_saved_ucmd, &ucmd, sizeof(usercmd_t)); } -void RestoreNPCGlobals() -{ +void RestoreNPCGlobals() { NPC = _saved_NPC; NPCInfo = _saved_NPCInfo; client = _saved_client; - memcpy( &ucmd, &_saved_ucmd, sizeof( usercmd_t ) ); + memcpy(&ucmd, &_saved_ucmd, sizeof(usercmd_t)); } -//We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC -void ClearNPCGlobals( void ) -{ +// We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC +void ClearNPCGlobals(void) { NPC = NULL; NPCInfo = NULL; client = NULL; } //=============== -extern qboolean showBBoxes; +extern qboolean showBBoxes; vec3_t NPCDEBUG_RED = {1.0, 0.0, 0.0}; vec3_t NPCDEBUG_GREEN = {0.0, 1.0, 0.0}; vec3_t NPCDEBUG_BLUE = {0.0, 0.0, 1.0}; vec3_t NPCDEBUG_LIGHT_BLUE = {0.3f, 0.7f, 1.0}; -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); - -void NPC_ShowDebugInfo (void) -{ - if ( showBBoxes ) - { - gentity_t *found = NULL; - vec3_t mins, maxs; - - while( (found = G_Find( found, FOFS(classname), "NPC" ) ) != NULL ) - { - if ( gi.inPVS( found->currentOrigin, g_entities[0].currentOrigin ) ) - { - VectorAdd( found->currentOrigin, found->mins, mins ); - VectorAdd( found->currentOrigin, found->maxs, maxs ); - CG_Cube( mins, maxs, NPCDEBUG_RED, 0.25 ); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); + +void NPC_ShowDebugInfo(void) { + if (showBBoxes) { + gentity_t *found = NULL; + vec3_t mins, maxs; + + while ((found = G_Find(found, FOFS(classname), "NPC")) != NULL) { + if (gi.inPVS(found->currentOrigin, g_entities[0].currentOrigin)) { + VectorAdd(found->currentOrigin, found->mins, mins); + VectorAdd(found->currentOrigin, found->maxs, maxs); + CG_Cube(mins, maxs, NPCDEBUG_RED, 0.25); } } } } -void NPC_ApplyScriptFlags (void) -{ - if ( NPCInfo->scriptFlags & SCF_CROUCHED ) - { - if ( NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the crouched command - } - else - { +void NPC_ApplyScriptFlags(void) { + if (NPCInfo->scriptFlags & SCF_CROUCHED) { + if (NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove)) { // ugh, if charmed and moving, ignore the crouched command + } else { ucmd.upmove = -127; } } - if(NPCInfo->scriptFlags & SCF_RUNNING) - { + if (NPCInfo->scriptFlags & SCF_RUNNING) { ucmd.buttons &= ~BUTTON_WALKING; - } - else if(NPCInfo->scriptFlags & SCF_WALKING) - { - if ( NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the walking command - } - else - { + } else if (NPCInfo->scriptFlags & SCF_WALKING) { + if (NPCInfo->charmedTime > level.time && (ucmd.forwardmove || ucmd.rightmove)) { // ugh, if charmed and moving, ignore the walking command + } else { ucmd.buttons |= BUTTON_WALKING; } } -/* - if(NPCInfo->scriptFlags & SCF_CAREFUL) - { - ucmd.buttons |= BUTTON_CAREFUL; - } -*/ - if(NPCInfo->scriptFlags & SCF_LEAN_RIGHT) - { + /* + if(NPCInfo->scriptFlags & SCF_CAREFUL) + { + ucmd.buttons |= BUTTON_CAREFUL; + } + */ + if (NPCInfo->scriptFlags & SCF_LEAN_RIGHT) { ucmd.buttons |= BUTTON_USE; ucmd.rightmove = 127; ucmd.forwardmove = 0; ucmd.upmove = 0; - } - else if(NPCInfo->scriptFlags & SCF_LEAN_LEFT) - { + } else if (NPCInfo->scriptFlags & SCF_LEAN_LEFT) { ucmd.buttons |= BUTTON_USE; ucmd.rightmove = -127; ucmd.forwardmove = 0; ucmd.upmove = 0; } - if ( (NPCInfo->scriptFlags & SCF_ALT_FIRE) && (ucmd.buttons & BUTTON_ATTACK) ) - {//Use altfire instead + if ((NPCInfo->scriptFlags & SCF_ALT_FIRE) && (ucmd.buttons & BUTTON_ATTACK)) { // Use altfire instead ucmd.buttons |= BUTTON_ALT_ATTACK; } } -void Q3_DebugPrint( int level, const char *format, ... ); -void NPC_HandleAIFlags (void) -{ - //FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers - if ( NPCInfo->aiFlags & NPCAI_LOST ) - {//Print that you need help! - //FIXME: shouldn't remove this just yet if cg_draw needs it +void Q3_DebugPrint(int level, const char *format, ...); +void NPC_HandleAIFlags(void) { + // FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers + if (NPCInfo->aiFlags & NPCAI_LOST) { // Print that you need help! + // FIXME: shouldn't remove this just yet if cg_draw needs it NPCInfo->aiFlags &= ~NPCAI_LOST; /* if ( showWaypoints ) { - Q3_DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, NPC->waypoint, NPCInfo->goalEntity->waypoint ); + Q3_DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, + NPC->waypoint, NPCInfo->goalEntity->waypoint ); } */ - if ( NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy ) - {//We can't nav to our enemy - //Drop enemy and see if we should search for him + if (NPCInfo->goalEntity && NPCInfo->goalEntity == NPC->enemy) { // We can't nav to our enemy + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); } } - //MRJ Request: + // MRJ Request: /* if ( NPCInfo->aiFlags & NPCAI_GREET_ALLIES && !NPC->enemy )//what if "enemy" is the greetEnt? {//If no enemy, look for teammates to greet @@ -996,167 +902,150 @@ void NPC_HandleAIFlags (void) } } */ - //been told to play a victory sound after a delay - if ( NPCInfo->greetingDebounceTime && NPCInfo->greetingDebounceTime < level.time ) - { - G_AddVoiceEvent( NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand( 2000, 4000 ) ); + // been told to play a victory sound after a delay + if (NPCInfo->greetingDebounceTime && NPCInfo->greetingDebounceTime < level.time) { + G_AddVoiceEvent(NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand(2000, 4000)); NPCInfo->greetingDebounceTime = 0; } - if ( NPCInfo->ffireCount > 0 ) - { - if ( NPCInfo->ffireFadeDebounce < level.time ) - { + if (NPCInfo->ffireCount > 0) { + if (NPCInfo->ffireFadeDebounce < level.time) { NPCInfo->ffireCount--; - //Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_spskill->integer)*2) ); + // Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_spskill->integer)*2) ); NPCInfo->ffireFadeDebounce = level.time + 3000; } } - if ( d_patched->integer ) - {//use patch-style navigation - if ( NPCInfo->consecutiveBlockedMoves > 20 ) - {//been stuck for a while, try again? + if (d_patched->integer) { // use patch-style navigation + if (NPCInfo->consecutiveBlockedMoves > 20) { // been stuck for a while, try again? NPCInfo->consecutiveBlockedMoves = 0; } } } -void NPC_AvoidWallsAndCliffs (void) -{ -/* - vec3_t forward, right, testPos, angles, mins; - trace_t trace; - float fwdDist, rtDist; - //FIXME: set things like this forward dir once at the beginning - //of a frame instead of over and over again - if ( NPCInfo->aiFlags & NPCAI_NO_COLL_AVOID ) - { - return; - } +void NPC_AvoidWallsAndCliffs(void) { + /* + vec3_t forward, right, testPos, angles, mins; + trace_t trace; + float fwdDist, rtDist; + //FIXME: set things like this forward dir once at the beginning + //of a frame instead of over and over again + if ( NPCInfo->aiFlags & NPCAI_NO_COLL_AVOID ) + { + return; + } - if ( ucmd.upmove > 0 || NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//Going to jump or in the air - return; - } + if ( ucmd.upmove > 0 || NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) + {//Going to jump or in the air + return; + } - if ( !ucmd.forwardmove && !ucmd.rightmove ) - { - return; - } + if ( !ucmd.forwardmove && !ucmd.rightmove ) + { + return; + } - if ( fabs( AngleDelta( NPC->currentAngles[YAW], NPCInfo->desiredYaw ) ) < 5.0 )//!ucmd.angles[YAW] ) - {//Not turning much, don't do this - //NOTE: Should this not happen only if you're not turning AT ALL? - // You could be turning slowly but moving fast, so that would - // still let you walk right off a cliff... - //NOTE: Or maybe it is a good idea to ALWAYS do this, regardless - // of whether ot not we're turning? But why would we be walking - // straight into a wall or off a cliff unless we really wanted to? - return; - } + if ( fabs( AngleDelta( NPC->currentAngles[YAW], NPCInfo->desiredYaw ) ) < 5.0 )//!ucmd.angles[YAW] ) + {//Not turning much, don't do this + //NOTE: Should this not happen only if you're not turning AT ALL? + // You could be turning slowly but moving fast, so that would + // still let you walk right off a cliff... + //NOTE: Or maybe it is a good idea to ALWAYS do this, regardless + // of whether ot not we're turning? But why would we be walking + // straight into a wall or off a cliff unless we really wanted to? + return; + } - VectorCopy( NPC->mins, mins ); - mins[2] += STEPSIZE; - angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); - fwdDist = ((float)ucmd.forwardmove)/16.0f; - rtDist = ((float)ucmd.rightmove)/16.0f; - VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); - VectorMA( testPos, rtDist, right, testPos ); - gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) - {//Going to bump into something, don't move, just turn - ucmd.forwardmove = 0; - ucmd.rightmove = 0; - return; - } + VectorCopy( NPC->mins, mins ); + mins[2] += STEPSIZE; + angles[YAW] = NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? + AngleVectors( angles, forward, right, NULL ); + fwdDist = ((float)ucmd.forwardmove)/16.0f; + rtDist = ((float)ucmd.rightmove)/16.0f; + VectorMA( NPC->currentOrigin, fwdDist, forward, testPos ); + VectorMA( testPos, rtDist, right, testPos ); + gi.trace( &trace, NPC->currentOrigin, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); + if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) + {//Going to bump into something, don't move, just turn + ucmd.forwardmove = 0; + ucmd.rightmove = 0; + return; + } - VectorCopy(trace.endpos, testPos); - testPos[2] -= 128; + VectorCopy(trace.endpos, testPos); + testPos[2] -= 128; - gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) - {//Not going off a cliff - return; - } + gi.trace( &trace, trace.endpos, mins, NPC->maxs, testPos, NPC->s.number, NPC->clipmask ); + if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0 ) + {//Not going off a cliff + return; + } - //going to fall at least 128, don't move, just turn... is this bad, though? What if we want them to drop off? - ucmd.forwardmove = 0; - ucmd.rightmove = 0; - return; -*/ + //going to fall at least 128, don't move, just turn... is this bad, though? What if we want them to drop off? + ucmd.forwardmove = 0; + ucmd.rightmove = 0; + return; + */ } -void NPC_CheckAttackScript(void) -{ - if(!(ucmd.buttons & BUTTON_ATTACK)) - { +void NPC_CheckAttackScript(void) { + if (!(ucmd.buttons & BUTTON_ATTACK)) { return; } G_ActivateBehavior(NPC, BSET_ATTACK); } -float NPC_MaxDistSquaredForWeapon (void); -void NPC_CheckAttackHold(void) -{ - vec3_t vec; +float NPC_MaxDistSquaredForWeapon(void); +void NPC_CheckAttackHold(void) { + vec3_t vec; // If they don't have an enemy they shouldn't hold their attack anim. - if ( !NPC->enemy ) - { + if (!NPC->enemy) { NPCInfo->attackHoldTime = 0; return; } -/* if ( ( NPC->client->ps.weapon == WP_BORG_ASSIMILATOR ) || ( NPC->client->ps.weapon == WP_BORG_DRILL ) ) - {//FIXME: don't keep holding this if can't hit enemy? + /* if ( ( NPC->client->ps.weapon == WP_BORG_ASSIMILATOR ) || ( NPC->client->ps.weapon == WP_BORG_DRILL ) ) + {//FIXME: don't keep holding this if can't hit enemy? - // If they don't have shields ( been disabled) they shouldn't hold their attack anim. - if ( !(NPC->NPC->aiFlags & NPCAI_SHIELDS) ) - { - NPCInfo->attackHoldTime = 0; - return; - } + // If they don't have shields ( been disabled) they shouldn't hold their attack anim. + if ( !(NPC->NPC->aiFlags & NPCAI_SHIELDS) ) + { + NPCInfo->attackHoldTime = 0; + return; + } - VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); - if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) - { - NPCInfo->attackHoldTime = 0; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); - } - else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) - { - ucmd.buttons |= BUTTON_ATTACK; - } - else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) - { - NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, NPCInfo->attackHold); - } - else - { - NPCInfo->attackHoldTime = 0; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); + if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) + { + NPCInfo->attackHoldTime = 0; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + } + else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) + { + ucmd.buttons |= BUTTON_ATTACK; + } + else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) + { + NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, NPCInfo->attackHold); + } + else + { + NPCInfo->attackHoldTime = 0; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + } } - } - else*/ - {//everyone else...? FIXME: need to tie this into AI somehow? + else*/ + { // everyone else...? FIXME: need to tie this into AI somehow? VectorSubtract(NPC->enemy->currentOrigin, NPC->currentOrigin, vec); - if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) - { + if (VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon()) { NPCInfo->attackHoldTime = 0; - } - else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) - { + } else if (NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time) { ucmd.buttons |= BUTTON_ATTACK; - } - else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) - { + } else if ((NPCInfo->attackHold) && (ucmd.buttons & BUTTON_ATTACK)) { NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; - } - else - { + } else { NPCInfo->attackHoldTime = 0; } } @@ -1167,16 +1056,13 @@ void NPC_KeepCurrentFacing(void) Fills in a default ucmd to keep current angles facing */ -void NPC_KeepCurrentFacing(void) -{ - if(!ucmd.angles[YAW]) - { - ucmd.angles[YAW] = ANGLE2SHORT( client->ps.viewangles[YAW] ) - client->ps.delta_angles[YAW]; +void NPC_KeepCurrentFacing(void) { + if (!ucmd.angles[YAW]) { + ucmd.angles[YAW] = ANGLE2SHORT(client->ps.viewangles[YAW]) - client->ps.delta_angles[YAW]; } - if(!ucmd.angles[PITCH]) - { - ucmd.angles[PITCH] = ANGLE2SHORT( client->ps.viewangles[PITCH] ) - client->ps.delta_angles[PITCH]; + if (!ucmd.angles[PITCH]) { + ucmd.angles[PITCH] = ANGLE2SHORT(client->ps.viewangles[PITCH]) - client->ps.delta_angles[PITCH]; } } @@ -1186,27 +1072,25 @@ NPC_BehaviorSet_Charmed ------------------------- */ -void NPC_BehaviorSet_Charmed( int bState ) -{ - switch( bState ) - { - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across +void NPC_BehaviorSet_Charmed(int bState) { + switch (bState) { + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: NPC_BSFlee(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -1217,32 +1101,30 @@ NPC_BehaviorSet_Default ------------------------- */ -void NPC_BehaviorSet_Default( int bState ) -{ - switch( bState ) - { - case BS_ADVANCE_FIGHT://head toward captureGoal, shoot anything that gets in the way - NPC_BSAdvanceFight (); +void NPC_BehaviorSet_Default(int bState) { + switch (bState) { + case BS_ADVANCE_FIGHT: // head toward captureGoal, shoot anything that gets in the way + NPC_BSAdvanceFight(); break; - case BS_SLEEP://Follow a path, looking for enemies - NPC_BSSleep (); + case BS_SLEEP: // Follow a path, looking for enemies + NPC_BSSleep(); break; - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; - case BS_JUMP: //41: Face navgoal and jump to it. + case BS_JUMP: // 41: Face navgoal and jump to it. NPC_BSJump(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; case BS_NOCLIP: NPC_BSNoClip(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: @@ -1255,7 +1137,7 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BSCinematic(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -1266,10 +1148,8 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BehaviorSet_Interrogator ------------------------- */ -void NPC_BehaviorSet_Interrogator( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Interrogator(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1278,13 +1158,13 @@ void NPC_BehaviorSet_Interrogator( int bState ) NPC_BSInterrogator_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSImperialProbe_Attack( void ); -void NPC_BSImperialProbe_Patrol( void ); +void NPC_BSImperialProbe_Attack(void); +void NPC_BSImperialProbe_Patrol(void); void NPC_BSImperialProbe_Wait(void); /* @@ -1292,10 +1172,8 @@ void NPC_BSImperialProbe_Wait(void); NPC_BehaviorSet_ImperialProbe ------------------------- */ -void NPC_BehaviorSet_ImperialProbe( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ImperialProbe(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1304,23 +1182,20 @@ void NPC_BehaviorSet_ImperialProbe( int bState ) NPC_BSImperialProbe_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } - -void NPC_BSSeeker_Default( void ); +void NPC_BSSeeker_Default(void); /* ------------------------- NPC_BehaviorSet_Seeker ------------------------- */ -void NPC_BehaviorSet_Seeker( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Seeker(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1329,22 +1204,20 @@ void NPC_BehaviorSet_Seeker( int bState ) NPC_BSSeeker_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSRemote_Default( void ); +void NPC_BSRemote_Default(void); /* ------------------------- NPC_BehaviorSet_Remote ------------------------- */ -void NPC_BehaviorSet_Remote( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Remote(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1353,22 +1226,20 @@ void NPC_BehaviorSet_Remote( int bState ) NPC_BSRemote_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSSentry_Default( void ); +void NPC_BSSentry_Default(void); /* ------------------------- NPC_BehaviorSet_Sentry ------------------------- */ -void NPC_BehaviorSet_Sentry( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sentry(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1377,7 +1248,7 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BSSentry_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1387,10 +1258,8 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BehaviorSet_Grenadier ------------------------- */ -void NPC_BehaviorSet_Grenadier( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Grenadier(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1400,7 +1269,7 @@ void NPC_BehaviorSet_Grenadier( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1409,10 +1278,8 @@ void NPC_BehaviorSet_Grenadier( int bState ) NPC_BehaviorSet_Sniper ------------------------- */ -void NPC_BehaviorSet_Sniper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sniper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1422,7 +1289,7 @@ void NPC_BehaviorSet_Sniper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1432,10 +1299,8 @@ NPC_BehaviorSet_Stormtrooper ------------------------- */ -void NPC_BehaviorSet_Stormtrooper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Stormtrooper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1453,7 +1318,7 @@ void NPC_BehaviorSet_Stormtrooper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1464,10 +1329,8 @@ NPC_BehaviorSet_Jedi ------------------------- */ -void NPC_BehaviorSet_Jedi( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Jedi(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1481,7 +1344,7 @@ void NPC_BehaviorSet_Jedi( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1491,17 +1354,15 @@ void NPC_BehaviorSet_Jedi( int bState ) NPC_BehaviorSet_Droid ------------------------- */ -void NPC_BehaviorSet_Droid( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Droid(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSDroid_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1511,17 +1372,15 @@ void NPC_BehaviorSet_Droid( int bState ) NPC_BehaviorSet_Mark1 ------------------------- */ -void NPC_BehaviorSet_Mark1( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark1(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSMark1_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1531,10 +1390,8 @@ void NPC_BehaviorSet_Mark1( int bState ) NPC_BehaviorSet_Mark2 ------------------------- */ -void NPC_BehaviorSet_Mark2( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark2(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1542,7 +1399,7 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BSMark2_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1552,10 +1409,8 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BehaviorSet_ATST ------------------------- */ -void NPC_BehaviorSet_ATST( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ATST(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1563,7 +1418,7 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BSATST_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1573,10 +1428,8 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BehaviorSet_MineMonster ------------------------- */ -void NPC_BehaviorSet_MineMonster( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_MineMonster(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1585,7 +1438,7 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BSMineMonster_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1595,10 +1448,8 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BehaviorSet_Howler ------------------------- */ -void NPC_BehaviorSet_Howler( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Howler(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1607,7 +1458,7 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_BSHowler_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1617,72 +1468,60 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_RunBehavior ------------------------- */ -extern void NPC_BSEmplaced( void ); -extern qboolean NPC_CheckSurrender( void ); -void NPC_RunBehavior( int team, int bState ) -{ - //qboolean dontSetAim = qfalse; +extern void NPC_BSEmplaced(void); +extern qboolean NPC_CheckSurrender(void); +void NPC_RunBehavior(int team, int bState) { + // qboolean dontSetAim = qfalse; - if ( bState == BS_CINEMATIC ) - { + if (bState == BS_CINEMATIC) { NPC_BSCinematic(); - } - else if ( NPC->client->ps.weapon == WP_EMPLACED_GUN ) - { + } else if (NPC->client->ps.weapon == WP_EMPLACED_GUN) { NPC_BSEmplaced(); NPC_CheckCharmed(); return; - } - else if ( NPC->client->ps.weapon == WP_SABER ) - {//jedi - NPC_BehaviorSet_Jedi( bState ); - //dontSetAim = qtrue; - } - else if ( NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to march + } else if (NPC->client->ps.weapon == WP_SABER) { // jedi + NPC_BehaviorSet_Jedi(bState); + // dontSetAim = qtrue; + } else if (NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to march NPC_BSDefault(); - } - else - { - switch( team ) - { - - // case TEAM_SCAVENGERS: - // case TEAM_IMPERIAL: - // case TEAM_KLINGON: - // case TEAM_HIROGEN: - // case TEAM_MALON: - // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv + } else { + switch (team) { + + // case TEAM_SCAVENGERS: + // case TEAM_IMPERIAL: + // case TEAM_KLINGON: + // case TEAM_HIROGEN: + // case TEAM_MALON: + // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv case TEAM_ENEMY: // special cases for enemy droids - switch( NPC->client->NPC_class) - { + switch (NPC->client->NPC_class) { case CLASS_ATST: - NPC_BehaviorSet_ATST( bState ); + NPC_BehaviorSet_ATST(bState); return; case CLASS_PROBE: NPC_BehaviorSet_ImperialProbe(bState); return; case CLASS_REMOTE: - NPC_BehaviorSet_Remote( bState ); + NPC_BehaviorSet_Remote(bState); return; case CLASS_SENTRY: NPC_BehaviorSet_Sentry(bState); return; case CLASS_INTERROGATOR: - NPC_BehaviorSet_Interrogator( bState ); + NPC_BehaviorSet_Interrogator(bState); return; case CLASS_MINEMONSTER: - NPC_BehaviorSet_MineMonster( bState ); + NPC_BehaviorSet_MineMonster(bState); return; case CLASS_HOWLER: - NPC_BehaviorSet_Howler( bState ); + NPC_BehaviorSet_Howler(bState); return; case CLASS_MARK1: - NPC_BehaviorSet_Mark1( bState ); + NPC_BehaviorSet_Mark1(bState); return; case CLASS_MARK2: - NPC_BehaviorSet_Mark2( bState ); + NPC_BehaviorSet_Mark2(bState); return; case CLASS_GALAKMECH: NPC_BSGM_Default(); @@ -1691,71 +1530,56 @@ void NPC_RunBehavior( int team, int bState ) break; } - if ( NPC->enemy && NPC->s.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there - if ( bState != BS_FLEE ) - { - NPC_StartFlee( NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - } - else - { + if (NPC->enemy && NPC->s.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && + !Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there + if (bState != BS_FLEE) { + NPC_StartFlee(NPC->enemy, NPC->enemy->currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } else { NPC_BSFlee(); } return; } - if ( NPC->client->ps.weapon == WP_SABER ) - {//special melee exception - NPC_BehaviorSet_Default( bState ); + if (NPC->client->ps.weapon == WP_SABER) { // special melee exception + NPC_BehaviorSet_Default(bState); return; } - if ( NPC->client->ps.weapon == WP_DISRUPTOR && (NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//a sniper - NPC_BehaviorSet_Sniper( bState ); + if (NPC->client->ps.weapon == WP_DISRUPTOR && (NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // a sniper + NPC_BehaviorSet_Sniper(bState); return; } - if ( NPC->client->ps.weapon == WP_THERMAL || NPC->client->ps.weapon == WP_MELEE )//FIXME: separate AI for melee fighters - {//a grenadier - NPC_BehaviorSet_Grenadier( bState ); + if (NPC->client->ps.weapon == WP_THERMAL || NPC->client->ps.weapon == WP_MELEE) // FIXME: separate AI for melee fighters + { // a grenadier + NPC_BehaviorSet_Grenadier(bState); return; } - if ( NPC_CheckSurrender() ) - { + if (NPC_CheckSurrender()) { return; } - NPC_BehaviorSet_Stormtrooper( bState ); + NPC_BehaviorSet_Stormtrooper(bState); break; case TEAM_NEUTRAL: // special cases for enemy droids - if ( NPC->client->NPC_class == CLASS_PROTOCOL || NPC->client->NPC_class == CLASS_UGNAUGHT) - { + if (NPC->client->NPC_class == CLASS_PROTOCOL || NPC->client->NPC_class == CLASS_UGNAUGHT) { NPC_BehaviorSet_Default(bState); - } - else - { + } else { // Just one of the average droids - NPC_BehaviorSet_Droid( bState ); + NPC_BehaviorSet_Droid(bState); } break; default: - if ( NPC->client->NPC_class == CLASS_SEEKER ) - { + if (NPC->client->NPC_class == CLASS_SEEKER) { NPC_BehaviorSet_Seeker(bState); - } - else - { - if ( NPCInfo->charmedTime > level.time ) - { - NPC_BehaviorSet_Charmed( bState ); - } - else - { - NPC_BehaviorSet_Default( bState ); + } else { + if (NPCInfo->charmedTime > level.time) { + NPC_BehaviorSet_Charmed(bState); + } else { + NPC_BehaviorSet_Default(bState); } NPC_CheckCharmed(); - //dontSetAim = qtrue; + // dontSetAim = qtrue; } break; } @@ -1772,113 +1596,92 @@ NPC Behavior state thinking =============== */ -void NPC_ExecuteBState ( gentity_t *self)//, int msec ) +void NPC_ExecuteBState(gentity_t *self) //, int msec ) { - bState_t bState; + bState_t bState; NPC_HandleAIFlags(); - //FIXME: these next three bits could be a function call, some sort of setup/cleanup func - //Lookmode must be reset every think cycle - if(NPC->delayScriptTime && NPC->delayScriptTime <= level.time) - { - G_ActivateBehavior( NPC, BSET_DELAYED); + // FIXME: these next three bits could be a function call, some sort of setup/cleanup func + // Lookmode must be reset every think cycle + if (NPC->delayScriptTime && NPC->delayScriptTime <= level.time) { + G_ActivateBehavior(NPC, BSET_DELAYED); NPC->delayScriptTime = 0; } - //Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func + // Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func NPCInfo->combatMove = qfalse; - //Execute our bState - if(NPCInfo->tempBehavior) - {//Overrides normal behavior until cleared + // Execute our bState + if (NPCInfo->tempBehavior) { // Overrides normal behavior until cleared bState = NPCInfo->tempBehavior; - } - else - { - if(!NPCInfo->behaviorState) + } else { + if (!NPCInfo->behaviorState) NPCInfo->behaviorState = NPCInfo->defaultBehavior; bState = NPCInfo->behaviorState; } - //Pick the proper bstate for us and run it - NPC_RunBehavior( self->client->playerTeam, bState ); - + // Pick the proper bstate for us and run it + NPC_RunBehavior(self->client->playerTeam, bState); -// if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) -// { - //level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; - //NPCInfo->combatPoint = -1; -// } + // if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) + // { + // level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; + // NPCInfo->combatPoint = -1; + // } - //Here we need to see what the scripted stuff told us to do -//Only process snapshot if independant and in combat mode- this would pick enemies and go after needed items -// ProcessSnapshot(); + // Here we need to see what the scripted stuff told us to do + // Only process snapshot if independant and in combat mode- this would pick enemies and go after needed items + // ProcessSnapshot(); -//Ignore my needs if I'm under script control- this would set needs for items -// CheckSelf(); + // Ignore my needs if I'm under script control- this would set needs for items + // CheckSelf(); - //Back to normal? All decisions made? + // Back to normal? All decisions made? - //FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface - //NPCPredict(); + // FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface + // NPCPredict(); - if ( NPC->enemy ) - { - if ( !NPC->enemy->inuse ) - {//just in case bState doesn't catch this - G_ClearEnemy( NPC ); + if (NPC->enemy) { + if (!NPC->enemy->inuse) { // just in case bState doesn't catch this + G_ClearEnemy(NPC); } } - if ( NPC->client->ps.saberLockTime && NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE ) - { - NPC_SetLookTarget( NPC, NPC->client->ps.saberLockEnemy, level.time+1000 ); - } - else if ( !NPC_CheckLookTarget( NPC ) ) - { - if ( NPC->enemy ) - { - NPC_SetLookTarget( NPC, NPC->enemy->s.number, 0 ); + if (NPC->client->ps.saberLockTime && NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE) { + NPC_SetLookTarget(NPC, NPC->client->ps.saberLockEnemy, level.time + 1000); + } else if (!NPC_CheckLookTarget(NPC)) { + if (NPC->enemy) { + NPC_SetLookTarget(NPC, NPC->enemy->s.number, 0); } } - if ( NPC->enemy ) - { - if(NPC->enemy->flags & FL_DONT_SHOOT) - { + if (NPC->enemy) { + if (NPC->enemy->flags & FL_DONT_SHOOT) { ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons &= ~BUTTON_ALT_ATTACK; - } - else if ( NPC->client->playerTeam != TEAM_ENEMY && NPC->enemy->NPC && (NPC->enemy->NPC->surrenderTime > level.time || (NPC->enemy->NPC->scriptFlags&SCF_FORCED_MARCH)) ) - {//don't shoot someone who's surrendering if you're a good guy + } else if (NPC->client->playerTeam != TEAM_ENEMY && NPC->enemy->NPC && + (NPC->enemy->NPC->surrenderTime > level.time || + (NPC->enemy->NPC->scriptFlags & SCF_FORCED_MARCH))) { // don't shoot someone who's surrendering if you're a good guy ucmd.buttons &= ~BUTTON_ATTACK; ucmd.buttons &= ~BUTTON_ALT_ATTACK; } - if(client->ps.weaponstate == WEAPON_IDLE) - { + if (client->ps.weaponstate == WEAPON_IDLE) { client->ps.weaponstate = WEAPON_READY; } - } - else - { - if(client->ps.weaponstate == WEAPON_READY) - { + } else { + if (client->ps.weaponstate == WEAPON_READY) { client->ps.weaponstate = WEAPON_IDLE; } } - if(!(ucmd.buttons & BUTTON_ATTACK) && NPC->attackDebounceTime > level.time) - {//We just shot but aren't still shooting, so hold the gun up for a while - if(client->ps.weapon == WP_SABER ) - {//One-handed - NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY1,SETANIM_FLAG_NORMAL); - } - else if(client->ps.weapon == WP_BRYAR_PISTOL) - {//Sniper pose - NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + if (!(ucmd.buttons & BUTTON_ATTACK) && NPC->attackDebounceTime > level.time) { // We just shot but aren't still shooting, so hold the gun up for a while + if (client->ps.weapon == WP_SABER) { // One-handed + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_WEAPONREADY1, SETANIM_FLAG_NORMAL); + } else if (client->ps.weapon == WP_BRYAR_PISTOL) { // Sniper pose + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } /*//FIXME: What's the proper solution here? else @@ -1886,39 +1689,34 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); } */ - } - else if ( !NPC->enemy )//HACK! + } else if (!NPC->enemy) // HACK! { - if( NPC->s.torsoAnim == TORSO_WEAPONREADY1 || NPC->s.torsoAnim == TORSO_WEAPONREADY3 ) - {//we look ready for action, using one of the first 2 weapon, let's rest our weapon on our shoulder - NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONIDLE1,SETANIM_FLAG_NORMAL); + if (NPC->s.torsoAnim == TORSO_WEAPONREADY1 || + NPC->s.torsoAnim == TORSO_WEAPONREADY3) { // we look ready for action, using one of the first 2 weapon, let's rest our weapon on our shoulder + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_WEAPONIDLE1, SETANIM_FLAG_NORMAL); } } NPC_CheckAttackHold(); NPC_ApplyScriptFlags(); - //cliff and wall avoidance + // cliff and wall avoidance NPC_AvoidWallsAndCliffs(); // run the bot through the server like it was a real client -//=== Save the ucmd for the second no-think Pmove ============================ + //=== Save the ucmd for the second no-think Pmove ============================ ucmd.serverTime = level.time - 50; - memcpy( &NPCInfo->last_ucmd, &ucmd, sizeof( usercmd_t ) ); - if ( !NPCInfo->attackHoldTime ) - { - NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK);//so we don't fire twice in one think + memcpy(&NPCInfo->last_ucmd, &ucmd, sizeof(usercmd_t)); + if (!NPCInfo->attackHoldTime) { + NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); // so we don't fire twice in one think } -//============================================================================ + //============================================================================ NPC_CheckAttackScript(); NPC_KeepCurrentFacing(); - if ( !NPC->next_roff_time || NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - ClientThink( NPC->s.number, &ucmd ); - } - else - { + if (!NPC->next_roff_time || NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + ClientThink(NPC->s.number, &ucmd); + } else { NPC_ApplyRoff(); } @@ -1952,28 +1750,24 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) if(la != -1 && ta != -1) {//FIXME: should never play same frame twice or restart an anim before finishing it - gi.Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, NPC->client->renderInfo.torsoFrame); + gi.Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, + NPC->client->renderInfo.torsoFrame); } }*/ } -void NPC_CheckInSolid(void) -{ - trace_t trace; - vec3_t point; +void NPC_CheckInSolid(void) { + trace_t trace; + vec3_t point; VectorCopy(NPC->currentOrigin, point); point[2] -= 0.25; gi.trace(&trace, NPC->currentOrigin, NPC->mins, NPC->maxs, point, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); - if(!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy(NPC->currentOrigin, NPCInfo->lastClearOrigin); - } - else - { - if(VectorLengthSquared(NPCInfo->lastClearOrigin)) - { -// gi.Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->currentOrigin)); + } else { + if (VectorLengthSquared(NPCInfo->lastClearOrigin)) { + // gi.Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->currentOrigin)); G_SetOrigin(NPC, NPCInfo->lastClearOrigin); gi.linkentity(NPC); } @@ -1987,170 +1781,150 @@ NPC_Think Main NPC AI - called once per frame =============== */ -#if AI_TIMERS +#if AI_TIMERS extern int AITime; -#endif// AI_TIMERS -void NPC_Think ( gentity_t *self)//, int msec ) +#endif // AI_TIMERS +void NPC_Think(gentity_t *self) //, int msec ) { - vec3_t oldMoveDir; + vec3_t oldMoveDir; self->nextthink = level.time + FRAMETIME; - SetNPCGlobals( self ); + SetNPCGlobals(self); - memset( &ucmd, 0, sizeof( ucmd ) ); + memset(&ucmd, 0, sizeof(ucmd)); - VectorCopy( self->client->ps.moveDir, oldMoveDir ); - VectorClear( self->client->ps.moveDir ); + VectorCopy(self->client->ps.moveDir, oldMoveDir); + VectorClear(self->client->ps.moveDir); // see if NPC ai is frozen - if ( debugNPCFreeze->value || (NPC->svFlags&SVF_ICARUS_FREEZE) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (debugNPCFreeze->value || (NPC->svFlags & SVF_ICARUS_FREEZE)) { + NPC_UpdateAngles(qtrue, qtrue); ClientThink(self->s.number, &ucmd); - VectorCopy(self->s.origin, self->s.origin2 ); + VectorCopy(self->s.origin, self->s.origin2); return; } - if(!self || !self->NPC || !self->client) - { + if (!self || !self->NPC || !self->client) { return; } // dead NPCs have a special think, don't run scripts (for now) - //FIXME: this breaks deathscripts - if ( self->health <= 0 ) - { + // FIXME: this breaks deathscripts + if (self->health <= 0) { DeadThink(); - if ( NPCInfo->nextBStateThink <= level.time ) - { - if( self->taskManager && !stop_icarus ) - { - self->taskManager->Update( ); + if (NPCInfo->nextBStateThink <= level.time) { + if (self->taskManager && !stop_icarus) { + self->taskManager->Update(); } } return; } - self->nextthink = level.time + FRAMETIME/2; + self->nextthink = level.time + FRAMETIME / 2; - if ( player->client->ps.viewEntity == self->s.number ) - {//being controlled by player - if ( self->client ) - {//make the noises - if ( TIMER_Done( self, "patrolNoise" ) && !Q_irand( 0, 20 ) ) - { - switch( self->client->NPC_class ) - { - case CLASS_R2D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)) ); + if (player->client->ps.viewEntity == self->s.number) { // being controlled by player + if (self->client) { // make the noises + if (TIMER_Done(self, "patrolNoise") && !Q_irand(0, 20)) { + switch (self->client->NPC_class) { + case CLASS_R2D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); break; - case CLASS_R5D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)) ); + case CLASS_R5D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); break; - case CLASS_PROBE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav",Q_irand(1, 3)) ); + case CLASS_PROBE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav", Q_irand(1, 3))); break; - case CLASS_MOUSE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)) ); + case CLASS_MOUSE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); break; - case CLASS_GONK: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)) ); + case CLASS_GONK: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); break; default: break; } - TIMER_Set( self, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(self, "patrolNoise", Q_irand(2000, 4000)); } } - //FIXME: might want to at least make sounds or something? - //NPC_UpdateAngles(qtrue, qtrue); - //Which ucmd should we send? Does it matter, since it gets overridden anyway? + // FIXME: might want to at least make sounds or something? + // NPC_UpdateAngles(qtrue, qtrue); + // Which ucmd should we send? Does it matter, since it gets overridden anyway? NPCInfo->last_ucmd.serverTime = level.time - 50; - ClientThink( NPC->s.number, &ucmd ); - VectorCopy(self->s.origin, self->s.origin2 ); + ClientThink(NPC->s.number, &ucmd); + VectorCopy(self->s.origin, self->s.origin2); return; } - if ( NPCInfo->nextBStateThink <= level.time ) - { -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS - if ( NPC->s.eType != ET_PLAYER ) - {//Something drastic happened in our script + if (NPCInfo->nextBStateThink <= level.time) { +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS + if (NPC->s.eType != ET_PLAYER) { // Something drastic happened in our script return; } - if ( NPC->s.weapon == WP_SABER && g_spskill->integer >= 2 && NPCInfo->rank > RANK_LT_JG ) - {//Jedi think faster on hard difficulty, except low-rank (reborn) - NPCInfo->nextBStateThink = level.time + FRAMETIME/2; - } - else - {//Maybe even 200 ms? + if (NPC->s.weapon == WP_SABER && g_spskill->integer >= 2 && + NPCInfo->rank > RANK_LT_JG) { // Jedi think faster on hard difficulty, except low-rank (reborn) + NPCInfo->nextBStateThink = level.time + FRAMETIME / 2; + } else { // Maybe even 200 ms? NPCInfo->nextBStateThink = level.time + FRAMETIME; } - //nextthink is set before this so something in here can override it - NPC_ExecuteBState( self ); + // nextthink is set before this so something in here can override it + NPC_ExecuteBState(self); -#if AI_TIMERS - int addTime = GetTime( startTime ); - if ( addTime > 50 ) - { - gi.Printf( S_COLOR_RED"ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, vtos(NPC->currentOrigin), NPC->s.weapon, addTime ); +#if AI_TIMERS + int addTime = GetTime(startTime); + if (addTime > 50) { + gi.Printf(S_COLOR_RED "ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, + vtos(NPC->currentOrigin), NPC->s.weapon, addTime); } AITime += addTime; -#endif// AI_TIMERS - } - else - { - VectorCopy( oldMoveDir, self->client->ps.moveDir ); - //or use client->pers.lastCommand? +#endif // AI_TIMERS + } else { + VectorCopy(oldMoveDir, self->client->ps.moveDir); + // or use client->pers.lastCommand? NPCInfo->last_ucmd.serverTime = level.time - 50; - if ( !NPC->next_roff_time || NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - //FIXME: firing angles (no aim offset) or regular angles? + if (!NPC->next_roff_time || NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + // FIXME: firing angles (no aim offset) or regular angles? NPC_UpdateAngles(qtrue, qtrue); - memcpy( &ucmd, &NPCInfo->last_ucmd, sizeof( usercmd_t ) ); + memcpy(&ucmd, &NPCInfo->last_ucmd, sizeof(usercmd_t)); ClientThink(NPC->s.number, &ucmd); - } - else - { + } else { NPC_ApplyRoff(); } - VectorCopy(self->s.origin, self->s.origin2 ); + VectorCopy(self->s.origin, self->s.origin2); } - //must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands - if( self->taskManager && !stop_icarus ) - { + // must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands + if (self->taskManager && !stop_icarus) { self->taskManager->Update(); } } -void NPC_InitAI ( void ) -{ - debugNoRoam = gi.cvar ( "d_noroam", "0", CVAR_CHEAT ); - debugNPCAimingBeam = gi.cvar ( "d_npcaiming", "0", CVAR_CHEAT ); - debugBreak = gi.cvar ( "d_break", "0", CVAR_CHEAT ); - - debugNPCAI = gi.cvar ( "d_npcai", "0", CVAR_CHEAT ); - debugNPCFreeze = gi.cvar ( "d_npcfreeze", "0", CVAR_CHEAT); - d_JediAI = gi.cvar ( "d_JediAI", "0", CVAR_CHEAT ); - d_noGroupAI = gi.cvar ( "d_noGroupAI", "0", CVAR_CHEAT ); - d_asynchronousGroupAI = gi.cvar ( "d_asynchronousGroupAI", "1", CVAR_CHEAT ); - d_altRoutes = gi.cvar ( "d_altRoutes", "1", CVAR_CHEAT ); - d_patched = gi.cvar ( "d_patched", "1", CVAR_CHEAT ); - - //0 = never (BORING) - //1 = kyle only - //2 = kyle and last enemy jedi - //3 = kyle and any enemy jedi - //4 = kyle and last enemy in a group - //5 = kyle and any enemy - //6 = also when kyle takes pain or enemy jedi dodges player saber swing or does an acrobatic evasion - d_slowmodeath = gi.cvar ( "d_slowmodeath", "3", CVAR_ARCHIVE );//save this setting - - d_saberCombat = gi.cvar ( "d_saberCombat", "0", CVAR_CHEAT ); +void NPC_InitAI(void) { + debugNoRoam = gi.cvar("d_noroam", "0", CVAR_CHEAT); + debugNPCAimingBeam = gi.cvar("d_npcaiming", "0", CVAR_CHEAT); + debugBreak = gi.cvar("d_break", "0", CVAR_CHEAT); + + debugNPCAI = gi.cvar("d_npcai", "0", CVAR_CHEAT); + debugNPCFreeze = gi.cvar("d_npcfreeze", "0", CVAR_CHEAT); + d_JediAI = gi.cvar("d_JediAI", "0", CVAR_CHEAT); + d_noGroupAI = gi.cvar("d_noGroupAI", "0", CVAR_CHEAT); + d_asynchronousGroupAI = gi.cvar("d_asynchronousGroupAI", "1", CVAR_CHEAT); + d_altRoutes = gi.cvar("d_altRoutes", "1", CVAR_CHEAT); + d_patched = gi.cvar("d_patched", "1", CVAR_CHEAT); + + // 0 = never (BORING) + // 1 = kyle only + // 2 = kyle and last enemy jedi + // 3 = kyle and any enemy jedi + // 4 = kyle and last enemy in a group + // 5 = kyle and any enemy + // 6 = also when kyle takes pain or enemy jedi dodges player saber swing or does an acrobatic evasion + d_slowmodeath = gi.cvar("d_slowmodeath", "3", CVAR_ARCHIVE); // save this setting + + d_saberCombat = gi.cvar("d_saberCombat", "0", CVAR_CHEAT); } /* @@ -2165,12 +1939,9 @@ void NPC_InitAnimTable( void ) (frameLerp of 0 * numFrames of 0 = 0) ================================== */ -void NPC_InitAnimTable( void ) -{ - for ( int i = 0; i < MAX_ANIM_FILES; i++ ) - { - for ( int j = 0; j < MAX_ANIMATIONS; j++ ) - { +void NPC_InitAnimTable(void) { + for (int i = 0; i < MAX_ANIM_FILES; i++) { + for (int j = 0; j < MAX_ANIMATIONS; j++) { level.knownAnimFileSets[i].animations[j].firstFrame = 0; level.knownAnimFileSets[i].animations[j].frameLerp = 100; level.knownAnimFileSets[i].animations[j].initialLerp = 100; @@ -2179,10 +1950,9 @@ void NPC_InitAnimTable( void ) } } -void NPC_InitGame( void ) -{ -// globals.NPCs = (gNPC_t *) gi.TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); - debugNPCName = gi.cvar ( "d_npc", "", 0 ); +void NPC_InitGame(void) { + // globals.NPCs = (gNPC_t *) gi.TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); + debugNPCName = gi.cvar("d_npc", "", 0); NPC_LoadParms(); NPC_InitAI(); NPC_InitAnimTable(); @@ -2195,54 +1965,40 @@ void NPC_InitGame( void ) */ } -void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags) -{ // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players +void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, + int setAnimFlags) { // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players // rename PM_SETAnimFinal to PM_SetAnim and have both NCP and Players call PM_SetAnim - if(ent->client) - {//Players, NPCs - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, 0 ); + if (ent->client) { // Players, NPCs + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim) { + PM_SetTorsoAnimTimer(ent, &ent->client->ps.torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim ) - { - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim) { + PM_SetLegsAnimTimer(ent, &ent->client->ps.legsAnimTimer, 0); } } } - PM_SetAnimFinal(&ent->client->ps.torsoAnim,&ent->client->ps.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->client->ps.torsoAnimTimer,&ent->client->ps.legsAnimTimer,ent); - } - else - {//bodies, etc. - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( ent, &ent->s.torsoAnimTimer, 0 ); + PM_SetAnimFinal(&ent->client->ps.torsoAnim, &ent->client->ps.legsAnim, setAnimParts, anim, setAnimFlags, &ent->client->ps.torsoAnimTimer, + &ent->client->ps.legsAnimTimer, ent); + } else { // bodies, etc. + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim) { + PM_SetTorsoAnimTimer(ent, &ent->s.torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim ) - { - PM_SetLegsAnimTimer( ent, &ent->s.legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim) { + PM_SetLegsAnimTimer(ent, &ent->s.legsAnimTimer, 0); } } } - PM_SetAnimFinal(&ent->s.torsoAnim,&ent->s.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->s.torsoAnimTimer,&ent->s.legsAnimTimer,ent); + PM_SetAnimFinal(&ent->s.torsoAnim, &ent->s.legsAnim, setAnimParts, anim, setAnimFlags, &ent->s.torsoAnimTimer, &ent->s.legsAnimTimer, ent); } } diff --git a/codeJK2/game/NPC_behavior.cpp b/codeJK2/game/NPC_behavior.cpp index 93dd4c08ac..905262e0e6 100644 --- a/codeJK2/game/NPC_behavior.cpp +++ b/codeJK2/game/NPC_behavior.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_behavior.cpp +// NPC_behavior.cpp /* FIXME - MCG: These all need to make use of the snapshots. Write something that can look for only specific @@ -32,108 +32,94 @@ we need it... #include "g_navigator.h" #include "Q3_Interface.h" -extern cvar_t *g_AIsurrender; -extern CNavigator navigator; -extern qboolean showBBoxes; +extern cvar_t *g_AIsurrender; +extern CNavigator navigator; +extern qboolean showBBoxes; static vec3_t NPCDEBUG_BLUE = {0.0, 0.0, 1.0}; -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void NPC_CheckGetNewWeapon( void ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern void NPC_AimAdjust( int change ); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void NPC_CheckGetNewWeapon(void); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern void NPC_AimAdjust(int change); /* void NPC_BSAdvanceFight (void) Advance towards your captureGoal and shoot anyone you can along the way. */ -void NPC_BSAdvanceFight (void) -{//FIXME: IMPLEMENT -//Head to Goal if I can +void NPC_BSAdvanceFight(void) { // FIXME: IMPLEMENT + // Head to Goal if I can - //Make sure we're still headed where we want to capture - if ( NPCInfo->captureGoal ) - {//FIXME: if no captureGoal, what do we do? - //VectorCopy( NPCInfo->captureGoal->currentOrigin, NPCInfo->tempGoal->currentOrigin ); - //NPCInfo->goalEntity = NPCInfo->tempGoal; + // Make sure we're still headed where we want to capture + if (NPCInfo->captureGoal) { // FIXME: if no captureGoal, what do we do? + // VectorCopy( NPCInfo->captureGoal->currentOrigin, NPCInfo->tempGoal->currentOrigin ); + // NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_SetMoveGoal( NPC, NPCInfo->captureGoal->currentOrigin, 16, qtrue ); + NPC_SetMoveGoal(NPC, NPCInfo->captureGoal->currentOrigin, 16, qtrue); -// NAV_ClearLastRoute(NPC); + // NAV_ClearLastRoute(NPC); NPCInfo->goalTime = level.time + 100000; } -// NPC_BSRun(); + // NPC_BSRun(); NPC_CheckEnemy(qtrue, qfalse); - //FIXME: Need melee code - if( NPC->enemy ) - {//See if we can shoot him - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; - qboolean dead_on = qfalse; - float attack_scale = 1.0; - float aim_off; - float max_aim_off = 64; - - //Yaw to enemy + // FIXME: Need melee code + if (NPC->enemy) { // See if we can shoot him + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + qboolean dead_on = qfalse; + float attack_scale = 1.0; + float aim_off; + float max_aim_off = 64; + + // Yaw to enemy VectorMA(NPC->enemy->absmin, 0.5, NPC->enemy->maxs, enemy_org); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); - if(!NPC_EnemyTooFar(NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue)) - { + if (!NPC_EnemyTooFar(NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { attack_ok = qtrue; } - if(attack_ok) - { + if (attack_ok) { NPC_UpdateShootAngles(angleToEnemy, qfalse, qtrue); NPCInfo->enemyLastVisibility = enemyVisibility; - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV);//CHECK_360|//CHECK_PVS| + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV); // CHECK_360|//CHECK_PVS| - if(enemyVisibility == VIS_FOV) - {//He's in our FOV + if (enemyVisibility == VIS_FOV) { // He's in our FOV attack_ok = qtrue; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_head); - if(attack_ok) - { - trace_t tr; - gentity_t *traceEnt; - //are we gonna hit him if we shoot at his center? - gi.trace ( &tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + if (attack_ok) { + trace_t tr; + gentity_t *traceEnt; + // are we gonna hit him if we shoot at his center? + gi.trace(&tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); traceEnt = &g_entities[tr.entityNum]; - if( traceEnt != NPC->enemy && - (!traceEnt || !traceEnt->client || !NPC->client->enemyTeam || NPC->client->enemyTeam != traceEnt->client->playerTeam) ) - {//no, so shoot for the head + if (traceEnt != NPC->enemy && (!traceEnt || !traceEnt->client || !NPC->client->enemyTeam || + NPC->client->enemyTeam != traceEnt->client->playerTeam)) { // no, so shoot for the head attack_scale *= 0.75; - gi.trace ( &tr, muzzle, NULL, NULL, enemy_head, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, muzzle, NULL, NULL, enemy_head, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); traceEnt = &g_entities[tr.entityNum]; } - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -141,87 +127,75 @@ void NPC_BSAdvanceFight (void) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateShootAngles(angleToEnemy, qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - AngleVectors (NPCInfo->shootAngles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + AngleVectors(NPCInfo->shootAngles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_head, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); - } - else + } else attack_ok = qfalse; } -//Don't do this- only for when stationary and trying to shoot an enemy -// else -// NPC->cantHitEnemyCounter++; - } - else - {//FIXME: + // Don't do this- only for when stationary and trying to shoot an enemy + // else + // NPC->cantHitEnemyCounter++; + } else { // FIXME: NPC_UpdateShootAngles(NPC->client->ps.viewangles, qtrue, qtrue); } - if(!ucmd.forwardmove && !ucmd.rightmove) - {//We reached our captureGoal - if(NPC->taskManager) - { - Q3_TaskIDComplete( NPC, TID_BSTATE ); + if (!ucmd.forwardmove && !ucmd.rightmove) { // We reached our captureGoal + if (NPC->taskManager) { + Q3_TaskIDComplete(NPC, TID_BSTATE); } } } -void Disappear(gentity_t *self) -{ -// ClientDisconnect(self); +void Disappear(gentity_t *self) { + // ClientDisconnect(self); self->s.eFlags |= EF_NODRAW; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; } -void MakeOwnerInvis (gentity_t *self); -void BeamOut (gentity_t *self) -{ -// gentity_t *tent = G_Spawn(); +void MakeOwnerInvis(gentity_t *self); +void BeamOut(gentity_t *self) { + // gentity_t *tent = G_Spawn(); -/* - tent->owner = self; - tent->think = MakeOwnerInvis; - tent->nextthink = level.time + 1800; - //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); - tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); -*/ - //fixme: doesn't actually go away! + /* + tent->owner = self; + tent->think = MakeOwnerInvis; + tent->nextthink = level.time + 1800; + //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); + tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); + */ + // fixme: doesn't actually go away! self->nextthink = level.time + 1500; self->e_ThinkFunc = thinkF_Disappear; self->client->squadname = NULL; @@ -229,262 +203,241 @@ void BeamOut (gentity_t *self) self->svFlags |= SVF_BEAMING; } -void NPC_BSCinematic( void ) -{ +void NPC_BSCinematic(void) { - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( UpdateGoal() ) - {//have a goalEntity - //move toward goal, should also face that goal - NPC_MoveToGoal( qtrue ); + if (UpdateGoal()) { // have a goalEntity + // move toward goal, should also face that goal + NPC_MoveToGoal(qtrue); } - if ( NPCInfo->watchTarget ) - {//have an entity which we want to keep facing - //NOTE: this will override any angles set by NPC_MoveToGoal + if (NPCInfo->watchTarget) { // have an entity which we want to keep facing + // NOTE: this will override any angles set by NPC_MoveToGoal vec3_t eyes, viewSpot, viewvec, viewangles; - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); - CalcEntitySpot( NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot ); + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); + CalcEntitySpot(NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot); - VectorSubtract( viewSpot, eyes, viewvec ); + VectorSubtract(viewSpot, eyes, viewvec); - vectoangles( viewvec, viewangles ); + vectoangles(viewvec, viewangles); NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw = viewangles[YAW]; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch = viewangles[PITCH]; } - NPC_UpdateAngles( qtrue, qtrue ); -} - -void NPC_BSWait( void ) -{ - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } +void NPC_BSWait(void) { NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSInvestigate (void) -{ -/* - //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the - //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) - vec3_t invDir, invAngles, spot; - gentity_t *saveGoal; - //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, - //look for enemies, then turn away after your investigate counter was down- - //investigate counter goes up every time you set it... - - if(level.time > NPCInfo->enemyCheckDebounceTime) - { - NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); - NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - {//FIXME: do anger script - NPCInfo->goalEntity = NPC->enemy; -// NAV_ClearLastRoute(NPC); - NPCInfo->behaviorState = BS_RUN_AND_SHOOT; - NPCInfo->tempBehavior = BS_DEFAULT; - NPC_AngerSound(); - return; +void NPC_BSInvestigate(void) { + /* + //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the + //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) + vec3_t invDir, invAngles, spot; + gentity_t *saveGoal; + //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, + //look for enemies, then turn away after your investigate counter was down- + //investigate counter goes up every time you set it... + + if(level.time > NPCInfo->enemyCheckDebounceTime) + { + NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); + NPC_CheckEnemy(qtrue, qfalse); + if(NPC->enemy) + {//FIXME: do anger script + NPCInfo->goalEntity = NPC->enemy; + // NAV_ClearLastRoute(NPC); + NPCInfo->behaviorState = BS_RUN_AND_SHOOT; + NPCInfo->tempBehavior = BS_DEFAULT; + NPC_AngerSound(); + return; + } } - } - - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) - { - VectorCopy(NPCInfo->eventOwner->currentOrigin, NPCInfo->investigateGoal); - } + NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - saveGoal = NPCInfo->goalEntity; - if( level.time > NPCInfo->walkDebounceTime ) - { - vec3_t vec; + if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) + { + VectorCopy(NPCInfo->eventOwner->currentOrigin, NPCInfo->investigateGoal); + } - VectorSubtract(NPCInfo->investigateGoal, NPC->currentOrigin, vec); - vec[2] = 0; - if(VectorLength(vec) > 64) + saveGoal = NPCInfo->goalEntity; + if( level.time > NPCInfo->walkDebounceTime ) { - if(Q_irand(0, 100) < NPCInfo->investigateCount) - {//take a full step - //NPCInfo->walkDebounceTime = level.time + 1400; - //actually finds length of my BOTH_WALK anim - NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + vec3_t vec; + + VectorSubtract(NPCInfo->investigateGoal, NPC->currentOrigin, vec); + vec[2] = 0; + if(VectorLength(vec) > 64) + { + if(Q_irand(0, 100) < NPCInfo->investigateCount) + {//take a full step + //NPCInfo->walkDebounceTime = level.time + 1400; + //actually finds length of my BOTH_WALK anim + NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + } } } - } - if( level.time < NPCInfo->walkDebounceTime ) - {//walk toward investigateGoal + if( level.time < NPCInfo->walkDebounceTime ) + {//walk toward investigateGoal - /* - NPCInfo->goalEntity = NPCInfo->tempGoal; -// NAV_ClearLastRoute(NPC); - VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->currentOrigin); - */ + /* + NPCInfo->goalEntity = NPCInfo->tempGoal; + // NAV_ClearLastRoute(NPC); + VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->currentOrigin); + */ -/* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); + /* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal( qtrue ); - //FIXME: walk2? - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); + //FIXME: walk2? + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); - ucmd.buttons |= BUTTON_WALKING; - } - else - { + ucmd.buttons |= BUTTON_WALKING; + } + else + { - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - if(NPCInfo->hlookCount > 30) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->hlookCount > 30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount < -30) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->hlookCount < -30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount == 0) - { - NPCInfo->hlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 7) - { - if(NPCInfo->hlookCount > 0) + else if(NPCInfo->hlookCount == 0) { - NPCInfo->hlookCount++; + NPCInfo->hlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 7) { - NPCInfo->hlookCount--; + if(NPCInfo->hlookCount > 0) + { + NPCInfo->hlookCount++; + } + else//lookCount < 0 + { + NPCInfo->hlookCount--; + } } - } - if(NPCInfo->vlookCount >= 15) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->vlookCount >= 15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount <= -15) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->vlookCount <= -15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount == 0) - { - NPCInfo->vlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 8) - { - if(NPCInfo->vlookCount > 0) + else if(NPCInfo->vlookCount == 0) { - NPCInfo->vlookCount++; + NPCInfo->vlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 8) { - NPCInfo->vlookCount--; + if(NPCInfo->vlookCount > 0) + { + NPCInfo->vlookCount++; + } + else//lookCount < 0 + { + NPCInfo->vlookCount--; + } } - } - //turn toward investigateGoal - CalcEntitySpot( NPC, SPOT_HEAD, spot ); - VectorSubtract(NPCInfo->investigateGoal, spot, invDir); - VectorNormalize(invDir); - vectoangles(invDir, invAngles); - NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); - NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); - } + //turn toward investigateGoal + CalcEntitySpot( NPC, SPOT_HEAD, spot ); + VectorSubtract(NPCInfo->investigateGoal, spot, invDir); + VectorNormalize(invDir); + vectoangles(invDir, invAngles); + NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); + NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); + } - NPC_UpdateAngles(qtrue, qtrue); + NPC_UpdateAngles(qtrue, qtrue); - NPCInfo->goalEntity = saveGoal; -// NAV_ClearLastRoute(NPC); + NPCInfo->goalEntity = saveGoal; + // NAV_ClearLastRoute(NPC); - if(level.time > NPCInfo->investigateDebounceTime) - { - NPCInfo->tempBehavior = BS_DEFAULT; - } + if(level.time > NPCInfo->investigateDebounceTime) + { + NPCInfo->tempBehavior = BS_DEFAULT; + } - NPC_CheckSoundEvents(); - */ + NPC_CheckSoundEvents(); + */ } -qboolean NPC_CheckInvestigate( int alertEventNum ) -{ - gentity_t *owner = level.alertEvents[alertEventNum].owner; - int invAdd = level.alertEvents[alertEventNum].level; - vec3_t soundPos; - float soundRad = level.alertEvents[alertEventNum].radius; - float earshot = NPCInfo->stats.earshot; +qboolean NPC_CheckInvestigate(int alertEventNum) { + gentity_t *owner = level.alertEvents[alertEventNum].owner; + int invAdd = level.alertEvents[alertEventNum].level; + vec3_t soundPos; + float soundRad = level.alertEvents[alertEventNum].radius; + float earshot = NPCInfo->stats.earshot; - VectorCopy( level.alertEvents[alertEventNum].position, soundPos ); + VectorCopy(level.alertEvents[alertEventNum].position, soundPos); - //NOTE: Trying to preserve previous investigation behavior - if ( !owner ) - { + // NOTE: Trying to preserve previous investigation behavior + if (!owner) { return qfalse; } - if ( owner->s.eType != ET_PLAYER && owner == NPCInfo->goalEntity ) - { + if (owner->s.eType != ET_PLAYER && owner == NPCInfo->goalEntity) { return qfalse; } - if ( owner->s.eFlags & EF_NODRAW ) - { + if (owner->s.eFlags & EF_NODRAW) { return qfalse; } - if ( owner->flags & FL_NOTARGET ) - { + if (owner->flags & FL_NOTARGET) { return qfalse; } - if ( soundRad < earshot ) - { + if (soundRad < earshot) { return qfalse; } - //if(!gi.inPVSIgnorePortals(ent->currentOrigin, NPC->currentOrigin))//should we be able to hear through areaportals? - if ( !gi.inPVS( soundPos, NPC->currentOrigin ) ) - {//can hear through doors? + // if(!gi.inPVSIgnorePortals(ent->currentOrigin, NPC->currentOrigin))//should we be able to hear through areaportals? + if (!gi.inPVS(soundPos, NPC->currentOrigin)) { // can hear through doors? return qfalse; } - if ( owner->client && owner->client->playerTeam && NPC->client->playerTeam && owner->client->playerTeam != NPC->client->playerTeam ) - { - if( (float)NPCInfo->investigateCount >= (NPCInfo->stats.vigilance*200) && owner ) - {//If investigateCount == 10, just take it as enemy and go - if ( ValidEnemy( owner ) ) - {//FIXME: run angerscript - G_SetEnemy( NPC, owner ); + if (owner->client && owner->client->playerTeam && NPC->client->playerTeam && owner->client->playerTeam != NPC->client->playerTeam) { + if ((float)NPCInfo->investigateCount >= (NPCInfo->stats.vigilance * 200) && owner) { // If investigateCount == 10, just take it as enemy and go + if (ValidEnemy(owner)) { // FIXME: run angerscript + G_SetEnemy(NPC, owner); NPCInfo->goalEntity = NPC->enemy; NPCInfo->goalRadius = 12; NPCInfo->behaviorState = BS_HUNT_AND_KILL; return qtrue; } - } - else - { + } else { NPCInfo->investigateCount += invAdd; } - //run awakescript + // run awakescript G_ActivateBehavior(NPC, BSET_AWAKE); /* @@ -494,16 +447,13 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) } */ - //NPCInfo->hlookCount = NPCInfo->vlookCount = 0; + // NPCInfo->hlookCount = NPCInfo->vlookCount = 0; NPCInfo->eventOwner = owner; - VectorCopy( soundPos, NPCInfo->investigateGoal ); - if ( NPCInfo->investigateCount > 20 ) - { + VectorCopy(soundPos, NPCInfo->investigateGoal); + if (NPCInfo->investigateCount > 20) { NPCInfo->investigateDebounceTime = level.time + 10000; - } - else - { - NPCInfo->investigateDebounceTime = level.time + (NPCInfo->investigateCount*500); + } else { + NPCInfo->investigateDebounceTime = level.time + (NPCInfo->investigateCount * 500); } NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; @@ -512,17 +462,14 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) return qfalse; } - /* void NPC_BSSleep( void ) */ -void NPC_BSSleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qfalse ); +void NPC_BSSleep(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qfalse); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { G_ActivateBehavior(NPC, BSET_AWAKE); return; } @@ -539,156 +486,119 @@ void NPC_BSSleep( void ) */ } -extern qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ); -void NPC_BSFollowLeader (void) -{ - vec3_t vec; - float leaderDist; - visibility_t leaderVis; - int curAnim; +extern qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset); +void NPC_BSFollowLeader(void) { + vec3_t vec; + float leaderDist; + visibility_t leaderVis; + int curAnim; - if ( !NPC->client->leader ) - {//ok, stand guard until we find an enemy - if( NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { + if (!NPC->client->leader) { // ok, stand guard until we find an enemy + if (NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } return; } - if ( !NPC->enemy ) - {//no enemy, find one - //don't find new enemy if this is tempbehav - NPC_CheckEnemy( (qboolean)(NPCInfo->confusionTime < level.time), qfalse ); - if ( NPC->enemy ) - {//just found one - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); - } - else - { - if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int eventID = NPC_CheckAlertEvents( qtrue, qtrue ); - if ( level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { + if (!NPC->enemy) { // no enemy, find one + // don't find new enemy if this is tempbehav + NPC_CheckEnemy((qboolean)(NPCInfo->confusionTime < level.time), qfalse); + if (NPC->enemy) { // just found one + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); + } else { + if (!(NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int eventID = NPC_CheckAlertEvents(qtrue, qtrue); + if (level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam ) - {//not an enemy - } - else - { - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - G_SetEnemy( NPC, level.alertEvents[eventID].owner ); - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPC->client->enemyTeam) { // not an enemy + } else { + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for + // him? Or just let combat AI handle this... (act as if you lost him) + G_SetEnemy(NPC, level.alertEvents[eventID].owner); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 1000 ) ); + TIMER_Set(NPC, "attackDelay", Q_irand(500, 1000)); } } - } } - if ( !NPC->enemy ) - { - if ( NPC->client->leader - && NPC->client->leader->enemy - && NPC->client->leader->enemy != NPC - && ( (NPC->client->leader->enemy->client&&NPC->client->leader->enemy->client->playerTeam==NPC->client->enemyTeam) - ||(NPC->client->leader->enemy->svFlags&SVF_NONNPC_ENEMY&&NPC->client->leader->enemy->noDamageTeam==NPC->client->enemyTeam) ) - && NPC->client->leader->enemy->health > 0 ) - { - G_SetEnemy( NPC, NPC->client->leader->enemy ); - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (!NPC->enemy) { + if (NPC->client->leader && NPC->client->leader->enemy && NPC->client->leader->enemy != NPC && + ((NPC->client->leader->enemy->client && NPC->client->leader->enemy->client->playerTeam == NPC->client->enemyTeam) || + (NPC->client->leader->enemy->svFlags & SVF_NONNPC_ENEMY && NPC->client->leader->enemy->noDamageTeam == NPC->client->enemyTeam)) && + NPC->client->leader->enemy->health > 0) { + G_SetEnemy(NPC, NPC->client->leader->enemy); + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCInfo->enemyLastSeenTime = level.time; } } - } - else - { - if ( NPC->enemy->health <= 0 || (NPC->enemy->flags&FL_NOTARGET) ) - { - G_ClearEnemy( NPC ); - if ( NPCInfo->enemyCheckDebounceTime > level.time + 1000 ) - { - NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 2000 ); + } else { + if (NPC->enemy->health <= 0 || (NPC->enemy->flags & FL_NOTARGET)) { + G_ClearEnemy(NPC); + if (NPCInfo->enemyCheckDebounceTime > level.time + 1000) { + NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 2000); } - } - else if ( NPC->client->ps.weapon && NPCInfo->enemyCheckDebounceTime < level.time ) - { - NPC_CheckEnemy( - (qboolean)((NPCInfo->confusionTime < level.time) || (NPCInfo->tempBehavior != BS_FOLLOW_LEADER)), - qfalse);//don't find new enemy if this is tempbehav + } else if (NPC->client->ps.weapon && NPCInfo->enemyCheckDebounceTime < level.time) { + NPC_CheckEnemy((qboolean)((NPCInfo->confusionTime < level.time) || (NPCInfo->tempBehavior != BS_FOLLOW_LEADER)), + qfalse); // don't find new enemy if this is tempbehav } } - if ( NPC->enemy && NPC->client->ps.weapon ) - {//If have an enemy, face him and fire - if ( NPC->client->ps.weapon == WP_SABER )//|| NPCInfo->confusionTime>level.time ) - {//lightsaber user or charmed enemy - if ( NPCInfo->tempBehavior != BS_FOLLOW_LEADER ) - {//not already in a temp bState - //go after the guy + if (NPC->enemy && NPC->client->ps.weapon) { // If have an enemy, face him and fire + if (NPC->client->ps.weapon == WP_SABER) //|| NPCInfo->confusionTime>level.time ) + { // lightsaber user or charmed enemy + if (NPCInfo->tempBehavior != BS_FOLLOW_LEADER) { // not already in a temp bState + // go after the guy NPCInfo->tempBehavior = BS_HUNT_AND_KILL; NPC_UpdateAngles(qtrue, qtrue); return; } } - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|CHECK_PVS| - if ( enemyVisibility > VIS_PVS ) - {//face - vec3_t enemy_org, muzzle, delta, angleToEnemy; - //float distanceToEnemy; + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|CHECK_PVS| + if (enemyVisibility > VIS_PVS) { // face + vec3_t enemy_org, muzzle, delta, angleToEnemy; + // float distanceToEnemy; - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - VectorSubtract( enemy_org, muzzle, delta); - vectoangles( delta, angleToEnemy ); - //distanceToEnemy = VectorNormalize( delta ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); + // distanceToEnemy = VectorNormalize( delta ); NPCInfo->desiredYaw = angleToEnemy[YAW]; NPCInfo->desiredPitch = angleToEnemy[PITCH]; - NPC_UpdateFiringAngles( qtrue, qtrue ); - - if ( enemyVisibility >= VIS_SHOOT ) - {//shoot - NPC_AimAdjust( 2 ); - if ( NPC_GetHFOVPercentage( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.hfov ) > 0.6f - && NPC_GetHFOVPercentage( NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.vfov ) > 0.5f ) - {//actually withing our front cone - WeaponThink( qtrue ); + NPC_UpdateFiringAngles(qtrue, qtrue); + + if (enemyVisibility >= VIS_SHOOT) { // shoot + NPC_AimAdjust(2); + if (NPC_GetHFOVPercentage(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.hfov) > 0.6f && + NPC_GetHFOVPercentage(NPC->enemy->currentOrigin, NPC->currentOrigin, NPC->client->ps.viewangles, NPCInfo->stats.vfov) > + 0.5f) { // actually withing our front cone + WeaponThink(qtrue); } - } - else - { - NPC_AimAdjust( 1 ); + } else { + NPC_AimAdjust(1); } - //NPC_CheckCanAttack(1.0, qfalse); - } - else - { - NPC_AimAdjust( -1 ); + // NPC_CheckCanAttack(1.0, qfalse); + } else { + NPC_AimAdjust(-1); } - } - else - {//FIXME: combine with vector calc below - vec3_t head, leaderHead, delta, angleToLeader; - - CalcEntitySpot( NPC->client->leader, SPOT_HEAD, leaderHead ); - CalcEntitySpot( NPC, SPOT_HEAD, head ); - VectorSubtract (leaderHead, head, delta); - vectoangles ( delta, angleToLeader ); + } else { // FIXME: combine with vector calc below + vec3_t head, leaderHead, delta, angleToLeader; + + CalcEntitySpot(NPC->client->leader, SPOT_HEAD, leaderHead); + CalcEntitySpot(NPC, SPOT_HEAD, head); + VectorSubtract(leaderHead, head, delta); + vectoangles(delta, angleToLeader); VectorNormalize(delta); NPC->NPC->desiredYaw = angleToLeader[YAW]; NPC->NPC->desiredPitch = angleToLeader[PITCH]; @@ -696,126 +606,108 @@ void NPC_BSFollowLeader (void) NPC_UpdateAngles(qtrue, qtrue); } - //leader visible? - leaderVis = NPC_CheckVisibility( NPC->client->leader, CHECK_PVS|CHECK_360|CHECK_SHOOT );// ent->e_UseFunc = useF_NULL; - + // leader visible? + leaderVis = NPC_CheckVisibility(NPC->client->leader, CHECK_PVS | CHECK_360 | CHECK_SHOOT); // ent->e_UseFunc = useF_NULL; - //Follow leader, stay within visibility and a certain distance, maintain a distance from. + // Follow leader, stay within visibility and a certain distance, maintain a distance from. curAnim = NPC->client->ps.legsAnim; - if ( curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 ) - {//Don't move toward leader if we're in a full-body attack anim - //FIXME, use IdealDistance to determine if we need to close distance - float followDist = 96.0f;//FIXME: If there are enmies, make this larger? - float backupdist, walkdist, minrundist; + if (curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && + curAnim != BOTH_MELEE2) { // Don't move toward leader if we're in a full-body attack anim + // FIXME, use IdealDistance to determine if we need to close distance + float followDist = 96.0f; // FIXME: If there are enmies, make this larger? + float backupdist, walkdist, minrundist; - if ( NPCInfo->followDist ) - { + if (NPCInfo->followDist) { followDist = NPCInfo->followDist; } - backupdist = followDist/2.0f; - walkdist = followDist*0.83; - minrundist = followDist*1.33; + backupdist = followDist / 2.0f; + walkdist = followDist * 0.83; + minrundist = followDist * 1.33; VectorSubtract(NPC->client->leader->currentOrigin, NPC->currentOrigin, vec); - leaderDist = VectorLength( vec );//FIXME: make this just nav distance? - //never get within their radius horizontally + leaderDist = VectorLength(vec); // FIXME: make this just nav distance? + // never get within their radius horizontally vec[2] = 0; - float leaderHDist = VectorLength( vec ); - if( leaderHDist > backupdist && (leaderVis != VIS_SHOOT || leaderDist > walkdist) ) - {//We should close in? + float leaderHDist = VectorLength(vec); + if (leaderHDist > backupdist && (leaderVis != VIS_SHOOT || leaderDist > walkdist)) { // We should close in? NPCInfo->goalEntity = NPC->client->leader; NPC_SlideMoveToGoal(); - if ( leaderVis == VIS_SHOOT && leaderDist < minrundist ) - { + if (leaderVis == VIS_SHOOT && leaderDist < minrundist) { ucmd.buttons |= BUTTON_WALKING; } - } - else if ( leaderDist < backupdist ) - {//We should back off? + } else if (leaderDist < backupdist) { // We should back off? NPCInfo->goalEntity = NPC->client->leader; NPC_SlideMoveToGoal(); - //reversing direction + // reversing direction ucmd.forwardmove = -ucmd.forwardmove; - ucmd.rightmove = -ucmd.rightmove; - VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); - }//otherwise, stay where we are - //check for do not enter and stop if there's one there... - if ( ucmd.forwardmove || ucmd.rightmove || VectorCompare( vec3_origin, NPC->client->ps.moveDir ) ) - { - NPC_MoveDirClear( ucmd.forwardmove, ucmd.rightmove, qtrue ); + ucmd.rightmove = -ucmd.rightmove; + VectorScale(NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir); + } // otherwise, stay where we are + // check for do not enter and stop if there's one there... + if (ucmd.forwardmove || ucmd.rightmove || VectorCompare(vec3_origin, NPC->client->ps.moveDir)) { + NPC_MoveDirClear(ucmd.forwardmove, ucmd.rightmove, qtrue); } } } -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f -void NPC_BSJump (void) -{ - vec3_t dir, angles, p1, p2, apex; - float time, height, forward, z, xy, dist, yawError, apexHeight; - - if( !NPCInfo->goalEntity ) - {//Should have task completed the navgoal +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f +void NPC_BSJump(void) { + vec3_t dir, angles, p1, p2, apex; + float time, height, forward, z, xy, dist, yawError, apexHeight; + + if (!NPCInfo->goalEntity) { // Should have task completed the navgoal return; } - if ( NPCInfo->jumpState != JS_JUMPING && NPCInfo->jumpState != JS_LANDING ) - { - //Face navgoal + if (NPCInfo->jumpState != JS_JUMPING && NPCInfo->jumpState != JS_LANDING) { + // Face navgoal VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); vectoangles(dir, angles); NPCInfo->desiredPitch = NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); NPCInfo->desiredYaw = NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); } - NPC_UpdateAngles ( qtrue, qtrue ); - yawError = AngleDelta ( NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw ); - //We don't really care about pitch here + NPC_UpdateAngles(qtrue, qtrue); + yawError = AngleDelta(NPC->client->ps.viewangles[YAW], NPCInfo->desiredYaw); + // We don't really care about pitch here - switch ( NPCInfo->jumpState ) - { + switch (NPCInfo->jumpState) { case JS_FACING: - if ( yawError < MIN_ANGLE_ERROR ) - {//Facing it, Start crouching - NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (yawError < MIN_ANGLE_ERROR) { // Facing it, Start crouching + NPC_SetAnim(NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCInfo->jumpState = JS_CROUCHING; } break; case JS_CROUCHING: - if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing crouching anim + if (NPC->client->ps.legsAnimTimer > 0) { // Still playing crouching anim return; } - //Create a parabola + // Create a parabola - if ( NPC->currentOrigin[2] > NPCInfo->goalEntity->currentOrigin[2] ) - { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( NPCInfo->goalEntity->currentOrigin, p2 ); - } - else if ( NPC->currentOrigin[2] < NPCInfo->goalEntity->currentOrigin[2] ) - { - VectorCopy( NPCInfo->goalEntity->currentOrigin, p1 ); - VectorCopy( NPC->currentOrigin, p2 ); - } - else - { - VectorCopy( NPC->currentOrigin, p1 ); - VectorCopy( NPCInfo->goalEntity->currentOrigin, p2 ); + if (NPC->currentOrigin[2] > NPCInfo->goalEntity->currentOrigin[2]) { + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(NPCInfo->goalEntity->currentOrigin, p2); + } else if (NPC->currentOrigin[2] < NPCInfo->goalEntity->currentOrigin[2]) { + VectorCopy(NPCInfo->goalEntity->currentOrigin, p1); + VectorCopy(NPC->currentOrigin, p2); + } else { + VectorCopy(NPC->currentOrigin, p1); + VectorCopy(NPCInfo->goalEntity->currentOrigin, p2); } - //z = xy*xy - VectorSubtract( p2, p1, dir ); + // z = xy*xy + VectorSubtract(p2, p1, dir); dir[2] = 0; - //Get xy and z diffs - xy = VectorNormalize( dir ); + // Get xy and z diffs + xy = VectorNormalize(dir); z = p1[2] - p2[2]; - apexHeight = APEX_HEIGHT/2; + apexHeight = APEX_HEIGHT / 2; /* //Determine most desirable apex height apexHeight = (APEX_HEIGHT * PARA_WIDTH/xy) + (APEX_HEIGHT * z/128); @@ -829,97 +721,86 @@ void NPC_BSJump (void) } */ - //FIXME: length of xy will change curve of parabola, need to account for this - //somewhere... PARA_WIDTH + // FIXME: length of xy will change curve of parabola, need to account for this + // somewhere... PARA_WIDTH z = (sqrt(apexHeight + z) - sqrt(apexHeight)); assert(z >= 0); -// gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); + // gi.Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); xy -= z; xy *= 0.5; assert(xy > 0); - VectorMA( p1, xy, dir, apex ); + VectorMA(p1, xy, dir, apex); apex[2] += apexHeight; VectorCopy(apex, NPC->pos1); - //Now we have the apex, aim for it + // Now we have the apex, aim for it height = apex[2] - NPC->currentOrigin[2]; - time = sqrt( height / ( .5 * NPC->client->ps.gravity ) ); - if ( !time ) - { -// gi.Printf("ERROR no time in jump\n"); + time = sqrt(height / (.5 * NPC->client->ps.gravity)); + if (!time) { + // gi.Printf("ERROR no time in jump\n"); return; } // set s.origin2 to the push velocity - VectorSubtract ( apex, NPC->currentOrigin, NPC->client->ps.velocity ); + VectorSubtract(apex, NPC->currentOrigin, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = 0; - dist = VectorNormalize( NPC->client->ps.velocity ); + dist = VectorNormalize(NPC->client->ps.velocity); forward = dist / time; - VectorScale( NPC->client->ps.velocity, forward, NPC->client->ps.velocity ); + VectorScale(NPC->client->ps.velocity, forward, NPC->client->ps.velocity); NPC->client->ps.velocity[2] = time * NPC->client->ps.gravity; -// gi.Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); + // gi.Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); NPC->flags |= FL_NO_KNOCKBACK; NPCInfo->jumpState = JS_JUMPING; - //FIXME: jumpsound? + // FIXME: jumpsound? break; case JS_JUMPING: - if ( showBBoxes ) - { + if (showBBoxes) { VectorAdd(NPC->mins, NPC->pos1, p1); VectorAdd(NPC->maxs, NPC->pos1, p2); - CG_Cube( p1, p2, NPCDEBUG_BLUE, 0.5 ); + CG_Cube(p1, p2, NPCDEBUG_BLUE, 0.5); } - if ( NPC->s.groundEntityNum != ENTITYNUM_NONE) - {//Landed, start landing anim - //FIXME: if the + if (NPC->s.groundEntityNum != ENTITYNUM_NONE) { // Landed, start landing anim + // FIXME: if the VectorClear(NPC->client->ps.velocity); - NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCInfo->jumpState = JS_LANDING; - //FIXME: landsound? - } - else if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing jumping anim - //FIXME: apply jump velocity here, a couple frames after start, not right away + // FIXME: landsound? + } else if (NPC->client->ps.legsAnimTimer > 0) { // Still playing jumping anim + // FIXME: apply jump velocity here, a couple frames after start, not right away return; - } - else - {//still in air, but done with jump anim, play inair anim + } else { // still in air, but done with jump anim, play inair anim NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_OVERRIDE); } break; case JS_LANDING: - if ( NPC->client->ps.legsAnimTimer > 0 ) - {//Still playing landing anim + if (NPC->client->ps.legsAnimTimer > 0) { // Still playing landing anim return; - } - else - { + } else { NPCInfo->jumpState = JS_WAITING; - - //task complete no matter what... + // task complete no matter what... NPC_ClearGoal(); NPCInfo->goalTime = level.time; NPCInfo->aiFlags &= ~NPCAI_MOVING; ucmd.forwardmove = 0; NPC->flags &= ~FL_NO_KNOCKBACK; - //Return that the goal was reached - Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); + // Return that the goal was reached + Q3_TaskIDComplete(NPC, TID_MOVE_NAV); - //Or should we keep jumping until reached goal? + // Or should we keep jumping until reached goal? /* NPCInfo->goalEntity = UpdateGoal(); @@ -929,7 +810,6 @@ void NPC_BSJump (void) Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); } */ - } break; case JS_WAITING: @@ -939,12 +819,11 @@ void NPC_BSJump (void) } } -void NPC_BSRemove (void) -{ - NPC_UpdateAngles ( qtrue, qtrue ); - if( !gi.inPVS( NPC->currentOrigin, g_entities[0].currentOrigin ) )//FIXME: use cg.vieworg? +void NPC_BSRemove(void) { + NPC_UpdateAngles(qtrue, qtrue); + if (!gi.inPVS(NPC->currentOrigin, g_entities[0].currentOrigin)) // FIXME: use cg.vieworg? { - G_UseTargets2( NPC, NPC, NPC->target3 ); + G_UseTargets2(NPC, NPC, NPC->target3); NPC->s.eFlags |= EF_NODRAW; NPC->s.eFlags &= ~EF_NPC; NPC->svFlags &= ~SVF_NPC; @@ -953,52 +832,44 @@ void NPC_BSRemove (void) NPC->health = 0; NPC->targetname = NULL; - //Disappear in half a second + // Disappear in half a second NPC->e_ThinkFunc = thinkF_G_FreeEntity; NPC->nextthink = level.time + FRAMETIME; - }//FIXME: else allow for out of FOV??? + } // FIXME: else allow for out of FOV??? } -void NPC_BSSearch (void) -{ +void NPC_BSSearch(void) { NPC_CheckEnemy(qtrue, qfalse); - //Look for enemies, if find one: - if ( NPC->enemy ) - { - if( NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + // Look for enemies, if find one: + if (NPC->enemy) { + if (NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to run and shoot + } else { // if bState, change to run and shoot NPCInfo->behaviorState = BS_HUNT_AND_KILL; NPC_BSRunAndShoot(); } return; } - //FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must - //want us to do something else? If tempBehavior, just default, else set - //to run and shoot...? + // FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must + // want us to do something else? If tempBehavior, just default, else set + // to run and shoot...? - //FIXME: Reimplement + // FIXME: Reimplement - if ( !NPCInfo->investigateDebounceTime ) - {//On our way to a tempGoal - float minGoalReachedDistSquared = 32*32; - vec3_t vec; + if (!NPCInfo->investigateDebounceTime) { // On our way to a tempGoal + float minGoalReachedDistSquared = 32 * 32; + vec3_t vec; - //Keep moving toward our tempGoal + // Keep moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); - if ( vec[2] < 24 ) - { + VectorSubtract(NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); + if (vec[2] < 24) { vec[2] = 0; } - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { /* //FIXME: can't get the radius... float wpRadSq = waypoints[NPCInfo->tempGoal->waypoint].radius * waypoints[NPCInfo->tempGoal->waypoint].radius; @@ -1008,110 +879,87 @@ void NPC_BSSearch (void) } */ - minGoalReachedDistSquared = 32*32;//12*12; + minGoalReachedDistSquared = 32 * 32; // 12*12; } - if ( VectorLengthSquared( vec ) < minGoalReachedDistSquared ) - { - //Close enough, just got there - NPC->waypoint = NAV_FindClosestWaypointForEnt( NPC, WAYPOINT_NONE ); + if (VectorLengthSquared(vec) < minGoalReachedDistSquared) { + // Close enough, just got there + NPC->waypoint = NAV_FindClosestWaypointForEnt(NPC, WAYPOINT_NONE); - if ( ( NPCInfo->homeWp == WAYPOINT_NONE ) || ( NPC->waypoint == WAYPOINT_NONE ) ) - { - //Heading for or at an invalid waypoint, get out of this bState - if( NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + if ((NPCInfo->homeWp == WAYPOINT_NONE) || (NPC->waypoint == WAYPOINT_NONE)) { + // Heading for or at an invalid waypoint, get out of this bState + if (NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to stand guard + } else { // if bState, change to stand guard NPCInfo->behaviorState = BS_STAND_GUARD; NPC_BSRunAndShoot(); } return; } - if ( NPC->waypoint == NPCInfo->homeWp ) - { - //Just Reached our homeWp, if this is the first time, run your lostenemyscript - if ( NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP ) - { + if (NPC->waypoint == NPCInfo->homeWp) { + // Just Reached our homeWp, if this is the first time, run your lostenemyscript + if (NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP) { NPCInfo->aiFlags &= ~NPCAI_ENROUTE_TO_HOMEWP; - G_ActivateBehavior( NPC, BSET_LOSTENEMY ); + G_ActivateBehavior(NPC, BSET_LOSTENEMY); } - } - //gi.Printf("Got there.\n"); - //gi.Printf("Looking..."); - if( !Q_irand(0, 1) ) - { + // gi.Printf("Got there.\n"); + // gi.Printf("Looking..."); + if (!Q_irand(0, 1)) { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); - } - else - { + } else { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); } NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); + } else { + NPC_MoveToGoal(qtrue); } - else - { - NPC_MoveToGoal( qtrue ); - } - } - else - { - //We're there - if ( NPCInfo->investigateDebounceTime > level.time ) - { - //Still waiting around for a bit - //Turn angles every now and then to look around - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { - if ( !Q_irand( 0, 30 ) ) - { - int numEdges = navigator.GetNodeNumEdges( NPCInfo->tempGoal->waypoint ); + } else { + // We're there + if (NPCInfo->investigateDebounceTime > level.time) { + // Still waiting around for a bit + // Turn angles every now and then to look around + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { + if (!Q_irand(0, 30)) { + int numEdges = navigator.GetNodeNumEdges(NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - vec3_t branchPos, lookDir; + vec3_t branchPos, lookDir; - int nextWp = navigator.GetNodeEdge( NPCInfo->tempGoal->waypoint, branchNum ); - navigator.GetNodePosition( nextWp, branchPos ); + int nextWp = navigator.GetNodeEdge(NPCInfo->tempGoal->waypoint, branchNum); + navigator.GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPCInfo->tempGoal->currentOrigin, lookDir ); - NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); + VectorSubtract(branchPos, NPCInfo->tempGoal->currentOrigin, lookDir); + NPCInfo->desiredYaw = AngleNormalize360(vectoyaw(lookDir) + Q_flrand(-45, 45)); } - //pick an angle +-45 degrees off of the dir of a random branch - //from NPCInfo->tempGoal->waypoint - //int branch = Q_irand( 0, (waypoints[NPCInfo->tempGoal->waypoint].numNeighbors - 1) ); - //int nextWp = waypoints[NPCInfo->tempGoal->waypoint].nextWaypoint[branch][NPCInfo->stats.moveType]; - //vec3_t lookDir; + // pick an angle +-45 degrees off of the dir of a random branch + // from NPCInfo->tempGoal->waypoint + // int branch = Q_irand( 0, (waypoints[NPCInfo->tempGoal->waypoint].numNeighbors - 1) ); + // int nextWp = waypoints[NPCInfo->tempGoal->waypoint].nextWaypoint[branch][NPCInfo->stats.moveType]; + // vec3_t lookDir; - //VectorSubtract( waypoints[nextWp].origin, NPCInfo->tempGoal->currentOrigin, lookDir ); - //Look in that direction +- 45 degrees - //NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); + // VectorSubtract( waypoints[nextWp].origin, NPCInfo->tempGoal->currentOrigin, lookDir ); + // Look in that direction +- 45 degrees + // NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); } } - //gi.Printf("."); - } - else - {//Just finished waiting - NPC->waypoint = NAV_FindClosestWaypointForEnt( NPC, WAYPOINT_NONE ); + // gi.Printf("."); + } else { // Just finished waiting + NPC->waypoint = NAV_FindClosestWaypointForEnt(NPC, WAYPOINT_NONE); - if ( NPC->waypoint == NPCInfo->homeWp ) - { - int numEdges = navigator.GetNodeNumEdges( NPCInfo->tempGoal->waypoint ); + if (NPC->waypoint == NPCInfo->homeWp) { + int numEdges = navigator.GetNodeNumEdges(NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - int nextWp = navigator.GetNodeEdge( NPCInfo->homeWp, branchNum ); - navigator.GetNodePosition( nextWp, NPCInfo->tempGoal->currentOrigin ); + int nextWp = navigator.GetNodeEdge(NPCInfo->homeWp, branchNum); + navigator.GetNodePosition(nextWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = nextWp; } @@ -1124,10 +972,8 @@ void NPC_BSSearch (void) NPCInfo->tempGoal->waypoint = nextWp; //gi.Printf("\nHeading for wp %d...\n", waypoints[NPCInfo->homeWp].nextWaypoint[branch][NPCInfo->stats.moveType]); */ - } - else - {//At a branch, so return home - navigator.GetNodePosition( NPCInfo->homeWp, NPCInfo->tempGoal->currentOrigin ); + } else { // At a branch, so return home + navigator.GetNodePosition(NPCInfo->homeWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = NPCInfo->homeWp; /* VectorCopy( waypoints[NPCInfo->homeWp].origin, NPCInfo->tempGoal->currentOrigin ); @@ -1137,13 +983,13 @@ void NPC_BSSearch (void) } NPCInfo->investigateDebounceTime = 0; - //Start moving toward our tempGoal + // Start moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -1152,16 +998,15 @@ NPC_BSSearchStart ------------------------- */ -void NPC_BSSearchStart( int homeWp, bState_t bState ) -{ - //FIXME: Reimplement +void NPC_BSSearchStart(int homeWp, bState_t bState) { + // FIXME: Reimplement NPCInfo->homeWp = homeWp; NPCInfo->tempBehavior = bState; NPCInfo->aiFlags |= NPCAI_ENROUTE_TO_HOMEWP; NPCInfo->investigateDebounceTime = 0; - navigator.GetNodePosition( homeWp, NPCInfo->tempGoal->currentOrigin ); + navigator.GetNodePosition(homeWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = homeWp; - //gi.Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); + // gi.Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); } /* @@ -1172,21 +1017,19 @@ NPC_BSNoClip ------------------------- */ -void NPC_BSNoClip ( void ) -{ - if ( UpdateGoal() ) - { - vec3_t dir, forward, right, angles, up = {0, 0, 1}; - float fDot, rDot, uDot; +void NPC_BSNoClip(void) { + if (UpdateGoal()) { + vec3_t dir, forward, right, angles, up = {0, 0, 1}; + float fDot, rDot, uDot; - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); NPCInfo->desiredYaw = angles[YAW]; - AngleVectors( NPC->currentAngles, forward, right, NULL ); + AngleVectors(NPC->currentAngles, forward, right, NULL); - VectorNormalize( dir ); + VectorNormalize(dir); fDot = DotProduct(forward, dir) * 127; rDot = DotProduct(right, dir) * 127; @@ -1195,109 +1038,88 @@ void NPC_BSNoClip ( void ) ucmd.forwardmove = floor(fDot); ucmd.rightmove = floor(rDot); ucmd.upmove = floor(uDot); - } - else - { - //Cut velocity? - VectorClear( NPC->client->ps.velocity ); + } else { + // Cut velocity? + VectorClear(NPC->client->ps.velocity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSWander (void) -{//FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? - if ( !NPCInfo->investigateDebounceTime ) - {//Starting out - float minGoalReachedDistSquared = 64;//32*32; - vec3_t vec; +void NPC_BSWander(void) { // FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? + if (!NPCInfo->investigateDebounceTime) { // Starting out + float minGoalReachedDistSquared = 64; // 32*32; + vec3_t vec; - //Keep moving toward our tempGoal + // Keep moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); + VectorSubtract(NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { minGoalReachedDistSquared = 64; } - if ( VectorLengthSquared( vec ) < minGoalReachedDistSquared ) - { - //Close enough, just got there - NPC->waypoint = NAV_FindClosestWaypointForEnt( NPC, WAYPOINT_NONE ); + if (VectorLengthSquared(vec) < minGoalReachedDistSquared) { + // Close enough, just got there + NPC->waypoint = NAV_FindClosestWaypointForEnt(NPC, WAYPOINT_NONE); - if( !Q_irand(0, 1) ) - { + if (!Q_irand(0, 1)) { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); - } - else - { + } else { NPC_SetAnim(NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); } - //Just got here, so Look around for a while + // Just got here, so Look around for a while NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); + } else { + // Keep moving toward goal + NPC_MoveToGoal(qtrue); } - else - { - //Keep moving toward goal - NPC_MoveToGoal( qtrue ); - } - } - else - { - //We're there - if ( NPCInfo->investigateDebounceTime > level.time ) - { - //Still waiting around for a bit - //Turn angles every now and then to look around - if ( NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { - if ( !Q_irand( 0, 30 ) ) - { - int numEdges = navigator.GetNodeNumEdges( NPCInfo->tempGoal->waypoint ); + } else { + // We're there + if (NPCInfo->investigateDebounceTime > level.time) { + // Still waiting around for a bit + // Turn angles every now and then to look around + if (NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { + if (!Q_irand(0, 30)) { + int numEdges = navigator.GetNodeNumEdges(NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - vec3_t branchPos, lookDir; + vec3_t branchPos, lookDir; - int nextWp = navigator.GetNodeEdge( NPCInfo->tempGoal->waypoint, branchNum ); - navigator.GetNodePosition( nextWp, branchPos ); + int nextWp = navigator.GetNodeEdge(NPCInfo->tempGoal->waypoint, branchNum); + navigator.GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPCInfo->tempGoal->currentOrigin, lookDir ); - NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); + VectorSubtract(branchPos, NPCInfo->tempGoal->currentOrigin, lookDir); + NPCInfo->desiredYaw = AngleNormalize360(vectoyaw(lookDir) + Q_flrand(-45, 45)); } } } - } - else - {//Just finished waiting - NPC->waypoint = NAV_FindClosestWaypointForEnt( NPC, WAYPOINT_NONE ); + } else { // Just finished waiting + NPC->waypoint = NAV_FindClosestWaypointForEnt(NPC, WAYPOINT_NONE); - if ( NPC->waypoint != WAYPOINT_NONE ) - { - int numEdges = navigator.GetNodeNumEdges( NPC->waypoint ); + if (NPC->waypoint != WAYPOINT_NONE) { + int numEdges = navigator.GetNodeNumEdges(NPC->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - int nextWp = navigator.GetNodeEdge( NPC->waypoint, branchNum ); - navigator.GetNodePosition( nextWp, NPCInfo->tempGoal->currentOrigin ); + int nextWp = navigator.GetNodeEdge(NPC->waypoint, branchNum); + navigator.GetNodePosition(nextWp, NPCInfo->tempGoal->currentOrigin); NPCInfo->tempGoal->waypoint = nextWp; } NPCInfo->investigateDebounceTime = 0; - //Start moving toward our tempGoal + // Start moving toward our tempGoal NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -1326,124 +1148,90 @@ void NPC_BSFaceLeader (void) NPC_BSFlee ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void WP_DropWeapon( gentity_t *dropper, vec3_t velocity ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void WP_DropWeapon(gentity_t *dropper, vec3_t velocity); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); extern int g_crosshairEntNum; -void NPC_Surrender( void ) -{//FIXME: say "don't shoot!" if we weren't already surrendering - if ( NPC->client->ps.weaponTime || PM_InKnockDown( &NPC->client->ps ) ) - { +void NPC_Surrender(void) { // FIXME: say "don't shoot!" if we weren't already surrendering + if (NPC->client->ps.weaponTime || PM_InKnockDown(&NPC->client->ps)) { return; } - if ( NPC->s.weapon != WP_NONE && - NPC->s.weapon != WP_MELEE && - NPC->s.weapon != WP_SABER ) - { - WP_DropWeapon( NPC, NULL ); + if (NPC->s.weapon != WP_NONE && NPC->s.weapon != WP_MELEE && NPC->s.weapon != WP_SABER) { + WP_DropWeapon(NPC, NULL); } - if ( NPCInfo->surrenderTime < level.time - 5000 ) - {//haven't surrendered for at least 6 seconds, tell them what you're doing - //FIXME: need real dialogue EV_SURRENDER - NPCInfo->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( NPC, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 3000 ); + if (NPCInfo->surrenderTime < level.time - 5000) { // haven't surrendered for at least 6 seconds, tell them what you're doing + // FIXME: need real dialogue EV_SURRENDER + NPCInfo->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(NPC, Q_irand(EV_PUSHED1, EV_PUSHED3), 3000); } - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); + NPC_SetAnim(NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); NPC->client->ps.torsoAnimTimer = 1000; - NPCInfo->surrenderTime = level.time + 1000;//stay surrendered for at least 1 second - //FIXME: while surrendering, make a big sight/sound alert? Or G_AlertTeam? + NPCInfo->surrenderTime = level.time + 1000; // stay surrendered for at least 1 second + // FIXME: while surrendering, make a big sight/sound alert? Or G_AlertTeam? } -qboolean NPC_CheckSurrender( void ) -{ - if ( !g_AIsurrender->integer ) - {//not enabled +qboolean NPC_CheckSurrender(void) { + if (!g_AIsurrender->integer) { // not enabled return qfalse; } - if ( !Q3_TaskIDPending( NPC, TID_MOVE_NAV ) - && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE - && !NPC->client->ps.weaponTime && !PM_InKnockDown( &NPC->client->ps ) - && NPC->enemy && NPC->enemy->client && NPC->enemy->enemy == NPC && NPC->enemy->s.weapon != WP_NONE && NPC->enemy->s.weapon != WP_MELEE - && NPC->enemy->health > 20 && NPC->enemy->painDebounceTime < level.time - 3000 && NPC->enemy->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time - 1000 ) - {//don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the enemy is not mad at me or is hurt or not a threat or busy being attacked - //FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? - if ( NPC->s.weapon != WP_ROCKET_LAUNCHER - && NPC->s.weapon != WP_REPEATER - && NPC->s.weapon != WP_FLECHETTE - && NPC->s.weapon != WP_SABER ) - {//jedi and heavy weapons guys never surrender - //FIXME: rework all this logic into some orderly fashion!!! - if ( NPC->s.weapon != WP_NONE ) - {//they have a weapon so they'd have to drop it to surrender - //don't give up unless low on health - if ( NPC->health > 25 || NPC->health >= NPC->max_health ) - { + if (!Q3_TaskIDPending(NPC, TID_MOVE_NAV) && NPC->client->ps.groundEntityNum != ENTITYNUM_NONE && !NPC->client->ps.weaponTime && + !PM_InKnockDown(&NPC->client->ps) && NPC->enemy && NPC->enemy->client && NPC->enemy->enemy == NPC && NPC->enemy->s.weapon != WP_NONE && + NPC->enemy->s.weapon != WP_MELEE && NPC->enemy->health > 20 && NPC->enemy->painDebounceTime < level.time - 3000 && + NPC->enemy->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < + level.time - 1000) { // don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the + // enemy is not mad at me or is hurt or not a threat or busy being attacked + // FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? + if (NPC->s.weapon != WP_ROCKET_LAUNCHER && NPC->s.weapon != WP_REPEATER && NPC->s.weapon != WP_FLECHETTE && + NPC->s.weapon != WP_SABER) { // jedi and heavy weapons guys never surrender + // FIXME: rework all this logic into some orderly fashion!!! + if (NPC->s.weapon != WP_NONE) { // they have a weapon so they'd have to drop it to surrender + // don't give up unless low on health + if (NPC->health > 25 || NPC->health >= NPC->max_health) { return qfalse; } - if ( g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time ) - {//if he just shot me, always give up - //fall through - } - else - {//don't give up unless facing enemy and he's very close - if ( !InFOV( player, NPC, 60, 30 ) ) - {//I'm not looking at them + if (g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time) { // if he just shot me, always give up + // fall through + } else { // don't give up unless facing enemy and he's very close + if (!InFOV(player, NPC, 60, 30)) { // I'm not looking at them return qfalse; - } - else if ( DistanceSquared( NPC->currentOrigin, player->currentOrigin ) < 65536/*256*256*/ ) - {//they're not close + } else if (DistanceSquared(NPC->currentOrigin, player->currentOrigin) < 65536 /*256*256*/) { // they're not close return qfalse; - } - else if ( !gi.inPVS( NPC->currentOrigin, player->currentOrigin ) ) - {//they're not in the same room + } else if (!gi.inPVS(NPC->currentOrigin, player->currentOrigin)) { // they're not in the same room return qfalse; } } } - if ( NPCInfo->group && NPCInfo->group->numGroup <= 1 ) - {//I'm alone but I was in a group//FIXME: surrender anyway if just melee or no weap? - if ( NPC->s.weapon == WP_NONE - //NPC has a weapon - || NPC->enemy == player - || (NPC->enemy->s.weapon == WP_SABER&&NPC->enemy->client&&NPC->enemy->client->ps.saberActive) - || (NPC->enemy->NPC && NPC->enemy->NPC->group && NPC->enemy->NPC->group->numGroup > 2) ) - {//surrender only if have no weapon or fighting a player or jedi or if we are outnumbered at least 3 to 1 - if ( NPC->enemy == player ) - {//player is the guy I'm running from - if ( g_crosshairEntNum == NPC->s.number ) - {//give up if player is aiming at me + if (NPCInfo->group && NPCInfo->group->numGroup <= 1) { // I'm alone but I was in a group//FIXME: surrender anyway if just melee or no weap? + if (NPC->s.weapon == WP_NONE + // NPC has a weapon + || NPC->enemy == player || (NPC->enemy->s.weapon == WP_SABER && NPC->enemy->client && NPC->enemy->client->ps.saberActive) || + (NPC->enemy->NPC && NPC->enemy->NPC->group && + NPC->enemy->NPC->group->numGroup > + 2)) { // surrender only if have no weapon or fighting a player or jedi or if we are outnumbered at least 3 to 1 + if (NPC->enemy == player) { // player is the guy I'm running from + if (g_crosshairEntNum == NPC->s.number) { // give up if player is aiming at me NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else if ( player->s.weapon == WP_SABER ) - {//player is using saber - if ( InFOV( NPC, player, 60, 30 ) ) - {//they're looking at me - if ( DistanceSquared( NPC->currentOrigin, player->currentOrigin ) < 16384/*128*128*/ ) - {//they're close - if ( gi.inPVS( NPC->currentOrigin, player->currentOrigin ) ) - {//they're in the same room + } else if (player->s.weapon == WP_SABER) { // player is using saber + if (InFOV(NPC, player, 60, 30)) { // they're looking at me + if (DistanceSquared(NPC->currentOrigin, player->currentOrigin) < 16384 /*128*128*/) { // they're close + if (gi.inPVS(NPC->currentOrigin, player->currentOrigin)) { // they're in the same room NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } } } - } - else if ( NPC->enemy ) - {//??? - //should NPC's surrender to others? - if ( InFOV( NPC, NPC->enemy, 30, 30 ) ) - {//they're looking at me - if ( DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ) < 4096 ) - {//they're close - if ( gi.inPVS( NPC->currentOrigin, NPC->enemy->currentOrigin ) ) - {//they're in the same room - //FIXME: should player-team NPCs not fire on surrendered NPCs? + } else if (NPC->enemy) { //??? + // should NPC's surrender to others? + if (InFOV(NPC, NPC->enemy, 30, 30)) { // they're looking at me + if (DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin) < 4096) { // they're close + if (gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) { // they're in the same room + // FIXME: should player-team NPCs not fire on surrendered NPCs? NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -1456,229 +1244,191 @@ qboolean NPC_CheckSurrender( void ) return qfalse; } -void NPC_BSFlee( void ) -{//FIXME: keep checking for danger - if ( TIMER_Done( NPC, "flee" ) && NPCInfo->tempBehavior == BS_FLEE ) - { +void NPC_BSFlee(void) { // FIXME: keep checking for danger + if (TIMER_Done(NPC, "flee") && NPCInfo->tempBehavior == BS_FLEE) { NPCInfo->tempBehavior = BS_DEFAULT; NPCInfo->squadState = SQUAD_IDLE; - //FIXME: should we set some timer to make him stay in this spot for a bit, - //so he doesn't just suddenly turn around and come back at the enemy? - //OR, just stop running toward goal for last second or so of flee? + // FIXME: should we set some timer to make him stay in this spot for a bit, + // so he doesn't just suddenly turn around and come back at the enemy? + // OR, just stop running toward goal for last second or so of flee? } - if ( NPC_CheckSurrender() ) - { + if (NPC_CheckSurrender()) { return; } gentity_t *goal = NPCInfo->goalEntity; - if ( !goal ) - { + if (!goal) { goal = NPCInfo->lastGoalEntity; - if ( !goal ) - {//???!!! + if (!goal) { //???!!! goal = NPCInfo->tempGoal; } } - if ( goal ) - { + if (goal) { qboolean reverseCourse = qtrue; - //FIXME: if no weapon, find one and run to pick it up? + // FIXME: if no weapon, find one and run to pick it up? - //Let's try to find a waypoint that gets me away from this thing - if ( NPC->waypoint == WAYPOINT_NONE ) - { - NPC->waypoint = NAV_GetNearestNode( NPC, NPC->lastWaypoint ); + // Let's try to find a waypoint that gets me away from this thing + if (NPC->waypoint == WAYPOINT_NONE) { + NPC->waypoint = NAV_GetNearestNode(NPC, NPC->lastWaypoint); } - if ( NPC->waypoint != WAYPOINT_NONE ) - { - int numEdges = navigator.GetNodeNumEdges( NPC->waypoint ); + if (NPC->waypoint != WAYPOINT_NONE) { + int numEdges = navigator.GetNodeNumEdges(NPC->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - vec3_t dangerDir; - int nextWp; + if (numEdges != WAYPOINT_NONE) { + vec3_t dangerDir; + int nextWp; - VectorSubtract( NPCInfo->investigateGoal, NPC->currentOrigin, dangerDir ); - VectorNormalize( dangerDir ); + VectorSubtract(NPCInfo->investigateGoal, NPC->currentOrigin, dangerDir); + VectorNormalize(dangerDir); - for ( int branchNum = 0; branchNum < numEdges; branchNum++ ) - { - vec3_t branchPos, runDir; + for (int branchNum = 0; branchNum < numEdges; branchNum++) { + vec3_t branchPos, runDir; - nextWp = navigator.GetNodeEdge( NPC->waypoint, branchNum ); - navigator.GetNodePosition( nextWp, branchPos ); + nextWp = navigator.GetNodeEdge(NPC->waypoint, branchNum); + navigator.GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPC->currentOrigin, runDir ); - VectorNormalize( runDir ); - if ( DotProduct( runDir, dangerDir ) > Q_flrand( 0, 0.5 ) ) - {//don't run toward danger + VectorSubtract(branchPos, NPC->currentOrigin, runDir); + VectorNormalize(runDir); + if (DotProduct(runDir, dangerDir) > Q_flrand(0, 0.5)) { // don't run toward danger continue; } - //FIXME: don't want to ping-pong back and forth - NPC_SetMoveGoal( NPC, branchPos, 0, qtrue ); + // FIXME: don't want to ping-pong back and forth + NPC_SetMoveGoal(NPC, branchPos, 0, qtrue); reverseCourse = qfalse; break; } } } - qboolean moved = NPC_MoveToGoal( qfalse );//qtrue? (do try to move straight to (away from) goal) + qboolean moved = NPC_MoveToGoal(qfalse); // qtrue? (do try to move straight to (away from) goal) - if ( NPC->s.weapon == WP_NONE && (moved == qfalse || reverseCourse) ) - {//No weapon and no escape route... Just cower? Need anim. + if (NPC->s.weapon == WP_NONE && (moved == qfalse || reverseCourse)) { // No weapon and no escape route... Just cower? Need anim. NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If our move failed, then just run straight away from our goal - //FIXME: We really shouldn't do this. - if ( moved == qfalse ) - { - vec3_t dir; - float dist; - if ( reverseCourse ) - { - VectorSubtract( NPC->currentOrigin, goal->currentOrigin, dir ); - } - else - { - VectorSubtract( goal->currentOrigin, NPC->currentOrigin, dir ); + // If our move failed, then just run straight away from our goal + // FIXME: We really shouldn't do this. + if (moved == qfalse) { + vec3_t dir; + float dist; + if (reverseCourse) { + VectorSubtract(NPC->currentOrigin, goal->currentOrigin, dir); + } else { + VectorSubtract(goal->currentOrigin, NPC->currentOrigin, dir); } - NPCInfo->distToGoal = dist = VectorNormalize( dir ); - NPCInfo->desiredYaw = vectoyaw( dir ); + NPCInfo->distToGoal = dist = VectorNormalize(dir); + NPCInfo->desiredYaw = vectoyaw(dir); NPCInfo->desiredPitch = 0; ucmd.forwardmove = 127; - } - else if ( reverseCourse ) - { - //ucmd.forwardmove *= -1; - //ucmd.rightmove *= -1; - //VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + } else if (reverseCourse) { + // ucmd.forwardmove *= -1; + // ucmd.rightmove *= -1; + // VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); NPCInfo->desiredYaw *= -1; } - //FIXME: can stop after a safe distance? + // FIXME: can stop after a safe distance? ucmd.upmove = 0; ucmd.buttons &= ~BUTTON_WALKING; - //FIXME: what do we do once we've gotten to our goal? + // FIXME: what do we do once we've gotten to our goal? } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPC_CheckGetNewWeapon(); } -void NPC_StartFlee( gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ - if ( Q3_TaskIDPending( NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't interrupt that! +void NPC_StartFlee(gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { + if (Q3_TaskIDPending(NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't interrupt that! return; } - //if have a fleescript, run that instead - if ( G_ActivateBehavior( NPC, BSET_FLEE ) ) - { + // if have a fleescript, run that instead + if (G_ActivateBehavior(NPC, BSET_FLEE)) { return; } - //FIXME: play a flee sound? Appropriate to situation? - if ( enemy ) - { - G_SetEnemy( NPC, enemy ); + // FIXME: play a flee sound? Appropriate to situation? + if (enemy) { + G_SetEnemy(NPC, enemy); } - //FIXME: if don't have a weapon, find nearest one we have a route to and run for it? + // FIXME: if don't have a weapon, find nearest one we have a route to and run for it? int cp = -1; - if ( dangerLevel > AEL_DANGER || NPC->s.weapon == WP_NONE || ((!NPCInfo->group || NPCInfo->group->numGroup <= 1) && NPC->health <= 10 ) ) - {//IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER|CP_AVOID|CP_HAS_ROUTE|CP_NO_PVS, 128 ); - } - //FIXME: still happens too often... - if ( cp == -1 ) - {//okay give up on the no PVS thing - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER|CP_AVOID|CP_HAS_ROUTE, 128 ); - if ( cp == -1 ) - {//okay give up on the avoid - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER|CP_HAS_ROUTE, 128 ); - if ( cp == -1 ) - {//okay give up on the cover - cp = NPC_FindCombatPoint( NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_HAS_ROUTE, 128 ); + if (dangerLevel > AEL_DANGER || NPC->s.weapon == WP_NONE || + ((!NPCInfo->group || NPCInfo->group->numGroup <= 1) && + NPC->health <= 10)) { // IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER | CP_AVOID | CP_HAS_ROUTE | CP_NO_PVS, 128); + } + // FIXME: still happens too often... + if (cp == -1) { // okay give up on the no PVS thing + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER | CP_AVOID | CP_HAS_ROUTE, 128); + if (cp == -1) { // okay give up on the avoid + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_COVER | CP_HAS_ROUTE, 128); + if (cp == -1) { // okay give up on the cover + cp = NPC_FindCombatPoint(NPC->currentOrigin, NPC->currentOrigin, dangerPoint, CP_HAS_ROUTE, 128); } } } - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPC, level.combatPoints[cp].origin, 8, qtrue, cp ); + // see if we got a valid one + if (cp != -1) { // found a combat point + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPC, level.combatPoints[cp].origin, 8, qtrue, cp); NPCInfo->behaviorState = BS_HUNT_AND_KILL; NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//need to just run like hell! - if ( NPC->s.weapon != WP_NONE ) - { - return;//let's just not flee? - } - else - { - //FIXME: other evasion AI? Duck? Strafe? Dodge? + } else { // need to just run like hell! + if (NPC->s.weapon != WP_NONE) { + return; // let's just not flee? + } else { + // FIXME: other evasion AI? Duck? Strafe? Dodge? NPCInfo->tempBehavior = BS_FLEE; - //Run straight away from here... FIXME: really want to find farthest waypoint/navgoal from this pos... maybe based on alert event radius? - NPC_SetMoveGoal( NPC, dangerPoint, 0, qtrue ); - //store the danger point - VectorCopy( dangerPoint, NPCInfo->investigateGoal );//FIXME: make a new field for this? + // Run straight away from here... FIXME: really want to find farthest waypoint/navgoal from this pos... maybe based on alert event radius? + NPC_SetMoveGoal(NPC, dangerPoint, 0, qtrue); + // store the danger point + VectorCopy(dangerPoint, NPCInfo->investigateGoal); // FIXME: make a new field for this? } } - //FIXME: localize this Timer? - TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2500 ) ); - //FIXME: is this always applicable? + // FIXME: localize this Timer? + TIMER_Set(NPC, "attackDelay", Q_irand(500, 2500)); + // FIXME: is this always applicable? NPCInfo->squadState = SQUAD_RETREAT; - TIMER_Set( NPC, "flee", Q_irand( fleeTimeMin, fleeTimeMax ) ); - TIMER_Set( NPC, "panic", Q_irand( 1000, 4000 ) );//how long to wait before trying to nav to a dropped weapon - TIMER_Set( NPC, "duck", 0 ); + TIMER_Set(NPC, "flee", Q_irand(fleeTimeMin, fleeTimeMax)); + TIMER_Set(NPC, "panic", Q_irand(1000, 4000)); // how long to wait before trying to nav to a dropped weapon + TIMER_Set(NPC, "duck", 0); } -void G_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ - if ( !self->NPC ) - {//player +void G_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { + if (!self->NPC) { // player return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - NPC_StartFlee( enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax ); + NPC_StartFlee(enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax); RestoreNPCGlobals(); } -void NPC_BSEmplaced( void ) -{ - //Don't do anything if we're hurt - if ( NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSEmplaced(void) { + // Don't do anything if we're hurt + if (NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - if( NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt() == qfalse ) - { - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand( -90, 90 ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt() == qfalse) { + if (!Q_irand(0, 30)) { + NPCInfo->desiredYaw = NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCInfo->desiredPitch = Q_irand(-20, 20); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -1686,66 +1436,58 @@ void NPC_BSEmplaced( void ) qboolean enemyCS = qfalse; qboolean faceEnemy = qfalse; qboolean shoot = qfalse; - vec3_t impactPos; + vec3_t impactPos; - if ( NPC_ClearLOS( NPC->enemy ) ) - { + if (NPC_ClearLOS(NPC->enemy)) { enemyLOS = qtrue; - int hit = NPC_ShotEntity( NPC->enemy, impactPos ); + int hit = NPC_ShotEntity(NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPC->enemy->s.number || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + if (hit == NPC->enemy->s.number || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation ); + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPC->enemy->currentOrigin, NPCInfo->enemyLastSeenLocation); } } -/* - else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) - { - NPCInfo->enemyLastSeenTime = level.time; - faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy - } -*/ + /* + else if ( gi.inPVS( NPC->enemy->currentOrigin, NPC->currentOrigin ) ) + { + NPCInfo->enemyLastSeenTime = level.time; + faceEnemy = qtrue; + NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } + */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); - } - else - {//we want to face in the dir we're running - NPC_UpdateAngles( qtrue, qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); + } else { // we want to face in the dir we're running + NPC_UpdateAngles(qtrue, qtrue); } - if ( NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPC->enemy && NPC->enemy->enemy ) - { - if ( NPC->enemy->s.weapon == WP_SABER && NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPC->enemy && NPC->enemy->enemy) { + if (NPC->enemy->s.weapon == WP_SABER && + NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue + // blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - if ( shoot ) - {//try to shoot if it's time - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + if (shoot) { // try to shoot if it's time + if (!(NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } } } \ No newline at end of file diff --git a/codeJK2/game/NPC_combat.cpp b/codeJK2/game/NPC_combat.cpp index dbf7d67ec8..e9367801ed 100644 --- a/codeJK2/game/NPC_combat.cpp +++ b/codeJK2/game/NPC_combat.cpp @@ -20,46 +20,40 @@ along with this program; if not, see . =========================================================================== */ -//NPC_combat.cpp +// NPC_combat.cpp #include "g_headers.h" - - #include "b_local.h" #include "g_nav.h" #include "g_navigator.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ); -extern int NAV_FindClosestWaypointForPoint( vec3_t point ); -extern int NAV_GetNearestNode( gentity_t *self, int lastNode ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -extern qboolean PM_DroidMelee( int npc_class ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy); +extern int NAV_FindClosestWaypointForPoint(vec3_t point); +extern int NAV_GetNearestNode(gentity_t *self, int lastNode); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +extern qboolean PM_DroidMelee(int npc_class); -extern CNavigator navigator; +extern CNavigator navigator; -void ChangeWeapon( gentity_t *ent, int newWeapon ); +void ChangeWeapon(gentity_t *ent, int newWeapon); -void G_ClearEnemy (gentity_t *self) -{ - NPC_CheckLookTarget( self ); +void G_ClearEnemy(gentity_t *self) { + NPC_CheckLookTarget(self); - if ( self->enemy ) - { - if( self->client && self->client->renderInfo.lookTarget == self->enemy->s.number ) - { - NPC_ClearLookTarget( self ); + if (self->enemy) { + if (self->client && self->client->renderInfo.lookTarget == self->enemy->s.number) { + NPC_ClearLookTarget(self); } - if ( self->NPC && self->enemy == self->NPC->goalEntity ) - { + if (self->NPC && self->enemy == self->NPC->goalEntity) { self->NPC->goalEntity = NULL; } - //FIXME: set last enemy? + // FIXME: set last enemy? } self->enemy = NULL; @@ -71,21 +65,18 @@ NPC_AngerAlert ------------------------- */ -#define ANGER_ALERT_RADIUS 512 -#define ANGER_ALERT_SOUND_RADIUS 256 +#define ANGER_ALERT_RADIUS 512 +#define ANGER_ALERT_SOUND_RADIUS 256 -void G_AngerAlert( gentity_t *self ) -{ - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... +void G_AngerAlert(gentity_t *self) { + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return; } - if ( !TIMER_Done( self, "interrogating" ) ) - {//I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! + if (!TIMER_Done(self, "interrogating")) { // I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! return; } - //FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? - G_AlertTeam( self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS ); + // FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? + G_AlertTeam(self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS); } /* @@ -94,48 +85,39 @@ G_TeamEnemy ------------------------- */ -qboolean G_TeamEnemy( gentity_t *self ) -{//FIXME: Probably a better way to do this, is a linked list of your teammates already available? - int i; - gentity_t *ent; +qboolean G_TeamEnemy(gentity_t *self) { // FIXME: Probably a better way to do this, is a linked list of your teammates already available? + int i; + gentity_t *ent; - if ( !self->client || self->client->playerTeam == TEAM_FREE ) - { + if (!self->client || self->client->playerTeam == TEAM_FREE) { return qfalse; } - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return qfalse; } - for( i = 1; i < MAX_GENTITIES; i++ ) - { + for (i = 1; i < MAX_GENTITIES; i++) { ent = &g_entities[i]; - if ( ent == self ) - { + if (ent == self) { continue; } - if ( ent->health <= 0 ) - { + if (ent->health <= 0) { continue; } - if ( !ent->client ) - { + if (!ent->client) { continue; } - if ( ent->client->playerTeam != self->client->playerTeam ) - {//ent is not on my team + if (ent->client->playerTeam != self->client->playerTeam) { // ent is not on my team continue; } - if ( ent->enemy ) - {//they have an enemy - if ( !ent->enemy->client || ent->enemy->client->playerTeam != self->client->playerTeam ) - {//the ent's enemy is either a normal ent or is a player/NPC that is not on my team + if (ent->enemy) { // they have an enemy + if (!ent->enemy->client || ent->enemy->client->playerTeam != + self->client->playerTeam) { // the ent's enemy is either a normal ent or is a player/NPC that is not on my team return qtrue; } } @@ -144,62 +126,55 @@ qboolean G_TeamEnemy( gentity_t *self ) return qfalse; } -void G_AttackDelay( gentity_t *self, gentity_t *enemy ) -{ - if ( enemy && self->client && self->NPC ) - {//delay their attack based on how far away they're facing from enemy - vec3_t fwd, dir; - int attDelay; - - VectorSubtract( self->client->renderInfo.eyePoint, enemy->currentOrigin, dir );//purposely backwards - VectorNormalize( dir ); - AngleVectors( self->client->renderInfo.eyeAngles, fwd, NULL, NULL ); - //dir[2] = fwd[2] = 0;//ignore z diff? - - attDelay = (4-g_spskill->integer)*500;//initial: from 1000ms delay on hard to 2000ms delay on easy - if ( self->client->playerTeam == TEAM_PLAYER ) - {//invert - attDelay = 2000-attDelay; - } - attDelay += floor( (DotProduct( fwd, dir )+1.0f) * 2000.0f );//add up to 4000ms delay if they're facing away - - //FIXME: should distance matter, too? - - //Now modify the delay based on NPC_class, weapon, and team - //NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds - switch ( self->client->NPC_class ) - { - case CLASS_IMPERIAL://they give orders and hang back - attDelay += Q_irand( 500, 1500 ); +void G_AttackDelay(gentity_t *self, gentity_t *enemy) { + if (enemy && self->client && self->NPC) { // delay their attack based on how far away they're facing from enemy + vec3_t fwd, dir; + int attDelay; + + VectorSubtract(self->client->renderInfo.eyePoint, enemy->currentOrigin, dir); // purposely backwards + VectorNormalize(dir); + AngleVectors(self->client->renderInfo.eyeAngles, fwd, NULL, NULL); + // dir[2] = fwd[2] = 0;//ignore z diff? + + attDelay = (4 - g_spskill->integer) * 500; // initial: from 1000ms delay on hard to 2000ms delay on easy + if (self->client->playerTeam == TEAM_PLAYER) { // invert + attDelay = 2000 - attDelay; + } + attDelay += floor((DotProduct(fwd, dir) + 1.0f) * 2000.0f); // add up to 4000ms delay if they're facing away + + // FIXME: should distance matter, too? + + // Now modify the delay based on NPC_class, weapon, and team + // NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds + switch (self->client->NPC_class) { + case CLASS_IMPERIAL: // they give orders and hang back + attDelay += Q_irand(500, 1500); break; - case CLASS_STORMTROOPER://stormtroopers shoot sooner - if ( self->NPC->rank >= RANK_LT ) - {//officers shoot even sooner - attDelay -= Q_irand( 500, 1500 ); - } - else - {//normal stormtroopers don't have as fast reflexes as officers - attDelay -= Q_irand( 0, 1000 ); + case CLASS_STORMTROOPER: // stormtroopers shoot sooner + if (self->NPC->rank >= RANK_LT) { // officers shoot even sooner + attDelay -= Q_irand(500, 1500); + } else { // normal stormtroopers don't have as fast reflexes as officers + attDelay -= Q_irand(0, 1000); } break; - case CLASS_SWAMPTROOPER://shoot very quickly? What about guys in water? - attDelay -= Q_irand( 1000, 2000 ); + case CLASS_SWAMPTROOPER: // shoot very quickly? What about guys in water? + attDelay -= Q_irand(1000, 2000); break; - case CLASS_IMPWORKER://they panic, don't fire right away - attDelay += Q_irand( 1000, 2500 ); + case CLASS_IMPWORKER: // they panic, don't fire right away + attDelay += Q_irand(1000, 2500); break; case CLASS_TRANDOSHAN: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; - case CLASS_JAN: - case CLASS_LANDO: + case CLASS_JAN: + case CLASS_LANDO: case CLASS_PRISONER: case CLASS_REBEL: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; - case CLASS_GALAKMECH: - case CLASS_ATST: - attDelay -= Q_irand( 1000, 2000 ); + case CLASS_GALAKMECH: + case CLASS_ATST: + attDelay -= Q_irand(1000, 2000); break; case CLASS_REELO: case CLASS_UGNAUGHT: @@ -210,10 +185,10 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) return; break; case CLASS_INTERROGATOR: - case CLASS_PROBE: - case CLASS_MARK1: - case CLASS_MARK2: - case CLASS_SENTRY: + case CLASS_PROBE: + case CLASS_MARK1: + case CLASS_MARK2: + case CLASS_SENTRY: return; break; case CLASS_REMOTE: @@ -225,20 +200,19 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) case CLASS_RODIAN: case CLASS_WEEQUAY: break; - case CLASS_JEDI: + case CLASS_JEDI: case CLASS_SHADOWTROOPER: case CLASS_TAVION: case CLASS_REBORN: - case CLASS_LUKE: - case CLASS_DESANN: + case CLASS_LUKE: + case CLASS_DESANN: break; */ default: break; } - switch ( self->s.weapon ) - { + switch (self->s.weapon) { case WP_NONE: case WP_SABER: return; @@ -246,96 +220,86 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) case WP_BRYAR_PISTOL: break; case WP_BLASTER: - if ( self->NPC->scriptFlags & SCF_ALT_FIRE ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); - } - else - {//regular blaster - attDelay -= Q_irand( 0, 500 ); + if (self->NPC->scriptFlags & SCF_ALT_FIRE) { // rapid-fire blasters + attDelay += Q_irand(0, 500); + } else { // regular blaster + attDelay -= Q_irand(0, 500); } break; case WP_BOWCASTER: - attDelay += Q_irand( 0, 500 ); + attDelay += Q_irand(0, 500); break; case WP_REPEATER: - if ( !(self->NPC->scriptFlags&SCF_ALT_FIRE) ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); + if (!(self->NPC->scriptFlags & SCF_ALT_FIRE)) { // rapid-fire blasters + attDelay += Q_irand(0, 500); } break; case WP_FLECHETTE: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; case WP_ROCKET_LAUNCHER: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; - case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster - attDelay -= Q_irand( 500, 1500 ); + case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster + attDelay -= Q_irand(500, 1500); break; - case WP_DISRUPTOR://sniper's don't delay? + case WP_DISRUPTOR: // sniper's don't delay? return; break; - case WP_THERMAL://grenade-throwing has a built-in delay + case WP_THERMAL: // grenade-throwing has a built-in delay return; break; - case WP_MELEE: // Any ol' melee attack + case WP_MELEE: // Any ol' melee attack return; break; case WP_EMPLACED_GUN: return; break; - case WP_TURRET: // turret guns + case WP_TURRET: // turret guns return; break; - case WP_BOT_LASER: // Probe droid - Laser blast + case WP_BOT_LASER: // Probe droid - Laser blast return; break; - /* - case WP_DEMP2: - break; - case WP_TRIP_MINE: - break; - case WP_DET_PACK: - break; - case WP_STUN_BATON: - break; - case WP_ATST_MAIN: - break; - case WP_ATST_SIDE: - break; - case WP_TIE_FIGHTER: - break; - case WP_RAPID_FIRE_CONC: - break; - */ + /* + case WP_DEMP2: + break; + case WP_TRIP_MINE: + break; + case WP_DET_PACK: + break; + case WP_STUN_BATON: + break; + case WP_ATST_MAIN: + break; + case WP_ATST_SIDE: + break; + case WP_TIE_FIGHTER: + break; + case WP_RAPID_FIRE_CONC: + break; + */ } - if ( self->client->playerTeam == TEAM_PLAYER ) - {//clamp it - if ( attDelay > 2000 ) - { + if (self->client->playerTeam == TEAM_PLAYER) { // clamp it + if (attDelay > 2000) { attDelay = 2000; } } - //don't shoot right away - if ( attDelay > 4000+((2-g_spskill->integer)*3000) ) - { - attDelay = 4000+((2-g_spskill->integer)*3000); + // don't shoot right away + if (attDelay > 4000 + ((2 - g_spskill->integer) * 3000)) { + attDelay = 4000 + ((2 - g_spskill->integer) * 3000); } - TIMER_Set( self, "attackDelay", attDelay );//Q_irand( 1500, 4500 ) ); - //don't move right away either - if ( attDelay > 4000 ) - { + TIMER_Set(self, "attackDelay", attDelay); // Q_irand( 1500, 4500 ) ); + // don't move right away either + if (attDelay > 4000) { attDelay = 4000 - Q_irand(500, 1500); - } - else - { + } else { attDelay -= Q_irand(500, 1500); } - TIMER_Set( self, "roamTime", attDelay );//was Q_irand( 1000, 3500 ); + TIMER_Set(self, "roamTime", attDelay); // was Q_irand( 1000, 3500 ); } } /* @@ -343,215 +307,184 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) G_SetEnemy ------------------------- */ -void G_AimSet( gentity_t *self, int aim ); -void G_SetEnemy( gentity_t *self, gentity_t *enemy ) -{ - int event = 0; - - //Must be valid - if ( enemy == NULL ) +void G_AimSet(gentity_t *self, int aim); +void G_SetEnemy(gentity_t *self, gentity_t *enemy) { + int event = 0; + + // Must be valid + if (enemy == NULL) return; - //Must be valid - if ( enemy->inuse == 0 ) - { + // Must be valid + if (enemy->inuse == 0) { return; } - //Don't take the enemy if in notarget - if ( enemy->flags & FL_NOTARGET ) + // Don't take the enemy if in notarget + if (enemy->flags & FL_NOTARGET) return; - if ( !self->NPC ) - { + if (!self->NPC) { self->enemy = enemy; return; } - if ( self->NPC->confusionTime > level.time ) - {//can't pick up enemies if confused + if (self->NPC->confusionTime > level.time) { // can't pick up enemies if confused return; } #ifdef _DEBUG - if ( self->s.number ) - { - assert( enemy != self ); - } -#endif// _DEBUG - -// if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) -// {//unmask the player -// enemy->client->playerTeam = TEAM_PLAYER; -// } - - if ( self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam ) - {//Probably a damn script! - if ( self->NPC->charmedTime > level.time ) - {//Probably a damn script! + if (self->s.number) { + assert(enemy != self); + } +#endif // _DEBUG + + // if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) + // {//unmask the player + // enemy->client->playerTeam = TEAM_PLAYER; + // } + + if (self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam) { // Probably a damn script! + if (self->NPC->charmedTime > level.time) { // Probably a damn script! return; } } - if ( self->NPC && self->client && self->client->ps.weapon == WP_SABER ) - { - //when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. - NPC_Jedi_RateNewEnemy( self, enemy ); + if (self->NPC && self->client && self->client->ps.weapon == WP_SABER) { + // when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. + NPC_Jedi_RateNewEnemy(self, enemy); } - //NOTE: this is not necessarily true! - //self->NPC->enemyLastSeenTime = level.time; + // NOTE: this is not necessarily true! + // self->NPC->enemyLastSeenTime = level.time; - if ( self->enemy == NULL ) - { - //TEMP HACK: turn on our saber - if ( self->health > 0 ) - { + if (self->enemy == NULL) { + // TEMP HACK: turn on our saber + if (self->health > 0) { self->client->ps.saberActive = qtrue; } - //FIXME: Have to do this to prevent alert cascading - G_ClearEnemy( self ); + // FIXME: Have to do this to prevent alert cascading + G_ClearEnemy(self); self->enemy = enemy; - //Special case- if player is being hunted by his own people, set their enemy team correctly - if ( self->client->playerTeam == TEAM_PLAYER && enemy->s.number == 0 ) - { + // Special case- if player is being hunted by his own people, set their enemy team correctly + if (self->client->playerTeam == TEAM_PLAYER && enemy->s.number == 0) { self->client->enemyTeam = TEAM_PLAYER; } - //If have an anger script, run that instead of yelling - if( G_ActivateBehavior( self, BSET_ANGER ) ) - { - } - else if ( self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam ) - { - //FIXME: Use anger when entire team has no enemy. + // If have an anger script, run that instead of yelling + if (G_ActivateBehavior(self, BSET_ANGER)) { + } else if (self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam) { + // FIXME: Use anger when entire team has no enemy. // Basically, you're first one to notice enemies - if ( self->forcePushTime < level.time ) // not currently being pushed + if (self->forcePushTime < level.time) // not currently being pushed { - if ( !G_TeamEnemy( self ) ) - {//team did not have an enemy previously + if (!G_TeamEnemy(self)) { // team did not have an enemy previously event = Q_irand(EV_ANGER1, EV_ANGER3); } } - - if ( event ) - {//yell - G_AddVoiceEvent( self, event, 2000 ); + + if (event) { // yell + G_AddVoiceEvent(self, event, 2000); } } - - if ( self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || - self->s.weapon == WP_THERMAL || self->s.weapon == WP_BLASTER_PISTOL - || self->s.weapon == WP_BOWCASTER ) - {//Hmm, how about sniper and bowcaster? - //When first get mad, aim is bad - //Hmm, base on game difficulty, too? Rank? - if ( self->client->playerTeam == TEAM_PLAYER ) - { - G_AimSet( self, Q_irand( self->NPC->stats.aim - (5*(g_spskill->integer)), self->NPC->stats.aim - g_spskill->integer ) ); - } - else - { + + if (self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || self->s.weapon == WP_THERMAL || self->s.weapon == WP_BLASTER_PISTOL || + self->s.weapon == WP_BOWCASTER) { // Hmm, how about sniper and bowcaster? + // When first get mad, aim is bad + // Hmm, base on game difficulty, too? Rank? + if (self->client->playerTeam == TEAM_PLAYER) { + G_AimSet(self, Q_irand(self->NPC->stats.aim - (5 * (g_spskill->integer)), self->NPC->stats.aim - g_spskill->integer)); + } else { int minErr = 3; int maxErr = 12; - if ( self->client->NPC_class == CLASS_IMPWORKER ) - { + if (self->client->NPC_class == CLASS_IMPWORKER) { minErr = 15; maxErr = 30; - } - else if ( self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN ) - { + } else if (self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN) { minErr = 5; maxErr = 15; } - G_AimSet( self, Q_irand( self->NPC->stats.aim - (maxErr*(3-g_spskill->integer)), self->NPC->stats.aim - (minErr*(3-g_spskill->integer)) ) ); + G_AimSet(self, Q_irand(self->NPC->stats.aim - (maxErr * (3 - g_spskill->integer)), self->NPC->stats.aim - (minErr * (3 - g_spskill->integer)))); } } - - //Alert anyone else in the area - if ( Q_stricmp( "desperado", self->NPC_type ) != 0 && Q_stricmp( "paladin", self->NPC_type ) != 0 ) - {//special holodeck enemies exception - if ( !(self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//gripped people can't call for help - G_AngerAlert( self ); + + // Alert anyone else in the area + if (Q_stricmp("desperado", self->NPC_type) != 0 && Q_stricmp("paladin", self->NPC_type) != 0) { // special holodeck enemies exception + if (!(self->client->ps.eFlags & EF_FORCE_GRIPPED)) { // gripped people can't call for help + G_AngerAlert(self); } } - //Stormtroopers don't fire right away! - G_AttackDelay( self, enemy ); + // Stormtroopers don't fire right away! + G_AttackDelay(self, enemy); - //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way - if ( self->client->ps.weapon == WP_NONE && !Q_strncmp( self->NPC_type, "imp", 3 ) && !(self->NPC->scriptFlags & SCF_FORCED_MARCH) ) - { - if ( self->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_BLASTER ) ) - { - ChangeWeapon( self, WP_BLASTER ); + // FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way + if (self->client->ps.weapon == WP_NONE && !Q_strncmp(self->NPC_type, "imp", 3) && !(self->NPC->scriptFlags & SCF_FORCED_MARCH)) { + if (self->client->ps.stats[STAT_WEAPONS] & (1 << WP_BLASTER)) { + ChangeWeapon(self, WP_BLASTER); self->client->ps.weapon = WP_BLASTER; self->client->ps.weaponstate = WEAPON_READY; - G_CreateG2AttachedWeaponModel( self, weaponData[WP_BLASTER].weaponMdl ); - } - else if ( self->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_BLASTER_PISTOL ) ) - { - ChangeWeapon( self, WP_BLASTER_PISTOL ); + G_CreateG2AttachedWeaponModel(self, weaponData[WP_BLASTER].weaponMdl); + } else if (self->client->ps.stats[STAT_WEAPONS] & (1 << WP_BLASTER_PISTOL)) { + ChangeWeapon(self, WP_BLASTER_PISTOL); self->client->ps.weapon = WP_BLASTER_PISTOL; self->client->ps.weaponstate = WEAPON_READY; - G_CreateG2AttachedWeaponModel( self, weaponData[WP_BLASTER_PISTOL].weaponMdl ); + G_CreateG2AttachedWeaponModel(self, weaponData[WP_BLASTER_PISTOL].weaponMdl); } } return; } - - //Otherwise, just picking up another enemy - if ( event ) - { - G_AddVoiceEvent( self, event, 2000 ); + // Otherwise, just picking up another enemy + + if (event) { + G_AddVoiceEvent(self, event, 2000); } - //Take the enemy + // Take the enemy G_ClearEnemy(self); self->enemy = enemy; } /* -int ChooseBestWeapon( void ) +int ChooseBestWeapon( void ) { int n; int weapon; // check weapons in the NPC's weapon preference order - for ( n = 0; n < MAX_WEAPONS; n++ ) + for ( n = 0; n < MAX_WEAPONS; n++ ) { weapon = NPCInfo->weaponOrder[n]; - if ( weapon == WP_NONE ) + if ( weapon == WP_NONE ) { break; } - if ( !HaveWeapon( weapon ) ) + if ( !HaveWeapon( weapon ) ) { continue; } - if ( client->ps.ammo[weaponData[weapon].ammoIndex] ) + if ( client->ps.ammo[weaponData[weapon].ammoIndex] ) { return weapon; } } // check weapons serially (mainly in case a weapon is not on the NPC's list) - for ( weapon = 1; weapon < WP_NUM_WEAPONS; weapon++ ) + for ( weapon = 1; weapon < WP_NUM_WEAPONS; weapon++ ) { - if ( !HaveWeapon( weapon ) ) + if ( !HaveWeapon( weapon ) ) { continue; } - if ( client->ps.ammo[weaponData[weapon].ammoIndex] ) + if ( client->ps.ammo[weaponData[weapon].ammoIndex] ) { return weapon; } @@ -561,10 +494,8 @@ int ChooseBestWeapon( void ) } */ -void ChangeWeapon( gentity_t *ent, int newWeapon ) -{ - if ( !ent || !ent->client || !ent->NPC ) - { +void ChangeWeapon(gentity_t *ent, int newWeapon) { + if (!ent || !ent->client || !ent->NPC) { return; } @@ -574,235 +505,206 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) ent->NPC->attackHold = 0; ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[newWeapon].ammoIndex]; - switch ( newWeapon ) - { - case WP_BRYAR_PISTOL://prifle + switch (newWeapon) { + case WP_BRYAR_PISTOL: // prifle ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_BLASTER_PISTOL: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce break; - case WP_BOT_LASER://probe attack + case WP_BOT_LASER: // probe attack ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 600;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 600;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 400;//attack debounce - else - ent->NPC->burstSpacing = 200;//attack debounce + // ent->NPC->burstSpacing = 600;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 600; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 400; // attack debounce + else + ent->NPC->burstSpacing = 200; // attack debounce break; case WP_SABER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 0;//attackdebounce + ent->NPC->burstSpacing = 0; // attackdebounce break; case WP_DISRUPTOR: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - switch( g_spskill->integer ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + switch (g_spskill->integer) { case 0: - ent->NPC->burstSpacing = 2500;//attackdebounce + ent->NPC->burstSpacing = 2500; // attackdebounce break; case 1: - ent->NPC->burstSpacing = 2000;//attackdebounce + ent->NPC->burstSpacing = 2000; // attackdebounce break; case 2: - ent->NPC->burstSpacing = 1500;//attackdebounce + ent->NPC->burstSpacing = 1500; // attackdebounce break; } - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_BOWCASTER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce break; case WP_REPEATER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; ent->NPC->burstMax = 10; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce } break; case WP_DEMP2: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_FLECHETTE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_ROCKET_LAUNCHER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 2500;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 2500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 2000;//attack debounce - else - ent->NPC->burstSpacing = 1500;//attack debounce + // ent->NPC->burstSpacing = 2500;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 2500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 2000; // attack debounce + else + ent->NPC->burstSpacing = 1500; // attack debounce break; case WP_THERMAL: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 3000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 3000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 2500;//attack debounce - else - ent->NPC->burstSpacing = 2000;//attack debounce + // ent->NPC->burstSpacing = 3000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 3000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 2500; // attack debounce + else + ent->NPC->burstSpacing = 2000; // attack debounce break; - /* - case WP_SABER: - ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; - ent->NPC->burstMin = 5;//0.5 sec - ent->NPC->burstMax = 20;//3 seconds - ent->NPC->burstSpacing = 2000;//2 seconds - ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst - break; - */ + /* + case WP_SABER: + ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; + ent->NPC->burstMin = 5;//0.5 sec + ent->NPC->burstMax = 20;//3 seconds + ent->NPC->burstSpacing = 2000;//2 seconds + ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst + break; + */ case WP_BLASTER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; ent->NPC->burstMax = 3; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce - } - else - { + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce + } else { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce - // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce } break; case WP_MELEE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_ATST_MAIN: case WP_ATST_SIDE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_spskill->integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_spskill->integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce - else - ent->NPC->burstSpacing = 500;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_spskill->integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_spskill->integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce + else + ent->NPC->burstSpacing = 500; // attack debounce break; case WP_EMPLACED_GUN: - //FIXME: give some designer-control over this? - if ( ent->client && ent->client->NPC_class == CLASS_REELO ) - { + // FIXME: give some designer-control over this? + if (ent->client && ent->client->NPC_class == CLASS_REELO) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attack debounce - // if ( g_spskill->integer == 0 ) - // ent->NPC->burstSpacing = 300;//attack debounce - // else if ( g_spskill->integer == 1 ) - // ent->NPC->burstSpacing = 200;//attack debounce - // else - // ent->NPC->burstSpacing = 100;//attack debounce - } - else - { + ent->NPC->burstSpacing = 1000; // attack debounce + // if ( g_spskill->integer == 0 ) + // ent->NPC->burstSpacing = 300;//attack debounce + // else if ( g_spskill->integer == 1 ) + // ent->NPC->burstSpacing = 200;//attack debounce + // else + // ent->NPC->burstSpacing = 100;//attack debounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 2; // 3 shots, really ent->NPC->burstMax = 2; - if ( ent->owner ) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. + if (ent->owner) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. { - if ( g_spskill->integer == 0 ) - { - ent->NPC->burstSpacing = ent->owner->wait + 400;//attack debounce - ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots - } - else if ( g_spskill->integer == 1 ) - { - ent->NPC->burstSpacing = ent->owner->wait + 200;//attack debounce + if (g_spskill->integer == 0) { + ent->NPC->burstSpacing = ent->owner->wait + 400; // attack debounce + ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots + } else if (g_spskill->integer == 1) { + ent->NPC->burstSpacing = ent->owner->wait + 200; // attack debounce + } else { + ent->NPC->burstSpacing = ent->owner->wait; // attack debounce } - else - { - ent->NPC->burstSpacing = ent->owner->wait;//attack debounce - } - } - else - { - if ( g_spskill->integer == 0 ) - { - ent->NPC->burstSpacing = 1200;//attack debounce + } else { + if (g_spskill->integer == 0) { + ent->NPC->burstSpacing = 1200; // attack debounce ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots - } - else if ( g_spskill->integer == 1 ) - { - ent->NPC->burstSpacing = 1000;//attack debounce - } - else - { - ent->NPC->burstSpacing = 800;//attack debounce + } else if (g_spskill->integer == 1) { + ent->NPC->burstSpacing = 1000; // attack debounce + } else { + ent->NPC->burstSpacing = 800; // attack debounce } } } @@ -814,27 +716,20 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) } } -void NPC_ChangeWeapon( int newWeapon ) -{ - qboolean changing = qfalse; - if ( newWeapon != NPC->client->ps.weapon ) - { +void NPC_ChangeWeapon(int newWeapon) { + qboolean changing = qfalse; + if (newWeapon != NPC->client->ps.weapon) { changing = qtrue; } - if ( changing && NPC->weaponModel >= 9 ) - { - gi.G2API_RemoveGhoul2Model( NPC->ghoul2, NPC->weaponModel ); + if (changing && NPC->weaponModel >= 9) { + gi.G2API_RemoveGhoul2Model(NPC->ghoul2, NPC->weaponModel); } - ChangeWeapon( NPC, newWeapon ); - if ( changing && NPC->client->ps.weapon != WP_NONE ) - { - if ( NPC->client->ps.weapon == WP_SABER ) - { - G_CreateG2AttachedWeaponModel( NPC, NPC->client->ps.saberModel ); - } - else - { - G_CreateG2AttachedWeaponModel( NPC, weaponData[NPC->client->ps.weapon].weaponMdl ); + ChangeWeapon(NPC, newWeapon); + if (changing && NPC->client->ps.weapon != WP_NONE) { + if (NPC->client->ps.weapon == WP_SABER) { + G_CreateG2AttachedWeaponModel(NPC, NPC->client->ps.saberModel); + } else { + G_CreateG2AttachedWeaponModel(NPC, weaponData[NPC->client->ps.weapon].weaponMdl); } } } @@ -842,25 +737,21 @@ void NPC_ChangeWeapon( int newWeapon ) void NPC_ApplyWeaponFireDelay(void) How long, if at all, in msec the actual fire should delay from the time the attack was started */ -void NPC_ApplyWeaponFireDelay(void) -{ - if ( NPC->attackDebounceTime > level.time ) - {//Just fired, if attacking again, must be a burst fire, so don't add delay - //NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! +void NPC_ApplyWeaponFireDelay(void) { + if (NPC->attackDebounceTime > level.time) { // Just fired, if attacking again, must be a burst fire, so don't add delay + // NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! return; } - - switch(client->ps.weapon) - { + + switch (client->ps.weapon) { case WP_BOT_LASER: NPCInfo->burstCount = 0; client->fireDelay = 500; break; case WP_THERMAL: - if ( client->ps.clientNum ) - {//NPCs delay... - //FIXME: player should, too, but would feel weird in 1st person, even though it + if (client->ps.clientNum) { // NPCs delay... + // FIXME: player should, too, but would feel weird in 1st person, even though it // would look right in 3rd person. Really should have a wind-up anim // for player as he holds down the fire button to throw, then play // the actual throw when he lets go... @@ -869,8 +760,7 @@ void NPC_ApplyWeaponFireDelay(void) break; case WP_MELEE: - if ( !PM_DroidMelee( client->NPC_class ) ) - {//FIXME: should be unique per melee anim + if (!PM_DroidMelee(client->NPC_class)) { // FIXME: should be unique per melee anim client->fireDelay = 300; } break; @@ -886,80 +776,56 @@ void NPC_ApplyWeaponFireDelay(void) ShootThink ------------------------- */ -void ShootThink( void ) -{ - int delay; -/* - if ( enemyVisibility != VIS_SHOOT) - return; -*/ +void ShootThink(void) { + int delay; + /* + if ( enemyVisibility != VIS_SHOOT) + return; + */ ucmd.buttons |= BUTTON_ATTACK; - NPCInfo->currentAmmo = client->ps.ammo[weaponData[client->ps.weapon].ammoIndex]; // checkme + NPCInfo->currentAmmo = client->ps.ammo[weaponData[client->ps.weapon].ammoIndex]; // checkme NPC_ApplyWeaponFireDelay(); - if ( NPCInfo->aiFlags & NPCAI_BURST_WEAPON ) - { - if ( !NPCInfo->burstCount ) - { - NPCInfo->burstCount = Q_irand( NPCInfo->burstMin, NPCInfo->burstMax ); + if (NPCInfo->aiFlags & NPCAI_BURST_WEAPON) { + if (!NPCInfo->burstCount) { + NPCInfo->burstCount = Q_irand(NPCInfo->burstMin, NPCInfo->burstMax); delay = 0; - } - else - { + } else { NPCInfo->burstCount--; - if ( NPCInfo->burstCount == 0 ) - { + if (NPCInfo->burstCount == 0) { delay = NPCInfo->burstSpacing; - } - else - { + } else { delay = 0; } } - if ( !delay ) - { + if (!delay) { // HACK: dirty little emplaced bits, but is done because it would otherwise require some sort of new variable... - if ( client->ps.weapon == WP_EMPLACED_GUN ) - { - if ( NPC->owner ) // try and get the debounce values from the chair if we can + if (client->ps.weapon == WP_EMPLACED_GUN) { + if (NPC->owner) // try and get the debounce values from the chair if we can { - if ( g_spskill->integer == 0 ) - { + if (g_spskill->integer == 0) { delay = NPC->owner->random + 150; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { delay = NPC->owner->random + 100; - } - else - { + } else { delay = NPC->owner->random; } - } - else - { - if ( g_spskill->integer == 0 ) - { + } else { + if (g_spskill->integer == 0) { delay = 350; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { delay = 300; - } - else - { + } else { delay = 200; } } } } - } - else - { + } else { delay = NPCInfo->burstSpacing; } @@ -968,42 +834,37 @@ void ShootThink( void ) } /* -static void WeaponThink( qboolean inCombat ) +static void WeaponThink( qboolean inCombat ) FIXME makes this so there's a delay from event that caused us to check to actually doing it Added: hacks for Borg */ -void WeaponThink( qboolean inCombat ) -{ +void WeaponThink(qboolean inCombat) { ucmd.buttons &= ~BUTTON_ATTACK; - if ( client->ps.weaponstate == WEAPON_RAISING || client->ps.weaponstate == WEAPON_DROPPING ) - { + if (client->ps.weaponstate == WEAPON_RAISING || client->ps.weaponstate == WEAPON_DROPPING) { ucmd.weapon = client->ps.weapon; return; } - if ( client->ps.weapon == WP_NONE ) - { + if (client->ps.weapon == WP_NONE) { return; } - if ( client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING && client->ps.weaponstate != WEAPON_IDLE) - { + if (client->ps.weaponstate != WEAPON_READY && client->ps.weaponstate != WEAPON_FIRING && client->ps.weaponstate != WEAPON_IDLE) { return; } - if ( level.time < NPCInfo->shotTime ) - { + if (level.time < NPCInfo->shotTime) { return; } -//MCG - Begin - //For now, no-one runs out of ammo - if(NPC->client->ps.ammo[ weaponData[client->ps.weapon].ammoIndex ] < 10) // checkme -// if(NPC->client->ps.ammo[ client->ps.weapon ] < 10) + // MCG - Begin + // For now, no-one runs out of ammo + if (NPC->client->ps.ammo[weaponData[client->ps.weapon].ammoIndex] < 10) // checkme + // if(NPC->client->ps.ammo[ client->ps.weapon ] < 10) { - Add_Ammo (NPC, client->ps.weapon, 100); + Add_Ammo(NPC, client->ps.weapon, 100); } ucmd.weapon = client->ps.weapon; @@ -1014,33 +875,24 @@ void WeaponThink( qboolean inCombat ) HaveWeapon */ -qboolean HaveWeapon( int weapon ) -{ - return (qboolean)(client->ps.stats[STAT_WEAPONS] & (1 << weapon)); -} +qboolean HaveWeapon(int weapon) { return (qboolean)(client->ps.stats[STAT_WEAPONS] & (1 << weapon)); } -qboolean EntIsGlass (gentity_t *check) -{ - if(check->classname && - !Q_stricmp("func_breakable", check->classname) && - check->count == 1 && check->health <= 100) - { +qboolean EntIsGlass(gentity_t *check) { + if (check->classname && !Q_stricmp("func_breakable", check->classname) && check->count == 1 && check->health <= 100) { return qtrue; } return qfalse; } -qboolean ShotThroughGlass (trace_t *tr, gentity_t *target, vec3_t spot, int mask) -{ - gentity_t *hit = &g_entities[ tr->entityNum ]; - if(hit != target && EntIsGlass(hit)) - {//ok to shoot through breakable glass - int skip = hit->s.number; - vec3_t muzzle; +qboolean ShotThroughGlass(trace_t *tr, gentity_t *target, vec3_t spot, int mask) { + gentity_t *hit = &g_entities[tr->entityNum]; + if (hit != target && EntIsGlass(hit)) { // ok to shoot through breakable glass + int skip = hit->s.number; + vec3_t muzzle; VectorCopy(tr->endpos, muzzle); - gi.trace (tr, muzzle, NULL, NULL, spot, skip, mask, G2_NOCOLLIDE, 0 ); + gi.trace(tr, muzzle, NULL, NULL, spot, skip, mask, G2_NOCOLLIDE, 0); return qtrue; } @@ -1055,72 +907,62 @@ this function does not check teams, invulnerability, notarget, etc.... Added: If can't shoot center, try head, if not, see if it's close enough to try anyway. */ -qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) -{ - trace_t tr; - vec3_t muzzle; - vec3_t spot, diff; - gentity_t *traceEnt; +qboolean CanShoot(gentity_t *ent, gentity_t *shooter) { + trace_t tr; + vec3_t muzzle; + vec3_t spot, diff; + gentity_t *traceEnt; - CalcEntitySpot( shooter, SPOT_WEAPON, muzzle ); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); //FIXME preferred target locations for some weapons (feet for R/L) + CalcEntitySpot(shooter, SPOT_WEAPON, muzzle); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); // FIXME preferred target locations for some weapons (feet for R/L) - gi.trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; + gi.trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + traceEnt = &g_entities[tr.entityNum]; // point blank, baby! - if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer) ) - { + if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer)) { traceEnt = shooter->NPC->touchedByPlayer; } - - if ( ShotThroughGlass( &tr, ent, spot, MASK_SHOT ) ) - { - traceEnt = &g_entities[ tr.entityNum ]; + + if (ShotThroughGlass(&tr, ent, spot, MASK_SHOT)) { + traceEnt = &g_entities[tr.entityNum]; } // shot is dead on - if ( traceEnt == ent ) - { + if (traceEnt == ent) { return qtrue; } -//MCG - Begin - else - {//ok, can't hit them in center, try their head - CalcEntitySpot( ent, SPOT_HEAD, spot ); - gi.trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; - if ( traceEnt == ent) - { + // MCG - Begin + else { // ok, can't hit them in center, try their head + CalcEntitySpot(ent, SPOT_HEAD, spot); + gi.trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + traceEnt = &g_entities[tr.entityNum]; + if (traceEnt == ent) { return qtrue; } } - //Actually, we should just check to fire in dir we're facing and if it's close enough, - //and we didn't hit someone on our own team, shoot + // Actually, we should just check to fire in dir we're facing and if it's close enough, + // and we didn't hit someone on our own team, shoot VectorSubtract(spot, tr.endpos, diff); - if(VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) - { + if (VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) { return qtrue; } -//MCG - End - // shot would hit a non-client - if ( !traceEnt->client ) - { + // MCG - End + // shot would hit a non-client + if (!traceEnt->client) { return qfalse; } // shot is blocked by another player // he's already dead, so go ahead - if ( traceEnt->health <= 0 ) - { + if (traceEnt->health <= 0) { return qtrue; } // don't deliberately shoot a teammate - if ( traceEnt->client && ( traceEnt->client->playerTeam == shooter->client->playerTeam ) ) - { + if (traceEnt->client && (traceEnt->client->playerTeam == shooter->client->playerTeam)) { return qfalse; } @@ -1128,62 +970,51 @@ qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) return qtrue; } - /* -void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) +void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) Added: hacks for scripted NPCs */ -void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) -{ +void NPC_CheckPossibleEnemy(gentity_t *other, visibility_t vis) { // is he is already our enemy? - if ( other == NPC->enemy ) + if (other == NPC->enemy) return; - if ( other->flags & FL_NOTARGET ) + if (other->flags & FL_NOTARGET) return; // we already have an enemy and this guy is in our FOV, see if this guy would be better - if ( NPC->enemy && vis == VIS_FOV ) - { - if ( NPCInfo->enemyLastSeenTime - level.time < 2000 ) - { + if (NPC->enemy && vis == VIS_FOV) { + if (NPCInfo->enemyLastSeenTime - level.time < 2000) { return; } - if ( enemyVisibility == VIS_UNKNOWN ) - { - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_360|CHECK_FOV ); + if (enemyVisibility == VIS_UNKNOWN) { + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_360 | CHECK_FOV); } - if ( enemyVisibility == VIS_FOV ) - { + if (enemyVisibility == VIS_FOV) { return; } } - if ( !NPC->enemy ) - {//only take an enemy if you don't have one yet - G_SetEnemy( NPC, other ); + if (!NPC->enemy) { // only take an enemy if you don't have one yet + G_SetEnemy(NPC, other); } - if ( vis == VIS_FOV ) - { + if (vis == VIS_FOV) { NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( other->currentOrigin, NPCInfo->enemyLastSeenLocation ); + VectorCopy(other->currentOrigin, NPCInfo->enemyLastSeenLocation); NPCInfo->enemyLastHeardTime = 0; - VectorClear( NPCInfo->enemyLastHeardLocation ); - } - else - { + VectorClear(NPCInfo->enemyLastHeardLocation); + } else { NPCInfo->enemyLastSeenTime = 0; - VectorClear( NPCInfo->enemyLastSeenLocation ); + VectorClear(NPCInfo->enemyLastSeenLocation); NPCInfo->enemyLastHeardTime = level.time; - VectorCopy( other->currentOrigin, NPCInfo->enemyLastHeardLocation ); + VectorCopy(other->currentOrigin, NPCInfo->enemyLastHeardLocation); } } - //========================================== -//MCG Added functions: +// MCG Added functions: //========================================== /* @@ -1193,94 +1024,83 @@ DOES NOT control how fast you can fire Only makes you keep your weapon up after you fire */ -int NPC_AttackDebounceForWeapon (void) -{ - switch ( NPC->client->ps.weapon ) - { -/* - case WP_BLASTER://scav rifle - return 1000; - break; +int NPC_AttackDebounceForWeapon(void) { + switch (NPC->client->ps.weapon) { + /* + case WP_BLASTER://scav rifle + return 1000; + break; - case WP_BRYAR_PISTOL://prifle - return 3000; - break; + case WP_BRYAR_PISTOL://prifle + return 3000; + break; - case WP_SABER: - return 100; - break; -*/ + case WP_SABER: + return 100; + break; + */ case WP_SABER: return 0; break; case WP_BOT_LASER: - - if ( g_spskill->integer == 0 ) + + if (g_spskill->integer == 0) return 2000; - if ( g_spskill->integer == 1 ) + if (g_spskill->integer == 1) return 1500; return 1000; break; default: - return NPCInfo->burstSpacing;//was 100 by default + return NPCInfo->burstSpacing; // was 100 by default break; } } -//FIXME: need a mindist for explosive weapons -float NPC_MaxDistSquaredForWeapon (void) -{ - if(NPCInfo->stats.shootDistance > 0) - {//overrides default weapon dist +// FIXME: need a mindist for explosive weapons +float NPC_MaxDistSquaredForWeapon(void) { + if (NPCInfo->stats.shootDistance > 0) { // overrides default weapon dist return NPCInfo->stats.shootDistance * NPCInfo->stats.shootDistance; } - switch ( NPC->s.weapon ) - { - case WP_BLASTER://scav rifle - return 1024 * 1024;//should be shorter? + switch (NPC->s.weapon) { + case WP_BLASTER: // scav rifle + return 1024 * 1024; // should be shorter? break; - case WP_BRYAR_PISTOL://prifle + case WP_BRYAR_PISTOL: // prifle return 1024 * 1024; break; - case WP_BLASTER_PISTOL://prifle + case WP_BLASTER_PISTOL: // prifle return 1024 * 1024; break; - case WP_DISRUPTOR://disruptor - if ( NPCInfo->scriptFlags & SCF_ALT_FIRE ) - { - return ( 4096 * 4096 ); - } - else - { + case WP_DISRUPTOR: // disruptor + if (NPCInfo->scriptFlags & SCF_ALT_FIRE) { + return (4096 * 4096); + } else { return 1024 * 1024; } break; -/* - case WP_SABER: - return 1024 * 1024; - break; -*/ + /* + case WP_SABER: + return 1024 * 1024; + break; + */ case WP_SABER: - if ( NPC->client && NPC->client->ps.saberLength ) - {//FIXME: account for whether enemy and I are heading towards each other! - return (NPC->client->ps.saberLength + NPC->maxs[0]*1.5)*(NPC->client->ps.saberLength + NPC->maxs[0]*1.5); - } - else - { - return 48*48; + if (NPC->client && NPC->client->ps.saberLength) { // FIXME: account for whether enemy and I are heading towards each other! + return (NPC->client->ps.saberLength + NPC->maxs[0] * 1.5) * (NPC->client->ps.saberLength + NPC->maxs[0] * 1.5); + } else { + return 48 * 48; } break; default: - return 1024 * 1024;//was 0 + return 1024 * 1024; // was 0 break; } } @@ -1291,28 +1111,22 @@ ValidEnemy ------------------------- */ -qboolean ValidEnemy(gentity_t *ent) -{ - if ( ent == NULL ) +qboolean ValidEnemy(gentity_t *ent) { + if (ent == NULL) return qfalse; - if ( ent == NPC ) + if (ent == NPC) return qfalse; - //if team_free, maybe everyone is an enemy? - if ( !NPC->client->enemyTeam ) + // if team_free, maybe everyone is an enemy? + if (!NPC->client->enemyTeam) return qfalse; - if ( !(ent->flags & FL_NOTARGET) ) - { - if( ent->health > 0 ) - { - if( !ent->client ) - { + if (!(ent->flags & FL_NOTARGET)) { + if (ent->health > 0) { + if (!ent->client) { return qtrue; - } - else if( ent->client->playerTeam == NPC->client->enemyTeam ) - { + } else if (ent->client->playerTeam == NPC->client->enemyTeam) { return qtrue; } } @@ -1321,27 +1135,21 @@ qboolean ValidEnemy(gentity_t *ent) return qfalse; } -qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) -{ - vec3_t vec; +qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) { + vec3_t vec; - - if ( !toShoot ) - {//Not trying to actually press fire button with this check - if ( NPC->client->ps.weapon == WP_SABER ) - {//Just have to get to him + if (!toShoot) { // Not trying to actually press fire button with this check + if (NPC->client->ps.weapon == WP_SABER) { // Just have to get to him return qfalse; } } - - if(!dist) - { + if (!dist) { VectorSubtract(NPC->currentOrigin, enemy->currentOrigin, vec); dist = VectorLengthSquared(vec); } - if(dist > NPC_MaxDistSquaredForWeapon()) + if (dist > NPC_MaxDistSquaredForWeapon()) return qtrue; return qfalse; @@ -1364,132 +1172,94 @@ You can mix and match any of those options (example: find closest visible player FIXME: this should go through the snapshot and find the closest enemy */ -gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest ) -{ - int num_choices = 0; - int choice[128];//FIXME: need a different way to determine how many choices? - gentity_t *newenemy = NULL; - gentity_t *closestEnemy = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = Q3_INFINITE; - qboolean failed = qfalse; - int visChecks = (CHECK_360|CHECK_FOV|CHECK_VISRANGE); - int minVis = VIS_FOV; - - if (!enemyTeam) - { +gentity_t *NPC_PickEnemy(gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest) { + int num_choices = 0; + int choice[128]; // FIXME: need a different way to determine how many choices? + gentity_t *newenemy = NULL; + gentity_t *closestEnemy = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = Q3_INFINITE; + qboolean failed = qfalse; + int visChecks = (CHECK_360 | CHECK_FOV | CHECK_VISRANGE); + int minVis = VIS_FOV; + + if (!enemyTeam) { return NULL; } - if ( NPCInfo->behaviorState == BS_STAND_AND_SHOOT || - NPCInfo->behaviorState == BS_HUNT_AND_KILL ) - {//Formations guys don't require inFov to pick up a target - //These other behavior states are active battle states and should not - //use FOV. FOV checks are for enemies who are patrolling, guarding, etc. + if (NPCInfo->behaviorState == BS_STAND_AND_SHOOT || NPCInfo->behaviorState == BS_HUNT_AND_KILL) { // Formations guys don't require inFov to pick up a target + // These other behavior states are active battle states and should not + // use FOV. FOV checks are for enemies who are patrolling, guarding, etc. visChecks &= ~CHECK_FOV; minVis = VIS_360; } - if( findPlayersFirst ) - {//try to find a player first + if (findPlayersFirst) { // try to find a player first newenemy = &g_entities[0]; - if( newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if( newenemy->health > 0 ) - { - if( enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || - ( enemyTeam == TEAM_PLAYER ) ) - {//FIXME: check for range and FOV or vis? - if( newenemy != NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if ( gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin) ) - { - if(NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) - { - if(!NPC->enemy) - { - if(!InVisrange(newenemy)) - { + if (newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if (enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || + (enemyTeam == TEAM_PLAYER)) { // FIXME: check for range and FOV or vis? + if (newenemy != NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) { + if (NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) { + if (!NPC->enemy) { + if (!InVisrange(newenemy)) { failed = qtrue; - } - else if(NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { failed = qtrue; } } } - if ( !failed ) - { - VectorSubtract( closestTo->currentOrigin, newenemy->currentOrigin, diff ); + if (!failed) { + VectorSubtract(closestTo->currentOrigin, newenemy->currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them failed = qtrue; + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { failed = qtrue; } - } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, + newenemy->targetname, newenemy->client->hiddenDist); } } - if(!failed) - { - if(findClosest) - { - if(relDist < bestDist) - { - if(!NPC_EnemyTooFar(newenemy, relDist, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (!failed) { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if(!NPC_EnemyTooFar(newenemy, 0, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) == VIS_FOV) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1502,14 +1272,12 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - if (findClosest && closestEnemy) - { + if (findClosest && closestEnemy) { return closestEnemy; } - if (num_choices) - { - return &g_entities[ choice[rand() % num_choices] ]; + if (num_choices) { + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1524,116 +1292,84 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis bestDist = Q3_INFINITE; closestEnemy = NULL; - for ( entNum = 0; entNum < globals.num_entities; entNum++ ) - { + for (entNum = 0; entNum < globals.num_entities; entNum++) { newenemy = &g_entities[entNum]; - if ( newenemy != NPC && (newenemy->client || newenemy->svFlags & SVF_NONNPC_ENEMY) && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if ( newenemy->health > 0 ) - { - if ( (newenemy->client && newenemy->client->playerTeam == enemyTeam) || (!newenemy->client && newenemy->noDamageTeam == enemyTeam) ) - {//FIXME: check for range and FOV or vis? - if ( NPC->client->playerTeam == TEAM_PLAYER && enemyTeam == TEAM_PLAYER ) - {//player allies turning on ourselves? How? - if ( newenemy->s.number ) - {//only turn on the player, not other player allies + if (newenemy != NPC && (newenemy->client || newenemy->svFlags & SVF_NONNPC_ENEMY) && !(newenemy->flags & FL_NOTARGET) && + !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if ((newenemy->client && newenemy->client->playerTeam == enemyTeam) || + (!newenemy->client && newenemy->noDamageTeam == enemyTeam)) { // FIXME: check for range and FOV or vis? + if (NPC->client->playerTeam == TEAM_PLAYER && enemyTeam == TEAM_PLAYER) { // player allies turning on ourselves? How? + if (newenemy->s.number) { // only turn on the player, not other player allies continue; } } - if ( newenemy != NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if(!gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) - { + if (newenemy != NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (!gi.inPVS(newenemy->currentOrigin, NPC->currentOrigin)) { continue; } - if ( NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL ) - { - if ( !NPC->enemy ) - { - if ( !InVisrange( newenemy ) ) - { + if (NPCInfo->behaviorState == BS_INVESTIGATE || NPCInfo->behaviorState == BS_PATROL) { + if (!NPC->enemy) { + if (!InVisrange(newenemy)) { continue; - } - else if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV ) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { continue; } } } - VectorSubtract( closestTo->currentOrigin, newenemy->currentOrigin, diff ); + VectorSubtract(closestTo->currentOrigin, newenemy->currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client && newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client && newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them continue; + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { continue; } - } - else - { - Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(debugNPCAI, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPC->targetname, newenemy->targetname, + newenemy->client->hiddenDist); } } - if ( findClosest ) - { - if ( relDist < bestDist ) - { - if ( !NPC_EnemyTooFar( newenemy, relDist, qfalse ) ) - { - if ( checkVis ) - { - //FIXME: NPCs need to be able to pick up other NPCs behind them, - //but for now, commented out because it was picking up enemies it shouldn't - //if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - if ( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + // FIXME: NPCs need to be able to pick up other NPCs behind them, + // but for now, commented out because it was picking up enemies it shouldn't + // if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if ( !NPC_EnemyTooFar( newenemy, 0, qfalse ) ) - { - if ( checkVis ) - { - //if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + // if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1643,18 +1379,15 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - - if (findClosest) - {//FIXME: you can pick up an enemy around a corner this way. + if (findClosest) { // FIXME: you can pick up an enemy around a corner this way. return closestEnemy; } - if (!num_choices) - { + if (!num_choices) { return NULL; } - return &g_entities[ choice[rand() % num_choices] ]; + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1663,84 +1396,69 @@ gentity_t *NPC_PickAlly ( void ) Simply returns closest visible ally */ -gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly ) -{ - gentity_t *ally = NULL; - gentity_t *closestAlly = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = range; - - for ( entNum = 0; entNum < globals.num_entities; entNum++ ) - { +gentity_t *NPC_PickAlly(qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly) { + gentity_t *ally = NULL; + gentity_t *closestAlly = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = range; + + for (entNum = 0; entNum < globals.num_entities; entNum++) { ally = &g_entities[entNum]; - if ( ally->client ) - { - if ( ally->health > 0 ) - { - if ( ally->client && ( ally->client->playerTeam == NPC->client->playerTeam || - NPC->client->playerTeam == TEAM_ENEMY ) )// && ally->client->playerTeam == TEAM_DISGUISE ) ) ) - {//if on same team or if player is disguised as your team - if ( ignoreGroup ) - { - if ( ally == NPC->client->leader ) - { - //reject + if (ally->client) { + if (ally->health > 0) { + if (ally->client && (ally->client->playerTeam == NPC->client->playerTeam || + NPC->client->playerTeam == TEAM_ENEMY)) // && ally->client->playerTeam == TEAM_DISGUISE ) ) ) + { // if on same team or if player is disguised as your team + if (ignoreGroup) { + if (ally == NPC->client->leader) { + // reject continue; } - if ( ally->client && ally->client->leader && ally->client->leader == NPC ) - { - //reject + if (ally->client && ally->client->leader && ally->client->leader == NPC) { + // reject continue; } } - if(!gi.inPVS(ally->currentOrigin, NPC->currentOrigin)) - { + if (!gi.inPVS(ally->currentOrigin, NPC->currentOrigin)) { continue; } - if ( movingOnly && ally->client && NPC->client ) - {//They have to be moving relative to each other - if ( !DistanceSquared( ally->client->ps.velocity, NPC->client->ps.velocity ) ) - { + if (movingOnly && ally->client && NPC->client) { // They have to be moving relative to each other + if (!DistanceSquared(ally->client->ps.velocity, NPC->client->ps.velocity)) { continue; } } - VectorSubtract( NPC->currentOrigin, ally->currentOrigin, diff ); - relDist = VectorNormalize( diff ); - if ( relDist < bestDist ) - { - if ( facingEachOther ) - { - vec3_t vf; - float dot; + VectorSubtract(NPC->currentOrigin, ally->currentOrigin, diff); + relDist = VectorNormalize(diff); + if (relDist < bestDist) { + if (facingEachOther) { + vec3_t vf; + float dot; - AngleVectors( ally->client->ps.viewangles, vf, NULL, NULL ); + AngleVectors(ally->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot < 0.5 ) - {//Not facing in dir to me + if (dot < 0.5) { // Not facing in dir to me continue; } - //He's facing me, am I facing him? - AngleVectors( NPC->client->ps.viewangles, vf, NULL, NULL ); + // He's facing me, am I facing him? + AngleVectors(NPC->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot > -0.5 ) - {//I'm not facing opposite of dir to me + if (dot > -0.5) { // I'm not facing opposite of dir to me continue; } - //I am facing him + // I am facing him } - if ( NPC_CheckVisibility ( ally, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + if (NPC_CheckVisibility(ally, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { bestDist = relDist; closestAlly = ally; } @@ -1750,88 +1468,70 @@ gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignore } } - return closestAlly; } -gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnemy ) -{ - qboolean forcefindNew = qfalse; - gentity_t *closestTo; - gentity_t *newEnemy = NULL; - //FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot - //someone we can't hit? Rather than hard-coded 10? +gentity_t *NPC_CheckEnemy(qboolean findNew, qboolean tooFarOk, qboolean setEnemy) { + qboolean forcefindNew = qfalse; + gentity_t *closestTo; + gentity_t *newEnemy = NULL; + // FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot + // someone we can't hit? Rather than hard-coded 10? - //FIXME they shouldn't recognize enemy's death instantly + // FIXME they shouldn't recognize enemy's death instantly - //TEMP FIX: - //if(NPC->enemy->client) + // TEMP FIX: + // if(NPC->enemy->client) //{ // NPC->enemy->health = NPC->enemy->client->ps.stats[STAT_HEALTH]; - //} + // } - if ( NPC->enemy ) - { - if ( !NPC->enemy->inuse )//|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! + if (NPC->enemy) { + if (!NPC->enemy->inuse) //|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (setEnemy) { + G_ClearEnemy(NPC); } } } - if ( NPC->svFlags & SVF_IGNORE_ENEMIES ) - {//We're ignoring all enemies for now - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (NPC->svFlags & SVF_IGNORE_ENEMIES) { // We're ignoring all enemies for now + if (setEnemy) { + G_ClearEnemy(NPC); } return NULL; } - if ( NPC->svFlags & SVF_LOCKEDENEMY ) - {//keep this enemy until dead - if ( NPC->enemy ) - { - if ( (!NPC->NPC && !(NPC->svFlags & SVF_NONNPC_ENEMY) ) || NPC->enemy->health > 0 ) - {//Enemy never had health (a train or info_not_null, etc) or did and is now dead (NPCs, turrets, etc) + if (NPC->svFlags & SVF_LOCKEDENEMY) { // keep this enemy until dead + if (NPC->enemy) { + if ((!NPC->NPC && !(NPC->svFlags & SVF_NONNPC_ENEMY)) || + NPC->enemy->health > 0) { // Enemy never had health (a train or info_not_null, etc) or did and is now dead (NPCs, turrets, etc) return NULL; } } NPC->svFlags &= ~SVF_LOCKEDENEMY; } - if ( NPC->enemy ) - { - if ( NPC_EnemyTooFar(NPC->enemy, 0, qfalse) ) - { - if(findNew) - {//See if there is a close one and take it if so, else keep this one + if (NPC->enemy) { + if (NPC_EnemyTooFar(NPC->enemy, 0, qfalse)) { + if (findNew) { // See if there is a close one and take it if so, else keep this one forcefindNew = qtrue; - } - else if(!tooFarOk)//FIXME: don't need this extra bool any more + } else if (!tooFarOk) // FIXME: don't need this extra bool any more { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (setEnemy) { + G_ClearEnemy(NPC); } } - } - else if ( !gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin ) ) - {//FIXME: should this be a line-of site check? - //FIXME: a lot of things check PVS AGAIN when deciding whether - //or not to shoot, redundant! - //Should we lose the enemy? - //FIXME: if lose enemy, run lostenemyscript - if ( NPC->enemy->client && NPC->enemy->client->hiddenDist ) - {//He ducked into shadow while we weren't looking - //Drop enemy and see if we should search for him + } else if (!gi.inPVS(NPC->currentOrigin, NPC->enemy->currentOrigin)) { // FIXME: should this be a line-of site check? + // FIXME: a lot of things check PVS AGAIN when deciding whether + // or not to shoot, redundant! + // Should we lose the enemy? + // FIXME: if lose enemy, run lostenemyscript + if (NPC->enemy->client && NPC->enemy->client->hiddenDist) { // He ducked into shadow while we weren't looking + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); - } - else - {//If we're not chasing him, we need to lose him - //NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up + } else { // If we're not chasing him, we need to lose him + // NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up /* switch( NPCInfo->behaviorState ) @@ -1857,101 +1557,80 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem } } - if ( NPC->enemy ) - { - if ( NPC->enemy->health <= 0 || NPC->enemy->flags & FL_NOTARGET ) - { - if ( setEnemy ) - { - G_ClearEnemy( NPC ); + if (NPC->enemy) { + if (NPC->enemy->health <= 0 || NPC->enemy->flags & FL_NOTARGET) { + if (setEnemy) { + G_ClearEnemy(NPC); } } } closestTo = NPC; - //FIXME: check your defendEnt, if you have one, see if their enemy is different - //than yours, or, if they don't have one, pick the closest enemy to THEM? - if ( NPCInfo->defendEnt ) - {//Trying to protect someone - if ( NPCInfo->defendEnt->health > 0 ) - {//Still alive, We presume we're close to them, navigation should handle this? - if ( NPCInfo->defendEnt->enemy ) - {//They were shot or acquired an enemy - if ( NPC->enemy != NPCInfo->defendEnt->enemy ) - {//They have a different enemy, take it! + // FIXME: check your defendEnt, if you have one, see if their enemy is different + // than yours, or, if they don't have one, pick the closest enemy to THEM? + if (NPCInfo->defendEnt) { // Trying to protect someone + if (NPCInfo->defendEnt->health > 0) { // Still alive, We presume we're close to them, navigation should handle this? + if (NPCInfo->defendEnt->enemy) { // They were shot or acquired an enemy + if (NPC->enemy != NPCInfo->defendEnt->enemy) { // They have a different enemy, take it! newEnemy = NPCInfo->defendEnt->enemy; - if ( setEnemy ) - { - G_SetEnemy( NPC, NPCInfo->defendEnt->enemy ); + if (setEnemy) { + G_SetEnemy(NPC, NPCInfo->defendEnt->enemy); } } - } - else if ( NPC->enemy == NULL ) - {//We don't have an enemy, so find closest to defendEnt + } else if (NPC->enemy == NULL) { // We don't have an enemy, so find closest to defendEnt closestTo = NPCInfo->defendEnt; } } } - if (!NPC->enemy || ( NPC->enemy && NPC->enemy->health <= 0 ) || forcefindNew ) - {//FIXME: NPCs that are moving after an enemy should ignore the can't hit enemy counter- that should only be for NPCs that are standing still - //NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full + if (!NPC->enemy || (NPC->enemy && NPC->enemy->health <= 0) || forcefindNew) { // FIXME: NPCs that are moving after an enemy should ignore the can't hit + // enemy counter- that should only be for NPCs that are standing still + // NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full // 10 seconds, so give up. This means even if we're chasing him, we would // try to find another enemy after 10 seconds (assuming the cantHitEnemyCounter // is allowed to increment in a chasing bState) - qboolean foundenemy = qfalse; + qboolean foundenemy = qfalse; - if(!findNew) - { - if ( setEnemy ) - { + if (!findNew) { + if (setEnemy) { NPC->lastEnemy = NPC->enemy; G_ClearEnemy(NPC); } return NULL; } - //If enemy dead or unshootable, look for others on out enemy's team - if ( NPC->client->enemyTeam ) - { - //NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose + // If enemy dead or unshootable, look for others on out enemy's team + if (NPC->client->enemyTeam) { + // NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose // means they need to find one that in more than just PVS - //newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - //For now, made it so you ALWAYS have to check VIS - newEnemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, qtrue, qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - if ( newEnemy ) - { + // newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == + // TEAM_STARFLEET) For now, made it so you ALWAYS have to check VIS + newEnemy = NPC_PickEnemy(closestTo, NPC->client->enemyTeam, qtrue, qfalse, qtrue); // 3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) + if (newEnemy) { foundenemy = qtrue; - if ( setEnemy ) - { - G_SetEnemy( NPC, newEnemy ); + if (setEnemy) { + G_SetEnemy(NPC, newEnemy); } } } - - if ( !forcefindNew ) - { - if ( !foundenemy ) - { - if ( setEnemy ) - { + + if (!forcefindNew) { + if (!foundenemy) { + if (setEnemy) { NPC->lastEnemy = NPC->enemy; G_ClearEnemy(NPC); } } - + NPC->cantHitEnemyCounter = 0; } - //FIXME: if we can't find any at all, go into INdependant NPC AI, pursue and kill + // FIXME: if we can't find any at all, go into INdependant NPC AI, pursue and kill } - if ( NPC->enemy && NPC->enemy->client ) - { - if(NPC->enemy->client->playerTeam) - { -// assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); - if( NPC->client->playerTeam != NPC->enemy->client->playerTeam ) - { + if (NPC->enemy && NPC->enemy->client) { + if (NPC->enemy->client->playerTeam) { + // assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); + if (NPC->client->playerTeam != NPC->enemy->client->playerTeam) { NPC->client->enemyTeam = NPC->enemy->client->playerTeam; } } @@ -1965,39 +1644,35 @@ NPC_ClearShot ------------------------- */ -qboolean NPC_ClearShot( gentity_t *ent ) -{ - if ( ( NPC == NULL ) || ( ent == NULL ) ) +qboolean NPC_ClearShot(gentity_t *ent) { + if ((NPC == NULL) || (ent == NULL)) return qfalse; - vec3_t muzzle; - trace_t tr; + vec3_t muzzle; + trace_t tr; - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - gi.trace ( &tr, muzzle, mins, maxs, ent->currentOrigin, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - } - else - { - gi.trace ( &tr, muzzle, NULL, NULL, ent->currentOrigin, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, muzzle, mins, maxs, ent->currentOrigin, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + } else { + gi.trace(&tr, muzzle, NULL, NULL, ent->currentOrigin, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); } - - if ( tr.startsolid || tr.allsolid ) - { + + if (tr.startsolid || tr.allsolid) { return qfalse; } - if ( tr.entityNum == ent->s.number ) + if (tr.entityNum == ent->s.number) return qtrue; - + return qfalse; } @@ -2007,71 +1682,62 @@ NPC_ShotEntity ------------------------- */ -int NPC_ShotEntity( gentity_t *ent, vec3_t impactPos ) -{ - if ( ( NPC == NULL ) || ( ent == NULL ) ) +int NPC_ShotEntity(gentity_t *ent, vec3_t impactPos) { + if ((NPC == NULL) || (ent == NULL)) return qfalse; - vec3_t muzzle; + vec3_t muzzle; vec3_t targ; - trace_t tr; + trace_t tr; - if ( NPC->s.weapon == WP_THERMAL ) - {//thermal aims from slightly above head - //FIXME: what about low-angle shots, rolling the thermal under something? - vec3_t angles, forward, end; + if (NPC->s.weapon == WP_THERMAL) { // thermal aims from slightly above head + // FIXME: what about low-angle shots, rolling the thermal under something? + vec3_t angles, forward, end; - CalcEntitySpot( NPC, SPOT_HEAD, muzzle ); - VectorSet( angles, 0, NPC->client->ps.viewangles[1], 0 ); - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( muzzle, 8, forward, end ); + CalcEntitySpot(NPC, SPOT_HEAD, muzzle); + VectorSet(angles, 0, NPC->client->ps.viewangles[1], 0); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(muzzle, 8, forward, end); end[2] += 24; - gi.trace ( &tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - VectorCopy( tr.endpos, muzzle ); + gi.trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + VectorCopy(tr.endpos, muzzle); + } else { + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); } - else - { - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - } - CalcEntitySpot( ent, SPOT_CHEST, targ ); - + CalcEntitySpot(ent, SPOT_CHEST, targ); + // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPC->s.weapon == WP_BLASTER || NPC->s.weapon == WP_BLASTER_PISTOL) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - gi.trace ( &tr, muzzle, mins, maxs, targ, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, muzzle, mins, maxs, targ, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + } else { + gi.trace(&tr, muzzle, NULL, NULL, targ, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); } - else - { - gi.trace ( &tr, muzzle, NULL, NULL, targ, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - } - //FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? - if ( impactPos ) - {//they want to know *where* the hit would be, too - VectorCopy( tr.endpos, impactPos ); - } -/* // NPCs should be able to shoot even if the muzzle would be inside their target - if ( tr.startsolid || tr.allsolid ) - { - return ENTITYNUM_NONE; + // FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? + if (impactPos) { // they want to know *where* the hit would be, too + VectorCopy(tr.endpos, impactPos); } -*/ + /* // NPCs should be able to shoot even if the muzzle would be inside their target + if ( tr.startsolid || tr.allsolid ) + { + return ENTITYNUM_NONE; + } + */ return tr.entityNum; } -qboolean NPC_EvaluateShot( int hit, qboolean glassOK ) -{ - if ( !NPC->enemy ) - { +qboolean NPC_EvaluateShot(int hit, qboolean glassOK) { + if (!NPC->enemy) { return qfalse; } - if ( hit == NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -2083,17 +1749,15 @@ NPC_CheckAttack Simply checks aggression and returns true or false */ -qboolean NPC_CheckAttack (float scale) -{ - if(!scale) +qboolean NPC_CheckAttack(float scale) { + if (!scale) scale = 1.0; - if(((float)NPCInfo->stats.aggression) * scale < Q_flrand(0, 4)) - { + if (((float)NPCInfo->stats.aggression) * scale < Q_flrand(0, 4)) { return qfalse; } - if(NPCInfo->shotTime > level.time) + if (NPCInfo->shotTime > level.time) return qfalse; return qtrue; @@ -2105,93 +1769,81 @@ NPC_CheckDefend Simply checks evasion and returns true or false */ -qboolean NPC_CheckDefend (float scale) -{ - if(!scale) +qboolean NPC_CheckDefend(float scale) { + if (!scale) scale = 1.0; - if((float)(NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) + if ((float)(NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) return qtrue; return qfalse; } - -//NOTE: BE SURE TO CHECK PVS BEFORE THIS! -qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) -{ - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org;//, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; -// qboolean duck_ok = qfalse; - qboolean dead_on = qfalse; - float aim_off; - float max_aim_off = 128 - (16 * (float)NPCInfo->stats.aim); - trace_t tr; - gentity_t *traceEnt = NULL; - - if(NPC->enemy->flags & FL_NOTARGET) - { +// NOTE: BE SURE TO CHECK PVS BEFORE THIS! +qboolean NPC_CheckCanAttack(float attack_scale, qboolean stationary) { + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org; //, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + // qboolean duck_ok = qfalse; + qboolean dead_on = qfalse; + float aim_off; + float max_aim_off = 128 - (16 * (float)NPCInfo->stats.aim); + trace_t tr; + gentity_t *traceEnt = NULL; + + if (NPC->enemy->flags & FL_NOTARGET) { return qfalse; } - //FIXME: only check to see if should duck if that provides cover from the - //enemy!!! - if(!attack_scale) - { + // FIXME: only check to see if should duck if that provides cover from the + // enemy!!! + if (!attack_scale) { attack_scale = 1.0; } - //Yaw to enemy - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + // Yaw to enemy + CalcEntitySpot(NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); + + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); NPC->NPC->desiredYaw = angleToEnemy[YAW]; NPC_UpdateFiringAngles(qfalse, qtrue); - if( NPC_EnemyTooFar(NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue) ) - {//Too far away? Do not attack + if (NPC_EnemyTooFar(NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { // Too far away? Do not attack return qfalse; } - if(client->fireDelay > 0) - {//already waiting for a shot to fire + if (client->fireDelay > 0) { // already waiting for a shot to fire NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); return qfalse; } - if(NPCInfo->scriptFlags & SCF_DONT_FIRE) - { + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) { return qfalse; } NPCInfo->enemyLastVisibility = enemyVisibility; - //See if they're in our FOV and we have a clear shot to them - enemyVisibility = NPC_CheckVisibility ( NPC->enemy, CHECK_360|CHECK_FOV);////CHECK_PVS| + // See if they're in our FOV and we have a clear shot to them + enemyVisibility = NPC_CheckVisibility(NPC->enemy, CHECK_360 | CHECK_FOV); ////CHECK_PVS| - if(enemyVisibility >= VIS_FOV) - {//He's in our FOV - - attack_ok = qtrue; - //CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + if (enemyVisibility >= VIS_FOV) { // He's in our FOV - //Check to duck - if ( NPC->enemy->client ) - { - if ( NPC->enemy->enemy == NPC ) - { - if ( NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? - {//duck and don't shoot + attack_ok = qtrue; + // CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + + // Check to duck + if (NPC->enemy->client) { + if (NPC->enemy->enemy == NPC) { + if (NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? + { // duck and don't shoot attack_ok = qfalse; ucmd.upmove = -127; } @@ -2199,14 +1851,13 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if(attack_ok) - { - //are we gonna hit him - //NEW: use actual forward facing - AngleVectors( client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, distanceToEnemy, forward, hitspot ); - gi.trace( &tr, muzzle, NULL, NULL, hitspot, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - ShotThroughGlass( &tr, NPC->enemy, hitspot, MASK_SHOT ); + if (attack_ok) { + // are we gonna hit him + // NEW: use actual forward facing + AngleVectors(client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); + gi.trace(&tr, muzzle, NULL, NULL, hitspot, NPC->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + ShotThroughGlass(&tr, NPC->enemy, hitspot, MASK_SHOT); /* //OLD: trace regardless of facing gi.trace ( &tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT ); @@ -2231,21 +1882,15 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } */ - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPC->enemy || (traceEnt->client && NPC->client->enemyTeam && NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -2253,75 +1898,60 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - if(traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) - {//easy to kill - go for it - if(traceEnt->e_DieFunc == dieF_ExplodeDeath_Wait && traceEnt->splashDamage) - {//going to explode, don't shoot if close to self + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + if (traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) { // easy to kill - go for it + if (traceEnt->e_DieFunc == dieF_ExplodeDeath_Wait && traceEnt->splashDamage) { // going to explode, don't shoot if close to self VectorSubtract(NPC->currentOrigin, traceEnt->currentOrigin, diff); - if(VectorLengthSquared(diff) < traceEnt->splashRadius*traceEnt->splashRadius) - {//Too close to shoot! + if (VectorLengthSquared(diff) < traceEnt->splashRadius * traceEnt->splashRadius) { // Too close to shoot! attack_ok = qfalse; - } - else - {//Hey, it might kill him, do it! - attack_scale *= 2;// + } else { // Hey, it might kill him, do it! + attack_scale *= 2; // } } - } - else - { - AngleVectors (client->ps.viewangles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + } else { + AngleVectors(client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } - } - else - {//Update pitch anyway + } else { // Update pitch anyway NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); - } - else + } else attack_ok = qfalse; } return attack_ok; } //======================================================================================== -//OLD id-style hunt and kill +// OLD id-style hunt and kill //======================================================================================== /* IdealDistance @@ -2329,13 +1959,11 @@ IdealDistance determines what the NPC's ideal distance from it's enemy should be in the current situation */ -float IdealDistance ( gentity_t *self ) -{ - float ideal; +float IdealDistance(gentity_t *self) { + float ideal; ideal = 225 - 20 * NPCInfo->stats.aggression; - switch ( NPC->s.weapon ) - { + switch (NPC->s.weapon) { case WP_ROCKET_LAUNCHER: ideal += 200; break; @@ -2366,12 +1994,10 @@ LEAN - Lean-type cover, NOT IMPLEMENTED SNIPE - Snipers look for these first, NOT IMPLEMENTED */ -void SP_point_combat( gentity_t *self ) -{ - if(level.numCombatPoints >= MAX_COMBAT_POINTS) - { +void SP_point_combat(gentity_t *self) { + if (level.numCombatPoints >= MAX_COMBAT_POINTS) { #ifndef FINAL_BUILD - gi.Printf(S_COLOR_RED"ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); + gi.Printf(S_COLOR_RED "ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); #endif G_FreeEntity(self); return; @@ -2381,15 +2007,14 @@ void SP_point_combat( gentity_t *self ) G_SetOrigin(self, self->s.origin); gi.linkentity(self); - if ( G_CheckInSolid( self, qtrue ) ) - { + if (G_CheckInSolid(self, qtrue)) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"ERROR: combat point at %s in solid!\n", vtos(self->currentOrigin) ); + gi.Printf(S_COLOR_RED "ERROR: combat point at %s in solid!\n", vtos(self->currentOrigin)); #endif } - VectorCopy( self->currentOrigin, level.combatPoints[level.numCombatPoints].origin ); - + VectorCopy(self->currentOrigin, level.combatPoints[level.numCombatPoints].origin); + level.combatPoints[level.numCombatPoints].flags = self->spawnflags; level.combatPoints[level.numCombatPoints].occupied = qfalse; @@ -2398,78 +2023,66 @@ void SP_point_combat( gentity_t *self ) G_FreeEntity(self); }; -void CP_FindCombatPointWaypoints( void ) -{ - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - level.combatPoints[i].waypoint = NAV_FindClosestWaypointForPoint( level.combatPoints[i].origin ); +void CP_FindCombatPointWaypoints(void) { + for (int i = 0; i < level.numCombatPoints; i++) { + level.combatPoints[i].waypoint = NAV_FindClosestWaypointForPoint(level.combatPoints[i].origin); #ifndef FINAL_BUILD - if ( level.combatPoints[i].waypoint == WAYPOINT_NONE ) - { - gi.Printf( S_COLOR_RED"ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin) ); + if (level.combatPoints[i].waypoint == WAYPOINT_NONE) { + gi.Printf(S_COLOR_RED "ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin)); } #endif } } - /* ------------------------- NPC_CollectCombatPoints ------------------------- */ -typedef std::map< float, int > combatPoint_m; +typedef std::map combatPoint_m; -static int NPC_CollectCombatPoints( const vec3_t origin, const float radius, combatPoint_m &points, const int flags ) -{ - float radiusSqr = (radius*radius); - float distance; +static int NPC_CollectCombatPoints(const vec3_t origin, const float radius, combatPoint_m &points, const int flags) { + float radiusSqr = (radius * radius); + float distance; - //Collect all nearest - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - //Must be vacant - if ( level.combatPoints[i].occupied == (int) qtrue ) + // Collect all nearest + for (int i = 0; i < level.numCombatPoints; i++) { + // Must be vacant + if (level.combatPoints[i].occupied == (int)qtrue) continue; - //If we want a duck space, make sure this is one - if ( ( flags & CP_DUCK ) && ( level.combatPoints[i].flags & CPF_DUCK ) ) + // If we want a duck space, make sure this is one + if ((flags & CP_DUCK) && (level.combatPoints[i].flags & CPF_DUCK)) continue; - //If we want a duck space, make sure this is one - if ( ( flags & CP_FLEE ) && ( level.combatPoints[i].flags & CPF_FLEE ) ) + // If we want a duck space, make sure this is one + if ((flags & CP_FLEE) && (level.combatPoints[i].flags & CPF_FLEE)) continue; - ///Make sure this is an investigate combat point - if ( ( flags & CP_INVESTIGATE ) && ( level.combatPoints[i].flags & CPF_INVESTIGATE ) ) + /// Make sure this is an investigate combat point + if ((flags & CP_INVESTIGATE) && (level.combatPoints[i].flags & CPF_INVESTIGATE)) continue; - - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) && ( ( flags & CP_SQUAD ) == qfalse ) ) + + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) && ((flags & CP_SQUAD) == qfalse)) continue; - if ( flags&CP_NO_PVS ) - {//must not be within PVS of mu current origin - if ( gi.inPVS( origin, level.combatPoints[i].origin ) ) - { + if (flags & CP_NO_PVS) { // must not be within PVS of mu current origin + if (gi.inPVS(origin, level.combatPoints[i].origin)) { continue; } } - if ( flags&CP_HORZ_DIST_COLL ) - { - distance = DistanceHorizontalSquared( origin, level.combatPoints[i].origin ); - } - else - { - distance = DistanceSquared( origin, level.combatPoints[i].origin ); + if (flags & CP_HORZ_DIST_COLL) { + distance = DistanceHorizontalSquared(origin, level.combatPoints[i].origin); + } else { + distance = DistanceSquared(origin, level.combatPoints[i].origin); } - if ( distance < radiusSqr ) - { - //Using a map will sort nearest automatically - points[ distance ] = i; + if (distance < radiusSqr) { + // Using a map will sort nearest automatically + points[distance] = i; } } @@ -2482,150 +2095,121 @@ NPC_FindCombatPoint ------------------------- */ -#define MIN_AVOID_DOT 0.75f -#define MIN_AVOID_DISTANCE 128 -#define MIN_AVOID_DISTANCE_SQUARED ( MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE ) -#define CP_COLLECT_RADIUS 512.0f +#define MIN_AVOID_DOT 0.75f +#define MIN_AVOID_DISTANCE 128 +#define MIN_AVOID_DISTANCE_SQUARED (MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE) +#define CP_COLLECT_RADIUS 512.0f -int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3_t enemyPosition, const int flags, float avoidDist, const int ignorePoint ) -{ - combatPoint_m points; - int best = -1, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE; - float dist; - trace_t tr; - float collRad = CP_COLLECT_RADIUS; +int NPC_FindCombatPoint(const vec3_t position, const vec3_t avoidPosition, vec3_t enemyPosition, const int flags, float avoidDist, const int ignorePoint) { + combatPoint_m points; + int best = -1, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE; + float dist; + trace_t tr; + float collRad = CP_COLLECT_RADIUS; - if ( avoidDist <= 0 ) - { + if (avoidDist <= 0) { avoidDist = MIN_AVOID_DISTANCE_SQUARED; - } - else - { + } else { avoidDist *= avoidDist; } - if ( (flags & CP_HAS_ROUTE) || (flags & CP_NEAREST) ) - {//going to be doing macro nav tests - if ( NPC->waypoint == WAYPOINT_NONE ) - { - waypoint = NAV_GetNearestNode( NPC, NPC->lastWaypoint ); - } - else - { + if ((flags & CP_HAS_ROUTE) || (flags & CP_NEAREST)) { // going to be doing macro nav tests + if (NPC->waypoint == WAYPOINT_NONE) { + waypoint = NAV_GetNearestNode(NPC, NPC->lastWaypoint); + } else { waypoint = NPC->waypoint; } } - //Collect our nearest points - if ( flags & CP_NO_PVS ) - {//much larger radius since most will be dropped? - collRad = CP_COLLECT_RADIUS*4; + // Collect our nearest points + if (flags & CP_NO_PVS) { // much larger radius since most will be dropped? + collRad = CP_COLLECT_RADIUS * 4; } - NPC_CollectCombatPoints( enemyPosition, collRad, points, flags );//position + NPC_CollectCombatPoints(enemyPosition, collRad, points, flags); // position - combatPoint_m::iterator cpi; - STL_ITERATE( cpi, points ) - { + combatPoint_m::iterator cpi; + STL_ITERATE(cpi, points) { const int i = (*cpi).second; - //Must not be one we want to ignore - if ( i == ignorePoint ) + // Must not be one we want to ignore + if (i == ignorePoint) continue; - //FIXME: able to mark certain ones as too dangerous to go to for now? Like a tripmine/thermal/detpack is near or something? - //If we need a cover point, check this point - if ( ( flags & CP_COVER ) && ( NPC_ClearLOS( level.combatPoints[i].origin, enemyPosition ) == qtrue ) )//Used to use NPC->enemy + // FIXME: able to mark certain ones as too dangerous to go to for now? Like a tripmine/thermal/detpack is near or something? + // If we need a cover point, check this point + if ((flags & CP_COVER) && (NPC_ClearLOS(level.combatPoints[i].origin, enemyPosition) == qtrue)) // Used to use NPC->enemy continue; - //Need a clear LOS to our target... and be within shot range to enemy position (FIXME: make this a separate CS_ flag? and pass in a range?) - if ( flags & CP_CLEAR ) - { - if ( NPC_ClearLOS( level.combatPoints[i].origin, NPC->enemy ) == qfalse ) - { + // Need a clear LOS to our target... and be within shot range to enemy position (FIXME: make this a separate CS_ flag? and pass in a range?) + if (flags & CP_CLEAR) { + if (NPC_ClearLOS(level.combatPoints[i].origin, NPC->enemy) == qfalse) { continue; } - if ( NPC->s.weapon == WP_THERMAL ) - {//horizontal - dist = DistanceHorizontalSquared( level.combatPoints[i].origin, NPC->enemy->currentOrigin ); + if (NPC->s.weapon == WP_THERMAL) { // horizontal + dist = DistanceHorizontalSquared(level.combatPoints[i].origin, NPC->enemy->currentOrigin); + } else { // actual + dist = DistanceSquared(level.combatPoints[i].origin, NPC->enemy->currentOrigin); } - else - {//actual - dist = DistanceSquared( level.combatPoints[i].origin, NPC->enemy->currentOrigin ); - } - if ( dist > (NPCInfo->stats.visrange*NPCInfo->stats.visrange) ) - { + if (dist > (NPCInfo->stats.visrange * NPCInfo->stats.visrange)) { continue; } } - //Avoid this position? - if ( ( flags & CP_AVOID ) && ( DistanceSquared( level.combatPoints[i].origin, position ) < avoidDist ) )//was using MIN_AVOID_DISTANCE_SQUARED, not passed in avoidDist + // Avoid this position? + if ((flags & CP_AVOID) && + (DistanceSquared(level.combatPoints[i].origin, position) < avoidDist)) // was using MIN_AVOID_DISTANCE_SQUARED, not passed in avoidDist continue; - //Try to find a point closer to the enemy than where we are - if ( flags & CP_APPROACH_ENEMY ) - { - if ( flags&CP_HORZ_DIST_COLL ) - { - if ( (*cpi).first > DistanceHorizontalSquared( position, enemyPosition ) ) - { + // Try to find a point closer to the enemy than where we are + if (flags & CP_APPROACH_ENEMY) { + if (flags & CP_HORZ_DIST_COLL) { + if ((*cpi).first > DistanceHorizontalSquared(position, enemyPosition)) { continue; } - } - else - { - if ( (*cpi).first > DistanceSquared( position, enemyPosition ) ) - { + } else { + if ((*cpi).first > DistanceSquared(position, enemyPosition)) { continue; } } } - //Try to find a point farther from the enemy than where we are - if ( flags & CP_RETREAT ) - { - if ( flags&CP_HORZ_DIST_COLL ) - { - if ( (*cpi).first < DistanceHorizontalSquared( position, enemyPosition ) ) - {//it's closer, don't use it + // Try to find a point farther from the enemy than where we are + if (flags & CP_RETREAT) { + if (flags & CP_HORZ_DIST_COLL) { + if ((*cpi).first < DistanceHorizontalSquared(position, enemyPosition)) { // it's closer, don't use it continue; } - } - else - { - if ( (*cpi).first < DistanceSquared( position, enemyPosition ) ) - {//it's closer, don't use it + } else { + if ((*cpi).first < DistanceSquared(position, enemyPosition)) { // it's closer, don't use it continue; } } } - //We want a point on other side of the enemy from current pos - if ( flags & CP_FLANK ) - { - vec3_t eDir2Me, eDir2CP; - - VectorSubtract( position, enemyPosition, eDir2Me ); - VectorNormalize( eDir2Me ); - - VectorSubtract( level.combatPoints[i].origin, enemyPosition, eDir2CP ); - VectorNormalize( eDir2CP ); - - const float dot = DotProduct( eDir2Me, eDir2CP ); - - //Not far enough behind enemy from current pos - if ( dot >= 0.4 ) + // We want a point on other side of the enemy from current pos + if (flags & CP_FLANK) { + vec3_t eDir2Me, eDir2CP; + + VectorSubtract(position, enemyPosition, eDir2Me); + VectorNormalize(eDir2Me); + + VectorSubtract(level.combatPoints[i].origin, enemyPosition, eDir2CP); + VectorNormalize(eDir2CP); + + const float dot = DotProduct(eDir2Me, eDir2CP); + + // Not far enough behind enemy from current pos + if (dot >= 0.4) continue; } - //See if we're trying to avoid our enemy - //FIXME: this needs to check for the waypoint you'll be taking to get to that combat point - if ( flags & CP_AVOID_ENEMY ) - { - vec3_t eDir, gDir; - vec3_t wpOrg; - - VectorSubtract( position, enemyPosition, eDir ); - VectorNormalize( eDir ); + // See if we're trying to avoid our enemy + // FIXME: this needs to check for the waypoint you'll be taking to get to that combat point + if (flags & CP_AVOID_ENEMY) { + vec3_t eDir, gDir; + vec3_t wpOrg; + + VectorSubtract(position, enemyPosition, eDir); + VectorNormalize(eDir); /* NAV_FindClosestWaypointForEnt( NPC, level.combatPoints[i].waypoint ); @@ -2635,33 +2219,29 @@ int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3 } else */ - { - VectorCopy( level.combatPoints[i].origin, wpOrg ); - } - VectorSubtract( position, wpOrg, gDir ); - VectorNormalize( gDir ); + { VectorCopy(level.combatPoints[i].origin, wpOrg); } + VectorSubtract(position, wpOrg, gDir); + VectorNormalize(gDir); + + float dot = DotProduct(gDir, eDir); - float dot = DotProduct( gDir, eDir ); - - //Don't want to run at enemy - if ( dot >= MIN_AVOID_DOT ) + // Don't want to run at enemy + if (dot >= MIN_AVOID_DOT) continue; - //Can't be too close to the enemy - if ( DistanceSquared( wpOrg, enemyPosition ) < avoidDist ) + // Can't be too close to the enemy + if (DistanceSquared(wpOrg, enemyPosition) < avoidDist) continue; } - - //Okay, now make sure it's not blocked - gi.trace( &tr, level.combatPoints[i].origin, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + + // Okay, now make sure it's not blocked + gi.trace(&tr, level.combatPoints[i].origin, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->s.number, NPC->clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { continue; } - //we must have a route to the combat point - if ( flags & CP_HAS_ROUTE ) - { + // we must have a route to the combat point + if (flags & CP_HAS_ROUTE) { /* if ( level.combatPoints[i].waypoint == WAYPOINT_NONE ) { @@ -2669,30 +2249,29 @@ int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3 } */ - if ( waypoint == WAYPOINT_NONE || level.combatPoints[i].waypoint == WAYPOINT_NONE || navigator.GetBestNodeAltRoute( waypoint, level.combatPoints[i].waypoint ) == WAYPOINT_NONE ) - {//can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one - if ( !NAV_ClearPathToPoint( NPC, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->clipmask, ENTITYNUM_NONE ) ) - {//don't even have a clear straight path to this one + if (waypoint == WAYPOINT_NONE || level.combatPoints[i].waypoint == WAYPOINT_NONE || + navigator.GetBestNodeAltRoute(waypoint, level.combatPoints[i].waypoint) == + WAYPOINT_NONE) { // can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one + if (!NAV_ClearPathToPoint(NPC, NPC->mins, NPC->maxs, level.combatPoints[i].origin, NPC->clipmask, + ENTITYNUM_NONE)) { // don't even have a clear straight path to this one continue; } } } - //We want the one with the shortest path from current pos - if ( flags & CP_NEAREST && waypoint != WAYPOINT_NONE && level.combatPoints[i].waypoint != WAYPOINT_NONE ) - { - cost = navigator.GetPathCost( waypoint, level.combatPoints[i].waypoint ); - if ( cost < bestCost ) - { + // We want the one with the shortest path from current pos + if (flags & CP_NEAREST && waypoint != WAYPOINT_NONE && level.combatPoints[i].waypoint != WAYPOINT_NONE) { + cost = navigator.GetPathCost(waypoint, level.combatPoints[i].waypoint); + if (cost < bestCost) { bestCost = cost; best = i; } continue; } - //we want the combat point closest to the enemy - //if ( flags & CP_CLOSEST ) - //they are sorted by this distance, so the first one to get this far is the closest + // we want the combat point closest to the enemy + // if ( flags & CP_CLOSEST ) + // they are sorted by this distance, so the first one to get this far is the closest return i; } @@ -2705,32 +2284,29 @@ NPC_FindSquadPoint ------------------------- */ -int NPC_FindSquadPoint( vec3_t position ) -{ - float dist, nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - int nearestPoint = -1; +int NPC_FindSquadPoint(vec3_t position) { + float dist, nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + int nearestPoint = -1; - //float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->currentOrigin ); + // float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->currentOrigin ); - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) == qfalse ) + for (int i = 0; i < level.numCombatPoints; i++) { + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) == qfalse) continue; - //Must be vacant - if ( level.combatPoints[i].occupied == qtrue ) + // Must be vacant + if (level.combatPoints[i].occupied == qtrue) continue; - - dist = DistanceSquared( position, level.combatPoints[i].origin ); - //The point cannot take us past the player - //if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this + dist = DistanceSquared(position, level.combatPoints[i].origin); + + // The point cannot take us past the player + // if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this // continue; - //See if this is closer than the others - if ( dist < nearestDist ) - { + // See if this is closer than the others + if (dist < nearestDist) { nearestPoint = i; nearestDist = dist; } @@ -2745,17 +2321,16 @@ NPC_ReserveCombatPoint ------------------------- */ -qboolean NPC_ReserveCombatPoint( int combatPointID ) -{ - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) +qboolean NPC_ReserveCombatPoint(int combatPointID) { + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's not already occupied - if ( level.combatPoints[combatPointID].occupied ) + // Make sure it's not already occupied + if (level.combatPoints[combatPointID].occupied) return qfalse; - //Reserve it + // Reserve it level.combatPoints[combatPointID].occupied = qtrue; return qtrue; @@ -2767,23 +2342,21 @@ NPC_FreeCombatPoint ------------------------- */ -qboolean NPC_FreeCombatPoint( int combatPointID, qboolean failed ) -{ - if ( failed ) - {//remember that this one failed for us +qboolean NPC_FreeCombatPoint(int combatPointID, qboolean failed) { + if (failed) { // remember that this one failed for us NPCInfo->lastFailedCombatPoint = combatPointID; } - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's currently occupied - if ( level.combatPoints[combatPointID].occupied == qfalse ) + // Make sure it's currently occupied + if (level.combatPoints[combatPointID].occupied == qfalse) return qfalse; - //Free it + // Free it level.combatPoints[combatPointID].occupied = qfalse; - + return qtrue; } @@ -2793,15 +2366,13 @@ NPC_SetCombatPoint ------------------------- */ -qboolean NPC_SetCombatPoint( int combatPointID ) -{ - //Free a combat point if we already have one - if ( NPCInfo->combatPoint != -1 ) - { - NPC_FreeCombatPoint( NPCInfo->combatPoint ); +qboolean NPC_SetCombatPoint(int combatPointID) { + // Free a combat point if we already have one + if (NPCInfo->combatPoint != -1) { + NPC_FreeCombatPoint(NPCInfo->combatPoint); } - if ( NPC_ReserveCombatPoint( combatPointID ) == qfalse ) + if (NPC_ReserveCombatPoint(combatPointID) == qfalse) return qfalse; NPCInfo->combatPoint = combatPointID; @@ -2809,55 +2380,45 @@ qboolean NPC_SetCombatPoint( int combatPointID ) return qtrue; } -extern qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ); -gentity_t *NPC_SearchForWeapons( void ) -{ +extern qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper); +gentity_t *NPC_SearchForWeapons(void) { gentity_t *found = g_entities, *bestFound = NULL; - float dist, bestDist = Q3_INFINITE; + float dist, bestDist = Q3_INFINITE; int i; -// for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) - for ( i = 0; iinuse ) -// { -// continue; -// } - if(!PInUse(i)) + // for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) + for (i = 0; i < globals.num_entities; i++) { + // if ( !found->inuse ) + // { + // continue; + // } + if (!PInUse(i)) continue; - - found=&g_entities[i]; - - //FIXME: Also look for ammo_racks that have weapons on them? - if ( found->s.eType != ET_ITEM ) - { + + found = &g_entities[i]; + + // FIXME: Also look for ammo_racks that have weapons on them? + if (found->s.eType != ET_ITEM) { continue; } - if ( found->item->giType != IT_WEAPON ) - { + if (found->item->giType != IT_WEAPON) { continue; } - if ( found->s.eFlags & EF_NODRAW ) - { + if (found->s.eFlags & EF_NODRAW) { continue; } - if ( CheckItemCanBePickedUpByNPC( found, NPC ) ) - { - if ( gi.inPVS( found->currentOrigin, NPC->currentOrigin ) ) - { - dist = DistanceSquared( found->currentOrigin, NPC->currentOrigin ); - if ( dist < bestDist ) - { - if ( !navigator.GetBestPathBetweenEnts( NPC, found, NF_CLEAR_PATH ) - || navigator.GetBestNodeAltRoute( NPC->waypoint, found->waypoint ) == WAYPOINT_NONE ) - {//can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one - if ( NAV_ClearPathToPoint( NPC, NPC->mins, NPC->maxs, found->currentOrigin, NPC->clipmask, ENTITYNUM_NONE ) ) - {//have a clear straight path to this one + if (CheckItemCanBePickedUpByNPC(found, NPC)) { + if (gi.inPVS(found->currentOrigin, NPC->currentOrigin)) { + dist = DistanceSquared(found->currentOrigin, NPC->currentOrigin); + if (dist < bestDist) { + if (!navigator.GetBestPathBetweenEnts(NPC, found, NF_CLEAR_PATH) || + navigator.GetBestNodeAltRoute(NPC->waypoint, found->waypoint) == + WAYPOINT_NONE) { // can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one + if (NAV_ClearPathToPoint(NPC, NPC->mins, NPC->maxs, found->currentOrigin, NPC->clipmask, + ENTITYNUM_NONE)) { // have a clear straight path to this one bestDist = dist; bestFound = found; } - } - else - {//can nav to it + } else { // can nav to it bestDist = dist; bestFound = found; } @@ -2869,37 +2430,29 @@ gentity_t *NPC_SearchForWeapons( void ) return bestFound; } -void NPC_SetPickUpGoal( gentity_t *foundWeap ) -{ +void NPC_SetPickUpGoal(gentity_t *foundWeap) { vec3_t org; - //NPCInfo->goalEntity = foundWeap; - VectorCopy( foundWeap->currentOrigin, org ); - org[2] += 24 - (foundWeap->mins[2]*-1);//adjust the origin so that I am on the ground - NPC_SetMoveGoal( NPC, org, foundWeap->maxs[0]*0.75, qfalse, -1, foundWeap ); + // NPCInfo->goalEntity = foundWeap; + VectorCopy(foundWeap->currentOrigin, org); + org[2] += 24 - (foundWeap->mins[2] * -1); // adjust the origin so that I am on the ground + NPC_SetMoveGoal(NPC, org, foundWeap->maxs[0] * 0.75, qfalse, -1, foundWeap); NPCInfo->tempGoal->waypoint = foundWeap->waypoint; NPCInfo->tempBehavior = BS_DEFAULT; NPCInfo->squadState = SQUAD_TRANSITION; } -void NPC_CheckGetNewWeapon( void ) -{ - if ( NPC->s.weapon == WP_NONE && NPC->enemy ) - {//if running away because dropped weapon... - if ( NPCInfo->goalEntity - && NPCInfo->goalEntity == NPCInfo->tempGoal - && NPCInfo->goalEntity->enemy - && !NPCInfo->goalEntity->enemy->inuse ) - {//maybe was running at a weapon that was picked up +void NPC_CheckGetNewWeapon(void) { + if (NPC->s.weapon == WP_NONE && NPC->enemy) { // if running away because dropped weapon... + if (NPCInfo->goalEntity && NPCInfo->goalEntity == NPCInfo->tempGoal && NPCInfo->goalEntity->enemy && + !NPCInfo->goalEntity->enemy->inuse) { // maybe was running at a weapon that was picked up NPCInfo->goalEntity = NULL; } - if ( TIMER_Done( NPC, "panic" ) && NPCInfo->goalEntity == NULL ) - {//need a weapon, any lying around? + if (TIMER_Done(NPC, "panic") && NPCInfo->goalEntity == NULL) { // need a weapon, any lying around? gentity_t *foundWeap = NPC_SearchForWeapons(); - if ( foundWeap ) - {//try to nav to it + if (foundWeap) { // try to nav to it /* - if ( !navigator.GetBestPathBetweenEnts( NPC, foundWeap, NF_CLEAR_PATH ) + if ( !navigator.GetBestPathBetweenEnts( NPC, foundWeap, NF_CLEAR_PATH ) || navigator.GetBestNodeAltRoute( NPC->waypoint, foundWeap->waypoint ) == WAYPOINT_NONE ) {//can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one if ( !NAV_ClearPathToPoint( NPC, NPC->mins, NPC->maxs, foundWeap->currentOrigin, NPC->clipmask, ENTITYNUM_NONE ) ) @@ -2912,55 +2465,45 @@ void NPC_CheckGetNewWeapon( void ) } else */ - { - NPC_SetPickUpGoal( foundWeap ); - } + { NPC_SetPickUpGoal(foundWeap); } } } } } -void NPC_AimAdjust( int change ) -{ - if ( !TIMER_Exists( NPC, "aimDebounce" ) ) - { - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_spskill->integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); +void NPC_AimAdjust(int change) { + if (!TIMER_Exists(NPC, "aimDebounce")) { + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); return; } - if ( TIMER_Done( NPC, "aimDebounce" ) ) - { + if (TIMER_Done(NPC, "aimDebounce")) { NPCInfo->currentAim += change; - if ( NPCInfo->currentAim > NPCInfo->stats.aim ) - {//can never be better than max aim + if (NPCInfo->currentAim > NPCInfo->stats.aim) { // can never be better than max aim NPCInfo->currentAim = NPCInfo->stats.aim; - } - else if ( NPCInfo->currentAim < -30 ) - {//can never be worse than this + } else if (NPCInfo->currentAim < -30) { // can never be worse than this NPCInfo->currentAim = -30; } - //Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); + // Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_spskill->integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); } } -void G_AimSet( gentity_t *self, int aim ) -{ - if ( self->NPC ) - { +void G_AimSet(gentity_t *self, int aim) { + if (self->NPC) { self->NPC->currentAim = aim; - //Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); + // Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); - int debounce = 500+(3-g_spskill->integer)*100; - TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - // int debounce = 1000+(3-g_spskill->integer)*500; - // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); + int debounce = 500 + (3 - g_spskill->integer) * 100; + TIMER_Set(self, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_spskill->integer)*500; + // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); } } diff --git a/codeJK2/game/NPC_goal.cpp b/codeJK2/game/NPC_goal.cpp index 6b79122e91..77e37dbfbb 100644 --- a/codeJK2/game/NPC_goal.cpp +++ b/codeJK2/game/NPC_goal.cpp @@ -25,87 +25,73 @@ along with this program; if not, see . #include "b_local.h" #include "Q3_Interface.h" -extern qboolean FlyingCreature( gentity_t *ent ); +extern qboolean FlyingCreature(gentity_t *ent); /* SetGoal */ -void SetGoal( gentity_t *goal, float rating ) -{ +void SetGoal(gentity_t *goal, float rating) { NPCInfo->goalEntity = goal; -// NPCInfo->goalEntityNeed = rating; + // NPCInfo->goalEntityNeed = rating; NPCInfo->goalTime = level.time; -// NAV_ClearLastRoute(NPC); - if ( goal ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); - } - else - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); + // NAV_ClearLastRoute(NPC); + if (goal) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); + } else { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); } } - /* NPC_SetGoal */ -void NPC_SetGoal( gentity_t *goal, float rating ) -{ - if ( goal == NPCInfo->goalEntity ) - { +void NPC_SetGoal(gentity_t *goal, float rating) { + if (goal == NPCInfo->goalEntity) { return; } - if ( !goal ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); + if (!goal) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); return; } - if ( goal->client ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); + if (goal->client) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); return; } - if ( NPCInfo->goalEntity ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); + if (NPCInfo->goalEntity) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); NPCInfo->lastGoalEntity = NPCInfo->goalEntity; -// NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; + // NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; } - SetGoal( goal, rating ); + SetGoal(goal, rating); } - /* NPC_ClearGoal */ -void NPC_ClearGoal( void ) -{ - gentity_t *goal; +void NPC_ClearGoal(void) { + gentity_t *goal; - if ( !NPCInfo->lastGoalEntity ) - { - SetGoal( NULL, 0.0 ); + if (!NPCInfo->lastGoalEntity) { + SetGoal(NULL, 0.0); return; } goal = NPCInfo->lastGoalEntity; NPCInfo->lastGoalEntity = NULL; -// NAV_ClearLastRoute(NPC); - if ( goal->inuse && !(goal->s.eFlags & EF_NODRAW) ) - { -// Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); - SetGoal( goal, 0 );//, NPCInfo->lastGoalEntityNeed + // NAV_ClearLastRoute(NPC); + if (goal->inuse && !(goal->s.eFlags & EF_NODRAW)) { + // Debug_NPCPrintf( NPC, debugNPCAI, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); + SetGoal(goal, 0); //, NPCInfo->lastGoalEntityNeed return; } - SetGoal( NULL, 0.0 ); + SetGoal(NULL, 0.0); } /* @@ -114,147 +100,143 @@ G_BoundsOverlap ------------------------- */ -qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) -{//NOTE: flush up against counts as overlapping - if(mins1[0]>maxs2[0]) +qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) { // NOTE: flush up against counts as overlapping + if (mins1[0] > maxs2[0]) return qfalse; - if(mins1[1]>maxs2[1]) + if (mins1[1] > maxs2[1]) return qfalse; - if(mins1[2]>maxs2[2]) + if (mins1[2] > maxs2[2]) return qfalse; - if(maxs1[0]goalTime = level.time; -//MCG - Begin + // MCG - Begin NPCInfo->aiFlags &= ~NPCAI_MOVING; ucmd.forwardmove = 0; - //Return that the goal was reached - Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); -//MCG - End + // Return that the goal was reached + Q3_TaskIDComplete(NPC, TID_MOVE_NAV); + // MCG - End } /* ReachedGoal id removed checks against waypoints and is now checking surfaces */ -//qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, gentity_t *goal, qboolean flying ); -qboolean ReachedGoal( gentity_t *goal ) -{ - //FIXME: For script waypoints, need a special check -/* - int goalWpNum; - vec3_t vec; - //vec3_t angles; - float delta; - - if ( goal->svFlags & SVF_NAVGOAL ) - {//waypoint_navgoal - return NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, goal, FlyingCreature( NPC ) ); - } +// qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, gentity_t *goal, qboolean flying ); +qboolean ReachedGoal(gentity_t *goal) { + // FIXME: For script waypoints, need a special check + /* + int goalWpNum; + vec3_t vec; + //vec3_t angles; + float delta; + + if ( goal->svFlags & SVF_NAVGOAL ) + {//waypoint_navgoal + return NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, goal, FlyingCreature( NPC ) ); + } - if ( goal == NPCInfo->tempGoal && !(goal->svFlags & SVF_NAVGOAL)) - {//MUST touch waypoints, even if moving to it - //This is odd, it just checks to see if they are on the same - //surface and the tempGoal in in the FOV - does NOT check distance! - // are we on same surface? - - //FIXME: NPC->waypoint reset every frame, need to find it first - //Should we do that here? (Still will do it only once per frame) - if ( NPC->waypoint >= 0 && NPC->waypoint < num_waypoints ) - { - goalWpNum = NAV_FindWaypointAt ( goal->currentOrigin ); - if ( NPC->waypoint != goalWpNum ) + if ( goal == NPCInfo->tempGoal && !(goal->svFlags & SVF_NAVGOAL)) + {//MUST touch waypoints, even if moving to it + //This is odd, it just checks to see if they are on the same + //surface and the tempGoal in in the FOV - does NOT check distance! + // are we on same surface? + + //FIXME: NPC->waypoint reset every frame, need to find it first + //Should we do that here? (Still will do it only once per frame) + if ( NPC->waypoint >= 0 && NPC->waypoint < num_waypoints ) + { + goalWpNum = NAV_FindWaypointAt ( goal->currentOrigin ); + if ( NPC->waypoint != goalWpNum ) + { + return qfalse; + } + } + + VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); + //Who cares if it's in our FOV?! + /* + // is it in our FOV + vectoangles ( vec, angles ); + delta = AngleDelta ( NPC->client->ps.viewangles[YAW], angles[YAW] ); + if ( fabs ( delta ) > NPCInfo->stats.hfov ) { return qfalse; } - } + */ - VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); - //Who cares if it's in our FOV?! - /* - // is it in our FOV - vectoangles ( vec, angles ); - delta = AngleDelta ( NPC->client->ps.viewangles[YAW], angles[YAW] ); - if ( fabs ( delta ) > NPCInfo->stats.hfov ) + /* + //If in the same waypoint as tempGoal, we're there, right? + if ( goal->waypoint >= 0 && goal->waypoint < num_waypoints ) + { + if ( NPC->waypoint == goal->waypoint ) { - return qfalse; + return qtrue; } - */ + } + */ - /* - //If in the same waypoint as tempGoal, we're there, right? - if ( goal->waypoint >= 0 && goal->waypoint < num_waypoints ) - { - if ( NPC->waypoint == goal->waypoint ) - { + /* + if ( VectorLengthSquared( vec ) < (64*64) ) + {//Close enough return qtrue; } - } - */ -/* - if ( VectorLengthSquared( vec ) < (64*64) ) - {//Close enough - return qtrue; + return qfalse; } - - return qfalse; - } -*/ - if ( NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL ) - { + */ + if (NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL) { NPCInfo->aiFlags &= ~NPCAI_TOUCHED_GOAL; return qtrue; } -/* - if ( goal->s.eFlags & EF_NODRAW ) - { - goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); - if ( NPC->waypoint == goalWpNum ) + /* + if ( goal->s.eFlags & EF_NODRAW ) { - return qtrue; + goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); + if ( NPC->waypoint == goalWpNum ) + { + return qtrue; + } + return qfalse; } - return qfalse; - } - if(goal->client && goal->health <= 0) - {//trying to get to dead guy - goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); - if ( NPC->waypoint == goalWpNum ) - { - VectorSubtract(NPC->currentOrigin, goal->currentOrigin, vec); - vec[2] = 0; - delta = VectorLengthSquared(vec); - if(delta <= 800) - {//with 20-30 of other guy's origin - return qtrue; + if(goal->client && goal->health <= 0) + {//trying to get to dead guy + goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); + if ( NPC->waypoint == goalWpNum ) + { + VectorSubtract(NPC->currentOrigin, goal->currentOrigin, vec); + vec[2] = 0; + delta = VectorLengthSquared(vec); + if(delta <= 800) + {//with 20-30 of other guy's origin + return qtrue; + } } } - } -*/ - return NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature( NPC ) ); + */ + return NAV_HitNavGoal(NPC->currentOrigin, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature(NPC)); } /* -static gentity_t *UpdateGoal( void ) +static gentity_t *UpdateGoal( void ) Id removed a lot of shit here... doesn't seem to handle waypoints independantly of goalentity @@ -263,29 +245,24 @@ In fact, doesn't seem to be any waypoint info on entities at all any more? MCG - Since goal is ALWAYS goalEntity, took out a lot of sending goal entity pointers around for no reason */ -gentity_t *UpdateGoal( void ) -{ - gentity_t *goal; +gentity_t *UpdateGoal(void) { + gentity_t *goal; - if ( !NPCInfo->goalEntity ) - { + if (!NPCInfo->goalEntity) { return NULL; } - if ( !NPCInfo->goalEntity->inuse ) - {//Somehow freed it, but didn't clear it + if (!NPCInfo->goalEntity->inuse) { // Somehow freed it, but didn't clear it NPC_ClearGoal(); return NULL; } goal = NPCInfo->goalEntity; - if ( ReachedGoal( goal ) ) - { + if (ReachedGoal(goal)) { NPC_ReachedGoal(); - goal = NULL;//so they don't keep trying to move to it - }//else if fail, need to tell script so? + goal = NULL; // so they don't keep trying to move to it + } // else if fail, need to tell script so? return goal; } - diff --git a/codeJK2/game/NPC_misc.cpp b/codeJK2/game/NPC_misc.cpp index 8ee9116a10..b3693f6ef3 100644 --- a/codeJK2/game/NPC_misc.cpp +++ b/codeJK2/game/NPC_misc.cpp @@ -31,11 +31,10 @@ along with this program; if not, see . /* Debug_Printf */ -void Debug_Printf (cvar_t *cv, int debugLevel, char *fmt, ...) -{ - char *color; - va_list argptr; - char msg[1024]; +void Debug_Printf(cvar_t *cv, int debugLevel, char *fmt, ...) { + char *color; + va_list argptr; + char msg[1024]; if (cv->value < debugLevel) return; @@ -51,30 +50,26 @@ void Debug_Printf (cvar_t *cv, int debugLevel, char *fmt, ...) else color = S_COLOR_RED; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); gi.Printf("%s%5i:%s", color, level.time, msg); } - /* Debug_NPCPrintf */ -void Debug_NPCPrintf (gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt, ...) -{ - int color; - va_list argptr; - char msg[1024]; +void Debug_NPCPrintf(gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt, ...) { + int color; + va_list argptr; + char msg[1024]; - if (cv->value < debugLevel) - { + if (cv->value < debugLevel) { return; } - if ( debugNPCName->string[0] && Q_stricmp( debugNPCName->string, printNPC->targetname) != 0 ) - { + if (debugNPCName->string[0] && Q_stricmp(debugNPCName->string, printNPC->targetname) != 0) { return; } @@ -89,9 +84,9 @@ void Debug_NPCPrintf (gentity_t *printNPC, cvar_t *cv, int debugLevel, char *fmt else color = COLOR_RED; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - gi.Printf ("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); + gi.Printf("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); } diff --git a/codeJK2/game/NPC_move.cpp b/codeJK2/game/NPC_move.cpp index 0ed5725780..ab4b13c27d 100644 --- a/codeJK2/game/NPC_move.cpp +++ b/codeJK2/game/NPC_move.cpp @@ -30,15 +30,15 @@ along with this program; if not, see . #include "g_nav.h" #include "anims.h" -extern cvar_t *d_altRoutes; +extern cvar_t *d_altRoutes; qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2); -int NAV_Steer( gentity_t *self, vec3_t dir, float distance ); -extern int GetTime ( int lastTime ); +int NAV_Steer(gentity_t *self, vec3_t dir, float distance); +extern int GetTime(int lastTime); -navInfo_t frameNavInfo; -extern qboolean FlyingCreature( gentity_t *ent ); -extern qboolean PM_InKnockDown( playerState_t *ps ); +navInfo_t frameNavInfo; +extern qboolean FlyingCreature(gentity_t *ent); +extern qboolean PM_InKnockDown(playerState_t *ps); /* ------------------------- @@ -46,43 +46,38 @@ NPC_ClearPathToGoal ------------------------- */ -qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal ) -{ - trace_t trace; +qboolean NPC_ClearPathToGoal(vec3_t dir, gentity_t *goal) { + trace_t trace; - //FIXME: What does do about area portals? THIS IS BROKEN - //if ( gi.inPVS( NPC->currentOrigin, goal->currentOrigin ) == qfalse ) + // FIXME: What does do about area portals? THIS IS BROKEN + // if ( gi.inPVS( NPC->currentOrigin, goal->currentOrigin ) == qfalse ) // return qfalse; - //Look ahead and see if we're clear to move to our goal position - if ( NAV_CheckAhead( NPC, goal->currentOrigin, trace, ( NPC->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - //VectorSubtract( goal->currentOrigin, NPC->currentOrigin, dir ); + // Look ahead and see if we're clear to move to our goal position + if (NAV_CheckAhead(NPC, goal->currentOrigin, trace, (NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + // VectorSubtract( goal->currentOrigin, NPC->currentOrigin, dir ); return qtrue; } - if (!FlyingCreature(NPC)) - { - //See if we're too far above - if ( fabs( NPC->currentOrigin[2] - goal->currentOrigin[2] ) > 48 ) + if (!FlyingCreature(NPC)) { + // See if we're too far above + if (fabs(NPC->currentOrigin[2] - goal->currentOrigin[2]) > 48) return qfalse; } - //This is a work around - float radius = ( NPC->maxs[0] > NPC->maxs[1] ) ? NPC->maxs[0] : NPC->maxs[1]; - float dist = Distance( NPC->currentOrigin, goal->currentOrigin ); - float tFrac = 1.0f - ( radius / dist ); + // This is a work around + float radius = (NPC->maxs[0] > NPC->maxs[1]) ? NPC->maxs[0] : NPC->maxs[1]; + float dist = Distance(NPC->currentOrigin, goal->currentOrigin); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; - //See if we're looking for a navgoal - if ( goal->svFlags & SVF_NAVGOAL ) - { - //Okay, didn't get all the way there, let's see if we got close enough: - if ( NAV_HitNavGoal( trace.endpos, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature( NPC ) ) ) - { - //VectorSubtract(goal->currentOrigin, NPC->currentOrigin, dir); + // See if we're looking for a navgoal + if (goal->svFlags & SVF_NAVGOAL) { + // Okay, didn't get all the way there, let's see if we got close enough: + if (NAV_HitNavGoal(trace.endpos, NPC->mins, NPC->maxs, goal->currentOrigin, NPCInfo->goalRadius, FlyingCreature(NPC))) { + // VectorSubtract(goal->currentOrigin, NPC->currentOrigin, dir); return qtrue; } } @@ -96,18 +91,14 @@ NPC_CheckCombatMove ------------------------- */ -inline qboolean NPC_CheckCombatMove( void ) -{ - //return NPCInfo->combatMove; - if ( ( NPCInfo->goalEntity && NPC->enemy && NPCInfo->goalEntity == NPC->enemy ) || ( NPCInfo->combatMove ) ) - { +inline qboolean NPC_CheckCombatMove(void) { + // return NPCInfo->combatMove; + if ((NPCInfo->goalEntity && NPC->enemy && NPCInfo->goalEntity == NPC->enemy) || (NPCInfo->combatMove)) { return qtrue; } - if ( NPCInfo->goalEntity && NPCInfo->watchTarget ) - { - if ( NPCInfo->goalEntity != NPCInfo->watchTarget ) - { + if (NPCInfo->goalEntity && NPCInfo->watchTarget) { + if (NPCInfo->goalEntity != NPCInfo->watchTarget) { return qtrue; } } @@ -121,19 +112,17 @@ NPC_LadderMove ------------------------- */ -static void NPC_LadderMove( vec3_t dir ) -{ - //FIXME: this doesn't guarantee we're facing ladder - //ALSO: Need to be able to get off at top - //ALSO: Need to play an anim - //ALSO: Need transitionary anims? - - if ( ( dir[2] > 0 ) || ( dir[2] < 0 && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) ) - { - //Set our movement direction +static void NPC_LadderMove(vec3_t dir) { + // FIXME: this doesn't guarantee we're facing ladder + // ALSO: Need to be able to get off at top + // ALSO: Need to play an anim + // ALSO: Need transitionary anims? + + if ((dir[2] > 0) || (dir[2] < 0 && NPC->client->ps.groundEntityNum == ENTITYNUM_NONE)) { + // Set our movement direction ucmd.upmove = (dir[2] > 0) ? 127 : -127; - //Don't move around on XY + // Don't move around on XY ucmd.forwardmove = ucmd.rightmove = 0; } } @@ -144,19 +133,18 @@ NPC_GetMoveInformation ------------------------- */ -inline qboolean NPC_GetMoveInformation( vec3_t dir, float *distance ) -{ - //NOTENOTE: Use path stacks! +inline qboolean NPC_GetMoveInformation(vec3_t dir, float *distance) { + // NOTENOTE: Use path stacks! - //Make sure we have somewhere to go - if ( NPCInfo->goalEntity == NULL ) + // Make sure we have somewhere to go + if (NPCInfo->goalEntity == NULL) return qfalse; - //Get our move info - VectorSubtract( NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir ); - *distance = VectorNormalize( dir ); - - VectorCopy( NPCInfo->goalEntity->currentOrigin, NPCInfo->blockedDest ); + // Get our move info + VectorSubtract(NPCInfo->goalEntity->currentOrigin, NPC->currentOrigin, dir); + *distance = VectorNormalize(dir); + + VectorCopy(NPCInfo->goalEntity->currentOrigin, NPCInfo->blockedDest); return qtrue; } @@ -167,10 +155,7 @@ NAV_GetLastMove ------------------------- */ -void NAV_GetLastMove( navInfo_t &info ) -{ - info = frameNavInfo; -} +void NAV_GetLastMove(navInfo_t &info) { info = frameNavInfo; } /* ------------------------- @@ -178,40 +163,36 @@ NPC_GetMoveDirection ------------------------- */ -qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) -{ - vec3_t angles; +qboolean NPC_GetMoveDirection(vec3_t out, float *distance) { + vec3_t angles; - //Clear the struct - memset( &frameNavInfo, 0, sizeof( frameNavInfo ) ); + // Clear the struct + memset(&frameNavInfo, 0, sizeof(frameNavInfo)); - //Get our movement, if any - if ( NPC_GetMoveInformation( frameNavInfo.direction, &frameNavInfo.distance ) == qfalse ) + // Get our movement, if any + if (NPC_GetMoveInformation(frameNavInfo.direction, &frameNavInfo.distance) == qfalse) return qfalse; - //Setup the return value + // Setup the return value *distance = frameNavInfo.distance; - //For starters - VectorCopy( frameNavInfo.direction, frameNavInfo.pathDirection ); + // For starters + VectorCopy(frameNavInfo.direction, frameNavInfo.pathDirection); - //If on a ladder, move appropriately - if ( NPC->watertype & CONTENTS_LADDER ) - { - NPC_LadderMove( frameNavInfo.direction ); + // If on a ladder, move appropriately + if (NPC->watertype & CONTENTS_LADDER) { + NPC_LadderMove(frameNavInfo.direction); return qtrue; } - //Attempt a straight move to goal - if ( NPC_ClearPathToGoal( frameNavInfo.direction, NPCInfo->goalEntity ) == qfalse ) - { - //See if we're just stuck - if ( NAV_MoveToGoal( NPC, frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + // Attempt a straight move to goal + if (NPC_ClearPathToGoal(frameNavInfo.direction, NPCInfo->goalEntity) == qfalse) { + // See if we're just stuck + if (NAV_MoveToGoal(NPC, frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } @@ -219,22 +200,19 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) frameNavInfo.flags |= NIF_MACRO_NAV; } - //Avoid any collisions on the way - if ( NAV_AvoidCollision( NPC, NPCInfo->goalEntity, frameNavInfo ) == qfalse ) - { - //FIXME: Emit a warning, this is a worst case scenario - //FIXME: if we have a clear path to our goal (exluding bodies), but then this - // check (against bodies only) fails, shouldn't we fall back + // Avoid any collisions on the way + if (NAV_AvoidCollision(NPC, NPCInfo->goalEntity, frameNavInfo) == qfalse) { + // FIXME: Emit a warning, this is a worst case scenario + // FIXME: if we have a clear path to our goal (exluding bodies), but then this + // check (against bodies only) fails, shouldn't we fall back // to macro navigation? Like so: - if ( !(frameNavInfo.flags&NIF_MACRO_NAV) ) - {//we had a clear path to goal and didn't try macro nav, but can't avoid collision so try macro nav here - //See if we're just stuck - if ( NAV_MoveToGoal( NPC, frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + if (!(frameNavInfo.flags & NIF_MACRO_NAV)) { // we had a clear path to goal and didn't try macro nav, but can't avoid collision so try macro nav here + // See if we're just stuck + if (NAV_MoveToGoal(NPC, frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } @@ -243,8 +221,8 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) } } - //Setup the return values - VectorCopy( frameNavInfo.direction, out ); + // Setup the return values + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qtrue; @@ -255,121 +233,102 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) NPC_GetMoveDirectionAltRoute ------------------------- */ -extern int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t &info ); -extern qboolean NAVNEW_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t &info, qboolean setBlockedInfo, int blockedMovesLimit ); -qboolean NPC_GetMoveDirectionAltRoute( vec3_t out, float *distance, qboolean tryStraight ) -{ - vec3_t angles; +extern int NAVNEW_MoveToGoal(gentity_t *self, navInfo_t &info); +extern qboolean NAVNEW_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t &info, qboolean setBlockedInfo, int blockedMovesLimit); +qboolean NPC_GetMoveDirectionAltRoute(vec3_t out, float *distance, qboolean tryStraight) { + vec3_t angles; NPCInfo->aiFlags &= ~NPCAI_BLOCKED; - //Clear the struct - memset( &frameNavInfo, 0, sizeof( frameNavInfo ) ); + // Clear the struct + memset(&frameNavInfo, 0, sizeof(frameNavInfo)); - //Get our movement, if any - if ( NPC_GetMoveInformation( frameNavInfo.direction, &frameNavInfo.distance ) == qfalse ) + // Get our movement, if any + if (NPC_GetMoveInformation(frameNavInfo.direction, &frameNavInfo.distance) == qfalse) return qfalse; - //Setup the return value + // Setup the return value *distance = frameNavInfo.distance; - //For starters - VectorCopy( frameNavInfo.direction, frameNavInfo.pathDirection ); + // For starters + VectorCopy(frameNavInfo.direction, frameNavInfo.pathDirection); - //If on a ladder, move appropriately - if ( NPC->watertype & CONTENTS_LADDER ) - { - NPC_LadderMove( frameNavInfo.direction ); + // If on a ladder, move appropriately + if (NPC->watertype & CONTENTS_LADDER) { + NPC_LadderMove(frameNavInfo.direction); return qtrue; } - //Attempt a straight move to goal - if ( !tryStraight || NPC_ClearPathToGoal( frameNavInfo.direction, NPCInfo->goalEntity ) == qfalse ) - {//blocked - //Can't get straight to goal, use macro nav - if ( NAVNEW_MoveToGoal( NPC, frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + // Attempt a straight move to goal + if (!tryStraight || NPC_ClearPathToGoal(frameNavInfo.direction, NPCInfo->goalEntity) == qfalse) { // blocked + // Can't get straight to goal, use macro nav + if (NAVNEW_MoveToGoal(NPC, frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } - //else we are on our way + // else we are on our way frameNavInfo.flags |= NIF_MACRO_NAV; - } - else - {//we have no architectural problems, see if there are ents inthe way and try to go around them - //not blocked - if ( d_altRoutes->integer ) - {//try macro nav - navInfo_t tempInfo; - memcpy( &tempInfo, &frameNavInfo, sizeof( tempInfo ) ); - if ( NAVNEW_AvoidCollision( NPC, NPCInfo->goalEntity, tempInfo, qtrue, 5 ) == qfalse ) - {//revert to macro nav - //Can't get straight to goal, dump tempInfo and use macro nav - if ( NAVNEW_MoveToGoal( NPC, frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + } else { // we have no architectural problems, see if there are ents inthe way and try to go around them + // not blocked + if (d_altRoutes->integer) { // try macro nav + navInfo_t tempInfo; + memcpy(&tempInfo, &frameNavInfo, sizeof(tempInfo)); + if (NAVNEW_AvoidCollision(NPC, NPCInfo->goalEntity, tempInfo, qtrue, 5) == qfalse) { // revert to macro nav + // Can't get straight to goal, dump tempInfo and use macro nav + if (NAVNEW_MoveToGoal(NPC, frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } - //else we are on our way + // else we are on our way frameNavInfo.flags |= NIF_MACRO_NAV; + } else { // otherwise, either clear or can avoid + memcpy(&frameNavInfo, &tempInfo, sizeof(frameNavInfo)); } - else - {//otherwise, either clear or can avoid - memcpy( &frameNavInfo, &tempInfo, sizeof( frameNavInfo ) ); - } - } - else - {//OR: just give up - if ( NAVNEW_AvoidCollision( NPC, NPCInfo->goalEntity, frameNavInfo, qtrue, 30 ) == qfalse ) - {//give up + } else { // OR: just give up + if (NAVNEW_AvoidCollision(NPC, NPCInfo->goalEntity, frameNavInfo, qtrue, 30) == qfalse) { // give up return qfalse; } } } - //Setup the return values - VectorCopy( frameNavInfo.direction, out ); + // Setup the return values + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qtrue; } -void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ) -{ - vec3_t forward, right; +void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir) { + vec3_t forward, right; - AngleVectors( self->currentAngles, forward, right, NULL ); + AngleVectors(self->currentAngles, forward, right, NULL); dir[2] = 0; - VectorNormalize( dir ); - //NPCs cheat and store this directly because converting movement into a ucmd loses precision - VectorCopy( dir, self->client->ps.moveDir ); - - float fDot = DotProduct( forward, dir ) * 127.0f; - float rDot = DotProduct( right, dir ) * 127.0f; - //Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte - if ( fDot > 127.0f ) - { + VectorNormalize(dir); + // NPCs cheat and store this directly because converting movement into a ucmd loses precision + VectorCopy(dir, self->client->ps.moveDir); + + float fDot = DotProduct(forward, dir) * 127.0f; + float rDot = DotProduct(right, dir) * 127.0f; + // Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte + if (fDot > 127.0f) { fDot = 127.0f; } - if ( fDot < -127.0f ) - { + if (fDot < -127.0f) { fDot = -127.0f; } - if ( rDot > 127.0f ) - { + if (rDot > 127.0f) { rDot = 127.0f; } - if ( rDot < -127.0f ) - { + if (rDot < -127.0f) { rDot = -127.0f; } cmd->forwardmove = floor(fDot); @@ -377,7 +336,7 @@ void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ) /* vec3_t wishvel; - for ( int i = 0 ; i < 3 ; i++ ) + for ( int i = 0 ; i < 3 ; i++ ) { wishvel[i] = forward[i]*cmd->forwardmove + right[i]*cmd->rightmove; } @@ -396,82 +355,71 @@ NPC_MoveToGoal Now assumes goal is goalEntity, was no reason for it to be otherwise ------------------------- */ -#if AI_TIMERS +#if AI_TIMERS extern int navTime; -#endif// AI_TIMERS -qboolean NPC_MoveToGoal( qboolean tryStraight ) -{ -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS - //If taking full body pain, don't move - if ( PM_InKnockDown( &NPC->client->ps ) || ( ( NPC->s.legsAnim >= BOTH_PAIN1 ) && ( NPC->s.legsAnim <= BOTH_PAIN19 ) ) ) - { +#endif // AI_TIMERS +qboolean NPC_MoveToGoal(qboolean tryStraight) { +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS + // If taking full body pain, don't move + if (PM_InKnockDown(&NPC->client->ps) || ((NPC->s.legsAnim >= BOTH_PAIN1) && (NPC->s.legsAnim <= BOTH_PAIN19))) { return qtrue; } - if( NPC->s.eFlags & EF_LOCKED_TO_WEAPON ) - {//If in an emplaced gun, never try to navigate! + if (NPC->s.eFlags & EF_LOCKED_TO_WEAPON) { // If in an emplaced gun, never try to navigate! return qtrue; } - float distance; - vec3_t dir; + float distance; + vec3_t dir; - //FIXME: if can't get to goal & goal is a target (enemy), try to find a waypoint that has line of sight to target, at least? - //Get our movement direction + // FIXME: if can't get to goal & goal is a target (enemy), try to find a waypoint that has line of sight to target, at least? + // Get our movement direction #if 1 - if ( NPC_GetMoveDirectionAltRoute( dir, &distance, tryStraight ) == qfalse ) + if (NPC_GetMoveDirectionAltRoute(dir, &distance, tryStraight) == qfalse) #else - if ( NPC_GetMoveDirection( dir, &distance ) == qfalse ) + if (NPC_GetMoveDirection(dir, &distance) == qfalse) #endif return qfalse; - NPCInfo->distToGoal = distance; + NPCInfo->distToGoal = distance; - //Convert the move to angles - vectoangles( dir, NPCInfo->lastPathAngles ); + // Convert the move to angles + vectoangles(dir, NPCInfo->lastPathAngles); - //FIXME: still getting ping-ponging in certain cases... !!! Nav/avoidance error? WTF???!!! - //If in combat move, then move directly towards our goal - if ( NPC_CheckCombatMove() ) - {//keep current facing - G_UcmdMoveForDir( NPC, &ucmd, dir ); - } - else - {//face our goal - //FIXME: strafe instead of turn if change in dir is small and temporary - NPCInfo->desiredPitch = 0.0f; - NPCInfo->desiredYaw = AngleNormalize360( NPCInfo->lastPathAngles[YAW] ); - - //Pitch towards the goal and also update if flying or swimming - if ( NPCInfo->stats.moveType == MT_FLYSWIM ) - { - NPCInfo->desiredPitch = AngleNormalize360( NPCInfo->lastPathAngles[PITCH] ); - - if ( dir[2] ) - { + // FIXME: still getting ping-ponging in certain cases... !!! Nav/avoidance error? WTF???!!! + // If in combat move, then move directly towards our goal + if (NPC_CheckCombatMove()) { // keep current facing + G_UcmdMoveForDir(NPC, &ucmd, dir); + } else { // face our goal + // FIXME: strafe instead of turn if change in dir is small and temporary + NPCInfo->desiredPitch = 0.0f; + NPCInfo->desiredYaw = AngleNormalize360(NPCInfo->lastPathAngles[YAW]); + + // Pitch towards the goal and also update if flying or swimming + if (NPCInfo->stats.moveType == MT_FLYSWIM) { + NPCInfo->desiredPitch = AngleNormalize360(NPCInfo->lastPathAngles[PITCH]); + + if (dir[2]) { float scale = (dir[2] * distance); - if ( scale > 64 ) - { + if (scale > 64) { scale = 64; - } - else if ( scale < -64 ) - { + } else if (scale < -64) { scale = -64; } NPC->client->ps.velocity[2] = scale; - //NPC->client->ps.velocity[2] = (dir[2] > 0) ? 64 : -64; + // NPC->client->ps.velocity[2] = (dir[2] > 0) ? 64 : -64; } } - //Set any final info + // Set any final info ucmd.forwardmove = 127; } -#if AI_TIMERS - navTime += GetTime( startTime ); -#endif// AI_TIMERS +#if AI_TIMERS + navTime += GetTime(startTime); +#endif // AI_TIMERS return qtrue; } @@ -482,32 +430,28 @@ void NPC_SlideMoveToGoal( void ) Now assumes goal is goalEntity, if want to use tempGoal, you set that before calling the func ------------------------- */ -qboolean NPC_SlideMoveToGoal( void ) -{ - float saveYaw = NPC->client->ps.viewangles[YAW]; +qboolean NPC_SlideMoveToGoal(void) { + float saveYaw = NPC->client->ps.viewangles[YAW]; NPCInfo->combatMove = qtrue; - - qboolean ret = NPC_MoveToGoal( qtrue ); - NPCInfo->desiredYaw = saveYaw; + qboolean ret = NPC_MoveToGoal(qtrue); + + NPCInfo->desiredYaw = saveYaw; return ret; } - /* ------------------------- NPC_ApplyRoff ------------------------- */ -void NPC_ApplyRoff(void) -{ - PlayerStateToEntityState( &NPC->client->ps, &NPC->s ); - VectorCopy ( NPC->currentOrigin, NPC->lastOrigin ); +void NPC_ApplyRoff(void) { + PlayerStateToEntityState(&NPC->client->ps, &NPC->s); + VectorCopy(NPC->currentOrigin, NPC->lastOrigin); // use the precise origin for linking gi.linkentity(NPC); } - diff --git a/codeJK2/game/NPC_reactions.cpp b/codeJK2/game/NPC_reactions.cpp index 209f3e607d..be4b55009c 100644 --- a/codeJK2/game/NPC_reactions.cpp +++ b/codeJK2/game/NPC_reactions.cpp @@ -20,40 +20,39 @@ along with this program; if not, see . =========================================================================== */ -//NPC_reactions.cpp +// NPC_reactions.cpp #include "g_headers.h" - #include "b_local.h" #include "anims.h" #include "g_functions.h" #include "wp_saber.h" -extern qboolean G_CheckForStrongAttackMomentum( gentity_t *self ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void cgi_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern void Jedi_Ambush( gentity_t *self ); - -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SpinningAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); - -extern cvar_t *g_spskill; -extern int teamLastEnemyTime[]; -extern qboolean stop_icarus; +extern qboolean G_CheckForStrongAttackMomentum(gentity_t *self); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void cgi_S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern void Jedi_Ambush(gentity_t *self); + +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SpinningAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InCartwheel(int anim); + +extern cvar_t *g_spskill; +extern int teamLastEnemyTime[]; +extern qboolean stop_icarus; extern int killPlayerTimer; float g_crosshairEntDist = Q3_INFINITE; @@ -66,89 +65,81 @@ NPC_CheckAttacker ------------------------- */ -static void NPC_CheckAttacker( gentity_t *other, int mod ) -{ - //FIXME: I don't see anything in here that would stop teammates from taking a teammate +static void NPC_CheckAttacker(gentity_t *other, int mod) { + // FIXME: I don't see anything in here that would stop teammates from taking a teammate // as an enemy. Ideally, there would be code before this to prevent that from // happening, but that is presumptuous. - - //valid ent - FIXME: a VALIDENT macro would be nice here - if ( !other ) + + // valid ent - FIXME: a VALIDENT macro would be nice here + if (!other) return; - if ( other == NPC ) + if (other == NPC) return; - if ( !other->inuse ) + if (!other->inuse) return; - //Don't take a target that doesn't want to be - if ( other->flags & FL_NOTARGET ) + // Don't take a target that doesn't want to be + if (other->flags & FL_NOTARGET) return; - if ( NPC->svFlags & SVF_LOCKEDENEMY ) - {//IF LOCKED, CANNOT CHANGE ENEMY!!!!! + if (NPC->svFlags & SVF_LOCKEDENEMY) { // IF LOCKED, CANNOT CHANGE ENEMY!!!!! return; } - //If we haven't taken a target, just get mad - if ( NPC->enemy == NULL )//was using "other", fixed to NPC + // If we haven't taken a target, just get mad + if (NPC->enemy == NULL) // was using "other", fixed to NPC { - G_SetEnemy( NPC, other ); + G_SetEnemy(NPC, other); return; } - //we have an enemy, see if he's dead - if ( NPC->enemy->health <= 0 ) - { - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, other ); + // we have an enemy, see if he's dead + if (NPC->enemy->health <= 0) { + G_ClearEnemy(NPC); + G_SetEnemy(NPC, other); return; } - //Don't take the same enemy again - if ( other == NPC->enemy ) + // Don't take the same enemy again + if (other == NPC->enemy) return; - if ( NPC->client->ps.weapon == WP_SABER ) - {//I'm a jedi - if ( mod == MOD_SABER ) - {//I was hit by a saber FIXME: what if this was a thrown saber? - //always switch to this enemy if I'm a jedi and hit by another saber - G_ClearEnemy( NPC ); - G_SetEnemy( NPC, other ); + if (NPC->client->ps.weapon == WP_SABER) { // I'm a jedi + if (mod == MOD_SABER) { // I was hit by a saber FIXME: what if this was a thrown saber? + // always switch to this enemy if I'm a jedi and hit by another saber + G_ClearEnemy(NPC); + G_SetEnemy(NPC, other); return; } } - //Special case player interactions - if ( other == &g_entities[0] ) - { - //Account for the skill level to skew the results - float luckThreshold; + // Special case player interactions + if (other == &g_entities[0]) { + // Account for the skill level to skew the results + float luckThreshold; - switch ( g_spskill->integer ) - { - //Easiest difficulty, mild chance of picking up the player + switch (g_spskill->integer) { + // Easiest difficulty, mild chance of picking up the player case 0: luckThreshold = 0.9f; break; - //Medium difficulty, half-half chance of picking up the player + // Medium difficulty, half-half chance of picking up the player case 1: luckThreshold = 0.5f; break; - //Hardest difficulty, always turn on attacking player + // Hardest difficulty, always turn on attacking player case 2: default: luckThreshold = 0.0f; break; } - //Randomly pick up the target - if ( Q_flrand(0.0f, 1.0f) > luckThreshold ) - { - G_ClearEnemy( other ); + // Randomly pick up the target + if (Q_flrand(0.0f, 1.0f) > luckThreshold) { + G_ClearEnemy(other); other->enemy = NPC; } @@ -156,14 +147,11 @@ static void NPC_CheckAttacker( gentity_t *other, int mod ) } } -void NPC_SetPainEvent( gentity_t *self ) -{ - if ( !self->NPC || !(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); - } +void NPC_SetPainEvent(gentity_t *self) { + if (!self->NPC || !(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->max_health * 100.0f)); + } } } @@ -173,37 +161,33 @@ NPC_GetPainChance ------------------------- */ -float NPC_GetPainChance( gentity_t *self, int damage ) -{ - if ( !self->enemy ) - {//surprised, always take pain +float NPC_GetPainChance(gentity_t *self, int damage) { + if (!self->enemy) { // surprised, always take pain return 1.0f; } - if ( damage > self->max_health/2.0f ) - { + if (damage > self->max_health / 2.0f) { return 1.0f; } - float pain_chance = (float)(self->max_health-self->health)/(self->max_health*2.0f) + (float)damage/(self->max_health/2.0f); - switch ( g_spskill->integer ) - { - case 0: //easy - //return 0.75f; + float pain_chance = (float)(self->max_health - self->health) / (self->max_health * 2.0f) + (float)damage / (self->max_health / 2.0f); + switch (g_spskill->integer) { + case 0: // easy + // return 0.75f; break; - case 1://med + case 1: // med pain_chance *= 0.5f; - //return 0.35f; + // return 0.35f; break; - case 2://hard + case 2: // hard default: pain_chance *= 0.1f; - //return 0.05f; + // return 0.05f; break; } - //Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); + // Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); return pain_chance; } @@ -213,141 +197,96 @@ NPC_ChoosePainAnimation ------------------------- */ -#define MIN_PAIN_TIME 200 +#define MIN_PAIN_TIME 200 -extern int G_PickPainAnim( gentity_t *self, vec3_t point, int damage, int hitLoc ); -void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc, int voiceEvent = -1 ) -{ - //If we've already taken pain, then don't take it again - if ( level.time < self->painDebounceTime && mod != MOD_ELECTROCUTE && mod != MOD_MELEE ) - {//FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? +extern int G_PickPainAnim(gentity_t *self, vec3_t point, int damage, int hitLoc); +void NPC_ChoosePainAnimation(gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc, int voiceEvent = -1) { + // If we've already taken pain, then don't take it again + if (level.time < self->painDebounceTime && mod != MOD_ELECTROCUTE && + mod != MOD_MELEE) { // FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? return; } - int pain_anim = -1; - float pain_chance; - - if ( self->s.weapon == WP_THERMAL && self->client->fireDelay > 0 ) - {//don't interrupt thermal throwing anim + int pain_anim = -1; + float pain_chance; + + if (self->s.weapon == WP_THERMAL && self->client->fireDelay > 0) { // don't interrupt thermal throwing anim return; - } - else if ( self->client->NPC_class == CLASS_GALAKMECH ) - { - if ( hitLoc == HL_GENERIC1 ) - {//hit the antenna! + } else if (self->client->NPC_class == CLASS_GALAKMECH) { + if (hitLoc == HL_GENERIC1) { // hit the antenna! pain_chance = 1.0f; - self->s.powerups |= ( 1 << PW_SHOCKED ); - self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); - } - else if ( self->client->ps.powerups[PW_GALAK_SHIELD] ) - {//shield up + self->s.powerups |= (1 << PW_SHOCKED); + self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand(500, 2500); + } else if (self->client->ps.powerups[PW_GALAK_SHIELD]) { // shield up return; - } - else if ( self->health > 200 && damage < 100 ) - {//have a *lot* of health + } else if (self->health > 200 && damage < 100) { // have a *lot* of health pain_chance = 0.05f; + } else { // the lower my health and greater the damage, the more likely I am to play a pain anim + pain_chance = (200.0f - self->health) / 100.0f + damage / 50.0f; } - else - {//the lower my health and greater the damage, the more likely I am to play a pain anim - pain_chance = (200.0f-self->health)/100.0f + damage/50.0f; - } - } - else if ( self->client && self->client->playerTeam == TEAM_PLAYER && other && !other->s.number ) - {//ally shot by player always complains + } else if (self->client && self->client->playerTeam == TEAM_PLAYER && other && !other->s.number) { // ally shot by player always complains pain_chance = 1.1f; - } - else - { - if ( other && (other->s.weapon == WP_SABER || mod == MOD_ELECTROCUTE || mod == MOD_CRUSH/*FIXME:MOD_FORCE_GRIP*/) ) - { - pain_chance = 1.0f;//always take pain from saber - } - else if ( mod == MOD_MELEE ) - {//higher in rank (skill) we are, less likely we are to be fazed by a punch - pain_chance = 1.0f - ((RANK_CAPTAIN-self->NPC->rank)/(float)RANK_CAPTAIN); - } - else if ( self->client->NPC_class == CLASS_PROTOCOL ) - { + } else { + if (other && (other->s.weapon == WP_SABER || mod == MOD_ELECTROCUTE || mod == MOD_CRUSH /*FIXME:MOD_FORCE_GRIP*/)) { + pain_chance = 1.0f; // always take pain from saber + } else if (mod == MOD_MELEE) { // higher in rank (skill) we are, less likely we are to be fazed by a punch + pain_chance = 1.0f - ((RANK_CAPTAIN - self->NPC->rank) / (float)RANK_CAPTAIN); + } else if (self->client->NPC_class == CLASS_PROTOCOL) { pain_chance = 1.0f; + } else { + pain_chance = NPC_GetPainChance(self, damage); } - else - { - pain_chance = NPC_GetPainChance( self, damage ); - } - if ( self->client->NPC_class == CLASS_DESANN ) - { + if (self->client->NPC_class == CLASS_DESANN) { pain_chance *= 0.5f; } } - //See if we're going to flinch - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) - { - //Pick and play our animation - if ( !(self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//not being force-gripped - if ( G_CheckForStrongAttackMomentum( self ) - || PM_SpinningAnim( self->client->ps.legsAnim ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || PM_InKnockDown( &self->client->ps ) - || PM_RollingAnim( self->client->ps.legsAnim ) - || (PM_FlippingAnim( self->client->ps.legsAnim )&&!PM_InCartwheel( self->client->ps.legsAnim )) ) - {//strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain + // See if we're going to flinch + if (Q_flrand(0.0f, 1.0f) < pain_chance) { + // Pick and play our animation + if (!(self->client->ps.eFlags & EF_FORCE_GRIPPED)) { // not being force-gripped + if (G_CheckForStrongAttackMomentum(self) || PM_SpinningAnim(self->client->ps.legsAnim) || PM_SaberInSpecialAttack(self->client->ps.torsoAnim) || + PM_InKnockDown(&self->client->ps) || PM_RollingAnim(self->client->ps.legsAnim) || + (PM_FlippingAnim(self->client->ps.legsAnim) && + !PM_InCartwheel(self->client->ps.legsAnim))) { // strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain return; - } - else - {//play an anim - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//only has 1 for now - //FIXME: never plays this, it seems... + } else { // play an anim + if (self->client->NPC_class == CLASS_GALAKMECH) { // only has 1 for now + // FIXME: never plays this, it seems... pain_anim = BOTH_PAIN1; - } - else if ( mod == MOD_MELEE ) - { - pain_anim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); - } - else if ( self->s.weapon == WP_SABER ) - {//temp HACK: these are the only 2 pain anims that look good when holding a saber - pain_anim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); - } - else if ( mod != MOD_ELECTROCUTE ) - { - pain_anim = G_PickPainAnim( self, point, damage, hitLoc ); + } else if (mod == MOD_MELEE) { + pain_anim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else if (self->s.weapon == WP_SABER) { // temp HACK: these are the only 2 pain anims that look good when holding a saber + pain_anim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else if (mod != MOD_ELECTROCUTE) { + pain_anim = G_PickPainAnim(self, point, damage, hitLoc); } - if ( pain_anim == -1 ) - { - pain_anim = PM_PickAnim( self, BOTH_PAIN1, BOTH_PAIN19 ); + if (pain_anim == -1) { + pain_anim = PM_PickAnim(self, BOTH_PAIN1, BOTH_PAIN19); } - self->client->ps.saberAnimLevel = FORCE_LEVEL_1;//next attack must be a quick attack - self->client->ps.saberMove = LS_READY;//don't finish whatever saber move you may have been in + self->client->ps.saberAnimLevel = FORCE_LEVEL_1; // next attack must be a quick attack + self->client->ps.saberMove = LS_READY; // don't finish whatever saber move you may have been in int parts = SETANIM_BOTH; - if ( PM_CrouchAnim( self->client->ps.legsAnim ) || PM_InCartwheel( self->client->ps.legsAnim ) ) - { + if (PM_CrouchAnim(self->client->ps.legsAnim) || PM_InCartwheel(self->client->ps.legsAnim)) { parts = SETANIM_LEGS; } - NPC_SetAnim( self, parts, pain_anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - if ( voiceEvent != -1 ) - { - G_AddVoiceEvent( self, voiceEvent, Q_irand( 2000, 4000 ) ); + NPC_SetAnim(self, parts, pain_anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetPainEvent( self ); + if (voiceEvent != -1) { + G_AddVoiceEvent(self, voiceEvent, Q_irand(2000, 4000)); + } else { + NPC_SetPainEvent(self); } + } else { + G_AddVoiceEvent(self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0); } - else - { - G_AddVoiceEvent( self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0 ); - } - - //Setup the timing for it - if ( mod == MOD_ELECTROCUTE ) - { + + // Setup the timing for it + if (mod == MOD_ELECTROCUTE) { self->painDebounceTime = level.time + 4000; } - self->painDebounceTime = level.time + PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t) pain_anim ); + self->painDebounceTime = level.time + PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)pain_anim); self->client->fireDelay = 0; } } @@ -357,114 +296,89 @@ void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, vec3_t point, i NPC_Pain =============== */ -void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc ) -{ +void NPC_Pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { team_t otherTeam = TEAM_FREE; - int voiceEvent = -1; + int voiceEvent = -1; - if ( self->NPC == NULL ) + if (self->NPC == NULL) return; - if ( other == NULL ) + if (other == NULL) return; - //or just remove ->pain in player_die? - if ( self->client->ps.pm_type == PM_DEAD ) + // or just remove ->pain in player_die? + if (self->client->ps.pm_type == PM_DEAD) return; - if ( other == self ) + if (other == self) return; - //MCG: Ignore damage from your own team for now - if ( other->client ) - { + // MCG: Ignore damage from your own team for now + if (other->client) { otherTeam = other->client->playerTeam; - // if ( otherTeam == TEAM_DISGUISE ) - // { - // otherTeam = TEAM_PLAYER; - // } - } - - if ( self->client->playerTeam - && other->client - && otherTeam == self->client->playerTeam - && (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) - {//hit by a teammate - if ( other != self->enemy && self != other->enemy ) - {//we weren't already enemies - if ( self->enemy || other->enemy - || (other->s.number&&other->s.number!=player->client->ps.viewEntity) - /*|| (!other->s.number&&Q_irand( 0, 3 ))*/ ) - {//if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad (FIXME:accumulate anger+base on diff?) - //FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad - //Still run pain and flee scripts - if ( self->client && self->NPC ) - {//Run any pain instructions - if ( self->health <= (self->max_health/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { - - } - else// if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + // if ( otherTeam == TEAM_DISGUISE ) + // { + // otherTeam = TEAM_PLAYER; + // } + } + + if (self->client->playerTeam && other->client && otherTeam == self->client->playerTeam && + (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) { // hit by a teammate + if (other != self->enemy && self != other->enemy) { // we weren't already enemies + if (self->enemy || other->enemy || (other->s.number && other->s.number != player->client->ps.viewEntity) + /*|| (!other->s.number&&Q_irand( 0, 3 ))*/) { // if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player + // or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad + // (FIXME:accumulate anger+base on diff?) + // FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad + // Still run pain and flee scripts + if (self->client && self->NPC) { // Run any pain instructions + if (self->health <= (self->max_health / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc); } } return; - } - else if ( self->NPC && !other->s.number )//should be assumed, but... - {//dammit, stop that! - if ( self->NPC->charmedTime ) - {//mindtricked + } else if (self->NPC && !other->s.number) // should be assumed, but... + { // dammit, stop that! + if (self->NPC->charmedTime) { // mindtricked return; - } - else if ( self->NPC->ffireCount < 3+((2-g_spskill->integer)*2) ) - {//not mad enough yet - //Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc ); + } else if (self->NPC->ffireCount < 3 + ((2 - g_spskill->integer) * 2)) { // not mad enough yet + // Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc); } } return; - } - else if ( G_ActivateBehavior( self, BSET_FFIRE ) ) - {//we have a specific script to run, so do that instead + } else if (G_ActivateBehavior(self, BSET_FFIRE)) { // we have a specific script to run, so do that instead return; - } - else - {//okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and clear any flags that would stop us) + } else { // okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and + // clear any flags that would stop us) self->NPC->blockedSpeechDebounceTime = 0; voiceEvent = EV_FFTURN; self->NPC->behaviorState = self->NPC->tempBehavior = self->NPC->defaultBehavior = BS_DEFAULT; other->flags &= ~FL_NOTARGET; - self->svFlags &= ~(SVF_IGNORE_ENEMIES|SVF_ICARUS_FREEZE|SVF_NO_COMBAT_SOUNDS); - G_SetEnemy( self, other ); + self->svFlags &= ~(SVF_IGNORE_ENEMIES | SVF_ICARUS_FREEZE | SVF_NO_COMBAT_SOUNDS); + G_SetEnemy(self, other); self->svFlags |= SVF_LOCKEDENEMY; - self->NPC->scriptFlags &= ~(SCF_DONT_FIRE|SCF_CROUCHED|SCF_WALKING|SCF_NO_COMBAT_TALK|SCF_FORCED_MARCH); - self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES|SCF_NO_MIND_TRICK); - //NOTE: we also stop ICARUS altogether + self->NPC->scriptFlags &= ~(SCF_DONT_FIRE | SCF_CROUCHED | SCF_WALKING | SCF_NO_COMBAT_TALK | SCF_FORCED_MARCH); + self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES | SCF_NO_MIND_TRICK); + // NOTE: we also stop ICARUS altogether stop_icarus = qtrue; - if ( !killPlayerTimer ) - { + if (!killPlayerTimer) { killPlayerTimer = level.time + 10000; } } @@ -473,40 +387,33 @@ void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t p } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - //Do extra bits - if ( NPCInfo->ignorePain == qfalse ) - { - NPCInfo->confusionTime = 0;//clear any charm or confusion, regardless - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, voiceEvent ); + // Do extra bits + if (NPCInfo->ignorePain == qfalse) { + NPCInfo->confusionTime = 0; // clear any charm or confusion, regardless + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, voiceEvent); } - //Check to take a new enemy - if ( NPC->enemy != other && NPC != other ) - {//not already mad at them - NPC_CheckAttacker( other, mod ); + // Check to take a new enemy + if (NPC->enemy != other && NPC != other) { // not already mad at them + NPC_CheckAttacker(other, mod); } } - //Attempt to run any pain instructions - if ( self->client && self->NPC ) - { - //FIXME: This needs better heuristics perhaps - if(self->health <= (self->max_health/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { - } - else //if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + // Attempt to run any pain instructions + if (self->client && self->NPC) { + // FIXME: This needs better heuristics perhaps + if (self->health <= (self->max_health / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - //Attempt to fire any paintargets we might have - if( self->paintarget && self->paintarget[0] ) - { + // Attempt to fire any paintargets we might have + if (self->paintarget && self->paintarget[0]) { G_UseTargets2(self, other, self->paintarget); } @@ -518,110 +425,85 @@ void NPC_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t p NPC_Touch ------------------------- */ -extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); -void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) -{ - if(!self->NPC) +extern qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname); +void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!self->NPC) return; SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if ( self->message && self->health <= 0 ) - {//I am dead and carrying a key - if ( other && player && player->health > 0 && other == player ) - {//player touched me + if (self->message && self->health <= 0) { // I am dead and carrying a key + if (other && player && player->health > 0 && other == player) { // player touched me char *text; - qboolean keyTaken; - //give him my key - if ( Q_stricmp( "goodie", self->message ) == 0 ) - {//a goodie key - if ( (keyTaken = INV_GoodieKeyGive( other )) == qtrue ) - { + qboolean keyTaken; + // give him my key + if (Q_stricmp("goodie", self->message) == 0) { // a goodie key + if ((keyTaken = INV_GoodieKeyGive(other)) == qtrue) { text = "cp @INGAME_TOOK_IMPERIAL_GOODIE_KEY"; - G_AddEvent( other, EV_ITEM_PICKUP, (FindItemForInventory( INV_GOODIE_KEY )-bg_itemlist) ); - } - else - { + G_AddEvent(other, EV_ITEM_PICKUP, (FindItemForInventory(INV_GOODIE_KEY) - bg_itemlist)); + } else { text = "cp @INGAME_CANT_CARRY_GOODIE_KEY"; } - } - else - {//a named security key - if ( (keyTaken = INV_SecurityKeyGive( player, self->message )) == qtrue ) - { + } else { // a named security key + if ((keyTaken = INV_SecurityKeyGive(player, self->message)) == qtrue) { text = "cp @INGAME_TOOK_IMPERIAL_SECURITY_KEY"; - G_AddEvent( other, EV_ITEM_PICKUP, (FindItemForInventory( INV_SECURITY_KEY )-bg_itemlist) ); - } - else - { + G_AddEvent(other, EV_ITEM_PICKUP, (FindItemForInventory(INV_SECURITY_KEY) - bg_itemlist)); + } else { text = "cp @INGAME_CANT_CARRY_SECURITY_KEY"; } } - if ( keyTaken ) - {//remove my key - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm_key", 0x00000002 ); + if (keyTaken) { // remove my key + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "l_arm_key", 0x00000002); self->message = NULL; - //FIXME: temp pickup sound - G_Sound( player, G_SoundIndex( "sound/weapons/key_pkup.wav" ) ); - //FIXME: need some event to pass to cgame for sound/graphic/message? + // FIXME: temp pickup sound + G_Sound(player, G_SoundIndex("sound/weapons/key_pkup.wav")); + // FIXME: need some event to pass to cgame for sound/graphic/message? } - gi.SendServerCommand( 0, text ); + gi.SendServerCommand(0, text); } } - if ( other->client ) - {//FIXME: if pushing against another bot, both ucmd.rightmove = 127??? - //Except if not facing one another... - if ( other->health > 0 ) - { + if (other->client) { // FIXME: if pushing against another bot, both ucmd.rightmove = 127??? + // Except if not facing one another... + if (other->health > 0) { NPCInfo->touchedByPlayer = other; } - if ( other == NPCInfo->goalEntity ) - { + if (other == NPCInfo->goalEntity) { NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } - if( !(self->svFlags&SVF_LOCKEDENEMY) && !(self->svFlags&SVF_IGNORE_ENEMIES) && !(other->flags & FL_NOTARGET) ) - { - if ( self->client->enemyTeam ) - {//See if we bumped into an enemy - if ( other->client->playerTeam == self->client->enemyTeam ) - {//bumped into an enemy - if( NPCInfo->behaviorState != BS_HUNT_AND_KILL && !NPCInfo->tempBehavior ) - {//MCG - Begin: checking specific BS mode here, this is bad, a HACK - //FIXME: not medics? - if ( NPC->enemy != other ) - {//not already mad at them - G_SetEnemy( NPC, other ); + if (!(self->svFlags & SVF_LOCKEDENEMY) && !(self->svFlags & SVF_IGNORE_ENEMIES) && !(other->flags & FL_NOTARGET)) { + if (self->client->enemyTeam) { // See if we bumped into an enemy + if (other->client->playerTeam == self->client->enemyTeam) { // bumped into an enemy + if (NPCInfo->behaviorState != BS_HUNT_AND_KILL && + !NPCInfo->tempBehavior) { // MCG - Begin: checking specific BS mode here, this is bad, a HACK + // FIXME: not medics? + if (NPC->enemy != other) { // not already mad at them + G_SetEnemy(NPC, other); } - // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; + // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; } } } } - //FIXME: do this if player is moving toward me and with a certain dist? + // FIXME: do this if player is moving toward me and with a certain dist? /* if ( other->s.number == 0 && self->client->playerTeam == other->client->playerTeam ) { VectorAdd( self->client->pushVec, other->client->ps.velocity, self->client->pushVec ); } */ - } - else - {//FIXME: check for SVF_NONNPC_ENEMY flag here? - if ( other->health > 0 ) - { - if ( NPC->enemy == other && (other->svFlags&SVF_NONNPC_ENEMY) ) - { + } else { // FIXME: check for SVF_NONNPC_ENEMY flag here? + if (other->health > 0) { + if (NPC->enemy == other && (other->svFlags & SVF_NONNPC_ENEMY)) { NPCInfo->touchedByPlayer = other; } } - if ( other == NPCInfo->goalEntity ) - { + if (other == NPCInfo->goalEntity) { NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } } @@ -635,32 +517,26 @@ NPC_TempLookTarget ------------------------- */ -void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ) -{ - if ( !self->client ) - { +void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime) { + if (!self->client) { return; } - if ( !minLookTime ) - { + if (!minLookTime) { minLookTime = 1000; } - if ( !maxLookTime ) - { + if (!maxLookTime) { maxLookTime = 1000; } - if ( !NPC_CheckLookTarget( self ) ) - {//Not already looking at something else - //Look at him for 1 to 3 seconds - NPC_SetLookTarget( self, lookEntNum, level.time + Q_irand( minLookTime, maxLookTime ) ); + if (!NPC_CheckLookTarget(self)) { // Not already looking at something else + // Look at him for 1 to 3 seconds + NPC_SetLookTarget(self, lookEntNum, level.time + Q_irand(minLookTime, maxLookTime)); } } -void NPC_Respond( gentity_t *self, int userNum ) -{ +void NPC_Respond(gentity_t *self, int userNum) { int event = -1; /* @@ -674,239 +550,153 @@ void NPC_Respond( gentity_t *self, int userNum ) } */ - if ( !Q_irand( 0, 1 ) ) - {//set looktarget to them for a second or two - NPC_TempLookTarget( self, userNum, 1000, 3000 ); + if (!Q_irand(0, 1)) { // set looktarget to them for a second or two + NPC_TempLookTarget(self, userNum, 1000, 3000); } - //some last-minute hacked in responses - switch ( self->client->NPC_class ) - { + // some last-minute hacked in responses + switch (self->client->NPC_class) { case CLASS_JAN: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 2 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 2)) { event = EV_SUSPICIOUS4; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_SOUND1; - } - else - { + } else { event = EV_CONFUSE1; } break; case CLASS_LANDO: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 6 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 6)) { event = EV_SIGHT2; - } - else if ( !Q_irand( 0, 5 ) ) - { + } else if (!Q_irand(0, 5)) { event = EV_GIVEUP4; - } - else if ( Q_irand( 0, 4 ) > 1 ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else - { - event = Q_irand( EV_JDETECTED1, EV_JDETECTED2 ); + } else if (Q_irand(0, 4) > 1) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else { + event = Q_irand(EV_JDETECTED1, EV_JDETECTED2); } break; case CLASS_LUKE: - if ( self->enemy ) - { + if (self->enemy) { event = EV_COVER1; - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_JEDI: - if ( !self->enemy ) - { - if ( !(self->svFlags&SVF_IGNORE_ENEMIES) - && (self->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) - && self->client->enemyTeam == TEAM_ENEMY ) - { - event = Q_irand( EV_ANGER1, EV_ANGER3 ); - } - else - { - event = Q_irand( EV_TAUNT1, EV_TAUNT2 ); + if (!self->enemy) { + if (!(self->svFlags & SVF_IGNORE_ENEMIES) && (self->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES) && self->client->enemyTeam == TEAM_ENEMY) { + event = Q_irand(EV_ANGER1, EV_ANGER3); + } else { + event = Q_irand(EV_TAUNT1, EV_TAUNT2); } } break; case CLASS_PRISONER: - if ( self->enemy ) - { - if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); + if (self->enemy) { + if (Q_irand(0, 1)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); } - else - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_REBEL: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else - { - event = Q_irand( EV_DETECTED1, EV_DETECTED5 ); + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_DETECTED1, EV_DETECTED5); } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_BESPIN_COP: - if ( !Q_stricmp( "bespincop", self->NPC_type ) ) - {//variant 1 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); + if (!Q_stricmp("bespincop", self->NPC_type)) { // variant 1 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT2, EV_SIGHT3 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT2, EV_SIGHT3); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_ESCAPING2; - } - else - { + } else { event = EV_GIVEUP4; } - } - else - {//variant2 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); + } else { // variant2 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT1, EV_SIGHT2 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT1, EV_SIGHT2); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_GIVEUP3; - } - else - { + } else { event = EV_CONFUSE1; } } break; - case CLASS_R2D2: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)))); + case CLASS_R2D2: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)))); break; - case CLASS_R5D2: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)))); + case CLASS_R5D2: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)))); break; - case CLASS_MOUSE: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)))); + case CLASS_MOUSE: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)))); break; - case CLASS_GONK: // droid - G_Sound(self, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)))); + case CLASS_GONK: // droid + G_Sound(self, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)))); break; default: break; } - - if ( event != -1 ) - { - //hack here because we reuse some "combat" and "extra" sounds + + if (event != -1) { + // hack here because we reuse some "combat" and "extra" sounds qboolean addFlag = (qboolean)(self->NPC->scriptFlags & SCF_NO_COMBAT_TALK); self->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; - G_AddVoiceEvent( self, event, 3000 ); + G_AddVoiceEvent(self, event, 3000); - if ( addFlag ) - { + if (addFlag) { self->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; } } @@ -918,51 +708,39 @@ NPC_UseResponse ------------------------- */ -void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) -{ - if ( !self->NPC || !self->client ) - { +void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone) { + if (!self->NPC || !self->client) { return; } - if ( user->s.number != 0 ) - {//not used by the player - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->s.number != 0) { // not used by the player + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( user->client && self->client->playerTeam != user->client->playerTeam && self->client->playerTeam != TEAM_NEUTRAL ) - {//only those on the same team react - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->client && self->client->playerTeam != user->client->playerTeam && self->client->playerTeam != TEAM_NEUTRAL) { // only those on the same team react + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - {//I'm not responding right now + if (self->NPC->blockedSpeechDebounceTime > level.time) { // I'm not responding right now return; } - if ( gi.VoiceVolume[self->s.number] ) - {//I'm talking already - if ( !useWhenDone ) - {//you're not trying to use me + if (gi.VoiceVolume[self->s.number]) { // I'm talking already + if (!useWhenDone) { // you're not trying to use me return; } } - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); - } - else - { - NPC_Respond( self, user->s.number ); + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); + } else { + NPC_Respond(self, user->s.number); } } @@ -971,76 +749,69 @@ void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) NPC_Use ------------------------- */ -extern void Add_Batteries( gentity_t *ent, int *count ); +extern void Add_Batteries(gentity_t *ent, int *count); -void NPC_Use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if (self->client->ps.pm_type == PM_DEAD) - {//or just remove ->pain in player_die? +void NPC_Use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->client->ps.pm_type == PM_DEAD) { // or just remove ->pain in player_die? return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if(self->client && self->NPC) - { - if ( Jedi_WaitingAmbush( NPC ) ) - { - Jedi_Ambush( NPC ); + if (self->client && self->NPC) { + if (Jedi_WaitingAmbush(NPC)) { + Jedi_Ambush(NPC); } - //Run any use instructions - if ( activator && activator->s.number == 0 && self->client->NPC_class == CLASS_GONK ) - { + // Run any use instructions + if (activator && activator->s.number == 0 && self->client->NPC_class == CLASS_GONK) { // must be using the gonk, so attempt to give battery power. // NOTE: this will steal up to MAX_BATTERIES for the activator, leaving the residual on the gonk for potential later use. - Add_Batteries( activator, &self->client->ps.batteryCharge ); + Add_Batteries(activator, &self->client->ps.batteryCharge); } // Not using MEDICs anymore -/* - if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) - {//Heal me NOW, dammit! - if ( activator->health < activator->max_health ) - {//person needs help - if ( self->NPC->eventualGoal != activator ) - {//not my current patient already - NPC_TakePatient( activator ); - G_ActivateBehavior( self, BSET_USE ); + /* + if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) + {//Heal me NOW, dammit! + if ( activator->health < activator->max_health ) + {//person needs help + if ( self->NPC->eventualGoal != activator ) + {//not my current patient already + NPC_TakePatient( activator ); + G_ActivateBehavior( self, BSET_USE ); + } + } + else if ( !self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) + {//I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse( self, other, qfalse ); + } } - } - else if ( !self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); - } - } -*/ -// else if ( self->behaviorSet[BSET_USE] ) - if ( self->behaviorSet[BSET_USE] ) - { - NPC_UseResponse( self, other, qtrue ); + */ + // else if ( self->behaviorSet[BSET_USE] ) + if (self->behaviorSet[BSET_USE]) { + NPC_UseResponse(self, other, qtrue); } -// else if ( isMedic( self ) ) -// {//Heal me NOW, dammit! -// NPC_TakePatient( activator ); -// } - else if ( !self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); + // else if ( isMedic( self ) ) + // {//Heal me NOW, dammit! + // NPC_TakePatient( activator ); + // } + else if (!self->enemy && activator->s.number == 0 && !gi.VoiceVolume[self->s.number] && + !(self->NPC->scriptFlags & SCF_NO_RESPONSE)) { // I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse(self, other, qfalse); } } RestoreNPCGlobals(); } -void NPC_CheckPlayerAim( void ) -{ - //FIXME: need appropriate dialogue +void NPC_CheckPlayerAim(void) { + // FIXME: need appropriate dialogue /* gentity_t *player = &g_entities[0]; if ( player && player->client && player->client->ps.weapon > (int)(WP_NONE) && player->client->ps.weapon < (int)(WP_TRICORDER) ) {//player has a weapon ready - if ( g_crosshairEntNum == NPC->s.number && level.time - g_crosshairEntTime < 200 + if ( g_crosshairEntNum == NPC->s.number && level.time - g_crosshairEntTime < 200 && g_crosshairSameEntTime >= 3000 && g_crosshairEntDist < 256 ) {//if the player holds the crosshair on you for a few seconds //ask them what the fuck they're doing @@ -1050,9 +821,8 @@ void NPC_CheckPlayerAim( void ) */ } -void NPC_CheckAllClear( void ) -{ - //FIXME: need to make this happen only once after losing enemies, not over and over again +void NPC_CheckAllClear(void) { + // FIXME: need to make this happen only once after losing enemies, not over and over again /* if ( NPC->client && !NPC->enemy && level.time - teamLastEnemyTime[NPC->client->playerTeam] > 10000 ) {//Team hasn't seen an enemy in 10 seconds diff --git a/codeJK2/game/NPC_senses.cpp b/codeJK2/game/NPC_senses.cpp index bf7ee9dfdf..8920700379 100644 --- a/codeJK2/game/NPC_senses.cpp +++ b/codeJK2/game/NPC_senses.cpp @@ -20,13 +20,13 @@ along with this program; if not, see . =========================================================================== */ -//NPC_senses.cpp +// NPC_senses.cpp #include "g_headers.h" #include "b_local.h" #ifdef _DEBUG - #include +#include #endif extern int eventClearTime; @@ -35,25 +35,21 @@ qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore returns true if can see from point 1 to 2, even through glass (1 pane)- doesn't work with portals */ -qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) -{ - trace_t tr; +qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) { + trace_t tr; - gi.trace ( &tr, point1, NULL, NULL, point2, ignore, clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.fraction == 1.0 ) - { + gi.trace(&tr, point1, NULL, NULL, point2, ignore, clipmask, G2_NOCOLLIDE, 0); + if (tr.fraction == 1.0) { return qtrue; } - gentity_t *hit = &g_entities[ tr.entityNum ]; - if(EntIsGlass(hit)) - { - vec3_t newpoint1; + gentity_t *hit = &g_entities[tr.entityNum]; + if (EntIsGlass(hit)) { + vec3_t newpoint1; VectorCopy(tr.endpos, newpoint1); - gi.trace (&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, G2_NOCOLLIDE, 0); - if ( tr.fraction == 1.0 ) - { + if (tr.fraction == 1.0) { return qtrue; } } @@ -70,55 +66,50 @@ or take any AI related factors (for example, the NPC's reaction time) into accou FIXME do we need fat and thin version of this? */ -qboolean CanSee ( gentity_t *ent ) -{ - trace_t tr; - vec3_t eyes; - vec3_t spot; - - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); - - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { +qboolean CanSee(gentity_t *ent) { + trace_t tr; + vec3_t eyes; + vec3_t spot; + + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); + + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - gi.trace ( &tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + gi.trace(&tr, eyes, NULL, NULL, spot, NPC->s.number, MASK_OPAQUE, G2_NOCOLLIDE, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } return qfalse; } -qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ) -{ - vec3_t dir, forward, angles; - float dot; +qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f) { + vec3_t dir, forward, angles; + float dot; - VectorSubtract( spot, from, dir ); + VectorSubtract(spot, from, dir); dir[2] = 0; - VectorNormalize( dir ); + VectorNormalize(dir); - VectorCopy( fromAngles, angles ); + VectorCopy(fromAngles, angles); angles[0] = 0; - AngleVectors( angles, forward, NULL, NULL ); + AngleVectors(angles, forward, NULL, NULL); - dot = DotProduct( dir, forward ); + dot = DotProduct(dir, forward); return (qboolean)(dot > threshHold); } @@ -130,121 +121,104 @@ IDEA: further off to side of FOV range, higher chance of failing even if technic keep core of 50% to sides as always succeeding */ -//Position compares +// Position compares -qboolean InFOV( vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV ) -{ - vec3_t deltaVector, angles, deltaAngles; +qboolean InFOV(vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV) { + vec3_t deltaVector, angles, deltaAngles; - VectorSubtract ( spot, from, deltaVector ); - vectoangles ( deltaVector, angles ); - - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); + VectorSubtract(spot, from, deltaVector); + vectoangles(deltaVector, angles); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -//NPC to position +// NPC to position -qboolean InFOV( vec3_t origin, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t fromAngles, eyes; +qboolean InFOV(vec3_t origin, gentity_t *from, int hFOV, int vFOV) { + vec3_t fromAngles, eyes; - if( from->client ) - { + if (from->client) { VectorCopy(from->client->ps.viewangles, fromAngles); - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD, eyes ); + CalcEntitySpot(from, SPOT_HEAD, eyes); - return InFOV( origin, eyes, fromAngles, hFOV, vFOV ); + return InFOV(origin, eyes, fromAngles, hFOV, vFOV); } -//Entity to entity - -qboolean InFOV ( gentity_t *ent, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - vec3_t angles, fromAngles; - vec3_t deltaAngles; - - if( from->client ) - { - if( !VectorCompare( from->client->renderInfo.eyeAngles, vec3_origin ) ) - {//Actual facing of tag_head! - //NOTE: Stasis aliens may have a problem with this? - VectorCopy( from->client->renderInfo.eyeAngles, fromAngles ); +// Entity to entity + +qboolean InFOV(gentity_t *ent, gentity_t *from, int hFOV, int vFOV) { + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + vec3_t angles, fromAngles; + vec3_t deltaAngles; + + if (from->client) { + if (!VectorCompare(from->client->renderInfo.eyeAngles, vec3_origin)) { // Actual facing of tag_head! + // NOTE: Stasis aliens may have a problem with this? + VectorCopy(from->client->renderInfo.eyeAngles, fromAngles); + } else { + VectorCopy(from->client->ps.viewangles, fromAngles); } - else - { - VectorCopy( from->client->ps.viewangles, fromAngles ); - } - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(from, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -qboolean InVisrange ( gentity_t *ent ) -{//FIXME: make a calculate visibility for ents that takes into account - //lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - float visrange = (NPCInfo->stats.visrange*NPCInfo->stats.visrange); +qboolean InVisrange(gentity_t *ent) { // FIXME: make a calculate visibility for ents that takes into account + // lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + float visrange = (NPCInfo->stats.visrange * NPCInfo->stats.visrange); - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); /*if(ent->client) { @@ -268,8 +242,7 @@ qboolean InVisrange ( gentity_t *ent ) } }*/ - if(VectorLengthSquared(deltaVector) > visrange) - { + if (VectorLengthSquared(deltaVector) > visrange) { return qfalse; } @@ -280,69 +253,54 @@ qboolean InVisrange ( gentity_t *ent ) NPC_CheckVisibility */ -visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) -{ +visibility_t NPC_CheckVisibility(gentity_t *ent, int flags) { // flags should never be 0 - if ( !flags ) - { + if (!flags) { return VIS_NOT; } // check PVS - if ( flags & CHECK_PVS ) - { - if ( !gi.inPVS ( ent->currentOrigin, NPC->currentOrigin ) ) - { + if (flags & CHECK_PVS) { + if (!gi.inPVS(ent->currentOrigin, NPC->currentOrigin)) { return VIS_NOT; } } - if ( !(flags & (CHECK_360|CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_360 | CHECK_FOV | CHECK_SHOOT))) { return VIS_PVS; } // check within visrange - if (flags & CHECK_VISRANGE) - { - if( !InVisrange ( ent ) ) - { + if (flags & CHECK_VISRANGE) { + if (!InVisrange(ent)) { return VIS_PVS; } } // check 360 degree visibility - //Meaning has to be a direct line of site - if ( flags & CHECK_360 ) - { - if ( !CanSee ( ent ) ) - { + // Meaning has to be a direct line of site + if (flags & CHECK_360) { + if (!CanSee(ent)) { return VIS_PVS; } } - if ( !(flags & (CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_FOV | CHECK_SHOOT))) { return VIS_360; } // check FOV - if ( flags & CHECK_FOV ) - { - if ( !InFOV ( ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) ) - { + if (flags & CHECK_FOV) { + if (!InFOV(ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov)) { return VIS_360; } } - if ( !(flags & CHECK_SHOOT) ) - { + if (!(flags & CHECK_SHOOT)) { return VIS_FOV; } // check shootability - if ( flags & CHECK_SHOOT ) - { - if ( !CanShoot ( ent, NPC ) ) - { + if (flags & CHECK_SHOOT) { + if (!CanShoot(ent, NPC)) { return VIS_FOV; } } @@ -355,52 +313,48 @@ visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) NPC_CheckSoundEvents ------------------------- */ -static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - int bestEvent = -1; +static int G_CheckSoundEvents(gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; + int bestTime = -1; float dist, radius; maxHearDist *= maxHearDist; - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( i == ignoreAlert ) + for (int i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (i == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SOUND ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SOUND) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->currentOrigin); - //can't hear it - if ( dist > maxHearDist ) + // can't hear it + if (dist > maxHearDist) continue; radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - if ( level.alertEvents[i].addLight ) - {//a quiet sound, must have LOS to hear it - if ( G_ClearLOS( self, level.alertEvents[i].position ) == qfalse ) - {//no LOS, didn't hear it + if (level.alertEvents[i].addLight) { // a quiet sound, must have LOS to hear it + if (G_ClearLOS(self, level.alertEvents[i].position) == qfalse) { // no LOS, didn't hear it continue; } } - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -410,14 +364,13 @@ static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAle return bestEvent; } -float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) -{ - vec3_t ambient={0}, directed, lightDir; - float lightLevel; +float G_GetLightLevel(vec3_t pos, vec3_t fromDir) { + vec3_t ambient = {0}, directed, lightDir; + float lightLevel; - cgi_R_GetLighting( pos, ambient, directed, lightDir ); + cgi_R_GetLighting(pos, ambient, directed, lightDir); - lightLevel = VectorLength( ambient ) + (VectorLength( directed )*DotProduct( lightDir, fromDir )); + lightLevel = VectorLength(ambient) + (VectorLength(directed) * DotProduct(lightDir, fromDir)); return lightLevel; } @@ -426,58 +379,56 @@ float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) NPC_CheckSightEvents ------------------------- */ -static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - int bestEvent = -1; +static int G_CheckSightEvents(gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; - float dist, radius; + int bestTime = -1; + float dist, radius; maxSeeDist *= maxSeeDist; - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( i == ignoreAlert ) + for (int i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (i == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SIGHT ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SIGHT) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->currentOrigin); - //can't see it - if ( dist > maxSeeDist ) + // can't see it + if (dist > maxSeeDist) continue; radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - //Must be visible - if ( InFOV( level.alertEvents[i].position, self, hFOV, vFOV ) == qfalse ) + // Must be visible + if (InFOV(level.alertEvents[i].position, self, hFOV, vFOV) == qfalse) continue; - if ( G_ClearLOS( self, level.alertEvents[i].position ) == qfalse ) + if (G_ClearLOS(self, level.alertEvents[i].position) == qfalse) continue; - //FIXME: possibly have the light level at this point affect the + // FIXME: possibly have the light level at this point affect the // visibility/alert level of this event? Would also // need to take into account how bright the event // itself is. A lightsaber would stand out more // in the dark... maybe pass in a light level that // is added to the actual light level at this position? - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -491,15 +442,14 @@ static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSee ------------------------- NPC_CheckAlertEvents - NOTE: Should all NPCs create alertEvents too so they can detect each other? + NOTE: Should all NPCs create alertEvents too so they can detect each other? ------------------------- */ -int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - if ( &g_entities[0] == NULL || g_entities[0].health <= 0 ) - { - //player is dead +int G_CheckAlertEvents(gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, + int minAlertLevel) { + if (&g_entities[0] == NULL || g_entities[0].health <= 0) { + // player is dead return -1; } @@ -508,86 +458,71 @@ int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSoun int bestSoundAlert = -1; int bestSightAlert = -1; - //get sound event - bestSoundEvent = G_CheckSoundEvents( self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel ); - //get sound event alert level - if ( bestSoundEvent >= 0 ) - { + // get sound event + bestSoundEvent = G_CheckSoundEvents(self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel); + // get sound event alert level + if (bestSoundEvent >= 0) { bestSoundAlert = level.alertEvents[bestSoundEvent].level; } - //get sight event - if ( self->NPC ) - { - bestSightEvent = G_CheckSightEvents( self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel ); - } - else - { - bestSightEvent = G_CheckSightEvents( self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel );//FIXME: look at cg_view to get more accurate numbers? + // get sight event + if (self->NPC) { + bestSightEvent = G_CheckSightEvents(self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); + } else { + bestSightEvent = + G_CheckSightEvents(self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); // FIXME: look at cg_view to get more accurate numbers? } - //get sight event alert level - if ( bestSightEvent >= 0 ) - { + // get sight event alert level + if (bestSightEvent >= 0) { bestSightAlert = level.alertEvents[bestSightEvent].level; } - //return the one that has a higher alert (or sound if equal) - //FIXME: This doesn't take the distance of the event into account + // return the one that has a higher alert (or sound if equal) + // FIXME: This doesn't take the distance of the event into account - if ( bestSightEvent >= 0 && bestSightAlert > bestSoundAlert ) - {//valid best sight event, more important than the sound event - //get the light level of the alert event for this checker - vec3_t eyePoint, sightDir; - //get eye point - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyePoint ); - VectorSubtract( level.alertEvents[bestSightEvent].position, eyePoint, sightDir ); - level.alertEvents[bestSightEvent].light = level.alertEvents[bestSightEvent].addLight + G_GetLightLevel( level.alertEvents[bestSightEvent].position, sightDir ); - //return the sight event + if (bestSightEvent >= 0 && bestSightAlert > bestSoundAlert) { // valid best sight event, more important than the sound event + // get the light level of the alert event for this checker + vec3_t eyePoint, sightDir; + // get eye point + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyePoint); + VectorSubtract(level.alertEvents[bestSightEvent].position, eyePoint, sightDir); + level.alertEvents[bestSightEvent].light = + level.alertEvents[bestSightEvent].addLight + G_GetLightLevel(level.alertEvents[bestSightEvent].position, sightDir); + // return the sight event return bestSightEvent; } - //return the sound event + // return the sound event return bestSoundEvent; } -int NPC_CheckAlertEvents( qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - return G_CheckAlertEvents( NPC, checkSight, checkSound, NPCInfo->stats.visrange, NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, minAlertLevel ); +int NPC_CheckAlertEvents(qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + return G_CheckAlertEvents(NPC, checkSight, checkSound, NPCInfo->stats.visrange, NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, minAlertLevel); } -qboolean G_CheckForDanger( gentity_t *self, int alertEvent ) -{//FIXME: more bStates need to call this? - if ( alertEvent == -1 ) - { +qboolean G_CheckForDanger(gentity_t *self, int alertEvent) { // FIXME: more bStates need to call this? + if (alertEvent == -1) { return qfalse; } - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || (level.alertEvents[alertEvent].owner!=self&&level.alertEvents[alertEvent].owner->client->playerTeam!=self->client->playerTeam) ) - { - if ( self->NPC ) - { - if ( self->NPC->scriptFlags & SCF_DONT_FLEE ) - {//can't flee + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != self && level.alertEvents[alertEvent].owner->client->playerTeam != self->client->playerTeam)) { + if (self->NPC) { + if (self->NPC->scriptFlags & SCF_DONT_FLEE) { // can't flee return qfalse; - } - else - { - NPC_StartFlee( level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, 6000 ); + } else { + NPC_StartFlee(level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, 6000); return qtrue; } - } - else - { + } else { return qtrue; } } } return qfalse; } -qboolean NPC_CheckForDanger( int alertEvent ) -{//FIXME: more bStates need to call this? - return G_CheckForDanger( NPC, alertEvent ); +qboolean NPC_CheckForDanger(int alertEvent) { // FIXME: more bStates need to call this? + return G_CheckForDanger(NPC, alertEvent); } /* @@ -595,44 +530,38 @@ qboolean NPC_CheckForDanger( int alertEvent ) AddSoundEvent ------------------------- */ -qboolean RemoveOldestAlert( void ); -void AddSoundEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +qboolean RemoveOldestAlert(void); +void AddSoundEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: if owner is not a player or player ally, and there are no player allies present, - // perhaps we don't need to store the alert... unless we want the player to - // react to enemy alert events in some way? + // FIXME: if owner is not a player or player ally, and there are no player allies present, + // perhaps we don't need to store the alert... unless we want the player to + // react to enemy alert events in some way? #ifdef _DEBUG - assert( !Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2]) ); + assert(!Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2])); #endif - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SOUND; - level.alertEvents[ level.numAlertEvents ].owner = owner; - if ( needLOS ) - {//a very low-level sound, when check this sound event, check for LOS - level.alertEvents[ level.numAlertEvents ].addLight = 1; //will force an LOS trace on this sound + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SOUND; + level.alertEvents[level.numAlertEvents].owner = owner; + if (needLOS) { // a very low-level sound, when check this sound event, check for LOS + level.alertEvents[level.numAlertEvents].addLight = 1; // will force an LOS trace on this sound + } else { + level.alertEvents[level.numAlertEvents].addLight = 0; // will force an LOS trace on this sound } - else - { - level.alertEvents[ level.numAlertEvents ].addLight = 0; //will force an LOS trace on this sound - } - level.alertEvents[ level.numAlertEvents ].ID = level.curAlertID++; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].ID = level.curAlertID++; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -643,36 +572,33 @@ AddSightEvent ------------------------- */ -void AddSightEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +void AddSightEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: if owner is not a player or player ally, and there are no player allies present, - // perhaps we don't need to store the alert... unless we want the player to - // react to enemy alert events in some way? + // FIXME: if owner is not a player or player ally, and there are no player allies present, + // perhaps we don't need to store the alert... unless we want the player to + // react to enemy alert events in some way? #ifdef _DEBUG - assert( !Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2]) ); + assert(!Q_isnan(position[0]) && !Q_isnan(position[1]) && !Q_isnan(position[2])); #endif - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SIGHT; - level.alertEvents[ level.numAlertEvents ].owner = owner; - level.alertEvents[ level.numAlertEvents ].addLight = addLight; //will get added to actual light at that point when it's checked - level.alertEvents[ level.numAlertEvents ].ID = level.curAlertID++; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SIGHT; + level.alertEvents[level.numAlertEvents].owner = owner; + level.alertEvents[level.numAlertEvents].addLight = addLight; // will get added to actual light at that point when it's checked + level.alertEvents[level.numAlertEvents].ID = level.curAlertID++; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -683,73 +609,58 @@ ClearPlayerAlertEvents ------------------------- */ -void ClearPlayerAlertEvents( void ) -{ +void ClearPlayerAlertEvents(void) { int curNumAlerts = level.numAlertEvents; - //loop through them all (max 32) - for ( int i = 0; i < curNumAlerts; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time ) - {//this event has timed out - //drop the count + // loop through them all (max 32) + for (int i = 0; i < curNumAlerts; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time) { // this event has timed out + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (i+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[i], &level.alertEvents[i+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(i+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((i + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[i], &level.alertEvents[i + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (i + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[i], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[i], 0, sizeof(alertEvent_t)); } } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); + // make sure this never drops below zero... if it does, something very very bad happened + assert(level.numAlertEvents >= 0); - if ( eventClearTime < level.time ) - {//this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms + if (eventClearTime < + level.time) { // this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms eventClearTime = level.time + ALERT_CLEAR_TIME; } } -qboolean RemoveOldestAlert( void ) -{ - int oldestEvent = -1, oldestTime = Q3_INFINITE; - //loop through them all (max 32) - for ( int i = 0; i < level.numAlertEvents; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp < oldestTime ) - { +qboolean RemoveOldestAlert(void) { + int oldestEvent = -1, oldestTime = Q3_INFINITE; + // loop through them all (max 32) + for (int i = 0; i < level.numAlertEvents; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp < oldestTime) { oldestEvent = i; oldestTime = level.alertEvents[i].timestamp; } } - if ( oldestEvent != -1 ) - { - //drop the count + if (oldestEvent != -1) { + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (oldestEvent+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(oldestEvent+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((oldestEvent + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (oldestEvent + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[oldestEvent], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[oldestEvent], 0, sizeof(alertEvent_t)); } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); - //return true is have room for one now + // make sure this never drops below zero... if it does, something very very bad happened + assert(level.numAlertEvents >= 0); + // return true is have room for one now return (qboolean)(level.numAlertEvents < MAX_ALERT_EVENTS); } @@ -760,20 +671,16 @@ G_ClearLOS */ // Position to position -qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) -{ - trace_t tr; - int traceCount = 0; - - //FIXME: ENTITYNUM_NONE ok? - gi.trace ( &tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE/*CONTENTS_SOLID*//*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, G2_NOCOLLIDE, 0 ); - while ( tr.fraction < 1.0 && traceCount < 3 ) - {//can see through 3 panes of glass - if ( tr.entityNum < ENTITYNUM_WORLD ) - { - if ( &g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].svFlags&SVF_GLASS_BRUSH) ) - {//can see through glass, trace again, ignoring me - gi.trace ( &tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, G2_NOCOLLIDE, 0 ); +qboolean G_ClearLOS(gentity_t *self, const vec3_t start, const vec3_t end) { + trace_t tr; + int traceCount = 0; + + // FIXME: ENTITYNUM_NONE ok? + gi.trace(&tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE /*CONTENTS_SOLID*/ /*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, G2_NOCOLLIDE, 0); + while (tr.fraction < 1.0 && traceCount < 3) { // can see through 3 panes of glass + if (tr.entityNum < ENTITYNUM_WORLD) { + if (&g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].svFlags & SVF_GLASS_BRUSH)) { // can see through glass, trace again, ignoring me + gi.trace(&tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, G2_NOCOLLIDE, 0); traceCount++; continue; } @@ -781,62 +688,58 @@ qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) return qfalse; } - if ( tr.fraction == 1.0 ) + if (tr.fraction == 1.0) return qtrue; return qfalse; } -//Entity to position -qboolean G_ClearLOS( gentity_t *self, gentity_t *ent, const vec3_t end ) -{ - vec3_t eyes; +// Entity to position +qboolean G_ClearLOS(gentity_t *self, gentity_t *ent, const vec3_t end) { + vec3_t eyes; - CalcEntitySpot( ent, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(ent, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } -//Position to entity -qboolean G_ClearLOS( gentity_t *self, const vec3_t start, gentity_t *ent ) -{ - vec3_t spot; +// Position to entity +qboolean G_ClearLOS(gentity_t *self, const vec3_t start, gentity_t *ent) { + vec3_t spot; - //Look for the chest first - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); + // Look for the chest first + CalcEntitySpot(ent, SPOT_ORIGIN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; - //Look for the head next - CalcEntitySpot( ent, SPOT_HEAD_LEAN, spot ); + // Look for the head next + CalcEntitySpot(ent, SPOT_HEAD_LEAN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; return qfalse; } -//NPC's eyes to entity -qboolean G_ClearLOS( gentity_t *self, gentity_t *ent ) -{ - vec3_t eyes; +// NPC's eyes to entity +qboolean G_ClearLOS(gentity_t *self, gentity_t *ent) { + vec3_t eyes; - //Calculate my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); - - return G_ClearLOS( self, eyes, ent ); + // Calculate my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); + + return G_ClearLOS(self, eyes, ent); } -//NPC's eyes to position -qboolean G_ClearLOS( gentity_t *self, const vec3_t end ) -{ - vec3_t eyes; +// NPC's eyes to position +qboolean G_ClearLOS(gentity_t *self, const vec3_t end) { + vec3_t eyes; + + // Calculate the my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); - //Calculate the my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); - - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } /* @@ -845,21 +748,20 @@ NPC_GetFOVPercentage ------------------------- */ -float NPC_GetHFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float hFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetHFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float hFOV) { + vec3_t deltaVector, angles; + float delta; - VectorSubtract ( spot, from, deltaVector ); + VectorSubtract(spot, from, deltaVector); - vectoangles ( deltaVector, angles ); - - delta = fabs( AngleDelta ( facing[YAW], angles[YAW] ) ); + vectoangles(deltaVector, angles); - if ( delta > hFOV ) - return 0.0f; + delta = fabs(AngleDelta(facing[YAW], angles[YAW])); - return ( ( hFOV - delta ) / hFOV ); + if (delta > hFOV) + return 0.0f; + + return ((hFOV - delta) / hFOV); } /* @@ -868,64 +770,56 @@ NPC_GetVFOVPercentage ------------------------- */ -float NPC_GetVFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float vFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetVFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float vFOV) { + vec3_t deltaVector, angles; + float delta; + + VectorSubtract(spot, from, deltaVector); - VectorSubtract ( spot, from, deltaVector ); + vectoangles(deltaVector, angles); - vectoangles ( deltaVector, angles ); - - delta = fabs( AngleDelta ( facing[PITCH], angles[PITCH] ) ); + delta = fabs(AngleDelta(facing[PITCH], angles[PITCH])); - if ( delta > vFOV ) - return 0.0f; + if (delta > vFOV) + return 0.0f; - return ( ( vFOV - delta ) / vFOV ); + return ((vFOV - delta) / vFOV); } -#define MAX_INTEREST_DIST ( 256 * 256 ) +#define MAX_INTEREST_DIST (256 * 256) /* ------------------------- -NPC_FindLocalInterestPoint +NPC_FindLocalInterestPoint ------------------------- */ -int G_FindLocalInterestPoint( gentity_t *self ) -{ - int i, bestPoint = ENTITYNUM_NONE; - float dist, bestDist = Q3_INFINITE; - vec3_t diffVec, eyes; - - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); - for ( i = 0; i < level.numInterestPoints; i++ ) - { - //Don't ignore portals? If through a portal, need to look at portal! - if ( gi.inPVS( level.interestPoints[i].origin, eyes ) ) - { - VectorSubtract( level.interestPoints[i].origin, eyes, diffVec ); - if ( (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && - fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 ) - {//Too close to look so far up or down +int G_FindLocalInterestPoint(gentity_t *self) { + int i, bestPoint = ENTITYNUM_NONE; + float dist, bestDist = Q3_INFINITE; + vec3_t diffVec, eyes; + + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); + for (i = 0; i < level.numInterestPoints; i++) { + // Don't ignore portals? If through a portal, need to look at portal! + if (gi.inPVS(level.interestPoints[i].origin, eyes)) { + VectorSubtract(level.interestPoints[i].origin, eyes, diffVec); + if ((fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && + fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2) { // Too close to look so far up or down continue; } - dist = VectorLengthSquared( diffVec ); - //Some priority to more interesting points - //dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); - if ( dist < MAX_INTEREST_DIST && dist < bestDist ) - { - if ( G_ClearLineOfSight( eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE ) ) - { + dist = VectorLengthSquared(diffVec); + // Some priority to more interesting points + // dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); + if (dist < MAX_INTEREST_DIST && dist < bestDist) { + if (G_ClearLineOfSight(eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE)) { bestDist = dist; bestPoint = i; } } } } - if ( bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target ) - { - G_UseTargets2( self, self, level.interestPoints[bestPoint].target ); + if (bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target) { + G_UseTargets2(self, self, level.interestPoints[bestPoint].target); } return bestPoint; } @@ -936,10 +830,8 @@ A point that a squadmate will look at if standing still target - thing to fire when someone looks at this thing */ -void SP_target_interest( gentity_t *self ) -{//FIXME: rename point_interest - if(level.numInterestPoints >= MAX_INTEREST_POINTS) - { +void SP_target_interest(gentity_t *self) { // FIXME: rename point_interest + if (level.numInterestPoints >= MAX_INTEREST_POINTS) { gi.Printf("ERROR: Too many interest points, limit is %d\n", MAX_INTEREST_POINTS); G_FreeEntity(self); return; @@ -947,9 +839,8 @@ void SP_target_interest( gentity_t *self ) VectorCopy(self->currentOrigin, level.interestPoints[level.numInterestPoints].origin); - if(self->target && self->target[0]) - { - level.interestPoints[level.numInterestPoints].target = G_NewString( self->target ); + if (self->target && self->target[0]) { + level.interestPoints[level.numInterestPoints].target = G_NewString(self->target); } level.numInterestPoints++; diff --git a/codeJK2/game/NPC_sounds.cpp b/codeJK2/game/NPC_sounds.cpp index 21917661c5..9716f706fa 100644 --- a/codeJK2/game/NPC_sounds.cpp +++ b/codeJK2/game/NPC_sounds.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_sounds.cpp +// NPC_sounds.cpp #include "g_headers.h" @@ -44,75 +44,66 @@ void NPC_AngerSound (void) } */ -extern void G_SpeechEvent( gentity_t *self, int event ); -void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ) -{ - if ( !self->NPC ) - { +extern void G_SpeechEvent(gentity_t *self, int event); +void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime) { + if (!self->NPC) { return; } - if ( !self->client || self->client->ps.pm_type >= PM_DEAD ) - { + if (!self->client || self->client->ps.pm_type >= PM_DEAD) { return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - if ( Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { + if (Q3_TaskIDPending(self, TID_CHAN_VOICE)) { return; } - - if ( (self->NPC->scriptFlags&SCF_NO_COMBAT_TALK) && ( (event >= EV_ANGER1 && event <= EV_VICTORY3) || (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5) ) )//(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) + if ((self->NPC->scriptFlags & SCF_NO_COMBAT_TALK) && + ((event >= EV_ANGER1 && event <= EV_VICTORY3) || + (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5))) //(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) { return; } - - if ( (self->NPC->scriptFlags&SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5) ) - { + + if ((self->NPC->scriptFlags & SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5)) { return; } - //FIXME: Also needs to check for teammates. Don't want + // FIXME: Also needs to check for teammates. Don't want // everyone babbling at once - //NOTE: was losing too many speech events, so we do it directly now, screw networking! - //G_AddEvent( self, event, 0 ); - G_SpeechEvent( self, event ); + // NOTE: was losing too many speech events, so we do it directly now, screw networking! + // G_AddEvent( self, event, 0 ); + G_SpeechEvent(self, event); - //won't speak again for 5 seconds (unless otherwise specified) - self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime==0) ? 5000 : speakDebounceTime); + // won't speak again for 5 seconds (unless otherwise specified) + self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime == 0) ? 5000 : speakDebounceTime); } -void NPC_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->enemy ||//was mad - !TIMER_Done( self, "enemyLastVisible" ) ||//saw something suspicious - self->client->renderInfo.lookTarget == 0//was looking at player - ) +void NPC_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->enemy || // was mad + !TIMER_Done(self, "enemyLastVisible") || // saw something suspicious + self->client->renderInfo.lookTarget == 0 // was looking at player + ) { + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE2, EV_CONFUSE3), 2000); + } else if (self->NPC && self->NPC->investigateDebounceTime + self->NPC->pauseTime > level.time) // was checking something out { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE2, EV_CONFUSE3 ), 2000 ); + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, EV_CONFUSE1, 2000); } - else if ( self->NPC && self->NPC->investigateDebounceTime+self->NPC->pauseTime > level.time )//was checking something out - { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, EV_CONFUSE1, 2000 ); - } - //G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + // G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); self->NPC->tempBehavior = BS_DEFAULT; - - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } diff --git a/codeJK2/game/NPC_spawn.cpp b/codeJK2/game/NPC_spawn.cpp index f5343ef5c4..9a90351997 100644 --- a/codeJK2/game/NPC_spawn.cpp +++ b/codeJK2/game/NPC_spawn.cpp @@ -20,8 +20,8 @@ along with this program; if not, see . =========================================================================== */ -//b_spawn.cpp -//added by MCG +// b_spawn.cpp +// added by MCG #include "g_headers.h" @@ -33,53 +33,52 @@ along with this program; if not, see . extern cvar_t *g_sex; -extern qboolean G_CheckInSolid (gentity_t *self, qboolean fix); -extern void ClientUserinfoChanged( int clientNum ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -extern void Jedi_Cloak( gentity_t *self ); +extern qboolean G_CheckInSolid(gentity_t *self, qboolean fix); +extern void ClientUserinfoChanged(int clientNum); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +extern void Jedi_Cloak(gentity_t *self); -//extern void FX_BorgTeleport( vec3_t org ); +// extern void FX_BorgTeleport( vec3_t org ); -extern void G_MatchPlayerWeapon( gentity_t *ent ); -extern void Q3_SetParm (int entID, int parmNum, const char *parmValue); -extern team_t TranslateTeamName( const char *name ); -extern char *TeamNames[TEAM_NUM_TEAMS]; +extern void G_MatchPlayerWeapon(gentity_t *ent); +extern void Q3_SetParm(int entID, int parmNum, const char *parmValue); +extern team_t TranslateTeamName(const char *name); +extern char *TeamNames[TEAM_NUM_TEAMS]; -//extern void CG_ShimmeryThing_Spawner( vec3_t start, vec3_t end, float radius, qboolean taper, int duration ); -extern void Q3_DebugPrint( int level, const char *format, ... ); +// extern void CG_ShimmeryThing_Spawner( vec3_t start, vec3_t end, float radius, qboolean taper, int duration ); +extern void Q3_DebugPrint(int level, const char *format, ...); -//extern void NPC_StasisSpawnEffect( gentity_t *ent ); +// extern void NPC_StasisSpawnEffect( gentity_t *ent ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); -extern void WP_SaberInitBladeData( gentity_t *ent ); -extern void ST_ClearTimers( gentity_t *ent ); -extern void Jedi_ClearTimers( gentity_t *ent ); -extern void NPC_ShadowTrooper_Precache( void ); -extern void NPC_Gonk_Precache( void ); -extern void NPC_Mouse_Precache( void ); -extern void NPC_Seeker_Precache( void ); -extern void NPC_Remote_Precache( void ); -extern void NPC_R2D2_Precache(void); -extern void NPC_R5D2_Precache(void); +extern void WP_SaberInitBladeData(gentity_t *ent); +extern void ST_ClearTimers(gentity_t *ent); +extern void Jedi_ClearTimers(gentity_t *ent); +extern void NPC_ShadowTrooper_Precache(void); +extern void NPC_Gonk_Precache(void); +extern void NPC_Mouse_Precache(void); +extern void NPC_Seeker_Precache(void); +extern void NPC_Remote_Precache(void); +extern void NPC_R2D2_Precache(void); +extern void NPC_R5D2_Precache(void); extern void NPC_Probe_Precache(void); extern void NPC_Interrogator_Precache(gentity_t *self); -extern void NPC_MineMonster_Precache( void ); -extern void NPC_Howler_Precache( void ); +extern void NPC_MineMonster_Precache(void); +extern void NPC_Howler_Precache(void); extern void NPC_ATST_Precache(void); extern void NPC_Sentry_Precache(void); extern void NPC_Mark1_Precache(void); extern void NPC_Mark2_Precache(void); -extern void NPC_GalakMech_Precache( void ); -extern void NPC_GalakMech_Init( gentity_t *ent ); -extern void NPC_Protocol_Precache( void ); -extern int WP_SetSaberModel( gclient_t *client, class_t npcClass ); +extern void NPC_GalakMech_Precache(void); +extern void NPC_GalakMech_Init(gentity_t *ent); +extern void NPC_Protocol_Precache(void); +extern int WP_SetSaberModel(gclient_t *client, class_t npcClass); -#define NSF_DROP_TO_FLOOR 16 +#define NSF_DROP_TO_FLOOR 16 - -//void HirogenAlpha_Precache( void ); +// void HirogenAlpha_Precache( void ); /* ------------------------- @@ -87,16 +86,12 @@ NPC_PainFunc ------------------------- */ -painFunc_t NPC_PainFunc( gentity_t *ent ) -{ - painFunc_t func; +painFunc_t NPC_PainFunc(gentity_t *ent) { + painFunc_t func; - if ( ent->client->ps.weapon == WP_SABER ) - { + if (ent->client->ps.weapon == WP_SABER) { func = painF_NPC_Jedi_Pain; - } - else - { + } else { // team no longer indicates race/species, use NPC_class to determine different npc types /* switch ( ent->client->playerTeam ) @@ -106,8 +101,7 @@ painFunc_t NPC_PainFunc( gentity_t *ent ) break; } */ - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { // troopers get special pain case CLASS_STORMTROOPER: case CLASS_SWAMPTROOPER: @@ -152,7 +146,7 @@ painFunc_t NPC_PainFunc( gentity_t *ent ) case CLASS_MARK2: func = painF_NPC_Mark2_Pain; break; - case CLASS_ATST: + case CLASS_ATST: func = painF_NPC_ATST_Pain; break; case CLASS_GALAKMECH: @@ -163,23 +157,18 @@ painFunc_t NPC_PainFunc( gentity_t *ent ) func = painF_NPC_Pain; break; } - } return func; } - /* ------------------------- NPC_TouchFunc ------------------------- */ -touchFunc_t NPC_TouchFunc( gentity_t *ent ) -{ - return touchF_NPC_Touch; -} +touchFunc_t NPC_TouchFunc(gentity_t *ent) { return touchF_NPC_Touch; } /* ------------------------- @@ -187,51 +176,40 @@ NPC_SetMiscDefaultData ------------------------- */ -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -void NPC_SetMiscDefaultData( gentity_t *ent ) -{ - if ( ent->spawnflags & SFB_CINEMATIC ) - {//if a cinematic guy, default us to wait bState +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +void NPC_SetMiscDefaultData(gentity_t *ent) { + if (ent->spawnflags & SFB_CINEMATIC) { // if a cinematic guy, default us to wait bState ent->NPC->behaviorState = BS_CINEMATIC; } //***I'm not sure whether I should leave this as a TEAM_ switch, I think NPC_class may be more appropriate - dmv - switch(ent->client->playerTeam) - { + switch (ent->client->playerTeam) { case TEAM_PLAYER: - //ent->flags |= FL_NO_KNOCKBACK; - if ( ent->client->NPC_class == CLASS_SEEKER ) - { + // ent->flags |= FL_NO_KNOCKBACK; + if (ent->client->NPC_class == CLASS_SEEKER) { ent->NPC->defaultBehavior = BS_DEFAULT; ent->client->ps.gravity = 0; ent->svFlags |= SVF_CUSTOM_GRAVITY; ent->NPC->stats.moveType = MT_FLYSWIM; ent->count = 30; // SEEKER shot ammo count return; - } - else if ( ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_LUKE ) - {//good jedi + } else if (ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_LUKE) { // good jedi ent->client->ps.saberActive = qfalse; ent->client->ps.saberLength = 0; - WP_SaberInitBladeData( ent ); - G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saberModel ); + WP_SaberInitBladeData(ent); + G_CreateG2AttachedWeaponModel(ent, ent->client->ps.saberModel); ent->client->enemyTeam = TEAM_ENEMY; - WP_InitForcePowers( ent ); - Jedi_ClearTimers( ent ); - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher + WP_InitForcePowers(ent); + Jedi_ClearTimers(ent); + if (ent->spawnflags & JSF_AMBUSH) { // ambusher ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = qtrue;//hang + ent->client->noclip = qtrue; // hang } - } - else - { - if (ent->client->ps.weapon != WP_NONE) - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl ); + } else { + if (ent->client->ps.weapon != WP_NONE) { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl); } - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL://FIXME: new weapon: imp blaster pistol + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: // FIXME: new weapon: imp blaster pistol case WP_BLASTER_PISTOL: case WP_DISRUPTOR: case WP_BOWCASTER: @@ -243,152 +221,129 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) break; case WP_THERMAL: case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //ent->health = 25; - //FIXME: not necc. a ST - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL ) - {//officers, grenade-throwers use alt-fire - //ent->health = 50; + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // ent->health = 25; + // FIXME: not necc. a ST + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL) { // officers, grenade-throwers use alt-fire + // ent->health = 50; ent->NPC->scriptFlags |= SCF_ALT_FIRE; } break; } } - if ( ent->client->NPC_class == CLASS_KYLE || (ent->spawnflags & SFB_CINEMATIC) ) - { + if (ent->client->NPC_class == CLASS_KYLE || (ent->spawnflags & SFB_CINEMATIC)) { ent->NPC->defaultBehavior = BS_CINEMATIC; - } - else - { + } else { ent->NPC->defaultBehavior = BS_FOLLOW_LEADER; ent->client->leader = &g_entities[0]; } break; - case TEAM_NEUTRAL: + case TEAM_NEUTRAL: - if ( Q_stricmp( ent->NPC_type, "gonk" ) == 0 ) - { + if (Q_stricmp(ent->NPC_type, "gonk") == 0) { // I guess we generically make them player usable ent->svFlags |= SVF_PLAYER_USABLE; // Not even sure if we want to give different levels of batteries? ...Or even that these are the values we'd want to use. - switch ( g_spskill->integer ) - { - case 0: // EASY - ent->client->ps.batteryCharge = MAX_BATTERIES * 0.8f; + switch (g_spskill->integer) { + case 0: // EASY + ent->client->ps.batteryCharge = MAX_BATTERIES * 0.8f; break; - case 1: // MEDIUM - ent->client->ps.batteryCharge = MAX_BATTERIES * 0.75f; + case 1: // MEDIUM + ent->client->ps.batteryCharge = MAX_BATTERIES * 0.75f; break; - default : - case 2: // HARD - ent->client->ps.batteryCharge = MAX_BATTERIES * 0.5f; + default: + case 2: // HARD + ent->client->ps.batteryCharge = MAX_BATTERIES * 0.5f; break; } } break; - case TEAM_ENEMY: - { - ent->NPC->defaultBehavior = BS_DEFAULT; - if ( ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//FIXME: a spawnflag? - Jedi_Cloak( ent ); + case TEAM_ENEMY: { + ent->NPC->defaultBehavior = BS_DEFAULT; + if (ent->client->NPC_class == CLASS_SHADOWTROOPER) { // FIXME: a spawnflag? + Jedi_Cloak(ent); + } + if (ent->client->NPC_class == CLASS_TAVION || ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_DESANN || + ent->client->NPC_class == CLASS_SHADOWTROOPER) { + ent->client->ps.saberActive = qfalse; + ent->client->ps.saberLength = 0; + WP_SaberInitBladeData(ent); + G_CreateG2AttachedWeaponModel(ent, ent->client->ps.saberModel); + WP_InitForcePowers(ent); + ent->client->enemyTeam = TEAM_PLAYER; + Jedi_ClearTimers(ent); + if (ent->spawnflags & JSF_AMBUSH) { // ambusher + ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; + ent->client->noclip = qtrue; // hang } - if( ent->client->NPC_class == CLASS_TAVION || - ent->client->NPC_class == CLASS_REBORN || - ent->client->NPC_class == CLASS_DESANN || - ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - ent->client->ps.saberActive = qfalse; - ent->client->ps.saberLength = 0; - WP_SaberInitBladeData( ent ); - G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saberModel ); - WP_InitForcePowers( ent ); - ent->client->enemyTeam = TEAM_PLAYER; - Jedi_ClearTimers( ent ); - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher - ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = qtrue;//hang + } else if (ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_SENTRY) { + ent->NPC->defaultBehavior = BS_DEFAULT; + ent->client->ps.gravity = 0; + ent->svFlags |= SVF_CUSTOM_GRAVITY; + ent->NPC->stats.moveType = MT_FLYSWIM; + } else { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl); + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: + break; + case WP_BLASTER_PISTOL: + break; + case WP_DISRUPTOR: + // Sniper + ent->NPC->scriptFlags |= SCF_ALT_FIRE; // FIXME: use primary fire sometimes? Up close? Different class of NPC? + break; + case WP_BOWCASTER: + break; + case WP_REPEATER: + // machine-gunner + break; + case WP_DEMP2: + break; + case WP_FLECHETTE: + // shotgunner + if (!Q_stricmp("stofficeralt", ent->NPC_type)) { + ent->NPC->scriptFlags |= SCF_ALT_FIRE; } - } - else if( ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || - ent->client->NPC_class == CLASS_INTERROGATOR || ent->client->NPC_class == CLASS_SENTRY) - { - ent->NPC->defaultBehavior = BS_DEFAULT; - ent->client->ps.gravity = 0; - ent->svFlags |= SVF_CUSTOM_GRAVITY; - ent->NPC->stats.moveType = MT_FLYSWIM; - } - else - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl ); - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL: - break; - case WP_BLASTER_PISTOL: - break; - case WP_DISRUPTOR: - //Sniper - ent->NPC->scriptFlags |= SCF_ALT_FIRE;//FIXME: use primary fire sometimes? Up close? Different class of NPC? - break; - case WP_BOWCASTER: - break; - case WP_REPEATER: - //machine-gunner - break; - case WP_DEMP2: - break; - case WP_FLECHETTE: - //shotgunner - if ( !Q_stricmp( "stofficeralt", ent->NPC_type ) ) - { - ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; - case WP_ROCKET_LAUNCHER: - break; - case WP_THERMAL: - //Gran, use main, bouncy fire -// ent->NPC->scriptFlags |= SCF_ALT_FIRE; - break; - case WP_MELEE: - break; - default: - case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //FIXME: not necc. a ST - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_COMMANDER ) - {//commanders use alt-fire - ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - if ( !Q_stricmp( "rodian2", ent->NPC_type ) ) - { - ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; + break; + case WP_ROCKET_LAUNCHER: + break; + case WP_THERMAL: + // Gran, use main, bouncy fire + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; + break; + case WP_MELEE: + break; + default: + case WP_BLASTER: + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // FIXME: not necc. a ST + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_COMMANDER) { // commanders use alt-fire + ent->NPC->scriptFlags |= SCF_ALT_FIRE; } - if ( !Q_stricmp( "galak_mech", ent->NPC_type ) ) - {//starts with armor - NPC_GalakMech_Init( ent ); + if (!Q_stricmp("rodian2", ent->NPC_type)) { + ent->NPC->scriptFlags |= SCF_ALT_FIRE; } + break; + } + if (!Q_stricmp("galak_mech", ent->NPC_type)) { // starts with armor + NPC_GalakMech_Init(ent); } } - break; + } break; default: break; } - - if ( ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1 ) // chris/steve/kevin requested that the mark1 be shielded also + if (ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1) // chris/steve/kevin requested that the mark1 be shielded also { - ent->flags |= (FL_SHIELDED|FL_NO_KNOCKBACK); + ent->flags |= (FL_SHIELDED | FL_NO_KNOCKBACK); } } @@ -398,213 +353,172 @@ NPC_WeaponsForTeam ------------------------- */ -int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ) -{ +int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type) { //*** not sure how to handle this, should I pass in class instead of team and go from there? - dmv - switch(team) - { + switch (team) { -// case TEAM_IMPERIAL: + // case TEAM_IMPERIAL: case TEAM_ENEMY: - if ( Q_stricmp( "tavion", NPC_type ) == 0 || - Q_strncmp( "reborn", NPC_type, 6 ) == 0 || - Q_stricmp( "desann", NPC_type ) == 0 || - Q_strncmp( "shadowtrooper", NPC_type, 13 ) == 0 ) - return ( 1 << WP_SABER); -// return ( 1 << WP_IMPERIAL_BLADE); - //NOTENOTE: Falls through if not a knife user - - //FIXME: default weapon in npc config? - if ( Q_strncmp( "stofficer", NPC_type, 9 ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("tavion", NPC_type) == 0 || Q_strncmp("reborn", NPC_type, 6) == 0 || Q_stricmp("desann", NPC_type) == 0 || + Q_strncmp("shadowtrooper", NPC_type, 13) == 0) + return (1 << WP_SABER); + // return ( 1 << WP_IMPERIAL_BLADE); + // NOTENOTE: Falls through if not a knife user + + // FIXME: default weapon in npc config? + if (Q_strncmp("stofficer", NPC_type, 9) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "stcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("stcommander", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "swamptrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("swamptrooper", NPC_type) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "swamptrooper2", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("swamptrooper2", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "rockettrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_ROCKET_LAUNCHER); + if (Q_stricmp("rockettrooper", NPC_type) == 0) { + return (1 << WP_ROCKET_LAUNCHER); } - if ( Q_strncmp( "shadowtrooper", NPC_type, 13 ) == 0 ) - { - return ( 1 << WP_SABER);//|( 1 << WP_RAPID_CONCUSSION)? + if (Q_strncmp("shadowtrooper", NPC_type, 13) == 0) { + return (1 << WP_SABER); //|( 1 << WP_RAPID_CONCUSSION)? } - if ( Q_stricmp( "imperial", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_stricmp("imperial", NPC_type) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_strncmp( "impworker", NPC_type, 9 ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_strncmp("impworker", NPC_type, 9) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_stricmp( "stormpilot", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER_PISTOL); + if (Q_stricmp("stormpilot", NPC_type) == 0) { + return (1 << WP_BLASTER_PISTOL); } - if ( Q_stricmp( "galak", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("galak", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "galak_mech", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("galak_mech", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_strncmp( "ugnaught", NPC_type, 8 ) == 0 ) - { + if (Q_strncmp("ugnaught", NPC_type, 8) == 0) { return WP_NONE; } - if ( Q_stricmp( "granshooter", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("granshooter", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "granboxer", NPC_type ) == 0 ) - { - return ( 1 << WP_MELEE); + if (Q_stricmp("granboxer", NPC_type) == 0) { + return (1 << WP_MELEE); } - if ( Q_strncmp( "gran", NPC_type, 4 ) == 0 ) - { - return (( 1 << WP_THERMAL)|( 1 << WP_MELEE)); + if (Q_strncmp("gran", NPC_type, 4) == 0) { + return ((1 << WP_THERMAL) | (1 << WP_MELEE)); } - if ( Q_stricmp( "rodian", NPC_type ) == 0 ) - { - return ( 1 << WP_DISRUPTOR); + if (Q_stricmp("rodian", NPC_type) == 0) { + return (1 << WP_DISRUPTOR); } - if ( Q_stricmp( "rodian2", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("rodian2", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "interrogator",NPC_type) == 0) || ( Q_stricmp( "sentry",NPC_type) == 0) || (Q_strncmp( "protocol",NPC_type,8) == 0) ) - { + if ((Q_stricmp("interrogator", NPC_type) == 0) || (Q_stricmp("sentry", NPC_type) == 0) || (Q_strncmp("protocol", NPC_type, 8) == 0)) { return WP_NONE; } - if ( Q_strncmp( "weequay", NPC_type, 7 ) == 0 ) - { - return ( 1 << WP_BOWCASTER);//|( 1 << WP_STAFF )(FIXME: new weap?) + if (Q_strncmp("weequay", NPC_type, 7) == 0) { + return (1 << WP_BOWCASTER); //|( 1 << WP_STAFF )(FIXME: new weap?) } - if ( Q_stricmp( "impofficer", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impofficer", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "impcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impcommander", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "probe", NPC_type ) == 0 ) || ( Q_stricmp( "seeker", NPC_type ) == 0 )) - { - return ( 1 << WP_BOT_LASER); - } - if ( Q_stricmp( "remote", NPC_type ) == 0 ) - { - return ( 1 << WP_BOT_LASER ); - } - if ( Q_stricmp( "trandoshan", NPC_type ) == 0 ) - { - return (1<client->playerTeam, ent->spawnflags, ent->NPC_type ); +void NPC_SetWeapons(gentity_t *ent) { + int bestWeap = WP_NONE; + int weapons = NPC_WeaponsForTeam(ent->client->playerTeam, ent->spawnflags, ent->NPC_type); // these teams are gone now anyway, plus all team stuff should be read in from the config file -/* - switch ( ent->client->playerTeam ) - { - case TEAM_KLINGON: - case TEAM_MALON: - case TEAM_HIROGEN: - case TEAM_IMPERIAL: - ent->client->playerTeam = TEAM_SCAVENGERS; - break; - } -*/ + /* + switch ( ent->client->playerTeam ) + { + case TEAM_KLINGON: + case TEAM_MALON: + case TEAM_HIROGEN: + case TEAM_IMPERIAL: + ent->client->playerTeam = TEAM_SCAVENGERS; + break; + } + */ ent->client->ps.stats[STAT_WEAPONS] = 0; - for ( int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if ( (weapons & ( 1 << curWeap )) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << curWeap ); - RegisterItem( FindItemForWeapon( (weapon_t)(curWeap) ) ); //precache the weapon - ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100;//FIXME: max ammo + for (int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if ((weapons & (1 << curWeap))) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << curWeap); + RegisterItem(FindItemForWeapon((weapon_t)(curWeap))); // precache the weapon + ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100; // FIXME: max ammo - if ( bestWeap == WP_SABER ) - { + if (bestWeap == WP_SABER) { // still want to register other weapons -- force saber to be best weap continue; } - if ( curWeap == WP_MELEE ) - { - if ( bestWeap == WP_NONE ) - {// We'll only consider giving Melee since we haven't found anything better yet. + if (curWeap == WP_MELEE) { + if (bestWeap == WP_NONE) { // We'll only consider giving Melee since we haven't found anything better yet. bestWeap = curWeap; } - } - else if ( curWeap > bestWeap || bestWeap == WP_MELEE ) - { + } else if (curWeap > bestWeap || bestWeap == WP_MELEE) { // This will never override saber as best weap. Also will override WP_MELEE if something better comes later in the list bestWeap = curWeap; } @@ -671,7 +577,7 @@ void NPC_SetWeapons( gentity_t *ent ) ent->client->ps.weapon = bestWeap; ent->client->ps.weaponstate = WEAPON_IDLE; - ChangeWeapon( ent, bestWeap ); + ChangeWeapon(ent, bestWeap); } /* @@ -683,8 +589,7 @@ NPC_SpawnEffect ------------------------- */ -void NPC_SpawnEffect (gentity_t *ent) -{ +void NPC_SpawnEffect(gentity_t *ent) { /* gentity_t *tent; @@ -709,102 +614,94 @@ void NPC_SpawnEffect (gentity_t *ent) // // Set up any special parms for spawn effects //-------------------------------------------------------------- -void NPC_SetFX_SpawnStates( gentity_t *ent ) -{ +void NPC_SetFX_SpawnStates(gentity_t *ent) { // stasis, 8472, etc no longer exist. However if certain NPC's need customized spawn effects, use // NPC_class instead of TEAM_ -/* - // -Etherians ------- - if ( ent->client->playerTeam == TEAM_STASIS ) - { - ent->svFlags |= SVF_CUSTOM_GRAVITY; - ent->client->ps.gravity = 300; + /* + // -Etherians ------- + if ( ent->client->playerTeam == TEAM_STASIS ) + { + ent->svFlags |= SVF_CUSTOM_GRAVITY; + ent->client->ps.gravity = 300; - // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. - ent->fx_time = level.time; - ent->s.eFlags |= EF_SCALE_UP; - ent->client->ps.eFlags |= EF_SCALE_UP; - // Make it really small to start with - VectorSet( ent->->s.modelScale, 0.001,0.001,0.001 ); - } - else -*/ - { - ent->client->ps.gravity = g_gravity->value; - } -/* - // -Hunterseeker ------- - if ( !stricmp( ent->NPC_type, "hunterseeker" ) ) - { - // Set the custom banking flag - ent->s.eFlags |= EF_BANK_STRAFE; - ent->client->ps.eFlags |= EF_BANK_STRAFE; - } + // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. + ent->fx_time = level.time; + ent->s.eFlags |= EF_SCALE_UP; + ent->client->ps.eFlags |= EF_SCALE_UP; + // Make it really small to start with + VectorSet( ent->->s.modelScale, 0.001,0.001,0.001 ); + } + else + */ + { ent->client->ps.gravity = g_gravity->value; } + /* + // -Hunterseeker ------- + if ( !stricmp( ent->NPC_type, "hunterseeker" ) ) + { + // Set the custom banking flag + ent->s.eFlags |= EF_BANK_STRAFE; + ent->client->ps.eFlags |= EF_BANK_STRAFE; + } - // -8472 ------- - if ( ent->client->playerTeam == TEAM_8472 ) - { - // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. - ent->fx_time = level.time; - ent->s.eFlags |= EF_SCALE_UP; - ent->client->ps.eFlags |= EF_SCALE_UP; - // Make it really small to start with - VectorSet( ent->s.modelScale, 0.001,0.001,1 ); - } + // -8472 ------- + if ( ent->client->playerTeam == TEAM_8472 ) + { + // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. + ent->fx_time = level.time; + ent->s.eFlags |= EF_SCALE_UP; + ent->client->ps.eFlags |= EF_SCALE_UP; + // Make it really small to start with + VectorSet( ent->s.modelScale, 0.001,0.001,1 ); + } - // -Forge ----- - if ( ent->client->playerTeam == TEAM_FORGE ) - { - // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. - ent->fx_time = level.time; - ent->s.eFlags |= EF_SCALE_UP; - ent->client->ps.eFlags |= EF_SCALE_UP; - // Make it really small to start with - VectorSet( ent->s.modelScale, 0.001,0.001,1 ); - } -*/ + // -Forge ----- + if ( ent->client->playerTeam == TEAM_FORGE ) + { + // The spawn effect can happen, so it's ok to do this extra setup stuff for the effect. + ent->fx_time = level.time; + ent->s.eFlags |= EF_SCALE_UP; + ent->client->ps.eFlags |= EF_SCALE_UP; + // Make it really small to start with + VectorSet( ent->s.modelScale, 0.001,0.001,1 ); + } + */ } //-------------------------------------------------------------- -extern qboolean stop_icarus; -void NPC_Begin (gentity_t *ent) -{ - vec3_t spawn_origin, spawn_angles; - gclient_t *client; - usercmd_t ucmd; - gentity_t *spawnPoint = NULL; +extern qboolean stop_icarus; +void NPC_Begin(gentity_t *ent) { + vec3_t spawn_origin, spawn_angles; + gclient_t *client; + usercmd_t ucmd; + gentity_t *spawnPoint = NULL; - memset( &ucmd, 0, sizeof( ucmd ) ); + memset(&ucmd, 0, sizeof(ucmd)); - if ( !(ent->spawnflags & SFB_NOTSOLID) ) - {//No NPCs should telefrag - if( SpotWouldTelefrag( ent, TEAM_FREE ) )//(team_t)(ent->client->playerTeam) + if (!(ent->spawnflags & SFB_NOTSOLID)) { // No NPCs should telefrag + if (SpotWouldTelefrag(ent, TEAM_FREE)) //(team_t)(ent->client->playerTeam) { - if ( ent->wait < 0 ) - {//remove yourself - Q3_DebugPrint( WL_DEBUG, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, ent->target3 ); - //Fire off our target3 - G_UseTargets2( ent, ent, ent->target3 ); + if (ent->wait < 0) { // remove yourself + Q3_DebugPrint(WL_DEBUG, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, ent->target3); + // Fire off our target3 + G_UseTargets2(ent, ent, ent->target3); - //Kill us + // Kill us ent->e_ThinkFunc = thinkF_G_FreeEntity; ent->nextthink = level.time + 100; - } - else - { - Q3_DebugPrint( WL_DEBUG, "NPC %s could not spawn, waiting %4.2 secs to try again\n", ent->targetname, ent->wait/1000.0f ); + } else { + Q3_DebugPrint(WL_DEBUG, "NPC %s could not spawn, waiting %4.2 secs to try again\n", ent->targetname, ent->wait / 1000.0f); ent->e_ThinkFunc = thinkF_NPC_Begin; - ent->nextthink = level.time + ent->wait;//try again in half a second + ent->nextthink = level.time + ent->wait; // try again in half a second } return; } } - //Spawn effect - NPC_SpawnEffect( ent ); + // Spawn effect + NPC_SpawnEffect(ent); - VectorCopy( ent->client->ps.origin, spawn_origin); - VectorCopy( ent->s.angles, spawn_angles); + VectorCopy(ent->client->ps.origin, spawn_origin); + VectorCopy(ent->s.angles, spawn_angles); spawn_angles[YAW] = ent->NPC->desiredYaw; client = ent->client; @@ -817,79 +714,61 @@ void NPC_Begin (gentity_t *ent) client->ps.clientNum = ent->s.number; // clear entity values - if ( ent->health ) // Was health supplied in map + if (ent->health) // Was health supplied in map { ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->health; - } - else if ( ent->NPC->stats.health ) // Was health supplied in NPC.cfg? + } else if (ent->NPC->stats.health) // Was health supplied in NPC.cfg? { - - if ( ent->client->NPC_class != CLASS_REBORN - && ent->client->NPC_class != CLASS_SHADOWTROOPER + + if (ent->client->NPC_class != CLASS_REBORN && + ent->client->NPC_class != CLASS_SHADOWTROOPER //&& ent->client->NPC_class != CLASS_TAVION - //&& ent->client->NPC_class != CLASS_DESANN - && ent->client->NPC_class != CLASS_JEDI ) - {// up everyone except jedi - ent->NPC->stats.health += ent->NPC->stats.health/4 * g_spskill->integer; // 100% on easy, 125% on medium, 150% on hard + //&& ent->client->NPC_class != CLASS_DESANN + && ent->client->NPC_class != CLASS_JEDI) { // up everyone except jedi + ent->NPC->stats.health += ent->NPC->stats.health / 4 * g_spskill->integer; // 100% on easy, 125% on medium, 150% on hard } - + ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->NPC->stats.health; - } - else - { + } else { ent->max_health = client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = 100; } - if ( !Q_stricmp( "rodian", ent->NPC_type ) ) - {//sniper - //NOTE: this will get overridden by any aim settings in their spawnscripts - switch ( g_spskill->integer ) - { + if (!Q_stricmp("rodian", ent->NPC_type)) { // sniper + // NOTE: this will get overridden by any aim settings in their spawnscripts + switch (g_spskill->integer) { case 0: ent->NPC->stats.aim = 1; break; case 1: - ent->NPC->stats.aim = Q_irand( 2, 3 ); + ent->NPC->stats.aim = Q_irand(2, 3); break; case 2: - ent->NPC->stats.aim = Q_irand( 3, 4 ); + ent->NPC->stats.aim = Q_irand(3, 4); break; } - } - else if ( ent->client->NPC_class == CLASS_STORMTROOPER - || ent->client->NPC_class == CLASS_SWAMPTROOPER - || ent->client->NPC_class == CLASS_IMPWORKER - || !Q_stricmp( "rodian2", ent->NPC_type ) ) - {//tweak yawspeed for these NPCs based on difficulty - switch ( g_spskill->integer ) - { + } else if (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_IMPWORKER || + !Q_stricmp("rodian2", ent->NPC_type)) { // tweak yawspeed for these NPCs based on difficulty + switch (g_spskill->integer) { case 0: ent->NPC->stats.yawSpeed *= 0.75f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 3, 6 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(3, 6); } break; case 1: - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 2, 4 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(2, 4); } break; case 2: ent->NPC->stats.yawSpeed *= 1.5f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 0, 2 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(0, 2); } break; } - } - else if ( ent->client->NPC_class == CLASS_REBORN - || ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - switch ( g_spskill->integer ) - { + } else if (ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_SHADOWTROOPER) { + switch (g_spskill->integer) { case 1: ent->NPC->stats.yawSpeed *= 1.25f; break; @@ -899,54 +778,46 @@ void NPC_Begin (gentity_t *ent) } } - ent->s.groundEntityNum = ENTITYNUM_NONE; ent->mass = 10; ent->takedamage = qtrue; ent->inuse = qtrue; SetInUse(ent); ent->classname = "NPC"; -// if ( ent->client->race == RACE_HOLOGRAM ) -// {//can shoot through holograms, but not walk through them -// ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces -// ent->clipmask = MASK_NPCSOLID; -// } else - if(!(ent->spawnflags & SFB_NOTSOLID)) - { + // if ( ent->client->race == RACE_HOLOGRAM ) + // {//can shoot through holograms, but not walk through them + // ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces + // ent->clipmask = MASK_NPCSOLID; + // } else + if (!(ent->spawnflags & SFB_NOTSOLID)) { ent->contents = CONTENTS_BODY; ent->clipmask = MASK_NPCSOLID; - } - else - { + } else { ent->contents = 0; - ent->clipmask = MASK_NPCSOLID&~CONTENTS_BODY; + ent->clipmask = MASK_NPCSOLID & ~CONTENTS_BODY; } - if(!ent->NPC->stats.moveType)//Static? + if (!ent->NPC->stats.moveType) // Static? { ent->NPC->stats.moveType = MT_RUNJUMP; } ent->e_DieFunc = dieF_player_die; ent->waterlevel = 0; ent->watertype = 0; - - //visible to player and NPCs - if ( ent->client->NPC_class != CLASS_R2D2 && - ent->client->NPC_class != CLASS_R5D2 && - ent->client->NPC_class != CLASS_MOUSE && - ent->client->NPC_class != CLASS_GONK && - ent->client->NPC_class != CLASS_PROTOCOL ) - { + + // visible to player and NPCs + if (ent->client->NPC_class != CLASS_R2D2 && ent->client->NPC_class != CLASS_R5D2 && ent->client->NPC_class != CLASS_MOUSE && + ent->client->NPC_class != CLASS_GONK && ent->client->NPC_class != CLASS_PROTOCOL) { ent->flags &= ~FL_NOTARGET; } ent->s.eFlags &= ~EF_NODRAW; - NPC_SetFX_SpawnStates( ent ); - + NPC_SetFX_SpawnStates(ent); + client->ps.friction = 6; NPC_SetWeapons(ent); - VectorCopy( spawn_origin, client->ps.origin ); + VectorCopy(spawn_origin, client->ps.origin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; @@ -954,18 +825,17 @@ void NPC_Begin (gentity_t *ent) // clear entity state values ent->s.eType = ET_PLAYER; ent->s.eFlags |= EF_NPC; -// ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models + // ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models - VectorCopy (spawn_origin, ent->s.origin); -// ent->s.origin[2] += 1; // make sure off ground + VectorCopy(spawn_origin, ent->s.origin); + // ent->s.origin[2] += 1; // make sure off ground - SetClientViewAngle( ent, spawn_angles ); + SetClientViewAngle(ent, spawn_angles); client->renderInfo.lookTarget = ENTITYNUM_NONE; - if(!(ent->spawnflags & 64)) - { - G_KillBox( ent ); - gi.linkentity (ent); + if (!(ent->spawnflags & 64)) { + G_KillBox(ent); + gi.linkentity(ent); } // don't allow full run speed for a bit @@ -977,108 +847,95 @@ void NPC_Begin (gentity_t *ent) client->latched_buttons = 0; // set default animations - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); - if( spawnPoint ) - { + if (spawnPoint) { // fire the targets of the spawn point - G_UseTargets( spawnPoint, ent ); + G_UseTargets(spawnPoint, ent); } - //ICARUS include - ICARUS_InitEnt( ent ); + // ICARUS include + ICARUS_InitEnt(ent); -//==NPC initialization - SetNPCGlobals( ent ); + //==NPC initialization + SetNPCGlobals(ent); ent->enemy = NULL; NPCInfo->timeOfDeath = 0; NPCInfo->shotTime = 0; NPC_ClearGoal(); - NPC_ChangeWeapon( ent->client->ps.weapon ); + NPC_ChangeWeapon(ent->client->ps.weapon); -//==Final NPC initialization - ent->e_PainFunc = NPC_PainFunc( ent ); //painF_NPC_Pain; - ent->e_TouchFunc = NPC_TouchFunc( ent ); //touchF_NPC_Touch; -// ent->NPC->side = 1; + //==Final NPC initialization + ent->e_PainFunc = NPC_PainFunc(ent); // painF_NPC_Pain; + ent->e_TouchFunc = NPC_TouchFunc(ent); // touchF_NPC_Touch; + // ent->NPC->side = 1; ent->client->ps.ping = ent->NPC->stats.reactions * 50; - //MCG - Begin: NPC hacks - //FIXME: Set the team correctly + // MCG - Begin: NPC hacks + // FIXME: Set the team correctly ent->client->ps.persistant[PERS_TEAM] = ent->client->playerTeam; ent->client->ps.eFlags |= EF_NPC; - ent->e_UseFunc = useF_NPC_Use; + ent->e_UseFunc = useF_NPC_Use; ent->e_ThinkFunc = thinkF_NPC_Think; ent->nextthink = level.time + FRAMETIME + Q_irand(0, 100); - NPC_SetMiscDefaultData( ent ); - if ( ent->health <= 0 ) - { - //ORIGINAL ID: health will count down towards max_health + NPC_SetMiscDefaultData(ent); + if (ent->health <= 0) { + // ORIGINAL ID: health will count down towards max_health ent->health = client->ps.stats[STAT_HEALTH] = ent->max_health; - } - else - { + } else { client->ps.stats[STAT_HEALTH] = ent->max_health = ent->health; } - ChangeWeapon( ent, ent->client->ps.weapon );//yes, again... sigh + ChangeWeapon(ent, ent->client->ps.weapon); // yes, again... sigh - if ( !(ent->spawnflags & SFB_STARTINSOLID) ) - {//Not okay to start in solid - G_CheckInSolid( ent, qtrue ); + if (!(ent->spawnflags & SFB_STARTINSOLID)) { // Not okay to start in solid + G_CheckInSolid(ent, qtrue); } - VectorClear( ent->NPC->lastClearOrigin ); + VectorClear(ent->NPC->lastClearOrigin); - //Run a script if you have one assigned to you - if ( G_ActivateBehavior( ent, BSET_SPAWN ) ) - { - if( ent->taskManager && !stop_icarus ) - { + // Run a script if you have one assigned to you + if (G_ActivateBehavior(ent, BSET_SPAWN)) { + if (ent->taskManager && !stop_icarus) { ent->taskManager->Update(); } } - VectorCopy( ent->currentOrigin, ent->client->renderInfo.eyePoint ); + VectorCopy(ent->currentOrigin, ent->client->renderInfo.eyePoint); // run a client frame to drop exactly to the floor, // initialize animations and other things - memset( &ucmd, 0, sizeof( ucmd ) ); - VectorCopyM( client->pers.cmd_angles, ucmd.angles ); - + memset(&ucmd, 0, sizeof(ucmd)); + VectorCopyM(client->pers.cmd_angles, ucmd.angles); + ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON ) - { - G_MatchPlayerWeapon( ent ); + if (ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) { + G_MatchPlayerWeapon(ent); } - ClientThink( ent->s.number, &ucmd ); + ClientThink(ent->s.number, &ucmd); - gi.linkentity( ent ); + gi.linkentity(ent); - if ( ent->client->playerTeam == TEAM_ENEMY ) - {//valid enemy spawned - if ( !(ent->spawnflags&SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC ) - {//not a cinematic enemy - if ( g_entities[0].client ) - { + if (ent->client->playerTeam == TEAM_ENEMY) { // valid enemy spawned + if (!(ent->spawnflags & SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC) { // not a cinematic enemy + if (g_entities[0].client) { g_entities[0].client->sess.missionStats.enemiesSpawned++; } } } } -gNPC_t *New_NPC_t() -{ - gNPC_t *ptr = (gNPC_t *)G_Alloc (sizeof(gNPC_t)); +gNPC_t *New_NPC_t() { + gNPC_t *ptr = (gNPC_t *)G_Alloc(sizeof(gNPC_t)); - if (ptr) - { + if (ptr) { // clear it... // - memset(ptr, 0, sizeof( *ptr ) ); + memset(ptr, 0, sizeof(*ptr)); } return ptr; @@ -1089,14 +946,14 @@ gNPC_t *New_NPC_t() NPC_StasisSpawn_Go ------------------------- */ -/* +/* qboolean NPC_StasisSpawn_Go( gentity_t *ent ) { //Setup an owner pointer if we need it if VALIDSTRING( ent->ownername ) { ent->owner = G_Find( NULL, FOFS( targetname ), ent->ownername ); - + if ( ( ent->owner ) && ( ent->owner->health <= 0 ) ) {//our spawner thing is broken if ( ent->target2 && ent->target2[0] ) @@ -1132,14 +989,12 @@ qboolean NPC_StasisSpawn_Go( gentity_t *ent ) return qtrue; } */ -void NPC_DefaultScriptFlags( gentity_t *ent ) -{ - if ( !ent || !ent->NPC ) - { +void NPC_DefaultScriptFlags(gentity_t *ent) { + if (!ent || !ent->NPC) { return; } - //Set up default script flags - ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES|SCF_LOOK_FOR_ENEMIES); + // Set up default script flags + ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES | SCF_LOOK_FOR_ENEMIES); } /* ------------------------- @@ -1147,72 +1002,64 @@ NPC_Spawn_Go ------------------------- */ -void NPC_Spawn_Go( gentity_t *ent ) -{ - gentity_t *newent; - int index; - vec3_t saveOrg; +void NPC_Spawn_Go(gentity_t *ent) { + gentity_t *newent; + int index; + vec3_t saveOrg; -/* //Do extra code for stasis spawners - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ - //Test for drop to floor - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - trace_t tr; - vec3_t bottom; + /* //Do extra code for stasis spawners + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ + // Test for drop to floor + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + trace_t tr; + vec3_t bottom; - VectorCopy( ent->currentOrigin, saveOrg ); - VectorCopy( ent->currentOrigin, bottom ); + VectorCopy(ent->currentOrigin, saveOrg); + VectorCopy(ent->currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, G2_NOCOLLIDE, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, G2_NOCOLLIDE, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); } } - //Check the spawner's count - if( ent->count != -1 ) - { + // Check the spawner's count + if (ent->count != -1) { ent->count--; - - if( ent->count <= 0 ) - { - ent->e_UseFunc = useF_NULL;//never again - //FIXME: why not remove me...? Because of all the string pointers? Just do G_NewStrings? + + if (ent->count <= 0) { + ent->e_UseFunc = useF_NULL; // never again + // FIXME: why not remove me...? Because of all the string pointers? Just do G_NewStrings? } } newent = G_Spawn(); - if ( newent == NULL ) - { - gi.Printf ( S_COLOR_RED"ERROR: NPC G_Spawn failed\n" ); - + if (newent == NULL) { + gi.Printf(S_COLOR_RED "ERROR: NPC G_Spawn failed\n"); + goto finish; return; } - + newent->svFlags |= SVF_NPC; newent->fullName = ent->fullName; - newent->NPC = New_NPC_t(); - if ( newent->NPC == NULL ) - { - gi.Printf ( S_COLOR_RED"ERROR: NPC G_Alloc NPC failed\n" ); + newent->NPC = New_NPC_t(); + if (newent->NPC == NULL) { + gi.Printf(S_COLOR_RED "ERROR: NPC G_Alloc NPC failed\n"); goto finish; return; - } + } newent->NPC->tempGoal = G_Spawn(); - - if ( newent->NPC->tempGoal == NULL ) - { + + if (newent->NPC->tempGoal == NULL) { newent->NPC = NULL; goto finish; return; @@ -1222,68 +1069,53 @@ void NPC_Spawn_Go( gentity_t *ent ) newent->NPC->tempGoal->owner = newent; newent->NPC->tempGoal->svFlags |= SVF_NOCLIENT; - newent->client = (gclient_t *)G_Alloc (sizeof(gclient_t)); - - if ( newent->client == NULL ) - { - gi.Printf ( S_COLOR_RED"ERROR: NPC G_Alloc client failed\n" ); + newent->client = (gclient_t *)G_Alloc(sizeof(gclient_t)); + + if (newent->client == NULL) { + gi.Printf(S_COLOR_RED "ERROR: NPC G_Alloc client failed\n"); goto finish; return; } - - memset ( newent->client, 0, sizeof(*newent->client) ); -//==NPC_Connect( newent, net_name );=================================== + memset(newent->client, 0, sizeof(*newent->client)); - if ( ent->NPC_type == NULL ) - { + //==NPC_Connect( newent, net_name );=================================== + + if (ent->NPC_type == NULL) { ent->NPC_type = "random"; - } - else - { - ent->NPC_type = Q_strlwr( G_NewString( ent->NPC_type ) ); + } else { + ent->NPC_type = Q_strlwr(G_NewString(ent->NPC_type)); } - if ( ent->svFlags & SVF_NO_BASIC_SOUNDS ) - { + if (ent->svFlags & SVF_NO_BASIC_SOUNDS) { newent->svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( ent->svFlags & SVF_NO_COMBAT_SOUNDS ) - { + if (ent->svFlags & SVF_NO_COMBAT_SOUNDS) { newent->svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( ent->svFlags & SVF_NO_EXTRA_SOUNDS ) - { + if (ent->svFlags & SVF_NO_EXTRA_SOUNDS) { newent->svFlags |= SVF_NO_EXTRA_SOUNDS; } - - if ( ent->message ) - {//has a key - newent->message = ent->message;//transfer the key name - newent->flags |= FL_NO_KNOCKBACK;//don't fall off ledges + + if (ent->message) { // has a key + newent->message = ent->message; // transfer the key name + newent->flags |= FL_NO_KNOCKBACK; // don't fall off ledges } - if ( !NPC_ParseParms( ent->NPC_type, newent ) ) - { - gi.Printf ( S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type ); - G_FreeEntity( newent ); + if (!NPC_ParseParms(ent->NPC_type, newent)) { + gi.Printf(S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type); + G_FreeEntity(newent); goto finish; return; } - if ( ent->NPC_type ) - { - if ( !Q_stricmp( ent->NPC_type, "kyle" ) ) - { + if (ent->NPC_type) { + if (!Q_stricmp(ent->NPC_type, "kyle")) { newent->NPC->aiFlags |= NPCAI_MATCHPLAYERWEAPON; - } - else if ( !Q_stricmp( ent->NPC_type, "test" ) ) - { - int n; - for ( n = 0; n < 1 ; n++) - { - if ( !(g_entities[n].svFlags & SVF_NPC) && g_entities[n].client) - { + } else if (!Q_stricmp(ent->NPC_type, "test")) { + int n; + for (n = 0; n < 1; n++) { + if (!(g_entities[n].svFlags & SVF_NPC) && g_entities[n].client) { VectorCopy(g_entities[n].s.origin, newent->s.origin); newent->client->playerTeam = g_entities[n].client->playerTeam; break; @@ -1291,24 +1123,22 @@ void NPC_Spawn_Go( gentity_t *ent ) } newent->NPC->defaultBehavior = newent->NPC->behaviorState = BS_WAIT; newent->classname = "NPC"; - // newent->svFlags |= SVF_NOPUSH; + // newent->svFlags |= SVF_NOPUSH; } } -//===================================================================== - //set the info we want + //===================================================================== + // set the info we want newent->health = ent->health; newent->script_targetname = ent->NPC_targetname; newent->targetname = ent->NPC_targetname; - newent->target = ent->NPC_target;//death - newent->target2 = ent->target2;//knocked out death - newent->target3 = ent->target3;//??? - newent->target4 = ent->target4;//ffire death + newent->target = ent->NPC_target; // death + newent->target2 = ent->target2; // knocked out death + newent->target3 = ent->target3; //??? + newent->target4 = ent->target4; // ffire death newent->wait = ent->wait; - - for( index = BSET_FIRST; index < NUM_BSETS; index++) - { - if ( ent->behaviorSet[index] ) - { + + for (index = BSET_FIRST; index < NUM_BSETS; index++) { + if (ent->behaviorSet[index]) { newent->behaviorSet[index] = ent->behaviorSet[index]; } } @@ -1316,88 +1146,79 @@ void NPC_Spawn_Go( gentity_t *ent ) newent->classname = "NPC"; newent->NPC_type = ent->NPC_type; gi.unlinkentity(newent); - + VectorCopy(ent->s.origin, newent->s.origin); VectorCopy(ent->s.origin, newent->client->ps.origin); VectorCopy(ent->s.origin, newent->currentOrigin); - G_SetOrigin(newent, ent->s.origin);//just to be sure! + G_SetOrigin(newent, ent->s.origin); // just to be sure! VectorCopy(ent->s.angles, newent->s.angles); VectorCopy(ent->s.angles, newent->currentAngles); VectorCopy(ent->s.angles, newent->client->ps.viewangles); - newent->NPC->desiredYaw =ent->s.angles[YAW]; - + newent->NPC->desiredYaw = ent->s.angles[YAW]; + gi.linkentity(newent); newent->spawnflags = ent->spawnflags; - if(ent->paintarget) - { //safe to point at owner's string since memory is never freed during game + if (ent->paintarget) { // safe to point at owner's string since memory is never freed during game newent->paintarget = ent->paintarget; } - if(ent->opentarget) - { + if (ent->opentarget) { newent->opentarget = ent->opentarget; } -//==New stuff===================================================================== - newent->s.eType = ET_PLAYER; - - //FIXME: Call CopyParms - if ( ent->parms ) - { - for ( int parmNum = 0; parmNum < MAX_PARMS; parmNum++ ) - { - if ( ent->parms->parm[parmNum] && ent->parms->parm[parmNum][0] ) - { - Q3_SetParm( newent->s.number, parmNum, ent->parms->parm[parmNum] ); + //==New stuff===================================================================== + newent->s.eType = ET_PLAYER; + + // FIXME: Call CopyParms + if (ent->parms) { + for (int parmNum = 0; parmNum < MAX_PARMS; parmNum++) { + if (ent->parms->parm[parmNum] && ent->parms->parm[parmNum][0]) { + Q3_SetParm(newent->s.number, parmNum, ent->parms->parm[parmNum]); } } } - //FIXME: copy cameraGroup, store mine in message or other string field + // FIXME: copy cameraGroup, store mine in message or other string field - //set origin + // set origin newent->s.pos.trType = TR_INTERPOLATE; newent->s.pos.trTime = level.time; - VectorCopy( newent->currentOrigin, newent->s.pos.trBase ); - VectorClear( newent->s.pos.trDelta ); + VectorCopy(newent->currentOrigin, newent->s.pos.trBase); + VectorClear(newent->s.pos.trDelta); newent->s.pos.trDuration = 0; - //set angles + // set angles newent->s.apos.trType = TR_INTERPOLATE; newent->s.apos.trTime = level.time; - VectorCopy( newent->currentOrigin, newent->s.apos.trBase ); - VectorClear( newent->s.apos.trDelta ); + VectorCopy(newent->currentOrigin, newent->s.apos.trBase); + VectorClear(newent->s.apos.trDelta); newent->s.apos.trDuration = 0; - + newent->NPC->combatPoint = -1; - newent->flags |= FL_NOTARGET;//So he's ignored until he's fully spawned - newent->s.eFlags |= EF_NODRAW;//So he's ignored until he's fully spawned + newent->flags |= FL_NOTARGET; // So he's ignored until he's fully spawned + newent->s.eFlags |= EF_NODRAW; // So he's ignored until he's fully spawned newent->e_ThinkFunc = thinkF_NPC_Begin; newent->nextthink = level.time + FRAMETIME; - NPC_DefaultScriptFlags( newent ); + NPC_DefaultScriptFlags(newent); - gi.linkentity (newent); + gi.linkentity(newent); - if(ent->e_UseFunc == useF_NULL) - { - if( ent->target ) - {//use any target we're pointed at - G_UseTargets ( ent, ent ); + if (ent->e_UseFunc == useF_NULL) { + if (ent->target) { // use any target we're pointed at + G_UseTargets(ent, ent); } - if(ent->closetarget) - {//last guy should fire this target when he dies + if (ent->closetarget) { // last guy should fire this target when he dies newent->target = ent->closetarget; } ent->targetname = NULL; - //why not remove me...? Because of all the string pointers? Just do G_NewStrings? - G_FreeEntity( ent );//bye! + // why not remove me...? Because of all the string pointers? Just do G_NewStrings? + G_FreeEntity(ent); // bye! } finish: - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } } @@ -1418,9 +1239,9 @@ void NPC_StasisSpawnEffect( gentity_t *ent ) AngleVectors( ent->s.angles, forward, NULL, NULL ); VectorMA( ent->currentOrigin, 24, forward, end ); VectorMA( ent->currentOrigin, -20, forward, start ); - + start[2] += 64; - + taper = qtrue; } else @@ -1441,26 +1262,25 @@ NPC_ShySpawn ------------------------- */ -#define SHY_THINK_TIME 1000 -#define SHY_SPAWN_DISTANCE 128 -#define SHY_SPAWN_DISTANCE_SQR ( SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE ) +#define SHY_THINK_TIME 1000 +#define SHY_SPAWN_DISTANCE 128 +#define SHY_SPAWN_DISTANCE_SQR (SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE) -void NPC_ShySpawn( gentity_t *ent ) -{ +void NPC_ShySpawn(gentity_t *ent) { ent->nextthink = level.time + SHY_THINK_TIME; ent->e_ThinkFunc = thinkF_NPC_ShySpawn; - if ( DistanceSquared( g_entities[0].currentOrigin, ent->currentOrigin ) <= SHY_SPAWN_DISTANCE_SQR ) + if (DistanceSquared(g_entities[0].currentOrigin, ent->currentOrigin) <= SHY_SPAWN_DISTANCE_SQR) return; - if ( (InFOV( ent, &g_entities[0], 80, 64 )) ) // FIXME: hardcoded fov - if ( (NPC_ClearLOS( &g_entities[0], ent->currentOrigin )) ) + if ((InFOV(ent, &g_entities[0], 80, 64))) // FIXME: hardcoded fov + if ((NPC_ClearLOS(&g_entities[0], ent->currentOrigin))) return; ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = 0; - NPC_Spawn_Go( ent ); + NPC_Spawn_Go(ent); } /* @@ -1469,31 +1289,27 @@ NPC_Spawn ------------------------- */ -void NPC_Spawn ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - //delay before spawning NPC - if( ent->delay ) - { -/* //Stasis does an extra step - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ - if ( ent->spawnflags & 2048 ) // SHY +void NPC_Spawn(gentity_t *ent, gentity_t *other, gentity_t *activator) { + // delay before spawning NPC + if (ent->delay) { + /* //Stasis does an extra step + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ + if (ent->spawnflags & 2048) // SHY ent->e_ThinkFunc = thinkF_NPC_ShySpawn; else ent->e_ThinkFunc = thinkF_NPC_Spawn_Go; ent->nextthink = level.time + ent->delay; - } - else - { - if ( ent->spawnflags & 2048 ) // SHY - NPC_ShySpawn( ent ); + } else { + if (ent->spawnflags & 2048) // SHY + NPC_ShySpawn(ent); else - NPC_Spawn_Go( ent ); + NPC_Spawn_Go(ent); } } @@ -1531,7 +1347,7 @@ fleescript - default script to run when hit and below 50% health (none by defaul deathscript - default script to run when killed (none by default) These strings can be used to activate behaviors instead of scripts - these are checked first and so no scripts should be names with these names: - default - 0: whatever + default - 0: whatever idle - 1: Stand around, do abolutely nothing roam - 2: Roam around, collect stuff walk - 3: Crouch-Walk toward their goals @@ -1557,90 +1373,74 @@ first and so no scripts should be names with these names: delay - after spawned or triggered, how many seconds to wait to spawn the NPC */ -//void NPC_PrecacheModels ( char *NPCName ); -extern qboolean spawning; // the G_Spawn*() functions are valid (only turned on during one function) -void SP_NPC_spawner( gentity_t *self) -{ - extern void NPC_PrecacheAnimationCFG( const char *NPC_type ); +// void NPC_PrecacheModels ( char *NPCName ); +extern qboolean spawning; // the G_Spawn*() functions are valid (only turned on during one function) +void SP_NPC_spawner(gentity_t *self) { + extern void NPC_PrecacheAnimationCFG(const char *NPC_type); - if ( !self->fullName || !self->fullName[0] ) - { - //FIXME: make an index into an external string table for localization + if (!self->fullName || !self->fullName[0]) { + // FIXME: make an index into an external string table for localization self->fullName = "Humanoid Lifeform"; } - //register/precache the models needed for this NPC, not anymore - //self->classname = "NPC_spawner"; + // register/precache the models needed for this NPC, not anymore + // self->classname = "NPC_spawner"; - if(!self->count) - { + if (!self->count) { self->count = 1; } - {//Stop loading of certain extra sounds - static int garbage; + { // Stop loading of certain extra sounds + static int garbage; - if ( G_SpawnInt( "noBasicSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noBasicSounds", "0", &garbage)) { self->svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( G_SpawnInt( "noCombatSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noCombatSounds", "0", &garbage)) { self->svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( G_SpawnInt( "noExtraSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noExtraSounds", "0", &garbage)) { self->svFlags |= SVF_NO_EXTRA_SOUNDS; } } - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; - } - else - { - self->wait *= 1000;//1 = 1 msec, 1000 = 1 sec + } else { + self->wait *= 1000; // 1 = 1 msec, 1000 = 1 sec } - self->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + self->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - if ( self->delay > 0 ) - { + if (self->delay > 0) { self->svFlags |= SVF_NPC_PRECACHE; } - //We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid - NPC_PrecacheAnimationCFG( self->NPC_type ); + // We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid + NPC_PrecacheAnimationCFG(self->NPC_type); - if ( self->targetname ) - {//Wait for triggering + if (self->targetname) { // Wait for triggering self->e_UseFunc = useF_NPC_Spawn; - self->svFlags |= SVF_NPC_PRECACHE;//FIXME: precache my weapons somehow? + self->svFlags |= SVF_NPC_PRECACHE; // FIXME: precache my weapons somehow? - //NPC_PrecacheModels( self->NPC_type ); - } - else - { - //NOTE: auto-spawners never check for shy spawning - if ( spawning ) - {//in entity spawn stage - map starting up + // NPC_PrecacheModels( self->NPC_type ); + } else { + // NOTE: auto-spawners never check for shy spawning + if (spawning) { // in entity spawn stage - map starting up self->e_ThinkFunc = thinkF_NPC_Spawn_Go; self->nextthink = level.time + START_TIME_REMOVE_ENTS + 50; - } - else - {//else spawn right now - NPC_Spawn( self, self, self ); + } else { // else spawn right now + NPC_Spawn(self, self, self); } } - //FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup - //Or just don't include NPC_spawners in cameraGroupings + // FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup + // Or just don't include NPC_spawners in cameraGroupings } -//Characters +// Characters -//STAR WARS NPCs============================================================================ +// STAR WARS NPCs============================================================================ /*QUAKED NPC_***** (1 0 0) (-16 -16 -24) (16 16 32) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -1682,7 +1482,7 @@ deathscript - default script to run when killed (none by default) These strings can be used to activate behaviors instead of scripts - these are checked first and so no scripts should be names with these names: - default - 0: whatever + default - 0: whatever idle - 1: Stand around, do abolutely nothing roam - 2: Roam around, collect stuff walk - 3: Crouch-Walk toward their goals @@ -1710,7 +1510,7 @@ delay - after spawned or triggered, how many seconds to wait to spawn the NPC */ //============================================================================================= -//CHARACTERS +// CHARACTERS //============================================================================================= /*QUAKED NPC_Kyle (1 0 0) (-16 -16 -24) (16 16 32) x RIFLEMAN PHASER TRICORDER DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1719,13 +1519,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Kyle( gentity_t *self) -{ +void SP_NPC_Kyle(gentity_t *self) { self->NPC_type = "Kyle"; - WP_SetSaberModel( NULL, CLASS_KYLE ); + WP_SetSaberModel(NULL, CLASS_KYLE); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Lando(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1735,11 +1534,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Lando( gentity_t *self) -{ +void SP_NPC_Lando(gentity_t *self) { self->NPC_type = "Lando"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Jan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1749,11 +1547,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Jan( gentity_t *self) -{ +void SP_NPC_Jan(gentity_t *self) { self->NPC_type = "Jan"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Luke(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1763,13 +1560,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Luke( gentity_t *self) -{ +void SP_NPC_Luke(gentity_t *self) { self->NPC_type = "Luke"; - WP_SetSaberModel( NULL, CLASS_LUKE ); + WP_SetSaberModel(NULL, CLASS_LUKE); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MonMothma(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1779,11 +1575,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MonMothma( gentity_t *self) -{ +void SP_NPC_MonMothma(gentity_t *self) { self->NPC_type = "MonMothma"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tavion (1 0 0) (-16 -16 -24) (16 16 32) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1793,13 +1588,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tavion( gentity_t *self) -{ +void SP_NPC_Tavion(gentity_t *self) { self->NPC_type = "Tavion"; - WP_SetSaberModel( NULL, CLASS_TAVION ); + WP_SetSaberModel(NULL, CLASS_TAVION); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reelo(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1809,11 +1603,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reelo( gentity_t *self) -{ +void SP_NPC_Reelo(gentity_t *self) { self->NPC_type = "Reelo"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Galak(1 0 0) (-16 -16 -24) (16 16 40) MECH x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1825,19 +1618,15 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Galak( gentity_t *self) -{ - if ( self->spawnflags & 1 ) - { +void SP_NPC_Galak(gentity_t *self) { + if (self->spawnflags & 1) { self->NPC_type = "Galak_Mech"; NPC_GalakMech_Precache(); - } - else - { + } else { self->NPC_type = "Galak"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Desann(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1847,13 +1636,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Desann( gentity_t *self) -{ +void SP_NPC_Desann(gentity_t *self) { self->NPC_type = "Desann"; - WP_SetSaberModel( NULL, CLASS_DESANN ); + WP_SetSaberModel(NULL, CLASS_DESANN); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Bartender(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1863,11 +1651,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Bartender( gentity_t *self) -{ +void SP_NPC_Bartender(gentity_t *self) { self->NPC_type = "Bartender"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MorganKatarn(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1877,15 +1664,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MorganKatarn( gentity_t *self) -{ +void SP_NPC_MorganKatarn(gentity_t *self) { self->NPC_type = "MorganKatarn"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ALLIES +// ALLIES //============================================================================================= /*QUAKED NPC_Jedi(1 0 0) (-16 -16 -24) (16 16 40) TRAINER x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1898,36 +1684,29 @@ SHY - Spawner is shy Ally Jedi NPC Buddy - tags along with player */ -void SP_NPC_Jedi( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Jedi(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "jeditrainer"; - } - else - { + } else { /* if ( !Q_irand( 0, 2 ) ) { self->NPC_type = "JediF"; } - else - */if ( Q_irand( 0, 1 ) ) - { - self->NPC_type = "Jedi"; - } else - { + */ + if (Q_irand(0, 1)) { + self->NPC_type = "Jedi"; + } else { self->NPC_type = "Jedi2"; } } } - WP_SetSaberModel( NULL, CLASS_JEDI ); + WP_SetSaberModel(NULL, CLASS_JEDI); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Prisoner(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1937,21 +1716,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Prisoner( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Prisoner(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Prisoner"; - } - else - { + } else { self->NPC_type = "Prisoner2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rebel(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1961,25 +1735,20 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rebel( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Rebel(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Rebel"; - } - else - { + } else { self->NPC_type = "Rebel2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ENEMIES +// ENEMIES //============================================================================================= /*QUAKED NPC_Stormtrooper(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER ALTOFFICER ROCKET DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -1996,42 +1765,28 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Stormtrooper( gentity_t *self) -{ - if ( self->spawnflags & 8 ) - {//rocketer +void SP_NPC_Stormtrooper(gentity_t *self) { + if (self->spawnflags & 8) { // rocketer self->NPC_type = "rockettrooper"; - } - else if ( self->spawnflags & 4 ) - {//alt-officer + } else if (self->spawnflags & 4) { // alt-officer self->NPC_type = "stofficeralt"; - } - else if ( self->spawnflags & 2 ) - {//commander + } else if (self->spawnflags & 2) { // commander self->NPC_type = "stcommander"; - } - else if ( self->spawnflags & 1 ) - {//officer + } else if (self->spawnflags & 1) { // officer self->NPC_type = "stofficer"; - } - else - {//regular trooper - if ( Q_irand( 0, 1 ) ) - { + } else { // regular trooper + if (Q_irand(0, 1)) { self->NPC_type = "StormTrooper"; - } - else - { + } else { self->NPC_type = "StormTrooper2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -void SP_NPC_StormtrooperOfficer( gentity_t *self) -{ +void SP_NPC_StormtrooperOfficer(gentity_t *self) { self->spawnflags |= 1; - SP_NPC_Stormtrooper( self ); + SP_NPC_Stormtrooper(self); } /*QUAKED NPC_Tie_Pilot(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY 30 health, blaster @@ -2042,11 +1797,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tie_Pilot( gentity_t *self) -{ +void SP_NPC_Tie_Pilot(gentity_t *self) { self->NPC_type = "stormpilot"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Ugnaught(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2056,27 +1810,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Ugnaught( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Ugnaught(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Ugnaught"; - } - else - { + } else { self->NPC_type = "Ugnaught2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Gran(1 0 0) (-16 -16 -24) (16 16 40) SHOOTER BOXER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY Uses grenade -SHOOTER - uses blaster instead of +SHOOTER - uses blaster instead of BOXER - uses fists only DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2084,32 +1833,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Gran( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Gran(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "granshooter"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "granboxer"; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { self->NPC_type = "gran"; - } - else - { + } else { self->NPC_type = "gran2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rodian(1 0 0) (-16 -16 -24) (16 16 40) BLASTER NO_HIDE x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2121,21 +1860,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rodian( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags&1 ) - { +void SP_NPC_Rodian(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rodian2"; - } - else - { + } else { self->NPC_type = "rodian"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Weequay(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2145,12 +1879,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Weequay( gentity_t *self) -{ - if ( !self->NPC_type ) - { - switch ( Q_irand( 0, 3 ) ) - { +void SP_NPC_Weequay(gentity_t *self) { + if (!self->NPC_type) { + switch (Q_irand(0, 3)) { case 0: self->NPC_type = "Weequay"; break; @@ -2166,7 +1897,7 @@ void SP_NPC_Weequay( gentity_t *self) } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Trandoshan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2176,14 +1907,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Trandoshan( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Trandoshan(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "Trandoshan"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_SwampTrooper(1 0 0) (-16 -16 -24) (16 16 40) REPEATER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2194,21 +1923,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_SwampTrooper( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_SwampTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "SwampTrooper2"; - } - else - { + } else { self->NPC_type = "SwampTrooper"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Imperial(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2218,7 +1942,9 @@ Greyshirt grunt, uses blaster pistol, 20 health. OFFICER - Brownshirt Officer, uses blaster rifle, 40 health COMMANDER - Blackshirt Commander, uses rapid-fire blaster rifle, 80 healt -"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. +"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of +the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" +spawnflag. DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2226,37 +1952,26 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Imperial( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Imperial(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "ImpOfficer"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "ImpCommander"; - } - else - { + } else { self->NPC_type = "Imperial"; } } - if ( self->message ) - {//may drop a key, precache the key model and pickup sound - G_SoundIndex( "sound/weapons/key_pkup.wav" ); - if ( !Q_stricmp( "goodie", self->message ) ) - { - RegisterItem( FindItemForInventory( INV_GOODIE_KEY ) ); - } - else - { - RegisterItem( FindItemForInventory( INV_SECURITY_KEY ) ); + if (self->message) { // may drop a key, precache the key model and pickup sound + G_SoundIndex("sound/weapons/key_pkup.wav"); + if (!Q_stricmp("goodie", self->message)) { + RegisterItem(FindItemForInventory(INV_GOODIE_KEY)); + } else { + RegisterItem(FindItemForInventory(INV_SECURITY_KEY)); } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_ImpWorker(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2266,25 +1981,18 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_ImpWorker( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( !Q_irand( 0, 2 ) ) - { +void SP_NPC_ImpWorker(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 2)) { self->NPC_type = "ImpWorker"; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { self->NPC_type = "ImpWorker2"; - } - else - { + } else { self->NPC_type = "ImpWorker3"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_BespinCop(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2294,21 +2002,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_BespinCop( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_BespinCop(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "BespinCop"; - } - else - { + } else { self->NPC_type = "BespinCop2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reborn(1 0 0) (-16 -16 -24) (16 16 40) FORCE FENCER ACROBAT BOSS CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2328,34 +2031,23 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reborn( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Reborn(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rebornforceuser"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "rebornfencer"; - } - else if ( self->spawnflags & 4 ) - { + } else if (self->spawnflags & 4) { self->NPC_type = "rebornacrobat"; - } - else if ( self->spawnflags & 8 ) - { + } else if (self->spawnflags & 8) { self->NPC_type = "rebornboss"; - } - else - { + } else { self->NPC_type = "reborn"; } } - - WP_SetSaberModel( NULL, CLASS_REBORN ); - SP_NPC_spawner( self ); + + WP_SetSaberModel(NULL, CLASS_REBORN); + SP_NPC_spawner(self); } /*QUAKED NPC_ShadowTrooper(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2365,27 +2057,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_ShadowTrooper( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_ShadowTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "ShadowTrooper"; - } - else - { + } else { self->NPC_type = "ShadowTrooper2"; } } - + NPC_ShadowTrooper_Precache(); - WP_SetSaberModel( NULL, CLASS_SHADOWTROOPER ); + WP_SetSaberModel(NULL, CLASS_SHADOWTROOPER); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//MONSTERS +// MONSTERS //============================================================================================= /*QUAKED NPC_Monster_Murjj (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2395,11 +2082,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Murjj( gentity_t *self) -{ +void SP_NPC_Monster_Murjj(gentity_t *self) { self->NPC_type = "Murjj"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Swamp (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2409,11 +2095,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Swamp( gentity_t *self) -{ +void SP_NPC_Monster_Swamp(gentity_t *self) { self->NPC_type = "Swamp"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Howler (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2423,11 +2108,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Howler( gentity_t *self) -{ +void SP_NPC_Monster_Howler(gentity_t *self) { self->NPC_type = "howler"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MineMonster (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2437,11 +2121,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MineMonster( gentity_t *self) -{ +void SP_NPC_MineMonster(gentity_t *self) { self->NPC_type = "minemonster"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_MineMonster_Precache(); } @@ -2452,11 +2135,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Claw( gentity_t *self) -{ +void SP_NPC_Monster_Claw(gentity_t *self) { self->NPC_type = "Claw"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Glider (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2466,11 +2148,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Glider( gentity_t *self) -{ +void SP_NPC_Monster_Glider(gentity_t *self) { self->NPC_type = "Glider"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Flier2 (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2480,11 +2161,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Flier2( gentity_t *self) -{ +void SP_NPC_Monster_Flier2(gentity_t *self) { self->NPC_type = "Flier2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Lizard (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2494,11 +2174,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Lizard( gentity_t *self) -{ +void SP_NPC_Monster_Lizard(gentity_t *self) { self->NPC_type = "Lizard"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Fish (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2508,15 +2187,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Fish( gentity_t *self) -{ +void SP_NPC_Monster_Fish(gentity_t *self) { self->NPC_type = "Fish"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//DROIDS +// DROIDS //============================================================================================= /*QUAKED NPC_Droid_Interrogator (1 0 0) (-12 -12 -24) (12 12 0) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2526,11 +2204,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_Interrogator( gentity_t *self) -{ +void SP_NPC_Droid_Interrogator(gentity_t *self) { self->NPC_type = "interrogator"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Interrogator_Precache(self); } @@ -2544,11 +2221,10 @@ SHY - Spawner is shy Imperial Probe Droid - the multilegged floating droid that Han and Chewie shot on the ice planet Hoth */ -void SP_NPC_Droid_Probe( gentity_t *self) -{ +void SP_NPC_Droid_Probe(gentity_t *self) { self->NPC_type = "probe"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Probe_Precache(); } @@ -2563,11 +2239,10 @@ SHY - Spawner is shy Big walking droid */ -void SP_NPC_Droid_Mark1( gentity_t *self) -{ +void SP_NPC_Droid_Mark1(gentity_t *self) { self->NPC_type = "mark1"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Mark1_Precache(); } @@ -2582,11 +2257,10 @@ SHY - Spawner is shy Small rolling droid with one gun. */ -void SP_NPC_Droid_Mark2( gentity_t *self) -{ +void SP_NPC_Droid_Mark2(gentity_t *self) { self->NPC_type = "mark2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Mark2_Precache(); } @@ -2598,11 +2272,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_ATST( gentity_t *self) -{ +void SP_NPC_Droid_ATST(gentity_t *self) { self->NPC_type = "atst"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_ATST_Precache(); } @@ -2616,11 +2289,10 @@ SHY - Spawner is shy Remote Droid - the floating round droid used by Obi Wan to train Luke about the force while on the Millenium Falcon. */ -void SP_NPC_Droid_Remote( gentity_t *self) -{ +void SP_NPC_Droid_Remote(gentity_t *self) { self->NPC_type = "remote"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Remote_Precache(); } @@ -2634,11 +2306,10 @@ SHY - Spawner is shy Seeker Droid - floating round droids that shadow troopers spawn */ -void SP_NPC_Droid_Seeker( gentity_t *self) -{ +void SP_NPC_Droid_Seeker(gentity_t *self) { self->NPC_type = "seeker"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Seeker_Precache(); } @@ -2652,11 +2323,10 @@ SHY - Spawner is shy Sentry Droid - Large, armored floating Imperial droids with 3 forward-facing gun turrets */ -void SP_NPC_Droid_Sentry( gentity_t *self) -{ +void SP_NPC_Droid_Sentry(gentity_t *self) { self->NPC_type = "sentry"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Sentry_Precache(); } @@ -2672,13 +2342,12 @@ Gonk Droid - the droid that looks like a walking ice machine. Was in the Jawa la NOTARGET by default */ -void SP_NPC_Droid_Gonk( gentity_t *self) -{ +void SP_NPC_Droid_Gonk(gentity_t *self) { self->NPC_type = "gonk"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); - //precache the Gonk sounds + // precache the Gonk sounds NPC_Gonk_Precache(); } @@ -2693,15 +2362,13 @@ Mouse Droid - small, box shaped droid, first seen on the Death Star. Chewie yell NOTARGET by default */ -void SP_NPC_Droid_Mouse( gentity_t *self) -{ +void SP_NPC_Droid_Mouse(gentity_t *self) { self->NPC_type = "mouse"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); - //precache the Mouse sounds + // precache the Mouse sounds NPC_Mouse_Precache(); - } /*QUAKED NPC_Droid_R2D2 (1 0 0) (-12 -12 -24) (12 12 40) IMPERIAL x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2711,22 +2378,18 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy -R2D2 Droid - you probably know this one already. +R2D2 Droid - you probably know this one already. NOTARGET by default */ -void SP_NPC_Droid_R2D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R2D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r2d2_imp"; - } - else - { + } else { self->NPC_type = "r2d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_R2D2_Precache(); } @@ -2743,18 +2406,14 @@ R5D2 Droid - the droid originally chosen by Uncle Owen until it blew a bad motiv NOTARGET by default */ -void SP_NPC_Droid_R5D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R5D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r5d2_imp"; - } - else - { + } else { self->NPC_type = "r5d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_R5D2_Precache(); } @@ -2768,51 +2427,43 @@ SHY - Spawner is shy NOTARGET by default */ -void SP_NPC_Droid_Protocol( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_Protocol(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "protocol_imp"; - } - else - { + } else { self->NPC_type = "protocol"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Protocol_Precache(); } - -//NPC console commands +// NPC console commands /* NPC_Spawn_f */ -static void NPC_Spawn_f(void) -{ - gentity_t *NPCspawner = G_Spawn(); - vec3_t forward, end; - trace_t trace; - - if(!NPCspawner) - { - gi.Printf( S_COLOR_RED"NPC_Spawn Error: Out of entities!\n" ); +static void NPC_Spawn_f(void) { + gentity_t *NPCspawner = G_Spawn(); + vec3_t forward, end; + trace_t trace; + + if (!NPCspawner) { + gi.Printf(S_COLOR_RED "NPC_Spawn Error: Out of entities!\n"); return; } NPCspawner->e_ThinkFunc = thinkF_G_FreeEntity; NPCspawner->nextthink = level.time + FRAMETIME; - - const char *npc_type = gi.argv( 2 ); - if (!*npc_type ) - { - gi.Printf( S_COLOR_RED"Error, expected:\n NPC spawn [NPC type (from NCPCs.cfg)]\n" ); + + const char *npc_type = gi.argv(2); + if (!*npc_type) { + gi.Printf(S_COLOR_RED "Error, expected:\n NPC spawn [NPC type (from NCPCs.cfg)]\n"); return; } - //Spawn it at spot of first player - //FIXME: will gib them! + // Spawn it at spot of first player + // FIXME: will gib them! AngleVectors(g_entities[0].client->ps.viewangles, forward, NULL, NULL); VectorNormalize(forward); VectorMA(g_entities[0].currentOrigin, 64, forward, end); @@ -2824,277 +2475,198 @@ static void NPC_Spawn_f(void) end[2] += 24; G_SetOrigin(NPCspawner, end); VectorCopy(NPCspawner->currentOrigin, NPCspawner->s.origin); - //set the yaw so that they face away from player + // set the yaw so that they face away from player NPCspawner->s.angles[1] = g_entities[0].client->ps.viewangles[1]; gi.linkentity(NPCspawner); - NPCspawner->NPC_type = G_NewString( npc_type ); - NPCspawner->NPC_targetname = G_NewString(gi.argv( 3 )); + NPCspawner->NPC_type = G_NewString(npc_type); + NPCspawner->NPC_targetname = G_NewString(gi.argv(3)); NPCspawner->count = 1; NPCspawner->delay = 0; - //NPCspawner->spawnflags |= SFB_NOTSOLID; + // NPCspawner->spawnflags |= SFB_NOTSOLID; - //NPCspawner->playerTeam = TEAM_FREE; - //NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; - //call precache funcs for James' builds - if ( !Q_stricmp( "gonk", NPCspawner->NPC_type)) - { + // NPCspawner->playerTeam = TEAM_FREE; + // NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; + // call precache funcs for James' builds + if (!Q_stricmp("gonk", NPCspawner->NPC_type)) { NPC_Gonk_Precache(); - } - else if ( !Q_stricmp( "mouse", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mouse", NPCspawner->NPC_type)) { NPC_Mouse_Precache(); - } - else if ( !Q_strncmp( "r2d2", NPCspawner->NPC_type, 4)) - { + } else if (!Q_strncmp("r2d2", NPCspawner->NPC_type, 4)) { NPC_R2D2_Precache(); - } - else if ( !Q_stricmp( "atst", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("atst", NPCspawner->NPC_type)) { NPC_ATST_Precache(); - } - else if ( !Q_strncmp( "r5d2", NPCspawner->NPC_type, 4)) - { + } else if (!Q_strncmp("r5d2", NPCspawner->NPC_type, 4)) { NPC_R5D2_Precache(); - } - else if ( !Q_stricmp( "mark1", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mark1", NPCspawner->NPC_type)) { NPC_Mark1_Precache(); - } - else if ( !Q_stricmp( "mark2", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mark2", NPCspawner->NPC_type)) { NPC_Mark2_Precache(); - } - else if ( !Q_stricmp( "interrogator", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("interrogator", NPCspawner->NPC_type)) { NPC_Interrogator_Precache(NULL); - } - else if ( !Q_stricmp( "probe", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("probe", NPCspawner->NPC_type)) { NPC_Probe_Precache(); - } - else if ( !Q_stricmp( "seeker", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("seeker", NPCspawner->NPC_type)) { NPC_Seeker_Precache(); - } - else if ( !Q_stricmp( "remote", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("remote", NPCspawner->NPC_type)) { NPC_Remote_Precache(); - } - else if ( !Q_strncmp( "shadowtrooper", NPCspawner->NPC_type, 13 ) ) - { + } else if (!Q_strncmp("shadowtrooper", NPCspawner->NPC_type, 13)) { NPC_ShadowTrooper_Precache(); - } - else if ( !Q_stricmp( "minemonster", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("minemonster", NPCspawner->NPC_type)) { NPC_MineMonster_Precache(); - } - else if ( !Q_stricmp( "howler", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("howler", NPCspawner->NPC_type)) { NPC_Howler_Precache(); - } - else if ( !Q_stricmp( "sentry", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("sentry", NPCspawner->NPC_type)) { NPC_Sentry_Precache(); - } - else if ( !Q_stricmp( "protocol", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("protocol", NPCspawner->NPC_type)) { NPC_Protocol_Precache(); - } - else if ( !Q_stricmp( "galak_mech", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("galak_mech", NPCspawner->NPC_type)) { NPC_GalakMech_Precache(); } - NPC_Spawn( NPCspawner, NPCspawner, NPCspawner ); + NPC_Spawn(NPCspawner, NPCspawner, NPCspawner); } /* NPC_Kill_f */ -void NPC_Kill_f( void ) -{ - int n; - gentity_t *player; - char *name; - team_t killTeam = TEAM_FREE; - qboolean killNonSF = qfalse; +void NPC_Kill_f(void) { + int n; + gentity_t *player; + char *name; + team_t killTeam = TEAM_FREE; + qboolean killNonSF = qfalse; - name = gi.argv( 2 ); + name = gi.argv(2); - if ( !*name || !name[0] ) - { - gi.Printf( S_COLOR_RED"Error, Expected:\n"); - gi.Printf( S_COLOR_RED"NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n" ); - gi.Printf( S_COLOR_RED"or\n" ); - gi.Printf( S_COLOR_RED"NPC kill 'all' - kills all NPCs\n" ); - gi.Printf( S_COLOR_RED"or\n" ); - gi.Printf( S_COLOR_RED"NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n" ); + if (!*name || !name[0]) { + gi.Printf(S_COLOR_RED "Error, Expected:\n"); + gi.Printf(S_COLOR_RED "NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n"); + gi.Printf(S_COLOR_RED "or\n"); + gi.Printf(S_COLOR_RED "NPC kill 'all' - kills all NPCs\n"); + gi.Printf(S_COLOR_RED "or\n"); + gi.Printf(S_COLOR_RED "NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n"); return; } - if ( Q_stricmp( "team", name ) == 0 ) - { - name = gi.argv( 3 ); + if (Q_stricmp("team", name) == 0) { + name = gi.argv(3); - if ( !*name || !name[0] ) - { - gi.Printf( S_COLOR_RED"NPC_Kill Error: 'npc kill team' requires a team name!\n" ); - gi.Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED"%s\n", TeamNames[n] ); + if (!*name || !name[0]) { + gi.Printf(S_COLOR_RED "NPC_Kill Error: 'npc kill team' requires a team name!\n"); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - gi.Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + gi.Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } - if ( Q_stricmp( "nonally", name ) == 0 ) - { + if (Q_stricmp("nonally", name) == 0) { killNonSF = qtrue; - } - else - { - killTeam = TranslateTeamName( name ); - - if ( killTeam == TEAM_FREE ) - { - gi.Printf( S_COLOR_RED"NPC_Kill Error: team '%s' not recognized\n", name ); - gi.Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED"%s\n", TeamNames[n] ); + } else { + killTeam = TranslateTeamName(name); + + if (killTeam == TEAM_FREE) { + gi.Printf(S_COLOR_RED "NPC_Kill Error: team '%s' not recognized\n", name); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - gi.Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + gi.Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } } } - for ( n = 1; n < ENTITYNUM_MAX_NORMAL; n++) - { + for (n = 1; n < ENTITYNUM_MAX_NORMAL; n++) { player = &g_entities[n]; if (!player->inuse) { continue; } - if ( killNonSF ) - { - if ( player ) - { - if ( player->client ) - { - if ( player->client->playerTeam != TEAM_PLAYER ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + if (killNonSF) { + if (player) { + if (player->client) { + if (player->client->playerTeam != TEAM_PLAYER) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; GEntity_DieFunc(player, player, player, player->max_health, MOD_UNKNOWN); } - } - else if ( player->NPC_type && player->classname && player->classname[0] && Q_stricmp( "NPC_starfleet", player->classname ) != 0 ) - {//A spawner, remove it - gi.Printf( S_COLOR_GREEN"Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname ); - G_FreeEntity( player ); - //FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? + } else if (player->NPC_type && player->classname && player->classname[0] && + Q_stricmp("NPC_starfleet", player->classname) != 0) { // A spawner, remove it + gi.Printf(S_COLOR_GREEN "Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname); + G_FreeEntity(player); + // FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? } } - } - else if ( player && player->NPC && player->client ) - { - if ( killTeam != TEAM_FREE ) - { - if ( player->client->playerTeam == killTeam ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if (player && player->NPC && player->client) { + if (killTeam != TEAM_FREE) { + if (player->client->playerTeam == killTeam) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; GEntity_DieFunc(player, player, player, player->max_health, MOD_UNKNOWN); } - } - else if( (player->targetname && Q_stricmp( name, player->targetname ) == 0) - || Q_stricmp( name, "all" ) == 0 ) - { - gi.Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if ((player->targetname && Q_stricmp(name, player->targetname) == 0) || Q_stricmp(name, "all") == 0) { + gi.Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; player->client->ps.stats[STAT_HEALTH] = 0; GEntity_DieFunc(player, player, player, 100, MOD_UNKNOWN); } - } - else if ( player && (player->svFlags&SVF_NPC_PRECACHE) ) - {//a spawner - gi.Printf( S_COLOR_GREEN"Removing NPC spawner %s named %s\n", player->NPC_type, player->targetname ); - G_FreeEntity( player ); + } else if (player && (player->svFlags & SVF_NPC_PRECACHE)) { // a spawner + gi.Printf(S_COLOR_GREEN "Removing NPC spawner %s named %s\n", player->NPC_type, player->targetname); + G_FreeEntity(player); } } } -void NPC_PrintScore( gentity_t *ent ) -{ - gi.Printf( "%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE] ); -} +void NPC_PrintScore(gentity_t *ent) { gi.Printf("%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE]); } /* Svcmd_NPC_f parse and dispatch bot commands */ -qboolean showBBoxes = qfalse; -void Svcmd_NPC_f( void ) -{ - char *cmd; +qboolean showBBoxes = qfalse; +void Svcmd_NPC_f(void) { + char *cmd; - cmd = gi.argv( 1 ); + cmd = gi.argv(1); - if ( !*cmd ) - { - gi.Printf( "Valid NPC commands are:\n" ); - gi.Printf( " spawn [NPC type (from NCPCs.cfg)]\n" ); - gi.Printf( " kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n" ); - gi.Printf( " showbounds (draws exact bounding boxes of NPCs)\n" ); - gi.Printf( " score [NPC targetname] (prints number of kills per NPC)\n" ); - } - else if ( Q_stricmp( cmd, "spawn" ) == 0 ) - { + if (!*cmd) { + gi.Printf("Valid NPC commands are:\n"); + gi.Printf(" spawn [NPC type (from NCPCs.cfg)]\n"); + gi.Printf(" kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n"); + gi.Printf(" showbounds (draws exact bounding boxes of NPCs)\n"); + gi.Printf(" score [NPC targetname] (prints number of kills per NPC)\n"); + } else if (Q_stricmp(cmd, "spawn") == 0) { NPC_Spawn_f(); - } - else if ( Q_stricmp( cmd, "kill" ) == 0 ) - { + } else if (Q_stricmp(cmd, "kill") == 0) { NPC_Kill_f(); - } - else if ( Q_stricmp( cmd, "showbounds" ) == 0 ) - {//Toggle on and off + } else if (Q_stricmp(cmd, "showbounds") == 0) { // Toggle on and off showBBoxes = showBBoxes ? qfalse : qtrue; - } - else if ( Q_stricmp ( cmd, "score" ) == 0 ) - { - char *cmd2 = gi.argv(2); + } else if (Q_stricmp(cmd, "score") == 0) { + char *cmd2 = gi.argv(2); gentity_t *ent = NULL; - if ( !cmd2 || !cmd2[0] ) - {//Show the score for all NPCs - gi.Printf( "SCORE LIST:\n" ); - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { + if (!cmd2 || !cmd2[0]) { // Show the score for all NPCs + gi.Printf("SCORE LIST:\n"); + for (int i = 0; i < ENTITYNUM_WORLD; i++) { ent = &g_entities[i]; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { continue; } - NPC_PrintScore( ent ); - } - } - else - { - if ( (ent = G_Find( NULL, FOFS(targetname), cmd2 )) != NULL && ent->client ) - { - NPC_PrintScore( ent ); + NPC_PrintScore(ent); } - else - { - gi.Printf( "ERROR: NPC score - no such NPC %s\n", cmd2 ); + } else { + if ((ent = G_Find(NULL, FOFS(targetname), cmd2)) != NULL && ent->client) { + NPC_PrintScore(ent); + } else { + gi.Printf("ERROR: NPC score - no such NPC %s\n", cmd2); } } } diff --git a/codeJK2/game/NPC_stats.cpp b/codeJK2/game/NPC_stats.cpp index ecaa627b01..92c1086b64 100644 --- a/codeJK2/game/NPC_stats.cpp +++ b/codeJK2/game/NPC_stats.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_stats.cpp +// NPC_stats.cpp #include "g_headers.h" @@ -32,98 +32,39 @@ extern qboolean NPCsPrecached; extern vec3_t playerMins; extern vec3_t playerMaxs; -char *TeamNames[TEAM_NUM_TEAMS] = -{ - "", - "player", - "enemy", - "neutral" -}; +char *TeamNames[TEAM_NUM_TEAMS] = {"", "player", "enemy", "neutral"}; // this list was made using the model directories, this MUST be in the same order as the CLASS_ enum in teams.h -char *ClassNames[CLASS_NUM_CLASSES] = -{ - "", // class none - "atst", - "bartender", - "bespin_cop", - "claw", - "commando", - "desann", - "fish", - "flier2", - "galak", - "glider", - "gonk", - "gran", - "howler", - "imperial", - "impworker", - "interrogator", - "jan", - "jedi", - "kyle", - "lando", - "lizard", - "luke", - "mark1", - "mark2", - "galak_mech", - "minemonster", - "monmotha", - "morgankatarn", - "mouse", - "murjj", - "prisoner", - "probe", - "protocol", - "r2d2", - "r5d2", - "rebel", - "reborn", - "reelo", - "remote", - "rodian", - "seeker", - "sentry", - "shadowtrooper", - "stormtrooper", - "swamp", - "swamptrooper", - "tavion", - "trandoshan", - "ugnaught", - "weequay", +char *ClassNames[CLASS_NUM_CLASSES] = { + "", // class none + "atst", "bartender", "bespin_cop", "claw", "commando", "desann", "fish", "flier2", "galak", "glider", + "gonk", "gran", "howler", "imperial", "impworker", "interrogator", "jan", "jedi", "kyle", "lando", + "lizard", "luke", "mark1", "mark2", "galak_mech", "minemonster", "monmotha", "morgankatarn", "mouse", "murjj", + "prisoner", "probe", "protocol", "r2d2", "r5d2", "rebel", "reborn", "reelo", "remote", "rodian", + "seeker", "sentry", "shadowtrooper", "stormtrooper", "swamp", "swamptrooper", "tavion", "trandoshan", "ugnaught", "weequay", }; - /* NPC_ReactionTime */ -//FIXME use grandom in here -int NPC_ReactionTime ( void ) -{ - return 200 * ( 6 - NPCInfo->stats.reactions ); -} +// FIXME use grandom in here +int NPC_ReactionTime(void) { return 200 * (6 - NPCInfo->stats.reactions); } // // parse support routines // -qboolean G_ParseLiteral( const char **data, const char *string ) -{ - const char *token; +qboolean G_ParseLiteral(const char **data, const char *string) { + const char *token; - token = COM_ParseExt( data, qtrue ); - if ( token[0] == 0 ) - { - gi.Printf( "unexpected EOF\n" ); + token = COM_ParseExt(data, qtrue); + if (token[0] == 0) { + gi.Printf("unexpected EOF\n"); return qtrue; } - if ( Q_stricmp( token, string ) ) - { - gi.Printf( "required string '%s' missing\n", string ); + if (Q_stricmp(token, string)) { + gi.Printf("required string '%s' missing\n", string); return qtrue; } @@ -134,33 +75,26 @@ qboolean G_ParseLiteral( const char **data, const char *string ) // NPC parameters file : scripts/NPCs.cfg // #define MAX_NPC_DATA_SIZE 0x40000 -char NPCParms[MAX_NPC_DATA_SIZE]; - -team_t TranslateTeamName( const char *name ) -{ - for ( int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - if ( Q_stricmp( TeamNames[n], name ) == 0 ) - { - return ((team_t) n); +char NPCParms[MAX_NPC_DATA_SIZE]; + +team_t TranslateTeamName(const char *name) { + for (int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + if (Q_stricmp(TeamNames[n], name) == 0) { + return ((team_t)n); } } return TEAM_FREE; } - -class_t TranslateClassName( const char *name ) -{ - for ( int n = (CLASS_NONE + 1); n < CLASS_NUM_CLASSES; n++ ) - { - if ( Q_stricmp( ClassNames[n], name ) == 0 ) - { - return ((class_t) n); +class_t TranslateClassName(const char *name) { + for (int n = (CLASS_NONE + 1); n < CLASS_NUM_CLASSES; n++) { + if (Q_stricmp(ClassNames[n], name) == 0) { + return ((class_t)n); } } - return CLASS_NONE; // I hope this never happens, maybe print a warning + return CLASS_NONE; // I hope this never happens, maybe print a warning } /* @@ -168,79 +102,62 @@ static rank_t TranslateRankName( const char *name ) Should be used to determine pip bolt-ons */ -static rank_t TranslateRankName( const char *name ) -{ - if ( !Q_stricmp( name, "civilian" ) ) - { +static rank_t TranslateRankName(const char *name) { + if (!Q_stricmp(name, "civilian")) { return RANK_CIVILIAN; } - if ( !Q_stricmp( name, "crewman" ) ) - { + if (!Q_stricmp(name, "crewman")) { return RANK_CREWMAN; } - if ( !Q_stricmp( name, "ensign" ) ) - { + if (!Q_stricmp(name, "ensign")) { return RANK_ENSIGN; } - if ( !Q_stricmp( name, "ltjg" ) ) - { + if (!Q_stricmp(name, "ltjg")) { return RANK_LT_JG; } - if ( !Q_stricmp( name, "lt" ) ) - { + if (!Q_stricmp(name, "lt")) { return RANK_LT; } - if ( !Q_stricmp( name, "ltcomm" ) ) - { + if (!Q_stricmp(name, "ltcomm")) { return RANK_LT_COMM; } - if ( !Q_stricmp( name, "commander" ) ) - { + if (!Q_stricmp(name, "commander")) { return RANK_COMMANDER; } - if ( !Q_stricmp( name, "captain" ) ) - { + if (!Q_stricmp(name, "captain")) { return RANK_CAPTAIN; } return RANK_CIVILIAN; } -static saber_colors_t TranslateSaberColor( const char *name ) -{ - if ( !Q_stricmp( name, "red" ) ) - { +static saber_colors_t TranslateSaberColor(const char *name) { + if (!Q_stricmp(name, "red")) { return SABER_RED; } - if ( !Q_stricmp( name, "orange" ) ) - { + if (!Q_stricmp(name, "orange")) { return SABER_ORANGE; } - if ( !Q_stricmp( name, "yellow" ) ) - { + if (!Q_stricmp(name, "yellow")) { return SABER_YELLOW; } - if ( !Q_stricmp( name, "green" ) ) - { + if (!Q_stricmp(name, "green")) { return SABER_GREEN; } - if ( !Q_stricmp( name, "blue" ) ) - { + if (!Q_stricmp(name, "blue")) { return SABER_BLUE; } - if ( !Q_stricmp( name, "purple" ) ) - { + if (!Q_stricmp(name, "purple")) { return SABER_PURPLE; } - if ( !Q_stricmp( name, "random" ) ) - { - return ((saber_colors_t)(Q_irand( SABER_ORANGE, SABER_PURPLE ))); + if (!Q_stricmp(name, "random")) { + return ((saber_colors_t)(Q_irand(SABER_ORANGE, SABER_PURPLE))); } return SABER_BLUE; } @@ -279,22 +196,14 @@ static int ItemNameToNumber( const char *name, int itemType ) { } */ -static int MoveTypeNameToEnum( const char *name ) -{ - if(!Q_stricmp("runjump", name)) - { +static int MoveTypeNameToEnum(const char *name) { + if (!Q_stricmp("runjump", name)) { return MT_RUNJUMP; - } - else if(!Q_stricmp("walk", name)) - { + } else if (!Q_stricmp("walk", name)) { return MT_WALK; - } - else if(!Q_stricmp("flyswim", name)) - { + } else if (!Q_stricmp("flyswim", name)) { return MT_FLYSWIM; - } - else if(!Q_stricmp("static", name)) - { + } else if (!Q_stricmp("static", name)) { return MT_STATIC; } @@ -302,31 +211,28 @@ static int MoveTypeNameToEnum( const char *name ) } extern void CG_RegisterClientRenderInfo(clientInfo_t *ci, renderInfo_t *ri); -extern void CG_RegisterClientModels (int entityNum); -extern void CG_RegisterNPCCustomSounds( clientInfo_t *ci ); -extern void CG_RegisterNPCEffects( team_t team ); -extern void CG_ParseAnimationSndFile( const char *filename, int animFileIndex ); +extern void CG_RegisterClientModels(int entityNum); +extern void CG_RegisterNPCCustomSounds(clientInfo_t *ci); +extern void CG_RegisterNPCEffects(team_t team); +extern void CG_ParseAnimationSndFile(const char *filename, int animFileIndex); //#define CONVENIENT_ANIMATION_FILE_DEBUG_THING #ifdef CONVENIENT_ANIMATION_FILE_DEBUG_THING -void SpewDebugStuffToFile(animation_t *bgGlobalAnimations) -{ +void SpewDebugStuffToFile(animation_t *bgGlobalAnimations) { char BGPAFtext[40000]; fileHandle_t f; int i = 0; gi.FS_FOpenFile("file_of_debug_stuff_SP.txt", &f, FS_WRITE); - if (!f) - { + if (!f) { return; } BGPAFtext[0] = 0; - while (i < MAX_ANIMATIONS) - { + while (i < MAX_ANIMATIONS) { strcat(BGPAFtext, va("%i %i\n", i, bgGlobalAnimations[i].frameLerp)); i++; } @@ -345,43 +251,38 @@ models/players/visor/animation.cfg, etc ====================== */ -qboolean G_ParseAnimationFile( const char *af_filename ) -{ - const char *text_p; - int len; - int i; - const char *token; - float fps; - //int skip; - char text[40000]; - int animNum; - animation_t *animations = level.knownAnimFileSets[level.numKnownAnimFileSets].animations; +qboolean G_ParseAnimationFile(const char *af_filename) { + const char *text_p; + int len; + int i; + const char *token; + float fps; + // int skip; + char text[40000]; + int animNum; + animation_t *animations = level.knownAnimFileSets[level.numKnownAnimFileSets].animations; len = gi.RE_GetAnimationCFG(af_filename, NULL, 0); - if (len <= 0) - { + if (len <= 0) { return qfalse; } - if ( len <= 0 ) - { + if (len <= 0) { return qfalse; } - if ( len >= (int)sizeof(text) - 1 ) - { - G_Error( "G_ParseAnimationFile: File %s too long\n (%d > %d)", af_filename, len, sizeof( text ) - 1); + if (len >= (int)sizeof(text) - 1) { + G_Error("G_ParseAnimationFile: File %s too long\n (%d > %d)", af_filename, len, sizeof(text) - 1); return qfalse; } len = gi.RE_GetAnimationCFG(af_filename, text, sizeof(text)); // parse the text text_p = text; - //skip = 0; // quiet the compiler warning + // skip = 0; // quiet the compiler warning - //FIXME: have some way of playing anims backwards... negative numFrames? + // FIXME: have some way of playing anims backwards... negative numFrames? - //initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 - for(i = 0; i < MAX_ANIMATIONS; i++) - { + // initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 + for (i = 0; i < MAX_ANIMATIONS; i++) { animations[i].firstFrame = 0; animations[i].numFrames = 0; animations[i].loopFrames = -1; @@ -391,62 +292,51 @@ qboolean G_ParseAnimationFile( const char *af_filename ) // read information for each frame COM_BeginParseSession(); - while(1) - { - token = COM_Parse( &text_p ); + while (1) { + token = COM_Parse(&text_p); - if ( !token || !token[0]) - { + if (!token || !token[0]) { break; } animNum = GetIDForString(animTable, token); - if(animNum == -1) - { + if (animNum == -1) { //#ifndef FINAL_BUILD #ifdef _DEBUG - Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, af_filename); + Com_Printf(S_COLOR_RED "WARNING: Unknown token %s in %s\n", token, af_filename); #endif continue; } - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].firstFrame = atoi( token ); + animations[animNum].firstFrame = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].numFrames = atoi( token ); + animations[animNum].numFrames = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - animations[animNum].loopFrames = atoi( token ); + animations[animNum].loopFrames = atoi(token); - token = COM_Parse( &text_p ); - if ( !token ) - { + token = COM_Parse(&text_p); + if (!token) { break; } - fps = atof( token ); - if ( fps == 0 ) - { - fps = 1;//Don't allow divide by zero error + fps = atof(token); + if (fps == 0) { + fps = 1; // Don't allow divide by zero error } - if ( fps < 0 ) - {//backwards + if (fps < 0) { // backwards animations[animNum].frameLerp = floor(1000.0f / fps); - } - else - { + } else { animations[animNum].frameLerp = ceil(1000.0f / fps); } @@ -455,8 +345,7 @@ qboolean G_ParseAnimationFile( const char *af_filename ) COM_EndParseSession(); #ifdef CONVENIENT_ANIMATION_FILE_DEBUG_THING - if (strstr(af_filename, "humanoid")) - { + if (strstr(af_filename, "humanoid")) { SpewDebugStuffToFile(animations); } #endif @@ -464,105 +353,90 @@ qboolean G_ParseAnimationFile( const char *af_filename ) return qtrue; } -qboolean G_ParseAnimFileSet( const char *filename, const char *animCFG, int *animFileIndex ) -{ - char afilename[MAX_QPATH]; - char strippedName[MAX_QPATH]; - int i; - char *slash; +qboolean G_ParseAnimFileSet(const char *filename, const char *animCFG, int *animFileIndex) { + char afilename[MAX_QPATH]; + char strippedName[MAX_QPATH]; + int i; + char *slash; Q_strncpyz(strippedName, filename, sizeof(strippedName)); - slash = strchr( strippedName, '/' ); - if ( slash ) - { + slash = strchr(strippedName, '/'); + if (slash) { // truncate modelName to find just the dir not the extension *slash = 0; } - //if this anims file was loaded before, don't parse it again, just point to the correct table of info - for ( i = 0; i < level.numKnownAnimFileSets; i++ ) - { - if ( Q_stricmp(level.knownAnimFileSets[i].filename, strippedName ) == 0 ) - { + // if this anims file was loaded before, don't parse it again, just point to the correct table of info + for (i = 0; i < level.numKnownAnimFileSets; i++) { + if (Q_stricmp(level.knownAnimFileSets[i].filename, strippedName) == 0) { *animFileIndex = i; - CG_ParseAnimationSndFile( strippedName, *animFileIndex ); + CG_ParseAnimationSndFile(strippedName, *animFileIndex); return qtrue; } } - if ( level.numKnownAnimFileSets == MAX_ANIM_FILES ) - {//TOO MANY! - G_Error( "G_ParseAnimFileSet: MAX_ANIM_FILES" ); + if (level.numKnownAnimFileSets == MAX_ANIM_FILES) { // TOO MANY! + G_Error("G_ParseAnimFileSet: MAX_ANIM_FILES"); } - //Okay, time to parse in a new one - Q_strncpyz( level.knownAnimFileSets[level.numKnownAnimFileSets].filename, strippedName, sizeof( level.knownAnimFileSets[level.numKnownAnimFileSets].filename ) ); + // Okay, time to parse in a new one + Q_strncpyz(level.knownAnimFileSets[level.numKnownAnimFileSets].filename, strippedName, + sizeof(level.knownAnimFileSets[level.numKnownAnimFileSets].filename)); // Load and parse animations.cfg file - Com_sprintf( afilename, sizeof( afilename ), "models/players/%s/animation.cfg", animCFG ); - if ( !G_ParseAnimationFile( afilename ) ) - { + Com_sprintf(afilename, sizeof(afilename), "models/players/%s/animation.cfg", animCFG); + if (!G_ParseAnimationFile(afilename)) { *animFileIndex = -1; return qfalse; } - //set index and increment + // set index and increment *animFileIndex = level.numKnownAnimFileSets++; - CG_ParseAnimationSndFile( strippedName, *animFileIndex ); + CG_ParseAnimationSndFile(strippedName, *animFileIndex); return qtrue; } -void G_LoadAnimFileSet( gentity_t *ent, const char *modelName ) -{ -//load its animation config - char animName[MAX_QPATH]; - char *GLAName; - char *slash = NULL; - char *strippedName; +void G_LoadAnimFileSet(gentity_t *ent, const char *modelName) { + // load its animation config + char animName[MAX_QPATH]; + char *GLAName; + char *slash = NULL; + char *strippedName; - if ( ent->playerModel == -1 ) - { + if (ent->playerModel == -1) { return; } - //get the location of the animation.cfg - GLAName = gi.G2API_GetGLAName( &ent->ghoul2[ent->playerModel] ); - //now load and parse the animation.cfg, animsounds.cfg and set the animFileIndex - if ( !GLAName) - { - Com_Printf( S_COLOR_RED"Failed find animation file name models/players/%s/animation.cfg\n", modelName ); - strippedName="broken"; - } - else - { - Q_strncpyz(animName, GLAName, sizeof( animName )); - slash = strrchr( animName, '/' ); - if ( slash ) - { + // get the location of the animation.cfg + GLAName = gi.G2API_GetGLAName(&ent->ghoul2[ent->playerModel]); + // now load and parse the animation.cfg, animsounds.cfg and set the animFileIndex + if (!GLAName) { + Com_Printf(S_COLOR_RED "Failed find animation file name models/players/%s/animation.cfg\n", modelName); + strippedName = "broken"; + } else { + Q_strncpyz(animName, GLAName, sizeof(animName)); + slash = strrchr(animName, '/'); + if (slash) { *slash = 0; } - strippedName = COM_SkipPath( animName ); + strippedName = COM_SkipPath(animName); } - //now load and parse the animation.cfg, animsounds.cfg and set the animFileIndex - if ( !G_ParseAnimFileSet( modelName, strippedName, &ent->client->clientInfo.animFileIndex ) ) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/%s/animation.cfg\n", modelName ); + // now load and parse the animation.cfg, animsounds.cfg and set the animFileIndex + if (!G_ParseAnimFileSet(modelName, strippedName, &ent->client->clientInfo.animFileIndex)) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/%s/animation.cfg\n", modelName); } } +void NPC_PrecacheAnimationCFG(const char *NPC_type) { + char filename[MAX_QPATH]; + const char *token; + const char *value; + const char *p; + int junk; -void NPC_PrecacheAnimationCFG( const char *NPC_type ) -{ - char filename[MAX_QPATH]; - const char *token; - const char *value; - const char *p; - int junk; - - if ( !Q_stricmp( "random", NPC_type ) ) - {//sorry, can't precache a random just yet + if (!Q_stricmp("random", NPC_type)) { // sorry, can't precache a random just yet return; } @@ -570,129 +444,112 @@ void NPC_PrecacheAnimationCFG( const char *NPC_type ) COM_BeginParseSession(); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, NPC_type ) ) - { + if (!Q_stricmp(token, NPC_type)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", NPC_type ); - COM_EndParseSession( ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", NPC_type); + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - //must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt - Q_strncpyz(filename, value, sizeof( filename )); - G_ParseAnimFileSet( filename, filename, &junk ); - COM_EndParseSession( ); + // must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt + Q_strncpyz(filename, value, sizeof(filename)); + G_ParseAnimFileSet(filename, filename, &junk); + COM_EndParseSession(); return; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - char animName[MAX_QPATH]; - char *GLAName; - char *slash = NULL; - char *strippedName; + char animName[MAX_QPATH]; + char *GLAName; + char *slash = NULL; + char *strippedName; - int handle = gi.G2API_PrecacheGhoul2Model( va( "models/players/%s/model.glm", value ) ); - if ( handle > 0 )//FIXME: isn't 0 a valid handle? + int handle = gi.G2API_PrecacheGhoul2Model(va("models/players/%s/model.glm", value)); + if (handle > 0) // FIXME: isn't 0 a valid handle? { - GLAName = gi.G2API_GetAnimFileNameIndex( handle ); - if ( GLAName ) - { - Q_strncpyz(animName, GLAName, sizeof( animName )); - slash = strrchr( animName, '/' ); - if ( slash ) - { + GLAName = gi.G2API_GetAnimFileNameIndex(handle); + if (GLAName) { + Q_strncpyz(animName, GLAName, sizeof(animName)); + slash = strrchr(animName, '/'); + if (slash) { *slash = 0; } - strippedName = COM_SkipPath( animName ); + strippedName = COM_SkipPath(animName); - //must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt - Q_strncpyz(filename, value, sizeof( filename )); - G_ParseAnimFileSet( value, strippedName, &junk );//qfalse ); - COM_EndParseSession( ); - //FIXME: still not precaching the animsounds.cfg? + // must copy data out of this pointer into a different part of memory because the funcs we're about to call will call COM_ParseExt + Q_strncpyz(filename, value, sizeof(filename)); + G_ParseAnimFileSet(value, strippedName, &junk); // qfalse ); + COM_EndParseSession(); + // FIXME: still not precaching the animsounds.cfg? return; } } } } - COM_EndParseSession( ); + COM_EndParseSession(); } -extern int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ); -void NPC_PrecacheWeapons( team_t playerTeam, int spawnflags, char *NPCtype ) -{ - int weapons = NPC_WeaponsForTeam( playerTeam, spawnflags, NPCtype ); - gitem_t *item; - for ( int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if ( (weapons & ( 1 << curWeap )) ) - { - item = FindItemForWeapon( ((weapon_t)(curWeap)) ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - //precache the in-hand/in-world ghoul2 weapon model +extern int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type); +void NPC_PrecacheWeapons(team_t playerTeam, int spawnflags, char *NPCtype) { + int weapons = NPC_WeaponsForTeam(playerTeam, spawnflags, NPCtype); + gitem_t *item; + for (int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if ((weapons & (1 << curWeap))) { + item = FindItemForWeapon(((weapon_t)(curWeap))); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + // precache the in-hand/in-world ghoul2 weapon model char weaponModel[MAX_QPATH]; Q_strncpyz(weaponModel, weaponData[curWeap].weaponMdl, sizeof(weaponModel)); - if (char *spot = strstr(weaponModel, ".md3") ) { + if (char *spot = strstr(weaponModel, ".md3")) { *spot = 0; - spot = strstr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on + spot = strstr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on if (!spot) { - strcat (weaponModel, "_w"); + strcat(weaponModel, "_w"); } - strcat (weaponModel, ".glm"); //and change to ghoul2 + strcat(weaponModel, ".glm"); // and change to ghoul2 } - gi.G2API_PrecacheGhoul2Model( weaponModel ); // correct way is item->world_model + gi.G2API_PrecacheGhoul2Model(weaponModel); // correct way is item->world_model } } } @@ -703,22 +560,20 @@ void NPC_Precache ( char *NPCName ) Precaches NPC skins, tgas and md3s. */ -void NPC_Precache ( gentity_t *spawner ) -{ - clientInfo_t ci={}; - renderInfo_t ri={}; - team_t playerTeam = TEAM_FREE; - const char *token; - const char *value; - const char *p; - char *patch; - char sound[MAX_QPATH]; - qboolean md3Model = qfalse; - char playerModel[MAX_QPATH]; - char customSkin[MAX_QPATH]; - - if ( !Q_stricmp( "random", spawner->NPC_type ) ) - {//sorry, can't precache a random just yet +void NPC_Precache(gentity_t *spawner) { + clientInfo_t ci = {}; + renderInfo_t ri = {}; + team_t playerTeam = TEAM_FREE; + const char *token; + const char *value; + const char *p; + char *patch; + char sound[MAX_QPATH]; + qboolean md3Model = qfalse; + char playerModel[MAX_QPATH]; + char customSkin[MAX_QPATH]; + + if (!Q_stricmp("random", spawner->NPC_type)) { // sorry, can't precache a random just yet return; } Q_strncpyz(customSkin, "default", sizeof(customSkin)); @@ -727,66 +582,53 @@ void NPC_Precache ( gentity_t *spawner ) COM_BeginParseSession(); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, spawner->NPC_type ) ) - { + if (!Q_stricmp(token, spawner->NPC_type)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return; } // parse the NPC info block - while ( 1 ) - { - COM_EndParseSession(); // if still in session (or using continue;) + while (1) { + COM_EndParseSession(); // if still in session (or using continue;) COM_BeginParseSession(); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type ); - COM_EndParseSession( ); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type); + COM_EndParseSession(); return; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { + if (!Q_stricmp("none", value)) { + } else { Q_strncpyz(ri.headModelName, value, sizeof(ri.headModelName)); } md3Model = qtrue; @@ -794,18 +636,13 @@ void NPC_Precache ( gentity_t *spawner ) } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { + if (!Q_stricmp("none", value)) { + } else { Q_strncpyz(ri.torsoModelName, value, sizeof(ri.torsoModelName)); } md3Model = qtrue; @@ -813,10 +650,8 @@ void NPC_Precache ( gentity_t *spawner ) } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } Q_strncpyz(ri.legsModelName, value, sizeof(ri.legsModelName)); @@ -825,10 +660,8 @@ void NPC_Precache ( gentity_t *spawner ) } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } Q_strncpyz(playerModel, value, sizeof(playerModel)); @@ -837,10 +670,8 @@ void NPC_Precache ( gentity_t *spawner ) } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } Q_strncpyz(customSkin, value, sizeof(customSkin)); @@ -848,132 +679,115 @@ void NPC_Precache ( gentity_t *spawner ) } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerTeam")) { + if (COM_ParseString(&p, &value)) { continue; } playerTeam = TranslateTeamName(value); continue; } - // snd - if ( !Q_stricmp( token, "snd" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customBasicSoundDir = G_NewString( sound ); + ci.customBasicSoundDir = G_NewString(sound); } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customCombatSoundDir = G_NewString( sound ); + ci.customCombatSoundDir = G_NewString(sound); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customExtraSoundDir = G_NewString( sound ); + ci.customExtraSoundDir = G_NewString(sound); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci.customJediSoundDir = G_NewString( sound ); + ci.customJediSoundDir = G_NewString(sound); } continue; } } - COM_EndParseSession( ); + COM_EndParseSession(); - if ( md3Model ) - { - CG_RegisterClientRenderInfo( &ci, &ri ); - } - else - { - char skinName[MAX_QPATH]; - //precache ghoul2 model - gi.G2API_PrecacheGhoul2Model( va( "models/players/%s/model.glm", playerModel ) ); - //precache skin - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_%s.skin", playerModel, customSkin ); + if (md3Model) { + CG_RegisterClientRenderInfo(&ci, &ri); + } else { + char skinName[MAX_QPATH]; + // precache ghoul2 model + gi.G2API_PrecacheGhoul2Model(va("models/players/%s/model.glm", playerModel)); + // precache skin + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_%s.skin", playerModel, customSkin); // lets see if it's out there - gi.RE_RegisterSkin( skinName ); + gi.RE_RegisterSkin(skinName); } - //precache this NPC's possible weapons - NPC_PrecacheWeapons( playerTeam, spawner->spawnflags, spawner->NPC_type ); + // precache this NPC's possible weapons + NPC_PrecacheWeapons(playerTeam, spawner->spawnflags, spawner->NPC_type); - CG_RegisterNPCCustomSounds( &ci ); - CG_RegisterNPCEffects( playerTeam ); + CG_RegisterNPCCustomSounds(&ci); + CG_RegisterNPCEffects(playerTeam); - //FIXME: Look for a "sounds" directory and precache death, pain, alert sounds + // FIXME: Look for a "sounds" directory and precache death, pain, alert sounds } -void NPC_BuildRandom( gentity_t *NPC ) -{ - int sex, color, head; +void NPC_BuildRandom(gentity_t *NPC) { + int sex, color, head; sex = Q_irand(0, 2); color = Q_irand(0, 2); - switch( sex ) - { - case 0://female + switch (sex) { + case 0: // female head = Q_irand(0, 2); - switch( head ) - { + switch (head) { default: case 0: Q_strncpyz(NPC->client->renderInfo.headModelName, "garren", sizeof(NPC->client->renderInfo.headModelName)); @@ -983,11 +797,10 @@ void NPC_BuildRandom( gentity_t *NPC ) break; case 2: Q_strncpyz(NPC->client->renderInfo.headModelName, "garren/mackey", sizeof(NPC->client->renderInfo.headModelName)); - color = Q_irand(3, 5);//torso needs to be afam + color = Q_irand(3, 5); // torso needs to be afam break; } - switch( color ) - { + switch (color) { default: case 0: Q_strncpyz(NPC->client->renderInfo.torsoModelName, "crewfemale/gold", sizeof(NPC->client->renderInfo.torsoModelName)); @@ -1011,11 +824,10 @@ void NPC_BuildRandom( gentity_t *NPC ) Q_strncpyz(NPC->client->renderInfo.legsModelName, "crewfemale", sizeof(NPC->client->renderInfo.legsModelName)); break; default: - case 1://male - case 2://male + case 1: // male + case 2: // male head = Q_irand(0, 4); - switch( head ) - { + switch (head) { default: case 0: Q_strncpyz(NPC->client->renderInfo.headModelName, "chakotay/nelson", sizeof(NPC->client->renderInfo.headModelName)); @@ -1033,8 +845,7 @@ void NPC_BuildRandom( gentity_t *NPC ) Q_strncpyz(NPC->client->renderInfo.headModelName, "paris/kray", sizeof(NPC->client->renderInfo.headModelName)); break; } - switch( color ) - { + switch (color) { default: case 0: Q_strncpyz(NPC->client->renderInfo.torsoModelName, "crewthin/red", sizeof(NPC->client->renderInfo.torsoModelName)); @@ -1045,98 +856,93 @@ void NPC_BuildRandom( gentity_t *NPC ) case 2: Q_strncpyz(NPC->client->renderInfo.torsoModelName, "crewthin/blue", sizeof(NPC->client->renderInfo.torsoModelName)); break; - //NOTE: 3 - 5 should be red, gold & blue, afram hands + // NOTE: 3 - 5 should be red, gold & blue, afram hands } Q_strncpyz(NPC->client->renderInfo.legsModelName, "crewthin", sizeof(NPC->client->renderInfo.legsModelName)); break; } - NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = Q_irand(87, 102)/100.0f; + NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = Q_irand(87, 102) / 100.0f; NPC->NPC->rank = RANK_CREWMAN; NPC->client->playerTeam = TEAM_PLAYER; NPC->client->clientInfo.customBasicSoundDir = "kyle"; } -extern void G_SetG2PlayerModel( gentity_t * const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ); -qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) -{ - const char *token; - const char *value; - const char *p; - int n; - float f; - char *patch; - char sound[MAX_QPATH]; - char playerModel[MAX_QPATH]; - char customSkin[MAX_QPATH]; - clientInfo_t *ci = &NPC->client->clientInfo; - renderInfo_t *ri = &NPC->client->renderInfo; - gNPCstats_t *stats = NULL; - qboolean md3Model = qtrue; - char surfOff[1024]; - char surfOn[1024]; +extern void G_SetG2PlayerModel(gentity_t *const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn); +qboolean NPC_ParseParms(const char *NPCName, gentity_t *NPC) { + const char *token; + const char *value; + const char *p; + int n; + float f; + char *patch; + char sound[MAX_QPATH]; + char playerModel[MAX_QPATH]; + char customSkin[MAX_QPATH]; + clientInfo_t *ci = &NPC->client->clientInfo; + renderInfo_t *ri = &NPC->client->renderInfo; + gNPCstats_t *stats = NULL; + qboolean md3Model = qtrue; + char surfOff[1024]; + char surfOn[1024]; Q_strncpyz(customSkin, "default", sizeof(customSkin)); - if ( !NPCName || !NPCName[0]) - { + if (!NPCName || !NPCName[0]) { NPCName = "Player"; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats = &NPC->NPC->stats; -/* - NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; - NPC->NPC->allWeaponOrder[1] = WP_SABER; - NPC->NPC->allWeaponOrder[2] = WP_IMOD; - NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; - NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[7] = WP_NONE; -*/ + /* + NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; + NPC->NPC->allWeaponOrder[1] = WP_SABER; + NPC->NPC->allWeaponOrder[2] = WP_IMOD; + NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; + NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[7] = WP_NONE; + */ // fill in defaults - stats->aggression = 3; - stats->aim = 3; - stats->earshot = 1024; - stats->evasion = 3; - stats->hfov = 90; - stats->intelligence = 3; - stats->move = 3; - stats->reactions = 3; - stats->vfov = 60; - stats->vigilance = 0.1f; - stats->visrange = 1024; - - stats->health = 0; - - stats->moveType = MT_RUNJUMP; - stats->yawSpeed = 90; - stats->walkSpeed = 90; - stats->runSpeed = 300; - stats->acceleration = 15;//Increase/descrease speed this much per frame (20fps) - } - else - { + stats->aggression = 3; + stats->aim = 3; + stats->earshot = 1024; + stats->evasion = 3; + stats->hfov = 90; + stats->intelligence = 3; + stats->move = 3; + stats->reactions = 3; + stats->vfov = 60; + stats->vigilance = 0.1f; + stats->visrange = 1024; + + stats->health = 0; + + stats->moveType = MT_RUNJUMP; + stats->yawSpeed = 90; + stats->walkSpeed = 90; + stats->runSpeed = 300; + stats->acceleration = 15; // Increase/descrease speed this much per frame (20fps) + } else { stats = NULL; } - Q_strncpyz( ci->name, NPCName, sizeof( ci->name ) ); + Q_strncpyz(ci->name, NPCName, sizeof(ci->name)); NPC->playerModel = -1; - //Set defaults - //FIXME: should probably put default torso and head models, but what about enemies - //that don't have any- like Stasis? - //Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName)); - //Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName)); - //Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName)); - memset( ri->headModelName, 0, sizeof( ri->headModelName ) ); - memset( ri->torsoModelName, 0, sizeof( ri->torsoModelName ) ); - memset( ri->legsModelName, 0, sizeof( ri->legsModelName ) ); - //FIXME: should we have one for weapon too? - memset( (char *)surfOff, 0, sizeof(surfOff) ); - memset( (char *)surfOn, 0, sizeof(surfOn) ); + // Set defaults + // FIXME: should probably put default torso and head models, but what about enemies + // that don't have any- like Stasis? + // Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName)); + // Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName)); + // Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName)); + memset(ri->headModelName, 0, sizeof(ri->headModelName)); + memset(ri->torsoModelName, 0, sizeof(ri->torsoModelName)); + memset(ri->legsModelName, 0, sizeof(ri->legsModelName)); + // FIXME: should we have one for weapon too? + memset((char *)surfOff, 0, sizeof(surfOff)); + memset((char *)surfOn, 0, sizeof(surfOn)); /* ri->headYawRangeLeft = 50; @@ -1169,313 +975,245 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) NPC->client->dismemberProbWaist = 100; NPC->client->dismemberProbLegs = 100; - - if ( !Q_stricmp( "random", NPCName ) ) - {//Randomly assemble a starfleet guy - NPC_BuildRandom( NPC ); - } - else - { + if (!Q_stricmp("random", NPCName)) { // Randomly assemble a starfleet guy + NPC_BuildRandom(NPC); + } else { p = NPCParms; COM_BeginParseSession(); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { - COM_EndParseSession( ); + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, NPCName ) ) - { + if (!Q_stricmp(token, NPCName)) { break; } - SkipBracedSection( &p ); + SkipBracedSection(&p); } - if ( !p ) - { - COM_EndParseSession( ); + if (!p) { + COM_EndParseSession(); return qfalse; } - if ( G_ParseLiteral( &p, "{" ) ) - { - COM_EndParseSession( ); + if (G_ParseLiteral(&p, "{")) { + COM_EndParseSession(); return qfalse; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - gi.Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", NPCName ); - COM_EndParseSession( ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + gi.Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", NPCName); + COM_EndParseSession(); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - //===MODEL PROPERTIES=========================================================== + //===MODEL PROPERTIES=========================================================== // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { + if (!Q_stricmp("none", value)) { ri->headModelName[0] = '\0'; - //Zero the head clamp range so the torso & legs don't lag behind - ri->headYawRangeLeft = - ri->headYawRangeRight = - ri->headPitchRangeUp = - ri->headPitchRangeDown = 0; - } - else - { - Q_strncpyz( ri->headModelName, value, sizeof(ri->headModelName)); + // Zero the head clamp range so the torso & legs don't lag behind + ri->headYawRangeLeft = ri->headYawRangeRight = ri->headPitchRangeUp = ri->headPitchRangeDown = 0; + } else { + Q_strncpyz(ri->headModelName, value, sizeof(ri->headModelName)); } continue; } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { + if (!Q_stricmp("none", value)) { ri->torsoModelName[0] = '\0'; - //Zero the torso clamp range so the legs don't lag behind - ri->torsoYawRangeLeft = - ri->torsoYawRangeRight = - ri->torsoPitchRangeUp = - ri->torsoPitchRangeDown = 0; - } - else - { - Q_strncpyz( ri->torsoModelName, value, sizeof(ri->torsoModelName)); + // Zero the torso clamp range so the legs don't lag behind + ri->torsoYawRangeLeft = ri->torsoYawRangeRight = ri->torsoPitchRangeUp = ri->torsoPitchRangeDown = 0; + } else { + Q_strncpyz(ri->torsoModelName, value, sizeof(ri->torsoModelName)); } continue; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( ri->legsModelName, value, sizeof(ri->legsModelName)); - //Need to do this here to get the right index - G_ParseAnimFileSet( ri->legsModelName, ri->legsModelName, &ci->animFileIndex ); + Q_strncpyz(ri->legsModelName, value, sizeof(ri->legsModelName)); + // Need to do this here to get the right index + G_ParseAnimFileSet(ri->legsModelName, ri->legsModelName, &ci->animFileIndex); continue; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( playerModel, value, sizeof(playerModel)); + Q_strncpyz(playerModel, value, sizeof(playerModel)); md3Model = qfalse; continue; } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( customSkin, value, sizeof(customSkin)); + Q_strncpyz(customSkin, value, sizeof(customSkin)); continue; } // surfOff - if ( !Q_stricmp( token, "surfOff" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOff")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOff[0] ) - { - Q_strcat( surfOff, sizeof( surfOff ), "," ); - Q_strcat( surfOff, sizeof( surfOff ), value ); - } - else - { - Q_strncpyz( surfOff, value, sizeof(surfOff)); + if (surfOff[0]) { + Q_strcat(surfOff, sizeof(surfOff), ","); + Q_strcat(surfOff, sizeof(surfOff), value); + } else { + Q_strncpyz(surfOff, value, sizeof(surfOff)); } continue; } // surfOn - if ( !Q_stricmp( token, "surfOn" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOn")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOn[0] ) - { - Q_strcat( surfOn, sizeof( surfOn ), "," ); - Q_strcat( surfOn, sizeof( surfOn ), value ); - } - else - { - Q_strncpyz( surfOn, value, sizeof(surfOn)); + if (surfOn[0]) { + Q_strcat(surfOn, sizeof(surfOn), ","); + Q_strcat(surfOn, sizeof(surfOn), value); + } else { + Q_strncpyz(surfOn, value, sizeof(surfOn)); } continue; } - //headYawRangeLeft - if ( !Q_stricmp( token, "headYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeLeft + if (!Q_stricmp(token, "headYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeLeft = n; continue; } - //headYawRangeRight - if ( !Q_stricmp( token, "headYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeRight + if (!Q_stricmp(token, "headYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeRight = n; continue; } - //headPitchRangeUp - if ( !Q_stricmp( token, "headPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeUp + if (!Q_stricmp(token, "headPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeUp = n; continue; } - //headPitchRangeDown - if ( !Q_stricmp( token, "headPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeDown + if (!Q_stricmp(token, "headPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeDown = n; continue; } - //torsoYawRangeLeft - if ( !Q_stricmp( token, "torsoYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeLeft + if (!Q_stricmp(token, "torsoYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeLeft = n; continue; } - //torsoYawRangeRight - if ( !Q_stricmp( token, "torsoYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeRight + if (!Q_stricmp(token, "torsoYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeRight = n; continue; } - //torsoPitchRangeUp - if ( !Q_stricmp( token, "torsoPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeUp + if (!Q_stricmp(token, "torsoPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeUp = n; continue; } - //torsoPitchRangeDown - if ( !Q_stricmp( token, "torsoPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeDown + if (!Q_stricmp(token, "torsoPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeDown = n; @@ -1483,360 +1221,314 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // Uniform XYZ scale - if ( !Q_stricmp( token, "scale" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "scale")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = n / 100.0f; } continue; } - //X scale - if ( !Q_stricmp( token, "scaleX" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // X scale + if (!Q_stricmp(token, "scaleX")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[0] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[0] = n / 100.0f; } continue; } - //Y scale - if ( !Q_stricmp( token, "scaleY" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Y scale + if (!Q_stricmp(token, "scaleY")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[1] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[1] = n / 100.0f; } continue; } - //Z scale - if ( !Q_stricmp( token, "scaleZ" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Z scale + if (!Q_stricmp(token, "scaleZ")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->s.modelScale[2] = n/100.0f; + if (n != 100) { + NPC->s.modelScale[2] = n / 100.0f; } continue; } - //===AI STATS===================================================================== + //===AI STATS===================================================================== // aggression - if ( !Q_stricmp( token, "aggression" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aggression")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aggression = n; } continue; } // aim - if ( !Q_stricmp( token, "aim" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aim")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aim = n; } continue; } // earshot - if ( !Q_stricmp( token, "earshot" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "earshot")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->earshot = f; } continue; } // evasion - if ( !Q_stricmp( token, "evasion" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "evasion")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->evasion = n; } continue; } // hfov - if ( !Q_stricmp( token, "hfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "hfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 30 || n > 180 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 30 || n > 180) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - stats->hfov = n;// / 2; //FIXME: Why was this being done?! + if (NPC->NPC) { + stats->hfov = n; // / 2; //FIXME: Why was this being done?! } continue; } // intelligence - if ( !Q_stricmp( token, "intelligence" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "intelligence")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->intelligence = n; } continue; } // move - if ( !Q_stricmp( token, "move" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "move")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->move = n; } continue; } // reactions - if ( !Q_stricmp( token, "reactions" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "reactions")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->reactions = n; } continue; } // shootDistance - if ( !Q_stricmp( token, "saberColor" ) ) { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->ps.saberColor = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->ps.saberColor = TranslateSaberColor(value); } continue; } // shootDistance - if ( !Q_stricmp( token, "shootDistance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "shootDistance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->shootDistance = f; } continue; } // shootDistance - if ( !Q_stricmp( token, "health" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "health")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->health = n; } continue; } // vfov - if ( !Q_stricmp( token, "vfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 30 || n > 180 ) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 30 || n > 180) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vfov = n / 2; } continue; } // vigilance - if ( !Q_stricmp( token, "vigilance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vigilance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vigilance = f; } continue; } // visrange - if ( !Q_stricmp( token, "visrange" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "visrange")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->visrange = f; } continue; } // race - // if ( !Q_stricmp( token, "race" ) ) - // { - // if ( COM_ParseString( &p, &value ) ) - // { - // continue; - // } - // NPC->client->race = TranslateRaceName(value); - // continue; - // } + // if ( !Q_stricmp( token, "race" ) ) + // { + // if ( COM_ParseString( &p, &value ) ) + // { + // continue; + // } + // NPC->client->race = TranslateRaceName(value); + // continue; + // } // rank - if ( !Q_stricmp( token, "rank" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "rank")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->rank = TranslateRankName(value); } continue; } // fullName - if ( !Q_stricmp( token, "fullName" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "fullName")) { + if (COM_ParseString(&p, &value)) { continue; } NPC->fullName = G_NewString(value); @@ -1844,10 +1536,8 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerTeam")) { + if (COM_ParseString(&p, &value)) { continue; } NPC->client->playerTeam = TranslateTeamName(value); @@ -1855,10 +1545,8 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // enemyTeam - if ( !Q_stricmp( token, "enemyTeam" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "enemyTeam")) { + if (COM_ParseString(&p, &value)) { continue; } NPC->client->enemyTeam = TranslateTeamName(value); @@ -1866,10 +1554,8 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // class - if ( !Q_stricmp( token, "class" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "class")) { + if (COM_ParseString(&p, &value)) { continue; } NPC->client->NPC_class = TranslateClassName(value); @@ -1877,101 +1563,89 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // dismemberment probability for head - if ( !Q_stricmp( token, "dismemberProbHead" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHead")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbHead = n; } continue; } // dismemberment probability for arms - if ( !Q_stricmp( token, "dismemberProbArms" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbArms")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbArms = n; } continue; } // dismemberment probability for hands - if ( !Q_stricmp( token, "dismemberProbHands" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHands")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbHands = n; } continue; } // dismemberment probability for waist - if ( !Q_stricmp( token, "dismemberProbWaist" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbWaist")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbWaist = n; } continue; } // dismemberment probability for legs - if ( !Q_stricmp( token, "dismemberProbLegs" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbLegs")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->client->dismemberProbLegs = n; } continue; } - //===MOVEMENT STATS============================================================ + //===MOVEMENT STATS============================================================ - if ( !Q_stricmp( token, "width" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "width")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -1980,23 +1654,19 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !Q_stricmp( token, "height" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "height")) { + if (COM_ParseInt(&p, &n)) { continue; } - NPC->mins[2] = DEFAULT_MINS_2;//Cannot change + NPC->mins[2] = DEFAULT_MINS_2; // Cannot change NPC->maxs[2] = NPC->client->standheight = n + DEFAULT_MINS_2; NPC->radius = n; continue; } - if ( !Q_stricmp( token, "crouchheight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "crouchheight")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -2004,271 +1674,236 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !Q_stricmp( token, "movetype" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "movetype")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->moveType = (movetype_t)MoveTypeNameToEnum(value); } continue; } // yawSpeed - if ( !Q_stricmp( token, "yawSpeed" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "yawSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n <= 0) { - gi.Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n <= 0) { + gi.Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->yawSpeed = ((float)(n)); } continue; } // walkSpeed - if ( !Q_stricmp( token, "walkSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "walkSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->walkSpeed = n; } continue; } - //runSpeed - if ( !Q_stricmp( token, "runSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // runSpeed + if (!Q_stricmp(token, "runSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->runSpeed = n; } continue; } - //acceleration - if ( !Q_stricmp( token, "acceleration" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // acceleration + if (!Q_stricmp(token, "acceleration")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->acceleration = n; } continue; } - //===MISC=============================================================================== + //===MISC=============================================================================== // default behavior - if ( !Q_stricmp( token, "behavior" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "behavior")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < BS_DEFAULT || n >= NUM_BSTATES ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < BS_DEFAULT || n >= NUM_BSTATES) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->defaultBehavior = (bState_t)(n); } continue; } // snd - if ( !Q_stricmp( token, "snd" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customBasicSoundDir = G_NewString( sound ); + ci->customBasicSoundDir = G_NewString(sound); } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customCombatSoundDir = G_NewString( sound ); + ci->customCombatSoundDir = G_NewString(sound); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customExtraSoundDir = G_NewString( sound ); + ci->customExtraSoundDir = G_NewString(sound); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - ci->customJediSoundDir = G_NewString( sound ); + ci->customJediSoundDir = G_NewString(sound); } continue; } - gi.Printf( "WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName ); - SkipRestOfLine( &p ); + gi.Printf("WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName); + SkipRestOfLine(&p); } - COM_EndParseSession( ); + COM_EndParseSession(); } ci->infoValid = qfalse; -/* -Ghoul2 Insert Start -*/ - if ( !md3Model ) - { + /* + Ghoul2 Insert Start + */ + if (!md3Model) { NPC->weaponModel = -1; - G_SetG2PlayerModel( NPC, playerModel, customSkin, surfOff, surfOn ); + G_SetG2PlayerModel(NPC, playerModel, customSkin, surfOff, surfOn); } -/* -Ghoul2 Insert End -*/ - if( NPCsPrecached ) - {//Spawning in after initial precache, our models are precached, we just need to set our clientInfo - CG_RegisterClientModels( NPC->s.number ); - CG_RegisterNPCCustomSounds( ci ); - CG_RegisterNPCEffects( NPC->client->playerTeam ); + /* + Ghoul2 Insert End + */ + if (NPCsPrecached) { // Spawning in after initial precache, our models are precached, we just need to set our clientInfo + CG_RegisterClientModels(NPC->s.number); + CG_RegisterNPCCustomSounds(ci); + CG_RegisterNPCEffects(NPC->client->playerTeam); } return qtrue; } -void NPC_LoadParms( void ) -{ - int len, totallen, npcExtFNLen, mainBlockLen, fileCnt, i; - const char filename[] = "ext_data/NPCs.cfg"; - char *buffer, *holdChar, *marker; - char npcExtensionListBuf[2048]; // The list of file names read in - - //First, load in the npcs.cfg - len = gi.FS_ReadFile( filename, (void **) &buffer ); - if ( len == -1 ) { - gi.Printf( "file not found\n" ); +void NPC_LoadParms(void) { + int len, totallen, npcExtFNLen, mainBlockLen, fileCnt, i; + const char filename[] = "ext_data/NPCs.cfg"; + char *buffer, *holdChar, *marker; + char npcExtensionListBuf[2048]; // The list of file names read in + + // First, load in the npcs.cfg + len = gi.FS_ReadFile(filename, (void **)&buffer); + if (len == -1) { + gi.Printf("file not found\n"); return; } - if ( len >= MAX_NPC_DATA_SIZE ) { - G_Error( "ext_data/NPCs.cfg is too large" ); + if (len >= MAX_NPC_DATA_SIZE) { + G_Error("ext_data/NPCs.cfg is too large"); } - strncpy( NPCParms, buffer, sizeof( NPCParms ) - 1 ); - gi.FS_FreeFile( buffer ); + strncpy(NPCParms, buffer, sizeof(NPCParms) - 1); + gi.FS_FreeFile(buffer); - //remember where to store the next one + // remember where to store the next one totallen = mainBlockLen = len; - marker = NPCParms+totallen; + marker = NPCParms + totallen; - //now load in the extra .npc extensions - fileCnt = gi.FS_GetFileList("ext_data", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf) ); + // now load in the extra .npc extensions + fileCnt = gi.FS_GetFileList("ext_data", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf)); holdChar = npcExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1 ) - { - npcExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1) { + npcExtFNLen = strlen(holdChar); - len = gi.FS_ReadFile( va( "ext_data/%s", holdChar), (void **) &buffer ); + len = gi.FS_ReadFile(va("ext_data/%s", holdChar), (void **)&buffer); - if ( len == -1 ) - { - gi.Printf( "error reading file\n" ); - } - else - { - if ( totallen + len >= MAX_NPC_DATA_SIZE ) { - G_Error( "NPC extensions (*.npc) are too large" ); + if (len == -1) { + gi.Printf("error reading file\n"); + } else { + if (totallen + len >= MAX_NPC_DATA_SIZE) { + G_Error("NPC extensions (*.npc) are too large"); } - strcat( marker, buffer ); - gi.FS_FreeFile( buffer ); + strcat(marker, buffer); + gi.FS_FreeFile(buffer); totallen += len; - marker = NPCParms+totallen; + marker = NPCParms + totallen; } } } diff --git a/codeJK2/game/NPC_utils.cpp b/codeJK2/game/NPC_utils.cpp index da44b88c8b..cfd27a7650 100644 --- a/codeJK2/game/NPC_utils.cpp +++ b/codeJK2/game/NPC_utils.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_utils.cpp +// NPC_utils.cpp #include "g_headers.h" @@ -28,17 +28,17 @@ along with this program; if not, see . #include "g_icarus.h" #include "Q3_Interface.h" -extern int ICARUS_entFilter; -int teamNumbers[TEAM_NUM_TEAMS]; -int teamStrength[TEAM_NUM_TEAMS]; -int teamCounter[TEAM_NUM_TEAMS]; +extern int ICARUS_entFilter; +int teamNumbers[TEAM_NUM_TEAMS]; +int teamStrength[TEAM_NUM_TEAMS]; +int teamCounter[TEAM_NUM_TEAMS]; -#define VALID_ATTACK_CONE 2.0f //Degrees -void GetAnglesForDirection( const vec3_t p1, const vec3_t p2, vec3_t out ); -extern void Q3_DebugPrint( int level, const char *format, ... ); +#define VALID_ATTACK_CONE 2.0f // Degrees +void GetAnglesForDirection(const vec3_t p1, const vec3_t p2, vec3_t out); +extern void Q3_DebugPrint(int level, const char *format, ...); /* -void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) +void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) Added: Uses shootAngles if a NPC has them @@ -46,158 +46,130 @@ Added: Uses shootAngles if a NPC has them extern void ViewHeightFix(const gentity_t *const ent); extern void AddLeanOfs(const gentity_t *const ent, vec3_t point); extern void SubtractLeanOfs(const gentity_t *const ent, vec3_t point); -void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) -{ - vec3_t forward, up, right; - vec3_t start, end; - trace_t tr; +void CalcEntitySpot(const gentity_t *ent, const spot_t spot, vec3_t point) { + vec3_t forward, up, right; + vec3_t start, end; + trace_t tr; - if ( !ent ) - { + if (!ent) { return; } ViewHeightFix(ent); - switch ( spot ) - { + switch (spot) { case SPOT_ORIGIN: - if(VectorCompare(ent->currentOrigin, vec3_origin)) - {//brush - VectorSubtract(ent->absmax, ent->absmin, point);//size + if (VectorCompare(ent->currentOrigin, vec3_origin)) { // brush + VectorSubtract(ent->absmax, ent->absmin, point); // size VectorMA(ent->absmin, 0.5, point, point); - } - else - { - VectorCopy ( ent->currentOrigin, point ); + } else { + VectorCopy(ent->currentOrigin, point); } break; case SPOT_CHEST: case SPOT_HEAD: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && VectorLengthSquared(ent->client->renderInfo.eyePoint) && + (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; + } else if (!ent->s.number) { + SubtractLeanOfs(ent, point); } - else if ( !ent->s.number ) - { - SubtractLeanOfs( ent, point ); - } - } - else - { - VectorCopy ( ent->currentOrigin, point ); - if ( ent->client ) - { + } else { + VectorCopy(ent->currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } } - if ( spot == SPOT_CHEST && ent->client ) - { - if ( ent->client->NPC_class != CLASS_ATST ) - {//adjust up some - point[2] -= ent->maxs[2]*0.2f; + if (spot == SPOT_CHEST && ent->client) { + if (ent->client->NPC_class != CLASS_ATST) { // adjust up some + point[2] -= ent->maxs[2] * 0.2f; } } break; case SPOT_HEAD_LEAN: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) && (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && VectorLengthSquared(ent->client->renderInfo.eyePoint) && + (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; + } else if (!ent->s.number) { + SubtractLeanOfs(ent, point); } - else if ( !ent->s.number ) - { - SubtractLeanOfs( ent, point ); - } - //NOTE: automatically takes leaning into account! - } - else - { - VectorCopy ( ent->currentOrigin, point ); - if ( ent->client ) - { + // NOTE: automatically takes leaning into account! + } else { + VectorCopy(ent->currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } - //AddLeanOfs ( ent, point ); + // AddLeanOfs ( ent, point ); } break; - //FIXME: implement... - //case SPOT_CHEST: - //Returns point 3/4 from tag_torso to tag_head? - //break; + // FIXME: implement... + // case SPOT_CHEST: + // Returns point 3/4 from tag_torso to tag_head? + // break; case SPOT_LEGS: - VectorCopy ( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); point[2] += (ent->mins[2] * 0.5); break; case SPOT_WEAPON: - if( ent->NPC && !VectorCompare( ent->NPC->shootAngles, vec3_origin ) && !VectorCompare( ent->NPC->shootAngles, ent->client->ps.viewangles )) - { - AngleVectors( ent->NPC->shootAngles, forward, right, up ); - } - else - { - AngleVectors( ent->client->ps.viewangles, forward, right, up ); + if (ent->NPC && !VectorCompare(ent->NPC->shootAngles, vec3_origin) && !VectorCompare(ent->NPC->shootAngles, ent->client->ps.viewangles)) { + AngleVectors(ent->NPC->shootAngles, forward, right, up); + } else { + AngleVectors(ent->client->ps.viewangles, forward, right, up); } - CalcMuzzlePoint( (gentity_t*)ent, forward, right, up, point, 0 ); - //NOTE: automatically takes leaning into account! + CalcMuzzlePoint((gentity_t *)ent, forward, right, up, point, 0); + // NOTE: automatically takes leaning into account! break; case SPOT_GROUND: // if entity is on the ground, just use it's absmin - if ( ent->s.groundEntityNum != -1 ) - { - VectorCopy( ent->currentOrigin, point ); + if (ent->s.groundEntityNum != -1) { + VectorCopy(ent->currentOrigin, point); point[2] = ent->absmin[2]; break; } // if it is reasonably close to the ground, give the point underneath of it - VectorCopy( ent->currentOrigin, start ); + VectorCopy(ent->currentOrigin, start); start[2] = ent->absmin[2]; - VectorCopy( start, end ); + VectorCopy(start, end); end[2] -= 64; - gi.trace( &tr, start, ent->mins, ent->maxs, end, ent->s.number, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); - if ( tr.fraction < 1.0 ) - { - VectorCopy( tr.endpos, point); + gi.trace(&tr, start, ent->mins, ent->maxs, end, ent->s.number, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); + if (tr.fraction < 1.0) { + VectorCopy(tr.endpos, point); break; } // otherwise just use the origin - VectorCopy( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); break; default: - VectorCopy ( ent->currentOrigin, point ); + VectorCopy(ent->currentOrigin, point); break; } } - //=================================================================================== /* -qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) +qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) Added: option to do just pitch or just yaw @@ -205,186 +177,155 @@ Does not include "aim" in it's calculations FIXME: stop compressing angles into shorts!!!! */ -extern cvar_t *g_timescale; -qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) -{ +extern cvar_t *g_timescale; +qboolean NPC_UpdateAngles(qboolean doPitch, qboolean doYaw) { #if 1 - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - qboolean exact = qtrue; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the existing render flag... - dmv - if ( !NPC->enemy && ( (level.time < NPCInfo->aimTime) || NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE) ) - { - if(doPitch) + // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the + // existing render flag... - dmv + if (!NPC->enemy && ((level.time < NPCInfo->aimTime) || NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE)) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { + } else { // we're changing the lockedDesired Pitch/Yaw below so it's lost it's original meaning, get rid of the lock flag NPC->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; - if(doPitch) - { + if (doPitch) { targetPitch = NPCInfo->desiredPitch; NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; } - if(doYaw) - { + if (doYaw) { targetYaw = NPCInfo->desiredYaw; NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; - } + } } - if ( NPC->s.weapon == WP_EMPLACED_GUN ) - { + if (NPC->s.weapon == WP_EMPLACED_GUN) { // FIXME: this seems to do nothing, actually... yawSpeed = 20; - } - else - { + } else { yawSpeed = NPCInfo->stats.yawSpeed; } - if ( NPC->s.weapon == WP_SABER && NPC->client->ps.forcePowersActive&(1<value; + if (NPC->s.weapon == WP_SABER && NPC->client->ps.forcePowersActive & (1 << FP_SPEED)) { + yawSpeed *= 1.0f / g_timescale->value; } - - if( doYaw ) - { + + if (doYaw) { // decay yaw error - error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; + + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if( doPitch ) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; - if ( exact && Q3_TaskIDPending( NPC, TID_ANGLE_FACE ) ) - { - Q3_TaskIDComplete( NPC, TID_ANGLE_FACE ); + if (exact && Q3_TaskIDPending(NPC, TID_ANGLE_FACE)) { + Q3_TaskIDComplete(NPC, TID_ANGLE_FACE); } return exact; #else - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - //float runningMod = NPCInfo->currentSpeed/100.0f; - qboolean exact = qtrue; - qboolean doSound = qfalse; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + // float runningMod = NPCInfo->currentSpeed/100.0f; + qboolean exact = qtrue; + qboolean doSound = qfalse; // if angle changes are locked; just keep the current angles - if ( level.time < NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } yawSpeed = NPCInfo->stats.yawSpeed; - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) {//HACK - borg turn more jittery - if ( error ) + if ( error ) { exact = qfalse; @@ -399,18 +340,18 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } } - if ( error < 0.0)//-10.0 ) + if ( error < 0.0)//-10.0 ) { error += decay; - if ( error > 0.0 ) + if ( error > 0.0 ) { error = 0.0; } } - else if ( error > 0.0)//10.0 ) + else if ( error > 0.0)//10.0 ) { error -= decay; - if ( error < 0.0 ) + if ( error < 0.0 ) { error = 0.0; } @@ -418,47 +359,39 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } } else*/ - - if ( error ) - { + + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if(doPitch) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) {//HACK - borg turn more jittery - if ( error ) + if ( error ) { exact = qfalse; @@ -473,18 +406,18 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } } - if ( error < 0.0)//-10.0 ) + if ( error < 0.0)//-10.0 ) { error += decay; - if ( error > 0.0 ) + if ( error > 0.0 ) { error = 0.0; } } - else if ( error > 0.0)//10.0 ) + else if ( error > 0.0)//10.0 ) { error -= decay; - if ( error < 0.0 ) + if ( error < 0.0 ) { error = 0.0; } @@ -492,36 +425,30 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } } else*/ - - if ( error ) - { + + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; /* if(doSound) @@ -533,32 +460,27 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) return exact; #endif - } -void NPC_AimWiggle( vec3_t enemy_org ) -{ - //shoot for somewhere between the head and torso - //NOTE: yes, I know this looks weird, but it works - if ( NPCInfo->aimErrorDebounceTime < level.time ) - { - NPCInfo->aimOfs[0] = 0.3*Q_flrand(NPC->enemy->mins[0], NPC->enemy->maxs[0]); - NPCInfo->aimOfs[1] = 0.3*Q_flrand(NPC->enemy->mins[1], NPC->enemy->maxs[1]); - if ( NPC->enemy->maxs[2] > 0 ) - { - NPCInfo->aimOfs[2] = NPC->enemy->maxs[2]*Q_flrand(0.0f, -1.0f); +void NPC_AimWiggle(vec3_t enemy_org) { + // shoot for somewhere between the head and torso + // NOTE: yes, I know this looks weird, but it works + if (NPCInfo->aimErrorDebounceTime < level.time) { + NPCInfo->aimOfs[0] = 0.3 * Q_flrand(NPC->enemy->mins[0], NPC->enemy->maxs[0]); + NPCInfo->aimOfs[1] = 0.3 * Q_flrand(NPC->enemy->mins[1], NPC->enemy->maxs[1]); + if (NPC->enemy->maxs[2] > 0) { + NPCInfo->aimOfs[2] = NPC->enemy->maxs[2] * Q_flrand(0.0f, -1.0f); } } - VectorAdd( enemy_org, NPCInfo->aimOfs, enemy_org ); + VectorAdd(enemy_org, NPCInfo->aimOfs, enemy_org); } /* -qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) +qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) Includes aim when determining angles - so they don't always hit... */ -qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) -{ +qboolean NPC_UpdateFiringAngles(qboolean doPitch, qboolean doYaw) { #if 0 @@ -623,79 +545,66 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; return exact; - + #else - float error, diff; - float decay; - float targetPitch = 0; - float targetYaw = 0; - qboolean exact = qtrue; + float error, diff; + float decay; + float targetPitch = 0; + float targetYaw = 0; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - if ( level.time < NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } - if ( NPCInfo->aimErrorDebounceTime < level.time ) - { - if ( Q_irand(0, 1 ) ) - { + if (NPCInfo->aimErrorDebounceTime < level.time) { + if (Q_irand(0, 1)) { NPCInfo->lastAimErrorYaw = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } - if ( Q_irand(0, 1 ) ) - { + if (Q_irand(0, 1)) { NPCInfo->lastAimErrorPitch = ((float)(6 - NPCInfo->stats.aim)) * Q_flrand(-1, 1); } NPCInfo->aimErrorDebounceTime = level.time + Q_irand(250, 2000); } - if(doYaw) - { + if (doYaw) { // decay yaw diff - diff = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - - if ( diff) - { + diff = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } } - + // add yaw error based on NPCInfo->aim value error = NPCInfo->lastAimErrorYaw; @@ -706,91 +615,74 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) } */ - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + diff + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + diff + error) - client->ps.delta_angles[YAW]; } - if(doPitch) - { + if (doPitch) { // decay pitch diff - diff = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( diff) - { + diff = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } } - + error = NPCInfo->lastAimErrorPitch; - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + diff + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + diff + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; return exact; #endif - } //=================================================================================== /* -static void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) +static void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) Does update angles on shootAngles */ -void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) -{//FIXME: shoot angles either not set right or not used! - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; +void NPC_UpdateShootAngles(vec3_t angles, qboolean doPitch, qboolean doYaw) { // FIXME: shoot angles either not set right or not used! + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; - if(doPitch) + if (doPitch) targetPitch = angles[PITCH]; - if(doYaw) + if (doYaw) targetYaw = angles[YAW]; - - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPCInfo->shootAngles[YAW], targetYaw ); - if ( error ) - { + error = AngleDelta(NPCInfo->shootAngles[YAW], targetYaw); + if (error) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -798,27 +690,20 @@ void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) NPCInfo->shootAngles[YAW] = targetYaw + error; } - if(doPitch) - { + if (doPitch) { // decay pitch error - error = AngleDelta ( NPCInfo->shootAngles[PITCH], targetPitch ); - if ( error ) - { + error = AngleDelta(NPCInfo->shootAngles[PITCH], targetPitch); + if (error) { decay = 60.0 + 80.0 * NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -835,24 +720,20 @@ Sets the number of living clients on each team FIXME: Does not account for non-respawned players! FIXME: Don't include medics? */ -void SetTeamNumbers (void) -{ - gentity_t *found; - int i; +void SetTeamNumbers(void) { + gentity_t *found; + int i; - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - { + for (i = 0; i < TEAM_NUM_TEAMS; i++) { teamNumbers[i] = 0; teamStrength[i] = 0; } - for( i = 0; i < 1 ; i++ ) - { + for (i = 0; i < 1; i++) { found = &g_entities[i]; - if( found->client ) - { - if( found->health > 0 )//FIXME: or if a player! + if (found->client) { + if (found->health > 0) // FIXME: or if a player! { teamNumbers[found->client->playerTeam]++; teamStrength[found->client->playerTeam] += found->health; @@ -860,59 +741,49 @@ void SetTeamNumbers (void) } } - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - {//Get the average health - teamStrength[i] = floor( ((float)(teamStrength[i])) / ((float)(teamNumbers[i])) ); + for (i = 0; i < TEAM_NUM_TEAMS; i++) { // Get the average health + teamStrength[i] = floor(((float)(teamStrength[i])) / ((float)(teamNumbers[i]))); } } extern stringID_table_t BSTable[]; extern stringID_table_t BSETTable[]; -qboolean G_ActivateBehavior (gentity_t *self, int bset ) -{ - bState_t bSID = (bState_t)-1; +qboolean G_ActivateBehavior(gentity_t *self, int bset) { + bState_t bSID = (bState_t)-1; char *bs_name = NULL; - if ( !self ) - { + if (!self) { return qfalse; } bs_name = self->behaviorSet[bset]; - - if( !(VALIDSTRING( bs_name )) ) - { + + if (!(VALIDSTRING(bs_name))) { return qfalse; } - if ( self->NPC ) - { - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); + if (self->NPC) { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); } - if(bSID != (bState_t)-1) - { + if (bSID != (bState_t)-1) { self->NPC->tempBehavior = BS_DEFAULT; self->NPC->behaviorState = bSID; - } - else - { + } else { /* - char newname[MAX_FILENAME_LENGTH]; + char newname[MAX_FILENAME_LENGTH]; sprintf((char *) &newname, "%s/%s", Q3_SCRIPT_DIR, bs_name ); */ - - //FIXME: between here and actually getting into the ICARUS_RunScript function, the stack gets blown! - if ( ( ICARUS_entFilter == -1 ) || ( ICARUS_entFilter == self->s.number ) ) - { - Q3_DebugPrint( WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID( BSETTable, bset ), bs_name ); + + // FIXME: between here and actually getting into the ICARUS_RunScript function, the stack gets blown! + if ((ICARUS_entFilter == -1) || (ICARUS_entFilter == self->s.number)) { + Q3_DebugPrint(WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID(BSETTable, bset), bs_name); } - ICARUS_RunScript( self, va( "%s/%s", Q3_SCRIPT_DIR, bs_name ) ); + ICARUS_RunScript(self, va("%s/%s", Q3_SCRIPT_DIR, bs_name)); } return qtrue; } - /* ============================================================================= @@ -921,61 +792,52 @@ qboolean G_ActivateBehavior (gentity_t *self, int bset ) ============================================================================= */ - /* ------------------------- NPC_ValidEnemy ------------------------- */ -qboolean NPC_ValidEnemy( gentity_t *ent ) -{ - //Must be a valid pointer - if ( ent == NULL ) +qboolean NPC_ValidEnemy(gentity_t *ent) { + // Must be a valid pointer + if (ent == NULL) return qfalse; - //Must not be me - if ( ent == NPC ) + // Must not be me + if (ent == NPC) return qfalse; - //Must not be deleted - if ( ent->inuse == qfalse ) + // Must not be deleted + if (ent->inuse == qfalse) return qfalse; - //Must be alive - if ( ent->health <= 0 ) + // Must be alive + if (ent->health <= 0) return qfalse; - //In case they're in notarget mode - if ( ent->flags & FL_NOTARGET ) + // In case they're in notarget mode + if (ent->flags & FL_NOTARGET) return qfalse; - //Must be an NPC - if ( ent->client == NULL ) - { - if ( ent->svFlags&SVF_NONNPC_ENEMY ) - {//still potentially valid - if ( ent->noDamageTeam == NPC->client->playerTeam ) - { + // Must be an NPC + if (ent->client == NULL) { + if (ent->svFlags & SVF_NONNPC_ENEMY) { // still potentially valid + if (ent->noDamageTeam == NPC->client->playerTeam) { return qfalse; - } - else - { + } else { return qtrue; } - } - else - { + } else { return qfalse; } } - //Can't be on the same team - if ( ent->client->playerTeam == NPC->client->playerTeam ) + // Can't be on the same team + if (ent->client->playerTeam == NPC->client->playerTeam) return qfalse; - //if haven't seen him in a while, give up - //if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? + // if haven't seen him in a while, give up + // if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? // return qfalse; return qtrue; @@ -987,18 +849,17 @@ NPC_TargetVisible ------------------------- */ -qboolean NPC_TargetVisible( gentity_t *ent ) -{ - //Make sure we're in a valid range - if ( DistanceSquared( ent->currentOrigin, NPC->currentOrigin ) > ( NPCInfo->stats.visrange * NPCInfo->stats.visrange ) ) +qboolean NPC_TargetVisible(gentity_t *ent) { + // Make sure we're in a valid range + if (DistanceSquared(ent->currentOrigin, NPC->currentOrigin) > (NPCInfo->stats.visrange * NPCInfo->stats.visrange)) return qfalse; - //Check our FOV - if ( InFOV( ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Check our FOV + if (InFOV(ent, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - //Check for sight - if ( NPC_ClearLOS( ent ) == qfalse ) + // Check for sight + if (NPC_ClearLOS(ent) == qfalse) return qfalse; return qtrue; @@ -1035,49 +896,45 @@ NPC_FindNearestEnemy ------------------------- */ -#define MAX_RADIUS_ENTS 256 //NOTE: This can cause entities to be lost -#define NEAR_DEFAULT_RADIUS 256 +#define MAX_RADIUS_ENTS 256 // NOTE: This can cause entities to be lost +#define NEAR_DEFAULT_RADIUS 256 -int NPC_FindNearestEnemy( gentity_t *ent ) -{ - gentity_t *radiusEnts[ MAX_RADIUS_ENTS ]; - vec3_t mins, maxs; - int nearestEntID = -1; - float nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - float distance; - int numEnts, numChecks = 0; - int i; - - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { +int NPC_FindNearestEnemy(gentity_t *ent) { + gentity_t *radiusEnts[MAX_RADIUS_ENTS]; + vec3_t mins, maxs; + int nearestEntID = -1; + float nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + float distance; + int numEnts, numChecks = 0; + int i; + + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = ent->currentOrigin[i] - NPCInfo->stats.visrange; maxs[i] = ent->currentOrigin[i] + NPCInfo->stats.visrange; } - //Get a number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get a number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - for ( i = 0; i < numEnts; i++ ) - { - //Don't consider self - if ( radiusEnts[i] == ent ) + for (i = 0; i < numEnts; i++) { + // Don't consider self + if (radiusEnts[i] == ent) continue; - //Must be valid - if ( NPC_ValidEnemy( radiusEnts[i] ) == qfalse ) + // Must be valid + if (NPC_ValidEnemy(radiusEnts[i]) == qfalse) continue; numChecks++; - //Must be visible - if ( NPC_TargetVisible( radiusEnts[i] ) == qfalse ) + // Must be visible + if (NPC_TargetVisible(radiusEnts[i]) == qfalse) continue; - distance = DistanceSquared( ent->currentOrigin, radiusEnts[i]->currentOrigin ); + distance = DistanceSquared(ent->currentOrigin, radiusEnts[i]->currentOrigin); - //Found one closer to us - if ( distance < nearestDist ) - { + // Found one closer to us + if (distance < nearestDist) { nearestEntID = radiusEnts[i]->s.number; nearestDist = distance; } @@ -1092,36 +949,32 @@ NPC_PickEnemyExt ------------------------- */ -gentity_t *NPC_PickEnemyExt( qboolean checkAlerts = qfalse ) -{ - //If we've asked for the closest enemy - int entID = NPC_FindNearestEnemy( NPC ); +gentity_t *NPC_PickEnemyExt(qboolean checkAlerts = qfalse) { + // If we've asked for the closest enemy + int entID = NPC_FindNearestEnemy(NPC); - //If we have a valid enemy, use it - if ( entID >= 0 ) + // If we have a valid enemy, use it + if (entID >= 0) return &g_entities[entID]; - if ( checkAlerts ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); + if (checkAlerts) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { alertEvent_t *event = &level.alertEvents[alertEvent]; - //Don't pay attention to our own alerts - if ( event->owner == NPC ) + // Don't pay attention to our own alerts + if (event->owner == NPC) return NULL; - if ( event->level >= AEL_DISCOVERED ) - { - //If it's the player, attack him - if ( event->owner == &g_entities[0] ) + if (event->level >= AEL_DISCOVERED) { + // If it's the player, attack him + if (event->owner == &g_entities[0]) return event->owner; - //If it's on our team, then take its enemy as well - if ( ( event->owner->client ) && ( event->owner->client->playerTeam == NPC->client->playerTeam ) ) + // If it's on our team, then take its enemy as well + if ((event->owner->client) && (event->owner->client->playerTeam == NPC->client->playerTeam)) return event->owner->enemy; } } @@ -1136,10 +989,7 @@ NPC_FindPlayer ------------------------- */ -qboolean NPC_FindPlayer( void ) -{ - return NPC_TargetVisible( &g_entities[0] ); -} +qboolean NPC_FindPlayer(void) { return NPC_TargetVisible(&g_entities[0]); } /* ------------------------- @@ -1147,29 +997,27 @@ NPC_CheckPlayerDistance ------------------------- */ -static qboolean NPC_CheckPlayerDistance( void ) -{ - //Make sure we have an enemy - if ( NPC->enemy == NULL ) +static qboolean NPC_CheckPlayerDistance(void) { + // Make sure we have an enemy + if (NPC->enemy == NULL) return qfalse; - //Only do this for non-players - if ( NPC->enemy->s.number == 0 ) + // Only do this for non-players + if (NPC->enemy->s.number == 0) return qfalse; - //must be set up to get mad at player - if ( !NPC->client || NPC->client->enemyTeam != TEAM_PLAYER ) + // must be set up to get mad at player + if (!NPC->client || NPC->client->enemyTeam != TEAM_PLAYER) return qfalse; - //Must be within our FOV - if ( InFOV( &g_entities[0], NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ) == qfalse ) + // Must be within our FOV + if (InFOV(&g_entities[0], NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov) == qfalse) return qfalse; - float distance = DistanceSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); + float distance = DistanceSquared(NPC->currentOrigin, NPC->enemy->currentOrigin); - if ( distance > DistanceSquared( NPC->currentOrigin, g_entities[0].currentOrigin ) ) - { - G_SetEnemy( NPC, &g_entities[0] ); + if (distance > DistanceSquared(NPC->currentOrigin, g_entities[0].currentOrigin)) { + G_SetEnemy(NPC, &g_entities[0]); return qtrue; } @@ -1182,44 +1030,39 @@ NPC_FindEnemy ------------------------- */ -qboolean NPC_FindEnemy( qboolean checkAlerts = qfalse ) -{ - //We're ignoring all enemies for now - if( NPC->svFlags & SVF_IGNORE_ENEMIES ) - { - G_ClearEnemy( NPC ); +qboolean NPC_FindEnemy(qboolean checkAlerts = qfalse) { + // We're ignoring all enemies for now + if (NPC->svFlags & SVF_IGNORE_ENEMIES) { + G_ClearEnemy(NPC); return qfalse; } - //we can't pick up any enemies for now - if( NPCInfo->confusionTime > level.time ) - { + // we can't pick up any enemies for now + if (NPCInfo->confusionTime > level.time) { return qfalse; } - //Don't want a new enemy - if ( ( ValidEnemy( NPC->enemy ) ) && ( NPC->svFlags & SVF_LOCKEDENEMY ) ) + // Don't want a new enemy + if ((ValidEnemy(NPC->enemy)) && (NPC->svFlags & SVF_LOCKEDENEMY)) return qtrue; - //See if the player is closer than our current enemy - if ( NPC_CheckPlayerDistance() ) - { + // See if the player is closer than our current enemy + if (NPC_CheckPlayerDistance()) { return qtrue; } - //Otherwise, turn off the flag + // Otherwise, turn off the flag NPC->svFlags &= ~SVF_LOCKEDENEMY; - //If we've gotten here alright, then our target it still valid - if ( NPC_ValidEnemy( NPC->enemy ) ) + // If we've gotten here alright, then our target it still valid + if (NPC_ValidEnemy(NPC->enemy)) return qtrue; - gentity_t *newenemy = NPC_PickEnemyExt( checkAlerts ); + gentity_t *newenemy = NPC_PickEnemyExt(checkAlerts); - //if we found one, take it as the enemy - if( NPC_ValidEnemy( newenemy ) ) - { - G_SetEnemy( NPC, newenemy ); + // if we found one, take it as the enemy + if (NPC_ValidEnemy(newenemy)) { + G_SetEnemy(NPC, newenemy); return qtrue; } @@ -1232,20 +1075,19 @@ NPC_CheckEnemyExt ------------------------- */ -qboolean NPC_CheckEnemyExt( qboolean checkAlerts ) -{ - //Make sure we're ready to think again -/* - if ( NPCInfo->enemyCheckDebounceTime > level.time ) - return qfalse; +qboolean NPC_CheckEnemyExt(qboolean checkAlerts) { + // Make sure we're ready to think again + /* + if ( NPCInfo->enemyCheckDebounceTime > level.time ) + return qfalse; - //Get our next think time - NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); + //Get our next think time + NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); - //Attempt to find an enemy - return NPC_FindEnemy(); -*/ - return NPC_FindEnemy( checkAlerts ); + //Attempt to find an enemy + return NPC_FindEnemy(); + */ + return NPC_FindEnemy(checkAlerts); } /* @@ -1254,53 +1096,47 @@ NPC_FacePosition ------------------------- */ -qboolean NPC_FacePosition( vec3_t position, qboolean doPitch ) -{ - vec3_t muzzle; - qboolean facing = qtrue; +qboolean NPC_FacePosition(vec3_t position, qboolean doPitch) { + vec3_t muzzle; + qboolean facing = qtrue; - //Get the positions - if ( NPC->client && NPC->client->NPC_class == CLASS_GALAKMECH ) - { - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - } - else - { - CalcEntitySpot( NPC, SPOT_HEAD_LEAN, muzzle );//SPOT_HEAD + // Get the positions + if (NPC->client && NPC->client->NPC_class == CLASS_GALAKMECH) { + CalcEntitySpot(NPC, SPOT_WEAPON, muzzle); + } else { + CalcEntitySpot(NPC, SPOT_HEAD_LEAN, muzzle); // SPOT_HEAD } - //Find the desired angles - vec3_t angles; + // Find the desired angles + vec3_t angles; - GetAnglesForDirection( muzzle, position, angles ); + GetAnglesForDirection(muzzle, position, angles); - NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); - if ( NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_ATST ) - { + if (NPC->enemy && NPC->enemy->client && NPC->enemy->client->NPC_class == CLASS_ATST) { // FIXME: this is kind of dumb, but it was the easiest way to get it to look sort of ok - NPCInfo->desiredYaw += Q_flrand( -5, 5 ) + sin( level.time * 0.004f ) * 7; - NPCInfo->desiredPitch += Q_flrand( -2, 2 ); + NPCInfo->desiredYaw += Q_flrand(-5, 5) + sin(level.time * 0.004f) * 7; + NPCInfo->desiredPitch += Q_flrand(-2, 2); } - //Face that yaw - NPC_UpdateAngles( qtrue, qtrue ); - - //Find the delta between our goal and our current facing - float yawDelta = AngleNormalize360( NPCInfo->desiredYaw - ( SHORT2ANGLE( ucmd.angles[YAW] + client->ps.delta_angles[YAW] ) ) ); - - //See if we are facing properly - if ( fabs( yawDelta ) > VALID_ATTACK_CONE ) + // Face that yaw + NPC_UpdateAngles(qtrue, qtrue); + + // Find the delta between our goal and our current facing + float yawDelta = AngleNormalize360(NPCInfo->desiredYaw - (SHORT2ANGLE(ucmd.angles[YAW] + client->ps.delta_angles[YAW]))); + + // See if we are facing properly + if (fabs(yawDelta) > VALID_ATTACK_CONE) facing = qfalse; - if ( doPitch ) - { - //Find the delta between our goal and our current facing - float currentAngles = ( SHORT2ANGLE( ucmd.angles[PITCH] + client->ps.delta_angles[PITCH] ) ); + if (doPitch) { + // Find the delta between our goal and our current facing + float currentAngles = (SHORT2ANGLE(ucmd.angles[PITCH] + client->ps.delta_angles[PITCH])); float pitchDelta = NPCInfo->desiredPitch - currentAngles; - - //See if we are facing properly - if ( fabs( pitchDelta ) > VALID_ATTACK_CONE ) + + // See if we are facing properly + if (fabs(pitchDelta) > VALID_ATTACK_CONE) facing = qfalse; } @@ -1313,14 +1149,13 @@ NPC_FaceEntity ------------------------- */ -qboolean NPC_FaceEntity( gentity_t *ent, qboolean doPitch ) -{ - vec3_t entPos; +qboolean NPC_FaceEntity(gentity_t *ent, qboolean doPitch) { + vec3_t entPos; - //Get the positions - CalcEntitySpot( ent, SPOT_HEAD_LEAN, entPos ); + // Get the positions + CalcEntitySpot(ent, SPOT_HEAD_LEAN, entPos); - return NPC_FacePosition( entPos, doPitch ); + return NPC_FacePosition(entPos, doPitch); } /* @@ -1329,15 +1164,14 @@ NPC_FaceEnemy ------------------------- */ -qboolean NPC_FaceEnemy( qboolean doPitch ) -{ - if ( NPC == NULL ) +qboolean NPC_FaceEnemy(qboolean doPitch) { + if (NPC == NULL) return qfalse; - if ( NPC->enemy == NULL ) + if (NPC->enemy == NULL) return qfalse; - return NPC_FaceEntity( NPC->enemy, doPitch ); + return NPC_FaceEntity(NPC->enemy, doPitch); } /* @@ -1346,18 +1180,17 @@ NPC_CheckCanAttackExt ------------------------- */ -qboolean NPC_CheckCanAttackExt( void ) -{ - //We don't want them to shoot - if( NPCInfo->scriptFlags & SCF_DONT_FIRE ) +qboolean NPC_CheckCanAttackExt(void) { + // We don't want them to shoot + if (NPCInfo->scriptFlags & SCF_DONT_FIRE) return qfalse; - //Turn to face - if ( NPC_FaceEnemy( qtrue ) == qfalse ) + // Turn to face + if (NPC_FaceEnemy(qtrue) == qfalse) return qfalse; - //Must have a clear line of sight to the target - if ( NPC_ClearShot( NPC->enemy ) == qfalse ) + // Must have a clear line of sight to the target + if (NPC_ClearShot(NPC->enemy) == qfalse) return qfalse; return qtrue; @@ -1369,14 +1202,12 @@ NPC_ClearLookTarget ------------------------- */ -void NPC_ClearLookTarget( gentity_t *self ) -{ - if ( !self->client ) - { +void NPC_ClearLookTarget(gentity_t *self) { + if (!self->client) { return; } - self->client->renderInfo.lookTarget = ENTITYNUM_NONE;//ENTITYNUM_WORLD; + self->client->renderInfo.lookTarget = ENTITYNUM_NONE; // ENTITYNUM_WORLD; self->client->renderInfo.lookTargetClearTime = 0; } @@ -1385,10 +1216,8 @@ void NPC_ClearLookTarget( gentity_t *self ) NPC_SetLookTarget ------------------------- */ -void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) -{ - if ( !self->client ) - { +void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime) { + if (!self->client) { return; } @@ -1401,26 +1230,19 @@ void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) NPC_CheckLookTarget ------------------------- */ -qboolean NPC_CheckLookTarget( gentity_t *self ) -{ - if ( self->client ) - { - if ( self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - {//within valid range - if ( (&g_entities[self->client->renderInfo.lookTarget] == NULL) || !g_entities[self->client->renderInfo.lookTarget].inuse ) - {//lookTarget not inuse or not valid anymore - NPC_ClearLookTarget( self ); - } - else if ( self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time ) - {//Time to clear lookTarget - NPC_ClearLookTarget( self ); - } - else if ( g_entities[self->client->renderInfo.lookTarget].client && self->enemy && (&g_entities[self->client->renderInfo.lookTarget] != self->enemy) ) - {//should always look at current enemy if engaged in battle... FIXME: this could override certain scripted lookTargets...??? - NPC_ClearLookTarget( self ); - } - else - { +qboolean NPC_CheckLookTarget(gentity_t *self) { + if (self->client) { + if (self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { // within valid range + if ((&g_entities[self->client->renderInfo.lookTarget] == NULL) || + !g_entities[self->client->renderInfo.lookTarget].inuse) { // lookTarget not inuse or not valid anymore + NPC_ClearLookTarget(self); + } else if (self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time) { // Time to clear lookTarget + NPC_ClearLookTarget(self); + } else if (g_entities[self->client->renderInfo.lookTarget].client && self->enemy && + (&g_entities[self->client->renderInfo.lookTarget] != self->enemy)) { // should always look at current enemy if engaged in battle... + // FIXME: this could override certain scripted lookTargets...??? + NPC_ClearLookTarget(self); + } else { return qtrue; } } @@ -1434,25 +1256,20 @@ qboolean NPC_CheckLookTarget( gentity_t *self ) NPC_CheckCharmed ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -void NPC_CheckCharmed( void ) -{ - if ( NPC->client->playerTeam == TEAM_PLAYER && NPCInfo->charmedTime && NPCInfo->charmedTime < level.time && NPC->client ) - {//we were charmed, set us back! - //NOTE: presumptions here... - team_t savTeam = NPC->client->enemyTeam; +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +void NPC_CheckCharmed(void) { + if (NPC->client->playerTeam == TEAM_PLAYER && NPCInfo->charmedTime && NPCInfo->charmedTime < level.time && NPC->client) { // we were charmed, set us back! + // NOTE: presumptions here... + team_t savTeam = NPC->client->enemyTeam; NPC->client->enemyTeam = NPC->client->playerTeam; NPC->client->playerTeam = savTeam; NPC->client->leader = NULL; - if ( NPCInfo->tempBehavior == BS_FOLLOW_LEADER ) - { + if (NPCInfo->tempBehavior == BS_FOLLOW_LEADER) { NPCInfo->tempBehavior = BS_DEFAULT; } - G_ClearEnemy( NPC ); + G_ClearEnemy(NPC); NPCInfo->charmedTime = 0; - //say something to let player know you've snapped out of it - G_AddVoiceEvent( NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + // say something to let player know you've snapped out of it + G_AddVoiceEvent(NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - } - diff --git a/codeJK2/game/Q3_Interface.cpp b/codeJK2/game/Q3_Interface.cpp index 4be6d5216f..a7ba066917 100644 --- a/codeJK2/game/Q3_Interface.cpp +++ b/codeJK2/game/Q3_Interface.cpp @@ -22,7 +22,7 @@ along with this program; if not, see . // ICARUS Engine Interface File // -// This file is the only section of the ICARUS systems that +// This file is the only section of the ICARUS systems that // is not directly portable from engine to engine. // // -- jweier @@ -48,150 +48,131 @@ along with this program; if not, see . #include #endif -extern int ICARUS_LinkEntity( int entID, CSequencer *sequencer, CTaskManager *taskManager ); +extern int ICARUS_LinkEntity(int entID, CSequencer *sequencer, CTaskManager *taskManager); -extern void InitMover( gentity_t *ent ); -extern void MatchTeam( gentity_t *teamLeader, int moverState, int time ); -//extern void SetMoverState( gentity_t *ent, moverState_t moverState, int time ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern char *G_GetLocationForEnt( gentity_t *ent ); -extern void NPC_BSSearchStart( int homeWp, bState_t bState ); -extern void InitMoverTrData( gentity_t *ent ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); +extern void InitMover(gentity_t *ent); +extern void MatchTeam(gentity_t *teamLeader, int moverState, int time); +// extern void SetMoverState( gentity_t *ent, moverState_t moverState, int time ); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern char *G_GetLocationForEnt(gentity_t *ent); +extern void NPC_BSSearchStart(int homeWp, bState_t bState); +extern void InitMoverTrData(gentity_t *ent); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); extern cvar_t *g_sex; extern cvar_t *g_timescale; -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -//extern void FX_BorgTeleport( vec3_t org ); -static void Q3_SetWeapon (int entID, const char *wp_name); -static void Q3_SetItem (int entID, const char *item_name); -extern void CG_ChangeWeapon( int num ); -extern int TAG_GetOrigin2( const char *owner, const char *name, vec3_t origin ); -extern void G_TeamRetaliation ( gentity_t *targ, gentity_t *attacker, qboolean stopIcarus ); -extern void G_PlayDoorLoopSound( gentity_t *ent ); -extern void G_PlayDoorSound( gentity_t *ent, int type ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void NPC_ClearLookTarget( gentity_t *self ); -qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern int BMS_START; -extern int BMS_MID; -extern int BMS_END; -extern cvar_t *g_skippingcin; - -extern qboolean stop_icarus; - -#define stringIDExpand(str, strEnum) { str, strEnum }, ENUM2STRING(strEnum) +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +// extern void FX_BorgTeleport( vec3_t org ); +static void Q3_SetWeapon(int entID, const char *wp_name); +static void Q3_SetItem(int entID, const char *item_name); +extern void CG_ChangeWeapon(int num); +extern int TAG_GetOrigin2(const char *owner, const char *name, vec3_t origin); +extern void G_TeamRetaliation(gentity_t *targ, gentity_t *attacker, qboolean stopIcarus); +extern void G_PlayDoorLoopSound(gentity_t *ent); +extern void G_PlayDoorSound(gentity_t *ent, int type); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void NPC_ClearLookTarget(gentity_t *self); +qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern int BMS_START; +extern int BMS_MID; +extern int BMS_END; +extern cvar_t *g_skippingcin; + +extern qboolean stop_icarus; + +#define stringIDExpand(str, strEnum) {str, strEnum}, ENUM2STRING(strEnum) //#define stringIDExpand(str, strEnum) str,strEnum /* -stringID_table_t tagsTable [] = +stringID_table_t tagsTable [] = { } */ -stringID_table_t BSTable[] = -{ - ENUM2STRING(BS_DEFAULT),//# default behavior for that NPC - ENUM2STRING(BS_ADVANCE_FIGHT),//# Advance to captureGoal and shoot enemies if you can - ENUM2STRING(BS_SLEEP),//# Play awake script when startled by sound - ENUM2STRING(BS_FOLLOW_LEADER),//# Follow your leader and shoot any enemies you come across - ENUM2STRING(BS_JUMP),//# Face navgoal and jump to it. - ENUM2STRING(BS_SEARCH),//# Using current waypoint as a base), search the immediate branches of waypoints for enemies - ENUM2STRING(BS_WANDER),//# Wander down random waypoint paths - ENUM2STRING(BS_NOCLIP),//# Moves through walls), etc. - ENUM2STRING(BS_REMOVE),//# Waits for player to leave PVS then removes itself - ENUM2STRING(BS_CINEMATIC),//# Does nothing but face it's angles and move to a goal if it has one - //the rest are internal only - {"", -1}, +stringID_table_t BSTable[] = { + ENUM2STRING(BS_DEFAULT), //# default behavior for that NPC + ENUM2STRING(BS_ADVANCE_FIGHT), //# Advance to captureGoal and shoot enemies if you can + ENUM2STRING(BS_SLEEP), //# Play awake script when startled by sound + ENUM2STRING(BS_FOLLOW_LEADER), //# Follow your leader and shoot any enemies you come across + ENUM2STRING(BS_JUMP), //# Face navgoal and jump to it. + ENUM2STRING(BS_SEARCH), //# Using current waypoint as a base), search the immediate branches of waypoints for enemies + ENUM2STRING(BS_WANDER), //# Wander down random waypoint paths + ENUM2STRING(BS_NOCLIP), //# Moves through walls), etc. + ENUM2STRING(BS_REMOVE), //# Waits for player to leave PVS then removes itself + ENUM2STRING(BS_CINEMATIC), //# Does nothing but face it's angles and move to a goal if it has one + // the rest are internal only + {"", -1}, }; - - -stringID_table_t BSETTable[] = -{ - ENUM2STRING(BSET_SPAWN),//# script to use when first spawned - ENUM2STRING(BSET_USE),//# script to use when used - ENUM2STRING(BSET_AWAKE),//# script to use when awoken/startled - ENUM2STRING(BSET_ANGER),//# script to use when aquire an enemy - ENUM2STRING(BSET_ATTACK),//# script to run when you attack - ENUM2STRING(BSET_VICTORY),//# script to run when you kill someone - ENUM2STRING(BSET_LOSTENEMY),//# script to run when you can't find your enemy - ENUM2STRING(BSET_PAIN),//# script to use when take pain - ENUM2STRING(BSET_FLEE),//# script to use when take pain below 50% of health - ENUM2STRING(BSET_DEATH),//# script to use when killed - ENUM2STRING(BSET_DELAYED),//# script to run when self->delayScriptTime is reached - ENUM2STRING(BSET_BLOCKED),//# script to run when blocked by a friendly NPC or player - ENUM2STRING(BSET_BUMPED),//# script to run when bumped into a friendly NPC or player (can set bumpRadius) - ENUM2STRING(BSET_STUCK),//# script to run when blocked by a wall - ENUM2STRING(BSET_FFIRE),//# script to run when player shoots their own teammates - ENUM2STRING(BSET_FFDEATH),//# script to run when player kills a teammate +stringID_table_t BSETTable[] = { + ENUM2STRING(BSET_SPAWN), //# script to use when first spawned + ENUM2STRING(BSET_USE), //# script to use when used + ENUM2STRING(BSET_AWAKE), //# script to use when awoken/startled + ENUM2STRING(BSET_ANGER), //# script to use when aquire an enemy + ENUM2STRING(BSET_ATTACK), //# script to run when you attack + ENUM2STRING(BSET_VICTORY), //# script to run when you kill someone + ENUM2STRING(BSET_LOSTENEMY), //# script to run when you can't find your enemy + ENUM2STRING(BSET_PAIN), //# script to use when take pain + ENUM2STRING(BSET_FLEE), //# script to use when take pain below 50% of health + ENUM2STRING(BSET_DEATH), //# script to use when killed + ENUM2STRING(BSET_DELAYED), //# script to run when self->delayScriptTime is reached + ENUM2STRING(BSET_BLOCKED), //# script to run when blocked by a friendly NPC or player + ENUM2STRING(BSET_BUMPED), //# script to run when bumped into a friendly NPC or player (can set bumpRadius) + ENUM2STRING(BSET_STUCK), //# script to run when blocked by a wall + ENUM2STRING(BSET_FFIRE), //# script to run when player shoots their own teammates + ENUM2STRING(BSET_FFDEATH), //# script to run when player kills a teammate stringIDExpand("", BSET_INVALID), - {"", -1}, -}; - -stringID_table_t WPTable[] = -{ - {"NULL", WP_NONE}, - ENUM2STRING(WP_NONE), - // Player weapons - ENUM2STRING(WP_SABER), // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. - ENUM2STRING(WP_BRYAR_PISTOL), - ENUM2STRING(WP_BLASTER), - ENUM2STRING(WP_DISRUPTOR), - ENUM2STRING(WP_BOWCASTER), - ENUM2STRING(WP_REPEATER), - ENUM2STRING(WP_DEMP2), - ENUM2STRING(WP_FLECHETTE), - ENUM2STRING(WP_ROCKET_LAUNCHER), - ENUM2STRING(WP_THERMAL), - ENUM2STRING(WP_TRIP_MINE), - ENUM2STRING(WP_DET_PACK), - ENUM2STRING(WP_STUN_BATON), - //NOTE: player can only have up to 16 weapons), anything after that is enemy only - ENUM2STRING(WP_MELEE), // Any ol' melee attack - // NPC enemy weapons - ENUM2STRING(WP_EMPLACED_GUN), - ENUM2STRING(WP_BOT_LASER), // Probe droid - Laser blast - ENUM2STRING(WP_TURRET), // turret guns - ENUM2STRING(WP_ATST_MAIN), - ENUM2STRING(WP_ATST_SIDE), - ENUM2STRING(WP_TIE_FIGHTER), - ENUM2STRING(WP_RAPID_FIRE_CONC), - ENUM2STRING(WP_BLASTER_PISTOL), // apparently some enemy only version of the blaster - {"", 0} -}; - -stringID_table_t INVTable[] = -{ - ENUM2STRING(INV_ELECTROBINOCULARS), - ENUM2STRING(INV_BACTA_CANISTER), - ENUM2STRING(INV_SEEKER), - ENUM2STRING(INV_LIGHTAMP_GOGGLES), - ENUM2STRING(INV_SENTRY), - {"", 0} -}; - -stringID_table_t eventTable[] = -{ - //BOTH_h - //END - {"", EV_BAD}, + {"", -1}, }; -stringID_table_t DMSTable[] = -{ - {"NULL",-1}, - ENUM2STRING(DM_AUTO), //# let the game determine the dynamic music as normal - ENUM2STRING(DM_SILENCE), //# stop the music - ENUM2STRING(DM_EXPLORE), //# force the exploration music to play - ENUM2STRING(DM_ACTION), //# force the action music to play - ENUM2STRING(DM_BOSS), //# force the boss battle music to play (if there is any) - ENUM2STRING(DM_DEATH), //# force the "player dead" music to play - {"", -1} +stringID_table_t WPTable[] = {{"NULL", WP_NONE}, + ENUM2STRING(WP_NONE), + // Player weapons + ENUM2STRING(WP_SABER), // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. + ENUM2STRING(WP_BRYAR_PISTOL), + ENUM2STRING(WP_BLASTER), + ENUM2STRING(WP_DISRUPTOR), + ENUM2STRING(WP_BOWCASTER), + ENUM2STRING(WP_REPEATER), + ENUM2STRING(WP_DEMP2), + ENUM2STRING(WP_FLECHETTE), + ENUM2STRING(WP_ROCKET_LAUNCHER), + ENUM2STRING(WP_THERMAL), + ENUM2STRING(WP_TRIP_MINE), + ENUM2STRING(WP_DET_PACK), + ENUM2STRING(WP_STUN_BATON), + // NOTE: player can only have up to 16 weapons), anything after that is enemy only + ENUM2STRING(WP_MELEE), // Any ol' melee attack + // NPC enemy weapons + ENUM2STRING(WP_EMPLACED_GUN), + ENUM2STRING(WP_BOT_LASER), // Probe droid - Laser blast + ENUM2STRING(WP_TURRET), // turret guns + ENUM2STRING(WP_ATST_MAIN), + ENUM2STRING(WP_ATST_SIDE), + ENUM2STRING(WP_TIE_FIGHTER), + ENUM2STRING(WP_RAPID_FIRE_CONC), + ENUM2STRING(WP_BLASTER_PISTOL), // apparently some enemy only version of the blaster + {"", 0}}; + +stringID_table_t INVTable[] = {ENUM2STRING(INV_ELECTROBINOCULARS), ENUM2STRING(INV_BACTA_CANISTER), ENUM2STRING(INV_SEEKER), + ENUM2STRING(INV_LIGHTAMP_GOGGLES), ENUM2STRING(INV_SENTRY), {"", 0}}; + +stringID_table_t eventTable[] = { + // BOTH_h + // END + {"", EV_BAD}, }; -stringID_table_t setTable[] = -{ - ENUM2STRING(SET_SPAWNSCRIPT),//0 +stringID_table_t DMSTable[] = {{"NULL", -1}, + ENUM2STRING(DM_AUTO), //# let the game determine the dynamic music as normal + ENUM2STRING(DM_SILENCE), //# stop the music + ENUM2STRING(DM_EXPLORE), //# force the exploration music to play + ENUM2STRING(DM_ACTION), //# force the action music to play + ENUM2STRING(DM_BOSS), //# force the boss battle music to play (if there is any) + ENUM2STRING(DM_DEATH), //# force the "player dead" music to play + {"", -1}}; + +stringID_table_t setTable[] = { + ENUM2STRING(SET_SPAWNSCRIPT), // 0 ENUM2STRING(SET_USESCRIPT), ENUM2STRING(SET_AWAKESCRIPT), ENUM2STRING(SET_ANGERSCRIPT), @@ -403,71 +384,66 @@ stringID_table_t setTable[] = ENUM2STRING(SET_CLEAN_DAMAGING_ENTS), ENUM2STRING(SET_HUD), -//FIXME: add BOTH_ attributes here too - {"", SET_}, + // FIXME: add BOTH_ attributes here too + {"", SET_}, }; -qboolean COM_ParseString( char **data, char **s ); +qboolean COM_ParseString(char **data, char **s); //======================================================================= -interface_export_t interface_export; - +interface_export_t interface_export; vec4_t textcolor_caption; vec4_t textcolor_center; vec4_t textcolor_scroll; - /* ============ Q3_ReadScript Description : Reads in a file and attaches the script directory properly - Return type : static int + Return type : static int Argument : const char *name Argument : void **buf ============ */ -extern int ICARUS_GetScript( const char *name, char **buf ); //g_icarus.cpp -static int Q3_ReadScript( const char *name, void **buf ) -{ - return ICARUS_GetScript( va( "%s/%s", Q3_SCRIPT_DIR, name ), (char**)buf ); //get a (hopefully) cached file +extern int ICARUS_GetScript(const char *name, char **buf); // g_icarus.cpp +static int Q3_ReadScript(const char *name, void **buf) { + return ICARUS_GetScript(va("%s/%s", Q3_SCRIPT_DIR, name), (char **)buf); // get a (hopefully) cached file } /* ============ -Q3_CenterPrint +Q3_CenterPrint Description : Prints a message in the center of the screen - Return type : static void + Return type : static void Argument : const char *format Argument : ... ============ */ -static void Q3_CenterPrint ( const char *format, ... ) -{ +static void Q3_CenterPrint(const char *format, ...) { - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr, format); - Q_vsnprintf (text, sizeof(text), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(text, sizeof(text), format, argptr); + va_end(argptr); // FIXME: added '!' so you can print something that's hasn't been precached, '@' searches only for precache text // this is just a TEMPORARY placeholder until objectives are in!!! -- dmv 11/26/01 - if ((text[0] == '@') || text[0] == '!') // It's a key + if ((text[0] == '@') || text[0] == '!') // It's a key { - if( text[0] == '!') - { - gi.SendServerCommand( 0, "cp \"%s\"", (text+1) ); + if (text[0] == '!') { + gi.SendServerCommand(0, "cp \"%s\"", (text + 1)); return; } - gi.SendServerCommand( 0, "cp \"%s\"", text ); + gi.SendServerCommand(0, "cp \"%s\"", text); } - Q3_DebugPrint( WL_VERBOSE, "%s\n", text); // Just a developers note + Q3_DebugPrint(WL_VERBOSE, "%s\n", text); // Just a developers note return; } @@ -478,44 +454,26 @@ SetTextColor ------------------------- */ -static void SetTextColor ( vec4_t textcolor,const char *color) -{ - - if (Q_stricmp(color,"BLACK") == 0) - { - VectorCopy4( colorTable[CT_BLACK], textcolor ); - } - else if (Q_stricmp(color,"RED") == 0) - { - VectorCopy4( colorTable[CT_RED], textcolor ); - } - else if (Q_stricmp(color,"GREEN") == 0) - { - VectorCopy4( colorTable[CT_GREEN], textcolor ); - } - else if (Q_stricmp(color,"YELLOW") == 0) - { - VectorCopy4( colorTable[CT_YELLOW], textcolor ); - } - else if (Q_stricmp(color,"BLUE") == 0) - { - VectorCopy4( colorTable[CT_BLUE], textcolor ); - } - else if (Q_stricmp(color,"CYAN") == 0) - { - VectorCopy4( colorTable[CT_CYAN], textcolor ); - } - else if (Q_stricmp(color,"MAGENTA") == 0) - { - VectorCopy4( colorTable[CT_MAGENTA], textcolor ); - } - else if (Q_stricmp(color,"WHITE") == 0) - { - VectorCopy4( colorTable[CT_WHITE], textcolor ); - } - else - { - VectorCopy4( colorTable[CT_WHITE], textcolor ); +static void SetTextColor(vec4_t textcolor, const char *color) { + + if (Q_stricmp(color, "BLACK") == 0) { + VectorCopy4(colorTable[CT_BLACK], textcolor); + } else if (Q_stricmp(color, "RED") == 0) { + VectorCopy4(colorTable[CT_RED], textcolor); + } else if (Q_stricmp(color, "GREEN") == 0) { + VectorCopy4(colorTable[CT_GREEN], textcolor); + } else if (Q_stricmp(color, "YELLOW") == 0) { + VectorCopy4(colorTable[CT_YELLOW], textcolor); + } else if (Q_stricmp(color, "BLUE") == 0) { + VectorCopy4(colorTable[CT_BLUE], textcolor); + } else if (Q_stricmp(color, "CYAN") == 0) { + VectorCopy4(colorTable[CT_CYAN], textcolor); + } else if (Q_stricmp(color, "MAGENTA") == 0) { + VectorCopy4(colorTable[CT_MAGENTA], textcolor); + } else if (Q_stricmp(color, "WHITE") == 0) { + VectorCopy4(colorTable[CT_WHITE], textcolor); + } else { + VectorCopy4(colorTable[CT_WHITE], textcolor); } return; @@ -529,29 +487,23 @@ WARNING: Clearing a taskID will make that task never finish unless you intend to return the same taskID from somewhere else. ------------------------- */ -void Q3_TaskIDClear( int *taskID ) -{ - *taskID = -1; -} +void Q3_TaskIDClear(int *taskID) { *taskID = -1; } /* ------------------------- qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) ------------------------- */ -qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) -{ - if ( !ent->sequencer || !ent->taskManager ) - { +qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType) { + if (!ent->sequencer || !ent->taskManager) { return qfalse; } - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return qfalse; } - if ( ent->taskID[taskType] >= 0 )//-1 is none + if (ent->taskID[taskType] >= 0) //-1 is none { return qtrue; } @@ -564,31 +516,26 @@ qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ) void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ) ------------------------- */ -void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +void Q3_TaskIDComplete(gentity_t *ent, taskID_t taskType) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - if ( ent->taskManager && Q3_TaskIDPending( ent, taskType ) ) - {//Complete it - ent->taskManager->Completed( ent->taskID[taskType] ); + if (ent->taskManager && Q3_TaskIDPending(ent, taskType)) { // Complete it + ent->taskManager->Completed(ent->taskID[taskType]); - //See if any other tasks have the name number and clear them so we don't complete more than once - int clearTask = ent->taskID[taskType]; - for ( int tid = 0; tid < NUM_TIDS; tid++ ) - { - if ( ent->taskID[tid] == clearTask ) - { - Q3_TaskIDClear( &ent->taskID[tid] ); + // See if any other tasks have the name number and clear them so we don't complete more than once + int clearTask = ent->taskID[taskType]; + for (int tid = 0; tid < NUM_TIDS; tid++) { + if (ent->taskID[tid] == clearTask) { + Q3_TaskIDClear(&ent->taskID[tid]); } } - //clear it - should be cleared in for loop above - //Q3_TaskIDClear( &ent->taskID[taskType] ); + // clear it - should be cleared in for loop above + // Q3_TaskIDClear( &ent->taskID[taskType] ); } - //otherwise, wasn't waiting for a task to complete anyway + // otherwise, wasn't waiting for a task to complete anyway } /* @@ -597,47 +544,38 @@ void Q3_SetTaskID( gentity_t *ent, taskID_t taskType, int taskID ) ------------------------- */ -static void Q3_TaskIDSet( gentity_t *ent, taskID_t taskType, int taskID ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +static void Q3_TaskIDSet(gentity_t *ent, taskID_t taskType, int taskID) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - //Might be stomping an old task, so complete and clear previous task if there was one - Q3_TaskIDComplete( ent, taskType ); + // Might be stomping an old task, so complete and clear previous task if there was one + Q3_TaskIDComplete(ent, taskType); ent->taskID[taskType] = taskID; } - /* ============ Q3_CheckStringCounterIncrement - Description : - Return type : static float + Description : + Return type : static float Argument : const char *string ============ */ -static float Q3_CheckStringCounterIncrement( const char *string ) -{ - char *numString; - float val = 0.0f; +static float Q3_CheckStringCounterIncrement(const char *string) { + char *numString; + float val = 0.0f; - if ( string[0] == '+' ) - {//We want to increment whatever the value is by whatever follows the + - if ( string[1] ) - { + if (string[0] == '+') { // We want to increment whatever the value is by whatever follows the + + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ); + val = atof(numString); } - } - else if ( string[0] == '-' ) - {//we want to decrement - if ( string[1] ) - { + } else if (string[0] == '-') { // we want to decrement + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ) * -1; + val = atof(numString) * -1; } } @@ -649,17 +587,15 @@ static float Q3_CheckStringCounterIncrement( const char *string ) Q3_GetAnimLower ------------------------- */ -static char *Q3_GetAnimLower( gentity_t *ent ) -{ - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n" ); +static char *Q3_GetAnimLower(gentity_t *ent) { + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n"); return NULL; } int anim = ent->client->ps.legsAnim; - return (char *) GetStringForID( animTable, anim ); + return (char *)GetStringForID(animTable, anim); } /* @@ -667,17 +603,15 @@ static char *Q3_GetAnimLower( gentity_t *ent ) Q3_GetAnimUpper ------------------------- */ -static char *Q3_GetAnimUpper( gentity_t *ent ) -{ - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n" ); +static char *Q3_GetAnimUpper(gentity_t *ent) { + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n"); return NULL; } int anim = ent->client->ps.torsoAnim; - return (char *) GetStringForID( animTable, anim ); + return (char *)GetStringForID(animTable, anim); } /* @@ -685,29 +619,25 @@ static char *Q3_GetAnimUpper( gentity_t *ent ) Q3_GetAnimBoth ------------------------- */ -static char *Q3_GetAnimBoth( gentity_t *ent ) -{ - char *lowerName, *upperName; +static char *Q3_GetAnimBoth(gentity_t *ent) { + char *lowerName, *upperName; - lowerName = Q3_GetAnimLower( ent ); - upperName = Q3_GetAnimUpper( ent ); + lowerName = Q3_GetAnimLower(ent); + upperName = Q3_GetAnimUpper(ent); - if ( VALIDSTRING( lowerName ) == false ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n" ); + if (VALIDSTRING(lowerName) == false) { + Q3_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n"); return NULL; } - if ( VALIDSTRING( upperName ) == false ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n" ); + if (VALIDSTRING(upperName) == false) { + Q3_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n"); return NULL; } - if ( Q_stricmp( lowerName, upperName ) ) - { -#ifdef _DEBUG // sigh, cut down on tester reports that aren't important - Q3_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n" ); + if (Q_stricmp(lowerName, upperName)) { +#ifdef _DEBUG // sigh, cut down on tester reports that aren't important + Q3_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n"); #endif } @@ -719,80 +649,70 @@ static char *Q3_GetAnimBoth( gentity_t *ent ) Q3_SetObjective ------------------------- */ -static void Q3_SetObjective(const char *ObjEnum, int status) -{ +static void Q3_SetObjective(const char *ObjEnum, int status) { int objectiveID; - gclient_t *client; - objectives_t *objective; - int *objectivesShown; + gclient_t *client; + objectives_t *objective; + int *objectivesShown; client = &level.clients[0]; - objectiveID = GetIDForString( objectiveTable, ObjEnum ); + objectiveID = GetIDForString(objectiveTable, ObjEnum); objective = &client->sess.mission_objectives[objectiveID]; objectivesShown = &client->sess.missionObjectivesShown; - - switch (status) - { - case SET_OBJ_HIDE : + switch (status) { + case SET_OBJ_HIDE: objective->display = OBJECTIVE_HIDE; break; - case SET_OBJ_SHOW : + case SET_OBJ_SHOW: objective->display = OBJECTIVE_SHOW; objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text break; - case SET_OBJ_PENDING : + case SET_OBJ_PENDING: objective->status = OBJECTIVE_STAT_PENDING; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; - case SET_OBJ_SUCCEEDED : + case SET_OBJ_SUCCEEDED: objective->status = OBJECTIVE_STAT_SUCCEEDED; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; - case SET_OBJ_FAILED : + case SET_OBJ_FAILED: objective->status = OBJECTIVE_STAT_FAILED; - if (objective->display != OBJECTIVE_HIDE) - { + if (objective->display != OBJECTIVE_HIDE) { objectivesShown++; - missionInfo_Updated = qtrue; // Activate flashing text + missionInfo_Updated = qtrue; // Activate flashing text } break; } } - /* ------------------------- Q3_SetMissionFailed ------------------------- */ -extern void G_PlayerGuiltDeath( void ); -static void Q3_SetMissionFailed(const char *TextEnum) -{ - gentity_t *ent = &g_entities[0]; +extern void G_PlayerGuiltDeath(void); +static void Q3_SetMissionFailed(const char *TextEnum) { + gentity_t *ent = &g_entities[0]; - if ( ent->health >= 0 ) - { + if (ent->health >= 0) { G_PlayerGuiltDeath(); } ent->health = 0; - //FIXME: what about other NPCs? Scripts? + // FIXME: what about other NPCs? Scripts? - // statusTextIndex is looked at on the client side. - statusTextIndex = GetIDForString( missionFailedTable, TextEnum ); + // statusTextIndex is looked at on the client side. + statusTextIndex = GetIDForString(missionFailedTable, TextEnum); cg.missionStatusShow = qtrue; - if ( ent->client ) - {//hold this screen up for at least 2 seconds + if (ent->client) { // hold this screen up for at least 2 seconds ent->client->respawnTime = level.time + 2000; } } @@ -802,14 +722,12 @@ static void Q3_SetMissionFailed(const char *TextEnum) Q3_SetStatusText ------------------------- */ -static void Q3_SetStatusText(const char *StatusTextEnum) -{ +static void Q3_SetStatusText(const char *StatusTextEnum) { int statusTextID; - statusTextID = GetIDForString( statusTextTable, StatusTextEnum ); + statusTextID = GetIDForString(statusTextTable, StatusTextEnum); - switch (statusTextID) - { + switch (statusTextID) { case STAT_INSUBORDINATION: case STAT_YOUCAUSEDDEATHOFTEAMMATE: case STAT_DIDNTPROTECTTECH: @@ -826,16 +744,14 @@ static void Q3_SetStatusText(const char *StatusTextEnum) } } - /* ------------------------- Q3_ObjectiveClearAll ------------------------- */ -static void Q3_ObjectiveClearAll(void) -{ +static void Q3_ObjectiveClearAll(void) { client = &level.clients[0]; - memset(client->sess.mission_objectives,0,sizeof(client->sess.mission_objectives)); + memset(client->sess.mission_objectives, 0, sizeof(client->sess.mission_objectives)); } /* @@ -845,10 +761,7 @@ Q3_SetCaptionTextColor Change color text prints in ============= */ -static void Q3_SetCaptionTextColor ( const char *color) -{ - SetTextColor(textcolor_caption,color); -} +static void Q3_SetCaptionTextColor(const char *color) { SetTextColor(textcolor_caption, color); } /* ============= @@ -857,10 +770,7 @@ Q3_SetCenterTextColor Change color text prints in ============= */ -static void Q3_SetCenterTextColor ( const char *color) -{ - SetTextColor(textcolor_center,color); -} +static void Q3_SetCenterTextColor(const char *color) { SetTextColor(textcolor_center, color); } /* ============= @@ -869,10 +779,7 @@ Q3_SetScrollTextColor Change color text prints in ============= */ -static void Q3_SetScrollTextColor ( const char *color) -{ - SetTextColor(textcolor_scroll,color); -} +static void Q3_SetScrollTextColor(const char *color) { SetTextColor(textcolor_scroll, color); } /* ============= @@ -881,9 +788,8 @@ Q3_ScrollText Prints a message in the center of the screen ============= */ -static void Q3_ScrollText ( const char *id) -{ - gi.SendServerCommand( 0, "st \"%s\"", id); +static void Q3_ScrollText(const char *id) { + gi.SendServerCommand(0, "st \"%s\"", id); return; } @@ -895,9 +801,8 @@ Q3_LCARSText Prints a message in the center of the screen giving it an LCARS frame around it ============= */ -static void Q3_LCARSText ( const char *id) -{ - gi.SendServerCommand( 0, "lt \"%s\"", id); +static void Q3_LCARSText(const char *id) { + gi.SendServerCommand(0, "lt \"%s\"", id); return; } @@ -909,30 +814,29 @@ Q3_GetEntityByName Returns the sequencer of the entity by the given name ============= */ -static gentity_t *Q3_GetEntityByName( const char *name ) -{ - gentity_t *ent; - entlist_t::iterator ei; - char temp[1024]; +static gentity_t *Q3_GetEntityByName(const char *name) { + gentity_t *ent; + entlist_t::iterator ei; + char temp[1024]; - if ( name == NULL || name[0] == '\0' ) + if (name == NULL || name[0] == '\0') return NULL; - strncpy( (char *) temp, name, sizeof(temp) ); - temp[sizeof(temp)-1] = 0; + strncpy((char *)temp, name, sizeof(temp)); + temp[sizeof(temp) - 1] = 0; - ei = ICARUS_EntList.find( Q_strupr( (char *) temp ) ); + ei = ICARUS_EntList.find(Q_strupr((char *)temp)); - if ( ei == ICARUS_EntList.end() ) + if (ei == ICARUS_EntList.end()) return NULL; ent = &g_entities[(*ei).second]; return ent; // this now returns the ent instead of the sequencer -- dmv 06/27/01 -// if (ent == NULL) -// return NULL; -// return ent->sequencer; + // if (ent == NULL) + // return NULL; + // return ent->sequencer; } /* @@ -942,17 +846,14 @@ Q3_GetTime Get the current game time ============= */ -static unsigned int Q3_GetTime( void ) -{ - return level.time; -} +static unsigned int Q3_GetTime(void) { return level.time; } /* ============= G_AddSexToMunroString Take any string, look for "kyle/" replace with "kyla/" based on "sex" -And: Take any string, look for "/mr_" replace with "/ms_" based on "sex" +And: Take any string, look for "/mr_" replace with "/ms_" based on "sex" returns qtrue if changed to ms ============= */ @@ -1001,42 +902,36 @@ Q3_PlaySound Plays a sound from an entity ============= */ -extern void G_SoundOnEnt (gentity_t *ent, soundChannel_t channel, const char *soundPath); -extern void G_SoundBroadcast( gentity_t *ent, int soundIndex ); -static int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) -{ - gentity_t *ent = &g_entities[entID]; - char finalName[MAX_QPATH]; - soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch - qboolean type_voice = qfalse; +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void G_SoundBroadcast(gentity_t *ent, int soundIndex); +static int Q3_PlaySound(int taskID, int entID, const char *name, const char *channel) { + gentity_t *ent = &g_entities[entID]; + char finalName[MAX_QPATH]; + soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch + qboolean type_voice = qfalse; - Q_strncpyz( finalName, name, MAX_QPATH ); + Q_strncpyz(finalName, name, MAX_QPATH); Q_strupr(finalName); - //G_AddSexToMunroString( finalName, qtrue ); + // G_AddSexToMunroString( finalName, qtrue ); - COM_StripExtension( (const char *)finalName, finalName, sizeof(finalName) ); + COM_StripExtension((const char *)finalName, finalName, sizeof(finalName)); - int soundHandle = G_SoundIndex( (char *) finalName ); + int soundHandle = G_SoundIndex((char *)finalName); bool bBroadcast = false; - if ( ( Q_stricmp( channel, "CHAN_ANNOUNCER" ) == 0 ) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname ) == 0) ) { + if ((Q_stricmp(channel, "CHAN_ANNOUNCER") == 0) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname) == 0)) { bBroadcast = true; } - // moved here from further down so I can easily check channel-type without code dup... // - if ( Q_stricmp( channel, "CHAN_VOICE" ) == 0 ) - { + if (Q_stricmp(channel, "CHAN_VOICE") == 0) { voice_chan = CHAN_VOICE; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_ATTEN" ) == 0 ) - { + } else if (Q_stricmp(channel, "CHAN_VOICE_ATTEN") == 0) { voice_chan = CHAN_VOICE_ATTEN; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_GLOBAL" ) == 0 ) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... + } else if (Q_stricmp(channel, "CHAN_VOICE_GLOBAL") == 0) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... { voice_chan = CHAN_VOICE_GLOBAL; type_voice = qtrue; @@ -1046,74 +941,63 @@ static int Q3_PlaySound( int taskID, int entID, const char *name, const char *ch // if we're in-camera, check for skipping cinematic and ifso, no subtitle print (since screen is not being // updated anyway during skipping). This stops leftover subtitles being left onscreen after unskipping. // - if (!in_camera || - (!g_skippingcin || !g_skippingcin->integer) - ) // paranoia towards project end + if (!in_camera || (!g_skippingcin || !g_skippingcin->integer)) // paranoia towards project end { // Text on // certain NPC's we always want to use subtitles regardless of subtitle setting - if (g_subtitles->integer == 1 || (ent->NPC && (ent->NPC->scriptFlags & SCF_USE_SUBTITLES) ) ) // Show all text + if (g_subtitles->integer == 1 || (ent->NPC && (ent->NPC->scriptFlags & SCF_USE_SUBTITLES))) // Show all text { - if ( in_camera) // Cinematic - { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle ); - } - else //if (precacheWav[i].speaker==SP_NONE) // lower screen text + if (in_camera) // Cinematic + { + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); + } else // if (precacheWav[i].speaker==SP_NONE) // lower screen text { - gentity_t *ent2 = &g_entities[0]; - // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 by the computer core that was submitted as a bug report... + gentity_t *ent2 = &g_entities[0]; + // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 + // by the computer core that was submitted as a bug report... // - if (bBroadcast || (DistanceSquared(ent->currentOrigin, ent2->currentOrigin) < ((voice_chan == CHAN_VOICE_ATTEN)?(350 * 350):(1200 * 1200)) ) ) - { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle ); + if (bBroadcast || + (DistanceSquared(ent->currentOrigin, ent2->currentOrigin) < ((voice_chan == CHAN_VOICE_ATTEN) ? (350 * 350) : (1200 * 1200)))) { + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); } } } // Cinematic only else if (g_subtitles->integer == 2) // Show only talking head text and CINEMATIC { - if ( in_camera) // Cinematic text - { - gi.SendServerCommand( 0, "ct \"%s\" %i", finalName, soundHandle); + if (in_camera) // Cinematic text + { + gi.SendServerCommand(0, "ct \"%s\" %i", finalName, soundHandle); } } - } - if ( type_voice ) - { - if ( g_timescale->value > 1.0f ) - {//Skip the damn sound! + if (type_voice) { + if (g_timescale->value > 1.0f) { // Skip the damn sound! return qtrue; - } - else - { - //This the voice channel - G_SoundOnEnt( ent, voice_chan, ((char *) finalName) ); - } - //Remember we're waiting for this - Q3_TaskIDSet( ent, TID_CHAN_VOICE, taskID ); - //do not task_return complete - // if( voice_chan == CHAN_VOICE_GLOBAL ) - // { - // G_SoundBroadcast( ent, soundHandle ); - // } + } else { + // This the voice channel + G_SoundOnEnt(ent, voice_chan, ((char *)finalName)); + } + // Remember we're waiting for this + Q3_TaskIDSet(ent, TID_CHAN_VOICE, taskID); + // do not task_return complete + // if( voice_chan == CHAN_VOICE_GLOBAL ) + // { + // G_SoundBroadcast( ent, soundHandle ); + // } return qfalse; } - if ( bBroadcast ) - {//Broadcast the sound - G_SoundBroadcast( ent, soundHandle ); - } - else - { - G_Sound( ent, soundHandle ); + if (bBroadcast) { // Broadcast the sound + G_SoundBroadcast(ent, soundHandle); + } else { + G_Sound(ent, soundHandle); } return qtrue; } - /* ============= Q3_SetAngles @@ -1121,31 +1005,24 @@ Q3_SetAngles Sets the angles of an entity directly ============= */ -static void Q3_SetDYaw( int entID, float data ); -static void Q3_SetAngles( int entID, vec3_t angles ) -{ - gentity_t *ent = &g_entities[entID]; - +static void Q3_SetDYaw(int entID, float data); +static void Q3_SetAngles(int entID, vec3_t angles) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); return; } - if (ent->client) - { - SetClientViewAngle( ent, angles ); - if ( ent->NPC ) - { - Q3_SetDYaw( entID, angles[YAW] ); + if (ent->client) { + SetClientViewAngle(ent, angles); + if (ent->NPC) { + Q3_SetDYaw(entID, angles[YAW]); } + } else { + VectorCopy(angles, ent->s.angles); } - else - { - VectorCopy( angles, ent->s.angles ); - } - gi.linkentity( ent ); + gi.linkentity(ent); } /* @@ -1155,71 +1032,59 @@ Q3_SetOrigin Sets the origin of an entity directly ============= */ -static void Q3_SetOrigin( int entID, vec3_t origin ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOrigin(int entID, vec3_t origin) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); return; } - gi.unlinkentity (ent); + gi.unlinkentity(ent); - if(ent->client) - { + if (ent->client) { VectorCopy(origin, ent->client->ps.origin); VectorCopy(origin, ent->currentOrigin); ent->client->ps.origin[2] += 1; - VectorClear (ent->client->ps.velocity); - ent->client->ps.pm_time = 160; // hold time + VectorClear(ent->client->ps.velocity); + ent->client->ps.pm_time = 160; // hold time ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - + ent->client->ps.eFlags ^= EF_TELEPORT_BIT; -// G_KillBox (ent); - } - else - { - G_SetOrigin( ent, origin ); + // G_KillBox (ent); + } else { + G_SetOrigin(ent, origin); } - gi.linkentity( ent ); + gi.linkentity(ent); } - /* ============ MoveOwner - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *self ============ */ -void MoveOwner( gentity_t *self ) -{ +void MoveOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } - if ( SpotWouldTelefrag2( self->owner, self->currentOrigin ) ) - { + if (SpotWouldTelefrag2(self->owner, self->currentOrigin)) { self->e_ThinkFunc = thinkF_MoveOwner; - } - else - { - G_SetOrigin( self->owner, self->currentOrigin ); - Q3_TaskIDComplete( self->owner, TID_MOVE_NAV ); + } else { + G_SetOrigin(self->owner, self->currentOrigin); + Q3_TaskIDComplete(self->owner, TID_MOVE_NAV); } } - /* ============= Q3_SetTeleportDest @@ -1227,27 +1092,22 @@ Q3_SetTeleportDest Copies passed origin to ent running script once there is nothing there blocking the spot ============= */ -static qboolean Q3_SetTeleportDest( int entID, vec3_t org ) -{ - gentity_t *teleEnt = &g_entities[entID]; +static qboolean Q3_SetTeleportDest(int entID, vec3_t org) { + gentity_t *teleEnt = &g_entities[entID]; - if ( teleEnt ) - { - if ( SpotWouldTelefrag2( teleEnt, org ) ) - { + if (teleEnt) { + if (SpotWouldTelefrag2(teleEnt, org)) { gentity_t *teleporter = G_Spawn(); - G_SetOrigin( teleporter, org ); + G_SetOrigin(teleporter, org); teleporter->owner = teleEnt; teleporter->e_ThinkFunc = thinkF_MoveOwner; teleporter->nextthink = level.time + FRAMETIME; - + return qfalse; - } - else - { - G_SetOrigin( teleEnt, org ); + } else { + G_SetOrigin(teleEnt, org); } } @@ -1261,18 +1121,14 @@ Q3_SetCopyOrigin Copies origin of found ent into ent running script =============` */ -static void Q3_SetCopyOrigin( int entID, const char *name ) -{ - gentity_t *found = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCopyOrigin(int entID, const char *name) { + gentity_t *found = G_Find(NULL, FOFS(targetname), (char *)name); - if(found) - { - Q3_SetOrigin( entID, found->currentOrigin ); - SetClientViewAngle( &g_entities[entID], found->s.angles ); - } - else - { - Q3_DebugPrint( WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); + if (found) { + Q3_SetOrigin(entID, found->currentOrigin); + SetClientViewAngle(&g_entities[entID], found->s.angles); + } else { + Q3_DebugPrint(WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); } } @@ -1283,23 +1139,20 @@ Q3_SetVelocity Set the velocity of an entity directly ============= */ -static void Q3_SetVelocity( int entID, int axis, float speed ) -{ - gentity_t *found = &g_entities[entID]; - //FIXME: Not supported - if(!found) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); +static void Q3_SetVelocity(int entID, int axis, float speed) { + gentity_t *found = &g_entities[entID]; + // FIXME: Not supported + if (!found) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); return; } - if(!found->client) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); + if (!found->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); return; } - //FIXME: add or set? + // FIXME: add or set? found->client->ps.velocity[axis] += speed; found->client->ps.pm_time = 500; @@ -1309,95 +1162,86 @@ static void Q3_SetVelocity( int entID, int axis, float speed ) /* ============ Q3_SetAdjustAreaPortals - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean shields ============ */ -static void Q3_SetAdjustAreaPortals( int entID, qboolean adjust ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAdjustAreaPortals(int entID, qboolean adjust) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAdjustAreaPortals: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAdjustAreaPortals: invalid entID %d\n", entID); return; } - ent->svFlags = (adjust) ? (ent->svFlags|SVF_MOVER_ADJ_AREA_PORTALS) : (ent->svFlags&~SVF_MOVER_ADJ_AREA_PORTALS); + ent->svFlags = (adjust) ? (ent->svFlags | SVF_MOVER_ADJ_AREA_PORTALS) : (ent->svFlags & ~SVF_MOVER_ADJ_AREA_PORTALS); } /* ============ Q3_SetDmgByHeavyWeapOnly - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean dmg ============ */ -static void Q3_SetDmgByHeavyWeapOnly( int entID, qboolean dmg ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDmgByHeavyWeapOnly(int entID, qboolean dmg) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: invalid entID %d\n", entID); return; } - - ent->flags = (dmg) ? (ent->flags|FL_DMG_BY_HEAVY_WEAP_ONLY) : (ent->flags&~FL_DMG_BY_HEAVY_WEAP_ONLY); + + ent->flags = (dmg) ? (ent->flags | FL_DMG_BY_HEAVY_WEAP_ONLY) : (ent->flags & ~FL_DMG_BY_HEAVY_WEAP_ONLY); } /* ============ Q3_SetShielded - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean dmg ============ */ -static void Q3_SetShielded( int entID, qboolean dmg ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShielded(int entID, qboolean dmg) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetShielded: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetShielded: invalid entID %d\n", entID); return; } - - ent->flags = (dmg) ? (ent->flags|FL_SHIELDED) : (ent->flags&~FL_SHIELDED); + + ent->flags = (dmg) ? (ent->flags | FL_SHIELDED) : (ent->flags & ~FL_SHIELDED); } /* ============ Q3_SetNoGroups - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean dmg ============ */ -static void Q3_SetNoGroups( int entID, qboolean noGroups ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoGroups(int entID, qboolean noGroups) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoGroups: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoGroups: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoGroups: ent %s is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoGroups: ent %s is not an NPC!\n", ent->targetname); return; } - - ent->NPC->scriptFlags = noGroups ? (ent->NPC->scriptFlags|SCF_NO_GROUPS) : (ent->NPC->scriptFlags&~SCF_NO_GROUPS); + + ent->NPC->scriptFlags = noGroups ? (ent->NPC->scriptFlags | SCF_NO_GROUPS) : (ent->NPC->scriptFlags & ~SCF_NO_GROUPS); } /* @@ -1407,41 +1251,34 @@ moverCallback Utility function ============= */ -extern void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ); -void moverCallback( gentity_t *ent ) -{ - //complete the task - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); - +extern void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor); +void moverCallback(gentity_t *ent) { + // complete the task + Q3_TaskIDComplete(ent, TID_MOVE_NAV); + // play sound - ent->s.loopSound = 0;//stop looping sound - G_PlayDoorSound( ent, BMS_END );//play end sound + ent->s.loopSound = 0; // stop looping sound + G_PlayDoorSound(ent, BMS_END); // play end sound - if ( ent->moverState == MOVER_1TO2 ) - {//reached open + if (ent->moverState == MOVER_1TO2) { // reached open // reached pos2 - MatchTeam( ent, MOVER_POS2, level.time ); - //SetMoverState( ent, MOVER_POS2, level.time ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//reached closed - MatchTeam( ent, MOVER_POS1, level.time ); - //SetMoverState( ent, MOVER_POS1, level.time ); - //close the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qfalse ); + MatchTeam(ent, MOVER_POS2, level.time); + // SetMoverState( ent, MOVER_POS2, level.time ); + } else if (ent->moverState == MOVER_2TO1) { // reached closed + MatchTeam(ent, MOVER_POS1, level.time); + // SetMoverState( ent, MOVER_POS1, level.time ); + // close the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qfalse); } } - if ( ent->e_BlockedFunc == blockedF_Blocked_Mover ) - { + if (ent->e_BlockedFunc == blockedF_Blocked_Mover) { ent->e_BlockedFunc = blockedF_NULL; } - if ( !Q_stricmp( "misc_model_breakable", ent->classname ) && ent->physicsBounce ) - {//a gravity-affected model - misc_model_breakable_gravity_init( ent, qfalse ); + if (!Q_stricmp("misc_model_breakable", ent->classname) && ent->physicsBounce) { // a gravity-affected model + misc_model_breakable_gravity_init(ent, qfalse); } } @@ -1452,28 +1289,26 @@ anglerCallback Utility function ============= */ -void anglerCallback( gentity_t *ent ) -{ - //Complete the task - Q3_TaskIDComplete( ent, TID_ANGLE_FACE ); +void anglerCallback(gentity_t *ent) { + // Complete the task + Q3_TaskIDComplete(ent, TID_ANGLE_FACE); - //Set the currentAngles, clear all movement - VectorMA( ent->s.apos.trBase, (ent->s.apos.trDuration*0.001f), ent->s.apos.trDelta, ent->currentAngles ); - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + // Set the currentAngles, clear all movement + VectorMA(ent->s.apos.trBase, (ent->s.apos.trDuration * 0.001f), ent->s.apos.trDelta, ent->currentAngles); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trDuration = 1; ent->s.apos.trType = TR_STATIONARY; ent->s.apos.trTime = level.time; - //Stop thinking + // Stop thinking ent->e_ReachedFunc = reachedF_NULL; - if ( ent->e_ThinkFunc == thinkF_anglerCallback ) - { + if (ent->e_ThinkFunc == thinkF_anglerCallback) { ent->e_ThinkFunc = thinkF_NULL; } - //link - gi.linkentity( ent ); + // link + gi.linkentity(ent); } /* @@ -1483,35 +1318,31 @@ moveAndRotateCallback Utility function ============= */ -void moveAndRotateCallback( gentity_t *ent ) -{ - //stop turning - anglerCallback( ent ); - //stop moving - moverCallback( ent ); +void moveAndRotateCallback(gentity_t *ent) { + // stop turning + anglerCallback(ent); + // stop moving + moverCallback(ent); } -void Blocked_Mover( gentity_t *ent, gentity_t *other ) { +void Blocked_Mover(gentity_t *ent, gentity_t *other) { // remove anything other than a client -- no longer the case // don't remove security keys or goodie keys - if ( (other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY) ) - { + if ((other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY)) { // should we be doing anything special if a key blocks it... move it somehow..? } // if your not a client, or your a dead client remove yourself... - else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message)) ) - { - if ( !other->taskManager || !other->taskManager->IsRunning() ) - { + else if (other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message))) { + if (!other->taskManager || !other->taskManager->IsRunning()) { // if an item or weapon can we do a little explosion..? - G_FreeEntity( other ); + G_FreeEntity(other); return; } } - if ( ent->damage ) { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } } @@ -1522,45 +1353,40 @@ Q3_Lerp2Start Lerps the origin of an entity to its starting position ============= */ -static void Q3_Lerp2Start( int entID, int taskID, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Lerp2Start(int entID, int taskID, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_Lerp2Start: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Lerp2Start: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Lerp2Start: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_Lerp2Start: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //FIXME: set up correctly!!! + // FIXME: set up correctly!!! ent->moverState = MOVER_2TO1; ent->s.eType = ET_MOVER; - ent->e_ReachedFunc = reachedF_moverCallback; //Callsback the the completion of the move - if ( ent->damage ) - { + ent->e_ReachedFunc = reachedF_moverCallback; // Callsback the the completion of the move + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - ent->s.pos.trDuration = duration * 10; //In seconds + ent->s.pos.trDuration = duration * 10; // In seconds ent->s.pos.trTime = level.time; - - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - gi.linkentity( ent ); + gi.linkentity(ent); } /* @@ -1570,53 +1396,46 @@ Q3_Lerp2End Lerps the origin of an entity to its ending position ============= */ -static void Q3_Lerp2End( int entID, int taskID, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Lerp2End(int entID, int taskID, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_Lerp2End: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Lerp2End: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Lerp2End: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_Lerp2End: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - if ( ent->moverState == MOVER_POS1 ) - {//open the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qtrue ); + if (ent->moverState == MOVER_POS1) { // open the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qtrue); } } - //FIXME: set up correctly!!! + // FIXME: set up correctly!!! ent->moverState = MOVER_1TO2; ent->s.eType = ET_MOVER; - ent->e_ReachedFunc = reachedF_moverCallback; //Callsback the the completion of the move - if ( ent->damage ) - { + ent->e_ReachedFunc = reachedF_moverCallback; // Callsback the the completion of the move + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - ent->s.pos.trDuration = duration * 10; //In seconds + ent->s.pos.trDuration = duration * 10; // In seconds ent->s.time = level.time; - - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - gi.linkentity( ent ); + gi.linkentity(ent); } /* @@ -1627,31 +1446,27 @@ Lerps the origin and angles of an entity to the destination values ============= */ -static void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +static void Q3_Lerp2Pos(int taskID, int entID, vec3_t origin, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_Lerp2Pos: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Lerp2Pos: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Lerp2Pos: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_Lerp2Pos: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //Don't allow a zero duration - if ( duration == 0 ) + // Don't allow a zero duration + if (duration == 0) duration = 1; // @@ -1659,57 +1474,48 @@ static void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, fl moverState_t moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); - if ( moverState == MOVER_POS1 ) - {//open the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qtrue ); + if (moverState == MOVER_POS1) { // open the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qtrue); } } moverState = MOVER_1TO2; - } - else /*if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 )*/ + } else /*if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 )*/ { - VectorCopy( ent->currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); + InitMoverTrData(ent); ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); - //Only do the angles if specified - if ( angles != NULL ) - { + // Only do the angles if specified + if (angles != NULL) { // // Rotation - for ( i = 0; i < 3; i++ ) - { - ang[i] = AngleDelta( angles[i], ent->currentAngles[i] ); - ent->s.apos.trDelta[i] = ( ang[i] / ( duration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleDelta(angles[i], ent->currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (duration * 0.001f)); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trDuration = duration; @@ -1717,26 +1523,22 @@ static void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, fl ent->s.apos.trTime = level.time; ent->e_ReachedFunc = reachedF_moveAndRotateCallback; - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); - } - else - { - //Setup the last bits of information - ent->e_ReachedFunc = reachedF_moverCallback; + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); + } else { + // Setup the last bits of information + ent->e_ReachedFunc = reachedF_moverCallback; } - if ( ent->damage ) - { + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? - - gi.linkentity( ent ); + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? + gi.linkentity(ent); } /* @@ -1746,101 +1548,86 @@ Q3_Lerp2Origin Lerps the origin to the destination value ============= */ -static void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Lerp2Origin(int taskID, int entID, vec3_t origin, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } moverState_t moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); - if ( moverState == MOVER_POS1 ) - {//open the portal - if ( ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS ) - { - gi.AdjustAreaPortalState( ent, qtrue ); + if (moverState == MOVER_POS1) { // open the portal + if (ent->svFlags & SVF_MOVER_ADJ_AREA_PORTALS) { + gi.AdjustAreaPortalState(ent, qtrue); } } moverState = MOVER_1TO2; - } - else if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 ) - { - VectorCopy( ent->currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + } else if (moverState == MOVER_POS2 || moverState == MOVER_1TO2) { + VectorCopy(ent->currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); //FIXME: This will probably break normal things that are being moved... + InitMoverTrData(ent); // FIXME: This will probably break normal things that are being moved... ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); - ent->e_ReachedFunc = reachedF_moverCallback; - if ( ent->damage ) - { + ent->e_ReachedFunc = reachedF_moverCallback; + if (ent->damage) { ent->e_BlockedFunc = blockedF_Blocked_Mover; } - if ( taskID != -1 ) - { - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + if (taskID != -1) { + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); } // starting sound - G_PlayDoorLoopSound( ent );//start looping sound - G_PlayDoorSound( ent, BMS_START ); //play start sound + G_PlayDoorLoopSound(ent); // start looping sound + G_PlayDoorSound(ent, BMS_START); // play start sound - gi.linkentity( ent ); + gi.linkentity(ent); } -static void Q3_SetOriginOffset( int entID, int axis, float offset ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOriginOffset(int entID, int axis, float offset) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); return; } vec3_t origin; - VectorCopy( ent->s.origin, origin ); + VectorCopy(ent->s.origin, origin); origin[axis] += offset; float duration = 0; - if ( ent->speed ) - { - duration = fabs(offset)/fabs(ent->speed)*1000.0f; + if (ent->speed) { + duration = fabs(offset) / fabs(ent->speed) * 1000.0f; } - Q3_Lerp2Origin( -1, entID, origin, duration ); + Q3_Lerp2Origin(-1, entID, origin, duration); } /* ============= @@ -1849,53 +1636,46 @@ Q3_LerpAngles Lerps the angles to the destination value ============= */ -static void Q3_Lerp2Angles( int taskID, int entID, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +static void Q3_Lerp2Angles(int taskID, int entID, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; - if(!ent) - { - Q3_DebugPrint( WL_WARNING, "Q3_Lerp2Angles: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Lerp2Angles: invalid entID %d\n", entID); return; } - - if ( ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Lerp2Angles: ent %d is NOT a mover!\n", entID); + + if (ent->client || ent->NPC || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + Q3_DebugPrint(WL_ERROR, "Q3_Lerp2Angles: ent %d is NOT a mover!\n", entID); return; } - //If we want an instant move, don't send 0... - ent->s.apos.trDuration = (duration>0) ? duration : 1; + // If we want an instant move, don't send 0... + ent->s.apos.trDuration = (duration > 0) ? duration : 1; - for ( i = 0; i < 3; i++ ) - { - ang [i] = AngleSubtract( angles[i], ent->currentAngles[i]); - ent->s.apos.trDelta[i] = ( ang[i] / ( ent->s.apos.trDuration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleSubtract(angles[i], ent->currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (ent->s.apos.trDuration * 0.001f)); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trTime = level.time; - - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); - //ent->e_ReachedFunc = reachedF_NULL; + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); + + // ent->e_ReachedFunc = reachedF_NULL; ent->e_ThinkFunc = thinkF_anglerCallback; ent->nextthink = level.time + duration; - gi.linkentity( ent ); + gi.linkentity(ent); } /* @@ -1905,23 +1685,21 @@ Q3_GetTag Gets the value of a tag by the give name ============= */ -static int Q3_GetTag( int entID, const char *name, int lookup, vec3_t info ) -{ - gentity_t *ent = &g_entities[ entID ]; +static int Q3_GetTag(int entID, const char *name, int lookup, vec3_t info) { + gentity_t *ent = &g_entities[entID]; - VALIDATEB( ent ); + VALIDATEB(ent); - switch ( lookup ) - { + switch (lookup) { case TYPE_ORIGIN: - //return TAG_GetOrigin( ent->targetname, name, info ); - return TAG_GetOrigin( ent->ownername, name, info ); + // return TAG_GetOrigin( ent->targetname, name, info ); + return TAG_GetOrigin(ent->ownername, name, info); break; case TYPE_ANGLES: - //return TAG_GetAngles( ent->targetname, name, info ); - return TAG_GetAngles( ent->ownername, name, info ); - break; + // return TAG_GetAngles( ent->targetname, name, info ); + return TAG_GetAngles(ent->ownername, name, info); + break; } return false; @@ -1934,65 +1712,51 @@ Q3_SetNavGoal Sets the navigational goal of an entity ============= */ -static void Q3_SetNavGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[ entID ]; - vec3_t goalPos; +static void Q3_SetNavGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + vec3_t goalPos; - if ( !ent->health ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, ent->script_targetname ); + if (!ent->health) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, ent->script_targetname); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, ent->script_targetname); return; } - if ( !ent->NPC->tempGoal ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, ent->script_targetname); return; } - if ( !ent->NPC->tempGoal->inuse ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal->inuse) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname); return; } - if( Q_stricmp( "null", name) == 0 ) - { + if (Q_stricmp("null", name) == 0) { ent->NPC->goalEntity = NULL; - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); - } - else - { - //Get the position of the goal - if ( TAG_GetOrigin2( NULL, name, goalPos ) == false ) - { - gentity_t *targ = G_Find(NULL, FOFS(targetname), (char*)name); - if ( !targ ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name ); + Q3_TaskIDComplete(ent, TID_MOVE_NAV); + } else { + // Get the position of the goal + if (TAG_GetOrigin2(NULL, name, goalPos) == false) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), (char *)name); + if (!targ) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name); return; - } - else - { + } else { ent->NPC->goalEntity = targ; - ent->NPC->goalRadius = sqrt(ent->maxs[0]+ent->maxs[0]) + sqrt(targ->maxs[0]+targ->maxs[0]); + ent->NPC->goalRadius = sqrt(ent->maxs[0] + ent->maxs[0]) + sqrt(targ->maxs[0] + targ->maxs[0]); ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; } - } - else - { - int goalRadius = TAG_GetRadius( NULL, name ); - NPC_SetMoveGoal( ent, goalPos, goalRadius, qtrue ); - //We know we want to clear the lastWaypoint here + } else { + int goalRadius = TAG_GetRadius(NULL, name); + NPC_SetMoveGoal(ent, goalPos, goalRadius, qtrue); + // We know we want to clear the lastWaypoint here ent->NPC->goalEntity->lastWaypoint = WAYPOINT_NONE; ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; - #ifdef _DEBUG - //this is *only* for debugging navigation - ent->NPC->tempGoal->target = G_NewString( name ); - #endif// _DEBUG +#ifdef _DEBUG + // this is *only* for debugging navigation + ent->NPC->tempGoal->target = G_NewString(name); +#endif // _DEBUG } } } @@ -2002,58 +1766,51 @@ static void Q3_SetNavGoal( int entID, const char *name ) /* ============ SetLowerAnim - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int animID ============ */ -static void SetLowerAnim( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetLowerAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - NPC_SetAnim(ent,SETANIM_LEGS,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(ent, SETANIM_LEGS, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); } - /* ============ -SetUpperAnim - Description : - Return type : static void +SetUpperAnim + Description : + Return type : static void Argument : int entID Argument : int animID ============ */ -static void SetUpperAnim ( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetUpperAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - NPC_SetAnim(ent,SETANIM_TORSO,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(ent, SETANIM_TORSO, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); } //----------------------------------------------- @@ -2065,28 +1822,24 @@ Q3_SetAnimUpper Sets the upper animation of an entity ============= */ -static qboolean Q3_SetAnimUpper( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimUpper(int entID, const char *anim_name) { + int animID = 0; - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name); return qfalse; } - - if ( !PM_HasAnimation( &g_entities[entID], animID ) ) - { + + if (!PM_HasAnimation(&g_entities[entID], animID)) { return qfalse; } - SetUpperAnim( entID, animID ); + SetUpperAnim(entID, animID); return qtrue; } - /* ============= Q3_SetAnimLower @@ -2094,64 +1847,55 @@ Q3_SetAnimLower Sets the lower animation of an entity ============= */ -static qboolean Q3_SetAnimLower( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimLower(int entID, const char *anim_name) { + int animID = 0; - //FIXME: Setting duck anim does not actually duck! + // FIXME: Setting duck anim does not actually duck! - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name); return qfalse; } - - if ( !PM_HasAnimation( &g_entities[entID], animID ) ) - { + + if (!PM_HasAnimation(&g_entities[entID], animID)) { return qfalse; } - SetLowerAnim( entID, animID ); + SetLowerAnim(entID, animID); return qtrue; } /* ============ Q3_SetAnimHoldTime - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int int_data Argument : qboolean lower ============ */ -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -static void Q3_SetAnimHoldTime( int entID, int int_data, qboolean lower ) -{ - gentity_t *ent = &g_entities[entID]; +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +static void Q3_SetAnimHoldTime(int entID, int int_data, qboolean lower) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimHoldTime: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimHoldTime: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAnimHoldTime: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetAnimHoldTime: ent %d is NOT a player or NPC!\n", entID); return; } - - if(lower) - { - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, int_data ); - } - else - { - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoAnimTimer, int_data ); + + if (lower) { + PM_SetLegsAnimTimer(ent, &ent->client->ps.legsAnimTimer, int_data); + } else { + PM_SetTorsoAnimTimer(ent, &ent->client->ps.torsoAnimTimer, int_data); } } @@ -2162,34 +1906,25 @@ Q3_SetEnemy Sets the enemy of an entity ============= */ -static void Q3_SetEnemy( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEnemy(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { - if(ent->NPC) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { + if (ent->NPC) { G_ClearEnemy(ent); - } - else - { + } else { ent->enemy = NULL; } - } - else - { - gentity_t *enemy = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *enemy = G_Find(NULL, FOFS(targetname), (char *)name); - if(enemy == NULL) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name ); + if (enemy == NULL) { + Q3_DebugPrint(WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name); return; } /*else if(enemy->health <= 0) @@ -2197,15 +1932,11 @@ static void Q3_SetEnemy( int entID, const char *name ) //Q3_DebugPrint( WL_ERROR, "Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; }*/ - else - { - if(ent->NPC) - { - G_SetEnemy( ent, enemy ); + else { + if (ent->NPC) { + G_SetEnemy(ent, enemy); ent->cantHitEnemyCounter = 0; - } - else - { + } else { G_SetEnemy(ent, enemy); } } @@ -2256,170 +1987,137 @@ Q3_SetLeader Sets the leader of an NPC ============= */ -static void Q3_SetLeader( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLeader(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { ent->client->leader = NULL; - } - else - { - gentity_t *leader = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *leader = G_Find(NULL, FOFS(targetname), (char *)name); - if(leader == NULL) - { - //Q3_DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); + if (leader == NULL) { + // Q3_DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); return; - } - else if(leader->health <= 0) - { - //Q3_DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); + } else if (leader->health <= 0) { + // Q3_DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; - } - else - { + } else { ent->client->leader = leader; } } } -stringID_table_t teamTable [] = -{ - ENUM2STRING(TEAM_FREE), - ENUM2STRING(TEAM_PLAYER), - ENUM2STRING(TEAM_ENEMY), - ENUM2STRING(TEAM_NEUTRAL), - {"", TEAM_FREE}, +stringID_table_t teamTable[] = { + ENUM2STRING(TEAM_FREE), ENUM2STRING(TEAM_PLAYER), ENUM2STRING(TEAM_ENEMY), ENUM2STRING(TEAM_NEUTRAL), {"", TEAM_FREE}, }; - /* ============ Q3_SetPlayerTeam - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *teamName ============ */ -static void Q3_SetPlayerTeam( int entID, const char *teamName ) -{ - gentity_t *ent = &g_entities[entID]; - team_t newTeam; +static void Q3_SetPlayerTeam(int entID, const char *teamName) { + gentity_t *ent = &g_entities[entID]; + team_t newTeam; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetPlayerTeam: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetPlayerTeam: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetPlayerTeam: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetPlayerTeam: ent %d is NOT a player or NPC!\n", entID); return; } - newTeam = (team_t)GetIDForString( teamTable, teamName ); + newTeam = (team_t)GetIDForString(teamTable, teamName); ent->client->playerTeam = newTeam; } - /* ============ Q3_SetEnemyTeam - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *teamName ============ */ -static void Q3_SetEnemyTeam( int entID, const char *teamName ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEnemyTeam(int entID, const char *teamName) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEnemyTeam: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEnemyTeam: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetEnemyTeam: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetEnemyTeam: ent %d is NOT a player or NPC!\n", entID); return; } - - ent->client->enemyTeam = (team_t)GetIDForString( teamTable, teamName ); -} + ent->client->enemyTeam = (team_t)GetIDForString(teamTable, teamName); +} /* ============ Q3_SetHealth - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int data ============ */ -static void Q3_SetHealth( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHealth(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); return; } - - if ( data < 0 ) - { + + if (data < 0) { data = 0; } ent->health = data; // should adjust max if new health is higher than max - if ( ent->health > ent->max_health ) - { + if (ent->health > ent->max_health) { ent->max_health = ent->health; } - if(!ent->client) - { + if (!ent->client) { return; } ent->client->ps.stats[STAT_HEALTH] = data; - if ( ent->s.number == 0 ) - {//clamp health to max - if ( ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->s.number == 0) { // clamp health to max + if (ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_HEALTH] = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if ( data == 0 ) - {//artificially "killing" the player", don't let him respawn right away + if (data == 0) { // artificially "killing" the player", don't let him respawn right away ent->client->ps.pm_type = PM_DEAD; - //delay respawn for 2 seconds + // delay respawn for 2 seconds ent->client->respawnTime = level.time + 2000; - //stop all scripts + // stop all scripts stop_icarus = qtrue; - //make the team killable - //G_MakeTeamVulnerable(); + // make the team killable + // G_MakeTeamVulnerable(); } } } @@ -2427,32 +2125,27 @@ static void Q3_SetHealth( int entID, int data ) /* ============ Q3_SetArmor - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int data ============ */ -static void Q3_SetArmor( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetArmor(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); return; } - - if(!ent->client) - { + + if (!ent->client) { return; } ent->client->ps.stats[STAT_ARMOR] = data; - if ( ent->s.number == 0 ) - {//clamp armor to max_health - if ( ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->s.number == 0) { // clamp armor to max_health + if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; } } @@ -2461,49 +2154,40 @@ static void Q3_SetArmor( int entID, int data ) /* ============ Q3_SetBState - Description : - Return type : static qboolean + Description : + Return type : static qboolean Argument : int entID Argument : const char *bs_name -FIXME: this should be a general NPC wrapper function +FIXME: this should be a general NPC wrapper function that is called ANY time a bState is changed... ============ */ -static qboolean Q3_SetBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); return qtrue; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { - if ( bSID == BS_SEARCH || bSID == BS_WANDER ) - { - //FIXME: Reimplement - - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); - } - else - { - ent->waypoint = NAV_FindClosestWaypointForEnt( ent, WAYPOINT_NONE ); + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { + if (bSID == BS_SEARCH || bSID == BS_WANDER) { + // FIXME: Reimplement - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); + } else { + ent->waypoint = NAV_FindClosestWaypointForEnt(ent, WAYPOINT_NONE); + + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); } /*else if( ent->lastWaypoint >=0 && ent->lastWaypoint < num_waypoints ) { @@ -2513,206 +2197,178 @@ static qboolean Q3_SetBState( int entID, const char *bs_name ) { NPC_BSSearchStart( ent->lastValidWaypoint, bSID ); }*/ - else - { - Q3_DebugPrint( WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname ); + else { + Q3_DebugPrint(WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname); return qtrue; } } } - - ent->NPC->tempBehavior = BS_DEFAULT;//need to clear any temp behaviour - if ( ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP ) - {//need to rise up out of the floor after noclipping + ent->NPC->tempBehavior = BS_DEFAULT; // need to clear any temp behaviour + if (ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP) { // need to rise up out of the floor after noclipping ent->currentOrigin[2] += 0.125; - G_SetOrigin( ent, ent->currentOrigin ); + G_SetOrigin(ent, ent->currentOrigin); } ent->NPC->behaviorState = bSID; - if ( bSID == BS_DEFAULT ) - { + if (bSID == BS_DEFAULT) { ent->NPC->defaultBehavior = bSID; } } ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; -// if ( bSID == BS_FLY ) -// {//FIXME: need a set bState wrapper -// ent->NPC->stats.moveType = MT_FLYSWIM; -// } -// else + // if ( bSID == BS_FLY ) + // {//FIXME: need a set bState wrapper + // ent->NPC->stats.moveType = MT_FLYSWIM; + // } + // else { - //FIXME: these are presumptions! - //Q3_SetGravity( entID, g_gravity->value ); - //ent->NPC->stats.moveType = MT_RUNJUMP; + // FIXME: these are presumptions! + // Q3_SetGravity( entID, g_gravity->value ); + // ent->NPC->stats.moveType = MT_RUNJUMP; } - if ( bSID == BS_NOCLIP ) - { + if (bSID == BS_NOCLIP) { ent->client->noclip = qtrue; - } - else - { + } else { ent->client->noclip = qfalse; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -// if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) - if ( bSID == BS_ADVANCE_FIGHT ) - { - return qfalse;//need to wait for task complete message + // if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) + if (bSID == BS_ADVANCE_FIGHT) { + return qfalse; // need to wait for task complete message } -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - if ( bSID == BS_JUMP ) - { + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + if (bSID == BS_JUMP) { ent->NPC->jumpState = JS_FACING; } - return qtrue;//ok to complete + return qtrue; // ok to complete } - /* ============ Q3_SetTempBState - Description : - Return type : static qboolean + Description : + Return type : static qboolean Argument : int entID Argument : const char *bs_name ============ */ -static qboolean Q3_SetTempBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetTempBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); return qtrue; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->tempBehavior = bSID; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - return qtrue;//ok to complete + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + return qtrue; // ok to complete } - /* ============ Q3_SetDefaultBState - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *bs_name ============ */ -static void Q3_SetDefaultBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static void Q3_SetDefaultBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname); return; } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->defaultBehavior = bSID; } } - /* ============ Q3_SetDPitch - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetDPitch( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDPitch(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); return; } - - if ( !ent->NPC || !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC || !ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname); return; } - + int pitchMin = -ent->client->renderInfo.headPitchRangeUp + 1; int pitchMax = ent->client->renderInfo.headPitchRangeDown - 1; - //clamp angle to -180 -> 180 - data = AngleNormalize180( data ); + // clamp angle to -180 -> 180 + data = AngleNormalize180(data); - //Clamp it to my valid range - if ( data < -1 ) - { - if ( data < pitchMin ) - { + // Clamp it to my valid range + if (data < -1) { + if (data < pitchMin) { data = pitchMin; } - } - else if ( data > 1 ) - { - if ( data > pitchMax ) - { + } else if (data > 1) { + if (data > pitchMax) { data = pitchMax; } } @@ -2720,309 +2376,261 @@ static void Q3_SetDPitch( int entID, float data ) ent->NPC->lockedDesiredPitch = ent->NPC->desiredPitch = data; } - /* ============ Q3_SetDYaw - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetDYaw( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; - - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); +static void Q3_SetDYaw(int entID, float data) { + gentity_t *ent = &g_entities[entID]; + + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname); return; } - if(!ent->enemy) - {//don't mess with this if they're aiming at someone + if (!ent->enemy) { // don't mess with this if they're aiming at someone ent->NPC->lockedDesiredYaw = ent->NPC->desiredYaw = ent->s.angles[1] = data; - } - else - { - Q3_DebugPrint( WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname ); + } else { + Q3_DebugPrint(WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname); } } - /* ============ Q3_SetShootDist - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetShootDist( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShootDist(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.shootDistance = data; } - /* ============ Q3_SetVisrange - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetVisrange( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVisrange(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.visrange = data; } - /* ============ Q3_SetEarshot - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetEarshot( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEarshot(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.earshot = data; } - /* ============ Q3_SetVigilance - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetVigilance( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVigilance(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vigilance = data; } - /* ============ Q3_SetVFOV - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int data ============ */ -static void Q3_SetVFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vfov = data; } - /* ============ Q3_SetHFOV - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int data ============ */ -static void Q3_SetHFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.hfov = data; } - /* ============ Q3_SetWidth - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float data ============ */ -static void Q3_SetWidth( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; - - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWidth: invalid entID %d\n", entID); +static void Q3_SetWidth(int entID, int data) { + gentity_t *ent = &g_entities[entID]; + + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWidth: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWidth: '%s' is not an NPC\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWidth: '%s' is not an NPC\n", ent->targetname); return; } - ent->maxs[0] = ent->maxs[1] = data; + ent->maxs[0] = ent->maxs[1] = data; ent->mins[0] = ent->mins[1] = -data; } /* ============ Q3_GetTimeScale - Description : - Return type : static unsigned int + Description : + Return type : static unsigned int Argument : void ============ */ -static unsigned int Q3_GetTimeScale( void ) -{ - //return Q3_TIME_SCALE; +static unsigned int Q3_GetTimeScale(void) { + // return Q3_TIME_SCALE; return g_timescale->value; } - /* ============ Q3_SetTimeScale - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *data ============ */ -static void Q3_SetTimeScale( int entID, const char *data ) -{ - gi.cvar_set("timescale", data); -} - +static void Q3_SetTimeScale(int entID, const char *data) { gi.cvar_set("timescale", data); } /* ============ Q3_SetInvisible - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : qboolean invisible ============ */ -static void Q3_SetInvisible( int entID, qboolean invisible ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetInvisible(int entID, qboolean invisible) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); return; } - - if ( invisible ) - { + + if (invisible) { self->s.eFlags |= EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags |= EF_NODRAW; } self->contents = 0; - } - else - { + } else { self->s.eFlags &= ~EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags &= ~EF_NODRAW; } } @@ -3031,218 +2639,179 @@ static void Q3_SetInvisible( int entID, qboolean invisible ) /* ============ Q3_SetVampire - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : qboolean vampire ============ */ -static void Q3_SetVampire( int entID, qboolean vampire ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetVampire(int entID, qboolean vampire) { + gentity_t *self = &g_entities[entID]; - if ( !self || !self->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetVampire: entID %d not a client\n", entID); + if (!self || !self->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetVampire: entID %d not a client\n", entID); return; } - - if ( vampire ) - { + + if (vampire) { self->client->ps.powerups[PW_DISINT_2] = Q3_INFINITE; - } - else - { + } else { self->client->ps.powerups[PW_DISINT_2] = 0; } } /* ============ Q3_SetGreetAllies - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : qboolean greet ============ */ -static void Q3_SetGreetAllies( int entID, qboolean greet ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGreetAllies(int entID, qboolean greet) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname); return; } - if ( greet ) - { + if (greet) { self->NPC->aiFlags |= NPCAI_GREET_ALLIES; - } - else - { + } else { self->NPC->aiFlags &= ~NPCAI_GREET_ALLIES; } } - /* ============ -Q3_SetViewTarget - Description : - Return type : static void +Q3_SetViewTarget + Description : + Return type : static void Argument : int entID Argument : const char *name ============ */ -static void Q3_SetViewTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *viewtarget = G_Find( NULL, FOFS(targetname), (char *) name); - vec3_t viewspot, selfspot, viewvec, viewangles; +static void Q3_SetViewTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *viewtarget = G_Find(NULL, FOFS(targetname), (char *)name); + vec3_t viewspot, selfspot, viewvec, viewangles; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname); return; } - - //FIXME: Exception handle here - if (viewtarget == NULL) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name ); + + // FIXME: Exception handle here + if (viewtarget == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name); return; } - - //FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves - //around for a script-specified length of time...? - VectorCopy ( self->currentOrigin, selfspot ); + + // FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves + // around for a script-specified length of time...? + VectorCopy(self->currentOrigin, selfspot); selfspot[2] += self->client->ps.viewheight; - if ( viewtarget->client && (!g_skippingcin || !g_skippingcin->integer ) ) - { - VectorCopy ( viewtarget->client->renderInfo.eyePoint, viewspot ); + if (viewtarget->client && (!g_skippingcin || !g_skippingcin->integer)) { + VectorCopy(viewtarget->client->renderInfo.eyePoint, viewspot); + } else { + VectorCopy(viewtarget->currentOrigin, viewspot); } - else - { - VectorCopy ( viewtarget->currentOrigin, viewspot ); - } - - VectorSubtract( viewspot, selfspot, viewvec ); - - vectoangles( viewvec, viewangles ); - Q3_SetDYaw( entID, viewangles[YAW] ); - if ( !g_skippingcin || !g_skippingcin->integer ) - { - Q3_SetDPitch( entID, viewangles[PITCH] ); + VectorSubtract(viewspot, selfspot, viewvec); + + vectoangles(viewvec, viewangles); + + Q3_SetDYaw(entID, viewangles[YAW]); + if (!g_skippingcin || !g_skippingcin->integer) { + Q3_SetDPitch(entID, viewangles[PITCH]); } } - /* ============ -Q3_SetWatchTarget - Description : - Return type : static void +Q3_SetWatchTarget + Description : + Return type : static void Argument : int entID Argument : const char *name ============ */ -static void Q3_SetWatchTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *watchTarget = NULL; +static void Q3_SetWatchTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *watchTarget = NULL; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname); return; } - - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name ) == 0 || ( self->targetname && (Q_stricmp( self->targetname, name ) == 0) ) ) - {//clearing watchTarget + + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0 || (self->targetname && (Q_stricmp(self->targetname, name) == 0))) { // clearing + // watchTarget self->NPC->watchTarget = NULL; } - watchTarget = G_Find( NULL, FOFS(targetname), (char *) name); - if ( watchTarget == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name ); + watchTarget = G_Find(NULL, FOFS(targetname), (char *)name); + if (watchTarget == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name); return; } - + self->NPC->watchTarget = watchTarget; } -void Q3_SetLoopSound(int entID, const char *name) -{ - sfxHandle_t index; - gentity_t *self = &g_entities[entID]; +void Q3_SetLoopSound(int entID, const char *name) { + sfxHandle_t index; + gentity_t *self = &g_entities[entID]; - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name )==0) - { + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0) { self->s.loopSound = 0; return; } - if ( self->s.eType == ET_MOVER ) - { - index = cgi_S_RegisterSound( name ); - } - else - { - index = G_SoundIndex( name ); + if (self->s.eType == ET_MOVER) { + index = cgi_S_RegisterSound(name); + } else { + index = G_SoundIndex(name); } - if (index) - { + if (index) { self->s.loopSound = index; - } - else - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name ); + } else { + Q3_DebugPrint(WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name); } } -void Q3_SetICARUSFreeze( int entID, const char *name, qboolean freeze ) -{ - gentity_t *self = G_Find( NULL, FOFS(targetname), name ); - if ( !self ) - {//hmm, targetname failed, try script_targetname? - self = G_Find( NULL, FOFS(script_targetname), name ); +void Q3_SetICARUSFreeze(int entID, const char *name, qboolean freeze) { + gentity_t *self = G_Find(NULL, FOFS(targetname), name); + if (!self) { // hmm, targetname failed, try script_targetname? + self = G_Find(NULL, FOFS(script_targetname), name); } - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); return; } - - if ( freeze ) - { + + if (freeze) { self->svFlags |= SVF_ICARUS_FREEZE; - } - else - { + } else { self->svFlags &= ~SVF_ICARUS_FREEZE; } } @@ -3250,466 +2819,398 @@ void Q3_SetICARUSFreeze( int entID, const char *name, qboolean freeze ) /* ============ Q3_SetViewEntity - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *name ============ */ -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -void Q3_SetViewEntity(int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *viewtarget = G_Find( NULL, FOFS(targetname), (char *) name); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +void Q3_SetViewEntity(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *viewtarget = G_Find(NULL, FOFS(targetname), (char *)name); - if ( entID != 0 ) - {//only valid on player - Q3_DebugPrint( WL_ERROR, "Q3_SetViewEntity: only valid on player\n", entID); + if (entID != 0) { // only valid on player + Q3_DebugPrint(WL_ERROR, "Q3_SetViewEntity: only valid on player\n", entID); return; } - if ( !self ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetViewEntity: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_ERROR, "Q3_SetViewEntity: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetViewEntity: '%s' is not a player!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetViewEntity: '%s' is not a player!\n", self->targetname); return; } - if ( !name ) - { - G_ClearViewEntity( self ); + if (!name) { + G_ClearViewEntity(self); return; } - - if ( viewtarget == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetViewEntity: can't find ViewEntity: '%s'\n", name ); + + if (viewtarget == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_SetViewEntity: can't find ViewEntity: '%s'\n", name); return; } - G_SetViewEntity( self, viewtarget ); + G_SetViewEntity(self, viewtarget); } /* ============ -Q3_SetWeapon - Description : - Return type : static void +Q3_SetWeapon + Description : + Return type : static void Argument : int entID Argument : const char *wp_name ============ */ -extern gentity_t *TossClientItems( gentity_t *self ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -extern void WP_SaberInitBladeData( gentity_t *ent ); -static void Q3_SetWeapon (int entID, const char *wp_name) -{ - gentity_t *self = &g_entities[entID]; - int wp; - qboolean hadWeapon = qfalse; +extern gentity_t *TossClientItems(gentity_t *self); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +extern void WP_SaberInitBladeData(gentity_t *ent); +static void Q3_SetWeapon(int entID, const char *wp_name) { + gentity_t *self = &g_entities[entID]; + int wp; + qboolean hadWeapon = qfalse; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname); return; } - if ( self->NPC ) - {//since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore + if (self->NPC) { // since a script sets a weapon, we presume we don't want to auto-match the player's weapon anymore self->NPC->aiFlags &= ~NPCAI_MATCHPLAYERWEAPON; } - if(!Q_stricmp("drop", wp_name)) - {//no weapon, drop it - TossClientItems( self ); + if (!Q_stricmp("drop", wp_name)) { // no weapon, drop it + TossClientItems(self); self->client->ps.weapon = WP_NONE; - if ( self->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->weaponModel ); + if (self->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel); self->weaponModel = -1; } return; } - wp = GetIDForString( WPTable, wp_name ); - if(wp == WP_NONE) - {//no weapon + wp = GetIDForString(WPTable, wp_name); + if (wp == WP_NONE) { // no weapon self->client->ps.weapon = WP_NONE; - if ( self->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->weaponModel ); + if (self->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel); self->weaponModel = -1; } return; } - gitem_t *item = FindItemForWeapon( (weapon_t) wp); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup + gitem_t *item = FindItemForWeapon((weapon_t)wp); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup - if ( self->client->ps.stats[STAT_WEAPONS]&( 1 << wp ) ) - { + if (self->client->ps.stats[STAT_WEAPONS] & (1 << wp)) { hadWeapon = qtrue; } - if ( self->NPC ) - {//Should NPCs have only 1 weapon at a time? - self->client->ps.stats[STAT_WEAPONS] = ( 1 << wp ); + if (self->NPC) { // Should NPCs have only 1 weapon at a time? + self->client->ps.stats[STAT_WEAPONS] = (1 << wp); self->client->ps.ammo[weaponData[wp].ammoIndex] = 999; - ChangeWeapon( self, wp ); + ChangeWeapon(self, wp); self->client->ps.weapon = wp; - self->client->ps.weaponstate = WEAPON_READY;//WEAPON_RAISING; - G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - } - else - { - self->client->ps.stats[STAT_WEAPONS] |= ( 1 << wp ); + self->client->ps.weaponstate = WEAPON_READY; // WEAPON_RAISING; + G_AddEvent(self, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); + } else { + self->client->ps.stats[STAT_WEAPONS] |= (1 << wp); self->client->ps.ammo[weaponData[wp].ammoIndex] = ammoData[weaponData[wp].ammoIndex].max; - G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); - //force it to change - CG_ChangeWeapon( wp ); - G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + G_AddEvent(self, EV_ITEM_PICKUP, (item - bg_itemlist)); + // force it to change + CG_ChangeWeapon(wp); + G_AddEvent(self, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); } - if ( self->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->weaponModel ); + if (self->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel); } - if ( wp == WP_SABER ) - { - if ( !hadWeapon ) - { - WP_SaberInitBladeData( self ); + if (wp == WP_SABER) { + if (!hadWeapon) { + WP_SaberInitBladeData(self); } - G_CreateG2AttachedWeaponModel( self, self->client->ps.saberModel ); - } - else - { - G_CreateG2AttachedWeaponModel( self, weaponData[wp].weaponMdl ); + G_CreateG2AttachedWeaponModel(self, self->client->ps.saberModel); + } else { + G_CreateG2AttachedWeaponModel(self, weaponData[wp].weaponMdl); } } /* ============ -Q3_SetItem - Description : - Return type : static void +Q3_SetItem + Description : + Return type : static void Argument : int entID Argument : const char *wp_name ============ */ -static void Q3_SetItem (int entID, const char *item_name) -{ - gentity_t *self = &g_entities[entID]; - int inv; +static void Q3_SetItem(int entID, const char *item_name) { + gentity_t *self = &g_entities[entID]; + int inv; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWeapon: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWeapon: '%s' is not a player/NPC!\n", self->targetname); return; } - inv = GetIDForString( INVTable, item_name ); + inv = GetIDForString(INVTable, item_name); - gitem_t *item = FindItemForInventory(inv); - RegisterItem( item ); //make sure the item is cached in case this runs at startup + RegisterItem(item); // make sure the item is cached in case this runs at startup -// G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); -// G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + // G_AddEvent( self, EV_ITEM_PICKUP, (item - bg_itemlist) ); + // G_AddEvent( self, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); - self->client->ps.stats[STAT_ITEMS] |= (1<giTag); + self->client->ps.stats[STAT_ITEMS] |= (1 << item->giTag); - if( (inv == INV_ELECTROBINOCULARS) || (inv == INV_LIGHTAMP_GOGGLES) ) - { + if ((inv == INV_ELECTROBINOCULARS) || (inv == INV_LIGHTAMP_GOGGLES)) { self->client->ps.inventory[inv] = 1; return; - } + } // else Bacta, seeker, sentry - if( self->client->ps.inventory[inv] < 5 ) - { + if (self->client->ps.inventory[inv] < 5) { self->client->ps.inventory[inv]++; } } - - /* ============ -Q3_SetWalkSpeed - Description : - Return type : static void +Q3_SetWalkSpeed + Description : + Return type : static void Argument : int entID Argument : int int_data ============ */ -static void Q3_SetWalkSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWalkSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.walkSpeed = self->client->ps.speed = 1; } self->NPC->stats.walkSpeed = self->client->ps.speed = int_data; } - /* ============ -Q3_SetRunSpeed - Description : - Return type : static void +Q3_SetRunSpeed + Description : + Return type : static void Argument : int entID Argument : int int_data ============ */ -static void Q3_SetRunSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRunSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.runSpeed = self->client->ps.speed = 1; } self->NPC->stats.runSpeed = self->client->ps.speed = int_data; } - /* ============ -Q3_SetYawSpeed - Description : - Return type : static void +Q3_SetYawSpeed + Description : + Return type : static void Argument : int entID Argument : float float_data ============ */ -static void Q3_SetYawSpeed (int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetYawSpeed(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->stats.yawSpeed = float_data; } - /* ============ Q3_SetAggression - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int int_data ============ */ -static void Q3_SetAggression(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetAggression(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aggression = int_data; } - /* ============ Q3_SetAim - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int int_data ============ */ -static void Q3_SetAim(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetAim(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aim = int_data; } - /* ============ Q3_SetFriction - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int int_data ============ */ -static void Q3_SetFriction(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFriction(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname); return; } self->client->ps.friction = int_data; } - /* ============ Q3_SetGravity - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float float_data ============ */ -static void Q3_SetGravity(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGravity(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); return; } - - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname ); + + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname); return; } - //FIXME: what if we want to return them to normal global gravity? + // FIXME: what if we want to return them to normal global gravity? self->svFlags |= SVF_CUSTOM_GRAVITY; self->client->ps.gravity = float_data; } - /* ============ Q3_SetWait - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float float_data ============ */ -static void Q3_SetWait(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWait(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); return; } - + self->wait = float_data; } +static void Q3_SetShotSpacing(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; -static void Q3_SetShotSpacing(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; - - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); return; } - - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname ); + + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname); return; } @@ -3720,92 +3221,79 @@ static void Q3_SetShotSpacing(int entID, int int_data) /* ============ Q3_SetFollowDist - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float float_data ============ */ -static void Q3_SetFollowDist(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFollowDist(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); return; } - - if ( !self->client || !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname ); + + if (!self->client || !self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->followDist = float_data; } - /* ============ Q3_SetScale - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : float float_data ============ */ -static void Q3_SetScale(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetScale(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); return; } - + self->s.scale = float_data; } - /* ============ Q3_SetCount - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *data ============ */ -static void Q3_SetCount(int entID, const char *data) -{ - gentity_t *self = &g_entities[entID]; - float val = 0.0f; +static void Q3_SetCount(int entID, const char *data) { + gentity_t *self = &g_entities[entID]; + float val = 0.0f; - //FIXME: use FOFS() stuff here to make a generic entity field setting? - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); + // FIXME: use FOFS() stuff here to make a generic entity field setting? + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); return; } - - if ( (val = Q3_CheckStringCounterIncrement( data )) ) - { + + if ((val = Q3_CheckStringCounterIncrement(data))) { self->count += (int)(val); - } - else - { - self->count = atoi((char *) data); + } else { + self->count = atoi((char *)data); } } - /* ============ -Q3_SetSquadName - Description : - Return type : static void +Q3_SetSquadName + Description : + Return type : static void Argument : int entID Argument : const char *squadname ============ @@ -3820,7 +3308,7 @@ static void Q3_SetSquadName (int entID, const char *squadname) Q3_DebugPrint( WL_WARNING, "Q3_SetSquadName: invalid entID %d\n", entID); return; } - + if ( !self->client ) { Q3_DebugPrint( WL_ERROR, "Q3_SetSquadName: '%s' is not an NPC/player!\n", self->targetname ); @@ -3840,30 +3328,25 @@ static void Q3_SetSquadName (int entID, const char *squadname) /* ============ -Q3_SetTargetName - Description : - Return type : static void +Q3_SetTargetName + Description : + Return type : static void Argument : int entID Argument : const char *targetname ============ */ -static void Q3_SetTargetName (int entID, const char *targetname) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTargetName(int entID, const char *targetname) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)targetname))) - { + if (!Q_stricmp("NULL", ((char *)targetname))) { self->targetname = NULL; - } - else - { - self->targetname = G_NewString( targetname ); + } else { + self->targetname = G_NewString(targetname); } /* @@ -3874,280 +3357,226 @@ static void Q3_SetTargetName (int entID, const char *targetname) */ } - /* ============ -Q3_SetTarget - Description : - Return type : static void +Q3_SetTarget + Description : + Return type : static void Argument : int entID Argument : const char *target ============ */ -static void Q3_SetTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)target))) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target = NULL; - } - else - { - self->target = G_NewString( target ); + } else { + self->target = G_NewString(target); } } /* ============ Q3_SetTarget2 - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : const char *target ============ */ -static void Q3_SetTarget2 (int entID, const char *target2) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTarget2(int entID, const char *target2) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetTarget2: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetTarget2: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)target2))) - { + if (!Q_stricmp("NULL", ((char *)target2))) { self->target2 = NULL; - } - else - { - self->target2 = G_NewString( target2 ); + } else { + self->target2 = G_NewString(target2); } } /* ============ -Q3_SetRemoveTarget - Description : - Return type : static void +Q3_SetRemoveTarget + Description : + Return type : static void Argument : int entID Argument : const char *target ============ */ -static void Q3_SetRemoveTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRemoveTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname); return; } - if( !Q_stricmp("NULL", ((char *)target)) ) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target3 = NULL; - } - else - { - self->target3 = G_NewString( target ); + } else { + self->target3 = G_NewString(target); } } - /* ============ -Q3_SetPainTarget - Description : - Return type : void +Q3_SetPainTarget + Description : + Return type : void Argument : int entID Argument : const char *targetname ============ */ -static void Q3_SetPainTarget (int entID, const char *targetname) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetPainTarget(int entID, const char *targetname) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetPainTarget: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetPainTarget: invalid entID %d\n", entID); return; } - if(Q_stricmp("NULL", ((char *)targetname)) == 0) - { + if (Q_stricmp("NULL", ((char *)targetname)) == 0) { self->paintarget = NULL; - } - else - { + } else { self->paintarget = G_NewString((char *)targetname); } } /* ============ -Q3_SetFullName - Description : - Return type : static void +Q3_SetFullName + Description : + Return type : static void Argument : int entID Argument : const char *fullName ============ */ -static void Q3_SetFullName (int entID, const char *fullName) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFullName(int entID, const char *fullName) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetFullName: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_WARNING, "Q3_SetFullName: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)fullName))) - { + if (!Q_stricmp("NULL", ((char *)fullName))) { self->fullName = NULL; - } - else - { - self->fullName = G_NewString( fullName ); + } else { + self->fullName = G_NewString(fullName); } } -static void Q3_SetMusicState( const char *dms ) -{ - int newDMS = GetIDForString( DMSTable, dms ); - if ( newDMS != -1 ) - { +static void Q3_SetMusicState(const char *dms) { + int newDMS = GetIDForString(DMSTable, dms); + if (newDMS != -1) { level.dmState = newDMS; } } -static void Q3_SetForcePowerLevel ( int entID, int forcePower, int forceLevel ) -{ - if ( forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, (NUM_FORCE_POWERS-1) ); +static void Q3_SetForcePowerLevel(int entID, int forcePower, int forceLevel) { + if (forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, (NUM_FORCE_POWERS - 1)); return; } - if ( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel ); + if (forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel); return; } - gentity_t *self = &g_entities[entID]; + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); + if (!self) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname ); + if (!self->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname); return; } - if ((forceLevel > self->client->ps.forcePowerLevel[forcePower]) && (entID==0) && (forceLevel > 0)) - { - if (!cg_updatedDataPadForcePower1.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower1.integer = forcePower+1; - } - else if (!cg_updatedDataPadForcePower2.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower2", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower2.integer = forcePower+1; - } - else if (!cg_updatedDataPadForcePower3.integer) - { - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower3", va("%d",forcePower+1)); // The +1 is offset in the print routine. It ain't pretty, I know. - cg_updatedDataPadForcePower3.integer = forcePower+1; + if ((forceLevel > self->client->ps.forcePowerLevel[forcePower]) && (entID == 0) && (forceLevel > 0)) { + if (!cg_updatedDataPadForcePower1.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower1", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower1.integer = forcePower + 1; + } else if (!cg_updatedDataPadForcePower2.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower2", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower2.integer = forcePower + 1; + } else if (!cg_updatedDataPadForcePower3.integer) { + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower3", va("%d", forcePower + 1)); // The +1 is offset in the print routine. It ain't pretty, I know. + cg_updatedDataPadForcePower3.integer = forcePower + 1; } } self->client->ps.forcePowerLevel[forcePower] = forceLevel; - if ( forceLevel ) - { - self->client->ps.forcePowersKnown |= ( 1 << forcePower ); - } - else - { - self->client->ps.forcePowersKnown &= ~( 1 << forcePower ); + if (forceLevel) { + self->client->ps.forcePowersKnown |= (1 << forcePower); + } else { + self->client->ps.forcePowersKnown &= ~(1 << forcePower); } } /* ============ Q3_SetParm - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : int parmNum Argument : const char *parmValue ============ */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue) -{ - gentity_t *ent = &g_entities[entID]; - float val; +void Q3_SetParm(int entID, int parmNum, const char *parmValue) { + gentity_t *ent = &g_entities[entID]; + float val; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); return; } - if ( parmNum < 0 || parmNum >= MAX_PARMS ) - { - Q3_DebugPrint( WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum ); + if (parmNum < 0 || parmNum >= MAX_PARMS) { + Q3_DebugPrint(WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum); return; } - if( !ent->parms ) - { - ent->parms = (parms_t *)G_Alloc( sizeof(parms_t) ); - memset( ent->parms, 0, sizeof(parms_t) ); + if (!ent->parms) { + ent->parms = (parms_t *)G_Alloc(sizeof(parms_t)); + memset(ent->parms, 0, sizeof(parms_t)); } - if ( (val = Q3_CheckStringCounterIncrement( parmValue )) ) - { - val += atof( ent->parms->parm[parmNum] ); - sprintf( ent->parms->parm[parmNum], "%f", val ); - } - else - {//Just copy the string - //copy only 16 characters - strncpy( ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[0]) ); - //set the last charcter to null in case we had to truncate their passed string - if ( ent->parms->parm[parmNum][sizeof(ent->parms->parm[0]) - 1] != 0 ) - {//Tried to set a string that is too long + if ((val = Q3_CheckStringCounterIncrement(parmValue))) { + val += atof(ent->parms->parm[parmNum]); + sprintf(ent->parms->parm[parmNum], "%f", val); + } else { // Just copy the string + // copy only 16 characters + strncpy(ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[0])); + // set the last charcter to null in case we had to truncate their passed string + if (ent->parms->parm[parmNum][sizeof(ent->parms->parm[0]) - 1] != 0) { // Tried to set a string that is too long ent->parms->parm[parmNum][sizeof(ent->parms->parm[0]) - 1] = 0; - Q3_DebugPrint( WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum] ); + Q3_DebugPrint(WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum]); } } } - - /* ============= Q3_SetCaptureGoal @@ -4155,36 +3584,31 @@ Q3_SetCaptureGoal Sets the capture spot goal of an entity ============= */ -static void Q3_SetCaptureGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *goal = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCaptureGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *goal = G_Find(NULL, FOFS(targetname), (char *)name); - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname); return; } - - //FIXME: Exception handle here - if (goal == NULL) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name ); + + // FIXME: Exception handle here + if (goal == NULL) { + Q3_DebugPrint(WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name); return; } - if(ent->NPC) - { + if (ent->NPC) { ent->NPC->captureGoal = goal; ent->NPC->goalEntity = goal; ent->NPC->goalTime = level.time + 100000; -// NAV_ClearLastRoute(ent); + // NAV_ClearLastRoute(ent); } } @@ -4195,43 +3619,40 @@ Q3_SetEvent ? ============= */ -static void Q3_SetEvent( int entID, const char *event_name ) -{ - gentity_t *ent = &g_entities[entID]; -// gentity_t *tent = NULL; - int event; -// vec3_t spot; +static void Q3_SetEvent(int entID, const char *event_name) { + gentity_t *ent = &g_entities[entID]; + // gentity_t *tent = NULL; + int event; + // vec3_t spot; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEvent: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEvent: invalid entID %d\n", entID); return; } - - event = GetIDForString( eventTable, event_name ); - switch( event ) - { -/* - case EV_DISINTEGRATE: - if( VectorCompare( ent->currentOrigin, vec3_origin ) ) - {//Brush with no origin - VectorSubtract( ent->absmax, ent->absmin, spot ); - VectorMA( ent->absmin, 0.5, spot, spot ); - } - else - { - VectorCopy( ent->currentOrigin, spot ); - spot[2] += ent->maxs[2]/2; - } - tent = G_TempEntity( spot, EV_DISINTEGRATION ); - tent->s.eventParm = PW_REGEN; - tent->owner = ent; - break; -*/ + event = GetIDForString(eventTable, event_name); + switch (event) { + /* + case EV_DISINTEGRATE: + if( VectorCompare( ent->currentOrigin, vec3_origin ) ) + {//Brush with no origin + VectorSubtract( ent->absmax, ent->absmin, spot ); + VectorMA( ent->absmin, 0.5, spot, spot ); + } + else + { + VectorCopy( ent->currentOrigin, spot ); + spot[2] += ent->maxs[2]/2; + } + tent = G_TempEntity( spot, EV_DISINTEGRATION ); + tent->s.eventParm = PW_REGEN; + tent->owner = ent; + break; + + */ case EV_BAD: default: - //Q3_DebugPrint( WL_ERROR,"Q3_SetEvent: Invalid Event %d\n", event ); + // Q3_DebugPrint( WL_ERROR,"Q3_SetEvent: Invalid Event %d\n", event ); return; break; } @@ -4244,26 +3665,22 @@ Q3_Use Uses an entity ============ */ -static void Q3_Use( int entID, const char *target ) -{ - gentity_t *ent = &g_entities[entID]; - - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Use: invalid entID %d\n", entID); +static void Q3_Use(int entID, const char *target) { + gentity_t *ent = &g_entities[entID]; + + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Use: invalid entID %d\n", entID); return; } - if( !target || !target[0] ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Use: string is NULL!\n" ); + if (!target || !target[0]) { + Q3_DebugPrint(WL_WARNING, "Q3_Use: string is NULL!\n"); return; } G_UseTargets2(ent, ent, target); } - /* ============ Q3_SetBehaviorSet @@ -4271,19 +3688,16 @@ Q3_SetBehaviorSet ? ============ */ -static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) -{ - gentity_t *ent = &g_entities[entID]; - bSet_t bSet = BSET_INVALID; +static qboolean Q3_SetBehaviorSet(int entID, int toSet, const char *scriptname) { + gentity_t *ent = &g_entities[entID]; + bSet_t bSet = BSET_INVALID; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); return qfalse; } - switch(toSet) - { + switch (toSet) { case SET_SPAWNSCRIPT: bSet = BSET_SPAWN; break; @@ -4331,35 +3745,28 @@ static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) break; } - if(bSet < BSET_SPAWN || bSet >= NUM_BSETS) - { + if (bSet < BSET_SPAWN || bSet >= NUM_BSETS) { return qfalse; } - if(!Q_stricmp("NULL", scriptname)) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// gi.TagFree( ent->behaviorSet[bSet] ); + if (!Q_stricmp("NULL", scriptname)) { + if (ent->behaviorSet[bSet] != NULL) { + // gi.TagFree( ent->behaviorSet[bSet] ); } ent->behaviorSet[bSet] = NULL; - //memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); - } - else - { - if ( scriptname ) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// gi.TagFree( ent->behaviorSet[bSet] ); + // memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); + } else { + if (scriptname) { + if (ent->behaviorSet[bSet] != NULL) { + // gi.TagFree( ent->behaviorSet[bSet] ); } - - ent->behaviorSet[bSet] = G_NewString( (char *) scriptname ); //FIXME: This really isn't good... + + ent->behaviorSet[bSet] = G_NewString((char *)scriptname); // FIXME: This really isn't good... } - //ent->behaviorSet[bSet] = scriptname; - //strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); + // ent->behaviorSet[bSet] = scriptname; + // strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); } return qtrue; } @@ -4371,20 +3778,17 @@ Q3_SetDelayScriptTime ? ============ */ -static void Q3_SetDelayScriptTime(int entID, int delayTime) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDelayScriptTime(int entID, int delayTime) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDelayScriptTime: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDelayScriptTime: invalid entID %d\n", entID); return; } ent->delayScriptTime = level.time + delayTime; } - /* ============ Q3_SetIgnorePain @@ -4392,19 +3796,16 @@ Q3_SetIgnorePain ? ============ */ -static void Q3_SetIgnorePain( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnorePain(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname); return; } @@ -4418,28 +3819,22 @@ Q3_SetIgnoreEnemies ? ============ */ -static void Q3_SetIgnoreEnemies( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnoreEnemies(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetIgnoreEnemies: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetIgnoreEnemies: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetIgnoreEnemies: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetIgnoreEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(data) - { + if (data) { ent->svFlags |= SVF_IGNORE_ENEMIES; - } - else - { + } else { ent->svFlags &= ~SVF_IGNORE_ENEMIES; } } @@ -4451,33 +3846,26 @@ Q3_SetIgnoreAlerts ? ============ */ -static void Q3_SetIgnoreAlerts( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnoreAlerts(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname); return; } - if(data) - { + if (data) { ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_IGNORE_ALERTS; } } - /* ============ Q3_SetNoTarget @@ -4485,17 +3873,15 @@ Q3_SetNoTarget ? ============ */ -static void Q3_SetNoTarget( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoTarget(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); return; } - if(data) + if (data) ent->flags |= FL_NOTARGET; else ent->flags &= ~FL_NOTARGET; @@ -4508,22 +3894,17 @@ Q3_SetDontShoot ? ============ */ -static void Q3_SetDontShoot( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontShoot(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); return; } - if(add) - { + if (add) { ent->flags |= FL_DONT_SHOOT; - } - else - { + } else { ent->flags &= ~FL_DONT_SHOOT; } } @@ -4535,28 +3916,22 @@ Q3_SetDontFire ? ============ */ -static void Q3_SetDontFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FIRE; } } @@ -4568,33 +3943,26 @@ Q3_SetFireWeapon ? ============ */ -static void Q3_SetFireWeapon(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFireWeapon(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); return; } - - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname ); + + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FIRE_WEAPON; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FIRE_WEAPON; } } - /* ============ Q3_SetInactive @@ -4602,22 +3970,17 @@ Q3_SetInactive ? ============ */ -static void Q3_SetInactive(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInactive(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); return; } - - if(add) - { + + if (add) { ent->svFlags |= SVF_INACTIVE; - } - else - { + } else { ent->svFlags &= ~SVF_INACTIVE; } } @@ -4629,26 +3992,21 @@ Q3_SetFuncUsableVisible ? ============ */ -static void Q3_SetFuncUsableVisible(int entID, qboolean visible ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFuncUsableVisible(int entID, qboolean visible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); return; } - + // Yeah, I know that this doesn't even do half of what the func_usable use code does, but if I've got two things on top of each other...and only // one is visible at a time....and neither can ever be used......and finally, the shader on it has the shader_anim stuff going on....It doesn't seem // like I can easily use the other version without nasty side effects. - if( visible ) - { + if (visible) { ent->svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; - } - else - { + } else { ent->svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; } @@ -4661,29 +4019,23 @@ Q3_SetLockedEnemy ? ============ */ -static void Q3_SetLockedEnemy ( int entID, qboolean locked) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLockedEnemy(int entID, qboolean locked) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLockedEnemy: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLockedEnemy: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetLockedEnemy: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetLockedEnemy: '%s' is not an NPC!\n", ent->targetname); return; } - - //FIXME: make an NPCAI_FLAG - if(locked) - { + + // FIXME: make an NPCAI_FLAG + if (locked) { ent->svFlags |= SVF_LOCKEDENEMY; - } - else - { + } else { ent->svFlags &= ~SVF_LOCKEDENEMY; } } @@ -4696,18 +4048,13 @@ Q3_SetCinematicSkipScript ============ */ -static void Q3_SetCinematicSkipScript( char *scriptname ) -{ +static void Q3_SetCinematicSkipScript(char *scriptname) { - if(Q_stricmp("none", scriptname) == 0 || Q_stricmp("NULL", scriptname) == 0) - { - memset( cinematicSkipScript, 0, sizeof( cinematicSkipScript ) ); - } - else - { - Q_strncpyz(cinematicSkipScript,scriptname,sizeof(cinematicSkipScript)); + if (Q_stricmp("none", scriptname) == 0 || Q_stricmp("NULL", scriptname) == 0) { + memset(cinematicSkipScript, 0, sizeof(cinematicSkipScript)); + } else { + Q_strncpyz(cinematicSkipScript, scriptname, sizeof(cinematicSkipScript)); } - } /* @@ -4717,29 +4064,23 @@ Q3_SetNoMindTrick ? ============ */ -static void Q3_SetNoMindTrick( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoMindTrick(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoMindTrick: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoMindTrick: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoMindTrick: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoMindTrick: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_MIND_TRICK; ent->NPC->confusionTime = 0; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_MIND_TRICK; } } @@ -4751,28 +4092,22 @@ Q3_SetCrouched ? ============ */ -static void Q3_SetCrouched( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetCrouched(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CROUCHED; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CROUCHED; } } @@ -4784,28 +4119,22 @@ Q3_SetWalking ? ============ */ -static void Q3_SetWalking( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetWalking(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_WALKING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_WALKING; } } @@ -4817,28 +4146,22 @@ Q3_SetRunning ? ============ */ -static void Q3_SetRunning( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRunning(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_RUNNING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_RUNNING; } } @@ -4850,28 +4173,22 @@ Q3_SetForcedMarch ? ============ */ -static void Q3_SetForcedMarch( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForcedMarch(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FORCED_MARCH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FORCED_MARCH; } } @@ -4879,31 +4196,25 @@ static void Q3_SetForcedMarch( int entID, qboolean add) ============ Q3_SetChaseEnemies -indicates whether the npc should chase after an enemy +indicates whether the npc should chase after an enemy ============ */ -static void Q3_SetChaseEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetChaseEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CHASE_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CHASE_ENEMIES; } } @@ -4916,28 +4227,22 @@ if set npc will be on the look out for potential enemies if not set, npc will ignore enemies ============ */ -static void Q3_SetLookForEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLookForEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_LOOK_FOR_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; } } @@ -4948,28 +4253,22 @@ Q3_SetFaceMoveDir ============ */ -static void Q3_SetFaceMoveDir( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFaceMoveDir(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FACE_MOVE_DIR; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FACE_MOVE_DIR; } } @@ -4981,33 +4280,26 @@ Q3_SetAltFire ? ============ */ -static void Q3_SetAltFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAltFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_ALT_FIRE; } - ChangeWeapon( ent, ent->client->ps.weapon ); - + ChangeWeapon(ent, ent->client->ps.weapon); } /* @@ -5017,28 +4309,22 @@ Q3_SetDontFlee ? ============ */ -static void Q3_SetDontFlee( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFlee(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FLEE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FLEE; } } @@ -5050,28 +4336,22 @@ Q3_SetNoResponse ? ============ */ -static void Q3_SetNoResponse( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoResponse(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_RESPONSE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_RESPONSE; } } @@ -5083,28 +4363,22 @@ Q3_SetCombatTalk ? ============ */ -static void Q3_SetCombatTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetCombatTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; } } @@ -5116,28 +4390,22 @@ Q3_SetAlertTalk ? ============ */ -static void Q3_SetAlertTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAlertTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ALERT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ALERT_TALK; } } @@ -5149,28 +4417,22 @@ Q3_SetUseCpNearest ? ============ */ -static void Q3_SetUseCpNearest( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUseCpNearest(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_USE_CP_NEAREST; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_USE_CP_NEAREST; } } @@ -5182,28 +4444,22 @@ Q3_SetNoForce ? ============ */ -static void Q3_SetNoForce( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoForce(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FORCE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FORCE; } } @@ -5215,28 +4471,22 @@ Q3_SetNoAcrobatics ? ============ */ -static void Q3_SetNoAcrobatics( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAcrobatics(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ACROBATICS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ACROBATICS; } } @@ -5248,28 +4498,22 @@ Q3_SetUseSubtitles ? ============ */ -static void Q3_SetUseSubtitles( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUseSubtitles(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetUseSubtitles: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetUseSubtitles: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetUseSubtitles: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetUseSubtitles: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_USE_SUBTITLES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_USE_SUBTITLES; } } @@ -5281,28 +4525,22 @@ Q3_SetNoFallToDeath ? ============ */ -static void Q3_SetNoFallToDeath( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoFallToDeath(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FALLTODEATH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FALLTODEATH; } } @@ -5314,26 +4552,22 @@ Q3_SetDismemberable ? ============ */ -static void Q3_SetDismemberable( int entID, qboolean dismemberable) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDismemberable(int entID, qboolean dismemberable) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDismemberable: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDismemberable: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetDismemberable: '%s' is not an client!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetDismemberable: '%s' is not an client!\n", ent->targetname); return; } ent->client->dismembered = (qboolean)(!dismemberable); } - /* ============ Q3_SetMoreLight @@ -5341,28 +4575,22 @@ Q3_SetMoreLight ? ============ */ -static void Q3_SetMoreLight( int entID, qboolean add ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetMoreLight(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetMoreLight: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetMoreLight: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetMoreLight: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetMoreLight: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_MORELIGHT; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_MORELIGHT; } } @@ -5374,22 +4602,17 @@ Q3_SetUndying ? ============ */ -static void Q3_SetUndying( int entID, qboolean undying) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUndying(int entID, qboolean undying) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); return; } - if(undying) - { + if (undying) { ent->flags |= FL_UNDYING; - } - else - { + } else { ent->flags &= ~FL_UNDYING; } } @@ -5401,64 +4624,50 @@ Q3_SetInvincible ? ============ */ -static void Q3_SetInvincible( int entID, qboolean invincible) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInvincible(int entID, qboolean invincible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); return; } - if ( !Q_stricmp( "func_breakable", ent->classname ) ) - { - if ( invincible ) - { + if (!Q_stricmp("func_breakable", ent->classname)) { + if (invincible) { ent->spawnflags |= 1; - } - else - { + } else { ent->spawnflags &= ~1; } return; } - - if ( invincible ) - { + + if (invincible) { ent->flags |= FL_GODMODE; - } - else - { + } else { ent->flags &= ~FL_GODMODE; } } /* ============ Q3_SetForceInvincible - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : qboolean forceInv ============ */ -static void Q3_SetForceInvincible( int entID, qboolean forceInv ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetForceInvincible(int entID, qboolean forceInv) { + gentity_t *self = &g_entities[entID]; - if ( !self || !self->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetForceInvincible: entID %d not a client\n", entID); + if (!self || !self->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetForceInvincible: entID %d not a client\n", entID); return; } - - Q3_SetInvincible( entID, forceInv ); - if ( forceInv ) - { + + Q3_SetInvincible(entID, forceInv); + if (forceInv) { self->client->ps.powerups[PW_INVINCIBLE] = Q3_INFINITE; - } - else - { + } else { self->client->ps.powerups[PW_INVINCIBLE] = 0; } } @@ -5470,28 +4679,22 @@ Q3_SetNoAvoid ? ============ */ -static void Q3_SetNoAvoid( int entID, qboolean noAvoid) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAvoid(int entID, qboolean noAvoid) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname); return; } - if(noAvoid) - { + if (noAvoid) { ent->NPC->aiFlags |= NPCAI_NO_COLL_AVOID; - } - else - { + } else { ent->NPC->aiFlags &= ~NPCAI_NO_COLL_AVOID; } } @@ -5499,39 +4702,32 @@ static void Q3_SetNoAvoid( int entID, qboolean noAvoid) /* ============ SolidifyOwner - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *self ============ */ -void SolidifyOwner( gentity_t *self ) -{ +void SolidifyOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } int oldContents = self->owner->contents; self->owner->contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( self->owner, self->owner->currentOrigin ) ) - { + if (SpotWouldTelefrag2(self->owner, self->owner->currentOrigin)) { self->owner->contents = oldContents; self->e_ThinkFunc = thinkF_SolidifyOwner; - } - else - { - if ( self->owner->NPC && !(self->owner->spawnflags & SFB_NOTSOLID) ) - { + } else { + if (self->owner->NPC && !(self->owner->spawnflags & SFB_NOTSOLID)) { self->owner->clipmask |= CONTENTS_BODY; } - Q3_TaskIDComplete( self->owner, TID_RESIZE ); + Q3_TaskIDComplete(self->owner, TID_RESIZE); } } - /* ============ Q3_SetSolid @@ -5539,48 +4735,37 @@ Q3_SetSolid ? ============ */ -static qboolean Q3_SetSolid( int entID, qboolean solid) -{ - gentity_t *ent = &g_entities[entID]; - - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); +static qboolean Q3_SetSolid(int entID, qboolean solid) { + gentity_t *ent = &g_entities[entID]; + + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); return qtrue; } - if ( solid ) - {//FIXME: Presumption + if (solid) { // FIXME: Presumption int oldContents = ent->contents; ent->contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( ent, ent->currentOrigin ) ) - { + if (SpotWouldTelefrag2(ent, ent->currentOrigin)) { gentity_t *solidifier = G_Spawn(); solidifier->owner = ent; solidifier->e_ThinkFunc = thinkF_SolidifyOwner; solidifier->nextthink = level.time + FRAMETIME; - + ent->contents = oldContents; return qfalse; } ent->clipmask |= CONTENTS_BODY; - } - else - {//FIXME: Presumption - if ( ent->s.eFlags & EF_NODRAW ) - {//We're invisible too, so set contents to none + } else { // FIXME: Presumption + if (ent->s.eFlags & EF_NODRAW) { // We're invisible too, so set contents to none ent->contents = 0; - } - else - { + } else { ent->contents = CONTENTS_CORPSE; } - if ( ent->NPC ) - { - if(!(ent->spawnflags & SFB_NOTSOLID)) - { + if (ent->NPC) { + if (!(ent->spawnflags & SFB_NOTSOLID)) { ent->clipmask &= ~CONTENTS_BODY; } } @@ -5594,37 +4779,29 @@ Q3_SetLean ? ============ */ -#define LEAN_NONE 0 -#define LEAN_RIGHT 1 -#define LEAN_LEFT 2 -static void Q3_SetLean( int entID, int lean) -{ - gentity_t *ent = &g_entities[entID]; +#define LEAN_NONE 0 +#define LEAN_RIGHT 1 +#define LEAN_LEFT 2 +static void Q3_SetLean(int entID, int lean) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLean: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLean: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetLean: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetLean: '%s' is not an NPC!\n", ent->targetname); return; } - if(lean == LEAN_RIGHT) - { + if (lean == LEAN_RIGHT) { ent->NPC->scriptFlags |= SCF_LEAN_RIGHT; ent->NPC->scriptFlags &= ~SCF_LEAN_LEFT; - } - else if(lean == LEAN_LEFT) - { + } else if (lean == LEAN_LEFT) { ent->NPC->scriptFlags |= SCF_LEAN_LEFT; ent->NPC->scriptFlags &= ~SCF_LEAN_RIGHT; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_LEAN_LEFT; ent->NPC->scriptFlags &= ~SCF_LEAN_RIGHT; } @@ -5637,19 +4814,16 @@ Q3_SetForwardMove ? ============ */ -static void Q3_SetForwardMove( int entID, int fmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForwardMove(int entID, int fmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname); return; } @@ -5663,19 +4837,16 @@ Q3_SetRightMove ? ============ */ -static void Q3_SetRightMove( int entID, int rmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRightMove(int entID, int rmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname); return; } @@ -5689,57 +4860,42 @@ Q3_SetLockAngle ? ============ */ -static void Q3_SetLockAngle( int entID, const char *lockAngle) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLockAngle(int entID, const char *lockAngle) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname); return; } - if(Q_stricmp("off", lockAngle) == 0) - {//free it + if (Q_stricmp("off", lockAngle) == 0) { // free it ent->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; - } - else - { + } else { ent->client->renderInfo.renderFlags |= RF_LOCKEDANGLE; - - if(Q_stricmp("auto", lockAngle) == 0) - {//use current yaw - if( ent->NPC ) // I need this to work on NPCs, so their locked value - { - ent->NPC->lockedDesiredYaw = NPC->client->ps.viewangles[YAW]; // could also set s.angles[1] and desiredYaw to this value... - } - else + if (Q_stricmp("auto", lockAngle) == 0) { // use current yaw + if (ent->NPC) // I need this to work on NPCs, so their locked value { - ent->client->renderInfo.lockYaw = ent->client->ps.viewangles[YAW]; - } - } - else - {//specified yaw - if( ent->NPC ) // I need this to work on NPCs, so their locked value - { - ent->NPC->lockedDesiredYaw = atof((char *)lockAngle); // could also set s.angles[1] and desiredYaw to this value... + ent->NPC->lockedDesiredYaw = NPC->client->ps.viewangles[YAW]; // could also set s.angles[1] and desiredYaw to this value... + } else { + ent->client->renderInfo.lockYaw = ent->client->ps.viewangles[YAW]; } - else + } else { // specified yaw + if (ent->NPC) // I need this to work on NPCs, so their locked value { + ent->NPC->lockedDesiredYaw = atof((char *)lockAngle); // could also set s.angles[1] and desiredYaw to this value... + } else { ent->client->renderInfo.lockYaw = atof((char *)lockAngle); } } } } - /* ============ Q3_CameraGroup @@ -5747,20 +4903,18 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroup( int entID, char *camG) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_CameraGroup(int entID, char *camG) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_CameraGroup: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_CameraGroup: invalid entID %d\n", entID); return; } ent->cameraGroup = G_NewString(camG); } -extern camera_t client_camera; +extern camera_t client_camera; /* ============ Q3_CameraGroupZOfs @@ -5768,10 +4922,7 @@ Q3_CameraGroupZOfs ? ============ */ -static void Q3_CameraGroupZOfs( float camGZOfs ) -{ - client_camera.cameraGroupZOfs = camGZOfs; -} +static void Q3_CameraGroupZOfs(float camGZOfs) { client_camera.cameraGroupZOfs = camGZOfs; } /* ============ Q3_CameraGroup @@ -5779,23 +4930,18 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroupTag( char *camGTag ) -{ - Q_strncpyz( client_camera.cameraGroupTag, camGTag, sizeof(client_camera.cameraGroupTag) ); -} +static void Q3_CameraGroupTag(char *camGTag) { Q_strncpyz(client_camera.cameraGroupTag, camGTag, sizeof(client_camera.cameraGroupTag)); } /* ============ Q3_RemoveRHandModel ============ */ -static void Q3_RemoveRHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_RemoveRHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - if ( ent->cinematicModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model(ent->ghoul2,ent->cinematicModel); + if (ent->cinematicModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->cinematicModel); } } @@ -5804,16 +4950,13 @@ static void Q3_RemoveRHandModel( int entID, char *addModel) Q3_AddRHandModel ============ */ -static void Q3_AddRHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_AddRHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex( addModel ), NULL_HANDLE, NULL_HANDLE, 0, 0); - if ( ent->cinematicModel != -1 ) - { + ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex(addModel), NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->cinematicModel != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], - ent->handRBolt, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], ent->handRBolt, ent->playerModel); } } @@ -5822,16 +4965,13 @@ static void Q3_AddRHandModel( int entID, char *addModel) Q3_AddLHandModel ============ */ -static void Q3_AddLHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_AddLHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex( addModel ), NULL_HANDLE, NULL_HANDLE, 0, 0); - if ( ent->cinematicModel != -1 ) - { + ent->cinematicModel = gi.G2API_InitGhoul2Model(ent->ghoul2, addModel, G_ModelIndex(addModel), NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->cinematicModel != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], - ent->handLBolt, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->cinematicModel], &ent->ghoul2[ent->playerModel], ent->handLBolt, ent->playerModel); } } @@ -5840,12 +4980,10 @@ static void Q3_AddLHandModel( int entID, char *addModel) Q3_RemoveLHandModel ============ */ -static void Q3_RemoveLHandModel( int entID, char *addModel) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_RemoveLHandModel(int entID, char *addModel) { + gentity_t *ent = &g_entities[entID]; - if ( ent->cinematicModel >= 0 ) - { + if (ent->cinematicModel >= 0) { gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->cinematicModel); } } @@ -5857,36 +4995,31 @@ Q3_LookTarget ? ============ */ -static void Q3_LookTarget( int entID, char *targetName) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_LookTarget(int entID, char *targetName) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname); return; } - if(Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) - {//clearing look target - NPC_ClearLookTarget( ent ); + if (Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) { // clearing look target + NPC_ClearLookTarget(ent); return; } - gentity_t *targ = G_Find(NULL, FOFS(targetname), targetName); - if(!targ) - { - Q3_DebugPrint( WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName ); + gentity_t *targ = G_Find(NULL, FOFS(targetname), targetName); + if (!targ) { + Q3_DebugPrint(WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName); return; } - NPC_SetLookTarget( ent, targ->s.number, 0 ); + NPC_SetLookTarget(ent, targ->s.number, 0); } /* @@ -5896,27 +5029,23 @@ Q3_Face ? ============ */ -static void Q3_Face( int entID,int expression, float holdtime) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_Face(int entID, int expression, float holdtime) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Face: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_Face: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Face: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_Face: '%s' is not an NPC/player!\n", ent->targetname); return; } - - //FIXME: change to milliseconds to be consistant! + + // FIXME: change to milliseconds to be consistant! holdtime *= 1000; - switch(expression) - { + switch (expression) { case SET_FACEEYESCLOSED: ent->client->facial_blink = 1; break; @@ -5956,35 +5085,28 @@ static void Q3_Face( int entID,int expression, float holdtime) ent->client->facial_frown = level.time + holdtime + Q_flrand(6000.0, 10000.0); break; } - } - /* ============ Q3_SetPlayerUsable - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean usable ============ */ -static void Q3_SetPlayerUsable( int entID, qboolean usable ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetPlayerUsable(int entID, qboolean usable) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); return; } - if(usable) - { + if (usable) { ent->svFlags |= SVF_PLAYER_USABLE; - } - else - { + } else { ent->svFlags &= ~SVF_PLAYER_USABLE; } } @@ -5992,28 +5114,23 @@ static void Q3_SetPlayerUsable( int entID, qboolean usable ) /* ============ Q3_SetDisableShaderAnims - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int disabled ============ */ -static void Q3_SetDisableShaderAnims( int entID, int disabled ) -{ +static void Q3_SetDisableShaderAnims(int entID, int disabled) { gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetDisableShaderAnims: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetDisableShaderAnims: invalid entID %d\n", entID); return; } - if ( disabled ) - { + if (disabled) { ent->s.eFlags |= EF_DISABLE_SHADER_ANIM; - } - else - { + } else { ent->s.eFlags &= ~EF_DISABLE_SHADER_ANIM; } } @@ -6021,28 +5138,23 @@ static void Q3_SetDisableShaderAnims( int entID, int disabled ) /* ============ Q3_SetShaderAnim - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int disabled ============ */ -static void Q3_SetShaderAnim( int entID, int disabled ) -{ +static void Q3_SetShaderAnim(int entID, int disabled) { gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetShaderAnim: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetShaderAnim: invalid entID %d\n", entID); return; } - if ( disabled ) - { + if (disabled) { ent->s.eFlags |= EF_SHADER_ANIM; - } - else - { + } else { ent->s.eFlags &= ~EF_SHADER_ANIM; } } @@ -6050,63 +5162,54 @@ static void Q3_SetShaderAnim( int entID, int disabled ) /* ============ Q3_SetStartFrame - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int startFrame ============ */ -static void Q3_SetStartFrame( int entID, int startFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetStartFrame(int entID, int startFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetStartFrame: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetStartFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n" ); + if (ent->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n"); return; } - if ( startFrame >= 0 ) - { + if (startFrame >= 0) { ent->s.frame = startFrame; ent->startFrame = startFrame; } } - /* ============ Q3_SetEndFrame - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int endFrame ============ */ -static void Q3_SetEndFrame( int entID, int endFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEndFrame(int entID, int endFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEndFrame: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEndFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetEndFrame: command not valid on players/NPCs!\n" ); + if (ent->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetEndFrame: command not valid on players/NPCs!\n"); return; } - if ( endFrame >= 0 ) - { + if (endFrame >= 0) { ent->endFrame = endFrame; } } @@ -6114,134 +5217,112 @@ static void Q3_SetEndFrame( int entID, int endFrame ) /* ============ Q3_SetAnimFrame - Description : - Return type : static void + Description : + Return type : static void Argument : int entID Argument : int startFrame ============ */ -static void Q3_SetAnimFrame( int entID, int animFrame ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAnimFrame(int entID, int animFrame) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimFrame: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimFrame: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimFrame: command not valid on players/NPCs!\n" ); + if (ent->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimFrame: command not valid on players/NPCs!\n"); return; } - if ( animFrame >= ent->endFrame ) - { + if (animFrame >= ent->endFrame) { ent->s.frame = ent->endFrame; - } - else if ( animFrame >= ent->startFrame ) - { + } else if (animFrame >= ent->startFrame) { ent->s.frame = animFrame; - } - else - { + } else { // FIXME/NOTE: Set s.frame anyway?? - Q3_DebugPrint( WL_WARNING, "Q3_SetAnimFrame: value must be valid number between StartFrame and EndFrame.\n" ); + Q3_DebugPrint(WL_WARNING, "Q3_SetAnimFrame: value must be valid number between StartFrame and EndFrame.\n"); return; } } -void InflateOwner( gentity_t *self ) -{ +void InflateOwner(gentity_t *self) { self->nextthink = level.time + FRAMETIME; self->e_ThinkFunc = thinkF_G_FreeEntity; - if ( !self->owner || !self->owner->inuse ) - { + if (!self->owner || !self->owner->inuse) { return; } - trace_t trace; + trace_t trace; - gi.trace( &trace, self->currentOrigin, self->mins, self->maxs, self->currentOrigin, self->owner->s.number, self->owner->clipmask&~(CONTENTS_SOLID|CONTENTS_MONSTERCLIP), G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid ) - { + gi.trace(&trace, self->currentOrigin, self->mins, self->maxs, self->currentOrigin, self->owner->s.number, + self->owner->clipmask & ~(CONTENTS_SOLID | CONTENTS_MONSTERCLIP), G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid) { self->e_ThinkFunc = thinkF_InflateOwner; return; } - if ( Q3_TaskIDPending( self->owner, TID_RESIZE ) ) - { - Q3_TaskIDComplete( self->owner, TID_RESIZE ); + if (Q3_TaskIDPending(self->owner, TID_RESIZE)) { + Q3_TaskIDComplete(self->owner, TID_RESIZE); - VectorCopy( self->mins, self->owner->mins ); - VectorCopy( self->maxs, self->owner->maxs ); - gi.linkentity( self->owner ); + VectorCopy(self->mins, self->owner->mins); + VectorCopy(self->maxs, self->owner->maxs); + gi.linkentity(self->owner); } } - /* ============ Q3_SetLoopAnim - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean loopAnim ============ */ -static void Q3_SetLoopAnim( int entID, qboolean loopAnim ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLoopAnim(int entID, qboolean loopAnim) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLoopAnim: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLoopAnim: invalid entID %d\n", entID); return; } - if ( ent->client ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n" ); + if (ent->client) { + Q3_DebugPrint(WL_WARNING, "Q3_SetLoopAnim: command not valid on players/NPCs!\n"); return; } ent->loopAnim = loopAnim; } - /* ============ Q3_SetShields - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean shields ============ */ -static void Q3_SetShields( int entID, qboolean shields ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShields(int entID, qboolean shields) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetShields: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetShields: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetShields: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + Q3_DebugPrint(WL_ERROR, "Q3_SetShields: '%s' is not an NPC!\n", ent->targetname); return; } - if ( shields ) - { + if (shields) { ent->NPC->aiFlags |= NPCAI_SHIELDS; - } - else - { + } else { ent->NPC->aiFlags &= ~NPCAI_SHIELDS; } } @@ -6249,62 +5330,53 @@ static void Q3_SetShields( int entID, qboolean shields ) /* ============ Q3_SetSaberActive - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean shields ============ */ -static void Q3_SetSaberActive( int entID, qboolean active ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetSaberActive(int entID, qboolean active) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetSaberActive: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetSaberActive: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetSaberActive: '%s' is not an player/NPC!\n", ent->targetname ); + if (!ent->client) { + Q3_DebugPrint(WL_ERROR, "Q3_SetSaberActive: '%s' is not an player/NPC!\n", ent->targetname); return; } - if ( ent->client->ps.weapon != WP_SABER ) - { - Q3_DebugPrint( WL_ERROR, "Q3_SetSaberActive: '%s' is not using a saber!\n", ent->targetname ); + if (ent->client->ps.weapon != WP_SABER) { + Q3_DebugPrint(WL_ERROR, "Q3_SetSaberActive: '%s' is not using a saber!\n", ent->targetname); return; } - //FIXME: need an externalized call for the sound and any other internal changes? + // FIXME: need an externalized call for the sound and any other internal changes? ent->client->ps.saberActive = active; } /* ============ Q3_SetNoKnockback - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean noKnockback ============ */ -static void Q3_SetNoKnockback( int entID, qboolean noKnockback ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoKnockback(int entID, qboolean noKnockback) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - Q3_DebugPrint( WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); + if (!ent) { + Q3_DebugPrint(WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); return; } - if ( noKnockback ) - { + if (noKnockback) { ent->flags |= FL_NO_KNOCKBACK; - } - else - { + } else { ent->flags &= ~FL_NO_KNOCKBACK; } } @@ -6312,105 +5384,87 @@ static void Q3_SetNoKnockback( int entID, qboolean noKnockback ) /* ============ Q3_SetCleanDamagingEnts - Description : - Return type : void + Description : + Return type : void ============ */ -static void Q3_SetCleanDamagingEnts( void ) -{ +static void Q3_SetCleanDamagingEnts(void) { gentity_t *ent = NULL; - for ( int i = 0; i < ENTITYNUM_WORLD; i++ ) - { - if ( !PInUse( i )) - { + for (int i = 0; i < ENTITYNUM_WORLD; i++) { + if (!PInUse(i)) { continue; } ent = &g_entities[i]; - if ( ent ) - { - if ( !ent->client && ( ent->s.weapon == WP_DET_PACK || ent->s.weapon == WP_TRIP_MINE || ent->s.weapon == WP_THERMAL )) - { + if (ent) { + if (!ent->client && (ent->s.weapon == WP_DET_PACK || ent->s.weapon == WP_TRIP_MINE || ent->s.weapon == WP_THERMAL)) { // check for a client, otherwise we could remove someone holding this weapon - G_FreeEntity( ent ); - } - else if ( ent->s.weapon == WP_TURRET && ent->activator && ent->activator->s.number == 0 && !Q_stricmp( "PAS", ent->classname )) - { + G_FreeEntity(ent); + } else if (ent->s.weapon == WP_TURRET && ent->activator && ent->activator->s.number == 0 && !Q_stricmp("PAS", ent->classname)) { // is a player owner personal assault sentry gun. - G_FreeEntity( ent ); - } - else if ( ent->client && ent->client->NPC_class == CLASS_SEEKER ) - { + G_FreeEntity(ent); + } else if (ent->client && ent->client->NPC_class == CLASS_SEEKER) { // they blow up when they run out of ammo, so this may as well just do the same. - G_Damage( ent, ent, ent, NULL, NULL, 999, 0, MOD_UNKNOWN ); + G_Damage(ent, ent, ent, NULL, NULL, 999, 0, MOD_UNKNOWN); } } } } - /* ============ Q3_SetInterface - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : const char *data ============ */ -static void Q3_SetInterface( int entID, const char *data ) -{ - gi.cvar_set("cg_drawStatus", data); -} +static void Q3_SetInterface(int entID, const char *data) { gi.cvar_set("cg_drawStatus", data); } /* ============ Q3_SetLocation - Description : - Return type : qboolean + Description : + Return type : qboolean Argument : int entID Argument : const char *location ============ */ -static qboolean Q3_SetLocation( int entID, const char *location ) -{ - gentity_t *ent = &g_entities[entID]; - char *currentLoc; - - if ( !ent ) - { +static qboolean Q3_SetLocation(int entID, const char *location) { + gentity_t *ent = &g_entities[entID]; + char *currentLoc; + + if (!ent) { return qtrue; } - currentLoc = G_GetLocationForEnt( ent ); - if ( currentLoc && currentLoc[0] && Q_stricmp( location, currentLoc ) == 0 ) - { + currentLoc = G_GetLocationForEnt(ent); + if (currentLoc && currentLoc[0] && Q_stricmp(location, currentLoc) == 0) { return qtrue; } - ent->message = G_NewString( location ); + ent->message = G_NewString(location); return qfalse; } /* ============ Q3_SetPlayerLocked - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean locked ============ */ -qboolean player_locked = qfalse; -static void Q3_SetPlayerLocked( int entID, qboolean locked ) -{ - gentity_t *ent = &g_entities[0]; +qboolean player_locked = qfalse; +static void Q3_SetPlayerLocked(int entID, qboolean locked) { + gentity_t *ent = &g_entities[0]; player_locked = locked; - if ( ent && ent->client ) - {//stop him too + if (ent && ent->client) { // stop him too VectorClear(ent->client->ps.velocity); } } @@ -6418,549 +5472,514 @@ static void Q3_SetPlayerLocked( int entID, qboolean locked ) /* ============ Q3_SetLockPlayerWeapons - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean locked ============ */ -static void Q3_SetLockPlayerWeapons( int entID, qboolean locked ) -{ - gentity_t *ent = &g_entities[0]; +static void Q3_SetLockPlayerWeapons(int entID, qboolean locked) { + gentity_t *ent = &g_entities[0]; ent->flags &= ~FL_LOCK_PLAYER_WEAPONS; - if( locked ) - { + if (locked) { ent->flags |= FL_LOCK_PLAYER_WEAPONS; } - } - /* ============ Q3_SetNoImpactDamage - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : qboolean locked ============ */ -static void Q3_SetNoImpactDamage( int entID, qboolean noImp ) -{ - gentity_t *ent = &g_entities[0]; +static void Q3_SetNoImpactDamage(int entID, qboolean noImp) { + gentity_t *ent = &g_entities[0]; ent->flags &= ~FL_NO_IMPACT_DMG; - if( noImp ) - { + if (noImp) { ent->flags |= FL_NO_IMPACT_DMG; } - } -extern void CG_CameraAutoAim( const char *name ); -extern void CG_CameraAutoTrack( const char *name ); +extern void CG_CameraAutoAim(const char *name); +extern void CG_CameraAutoTrack(const char *name); /* ============ Q3_SetVar - Description : - Return type : static void + Description : + Return type : static void Argument : int taskID Argument : int entID Argument : const char *type_name Argument : const char *data ============ */ -void Q3_SetVar( int taskID, int entID, const char *type_name, const char *data ) -{ - int vret = Q3_VariableDeclared( type_name ) ; - float float_data; - float val = 0.0f; +void Q3_SetVar(int taskID, int entID, const char *type_name, const char *data) { + int vret = Q3_VariableDeclared(type_name); + float float_data; + float val = 0.0f; - - if ( vret != VTYPE_NONE ) - { - switch ( vret ) - { + if (vret != VTYPE_NONE) { + switch (vret) { case VTYPE_FLOAT: - //Check to see if increment command - if ( (val = Q3_CheckStringCounterIncrement( data )) ) - { - Q3_GetFloatVariable( type_name, &float_data ); + // Check to see if increment command + if ((val = Q3_CheckStringCounterIncrement(data))) { + Q3_GetFloatVariable(type_name, &float_data); float_data += val; + } else { + float_data = atof((char *)data); } - else - { - float_data = atof((char *) data); - } - Q3_SetFloatVariable( type_name, float_data ); + Q3_SetFloatVariable(type_name, float_data); break; case VTYPE_STRING: - Q3_SetStringVariable( type_name, data ); + Q3_SetStringVariable(type_name, data); break; case VTYPE_VECTOR: - Q3_SetVectorVariable( type_name, (char *) data ); + Q3_SetVectorVariable(type_name, (char *)data); break; } return; } - Q3_DebugPrint( WL_ERROR, "%s variable or field not found!\n", type_name ); + Q3_DebugPrint(WL_ERROR, "%s variable or field not found!\n", type_name); } - /* ============ Q3_Set - Description : - Return type : void + Description : + Return type : void Argument : int taskID Argument : int entID Argument : const char *type_name Argument : const char *data ============ */ -static void Q3_Set( int taskID, int entID, const char *type_name, const char *data ) -{ - gentity_t *ent = &g_entities[entID]; - float float_data; - int int_data, toSet; - vec3_t vector_data; +static void Q3_Set(int taskID, int entID, const char *type_name, const char *data) { + gentity_t *ent = &g_entities[entID]; + float float_data; + int int_data, toSet; + vec3_t vector_data; // eezstreet: Add support for cvars getting modified thru ICARUS script - if(strlen(type_name) > 5 && !Q_stricmpn(type_name, "cvar_", 5)) - { - gi.cvar_set(type_name+5, data); + if (strlen(type_name) > 5 && !Q_stricmpn(type_name, "cvar_", 5)) { + gi.cvar_set(type_name + 5, data); return; } - //Set this for callbacks - toSet = GetIDForString( setTable, type_name ); + // Set this for callbacks + toSet = GetIDForString(setTable, type_name); - //TODO: Throw in a showscript command that will list each command and what they're doing... + // TODO: Throw in a showscript command that will list each command and what they're doing... // maybe as simple as printing that line of the script to the console preceeded by the person's name? // showscript can take any number of targetnames or "all"? Groupname? - switch ( toSet ) - { + switch (toSet) { case SET_ORIGIN: - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - G_SetOrigin( ent, vector_data ); - if ( strncmp( "NPC_", ent->classname, 4 ) == 0 ) - {//hack for moving spawners - VectorCopy( vector_data, ent->s.origin); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + G_SetOrigin(ent, vector_data); + if (strncmp("NPC_", ent->classname, 4) == 0) { // hack for moving spawners + VectorCopy(vector_data, ent->s.origin); } break; case SET_TELEPORT_DEST: - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - if ( !Q3_SetTeleportDest( entID, vector_data ) ) - { - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + if (!Q3_SetTeleportDest(entID, vector_data)) { + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); return; } break; case SET_COPY_ORIGIN: - Q3_SetCopyOrigin( entID, (char *) data ); + Q3_SetCopyOrigin(entID, (char *)data); break; case SET_ANGLES: - //Q3_SetAngles( entID, *(vec3_t *) data); - sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ); - Q3_SetAngles( entID, vector_data); + // Q3_SetAngles( entID, *(vec3_t *) data); + sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]); + Q3_SetAngles(entID, vector_data); break; case SET_XVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 0, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 0, float_data); break; - + case SET_YVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 1, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 1, float_data); break; case SET_ZVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 2, float_data); break; case SET_Z_OFFSET: - float_data = atof((char *) data); - Q3_SetOriginOffset( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetOriginOffset(entID, 2, float_data); break; case SET_ENEMY: - Q3_SetEnemy( entID, (char *) data ); + Q3_SetEnemy(entID, (char *)data); break; case SET_LEADER: - Q3_SetLeader( entID, (char *) data ); + Q3_SetLeader(entID, (char *)data); break; case SET_NAVGOAL: - Q3_SetNavGoal( entID, (char *) data ); - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); - return; //Don't call it back + Q3_SetNavGoal(entID, (char *)data); + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); + return; // Don't call it back break; case SET_ANIM_UPPER: - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - return; //Don't call it back + if (Q3_SetAnimUpper(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + return; // Don't call it back } break; case SET_ANIM_LOWER: - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + if (Q3_SetAnimLower(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back } break; - case SET_ANIM_BOTH: - { - int both = 0; - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - both++; - } - else - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - both++; - } - else - { - Q3_DebugPrint( WL_ERROR, "Q3_SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( both >= 2 ) - { - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); - } - if ( both ) - { - return; //Don't call it back - } + case SET_ANIM_BOTH: { + int both = 0; + if (Q3_SetAnimUpper(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + both++; + } else { + Q3_DebugPrint(WL_ERROR, "Q3_SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data); } - break; - + if (Q3_SetAnimLower(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + both++; + } else { + Q3_DebugPrint(WL_ERROR, "Q3_SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data); + } + if (both >= 2) { + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); + } + if (both) { + return; // Don't call it back + } + } break; + case SET_ANIM_HOLDTIME_LOWER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back break; case SET_ANIM_HOLDTIME_UPPER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + return; // Don't call it back break; case SET_ANIM_HOLDTIME_BOTH: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); - Q3_TaskIDSet( ent, TID_ANIM_UPPER, taskID ); - Q3_TaskIDSet( ent, TID_ANIM_LOWER, taskID ); - return; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); + Q3_TaskIDSet(ent, TID_ANIM_UPPER, taskID); + Q3_TaskIDSet(ent, TID_ANIM_LOWER, taskID); + return; // Don't call it back break; case SET_PLAYER_TEAM: - Q3_SetPlayerTeam( entID, (char *) data ); + Q3_SetPlayerTeam(entID, (char *)data); break; case SET_ENEMY_TEAM: - Q3_SetEnemyTeam( entID, (char *) data ); + Q3_SetEnemyTeam(entID, (char *)data); break; case SET_HEALTH: - int_data = atoi((char *) data); - Q3_SetHealth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHealth(entID, int_data); break; case SET_ARMOR: - int_data = atoi((char *) data); - Q3_SetArmor( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetArmor(entID, int_data); break; case SET_BEHAVIOR_STATE: - if( !Q3_SetBState( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_BSTATE, taskID ); - return;//don't complete + if (!Q3_SetBState(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_BSTATE, taskID); + return; // don't complete } break; case SET_DEFAULT_BSTATE: - Q3_SetDefaultBState( entID, (char *) data ); + Q3_SetDefaultBState(entID, (char *)data); break; case SET_TEMP_BSTATE: - if( !Q3_SetTempBState( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_BSTATE, taskID ); - return;//don't complete + if (!Q3_SetTempBState(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_BSTATE, taskID); + return; // don't complete } break; case SET_CAPTURE: - Q3_SetCaptureGoal( entID, (char *) data ); + Q3_SetCaptureGoal(entID, (char *)data); break; - case SET_DPITCH://FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? - float_data = atof((char *) data); - Q3_SetDPitch( entID, float_data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + case SET_DPITCH: // FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? + float_data = atof((char *)data); + Q3_SetDPitch(entID, float_data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_DYAW: - float_data = atof((char *) data); - Q3_SetDYaw( entID, float_data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + float_data = atof((char *)data); + Q3_SetDYaw(entID, float_data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_EVENT: - Q3_SetEvent( entID, (char *) data ); + Q3_SetEvent(entID, (char *)data); break; case SET_VIEWTARGET: - Q3_SetViewTarget( entID, (char *) data ); - Q3_TaskIDSet( ent, TID_ANGLE_FACE, taskID ); + Q3_SetViewTarget(entID, (char *)data); + Q3_TaskIDSet(ent, TID_ANGLE_FACE, taskID); return; break; case SET_WATCHTARGET: - Q3_SetWatchTarget( entID, (char *) data ); + Q3_SetWatchTarget(entID, (char *)data); break; case SET_VIEWENTITY: - Q3_SetViewEntity( entID, (char *) data ); + Q3_SetViewEntity(entID, (char *)data); break; case SET_LOOPSOUND: - Q3_SetLoopSound( entID, (char *) data ); + Q3_SetLoopSound(entID, (char *)data); break; case SET_ICARUS_FREEZE: case SET_ICARUS_UNFREEZE: - Q3_SetICARUSFreeze( entID, (char *) data, (qboolean)(toSet == SET_ICARUS_FREEZE) ); + Q3_SetICARUSFreeze(entID, (char *)data, (qboolean)(toSet == SET_ICARUS_FREEZE)); break; case SET_WEAPON: - Q3_SetWeapon ( entID, (char *) data); + Q3_SetWeapon(entID, (char *)data); break; case SET_ITEM: - Q3_SetItem ( entID, (char *) data); + Q3_SetItem(entID, (char *)data); break; case SET_WALKSPEED: - int_data = atoi((char *) data); - Q3_SetWalkSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetWalkSpeed(entID, int_data); break; case SET_RUNSPEED: - int_data = atoi((char *) data); - Q3_SetRunSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRunSpeed(entID, int_data); break; case SET_WIDTH: - int_data = atoi((char *) data); - Q3_SetWidth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetWidth(entID, int_data); return; break; case SET_YAWSPEED: - float_data = atof((char *) data); - Q3_SetYawSpeed ( entID, float_data); + float_data = atof((char *)data); + Q3_SetYawSpeed(entID, float_data); break; case SET_AGGRESSION: - int_data = atoi((char *) data); - Q3_SetAggression ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAggression(entID, int_data); break; case SET_AIM: - int_data = atoi((char *) data); - Q3_SetAim ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAim(entID, int_data); break; case SET_FRICTION: - int_data = atoi((char *) data); - Q3_SetFriction ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetFriction(entID, int_data); break; case SET_GRAVITY: - float_data = atof((char *) data); - Q3_SetGravity ( entID, float_data); + float_data = atof((char *)data); + Q3_SetGravity(entID, float_data); break; case SET_WAIT: - float_data = atof((char *) data); - Q3_SetWait( entID, float_data); + float_data = atof((char *)data); + Q3_SetWait(entID, float_data); break; case SET_FOLLOWDIST: - float_data = atof((char *) data); - Q3_SetFollowDist( entID, float_data); + float_data = atof((char *)data); + Q3_SetFollowDist(entID, float_data); break; case SET_SCALE: - float_data = atof((char *) data); - Q3_SetScale( entID, float_data); + float_data = atof((char *)data); + Q3_SetScale(entID, float_data); break; case SET_COUNT: - Q3_SetCount( entID, (char *) data); + Q3_SetCount(entID, (char *)data); break; case SET_SHOT_SPACING: - int_data = atoi((char *) data); - Q3_SetShotSpacing( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetShotSpacing(entID, int_data); break; case SET_IGNOREPAIN: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnorePain( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnorePain( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnorePain(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnorePain(entID, qfalse); break; case SET_IGNOREENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qfalse); break; case SET_IGNOREALERTS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qfalse); break; - + case SET_DONTSHOOT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontShoot( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontShoot( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontShoot(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontShoot(entID, qfalse); break; - + case SET_DONTFIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFire( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontFire( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFire(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontFire(entID, qfalse); break; case SET_LOCKED_ENEMY: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLockedEnemy( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetLockedEnemy( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockedEnemy(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetLockedEnemy(entID, qfalse); break; case SET_NOTARGET: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoTarget( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetNoTarget( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoTarget(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetNoTarget(entID, qfalse); break; case SET_LEAN: - if(!Q_stricmp("right", ((char *)data))) - Q3_SetLean( entID, LEAN_RIGHT); - else if(!Q_stricmp("left", ((char *)data))) - Q3_SetLean( entID, LEAN_LEFT); + if (!Q_stricmp("right", ((char *)data))) + Q3_SetLean(entID, LEAN_RIGHT); + else if (!Q_stricmp("left", ((char *)data))) + Q3_SetLean(entID, LEAN_LEFT); else - Q3_SetLean( entID, LEAN_NONE); + Q3_SetLean(entID, LEAN_NONE); break; case SET_SHOOTDIST: - float_data = atof((char *) data); - Q3_SetShootDist( entID, float_data ); + float_data = atof((char *)data); + Q3_SetShootDist(entID, float_data); break; case SET_TIMESCALE: - Q3_SetTimeScale( entID, (char *) data ); + Q3_SetTimeScale(entID, (char *)data); break; case SET_VISRANGE: - float_data = atof((char *) data); - Q3_SetVisrange( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVisrange(entID, float_data); break; - + case SET_EARSHOT: - float_data = atof((char *) data); - Q3_SetEarshot( entID, float_data ); + float_data = atof((char *)data); + Q3_SetEarshot(entID, float_data); break; - + case SET_VIGILANCE: - float_data = atof((char *) data); - Q3_SetVigilance( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVigilance(entID, float_data); break; - + case SET_VFOV: - int_data = atoi((char *) data); - Q3_SetVFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetVFOV(entID, int_data); break; case SET_HFOV: - int_data = atoi((char *) data); - Q3_SetHFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHFOV(entID, int_data); break; case SET_TARGETNAME: - Q3_SetTargetName( entID, (char *) data ); + Q3_SetTargetName(entID, (char *)data); break; case SET_TARGET: - Q3_SetTarget( entID, (char *) data ); + Q3_SetTarget(entID, (char *)data); break; case SET_TARGET2: - Q3_SetTarget2( entID, (char *) data ); + Q3_SetTarget2(entID, (char *)data); break; - + case SET_LOCATION: - if ( !Q3_SetLocation( entID, (char *) data ) ) - { - Q3_TaskIDSet( ent, TID_LOCATION, taskID ); + if (!Q3_SetLocation(entID, (char *)data)) { + Q3_TaskIDSet(ent, TID_LOCATION, taskID); return; } break; case SET_PAINTARGET: - Q3_SetPainTarget( entID, (char *) data ); + Q3_SetPainTarget(entID, (char *)data); break; case SET_DEFEND_TARGET: - Q3_DebugPrint( WL_WARNING, "Q3_SetDefendTarget unimplemented\n", entID ); - //Q3_SetEnemy( entID, (char *) data); + Q3_DebugPrint(WL_WARNING, "Q3_SetDefendTarget unimplemented\n", entID); + // Q3_SetEnemy( entID, (char *) data); break; case SET_PARM1: @@ -6979,7 +5998,7 @@ static void Q3_Set( int taskID, int entID, const char *type_name, const char *da case SET_PARM14: case SET_PARM15: case SET_PARM16: - Q3_SetParm( entID, (toSet-SET_PARM1), (char *) data ); + Q3_SetParm(entID, (toSet - SET_PARM1), (char *)data); break; case SET_SPAWNSCRIPT: @@ -6996,163 +6015,161 @@ static void Q3_Set( int taskID, int entID, const char *type_name, const char *da case SET_FFIRESCRIPT: case SET_FFDEATHSCRIPT: case SET_MINDTRICKSCRIPT: - if( !Q3_SetBehaviorSet(entID, toSet, (char *) data) ) - Q3_DebugPrint( WL_ERROR, "Q3_SetBehaviorSet: Invalid bSet %s\n", type_name ); + if (!Q3_SetBehaviorSet(entID, toSet, (char *)data)) + Q3_DebugPrint(WL_ERROR, "Q3_SetBehaviorSet: Invalid bSet %s\n", type_name); break; case SET_NO_MINDTRICK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoMindTrick( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoMindTrick(entID, qtrue); else - Q3_SetNoMindTrick( entID, qfalse); + Q3_SetNoMindTrick(entID, qfalse); break; - case SET_CINEMATIC_SKIPSCRIPT : - Q3_SetCinematicSkipScript((char *) data); + case SET_CINEMATIC_SKIPSCRIPT: + Q3_SetCinematicSkipScript((char *)data); break; - case SET_DELAYSCRIPTTIME: - int_data = atoi((char *) data); - Q3_SetDelayScriptTime( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetDelayScriptTime(entID, int_data); break; case SET_CROUCHED: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCrouched( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCrouched(entID, qtrue); else - Q3_SetCrouched( entID, qfalse); + Q3_SetCrouched(entID, qfalse); break; case SET_WALKING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetWalking( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetWalking(entID, qtrue); else - Q3_SetWalking( entID, qfalse); + Q3_SetWalking(entID, qfalse); break; case SET_RUNNING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetRunning( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetRunning(entID, qtrue); else - Q3_SetRunning( entID, qfalse); + Q3_SetRunning(entID, qfalse); break; case SET_CHASE_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetChaseEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetChaseEnemies(entID, qtrue); else - Q3_SetChaseEnemies( entID, qfalse); + Q3_SetChaseEnemies(entID, qfalse); break; case SET_LOOK_FOR_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLookForEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLookForEnemies(entID, qtrue); else - Q3_SetLookForEnemies( entID, qfalse); + Q3_SetLookForEnemies(entID, qfalse); break; case SET_FACE_MOVE_DIR: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetFaceMoveDir( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetFaceMoveDir(entID, qtrue); else - Q3_SetFaceMoveDir( entID, qfalse); + Q3_SetFaceMoveDir(entID, qfalse); break; case SET_ALT_FIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAltFire( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAltFire(entID, qtrue); else - Q3_SetAltFire( entID, qfalse); + Q3_SetAltFire(entID, qfalse); break; case SET_DONT_FLEE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFlee( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFlee(entID, qtrue); else - Q3_SetDontFlee( entID, qfalse); + Q3_SetDontFlee(entID, qfalse); break; case SET_FORCED_MARCH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetForcedMarch( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForcedMarch(entID, qtrue); else - Q3_SetForcedMarch( entID, qfalse); + Q3_SetForcedMarch(entID, qfalse); break; case SET_NO_RESPONSE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoResponse( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoResponse(entID, qtrue); else - Q3_SetNoResponse( entID, qfalse); + Q3_SetNoResponse(entID, qfalse); break; case SET_NO_COMBAT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCombatTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCombatTalk(entID, qtrue); else - Q3_SetCombatTalk( entID, qfalse); + Q3_SetCombatTalk(entID, qfalse); break; case SET_NO_ALERT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAlertTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAlertTalk(entID, qtrue); else - Q3_SetAlertTalk( entID, qfalse); + Q3_SetAlertTalk(entID, qfalse); break; case SET_USE_CP_NEAREST: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseCpNearest( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseCpNearest(entID, qtrue); else - Q3_SetUseCpNearest( entID, qfalse); + Q3_SetUseCpNearest(entID, qfalse); break; case SET_NO_FORCE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoForce( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoForce(entID, qtrue); else - Q3_SetNoForce( entID, qfalse); + Q3_SetNoForce(entID, qfalse); break; case SET_NO_ACROBATICS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAcrobatics( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAcrobatics(entID, qtrue); else - Q3_SetNoAcrobatics( entID, qfalse); + Q3_SetNoAcrobatics(entID, qfalse); break; case SET_USE_SUBTITLES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseSubtitles( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseSubtitles(entID, qtrue); else - Q3_SetUseSubtitles( entID, qfalse); + Q3_SetUseSubtitles(entID, qfalse); break; case SET_NO_FALLTODEATH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoFallToDeath( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoFallToDeath(entID, qtrue); else - Q3_SetNoFallToDeath( entID, qfalse); + Q3_SetNoFallToDeath(entID, qfalse); break; case SET_DISMEMBERABLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDismemberable( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDismemberable(entID, qtrue); else - Q3_SetDismemberable( entID, qfalse); + Q3_SetDismemberable(entID, qfalse); break; case SET_MORELIGHT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetMoreLight( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetMoreLight(entID, qtrue); else - Q3_SetMoreLight( entID, qfalse); + Q3_SetMoreLight(entID, qfalse); break; - case SET_TREASONED: - Q3_DebugPrint( WL_VERBOSE, "SET_TREASONED is disabled, do not use\n" ); + Q3_DebugPrint(WL_VERBOSE, "SET_TREASONED is disabled, do not use\n"); /* G_TeamRetaliation( NULL, &g_entities[0], qfalse ); ffireLevel = FFIRE_LEVEL_RETALIATION; @@ -7160,116 +6177,112 @@ static void Q3_Set( int taskID, int entID, const char *type_name, const char *da break; case SET_UNDYING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUndying( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUndying(entID, qtrue); else - Q3_SetUndying( entID, qfalse); + Q3_SetUndying(entID, qfalse); break; case SET_INVINCIBLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetInvincible( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvincible(entID, qtrue); else - Q3_SetInvincible( entID, qfalse); + Q3_SetInvincible(entID, qfalse); break; case SET_NOAVOID: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAvoid( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAvoid(entID, qtrue); else - Q3_SetNoAvoid( entID, qfalse); + Q3_SetNoAvoid(entID, qfalse); break; case SET_SOLID: - if(!Q_stricmp("true", ((char *)data))) - { - if ( !Q3_SetSolid( entID, qtrue) ) - { - Q3_TaskIDSet( ent, TID_RESIZE, taskID ); + if (!Q_stricmp("true", ((char *)data))) { + if (!Q3_SetSolid(entID, qtrue)) { + Q3_TaskIDSet(ent, TID_RESIZE, taskID); return; } - } - else - { - Q3_SetSolid( entID, qfalse); + } else { + Q3_SetSolid(entID, qfalse); } break; case SET_INVISIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetInvisible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvisible(entID, qtrue); else - Q3_SetInvisible( entID, qfalse ); + Q3_SetInvisible(entID, qfalse); break; case SET_VAMPIRE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetVampire( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetVampire(entID, qtrue); else - Q3_SetVampire( entID, qfalse ); + Q3_SetVampire(entID, qfalse); break; case SET_FORCE_INVINCIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetForceInvincible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForceInvincible(entID, qtrue); else - Q3_SetForceInvincible( entID, qfalse ); + Q3_SetForceInvincible(entID, qfalse); break; case SET_GREET_ALLIES: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetGreetAllies( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetGreetAllies(entID, qtrue); else - Q3_SetGreetAllies( entID, qfalse ); + Q3_SetGreetAllies(entID, qfalse); break; case SET_PLAYER_LOCKED: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetPlayerLocked( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetPlayerLocked(entID, qtrue); else - Q3_SetPlayerLocked( entID, qfalse ); + Q3_SetPlayerLocked(entID, qfalse); break; - + case SET_LOCK_PLAYER_WEAPONS: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetLockPlayerWeapons( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockPlayerWeapons(entID, qtrue); else - Q3_SetLockPlayerWeapons( entID, qfalse ); + Q3_SetLockPlayerWeapons(entID, qfalse); break; case SET_NO_IMPACT_DAMAGE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetNoImpactDamage( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoImpactDamage(entID, qtrue); else - Q3_SetNoImpactDamage( entID, qfalse ); + Q3_SetNoImpactDamage(entID, qfalse); break; case SET_FORWARDMOVE: - int_data = atoi((char *) data); - Q3_SetForwardMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetForwardMove(entID, int_data); break; case SET_RIGHTMOVE: - int_data = atoi((char *) data); - Q3_SetRightMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRightMove(entID, int_data); break; case SET_LOCKYAW: - Q3_SetLockAngle( entID, data); + Q3_SetLockAngle(entID, data); break; - + case SET_CAMERA_GROUP: Q3_CameraGroup(entID, (char *)data); break; case SET_CAMERA_GROUP_Z_OFS: - float_data = atof((char *) data); - Q3_CameraGroupZOfs( float_data ); + float_data = atof((char *)data); + Q3_CameraGroupZOfs(float_data); break; case SET_CAMERA_GROUP_TAG: - Q3_CameraGroupTag( (char *)data ); + Q3_CameraGroupTag((char *)data); break; - //FIXME: put these into camera commands + // FIXME: put these into camera commands case SET_LOOK_TARGET: Q3_LookTarget(entID, (char *)data); break; @@ -7297,181 +6310,144 @@ static void Q3_Set( int taskID, int entID, const char *type_name, const char *da case SET_FACEBLINKFROWN: case SET_FACEFROWN: case SET_FACENORMAL: - float_data = atof((char *) data); + float_data = atof((char *)data); Q3_Face(entID, toSet, float_data); break; case SET_SCROLLTEXT: - Q3_ScrollText( (char *)data ); + Q3_ScrollText((char *)data); break; case SET_LCARSTEXT: - Q3_LCARSText( (char *)data ); + Q3_LCARSText((char *)data); break; case SET_CAPTIONTEXTCOLOR: - Q3_SetCaptionTextColor ( (char *)data ); + Q3_SetCaptionTextColor((char *)data); break; case SET_CENTERTEXTCOLOR: - Q3_SetCenterTextColor ( (char *)data ); + Q3_SetCenterTextColor((char *)data); break; case SET_SCROLLTEXTCOLOR: - Q3_SetScrollTextColor ( (char *)data ); + Q3_SetScrollTextColor((char *)data); break; case SET_PLAYER_USABLE: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetPlayerUsable(entID, qtrue); - } - else - { + } else { Q3_SetPlayerUsable(entID, qfalse); } break; case SET_STARTFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetStartFrame(entID, int_data); break; - + case SET_ENDFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetEndFrame(entID, int_data); - Q3_TaskIDSet( ent, TID_ANIM_BOTH, taskID ); + Q3_TaskIDSet(ent, TID_ANIM_BOTH, taskID); return; break; case SET_ANIMFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetAnimFrame(entID, int_data); return; break; - + case SET_LOOP_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetLoopAnim(entID, qtrue); - } - else - { + } else { Q3_SetLoopAnim(entID, qfalse); } break; case SET_INTERFACE: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetInterface(entID, "1"); - } - else - { + } else { Q3_SetInterface(entID, "0"); } break; case SET_SHIELDS: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetShields(entID, qtrue); - } - else - { + } else { Q3_SetShields(entID, qfalse); } break; - + case SET_SABERACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetSaberActive( entID, qtrue ); - } - else - { - Q3_SetSaberActive( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetSaberActive(entID, qtrue); + } else { + Q3_SetSaberActive(entID, qfalse); } break; case SET_ADJUST_AREA_PORTALS: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetAdjustAreaPortals( entID, qtrue ); - } - else - { - Q3_SetAdjustAreaPortals( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetAdjustAreaPortals(entID, qtrue); + } else { + Q3_SetAdjustAreaPortals(entID, qfalse); } break; - + case SET_DMG_BY_HEAVY_WEAP_ONLY: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetDmgByHeavyWeapOnly( entID, qtrue ); - } - else - { - Q3_SetDmgByHeavyWeapOnly( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetDmgByHeavyWeapOnly(entID, qtrue); + } else { + Q3_SetDmgByHeavyWeapOnly(entID, qfalse); } break; case SET_SHIELDED: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetShielded( entID, qtrue ); - } - else - { - Q3_SetShielded( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetShielded(entID, qtrue); + } else { + Q3_SetShielded(entID, qfalse); } break; - - case SET_NO_GROUPS: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetNoGroups( entID, qtrue ); - } - else - { - Q3_SetNoGroups( entID, qfalse ); + + case SET_NO_GROUPS: + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetNoGroups(entID, qtrue); + } else { + Q3_SetNoGroups(entID, qfalse); } break; case SET_FIRE_WEAPON: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFireWeapon( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFireWeapon( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFireWeapon(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFireWeapon(entID, qfalse); } break; case SET_INACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetInactive( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetInactive( entID, qfalse); - } - else if(!Q_stricmp("unlocked", ((char *)data))) - { -extern void UnLockDoors(gentity_t *const ent); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetInactive(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetInactive(entID, qfalse); + } else if (!Q_stricmp("unlocked", ((char *)data))) { + extern void UnLockDoors(gentity_t *const ent); UnLockDoors(&g_entities[entID]); - } - else if(!Q_stricmp("locked", ((char *)data))) - { -extern void LockDoors(gentity_t *const ent); + } else if (!Q_stricmp("locked", ((char *)data))) { + extern void LockDoors(gentity_t *const ent); LockDoors(&g_entities[entID]); } break; case SET_END_SCREENDISSOLVE: - gi.SendConsoleCommand( "endscreendissolve\n"); + gi.SendConsoleCommand("endscreendissolve\n"); break; case SET_MISSION_STATUS_SCREEN: @@ -7479,23 +6455,17 @@ extern void LockDoors(gentity_t *const ent); break; case SET_FUNC_USABLE_VISIBLE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qfalse); } break; case SET_NO_KNOCKBACK: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetNoKnockback(entID, qtrue); - } - else - { + } else { Q3_SetNoKnockback(entID, qfalse); } break; @@ -7505,62 +6475,54 @@ extern void LockDoors(gentity_t *const ent); // the "timescale" and "skippingCinematic" cvars will be set back to normal in the Video code, so doing a // skip will now only skip one section of a multiple-part story (eg VOY1 bridge sequence) // -// if ( g_timescale->value <= 1.0f ) - { - gi.SendConsoleCommand( va("inGameCinematic %s\n", (char *)data) ); - } + // if ( g_timescale->value <= 1.0f ) + { gi.SendConsoleCommand(va("inGameCinematic %s\n", (char *)data)); } break; case SET_VIDEO_FADE_IN: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cl_VidFadeUp", "1"); - } - else - { + } else { gi.cvar_set("cl_VidFadeUp", "0"); } break; case SET_VIDEO_FADE_OUT: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cl_VidFadeDown", "1"); - } - else - { + } else { gi.cvar_set("cl_VidFadeDown", "0"); } break; case SET_REMOVE_TARGET: - Q3_SetRemoveTarget( entID, (const char *) data ); + Q3_SetRemoveTarget(entID, (const char *)data); break; case SET_LOADGAME: - gi.SendConsoleCommand( va("load %s\n", (const char *) data ) ); + gi.SendConsoleCommand(va("load %s\n", (const char *)data)); break; case SET_MENU_SCREEN: - //UI_SetActiveMenu( (const char *) data ); + // UI_SetActiveMenu( (const char *) data ); break; case SET_OBJECTIVE_SHOW: - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadObjective", "1"); + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadObjective", "1"); - Q3_SetObjective((const char *) data ,SET_OBJ_SHOW); - Q3_SetObjective((const char *) data ,SET_OBJ_PENDING); + Q3_SetObjective((const char *)data, SET_OBJ_SHOW); + Q3_SetObjective((const char *)data, SET_OBJ_PENDING); break; case SET_OBJECTIVE_HIDE: - Q3_SetObjective((const char *) data ,SET_OBJ_HIDE); + Q3_SetObjective((const char *)data, SET_OBJ_HIDE); break; case SET_OBJECTIVE_SUCCEEDED: - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadObjective", "1"); - Q3_SetObjective((const char *) data ,SET_OBJ_SUCCEEDED); + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadObjective", "1"); + Q3_SetObjective((const char *)data, SET_OBJ_SUCCEEDED); break; case SET_OBJECTIVE_FAILED: - Q3_SetObjective((const char *) data ,SET_OBJ_FAILED); + Q3_SetObjective((const char *)data, SET_OBJ_FAILED); break; case SET_OBJECTIVE_CLEARALL: @@ -7568,15 +6530,15 @@ extern void LockDoors(gentity_t *const ent); break; case SET_MISSIONFAILED: - Q3_SetMissionFailed((const char *) data); + Q3_SetMissionFailed((const char *)data); break; case SET_MISSIONSTATUSTEXT: - Q3_SetStatusText((const char *) data); + Q3_SetStatusText((const char *)data); break; - + case SET_MISSIONSTATUSTIME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); cg.missionStatusDeadTime = level.time + int_data; break; @@ -7585,37 +6547,31 @@ extern void LockDoors(gentity_t *const ent); break; case SET_SKILL: -// //can never be set + // //can never be set break; case SET_FULLNAME: - Q3_SetFullName( entID, (char *) data ); + Q3_SetFullName(entID, (char *)data); break; case SET_DISABLE_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetDisableShaderAnims( entID, qtrue); - } - else - { - Q3_SetDisableShaderAnims( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetDisableShaderAnims(entID, qtrue); + } else { + Q3_SetDisableShaderAnims(entID, qfalse); } break; case SET_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetShaderAnim( entID, qtrue); - } - else - { - Q3_SetShaderAnim( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetShaderAnim(entID, qtrue); + } else { + Q3_SetShaderAnim(entID, qfalse); } break; case SET_MUSIC_STATE: - Q3_SetMusicState( (char *) data ); + Q3_SetMusicState((char *)data); break; case SET_CLEAN_DAMAGING_ENTS: @@ -7623,12 +6579,9 @@ extern void LockDoors(gentity_t *const ent); break; case SET_HUD: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { gi.cvar_set("cg_drawHUD", "1"); - } - else - { + } else { gi.cvar_set("cg_drawHUD", "0"); } break; @@ -7644,52 +6597,43 @@ extern void LockDoors(gentity_t *const ent); case SET_SABER_THROW: case SET_SABER_DEFENSE: case SET_SABER_OFFENSE: - int_data = atoi((char *) data); - Q3_SetForcePowerLevel( entID, (toSet-SET_FORCE_HEAL_LEVEL), int_data ); + int_data = atoi((char *)data); + Q3_SetForcePowerLevel(entID, (toSet - SET_FORCE_HEAL_LEVEL), int_data); break; - + default: - //Q3_DebugPrint( WL_ERROR, "Q3_Set: '%s' is not a valid set field\n", type_name ); - Q3_SetVar( taskID, entID, type_name, data ); + // Q3_DebugPrint( WL_ERROR, "Q3_Set: '%s' is not a valid set field\n", type_name ); + Q3_SetVar(taskID, entID, type_name, data); break; } - ent->taskManager->Completed( taskID ); + ent->taskManager->Completed(taskID); } - - /* ============ Q3_Kill - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : const char *name ============ */ -static void Q3_Kill( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; - int o_health; +static void Q3_Kill(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *victim = NULL; + int o_health; - if( !Q_stricmp( name, "self") ) - { + if (!Q_stricmp(name, "self")) { victim = ent; - } - else if( !Q_stricmp( name, "enemy" ) ) - { + } else if (!Q_stricmp(name, "enemy")) { victim = ent->enemy; - } - else - { - victim = G_Find (NULL, FOFS(targetname), (char *) name ); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); } - if ( !victim ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Kill: can't find %s\n", name); + if (!victim) { + Q3_DebugPrint(WL_WARNING, "Q3_Kill: can't find %s\n", name); return; } @@ -7700,38 +6644,33 @@ static void Q3_Kill( int entID, const char *name ) return; } */ - if ( victim == ent ) - {//don't ICARUS_FreeEnt me, I'm in the middle of a script! (FIXME: shouldn't ICARUS handle this internally?) + if (victim == ent) { // don't ICARUS_FreeEnt me, I'm in the middle of a script! (FIXME: shouldn't ICARUS handle this internally?) victim->svFlags |= SVF_KILLED_SELF; } o_health = victim->health; victim->health = 0; - if ( victim->client ) - { + if (victim->client) { victim->flags |= FL_NO_KNOCKBACK; } - //G_SetEnemy(victim, ent); - if( victim->e_DieFunc != dieF_NULL ) // check can be omitted + // G_SetEnemy(victim, ent); + if (victim->e_DieFunc != dieF_NULL) // check can be omitted { - GEntity_DieFunc( victim, NULL, NULL, o_health, MOD_UNKNOWN ); + GEntity_DieFunc(victim, NULL, NULL, o_health, MOD_UNKNOWN); } } - /* ============ Q3_RemoveEnt - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *victim ============ */ -static void Q3_RemoveEnt( gentity_t *victim ) -{ - if( victim->client ) - { - //ClientDisconnect(ent); +static void Q3_RemoveEnt(gentity_t *victim) { + if (victim->client) { + // ClientDisconnect(ent); victim->s.eFlags |= EF_NODRAW; victim->s.eFlags &= ~EF_NPC; victim->svFlags &= ~SVF_NPC; @@ -7740,79 +6679,63 @@ static void Q3_RemoveEnt( gentity_t *victim ) victim->health = 0; victim->targetname = NULL; - if ( victim->NPC && victim->NPC->tempGoal != NULL ) - { - G_FreeEntity( victim->NPC->tempGoal ); + if (victim->NPC && victim->NPC->tempGoal != NULL) { + G_FreeEntity(victim->NPC->tempGoal); victim->NPC->tempGoal = NULL; } - if ( victim->client->ps.saberEntityNum != ENTITYNUM_NONE && victim->client->ps.saberEntityNum > 0 ) - { - if ( g_entities[victim->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[victim->client->ps.saberEntityNum] ); + if (victim->client->ps.saberEntityNum != ENTITYNUM_NONE && victim->client->ps.saberEntityNum > 0) { + if (g_entities[victim->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[victim->client->ps.saberEntityNum]); } victim->client->ps.saberEntityNum = ENTITYNUM_NONE; } - //Disappear in half a second + // Disappear in half a second victim->e_ThinkFunc = thinkF_G_FreeEntity; victim->nextthink = level.time + 500; return; - } - else - { + } else { victim->e_ThinkFunc = thinkF_G_FreeEntity; victim->nextthink = level.time + 100; } } - /* ============ Q3_Remove - Description : - Return type : void + Description : + Return type : void Argument : int entID Argument : const char *name ============ */ -static void Q3_Remove( int entID, const char *name ) -{ +static void Q3_Remove(int entID, const char *name) { gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; + gentity_t *victim = NULL; - if( !Q_stricmp( "self", name ) ) - { + if (!Q_stricmp("self", name)) { victim = ent; - if ( !victim ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + Q3_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else if( !Q_stricmp( "enemy", name ) ) - { + Q3_RemoveEnt(victim); + } else if (!Q_stricmp("enemy", name)) { victim = ent->enemy; - if ( !victim ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + Q3_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else - { - victim = G_Find( NULL, FOFS(targetname), (char *) name ); - if ( !victim ) - { - Q3_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + Q3_RemoveEnt(victim); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); + if (!victim) { + Q3_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - while ( victim ) - { - Q3_RemoveEnt( victim ); - victim = G_Find( victim, FOFS(targetname), (char *) name ); + while (victim) { + Q3_RemoveEnt(victim); + victim = G_Find(victim, FOFS(targetname), (char *)name); } } } @@ -7820,37 +6743,32 @@ static void Q3_Remove( int entID, const char *name ) /* ============ MakeOwnerInvis - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *self ============ */ -void MakeOwnerInvis(gentity_t *self) -{ - if(self->owner && self->owner->client) - { +void MakeOwnerInvis(gentity_t *self) { + if (self->owner && self->owner->client) { self->owner->client->ps.powerups[PW_CLOAKED] = level.time + 500; } - //HACKHGACLHACK!! - MCG + // HACKHGACLHACK!! - MCG self->e_ThinkFunc = thinkF_RemoveOwner; self->nextthink = level.time + 400; } - /* ============ MakeOwnerEnergy - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *self ============ */ -void MakeOwnerEnergy(gentity_t *self) -{ - if(self->owner && self->owner->client) - { -// self->owner->client->ps.powerups[PW_QUAD] = level.time + 1000; +void MakeOwnerEnergy(gentity_t *self) { + if (self->owner && self->owner->client) { + // self->owner->client->ps.powerups[PW_QUAD] = level.time + 1000; } G_FreeEntity(self); @@ -7859,19 +6777,17 @@ void MakeOwnerEnergy(gentity_t *self) /* ============ RemoveOwner - Description : - Return type : void + Description : + Return type : void Argument : gentity_t *self ============ */ -void RemoveOwner (gentity_t *self) -{ - if ( self->owner && self->owner->inuse ) - {//I have an owner and they heavn't been freed yet - Q3_Remove( self->owner->s.number, "self" ); +void RemoveOwner(gentity_t *self) { + if (self->owner && self->owner->inuse) { // I have an owner and they heavn't been freed yet + Q3_Remove(self->owner->s.number, "self"); } - G_FreeEntity( self ); + G_FreeEntity(self); } /* @@ -7885,36 +6801,32 @@ void RemoveOwner (gentity_t *self) /* ============ Q3_GetFloat - Description : - Return type : int + Description : + Return type : int Argument : int entID Argument : int type Argument : const char *name Argument : float *value ============ */ -static int Q3_GetFloat( int entID, int type, const char *name, float *value ) -{ - gentity_t *ent = &g_entities[entID]; -// gclient_t *client; +static int Q3_GetFloat(int entID, int type, const char *name, float *value) { + gentity_t *ent = &g_entities[entID]; + // gclient_t *client; - if ( !ent ) - { + if (!ent) { return false; } - if( strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5) ) - { - *value = (float)gi.Cvar_VariableIntegerValue(name+5); + if (strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5)) { + *value = (float)gi.Cvar_VariableIntegerValue(name + 5); return true; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -7931,14 +6843,13 @@ static int Q3_GetFloat( int entID, int type, const char *name, float *value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if (ent->parms == NULL) - { - Q3_DebugPrint( WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname ); - return false; // would prefer qfalse, but I'm fitting in with what's here + if (ent->parms == NULL) { + Q3_DebugPrint(WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname); + return false; // would prefer qfalse, but I'm fitting in with what's here } - *value = atof( ent->parms->parm[toGet - SET_PARM1] ); + *value = atof(ent->parms->parm[toGet - SET_PARM1]); break; - + case SET_COUNT: *value = ent->count; break; @@ -7951,28 +6862,25 @@ static int Q3_GetFloat( int entID, int type, const char *name, float *value ) *value = g_spskill->integer; break; - case SET_XVELOCITY://## %f="0.0" # Velocity along X axis - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname ); + case SET_XVELOCITY: //## %f="0.0" # Velocity along X axis + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[0]; break; - case SET_YVELOCITY://## %f="0.0" # Velocity along Y axis - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname ); + case SET_YVELOCITY: //## %f="0.0" # Velocity along Y axis + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[1]; break; - case SET_ZVELOCITY://## %f="0.0" # Velocity along Z axis - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname ); + case SET_ZVELOCITY: //## %f="0.0" # Velocity along Z axis + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.velocity[2]; @@ -7982,559 +6890,500 @@ static int Q3_GetFloat( int entID, int type, const char *name, float *value ) *value = ent->currentOrigin[2] - ent->s.origin[2]; break; - case SET_DPITCH://## %f="0.0" # Pitch for NPC to turn to - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_DPITCH, %s not an NPC\n", ent->targetname ); + case SET_DPITCH: //## %f="0.0" # Pitch for NPC to turn to + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_DPITCH, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->desiredPitch; break; - case SET_DYAW://## %f="0.0" # Yaw for NPC to turn to - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_DYAW, %s not an NPC\n", ent->targetname ); + case SET_DYAW: //## %f="0.0" # Yaw for NPC to turn to + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_DYAW, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->desiredPitch; break; - case SET_WIDTH://## %f="0.0" # Width of NPC bounding box - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_WIDTH, %s not an NPC\n", ent->targetname ); + case SET_WIDTH: //## %f="0.0" # Width of NPC bounding box + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_WIDTH, %s not an NPC\n", ent->targetname); return false; } *value = ent->mins[0]; break; - case SET_TIMESCALE://## %f="0.0" # Speed-up slow down game (0 - 1.0) + case SET_TIMESCALE: //## %f="0.0" # Speed-up slow down game (0 - 1.0) *value = g_timescale->value; break; - case SET_CAMERA_GROUP_Z_OFS://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_Z_OFS: //## %s="NULL" # all ents with this cameraGroup will be focused on return false; break; - case SET_VISRANGE://## %f="0.0" # How far away NPC can see - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VISRANGE, %s not an NPC\n", ent->targetname ); + case SET_VISRANGE: //## %f="0.0" # How far away NPC can see + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VISRANGE, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.visrange; break; - case SET_EARSHOT://## %f="0.0" # How far an NPC can hear - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_EARSHOT, %s not an NPC\n", ent->targetname ); + case SET_EARSHOT: //## %f="0.0" # How far an NPC can hear + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_EARSHOT, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.earshot; break; - case SET_VIGILANCE://## %f="0.0" # How often to look for enemies (0 - 1.0) - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VIGILANCE, %s not an NPC\n", ent->targetname ); + case SET_VIGILANCE: //## %f="0.0" # How often to look for enemies (0 - 1.0) + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VIGILANCE, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.vigilance; break; - case SET_GRAVITY://## %f="0.0" # Change this ent's gravity - 800 default - if ( (ent->svFlags&SVF_CUSTOM_GRAVITY) && ent->client ) - { + case SET_GRAVITY: //## %f="0.0" # Change this ent's gravity - 800 default + if ((ent->svFlags & SVF_CUSTOM_GRAVITY) && ent->client) { *value = ent->client->ps.gravity; - } - else - { + } else { *value = g_gravity->value; } break; case SET_FACEEYESCLOSED: case SET_FACEEYESOPENED: - case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds - case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds - case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds - case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds - case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FACE___ not implemented\n" ); + case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds + case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds + case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds + case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds + case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FACE___ not implemented\n"); return false; break; - case SET_WAIT: //## %f="0.0" # Change an entity's wait field + case SET_WAIT: //## %f="0.0" # Change an entity's wait field *value = ent->wait; break; - case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FOLLOWDIST, %s not an NPC\n", ent->targetname ); + case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FOLLOWDIST, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->followDist; break; //# #sep ints - case SET_ANIM_HOLDTIME_LOWER://## %d="0" # Hold lower anim for number of milliseconds - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_LOWER: //## %d="0" # Hold lower anim for number of milliseconds + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.legsAnimTimer; break; - case SET_ANIM_HOLDTIME_UPPER://## %d="0" # Hold upper anim for number of milliseconds - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_UPPER: //## %d="0" # Hold upper anim for number of milliseconds + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.torsoAnimTimer; break; - case SET_ANIM_HOLDTIME_BOTH://## %d="0" # Hold lower and upper anims for number of milliseconds - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n" ); + case SET_ANIM_HOLDTIME_BOTH: //## %d="0" # Hold lower and upper anims for number of milliseconds + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n"); return false; break; - case SET_ARMOR://## %d="0" # Change armor - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ARMOR, %s not a client\n", ent->targetname ); + case SET_ARMOR: //## %d="0" # Change armor + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ARMOR, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.stats[STAT_ARMOR]; break; - case SET_WALKSPEED://## %d="0" # Change walkSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_WALKSPEED, %s not an NPC\n", ent->targetname ); + case SET_WALKSPEED: //## %d="0" # Change walkSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_WALKSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.walkSpeed; break; - case SET_RUNSPEED://## %d="0" # Change runSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_RUNSPEED, %s not an NPC\n", ent->targetname ); + case SET_RUNSPEED: //## %d="0" # Change runSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_RUNSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.runSpeed; break; - case SET_YAWSPEED://## %d="0" # Change yawSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_YAWSPEED, %s not an NPC\n", ent->targetname ); + case SET_YAWSPEED: //## %d="0" # Change yawSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_YAWSPEED, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.yawSpeed; break; - case SET_AGGRESSION://## %d="0" # Change aggression 1-5 - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_AGGRESSION, %s not an NPC\n", ent->targetname ); + case SET_AGGRESSION: //## %d="0" # Change aggression 1-5 + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_AGGRESSION, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.aggression; break; - case SET_AIM://## %d="0" # Change aim 1-5 - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_AIM, %s not an NPC\n", ent->targetname ); + case SET_AIM: //## %d="0" # Change aim 1-5 + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_AIM, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.aim; break; - case SET_FRICTION://## %d="0" # Change ent's friction - 6 default - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FRICTION, %s not a client\n", ent->targetname ); + case SET_FRICTION: //## %d="0" # Change ent's friction - 6 default + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FRICTION, %s not a client\n", ent->targetname); return false; } *value = ent->client->ps.friction; break; - case SET_SHOOTDIST://## %d="0" # How far the ent can shoot - 0 uses weapon - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_SHOOTDIST, %s not an NPC\n", ent->targetname ); + case SET_SHOOTDIST: //## %d="0" # How far the ent can shoot - 0 uses weapon + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_SHOOTDIST, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.shootDistance; break; - case SET_HFOV://## %d="0" # Horizontal field of view - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_HFOV, %s not an NPC\n", ent->targetname ); + case SET_HFOV: //## %d="0" # Horizontal field of view + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_HFOV, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.hfov; break; - case SET_VFOV://## %d="0" # Vertical field of view - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VFOV, %s not an NPC\n", ent->targetname ); + case SET_VFOV: //## %d="0" # Vertical field of view + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VFOV, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->stats.vfov; break; - case SET_DELAYSCRIPTTIME://## %d="0" # How many seconds to wait before running delayscript + case SET_DELAYSCRIPTTIME: //## %d="0" # How many seconds to wait before running delayscript *value = ent->delayScriptTime - level.time; break; - case SET_FORWARDMOVE://## %d="0" # NPC move forward -127(back) to 127 - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FORWARDMOVE, %s not a client\n", ent->targetname ); + case SET_FORWARDMOVE: //## %d="0" # NPC move forward -127(back) to 127 + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FORWARDMOVE, %s not a client\n", ent->targetname); return false; } *value = ent->client->forced_forwardmove; break; - case SET_RIGHTMOVE://## %d="0" # NPC move right -127(left) to 127 - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_RIGHTMOVE, %s not a client\n", ent->targetname ); + case SET_RIGHTMOVE: //## %d="0" # NPC move right -127(left) to 127 + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_RIGHTMOVE, %s not a client\n", ent->targetname); return false; } *value = ent->client->forced_rightmove; break; - case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on + case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on *value = ent->startFrame; break; - case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on + case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on *value = ent->endFrame; break; - case SET_ANIMFRAME: //## %d="0" # of current frame + case SET_ANIMFRAME: //## %d="0" # of current frame *value = ent->s.frame; break; - case SET_SHOT_SPACING://## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_SHOT_SPACING, %s not an NPC\n", ent->targetname ); + case SET_SHOT_SPACING: //## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_SHOT_SPACING, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->burstSpacing; break; - case SET_MISSIONSTATUSTIME://## %d="0" # Amount of time until Mission Status should be shown after death + case SET_MISSIONSTATUSTIME: //## %d="0" # Amount of time until Mission Status should be shown after death *value = cg.missionStatusDeadTime - level.time; break; //# #sep booleans - case SET_IGNOREPAIN://## %t="BOOL_TYPES" # Do not react to pain - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_IGNOREPAIN, %s not an NPC\n", ent->targetname ); + case SET_IGNOREPAIN: //## %t="BOOL_TYPES" # Do not react to pain + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_IGNOREPAIN, %s not an NPC\n", ent->targetname); return false; } *value = ent->NPC->ignorePain; break; - case SET_IGNOREENEMIES://## %t="BOOL_TYPES" # Do not acquire enemies - *value = (ent->svFlags&SVF_IGNORE_ENEMIES); + case SET_IGNOREENEMIES: //## %t="BOOL_TYPES" # Do not acquire enemies + *value = (ent->svFlags & SVF_IGNORE_ENEMIES); break; - case SET_IGNOREALERTS://## Do not get enemy set by allies in area(ambush) - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_IGNOREALERTS, %s not an NPC\n", ent->targetname ); + case SET_IGNOREALERTS: //## Do not get enemy set by allies in area(ambush) + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_IGNOREALERTS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_IGNORE_ALERTS); + *value = (ent->NPC->scriptFlags & SCF_IGNORE_ALERTS); break; - case SET_DONTSHOOT://## %t="BOOL_TYPES" # Others won't shoot you - *value = (ent->flags&FL_DONT_SHOOT); + case SET_DONTSHOOT: //## %t="BOOL_TYPES" # Others won't shoot you + *value = (ent->flags & FL_DONT_SHOOT); break; - case SET_NOTARGET://## %t="BOOL_TYPES" # Others won't pick you as enemy - *value = (ent->flags&FL_NOTARGET); + case SET_NOTARGET: //## %t="BOOL_TYPES" # Others won't pick you as enemy + *value = (ent->flags & FL_NOTARGET); break; - case SET_DONTFIRE://## %t="BOOL_TYPES" # Don't fire your weapon - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_DONTFIRE, %s not an NPC\n", ent->targetname ); + case SET_DONTFIRE: //## %t="BOOL_TYPES" # Don't fire your weapon + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_DONTFIRE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_DONT_FIRE); + *value = (ent->NPC->scriptFlags & SCF_DONT_FIRE); break; - case SET_LOCKED_ENEMY://## %t="BOOL_TYPES" # Keep current enemy until dead - *value = (ent->svFlags&SVF_LOCKEDENEMY); + case SET_LOCKED_ENEMY: //## %t="BOOL_TYPES" # Keep current enemy until dead + *value = (ent->svFlags & SVF_LOCKEDENEMY); break; - case SET_CROUCHED://## %t="BOOL_TYPES" # Force NPC to crouch - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_CROUCHED, %s not an NPC\n", ent->targetname ); + case SET_CROUCHED: //## %t="BOOL_TYPES" # Force NPC to crouch + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_CROUCHED, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_CROUCHED); + *value = (ent->NPC->scriptFlags & SCF_CROUCHED); break; - case SET_WALKING://## %t="BOOL_TYPES" # Force NPC to move at walkSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_WALKING, %s not an NPC\n", ent->targetname ); + case SET_WALKING: //## %t="BOOL_TYPES" # Force NPC to move at walkSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_WALKING, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_WALKING); + *value = (ent->NPC->scriptFlags & SCF_WALKING); break; - case SET_RUNNING://## %t="BOOL_TYPES" # Force NPC to move at runSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_RUNNING, %s not an NPC\n", ent->targetname ); + case SET_RUNNING: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_RUNNING, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_RUNNING); + *value = (ent->NPC->scriptFlags & SCF_RUNNING); break; - case SET_CHASE_ENEMIES://## %t="BOOL_TYPES" # NPC will chase after enemies - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_CHASE_ENEMIES, %s not an NPC\n", ent->targetname ); + case SET_CHASE_ENEMIES: //## %t="BOOL_TYPES" # NPC will chase after enemies + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_CHASE_ENEMIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_CHASE_ENEMIES); + *value = (ent->NPC->scriptFlags & SCF_CHASE_ENEMIES); break; - case SET_LOOK_FOR_ENEMIES://## %t="BOOL_TYPES" # NPC will be on the lookout for enemies - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_LOOK_FOR_ENEMIES, %s not an NPC\n", ent->targetname ); + case SET_LOOK_FOR_ENEMIES: //## %t="BOOL_TYPES" # NPC will be on the lookout for enemies + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_LOOK_FOR_ENEMIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES); + *value = (ent->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES); break; - case SET_FACE_MOVE_DIR://## %t="BOOL_TYPES" # NPC will face in the direction it's moving - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FACE_MOVE_DIR, %s not an NPC\n", ent->targetname ); + case SET_FACE_MOVE_DIR: //## %t="BOOL_TYPES" # NPC will face in the direction it's moving + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FACE_MOVE_DIR, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_FACE_MOVE_DIR); + *value = (ent->NPC->scriptFlags & SCF_FACE_MOVE_DIR); break; - case SET_FORCED_MARCH://## %t="BOOL_TYPES" # Force NPC to move at runSpeed - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FORCED_MARCH, %s not an NPC\n", ent->targetname ); + case SET_FORCED_MARCH: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FORCED_MARCH, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SET_FORCED_MARCH); + *value = (ent->NPC->scriptFlags & SET_FORCED_MARCH); break; - case SET_UNDYING://## %t="BOOL_TYPES" # Can take damage down to 1 but not die - *value = (ent->flags&FL_UNDYING); + case SET_UNDYING: //## %t="BOOL_TYPES" # Can take damage down to 1 but not die + *value = (ent->flags & FL_UNDYING); break; - case SET_NOAVOID://## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NOAVOID, %s not an NPC\n", ent->targetname ); + case SET_NOAVOID: //## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NOAVOID, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_NO_COLL_AVOID); + *value = (ent->NPC->aiFlags & NPCAI_NO_COLL_AVOID); break; - case SET_SOLID://## %t="BOOL_TYPES" # Make yourself notsolid or solid + case SET_SOLID: //## %t="BOOL_TYPES" # Make yourself notsolid or solid *value = ent->contents; break; - case SET_PLAYER_USABLE://## %t="BOOL_TYPES" # Can be activateby the player's "use" button - *value = (ent->svFlags&SVF_PLAYER_USABLE); + case SET_PLAYER_USABLE: //## %t="BOOL_TYPES" # Can be activateby the player's "use" button + *value = (ent->svFlags & SVF_PLAYER_USABLE); break; - case SET_LOOP_ANIM://## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence + case SET_LOOP_ANIM: //## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence *value = ent->loopAnim; break; - case SET_INTERFACE://## %t="BOOL_TYPES" # Player interface on/off - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_INTERFACE not implemented\n" ); + case SET_INTERFACE: //## %t="BOOL_TYPES" # Player interface on/off + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_INTERFACE not implemented\n"); return false; break; - case SET_SHIELDS://## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_SHIELDS, %s not an NPC\n", ent->targetname ); + case SET_SHIELDS: //## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_SHIELDS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_SHIELDS); + *value = (ent->NPC->aiFlags & NPCAI_SHIELDS); break; - case SET_INVISIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - *value = (ent->s.eFlags&EF_NODRAW); + case SET_INVISIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + *value = (ent->s.eFlags & EF_NODRAW); break; - case SET_VAMPIRE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - if ( !ent->client ) - { + case SET_VAMPIRE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + if (!ent->client) { return false; - } - else - { - *value = (ent->client->ps.powerups[PW_DISINT_2]>level.time); + } else { + *value = (ent->client->ps.powerups[PW_DISINT_2] > level.time); } break; - case SET_FORCE_INVINCIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - if ( !ent->client ) - { + case SET_FORCE_INVINCIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + if (!ent->client) { return false; - } - else - { - *value = (ent->client->ps.powerups[PW_INVINCIBLE]>level.time); + } else { + *value = (ent->client->ps.powerups[PW_INVINCIBLE] > level.time); } break; - case SET_GREET_ALLIES://## %t="BOOL_TYPES" # Makes an NPC greet teammates - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_GREET_ALLIES, %s not an NPC\n", ent->targetname ); + case SET_GREET_ALLIES: //## %t="BOOL_TYPES" # Makes an NPC greet teammates + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_GREET_ALLIES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->aiFlags&NPCAI_GREET_ALLIES); + *value = (ent->NPC->aiFlags & NPCAI_GREET_ALLIES); break; - case SET_VIDEO_FADE_IN://## %t="BOOL_TYPES" # Makes video playback fade in - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_IN not implemented\n" ); + case SET_VIDEO_FADE_IN: //## %t="BOOL_TYPES" # Makes video playback fade in + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_IN not implemented\n"); return false; break; - case SET_VIDEO_FADE_OUT://## %t="BOOL_TYPES" # Makes video playback fade out - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_OUT not implemented\n" ); + case SET_VIDEO_FADE_OUT: //## %t="BOOL_TYPES" # Makes video playback fade out + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_OUT not implemented\n"); return false; break; - case SET_PLAYER_LOCKED://## %t="BOOL_TYPES" # Makes it so player cannot move + case SET_PLAYER_LOCKED: //## %t="BOOL_TYPES" # Makes it so player cannot move *value = player_locked; break; - case SET_LOCK_PLAYER_WEAPONS://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons - *value = (ent->flags&FL_LOCK_PLAYER_WEAPONS); + case SET_LOCK_PLAYER_WEAPONS: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + *value = (ent->flags & FL_LOCK_PLAYER_WEAPONS); break; - case SET_NO_IMPACT_DAMAGE://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons - *value = (ent->flags&FL_NO_IMPACT_DMG); + case SET_NO_IMPACT_DAMAGE: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + *value = (ent->flags & FL_NO_IMPACT_DMG); break; - case SET_NO_KNOCKBACK://## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons - *value = (ent->flags&FL_NO_KNOCKBACK); + case SET_NO_KNOCKBACK: //## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons + *value = (ent->flags & FL_NO_KNOCKBACK); break; - case SET_ALT_FIRE://## %t="BOOL_TYPES" # Force NPC to use altfire when shooting - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ALT_FIRE, %s not an NPC\n", ent->targetname ); + case SET_ALT_FIRE: //## %t="BOOL_TYPES" # Force NPC to use altfire when shooting + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ALT_FIRE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_ALT_FIRE); + *value = (ent->NPC->scriptFlags & SCF_ALT_FIRE); break; - case SET_NO_RESPONSE://## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_RESPONSE, %s not an NPC\n", ent->targetname ); + case SET_NO_RESPONSE: //## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_RESPONSE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_RESPONSE); + *value = (ent->NPC->scriptFlags & SCF_NO_RESPONSE); break; - case SET_INVINCIBLE://## %t="BOOL_TYPES" # Completely unkillable - *value = (ent->flags&FL_GODMODE); + case SET_INVINCIBLE: //## %t="BOOL_TYPES" # Completely unkillable + *value = (ent->flags & FL_GODMODE); break; - case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen + case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen *value = cg.missionStatusShow; break; - case SET_NO_COMBAT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_COMBAT_TALK, %s not an NPC\n", ent->targetname ); + case SET_NO_COMBAT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_COMBAT_TALK, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_COMBAT_TALK); + *value = (ent->NPC->scriptFlags & SCF_NO_COMBAT_TALK); break; - case SET_NO_ALERT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_ALERT_TALK, %s not an NPC\n", ent->targetname ); + case SET_NO_ALERT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_ALERT_TALK, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_ALERT_TALK); + *value = (ent->NPC->scriptFlags & SCF_NO_ALERT_TALK); break; - case SET_USE_CP_NEAREST://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_USE_CP_NEAREST, %s not an NPC\n", ent->targetname ); + case SET_USE_CP_NEAREST: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_USE_CP_NEAREST, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_USE_CP_NEAREST); + *value = (ent->NPC->scriptFlags & SCF_USE_CP_NEAREST); break; - case SET_DISMEMBERABLE://## %t="BOOL_TYPES" # NPC will not be affected by force powers - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_DISMEMBERABLE, %s not a client\n", ent->targetname ); + case SET_DISMEMBERABLE: //## %t="BOOL_TYPES" # NPC will not be affected by force powers + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_DISMEMBERABLE, %s not a client\n", ent->targetname); return false; } *value = !(ent->client->dismembered); break; case SET_NO_FORCE: - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_FORCE, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_FORCE, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_FORCE); + *value = (ent->NPC->scriptFlags & SCF_NO_FORCE); break; case SET_NO_ACROBATICS: - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_ACROBATICS, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_ACROBATICS, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_ACROBATICS); + *value = (ent->NPC->scriptFlags & SCF_NO_ACROBATICS); break; case SET_USE_SUBTITLES: - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_USE_SUBTITLES, %s not an NPC\n", ent->targetname ); + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_USE_SUBTITLES, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_USE_SUBTITLES); + *value = (ent->NPC->scriptFlags & SCF_USE_SUBTITLES); break; - case SET_NO_FALLTODEATH://## %t="BOOL_TYPES" # NPC will not be affected by force powers - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_NO_FALLTODEATH, %s not an NPC\n", ent->targetname ); + case SET_NO_FALLTODEATH: //## %t="BOOL_TYPES" # NPC will not be affected by force powers + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_NO_FALLTODEATH, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_NO_FALLTODEATH); + *value = (ent->NPC->scriptFlags & SCF_NO_FALLTODEATH); break; - case SET_MORELIGHT://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_MORELIGHT, %s not an NPC\n", ent->targetname ); + case SET_MORELIGHT: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_MORELIGHT, %s not an NPC\n", ent->targetname); return false; } - *value = (ent->NPC->scriptFlags&SCF_MORELIGHT); + *value = (ent->NPC->scriptFlags & SCF_MORELIGHT); break; - case SET_TREASONED://## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig - Q3_DebugPrint( WL_VERBOSE, "SET_TREASONED is disabled, do not use\n" ); - *value = 0;//(ffireLevel>=FFIRE_LEVEL_RETALIATION); + case SET_TREASONED: //## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig + Q3_DebugPrint(WL_VERBOSE, "SET_TREASONED is disabled, do not use\n"); + *value = 0; //(ffireLevel>=FFIRE_LEVEL_RETALIATION); break; - case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate + case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate *value = (ent->s.eFlags & EF_DISABLE_SHADER_ANIM); break; - case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control + case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control *value = (ent->s.eFlags & EF_SHADER_ANIM); break; default: - if ( Q3_VariableDeclared( name ) != VTYPE_FLOAT ) + if (Q3_VariableDeclared(name) != VTYPE_FLOAT) return false; - return Q3_GetFloatVariable( name, value ); + return Q3_GetFloatVariable(name, value); } return true; } - /* ============ Q3_GetVector - Description : - Return type : int + Description : + Return type : int Argument : int entID Argument : int type Argument : const char *name Argument : vec3_t value ============ */ -static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) -{ - gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { +static int Q3_GetVector(int entID, int type, const char *name, vec3_t value) { + gentity_t *ent = &g_entities[entID]; + if (!ent) { return false; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -8551,7 +7400,7 @@ static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - sscanf( ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2] ); + sscanf(ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2]); break; case SET_ORIGIN: @@ -8561,18 +7410,18 @@ static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) case SET_ANGLES: VectorCopy(ent->currentAngles, value); break; - - case SET_TELEPORT_DEST://## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear - Q3_DebugPrint( WL_WARNING, "Q3_GetVector: SET_TELEPORT_DEST not implemented\n" ); + + case SET_TELEPORT_DEST: //## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear + Q3_DebugPrint(WL_WARNING, "Q3_GetVector: SET_TELEPORT_DEST not implemented\n"); return false; break; default: - if ( Q3_VariableDeclared( name ) != VTYPE_VECTOR ) + if (Q3_VariableDeclared(name) != VTYPE_VECTOR) return false; - return Q3_GetVectorVariable( name, value ); + return Q3_GetVectorVariable(name, value); } return true; @@ -8581,43 +7430,39 @@ static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) /* ============ Q3_GetString - Description : - Return type : int + Description : + Return type : int Argument : int entID Argument : int type Argument : const char *name Argument : char **value ============ */ -static int Q3_GetString( int entID, int type, const char *name, char **value ) -{ - gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { +static int Q3_GetString(int entID, int type, const char *name, char **value) { + gentity_t *ent = &g_entities[entID]; + if (!ent) { return false; } - if( strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5) ) - { - const char* cvar_name = name + 5; + if (strlen(name) > 5 && !Q_stricmpn(name, "cvar_", 5)) { + const char *cvar_name = name + 5; // by allocating and then re-using the same sufficiently large buffer, // we ensure that pointers to it never become invalid, // so we can support expressions using the same cvar twice, // e.g. if(get(cvar_x) == get(cvar_x)) - std::array& buf = ICARUS_CvarList[cvar_name]; + std::array &buf = ICARUS_CvarList[cvar_name]; gi.Cvar_VariableStringBuffer(cvar_name, buf.data(), buf.size()); *value = buf.data(); return true; } - int toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well + int toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well - switch ( toGet ) - { + switch (toGet) { case SET_ANIM_BOTH: - *value = (char *) Q3_GetAnimBoth( ent ); + *value = (char *)Q3_GetAnimBoth(ent); - if ( VALIDSTRING( *value ) == false ) + if (VALIDSTRING(*value) == false) return false; break; @@ -8638,241 +7483,218 @@ static int Q3_GetString( int entID, int type, const char *name, char **value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if ( ent->parms ) - { - *value = (char *) ent->parms->parm[toGet - SET_PARM1]; - } - else - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: invalid ent %s has no parms!\n", ent->targetname ); + if (ent->parms) { + *value = (char *)ent->parms->parm[toGet - SET_PARM1]; + } else { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: invalid ent %s has no parms!\n", ent->targetname); return false; } break; case SET_TARGET: - *value = (char *) ent->target; + *value = (char *)ent->target; break; case SET_LOCATION: - *value = G_GetLocationForEnt( ent ); - if ( !value || !value[0] ) - { + *value = G_GetLocationForEnt(ent); + if (!value || !value[0]) { return false; } break; //# #sep Scripts and other file paths - case SET_SPAWNSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to BSET_SPAWN, etc + case SET_SPAWNSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to + //BSET_SPAWN, etc *value = ent->behaviorSet[BSET_SPAWN]; break; - case SET_USESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used + case SET_USESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used *value = ent->behaviorSet[BSET_USE]; break; - case SET_AWAKESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled + case SET_AWAKESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled *value = ent->behaviorSet[BSET_AWAKE]; break; - case SET_ANGERSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time + case SET_ANGERSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time *value = ent->behaviorSet[BSET_ANGER]; break; - case SET_ATTACKSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot + case SET_ATTACKSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot *value = ent->behaviorSet[BSET_ATTACK]; break; - case SET_VICTORYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone + case SET_VICTORYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone *value = ent->behaviorSet[BSET_VICTORY]; break; - case SET_LOSTENEMYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy + case SET_LOSTENEMYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy *value = ent->behaviorSet[BSET_LOSTENEMY]; break; - case SET_PAINSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit + case SET_PAINSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit *value = ent->behaviorSet[BSET_PAIN]; break; - case SET_FLEESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health + case SET_FLEESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health *value = ent->behaviorSet[BSET_FLEE]; break; - case SET_DEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed + case SET_DEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed *value = ent->behaviorSet[BSET_DEATH]; break; - case SET_DELAYEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay + case SET_DELAYEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay *value = ent->behaviorSet[BSET_DELAYED]; break; - case SET_BLOCKEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate + case SET_BLOCKEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate *value = ent->behaviorSet[BSET_BLOCKED]; break; - case SET_FFIRESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly + case SET_FFIRESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly *value = ent->behaviorSet[BSET_FFIRE]; break; - case SET_FFDEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate + case SET_FFDEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate *value = ent->behaviorSet[BSET_FFDEATH]; break; //# #sep Standard strings - case SET_ENEMY://## %s="NULL" # Set enemy by targetname - if ( ent->enemy != NULL ) - { + case SET_ENEMY: //## %s="NULL" # Set enemy by targetname + if (ent->enemy != NULL) { *value = ent->enemy->targetname; - } - else return false; + } else + return false; break; - case SET_LEADER://## %s="NULL" # Set for BS_FOLLOW_LEADER - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_LEADER, %s not a client\n", ent->targetname ); + case SET_LEADER: //## %s="NULL" # Set for BS_FOLLOW_LEADER + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_LEADER, %s not a client\n", ent->targetname); return false; - } - else if ( ent->client->leader ) - { + } else if (ent->client->leader) { *value = ent->client->leader->targetname; - } - else return false; + } else + return false; break; - case SET_CAPTURE://## %s="NULL" # Set captureGoal by targetname - if ( ent->NPC == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_CAPTURE, %s not an NPC\n", ent->targetname ); + case SET_CAPTURE: //## %s="NULL" # Set captureGoal by targetname + if (ent->NPC == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_CAPTURE, %s not an NPC\n", ent->targetname); return false; - } - else if ( ent->NPC->captureGoal != NULL ) - { + } else if (ent->NPC->captureGoal != NULL) { *value = ent->NPC->captureGoal->targetname; - } - else return false; + } else + return false; break; - case SET_TARGETNAME://## %s="NULL" # Set/change your targetname + case SET_TARGETNAME: //## %s="NULL" # Set/change your targetname *value = ent->targetname; break; - case SET_PAINTARGET://## %s="NULL" # Set/change what to use when hit + case SET_PAINTARGET: //## %s="NULL" # Set/change what to use when hit *value = ent->paintarget; break; - case SET_CAMERA_GROUP://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP: //## %s="NULL" # all ents with this cameraGroup will be focused on *value = ent->cameraGroup; break; - case SET_CAMERA_GROUP_TAG://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_TAG: //## %s="NULL" # all ents with this cameraGroup will be focused on return false; break; - case SET_LOOK_TARGET://## %s="NULL" # object for NPC to look at - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOOK_TARGET, %s not a client\n", ent->targetname ); + case SET_LOOK_TARGET: //## %s="NULL" # object for NPC to look at + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOOK_TARGET, %s not a client\n", ent->targetname); return false; - } - else - { + } else { gentity_t *lookTarg = &g_entities[ent->client->renderInfo.lookTarget]; - if ( lookTarg != NULL ) - { + if (lookTarg != NULL) { *value = lookTarg->targetname; - } - else return false; + } else + return false; } break; - case SET_TARGET2://## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo + case SET_TARGET2: //## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo *value = ent->target2; break; - case SET_REMOVE_TARGET://## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState + case SET_REMOVE_TARGET: //## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState *value = ent->target3; break; case SET_WEAPON: - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_WEAPON, %s not a client\n", ent->targetname ); + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_WEAPON, %s not a client\n", ent->targetname); return false; - } - else - { - *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); + } else { + *value = (char *)GetStringForID(WPTable, ent->client->ps.weapon); } break; case SET_ITEM: - if ( ent->client == NULL ) - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_ITEM, %s not a client\n", ent->targetname ); + if (ent->client == NULL) { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_ITEM, %s not a client\n", ent->targetname); return false; - } - else - { - // *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); + } else { + // *value = (char *)GetStringForID( WPTable, ent->client->ps.weapon ); } break; case SET_MUSIC_STATE: - *value = (char *)GetStringForID( DMSTable, level.dmState ); + *value = (char *)GetStringForID(DMSTable, level.dmState); break; - //The below cannot be gotten - case SET_NAVGOAL://## %s="NULL" # *Move to this navgoal then continue script - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_NAVGOAL not implemented\n" ); + // The below cannot be gotten + case SET_NAVGOAL: //## %s="NULL" # *Move to this navgoal then continue script + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_NAVGOAL not implemented\n"); return false; break; - case SET_VIEWTARGET://## %s="NULL" # Set angles toward ent by targetname - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIEWTARGET not implemented\n" ); + case SET_VIEWTARGET: //## %s="NULL" # Set angles toward ent by targetname + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIEWTARGET not implemented\n"); return false; break; - case SET_WATCHTARGET://## %s="NULL" # Set angles toward ent by targetname - if ( ent && ent->NPC && ent->NPC->watchTarget ) - { + case SET_WATCHTARGET: //## %s="NULL" # Set angles toward ent by targetname + if (ent && ent->NPC && ent->NPC->watchTarget) { *value = ent->NPC->watchTarget->targetname; - } - else - { - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_WATCHTARGET no watchTarget!\n" ); + } else { + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_WATCHTARGET no watchTarget!\n"); return false; } break; case SET_VIEWENTITY: - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIEWENTITY not implemented\n" ); + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIEWENTITY not implemented\n"); return false; break; - case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_CAPTIONTEXTCOLOR not implemented\n" ); + case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_CAPTIONTEXTCOLOR not implemented\n"); return false; break; - case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_CENTERTEXTCOLOR not implemented\n" ); + case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_CENTERTEXTCOLOR not implemented\n"); return false; break; - case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_SCROLLTEXTCOLOR not implemented\n" ); + case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_SCROLLTEXTCOLOR not implemented\n"); return false; break; - case SET_COPY_ORIGIN://## %s="targetname" # Copy the origin of the ent with targetname to your origin - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_COPY_ORIGIN: //## %s="targetname" # Copy the origin of the ent with targetname to your origin + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n"); return false; break; - case SET_DEFEND_TARGET://## %s="targetname" # This NPC will attack the target NPC's enemies - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_DEFEND_TARGET: //## %s="targetname" # This NPC will attack the target NPC's enemies + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n"); return false; break; - case SET_VIDEO_PLAY://## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIDEO_PLAY not implemented\n" ); + case SET_VIDEO_PLAY: //## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIDEO_PLAY not implemented\n"); return false; break; - case SET_LOADGAME://## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOADGAME not implemented\n" ); + case SET_LOADGAME: //## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOADGAME not implemented\n"); return false; break; - case SET_LOCKYAW://## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOCKYAW not implemented\n" ); + case SET_LOCKYAW: //## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOCKYAW not implemented\n"); return false; break; - case SET_SCROLLTEXT: //## %s="" # key of text string to print - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_SCROLLTEXT not implemented\n" ); + case SET_SCROLLTEXT: //## %s="" # key of text string to print + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_SCROLLTEXT not implemented\n"); return false; break; - case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame - Q3_DebugPrint( WL_WARNING, "Q3_GetString: SET_LCARSTEXT not implemented\n" ); + case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame + Q3_DebugPrint(WL_WARNING, "Q3_GetString: SET_LCARSTEXT not implemented\n"); return false; break; - case SET_FULLNAME://## %s="NULL" # Set/change your targetname + case SET_FULLNAME: //## %s="NULL" # Set/change your targetname *value = ent->fullName; break; default: - if ( Q3_VariableDeclared( name ) != VTYPE_STRING ) + if (Q3_VariableDeclared(name) != VTYPE_STRING) return false; - return Q3_GetStringVariable( name, (const char **) value ); + return Q3_GetStringVariable(name, (const char **)value); } return true; @@ -8881,8 +7703,8 @@ static int Q3_GetString( int entID, int type, const char *name, char **value ) /* ============ Q3_Evaluate - Description : - Return type : int + Description : + Return type : int Argument : int p1Type Argument : const char *p1 Argument : int p2Type @@ -8890,197 +7712,188 @@ Q3_Evaluate Argument : int operatorType ============ */ -static int Q3_Evaluate( int p1Type, const char *p1, int p2Type, const char *p2, int operatorType ) -{ - float f1=0, f2=0; - vec3_t v1, v2; - char *c1=0, *c2=0; - int i1=0, i2=0; +static int Q3_Evaluate(int p1Type, const char *p1, int p2Type, const char *p2, int operatorType) { + float f1 = 0, f2 = 0; + vec3_t v1, v2; + char *c1 = 0, *c2 = 0; + int i1 = 0, i2 = 0; - //Always demote to int on float to integer comparisons - if ( ( ( p1Type == TK_FLOAT ) && ( p2Type == TK_INT ) ) || ( ( p1Type == TK_INT ) && ( p2Type == TK_FLOAT ) ) ) - { + // Always demote to int on float to integer comparisons + if (((p1Type == TK_FLOAT) && (p2Type == TK_INT)) || ((p1Type == TK_INT) && (p2Type == TK_FLOAT))) { p1Type = TK_INT; p2Type = TK_INT; } - //Cannot compare two disimilar types - if ( p1Type != p2Type ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate comparing two disimilar types!\n"); + // Cannot compare two disimilar types + if (p1Type != p2Type) { + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate comparing two disimilar types!\n"); return false; } - //Format the parameters - switch ( p1Type ) - { + // Format the parameters + switch (p1Type) { case TK_FLOAT: - sscanf( p1, "%f", &f1 ); - sscanf( p2, "%f", &f2 ); + sscanf(p1, "%f", &f1); + sscanf(p2, "%f", &f2); break; case TK_INT: - sscanf( p1, "%d", &i1 ); - sscanf( p2, "%d", &i2 ); + sscanf(p1, "%d", &i1); + sscanf(p2, "%d", &i2); break; case TK_VECTOR: - sscanf( p1, "%f %f %f", &v1[0], &v1[1], &v1[2] ); - sscanf( p2, "%f %f %f", &v2[0], &v2[1], &v2[2] ); + sscanf(p1, "%f %f %f", &v1[0], &v1[1], &v1[2]); + sscanf(p2, "%f %f %f", &v2[0], &v2[1], &v2[2]); break; case TK_STRING: case TK_IDENTIFIER: - c1 = (char *) p1; - c2 = (char *) p2; + c1 = (char *)p1; + c2 = (char *)p2; break; default: - Q3_DebugPrint( WL_WARNING, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_WARNING, "Q3_Evaluate unknown type used!\n"); return false; } - //Compare them and return the result + // Compare them and return the result - //FIXME: YUCK!!! Better way to do this? + // FIXME: YUCK!!! Better way to do this? - switch ( operatorType ) - { + switch (operatorType) { - // - // EQUAL TO - // + // + // EQUAL TO + // case TK_EQUALS: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 == f2 ); + return (int)(f1 == f2); break; case TK_INT: - return (int) ( i1 == i2 ); + return (int)(i1 == i2); break; case TK_VECTOR: - return (int) VectorCompare( v1, v2 ); + return (int)VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) !Q_stricmp( c1, c2 ); //NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) + return (int)!Q_stricmp(c1, c2); // NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // GREATER THAN - // + // + // GREATER THAN + // case TK_GREATER_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 > f2 ); + return (int)(f1 > f2); break; case TK_INT: - return (int) ( i1 > i2 ); + return (int)(i1 > i2); break; case TK_VECTOR: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate vector comparisons of type GREATER THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate vector comparisons of type GREATER THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate string comparisons of type GREATER THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate string comparisons of type GREATER THAN cannot be performed!"); return false; break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // LESS THAN - // + // + // LESS THAN + // case TK_LESS_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 < f2 ); + return (int)(f1 < f2); break; case TK_INT: - return (int) ( i1 < i2 ); + return (int)(i1 < i2); break; case TK_VECTOR: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate vector comparisons of type LESS THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate vector comparisons of type LESS THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate string comparisons of type LESS THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate string comparisons of type LESS THAN cannot be performed!"); return false; break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // NOT - // + // + // NOT + // - case TK_NOT: //NOTENOTE: Implied "NOT EQUAL TO" + case TK_NOT: // NOTENOTE: Implied "NOT EQUAL TO" - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 != f2 ); + return (int)(f1 != f2); break; case TK_INT: - return (int) ( i1 != i2 ); + return (int)(i1 != i2); break; case TK_VECTOR: - return (int) !VectorCompare( v1, v2 ); + return (int)!VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) Q_stricmp( c1, c2 ); + return (int)Q_stricmp(c1, c2); break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - + default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown operator used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown operator used!\n"); break; } @@ -9092,9 +7905,8 @@ static int Q3_Evaluate( int p1Type, const char *p1, int p2Type, const char *p2, Q3_CameraFade ------------------------- */ -static void Q3_CameraFade( float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration ) -{ - vec4_t src, dst; +static void Q3_CameraFade(float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration) { + vec4_t src, dst; src[0] = sr; src[1] = sg; @@ -9106,7 +7918,7 @@ static void Q3_CameraFade( float sr, float sg, float sb, float sa, float dr, flo dst[2] = db; dst[3] = da; - CGCam_Fade( src, dst, duration ); + CGCam_Fade(src, dst, duration); } /* @@ -9114,63 +7926,57 @@ static void Q3_CameraFade( float sr, float sg, float sb, float sa, float dr, flo Q3_CameraPath ------------------------- */ -static void Q3_CameraPath( const char *name ) -{ - CGCam_StartRoff( G_NewString( name ) ); -} +static void Q3_CameraPath(const char *name) { CGCam_StartRoff(G_NewString(name)); } /* ------------------------- Q3_DebugPrint ------------------------- */ -void Q3_DebugPrint( int level, const char *format, ... ) -{ - //Don't print messages they don't want to see - if ( g_ICARUSDebug->integer < level ) +void Q3_DebugPrint(int level, const char *format, ...) { + // Don't print messages they don't want to see + if (g_ICARUSDebug->integer < level) return; - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr, format); - Q_vsnprintf (text, sizeof(text), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(text, sizeof(text), format, argptr); + va_end(argptr); - //Add the color formatting - switch ( level ) - { - case WL_ERROR: - Com_Printf ( S_COLOR_RED"ERROR: %s", text ); - break; - - case WL_WARNING: - Com_Printf ( S_COLOR_YELLOW"WARNING: %s", text ); - break; - - case WL_DEBUG: - { - int entNum; - char *buffer; + // Add the color formatting + switch (level) { + case WL_ERROR: + Com_Printf(S_COLOR_RED "ERROR: %s", text); + break; - sscanf( text, "%d", &entNum ); + case WL_WARNING: + Com_Printf(S_COLOR_YELLOW "WARNING: %s", text); + break; - if ( ( ICARUS_entFilter >= 0 ) && ( ICARUS_entFilter != entNum ) ) - return; + case WL_DEBUG: { + int entNum; + char *buffer; - buffer = (char *) text; - buffer += 5; + sscanf(text, "%d", &entNum); - if ( ( entNum < 0 ) || ( entNum >= MAX_GENTITIES ) ) - entNum = 0; + if ((ICARUS_entFilter >= 0) && (ICARUS_entFilter != entNum)) + return; - Com_Printf ( S_COLOR_BLUE"DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer ); - break; - } - default: - case WL_VERBOSE: - Com_Printf ( S_COLOR_GREEN"INFO: %s", text ); - break; + buffer = (char *)text; + buffer += 5; + + if ((entNum < 0) || (entNum >= MAX_GENTITIES)) + entNum = 0; + + Com_Printf(S_COLOR_BLUE "DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer); + break; + } + default: + case WL_VERBOSE: + Com_Printf(S_COLOR_GREEN "INFO: %s", text); + break; } } @@ -9179,31 +7985,28 @@ void Q3_DebugPrint( int level, const char *format, ... ) Q3_Play ------------------------- */ -static void Q3_Play( int taskID, int entID, const char *type, const char *name ) -{ +static void Q3_Play(int taskID, int entID, const char *type, const char *name) { gentity_t *ent = &g_entities[entID]; - if ( !Q_stricmp( type, "PLAY_ROFF" ) ) - { + if (!Q_stricmp(type, "PLAY_ROFF")) { // Try to load the requested ROFF - if ( G_LoadRoff( name ) ) - { - ent->roff = G_NewString( name ); + if (G_LoadRoff(name)) { + ent->roff = G_NewString(name); // Start the roff from the beginning ent->roff_ctr = 0; - //Save this off for later - Q3_TaskIDSet( ent, TID_MOVE_NAV, taskID ); + // Save this off for later + Q3_TaskIDSet(ent, TID_MOVE_NAV, taskID); // Let the ROFF playing start. ent->next_roff_time = level.time; // These need to be initialised up front... - VectorCopy( ent->currentOrigin, ent->pos1 ); - VectorCopy( ent->currentAngles, ent->pos2 ); - - gi.linkentity( ent ); + VectorCopy(ent->currentOrigin, ent->pos1); + VectorCopy(ent->currentAngles, ent->pos2); + + gi.linkentity(ent); } } } @@ -9212,78 +8015,75 @@ static void Q3_Play( int taskID, int entID, const char *type, const char *name ) ============ Interface_Init Description : Inits the interface for the game - Return type : void + Return type : void Argument : interface_export_t *pe ============ */ -void Interface_Init( interface_export_t *pe ) -{ - //TODO: This is where you link up all your functions to the engine - - //General - pe->I_LoadFile = Q3_ReadScript; - pe->I_CenterPrint = Q3_CenterPrint; - pe->I_DPrintf = Q3_DebugPrint; - pe->I_GetEntityByName = Q3_GetEntityByName; - pe->I_GetTime = Q3_GetTime; - pe->I_GetTimeScale = Q3_GetTimeScale; - pe->I_PlaySound = Q3_PlaySound; - pe->I_Lerp2Pos = Q3_Lerp2Pos; - pe->I_Lerp2Origin = Q3_Lerp2Origin; - pe->I_Lerp2Angles = Q3_Lerp2Angles; - pe->I_GetTag = Q3_GetTag; - pe->I_Lerp2Start = Q3_Lerp2Start; - pe->I_Lerp2End = Q3_Lerp2End; - pe->I_Use = Q3_Use; - pe->I_Kill = Q3_Kill; - pe->I_Remove = Q3_Remove; - pe->I_Set = Q3_Set; - pe->I_Random = Q_flrand; - pe->I_Play = Q3_Play; - - //Camera functions - pe->I_CameraEnable = CGCam_Enable; - pe->I_CameraDisable = CGCam_Disable; - pe->I_CameraZoom = CGCam_Zoom; - pe->I_CameraMove = CGCam_Move; - pe->I_CameraPan = CGCam_Pan; - pe->I_CameraRoll = CGCam_Roll; - pe->I_CameraTrack = CGCam_Track; - pe->I_CameraFollow = CGCam_Follow; - pe->I_CameraDistance = CGCam_Distance; - pe->I_CameraShake = CGCam_Shake; - pe->I_CameraFade = Q3_CameraFade; - pe->I_CameraPath = Q3_CameraPath; - - //Variable information - pe->I_GetFloat = Q3_GetFloat; - pe->I_GetVector = Q3_GetVector; - pe->I_GetString = Q3_GetString; - - pe->I_Evaluate = Q3_Evaluate; - - pe->I_DeclareVariable = Q3_DeclareVariable; - pe->I_FreeVariable = Q3_FreeVariable; - - //Save / Load functions - pe->I_LinkEntity = ICARUS_LinkEntity; +void Interface_Init(interface_export_t *pe) { + // TODO: This is where you link up all your functions to the engine + + // General + pe->I_LoadFile = Q3_ReadScript; + pe->I_CenterPrint = Q3_CenterPrint; + pe->I_DPrintf = Q3_DebugPrint; + pe->I_GetEntityByName = Q3_GetEntityByName; + pe->I_GetTime = Q3_GetTime; + pe->I_GetTimeScale = Q3_GetTimeScale; + pe->I_PlaySound = Q3_PlaySound; + pe->I_Lerp2Pos = Q3_Lerp2Pos; + pe->I_Lerp2Origin = Q3_Lerp2Origin; + pe->I_Lerp2Angles = Q3_Lerp2Angles; + pe->I_GetTag = Q3_GetTag; + pe->I_Lerp2Start = Q3_Lerp2Start; + pe->I_Lerp2End = Q3_Lerp2End; + pe->I_Use = Q3_Use; + pe->I_Kill = Q3_Kill; + pe->I_Remove = Q3_Remove; + pe->I_Set = Q3_Set; + pe->I_Random = Q_flrand; + pe->I_Play = Q3_Play; + + // Camera functions + pe->I_CameraEnable = CGCam_Enable; + pe->I_CameraDisable = CGCam_Disable; + pe->I_CameraZoom = CGCam_Zoom; + pe->I_CameraMove = CGCam_Move; + pe->I_CameraPan = CGCam_Pan; + pe->I_CameraRoll = CGCam_Roll; + pe->I_CameraTrack = CGCam_Track; + pe->I_CameraFollow = CGCam_Follow; + pe->I_CameraDistance = CGCam_Distance; + pe->I_CameraShake = CGCam_Shake; + pe->I_CameraFade = Q3_CameraFade; + pe->I_CameraPath = Q3_CameraPath; + + // Variable information + pe->I_GetFloat = Q3_GetFloat; + pe->I_GetVector = Q3_GetVector; + pe->I_GetString = Q3_GetString; + + pe->I_Evaluate = Q3_Evaluate; + + pe->I_DeclareVariable = Q3_DeclareVariable; + pe->I_FreeVariable = Q3_FreeVariable; + + // Save / Load functions + pe->I_LinkEntity = ICARUS_LinkEntity; pe->saved_game = gi.saved_game; - gclient_t *client; + gclient_t *client; client = &level.clients[0]; - memset(&client->sess,0,sizeof(client->sess)); + memset(&client->sess, 0, sizeof(client->sess)); } // leave these two as standard mallocs for the moment, there's something weird happening in ICARUS... // -void *ICARUS_Malloc(int iSize) -{ - //return gi.Malloc(iSize, TAG_ICARUS); +void *ICARUS_Malloc(int iSize) { + // return gi.Malloc(iSize, TAG_ICARUS); return malloc(iSize); } -void ICARUS_Free(void *pMem) -{ - //gi.Free(pMem); +void ICARUS_Free(void *pMem) { + // gi.Free(pMem); free(pMem); } diff --git a/codeJK2/game/Q3_Registers.cpp b/codeJK2/game/Q3_Registers.cpp index f278c09085..6fcd3d90be 100644 --- a/codeJK2/game/Q3_Registers.cpp +++ b/codeJK2/game/Q3_Registers.cpp @@ -26,13 +26,13 @@ along with this program; if not, see . #include "Q3_Registers.h" #include "../code/qcommon/ojk_saved_game_helper.h" -extern void Q3_DebugPrint( int level, const char *format, ... ); +extern void Q3_DebugPrint(int level, const char *format, ...); -varString_m varStrings; -varFloat_m varFloats; -varString_m varVectors; //Work around for vector types +varString_m varStrings; +varFloat_m varFloats; +varString_m varVectors; // Work around for vector types -int numVariables = 0; +int numVariables = 0; /* ------------------------- @@ -40,24 +40,23 @@ Q3_VariableDeclared ------------------------- */ -int Q3_VariableDeclared( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_VariableDeclared(const char *name) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) + if (vsi != varStrings.end()) return VTYPE_STRING; - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) + if (vfi != varFloats.end()) return VTYPE_FLOAT; - //Check the vectors - varString_m::iterator vvi = varVectors.find( name ); + // Check the vectors + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) + if (vvi != varVectors.end()) return VTYPE_VECTOR; return VTYPE_NONE; @@ -69,34 +68,31 @@ Q3_DeclareVariable ------------------------- */ -void Q3_DeclareVariable( int type, const char *name ) -{ - //Cannot declare the same variable twice - if ( Q3_VariableDeclared( name ) != VTYPE_NONE ) +void Q3_DeclareVariable(int type, const char *name) { + // Cannot declare the same variable twice + if (Q3_VariableDeclared(name) != VTYPE_NONE) return; - if ( numVariables > MAX_VARIABLES ) - { - Q3_DebugPrint( WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES ); + if (numVariables > MAX_VARIABLES) { + Q3_DebugPrint(WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES); return; } - switch( type ) - { + switch (type) { case TK_FLOAT: - varFloats[ name ] = 0.0f; + varFloats[name] = 0.0f; break; - case TK_STRING: - varStrings[ name ] = "NULL"; + case TK_STRING: + varStrings[name] = "NULL"; break; case TK_VECTOR: - varVectors[ name ] = "0.0 0.0 0.0"; + varVectors[name] = "0.0 0.0 0.0"; break; default: - Q3_DebugPrint( WL_ERROR, "unknown 'type' for declare() function!\n" ); + Q3_DebugPrint(WL_ERROR, "unknown 'type' for declare() function!\n"); return; break; } @@ -110,34 +106,30 @@ Q3_FreeVariable ------------------------- */ -void Q3_FreeVariable( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +void Q3_FreeVariable(const char *name) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) - { - varStrings.erase( vsi ); + if (vsi != varStrings.end()) { + varStrings.erase(vsi); numVariables--; return; } - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) - { - varFloats.erase( vfi ); + if (vfi != varFloats.end()) { + varFloats.erase(vfi); numVariables--; return; } - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) - { - varVectors.erase( vvi ); + if (vvi != varVectors.end()) { + varVectors.erase(vvi); numVariables--; return; } @@ -149,13 +141,11 @@ Q3_GetFloatVariable ------------------------- */ -int Q3_GetFloatVariable( const char *name, float *value ) -{ - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); +int Q3_GetFloatVariable(const char *name, float *value) { + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) - { + if (vfi != varFloats.end()) { *value = (*vfi).second; return true; } @@ -169,14 +159,12 @@ Q3_GetStringVariable ------------------------- */ -int Q3_GetStringVariable( const char *name, const char **value ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_GetStringVariable(const char *name, const char **value) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) - { - *value = (const char *) ((*vsi).second).c_str(); + if (vsi != varStrings.end()) { + *value = (const char *)((*vsi).second).c_str(); return true; } @@ -189,16 +177,14 @@ Q3_GetVectorVariable ------------------------- */ -int Q3_GetVectorVariable( const char *name, vec3_t value ) -{ - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); +int Q3_GetVectorVariable(const char *name, vec3_t value) { + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) - { + if (vvi != varVectors.end()) { const char *str = ((*vvi).second).c_str(); - sscanf( str, "%f %f %f", &value[0], &value[1], &value[2] ); + sscanf(str, "%f %f %f", &value[0], &value[1], &value[2]); return true; } @@ -211,14 +197,13 @@ Q3_InitVariables ------------------------- */ -void Q3_InitVariables( void ) -{ +void Q3_InitVariables(void) { varStrings.clear(); varFloats.clear(); varVectors.clear(); - if ( numVariables > 0 ) - Q3_DebugPrint( WL_WARNING, "%d residual variables found!\n", numVariables ); + if (numVariables > 0) + Q3_DebugPrint(WL_WARNING, "%d residual variables found!\n", numVariables); numVariables = 0; } @@ -229,16 +214,15 @@ Q3_SetVariable_Float ------------------------- */ -int Q3_SetFloatVariable( const char *name, float value ) -{ - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); +int Q3_SetFloatVariable(const char *name, float value) { + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi == varFloats.end() ) + if (vfi == varFloats.end()) return VTYPE_FLOAT; (*vfi).second = value; - + return true; } @@ -248,12 +232,11 @@ Q3_SetVariable_String ------------------------- */ -int Q3_SetStringVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_SetStringVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi == varStrings.end() ) + if (vsi == varStrings.end()) return false; (*vsi).second = value; @@ -267,12 +250,11 @@ Q3_SetVariable_Vector ------------------------- */ -int Q3_SetVectorVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); +int Q3_SetVectorVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi == varVectors.end() ) + if (vvi == varVectors.end()) return false; (*vvi).second = value; @@ -286,37 +268,25 @@ Q3_VariableSaveFloats ------------------------- */ -void Q3_VariableSaveFloats( varFloat_m &fmap ) -{ +void Q3_VariableSaveFloats(varFloat_m &fmap) { int numFloats = fmap.size(); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.write_chunk( - INT_ID('F', 'V', 'A', 'R'), - numFloats); - - varFloat_m::iterator vfi; - STL_ITERATE( vfi, fmap ) - { - //Save out the map id - int idSize = strlen( ((*vfi).first).c_str() ); - - //Save out the real data - saved_game.write_chunk( - INT_ID('F', 'I', 'D', 'L'), - idSize); - - saved_game.write_chunk( - INT_ID('F', 'I', 'D', 'S'), - ((*vfi).first).c_str(), - idSize); - - //Save out the float value - saved_game.write_chunk( - INT_ID('F', 'V', 'A', 'L'), - (*vfi).second); + ojk::SavedGameHelper saved_game(::gi.saved_game); + + saved_game.write_chunk(INT_ID('F', 'V', 'A', 'R'), numFloats); + + varFloat_m::iterator vfi; + STL_ITERATE(vfi, fmap) { + // Save out the map id + int idSize = strlen(((*vfi).first).c_str()); + + // Save out the real data + saved_game.write_chunk(INT_ID('F', 'I', 'D', 'L'), idSize); + + saved_game.write_chunk(INT_ID('F', 'I', 'D', 'S'), ((*vfi).first).c_str(), idSize); + + // Save out the float value + saved_game.write_chunk(INT_ID('F', 'V', 'A', 'L'), (*vfi).second); } } @@ -326,44 +296,29 @@ Q3_VariableSaveStrings ------------------------- */ -void Q3_VariableSaveStrings( varString_m &smap ) -{ +void Q3_VariableSaveStrings(varString_m &smap) { int numStrings = smap.size(); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.write_chunk( - INT_ID('S', 'V', 'A', 'R'), - numStrings); - - varString_m::iterator vsi; - STL_ITERATE( vsi, smap ) - { - //Save out the map id - int idSize = strlen( ((*vsi).first).c_str() ); - - //Save out the real data - saved_game.write_chunk( - INT_ID('S', 'I', 'D', 'L'), - idSize); - - saved_game.write_chunk( - INT_ID('S', 'I', 'D', 'S'), - ((*vsi).first).c_str(), - idSize); - - //Save out the string value - idSize = strlen( ((*vsi).second).c_str() ); - - saved_game.write_chunk( - INT_ID('S', 'V', 'S', 'Z'), - idSize); - - saved_game.write_chunk( - INT_ID('S', 'V', 'A', 'L'), - ((*vsi).second).c_str(), - idSize); + ojk::SavedGameHelper saved_game(::gi.saved_game); + + saved_game.write_chunk(INT_ID('S', 'V', 'A', 'R'), numStrings); + + varString_m::iterator vsi; + STL_ITERATE(vsi, smap) { + // Save out the map id + int idSize = strlen(((*vsi).first).c_str()); + + // Save out the real data + saved_game.write_chunk(INT_ID('S', 'I', 'D', 'L'), idSize); + + saved_game.write_chunk(INT_ID('S', 'I', 'D', 'S'), ((*vsi).first).c_str(), idSize); + + // Save out the string value + idSize = strlen(((*vsi).second).c_str()); + + saved_game.write_chunk(INT_ID('S', 'V', 'S', 'Z'), idSize); + + saved_game.write_chunk(INT_ID('S', 'V', 'A', 'L'), ((*vsi).second).c_str(), idSize); } } @@ -373,11 +328,10 @@ Q3_VariableSave ------------------------- */ -int Q3_VariableSave( void ) -{ - Q3_VariableSaveFloats( varFloats ); - Q3_VariableSaveStrings( varStrings ); - Q3_VariableSaveStrings( varVectors); +int Q3_VariableSave(void) { + Q3_VariableSaveFloats(varFloats); + Q3_VariableSaveStrings(varStrings); + Q3_VariableSaveStrings(varVectors); return qtrue; } @@ -388,46 +342,33 @@ Q3_VariableLoadFloats ------------------------- */ -void Q3_VariableLoadFloats( varFloat_m &fmap ) -{ - int numFloats = 0; - char tempBuffer[1024]; +void Q3_VariableLoadFloats(varFloat_m &fmap) { + int numFloats = 0; + char tempBuffer[1024]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('F', 'V', 'A', 'R'), - numFloats); + saved_game.read_chunk(INT_ID('F', 'V', 'A', 'R'), numFloats); - for ( int i = 0; i < numFloats; i++ ) - { + for (int i = 0; i < numFloats; i++) { int idSize = 0; - - saved_game.read_chunk( - INT_ID('F', 'I', 'D', 'L'), - idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) - { + saved_game.read_chunk(INT_ID('F', 'I', 'D', 'L'), idSize); + + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) { ::G_Error("invalid length for FIDS string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('F', 'I', 'D', 'S'), - tempBuffer, - idSize); + saved_game.read_chunk(INT_ID('F', 'I', 'D', 'S'), tempBuffer, idSize); - tempBuffer[ idSize ] = 0; + tempBuffer[idSize] = 0; - float val = 0.0F; + float val = 0.0F; - saved_game.read_chunk( - INT_ID('F', 'V', 'A', 'L'), - val); + saved_game.read_chunk(INT_ID('F', 'V', 'A', 'L'), val); - Q3_DeclareVariable( TK_FLOAT, (const char *) &tempBuffer ); - Q3_SetFloatVariable( (const char *) &tempBuffer, val ); + Q3_DeclareVariable(TK_FLOAT, (const char *)&tempBuffer); + Q3_SetFloatVariable((const char *)&tempBuffer, val); } } @@ -437,65 +378,47 @@ Q3_VariableLoadStrings ------------------------- */ -void Q3_VariableLoadStrings( int type, varString_m &fmap ) -{ - int numFloats = 0; - char tempBuffer[1024]; - char tempBuffer2[1024]; +void Q3_VariableLoadStrings(int type, varString_m &fmap) { + int numFloats = 0; + char tempBuffer[1024]; + char tempBuffer2[1024]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('S', 'V', 'A', 'R'), - numFloats); + saved_game.read_chunk(INT_ID('S', 'V', 'A', 'R'), numFloats); - for ( int i = 0; i < numFloats; i++ ) - { + for (int i = 0; i < numFloats; i++) { int idSize = 0; - - saved_game.read_chunk( - INT_ID('S', 'I', 'D', 'L'), - idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) - { + saved_game.read_chunk(INT_ID('S', 'I', 'D', 'L'), idSize); + + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer)) { ::G_Error("invalid length for SIDS string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('S', 'I', 'D', 'S'), - tempBuffer, - idSize); + saved_game.read_chunk(INT_ID('S', 'I', 'D', 'S'), tempBuffer, idSize); - tempBuffer[ idSize ] = 0; + tempBuffer[idSize] = 0; - saved_game.read_chunk( - INT_ID('S', 'V', 'S', 'Z'), - idSize); + saved_game.read_chunk(INT_ID('S', 'V', 'S', 'Z'), idSize); - if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer2)) - { + if (idSize < 0 || static_cast(idSize) >= sizeof(tempBuffer2)) { ::G_Error("invalid length for SVAL string in save game: %d bytes\n", idSize); } - saved_game.read_chunk( - INT_ID('S', 'V', 'A', 'L'), - tempBuffer2, - idSize); + saved_game.read_chunk(INT_ID('S', 'V', 'A', 'L'), tempBuffer2, idSize); - tempBuffer2[ idSize ] = 0; + tempBuffer2[idSize] = 0; - switch ( type ) - { + switch (type) { case TK_STRING: - Q3_DeclareVariable( TK_STRING, (const char *) &tempBuffer ); - Q3_SetStringVariable( (const char *) &tempBuffer, (const char *) &tempBuffer2 ); + Q3_DeclareVariable(TK_STRING, (const char *)&tempBuffer); + Q3_SetStringVariable((const char *)&tempBuffer, (const char *)&tempBuffer2); break; case TK_VECTOR: - Q3_DeclareVariable( TK_VECTOR, (const char *) &tempBuffer ); - Q3_SetVectorVariable( (const char *) &tempBuffer, (const char *) &tempBuffer2 ); + Q3_DeclareVariable(TK_VECTOR, (const char *)&tempBuffer); + Q3_SetVectorVariable((const char *)&tempBuffer, (const char *)&tempBuffer2); break; } } @@ -507,13 +430,12 @@ Q3_VariableLoad ------------------------- */ -int Q3_VariableLoad( void ) -{ +int Q3_VariableLoad(void) { Q3_InitVariables(); - Q3_VariableLoadFloats( varFloats ); - Q3_VariableLoadStrings( TK_STRING, varStrings ); - Q3_VariableLoadStrings( TK_VECTOR, varVectors); + Q3_VariableLoadFloats(varFloats); + Q3_VariableLoadStrings(TK_STRING, varStrings); + Q3_VariableLoadStrings(TK_VECTOR, varVectors); return qfalse; } diff --git a/codeJK2/game/bg_misc.cpp b/codeJK2/game/bg_misc.cpp index 8fd1193bb1..96567c1a56 100644 --- a/codeJK2/game/bg_misc.cpp +++ b/codeJK2/game/bg_misc.cpp @@ -27,11 +27,9 @@ along with this program; if not, see . #include "bg_public.h" #include "g_items.h" - extern weaponData_t weaponData[WP_NUM_WEAPONS]; extern ammoData_t ammoData[AMMO_MAX]; - #define PICKUPSOUND "sound/weapons/w_pkup.wav" /*QUAKED weapon_***** ( 0 0 0 ) (-16 -16 -16) (16 16 16) suspended @@ -50,31 +48,31 @@ An item fires all of its targets when it is picked up. If the toucher can't car */ /*QUAKED weapon_stun_baton (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_saber (.3 .3 1) (-16 -16 -8) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_bryar_pistol (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_blaster (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_disruptor (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_bowcaster (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_repeater (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_demp2 (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_flechette (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_rocket_launcher (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_thermal (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_trip_mine (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED weapon_det_pack (.3 .3 1) (-16 -16 -2) (16 16 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED item_seeker (.3 .3 1) (-8 -8 -4) (8 8 16) suspended 30 seconds of seeker drone @@ -83,15 +81,15 @@ An item fires all of its targets when it is picked up. If the toucher can't car Personal shield */ /*QUAKED item_bacta (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_datapad (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_binoculars (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_sentry_gun (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_la_goggles (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED ammo_force (.3 .5 1) (-8 -8 -0) (8 8 16) SUSPEND STARFLEET MONSTER NOTSOLID Ammo for the force. */ @@ -118,15 +116,15 @@ Belt of thermal detonators */ /*QUAKED item_medpak_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED item_shield_sm_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED item_shield_lrg_instant (.3 .3 1) (-8 -8 -4) (8 8 16) SUSPEND STARFLEET MONSTER NOTSOLID VERTICAL INVISIBLE -*/ + */ /*QUAKED item_goodie_key (.3 .3 1) (-8 -8 0) (8 8 16) suspended -*/ + */ /*QUAKED item_security_key (.3 .3 1) (-8 -8 0) (8 8 16) suspended message - used to differentiate one key from another. */ @@ -188,12 +186,10 @@ force saberthrow pickup item "count" level of force power this holocron gives activator ( range: 0-3, default 1) */ -gitem_t bg_itemlist[ITM_NUM_ITEMS+1];//need a null on the end - -//int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) ; -const int bg_numItems = ITM_NUM_ITEMS; - +gitem_t bg_itemlist[ITM_NUM_ITEMS + 1]; // need a null on the end +// int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) ; +const int bg_numItems = ITM_NUM_ITEMS; /* =============== @@ -201,40 +197,36 @@ FindItemForWeapon =============== */ -gitem_t *FindItemForWeapon( weapon_t weapon ) { - int i; +gitem_t *FindItemForWeapon(weapon_t weapon) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( bg_itemlist[i].giType == IT_WEAPON && bg_itemlist[i].giTag == weapon ) { + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giType == IT_WEAPON && bg_itemlist[i].giTag == weapon) { return &bg_itemlist[i]; } } - Com_Error( ERR_DROP, "Couldn't find item for weapon %i", weapon); + Com_Error(ERR_DROP, "Couldn't find item for weapon %i", weapon); return NULL; } //---------------------------------------------- -gitem_t *FindItemForInventory( int inv ) -{ - int i; - gitem_t *it; +gitem_t *FindItemForInventory(int inv) { + int i; + gitem_t *it; // Now just check for any other kind of item. - for ( i = 1 ; i < bg_numItems ; i++ ) - { + for (i = 1; i < bg_numItems; i++) { it = &bg_itemlist[i]; - if ( it->giType == IT_HOLDABLE ) - { - if ( it->giTag == inv ) - { + if (it->giType == IT_HOLDABLE) { + if (it->giTag == inv) { return it; } } } - Com_Error( ERR_DROP, "Couldn't find item for inventory %i", inv ); + Com_Error(ERR_DROP, "Couldn't find item for inventory %i", inv); return NULL; } @@ -244,19 +236,16 @@ FindItemForWeapon =============== */ -gitem_t *FindItemForAmmo( ammo_t ammo ) -{ - int i; +gitem_t *FindItemForAmmo(ammo_t ammo) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) - { - if ( bg_itemlist[i].giType == IT_AMMO && bg_itemlist[i].giTag == ammo ) - { + for (i = 1; i < bg_numItems; i++) { + if (bg_itemlist[i].giType == IT_AMMO && bg_itemlist[i].giTag == ammo) { return &bg_itemlist[i]; } } - Com_Error( ERR_DROP, "Couldn't find item for ammo %i", ammo ); + Com_Error(ERR_DROP, "Couldn't find item for ammo %i", ammo); return NULL; } @@ -266,18 +255,17 @@ FindItem =============== */ -gitem_t *FindItem( const char *className ) { - int i; +gitem_t *FindItem(const char *className) { + int i; - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( !Q_stricmp( bg_itemlist[i].classname, className ) ) + for (i = 1; i < bg_numItems; i++) { + if (!Q_stricmp(bg_itemlist[i].classname, className)) return &bg_itemlist[i]; } return NULL; } - /* ================ BG_CanItemBeGrabbed @@ -286,28 +274,26 @@ Returns false if the item should not be picked up. This needs to be the same for client side prediction and server use. ================ */ -qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps ) { - gitem_t *item; +qboolean BG_CanItemBeGrabbed(const entityState_t *ent, const playerState_t *ps) { + gitem_t *item; - if ( ent->modelindex < 1 || ent->modelindex >= bg_numItems ) { - Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" ); + if (ent->modelindex < 1 || ent->modelindex >= bg_numItems) { + Com_Error(ERR_DROP, "BG_CanItemBeGrabbed: index out of range"); } item = &bg_itemlist[ent->modelindex]; - switch( item->giType ) { + switch (item->giType) { case IT_WEAPON: // See if we already have this weapon. - if ( !(ps->stats[ STAT_WEAPONS ] & ( 1 << item->giTag ))) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << item->giTag))) { // Don't have this weapon yet, so pick it up. return qtrue; } // Make sure that we aren't already full on ammo for this weapon - if ( ps->ammo[weaponData[item->giTag].ammoIndex] >= ammoData[weaponData[item->giTag].ammoIndex].max ) - { + if (ps->ammo[weaponData[item->giTag].ammoIndex] >= ammoData[weaponData[item->giTag].ammoIndex].max) { // full, so don't grab the item return qfalse; } @@ -316,65 +302,55 @@ qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps case IT_AMMO: - if (item->giTag != AMMO_FORCE) - { + if (item->giTag != AMMO_FORCE) { // since the ammo is the weapon in this case, picking up ammo should actually give you the weapon - switch( item->giTag ) - { + switch (item->giTag) { case AMMO_THERMAL: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_THERMAL ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_THERMAL))) { return qtrue; } break; case AMMO_DETPACK: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_DET_PACK ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_DET_PACK))) { return qtrue; } break; case AMMO_TRIPMINE: - if( !(ps->stats[STAT_WEAPONS] & ( 1 << WP_TRIP_MINE ) ) ) - { + if (!(ps->stats[STAT_WEAPONS] & (1 << WP_TRIP_MINE))) { return qtrue; } break; } - if ( ps->ammo[ item->giTag ] >= ammoData[item->giTag].max ) // checkme + if (ps->ammo[item->giTag] >= ammoData[item->giTag].max) // checkme { - return qfalse; // can't hold any more + return qfalse; // can't hold any more } - } - else - { - if (ps->forcePower >= ammoData[item->giTag].max*2) - { - return qfalse; // can't hold any more + } else { + if (ps->forcePower >= ammoData[item->giTag].max * 2) { + return qfalse; // can't hold any more } - } return qtrue; case IT_ARMOR: // we also clamp armor to the maxhealth for handicapping - if ( ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH] ) { + if (ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH]) { return qfalse; } return qtrue; case IT_HEALTH: // don't pick up if already at max - if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] ) { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) { return qfalse; } return qtrue; case IT_BATTERY: // don't pick up if already at max - if ( ps->batteryCharge >= MAX_BATTERIES ) - { + if (ps->batteryCharge >= MAX_BATTERIES) { return qfalse; } return qtrue; @@ -383,20 +359,17 @@ qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps // pretty lame but for now you can always pick these up return qtrue; - case IT_HOLDABLE: - if ( item->giTag >= INV_ELECTROBINOCULARS && item->giTag <= INV_SENTRY ) - { + if (item->giTag >= INV_ELECTROBINOCULARS && item->giTag <= INV_SENTRY) { // hardcoded--can only pick up five of any holdable - if ( ps->inventory[item->giTag] >= 5 ) - { + if (ps->inventory[item->giTag] >= 5) { return qfalse; } } return qtrue; default: - assert( !"BG_CanItemBeGrabbed: invalid item" ); + assert(!"BG_CanItemBeGrabbed: invalid item"); break; } @@ -411,60 +384,54 @@ EvaluateTrajectory ================ */ -void EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void EvaluateTrajectory(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorCopy( tr->trBase, result ); + VectorCopy(tr->trBase, result); break; case TR_LINEAR: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = (float)sin( deltaTime * M_PI * 2 ); - VectorMA( tr->trBase, phase, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = (float)sin(deltaTime * M_PI * 2); + VectorMA(tr->trBase, phase, tr->trDelta, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - //old totally linear - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - if ( deltaTime < 0 ) - {//going past the total duration + // old totally linear + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + if (deltaTime < 0) { // going past the total duration deltaTime = 0; } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - //new slow-down at end - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { + // new slow-down at end + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { deltaTime = 0; + } else { // FIXME: maybe scale this somehow? So that it starts out faster and stops faster? + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)atTime - tr->trTime) / (float)tr->trDuration)))); } - else - {//FIXME: maybe scale this somehow? So that it starts out faster and stops faster? - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)atTime-tr->trTime)/(float)tr->trDuration)) )); - } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); - result[2] -= 0.5F * g_gravity->value * deltaTime * deltaTime;//DEFAULT_GRAVITY + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); + result[2] -= 0.5F * g_gravity->value * deltaTime * deltaTime; // DEFAULT_GRAVITY break; default: - Com_Error( ERR_DROP, "EvaluateTrajectory: unknown trType: %i", tr->trTime ); + Com_Error(ERR_DROP, "EvaluateTrajectory: unknown trType: %i", tr->trTime); break; } } @@ -476,48 +443,46 @@ EvaluateTrajectoryDelta Returns current speed at given time ================ */ -void EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void EvaluateTrajectoryDelta(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorClear( result ); + VectorClear(result); break; case TR_LINEAR: - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = (float)cos( deltaTime * M_PI * 2 ); // derivative of sin = cos + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = (float)cos(deltaTime * M_PI * 2); // derivative of sin = cos phase *= 0.5; - VectorScale( tr->trDelta, phase, result ); + VectorScale(tr->trDelta, phase, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { - VectorClear( result ); + if (atTime > tr->trTime + tr->trDuration) { + VectorClear(result); return; } - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { - VectorClear( result ); + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { + VectorClear(result); return; } - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)atTime-tr->trTime)/(float)tr->trDuration)) )); - VectorScale( tr->trDelta, deltaTime, result ); + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)atTime - tr->trTime) / (float)tr->trDuration)))); + VectorScale(tr->trDelta, deltaTime, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001F; // milliseconds to seconds - VectorCopy( tr->trDelta, result ); - result[2] -= g_gravity->value * deltaTime; // DEFAULT_GRAVITY + deltaTime = (atTime - tr->trTime) * 0.001F; // milliseconds to seconds + VectorCopy(tr->trDelta, result); + result[2] -= g_gravity->value * deltaTime; // DEFAULT_GRAVITY break; default: - Com_Error( ERR_DROP, "EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime ); + Com_Error(ERR_DROP, "EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime); break; } } @@ -529,22 +494,19 @@ AddEventToPlayerstate Handles the sequence numbers =============== */ -void AddEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps ) { - ps->events[ps->eventSequence & (MAX_PS_EVENTS-1)] = newEvent; - ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS-1)] = eventParm; +void AddEventToPlayerstate(int newEvent, int eventParm, playerState_t *ps) { + ps->events[ps->eventSequence & (MAX_PS_EVENTS - 1)] = newEvent; + ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS - 1)] = eventParm; ps->eventSequence++; } - /* =============== CurrentPlayerstateEvent =============== */ -int CurrentPlayerstateEvent( playerState_t *ps ) { - return ps->events[ (ps->eventSequence-1) & (MAX_PS_EVENTS-1) ]; -} +int CurrentPlayerstateEvent(playerState_t *ps) { return ps->events[(ps->eventSequence - 1) & (MAX_PS_EVENTS - 1)]; } /* ======================== @@ -554,39 +516,37 @@ This is done after each set of usercmd_t on the server, and after local prediction on the client ======================== */ -void PlayerStateToEntityState( playerState_t *ps, entityState_t *s ) { - int i; +void PlayerStateToEntityState(playerState_t *ps, entityState_t *s) { + int i; - if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) - { + if (ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) { s->eType = ET_INVISIBLE; } /*else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) { s->eType = ET_INVISIBLE; } */ - else - { + else { s->eType = ET_PLAYER; } s->number = ps->clientNum; s->pos.trType = TR_INTERPOLATE; - VectorCopy( ps->origin, s->pos.trBase ); - //SnapVector( s->pos.trBase ); + VectorCopy(ps->origin, s->pos.trBase); + // SnapVector( s->pos.trBase ); s->apos.trType = TR_INTERPOLATE; - VectorCopy( ps->viewangles, s->apos.trBase ); - //SnapVector( s->apos.trBase ); + VectorCopy(ps->viewangles, s->apos.trBase); + // SnapVector( s->apos.trBase ); s->angles2[YAW] = ps->movementDir; s->legsAnim = ps->legsAnim; s->torsoAnim = ps->torsoAnim; - s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number - // so corpses can also reference the proper config + s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number + // so corpses can also reference the proper config s->eFlags = ps->eFlags; - if ( ps->stats[STAT_HEALTH] <= 0 ) { + if (ps->stats[STAT_HEALTH] <= 0) { s->eFlags |= EF_DEAD; } else { s->eFlags &= ~EF_DEAD; @@ -602,8 +562,8 @@ void PlayerStateToEntityState( playerState_t *ps, entityState_t *s ) { s->groundEntityNum = ps->groundEntityNum; s->powerups = 0; - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { - if ( ps->powerups[ i ] ) { + for (i = 0; i < MAX_POWERUPS; i++) { + if (ps->powerups[i]) { s->powerups |= 1 << i; } } @@ -644,7 +604,6 @@ void PlayerStateToEntityState( playerState_t *ps, entityState_t *s ) { #endif } - /* ============ BG_PlayerTouchesItem @@ -652,22 +611,16 @@ BG_PlayerTouchesItem Items can be picked up without actually touching their physical bounds ============ */ -qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime ) { - vec3_t origin = { 0.0f }; +qboolean BG_PlayerTouchesItem(playerState_t *ps, entityState_t *item, int atTime) { + vec3_t origin = {0.0f}; - EvaluateTrajectory( &item->pos, atTime, origin ); + EvaluateTrajectory(&item->pos, atTime, origin); // we are ignoring ducked differences here - if ( ps->origin[0] - origin[0] > 44 - || ps->origin[0] - origin[0] < -50 - || ps->origin[1] - origin[1] > 36 - || ps->origin[1] - origin[1] < -36 - || ps->origin[2] - origin[2] > 36 - || ps->origin[2] - origin[2] < -36 ) { + if (ps->origin[0] - origin[0] > 44 || ps->origin[0] - origin[0] < -50 || ps->origin[1] - origin[1] > 36 || ps->origin[1] - origin[1] < -36 || + ps->origin[2] - origin[2] > 36 || ps->origin[2] - origin[2] < -36) { return qfalse; } return qtrue; } - - diff --git a/codeJK2/game/bg_pangles.cpp b/codeJK2/game/bg_pangles.cpp index 7fe3aa55fd..dcf7ed5497 100644 --- a/codeJK2/game/bg_pangles.cpp +++ b/codeJK2/game/bg_pangles.cpp @@ -34,72 +34,61 @@ along with this program; if not, see . #include "anims.h" #include "wp_saber.h" -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern qboolean PM_InKnockDown( playerState_t *ps ); - -extern qboolean player_locked; -extern pmove_t *pm; -extern pml_t pml; - -void BG_G2SetBoneAngles( centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, qhandle_t *modelList ) -{ - if (boneIndex!=-1) - { - gi.G2API_SetBoneAnglesIndex( ¢->gent->ghoul2[0], boneIndex, angles, flags, up, left, forward, modelList, 0, 0 ); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern qboolean PM_InKnockDown(playerState_t *ps); + +extern qboolean player_locked; +extern pmove_t *pm; +extern pml_t pml; + +void BG_G2SetBoneAngles(centity_t *cent, gentity_t *gent, int boneIndex, const vec3_t angles, const int flags, const Eorientations up, const Eorientations left, + const Eorientations forward, qhandle_t *modelList) { + if (boneIndex != -1) { + gi.G2API_SetBoneAnglesIndex(¢->gent->ghoul2[0], boneIndex, angles, flags, up, left, forward, modelList, 0, 0); } } -#define MAX_YAWSPEED_X_WING 1 -#define MAX_PITCHSPEED_X_WING 1 -void PM_ScaleUcmd( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) -{ - if ( ps->vehicleModel != 0 ) - {//driving a vehicle - //clamp the turn rate - int maxPitchSpeed = MAX_PITCHSPEED_X_WING;//switch, eventually? Or read from file? - int diff = AngleNormalize180(SHORT2ANGLE((cmd->angles[PITCH]+ps->delta_angles[PITCH]))) - floor(ps->viewangles[PITCH]); - - if ( diff > maxPitchSpeed ) - { - cmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] + maxPitchSpeed ) - ps->delta_angles[PITCH]; - } - else if ( diff < -maxPitchSpeed ) - { - cmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] - maxPitchSpeed ) - ps->delta_angles[PITCH]; +#define MAX_YAWSPEED_X_WING 1 +#define MAX_PITCHSPEED_X_WING 1 +void PM_ScaleUcmd(playerState_t *ps, usercmd_t *cmd, gentity_t *gent) { + if (ps->vehicleModel != 0) { // driving a vehicle + // clamp the turn rate + int maxPitchSpeed = MAX_PITCHSPEED_X_WING; // switch, eventually? Or read from file? + int diff = AngleNormalize180(SHORT2ANGLE((cmd->angles[PITCH] + ps->delta_angles[PITCH]))) - floor(ps->viewangles[PITCH]); + + if (diff > maxPitchSpeed) { + cmd->angles[PITCH] = ANGLE2SHORT(ps->viewangles[PITCH] + maxPitchSpeed) - ps->delta_angles[PITCH]; + } else if (diff < -maxPitchSpeed) { + cmd->angles[PITCH] = ANGLE2SHORT(ps->viewangles[PITCH] - maxPitchSpeed) - ps->delta_angles[PITCH]; } - //Um, WTF? When I turn in a certain direction, I start going backwards? Or strafing? - int maxYawSpeed = MAX_YAWSPEED_X_WING;//switch, eventually? Or read from file? - diff = AngleNormalize180(SHORT2ANGLE(cmd->angles[YAW]+ps->delta_angles[YAW]) - floor(ps->viewangles[YAW])); + // Um, WTF? When I turn in a certain direction, I start going backwards? Or strafing? + int maxYawSpeed = MAX_YAWSPEED_X_WING; // switch, eventually? Or read from file? + diff = AngleNormalize180(SHORT2ANGLE(cmd->angles[YAW] + ps->delta_angles[YAW]) - floor(ps->viewangles[YAW])); - //clamp the turn rate - if ( diff > maxYawSpeed ) - { - cmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] + maxYawSpeed ) - ps->delta_angles[YAW]; - } - else if ( diff < -maxYawSpeed ) - { - cmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] - maxYawSpeed ) - ps->delta_angles[YAW]; + // clamp the turn rate + if (diff > maxYawSpeed) { + cmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW] + maxYawSpeed) - ps->delta_angles[YAW]; + } else if (diff < -maxYawSpeed) { + cmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW] - maxYawSpeed) - ps->delta_angles[YAW]; } } } -extern void SetClientViewAngle( gentity_t *ent, vec3_t angle ); -qboolean PM_AdjustAnglesToGripper( gentity_t *ent, usercmd_t *ucmd ) -{//FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? - if ( (ent->client->ps.eFlags&EF_FORCE_GRIPPED) && ent->enemy ) - { +extern void SetClientViewAngle(gentity_t *ent, vec3_t angle); +qboolean +PM_AdjustAnglesToGripper(gentity_t *ent, + usercmd_t *ucmd) { // FIXME: make this more generic and have it actually *tell* the client what cmd angles it should be locked at? + if ((ent->client->ps.eFlags & EF_FORCE_GRIPPED) && ent->enemy) { vec3_t dir, angles; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, dir ); - vectoangles( dir, angles ); - angles[PITCH] = AngleNormalize180( angles[PITCH] ); - angles[YAW] = AngleNormalize180( angles[YAW] ); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, angles ); + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, dir); + vectoangles(dir, angles); + angles[PITCH] = AngleNormalize180(angles[PITCH]); + angles[YAW] = AngleNormalize180(angles[YAW]); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, angles); } ucmd->angles[PITCH] = ANGLE2SHORT(angles[PITCH]) - ent->client->ps.delta_angles[PITCH]; ucmd->angles[YAW] = ANGLE2SHORT(angles[YAW]) - ent->client->ps.delta_angles[YAW]; @@ -108,280 +97,218 @@ qboolean PM_AdjustAnglesToGripper( gentity_t *ent, usercmd_t *ucmd ) return qfalse; } -qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ) -{ - if (( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT || ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT ) && ent->client->ps.legsAnimTimer > 500 ) - {//wall-running and not at end of anim - //stick to wall, if there is one - vec3_t rt, traceTo, mins = {ent->mins[0],ent->mins[1],0}, maxs = {ent->maxs[0],ent->maxs[1],24}, fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; - trace_t trace; - float dist, yawAdjust; - - AngleVectors( fwdAngles, NULL, rt, NULL ); - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { +qboolean PM_AdjustAngleForWallRun(gentity_t *ent, usercmd_t *ucmd, qboolean doMove) { + if ((ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT || ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT) && + ent->client->ps.legsAnimTimer > 500) { // wall-running and not at end of anim + // stick to wall, if there is one + vec3_t rt, traceTo, mins = {ent->mins[0], ent->mins[1], 0}, maxs = {ent->maxs[0], ent->maxs[1], 24}, + fwdAngles = {0, ent->client->ps.viewangles[YAW], 0}; + trace_t trace; + float dist, yawAdjust; + + AngleVectors(fwdAngles, NULL, rt, NULL); + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { dist = 128; yawAdjust = -90; - } - else - { + } else { dist = -128; yawAdjust = 90; } - VectorMA( ent->currentOrigin, dist, rt, traceTo ); - gi.trace( &trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.fraction < 1.0f && trace.plane.normal[2] == 0.0f ) - {//still a vertical wall there - //FIXME: don't pull around 90 turns - //FIXME: simulate stepping up steps here, somehow? - if ( ent->s.number || !player_locked ) - { - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { + VectorMA(ent->currentOrigin, dist, rt, traceTo); + gi.trace(&trace, ent->currentOrigin, mins, maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0); + if (trace.fraction < 1.0f && trace.plane.normal[2] == 0.0f) { // still a vertical wall there + // FIXME: don't pull around 90 turns + // FIXME: simulate stepping up steps here, somehow? + if (ent->s.number || !player_locked) { + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { ucmd->rightmove = 127; - } - else - { + } else { ucmd->rightmove = -127; } } - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - //make me face perpendicular to the wall - ent->client->ps.viewangles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + // make me face perpendicular to the wall + ent->client->ps.viewangles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( ent->s.number || !player_locked ) - { - if ( doMove ) - { - //push me forward - vec3_t fwd; - float zVel = ent->client->ps.velocity[2]; - if ( zVel > forceJumpStrength[FORCE_LEVEL_2]/2.0f ) - { - zVel = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if (ent->s.number || !player_locked) { + if (doMove) { + // push me forward + vec3_t fwd; + float zVel = ent->client->ps.velocity[2]; + if (zVel > forceJumpStrength[FORCE_LEVEL_2] / 2.0f) { + zVel = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; } - if ( ent->client->ps.legsAnimTimer > 500 ) - {//not at end of anim yet + if (ent->client->ps.legsAnimTimer > 500) { // not at end of anim yet fwdAngles[YAW] = ent->client->ps.viewangles[YAW]; - AngleVectors( fwdAngles, fwd, NULL, NULL ); - //FIXME: or MA? + AngleVectors(fwdAngles, fwd, NULL, NULL); + // FIXME: or MA? float speed = 175; - if ( ucmd->forwardmove < 0 ) - {//slower + if (ucmd->forwardmove < 0) { // slower speed = 100; + } else if (ucmd->forwardmove > 0) { + speed = 250; // running speed } - else if ( ucmd->forwardmove > 0 ) - { - speed = 250;//running speed - } - VectorScale( fwd, speed, ent->client->ps.velocity ); + VectorScale(fwd, speed, ent->client->ps.velocity); } - ent->client->ps.velocity[2] = zVel;//preserve z velocity - VectorMA( ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity ); - //pull me toward the wall, too - //VectorMA( ent->client->ps.velocity, dist, rt, ent->client->ps.velocity ); + ent->client->ps.velocity[2] = zVel; // preserve z velocity + VectorMA(ent->client->ps.velocity, -128, trace.plane.normal, ent->client->ps.velocity); + // pull me toward the wall, too + // VectorMA( ent->client->ps.velocity, dist, rt, ent->client->ps.velocity ); } } ucmd->forwardmove = 0; return qtrue; - } - else if ( doMove ) - {//stop it - if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (doMove) { // stop it + if (ent->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (ent->client->ps.legsAnim == BOTH_WALL_RUN_LEFT) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } return qfalse; } -extern int PM_AnimLength( int index, animNumber_t anim ); -qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ) -{ - vec3_t newAngles; - float animLength, spinStart, spinEnd, spinAmt, spinLength; - animNumber_t spinAnim; +extern int PM_AnimLength(int index, animNumber_t anim); +qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly) { + vec3_t newAngles; + float animLength, spinStart, spinEnd, spinAmt, spinLength; + animNumber_t spinAnim; - if ( ent->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN ) - { + if (ent->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN) { spinAnim = BOTH_JUMPFLIPSTABDOWN; - spinStart = 300.0f;//700.0f; + spinStart = 300.0f; // 700.0f; spinEnd = 1400.0f; spinAmt = 180.0f; - } - else if ( ent->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 ) - { + } else if (ent->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1) { spinAnim = BOTH_JUMPFLIPSLASHDOWN1; - spinStart = 300.0f;//700.0f;//1500.0f; - spinEnd = 1400.0f;//2300.0f; + spinStart = 300.0f; // 700.0f;//1500.0f; + spinEnd = 1400.0f; // 2300.0f; spinAmt = 180.0f; - } - else - { - if ( !anglesOnly ) - { - if ( !ent->s.number ) - { + } else { + if (!anglesOnly) { + if (!ent->s.number) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_VOF; cg.overrides.thirdPersonVertOffset = 0; } } return qfalse; } - animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, spinAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); - //face me - if ( elapsedTime >= spinStart && elapsedTime <= spinEnd ) - { + animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, spinAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); + // face me + if (elapsedTime >= spinStart && elapsedTime <= spinEnd) { spinLength = spinEnd - spinStart; - VectorCopy( ent->client->ps.viewangles, newAngles ); - newAngles[YAW] = ent->angle + (spinAmt * (elapsedTime-spinStart) / spinLength); - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, newAngles ); + VectorCopy(ent->client->ps.viewangles, newAngles); + newAngles[YAW] = ent->angle + (spinAmt * (elapsedTime - spinStart) / spinLength); + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, newAngles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - if ( anglesOnly ) - { + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + if (anglesOnly) { return qtrue; } - } - else if ( anglesOnly ) - { + } else if (anglesOnly) { return qfalse; } - //push me - if ( ent->client->ps.legsAnimTimer > 300 )//&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//haven't landed or reached end of anim yet - if ( ent->s.number || !player_locked ) - { - vec3_t pushDir, pushAngles = {0,ent->angle,0}; - AngleVectors( pushAngles, pushDir, NULL, NULL ); - if ( DotProduct( ent->client->ps.velocity, pushDir ) < 100 ) - { - VectorMA( ent->client->ps.velocity, 10, pushDir, ent->client->ps.velocity ); + // push me + if (ent->client->ps.legsAnimTimer > 300) //&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) + { // haven't landed or reached end of anim yet + if (ent->s.number || !player_locked) { + vec3_t pushDir, pushAngles = {0, ent->angle, 0}; + AngleVectors(pushAngles, pushDir, NULL, NULL); + if (DotProduct(ent->client->ps.velocity, pushDir) < 100) { + VectorMA(ent->client->ps.velocity, 10, pushDir, ent->client->ps.velocity); } } } - //do a dip in the view - if ( !ent->s.number ) - { + // do a dip in the view + if (!ent->s.number) { float viewDip = 0; - if ( elapsedTime < animLength/2.0f ) - {//starting anim - viewDip = (elapsedTime/animLength)*-120.0f; - } - else - {//ending anim - viewDip = ((animLength-elapsedTime)/animLength)*-120.0f; + if (elapsedTime < animLength / 2.0f) { // starting anim + viewDip = (elapsedTime / animLength) * -120.0f; + } else { // ending anim + viewDip = ((animLength - elapsedTime) / animLength) * -120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_VOF; - cg.overrides.thirdPersonVertOffset = cg_thirdPersonVertOffset.value+viewDip; - //pm->ps->viewheight = standheight + viewDip; + cg.overrides.thirdPersonVertOffset = cg_thirdPersonVertOffset.value + viewDip; + // pm->ps->viewheight = standheight + viewDip; } return qtrue; } -qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->s.number ) - { +qboolean PM_AdjustAnglesForBackAttack(gentity_t *ent, usercmd_t *ucmd) { + if (ent->s.number) { return qfalse; } - if ( ( ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || ent->client->ps.saberMove == LS_A_BACKSTAB ) - && PM_InAnimForSaberMove( ent->client->ps.torsoAnim, ent->client->ps.saberMove ) ) - { - if ( ent->client->ps.saberMove != LS_A_BACKSTAB || !ent->enemy || ent->s.number ) - { - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + if ((ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || ent->client->ps.saberMove == LS_A_BACKSTAB) && + PM_InAnimForSaberMove(ent->client->ps.torsoAnim, ent->client->ps.saberMove)) { + if (ent->client->ps.saberMove != LS_A_BACKSTAB || !ent->enemy || ent->s.number) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; - } - else - {//keep player facing away from their enemy + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; + } else { // keep player facing away from their enemy vec3_t enemyBehindDir; - VectorSubtract( ent->currentOrigin, ent->enemy->currentOrigin, enemyBehindDir ); - float enemyBehindYaw = AngleNormalize180( vectoyaw( enemyBehindDir ) ); - float yawError = AngleNormalize180( enemyBehindYaw - AngleNormalize180( ent->client->ps.viewangles[YAW] ) ); - if ( yawError > 1 ) - { + VectorSubtract(ent->currentOrigin, ent->enemy->currentOrigin, enemyBehindDir); + float enemyBehindYaw = AngleNormalize180(vectoyaw(enemyBehindDir)); + float yawError = AngleNormalize180(enemyBehindYaw - AngleNormalize180(ent->client->ps.viewangles[YAW])); + if (yawError > 1) { yawError = 1; - } - else if ( yawError < -1 ) - { + } else if (yawError < -1) { yawError = -1; } - ucmd->angles[YAW] = ANGLE2SHORT( AngleNormalize180( ent->client->ps.viewangles[YAW] + yawError ) ) - ent->client->ps.delta_angles[YAW]; - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(AngleNormalize180(ent->client->ps.viewangles[YAW] + yawError)) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; } return qtrue; } return qfalse; } -qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client->ps.saberLockTime > level.time ) - { - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); +qboolean PM_AdjustAnglesForSaberLock(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client->ps.saberLockTime > level.time) { + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } return qfalse; } -qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ) -{ - if ( PM_InKnockDown( &ent->client->ps ) ) - {//being knocked down or getting up, can't do anything! - if ( !angleClampOnly ) - { +qboolean PM_AdjustAnglesForKnockdown(gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly) { + if (PM_InKnockDown(&ent->client->ps)) { // being knocked down or getting up, can't do anything! + if (!angleClampOnly) { ucmd->forwardmove = 0; ucmd->rightmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } - //you can jump up out of a knockdown and you get get up into a crouch from a knockdown - //ucmd->upmove = 0; - //if ( !PM_InForceGetUp( &ent->client->ps ) || ent->client->ps.torsoAnimTimer > 800 || ent->s.weapon != WP_SABER ) - if ( ent->health > 0 ) - {//can only attack if you've started a force-getup and are using the saber + // you can jump up out of a knockdown and you get get up into a crouch from a knockdown + // ucmd->upmove = 0; + // if ( !PM_InForceGetUp( &ent->client->ps ) || ent->client->ps.torsoAnimTimer > 800 || ent->s.weapon != WP_SABER ) + if (ent->health > 0) { // can only attack if you've started a force-getup and are using the saber ucmd->buttons = 0; } } - if ( !PM_InForceGetUp( &ent->client->ps ) ) - {//can't turn unless in a force getup - if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) - {//don't clamp angles when looking through a viewEntity - SetClientViewAngle( ent, ent->client->ps.viewangles ); + if (!PM_InForceGetUp(&ent->client->ps)) { // can't turn unless in a force getup + if (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD) { // don't clamp angles when looking through a viewEntity + SetClientViewAngle(ent, ent->client->ps.viewangles); } - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; return qtrue; } } @@ -397,50 +324,42 @@ are being updated isntead of a full move //FIXME: Now that they pmove twice per think, they snap-look really fast ================ */ -void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) -{ - short temp; - float pitchMin=-75, pitchMax=75, yawMin=0, yawMax=0; //just to shut up warnings - int i; - vec3_t start, end, tmins, tmaxs, right; - trace_t trace; - qboolean lockedYaw = qfalse; - - if ( ps->pm_type == PM_INTERMISSION ) - { - return; // no view changes at all +void PM_UpdateViewAngles(playerState_t *ps, usercmd_t *cmd, gentity_t *gent) { + short temp; + float pitchMin = -75, pitchMax = 75, yawMin = 0, yawMax = 0; // just to shut up warnings + int i; + vec3_t start, end, tmins, tmaxs, right; + trace_t trace; + qboolean lockedYaw = qfalse; + + if (ps->pm_type == PM_INTERMISSION) { + return; // no view changes at all } - if ( ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0 ) - { - return; // no view changes at all + if (ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0) { + return; // no view changes at all } -// if ( player_locked ) -// {//can't turn -// return; -// } - if ( ps->eFlags & EF_NPC && gent != NULL && gent->client != NULL ) - { - if(gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) - { + // if ( player_locked ) + // {//can't turn + // return; + // } + if (ps->eFlags & EF_NPC && gent != NULL && gent->client != NULL) { + if (gent->client->renderInfo.renderFlags & RF_LOCKEDANGLE) { pitchMin = 0 - gent->client->renderInfo.headPitchRangeUp - gent->client->renderInfo.torsoPitchRangeUp; pitchMax = gent->client->renderInfo.headPitchRangeDown + gent->client->renderInfo.torsoPitchRangeDown; - + yawMin = 0 - gent->client->renderInfo.headYawRangeLeft - gent->client->renderInfo.torsoYawRangeLeft; yawMax = gent->client->renderInfo.headYawRangeRight + gent->client->renderInfo.torsoYawRangeRight; lockedYaw = qtrue; - } - else - { - pitchMin = -gent->client->renderInfo.headPitchRangeUp-gent->client->renderInfo.torsoPitchRangeUp; - pitchMax = gent->client->renderInfo.headPitchRangeDown+gent->client->renderInfo.torsoPitchRangeDown; + } else { + pitchMin = -gent->client->renderInfo.headPitchRangeUp - gent->client->renderInfo.torsoPitchRangeUp; + pitchMax = gent->client->renderInfo.headPitchRangeDown + gent->client->renderInfo.torsoPitchRangeDown; } } - if ( ps->eFlags & EF_LOCKED_TO_WEAPON ) - { + if (ps->eFlags & EF_LOCKED_TO_WEAPON) { // Emplaced guns have different pitch capabilities pitchMin = -35; pitchMax = 30; @@ -450,63 +369,48 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) const short pitchClampMax = ANGLE2SHORT(pitchMax); // circularly clamp the angles with deltas - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { temp = cmd->angles[i] + ps->delta_angles[i]; - if ( i == PITCH ) - { - //FIXME get this limit from the NPCs stats? - // don't let the player look up or down more than 90 degrees - if ( temp > pitchClampMax ) - { - ps->delta_angles[i] = (pitchClampMax - cmd->angles[i]) & 0xffff; //& clamp to short + if (i == PITCH) { + // FIXME get this limit from the NPCs stats? + // don't let the player look up or down more than 90 degrees + if (temp > pitchClampMax) { + ps->delta_angles[i] = (pitchClampMax - cmd->angles[i]) & 0xffff; //& clamp to short temp = pitchClampMax; - } - else if ( temp < pitchClampMin ) - { - ps->delta_angles[i] = (pitchClampMin - cmd->angles[i]) & 0xffff; //& clamp to short + } else if (temp < pitchClampMin) { + ps->delta_angles[i] = (pitchClampMin - cmd->angles[i]) & 0xffff; //& clamp to short temp = pitchClampMin; } } - if ( i == ROLL && ps->vehicleModel != 0 ) - { - if ( temp > pitchClampMax ) - { + if (i == ROLL && ps->vehicleModel != 0) { + if (temp > pitchClampMax) { ps->delta_angles[i] = (pitchClampMax - cmd->angles[i]) & 0xffff; temp = pitchClampMax; - } - else if ( temp < pitchClampMin ) - { + } else if (temp < pitchClampMin) { ps->delta_angles[i] = (pitchClampMin - cmd->angles[i]) & 0xffff; temp = pitchClampMin; } } - //FIXME: Are we losing precision here? Is this why it jitters? + // FIXME: Are we losing precision here? Is this why it jitters? ps->viewangles[i] = SHORT2ANGLE(temp); - if ( i == YAW && lockedYaw) - { + if (i == YAW && lockedYaw) { // don't let the player look left or right more than the clamp, if any - if ( AngleSubtract(ps->viewangles[i], gent->client->renderInfo.lockYaw) > yawMax ) - { + if (AngleSubtract(ps->viewangles[i], gent->client->renderInfo.lockYaw) > yawMax) { ps->viewangles[i] = yawMax; - } - else if ( AngleSubtract(ps->viewangles[i], gent->client->renderInfo.lockYaw) < yawMin ) - { + } else if (AngleSubtract(ps->viewangles[i], gent->client->renderInfo.lockYaw) < yawMin) { ps->viewangles[i] = yawMin; } } } - if ( (!cg.renderingThirdPerson||cg.zoomMode) && (cmd->buttons & BUTTON_USE) && cmd->rightmove != 0 && !cmd->forwardmove && cmd->upmove <= 0 ) - {//Only lean if holding use button, strafing and not moving forward or back and not jumping - if ( gent ) - { + if ((!cg.renderingThirdPerson || cg.zoomMode) && (cmd->buttons & BUTTON_USE) && cmd->rightmove != 0 && !cmd->forwardmove && + cmd->upmove <= 0) { // Only lean if holding use button, strafing and not moving forward or back and not jumping + if (gent) { int leanofs = 0; - vec3_t viewangles; + vec3_t viewangles; - if ( cmd->rightmove > 0 ) - { + if (cmd->rightmove > 0) { /* if( pm->ps->legsAnim != LEGS_LEAN_RIGHT1) { @@ -515,17 +419,12 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) pm->ps->legsAnimTimer = 500;//Force it to hold the anim for at least half a sec */ - if ( ps->leanofs <= 28 ) - { + if (ps->leanofs <= 28) { leanofs = ps->leanofs + 4; - } - else - { + } else { leanofs = 32; } - } - else - { + } else { /* if ( pm->ps->legsAnim != LEGS_LEAN_LEFT1 ) { @@ -534,71 +433,56 @@ void PM_UpdateViewAngles( playerState_t *ps, usercmd_t *cmd, gentity_t *gent ) pm->ps->legsAnimTimer = 500;//Force it to hold the anim for at least half a sec */ - if ( ps->leanofs >= -28 ) - { + if (ps->leanofs >= -28) { leanofs = ps->leanofs - 4; - } - else - { + } else { leanofs = -32; } } - VectorCopy( ps->origin, start ); + VectorCopy(ps->origin, start); start[2] += ps->viewheight; - VectorCopy( ps->viewangles, viewangles ); + VectorCopy(ps->viewangles, viewangles); viewangles[ROLL] = 0; - AngleVectors( ps->viewangles, NULL, right, NULL ); - VectorNormalize( right ); - right[2] = (leanofs<0)?0.25:-0.25; - VectorMA( start, leanofs, right, end ); - VectorSet( tmins, -8, -8, -4 ); - VectorSet( tmaxs, 8, 8, 4 ); - //if we don't trace EVERY frame, can TURN while leaning and - //end up leaning into solid architecture (sigh) - gi.trace( &trace, start, tmins, tmaxs, end, gent->s.number, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); + AngleVectors(ps->viewangles, NULL, right, NULL); + VectorNormalize(right); + right[2] = (leanofs < 0) ? 0.25 : -0.25; + VectorMA(start, leanofs, right, end); + VectorSet(tmins, -8, -8, -4); + VectorSet(tmaxs, 8, 8, 4); + // if we don't trace EVERY frame, can TURN while leaning and + // end up leaning into solid architecture (sigh) + gi.trace(&trace, start, tmins, tmaxs, end, gent->s.number, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); ps->leanofs = floor((float)leanofs * trace.fraction); ps->leanStopDebounceTime = 20; } - } - else - { - if ( gent && (cmd->forwardmove || cmd->upmove > 0) ) - { - if( ( pm->ps->legsAnim == LEGS_LEAN_RIGHT1) || - ( pm->ps->legsAnim == LEGS_LEAN_LEFT1) ) - { - pm->ps->legsAnimTimer = 0;//Force it to stop the anim + } else { + if (gent && (cmd->forwardmove || cmd->upmove > 0)) { + if ((pm->ps->legsAnim == LEGS_LEAN_RIGHT1) || (pm->ps->legsAnim == LEGS_LEAN_LEFT1)) { + pm->ps->legsAnimTimer = 0; // Force it to stop the anim } } - if ( ps->leanofs > 0 ) - { - //FIXME: play lean anim backwards? - ps->leanofs-=4; - if ( ps->leanofs < 0 ) - { + if (ps->leanofs > 0) { + // FIXME: play lean anim backwards? + ps->leanofs -= 4; + if (ps->leanofs < 0) { ps->leanofs = 0; } - } - else if ( ps->leanofs < 0 ) - { - //FIXME: play lean anim backwards? - ps->leanofs+=4; - if ( ps->leanofs > 0 ) - { + } else if (ps->leanofs < 0) { + // FIXME: play lean anim backwards? + ps->leanofs += 4; + if (ps->leanofs > 0) { ps->leanofs = 0; } } } - if ( ps->leanStopDebounceTime ) - { + if (ps->leanStopDebounceTime) { ps->leanStopDebounceTime -= 1; cmd->rightmove = 0; cmd->buttons &= ~BUTTON_USE; } } - diff --git a/codeJK2/game/bg_panimate.cpp b/codeJK2/game/bg_panimate.cpp index 91ecc83a3f..acdf5cab7a 100644 --- a/codeJK2/game/bg_panimate.cpp +++ b/codeJK2/game/bg_panimate.cpp @@ -35,449 +35,408 @@ along with this program; if not, see . #include "g_local.h" #include "wp_saber.h" -extern pmove_t *pm; -extern pml_t pml; -extern cvar_t *g_ICARUSDebug; -extern cvar_t *g_timescale; -extern cvar_t *g_synchSplitAnims; -extern cvar_t *g_saberAnimSpeed; -extern cvar_t *g_saberAutoAim; - -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -extern qboolean ValidAnimFileIndex ( int index ); -extern qboolean PM_ControlledByPlayer( void ); -extern qboolean PM_DroidMelee( int npc_class ); -extern qboolean PM_PainAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern qboolean PM_DodgeAnim( int anim ); -extern qboolean PM_InSlopeAnim( int anim ); -extern qboolean PM_ForceAnim( int anim ); -extern qboolean PM_InKnockDownOnGround( playerState_t *ps ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_RunningAnim( int anim ); -extern qboolean PM_WalkingAnim( int anim ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); - -int PM_AnimLength( int index, animNumber_t anim ); +extern pmove_t *pm; +extern pml_t pml; +extern cvar_t *g_ICARUSDebug; +extern cvar_t *g_timescale; +extern cvar_t *g_synchSplitAnims; +extern cvar_t *g_saberAnimSpeed; +extern cvar_t *g_saberAutoAim; + +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +extern qboolean ValidAnimFileIndex(int index); +extern qboolean PM_ControlledByPlayer(void); +extern qboolean PM_DroidMelee(int npc_class); +extern qboolean PM_PainAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern qboolean PM_DodgeAnim(int anim); +extern qboolean PM_InSlopeAnim(int anim); +extern qboolean PM_ForceAnim(int anim); +extern qboolean PM_InKnockDownOnGround(playerState_t *ps); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_RunningAnim(int anim); +extern qboolean PM_WalkingAnim(int anim); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); + +int PM_AnimLength(int index, animNumber_t anim); // Okay, here lies the much-dreaded Pat-created FSM movement chart... Heretic II strikes again! // Why am I inflicting this on you? Well, it's better than hardcoded states. // Ideally this will be replaced with an external file or more sophisticated move-picker // once the game gets out of prototype stage. // Silly, but I'm replacing these macros so they are shorter! -#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) +#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) #define AFLAG_ACTIVE (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_WAIT (SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_FINISH (SETANIM_FLAG_HOLD) -saberMoveData_t saberMoveData[LS_MOVE_MAX] = {// NB:randomized +saberMoveData_t saberMoveData[LS_MOVE_MAX] = { + // NB:randomized // name anim startQ endQ setanimflag blend, blocking chain_idle chain_attack trailLen - {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0 }, // LS_NONE = 0, + {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0}, // LS_NONE = 0, // General movements with saber - {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0 }, // LS_READY, - {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_DRAW, - {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_PUTAWAY, + {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0}, // LS_READY, + {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_DRAW, + {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_PUTAWAY, // Attacks - //UL2LR - {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200 }, // LS_A_TL2BR - //SLASH LEFT - {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200 }, // LS_A_L2R - //LL2UR - {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200 }, // LS_A_BL2TR - //LR2UL - {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200 }, // LS_A_BR2TL - //SLASH RIGHT - {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200 },// LS_A_R2L - //UR2LL - {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200 }, // LS_A_TR2BL - //SLASH DOWN - {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200 }, // LS_A_T2B - //special attacks - {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACKSTAB - {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK - {"CR Back Att", BOTH_CROUCHATTACKBACK1,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK_CR - {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_LUNGE - {"Jump Att", BOTH_FORCELEAP2_T__B_,Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_JUMP_T__B_ - {"Flip Stab", BOTH_JUMPFLIPSTABDOWN,Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200 }, // LS_A_FLIP_STAB - {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1,Q_L,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200 }, // LS_A_FLIP_SLASH - - //starts - {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200 }, // LS_S_TL2BR - {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200 }, // LS_S_L2R - {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200 }, // LS_S_BL2TR - {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200 }, // LS_S_BR2TL - {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200 }, // LS_S_R2L - {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200 }, // LS_S_TR2BL - {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200 }, // LS_S_T2B - - //returns - {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TL2BR - {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_L2R - {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BL2TR - {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BR2TL - {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_R2L - {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TR2BL - {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_T2B - - //Transitions - {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc bottom right to right - {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) - {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) - {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast weak spin bottom right to top left - {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin bottom right to left - {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin bottom right to bottom left - {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) - {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc right to top right - {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast ar right to top (use: BOTH_T1_T___R) - {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc right to top left - {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin right to left - {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin right to bottom left - {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top right to bottom right - {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top right to right (use: BOTH_T1__R_TR) - {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top right to top (use: BOTH_T1_T__TR) - {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top right to top left - {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top right to left - {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin top right to bottom left - {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top to bottom right - {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top to right - {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top to top right - {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top to top left - {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top to left - {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top to bottom left - {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin top left to bottom right - {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top left to right (use: BOTH_T1__R_TL) - {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) - {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top left to top (use: BOTH_T1_T__TL) - {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top left to left (use: BOTH_T1__L_TL) - {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top left to bottom left - {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin left to bottom right - {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin left to right - {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc left to top right (use: BOTH_T1_TR__L) - {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc left to top (use: BOTH_T1_T___L) - {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc left to top left - {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) - {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin bottom left to bottom right - {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin bottom left to right - {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast weak spin bottom left to top right - {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) - {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) - {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc bottom left to left - - //Bounces - {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - - //Deflected attacks (like bounces, but slide off enemy saber, not straight back) - {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - - //Reflected attacks - {"Reflected BR",BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BR - {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__R - {"Reflected TR",BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TR - {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_T_ - {"Reflected TL",BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TL - {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__L - {"Reflected BL",BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BL - {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_B_ + // UL2LR + {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200}, // LS_A_TL2BR + // SLASH LEFT + {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200}, // LS_A_L2R + // LL2UR + {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200}, // LS_A_BL2TR + // LR2UL + {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200}, // LS_A_BR2TL + // SLASH RIGHT + {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200}, // LS_A_R2L + // UR2LL + {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200}, // LS_A_TR2BL + // SLASH DOWN + {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200}, // LS_A_T2B + // special attacks + {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACKSTAB + {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK + {"CR Back Att", BOTH_CROUCHATTACKBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK_CR + {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_LUNGE + {"Jump Att", BOTH_FORCELEAP2_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_JUMP_T__B_ + {"Flip Stab", BOTH_JUMPFLIPSTABDOWN, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200}, // LS_A_FLIP_STAB + {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200}, // LS_A_FLIP_SLASH + + // starts + {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200}, // LS_S_TL2BR + {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200}, // LS_S_L2R + {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200}, // LS_S_BL2TR + {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200}, // LS_S_BR2TL + {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200}, // LS_S_R2L + {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200}, // LS_S_TR2BL + {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200}, // LS_S_T2B + + // returns + {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TL2BR + {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_L2R + {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BL2TR + {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BR2TL + {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_R2L + {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TR2BL + {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_T2B + + // Transitions + {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc bottom right to right + {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) + {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) + {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast weak spin bottom right to top left + {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin bottom right to left + {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin bottom right to bottom left + {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, + 150}, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) + {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc right to top right + {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast ar right to top (use: BOTH_T1_T___R) + {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc right to top left + {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin right to left + {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin right to bottom left + {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top right to bottom right + {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top right to right (use: BOTH_T1__R_TR) + {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top right to top (use: BOTH_T1_T__TR) + {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top right to top left + {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top right to left + {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin top right to bottom left + {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top to bottom right + {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top to right + {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc top to top right + {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top to top left + {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top to left + {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top to bottom left + {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin top left to bottom right + {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top left to right (use: BOTH_T1__R_TL) + {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) + {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top left to top (use: BOTH_T1_T__TL) + {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top left to left (use: BOTH_T1__L_TL) + {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top left to bottom left + {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin left to bottom right + {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin left to right + {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc left to top right (use: BOTH_T1_TR__L) + {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc left to top (use: BOTH_T1_T___L) + {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc left to top left + {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, + 150}, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) + {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin bottom left to bottom right + {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin bottom left to right + {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast weak spin bottom left to top right + {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) + {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, + 150}, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) + {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc bottom left to left + + // Bounces + {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + + // Deflected attacks (like bounces, but slide off enemy saber, not straight back) + {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + + // Reflected attacks + {"Reflected BR", BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BR + {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__R + {"Reflected TR", BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TR + {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_T_ + {"Reflected TL", BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TL + {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__L + {"Reflected BL", BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BL + {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_B_ // Broken parries - {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UP, - {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UR, - {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UL, - {"BParry LR", BOTH_H1_S1_BL, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LR, - {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL - {"BParry LL", BOTH_H1_S1_BR, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL + {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UP, + {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UR, + {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UL, + {"BParry LR", BOTH_H1_S1_BL, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LR, + {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LL + {"BParry LL", BOTH_H1_S1_BR, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LL // Knockaways - {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150 }, // LS_PARRY_UP, - {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150 }, // LS_PARRY_UR, - {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150 }, // LS_PARRY_UL, - {"Knock LR", BOTH_K1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150 }, // LS_PARRY_LR, - {"Knock LL", BOTH_K1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150 }, // LS_PARRY_LL + {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150}, // LS_PARRY_UP, + {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150}, // LS_PARRY_UR, + {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150}, // LS_PARRY_UL, + {"Knock LR", BOTH_K1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150}, // LS_PARRY_LR, + {"Knock LL", BOTH_K1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150}, // LS_PARRY_LL // Parry - {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150 }, // LS_PARRY_UP, - {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150 }, // LS_PARRY_UR, - {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150 }, // LS_PARRY_UL, - {"Parry LR", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150 }, // LS_PARRY_LR, - {"Parry LL", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150 }, // LS_PARRY_LL + {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150}, // LS_PARRY_UP, + {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150}, // LS_PARRY_UR, + {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150}, // LS_PARRY_UL, + {"Parry LR", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150}, // LS_PARRY_LR, + {"Parry LL", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150}, // LS_PARRY_LL // Reflecting a missile - {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300 }, // LS_PARRY_UP, - {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300 }, // LS_PARRY_UR, - {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300 }, // LS_PARRY_UL, - {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300 }, // LS_PARRY_LR - {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300 }, // LS_PARRY_LL, + {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300}, // LS_PARRY_UP, + {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300}, // LS_PARRY_UR, + {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300}, // LS_PARRY_UL, + {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300}, // LS_PARRY_LR + {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300}, // LS_PARRY_LL, }; - -saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = -{ +saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = { { - LS_NONE, //Can't transition to same pos! - LS_T1_BR__R,//40 - LS_T1_BR_TR, - LS_T1_BR_T_, - LS_T1_BR_TL, - LS_T1_BR__L, - LS_T1_BR_BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE, // Can't transition to same pos! + LS_T1_BR__R, // 40 + LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1__R_BR,//46 - LS_NONE, //Can't transition to same pos! - LS_T1__R_TR, - LS_T1__R_T_, - LS_T1__R_TL, - LS_T1__R__L, - LS_T1__R_BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1__R_BR, // 46 + LS_NONE, // Can't transition to same pos! + LS_T1__R_TR, LS_T1__R_T_, LS_T1__R_TL, LS_T1__R__L, LS_T1__R_BL, + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_TR_BR,//52 + LS_T1_TR_BR, // 52 LS_T1_TR__R, - LS_NONE, //Can't transition to same pos! - LS_T1_TR_T_, - LS_T1_TR_TL, - LS_T1_TR__L, - LS_T1_TR_BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE, // Can't transition to same pos! + LS_T1_TR_T_, LS_T1_TR_TL, LS_T1_TR__L, LS_T1_TR_BL, + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_T__BR,//58 - LS_T1_T___R, - LS_T1_T__TR, - LS_NONE, //Can't transition to same pos! - LS_T1_T__TL, - LS_T1_T___L, - LS_T1_T__BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_T__BR, // 58 + LS_T1_T___R, LS_T1_T__TR, + LS_NONE, // Can't transition to same pos! + LS_T1_T__TL, LS_T1_T___L, LS_T1_T__BL, + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_TL_BR,//64 - LS_T1_TL__R, - LS_T1_TL_TR, - LS_T1_TL_T_, - LS_NONE, //Can't transition to same pos! - LS_T1_TL__L, - LS_T1_TL_BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_TL_BR, // 64 + LS_T1_TL__R, LS_T1_TL_TR, LS_T1_TL_T_, + LS_NONE, // Can't transition to same pos! + LS_T1_TL__L, LS_T1_TL_BL, + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1__L_BR,//70 - LS_T1__L__R, - LS_T1__L_TR, - LS_T1__L_T_, - LS_T1__L_TL, - LS_NONE, //Can't transition to same pos! + LS_T1__L_BR, // 70 + LS_T1__L__R, LS_T1__L_TR, LS_T1__L_T_, LS_T1__L_TL, + LS_NONE, // Can't transition to same pos! LS_T1__L_BL, - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_BL_BR,//76 - LS_T1_BL__R, - LS_T1_BL_TR, - LS_T1_BL_T_, - LS_T1_BL_TL, - LS_T1_BL__L, - LS_NONE, //Can't transition to same pos! - LS_NONE, //No transitions to bottom, and no anims start there, so shouldn't need any + LS_T1_BL_BR, // 76 + LS_T1_BL__R, LS_T1_BL_TR, LS_T1_BL_T_, LS_T1_BL_TL, LS_T1_BL__L, + LS_NONE, // Can't transition to same pos! + LS_NONE, // No transitions to bottom, and no anims start there, so shouldn't need any }, { - LS_T1_BL_BR,//NOTE: there are no transitions from bottom, so re-use the bottom right transitions - LS_T1_BR__R, - LS_T1_BR_TR, - LS_T1_BR_T_, - LS_T1_BR_TL, - LS_T1_BR__L, - LS_T1_BR_BL, - LS_NONE //No transitions to bottom, and no anims start there, so shouldn't need any - } -}; + LS_T1_BL_BR, // NOTE: there are no transitions from bottom, so re-use the bottom right transitions + LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, + LS_NONE // No transitions to bottom, and no anims start there, so shouldn't need any + }}; -void PM_VelocityForSaberMove( playerState_t *ps, vec3_t throwDir ) -{ - vec3_t vForward = { 0.0f }, vRight = { 0.0f }, vUp = { 0.0f }, startQ = { 0.0f }, endQ = { 0.0f }; +void PM_VelocityForSaberMove(playerState_t *ps, vec3_t throwDir) { + vec3_t vForward = {0.0f}, vRight = {0.0f}, vUp = {0.0f}, startQ = {0.0f}, endQ = {0.0f}; - AngleVectors( ps->viewangles, vForward, vRight, vUp ); + AngleVectors(ps->viewangles, vForward, vRight, vUp); - switch ( saberMoveData[ps->saberMove].startQuad ) - { + switch (saberMoveData[ps->saberMove].startQuad) { case Q_BR: - VectorScale( vRight, 1, startQ ); - VectorMA( startQ, -1, vUp, startQ ); + VectorScale(vRight, 1, startQ); + VectorMA(startQ, -1, vUp, startQ); break; case Q_R: - VectorScale( vRight, 2, startQ ); + VectorScale(vRight, 2, startQ); break; case Q_TR: - VectorScale( vRight, 1, startQ ); - VectorMA( startQ, 1, vUp, startQ ); + VectorScale(vRight, 1, startQ); + VectorMA(startQ, 1, vUp, startQ); break; case Q_T: - VectorScale( vUp, 2, startQ ); + VectorScale(vUp, 2, startQ); break; case Q_TL: - VectorScale( vRight, -1, startQ ); - VectorMA( startQ, 1, vUp, startQ ); + VectorScale(vRight, -1, startQ); + VectorMA(startQ, 1, vUp, startQ); break; case Q_L: - VectorScale( vRight, -2, startQ ); + VectorScale(vRight, -2, startQ); break; case Q_BL: - VectorScale( vRight, -1, startQ ); - VectorMA( startQ, -1, vUp, startQ ); + VectorScale(vRight, -1, startQ); + VectorMA(startQ, -1, vUp, startQ); break; case Q_B: - VectorScale( vUp, -2, startQ ); + VectorScale(vUp, -2, startQ); break; } - switch ( saberMoveData[ps->saberMove].endQuad ) - { + switch (saberMoveData[ps->saberMove].endQuad) { case Q_BR: - VectorScale( vRight, 1, endQ ); - VectorMA( endQ, -1, vUp, endQ ); + VectorScale(vRight, 1, endQ); + VectorMA(endQ, -1, vUp, endQ); break; case Q_R: - VectorScale( vRight, 2, endQ ); + VectorScale(vRight, 2, endQ); break; case Q_TR: - VectorScale( vRight, 1, endQ ); - VectorMA( endQ, 1, vUp, endQ ); + VectorScale(vRight, 1, endQ); + VectorMA(endQ, 1, vUp, endQ); break; case Q_T: - VectorScale( vUp, 2, endQ ); + VectorScale(vUp, 2, endQ); break; case Q_TL: - VectorScale( vRight, -1, endQ ); - VectorMA( endQ, 1, vUp, endQ ); + VectorScale(vRight, -1, endQ); + VectorMA(endQ, 1, vUp, endQ); break; case Q_L: - VectorScale( vRight, -2, endQ ); + VectorScale(vRight, -2, endQ); break; case Q_BL: - VectorScale( vRight, -1, endQ ); - VectorMA( endQ, -1, vUp, endQ ); + VectorScale(vRight, -1, endQ); + VectorMA(endQ, -1, vUp, endQ); break; case Q_B: - VectorScale( vUp, -2, endQ ); + VectorScale(vUp, -2, endQ); break; } - VectorMA( endQ, 2, vForward, endQ ); - VectorScale( throwDir, 125, throwDir );//FIXME: pass in the throw strength? - VectorSubtract( endQ, startQ, throwDir ); + VectorMA(endQ, 2, vForward, endQ); + VectorScale(throwDir, 125, throwDir); // FIXME: pass in the throw strength? + VectorSubtract(endQ, startQ, throwDir); } -qboolean PM_VelocityForBlockedMove( playerState_t *ps, vec3_t throwDir ) -{ - vec3_t vForward, vRight, vUp; - AngleVectors( ps->viewangles, vForward, vRight, vUp ); - switch ( ps->saberBlocked ) - { +qboolean PM_VelocityForBlockedMove(playerState_t *ps, vec3_t throwDir) { + vec3_t vForward, vRight, vUp; + AngleVectors(ps->viewangles, vForward, vRight, vUp); + switch (ps->saberBlocked) { case BLOCKED_UPPER_RIGHT: - VectorScale( vRight, 1, throwDir ); - VectorMA( throwDir, 1, vUp, throwDir ); + VectorScale(vRight, 1, throwDir); + VectorMA(throwDir, 1, vUp, throwDir); break; case BLOCKED_UPPER_LEFT: - VectorScale( vRight, -1, throwDir ); - VectorMA( throwDir, 1, vUp, throwDir ); + VectorScale(vRight, -1, throwDir); + VectorMA(throwDir, 1, vUp, throwDir); break; case BLOCKED_LOWER_RIGHT: - VectorScale( vRight, 1, throwDir ); - VectorMA( throwDir, -1, vUp, throwDir ); + VectorScale(vRight, 1, throwDir); + VectorMA(throwDir, -1, vUp, throwDir); break; case BLOCKED_LOWER_LEFT: - VectorScale( vRight, -1, throwDir ); - VectorMA( throwDir, -1, vUp, throwDir ); + VectorScale(vRight, -1, throwDir); + VectorMA(throwDir, -1, vUp, throwDir); break; case BLOCKED_TOP: - VectorScale( vUp, 2, throwDir ); + VectorScale(vUp, 2, throwDir); break; default: return qfalse; break; } - VectorMA( throwDir, 2, vForward, throwDir ); - VectorScale( throwDir, 250, throwDir );//FIXME: pass in the throw strength? + VectorMA(throwDir, 2, vForward, throwDir); + VectorScale(throwDir, 250, throwDir); // FIXME: pass in the throw strength? return qtrue; } -int PM_AnimLevelForSaberAnim( int anim ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____ ) - { +int PM_AnimLevelForSaberAnim(int anim) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____) { return FORCE_LEVEL_1; } - if ( anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____ ) - { + if (anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____) { return FORCE_LEVEL_2; } - if ( anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____ ) - { + if (anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____) { return FORCE_LEVEL_3; } - if ( anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____ ) - {//desann + if (anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____) { // desann return FORCE_LEVEL_4; } - if ( anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____ ) - {//tavion + if (anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____) { // tavion return FORCE_LEVEL_5; } return FORCE_LEVEL_0; } -int PM_PowerLevelForSaberAnim( playerState_t *ps ) -{ +int PM_PowerLevelForSaberAnim(playerState_t *ps) { int anim = ps->torsoAnim; - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____ ) - { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____) { return FORCE_LEVEL_1; } - if ( anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____ ) - { + if (anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____) { return FORCE_LEVEL_2; } - if ( anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____ ) - { + if (anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____) { return FORCE_LEVEL_3; } - if ( anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____ ) - {//desann + if (anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____) { // desann return FORCE_LEVEL_4; } - if ( anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____ ) - {//tavion + if (anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____) { // tavion return FORCE_LEVEL_2; } - if ( anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR ) - {//parries, knockaways and broken parries - return FORCE_LEVEL_1;//FIXME: saberAnimLevel? + if (anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR) { // parries, knockaways and broken parries + return FORCE_LEVEL_1; // FIXME: saberAnimLevel? } - switch ( anim ) - { + switch (anim) { case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -485,24 +444,22 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps ) case BOTH_BUTTERFLY_RIGHT: case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: - case BOTH_K1_S1_T_: //# knockaway saber top - case BOTH_K1_S1_TR: //# knockaway saber top right - case BOTH_K1_S1_TL: //# knockaway saber top left - case BOTH_K1_S1_BL: //# knockaway saber bottom left - case BOTH_K1_S1_B_: //# knockaway saber bottom - case BOTH_K1_S1_BR: //# knockaway saber bottom right + case BOTH_K1_S1_T_: //# knockaway saber top + case BOTH_K1_S1_TR: //# knockaway saber top right + case BOTH_K1_S1_TL: //# knockaway saber top left + case BOTH_K1_S1_BL: //# knockaway saber bottom left + case BOTH_K1_S1_B_: //# knockaway saber bottom + case BOTH_K1_S1_BR: //# knockaway saber bottom right case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: return FORCE_LEVEL_3; break; - case BOTH_JUMPFLIPSLASHDOWN1://FIXME: only middle of anim should have any power - case BOTH_JUMPFLIPSTABDOWN://FIXME: only middle of anim should have any power - if ( ps->torsoAnimTimer <= 300 ) - {//end of anim + case BOTH_JUMPFLIPSLASHDOWN1: // FIXME: only middle of anim should have any power + case BOTH_JUMPFLIPSTABDOWN: // FIXME: only middle of anim should have any power + if (ps->torsoAnimTimer <= 300) { // end of anim return FORCE_LEVEL_0; - } - else if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)anim ) - ps->torsoAnimTimer < 300 ) - {//beginning of anim + } else if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)anim) - ps->torsoAnimTimer < + 300) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -511,10 +468,8 @@ int PM_PowerLevelForSaberAnim( playerState_t *ps ) return FORCE_LEVEL_0; } -qboolean PM_InAnimForSaberMove( int anim, int saberMove ) -{ - switch ( anim ) - {//special case anims +qboolean PM_InAnimForSaberMove(int anim, int saberMove) { + switch (anim) { // special case anims case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -524,57 +479,48 @@ qboolean PM_InAnimForSaberMove( int anim, int saberMove ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# return qtrue; } - int animLevel = PM_AnimLevelForSaberAnim( anim ); - if ( animLevel <= 0 ) - {//NOTE: this will always return false for the ready poses and putaway/draw... + int animLevel = PM_AnimLevelForSaberAnim(anim); + if (animLevel <= 0) { // NOTE: this will always return false for the ready poses and putaway/draw... return qfalse; } - //drop the anim to the first level and start the checks there - anim -= (animLevel-FORCE_LEVEL_1)*SABER_ANIM_GROUP_SIZE; - //check level 1 - if ( anim == saberMoveData[saberMove].animToUse ) - { + // drop the anim to the first level and start the checks there + anim -= (animLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + // check level 1 + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 2 + // check level 2 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 3 + // check level 3 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 4 + // check level 4 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - //check level 5 + // check level 5 anim += SABER_ANIM_GROUP_SIZE; - if ( anim == saberMoveData[saberMove].animToUse ) - { + if (anim == saberMoveData[saberMove].animToUse) { return qtrue; } - if ( anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR ) - {//parries, knockaways and broken parries + if (anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR) { // parries, knockaways and broken parries return (qboolean)(anim == saberMoveData[saberMove].animToUse); } return qfalse; } -qboolean PM_SaberInIdle( int move ) -{ - switch ( move ) - { +qboolean PM_SaberInIdle(int move) { + switch (move) { case LS_NONE: case LS_READY: case LS_DRAW: @@ -584,10 +530,8 @@ qboolean PM_SaberInIdle( int move ) } return qfalse; } -qboolean PM_SaberInSpecialAttack( int anim ) -{ - switch ( anim ) - { +qboolean PM_SaberInSpecialAttack(int anim) { + switch (anim) { case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -597,20 +541,17 @@ qboolean PM_SaberInSpecialAttack( int anim ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# return qtrue; } return qfalse; } -qboolean PM_SaberInAttack( int move ) -{ - if ( move >= LS_A_TL2BR && move <= LS_A_T2B ) - { +qboolean PM_SaberInAttack(int move) { + if (move >= LS_A_TL2BR && move <= LS_A_T2B) { return qtrue; } - switch ( move ) - { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -623,107 +564,79 @@ qboolean PM_SaberInAttack( int move ) } return qfalse; } -qboolean PM_SaberInTransition( int move ) -{ - if ( move >= LS_T1_BR__R && move <= LS_T1_BL__L ) - { +qboolean PM_SaberInTransition(int move) { + if (move >= LS_T1_BR__R && move <= LS_T1_BL__L) { return qtrue; } return qfalse; } -qboolean PM_SaberInStart( int move ) -{ - if ( move >= LS_S_TL2BR && move <= LS_S_T2B ) - { +qboolean PM_SaberInStart(int move) { + if (move >= LS_S_TL2BR && move <= LS_S_T2B) { return qtrue; } return qfalse; } -qboolean PM_SaberInReturn( int move ) -{ - if ( move >= LS_R_TL2BR && move <= LS_R_TL2BR ) - { +qboolean PM_SaberInReturn(int move) { + if (move >= LS_R_TL2BR && move <= LS_R_TL2BR) { return qtrue; } return qfalse; } -qboolean PM_SaberInTransitionAny( int move ) -{ - if ( PM_SaberInStart( move ) ) - { +qboolean PM_SaberInTransitionAny(int move) { + if (PM_SaberInStart(move)) { return qtrue; - } - else if ( PM_SaberInTransition( move ) ) - { + } else if (PM_SaberInTransition(move)) { return qtrue; - } - else if ( PM_SaberInReturn( move ) ) - { + } else if (PM_SaberInReturn(move)) { return qtrue; } return qfalse; } -qboolean PM_SaberInBounce( int move ) -{ - if ( move >= LS_B1_BR && move <= LS_B1_BL ) - { +qboolean PM_SaberInBounce(int move) { + if (move >= LS_B1_BR && move <= LS_B1_BL) { return qtrue; } - if ( move >= LS_D1_BR && move <= LS_D1_BL ) - { + if (move >= LS_D1_BR && move <= LS_D1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInBrokenParry( int move ) -{ - if ( move >= LS_V1_BR && move <= LS_V1_B_ ) - { +qboolean PM_SaberInBrokenParry(int move) { + if (move >= LS_V1_BR && move <= LS_V1_B_) { return qtrue; } - if ( move >= LS_H1_T_ && move <= LS_H1_BL ) - { + if (move >= LS_H1_T_ && move <= LS_H1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInDeflect( int move ) -{ - if ( move >= LS_D1_BR && move <= LS_D1_B_ ) - { +qboolean PM_SaberInDeflect(int move) { + if (move >= LS_D1_BR && move <= LS_D1_B_) { return qtrue; } return qfalse; } -qboolean PM_SaberInParry( int move ) -{ - if ( move >= LS_PARRY_UP && move <= LS_PARRY_LL ) - { +qboolean PM_SaberInParry(int move) { + if (move >= LS_PARRY_UP && move <= LS_PARRY_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInKnockaway( int move ) -{ - if ( move >= LS_K1_T_ && move <= LS_K1_BL ) - { +qboolean PM_SaberInKnockaway(int move) { + if (move >= LS_K1_T_ && move <= LS_K1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInReflect( int move ) -{ - if ( move >= LS_REFLECT_UP && move <= LS_REFLECT_LL ) - { +qboolean PM_SaberInReflect(int move) { + if (move >= LS_REFLECT_UP && move <= LS_REFLECT_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInSpecial( int move ) -{ - switch( move ) - { +qboolean PM_SaberInSpecial(int move) { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -736,13 +649,11 @@ qboolean PM_SaberInSpecial( int move ) return qfalse; } -int PM_BrokenParryForAttack( int move ) -{ - //Our attack was knocked away by a knockaway parry - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( saberMoveData[move].startQuad ) - { +int PM_BrokenParryForAttack(int move) { + // Our attack was knocked away by a knockaway parry + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (saberMoveData[move].startQuad) { case Q_B: return LS_V1_B_; break; @@ -771,20 +682,15 @@ int PM_BrokenParryForAttack( int move ) return LS_NONE; } -int PM_BrokenParryForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { +int PM_BrokenParryForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { case LS_PARRY_UP: - //Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back - if ( Q_irand( 0, 1 ) ) - { + // Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back + if (Q_irand(0, 1)) { return LS_H1_B_; - } - else - { + } else { return LS_H1_T_; } break; @@ -801,42 +707,38 @@ int PM_BrokenParryForParry( int move ) return LS_H1_BL; break; case LS_READY: - return LS_H1_B_;//??? + return LS_H1_B_; //??? break; } return LS_NONE; } -int PM_KnockawayForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { - case BLOCKED_TOP://LS_PARRY_UP: - return LS_K1_T_;//push up +int PM_KnockawayForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { + case BLOCKED_TOP: // LS_PARRY_UP: + return LS_K1_T_; // push up break; - case BLOCKED_UPPER_RIGHT://LS_PARRY_UR: - default://case LS_READY: - return LS_K1_TR;//push up, slightly to right + case BLOCKED_UPPER_RIGHT: // LS_PARRY_UR: + default: // case LS_READY: + return LS_K1_TR; // push up, slightly to right break; - case BLOCKED_UPPER_LEFT://LS_PARRY_UL: - return LS_K1_TL;//push up and to left + case BLOCKED_UPPER_LEFT: // LS_PARRY_UL: + return LS_K1_TL; // push up and to left break; - case BLOCKED_LOWER_RIGHT://LS_PARRY_LR: - return LS_K1_BR;//push down and to left + case BLOCKED_LOWER_RIGHT: // LS_PARRY_LR: + return LS_K1_BR; // push down and to left break; - case BLOCKED_LOWER_LEFT://LS_PARRY_LL: - return LS_K1_BL;//push down and to right + case BLOCKED_LOWER_LEFT: // LS_PARRY_LL: + return LS_K1_BL; // push down and to right break; } - //return LS_NONE; + // return LS_NONE; } -int PM_SaberBounceForAttack( int move ) -{ - switch ( saberMoveData[move].startQuad ) - { +int PM_SaberBounceForAttack(int move) { + switch (saberMoveData[move].startQuad) { case Q_B: case Q_BR: return LS_B1_BR; @@ -863,10 +765,8 @@ int PM_SaberBounceForAttack( int move ) return LS_NONE; } -saberMoveName_t PM_AttackMoveForQuad( int quad ) -{ - switch ( quad ) - { +saberMoveName_t PM_AttackMoveForQuad(int quad) { + switch (quad) { case Q_B: case Q_BR: return LS_A_BR2TL; @@ -893,101 +793,95 @@ saberMoveName_t PM_AttackMoveForQuad( int quad ) return LS_NONE; } -int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = -{ - { - 0,//Q_BR,Q_BR, - 45,//Q_BR,Q_R, - 90,//Q_BR,Q_TR, - 135,//Q_BR,Q_T, - 180,//Q_BR,Q_TL, - 215,//Q_BR,Q_L, - 270,//Q_BR,Q_BL, - 45,//Q_BR,Q_B, - }, - { - 45,//Q_R,Q_BR, - 0,//Q_R,Q_R, - 45,//Q_R,Q_TR, - 90,//Q_R,Q_T, - 135,//Q_R,Q_TL, - 180,//Q_R,Q_L, - 215,//Q_R,Q_BL, - 90,//Q_R,Q_B, - }, - { - 90,//Q_TR,Q_BR, - 45,//Q_TR,Q_R, - 0,//Q_TR,Q_TR, - 45,//Q_TR,Q_T, - 90,//Q_TR,Q_TL, - 135,//Q_TR,Q_L, - 180,//Q_TR,Q_BL, - 135,//Q_TR,Q_B, - }, - { - 135,//Q_T,Q_BR, - 90,//Q_T,Q_R, - 45,//Q_T,Q_TR, - 0,//Q_T,Q_T, - 45,//Q_T,Q_TL, - 90,//Q_T,Q_L, - 135,//Q_T,Q_BL, - 180,//Q_T,Q_B, - }, - { - 180,//Q_TL,Q_BR, - 135,//Q_TL,Q_R, - 90,//Q_TL,Q_TR, - 45,//Q_TL,Q_T, - 0,//Q_TL,Q_TL, - 45,//Q_TL,Q_L, - 90,//Q_TL,Q_BL, - 135,//Q_TL,Q_B, - }, - { - 215,//Q_L,Q_BR, - 180,//Q_L,Q_R, - 135,//Q_L,Q_TR, - 90,//Q_L,Q_T, - 45,//Q_L,Q_TL, - 0,//Q_L,Q_L, - 45,//Q_L,Q_BL, - 90,//Q_L,Q_B, - }, - { - 270,//Q_BL,Q_BR, - 215,//Q_BL,Q_R, - 180,//Q_BL,Q_TR, - 135,//Q_BL,Q_T, - 90,//Q_BL,Q_TL, - 45,//Q_BL,Q_L, - 0,//Q_BL,Q_BL, - 45,//Q_BL,Q_B, - }, - { - 45,//Q_B,Q_BR, - 90,//Q_B,Q_R, - 135,//Q_B,Q_TR, - 180,//Q_B,Q_T, - 135,//Q_B,Q_TL, - 90,//Q_B,Q_L, - 45,//Q_B,Q_BL, - 0//Q_B,Q_B, - } -}; - -int PM_SaberAttackChainAngle( int move1, int move2 ) -{ - if ( move1 == -1 || move2 == -1 ) - { +int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = {{ + 0, // Q_BR,Q_BR, + 45, // Q_BR,Q_R, + 90, // Q_BR,Q_TR, + 135, // Q_BR,Q_T, + 180, // Q_BR,Q_TL, + 215, // Q_BR,Q_L, + 270, // Q_BR,Q_BL, + 45, // Q_BR,Q_B, + }, + { + 45, // Q_R,Q_BR, + 0, // Q_R,Q_R, + 45, // Q_R,Q_TR, + 90, // Q_R,Q_T, + 135, // Q_R,Q_TL, + 180, // Q_R,Q_L, + 215, // Q_R,Q_BL, + 90, // Q_R,Q_B, + }, + { + 90, // Q_TR,Q_BR, + 45, // Q_TR,Q_R, + 0, // Q_TR,Q_TR, + 45, // Q_TR,Q_T, + 90, // Q_TR,Q_TL, + 135, // Q_TR,Q_L, + 180, // Q_TR,Q_BL, + 135, // Q_TR,Q_B, + }, + { + 135, // Q_T,Q_BR, + 90, // Q_T,Q_R, + 45, // Q_T,Q_TR, + 0, // Q_T,Q_T, + 45, // Q_T,Q_TL, + 90, // Q_T,Q_L, + 135, // Q_T,Q_BL, + 180, // Q_T,Q_B, + }, + { + 180, // Q_TL,Q_BR, + 135, // Q_TL,Q_R, + 90, // Q_TL,Q_TR, + 45, // Q_TL,Q_T, + 0, // Q_TL,Q_TL, + 45, // Q_TL,Q_L, + 90, // Q_TL,Q_BL, + 135, // Q_TL,Q_B, + }, + { + 215, // Q_L,Q_BR, + 180, // Q_L,Q_R, + 135, // Q_L,Q_TR, + 90, // Q_L,Q_T, + 45, // Q_L,Q_TL, + 0, // Q_L,Q_L, + 45, // Q_L,Q_BL, + 90, // Q_L,Q_B, + }, + { + 270, // Q_BL,Q_BR, + 215, // Q_BL,Q_R, + 180, // Q_BL,Q_TR, + 135, // Q_BL,Q_T, + 90, // Q_BL,Q_TL, + 45, // Q_BL,Q_L, + 0, // Q_BL,Q_BL, + 45, // Q_BL,Q_B, + }, + { + 45, // Q_B,Q_BR, + 90, // Q_B,Q_R, + 135, // Q_B,Q_TR, + 180, // Q_B,Q_T, + 135, // Q_B,Q_TL, + 90, // Q_B,Q_L, + 45, // Q_B,Q_BL, + 0 // Q_B,Q_B, + }}; + +int PM_SaberAttackChainAngle(int move1, int move2) { + if (move1 == -1 || move2 == -1) { return -1; } return saberMoveTransitionAngle[saberMoveData[move1].endQuad][saberMoveData[move2].startQuad]; } -qboolean PM_SaberKataDone( int curmove = LS_NONE, int newmove = LS_NONE ) -{ +qboolean PM_SaberKataDone(int curmove = LS_NONE, int newmove = LS_NONE) { /* if ( pm->gent && pm->gent->client ) { @@ -998,90 +892,62 @@ qboolean PM_SaberKataDone( int curmove = LS_NONE, int newmove = LS_NONE ) } } */ - if ( pm->ps->saberAnimLevel > FORCE_LEVEL_3 ) - {//desann and tavion can link up as many attacks as they want + if (pm->ps->saberAnimLevel > FORCE_LEVEL_3) { // desann and tavion can link up as many attacks as they want return qfalse; } - //FIXME: instead of random, apply some sort of logical conditions to whether or + // FIXME: instead of random, apply some sort of logical conditions to whether or // not you can chain? Like if you were completely missed, you can't chain as much, or...? // And/Or based on FP_SABER_OFFENSE level? So number of attacks you can chain // increases with your FP_SABER_OFFENSE skill? - if ( pm->ps->saberAnimLevel == FORCE_LEVEL_3 ) - { - if ( curmove == LS_NONE || newmove == LS_NONE ) - { - if ( pm->ps->saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > Q_irand( 0, 1 ) ) - { + if (pm->ps->saberAnimLevel == FORCE_LEVEL_3) { + if (curmove == LS_NONE || newmove == LS_NONE) { + if (pm->ps->saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > Q_irand(0, 1)) { return qtrue; } - } - else if ( pm->ps->saberAttackChainCount > Q_irand( 2, 3 ) ) - { + } else if (pm->ps->saberAttackChainCount > Q_irand(2, 3)) { return qtrue; - } - else if ( pm->ps->saberAttackChainCount > 0 ) - { - int chainAngle = PM_SaberAttackChainAngle( curmove, newmove ); - if ( chainAngle < 135 || chainAngle > 215 ) - {//if trying to chain to a move that doesn't continue the momentum + } else if (pm->ps->saberAttackChainCount > 0) { + int chainAngle = PM_SaberAttackChainAngle(curmove, newmove); + if (chainAngle < 135 || chainAngle > 215) { // if trying to chain to a move that doesn't continue the momentum return qtrue; - } - else if ( chainAngle == 180 ) - {//continues the momentum perfectly, allow it to chain 66% of the time - if ( pm->ps->saberAttackChainCount > 1 ) - { + } else if (chainAngle == 180) { // continues the momentum perfectly, allow it to chain 66% of the time + if (pm->ps->saberAttackChainCount > 1) { return qtrue; } - } - else - {//would continue the movement somewhat, 50% chance of continuing - if ( pm->ps->saberAttackChainCount > 2 ) - { + } else { // would continue the movement somewhat, 50% chance of continuing + if (pm->ps->saberAttackChainCount > 2) { return qtrue; } } } - } - else - {//FIXME: have chainAngle influence fast and medium chains as well? - if ( pm->ps->saberAnimLevel == FORCE_LEVEL_2 && pm->ps->saberAttackChainCount > Q_irand( 2, 5 ) ) - { + } else { // FIXME: have chainAngle influence fast and medium chains as well? + if (pm->ps->saberAnimLevel == FORCE_LEVEL_2 && pm->ps->saberAttackChainCount > Q_irand(2, 5)) { return qtrue; } } return qfalse; } -qboolean PM_CheckEnemyInBack( float backCheckDist ) -{ - if ( !pm->gent || !pm->gent->client ) - { +qboolean PM_CheckEnemyInBack(float backCheckDist) { + if (!pm->gent || !pm->gent->client) { return qfalse; } - if ( !pm->ps->clientNum && !g_saberAutoAim->integer && pm->cmd.forwardmove >= 0 ) - {//don't auto-backstab + if (!pm->ps->clientNum && !g_saberAutoAim->integer && pm->cmd.forwardmove >= 0) { // don't auto-backstab return qfalse; } - trace_t trace; - vec3_t end, fwd, fwdAngles = {0,pm->ps->viewangles[YAW],0}; + trace_t trace; + vec3_t end, fwd, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( pm->ps->origin, -backCheckDist, fwd, end ); + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(pm->ps->origin, -backCheckDist, fwd, end); - pm->trace( &trace, pm->ps->origin, vec3_origin, vec3_origin, end, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY, G2_NOCOLLIDE, 0 ); - if ( trace.fraction < 1.0f && trace.entityNum < ENTITYNUM_WORLD ) - { + pm->trace(&trace, pm->ps->origin, vec3_origin, vec3_origin, end, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY, G2_NOCOLLIDE, 0); + if (trace.fraction < 1.0f && trace.entityNum < ENTITYNUM_WORLD) { gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt - && traceEnt->health > 0 - && traceEnt->client - && traceEnt->client->playerTeam == pm->gent->client->enemyTeam - && traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( !pm->ps->clientNum ) - {//player - if ( pm->gent ) - {//set player enemy to traceEnt so he auto-aims at him + if (traceEnt && traceEnt->health > 0 && traceEnt->client && traceEnt->client->playerTeam == pm->gent->client->enemyTeam && + traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (!pm->ps->clientNum) { // player + if (pm->gent) { // set player enemy to traceEnt so he auto-aims at him pm->gent->enemy = traceEnt; } } @@ -1091,223 +957,156 @@ qboolean PM_CheckEnemyInBack( float backCheckDist ) return qfalse; } -int PM_PickBackStab( void ) -{ - if ( !pm->gent || !pm->gent->client ) - { +int PM_PickBackStab(void) { + if (!pm->gent || !pm->gent->client) { return LS_READY; } - if ( pm->gent->client->NPC_class == CLASS_TAVION ) - { + if (pm->gent->client->NPC_class == CLASS_TAVION) { return LS_A_BACKSTAB; - } - else if ( pm->gent->client->NPC_class == CLASS_DESANN ) - { - if ( pm->ps->saberMove == LS_READY || !Q_irand( 0, 3 ) ) - { + } else if (pm->gent->client->NPC_class == CLASS_DESANN) { + if (pm->ps->saberMove == LS_READY || !Q_irand(0, 3)) { return LS_A_BACKSTAB; - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - { + } else if (pm->ps->pm_flags & PMF_DUCKED) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } - } - else if ( pm->ps->saberAnimLevel == FORCE_LEVEL_2 ) - {//using medium attacks - if ( pm->ps->pm_flags & PMF_DUCKED ) - { + } else if (pm->ps->saberAnimLevel == FORCE_LEVEL_2) { // using medium attacks + if (pm->ps->pm_flags & PMF_DUCKED) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } - } - else - { + } else { return LS_A_BACKSTAB; } } -extern int PM_NPCSaberAttackFromQuad( int quad ); -int PM_SaberFlipOverAttackMove( void ); -int PM_AttackForEnemyPos( qboolean allowFB ) -{ +extern int PM_NPCSaberAttackFromQuad(int quad); +int PM_SaberFlipOverAttackMove(void); +int PM_AttackForEnemyPos(qboolean allowFB) { int autoMove = -1; vec3_t enemy_org, enemyDir, faceFwd, faceRight, faceUp, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( facingAngles, faceFwd, faceRight, faceUp ); - //FIXME: predict enemy position? - if ( pm->gent->enemy->client ) - { - VectorCopy( pm->gent->enemy->currentOrigin, enemy_org ); - VectorSubtract( pm->gent->enemy->client->renderInfo.eyePoint, pm->ps->origin, enemyDir ); - } - else - { - if ( pm->gent->enemy->bmodel && VectorCompare( vec3_origin, pm->gent->enemy->currentOrigin ) ) - {//a brush model without an origin brush - vec3_t size; - VectorSubtract( pm->gent->enemy->absmax, pm->gent->enemy->absmin, size ); - VectorMA( pm->gent->enemy->absmin, 0.5, size, enemy_org ); - } - else - { - VectorCopy( pm->gent->enemy->currentOrigin, enemy_org ); - } - VectorSubtract( enemy_org, pm->ps->origin, enemyDir ); - } - float enemyDist = VectorNormalize( enemyDir ); - float dot = DotProduct( enemyDir, faceFwd ); - if ( dot > 0 ) - {//enemy is in front - if ( (!pm->ps->clientNum || PM_ControlledByPlayer()) - && dot > 0.65f - && pm->gent->enemy->client && PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) - && enemyDir[2] <= 20 ) - {//guy is on the ground below me, do a top-down attack + AngleVectors(facingAngles, faceFwd, faceRight, faceUp); + // FIXME: predict enemy position? + if (pm->gent->enemy->client) { + VectorCopy(pm->gent->enemy->currentOrigin, enemy_org); + VectorSubtract(pm->gent->enemy->client->renderInfo.eyePoint, pm->ps->origin, enemyDir); + } else { + if (pm->gent->enemy->bmodel && VectorCompare(vec3_origin, pm->gent->enemy->currentOrigin)) { // a brush model without an origin brush + vec3_t size; + VectorSubtract(pm->gent->enemy->absmax, pm->gent->enemy->absmin, size); + VectorMA(pm->gent->enemy->absmin, 0.5, size, enemy_org); + } else { + VectorCopy(pm->gent->enemy->currentOrigin, enemy_org); + } + VectorSubtract(enemy_org, pm->ps->origin, enemyDir); + } + float enemyDist = VectorNormalize(enemyDir); + float dot = DotProduct(enemyDir, faceFwd); + if (dot > 0) { // enemy is in front + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) && dot > 0.65f && pm->gent->enemy->client && PM_InKnockDownOnGround(&pm->gent->enemy->client->ps) && + enemyDir[2] <= 20) { // guy is on the ground below me, do a top-down attack return LS_A_T2B; } - if ( allowFB ) - {//directly in front anim allowed - if ( enemyDist > 200 || pm->gent->enemy->health <= 0 ) - {//hmm, look in back for an enemy - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//player should never do this automatically - if ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 100 ) ) - { + if (allowFB) { // directly in front anim allowed + if (enemyDist > 200 || pm->gent->enemy->health <= 0) { // hmm, look in back for an enemy + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // player should never do this automatically + if (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(100)) { return PM_PickBackStab(); } } } } - //this is the default only if they're *right* in front... - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5)//using medium attacks or Tavion - //&& !PM_InKnockDown( pm->ps ) - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=500) //on ground or just jumped - && ( pm->ps->clientNum || pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_FORCEJUMP1 || pm->ps->legsAnim == BOTH_INAIR1 || pm->ps->legsAnim == BOTH_FORCEINAIR1 )//either an NPC or in a non-flip forward jump - && ( (pm->ps->clientNum&&!PM_ControlledByPlayer()&&!Q_irand(0,2)) || pm->cmd.upmove || (pm->ps->pm_flags&PMF_JUMPING) ) )//jumping - {//flip over-forward down-attack - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - (pm->gent->NPC && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) && !Q_irand(0, 2) ) ) - {//only player or acrobat or boss and higher can do this - if ( pm->gent->enemy->health > 0 - && pm->gent->enemy->maxs[2] > 12 - && (!pm->gent->enemy->client || !PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) ) - && DistanceSquared( pm->gent->currentOrigin, enemy_org ) < 10000 - && InFront( enemy_org, pm->gent->currentOrigin, facingAngles, 0.3f ) ) - {//enemy must be close and in front + // this is the default only if they're *right* in front... + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5) // using medium attacks or Tavion + //&& !PM_InKnockDown( pm->ps ) + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 500) // on ground or just jumped + && (pm->ps->clientNum || pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_FORCEJUMP1 || pm->ps->legsAnim == BOTH_INAIR1 || + pm->ps->legsAnim == BOTH_FORCEINAIR1) // either an NPC or in a non-flip forward jump + && ((pm->ps->clientNum && !PM_ControlledByPlayer() && !Q_irand(0, 2)) || pm->cmd.upmove || (pm->ps->pm_flags & PMF_JUMPING))) // jumping + { // flip over-forward down-attack + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent->NPC && (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT) && + !Q_irand(0, 2))) { // only player or acrobat or boss and higher can do this + if (pm->gent->enemy->health > 0 && pm->gent->enemy->maxs[2] > 12 && + (!pm->gent->enemy->client || !PM_InKnockDownOnGround(&pm->gent->enemy->client->ps)) && + DistanceSquared(pm->gent->currentOrigin, enemy_org) < 10000 && + InFront(enemy_org, pm->gent->currentOrigin, facingAngles, 0.3f)) { // enemy must be close and in front return PM_SaberFlipOverAttackMove(); } } } } - if ( pm->ps->clientNum && !PM_ControlledByPlayer()) - {//NPC - if ( pm->gent->NPC - && pm->gent->NPC->rank >= RANK_LT_JG - && ( pm->gent->NPC->rank == RANK_LT_JG || Q_irand( 0, pm->gent->NPC->rank ) >= RANK_ENSIGN ) + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPC + if (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + (pm->gent->NPC->rank == RANK_LT_JG || Q_irand(0, pm->gent->NPC->rank) >= RANK_ENSIGN) //&& !PM_InKnockDown( pm->ps ) - && ((pm->ps->saberAnimLevel == FORCE_LEVEL_1 && !Q_irand( 0, 2 )) - ||(pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand( 0, 4 ))) ) - {//fencers and higher only - 33% chance of using lunge (desann 20% chance) + && ((pm->ps->saberAnimLevel == FORCE_LEVEL_1 && !Q_irand(0, 2)) || + (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_DESANN && + !Q_irand(0, 4)))) { // fencers and higher only - 33% chance of using lunge (desann 20% chance) autoMove = LS_A_LUNGE; - } - else - { + } else { autoMove = LS_A_T2B; } - } - else - {//player - if ( pm->ps->saberAnimLevel == FORCE_LEVEL_1 + } else { // player + if (pm->ps->saberAnimLevel == FORCE_LEVEL_1 //&& !PM_InKnockDown( pm->ps ) - && (pm->ps->pm_flags&PMF_DUCKED||pm->cmd.upmove<0) ) - {//ducking player + && (pm->ps->pm_flags & PMF_DUCKED || pm->cmd.upmove < 0)) { // ducking player autoMove = LS_A_LUNGE; - } - else - { + } else { autoMove = LS_A_T2B; } } - } - else - {//pick a random one - if ( Q_irand( 0, 1 ) ) - { + } else { // pick a random one + if (Q_irand(0, 1)) { autoMove = LS_A_TR2BL; - } - else - { + } else { autoMove = LS_A_TL2BR; } } - float dotR = DotProduct( enemyDir, faceRight ); - if ( dotR > 0.35 ) - {//enemy is to far right + float dotR = DotProduct(enemyDir, faceRight); + if (dotR > 0.35) { // enemy is to far right autoMove = LS_A_L2R; - } - else if ( dotR < -0.35 ) - {//far left + } else if (dotR < -0.35) { // far left autoMove = LS_A_R2L; - } - else if ( dotR > 0.15 ) - {//enemy is to near right + } else if (dotR > 0.15) { // enemy is to near right autoMove = LS_A_TR2BL; - } - else if ( dotR < -0.15 ) - {//near left + } else if (dotR < -0.15) { // near left autoMove = LS_A_TL2BR; } - if ( DotProduct( enemyDir, faceUp ) > 0.5 ) - {//enemy is above me - if ( autoMove == LS_A_TR2BL ) - { + if (DotProduct(enemyDir, faceUp) > 0.5) { // enemy is above me + if (autoMove == LS_A_TR2BL) { autoMove = LS_A_BL2TR; - } - else if ( autoMove == LS_A_TL2BR ) - { + } else if (autoMove == LS_A_TL2BR) { autoMove = LS_A_BR2TL; } } - } - else if ( allowFB ) - {//back attack allowed - //if ( !PM_InKnockDown( pm->ps ) ) - if ( !pm->gent->enemy->client || pm->gent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( dot < -0.75f - && enemyDist < 128 - && (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || (pm->gent->client &&pm->gent->client->NPC_class == CLASS_TAVION&&Q_irand(0,2))) ) - {//fast back-stab - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//can't do it while ducked? - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG) ) - {//only fencers and above can do this + } else if (allowFB) { // back attack allowed + // if ( !PM_InKnockDown( pm->ps ) ) + if (!pm->gent->enemy->client || pm->gent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (dot < -0.75f && enemyDist < 128 && + (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || + (pm->gent->client && pm->gent->client->NPC_class == CLASS_TAVION && Q_irand(0, 2)))) { // fast back-stab + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // can't do it while ducked? + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG)) { // only fencers and above can do this autoMove = LS_A_BACKSTAB; } } - } - else if ( pm->ps->saberAnimLevel > FORCE_LEVEL_1 ) - {//higher level back spin-attacks - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( (pm->ps->pm_flags&PMF_DUCKED) || pm->cmd.upmove < 0 ) - { + } else if (pm->ps->saberAnimLevel > FORCE_LEVEL_1) { // higher level back spin-attacks + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if ((pm->ps->pm_flags & PMF_DUCKED) || pm->cmd.upmove < 0) { autoMove = LS_A_BACK_CR; - } - else - { + } else { autoMove = LS_A_BACK; } } @@ -1317,373 +1116,290 @@ int PM_AttackForEnemyPos( qboolean allowFB ) return autoMove; } -int PM_SaberLungeAttackMove( void ) -{ +int PM_SaberLungeAttackMove(void) { vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the lunge - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity ); + // do the lunge + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); pm->ps->velocity[2] = 50; - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); return LS_A_LUNGE; } -int PM_SaberJumpAttackMove( void ) -{ +int PM_SaberJumpAttackMove(void) { vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 200, pm->ps->velocity ); + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 200, pm->ps->velocity); pm->ps->velocity[2] = 180; - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - PM_AddEvent( EV_JUMP ); - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // FIXME: NPCs yell? + PM_AddEvent(EV_JUMP); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); pm->cmd.upmove = 0; return LS_A_JUMP_T__B_; } -int PM_SaberFlipOverAttackMove( void ) -{ - //FIXME: check above for room enough to jump! - //FIXME: while in this jump, keep velocity[2] at a minimum until the end of the anim +int PM_SaberFlipOverAttackMove(void) { + // FIXME: check above for room enough to jump! + // FIXME: while in this jump, keep velocity[2] at a minimum until the end of the anim vec3_t fwdAngles, jumpFwd; - VectorCopy( pm->ps->viewangles, fwdAngles ); + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity ); + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); pm->ps->velocity[2] = 250; - //250 is normalized for a standing enemy at your z level, about 64 tall... adjust for actual maxs[2]-mins[2] of enemy and for zdiff in origins - if ( pm->gent && pm->gent->enemy ) - { //go higher for taller enemies - pm->ps->velocity[2] *= (pm->gent->enemy->maxs[2]-pm->gent->enemy->mins[2])/64.0f; - //go higher for enemies higher than you, lower for those lower than you + // 250 is normalized for a standing enemy at your z level, about 64 tall... adjust for actual maxs[2]-mins[2] of enemy and for zdiff in origins + if (pm->gent && pm->gent->enemy) { // go higher for taller enemies + pm->ps->velocity[2] *= (pm->gent->enemy->maxs[2] - pm->gent->enemy->mins[2]) / 64.0f; + // go higher for enemies higher than you, lower for those lower than you float zDiff = pm->gent->enemy->currentOrigin[2] - pm->ps->origin[2]; pm->ps->velocity[2] += (zDiff)*1.5f; - //clamp to decent-looking values - //FIXME: still jump too low sometimes - if ( zDiff <= 0 && pm->ps->velocity[2] < 200 ) - {//if we're on same level, don't let me jump so low, I clip into the ground + // clamp to decent-looking values + // FIXME: still jump too low sometimes + if (zDiff <= 0 && pm->ps->velocity[2] < 200) { // if we're on same level, don't let me jump so low, I clip into the ground pm->ps->velocity[2] = 200; - } - else if ( pm->ps->velocity[2] < 50 ) - { + } else if (pm->ps->velocity[2] < 50) { pm->ps->velocity[2] = 50; - } - else if ( pm->ps->velocity[2] > 400 ) - { + } else if (pm->ps->velocity[2] > 400) { pm->ps->velocity[2] = 400; } } - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? - PM_AddEvent( EV_JUMP ); - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // FIXME: NPCs yell? + PM_AddEvent(EV_JUMP); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); pm->cmd.upmove = 0; - //FIXME: don't allow this to land on other people + // FIXME: don't allow this to land on other people - pm->gent->angle = pm->ps->viewangles[YAW];//so we know what yaw we started this at - if ( Q_irand( 0, 1 ) ) - { + pm->gent->angle = pm->ps->viewangles[YAW]; // so we know what yaw we started this at + if (Q_irand(0, 1)) { return LS_A_FLIP_STAB; - } - else - { + } else { return LS_A_FLIP_SLASH; } } -int PM_SaberAttackForMovement( int forwardmove, int rightmove, int move ) -{ - if ( rightmove > 0 ) - {//moving right - if ( forwardmove > 0 ) - {//forward right = TL2BR slash +int PM_SaberAttackForMovement(int forwardmove, int rightmove, int move) { + if (rightmove > 0) { // moving right + if (forwardmove > 0) { // forward right = TL2BR slash return LS_A_TL2BR; - } - else if ( forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (forwardmove < 0) { // backward right = BL2TR uppercut return LS_A_BL2TR; - } - else - {//just right is a left slice + } else { // just right is a left slice return LS_A_L2R; } - } - else if ( rightmove < 0 ) - {//moving left - if ( forwardmove > 0 ) - {//forward left = TR2BL slash + } else if (rightmove < 0) { // moving left + if (forwardmove > 0) { // forward left = TR2BL slash return LS_A_TR2BL; - } - else if ( forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (forwardmove < 0) { // backward left = BR2TL uppercut return LS_A_BR2TL; - } - else - {//just left is a right slice + } else { // just left is a right slice return LS_A_R2L; } - } - else - {//not moving left or right - if ( forwardmove > 0 ) - {//forward= T2B slash - if ( pm->gent && pm->gent->enemy && pm->gent->enemy->client ) - {//I have an active enemy - if ( !pm->ps->clientNum || PM_ControlledByPlayer() ) - {//a player who is running at an enemy - //if the enemy is not a jedi, don't use top-down, pick a diagonal or side attack - if ( pm->gent->enemy->s.weapon != WP_SABER && g_saberAutoAim->integer ) - { - int autoMove = PM_AttackForEnemyPos( qfalse ); - if ( autoMove != -1 ) - { + } else { // not moving left or right + if (forwardmove > 0) { // forward= T2B slash + if (pm->gent && pm->gent->enemy && pm->gent->enemy->client) { // I have an active enemy + if (!pm->ps->clientNum || PM_ControlledByPlayer()) { // a player who is running at an enemy + // if the enemy is not a jedi, don't use top-down, pick a diagonal or side attack + if (pm->gent->enemy->s.weapon != WP_SABER && g_saberAutoAim->integer) { + int autoMove = PM_AttackForEnemyPos(qfalse); + if (autoMove != -1) { return autoMove; } } } - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5)//using medium attacks or Tavion - //&& !PM_InKnockDown( pm->ps ) - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=500) //on ground or just jumped - && ( pm->ps->clientNum || pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_FORCEJUMP1 || pm->ps->legsAnim == BOTH_INAIR1 || pm->ps->legsAnim == BOTH_FORCEINAIR1 )//either an NPC or in a non-flip forward jump - && ((pm->ps->clientNum&&!PM_ControlledByPlayer()&&!Q_irand(0,2))||pm->cmd.upmove>0||pm->ps->pm_flags&PMF_JUMPING))//jumping - {//flip over-forward down-attack - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - (pm->gent->NPC && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) && !Q_irand(0, 2) ) ) - {//only player or acrobat or boss and higher can do this - vec3_t fwdAngles = {0,pm->ps->viewangles[YAW],0}; - if ( pm->gent->enemy->health > 0 - && pm->gent->enemy->maxs[2] > 12 - && (!pm->gent->enemy->client || !PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) ) - && DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ) < 10000 - && InFront( pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, 0.3f ) ) - {//enemy must be alive, not low to ground, close and in front + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5) // using medium attacks or Tavion + //&& !PM_InKnockDown( pm->ps ) + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 500) // on ground or just jumped + && (pm->ps->clientNum || pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_FORCEJUMP1 || pm->ps->legsAnim == BOTH_INAIR1 || + pm->ps->legsAnim == BOTH_FORCEINAIR1) // either an NPC or in a non-flip forward jump + && + ((pm->ps->clientNum && !PM_ControlledByPlayer() && !Q_irand(0, 2)) || pm->cmd.upmove > 0 || pm->ps->pm_flags & PMF_JUMPING)) // jumping + { // flip over-forward down-attack + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent->NPC && (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT) && + !Q_irand(0, 2))) { // only player or acrobat or boss and higher can do this + vec3_t fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + if (pm->gent->enemy->health > 0 && pm->gent->enemy->maxs[2] > 12 && + (!pm->gent->enemy->client || !PM_InKnockDownOnGround(&pm->gent->enemy->client->ps)) && + DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin) < 10000 && + InFront(pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, + 0.3f)) { // enemy must be alive, not low to ground, close and in front return PM_SaberFlipOverAttackMove(); } } } } } - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || (pm->gent&&pm->gent->client&&pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand( 0, 2 ))) + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_1 || (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0, 2))) //&& !PM_InKnockDown( pm->ps ) - && (pm->cmd.upmove < 0 || pm->ps->pm_flags&PMF_DUCKED) - && (pm->ps->legsAnim == BOTH_STAND2||pm->ps->legsAnim == BOTH_SABERFAST_STANCE||pm->ps->legsAnim == BOTH_SABERSLOW_STANCE||level.time-pm->ps->lastStationary<=500) ) - {//not moving (or just started), ducked and using fast attacks - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - ( pm->gent - && pm->gent->NPC - && pm->gent->NPC->rank >= RANK_LT_JG - && ( pm->gent->NPC->rank == RANK_LT_JG || Q_irand( 0, pm->gent->NPC->rank ) >= RANK_ENSIGN ) - && !Q_irand( 0, 3-g_spskill->integer ) ) ) - {//only player or fencer and higher can do this + && (pm->cmd.upmove < 0 || pm->ps->pm_flags & PMF_DUCKED) && + (pm->ps->legsAnim == BOTH_STAND2 || pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || + level.time - pm->ps->lastStationary <= 500)) { // not moving (or just started), ducked and using fast attacks + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + (pm->gent->NPC->rank == RANK_LT_JG || Q_irand(0, pm->gent->NPC->rank) >= RANK_ENSIGN) && + !Q_irand(0, 3 - g_spskill->integer))) { // only player or fencer and higher can do this return PM_SaberLungeAttackMove(); } } } - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - { - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_3 || (pm->gent&&pm->gent->client&&pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand( 0, 1 )))//using strong attacks - //&& !PM_InKnockDown( pm->ps ) - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && pm->gent && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=500) //on ground or just jumped (if not player) - //&& (pm->ps->legsAnim == BOTH_STAND2||pm->ps->legsAnim == BOTH_SABERFAST_STANCE||pm->ps->legsAnim == BOTH_SABERSLOW_STANCE||level.time-pm->ps->lastStationary<=500)//standing or just started moving - && (pm->cmd.upmove||pm->ps->pm_flags&PMF_JUMPING))//jumping - {//strong attack: jump-hack - if ( //!pm->ps->clientNum || - (pm->gent && pm->gent->NPC && !PM_ControlledByPlayer() && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) ) - {//only player or acrobat or boss and higher can do this + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_3 || + (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0, 1))) // using strong attacks + //&& !PM_InKnockDown( pm->ps ) + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && pm->gent && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 500) // on ground or just jumped (if not player) + //&& (pm->ps->legsAnim == BOTH_STAND2||pm->ps->legsAnim == BOTH_SABERFAST_STANCE||pm->ps->legsAnim == + //BOTH_SABERSLOW_STANCE||level.time-pm->ps->lastStationary<=500)//standing or just started moving + && (pm->cmd.upmove || pm->ps->pm_flags & PMF_JUMPING)) // jumping + { // strong attack: jump-hack + if ( //! pm->ps->clientNum || + (pm->gent && pm->gent->NPC && !PM_ControlledByPlayer() && + (pm->gent->NPC->rank == RANK_CREWMAN || pm->gent->NPC->rank >= RANK_LT))) { // only player or acrobat or boss and higher can do this return PM_SaberJumpAttackMove(); } } } return LS_A_T2B; - } - else if ( forwardmove < 0 ) - {//backward= T2B slash//B2T uppercut? - if ( (pm->ps->clientNum&&!PM_ControlledByPlayer()) || ((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode) ) - { - if ( pm->gent && pm->gent->enemy ) - {//FIXME: or just trace for a valid enemy standing behind me? And no enemy in front? + } else if (forwardmove < 0) { // backward= T2B slash//B2T uppercut? + if ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) { + if (pm->gent && pm->gent->enemy) { // FIXME: or just trace for a valid enemy standing behind me? And no enemy in front? vec3_t enemyDir, faceFwd, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - AngleVectors( facingAngles, faceFwd, NULL, NULL ); - VectorSubtract( pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir ); - float dot = DotProduct( enemyDir, faceFwd ); - if ( dot < 0 ) - {//enemy is behind me - if ( dot < -0.75f - && DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ) < 16384//128 squared - && (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || (pm->gent->client &&pm->gent->client->NPC_class == CLASS_TAVION&&Q_irand(0,1))) ) - {//fast attacks and Tavion - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//can't do it while ducked? - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG) ) - {//only fencers and above can do this + AngleVectors(facingAngles, faceFwd, NULL, NULL); + VectorSubtract(pm->gent->enemy->currentOrigin, pm->ps->origin, enemyDir); + float dot = DotProduct(enemyDir, faceFwd); + if (dot < 0) { // enemy is behind me + if (dot < -0.75f && DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin) < 16384 // 128 squared + && (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || + (pm->gent->client && pm->gent->client->NPC_class == CLASS_TAVION && Q_irand(0, 1)))) { // fast attacks and Tavion + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // can't do it while ducked? + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG)) { // only fencers and above can do this return LS_A_BACKSTAB; } } - } - else if ( pm->ps->saberAnimLevel > FORCE_LEVEL_1 ) - {//medium and higher attacks - if ( (pm->ps->pm_flags&PMF_DUCKED) || pm->cmd.upmove < 0 ) - { + } else if (pm->ps->saberAnimLevel > FORCE_LEVEL_1) { // medium and higher attacks + if ((pm->ps->pm_flags & PMF_DUCKED) || pm->cmd.upmove < 0) { return LS_A_BACK_CR; - } - else - { + } else { return LS_A_BACK; } } - } - else - {//enemy in front - float enemyDistSq = DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ); - if ( (pm->ps->saberAnimLevel == FORCE_LEVEL_1 - || pm->gent->client->NPC_class == CLASS_TAVION - || (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand( 0, 3 ))) - && (enemyDistSq > 16384 || pm->gent->enemy->health <= 0) )//128 squared - {//my enemy is pretty far in front of me and I'm using fast attacks - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 128 ) ) - { + } else { // enemy in front + float enemyDistSq = DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin); + if ((pm->ps->saberAnimLevel == FORCE_LEVEL_1 || pm->gent->client->NPC_class == CLASS_TAVION || + (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0, 3))) && + (enemyDistSq > 16384 || pm->gent->enemy->health <= 0)) // 128 squared + { // my enemy is pretty far in front of me and I'm using fast attacks + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN)) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(128)) { return PM_PickBackStab(); } } - } - else if ( (pm->ps->saberAnimLevel >= FORCE_LEVEL_2 - || pm->gent->client->NPC_class == CLASS_DESANN) - && (enemyDistSq > 40000 || pm->gent->enemy->health <= 0) )//200 squared - {//enemy is very faw away and I'm using medium/strong attacks - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - ( pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, pm->gent->NPC->rank ) > RANK_ENSIGN ) ) - {//only fencers and higher can do this, higher rank does it more - if ( PM_CheckEnemyInBack( 164 ) ) - { + } else if ((pm->ps->saberAnimLevel >= FORCE_LEVEL_2 || pm->gent->client->NPC_class == CLASS_DESANN) && + (enemyDistSq > 40000 || pm->gent->enemy->health <= 0)) // 200 squared + { // enemy is very faw away and I'm using medium/strong attacks + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->client && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, pm->gent->NPC->rank) > RANK_ENSIGN)) { // only fencers and higher can do this, higher rank does it more + if (PM_CheckEnemyInBack(164)) { return PM_PickBackStab(); } } } } - } - else - {//no current enemy - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) && pm->gent && pm->gent->client ) - {//only player - if ( PM_CheckEnemyInBack( 128 ) ) - { + } else { // no current enemy + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) && pm->gent && pm->gent->client) { // only player + if (PM_CheckEnemyInBack(128)) { return PM_PickBackStab(); } } } } - //else just swing down + // else just swing down return LS_A_T2B; - } - else if ( PM_SaberInBounce( move ) ) - {//bounces should go to their default attack if you don't specify a direction but are attacking + } else if (PM_SaberInBounce(move)) { // bounces should go to their default attack if you don't specify a direction but are attacking int newmove; - if ( pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand( 0, 3 ) ) - {//use NPC random - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[move].endQuad ); - } - else - {//player uses chain-attack + if (pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand(0, 3)) { // use NPC random + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[move].endQuad); + } else { // player uses chain-attack newmove = saberMoveData[move].chain_attack; } - if ( PM_SaberKataDone( move, newmove ) ) - { + if (PM_SaberKataDone(move, newmove)) { return saberMoveData[move].chain_idle; - } - else - { + } else { return newmove; } - } - else if ( PM_SaberInKnockaway( move ) ) - {//bounces should go to their default attack if you don't specify a direction but are attacking + } else if (PM_SaberInKnockaway(move)) { // bounces should go to their default attack if you don't specify a direction but are attacking int newmove; - if ( pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand( 0, 3 ) ) - {//use NPC random - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[move].endQuad ); - } - else - { - if ( pm->ps->saberAnimLevel == FORCE_LEVEL_1 || - pm->ps->saberAnimLevel == FORCE_LEVEL_5 ) - {//player is in fast attacks, so come right back down from the same spot - newmove = PM_AttackMoveForQuad( saberMoveData[move].endQuad ); - } - else - {//use a transition to wrap to another attack from a different dir + if (pm->ps->clientNum && !PM_ControlledByPlayer() && Q_irand(0, 3)) { // use NPC random + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[move].endQuad); + } else { + if (pm->ps->saberAnimLevel == FORCE_LEVEL_1 || + pm->ps->saberAnimLevel == FORCE_LEVEL_5) { // player is in fast attacks, so come right back down from the same spot + newmove = PM_AttackMoveForQuad(saberMoveData[move].endQuad); + } else { // use a transition to wrap to another attack from a different dir newmove = saberMoveData[move].chain_attack; } } - if ( PM_SaberKataDone( move, newmove ) ) - { + if (PM_SaberKataDone(move, newmove)) { return saberMoveData[move].chain_idle; - } - else - { + } else { return newmove; } - } - else if ( move == LS_READY || move == LS_A_FLIP_STAB || move == LS_A_FLIP_SLASH ) - {//Not moving at all, shouldn't have gotten here...? - if ( pm->ps->clientNum || g_saberAutoAim->integer ) - {//auto-aim - if ( pm->gent && pm->gent->enemy ) - {//based on enemy position, pick a proper attack - int autoMove = PM_AttackForEnemyPos( qtrue ); - if ( autoMove != -1 ) - { + } else if (move == LS_READY || move == LS_A_FLIP_STAB || move == LS_A_FLIP_SLASH) { // Not moving at all, shouldn't have gotten here...? + if (pm->ps->clientNum || g_saberAutoAim->integer) { // auto-aim + if (pm->gent && pm->gent->enemy) { // based on enemy position, pick a proper attack + int autoMove = PM_AttackForEnemyPos(qtrue); + if (autoMove != -1) { return autoMove; } - } - else if ( fabs(pm->ps->viewangles[0]) > 30 ) - {//looking far up or far down uses the top to bottom attack, presuming you want a vertical attack + } else if (fabs(pm->ps->viewangles[0]) > 30) { // looking far up or far down uses the top to bottom attack, presuming you want a vertical attack return LS_A_T2B; } - } - else - {//for now, just pick a random attack - return Q_irand( LS_A_TL2BR, LS_A_T2B ); + } else { // for now, just pick a random attack + return Q_irand(LS_A_TL2BR, LS_A_T2B); } } } - //FIXME: pick a return? + // FIXME: pick a return? return LS_NONE; } -int PM_SaberAnimTransitionAnim( int curmove, int newmove ) -{ - //FIXME: take FP_SABER_OFFENSE into account here somehow? +int PM_SaberAnimTransitionAnim(int curmove, int newmove) { + // FIXME: take FP_SABER_OFFENSE into account here somehow? int retmove = newmove; - if ( curmove == LS_READY ) - {//just standing there - switch ( newmove ) - { + if (curmove == LS_READY) { // just standing there + switch (newmove) { case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -1691,20 +1407,16 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the start - retmove = LS_S_TL2BR + (newmove-LS_A_TL2BR); + // transition is the start + retmove = LS_S_TL2BR + (newmove - LS_A_TL2BR); break; } - } - else - { - switch ( newmove ) - { - //transitioning to ready pose + } else { + switch (newmove) { + // transitioning to ready pose case LS_READY: - switch ( curmove ) - { - //transitioning from an attack + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -1712,12 +1424,12 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the return - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); + // transition is the return + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); break; } break; - //transitioning to an attack + // transitioning to an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -1725,29 +1437,20 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - if ( newmove == curmove ) - {//FIXME: need a spin or something or go to next level, but for now, just play the return - //going into another attack... - //allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 - //FIXME: don't let strong attacks chain to an attack in the opposite direction ( > 45 degrees?) - if ( PM_SaberKataDone( curmove, newmove ) ) - {//done with this kata, must return to ready before attack again - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); - } - else - {//okay to chain to another attack + if (newmove == curmove) { // FIXME: need a spin or something or go to next level, but for now, just play the return + // going into another attack... + // allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 + // FIXME: don't let strong attacks chain to an attack in the opposite direction ( > 45 degrees?) + if (PM_SaberKataDone(curmove, newmove)) { // done with this kata, must return to ready before attack again + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); + } else { // okay to chain to another attack retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; } - } - else if ( saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad ) - {//new move starts from same quadrant + } else if (saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad) { // new move starts from same quadrant retmove = newmove; - } - else - { - switch ( curmove ) - { - //transitioning from an attack + } else { + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -1765,7 +1468,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_D1_B_: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //transitioning from a return + // transitioning from a return case LS_R_TL2BR: case LS_R_L2R: case LS_R_BL2TR: @@ -1773,7 +1476,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_R_R2L: case LS_R_TR2BL: case LS_R_T2B: - //transitioning from a bounce + // transitioning from a bounce /* case LS_BOUNCE_UL2LL: case LS_BOUNCE_LL2UL: @@ -1791,7 +1494,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_BOUNCE_LR: case LS_BOUNCE_LL: */ - //transitioning from a parry/reflection/knockaway/broken parry + // transitioning from a parry/reflection/knockaway/broken parry case LS_PARRY_UP: case LS_PARRY_UR: case LS_PARRY_UL: @@ -1822,16 +1525,15 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_H1_BL: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //NB: transitioning from transitions is fine + // NB: transitioning from transitions is fine } } break; - //transitioning to any other anim is not supported + // transitioning to any other anim is not supported } } - if ( retmove == LS_NONE ) - { + if (retmove == LS_NONE) { return newmove; } @@ -1844,76 +1546,62 @@ PM_LegsAnimForFrame Returns animNumber for current frame ------------------------- */ -int PM_LegsAnimForFrame( gentity_t *ent, int legsFrame ) -{ - //Must be a valid client - if ( ent->client == NULL ) +int PM_LegsAnimForFrame(gentity_t *ent, int legsFrame) { + // Must be a valid client + if (ent->client == NULL) return -1; - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return -1; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - for ( int animation = 0; animation < FACE_TALK1; animation++ ) - { - if ( animation >= TORSO_DROPWEAP1 && animation < LEGS_WALKBACK1 ) - {//not a possible legs anim + for (int animation = 0; animation < FACE_TALK1; animation++) { + if (animation >= TORSO_DROPWEAP1 && animation < LEGS_WALKBACK1) { // not a possible legs anim continue; } - if ( animations[animation].firstFrame > legsFrame ) - {//This anim starts after this frame + if (animations[animation].firstFrame > legsFrame) { // This anim starts after this frame continue; } - if ( animations[animation].firstFrame + animations[animation].numFrames < legsFrame ) - {//This anim ends before this frame + if (animations[animation].firstFrame + animations[animation].numFrames < legsFrame) { // This anim ends before this frame continue; } - //else, must be in this anim! + // else, must be in this anim! return animation; } - //Not in ANY torsoAnim? SHOULD NEVER HAPPEN -// assert(0); + // Not in ANY torsoAnim? SHOULD NEVER HAPPEN + // assert(0); return -1; } -int PM_ValidateAnimRange( int startFrame, int endFrame, float animSpeed ) -{//given a startframe and endframe, see if that lines up with any known animation +int PM_ValidateAnimRange(int startFrame, int endFrame, float animSpeed) { // given a startframe and endframe, see if that lines up with any known animation animation_t *animations = level.knownAnimFileSets[0].animations; - for ( int anim = 0; anim < MAX_ANIMATIONS; anim++ ) - { - if ( animSpeed < 0 ) - {//playing backwards - if ( animations[anim].firstFrame == endFrame ) - { - if ( animations[anim].numFrames + animations[anim].firstFrame == startFrame ) - { - //Com_Printf( "valid reverse anim: %s\n", animTable[anim].name ); + for (int anim = 0; anim < MAX_ANIMATIONS; anim++) { + if (animSpeed < 0) { // playing backwards + if (animations[anim].firstFrame == endFrame) { + if (animations[anim].numFrames + animations[anim].firstFrame == startFrame) { + // Com_Printf( "valid reverse anim: %s\n", animTable[anim].name ); return anim; } - } - } - else - {//playing forwards - if ( animations[anim].firstFrame == startFrame ) - {//This anim starts on this frame - if ( animations[anim].firstFrame + animations[anim].numFrames == endFrame ) - {//This anim ends on this frame - //Com_Printf( "valid forward anim: %s\n", animTable[anim].name ); + } + } else { // playing forwards + if (animations[anim].firstFrame == startFrame) { // This anim starts on this frame + if (animations[anim].firstFrame + animations[anim].numFrames == endFrame) { // This anim ends on this frame + // Com_Printf( "valid forward anim: %s\n", animTable[anim].name ); return anim; } } } - //else, must not be this anim! + // else, must not be this anim! } - //Not in ANY anim? SHOULD NEVER HAPPEN - Com_Printf( "invalid anim range %d to %d, speed %4.2f\n", startFrame, endFrame, animSpeed ); + // Not in ANY anim? SHOULD NEVER HAPPEN + Com_Printf("invalid anim range %d to %d, speed %4.2f\n", startFrame, endFrame, animSpeed); return -1; } /* @@ -1922,56 +1610,50 @@ PM_TorsoAnimForFrame Returns animNumber for current frame ------------------------- */ -int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ) -{ - //Must be a valid client - if ( ent->client == NULL ) +int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame) { + // Must be a valid client + if (ent->client == NULL) return -1; - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return -1; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - for ( int animation = 0; animation < LEGS_WALKBACK1; animation++ ) - { - if ( animations[animation].firstFrame > torsoFrame ) - {//This anim starts after this frame + for (int animation = 0; animation < LEGS_WALKBACK1; animation++) { + if (animations[animation].firstFrame > torsoFrame) { // This anim starts after this frame continue; } - if ( animations[animation].firstFrame + animations[animation].numFrames < torsoFrame ) - {//This anim ends before this frame + if (animations[animation].firstFrame + animations[animation].numFrames < torsoFrame) { // This anim ends before this frame continue; } - //else, must be in this anim! + // else, must be in this anim! return animation; } - //Not in ANY torsoAnim? SHOULD NEVER HAPPEN -// assert(0); + // Not in ANY torsoAnim? SHOULD NEVER HAPPEN + // assert(0); return -1; } -qboolean PM_FinishedCurrentLegsAnim( gentity_t *self ) -{ - int junk, curFrame; - float currentFrame, animSpeed; +qboolean PM_FinishedCurrentLegsAnim(gentity_t *self) { + int junk, curFrame; + float currentFrame, animSpeed; - if ( !self->client ) - { + if (!self->client) { return qtrue; } - gi.G2API_GetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &animSpeed, NULL ); - curFrame = floor( currentFrame ); + gi.G2API_GetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, (cg.time ? cg.time : level.time), ¤tFrame, &junk, &junk, &junk, + &animSpeed, NULL); + curFrame = floor(currentFrame); - int legsAnim = self->client->ps.legsAnim; - animation_t *animations = level.knownAnimFileSets[self->client->clientInfo.animFileIndex].animations; + int legsAnim = self->client->ps.legsAnim; + animation_t *animations = level.knownAnimFileSets[self->client->clientInfo.animFileIndex].animations; - if ( curFrame >= animations[legsAnim].firstFrame + (animations[legsAnim].numFrames - 2) ) - { + if (curFrame >= animations[legsAnim].firstFrame + (animations[legsAnim].numFrames - 2)) { return qtrue; } @@ -1984,47 +1666,41 @@ PM_HasAnimation ------------------------- */ -qboolean PM_HasAnimation( gentity_t *ent, int animation ) -{ - //Must be a valid client - if ( !ent || ent->client == NULL ) +qboolean PM_HasAnimation(gentity_t *ent, int animation) { + // Must be a valid client + if (!ent || ent->client == NULL) return qfalse; - //must be a valid anim number - if ( animation < 0 || animation >= MAX_ANIMATIONS ) - { + // must be a valid anim number + if (animation < 0 || animation >= MAX_ANIMATIONS) { return qfalse; } - //Must have a file index entry - if( ValidAnimFileIndex( ent->client->clientInfo.animFileIndex ) == qfalse ) + // Must have a file index entry + if (ValidAnimFileIndex(ent->client->clientInfo.animFileIndex) == qfalse) return qfalse; animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - //No frames, no anim - if ( animations[animation].numFrames == 0 ) + // No frames, no anim + if (animations[animation].numFrames == 0) return qfalse; - //Has the sequence + // Has the sequence return qtrue; } -int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ) -{ +int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim) { int anim; int count = 0; - if ( !self ) - { + if (!self) { return Q_irand(minAnim, maxAnim); } - do - { + do { anim = Q_irand(minAnim, maxAnim); count++; - } - while ( !PM_HasAnimation( self, anim ) && count < 1000 ); + } while (!PM_HasAnimation(self, anim) && count < 1000); return anim; } @@ -2035,8 +1711,8 @@ PM_AnimLength ------------------------- */ -int PM_AnimLength( int index, animNumber_t anim ) { - if ( !ValidAnimFileIndex( index ) || (int)anim < 0 || anim >= MAX_ANIMATIONS ) { +int PM_AnimLength(int index, animNumber_t anim) { + if (!ValidAnimFileIndex(index) || (int)anim < 0 || anim >= MAX_ANIMATIONS) { return 0; } @@ -2049,27 +1725,20 @@ PM_SetLegsAnimTimer ------------------------- */ -void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ) -{ +void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time) { *legsAnimTimer = time; - if ( *legsAnimTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional + if (*legsAnimTimer < 0 && time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional *legsAnimTimer = 0; } - if ( !*legsAnimTimer && ent && Q3_TaskIDPending( ent, TID_ANIM_LOWER ) ) - {//Waiting for legsAnimTimer to complete, and it just got set to zero - if ( !Q3_TaskIDPending( ent, TID_ANIM_BOTH) ) - {//Not waiting for top - Q3_TaskIDComplete( ent, TID_ANIM_LOWER ); - } - else - {//Waiting for both to finish before complete - Q3_TaskIDClear( &ent->taskID[TID_ANIM_LOWER] );//Bottom is done, regardless - if ( !Q3_TaskIDPending( ent, TID_ANIM_UPPER) ) - {//top is done and we're done - Q3_TaskIDComplete( ent, TID_ANIM_BOTH ); + if (!*legsAnimTimer && ent && Q3_TaskIDPending(ent, TID_ANIM_LOWER)) { // Waiting for legsAnimTimer to complete, and it just got set to zero + if (!Q3_TaskIDPending(ent, TID_ANIM_BOTH)) { // Not waiting for top + Q3_TaskIDComplete(ent, TID_ANIM_LOWER); + } else { // Waiting for both to finish before complete + Q3_TaskIDClear(&ent->taskID[TID_ANIM_LOWER]); // Bottom is done, regardless + if (!Q3_TaskIDPending(ent, TID_ANIM_UPPER)) { // top is done and we're done + Q3_TaskIDComplete(ent, TID_ANIM_BOTH); } } } @@ -2081,67 +1750,46 @@ PM_SetTorsoAnimTimer ------------------------- */ -void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ) -{ +void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time) { *torsoAnimTimer = time; - if ( *torsoAnimTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional + if (*torsoAnimTimer < 0 && time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional *torsoAnimTimer = 0; } - if ( !*torsoAnimTimer && ent && Q3_TaskIDPending( ent, TID_ANIM_UPPER ) ) - {//Waiting for torsoAnimTimer to complete, and it just got set to zero - if ( !Q3_TaskIDPending( ent, TID_ANIM_BOTH) ) - {//Not waiting for bottom - Q3_TaskIDComplete( ent, TID_ANIM_UPPER ); - } - else - {//Waiting for both to finish before complete - Q3_TaskIDClear( &ent->taskID[TID_ANIM_UPPER] );//Top is done, regardless - if ( !Q3_TaskIDPending( ent, TID_ANIM_LOWER) ) - {//lower is done and we're done - Q3_TaskIDComplete( ent, TID_ANIM_BOTH ); + if (!*torsoAnimTimer && ent && Q3_TaskIDPending(ent, TID_ANIM_UPPER)) { // Waiting for torsoAnimTimer to complete, and it just got set to zero + if (!Q3_TaskIDPending(ent, TID_ANIM_BOTH)) { // Not waiting for bottom + Q3_TaskIDComplete(ent, TID_ANIM_UPPER); + } else { // Waiting for both to finish before complete + Q3_TaskIDClear(&ent->taskID[TID_ANIM_UPPER]); // Top is done, regardless + if (!Q3_TaskIDPending(ent, TID_ANIM_LOWER)) { // lower is done and we're done + Q3_TaskIDComplete(ent, TID_ANIM_BOTH); } } } } -extern qboolean PM_SpinningSaberAnim( int anim ); +extern qboolean PM_SpinningSaberAnim(int anim); extern float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS]; -void PM_SaberStartTransAnim( int saberAnimLevel, int anim, float *animSpeed, gentity_t *gent ) -{ - if ( g_saberAnimSpeed->value != 1.0f ) - { - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_CROUCHATTACKBACK1 ) - { +void PM_SaberStartTransAnim(int saberAnimLevel, int anim, float *animSpeed, gentity_t *gent) { + if (g_saberAnimSpeed->value != 1.0f) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_CROUCHATTACKBACK1) { *animSpeed *= g_saberAnimSpeed->value; } } - if ( gent && gent->NPC && gent->NPC->rank == RANK_CIVILIAN ) - {//grunt reborn - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1 ) - {//his fast attacks are slower - if ( !PM_SpinningSaberAnim( anim ) ) - { + if (gent && gent->NPC && gent->NPC->rank == RANK_CIVILIAN) { // grunt reborn + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_R1_TR_S1) { // his fast attacks are slower + if (!PM_SpinningSaberAnim(anim)) { *animSpeed *= 0.75; } return; } } - if ( ( anim >= BOTH_T1_BR__R && - anim <= BOTH_T1_BL_TL ) || - ( anim >= BOTH_T3_BR__R && - anim <= BOTH_T3_BL_TL ) || - ( anim >= BOTH_T5_BR__R && - anim <= BOTH_T5_BL_TL ) ) - { - if ( saberAnimLevel == FORCE_LEVEL_1 || saberAnimLevel == FORCE_LEVEL_5 ) - {//FIXME: should not be necc for FORCE_LEVEL_1's + if ((anim >= BOTH_T1_BR__R && anim <= BOTH_T1_BL_TL) || (anim >= BOTH_T3_BR__R && anim <= BOTH_T3_BL_TL) || + (anim >= BOTH_T5_BR__R && anim <= BOTH_T5_BL_TL)) { + if (saberAnimLevel == FORCE_LEVEL_1 || saberAnimLevel == FORCE_LEVEL_5) { // FIXME: should not be necc for FORCE_LEVEL_1's *animSpeed *= 1.5; - } - else if ( saberAnimLevel == FORCE_LEVEL_3 ) - { + } else if (saberAnimLevel == FORCE_LEVEL_3) { *animSpeed *= 0.75; } } @@ -2191,20 +1839,14 @@ void PM_SaberStartTransAnim( int anim, int entNum, int saberOffenseLevel, float return; } */ -extern qboolean player_locked; -extern qboolean MatrixMode; -float PM_GetTimeScaleMod( gentity_t *gent ) -{ - if ( g_timescale->value ) - { - if ( !MatrixMode ) - { - if ( gent && gent->s.clientNum == 0 && !player_locked && gent->client->ps.forcePowersActive&(1<value) { + if (!MatrixMode) { + if (gent && gent->s.clientNum == 0 && !player_locked && gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { return (1.0 / g_timescale->value); - } - else if ( gent && gent->client && gent->client->ps.forcePowersActive&(1<client && gent->client->ps.forcePowersActive & (1 << FP_SPEED)) { return (1.0 / g_timescale->value); } } @@ -2218,48 +1860,40 @@ PM_SetAnimFinal ------------------------- */ #define G2_DEBUG_TIMING (0) -void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, - int setAnimParts,int anim,int setAnimFlags, - int *torsoAnimTimer,int *legsAnimTimer, - gentity_t *gent,int blendTime) // default blendTime=350 +void PM_SetAnimFinal(int *torsoAnim, int *legsAnim, int setAnimParts, int anim, int setAnimFlags, int *torsoAnimTimer, int *legsAnimTimer, gentity_t *gent, + int blendTime) // default blendTime=350 { - if(!ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) - { + if (!ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) { return; } - if ( anim < 0 || anim >= MAX_ANIMATIONS ) - { - assert( 0&&"anim out of range!!!" ); + if (anim < 0 || anim >= MAX_ANIMATIONS) { + assert(0 && "anim out of range!!!"); #ifndef FINAL_BUILD - G_Error( "%s tried to play invalid anim %d", gent->NPC_type, anim ); + G_Error("%s tried to play invalid anim %d", gent->NPC_type, anim); #endif return; } animation_t *animations = level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations; - float timeScaleMod = PM_GetTimeScaleMod( gent ); - float animSpeed, oldAnimSpeed; - int actualTime = (cg.time?cg.time:level.time); + float timeScaleMod = PM_GetTimeScaleMod(gent); + float animSpeed, oldAnimSpeed; + int actualTime = (cg.time ? cg.time : level.time); - if ( gent && gent->client ) - {//lower offensive skill slows down the saber start attack animations - PM_SaberStartTransAnim( gent->client->ps.saberAnimLevel, anim, &timeScaleMod, gent ); - // PM_SaberStartTransAnim( anim, gent->s.number, gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE], &timeScaleMod ); + if (gent && gent->client) { // lower offensive skill slows down the saber start attack animations + PM_SaberStartTransAnim(gent->client->ps.saberAnimLevel, anim, &timeScaleMod, gent); + // PM_SaberStartTransAnim( anim, gent->s.number, gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE], &timeScaleMod ); } // Set torso anim - if (setAnimParts & SETANIM_TORSO) - { + if (setAnimParts & SETANIM_TORSO) { // or if a more important anim is running - if( !(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((*torsoAnimTimer > 0)||(*torsoAnimTimer == -1)) ) - { + if (!(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((*torsoAnimTimer > 0) || (*torsoAnimTimer == -1))) { goto setAnimLegs; } - if ( !PM_HasAnimation( gent, anim ) ) - { - if ( g_ICARUSDebug->integer >= 3 ) - { - //gi.Printf(S_COLOR_RED"SET_ANIM_UPPER ERROR: anim %s does not exist in this model (%s)!\n", animTable[anim].name, ((gent!=NULL&&gent->client!=NULL) ? gent->client->renderInfo.torsoModelName : "unknown") ); + if (!PM_HasAnimation(gent, anim)) { + if (g_ICARUSDebug->integer >= 3) { + // gi.Printf(S_COLOR_RED"SET_ANIM_UPPER ERROR: anim %s does not exist in this model (%s)!\n", animTable[anim].name, + // ((gent!=NULL&&gent->client!=NULL) ? gent->client->renderInfo.torsoModelName : "unknown") ); } goto setAnimLegs; } @@ -2267,21 +1901,19 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). animSpeed = oldAnimSpeed = 50.0f / animations[anim].frameLerp * timeScaleMod; - if ( gi.G2API_HaveWeGhoul2Models(gent->ghoul2) && gent->lowerLumbarBone != -1 )//gent->upperLumbarBone - {//see if we need to tell ghoul2 to play it again because of a animSpeed change - int blah; - float junk; - if (!gi.G2API_GetBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, actualTime, &junk, &blah, &blah, &blah, &oldAnimSpeed, NULL )) - { + if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2) && gent->lowerLumbarBone != -1) // gent->upperLumbarBone + { // see if we need to tell ghoul2 to play it again because of a animSpeed change + int blah; + float junk; + if (!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, actualTime, &junk, &blah, &blah, &blah, &oldAnimSpeed, + NULL)) { animSpeed = oldAnimSpeed; } } - if ( oldAnimSpeed == animSpeed ) - {//animSpeed has not changed + if (oldAnimSpeed == animSpeed) { // animSpeed has not changed // Don't reset if it's already running the anim - if( !(setAnimFlags & SETANIM_FLAG_RESTART) && *torsoAnim == anim ) - { + if (!(setAnimFlags & SETANIM_FLAG_RESTART) && *torsoAnim == anim) { goto setAnimLegs; } } @@ -2289,225 +1921,162 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, *torsoAnim = anim; // lets try and run a ghoul2 animation if we have a ghoul2 model on this guy - if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) - { - if ( gent->lowerLumbarBone != -1 )//gent->upperLumbarBone + if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) { + if (gent->lowerLumbarBone != -1) // gent->upperLumbarBone { int startFrame, endFrame; - if ( cg_debugAnim.integer == 3 || (!gent->s.number && cg_debugAnim.integer == 1) || (gent->s.number && cg_debugAnim.integer == 2) ) - { - Com_Printf("Time=%d: %s TORSO anim %d %s\n", actualTime, gent->targetname, anim, animTable[anim].name ); + if (cg_debugAnim.integer == 3 || (!gent->s.number && cg_debugAnim.integer == 1) || (gent->s.number && cg_debugAnim.integer == 2)) { + Com_Printf("Time=%d: %s TORSO anim %d %s\n", actualTime, gent->targetname, anim, animTable[anim].name); } - // we have a ghoul2 model - animate it? // don't bother if the animation is missing - if (!animations[anim].numFrames) - { + if (!animations[anim].numFrames) { // remove it if we already have an animation on this bone - if (gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "lower_lumbar", &startFrame, &endFrame))//"upper_lumbar" + if (gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "lower_lumbar", &startFrame, &endFrame)) //"upper_lumbar" { #if G2_DEBUG_TIMING - Com_Printf( "tstop %d\n", cg.time ); + Com_Printf("tstop %d\n", cg.time); #endif - gi.G2API_StopBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->lowerLumbarBone );//gent->upperLumbarBone - if ( gent->motionBone != -1 ) - { - gi.G2API_StopBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->motionBone ); + gi.G2API_StopBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone); // gent->upperLumbarBone + if (gent->motionBone != -1) { + gi.G2API_StopBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone); } } - } - else - { + } else { // before we do this, lets see if this animation is one the legs are already playing? - int animFlags = BONE_ANIM_OVERRIDE_FREEZE; + int animFlags = BONE_ANIM_OVERRIDE_FREEZE; - if (animations[anim].loopFrames != -1) - { + if (animations[anim].loopFrames != -1) { animFlags = BONE_ANIM_OVERRIDE_LOOP; } - //HACKHACKHACK - need some better way of not lerping between something like a spin/flip and a death, etc. - if ( blendTime > 0 ) - { + // HACKHACKHACK - need some better way of not lerping between something like a spin/flip and a death, etc. + if (blendTime > 0) { animFlags |= BONE_ANIM_BLEND; } - //HACKHACKHACK - //qboolean animatingLegs = gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame); - float currentFrame, legAnimSpeed, firstFrame, lastFrame; - int flags; - qboolean animatingLegs = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], - gent->rootBone, actualTime, ¤tFrame, - &startFrame, &endFrame, &flags, &legAnimSpeed, NULL ); - if ( g_synchSplitAnims->integer - && !(setAnimFlags & SETANIM_FLAG_RESTART) - && animatingLegs - && (animations[anim].firstFrame == startFrame) - && (legAnimSpeed == animSpeed )//|| oldAnimSpeed != animSpeed) - && (((animations[anim].numFrames ) + animations[anim].firstFrame) == endFrame)) - {//if we're playing this *exact* anim (speed check should fix problems with anims that play other anims backwards) on the legs already andwe're not restarting the anim, then match the legs' frame - if ( 0 ) - {//just stop it - gi.G2API_StopBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->lowerLumbarBone );//gent->upperLumbarBone - gi.G2API_StopBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->motionBone );//gent->upperLumbarBone - } - else - {//try to synch it + // HACKHACKHACK + // qboolean animatingLegs = gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame); + float currentFrame, legAnimSpeed, firstFrame, lastFrame; + int flags; + qboolean animatingLegs = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, actualTime, ¤tFrame, &startFrame, + &endFrame, &flags, &legAnimSpeed, NULL); + if (g_synchSplitAnims->integer && !(setAnimFlags & SETANIM_FLAG_RESTART) && animatingLegs && (animations[anim].firstFrame == startFrame) && + (legAnimSpeed == animSpeed) //|| oldAnimSpeed != animSpeed) + && (((animations[anim].numFrames) + animations[anim].firstFrame) == + endFrame)) { // if we're playing this *exact* anim (speed check should fix problems with anims that play other anims backwards) on + // the legs already andwe're not restarting the anim, then match the legs' frame + if (0) { // just stop it + gi.G2API_StopBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone); // gent->upperLumbarBone + gi.G2API_StopBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone); // gent->upperLumbarBone + } else { // try to synch it // assert((currentFrame <=endFrame) && (currentFrame>=startFrame)); - // yes, its the same animation, so work out where we are in the leg anim, and blend us +// yes, its the same animation, so work out where we are in the leg anim, and blend us #if G2_DEBUG_TIMING - Com_Printf("tlegb %d %d %d %4.2f %4.2f %d\n", - actualTime, - animations[anim].firstFrame, - (animations[anim].numFrames )+ animations[anim].firstFrame, - legAnimSpeed, - currentFrame, - blendTime); + Com_Printf("tlegb %d %d %d %4.2f %4.2f %d\n", actualTime, animations[anim].firstFrame, + (animations[anim].numFrames) + animations[anim].firstFrame, legAnimSpeed, currentFrame, blendTime); #endif - if ( oldAnimSpeed != animSpeed - && ((oldAnimSpeed>0&&animSpeed>0) || (oldAnimSpeed<0&&animSpeed<0)) ) - {//match the new speed, actually + if (oldAnimSpeed != animSpeed && + ((oldAnimSpeed > 0 && animSpeed > 0) || (oldAnimSpeed < 0 && animSpeed < 0))) { // match the new speed, actually legAnimSpeed = animSpeed; } - if ( legAnimSpeed < 0 ) - {//play anim backwards - lastFrame = animations[anim].firstFrame;// -1; - firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame;// -1) + animations[anim].firstFrame; - } - else - { + if (legAnimSpeed < 0) { // play anim backwards + lastFrame = animations[anim].firstFrame; // -1; + firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame; // -1) + animations[anim].firstFrame; + } else { firstFrame = animations[anim].firstFrame; - lastFrame = (animations[anim].numFrames ) + animations[anim].firstFrame; + lastFrame = (animations[anim].numFrames) + animations[anim].firstFrame; } - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, //gent->upperLumbarBone - firstFrame, lastFrame, animFlags, legAnimSpeed, - actualTime, currentFrame, blendTime); - if ( gent->motionBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, - firstFrame, lastFrame, animFlags, legAnimSpeed, - actualTime, currentFrame, blendTime); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, // gent->upperLumbarBone + firstFrame, lastFrame, animFlags, legAnimSpeed, actualTime, currentFrame, blendTime); + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, firstFrame, lastFrame, animFlags, legAnimSpeed, + actualTime, currentFrame, blendTime); } } - } - else - {// no, we aren't the same anim as the legs are running, so just run it. + } else { // no, we aren't the same anim as the legs are running, so just run it. // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). - int firstFrame; - int lastFrame; - if ( animSpeed < 0 ) - {//play anim backwards - lastFrame = animations[anim].firstFrame;// -1; - firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame;;// -1) + animations[anim].firstFrame; - } - else - { + int firstFrame; + int lastFrame; + if (animSpeed < 0) { // play anim backwards + lastFrame = animations[anim].firstFrame; // -1; + firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame; + ; // -1) + animations[anim].firstFrame; + } else { firstFrame = animations[anim].firstFrame; lastFrame = (animations[anim].numFrames) + animations[anim].firstFrame; } // first decide if we are doing an animation on the torso already - qboolean animatingTorso = gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "lower_lumbar", &startFrame, &endFrame);//"upper_lumbar" + qboolean animatingTorso = + gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "lower_lumbar", &startFrame, &endFrame); //"upper_lumbar" // lets see if a) we are already animating and b) we aren't going to do the same animation again - if (animatingTorso && ( (firstFrame != startFrame) || (lastFrame != endFrame) ) ) - { + if (animatingTorso && ((firstFrame != startFrame) || (lastFrame != endFrame))) { #if G2_DEBUG_TIMING - Com_Printf("trsob %d %d %d %4.2f %4.2f %d\n", - actualTime, - firstFrame, - lastFrame, - animSpeed, - -1, - blendTime); + Com_Printf("trsob %d %d %d %4.2f %4.2f %d\n", actualTime, firstFrame, lastFrame, animSpeed, -1, blendTime); #endif - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, //gent->upperLumbarBone - firstFrame, lastFrame, animFlags, - animSpeed, actualTime, -1, blendTime); - - if ( gent->motionBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, - firstFrame, lastFrame, animFlags, - animSpeed, actualTime, -1, blendTime); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, // gent->upperLumbarBone + firstFrame, lastFrame, animFlags, animSpeed, actualTime, -1, blendTime); + + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, firstFrame, lastFrame, animFlags, animSpeed, + actualTime, -1, blendTime); } - } - else - { + } else { // no, ok, no blend then because we are either looping on the same anim, or starting from no anim #if G2_DEBUG_TIMING - Com_Printf("trson %d %d %d %4.2f %4.2f %d\n", - actualTime, - firstFrame, - lastFrame, - animSpeed, - -1, - -1); + Com_Printf("trson %d %d %d %4.2f %4.2f %d\n", actualTime, firstFrame, lastFrame, animSpeed, -1, -1); #endif - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, //gent->upperLumbarBone - firstFrame, lastFrame, animFlags&~BONE_ANIM_BLEND, - animSpeed, cg.time, -1, -1); - if ( gent->motionBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, - firstFrame, lastFrame, animFlags&~BONE_ANIM_BLEND, - animSpeed, cg.time, -1, -1); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, // gent->upperLumbarBone + firstFrame, lastFrame, animFlags & ~BONE_ANIM_BLEND, animSpeed, cg.time, -1, -1); + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, firstFrame, lastFrame, + animFlags & ~BONE_ANIM_BLEND, animSpeed, cg.time, -1, -1); } } } } } } -/* -#ifdef _DEBUG - gi.Printf(S_COLOR_GREEN"SET_ANIM_UPPER: %s (%s)\n", animTable[anim].name, gent->targetname ); -#endif -*/ - if ((gent->client) && (setAnimFlags & SETANIM_FLAG_HOLD)) - {//FIXME: allow to set a specific time? - if ( timeScaleMod != 1.0 ) - { - PM_SetTorsoAnimTimer( gent, torsoAnimTimer, (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp) / timeScaleMod ); - } - else if ( setAnimFlags & SETANIM_FLAG_HOLDLESS ) - { // Make sure to only wait in full 1/20 sec server frame intervals. + /* + #ifdef _DEBUG + gi.Printf(S_COLOR_GREEN"SET_ANIM_UPPER: %s (%s)\n", animTable[anim].name, gent->targetname ); + #endif + */ + if ((gent->client) && (setAnimFlags & SETANIM_FLAG_HOLD)) { // FIXME: allow to set a specific time? + if (timeScaleMod != 1.0) { + PM_SetTorsoAnimTimer(gent, torsoAnimTimer, (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp) / timeScaleMod); + } else if (setAnimFlags & SETANIM_FLAG_HOLDLESS) { // Make sure to only wait in full 1/20 sec server frame intervals. int dur; - dur = (animations[anim].numFrames -1) * fabs((double)animations[anim].frameLerp); - //dur = ((int)(dur/50.0)) * 50; - //dur -= blendTime; - if (dur > 1) - { - PM_SetTorsoAnimTimer( gent, torsoAnimTimer, dur-1 ); + dur = (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp); + // dur = ((int)(dur/50.0)) * 50; + // dur -= blendTime; + if (dur > 1) { + PM_SetTorsoAnimTimer(gent, torsoAnimTimer, dur - 1); + } else { + PM_SetTorsoAnimTimer(gent, torsoAnimTimer, fabs((double)animations[anim].frameLerp)); } - else - { - PM_SetTorsoAnimTimer( gent, torsoAnimTimer, fabs((double)animations[anim].frameLerp) ); - } - } - else - { - PM_SetTorsoAnimTimer( gent, torsoAnimTimer, (animations[anim].numFrames ) * fabs((double)animations[anim].frameLerp) ); + } else { + PM_SetTorsoAnimTimer(gent, torsoAnimTimer, (animations[anim].numFrames) * fabs((double)animations[anim].frameLerp)); } } } setAnimLegs: // Set legs anim - if (setAnimParts & SETANIM_LEGS) - { + if (setAnimParts & SETANIM_LEGS) { // or if a more important anim is running - if( !(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((*legsAnimTimer > 0)||(*legsAnimTimer == -1)) ) - { + if (!(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((*legsAnimTimer > 0) || (*legsAnimTimer == -1))) { goto setAnimDone; } - if ( !PM_HasAnimation( gent, anim ) ) - { - if ( g_ICARUSDebug->integer >= 3 ) - { - //gi.Printf(S_COLOR_RED"SET_ANIM_LOWER ERROR: anim %s does not exist in this model (%s)!\n", animTable[anim].name, ((gent!=NULL&&gent->client!=NULL) ? gent->client->renderInfo.legsModelName : "unknown") ); + if (!PM_HasAnimation(gent, anim)) { + if (g_ICARUSDebug->integer >= 3) { + // gi.Printf(S_COLOR_RED"SET_ANIM_LOWER ERROR: anim %s does not exist in this model (%s)!\n", animTable[anim].name, + // ((gent!=NULL&&gent->client!=NULL) ? gent->client->renderInfo.legsModelName : "unknown") ); } goto setAnimDone; } @@ -2515,21 +2084,17 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). animSpeed = oldAnimSpeed = 50.0f / animations[anim].frameLerp * timeScaleMod; - if ( gi.G2API_HaveWeGhoul2Models(gent->ghoul2) && gent->rootBone != -1 ) - {//see if we need to tell ghoul2 to play it again because of a animSpeed change - int blah; - float junk; - if (!gi.G2API_GetBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->rootBone, actualTime, &junk, &blah, &blah, &blah, &oldAnimSpeed, NULL )) - { + if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2) && gent->rootBone != -1) { // see if we need to tell ghoul2 to play it again because of a animSpeed change + int blah; + float junk; + if (!gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, actualTime, &junk, &blah, &blah, &blah, &oldAnimSpeed, NULL)) { animSpeed = oldAnimSpeed; } } - if ( oldAnimSpeed == animSpeed ) - {//animSpeed has not changed + if (oldAnimSpeed == animSpeed) { // animSpeed has not changed // Don't reset if it's already running the anim - if( !(setAnimFlags & SETANIM_FLAG_RESTART) && *legsAnim == anim ) - { + if (!(setAnimFlags & SETANIM_FLAG_RESTART) && *legsAnim == anim) { goto setAnimDone; } } @@ -2537,174 +2102,122 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, *legsAnim = anim; // lets try and run a ghoul2 animation if we have a ghoul2 model on this guy - if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) - { + if (gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) { int startFrame, endFrame; - if ( cg_debugAnim.integer == 3 || (!gent->s.number && cg_debugAnim.integer == 1) || (gent->s.number && cg_debugAnim.integer == 2) ) - { - Com_Printf("Time=%d: %s LEGS anim %d %s\n", actualTime, gent->targetname, anim, animTable[anim].name ); + if (cg_debugAnim.integer == 3 || (!gent->s.number && cg_debugAnim.integer == 1) || (gent->s.number && cg_debugAnim.integer == 2)) { + Com_Printf("Time=%d: %s LEGS anim %d %s\n", actualTime, gent->targetname, anim, animTable[anim].name); } - int animFlags = BONE_ANIM_OVERRIDE_FREEZE; + int animFlags = BONE_ANIM_OVERRIDE_FREEZE; - if (animations[anim].loopFrames != -1) - { + if (animations[anim].loopFrames != -1) { animFlags = BONE_ANIM_OVERRIDE_LOOP; } - //HACKHACKHACK - need some better way of not lerping between something like a spin/flip and a death, etc. - if ( blendTime > 0 ) - { + // HACKHACKHACK - need some better way of not lerping between something like a spin/flip and a death, etc. + if (blendTime > 0) { animFlags |= BONE_ANIM_BLEND; } - //HACKHACKHACK + // HACKHACKHACK // don't bother if the animation is missing - if (!animations[anim].numFrames) - { + if (!animations[anim].numFrames) { // remove it if we already have an animation on this bone - if (gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame)) - { + if (gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame)) { #if G2_DEBUG_TIMING - Com_Printf( "lstop %d\n", cg.time ); + Com_Printf("lstop %d\n", cg.time); #endif - gi.G2API_StopBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->rootBone ); + gi.G2API_StopBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone); } - } - else - { - int firstFrame; - int lastFrame; - if ( animSpeed < 0 ) - {//play anim backwards - lastFrame = animations[anim].firstFrame;// -1; - firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame;// -1) + animations[anim].firstFrame; - } - else - { + } else { + int firstFrame; + int lastFrame; + if (animSpeed < 0) { // play anim backwards + lastFrame = animations[anim].firstFrame; // -1; + firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame; // -1) + animations[anim].firstFrame; + } else { firstFrame = animations[anim].firstFrame; - lastFrame = (animations[anim].numFrames ) + animations[anim].firstFrame; + lastFrame = (animations[anim].numFrames) + animations[anim].firstFrame; } - //HACKHACKHACK - //qboolean animatingTorso = gi.G2API_GetAnimRangeIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, &startFrame, &endFrame); - float currentFrame, torsoAnimSpeed; - int flags; - qboolean animatingTorso = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone,actualTime, ¤tFrame, &startFrame, &endFrame, &flags, &torsoAnimSpeed, NULL); - if ( g_synchSplitAnims->integer - && !(setAnimFlags & SETANIM_FLAG_RESTART) - && animatingTorso - && (torsoAnimSpeed == animSpeed)//|| oldAnimSpeed != animSpeed) - && (animations[anim].firstFrame == startFrame) - && (((animations[anim].numFrames ) + animations[anim].firstFrame) == endFrame)) - {//if we're playing this *exact* anim on the torso already and we're not restarting the anim, then match the torso's frame - //try to synch it + // HACKHACKHACK + // qboolean animatingTorso = gi.G2API_GetAnimRangeIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, &startFrame, &endFrame); + float currentFrame, torsoAnimSpeed; + int flags; + qboolean animatingTorso = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, actualTime, ¤tFrame, + &startFrame, &endFrame, &flags, &torsoAnimSpeed, NULL); + if (g_synchSplitAnims->integer && !(setAnimFlags & SETANIM_FLAG_RESTART) && animatingTorso && + (torsoAnimSpeed == animSpeed) //|| oldAnimSpeed != animSpeed) + && (animations[anim].firstFrame == startFrame) && + (((animations[anim].numFrames) + animations[anim].firstFrame) == + endFrame)) { // if we're playing this *exact* anim on the torso already and we're not restarting the anim, then match the torso's frame + // try to synch it // assert((currentFrame <=endFrame) && (currentFrame>=startFrame)); - // yes, its the same animation, so work out where we are in the torso anim, and blend us +// yes, its the same animation, so work out where we are in the torso anim, and blend us #if G2_DEBUG_TIMING - Com_Printf("ltrsb %d %d %d %4.2f %4.2f %d\n", - actualTime, - animations[anim].firstFrame, - (animations[anim].numFrames )+ animations[anim].firstFrame, - legAnimSpeed, - currentFrame, - blendTime); + Com_Printf("ltrsb %d %d %d %4.2f %4.2f %d\n", actualTime, animations[anim].firstFrame, + (animations[anim].numFrames) + animations[anim].firstFrame, legAnimSpeed, currentFrame, blendTime); #endif - if ( oldAnimSpeed != animSpeed - && ((oldAnimSpeed>0&&animSpeed>0) || (oldAnimSpeed<0&&animSpeed<0)) ) - {//match the new speed, actually + if (oldAnimSpeed != animSpeed && + ((oldAnimSpeed > 0 && animSpeed > 0) || (oldAnimSpeed < 0 && animSpeed < 0))) { // match the new speed, actually torsoAnimSpeed = animSpeed; } - if ( torsoAnimSpeed < 0 ) - {//play anim backwards - lastFrame = animations[anim].firstFrame;// -1; - firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame;// -1) + animations[anim].firstFrame; - } - else - { + if (torsoAnimSpeed < 0) { // play anim backwards + lastFrame = animations[anim].firstFrame; // -1; + firstFrame = (animations[anim].numFrames) + animations[anim].firstFrame; // -1) + animations[anim].firstFrame; + } else { firstFrame = animations[anim].firstFrame; - lastFrame = (animations[anim].numFrames ) + animations[anim].firstFrame; + lastFrame = (animations[anim].numFrames) + animations[anim].firstFrame; } - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, - firstFrame, lastFrame, animFlags, torsoAnimSpeed, - actualTime, currentFrame, blendTime ); - } - else - {// no, we aren't the same anim as the torso is running, so just run it. + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, firstFrame, lastFrame, animFlags, torsoAnimSpeed, actualTime, + currentFrame, blendTime); + } else { // no, we aren't the same anim as the torso is running, so just run it. // before we do this, lets see if this animation is one the legs are already playing? - //qboolean animatingLegs = gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame); - float currentFrame, legAnimSpeed; - int flags; - qboolean animatingLegs = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], - gent->rootBone, actualTime, ¤tFrame, - &startFrame, &endFrame, &flags, &legAnimSpeed, NULL ); + // qboolean animatingLegs = gi.G2API_GetAnimRange(&gent->ghoul2[gent->playerModel], "model_root", &startFrame, &endFrame); + float currentFrame, legAnimSpeed; + int flags; + qboolean animatingLegs = gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, actualTime, ¤tFrame, &startFrame, + &endFrame, &flags, &legAnimSpeed, NULL); // lets see if a) we are already animating and b) we aren't going to do the same animation again - if (animatingLegs - && ( (legAnimSpeed!=animSpeed) || (firstFrame != startFrame) || (lastFrame != endFrame) ) ) - { + if (animatingLegs && ((legAnimSpeed != animSpeed) || (firstFrame != startFrame) || (lastFrame != endFrame))) { #if G2_DEBUG_TIMING - Com_Printf("legsb %d %d %d %4.2f %4.2f %d\n", - actualTime, - firstFrame, - lastFrame, - animSpeed, - -1, - blendTime); + Com_Printf("legsb %d %d %d %4.2f %4.2f %d\n", actualTime, firstFrame, lastFrame, animSpeed, -1, blendTime); #endif - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, - firstFrame, lastFrame, animFlags, - animSpeed, actualTime, -1, blendTime); - } - else - { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, firstFrame, lastFrame, animFlags, animSpeed, actualTime, -1, + blendTime); + } else { // no, ok, no blend then because we are either looping on the same anim, or starting from no anim #if G2_DEBUG_TIMING - Com_Printf("legsn %d %d %d %4.2f %4.2f %d\n", - actualTime, - firstFrame, - lastFrame, - animSpeed, - -1, - -1); + Com_Printf("legsn %d %d %d %4.2f %4.2f %d\n", actualTime, firstFrame, lastFrame, animSpeed, -1, -1); #endif - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, - firstFrame, lastFrame, animFlags&~BONE_ANIM_BLEND, - animSpeed, cg.time, -1, -1); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, firstFrame, lastFrame, animFlags & ~BONE_ANIM_BLEND, + animSpeed, cg.time, -1, -1); } } } } -/* -#ifdef _DEBUG - gi.Printf(S_COLOR_GREEN"SET_ANIM_LOWER: %s (%s)\n", animTable[anim].name, gent->targetname ); -#endif -*/ - if ((gent->client) && (setAnimFlags & SETANIM_FLAG_HOLD)) - {//FIXME: allow to set a specific time? - if ( timeScaleMod != 1.0 ) - { - PM_SetLegsAnimTimer( gent, legsAnimTimer, (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp) / timeScaleMod ); - } - else if ( setAnimFlags & SETANIM_FLAG_HOLDLESS ) - { // Make sure to only wait in full 1/20 sec server frame intervals. + /* + #ifdef _DEBUG + gi.Printf(S_COLOR_GREEN"SET_ANIM_LOWER: %s (%s)\n", animTable[anim].name, gent->targetname ); + #endif + */ + if ((gent->client) && (setAnimFlags & SETANIM_FLAG_HOLD)) { // FIXME: allow to set a specific time? + if (timeScaleMod != 1.0) { + PM_SetLegsAnimTimer(gent, legsAnimTimer, (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp) / timeScaleMod); + } else if (setAnimFlags & SETANIM_FLAG_HOLDLESS) { // Make sure to only wait in full 1/20 sec server frame intervals. int dur; - dur = (animations[anim].numFrames -1) * fabs((double)animations[anim].frameLerp); - //dur = ((int)(dur/50.0)) * 50; - //dur -= blendTime; - if (dur > 1) - { - PM_SetLegsAnimTimer( gent, legsAnimTimer, dur-1 ); - } - else - { - PM_SetLegsAnimTimer( gent, legsAnimTimer, fabs((double)animations[anim].frameLerp) ); + dur = (animations[anim].numFrames - 1) * fabs((double)animations[anim].frameLerp); + // dur = ((int)(dur/50.0)) * 50; + // dur -= blendTime; + if (dur > 1) { + PM_SetLegsAnimTimer(gent, legsAnimTimer, dur - 1); + } else { + PM_SetLegsAnimTimer(gent, legsAnimTimer, fabs((double)animations[anim].frameLerp)); } - } - else - { - PM_SetLegsAnimTimer( gent, legsAnimTimer, (animations[anim].numFrames ) * fabs((double)animations[anim].frameLerp) ); + } else { + PM_SetLegsAnimTimer(gent, legsAnimTimer, (animations[anim].numFrames) * fabs((double)animations[anim].frameLerp)); } } } @@ -2713,41 +2226,35 @@ void PM_SetAnimFinal(int *torsoAnim,int *legsAnim, return; } -void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags, int blendTime) -{ // FIXME : once torsoAnim and legsAnim are in the same structure for NPC and Players +void PM_SetAnim(pmove_t *pm, int setAnimParts, int anim, int setAnimFlags, + int blendTime) { // FIXME : once torsoAnim and legsAnim are in the same structure for NPC and Players // rename PM_SetAnimFinal to PM_SetAnim and have both NPC and Players call PM_SetAnim - if ( pm->ps->pm_type >= PM_DEAD ) - {//FIXME: sometimes we'll want to set anims when your dead... twitches, impacts, etc. + if (pm->ps->pm_type >= PM_DEAD) { // FIXME: sometimes we'll want to set anims when your dead... twitches, impacts, etc. return; } - if ( pm->gent == NULL ) - { + if (pm->gent == NULL) { return; } - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { -// pm->ps->animationTimer = 0; + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + // pm->ps->animationTimer = 0; - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->torsoAnim != anim ) - { - PM_SetTorsoAnimTimer( pm->gent, &pm->ps->torsoAnimTimer, 0 ); + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->torsoAnim != anim) { + PM_SetTorsoAnimTimer(pm->gent, &pm->ps->torsoAnimTimer, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->legsAnim != anim ) - { - PM_SetLegsAnimTimer( pm->gent, &pm->ps->legsAnimTimer, 0 ); + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || pm->ps->legsAnim != anim) { + PM_SetLegsAnimTimer(pm->gent, &pm->ps->legsAnimTimer, 0); } } } - PM_SetAnimFinal(&pm->ps->torsoAnim,&pm->ps->legsAnim,setAnimParts,anim,setAnimFlags,&pm->ps->torsoAnimTimer,&pm->ps->legsAnimTimer,&g_entities[pm->ps->clientNum],blendTime);//was pm->gent + PM_SetAnimFinal(&pm->ps->torsoAnim, &pm->ps->legsAnim, setAnimParts, anim, setAnimFlags, &pm->ps->torsoAnimTimer, &pm->ps->legsAnimTimer, + &g_entities[pm->ps->clientNum], blendTime); // was pm->gent } /* @@ -2756,126 +2263,80 @@ PM_TorsoAnimLightsaber ------------------------- */ - // Note that this function is intended to set the animation for the player, but // only does idle-ish anims. Anything that has a timer associated, such as attacks and blocks, // are set by PM_WeaponLightsaber() -extern qboolean PM_LandingAnim( int anim ); -extern qboolean PM_JumpingAnim( int anim ); -qboolean PM_InCartwheel( int anim ); -void PM_TorsoAnimLightsaber() -{ +extern qboolean PM_LandingAnim(int anim); +extern qboolean PM_JumpingAnim(int anim); +qboolean PM_InCartwheel(int anim); +void PM_TorsoAnimLightsaber() { // ********************************************************* // WEAPON_READY // ********************************************************* - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->forcePowersActive & (1 << FP_GRIP) && pm->ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->forcePowersActive & (1 << FP_LIGHTNING) && pm->ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if ( pm->ps->saberActive - && pm->ps->saberLength < 3 - && !(pm->ps->saberEventFlags&SEF_HITWALL) - && pm->ps->weaponstate == WEAPON_RAISING ) - { + if (pm->ps->saberActive && pm->ps->saberLength < 3 && !(pm->ps->saberEventFlags & SEF_HITWALL) && pm->ps->weaponstate == WEAPON_RAISING) { PM_SetSaberMove(LS_DRAW); return; - } - else if ( !pm->ps->saberActive && pm->ps->saberLength ) - { + } else if (!pm->ps->saberActive && pm->ps->saberLength) { PM_SetSaberMove(LS_PUTAWAY); return; } - if (pm->ps->weaponTime > 0) - { // weapon is already busy. + if (pm->ps->weaponTime > 0) { // weapon is already busy. return; } - if ( pm->ps->weaponstate == WEAPON_READY || - pm->ps->weaponstate == WEAPON_CHARGING || - pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { - if ( pm->ps->weapon == WP_SABER && pm->ps->saberLength ) - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + if (pm->ps->weaponstate == WEAPON_READY || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) { + if (pm->ps->weapon == WP_SABER && pm->ps->saberLength) { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetSaberMove(LS_READY); } - else - { - PM_SetSaberMove( LS_READY ); - } - } - else if( pm->ps->legsAnim == BOTH_RUN1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_RUN2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_WALK2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0 )//player falls through + } else if (pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0) // player falls through { //??? Why nothing? What if you were running??? - //PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_JUMP1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_JUMP1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_JUMP1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_JUMP1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else - {//Used to default to both_stand1 which is an arms-down anim -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 + } else { // Used to default to both_stand1 which is an arms-down anim + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 // Select the next proper pose for the lightsaber assuming that there are no attacks. - if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); - } - else - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( !pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { + } else { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || + PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (!pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { PM_SetSaberMove(LS_READY); } } @@ -2887,114 +2348,74 @@ void PM_TorsoAnimLightsaber() // WEAPON_IDLE // ********************************************************* - else if ( pm->ps->weaponstate == WEAPON_IDLE ) - { - if( pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_LOOKAROUND1,SETANIM_FLAG_NORMAL); + else if (pm->ps->weaponstate == WEAPON_IDLE) { + if (pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_GUARD_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_IDLE1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_GUARD_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND1IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE2 - || pm->ps->legsAnim == BOTH_STAND3IDLE1 - || pm->ps->legsAnim == BOTH_STAND4IDLE1 - || pm->ps->legsAnim == BOTH_STAND5IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND1IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE2 || + pm->ps->legsAnim == BOTH_STAND3IDLE1 || pm->ps->legsAnim == BOTH_STAND4IDLE1 || pm->ps->legsAnim == BOTH_STAND5IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND2TO4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2TO4,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND2TO4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2TO4, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND4TO2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4TO2,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4TO2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4TO2, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else - { -// This is now set in SetSaberMove. + } else { + // This is now set in SetSaberMove. // Idle for Lightsaber - if ( pm->gent && pm->gent->client ) - { -// pm->gent->client->saberTrail.inAction = qfalse; + if (pm->gent && pm->gent->client) { + // pm->gent->client->saberTrail.inAction = qfalse; } qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->saberInFlight && saberInAir ) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->saberInFlight && saberInAir) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - {//saber is on + } else { // saber is on // Idle for Lightsaber - if ( pm->gent && pm->gent->client ) - { + if (pm->gent && pm->gent->client) { pm->gent->client->saberTrail.inAction = qfalse; } // Idle for idle/ready Lightsaber -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONIDLE1 + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONIDLE1 // Select the proper idle Lightsaber attack move from the chart. - if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_READY && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); - } - else - { - if ( PM_JumpingAnim( pm->ps->legsAnim ) - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_InCartwheel( pm->ps->legsAnim ) - || PM_FlippingAnim( pm->ps->legsAnim )) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( !pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - if ( PM_RunningAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { + } else { + if (PM_JumpingAnim(pm->ps->legsAnim) || PM_LandingAnim(pm->ps->legsAnim) || PM_InCartwheel(pm->ps->legsAnim) || + PM_FlippingAnim(pm->ps->legsAnim)) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (!pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + if (PM_RunningAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { PM_SetSaberMove(LS_READY); } } @@ -3005,119 +2426,91 @@ void PM_TorsoAnimLightsaber() } } - /* ------------------------- PM_TorsoAnimation ------------------------- */ -void PM_TorsoAnimation( void ) -{//FIXME: Write a much smarter and more appropriate anim picking routine logic... -// int oldAnim; - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown +void PM_TorsoAnimation(void) { // FIXME: Write a much smarter and more appropriate anim picking routine logic... + // int oldAnim; + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return; } - if( pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags & SCF_FORCED_MARCH) ) - { + if (pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags & SCF_FORCED_MARCH)) { return; } - if(pm->gent != NULL && pm->gent->client) - { + if (pm->gent != NULL && pm->gent->client) { pm->gent->client->renderInfo.torsoFpsMod = 1.0f; } - if ( pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL + if (pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL return; } - if ( pm->ps->taunting > level.time ) - { - if ( PM_HasAnimation( pm->gent, BOTH_GESTURE1 ) ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GESTURE1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL + if (pm->ps->taunting > level.time) { + if (PM_HasAnimation(pm->gent, BOTH_GESTURE1)) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GESTURE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL pm->gent->client->saberTrail.inAction = qtrue; pm->gent->client->saberTrail.duration = 100; - //FIXME: will this reset? - //FIXME: force-control (yellow glow) effect on hand and saber? - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE1,SETANIM_FLAG_NORMAL); + // FIXME: will this reset? + // FIXME: force-control (yellow glow) effect on hand and saber? + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE1, SETANIM_FLAG_NORMAL); } return; } - if (pm->ps->weapon == WP_SABER ) // WP_LIGHTSABER + if (pm->ps->weapon == WP_SABER) // WP_LIGHTSABER { - if ( pm->ps->saberLength > 0 && !pm->ps->saberInFlight ) - { + if (pm->ps->saberLength > 0 && !pm->ps->saberInFlight) { PM_TorsoAnimLightsaber(); - } - else - { - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + if (pm->ps->forcePowersActive & (1 << FP_GRIP) && pm->ps->forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } - if ( pm->ps->forcePowersActive&(1<ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//holding an enemy aloft with force-grip - //PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->forcePowersActive & (1 << FP_LIGHTNING) && + pm->ps->forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // holding an enemy aloft with force-grip + // PM_SetAnim( pm, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); return; } qboolean saberInAir = qtrue; - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry PM_TorsoAnimLightsaber(); return; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } - if ( pm->ps->saberInFlight && saberInAir ) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->saberInFlight && saberInAir) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - if ( PM_InSlopeAnim( pm->ps->legsAnim ) ) - {//HMM... this probably breaks the saber putaway and select anims - if ( pm->ps->saberLength > 0 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else - { - if ( !pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else { + if (PM_InSlopeAnim(pm->ps->legsAnim)) { // HMM... this probably breaks the saber putaway and select anims + if (pm->ps->saberLength > 0) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); + } + } else { + if (!pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); } } } @@ -3125,83 +2518,48 @@ void PM_TorsoAnimation( void ) return; } - qboolean weaponBusy = qfalse; - if ( pm->ps->weapon == WP_NONE ) - { + if (pm->ps->weapon == WP_NONE) { weaponBusy = qfalse; - } - else if ( pm->ps->weaponstate == WEAPON_FIRING || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + } else if (pm->ps->weaponstate == WEAPON_FIRING || pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) { weaponBusy = qtrue; - } - else if ( pm->ps->lastShotTime > level.time - 3000 ) - { + } else if (pm->ps->lastShotTime > level.time - 3000) { weaponBusy = qtrue; - } - else if ( pm->ps->weaponTime ) - { + } else if (pm->ps->weaponTime) { weaponBusy = qtrue; - } - else if ( pm->gent && pm->gent->client->fireDelay > 0 ) - { + } else if (pm->gent && pm->gent->client->fireDelay > 0) { weaponBusy = qtrue; - } - else if ( !pm->ps->clientNum && cg.zoomTime > cg.time - 5000 ) - {//if we used binoculars recently, aim weapon + } else if (!pm->ps->clientNum && cg.zoomTime > cg.time - 5000) { // if we used binoculars recently, aim weapon weaponBusy = qtrue; pm->ps->weaponstate = WEAPON_IDLE; - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - {//ducking is considered on alert... plus looks stupid to have arms hanging down when crouched + } else if (pm->ps->pm_flags & PMF_DUCKED) { // ducking is considered on alert... plus looks stupid to have arms hanging down when crouched weaponBusy = qtrue; } - if ( pm->ps->weapon == WP_NONE || - pm->ps->weaponstate == WEAPON_READY || - pm->ps->weaponstate == WEAPON_CHARGING || - pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { - if ( pm->ps->weapon == WP_SABER && pm->ps->saberLength ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 - } - else if( pm->ps->legsAnim == BOTH_RUN1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN2 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK2 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0 )//player falls through + if (pm->ps->weapon == WP_NONE || pm->ps->weaponstate == WEAPON_READY || pm->ps->weaponstate == WEAPON_CHARGING || + pm->ps->weaponstate == WEAPON_CHARGING_ALT) { + if (pm->ps->weapon == WP_SABER && pm->ps->saberLength) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_NORMAL); // TORSO_WEAPONREADY1 + } else if (pm->ps->legsAnim == BOTH_RUN1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN2 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_CROUCH1IDLE && pm->ps->clientNum != 0) // player falls through { //??? Why nothing? What if you were running??? - //PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_JUMP1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_JUMP1,SETANIM_FLAG_NORMAL, 100); // Only blend over 100ms - } - else if( pm->ps->legsAnim == BOTH_SWIM_IDLE1 && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIMFORWARD && !weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else if ( pm->ps->weapon == WP_NONE ) - { + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_CROUCH1IDLE,SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_JUMP1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_JUMP1, SETANIM_FLAG_NORMAL, 100); // Only blend over 100ms + } else if (pm->ps->legsAnim == BOTH_SWIM_IDLE1 && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIMFORWARD && !weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else if (pm->ps->weapon == WP_NONE) { int legsAnim = pm->ps->legsAnim; /* if ( PM_RollingAnim( legsAnim ) || @@ -3210,481 +2568,303 @@ void PM_TorsoAnimation( void ) PM_PainAnim( legsAnim ) || PM_SwimmingAnim( legsAnim ) ) */ - { - PM_SetAnim(pm, SETANIM_TORSO, legsAnim, SETANIM_FLAG_NORMAL ); - } - } - else - {//Used to default to both_stand1 which is an arms-down anim - if ( !pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else if ( pm->gent != NULL - && pm->gent->s.number == 0 - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT ) - {//PLayer- temp hack for weapon frame - if ( pm->ps->weapon == WP_MELEE ) - {//hehe - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); + { PM_SetAnim(pm, SETANIM_TORSO, legsAnim, SETANIM_FLAG_NORMAL); } + } else { // Used to default to both_stand1 which is an arms-down anim + if (!pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else if (pm->gent != NULL && pm->gent->s.number == 0 && pm->ps->weaponstate != WEAPON_CHARGING && + pm->ps->weaponstate != WEAPON_CHARGING_ALT) { // PLayer- temp hack for weapon frame + if (pm->ps->weapon == WP_MELEE) { // hehe + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//use legs anim - //FIXME: or just use whatever's currently playing? - //PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); - } - else - { - switch(pm->ps->weapon) - { + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // use legs anim + // FIXME: or just use whatever's currently playing? + // PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); + } else { + switch (pm->ps->weapon) { // ******************************************************** - case WP_SABER: // WP_LIGHTSABER + case WP_SABER: // WP_LIGHTSABER // Ready pose for Lightsaber -// PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 + // PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_NORMAL);//TORSO_WEAPONREADY1 // Select the next proper pose for the lightsaber assuming that there are no attacks. - if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) - { + if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) { PM_SetSaberMove(saberMoveData[pm->ps->saberMove].chain_idle); } break; - // ******************************************************** + // ******************************************************** case WP_BRYAR_PISTOL: - //FIXME: if recently fired, hold the ready! - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); + // FIXME: if recently fired, hold the ready! + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); } break; case WP_BLASTER_PISTOL: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); } break; case WP_NONE: - //NOTE: should never get here + // NOTE: should never get here break; case WP_MELEE: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( pm->gent && pm->gent->client && !PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (pm->gent && pm->gent->client && !PM_DroidMelee(pm->gent->client->NPC_class)) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_BLASTER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_ATTACK2,SETANIM_FLAG_NORMAL); break; case WP_DISRUPTOR: - if ( (pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT) - || PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running sniper weapon uses normal ready - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - } - else - { - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + if ((pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT) || + PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running sniper weapon uses normal ready + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL ); + } else { + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL); } } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT - && (PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim )) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( !pm->ps->clientNum && (pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT) ) - {//player pulling back to throw - PM_SetAnim( pm, SETANIM_TORSO, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY10, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT && + (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim))) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (!pm->ps->clientNum && + (pm->ps->weaponstate == WEAPON_CHARGING || pm->ps->weaponstate == WEAPON_CHARGING_ALT)) { // player pulling back to throw + PM_SetAnim(pm, SETANIM_TORSO, BOTH_THERMAL_READY, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY10, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } } break; case WP_REPEATER: - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {// - if ( pm->gent->alt_fire ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY1,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { // + if (pm->gent->alt_fire) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY1, SETANIM_FLAG_NORMAL); } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } break; case WP_TRIP_MINE: case WP_DET_PACK: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; default: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); break; } } } - } - else if ( pm->ps->weaponstate == WEAPON_IDLE ) - { - if( pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_LOOKAROUND1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_GUARD_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_GUARD_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND1IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE1 - || pm->ps->legsAnim == BOTH_STAND2IDLE2 - || pm->ps->legsAnim == BOTH_STAND3IDLE1 - || pm->ps->legsAnim == BOTH_STAND4IDLE1 - || pm->ps->legsAnim == BOTH_STAND5IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); + } else if (pm->ps->weaponstate == WEAPON_IDLE) { + if (pm->ps->legsAnim == BOTH_GUARD_LOOKAROUND1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_GUARD_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND1IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE1 || pm->ps->legsAnim == BOTH_STAND2IDLE2 || + pm->ps->legsAnim == BOTH_STAND3IDLE1 || pm->ps->legsAnim == BOTH_STAND4IDLE1 || pm->ps->legsAnim == BOTH_STAND5IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); pm->ps->saberMove = LS_READY; - } - else if( pm->ps->legsAnim == BOTH_STAND2TO4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2TO4,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND4TO2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4TO2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_STAND4 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND4,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIM_IDLE1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_SWIMFORWARD ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//use legs anim - //FIXME: or just use whatever's currently playing? - //PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); - } - else if ( !pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD ) - {//using something - if ( !pm->ps->useTime ) - {//stopped holding it, release - PM_SetAnim( pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - }//else still holding, leave it as it is - } - else - { - if ( !weaponBusy - && pm->ps->weapon != WP_BOWCASTER - && pm->ps->weapon != WP_REPEATER - && pm->ps->weapon != WP_FLECHETTE - && pm->ps->weapon != WP_ROCKET_LAUNCHER - && ( PM_RunningAnim( pm->ps->legsAnim ) - || (PM_WalkingAnim( pm->ps->legsAnim ) && !pm->ps->clientNum) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) ) - {//running w/1-handed or light 2-handed weapon uses full-body anim if you're not using the weapon right now - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - switch ( pm->ps->weapon ) - { + } else if (pm->ps->legsAnim == BOTH_STAND2TO4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2TO4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4TO2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4TO2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_STAND4) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIM_IDLE1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_SWIMFORWARD) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // use legs anim + // FIXME: or just use whatever's currently playing? + // PM_SetAnim( pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL ); + } else if (!pm->ps->clientNum && pm->ps->torsoAnim == BOTH_BUTTON_HOLD) { // using something + if (!pm->ps->useTime) { // stopped holding it, release + PM_SetAnim(pm, SETANIM_TORSO, BOTH_BUTTON_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } // else still holding, leave it as it is + } else { + if (!weaponBusy && pm->ps->weapon != WP_BOWCASTER && pm->ps->weapon != WP_REPEATER && pm->ps->weapon != WP_FLECHETTE && + pm->ps->weapon != WP_ROCKET_LAUNCHER && + (PM_RunningAnim(pm->ps->legsAnim) || (PM_WalkingAnim(pm->ps->legsAnim) && !pm->ps->clientNum) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim( + pm->ps->legsAnim))) { // running w/1-handed or light 2-handed weapon uses full-body anim if you're not using the weapon right now + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + switch (pm->ps->weapon) { // ******************************************************** - case WP_SABER: // WP_LIGHTSABER + case WP_SABER: // WP_LIGHTSABER // Shouldn't get here, should go to TorsoAnimLightsaber break; - // ******************************************************** + // ******************************************************** case WP_BRYAR_PISTOL: - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT || weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); } break; case WP_BLASTER_PISTOL: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY2,SETANIM_FLAG_NORMAL); - } - else if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY2, SETANIM_FLAG_NORMAL); + } else if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); } break; case WP_NONE: - //NOTE: should never get here + // NOTE: should never get here break; case WP_MELEE: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( pm->gent && pm->gent->client && !PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND6,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (pm->gent && pm->gent->client && !PM_DroidMelee(pm->gent->client->NPC_class)) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND6, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_BLASTER: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; case WP_DISRUPTOR: - if ( (pm->ps->weaponstate != WEAPON_FIRING - && pm->ps->weaponstate != WEAPON_CHARGING - && pm->ps->weaponstate != WEAPON_CHARGING_ALT) - || PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running sniper weapon uses normal ready - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + if ((pm->ps->weaponstate != WEAPON_FIRING && pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_CHARGING_ALT) || + PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running sniper weapon uses normal ready + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - } - } - else - { - if ( pm->ps->clientNum ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL ); + } else { + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // TORSO_WEAPONREADY4//SETANIM_FLAG_RESTART| + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY4, SETANIM_FLAG_NORMAL); } } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONIDLE10, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE10, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; case WP_REPEATER: - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {// - if ( pm->gent->alt_fire ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE1,SETANIM_FLAG_NORMAL); - } - } - else - { - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { // + if (pm->gent->alt_fire) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE1, SETANIM_FLAG_NORMAL); } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } } break; case WP_TRIP_MINE: case WP_DET_PACK: - if ( PM_RunningAnim( pm->ps->legsAnim ) - || PM_WalkingAnim( pm->ps->legsAnim ) - || PM_JumpingAnim( pm->ps->legsAnim ) - || PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//running w/1-handed weapon uses full-body anim - PM_SetAnim(pm,SETANIM_TORSO,pm->ps->legsAnim,SETANIM_FLAG_NORMAL); - } - else - { - if ( weaponBusy ) - { - PM_SetAnim( pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (PM_RunningAnim(pm->ps->legsAnim) || PM_WalkingAnim(pm->ps->legsAnim) || PM_JumpingAnim(pm->ps->legsAnim) || + PM_SwimmingAnim(pm->ps->legsAnim)) { // running w/1-handed weapon uses full-body anim + PM_SetAnim(pm, SETANIM_TORSO, pm->ps->legsAnim, SETANIM_FLAG_NORMAL); + } else { + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } break; default: - if ( weaponBusy ) - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + if (weaponBusy) { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); } break; } @@ -3697,69 +2877,60 @@ void PM_TorsoAnimation( void ) // Anim checking utils //========================================================================= -int PM_GetTurnAnim( gentity_t *gent, int anim ) -{ - if ( !gent ) - { +int PM_GetTurnAnim(gentity_t *gent, int anim) { + if (!gent) { return -1; } - switch( anim ) - { - case BOTH_STAND1: //# Standing idle: no weapon: hands down - case BOTH_STAND1IDLE1: //# Random standing idle - case BOTH_STAND2: //# Standing idle with a weapon + switch (anim) { + case BOTH_STAND1: //# Standing idle: no weapon: hands down + case BOTH_STAND1IDLE1: //# Random standing idle + case BOTH_STAND2: //# Standing idle with a weapon case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: - case BOTH_STAND2IDLE1: //# Random standing idle - case BOTH_STAND2IDLE2: //# Random standing idle - case BOTH_STAND3: //# Standing hands behind back: at ease: etc. - case BOTH_STAND3IDLE1: //# Random standing idle - case BOTH_STAND4: //# two handed: gun down: relaxed stand - case BOTH_STAND4IDLE1: //# Random standing idle - case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight - case BOTH_STAND5IDLE1: //# Random standing idle - case BOTH_STAND6: //# one handed: gun at side: relaxed stand - case BOTH_STAND1TO3: //# Transition from stand1 to stand3 - case BOTH_STAND3TO1: //# Transition from stand3 to stand1 - case BOTH_STAND2TO4: //# Transition from stand2 to stand4 - case BOTH_STAND4TO2: //# Transition from stand4 to stand2 - case BOTH_STANDUP1: //# standing up and stumbling - case BOTH_GESTURE1: //# Generic gesture: non-specific - case BOTH_GESTURE2: //# Generic gesture: non-specific - case BOTH_GESTURE3: //# Generic gesture: non-specific - case BOTH_TALK1: //# Generic talk anim - case BOTH_TALK2: //# Generic talk anim - if ( PM_HasAnimation( gent, LEGS_TURN1 ) ) - { + case BOTH_STAND2IDLE1: //# Random standing idle + case BOTH_STAND2IDLE2: //# Random standing idle + case BOTH_STAND3: //# Standing hands behind back: at ease: etc. + case BOTH_STAND3IDLE1: //# Random standing idle + case BOTH_STAND4: //# two handed: gun down: relaxed stand + case BOTH_STAND4IDLE1: //# Random standing idle + case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight + case BOTH_STAND5IDLE1: //# Random standing idle + case BOTH_STAND6: //# one handed: gun at side: relaxed stand + case BOTH_STAND1TO3: //# Transition from stand1 to stand3 + case BOTH_STAND3TO1: //# Transition from stand3 to stand1 + case BOTH_STAND2TO4: //# Transition from stand2 to stand4 + case BOTH_STAND4TO2: //# Transition from stand4 to stand2 + case BOTH_STANDUP1: //# standing up and stumbling + case BOTH_GESTURE1: //# Generic gesture: non-specific + case BOTH_GESTURE2: //# Generic gesture: non-specific + case BOTH_GESTURE3: //# Generic gesture: non-specific + case BOTH_TALK1: //# Generic talk anim + case BOTH_TALK2: //# Generic talk anim + if (PM_HasAnimation(gent, LEGS_TURN1)) { return LEGS_TURN1; - } - else - { + } else { return -1; } break; - case BOTH_ATTACK1: //# Attack with generic 1-handed weapon - case BOTH_ATTACK2: //# Attack with generic 2-handed weapon - case BOTH_ATTACK3: //# Attack with heavy 2-handed weapon - case BOTH_ATTACK4: //# Attack with ??? - case BOTH_ATTACK5: //# Attack with rocket launcher - case BOTH_MELEE1: //# First melee attack - case BOTH_MELEE2: //# Second melee attack - case BOTH_MELEE3: //# Third melee attack - case BOTH_MELEE4: //# Fourth melee attack - case BOTH_MELEE5: //# Fifth melee attack - case BOTH_MELEE6: //# Sixth melee attack - case BOTH_COVERUP1_LOOP: //# animation of getting in line of friendly fire - case BOTH_GUARD_LOOKAROUND1: //# Cradling weapon and looking around - case BOTH_GUARD_IDLE1: //# Cradling weapon and standing - case BOTH_ALERT1: //# Startled by something while on guard - if ( PM_HasAnimation( gent, LEGS_TURN2 ) ) - { + case BOTH_ATTACK1: //# Attack with generic 1-handed weapon + case BOTH_ATTACK2: //# Attack with generic 2-handed weapon + case BOTH_ATTACK3: //# Attack with heavy 2-handed weapon + case BOTH_ATTACK4: //# Attack with ??? + case BOTH_ATTACK5: //# Attack with rocket launcher + case BOTH_MELEE1: //# First melee attack + case BOTH_MELEE2: //# Second melee attack + case BOTH_MELEE3: //# Third melee attack + case BOTH_MELEE4: //# Fourth melee attack + case BOTH_MELEE5: //# Fifth melee attack + case BOTH_MELEE6: //# Sixth melee attack + case BOTH_COVERUP1_LOOP: //# animation of getting in line of friendly fire + case BOTH_GUARD_LOOKAROUND1: //# Cradling weapon and looking around + case BOTH_GUARD_IDLE1: //# Cradling weapon and standing + case BOTH_ALERT1: //# Startled by something while on guard + if (PM_HasAnimation(gent, LEGS_TURN2)) { return LEGS_TURN2; - } - else - { + } else { return -1; } break; @@ -3769,90 +2940,69 @@ int PM_GetTurnAnim( gentity_t *gent, int anim ) } } -int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ) -{ - if ( !gent ) - { +int PM_TurnAnimForLegsAnim(gentity_t *gent, int anim) { + if (!gent) { return -1; } - switch( anim ) - { - case BOTH_STAND1: //# Standing idle: no weapon: hands down - case BOTH_STAND1IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND1 ) ) - { + switch (anim) { + case BOTH_STAND1: //# Standing idle: no weapon: hands down + case BOTH_STAND1IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND1)) { return BOTH_TURNSTAND1; - } - else - { + } else { return -1; } break; - case BOTH_STAND2: //# Standing idle with a weapon + case BOTH_STAND2: //# Standing idle with a weapon case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: - case BOTH_STAND2IDLE1: //# Random standing idle - case BOTH_STAND2IDLE2: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND2 ) ) - { + case BOTH_STAND2IDLE1: //# Random standing idle + case BOTH_STAND2IDLE2: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND2)) { return BOTH_TURNSTAND2; - } - else - { + } else { return -1; } break; - case BOTH_STAND3: //# Standing hands behind back: at ease: etc. - case BOTH_STAND3IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND3 ) ) - { + case BOTH_STAND3: //# Standing hands behind back: at ease: etc. + case BOTH_STAND3IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND3)) { return BOTH_TURNSTAND3; - } - else - { + } else { return -1; } break; - case BOTH_STAND4: //# two handed: gun down: relaxed stand - case BOTH_STAND4IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND4 ) ) - { + case BOTH_STAND4: //# two handed: gun down: relaxed stand + case BOTH_STAND4IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND4)) { return BOTH_TURNSTAND4; - } - else - { + } else { return -1; } break; - case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight - case BOTH_STAND5IDLE1: //# Random standing idle - if ( PM_HasAnimation( gent, BOTH_TURNSTAND5 ) ) - { + case BOTH_STAND5: //# standing idle, no weapon, hand down, back straight + case BOTH_STAND5IDLE1: //# Random standing idle + if (PM_HasAnimation(gent, BOTH_TURNSTAND5)) { return BOTH_TURNSTAND5; - } - else - { + } else { return -1; } break; - case BOTH_CROUCH1: //# Transition from standing to crouch - case BOTH_CROUCH1IDLE: //# Crouching idle - /* - case BOTH_UNCROUCH1: //# Transition from crouch to standing - case BOTH_CROUCH2IDLE: //# crouch and resting on back righ heel: no weapon - case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 - case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) - case BOTH_UNCROUCH3: //# Desann uncrouching down to Kyle (cin 9) - case BOTH_CROUCH4: //# Slower version of crouch1 for cinematics - case BOTH_UNCROUCH4: //# Slower version of uncrouch1 for cinematics - */ - if ( PM_HasAnimation( gent, BOTH_TURNCROUCH1 ) ) - { + case BOTH_CROUCH1: //# Transition from standing to crouch + case BOTH_CROUCH1IDLE: //# Crouching idle + /* + case BOTH_UNCROUCH1: //# Transition from crouch to standing + case BOTH_CROUCH2IDLE: //# crouch and resting on back righ heel: no weapon + case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 + case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) + case BOTH_UNCROUCH3: //# Desann uncrouching down to Kyle (cin 9) + case BOTH_CROUCH4: //# Slower version of crouch1 for cinematics + case BOTH_UNCROUCH4: //# Slower version of uncrouch1 for cinematics + */ + if (PM_HasAnimation(gent, BOTH_TURNCROUCH1)) { return BOTH_TURNCROUCH1; - } - else - { + } else { return -1; } break; @@ -3862,10 +3012,8 @@ int PM_TurnAnimForLegsAnim( gentity_t *gent, int anim ) } } -qboolean PM_InOnGroundAnim ( playerState_t *ps ) -{ - switch( ps->legsAnim ) - { +qboolean PM_InOnGroundAnim(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_DEAD1: case BOTH_DEAD2: case BOTH_DEAD3: @@ -3877,36 +3025,35 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) case BOTH_DEADBACKWARD2: case BOTH_LYINGDEATH1: case BOTH_LYINGDEAD1: - case BOTH_PAIN2WRITHE1: //# Transition from upright position to writhing on ground anim - case BOTH_WRITHING1: //# Lying on ground writhing in pain - case BOTH_WRITHING1RLEG: //# Lying on ground writhing in pain: holding right leg - case BOTH_WRITHING1LLEG: //# Lying on ground writhing in pain: holding left leg - case BOTH_WRITHING2: //# Lying on stomache writhing in pain - case BOTH_INJURED1: //# Lying down: against wall - can also be sleeping - case BOTH_CRAWLBACK1: //# Lying on back: crawling backwards with elbows - case BOTH_INJURED2: //# Injured pose 2 - case BOTH_INJURED3: //# Injured pose 3 - case BOTH_INJURED6: //# Injured pose 6 - case BOTH_INJURED6ATTACKSTART: //# Start attack while in injured 6 pose - case BOTH_INJURED6ATTACKSTOP: //# End attack while in injured 6 pose - case BOTH_INJURED6COMBADGE: //# Hit combadge while in injured 6 pose - case BOTH_INJURED6POINT: //# Chang points to door while in injured state - case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso - case BOTH_SLEEP2: //# on floor-back against wall-arms crossed - case BOTH_SLEEP5: //# Laying on side sleeping on flat sufrace - case BOTH_SLEEP_IDLE1: //# rub face and nose while asleep from sleep pose 1 - case BOTH_SLEEP_IDLE2: //# shift position while asleep - stays in sleep2 - case BOTH_SLEEP1_NOSE: //# Scratch nose from SLEEP1 pose - case BOTH_SLEEP2_SHIFT: //# Shift in sleep from SLEEP2 pose + case BOTH_PAIN2WRITHE1: //# Transition from upright position to writhing on ground anim + case BOTH_WRITHING1: //# Lying on ground writhing in pain + case BOTH_WRITHING1RLEG: //# Lying on ground writhing in pain: holding right leg + case BOTH_WRITHING1LLEG: //# Lying on ground writhing in pain: holding left leg + case BOTH_WRITHING2: //# Lying on stomache writhing in pain + case BOTH_INJURED1: //# Lying down: against wall - can also be sleeping + case BOTH_CRAWLBACK1: //# Lying on back: crawling backwards with elbows + case BOTH_INJURED2: //# Injured pose 2 + case BOTH_INJURED3: //# Injured pose 3 + case BOTH_INJURED6: //# Injured pose 6 + case BOTH_INJURED6ATTACKSTART: //# Start attack while in injured 6 pose + case BOTH_INJURED6ATTACKSTOP: //# End attack while in injured 6 pose + case BOTH_INJURED6COMBADGE: //# Hit combadge while in injured 6 pose + case BOTH_INJURED6POINT: //# Chang points to door while in injured state + case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso + case BOTH_SLEEP2: //# on floor-back against wall-arms crossed + case BOTH_SLEEP5: //# Laying on side sleeping on flat sufrace + case BOTH_SLEEP_IDLE1: //# rub face and nose while asleep from sleep pose 1 + case BOTH_SLEEP_IDLE2: //# shift position while asleep - stays in sleep2 + case BOTH_SLEEP1_NOSE: //# Scratch nose from SLEEP1 pose + case BOTH_SLEEP2_SHIFT: //# Shift in sleep from SLEEP2 pose return qtrue; break; - case BOTH_KNOCKDOWN1: //# - case BOTH_KNOCKDOWN2: //# - case BOTH_KNOCKDOWN3: //# - case BOTH_KNOCKDOWN4: //# - case BOTH_KNOCKDOWN5: //# - if ( ps->legsAnimTimer < 500 ) - {//pretty much horizontal by this point + case BOTH_KNOCKDOWN1: //# + case BOTH_KNOCKDOWN2: //# + case BOTH_KNOCKDOWN3: //# + case BOTH_KNOCKDOWN4: //# + case BOTH_KNOCKDOWN5: //# + if (ps->legsAnimTimer < 500) { // pretty much horizontal by this point return qtrue; } break; @@ -3925,8 +3072,8 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( ps->legsAnimTimer > PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim )-400 ) - {//still pretty much horizontal at this point + if (ps->legsAnimTimer > PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - + 400) { // still pretty much horizontal at this point return qtrue; } break; @@ -3935,10 +3082,8 @@ qboolean PM_InOnGroundAnim ( playerState_t *ps ) return qfalse; } -qboolean PM_InSpecialDeathAnim( int anim ) -{ - switch( pm->ps->legsAnim ) - { +qboolean PM_InSpecialDeathAnim(int anim) { + switch (pm->ps->legsAnim) { case BOTH_DEATH_ROLL: //# Death anim from a roll case BOTH_DEATH_FLIP: //# Death anim from a flip case BOTH_DEATH_SPIN_90_R: //# Death anim when facing 90 degrees right @@ -3946,8 +3091,8 @@ qboolean PM_InSpecialDeathAnim( int anim ) case BOTH_DEATH_SPIN_180: //# Death anim when facing backwards case BOTH_DEATH_LYING_UP: //# Death anim when lying on back case BOTH_DEATH_LYING_DN: //# Death anim when lying on front - case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face - case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back + case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face + case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back case BOTH_DEATH_CROUCHED: //# Death anim when crouched return qtrue; break; @@ -3957,114 +3102,110 @@ qboolean PM_InSpecialDeathAnim( int anim ) } } -qboolean PM_InDeathAnim ( void ) -{//Purposely does not cover stumbledeath and falldeath... - switch( pm->ps->legsAnim ) - { - case BOTH_DEATH1: //# First Death anim - case BOTH_DEATH2: //# Second Death anim - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH8: //# - case BOTH_DEATH9: //# - case BOTH_DEATH10: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH13: //# - case BOTH_DEATH14: //# - case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) - case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) - case BOTH_DEATH15: //# - case BOTH_DEATH16: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATH20: //# - case BOTH_DEATH21: //# - case BOTH_DEATH22: //# - case BOTH_DEATH23: //# - case BOTH_DEATH24: //# - case BOTH_DEATH25: //# - - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom +qboolean PM_InDeathAnim(void) { // Purposely does not cover stumbledeath and falldeath... + switch (pm->ps->legsAnim) { + case BOTH_DEATH1: //# First Death anim + case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH8: //# + case BOTH_DEATH9: //# + case BOTH_DEATH10: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH13: //# + case BOTH_DEATH14: //# + case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) + case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) + case BOTH_DEATH15: //# + case BOTH_DEATH16: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATH20: //# + case BOTH_DEATH21: //# + case BOTH_DEATH22: //# + case BOTH_DEATH23: //# + case BOTH_DEATH24: //# + case BOTH_DEATH25: //# + + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom //# #sep case BOTH_ DEAD POSES # Should be last frame of corresponding previous anims - case BOTH_DEAD1: //# First Death finished pose - case BOTH_DEAD2: //# Second Death finished pose - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD8: //# - case BOTH_DEAD9: //# - case BOTH_DEAD10: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD13: //# - case BOTH_DEAD14: //# - case BOTH_DEAD15: //# - case BOTH_DEAD16: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_DEAD20: //# - case BOTH_DEAD21: //# - case BOTH_DEAD22: //# - case BOTH_DEAD23: //# - case BOTH_DEAD24: //# - case BOTH_DEAD25: //# - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEAD1: //# First Death finished pose + case BOTH_DEAD2: //# Second Death finished pose + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD8: //# + case BOTH_DEAD9: //# + case BOTH_DEAD10: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD13: //# + case BOTH_DEAD14: //# + case BOTH_DEAD15: //# + case BOTH_DEAD16: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_DEAD20: //# + case BOTH_DEAD21: //# + case BOTH_DEAD22: //# + case BOTH_DEAD23: //# + case BOTH_DEAD24: //# + case BOTH_DEAD25: //# + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose //# #sep case BOTH_ DEAD TWITCH/FLOP # React to being shot from death poses - case BOTH_DEADFLOP1: //# React to being shot from First Death finished pose - case BOTH_DEADFLOP2: //# React to being shot from Second Death finished pose - case BOTH_DEADFLOP3: //# React to being shot from Third Death finished pose - case BOTH_DEADFLOP4: //# React to being shot from Fourth Death finished pose - case BOTH_DEADFLOP5: //# React to being shot from Fifth Death finished pose - case BOTH_DEADFORWARD1_FLOP: //# React to being shot First thrown forward death finished pose - case BOTH_DEADFORWARD2_FLOP: //# React to being shot Second thrown forward death finished pose - case BOTH_DEADBACKWARD1_FLOP: //# React to being shot First thrown backward death finished pose - case BOTH_DEADBACKWARD2_FLOP: //# React to being shot Second thrown backward death finished pose - case BOTH_LYINGDEAD1_FLOP: //# React to being shot Killed lying down death finished pose - case BOTH_STUMBLEDEAD1_FLOP: //# React to being shot Stumble forward death finished pose - case BOTH_FALLDEAD1_FLOP: //# React to being shot Fall forward and splat death finished pose - case BOTH_DISMEMBER_HEAD1: //# - case BOTH_DISMEMBER_TORSO1: //# - case BOTH_DISMEMBER_LLEG: //# - case BOTH_DISMEMBER_RLEG: //# - case BOTH_DISMEMBER_RARM: //# - case BOTH_DISMEMBER_LARM: //# + case BOTH_DEADFLOP1: //# React to being shot from First Death finished pose + case BOTH_DEADFLOP2: //# React to being shot from Second Death finished pose + case BOTH_DEADFLOP3: //# React to being shot from Third Death finished pose + case BOTH_DEADFLOP4: //# React to being shot from Fourth Death finished pose + case BOTH_DEADFLOP5: //# React to being shot from Fifth Death finished pose + case BOTH_DEADFORWARD1_FLOP: //# React to being shot First thrown forward death finished pose + case BOTH_DEADFORWARD2_FLOP: //# React to being shot Second thrown forward death finished pose + case BOTH_DEADBACKWARD1_FLOP: //# React to being shot First thrown backward death finished pose + case BOTH_DEADBACKWARD2_FLOP: //# React to being shot Second thrown backward death finished pose + case BOTH_LYINGDEAD1_FLOP: //# React to being shot Killed lying down death finished pose + case BOTH_STUMBLEDEAD1_FLOP: //# React to being shot Stumble forward death finished pose + case BOTH_FALLDEAD1_FLOP: //# React to being shot Fall forward and splat death finished pose + case BOTH_DISMEMBER_HEAD1: //# + case BOTH_DISMEMBER_TORSO1: //# + case BOTH_DISMEMBER_LLEG: //# + case BOTH_DISMEMBER_RLEG: //# + case BOTH_DISMEMBER_RARM: //# + case BOTH_DISMEMBER_LARM: //# return qtrue; break; default: - return PM_InSpecialDeathAnim( pm->ps->legsAnim ); + return PM_InSpecialDeathAnim(pm->ps->legsAnim); break; } } -qboolean PM_InCartwheel( int anim ) -{ - switch ( anim ) - { +qboolean PM_InCartwheel(int anim) { + switch (anim) { case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: case BOTH_ARIAL_F1: @@ -4076,10 +3217,8 @@ qboolean PM_InCartwheel( int anim ) return qfalse; } -qboolean PM_StandingAnim( int anim ) -{//NOTE: does not check idles or special (cinematic) stands - switch ( anim ) - { +qboolean PM_StandingAnim(int anim) { // NOTE: does not check idles or special (cinematic) stands + switch (anim) { case BOTH_STAND1: case BOTH_STAND2: case BOTH_STAND3: diff --git a/codeJK2/game/bg_pmove.cpp b/codeJK2/game/bg_pmove.cpp index 964cfcece2..78f0d33e1e 100644 --- a/codeJK2/game/bg_pmove.cpp +++ b/codeJK2/game/bg_pmove.cpp @@ -27,7 +27,7 @@ along with this program; if not, see . // define GAME_INCLUDE so that g_public.h does not define the // short, server-visible gclient_t and gentity_t structures, // because we define the full size ones in this file -#define GAME_INCLUDE +#define GAME_INCLUDE #include "../../code/qcommon/q_shared.h" #include "b_local.h" #include "g_shared.h" @@ -35,126 +35,120 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" #include "anims.h" -#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... +#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... #include "wp_saber.h" #include -extern qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ); -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern void WP_SaberInitBladeData( gentity_t *ent ); -extern qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern int PM_SaberAnimTransitionAnim( int curmove, int newmove ); -extern saberMoveName_t PM_AttackMoveForQuad( int quad ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern int PM_SaberBounceForAttack( int move ); -extern int PM_SaberAttackForMovement( int forwardmove, int rightmove, int move ); -extern int PM_BrokenParryForParry( int move ); -extern int PM_KnockawayForParry( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberKataDone( int curmove, int newmove ); -extern qboolean PM_SaberInSpecial( int move ); -extern qboolean PM_InDeathAnim ( void ); -extern qboolean PM_StandingAnim( int anim ); -extern int PM_SaberFlipOverAttackMove( void ); -extern int PM_SaberJumpAttackMove( void ); - -qboolean PM_InKnockDown( playerState_t *ps ); -qboolean PM_InKnockDownOnGround( playerState_t *ps ); -qboolean PM_InGetUp( playerState_t *ps ); -qboolean PM_InRoll( playerState_t *ps ); -qboolean PM_SpinningSaberAnim( int anim ); -qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ); -qboolean PM_SpinningAnim( int anim ); -qboolean PM_FlippingAnim( int anim ); -qboolean PM_PainAnim( int anim ); -qboolean PM_RollingAnim( int anim ); -qboolean PM_SwimmingAnim( int anim ); +extern qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse); +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern void WP_SaberInitBladeData(gentity_t *ent); +extern qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern int PM_SaberAnimTransitionAnim(int curmove, int newmove); +extern saberMoveName_t PM_AttackMoveForQuad(int quad); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern int PM_SaberBounceForAttack(int move); +extern int PM_SaberAttackForMovement(int forwardmove, int rightmove, int move); +extern int PM_BrokenParryForParry(int move); +extern int PM_KnockawayForParry(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberKataDone(int curmove, int newmove); +extern qboolean PM_SaberInSpecial(int move); +extern qboolean PM_InDeathAnim(void); +extern qboolean PM_StandingAnim(int anim); +extern int PM_SaberFlipOverAttackMove(void); +extern int PM_SaberJumpAttackMove(void); + +qboolean PM_InKnockDown(playerState_t *ps); +qboolean PM_InKnockDownOnGround(playerState_t *ps); +qboolean PM_InGetUp(playerState_t *ps); +qboolean PM_InRoll(playerState_t *ps); +qboolean PM_SpinningSaberAnim(int anim); +qboolean PM_GettingUpFromKnockDown(float standheight, float crouchheight); +qboolean PM_SpinningAnim(int anim); +qboolean PM_FlippingAnim(int anim); +qboolean PM_PainAnim(int anim); +qboolean PM_RollingAnim(int anim); +qboolean PM_SwimmingAnim(int anim); extern int parryDebounce[]; -extern qboolean player_locked; -extern qboolean MatrixMode; -qboolean waterForceJump; -extern cvar_t *g_timescale; +extern qboolean player_locked; +extern qboolean MatrixMode; +qboolean waterForceJump; +extern cvar_t *g_timescale; -static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype ); +static void PM_SetWaterLevelAtPoint(vec3_t org, int *waterlevel, int *watertype); -#define FLY_NONE 0 -#define FLY_NORMAL 1 -#define FLY_VEHICLE 2 -#define FLY_HOVER 3 -int Flying = FLY_NONE; +#define FLY_NONE 0 +#define FLY_NORMAL 1 +#define FLY_VEHICLE 2 +#define FLY_HOVER 3 +int Flying = FLY_NONE; -pmove_t *pm; -pml_t pml; +pmove_t *pm; +pml_t pml; // movement parameters -const float pm_stopspeed = 100.0f; -const float pm_duckScale = 0.50f; -const float pm_swimScale = 0.50f; -float pm_ladderScale = 0.7f; - -const float pm_accelerate = 12.0f; -const float pm_airaccelerate = 4.0f; -const float pm_wateraccelerate = 4.0f; -const float pm_flyaccelerate = 8.0f; - -const float pm_friction = 6.0f; -const float pm_waterfriction = 1.0f; -const float pm_flightfriction = 3.0f; - -const float pm_frictionModifier = 3.0f; //Used for "careful" mode (when pressing use) -const float pm_airDecelRate = 1.35f; //Used for air decelleration away from current movement velocity - -int c_pmove = 0; - -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -//extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags); -extern void PM_TorsoAnimation( void ); -extern int PM_TorsoAnimForFrame( gentity_t *ent, int torsoFrame ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InDeathAnim ( void ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern weaponInfo_t cg_weapons[MAX_WEAPONS]; -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); - -extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ); - -#define PHASER_RECHARGE_TIME 100 +const float pm_stopspeed = 100.0f; +const float pm_duckScale = 0.50f; +const float pm_swimScale = 0.50f; +float pm_ladderScale = 0.7f; + +const float pm_accelerate = 12.0f; +const float pm_airaccelerate = 4.0f; +const float pm_wateraccelerate = 4.0f; +const float pm_flyaccelerate = 8.0f; + +const float pm_friction = 6.0f; +const float pm_waterfriction = 1.0f; +const float pm_flightfriction = 3.0f; + +const float pm_frictionModifier = 3.0f; // Used for "careful" mode (when pressing use) +const float pm_airDecelRate = 1.35f; // Used for air decelleration away from current movement velocity + +int c_pmove = 0; + +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +// extern void PM_SetAnim(pmove_t *pm,int setAnimParts,int anim,int setAnimFlags); +extern void PM_TorsoAnimation(void); +extern int PM_TorsoAnimForFrame(gentity_t *ent, int torsoFrame); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InDeathAnim(void); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern weaponInfo_t cg_weapons[MAX_WEAPONS]; +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); + +extern void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf); + +#define PHASER_RECHARGE_TIME 100 extern saberMoveName_t transitionMove[Q_NUM_QUADS][Q_NUM_QUADS]; -extern qboolean G_ControlledByPlayer( gentity_t *self ); -qboolean PM_ControlledByPlayer( void ) -{ - return G_ControlledByPlayer( pm->gent ); -} +extern qboolean G_ControlledByPlayer(gentity_t *self); +qboolean PM_ControlledByPlayer(void) { return G_ControlledByPlayer(pm->gent); } /* =============== PM_AddEvent =============== */ -void PM_AddEvent( int newEvent ) -{ - AddEventToPlayerstate( newEvent, 0, pm->ps ); -} +void PM_AddEvent(int newEvent) { AddEventToPlayerstate(newEvent, 0, pm->ps); } /* =============== @@ -162,28 +156,25 @@ qboolean PM_ClientImpact( int otherEntityNum, qboolean damageSelf ) =============== */ -qboolean PM_ClientImpact( int otherEntityNum, qboolean damageSelf ) -{ - gentity_t *traceEnt; +qboolean PM_ClientImpact(int otherEntityNum, qboolean damageSelf) { + gentity_t *traceEnt; - if ( !pm->gent ) - { + if (!pm->gent) { return qfalse; } - if( (VectorLength( pm->ps->velocity )*(pm->gent->mass/10)) >= 100 && pm->ps->lastOnGround+100material>=MAT_GLASS&&pm->gent->lastImpact+100<=level.time)) + if ((VectorLength(pm->ps->velocity) * (pm->gent->mass / 10)) >= 100 && + pm->ps->lastOnGround + 100 < level.time) // was 300 ||(other->material>=MAT_GLASS&&pm->gent->lastImpact+100<=level.time)) { - DoImpact( pm->gent, &g_entities[otherEntityNum], damageSelf ); + DoImpact(pm->gent, &g_entities[otherEntityNum], damageSelf); } - if ( otherEntityNum >= ENTITYNUM_WORLD ) - { + if (otherEntityNum >= ENTITYNUM_WORLD) { return qfalse; } traceEnt = &g_entities[otherEntityNum]; - if ( !traceEnt || !(traceEnt->contents&pm->tracemask) ) - {//it's dead or not in my way anymore + if (!traceEnt || !(traceEnt->contents & pm->tracemask)) { // it's dead or not in my way anymore return qtrue; } @@ -194,19 +185,19 @@ qboolean PM_ClientImpact( int otherEntityNum, qboolean damageSelf ) PM_AddTouchEnt =============== */ -void PM_AddTouchEnt( int entityNum ) { - int i; +void PM_AddTouchEnt(int entityNum) { + int i; - if ( entityNum == ENTITYNUM_WORLD ) { + if (entityNum == ENTITYNUM_WORLD) { return; } - if ( pm->numtouch == MAXTOUCH ) { + if (pm->numtouch == MAXTOUCH) { return; } // see if it is already added - for ( i = 0 ; i < pm->numtouch ; i++ ) { - if ( pm->touchents[ i ] == entityNum ) { + for (i = 0; i < pm->numtouch; i++) { + if (pm->touchents[i] == entityNum) { return; } } @@ -216,9 +207,6 @@ void PM_AddTouchEnt( int entityNum ) { pm->numtouch++; } - - - /* ================== PM_ClipVelocity @@ -231,27 +219,25 @@ Slide off of the impacting surface ================== */ -void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) { - float backoff; - float change; - int i; +void PM_ClipVelocity(vec3_t in, vec3_t normal, vec3_t out, float overbounce) { + float backoff; + float change; + int i; - backoff = DotProduct (in, normal); + backoff = DotProduct(in, normal); - if ( backoff < 0 ) { + if (backoff < 0) { backoff *= overbounce; } else { backoff /= overbounce; } - for ( i=0 ; i<3 ; i++ ) - { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; out[i] = in[i] - change; } } - /* ================== PM_Friction @@ -259,23 +245,23 @@ PM_Friction Handles both ground friction and water friction ================== */ -static void PM_Friction( void ) { - vec3_t vec; - float *vel; - float speed, newspeed, control; - float drop, friction = pm->ps->friction; +static void PM_Friction(void) { + vec3_t vec; + float *vel; + float speed, newspeed, control; + float drop, friction = pm->ps->friction; vel = pm->ps->velocity; - VectorCopy( vel, vec ); - if ( pml.walking ) { - vec[2] = 0; // ignore slope movement + VectorCopy(vel, vec); + if (pml.walking) { + vec[2] = 0; // ignore slope movement } speed = VectorLength(vec); if (speed < 1) { vel[0] = 0; - vel[1] = 0; // allow sinking underwater + vel[1] = 0; // allow sinking underwater // FIXME: still have z friction underwater? return; } @@ -283,48 +269,39 @@ static void PM_Friction( void ) { drop = 0; // apply ground friction, even if on ladder - if ( Flying != FLY_NORMAL ) - { - if ( (pm->watertype & CONTENTS_LADDER) || pm->waterlevel <= 1 ) - { - if ( (pm->watertype & CONTENTS_LADDER) || (pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK)) ) - { + if (Flying != FLY_NORMAL) { + if ((pm->watertype & CONTENTS_LADDER) || pm->waterlevel <= 1) { + if ((pm->watertype & CONTENTS_LADDER) || (pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK))) { // if getting knocked back, no friction - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION) ) - { - //If the use key is pressed. slow the player more quickly - if ( pm->cmd.buttons & BUTTON_USE ) + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { + // If the use key is pressed. slow the player more quickly + if (pm->cmd.buttons & BUTTON_USE) friction *= pm_frictionModifier; control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; } } } } - if ( Flying == FLY_VEHICLE ) - { - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION) ) - { + if (Flying == FLY_VEHICLE) { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) && !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; } } // apply water friction even if just wading - if ( !waterForceJump ) - { - if ( pm->waterlevel && !(pm->watertype & CONTENTS_LADDER)) - { - drop += speed*pm_waterfriction*pm->waterlevel*pml.frametime; + if (!waterForceJump) { + if (pm->waterlevel && !(pm->watertype & CONTENTS_LADDER)) { + drop += speed * pm_waterfriction * pm->waterlevel * pml.frametime; } } // apply flying friction - if ( pm->ps->pm_type == PM_SPECTATOR ) - { - drop += speed*pm_flightfriction*pml.frametime; + if (pm->ps->pm_type == PM_SPECTATOR) { + drop += speed * pm_flightfriction * pml.frametime; } // scale the velocity @@ -339,7 +316,6 @@ static void PM_Friction( void ) { vel[2] = vel[2] * newspeed; } - /* ============== PM_Accelerate @@ -348,24 +324,23 @@ Handles user intended acceleration ============== */ -static void PM_Accelerate( vec3_t wishdir, float wishspeed, float accel ) -{ - int i; - float addspeed, accelspeed, currentspeed; +static void PM_Accelerate(vec3_t wishdir, float wishspeed, float accel) { + int i; + float addspeed, accelspeed, currentspeed; - currentspeed = DotProduct (pm->ps->velocity, wishdir); + currentspeed = DotProduct(pm->ps->velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0) { return; } - accelspeed = ( accel * pml.frametime ) * wishspeed; + accelspeed = (accel * pml.frametime) * wishspeed; if (accelspeed > addspeed) { accelspeed = addspeed; } - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { pm->ps->velocity[i] += accelspeed * wishdir[i]; } } @@ -379,33 +354,29 @@ This allows the clients to use axial -127 to 127 values for all directions without getting a sqrt(2) distortion in speed. ============ */ -static float PM_CmdScale( usercmd_t *cmd ) -{ - int max; - float total; - float scale; +static float PM_CmdScale(usercmd_t *cmd) { + int max; + float total; + float scale; - max = abs( cmd->forwardmove ); + max = abs(cmd->forwardmove); - if ( abs( cmd->rightmove ) > max ) { - max = abs( cmd->rightmove ); + if (abs(cmd->rightmove) > max) { + max = abs(cmd->rightmove); } - if ( abs( cmd->upmove ) > max ) { - max = abs( cmd->upmove ); + if (abs(cmd->upmove) > max) { + max = abs(cmd->upmove); } - if ( !max ) { + if (!max) { return 0; } - total = sqrt((double)( ( cmd->forwardmove * cmd->forwardmove ) - + ( cmd->rightmove * cmd->rightmove ) - + ( cmd->upmove * cmd->upmove ) )); + total = sqrt((double)((cmd->forwardmove * cmd->forwardmove) + (cmd->rightmove * cmd->rightmove) + (cmd->upmove * cmd->upmove))); - scale = (float) pm->ps->speed * max / ( 127.0f * total ); + scale = (float)pm->ps->speed * max / (127.0f * total); return scale; } - /* ================ PM_SetMovementDir @@ -414,48 +385,45 @@ Determine the rotation of the legs reletive to the facing dir ================ */ -static void PM_SetMovementDir( void ) { - if ( pm->cmd.forwardmove || pm->cmd.rightmove ) { - if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0 ) { +static void PM_SetMovementDir(void) { + if (pm->cmd.forwardmove || pm->cmd.rightmove) { + if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 0; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 1; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 2; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 3; - } else if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 4; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 5; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 6; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 7; } } else { // if they aren't actively going directly sideways, // change the animation to the diagonal so they // don't stop too crooked - if ( pm->ps->movementDir == 2 ) { + if (pm->ps->movementDir == 2) { pm->ps->movementDir = 1; - } else if ( pm->ps->movementDir == 6 ) { + } else if (pm->ps->movementDir == 6) { pm->ps->movementDir = 7; } } } - /* ============= PM_CheckJump ============= */ #define METROID_JUMP 1 -qboolean PM_InSpecialJump( int anim ) -{ - switch ( anim ) - { +qboolean PM_InSpecialJump(int anim) { + switch (anim) { case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_RIGHT_STOP: case BOTH_WALL_RUN_RIGHT_FLIP: @@ -473,8 +441,8 @@ qboolean PM_InSpecialJump( int anim ) case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: case BOTH_ARIAL_F1: @@ -485,54 +453,43 @@ qboolean PM_InSpecialJump( int anim ) return qfalse; } -extern void CG_PlayerLockedWeaponSpeech( int jumping ); -qboolean PM_ForceJumpingUp( gentity_t *gent ) -{ - if ( !gent || !gent->client ) - { +extern void CG_PlayerLockedWeaponSpeech(int jumping); +qboolean PM_ForceJumpingUp(gentity_t *gent) { + if (!gent || !gent->client) { return qfalse; } - if ( gent->NPC ) - {//this is ONLY for the player - if ( player - && player->client - && player->client->ps.viewEntity == gent->s.number ) - {//okay to jump if an NPC controlled by the player - } - else - { + if (gent->NPC) { // this is ONLY for the player + if (player && player->client && player->client->ps.viewEntity == gent->s.number) { // okay to jump if an NPC controlled by the player + } else { return qfalse; } } - if ( !(gent->client->ps.forcePowersActive&(1<client->ps.forceJumpCharge ) - {//already jumped and let go + if (!(gent->client->ps.forcePowersActive & (1 << FP_LEVITATION)) && gent->client->ps.forceJumpCharge) { // already jumped and let go return qfalse; } - if ( PM_InSpecialJump( gent->client->ps.legsAnim ) ) - { + if (PM_InSpecialJump(gent->client->ps.legsAnim)) { return qfalse; } - if ( PM_InKnockDown( &gent->client->ps ) ) - { + if (PM_InKnockDown(&gent->client->ps)) { return qfalse; } - if ( !gent->s.number && in_camera ) - {//player can't use force powers in cinematic + if (!gent->s.number && in_camera) { // player can't use force powers in cinematic return qfalse; } - if ( gent->client->ps.groundEntityNum == ENTITYNUM_NONE //in air - && ( /*(gent->client->ps.waterHeightLevel==WHL_SHOULDERS&&gent->client->usercmd.upmove>0) ||*/ ((gent->client->ps.pm_flags&PMF_JUMPING)&&gent->client->ps.velocity[2] > 0) )//jumped & going up or at water surface - && gent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 //force-jump capable - && !(gent->client->ps.pm_flags&PMF_TRIGGER_PUSHED) )//not pushed by a trigger + if (gent->client->ps.groundEntityNum == ENTITYNUM_NONE // in air + && (/*(gent->client->ps.waterHeightLevel==WHL_SHOULDERS&&gent->client->usercmd.upmove>0) ||*/ ( + (gent->client->ps.pm_flags & PMF_JUMPING) && gent->client->ps.velocity[2] > 0)) // jumped & going up or at water surface + && gent->client->ps.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 // force-jump capable + && !(gent->client->ps.pm_flags & PMF_TRIGGER_PUSHED)) // not pushed by a trigger { - if( gent->flags & FL_LOCK_PLAYER_WEAPONS ) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + if (gent->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one { - CG_PlayerLockedWeaponSpeech( qtrue ); + CG_PlayerLockedWeaponSpeech(qtrue); return qfalse; } return qtrue; @@ -540,77 +497,53 @@ qboolean PM_ForceJumpingUp( gentity_t *gent ) return qfalse; } -static void PM_JumpForDir( void ) -{ +static void PM_JumpForDir(void) { int anim = BOTH_JUMP1; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_JUMPBACK1; pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_JUMPRIGHT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_JUMPLEFT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else - { + } else { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; } - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,anim,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } } -extern qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); - -qboolean PM_GentCantJump( gentity_t *gent ) -{//FIXME: ugh, hacky, set a flag on NPC or something, please... - if ( gent && gent->client && - ( gent->client->NPC_class == CLASS_ATST || - gent->client->NPC_class == CLASS_GONK || - gent->client->NPC_class == CLASS_MARK1 || - gent->client->NPC_class == CLASS_MARK2 || - gent->client->NPC_class == CLASS_MOUSE || - gent->client->NPC_class == CLASS_PROBE || - gent->client->NPC_class == CLASS_PROTOCOL || - gent->client->NPC_class == CLASS_R2D2 || - gent->client->NPC_class == CLASS_R5D2 || - gent->client->NPC_class == CLASS_SEEKER || - gent->client->NPC_class == CLASS_REMOTE || - gent->client->NPC_class == CLASS_SENTRY ) ) - { +extern qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); + +qboolean PM_GentCantJump(gentity_t *gent) { // FIXME: ugh, hacky, set a flag on NPC or something, please... + if (gent && gent->client && + (gent->client->NPC_class == CLASS_ATST || gent->client->NPC_class == CLASS_GONK || gent->client->NPC_class == CLASS_MARK1 || + gent->client->NPC_class == CLASS_MARK2 || gent->client->NPC_class == CLASS_MOUSE || gent->client->NPC_class == CLASS_PROBE || + gent->client->NPC_class == CLASS_PROTOCOL || gent->client->NPC_class == CLASS_R2D2 || gent->client->NPC_class == CLASS_R5D2 || + gent->client->NPC_class == CLASS_SEEKER || gent->client->NPC_class == CLASS_REMOTE || gent->client->NPC_class == CLASS_SENTRY)) { return qtrue; } return qfalse; } -static qboolean PM_CheckJump( void ) -{ - //Don't allow jump until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { +static qboolean PM_CheckJump(void) { + // Don't allow jump until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return qfalse; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps ) ) - {//in knockdown + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return qfalse; } - if ( PM_GentCantJump( pm->gent ) ) - { + if (PM_GentCantJump(pm->gent)) { return qfalse; } /* @@ -621,13 +554,12 @@ static qboolean PM_CheckJump( void ) */ #if METROID_JUMP - if ( pm->waterlevel < 3 )//|| (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) + if (pm->waterlevel < 3) //|| (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) { - if ( pm->ps->gravity > 0 ) - {//can't do this in zero-G - //FIXME: still able to pogo-jump... - if ( PM_ForceJumpingUp( pm->gent ) && (pm->ps->pm_flags&PMF_JUMP_HELD) )//||pm->ps->waterHeightLevel==WHL_SHOULDERS) ) - {//force jumping && holding jump + if (pm->ps->gravity > 0) { // can't do this in zero-G + // FIXME: still able to pogo-jump... + if (PM_ForceJumpingUp(pm->gent) && (pm->ps->pm_flags & PMF_JUMP_HELD)) //||pm->ps->waterHeightLevel==WHL_SHOULDERS) ) + { // force jumping && holding jump /* if ( !pm->ps->forceJumpZStart && (pm->ps->waterHeightLevel==WHL_SHOULDERS&&pm->cmd.upmove>0) ) { @@ -635,40 +567,34 @@ static qboolean PM_CheckJump( void ) } */ float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart; - //check for max force jump level and cap off & cut z vel - if ( ( curHeight<=forceJumpHeight[0] ||//still below minimum jump height - (pm->ps->forcePower&&pm->cmd.upmove>=10) ) &&////still have force power available and still trying to jump up - curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] )//still below maximum jump height - {//can still go up - //FIXME: after a certain amount of time of held jump, play force jump sound and flip if a dir is being held - //FIXME: if hit a wall... should we cut velocity or allow them to slide up it? - //FIXME: constantly drain force power at a rate by which the usage for maximum height would use up the full cost of force jump - if ( curHeight > forceJumpHeight[0] ) - {//passed normal jump height *2? - if ( !(pm->ps->forcePowersActive&(1<ps->forcePower && pm->cmd.upmove >= 10)) && ////still have force power available and still trying to jump up + curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]) // still below maximum jump height + { // can still go up + // FIXME: after a certain amount of time of held jump, play force jump sound and flip if a dir is being held + // FIXME: if hit a wall... should we cut velocity or allow them to slide up it? + // FIXME: constantly drain force power at a rate by which the usage for maximum height would use up the full cost of force jump + if (curHeight > forceJumpHeight[0]) { // passed normal jump height *2? + if (!(pm->ps->forcePowersActive & (1 << FP_LEVITATION))) // haven't started forcejump yet { - //start force jump - pm->ps->forcePowersActive |= (1<gent ) - { - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // start force jump + pm->ps->forcePowersActive |= (1 << FP_LEVITATION); + if (pm->gent) { + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); } - //play flip - //FIXME: do this only when they stop the jump (below) or when they're just about to hit the peak of the jump - if ((pm->cmd.forwardmove || pm->cmd.rightmove) && //pushing in a dir - //pm->ps->legsAnim != BOTH_ARIAL_F1 &&//not already flipping - pm->ps->legsAnim != BOTH_FLIP_F && - pm->ps->legsAnim != BOTH_FLIP_B && - pm->ps->legsAnim != BOTH_FLIP_R && - pm->ps->legsAnim != BOTH_FLIP_L - && cg.renderingThirdPerson//third person only - && !cg.zoomMode )//not zoomed in - {//FIXME: this could end up playing twice if the jump is very long... + // play flip + // FIXME: do this only when they stop the jump (below) or when they're just about to hit the peak of the jump + if ((pm->cmd.forwardmove || pm->cmd.rightmove) && // pushing in a dir + // pm->ps->legsAnim != BOTH_ARIAL_F1 &&//not already flipping + pm->ps->legsAnim != BOTH_FLIP_F && pm->ps->legsAnim != BOTH_FLIP_B && pm->ps->legsAnim != BOTH_FLIP_R && + pm->ps->legsAnim != BOTH_FLIP_L && cg.renderingThirdPerson // third person only + && !cg.zoomMode) // not zoomed in + { // FIXME: this could end up playing twice if the jump is very long... int anim = BOTH_FORCEINAIR1; - int parts = SETANIM_BOTH; + int parts = SETANIM_BOTH; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { /* if ( pm->ps->forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_2 ) { @@ -676,120 +602,91 @@ static qboolean PM_CheckJump( void ) } else */ - { - anim = BOTH_FLIP_F; - } - } - else if ( pm->cmd.forwardmove < 0 ) - { + { anim = BOTH_FLIP_F; } + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FLIP_B; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_FLIP_R; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FLIP_L; } - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//FIXME: really want to know how far off ground we are, probably... + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (pm->ps->forcePowerLevel[FP_LEVITATION] > + FORCE_LEVEL_1) { // FIXME: really want to know how far off ground we are, probably... vec3_t facingFwd, facingRight, facingAngles = {0, pm->ps->viewangles[YAW], 0}; - int anim = -1; - AngleVectors( facingAngles, facingFwd, facingRight, NULL ); - float dotR = DotProduct( facingRight, pm->ps->velocity ); - float dotF = DotProduct( facingFwd, pm->ps->velocity ); - if ( fabs(dotR) > fabs(dotF) * 1.5 ) - { - if ( dotR > 150 ) - { + int anim = -1; + AngleVectors(facingAngles, facingFwd, facingRight, NULL); + float dotR = DotProduct(facingRight, pm->ps->velocity); + float dotF = DotProduct(facingFwd, pm->ps->velocity); + if (fabs(dotR) > fabs(dotF) * 1.5) { + if (dotR > 150) { anim = BOTH_FORCEJUMPRIGHT1; - } - else if ( dotR < -150 ) - { + } else if (dotR < -150) { anim = BOTH_FORCEJUMPLEFT1; } - } - else - { - if ( dotF > 150 ) - { + } else { + if (dotF > 150) { anim = BOTH_FORCEJUMP1; - } - else if ( dotF < -150 ) - { + } else if (dotF < -150) { anim = BOTH_FORCEJUMPBACK1; } } - if ( anim != -1 ) - { + if (anim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else - { - if ( !pm->ps->legsAnimTimer ) - {//not in the middle of a legsAnim + } else { + if (!pm->ps->legsAnimTimer) { // not in the middle of a legsAnim int anim = pm->ps->legsAnim; int newAnim = -1; - switch ( anim ) - { + switch (anim) { case BOTH_FORCEJUMP1: - newAnim = BOTH_FORCELAND1;//BOTH_FORCEINAIR1; + newAnim = BOTH_FORCELAND1; // BOTH_FORCEINAIR1; break; case BOTH_FORCEJUMPBACK1: - newAnim = BOTH_FORCELANDBACK1;//BOTH_FORCEINAIRBACK1; + newAnim = BOTH_FORCELANDBACK1; // BOTH_FORCEINAIRBACK1; break; case BOTH_FORCEJUMPLEFT1: - newAnim = BOTH_FORCELANDLEFT1;//BOTH_FORCEINAIRLEFT1; + newAnim = BOTH_FORCELANDLEFT1; // BOTH_FORCEINAIRLEFT1; break; case BOTH_FORCEJUMPRIGHT1: - newAnim = BOTH_FORCELANDRIGHT1;//BOTH_FORCEINAIRRIGHT1; + newAnim = BOTH_FORCELANDRIGHT1; // BOTH_FORCEINAIRRIGHT1; break; } - if ( newAnim != -1 ) - { + if (newAnim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( pm, parts, newAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, parts, newAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } } - //need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel - pm->ps->velocity[2] = (forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]-curHeight)/forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]*forceJumpStrength[pm->ps->forcePowerLevel[FP_LEVITATION]];//JUMP_VELOCITY; + // need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel + pm->ps->velocity[2] = (forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - curHeight) / + forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] * + forceJumpStrength[pm->ps->forcePowerLevel[FP_LEVITATION]]; // JUMP_VELOCITY; pm->ps->velocity[2] /= 10; pm->ps->velocity[2] += JUMP_VELOCITY; pm->ps->pm_flags |= PMF_JUMP_HELD; - } - else if ( curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - forceJumpHeight[0] ) - {//still have some headroom, don't totally stop it - if ( pm->ps->velocity[2] > JUMP_VELOCITY ) - { + } else if (curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]] - + forceJumpHeight[0]) { // still have some headroom, don't totally stop it + if (pm->ps->velocity[2] > JUMP_VELOCITY) { pm->ps->velocity[2] = JUMP_VELOCITY; } - } - else - { + } else { pm->ps->velocity[2] = 0; } pm->cmd.upmove = 0; @@ -800,127 +697,101 @@ static qboolean PM_CheckJump( void ) #endif - //Not jumping - if ( pm->cmd.upmove < 10 ) { + // Not jumping + if (pm->cmd.upmove < 10) { return qfalse; } // must wait for jump to be released - if ( pm->ps->pm_flags & PMF_JUMP_HELD ) - { + if (pm->ps->pm_flags & PMF_JUMP_HELD) { // clear upmove so cmdscale doesn't lower running speed pm->cmd.upmove = 0; return qfalse; } - if ( pm->ps->gravity <= 0 ) - {//in low grav, you push in the dir you're facing as long as there is something behind you to shove off of - vec3_t forward, back; - trace_t trace; + if (pm->ps->gravity <= 0) { // in low grav, you push in the dir you're facing as long as there is something behind you to shove off of + vec3_t forward, back; + trace_t trace; - AngleVectors( pm->ps->viewangles, forward, NULL, NULL ); - VectorMA( pm->ps->origin, -8, forward, back ); - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); + AngleVectors(pm->ps->viewangles, forward, NULL, NULL); + VectorMA(pm->ps->origin, -8, forward, back); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); pm->cmd.upmove = 0; - if ( trace.fraction < 1.0f ) - { - VectorMA( pm->ps->velocity, JUMP_VELOCITY/2, forward, pm->ps->velocity ); - //FIXME: kicking off wall anim? At least check what anim we're in? - PM_SetAnim(pm,SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); - } - else - {//else no surf close enough to push off of + if (trace.fraction < 1.0f) { + VectorMA(pm->ps->velocity, JUMP_VELOCITY / 2, forward, pm->ps->velocity); + // FIXME: kicking off wall anim? At least check what anim we're in? + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FORCEJUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { // else no surf close enough to push off of return qfalse; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//need to set some things and return - //Jumping + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // need to set some things and return + // Jumping pm->ps->forceJumpZStart = 0; pml.groundPlane = qfalse; pml.walking = qfalse; - pm->ps->pm_flags |= (PMF_JUMPING|PMF_JUMP_HELD); + pm->ps->pm_flags |= (PMF_JUMPING | PMF_JUMP_HELD); pm->ps->groundEntityNum = ENTITYNUM_NONE; pm->ps->jumpZStart = pm->ps->origin[2]; - if ( pm->gent ) - { - if ( !Q3_TaskIDPending( pm->gent, TID_CHAN_VOICE ) ) - { - PM_AddEvent( EV_JUMP ); + if (pm->gent) { + if (!Q3_TaskIDPending(pm->gent, TID_CHAN_VOICE)) { + PM_AddEvent(EV_JUMP); } - } - else - { - PM_AddEvent( EV_JUMP ); + } else { + PM_AddEvent(EV_JUMP); } return qtrue; - }//else no surf close enough to push off of - } - else if ( pm->cmd.upmove > 0 && pm->waterlevel < 2 - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 - && !(pm->ps->pm_flags&PMF_JUMP_HELD) - //&& !PM_InKnockDown( pm->ps ) - && pm->gent && WP_ForcePowerAvailable( pm->gent, FP_LEVITATION, 0 ) - && ((pm->ps->clientNum&&!PM_ControlledByPlayer())||((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) )) )// yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - { - if ( pm->gent->NPC && pm->gent->NPC->rank != RANK_CREWMAN && pm->gent->NPC->rank <= RANK_LT_JG ) - {//reborn who are not acrobats can't do any of these acrobatics - } - else if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - //check for left-wall and right-wall special jumps + } // else no surf close enough to push off of + } else if (pm->cmd.upmove > 0 && pm->waterlevel < 2 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && + !(pm->ps->pm_flags & PMF_JUMP_HELD) + //&& !PM_InKnockDown( pm->ps ) + && pm->gent && WP_ForcePowerAvailable(pm->gent, FP_LEVITATION, 0) && + ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS)))) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + { + if (pm->gent->NPC && pm->gent->NPC->rank != RANK_CREWMAN && + pm->gent->NPC->rank <= RANK_LT_JG) { // reborn who are not acrobats can't do any of these acrobatics + } else if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on the ground + // check for left-wall and right-wall special jumps int anim = -1; - float vertPush = 0; - if ( pm->cmd.rightmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing right - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + float vertPush = 0; + if (pm->cmd.rightmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing right + if (pm->cmd.forwardmove > 0) { // wall-run + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_RIGHT; - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_RIGHT; } - } - else if ( pm->cmd.rightmove < 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing left - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + } else if (pm->cmd.rightmove < 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing left + if (pm->cmd.forwardmove > 0) { // wall-run + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_LEFT; - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_LEFT; } - } - else if ( pm->ps->clientNum && !PM_ControlledByPlayer() && pm->cmd.forwardmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//run up wall, flip backwards - if ( VectorLengthSquared( pm->ps->velocity ) > 40000 /*200*200*/) - {//have to be moving... FIXME: make sure it's opposite the wall... or at least forward? - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->ps->clientNum && !PM_ControlledByPlayer() && pm->cmd.forwardmove > 0 && + pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // run up wall, flip backwards + if (VectorLengthSquared(pm->ps->velocity) > + 40000 /*200*200*/) { // have to be moving... FIXME: make sure it's opposite the wall... or at least forward? + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_BACK1; } - } - else if ( pm->cmd.forwardmove < 0 && !(pm->cmd.buttons&BUTTON_ATTACK) )//pm->ps->clientNum && - {//double-tap back-jump does backflip - if ( pm->ps->velocity[2] >= 0 ) - {//must be going up already + } else if (pm->cmd.forwardmove < 0 && !(pm->cmd.buttons & BUTTON_ATTACK)) // pm->ps->clientNum && + { // double-tap back-jump does backflip + if (pm->ps->velocity[2] >= 0) { // must be going up already vertPush = JUMP_VELOCITY; - anim = PM_PickAnim( pm->gent, BOTH_FLIP_BACK1, BOTH_FLIP_BACK3 ); + anim = PM_PickAnim(pm->gent, BOTH_FLIP_BACK1, BOTH_FLIP_BACK3); } - } - else if ( VectorLengthSquared( pm->ps->velocity ) < 256 /*16 squared*/) - {//not moving - if ( pm->ps->weapon == WP_SABER && (pm->cmd.buttons & BUTTON_ATTACK) && pm->ps->saberAnimLevel == FORCE_LEVEL_2 ) - { + } else if (VectorLengthSquared(pm->ps->velocity) < 256 /*16 squared*/) { // not moving + if (pm->ps->weapon == WP_SABER && (pm->cmd.buttons & BUTTON_ATTACK) && pm->ps->saberAnimLevel == FORCE_LEVEL_2) { /* //Only tavion does these now if ( pm->ps->clientNum && Q_irand( 0, 1 ) ) @@ -936,264 +807,211 @@ static qboolean PM_CheckJump( void ) } } else - */if ( pm->ps->clientNum && !PM_ControlledByPlayer() )//NOTE: pretty much useless, so player never does these - {//jump-spin FIXME: does direction matter? - vertPush = forceJumpStrength[FORCE_LEVEL_2]/1.5f; - anim = Q_irand( BOTH_FJSS_TR_BL, BOTH_FJSS_TL_BR ); + */ + if (pm->ps->clientNum && !PM_ControlledByPlayer()) // NOTE: pretty much useless, so player never does these + { // jump-spin FIXME: does direction matter? + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 1.5f; + anim = Q_irand(BOTH_FJSS_TR_BL, BOTH_FJSS_TL_BR); } } } - if ( anim != -1 && PM_HasAnimation( pm->gent, anim ) ) - { - vec3_t fwd, right, traceto, mins = {pm->mins[0],pm->mins[1],0}, maxs = {pm->maxs[0],pm->maxs[1],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; + if (anim != -1 && PM_HasAnimation(pm->gent, anim)) { + vec3_t fwd, right, traceto, mins = {pm->mins[0], pm->mins[1], 0}, maxs = {pm->maxs[0], pm->maxs[1], 24}, + fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; qboolean doTrace = qfalse; int contents = CONTENTS_SOLID; - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); - //trace-check for a wall, if necc. - switch ( anim ) - { + // trace-check for a wall, if necc. + switch (anim) { case BOTH_WALL_FLIP_LEFT: - //contents |= CONTENTS_BODY; - //NOTE: purposely falls through to next case! + // contents |= CONTENTS_BODY; + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_LEFT: doTrace = qtrue; - VectorMA( pm->ps->origin, -16, right, traceto ); + VectorMA(pm->ps->origin, -16, right, traceto); break; case BOTH_WALL_FLIP_RIGHT: - //contents |= CONTENTS_BODY; - //NOTE: purposely falls through to next case! + // contents |= CONTENTS_BODY; + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_RIGHT: doTrace = qtrue; - VectorMA( pm->ps->origin, 16, right, traceto ); + VectorMA(pm->ps->origin, 16, right, traceto); break; case BOTH_WALL_FLIP_BACK1: - //contents |= CONTENTS_BODY; + // contents |= CONTENTS_BODY; doTrace = qtrue; - VectorMA( pm->ps->origin, 16, fwd, traceto ); + VectorMA(pm->ps->origin, 16, fwd, traceto); break; } - vec3_t idealNormal; - if ( doTrace ) - { - //FIXME: all these jump ones should check for head clearance - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); - if ( anim == BOTH_WALL_FLIP_LEFT ) - {//sigh.. check for bottomless pit to the right - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, 128, right, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + vec3_t idealNormal; + if (doTrace) { + // FIXME: all these jump ones should check for head clearance + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); + if (anim == BOTH_WALL_FLIP_LEFT) { // sigh.. check for bottomless pit to the right + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, 128, right, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } - } - else if ( anim == BOTH_WALL_FLIP_RIGHT ) - {//sigh.. check for bottomless pit to the left - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, -128, right, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + } else if (anim == BOTH_WALL_FLIP_RIGHT) { // sigh.. check for bottomless pit to the left + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, -128, right, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } - } - else if ( anim == BOTH_WALL_FLIP_BACK1 ) - {//sigh.. check for bottomless pit to the rear - trace_t trace2; - vec3_t start; - VectorMA( pm->ps->origin, -128, fwd, traceto ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid ) - { - VectorCopy( trace2.endpos, traceto ); - VectorCopy( traceto, start ); + } else if (anim == BOTH_WALL_FLIP_BACK1) { // sigh.. check for bottomless pit to the rear + trace_t trace2; + vec3_t start; + VectorMA(pm->ps->origin, -128, fwd, traceto); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid) { + VectorCopy(trace2.endpos, traceto); + VectorCopy(traceto, start); traceto[2] -= 384; - pm->trace( &trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0 ); - if ( !trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f ) - {//bottomless pit! - trace.fraction = 1.0f;//way to stop it from doing the side-flip + pm->trace(&trace2, start, mins, maxs, traceto, pm->ps->clientNum, contents, G2_NOCOLLIDE, 0); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction >= 1.0f) { // bottomless pit! + trace.fraction = 1.0f; // way to stop it from doing the side-flip } } } } gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( !doTrace || (trace.fraction < 1.0f&&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(trace.plane.normal,idealNormal)>0.7)) ) - {//there is a wall there - if ( (anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT) || trace.plane.normal[2] == 0.0f ) - {//wall-runs can only run on perfectly flat walls, sorry. - //move me to side - if ( anim == BOTH_WALL_FLIP_LEFT ) - { + if (!doTrace || (trace.fraction < 1.0f && ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7))) { // there is a wall there + if ((anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT) || + trace.plane.normal[2] == 0.0f) { // wall-runs can only run on perfectly flat walls, sorry. + // move me to side + if (anim == BOTH_WALL_FLIP_LEFT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_FLIP_RIGHT ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_FLIP_RIGHT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_FLIP_BACK1 - || anim == BOTH_FLIP_BACK2 - || anim == BOTH_FLIP_BACK3 - || anim == BOTH_WALL_FLIP_BACK1 ) - { + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); + } else if (anim == BOTH_FLIP_BACK1 || anim == BOTH_FLIP_BACK2 || anim == BOTH_FLIP_BACK3 || anim == BOTH_WALL_FLIP_BACK1) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, fwd, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -150, fwd, pm->ps->velocity); } - //kick if jumping off an ent - if ( doTrace && anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT ) - { - if ( pm->gent && trace.entityNum < ENTITYNUM_WORLD ) - { - if ( traceEnt && traceEnt->client && traceEnt->health > 0 && traceEnt->takedamage ) - {//push them away and do pain + // kick if jumping off an ent + if (doTrace && anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT) { + if (pm->gent && trace.entityNum < ENTITYNUM_WORLD) { + if (traceEnt && traceEnt->client && traceEnt->health > 0 && traceEnt->takedamage) { // push them away and do pain vec3_t oppDir; - float strength = VectorNormalize2( pm->ps->velocity, oppDir ); - VectorScale( oppDir, -1, oppDir ); - //FIXME: need knockdown anim - G_Damage( traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, DAMAGE_NO_ARMOR|DAMAGE_NO_HIT_LOC|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - NPC_SetAnim( traceEnt, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_Throw( traceEnt, oppDir, strength ); - G_Sound( traceEnt, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + float strength = VectorNormalize2(pm->ps->velocity, oppDir); + VectorScale(oppDir, -1, oppDir); + // FIXME: need knockdown anim + G_Damage(traceEnt, pm->gent, pm->gent, oppDir, traceEnt->currentOrigin, 10, + DAMAGE_NO_ARMOR | DAMAGE_NO_HIT_LOC | DAMAGE_NO_KNOCKBACK, MOD_MELEE); + NPC_SetAnim(traceEnt, SETANIM_BOTH, BOTH_KNOCKDOWN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_Throw(traceEnt, oppDir, strength); + G_Sound(traceEnt, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); } } } - //up - if ( vertPush ) - { + // up + if (vertPush) { pm->ps->velocity[2] = vertPush; } - //animate me + // animate me int parts = SETANIM_LEGS; - if ( anim == BOTH_BUTTERFLY_LEFT || - anim == BOTH_BUTTERFLY_RIGHT || - anim == BOTH_FJSS_TR_BL || - anim == BOTH_FJSS_TL_BR ) - { + if (anim == BOTH_BUTTERFLY_LEFT || anim == BOTH_BUTTERFLY_RIGHT || anim == BOTH_FJSS_TR_BL || anim == BOTH_FJSS_TL_BR) { parts = SETANIM_BOTH; - pm->cmd.buttons&=~BUTTON_ATTACK; + pm->cmd.buttons &= ~BUTTON_ATTACK; pm->ps->saberMove = LS_NONE; - pm->gent->client->saberTrail.inAction = qtrue;//FIXME: reset this when done! - pm->gent->client->saberTrail.duration = 300;//FIXME: reset this when done! - } - else if ( !pm->ps->weaponTime ) - { + pm->gent->client->saberTrail.inAction = qtrue; // FIXME: reset this when done! + pm->gent->client->saberTrail.duration = 300; // FIXME: reset this when done! + } else if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - if ( anim == BOTH_BUTTERFLY_LEFT - || anim == BOTH_BUTTERFLY_RIGHT - || anim == BOTH_FJSS_TR_BL - || anim == BOTH_FJSS_TL_BR ) - { + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (anim == BOTH_BUTTERFLY_LEFT || anim == BOTH_BUTTERFLY_RIGHT || anim == BOTH_FJSS_TR_BL || anim == BOTH_FJSS_TL_BR) { pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else if ( anim == BOTH_WALL_FLIP_LEFT - || anim == BOTH_WALL_FLIP_RIGHT - || anim == BOTH_WALL_FLIP_BACK1 ) - {//let us do some more moves after this + } else if (anim == BOTH_WALL_FLIP_LEFT || anim == BOTH_WALL_FLIP_RIGHT || + anim == BOTH_WALL_FLIP_BACK1) { // let us do some more moves after this pm->ps->saberAttackChainCount = 0; } - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= (PMF_JUMPING | PMF_SLOW_MO_FALL); pm->cmd.upmove = 0; - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - WP_ForcePowerDrain( pm->gent, FP_LEVITATION, 0 ); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + WP_ForcePowerDrain(pm->gent, FP_LEVITATION, 0); } } } - } - else - {//in the air + } else { // in the air int legsAnim = pm->ps->legsAnim; - if ( legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT ) - {//running on a wall - vec3_t right, traceto, mins = {pm->mins[0],pm->mins[0],0}, maxs = {pm->maxs[0],pm->maxs[0],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; - int anim = -1; - - AngleVectors( fwdAngles, NULL, right, NULL ); - - if ( legsAnim == BOTH_WALL_RUN_LEFT ) - { - if ( pm->ps->legsAnimTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_LEFT ); - if ( pm->ps->legsAnimTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, -16, right, traceto ); + if (legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT) { // running on a wall + vec3_t right, traceto, mins = {pm->mins[0], pm->mins[0], 0}, maxs = {pm->maxs[0], pm->maxs[0], 24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + int anim = -1; + + AngleVectors(fwdAngles, NULL, right, NULL); + + if (legsAnim == BOTH_WALL_RUN_LEFT) { + if (pm->ps->legsAnimTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_LEFT); + if (pm->ps->legsAnimTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, -16, right, traceto); anim = BOTH_WALL_RUN_LEFT_FLIP; } } - } - else if ( legsAnim == BOTH_WALL_RUN_RIGHT ) - { - if ( pm->ps->legsAnimTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_RIGHT ); - if ( pm->ps->legsAnimTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, 16, right, traceto ); + } else if (legsAnim == BOTH_WALL_RUN_RIGHT) { + if (pm->ps->legsAnimTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(pm->gent->client->clientInfo.animFileIndex, BOTH_WALL_RUN_RIGHT); + if (pm->ps->legsAnimTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, 16, right, traceto); anim = BOTH_WALL_RUN_RIGHT_FLIP; } } } - if ( anim != -1 ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY, G2_NOCOLLIDE, 0 ); - if ( trace.fraction < 1.0f ) - {//flip off wall - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + if (anim != -1) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY, G2_NOCOLLIDE, 0); + if (trace.fraction < 1.0f) { // flip off wall + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); } int parts = SETANIM_LEGS; - if ( !pm->ps->weaponTime ) - { + if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( pm, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - //FIXME: do damage to traceEnt, like above? - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + PM_SetAnim(pm, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + // FIXME: do damage to traceEnt, like above? + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; pm->cmd.upmove = 0; } } - if ( pm->cmd.upmove != 0 ) - {//jump failed, so don't try to do normal jump code, just return + if (pm->cmd.upmove != 0) { // jump failed, so don't try to do normal jump code, just return return qfalse; } } @@ -1223,122 +1041,107 @@ static qboolean PM_CheckJump( void ) WP_ForcePowerDrain( pm->gent, FP_LEVITATION, 0 ); } */ - else if ( pm->cmd.forwardmove > 0 //pushing forward - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 - && (level.time - pm->ps->lastOnGround) <= 500 //just jumped - && (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything - {//run up wall, flip backwards - //FIXME: have to be moving... make sure it's opposite the wall... or at least forward? - if ( PM_HasAnimation( pm->gent, BOTH_WALL_FLIP_BACK1 ) ) - { - vec3_t fwd, traceto, mins = {pm->mins[0],pm->mins[1],0}, maxs = {pm->maxs[0],pm->maxs[1],24}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; - trace_t trace; - vec3_t idealNormal; - - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( pm->ps->origin, 32, fwd, traceto ); - - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, G2_NOCOLLIDE, 0 );//FIXME: clip brushes too? - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + else if (pm->cmd.forwardmove > 0 // pushing forward + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && (level.time - pm->ps->lastOnGround) <= 500 // just jumped + && (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1)) // not in a flip or spin or anything + { // run up wall, flip backwards + // FIXME: have to be moving... make sure it's opposite the wall... or at least forward? + if (PM_HasAnimation(pm->gent, BOTH_WALL_FLIP_BACK1)) { + vec3_t fwd, traceto, mins = {pm->mins[0], pm->mins[1], 0}, maxs = {pm->maxs[0], pm->maxs[1], 24}, + fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + vec3_t idealNormal; + + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(pm->ps->origin, 32, fwd, traceto); + + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, G2_NOCOLLIDE, 0); // FIXME: clip brushes too? + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.fraction < 1.0f&&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(trace.plane.normal,idealNormal)>0.7) ) - {//there is a wall there + if (trace.fraction < 1.0f && ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7)) { // there is a wall there pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, fwd, pm->ps->velocity ); - //pm->ps->velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + VectorMA(pm->ps->velocity, -150, fwd, pm->ps->velocity); + // pm->ps->velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + // animate me int parts = SETANIM_LEGS; - if ( !pm->ps->weaponTime ) - { + if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( pm, parts, BOTH_WALL_FLIP_BACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + PM_SetAnim(pm, parts, BOTH_WALL_FLIP_BACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + pm->ps->pm_flags |= PMF_JUMPING | PMF_SLOW_MO_FALL; pm->cmd.upmove = 0; - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - WP_ForcePowerDrain( pm->gent, FP_LEVITATION, 0 ); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + WP_ForcePowerDrain(pm->gent, FP_LEVITATION, 0); } } - } - else - { - //FIXME: if in a butterfly, kick people away? - } - } - } - - if ( pm->gent - && pm->cmd.upmove > 0 - && pm->ps->weapon == WP_SABER - && (pm->ps->weaponTime > 0||pm->cmd.buttons&BUTTON_ATTACK) - && ((pm->ps->clientNum&&!PM_ControlledByPlayer())||((!pm->ps->clientNum||PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode)) ) - {//okay, we just jumped and we're in an attack - if ( !PM_RollingAnim( pm->ps->legsAnim ) - && !PM_InKnockDown( pm->ps ) - && !PM_InDeathAnim() - && !PM_PainAnim( pm->ps->torsoAnim ) - && !PM_FlippingAnim( pm->ps->legsAnim ) - && !PM_SpinningAnim( pm->ps->legsAnim ) - && !PM_SaberInSpecialAttack( pm->ps->torsoAnim ) - && ( PM_SaberInTransitionAny( pm->ps->saberMove ) || PM_SaberInAttack( pm->ps->saberMove ) ) - && PM_InAnimForSaberMove( pm->ps->torsoAnim, pm->ps->saberMove ) ) - {//not in an anim we shouldn't interrupt - //see if it's not too late to start a special jump-attack - float animLength = PM_AnimLength( g_entities[pm->ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)pm->ps->torsoAnim ); - if ( animLength - pm->ps->torsoAnimTimer < 500 ) - {//just started the saberMove - //check for special-case jump attacks - if ( pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5 )//using medium attacks or Tavion) - {//using medium attacks - if ( pm->gent->enemy && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||level.time-pm->ps->lastOnGround<=500) )//on ground or just jumped - {//flip over-forward down-attack - if ( ((!pm->ps->clientNum||PM_ControlledByPlayer())&&pm->cmd.forwardmove >= 0&&!pm->cmd.rightmove) || - (pm->gent->NPC && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) ) - {//only player or acrobat or boss and higher can do this - vec3_t fwdAngles = {0,pm->ps->viewangles[YAW],0}; - if ( pm->gent->enemy->health > 0 - && pm->gent->enemy->maxs[2] > 12 - && (!pm->gent->enemy->client || !PM_InKnockDownOnGround( &pm->gent->enemy->client->ps ) ) - && DistanceSquared( pm->gent->currentOrigin, pm->gent->enemy->currentOrigin ) < 10000 - && InFront( pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, 0.3f ) ) - {//enemy must be alive, not low to ground, close and in front - PM_SetSaberMove( PM_SaberFlipOverAttackMove() ); + } else { + // FIXME: if in a butterfly, kick people away? + } + } + } + + if (pm->gent && pm->cmd.upmove > 0 && pm->ps->weapon == WP_SABER && (pm->ps->weaponTime > 0 || pm->cmd.buttons & BUTTON_ATTACK) && + ((pm->ps->clientNum && !PM_ControlledByPlayer()) || + ((!pm->ps->clientNum || PM_ControlledByPlayer()) && cg.renderingThirdPerson && !cg.zoomMode))) { // okay, we just jumped and we're in an attack + if (!PM_RollingAnim(pm->ps->legsAnim) && !PM_InKnockDown(pm->ps) && !PM_InDeathAnim() && !PM_PainAnim(pm->ps->torsoAnim) && + !PM_FlippingAnim(pm->ps->legsAnim) && !PM_SpinningAnim(pm->ps->legsAnim) && !PM_SaberInSpecialAttack(pm->ps->torsoAnim) && + (PM_SaberInTransitionAny(pm->ps->saberMove) || PM_SaberInAttack(pm->ps->saberMove)) && + PM_InAnimForSaberMove(pm->ps->torsoAnim, pm->ps->saberMove)) { // not in an anim we shouldn't interrupt + // see if it's not too late to start a special jump-attack + float animLength = PM_AnimLength(g_entities[pm->ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)pm->ps->torsoAnim); + if (animLength - pm->ps->torsoAnimTimer < 500) { // just started the saberMove + // check for special-case jump attacks + if (pm->ps->saberAnimLevel == FORCE_LEVEL_2 || pm->ps->saberAnimLevel == FORCE_LEVEL_5) // using medium attacks or Tavion) + { // using medium attacks + if (pm->gent->enemy && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || level.time - pm->ps->lastOnGround <= 500)) // on ground or just jumped + { // flip over-forward down-attack + if (((!pm->ps->clientNum || PM_ControlledByPlayer()) && pm->cmd.forwardmove >= 0 && !pm->cmd.rightmove) || + (pm->gent->NPC && (pm->gent->NPC->rank == RANK_CREWMAN || + pm->gent->NPC->rank >= RANK_LT))) { // only player or acrobat or boss and higher can do this + vec3_t fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + if (pm->gent->enemy->health > 0 && pm->gent->enemy->maxs[2] > 12 && + (!pm->gent->enemy->client || !PM_InKnockDownOnGround(&pm->gent->enemy->client->ps)) && + DistanceSquared(pm->gent->currentOrigin, pm->gent->enemy->currentOrigin) < 10000 && + InFront(pm->gent->enemy->currentOrigin, pm->gent->currentOrigin, fwdAngles, + 0.3f)) { // enemy must be alive, not low to ground, close and in front + PM_SetSaberMove(PM_SaberFlipOverAttackMove()); } } } - } - else if ( pm->ps->saberAnimLevel == FORCE_LEVEL_3 || (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand( 0, 1 )) ) - {//using strong attacks - if ( pm->cmd.forwardmove > 0 //going forward - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 //can force jump - && !(pm->gent->flags&FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one - && ( pm->ps->legsAnim == BOTH_STAND2 - || pm->ps->legsAnim == BOTH_SABERFAST_STANCE - || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE - || level.time-pm->ps->lastStationary <= 500 )//standing or just started moving - && (pm->ps->groundEntityNum != ENTITYNUM_NONE||(pm->ps->clientNum&&!PM_ControlledByPlayer()&&level.time-pm->ps->lastOnGround<=500)))//on ground or just jumped if non-player - {//strong attack: jump-hack - if ( (!pm->ps->clientNum||PM_ControlledByPlayer()) || - (pm->gent && pm->gent->NPC && (pm->gent->NPC->rank==RANK_CREWMAN||pm->gent->NPC->rank>=RANK_LT) ) ) - {//only player or acrobat or boss and higher can do this - PM_SetSaberMove( PM_SaberJumpAttackMove() ); + } else if (pm->ps->saberAnimLevel == FORCE_LEVEL_3 || (pm->gent->client->NPC_class == CLASS_DESANN && !Q_irand(0, 1))) { // using strong attacks + if (pm->cmd.forwardmove > 0 // going forward + && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 // can force jump + && + !(pm->gent->flags & + FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + && (pm->ps->legsAnim == BOTH_STAND2 || pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || + level.time - pm->ps->lastStationary <= 500) // standing or just started moving + && (pm->ps->groundEntityNum != ENTITYNUM_NONE || (pm->ps->clientNum && !PM_ControlledByPlayer() && + level.time - pm->ps->lastOnGround <= 500))) // on ground or just jumped if non-player + { // strong attack: jump-hack + if ((!pm->ps->clientNum || PM_ControlledByPlayer()) || + (pm->gent && pm->gent->NPC && + (pm->gent->NPC->rank == RANK_CREWMAN || + pm->gent->NPC->rank >= RANK_LT))) { // only player or acrobat or boss and higher can do this + PM_SetSaberMove(PM_SaberJumpAttackMove()); } } } } } } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - if ( pm->cmd.upmove > 0 ) - {//no special jumps + if (pm->cmd.upmove > 0) { // no special jumps /* gentity_t *groundEnt = &g_entities[pm->ps->groundEntityNum]; if ( groundEnt && groundEnt->NPC ) @@ -1348,39 +1151,32 @@ static qboolean PM_CheckJump( void ) */ pm->ps->velocity[2] = JUMP_VELOCITY; - pm->ps->forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height + pm->ps->forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height pm->ps->pm_flags |= PMF_JUMPING; } - if ( d_JediAI->integer ) - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_SABER ) - { - Com_Printf( "jumping\n" ); + if (d_JediAI->integer) { + if (pm->ps->clientNum && pm->ps->weapon == WP_SABER) { + Com_Printf("jumping\n"); } } - //Jumping + // Jumping pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->pm_flags |= PMF_JUMP_HELD; pm->ps->groundEntityNum = ENTITYNUM_NONE; pm->ps->jumpZStart = pm->ps->origin[2]; - if ( pm->gent ) - { - if ( !Q3_TaskIDPending( pm->gent, TID_CHAN_VOICE ) ) - { - PM_AddEvent( EV_JUMP ); + if (pm->gent) { + if (!Q3_TaskIDPending(pm->gent, TID_CHAN_VOICE)) { + PM_AddEvent(EV_JUMP); } - } - else - { - PM_AddEvent( EV_JUMP ); + } else { + PM_AddEvent(EV_JUMP); } - //Set the animations - if ( pm->ps->gravity > 0 && !PM_InSpecialJump( pm->ps->legsAnim ) && !PM_InGetUp( pm->ps ) ) - { + // Set the animations + if (pm->ps->gravity > 0 && !PM_InSpecialJump(pm->ps->legsAnim) && !PM_InGetUp(pm->ps)) { PM_JumpForDir(); } @@ -1392,25 +1188,24 @@ static qboolean PM_CheckJump( void ) PM_CheckWaterJump ============= */ -static qboolean PM_CheckWaterJump( void ) { - vec3_t spot; - int cont; - vec3_t flatforward; +static qboolean PM_CheckWaterJump(void) { + vec3_t spot; + int cont; + vec3_t flatforward; if (pm->ps->pm_time) { return qfalse; } - if ( pm->cmd.forwardmove <= 0 && pm->cmd.upmove <= 0 ) - {//they must not want to get out? + if (pm->cmd.forwardmove <= 0 && pm->cmd.upmove <= 0) { // they must not want to get out? return qfalse; } // check for water jump - if ( pm->waterlevel != 2 ) { + if (pm->waterlevel != 2) { return qfalse; } - if ( pm->watertype & CONTENTS_LADDER ) { + if (pm->watertype & CONTENTS_LADDER) { if (pm->ps->velocity[2] <= 0) return qfalse; } @@ -1418,24 +1213,24 @@ static qboolean PM_CheckWaterJump( void ) { flatforward[0] = pml.forward[0]; flatforward[1] = pml.forward[1]; flatforward[2] = 0; - VectorNormalize( flatforward ); + VectorNormalize(flatforward); - VectorMA( pm->ps->origin, 30, flatforward, spot ); + VectorMA(pm->ps->origin, 30, flatforward, spot); spot[2] += 24; - cont = pm->pointcontents (spot, pm->ps->clientNum ); - if ( !(cont & CONTENTS_SOLID) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (!(cont & CONTENTS_SOLID)) { return qfalse; } spot[2] += 16; - cont = pm->pointcontents( spot, pm->ps->clientNum ); - if ( cont&(CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA|CONTENTS_BODY) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (cont & (CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA | CONTENTS_BODY)) { return qfalse; } // jump out of water - VectorScale( pml.forward, 200, pm->ps->velocity ); - pm->ps->velocity[2] = 350+((pm->ps->waterheight-pm->ps->origin[2])*2); + VectorScale(pml.forward, 200, pm->ps->velocity); + pm->ps->velocity[2] = 350 + ((pm->ps->waterheight - pm->ps->origin[2]) * 2); pm->ps->pm_flags |= PMF_TIME_WATERJUMP; pm->ps->pm_time = 2000; @@ -1445,7 +1240,6 @@ static qboolean PM_CheckWaterJump( void ) { //============================================================================ - /* =================== PM_WaterJumpMove @@ -1453,15 +1247,13 @@ PM_WaterJumpMove Flying out of the water =================== */ -static void PM_WaterJumpMove( void ) -{ +static void PM_WaterJumpMove(void) { // waterjump has no control, but falls - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; - if (pm->ps->velocity[2] < 0) - { + if (pm->ps->velocity[2] < 0) { // cancel as soon as we are falling down again pm->ps->pm_flags &= ~PMF_ALL_TIMES; pm->ps->pm_time = 0; @@ -1474,21 +1266,19 @@ PM_WaterMove =================== */ -static void PM_WaterMove( void ) { - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float vel; - - if ( PM_CheckWaterJump() ) { +static void PM_WaterMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float vel; + + if (PM_CheckWaterJump()) { PM_WaterJumpMove(); return; - } - else if ( pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->waterlevel < 3 ) - { - if ( PM_CheckJump () ) { + } else if (pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->waterlevel < 3) { + if (PM_CheckJump()) { // jumped away return; } @@ -1507,142 +1297,124 @@ static void PM_WaterMove( void ) { } } #endif - PM_Friction (); + PM_Friction(); - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; - if ( pm->watertype & CONTENTS_LADDER ) { + if (pm->watertype & CONTENTS_LADDER) { wishvel[2] = 0; } else { - wishvel[2] = -60; // sink towards bottom + wishvel[2] = -60; // sink towards bottom } } else { - for (i=0 ; i<3 ; i++) { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } wishvel[2] += scale * pm->cmd.upmove; - if ( !(pm->watertype&CONTENTS_LADDER) ) //ladder + if (!(pm->watertype & CONTENTS_LADDER)) // ladder { - float depth = (pm->ps->origin[2]+pm->gent->client->standheight)-pm->ps->waterheight; - if ( depth >= 12 ) - {//too high! - wishvel[2] -= 120; // sink towards bottom - if ( wishvel[2] > 0 ) - { + float depth = (pm->ps->origin[2] + pm->gent->client->standheight) - pm->ps->waterheight; + if (depth >= 12) { // too high! + wishvel[2] -= 120; // sink towards bottom + if (wishvel[2] > 0) { wishvel[2] = 0; } - } - else if ( pm->ps->waterHeightLevel >= WHL_UNDER )//!depth && pm->waterlevel == 3 ) + } else if (pm->ps->waterHeightLevel >= WHL_UNDER) //! depth && pm->waterlevel == 3 ) { - } - else if ( depth < 12 ) - {//still deep - wishvel[2] -= 60; // sink towards bottom - if ( wishvel[2] > 30 ) - { + } else if (depth < 12) { // still deep + wishvel[2] -= 60; // sink towards bottom + if (wishvel[2] > 30) { wishvel[2] = 30; } } } } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); - if ( pm->watertype & CONTENTS_LADDER ) //ladder + if (pm->watertype & CONTENTS_LADDER) // ladder { - if ( wishspeed > pm->ps->speed * pm_ladderScale ) { + if (wishspeed > pm->ps->speed * pm_ladderScale) { wishspeed = pm->ps->speed * pm_ladderScale; } - PM_Accelerate( wishdir, wishspeed, pm_flyaccelerate ); + PM_Accelerate(wishdir, wishspeed, pm_flyaccelerate); } else { - if ( pm->ps->gravity < 0 ) - {//float up + if (pm->ps->gravity < 0) { // float up pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; } - if ( wishspeed > pm->ps->speed * pm_swimScale ) { + if (wishspeed > pm->ps->speed * pm_swimScale) { wishspeed = pm->ps->speed * pm_swimScale; } - PM_Accelerate( wishdir, wishspeed, pm_wateraccelerate ); + PM_Accelerate(wishdir, wishspeed, pm_wateraccelerate); } // make sure we can go up slopes easily under water - if ( pml.groundPlane && DotProduct( pm->ps->velocity, pml.groundTrace.plane.normal ) < 0 ) { + if (pml.groundPlane && DotProduct(pm->ps->velocity, pml.groundTrace.plane.normal) < 0) { vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); VectorNormalize(pm->ps->velocity); VectorScale(pm->ps->velocity, vel, pm->ps->velocity); } - PM_SlideMove( qfalse ); + PM_SlideMove(qfalse); } - /* =================== PM_FlyVehicleMove =================== */ -static void PM_FlyVehicleMove( void ) -{ - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float zVel; +static void PM_FlyVehicleMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float zVel; // normal slowdown - if ( pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//falling + if (pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE) { // falling zVel = pm->ps->velocity[2]; - PM_Friction (); + PM_Friction(); pm->ps->velocity[2] = zVel; - } - else - { - PM_Friction (); - if ( pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { - pm->ps->velocity[2] = 0; // ignore slope movement + } else { + PM_Friction(); + if (pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE) { + pm->ps->velocity[2] = 0; // ignore slope movement } } - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) - { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; wishvel[2] = 0; - } - else - { - for (i=0 ; i<3 ; i++) - { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } wishvel[2] += scale * pm->cmd.upmove; } - VectorCopy( wishvel, wishdir ); - wishspeed = VectorNormalize( wishdir ); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - PM_Accelerate( wishdir, wishspeed, 100 ); + PM_Accelerate(wishdir, wishspeed, 100); - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); } /* @@ -1652,74 +1424,59 @@ PM_FlyMove Only with the flight powerup =================== */ -static void PM_FlyMove( void ) -{ - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float accel; - qboolean lowGravMove = qfalse; +static void PM_FlyMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float accel; + qboolean lowGravMove = qfalse; // normal slowdown - PM_Friction (); + PM_Friction(); - if ( pm->ps->gravity <= 0 && (!pm->ps->clientNum || (pm->gent&&pm->gent->NPC&&pm->gent->NPC->stats.moveType == MT_RUNJUMP)) ) - { + if (pm->ps->gravity <= 0 && (!pm->ps->clientNum || (pm->gent && pm->gent->NPC && pm->gent->NPC->stats.moveType == MT_RUNJUMP))) { PM_CheckJump(); accel = 1.0f; pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; - pm->ps->jumpZStart = pm->ps->origin[2];//so we don't take a lot of damage when the gravity comes back on + pm->ps->jumpZStart = pm->ps->origin[2]; // so we don't take a lot of damage when the gravity comes back on lowGravMove = qtrue; - } - else - { + } else { accel = pm_flyaccelerate; } - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) - { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; wishvel[2] = 0; - } - else - { - for (i=0 ; i<3 ; i++) - { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } - if ( lowGravMove ) - { + if (lowGravMove) { wishvel[2] += scale * pm->cmd.upmove; - VectorScale( wishvel, 0.5f, wishvel ); + VectorScale(wishvel, 0.5f, wishvel); } } - VectorCopy( wishvel, wishdir ); - wishspeed = VectorNormalize( wishdir ); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - PM_Accelerate( wishdir, wishspeed, accel ); + PM_Accelerate(wishdir, wishspeed, accel); - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); } -qboolean PM_GroundSlideOkay( float zNormal ) -{ - if ( zNormal > 0 ) - { - if ( pm->ps->velocity[2] > 0 ) - { - if ( pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP ) - { +qboolean PM_GroundSlideOkay(float zNormal) { + if (zNormal > 0) { + if (pm->ps->velocity[2] > 0) { + if (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP) { return qfalse; } } @@ -1732,15 +1489,15 @@ PM_AirMove =================== */ -static void PM_AirMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - //float scale; - usercmd_t cmd; - float gravMod = 1.0f; +static void PM_AirMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + // float scale; + usercmd_t cmd; + float gravMod = 1.0f; #if METROID_JUMP PM_CheckJump(); @@ -1752,7 +1509,7 @@ static void PM_AirMove( void ) { smove = pm->cmd.rightmove; cmd = pm->cmd; - PM_CmdScale( &cmd ); + PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -1760,22 +1517,19 @@ static void PM_AirMove( void ) { // project moves down to flat plane pml.forward[2] = 0; pml.right[2] = 0; - VectorNormalize (pml.forward); - VectorNormalize (pml.right); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); - if ( (pm->ps->pm_flags&PMF_SLOW_MO_FALL) ) - {//no air-control - VectorClear( wishvel ); - } - else - { - for ( i = 0 ; i < 2 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if ((pm->ps->pm_flags & PMF_SLOW_MO_FALL)) { // no air-control + VectorClear(wishvel); + } else { + for (i = 0; i < 2; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } wishvel[2] = 0; } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); /* @@ -1787,36 +1541,28 @@ static void PM_AirMove( void ) { else { */ - if ( ( DotProduct (pm->ps->velocity, wishdir) ) < 0.0f ) - {//Encourage deceleration away from the current velocity - wishspeed *= pm_airDecelRate; - } + if ((DotProduct(pm->ps->velocity, wishdir)) < 0.0f) { // Encourage deceleration away from the current velocity + wishspeed *= pm_airDecelRate; + } - // not on ground, so little effect on velocity - PM_Accelerate( wishdir, wishspeed, pm_airaccelerate ); + // not on ground, so little effect on velocity + PM_Accelerate(wishdir, wishspeed, pm_airaccelerate); //} // we may have a ground plane that is very steep, even // though we don't have a groundentity // slide along the steep plane - if ( pml.groundPlane ) - { - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - { - PM_ClipVelocity( pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } - if ( !pm->ps->clientNum - && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 - && pm->ps->forceJumpZStart - && pm->ps->velocity[2] > 0 ) - {//I am force jumping and I'm not holding the button anymore - float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart + (pm->ps->velocity[2]*pml.frametime); + if (!pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && pm->ps->forceJumpZStart && + pm->ps->velocity[2] > 0) { // I am force jumping and I'm not holding the button anymore + float curHeight = pm->ps->origin[2] - pm->ps->forceJumpZStart + (pm->ps->velocity[2] * pml.frametime); float maxJumpHeight = forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]; - if ( curHeight >= maxJumpHeight ) - {//reached top, cut velocity + if (curHeight >= maxJumpHeight) { // reached top, cut velocity pm->ps->velocity[2] = 0; /* //put on a cvar? @@ -1841,34 +1587,32 @@ static void PM_AirMove( void ) { } */ - PM_StepSlideMove( gravMod ); + PM_StepSlideMove(gravMod); } - /* =================== PM_WalkMove =================== */ -static void PM_WalkMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; - usercmd_t cmd; - float accelerate; - float vel; - - if ( pm->ps->gravity < 0 ) - {//float away +static void PM_WalkMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; + usercmd_t cmd; + float accelerate; + float vel; + + if (pm->ps->gravity < 0) { // float away pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; pm->ps->groundEntityNum = ENTITYNUM_NONE; pml.groundPlane = qfalse; pml.walking = qfalse; - if ( pm->waterlevel > 1 ) { + if (pm->waterlevel > 1) { PM_WaterMove(); } else { PM_AirMove(); @@ -1876,16 +1620,15 @@ static void PM_WalkMove( void ) { return; } - if ( pm->waterlevel > 2 && DotProduct( pml.forward, pml.groundTrace.plane.normal ) > 0 ) { + if (pm->waterlevel > 2 && DotProduct(pml.forward, pml.groundTrace.plane.normal) > 0) { // begin swimming PM_WaterMove(); return; } - - if ( PM_CheckJump () ) { + if (PM_CheckJump()) { // jumped away - if ( pm->waterlevel > 1 ) { + if (pm->waterlevel > 1) { PM_WaterMove(); } else { PM_AirMove(); @@ -1893,35 +1636,31 @@ static void PM_WalkMove( void ) { return; } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE &&//on ground - pm->ps->velocity[2] <= 0 &&//not going up - pm->ps->pm_flags&PMF_TIME_KNOCKBACK )//knockback fimter on (stops friction) + if (pm->ps->groundEntityNum != ENTITYNUM_NONE && // on ground + pm->ps->velocity[2] <= 0 && // not going up + pm->ps->pm_flags & PMF_TIME_KNOCKBACK) // knockback fimter on (stops friction) { pm->ps->pm_flags &= ~PMF_TIME_KNOCKBACK; } qboolean slide = qfalse; - if ( pm->ps->pm_type == PM_DEAD ) - {//corpse - if ( g_entities[pm->ps->groundEntityNum].client ) - {//on a client - if ( g_entities[pm->ps->groundEntityNum].health > 0 ) - {//a living client - //no friction + if (pm->ps->pm_type == PM_DEAD) { // corpse + if (g_entities[pm->ps->groundEntityNum].client) { // on a client + if (g_entities[pm->ps->groundEntityNum].health > 0) { // a living client + // no friction slide = qtrue; } } } - if ( !slide ) - { - PM_Friction (); + if (!slide) { + PM_Friction(); } fmove = pm->cmd.forwardmove; smove = pm->cmd.rightmove; cmd = pm->cmd; - scale = PM_CmdScale( &cmd ); + scale = PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -1931,166 +1670,148 @@ static void PM_WalkMove( void ) { pml.right[2] = 0; // project the forward and right directions onto the ground plane - PM_ClipVelocity (pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP ); - PM_ClipVelocity (pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP ); + PM_ClipVelocity(pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP); + PM_ClipVelocity(pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP); // - VectorNormalize (pml.forward); - VectorNormalize (pml.right); - - if ( pm->ps->clientNum && !VectorCompare( pm->ps->moveDir, vec3_origin ) ) - {//NPC - //FIXME: what if the ucmd was set directly.... sigh.... check movedir timestamp? - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); + + if (pm->ps->clientNum && !VectorCompare(pm->ps->moveDir, vec3_origin)) { // NPC + // FIXME: what if the ucmd was set directly.... sigh.... check movedir timestamp? + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); wishspeed = pm->ps->speed; - } - else - { - for ( i = 0 ; i < 3 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } // when going up or down slopes the wish velocity should Not be zero - // wishvel[2] = 0; + // wishvel[2] = 0; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // clamp the speed lower if ducking - if ( pm->ps->pm_flags & PMF_DUCKED && !PM_InKnockDown( pm->ps ) ) - { - if ( wishspeed > pm->ps->speed * pm_duckScale ) - { + if (pm->ps->pm_flags & PMF_DUCKED && !PM_InKnockDown(pm->ps)) { + if (wishspeed > pm->ps->speed * pm_duckScale) { wishspeed = pm->ps->speed * pm_duckScale; } } // clamp the speed lower if wading or walking on the bottom - if ( pm->waterlevel ) { - float waterScale; + if (pm->waterlevel) { + float waterScale; waterScale = pm->waterlevel / 3.0; - waterScale = 1.0 - ( 1.0 - pm_swimScale ) * waterScale; - if ( wishspeed > pm->ps->speed * waterScale ) { + waterScale = 1.0 - (1.0 - pm_swimScale) * waterScale; + if (wishspeed > pm->ps->speed * waterScale) { wishspeed = pm->ps->speed * waterScale; } } // when a player gets hit, they temporarily lose // full control, which allows them to be moved a bit - if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || (pm->ps->pm_flags&PMF_TIME_KNOCKBACK) || (pm->ps->pm_flags&PMF_TIME_NOFRICTION) ) { + if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || (pm->ps->pm_flags & PMF_TIME_KNOCKBACK) || (pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { accelerate = pm_airaccelerate; } else { accelerate = pm_accelerate; } - PM_Accelerate (wishdir, wishspeed, accelerate); + PM_Accelerate(wishdir, wishspeed, accelerate); - //Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); - //Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); + // Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); + // Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); - if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK || (pm->ps->pm_flags&PMF_TIME_NOFRICTION) ) { - if ( pm->ps->gravity >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE && !VectorLengthSquared( pm->ps->velocity ) && pml.groundTrace.plane.normal[2] == 1.0 ) - {//on ground and not moving and on level ground, no reason to do stupid fucking gravity with the clipvelocity!!!! - } - else - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) ) - { + if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK || (pm->ps->pm_flags & PMF_TIME_NOFRICTION)) { + if (pm->ps->gravity >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE && !VectorLengthSquared(pm->ps->velocity) && + pml.groundTrace.plane.normal[2] == + 1.0) { // on ground and not moving and on level ground, no reason to do stupid fucking gravity with the clipvelocity!!!! + } else { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED)) { pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; } } } else { // don't reset the z velocity for slopes -// pm->ps->velocity[2] = 0; + // pm->ps->velocity[2] = 0; } vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); // don't decrease velocity when going up or down a slope VectorNormalize(pm->ps->velocity); VectorScale(pm->ps->velocity, vel, pm->ps->velocity); // don't do anything if standing still - if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] ) { + if (!pm->ps->velocity[0] && !pm->ps->velocity[1]) { return; } - if ( pm->ps->gravity <= 0 ) - {//need to apply gravity since we're going to float up from ground - PM_StepSlideMove( 1 ); - } - else - { - PM_StepSlideMove( 0 ); + if (pm->ps->gravity <= 0) { // need to apply gravity since we're going to float up from ground + PM_StepSlideMove(1); + } else { + PM_StepSlideMove(0); } - //Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); - + // Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); } - /* ============== PM_DeadMove ============== */ -static void PM_DeadMove( void ) { - float forward; +static void PM_DeadMove(void) { + float forward; - if ( !pml.walking ) { + if (!pml.walking) { return; } // extra friction - forward = VectorLength (pm->ps->velocity); + forward = VectorLength(pm->ps->velocity); forward -= 20; - if ( forward <= 0 ) { - VectorClear (pm->ps->velocity); + if (forward <= 0) { + VectorClear(pm->ps->velocity); } else { - VectorNormalize (pm->ps->velocity); - VectorScale (pm->ps->velocity, forward, pm->ps->velocity); + VectorNormalize(pm->ps->velocity); + VectorScale(pm->ps->velocity, forward, pm->ps->velocity); } } - /* =============== PM_NoclipMove =============== */ -static void PM_NoclipMove( void ) { - float speed, drop, friction, control, newspeed; - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; - - if(pm->gent && pm->gent->client) - { +static void PM_NoclipMove(void) { + float speed, drop, friction, control, newspeed; + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; + + if (pm->gent && pm->gent->client) { pm->ps->viewheight = pm->gent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET; -// if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) -// { -// assert(0); -// } + // if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) + // { + // assert(0); + // } - VectorCopy( pm->gent->mins, pm->mins ); - VectorCopy( pm->gent->maxs, pm->maxs ); - } - else - { - pm->ps->viewheight = DEFAULT_MAXS_2 + STANDARD_VIEWHEIGHT_OFFSET;//DEFAULT_VIEWHEIGHT; + VectorCopy(pm->gent->mins, pm->mins); + VectorCopy(pm->gent->maxs, pm->maxs); + } else { + pm->ps->viewheight = DEFAULT_MAXS_2 + STANDARD_VIEWHEIGHT_OFFSET; // DEFAULT_VIEWHEIGHT; - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -2105,18 +1826,15 @@ static void PM_NoclipMove( void ) { // friction - speed = VectorLength (pm->ps->velocity); - if (speed < 1) - { - VectorCopy (vec3_origin, pm->ps->velocity); - } - else - { + speed = VectorLength(pm->ps->velocity); + if (speed < 1) { + VectorCopy(vec3_origin, pm->ps->velocity); + } else { drop = 0; - friction = pm_friction*1.5; // extra friction + friction = pm_friction * 1.5; // extra friction control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; // scale the velocity newspeed = speed - drop; @@ -2124,33 +1842,33 @@ static void PM_NoclipMove( void ) { newspeed = 0; newspeed /= speed; - VectorScale (pm->ps->velocity, newspeed, pm->ps->velocity); + VectorScale(pm->ps->velocity, newspeed, pm->ps->velocity); } // accelerate - scale = PM_CmdScale( &pm->cmd ); - if (pm->cmd.buttons & BUTTON_ATTACK) { //turbo boost + scale = PM_CmdScale(&pm->cmd); + if (pm->cmd.buttons & BUTTON_ATTACK) { // turbo boost scale *= 10; } - if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { //turbo boost + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // turbo boost scale *= 10; } fmove = pm->cmd.forwardmove; smove = pm->cmd.rightmove; - for (i=0 ; i<3 ; i++) - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + for (i = 0; i < 3; i++) + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; wishvel[2] += pm->cmd.upmove; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; - PM_Accelerate( wishdir, wishspeed, pm_accelerate ); + PM_Accelerate(wishdir, wishspeed, pm_accelerate); // move - VectorMA (pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); + VectorMA(pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); } //============================================================================ @@ -2162,60 +1880,45 @@ PM_FootstepForSurface Returns an event number apropriate for the groundsurface ================ */ -static int PM_FootstepForSurface( void ) { - if ( pml.groundTrace.surfaceFlags & SURF_NOSTEPS ) { +static int PM_FootstepForSurface(void) { + if (pml.groundTrace.surfaceFlags & SURF_NOSTEPS) { return 0; } - if ( pml.groundTrace.surfaceFlags & SURF_METALSTEPS ) { + if (pml.groundTrace.surfaceFlags & SURF_METALSTEPS) { return EV_FOOTSTEP_METAL; } return EV_FOOTSTEP; } -static float PM_DamageForDelta( int delta ) -{ +static float PM_DamageForDelta(int delta) { float damage = delta; - if ( pm->gent->NPC ) - { - if ( pm->ps->weapon == WP_SABER ) - {//FIXME: for now Jedi take no falling damage, but really they should if pushed off? + if (pm->gent->NPC) { + if (pm->ps->weapon == WP_SABER) { // FIXME: for now Jedi take no falling damage, but really they should if pushed off? damage = 0; } - } - else if ( !pm->ps->clientNum ) - { - if ( damage < 50 ) - { - if ( damage > 24 ) - { + } else if (!pm->ps->clientNum) { + if (damage < 50) { + if (damage > 24) { damage = damage - 25; } - } - else - { + } else { damage /= 2; } } - return damage/2; + return damage / 2; } -static void PM_CrashLandDamage( int damage ) -{ - if ( pm->gent ) - { - if ( pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT ) - { +static void PM_CrashLandDamage(int damage) { + if (pm->gent) { + if (pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT) { damage = 1000; - } - else - { - damage = PM_DamageForDelta( damage ); + } else { + damage = PM_DamageForDelta(damage); } - if ( damage && !(pm->gent->flags&FL_NO_IMPACT_DMG) ) - { - pm->gent->painDebounceTime = level.time + 200; // no normal pain sound - G_Damage( pm->gent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING ); + if (damage && !(pm->gent->flags & FL_NO_IMPACT_DMG)) { + pm->gent->painDebounceTime = level.time + 200; // no normal pain sound + G_Damage(pm->gent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING); } } } @@ -2267,38 +1970,31 @@ static float PM_CrashLandDelta( vec3_t org, vec3_t prevOrg, vec3_t prev_vel, flo } */ -static float PM_CrashLandDelta( vec3_t prev_vel, int waterlevel ) -{ +static float PM_CrashLandDelta(vec3_t prev_vel, int waterlevel) { float delta; - if ( pm->waterlevel == 3 ) - { + if (pm->waterlevel == 3) { return 0; } - delta = fabs(prev_vel[2])/10;//VectorLength( prev_vel ) + delta = fabs(prev_vel[2]) / 10; // VectorLength( prev_vel ) // reduce falling damage if there is standing water - if ( pm->waterlevel == 2 ) - { + if (pm->waterlevel == 2) { delta *= 0.25; } - if ( pm->waterlevel == 1 ) - { + if (pm->waterlevel == 1) { delta *= 0.5; } return delta; } -int PM_GetLandingAnim( void ) -{ +int PM_GetLandingAnim(void) { int anim = pm->ps->legsAnim; - if ( PM_SpinningAnim( anim ) || PM_SaberInSpecialAttack( anim ) ) - { + if (PM_SpinningAnim(anim) || PM_SaberInSpecialAttack(anim)) { return -1; } - switch ( anim ) - { + switch (anim) { case BOTH_FORCEJUMPLEFT1: case BOTH_FORCEINAIRLEFT1: anim = BOTH_FORCELANDLEFT1; @@ -2342,24 +2038,20 @@ int PM_GetLandingAnim( void ) case BOTH_ARIAL_F1: case BOTH_CARTWHEEL_LEFT: case BOTH_CARTWHEEL_RIGHT: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# anim = -1; break; - case BOTH_WALL_RUN_LEFT://# - case BOTH_WALL_RUN_RIGHT://# - if ( pm->ps->legsAnimTimer > 500 ) - {//only land at end of anim + case BOTH_WALL_RUN_LEFT: //# + case BOTH_WALL_RUN_RIGHT: //# + if (pm->ps->legsAnimTimer > 500) { // only land at end of anim return -1; } - //NOTE: falls through on purpose! + // NOTE: falls through on purpose! default: - if ( pm->ps->pm_flags & PMF_BACKWARDS_JUMP ) - { + if (pm->ps->pm_flags & PMF_BACKWARDS_JUMP) { anim = BOTH_LANDBACK1; - } - else - { + } else { anim = BOTH_LAND1; } break; @@ -2367,136 +2059,95 @@ int PM_GetLandingAnim( void ) return anim; } -static qboolean PM_TryRoll( void ) -{ - float rollDist = 192;//was 64; - if ( PM_SaberInAttack( pm->ps->saberMove ) || PM_SaberInSpecialAttack( pm->ps->torsoAnim ) - || PM_SpinningSaberAnim( pm->ps->legsAnim ) - || (!pm->ps->clientNum&&PM_SaberInStart( pm->ps->saberMove )) ) - {//attacking or spinning (or, if player, starting an attack) +static qboolean PM_TryRoll(void) { + float rollDist = 192; // was 64; + if (PM_SaberInAttack(pm->ps->saberMove) || PM_SaberInSpecialAttack(pm->ps->torsoAnim) || PM_SpinningSaberAnim(pm->ps->legsAnim) || + (!pm->ps->clientNum && PM_SaberInStart(pm->ps->saberMove))) { // attacking or spinning (or, if player, starting an attack) return qfalse; } - if ( !pm->ps->clientNum && (!cg.renderingThirdPerson || cg.zoomMode) ) - {//player can't do this in 1st person + if (!pm->ps->clientNum && (!cg.renderingThirdPerson || cg.zoomMode)) { // player can't do this in 1st person return qfalse; } - if ( !pm->gent ) - { + if (!pm->gent) { return qfalse; } - if ( pm->ps->clientNum && pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_NONE ) - {//only jedi + if (pm->ps->clientNum && pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_NONE) { // only jedi return qfalse; } - if ( pm->gent && pm->gent->NPC ) - { - if ( pm->gent->NPC->rank != RANK_CREWMAN && pm->gent->NPC->rank < RANK_LT_JG ) - {//reborn who are not acrobats or fencers can't do any of these acrobatics + if (pm->gent && pm->gent->NPC) { + if (pm->gent->NPC->rank != RANK_CREWMAN && pm->gent->NPC->rank < RANK_LT_JG) { // reborn who are not acrobats or fencers can't do any of these + // acrobatics return qfalse; } - if ( pm->gent->NPC->scriptFlags&SCF_NO_ACROBATICS ) - { + if (pm->gent->NPC->scriptFlags & SCF_NO_ACROBATICS) { return qfalse; } } - vec3_t fwd, right, traceto, - mins = { pm->mins[0], pm->mins[1], pm->mins[2] + STEPSIZE }, - maxs = { pm->maxs[0], pm->maxs[1], (float)pm->gent->client->crouchheight }, - fwdAngles = { 0, pm->ps->viewangles[YAW], 0 }; - trace_t trace; - int anim = -1; - AngleVectors( fwdAngles, fwd, right, NULL ); - //FIXME: trace ahead for clearance to roll - if ( pm->cmd.forwardmove ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { + vec3_t fwd, right, traceto, mins = {pm->mins[0], pm->mins[1], pm->mins[2] + STEPSIZE}, + maxs = {pm->maxs[0], pm->maxs[1], (float)pm->gent->client->crouchheight}, fwdAngles = {0, pm->ps->viewangles[YAW], 0}; + trace_t trace; + int anim = -1; + AngleVectors(fwdAngles, fwd, right, NULL); + // FIXME: trace ahead for clearance to roll + if (pm->cmd.forwardmove) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { anim = BOTH_ROLL_B; - VectorMA( pm->ps->origin, -rollDist, fwd, traceto ); - } - else - { + VectorMA(pm->ps->origin, -rollDist, fwd, traceto); + } else { anim = BOTH_ROLL_F; - VectorMA( pm->ps->origin, rollDist, fwd, traceto ); + VectorMA(pm->ps->origin, rollDist, fwd, traceto); } - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_ROLL_R; - VectorMA( pm->ps->origin, rollDist, right, traceto ); - } - else if ( pm->cmd.rightmove < 0 ) - { + VectorMA(pm->ps->origin, rollDist, right, traceto); + } else if (pm->cmd.rightmove < 0) { anim = BOTH_ROLL_L; - VectorMA( pm->ps->origin, -rollDist, right, traceto ); + VectorMA(pm->ps->origin, -rollDist, right, traceto); + } else { //??? } - else - {//??? - } - if ( anim != -1 ) - { + if (anim != -1) { qboolean roll = qfalse; - int clipmask = CONTENTS_SOLID; - if ( pm->ps->clientNum ) - { - clipmask |= (CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP); - } - else - { - if ( pm->gent && pm->gent->enemy && pm->gent->enemy->health > 0 ) - {//player can always roll in combat + int clipmask = CONTENTS_SOLID; + if (pm->ps->clientNum) { + clipmask |= (CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); + } else { + if (pm->gent && pm->gent->enemy && pm->gent->enemy->health > 0) { // player can always roll in combat roll = qtrue; - } - else - { + } else { clipmask |= CONTENTS_PLAYERCLIP; } } - if ( !roll ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f ) - {//okay, clear, check for a bottomless drop - vec3_t top; - VectorCopy( traceto, top ); + if (!roll) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, clipmask, G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f) { // okay, clear, check for a bottomless drop + vec3_t top; + VectorCopy(traceto, top); traceto[2] -= 256; - pm->trace( &trace, top, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, G2_NOCOLLIDE, 0 ); - if ( trace.fraction < 1.0f ) - {//not a bottomless drop + pm->trace(&trace, top, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID, G2_NOCOLLIDE, 0); + if (trace.fraction < 1.0f) { // not a bottomless drop roll = qtrue; } - } - else - {//hit an architectural obstruction - if ( pm->ps->clientNum ) - {//NPCs don't care about rolling into walls, just off ledges - if ( !(trace.contents&CONTENTS_BOTCLIP) ) - { + } else { // hit an architectural obstruction + if (pm->ps->clientNum) { // NPCs don't care about rolling into walls, just off ledges + if (!(trace.contents & CONTENTS_BOTCLIP)) { roll = qtrue; } - } - else if ( G_EntIsDoor( trace.entityNum ) ) - {//okay to roll into a door - if ( G_EntIsUnlockedDoor( trace.entityNum ) ) - {//if it's an auto-door + } else if (G_EntIsDoor(trace.entityNum)) { // okay to roll into a door + if (G_EntIsUnlockedDoor(trace.entityNum)) { // if it's an auto-door roll = qtrue; } - } - else - {//check other conditions + } else { // check other conditions gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && (traceEnt->svFlags&SVF_GLASS_BRUSH) ) - {//okay to roll through glass + if (traceEnt && (traceEnt->svFlags & SVF_GLASS_BRUSH)) { // okay to roll through glass roll = qtrue; } } } } - if ( roll ) - { - PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - pm->ps->weaponTime = pm->ps->torsoAnimTimer - 200;//just to make sure it's cleared when roll is done - PM_AddEvent( EV_ROLL ); + if (roll) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->weaponTime = pm->ps->torsoAnimTimer - 200; // just to make sure it's cleared when roll is done + PM_AddEvent(EV_ROLL); pm->ps->saberMove = LS_NONE; return qtrue; } @@ -2511,130 +2162,99 @@ PM_CrashLand Check for hard landings that generate sound events ================= */ -static void PM_CrashLand( void ) -{ - float delta = 0; - qboolean forceLanding = qfalse; +static void PM_CrashLand(void) { + float delta = 0; + qboolean forceLanding = qfalse; - if ( pm->ps->pm_flags&PMF_TRIGGER_PUSHED ) - { - delta = 21;//? + if (pm->ps->pm_flags & PMF_TRIGGER_PUSHED) { + delta = 21; //? forceLanding = qtrue; - } - else - { - if ( pm->gent && pm->gent->NPC && pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT ) - {//have to do death on impact if we are falling to our death, FIXME: should we avoid any additional damage this func? - PM_CrashLandDamage( 1000 ); + } else { + if (pm->gent && pm->gent->NPC && + pm->gent->NPC->aiFlags & + NPCAI_DIE_ON_IMPACT) { // have to do death on impact if we are falling to our death, FIXME: should we avoid any additional damage this func? + PM_CrashLandDamage(1000); } - if ( pm->ps->jumpZStart && (pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_1||!pm->ps->clientNum) ) - {//we were force-jumping - if ( pm->ps->origin[2] >= pm->ps->jumpZStart ) - {//we landed at same height or higher than we landed - if ( pm->ps->forceJumpZStart ) - {//we were force-jumping + if (pm->ps->jumpZStart && (pm->ps->forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_1 || !pm->ps->clientNum)) { // we were force-jumping + if (pm->ps->origin[2] >= pm->ps->jumpZStart) { // we landed at same height or higher than we landed + if (pm->ps->forceJumpZStart) { // we were force-jumping forceLanding = qtrue; } delta = 0; - } - else - {//take off some of it, at least - delta = (pm->ps->jumpZStart-pm->ps->origin[2]); + } else { // take off some of it, at least + delta = (pm->ps->jumpZStart - pm->ps->origin[2]); float dropAllow = forceJumpHeight[pm->ps->forcePowerLevel[FP_LEVITATION]]; - if ( dropAllow < 128 ) - {//always allow a drop from 128, at least + if (dropAllow < 128) { // always allow a drop from 128, at least dropAllow = 128; } - if ( delta > forceJumpHeight[FORCE_LEVEL_1] ) - {//will have to use force jump ability to absorb some of it - forceLanding = qtrue;//absorbed some - just to force the correct animation to play below + if (delta > forceJumpHeight[FORCE_LEVEL_1]) { // will have to use force jump ability to absorb some of it + forceLanding = qtrue; // absorbed some - just to force the correct animation to play below } - delta = (delta - dropAllow)/2; + delta = (delta - dropAllow) / 2; } - if ( delta < 1 ) - { + if (delta < 1) { delta = 1; } } - if ( !delta ) - { - delta = PM_CrashLandDelta( pml.previous_velocity, pm->waterlevel ); + if (!delta) { + delta = PM_CrashLandDelta(pml.previous_velocity, pm->waterlevel); } } // FIXME: if duck just as you land, roll and take half damage - if ( (pm->ps->pm_flags&PMF_DUCKED) && (level.time-pm->ps->lastOnGround)>500 ) - {//must be crouched and have been inthe air for half a second minimum - if( !PM_InOnGroundAnim( pm->ps ) && !PM_InKnockDown( pm->ps ) ) - {//roll! - if ( PM_TryRoll() ) - {//absorb some impact + if ((pm->ps->pm_flags & PMF_DUCKED) && (level.time - pm->ps->lastOnGround) > 500) { // must be crouched and have been inthe air for half a second minimum + if (!PM_InOnGroundAnim(pm->ps) && !PM_InKnockDown(pm->ps)) { // roll! + if (PM_TryRoll()) { // absorb some impact delta /= 2; } } } - - if ( delta < 1 ) - { + if (delta < 1) { return; } qboolean deadFallSound = qfalse; - if( !PM_InDeathAnim() ) - { - if ( pm->cmd.upmove >= 0 && !PM_InKnockDown( pm->ps ) && !PM_InRoll( pm->ps )) - {//not crouching - if ( delta > 10 - || pm->ps->pm_flags & PMF_BACKWARDS_JUMP - || (pm->ps->forcePowersActive&(1<cmd.upmove >= 0 && !PM_InKnockDown(pm->ps) && !PM_InRoll(pm->ps)) { // not crouching + if (delta > 10 || pm->ps->pm_flags & PMF_BACKWARDS_JUMP || (pm->ps->forcePowersActive & (1 << FP_LEVITATION)) || + forceLanding) // EV_FALL_SHORT or jumping back or force-land + { // decide which landing animation to use int anim = PM_GetLandingAnim(); - if ( anim != -1 ) - { - if ( PM_FlippingAnim( pm->ps->torsoAnim ) || - PM_SpinningAnim( pm->ps->torsoAnim ) ) - {//interrupt these if we're going to play a land + if (anim != -1) { + if (PM_FlippingAnim(pm->ps->torsoAnim) || PM_SpinningAnim(pm->ps->torsoAnim)) { // interrupt these if we're going to play a land pm->ps->torsoAnimTimer = 0; } - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 100 ); // Only blend over 100ms + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 100); // Only blend over 100ms } } } - } - else - { + } else { pm->ps->gravity = 1.0; - //PM_CrashLandDamage( delta ); - if ( pm->gent ) - { + // PM_CrashLandDamage( delta ); + if (pm->gent) { if ((!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) && -// (!(pml.groundTrace.contents & CONTENTS_NODROP)) && - (!(pm->pointcontents(pm->ps->origin,pm->ps->clientNum) & CONTENTS_NODROP))) - { - if ( pm->waterlevel < 2 ) - {//don't play fallsplat when impact in the water + // (!(pml.groundTrace.contents & CONTENTS_NODROP)) && + (!(pm->pointcontents(pm->ps->origin, pm->ps->clientNum) & CONTENTS_NODROP))) { + if (pm->waterlevel < 2) { // don't play fallsplat when impact in the water deadFallSound = qtrue; - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/player/fallsplat.wav" ); + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/player/fallsplat.wav"); } - if ( gi.VoiceVolume[pm->ps->clientNum] - && pm->gent->NPC && (pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//I was talking, so cut it off... with a jump sound? - G_SoundOnEnt( pm->gent, CHAN_VOICE_ATTEN, "*pain100.wav" ); + if (gi.VoiceVolume[pm->ps->clientNum] && pm->gent->NPC && + (pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // I was talking, so cut it off... with a jump sound? + G_SoundOnEnt(pm->gent, CHAN_VOICE_ATTEN, "*pain100.wav"); } } } - if( pm->ps->legsAnim == BOTH_FALLDEATH1 || pm->ps->legsAnim == BOTH_FALLDEATH1INAIR) - {//FIXME: add a little bounce? - //FIXME: cut voice channel? + if (pm->ps->legsAnim == BOTH_FALLDEATH1 || pm->ps->legsAnim == BOTH_FALLDEATH1INAIR) { // FIXME: add a little bounce? + // FIXME: cut voice channel? int old_pm_type = pm->ps->pm_type; pm->ps->pm_type = PM_NORMAL; - //Hack because for some reason PM_SetAnim just returns if you're dead...??? - PM_SetAnim(pm, SETANIM_BOTH, BOTH_FALLDEATH1LAND, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + // Hack because for some reason PM_SetAnim just returns if you're dead...??? + PM_SetAnim(pm, SETANIM_BOTH, BOTH_FALLDEATH1LAND, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->pm_type = old_pm_type; return; } @@ -2642,130 +2262,92 @@ static void PM_CrashLand( void ) // create a local entity event to play the sound - if ( pm->gent && pm->gent->client && pm->gent->client->respawnTime >= level.time - 500 ) - {//just spawned in, don't make a noise + if (pm->gent && pm->gent->client && pm->gent->client->respawnTime >= level.time - 500) { // just spawned in, don't make a noise return; } - if ( delta >= 75 ) - { - if ( !deadFallSound ) - { - PM_AddEvent( EV_FALL_FAR ); + if (delta >= 75) { + if (!deadFallSound) { + PM_AddEvent(EV_FALL_FAR); } - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } - if ( pm->gent ) - { - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent) { + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_SUSPICIOUS ); - } - } - else if ( pm->ps->stats[STAT_HEALTH] <= 0 && pm->gent && pm->gent->enemy ) - { - AddSoundEvent( pm->gent->enemy, pm->ps->origin, 256, AEL_DISCOVERED ); + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_SUSPICIOUS); } + } else if (pm->ps->stats[STAT_HEALTH] <= 0 && pm->gent && pm->gent->enemy) { + AddSoundEvent(pm->gent->enemy, pm->ps->origin, 256, AEL_DISCOVERED); } } - } - else if ( delta >= 50 ) - { + } else if (delta >= 50) { // this is a pain grunt, so don't play it if dead - if ( pm->ps->stats[STAT_HEALTH] > 0 ) - { - if ( !deadFallSound ) - { - PM_AddEvent( EV_FALL_MEDIUM );//damage is dealt in g_active, ClientEvents + if (pm->ps->stats[STAT_HEALTH] > 0) { + if (!deadFallSound) { + PM_AddEvent(EV_FALL_MEDIUM); // damage is dealt in g_active, ClientEvents } - if ( pm->gent ) - { - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + if (pm->gent) { + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_MINOR ); - } + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_MINOR); } } } } - } - else if ( delta >= 30 ) - { - if ( !deadFallSound ) - { - PM_AddEvent( EV_FALL_SHORT ); + } else if (delta >= 30) { + if (!deadFallSound) { + PM_AddEvent(EV_FALL_SHORT); } - if ( pm->gent ) - { - if ( pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent) { + if (pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; - // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 128, AEL_MINOR ); - } - } - else - { - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) - { - PM_CrashLandDamage( delta ); + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 128, AEL_MINOR); } + } else { + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + PM_CrashLandDamage(delta); } } } - } - else - { - if ( !deadFallSound ) - { - if ( forceLanding ) - {//we were force-jumping - PM_AddEvent( EV_FALL_SHORT ); - } - else - { - PM_AddEvent( PM_FootstepForSurface() ); + } else { + if (!deadFallSound) { + if (forceLanding) { // we were force-jumping + PM_AddEvent(EV_FALL_SHORT); + } else { + PM_AddEvent(PM_FootstepForSurface()); } } } // start footstep cycle over pm->ps->bobCycle = 0; - if ( pm->gent && pm->gent->client ) - {//stop the force push effect when you land + if (pm->gent && pm->gent->client) { // stop the force push effect when you land pm->gent->forcePushTime = 0; } } - - /* ============= PM_CorrectAllSolid ============= */ -static void PM_CorrectAllSolid( void ) { - if ( pm->debugLevel ) { - Com_Printf("%i:allsolid\n", c_pmove); //NOTENOTE: If this ever happens, I'd really like to see this print! +static void PM_CorrectAllSolid(void) { + if (pm->debugLevel) { + Com_Printf("%i:allsolid\n", c_pmove); // NOTENOTE: If this ever happens, I'd really like to see this print! } // FIXME: jitter around @@ -2775,77 +2357,67 @@ static void PM_CorrectAllSolid( void ) { pml.walking = qfalse; } -qboolean FlyingCreature( gentity_t *ent ) -{ - if ( ent->client->ps.gravity <= 0 && (ent->svFlags&SVF_CUSTOM_GRAVITY) ) - { +qboolean FlyingCreature(gentity_t *ent) { + if (ent->client->ps.gravity <= 0 && (ent->svFlags & SVF_CUSTOM_GRAVITY)) { return qtrue; } return qfalse; } -static void PM_FallToDeath( void ) -{ - if ( !pm->gent ) - { +static void PM_FallToDeath(void) { + if (!pm->gent) { return; } - if ( PM_HasAnimation( pm->gent, BOTH_FALLDEATH1 ) ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_FALLDEATH1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_DEATH1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (PM_HasAnimation(pm->gent, BOTH_FALLDEATH1)) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - G_SoundOnEnt( pm->gent, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - if ( pm->gent->NPC ) - { + G_SoundOnEnt(pm->gent, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + if (pm->gent->NPC) { pm->gent->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; pm->gent->NPC->nextBStateThink = Q3_INFINITE; } pm->ps->friction = 1; } -int PM_ForceJumpAnimForJumpAnim( int anim ) -{ - switch( anim ) - { - case BOTH_JUMP1: //# Jump - wind-up and leave ground - anim = BOTH_FORCEJUMP1; //# Jump - wind-up and leave ground +int PM_ForceJumpAnimForJumpAnim(int anim) { + switch (anim) { + case BOTH_JUMP1: //# Jump - wind-up and leave ground + anim = BOTH_FORCEJUMP1; //# Jump - wind-up and leave ground break; - case BOTH_INAIR1: //# In air loop (from jump) - anim = BOTH_FORCEINAIR1; //# In air loop (from jump) + case BOTH_INAIR1: //# In air loop (from jump) + anim = BOTH_FORCEINAIR1; //# In air loop (from jump) break; - case BOTH_LAND1: //# Landing (from in air loop) - anim = BOTH_FORCELAND1; //# Landing (from in air loop) + case BOTH_LAND1: //# Landing (from in air loop) + anim = BOTH_FORCELAND1; //# Landing (from in air loop) break; case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground - anim = BOTH_FORCEJUMPBACK1; //# Jump backwards - wind-up and leave ground + anim = BOTH_FORCEJUMPBACK1; //# Jump backwards - wind-up and leave ground break; - case BOTH_INAIRBACK1: //# In air loop (from jump back) - anim = BOTH_FORCEINAIRBACK1; //# In air loop (from jump back) + case BOTH_INAIRBACK1: //# In air loop (from jump back) + anim = BOTH_FORCEINAIRBACK1; //# In air loop (from jump back) break; case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - anim = BOTH_FORCELANDBACK1; //# Landing backwards(from in air loop) + anim = BOTH_FORCELANDBACK1; //# Landing backwards(from in air loop) break; case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground - anim = BOTH_FORCEJUMPLEFT1; //# Jump left - wind-up and leave ground + anim = BOTH_FORCEJUMPLEFT1; //# Jump left - wind-up and leave ground break; - case BOTH_INAIRLEFT1: //# In air loop (from jump left) - anim = BOTH_FORCEINAIRLEFT1; //# In air loop (from jump left) + case BOTH_INAIRLEFT1: //# In air loop (from jump left) + anim = BOTH_FORCEINAIRLEFT1; //# In air loop (from jump left) break; case BOTH_LANDLEFT1: //# Landing left(from in air loop) - anim = BOTH_FORCELANDLEFT1; //# Landing left(from in air loop) + anim = BOTH_FORCELANDLEFT1; //# Landing left(from in air loop) break; - case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground - anim = BOTH_FORCEJUMPRIGHT1; //# Jump right - wind-up and leave ground + case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground + anim = BOTH_FORCEJUMPRIGHT1; //# Jump right - wind-up and leave ground break; - case BOTH_INAIRRIGHT1: //# In air loop (from jump right) - anim = BOTH_FORCEINAIRRIGHT1; //# In air loop (from jump right) + case BOTH_INAIRRIGHT1: //# In air loop (from jump right) + anim = BOTH_FORCEINAIRRIGHT1; //# In air loop (from jump right) break; - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - anim = BOTH_FORCELANDRIGHT1; //# Landing right(from in air loop) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + anim = BOTH_FORCELANDRIGHT1; //# Landing right(from in air loop) break; } return anim; @@ -2857,119 +2429,98 @@ PM_GroundTraceMissed The ground trace didn't hit a surface, so we are in freefall ============= */ -static void PM_GroundTraceMissed( void ) { - trace_t trace; - vec3_t point; - qboolean cliff_fall = qfalse; - - - //FIXME: if in a contents_falldeath brush, play the falling death anim and sound? - if ( pm->ps->clientNum != 0 && pm->gent && pm->gent->NPC && pm->gent->client && pm->gent->client->NPC_class != CLASS_DESANN )//desann never falls to his death - { - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { - if ( pm->ps->stats[STAT_HEALTH] > 0 - && !(pm->gent->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) - && !(pm->gent->NPC->scriptFlags&SCF_NO_FALLTODEATH) ) - { - if ( (level.time - pm->gent->client->respawnTime > 2000)//been in the world for at least 2 seconds - && (!pm->gent->NPC->timeOfDeath || level.time - pm->gent->NPC->timeOfDeath < 1000) && pm->gent->e_ThinkFunc != thinkF_NPC_RemoveBody //Have to do this now because timeOfDeath is used by thinkF_NPC_RemoveBody to debounce removal checks - && !(pm->gent->client->ps.forcePowersActive&(1<gent ) - && g_gravity->value > 0 ) - { - if ( !(pm->gent->flags&FL_UNDYING) - && !(pm->gent->flags&FL_GODMODE) ) - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) - && !(pm->ps->pm_flags&PMF_TRIGGER_PUSHED) ) - { - if ( !pm->ps->forceJumpZStart || pm->ps->forceJumpZStart > pm->ps->origin[2] )// && fabs(pm->ps->velocity[0])<10 && fabs(pm->ps->velocity[1])<10 && pm->ps->velocity[2]<0)//either not force-jumping or force-jumped and now fell below original jump start height +static void PM_GroundTraceMissed(void) { + trace_t trace; + vec3_t point; + qboolean cliff_fall = qfalse; + + // FIXME: if in a contents_falldeath brush, play the falling death anim and sound? + if (pm->ps->clientNum != 0 && pm->gent && pm->gent->NPC && pm->gent->client && + pm->gent->client->NPC_class != CLASS_DESANN) // desann never falls to his death + { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { + if (pm->ps->stats[STAT_HEALTH] > 0 && !(pm->gent->NPC->aiFlags & NPCAI_DIE_ON_IMPACT) && !(pm->gent->NPC->scriptFlags & SCF_NO_FALLTODEATH)) { + if ((level.time - pm->gent->client->respawnTime > 2000) // been in the world for at least 2 seconds + && (!pm->gent->NPC->timeOfDeath || level.time - pm->gent->NPC->timeOfDeath < 1000) && + pm->gent->e_ThinkFunc != + thinkF_NPC_RemoveBody // Have to do this now because timeOfDeath is used by thinkF_NPC_RemoveBody to debounce removal checks + && !(pm->gent->client->ps.forcePowersActive & (1 << FP_LEVITATION))) { + if (!FlyingCreature(pm->gent) && g_gravity->value > 0) { + if (!(pm->gent->flags & FL_UNDYING) && !(pm->gent->flags & FL_GODMODE)) { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED) && !(pm->ps->pm_flags & PMF_TRIGGER_PUSHED)) { + if (!pm->ps->forceJumpZStart || + pm->ps->forceJumpZStart > + pm->ps->origin[2]) // && fabs(pm->ps->velocity[0])<10 && fabs(pm->ps->velocity[1])<10 && pm->ps->velocity[2]<0)//either + // not force-jumping or force-jumped and now fell below original jump start height { /*if ( pm->ps->legsAnim = BOTH_FALLDEATH1 && pm->ps->legsAnim != BOTH_DEATH1 && PM_HasAnimation( pm->gent, BOTH_FALLDEATH1 )*/ - //New method: predict impact, 400 ahead - vec3_t vel; - float time; - - VectorCopy( pm->ps->velocity, vel ); - float speed = VectorLength( vel ); - if ( !speed ) - {//damn divide by zero + // New method: predict impact, 400 ahead + vec3_t vel; + float time; + + VectorCopy(pm->ps->velocity, vel); + float speed = VectorLength(vel); + if (!speed) { // damn divide by zero speed = 1; } - time = 400/speed; + time = 400 / speed; vel[2] -= 0.5 * time * pm->ps->gravity; - speed = VectorLength( vel ); - if ( !speed ) - {//damn divide by zero + speed = VectorLength(vel); + if (!speed) { // damn divide by zero speed = 1; } - time = 400/speed; - VectorScale( vel, time, vel ); - VectorAdd( pm->ps->origin, vel, point ); + time = 400 / speed; + VectorScale(vel, time, vel); + VectorAdd(pm->ps->origin, vel, point); - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); - if ( !trace.allsolid && !trace.startsolid && (pm->ps->origin[2] - trace.endpos[2]) >= 128 )//>=128 so we don't die on steps! + if (!trace.allsolid && !trace.startsolid && (pm->ps->origin[2] - trace.endpos[2]) >= 128) //>=128 so we don't die on steps! { - if ( trace.fraction == 1.0 ) - {//didn't hit, we're probably going to die - if ( pm->ps->velocity[2] < 0 && pm->ps->origin[2] - point[2] > 256 ) - {//going down, into a bottomless pit, apparently + if (trace.fraction == 1.0) { // didn't hit, we're probably going to die + if (pm->ps->velocity[2] < 0 && pm->ps->origin[2] - point[2] > 256) { // going down, into a bottomless pit, + // apparently PM_FallToDeath(); cliff_fall = qtrue; } - } - else if ( trace.entityNum < ENTITYNUM_NONE && pm->ps->weapon != WP_SABER ) - {//Jedi don't scream and die if they're heading for a hard impact + } else if (trace.entityNum < ENTITYNUM_NONE && + pm->ps->weapon != WP_SABER) { // Jedi don't scream and die if they're heading for a hard impact gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.entityNum == ENTITYNUM_WORLD || (traceEnt && traceEnt->bmodel) ) - {//hit architecture, find impact force - float dmg; + if (trace.entityNum == ENTITYNUM_WORLD || (traceEnt && traceEnt->bmodel)) { // hit architecture, find impact force + float dmg; - VectorCopy( pm->ps->velocity, vel ); - time = Distance( trace.endpos, pm->ps->origin )/VectorLength( vel ); + VectorCopy(pm->ps->velocity, vel); + time = Distance(trace.endpos, pm->ps->origin) / VectorLength(vel); vel[2] -= 0.5 * time * pm->ps->gravity; - if ( trace.plane.normal[2] > 0.5 ) - {//use falling damage - int waterlevel, junk; - PM_SetWaterLevelAtPoint( trace.endpos, &waterlevel, &junk ); - dmg = PM_CrashLandDelta( vel, waterlevel ); - if ( dmg >= 30 ) - {//there is a minimum fall threshhold - dmg = PM_DamageForDelta( dmg ); - } - else - { + if (trace.plane.normal[2] > 0.5) { // use falling damage + int waterlevel, junk; + PM_SetWaterLevelAtPoint(trace.endpos, &waterlevel, &junk); + dmg = PM_CrashLandDelta(vel, waterlevel); + if (dmg >= 30) { // there is a minimum fall threshhold + dmg = PM_DamageForDelta(dmg); + } else { dmg = 0; } - } - else - {//use impact damage - //guestimate - if ( pm->gent->client && pm->gent->client->ps.forceJumpZStart ) - {//we were force-jumping - if ( pm->gent->currentOrigin[2] >= pm->gent->client->ps.forceJumpZStart ) - {//we landed at same height or higher than we landed + } else { // use impact damage + // guestimate + if (pm->gent->client && pm->gent->client->ps.forceJumpZStart) { // we were force-jumping + if (pm->gent->currentOrigin[2] >= + pm->gent->client->ps.forceJumpZStart) { // we landed at same height or higher than we landed dmg = 0; - } - else - {//FIXME: take off some of it, at least? - dmg = (pm->gent->client->ps.forceJumpZStart-pm->gent->currentOrigin[2])/3; + } else { // FIXME: take off some of it, at least? + dmg = (pm->gent->client->ps.forceJumpZStart - pm->gent->currentOrigin[2]) / 3; } } - dmg = 10 * VectorLength( pm->ps->velocity ); - if ( !pm->ps->clientNum ) - { + dmg = 10 * VectorLength(pm->ps->velocity); + if (!pm->ps->clientNum) { dmg /= 2; } - dmg *= 0.01875f;//magic number + dmg *= 0.01875f; // magic number } - if ( dmg >= pm->ps->stats[STAT_HEALTH] )//armor? + if (dmg >= pm->ps->stats[STAT_HEALTH]) // armor? { PM_FallToDeath(); cliff_fall = qtrue; @@ -2981,9 +2532,9 @@ static void PM_GroundTraceMissed( void ) { /* vec3_t start; //okay, kind of expensive temp hack here, but let's check to see if we should scream - //FIXME: we should either do a better check (predict using actual velocity) or we should wait until they've been over a bottomless pit for a certain amount of time... - VectorCopy( pm->ps->origin, start ); - if ( pm->ps->forceJumpZStart < start[2] ) + //FIXME: we should either do a better check (predict using actual velocity) or we should wait until they've been over a + bottomless pit for a certain amount of time... VectorCopy( pm->ps->origin, start ); if ( pm->ps->forceJumpZStart < start[2] + ) {//Jedi who are force-jumping should only do this from landing point down? start[2] = pm->ps->forceJumpZStart; } @@ -3005,105 +2556,69 @@ static void PM_GroundTraceMissed( void ) { } } } - if ( !cliff_fall ) - { - if ( ( pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_FLIP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_FLIP - || pm->ps->legsAnim == BOTH_WALL_FLIP_RIGHT - || pm->ps->legsAnim == BOTH_WALL_FLIP_LEFT - || pm->ps->legsAnim == BOTH_CEILING_DROP ) - && !pm->ps->legsAnimTimer ) - {//if flip anim is done, okay to use inair - PM_SetAnim( pm, SETANIM_LEGS, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE, 350 ); // Only blend over 100ms - } - else if ( !PM_InRoll( pm->ps ) - && !PM_SpinningAnim( pm->ps->legsAnim ) - && !PM_FlippingAnim( pm->ps->legsAnim ) - && !PM_InSpecialJump( pm->ps->legsAnim ) ) - { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { + if (!cliff_fall) { + if ((pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_FLIP || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_FLIP || + pm->ps->legsAnim == BOTH_WALL_FLIP_RIGHT || pm->ps->legsAnim == BOTH_WALL_FLIP_LEFT || pm->ps->legsAnim == BOTH_CEILING_DROP) && + !pm->ps->legsAnimTimer) { // if flip anim is done, okay to use inair + PM_SetAnim(pm, SETANIM_LEGS, BOTH_FORCEINAIR1, SETANIM_FLAG_OVERRIDE, 350); // Only blend over 100ms + } else if (!PM_InRoll(pm->ps) && !PM_SpinningAnim(pm->ps->legsAnim) && !PM_FlippingAnim(pm->ps->legsAnim) && !PM_InSpecialJump(pm->ps->legsAnim)) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // we just transitioned into freefall - if ( pm->debugLevel ) - { + if (pm->debugLevel) { Com_Printf("%i:lift\n", c_pmove); } // if they aren't in a jumping animation and the ground is a ways away, force into it // if we didn't do the trace, the player would be backflipping down staircases - VectorCopy( pm->ps->origin, point ); + VectorCopy(pm->ps->origin, point); point[2] -= 64; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); - if ( trace.fraction == 1.0 ) - {//FIXME: if velocity[2] < 0 and didn't jump, use some falling anim - if ( pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags&PMF_JUMP_HELD)) - { - if(!PM_InDeathAnim()) - { - vec3_t moveDir, lookAngles, lookDir, lookRight; - int anim = BOTH_INAIR1; + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (trace.fraction == 1.0) { // FIXME: if velocity[2] < 0 and didn't jump, use some falling anim + if (pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags & PMF_JUMP_HELD)) { + if (!PM_InDeathAnim()) { + vec3_t moveDir, lookAngles, lookDir, lookRight; + int anim = BOTH_INAIR1; - VectorCopy( pm->ps->velocity, moveDir ); + VectorCopy(pm->ps->velocity, moveDir); moveDir[2] = 0; - VectorNormalize( moveDir ); + VectorNormalize(moveDir); - VectorCopy( pm->ps->viewangles, lookAngles ); + VectorCopy(pm->ps->viewangles, lookAngles); lookAngles[PITCH] = lookAngles[ROLL] = 0; - AngleVectors( lookAngles, lookDir, lookRight, NULL ); + AngleVectors(lookAngles, lookDir, lookRight, NULL); - float dot = DotProduct( moveDir, lookDir ); - if ( dot > 0.5 ) - {//redundant + float dot = DotProduct(moveDir, lookDir); + if (dot > 0.5) { // redundant anim = BOTH_INAIR1; - } - else if ( dot < -0.5 ) - { + } else if (dot < -0.5) { anim = BOTH_INAIRBACK1; - } - else - { - dot = DotProduct( moveDir, lookRight ); - if ( dot > 0.5 ) - { + } else { + dot = DotProduct(moveDir, lookRight); + if (dot > 0.5) { anim = BOTH_INAIRRIGHT1; - } - else if ( dot < -0.5 ) - { + } else if (dot < -0.5) { anim = BOTH_INAIRLEFT1; - } - else - {//redundant + } else { // redundant anim = BOTH_INAIR1; } } - if ( pm->ps->forcePowersActive & ( 1 << FP_LEVITATION ) ) - { - anim = PM_ForceJumpAnimForJumpAnim( anim ); + if (pm->ps->forcePowersActive & (1 << FP_LEVITATION)) { + anim = PM_ForceJumpAnimForJumpAnim(anim); } - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100 ); // Only blend over 100ms + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( !(pm->ps->forcePowersActive&(1<cmd.forwardmove >= 0 ) - { - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_JUMP1,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + } else if (!(pm->ps->forcePowersActive & (1 << FP_LEVITATION))) { + if (pm->cmd.forwardmove >= 0) { + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove < 0 ) - { - if(!PM_InDeathAnim()) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_JUMPBACK1,SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms + } else if (pm->cmd.forwardmove < 0) { + if (!PM_InDeathAnim()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_JUMPBACK1, SETANIM_FLAG_OVERRIDE, 100); // Only blend over 100ms } pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; } @@ -3113,8 +2628,7 @@ static void PM_GroundTraceMissed( void ) { } } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { pm->ps->jumpZStart = pm->ps->origin[2]; } pm->ps->groundEntityNum = ENTITYNUM_NONE; @@ -3122,18 +2636,16 @@ static void PM_GroundTraceMissed( void ) { pml.walking = qfalse; } - /* ============= PM_GroundTrace ============= */ -static void PM_GroundTrace( void ) { - vec3_t point; - trace_t trace; +static void PM_GroundTrace(void) { + vec3_t point; + trace_t trace; - if ( pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - { + if (pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { pml.groundPlane = qtrue; pml.walking = qtrue; pm->ps->groundEntityNum = ENTITYNUM_WORLD; @@ -3154,32 +2666,29 @@ static void PM_GroundTrace( void ) { pml.groundTrace.surfaceFlags = 0; */ return; - } - else if ( pm->ps->legsAnimTimer > 300 && (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT) ) - {//wall-running forces you to be in the air + } else if (pm->ps->legsAnimTimer > 300 && + (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT)) { // wall-running forces you to be in the air pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->groundEntityNum = ENTITYNUM_NONE; return; } - point[0] = pm->ps->origin[0]; point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] - 0.25; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); pml.groundTrace = trace; // do something corrective if the trace starts in a solid... - if ( trace.allsolid ) { + if (trace.allsolid) { PM_CorrectAllSolid(); return; } // if the trace didn't hit anything, we are in free fall - if ( trace.fraction == 1.0 || g_gravity->value <= 0 ) - { + if (trace.fraction == 1.0 || g_gravity->value <= 0) { PM_GroundTraceMissed(); pml.groundPlane = qfalse; pml.walking = qfalse; @@ -3187,26 +2696,17 @@ static void PM_GroundTrace( void ) { } // check if getting thrown off the ground - if ( ((pm->ps->velocity[2]>0&&(pm->ps->pm_flags&PMF_TIME_KNOCKBACK))||pm->ps->velocity[2]>100) && DotProduct( pm->ps->velocity, trace.plane.normal ) > 10 ) - {//either thrown off ground (PMF_TIME_KNOCKBACK) or going off the ground at a large velocity - if ( pm->debugLevel ) { + if (((pm->ps->velocity[2] > 0 && (pm->ps->pm_flags & PMF_TIME_KNOCKBACK)) || pm->ps->velocity[2] > 100) && + DotProduct(pm->ps->velocity, trace.plane.normal) > 10) { // either thrown off ground (PMF_TIME_KNOCKBACK) or going off the ground at a large velocity + if (pm->debugLevel) { Com_Printf("%i:kickoff\n", c_pmove); } // go into jump animation - if ( PM_FlippingAnim( pm->ps->legsAnim) ) - {//we're flipping - } - else if ( PM_InSpecialJump( pm->ps->legsAnim ) ) - {//special jumps - } - else if ( PM_InKnockDown( pm->ps ) ) - {//in knockdown - } - else if ( PM_InRoll( pm->ps ) ) - {//in knockdown - } - else - { + if (PM_FlippingAnim(pm->ps->legsAnim)) { // we're flipping + } else if (PM_InSpecialJump(pm->ps->legsAnim)) { // special jumps + } else if (PM_InKnockDown(pm->ps)) { // in knockdown + } else if (PM_InRoll(pm->ps)) { // in knockdown + } else { PM_JumpForDir(); } @@ -3217,8 +2717,8 @@ static void PM_GroundTrace( void ) { } // slopes that are too steep will not be considered onground - if ( trace.plane.normal[2] < MIN_WALK_NORMAL ) { - if ( pm->debugLevel ) { + if (trace.plane.normal[2] < MIN_WALK_NORMAL) { + if (pm->debugLevel) { Com_Printf("%i:steep\n", c_pmove); } // FIXME: if they can't slide down the slope, let them @@ -3229,64 +2729,60 @@ static void PM_GroundTrace( void ) { return; } - //FIXME: if the ground surface is a "cover surface (like tall grass), add a "cover" flag to me + // FIXME: if the ground surface is a "cover surface (like tall grass), add a "cover" flag to me pml.groundPlane = qtrue; pml.walking = qtrue; // hitting solid ground will end a waterjump - if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) - { + if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { pm->ps->pm_flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND); pm->ps->pm_time = 0; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // just hit the ground - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:Land\n", c_pmove); } - //if ( !PM_ClientImpact( trace.entityNum, qtrue ) ) + // if ( !PM_ClientImpact( trace.entityNum, qtrue ) ) { PM_CrashLand(); // don't do landing time if we were just going down a slope - if ( pml.previous_velocity[2] < -200 ) { + if (pml.previous_velocity[2] < -200) { // don't allow another jump for a little while pm->ps->pm_flags |= PMF_TIME_LAND; pm->ps->pm_time = 250; } if (!pm->cmd.forwardmove && !pm->cmd.rightmove) { - pm->ps->velocity[2] = 0; //wouldn't normally want this because of slopes, but we aren't tyring to move... + pm->ps->velocity[2] = 0; // wouldn't normally want this because of slopes, but we aren't tyring to move... } } } pm->ps->groundEntityNum = trace.entityNum; pm->ps->lastOnGround = level.time; - if ( !pm->ps->clientNum ) - {//if a player, clear the jumping "flag" so can't double-jump + if (!pm->ps->clientNum) { // if a player, clear the jumping "flag" so can't double-jump pm->ps->forceJumpCharge = 0; } // don't reset the z velocity for slopes -// pm->ps->velocity[2] = 0; + // pm->ps->velocity[2] = 0; - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); } - /* ============= PM_SetWaterLevelAtPoint FIXME: avoid this twice? certainly if not moving ============= */ -static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype ) -{ - vec3_t point; - int cont; - int sample1; - int sample2; +static void PM_SetWaterLevelAtPoint(vec3_t org, int *waterlevel, int *watertype) { + vec3_t point; + int cont; + int sample1; + int sample2; // // get waterlevel, accounting for ducking @@ -3297,105 +2793,76 @@ static void PM_SetWaterLevelAtPoint( vec3_t org, int *waterlevel, int *watertype point[0] = org[0]; point[1] = org[1]; point[2] = org[2] + DEFAULT_MINS_2 + 1; - cont = pm->pointcontents( point, pm->ps->clientNum ); + cont = pm->pointcontents(point, pm->ps->clientNum); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + if (cont & (MASK_WATER | CONTENTS_LADDER)) { sample2 = pm->ps->viewheight - DEFAULT_MINS_2; sample1 = sample2 / 2; *watertype = cont; *waterlevel = 1; point[2] = org[2] + DEFAULT_MINS_2 + sample1; - cont = pm->pointcontents( point, pm->ps->clientNum ); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & (MASK_WATER | CONTENTS_LADDER)) { *waterlevel = 2; point[2] = org[2] + DEFAULT_MINS_2 + sample2; - cont = pm->pointcontents( point, pm->ps->clientNum ); - if ( cont & (MASK_WATER|CONTENTS_LADDER) ) - { + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & (MASK_WATER | CONTENTS_LADDER)) { *waterlevel = 3; } } } } -void PM_SetWaterHeight( void ) -{ +void PM_SetWaterHeight(void) { pm->ps->waterHeightLevel = WHL_NONE; - if ( pm->waterlevel < 1 ) - { + if (pm->waterlevel < 1) { pm->ps->waterheight = pm->ps->origin[2] + DEFAULT_MINS_2 - 4; return; } trace_t trace; - vec3_t top, bottom; + vec3_t top, bottom; - VectorCopy( pm->ps->origin, top ); - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, top); + VectorCopy(pm->ps->origin, bottom); top[2] += pm->gent->client->standheight; bottom[2] += DEFAULT_MINS_2; - gi.trace( &trace, top, pm->mins, pm->maxs, bottom, pm->ps->clientNum, (CONTENTS_WATER|CONTENTS_SLIME), G2_NOCOLLIDE, 0 ); + gi.trace(&trace, top, pm->mins, pm->maxs, bottom, pm->ps->clientNum, (CONTENTS_WATER | CONTENTS_SLIME), G2_NOCOLLIDE, 0); - if ( trace.startsolid ) - {//under water + if (trace.startsolid) { // under water pm->ps->waterheight = top[2] + 4; - } - else if ( trace.fraction < 1.0f ) - {//partially in and partially out of water - pm->ps->waterheight = trace.endpos[2]+pm->mins[2]; - } - else if ( trace.contents&(CONTENTS_WATER|CONTENTS_SLIME) ) - {//water is above me + } else if (trace.fraction < 1.0f) { // partially in and partially out of water + pm->ps->waterheight = trace.endpos[2] + pm->mins[2]; + } else if (trace.contents & (CONTENTS_WATER | CONTENTS_SLIME)) { // water is above me pm->ps->waterheight = top[2] + 4; - } - else - {//water is below me + } else { // water is below me pm->ps->waterheight = bottom[2] - 4; } - float distFromEyes = (pm->ps->origin[2]+pm->gent->client->standheight)-pm->ps->waterheight; + float distFromEyes = (pm->ps->origin[2] + pm->gent->client->standheight) - pm->ps->waterheight; - if ( distFromEyes < 0 ) - { + if (distFromEyes < 0) { pm->ps->waterHeightLevel = WHL_UNDER; - } - else if ( distFromEyes < 6 ) - { + } else if (distFromEyes < 6) { pm->ps->waterHeightLevel = WHL_HEAD; - } - else if ( distFromEyes < 18 ) - { + } else if (distFromEyes < 18) { pm->ps->waterHeightLevel = WHL_SHOULDERS; - } - else if ( distFromEyes < pm->gent->client->standheight-8 ) - {//at least 8 above origin + } else if (distFromEyes < pm->gent->client->standheight - 8) { // at least 8 above origin pm->ps->waterHeightLevel = WHL_TORSO; - } - else - { - float distFromOrg = pm->ps->origin[2]-pm->ps->waterheight; - if ( distFromOrg < 6 ) - { + } else { + float distFromOrg = pm->ps->origin[2] - pm->ps->waterheight; + if (distFromOrg < 6) { pm->ps->waterHeightLevel = WHL_WAIST; - } - else if ( distFromOrg < 16 ) - { + } else if (distFromOrg < 16) { pm->ps->waterHeightLevel = WHL_KNEES; - } - else if ( distFromOrg > fabs(pm->mins[2]) ) - { + } else if (distFromOrg > fabs(pm->mins[2])) { pm->ps->waterHeightLevel = WHL_NONE; - } - else - { + } else { pm->ps->waterHeightLevel = WHL_ANKLES; } } } - /* ============== PM_SetBounds @@ -3403,22 +2870,16 @@ PM_SetBounds Sets mins, maxs ============== */ -static void PM_SetBounds (void) -{ - if ( pm->gent && pm->gent->client ) - { - if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) - { - //assert(0); +static void PM_SetBounds(void) { + if (pm->gent && pm->gent->client) { + if (!pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2]) { + // assert(0); } - VectorCopy( pm->gent->mins, pm->mins ); - VectorCopy( pm->gent->maxs, pm->maxs ); - } - else - { - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + VectorCopy(pm->gent->mins, pm->mins); + VectorCopy(pm->gent->maxs, pm->maxs); + } else { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -3440,34 +2901,25 @@ PM_CheckDuck Sets mins, maxs, and pm->ps->viewheight ============== */ -static void PM_CheckDuck (void) -{ - trace_t trace; - int standheight; - int crouchheight; - int oldHeight; +static void PM_CheckDuck(void) { + trace_t trace; + int standheight; + int crouchheight; + int oldHeight; - if ( pm->gent && pm->gent->client ) - { - if ( !pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2] ) - { - //assert(0); + if (pm->gent && pm->gent->client) { + if (!pm->gent->mins[0] || !pm->gent->mins[1] || !pm->gent->mins[2] || !pm->gent->maxs[0] || !pm->gent->maxs[1] || !pm->gent->maxs[2]) { + // assert(0); } - if ( !pm->ps->clientNum && pm->gent->client->NPC_class == CLASS_ATST && !cg.renderingThirdPerson ) - { + if (!pm->ps->clientNum && pm->gent->client->NPC_class == CLASS_ATST && !cg.renderingThirdPerson) { standheight = crouchheight = 128; - } - else - { + } else { standheight = pm->gent->client->standheight; crouchheight = pm->gent->client->crouchheight; } - } - else - { - if ( !DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2 ) - { + } else { + if (!DEFAULT_MINS_0 || !DEFAULT_MINS_1 || !DEFAULT_MAXS_0 || !DEFAULT_MAXS_1 || !DEFAULT_MINS_2 || !DEFAULT_MAXS_2) { assert(0); } @@ -3475,10 +2927,8 @@ static void PM_CheckDuck (void) crouchheight = CROUCH_MAXS_2; } - if ( PM_InGetUp( pm->ps ) ) - {//can't do any kind of crouching when getting up - if ( pm->ps->legsAnim == BOTH_GETUP_CROUCH_B1 || pm->ps->legsAnim == BOTH_GETUP_CROUCH_F1 ) - {//crouched still + if (PM_InGetUp(pm->ps)) { // can't do any kind of crouching when getting up + if (pm->ps->legsAnim == BOTH_GETUP_CROUCH_B1 || pm->ps->legsAnim == BOTH_GETUP_CROUCH_F1) { // crouched still pm->ps->pm_flags |= PMF_DUCKED; pm->maxs[2] = crouchheight; } @@ -3488,8 +2938,7 @@ static void PM_CheckDuck (void) oldHeight = pm->maxs[2]; - if ( PM_InRoll( pm->ps ) ) - { + if (PM_InRoll(pm->ps)) { /* if ( pm->ps->clientNum && pm->gent && pm->gent->client ) { @@ -3501,22 +2950,17 @@ static void PM_CheckDuck (void) } else */ - { - pm->maxs[2] = crouchheight; - } + { pm->maxs[2] = crouchheight; } pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; pm->ps->pm_flags |= PMF_DUCKED; return; } - if ( PM_GettingUpFromKnockDown( standheight, crouchheight ) ) - { + if (PM_GettingUpFromKnockDown(standheight, crouchheight)) { pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; return; } - if ( PM_InKnockDown( pm->ps ) ) - {//forced crouch - if ( pm->gent && pm->gent->client ) - {//interrupted any potential delayed weapon fires + if (PM_InKnockDown(pm->ps)) { // forced crouch + if (pm->gent && pm->gent->client) { // interrupted any potential delayed weapon fires pm->gent->client->fireDelay = 0; } pm->maxs[2] = crouchheight; @@ -3524,137 +2968,108 @@ static void PM_CheckDuck (void) pm->ps->pm_flags |= PMF_DUCKED; return; } - if ( pm->cmd.upmove < 0 ) - { // trying to duck + if (pm->cmd.upmove < 0) { // trying to duck pm->maxs[2] = crouchheight; - pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET;//CROUCH_VIEWHEIGHT; - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE && !PM_SwimmingAnim( pm->ps->legsAnim ) ) - {//Not ducked already and trying to duck in mid-air - //will raise your feet, unducking whilst in air will drop feet - if ( !(pm->ps->pm_flags&PMF_DUCKED) ) - { + pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; // CROUCH_VIEWHEIGHT; + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && !PM_SwimmingAnim(pm->ps->legsAnim)) { // Not ducked already and trying to duck in mid-air + // will raise your feet, unducking whilst in air will drop feet + if (!(pm->ps->pm_flags & PMF_DUCKED)) { pm->ps->eFlags ^= EF_TELEPORT_BIT; } - if ( pm->gent ) - { - pm->ps->origin[2] += oldHeight - pm->maxs[2];//diff will be zero if were already ducking - //Don't worry, we know we fit in a smaller size + if (pm->gent) { + pm->ps->origin[2] += oldHeight - pm->maxs[2]; // diff will be zero if were already ducking + // Don't worry, we know we fit in a smaller size } } pm->ps->pm_flags |= PMF_DUCKED; - if ( d_JediAI->integer ) - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_SABER ) - { - Com_Printf( "ducking\n" ); + if (d_JediAI->integer) { + if (pm->ps->clientNum && pm->ps->weapon == WP_SABER) { + Com_Printf("ducking\n"); } } - } - else - { // want to stop ducking, stand up if possible - if ( pm->ps->pm_flags & PMF_DUCKED ) - {//Was ducking - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//unducking whilst in air will try to drop feet + } else { // want to stop ducking, stand up if possible + if (pm->ps->pm_flags & PMF_DUCKED) { // Was ducking + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // unducking whilst in air will try to drop feet pm->maxs[2] = standheight; pm->ps->origin[2] += oldHeight - pm->maxs[2]; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); - if ( !trace.allsolid ) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (!trace.allsolid) { pm->ps->eFlags ^= EF_TELEPORT_BIT; pm->ps->pm_flags &= ~PMF_DUCKED; - } - else - {//Put us back + } else { // Put us back pm->ps->origin[2] -= oldHeight - pm->maxs[2]; } - //NOTE: this isn't the best way to check this, you may have room to unduck - //while in air, but your feet are close to landing. Probably won't be a - //noticable shortcoming - } - else - { + // NOTE: this isn't the best way to check this, you may have room to unduck + // while in air, but your feet are close to landing. Probably won't be a + // noticable shortcoming + } else { // try to stand up pm->maxs[2] = standheight; - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); - if ( !trace.allsolid ) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (!trace.allsolid) { pm->ps->pm_flags &= ~PMF_DUCKED; } } } - if ( pm->ps->pm_flags & PMF_DUCKED ) - {//Still ducking + if (pm->ps->pm_flags & PMF_DUCKED) { // Still ducking pm->maxs[2] = crouchheight; - pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET;//CROUCH_VIEWHEIGHT; - } - else - {//standing now + pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; // CROUCH_VIEWHEIGHT; + } else { // standing now pm->maxs[2] = standheight; - //FIXME: have a crouchviewheight and standviewheight on ent? - pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET;//DEFAULT_VIEWHEIGHT; + // FIXME: have a crouchviewheight and standviewheight on ent? + pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET; // DEFAULT_VIEWHEIGHT; } } } - - //=================================================================== -qboolean PM_SaberLockAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_BF2LOCK: //# - case BOTH_BF1LOCK: //# - case BOTH_CWCIRCLELOCK: //# - case BOTH_CCWCIRCLELOCK: //# +qboolean PM_SaberLockAnim(int anim) { + switch (anim) { + case BOTH_BF2LOCK: //# + case BOTH_BF1LOCK: //# + case BOTH_CWCIRCLELOCK: //# + case BOTH_CCWCIRCLELOCK: //# return qtrue; } return qfalse; } -qboolean PM_ForceAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_CHOKE1: //being choked...??? - case BOTH_GESTURE1: //taunting... - case BOTH_RESISTPUSH: //# plant yourself to resist force push/pulls. - case BOTH_FORCEPUSH: //# Use off-hand to do force power. - case BOTH_FORCEPULL: //# Use off-hand to do force power. - case BOTH_MINDTRICK1: //# Use off-hand to do mind trick - case BOTH_MINDTRICK2: //# Use off-hand to do distraction - case BOTH_FORCELIGHTNING: //# Use off-hand to do lightning +qboolean PM_ForceAnim(int anim) { + switch (anim) { + case BOTH_CHOKE1: // being choked...??? + case BOTH_GESTURE1: // taunting... + case BOTH_RESISTPUSH: //# plant yourself to resist force push/pulls. + case BOTH_FORCEPUSH: //# Use off-hand to do force power. + case BOTH_FORCEPULL: //# Use off-hand to do force power. + case BOTH_MINDTRICK1: //# Use off-hand to do mind trick + case BOTH_MINDTRICK2: //# Use off-hand to do distraction + case BOTH_FORCELIGHTNING: //# Use off-hand to do lightning case BOTH_FORCELIGHTNING_START: - case BOTH_FORCELIGHTNING_HOLD: //# Use off-hand to do lightning - case BOTH_FORCELIGHTNING_RELEASE: //# Use off-hand to do lightning - case BOTH_FORCEHEAL_START: //# Healing meditation pose start - case BOTH_FORCEHEAL_STOP: //# Healing meditation pose end - case BOTH_FORCEHEAL_QUICK: //# Healing meditation gesture - case BOTH_FORCEGRIP1: //# temp force-grip anim (actually re-using push) - case BOTH_FORCEGRIP_HOLD: //# temp force-grip anim (actually re-using push) - case BOTH_FORCEGRIP_RELEASE: //# temp force-grip anim (actually re-using push) - //case BOTH_FORCEGRIP3: //# force-gripping + case BOTH_FORCELIGHTNING_HOLD: //# Use off-hand to do lightning + case BOTH_FORCELIGHTNING_RELEASE: //# Use off-hand to do lightning + case BOTH_FORCEHEAL_START: //# Healing meditation pose start + case BOTH_FORCEHEAL_STOP: //# Healing meditation pose end + case BOTH_FORCEHEAL_QUICK: //# Healing meditation gesture + case BOTH_FORCEGRIP1: //# temp force-grip anim (actually re-using push) + case BOTH_FORCEGRIP_HOLD: //# temp force-grip anim (actually re-using push) + case BOTH_FORCEGRIP_RELEASE: //# temp force-grip anim (actually re-using push) + // case BOTH_FORCEGRIP3: //# force-gripping return qtrue; break; } return qfalse; } -qboolean PM_InSaberAnim( int anim ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR ) - { +qboolean PM_InSaberAnim(int anim) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_H1_S1_BR) { return qtrue; } return qfalse; } -qboolean PM_InForceGetUp( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InForceGetUp(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_FORCE_GETUP_F1: case BOTH_FORCE_GETUP_F2: case BOTH_FORCE_GETUP_B1: @@ -3663,8 +3078,7 @@ qboolean PM_InForceGetUp( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; @@ -3672,10 +3086,8 @@ qboolean PM_InForceGetUp( playerState_t *ps ) return qfalse; } -qboolean PM_InGetUp( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InGetUp(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -3683,23 +3095,20 @@ qboolean PM_InGetUp( playerState_t *ps ) case BOTH_GETUP5: case BOTH_GETUP_CROUCH_F1: case BOTH_GETUP_CROUCH_B1: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; default: - return PM_InForceGetUp( ps ); + return PM_InForceGetUp(ps); break; } - //what the hell, redundant, but... + // what the hell, redundant, but... return qfalse; } -qboolean PM_InKnockDown( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InKnockDown(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: @@ -3708,22 +3117,20 @@ qboolean PM_InKnockDown( playerState_t *ps ) return qtrue; break; default: - return PM_InGetUp( ps ); + return PM_InGetUp(ps); break; } } -qboolean PM_InKnockDownOnGround( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InKnockDownOnGround(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: - //if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) - {//at end of fall down anim + // if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) + { // at end of fall down anim return qtrue; } break; @@ -3742,8 +3149,8 @@ qboolean PM_InKnockDownOnGround( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer < 500 ) - {//at beginning of getup anim + if (PM_AnimLength(g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim) - ps->legsAnimTimer < + 500) { // at beginning of getup anim return qtrue; } break; @@ -3751,13 +3158,11 @@ qboolean PM_InKnockDownOnGround( playerState_t *ps ) return qfalse; } -qboolean PM_CrouchGetup( float crouchheight ) -{ +qboolean PM_CrouchGetup(float crouchheight) { pm->maxs[2] = crouchheight; pm->ps->viewheight = crouchheight + STANDARD_VIEWHEIGHT_OFFSET; - int anim = -1; - switch ( pm->ps->legsAnim ) - { + int anim = -1; + switch (pm->ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN4: @@ -3768,129 +3173,100 @@ qboolean PM_CrouchGetup( float crouchheight ) anim = BOTH_GETUP_CROUCH_F1; break; } - if ( anim == -1 ) - {//WTF? stay down? - pm->ps->legsAnimTimer = 100;//hold this anim for another 10th of a second + if (anim == -1) { // WTF? stay down? + pm->ps->legsAnimTimer = 100; // hold this anim for another 10th of a second return qfalse; - } - else - {//get up into crouch anim - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS ); - pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + } else { // get up into crouch anim + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in pm->ps->saberBlocked = BLOCKED_NONE; return qtrue; } } -qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ) -{ +qboolean PM_GettingUpFromKnockDown(float standheight, float crouchheight) { int legsAnim = pm->ps->legsAnim; - if ( legsAnim == BOTH_KNOCKDOWN1 - ||legsAnim == BOTH_KNOCKDOWN2 - ||legsAnim == BOTH_KNOCKDOWN3 - ||legsAnim == BOTH_KNOCKDOWN4 - ||legsAnim == BOTH_KNOCKDOWN5 ) - {//in a knockdown - if ( !pm->ps->legsAnimTimer ) - {//done with the knockdown - FIXME: somehow this is allowing an *instant* getup...??? - //FIXME: if trying to crouch (holding button?), just get up into a crouch? - if ( pm->cmd.upmove < 0 ) - { - return PM_CrouchGetup( crouchheight ); - } - else - { - trace_t trace; + if (legsAnim == BOTH_KNOCKDOWN1 || legsAnim == BOTH_KNOCKDOWN2 || legsAnim == BOTH_KNOCKDOWN3 || legsAnim == BOTH_KNOCKDOWN4 || + legsAnim == BOTH_KNOCKDOWN5) { // in a knockdown + if (!pm->ps->legsAnimTimer) { // done with the knockdown - FIXME: somehow this is allowing an *instant* getup...??? + // FIXME: if trying to crouch (holding button?), just get up into a crouch? + if (pm->cmd.upmove < 0) { + return PM_CrouchGetup(crouchheight); + } else { + trace_t trace; // try to stand up pm->maxs[2] = standheight; - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); - if ( !trace.allsolid ) - {//stand up + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (!trace.allsolid) { // stand up qboolean forceGetUp = qfalse; - int anim = BOTH_GETUP1; + int anim = BOTH_GETUP1; pm->maxs[2] = standheight; pm->ps->viewheight = standheight + STANDARD_VIEWHEIGHT_OFFSET; - //NOTE: the force power checks will stop fencers and grunts from getting up using force jump - switch ( pm->ps->legsAnim ) - { + // NOTE: the force power checks will stop fencers and grunts from getting up using force jump + switch (pm->ps->legsAnim) { case BOTH_KNOCKDOWN1: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || (!pm->ps->clientNum&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) ) - { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + (!pm->ps->clientNum && pm->cmd.upmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1)) { + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP1; } break; case BOTH_KNOCKDOWN2: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || (!pm->ps->clientNum&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) ) - { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + (!pm->ps->clientNum && pm->cmd.upmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1)) { + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP2; } break; case BOTH_KNOCKDOWN3: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || (!pm->ps->clientNum&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) ) - { - anim = Q_irand( BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2 ); + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + (!pm->ps->clientNum && pm->cmd.upmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1)) { + anim = Q_irand(BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2); forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP3; } break; case BOTH_KNOCKDOWN4: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || (!pm->ps->clientNum&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) ) - { - anim = Q_irand( BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6 );//NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + (!pm->ps->clientNum && pm->cmd.upmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1)) { + anim = Q_irand(BOTH_FORCE_GETUP_B1, BOTH_FORCE_GETUP_B6); // NOTE: BOTH_FORCE_GETUP_B5 takes soe steps forward at end forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP4; } break; case BOTH_KNOCKDOWN5: - if ( (pm->ps->clientNum&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || (!pm->ps->clientNum&&pm->cmd.upmove>0&&pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) ) - { - anim = Q_irand( BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2 ); + if ((pm->ps->clientNum && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0) || + (!pm->ps->clientNum && pm->cmd.upmove > 0 && pm->ps->forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1)) { + anim = Q_irand(BOTH_FORCE_GETUP_F1, BOTH_FORCE_GETUP_F2); forceGetUp = qtrue; - } - else - { + } else { anim = BOTH_GETUP5; } break; } - //Com_Printf( "getupanim = %s\n", animTable[anim].name ); - if ( forceGetUp ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY - && pm->gent->NPC && pm->gent->NPC->blockedSpeechDebounceTime < level.time - && !Q_irand( 0, 1 ) ) - { - PM_AddEvent( Q_irand( EV_COMBAT1, EV_COMBAT3 ) ); + // Com_Printf( "getupanim = %s\n", animTable[anim].name ); + if (forceGetUp) { + if (pm->gent && pm->gent->client && pm->gent->client->playerTeam == TEAM_ENEMY && pm->gent->NPC && + pm->gent->NPC->blockedSpeechDebounceTime < level.time && !Q_irand(0, 1)) { + PM_AddEvent(Q_irand(EV_COMBAT1, EV_COMBAT3)); pm->gent->NPC->blockedSpeechDebounceTime = level.time + 1000; } - G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - //launch off ground? - pm->ps->weaponTime = 300;//just to make sure it's cleared + G_SoundOnEnt(pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav"); + // launch off ground? + pm->ps->weaponTime = 300; // just to make sure it's cleared } - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS ); - pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS); + pm->ps->saberMove = pm->ps->saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in pm->ps->saberBlocked = BLOCKED_NONE; return qtrue; - } - else - { - return PM_CrouchGetup( crouchheight ); + } else { + return PM_CrouchGetup(crouchheight); } } } @@ -3898,10 +3274,8 @@ qboolean PM_GettingUpFromKnockDown( float standheight, float crouchheight ) return qfalse; } -void PM_CmdForRoll( int anim, usercmd_t *pCmd ) -{ - switch ( anim ) - { +void PM_CmdForRoll(int anim, usercmd_t *pCmd) { + switch (anim) { case BOTH_ROLL_F: pCmd->forwardmove = 127; pCmd->rightmove = 0; @@ -3922,16 +3296,13 @@ void PM_CmdForRoll( int anim, usercmd_t *pCmd ) pCmd->upmove = 0; } -qboolean PM_InRoll( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean PM_InRoll(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: case BOTH_ROLL_L: - if ( ps->legsAnimTimer ) - { + if (ps->legsAnimTimer) { return qtrue; } break; @@ -3939,147 +3310,135 @@ qboolean PM_InRoll( playerState_t *ps ) return qfalse; } -qboolean PM_CrouchAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SIT1: //# Normal chair sit. - case BOTH_SIT2: //# Lotus position. - case BOTH_SIT3: //# Sitting in tired position: elbows on knees - case BOTH_SIT2TO3: //# Trans from sit2 to sit3? - case BOTH_SIT3TO1: //# Trans from sit3 to sit1? - case BOTH_SIT3TO2: //# Trans from sit3 to sit2? - case BOTH_SIT4TO5: //# Trans from sit4 to sit5 - case BOTH_SIT4TO6: //# Trans from sit4 to sit6 - case BOTH_SIT5TO4: //# Trans from sit5 to sit4 - case BOTH_SIT5TO6: //# Trans from sit5 to sit6 - case BOTH_SIT6TO4: //# Trans from sit6 to sit4 - case BOTH_SIT6TO5: //# Trans from sit6 to sit5 - case BOTH_SIT7: //# sitting with arms over knees: no weapon - case BOTH_CROUCH1: //# Transition from standing to crouch - case BOTH_CROUCH1IDLE: //# Crouching idle - case BOTH_CROUCH1WALK: //# Walking while crouched - case BOTH_CROUCH1WALKBACK: //# Walking while crouched - case BOTH_CROUCH2IDLE: //# crouch and resting on back righ heel: no weapon - case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 - case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) - case BOTH_KNEES1: //# Tavion on her knees - case LEGS_CRLEAN_LEFT1: //# Crouch Lean left - case LEGS_CRLEAN_RIGHT1: //# Crouch Lean Right - case BOTH_CROUCHATTACKBACK1://FIXME: not if in middle of anim? +qboolean PM_CrouchAnim(int anim) { + switch (anim) { + case BOTH_SIT1: //# Normal chair sit. + case BOTH_SIT2: //# Lotus position. + case BOTH_SIT3: //# Sitting in tired position: elbows on knees + case BOTH_SIT2TO3: //# Trans from sit2 to sit3? + case BOTH_SIT3TO1: //# Trans from sit3 to sit1? + case BOTH_SIT3TO2: //# Trans from sit3 to sit2? + case BOTH_SIT4TO5: //# Trans from sit4 to sit5 + case BOTH_SIT4TO6: //# Trans from sit4 to sit6 + case BOTH_SIT5TO4: //# Trans from sit5 to sit4 + case BOTH_SIT5TO6: //# Trans from sit5 to sit6 + case BOTH_SIT6TO4: //# Trans from sit6 to sit4 + case BOTH_SIT6TO5: //# Trans from sit6 to sit5 + case BOTH_SIT7: //# sitting with arms over knees: no weapon + case BOTH_CROUCH1: //# Transition from standing to crouch + case BOTH_CROUCH1IDLE: //# Crouching idle + case BOTH_CROUCH1WALK: //# Walking while crouched + case BOTH_CROUCH1WALKBACK: //# Walking while crouched + case BOTH_CROUCH2IDLE: //# crouch and resting on back righ heel: no weapon + case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 + case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) + case BOTH_KNEES1: //# Tavion on her knees + case LEGS_CRLEAN_LEFT1: //# Crouch Lean left + case LEGS_CRLEAN_RIGHT1: //# Crouch Lean Right + case BOTH_CROUCHATTACKBACK1: // FIXME: not if in middle of anim? return qtrue; break; } return qfalse; } -qboolean PM_PainAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_PAIN1: //# First take pain anim - case BOTH_PAIN2: //# Second take pain anim - case BOTH_PAIN3: //# Third take pain anim - case BOTH_PAIN4: //# Fourth take pain anim - case BOTH_PAIN5: //# Fifth take pain anim - from behind - case BOTH_PAIN6: //# Sixth take pain anim - from behind - case BOTH_PAIN7: //# Seventh take pain anim - from behind - case BOTH_PAIN8: //# Eigth take pain anim - from behind - case BOTH_PAIN9: //# - case BOTH_PAIN10: //# - case BOTH_PAIN11: //# - case BOTH_PAIN12: //# - case BOTH_PAIN13: //# - case BOTH_PAIN14: //# - case BOTH_PAIN15: //# - case BOTH_PAIN16: //# - case BOTH_PAIN17: //# - case BOTH_PAIN18: //# - case BOTH_PAIN19: //# +qboolean PM_PainAnim(int anim) { + switch (anim) { + case BOTH_PAIN1: //# First take pain anim + case BOTH_PAIN2: //# Second take pain anim + case BOTH_PAIN3: //# Third take pain anim + case BOTH_PAIN4: //# Fourth take pain anim + case BOTH_PAIN5: //# Fifth take pain anim - from behind + case BOTH_PAIN6: //# Sixth take pain anim - from behind + case BOTH_PAIN7: //# Seventh take pain anim - from behind + case BOTH_PAIN8: //# Eigth take pain anim - from behind + case BOTH_PAIN9: //# + case BOTH_PAIN10: //# + case BOTH_PAIN11: //# + case BOTH_PAIN12: //# + case BOTH_PAIN13: //# + case BOTH_PAIN14: //# + case BOTH_PAIN15: //# + case BOTH_PAIN16: //# + case BOTH_PAIN17: //# + case BOTH_PAIN18: //# + case BOTH_PAIN19: //# return qtrue; break; } return qfalse; } -qboolean PM_DodgeAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_DODGE_FL: //# lean-dodge forward left - case BOTH_DODGE_FR: //# lean-dodge forward right - case BOTH_DODGE_BL: //# lean-dodge backwards left - case BOTH_DODGE_BR: //# lean-dodge backwards right - case BOTH_DODGE_L: //# lean-dodge left - case BOTH_DODGE_R: //# lean-dodge right +qboolean PM_DodgeAnim(int anim) { + switch (anim) { + case BOTH_DODGE_FL: //# lean-dodge forward left + case BOTH_DODGE_FR: //# lean-dodge forward right + case BOTH_DODGE_BL: //# lean-dodge backwards left + case BOTH_DODGE_BR: //# lean-dodge backwards right + case BOTH_DODGE_L: //# lean-dodge left + case BOTH_DODGE_R: //# lean-dodge right return qtrue; break; } return qfalse; } -qboolean PM_JumpingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_JUMP1: //# Jump - wind-up and leave ground - case BOTH_INAIR1: //# In air loop (from jump) - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_INAIRBACK1: //# In air loop (from jump back) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_INAIRLEFT1: //# In air loop (from jump left) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_INAIRRIGHT1: //# In air loop (from jump right) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground - case BOTH_FORCEINAIR1: //# In air loop (from jump) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_JumpingAnim(int anim) { + switch (anim) { + case BOTH_JUMP1: //# Jump - wind-up and leave ground + case BOTH_INAIR1: //# In air loop (from jump) + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_INAIRBACK1: //# In air loop (from jump back) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_INAIRLEFT1: //# In air loop (from jump left) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_INAIRRIGHT1: //# In air loop (from jump right) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground + case BOTH_FORCEINAIR1: //# In air loop (from jump) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_LandingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_LandingAnim(int anim) { + switch (anim) { + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_FlippingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_FLIP_F: //# Flip forward - case BOTH_FLIP_B: //# Flip backwards - case BOTH_FLIP_L: //# Flip left - case BOTH_FLIP_R: //# Flip right +qboolean PM_FlippingAnim(int anim) { + switch (anim) { + case BOTH_FLIP_F: //# Flip forward + case BOTH_FLIP_B: //# Flip backwards + case BOTH_FLIP_L: //# Flip left + case BOTH_FLIP_R: //# Flip right case BOTH_WALL_RUN_RIGHT_FLIP: case BOTH_WALL_RUN_LEFT_FLIP: case BOTH_WALL_FLIP_RIGHT: @@ -4088,7 +3447,7 @@ qboolean PM_FlippingAnim( int anim ) case BOTH_FLIP_BACK2: case BOTH_FLIP_BACK3: case BOTH_WALL_FLIP_BACK1: - //Not really flips, but... + // Not really flips, but... case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_LEFT: case BOTH_WALL_RUN_RIGHT_STOP: @@ -4109,40 +3468,36 @@ qboolean PM_FlippingAnim( int anim ) return qfalse; } -qboolean PM_WalkingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_WALK1: //# Normal walk - case BOTH_WALK2: //# Normal walk - case BOTH_WALK3: //# Goes with stand3 - case BOTH_WALK4: //# Walk cycle goes to a stand4 - case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) - case BOTH_WALK6: //# Slow walk for Luke (cin 12) - case BOTH_WALK7: //# Fast walk - case BOTH_WALKTORUN1: //# transition from walk to run - case BOTH_WALKBACK1: //# Walk1 backwards - case BOTH_WALKBACK2: //# Walk2 backwards +qboolean PM_WalkingAnim(int anim) { + switch (anim) { + case BOTH_WALK1: //# Normal walk + case BOTH_WALK2: //# Normal walk + case BOTH_WALK3: //# Goes with stand3 + case BOTH_WALK4: //# Walk cycle goes to a stand4 + case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) + case BOTH_WALK6: //# Slow walk for Luke (cin 12) + case BOTH_WALK7: //# Fast walk + case BOTH_WALKTORUN1: //# transition from walk to run + case BOTH_WALKBACK1: //# Walk1 backwards + case BOTH_WALKBACK2: //# Walk2 backwards return qtrue; break; } return qfalse; } -qboolean PM_RunningAnim( int anim ) -{ - switch ( anim ) - { +qboolean PM_RunningAnim(int anim) { + switch (anim) { case BOTH_RUN1: case BOTH_RUN2: case BOTH_RUNBACK1: case BOTH_RUNBACK2: case BOTH_WALKTORUN1: //# transition from walk to run - case BOTH_RUN1START: //# Start into full run1 + case BOTH_RUN1START: //# Start into full run1 case BOTH_RUN1STOP: //# Stop from full run1 case BOTH_RUNINJURED1: //# Run with injured left leg case BOTH_RUNSTRAFE_LEFT1: //# Sidestep left: should loop - case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop + case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop case BOTH_RUNAWAY1: //# Running scared return qtrue; break; @@ -4150,42 +3505,36 @@ qboolean PM_RunningAnim( int anim ) return qfalse; } -qboolean PM_RollingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_ROLL_F: //# Roll forward - case BOTH_ROLL_B: //# Roll backward - case BOTH_ROLL_L: //# Roll left - case BOTH_ROLL_R: //# Roll right - case BOTH_ROLL_FR: //# Roll forward right - case BOTH_ROLL_FL: //# Roll forward left - case BOTH_ROLL_BR: //# Roll back right - case BOTH_ROLL_BL: //# Roll back left +qboolean PM_RollingAnim(int anim) { + switch (anim) { + case BOTH_ROLL_F: //# Roll forward + case BOTH_ROLL_B: //# Roll backward + case BOTH_ROLL_L: //# Roll left + case BOTH_ROLL_R: //# Roll right + case BOTH_ROLL_FR: //# Roll forward right + case BOTH_ROLL_FL: //# Roll forward left + case BOTH_ROLL_BR: //# Roll back right + case BOTH_ROLL_BL: //# Roll back left return qtrue; break; } return qfalse; } -qboolean PM_SwimmingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SWIM1: //# Swimming - case BOTH_SWIM_IDLE1: //# Swimming Idle 1 - case BOTH_SWIMFORWARD: //# Swim forward loop +qboolean PM_SwimmingAnim(int anim) { + switch (anim) { + case BOTH_SWIM1: //# Swimming + case BOTH_SWIM_IDLE1: //# Swimming Idle 1 + case BOTH_SWIMFORWARD: //# Swim forward loop return qtrue; break; } return qfalse; } -qboolean PM_SpinningSaberAnim( int anim ) -{ - switch ( anim ) - { - //level 1 - FIXME: level 1 will have *no* spins +qboolean PM_SpinningSaberAnim(int anim) { + switch (anim) { + // level 1 - FIXME: level 1 will have *no* spins case BOTH_T1_BR_BL: case BOTH_T1__R__L: case BOTH_T1__R_BL: @@ -4198,28 +3547,28 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T1_BL_BR: case BOTH_T1_BL__R: case BOTH_T1_BL_TR: - //level 2 + // level 2 case BOTH_T2_BR__L: case BOTH_T2_BR_BL: case BOTH_T2__R_BL: case BOTH_T2__L_BR: case BOTH_T2_BL_BR: case BOTH_T2_BL__R: - //level 3 + // level 3 case BOTH_T3_BR__L: case BOTH_T3_BR_BL: case BOTH_T3__R_BL: case BOTH_T3__L_BR: case BOTH_T3_BL_BR: case BOTH_T3_BL__R: - //level 4 + // level 4 case BOTH_T4_BR__L: case BOTH_T4_BR_BL: case BOTH_T4__R_BL: case BOTH_T4__L_BR: case BOTH_T4_BL_BR: case BOTH_T4_BL__R: - //level 5 + // level 5 case BOTH_T5_BR_BL: case BOTH_T5__R__L: case BOTH_T5__R_BL: @@ -4232,8 +3581,8 @@ qboolean PM_SpinningSaberAnim( int anim ) case BOTH_T5_BL_BR: case BOTH_T5_BL__R: case BOTH_T5_BL_TR: - //special - //case BOTH_A2_STABBACK1: + // special + // case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: case BOTH_BUTTERFLY_LEFT: @@ -4248,8 +3597,7 @@ qboolean PM_SpinningSaberAnim( int anim ) return qfalse; } -qboolean PM_SpinningAnim( int anim ) -{ +qboolean PM_SpinningAnim(int anim) { /* switch ( anim ) { @@ -4258,91 +3606,76 @@ qboolean PM_SpinningAnim( int anim ) break; } */ - return PM_SpinningSaberAnim( anim ); + return PM_SpinningSaberAnim(anim); } -void PM_ResetAnkleAngles( void ) -{ - if ( !pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_ATST ) - { +void PM_ResetAnkleAngles(void) { + if (!pm->gent || !pm->gent->client || pm->gent->client->NPC_class != CLASS_ATST) { return; } - if ( pm->gent->footLBone != -1 ) - { - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footLBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (pm->gent->footLBone != -1) { + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footLBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, + 0); } - if ( pm->gent->footRBone != -1 ) - { - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footRBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (pm->gent->footRBone != -1) { + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footRBone, vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, + 0); } } -void PM_AnglesForSlope( const float yaw, const vec3_t slope, vec3_t angles ) -{ - vec3_t nvf, ovf, ovr, new_angles; - float pitch, mod, dot; +void PM_AnglesForSlope(const float yaw, const vec3_t slope, vec3_t angles) { + vec3_t nvf, ovf, ovr, new_angles; + float pitch, mod, dot; - VectorSet( angles, 0, yaw, 0 ); - AngleVectors( angles, ovf, ovr, NULL ); + VectorSet(angles, 0, yaw, 0); + AngleVectors(angles, ovf, ovr, NULL); - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod < 0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); angles[YAW] = 0; angles[PITCH] = dot * pitch; - angles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + angles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } -void PM_FootSlopeTrace( float *pDiff, float *pInterval ) -{ - vec3_t footLOrg, footROrg, footLBot, footRBot; - trace_t trace; - float diff, interval; - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { +void PM_FootSlopeTrace(float *pDiff, float *pInterval) { + vec3_t footLOrg, footROrg, footLBot, footRBot; + trace_t trace; + float diff, interval; + if (pm->gent->client->NPC_class == CLASS_ATST) { interval = 10; - } - else - { - interval = 4;//? + } else { + interval = 4; //? } - if ( pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1 ) - { - if ( pDiff != NULL ) - { + if (pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1) { + if (pDiff != NULL) { *pDiff = 0; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } return; } #if 1 - for ( int i = 0; i < 3; i++ ) - { - if ( Q_isnan( pm->gent->client->renderInfo.footLPoint[i] ) - || Q_isnan( pm->gent->client->renderInfo.footRPoint[i] ) ) - { - if ( pDiff != NULL ) - { + for (int i = 0; i < 3; i++) { + if (Q_isnan(pm->gent->client->renderInfo.footLPoint[i]) || Q_isnan(pm->gent->client->renderInfo.footRPoint[i])) { + if (pDiff != NULL) { *pDiff = 0; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } return; @@ -4350,21 +3683,19 @@ void PM_FootSlopeTrace( float *pDiff, float *pInterval ) } #else - //FIXME: these really should have been gotten on the cgame, but I guess sometimes they're not and we end up with qnan numbers! - mdxaBone_t boltMatrix; - vec3_t G2Angles = {0, pm->gent->client->ps.legsYaw, 0}; - //get the feet - gi.G2API_GetBoltMatrix( pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footLBolt, - &boltMatrix, G2Angles, pm->ps->origin, (cg.time?cg.time:level.time), - NULL, pm->gent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footLPoint ); - - gi.G2API_GetBoltMatrix( pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footRBolt, - &boltMatrix, G2Angles, pm->ps->origin, (cg.time?cg.time:level.time), - NULL, pm->gent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint ); + // FIXME: these really should have been gotten on the cgame, but I guess sometimes they're not and we end up with qnan numbers! + mdxaBone_t boltMatrix; + vec3_t G2Angles = {0, pm->gent->client->ps.legsYaw, 0}; + // get the feet + gi.G2API_GetBoltMatrix(pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footLBolt, &boltMatrix, G2Angles, pm->ps->origin, + (cg.time ? cg.time : level.time), NULL, pm->gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pm->gent->client->renderInfo.footLPoint); + + gi.G2API_GetBoltMatrix(pm->gent->ghoul2, pm->gent->playerModel, pm->gent->footRBolt, &boltMatrix, G2Angles, pm->ps->origin, + (cg.time ? cg.time : level.time), NULL, pm->gent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint); #endif - //NOTE: on AT-STs, rotating the foot moves this point, so it will wiggle... + // NOTE: on AT-STs, rotating the foot moves this point, so it will wiggle... // we have to do this extra work (more G2 transforms) to stop the wiggle... is it worth it? /* if ( pm->gent->client->NPC_class == CLASS_ATST ) @@ -4385,82 +3716,74 @@ void PM_FootSlopeTrace( float *pDiff, float *pInterval ) gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, pm->gent->client->renderInfo.footRPoint ); } */ - //get these on the cgame and store it, save ourselves a ghoul2 construct skel call - VectorCopy( pm->gent->client->renderInfo.footLPoint, footLOrg ); - VectorCopy( pm->gent->client->renderInfo.footRPoint, footROrg ); + // get these on the cgame and store it, save ourselves a ghoul2 construct skel call + VectorCopy(pm->gent->client->renderInfo.footLPoint, footLOrg); + VectorCopy(pm->gent->client->renderInfo.footRPoint, footROrg); - //step 2: adjust foot tag z height to bottom of bbox+1 + // step 2: adjust foot tag z height to bottom of bbox+1 footLOrg[2] = pm->gent->currentOrigin[2] + pm->gent->mins[2] + 1; footROrg[2] = pm->gent->currentOrigin[2] + pm->gent->mins[2] + 1; - VectorSet( footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval*10 ); - VectorSet( footRBot, footROrg[0], footROrg[1], footROrg[2] - interval*10 ); + VectorSet(footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval * 10); + VectorSet(footRBot, footROrg[0], footROrg[1], footROrg[2] - interval * 10); - //step 3: trace down from each, find difference + // step 3: trace down from each, find difference vec3_t footMins, footMaxs; vec3_t footLSlope, footRSlope; - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { - VectorSet( footMins, -16, -16, 0 ); - VectorSet( footMaxs, 16, 16, 1 ); - } - else - { - VectorSet( footMins, -3, -3, 0 ); - VectorSet( footMaxs, 3, 3, 1 ); + if (pm->gent->client->NPC_class == CLASS_ATST) { + VectorSet(footMins, -16, -16, 0); + VectorSet(footMaxs, 16, 16, 1); + } else { + VectorSet(footMins, -3, -3, 0); + VectorSet(footMaxs, 3, 3, 1); } - pm->trace( &trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); - VectorCopy( trace.endpos, footLBot ); - VectorCopy( trace.plane.normal, footLSlope ); + pm->trace(&trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + VectorCopy(trace.endpos, footLBot); + VectorCopy(trace.plane.normal, footLSlope); - pm->trace( &trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0 ); - VectorCopy( trace.endpos, footRBot ); - VectorCopy( trace.plane.normal, footRSlope ); + pm->trace(&trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + VectorCopy(trace.endpos, footRBot); + VectorCopy(trace.plane.normal, footRSlope); diff = footLBot[2] - footRBot[2]; - //optional step: for atst, tilt the footpads to match the slopes under it... - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { + // optional step: for atst, tilt the footpads to match the slopes under it... + if (pm->gent->client->NPC_class == CLASS_ATST) { vec3_t footAngles; - if ( !VectorCompare( footLSlope, vec3_origin ) ) - {//rotate the ATST's left foot pad to match the slope - PM_AnglesForSlope( pm->gent->client->renderInfo.legsYaw, footLSlope, footAngles ); - //Hmm... lerp this? - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footLBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (!VectorCompare(footLSlope, vec3_origin)) { // rotate the ATST's left foot pad to match the slope + PM_AnglesForSlope(pm->gent->client->renderInfo.legsYaw, footLSlope, footAngles); + // Hmm... lerp this? + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footLBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, + 0, 0); } - if ( !VectorCompare( footRSlope, vec3_origin ) ) - {//rotate the ATST's right foot pad to match the slope - PM_AnglesForSlope( pm->gent->client->renderInfo.legsYaw, footRSlope, footAngles ); - //Hmm... lerp this? - gi.G2API_SetBoneAnglesIndex( &pm->gent->ghoul2[0], pm->gent->footRBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + if (!VectorCompare(footRSlope, vec3_origin)) { // rotate the ATST's right foot pad to match the slope + PM_AnglesForSlope(pm->gent->client->renderInfo.legsYaw, footRSlope, footAngles); + // Hmm... lerp this? + gi.G2API_SetBoneAnglesIndex(&pm->gent->ghoul2[0], pm->gent->footRBone, footAngles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, + 0, 0); } } - if ( pDiff != NULL ) - { + if (pDiff != NULL) { *pDiff = diff; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } } -qboolean PM_InSlopeAnim( int anim ) -{ - switch ( anim ) - { - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left +qboolean PM_InSlopeAnim(int anim) { + switch (anim) { + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left case LEGS_S1_LUP1: case LEGS_S1_LUP2: case LEGS_S1_LUP3: @@ -4507,85 +3830,56 @@ qboolean PM_InSlopeAnim( int anim ) return qfalse; } -#define SLOPE_RECALC_INT 100 -extern qboolean G_StandardHumanoid( const char *modelName ); -qboolean PM_AdjustStandAnimForSlope( void ) -{ - if ( !pm->gent || !pm->gent->client ) - { +#define SLOPE_RECALC_INT 100 +extern qboolean G_StandardHumanoid(const char *modelName); +qboolean PM_AdjustStandAnimForSlope(void) { + if (!pm->gent || !pm->gent->client) { return qfalse; } - if ( pm->gent->client->NPC_class != CLASS_ATST - && (!pm->gent||!G_StandardHumanoid( pm->gent->NPC_type )) ) - {//only ATST and player does this + if (pm->gent->client->NPC_class != CLASS_ATST && (!pm->gent || !G_StandardHumanoid(pm->gent->NPC_type))) { // only ATST and player does this return qfalse; } - if ( !pm->ps->clientNum && (!cg.renderingThirdPerson || cg.zoomMode) ) - {//first person doesn't do this + if (!pm->ps->clientNum && (!cg.renderingThirdPerson || cg.zoomMode)) { // first person doesn't do this return qfalse; } - if ( pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1 ) - {//need these bolts! + if (pm->gent->footLBolt == -1 || pm->gent->footRBolt == -1) { // need these bolts! return qfalse; } - //step 1: find the 2 foot tags - float diff; - float interval; - PM_FootSlopeTrace( &diff, &interval ); + // step 1: find the 2 foot tags + float diff; + float interval; + PM_FootSlopeTrace(&diff, &interval); - //step 4: based on difference, choose one of the left/right slope-match intervals - int destAnim; - if ( diff >= interval*5 ) - { + // step 4: based on difference, choose one of the left/right slope-match intervals + int destAnim; + if (diff >= interval * 5) { destAnim = LEGS_LEFTUP5; - } - else if ( diff >= interval*4 ) - { + } else if (diff >= interval * 4) { destAnim = LEGS_LEFTUP4; - } - else if ( diff >= interval*3 ) - { + } else if (diff >= interval * 3) { destAnim = LEGS_LEFTUP3; - } - else if ( diff >= interval*2 ) - { + } else if (diff >= interval * 2) { destAnim = LEGS_LEFTUP2; - } - else if ( diff >= interval ) - { + } else if (diff >= interval) { destAnim = LEGS_LEFTUP1; - } - else if ( diff <= interval*-5 ) - { + } else if (diff <= interval * -5) { destAnim = LEGS_RIGHTUP5; - } - else if ( diff <= interval*-4 ) - { + } else if (diff <= interval * -4) { destAnim = LEGS_RIGHTUP4; - } - else if ( diff <= interval*-3 ) - { + } else if (diff <= interval * -3) { destAnim = LEGS_RIGHTUP3; - } - else if ( diff <= interval*-2 ) - { + } else if (diff <= interval * -2) { destAnim = LEGS_RIGHTUP2; - } - else if ( diff <= interval*-1 ) - { + } else if (diff <= interval * -1) { destAnim = LEGS_RIGHTUP1; - } - else - { + } else { return qfalse; } int legsAnim = pm->ps->legsAnim; - if ( pm->gent->client->NPC_class != CLASS_ATST ) - { - //adjust for current legs anim - switch ( legsAnim ) - { + if (pm->gent->client->NPC_class != CLASS_ATST) { + // adjust for current legs anim + switch (legsAnim) { case BOTH_STAND1: case LEGS_S1_LUP1: case LEGS_S1_LUP2: @@ -4597,24 +3891,24 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S1_RUP3: case LEGS_S1_RUP4: case LEGS_S1_RUP5: - destAnim = LEGS_S1_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S1_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND2: case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: case BOTH_CROUCH1: - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left - //fine + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left + // fine break; case BOTH_STAND3: case LEGS_S3_LUP1: @@ -4627,7 +3921,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S3_RUP3: case LEGS_S3_RUP4: case LEGS_S3_RUP5: - destAnim = LEGS_S3_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S3_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND4: case LEGS_S4_LUP1: @@ -4640,7 +3934,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S4_RUP3: case LEGS_S4_RUP4: case LEGS_S4_RUP5: - destAnim = LEGS_S4_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S4_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND5: case LEGS_S5_LUP1: @@ -4653,7 +3947,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S5_RUP3: case LEGS_S5_RUP4: case LEGS_S5_RUP5: - destAnim = LEGS_S5_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S5_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND6: default: @@ -4661,89 +3955,55 @@ qboolean PM_AdjustStandAnimForSlope( void ) break; } } - //step 5: based on the chosen interval and the current legsAnim, pick the correct anim - //step 6: increment/decrement to the dest anim, not instant - if ( (legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) - || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) - || (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) - || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) - || (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5) ) - {//already in left-side up - if ( destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + // step 5: based on the chosen interval and the current legsAnim, pick the correct anim + // step 6: increment/decrement to the dest anim, not instant + if ((legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) || + (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) || + (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5)) { // already in left-side up + if (destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim++; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if (destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim--; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - { + } else { destAnim = legsAnim; } - } - else if ( (legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) - || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) - || (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) - || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) - || (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5) ) - {//already in right-side up - if ( destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if ((legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) || + (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) || + (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5)) { // already in right-side up + if (destAnim > legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim++; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time ) - { + } else if (destAnim < legsAnim && pm->gent->client->slopeRecalcTime < level.time) { legsAnim--; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - { + } else { destAnim = legsAnim; } - } - else - {//in a stand of some sort? - if ( pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( legsAnim == BOTH_STAND1 || legsAnim == BOTH_STAND2 || legsAnim == BOTH_CROUCH1IDLE ) - { - if ( destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5 ) - {//going into left side up + } else { // in a stand of some sort? + if (pm->gent->client->NPC_class == CLASS_ATST) { + if (legsAnim == BOTH_STAND1 || legsAnim == BOTH_STAND2 || legsAnim == BOTH_CROUCH1IDLE) { + if (destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5) { // going into left side up destAnim = LEGS_LEFTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5) { // going into right side up destAnim = LEGS_RIGHTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } } - } - else - { - switch ( legsAnim ) - { + } else { + switch (legsAnim) { case BOTH_STAND1: - if ( destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5) { // going into left side up destAnim = LEGS_S1_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5) { // going into right side up destAnim = LEGS_S1_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -4751,66 +4011,46 @@ qboolean PM_AdjustStandAnimForSlope( void ) case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: - if ( destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5 ) - {//going into left side up + if (destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5) { // going into left side up destAnim = LEGS_LEFTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5) { // going into right side up destAnim = LEGS_RIGHTUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND3: - if ( destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5) { // going into left side up destAnim = LEGS_S3_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5) { // going into right side up destAnim = LEGS_S3_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND4: - if ( destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5) { // going into left side up destAnim = LEGS_S4_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5) { // going into right side up destAnim = LEGS_S4_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND5: - if ( destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5) { // going into left side up destAnim = LEGS_S5_LUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5) { // going into right side up destAnim = LEGS_S5_RUP1; pm->gent->client->slopeRecalcTime = level.time + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -4821,34 +4061,25 @@ qboolean PM_AdjustStandAnimForSlope( void ) } } } - //step 7: set the anim - PM_SetAnim( pm, SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL ); + // step 7: set the anim + PM_SetAnim(pm, SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL); return qtrue; } -void PM_SwimFloatAnim( void ) -{ +void PM_SwimFloatAnim(void) { int legsAnim = pm->ps->legsAnim; - //FIXME: no start or stop anims - if ( pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIMFORWARD,SETANIM_FLAG_NORMAL); - } - else - {//stopping - if ( legsAnim == BOTH_SWIMFORWARD ) - {//I was swimming - if ( !pm->ps->legsAnimTimer ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); + // FIXME: no start or stop anims + if (pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIMFORWARD, SETANIM_FLAG_NORMAL); + } else { // stopping + if (legsAnim == BOTH_SWIMFORWARD) { // I was swimming + if (!pm->ps->legsAnimTimer) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); } - } - else - {//idle - if ( !(pm->ps->pm_flags&PMF_DUCKED) && pm->cmd.upmove >= 0 ) - {//not crouching - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SWIM_IDLE1,SETANIM_FLAG_NORMAL); + } else { // idle + if (!(pm->ps->pm_flags & PMF_DUCKED) && pm->cmd.upmove >= 0) { // not crouching + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SWIM_IDLE1, SETANIM_FLAG_NORMAL); } } } @@ -4859,169 +4090,127 @@ void PM_SwimFloatAnim( void ) PM_Footsteps =============== */ -static void PM_Footsteps( void ) -{ - float bobmove; - int old, oldAnim; - qboolean footstep = qfalse; - qboolean validNPC = qfalse; - qboolean flipping = qfalse; - int setAnimFlags = SETANIM_FLAG_NORMAL; - - if( pm->gent == NULL || pm->gent->client == NULL ) +static void PM_Footsteps(void) { + float bobmove; + int old, oldAnim; + qboolean footstep = qfalse; + qboolean validNPC = qfalse; + qboolean flipping = qfalse; + int setAnimFlags = SETANIM_FLAG_NORMAL; + + if (pm->gent == NULL || pm->gent->client == NULL) return; - if ( PM_SpinningSaberAnim( pm->ps->legsAnim ) && pm->ps->legsAnimTimer ) - {//spinning + if (PM_SpinningSaberAnim(pm->ps->legsAnim) && pm->ps->legsAnimTimer) { // spinning return; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown return; } - if( pm->gent->NPC != NULL ) - { + if (pm->gent->NPC != NULL) { validNPC = qtrue; } pm->gent->client->renderInfo.legsFpsMod = 1.0f; - //PM_ResetAnkleAngles(); + // PM_ResetAnkleAngles(); // // calculate speed and cycle to be used for // all cyclic walking effects // - pm->xyspeed = sqrt( pm->ps->velocity[0] * pm->ps->velocity[0] - + pm->ps->velocity[1] * pm->ps->velocity[1] ); + pm->xyspeed = sqrt(pm->ps->velocity[0] * pm->ps->velocity[0] + pm->ps->velocity[1] * pm->ps->velocity[1]); - if ( pm->ps->legsAnim == BOTH_FLIP_F || - pm->ps->legsAnim == BOTH_FLIP_B || - pm->ps->legsAnim == BOTH_FLIP_L || - pm->ps->legsAnim == BOTH_FLIP_R ) - { + if (pm->ps->legsAnim == BOTH_FLIP_F || pm->ps->legsAnim == BOTH_FLIP_B || pm->ps->legsAnim == BOTH_FLIP_L || pm->ps->legsAnim == BOTH_FLIP_R) { flipping = qtrue; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE - || ( pm->watertype & CONTENTS_LADDER ) - || pm->ps->waterHeightLevel >= WHL_TORSO ) - {//in air or submerged in water or in ladder + if (pm->ps->groundEntityNum == ENTITYNUM_NONE || (pm->watertype & CONTENTS_LADDER) || + pm->ps->waterHeightLevel >= WHL_TORSO) { // in air or submerged in water or in ladder // airborne leaves position in cycle intact, but doesn't advance - if ( pm->waterlevel > 0 ) - { - if ( pm->watertype & CONTENTS_LADDER ) - {//FIXME: check for watertype, save waterlevel for whether to play - //the get off ladder transition anim! - if ( pm->ps->velocity[2] ) - {//going up or down it - int anim; - if ( pm->ps->velocity[2] > 0 ) - { + if (pm->waterlevel > 0) { + if (pm->watertype & CONTENTS_LADDER) { // FIXME: check for watertype, save waterlevel for whether to play + // the get off ladder transition anim! + if (pm->ps->velocity[2]) { // going up or down it + int anim; + if (pm->ps->velocity[2] > 0) { anim = BOTH_LADDER_UP1; - } - else - { + } else { anim = BOTH_LADDER_DWN1; } - PM_SetAnim( pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( pm->waterlevel >= 2 ) //arms on ladder + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (pm->waterlevel >= 2) // arms on ladder { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if (fabs(pm->ps->velocity[2]) >5) { - bobmove = 0.005 * fabs(pm->ps->velocity[2]); // climbing bobs slow + if (fabs(pm->ps->velocity[2]) > 5) { + bobmove = 0.005 * fabs(pm->ps->velocity[2]); // climbing bobs slow if (bobmove > 0.3) bobmove = 0.3F; goto DoFootSteps; } - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); pm->ps->legsAnimTimer += 300; - if ( pm->waterlevel >= 2 ) //arms on ladder + if (pm->waterlevel >= 2) // arms on ladder { - PM_SetAnim( pm, SETANIM_TORSO, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_LADDER_IDLE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); pm->ps->torsoAnimTimer += 300; } } return; - } - else if ( pm->ps->waterHeightLevel >= WHL_TORSO - && (!pm->ps->clientNum||pm->ps->weapon==WP_SABER||pm->ps->weapon==WP_NONE||pm->ps->weapon==WP_MELEE) )//pm->waterlevel > 1 ) //in deep water - { - if ( !PM_ForceJumpingUp( pm->gent ) ) - { - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE && (pm->ps->pm_flags&PMF_DUCKED) ) - { - if ( !flipping ) - {//you can crouch under water if feet are on ground - if ( pm->cmd.forwardmove || pm->cmd.rightmove ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALKBACK,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALK,setAnimFlags); + } else if (pm->ps->waterHeightLevel >= WHL_TORSO && (!pm->ps->clientNum || pm->ps->weapon == WP_SABER || pm->ps->weapon == WP_NONE || + pm->ps->weapon == WP_MELEE)) // pm->waterlevel > 1 ) //in deep water + { + if (!PM_ForceJumpingUp(pm->gent)) { + if (pm->ps->groundEntityNum != ENTITYNUM_NONE && (pm->ps->pm_flags & PMF_DUCKED)) { + if (!flipping) { // you can crouch under water if feet are on ground + if (pm->cmd.forwardmove || pm->cmd.rightmove) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); } - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } return; } } PM_SwimFloatAnim(); - if ( pm->ps->legsAnim != BOTH_SWIM_IDLE1 ) - {//moving + if (pm->ps->legsAnim != BOTH_SWIM_IDLE1) { // moving old = pm->ps->bobCycle; - bobmove = 0.15f; // swim is a slow cycle - pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255; + bobmove = 0.15f; // swim is a slow cycle + pm->ps->bobCycle = (int)(old + bobmove * pml.msec) & 255; // if we just crossed a cycle boundary, play an apropriate footstep event - if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) - { - PM_AddEvent( EV_SWIM ); + if (((old + 64) ^ (pm->ps->bobCycle + 64)) & 128) { + PM_AddEvent(EV_SWIM); } } } return; - } - else - {//hmm, in water, but not high enough to swim - //fall through to walk/run/stand - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//unless in the air - //NOTE: this is a dupe of the code just below... for when you are not in the water at all - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if ( !flipping ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else { // hmm, in water, but not high enough to swim + // fall through to walk/run/stand + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // unless in the air + // NOTE: this is a dupe of the code just below... for when you are not in the water at all + if (pm->ps->pm_flags & PMF_DUCKED) { + if (!flipping) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->ps->gravity <= 0 )//FIXME: or just less than normal? + } else if (pm->ps->gravity <= 0) // FIXME: or just less than normal? { PM_SwimFloatAnim(); } return; } } - } - else - { - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if ( !flipping ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else { + if (pm->ps->pm_flags & PMF_DUCKED) { + if (!flipping) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->ps->gravity <= 0 )//FIXME: or just less than normal? + } else if (pm->ps->gravity <= 0) // FIXME: or just less than normal? { PM_SwimFloatAnim(); } @@ -5029,70 +4218,51 @@ static void PM_Footsteps( void ) } } - if ( PM_SwimmingAnim( pm->ps->legsAnim ) && pm->waterlevel < 2 ) - {//legs are in swim anim, and not swimming, be sure to override it + if (PM_SwimmingAnim(pm->ps->legsAnim) && pm->waterlevel < 2) { // legs are in swim anim, and not swimming, be sure to override it setAnimFlags |= SETANIM_FLAG_OVERRIDE; } // if not trying to move - if ( !pm->cmd.forwardmove && !pm->cmd.rightmove ) - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (!pm->cmd.forwardmove && !pm->cmd.rightmove) { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if( !PM_InOnGroundAnim( pm->ps ) ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1,SETANIM_FLAG_NORMAL); + } else if (pm->ps->pm_flags & PMF_DUCKED) { + if (!PM_InOnGroundAnim(pm->ps)) { + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_NORMAL); } } - } - else - { - if ( pm->ps->legsAnimTimer && PM_LandingAnim( pm->ps->legsAnim ) ) - {//still in a landing anim, let it play + } else { + if (pm->ps->legsAnimTimer && PM_LandingAnim(pm->ps->legsAnim)) { // still in a landing anim, let it play return; } qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {//NOTE: stand1 is with the helmet retracted, stand1to2 is the helmet going into place - PM_SetAnim( pm, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_NORMAL ); - } - else if ( pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_SABERPULL,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && + pm->gent->client->NPC_class == CLASS_GALAKMECH) { // NOTE: stand1 is with the helmet retracted, stand1to2 is the helmet going into place + PM_SetAnim(pm, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir) { + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_SABERPULL, SETANIM_FLAG_NORMAL); } - } - else if ( (pm->ps->weapon == WP_SABER&&pm->ps->saberLength>0&&!pm->ps->saberInFlight) ) - { - if ( !PM_AdjustStandAnimForSlope() ) - { + } else if ((pm->ps->weapon == WP_SABER && pm->ps->saberLength > 0 && !pm->ps->saberInFlight)) { + if (!PM_AdjustStandAnimForSlope()) { int legsAnim; - switch ( pm->ps->saberAnimLevel ) - { + switch (pm->ps->saberAnimLevel) { case FORCE_LEVEL_1: case FORCE_LEVEL_5: legsAnim = BOTH_SABERFAST_STANCE; @@ -5107,38 +4277,28 @@ static void PM_Footsteps( void ) legsAnim = BOTH_STAND2; break; } - PM_SetAnim(pm,SETANIM_LEGS,legsAnim,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_LEGS, legsAnim, SETANIM_FLAG_NORMAL); } - } - else if( (validNPC && pm->ps->weapon > WP_SABER && pm->ps->weapon < WP_DET_PACK ))//Being careful or carrying a 2-handed weapon - {//Squadmates use BOTH_STAND3 + } else if ((validNPC && pm->ps->weapon > WP_SABER && pm->ps->weapon < WP_DET_PACK)) // Being careful or carrying a 2-handed weapon + { // Squadmates use BOTH_STAND3 oldAnim = pm->ps->legsAnim; - if(oldAnim != BOTH_GUARD_LOOKAROUND1 && oldAnim != BOTH_GUARD_IDLE1 && - oldAnim != BOTH_STAND3IDLE1 && oldAnim != BOTH_STAND2TO4 - && oldAnim != BOTH_STAND4TO2 && oldAnim != BOTH_STAND4 ) - {//Don't auto-override the guard idles - if ( !PM_AdjustStandAnimForSlope() ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND3,SETANIM_FLAG_NORMAL); - //if(oldAnim != BOTH_STAND2 && pm->ps->legsAnim == BOTH_STAND2) + if (oldAnim != BOTH_GUARD_LOOKAROUND1 && oldAnim != BOTH_GUARD_IDLE1 && oldAnim != BOTH_STAND3IDLE1 && oldAnim != BOTH_STAND2TO4 && + oldAnim != BOTH_STAND4TO2 && oldAnim != BOTH_STAND4) { // Don't auto-override the guard idles + if (!PM_AdjustStandAnimForSlope()) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND3, SETANIM_FLAG_NORMAL); + // if(oldAnim != BOTH_STAND2 && pm->ps->legsAnim == BOTH_STAND2) //{ // pm->ps->legsAnimTimer = 500; - //} + // } } } - } - else - { - if ( !PM_AdjustStandAnimForSlope() ) - { + } else { + if (!PM_AdjustStandAnimForSlope()) { // FIXME: Do we need this here... The imps stand is 4, not 1... - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_IMPERIAL ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND4,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_IMPERIAL) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND4, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_STAND1, SETANIM_FLAG_NORMAL); } } } @@ -5146,152 +4306,100 @@ static void PM_Footsteps( void ) return; } - //maybe call this every frame, even when moving? - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - PM_FootSlopeTrace( NULL, NULL ); - } - - //trying to move laterally - if ( (PM_InSaberAnim( pm->ps->legsAnim ) && !PM_SpinningSaberAnim( pm->ps->legsAnim )) - || pm->ps->legsAnim == BOTH_STAND1 - || pm->ps->legsAnim == BOTH_STAND1TO2 - || pm->ps->legsAnim == BOTH_STAND2TO1 - || pm->ps->legsAnim == BOTH_STAND2 - || pm->ps->legsAnim == BOTH_SABERFAST_STANCE - || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE - || pm->ps->legsAnim == BOTH_BUTTON_HOLD - || pm->ps->legsAnim == BOTH_BUTTON_RELEASE - || PM_LandingAnim( pm->ps->legsAnim ) - || PM_PainAnim( pm->ps->legsAnim ) - || PM_ForceAnim( pm->ps->legsAnim )) - {//legs are in a saber anim, and not spinning, be sure to override it + // maybe call this every frame, even when moving? + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + PM_FootSlopeTrace(NULL, NULL); + } + + // trying to move laterally + if ((PM_InSaberAnim(pm->ps->legsAnim) && !PM_SpinningSaberAnim(pm->ps->legsAnim)) || pm->ps->legsAnim == BOTH_STAND1 || + pm->ps->legsAnim == BOTH_STAND1TO2 || pm->ps->legsAnim == BOTH_STAND2TO1 || pm->ps->legsAnim == BOTH_STAND2 || + pm->ps->legsAnim == BOTH_SABERFAST_STANCE || pm->ps->legsAnim == BOTH_SABERSLOW_STANCE || pm->ps->legsAnim == BOTH_BUTTON_HOLD || + pm->ps->legsAnim == BOTH_BUTTON_RELEASE || PM_LandingAnim(pm->ps->legsAnim) || PM_PainAnim(pm->ps->legsAnim) || + PM_ForceAnim(pm->ps->legsAnim)) { // legs are in a saber anim, and not spinning, be sure to override it setAnimFlags |= SETANIM_FLAG_OVERRIDE; } - if ( (pm->ps->eFlags&EF_IN_ATST) )//does this catch NPCs, too? - {//atst - if ( pm->ps->legsAnim == BOTH_TURN_LEFT1 || - pm->ps->legsAnim == BOTH_TURN_RIGHT1 ) - {//moving overrides turning + if ((pm->ps->eFlags & EF_IN_ATST)) // does this catch NPCs, too? + { // atst + if (pm->ps->legsAnim == BOTH_TURN_LEFT1 || pm->ps->legsAnim == BOTH_TURN_RIGHT1) { // moving overrides turning setAnimFlags |= SETANIM_FLAG_OVERRIDE; } } - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - bobmove = 0.5; // ducked characters bob much faster - if( !PM_InOnGroundAnim( pm->ps ) ) - { + if (pm->ps->pm_flags & PMF_DUCKED) { + bobmove = 0.5; // ducked characters bob much faster + if (!PM_InOnGroundAnim(pm->ps)) { qboolean rolled = qfalse; - if ( PM_RunningAnim( pm->ps->legsAnim ) || pm->ps->legsAnim == BOTH_FORCEHEAL_START ) - {//roll! + if (PM_RunningAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_FORCEHEAL_START) { // roll! rolled = PM_TryRoll(); } - if ( !rolled ) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALKBACK,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_CROUCH1WALK,setAnimFlags); + if (!rolled) { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); } } } // ducked characters never play footsteps - } - else if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - {//Moving backwards - if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) - {//running backwards - bobmove = 0.4F; // faster speeds bob faster - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUNBACK1,setAnimFlags); + } else if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { // Moving backwards + if (!(pm->cmd.buttons & BUTTON_WALKING)) { // running backwards + bobmove = 0.4F; // faster speeds bob faster + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUNBACK1, setAnimFlags); footstep = qtrue; + } else { // walking backwards + bobmove = 0.3F; // faster speeds bob faster + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALKBACK1, setAnimFlags); } - else - {//walking backwards - bobmove = 0.3F; // faster speeds bob faster - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALKBACK1,setAnimFlags); - } - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - { - bobmove = 0.3F; // walking bobs slow - if ( pm->ps->weapon == WP_NONE ) - {//helmet retracted - PM_SetAnim( pm, SETANIM_BOTH, BOTH_WALK1, SETANIM_FLAG_NORMAL ); - } - else - {//helmet in place - PM_SetAnim( pm, SETANIM_BOTH, BOTH_WALK2, SETANIM_FLAG_NORMAL ); - } - } - else if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) - { - bobmove = 0.4F; // faster speeds bob faster - if ( pm->ps->weapon == WP_SABER && pm->ps->saberActive ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_RUN2,setAnimFlags); - } - else - { - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( pm->ps->legsAnim != BOTH_RUN1 ) - { - if ( pm->ps->legsAnim != BOTH_RUN1START ) - {//Hmm, he should really start slow and have to accelerate... also need to do this for stopping - PM_SetAnim( pm,SETANIM_LEGS, BOTH_RUN1START, setAnimFlags|SETANIM_FLAG_HOLD ); - } - else if ( !pm->ps->legsAnimTimer ) - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { + bobmove = 0.3F; // walking bobs slow + if (pm->ps->weapon == WP_NONE) { // helmet retracted + PM_SetAnim(pm, SETANIM_BOTH, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else { // helmet in place + PM_SetAnim(pm, SETANIM_BOTH, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } + } else if (!(pm->cmd.buttons & BUTTON_WALKING)) { + bobmove = 0.4F; // faster speeds bob faster + if (pm->ps->weapon == WP_SABER && pm->ps->saberActive) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN2, setAnimFlags); + } else { + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + if (pm->ps->legsAnim != BOTH_RUN1) { + if (pm->ps->legsAnim != BOTH_RUN1START) { // Hmm, he should really start slow and have to accelerate... also need to do this for + // stopping + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1START, setAnimFlags | SETANIM_FLAG_HOLD); + } else if (!pm->ps->legsAnimTimer) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); - } - } - else - { - PM_SetAnim( pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags ); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_RUN1, setAnimFlags); } } footstep = qtrue; - } - else - { - bobmove = 0.3F; // walking bobs slow - if ( pm->ps->clientNum && pm->ps->weapon == WP_SABER && pm->ps->saberActive ) - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK2,setAnimFlags); - } - else - { - PM_SetAnim(pm,SETANIM_LEGS,BOTH_WALK1,setAnimFlags); + } else { + bobmove = 0.3F; // walking bobs slow + if (pm->ps->clientNum && pm->ps->weapon == WP_SABER && pm->ps->saberActive) { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK2, setAnimFlags); + } else { + PM_SetAnim(pm, SETANIM_LEGS, BOTH_WALK1, setAnimFlags); } - //Enemy NPCs always make footsteps for the benefit of the player - if ( pm->gent && pm->gent->NPC && pm->gent->client && pm->gent->client->playerTeam != TEAM_PLAYER ) - { + // Enemy NPCs always make footsteps for the benefit of the player + if (pm->gent && pm->gent->NPC && pm->gent->client && pm->gent->client->playerTeam != TEAM_PLAYER) { footstep = qtrue; } } } - if(pm->gent != NULL) - { - if( pm->gent->client->renderInfo.legsFpsMod > 2 ) - { + if (pm->gent != NULL) { + if (pm->gent->client->renderInfo.legsFpsMod > 2) { pm->gent->client->renderInfo.legsFpsMod = 2; - } - else if(pm->gent->client->renderInfo.legsFpsMod < 0.5) - { + } else if (pm->gent->client->renderInfo.legsFpsMod < 0.5) { pm->gent->client->renderInfo.legsFpsMod = 0.5; } } @@ -5300,74 +4408,54 @@ static void PM_Footsteps( void ) // check for footstep / splash sounds old = pm->ps->bobCycle; - pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255; + pm->ps->bobCycle = (int)(old + bobmove * pml.msec) & 255; // if we just crossed a cycle boundary, play an apropriate footstep event - if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) - { - if ( pm->watertype & CONTENTS_LADDER ) - { - if ( !pm->noFootsteps ) - { - if (pm->ps->groundEntityNum == ENTITYNUM_NONE) {// on ladder - PM_AddEvent( EV_FOOTSTEP_METAL ); + if (((old + 64) ^ (pm->ps->bobCycle + 64)) & 128) { + if (pm->watertype & CONTENTS_LADDER) { + if (!pm->noFootsteps) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // on ladder + PM_AddEvent(EV_FOOTSTEP_METAL); } else { - PM_AddEvent( PM_FootstepForSurface() ); //still on ground + PM_AddEvent(PM_FootstepForSurface()); // still on ground } - if ( pm->gent && pm->gent->s.number == 0 ) - { -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue ); - } + if (pm->gent && pm->gent->s.number == 0) { + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, pm->ps->origin, 128, AEL_MINOR, qtrue); } } } - } - else if ( pm->waterlevel == 0 ) - { + } else if (pm->waterlevel == 0) { // on ground will only play sounds if running - if ( footstep && !pm->noFootsteps ) - { - PM_AddEvent( PM_FootstepForSurface() ); - if ( pm->gent && pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (footstep && !pm->noFootsteps) { + PM_AddEvent(PM_FootstepForSurface()); + if (pm->gent && pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) - { - AddSoundEvent( pm->gent, bottom, 256, AEL_MINOR, qtrue ); - } + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { AddSoundEvent(pm->gent, bottom, 256, AEL_MINOR, qtrue); } } } - } - else if ( pm->waterlevel == 1 ) - { + } else if (pm->waterlevel == 1) { // splashing - if ( pm->ps->waterHeightLevel >= WHL_KNEES ) - { - PM_AddEvent( EV_FOOTWADE ); - } - else - { - PM_AddEvent( EV_FOOTSPLASH ); + if (pm->ps->waterHeightLevel >= WHL_KNEES) { + PM_AddEvent(EV_FOOTWADE); + } else { + PM_AddEvent(EV_FOOTSPLASH); } - if ( pm->gent && pm->gent->s.number == 0 ) - { - vec3_t bottom; + if (pm->gent && pm->gent->s.number == 0) { + vec3_t bottom; - VectorCopy( pm->ps->origin, bottom ); + VectorCopy(pm->ps->origin, bottom); bottom[2] += pm->mins[2]; -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS );//was bottom - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_MINOR ); + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); // was bottom + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_MINOR); } } - } - else if ( pm->waterlevel == 2 ) - { + } else if (pm->waterlevel == 2) { // wading / swimming at surface /* if ( pm->ps->waterHeightLevel >= WHL_TORSO ) @@ -5376,21 +4464,16 @@ static void PM_Footsteps( void ) } else */ - { - PM_AddEvent( EV_FOOTWADE ); - } - if ( pm->gent && pm->gent->s.number == 0 ) - { -// if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) + { PM_AddEvent(EV_FOOTWADE); } + if (pm->gent && pm->gent->s.number == 0) { + // if ( pm->gent->client && pm->gent->client->playerTeam != TEAM_DISGUISE ) { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } - } - else - {// or no sound when completely underwater...? - PM_AddEvent( EV_SWIM ); + } else { // or no sound when completely underwater...? + PM_AddEvent(EV_SWIM); } } } @@ -5402,11 +4485,11 @@ PM_WaterEvents Generate sound events for entering and leaving water ============== */ -static void PM_WaterEvents( void ) { // FIXME? +static void PM_WaterEvents(void) { // FIXME? qboolean impact_splash = qfalse; - if ( pm->watertype & CONTENTS_LADDER ) //fake water for ladder + if (pm->watertype & CONTENTS_LADDER) // fake water for ladder { return; } @@ -5414,15 +4497,13 @@ static void PM_WaterEvents( void ) { // FIXME? // if just entered a water volume, play a sound // if (!pml.previous_waterlevel && pm->waterlevel) { - PM_AddEvent( EV_WATER_TOUCH ); - if ( pm->gent && VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + PM_AddEvent(EV_WATER_TOUCH); + if (pm->gent && VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } - if ( pm->gent && !pm->ps->clientNum ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + if (pm->gent && !pm->ps->clientNum) { + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } @@ -5430,39 +4511,35 @@ static void PM_WaterEvents( void ) { // FIXME? // if just completely exited a water volume, play a sound // if (pml.previous_waterlevel && !pm->waterlevel) { - PM_AddEvent( EV_WATER_LEAVE ); - if ( pm->gent && VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + PM_AddEvent(EV_WATER_LEAVE); + if (pm->gent && VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } - if ( pm->gent && !pm->ps->clientNum ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); - AddSightEvent( pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS ); + if (pm->gent && !pm->ps->clientNum) { + AddSoundEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); + AddSightEvent(pm->gent, pm->ps->origin, 512, AEL_SUSPICIOUS); } } - if ( impact_splash ) - { - //play the splash effect - trace_t tr; - vec3_t axis[3], angs, start, end; + if (impact_splash) { + // play the splash effect + trace_t tr; + vec3_t axis[3], angs, start, end; - VectorSet( angs, 0, pm->gent->currentAngles[YAW], 0 ); - AngleVectors( angs, axis[2], axis[1], axis[0] ); + VectorSet(angs, 0, pm->gent->currentAngles[YAW], 0); + AngleVectors(angs, axis[2], axis[1], axis[0]); - VectorCopy( pm->ps->origin, start ); - VectorCopy( pm->ps->origin, end ); + VectorCopy(pm->ps->origin, start); + VectorCopy(pm->ps->origin, end); // FIXME: set start and end better start[2] += 10; end[2] -= 40; - gi.trace( &tr, start, vec3_origin, vec3_origin, end, pm->gent->s.number, CONTENTS_WATER, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, start, vec3_origin, vec3_origin, end, pm->gent->s.number, CONTENTS_WATER, G2_NOCOLLIDE, 0); - if ( tr.fraction < 1.0f ) - { - G_PlayEffect( "water_impact", tr.endpos, axis ); + if (tr.fraction < 1.0f) { + G_PlayEffect("water_impact", tr.endpos, axis); } } @@ -5470,11 +4547,10 @@ static void PM_WaterEvents( void ) { // FIXME? // check for head just going under water // if (pml.previous_waterlevel != 3 && pm->waterlevel == 3) { - PM_AddEvent( EV_WATER_UNDER ); - if ( pm->gent && !pm->ps->clientNum ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR ); - AddSightEvent( pm->gent, pm->ps->origin, 384, AEL_MINOR ); + PM_AddEvent(EV_WATER_UNDER); + if (pm->gent && !pm->ps->clientNum) { + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR); + AddSightEvent(pm->gent, pm->ps->origin, 384, AEL_MINOR); } } @@ -5482,139 +4558,110 @@ static void PM_WaterEvents( void ) { // FIXME? // check for head just coming out of water // if (pml.previous_waterlevel == 3 && pm->waterlevel != 3) { - if ( !pm->gent || !pm->gent->client || pm->gent->client->airOutTime < level.time + 2000 ) - {//only do this if we were drowning or about to start drowning - PM_AddEvent( EV_WATER_CLEAR ); - } - else - { - PM_AddEvent( EV_WATER_LEAVE ); + if (!pm->gent || !pm->gent->client || pm->gent->client->airOutTime < level.time + 2000) { // only do this if we were drowning or about to start drowning + PM_AddEvent(EV_WATER_CLEAR); + } else { + PM_AddEvent(EV_WATER_LEAVE); } - if ( pm->gent && !pm->ps->clientNum ) - { - AddSoundEvent( pm->gent, pm->ps->origin, 256, AEL_MINOR ); - AddSightEvent( pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS ); + if (pm->gent && !pm->ps->clientNum) { + AddSoundEvent(pm->gent, pm->ps->origin, 256, AEL_MINOR); + AddSightEvent(pm->gent, pm->ps->origin, 384, AEL_SUSPICIOUS); } } } - /* =============== PM_BeginWeaponChange =============== */ -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -static void PM_BeginWeaponChange( int weapon ) { +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +static void PM_BeginWeaponChange(int weapon) { - if ( pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500 ) - {//just entered map - if ( weapon == WP_NONE && pm->ps->weapon != weapon ) - {//don't switch to weapon none if just entered map + if (pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500) { // just entered map + if (weapon == WP_NONE && pm->ps->weapon != weapon) { // don't switch to weapon none if just entered map return; } } - if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) { + if (weapon < WP_NONE || weapon >= WP_NUM_WEAPONS) { return; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { return; } - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { return; } - if ( cg.time > 0 ) - {//this way we don't get that annoying change weapon sound every time a map starts - PM_AddEvent( EV_CHANGE_WEAPON ); + if (cg.time > 0) { // this way we don't get that annoying change weapon sound every time a map starts + PM_AddEvent(EV_CHANGE_WEAPON); } pm->ps->weaponstate = WEAPON_DROPPING; pm->ps->weaponTime += 200; - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - { - if ( pm->gent->alt_fire ) - {//FIXME: attack delay? - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { + if (pm->gent->alt_fire) { // FIXME: attack delay? + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // FIXME: attack delay? + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - {//FIXME: attack delay? - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP1,SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP1, SETANIM_FLAG_HOLD); } - // turn of any kind of zooming when weapon switching....except the LA Goggles - if ( pm->ps->clientNum == 0 ) - { - if ( cg.zoomMode > 0 && cg.zoomMode < 3 ) - { + if (pm->ps->clientNum == 0) { + if (cg.zoomMode > 0 && cg.zoomMode < 3) { cg.zoomMode = 0; cg.zoomTime = cg.time; } } - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - { - if ( !pm->ps->clientNum ) - { - gi.cvar_set( "cg_thirdperson", "1" ); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { + if (!pm->ps->clientNum) { + gi.cvar_set("cg_thirdperson", "1"); } - } - else if ( weapon == WP_SABER ) - {//going to switch to lightsaber - } - else - { - if ( pm->ps->weapon == WP_SABER ) - {//going to switch away from saber - if ( pm->gent ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav" ); + } else if (weapon == WP_SABER) { // going to switch to lightsaber + } else { + if (pm->ps->weapon == WP_SABER) { // going to switch away from saber + if (pm->gent) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav"); } PM_SetSaberMove(LS_PUTAWAY); } - //put this back in because saberActive isn't being set somewhere else anymore + // put this back in because saberActive isn't being set somewhere else anymore pm->ps->saberActive = qfalse; pm->ps->saberLength = 0; } } - /* =============== PM_FinishWeaponChange =============== */ -static void PM_FinishWeaponChange( void ) { - int weapon; - qboolean trueSwitch = qtrue; - - if ( pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500 ) - {//just entered map - if ( pm->cmd.weapon == WP_NONE && pm->ps->weapon != pm->cmd.weapon ) - {//don't switch to weapon none if just entered map +static void PM_FinishWeaponChange(void) { + int weapon; + qboolean trueSwitch = qtrue; + + if (pm->gent && pm->gent->client && pm->gent->client->pers.enterTime >= level.time - 500) { // just entered map + if (pm->cmd.weapon == WP_NONE && pm->ps->weapon != pm->cmd.weapon) { // don't switch to weapon none if just entered map return; } } weapon = pm->cmd.weapon; - if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) { + if (weapon < WP_NONE || weapon >= WP_NUM_WEAPONS) { weapon = WP_NONE; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { weapon = WP_NONE; } - if ( pm->ps->weapon == weapon ) - { + if (pm->ps->weapon == weapon) { trueSwitch = qfalse; } int oldWeap = pm->ps->weapon; @@ -5622,90 +4669,66 @@ static void PM_FinishWeaponChange( void ) { pm->ps->weaponstate = WEAPON_RAISING; pm->ps->weaponTime += 250; - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST ) - {//do nothing - } - else if ( weapon == WP_SABER ) - {//turn on the lightsaber - //FIXME: somehow sometimes I still end up with 2 weapons in hand... usually if I + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { // do nothing + } else if (weapon == WP_SABER) { // turn on the lightsaber + // FIXME: somehow sometimes I still end up with 2 weapons in hand... usually if I // cycle weapons fast enough that I end up in 1st person lightsaber, then // somehow throw the saber and switch to another weapon (all in 1st person), // making my saber drop to the ground... when I switch back to the saber, it // does not remove the current weapon model and then, when I pull the saber // back to my hand, I have 2 weaponModels active...? - if ( pm->gent ) - {// remove gun if we had it. - if ( pm->gent->weaponModel >= 0 ) - { + if (pm->gent) { // remove gun if we had it. + if (pm->gent->weaponModel >= 0) { gi.G2API_RemoveGhoul2Model(pm->gent->ghoul2, pm->gent->weaponModel); } } - if ( !pm->ps->saberInFlight ) - {//if it's not in flight or lying around, turn it on! - //FIXME: AddSound/Sight Event - //FIXME: don't do this if just loaded a game - if ( trueSwitch ) - {//actually did switch weapons, turn it on + if (!pm->ps->saberInFlight) { // if it's not in flight or lying around, turn it on! + // FIXME: AddSound/Sight Event + // FIXME: don't do this if just loaded a game + if (trueSwitch) { // actually did switch weapons, turn it on pm->ps->saberActive = qtrue; pm->ps->saberLength = 0; } - if ( pm->gent ) - { - G_CreateG2AttachedWeaponModel( pm->gent, pm->ps->saberModel ); + if (pm->gent) { + G_CreateG2AttachedWeaponModel(pm->gent, pm->ps->saberModel); } - } - else - {//FIXME: pull it back to us? + } else { // FIXME: pull it back to us? } - if ( pm->gent ) - { - WP_SaberInitBladeData( pm->gent ); - if ( !pm->ps->clientNum && cg_saberAutoThird.value ) - { - gi.cvar_set( "cg_thirdperson", "1" ); + if (pm->gent) { + WP_SaberInitBladeData(pm->gent); + if (!pm->ps->clientNum && cg_saberAutoThird.value) { + gi.cvar_set("cg_thirdperson", "1"); } } - if ( trueSwitch ) - {//actually did switch weapons, play anim + if (trueSwitch) { // actually did switch weapons, play anim PM_SetSaberMove(LS_DRAW); } - } - else - {//switched away from saber - if ( pm->gent ) - { + } else { // switched away from saber + if (pm->gent) { // remove the sabre if we had it. - if ( pm->gent->weaponModel >= 0 ) - { + if (pm->gent->weaponModel >= 0) { gi.G2API_RemoveGhoul2Model(pm->gent->ghoul2, pm->gent->weaponModel); pm->gent->weaponModel = -1; } - if (weaponData[weapon].weaponMdl[0]) { //might be NONE, so check if it has a model - G_CreateG2AttachedWeaponModel( pm->gent, weaponData[weapon].weaponMdl ); + if (weaponData[weapon].weaponMdl[0]) { // might be NONE, so check if it has a model + G_CreateG2AttachedWeaponModel(pm->gent, weaponData[weapon].weaponMdl); } } - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - { - if ( pm->gent->alt_fire ) - {//FIXME: attack delay? - PM_SetAnim(pm,SETANIM_TORSO,TORSO_RAISEWEAP3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { + if (pm->gent->alt_fire) { // FIXME: attack delay? + PM_SetAnim(pm, SETANIM_TORSO, TORSO_RAISEWEAP3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // FIXME: attack delay? + PM_SetAnim(pm, SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - {//FIXME: attack delay? - PM_SetAnim(pm,SETANIM_TORSO,TORSO_RAISEWEAP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,TORSO_RAISEWEAP1,SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_HOLD); } - if ( !pm->ps->clientNum && cg_gunAutoFirst.value && oldWeap == WP_SABER && weapon != WP_NONE ) - { - gi.cvar_set( "cg_thirdperson", "0" ); + if (!pm->ps->clientNum && cg_gunAutoFirst.value && oldWeap == WP_SABER && weapon != WP_NONE) { + gi.cvar_set("cg_thirdperson", "0"); } pm->ps->saberMove = LS_NONE; pm->ps->saberBlocking = BLK_NO; @@ -5713,32 +4736,23 @@ static void PM_FinishWeaponChange( void ) { } } -void PM_SetSaberMove(short newMove) -{ +void PM_SetSaberMove(short newMove) { unsigned int setflags = saberMoveData[newMove].animSetFlags; - int anim = saberMoveData[newMove].animToUse; + int anim = saberMoveData[newMove].animToUse; int parts = SETANIM_TORSO; - if ( cg_debugSaber.integer&0x01 && (newMove != LS_READY) ) - { - Com_Printf("SetSaberMove: From '%s' to '%s'\n", - saberMoveData[pm->ps->saberMove].name, - saberMoveData[newMove].name); + if (cg_debugSaber.integer & 0x01 && (newMove != LS_READY)) { + Com_Printf("SetSaberMove: From '%s' to '%s'\n", saberMoveData[pm->ps->saberMove].name, saberMoveData[newMove].name); } - if ( newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH ) - {//finished with a kata (or in a special move) reset attack counter + if (newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH) { // finished with a kata (or in a special move) reset attack counter pm->ps->saberAttackChainCount = 0; - } - else if ( PM_SaberInAttack( newMove ) ) - {//continuing with a kata, increment attack counter + } else if (PM_SaberInAttack(newMove)) { // continuing with a kata, increment attack counter pm->ps->saberAttackChainCount++; } - if ( newMove == LS_READY ) - { - switch ( pm->ps->saberAnimLevel ) - { + if (newMove == LS_READY) { + switch (pm->ps->saberAnimLevel) { case FORCE_LEVEL_1: case FORCE_LEVEL_5: anim = BOTH_SABERFAST_STANCE; @@ -5753,144 +4767,99 @@ void PM_SetSaberMove(short newMove) anim = BOTH_STAND2; break; } - } - else if ( pm->ps->saberAnimLevel > FORCE_LEVEL_1 && - !PM_SaberInIdle( newMove ) && !PM_SaberInParry( newMove ) && !PM_SaberInKnockaway( newMove ) && !PM_SaberInBrokenParry( newMove ) && !PM_SaberInReflect( newMove ) && !PM_SaberInSpecial( newMove )) - {//readies, parries and reflections have only 1 level - //increment the anim to the next level of saber anims - anim += (pm->ps->saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + } else if (pm->ps->saberAnimLevel > FORCE_LEVEL_1 && !PM_SaberInIdle(newMove) && !PM_SaberInParry(newMove) && !PM_SaberInKnockaway(newMove) && + !PM_SaberInBrokenParry(newMove) && !PM_SaberInReflect(newMove) && + !PM_SaberInSpecial(newMove)) { // readies, parries and reflections have only 1 level + // increment the anim to the next level of saber anims + anim += (pm->ps->saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; } // If the move does the same animation as the last one, we need to force a restart... - if ( saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) - { + if (saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) { setflags |= SETANIM_FLAG_RESTART; } - if ( anim == BOTH_STAND2 - || anim == BOTH_SABERFAST_STANCE - || anim == BOTH_SABERSLOW_STANCE ) - { - //FIXME: play both_stand2_random1 when you've been idle for a while - if( pm->ps->legsAnim == BOTH_WALK1 ) - { + if (anim == BOTH_STAND2 || anim == BOTH_SABERFAST_STANCE || anim == BOTH_SABERSLOW_STANCE) { + // FIXME: play both_stand2_random1 when you've been idle for a while + if (pm->ps->legsAnim == BOTH_WALK1) { anim = BOTH_WALK1; - } - else if( pm->ps->legsAnim == BOTH_RUN2 ) - { + } else if (pm->ps->legsAnim == BOTH_RUN2) { anim = BOTH_RUN2; - } - else if( pm->ps->legsAnim == BOTH_WALK2 ) - { + } else if (pm->ps->legsAnim == BOTH_WALK2) { anim = BOTH_WALK2; } } - if ( newMove == LS_A_LUNGE - || newMove == LS_A_JUMP_T__B_ - || newMove == LS_A_BACKSTAB - || newMove == LS_A_BACK - || newMove == LS_A_BACK_CR - || newMove == LS_A_FLIP_STAB - || newMove == LS_A_FLIP_SLASH ) - { + if (newMove == LS_A_LUNGE || newMove == LS_A_JUMP_T__B_ || newMove == LS_A_BACKSTAB || newMove == LS_A_BACK || newMove == LS_A_BACK_CR || + newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH) { parts = SETANIM_BOTH; - } - else if ( PM_SpinningSaberAnim( anim ) ) - {//spins must be played on entire body + } else if (PM_SpinningSaberAnim(anim)) { // spins must be played on entire body parts = SETANIM_BOTH; - } - else if ( (!pm->cmd.forwardmove&&!pm->cmd.rightmove&&!pm->cmd.upmove)) - {//not trying to run, duck or jump - if ( !PM_FlippingAnim( pm->ps->legsAnim ) && - !PM_InRoll( pm->ps ) && - !PM_InKnockDown( pm->ps ) && - !PM_JumpingAnim( pm->ps->legsAnim ) && - !PM_PainAnim( pm->ps->legsAnim ) && - !PM_InSpecialJump( pm->ps->legsAnim ) && - !PM_InSlopeAnim( pm->ps->legsAnim ) && - //!PM_CrouchAnim( pm->ps->legsAnim ) && - //pm->cmd.upmove >= 0 && - !(pm->ps->pm_flags & PMF_DUCKED)) - { + } else if ((!pm->cmd.forwardmove && !pm->cmd.rightmove && !pm->cmd.upmove)) { // not trying to run, duck or jump + if (!PM_FlippingAnim(pm->ps->legsAnim) && !PM_InRoll(pm->ps) && !PM_InKnockDown(pm->ps) && !PM_JumpingAnim(pm->ps->legsAnim) && + !PM_PainAnim(pm->ps->legsAnim) && !PM_InSpecialJump(pm->ps->legsAnim) && !PM_InSlopeAnim(pm->ps->legsAnim) && + //! PM_CrouchAnim( pm->ps->legsAnim ) && + // pm->cmd.upmove >= 0 && + !(pm->ps->pm_flags & PMF_DUCKED)) { parts = SETANIM_BOTH; } } - PM_SetAnim( pm, parts, anim, setflags, saberMoveData[newMove].blendTime ); + PM_SetAnim(pm, parts, anim, setflags, saberMoveData[newMove].blendTime); - if ( pm->ps->torsoAnim == anim ) - {//successfully changed anims - //special check for *starting* a saber swing - if ( pm->gent && pm->ps->saberLength > 1 ) - { - if ( PM_SaberInAttack( newMove ) || PM_SaberInSpecialAttack( anim ) ) - {//playing an attack - if ( pm->ps->saberMove != newMove ) - {//wasn't playing that attack before - if ( PM_SaberInSpecialAttack( anim ) ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", Q_irand( 1, 3 ) ) ); - } - else - { - switch ( pm->ps->saberAnimLevel ) - { + if (pm->ps->torsoAnim == anim) { // successfully changed anims + // special check for *starting* a saber swing + if (pm->gent && pm->ps->saberLength > 1) { + if (PM_SaberInAttack(newMove) || PM_SaberInSpecialAttack(anim)) { // playing an attack + if (pm->ps->saberMove != newMove) { // wasn't playing that attack before + if (PM_SaberInSpecialAttack(anim)) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", Q_irand(1, 3))); + } else { + switch (pm->ps->saberAnimLevel) { case FORCE_LEVEL_4: case FORCE_LEVEL_3: - G_SoundOnEnt( pm->gent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", Q_irand( 7, 9 ) ) ); + G_SoundOnEnt(pm->gent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", Q_irand(7, 9))); break; case FORCE_LEVEL_2: - G_SoundOnEnt( pm->gent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", Q_irand( 4, 6 ) ) ); + G_SoundOnEnt(pm->gent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", Q_irand(4, 6))); break; case FORCE_LEVEL_5: case FORCE_LEVEL_1: - G_SoundOnEnt( pm->gent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", Q_irand( 1, 3 ) ) ); + G_SoundOnEnt(pm->gent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", Q_irand(1, 3))); break; } } } - } - else if ( PM_SaberInStart( newMove ) && pm->ps->saberAnimLevel == FORCE_LEVEL_3 ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, va( "sound/weapons/saber/saberhup%d.wav", Q_irand( 1, 3 ) ) ); + } else if (PM_SaberInStart(newMove) && pm->ps->saberAnimLevel == FORCE_LEVEL_3) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, va("sound/weapons/saber/saberhup%d.wav", Q_irand(1, 3))); } } pm->ps->saberMove = newMove; pm->ps->saberBlocking = saberMoveData[newMove].blocking; - if ( pm->ps->clientNum == 0 || PM_ControlledByPlayer() ) - { - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ - && newMove >= LS_REFLECT_UP && newMove <= LS_REFLECT_LL ) - {//don't clear it when blocking projectiles - } - else - { + if (pm->ps->clientNum == 0 || PM_ControlledByPlayer()) { + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ && newMove >= LS_REFLECT_UP && + newMove <= LS_REFLECT_LL) { // don't clear it when blocking projectiles + } else { pm->ps->saberBlocked = BLOCKED_NONE; } - } - else if ( pm->ps->saberBlocked <= BLOCKED_ATK_BOUNCE || !pm->ps->saberActive || (newMove < LS_PARRY_UR || newMove > LS_REFLECT_LL) ) - {//NPCs only clear blocked if not blocking? + } else if (pm->ps->saberBlocked <= BLOCKED_ATK_BOUNCE || !pm->ps->saberActive || + (newMove < LS_PARRY_UR || newMove > LS_REFLECT_LL)) { // NPCs only clear blocked if not blocking? pm->ps->saberBlocked = BLOCKED_NONE; } - if ( pm->gent && pm->gent->client ) - { - if ( saberMoveData[newMove].trailLength > 0 ) - { + if (pm->gent && pm->gent->client) { + if (saberMoveData[newMove].trailLength > 0) { pm->gent->client->saberTrail.inAction = qtrue; - pm->gent->client->saberTrail.duration = saberMoveData[newMove].trailLength; // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter - } - else - { + pm->gent->client->saberTrail.duration = + saberMoveData[newMove].trailLength; // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter + } else { pm->gent->client->saberTrail.inAction = qfalse; } } } } - /* ============== PM_Use @@ -5900,23 +4869,19 @@ Generates a use event */ #define USE_DELAY 250 -void PM_Use( void ) -{ - if ( pm->ps->useTime > 0 ) - { +void PM_Use(void) { + if (pm->ps->useTime > 0) { pm->ps->useTime -= pml.msec; - if ( pm->ps->useTime < 0 ) - { + if (pm->ps->useTime < 0) { pm->ps->useTime = 0; } } - if ( pm->ps->useTime > 0 ) { + if (pm->ps->useTime > 0) { return; } - if ( ! (pm->cmd.buttons & BUTTON_USE ) ) - { + if (!(pm->cmd.buttons & BUTTON_USE)) { pm->useEvent = 0; pm->ps->useTime = 0; return; @@ -5926,125 +4891,85 @@ void PM_Use( void ) pm->ps->useTime = USE_DELAY; } -extern int PM_AttackForEnemyPos( qboolean allowFB ); -int PM_NPCSaberAttackFromQuad( int quad ) -{ - //FIXME: this should be an AI decision - // It should be based on the enemy's current LS_ move, saberAnimLevel, - // the jedi's difficulty level, rank and FP_OFFENSE skill... +extern int PM_AttackForEnemyPos(qboolean allowFB); +int PM_NPCSaberAttackFromQuad(int quad) { + // FIXME: this should be an AI decision + // It should be based on the enemy's current LS_ move, saberAnimLevel, + // the jedi's difficulty level, rank and FP_OFFENSE skill... int autoMove = LS_NONE; - if ( pm->gent && ((pm->gent->NPC && pm->gent->NPC->rank != RANK_ENSIGN && pm->gent->NPC->rank != RANK_CIVILIAN ) || (pm->gent->client && pm->gent->client->NPC_class == CLASS_TAVION)) ) - { - autoMove = PM_AttackForEnemyPos( qtrue ); + if (pm->gent && ((pm->gent->NPC && pm->gent->NPC->rank != RANK_ENSIGN && pm->gent->NPC->rank != RANK_CIVILIAN) || + (pm->gent->client && pm->gent->client->NPC_class == CLASS_TAVION))) { + autoMove = PM_AttackForEnemyPos(qtrue); } - if ( autoMove != LS_NONE && PM_SaberInSpecial( autoMove ) ) - {//if have opportunity to do a special attack, do one + if (autoMove != LS_NONE && PM_SaberInSpecial(autoMove)) { // if have opportunity to do a special attack, do one return autoMove; - } - else - {//pick another one + } else { // pick another one int newmove = LS_NONE; - switch( quad ) - { - case Q_T://blocked top - if ( Q_irand( 0, 1 ) ) - { + switch (quad) { + case Q_T: // blocked top + if (Q_irand(0, 1)) { newmove = LS_A_T2B; - } - else - { + } else { newmove = LS_A_TR2BL; } break; case Q_TR: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_R2L; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_A_TR2BL; - } - else - { + } else { newmove = LS_T1_TR_BR; } break; case Q_TL: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_L2R; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_A_TL2BR; - } - else - { + } else { newmove = LS_T1_TL_BL; } break; case Q_BR: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_BR2TL; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1_BR_TR; - } - else - { + } else { newmove = LS_A_R2L; } break; case Q_BL: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_BL2TR; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1_BL_TL; - } - else - { + } else { newmove = LS_A_L2R; } break; case Q_L: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_L2R; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1__L_T_; - } - else - { + } else { newmove = LS_A_R2L; } break; case Q_R: - if ( !Q_irand( 0, 2 ) ) - { + if (!Q_irand(0, 2)) { newmove = LS_A_R2L; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { newmove = LS_T1__R_T_; - } - else - { + } else { newmove = LS_A_L2R; } break; case Q_B: - if ( ( pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG ) ) - {//fencers and above can do bottom-up attack - if ( Q_irand( 0, pm->gent->NPC->rank ) >= RANK_LT_JG ) - {//but not overly likely + if ((pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG)) { // fencers and above can do bottom-up attack + if (Q_irand(0, pm->gent->NPC->rank) >= RANK_LT_JG) { // but not overly likely newmove = LS_A_LUNGE; } } @@ -6056,208 +4981,149 @@ int PM_NPCSaberAttackFromQuad( int quad ) } } -int PM_SaberMoveQuadrantForMovement( usercmd_t *ucmd ) -{ - if ( ucmd->rightmove > 0 ) - {//moving right - if ( ucmd->forwardmove > 0 ) - {//forward right = TL2BR slash +int PM_SaberMoveQuadrantForMovement(usercmd_t *ucmd) { + if (ucmd->rightmove > 0) { // moving right + if (ucmd->forwardmove > 0) { // forward right = TL2BR slash return Q_TL; - } - else if ( ucmd->forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (ucmd->forwardmove < 0) { // backward right = BL2TR uppercut return Q_BL; - } - else - {//just right is a left slice + } else { // just right is a left slice return Q_L; } - } - else if ( ucmd->rightmove < 0 ) - {//moving left - if ( ucmd->forwardmove > 0 ) - {//forward left = TR2BL slash + } else if (ucmd->rightmove < 0) { // moving left + if (ucmd->forwardmove > 0) { // forward left = TR2BL slash return Q_TR; - } - else if ( ucmd->forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (ucmd->forwardmove < 0) { // backward left = BR2TL uppercut return Q_BR; - } - else - {//just left is a right slice + } else { // just left is a right slice return Q_R; } - } - else - {//not moving left or right - if ( ucmd->forwardmove > 0 ) - {//forward= T2B slash + } else { // not moving left or right + if (ucmd->forwardmove > 0) { // forward= T2B slash return Q_T; - } - else if ( ucmd->forwardmove < 0 ) - {//backward= T2B slash //or B2T uppercut? + } else if (ucmd->forwardmove < 0) { // backward= T2B slash //or B2T uppercut? return Q_T; - } - else //if ( curmove == LS_READY )//??? - {//Not moving at all + } else // if ( curmove == LS_READY )//??? + { // Not moving at all return Q_R; } } - //return Q_R;//???? + // return Q_R;//???? } -void PM_SetAnimFrame( gentity_t *gent, int frame, qboolean torso, qboolean legs ) -{ - if ( !gi.G2API_HaveWeGhoul2Models( gent->ghoul2 ) ) - { +void PM_SetAnimFrame(gentity_t *gent, int frame, qboolean torso, qboolean legs) { + if (!gi.G2API_HaveWeGhoul2Models(gent->ghoul2)) { return; } - int actualTime = (cg.time?cg.time:level.time); - if ( torso && gent->lowerLumbarBone != -1 )//gent->upperLumbarBone + int actualTime = (cg.time ? cg.time : level.time); + if (torso && gent->lowerLumbarBone != -1) // gent->upperLumbarBone { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, //gent->upperLumbarBone - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); - if ( gent->motionBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, //gent->upperLumbarBone - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, // gent->upperLumbarBone + frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, actualTime, frame, 150); + if (gent->motionBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->motionBone, // gent->upperLumbarBone + frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, actualTime, frame, 150); } } - if ( legs && gent->rootBone != -1 ) - { - gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, - frame, frame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, 1, actualTime, frame, 150 ); + if (legs && gent->rootBone != -1) { + gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->rootBone, frame, frame + 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1, + actualTime, frame, 150); } } -int PM_SaberLockWinAnim( saberLockResult_t result ) -{ +int PM_SaberLockWinAnim(saberLockResult_t result) { int winAnim = -1; - switch ( pm->ps->torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, animTable[pm->ps->torsoAnim].name ); -#endif -*/ + switch (pm->ps->torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, + animTable[pm->ps->torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { winAnim = BOTH_BF1BREAK; - } - else - { + } else { pm->ps->saberMove = LS_A_T2B; winAnim = BOTH_A3_T__B_; } break; case BOTH_BF1LOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { winAnim = BOTH_KNOCKDOWN4; - } - else - { + } else { pm->ps->saberMove = LS_K1_T_; winAnim = BOTH_K1_S1_T_; } break; case BOTH_CWCIRCLELOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { pm->ps->saberMove = pm->ps->saberBounceMove = LS_V1_BL; pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BL_S1; - } - else - { + } else { winAnim = BOTH_CWCIRCLEBREAK; } break; case BOTH_CCWCIRCLELOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { pm->ps->saberMove = pm->ps->saberBounceMove = LS_V1_BR; pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BR_S1; - } - else - { + } else { winAnim = BOTH_CCWCIRCLEBREAK; } break; } - if ( winAnim != -1 ) - { - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (winAnim != -1) { + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer; } return winAnim; } -int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result ) -{ +int PM_SaberLockLoseAnim(gentity_t *genemy, saberLockResult_t result) { int loseAnim = -1; - switch ( genemy->client->ps.torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, animTable[genemy->client->ps.torsoAnim].name ); -#endif -*/ + switch (genemy->client->ps.torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, + animTable[genemy->client->ps.torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { loseAnim = BOTH_BF1BREAK; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won genemy->client->ps.saberMove = LS_K1_T_; loseAnim = BOTH_K1_S1_T_; - } - else - {//FIXME: this anim needs to transition back to ready when done + } else { // FIXME: this anim needs to transition back to ready when done loseAnim = BOTH_BF1BREAK; } } break; case BOTH_BF1LOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { loseAnim = BOTH_KNOCKDOWN4; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won genemy->client->ps.saberMove = LS_A_T2B; loseAnim = BOTH_A3_T__B_; - } - else - { + } else { loseAnim = BOTH_KNOCKDOWN4; } } break; case BOTH_CWCIRCLELOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BL; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won loseAnim = BOTH_CCWCIRCLEBREAK; - } - else - { + } else { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BL; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; @@ -6270,20 +5136,14 @@ int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result ) } break; case BOTH_CCWCIRCLELOCK: - if ( result == LOCK_DRAW ) - { + if (result == LOCK_DRAW) { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BR; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; - } - else - { - if ( result == LOCK_STALEMATE ) - {//no-one won + } else { + if (result == LOCK_STALEMATE) { // no-one won loseAnim = BOTH_CWCIRCLEBREAK; - } - else - { + } else { genemy->client->ps.saberMove = genemy->client->ps.saberBounceMove = LS_V1_BR; genemy->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; @@ -6296,104 +5156,87 @@ int PM_SaberLockLoseAnim( gentity_t *genemy, saberLockResult_t result ) } break; } - if ( loseAnim != -1 ) - { - NPC_SetAnim( genemy, SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - genemy->client->ps.weaponTime = genemy->client->ps.torsoAnimTimer;// + 250; + if (loseAnim != -1) { + NPC_SetAnim(genemy, SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + genemy->client->ps.weaponTime = genemy->client->ps.torsoAnimTimer; // + 250; } return loseAnim; } -void PM_SaberLockBreak( gentity_t *gent, gentity_t *genemy, saberLockResult_t result, int victoryStrength ) -{ - int winAnim = -1, loseAnim = -1; +void PM_SaberLockBreak(gentity_t *gent, gentity_t *genemy, saberLockResult_t result, int victoryStrength) { + int winAnim = -1, loseAnim = -1; - winAnim = PM_SaberLockWinAnim( result ); - if ( genemy && genemy->client ) - { - loseAnim = PM_SaberLockLoseAnim( genemy, result ); + winAnim = PM_SaberLockWinAnim(result); + if (genemy && genemy->client) { + loseAnim = PM_SaberLockLoseAnim(genemy, result); } - if ( d_saberCombat->integer ) - { - Com_Printf( "%s won saber lock, anim = %s!\n", gent->NPC_type, animTable[winAnim].name ); - Com_Printf( "%s lost saber lock, anim = %s!\n", genemy->NPC_type, animTable[loseAnim].name ); + if (d_saberCombat->integer) { + Com_Printf("%s won saber lock, anim = %s!\n", gent->NPC_type, animTable[winAnim].name); + Com_Printf("%s lost saber lock, anim = %s!\n", genemy->NPC_type, animTable[loseAnim].name); } pm->ps->saberLockTime = genemy->client->ps.saberLockTime = 0; pm->ps->saberLockEnemy = genemy->client->ps.saberLockEnemy = ENTITYNUM_NONE; - PM_AddEvent( EV_JUMP ); - if ( result == LOCK_STALEMATE ) - {//no-one won - G_AddEvent( genemy, EV_JUMP, 0 ); - } - else - { - if ( pm->ps->clientNum ) - {//an NPC - pm->ps->saberEventFlags |= SEF_LOCK_WON;//tell the winner to press the advantage + PM_AddEvent(EV_JUMP); + if (result == LOCK_STALEMATE) { // no-one won + G_AddEvent(genemy, EV_JUMP, 0); + } else { + if (pm->ps->clientNum) { // an NPC + pm->ps->saberEventFlags |= SEF_LOCK_WON; // tell the winner to press the advantage } - //painDebounceTime will stop them from doing anything + // painDebounceTime will stop them from doing anything genemy->painDebounceTime = level.time + genemy->client->ps.torsoAnimTimer + 500; - if ( Q_irand( 0, 1 ) ) - { - G_AddEvent( genemy, EV_PAIN, Q_irand( 0, 75 ) ); - } - else - { - if ( genemy->NPC ) - { + if (Q_irand(0, 1)) { + G_AddEvent(genemy, EV_PAIN, Q_irand(0, 75)); + } else { + if (genemy->NPC) { genemy->NPC->blockedSpeechDebounceTime = 0; } - G_AddVoiceEvent( genemy, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 500 ); - } - if ( result == LOCK_VICTORY && winAnim != BOTH_CCWCIRCLEBREAK ) - {//one person won - if ( Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_2 ) < pm->ps->forcePowerLevel[FP_SABER_OFFENSE] ) - { - if ( (!genemy->s.number&&genemy->health<=25)//player low on health - ||(genemy->s.number&&genemy->client->NPC_class!=CLASS_LUKE&&genemy->client->NPC_class!=CLASS_TAVION&&genemy->client->NPC_class!=CLASS_DESANN)//any NPC that's not a boss character - ||(genemy->s.number&&genemy->health<=50) )//boss character with less than 50 health left - {//possibly knock saber out of hand OR cut hand off! - vec3_t throwDir = {0,0,350}; - int winMove = pm->ps->saberMove; - switch ( winAnim ) - { + G_AddVoiceEvent(genemy, Q_irand(EV_PUSHED1, EV_PUSHED3), 500); + } + if (result == LOCK_VICTORY && winAnim != BOTH_CCWCIRCLEBREAK) { // one person won + if (Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_2) < pm->ps->forcePowerLevel[FP_SABER_OFFENSE]) { + if ((!genemy->s.number && genemy->health <= 25) // player low on health + || (genemy->s.number && genemy->client->NPC_class != CLASS_LUKE && genemy->client->NPC_class != CLASS_TAVION && + genemy->client->NPC_class != CLASS_DESANN) // any NPC that's not a boss character + || (genemy->s.number && genemy->health <= 50)) // boss character with less than 50 health left + { // possibly knock saber out of hand OR cut hand off! + vec3_t throwDir = {0, 0, 350}; + int winMove = pm->ps->saberMove; + switch (winAnim) { case BOTH_A3_T__B_: winAnim = BOTH_D1_TL___; winMove = LS_D1_TL; - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_K1_S1_T_: - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_CWCIRCLEBREAK: - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; case BOTH_CCWCIRCLEBREAK: winAnim = BOTH_A1_BR_TL; winMove = LS_A_BR2TL; - //FIXME: mod throwDir? + // FIXME: mod throwDir? break; } - if ( Q_irand( 0, 25 ) < victoryStrength - && ((!genemy->s.number&&genemy->health<=10)||genemy->s.number) ) - { - NPC_SetAnim( genemy, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD );//force this + if (Q_irand(0, 25) < victoryStrength && ((!genemy->s.number && genemy->health <= 10) || genemy->s.number)) { + NPC_SetAnim(genemy, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // force this genemy->client->dismembered = qfalse; - G_DoDismemberment( genemy, genemy->client->renderInfo.handRPoint, MOD_SABER, 1000, HL_HAND_RT, qtrue ); - G_Damage( genemy, gent, gent, throwDir, genemy->client->renderInfo.handRPoint, genemy->health+10, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_SABER, HL_NONE ); + G_DoDismemberment(genemy, genemy->client->renderInfo.handRPoint, MOD_SABER, 1000, HL_HAND_RT, qtrue); + G_Damage(genemy, gent, gent, throwDir, genemy->client->renderInfo.handRPoint, genemy->health + 10, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_SABER, HL_NONE); - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer + 500; pm->ps->saberMove = winMove; - } - else if ( Q_irand( 0, 10 ) < victoryStrength ) - { - WP_SaberLose( genemy, throwDir ); + } else if (Q_irand(0, 10) < victoryStrength) { + WP_SaberLose(genemy, throwDir); - PM_SetAnim( pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(pm, SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoAnimTimer; pm->ps->saberMove = winMove; } @@ -6403,221 +5246,162 @@ void PM_SaberLockBreak( gentity_t *gent, gentity_t *genemy, saberLockResult_t re } } -int G_SaberLockStrength( gentity_t *gent ) -{ - if ( gent->s.number ) - { - if ( gent->client->NPC_class == CLASS_DESANN || gent->client->NPC_class == CLASS_LUKE ) - { - return 5+Q_irand(0,g_spskill->integer); - } - else - { - return gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE]+Q_irand(0,g_spskill->integer); +int G_SaberLockStrength(gentity_t *gent) { + if (gent->s.number) { + if (gent->client->NPC_class == CLASS_DESANN || gent->client->NPC_class == CLASS_LUKE) { + return 5 + Q_irand(0, g_spskill->integer); + } else { + return gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] + Q_irand(0, g_spskill->integer); } - } - else - {//player - return gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE]+Q_irand(0,g_spskill->integer); + } else { // player + return gent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] + Q_irand(0, g_spskill->integer); } } -extern qboolean ValidAnimFileIndex ( int index ); -qboolean PM_SaberLocked( void ) -{ - if ( pm->ps->saberLockEnemy == ENTITYNUM_NONE ) - { - if ( pm->ps->torsoAnim == BOTH_BF2LOCK || - pm->ps->torsoAnim == BOTH_BF1LOCK || - pm->ps->torsoAnim == BOTH_CWCIRCLELOCK || - pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK ) - {//wtf? Maybe enemy died? - PM_SaberLockWinAnim( LOCK_STALEMATE ); +extern qboolean ValidAnimFileIndex(int index); +qboolean PM_SaberLocked(void) { + if (pm->ps->saberLockEnemy == ENTITYNUM_NONE) { + if (pm->ps->torsoAnim == BOTH_BF2LOCK || pm->ps->torsoAnim == BOTH_BF1LOCK || pm->ps->torsoAnim == BOTH_CWCIRCLELOCK || + pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK) { // wtf? Maybe enemy died? + PM_SaberLockWinAnim(LOCK_STALEMATE); } return qfalse; } gentity_t *gent = pm->gent; - if ( !gent ) - { + if (!gent) { return qfalse; } gentity_t *genemy = &g_entities[pm->ps->saberLockEnemy]; - if ( !genemy ) - { + if (!genemy) { return qfalse; } - if ( ( pm->ps->torsoAnim == BOTH_BF2LOCK || - pm->ps->torsoAnim == BOTH_BF1LOCK || - pm->ps->torsoAnim == BOTH_CWCIRCLELOCK || - pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK ) - && ( genemy->client->ps.torsoAnim == BOTH_BF2LOCK || - genemy->client->ps.torsoAnim == BOTH_BF1LOCK || - genemy->client->ps.torsoAnim == BOTH_CWCIRCLELOCK || - genemy->client->ps.torsoAnim == BOTH_CCWCIRCLELOCK ) - ) - { - if ( pm->ps->saberLockTime <= level.time + 500 - && pm->ps->saberLockEnemy != ENTITYNUM_NONE ) - {//lock just ended - int strength = G_SaberLockStrength( gent ); - int eStrength = G_SaberLockStrength( genemy ); - if ( strength > 1 && eStrength > 1 && !Q_irand( 0, fabs((double)strength-eStrength)+1 ) ) - {//both knock each other down! - PM_SaberLockBreak( gent, genemy, LOCK_DRAW, 0 ); - } - else - {//both "win" - PM_SaberLockBreak( gent, genemy, LOCK_STALEMATE, 0 ); + if ((pm->ps->torsoAnim == BOTH_BF2LOCK || pm->ps->torsoAnim == BOTH_BF1LOCK || pm->ps->torsoAnim == BOTH_CWCIRCLELOCK || + pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK) && + (genemy->client->ps.torsoAnim == BOTH_BF2LOCK || genemy->client->ps.torsoAnim == BOTH_BF1LOCK || genemy->client->ps.torsoAnim == BOTH_CWCIRCLELOCK || + genemy->client->ps.torsoAnim == BOTH_CCWCIRCLELOCK)) { + if (pm->ps->saberLockTime <= level.time + 500 && pm->ps->saberLockEnemy != ENTITYNUM_NONE) { // lock just ended + int strength = G_SaberLockStrength(gent); + int eStrength = G_SaberLockStrength(genemy); + if (strength > 1 && eStrength > 1 && !Q_irand(0, fabs((double)strength - eStrength) + 1)) { // both knock each other down! + PM_SaberLockBreak(gent, genemy, LOCK_DRAW, 0); + } else { // both "win" + PM_SaberLockBreak(gent, genemy, LOCK_STALEMATE, 0); } return qtrue; - } - else if ( pm->ps->saberLockTime < level.time ) - {//done... tie breaker above should have handled this, but...? - if ( PM_SaberLockAnim( pm->ps->torsoAnim ) && pm->ps->torsoAnimTimer > 0 ) - { + } else if (pm->ps->saberLockTime < level.time) { // done... tie breaker above should have handled this, but...? + if (PM_SaberLockAnim(pm->ps->torsoAnim) && pm->ps->torsoAnimTimer > 0) { pm->ps->torsoAnimTimer = 0; } - if ( PM_SaberLockAnim( pm->ps->legsAnim ) && pm->ps->legsAnimTimer > 0 ) - { + if (PM_SaberLockAnim(pm->ps->legsAnim) && pm->ps->legsAnimTimer > 0) { pm->ps->legsAnimTimer = 0; } return qfalse; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK ) - {//holding attack - if ( !(pm->ps->pm_flags&PMF_ATTACK_HELD) ) - {//tapping - int remaining = 0; - if( ValidAnimFileIndex( gent->client->clientInfo.animFileIndex ) ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK) { // holding attack + if (!(pm->ps->pm_flags & PMF_ATTACK_HELD)) { // tapping + int remaining = 0; + if (ValidAnimFileIndex(gent->client->clientInfo.animFileIndex)) { animation_t *anim; - float currentFrame, junk2; - int curFrame, junk; - int strength = 1; + float currentFrame, junk2; + int curFrame, junk; + int strength = 1; anim = &level.knownAnimFileSets[gent->client->clientInfo.animFileIndex].animations[pm->ps->torsoAnim]; #ifdef _DEBUG qboolean ret = #endif // _DEBUG - gi.G2API_GetBoneAnimIndex( &gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex(&gent->ghoul2[gent->playerModel], gent->lowerLumbarBone, (cg.time ? cg.time : level.time), ¤tFrame, + &junk, &junk, &junk, &junk2, NULL); #ifdef _DEBUG assert(ret); // this would be pretty bad, the below code seems to assume the call succeeds. -gil #endif - strength = G_SaberLockStrength( gent ); - if ( pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK || - pm->ps->torsoAnim == BOTH_BF2LOCK ) - { - curFrame = floor( currentFrame )-strength; - //drop my frame one - if ( curFrame <= anim->firstFrame ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + strength = G_SaberLockStrength(gent); + if (pm->ps->torsoAnim == BOTH_CCWCIRCLELOCK || pm->ps->torsoAnim == BOTH_BF2LOCK) { + curFrame = floor(currentFrame) - strength; + // drop my frame one + if (curFrame <= anim->firstFrame) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = curFrame-anim->firstFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = curFrame - anim->firstFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } - } - else - { - curFrame = ceil( currentFrame )+strength; - //advance my frame one - if ( curFrame >= anim->firstFrame+anim->numFrames ) - {//I won! Break out - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, strength ); + } else { + curFrame = ceil(currentFrame) + strength; + // advance my frame one + if (curFrame >= anim->firstFrame + anim->numFrames) { // I won! Break out + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, strength); return qtrue; - } - else - { - PM_SetAnimFrame( gent, curFrame, qtrue, qtrue ); - remaining = anim->firstFrame+anim->numFrames-curFrame; - if ( d_saberCombat->integer ) - { - Com_Printf( "%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining ); + } else { + PM_SetAnimFrame(gent, curFrame, qtrue, qtrue); + remaining = anim->firstFrame + anim->numFrames - curFrame; + if (d_saberCombat->integer) { + Com_Printf("%s pushing in saber lock, %d frames to go!\n", gent->NPC_type, remaining); } } } - if ( !Q_irand( 0, 2 ) ) - { - if ( !pm->ps->clientNum ) - { - if ( !Q_irand( 0, 3 ) ) - { - PM_AddEvent( EV_JUMP ); - } - else - { - PM_AddEvent( Q_irand( EV_PUSHED1, EV_PUSHED3 ) ); + if (!Q_irand(0, 2)) { + if (!pm->ps->clientNum) { + if (!Q_irand(0, 3)) { + PM_AddEvent(EV_JUMP); + } else { + PM_AddEvent(Q_irand(EV_PUSHED1, EV_PUSHED3)); } - } - else - { - if ( gent->NPC && gent->NPC->blockedSpeechDebounceTime < level.time ) - { - switch ( Q_irand( 0, 3 ) ) - { + } else { + if (gent->NPC && gent->NPC->blockedSpeechDebounceTime < level.time) { + switch (Q_irand(0, 3)) { case 0: - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); break; case 1: - PM_AddEvent( Q_irand( EV_ANGER1, EV_ANGER3 ) ); + PM_AddEvent(Q_irand(EV_ANGER1, EV_ANGER3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; case 2: - PM_AddEvent( Q_irand( EV_TAUNT1, EV_TAUNT3 ) ); + PM_AddEvent(Q_irand(EV_TAUNT1, EV_TAUNT3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; case 3: - PM_AddEvent( Q_irand( EV_GLOAT1, EV_GLOAT3 ) ); + PM_AddEvent(Q_irand(EV_GLOAT1, EV_GLOAT3)); gent->NPC->blockedSpeechDebounceTime = level.time + 3000; break; } } } } - } - else - { + } else { return qfalse; } - if( ValidAnimFileIndex( genemy->client->clientInfo.animFileIndex ) ) - { + if (ValidAnimFileIndex(genemy->client->clientInfo.animFileIndex)) { animation_t *anim; anim = &level.knownAnimFileSets[genemy->client->clientInfo.animFileIndex].animations[genemy->client->ps.torsoAnim]; /* float currentFrame, junk2; int junk; - gi.G2API_GetBoneAnimIndex( &genemy->ghoul2[genemy->playerModel], genemy->lowerLumbarBone, (cg.time?cg.time:level.time), ¤tFrame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex( &genemy->ghoul2[genemy->playerModel], genemy->lowerLumbarBone, (cg.time?cg.time:level.time), ¤tFrame, + &junk, &junk, &junk, &junk2, NULL ); */ - if ( genemy->client->ps.torsoAnim == BOTH_CWCIRCLELOCK || - genemy->client->ps.torsoAnim == BOTH_BF1LOCK ) - { - if ( !Q_irand( 0, 2 ) ) - { - switch ( Q_irand( 0, 3 ) ) - { + if (genemy->client->ps.torsoAnim == BOTH_CWCIRCLELOCK || genemy->client->ps.torsoAnim == BOTH_BF1LOCK) { + if (!Q_irand(0, 2)) { + switch (Q_irand(0, 3)) { case 0: - G_AddEvent( genemy, EV_PAIN, floor((float)genemy->health/genemy->max_health*100.0f) ); + G_AddEvent(genemy, EV_PAIN, floor((float)genemy->health / genemy->max_health * 100.0f)); break; case 1: - G_AddVoiceEvent( genemy, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 500 ); + G_AddVoiceEvent(genemy, Q_irand(EV_PUSHED1, EV_PUSHED3), 500); break; case 2: - G_AddVoiceEvent( genemy, Q_irand( EV_CHOKE1, EV_CHOKE3 ), 500 ); + G_AddVoiceEvent(genemy, Q_irand(EV_CHOKE1, EV_CHOKE3), 500); break; case 3: - G_AddVoiceEvent( genemy, EV_PUSHFAIL, 2000 ); + G_AddVoiceEvent(genemy, EV_PUSHFAIL, 2000); break; } } - PM_SetAnimFrame( genemy, anim->firstFrame+remaining, qtrue, qtrue ); + PM_SetAnimFrame(genemy, anim->firstFrame + remaining, qtrue, qtrue); /* curFrame = floor( currentFrame ); @@ -6636,10 +5420,8 @@ qboolean PM_SaberLocked( void ) PM_SetAnimFrame( genemy, curFrame-1, qtrue, qtrue ); } */ - } - else - { - PM_SetAnimFrame( genemy, anim->firstFrame+anim->numFrames-remaining, qtrue, qtrue ); + } else { + PM_SetAnimFrame(genemy, anim->firstFrame + anim->numFrames - remaining, qtrue, qtrue); /* curFrame = ceil( currentFrame ); //advance his frame one @@ -6660,32 +5442,21 @@ qboolean PM_SaberLocked( void ) } } } + } else { // FIXME: other ways out of a saberlock? + // force-push? (requires more force power?) + // kick? (requires anim ... hit jump key?) + // roll? + // backflip? } - else - {//FIXME: other ways out of a saberlock? - //force-push? (requires more force power?) - //kick? (requires anim ... hit jump key?) - //roll? - //backflip? - } - } - else - {//something broke us out of it - if ( gent->painDebounceTime > level.time && genemy->painDebounceTime > level.time ) - { - PM_SaberLockBreak( gent, genemy, LOCK_DRAW, 0 ); - } - else if ( gent->painDebounceTime > level.time ) - { - PM_SaberLockBreak( genemy, gent, LOCK_VICTORY, 0 ); - } - else if ( genemy->painDebounceTime > level.time ) - { - PM_SaberLockBreak( gent, genemy, LOCK_VICTORY, 0 ); - } - else - { - PM_SaberLockBreak( gent, genemy, LOCK_STALEMATE, 0 ); + } else { // something broke us out of it + if (gent->painDebounceTime > level.time && genemy->painDebounceTime > level.time) { + PM_SaberLockBreak(gent, genemy, LOCK_DRAW, 0); + } else if (gent->painDebounceTime > level.time) { + PM_SaberLockBreak(genemy, gent, LOCK_VICTORY, 0); + } else if (genemy->painDebounceTime > level.time) { + PM_SaberLockBreak(gent, genemy, LOCK_VICTORY, 0); + } else { + PM_SaberLockBreak(gent, genemy, LOCK_STALEMATE, 0); } } return qtrue; @@ -6701,20 +5472,14 @@ While this is a little different than the Quake 3 code, there is no clean way of */ // Ultimate goal is to set the sabermove to the proper next location // Note that if the resultant animation is NONE, then the animation is essentially "idle", and is set in WP_TorsoAnim -void PM_WeaponLightsaber(void) -{ - int addTime; - qboolean delayed_fire = qfalse; - int anim=-1, curmove, newmove=LS_NONE; - - if ( !pm->ps->clientNum - && cg.saberAnimLevelPending > FORCE_LEVEL_0 - && cg.saberAnimLevelPending != pm->ps->saberAnimLevel ) - { - if ( !PM_SaberInStart( pm->ps->saberMove ) - && !PM_SaberInTransition( pm->ps->saberMove ) - && !PM_SaberInAttack( pm->ps->saberMove ) ) - {//don't allow changes when in the middle of an attack set...(or delay the change until it's done) +void PM_WeaponLightsaber(void) { + int addTime; + qboolean delayed_fire = qfalse; + int anim = -1, curmove, newmove = LS_NONE; + + if (!pm->ps->clientNum && cg.saberAnimLevelPending > FORCE_LEVEL_0 && cg.saberAnimLevelPending != pm->ps->saberAnimLevel) { + if (!PM_SaberInStart(pm->ps->saberMove) && !PM_SaberInTransition(pm->ps->saberMove) && + !PM_SaberInAttack(pm->ps->saberMove)) { // don't allow changes when in the middle of an attack set...(or delay the change until it's done) pm->ps->saberAnimLevel = cg.saberAnimLevelPending; } } @@ -6743,56 +5508,46 @@ void PM_WeaponLightsaber(void) } else */ - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } return; } - if ( PM_SaberLocked() ) - { + if (PM_SaberLocked()) { pm->ps->saberMove = LS_NONE; return; } - if ( pm->ps->saberEventFlags&SEF_INWATER )//saber in water + if (pm->ps->saberEventFlags & SEF_INWATER) // saber in water { - pm->cmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + pm->cmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); } qboolean saberInAir = qtrue; - if ( !PM_SaberInBrokenParry( pm->ps->saberMove ) && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && !PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're not stuck in a broken parry - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (!PM_SaberInBrokenParry(pm->ps->saberMove) && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && + !PM_DodgeAnim(pm->ps->torsoAnim)) { // we're not stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } - if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) - { - if ( pm->ps->weapon != pm->cmd.weapon ) - { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } - } - else if ( pm->ps->weapon == WP_SABER ) - {//guiding saber - if ( saberInAir ) - { - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - PM_SetAnim( pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else if (pm->ps->weapon == WP_SABER) { // guiding saber + if (saberInAir) { + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } return; @@ -6800,51 +5555,41 @@ void PM_WeaponLightsaber(void) } } - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually pm->gent->client->fireDelay -= pml.msec; - if ( pm->gent->client->fireDelay <= 0 ) - {//just finished delay timer + if (pm->gent->client->fireDelay <= 0) { // just finished delay timer pm->gent->client->fireDelay = 0; delayed_fire = qtrue; } } - // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + // don't allow attack until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) - { - if ( pm->gent ) - { + if (pm->ps->stats[STAT_HEALTH] <= 0) { + if (pm->gent) { pm->gent->s.loopSound = 0; } return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } - if ( !pm->ps->clientNum || PM_ControlledByPlayer() ) - {//player - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ ) - {//blocking a projectile - if ( pm->ps->forcePowerDebounce[FP_SABER_DEFENSE] < level.time ) - {//block is done or breaking out of it with an attack + if (!pm->ps->clientNum || PM_ControlledByPlayer()) { // player + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT_PROJ && pm->ps->saberBlocked <= BLOCKED_TOP_PROJ) { // blocking a projectile + if (pm->ps->forcePowerDebounce[FP_SABER_DEFENSE] < level.time) { // block is done or breaking out of it with an attack pm->ps->weaponTime = 0; pm->ps->saberBlocked = BLOCKED_NONE; - } - else if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - {//block is done or breaking out of it with an attack + } else if ((pm->cmd.buttons & BUTTON_ATTACK)) { // block is done or breaking out of it with an attack pm->ps->weaponTime = 0; pm->ps->saberBlocked = BLOCKED_NONE; } @@ -6852,11 +5597,10 @@ void PM_WeaponLightsaber(void) } // Now we react to a block action by the player's lightsaber. - if ( pm->ps->saberBlocked ) - { - if ( pm->ps->saberMove > LS_PUTAWAY && pm->ps->saberMove <= LS_A_BL2TR && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && - (pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ || pm->ps->saberBlocked > BLOCKED_TOP_PROJ))//&& Q_irand( 0, 2 ) - {//we parried another lightsaber while attacking, so treat it as a bounce + if (pm->ps->saberBlocked) { + if (pm->ps->saberMove > LS_PUTAWAY && pm->ps->saberMove <= LS_A_BL2TR && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && + (pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ || pm->ps->saberBlocked > BLOCKED_TOP_PROJ)) //&& Q_irand( 0, 2 ) + { // we parried another lightsaber while attacking, so treat it as a bounce pm->ps->saberBlocked = BLOCKED_ATK_BOUNCE; } /* @@ -6873,257 +5617,199 @@ void PM_WeaponLightsaber(void) } */ - if ( pm->ps->saberBlocked != BLOCKED_ATK_BOUNCE ) - {//can't attack for twice whatever your skill level's parry debounce time is - if ( pm->ps->clientNum == 0 || PM_ControlledByPlayer() ) - {//player - if ( pm->ps->forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1 ) - { + if (pm->ps->saberBlocked != BLOCKED_ATK_BOUNCE) { // can't attack for twice whatever your skill level's parry debounce time is + if (pm->ps->clientNum == 0 || PM_ControlledByPlayer()) { // player + if (pm->ps->forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1) { pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]]; } - } - else - {//NPC - //pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; - if ( pm->gent ) - { - pm->ps->weaponTime = Jedi_ReCalcParryTime( pm->gent, EVASION_PARRY ); - } - else - {//WTF??? + } else { // NPC + // pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; + if (pm->gent) { + pm->ps->weaponTime = Jedi_ReCalcParryTime(pm->gent, EVASION_PARRY); + } else { // WTF??? pm->ps->weaponTime = parryDebounce[pm->ps->forcePowerLevel[FP_SABER_DEFENSE]] * 2; } } } - switch ( pm->ps->saberBlocked ) - { - case BLOCKED_PARRY_BROKEN: - //whatever parry we were is in now broken, play the appropriate knocked-away anim - { - int nextMove; - if ( PM_SaberInBrokenParry( pm->ps->saberBounceMove ) ) - {//already have one...? - nextMove = pm->ps->saberBounceMove; - } - else - { - nextMove = PM_BrokenParryForParry( pm->ps->saberMove ); - } - if ( nextMove != LS_NONE ) - { - PM_SetSaberMove( nextMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - {//Maybe in a knockaway? - } - //pm->ps->saberBounceMove = LS_NONE; + switch (pm->ps->saberBlocked) { + case BLOCKED_PARRY_BROKEN: + // whatever parry we were is in now broken, play the appropriate knocked-away anim + { + int nextMove; + if (PM_SaberInBrokenParry(pm->ps->saberBounceMove)) { // already have one...? + nextMove = pm->ps->saberBounceMove; + } else { + nextMove = PM_BrokenParryForParry(pm->ps->saberMove); } - break; - case BLOCKED_ATK_BOUNCE: - // If there is absolutely no blocked move in the chart, don't even mess with the animation. - // OR if we are already in a block or parry. - if ( pm->ps->saberMove >= LS_T1_BR__R/*LS_BOUNCE_TOP*/ )//|| saberMoveData[pm->ps->saberMove].bounceMove == LS_NONE ) - {//an actual bounce? Other bounces before this are actually transitions? - pm->ps->saberBlocked = BLOCKED_NONE; + if (nextMove != LS_NONE) { + PM_SetSaberMove(nextMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { // Maybe in a knockaway? } - else if ( PM_SaberInBounce( pm->ps->saberMove ) || !PM_SaberInAttack( pm->ps->saberMove ) ) - {//already in the bounce, go into an attack or transition to ready.. should never get here since can't be blocked in a bounce! - int nextMove; - - if ( pm->cmd.buttons & BUTTON_ATTACK ) - {//transition to a new attack - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPC - nextMove = saberMoveData[pm->ps->saberMove].chain_attack; - } - else - {//player - int newQuad = PM_SaberMoveQuadrantForMovement( &pm->cmd ); - while ( newQuad == saberMoveData[pm->ps->saberMove].startQuad ) - {//player is still in same attack quad, don't repeat that attack because it looks bad, - //FIXME: try to pick one that might look cool? - newQuad = Q_irand( Q_BR, Q_BL ); - //FIXME: sanity check, just in case? - }//else player is switching up anyway, take the new attack dir - nextMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; - } + // pm->ps->saberBounceMove = LS_NONE; + } + break; + case BLOCKED_ATK_BOUNCE: + // If there is absolutely no blocked move in the chart, don't even mess with the animation. + // OR if we are already in a block or parry. + if (pm->ps->saberMove >= LS_T1_BR__R /*LS_BOUNCE_TOP*/) //|| saberMoveData[pm->ps->saberMove].bounceMove == LS_NONE ) + { // an actual bounce? Other bounces before this are actually transitions? + pm->ps->saberBlocked = BLOCKED_NONE; + } else if (PM_SaberInBounce(pm->ps->saberMove) || + !PM_SaberInAttack(pm->ps->saberMove)) { // already in the bounce, go into an attack or transition to ready.. should never get here since + // can't be blocked in a bounce! + int nextMove; + + if (pm->cmd.buttons & BUTTON_ATTACK) { // transition to a new attack + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPC + nextMove = saberMoveData[pm->ps->saberMove].chain_attack; + } else { // player + int newQuad = PM_SaberMoveQuadrantForMovement(&pm->cmd); + while ( + newQuad == + saberMoveData[pm->ps->saberMove].startQuad) { // player is still in same attack quad, don't repeat that attack because it looks bad, + // FIXME: try to pick one that might look cool? + newQuad = Q_irand(Q_BR, Q_BL); + // FIXME: sanity check, just in case? + } // else player is switching up anyway, take the new attack dir + nextMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; } - else - {//return to ready - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPC - nextMove = saberMoveData[pm->ps->saberMove].chain_idle; - } - else - {//player - if ( saberMoveData[pm->ps->saberMove].startQuad == Q_T ) - { - nextMove = LS_R_BL2TR; - } - else if ( saberMoveData[pm->ps->saberMove].startQuad < Q_T ) - { - nextMove = LS_R_TL2BR+saberMoveData[pm->ps->saberMove].startQuad-Q_BR; - } - else// if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) - { - nextMove = LS_R_BR2TL+saberMoveData[pm->ps->saberMove].startQuad-Q_TL; - } + } else { // return to ready + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPC + nextMove = saberMoveData[pm->ps->saberMove].chain_idle; + } else { // player + if (saberMoveData[pm->ps->saberMove].startQuad == Q_T) { + nextMove = LS_R_BL2TR; + } else if (saberMoveData[pm->ps->saberMove].startQuad < Q_T) { + nextMove = LS_R_TL2BR + saberMoveData[pm->ps->saberMove].startQuad - Q_BR; + } else // if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) + { + nextMove = LS_R_BR2TL + saberMoveData[pm->ps->saberMove].startQuad - Q_TL; } } - PM_SetSaberMove( nextMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; } - else - {//start the bounce move - int bounceMove; - if ( pm->ps->saberBounceMove != LS_NONE ) - { - bounceMove = pm->ps->saberBounceMove; - } - else - { - bounceMove = PM_SaberBounceForAttack( pm->ps->saberMove ); - } - PM_SetSaberMove( bounceMove ); - pm->ps->weaponTime = pm->ps->torsoAnimTimer; + PM_SetSaberMove(nextMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { // start the bounce move + int bounceMove; + if (pm->ps->saberBounceMove != LS_NONE) { + bounceMove = pm->ps->saberBounceMove; + } else { + bounceMove = PM_SaberBounceForAttack(pm->ps->saberMove); } - //clear the saberBounceMove - //pm->ps->saberBounceMove = LS_NONE; + PM_SetSaberMove(bounceMove); + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } + // clear the saberBounceMove + // pm->ps->saberBounceMove = LS_NONE; - if (cg_debugSaber.integer>=2) - { - Com_Printf("Saber Block: Bounce\n"); - } - break; - case BLOCKED_UPPER_RIGHT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UR ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Bounce\n"); + } + break; + case BLOCKED_UPPER_RIGHT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove(pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UR); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf( "Saber Block: Parry UR\n" ); - } - break; - case BLOCKED_UPPER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_UR ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry UR\n"); + } + break; + case BLOCKED_UPPER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_UR); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect UR\n"); - } - break; - case BLOCKED_UPPER_LEFT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UL ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect UR\n"); + } + break; + case BLOCKED_UPPER_LEFT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove(pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UL); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf( "Saber Block: Parry UL\n" ); - } - break; - case BLOCKED_UPPER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_UL ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry UL\n"); + } + break; + case BLOCKED_UPPER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_UL); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect UL\n"); - } - break; - case BLOCKED_LOWER_RIGHT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_LR ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect UL\n"); + } + break; + case BLOCKED_LOWER_RIGHT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove(pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_LR); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry LR\n"); - } - break; - case BLOCKED_LOWER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_LR ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry LR\n"); + } + break; + case BLOCKED_LOWER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_LR); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect LR\n"); - } - break; - case BLOCKED_LOWER_LEFT: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_LL ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect LR\n"); + } + break; + case BLOCKED_LOWER_LEFT: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove(pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_LL); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry LL\n"); - } - break; - case BLOCKED_LOWER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_LL); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry LL\n"); + } + break; + case BLOCKED_LOWER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_LL); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect LL\n"); - } - break; - case BLOCKED_TOP: - if ( pm->ps->saberBounceMove != LS_NONE ) - { - PM_SetSaberMove( pm->ps->saberBounceMove ); - //pm->ps->saberBounceMove = LS_NONE; - pm->ps->weaponTime = pm->ps->torsoAnimTimer; - } - else - { - PM_SetSaberMove( LS_PARRY_UP ); - } + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect LL\n"); + } + break; + case BLOCKED_TOP: + if (pm->ps->saberBounceMove != LS_NONE) { + PM_SetSaberMove(pm->ps->saberBounceMove); + // pm->ps->saberBounceMove = LS_NONE; + pm->ps->weaponTime = pm->ps->torsoAnimTimer; + } else { + PM_SetSaberMove(LS_PARRY_UP); + } - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Parry Top\n"); - } - break; - case BLOCKED_TOP_PROJ: - PM_SetSaberMove( LS_REFLECT_UP ); + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Parry Top\n"); + } + break; + case BLOCKED_TOP_PROJ: + PM_SetSaberMove(LS_REFLECT_UP); - if ( cg_debugSaber.integer >= 2 ) - { - Com_Printf("Saber Block: Deflect Top\n"); - } - break; - default: - pm->ps->saberBlocked = BLOCKED_NONE; - break; + if (cg_debugSaber.integer >= 2) { + Com_Printf("Saber Block: Deflect Top\n"); + } + break; + default: + pm->ps->saberBlocked = BLOCKED_NONE; + break; } // Charging is like a lead-up before attacking again. This is an appropriate use, or we can create a new weaponstate for blocking @@ -7136,18 +5822,17 @@ void PM_WeaponLightsaber(void) // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) { - if ( pm->ps->weapon != pm->cmd.weapon ) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) - { - //FIXME: allow some window of opportunity to change your attack + if (pm->ps->weaponTime > 0) { + // FIXME: allow some window of opportunity to change your attack // if it just started and your directional input is different // than it was before... but only 100 milliseconds at most? - //OR: Make it so that attacks don't start until 100ms after you + // OR: Make it so that attacks don't start until 100ms after you // press the attack button...??? return; } @@ -7157,7 +5842,7 @@ void PM_WeaponLightsaber(void) // ********************************************************* // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } @@ -7166,58 +5851,40 @@ void PM_WeaponLightsaber(void) // WEAPON_RAISING // ********************************************************* - if ( pm->ps->weaponstate == WEAPON_RAISING ) - {//Just selected the weapon + if (pm->ps->weaponstate == WEAPON_RAISING) { // Just selected the weapon pm->ps->weaponstate = WEAPON_IDLE; - if(pm->gent && pm->gent->s.number == 0) - { - if( pm->ps->legsAnim == BOTH_WALK1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN1 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK2 ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND2,SETANIM_FLAG_NORMAL); + if (pm->gent && pm->gent->s.number == 0) { + if (pm->ps->legsAnim == BOTH_WALK1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN1) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND2, SETANIM_FLAG_NORMAL); } - } - else - { + } else { qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir ) - {//guiding saber - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - PM_SetAnim( pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir) { // guiding saber + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { + } else { // PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_NORMAL);//TORSO_WEAPONIDLE1 // Select the proper idle Lightsaber attack move from the chart. PM_SetSaberMove(LS_READY); @@ -7230,71 +5897,47 @@ void PM_WeaponLightsaber(void) // Check for WEAPON ATTACK // ********************************************************* - if(!delayed_fire) - { + if (!delayed_fire) { // Start with the current move, and cross index it with the current control states. - if ( pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX ) - { + if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) { curmove = pm->ps->saberMove; - } - else - { + } else { curmove = LS_READY; } - if ( curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_ ) - {//must transition back to ready from this anim + if (curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_) { // must transition back to ready from this anim newmove = LS_R_T2B; } // check for fire - else if ( !(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//not attacking + else if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // not attacking pm->ps->weaponTime = 0; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//Still firing + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // Still firing pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { + } else if (pm->ps->weaponstate != WEAPON_READY) { pm->ps->weaponstate = WEAPON_IDLE; } - //Check for finishing an anim if necc. - if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( curmove >= LS_A_TL2BR && curmove <= LS_A_T2B ) - {//finished an attack, must continue from here - newmove = LS_R_TL2BR + (curmove-LS_A_TL2BR); - } - else if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // Check for finishing an anim if necc. + if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (curmove >= LS_A_TL2BR && curmove <= LS_A_T2B) { // finished an attack, must continue from here + newmove = LS_R_TL2BR + (curmove - LS_A_TL2BR); + } else if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( PM_SaberInBounce( curmove ) ) - {//in a bounce - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPCs must play sequential attack - //going into another attack... - //allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 - if ( PM_SaberKataDone( LS_NONE, LS_NONE ) ) - {//done with this kata, must return to ready before attack again + } else if (PM_SaberInBounce(curmove)) { // in a bounce + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPCs must play sequential attack + // going into another attack... + // allow endless chaining in level 1 attacks, several in level 2 and only one or a few in level 3 + if (PM_SaberKataDone(LS_NONE, LS_NONE)) { // done with this kata, must return to ready before attack again newmove = saberMoveData[curmove].chain_idle; - } - else - {//okay to chain to another attack - newmove = saberMoveData[curmove].chain_attack;//we assume they're attacking, even if they're not + } else { // okay to chain to another attack + newmove = saberMoveData[curmove].chain_attack; // we assume they're attacking, even if they're not pm->ps->saberAttackChainCount++; } + } else { // player gets his by directional control + newmove = saberMoveData[curmove].chain_idle; // oops, not attacking, so don't chain } - else - {//player gets his by directional control - newmove = saberMoveData[curmove].chain_idle;//oops, not attacking, so don't chain - } - } - else - {//FIXME: what about returning from a parry? - //PM_SetSaberMove( LS_READY ); + } else { // FIXME: what about returning from a parry? + // PM_SetSaberMove( LS_READY ); return; } } @@ -7302,47 +5945,35 @@ void PM_WeaponLightsaber(void) // *************************************************** // Pressing attack, so we must look up the proper attack move. qboolean saberInAir = qtrue; - if ( pm->ps->saberInFlight ) - {//guiding saber - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || PM_DodgeAnim( pm->ps->torsoAnim ) ) - {//we're stuck in a broken parry + if (pm->ps->saberInFlight) { // guiding saber + if (PM_SaberInBrokenParry(pm->ps->saberMove) || pm->ps->saberBlocked == BLOCKED_PARRY_BROKEN || + PM_DodgeAnim(pm->ps->torsoAnim)) { // we're stuck in a broken parry saberInAir = qfalse; } - if ( pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[pm->ps->saberEntityNum] != NULL && g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground and we're not trying to pull it back + if (pm->ps->saberEntityNum < ENTITYNUM_NONE && pm->ps->saberEntityNum > 0) // player is 0 + { // + if (&g_entities[pm->ps->saberEntityNum] != NULL && + g_entities[pm->ps->saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground and we're not trying to pull it back saberInAir = qfalse; } } } - if ( pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir ) - {//guiding saber - if ( !PM_ForceAnim( pm->ps->torsoAnim ) || pm->ps->torsoAnimTimer < 300 ) - {//don't interrupt a force power anim - PM_SetAnim( pm, SETANIM_TORSO,BOTH_SABERPULL,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pm->ps->weapon == WP_SABER && pm->ps->saberInFlight && saberInAir) { // guiding saber + if (!PM_ForceAnim(pm->ps->torsoAnim) || pm->ps->torsoAnimTimer < 300) { // don't interrupt a force power anim + PM_SetAnim(pm, SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else if ( pm->ps->weaponTime > 0 ) - { // Last attack is not yet complete. + } else if (pm->ps->weaponTime > 0) { // Last attack is not yet complete. pm->ps->weaponstate = WEAPON_FIRING; return; - } - else - { - int both = qfalse; + } else { + int both = qfalse; - if ( curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL ) - {//from a parry or reflection, can go directly into an attack - if ( pm->ps->clientNum && !PM_ControlledByPlayer() ) - {//NPCs - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - { - switch ( saberMoveData[curmove].endQuad ) - { + if (curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL) { // from a parry or reflection, can go directly into an attack + if (pm->ps->clientNum && !PM_ControlledByPlayer()) { // NPCs + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { + switch (saberMoveData[curmove].endQuad) { case Q_T: newmove = LS_A_T2B; break; @@ -7358,60 +5989,50 @@ void PM_WeaponLightsaber(void) case Q_BL: newmove = LS_A_BL2TR; break; - //shouldn't be a parry that ends at L, R or B + // shouldn't be a parry that ends at L, R or B } } } - if ( newmove != LS_NONE ) - {//have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim - if (PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse)) - { + if (newmove != LS_NONE) { // have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { anim = saberMoveData[newmove].animToUse; } } - //FIXME: diagonal dirs use the figure-eight attacks from ready pose? - if ( anim == -1 ) - { - //FIXME: take FP_SABER_OFFENSE into account here somehow? - if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // FIXME: diagonal dirs use the figure-eight attacks from ready pose? + if (anim == -1) { + // FIXME: take FP_SABER_OFFENSE into account here somehow? + if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( PM_SaberInBrokenParry( curmove ) ) - {//broken parries must always return to ready + } else if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (PM_SaberInBrokenParry(curmove)) { // broken parries must always return to ready newmove = LS_READY; - } - else//if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? - {//get attack move from movement command + } else // if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? + { // get attack move from movement command /* if ( PM_SaberKataDone() ) {//we came from a bounce and cannot chain to another attack because our kata is done newmove = saberMoveData[curmove].chain_idle; } else */ - if ( pm->ps->clientNum - && !PM_ControlledByPlayer() - && (Q_irand( 0, pm->ps->saberAnimLevel-1 ) || ( pm->ps->saberAnimLevel == FORCE_LEVEL_1 && pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && Q_irand( 0, 1 ) ) ) )//minor change to make fast-attack users use the special attacks more - {//NPCs use more randomized attacks the more skilled they are - newmove = PM_NPCSaberAttackFromQuad( saberMoveData[curmove].endQuad ); - } - else - { - newmove = PM_SaberAttackForMovement( pm->cmd.forwardmove, pm->cmd.rightmove, curmove ); - if ( (PM_SaberInBounce( curmove )||PM_SaberInBrokenParry( curmove )) - && saberMoveData[newmove].startQuad == saberMoveData[curmove].endQuad ) - {//this attack would be a repeat of the last (which was blocked), so don't actually use it, use the default chain attack for this bounce + if (pm->ps->clientNum && !PM_ControlledByPlayer() && + (Q_irand(0, pm->ps->saberAnimLevel - 1) || + (pm->ps->saberAnimLevel == FORCE_LEVEL_1 && pm->gent && pm->gent->NPC && pm->gent->NPC->rank >= RANK_LT_JG && + Q_irand(0, 1)))) // minor change to make fast-attack users use the special attacks more + { // NPCs use more randomized attacks the more skilled they are + newmove = PM_NPCSaberAttackFromQuad(saberMoveData[curmove].endQuad); + } else { + newmove = PM_SaberAttackForMovement(pm->cmd.forwardmove, pm->cmd.rightmove, curmove); + if ((PM_SaberInBounce(curmove) || PM_SaberInBrokenParry(curmove)) && + saberMoveData[newmove].startQuad == + saberMoveData[curmove].endQuad) { // this attack would be a repeat of the last (which was blocked), so don't actually use it, + // use the default chain attack for this bounce newmove = saberMoveData[curmove].chain_attack; } } - if ( PM_SaberKataDone( curmove, newmove ) ) - {//cannot chain this time + if (PM_SaberKataDone(curmove, newmove)) { // cannot chain this time newmove = saberMoveData[curmove].chain_idle; } } @@ -7422,72 +6043,57 @@ void PM_WeaponLightsaber(void) newmove = PM_AttackMoveForQuad( saberMoveData[curmove].endQuad ); } */ - if ( newmove != LS_NONE ) - { - //Now get the proper transition move - newmove = PM_SaberAnimTransitionAnim( curmove, newmove ); - if ( PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse ) ) - { + if (newmove != LS_NONE) { + // Now get the proper transition move + newmove = PM_SaberAnimTransitionAnim(curmove, newmove); + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { anim = saberMoveData[newmove].animToUse; } } } - if (anim == -1) - {//not side-stepping, pick neutral anim + if (anim == -1) { // not side-stepping, pick neutral anim // Add randomness for prototype? newmove = saberMoveData[curmove].chain_attack; - if (PM_HasAnimation( pm->gent, saberMoveData[newmove].animToUse)) - { - anim= saberMoveData[newmove].animToUse; + if (PM_HasAnimation(pm->gent, saberMoveData[newmove].animToUse)) { + anim = saberMoveData[newmove].animToUse; } - if ( !pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//not moving at all, so set the anim on entire body + if (!pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && + pm->ps->groundEntityNum != ENTITYNUM_NONE) { // not moving at all, so set the anim on entire body both = qtrue; } - } - if ( anim == -1) - { - if( pm->ps->legsAnim == BOTH_WALK1 ) - { + if (anim == -1) { + if (pm->ps->legsAnim == BOTH_WALK1) { anim = BOTH_WALK1; - } - else if( pm->ps->legsAnim == BOTH_RUN2 ) - { + } else if (pm->ps->legsAnim == BOTH_RUN2) { anim = BOTH_RUN2; - } - else if( pm->ps->legsAnim == BOTH_WALK2 ) - { + } else if (pm->ps->legsAnim == BOTH_WALK2) { anim = BOTH_WALK2; - } - else - { - //FIXME: play both_stand2_random1 when you've been idle for a while + } else { + // FIXME: play both_stand2_random1 when you've been idle for a while anim = BOTH_STAND2; } newmove = LS_READY; } - if ( !pm->ps->saberActive ) - {//turn on the saber if it's not on + if (!pm->ps->saberActive) { // turn on the saber if it's not on pm->ps->saberActive = qtrue; } - PM_SetSaberMove( newmove ); + PM_SetSaberMove(newmove); - if ( both ) - { - PM_SetAnim( pm,SETANIM_LEGS,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (both) { + PM_SetAnim(pm, SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( pm->gent && pm->gent->client ) - { -// pm->gent->client->saberTrail.inAction = qtrue; -// pm->gent->client->saberTrail.duration = 75; // saber trail lasts for 75ms...feel free to change this if you want it longer or shorter + if (pm->gent && pm->gent->client) { + // pm->gent->client->saberTrail.inAction = qtrue; + // pm->gent->client->saberTrail.duration = 75; // saber trail lasts for 75ms...feel free to change this if you want it longer or + //shorter } - //don't fire again until anim is done + // don't fire again until anim is done pm->ps->weaponTime = pm->ps->torsoAnimTimer; /* //FIXME: this may be making it so sometimes you can't swing again right away... @@ -7505,8 +6111,7 @@ void PM_WeaponLightsaber(void) pm->ps->weaponstate = WEAPON_FIRING; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually // Clear these out since we're not actually firing yet pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; @@ -7514,48 +6119,32 @@ void PM_WeaponLightsaber(void) } addTime = pm->ps->weaponTime; - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) { - PM_AddEvent( EV_ALT_FIRE ); - if ( !addTime ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_AddEvent(EV_ALT_FIRE); + if (!addTime) { addTime = weaponData[pm->ps->weapon].altFireTime; - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive & (1 << FP_SPEED)) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client && pm->ps->forcePowersActive&(1<ps->clientNum].client && pm->ps->forcePowersActive & (1 << FP_SPEED)) { addTime *= g_timescale->value; } } } } } - } - else { - PM_AddEvent( EV_FIRE_WEAPON ); - if ( !addTime ) - { + } else { + PM_AddEvent(EV_FIRE_WEAPON); + if (!addTime) { addTime = weaponData[pm->ps->weapon].fireTime; - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive & (1 << FP_SPEED)) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client - && pm->ps->forcePowersActive&(1<ps->clientNum].client && pm->ps->forcePowersActive & (1 << FP_SPEED)) { addTime *= g_timescale->value; } } @@ -7564,9 +6153,8 @@ void PM_WeaponLightsaber(void) } } - //If the phaser has been fired, delay the next recharge time - if(pm->gent && pm->gent->NPC != NULL ) - {//NPCs have their own refire logic + // If the phaser has been fired, delay the next recharge time + if (pm->gent && pm->gent->NPC != NULL) { // NPCs have their own refire logic return; } @@ -7574,22 +6162,19 @@ void PM_WeaponLightsaber(void) } //--------------------------------------- -static bool PM_DoChargedWeapons( void ) +static bool PM_DoChargedWeapons(void) //--------------------------------------- { - qboolean charging = qfalse, - altFire = qfalse; + qboolean charging = qfalse, altFire = qfalse; - //FIXME: make jedi aware they're being aimed at with a charged-up weapon (strafe and be evasive?) - // If you want your weapon to be a charging weapon, just set this bit up - switch( pm->ps->weapon ) - { + // FIXME: make jedi aware they're being aimed at with a charged-up weapon (strafe and be evasive?) + // If you want your weapon to be a charging weapon, just set this bit up + switch (pm->ps->weapon) { //------------------ case WP_BRYAR_PISTOL: // alt-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -7600,23 +6185,16 @@ static bool PM_DoChargedWeapons( void ) // alt-fire charges the weapon...but due to zooming being controlled by the alt-button, the main button actually charges...but only when zoomed. // lovely, eh? - if ( !pm->ps->clientNum ) - { - if ( cg.zoomMode == 2 ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (!pm->ps->clientNum) { + if (cg.zoomMode == 2) { + if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; altFire = qtrue; // believe it or not, it really is an alt-fire in this case! } } - } - else if ( pm->gent && pm->gent->NPC ) - { - if ( (pm->gent->NPC->scriptFlags&SCF_ALT_FIRE) ) - { - if ( pm->gent->fly_sound_debounce_time > level.time ) - { + } else if (pm->gent && pm->gent->NPC) { + if ((pm->gent->NPC->scriptFlags & SCF_ALT_FIRE)) { + if (pm->gent->fly_sound_debounce_time > level.time) { charging = qtrue; altFire = qtrue; } @@ -7628,8 +6206,7 @@ static bool PM_DoChargedWeapons( void ) case WP_BOWCASTER: // main-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; @@ -7638,8 +6215,7 @@ static bool PM_DoChargedWeapons( void ) case WP_DEMP2: // alt-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -7650,8 +6226,7 @@ static bool PM_DoChargedWeapons( void ) // Not really a charge weapon, but we still want to delay fire until the button comes up so that we can // implement our alt-fire locking stuff - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -7662,13 +6237,10 @@ static bool PM_DoChargedWeapons( void ) // FIXME: Really should have a wind-up anim for player // as he holds down the fire button to throw, then play // the actual throw when he lets go... - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; // override default of not being an alt-fire charging = qtrue; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; @@ -7677,15 +6249,11 @@ static bool PM_DoChargedWeapons( void ) // set up the appropriate weapon state based on the button that's down. // Note that we ALWAYS return if charging is set ( meaning the buttons are still down ) - if ( charging ) - { - if ( altFire ) - { - if ( pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_DROPPING ) - { - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) - { - PM_AddEvent( EV_NOAMMO ); + if (charging) { + if (altFire) { + if (pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_DROPPING) { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; return true; } @@ -7694,19 +6262,14 @@ static bool PM_DoChargedWeapons( void ) pm->ps->weaponstate = WEAPON_CHARGING_ALT; pm->ps->weaponChargeTime = level.time; - if ( cg_weapons[pm->ps->weapon].altChargeSound ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].altChargeSnd ); + if (cg_weapons[pm->ps->weapon].altChargeSound) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].altChargeSnd); } } - } - else - { - if ( pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_DROPPING ) - { - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) - { - PM_AddEvent( EV_NOAMMO ); + } else { + if (pm->ps->weaponstate != WEAPON_CHARGING && pm->ps->weaponstate != WEAPON_DROPPING) { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; return true; } @@ -7715,9 +6278,9 @@ static bool PM_DoChargedWeapons( void ) pm->ps->weaponstate = WEAPON_CHARGING; pm->ps->weaponChargeTime = level.time; - if ( cg_weapons[pm->ps->weapon].chargeSound && pm->gent && !pm->gent->NPC ) // HACK: !NPC mostly for bowcaster and weequay + if (cg_weapons[pm->ps->weapon].chargeSound && pm->gent && !pm->gent->NPC) // HACK: !NPC mostly for bowcaster and weequay { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].chargeSnd ); + G_SoundOnEnt(pm->gent, CHAN_WEAPON, weaponData[pm->ps->weapon].chargeSnd); } } } @@ -7727,152 +6290,124 @@ static bool PM_DoChargedWeapons( void ) // Only charging weapons should be able to set these states...so.... // let's see which fire mode we need to set up now that the buttons are up - if ( pm->ps->weaponstate == WEAPON_CHARGING ) - { + if (pm->ps->weaponstate == WEAPON_CHARGING) { // weapon has a charge, so let us do an attack // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ATTACK; pm->ps->eFlags |= EF_FIRING; - } - else if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + } else if (pm->ps->weaponstate == WEAPON_CHARGING_ALT) { // weapon has a charge, so let us do an alt-attack // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ALT_ATTACK; - pm->ps->eFlags |= (EF_FIRING|EF_ALT_FIRING); + pm->ps->eFlags |= (EF_FIRING | EF_ALT_FIRING); } return false; // continue with the rest of the weapon code } - -#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define DEMP2_CHARGE_UNIT 500.0f // ditto -#define DISRUPTOR_CHARGE_UNIT 150.0f // ditto +#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon +#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon +#define DEMP2_CHARGE_UNIT 500.0f // ditto +#define DISRUPTOR_CHARGE_UNIT 150.0f // ditto // Specific weapons can opt to modify the ammo usage based on charges, otherwise if no special case code // is handled below, regular ammo usage will happen //--------------------------------------- -static int PM_DoChargingAmmoUsage( int *amount ) +static int PM_DoChargingAmmoUsage(int *amount) //--------------------------------------- { int count = 0; - if ( pm->ps->weapon == WP_BOWCASTER && !( pm->cmd.buttons & BUTTON_ALT_ATTACK )) - { + if (pm->ps->weapon == WP_BOWCASTER && !(pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the bowcaster alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / BOWCASTER_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / BOWCASTER_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if ( !(count & 1 )) - { + if (!(count & 1)) { // if we aren't odd, knock us down a level count--; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * BOWCASTER_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * BOWCASTER_CHARGE_UNIT); } } // now that count is cool, get the real ammo usage *amount *= count; - } - else if ( pm->ps->weapon == WP_BRYAR_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + } else if (pm->ps->weapon == WP_BRYAR_PISTOL && pm->cmd.buttons & BUTTON_ALT_ATTACK) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the bryar alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / BRYAR_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / BRYAR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * BRYAR_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * BRYAR_CHARGE_UNIT); } } // now that count is cool, get the real ammo usage *amount *= count; - } - else if ( pm->ps->weapon == WP_DEMP2 && pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + } else if (pm->ps->weapon == WP_DEMP2 && pm->cmd.buttons & BUTTON_ALT_ATTACK) { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the demp2 alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / DEMP2_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / DEMP2_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 3 ) - { + } else if (count > 3) { count = 3; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * DEMP2_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * DEMP2_CHARGE_UNIT); } } @@ -7880,43 +6415,36 @@ static int PM_DoChargingAmmoUsage( int *amount ) *amount *= count; // this is an after-thought. should probably re-write the function to do this naturally. - if ( *amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] ) - { + if (*amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]) { *amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]; } - } - else if ( pm->ps->weapon == WP_DISRUPTOR && pm->cmd.buttons & BUTTON_ALT_ATTACK ) // BUTTON_ATTACK will have been mapped to BUTTON_ALT_ATTACK if we are zoomed + } else if (pm->ps->weapon == WP_DISRUPTOR && + pm->cmd.buttons & BUTTON_ALT_ATTACK) // BUTTON_ATTACK will have been mapped to BUTTON_ALT_ATTACK if we are zoomed { // this code is duplicated ( I know, I know ) in G_weapon.cpp for the disruptor alt-fire - count = ( level.time - pm->ps->weaponChargeTime ) / DISRUPTOR_CHARGE_UNIT; + count = (level.time - pm->ps->weaponChargeTime) / DISRUPTOR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 10 ) - { + } else if (count > 10) { count = 10; } // Only bother with these checks if we don't have infinite ammo - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { int dif = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - *amount * count; // If we have enough ammo to do the full charged shot, we are ok - if ( dif < 0 ) - { + if (dif < 0) { // we are not ok, so hack our chargetime and ammo usage, note that DIF is going to be negative count += floor(dif / (float)*amount); - if ( count < 1 ) - { + if (count < 1) { count = 1; } // now get a real chargeTime so the duplicated code in g_weapon doesn't get freaked - pm->ps->weaponChargeTime = level.time - ( count * DISRUPTOR_CHARGE_UNIT ); + pm->ps->weaponChargeTime = level.time - (count * DISRUPTOR_CHARGE_UNIT); } } @@ -7924,8 +6452,7 @@ static int PM_DoChargingAmmoUsage( int *amount ) *amount *= count; // this is an after-thought. should probably re-write the function to do this naturally. - if ( *amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] ) - { + if (*amount > pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]) { *amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex]; } } @@ -7933,14 +6460,8 @@ static int PM_DoChargingAmmoUsage( int *amount ) return count; } -qboolean PM_DroidMelee( int npc_class ) -{ - if ( npc_class == CLASS_PROBE - || npc_class == CLASS_SEEKER - || npc_class == CLASS_INTERROGATOR - || npc_class == CLASS_SENTRY - || npc_class == CLASS_REMOTE ) - { +qboolean PM_DroidMelee(int npc_class) { + if (npc_class == CLASS_PROBE || npc_class == CLASS_SEEKER || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_SENTRY || npc_class == CLASS_REMOTE) { return qtrue; } return qfalse; @@ -7953,23 +6474,18 @@ PM_Weapon Generates weapon events and modifes the weapon counter ============== */ -static void PM_Weapon( void ) -{ - int addTime, amount, trueCount = 1; - qboolean delayed_fire = qfalse; +static void PM_Weapon(void) { + int addTime, amount, trueCount = 1; + qboolean delayed_fire = qfalse; - if (pm->ps->weapon == WP_SABER && (cg.zoomMode==3||!cg.zoomMode||pm->ps->clientNum) ) // WP_LIGHTSABER - { // Separate logic for lightsaber, but not for player when zoomed + if (pm->ps->weapon == WP_SABER && (cg.zoomMode == 3 || !cg.zoomMode || pm->ps->clientNum)) // WP_LIGHTSABER + { // Separate logic for lightsaber, but not for player when zoomed PM_WeaponLightsaber(); - if ( pm->gent && pm->gent->client && pm->ps->saberActive && pm->ps->saberInFlight ) - {//FIXME: put saberTrail in playerState - if ( pm->gent->client->ps.saberEntityState == SES_RETURNING ) - {//turn off the saber trail + if (pm->gent && pm->gent->client && pm->ps->saberActive && pm->ps->saberInFlight) { // FIXME: put saberTrail in playerState + if (pm->gent->client->ps.saberEntityState == SES_RETURNING) { // turn off the saber trail pm->gent->client->saberTrail.inAction = qfalse; pm->gent->client->saberTrail.duration = 75; - } - else - {//turn on the saber trail + } else { // turn on the saber trail pm->gent->client->saberTrail.inAction = qtrue; pm->gent->client->saberTrail.duration = 150; } @@ -7977,135 +6493,111 @@ static void PM_Weapon( void ) return; } - if ( PM_InKnockDown( pm->ps ) || PM_InRoll( pm->ps )) - {//in knockdown - if ( pm->ps->weaponTime > 0 ) { + if (PM_InKnockDown(pm->ps) || PM_InRoll(pm->ps)) { // in knockdown + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } return; } - if(pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually pm->gent->client->fireDelay -= pml.msec; - if(pm->gent->client->fireDelay <= 0) - {//just finished delay timer - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav" ); + if (pm->gent->client->fireDelay <= 0) { // just finished delay timer + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/lock.wav"); pm->cmd.buttons |= BUTTON_ALT_ATTACK; } pm->gent->client->fireDelay = 0; delayed_fire = qtrue; - } - else - { - if ( pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand( 0, 1 ) ) - { - G_SoundOnEnt( pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav" ); + } else { + if (pm->ps->clientNum && pm->ps->weapon == WP_ROCKET_LAUNCHER && Q_irand(0, 1)) { + G_SoundOnEnt(pm->gent, CHAN_WEAPON, "sound/weapons/rocket/tick.wav"); } } } - // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + // don't allow attack until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) - { - if ( pm->gent && pm->gent->client ) - { + if (pm->ps->stats[STAT_HEALTH] <= 0) { + if (pm->gent && pm->gent->client) { pm->ps->weapon = WP_NONE; } - if ( pm->gent ) - { + if (pm->gent) { pm->gent->s.loopSound = 0; } return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; } // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - if ( (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && pm->ps->weaponstate != WEAPON_CHARGING) { + if ((pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) && pm->ps->weaponstate != WEAPON_CHARGING_ALT && + pm->ps->weaponstate != WEAPON_CHARGING) { // eez- don't switch weapons if we're charging our current one up - if ( pm->ps->weapon != pm->cmd.weapon && (!pm->ps->viewEntity || pm->ps->viewEntity >= ENTITYNUM_WORLD) && !PM_DoChargedWeapons()) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weapon != pm->cmd.weapon && (!pm->ps->viewEntity || pm->ps->viewEntity >= ENTITYNUM_WORLD) && !PM_DoChargedWeapons()) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { return; } // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } - if ( pm->ps->weapon == WP_NONE ) - { + if (pm->ps->weapon == WP_NONE) { return; } - if ( PM_DoChargedWeapons() ) - { + if (PM_DoChargedWeapons()) { return; } - if ( pm->ps->weaponstate == WEAPON_RAISING ) - { - //Just selected the weapon + if (pm->ps->weaponstate == WEAPON_RAISING) { + // Just selected the weapon pm->ps->weaponstate = WEAPON_IDLE; - if(pm->gent && pm->gent->s.number == 0) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - else - { - switch(pm->ps->weapon) - { + if (pm->gent && pm->gent->s.number == 0) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_NORMAL); + } else { + switch (pm->ps->weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER_PISTOL: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE2,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE2, SETANIM_FLAG_NORMAL); break; default: - PM_SetAnim(pm,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); + PM_SetAnim(pm, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); break; } } return; } - if(!delayed_fire) - { + if (!delayed_fire) { // check for fire - if ( !(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - { + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { pm->ps->weaponTime = 0; - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//Still firing + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // Still firing pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { - if ( !pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time ) - { + } else if (pm->ps->weaponstate != WEAPON_READY) { + if (!pm->gent || !pm->gent->NPC || pm->gent->attackDebounceTime < level.time) { pm->ps->weaponstate = WEAPON_IDLE; } } @@ -8114,94 +6606,71 @@ static void PM_Weapon( void ) } // start the animation even if out of ammo - switch(pm->ps->weapon) - { -/* - case WP_SABER://1 - handed - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - break; -*/ - case WP_BRYAR_PISTOL://1-handed - case WP_BLASTER_PISTOL://1-handed - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + switch (pm->ps->weapon) { + /* + case WP_SABER://1 - handed + PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + break; + */ + case WP_BRYAR_PISTOL: // 1-handed + case WP_BLASTER_PISTOL: // 1-handed + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_MELEE: // since there's no RACE_BOTS, I listed all the droids that have might have melee attacks - dmv - if ( pm->gent && pm->gent->client ) - { - if ( PM_DroidMelee( pm->gent->client->NPC_class ) ) - { - if ( rand() & 1 ) - PM_SetAnim(pm,SETANIM_BOTH,BOTH_MELEE1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client) { + if (PM_DroidMelee(pm->gent->client->NPC_class)) { + if (rand() & 1) + PM_SetAnim(pm, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); else - PM_SetAnim(pm,SETANIM_BOTH,BOTH_MELEE2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else - { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { int anim; - if ( !pm->ps->clientNum ) - { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (!pm->ps->clientNum) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { anim = BOTH_MELEE2; - } - else - { + } else { anim = BOTH_MELEE1; } + } else { + anim = PM_PickAnim(pm->gent, BOTH_MELEE1, BOTH_MELEE2); } - else - { - anim = PM_PickAnim( pm->gent, BOTH_MELEE1, BOTH_MELEE2 ); - } - if ( VectorCompare( pm->ps->velocity, vec3_origin ) && pm->cmd.upmove >= 0 ) - { - PM_SetAnim( pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - } - else - { - PM_SetAnim( pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); + if (VectorCompare(pm->ps->velocity, vec3_origin) && pm->cmd.upmove >= 0) { + PM_SetAnim(pm, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } else { + PM_SetAnim(pm, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } } } break; case WP_BLASTER: - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); break; case WP_DISRUPTOR: - if ( (pm->ps->clientNum && pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags&SCF_ALT_FIRE)) || - (!pm->ps->clientNum && cg.zoomMode == 2 ) ) - {//NPC or player in alt-fire, sniper mode - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//in primary fire mode - PM_SetAnim( pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); + if ((pm->ps->clientNum && pm->gent && pm->gent->NPC && (pm->gent->NPC->scriptFlags & SCF_ALT_FIRE)) || + (!pm->ps->clientNum && cg.zoomMode == 2)) { // NPC or player in alt-fire, sniper mode + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // in primary fire mode + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } break; case WP_BOT_LASER: - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; case WP_THERMAL: - if ( pm->ps->clientNum ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK10,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - if ( cg.renderingThirdPerson ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_THERMAL_THROW,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (pm->ps->clientNum) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK10, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + if (cg.renderingThirdPerson) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } } break; @@ -8215,129 +6684,99 @@ static void PM_Weapon( void ) break; case WP_REPEATER: - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH ) - {// - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_GALAKMECH) { // + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } - } - else - { - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } break; - default://2-handed heavy weapon - PM_SetAnim(pm,SETANIM_TORSO,BOTH_ATTACK3,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + default: // 2-handed heavy weapon + PM_SetAnim(pm, SETANIM_TORSO, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); break; } } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { amount = weaponData[pm->ps->weapon].altEnergyPerShot; - } - else - { + } else { amount = weaponData[pm->ps->weapon].energyPerShot; } - if ( (pm->ps->weaponstate == WEAPON_CHARGING) || (pm->ps->weaponstate == WEAPON_CHARGING_ALT) ) - { + if ((pm->ps->weaponstate == WEAPON_CHARGING) || (pm->ps->weaponstate == WEAPON_CHARGING_ALT)) { // charging weapons may want to do their own ammo logic. - trueCount = PM_DoChargingAmmoUsage( &amount ); + trueCount = PM_DoChargingAmmoUsage(&amount); } pm->ps->weaponstate = WEAPON_FIRING; // take an ammo away if not infinite - if ( pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { // enough energy to fire this weapon? - if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) - { + if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) { pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] -= amount; - } - else // Not enough energy + } else // Not enough energy { - if ( !( pm->ps->eFlags & EF_LOCKED_TO_WEAPON )) - { + if (!(pm->ps->eFlags & EF_LOCKED_TO_WEAPON)) { // Switch weapons - PM_AddEvent( EV_NOAMMO ); + PM_AddEvent(EV_NOAMMO); pm->ps->weaponTime += 500; } return; } } - if ( pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0 ) - {//FIXME: this is going to fire off one frame before you expect, actually + if (pm->gent && pm->gent->client && pm->gent->client->fireDelay > 0) { // FIXME: this is going to fire off one frame before you expect, actually // Clear these out since we're not actually firing yet pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; return; } - if ( pm->ps->weapon == WP_MELEE ) - { - PM_AddEvent( EV_FIRE_WEAPON ); + if (pm->ps->weapon == WP_MELEE) { + PM_AddEvent(EV_FIRE_WEAPON); addTime = pm->ps->torsoAnimTimer; - } - else if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - PM_AddEvent( EV_ALT_FIRE ); + } else if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + PM_AddEvent(EV_ALT_FIRE); addTime = weaponData[pm->ps->weapon].altFireTime; - } - else - { - if ( pm->ps->clientNum //NPC - && !PM_ControlledByPlayer() //not under player control - && pm->ps->weapon == WP_THERMAL //using thermals - && pm->ps->torsoAnim != BOTH_ATTACK10 )//not in the throw anim - {//oops, got knocked out of the anim, don't throw the thermal + } else { + if (pm->ps->clientNum // NPC + && !PM_ControlledByPlayer() // not under player control + && pm->ps->weapon == WP_THERMAL // using thermals + && pm->ps->torsoAnim != BOTH_ATTACK10) // not in the throw anim + { // oops, got knocked out of the anim, don't throw the thermal return; } - PM_AddEvent( EV_FIRE_WEAPON ); + PM_AddEvent(EV_FIRE_WEAPON); addTime = weaponData[pm->ps->weapon].fireTime; - switch( pm->ps->weapon) - { + switch (pm->ps->weapon) { case WP_REPEATER: // repeater is supposed to do smoke after sustained bursts pm->ps->weaponShotCount++; break; case WP_BOWCASTER: - addTime *= (( trueCount < 3 ) ? 0.35f : 1.0f );// if you only did a small charge shot with the bowcaster, use less time between shots + addTime *= ((trueCount < 3) ? 0.35f : 1.0f); // if you only did a small charge shot with the bowcaster, use less time between shots break; } } - - if(pm->gent && pm->gent->NPC != NULL ) - {//NPCs have their own refire logic + if (pm->gent && pm->gent->NPC != NULL) { // NPCs have their own refire logic // eez: Unless they're controlled by the player! - if(!PM_ControlledByPlayer()) + if (!PM_ControlledByPlayer()) return; } - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - {//Special test for Matrix Mode (tm) - if ( pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive&(1<value < 1.0f) { + if (!MatrixMode) { // Special test for Matrix Mode (tm) + if (pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive & (1 << FP_SPEED)) { // player always fires at normal speed addTime *= g_timescale->value; - } - else if ( g_entities[pm->ps->clientNum].client - && pm->ps->forcePowersActive&(1<ps->clientNum].client && pm->ps->forcePowersActive & (1 << FP_SPEED)) { addTime *= g_timescale->value; } } @@ -8345,78 +6784,70 @@ static void PM_Weapon( void ) } pm->ps->weaponTime += addTime; - pm->ps->lastShotTime = level.time;//so we know when the last time we fired our gun is + pm->ps->lastShotTime = level.time; // so we know when the last time we fired our gun is // HACK!!!!! - if ( pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0 ) - { - if ( pm->ps->weapon == WP_THERMAL || pm->ps->weapon == WP_TRIP_MINE ) - { + if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] <= 0) { + if (pm->ps->weapon == WP_THERMAL || pm->ps->weapon == WP_TRIP_MINE) { // because these weapons have the ammo attached to the hand, we should switch weapons when the last one is thrown, otherwise it will look silly // NOTE: could also switch to an empty had version, but was told we aren't getting any new models at this point CG_OutOfAmmoChange(); - PM_SetAnim(pm,SETANIM_TORSO,TORSO_DROPWEAP1 + 2,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); // hack weapon down! + PM_SetAnim(pm, SETANIM_TORSO, TORSO_DROPWEAP1 + 2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // hack weapon down! pm->ps->weaponTime = 50; } } } - /* ================ PM_Inventory ================ */ -static void PM_Inventory(void) -{ +static void PM_Inventory(void) { // check for item using -/* - if ( pm->cmd.buttons & BUTTON_USE_FORCEPOWER ) - { - if ( ! ( pm->ps->pm_flags & BUTTON_USE_FORCEPOWER ) ) + /* + if ( pm->cmd.buttons & BUTTON_USE_FORCEPOWER ) { - pm->ps->pm_flags |= BUTTON_USE_FORCEPOWER; - PM_AddEvent( EV_USE_FORCEPOWER); - return; + if ( ! ( pm->ps->pm_flags & BUTTON_USE_FORCEPOWER ) ) + { + pm->ps->pm_flags |= BUTTON_USE_FORCEPOWER; + PM_AddEvent( EV_USE_FORCEPOWER); + return; + } } - } - else - { - pm->ps->pm_flags &= ~PMF_USE_ITEM_HELD; - } -*/ + else + { + pm->ps->pm_flags &= ~PMF_USE_ITEM_HELD; + } + */ } -extern void ForceThrow( gentity_t *self, qboolean pull ); -extern void ForceHeal( gentity_t *self ); -extern void ForceTelepathy( gentity_t *self ); -void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( !ent ) - { +extern void ForceThrow(gentity_t *self, qboolean pull); +extern void ForceHeal(gentity_t *self); +extern void ForceTelepathy(gentity_t *self); +void PM_CheckForceUseButton(gentity_t *ent, usercmd_t *ucmd) { + if (!ent) { return; } - if ( ucmd->buttons & BUTTON_USE_FORCE ) - { - switch ( showPowers[cg.forcepowerSelect] ) - { + if (ucmd->buttons & BUTTON_USE_FORCE) { + switch (showPowers[cg.forcepowerSelect]) { case FP_HEAL: - ForceHeal( ent ); + ForceHeal(ent); break; case FP_LEVITATION: ucmd->upmove = 127; break; case FP_SPEED: - ForceSpeed( ent ); + ForceSpeed(ent); break; case FP_PUSH: - ForceThrow( ent, qfalse ); + ForceThrow(ent, qfalse); break; case FP_PULL: - ForceThrow( ent, qtrue ); + ForceThrow(ent, qtrue); break; case FP_TELEPATHY: - ForceTelepathy( ent ); + ForceTelepathy(ent); break; case FP_GRIP: ucmd->buttons |= BUTTON_FORCEGRIP; @@ -8433,20 +6864,15 @@ void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ) PM_ForcePower ================ */ -static void PM_ForcePower(void) -{ +static void PM_ForcePower(void) { // check for item using - if ( pm->cmd.buttons & BUTTON_USE_FORCE ) - { - if ( ! ( pm->ps->pm_flags & PMF_USE_FORCE ) ) - { + if (pm->cmd.buttons & BUTTON_USE_FORCE) { + if (!(pm->ps->pm_flags & PMF_USE_FORCE)) { pm->ps->pm_flags |= PMF_USE_FORCE; - PM_AddEvent( EV_USE_FORCE); + PM_AddEvent(EV_USE_FORCE); return; } - } - else - { + } else { pm->ps->pm_flags &= ~PMF_USE_FORCE; } } @@ -8456,186 +6882,140 @@ static void PM_ForcePower(void) PM_DropTimers ================ */ -static void PM_DropTimers( void ) -{ +static void PM_DropTimers(void) { // drop misc timing counter - if ( pm->ps->pm_time ) - { - if ( pml.msec >= pm->ps->pm_time ) - { + if (pm->ps->pm_time) { + if (pml.msec >= pm->ps->pm_time) { pm->ps->pm_flags &= ~PMF_ALL_TIMES; pm->ps->pm_time = 0; - } - else - { + } else { pm->ps->pm_time -= pml.msec; } } // drop legs animation counter - if ( pm->ps->legsAnimTimer > 0 ) - { + if (pm->ps->legsAnimTimer > 0) { int newTime = pm->ps->legsAnimTimer - pml.msec; - if ( newTime < 0 ) - { + if (newTime < 0) { newTime = 0; } - PM_SetLegsAnimTimer( pm->gent, &pm->ps->legsAnimTimer, newTime ); + PM_SetLegsAnimTimer(pm->gent, &pm->ps->legsAnimTimer, newTime); } // drop torso animation counter - if ( pm->ps->torsoAnimTimer > 0 ) - { + if (pm->ps->torsoAnimTimer > 0) { int newTime = pm->ps->torsoAnimTimer - pml.msec; - if ( newTime < 0 ) - { + if (newTime < 0) { newTime = 0; } - PM_SetTorsoAnimTimer( pm->gent, &pm->ps->torsoAnimTimer, newTime ); + PM_SetTorsoAnimTimer(pm->gent, &pm->ps->torsoAnimTimer, newTime); } } -void PM_SetSpecialMoveValues (void ) -{ +void PM_SetSpecialMoveValues(void) { Flying = 0; - if ( pm->gent ) - { - if ( pm->gent->NPC ) - { - if ( pm->gent->NPC->stats.moveType == MT_FLYSWIM ) - { + if (pm->gent) { + if (pm->gent->NPC) { + if (pm->gent->NPC->stats.moveType == MT_FLYSWIM) { Flying = FLY_NORMAL; } - } - else if ( pm->ps->vehicleModel != 0 ) - { + } else if (pm->ps->vehicleModel != 0) { Flying = FLY_VEHICLE; } } - if ( g_timescale != NULL ) - { - if ( g_timescale->value < 1.0f ) - { - if ( !MatrixMode ) - { - if ( pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive&(1<value); - } - else if ( g_entities[pm->ps->clientNum].client - && pm->ps->forcePowersActive&(1<value); + if (g_timescale != NULL) { + if (g_timescale->value < 1.0f) { + if (!MatrixMode) { + if (pm->ps->clientNum == 0 && !player_locked && pm->ps->forcePowersActive & (1 << FP_SPEED)) { + pml.frametime *= (1.0f / g_timescale->value); + } else if (g_entities[pm->ps->clientNum].client && pm->ps->forcePowersActive & (1 << FP_SPEED)) { + pml.frametime *= (1.0f / g_timescale->value); } } } } } -extern float cg_zoomFov; //from cg_view.cpp +extern float cg_zoomFov; // from cg_view.cpp //------------------------------------------- -void PM_AdjustAttackStates( pmove_t *pm ) +void PM_AdjustAttackStates(pmove_t *pm) //------------------------------------------- { int amount; // get ammo usage - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; - } - else - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - weaponData[pm->ps->weapon].energyPerShot; + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; + } else { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].energyPerShot; } - if ( pm->ps->weapon == WP_SABER && (!cg.zoomMode||pm->ps->clientNum) ) - {//don't let the alt-attack be interpreted as an actual attack command - //saber alt-attack does a normal swing, too + if (pm->ps->weapon == WP_SABER && (!cg.zoomMode || pm->ps->clientNum)) { // don't let the alt-attack be interpreted as an actual attack command + // saber alt-attack does a normal swing, too pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; - if ( pm->ps->saberInFlight ) - {//saber not in hand, can't swing it + if (pm->ps->saberInFlight) { // saber not in hand, can't swing it pm->cmd.buttons &= ~BUTTON_ATTACK; } } // disruptor alt-fire should toggle the zoom mode, but only bother doing this for the player? - if ( pm->ps->weapon == WP_DISRUPTOR && pm->gent && pm->gent->s.number == 0 && pm->ps->weaponstate != WEAPON_DROPPING ) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->gent && pm->gent->s.number == 0 && pm->ps->weaponstate != WEAPON_DROPPING) { // we are not alt-firing yet, but the alt-attack button was just pressed and // we either are ducking ( in which case we don't care if they are moving )...or they are not ducking...and also not moving right/forward. - if ( !(pm->ps->eFlags & EF_ALT_FIRING) && (pm->cmd.buttons & BUTTON_ALT_ATTACK) - && ( pm->cmd.upmove < 0 || ( !pm->cmd.forwardmove && !pm->cmd.rightmove ))) - { + if (!(pm->ps->eFlags & EF_ALT_FIRING) && (pm->cmd.buttons & BUTTON_ALT_ATTACK) && + (pm->cmd.upmove < 0 || (!pm->cmd.forwardmove && !pm->cmd.rightmove))) { // We just pressed the alt-fire key - if ( cg.zoomMode == 0 || cg.zoomMode == 3 ) - { - G_SoundOnEnt( pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomstart.wav" ); + if (cg.zoomMode == 0 || cg.zoomMode == 3) { + G_SoundOnEnt(pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomstart.wav"); // not already zooming, so do it now cg.zoomMode = 2; cg.zoomLocked = qfalse; - cg_zoomFov = 80.0f;//(cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; - } - else if ( cg.zoomMode == 2 ) - { - G_SoundOnEnt( pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomend.wav" ); + cg_zoomFov = 80.0f; //(cg.overrides.active&CG_OVERRIDE_FOV) ? cg.overrides.fov : cg_fov.value; + } else if (cg.zoomMode == 2) { + G_SoundOnEnt(pm->gent, CHAN_AUTO, "sound/weapons/disruptor/zoomend.wav"); // already zooming, so must be wanting to turn it off cg.zoomMode = 0; cg.zoomTime = cg.time; cg.zoomLocked = qfalse; } - } - else if ( !(pm->cmd.buttons & BUTTON_ALT_ATTACK )) - { + } else if (!(pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // Not pressing zoom any more - if ( cg.zoomMode == 2 ) - { + if (cg.zoomMode == 2) { // were zooming in, so now lock the zoom cg.zoomLocked = qtrue; } } - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { // If we are zoomed, we should switch the ammo usage to the alt-fire, otherwise, we'll // just use whatever ammo was selected from above - if ( cg.zoomMode == 2 ) - { - amount = pm->ps->ammo[weaponData[ pm->ps->weapon ].ammoIndex] - - weaponData[pm->ps->weapon].altEnergyPerShot; + if (cg.zoomMode == 2) { + amount = pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - weaponData[pm->ps->weapon].altEnergyPerShot; } - } - else - { + } else { // alt-fire button pressing doesn't use any ammo amount = 0; } - } // Check for binocular specific mode - if ( cg.zoomMode == 1 && pm->gent && pm->gent->s.number == 0 ) // + if (cg.zoomMode == 1 && pm->gent && pm->gent->s.number == 0) // { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->ps->batteryCharge ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->ps->batteryCharge) { // zooming out cg.zoomLocked = qfalse; cg.zoomDir = 1; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK && pm->ps->batteryCharge ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK && pm->ps->batteryCharge) { // zooming in cg.zoomLocked = qfalse; cg.zoomDir = -1; - } - else - { + } else { // if no buttons are down, we should be in a locked state cg.zoomLocked = qtrue; } @@ -8643,35 +7023,27 @@ void PM_AdjustAttackStates( pmove_t *pm ) // kill buttons and associated firing flags so we can't fire pm->ps->eFlags &= ~EF_FIRING; pm->ps->eFlags &= ~EF_ALT_FIRING; - pm->cmd.buttons &= ~(BUTTON_ALT_ATTACK|BUTTON_ATTACK); + pm->cmd.buttons &= ~(BUTTON_ALT_ATTACK | BUTTON_ATTACK); } // set the firing flag for continuous beam weapons, phaser will fire even if out of ammo - if ( (( pm->cmd.buttons & BUTTON_ATTACK || pm->cmd.buttons & BUTTON_ALT_ATTACK ) && ( amount >= 0 || pm->ps->weapon == WP_SABER )) ) - { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (((pm->cmd.buttons & BUTTON_ATTACK || pm->cmd.buttons & BUTTON_ALT_ATTACK) && (amount >= 0 || pm->ps->weapon == WP_SABER))) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { pm->ps->eFlags |= EF_ALT_FIRING; - if ( !pm->ps->clientNum && pm->gent && (pm->ps->eFlags&EF_IN_ATST) ) - {//switch ATST barrels + if (!pm->ps->clientNum && pm->gent && (pm->ps->eFlags & EF_IN_ATST)) { // switch ATST barrels pm->gent->alt_fire = qtrue; } - } - else - { + } else { pm->ps->eFlags &= ~EF_ALT_FIRING; - if ( !pm->ps->clientNum && pm->gent && (pm->ps->eFlags&EF_IN_ATST) ) - {//switch ATST barrels + if (!pm->ps->clientNum && pm->gent && (pm->ps->eFlags & EF_IN_ATST)) { // switch ATST barrels pm->gent->alt_fire = qfalse; } } // This flag should always get set, even when alt-firing pm->ps->eFlags |= EF_FIRING; - } - else - { -// int iFlags = pm->ps->eFlags; + } else { + // int iFlags = pm->ps->eFlags; // Clear 'em out pm->ps->eFlags &= ~EF_FIRING; @@ -8681,25 +7053,21 @@ void PM_AdjustAttackStates( pmove_t *pm ) // the stronger FFFX so you can hardly feel them. However, if you only do iton these flags then the // repeat-fire weapons like tetrion and dreadnought don't switch off quick enough. So... // -/* // Might need this for beam type weapons - if ( pm->ps->weapon == WP_DREADNOUGHT || (iFlags & (EF_FIRING|EF_ALT_FIRING) ) - { - cgi_FF_StopAllFX(); - } - */ + /* // Might need this for beam type weapons + if ( pm->ps->weapon == WP_DREADNOUGHT || (iFlags & (EF_FIRING|EF_ALT_FIRING) ) + { + cgi_FF_StopAllFX(); + } + */ } // disruptor should convert a main fire to an alt-fire if the gun is currently zoomed - if ( pm->ps->weapon == WP_DISRUPTOR && pm->gent && pm->gent->s.number == 0 ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK && cg.zoomMode == 2 ) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->gent && pm->gent->s.number == 0) { + if (pm->cmd.buttons & BUTTON_ATTACK && cg.zoomMode == 2) { // converting the main fire to an alt-fire pm->cmd.buttons |= BUTTON_ALT_ATTACK; pm->ps->eFlags |= EF_ALT_FIRING; - } - else - { + } else { // don't let an alt-fire through pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } @@ -8713,8 +7081,7 @@ Pmove Can be called by either the server or the client ================ */ -void Pmove( pmove_t *pmove ) -{ +void Pmove(pmove_t *pmove) { pm = pmove; // this counter lets us debug movement problems with a journal by setting a conditional breakpoint fot the previous frame @@ -8726,108 +7093,102 @@ void Pmove( pmove_t *pmove ) pm->waterlevel = 0; // Clear the blocked flag - //pm->ps->pm_flags &= ~PMF_BLOCKED; - //pm->ps->pm_flags &= ~PMF_BUMPED; + // pm->ps->pm_flags &= ~PMF_BLOCKED; + // pm->ps->pm_flags &= ~PMF_BUMPED; // In certain situations, we may want to control which attack buttons are pressed and what kind of functionality // is attached to them - PM_AdjustAttackStates( pm ); + PM_AdjustAttackStates(pm); // clear the respawned flag if attack and use are cleared - if ( pm->ps->stats[STAT_HEALTH] > 0 && - !( pm->cmd.buttons & BUTTON_ATTACK ) ) - { + if (pm->ps->stats[STAT_HEALTH] > 0 && !(pm->cmd.buttons & BUTTON_ATTACK)) { pm->ps->pm_flags &= ~PMF_RESPAWNED; } // clear all pmove local vars - memset (&pml, 0, sizeof(pml)); + memset(&pml, 0, sizeof(pml)); // determine the time pml.msec = pmove->cmd.serverTime - pm->ps->commandTime; - if ( pml.msec < 1 ) { + if (pml.msec < 1) { pml.msec = 1; - } else if ( pml.msec > 200 ) { + } else if (pml.msec > 200) { pml.msec = 200; } pm->ps->commandTime = pmove->cmd.serverTime; // save old org in case we get stuck - VectorCopy (pm->ps->origin, pml.previous_origin); + VectorCopy(pm->ps->origin, pml.previous_origin); // save old velocity for crashlanding - VectorCopy (pm->ps->velocity, pml.previous_velocity); + VectorCopy(pm->ps->velocity, pml.previous_velocity); pml.frametime = pml.msec * 0.001; PM_SetSpecialMoveValues(); // update the viewangles - PM_UpdateViewAngles( pm->ps, &pm->cmd, pm->gent); + PM_UpdateViewAngles(pm->ps, &pm->cmd, pm->gent); - AngleVectors ( pm->ps->viewangles, pml.forward, pml.right, pml.up ); + AngleVectors(pm->ps->viewangles, pml.forward, pml.right, pml.up); - if ( pm->cmd.upmove < 10 ) { + if (pm->cmd.upmove < 10) { // not holding jump pm->ps->pm_flags &= ~PMF_JUMP_HELD; } // decide if backpedaling animations should be used - if ( pm->cmd.forwardmove < 0 ) { + if (pm->cmd.forwardmove < 0) { pm->ps->pm_flags |= PMF_BACKWARDS_RUN; - } else if ( pm->cmd.forwardmove > 0 || ( pm->cmd.forwardmove == 0 && pm->cmd.rightmove ) ) { + } else if (pm->cmd.forwardmove > 0 || (pm->cmd.forwardmove == 0 && pm->cmd.rightmove)) { pm->ps->pm_flags &= ~PMF_BACKWARDS_RUN; } - if ( pm->ps->pm_type >= PM_DEAD ) { + if (pm->ps->pm_type >= PM_DEAD) { pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; pm->cmd.upmove = 0; - if ( pm->ps->viewheight > -12 ) - {//slowly sink view to ground + if (pm->ps->viewheight > -12) { // slowly sink view to ground pm->ps->viewheight -= 1; } } - if ( pm->ps->pm_type == PM_SPECTATOR ) { - PM_CheckDuck (); - PM_FlyMove (); - PM_DropTimers (); + if (pm->ps->pm_type == PM_SPECTATOR) { + PM_CheckDuck(); + PM_FlyMove(); + PM_DropTimers(); return; } - if ( pm->ps->pm_type == PM_NOCLIP ) { - PM_NoclipMove (); - PM_DropTimers (); + if (pm->ps->pm_type == PM_NOCLIP) { + PM_NoclipMove(); + PM_DropTimers(); return; } if (pm->ps->pm_type == PM_FREEZE) { - return; // no movement at all + return; // no movement at all } - if ( pm->ps->pm_type == PM_INTERMISSION ) { - return; // no movement at all + if (pm->ps->pm_type == PM_INTERMISSION) { + return; // no movement at all } - if ( pm->ps->pm_flags & PMF_SLOW_MO_FALL ) - {//half grav + if (pm->ps->pm_flags & PMF_SLOW_MO_FALL) { // half grav pm->ps->gravity *= 0.5; } // set watertype, and waterlevel - PM_SetWaterLevelAtPoint( pm->ps->origin, &pm->waterlevel, &pm->watertype ); + PM_SetWaterLevelAtPoint(pm->ps->origin, &pm->waterlevel, &pm->watertype); PM_SetWaterHeight(); - if ( !(pm->watertype & CONTENTS_LADDER) ) - {//Don't want to remember this for ladders, is only for waterlevel change events (sounds) + if (!(pm->watertype & CONTENTS_LADDER)) { // Don't want to remember this for ladders, is only for waterlevel change events (sounds) pml.previous_waterlevel = pmove->waterlevel; } waterForceJump = qfalse; - if ( pmove->waterlevel && pm->ps->clientNum ) - { - if ( pm->ps->forceJumpZStart//force jumping - ||(pm->gent&&!TIMER_Done(pm->gent, "forceJumpChasing" )) )//force-jumping + if (pmove->waterlevel && pm->ps->clientNum) { + if (pm->ps->forceJumpZStart // force jumping + || (pm->gent && !TIMER_Done(pm->gent, "forceJumpChasing"))) // force-jumping { waterForceJump = qtrue; } @@ -8836,86 +7197,66 @@ void Pmove( pmove_t *pmove ) // set mins, maxs, and viewheight PM_SetBounds(); - if ( !Flying && !(pm->watertype & CONTENTS_LADDER) && pm->ps->pm_type != PM_DEAD ) - {//NOTE: noclippers shouldn't jump or duck either, no? + if (!Flying && !(pm->watertype & CONTENTS_LADDER) && pm->ps->pm_type != PM_DEAD) { // NOTE: noclippers shouldn't jump or duck either, no? PM_CheckDuck(); } // set groundentity PM_GroundTrace(); - if ( pm->ps->pm_type == PM_DEAD ) { - PM_DeadMove (); + if (pm->ps->pm_type == PM_DEAD) { + PM_DeadMove(); } PM_DropTimers(); - if ( pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - {//in an emplaced gun + if (pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { // in an emplaced gun PM_NoclipMove(); - } - else if ( Flying == FLY_NORMAL )//|| pm->ps->gravity <= 0 ) + } else if (Flying == FLY_NORMAL) //|| pm->ps->gravity <= 0 ) { // flight powerup doesn't allow jump and has different friction PM_FlyMove(); - } - else if ( Flying == FLY_VEHICLE ) - { + } else if (Flying == FLY_VEHICLE) { PM_FlyVehicleMove(); - } - else if ( pm->ps->pm_flags & PMF_TIME_WATERJUMP ) - { + } else if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { PM_WaterJumpMove(); - } - else if ( pm->waterlevel > 1 //in water - &&(!pm->ps->clientNum || !waterForceJump) )//player or NPC not force jumping - {//force-jumping NPCs should + } else if (pm->waterlevel > 1 // in water + && (!pm->ps->clientNum || !waterForceJump)) // player or NPC not force jumping + { // force-jumping NPCs should // swimming or in ladder PM_WaterMove(); - } - else if ( pml.walking ) - {// walking on ground - vec3_t oldOrg; + } else if (pml.walking) { // walking on ground + vec3_t oldOrg; - VectorCopy( pm->ps->origin, oldOrg ); + VectorCopy(pm->ps->origin, oldOrg); PM_WalkMove(); - - float threshHold = 0.001f, movedDist = DistanceSquared( oldOrg, pm->ps->origin ); - if ( PM_StandingAnim( pm->ps->legsAnim ) || pm->ps->legsAnim == BOTH_CROUCH1 ) - { + float threshHold = 0.001f, movedDist = DistanceSquared(oldOrg, pm->ps->origin); + if (PM_StandingAnim(pm->ps->legsAnim) || pm->ps->legsAnim == BOTH_CROUCH1) { threshHold = 0.005f; } - if ( movedDist < threshHold ) - {//didn't move, play no legs anim + if (movedDist < threshHold) { // didn't move, play no legs anim pm->cmd.forwardmove = pm->cmd.rightmove = 0; } - } - else - { - if ( pm->ps->gravity <= 0 ) - { + } else { + if (pm->ps->gravity <= 0) { PM_FlyMove(); - } - else - { + } else { // airborne PM_AirMove(); } } - //PM_Animate(); + // PM_Animate(); // If we didn't move at all, then why bother doing this again -MW. - if(!(VectorCompare(pm->ps->origin,pml.previous_origin))) - { + if (!(VectorCompare(pm->ps->origin, pml.previous_origin))) { PM_GroundTrace(); } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on ground + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on ground pm->ps->forceJumpZStart = 0; pm->ps->jumpZStart = 0; pm->ps->pm_flags &= ~PMF_JUMPING; @@ -8925,9 +7266,8 @@ void Pmove( pmove_t *pmove ) // If we didn't move at all, then why bother doing this again -MW. // Note: ok, so long as we don't have water levels that change. - if(!(VectorCompare(pm->ps->origin,pml.previous_origin))) - { - PM_SetWaterLevelAtPoint( pm->ps->origin, &pm->waterlevel, &pm->watertype ); + if (!(VectorCompare(pm->ps->origin, pml.previous_origin))) { + PM_SetWaterLevelAtPoint(pm->ps->origin, &pm->waterlevel, &pm->watertype); PM_SetWaterHeight(); } @@ -8937,35 +7277,27 @@ void Pmove( pmove_t *pmove ) // weapons PM_Weapon(); - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { pm->ps->pm_flags |= PMF_ATTACK_HELD; - } - else - { + } else { pm->ps->pm_flags &= ~PMF_ATTACK_HELD; } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { pm->ps->pm_flags |= PMF_ALT_ATTACK_HELD; - } - else - { + } else { pm->ps->pm_flags &= ~PMF_ALT_ATTACK_HELD; } - if ( pm->gent )//&& pm->gent->s.number == 0 )//player only? + if (pm->gent) //&& pm->gent->s.number == 0 )//player only? { // Use PM_Use(); } // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP - if ( pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON ) - { - PM_SetAnim(pm,SETANIM_BOTH,BOTH_GUNSIT1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD);//SETANIM_FLAG_NORMAL - } - else // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP + if (pm->gent && pm->ps && pm->ps->eFlags & EF_LOCKED_TO_WEAPON) { + PM_SetAnim(pm, SETANIM_BOTH, BOTH_GUNSIT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // SETANIM_FLAG_NORMAL + } else // TEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMPTEMP { // footstep events / legs animations PM_Footsteps(); @@ -8979,16 +7311,13 @@ void Pmove( pmove_t *pmove ) // snap some parts of playerstate to save network bandwidth // SnapVector( pm->ps->velocity ); - if ( !pm->cmd.rightmove && !pm->cmd.forwardmove && pm->cmd.upmove <= 0 ) - { - if ( VectorCompare( pm->ps->velocity, vec3_origin ) ) - { + if (!pm->cmd.rightmove && !pm->cmd.forwardmove && pm->cmd.upmove <= 0) { + if (VectorCompare(pm->ps->velocity, vec3_origin)) { pm->ps->lastStationary = level.time; } } - if ( pm->ps->pm_flags & PMF_SLOW_MO_FALL ) - {//half grav + if (pm->ps->pm_flags & PMF_SLOW_MO_FALL) { // half grav pm->ps->gravity *= 2; } } \ No newline at end of file diff --git a/codeJK2/game/bg_slidemove.cpp b/codeJK2/game/bg_slidemove.cpp index ef2a4d240d..6706a1422c 100644 --- a/codeJK2/game/bg_slidemove.cpp +++ b/codeJK2/game/bg_slidemove.cpp @@ -26,7 +26,7 @@ along with this program; if not, see . #include "bg_public.h" #include "bg_local.h" -extern qboolean PM_ClientImpact( int otherEntityNum, qboolean damageSelf ); +extern qboolean PM_ClientImpact(int otherEntityNum, qboolean damageSelf); /* input: origin, velocity, bounds, groundPlane, trace function @@ -42,44 +42,39 @@ PM_SlideMove Returns qtrue if the velocity was clipped in some way ================== */ -#define MAX_CLIP_PLANES 5 -extern qboolean PM_GroundSlideOkay( float zNormal ); -qboolean PM_SlideMove( float gravMod ) { - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t normal, planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity; - vec3_t clipVelocity; - int i, j, k; - trace_t trace; - vec3_t end; - float time_left; - float into; - vec3_t endVelocity; - vec3_t endClipVelocity; - qboolean damageSelf = qtrue; +#define MAX_CLIP_PLANES 5 +extern qboolean PM_GroundSlideOkay(float zNormal); +qboolean PM_SlideMove(float gravMod) { + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t normal, planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity; + vec3_t clipVelocity; + int i, j, k; + trace_t trace; + vec3_t end; + float time_left; + float into; + vec3_t endVelocity; + vec3_t endClipVelocity; + qboolean damageSelf = qtrue; numbumps = 4; - VectorCopy (pm->ps->velocity, primal_velocity); - VectorCopy( pm->ps->velocity, endVelocity ); + VectorCopy(pm->ps->velocity, primal_velocity); + VectorCopy(pm->ps->velocity, endVelocity); - if ( gravMod ) - { - if ( !(pm->ps->eFlags&EF_FORCE_GRIPPED) ) - { + if (gravMod) { + if (!(pm->ps->eFlags & EF_FORCE_GRIPPED)) { endVelocity[2] -= pm->ps->gravity * pml.frametime * gravMod; } - pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5; + pm->ps->velocity[2] = (pm->ps->velocity[2] + endVelocity[2]) * 0.5; primal_velocity[2] = endVelocity[2]; - if ( pml.groundPlane ) - { - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - {// slide along the ground plane - PM_ClipVelocity( pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { // slide along the ground plane + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } } @@ -87,103 +82,89 @@ qboolean PM_SlideMove( float gravMod ) { time_left = pml.frametime; // never turn against the ground plane - if ( pml.groundPlane ) - { + if (pml.groundPlane) { numplanes = 1; - VectorCopy( pml.groundTrace.plane.normal, planes[0] ); - if ( !PM_GroundSlideOkay( planes[0][2] ) ) - { + VectorCopy(pml.groundTrace.plane.normal, planes[0]); + if (!PM_GroundSlideOkay(planes[0][2])) { planes[0][2] = 0; - VectorNormalize( planes[0] ); + VectorNormalize(planes[0]); } - } - else - { + } else { numplanes = 0; } // never turn against original velocity - VectorNormalize2( pm->ps->velocity, planes[numplanes] ); + VectorNormalize2(pm->ps->velocity, planes[numplanes]); numplanes++; - for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) { + for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { // calculate position we are trying to move to - VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end ); + VectorMA(pm->ps->origin, time_left, pm->ps->velocity, end); // see if we can make it there - pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); - if ( trace.allsolid ) - {// entity is completely trapped in another solid - pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration + if (trace.allsolid) { // entity is completely trapped in another solid + pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration return qtrue; } - if ( trace.fraction > 0 ) - {// actually covered some distance - VectorCopy( trace.endpos, pm->ps->origin ); + if (trace.fraction > 0) { // actually covered some distance + VectorCopy(trace.endpos, pm->ps->origin); } - if ( trace.fraction == 1 ) - { - break; // moved the entire distance + if (trace.fraction == 1) { + break; // moved the entire distance } - //pm->ps->pm_flags |= PMF_BUMPED; + // pm->ps->pm_flags |= PMF_BUMPED; // save entity for contact - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); - //Hit it - if ( trace.surfaceFlags&SURF_NODAMAGE ) - { + // Hit it + if (trace.surfaceFlags & SURF_NODAMAGE) { damageSelf = qfalse; - } - else if ( trace.entityNum == ENTITYNUM_WORLD && trace.plane.normal[2] > 0.5f ) - {//if we land on the ground, let falling damage do it's thing itself, otherwise do impact damage + } else if (trace.entityNum == ENTITYNUM_WORLD && + trace.plane.normal[2] > 0.5f) { // if we land on the ground, let falling damage do it's thing itself, otherwise do impact damage damageSelf = qfalse; - } - else - { + } else { damageSelf = qtrue; } - if ( PM_ClientImpact( trace.entityNum, damageSelf ) ) - { + if (PM_ClientImpact(trace.entityNum, damageSelf)) { continue; } time_left -= time_left * trace.fraction; - if ( numplanes >= MAX_CLIP_PLANES ) - {// this shouldn't really happen - VectorClear( pm->ps->velocity ); + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen + VectorClear(pm->ps->velocity); return qtrue; } - VectorCopy( trace.plane.normal, normal ); - if ( !PM_GroundSlideOkay( normal[2] ) ) - {//wall-running - //never push up off a sloped wall + VectorCopy(trace.plane.normal, normal); + if (!PM_GroundSlideOkay(normal[2])) { // wall-running + // never push up off a sloped wall normal[2] = 0; - VectorNormalize( normal ); + VectorNormalize(normal); } // // if this is the same plane we hit before, nudge velocity // out along it, which fixes some epsilon issues with // non-axial planes // - for ( i = 0 ; i < numplanes ; i++ ) { - if ( DotProduct( normal, planes[i] ) > 0.99 ) { - VectorAdd( normal, pm->ps->velocity, pm->ps->velocity ); + for (i = 0; i < numplanes; i++) { + if (DotProduct(normal, planes[i]) > 0.99) { + VectorAdd(normal, pm->ps->velocity, pm->ps->velocity); break; } } - if ( i < numplanes ) { + if (i < numplanes) { continue; } - VectorCopy( normal, planes[numplanes] ); + VectorCopy(normal, planes[numplanes]); numplanes++; // @@ -191,84 +172,84 @@ qboolean PM_SlideMove( float gravMod ) { // // find a plane that it enters - for ( i = 0 ; i < numplanes ; i++ ) { - into = DotProduct( pm->ps->velocity, planes[i] ); - if ( into >= 0.1 ) { - continue; // move doesn't interact with the plane + for (i = 0; i < numplanes; i++) { + into = DotProduct(pm->ps->velocity, planes[i]); + if (into >= 0.1) { + continue; // move doesn't interact with the plane } // see how hard we are hitting things - if ( -into > pml.impactSpeed ) { + if (-into > pml.impactSpeed) { pml.impactSpeed = -into; } // slide along the plane - PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, planes[i], clipVelocity, OVERCLIP); // slide along the plane - PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(endVelocity, planes[i], endClipVelocity, OVERCLIP); // see if there is a second plane that the new move enters - for ( j = 0 ; j < numplanes ; j++ ) { - if ( j == i ) { + for (j = 0; j < numplanes; j++) { + if (j == i) { continue; } - if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[j]) >= 0.1) { + continue; // move doesn't interact with the plane } // try clipping the move to the plane - PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP ); - PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(clipVelocity, planes[j], clipVelocity, OVERCLIP); + PM_ClipVelocity(endClipVelocity, planes[j], endClipVelocity, OVERCLIP); // see if it goes back into the first clip plane - if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) { + if (DotProduct(clipVelocity, planes[i]) >= 0) { continue; } // slide the original velocity along the crease - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, pm->ps->velocity ); - VectorScale( dir, d, clipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, pm->ps->velocity); + VectorScale(dir, d, clipVelocity); - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, endVelocity ); - VectorScale( dir, d, endClipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, endVelocity); + VectorScale(dir, d, endClipVelocity); // see if there is a third plane the the new move enters - for ( k = 0 ; k < numplanes ; k++ ) { - if ( k == i || k == j ) { + for (k = 0; k < numplanes; k++) { + if (k == i || k == j) { continue; } - if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[k]) >= 0.1) { + continue; // move doesn't interact with the plane } // stop dead at a triple plane interaction - VectorClear( pm->ps->velocity ); + VectorClear(pm->ps->velocity); return qtrue; } } // if we have fixed all interactions, try another move - VectorCopy( clipVelocity, pm->ps->velocity ); - VectorCopy( endClipVelocity, endVelocity ); + VectorCopy(clipVelocity, pm->ps->velocity); + VectorCopy(endClipVelocity, endVelocity); break; } } - if ( gravMod ) { - VectorCopy( endVelocity, pm->ps->velocity ); + if (gravMod) { + VectorCopy(endVelocity, pm->ps->velocity); } // don't change velocity if in a timer (FIXME: is this correct?) - if ( pm->ps->pm_time ) { - VectorCopy( primal_velocity, pm->ps->velocity ); + if (pm->ps->pm_time) { + VectorCopy(primal_velocity, pm->ps->velocity); } - return (qboolean)( bumpcount != 0 ); + return (qboolean)(bumpcount != 0); } /* @@ -277,103 +258,88 @@ PM_StepSlideMove ================== */ -void PM_StepSlideMove( float gravMod ) -{ - vec3_t start_o, start_v; - vec3_t down_o, down_v; - vec3_t slideMove, stepUpMove; - trace_t trace; - vec3_t up, down; - qboolean /*cantStepUpFwd, */isATST = qfalse;; - int stepSize = STEPSIZE; - - VectorCopy (pm->ps->origin, start_o); - VectorCopy (pm->ps->velocity, start_v); - - if ( PM_SlideMove( gravMod ) == 0 ) { - return; // we got exactly where we wanted to go first try - }//else Bumped into something, see if we can step over it - - if ( pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) - { +void PM_StepSlideMove(float gravMod) { + vec3_t start_o, start_v; + vec3_t down_o, down_v; + vec3_t slideMove, stepUpMove; + trace_t trace; + vec3_t up, down; + qboolean /*cantStepUpFwd, */ isATST = qfalse; + ; + int stepSize = STEPSIZE; + + VectorCopy(pm->ps->origin, start_o); + VectorCopy(pm->ps->velocity, start_v); + + if (PM_SlideMove(gravMod) == 0) { + return; // we got exactly where we wanted to go first try + } // else Bumped into something, see if we can step over it + + if (pm->gent && pm->gent->client && pm->gent->client->NPC_class == CLASS_ATST) { isATST = qtrue; - stepSize = 66;//hack for AT-ST stepping, slightly taller than a standing stormtrooper - } - else if ( pm->maxs[2] <= 0 ) - {//short little guys can't go up steps... FIXME: just make this a flag for certain NPCs- especially ones that roll? + stepSize = 66; // hack for AT-ST stepping, slightly taller than a standing stormtrooper + } else if (pm->maxs[2] <= 0) { // short little guys can't go up steps... FIXME: just make this a flag for certain NPCs- especially ones that roll? stepSize = 4; } - //Q3Final addition... + // Q3Final addition... VectorCopy(start_o, down); down[2] -= stepSize; - pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + pm->trace(&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); VectorSet(up, 0, 0, 1); // never step up when you still have up velocity - if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || - DotProduct(trace.plane.normal, up) < 0.7)) { + if (pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || DotProduct(trace.plane.normal, up) < 0.7)) { return; } - if ( !pm->ps->velocity[0] && !pm->ps->velocity[1] ) - {//All our velocity was cancelled sliding + if (!pm->ps->velocity[0] && !pm->ps->velocity[1]) { // All our velocity was cancelled sliding return; } - VectorCopy (pm->ps->origin, down_o); - VectorCopy (pm->ps->velocity, down_v); + VectorCopy(pm->ps->origin, down_o); + VectorCopy(pm->ps->velocity, down_v); - VectorCopy (start_o, up); + VectorCopy(start_o, up); up[2] += stepSize; // test the player position if they were a stepheight higher - pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); - if ( trace.allsolid || trace.startsolid || trace.fraction == 0) { - if ( pm->debugLevel ) { + pm->trace(&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid || trace.fraction == 0) { + if (pm->debugLevel) { Com_Printf("%i:bend can't step\n", c_pmove); } - return; // can't step up + return; // can't step up } // try slidemove from this position - VectorCopy (trace.endpos, pm->ps->origin); - VectorCopy (start_v, pm->ps->velocity); + VectorCopy(trace.endpos, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); - /*cantStepUpFwd = */PM_SlideMove( gravMod ); + /*cantStepUpFwd = */ PM_SlideMove(gravMod); - //compare the initial slidemove and this slidemove from a step up position - VectorSubtract( down_o, start_o, slideMove ); - VectorSubtract( trace.endpos, pm->ps->origin, stepUpMove ); + // compare the initial slidemove and this slidemove from a step up position + VectorSubtract(down_o, start_o, slideMove); + VectorSubtract(trace.endpos, pm->ps->origin, stepUpMove); - if ( fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared( slideMove ) > VectorLengthSquared( stepUpMove ) ) - { - //slideMove was better, use it - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); - } - else - { + if (fabs(stepUpMove[0]) < 0.1 && fabs(stepUpMove[1]) < 0.1 && VectorLengthSquared(slideMove) > VectorLengthSquared(stepUpMove)) { + // slideMove was better, use it + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); + } else { // push down the final amount - VectorCopy (pm->ps->origin, down); + VectorCopy(pm->ps->origin, down); down[2] -= stepSize; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); - if ( !trace.allsolid ) - { - if ( pm->ps->clientNum - && isATST - && g_entities[trace.entityNum].client - && g_entities[trace.entityNum].client->playerTeam == pm->gent->client->playerTeam ) - {//AT-ST's don't step up on allies - } - else - { - VectorCopy( trace.endpos, pm->ps->origin ); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask, G2_NOCOLLIDE, 0); + if (!trace.allsolid) { + if (pm->ps->clientNum && isATST && g_entities[trace.entityNum].client && + g_entities[trace.entityNum].client->playerTeam == pm->gent->client->playerTeam) { // AT-ST's don't step up on allies + } else { + VectorCopy(trace.endpos, pm->ps->origin); } } - if ( trace.fraction < 1.0 ) - { - PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); + if (trace.fraction < 1.0) { + PM_ClipVelocity(pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP); } } @@ -401,23 +367,22 @@ void PM_StepSlideMove( float gravMod ) #endif { // use the step move - float delta; + float delta; delta = pm->ps->origin[2] - start_o[2]; - if ( delta > 2 ) { - if ( delta < 7 ) { - PM_AddEvent( EV_STEP_4 ); - } else if ( delta < 11 ) { - PM_AddEvent( EV_STEP_8 ); - } else if ( delta < 15 ) { - PM_AddEvent( EV_STEP_12 ); + if (delta > 2) { + if (delta < 7) { + PM_AddEvent(EV_STEP_4); + } else if (delta < 11) { + PM_AddEvent(EV_STEP_8); + } else if (delta < 15) { + PM_AddEvent(EV_STEP_12); } else { - PM_AddEvent( EV_STEP_16 ); + PM_AddEvent(EV_STEP_16); } } - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:stepped\n", c_pmove); } } } - diff --git a/codeJK2/game/g_ICARUS.cpp b/codeJK2/game/g_ICARUS.cpp index c5fb26dac8..ca15b25ae1 100644 --- a/codeJK2/game/g_ICARUS.cpp +++ b/codeJK2/game/g_ICARUS.cpp @@ -30,18 +30,18 @@ along with this program; if not, see . #include "g_roff.h" #include "g_icarus.h" -ICARUS_Instance *iICARUS; -bufferlist_t ICARUS_BufferList; -entlist_t ICARUS_EntList; +ICARUS_Instance *iICARUS; +bufferlist_t ICARUS_BufferList; +entlist_t ICARUS_EntList; -cvarlist_t ICARUS_CvarList; +cvarlist_t ICARUS_CvarList; -extern uint32_t Com_BlockChecksum (const void *buffer, int length); -extern void Q3_DebugPrint( int level, const char *format, ... ); +extern uint32_t Com_BlockChecksum(const void *buffer, int length); +extern void Q3_DebugPrint(int level, const char *format, ...); -int ICARUS_entFilter = -1; +int ICARUS_entFilter = -1; -extern stringID_table_t setTable[]; +extern stringID_table_t setTable[]; /* ============= @@ -51,26 +51,23 @@ gets the named script from the cache or disk if not already loaded ============= */ -int ICARUS_GetScript( const char *name, char **buf ) -{ - bufferlist_t::iterator ei; - //Make sure the caller is valid +int ICARUS_GetScript(const char *name, char **buf) { + bufferlist_t::iterator ei; + // Make sure the caller is valid - //Attempt to retrieve a precached script - ei = ICARUS_BufferList.find( (char *) name ); + // Attempt to retrieve a precached script + ei = ICARUS_BufferList.find((char *)name); - //Not found, check the disk - if ( ei == ICARUS_BufferList.end() ) - { - if ( ICARUS_RegisterScript( name ) == false ) + // Not found, check the disk + if (ei == ICARUS_BufferList.end()) { + if (ICARUS_RegisterScript(name) == false) return 0; - //Script is now inserted, retrieve it and pass through - ei = ICARUS_BufferList.find( (char *) name ); + // Script is now inserted, retrieve it and pass through + ei = ICARUS_BufferList.find((char *)name); - if ( ei == ICARUS_BufferList.end() ) - { - //NOTENOTE: This is an internal error in STL if this happens... + if (ei == ICARUS_BufferList.end()) { + // NOTENOTE: This is an internal error in STL if this happens... assert(0); return 0; } @@ -87,31 +84,27 @@ ICARUS_RunScript Runs the script by the given name ============= */ -int ICARUS_RunScript( gentity_t *ent, const char *name ) -{ +int ICARUS_RunScript(gentity_t *ent, const char *name) { char *buf; int len; - //Make sure the caller is valid - if ( ent->sequencer == NULL ) - { - //Com_Printf( "%s : entity is not a valid script user\n", ent->classname ); + // Make sure the caller is valid + if (ent->sequencer == NULL) { + // Com_Printf( "%s : entity is not a valid script user\n", ent->classname ); return false; } - len = ICARUS_GetScript (name, &buf ); - if (len == 0) - { + len = ICARUS_GetScript(name, &buf); + if (len == 0) { return false; } - //Attempt to run the script - if S_FAILED(ent->sequencer->Run( buf, len )) + // Attempt to run the script + if S_FAILED (ent->sequencer->Run(buf, len)) return false; - if ( ( ICARUS_entFilter == -1 ) || ( ICARUS_entFilter == ent->s.number ) ) - { - Q3_DebugPrint( WL_VERBOSE, "%d Script %s executed by %s %s\n", level.time, (char *) name, ent->classname, ent->targetname ); + if ((ICARUS_entFilter == -1) || (ICARUS_entFilter == ent->s.number)) { + Q3_DebugPrint(WL_VERBOSE, "%d Script %s executed by %s %s\n", level.time, (char *)name, ent->classname, ent->targetname); } return true; @@ -125,17 +118,15 @@ Allocates a new ICARUS instance ================= */ -void ICARUS_Init( void ) -{ - //Link all interface functions - Interface_Init( &interface_export ); +void ICARUS_Init(void) { + // Link all interface functions + Interface_Init(&interface_export); - //Create the ICARUS instance for this session - iICARUS = ICARUS_Instance::Create( &interface_export ); + // Create the ICARUS instance for this session + iICARUS = ICARUS_Instance::Create(&interface_export); - if ( iICARUS == NULL ) - { - Com_Error( ERR_DROP, "Unable to initialize ICARUS instance\n" ); + if (iICARUS == NULL) { + Com_Error(ERR_DROP, "Unable to initialize ICARUS instance\n"); return; } @@ -150,37 +141,34 @@ Frees up ICARUS resources from all entities ================= */ -void ICARUS_Shutdown( void ) -{ - bufferlist_t::iterator ei; - gentity_t *ent = &g_entities[0];; +void ICARUS_Shutdown(void) { + bufferlist_t::iterator ei; + gentity_t *ent = &g_entities[0]; + ; - //Release all ICARUS resources from the entities - for ( int i = 0; i < globals.num_entities; i++, ent++ ) - { - if ( !ent->inuse ) + // Release all ICARUS resources from the entities + for (int i = 0; i < globals.num_entities; i++, ent++) { + if (!ent->inuse) continue; - - ICARUS_FreeEnt( ent ); + + ICARUS_FreeEnt(ent); } - //Clear out all precached scripts - for ( ei = ICARUS_BufferList.begin(); ei != ICARUS_BufferList.end(); ++ei ) - { - gi.Free( (*ei).second->buffer ); + // Clear out all precached scripts + for (ei = ICARUS_BufferList.begin(); ei != ICARUS_BufferList.end(); ++ei) { + gi.Free((*ei).second->buffer); delete (*ei).second; } ICARUS_BufferList.clear(); - //Clear the name map + // Clear the name map ICARUS_EntList.clear(); ICARUS_CvarList.clear(); - //Free this instance - if ( iICARUS ) - { + // Free this instance + if (iICARUS) { iICARUS->Delete(); iICARUS = NULL; } @@ -197,61 +185,54 @@ FIXME: shouldn't ICARUS handle this internally? ============== */ -void ICARUS_FreeEnt( gentity_t *ent ) -{ - assert( iICARUS ); +void ICARUS_FreeEnt(gentity_t *ent) { + assert(iICARUS); - //Make sure the ent is valid - if ( ent->sequencer == NULL ) + // Make sure the ent is valid + if (ent->sequencer == NULL) return; - //Remove them from the ICARUSE_EntList list so that when their g_entity index is reused, ICARUS doesn't try to affect the new (incorrect) ent. - if VALIDSTRING( ent->script_targetname ) - { - char temp[1024]; - - strncpy( (char *) temp, ent->script_targetname, 1023 ); - temp[ 1023 ] = 0; + // Remove them from the ICARUSE_EntList list so that when their g_entity index is reused, ICARUS doesn't try to affect the new (incorrect) ent. + if VALIDSTRING (ent->script_targetname) { + char temp[1024]; - entlist_t::iterator it = ICARUS_EntList.find( Q_strupr(temp) ); + strncpy((char *)temp, ent->script_targetname, 1023); + temp[1023] = 0; - if (it != ICARUS_EntList.end()) - { + entlist_t::iterator it = ICARUS_EntList.find(Q_strupr(temp)); + + if (it != ICARUS_EntList.end()) { ICARUS_EntList.erase(it); } } - //Delete the sequencer and the task manager - iICARUS->DeleteSequencer( ent->sequencer ); - - //Clean up the pointers - ent->sequencer = NULL; - ent->taskManager = NULL; -} + // Delete the sequencer and the task manager + iICARUS->DeleteSequencer(ent->sequencer); + // Clean up the pointers + ent->sequencer = NULL; + ent->taskManager = NULL; +} /* ============== ICARUS_ValidEnt -Determines whether or not an entity needs ICARUS information +Determines whether or not an entity needs ICARUS information ============== */ -bool ICARUS_ValidEnt( gentity_t *ent ) -{ +bool ICARUS_ValidEnt(gentity_t *ent) { int i; - //Targeted by a script - if VALIDSTRING( ent->script_targetname ) + // Targeted by a script + if VALIDSTRING (ent->script_targetname) return true; - //Potentially able to call a script - for ( i = 0; i < NUM_BSETS; i++ ) - { - if VALIDSTRING( ent->behaviorSet[i] ) - { - //Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", ent->s.number, ent->targetname ); + // Potentially able to call a script + for (i = 0; i < NUM_BSETS; i++) { + if VALIDSTRING (ent->behaviorSet[i]) { + // Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", ent->s.number, ent->targetname ); ent->script_targetname = ent->targetname; return true; } @@ -268,17 +249,16 @@ Associate the entity's id and name so that it can be referenced later ============== */ -void ICARUS_AssociateEnt( gentity_t *ent ) -{ - char temp[1024]; - - if ( VALIDSTRING( ent->script_targetname ) == false ) +void ICARUS_AssociateEnt(gentity_t *ent) { + char temp[1024]; + + if (VALIDSTRING(ent->script_targetname) == false) return; - strncpy( (char *) temp, ent->script_targetname, 1023 ); - temp[ 1023 ] = 0; + strncpy((char *)temp, ent->script_targetname, 1023); + temp[1023] = 0; - ICARUS_EntList[ Q_strupr( (char *) temp ) ] = ent->s.number; + ICARUS_EntList[Q_strupr((char *)temp)] = ent->s.number; } /* @@ -289,35 +269,33 @@ Loads and caches a script ============== */ -bool ICARUS_RegisterScript( const char *name, bool bCalledDuringInterrogate /* = false */ ) -{ - bufferlist_t::iterator ei; - pscript_t *pscript; - char newname[MAX_FILENAME_LENGTH]; - char *buffer = NULL; // lose compiler warning about uninitialised vars - long length; +bool ICARUS_RegisterScript(const char *name, bool bCalledDuringInterrogate /* = false */) { + bufferlist_t::iterator ei; + pscript_t *pscript; + char newname[MAX_FILENAME_LENGTH]; + char *buffer = NULL; // lose compiler warning about uninitialised vars + long length; - //Make sure this isn't already cached - ei = ICARUS_BufferList.find( (char *) name ); + // Make sure this isn't already cached + ei = ICARUS_BufferList.find((char *)name); // note special return condition here, if doing interrogate and we already have this file then we MUST return // false (which stops the interrogator proceeding), this not only saves some time, but stops a potential // script recursion bug which could lock the program in an infinite loop... Return TRUE for normal though! // - if ( ei != ICARUS_BufferList.end() ) - return (bCalledDuringInterrogate)?false:true; - - sprintf((char *) newname, "%s%s", name, IBI_EXT ); + if (ei != ICARUS_BufferList.end()) + return (bCalledDuringInterrogate) ? false : true; + sprintf((char *)newname, "%s%s", name, IBI_EXT); // small update here, if called during interrogate, don't let gi.FS_ReadFile() complain because it can't // find stuff like BS_RUN_AND_SHOOT as scriptname... During FINALBUILD the message won't appear anyway, hence // the ifndef, this just cuts down on internal error reports while testing release mode... // qboolean qbIgnoreFileRead = qfalse; - // + // // NOTENOTE: For the moment I've taken this back out, to avoid doubling the number of fopen()'s per file. -#if 0//#ifndef FINAL_BUILD +#if 0 //#ifndef FINAL_BUILD if (bCalledDuringInterrogate) { fileHandle_t file; @@ -335,28 +313,26 @@ bool ICARUS_RegisterScript( const char *name, bool bCalledDuringInterrogate /* = } #endif - length = qbIgnoreFileRead ? -1 : gi.FS_ReadFile( newname, (void **) &buffer ); + length = qbIgnoreFileRead ? -1 : gi.FS_ReadFile(newname, (void **)&buffer); - if ( length <= 0 ) - { + if (length <= 0) { // File not found, but keep quiet during interrogate stage, because of stuff like BS_RUN_AND_SHOOT as scriptname // - if (!bCalledDuringInterrogate) - { - Com_Printf(S_COLOR_RED"Could not open file '%s'\n", newname ); + if (!bCalledDuringInterrogate) { + Com_Printf(S_COLOR_RED "Could not open file '%s'\n", newname); } return false; } pscript = new pscript_t; - pscript->buffer = (char *) gi.Malloc(length, TAG_ICARUS, qfalse); - memcpy (pscript->buffer, buffer, length); + pscript->buffer = (char *)gi.Malloc(length, TAG_ICARUS, qfalse); + memcpy(pscript->buffer, buffer, length); pscript->length = length; - gi.FS_FreeFile( buffer ); + gi.FS_FreeFile(buffer); - ICARUS_BufferList[ name ] = pscript; + ICARUS_BufferList[name] = pscript; return true; } @@ -369,119 +345,107 @@ ICARUS_InterrogateScript // at this point the filename should have had the "scripts" (Q3_SCRIPT_DIR) added to it (but not the IBI extension) // -void ICARUS_InterrogateScript( const char *filename ) -{ - CBlockStream stream; - CBlockMember *blockMember; - CBlock block; +void ICARUS_InterrogateScript(const char *filename) { + CBlockStream stream; + CBlockMember *blockMember; + CBlock block; - if (!Q_stricmp(filename,"NULL") || !Q_stricmp(filename,"default")) + if (!Q_stricmp(filename, "NULL") || !Q_stricmp(filename, "default")) return; ////////////////////////////////// // // ensure "scripts" (Q3_SCRIPT_DIR), which will be missing if this was called recursively... // - char sFilename[MAX_FILENAME_LENGTH]; // should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code + char sFilename[MAX_FILENAME_LENGTH]; // should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code - if (!Q_stricmpn(filename,Q3_SCRIPT_DIR,strlen(Q3_SCRIPT_DIR))) - { - Q_strncpyz(sFilename,filename,sizeof(sFilename)); - } - else - { - Q_strncpyz(sFilename,va("%s/%s",Q3_SCRIPT_DIR,filename),sizeof(sFilename)); + if (!Q_stricmpn(filename, Q3_SCRIPT_DIR, strlen(Q3_SCRIPT_DIR))) { + Q_strncpyz(sFilename, filename, sizeof(sFilename)); + } else { + Q_strncpyz(sFilename, va("%s/%s", Q3_SCRIPT_DIR, filename), sizeof(sFilename)); } // ////////////////////////////////// - - //Attempt to register this script - if ( ICARUS_RegisterScript( sFilename, true ) == false ) // true = bCalledDuringInterrogate + // Attempt to register this script + if (ICARUS_RegisterScript(sFilename, true) == false) // true = bCalledDuringInterrogate return; - char *buf; - long len; + char *buf; + long len; - //Attempt to retrieve the new script data - if ( ( len = ICARUS_GetScript ( sFilename, &buf ) ) == 0 ) + // Attempt to retrieve the new script data + if ((len = ICARUS_GetScript(sFilename, &buf)) == 0) return; - //Open the stream - if ( stream.Open( buf, len ) == qfalse ) + // Open the stream + if (stream.Open(buf, len) == qfalse) return; - const char *sVal1, *sVal2; - char temp[1024]; - int setID; + const char *sVal1, *sVal2; + char temp[1024]; + int setID; - //Now iterate through all blocks of the script, searching for keywords - while ( stream.BlockAvailable() ) - { - //Get a block - if ( stream.ReadBlock( &block ) == qfalse ) + // Now iterate through all blocks of the script, searching for keywords + while (stream.BlockAvailable()) { + // Get a block + if (stream.ReadBlock(&block) == qfalse) return; - //Determine what type of block this is - switch( block.GetBlockID() ) + // Determine what type of block this is + switch (block.GetBlockID()) { + case ID_CAMERA: // to cache ROFF files { - case ID_CAMERA: // to cache ROFF files - { - float f = *(float *) block.GetMemberData( 0 ); + float f = *(float *)block.GetMemberData(0); - if (f == TYPE_PATH) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (f == TYPE_PATH) { + sVal1 = (const char *)block.GetMemberData(1); - G_LoadRoff(sVal1); - } + G_LoadRoff(sVal1); } - break; + } break; + + case ID_PLAY: // to cache ROFF files - case ID_PLAY: // to cache ROFF files - - sVal1 = (const char *) block.GetMemberData( 0 ); + sVal1 = (const char *)block.GetMemberData(0); - if (!Q_stricmp(sVal1,"PLAY_ROFF")) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (!Q_stricmp(sVal1, "PLAY_ROFF")) { + sVal1 = (const char *)block.GetMemberData(1); G_LoadRoff(sVal1); - } + } break; - //Run commands + // Run commands case ID_RUN: - - sVal1 = (const char *) block.GetMemberData( 0 ); - - COM_StripExtension( sVal1, (char *) temp, sizeof( temp ) ); - ICARUS_InterrogateScript( (const char *) &temp ); - + + sVal1 = (const char *)block.GetMemberData(0); + + COM_StripExtension(sVal1, (char *)temp, sizeof(temp)); + ICARUS_InterrogateScript((const char *)&temp); + break; - + case ID_SOUND: - sVal1 = (const char *) block.GetMemberData( 1 ); //0 is channel, 1 is filename + sVal1 = (const char *)block.GetMemberData(1); // 0 is channel, 1 is filename G_SoundIndex(sVal1); break; case ID_SET: - blockMember = block.GetMember( 0 ); + blockMember = block.GetMember(0); - //NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) + // NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) - //Make sure we're testing against strings - if ( blockMember->GetID() == TK_STRING ) - { - sVal1 = (const char *) block.GetMemberData( 0 ); - sVal2 = (const char *) block.GetMemberData( 1 ); - - //Get the id for this set identifier - setID = GetIDForString( setTable, sVal1 ); + // Make sure we're testing against strings + if (blockMember->GetID() == TK_STRING) { + sVal1 = (const char *)block.GetMemberData(0); + sVal2 = (const char *)block.GetMemberData(1); - //Check against valid types - switch ( setID ) - { + // Get the id for this set identifier + setID = GetIDForString(setTable, sVal1); + + // Check against valid types + switch (setID) { case SET_SPAWNSCRIPT: case SET_USESCRIPT: case SET_AWAKESCRIPT: @@ -498,40 +462,36 @@ void ICARUS_InterrogateScript( const char *filename ) case SET_FFDEATHSCRIPT: case SET_MINDTRICKSCRIPT: case SET_CINEMATIC_SKIPSCRIPT: - //Recursively obtain all embedded scripts - ICARUS_InterrogateScript( sVal2 ); + // Recursively obtain all embedded scripts + ICARUS_InterrogateScript(sVal2); break; - case SET_LOOPSOUND: //like ID_SOUND, but set's looping + case SET_LOOPSOUND: // like ID_SOUND, but set's looping G_SoundIndex(sVal2); break; - case SET_VIDEO_PLAY: //in game cinematic -extern cvar_t *com_buildScript; - if (com_buildScript->integer) - { + case SET_VIDEO_PLAY: // in game cinematic + extern cvar_t *com_buildScript; + if (com_buildScript->integer) { fileHandle_t file; - char name[MAX_OSPATH]; - + char name[MAX_OSPATH]; + if (strstr(sVal2, "/") == NULL && strstr(sVal2, "\\") == NULL) { - Com_sprintf (name, sizeof(name), "video/%s", sVal2); + Com_sprintf(name, sizeof(name), "video/%s", sVal2); } else { - Com_sprintf (name, sizeof(name), "%s", sVal2); + Com_sprintf(name, sizeof(name), "%s", sVal2); } - COM_StripExtension(name,name,sizeof(name)); - COM_DefaultExtension(name,sizeof(name),".roq"); + COM_StripExtension(name, name, sizeof(name)); + COM_DefaultExtension(name, sizeof(name), ".roq"); - gi.FS_FOpenFile( name, &file, FS_READ ); // trigger the file copy - if (file) - { - gi.FS_FCloseFile( file ); + gi.FS_FOpenFile(name, &file, FS_READ); // trigger the file copy + if (file) { + gi.FS_FCloseFile(file); } } break; case SET_ADDRHANDBOLT_MODEL: - case SET_ADDLHANDBOLT_MODEL: - { - gi.G2API_PrecacheGhoul2Model( sVal2 ); - } - break; + case SET_ADDLHANDBOLT_MODEL: { + gi.G2API_PrecacheGhoul2Model(sVal2); + } break; default: break; } @@ -542,11 +502,11 @@ extern cvar_t *com_buildScript; break; } - //Clean out the block for the next pass + // Clean out the block for the next pass block.Free(); } - //All done + // All done stream.Free(); } @@ -558,23 +518,20 @@ Precache all scripts being used by the entity ============== */ -void ICARUS_PrecacheEnt( gentity_t *ent ) -{ +void ICARUS_PrecacheEnt(gentity_t *ent) { extern stringID_table_t BSTable[]; - char newname[MAX_FILENAME_LENGTH]; - int i; + char newname[MAX_FILENAME_LENGTH]; + int i; - for ( i = 0; i < NUM_BSETS; i++ ) - { - if ( ent->behaviorSet[i] == NULL ) + for (i = 0; i < NUM_BSETS; i++) { + if (ent->behaviorSet[i] == NULL) continue; - if ( GetIDForString( BSTable, ent->behaviorSet[i] ) == -1 ) - {//not a behavior set - sprintf((char *) newname, "%s/%s", Q3_SCRIPT_DIR, ent->behaviorSet[i] ); + if (GetIDForString(BSTable, ent->behaviorSet[i]) == -1) { // not a behavior set + sprintf((char *)newname, "%s/%s", Q3_SCRIPT_DIR, ent->behaviorSet[i]); - //Precache this, and all internally referenced scripts - ICARUS_InterrogateScript( newname ); + // Precache this, and all internally referenced scripts + ICARUS_InterrogateScript(newname); } } } @@ -587,32 +544,31 @@ Allocates a sequencer and task manager only if an entity is a potential script u ============== */ -void Q3_TaskIDClear( int *taskID ); -void ICARUS_InitEnt( gentity_t *ent ) -{ - //Make sure this is a fresh ent - assert( iICARUS ); - assert( ent->taskManager == NULL ); - assert( ent->sequencer == NULL ); +void Q3_TaskIDClear(int *taskID); +void ICARUS_InitEnt(gentity_t *ent) { + // Make sure this is a fresh ent + assert(iICARUS); + assert(ent->taskManager == NULL); + assert(ent->sequencer == NULL); - if ( ent->sequencer != NULL ) + if (ent->sequencer != NULL) return; - if ( ent->taskManager != NULL ) + if (ent->taskManager != NULL) return; - //Create the sequencer and setup the task manager - ent->sequencer = iICARUS->GetSequencer( ent->s.number ); - ent->taskManager = ent->sequencer->GetTaskManager(); + // Create the sequencer and setup the task manager + ent->sequencer = iICARUS->GetSequencer(ent->s.number); + ent->taskManager = ent->sequencer->GetTaskManager(); - //Initialize all taskIDs to -1 - memset( &ent->taskID, -1, sizeof( ent->taskID ) ); + // Initialize all taskIDs to -1 + memset(&ent->taskID, -1, sizeof(ent->taskID)); - //Add this entity to a map of valid associated ents for quick retrieval later - ICARUS_AssociateEnt( ent ); + // Add this entity to a map of valid associated ents for quick retrieval later + ICARUS_AssociateEnt(ent); - //Precache all the entity's scripts - ICARUS_PrecacheEnt( ent ); + // Precache all the entity's scripts + ICARUS_PrecacheEnt(ent); } /* @@ -621,17 +577,16 @@ ICARUS_LinkEntity ------------------------- */ -int ICARUS_LinkEntity( int entID, CSequencer *sequencer, CTaskManager *taskManager ) -{ - gentity_t *ent = &g_entities[ entID ]; +int ICARUS_LinkEntity(int entID, CSequencer *sequencer, CTaskManager *taskManager) { + gentity_t *ent = &g_entities[entID]; - if ( ent == NULL ) + if (ent == NULL) return false; ent->sequencer = sequencer; ent->taskManager = taskManager; - ICARUS_AssociateEnt( ent ); + ICARUS_AssociateEnt(ent); return true; } @@ -642,33 +597,29 @@ Svcmd_ICARUS_f ------------------------- */ -void Svcmd_ICARUS_f( void ) -{ - const char *cmd = gi.argv( 1 ); +void Svcmd_ICARUS_f(void) { + const char *cmd = gi.argv(1); - if ( Q_stricmp( cmd, "log" ) == 0 ) - { + if (Q_stricmp(cmd, "log") == 0) { g_ICARUSDebug->integer = WL_DEBUG; - if ( VALIDSTRING( gi.argv( 2 ) ) ) - { - gentity_t *ent = G_Find( NULL, FOFS( script_targetname ), gi.argv(2) ); + if (VALIDSTRING(gi.argv(2))) { + gentity_t *ent = G_Find(NULL, FOFS(script_targetname), gi.argv(2)); - if ( ent == NULL ) - { - Com_Printf( "Entity \"%s\" not found!\n", gi.argv(2) ); + if (ent == NULL) { + Com_Printf("Entity \"%s\" not found!\n", gi.argv(2)); return; } - //Start logging - Com_Printf("Logging ICARUS info for entity %s\n", gi.argv(2) ); + // Start logging + Com_Printf("Logging ICARUS info for entity %s\n", gi.argv(2)); - ICARUS_entFilter = ( ent->s.number == ICARUS_entFilter ) ? -1 : ent->s.number; + ICARUS_entFilter = (ent->s.number == ICARUS_entFilter) ? -1 : ent->s.number; return; } - + Com_Printf("Logging ICARUS info for all entities\n"); - + return; } } diff --git a/codeJK2/game/g_active.cpp b/codeJK2/game/g_active.cpp index d204f64116..6d6beaedd1 100644 --- a/codeJK2/game/g_active.cpp +++ b/codeJK2/game/g_active.cpp @@ -31,130 +31,118 @@ along with this program; if not, see . #include "g_icarus.h" #ifdef _DEBUG - #include +#include #endif //_DEBUG -#define SLOWDOWN_DIST 128.0f -#define MIN_NPC_SPEED 16.0f +#define SLOWDOWN_DIST 128.0f +#define MIN_NPC_SPEED 16.0f -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); extern void G_MaintainFormations(gentity_t *self); -extern void BG_CalculateOffsetAngles( gentity_t *ent, usercmd_t *ucmd );//in bg_pangles.cpp -extern void TryUse( gentity_t *ent ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void BG_CalculateOffsetAngles(gentity_t *ent, usercmd_t *ucmd); // in bg_pangles.cpp +extern void TryUse(gentity_t *ent); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); extern void ScoreBoardReset(void); -extern void WP_SaberReflectCheck( gentity_t *self, usercmd_t *ucmd ); -extern void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ); -extern void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ); -extern void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ); -extern void WP_SaberInitBladeData( gentity_t *ent ); -extern gentity_t *SeekerAcquiresTarget ( gentity_t *ent, vec3_t pos ); -extern void FireSeeker( gentity_t *owner, gentity_t *target, vec3_t origin, vec3_t dir ); -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern qboolean PM_AdjustAnglesToGripper( gentity_t *gent, usercmd_t *cmd ); -extern qboolean PM_AdjustAngleForWallRun( gentity_t *ent, usercmd_t *ucmd, qboolean doMove ); -extern qboolean PM_AdjustAnglesForSpinningFlip( gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly ); -extern qboolean PM_AdjustAnglesForBackAttack( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForSaberLock( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_AdjustAnglesForKnockdown( gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern int PM_AnimLength( int index, animNumber_t anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern void PM_CmdForRoll( int anim, usercmd_t *pCmd ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); -extern qboolean PM_StandingAnim( int anim ); -extern qboolean PM_InForceGetUp( playerState_t *ps ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -extern qboolean FlyingCreature( gentity_t *ent ); - -extern bool in_camera; -extern qboolean player_locked; -extern qboolean stop_icarus; -extern cvar_t *g_spskill; -extern cvar_t *g_timescale; -extern cvar_t *g_saberMoveSpeed; -extern cvar_t *g_saberAutoBlocking; -extern vmCvar_t cg_thirdPersonAlpha; -extern vmCvar_t cg_thirdPersonAutoAlpha; - -void ClientEndPowerUps( gentity_t *ent ); - -int G_FindLookItem( gentity_t *self ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent; - int bestEntNum = ENTITYNUM_NONE; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward, dir; - int i, e; - float radius = 256; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? +extern void WP_SaberReflectCheck(gentity_t *self, usercmd_t *ucmd); +extern void WP_SaberUpdate(gentity_t *self, usercmd_t *ucmd); +extern void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd); +extern void WP_ForcePowersUpdate(gentity_t *self, usercmd_t *ucmd); +extern void WP_SaberInitBladeData(gentity_t *ent); +extern gentity_t *SeekerAcquiresTarget(gentity_t *ent, vec3_t pos); +extern void FireSeeker(gentity_t *owner, gentity_t *target, vec3_t origin, vec3_t dir); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern qboolean PM_AdjustAnglesToGripper(gentity_t *gent, usercmd_t *cmd); +extern qboolean PM_AdjustAngleForWallRun(gentity_t *ent, usercmd_t *ucmd, qboolean doMove); +extern qboolean PM_AdjustAnglesForSpinningFlip(gentity_t *ent, usercmd_t *ucmd, qboolean anglesOnly); +extern qboolean PM_AdjustAnglesForBackAttack(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForSaberLock(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_AdjustAnglesForKnockdown(gentity_t *ent, usercmd_t *ucmd, qboolean angleClampOnly); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SaberInAttack(int move); +extern int PM_AnimLength(int index, animNumber_t anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern void PM_CmdForRoll(int anim, usercmd_t *pCmd); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_InCartwheel(int anim); +extern qboolean PM_StandingAnim(int anim); +extern qboolean PM_InForceGetUp(playerState_t *ps); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +extern qboolean FlyingCreature(gentity_t *ent); + +extern bool in_camera; +extern qboolean player_locked; +extern qboolean stop_icarus; +extern cvar_t *g_spskill; +extern cvar_t *g_timescale; +extern cvar_t *g_saberMoveSpeed; +extern cvar_t *g_saberAutoBlocking; +extern vmCvar_t cg_thirdPersonAlpha; +extern vmCvar_t cg_thirdPersonAutoAlpha; + +void ClientEndPowerUps(gentity_t *ent); + +int G_FindLookItem(gentity_t *self) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent; + int bestEntNum = ENTITYNUM_NONE; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward, dir; + int i, e; + float radius = 256; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); - - if ( !numListedEntities ) - { + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); + + if (!numListedEntities) { return ENTITYNUM_NONE; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( !ent->item ) - { + if (!ent->item) { continue; } - if ( ent->s.eFlags&EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( (ent->spawnflags&4/*ITMSF_MONSTER*/) ) - {//NPCs only + if ((ent->spawnflags & 4 /*ITMSF_MONSTER*/)) { // NPCs only continue; } - if ( !BG_CanItemBeGrabbed( &ent->s, &self->client->ps ) ) - {//don't need it + if (!BG_CanItemBeGrabbed(&ent->s, &self->client->ps)) { // don't need it continue; } - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - //rate him based on how close & how in front he is - VectorSubtract( ent->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir ); - if ( ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY ) - {//security keys are of the highest importance + // rate him based on how close & how in front he is + VectorSubtract(ent->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir); + if (ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY) { // security keys are of the highest importance rating *= 2.0f; } - if ( rating > bestRating ) - { + if (rating > bestRating) { bestEntNum = ent->s.number; bestRating = rating; } @@ -162,62 +150,53 @@ int G_FindLookItem( gentity_t *self ) return bestEntNum; } -extern void CG_SetClientViewAngles( vec3_t angles, qboolean overrideViewEnt ); -qboolean G_ClearViewEntity( gentity_t *ent ) -{ - if ( !ent->client->ps.viewEntity ) +extern void CG_SetClientViewAngles(vec3_t angles, qboolean overrideViewEnt); +qboolean G_ClearViewEntity(gentity_t *ent) { + if (!ent->client->ps.viewEntity) return qfalse; - if ( ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_NONE ) - { - if ( g_entities[ent->client->ps.viewEntity].inuse ) - { + if (ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_NONE) { + if (g_entities[ent->client->ps.viewEntity].inuse) { g_entities[ent->client->ps.viewEntity].svFlags &= ~SVF_BROADCAST; - if ( g_entities[ent->client->ps.viewEntity].NPC ) - { + if (g_entities[ent->client->ps.viewEntity].NPC) { g_entities[ent->client->ps.viewEntity].NPC->controlledTime = 0; - SetClientViewAngle( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); - G_SetAngles( &g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles ); - VectorCopy( g_entities[ent->client->ps.viewEntity].currentAngles, g_entities[ent->client->ps.viewEntity].NPC->lastPathAngles ); + SetClientViewAngle(&g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles); + G_SetAngles(&g_entities[ent->client->ps.viewEntity], g_entities[ent->client->ps.viewEntity].currentAngles); + VectorCopy(g_entities[ent->client->ps.viewEntity].currentAngles, g_entities[ent->client->ps.viewEntity].NPC->lastPathAngles); g_entities[ent->client->ps.viewEntity].NPC->desiredYaw = g_entities[ent->client->ps.viewEntity].currentAngles[YAW]; } } - CG_SetClientViewAngles( ent->pos4, qtrue ); - SetClientViewAngle( ent, ent->pos4 ); + CG_SetClientViewAngles(ent->pos4, qtrue); + SetClientViewAngle(ent, ent->pos4); } ent->client->ps.viewEntity = 0; return qtrue; } -void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ) -{ - if ( !self || !self->client || !viewEntity ) - { +void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity) { + if (!self || !self->client || !viewEntity) { return; } - if ( self->s.number == 0 && cg.zoomMode ) - { + if (self->s.number == 0 && cg.zoomMode) { // yeah, it should really toggle them so it plays the end sound.... cg.zoomMode = 0; } - if ( viewEntity->s.number == self->client->ps.viewEntity ) - { + if (viewEntity->s.number == self->client->ps.viewEntity) { return; } - //clear old one first - G_ClearViewEntity( self ); - //set new one + // clear old one first + G_ClearViewEntity(self); + // set new one self->client->ps.viewEntity = viewEntity->s.number; viewEntity->svFlags |= SVF_BROADCAST; - //remember current angles - VectorCopy( self->client->ps.viewangles, self->pos4 ); - if ( viewEntity->client ) - { - //vec3_t clear = {0,0,0}; - CG_SetClientViewAngles( viewEntity->client->ps.viewangles, qtrue ); - //SetClientViewAngle( self, viewEntity->client->ps.viewangles ); - //SetClientViewAngle( viewEntity, clear ); + // remember current angles + VectorCopy(self->client->ps.viewangles, self->pos4); + if (viewEntity->client) { + // vec3_t clear = {0,0,0}; + CG_SetClientViewAngles(viewEntity->client->ps.viewangles, qtrue); + // SetClientViewAngle( self, viewEntity->client->ps.viewangles ); + // SetClientViewAngle( viewEntity, clear ); /* VectorCopy( viewEntity->client->ps.viewangles, self->client->ps.viewangles ); for ( int i = 0; i < 3; i++ ) @@ -226,168 +205,135 @@ void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ) } */ } - if ( !self->s.number ) - { - CG_CenterPrint( "@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + if (!self->s.number) { + CG_CenterPrint("@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } } -qboolean G_ControlledByPlayer( gentity_t *self ) -{ - if ( self && self->NPC && self->NPC->controlledTime > level.time ) - {//being controlled +qboolean G_ControlledByPlayer(gentity_t *self) { + if (self && self->NPC && self->NPC->controlledTime > level.time) { // being controlled gentity_t *controller = &g_entities[0]; - if ( controller->client && controller->client->ps.viewEntity == self->s.number ) - {//we're the player's viewEntity + if (controller->client && controller->client->ps.viewEntity == self->s.number) { // we're the player's viewEntity return qtrue; } } return qfalse; } -qboolean G_ValidateLookEnemy( gentity_t *self, gentity_t *enemy ) -{ - if ( !enemy ) - { +qboolean G_ValidateLookEnemy(gentity_t *self, gentity_t *enemy) { + if (!enemy) { return qfalse; } - if ( enemy->flags&FL_NOTARGET ) - { + if (enemy->flags & FL_NOTARGET) { return qfalse; } - if ( !enemy || enemy == self || !enemy->inuse ) - { + if (!enemy || enemy == self || !enemy->inuse) { return qfalse; } - if ( !enemy->client || !enemy->NPC ) - {//not valid - if ( (enemy->svFlags&SVF_NONNPC_ENEMY) - && enemy->s.weapon == WP_TURRET - && enemy->noDamageTeam != self->client->playerTeam - && enemy->health > 0 ) - {//a turret - //return qtrue; - } - else - { + if (!enemy->client || !enemy->NPC) { // not valid + if ((enemy->svFlags & SVF_NONNPC_ENEMY) && enemy->s.weapon == WP_TURRET && enemy->noDamageTeam != self->client->playerTeam && + enemy->health > 0) { // a turret + // return qtrue; + } else { return qfalse; } - } - else - { - if ( enemy->client->playerTeam == self->client->playerTeam ) - {//on same team + } else { + if (enemy->client->playerTeam == self->client->playerTeam) { // on same team return qfalse; } - if ( enemy->health <= 0 && ((level.time-enemy->s.time) > 3000||!InFront(enemy->currentOrigin,self->currentOrigin,self->client->ps.viewangles,0.2f)||DistanceHorizontal(enemy->currentOrigin,self->currentOrigin)>16384))//>128 - {//corpse, been dead too long or too out of sight to be interesting - if ( !enemy->message ) - { + if (enemy->health <= 0 && + ((level.time - enemy->s.time) > 3000 || !InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.2f) || + DistanceHorizontal(enemy->currentOrigin, self->currentOrigin) > 16384)) //>128 + { // corpse, been dead too long or too out of sight to be interesting + if (!enemy->message) { return qfalse; } } } - if ( (!InFront( enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || !G_ClearLOS( self, self->client->renderInfo.eyePoint, enemy ) ) - && ( DistanceHorizontalSquared( enemy->currentOrigin, self->currentOrigin ) > 65536 || fabs(enemy->currentOrigin[2]-self->currentOrigin[2]) > 384 ) ) - {//(not in front or not clear LOS) & greater than 256 away + if ((!InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || + !G_ClearLOS(self, self->client->renderInfo.eyePoint, enemy)) && + (DistanceHorizontalSquared(enemy->currentOrigin, self->currentOrigin) > 65536 || + fabs(enemy->currentOrigin[2] - self->currentOrigin[2]) > 384)) { //(not in front or not clear LOS) & greater than 256 away return qfalse; } - //LOS? + // LOS? return qtrue; } -void G_ChooseLookEnemy( gentity_t *self, usercmd_t *ucmd ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent, *bestEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward, dir; - int i, e; - float radius = 256; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? - fwdangles[0] = 0; //Must initialize data! +void G_ChooseLookEnemy(gentity_t *self, usercmd_t *ucmd) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent, *bestEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward, dir; + int i, e; + float radius = 256; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? + fwdangles[0] = 0; // Must initialize data! fwdangles[1] = self->client->ps.viewangles[1]; fwdangles[2] = 0; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); - - if ( !numListedEntities ) - {//should we clear the enemy? + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); + + if (!numListedEntities) { // should we clear the enemy? return; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ValidateLookEnemy( self, ent ) ) - {//doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call + if (!G_ValidateLookEnemy(self, + ent)) { // doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - //rate him based on how close & how in front he is - VectorSubtract( ent->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir )+1.0f; - if ( ent->health <= 0 ) - { - if ( (ucmd->buttons&BUTTON_ATTACK) || (ucmd->buttons&BUTTON_ALT_ATTACK) ) - {//if attacking, don't consider dead enemies + // rate him based on how close & how in front he is + VectorSubtract(ent->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir) + 1.0f; + if (ent->health <= 0) { + if ((ucmd->buttons & BUTTON_ATTACK) || (ucmd->buttons & BUTTON_ALT_ATTACK)) { // if attacking, don't consider dead enemies continue; } - if ( ent->message ) - {//keyholder + if (ent->message) { // keyholder rating *= 0.5f; - } - else - { + } else { rating *= 0.1f; } } - if ( ent->s.weapon == WP_SABER ) - { + if (ent->s.weapon == WP_SABER) { rating *= 2.0f; } - if ( ent->enemy == self ) - {//he's mad at me, he's more important + if (ent->enemy == self) { // he's mad at me, he's more important rating *= 2.0f; - } - else if ( ent->NPC && ent->NPC->blockedSpeechDebounceTime > level.time - 6000 ) - {//he's detected me, he's more important - if ( ent->NPC->blockedSpeechDebounceTime > level.time + 4000 ) - { + } else if (ent->NPC && ent->NPC->blockedSpeechDebounceTime > level.time - 6000) { // he's detected me, he's more important + if (ent->NPC->blockedSpeechDebounceTime > level.time + 4000) { rating *= 1.5f; - } - else - {//from 1.0f to 1.5f - rating += rating * ((float)(ent->NPC->blockedSpeechDebounceTime-level.time) + 6000.0f)/20000.0f; + } else { // from 1.0f to 1.5f + rating += rating * ((float)(ent->NPC->blockedSpeechDebounceTime - level.time) + 6000.0f) / 20000.0f; } } /* @@ -396,14 +342,12 @@ void G_ChooseLookEnemy( gentity_t *self, usercmd_t *ucmd ) rading *= 2.0f; } */ - if ( rating > bestRating ) - { + if (rating > bestRating) { bestEnt = ent; bestRating = rating; } } - if ( bestEnt ) - { + if (bestEnt) { self->enemy = bestEnt; } } @@ -418,23 +362,23 @@ damage values to that client for pain blends and kicks, and global pain sound events for all clients. =============== */ -void P_DamageFeedback( gentity_t *player ) { - gclient_t *client; - float count; - vec3_t angles; +void P_DamageFeedback(gentity_t *player) { + gclient_t *client; + float count; + vec3_t angles; client = player->client; - if ( client->ps.pm_type == PM_DEAD ) { + if (client->ps.pm_type == PM_DEAD) { return; } // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor; - if ( count == 0 ) { - return; // didn't take any damage + if (count == 0) { + return; // didn't take any damage } - if ( count > 255 ) { + if (count > 255) { count = 255; } @@ -442,18 +386,15 @@ void P_DamageFeedback( gentity_t *player ) { // world damage (falling, slime, etc) uses a special code // to make the blend blob centered instead of positional - if ( client->damage_fromWorld ) - { + if (client->damage_fromWorld) { client->ps.damagePitch = 255; client->ps.damageYaw = 255; client->damage_fromWorld = qfalse; - } - else - { - vectoangles( client->damage_from, angles ); - client->ps.damagePitch = angles[PITCH]/360.0 * 256; - client->ps.damageYaw = angles[YAW]/360.0 * 256; + } else { + vectoangles(client->damage_from, angles); + client->ps.damagePitch = angles[PITCH] / 360.0 * 256; + client->ps.damageYaw = angles[YAW] / 360.0 * 256; } client->ps.damageCount = count; @@ -466,8 +407,6 @@ void P_DamageFeedback( gentity_t *player ) { client->damage_knockback = 0; } - - /* ============= P_WorldEffects @@ -475,59 +414,47 @@ P_WorldEffects Check for lava / slime contents and drowning ============= */ -void P_WorldEffects( gentity_t *ent ) { - int mouthContents = 0; +void P_WorldEffects(gentity_t *ent) { + int mouthContents = 0; - if ( ent->client->noclip ) - { - ent->client->airOutTime = level.time + 12000; // don't need air + if (ent->client->noclip) { + ent->client->airOutTime = level.time + 12000; // don't need air return; } - if ( !in_camera ) - { - mouthContents = gi.pointcontents( ent->client->renderInfo.eyePoint, ent->s.number ); + if (!in_camera) { + mouthContents = gi.pointcontents(ent->client->renderInfo.eyePoint, ent->s.number); } // // check for drowning // - if ( (mouthContents&(CONTENTS_WATER|CONTENTS_SLIME)) ) - { - if ( ent->client->NPC_class == CLASS_SWAMPTROOPER ) - {//they have air tanks + if ((mouthContents & (CONTENTS_WATER | CONTENTS_SLIME))) { + if (ent->client->NPC_class == CLASS_SWAMPTROOPER) { // they have air tanks ent->client->airOutTime = level.time + 12000; // don't need air ent->damage = 2; - } - else if ( ent->client->airOutTime < level.time) - {// if out of air, start drowning + } else if (ent->client->airOutTime < level.time) { // if out of air, start drowning // drown! ent->client->airOutTime += 1000; - if ( ent->health > 0 ) { + if (ent->health > 0) { // take more damage the longer underwater ent->damage += 2; if (ent->damage > 15) ent->damage = 15; // play a gurp sound instead of a normal pain sound - if (ent->health <= ent->damage) - { - G_AddEvent( ent, EV_WATER_DROWN, 0 ); - } - else - { - G_AddEvent( ent, Q_irand(EV_WATER_GURP1, EV_WATER_GURP2), 0 ); - } + if (ent->health <= ent->damage) { + G_AddEvent(ent, EV_WATER_DROWN, 0); + } else { + G_AddEvent(ent, Q_irand(EV_WATER_GURP1, EV_WATER_GURP2), 0); + } // don't play a normal pain sound ent->painDebounceTime = level.time + 200; - G_Damage (ent, NULL, NULL, NULL, NULL, - ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); + G_Damage(ent, NULL, NULL, NULL, NULL, ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); } } - } - else - { + } else { ent->client->airOutTime = level.time + 12000; ent->damage = 2; } @@ -535,135 +462,108 @@ void P_WorldEffects( gentity_t *ent ) { // // check for sizzle damage (move to pmove?) // - if (ent->waterlevel && - (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) { - if (ent->health > 0 - && ent->painDebounceTime < level.time ) { + if (ent->waterlevel && (ent->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) { + if (ent->health > 0 && ent->painDebounceTime < level.time) { if (ent->watertype & CONTENTS_LAVA) { - G_Damage (ent, NULL, NULL, NULL, NULL, - 15*ent->waterlevel, 0, MOD_LAVA); + G_Damage(ent, NULL, NULL, NULL, NULL, 15 * ent->waterlevel, 0, MOD_LAVA); } if (ent->watertype & CONTENTS_SLIME) { - G_Damage (ent, NULL, NULL, NULL, NULL, - 1, 0, MOD_SLIME); + G_Damage(ent, NULL, NULL, NULL, NULL, 1, 0, MOD_SLIME); } } } // Poisoned? - if ((ent->client->poisonDamage) && (ent->client->poisonTime < level.time)) - { + if ((ent->client->poisonDamage) && (ent->client->poisonTime < level.time)) { ent->client->poisonDamage -= 2; ent->client->poisonTime = level.time + 1000; - G_Damage( ent, NULL, NULL, 0, 0, 2, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_ARMOR, MOD_UNKNOWN );//FIXME: MOD_POISON? + G_Damage(ent, NULL, NULL, 0, 0, 2, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_ARMOR, MOD_UNKNOWN); // FIXME: MOD_POISON? - if (ent->client->poisonDamage<0) - { + if (ent->client->poisonDamage < 0) { ent->client->poisonDamage = 0; } } - } - - /* =============== G_SetClientSound =============== */ -void G_SetClientSound( gentity_t *ent ) { -// if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) -// ent->s.loopSound = G_SoundIndex("sound/weapons/stasis/electricloop.wav"); +void G_SetClientSound(gentity_t *ent) { + // if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) + // ent->s.loopSound = G_SoundIndex("sound/weapons/stasis/electricloop.wav"); -// else -// ent->s.loopSound = 0; + // else + // ent->s.loopSound = 0; } - - //============================================================== -void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) -{ +void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf) { float magnitude, my_mass; - vec3_t velocity; + vec3_t velocity; - if( self->client ) - { - VectorCopy( self->client->ps.velocity, velocity ); + if (self->client) { + VectorCopy(self->client->ps.velocity, velocity); my_mass = self->mass; - } - else - { - VectorCopy( self->s.pos.trDelta, velocity ); - if ( self->s.pos.trType == TR_GRAVITY ) - { + } else { + VectorCopy(self->s.pos.trDelta, velocity); + if (self->s.pos.trType == TR_GRAVITY) { velocity[2] -= 0.25f * g_gravity->value; } - if( !self->mass ) - { + if (!self->mass) { my_mass = 1; - } - else if ( self->mass <= 10 ) - { + } else if (self->mass <= 10) { my_mass = 10; - } - else - { - my_mass = self->mass;///10; + } else { + my_mass = self->mass; /// 10; } } - magnitude = VectorLength( velocity ) * my_mass / 50; + magnitude = VectorLength(velocity) * my_mass / 50; - if ( !self->client || self->client->ps.lastOnGround+300client->ps.lastOnGround+100 < level.time ) ) - { + if (!self->client || self->client->ps.lastOnGround + 300 < level.time || (self->client->ps.lastOnGround + 100 < level.time)) { vec3_t dir1, dir2; float force = 0, dot; - if ( other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || ((other->svFlags&SVF_BBRUSH)&&(other->spawnflags&4/*THIN*/)) )//(other->absmax[0]-other->absmin[0]<=32||other->absmax[1]-other->absmin[1]<=32||other->absmax[2]-other->absmin[2]<=32)) ) - {//glass and thin breakable brushes (axially aligned only, unfortunately) take more impact damage + if (other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || + ((other->svFlags & SVF_BBRUSH) && + (other->spawnflags & + 4 /*THIN*/))) //(other->absmax[0]-other->absmin[0]<=32||other->absmax[1]-other->absmin[1]<=32||other->absmax[2]-other->absmin[2]<=32)) ) + { // glass and thin breakable brushes (axially aligned only, unfortunately) take more impact damage magnitude *= 2; } - //damage them - if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD ) - { - VectorCopy( velocity, dir1 ); - VectorNormalize( dir1 ); - if( VectorCompare( other->currentOrigin, vec3_origin ) ) - {//a brush with no origin - VectorCopy ( dir1, dir2 ); - } - else - { - VectorSubtract( other->currentOrigin, self->currentOrigin, dir2 ); - VectorNormalize( dir2 ); + // damage them + if (magnitude >= 100 && other->s.number < ENTITYNUM_WORLD) { + VectorCopy(velocity, dir1); + VectorNormalize(dir1); + if (VectorCompare(other->currentOrigin, vec3_origin)) { // a brush with no origin + VectorCopy(dir1, dir2); + } else { + VectorSubtract(other->currentOrigin, self->currentOrigin, dir2); + VectorNormalize(dir2); } - dot = DotProduct( dir1, dir2 ); + dot = DotProduct(dir1, dir2); - if ( dot >= 0.2 ) - { + if (dot >= 0.2) { force = dot; - } - else - { + } else { force = 0; } - force *= (magnitude/50); + force *= (magnitude / 50); - int cont = gi.pointcontents( other->absmax, other->s.number ); - if( (cont&CONTENTS_WATER) )//|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes + int cont = gi.pointcontents(other->absmax, other->s.number); + if ((cont & CONTENTS_WATER)) //|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes { - force /= 3; //water absorbs 2/3 velocity + force /= 3; // water absorbs 2/3 velocity } - if ( self->NPC && other->s.number == ENTITYNUM_WORLD ) - {//NPCs take less damage + if (self->NPC && other->s.number == ENTITYNUM_WORLD) { // NPCs take less damage force /= 2; } @@ -672,101 +572,87 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) force=10; */ - if( ( force >= 1 && other->s.number != 0 ) || force >= 10) - { - /* - dprint("Damage other ("); - dprint(loser.classname); - dprint("): "); - dprint(ftos(force)); - dprint("\n"); - */ - if ( other->svFlags & SVF_GLASS_BRUSH ) - { - other->splashRadius = (float)(self->maxs[0] - self->mins[0])/4.0f; + if ((force >= 1 && other->s.number != 0) || force >= 10) { + /* + dprint("Damage other ("); + dprint(loser.classname); + dprint("): "); + dprint(ftos(force)); + dprint("\n"); + */ + if (other->svFlags & SVF_GLASS_BRUSH) { + other->splashRadius = (float)(self->maxs[0] - self->mins[0]) / 4.0f; } - if ( self->forcePushTime > level.time - 1000//was force pushed/pulled in the last 1600 milliseconds - && self->forcePuller == other->s.number )//hit the person who pushed/pulled me - {//ignore the impact - } - else if ( other->takedamage ) - { - if ( !self->client || !other->s.number || !other->client ) - {//aw, fuck it, clients no longer take impact damage from other clients, unless you're the player - G_Damage( other, self, self, velocity, self->currentOrigin, force, DAMAGE_NO_ARMOR, MOD_IMPACT ); - } - else - { - GEntity_PainFunc( other, self, self, self->currentOrigin, force, MOD_IMPACT ); - //Hmm, maybe knockdown? - G_Throw( other, dir2, force ); + if (self->forcePushTime > level.time - 1000 // was force pushed/pulled in the last 1600 milliseconds + && self->forcePuller == other->s.number) // hit the person who pushed/pulled me + { // ignore the impact + } else if (other->takedamage) { + if (!self->client || !other->s.number || + !other->client) { // aw, fuck it, clients no longer take impact damage from other clients, unless you're the player + G_Damage(other, self, self, velocity, self->currentOrigin, force, DAMAGE_NO_ARMOR, MOD_IMPACT); + } else { + GEntity_PainFunc(other, self, self, self->currentOrigin, force, MOD_IMPACT); + // Hmm, maybe knockdown? + G_Throw(other, dir2, force); } - } - else - { - //Hmm, maybe knockdown? - G_Throw( other, dir2, force ); + } else { + // Hmm, maybe knockdown? + G_Throw(other, dir2, force); } } } - if ( damageSelf && self->takedamage && !(self->flags&FL_NO_IMPACT_DMG)) - { - //Now damage me - //FIXME: more lenient falling damage, especially for when driving a vehicle - if ( self->client && self->client->ps.forceJumpZStart ) - {//we were force-jumping - if ( self->currentOrigin[2] >= self->client->ps.forceJumpZStart ) - {//we landed at same height or higher than we landed + if (damageSelf && self->takedamage && !(self->flags & FL_NO_IMPACT_DMG)) { + // Now damage me + // FIXME: more lenient falling damage, especially for when driving a vehicle + if (self->client && self->client->ps.forceJumpZStart) { // we were force-jumping + if (self->currentOrigin[2] >= self->client->ps.forceJumpZStart) { // we landed at same height or higher than we landed magnitude = 0; - } - else - {//FIXME: take off some of it, at least? - magnitude = (self->client->ps.forceJumpZStart-self->currentOrigin[2])/3; + } else { // FIXME: take off some of it, at least? + magnitude = (self->client->ps.forceJumpZStart - self->currentOrigin[2]) / 3; } } - //if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet - if( ( magnitude >= 100 + self->health && self->s.number != 0 && self->s.weapon != WP_SABER ) || ( magnitude >= 700 ) )//&& self.safe_time < level.time ))//health here is used to simulate structural integrity - { - if ( (self->s.weapon == WP_SABER || self->s.number == 0) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 ) - {//players and jedi take less impact damage - //allow for some lenience on high falls - magnitude /= 2; - /* - if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage - { - magnitude/=2; - } - */ - } - magnitude /= 40; - magnitude = magnitude - force/2;//If damage other, subtract half of that damage off of own injury - if ( magnitude >= 1 ) + // if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet + if ((magnitude >= 100 + self->health && self->s.number != 0 && self->s.weapon != WP_SABER) || + (magnitude >= 700)) //&& self.safe_time < level.time ))//health here is used to simulate structural integrity + { + if ((self->s.weapon == WP_SABER || self->s.number == 0) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && + magnitude < 1000) { // players and jedi take less impact damage + // allow for some lenience on high falls + magnitude /= 2; + /* + if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage { - //FIXME: Put in a thingtype impact sound function - /* - dprint("Damage self ("); - dprint(self.classname); - dprint("): "); - dprint(ftos(magnitude)); - dprint("\n"); - */ - /* - if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 ) - return; - */ - if ( self->NPC && self->s.weapon == WP_SABER ) - {//FIXME: for now Jedi take no falling damage, but really they should if pushed off? - magnitude = 0; - } - G_Damage( self, NULL, NULL, NULL, self->currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + magnitude/=2; } + */ } + magnitude /= 40; + magnitude = magnitude - force / 2; // If damage other, subtract half of that damage off of own injury + if (magnitude >= 1) { + // FIXME: Put in a thingtype impact sound function + /* + dprint("Damage self ("); + dprint(self.classname); + dprint("): "); + dprint(ftos(magnitude)); + dprint("\n"); + */ + /* + if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 ) + return; + */ + if (self->NPC && self->s.weapon == WP_SABER) { // FIXME: for now Jedi take no falling damage, but really they should if pushed off? + magnitude = 0; + } + G_Damage(self, NULL, NULL, NULL, self->currentOrigin, magnitude / 2, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT + } + } } - //FIXME: slow my velocity some? - + // FIXME: slow my velocity some? + self->lastImpact = level.time; /* @@ -781,33 +667,32 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) ClientImpacts ============== */ -void ClientImpacts( gentity_t *ent, pmove_t *pm ) { - int i, j; - trace_t trace; - gentity_t *other; - - memset( &trace, 0, sizeof( trace ) ); - for (i=0 ; inumtouch ; i++) { - for (j=0 ; jtouchents[j] == pm->touchents[i] ) { +void ClientImpacts(gentity_t *ent, pmove_t *pm) { + int i, j; + trace_t trace; + gentity_t *other; + + memset(&trace, 0, sizeof(trace)); + for (i = 0; i < pm->numtouch; i++) { + for (j = 0; j < i; j++) { + if (pm->touchents[j] == pm->touchents[i]) { break; } } if (j != i) { - continue; // duplicated + continue; // duplicated } - other = &g_entities[ pm->touchents[i] ]; + other = &g_entities[pm->touchents[i]]; - if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { // last check unneccessary - GEntity_TouchFunc( ent, other, &trace ); + if ((ent->NPC != NULL) && (ent->e_TouchFunc != touchF_NULL)) { // last check unneccessary + GEntity_TouchFunc(ent, other, &trace); } - if ( other->e_TouchFunc == touchF_NULL ) { // not needed, but I'll leave it I guess (cache-hit issues) + if (other->e_TouchFunc == touchF_NULL) { // not needed, but I'll leave it I guess (cache-hit issues) continue; } - GEntity_TouchFunc( other, ent, &trace ); + GEntity_TouchFunc(other, ent, &trace); } - } /* @@ -820,77 +705,70 @@ Spectators will only interact with teleporters. This version checks at 6 unit steps between last and current origins ============ */ -void G_TouchTriggersLerped( gentity_t *ent ) { - int i, num; - float dist, curDist = 0; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t end, mins, maxs, diff; - const vec3_t range = { 40, 40, 52 }; - qboolean touched[MAX_GENTITIES]; - qboolean done = qfalse; - - if ( !ent->client ) { +void G_TouchTriggersLerped(gentity_t *ent) { + int i, num; + float dist, curDist = 0; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t end, mins, maxs, diff; + const vec3_t range = {40, 40, 52}; + qboolean touched[MAX_GENTITIES]; + qboolean done = qfalse; + + if (!ent->client) { return; } // dead NPCs don't activate triggers! - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { - if ( ent->s.number ) - { + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { + if (ent->s.number) { return; } } #ifdef _DEBUG - for ( int j = 0; j < 3; j++ ) - { - assert( !Q_isnan(ent->currentOrigin[j])); - assert( !Q_isnan(ent->lastOrigin[j])); + for (int j = 0; j < 3; j++) { + assert(!Q_isnan(ent->currentOrigin[j])); + assert(!Q_isnan(ent->lastOrigin[j])); } -#endif// _DEBUG - VectorSubtract( ent->currentOrigin, ent->lastOrigin, diff ); - dist = VectorNormalize( diff ); +#endif // _DEBUG + VectorSubtract(ent->currentOrigin, ent->lastOrigin, diff); + dist = VectorNormalize(diff); - memset (touched, qfalse, sizeof(touched) ); + memset(touched, qfalse, sizeof(touched)); - for ( curDist = 0; !done && ent->maxs[1]>0; curDist += (float)ent->maxs[1]/2.0f ) - { - if ( curDist >= dist ) - { - VectorCopy( ent->currentOrigin, end ); + for (curDist = 0; !done && ent->maxs[1] > 0; curDist += (float)ent->maxs[1] / 2.0f) { + if (curDist >= dist) { + VectorCopy(ent->currentOrigin, end); done = qtrue; + } else { + VectorMA(ent->lastOrigin, curDist, diff, end); } - else - { - VectorMA( ent->lastOrigin, curDist, diff, end ); - } - VectorSubtract( end, range, mins ); - VectorAdd( end, range, maxs ); + VectorSubtract(end, range, mins); + VectorAdd(end, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( end, ent->mins, mins ); - VectorAdd( end, ent->maxs, maxs ); + VectorAdd(end, ent->mins, mins); + VectorAdd(end, ent->maxs, maxs); - for ( i=0 ; ie_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { + if ((hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL)) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } - if ( touched[i] == qtrue ) { - continue;//already touched this move + if (touched[i] == qtrue) { + continue; // already touched this move } - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) - { - if ( Q_stricmp( "trigger_teleport", hit->classname ) || !(hit->spawnflags&16/*TTSF_DEAD_OK*/) ) - {//dead clients can only touch tiogger_teleports that are marked as touchable + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { + if (Q_stricmp("trigger_teleport", hit->classname) || + !(hit->spawnflags & 16 /*TTSF_DEAD_OK*/)) { // dead clients can only touch tiogger_teleports that are marked as touchable continue; } } @@ -903,20 +781,20 @@ void G_TouchTriggersLerped( gentity_t *ent ) { } } else */ { - if ( !gi.EntityContact( mins, maxs, hit ) ) { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } } touched[i] = qtrue; - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } - //WTF? Why would a trigger ever fire off the NPC's touch func??!!! + // WTF? Why would a trigger ever fire off the NPC's touch func??!!! /* if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { GEntity_TouchFunc( ent, hit, &trace ); @@ -934,38 +812,38 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_TouchTriggers( gentity_t *ent ) { - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t mins, maxs; - const vec3_t range = { 40, 40, 52 }; - - if ( !ent->client ) { +void G_TouchTriggers(gentity_t *ent) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t mins, maxs; + const vec3_t range = {40, 40, 52}; + + if (!ent->client) { return; } // dead clients don't activate triggers! - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { return; } - VectorSubtract( ent->client->ps.origin, range, mins ); - VectorAdd( ent->client->ps.origin, range, maxs ); + VectorSubtract(ent->client->ps.origin, range, mins); + VectorAdd(ent->client->ps.origin, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( ent->client->ps.origin, ent->mins, mins ); - VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); + VectorAdd(ent->client->ps.origin, ent->mins, mins); + VectorAdd(ent->client->ps.origin, ent->maxs, maxs); - for ( i=0 ; ie_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL) ) { + if ((hit->e_TouchFunc == touchF_NULL) && (ent->e_TouchFunc == touchF_NULL)) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } @@ -978,24 +856,23 @@ void G_TouchTriggers( gentity_t *ent ) { } } else */ { - if ( !gi.EntityContact( mins, maxs, hit ) ) { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } - if ( ( ent->NPC != NULL ) && ( ent->e_TouchFunc != touchF_NULL ) ) { - GEntity_TouchFunc( ent, hit, &trace ); + if ((ent->NPC != NULL) && (ent->e_TouchFunc != touchF_NULL)) { + GEntity_TouchFunc(ent, hit, &trace); } } } - /* ============ G_MoverTouchTriggers @@ -1004,126 +881,102 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ) -{ - int i, num; - float step, stepSize, dist; - gentity_t *touch[MAX_GENTITIES], *hit; - trace_t trace; - vec3_t mins, maxs, dir, size, checkSpot; - const vec3_t range = { 40, 40, 52 }; +void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg) { + int i, num; + float step, stepSize, dist; + gentity_t *touch[MAX_GENTITIES], *hit; + trace_t trace; + vec3_t mins, maxs, dir, size, checkSpot; + const vec3_t range = {40, 40, 52}; // non-moving movers don't hit triggers! - if ( !VectorLengthSquared( ent->s.pos.trDelta ) ) - { + if (!VectorLengthSquared(ent->s.pos.trDelta)) { return; } - VectorSubtract( ent->mins, ent->maxs, size ); - stepSize = VectorLength( size ); - if ( stepSize < 1 ) - { + VectorSubtract(ent->mins, ent->maxs, size); + stepSize = VectorLength(size); + if (stepSize < 1) { stepSize = 1; } - VectorSubtract( ent->currentOrigin, oldOrg, dir ); - dist = VectorNormalize( dir ); - for ( step = 0; step <= dist; step += stepSize ) - { - VectorMA( ent->currentOrigin, step, dir, checkSpot ); - VectorSubtract( checkSpot, range, mins ); - VectorAdd( checkSpot, range, maxs ); + VectorSubtract(ent->currentOrigin, oldOrg, dir); + dist = VectorNormalize(dir); + for (step = 0; step <= dist; step += stepSize) { + VectorMA(ent->currentOrigin, step, dir, checkSpot); + VectorSubtract(checkSpot, range, mins); + VectorAdd(checkSpot, range, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->absmin, because that has a one unit pad - VectorAdd( checkSpot, ent->mins, mins ); - VectorAdd( checkSpot, ent->maxs, maxs ); + VectorAdd(checkSpot, ent->mins, mins); + VectorAdd(checkSpot, ent->maxs, maxs); - for ( i=0 ; is.eType != ET_PUSH_TRIGGER ) - { + if (hit->s.eType != ET_PUSH_TRIGGER) { continue; } - if ( hit->e_TouchFunc == touchF_NULL ) - { + if (hit->e_TouchFunc == touchF_NULL) { continue; } - if ( !( hit->contents & CONTENTS_TRIGGER ) ) - { + if (!(hit->contents & CONTENTS_TRIGGER)) { continue; } - - if ( !gi.EntityContact( mins, maxs, hit ) ) - { + if (!gi.EntityContact(mins, maxs, hit)) { continue; } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->e_TouchFunc != touchF_NULL ) - { + if (hit->e_TouchFunc != touchF_NULL) { GEntity_TouchFunc(hit, ent, &trace); } } } } -void G_MatchPlayerWeapon( gentity_t *ent ) -{ - if ( g_entities[0].inuse && g_entities[0].client ) - {//player is around +void G_MatchPlayerWeapon(gentity_t *ent) { + if (g_entities[0].inuse && g_entities[0].client) { // player is around int newWeap; - if ( g_entities[0].client->ps.weapon > WP_DET_PACK ) - { + if (g_entities[0].client->ps.weapon > WP_DET_PACK) { newWeap = WP_BRYAR_PISTOL; - } - else - { + } else { newWeap = g_entities[0].client->ps.weapon; } - if ( newWeap != WP_NONE && ent->client->ps.weapon != newWeap ) - { - if ( ent->weaponModel >= 0 ) - { + if (newWeap != WP_NONE && ent->client->ps.weapon != newWeap) { + if (ent->weaponModel >= 0) { gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel); } - ent->client->ps.stats[STAT_WEAPONS] = ( 1 << newWeap ); + ent->client->ps.stats[STAT_WEAPONS] = (1 << newWeap); ent->client->ps.ammo[weaponData[newWeap].ammoIndex] = 999; - ChangeWeapon( ent, newWeap ); + ChangeWeapon(ent, newWeap); ent->client->ps.weapon = newWeap; ent->client->ps.weaponstate = WEAPON_READY; - if ( newWeap == WP_SABER ) - { - //FIXME: AddSound/Sight Event - WP_SaberInitBladeData( ent ); - G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saberModel ); + if (newWeap == WP_SABER) { + // FIXME: AddSound/Sight Event + WP_SaberInitBladeData(ent); + G_CreateG2AttachedWeaponModel(ent, ent->client->ps.saberModel); ent->client->ps.saberActive = g_entities[0].client->ps.saberActive; ent->client->ps.saberLength = g_entities[0].client->ps.saberLength; ent->client->ps.saberAnimLevel = g_entities[0].client->ps.saberAnimLevel; - } - else - { - G_CreateG2AttachedWeaponModel( ent, weaponData[newWeap].weaponMdl ); + } else { + G_CreateG2AttachedWeaponModel(ent, weaponData[newWeap].weaponMdl); } } } } -void G_NPCMunroMatchPlayerWeapon( gentity_t *ent ) -{ - //special uber hack for cinematic Munro's to match player's weapon - if ( !in_camera ) - { - if ( ent && ent->client && ent->NPC && (ent->NPC->aiFlags&NPCAI_MATCHPLAYERWEAPON) ) - {//we're a Kyle NPC - G_MatchPlayerWeapon( ent ); +void G_NPCMunroMatchPlayerWeapon(gentity_t *ent) { + // special uber hack for cinematic Munro's to match player's weapon + if (!in_camera) { + if (ent && ent->client && ent->NPC && (ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON)) { // we're a Kyle NPC + G_MatchPlayerWeapon(ent); } } } @@ -1134,38 +987,26 @@ ClientInactivityTimer Returns qfalse if the client is dropped ================= */ -qboolean ClientInactivityTimer( gclient_t *client ) { - if ( ! g_inactivity->integer ) - { +qboolean ClientInactivityTimer(gclient_t *client) { + if (!g_inactivity->integer) { // give everyone some time, so if the operator sets g_inactivity during // gameplay, everyone isn't kicked client->inactivityTime = level.time + 60 * 1000; client->inactivityWarning = qfalse; - } - else if ( client->usercmd.forwardmove || - client->usercmd.rightmove || - client->usercmd.upmove || - (client->usercmd.buttons & BUTTON_ATTACK) || - (client->usercmd.buttons & BUTTON_ALT_ATTACK) ) - { + } else if (client->usercmd.forwardmove || client->usercmd.rightmove || client->usercmd.upmove || (client->usercmd.buttons & BUTTON_ATTACK) || + (client->usercmd.buttons & BUTTON_ALT_ATTACK)) { client->inactivityTime = level.time + g_inactivity->integer * 1000; client->inactivityWarning = qfalse; - } - else if ( !client->pers.localClient ) - { - if ( level.time > client->inactivityTime ) - { - gi.DropClient( client - level.clients, "Dropped due to inactivity" ); + } else if (!client->pers.localClient) { + if (level.time > client->inactivityTime) { + gi.DropClient(client - level.clients, "Dropped due to inactivity"); return qfalse; } - if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) - { + if (level.time > client->inactivityTime - 10000 && !client->inactivityWarning) { client->inactivityWarning = qtrue; - gi.SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" ); + gi.SendServerCommand(client - level.clients, "cp \"Ten seconds until inactivity drop!\n\""); } - } - else - {//FIXME: here is where we can decide to play an idle animation + } else { // FIXME: here is where we can decide to play an idle animation } return qtrue; } @@ -1177,36 +1018,34 @@ ClientTimerActions Actions that happen once a second ================== */ -void ClientTimerActions( gentity_t *ent, int msec ) { +void ClientTimerActions(gentity_t *ent, int msec) { gclient_t *client; client = ent->client; client->timeResidual += msec; - while ( client->timeResidual >= 1000 ) - { + while (client->timeResidual >= 1000) { client->timeResidual -= 1000; - if ( ent->s.weapon != WP_NONE ) - { + if (ent->s.weapon != WP_NONE) { ent->client->sess.missionStats.weaponUsed[ent->s.weapon]++; } // if we've got the seeker powerup, see if we can shoot it at someone -/* if ( ent->client->ps.powerups[PW_SEEKER] > level.time ) - { - vec3_t seekerPos, dir; - gentity_t *enemy = SeekerAcquiresTarget( ent, seekerPos ); + /* if ( ent->client->ps.powerups[PW_SEEKER] > level.time ) + { + vec3_t seekerPos, dir; + gentity_t *enemy = SeekerAcquiresTarget( ent, seekerPos ); - if ( enemy != NULL ) // set the client's enemy to a valid target - { - FireSeeker( ent, enemy, seekerPos, dir ); + if ( enemy != NULL ) // set the client's enemy to a valid target + { + FireSeeker( ent, enemy, seekerPos, dir ); - gentity_t *tent; - tent = G_TempEntity( seekerPos, EV_POWERUP_SEEKER_FIRE ); - VectorCopy( dir, tent->pos1 ); - tent->s.eventParm = ent->s.number; - } - }*/ + gentity_t *tent; + tent = G_TempEntity( seekerPos, EV_POWERUP_SEEKER_FIRE ); + VectorCopy( dir, tent->pos1 ); + tent->s.eventParm = ent->s.number; + } + }*/ } } @@ -1215,19 +1054,18 @@ void ClientTimerActions( gentity_t *ent, int msec ) { ClientIntermissionThink ==================== */ -static qboolean ClientCinematicThink( gclient_t *client ) { +static qboolean ClientCinematicThink(gclient_t *client) { client->ps.eFlags &= ~EF_FIRING; // swap button actions client->oldbuttons = client->buttons; client->buttons = client->usercmd.buttons; - if ( client->buttons & ( BUTTON_USE ) & ( client->oldbuttons ^ client->buttons ) ) { - return( qtrue ); + if (client->buttons & (BUTTON_USE) & (client->oldbuttons ^ client->buttons)) { + return (qtrue); } - return( qfalse ); + return (qfalse); } - /* ================ ClientEvents @@ -1236,35 +1074,35 @@ Events will be passed on to the clients for presentation, but any server game effects are handled here ================ */ -extern void WP_SaberDamageTrace( gentity_t *ent ); -extern void WP_SaberUpdateOldBladeData( gentity_t *ent ); -void ClientEvents( gentity_t *ent, int oldEventSequence ) { - int i; - int event; +extern void WP_SaberDamageTrace(gentity_t *ent); +extern void WP_SaberUpdateOldBladeData(gentity_t *ent); +void ClientEvents(gentity_t *ent, int oldEventSequence) { + int i; + int event; gclient_t *client; - //int damage; + // int damage; #ifndef FINAL_BUILD - qboolean fired = qfalse; + qboolean fired = qfalse; #endif client = ent->client; - for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) { - event = client->ps.events[ i & (MAX_PS_EVENTS-1) ]; + for (i = oldEventSequence; i < client->ps.eventSequence; i++) { + event = client->ps.events[i & (MAX_PS_EVENTS - 1)]; - switch ( event ) { + switch (event) { case EV_FALL_MEDIUM: - case EV_FALL_FAR://these come from bg_pmove, PM_CrashLand - if ( ent->s.eType != ET_PLAYER ) { - break; // not in the player model + case EV_FALL_FAR: // these come from bg_pmove, PM_CrashLand + if (ent->s.eType != ET_PLAYER) { + break; // not in the player model } /* //FIXME: isn't there a more accurate way to calculate damage from falls? - if ( event == EV_FALL_FAR ) + if ( event == EV_FALL_FAR ) { damage = 50; - } - else + } + else { damage = 25; } @@ -1275,43 +1113,39 @@ void ClientEvents( gentity_t *ent, int oldEventSequence ) { case EV_FIRE_WEAPON: #ifndef FINAL_BUILD - if ( fired ) { - gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); + if (fired) { + gi.Printf("DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n"); } fired = qtrue; #endif - FireWeapon( ent, qfalse ); + FireWeapon(ent, qfalse); break; case EV_ALT_FIRE: #ifndef FINAL_BUILD - if ( fired ) { - gi.Printf( "DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n" ); + if (fired) { + gi.Printf("DOUBLE EV_FIRE_WEAPON AND-OR EV_ALT_FIRE!!\n"); } fired = qtrue; #endif - FireWeapon( ent, qtrue ); + FireWeapon(ent, qtrue); break; default: break; } } - //by the way, if you have your saber in hand and it's on, do the damage trace - if ( client->ps.weapon == WP_SABER ) - { - if ( g_timescale->value >= 1.0f || !(client->ps.forcePowersActive&(1<ps.saberDamageDebounceTime - level.time > wait ) - {//when you unpause the game with force speed on, the time gets *really* wiggy... + // by the way, if you have your saber in hand and it's on, do the damage trace + if (client->ps.weapon == WP_SABER) { + if (g_timescale->value >= 1.0f || !(client->ps.forcePowersActive & (1 << FP_SPEED))) { + int wait = FRAMETIME / 2; + // sanity check + if (client->ps.saberDamageDebounceTime - level.time > wait) { // when you unpause the game with force speed on, the time gets *really* wiggy... client->ps.saberDamageDebounceTime = level.time + wait; } - if ( client->ps.saberDamageDebounceTime <= level.time ) - { - WP_SaberDamageTrace( ent ); - WP_SaberUpdateOldBladeData( ent ); + if (client->ps.saberDamageDebounceTime <= level.time) { + WP_SaberDamageTrace(ent); + WP_SaberUpdateOldBladeData(ent); /* if ( g_timescale->value&&client->ps.clientNum==0&&!player_locked&&!MatrixMode&&client->ps.forcePowersActive&(1<s.number&&ent->aimDebounceTime>level.time) - || (ent->client->ps.pm_time && (ent->client->ps.pm_flags&PMF_TIME_KNOCKBACK)) - || ent->forcePushTime > level.time ) - {//being knocked back, can't do anything! + if ((!ent->s.number && ent->aimDebounceTime > level.time) || (ent->client->ps.pm_time && (ent->client->ps.pm_flags & PMF_TIME_KNOCKBACK)) || + ent->forcePushTime > level.time) { // being knocked back, can't do anything! ucmd->buttons = 0; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - overridAngles = (PM_AdjustAnglesForKnockdown( ent, ucmd, qfalse )?qtrue:overridAngles); + overridAngles = (PM_AdjustAnglesForKnockdown(ent, ucmd, qfalse) ? qtrue : overridAngles); - if ( ent->client->ps.saberLockTime > level.time ) - { + if (ent->client->ps.saberLockTime > level.time) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.saberLockTime - level.time > SABER_LOCK_DELAYED_TIME ) - {//2 second delay before either can push - //FIXME: base on difficulty + if (ent->client->ps.saberLockTime - level.time > SABER_LOCK_DELAYED_TIME) { // 2 second delay before either can push + // FIXME: base on difficulty ucmd->buttons = 0; + } else { + ucmd->buttons &= ~(ucmd->buttons & ~BUTTON_ATTACK); } - else - { - ucmd->buttons &= ~(ucmd->buttons&~BUTTON_ATTACK); - } - overridAngles = (PM_AdjustAnglesForSaberLock( ent, ucmd )?qtrue:overridAngles); - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); + overridAngles = (PM_AdjustAnglesForSaberLock(ent, ucmd) ? qtrue : overridAngles); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.saberMove == LS_A_LUNGE ) - {//can't move during lunge + if (ent->client->ps.saberMove == LS_A_LUNGE) { // can't move during lunge ucmd->rightmove = ucmd->upmove = 0; - if ( ent->client->ps.legsAnimTimer > 500 && (ent->s.number || !player_locked) ) - { + if (ent->client->ps.legsAnimTimer > 500 && (ent->s.number || !player_locked)) { ucmd->forwardmove = 127; - } - else - { + } else { ucmd->forwardmove = 0; } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.saberMove == LS_A_JUMP_T__B_ ) - {//can't move during leap - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE || (!ent->s.number && player_locked) ) - {//hit the ground + if (ent->client->ps.saberMove == LS_A_JUMP_T__B_) { // can't move during leap + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE || (!ent->s.number && player_locked)) { // hit the ground ucmd->forwardmove = 0; } ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } } - if ( ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR - || ent->client->ps.saberMove == LS_A_BACKSTAB ) - {//can't move or turn during back attacks + if (ent->client->ps.saberMove == LS_A_BACK || ent->client->ps.saberMove == LS_A_BACK_CR || + ent->client->ps.saberMove == LS_A_BACKSTAB) { // can't move or turn during back attacks ucmd->forwardmove = ucmd->rightmove = 0; - if ( ent->NPC ) - { - VectorClear( ent->client->ps.moveDir ); - } - if ( (overridAngles = (PM_AdjustAnglesForBackAttack( ent, ucmd )?qtrue:overridAngles)) == qtrue ) - { - //pull back the view - if ( !ent->s.number ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); + if (ent->NPC) { + VectorClear(ent->client->ps.moveDir); + } + if ((overridAngles = (PM_AdjustAnglesForBackAttack(ent, ucmd) ? qtrue : overridAngles)) == qtrue) { + // pull back the view + if (!ent->s.number) { + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); float backDist = 0; - if ( elapsedTime < animLength/2.0f ) - {//starting anim - backDist = (elapsedTime/animLength)*120.0f; - } - else - {//ending anim - backDist = ((animLength-elapsedTime)/animLength)*120.0f; + if (elapsedTime < animLength / 2.0f) { // starting anim + backDist = (elapsedTime / animLength) * 120.0f; + } else { // ending anim + backDist = ((animLength - elapsedTime) / animLength) * 120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; - cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; + cg.overrides.thirdPersonRange = cg_thirdPersonRange.value + backDist; } } - } - else if ( ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK1 - || ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK2 ) - { - //pull back the view - if ( !ent->s.number ) - { - float animLength = PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsAnimTimer); + } else if (ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK1 || ent->client->ps.torsoAnim == BOTH_WALL_FLIP_BACK2) { + // pull back the view + if (!ent->s.number) { + float animLength = PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)ent->client->ps.torsoAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsAnimTimer); float backDist = 0; - if ( elapsedTime < animLength/2.0f ) - {//starting anim - backDist = (elapsedTime/animLength)*120.0f; - } - else - {//ending anim - backDist = ((animLength-elapsedTime)/animLength)*120.0f; + if (elapsedTime < animLength / 2.0f) { // starting anim + backDist = (elapsedTime / animLength) * 120.0f; + } else { // ending anim + backDist = ((animLength - elapsedTime) / animLength) * 120.0f; } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; - cg.overrides.thirdPersonRange = cg_thirdPersonRange.value+backDist; + cg.overrides.thirdPersonRange = cg_thirdPersonRange.value + backDist; } - } - else if ( !ent->s.number ) - { - if ( ent->client->NPC_class != CLASS_ATST ) - { + } else if (!ent->s.number) { + if (ent->client->NPC_class != CLASS_ATST) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = 0; } } - - if ( PM_InRoll( &ent->client->ps ) ) - { - if ( ent->s.number || !player_locked ) - { - PM_CmdForRoll( ent->client->ps.legsAnim, ucmd ); + if (PM_InRoll(&ent->client->ps)) { + if (ent->s.number || !player_locked) { + PM_CmdForRoll(ent->client->ps.legsAnim, ucmd); } - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } ent->client->ps.speed = 400; } - if ( PM_InCartwheel( ent->client->ps.legsAnim ) ) - {//can't keep moving in cartwheel + if (PM_InCartwheel(ent->client->ps.legsAnim)) { // can't keep moving in cartwheel ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( ent->NPC ) - {//invalid now - VectorClear( ent->client->ps.moveDir ); + if (ent->NPC) { // invalid now + VectorClear(ent->client->ps.moveDir); } - if ( ent->s.number || !player_locked ) - { - switch ( ent->client->ps.legsAnim ) - { + if (ent->s.number || !player_locked) { + switch (ent->client->ps.legsAnim) { case BOTH_ARIAL_LEFT: case BOTH_CARTWHEEL_LEFT: ucmd->rightmove = -127; @@ -1494,97 +1286,74 @@ qboolean G_CheckClampUcmd( gentity_t *ent, usercmd_t *ucmd ) } } - overridAngles = (PM_AdjustAngleForWallRun( ent, ucmd, qtrue )?qtrue:overridAngles); + overridAngles = (PM_AdjustAngleForWallRun(ent, ucmd, qtrue) ? qtrue : overridAngles); return overridAngles; } -void BG_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd ) -{ - vec3_t forward, right, moveDir; - float pushSpeed, fMove, rMove; +void BG_AddPushVecToUcmd(gentity_t *self, usercmd_t *ucmd) { + vec3_t forward, right, moveDir; + float pushSpeed, fMove, rMove; - if ( !self->client ) - { + if (!self->client) { return; } pushSpeed = VectorLengthSquared(self->client->pushVec); - if(!pushSpeed) - {//not being pushed + if (!pushSpeed) { // not being pushed return; } AngleVectors(self->client->ps.viewangles, forward, right, NULL); - VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir); - VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir); - //moveDir is now our intended move velocity + VectorScale(forward, ucmd->forwardmove / 127.0f * self->client->ps.speed, moveDir); + VectorMA(moveDir, ucmd->rightmove / 127.0f * self->client->ps.speed, right, moveDir); + // moveDir is now our intended move velocity VectorAdd(moveDir, self->client->pushVec, moveDir); self->client->ps.speed = VectorNormalize(moveDir); - //moveDir is now our intended move velocity plus our push Vector + // moveDir is now our intended move velocity plus our push Vector fMove = 127.0 * DotProduct(forward, moveDir); rMove = 127.0 * DotProduct(right, moveDir); - ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive - ucmd->rightmove = floor(rMove);//If in the same dir , will be positive + ucmd->forwardmove = floor(fMove); // If in the same dir , will be positive + ucmd->rightmove = floor(rMove); // If in the same dir , will be positive - if ( self->client->pushVecTime < level.time ) - { - VectorClear( self->client->pushVec ); + if (self->client->pushVecTime < level.time) { + VectorClear(self->client->pushVec); } } -void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc ) -{ - if ( !ent->client || !ent->NPC ) - { +void NPC_Accelerate(gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc) { + if (!ent->client || !ent->NPC) { return; } - if ( !ent->NPC->stats.acceleration ) - {//No acceleration means just start and stop + if (!ent->NPC->stats.acceleration) { // No acceleration means just start and stop ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - //FIXME: in cinematics always accel/decel? - else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed ) - {//Only accelerate if at walkSpeeds - if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - { - //ent->client->ps.friction = 0; + // FIXME: in cinematics always accel/decel? + else if (ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed) { // Only accelerate if at walkSpeeds + if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - { - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - {//decelerate even when walking + } else if (fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { // decelerate even when walking ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//stop on a dime + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // stop on a dime ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - } - else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) - {//Only decelerate if at runSpeeds - if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - {//Accelerate to runspeed - //ent->client->ps.friction = 0; + } else // if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) + { // Only decelerate if at runSpeeds + if (fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { // Accelerate to runspeed + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - {//accelerate instantly - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { // accelerate instantly + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - { + } else if (fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - { + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } @@ -1596,16 +1365,14 @@ NPC_GetWalkSpeed ------------------------- */ -static int NPC_GetWalkSpeed( gentity_t *ent ) -{ - int walkSpeed = 0; +static int NPC_GetWalkSpeed(gentity_t *ent) { + int walkSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; - switch ( ent->client->playerTeam ) - { - case TEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code) + switch (ent->client->playerTeam) { + case TEAM_PLAYER: // To shutup compiler, will add entries later (this is stub code) default: walkSpeed = ent->NPC->stats.walkSpeed; break; @@ -1619,22 +1386,20 @@ static int NPC_GetWalkSpeed( gentity_t *ent ) NPC_GetRunSpeed ------------------------- */ -#define BORG_RUN_INCR 25 -#define SPECIES_RUN_INCR 25 -#define STASIS_RUN_INCR 20 -#define WARBOT_RUN_INCR 20 +#define BORG_RUN_INCR 25 +#define SPECIES_RUN_INCR 25 +#define STASIS_RUN_INCR 20 +#define WARBOT_RUN_INCR 20 -static int NPC_GetRunSpeed( gentity_t *ent ) -{ - int runSpeed = 0; +static int NPC_GetRunSpeed(gentity_t *ent) { + int runSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; // team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types - switch( ent->client->NPC_class) - { - case CLASS_PROBE: // droid cases here to shut-up compiler + switch (ent->client->NPC_class) { + case CLASS_PROBE: // droid cases here to shut-up compiler case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: @@ -1656,110 +1421,93 @@ static int NPC_GetRunSpeed( gentity_t *ent ) return runSpeed; } -void G_UpdateEmplacedWeaponData( gentity_t *ent ) -{ - if ( ent && ent->owner && ent->health > 0 ) - { +void G_UpdateEmplacedWeaponData(gentity_t *ent) { + if (ent && ent->owner && ent->health > 0) { gentity_t *chair = ent->owner; - //take the emplaced gun's waypoint as your own + // take the emplaced gun's waypoint as your own ent->waypoint = chair->waypoint; - //update the actual origin of the sitter - mdxaBone_t boltMatrix; - vec3_t chairAng = {0, ent->client->ps.viewangles[YAW], 0}; + // update the actual origin of the sitter + mdxaBone_t boltMatrix; + vec3_t chairAng = {0, ent->client->ps.viewangles[YAW], 0}; // Getting the seat bolt here - gi.G2API_GetBoltMatrix( chair->ghoul2, chair->playerModel, chair->headBolt, - &boltMatrix, chairAng, chair->currentOrigin, (cg.time?cg.time:level.time), - NULL, chair->s.modelScale ); + gi.G2API_GetBoltMatrix(chair->ghoul2, chair->playerModel, chair->headBolt, &boltMatrix, chairAng, chair->currentOrigin, + (cg.time ? cg.time : level.time), NULL, chair->s.modelScale); // Storing ent position, bolt position, and bolt axis - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->ps.origin ); - gi.linkentity( ent ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->ps.origin); + gi.linkentity(ent); } } -void ExitEmplacedWeapon( gentity_t *ent ) -{ +void ExitEmplacedWeapon(gentity_t *ent) { // requesting to unlock from the weapon int oldWeapon; // Remove this gun from our inventory - ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << ent->client->ps.weapon ); + ent->client->ps.stats[STAT_WEAPONS] &= ~(1 << ent->client->ps.weapon); // when we lock or unlock from the the gun, we just swap weapons with it oldWeapon = ent->client->ps.weapon; ent->client->ps.weapon = ent->owner->s.weapon; ent->owner->s.weapon = oldWeapon; -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - if ( ent->NPC ) - { - ChangeWeapon( ent, ent->client->ps.weapon ); - } - else - { -extern void CG_ChangeWeapon( int num ); - CG_ChangeWeapon( ent->client->ps.weapon ); - if (weaponData[ent->client->ps.weapon].weaponMdl[0]) - { - //might be NONE, so check if it has a model - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl ); + extern void ChangeWeapon(gentity_t * ent, int newWeapon); + if (ent->NPC) { + ChangeWeapon(ent, ent->client->ps.weapon); + } else { + extern void CG_ChangeWeapon(int num); + CG_ChangeWeapon(ent->client->ps.weapon); + if (weaponData[ent->client->ps.weapon].weaponMdl[0]) { + // might be NONE, so check if it has a model + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl); - if ( ent->client->ps.weapon == WP_SABER && cg_saberAutoThird.value ) - { - gi.cvar_set( "cg_thirdperson", "1" ); - } - else if ( ent->client->ps.weapon != WP_SABER && cg_gunAutoFirst.value ) - { - gi.cvar_set( "cg_thirdperson", "0" ); + if (ent->client->ps.weapon == WP_SABER && cg_saberAutoThird.value) { + gi.cvar_set("cg_thirdperson", "1"); + } else if (ent->client->ps.weapon != WP_SABER && cg_gunAutoFirst.value) { + gi.cvar_set("cg_thirdperson", "0"); } } } - if ( ent->client->ps.weapon == WP_SABER ) - { - ent->client->ps.saberActive = ent->owner->alt_fire; + if (ent->client->ps.weapon == WP_SABER) { + ent->client->ps.saberActive = ent->owner->alt_fire; } // We'll leave the gun pointed in the direction it was last facing, though we'll cut out the pitch - if ( ent->client ) - { - VectorCopy( ent->client->ps.viewangles, ent->owner->s.angles ); + if (ent->client) { + VectorCopy(ent->client->ps.viewangles, ent->owner->s.angles); ent->owner->s.angles[PITCH] = 0; - G_SetAngles( ent->owner, ent->owner->s.angles ); - VectorCopy( ent->owner->s.angles, ent->owner->pos1 ); + G_SetAngles(ent->owner, ent->owner->s.angles); + VectorCopy(ent->owner->s.angles, ent->owner->pos1); // if we are the player we will have put down a brush that blocks NPCs so that we have a clear spot to get back out. - //gentity_t *place = G_Find( NULL, FOFS(classname), "emp_placeholder" ); + // gentity_t *place = G_Find( NULL, FOFS(classname), "emp_placeholder" ); - if ( ent->health > 0 && ent->owner->nextTrain ) - {//he's still alive, and we have a placeholder, so put him back + if (ent->health > 0 && ent->owner->nextTrain) { // he's still alive, and we have a placeholder, so put him back // reset the players position - VectorCopy( ent->owner->nextTrain->currentOrigin, ent->client->ps.origin ); - //reset ent's size to normal - VectorCopy( ent->owner->nextTrain->mins, ent->mins ); - VectorCopy( ent->owner->nextTrain->maxs, ent->maxs ); - //free the placeholder - G_FreeEntity( ent->owner->nextTrain ); - //re-link the ent - gi.linkentity( ent ); - } - else if ( ent->health <= 0 ) - { + VectorCopy(ent->owner->nextTrain->currentOrigin, ent->client->ps.origin); + // reset ent's size to normal + VectorCopy(ent->owner->nextTrain->mins, ent->mins); + VectorCopy(ent->owner->nextTrain->maxs, ent->maxs); + // free the placeholder + G_FreeEntity(ent->owner->nextTrain); + // re-link the ent + gi.linkentity(ent); + } else if (ent->health <= 0) { // dead, so give 'em a push out of the chair vec3_t dir; - AngleVectors( ent->owner->s.angles, NULL, dir, NULL ); + AngleVectors(ent->owner->s.angles, NULL, dir, NULL); - if ( rand() & 1 ) - { - VectorScale( dir, -1, dir ); + if (rand() & 1) { + VectorScale(dir, -1, dir); } - VectorMA( ent->client->ps.velocity, 75, dir, ent->client->ps.velocity ); + VectorMA(ent->client->ps.velocity, 75, dir, ent->client->ps.velocity); } } -// gi.G2API_DetachG2Model( &ent->ghoul2[ent->playerModel] ); + // gi.G2API_DetachG2Model( &ent->ghoul2[ent->playerModel] ); ent->s.eFlags &= ~EF_LOCKED_TO_WEAPON; ent->client->ps.eFlags &= ~EF_LOCKED_TO_WEAPON; @@ -1769,113 +1517,90 @@ extern void CG_ChangeWeapon( int num ); ent->owner->delay = level.time; ent->owner->activator = NULL; - if ( !ent->NPC ) - { + if (!ent->NPC) { // by keeping the owner, a dead npc can be pushed out of the chair without colliding with it ent->owner = NULL; } } -void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ) -{ - if (( (*ucmd)->buttons & BUTTON_USE || (*ucmd)->forwardmove < 0 || (*ucmd)->upmove > 0 ) && ent->owner && ent->owner->delay + 500 < level.time ) - { +void RunEmplacedWeapon(gentity_t *ent, usercmd_t **ucmd) { + if (((*ucmd)->buttons & BUTTON_USE || (*ucmd)->forwardmove < 0 || (*ucmd)->upmove > 0) && ent->owner && ent->owner->delay + 500 < level.time) { ent->owner->s.loopSound = 0; - ExitEmplacedWeapon( ent ); + ExitEmplacedWeapon(ent); (*ucmd)->buttons &= ~BUTTON_USE; - G_Sound( ent, G_SoundIndex( "sound/weapons/emplaced/emplaced_dismount.mp3" )); - } - else - { + G_Sound(ent, G_SoundIndex("sound/weapons/emplaced/emplaced_dismount.mp3")); + } else { // this is a crappy way to put sounds on a moving emplaced gun.... -/* if ( ent->owner ) - { - if ( !VectorCompare( ent->owner->pos3, ent->owner->movedir )) - { - ent->owner->s.loopSound = G_SoundIndex( "sound/weapons/emplaced/emplaced_move_lp.wav" ); - ent->owner->fly_sound_debounce_time = level.time; - } - else - { - if ( ent->owner->fly_sound_debounce_time + 100 <= level.time ) + /* if ( ent->owner ) { - ent->owner->s.loopSound = 0; - } - } + if ( !VectorCompare( ent->owner->pos3, ent->owner->movedir )) + { + ent->owner->s.loopSound = G_SoundIndex( "sound/weapons/emplaced/emplaced_move_lp.wav" ); + ent->owner->fly_sound_debounce_time = level.time; + } + else + { + if ( ent->owner->fly_sound_debounce_time + 100 <= level.time ) + { + ent->owner->s.loopSound = 0; + } + } - VectorCopy( ent->owner->pos3, ent->owner->movedir ); - } -*/ + VectorCopy( ent->owner->pos3, ent->owner->movedir ); + } + */ // don't allow movement, weapon switching, and most kinds of button presses (*ucmd)->forwardmove = 0; (*ucmd)->rightmove = 0; (*ucmd)->upmove = 0; - (*ucmd)->buttons &= (BUTTON_ATTACK|BUTTON_ALT_ATTACK); + (*ucmd)->buttons &= (BUTTON_ATTACK | BUTTON_ALT_ATTACK); - (*ucmd)->weapon = ent->client->ps.weapon; //WP_EMPLACED_GUN; + (*ucmd)->weapon = ent->client->ps.weapon; // WP_EMPLACED_GUN; - if ( ent->health <= 0 ) - { - ExitEmplacedWeapon( ent ); + if (ent->health <= 0) { + ExitEmplacedWeapon(ent); } } } // yes... so stop skipping... -void G_StopCinematicSkip( void ) -{ +void G_StopCinematicSkip(void) { gi.cvar_set("skippingCinematic", "0"); gi.cvar_set("timescale", "1"); } -void G_StartCinematicSkip( void ) -{ - - if (cinematicSkipScript[0]) - { - ICARUS_RunScript( &g_entities[0], va( "%s/%s", Q3_SCRIPT_DIR, cinematicSkipScript ) ); - memset( cinematicSkipScript, 0, sizeof( cinematicSkipScript ) ); +void G_StartCinematicSkip(void) { + + if (cinematicSkipScript[0]) { + ICARUS_RunScript(&g_entities[0], va("%s/%s", Q3_SCRIPT_DIR, cinematicSkipScript)); + memset(cinematicSkipScript, 0, sizeof(cinematicSkipScript)); gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); - } - else - { + } else { // no... so start skipping... gi.cvar_set("skippingCinematic", "1"); gi.cvar_set("timescale", "100"); } } -void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( !ent || !ent->client || ent->health <= 0 ) - { +void G_CheckClientIdle(gentity_t *ent, usercmd_t *ucmd) { + if (!ent || !ent->client || ent->health <= 0) { return; } - if ( !ent->s.number && ( !cg.renderingThirdPerson || cg.zoomMode ) ) - { - if ( ent->client->idleTime < level.time ) - { + if (!ent->s.number && (!cg.renderingThirdPerson || cg.zoomMode)) { + if (ent->client->idleTime < level.time) { ent->client->idleTime = level.time; } return; } - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || !PM_StandingAnim( ent->client->ps.legsAnim ) - || ent->enemy - || ent->client->ps.legsAnimTimer - || ent->client->ps.torsoAnimTimer ) - {//FIXME: also check for turning? - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || ent->enemy ) - { - //if in an idle, break out - switch ( ent->client->ps.legsAnim ) - { + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || + !PM_StandingAnim(ent->client->ps.legsAnim) || ent->enemy || ent->client->ps.legsAnimTimer || + ent->client->ps.torsoAnimTimer) { // FIXME: also check for turning? + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || ucmd->buttons || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || ent->enemy) { + // if in an idle, break out + switch (ent->client->ps.legsAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -1884,8 +1609,7 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) ent->client->ps.legsAnimTimer = 0; break; } - switch ( ent->client->ps.torsoAnim ) - { + switch (ent->client->ps.torsoAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -1896,21 +1620,17 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) } } // - if ( ent->client->idleTime < level.time ) - { + if (ent->client->idleTime < level.time) { ent->client->idleTime = level.time; } - } - else if ( level.time - ent->client->idleTime > 5000 ) - {//been idle for 5 seconds - int idleAnim = -1; - switch ( ent->client->ps.legsAnim ) - { + } else if (level.time - ent->client->idleTime > 5000) { // been idle for 5 seconds + int idleAnim = -1; + switch (ent->client->ps.legsAnim) { case BOTH_STAND1: idleAnim = BOTH_STAND1IDLE1; break; case BOTH_STAND2: - idleAnim = Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); + idleAnim = Q_irand(BOTH_STAND2IDLE1, BOTH_STAND2IDLE2); break; case BOTH_STAND3: idleAnim = BOTH_STAND3IDLE1; @@ -1919,50 +1639,42 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) idleAnim = BOTH_STAND4IDLE1; break; } - if ( idleAnim != -1 && PM_HasAnimation( ent, idleAnim ) ) - { - NPC_SetAnim( ent, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //don't idle again after this anim for a while - ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); + if (idleAnim != -1 && PM_HasAnimation(ent, idleAnim)) { + NPC_SetAnim(ent, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // don't idle again after this anim for a while + ent->client->idleTime = level.time + PM_AnimLength(ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim) + Q_irand(0, 2000); } } } -void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client ) - { - if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir - || ucmd->forwardmove || ucmd->rightmove//moving using ucmds - || (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move - || (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move +void G_CheckMovingLoopingSounds(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client) { + if ((ent->NPC && !VectorCompare(vec3_origin, ent->client->ps.moveDir)) // moving using moveDir + || ucmd->forwardmove || ucmd->rightmove // moving using ucmds + || (ucmd->upmove && FlyingCreature(ent)) // flier using ucmds to move + || (FlyingCreature(ent) && !VectorCompare(vec3_origin, ent->client->ps.velocity) && ent->health > 0)) // flier using velocity to move { - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_R2D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); break; case CLASS_R5D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); break; case CLASS_MARK2: - ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); break; case CLASS_MOUSE: - ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); break; case CLASS_PROBE: - ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + ent->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); default: break; } - } - else - {//not moving under your own control, stop loopSound - if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_PROBE ) - { + } else { // not moving under your own control, stop loopSound + if (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_MARK2 || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_PROBE) { ent->s.loopSound = 0; } } @@ -1979,336 +1691,253 @@ usually be a couple times for each server frame on fast clients. ============== */ -extern int G_FindLocalInterestPoint( gentity_t *self ); -void ClientThink_real( gentity_t *ent, usercmd_t *ucmd ) -{ - gclient_t *client; - pmove_t pm; - vec3_t oldOrigin; - int oldEventSequence; - int msec; - qboolean inSpinFlipAttack = PM_AdjustAnglesForSpinningFlip( ent, ucmd, qfalse ); - qboolean controlledByPlayer = qfalse; - - //Don't let the player do anything if in a camera - if ( ent->s.number == 0 ) - { -extern cvar_t *g_skippingcin; - - if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { - G_UpdateEmplacedWeaponData( ent ); - RunEmplacedWeapon( ent, &ucmd ); - } - if ( ent->client->ps.saberLockTime > level.time && ent->client->ps.saberLockEnemy != ENTITYNUM_NONE ) - { - NPC_SetLookTarget( ent, ent->client->ps.saberLockEnemy, level.time+1000 ); - } - if ( ent->client->renderInfo.lookTargetClearTime < level.time //NOTE: here this is used as a debounce, not an actual timer - && ent->health > 0 //must be alive - && (!ent->enemy || ent->client->ps.saberMove != LS_A_BACKSTAB) )//don't update if in backstab unless don't currently have an enemy - {//NOTE: doesn't keep updating to nearest enemy once you're dead - int newLookTarget; - if ( !G_ValidateLookEnemy( ent, ent->enemy ) ) - { +extern int G_FindLocalInterestPoint(gentity_t *self); +void ClientThink_real(gentity_t *ent, usercmd_t *ucmd) { + gclient_t *client; + pmove_t pm; + vec3_t oldOrigin; + int oldEventSequence; + int msec; + qboolean inSpinFlipAttack = PM_AdjustAnglesForSpinningFlip(ent, ucmd, qfalse); + qboolean controlledByPlayer = qfalse; + + // Don't let the player do anything if in a camera + if (ent->s.number == 0) { + extern cvar_t *g_skippingcin; + + if (ent->s.eFlags & EF_LOCKED_TO_WEAPON) { + G_UpdateEmplacedWeaponData(ent); + RunEmplacedWeapon(ent, &ucmd); + } + if (ent->client->ps.saberLockTime > level.time && ent->client->ps.saberLockEnemy != ENTITYNUM_NONE) { + NPC_SetLookTarget(ent, ent->client->ps.saberLockEnemy, level.time + 1000); + } + if (ent->client->renderInfo.lookTargetClearTime < level.time // NOTE: here this is used as a debounce, not an actual timer + && ent->health > 0 // must be alive + && (!ent->enemy || ent->client->ps.saberMove != LS_A_BACKSTAB)) // don't update if in backstab unless don't currently have an enemy + { // NOTE: doesn't keep updating to nearest enemy once you're dead + int newLookTarget; + if (!G_ValidateLookEnemy(ent, ent->enemy)) { ent->enemy = NULL; } - //FIXME: make this a little prescient? - G_ChooseLookEnemy( ent, ucmd ); - if ( ent->enemy ) - {//target + // FIXME: make this a little prescient? + G_ChooseLookEnemy(ent, ucmd); + if (ent->enemy) { // target newLookTarget = ent->enemy->s.number; - //so we don't change our minds in the next 1 second - ent->client->renderInfo.lookTargetClearTime = level.time+1000; + // so we don't change our minds in the next 1 second + ent->client->renderInfo.lookTargetClearTime = level.time + 1000; ent->client->renderInfo.lookMode = LM_ENT; - } - else - {//no target - //FIXME: what about sightalerts and missiles? + } else { // no target + // FIXME: what about sightalerts and missiles? newLookTarget = ENTITYNUM_NONE; - newLookTarget = G_FindLocalInterestPoint( ent ); - if ( newLookTarget != ENTITYNUM_NONE ) - {//found something of interest + newLookTarget = G_FindLocalInterestPoint(ent); + if (newLookTarget != ENTITYNUM_NONE) { // found something of interest ent->client->renderInfo.lookMode = LM_INTEREST; - } - else - {//okay, no interesting things and no enemies, so look for items - newLookTarget = G_FindLookItem( ent ); + } else { // okay, no interesting things and no enemies, so look for items + newLookTarget = G_FindLookItem(ent); ent->client->renderInfo.lookMode = LM_ENT; } } - if ( ent->client->renderInfo.lookTarget != newLookTarget ) - {//transitioning - NPC_SetLookTarget( ent, newLookTarget, level.time+1000 ); + if (ent->client->renderInfo.lookTarget != newLookTarget) { // transitioning + NPC_SetLookTarget(ent, newLookTarget, level.time + 1000); } } - if ( in_camera ) - { + if (in_camera) { // watch the code here, you MUST "return" within this IF(), *unless* you're stopping the cinematic skip. // - if ( ClientCinematicThink(ent->client) ) - { - if (g_skippingcin->integer) // already doing cinematic skip? - {// yes... so stop skipping... + if (ClientCinematicThink(ent->client)) { + if (g_skippingcin->integer) // already doing cinematic skip? + { // yes... so stop skipping... G_StopCinematicSkip(); - } - else - {// no... so start skipping... + } else { // no... so start skipping... G_StartCinematicSkip(); return; } - } - else - { + } else { return; } - } - else if ( ent->client->ps.vehicleModel != 0 && ent->health > 0 ) - { + } else if (ent->client->ps.vehicleModel != 0 && ent->health > 0) { float speed; - speed = VectorLength( ent->client->ps.velocity ); - if ( speed && ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { - int diff = AngleNormalize180(SHORT2ANGLE(ucmd->angles[YAW]+ent->client->ps.delta_angles[YAW]) - floor(ent->client->ps.viewangles[YAW])); - int slide = floor(((float)(diff))/120.0f*-127.0f); - - if ( (slide > 0 && ucmd->rightmove >= 0) || ((slide < 0 && ucmd->rightmove <= 0)) ) - {//note: don't want these to conflict right now because that seems to feel really weird - //gi.Printf( "slide %i, diff %i, yaw %i\n", slide, diff, ucmd->angles[YAW] ); + speed = VectorLength(ent->client->ps.velocity); + if (speed && ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { + int diff = AngleNormalize180(SHORT2ANGLE(ucmd->angles[YAW] + ent->client->ps.delta_angles[YAW]) - floor(ent->client->ps.viewangles[YAW])); + int slide = floor(((float)(diff)) / 120.0f * -127.0f); + + if ((slide > 0 && ucmd->rightmove >= 0) || + ((slide < 0 && ucmd->rightmove <= 0))) { // note: don't want these to conflict right now because that seems to feel really weird + // gi.Printf( "slide %i, diff %i, yaw %i\n", slide, diff, ucmd->angles[YAW] ); ucmd->rightmove += slide; } - if ( ucmd->rightmove > 64 ) - { + if (ucmd->rightmove > 64) { ucmd->rightmove = 64; - } - else if ( ucmd->rightmove < -64 ) - { + } else if (ucmd->rightmove < -64) { ucmd->rightmove = -64; } - } - else - { + } else { ucmd->rightmove = 0; ucmd->angles[PITCH] = 0; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; } - } - else - { - if ( g_skippingcin->integer ) - {//We're skipping the cinematic and it's over now + } else { + if (g_skippingcin->integer) { // We're skipping the cinematic and it's over now gi.cvar_set("timescale", "1"); gi.cvar_set("skippingCinematic", "0"); } - if ( ent->client->ps.pm_type == PM_DEAD && cg.missionStatusDeadTime < level.time ) - {//mission status screen is up because player is dead, stop all scripts + if (ent->client->ps.pm_type == PM_DEAD && + cg.missionStatusDeadTime < level.time) { // mission status screen is up because player is dead, stop all scripts stop_icarus = qtrue; } } -// // Don't allow the player to adjust the pitch when they are in third person overhead cam. -//extern vmCvar_t cg_thirdPerson; -// if ( cg_thirdPerson.integer == 2 ) -// { -// ucmd->angles[PITCH] = 0; -// } + // // Don't allow the player to adjust the pitch when they are in third person overhead cam. + // extern vmCvar_t cg_thirdPerson; + // if ( cg_thirdPerson.integer == 2 ) + // { + // ucmd->angles[PITCH] = 0; + // } - if ( cg.zoomMode == 2 ) - { + if (cg.zoomMode == 2) { // Any kind of movement when the player is NOT ducked when the disruptor gun is zoomed will cause us to auto-magically un-zoom - if ( ( (ucmd->forwardmove||ucmd->rightmove) - && ucmd->upmove >= 0 //crouching-moving is ok - && !(ucmd->buttons&BUTTON_USE)/*leaning is ok*/ - ) - || ucmd->upmove > 0 //jumping not allowed - ) - { + if (((ucmd->forwardmove || ucmd->rightmove) && ucmd->upmove >= 0 // crouching-moving is ok + && !(ucmd->buttons & BUTTON_USE) /*leaning is ok*/ + ) || + ucmd->upmove > 0 // jumping not allowed + ) { // already zooming, so must be wanting to turn it off - G_Sound( ent, G_SoundIndex( "sound/weapons/disruptor/zoomend.wav" )); + G_Sound(ent, G_SoundIndex("sound/weapons/disruptor/zoomend.wav")); cg.zoomMode = 0; cg.zoomTime = cg.time; cg.zoomLocked = qfalse; } } - if ( (player_locked || (ent->client->ps.eFlags&EF_FORCE_GRIPPED)) && ent->client->ps.pm_type < PM_DEAD ) // unless dead - {//lock out player control - if ( !player_locked ) - { - VectorClearM( ucmd->angles ); + if ((player_locked || (ent->client->ps.eFlags & EF_FORCE_GRIPPED)) && ent->client->ps.pm_type < PM_DEAD) // unless dead + { // lock out player control + if (!player_locked) { + VectorClearM(ucmd->angles); } ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->buttons = 0; ucmd->upmove = 0; - PM_AdjustAnglesToGripper( ent, ucmd ); + PM_AdjustAnglesToGripper(ent, ucmd); } - if ( ent->client->ps.leanofs ) - {//no shooting while leaning + if (ent->client->ps.leanofs) { // no shooting while leaning ucmd->buttons &= ~BUTTON_ATTACK; - if ( ent->client->ps.weapon != WP_DISRUPTOR ) - {//can still zoom around corners + if (ent->client->ps.weapon != WP_DISRUPTOR) { // can still zoom around corners ucmd->buttons &= ~BUTTON_ALT_ATTACK; } } - } - else - { - if ( ent->s.eFlags & EF_LOCKED_TO_WEAPON ) - { - G_UpdateEmplacedWeaponData( ent ); + } else { + if (ent->s.eFlags & EF_LOCKED_TO_WEAPON) { + G_UpdateEmplacedWeaponData(ent); } - if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) - { + if (player && player->client && player->client->ps.viewEntity == ent->s.number) { controlledByPlayer = qtrue; int sav_weapon = ucmd->weapon; - memcpy( ucmd, &player->client->usercmd, sizeof( usercmd_t ) ); + memcpy(ucmd, &player->client->usercmd, sizeof(usercmd_t)); ucmd->weapon = sav_weapon; ent->client->usercmd = *ucmd; } - G_NPCMunroMatchPlayerWeapon( ent ); + G_NPCMunroMatchPlayerWeapon(ent); } - if ( ent->client ) - { - if ( ent->client->NPC_class == CLASS_GONK || - ent->client->NPC_class == CLASS_MOUSE || - ent->client->NPC_class == CLASS_R2D2 || - ent->client->NPC_class == CLASS_R5D2 ) - {//no jumping or strafing in these guys + if (ent->client) { + if (ent->client->NPC_class == CLASS_GONK || ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_R2D2 || + ent->client->NPC_class == CLASS_R5D2) { // no jumping or strafing in these guys ucmd->upmove = ucmd->rightmove = 0; - } - else if ( ent->client->NPC_class == CLASS_ATST ) - {//no jumping in atst - if (ent->client->ps.pm_type != PM_NOCLIP) - { + } else if (ent->client->NPC_class == CLASS_ATST) { // no jumping in atst + if (ent->client->ps.pm_type != PM_NOCLIP) { ucmd->upmove = 0; } - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//ATST crushed anything underneath it - gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; - if ( under && under->health && under->takedamage ) - { - vec3_t down = {0,0,-1}; - //FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin - G_Damage( under, ent, ent, down, under->currentOrigin, 100, 0, MOD_CRUSH ); + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // ATST crushed anything underneath it + gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; + if (under && under->health && under->takedamage) { + vec3_t down = {0, 0, -1}; + // FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin + G_Damage(under, ent, ent, down, under->currentOrigin, 100, 0, MOD_CRUSH); } - //so they know to run like hell when I get close - //FIXME: project this in the direction I'm moving? - if ( !Q_irand( 0, 10 ) ) - {//not so often... - AddSoundEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER ); - AddSightEvent( ent, ent->currentOrigin, ent->maxs[1]*5, AEL_DANGER, 100 ); + // so they know to run like hell when I get close + // FIXME: project this in the direction I'm moving? + if (!Q_irand(0, 10)) { // not so often... + AddSoundEvent(ent, ent->currentOrigin, ent->maxs[1] * 5, AEL_DANGER); + AddSightEvent(ent, ent->currentOrigin, ent->maxs[1] * 5, AEL_DANGER, 100); } } - } - else if ( ent->client->ps.groundEntityNum < ENTITYNUM_WORLD && !ent->client->ps.forceJumpCharge ) - {//standing on an entity and not currently force jumping + } else if (ent->client->ps.groundEntityNum < ENTITYNUM_WORLD && + !ent->client->ps.forceJumpCharge) { // standing on an entity and not currently force jumping gentity_t *groundEnt = &g_entities[ent->client->ps.groundEntityNum]; - if ( groundEnt && - groundEnt->client && - groundEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && - groundEnt->health > 0 && - !PM_InRoll( &groundEnt->client->ps ) - && !(groundEnt->client->ps.eFlags&EF_LOCKED_TO_WEAPON) - && !inSpinFlipAttack ) - {//landed on a live client who is on the ground, jump off them and knock them down - if ( ent->health > 0 ) - { - if ( !PM_InRoll( &ent->client->ps ) - && !PM_FlippingAnim( ent->client->ps.legsAnim ) ) - { - if ( ent->s.number && ent->s.weapon == WP_SABER ) - { - ent->client->ps.forceJumpCharge = 320;//FIXME: calc this intelligently? - } - else if ( !ucmd->upmove ) - {//if not ducking (which should cause a roll), then jump + if (groundEnt && groundEnt->client && groundEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && groundEnt->health > 0 && + !PM_InRoll(&groundEnt->client->ps) && !(groundEnt->client->ps.eFlags & EF_LOCKED_TO_WEAPON) && + !inSpinFlipAttack) { // landed on a live client who is on the ground, jump off them and knock them down + if (ent->health > 0) { + if (!PM_InRoll(&ent->client->ps) && !PM_FlippingAnim(ent->client->ps.legsAnim)) { + if (ent->s.number && ent->s.weapon == WP_SABER) { + ent->client->ps.forceJumpCharge = 320; // FIXME: calc this intelligently? + } else if (!ucmd->upmove) { // if not ducking (which should cause a roll), then jump ucmd->upmove = 127; } - if ( !ucmd->forwardmove && !ucmd->rightmove ) - {// If not moving, don't want to jump straight up - //FIXME: trace for clear di? - if ( !Q_irand( 0, 3 ) ) - { + if (!ucmd->forwardmove && !ucmd->rightmove) { // If not moving, don't want to jump straight up + // FIXME: trace for clear di? + if (!Q_irand(0, 3)) { ucmd->forwardmove = 127; - } - else if ( !Q_irand( 0, 3 ) ) - { + } else if (!Q_irand(0, 3)) { ucmd->forwardmove = -127; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { ucmd->rightmove = 127; - } - else - { + } else { ucmd->rightmove = -127; } } - if ( !ent->s.number && ucmd->upmove < 0 ) - {//player who should roll- force it - int rollAnim = BOTH_ROLL_F; - if ( ucmd->forwardmove >= 0 ) - { + if (!ent->s.number && ucmd->upmove < 0) { // player who should roll- force it + int rollAnim = BOTH_ROLL_F; + if (ucmd->forwardmove >= 0) { rollAnim = BOTH_ROLL_F; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { rollAnim = BOTH_ROLL_B; - } - else if ( ucmd->rightmove > 0 ) - { + } else if (ucmd->rightmove > 0) { rollAnim = BOTH_ROLL_R; - } - else if ( ucmd->rightmove < 0 ) - { + } else if (ucmd->rightmove < 0) { rollAnim = BOTH_ROLL_L; } - NPC_SetAnim(ent,SETANIM_BOTH,rollAnim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - G_AddEvent( ent, EV_ROLL, 0 ); + NPC_SetAnim(ent, SETANIM_BOTH, rollAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(ent, EV_ROLL, 0); ent->client->ps.saberMove = LS_NONE; } } - } - else - {//a corpse? Shit - //Hmm, corpses should probably *always* knockdown... + } else { // a corpse? Shit + // Hmm, corpses should probably *always* knockdown... ent->clipmask &= ~CONTENTS_BODY; } - //FIXME: need impact sound event - GEntity_PainFunc( groundEnt, ent, ent, groundEnt->currentOrigin, 0, MOD_CRUSH ); - if ( groundEnt->client->NPC_class == CLASS_DESANN && ent->client->NPC_class != CLASS_LUKE ) - {//can't knock down desann unless you're luke - //FIXME: should he smack you away like Galak Mech? - } - else if ( - ( ( (groundEnt->s.number&&(groundEnt->s.weapon!=WP_SABER||!groundEnt->NPC||groundEnt->NPC->ranks.number||G_ControlledByPlayer(groundEnt)) && !Q_irand( 0, 3 )&&cg.renderingThirdPerson&&!cg.zoomMode) )//or a player in third person, 25% of the time - && groundEnt->client->playerTeam != ent->client->playerTeam ) //and not on the same team - || ent->client->NPC_class == CLASS_DESANN )//desann always knocks people down + // FIXME: need impact sound event + GEntity_PainFunc(groundEnt, ent, ent, groundEnt->currentOrigin, 0, MOD_CRUSH); + if (groundEnt->client->NPC_class == CLASS_DESANN && ent->client->NPC_class != CLASS_LUKE) { // can't knock down desann unless you're luke + // FIXME: should he smack you away like Galak Mech? + } else if ((((groundEnt->s.number && + (groundEnt->s.weapon != WP_SABER || !groundEnt->NPC || + groundEnt->NPC->rank < + Q_irand(RANK_CIVILIAN, RANK_CAPTAIN + 1))) // an NPC who is either not a saber user or passed the rank-based probability test + || ((!ent->s.number || G_ControlledByPlayer(groundEnt)) && !Q_irand(0, 3) && cg.renderingThirdPerson && + !cg.zoomMode)) // or a player in third person, 25% of the time + && groundEnt->client->playerTeam != ent->client->playerTeam) // and not on the same team + || ent->client->NPC_class == CLASS_DESANN) // desann always knocks people down { int knockAnim = BOTH_KNOCKDOWN1; - if ( PM_CrouchAnim( groundEnt->client->ps.legsAnim ) ) - {//knockdown from crouch + if (PM_CrouchAnim(groundEnt->client->ps.legsAnim)) { // knockdown from crouch knockAnim = BOTH_KNOCKDOWN4; - } - else - { - vec3_t gEFwd, gEAngles = {0,groundEnt->client->ps.viewangles[YAW],0}; - AngleVectors( gEAngles, gEFwd, NULL, NULL ); - if ( DotProduct( ent->client->ps.velocity, gEFwd ) > 50 ) - {//pushing him forward + } else { + vec3_t gEFwd, gEAngles = {0, groundEnt->client->ps.viewangles[YAW], 0}; + AngleVectors(gEAngles, gEFwd, NULL, NULL); + if (DotProduct(ent->client->ps.velocity, gEFwd) > 50) { // pushing him forward knockAnim = BOTH_KNOCKDOWN3; } } - NPC_SetAnim( groundEnt, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(groundEnt, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } } - client = ent->client; // mark the time, so the connection sprite can be removed @@ -2316,249 +1945,179 @@ extern cvar_t *g_skippingcin; client->pers.lastCommand = *ucmd; // sanity check the command time to prevent speedup cheating - if ( ucmd->serverTime > level.time + 200 ) - { + if (ucmd->serverTime > level.time + 200) { ucmd->serverTime = level.time + 200; } - if ( ucmd->serverTime < level.time - 1000 ) - { + if (ucmd->serverTime < level.time - 1000) { ucmd->serverTime = level.time - 1000; - } + } msec = ucmd->serverTime - client->ps.commandTime; - if ( msec < 1 ) - { + if (msec < 1) { msec = 1; } - if ( msec > 200 ) - { + if (msec > 200) { msec = 200; } // check for inactivity timer, but never drop the local client of a non-dedicated server - if ( !ClientInactivityTimer( client ) ) + if (!ClientInactivityTimer(client)) return; - if ( client->noclip ) - { + if (client->noclip) { client->ps.pm_type = PM_NOCLIP; - } - else if ( client->ps.stats[STAT_HEALTH] <= 0 ) - { + } else if (client->ps.stats[STAT_HEALTH] <= 0) { client->ps.pm_type = PM_DEAD; - } - else - { + } else { client->ps.pm_type = PM_NORMAL; } - //FIXME: if global gravity changes this should update everyone's personal gravity... - if ( !(ent->svFlags & SVF_CUSTOM_GRAVITY) ) - { + // FIXME: if global gravity changes this should update everyone's personal gravity... + if (!(ent->svFlags & SVF_CUSTOM_GRAVITY)) { client->ps.gravity = g_gravity->value; } // set speed - if ( ent->NPC != NULL ) - {//we don't actually scale the ucmd, we use actual speeds - if ( ent->NPC->combatMove == qfalse ) - { - if ( !(ucmd->buttons & BUTTON_USE) ) - {//Not leaning + if (ent->NPC != NULL) { // we don't actually scale the ucmd, we use actual speeds + if (ent->NPC->combatMove == qfalse) { + if (!(ucmd->buttons & BUTTON_USE)) { // Not leaning qboolean Flying = (qboolean)(ucmd->upmove && ent->NPC->stats.moveType == MT_FLYSWIM); qboolean Climbing = (qboolean)(ucmd->upmove && (ent->watertype & CONTENTS_LADDER)); client->ps.friction = 6; - if ( ucmd->forwardmove || ucmd->rightmove || Flying ) - { - //if ( ent->NPC->behaviorState != BS_FORMATION ) - {//In - Formation NPCs set thier desiredSpeed themselves - if ( ucmd->buttons & BUTTON_WALKING ) + if (ucmd->forwardmove || ucmd->rightmove || Flying) { + // if ( ent->NPC->behaviorState != BS_FORMATION ) + { // In - Formation NPCs set thier desiredSpeed themselves + if (ucmd->buttons & BUTTON_WALKING) { + ent->NPC->desiredSpeed = NPC_GetWalkSpeed(ent); // ent->NPC->stats.walkSpeed; + } else // running { - ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed; - } - else//running - { - ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed; + ent->NPC->desiredSpeed = NPC_GetRunSpeed(ent); // ent->NPC->stats.runSpeed; } - if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer ) - {//At higher speeds, need to slow down close to stuff - //Slow down as you approach your goal - if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 + if (ent->NPC->currentSpeed >= 80 && !controlledByPlayer) { // At higher speeds, need to slow down close to stuff + // Slow down as you approach your goal + if (ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags & NPCAI_NO_SLOWDOWN)) // 128 { - if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED ) - { + if (ent->NPC->desiredSpeed > MIN_NPC_SPEED) { float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST; ent->NPC->desiredSpeed = ceil(slowdownSpeed); - if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED ) - {//don't slow down too much + if (ent->NPC->desiredSpeed < MIN_NPC_SPEED) { // don't slow down too much ent->NPC->desiredSpeed = MIN_NPC_SPEED; } } } } } - } - else if ( Climbing ) - { + } else if (Climbing) { ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed; - } - else - {//We want to stop + } else { // We want to stop ent->NPC->desiredSpeed = 0; } - NPC_Accelerate( ent, qfalse, qfalse ); + NPC_Accelerate(ent, qfalse, qfalse); - if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//No-one walks this slow - client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop + if (ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // No-one walks this slow + client->ps.speed = ent->NPC->currentSpeed = 0; // Full stop ucmd->forwardmove = 0; ucmd->rightmove = 0; - } - else - { - if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed ) - {//Play the walkanim + } else { + if (ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed) { // Play the walkanim ucmd->buttons |= BUTTON_WALKING; - } - else - { + } else { ucmd->buttons &= ~BUTTON_WALKING; } - if ( ent->NPC->currentSpeed > 0 ) - {//We should be moving - if ( Climbing || Flying ) - { - if ( !ucmd->upmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove; + if (ent->NPC->currentSpeed > 0) { // We should be moving + if (Climbing || Flying) { + if (!ucmd->upmove) { // We need to force them to take a couple more steps until stopped + ucmd->upmove = ent->NPC->last_ucmd.upmove; // was last_upmove; } - } - else if ( !ucmd->forwardmove && !ucmd->rightmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove; - ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove; + } else if (!ucmd->forwardmove && !ucmd->rightmove) { // We need to force them to take a couple more steps until stopped + ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove; // was last_forwardmove; + ucmd->rightmove = ent->NPC->last_ucmd.rightmove; // was last_rightmove; } } client->ps.speed = ent->NPC->currentSpeed; - if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) - { - } - else - { - //Slow down on turns - don't orbit!!! - float turndelta = 0; - // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw - if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... - { - turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180; - } - else + if (player && player->client && player->client->ps.viewEntity == ent->s.number) { + } else { + // Slow down on turns - don't orbit!!! + float turndelta = 0; + // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always + // thinks it trying to turn according to desiredYaw + if (client->renderInfo.renderFlags & RF_LOCKEDANGLE) // yeah I know the RF_ flag is a pretty ugly hack... { - turndelta = (180 - fabs( AngleDelta( ent->currentAngles[YAW], ent->NPC->desiredYaw ) ))/180; + turndelta = (180 - fabs(AngleDelta(ent->currentAngles[YAW], ent->NPC->lockedDesiredYaw))) / 180; + } else { + turndelta = (180 - fabs(AngleDelta(ent->currentAngles[YAW], ent->NPC->desiredYaw))) / 180; } - - if ( turndelta < 0.75f ) - { + + if (turndelta < 0.75f) { client->ps.speed = 0; - } - else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 ) - {//Turn is greater than 45 degrees or closer than 100 to goal - client->ps.speed = floor(((float)(client->ps.speed))*turndelta); + } else if (ent->NPC->distToGoal < 100 && turndelta < 1.0) { // Turn is greater than 45 degrees or closer than 100 to goal + client->ps.speed = floor(((float)(client->ps.speed)) * turndelta); } } } } - } - else - { - ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent ); + } else { + ent->NPC->desiredSpeed = (ucmd->buttons & BUTTON_WALKING) ? NPC_GetWalkSpeed(ent) : NPC_GetRunSpeed(ent); client->ps.speed = ent->NPC->desiredSpeed; } - } - else - {//Client sets ucmds and such for speed alterations - if ( ent->client->ps.vehicleModel != 0 && ent->health > 0 ) - { - if ( client->ps.speed || client->ps.groundEntityNum == ENTITYNUM_NONE || ucmd->forwardmove > 0 || ucmd->upmove > 0) - { - if ( ucmd->forwardmove > 0 ) - { + } else { // Client sets ucmds and such for speed alterations + if (ent->client->ps.vehicleModel != 0 && ent->health > 0) { + if (client->ps.speed || client->ps.groundEntityNum == ENTITYNUM_NONE || ucmd->forwardmove > 0 || ucmd->upmove > 0) { + if (ucmd->forwardmove > 0) { client->ps.speed += 20; - } - else if ( ucmd->forwardmove < 0 ) - { - if ( client->ps.speed > 800 ) - { + } else if (ucmd->forwardmove < 0) { + if (client->ps.speed > 800) { client->ps.speed -= 20; - } - else - { + } else { client->ps.speed -= 5; } - } - else - {//accelerate to cruising speed only, otherwise, just coast - if ( client->ps.speed < 800 ) - { + } else { // accelerate to cruising speed only, otherwise, just coast + if (client->ps.speed < 800) { client->ps.speed += 10; - if ( client->ps.speed > 800 ) - { + if (client->ps.speed > 800) { client->ps.speed = 800; } } } ucmd->forwardmove = 127; - } - else - { - if ( ucmd->forwardmove < 0 ) - { + } else { + if (ucmd->forwardmove < 0) { ucmd->forwardmove = 0; } - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } ucmd->rightmove = 0; } - if ( client->ps.speed > 3000 ) - { + if (client->ps.speed > 3000) { client->ps.speed = 3000; - } - else if ( client->ps.speed < 0 ) - { + } else if (client->ps.speed < 0) { client->ps.speed = 0; } - if ( client->ps.speed < 800 ) - { - client->ps.gravity = (800 - client->ps.speed)/4; - } - else - { + if (client->ps.speed < 800) { + client->ps.gravity = (800 - client->ps.speed) / 4; + } else { client->ps.gravity = 0; } - } - else - { - client->ps.speed = g_speed->value;//default is 320 + } else { + client->ps.speed = g_speed->value; // default is 320 /*if ( !ent->s.number && ent->painDebounceTime>level.time ) { client->ps.speed *= 0.25f; } - else */if ( PM_SaberInAttack( ent->client->ps.saberMove ) && ucmd->forwardmove < 0 ) - {//if running backwards while attacking, don't run as fast. - switch( client->ps.saberAnimLevel ) - { + else */ + if (PM_SaberInAttack(ent->client->ps.saberMove) && ucmd->forwardmove < 0) { // if running backwards while attacking, don't run as fast. + switch (client->ps.saberAnimLevel) { case FORCE_LEVEL_1: client->ps.speed *= 0.75f; break; @@ -2569,24 +2128,17 @@ extern cvar_t *g_skippingcin; client->ps.speed *= 0.45f; break; } - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } - } - else if ( PM_SpinningSaberAnim( client->ps.legsAnim ) ) - { + } else if (PM_SpinningSaberAnim(client->ps.legsAnim)) { client->ps.speed *= 0.5f; - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } - } - else if ( client->ps.weapon == WP_SABER && ( ucmd->buttons & BUTTON_ATTACK ) ) - {//if attacking with saber while running, drop your speed - //FIXME: should be weaponTime? Or in certain anims? - switch( client->ps.saberAnimLevel ) - { + } else if (client->ps.weapon == WP_SABER && (ucmd->buttons & BUTTON_ATTACK)) { // if attacking with saber while running, drop your speed + // FIXME: should be weaponTime? Or in certain anims? + switch (client->ps.saberAnimLevel) { case FORCE_LEVEL_2: client->ps.speed *= 0.85f; break; @@ -2594,235 +2146,193 @@ extern cvar_t *g_skippingcin; client->ps.speed *= 0.70f; break; } - if ( g_saberMoveSpeed->value != 1.0f ) - { + if (g_saberMoveSpeed->value != 1.0f) { client->ps.speed *= g_saberMoveSpeed->value; } } } } - if ( client->NPC_class == CLASS_ATST && client->ps.legsAnim == BOTH_RUN1START ) - {//HACK: when starting to move as atst, ramp up speed - //float animLength = PM_AnimLength( client->clientInfo.animFileIndex, (animNumber_t)client->ps.legsAnim); - //client->ps.speed *= ( animLength - client->ps.legsAnimTimer)/animLength; - if ( client->ps.legsAnimTimer > 100 ) - { + if (client->NPC_class == CLASS_ATST && client->ps.legsAnim == BOTH_RUN1START) { // HACK: when starting to move as atst, ramp up speed + // float animLength = PM_AnimLength( client->clientInfo.animFileIndex, (animNumber_t)client->ps.legsAnim); + // client->ps.speed *= ( animLength - client->ps.legsAnimTimer)/animLength; + if (client->ps.legsAnimTimer > 100) { client->ps.speed = 0; } } - //Apply forced movement - if ( client->forced_forwardmove ) - { + // Apply forced movement + if (client->forced_forwardmove) { ucmd->forwardmove = client->forced_forwardmove; - if ( !client->ps.speed ) - { - if ( ent->NPC != NULL ) - { + if (!client->ps.speed) { + if (ent->NPC != NULL) { client->ps.speed = ent->NPC->stats.runSpeed; - } - else - { - client->ps.speed = g_speed->value;//default is 320 + } else { + client->ps.speed = g_speed->value; // default is 320 } } } - if ( client->forced_rightmove ) - { + if (client->forced_rightmove) { ucmd->rightmove = client->forced_rightmove; - if ( !client->ps.speed ) - { - if ( ent->NPC != NULL ) - { + if (!client->ps.speed) { + if (ent->NPC != NULL) { client->ps.speed = ent->NPC->stats.runSpeed; - } - else - { - client->ps.speed = g_speed->value;//default is 320 + } else { + client->ps.speed = g_speed->value; // default is 320 } } } - if ( ucmd->forwardmove < 0 && !(ucmd->buttons&BUTTON_WALKING) && client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//running backwards is slower than running forwards + if (ucmd->forwardmove < 0 && !(ucmd->buttons & BUTTON_WALKING) && + client->ps.groundEntityNum != ENTITYNUM_NONE) { // running backwards is slower than running forwards client->ps.speed *= 0.75; } - //FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) - BG_AddPushVecToUcmd( ent, ucmd ); + // FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) + BG_AddPushVecToUcmd(ent, ucmd); - G_CheckClampUcmd( ent, ucmd ); + G_CheckClampUcmd(ent, ucmd); - if ( (ucmd->buttons&BUTTON_BLOCKING) && !g_saberAutoBlocking->integer ) - {//blocking with saber + if ((ucmd->buttons & BUTTON_BLOCKING) && !g_saberAutoBlocking->integer) { // blocking with saber ent->client->ps.saberBlockingTime = level.time + FRAMETIME; } - WP_ForcePowersUpdate( ent, ucmd ); - //if we have the saber in hand, check for starting a block to reflect shots - WP_SaberStartMissileBlockCheck( ent, ucmd ); + WP_ForcePowersUpdate(ent, ucmd); + // if we have the saber in hand, check for starting a block to reflect shots + WP_SaberStartMissileBlockCheck(ent, ucmd); // Update the position of the saber, and check to see if we're throwing it - if ( client->ps.saberEntityNum != ENTITYNUM_NONE ) - { + if (client->ps.saberEntityNum != ENTITYNUM_NONE) { int updates = 1; - if ( ent->NPC ) - { - updates = 3;//simulate player update rate? + if (ent->NPC) { + updates = 3; // simulate player update rate? } - for ( int update = 0; update < updates; update++ ) - { - WP_SaberUpdate( ent, ucmd ); + for (int update = 0; update < updates; update++) { + WP_SaberUpdate(ent, ucmd); } } - //NEED to do this every frame, since these overrides do not go into the save/load data - if ( ent->client->ps.vehicleModel != 0 ) - { - cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_FOV); + // NEED to do this every frame, since these overrides do not go into the save/load data + if (ent->client->ps.vehicleModel != 0) { + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_FOV); cg.overrides.thirdPersonRange = 240; cg.overrides.fov = 100; - } - else if ( client->ps.eFlags&EF_IN_ATST ) - { - cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_VOF); + } else if (client->ps.eFlags & EF_IN_ATST) { + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_POF | CG_OVERRIDE_3RD_PERSON_VOF); cg.overrides.thirdPersonRange = 240; - if ( cg_thirdPersonAutoAlpha.integer ) - { - if ( ent->health > 0 && ent->client->ps.viewangles[PITCH] < 15 && ent->client->ps.viewangles[PITCH] > 0 ) - { + if (cg_thirdPersonAutoAlpha.integer) { + if (ent->health > 0 && ent->client->ps.viewangles[PITCH] < 15 && ent->client->ps.viewangles[PITCH] > 0) { cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_APH; - if ( cg.overrides.thirdPersonAlpha > 0.525f ) - { + if (cg.overrides.thirdPersonAlpha > 0.525f) { cg.overrides.thirdPersonAlpha -= 0.025f; - } - else if ( cg.overrides.thirdPersonAlpha > 0.5f ) - { + } else if (cg.overrides.thirdPersonAlpha > 0.5f) { cg.overrides.thirdPersonAlpha = 0.5f; } - } - else if ( cg.overrides.active&CG_OVERRIDE_3RD_PERSON_APH ) - { - if ( cg.overrides.thirdPersonAlpha > cg_thirdPersonAlpha.value ) - { + } else if (cg.overrides.active & CG_OVERRIDE_3RD_PERSON_APH) { + if (cg.overrides.thirdPersonAlpha > cg_thirdPersonAlpha.value) { cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; - } - else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value-0.1f ) - { + } else if (cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value - 0.1f) { cg.overrides.thirdPersonAlpha += 0.1f; - } - else if ( cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value ) - { + } else if (cg.overrides.thirdPersonAlpha < cg_thirdPersonAlpha.value) { cg.overrides.thirdPersonAlpha = cg_thirdPersonAlpha.value; cg.overrides.active &= ~CG_OVERRIDE_3RD_PERSON_APH; } } } - if ( ent->client->ps.viewangles[PITCH] > 0 ) - { - cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; - cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-10; - if ( cg.overrides.thirdPersonVertOffset < 0 ) - { + if (ent->client->ps.viewangles[PITCH] > 0) { + cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH] * -0.75; + cg.overrides.thirdPersonVertOffset = 300 + ent->client->ps.viewangles[PITCH] * -10; + if (cg.overrides.thirdPersonVertOffset < 0) { cg.overrides.thirdPersonVertOffset = 0; } - } - else if ( ent->client->ps.viewangles[PITCH] < 0 ) - { - cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH]*-0.75; - cg.overrides.thirdPersonVertOffset = 300+ent->client->ps.viewangles[PITCH]*-5; - if ( cg.overrides.thirdPersonVertOffset > 300 ) - { + } else if (ent->client->ps.viewangles[PITCH] < 0) { + cg.overrides.thirdPersonPitchOffset = ent->client->ps.viewangles[PITCH] * -0.75; + cg.overrides.thirdPersonVertOffset = 300 + ent->client->ps.viewangles[PITCH] * -5; + if (cg.overrides.thirdPersonVertOffset > 300) { cg.overrides.thirdPersonVertOffset = 300; } - } - else - { + } else { cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonVertOffset = 200; } } - //play/stop any looping sounds tied to controlled movement - G_CheckMovingLoopingSounds( ent, ucmd ); + // play/stop any looping sounds tied to controlled movement + G_CheckMovingLoopingSounds(ent, ucmd); - //remember your last angles - VectorCopy ( ent->client->ps.viewangles, ent->lastAngles ); + // remember your last angles + VectorCopy(ent->client->ps.viewangles, ent->lastAngles); // set up for pmove oldEventSequence = client->ps.eventSequence; - memset( &pm, 0, sizeof(pm) ); + memset(&pm, 0, sizeof(pm)); pm.gent = ent; pm.ps = &client->ps; pm.cmd = *ucmd; -// pm.tracemask = MASK_PLAYERSOLID; // used differently for navgen + // pm.tracemask = MASK_PLAYERSOLID; // used differently for navgen pm.tracemask = ent->clipmask; pm.trace = gi.trace; pm.pointcontents = gi.pointcontents; pm.debugLevel = g_debugMove->integer; - pm.noFootsteps = qfalse;//( g_dmflags->integer & DF_NO_FOOTSTEPS ) > 0; + pm.noFootsteps = qfalse; //( g_dmflags->integer & DF_NO_FOOTSTEPS ) > 0; - VectorCopy( client->ps.origin, oldOrigin ); + VectorCopy(client->ps.origin, oldOrigin); // perform a pmove - Pmove( &pm ); + Pmove(&pm); // save results of pmove - if ( ent->client->ps.eventSequence != oldEventSequence ) - { + if (ent->client->ps.eventSequence != oldEventSequence) { ent->eventTime = level.time; { - int seq; + int seq; - seq = (ent->client->ps.eventSequence-1) & (MAX_PS_EVENTS-1); - ent->s.event = ent->client->ps.events[ seq ] | ( ( ent->client->ps.eventSequence & 3 ) << 8 ); - ent->s.eventParm = ent->client->ps.eventParms[ seq ]; + seq = (ent->client->ps.eventSequence - 1) & (MAX_PS_EVENTS - 1); + ent->s.event = ent->client->ps.events[seq] | ((ent->client->ps.eventSequence & 3) << 8); + ent->s.eventParm = ent->client->ps.eventParms[seq]; } } - PlayerStateToEntityState( &ent->client->ps, &ent->s ); + PlayerStateToEntityState(&ent->client->ps, &ent->s); - VectorCopy ( ent->currentOrigin, ent->lastOrigin ); + VectorCopy(ent->currentOrigin, ent->lastOrigin); #if 1 // use the precise origin for linking - VectorCopy( ent->client->ps.origin, ent->currentOrigin ); + VectorCopy(ent->client->ps.origin, ent->currentOrigin); #else - //We don't use prediction anymore, so screw this - // use the snapped origin for linking so it matches client predicted versions - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); + // We don't use prediction anymore, so screw this + // use the snapped origin for linking so it matches client predicted versions + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); #endif - //Had to leave this in, some legacy code must still be using s.angles - //Shouldn't interfere with interpolation of angles, should it? - VectorCopy( ent->client->ps.viewangles, ent->currentAngles ); + // Had to leave this in, some legacy code must still be using s.angles + // Shouldn't interfere with interpolation of angles, should it? + VectorCopy(ent->client->ps.viewangles, ent->currentAngles); - VectorCopy( pm.mins, ent->mins ); - VectorCopy( pm.maxs, ent->maxs ); + VectorCopy(pm.mins, ent->mins); + VectorCopy(pm.maxs, ent->maxs); ent->waterlevel = pm.waterlevel; ent->watertype = pm.watertype; - VectorCopyM( ucmd->angles, client->pers.cmd_angles ); + VectorCopyM(ucmd->angles, client->pers.cmd_angles); // execute client events - ClientEvents( ent, oldEventSequence ); + ClientEvents(ent, oldEventSequence); - if ( pm.useEvent ) - { - //TODO: Use - TryUse( ent ); + if (pm.useEvent) { + // TODO: Use + TryUse(ent); } // link entity now, after any personal teleporters have been used - gi.linkentity( ent ); + gi.linkentity(ent); ent->client->hiddenDist = 0; - if ( !ent->client->noclip ) - { - G_TouchTriggersLerped( ent ); + if (!ent->client->noclip) { + G_TouchTriggersLerped(ent); } // touch other objects - ClientImpacts( ent, &pm ); + ClientImpacts(ent, &pm); // swap and latch button actions client->oldbuttons = client->buttons; @@ -2830,18 +2340,16 @@ extern cvar_t *g_skippingcin; client->latched_buttons |= client->buttons & ~client->oldbuttons; // check for respawning - if ( client->ps.stats[STAT_HEALTH] <= 0 ) - { + if (client->ps.stats[STAT_HEALTH] <= 0) { // wait for the attack button to be pressed - if ( ent->NPC == NULL && level.time > client->respawnTime ) - { + if (ent->NPC == NULL && level.time > client->respawnTime) { // don't allow respawn if they are still flying through the // air, unless 10 extra seconds have passed, meaning something // strange is going on, like the corpse is caught in a wind tunnel /* - if ( level.time < client->respawnTime + 10000 ) + if ( level.time < client->respawnTime + 10000 ) { - if ( client->ps.groundEntityNum == ENTITYNUM_NONE ) + if ( client->ps.groundEntityNum == ENTITYNUM_NONE ) { return; } @@ -2849,34 +2357,22 @@ extern cvar_t *g_skippingcin; */ // pressing attack or use is the normal respawn method - if ( ucmd->buttons & ( BUTTON_ATTACK ) ) - { - respawn( ent ); -// gi.SendConsoleCommand( va("disconnect;wait;wait;wait;wait;wait;wait;devmap %s\n",level.mapname) ); - } - } - if ( ent - && !ent->s.number - && ent->enemy - && ent->enemy != ent - && ent->enemy->s.number < ENTITYNUM_WORLD - && ent->enemy->inuse - && !(cg.overrides.active&CG_OVERRIDE_3RD_PERSON_ANG) ) - {//keep facing enemy + if (ucmd->buttons & (BUTTON_ATTACK)) { + respawn(ent); + // gi.SendConsoleCommand( va("disconnect;wait;wait;wait;wait;wait;wait;devmap %s\n",level.mapname) ); + } + } + if (ent && !ent->s.number && ent->enemy && ent->enemy != ent && ent->enemy->s.number < ENTITYNUM_WORLD && ent->enemy->inuse && + !(cg.overrides.active & CG_OVERRIDE_3RD_PERSON_ANG)) { // keep facing enemy vec3_t deadDir; float deadYaw; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, deadDir ); - deadYaw = AngleNormalize180( vectoyaw ( deadDir ) ); - if ( deadYaw > ent->client->ps.stats[STAT_DEAD_YAW] + 1 ) - { + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, deadDir); + deadYaw = AngleNormalize180(vectoyaw(deadDir)); + if (deadYaw > ent->client->ps.stats[STAT_DEAD_YAW] + 1) { ent->client->ps.stats[STAT_DEAD_YAW]++; - } - else if ( deadYaw < ent->client->ps.stats[STAT_DEAD_YAW] - 1 ) - { + } else if (deadYaw < ent->client->ps.stats[STAT_DEAD_YAW] - 1) { ent->client->ps.stats[STAT_DEAD_YAW]--; - } - else - { + } else { ent->client->ps.stats[STAT_DEAD_YAW] = deadYaw; } } @@ -2884,21 +2380,21 @@ extern cvar_t *g_skippingcin; } // perform once-a-second actions - ClientTimerActions( ent, msec ); + ClientTimerActions(ent, msec); - ClientEndPowerUps( ent ); - //DEBUG INFO -/* - if ( client->ps.clientNum < 1 ) - {//Only a player - if ( ucmd->buttons & BUTTON_USE ) - { - NAV_PrintLocalWpDebugInfo( ent ); + ClientEndPowerUps(ent); + // DEBUG INFO + /* + if ( client->ps.clientNum < 1 ) + {//Only a player + if ( ucmd->buttons & BUTTON_USE ) + { + NAV_PrintLocalWpDebugInfo( ent ); + } } - } -*/ - //try some idle anims on ent if getting no input and not moving for some time - G_CheckClientIdle( ent, ucmd ); + */ + // try some idle anims on ent if getting no input and not moving for some time + G_CheckClientIdle(ent, ucmd); } /* @@ -2908,126 +2404,102 @@ ClientThink A new command has arrived from the client ================== */ -extern void PM_CheckForceUseButton( gentity_t *ent, usercmd_t *ucmd ); -extern qboolean PM_GentCantJump( gentity_t *gent ); -void ClientThink( int clientNum, usercmd_t *ucmd ) { +extern void PM_CheckForceUseButton(gentity_t *ent, usercmd_t *ucmd); +extern qboolean PM_GentCantJump(gentity_t *gent); +void ClientThink(int clientNum, usercmd_t *ucmd) { gentity_t *ent; qboolean restore_ucmd = qfalse; usercmd_t sav_ucmd = {0}; ent = g_entities + clientNum; - if ( !ent->s.number ) - { - if ( ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//you're controlling another NPC + if (!ent->s.number) { + if (ent->client->ps.viewEntity > 0 && ent->client->ps.viewEntity < ENTITYNUM_WORLD) { // you're controlling another NPC gentity_t *controlled = &g_entities[ent->client->ps.viewEntity]; qboolean freed = qfalse; - if ( controlled->NPC - && controlled->NPC->controlledTime - && ent->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//An NPC I'm controlling with mind trick - if ( controlled->NPC->controlledTime < level.time ) - {//time's up! - G_ClearViewEntity( ent ); + if (controlled->NPC && controlled->NPC->controlledTime && + ent->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // An NPC I'm controlling with mind trick + if (controlled->NPC->controlledTime < level.time) { // time's up! + G_ClearViewEntity(ent); freed = qtrue; - } - else if ( ucmd->upmove > 0 ) - {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? - G_ClearViewEntity( ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; - //stop player from doing anything for a half second after + } else if (ucmd->upmove > 0) { // jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have + // total control over an NPC? + G_ClearViewEntity(ent); + ucmd->upmove = 0; // ucmd->buttons = 0; + // stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } - } - else if ( controlled->NPC //an NPC - && PM_GentCantJump( controlled ) //that cannot jump - && controlled->NPC->stats.moveType != MT_FLYSWIM ) //and does not use upmove to fly - {//these types use jump to get out - if ( ucmd->upmove > 0 ) - {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? - G_ClearViewEntity( ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; - //stop player from doing anything for a half second after + } else if (controlled->NPC // an NPC + && PM_GentCantJump(controlled) // that cannot jump + && controlled->NPC->stats.moveType != MT_FLYSWIM) // and does not use upmove to fly + { // these types use jump to get out + if (ucmd->upmove > 0) { // jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total + // control over an NPC? + G_ClearViewEntity(ent); + ucmd->upmove = 0; // ucmd->buttons = 0; + // stop player from doing anything for a half second after ent->aimDebounceTime = level.time + 500; freed = qtrue; } - } - else - {//others use the blocking key, button3 - if ( (ucmd->buttons&BUTTON_BLOCKING) ) - {//jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could even have total control over an NPC? - G_ClearViewEntity( ent ); + } else { // others use the blocking key, button3 + if ((ucmd->buttons & BUTTON_BLOCKING)) { // jumping gets you out of it FIXME: check some other button instead... like ESCAPE... so you could + // even have total control over an NPC? + G_ClearViewEntity(ent); ucmd->buttons = 0; freed = qtrue; } } - if ( !freed ) - {//still controlling, save off my ucmd and clear it for my actual run through pmove + if (!freed) { // still controlling, save off my ucmd and clear it for my actual run through pmove restore_ucmd = qtrue; - memcpy( &sav_ucmd, ucmd, sizeof( usercmd_t ) ); - memset( ucmd, 0, sizeof( usercmd_t ) ); - //to keep pointing in same dir, need to set ucmd->angles - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + memcpy(&sav_ucmd, ucmd, sizeof(usercmd_t)); + memset(ucmd, 0, sizeof(usercmd_t)); + // to keep pointing in same dir, need to set ucmd->angles + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; - } - else - { - ucmd->angles[PITCH] = ANGLE2SHORT( ent->client->ps.viewangles[PITCH] ) - ent->client->ps.delta_angles[PITCH]; - ucmd->angles[YAW] = ANGLE2SHORT( ent->client->ps.viewangles[YAW] ) - ent->client->ps.delta_angles[YAW]; + } else { + ucmd->angles[PITCH] = ANGLE2SHORT(ent->client->ps.viewangles[PITCH]) - ent->client->ps.delta_angles[PITCH]; + ucmd->angles[YAW] = ANGLE2SHORT(ent->client->ps.viewangles[YAW]) - ent->client->ps.delta_angles[YAW]; ucmd->angles[ROLL] = 0; } - } - else if ( ent->client->NPC_class == CLASS_ATST ) - { - if ( ucmd->upmove > 0 ) - {//get out of ATST - GEntity_UseFunc( ent->activator, ent, ent ); - ucmd->upmove = 0;//ucmd->buttons = 0; + } else if (ent->client->NPC_class == CLASS_ATST) { + if (ucmd->upmove > 0) { // get out of ATST + GEntity_UseFunc(ent->activator, ent, ent); + ucmd->upmove = 0; // ucmd->buttons = 0; } } - if ( (ucmd->buttons&BUTTON_BLOCKING) && !g_saberAutoBlocking->integer ) - { - ucmd->buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + if ((ucmd->buttons & BUTTON_BLOCKING) && !g_saberAutoBlocking->integer) { + ucmd->buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); } - PM_CheckForceUseButton( ent, ucmd ); + PM_CheckForceUseButton(ent, ucmd); } ent->client->usercmd = *ucmd; -// if ( !g_syncronousClients->integer ) - { - ClientThink_real( ent, ucmd ); - } + // if ( !g_syncronousClients->integer ) + { ClientThink_real(ent, ucmd); } // ClientThink_real can end up freeing this ent, need to check - if ( restore_ucmd && ent->client ) - {//restore ucmd for later so NPC you're controlling can refer to them - memcpy( &ent->client->usercmd, &sav_ucmd, sizeof( usercmd_t ) ); + if (restore_ucmd && ent->client) { // restore ucmd for later so NPC you're controlling can refer to them + memcpy(&ent->client->usercmd, &sav_ucmd, sizeof(usercmd_t)); } - if ( ent->s.number ) - {//NPCs drown, burn from lava, etc, also - P_WorldEffects( ent ); + if (ent->s.number) { // NPCs drown, burn from lava, etc, also + P_WorldEffects(ent); } } -void ClientEndPowerUps( gentity_t *ent ) -{ - int i; +void ClientEndPowerUps(gentity_t *ent) { + int i; - if ( ent == NULL || ent->client == NULL ) - { + if (ent == NULL || ent->client == NULL) { return; } // turn off any expired powerups - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) - { - if ( ent->client->ps.powerups[ i ] < level.time ) - { - ent->client->ps.powerups[ i ] = 0; + for (i = 0; i < MAX_POWERUPS; i++) { + if (ent->client->ps.powerups[i] < level.time) { + ent->client->ps.powerups[i] = 0; } } } @@ -3040,29 +2512,26 @@ A fast client will have multiple ClientThink for each ClientEdFrame, while a slow client may have multiple ClientEndFrame between ClientThink. ============== */ -void ClientEndFrame( gentity_t *ent ) -{ +void ClientEndFrame(gentity_t *ent) { // // If the end of unit layout is displayed, don't give // the player any normal movement attributes // // burn from lava, etc - P_WorldEffects (ent); + P_WorldEffects(ent); // apply all the damage taken this frame - P_DamageFeedback (ent); + P_DamageFeedback(ent); // add the EF_CONNECTION flag if we haven't gotten commands recently - if ( level.time - ent->client->lastCmdTime > 1000 ) { + if (level.time - ent->client->lastCmdTime > 1000) { ent->s.eFlags |= EF_CONNECTION; } else { ent->s.eFlags &= ~EF_CONNECTION; } - ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... + ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... -// G_SetClientSound (ent); + // G_SetClientSound (ent); } - - diff --git a/codeJK2/game/g_breakable.cpp b/codeJK2/game/g_breakable.cpp index 3414928966..97a56d88eb 100644 --- a/codeJK2/game/g_breakable.cpp +++ b/codeJK2/game/g_breakable.cpp @@ -26,170 +26,153 @@ along with this program; if not, see . #include "g_functions.h" #include "../cgame/cg_media.h" -extern team_t TranslateTeamName( const char *name ); +extern team_t TranslateTeamName(const char *name); -//client side shortcut hacks from cg_local.h -//extern void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ); -extern void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ); -extern void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +// client side shortcut hacks from cg_local.h +// extern void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ); +extern void CG_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType); +extern void CG_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -extern qboolean player_locked; +extern qboolean player_locked; //--------------------------------------------------- -static void CacheChunkEffects( material_t material ) -{ - switch( material ) - { +static void CacheChunkEffects(material_t material) { + switch (material) { default: break; case MAT_GLASS: - G_EffectIndex( "chunks/glassbreak" ); + G_EffectIndex("chunks/glassbreak"); break; case MAT_GLASS_METAL: - G_EffectIndex( "chunks/glassbreak" ); - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/glassbreak"); + G_EffectIndex("chunks/metalexplode"); break; case MAT_ELECTRICAL: case MAT_ELEC_METAL: - G_EffectIndex( "chunks/sparkexplode" ); + G_EffectIndex("chunks/sparkexplode"); break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: case MAT_CRATE1: case MAT_CRATE2: - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/metalexplode"); break; case MAT_GRATE1: - G_EffectIndex( "chunks/grateexplode" ); + G_EffectIndex("chunks/grateexplode"); break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: case MAT_WHITE_METAL: // what is this crap really supposed to be?? - G_EffectIndex( "chunks/rockbreaklg" ); - G_EffectIndex( "chunks/rockbreakmed" ); + G_EffectIndex("chunks/rockbreaklg"); + G_EffectIndex("chunks/rockbreakmed"); break; case MAT_ROPE: - G_EffectIndex( "chunks/ropebreak" ); -// G_SoundIndex(); // FIXME: give it a sound + G_EffectIndex("chunks/ropebreak"); + // G_SoundIndex(); // FIXME: give it a sound break; } } //-------------------------------------- -void funcBBrushDieGo (gentity_t *self) -{ - vec3_t org, dir, up; - gentity_t *attacker = self->enemy; - float scale; - int numChunks, size = 0; - material_t chunkType = self->material; - +void funcBBrushDieGo(gentity_t *self) { + vec3_t org, dir, up; + gentity_t *attacker = self->enemy; + float scale; + int numChunks, size = 0; + material_t chunkType = self->material; + // if a missile is stuck to us, blow it up so we don't look dumb - for ( int i = 0; i < MAX_GENTITIES; i++ ) - { - if ( g_entities[i].s.groundEntityNum == self->s.number && ( g_entities[i].s.eFlags & EF_MISSILE_STICK )) - { - G_Damage( &g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH ); //?? MOD? + for (int i = 0; i < MAX_GENTITIES; i++) { + if (g_entities[i].s.groundEntityNum == self->s.number && (g_entities[i].s.eFlags & EF_MISSILE_STICK)) { + G_Damage(&g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH); //?? MOD? } } - //So chunks don't get stuck inside me + // So chunks don't get stuck inside me self->s.solid = 0; self->contents = 0; self->clipmask = 0; - gi.linkentity(self); + gi.linkentity(self); VectorSet(up, 0, 0, 1); - if ( self->target && attacker != NULL ) - { + if (self->target && attacker != NULL) { G_UseTargets(self, attacker); } - VectorSubtract( self->absmax, self->absmin, org );// size + VectorSubtract(self->absmax, self->absmin, org); // size numChunks = Q_flrand(0.0f, 1.0f) * 6 + 18; // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = sqrt( sqrt( org[0] * org[1] * org[2] )) * 1.75f; + scale = sqrt(sqrt(org[0] * org[1] * org[2])) * 1.75f; - if ( scale > 48 ) - { + if (scale > 48) { size = 2; - } - else if ( scale > 24 ) - { + } else if (scale > 24) { size = 1; } scale = scale / numChunks; - if ( self->radius > 0.0f ) - { + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit + //weak numChunks *= self->radius; } - VectorMA( self->absmin, 0.5, org, org ); - VectorAdd( self->absmin,self->absmax, org ); - VectorScale( org, 0.5f, org ); + VectorMA(self->absmin, 0.5, org, org); + VectorAdd(self->absmin, self->absmax, org); + VectorScale(org, 0.5f, org); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( org, attacker->currentOrigin, dir ); - VectorNormalize( dir ); - } - else - { + if (attacker != NULL && attacker->client) { + VectorSubtract(org, attacker->currentOrigin, dir); + VectorNormalize(dir); + } else { VectorCopy(up, dir); - } + } - if ( !(self->spawnflags & 2048) ) // NO_EXPLOSION + if (!(self->spawnflags & 2048)) // NO_EXPLOSION { // we are allowed to explode - CG_MiscModelExplosion( self->mins, self->maxs, size, chunkType ); + CG_MiscModelExplosion(self->mins, self->maxs, size, chunkType); } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - //explode - AddSightEvent( attacker, org, 256, AEL_DISCOVERED, 100 ); - AddSoundEvent( attacker, org, 128, AEL_DISCOVERED ); - G_RadiusDamage( org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + // explode + AddSightEvent(attacker, org, 256, AEL_DISCOVERED, 100); + AddSoundEvent(attacker, org, 128, AEL_DISCOVERED); + G_RadiusDamage(org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); - gentity_t *te = G_TempEntity( org, EV_GENERAL_SOUND ); + gentity_t *te = G_TempEntity(org, EV_GENERAL_SOUND); te->s.eventParm = G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - } - else - {//just break - AddSightEvent( attacker, org, 128, AEL_DISCOVERED ); - AddSoundEvent( attacker, org, 64, AEL_SUSPICIOUS ); + } else { // just break + AddSightEvent(attacker, org, 128, AEL_DISCOVERED); + AddSoundEvent(attacker, org, 64, AEL_SUSPICIOUS); } - //FIXME: base numChunks off size? - CG_Chunks( self->s.number, org, dir, self->mins, self->maxs, 300, numChunks, chunkType, 0, scale ); + // FIXME: base numChunks off size? + CG_Chunks(self->s.number, org, dir, self->mins, self->maxs, 300, numChunks, chunkType, 0, scale); - gi.AdjustAreaPortalState( self, qtrue ); + gi.AdjustAreaPortalState(self, qtrue); self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + 50; - //G_FreeEntity( self ); + // G_FreeEntity( self ); } -void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc) -{ - self->takedamage = qfalse;//stop chain reaction runaway loops +void funcBBrushDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + self->takedamage = qfalse; // stop chain reaction runaway loops G_SetEnemy(self, attacker); - if(self->delay) - { + if (self->delay) { self->e_ThinkFunc = thinkF_funcBBrushDieGo; self->nextthink = level.time + floor(self->delay * 1000.0f); return; @@ -198,63 +181,48 @@ void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, funcBBrushDieGo(self); } -void funcBBrushUse (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior( self, BSET_USE ); - if(self->spawnflags & 64) - {//Using it doesn't break it, makes it use it's targets - if(self->target && self->target[0]) - { +void funcBBrushUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + if (self->spawnflags & 64) { // Using it doesn't break it, makes it use it's targets + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - } - else - { + } else { funcBBrushDie(self, other, activator, self->health, MOD_UNKNOWN); } } -void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod,int hitLoc) -{ - if ( self->painDebounceTime > level.time ) - { +void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { + if (self->painDebounceTime > level.time) { return; } - if ( self->paintarget ) - { - G_UseTargets2 (self, self->activator, self->paintarget); + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); - if ( self->material == MAT_DRK_STONE - || self->material == MAT_LT_STONE - || self->material == MAT_GREY_STONE ) - { - vec3_t org, dir; - float scale; - VectorSubtract( self->absmax, self->absmin, org );// size + if (self->material == MAT_DRK_STONE || self->material == MAT_LT_STONE || self->material == MAT_GREY_STONE) { + vec3_t org, dir; + float scale; + VectorSubtract(self->absmax, self->absmin, org); // size // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = VectorLength( org ) / 100.0f; - VectorMA( self->absmin, 0.5, org, org ); - VectorAdd( self->absmin,self->absmax, org ); - VectorScale( org, 0.5f, org ); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( attacker->currentOrigin, org, dir ); - VectorNormalize( dir ); + scale = VectorLength(org) / 100.0f; + VectorMA(self->absmin, 0.5, org, org); + VectorAdd(self->absmin, self->absmax, org); + VectorScale(org, 0.5f, org); + if (attacker != NULL && attacker->client) { + VectorSubtract(attacker->currentOrigin, org, dir); + VectorNormalize(dir); + } else { + VectorSet(dir, 0, 0, 1); } - else - { - VectorSet( dir, 0, 0, 1 ); - } - CG_Chunks( self->s.number, org, dir, self->mins, self->maxs, 300, Q_irand( 1, 3 ), self->material, 0, scale ); + CG_Chunks(self->s.number, org, dir, self->mins, self->maxs, 300, Q_irand(1, 3), self->material, 0, scale); } - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->e_PainFunc = painF_NULL; return; } @@ -262,68 +230,62 @@ void funcBBrushPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, self->painDebounceTime = level.time + self->wait; } -static void InitBBrush ( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +static void InitBBrush(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; - VectorCopy( ent->s.origin, ent->pos1 ); - - gi.SetBrushModel( ent, ent->model ); + VectorCopy(ent->s.origin, ent->pos1); + + gi.SetBrushModel(ent, ent->model); ent->e_DieFunc = dieF_funcBBrushDie; - + ent->svFlags |= SVF_BBRUSH; // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 ) - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + if (ent->model2) { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) - { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } - if(ent->spawnflags & 128) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } ent->s.eType = ET_MOVER; - gi.linkentity (ent); + gi.linkentity(ent); ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); } -void funcBBrushTouch( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ -} +void funcBBrushTouch(gentity_t *ent, gentity_t *other, trace_t *trace) {} /*QUAKED func_breakable (0 .8 .5) ? INVINCIBLE IMPACT CRUSHER THIN SABERONLY HEAVY_WEAP USE_NOT_BREAK PLAYER_USE NO_EXPLOSION INVINCIBLE - can only be broken by being used @@ -345,7 +307,8 @@ When destroyed, fires it's trigger and chunks and plays sound "noise" or sound f "model2" .md3 model to also draw "target" all entities with a matching targetname will be used when this is destoryed "health" default is 10 -"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks +"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many +chunks, (2) is twice as many chunks Damage: default is none "splashDamage" - damage to do @@ -356,13 +319,13 @@ Damage: default is none "neutral" "enemy" -Don't know if these work: +Don't know if these work: "color" constantLight color "light" constantLight radius "material" - default is "0 - MAT_METAL" - choose from this list: 0 = MAT_METAL (basic blue-grey scorched-DEFAULT) -1 = MAT_GLASS +1 = MAT_GLASS 2 = MAT_ELECTRICAL (sparks only) 3 = MAT_ELEC_METAL (METAL2 chunks and sparks) 4 = MAT_DRK_STONE (brown stone chunks) @@ -379,49 +342,40 @@ Don't know if these work: 15 = MAT_WHITE_METAL (white angular chunks for Stu, NS_hideout ) */ -void SP_func_breakable( gentity_t *self ) -{ - if(!(self->spawnflags & 1)) - { - if(!self->health) - { +void SP_func_breakable(gentity_t *self) { + if (!(self->spawnflags & 1)) { + if (!self->health) { self->health = 10; } } - if ( self->spawnflags & 16 ) // saber only + if (self->spawnflags & 16) // saber only { self->flags |= FL_DMG_BY_SABER_ONLY; - } - else if ( self->spawnflags & 32 ) // heavy weap + } else if (self->spawnflags & 32) // heavy weap { self->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; } - if (self->health) - { + if (self->health) { self->takedamage = qtrue; } - G_SoundIndex("sound/weapons/explosions/cargoexplode.wav");//precaching - G_SpawnFloat( "radius", "1", &self->radius ); // used to scale chunk code if desired by a designer - G_SpawnInt( "material", "0", (int*)&self->material ); - CacheChunkEffects( self->material ); + G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); // precaching + G_SpawnFloat("radius", "1", &self->radius); // used to scale chunk code if desired by a designer + G_SpawnInt("material", "0", (int *)&self->material); + CacheChunkEffects(self->material); self->e_UseFunc = useF_funcBBrushUse; - //if ( self->paintarget ) - { - self->e_PainFunc = painF_funcBBrushPain; - } + // if ( self->paintarget ) + { self->e_PainFunc = painF_funcBBrushPain; } self->e_TouchFunc = touchF_funcBBrushTouch; - if ( self->team && self->team[0] ) - { - self->noDamageTeam = TranslateTeamName( self->team ); - if(self->noDamageTeam == TEAM_FREE) - { + if (self->team && self->team[0]) { + self->noDamageTeam = TranslateTeamName(self->team); + if (self->noDamageTeam == TEAM_FREE) { G_Error("team name %s not recognized", self->team); } } @@ -429,81 +383,72 @@ void SP_func_breakable( gentity_t *self ) if (!self->model) { G_Error("func_breakable with NULL model"); } - InitBBrush( self ); + InitBBrush(self); } - -void misc_model_breakable_pain ( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->health > 0 ) - { +void misc_model_breakable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + if (self->health > 0) { // still alive, react to the pain - if ( self->paintarget ) - { - G_UseTargets2 (self, self->activator, self->paintarget); + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } // Don't do script if dead - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); } } -void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ - int numChunks; - float size = 0, scale; - vec3_t dir, up, dis; +void misc_model_breakable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { + int numChunks; + float size = 0, scale; + vec3_t dir, up, dis; - //NOTE: Stop any scripts that are currently running (FLUSH)... ? - //Turn off animation + // NOTE: Stop any scripts that are currently running (FLUSH)... ? + // Turn off animation self->s.frame = self->startFrame = self->endFrame = 0; self->svFlags &= ~SVF_ANIMATING; - + self->health = 0; - //Throw some chunks - AngleVectors( self->s.apos.trBase, dir, NULL, NULL ); - VectorNormalize( dir ); + // Throw some chunks + AngleVectors(self->s.apos.trBase, dir, NULL, NULL); + VectorNormalize(dir); numChunks = Q_flrand(0.0f, 1.0f) * 6 + 20; - VectorSubtract( self->absmax, self->absmin, dis ); + VectorSubtract(self->absmax, self->absmin, dis); // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = sqrt( sqrt( dis[0] * dis[1] * dis[2] )) * 1.75f; + scale = sqrt(sqrt(dis[0] * dis[1] * dis[2])) * 1.75f; - if ( scale > 48 ) - { + if (scale > 48) { size = 2; - } - else if ( scale > 24 ) - { + } else if (scale > 24) { size = 1; } scale = scale / numChunks; - if ( self->radius > 0.0f ) - { + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit + //weak numChunks *= self->radius; } - VectorAdd( self->absmax, self->absmin, dis ); - VectorScale( dis, 0.5f, dis ); + VectorAdd(self->absmax, self->absmin, dis); + VectorScale(dis, 0.5f, dis); - CG_Chunks( self->s.number, dis, dir, self->absmin, self->absmax, 300, numChunks, self->material, self->s.modelindex3, scale ); + CG_Chunks(self->s.number, dis, dir, self->absmin, self->absmax, 300, numChunks, self->material, self->s.modelindex3, scale); self->e_PainFunc = painF_NULL; - self->e_DieFunc = dieF_NULL; -// self->e_UseFunc = useF_NULL; + self->e_DieFunc = dieF_NULL; + // self->e_UseFunc = useF_NULL; self->takedamage = qfalse; - if ( !(self->spawnflags & 4) ) - {//We don't want to stay solid + if (!(self->spawnflags & 4)) { // We don't want to stay solid self->s.solid = 0; self->contents = 0; self->clipmask = 0; @@ -512,57 +457,47 @@ void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t VectorSet(up, 0, 0, 1); - if(self->target) - { + if (self->target) { G_UseTargets(self, attacker); } - if(inflictor->client) - { - VectorSubtract( self->currentOrigin, inflictor->currentOrigin, dir ); - VectorNormalize( dir ); - } - else - { + if (inflictor->client) { + VectorSubtract(self->currentOrigin, inflictor->currentOrigin, dir); + VectorNormalize(dir); + } else { VectorCopy(up, dir); } - if ( !(self->spawnflags & 2048) ) // NO_EXPLOSION + if (!(self->spawnflags & 2048)) // NO_EXPLOSION { // Ok, we are allowed to explode, so do it now! - if(self->splashDamage > 0 && self->splashRadius > 0) - {//explode + if (self->splashDamage > 0 && self->splashRadius > 0) { // explode vec3_t org; - AddSightEvent( attacker, self->currentOrigin, 256, AEL_DISCOVERED, 100 ); - AddSoundEvent( attacker, self->currentOrigin, 128, AEL_DISCOVERED ); - //FIXME: specify type of explosion? (barrel, electrical, etc.) Also, maybe just use the explosion effect below since it's + AddSightEvent(attacker, self->currentOrigin, 256, AEL_DISCOVERED, 100); + AddSoundEvent(attacker, self->currentOrigin, 128, AEL_DISCOVERED); + // FIXME: specify type of explosion? (barrel, electrical, etc.) Also, maybe just use the explosion effect below since it's // a bit better? - // up the origin a little for the damage check, because several models have their origin on the ground, so they don't alwasy do damage, not the optimal solution... - VectorCopy( self->currentOrigin, org ); - if ( self->mins[2] > -4 ) - {//origin is going to be below it or very very low in the model - //center the origin - org[2] = self->currentOrigin[2] + self->mins[2] + (self->maxs[2] - self->mins[2])/2.0f; - } - G_RadiusDamage( org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); - - if ( self->model && Q_stricmp( "models/map_objects/ships/tie_fighter.md3", self->model ) == 0 ) - {//TEMP HACK for Tie Fighters- they're HUGE - G_PlayEffect( "fighter_explosion2", self->currentOrigin ); - G_Sound( self, G_SoundIndex( "sound/weapons/tie_fighter/TIEexplode.wav" ) ); + // up the origin a little for the damage check, because several models have their origin on the ground, so they don't alwasy do damage, not the + // optimal solution... + VectorCopy(self->currentOrigin, org); + if (self->mins[2] > -4) { // origin is going to be below it or very very low in the model + // center the origin + org[2] = self->currentOrigin[2] + self->mins[2] + (self->maxs[2] - self->mins[2]) / 2.0f; } - else - { - CG_MiscModelExplosion( self->absmin, self->absmax, size, self->material ); - G_Sound( self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav") ); + G_RadiusDamage(org, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); + + if (self->model && Q_stricmp("models/map_objects/ships/tie_fighter.md3", self->model) == 0) { // TEMP HACK for Tie Fighters- they're HUGE + G_PlayEffect("fighter_explosion2", self->currentOrigin); + G_Sound(self, G_SoundIndex("sound/weapons/tie_fighter/TIEexplode.wav")); + } else { + CG_MiscModelExplosion(self->absmin, self->absmax, size, self->material); + G_Sound(self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav")); } - } - else - {//just break - AddSightEvent( attacker, self->currentOrigin, 128, AEL_DISCOVERED ); - AddSoundEvent( attacker, self->currentOrigin, 64, AEL_SUSPICIOUS ); + } else { // just break + AddSightEvent(attacker, self->currentOrigin, 128, AEL_DISCOVERED); + AddSoundEvent(attacker, self->currentOrigin, 64, AEL_SUSPICIOUS); // This is the default explosion - CG_MiscModelExplosion( self->absmin, self->absmax, size, self->material ); + CG_MiscModelExplosion(self->absmin, self->absmax, size, self->material); G_Sound(self, G_SoundIndex("sound/weapons/explosions/cargoexplode.wav")); } } @@ -570,38 +505,28 @@ void misc_model_breakable_die( gentity_t *self, gentity_t *inflictor, gentity_t self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - if(self->s.modelindex2 != -1 && !(self->spawnflags & 8)) - {//FIXME: modelindex doesn't get set to -1 if the damage model doesn't exist + if (self->s.modelindex2 != -1 && !(self->spawnflags & 8)) { // FIXME: modelindex doesn't get set to -1 if the damage model doesn't exist self->svFlags |= SVF_BROKEN; self->s.modelindex = self->s.modelindex2; - G_ActivateBehavior( self, BSET_DEATH ); - } - else - { - G_FreeEntity( self ); + G_ActivateBehavior(self, BSET_DEATH); + } else { + G_FreeEntity(self); } } -void misc_model_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->health <= 0 && self->max_health > 0) - {//used while broken fired target3 - G_UseTargets2( self, activator, self->target3 ); +void misc_model_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->health <= 0 && self->max_health > 0) { // used while broken fired target3 + G_UseTargets2(self, activator, self->target3); return; } - G_ActivateBehavior( self, BSET_USE ); - //Don't explode if they've requested it to not - if ( self->spawnflags & 64 ) - {//Usemodels toggling - if ( self->spawnflags & 32 ) - { - if( self->s.modelindex == self->sound1to2 ) - { + G_ActivateBehavior(self, BSET_USE); + // Don't explode if they've requested it to not + if (self->spawnflags & 64) { // Usemodels toggling + if (self->spawnflags & 32) { + if (self->s.modelindex == self->sound1to2) { self->s.modelindex = self->sound2to1; - } - else - { + } else { self->s.modelindex = self->sound1to2; } } @@ -609,121 +534,102 @@ void misc_model_use (gentity_t *self, gentity_t *other, gentity_t *activator) return; } - misc_model_breakable_die( self, other, activator, self->health, MOD_UNKNOWN ); + misc_model_breakable_die(self, other, activator, self->health, MOD_UNKNOWN); } -#define MDL_OTHER 0 -#define MDL_ARMOR_HEALTH 1 -#define MDL_AMMO 2 +#define MDL_OTHER 0 +#define MDL_ARMOR_HEALTH 1 +#define MDL_AMMO 2 -void misc_model_breakable_init( gentity_t *ent ) -{ - int type; +void misc_model_breakable_init(gentity_t *ent) { + int type; type = MDL_OTHER; if (!ent->model) { - G_Error("no model set on %s at (%.1f %.1f %.1f)", ent->classname, ent->s.origin[0],ent->s.origin[1],ent->s.origin[2]); + G_Error("no model set on %s at (%.1f %.1f %.1f)", ent->classname, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2]); } - //Main model - ent->s.modelindex = ent->sound2to1 = G_ModelIndex( ent->model ); + // Main model + ent->s.modelindex = ent->sound2to1 = G_ModelIndex(ent->model); - if ( ent->spawnflags & 1 ) - {//Blocks movement - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//Was CONTENTS_SOLID, but only architecture should be this - } - else if ( ent->health ) - {//Can only be shot + if (ent->spawnflags & 1) { // Blocks movement + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | + CONTENTS_BOTCLIP; // Was CONTENTS_SOLID, but only architecture should be this + } else if (ent->health) { // Can only be shot ent->contents = CONTENTS_SHOTCLIP; } - if (type == MDL_OTHER) - { - ent->e_UseFunc = useF_misc_model_use; - } - else if ( type == MDL_ARMOR_HEALTH ) - { -// G_SoundIndex("sound/player/suithealth.wav"); + if (type == MDL_OTHER) { + ent->e_UseFunc = useF_misc_model_use; + } else if (type == MDL_ARMOR_HEALTH) { + // G_SoundIndex("sound/player/suithealth.wav"); ent->e_UseFunc = useF_health_use; - if (!ent->count) - { + if (!ent->count) { ent->count = 100; } ent->health = 60; - } - else if ( type == MDL_AMMO ) - { -// G_SoundIndex("sound/player/suitenergy.wav"); + } else if (type == MDL_AMMO) { + // G_SoundIndex("sound/player/suitenergy.wav"); ent->e_UseFunc = useF_ammo_use; - if (!ent->count) - { + if (!ent->count) { ent->count = 100; } ent->health = 60; } - if ( ent->health ) - { + if (ent->health) { G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); ent->max_health = ent->health; ent->takedamage = qtrue; ent->e_PainFunc = painF_misc_model_breakable_pain; - ent->e_DieFunc = dieF_misc_model_breakable_die; + ent->e_DieFunc = dieF_misc_model_breakable_die; } } -void TieFighterThink ( gentity_t *self ) -{ +void TieFighterThink(gentity_t *self) { gentity_t *player = &g_entities[0]; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } self->nextthink = level.time + FRAMETIME; - if ( player ) - { - vec3_t playerDir, fighterDir, fwd, rt; - float playerDist, fighterSpeed; + if (player) { + vec3_t playerDir, fighterDir, fwd, rt; + float playerDist, fighterSpeed; - //use player eyepoint - VectorSubtract( player->currentOrigin, self->currentOrigin, playerDir ); - playerDist = VectorNormalize( playerDir ); - VectorSubtract( self->currentOrigin, self->lastOrigin, fighterDir ); - VectorCopy( self->currentOrigin, self->lastOrigin ); - fighterSpeed = VectorNormalize( fighterDir )*1000; - AngleVectors( self->currentAngles, fwd, rt, NULL ); + // use player eyepoint + VectorSubtract(player->currentOrigin, self->currentOrigin, playerDir); + playerDist = VectorNormalize(playerDir); + VectorSubtract(self->currentOrigin, self->lastOrigin, fighterDir); + VectorCopy(self->currentOrigin, self->lastOrigin); + fighterSpeed = VectorNormalize(fighterDir) * 1000; + AngleVectors(self->currentAngles, fwd, rt, NULL); - if ( fighterSpeed ) - { - float side; + if (fighterSpeed) { + float side; // Magic number fun! Speed is used for banking, so modulate the speed by a sine wave - fighterSpeed *= sin( ( 100 ) * 0.003 ); + fighterSpeed *= sin((100) * 0.003); // Clamp to prevent harsh rolling - if ( fighterSpeed > 10 ) + if (fighterSpeed > 10) fighterSpeed = 10; - side = fighterSpeed * DotProduct( fighterDir, rt ); + side = fighterSpeed * DotProduct(fighterDir, rt); self->s.apos.trBase[2] -= side; } - //FIXME: bob up/down, strafe left/right some - float dot = DotProduct( playerDir, fighterDir ); - if ( dot > 0 ) - {//heading toward the player - if ( playerDist < 1024 ) - { - if ( DotProduct( playerDir, fwd ) > 0.7 ) - {//facing the player - if ( self->attackDebounceTime < level.time ) - { - gentity_t *bolt; + // FIXME: bob up/down, strafe left/right some + float dot = DotProduct(playerDir, fighterDir); + if (dot > 0) { // heading toward the player + if (playerDist < 1024) { + if (DotProduct(playerDir, fwd) > 0.7) { // facing the player + if (self->attackDebounceTime < level.time) { + gentity_t *bolt; bolt = G_Spawn(); - + bolt->classname = "tie_proj"; bolt->nextthink = level.time + 10000; bolt->e_ThinkFunc = thinkF_G_FreeEntity; @@ -731,105 +637,85 @@ void TieFighterThink ( gentity_t *self ) bolt->s.weapon = WP_BLASTER; bolt->owner = self; bolt->damage = 30; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; - bolt->methodOfDeath = MOD_ENERGY; // ? + bolt->methodOfDeath = MOD_ENERGY; // ? bolt->clipmask = MASK_SHOT; bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( self->currentOrigin, bolt->s.pos.trBase ); - VectorScale( fwd, 8000, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( self->currentOrigin, bolt->currentOrigin); - - if ( !Q_irand( 0, 2 ) ) - { - G_SoundOnEnt( bolt, CHAN_VOICE, "sound/weapons/tie_fighter/tie_fire.wav" ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(self->currentOrigin, bolt->s.pos.trBase); + VectorScale(fwd, 8000, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(self->currentOrigin, bolt->currentOrigin); + + if (!Q_irand(0, 2)) { + G_SoundOnEnt(bolt, CHAN_VOICE, "sound/weapons/tie_fighter/tie_fire.wav"); + } else { + G_SoundOnEnt(bolt, CHAN_VOICE, va("sound/weapons/tie_fighter/tie_fire%d.wav", Q_irand(2, 3))); } - else - { - G_SoundOnEnt( bolt, CHAN_VOICE, va( "sound/weapons/tie_fighter/tie_fire%d.wav", Q_irand( 2, 3 ) ) ); - } - self->attackDebounceTime = level.time + Q_irand( 300, 2000 ); + self->attackDebounceTime = level.time + Q_irand(300, 2000); } } } } - if ( playerDist < 1024 )//512 ) - {//within range to start our sound - if ( dot > 0 ) - { - if ( !self->fly_sound_debounce_time ) - {//start sound - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/tie_fighter/tiepass%d.wav", Q_irand( 1, 5 ) ) ); + if (playerDist < 1024) // 512 ) + { // within range to start our sound + if (dot > 0) { + if (!self->fly_sound_debounce_time) { // start sound + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/tie_fighter/tiepass%d.wav", Q_irand(1, 5))); self->fly_sound_debounce_time = 2000; - } - else - {//sound already started + } else { // sound already started self->fly_sound_debounce_time = -1; } } - } - else if ( self->fly_sound_debounce_time < level.time ) - { + } else if (self->fly_sound_debounce_time < level.time) { self->fly_sound_debounce_time = 0; } } } -void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ) -{ +void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor) { ent->s.eType = ET_GENERAL; ent->s.eFlags |= EF_BOUNCE_HALF; - ent->clipmask = MASK_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//? - ent->physicsBounce = ent->mass = VectorLength( ent->maxs ) + VectorLength( ent->mins ); - //drop to floor - trace_t tr; - vec3_t top, bottom; - - if ( dropToFloor ) - { - VectorCopy( ent->currentOrigin, top ); + ent->clipmask = MASK_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; //? + ent->physicsBounce = ent->mass = VectorLength(ent->maxs) + VectorLength(ent->mins); + // drop to floor + trace_t tr; + vec3_t top, bottom; + + if (dropToFloor) { + VectorCopy(ent->currentOrigin, top); top[2] += 1; - VectorCopy( ent->currentOrigin, bottom ); + VectorCopy(ent->currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - gi.trace( &tr, top, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, G2_NOCOLLIDE, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); - gi.linkentity( ent ); + gi.trace(&tr, top, ent->mins, ent->maxs, bottom, ent->s.number, MASK_NPCSOLID, G2_NOCOLLIDE, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); + gi.linkentity(ent); } + } else { + G_SetOrigin(ent, ent->currentOrigin); + gi.linkentity(ent); } - else - { - G_SetOrigin( ent, ent->currentOrigin ); - gi.linkentity( ent ); - } - //set up for object thinking - if ( VectorCompare( ent->s.pos.trDelta, vec3_origin ) ) - {//not moving + // set up for object thinking + if (VectorCompare(ent->s.pos.trDelta, vec3_origin)) { // not moving ent->s.pos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.pos.trType = TR_GRAVITY; } - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; - if ( VectorCompare( ent->s.apos.trDelta, vec3_origin ) ) - {//not moving + if (VectorCompare(ent->s.apos.trDelta, vec3_origin)) { // not moving ent->s.apos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.apos.trType = TR_LINEAR; } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trTime = level.time; ent->nextthink = level.time + FRAMETIME; ent->e_ThinkFunc = thinkF_G_RunObject; @@ -845,15 +731,11 @@ PLAYER_USE - Player can use it with the use button NO_EXPLOSION - By default, will explode when it dies...this is your override. "model" arbitrary .md3 file to display -"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block NPCs or players from moving -"targetname" when used, dies and displays damagemodel, if any (if not, removes itself) -"target" What to use when it dies -"target2" What to use when it's repaired -"target3" What to use when it's used while it's broken -"paintarget" target to fire when hit (but not destroyed) -"count" the amount of armor/health/ammo given (default 50) -"gravity" if set to 1, this will be affected by gravity -"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks +"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block +NPCs or players from moving "targetname" when used, dies and displays damagemodel, if any (if not, removes itself) "target" What to use when it dies "target2" +What to use when it's repaired "target3" What to use when it's used while it's broken "paintarget" target to fire when hit (but not destroyed) "count" the +amount of armor/health/ammo given (default 50) "gravity" if set to 1, this will be affected by gravity "radius" Chunk code tries to pick a good volume of +chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks Damage: default is none "splashDamage" - damage to do (will make it explode on death) @@ -866,7 +748,7 @@ Damage: default is none "material" - default is "8 - MAT_NONE" - choose from this list: 0 = MAT_METAL (grey metal) -1 = MAT_GLASS +1 = MAT_GLASS 2 = MAT_ELECTRICAL (sparks only) 3 = MAT_ELEC_METAL (METAL chunks and sparks) 4 = MAT_DRK_STONE (brown stone chunks) @@ -881,109 +763,99 @@ Damage: default is none 13 = MAT_ROPE (for yavin_trial, no chunks, just wispy bits ) 14 = MAT_CRATE2 (red multi-colored crate chunks) 15 = MAT_WHITE_METAL (white angular chunks for Stu, NS_hideout ) -FIXME/TODO: +FIXME/TODO: set size better? multiple damage models? custom explosion effect/sound? */ -void SP_misc_model_breakable( gentity_t *ent ) -{ - char damageModel[MAX_QPATH]; - char chunkModel[MAX_QPATH]; - char useModel[MAX_QPATH]; - int len; - +void SP_misc_model_breakable(gentity_t *ent) { + char damageModel[MAX_QPATH]; + char chunkModel[MAX_QPATH]; + char useModel[MAX_QPATH]; + int len; + // Chris F. requested default for misc_model_breakable to be NONE...so don't arbitrarily change this. - G_SpawnInt( "material", "8", (int*)&ent->material ); - G_SpawnFloat( "radius", "1", &ent->radius ); // used to scale chunk code if desired by a designer - CacheChunkEffects( ent->material ); - - misc_model_breakable_init( ent ); - - len = strlen( ent->model ) - 4; - strncpy( damageModel, ent->model, len ); - damageModel[len] = 0; //chop extension - strncpy( chunkModel, damageModel, sizeof(chunkModel)); - strncpy( useModel, damageModel, sizeof(useModel)); - + G_SpawnInt("material", "8", (int *)&ent->material); + G_SpawnFloat("radius", "1", &ent->radius); // used to scale chunk code if desired by a designer + CacheChunkEffects(ent->material); + + misc_model_breakable_init(ent); + + len = strlen(ent->model) - 4; + strncpy(damageModel, ent->model, len); + damageModel[len] = 0; // chop extension + strncpy(chunkModel, damageModel, sizeof(chunkModel)); + strncpy(useModel, damageModel, sizeof(useModel)); + if (ent->takedamage) { - //Dead/damaged model - if( !(ent->spawnflags & 8) ) { //no dmodel - strcat( damageModel, "_d1.md3" ); - ent->s.modelindex2 = G_ModelIndex( damageModel ); + // Dead/damaged model + if (!(ent->spawnflags & 8)) { // no dmodel + strcat(damageModel, "_d1.md3"); + ent->s.modelindex2 = G_ModelIndex(damageModel); } - - //Chunk model - strcat( chunkModel, "_c1.md3" ); - ent->s.modelindex3 = G_ModelIndex( chunkModel ); + + // Chunk model + strcat(chunkModel, "_c1.md3"); + ent->s.modelindex3 = G_ModelIndex(chunkModel); } - //Use model - if( ent->spawnflags & 32 ) { //has umodel - strcat( useModel, "_u1.md3" ); - ent->sound1to2 = G_ModelIndex( useModel ); + // Use model + if (ent->spawnflags & 32) { // has umodel + strcat(useModel, "_u1.md3"); + ent->sound1to2 = G_ModelIndex(useModel); } - if ( !ent->mins[0] && !ent->mins[1] && !ent->mins[2] ) - { - VectorSet (ent->mins, -16, -16, -16); + if (!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) { + VectorSet(ent->mins, -16, -16, -16); } - if ( !ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2] ) - { - VectorSet (ent->maxs, 16, 16, 16); + if (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2]) { + VectorSet(ent->maxs, 16, 16, 16); } - if ( ent->spawnflags & 2 ) - { + if (ent->spawnflags & 2) { ent->s.eFlags |= EF_ANIM_ALLFAST; } - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + gi.linkentity(ent); - if ( ent->spawnflags & 128 ) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = TranslateTeamName( ent->team ); - if ( ent->noDamageTeam == TEAM_FREE ) - { + if (ent->team && ent->team[0]) { + ent->noDamageTeam = TranslateTeamName(ent->team); + if (ent->noDamageTeam == TEAM_FREE) { G_Error("team name %s not recognized", ent->team); } } - + ent->team = NULL; - //HACK - if ( ent->model && Q_stricmp( "models/map_objects/ships/tie_fighter.md3", ent->model ) == 0 ) - {//run a think - G_EffectIndex( "fighter_explosion2" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass1.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass2.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass3.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass4.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tiepass5.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tie_fire.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tie_fire2.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/tie_fire3.wav" ); - G_SoundIndex( "sound/weapons/tie_fighter/TIEexplode.wav" ); + // HACK + if (ent->model && Q_stricmp("models/map_objects/ships/tie_fighter.md3", ent->model) == 0) { // run a think + G_EffectIndex("fighter_explosion2"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass1.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass2.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass3.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass4.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tiepass5.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tie_fire.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tie_fire2.wav"); + G_SoundIndex("sound/weapons/tie_fighter/tie_fire3.wav"); + G_SoundIndex("sound/weapons/tie_fighter/TIEexplode.wav"); ent->e_ThinkFunc = thinkF_TieFighterThink; ent->nextthink = level.time + FRAMETIME; } float grav = 0; - G_SpawnFloat( "gravity", "0", &grav ); - if ( grav ) - {//affected by gravity - G_SetAngles( ent, ent->s.angles ); - G_SetOrigin( ent, ent->currentOrigin ); - misc_model_breakable_gravity_init( ent, qtrue ); + G_SpawnFloat("gravity", "0", &grav); + if (grav) { // affected by gravity + G_SetAngles(ent, ent->s.angles); + G_SetOrigin(ent, ent->currentOrigin); + misc_model_breakable_gravity_init(ent, qtrue); } } - //---------------------------------- // // Breaking Glass Technology @@ -991,70 +863,65 @@ void SP_misc_model_breakable( gentity_t *ent ) //---------------------------------- // Really naughty cheating. Put in an EVENT at some point... -extern void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal ); -extern void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius ); -extern cgs_t cgs; +extern void cgi_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal); +extern void CG_DoGlass(vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius); +extern cgs_t cgs; //----------------------------------------------------- -void funcGlassDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ - vec3_t verts[4], normal; +void funcGlassDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + vec3_t verts[4], normal; // if a missile is stuck to us, blow it up so we don't look dumb....we could, alternately, just let the missile drop off?? - for ( int i = 0; i < MAX_GENTITIES; i++ ) - { - if ( g_entities[i].s.groundEntityNum == self->s.number && ( g_entities[i].s.eFlags & EF_MISSILE_STICK )) - { - G_Damage( &g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH ); //?? MOD? + for (int i = 0; i < MAX_GENTITIES; i++) { + if (g_entities[i].s.groundEntityNum == self->s.number && (g_entities[i].s.eFlags & EF_MISSILE_STICK)) { + G_Damage(&g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH); //?? MOD? } } // Really naughty cheating. Put in an EVENT at some point... - cgi_R_GetBModelVerts( cgs.inlineDrawModel[self->s.modelindex], verts, normal ); - CG_DoGlass( verts, normal, self->pos1, self->pos2, self->splashRadius ); + cgi_R_GetBModelVerts(cgs.inlineDrawModel[self->s.modelindex], verts, normal); + CG_DoGlass(verts, normal, self->pos1, self->pos2, self->splashRadius); - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops - G_SetEnemy( self, self->enemy ); + G_SetEnemy(self, self->enemy); - //So chunks don't get stuck inside me + // So chunks don't get stuck inside me self->s.solid = 0; self->contents = 0; self->clipmask = 0; - gi.linkentity(self); + gi.linkentity(self); - if ( self->target && attacker != NULL ) - { - G_UseTargets( self, attacker ); + if (self->target && attacker != NULL) { + G_UseTargets(self, attacker); } - gi.AdjustAreaPortalState( self, qtrue ); - G_FreeEntity( self ); + gi.AdjustAreaPortalState(self, qtrue); + G_FreeEntity(self); } //----------------------------------------------------- -void funcGlassUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void funcGlassUse(gentity_t *self, gentity_t *other, gentity_t *activator) { vec3_t temp1, temp2; // For now, we just break on use - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - VectorAdd( self->mins, self->maxs, temp1 ); - VectorScale( temp1, 0.5f, temp1 ); + VectorAdd(self->mins, self->maxs, temp1); + VectorScale(temp1, 0.5f, temp1); - VectorAdd( other->mins, other->maxs, temp2 ); - VectorScale( temp2, 0.5f, temp2 ); + VectorAdd(other->mins, other->maxs, temp2); + VectorScale(temp2, 0.5f, temp2); - VectorSubtract( temp1, temp2, self->pos2 ); - VectorCopy( temp1, self->pos1 ); + VectorSubtract(temp1, temp2, self->pos2); + VectorCopy(temp1, self->pos1); - VectorNormalize( self->pos2 ); - VectorScale( self->pos2, 390, self->pos2 ); + VectorNormalize(self->pos2); + VectorScale(self->pos2, 390, self->pos2); self->splashRadius = 40; // ?? some random number, maybe it's ok? - funcGlassDie( self, other, activator, self->health, MOD_UNKNOWN ); + funcGlassDie(self, other, activator, self->health, MOD_UNKNOWN); } //----------------------------------------------------- @@ -1069,63 +936,53 @@ INVINCIBLE - can only be broken by being used "health" default is 1 */ //----------------------------------------------------- -void SP_func_glass( gentity_t *self ) -{ - if ( !(self->spawnflags & 1 )) - { - if ( !self->health ) - { +void SP_func_glass(gentity_t *self) { + if (!(self->spawnflags & 1)) { + if (!self->health) { self->health = 1; } } - if ( self->health ) - { + if (self->health) { self->takedamage = qtrue; } self->e_UseFunc = useF_funcGlassUse; self->e_DieFunc = dieF_funcGlassDie; - VectorCopy( self->s.origin, self->pos1 ); - - gi.SetBrushModel( self, self->model ); - self->svFlags |= (SVF_GLASS_BRUSH|SVF_BBRUSH); + VectorCopy(self->s.origin, self->pos1); + + gi.SetBrushModel(self, self->model); + self->svFlags |= (SVF_GLASS_BRUSH | SVF_BBRUSH); self->material = MAT_GLASS; self->s.eType = ET_MOVER; self->s.pos.trType = TR_STATIONARY; - VectorCopy( self->pos1, self->s.pos.trBase ); + VectorCopy(self->pos1, self->s.pos.trBase); - G_SoundIndex( "sound/effects/glassbreak1.wav" ); - G_EffectIndex( "glass_impact" ); + G_SoundIndex("sound/effects/glassbreak1.wav"); + G_EffectIndex("glass_impact"); - gi.linkentity( self ); + gi.linkentity(self); } -qboolean G_EntIsBreakable( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_EntIsBreakable(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } gentity_t *ent = &g_entities[entityNum]; - if ( (ent->svFlags&SVF_GLASS_BRUSH) ) - { + if ((ent->svFlags & SVF_GLASS_BRUSH)) { return qtrue; } - if ( (ent->svFlags&SVF_BBRUSH) ) - { + if ((ent->svFlags & SVF_BBRUSH)) { return qtrue; } - if ( !Q_stricmp( "misc_model_breakable", ent->classname ) ) - { + if (!Q_stricmp("misc_model_breakable", ent->classname)) { return qtrue; } - if ( !Q_stricmp( "misc_maglock", ent->classname ) ) - { + if (!Q_stricmp("misc_maglock", ent->classname)) { return qtrue; } diff --git a/codeJK2/game/g_camera.cpp b/codeJK2/game/g_camera.cpp index e52c6f93b8..266eab47b1 100644 --- a/codeJK2/game/g_camera.cpp +++ b/codeJK2/game/g_camera.cpp @@ -22,7 +22,7 @@ along with this program; if not, see . #include "g_headers.h" -//g_camera.cpp +// g_camera.cpp #include "g_local.h" //#include "Q3_Interface.h" //#include "anims.h" @@ -70,11 +70,9 @@ The focal point for a camera in a scene "speed" angular speed modifier - 100 is normal */ -void SP_misc_camera_focus (gentity_t *self) -{ - if(!self->targetname) - { - gi.Printf(S_COLOR_RED"ERROR: misc_camera_focus with no targetname\n"); +void SP_misc_camera_focus(gentity_t *self) { + if (!self->targetname) { + gi.Printf(S_COLOR_RED "ERROR: misc_camera_focus with no targetname\n"); G_FreeEntity(self); return; } @@ -91,7 +89,7 @@ void SP_misc_camera_focus (gentity_t *self) */ self->speed = 0; self->script_targetname = self->targetname; -// self->e_UseFunc = useF_misc_camera_focus_use; + // self->e_UseFunc = useF_misc_camera_focus_use; } /* @@ -114,7 +112,7 @@ void misc_camera_track_think (gentity_t *self) self->enemy = NULL; } } - + if( !self->enemy) { if( self->target && self->target[0] ) @@ -186,66 +184,59 @@ use "path_corner"s - path it should stay on- if that path_corner has a speed val "radius" - How far camera should try to stay from it's subject, default is 0 (dist doesn't matter), can pick this up from a path_corner too */ -void SP_misc_camera_track (gentity_t *self) -{ - if(!self->targetname || !self->targetname[0]) - { - gi.Printf(S_COLOR_RED"ERROR: misc_camera_track with no targetname\n"); +void SP_misc_camera_track(gentity_t *self) { + if (!self->targetname || !self->targetname[0]) { + gi.Printf(S_COLOR_RED "ERROR: misc_camera_track with no targetname\n"); G_FreeEntity(self); return; } self->script_targetname = self->targetname; - //self->moveInfo.speed = self->speed/10; + // self->moveInfo.speed = self->speed/10; -// self->e_UseFunc = useF_misc_camera_track_use; + // self->e_UseFunc = useF_misc_camera_track_use; } - //------------------------------------------------- // Bezier camera stuff //------------------------------------------------- -void cam_point_link( gentity_t *ent ) -{ +void cam_point_link(gentity_t *ent) {} -} +void cam_ctrl_point_link(gentity_t *ent) { + /* gentity_t *target2 = NULL; -void cam_ctrl_point_link( gentity_t *ent ) -{ -/* gentity_t *target2 = NULL; + target2 = G_Find( NULL, FOFS(targetname), ent->target2 ); - target2 = G_Find( NULL, FOFS(targetname), ent->target2 ); - - if ( !target2 ) - { - // Bah, you fool! Target2 not found - Com_Printf( "cam_point_link: target2 specified but not found: %s\n", ent->target2 ); - G_FreeEntity( ent ); - return; - } - - // Store the control point here - VectorCopy( target2->s.origin, ent->pos1 ); - - //--------------------- - if ( ent->target ) - { - gentity_t *target = NULL; - - target = G_Find( NULL, FOFS(targetname), ent->target ); - - if ( !target ) + if ( !target2 ) { - // Bah, you fool! Target not found - Com_Printf( "cam_point_link: target specified but not found: %s\n", ent->target ); + // Bah, you fool! Target2 not found + Com_Printf( "cam_point_link: target2 specified but not found: %s\n", ent->target2 ); G_FreeEntity( ent ); return; } - ent->nextTrain = target; - } -*/ + // Store the control point here + VectorCopy( target2->s.origin, ent->pos1 ); + + //--------------------- + if ( ent->target ) + { + gentity_t *target = NULL; + + target = G_Find( NULL, FOFS(targetname), ent->target ); + + if ( !target ) + { + // Bah, you fool! Target not found + Com_Printf( "cam_point_link: target specified but not found: %s\n", ent->target ); + G_FreeEntity( ent ); + return; + } + + ent->nextTrain = target; + } + */ } /*QUAK-ED cam_point (0.25 0 0.5) (-2 -2 -2) (2 2 2) @@ -254,23 +245,22 @@ A camera point used to construct a camera bezier path Every cam_point MUST be targeted (target2) at one and only one control point */ -void SP_cam_point( gentity_t *ent ) -{ -/* if ( !ent->target2 ) - { - // Bah, you fool! Target2 not found so we have no idea how to make the curve - Com_Printf( "cam_point_link: target2 was required but not found\n" ); - G_FreeEntity( ent ); - return; +void SP_cam_point(gentity_t *ent) { + /* if ( !ent->target2 ) + { + // Bah, you fool! Target2 not found so we have no idea how to make the curve + Com_Printf( "cam_point_link: target2 was required but not found\n" ); + G_FreeEntity( ent ); + return; - } + } - // The thing we are targeting may not be spawned in yet so, wait a bit to try and link to it - ent->e_ThinkFunc = thinkF_cam_ctrl_point_link; - ent->nextthink = level.time + 200; + // The thing we are targeting may not be spawned in yet so, wait a bit to try and link to it + ent->e_ThinkFunc = thinkF_cam_ctrl_point_link; + ent->nextthink = level.time + 200; - // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); - gi.linkentity( ent ); -*/ + // Save our position and link us up! + G_SetOrigin( ent, ent->s.origin ); + gi.linkentity( ent ); + */ } \ No newline at end of file diff --git a/codeJK2/game/g_client.cpp b/codeJK2/game/g_client.cpp index 36e99e2bc8..3eea9b8796 100644 --- a/codeJK2/game/g_client.cpp +++ b/codeJK2/game/g_client.cpp @@ -29,11 +29,11 @@ along with this program; if not, see . #include "g_icarus.h" #include "wp_saber.h" -extern void Q3_DebugPrint( int level, const char *format, ... ); -extern void WP_SaberInitBladeData( gentity_t *ent ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -extern qboolean CheatsOk( gentity_t *ent ); -extern vmCvar_t cg_thirdPersonAlpha; +extern void Q3_DebugPrint(int level, const char *format, ...); +extern void WP_SaberInitBladeData(gentity_t *ent); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +extern qboolean CheatsOk(gentity_t *ent); +extern vmCvar_t cg_thirdPersonAlpha; // g_client.c -- client functions that don't happen every frame @@ -41,27 +41,25 @@ float DEFAULT_MINS_0 = -16; float DEFAULT_MINS_1 = -16; float DEFAULT_MAXS_0 = 16; float DEFAULT_MAXS_1 = 16; -float DEFAULT_PLAYER_RADIUS = sqrt((DEFAULT_MAXS_0*DEFAULT_MAXS_0) + (DEFAULT_MAXS_1*DEFAULT_MAXS_1)); +float DEFAULT_PLAYER_RADIUS = sqrt((DEFAULT_MAXS_0 * DEFAULT_MAXS_0) + (DEFAULT_MAXS_1 * DEFAULT_MAXS_1)); vec3_t playerMins = {DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2}; vec3_t playerMaxs = {DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2}; -void SP_misc_teleporter_dest (gentity_t *ent); +void SP_misc_teleporter_dest(gentity_t *ent); /*QUAK-ED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) - - NODRAW potential spawning position for deathmatch games. Targets will be fired when someone spawns in on them. */ void SP_info_player_deathmatch(gentity_t *ent) { - SP_misc_teleporter_dest (ent); + SP_misc_teleporter_dest(ent); - if ( ent->spawnflags & 32 ) // STUN_BATON + if (ent->spawnflags & 32) // STUN_BATON { - RegisterItem( FindItemForWeapon( WP_STUN_BATON )); - } - else - { - RegisterItem( FindItemForWeapon( WP_SABER ) ); //these are given in ClientSpawn(), but we register them now before cgame starts - G_SkinIndex("models/players/kyle/model_fpls2.skin"); //preache the skin used in cg_players.cpp + RegisterItem(FindItemForWeapon(WP_STUN_BATON)); + } else { + RegisterItem(FindItemForWeapon(WP_SABER)); // these are given in ClientSpawn(), but we register them now before cgame starts + G_SkinIndex("models/players/kyle/model_fpls2.skin"); // preache the skin used in cg_players.cpp } } @@ -76,13 +74,11 @@ equivalant to info_player_deathmatch void SP_info_player_start(gentity_t *ent) { ent->classname = "info_player_deathmatch"; - ent->spawnflags |= 1; // James suggests force-ORing the KEEP_PREV flag in for now + ent->spawnflags |= 1; // James suggests force-ORing the KEEP_PREV flag in for now - SP_info_player_deathmatch( ent ); + SP_info_player_deathmatch(ent); } - - /* ======================================================================= @@ -97,35 +93,30 @@ SpotWouldTelefrag ================ */ -qboolean SpotWouldTelefrag( gentity_t *spot, team_t checkteam ) -{ - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag(gentity_t *spot, team_t checkteam) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; // If we have a mins, use that instead of the hardcoded bounding box - if ( !VectorCompare(spot->mins, vec3_origin) && VectorLength( spot->mins ) ) - VectorAdd( spot->s.origin, spot->mins, mins ); + if (!VectorCompare(spot->mins, vec3_origin) && VectorLength(spot->mins)) + VectorAdd(spot->s.origin, spot->mins, mins); else - VectorAdd( spot->s.origin, playerMins, mins ); + VectorAdd(spot->s.origin, playerMins, mins); // If we have a maxs, use that instead of the hardcoded bounding box - if ( !VectorCompare(spot->maxs, vec3_origin) && VectorLength( spot->maxs ) ) - VectorAdd( spot->s.origin, spot->maxs, maxs ); + if (!VectorCompare(spot->maxs, vec3_origin) && VectorLength(spot->maxs)) + VectorAdd(spot->s.origin, spot->maxs, maxs); else - VectorAdd( spot->s.origin, playerMaxs, maxs ); + VectorAdd(spot->s.origin, playerMaxs, maxs); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient && hit->client->ps.stats[STAT_HEALTH] > 0 ) - { - if ( hit->contents & CONTENTS_BODY ) - { - if( checkteam == TEAM_FREE || hit->client->playerTeam == checkteam ) - {//checking against teammates only...? + if (hit != spot && hit->client && hit->client->ps.stats[STAT_HEALTH] > 0) { + if (hit->contents & CONTENTS_BODY) { + if (checkteam == TEAM_FREE || hit->client->playerTeam == checkteam) { // checking against teammates only...? return qtrue; } } @@ -135,26 +126,22 @@ qboolean SpotWouldTelefrag( gentity_t *spot, team_t checkteam ) return qfalse; } -qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ) -{ - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; - VectorAdd( dest, mover->mins, mins ); - VectorAdd( dest, mover->maxs, maxs ); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(dest, mover->mins, mins); + VectorAdd(dest, mover->maxs, maxs); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; icontents & mover->contents ) - { + if (hit->contents & mover->contents) { return qtrue; } } @@ -168,17 +155,17 @@ SelectNearestDeathmatchSpawnPoint Find the spot that we DON'T want to use ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { - gentity_t *spot; - float dist, nearestDist; - gentity_t *nearestSpot; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectNearestDeathmatchSpawnPoint(vec3_t from, team_t team) { + gentity_t *spot; + float dist, nearestDist; + gentity_t *nearestSpot; - nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; + nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; nearestSpot = NULL; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { /*if ( team == TEAM_RED && ( spot->spawnflags & 2 ) ) { continue; } @@ -186,12 +173,12 @@ gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { continue; }*/ - if ( spot->targetname != NULL ) { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted continue; } - dist = DistanceSquared( spot->s.origin, from ); - if ( dist < nearestDist ) { + dist = DistanceSquared(spot->s.origin, from); + if (dist < nearestDist) { nearestDist = dist; nearestSpot = spot; } @@ -200,7 +187,6 @@ gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from, team_t team ) { return nearestSpot; } - /* ================ SelectRandomDeathmatchSpawnPoint @@ -208,17 +194,17 @@ SelectRandomDeathmatchSpawnPoint go to a random point that doesn't telefrag ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectRandomDeathmatchSpawnPoint( team_t team ) { - gentity_t *spot; - int count; - int selection; - gentity_t *spots[MAX_SPAWN_POINTS]; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectRandomDeathmatchSpawnPoint(team_t team) { + gentity_t *spot; + int count; + int selection; + gentity_t *spots[MAX_SPAWN_POINTS]; count = 0; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { /*if ( team == TEAM_RED && ( spot->spawnflags & 2 ) ) { continue; } @@ -226,39 +212,34 @@ gentity_t *SelectRandomDeathmatchSpawnPoint( team_t team ) { continue; }*/ - if ( spot->targetname != NULL ) { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted continue; } - if ( SpotWouldTelefrag( spot, TEAM_FREE ) ) { + if (SpotWouldTelefrag(spot, TEAM_FREE)) { continue; } - spots[ count ] = spot; + spots[count] = spot; count++; } - if ( !count ) { // no spots that won't telefrag - spot = G_Find( NULL, FOFS(classname), "info_player_deathmatch"); - if ( !spot ) - { + if (!count) { // no spots that won't telefrag + spot = G_Find(NULL, FOFS(classname), "info_player_deathmatch"); + if (!spot) { return NULL; } - if ( spot->targetname != NULL ) - { - //this search routine should never find a spot that is targetted + if (spot->targetname != NULL) { + // this search routine should never find a spot that is targetted return NULL; - } - else - { + } else { return spot; } } selection = rand() % count; - return spots[ selection ]; + return spots[selection]; } - /* =========== SelectSpawnPoint @@ -266,78 +247,66 @@ SelectSpawnPoint Chooses a player start, deathmatch start, etc ============ */ -gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, team_t team, vec3_t origin, vec3_t angles ) { - gentity_t *spot; - gentity_t *nearestSpot; - - if ( level.spawntarget[0] ) - {//we have a spawnpoint specified, try to find it - if ( (nearestSpot = spot = G_Find( NULL, FOFS(targetname), level.spawntarget )) == NULL ) - {//you HAVE to be able to find the desired spot - G_Error( "Couldn't find spawntarget %s", level.spawntarget ); +gentity_t *SelectSpawnPoint(vec3_t avoidPoint, team_t team, vec3_t origin, vec3_t angles) { + gentity_t *spot; + gentity_t *nearestSpot; + + if (level.spawntarget[0]) { // we have a spawnpoint specified, try to find it + if ((nearestSpot = spot = G_Find(NULL, FOFS(targetname), level.spawntarget)) == NULL) { // you HAVE to be able to find the desired spot + G_Error("Couldn't find spawntarget %s", level.spawntarget); return NULL; } - } - else - {//not looking for a special startspot - nearestSpot = SelectNearestDeathmatchSpawnPoint( avoidPoint, team ); + } else { // not looking for a special startspot + nearestSpot = SelectNearestDeathmatchSpawnPoint(avoidPoint, team); - spot = SelectRandomDeathmatchSpawnPoint ( team ); - if ( spot == nearestSpot ) { + spot = SelectRandomDeathmatchSpawnPoint(team); + if (spot == nearestSpot) { // roll again if it would be real close to point of death - spot = SelectRandomDeathmatchSpawnPoint ( team ); + spot = SelectRandomDeathmatchSpawnPoint(team); } } // find a single player start spot if (!spot) { - G_Error( "Couldn't find a spawn point" ); + G_Error("Couldn't find a spawn point"); } - - VectorCopy( spot->s.origin, origin ); - if ( spot->spawnflags & 2 ) - { - trace_t tr; + VectorCopy(spot->s.origin, origin); + if (spot->spawnflags & 2) { + trace_t tr; origin[2] = MIN_WORLD_COORD; - gi.trace(&tr, spot->s.origin, playerMins, playerMaxs, origin, ENTITYNUM_NONE, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); - if ( tr.fraction < 1.0 && !tr.allsolid && !tr.startsolid ) - {//found a floor - VectorCopy(tr.endpos, origin ); - } - else - {//In solid or too far - VectorCopy( spot->s.origin, origin ); + gi.trace(&tr, spot->s.origin, playerMins, playerMaxs, origin, ENTITYNUM_NONE, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); + if (tr.fraction < 1.0 && !tr.allsolid && !tr.startsolid) { // found a floor + VectorCopy(tr.endpos, origin); + } else { // In solid or too far + VectorCopy(spot->s.origin, origin); } } origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } - //====================================================================== - /* ================== SetClientViewAngle ================== */ -void SetClientViewAngle( gentity_t *ent, vec3_t angle ) { - int i; +void SetClientViewAngle(gentity_t *ent, vec3_t angle) { + int i; // set the delta angle - for (i=0 ; i<3 ; i++) - { - ent->client->ps.delta_angles[i] = (ANGLE2SHORT(angle[i]) - ent->client->pers.cmd_angles[i])&0xffff; + for (i = 0; i < 3; i++) { + ent->client->ps.delta_angles[i] = (ANGLE2SHORT(angle[i]) - ent->client->pers.cmd_angles[i]) & 0xffff; } - VectorCopy( angle, ent->s.angles ); - VectorCopy (ent->s.angles, ent->client->ps.viewangles); + VectorCopy(angle, ent->s.angles); + VectorCopy(ent->s.angles, ent->client->ps.viewangles); } /* @@ -345,29 +314,28 @@ void SetClientViewAngle( gentity_t *ent, vec3_t angle ) { respawn ================ */ -void respawn( gentity_t *ent ) { +void respawn(gentity_t *ent) { - gi.SendConsoleCommand("load *respawn\n"); // special case + gi.SendConsoleCommand("load *respawn\n"); // special case } - /* ================ PickTeam ================ */ -team_t PickTeam( int ignoreClientNum ) { - int i; - int counts[TEAM_NUM_TEAMS]; +team_t PickTeam(int ignoreClientNum) { + int i; + int counts[TEAM_NUM_TEAMS]; - memset( counts, 0, sizeof( counts ) ); + memset(counts, 0, sizeof(counts)); - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( i == ignoreClientNum ) { + for (i = 0; i < level.maxclients; i++) { + if (i == ignoreClientNum) { continue; } - if ( level.clients[i].pers.connected == CON_DISCONNECTED ) { + if (level.clients[i].pers.connected == CON_DISCONNECTED) { continue; } } @@ -382,7 +350,7 @@ ForceClientSkin Forces a client's skin (for teamplay) =========== */ -void ForceClientSkin( gclient_t *client, char *model, const char *skin ) { +void ForceClientSkin(gclient_t *client, char *model, const char *skin) { char *p; if ((p = strchr(model, '/')) != NULL) { @@ -398,32 +366,27 @@ void ForceClientSkin( gclient_t *client, char *model, const char *skin ) { ClientCheckName ============ */ -static void ClientCleanName( const char *in, char *out, int outSize ) -{ +static void ClientCleanName(const char *in, char *out, int outSize) { int outpos = 0, colorlessLen = 0, spaces = 0; // discard leading spaces - for ( ; *in == ' '; in++); + for (; *in == ' '; in++) + ; // discard leading asterisk's (fail raven for using * as a skipnotify) // apparently .* causes the issue too so... derp - //for(; *in == '*'; in++); + // for(; *in == '*'; in++); - for(; *in && outpos < outSize - 1; in++) - { + for (; *in && outpos < outSize - 1; in++) { out[outpos] = *in; - if ( *in == ' ' ) - {// don't allow too many consecutive spaces - if ( spaces > 2 ) + if (*in == ' ') { // don't allow too many consecutive spaces + if (spaces > 2) continue; spaces++; - } - else if ( outpos > 0 && out[outpos-1] == Q_COLOR_ESCAPE ) - { - if ( Q_IsColorStringExt( &out[outpos-1] ) ) - { + } else if (outpos > 0 && out[outpos - 1] == Q_COLOR_ESCAPE) { + if (Q_IsColorStringExt(&out[outpos - 1])) { colorlessLen--; #if 0 @@ -433,15 +396,11 @@ static void ClientCleanName( const char *in, char *out, int outSize ) continue; } #endif - } - else - { + } else { spaces = 0; colorlessLen++; } - } - else - { + } else { spaces = 0; colorlessLen++; } @@ -452,8 +411,8 @@ static void ClientCleanName( const char *in, char *out, int outSize ) out[outpos] = '\0'; // don't allow empty names - if ( *out == '\0' || colorlessLen == 0 ) - Q_strncpyz( out, "Padawan", outSize ); + if (*out == '\0' || colorlessLen == 0) + Q_strncpyz(out, "Padawan", outSize); } /* @@ -467,50 +426,48 @@ The game can override any of the settings and call gi.SetUserinfo if desired. ============ */ -void ClientUserinfoChanged( int clientNum ) { - gentity_t *ent = g_entities + clientNum; - gclient_t *client = ent->client; - int health=100, maxHealth=100; - const char *s=NULL, *sex=NULL; - char userinfo[MAX_INFO_STRING]={0}, buf[MAX_INFO_STRING]={0}, - oldname[34]={0}; +void ClientUserinfoChanged(int clientNum) { + gentity_t *ent = g_entities + clientNum; + gclient_t *client = ent->client; + int health = 100, maxHealth = 100; + const char *s = NULL, *sex = NULL; + char userinfo[MAX_INFO_STRING] = {0}, buf[MAX_INFO_STRING] = {0}, oldname[34] = {0}; - gi.GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + gi.GetUserinfo(clientNum, userinfo, sizeof(userinfo)); // set name - Q_strncpyz ( oldname, client->pers.netname, sizeof( oldname ) ); - s = Info_ValueForKey (userinfo, "name"); - ClientCleanName( s, client->pers.netname, sizeof( client->pers.netname ) ); + Q_strncpyz(oldname, client->pers.netname, sizeof(oldname)); + s = Info_ValueForKey(userinfo, "name"); + ClientCleanName(s, client->pers.netname, sizeof(client->pers.netname)); // set max health maxHealth = 100; - health = Com_Clampi( 1, 100, atoi( Info_ValueForKey( userinfo, "handicap" ) ) ); + health = Com_Clampi(1, 100, atoi(Info_ValueForKey(userinfo, "handicap"))); client->pers.maxHealth = health; - if ( client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth ) + if (client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth) client->pers.maxHealth = 100; client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth; // sex - sex = Info_ValueForKey( userinfo, "sex" ); - if ( !sex[0] ) { + sex = Info_ValueForKey(userinfo, "sex"); + if (!sex[0]) { sex = "m"; } // send over a subset of the userinfo keys so other clients can // print scoreboards, display models, and play custom sounds buf[0] = '\0'; - Q_strcat( buf, sizeof( buf ), va( "n\\%s\\", client->pers.netname ) ); - Q_strcat( buf, sizeof( buf ), va( "t\\%i\\", client->sess.sessionTeam ) ); - Q_strcat( buf, sizeof( buf ), "headModel\\\\" ); - Q_strcat( buf, sizeof( buf ), "torsoModel\\\\" ); - Q_strcat( buf, sizeof( buf ), "legsModel\\\\" ); - Q_strcat( buf, sizeof( buf ), va( "sex\\%s\\", sex ) ); - Q_strcat( buf, sizeof( buf ), va( "hc\\%i\\", client->pers.maxHealth ) ); - - gi.SetConfigstring( CS_PLAYERS+clientNum, buf ); + Q_strcat(buf, sizeof(buf), va("n\\%s\\", client->pers.netname)); + Q_strcat(buf, sizeof(buf), va("t\\%i\\", client->sess.sessionTeam)); + Q_strcat(buf, sizeof(buf), "headModel\\\\"); + Q_strcat(buf, sizeof(buf), "torsoModel\\\\"); + Q_strcat(buf, sizeof(buf), "legsModel\\\\"); + Q_strcat(buf, sizeof(buf), va("sex\\%s\\", sex)); + Q_strcat(buf, sizeof(buf), va("hc\\%i\\", client->pers.maxHealth)); + + gi.SetConfigstring(CS_PLAYERS + clientNum, buf); } - /* =========== ClientConnect @@ -531,47 +488,43 @@ to the server machine, but qfalse on map changes and tournement restarts. ============ */ -char *ClientConnect( int clientNum, qboolean firstTime, SavedGameJustLoaded_e eSavedGameJustLoaded ) -{ - gentity_t *ent = &g_entities[ clientNum ]; - char userinfo[MAX_INFO_STRING] = {0}; +char *ClientConnect(int clientNum, qboolean firstTime, SavedGameJustLoaded_e eSavedGameJustLoaded) { + gentity_t *ent = &g_entities[clientNum]; + char userinfo[MAX_INFO_STRING] = {0}; - gi.GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + gi.GetUserinfo(clientNum, userinfo, sizeof(userinfo)); // they can connect ent->client = level.clients + clientNum; gclient_t *client = ent->client; -// if (!qbFromSavedGame) - if (eSavedGameJustLoaded != eFULL) - { - clientSession_t savedSess = client->sess; // - memset( client, 0, sizeof(*client) ); + // if (!qbFromSavedGame) + if (eSavedGameJustLoaded != eFULL) { + clientSession_t savedSess = client->sess; // + memset(client, 0, sizeof(*client)); client->sess = savedSess; } client->pers.connected = CON_CONNECTING; - if (eSavedGameJustLoaded == eFULL)//qbFromSavedGame) + if (eSavedGameJustLoaded == eFULL) // qbFromSavedGame) { // G_WriteClientSessionData( client ); // forget it, this is DM stuff anyway // get and distribute relevent paramters - ClientUserinfoChanged( clientNum ); - } - else - { + ClientUserinfoChanged(clientNum); + } else { // read or initialize the session data - if ( firstTime ) { - G_InitSessionData( client, userinfo ); + if (firstTime) { + G_InitSessionData(client, userinfo); } - G_ReadSessionData( client ); + G_ReadSessionData(client); // get and distribute relevent paramters - ClientUserinfoChanged( clientNum ); + ClientUserinfoChanged(clientNum); // don't do the "xxx connected" messages if they were caried over from previous level - if ( firstTime ) { - gi.SendServerCommand( -1, "print \"%s connected\n\"", client->pers.netname); + if (firstTime) { + gi.SendServerCommand(-1, "print \"%s connected\n\"", client->pers.netname); } } @@ -587,41 +540,39 @@ to be placed into the level. This will happen every level load, and on transition between teams, but doesn't happen on respawns ============ */ -void ClientBegin( int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded) +void ClientBegin(int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded) // qboolean qbFromSavedGame { - gentity_t *ent; - gclient_t *client; + gentity_t *ent; + gclient_t *client; ent = g_entities + clientNum; client = level.clients + clientNum; - if (eSavedGameJustLoaded == eFULL)//qbFromSavedGame) + if (eSavedGameJustLoaded == eFULL) // qbFromSavedGame) { client->pers.connected = CON_CONNECTED; ent->client = client; - ClientSpawn( ent, eSavedGameJustLoaded ); - } - else - { - if ( ent->linked ) { - gi.unlinkentity( ent ); + ClientSpawn(ent, eSavedGameJustLoaded); + } else { + if (ent->linked) { + gi.unlinkentity(ent); } - G_InitGentity( ent ); + G_InitGentity(ent); ent->e_TouchFunc = touchF_NULL; - ent->e_PainFunc = painF_PlayerPain;//painF_NULL; + ent->e_PainFunc = painF_PlayerPain; // painF_NULL; ent->client = client; client->pers.connected = CON_CONNECTED; client->pers.teamState.state = TEAM_BEGIN; - VectorCopyM( cmd->angles, client->pers.cmd_angles ); + VectorCopyM(cmd->angles, client->pers.cmd_angles); - memset( &client->ps, 0, sizeof( client->ps ) ); - memset( &client->sess.missionStats, 0, sizeof( client->sess.missionStats ) ); + memset(&client->ps, 0, sizeof(client->ps)); + memset(&client->sess.missionStats, 0, sizeof(client->sess.missionStats)); client->sess.missionStats.totalSecrets = gi.Cvar_VariableIntegerValue("newTotalSecrets"); // locate ent at a spawn point - if ( ClientSpawn( ent, eSavedGameJustLoaded) ) // SavedGameJustLoaded_e + if (ClientSpawn(ent, eSavedGameJustLoaded)) // SavedGameJustLoaded_e { // send teleport event } @@ -630,8 +581,6 @@ void ClientBegin( int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGam } } - - /* ============ Player_CacheFromPrevLevel @@ -640,39 +589,34 @@ Player_CacheFromPrevLevel Argument : void ============ */ -void Player_CacheFromPrevLevel(void) -{ - char s[MAX_STRING_CHARS]; - int i; +void Player_CacheFromPrevLevel(void) { + char s[MAX_STRING_CHARS]; + int i; - gi.Cvar_VariableStringBuffer( sCVARNAME_PLAYERSAVE, s, sizeof(s) ); + gi.Cvar_VariableStringBuffer(sCVARNAME_PLAYERSAVE, s, sizeof(s)); - if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer + if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer { int iDummy, bits, ibits; - sscanf( s, "%i %i %i %i", - &iDummy,//client->ps.stats[STAT_HEALTH], - &iDummy,//client->ps.stats[STAT_ARMOR], - &bits, //client->ps.stats[STAT_WEAPONS] - &ibits //client->ps.stats[STAT_ITEMS] - ); + sscanf(s, "%i %i %i %i", + &iDummy, // client->ps.stats[STAT_HEALTH], + &iDummy, // client->ps.stats[STAT_ARMOR], + &bits, // client->ps.stats[STAT_WEAPONS] + &ibits // client->ps.stats[STAT_ITEMS] + ); - for ( i = 1 ; i < 16 ; i++ ) - { - if ( bits & ( 1 << i ) ) - { - RegisterItem( FindItemForWeapon( (weapon_t)i ) ); + for (i = 1; i < 16; i++) { + if (bits & (1 << i)) { + RegisterItem(FindItemForWeapon((weapon_t)i)); } } -extern gitem_t *FindItemForInventory( int inv ); + extern gitem_t *FindItemForInventory(int inv); - for ( i = 1 ; i < 16 ; i++ ) - { - if ( ibits & ( 1 << i ) ) - { - RegisterItem( FindItemForInventory( i-1 )); + for (i = 1; i < 16; i++) { + if (ibits & (1 << i)) { + RegisterItem(FindItemForInventory(i - 1)); } } } @@ -686,90 +630,71 @@ Player_RestoreFromPrevLevel Argument : gentity_t *ent ============ */ -void Player_RestoreFromPrevLevel(gentity_t *ent) -{ - gclient_t *client = ent->client; - int i; +void Player_RestoreFromPrevLevel(gentity_t *ent) { + gclient_t *client = ent->client; + int i; assert(client); - if (client) // though I can't see it not being true... + if (client) // though I can't see it not being true... { - char s[MAX_STRING_CHARS]; - const char *var; + char s[MAX_STRING_CHARS]; + const char *var; int saberActive; - gi.Cvar_VariableStringBuffer( sCVARNAME_PLAYERSAVE, s, sizeof(s) ); + gi.Cvar_VariableStringBuffer(sCVARNAME_PLAYERSAVE, s, sizeof(s)); - if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer + if (strlen(s)) // actually this would be safe anyway because of the way sscanf() works, but this is clearer { - sscanf( s, "%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %i", - &client->ps.stats[STAT_HEALTH], - &client->ps.stats[STAT_ARMOR], - &client->ps.stats[STAT_WEAPONS], - &client->ps.stats[STAT_ITEMS], - &client->ps.weapon, - &client->ps.weaponstate, - &client->ps.batteryCharge, - &client->ps.viewangles[0], - &client->ps.viewangles[1], - &client->ps.viewangles[2], - &client->ps.forcePowersKnown, - &client->ps.forcePower, - &saberActive, - &client->ps.saberAnimLevel, - &client->ps.saberLockEnemy, - &client->ps.saberLockTime - ); + sscanf(s, "%i %i %i %i %i %i %i %f %f %f %i %i %i %i %i %i", &client->ps.stats[STAT_HEALTH], &client->ps.stats[STAT_ARMOR], + &client->ps.stats[STAT_WEAPONS], &client->ps.stats[STAT_ITEMS], &client->ps.weapon, &client->ps.weaponstate, &client->ps.batteryCharge, + &client->ps.viewangles[0], &client->ps.viewangles[1], &client->ps.viewangles[2], &client->ps.forcePowersKnown, &client->ps.forcePower, + &saberActive, &client->ps.saberAnimLevel, &client->ps.saberLockEnemy, &client->ps.saberLockTime); client->ps.saberActive = (saberActive ? qtrue : qfalse); ent->health = client->ps.stats[STAT_HEALTH]; -// slight issue with ths for the moment in that although it'll correctly restore angles it doesn't take into account -// the overall map orientation, so (eg) exiting east to enter south will be out by 90 degrees, best keep spawn angles for now -// -// VectorClear (ent->client->pers.cmd_angles); -// -// SetClientViewAngle( ent, ent->client->ps.viewangles); - - //ammo - gi.Cvar_VariableStringBuffer( "playerammo", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->ps.ammo[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + // slight issue with ths for the moment in that although it'll correctly restore angles it doesn't take into account + // the overall map orientation, so (eg) exiting east to enter south will be out by 90 degrees, best keep spawn angles for now + // + // VectorClear (ent->client->pers.cmd_angles); + // + // SetClientViewAngle( ent, ent->client->ps.viewangles); + + // ammo + gi.Cvar_VariableStringBuffer("playerammo", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->ps.ammo[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==AMMO_MAX); - - //inventory - gi.Cvar_VariableStringBuffer( "playerinv", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->ps.inventory[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + assert(i == AMMO_MAX); + + // inventory + gi.Cvar_VariableStringBuffer("playerinv", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->ps.inventory[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==INV_MAX); - + assert(i == INV_MAX); // the new JK2 stuff - force powers, etc... // - gi.Cvar_VariableStringBuffer( "playerfplvl", s, sizeof(s) ); - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->ps.forcePowerLevel[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + gi.Cvar_VariableStringBuffer("playerfplvl", s, sizeof(s)); + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->ps.forcePowerLevel[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==NUM_FORCE_POWERS); + assert(i == NUM_FORCE_POWERS); client->ps.forcePowerMax = FORCE_POWER_MAX; client->ps.forceGripEntityNum = ENTITYNUM_NONE; @@ -780,136 +705,93 @@ void Player_RestoreFromPrevLevel(gentity_t *ent) /* Ghoul2 Insert Start */ -void G_SetSkin( gentity_t *ent, const char *modelName, const char *customSkin ) -{ - char skinName[MAX_QPATH]; - //ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. - //FIXME: is have an alternate skin (in modelName, after '/'), replace "default" with that skin name - if ( !customSkin ) - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_default.skin", modelName ); - } - else - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_%s.skin", modelName, customSkin ); +void G_SetSkin(gentity_t *ent, const char *modelName, const char *customSkin) { + char skinName[MAX_QPATH]; + // ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. + // FIXME: is have an alternate skin (in modelName, after '/'), replace "default" with that skin name + if (!customSkin) { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_default.skin", modelName); + } else { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_%s.skin", modelName, customSkin); } // lets see if it's out there - int skin = gi.RE_RegisterSkin( skinName ); - if ( skin ) - { + int skin = gi.RE_RegisterSkin(skinName); + if (skin) { // put it in the config strings // and set the ghoul2 model to use it - gi.G2API_SetSkin( &ent->ghoul2[ent->playerModel], G_SkinIndex( skinName ), skin ); + gi.G2API_SetSkin(&ent->ghoul2[ent->playerModel], G_SkinIndex(skinName), skin); } } -qboolean G_StandardHumanoid( const char *modelName ) -{ - if ( !modelName ) - { +qboolean G_StandardHumanoid(const char *modelName) { + if (!modelName) { return qfalse; } - if ( !Q_stricmp( "kyle", modelName ) || - !Q_strncmp( "st", modelName, 2 ) || - !Q_strncmp( "imp", modelName, 3 ) || - !Q_strncmp( "gran", modelName, 4 ) || - !Q_strncmp( "rodian", modelName, 6 ) || - !Q_strncmp( "weequay", modelName, 7 ) || - !Q_strncmp( "reborn", modelName, 6 ) || - !Q_strncmp( "shadowtrooper", modelName, 13 ) || - !Q_strncmp( "swamptrooper", modelName, 12 ) || - !Q_stricmp( "rockettrooper", modelName ) || - !Q_stricmp( "bespin_cop", modelName ) || - !Q_strncmp( "bespincop", modelName, 9 ) || - !Q_strncmp( "rebel", modelName, 5 ) || - !Q_strncmp( "ugnaught", modelName, 8 ) || - !Q_strncmp( "morgan", modelName,6 ) || - !Q_strncmp( "protocol", modelName, 8 ) || - !Q_strncmp( "jedi", modelName, 4 ) || - !Q_strncmp( "prisoner", modelName, 8 ) || - !Q_stricmp( "tavion", modelName ) || - !Q_stricmp( "desann", modelName ) || - !Q_stricmp( "trandoshan", modelName ) || - !Q_stricmp( "jan", modelName ) || - !Q_stricmp( "luke", modelName ) || - !Q_stricmp( "lando", modelName ) || - !Q_stricmp( "reelo", modelName ) || - !Q_stricmp( "bartender", modelName ) || - !Q_stricmp( "monmothma", modelName ) || - !Q_stricmp( "chiss", modelName ) || - !Q_stricmp( "galak", modelName ) ) - { + if (!Q_stricmp("kyle", modelName) || !Q_strncmp("st", modelName, 2) || !Q_strncmp("imp", modelName, 3) || !Q_strncmp("gran", modelName, 4) || + !Q_strncmp("rodian", modelName, 6) || !Q_strncmp("weequay", modelName, 7) || !Q_strncmp("reborn", modelName, 6) || + !Q_strncmp("shadowtrooper", modelName, 13) || !Q_strncmp("swamptrooper", modelName, 12) || !Q_stricmp("rockettrooper", modelName) || + !Q_stricmp("bespin_cop", modelName) || !Q_strncmp("bespincop", modelName, 9) || !Q_strncmp("rebel", modelName, 5) || + !Q_strncmp("ugnaught", modelName, 8) || !Q_strncmp("morgan", modelName, 6) || !Q_strncmp("protocol", modelName, 8) || + !Q_strncmp("jedi", modelName, 4) || !Q_strncmp("prisoner", modelName, 8) || !Q_stricmp("tavion", modelName) || !Q_stricmp("desann", modelName) || + !Q_stricmp("trandoshan", modelName) || !Q_stricmp("jan", modelName) || !Q_stricmp("luke", modelName) || !Q_stricmp("lando", modelName) || + !Q_stricmp("reelo", modelName) || !Q_stricmp("bartender", modelName) || !Q_stricmp("monmothma", modelName) || !Q_stricmp("chiss", modelName) || + !Q_stricmp("galak", modelName)) { return qtrue; } return qfalse; } -extern void G_LoadAnimFileSet( gentity_t *ent, const char *modelName ); -qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ) -{ - if ( ent->playerModel != -1 ) - {// we found the model ok - vec3_t angles = {0,0,0}; - const char *token; - const char *p; - - //Now turn on/off any surfaces - if ( surfOff && surfOff[0] ) - { +extern void G_LoadAnimFileSet(gentity_t *ent, const char *modelName); +qboolean G_SetG2PlayerModelInfo(gentity_t *ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn) { + if (ent->playerModel != -1) { // we found the model ok + vec3_t angles = {0, 0, 0}; + const char *token; + const char *p; + + // Now turn on/off any surfaces + if (surfOff && surfOff[0]) { p = surfOff; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn off this surf - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], token, 0x00000002/*G2SURFACEFLAG_OFF*/ ); + // turn off this surf + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], token, 0x00000002 /*G2SURFACEFLAG_OFF*/); } COM_EndParseSession(); } - if ( surfOn && surfOn[0] ) - { + if (surfOn && surfOn[0]) { p = surfOn; COM_BeginParseSession(); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn on this surf - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], token, 0 ); + // turn on this surf + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], token, 0); } COM_EndParseSession(); } - if ( ent->client->NPC_class == CLASS_IMPERIAL && ent->message ) - {//carrying a key, turn on the key sleeve surface (assuming we have one) - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "l_arm_key", 0 ); + if (ent->client->NPC_class == CLASS_IMPERIAL && ent->message) { // carrying a key, turn on the key sleeve surface (assuming we have one) + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "l_arm_key", 0); } - G_LoadAnimFileSet( ent, modelName ); - //we shouldn't actually have to do this anymore - //G_SetSkin( ent, modelName, customSkin ); + G_LoadAnimFileSet(ent, modelName); + // we shouldn't actually have to do this anymore + // G_SetSkin( ent, modelName, customSkin ); - ent->headBolt = ent->cervicalBolt = ent->torsoBolt = ent->gutBolt = ent->chestBolt = - ent->crotchBolt = ent->elbowLBolt = ent->elbowRBolt = ent->handLBolt = - ent->handRBolt = ent->kneeLBolt = ent->kneeRBolt = ent->footLBolt = - ent->footRBolt = -1; + ent->headBolt = ent->cervicalBolt = ent->torsoBolt = ent->gutBolt = ent->chestBolt = ent->crotchBolt = ent->elbowLBolt = ent->elbowRBolt = + ent->handLBolt = ent->handRBolt = ent->kneeLBolt = ent->kneeRBolt = ent->footLBolt = ent->footRBolt = -1; // now turn on the bolt in the hand - this one would be best always turned on. - if ( G_StandardHumanoid( modelName ) ) - {//temp hack because only the gran are set up right so far + if (G_StandardHumanoid(modelName)) { // temp hack because only the gran are set up right so far ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_eyes"); - ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical" ); - if ( !Q_stricmp("protocol", modelName ) ) - {//*sigh*, no thoracic bone + ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical"); + if (!Q_stricmp("protocol", modelName)) { //*sigh*, no thoracic bone ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); ent->chestBolt = ent->gutBolt; - } - else - { + } else { ent->chestBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "thoracic"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); } @@ -923,22 +805,15 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->kneeRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*hips_r_knee"); ent->footLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_leg_foot"); ent->footRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_leg_foot"); - } - else - { - if ( !Q_stricmp( "gonk", modelName ) || !Q_stricmp( "seeker", modelName ) || !Q_stricmp( "remote", modelName ) - || !Q_strncmp( "r2d2", modelName, 4 ) || !Q_strncmp( "r5d2", modelName, 4 ) ) - {//TEMP HACK: not a non-humanoid droid + } else { + if (!Q_stricmp("gonk", modelName) || !Q_stricmp("seeker", modelName) || !Q_stricmp("remote", modelName) || !Q_strncmp("r2d2", modelName, 4) || + !Q_strncmp("r5d2", modelName, 4)) { // TEMP HACK: not a non-humanoid droid ent->headBolt = -1; - } - else if (!Q_stricmp( "interrogator",modelName)) - { + } else if (!Q_stricmp("interrogator", modelName)) { ent->headBolt = -1; - } - else if (!Q_strncmp( "probe",modelName, 5)) - { - ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); // head pivot point - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Gun 1 + } else if (!Q_strncmp("probe", modelName, 5)) { + ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); // head pivot point + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Gun 1 } /* else if (!Q_strncmp( "protocol",modelName, 8)) @@ -946,50 +821,38 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->headBolt = -1; } */ - else if (!Q_stricmp( "sentry",modelName)) - { + else if (!Q_stricmp("sentry", modelName)) { ent->headBolt = -1; - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Gun 1 - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Gun 2 - ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash03"); // Gun 3 - } - else if (!Q_stricmp( "mark1",modelName)) - { + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Gun 1 + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Gun 2 + ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash03"); // Gun 3 + } else if (!Q_stricmp("mark1", modelName)) { ent->headBolt = -1; - ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Blaster Gun 1 - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Blaster Gun 2 - ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Blaster Gun 3 - ent->genericBolt4 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Blaster Gun 4 - ent->genericBolt5 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash5"); // Missile Gun 1 - } - else if (!Q_stricmp( "mark2",modelName)) - { + ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Blaster Gun 1 + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); // Blaster Gun 2 + ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Blaster Gun 3 + ent->genericBolt4 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Blaster Gun 4 + ent->genericBolt5 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash5"); // Missile Gun 1 + } else if (!Q_stricmp("mark2", modelName)) { ent->headBolt = -1; - ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Blaster Gun 1 - } - else if (!Q_stricmp( "atst",modelName) )//&& (ent->client->playerTeam != TEAM_PLAYER)) + ent->handRBolt = ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash"); // Blaster Gun 1 + } else if (!Q_stricmp("atst", modelName)) //&& (ent->client->playerTeam != TEAM_PLAYER)) { ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head"); - ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Front guns + ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash1"); // Front guns ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash2"); - ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Left side gun - ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Right side missle launcher + ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash3"); // Left side gun + ent->genericBolt2 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flash4"); // Right side missle launcher ent->footLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*l_foot"); ent->footRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*r_foot"); - } - else if ( !Q_stricmp( "minemonster", modelName )) - { + } else if (!Q_stricmp("minemonster", modelName)) { ent->handRBolt = ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_f1"); - } - else if ( !Q_stricmp( "howler", modelName )) - { + } else if (!Q_stricmp("howler", modelName)) { ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cranium"); // FIXME! - } - else if ( !Q_stricmp( "galak_mech", modelName )) - { + } else if (!Q_stricmp("galak_mech", modelName)) { ent->genericBolt1 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*antenna_effect"); ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*head_eyes"); ent->torsoBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "torso"); @@ -997,14 +860,11 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flasha"); ent->genericBolt3 = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flashb"); ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*flashc"); - } - else - {//TEMP HACK: not a non-humanoid droid - ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*weapon");//should be r_hand - if ( Q_stricmp( "atst", modelName ) ) - {//not an ATST + } else { // TEMP HACK: not a non-humanoid droid + ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*weapon"); // should be r_hand + if (Q_stricmp("atst", modelName)) { // not an ATST ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "*headg"); - ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical" ); + ent->cervicalBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "cervical"); ent->torsoBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "lower_lumbar"); ent->gutBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "upper_lumbar"); ent->chestBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "thoracic"); @@ -1028,27 +888,22 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch ent->lowerLumbarBone = BONE_INDEX_INVALID; ent->motionBone = BONE_INDEX_INVALID; ent->hipsBone = BONE_INDEX_INVALID; - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); ent->footLBone = BONE_INDEX_INVALID; ent->footRBone = BONE_INDEX_INVALID; // now add overrides on specific joints so the client can set angle overrides on the legs, torso and head - if ( !Q_stricmp( "gonk", modelName ) || !Q_stricmp( "seeker", modelName ) || !Q_stricmp( "remote", modelName ) ) - {// - } - else if (!Q_stricmp( "sentry",modelName)) - { - } - else if (!Q_strncmp( "probe", modelName, 5 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + if (!Q_stricmp("gonk", modelName) || !Q_stricmp("seeker", modelName) || !Q_stricmp("remote", modelName)) { // + } else if (!Q_stricmp("sentry", modelName)) { + } else if (!Q_strncmp("probe", modelName, 5)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "pelvis", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "pelvis", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } } /* @@ -1056,215 +911,192 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch { } */ - else if (!Q_stricmp( "interrogator", modelName )) - { - ent->genericBone1 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "left_arm", qtrue ); - if (ent->genericBone1>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); + else if (!Q_stricmp("interrogator", modelName)) { + ent->genericBone1 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "left_arm", qtrue); + if (ent->genericBone1 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); } - ent->genericBone2 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "right_arm", qtrue ); - if (ent->genericBone2>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone2, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); + ent->genericBone2 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "right_arm", qtrue); + if (ent->genericBone2 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone2, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); } - ent->genericBone3 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "claw", qtrue ); - if (ent->genericBone3>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone3, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); + ent->genericBone3 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "claw", qtrue); + if (ent->genericBone3 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone3, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); } - } - else if (!Q_strncmp( "r2d2", modelName, 4 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_strncmp("r2d2", modelName, 4)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "body", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "body", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->genericBone1 = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "f_eye", qtrue ); - if (ent->genericBone1>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, NULL, 0, 0 ); + ent->genericBone1 = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "f_eye", qtrue); + if (ent->genericBone1 >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->genericBone1, angles, BONE_ANGLES_POSTMULT, NEGATIVE_Y, NEGATIVE_X, NEGATIVE_Z, + NULL, 0, 0); } - } - else if (!Q_strncmp( "r5d2", modelName, 4 )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_strncmp("r5d2", modelName, 4)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "body", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "body", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - } - else if ( !Q_stricmp( "atst", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_stricmp("atst", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->footLBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "l_tarsal", qtrue ); - if (ent->footLBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->footLBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + ent->footLBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "l_tarsal", qtrue); + if (ent->footLBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->footLBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, + NULL, 0, 0); } - ent->footRBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "r_tarsal", qtrue ); - if (ent->footRBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->footRBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, NULL, 0, 0 ); + ent->footRBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "r_tarsal", qtrue); + if (ent->footRBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->footRBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, NEGATIVE_X, + NULL, 0, 0); } - } - else if ( !Q_stricmp( "mark1", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_stricmp("mark1", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->upperLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->upperLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); } - } - else if ( !Q_stricmp( "mark2", modelName )) - { - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_stricmp("mark2", modelName)) { + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - } - else if ( !Q_stricmp( "minemonster", modelName )) - { - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic1", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_stricmp("minemonster", modelName)) { + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic1", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - } - else if ( !Q_stricmp( "howler", modelName )) - { - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + } else if (!Q_stricmp("howler", modelName)) { + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - } - else - { - //special case motion bone - to match up split anims - ent->motionBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "Motion", qtrue ); - if (ent->motionBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->motionBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, NULL, 0, 0 ); + } else { + // special case motion bone - to match up split anims + ent->motionBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "Motion", qtrue); + if (ent->motionBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->motionBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_X, NEGATIVE_Y, + NULL, 0, 0); } ent->motionBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], "Motion"); - //bone needed for turning anims - ent->hipsBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "pelvis", qtrue ); - if (ent->hipsBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->hipsBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + // bone needed for turning anims + ent->hipsBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "pelvis", qtrue); + if (ent->hipsBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->hipsBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - //regular bones we need - ent->upperLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue ); - if (ent->upperLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + // regular bones we need + ent->upperLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "upper_lumbar", qtrue); + if (ent->upperLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->upperLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); } - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue ); - if (ent->lowerLumbarBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "lower_lumbar", qtrue); + if (ent->lowerLumbarBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->lowerLumbarBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL, 0, 0); } - ent->faceBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "face", qtrue ); - if (ent->faceBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->faceBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->faceBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "face", qtrue); + if (ent->faceBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->faceBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); - if (ent->craniumBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", qtrue); + if (ent->craniumBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->craniumBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->cervicalBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cervical", qtrue ); - if (ent->cervicalBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->cervicalBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cervical", qtrue); + if (ent->cervicalBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->cervicalBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } - ent->thoracicBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "thoracic", qtrue ); - if (ent->thoracicBone>=0) - { - gi.G2API_SetBoneAnglesIndex( &ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, 0 ); + ent->thoracicBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "thoracic", qtrue); + if (ent->thoracicBone >= 0) { + gi.G2API_SetBoneAnglesIndex(&ent->ghoul2[ent->playerModel], ent->thoracicBone, angles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + NULL, 0, 0); } } ent->client->clientInfo.infoValid = qtrue; - } - int max; - if ( ent->s.radius <= 0 )//radius cannot be negative or zero - {//set the radius to be the largest axial distance on the entity - max = ent->mins[0];//NOTE: mins is always negative - if ( max > ent->mins[1] ) - { + int max; + if (ent->s.radius <= 0) // radius cannot be negative or zero + { // set the radius to be the largest axial distance on the entity + max = ent->mins[0]; // NOTE: mins is always negative + if (max > ent->mins[1]) { max = ent->mins[1]; } - if ( max > ent->mins[2] ) - { + if (max > ent->mins[2]) { max = ent->mins[2]; } - max = fabs((double)max);//convert to positive to compare with maxs - if ( max < ent->maxs[0] ) - { + max = fabs((double)max); // convert to positive to compare with maxs + if (max < ent->maxs[0]) { max = ent->maxs[0]; } - if ( max < ent->maxs[1] ) - { + if (max < ent->maxs[1]) { max = ent->maxs[1]; } - if ( max < ent->maxs[2] ) - { + if (max < ent->maxs[2]) { max = ent->maxs[2]; } ent->s.radius = max; - if (!ent->s.radius) // Still no radius? + if (!ent->s.radius) // Still no radius? { ent->s.radius = 60; } @@ -1273,238 +1105,207 @@ qboolean G_SetG2PlayerModelInfo( gentity_t *ent, const char *modelName, const ch // set the weaponmodel to -1 so we don't try and remove it in Pmove before we have it built ent->weaponModel = -1; - if ( ent->playerModel == -1 ) - { + if (ent->playerModel == -1) { return qfalse; } return qtrue; } -void G_SetG2PlayerModel( gentity_t * const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn ) -{ - char skinName[MAX_QPATH]; +void G_SetG2PlayerModel(gentity_t *const ent, const char *modelName, const char *customSkin, const char *surfOff, const char *surfOn) { + char skinName[MAX_QPATH]; - //ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. - if ( !customSkin ) - {//use the default - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_default.skin", modelName ); - } - else - { - Com_sprintf( skinName, sizeof( skinName ), "models/players/%s/model_%s.skin", modelName, customSkin ); + // ok, lets register the skin name, and then pass that name to the config strings so the client can get it too. + if (!customSkin) { // use the default + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_default.skin", modelName); + } else { + Com_sprintf(skinName, sizeof(skinName), "models/players/%s/model_%s.skin", modelName, customSkin); } - gi.RE_RegisterSkin( skinName ); - //now generate the ghoul2 model this client should be. - //NOTE: for some reason, it still loads the default skin's tga's? Because they're referenced in the .glm? - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, va("models/players/%s/model.glm", modelName), - G_ModelIndex( va("models/players/%s/model.glm", modelName) ), G_SkinIndex( skinName ), NULL_HANDLE, 0, 0 ); - if (ent->playerModel == -1) - {//try the stormtrooper as a default + gi.RE_RegisterSkin(skinName); + // now generate the ghoul2 model this client should be. + // NOTE: for some reason, it still loads the default skin's tga's? Because they're referenced in the .glm? + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, va("models/players/%s/model.glm", modelName), + G_ModelIndex(va("models/players/%s/model.glm", modelName)), G_SkinIndex(skinName), NULL_HANDLE, 0, 0); + if (ent->playerModel == -1) { // try the stormtrooper as a default modelName = "stormtrooper"; - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, va("models/players/%s/model.glm", modelName), - G_ModelIndex( va("models/players/%s/model.glm", modelName) ), NULL_HANDLE, NULL_HANDLE, 0, 0 ); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, va("models/players/%s/model.glm", modelName), + G_ModelIndex(va("models/players/%s/model.glm", modelName)), NULL_HANDLE, NULL_HANDLE, 0, 0); } - if ( !Q_stricmp( "kyle", modelName )) - { + if (!Q_stricmp("kyle", modelName)) { // Try to get the skin we'll use when we switch to the first person light saber. // We use a new skin to disable certain surfaces so they are not drawn but we can still collide against them - int skin = gi.RE_RegisterSkin( "models/players/kyle/model_fpls.skin" ); - if ( skin ) - { + int skin = gi.RE_RegisterSkin("models/players/kyle/model_fpls.skin"); + if (skin) { // put it in the config strings - G_SkinIndex( skinName ); + G_SkinIndex(skinName); } } // did we find a ghoul2 model? if so, load the animation.cfg file - if ( !G_SetG2PlayerModelInfo( ent, modelName, customSkin, surfOff, surfOn ) ) - {//couldn't set g2 info, fall back to a mouse md3 - NPC_ParseParms( "mouse", ent ); - //Com_Error( ERR_DROP, "couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName) ); - Com_Printf( S_COLOR_RED"couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName) ); + if (!G_SetG2PlayerModelInfo(ent, modelName, customSkin, surfOff, surfOn)) { // couldn't set g2 info, fall back to a mouse md3 + NPC_ParseParms("mouse", ent); + // Com_Error( ERR_DROP, "couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName) ); + Com_Printf(S_COLOR_RED "couldn't load playerModel %s!\n", va("models/players/%s/model.glm", modelName)); } - } /* Ghoul2 Insert End */ -void G_ActivatePersonalShield( gentity_t *ent ) -{ - ent->client->ps.stats[STAT_ARMOR] = 100;//FIXME: define? - ent->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE;//Doesn't go away until armor does +void G_ActivatePersonalShield(gentity_t *ent) { + ent->client->ps.stats[STAT_ARMOR] = 100; // FIXME: define? + ent->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; // Doesn't go away until armor does } -//HACK FOR FLYING -extern void CG_ChangeWeapon( int num ); -void G_PilotXWing( gentity_t *ent ) -{ - if ( !CheatsOk( ent ) ) - { +// HACK FOR FLYING +extern void CG_ChangeWeapon(int num); +void G_PilotXWing(gentity_t *ent) { + if (!CheatsOk(ent)) { return; } - if ( ent->client->ps.vehicleModel != 0 ) - { - CG_ChangeWeapon( WP_SABER ); + if (ent->client->ps.vehicleModel != 0) { + CG_ChangeWeapon(WP_SABER); ent->client->ps.vehicleModel = 0; ent->svFlags &= ~SVF_CUSTOM_GRAVITY; - ent->client->ps.stats[STAT_ARMOR] = 0;//HACK - //ent->mass = 10; - //gi.cvar_set( "m_pitchOverride", "0" ); - //gi.cvar_set( "m_yawOverride", "0" ); - if ( ent->client->ps.weapon != WP_SABER ) - { - gi.cvar_set( "cg_thirdperson", "0" ); + ent->client->ps.stats[STAT_ARMOR] = 0; // HACK + // ent->mass = 10; + // gi.cvar_set( "m_pitchOverride", "0" ); + // gi.cvar_set( "m_yawOverride", "0" ); + if (ent->client->ps.weapon != WP_SABER) { + gi.cvar_set("cg_thirdperson", "0"); } cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = 240; cg.overrides.active &= ~CG_OVERRIDE_FOV; cg.overrides.fov = 0; - } - else - { - ent->client->ps.vehicleModel = G_ModelIndex( "models/map_objects/ships/x_wing.md3" ); + } else { + ent->client->ps.vehicleModel = G_ModelIndex("models/map_objects/ships/x_wing.md3"); - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_ATST_SIDE ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_ATST_SIDE); ent->client->ps.ammo[weaponData[WP_ATST_SIDE].ammoIndex] = ammoData[weaponData[WP_ATST_SIDE].ammoIndex].max; - gitem_t *item = FindItemForWeapon( WP_ATST_SIDE ); - RegisterItem( item ); //make sure the weapon is cached in case this runs at startup - G_AddEvent( ent, EV_ITEM_PICKUP, (item - bg_itemlist) ); - CG_ChangeWeapon( WP_ATST_SIDE ); + gitem_t *item = FindItemForWeapon(WP_ATST_SIDE); + RegisterItem(item); // make sure the weapon is cached in case this runs at startup + G_AddEvent(ent, EV_ITEM_PICKUP, (item - bg_itemlist)); + CG_ChangeWeapon(WP_ATST_SIDE); ent->client->ps.gravity = 0; ent->svFlags |= SVF_CUSTOM_GRAVITY; - ent->client->ps.stats[STAT_ARMOR] = 200;//FIXME: define? - //ent->mass = 300; + ent->client->ps.stats[STAT_ARMOR] = 200; // FIXME: define? + // ent->mass = 300; ent->client->ps.speed = 0; - //gi.cvar_set( "m_pitchOverride", "0.01" );//ignore inverse mouse look - //gi.cvar_set( "m_yawOverride", "0.0075" ); - gi.cvar_set( "cg_thirdperson", "1" ); - cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_FOV); + // gi.cvar_set( "m_pitchOverride", "0.01" );//ignore inverse mouse look + // gi.cvar_set( "m_yawOverride", "0.0075" ); + gi.cvar_set("cg_thirdperson", "1"); + cg.overrides.active |= (CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_FOV); cg.overrides.thirdPersonRange = 240; cg.overrides.fov = 100; } } -//HACK FOR FLYING +// HACK FOR FLYING -//HACK FOR ATST -void G_DrivableATSTDie( gentity_t *self ) -{ -} +// HACK FOR ATST +void G_DrivableATSTDie(gentity_t *self) {} -void G_DriveATST( gentity_t *ent, gentity_t *atst ) -{ - if ( ent->NPC_type && ent->client && (ent->client->NPC_class == CLASS_ATST) ) - {//already an atst, switch back - //open hatch - if ( ent->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->playerModel ); +void G_DriveATST(gentity_t *ent, gentity_t *atst) { + if (ent->NPC_type && ent->client && (ent->client->NPC_class == CLASS_ATST)) { // already an atst, switch back + // open hatch + if (ent->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->playerModel); } ent->NPC_type = "kyle"; ent->client->NPC_class = CLASS_KYLE; ent->flags &= ~FL_SHIELDED; ent->client->ps.eFlags &= ~EF_IN_ATST; - //size - VectorCopy( playerMins, ent->mins ); - VectorCopy( playerMaxs, ent->maxs ); + // size + VectorCopy(playerMins, ent->mins); + VectorCopy(playerMaxs, ent->maxs); ent->client->crouchheight = CROUCH_MAXS_2; ent->client->standheight = DEFAULT_MAXS_2; - G_SetG2PlayerModel( ent, "kyle", NULL, NULL, NULL ); - //FIXME: reset/initialize their weapon - ent->client->ps.stats[STAT_WEAPONS] &= ~(( 1 << WP_ATST_MAIN )|( 1 << WP_ATST_SIDE )); + G_SetG2PlayerModel(ent, "kyle", NULL, NULL, NULL); + // FIXME: reset/initialize their weapon + ent->client->ps.stats[STAT_WEAPONS] &= ~((1 << WP_ATST_MAIN) | (1 << WP_ATST_SIDE)); ent->client->ps.ammo[weaponData[WP_ATST_MAIN].ammoIndex] = 0; ent->client->ps.ammo[weaponData[WP_ATST_SIDE].ammoIndex] = 0; - CG_ChangeWeapon( WP_BRYAR_PISTOL ); - //camera - //if ( ent->client->ps.weapon != WP_SABER ) - { - gi.cvar_set( "cg_thirdperson", "0" ); - } - cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG|CG_OVERRIDE_3RD_PERSON_VOF|CG_OVERRIDE_3RD_PERSON_POF|CG_OVERRIDE_3RD_PERSON_APH); + CG_ChangeWeapon(WP_BRYAR_PISTOL); + // camera + // if ( ent->client->ps.weapon != WP_SABER ) + { gi.cvar_set("cg_thirdperson", "0"); } + cg.overrides.active &= ~(CG_OVERRIDE_3RD_PERSON_RNG | CG_OVERRIDE_3RD_PERSON_VOF | CG_OVERRIDE_3RD_PERSON_POF | CG_OVERRIDE_3RD_PERSON_APH); cg.overrides.thirdPersonRange = cg.overrides.thirdPersonVertOffset = cg.overrides.thirdPersonPitchOffset = 0; cg.overrides.thirdPersonAlpha = cg_thirdPersonAlpha.value; ent->client->ps.viewheight = ent->maxs[2] + STANDARD_VIEWHEIGHT_OFFSET; - //ent->mass = 10; - } - else - {//become an atst + // ent->mass = 10; + } else { // become an atst ent->NPC_type = "atst"; ent->client->NPC_class = CLASS_ATST; ent->client->ps.eFlags |= EF_IN_ATST; ent->flags |= FL_SHIELDED; - //size - VectorSet( ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2 ); - VectorSet( ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2 ); + // size + VectorSet(ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2); + VectorSet(ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2); ent->client->crouchheight = ATST_MAXS2; ent->client->standheight = ATST_MAXS2; - if ( ent->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->playerModel ); + if (ent->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->playerModel); ent->playerModel = -1; } - if ( ent->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel ); + if (ent->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel); ent->weaponModel = -1; } - if ( !atst ) - {//no ent to copy from - G_SetG2PlayerModel( ent, "atst", NULL, NULL, NULL ); - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE ); - } - else - { - gi.G2API_CopyGhoul2Instance( atst->ghoul2, ent->ghoul2, -1 ); + if (!atst) { // no ent to copy from + G_SetG2PlayerModel(ent, "atst", NULL, NULL, NULL); + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_OVERRIDE); + } else { + gi.G2API_CopyGhoul2Instance(atst->ghoul2, ent->ghoul2, -1); ent->playerModel = 0; - G_SetG2PlayerModelInfo( ent, "atst", NULL, NULL, NULL ); - //turn off hatch underside - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "head_hatchcover_off", 0x00000002/*G2SURFACEFLAG_OFF*/ ); - G_Sound( ent, G_SoundIndex( "sound/chars/atst/atst_hatch_close" )); + G_SetG2PlayerModelInfo(ent, "atst", NULL, NULL, NULL); + // turn off hatch underside + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "head_hatchcover_off", 0x00000002 /*G2SURFACEFLAG_OFF*/); + G_Sound(ent, G_SoundIndex("sound/chars/atst/atst_hatch_close")); } ent->s.radius = 320; - //weapon - gitem_t *item = FindItemForWeapon( WP_ATST_MAIN ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_ATST_SIDE ); //precache the weapon - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_ATST_MAIN )|( 1 << WP_ATST_SIDE ); + // weapon + gitem_t *item = FindItemForWeapon(WP_ATST_MAIN); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_ATST_SIDE); // precache the weapon + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_ATST_MAIN) | (1 << WP_ATST_SIDE); ent->client->ps.ammo[weaponData[WP_ATST_MAIN].ammoIndex] = ammoData[weaponData[WP_ATST_MAIN].ammoIndex].max; ent->client->ps.ammo[weaponData[WP_ATST_SIDE].ammoIndex] = ammoData[weaponData[WP_ATST_SIDE].ammoIndex].max; - CG_ChangeWeapon( WP_ATST_MAIN ); - //HACKHACKHACKTEMP - item = FindItemForWeapon( WP_EMPLACED_GUN ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_ROCKET_LAUNCHER ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - item = FindItemForWeapon( WP_BOWCASTER ); - CG_RegisterItemSounds( (item-bg_itemlist) ); - CG_RegisterItemVisuals( (item-bg_itemlist) ); - //HACKHACKHACKTEMP - //FIXME: these get lost in load/save! Must use variables that are set every frame or saved/loaded - //camera - gi.cvar_set( "cg_thirdperson", "1" ); + CG_ChangeWeapon(WP_ATST_MAIN); + // HACKHACKHACKTEMP + item = FindItemForWeapon(WP_EMPLACED_GUN); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_ROCKET_LAUNCHER); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + item = FindItemForWeapon(WP_BOWCASTER); + CG_RegisterItemSounds((item - bg_itemlist)); + CG_RegisterItemVisuals((item - bg_itemlist)); + // HACKHACKHACKTEMP + // FIXME: these get lost in load/save! Must use variables that are set every frame or saved/loaded + // camera + gi.cvar_set("cg_thirdperson", "1"); cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_RNG; cg.overrides.thirdPersonRange = 240; - //cg.overrides.thirdPersonVertOffset = 100; - //cg.overrides.thirdPersonPitchOffset = -30; - //FIXME: this gets stomped in pmove? + // cg.overrides.thirdPersonVertOffset = 100; + // cg.overrides.thirdPersonPitchOffset = -30; + // FIXME: this gets stomped in pmove? ent->client->ps.viewheight = 120; - //FIXME: setting these broke things very badly...? - //ent->client->standheight = 200; - //ent->client->crouchheight = 200; - //ent->mass = 300; - //movement - //ent->client->ps.speed = 0;//FIXME: override speed? - //FIXME: slow turn turning/can't turn if not moving? + // FIXME: setting these broke things very badly...? + // ent->client->standheight = 200; + // ent->client->crouchheight = 200; + // ent->mass = 300; + // movement + // ent->client->ps.speed = 0;//FIXME: override speed? + // FIXME: slow turn turning/can't turn if not moving? } } -//HACK FOR ATST +// HACK FOR ATST /* =========== @@ -1516,25 +1317,24 @@ Initializes all non-persistant parts of playerState ============ */ -qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ) -{ - int index; - vec3_t spawn_origin, spawn_angles; - gclient_t *client; - int i; - clientPersistant_t saved; - clientSession_t savedSess; - clientInfo_t savedCi; - int persistant[MAX_PERSISTANT]; - usercmd_t ucmd; - gentity_t *spawnPoint; - qboolean beamInEffect = qfalse; +qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded) { + int index; + vec3_t spawn_origin, spawn_angles; + gclient_t *client; + int i; + clientPersistant_t saved; + clientSession_t savedSess; + clientInfo_t savedCi; + int persistant[MAX_PERSISTANT]; + usercmd_t ucmd; + gentity_t *spawnPoint; + qboolean beamInEffect = qfalse; extern qboolean g_qbLoadTransition; index = ent - g_entities; client = ent->client; - if ( eSavedGameJustLoaded == eFULL && g_qbLoadTransition == qfalse )//qbFromSavedGame) + if (eSavedGameJustLoaded == eFULL && g_qbLoadTransition == qfalse) // qbFromSavedGame) { ent->client->pers.teamState.state = TEAM_ACTIVE; @@ -1544,61 +1344,52 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->airOutTime = level.time + 12000; - for (i=0; i<3; i++) - { + for (i = 0; i < 3; i++) { ent->client->pers.cmd_angles[i] = 0.0f; } - SetClientViewAngle( ent, ent->client->ps.viewangles);//spawn_angles ); + SetClientViewAngle(ent, ent->client->ps.viewangles); // spawn_angles ); - gi.linkentity (ent); + gi.linkentity(ent); // run the presend to set anything else - ClientEndFrame( ent ); + ClientEndFrame(ent); // clear entity state values - PlayerStateToEntityState( &client->ps, &ent->s ); + PlayerStateToEntityState(&client->ps, &ent->s); - if ( ent->client->NPC_class == CLASS_ATST ) - { - G_LoadAnimFileSet( ent, "atst" ); - G_SetSkin( ent, "atst", NULL ); + if (ent->client->NPC_class == CLASS_ATST) { + G_LoadAnimFileSet(ent, "atst"); + G_SetSkin(ent, "atst", NULL); + } else { + G_LoadAnimFileSet(ent, "kyle"); + G_SetSkin(ent, "kyle", NULL); } - else - { - G_LoadAnimFileSet( ent, "kyle" ); - G_SetSkin( ent, "kyle", NULL ); - } - } - else - { + } else { // find a spawn point // do it before setting health back up, so farthest // ranging doesn't count this client // don't spawn near existing origin if possible - spawnPoint = SelectSpawnPoint ( ent->client->ps.origin, - (team_t) ent->client->ps.persistant[PERS_TEAM], spawn_origin, spawn_angles); + spawnPoint = SelectSpawnPoint(ent->client->ps.origin, (team_t)ent->client->ps.persistant[PERS_TEAM], spawn_origin, spawn_angles); ent->client->pers.teamState.state = TEAM_ACTIVE; // clear everything but the persistant data saved = client->pers; savedSess = client->sess; - for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) - { + for (i = 0; i < MAX_PERSISTANT; i++) { persistant[i] = client->ps.persistant[i]; } - //Preserve clientInfo - memcpy (&savedCi, &client->clientInfo, sizeof(clientInfo_t)); + // Preserve clientInfo + memcpy(&savedCi, &client->clientInfo, sizeof(clientInfo_t)); - memset (client, 0, sizeof(*client)); + memset(client, 0, sizeof(*client)); - memcpy (&client->clientInfo, &savedCi, sizeof(clientInfo_t)); + memcpy(&client->clientInfo, &savedCi, sizeof(clientInfo_t)); client->pers = saved; client->sess = savedSess; - for ( i = 0 ; i < MAX_PERSISTANT ; i++ ) - { + for (i = 0; i < MAX_PERSISTANT; i++) { client->ps.persistant[i] = persistant[i]; } @@ -1618,8 +1409,7 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded SetInUse(ent); ent->classname = "player"; client->squadname = ent->targetname = ent->script_targetname = ent->NPC_type = "kyle"; - if ( ent->client->NPC_class == CLASS_NONE ) - { + if (ent->client->NPC_class == CLASS_NONE) { ent->client->NPC_class = CLASS_KYLE; } client->playerTeam = TEAM_PLAYER; @@ -1636,29 +1426,27 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->renderInfo.lookTargetClearTime = 0; client->renderInfo.lookMode = LM_ENT; - VectorCopy (playerMins, ent->mins); - VectorCopy (playerMaxs, ent->maxs); + VectorCopy(playerMins, ent->mins); + VectorCopy(playerMaxs, ent->maxs); client->crouchheight = CROUCH_MAXS_2; client->standheight = DEFAULT_MAXS_2; client->ps.clientNum = index; // give default weapons - client->ps.stats[STAT_WEAPONS] = ( 1 << WP_NONE ); - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BRYAR_PISTOL ); //these are precached in g_items, ClearRegisteredItems() + client->ps.stats[STAT_WEAPONS] = (1 << WP_NONE); + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BRYAR_PISTOL); // these are precached in g_items, ClearRegisteredItems() client->ps.inventory[INV_ELECTROBINOCULARS] = 1; // always give the bryar pistol, but we have to give EITHER the saber or the stun baton..never both - if ( spawnPoint->spawnflags & 32 ) // STUN_BATON + if (spawnPoint->spawnflags & 32) // STUN_BATON { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_STUN_BATON ); - } - else - { // give the saber AND the blaster because most test maps will not have the STUN BATON flag set - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_SABER ); //this is precached in SP_info_player_deathmatch + client->ps.stats[STAT_WEAPONS] |= (1 << WP_STUN_BATON); + } else { // give the saber AND the blaster because most test maps will not have the STUN BATON flag set + client->ps.stats[STAT_WEAPONS] |= (1 << WP_SABER); // this is precached in SP_info_player_deathmatch } - for ( i = 0; i < AMMO_THERMAL; i++ ) // don't give ammo for explosives + for (i = 0; i < AMMO_THERMAL; i++) // don't give ammo for explosives { client->ps.ammo[i] = ammoData[i].max; } @@ -1666,8 +1454,8 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->ps.saberColor = SABER_BLUE; client->ps.saberActive = qfalse; client->ps.saberLength = 0; - //Initialize force powers - WP_InitForcePowers( ent ); + // Initialize force powers + WP_InitForcePowers(ent); // ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH]; @@ -1679,17 +1467,17 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ent->client->ps.batteryCharge = 2500; - VectorCopy( spawn_origin, client->ps.origin ); - VectorCopy( spawn_origin, ent->currentOrigin ); + VectorCopy(spawn_origin, client->ps.origin); + VectorCopy(spawn_origin, ent->currentOrigin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; - SetClientViewAngle( ent, spawn_angles ); + SetClientViewAngle(ent, spawn_angles); { - G_KillBox( ent ); - gi.linkentity (ent); + G_KillBox(ent); + gi.linkentity(ent); // force the base weapon up client->ps.weapon = WP_BRYAR_PISTOL; client->ps.weaponstate = WEAPON_READY; @@ -1709,34 +1497,25 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded // restore some player data if this is a spawn point with KEEP_REV (spawnflags&1) set... // - if ( eSavedGameJustLoaded == eAUTO || - (spawnPoint->spawnflags&1) || // KEEP_PREV - g_qbLoadTransition == qtrue ) - { + if (eSavedGameJustLoaded == eAUTO || (spawnPoint->spawnflags & 1) || // KEEP_PREV + g_qbLoadTransition == qtrue) { Player_RestoreFromPrevLevel(ent); } - /* Ghoul2 Insert Start */ - if (eSavedGameJustLoaded == eNO) - { + if (eSavedGameJustLoaded == eNO) { ent->weaponModel = -1; - G_SetG2PlayerModel( ent, "kyle", NULL, NULL, NULL ); - } - else - { - if ( ent->client->NPC_class == CLASS_ATST ) - { - G_LoadAnimFileSet( ent, "atst" ); - G_SetSkin( ent, "atst", NULL ); - } - else - { - G_LoadAnimFileSet( ent, "kyle" ); - G_SetSkin( ent, "kyle", NULL ); + G_SetG2PlayerModel(ent, "kyle", NULL, NULL, NULL); + } else { + if (ent->client->NPC_class == CLASS_ATST) { + G_LoadAnimFileSet(ent, "atst"); + G_SetSkin(ent, "atst", NULL); + } else { + G_LoadAnimFileSet(ent, "kyle"); + G_SetSkin(ent, "kyle", NULL); } } /* @@ -1748,47 +1527,43 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded client->ps.commandTime = level.time - 100; ucmd = client->pers.lastCommand; ucmd.serverTime = level.time; - VectorCopyM( client->pers.cmd_angles, ucmd.angles ); - ucmd.weapon = client->ps.weapon; // client think calls Pmove which sets the client->ps.weapon to ucmd.weapon, so ... + VectorCopyM(client->pers.cmd_angles, ucmd.angles); + ucmd.weapon = client->ps.weapon; // client think calls Pmove which sets the client->ps.weapon to ucmd.weapon, so ... ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - ClientThink( ent-g_entities, &ucmd ); + ClientThink(ent - g_entities, &ucmd); // run the presend to set anything else - ClientEndFrame( ent ); + ClientEndFrame(ent); // clear entity state values - PlayerStateToEntityState( &client->ps, &ent->s ); + PlayerStateToEntityState(&client->ps, &ent->s); - //ICARUS include - ICARUS_FreeEnt( ent ); //FIXME: This shouldn't need to be done...? - ICARUS_InitEnt( ent ); + // ICARUS include + ICARUS_FreeEnt(ent); // FIXME: This shouldn't need to be done...? + ICARUS_InitEnt(ent); - if ( spawnPoint->spawnflags & 64 ) - {//player starts with absolutely no weapons - ent->client->ps.stats[STAT_WEAPONS] = ( 1 << WP_NONE ); - ent->client->ps.ammo[weaponData[WP_NONE].ammoIndex] = 32000; // checkme + if (spawnPoint->spawnflags & 64) { // player starts with absolutely no weapons + ent->client->ps.stats[STAT_WEAPONS] = (1 << WP_NONE); + ent->client->ps.ammo[weaponData[WP_NONE].ammoIndex] = 32000; // checkme ent->client->ps.weapon = WP_NONE; ent->client->ps.weaponstate = WEAPON_READY; } - if ( ent->client->ps.stats[STAT_WEAPONS] & ( 1 << WP_SABER ) ) - {//set up so has lightsaber - WP_SaberInitBladeData( ent ); - if ( ent->weaponModel == -1 && ent->client->ps.weapon == WP_SABER ) - { - G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saberModel ); + if (ent->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { // set up so has lightsaber + WP_SaberInitBladeData(ent); + if (ent->weaponModel == -1 && ent->client->ps.weapon == WP_SABER) { + G_CreateG2AttachedWeaponModel(ent, ent->client->ps.saberModel); } } - if ( ent->weaponModel == -1 && ent->client->ps.weapon != WP_NONE ) - { - G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl ); + if (ent->weaponModel == -1 && ent->client->ps.weapon != WP_NONE) { + G_CreateG2AttachedWeaponModel(ent, weaponData[ent->client->ps.weapon].weaponMdl); } { // fire the targets of the spawn point - G_UseTargets( spawnPoint, ent ); - //Designers needed them to fire off target2's as well... this is kind of messy - G_UseTargets2( spawnPoint, ent, spawnPoint->target2 ); + G_UseTargets(spawnPoint, ent); + // Designers needed them to fire off target2's as well... this is kind of messy + G_UseTargets2(spawnPoint, ent, spawnPoint->target2); /* // select the highest weapon number available, after any @@ -1803,18 +1578,16 @@ qboolean ClientSpawn(gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded } } - client->pers.enterTime = level.time;//needed mainly to stop the weapon switch to WP_NONE that happens on loads + client->pers.enterTime = level.time; // needed mainly to stop the weapon switch to WP_NONE that happens on loads ent->max_health = client->ps.stats[STAT_MAX_HEALTH]; - if ( eSavedGameJustLoaded == eNO ) - {//on map transitions, Ghoul2 frame gets reset to zero, restart our anim - NPC_SetAnim( ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); - NPC_SetAnim( ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL|SETANIM_FLAG_RESTART ); + if (eSavedGameJustLoaded == eNO) { // on map transitions, Ghoul2 frame gets reset to zero, restart our anim + NPC_SetAnim(ent, SETANIM_LEGS, ent->client->ps.legsAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); + NPC_SetAnim(ent, SETANIM_TORSO, ent->client->ps.torsoAnim, SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART); } return beamInEffect; } - /* =========== ClientDisconnect @@ -1823,22 +1596,22 @@ Called when a player drops from the server. Will not be called between levels. ============ */ -void ClientDisconnect( int clientNum ) { - gentity_t *ent; +void ClientDisconnect(int clientNum) { + gentity_t *ent; ent = g_entities + clientNum; - if ( !ent->client ) { + if (!ent->client) { return; } // send effect if they were completely connected -/* if ( ent->client->pers.connected == CON_CONNECTED ) { - // They don't get to take powerups with them! - // Especially important for stuff like CTF flags - TossClientItems ( ent ); - } -*/ - gi.unlinkentity (ent); + /* if ( ent->client->pers.connected == CON_CONNECTED ) { + // They don't get to take powerups with them! + // Especially important for stuff like CTF flags + TossClientItems ( ent ); + } + */ + gi.unlinkentity(ent); ent->s.modelindex = 0; ent->inuse = qfalse; ClearInUse(ent); @@ -1846,8 +1619,5 @@ void ClientDisconnect( int clientNum ) { ent->client->pers.connected = CON_DISCONNECTED; ent->client->ps.persistant[PERS_TEAM] = TEAM_FREE; - gi.SetConfigstring( CS_PLAYERS + clientNum, ""); - + gi.SetConfigstring(CS_PLAYERS + clientNum, ""); } - - diff --git a/codeJK2/game/g_cmds.cpp b/codeJK2/game/g_cmds.cpp index 7fbc3270d1..915752b667 100644 --- a/codeJK2/game/g_cmds.cpp +++ b/codeJK2/game/g_cmds.cpp @@ -27,62 +27,61 @@ along with this program; if not, see . #include "objectives.h" #include "wp_saber.h" -extern bool in_camera; - -extern void ForceThrow( gentity_t *self, qboolean pull ); -extern void ForceLevitation( gentity_t *self ); -extern void ForceLightning( gentity_t *self ); -extern void ForceHeal( gentity_t *self ); -extern void ForceGrip( gentity_t *self ); -extern void ForceTelepathy( gentity_t *self ); -extern void G_ActivatePersonalShield( gentity_t *ent ); -extern void G_ActivateSeeker( gentity_t *ent ); -extern void G_PilotXWing( gentity_t *ent ); -extern void G_DriveATST( gentity_t *ent, gentity_t *atst ); -extern void G_StartMatrixEffect( gentity_t *ent, qboolean falling = qfalse, int length = 1000 ); +extern bool in_camera; + +extern void ForceThrow(gentity_t *self, qboolean pull); +extern void ForceLevitation(gentity_t *self); +extern void ForceLightning(gentity_t *self); +extern void ForceHeal(gentity_t *self); +extern void ForceGrip(gentity_t *self); +extern void ForceTelepathy(gentity_t *self); +extern void G_ActivatePersonalShield(gentity_t *ent); +extern void G_ActivateSeeker(gentity_t *ent); +extern void G_PilotXWing(gentity_t *ent); +extern void G_DriveATST(gentity_t *ent, gentity_t *atst); +extern void G_StartMatrixEffect(gentity_t *ent, qboolean falling = qfalse, int length = 1000); extern void ItemUse_Bacta(gentity_t *ent); -extern gentity_t *G_GetSelfForPlayerCmd( void ); +extern gentity_t *G_GetSelfForPlayerCmd(void); /* ================== CheatsOk ================== */ -qboolean CheatsOk( gentity_t *ent ) { - if ( !g_cheats->integer ) { - gi.SendServerCommand( ent-g_entities, "print \"Cheats are not enabled on this server.\n\""); +qboolean CheatsOk(gentity_t *ent) { + if (!g_cheats->integer) { + gi.SendServerCommand(ent - g_entities, "print \"Cheats are not enabled on this server.\n\""); return qfalse; } - if ( ent->health <= 0 ) { - gi.SendServerCommand( ent-g_entities, "print \"You must be alive to use this command.\n\""); + if (ent->health <= 0) { + gi.SendServerCommand(ent - g_entities, "print \"You must be alive to use this command.\n\""); return qfalse; } return qtrue; } - /* ================== ConcatArgs ================== */ -char *ConcatArgs( int start ) { - int i, c, tlen; - static char line[MAX_STRING_CHARS]; - int len; - const char *arg; +char *ConcatArgs(int start) { + int i, c, tlen; + static char line[MAX_STRING_CHARS]; + int len; + const char *arg; len = 0; c = gi.argc(); - for ( i = start ; i < c ; i++ ) { - arg = gi.argv( i ); - tlen = strlen( arg ); - if ( len + tlen >= MAX_STRING_CHARS - 1 ) { + for (i = start; i < c; i++) { + arg = gi.argv(i); + tlen = strlen(arg); + if (len + tlen >= MAX_STRING_CHARS - 1) { break; } - memcpy( line + len, arg, tlen ); + memcpy(line + len, arg, tlen); len += tlen; - if ( i != c - 1 ) { + if (i != c - 1) { line[len] = ' '; len++; } @@ -100,17 +99,17 @@ SanitizeString Remove case and control characters ================== */ -void SanitizeString( char *in, char *out ) { - while ( *in ) { - if ( *in == 94 ) { - in += 2; // skip color code +void SanitizeString(char *in, char *out) { + while (*in) { + if (*in == 94) { + in += 2; // skip color code continue; } - if ( *in < 32 ) { + if (*in < 32) { in++; continue; } - *out++ = tolower( *in++ ); + *out++ = tolower(*in++); } *out = 0; @@ -124,135 +123,126 @@ Returns a player number for either a number or name string Returns -1 if invalid ================== */ -int ClientNumberFromString( gentity_t *to, char *s ) { - gclient_t *cl; - int idnum; - char s2[MAX_STRING_CHARS]; - char n2[MAX_STRING_CHARS]; +int ClientNumberFromString(gentity_t *to, char *s) { + gclient_t *cl; + int idnum; + char s2[MAX_STRING_CHARS]; + char n2[MAX_STRING_CHARS]; // numeric values are just slot numbers if (s[0] >= '0' && s[0] <= '9') { - idnum = atoi( s ); - if ( idnum < 0 || idnum >= level.maxclients ) { - gi.SendServerCommand( to-g_entities, "print \"Bad client slot: %i\n\"", idnum); + idnum = atoi(s); + if (idnum < 0 || idnum >= level.maxclients) { + gi.SendServerCommand(to - g_entities, "print \"Bad client slot: %i\n\"", idnum); return -1; } cl = &level.clients[idnum]; - if ( cl->pers.connected != CON_CONNECTED ) { - gi.SendServerCommand( to-g_entities, "print \"Client %i is not active\n\"", idnum); + if (cl->pers.connected != CON_CONNECTED) { + gi.SendServerCommand(to - g_entities, "print \"Client %i is not active\n\"", idnum); return -1; } return idnum; } // check for a name match - SanitizeString( s, s2 ); - for ( idnum=0,cl=level.clients ; idnum < level.maxclients ; idnum++,cl++ ) { - if ( cl->pers.connected != CON_CONNECTED ) { + SanitizeString(s, s2); + for (idnum = 0, cl = level.clients; idnum < level.maxclients; idnum++, cl++) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - SanitizeString( cl->pers.netname, n2 ); - if ( !strcmp( n2, s2 ) ) { + SanitizeString(cl->pers.netname, n2); + if (!strcmp(n2, s2)) { return idnum; } } - gi.SendServerCommand( to-g_entities, "print \"User %s is not on the server\n\"", s); + gi.SendServerCommand(to - g_entities, "print \"User %s is not on the server\n\"", s); return -1; } -void G_Give( gentity_t *ent, const char *name, const char *args, int argc ) -{ - gitem_t *it; - int i; - qboolean give_all = qfalse; +void G_Give(gentity_t *ent, const char *name, const char *args, int argc) { + gitem_t *it; + int i; + qboolean give_all = qfalse; - if ( !Q_stricmp( name, "all" ) ) + if (!Q_stricmp(name, "all")) give_all = qtrue; - if ( give_all || !Q_stricmp( name, "health") ) - { - if ( argc == 3 ) - ent->health = Com_Clampi( 1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); + if (give_all || !Q_stricmp(name, "health")) { + if (argc == 3) + ent->health = Com_Clampi(1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); else ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "armor" ) || !Q_stricmp( name, "shield" ) ) - { - if ( argc == 3 ) - ent->client->ps.stats[STAT_ARMOR] = Com_Clampi( 0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); + if (give_all || !Q_stricmp(name, "armor") || !Q_stricmp(name, "shield")) { + if (argc == 3) + ent->client->ps.stats[STAT_ARMOR] = Com_Clampi(0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); else ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; - if ( ent->client->ps.stats[STAT_ARMOR] > 0 ) + if (ent->client->ps.stats[STAT_ARMOR] > 0) ent->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; else ent->client->ps.powerups[PW_BATTLESUIT] = 0; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "force" ) ) - { - if ( argc == 3 ) - ent->client->ps.forcePower = Com_Clampi( 0, FORCE_POWER_MAX, atoi( args ) ); + if (give_all || !Q_stricmp(name, "force")) { + if (argc == 3) + ent->client->ps.forcePower = Com_Clampi(0, FORCE_POWER_MAX, atoi(args)); else ent->client->ps.forcePower = FORCE_POWER_MAX; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "weapons" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] = (1 << (MAX_PLAYER_WEAPONS+1)) - ( 1 << WP_NONE ); - if ( !give_all ) + if (give_all || !Q_stricmp(name, "weapons")) { + ent->client->ps.stats[STAT_WEAPONS] = (1 << (MAX_PLAYER_WEAPONS + 1)) - (1 << WP_NONE); + if (!give_all) return; } - - if ( !give_all && !Q_stricmp( name, "weaponnum" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi( args )); + + if (!give_all && !Q_stricmp(name, "weaponnum")) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi(args)); return; } - if ( !give_all && !Q_stricmp( name, "eweaps" ) ) //for developing, gives you all the weapons, including enemy + if (!give_all && !Q_stricmp(name, "eweaps")) // for developing, gives you all the weapons, including enemy { - ent->client->ps.stats[STAT_WEAPONS] = (unsigned)(1 << WP_NUM_WEAPONS) - ( 1 << WP_NONE ); // NOTE: this wasn't giving the last weapon in the list + ent->client->ps.stats[STAT_WEAPONS] = (unsigned)(1 << WP_NUM_WEAPONS) - (1 << WP_NONE); // NOTE: this wasn't giving the last weapon in the list return; } - if ( give_all || !Q_stricmp( name, "ammo" ) ) - { + if (give_all || !Q_stricmp(name, "ammo")) { int num = 999; - if ( argc == 3 ) - num = Com_Clampi( -1, 999, atoi( args ) ); - for ( i=AMMO_BLASTER; iclient->ps.ammo[i] = num != -1 ? num : ammoData[i].max; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "batteries" ) ) - { - if ( argc == 3 ) - ent->client->ps.batteryCharge = Com_Clampi( 0, MAX_BATTERIES, atoi( args ) ); + if (give_all || !Q_stricmp(name, "batteries")) { + if (argc == 3) + ent->client->ps.batteryCharge = Com_Clampi(0, MAX_BATTERIES, atoi(args)); else ent->client->ps.batteryCharge = MAX_BATTERIES; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "inventory" ) ) - { + if (give_all || !Q_stricmp(name, "inventory")) { // Huh? Was doing a INV_MAX+1 which was wrong because then you'd actually have every inventory item including INV_MAX - ent->client->ps.stats[STAT_ITEMS] = (1 << (INV_MAX)) - ( 1 << INV_ELECTROBINOCULARS ); + ent->client->ps.stats[STAT_ITEMS] = (1 << (INV_MAX)) - (1 << INV_ELECTROBINOCULARS); ent->client->ps.inventory[INV_ELECTROBINOCULARS] = 1; ent->client->ps.inventory[INV_BACTA_CANISTER] = 5; @@ -262,175 +252,141 @@ void G_Give( gentity_t *ent, const char *name, const char *args, int argc ) ent->client->ps.inventory[INV_GOODIE_KEY] = 5; ent->client->ps.inventory[INV_SECURITY_KEY] = 5; - if ( !give_all ) + if (!give_all) return; } // spawn a specific item right on the player - if ( !give_all ) { - gentity_t *it_ent; - trace_t trace; - it = FindItem (args); + if (!give_all) { + gentity_t *it_ent; + trace_t trace; + it = FindItem(args); if (!it) { - it = FindItem (name); + it = FindItem(name); if (!it) { - gi.SendServerCommand( ent-g_entities, "print \"unknown item\n\""); + gi.SendServerCommand(ent - g_entities, "print \"unknown item\n\""); return; } } it_ent = G_Spawn(); - VectorCopy( ent->currentOrigin, it_ent->s.origin ); + VectorCopy(ent->currentOrigin, it_ent->s.origin); it_ent->classname = G_NewString(it->classname); - G_SpawnItem (it_ent, it); - FinishSpawningItem(it_ent ); - memset( &trace, 0, sizeof( trace ) ); - Touch_Item (it_ent, ent, &trace); + G_SpawnItem(it_ent, it); + FinishSpawningItem(it_ent); + memset(&trace, 0, sizeof(trace)); + Touch_Item(it_ent, ent, &trace); if (it_ent->inuse) { - G_FreeEntity( it_ent ); + G_FreeEntity(it_ent); } } } -void Cmd_Give_f( gentity_t *ent ) -{ - if ( !CheatsOk( ent ) ) { +void Cmd_Give_f(gentity_t *ent) { + if (!CheatsOk(ent)) { return; } - G_Give( ent, gi.argv(1), ConcatArgs( 2 ), gi.argc() ); + G_Give(ent, gi.argv(1), ConcatArgs(2), gi.argc()); } //------------------ -void Cmd_Fx( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *fx_ent = NULL; +void Cmd_Fx(gentity_t *ent) { + vec3_t dir; + gentity_t *fx_ent = NULL; - if ( Q_stricmp( gi.argv(1), "play" ) == 0 ) - { - if ( gi.argc() == 3 ) - { + if (Q_stricmp(gi.argv(1), "play") == 0) { + if (gi.argc() == 3) { // I guess, only allow one active at a time - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - G_FreeEntity( fx_ent ); + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + G_FreeEntity(fx_ent); } fx_ent = G_Spawn(); - fx_ent->fxFile = gi.argv( 2 ); + fx_ent->fxFile = gi.argv(2); // Move out in front of the person spawning the effect - AngleVectors( ent->currentAngles, dir, NULL, NULL ); - VectorMA( ent->currentOrigin, 32, dir, fx_ent->s.origin ); + AngleVectors(ent->currentAngles, dir, NULL, NULL); + VectorMA(ent->currentOrigin, 32, dir, fx_ent->s.origin); -extern void SP_fx_runner( gentity_t *ent ); + extern void SP_fx_runner(gentity_t * ent); - SP_fx_runner( fx_ent ); - fx_ent->delay = 2000; // adjusting delay - fx_ent->classname = "cmd_fx"; // and classname + SP_fx_runner(fx_ent); + fx_ent->delay = 2000; // adjusting delay + fx_ent->classname = "cmd_fx"; // and classname return; } - } - else if ( Q_stricmp( gi.argv(1), "stop" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - G_FreeEntity( fx_ent ); + } else if (Q_stricmp(gi.argv(1), "stop") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + G_FreeEntity(fx_ent); } return; - } - else if ( Q_stricmp( gi.argv(1), "delay" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 3 ) - { - fx_ent->delay = atoi( gi.argv( 2 )); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current delay is: %i\n", fx_ent->delay ); + } else if (Q_stricmp(gi.argv(1), "delay") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 3) { + fx_ent->delay = atoi(gi.argv(2)); + } else { + gi.Printf(S_COLOR_GREEN "FX: current delay is: %i\n", fx_ent->delay); } return; } - } - else if ( Q_stricmp( gi.argv(1), "random" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 3 ) - { - fx_ent->random = atoi( gi.argv( 2 )); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current random is: %6.2f\n", fx_ent->random ); + } else if (Q_stricmp(gi.argv(1), "random") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 3) { + fx_ent->random = atoi(gi.argv(2)); + } else { + gi.Printf(S_COLOR_GREEN "FX: current random is: %6.2f\n", fx_ent->random); } return; } - } - else if ( Q_stricmp( gi.argv(1), "origin" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 5 ) - { - fx_ent->s.origin[0] = atof( gi.argv( 2 )); - fx_ent->s.origin[1] = atof( gi.argv( 3 )); - fx_ent->s.origin[2] = atof( gi.argv( 4 )); - - G_SetOrigin( fx_ent, fx_ent->s.origin ); - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current origin is: <%6.2f %6.2f %6.2f>\n", - fx_ent->currentOrigin[0], fx_ent->currentOrigin[1], fx_ent->currentOrigin[2] ); + } else if (Q_stricmp(gi.argv(1), "origin") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 5) { + fx_ent->s.origin[0] = atof(gi.argv(2)); + fx_ent->s.origin[1] = atof(gi.argv(3)); + fx_ent->s.origin[2] = atof(gi.argv(4)); + + G_SetOrigin(fx_ent, fx_ent->s.origin); + } else { + gi.Printf(S_COLOR_GREEN "FX: current origin is: <%6.2f %6.2f %6.2f>\n", fx_ent->currentOrigin[0], fx_ent->currentOrigin[1], + fx_ent->currentOrigin[2]); } return; } - } - else if ( Q_stricmp( gi.argv(1), "dir" ) == 0 ) - { - while (( fx_ent = G_Find( fx_ent, FOFS(classname), "cmd_fx")) != NULL ) - { - if ( gi.argc() == 5 ) - { - fx_ent->s.angles[0] = atof( gi.argv( 2 )); - fx_ent->s.angles[1] = atof( gi.argv( 3 )); - fx_ent->s.angles[2] = atof( gi.argv( 4 )); - - if ( !VectorNormalize( fx_ent->s.angles )) - { + } else if (Q_stricmp(gi.argv(1), "dir") == 0) { + while ((fx_ent = G_Find(fx_ent, FOFS(classname), "cmd_fx")) != NULL) { + if (gi.argc() == 5) { + fx_ent->s.angles[0] = atof(gi.argv(2)); + fx_ent->s.angles[1] = atof(gi.argv(3)); + fx_ent->s.angles[2] = atof(gi.argv(4)); + + if (!VectorNormalize(fx_ent->s.angles)) { // must have been zero length fx_ent->s.angles[2] = 1; } - } - else - { - gi.Printf( S_COLOR_GREEN"FX: current dir is: <%6.2f %6.2f %6.2f>\n", - fx_ent->s.angles[0], fx_ent->s.angles[1], fx_ent->s.angles[2] ); + } else { + gi.Printf(S_COLOR_GREEN "FX: current dir is: <%6.2f %6.2f %6.2f>\n", fx_ent->s.angles[0], fx_ent->s.angles[1], fx_ent->s.angles[2]); } return; } } - gi.Printf( S_COLOR_CYAN"Fx--------------------------------------------------------\n" ); - gi.Printf( S_COLOR_CYAN"commands: sample usage:\n" ); - gi.Printf( S_COLOR_CYAN"----------------------------------------------------------\n" ); - gi.Printf( S_COLOR_CYAN"fx play fx play sparks, fx play env/fire\n" ); - gi.Printf( S_COLOR_CYAN"fx stop fx stop\n" ); - gi.Printf( S_COLOR_CYAN"fx delay <#> fx delay 1000\n" ); - gi.Printf( S_COLOR_CYAN"fx random <#> fx random 200\n" ); - gi.Printf( S_COLOR_CYAN"fx origin <#><#><#> fx origin 10 20 30\n" ); - gi.Printf( S_COLOR_CYAN"fx dir <#><#><#> fx dir 0 0 -1\n\n" ); + gi.Printf(S_COLOR_CYAN "Fx--------------------------------------------------------\n"); + gi.Printf(S_COLOR_CYAN "commands: sample usage:\n"); + gi.Printf(S_COLOR_CYAN "----------------------------------------------------------\n"); + gi.Printf(S_COLOR_CYAN "fx play fx play sparks, fx play env/fire\n"); + gi.Printf(S_COLOR_CYAN "fx stop fx stop\n"); + gi.Printf(S_COLOR_CYAN "fx delay <#> fx delay 1000\n"); + gi.Printf(S_COLOR_CYAN "fx random <#> fx random 200\n"); + gi.Printf(S_COLOR_CYAN "fx origin <#><#><#> fx origin 10 20 30\n"); + gi.Printf(S_COLOR_CYAN "fx dir <#><#><#> fx dir 0 0 -1\n\n"); } /* @@ -442,21 +398,20 @@ Sets client to godmode argv(0) god ================== */ -void Cmd_God_f (gentity_t *ent) -{ - const char *msg; +void Cmd_God_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_GODMODE; - if (!(ent->flags & FL_GODMODE) ) + if (!(ent->flags & FL_GODMODE)) msg = "godmode OFF\n"; else msg = "godmode ON\n"; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } /* @@ -468,32 +423,24 @@ Sets client to undead mode argv(0) undying ================== */ -void Cmd_Undying_f (gentity_t *ent) -{ - const char *msg; +void Cmd_Undying_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) - { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_UNDYING; - if (!(ent->flags & FL_UNDYING) ) - { + if (!(ent->flags & FL_UNDYING)) { msg = "undead mode OFF\n"; - } - else - { - int max; - const char *cmd; + } else { + int max; + const char *cmd; cmd = gi.argv(1); - if ( cmd && atoi( cmd ) ) - { - max = atoi( cmd ); - } - else - { + if (cmd && atoi(cmd)) { + max = atoi(cmd); + } else { max = 999; } @@ -501,13 +448,12 @@ void Cmd_Undying_f (gentity_t *ent) msg = "undead mode ON\n"; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.stats[STAT_HEALTH] = ent->client->ps.stats[STAT_MAX_HEALTH] = 999; } } - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } /* @@ -519,23 +465,22 @@ Sets client to notarget argv(0) notarget ================== */ -void Cmd_Notarget_f( gentity_t *ent ) { - const char *msg; +void Cmd_Notarget_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } ent->flags ^= FL_NOTARGET; - if (!(ent->flags & FL_NOTARGET) ) + if (!(ent->flags & FL_NOTARGET)) msg = "notarget OFF\n"; else msg = "notarget ON\n"; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } - /* ================== Cmd_Noclip_f @@ -543,24 +488,23 @@ Cmd_Noclip_f argv(0) noclip ================== */ -void Cmd_Noclip_f( gentity_t *ent ) { - const char *msg; +void Cmd_Noclip_f(gentity_t *ent) { + const char *msg; - if ( !CheatsOk( ent ) ) { + if (!CheatsOk(ent)) { return; } - if ( ent->client->noclip ) { + if (ent->client->noclip) { msg = "noclip OFF\n"; } else { msg = "noclip ON\n"; } ent->client->noclip = (qboolean)!ent->client->noclip; - gi.SendServerCommand( ent-g_entities, "print \"%s\"", msg); + gi.SendServerCommand(ent - g_entities, "print \"%s\"", msg); } - /* ================== Cmd_LevelShot_f @@ -571,98 +515,92 @@ and sends over a command to the client to resize the view, hide the scoreboard, and take a special screenshot ================== */ -void Cmd_LevelShot_f( gentity_t *ent ) { - if ( !CheatsOk( ent ) ) { +void Cmd_LevelShot_f(gentity_t *ent) { + if (!CheatsOk(ent)) { return; } - gi.SendServerCommand( ent-g_entities, "clientLevelShot" ); + gi.SendServerCommand(ent - g_entities, "clientLevelShot"); } - /* ================= Cmd_Kill_f ================= */ -void Cmd_Kill_f( gentity_t *ent ) { - if( ( level.time - ent->client->respawnTime ) < 5000 ) { - gi.SendServerCommand( ent-g_entities, "cp @INGAME_ONE_KILL_PER_5_SECONDS"); +void Cmd_Kill_f(gentity_t *ent) { + if ((level.time - ent->client->respawnTime) < 5000) { + gi.SendServerCommand(ent - g_entities, "cp @INGAME_ONE_KILL_PER_5_SECONDS"); return; } ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = 0; - player_die (ent, ent, ent, 100000, MOD_SUICIDE); + player_die(ent, ent, ent, 100000, MOD_SUICIDE); } - /* ================== Cmd_Where_f ================== */ -void Cmd_Where_f( gentity_t *ent ) { +void Cmd_Where_f(gentity_t *ent) { const char *s = gi.argv(1); const int len = strlen(s); - gentity_t *check; - - if ( gi.argc () < 2 ) { + gentity_t *check; + + if (gi.argc() < 2) { gi.Printf("usage: where classname\n"); return; } - for (int i = 0; i < globals.num_entities; i++) - { - if(!PInUse(i)) + for (int i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if(!check || !check->inuse) { -// continue; -// } + // if(!check || !check->inuse) { + // continue; + // } check = &g_entities[i]; - if (!Q_stricmpn(s, check->classname, len) ) { - gi.SendServerCommand( ent-g_entities, "print \"%s %s\n\"", check->classname, vtos( check->s.pos.trBase ) ); + if (!Q_stricmpn(s, check->classname, len)) { + gi.SendServerCommand(ent - g_entities, "print \"%s %s\n\"", check->classname, vtos(check->s.pos.trBase)); } } } - /* ------------------------- UserSpawn ------------------------- */ -extern qboolean G_CallSpawn( gentity_t *ent ); +extern qboolean G_CallSpawn(gentity_t *ent); + +void UserSpawn(gentity_t *ent, const char *name) { + vec3_t origin; + vec3_t vf; + vec3_t angles; + gentity_t *ent2; -void UserSpawn( gentity_t *ent, const char *name ) -{ - vec3_t origin; - vec3_t vf; - vec3_t angles; - gentity_t *ent2; - - //Spawn the ent + // Spawn the ent ent2 = G_Spawn(); - ent2->classname = G_NewString( name ); //FIXME: This will leave floating memory... + ent2->classname = G_NewString(name); // FIXME: This will leave floating memory... - //TODO: This should ultimately make sure this is a safe spawn! + // TODO: This should ultimately make sure this is a safe spawn! - //Spawn the entity and place it there - VectorSet( angles, 0, ent->s.apos.trBase[YAW], 0 ); - AngleVectors( angles, vf, NULL, NULL ); - VectorMA( ent->s.pos.trBase, 96, vf, origin ); //FIXME: Find the radius size of the object, and push out 32 + radius + // Spawn the entity and place it there + VectorSet(angles, 0, ent->s.apos.trBase[YAW], 0); + AngleVectors(angles, vf, NULL, NULL); + VectorMA(ent->s.pos.trBase, 96, vf, origin); // FIXME: Find the radius size of the object, and push out 32 + radius origin[2] += 8; - VectorCopy( origin, ent2->s.pos.trBase ); - VectorCopy( origin, ent2->s.origin ); - VectorCopy( ent->s.apos.trBase, ent2->s.angles ); + VectorCopy(origin, ent2->s.pos.trBase); + VectorCopy(origin, ent2->s.origin); + VectorCopy(ent->s.apos.trBase, ent2->s.angles); - gi.linkentity( ent2 ); + gi.linkentity(ent2); - //Find a valid spawning spot - if ( G_CallSpawn( ent2 ) == qfalse ) - { - gi.SendServerCommand( ent-g_entities, "print \"Failed to spawn '%s'\n\"", name ); - G_FreeEntity( ent2 ); + // Find a valid spawning spot + if (G_CallSpawn(ent2) == qfalse) { + gi.SendServerCommand(ent - g_entities, "print \"Failed to spawn '%s'\n\"", name); + G_FreeEntity(ent2); return; } } @@ -673,15 +611,14 @@ Cmd_Spawn ------------------------- */ -void Cmd_Spawn( gentity_t *ent ) -{ - char *name; +void Cmd_Spawn(gentity_t *ent) { + char *name; - name = ConcatArgs( 1 ); + name = ConcatArgs(1); - gi.SendServerCommand( ent-g_entities, "print \"Spawning '%s'\n\"", name ); + gi.SendServerCommand(ent - g_entities, "print \"Spawning '%s'\n\"", name); - UserSpawn( ent, name ); + UserSpawn(ent, name); } /* @@ -689,55 +626,49 @@ void Cmd_Spawn( gentity_t *ent ) Cmd_SetViewpos_f ================= */ -void Cmd_SetViewpos_f( gentity_t *ent ) { - vec3_t origin, angles; - int i; +void Cmd_SetViewpos_f(gentity_t *ent) { + vec3_t origin, angles; + int i; - if ( !g_cheats->integer ) { - gi.SendServerCommand( ent-g_entities, va("print \"Cheats are not enabled on this server.\n\"")); + if (!g_cheats->integer) { + gi.SendServerCommand(ent - g_entities, va("print \"Cheats are not enabled on this server.\n\"")); return; } - if ( gi.argc() != 5 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); + if (gi.argc() != 5) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); return; } - VectorClear( angles ); - for ( i = 0 ; i < 3 ; i++ ) { - origin[i] = atof( gi.argv( i+1 ) ); + VectorClear(angles); + for (i = 0; i < 3; i++) { + origin[i] = atof(gi.argv(i + 1)); } - angles[YAW] = atof( gi.argv( 4 ) ); + angles[YAW] = atof(gi.argv(4)); - TeleportPlayer( ent, origin, angles ); + TeleportPlayer(ent, origin, angles); } - - /* ================= Cmd_SetObjective_f ================= */ -void Cmd_SetObjective_f( gentity_t *ent ) -{ - int objectiveI,status,displayStatus; +void Cmd_SetObjective_f(gentity_t *ent) { + int objectiveI, status, displayStatus; - if ( gi.argc() == 2 ) { + if (gi.argc() == 2) { objectiveI = atoi(gi.argv(1)); - gi.Printf("objective #%d display status=%d, status=%d\n",objectiveI, - ent->client->sess.mission_objectives[objectiveI].display, - ent->client->sess.mission_objectives[objectiveI].status - ); + gi.Printf("objective #%d display status=%d, status=%d\n", objectiveI, ent->client->sess.mission_objectives[objectiveI].display, + ent->client->sess.mission_objectives[objectiveI].status); return; } - if ( gi.argc() != 4 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: setobjective \n\"")); + if (gi.argc() != 4) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: setobjective \n\"")); return; } - if ( !CheatsOk( ent ) ) - { + if (!CheatsOk(ent)) { return; } @@ -754,34 +685,32 @@ void Cmd_SetObjective_f( gentity_t *ent ) Cmd_ViewObjective_f ================= */ -void Cmd_ViewObjective_f( gentity_t *ent ) -{ +void Cmd_ViewObjective_f(gentity_t *ent) { int objectiveI; - if ( gi.argc() != 2 ) { - gi.SendServerCommand( ent-g_entities, va("print \"usage: viewobjective \n\"")); + if (gi.argc() != 2) { + gi.SendServerCommand(ent - g_entities, va("print \"usage: viewobjective \n\"")); return; } objectiveI = atoi(gi.argv(1)); - gi.SendServerCommand( ent-g_entities, va("print \"Objective %d Display Status(1=show): %d Status:%d\n\"",objectiveI,ent->client->sess.mission_objectives[objectiveI].display,ent->client->sess.mission_objectives[objectiveI].status)); + gi.SendServerCommand(ent - g_entities, + va("print \"Objective %d Display Status(1=show): %d Status:%d\n\"", objectiveI, + ent->client->sess.mission_objectives[objectiveI].display, ent->client->sess.mission_objectives[objectiveI].status)); } - /* ================ Cmd_UseElectrobinoculars_f ================ */ -void Cmd_UseElectrobinoculars_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseElectrobinoculars_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - G_AddEvent( ent, EV_USE_INV_BINOCULARS, 0 ); + G_AddEvent(ent, EV_USE_INV_BINOCULARS, 0); } /* @@ -789,10 +718,8 @@ void Cmd_UseElectrobinoculars_f(gentity_t *ent) Cmd_UseBacta_f ================ */ -void Cmd_UseBacta_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseBacta_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } @@ -800,60 +727,55 @@ void Cmd_UseBacta_f(gentity_t *ent) } //---------------------------------------------------------------------------------- -qboolean PickSeekerSpawnPoint( vec3_t org, vec3_t fwd, vec3_t right, int skip, vec3_t spot ) -{ - vec3_t mins, maxs, forward, end; +qboolean PickSeekerSpawnPoint(vec3_t org, vec3_t fwd, vec3_t right, int skip, vec3_t spot) { + vec3_t mins, maxs, forward, end; trace_t tr; - VectorSet( maxs, -8, -8, -24); // ?? size - VectorSet( maxs, 8, 8, 8 ); + VectorSet(maxs, -8, -8, -24); // ?? size + VectorSet(maxs, 8, 8, 8); - VectorCopy( fwd, forward ); + VectorCopy(fwd, forward); // to the front and side a bit forward[2] = 0.3f; // start up a bit - VectorMA( org, 48, forward, end ); - VectorMA( end, -8, right, end ); + VectorMA(org, 48, forward, end); + VectorMA(end, -8, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // side - VectorMA( org, 48, right, end ); + VectorMA(org, 48, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // other side - VectorMA( org, -48, right, end ); + VectorMA(org, -48, right, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } // behind - VectorMA( org, -48, fwd, end ); + VectorMA(org, -48, fwd, end); - gi.trace( &tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, org, mins, maxs, end, skip, MASK_PLAYERSOLID, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f ) - { - VectorCopy( tr.endpos, spot ); + if (!tr.startsolid && !tr.allsolid && tr.fraction >= 1.0f) { + VectorCopy(tr.endpos, spot); return qtrue; } @@ -865,41 +787,35 @@ qboolean PickSeekerSpawnPoint( vec3_t org, vec3_t fwd, vec3_t right, int skip, v Cmd_UseSeeker_f ================ */ -void Cmd_UseSeeker_f( gentity_t *ent ) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseSeeker_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } // don't use them if we don't have any...also don't use them if one is already going - if ( ent->client && ent->client->ps.inventory[INV_SEEKER] > 0 && level.time > ent->client->ps.powerups[PW_SEEKER] ) - { - gentity_t *tent = G_Spawn(); - - if ( tent ) - { - vec3_t fwd, right, spot; + if (ent->client && ent->client->ps.inventory[INV_SEEKER] > 0 && level.time > ent->client->ps.powerups[PW_SEEKER]) { + gentity_t *tent = G_Spawn(); + + if (tent) { + vec3_t fwd, right, spot; - AngleVectors( ent->client->ps.viewangles, fwd, right, NULL ); + AngleVectors(ent->client->ps.viewangles, fwd, right, NULL); - VectorCopy( ent->currentOrigin, spot ); // does nothing really, just initialize the goods... + VectorCopy(ent->currentOrigin, spot); // does nothing really, just initialize the goods... - if ( PickSeekerSpawnPoint( ent->currentOrigin, fwd, right, ent->s.number, spot )) - { - VectorCopy( spot, tent->s.origin ); - G_SetOrigin( tent, spot ); - G_SetAngles( tent, ent->currentAngles ); + if (PickSeekerSpawnPoint(ent->currentOrigin, fwd, right, ent->s.number, spot)) { + VectorCopy(spot, tent->s.origin); + G_SetOrigin(tent, spot); + G_SetAngles(tent, ent->currentAngles); -extern void SP_NPC_Droid_Seeker( gentity_t *ent ); + extern void SP_NPC_Droid_Seeker(gentity_t * ent); - SP_NPC_Droid_Seeker( tent ); - G_Sound( tent, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + SP_NPC_Droid_Seeker(tent); + G_Sound(tent, G_SoundIndex("sound/chars/seeker/misc/hiss")); // make sure that we even have some ent->client->ps.inventory[INV_SEEKER]--; - ent->client->ps.powerups[PW_SEEKER] = level.time + 1000;// can only drop one every second..maybe this is annoying? - + ent->client->ps.powerups[PW_SEEKER] = level.time + 1000; // can only drop one every second..maybe this is annoying? } } } @@ -910,16 +826,13 @@ extern void SP_NPC_Droid_Seeker( gentity_t *ent ); Cmd_UseGoggles_f ================ */ -void Cmd_UseGoggles_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +void Cmd_UseGoggles_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - if ( ent->client && ent->client->ps.inventory[INV_LIGHTAMP_GOGGLES] > 0 ) - { - G_AddEvent( ent, EV_USE_INV_LIGHTAMP_GOGGLES, 0 ); + if (ent->client && ent->client->ps.inventory[INV_LIGHTAMP_GOGGLES] > 0) { + G_AddEvent(ent, EV_USE_INV_LIGHTAMP_GOGGLES, 0); } } @@ -928,27 +841,21 @@ void Cmd_UseGoggles_f(gentity_t *ent) Cmd_UseSentry_f ================ */ -qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t dir ); -void Cmd_UseSentry_f(gentity_t *ent) -{ - if ( ent->health < 1 || in_camera ) - { +qboolean place_portable_assault_sentry(gentity_t *self, vec3_t origin, vec3_t dir); +void Cmd_UseSentry_f(gentity_t *ent) { + if (ent->health < 1 || in_camera) { return; } - if ( ent->client->ps.inventory[INV_SENTRY] <= 0 ) - { + if (ent->client->ps.inventory[INV_SENTRY] <= 0) { // have none to place...play sound? return; } - if ( place_portable_assault_sentry( ent, ent->currentOrigin, ent->client->ps.viewangles )) - { + if (place_portable_assault_sentry(ent, ent->currentOrigin, ent->client->ps.viewangles)) { ent->client->ps.inventory[INV_SENTRY]--; - G_AddEvent( ent, EV_USE_INV_SENTRY, 0 ); - } - else - { + G_AddEvent(ent, EV_USE_INV_SENTRY, 0); + } else { // couldn't be placed....play a notification sound!! } } @@ -958,47 +865,39 @@ void Cmd_UseSentry_f(gentity_t *ent) Cmd_UseInventory_f ================ */ -void Cmd_UseInventory_f(gentity_t *ent) -{ - switch (cg.inventorySelect) - { - case INV_ELECTROBINOCULARS : - Cmd_UseElectrobinoculars_f(ent); - return; - case INV_BACTA_CANISTER : - Cmd_UseBacta_f(ent); - return; - case INV_SEEKER : - Cmd_UseSeeker_f(ent); - return; - case INV_LIGHTAMP_GOGGLES : - Cmd_UseGoggles_f(ent); - return; - case INV_SENTRY : - Cmd_UseSentry_f(ent); - return; - default : - return; - +void Cmd_UseInventory_f(gentity_t *ent) { + switch (cg.inventorySelect) { + case INV_ELECTROBINOCULARS: + Cmd_UseElectrobinoculars_f(ent); + return; + case INV_BACTA_CANISTER: + Cmd_UseBacta_f(ent); + return; + case INV_SEEKER: + Cmd_UseSeeker_f(ent); + return; + case INV_LIGHTAMP_GOGGLES: + Cmd_UseGoggles_f(ent); + return; + case INV_SENTRY: + Cmd_UseSentry_f(ent); + return; + default: + return; } } -void G_Taunt( gentity_t *ent ) -{ - if ( ent->client ) - { +void G_Taunt(gentity_t *ent) { + if (ent->client) { ent->client->ps.taunting = level.time + 100; } } -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -void G_Victory( gentity_t *ent ) -{ - if ( ent->health > 0 ) - {//say something and put away saber - G_SoundOnEnt( ent, CHAN_VOICE, "sound/chars/kyle/misc/taunt1.wav" ); - if ( ent->client ) - { +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +void G_Victory(gentity_t *ent) { + if (ent->health > 0) { // say something and put away saber + G_SoundOnEnt(ent, CHAN_VOICE, "sound/chars/kyle/misc/taunt1.wav"); + if (ent->client) { ent->client->ps.saberActive = qfalse; } } @@ -1008,129 +907,101 @@ void G_Victory( gentity_t *ent ) ClientCommand ================= */ -void ClientCommand( int clientNum ) { +void ClientCommand(int clientNum) { gentity_t *ent; - const char *cmd; + const char *cmd; ent = g_entities + clientNum; - if ( !ent->client ) { - return; // not fully in game yet + if (!ent->client) { + return; // not fully in game yet } cmd = gi.argv(0); - if (Q_stricmp (cmd, "spawn") == 0) - { - Cmd_Spawn( ent ); + if (Q_stricmp(cmd, "spawn") == 0) { + Cmd_Spawn(ent); return; } - - if (Q_stricmp (cmd, "give") == 0) - Cmd_Give_f (ent); - else if (Q_stricmp (cmd, "god") == 0) - Cmd_God_f (ent); - else if (Q_stricmp (cmd, "undying") == 0) - Cmd_Undying_f (ent); - else if (Q_stricmp (cmd, "notarget") == 0) - Cmd_Notarget_f (ent); - else if (Q_stricmp (cmd, "noclip") == 0) - { - Cmd_Noclip_f (ent); - } - else if (Q_stricmp (cmd, "kill") == 0) - { - if ( !CheatsOk( ent ) ) - { + + if (Q_stricmp(cmd, "give") == 0) + Cmd_Give_f(ent); + else if (Q_stricmp(cmd, "god") == 0) + Cmd_God_f(ent); + else if (Q_stricmp(cmd, "undying") == 0) + Cmd_Undying_f(ent); + else if (Q_stricmp(cmd, "notarget") == 0) + Cmd_Notarget_f(ent); + else if (Q_stricmp(cmd, "noclip") == 0) { + Cmd_Noclip_f(ent); + } else if (Q_stricmp(cmd, "kill") == 0) { + if (!CheatsOk(ent)) { return; } - Cmd_Kill_f (ent); - } - else if (Q_stricmp (cmd, "levelshot") == 0) - Cmd_LevelShot_f (ent); - else if (Q_stricmp (cmd, "where") == 0) - Cmd_Where_f (ent); - else if (Q_stricmp (cmd, "setviewpos") == 0) - Cmd_SetViewpos_f( ent ); - else if (Q_stricmp (cmd, "setobjective") == 0) - Cmd_SetObjective_f( ent ); - else if (Q_stricmp (cmd, "viewobjective") == 0) - Cmd_ViewObjective_f( ent ); - else if (Q_stricmp (cmd, "force_throw") == 0) - { + Cmd_Kill_f(ent); + } else if (Q_stricmp(cmd, "levelshot") == 0) + Cmd_LevelShot_f(ent); + else if (Q_stricmp(cmd, "where") == 0) + Cmd_Where_f(ent); + else if (Q_stricmp(cmd, "setviewpos") == 0) + Cmd_SetViewpos_f(ent); + else if (Q_stricmp(cmd, "setobjective") == 0) + Cmd_SetObjective_f(ent); + else if (Q_stricmp(cmd, "viewobjective") == 0) + Cmd_ViewObjective_f(ent); + else if (Q_stricmp(cmd, "force_throw") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceThrow( ent, qfalse ); - } - else if (Q_stricmp (cmd, "force_pull") == 0) - { + ForceThrow(ent, qfalse); + } else if (Q_stricmp(cmd, "force_pull") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceThrow( ent, qtrue ); - } - else if (Q_stricmp (cmd, "force_speed") == 0) - { + ForceThrow(ent, qtrue); + } else if (Q_stricmp(cmd, "force_speed") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceSpeed( ent ); - } - else if (Q_stricmp (cmd, "force_heal") == 0) - { + ForceSpeed(ent); + } else if (Q_stricmp(cmd, "force_heal") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceHeal( ent ); - } - else if (Q_stricmp (cmd, "force_grip") == 0) - { + ForceHeal(ent); + } else if (Q_stricmp(cmd, "force_grip") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceGrip( ent ); - } - else if (Q_stricmp (cmd, "force_distract") == 0) - { + ForceGrip(ent); + } else if (Q_stricmp(cmd, "force_distract") == 0) { ent = G_GetSelfForPlayerCmd(); - ForceTelepathy( ent ); - } - else if (Q_stricmp (cmd, "taunt") == 0) - { + ForceTelepathy(ent); + } else if (Q_stricmp(cmd, "taunt") == 0) { ent = G_GetSelfForPlayerCmd(); - G_Taunt( ent ); - } - else if (Q_stricmp (cmd, "victory") == 0) - G_Victory( ent ); -// else if (Q_stricmp (cmd, "use_shield") == 0) // sounds like the design doc states that the shields will be a pickup and so the player never decides whether to use them or not. -// G_ActivatePersonalShield( ent ); // If you want shields (armor), type "give all" or "give armor" or "give armor #amt#" - else if (Q_stricmp (cmd, "fly_xwing") == 0) - G_PilotXWing( ent ); - else if (Q_stricmp (cmd, "drive_atst") == 0) - { - if ( CheatsOk( ent ) ) - { - G_DriveATST( ent, NULL ); + G_Taunt(ent); + } else if (Q_stricmp(cmd, "victory") == 0) + G_Victory(ent); + // else if (Q_stricmp (cmd, "use_shield") == 0) // sounds like the design doc states that the shields will be a pickup and so the player never decides + //whether to use them or not. G_ActivatePersonalShield( ent ); // If you want shields (armor), type "give all" or "give armor" or "give armor + //#amt#" + else if (Q_stricmp(cmd, "fly_xwing") == 0) + G_PilotXWing(ent); + else if (Q_stricmp(cmd, "drive_atst") == 0) { + if (CheatsOk(ent)) { + G_DriveATST(ent, NULL); } - } - else if (Q_stricmp (cmd, "thereisnospoon") == 0) - G_StartMatrixEffect( ent ); - else if (Q_stricmp (cmd, "use_electrobinoculars") == 0) - Cmd_UseElectrobinoculars_f( ent ); - else if (Q_stricmp (cmd, "use_bacta") == 0) - Cmd_UseBacta_f( ent ); - else if (Q_stricmp (cmd, "use_seeker") == 0) - Cmd_UseSeeker_f( ent ); - else if (Q_stricmp (cmd, "use_lightamp_goggles") == 0) - Cmd_UseGoggles_f( ent ); - else if (Q_stricmp (cmd, "use_sentry") == 0) - Cmd_UseSentry_f( ent ); - else if (Q_stricmp (cmd, "fx") == 0) - Cmd_Fx( ent ); - else if (Q_stricmp (cmd, "invuse") == 0) - { - Cmd_UseInventory_f( ent ); - } - else if (Q_stricmp (cmd, "playmusic") == 0) - { + } else if (Q_stricmp(cmd, "thereisnospoon") == 0) + G_StartMatrixEffect(ent); + else if (Q_stricmp(cmd, "use_electrobinoculars") == 0) + Cmd_UseElectrobinoculars_f(ent); + else if (Q_stricmp(cmd, "use_bacta") == 0) + Cmd_UseBacta_f(ent); + else if (Q_stricmp(cmd, "use_seeker") == 0) + Cmd_UseSeeker_f(ent); + else if (Q_stricmp(cmd, "use_lightamp_goggles") == 0) + Cmd_UseGoggles_f(ent); + else if (Q_stricmp(cmd, "use_sentry") == 0) + Cmd_UseSentry_f(ent); + else if (Q_stricmp(cmd, "fx") == 0) + Cmd_Fx(ent); + else if (Q_stricmp(cmd, "invuse") == 0) { + Cmd_UseInventory_f(ent); + } else if (Q_stricmp(cmd, "playmusic") == 0) { const char *cmd2 = gi.argv(1); - if ( cmd2 ) - { - gi.SetConfigstring( CS_MUSIC, cmd2 ); + if (cmd2) { + gi.SetConfigstring(CS_MUSIC, cmd2); } - } - else - { - gi.SendServerCommand( clientNum, va("print \"Unknown command %s\n\"", cmd ) ); + } else { + gi.SendServerCommand(clientNum, va("print \"Unknown command %s\n\"", cmd)); } } diff --git a/codeJK2/game/g_combat.cpp b/codeJK2/game/g_combat.cpp index 3a35dbf4d9..3ec6a4f810 100644 --- a/codeJK2/game/g_combat.cpp +++ b/codeJK2/game/g_combat.cpp @@ -36,57 +36,57 @@ along with this program; if not, see . #include "Q3_Interface.h" #include "../../code/qcommon/strippublic.h" -extern cvar_t *g_debugDamage; -extern qboolean stop_icarus; -extern cvar_t *g_dismemberment; -extern cvar_t *g_dismemberProbabilities; -extern cvar_t *g_saberRealisticCombat; -extern cvar_t *g_timescale; -extern cvar_t *d_slowmodeath; +extern cvar_t *g_debugDamage; +extern qboolean stop_icarus; +extern cvar_t *g_dismemberment; +extern cvar_t *g_dismemberProbabilities; +extern cvar_t *g_saberRealisticCombat; +extern cvar_t *g_timescale; +extern cvar_t *d_slowmodeath; extern gentity_t *player; gentity_t *g_lastClientDamaged; extern int killPlayerTimer; -extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); -extern qboolean G_TeamEnemy( gentity_t *self ); -extern void CG_ChangeWeapon( int num ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern qboolean PM_InOnGroundAnim ( playerState_t *ps ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void G_ATSTCheckPain( gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InRoll( playerState_t *ps ); -extern qboolean PM_SpinningAnim( int anim ); -extern qboolean PM_RunningAnim( int anim ); -extern int PM_PowerLevelForSaberAnim( playerState_t *ps ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInReturn( int move ); -extern int PM_AnimLength( int index, animNumber_t anim ); - -static int G_CheckForLedge( gentity_t *self, vec3_t fallCheckDir, float checkDist ); -static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ); -static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ); -static void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod ); -static qboolean G_Dismemberable( gentity_t *self, int hitLoc ); -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean PM_HasAnimation(gentity_t *ent, int animation); +extern qboolean G_TeamEnemy(gentity_t *self); +extern void CG_ChangeWeapon(int num); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); + +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern qboolean PM_InOnGroundAnim(playerState_t *ps); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void G_ATSTCheckPain(gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InRoll(playerState_t *ps); +extern qboolean PM_SpinningAnim(int anim); +extern qboolean PM_RunningAnim(int anim); +extern int PM_PowerLevelForSaberAnim(playerState_t *ps); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInReturn(int move); +extern int PM_AnimLength(int index, animNumber_t anim); + +static int G_CheckForLedge(gentity_t *self, vec3_t fallCheckDir, float checkDist); +static int G_CheckSpecialDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc); +static int G_PickDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc); +static void G_TrackWeaponUsage(gentity_t *self, gentity_t *inflictor, int add, int mod); +static qboolean G_Dismemberable(gentity_t *self, int hitLoc); +extern gitem_t *FindItemForAmmo(ammo_t ammo); /* ============ AddScore @@ -94,8 +94,8 @@ AddScore Adds score to both the client and his team ============ */ -void AddScore( gentity_t *ent, int score ) { - if ( !ent->client ) { +void AddScore(gentity_t *ent, int score) { + if (!ent->client) { return; } // no scoring during pre-match warmup @@ -109,63 +109,48 @@ TossClientItems Toss the weapon and powerups for the killed player ================= */ -extern gentity_t *WP_DropThermal( gentity_t *ent ); -extern qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -gentity_t *TossClientItems( gentity_t *self ) -{ - gentity_t *dropped = NULL; - gitem_t *item = NULL; - int weapon; - - if ( self->client->NPC_class == CLASS_SEEKER || self->client->NPC_class == CLASS_REMOTE ) - { +extern gentity_t *WP_DropThermal(gentity_t *ent); +extern qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +gentity_t *TossClientItems(gentity_t *self) { + gentity_t *dropped = NULL; + gitem_t *item = NULL; + int weapon; + + if (self->client->NPC_class == CLASS_SEEKER || self->client->NPC_class == CLASS_REMOTE) { // these things are so small that they shouldn't bother throwing anything return NULL; } // drop the weapon if not a saber or enemy-only weapon weapon = self->s.weapon; - if ( weapon == WP_SABER ) - { - if ( self->weaponModel < 0 || WP_SaberLose( self, NULL ) ) - { + if (weapon == WP_SABER) { + if (self->weaponModel < 0 || WP_SaberLose(self, NULL)) { self->s.weapon = WP_NONE; } - } - else if ( weapon == WP_BLASTER_PISTOL ) - {//FIXME: either drop the pistol and make the pickup only give ammo or drop ammo - } - else if ( weapon > WP_SABER && weapon <= MAX_PLAYER_WEAPONS )//&& self->client->ps.ammo[ weaponData[weapon].ammoIndex ] + } else if (weapon == WP_BLASTER_PISTOL) { // FIXME: either drop the pistol and make the pickup only give ammo or drop ammo + } else if (weapon > WP_SABER && weapon <= MAX_PLAYER_WEAPONS) //&& self->client->ps.ammo[ weaponData[weapon].ammoIndex ] { self->s.weapon = WP_NONE; - if ( weapon == WP_THERMAL && self->client->ps.torsoAnim == BOTH_ATTACK10 ) - {//we were getting ready to throw the thermal, drop it! - self->client->ps.weaponChargeTime = level.time - FRAMETIME;//so it just kind of drops it - dropped = WP_DropThermal( self ); + if (weapon == WP_THERMAL && self->client->ps.torsoAnim == BOTH_ATTACK10) { // we were getting ready to throw the thermal, drop it! + self->client->ps.weaponChargeTime = level.time - FRAMETIME; // so it just kind of drops it + dropped = WP_DropThermal(self); + } else { // find the item type for this weapon + item = FindItemForWeapon((weapon_t)weapon); } - else - {// find the item type for this weapon - item = FindItemForWeapon( (weapon_t) weapon ); - } - if ( item && !dropped ) - { + if (item && !dropped) { // spawn the item - dropped = Drop_Item( self, item, 0, qtrue ); - //TEST: dropped items never go away + dropped = Drop_Item(self, item, 0, qtrue); + // TEST: dropped items never go away dropped->e_ThinkFunc = thinkF_NULL; dropped->nextthink = -1; - if ( !self->s.number ) - {//player's dropped items never go away - //dropped->e_ThinkFunc = thinkF_NULL; - //dropped->nextthink = -1; - dropped->count = 0;//no ammo - } - else - {//FIXME: base this on the NPC's actual amount of ammo he's used up... - switch ( weapon ) - { + if (!self->s.number) { // player's dropped items never go away + // dropped->e_ThinkFunc = thinkF_NULL; + // dropped->nextthink = -1; + dropped->count = 0; // no ammo + } else { // FIXME: base this on the NPC's actual amount of ammo he's used up... + switch (weapon) { case WP_BRYAR_PISTOL: dropped->count = 20; break; @@ -208,75 +193,58 @@ gentity_t *TossClientItems( gentity_t *self ) } } // well, dropped weapons are G2 models, so they have to be initialised if they want to draw..give us a radius so we don't get prematurely culled - if ( weapon != WP_THERMAL - && weapon != WP_TRIP_MINE - && weapon != WP_DET_PACK ) - { - gi.G2API_InitGhoul2Model( dropped->ghoul2, item->world_model, G_ModelIndex( item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0); + if (weapon != WP_THERMAL && weapon != WP_TRIP_MINE && weapon != WP_DET_PACK) { + gi.G2API_InitGhoul2Model(dropped->ghoul2, item->world_model, G_ModelIndex(item->world_model), NULL_HANDLE, NULL_HANDLE, 0, 0); dropped->s.radius = 10; } } } -// else if (( self->client->NPC_class == CLASS_SENTRY ) || ( self->client->NPC_class == CLASS_PROBE )) // Looks dumb, Steve told us to take it out. -// { -// item = FindItemForAmmo( AMMO_BLASTER ); -// Drop_Item( self, item, 0, qtrue ); -// } - else if ( self->client->NPC_class == CLASS_MARK1 ) - { + // else if (( self->client->NPC_class == CLASS_SENTRY ) || ( self->client->NPC_class == CLASS_PROBE )) // Looks dumb, Steve told us to take it out. + // { + // item = FindItemForAmmo( AMMO_BLASTER ); + // Drop_Item( self, item, 0, qtrue ); + // } + else if (self->client->NPC_class == CLASS_MARK1) { - if (Q_irand( 1, 2 )>1) - { - item = FindItemForAmmo( AMMO_METAL_BOLTS ); - } - else - { - item = FindItemForAmmo( AMMO_BLASTER ); + if (Q_irand(1, 2) > 1) { + item = FindItemForAmmo(AMMO_METAL_BOLTS); + } else { + item = FindItemForAmmo(AMMO_BLASTER); } - Drop_Item( self, item, 0, qtrue ); - } - else if ( self->client->NPC_class == CLASS_MARK2 ) - { + Drop_Item(self, item, 0, qtrue); + } else if (self->client->NPC_class == CLASS_MARK2) { - if (Q_irand( 1, 2 )>1) - { - item = FindItemForAmmo( AMMO_METAL_BOLTS ); - } - else - { - item = FindItemForAmmo( AMMO_POWERCELL ); + if (Q_irand(1, 2) > 1) { + item = FindItemForAmmo(AMMO_METAL_BOLTS); + } else { + item = FindItemForAmmo(AMMO_POWERCELL); } - Drop_Item( self, item, 0, qtrue ); + Drop_Item(self, item, 0, qtrue); } - return dropped;//NOTE: presumes only drop one thing + return dropped; // NOTE: presumes only drop one thing } -void G_DropKey( gentity_t *self ) -{//drop whatever security key I was holding - gitem_t *item = NULL; - if ( !Q_stricmp( "goodie", self->message ) ) - { - item = FindItemForInventory( INV_GOODIE_KEY ); - } - else - { - item = FindItemForInventory( INV_SECURITY_KEY ); - } - gentity_t *dropped = Drop_Item( self, item, 0, qtrue ); - //Don't throw the key - VectorClear( dropped->s.pos.trDelta ); - dropped->message = G_NewString( self->message ); +void G_DropKey(gentity_t *self) { // drop whatever security key I was holding + gitem_t *item = NULL; + if (!Q_stricmp("goodie", self->message)) { + item = FindItemForInventory(INV_GOODIE_KEY); + } else { + item = FindItemForInventory(INV_SECURITY_KEY); + } + gentity_t *dropped = Drop_Item(self, item, 0, qtrue); + // Don't throw the key + VectorClear(dropped->s.pos.trDelta); + dropped->message = G_NewString(self->message); self->message = NULL; } -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) -{ - if(self->target) +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { + if (self->target) G_UseTargets(self, attacker); - //remove my script_targetname - G_FreeEntity( self ); + // remove my script_targetname + G_FreeEntity(self); } /* ================== @@ -284,118 +252,96 @@ ExplodeDeath ================== */ -//FIXME: all hacked up... +// FIXME: all hacked up... -//void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ); -void ExplodeDeath( gentity_t *self ) -{ -// gentity_t *tent; - vec3_t forward; +// void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ); +void ExplodeDeath(gentity_t *self) { + // gentity_t *tent; + vec3_t forward; - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops self->s.loopSound = 0; - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); -// tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); - AngleVectors(self->s.angles, forward, NULL, NULL); // FIXME: letting effect always shoot up? Might be ok. + // tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); + AngleVectors(self->s.angles, forward, NULL, NULL); // FIXME: letting effect always shoot up? Might be ok. - if ( self->fxID > 0 ) - { - G_PlayEffect( self->fxID, self->currentOrigin, forward ); + if (self->fxID > 0) { + G_PlayEffect(self->fxID, self->currentOrigin, forward); } -// else -// { -// CG_SurfaceExplosion( self->currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all exploders! -// G_Sound(self, self->sounds ); -// } + // else + // { + // CG_SurfaceExplosion( self->currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all + //exploders! G_Sound(self, self->sounds ); + // } - if(self->splashDamage > 0 && self->splashRadius > 0) - { + if (self->splashDamage > 0 && self->splashRadius > 0) { gentity_t *attacker = self; - if ( self->owner ) - { + if (self->owner) { attacker = self->owner; } - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, - attacker, MOD_UNKNOWN ); + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - ObjectDie( self, self, self, 20, 0 ); + ObjectDie(self, self, self, 20, 0); } -void ExplodeDeath_Wait( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ +void ExplodeDeath_Wait(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { self->e_DieFunc = dieF_NULL; self->nextthink = level.time + Q_irand(100, 500); self->e_ThinkFunc = thinkF_ExplodeDeath; } -void ExplodeDeath( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) -{ +void ExplodeDeath(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) { self->currentOrigin[2] += 16; // me bad for hacking this. should either do it in the effect file or make a custom explode death?? - ExplodeDeath( self ); + ExplodeDeath(self); } -void GoExplodeDeath( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void GoExplodeDeath(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - self->targetname = ""; //Make sure this entity cannot be told to explode again (recursive death fix) + self->targetname = ""; // Make sure this entity cannot be told to explode again (recursive death fix) - ExplodeDeath( self ); + ExplodeDeath(self); } -qboolean G_ActivateBehavior (gentity_t *self, int bset ); -void G_CheckVictoryScript(gentity_t *self) -{ - if ( !G_ActivateBehavior( self, BSET_VICTORY ) ) - { - if ( self->NPC && self->s.weapon == WP_SABER ) - {//Jedi taunt from within their AI - self->NPC->blockedSpeechDebounceTime = 0;//get them ready to taunt +qboolean G_ActivateBehavior(gentity_t *self, int bset); +void G_CheckVictoryScript(gentity_t *self) { + if (!G_ActivateBehavior(self, BSET_VICTORY)) { + if (self->NPC && self->s.weapon == WP_SABER) { // Jedi taunt from within their AI + self->NPC->blockedSpeechDebounceTime = 0; // get them ready to taunt return; } - if ( self->client && self->client->NPC_class == CLASS_GALAKMECH ) - { + if (self->client && self->client->NPC_class == CLASS_GALAKMECH) { self->wait = 1; - TIMER_Set( self, "gloatTime", Q_irand( 5000, 8000 ) ); - self->NPC->blockedSpeechDebounceTime = 0;//get him ready to taunt + TIMER_Set(self, "gloatTime", Q_irand(5000, 8000)); + self->NPC->blockedSpeechDebounceTime = 0; // get him ready to taunt return; } - //FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? - if ( self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand( 0, 2 ) ) - {//sometimes have the group commander speak instead - self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); - } - else if ( self->NPC ) - { - self->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + // FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? + if (self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && + self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand(0, 2)) { // sometimes have the group commander speak instead + self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + } else if (self->NPC) { + self->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); } } } -qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) -{ - if ( !ent1->client || !ent2->client ) - { - if ( ent1->noDamageTeam ) - { - if ( ent2->client && ent2->client->playerTeam == ent1->noDamageTeam ) - { +qboolean OnSameTeam(gentity_t *ent1, gentity_t *ent2) { + if (!ent1->client || !ent2->client) { + if (ent1->noDamageTeam) { + if (ent2->client && ent2->client->playerTeam == ent1->noDamageTeam) { return qtrue; - } - else if ( ent2->noDamageTeam == ent1->noDamageTeam ) - { - if ( ent1->splashDamage && ent2->splashDamage && Q_stricmp("ambient_etherian_fliers", ent1->classname) != 0 ) - {//Barrels, exploding breakables and mines will blow each other up + } else if (ent2->noDamageTeam == ent1->noDamageTeam) { + if (ent1->splashDamage && ent2->splashDamage && + Q_stricmp("ambient_etherian_fliers", ent1->classname) != 0) { // Barrels, exploding breakables and mines will blow each other up return qfalse; - } - else - { + } else { return qtrue; } } @@ -404,105 +350,97 @@ qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) } // shouldn't need this anymore, there were problems with certain droids, but now they have been labeled TEAM_ENEMY so this isn't needed -// if ((( ent1->client->playerTeam == TEAM_IMPERIAL ) && ( ent1->client->playerTeam == TEAM_BOTS )) || -// (( ent1->client->playerTeam == TEAM_BOTS ) && ( ent1->client->playerTeam == TEAM_IMPERIAL ))) -// { -// return qtrue; -// } + // if ((( ent1->client->playerTeam == TEAM_IMPERIAL ) && ( ent1->client->playerTeam == TEAM_BOTS )) || + // (( ent1->client->playerTeam == TEAM_BOTS ) && ( ent1->client->playerTeam == TEAM_IMPERIAL ))) + // { + // return qtrue; + // } - return (qboolean)( ent1->client->playerTeam == ent2->client->playerTeam ); + return (qboolean)(ent1->client->playerTeam == ent2->client->playerTeam); } - /* ------------------------- G_AlertTeam ------------------------- */ -void G_AlertTeam( gentity_t *victim, gentity_t *attacker, float radius, float soundDist ) -{ - gentity_t *radiusEnts[ 128 ]; - vec3_t mins, maxs; - int numEnts; - float distSq, sndDistSq = (soundDist*soundDist); +void G_AlertTeam(gentity_t *victim, gentity_t *attacker, float radius, float soundDist) { + gentity_t *radiusEnts[128]; + vec3_t mins, maxs; + int numEnts; + float distSq, sndDistSq = (soundDist * soundDist); int i; - if ( attacker == NULL || attacker->client == NULL ) + if (attacker == NULL || attacker->client == NULL) return; - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = victim->currentOrigin[i] - radius; maxs[i] = victim->currentOrigin[i] + radius; } - //Get the number of entities in a given space - numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = gi.EntitiesInBox(mins, maxs, radiusEnts, 128); - //Cull this list - for ( i = 0; i < numEnts; i++ ) - { - //Validate clients - if ( radiusEnts[i]->client == NULL ) + // Cull this list + for (i = 0; i < numEnts; i++) { + // Validate clients + if (radiusEnts[i]->client == NULL) continue; - //only want NPCs - if ( radiusEnts[i]->NPC == NULL ) + // only want NPCs + if (radiusEnts[i]->NPC == NULL) continue; - //Don't bother if they're ignoring enemies - if ( radiusEnts[i]->svFlags & SVF_IGNORE_ENEMIES ) + // Don't bother if they're ignoring enemies + if (radiusEnts[i]->svFlags & SVF_IGNORE_ENEMIES) continue; - //This NPC specifically flagged to ignore alerts - if ( radiusEnts[i]->NPC->scriptFlags & SCF_IGNORE_ALERTS ) + // This NPC specifically flagged to ignore alerts + if (radiusEnts[i]->NPC->scriptFlags & SCF_IGNORE_ALERTS) continue; - //This NPC specifically flagged to ignore alerts - if ( !(radiusEnts[i]->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) + // This NPC specifically flagged to ignore alerts + if (!(radiusEnts[i]->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES)) continue; - //this ent does not participate in group AI - if ( (radiusEnts[i]->NPC->scriptFlags&SCF_NO_GROUPS) ) + // this ent does not participate in group AI + if ((radiusEnts[i]->NPC->scriptFlags & SCF_NO_GROUPS)) continue; - //Skip the requested avoid radiusEnts[i] if present - if ( radiusEnts[i] == victim ) + // Skip the requested avoid radiusEnts[i] if present + if (radiusEnts[i] == victim) continue; - //Skip the attacker - if ( radiusEnts[i] == attacker ) + // Skip the attacker + if (radiusEnts[i] == attacker) continue; - //Must be on the same team - if ( radiusEnts[i]->client->playerTeam != victim->client->playerTeam ) + // Must be on the same team + if (radiusEnts[i]->client->playerTeam != victim->client->playerTeam) continue; - //Must be alive - if ( radiusEnts[i]->health <= 0 ) + // Must be alive + if (radiusEnts[i]->health <= 0) continue; - if ( radiusEnts[i]->enemy == NULL ) - {//only do this if they're not already mad at someone - distSq = DistanceSquared( radiusEnts[i]->currentOrigin, victim->currentOrigin ); - if ( distSq > 16384 /*128 squared*/ && !gi.inPVS( victim->currentOrigin, radiusEnts[i]->currentOrigin ) ) - {//not even potentially visible/hearable + if (radiusEnts[i]->enemy == NULL) { // only do this if they're not already mad at someone + distSq = DistanceSquared(radiusEnts[i]->currentOrigin, victim->currentOrigin); + if (distSq > 16384 /*128 squared*/ && !gi.inPVS(victim->currentOrigin, radiusEnts[i]->currentOrigin)) { // not even potentially visible/hearable continue; } - //NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... - if ( soundDist <= 0 || distSq > sndDistSq ) - {//out of sound range - if ( !InFOV( victim, radiusEnts[i], radiusEnts[i]->NPC->stats.hfov, radiusEnts[i]->NPC->stats.vfov ) - || !NPC_ClearLOS( radiusEnts[i], victim->currentOrigin ) ) - {//out of FOV or no LOS + // NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... + if (soundDist <= 0 || distSq > sndDistSq) { // out of sound range + if (!InFOV(victim, radiusEnts[i], radiusEnts[i]->NPC->stats.hfov, radiusEnts[i]->NPC->stats.vfov) || + !NPC_ClearLOS(radiusEnts[i], victim->currentOrigin)) { // out of FOV or no LOS continue; } } - //FIXME: This can have a nasty cascading effect if setup wrong... - G_SetEnemy( radiusEnts[i], attacker ); + // FIXME: This can have a nasty cascading effect if setup wrong... + G_SetEnemy(radiusEnts[i], attacker); } } } @@ -513,12 +451,11 @@ G_DeathAlert ------------------------- */ -#define DEATH_ALERT_RADIUS 512 -#define DEATH_ALERT_SOUND_RADIUS 512 +#define DEATH_ALERT_RADIUS 512 +#define DEATH_ALERT_SOUND_RADIUS 512 -void G_DeathAlert( gentity_t *victim, gentity_t *attacker ) -{//FIXME: with all the other alert stuff, do we really need this? - G_AlertTeam( victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS ); +void G_DeathAlert(gentity_t *victim, gentity_t *attacker) { // FIXME: with all the other alert stuff, do we really need this? + G_AlertTeam(victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS); } /* @@ -530,276 +467,245 @@ Not to be confused with NPC_RemoveBodyEffects (NPC.cpp), which only applies effe ---------------------------------------- */ -void DeathFX( gentity_t *ent ) -{ - if ( !ent || !ent->client ) +void DeathFX(gentity_t *ent) { + if (!ent || !ent->client) return; -/* - switch( ent->client->playerTeam ) - { - case TEAM_BOTS: - if (!Q_stricmp( ent->NPC_type, "mouse" )) + /* + switch( ent->client->playerTeam ) { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] -= 20; + case TEAM_BOTS: + if (!Q_stricmp( ent->NPC_type, "mouse" )) + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] -= 20; - G_PlayEffect( "mouseexplosion1", effectPos ); - G_PlayEffect( "smaller_chunks", effectPos ); + G_PlayEffect( "mouseexplosion1", effectPos ); + G_PlayEffect( "smaller_chunks", effectPos ); - } - else if (!Q_stricmp( ent->NPC_type, "probe" )) - { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] += 50; + } + else if (!Q_stricmp( ent->NPC_type, "probe" )) + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] += 50; - G_PlayEffect( "probeexplosion1", effectPos ); - G_PlayEffect( "small_chunks", effectPos ); - } - else - { - vec3_t effectPos; - VectorCopy( ent->currentOrigin, effectPos ); - effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); - G_PlayEffect( "small_chunks", effectPos ); - } + G_PlayEffect( "probeexplosion1", effectPos ); + G_PlayEffect( "small_chunks", effectPos ); + } + else + { + vec3_t effectPos; + VectorCopy( ent->currentOrigin, effectPos ); + effectPos[2] -= 15; + G_PlayEffect( "droidexplosion1", effectPos ); + G_PlayEffect( "small_chunks", effectPos ); + } - break; + break; - default: - break; - } -*/ + default: + break; + } + */ // team no longer indicates species/race. NPC_class should be used to identify certain npc types - vec3_t effectPos, right; - switch(ent->client->NPC_class) - { + vec3_t effectPos, right; + switch (ent->client->NPC_class) { case CLASS_MOUSE: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 20; - G_PlayEffect( "env/small_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mouse/misc/death1" ); + G_PlayEffect("env/small_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mouse/misc/death1"); break; case CLASS_PROBE: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] += 50; - G_PlayEffect( "probeexplosion1", effectPos ); + G_PlayEffect("probeexplosion1", effectPos); break; case CLASS_ATST: - AngleVectors( ent->currentAngles, NULL, right, NULL ); - VectorMA( ent->currentOrigin, 20, right, effectPos ); + AngleVectors(ent->currentAngles, NULL, right, NULL); + VectorMA(ent->currentOrigin, 20, right, effectPos); effectPos[2] += 180; - G_PlayEffect( "droidexplosion1", effectPos ); - VectorMA( effectPos, -40, right, effectPos ); - G_PlayEffect( "droidexplosion1", effectPos ); + G_PlayEffect("droidexplosion1", effectPos); + VectorMA(effectPos, -40, right, effectPos); + G_PlayEffect("droidexplosion1", effectPos); break; case CLASS_SEEKER: case CLASS_REMOTE: - G_PlayEffect( "env/small_explode", ent->currentOrigin ); + G_PlayEffect("env/small_explode", ent->currentOrigin); break; case CLASS_GONK: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 5; -// statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); - G_SoundOnEnt( ent, CHAN_AUTO, va("sound/chars/gonk/misc/death%d.wav",Q_irand( 1, 3 )) ); - G_PlayEffect( "env/med_explode", effectPos ); + // statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); + G_SoundOnEnt(ent, CHAN_AUTO, va("sound/chars/gonk/misc/death%d.wav", Q_irand(1, 3))); + G_PlayEffect("env/med_explode", effectPos); break; // should list all remaining droids here, hope I didn't miss any case CLASS_R2D2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffect( "env/med_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("env/med_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; - case CLASS_PROTOCOL://?? + case CLASS_PROTOCOL: //?? case CLASS_R5D2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffect( "env/med_explode", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("env/med_explode", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; case CLASS_MARK2: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo" ); + G_PlayEffect("droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark2/misc/mark2_explo"); break; case CLASS_INTERROGATOR: - VectorCopy( ent->currentOrigin, effectPos ); + VectorCopy(ent->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/interrogator/misc/int_droid_explo" ); + G_PlayEffect("droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/interrogator/misc/int_droid_explo"); break; case CLASS_MARK1: - AngleVectors( ent->currentAngles, NULL, right, NULL ); - VectorMA( ent->currentOrigin, 10, right, effectPos ); + AngleVectors(ent->currentAngles, NULL, right, NULL); + VectorMA(ent->currentOrigin, 10, right, effectPos); effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffect( "droidexplosion1", effectPos ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffect( "droidexplosion1", effectPos ); - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/mark1/misc/mark1_explo" ); + G_PlayEffect("droidexplosion1", effectPos); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffect("droidexplosion1", effectPos); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffect("droidexplosion1", effectPos); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/mark1/misc/mark1_explo"); break; case CLASS_SENTRY: - G_SoundOnEnt( ent, CHAN_AUTO, "sound/chars/sentry/misc/sentry_explo" ); - VectorCopy( ent->currentOrigin, effectPos ); - G_PlayEffect( "env/med_explode", effectPos ); + G_SoundOnEnt(ent, CHAN_AUTO, "sound/chars/sentry/misc/sentry_explo"); + VectorCopy(ent->currentOrigin, effectPos); + G_PlayEffect("env/med_explode", effectPos); break; default: break; - } - } -void G_SetMissionStatusText( gentity_t *attacker, int mod ) -{ - if ( statusTextIndex >= 0 ) - { +void G_SetMissionStatusText(gentity_t *attacker, int mod) { + if (statusTextIndex >= 0) { return; } - if ( mod == MOD_FALLING ) - {//fell to your death + if (mod == MOD_FALLING) { // fell to your death statusTextIndex = STAT_WATCHYOURSTEP; - } - else if ( mod == MOD_CRUSH ) - {//crushed + } else if (mod == MOD_CRUSH) { // crushed statusTextIndex = STAT_JUDGEMENTMUCHDESIRED; - } - else if ( attacker && Q_stricmp( "trigger_hurt", attacker->classname ) == 0 ) - {//Killed by something that should have been clearly dangerous -// statusTextIndex = Q_irand( IGT_JUDGEMENTDESIRED, IGT_JUDGEMENTMUCHDESIRED ); + } else if (attacker && Q_stricmp("trigger_hurt", attacker->classname) == 0) { // Killed by something that should have been clearly dangerous + // statusTextIndex = Q_irand( IGT_JUDGEMENTDESIRED, IGT_JUDGEMENTMUCHDESIRED ); statusTextIndex = STAT_JUDGEMENTMUCHDESIRED; - } - else if ( attacker && attacker->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) - {//killed by a teammate + } else if (attacker && attacker->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER) { // killed by a teammate statusTextIndex = STAT_INSUBORDINATION; } } -void G_MakeTeamVulnerable( void ) -{ +void G_MakeTeamVulnerable(void) { int i, newhealth; gentity_t *ent; gentity_t *self = &g_entities[0]; - if ( !self->client ) - { + if (!self->client) { return; } -// for ( i = 0; i < globals.num_entities ; i++, ent++) - for ( i = 0; i < globals.num_entities ; i++) - { - if(!PInUse(i)) + // for ( i = 0; i < globals.num_entities ; i++, ent++) + for (i = 0; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if ( !ent->inuse ) -// { -// continue; -// } -// if ( !ent ) -// { -// continue; -// } - ent=&g_entities[i]; - if ( !ent->client ) - { + // if ( !ent->inuse ) + // { + // continue; + // } + // if ( !ent ) + // { + // continue; + // } + ent = &g_entities[i]; + if (!ent->client) { continue; } - if ( ent->client->playerTeam != TEAM_PLAYER ) - { + if (ent->client->playerTeam != TEAM_PLAYER) { continue; } - if ( !(ent->flags&FL_UNDYING) ) - { + if (!(ent->flags & FL_UNDYING)) { continue; } ent->flags &= ~FL_UNDYING; - newhealth = Q_irand( 5, 40 ); - if ( ent->health > newhealth ) - { + newhealth = Q_irand(5, 40); + if (ent->health > newhealth) { ent->health = newhealth; } } } -void G_StartMatrixEffect( gentity_t *ent, qboolean falling = qfalse, int length = 1000 ) -{//FIXME: only do this if no other enemies around? - if ( g_timescale->value != 1.0 ) - {//already in some slow-mo mode +void G_StartMatrixEffect(gentity_t *ent, qboolean falling = qfalse, int length = 1000) { // FIXME: only do this if no other enemies around? + if (g_timescale->value != 1.0) { // already in some slow-mo mode return; } - gentity_t *matrix = G_Spawn(); - if ( matrix ) - { - G_SetOrigin( matrix, ent->currentOrigin ); - gi.linkentity( matrix ); + gentity_t *matrix = G_Spawn(); + if (matrix) { + G_SetOrigin(matrix, ent->currentOrigin); + gi.linkentity(matrix); matrix->s.otherEntityNum = ent->s.number; matrix->e_clThinkFunc = clThinkF_CG_MatrixEffect; matrix->s.eType = ET_THINKER; - matrix->svFlags |= SVF_BROADCAST;// Broadcast to all clients + matrix->svFlags |= SVF_BROADCAST; // Broadcast to all clients matrix->s.time = level.time; matrix->s.eventParm = length; matrix->e_ThinkFunc = thinkF_G_FreeEntity; matrix->nextthink = level.time + length + 500; - if ( falling ) - {//no timescale or vert bob + if (falling) { // no timescale or vert bob matrix->s.weapon = 1; } } } -qboolean G_JediInRoom( vec3_t from ) -{ +qboolean G_JediInRoom(vec3_t from) { gentity_t *ent; int i; -// for ( i = 1, ent = &g_entities[1]; i < globals.num_entities; i++, ent++ ) - for ( i = 1; i < globals.num_entities; i++) - { - if(!PInUse(i)) + // for ( i = 1, ent = &g_entities[1]; i < globals.num_entities; i++, ent++ ) + for (i = 1; i < globals.num_entities; i++) { + if (!PInUse(i)) continue; -// if ( !ent->inuse ) -// { -// continue; -// } -// if ( !ent ) -// { -// continue; -// } + // if ( !ent->inuse ) + // { + // continue; + // } + // if ( !ent ) + // { + // continue; + // } ent = &g_entities[i]; - if ( !ent->NPC ) - { + if (!ent->NPC) { continue; } - if ( ent->health <= 0 ) - { + if (ent->health <= 0) { continue; } - if ( ent->s.eFlags&EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( ent->s.weapon != WP_SABER ) - { + if (ent->s.weapon != WP_SABER) { continue; } - if ( !gi.inPVS( ent->currentOrigin, from ) ) - { + if (!gi.inPVS(ent->currentOrigin, from)) { continue; } return qtrue; @@ -807,416 +713,290 @@ qboolean G_JediInRoom( vec3_t from ) return qfalse; } -qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ) -{ +qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod) { qboolean dismember = qfalse; *hitLoc = HL_NONE; - if ( !surfName || !surfName[0] ) - { + if (!surfName || !surfName[0]) { return qfalse; } - if( !ent->client ) - { + if (!ent->client) { return qfalse; } - if ( ent->client - && ( ent->client->NPC_class == CLASS_R2D2 - || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_GONK - || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_SEEKER - || ent->client->NPC_class == CLASS_INTERROGATOR - || ent->client->NPC_class == CLASS_SENTRY - || ent->client->NPC_class == CLASS_PROBE ) ) - {//we don't care about per-surface hit-locations or dismemberment for these guys + if (ent->client && (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_GONK || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_SEEKER || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_SENTRY || + ent->client->NPC_class == CLASS_PROBE)) { // we don't care about per-surface hit-locations or dismemberment for these guys return qfalse; } - if ( ent->client && (ent->client->NPC_class == CLASS_ATST) ) - { - //FIXME: almost impossible to hit these... perhaps we should + if (ent->client && (ent->client->NPC_class == CLASS_ATST)) { + // FIXME: almost impossible to hit these... perhaps we should // check for splashDamage and do radius damage to these parts? // Or, if we ever get bbox G2 traces, that may fix it, too - if (!Q_stricmp("head_light_blaster_cann",surfName)) - { + if (!Q_stricmp("head_light_blaster_cann", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("head_concussion_charger",surfName)) - { + } else if (!Q_stricmp("head_concussion_charger", surfName)) { *hitLoc = HL_ARM_RT; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK1) ) - { - if (!Q_stricmp("l_arm",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK1)) { + if (!Q_stricmp("l_arm", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("r_arm",surfName)) - { + } else if (!Q_stricmp("r_arm", surfName)) { *hitLoc = HL_ARM_RT; - } - else if (!Q_stricmp("torso_front",surfName)) - { + } else if (!Q_stricmp("torso_front", surfName)) { *hitLoc = HL_CHEST; - } - else if (!Q_stricmp("torso_tube1",surfName)) - { + } else if (!Q_stricmp("torso_tube1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_tube2",surfName)) - { + } else if (!Q_stricmp("torso_tube2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_tube3",surfName)) - { + } else if (!Q_stricmp("torso_tube3", surfName)) { *hitLoc = HL_GENERIC3; - } - else if (!Q_stricmp("torso_tube4",surfName)) - { + } else if (!Q_stricmp("torso_tube4", surfName)) { *hitLoc = HL_GENERIC4; - } - else if (!Q_stricmp("torso_tube5",surfName)) - { + } else if (!Q_stricmp("torso_tube5", surfName)) { *hitLoc = HL_GENERIC5; - } - else if (!Q_stricmp("torso_tube6",surfName)) - { + } else if (!Q_stricmp("torso_tube6", surfName)) { *hitLoc = HL_GENERIC6; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK2) ) - { - if (!Q_stricmp("torso_canister1",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK2)) { + if (!Q_stricmp("torso_canister1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_canister2",surfName)) - { + } else if (!Q_stricmp("torso_canister2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_canister3",surfName)) - { + } else if (!Q_stricmp("torso_canister3", surfName)) { *hitLoc = HL_GENERIC3; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_GALAKMECH) ) - { - if (!Q_stricmp("torso_antenna",surfName)||!Q_stricmp("torso_antenna_base",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_GALAKMECH)) { + if (!Q_stricmp("torso_antenna", surfName) || !Q_stricmp("torso_antenna_base", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_shield_off",surfName)) - { + } else if (!Q_stricmp("torso_shield_off", surfName)) { *hitLoc = HL_GENERIC2; - } - else - { + } else { *hitLoc = HL_CHEST; } - return(qfalse); + return (qfalse); } - //FIXME: check the hitLoc and hitDir against the cap tag for the place - //where the split will be- if the hit dir is roughly perpendicular to - //the direction of the cap, then the split is allowed, otherwise we - //hit it at the wrong angle and should not dismember... - int actualTime = (cg.time?cg.time:level.time); - if ( !Q_strncmp( "hips", surfName, 4 ) ) - {//FIXME: test properly for legs + // FIXME: check the hitLoc and hitDir against the cap tag for the place + // where the split will be- if the hit dir is roughly perpendicular to + // the direction of the cap, then the split is allowed, otherwise we + // hit it at the wrong angle and should not dismember... + int actualTime = (cg.time ? cg.time : level.time); + if (!Q_strncmp("hips", surfName, 4)) { // FIXME: test properly for legs *hitLoc = HL_WAIST; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->kneeLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->kneeLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->kneeLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->kneeLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_LT; } } - if (*hitLoc == HL_WAIST) - { - if (ent->kneeRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->kneeRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (*hitLoc == HL_WAIST) { + if (ent->kneeRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->kneeRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_RT; } } } } - } - else if ( !Q_strncmp( "torso", surfName, 5 ) ) - { - if ( !ent->client ) - { + } else if (!Q_strncmp("torso", surfName, 5)) { + if (!ent->client) { *hitLoc = HL_CHEST; - } - else - { - vec3_t t_fwd, t_rt, t_up, dirToImpact; + } else { + vec3_t t_fwd, t_rt, t_up, dirToImpact; float frontSide, rightSide, upSide; - AngleVectors( ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up ); - VectorSubtract( point, ent->client->renderInfo.torsoPoint, dirToImpact ); - frontSide = DotProduct( t_fwd, dirToImpact ); - rightSide = DotProduct( t_rt, dirToImpact ); - upSide = DotProduct( t_up, dirToImpact ); - if ( upSide < -10 ) - {//hit at waist + AngleVectors(ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up); + VectorSubtract(point, ent->client->renderInfo.torsoPoint, dirToImpact); + frontSide = DotProduct(t_fwd, dirToImpact); + rightSide = DotProduct(t_rt, dirToImpact); + upSide = DotProduct(t_up, dirToImpact); + if (upSide < -10) { // hit at waist *hitLoc = HL_WAIST; - } - else - {//hit on upper torso - if ( rightSide > 4 ) - { + } else { // hit on upper torso + if (rightSide > 4) { *hitLoc = HL_ARM_RT; - } - else if ( rightSide < -4 ) - { + } else if (rightSide < -4) { *hitLoc = HL_ARM_LT; - } - else if ( rightSide > 2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide > 2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_RT; - } - else - { + } else { *hitLoc = HL_BACK_RT; } - } - else if ( rightSide < -2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide < -2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_LT; - } - else - { + } else { *hitLoc = HL_BACK_LT; } - } - else if ( upSide > -3 && mod == MOD_SABER ) - { + } else if (upSide > -3 && mod == MOD_SABER) { *hitLoc = HL_HEAD; - } - else if ( frontSide > 0 ) - { + } else if (frontSide > 0) { *hitLoc = HL_CHEST; - } - else - { + } else { *hitLoc = HL_BACK; } } } - } - else if ( !Q_strncmp( "head", surfName, 4 ) ) - { + } else if (!Q_strncmp("head", surfName, 4)) { *hitLoc = HL_HEAD; - } - else if ( !Q_strncmp( "r_arm", surfName, 5 ) ) - { + } else if (!Q_strncmp("r_arm", surfName, 5)) { *hitLoc = HL_ARM_RT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->handRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->handRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->handRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_RT; } } } - } - else if ( !Q_strncmp( "l_arm", surfName, 5 ) ) - { + } else if (!Q_strncmp("l_arm", surfName, 5)) { *hitLoc = HL_ARM_LT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->handLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->handLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->handLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_LT; } } } - } - else if ( !Q_strncmp( "r_leg", surfName, 5 ) ) - { + } else if (!Q_strncmp("r_leg", surfName, 5)) { *hitLoc = HL_LEG_RT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->footRBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->footRBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->footRBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->footRBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_RT; } } } - } - else if ( !Q_strncmp( "l_leg", surfName, 5 ) ) - { + } else if (!Q_strncmp("l_leg", surfName, 5)) { *hitLoc = HL_LEG_LT; - if ( ent->client != NULL && ent->ghoul2.size() ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - if (ent->footLBolt>=0) - { - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, ent->footLBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2.size()) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + if (ent->footLBolt >= 0) { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->footLBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_LT; } } } - } - else if ( !Q_strncmp( "r_hand", surfName, 6 ) || !Q_strncmp( "w_", surfName, 2 ) ) - {//right hand or weapon + } else if (!Q_strncmp("r_hand", surfName, 6) || !Q_strncmp("w_", surfName, 2)) { // right hand or weapon *hitLoc = HL_HAND_RT; - } - else if ( !Q_strncmp( "l_hand", surfName, 6 ) ) - { + } else if (!Q_strncmp("l_hand", surfName, 6)) { *hitLoc = HL_HAND_LT; } #ifdef _DEBUG - else - { - Com_Printf( "ERROR: surface %s does not belong to any hitLocation!!!\n", surfName ); + else { + Com_Printf("ERROR: surface %s does not belong to any hitLocation!!!\n", surfName); } #endif //_DEBUG - if ( g_saberRealisticCombat->integer ) - { + if (g_saberRealisticCombat->integer) { dismember = qtrue; - } - else if ( g_dismemberment->integer >= 11381138 || !ent->client->dismembered ) - { - if ( ent->client && ent->client->NPC_class == CLASS_PROTOCOL ) - { + } else if (g_dismemberment->integer >= 11381138 || !ent->client->dismembered) { + if (ent->client && ent->client->NPC_class == CLASS_PROTOCOL) { dismember = qtrue; - } - else if ( dir && (dir[0] || dir[1] || dir[2]) && - bladeDir && (bladeDir[0] || bladeDir[1] || bladeDir[2]) ) - {//we care about direction (presumably for dismemberment) - if ( g_dismemberProbabilities->value<=0.0f||G_Dismemberable( ent, *hitLoc ) ) - {//either we don't care about probabilties or the probability let us continue + } else if (dir && (dir[0] || dir[1] || dir[2]) && bladeDir && + (bladeDir[0] || bladeDir[1] || bladeDir[2])) { // we care about direction (presumably for dismemberment) + if (g_dismemberProbabilities->value <= 0.0f || + G_Dismemberable(ent, *hitLoc)) { // either we don't care about probabilties or the probability let us continue char *tagName = NULL; - float aoa = 0.5f; - //dir must be roughly perpendicular to the hitLoc's cap bolt - switch ( *hitLoc ) - { - case HL_LEG_RT: - tagName = "*hips_cap_r_leg"; - break; - case HL_LEG_LT: - tagName = "*hips_cap_l_leg"; - break; - case HL_WAIST: - tagName = "*hips_cap_torso"; - aoa = 0.25f; - break; - case HL_CHEST_RT: - case HL_ARM_RT: - case HL_BACK_LT: - tagName = "*torso_cap_r_arm"; - break; - case HL_CHEST_LT: - case HL_ARM_LT: - case HL_BACK_RT: - tagName = "*torso_cap_l_arm"; - break; - case HL_HAND_RT: - tagName = "*r_arm_cap_r_hand"; - break; - case HL_HAND_LT: - tagName = "*l_arm_cap_l_hand"; - break; - case HL_HEAD: - tagName = "*torso_cap_head"; - aoa = 0.25f; - break; - case HL_CHEST: - case HL_BACK: - case HL_FOOT_RT: - case HL_FOOT_LT: - default: - //no dismemberment possible with these, so no checks needed - break; + float aoa = 0.5f; + // dir must be roughly perpendicular to the hitLoc's cap bolt + switch (*hitLoc) { + case HL_LEG_RT: + tagName = "*hips_cap_r_leg"; + break; + case HL_LEG_LT: + tagName = "*hips_cap_l_leg"; + break; + case HL_WAIST: + tagName = "*hips_cap_torso"; + aoa = 0.25f; + break; + case HL_CHEST_RT: + case HL_ARM_RT: + case HL_BACK_LT: + tagName = "*torso_cap_r_arm"; + break; + case HL_CHEST_LT: + case HL_ARM_LT: + case HL_BACK_RT: + tagName = "*torso_cap_l_arm"; + break; + case HL_HAND_RT: + tagName = "*r_arm_cap_r_hand"; + break; + case HL_HAND_LT: + tagName = "*l_arm_cap_l_hand"; + break; + case HL_HEAD: + tagName = "*torso_cap_head"; + aoa = 0.25f; + break; + case HL_CHEST: + case HL_BACK: + case HL_FOOT_RT: + case HL_FOOT_LT: + default: + // no dismemberment possible with these, so no checks needed + break; } - if ( tagName ) - { - int tagBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], tagName ); - if ( tagBolt != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, tagDir, angles; - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, tagBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, tagOrg ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, tagDir ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//hit close - float dot = DotProduct( dir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//hit roughly perpendicular - dot = DotProduct( bladeDir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//blade was roughly perpendicular + if (tagName) { + int tagBolt = gi.G2API_AddBolt(&ent->ghoul2[ent->playerModel], tagName); + if (tagBolt != -1) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, tagDir, angles; + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, tagBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, + ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, tagOrg); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, tagDir); + if (DistanceSquared(point, tagOrg) < 256) { // hit close + float dot = DotProduct(dir, tagDir); + if (dot < aoa && dot > -aoa) { // hit roughly perpendicular + dot = DotProduct(bladeDir, tagDir); + if (dot < aoa && dot > -aoa) { // blade was roughly perpendicular dismember = qtrue; } } @@ -1229,286 +1009,225 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit return dismember; } -int G_GetHitLocation ( gentity_t *target, vec3_t ppoint ) -{ - vec3_t point, point_dir; - vec3_t forward, right, up; - vec3_t tangles, tcenter; - float udot, fdot, rdot; - int Vertical, Forward, Lateral; - int HitLoc; - -//get target forward, right and up - if(target->client) - {//ignore player's pitch and roll +int G_GetHitLocation(gentity_t *target, vec3_t ppoint) { + vec3_t point, point_dir; + vec3_t forward, right, up; + vec3_t tangles, tcenter; + float udot, fdot, rdot; + int Vertical, Forward, Lateral; + int HitLoc; + + // get target forward, right and up + if (target->client) { // ignore player's pitch and roll VectorSet(tangles, 0, target->currentAngles[YAW], 0); } AngleVectors(tangles, forward, right, up); -//get center of target + // get center of target VectorAdd(target->absmin, target->absmax, tcenter); VectorScale(tcenter, 0.5, tcenter); -//get impact point - if(ppoint && !VectorCompare(ppoint, vec3_origin)) - { + // get impact point + if (ppoint && !VectorCompare(ppoint, vec3_origin)) { VectorCopy(ppoint, point); - } - else - { + } else { return HL_NONE; } -/* -//get impact dir - if(pdir && !VectorCompare(pdir, vec3_origin)) - { - VectorCopy(pdir, dir); - } - else - { - return; - } + /* + //get impact dir + if(pdir && !VectorCompare(pdir, vec3_origin)) + { + VectorCopy(pdir, dir); + } + else + { + return; + } -//put point at controlled distance from center - VectorSubtract(point, tcenter, tempvec); - tempvec[2] = 0; - hdist = VectorLength(tempvec); + //put point at controlled distance from center + VectorSubtract(point, tcenter, tempvec); + tempvec[2] = 0; + hdist = VectorLength(tempvec); - VectorMA(point, hdist - tradius, dir, point); - //now a point on the surface of a cylinder with a radius of tradius -*/ + VectorMA(point, hdist - tradius, dir, point); + //now a point on the surface of a cylinder with a radius of tradius + */ VectorSubtract(point, tcenter, point_dir); VectorNormalize(point_dir); - //Get bottom to top (Vertical) position index + // Get bottom to top (Vertical) position index udot = DotProduct(up, point_dir); - if(udot>.800) + if (udot > .800) Vertical = 4; - else if(udot>.400) + else if (udot > .400) Vertical = 3; - else if(udot>-.333) + else if (udot > -.333) Vertical = 2; - else if(udot>-.666) + else if (udot > -.666) Vertical = 1; else Vertical = 0; - //Get back to front (Forward) position index + // Get back to front (Forward) position index fdot = DotProduct(forward, point_dir); - if(fdot>.666) + if (fdot > .666) Forward = 4; - else if(fdot>.333) + else if (fdot > .333) Forward = 3; - else if(fdot>-.333) + else if (fdot > -.333) Forward = 2; - else if(fdot>-.666) + else if (fdot > -.666) Forward = 1; else Forward = 0; - //Get left to right (Lateral) position index + // Get left to right (Lateral) position index rdot = DotProduct(right, point_dir); - if(rdot>.666) + if (rdot > .666) Lateral = 4; - else if(rdot>.333) + else if (rdot > .333) Lateral = 3; - else if(rdot>-.333) + else if (rdot > -.333) Lateral = 2; - else if(rdot>-.666) + else if (rdot > -.666) Lateral = 1; else Lateral = 0; HitLoc = Vertical * 25 + Forward * 5 + Lateral; - if(HitLoc <= 10) - {//feet - if ( rdot > 0 ) - { + if (HitLoc <= 10) { // feet + if (rdot > 0) { return HL_FOOT_RT; - } - else - { + } else { return HL_FOOT_LT; } - } - else if(HitLoc <= 50) - {//legs - if ( rdot > 0 ) - { + } else if (HitLoc <= 50) { // legs + if (rdot > 0) { return HL_LEG_RT; - } - else - { + } else { return HL_LEG_LT; } - } - else if ( HitLoc == 56||HitLoc == 60||HitLoc == 61||HitLoc == 65||HitLoc == 66||HitLoc == 70 ) - {//hands - if ( rdot > 0 ) - { + } else if (HitLoc == 56 || HitLoc == 60 || HitLoc == 61 || HitLoc == 65 || HitLoc == 66 || HitLoc == 70) { // hands + if (rdot > 0) { return HL_HAND_RT; - } - else - { + } else { return HL_HAND_LT; } - } - else if ( HitLoc == 83||HitLoc == 87||HitLoc == 88||HitLoc == 92||HitLoc == 93||HitLoc == 97 ) - {//arms - if ( rdot > 0 ) - { + } else if (HitLoc == 83 || HitLoc == 87 || HitLoc == 88 || HitLoc == 92 || HitLoc == 93 || HitLoc == 97) { // arms + if (rdot > 0) { return HL_ARM_RT; - } - else - { + } else { return HL_ARM_LT; } - } - else if((HitLoc >= 107 && HitLoc <= 109)|| - (HitLoc >= 112 && HitLoc <= 114)|| - (HitLoc >= 117 && HitLoc <= 119)) - {//head + } else if ((HitLoc >= 107 && HitLoc <= 109) || (HitLoc >= 112 && HitLoc <= 114) || (HitLoc >= 117 && HitLoc <= 119)) { // head return HL_HEAD; - } - else - { - if ( udot < 0.3 ) - { + } else { + if (udot < 0.3) { return HL_WAIST; - } - else if ( fdot < 0 ) - { - if ( rdot > 0.4 ) - { + } else if (fdot < 0) { + if (rdot > 0.4) { return HL_BACK_RT; - } - else if ( rdot < -0.4 ) - { + } else if (rdot < -0.4) { return HL_BACK_LT; - } - else - { + } else { return HL_BACK; } - } - else - { - if ( rdot > 0.3 ) - { + } else { + if (rdot > 0.3) { return HL_CHEST_RT; - } - else if ( rdot < -0.3 ) - { + } else if (rdot < -0.3) { return HL_CHEST_LT; - } - else - { + } else { return HL_CHEST; } } } - //return HL_NONE; + // return HL_NONE; } -int G_PickPainAnim( gentity_t *self, vec3_t point, int damage, int hitLoc = HL_NONE ) -{ - if ( hitLoc == HL_NONE ) - { - hitLoc = G_GetHitLocation( self, point ); +int G_PickPainAnim(gentity_t *self, vec3_t point, int damage, int hitLoc = HL_NONE) { + if (hitLoc == HL_NONE) { + hitLoc = G_GetHitLocation(self, point); } - switch( hitLoc ) - { + switch (hitLoc) { case HL_FOOT_RT: return BOTH_PAIN12; - //PAIN12 = right foot + // PAIN12 = right foot break; case HL_FOOT_LT: return -1; break; case HL_LEG_RT: - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { return BOTH_PAIN11; - } - else - { + } else { return BOTH_PAIN13; } - //PAIN11 = twitch right leg - //PAIN13 = right knee + // PAIN11 = twitch right leg + // PAIN13 = right knee break; case HL_LEG_LT: return BOTH_PAIN14; - //PAIN14 = twitch left leg + // PAIN14 = twitch left leg break; case HL_BACK_RT: return BOTH_PAIN7; - //PAIN7 = med left shoulder + // PAIN7 = med left shoulder break; case HL_BACK_LT: - return Q_irand( BOTH_PAIN15, BOTH_PAIN16 ); - //PAIN15 = med right shoulder - //PAIN16 = twitch right shoulder + return Q_irand(BOTH_PAIN15, BOTH_PAIN16); + // PAIN15 = med right shoulder + // PAIN16 = twitch right shoulder break; case HL_BACK: - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { return BOTH_PAIN1; - } - else - { + } else { return BOTH_PAIN5; } - //PAIN1 = back - //PAIN5 = same as 1 + // PAIN1 = back + // PAIN5 = same as 1 break; case HL_CHEST_RT: return BOTH_PAIN3; - //PAIN3 = long, right shoulder + // PAIN3 = long, right shoulder break; case HL_CHEST_LT: return BOTH_PAIN2; - //PAIN2 = long, left shoulder + // PAIN2 = long, left shoulder break; case HL_WAIST: case HL_CHEST: - if ( !Q_irand( 0, 3 ) ) - { + if (!Q_irand(0, 3)) { return BOTH_PAIN6; - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 2)) { return BOTH_PAIN8; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { return BOTH_PAIN17; - } - else - { + } else { return BOTH_PAIN19; } - //PAIN6 = gut - //PAIN8 = chest - //PAIN17 = twitch crotch - //PAIN19 = med crotch + // PAIN6 = gut + // PAIN8 = chest + // PAIN17 = twitch crotch + // PAIN19 = med crotch break; case HL_ARM_RT: case HL_HAND_RT: return BOTH_PAIN9; - //PAIN9 = twitch right arm + // PAIN9 = twitch right arm break; case HL_ARM_LT: case HL_HAND_LT: return BOTH_PAIN10; - //PAIN10 = twitch left arm + // PAIN10 = twitch left arm break; case HL_HEAD: return BOTH_PAIN4; - //PAIN4 = head + // PAIN4 = head break; default: return -1; @@ -1516,259 +1235,208 @@ int G_PickPainAnim( gentity_t *self, vec3_t point, int damage, int hitLoc = HL_N } } -extern void G_BounceMissile( gentity_t *ent, trace_t *trace ); -void LimbThink( gentity_t *ent ) -{//FIXME: just use object thinking? - vec3_t origin; - trace_t tr; +extern void G_BounceMissile(gentity_t *ent, trace_t *trace); +void LimbThink(gentity_t *ent) { // FIXME: just use object thinking? + vec3_t origin; + trace_t tr; ent->nextthink = level.time + FRAMETIME; - if ( ent->enemy ) - {//alert people that I am a piece of one of their friends - AddSightEvent( ent->enemy, ent->currentOrigin, 384, AEL_DISCOVERED ); + if (ent->enemy) { // alert people that I am a piece of one of their friends + AddSightEvent(ent->enemy, ent->currentOrigin, 384, AEL_DISCOVERED); } - if ( ent->s.pos.trType == TR_STATIONARY ) - {//stopped - if ( level.time > ent->s.apos.trTime + ent->s.apos.trDuration ) - { - ent->nextthink = level.time + Q_irand( 5000, 15000 ); + if (ent->s.pos.trType == TR_STATIONARY) { // stopped + if (level.time > ent->s.apos.trTime + ent->s.apos.trDuration) { + ent->nextthink = level.time + Q_irand(5000, 15000); ent->e_ThinkFunc = thinkF_G_FreeEntity; - //FIXME: these keep drawing for a frame or so after being freed?! See them lerp to origin of world... - } - else - { - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + // FIXME: these keep drawing for a frame or so after being freed?! See them lerp to origin of world... + } else { + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); } return; } // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); // get current angles - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_NOCOLLIDE, 0); - VectorCopy( tr.endpos, ent->currentOrigin ); - if ( tr.startsolid ) - { + VectorCopy(tr.endpos, ent->currentOrigin); + if (tr.startsolid) { tr.fraction = 0; } + gi.linkentity(ent); - gi.linkentity( ent ); - - if ( tr.fraction != 1 ) - { - G_BounceMissile( ent, &tr ); - if ( ent->s.pos.trType == TR_STATIONARY ) - {//stopped, stop spinning - //lay flat - //pitch - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - vec3_t flatAngles; - if ( ent->s.angles2[0] == -1 ) - {//any pitch is okay + if (tr.fraction != 1) { + G_BounceMissile(ent, &tr); + if (ent->s.pos.trType == TR_STATIONARY) { // stopped, stop spinning + // lay flat + // pitch + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + vec3_t flatAngles; + if (ent->s.angles2[0] == -1) { // any pitch is okay flatAngles[0] = ent->currentAngles[0]; - } - else - {//lay flat - if ( ent->owner - && ent->owner->client - && ent->owner->client->NPC_class == CLASS_PROTOCOL - && ent->count == BOTH_DISMEMBER_TORSO1 ) - { - if ( ent->currentAngles[0] > 0 || ent->currentAngles[0] < -180 ) - { + } else { // lay flat + if (ent->owner && ent->owner->client && ent->owner->client->NPC_class == CLASS_PROTOCOL && ent->count == BOTH_DISMEMBER_TORSO1) { + if (ent->currentAngles[0] > 0 || ent->currentAngles[0] < -180) { flatAngles[0] = -90; - } - else - { + } else { flatAngles[0] = 90; } - } - else - { - if ( ent->currentAngles[0] > 90 || ent->currentAngles[0] < -90 ) - { + } else { + if (ent->currentAngles[0] > 90 || ent->currentAngles[0] < -90) { flatAngles[0] = 180; - } - else - { + } else { flatAngles[0] = 0; } } } - //yaw + // yaw flatAngles[1] = ent->currentAngles[1]; - //roll - if ( ent->s.angles2[2] == -1 ) - {//any roll is okay + // roll + if (ent->s.angles2[2] == -1) { // any roll is okay flatAngles[2] = ent->currentAngles[2]; - } - else - { - if ( ent->currentAngles[2] > 90 || ent->currentAngles[2] < -90 ) - { + } else { + if (ent->currentAngles[2] > 90 || ent->currentAngles[2] < -90) { flatAngles[2] = 180; - } - else - { + } else { flatAngles[2] = 0; } } - VectorSubtract( flatAngles, ent->s.apos.trBase, ent->s.apos.trDelta ); - for ( int i = 0; i < 3; i++ ) - { - ent->s.apos.trDelta[i] = AngleNormalize180( ent->s.apos.trDelta[i] ); + VectorSubtract(flatAngles, ent->s.apos.trBase, ent->s.apos.trDelta); + for (int i = 0; i < 3; i++) { + ent->s.apos.trDelta[i] = AngleNormalize180(ent->s.apos.trDelta[i]); } ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 1000; ent->s.apos.trType = TR_LINEAR_STOP; - //VectorClear( ent->s.apos.trDelta ); + // VectorClear( ent->s.apos.trDelta ); } } } -float hitLocHealthPercentage[HL_MAX] = -{ - 0.0f, //HL_NONE = 0, - 0.05f, //HL_FOOT_RT, - 0.05f, //HL_FOOT_LT, - 0.20f, //HL_LEG_RT, - 0.20f, //HL_LEG_LT, - 0.30f, //HL_WAIST, - 0.15f, //HL_BACK_RT, - 0.15f, //HL_BACK_LT, - 0.30f, //HL_BACK, - 0.15f, //HL_CHEST_RT, - 0.15f, //HL_CHEST_LT, - 0.30f, //HL_CHEST, - 0.05f, //HL_ARM_RT, - 0.05f, //HL_ARM_LT, - 0.01f, //HL_HAND_RT, - 0.01f, //HL_HAND_LT, - 0.10f, //HL_HEAD - 0.0f, //HL_GENERIC1, - 0.0f, //HL_GENERIC2, - 0.0f, //HL_GENERIC3, - 0.0f, //HL_GENERIC4, - 0.0f, //HL_GENERIC5, - 0.0f //HL_GENERIC6 +float hitLocHealthPercentage[HL_MAX] = { + 0.0f, // HL_NONE = 0, + 0.05f, // HL_FOOT_RT, + 0.05f, // HL_FOOT_LT, + 0.20f, // HL_LEG_RT, + 0.20f, // HL_LEG_LT, + 0.30f, // HL_WAIST, + 0.15f, // HL_BACK_RT, + 0.15f, // HL_BACK_LT, + 0.30f, // HL_BACK, + 0.15f, // HL_CHEST_RT, + 0.15f, // HL_CHEST_LT, + 0.30f, // HL_CHEST, + 0.05f, // HL_ARM_RT, + 0.05f, // HL_ARM_LT, + 0.01f, // HL_HAND_RT, + 0.01f, // HL_HAND_LT, + 0.10f, // HL_HEAD + 0.0f, // HL_GENERIC1, + 0.0f, // HL_GENERIC2, + 0.0f, // HL_GENERIC3, + 0.0f, // HL_GENERIC4, + 0.0f, // HL_GENERIC5, + 0.0f // HL_GENERIC6 }; -char *hitLocName[HL_MAX] = -{ - "none", //HL_NONE = 0, - "right foot", //HL_FOOT_RT, - "left foot", //HL_FOOT_LT, - "right leg", //HL_LEG_RT, - "left leg", //HL_LEG_LT, - "waist", //HL_WAIST, - "back right shoulder", //HL_BACK_RT, - "back left shoulder", //HL_BACK_LT, - "back", //HL_BACK, - "front right shouler", //HL_CHEST_RT, - "front left shoulder", //HL_CHEST_LT, - "chest", //HL_CHEST, - "right arm", //HL_ARM_RT, - "left arm", //HL_ARM_LT, - "right hand", //HL_HAND_RT, - "left hand", //HL_HAND_LT, - "head", //HL_HEAD - "generic1", //HL_GENERIC1, - "generic2", //HL_GENERIC2, - "generic3", //HL_GENERIC3, - "generic4", //HL_GENERIC4, - "generic5", //HL_GENERIC5, - "generic6" //HL_GENERIC6 +char *hitLocName[HL_MAX] = { + "none", // HL_NONE = 0, + "right foot", // HL_FOOT_RT, + "left foot", // HL_FOOT_LT, + "right leg", // HL_LEG_RT, + "left leg", // HL_LEG_LT, + "waist", // HL_WAIST, + "back right shoulder", // HL_BACK_RT, + "back left shoulder", // HL_BACK_LT, + "back", // HL_BACK, + "front right shouler", // HL_CHEST_RT, + "front left shoulder", // HL_CHEST_LT, + "chest", // HL_CHEST, + "right arm", // HL_ARM_RT, + "left arm", // HL_ARM_LT, + "right hand", // HL_HAND_RT, + "left hand", // HL_HAND_LT, + "head", // HL_HEAD + "generic1", // HL_GENERIC1, + "generic2", // HL_GENERIC2, + "generic3", // HL_GENERIC3, + "generic4", // HL_GENERIC4, + "generic5", // HL_GENERIC5, + "generic6" // HL_GENERIC6 }; -qboolean G_LimbLost( gentity_t *ent, int hitLoc ) -{ - switch ( hitLoc ) - { +qboolean G_LimbLost(gentity_t *ent, int hitLoc) { + switch (hitLoc) { case HL_FOOT_RT: - if ( ent->locationDamage[HL_FOOT_RT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_FOOT_RT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_LEG_RT: - //NOTE: feet fall through - if ( ent->locationDamage[HL_LEG_RT] >= Q3_INFINITE ) - { + // NOTE: feet fall through + if (ent->locationDamage[HL_LEG_RT] >= Q3_INFINITE) { return qtrue; } return qfalse; case HL_FOOT_LT: - if ( ent->locationDamage[HL_FOOT_LT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_FOOT_LT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_LEG_LT: - //NOTE: feet fall through - if ( ent->locationDamage[HL_LEG_LT] >= Q3_INFINITE ) - { + // NOTE: feet fall through + if (ent->locationDamage[HL_LEG_LT] >= Q3_INFINITE) { return qtrue; } return qfalse; case HL_HAND_LT: - if ( ent->locationDamage[HL_HAND_LT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HAND_LT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_ARM_LT: case HL_CHEST_LT: case HL_BACK_RT: - //NOTE: hand falls through - if ( ent->locationDamage[HL_ARM_LT] >= Q3_INFINITE - || ent->locationDamage[HL_CHEST_LT] >= Q3_INFINITE - || ent->locationDamage[HL_BACK_RT] >= Q3_INFINITE - || ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: hand falls through + if (ent->locationDamage[HL_ARM_LT] >= Q3_INFINITE || ent->locationDamage[HL_CHEST_LT] >= Q3_INFINITE || + ent->locationDamage[HL_BACK_RT] >= Q3_INFINITE || ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; case HL_HAND_RT: - if ( ent->locationDamage[HL_HAND_RT] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HAND_RT] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_ARM_RT: case HL_CHEST_RT: case HL_BACK_LT: - //NOTE: hand falls through - if ( ent->locationDamage[HL_ARM_RT] >= Q3_INFINITE - || ent->locationDamage[HL_CHEST_RT] >= Q3_INFINITE - || ent->locationDamage[HL_BACK_LT] >= Q3_INFINITE - || ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: hand falls through + if (ent->locationDamage[HL_ARM_RT] >= Q3_INFINITE || ent->locationDamage[HL_CHEST_RT] >= Q3_INFINITE || + ent->locationDamage[HL_BACK_LT] >= Q3_INFINITE || ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; case HL_HEAD: - if ( ent->locationDamage[HL_HEAD] >= Q3_INFINITE ) - { + if (ent->locationDamage[HL_HEAD] >= Q3_INFINITE) { return qtrue; } - //NOTE: falls through + // NOTE: falls through case HL_WAIST: - //NOTE: head falls through - if ( ent->locationDamage[HL_WAIST] >= Q3_INFINITE ) - { + // NOTE: head falls through + if (ent->locationDamage[HL_WAIST] >= Q3_INFINITE) { return qtrue; } return qfalse; @@ -1777,41 +1445,35 @@ qboolean G_LimbLost( gentity_t *ent, int hitLoc ) } } -static qboolean G_Dismember( gentity_t *ent, vec3_t point, - const char *limbBone, const char *rotateBone, char *limbName, - char *limbCapName, char *stubCapName, char *limbTagName, char *stubTagName, - int limbAnim, float limbRollBase, float limbPitchBase, - int damage, int hitLoc ) -{ +static qboolean G_Dismember(gentity_t *ent, vec3_t point, const char *limbBone, const char *rotateBone, char *limbName, char *limbCapName, char *stubCapName, + char *limbTagName, char *stubTagName, int limbAnim, float limbRollBase, float limbPitchBase, int damage, int hitLoc) { int newBolt; - vec3_t dir, newPoint, limbAngles = {0,ent->client->ps.legsYaw,0}; + vec3_t dir, newPoint, limbAngles = {0, ent->client->ps.legsYaw, 0}; gentity_t *limb; - trace_t trace; + trace_t trace; - //make sure this limb hasn't been lopped off already! - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], limbName ) ) - {//already lost this limb + // make sure this limb hasn't been lopped off already! + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], limbName)) { // already lost this limb return qfalse; } - //NOTE: only reason I have this next part is because G2API_GetSurfaceRenderStatus is *not* working - if ( G_LimbLost( ent, hitLoc ) ) - {//already lost this limb + // NOTE: only reason I have this next part is because G2API_GetSurfaceRenderStatus is *not* working + if (G_LimbLost(ent, hitLoc)) { // already lost this limb return qfalse; } - //FIXME: when timescale is high, can sometimes cut off a surf that includes a surf that was already cut off -//0) create a limb ent - VectorCopy( point, newPoint ); + // FIXME: when timescale is high, can sometimes cut off a surf that includes a surf that was already cut off + // 0) create a limb ent + VectorCopy(point, newPoint); newPoint[2] += 6; limb = G_Spawn(); - G_SetOrigin( limb, newPoint ); - //VectorCopy(ent->currentAngles,limbAngles); - //G_SetAngles( limb, ent->currentAngles ); - VectorCopy( newPoint, limb->s.pos.trBase ); -//1) copy the g2 instance of the victim into the limb - gi.G2API_CopyGhoul2Instance( ent->ghoul2, limb->ghoul2, -1 ); - limb->playerModel = 0;//assumption! + G_SetOrigin(limb, newPoint); + // VectorCopy(ent->currentAngles,limbAngles); + // G_SetAngles( limb, ent->currentAngles ); + VectorCopy(newPoint, limb->s.pos.trBase); + // 1) copy the g2 instance of the victim into the limb + gi.G2API_CopyGhoul2Instance(ent->ghoul2, limb->ghoul2, -1); + limb->playerModel = 0; // assumption! limb->craniumBone = ent->craniumBone; limb->cervicalBone = ent->cervicalBone; limb->thoracicBone = ent->thoracicBone; @@ -1819,13 +1481,11 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, limb->lowerLumbarBone = ent->lowerLumbarBone; limb->hipsBone = ent->hipsBone; limb->rootBone = ent->rootBone; -//2) set the root surf on the limb - if ( limbTagName ) - {//add smoke to cap tag - newBolt = gi.G2API_AddBolt( &limb->ghoul2[limb->playerModel], limbTagName ); - if ( newBolt != -1 ) - { - G_PlayEffect( "blaster/smoke_bolton", limb->playerModel, newBolt, limb->s.number); + // 2) set the root surf on the limb + if (limbTagName) { // add smoke to cap tag + newBolt = gi.G2API_AddBolt(&limb->ghoul2[limb->playerModel], limbTagName); + if (newBolt != -1) { + G_PlayEffect("blaster/smoke_bolton", limb->playerModel, newBolt, limb->s.number); } } /* @@ -1836,9 +1496,9 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "upper_lumbar" ); } */ - gi.G2API_StopBoneAnimIndex( &limb->ghoul2[limb->playerModel], limb->hipsBone ); + gi.G2API_StopBoneAnimIndex(&limb->ghoul2[limb->playerModel], limb->hipsBone); - gi.G2API_SetRootSurface( limb->ghoul2, limb->playerModel, limbName ); + gi.G2API_SetRootSurface(limb->ghoul2, limb->playerModel, limbName); /* if ( limbBone && hitLoc != HL_WAIST ) {//play the dismember anim on the limb? @@ -1850,39 +1510,33 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time); } */ - if ( limbBone && hitLoc == HL_WAIST && ent->client->NPC_class == CLASS_PROTOCOL ) - {//play the dismember anim on the limb? - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "model_root" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "motion" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "pelvis" ); - gi.G2API_StopBoneAnim( &limb->ghoul2[limb->playerModel], "upper_lumbar" ); - //FIXME: screws up origin + if (limbBone && hitLoc == HL_WAIST && ent->client->NPC_class == CLASS_PROTOCOL) { // play the dismember anim on the limb? + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "model_root"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "motion"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "pelvis"); + gi.G2API_StopBoneAnim(&limb->ghoul2[limb->playerModel], "upper_lumbar"); + // FIXME: screws up origin animation_t *animations = level.knownAnimFileSets[ent->client->clientInfo.animFileIndex].animations; - //play the proper dismember anim on the limb + // play the proper dismember anim on the limb gi.G2API_SetBoneAnim(&limb->ghoul2[limb->playerModel], 0, animations[limbAnim].firstFrame, - animations[limbAnim].numFrames + animations[limbAnim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, -1, -1 ); - } - if ( rotateBone ) - { - gi.G2API_SetNewOrigin( &limb->ghoul2[0], gi.G2API_AddBolt( &limb->ghoul2[0], rotateBone ) ); - - //now let's try to position the limb at the *exact* right spot - int newBolt = gi.G2API_AddBolt( &ent->ghoul2[0], rotateBone ); - if ( newBolt != -1 ) - { - int actualTime = (cg.time?cg.time:level.time); - mdxaBone_t boltMatrix; - vec3_t angles; - - VectorSet( angles, 0, ent->currentAngles[YAW], 0 ); - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, newBolt, - &boltMatrix, angles, ent->currentOrigin, - actualTime, NULL, ent->s.modelScale ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, limb->s.origin ); - G_SetOrigin( limb, limb->s.origin ); - VectorCopy( limb->s.origin, limb->s.pos.trBase ); - //angles, too + animations[limbAnim].numFrames + animations[limbAnim].firstFrame, BONE_ANIM_OVERRIDE_FREEZE, 1, cg.time, -1, -1); + } + if (rotateBone) { + gi.G2API_SetNewOrigin(&limb->ghoul2[0], gi.G2API_AddBolt(&limb->ghoul2[0], rotateBone)); + + // now let's try to position the limb at the *exact* right spot + int newBolt = gi.G2API_AddBolt(&ent->ghoul2[0], rotateBone); + if (newBolt != -1) { + int actualTime = (cg.time ? cg.time : level.time); + mdxaBone_t boltMatrix; + vec3_t angles; + + VectorSet(angles, 0, ent->currentAngles[YAW], 0); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, newBolt, &boltMatrix, angles, ent->currentOrigin, actualTime, NULL, ent->s.modelScale); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, limb->s.origin); + G_SetOrigin(limb, limb->s.origin); + VectorCopy(limb->s.origin, limb->s.pos.trBase); + // angles, too /* vec3_t limbF, limbR; newBolt = gi.G2API_AddBolt( &ent->ghoul2[0], limbBone ); @@ -1901,16 +1555,14 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, */ } } - if ( limbCapName ) - {//turn on caps - gi.G2API_SetSurfaceOnOff( &limb->ghoul2[limb->playerModel], limbCapName, 0 ); + if (limbCapName) { // turn on caps + gi.G2API_SetSurfaceOnOff(&limb->ghoul2[limb->playerModel], limbCapName, 0); } -//3) turn off w/descendants that surf in original model -//NOTE: we actually change the ent's stuff on the cgame side so that there is no 50ms lag -// also, if the limb was going to start in solid, we can delete it and return - if ( stubTagName ) - {//add smoke to cap surf, spawn effect - limb->target = G_NewString( stubTagName ); + // 3) turn off w/descendants that surf in original model + // NOTE: we actually change the ent's stuff on the cgame side so that there is no 50ms lag + // also, if the limb was going to start in solid, we can delete it and return + if (stubTagName) { // add smoke to cap surf, spawn effect + limb->target = G_NewString(stubTagName); /* newBolt = gi.G2API_AddBolt( &ent->ghoul2[ent->playerModel], stubTagName ); if ( newBolt != -1 ) @@ -1919,64 +1571,50 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, } */ } - if ( limbName ) - { - limb->target2 = G_NewString( limbName ); - //gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], limbName, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS + if (limbName) { + limb->target2 = G_NewString(limbName); + // gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], limbName, 0x00000100 );//G2SURFACEFLAG_NODESCENDANTS } - if ( stubCapName ) - {//turn on caps - limb->target3 = G_NewString( stubCapName ); - //gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], stubCapName, 0 ); + if (stubCapName) { // turn on caps + limb->target3 = G_NewString(stubCapName); + // gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], stubCapName, 0 ); } limb->count = limbAnim; -// + // limb->s.radius = 60; -//4) toss the limb away + // 4) toss the limb away limb->classname = "limb"; limb->owner = ent; limb->enemy = ent->enemy; - if ( ent->weaponModel >= 0 && !ent->client->ps.saberInFlight ) - {//the corpse hasn't dropped their weapon - if ( limbAnim == BOTH_DISMEMBER_RARM || limbAnim == BOTH_DISMEMBER_TORSO1 )//&& ent->s.weapon == WP_SABER && ent->weaponModel != -1 ) - {//FIXME: is this first check needed with this lower one? - if ( !gi.G2API_GetSurfaceRenderStatus( &limb->ghoul2[0], "r_hand" ) ) - {//only copy the weapon over if the right hand is actually on this limb... - //copy it to limb - if ( ent->s.weapon != WP_NONE ) - {//only if they actually still have a weapon + if (ent->weaponModel >= 0 && !ent->client->ps.saberInFlight) { // the corpse hasn't dropped their weapon + if (limbAnim == BOTH_DISMEMBER_RARM || limbAnim == BOTH_DISMEMBER_TORSO1) //&& ent->s.weapon == WP_SABER && ent->weaponModel != -1 ) + { // FIXME: is this first check needed with this lower one? + if (!gi.G2API_GetSurfaceRenderStatus(&limb->ghoul2[0], "r_hand")) { // only copy the weapon over if the right hand is actually on this limb... + // copy it to limb + if (ent->s.weapon != WP_NONE) { // only if they actually still have a weapon limb->s.weapon = ent->s.weapon; limb->weaponModel = ent->weaponModel; - }//else - weaponModel is not -1 but don't have a weapon? Oops, somehow G2 model wasn't removed? - //remove it on owner - if ( ent->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel ); + } // else - weaponModel is not -1 but don't have a weapon? Oops, somehow G2 model wasn't removed? + // remove it on owner + if (ent->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(ent->ghoul2, ent->weaponModel); ent->weaponModel = -1; } - if ( ent->client->ps.saberEntityNum != ENTITYNUM_NONE && ent->client->ps.saberEntityNum > 0 ) - {//remove the owner ent's saber model and entity - if ( g_entities[ent->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[ent->client->ps.saberEntityNum] ); + if (ent->client->ps.saberEntityNum != ENTITYNUM_NONE && ent->client->ps.saberEntityNum > 0) { // remove the owner ent's saber model and entity + if (g_entities[ent->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[ent->client->ps.saberEntityNum]); } ent->client->ps.saberEntityNum = ENTITYNUM_NONE; } - } - else - { - if ( ent->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( limb->ghoul2, ent->weaponModel ); + } else { + if (ent->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(limb->ghoul2, ent->weaponModel); limb->weaponModel = -1; } } - } - else - { - if ( ent->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( limb->ghoul2, ent->weaponModel ); + } else { + if (ent->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(limb->ghoul2, ent->weaponModel); limb->weaponModel = -1; } } @@ -1985,47 +1623,44 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, limb->e_clThinkFunc = clThinkF_CG_Limb; limb->e_ThinkFunc = thinkF_LimbThink; limb->nextthink = level.time + FRAMETIME; - gi.linkentity( limb ); - //need size, contents, clipmask + gi.linkentity(limb); + // need size, contents, clipmask limb->svFlags = SVF_USE_CURRENT_ORIGIN; limb->clipmask = MASK_SOLID; limb->contents = CONTENTS_CORPSE; - VectorSet( limb->mins, -3.0f, -3.0f, -6.0f ); - VectorSet( limb->maxs, 3.0f, 3.0f, 6.0f ); + VectorSet(limb->mins, -3.0f, -3.0f, -6.0f); + VectorSet(limb->maxs, 3.0f, 3.0f, 6.0f); - //make sure it doesn't start in solid - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid ) - { + // make sure it doesn't start in solid + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] -= limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid ) - { + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0); + if (trace.startsolid) { limb->s.pos.trBase[2] += limb->mins[2]; - gi.trace( &trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid ) - {//stuck? don't remove - G_FreeEntity( limb ); + gi.trace(&trace, limb->s.pos.trBase, limb->mins, limb->maxs, limb->s.pos.trBase, limb->s.number, limb->clipmask, G2_NOCOLLIDE, 0); + if (trace.startsolid) { // stuck? don't remove + G_FreeEntity(limb); return qfalse; } } } - //move it - VectorCopy( limb->s.pos.trBase, limb->currentOrigin ); - gi.linkentity( limb ); + // move it + VectorCopy(limb->s.pos.trBase, limb->currentOrigin); + gi.linkentity(limb); - limb->s.eType = ET_THINKER;//ET_GENERAL; + limb->s.eType = ET_THINKER; // ET_GENERAL; limb->physicsBounce = 0.2f; limb->s.pos.trType = TR_GRAVITY; - limb->s.pos.trTime = level.time; // move a bit on the very first frame - VectorSubtract( point, ent->currentOrigin, dir ); - VectorNormalize( dir ); - //no trDuration? - //spin it - //new way- try to preserve the exact angle and position of the limb as it was when attached - VectorSet( limb->s.angles2, limbPitchBase, 0, limbRollBase ); - VectorCopy( limbAngles, limb->s.apos.trBase ); + limb->s.pos.trTime = level.time; // move a bit on the very first frame + VectorSubtract(point, ent->currentOrigin, dir); + VectorNormalize(dir); + // no trDuration? + // spin it + // new way- try to preserve the exact angle and position of the limb as it was when attached + VectorSet(limb->s.angles2, limbPitchBase, 0, limbRollBase); + VectorCopy(limbAngles, limb->s.apos.trBase); /* //old way- just set an angle... limb->s.apos.trBase[0] += limbPitchBase; @@ -2034,61 +1669,50 @@ static qboolean G_Dismember( gentity_t *ent, vec3_t point, */ limb->s.apos.trTime = level.time; limb->s.apos.trType = TR_LINEAR; - VectorClear( limb->s.apos.trDelta ); + VectorClear(limb->s.apos.trDelta); - if ( hitLoc == HL_HAND_RT || hitLoc == HL_HAND_LT ) - {//hands fly farther - VectorMA( ent->client->ps.velocity, 200, dir, limb->s.pos.trDelta ); - //make it bounce some + if (hitLoc == HL_HAND_RT || hitLoc == HL_HAND_LT) { // hands fly farther + VectorMA(ent->client->ps.velocity, 200, dir, limb->s.pos.trDelta); + // make it bounce some limb->s.eFlags |= EF_BOUNCE_HALF; - limb->s.apos.trDelta[0] = Q_irand( -300, 300 ); - limb->s.apos.trDelta[1] = Q_irand( -800, 800 ); - } - else if ( limbAnim == BOTH_DISMEMBER_HEAD1 - || limbAnim == BOTH_DISMEMBER_LARM - || limbAnim == BOTH_DISMEMBER_RARM ) - {//head and arms don't fly as far + limb->s.apos.trDelta[0] = Q_irand(-300, 300); + limb->s.apos.trDelta[1] = Q_irand(-800, 800); + } else if (limbAnim == BOTH_DISMEMBER_HEAD1 || limbAnim == BOTH_DISMEMBER_LARM || limbAnim == BOTH_DISMEMBER_RARM) { // head and arms don't fly as far limb->s.eFlags |= EF_BOUNCE_SHRAPNEL; - VectorMA( ent->client->ps.velocity, 150, dir, limb->s.pos.trDelta ); - limb->s.apos.trDelta[0] = Q_irand( -200, 200 ); - limb->s.apos.trDelta[1] = Q_irand( -400, 400 ); - } - else// if ( limbAnim == BOTH_DISMEMBER_TORSO1 || limbAnim == BOTH_DISMEMBER_LLEG || limbAnim == BOTH_DISMEMBER_RLEG ) - {//everything else just kinda falls off + VectorMA(ent->client->ps.velocity, 150, dir, limb->s.pos.trDelta); + limb->s.apos.trDelta[0] = Q_irand(-200, 200); + limb->s.apos.trDelta[1] = Q_irand(-400, 400); + } else // if ( limbAnim == BOTH_DISMEMBER_TORSO1 || limbAnim == BOTH_DISMEMBER_LLEG || limbAnim == BOTH_DISMEMBER_RLEG ) + { // everything else just kinda falls off limb->s.eFlags |= EF_BOUNCE_SHRAPNEL; - VectorMA( ent->client->ps.velocity, 100, dir, limb->s.pos.trDelta ); - limb->s.apos.trDelta[0] = Q_irand( -100, 100 ); - limb->s.apos.trDelta[1] = Q_irand( -200, 200 ); + VectorMA(ent->client->ps.velocity, 100, dir, limb->s.pos.trDelta); + limb->s.apos.trDelta[0] = Q_irand(-100, 100); + limb->s.apos.trDelta[1] = Q_irand(-200, 200); } - //roll? No, doesn't work... - //limb->s.apos.trDelta[2] = Q_irand( -300, 300 );//FIXME: this scales it down @ 80% and does weird stuff in timescale != 1.0 - //limb->s.apos.trDelta[2] = limbRoll; + // roll? No, doesn't work... + // limb->s.apos.trDelta[2] = Q_irand( -300, 300 );//FIXME: this scales it down @ 80% and does weird stuff in timescale != 1.0 + // limb->s.apos.trDelta[2] = limbRoll; - //preserve scale so giants don't have tiny limbs - VectorCopy( ent->s.modelScale, limb->s.modelScale ); + // preserve scale so giants don't have tiny limbs + VectorCopy(ent->s.modelScale, limb->s.modelScale); - //mark ent as dismembered - ent->locationDamage[hitLoc] = Q3_INFINITE;//mark this limb as gone + // mark ent as dismembered + ent->locationDamage[hitLoc] = Q3_INFINITE; // mark this limb as gone ent->client->dismembered = qtrue; return qtrue; } -static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) -{ - if ( self->client->dismembered ) - {//cannot dismember me right now +static qboolean G_Dismemberable(gentity_t *self, int hitLoc) { + if (self->client->dismembered) { // cannot dismember me right now return qfalse; } - if ( g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer ) - { - if ( g_dismemberProbabilities->value > 0.0f ) - {//use the ent-specific dismemberProbabilities + if (g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer) { + if (g_dismemberProbabilities->value > 0.0f) { // use the ent-specific dismemberProbabilities float dismemberProb = 0; // check which part of the body it is. Then check the npc's probability // of that body part coming off, if it doesn't pass, return out. - switch ( hitLoc ) - { + switch (hitLoc) { case HL_LEG_RT: case HL_LEG_LT: dismemberProb = self->client->dismemberProbLegs; @@ -2116,8 +1740,9 @@ static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) break; } - //check probability of this happening on this npc - if ( floor((Q_flrand( 1, 100 )*g_dismemberProbabilities->value)) > dismemberProb*2.0f )//probabilities seemed really really low, had to crank them up + // check probability of this happening on this npc + if (floor((Q_flrand(1, 100) * g_dismemberProbabilities->value)) > + dismemberProb * 2.0f) // probabilities seemed really really low, had to crank them up { return qfalse; } @@ -2126,18 +1751,15 @@ static qboolean G_Dismemberable( gentity_t *self, int hitLoc ) return qtrue; } -static qboolean G_Dismemberable2( gentity_t *self, int hitLoc ) -{ - if ( self->client->dismembered ) - {//cannot dismember me right now +static qboolean G_Dismemberable2(gentity_t *self, int hitLoc) { + if (self->client->dismembered) { // cannot dismember me right now return qfalse; } - if ( g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer ) - { - if ( g_dismemberProbabilities->value <= 0.0f ) - {//add the passed-in damage to the locationDamage array, check to see if it's taken enough damage to actually dismember - if ( self->locationDamage[hitLoc] < (self->client->ps.stats[STAT_MAX_HEALTH]*hitLocHealthPercentage[hitLoc]) ) - {//this location has not taken enough damage to dismember + if (g_dismemberment->integer < 11381138 && !g_saberRealisticCombat->integer) { + if (g_dismemberProbabilities->value <= + 0.0f) { // add the passed-in damage to the locationDamage array, check to see if it's taken enough damage to actually dismember + if (self->locationDamage[hitLoc] < + (self->client->ps.stats[STAT_MAX_HEALTH] * hitLocHealthPercentage[hitLoc])) { // this location has not taken enough damage to dismember return qfalse; } } @@ -2145,36 +1767,34 @@ static qboolean G_Dismemberable2( gentity_t *self, int hitLoc ) return qtrue; } -extern qboolean G_StandardHumanoid( const char *modelName ); -qboolean G_DoDismemberment( gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse ) -{ -extern cvar_t *g_iscensored; +extern qboolean G_StandardHumanoid(const char *modelName); +qboolean G_DoDismemberment(gentity_t *self, vec3_t point, int mod, int damage, int hitLoc, qboolean force = qfalse) { + extern cvar_t *g_iscensored; // dismemberment -- FIXME: should have a check for how long npc has been dead so people can't // continue to dismember a dead body long after it's been dead - //NOTE that you can only cut one thing off unless the dismemberment is >= 11381138 + // NOTE that you can only cut one thing off unless the dismemberment is >= 11381138 #ifdef GERMAN_CENSORED - if ( 0 ) //germany == censorship + if (0) // germany == censorship #else - if ( !g_iscensored->integer && ( g_dismemberment->integer || g_saberRealisticCombat->integer > 1 ) && mod == MOD_SABER )//only lightsaber + if (!g_iscensored->integer && (g_dismemberment->integer || g_saberRealisticCombat->integer > 1) && mod == MOD_SABER) // only lightsaber #endif - {//FIXME: don't do strcmps here - if ( G_StandardHumanoid( self->NPC_type ) - && (force||g_dismemberProbabilities->value>0.0f||G_Dismemberable2( self, hitLoc )) ) - {//either it's a forced dismemberment or we're using probabilities (which are checked before this) or we've done enough damage to this location - //FIXME: check the hitLoc and hitDir against the cap tag for the place - //where the split will be- if the hit dir is roughly perpendicular to - //the direction of the cap, then the split is allowed, otherwise we - //hit it at the wrong angle and should not dismember... - char *limbBone = NULL, *rotateBone = NULL, *limbName = NULL, *limbCapName = NULL, *stubCapName = NULL, *limbTagName = NULL, *stubTagName = NULL; - int anim = -1; - float limbRollBase = 0, limbPitchBase = 0; + { // FIXME: don't do strcmps here + if (G_StandardHumanoid(self->NPC_type) && (force || g_dismemberProbabilities->value > 0.0f || + G_Dismemberable2(self, hitLoc))) { // either it's a forced dismemberment or we're using probabilities (which + // are checked before this) or we've done enough damage to this location + // FIXME: check the hitLoc and hitDir against the cap tag for the place + // where the split will be- if the hit dir is roughly perpendicular to + // the direction of the cap, then the split is allowed, otherwise we + // hit it at the wrong angle and should not dismember... + char *limbBone = NULL, *rotateBone = NULL, *limbName = NULL, *limbCapName = NULL, *stubCapName = NULL, *limbTagName = NULL, *stubTagName = NULL; + int anim = -1; + float limbRollBase = 0, limbPitchBase = 0; qboolean doDismemberment = qfalse; - switch( hitLoc )//self->hitLoc + switch (hitLoc) // self->hitLoc { case HL_LEG_RT: - if ( g_dismemberment->integer > 1 ) - { + if (g_dismemberment->integer > 1) { doDismemberment = qtrue; limbBone = "rtibia"; rotateBone = "rtalus"; @@ -2189,8 +1809,7 @@ extern cvar_t *g_iscensored; } break; case HL_LEG_LT: - if ( g_dismemberment->integer > 1 ) - { + if (g_dismemberment->integer > 1) { doDismemberment = qtrue; limbBone = "ltibia"; rotateBone = "ltalus"; @@ -2205,9 +1824,7 @@ extern cvar_t *g_iscensored; } break; case HL_WAIST: - if ( g_dismemberment->integer > 2 && - (!self->s.number||!self->message)) - { + if (g_dismemberment->integer > 2 && (!self->s.number || !self->message)) { doDismemberment = qtrue; limbBone = "pelvis"; rotateBone = "thoracic"; @@ -2224,8 +1841,7 @@ extern cvar_t *g_iscensored; case HL_CHEST_RT: case HL_ARM_RT: case HL_BACK_RT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "rhumerus"; rotateBone = "rradius"; @@ -2242,9 +1858,7 @@ extern cvar_t *g_iscensored; case HL_CHEST_LT: case HL_ARM_LT: case HL_BACK_LT: - if ( g_dismemberment->integer && - (!self->s.number||!self->message)) - {//either the player or not carrying a key on my arm + if (g_dismemberment->integer && (!self->s.number || !self->message)) { // either the player or not carrying a key on my arm doDismemberment = qtrue; limbBone = "lhumerus"; rotateBone = "lradius"; @@ -2259,8 +1873,7 @@ extern cvar_t *g_iscensored; } break; case HL_HAND_RT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "rradiusX"; rotateBone = "rhand"; @@ -2275,8 +1888,7 @@ extern cvar_t *g_iscensored; } break; case HL_HAND_LT: - if ( g_dismemberment->integer ) - { + if (g_dismemberment->integer) { doDismemberment = qtrue; limbBone = "lradiusX"; rotateBone = "lhand"; @@ -2291,8 +1903,7 @@ extern cvar_t *g_iscensored; } break; case HL_HEAD: - if ( g_dismemberment->integer > 2 ) - { + if (g_dismemberment->integer > 2) { doDismemberment = qtrue; limbBone = "cervical"; rotateBone = "cranium"; @@ -2313,550 +1924,364 @@ extern cvar_t *g_iscensored; default: break; } - if ( doDismemberment ) - { - return G_Dismember( self, point, limbBone, rotateBone, limbName, - limbCapName, stubCapName, limbTagName, stubTagName, - anim, limbRollBase, limbPitchBase, damage, hitLoc ); + if (doDismemberment) { + return G_Dismember(self, point, limbBone, rotateBone, limbName, limbCapName, stubCapName, limbTagName, stubTagName, anim, limbRollBase, + limbPitchBase, damage, hitLoc); } } } return qfalse; } -static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{ +static int G_CheckSpecialDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc) { int deathAnim = -1; - if ( PM_InRoll( &self->client->ps ) ) - { - deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll - } - else if ( PM_FlippingAnim( self->client->ps.legsAnim ) ) - { - deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip - } - else if ( PM_SpinningAnim( self->client->ps.legsAnim ) ) - { + if (PM_InRoll(&self->client->ps)) { + deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll + } else if (PM_FlippingAnim(self->client->ps.legsAnim)) { + deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip + } else if (PM_SpinningAnim(self->client->ps.legsAnim)) { float yawDiff = AngleNormalize180(AngleNormalize180(self->client->renderInfo.torsoAngles[YAW]) - AngleNormalize180(self->client->ps.viewangles[YAW])); - if ( yawDiff > 135 || yawDiff < -135 ) - { - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( yawDiff < -60 ) - { - deathAnim = BOTH_DEATH_SPIN_90_R; //# Death anim when facing 90 degrees right - } - else if ( yawDiff > 60 ) - { - deathAnim = BOTH_DEATH_SPIN_90_L; //# Death anim when facing 90 degrees left - } - } - else if ( PM_InKnockDown( &self->client->ps ) ) - {//since these happen a lot, let's handle them case by case - int animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim ); - switch ( self->client->ps.legsAnim ) - { + if (yawDiff > 135 || yawDiff < -135) { + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (yawDiff < -60) { + deathAnim = BOTH_DEATH_SPIN_90_R; //# Death anim when facing 90 degrees right + } else if (yawDiff > 60) { + deathAnim = BOTH_DEATH_SPIN_90_L; //# Death anim when facing 90 degrees left + } + } else if (PM_InKnockDown(&self->client->ps)) { // since these happen a lot, let's handle them case by case + int animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.legsAnim); + switch (self->client->ps.legsAnim) { case BOTH_KNOCKDOWN1: - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 100) { // on our way down + if (self->client->ps.legsAnimTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_KNOCKDOWN2: - if ( animLength - self->client->ps.legsAnimTimer > 700 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 700) { // on our way down + if (self->client->ps.legsAnimTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_KNOCKDOWN3: - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 1300 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 100) { // on our way down + if (self->client->ps.legsAnimTimer > 1300) { // still partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_KNOCKDOWN4: - if ( animLength - self->client->ps.legsAnimTimer > 300 ) - {//on our way down - if ( self->client->ps.legsAnimTimer > 350 ) - {//still partially up + if (animLength - self->client->ps.legsAnimTimer > 300) { // on our way down + if (self->client->ps.legsAnimTimer > 350) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } - } - else - {//crouch death + } else { // crouch death vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } } break; case BOTH_KNOCKDOWN5: - if ( self->client->ps.legsAnimTimer < 750 ) - {//flat + if (self->client->ps.legsAnimTimer < 750) { // flat deathAnim = BOTH_DEATH_LYING_DN; } break; case BOTH_GETUP1: - if ( self->client->ps.legsAnimTimer < 350 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 350) { // standing up + } else if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 450 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 450) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP2: - if ( self->client->ps.legsAnimTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 850 ) - {//crouching + if (self->client->ps.legsAnimTimer < 150) { // standing up + } else if (self->client->ps.legsAnimTimer < 850) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 500 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 500) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP3: - if ( self->client->ps.legsAnimTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 600 ) - {//crouching + if (self->client->ps.legsAnimTimer < 250) { // standing up + } else if (self->client->ps.legsAnimTimer < 600) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP4: - if ( self->client->ps.legsAnimTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 600 ) - {//crouching + if (self->client->ps.legsAnimTimer < 250) { // standing up + } else if (self->client->ps.legsAnimTimer < 600) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 850 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 850) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP5: - if ( self->client->ps.legsAnimTimer > 850 ) - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 1500 ) - {//partially up + if (self->client->ps.legsAnimTimer > 850) { // lying down + if (animLength - self->client->ps.legsAnimTimer > 1500) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP_CROUCH_B1: - if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 400 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 400) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP_CROUCH_F1: - if ( self->client->ps.legsAnimTimer < 800 ) - {//crouching + if (self->client->ps.legsAnimTimer < 800) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_B1: - if ( self->client->ps.legsAnimTimer < 325 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 725 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsAnimTimer < 900 ) - {//crouching + if (self->client->ps.legsAnimTimer < 325) { // standing up + } else if (self->client->ps.legsAnimTimer < 725) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsAnimTimer < 900) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 50 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B2: - if ( self->client->ps.legsAnimTimer < 575 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 875 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsAnimTimer < 900 ) - {//crouching + if (self->client->ps.legsAnimTimer < 575) { // standing up + } else if (self->client->ps.legsAnimTimer < 875) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsAnimTimer < 900) { // crouching vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - //partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B3: - if ( self->client->ps.legsAnimTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 775 ) - {//flipping - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - //partially up + if (self->client->ps.legsAnimTimer < 150) { // standing up + } else if (self->client->ps.legsAnimTimer < 775) { // flipping + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B4: - if ( self->client->ps.legsAnimTimer < 325 ) - {//standing up - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 150 ) - {//partially up + if (self->client->ps.legsAnimTimer < 325) { // standing up + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B5: - if ( self->client->ps.legsAnimTimer < 550 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 1025 ) - {//kicking up - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 50 ) - {//partially up + if (self->client->ps.legsAnimTimer < 550) { // standing up + } else if (self->client->ps.legsAnimTimer < 1025) { // kicking up + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B6: - if ( self->client->ps.legsAnimTimer < 225 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 425 ) - {//crouching up + if (self->client->ps.legsAnimTimer < 225) { // standing up + } else if (self->client->ps.legsAnimTimer < 425) { // crouching up vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else if ( self->client->ps.legsAnimTimer < 825 ) - {//flipping up - deathAnim = BOTH_DEATHFORWARD3; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 225 ) - {//partially up + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } + } else if (self->client->ps.legsAnimTimer < 825) { // flipping up + deathAnim = BOTH_DEATHFORWARD3; // backflip + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_F1: - if ( self->client->ps.legsAnimTimer < 275 ) - {//standing up - } - else if ( self->client->ps.legsAnimTimer < 750 ) - {//flipping + if (self->client->ps.legsAnimTimer < 275) { // standing up + } else if (self->client->ps.legsAnimTimer < 750) { // flipping deathAnim = BOTH_DEATH14; - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 100 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 100) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_F2: - if ( self->client->ps.legsAnimTimer < 1200 ) - {//standing - } - else - {//lying down - if ( animLength - self->client->ps.legsAnimTimer > 225 ) - {//partially up + if (self->client->ps.legsAnimTimer < 1200) { // standing + } else { // lying down + if (animLength - self->client->ps.legsAnimTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; } - } - else if ( PM_InOnGroundAnim( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back - } - else - { - deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front + } else if (PM_InOnGroundAnim(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back + } else { + deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front } - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - { + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -200 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -200) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } } return deathAnim; } -extern qboolean PM_FinishedCurrentLegsAnim( gentity_t *self ); -static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{//FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called +extern qboolean PM_FinishedCurrentLegsAnim(gentity_t *self); +static int G_PickDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, + int hitLoc) { // FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called int deathAnim = -1; - if ( hitLoc == HL_NONE ) - { - hitLoc = G_GetHitLocation( self, point );//self->hitLoc + if (hitLoc == HL_NONE) { + hitLoc = G_GetHitLocation(self, point); // self->hitLoc } - //dead flops...if you are already playing a death animation, I guess it can just return directly - switch( self->client->ps.legsAnim ) - { - case BOTH_DEATH1: //# First Death anim + // dead flops...if you are already playing a death animation, I guess it can just return directly + switch (self->client->ps.legsAnim) { + case BOTH_DEATH1: //# First Death anim case BOTH_DEAD1: - case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH2: //# Second Death anim case BOTH_DEAD2: - case BOTH_DEATH8: //# + case BOTH_DEATH8: //# case BOTH_DEAD8: - case BOTH_DEATH13: //# + case BOTH_DEATH13: //# case BOTH_DEAD13: - case BOTH_DEATH14: //# + case BOTH_DEATH14: //# case BOTH_DEAD14: - case BOTH_DEATH16: //# + case BOTH_DEATH16: //# case BOTH_DEAD16: - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose return -2; break; /* @@ -2873,12 +2298,12 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, deathAnim = BOTH_DEADFLOP2; break; */ - case BOTH_DEATH10: //# + case BOTH_DEATH10: //# case BOTH_DEAD10: - case BOTH_DEATH15: //# + case BOTH_DEATH15: //# case BOTH_DEAD15: - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose return -2; break; /* @@ -2893,57 +2318,57 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, break; */ case BOTH_DEADFLOP1: - //deathAnim = BOTH_DEADFLOP1; + // deathAnim = BOTH_DEADFLOP1; return -2; break; - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD9: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_DEAD20: //# - case BOTH_DEAD21: //# - case BOTH_DEAD22: //# - case BOTH_DEAD23: //# - case BOTH_DEAD24: //# - case BOTH_DEAD25: //# - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH9: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATH20: //# - case BOTH_DEATH21: //# - case BOTH_DEATH22: //# - case BOTH_DEATH23: //# - case BOTH_DEATH24: //# - case BOTH_DEATH25: //# - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHFORWARD3: //# Second Death in which they get thrown forward - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD9: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_DEAD20: //# + case BOTH_DEAD21: //# + case BOTH_DEAD22: //# + case BOTH_DEAD23: //# + case BOTH_DEAD24: //# + case BOTH_DEAD25: //# + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH9: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATH20: //# + case BOTH_DEATH21: //# + case BOTH_DEATH22: //# + case BOTH_DEATH23: //# + case BOTH_DEATH24: //# + case BOTH_DEATH25: //# + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHFORWARD3: //# Second Death in which they get thrown forward + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom return -2; break; case BOTH_DEATH_ROLL: //# Death anim from a roll @@ -2953,103 +2378,71 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, case BOTH_DEATH_SPIN_180: //# Death anim when facing backwards case BOTH_DEATH_LYING_UP: //# Death anim when lying on back case BOTH_DEATH_LYING_DN: //# Death anim when lying on front - case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face - case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back + case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face + case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back case BOTH_DEATH_CROUCHED: //# Death anim when crouched case BOTH_RIGHTHANDCHOPPEDOFF: return -2; break; } // Not currently playing a death animation, so try and get an appropriate one now. - if ( deathAnim == -1 ) - { - deathAnim = G_CheckSpecialDeathAnim( self, point, damage, mod, hitLoc ); + if (deathAnim == -1) { + deathAnim = G_CheckSpecialDeathAnim(self, point, damage, mod, hitLoc); - if ( deathAnim == -1 ) - {//base on hitLoc + if (deathAnim == -1) { // base on hitLoc vec3_t fwd; - AngleVectors( self->currentAngles, fwd, NULL, NULL ); - float thrown = DotProduct( fwd, self->client->ps.velocity ); - //death anims - switch( hitLoc ) - { + AngleVectors(self->currentAngles, fwd, NULL, NULL); + float thrown = DotProduct(fwd, self->client->ps.velocity); + // death anims + switch (hitLoc) { case HL_FOOT_RT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH24;//right foot trips up, spin - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else - { - deathAnim = BOTH_DEATH5;//same as 4 + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH24; // right foot trips up, spin + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH5; // same as 4 } break; case HL_FOOT_LT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH25;//left foot trips up, spin - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else - { - deathAnim = BOTH_DEATH5;//same as 4 + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH25; // left foot trips up, spin + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH5; // same as 4 } break; case HL_LEG_RT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH3;//right leg collapse - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH4;//back: forward + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH3; // right leg collapse + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH4; // back: forward } break; case HL_LEG_LT: - if ( !Q_irand( 0, 2 ) && thrown < 250 ) - { - deathAnim = BOTH_DEATH7;//left leg collapse - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH4;//back: forward + if (!Q_irand(0, 2) && thrown < 250) { + deathAnim = BOTH_DEATH7; // left leg collapse + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH4; // back: forward } break; case HL_BACK: - if ( fabs(thrown) < 50 || (fabs(thrown) < 200&&!Q_irand(0,3)) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - deathAnim = BOTH_DEATH10;//back: bend back, fall forward + if (fabs(thrown) < 50 || (fabs(thrown) < 200 && !Q_irand(0, 3))) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + deathAnim = BOTH_DEATH10; // back: bend back, fall forward } - } - else - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else - { - deathAnim = BOTH_DEATH5;//same as 4 + } else { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH4; // back: forward + } else { + deathAnim = BOTH_DEATH5; // same as 4 } } break; @@ -3057,48 +2450,34 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, case HL_CHEST_RT: case HL_ARM_RT: case HL_BACK_LT: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,2)) || !Q_irand( 0, 10 ) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward - } - else - { - deathAnim = BOTH_DEATH20;//chest right: snap, fall forward - } - } - else if ( (damage <= self->max_health*0.5&&Q_irand(0,1)) || !Q_irand( 0, 10 ) ) - { - deathAnim = BOTH_DEATH3;//chest right: back - } - else if ( (damage <= self->max_health*0.75&&Q_irand(0,1)) || !Q_irand( 0, 10 ) ) - { - deathAnim = BOTH_DEATH6;//chest right: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH8;//chest right: spin high + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 2)) || !Q_irand(0, 10)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward + } else { + deathAnim = BOTH_DEATH20; // chest right: snap, fall forward } - else - { - switch ( Q_irand( 0, 3 ) ) - { + } else if ((damage <= self->max_health * 0.5 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH3; // chest right: back + } else if ((damage <= self->max_health * 0.75 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH6; // chest right: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH8; // chest right: spin high + } else { + switch (Q_irand(0, 3)) { default: case 0: - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH3;//chest right: back + deathAnim = BOTH_DEATH3; // chest right: back break; case 2: - deathAnim = BOTH_DEATH6;//chest right: spin + deathAnim = BOTH_DEATH6; // chest right: spin break; case 3: - deathAnim = BOTH_DEATH20;//chest right: spin + deathAnim = BOTH_DEATH20; // chest right: spin break; } } @@ -3108,48 +2487,34 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, case HL_ARM_LT: case HL_HAND_LT: case HL_BACK_RT: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,2)) || !Q_irand(0, 10) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward - } - else - { - deathAnim = BOTH_DEATH21;//chest left: snap, fall forward - } - } - else if ( (damage <= self->max_health*0.5&&Q_irand(0,1)) || !Q_irand(0, 10) ) - { - deathAnim = BOTH_DEATH7;//chest left: back - } - else if ( (damage <= self->max_health*0.75&&Q_irand(0,1)) || !Q_irand(0, 10) ) - { - deathAnim = BOTH_DEATH12;//chest left: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH14;//chest left: spin high + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 2)) || !Q_irand(0, 10)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward + } else { + deathAnim = BOTH_DEATH21; // chest left: snap, fall forward } - else - { - switch ( Q_irand( 0, 3 ) ) - { + } else if ((damage <= self->max_health * 0.5 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH7; // chest left: back + } else if ((damage <= self->max_health * 0.75 && Q_irand(0, 1)) || !Q_irand(0, 10)) { + deathAnim = BOTH_DEATH12; // chest left: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH14; // chest left: spin high + } else { + switch (Q_irand(0, 3)) { default: case 0: - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH7;//chest left: back + deathAnim = BOTH_DEATH7; // chest left: back break; case 2: - deathAnim = BOTH_DEATH12;//chest left: spin + deathAnim = BOTH_DEATH12; // chest left: spin break; case 3: - deathAnim = BOTH_DEATH21;//chest left: spin + deathAnim = BOTH_DEATH21; // chest left: spin break; } } @@ -3157,73 +2522,44 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, break; case HL_CHEST: case HL_WAIST: - if ( (damage <= self->max_health*0.25&&Q_irand(0,1)) || thrown > -50 ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH18;//gut: fall right + if ((damage <= self->max_health * 0.25 && Q_irand(0, 1)) || thrown > -50) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH18; // gut: fall right + } else { + deathAnim = BOTH_DEATH19; // gut: fall left } - else - { - deathAnim = BOTH_DEATH19;//gut: fall left + } else if ((damage <= self->max_health * 0.5 && !Q_irand(0, 1)) || (fabs(thrown) < 200 && !Q_irand(0, 3))) { + if (Q_irand(0, 2)) { + deathAnim = BOTH_DEATH2; // chest: backward short + } else if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH22; // chest: backward short + } else { + deathAnim = BOTH_DEATH23; // chest: backward short } - } - else if ( (damage <= self->max_health*0.5&&!Q_irand(0,1)) || (fabs(thrown)<200&&!Q_irand(0,3)) ) - { - if ( Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH2;//chest: backward short - } - else if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH22;//chest: backward short - } - else - { - deathAnim = BOTH_DEATH23;//chest: backward short - } - } - else if ( thrown < -300 && Q_irand( 0, 1 ) ) - { - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATHBACKWARD1;//chest: fly back - } - else - { - deathAnim = BOTH_DEATHBACKWARD2;//chest: flip back - } - } - else if ( thrown < -200 && Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH15;//chest: roll backward - } - else - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH1;//chest: backward med + } else if (thrown < -300 && Q_irand(0, 1)) { + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATHBACKWARD1; // chest: fly back + } else { + deathAnim = BOTH_DEATHBACKWARD2; // chest: flip back } - else - { - deathAnim = BOTH_DEATH16;//same as 1 + } else if (thrown < -200 && Q_irand(0, 1)) { + deathAnim = BOTH_DEATH15; // chest: roll backward + } else { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH1; // chest: backward med + } else { + deathAnim = BOTH_DEATH16; // same as 1 } } break; case HL_HEAD: - if ( damage <= self->max_health*0.5 && Q_irand(0,2) ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - if ( Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH13;//head: stumble, fall back - } - else - { - deathAnim = BOTH_DEATH10;//head: stumble, fall back + if (damage <= self->max_health * 0.5 && Q_irand(0, 2)) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + if (Q_irand(0, 2)) { + deathAnim = BOTH_DEATH13; // head: stumble, fall back + } else { + deathAnim = BOTH_DEATH10; // head: stumble, fall back } } break; @@ -3234,90 +2570,72 @@ static int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, } // Validate..... - if ( deathAnim == -1 || !PM_HasAnimation( self, deathAnim )) - { + if (deathAnim == -1 || !PM_HasAnimation(self, deathAnim)) { // I guess we'll take what we can get..... - deathAnim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); + deathAnim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); } return deathAnim; } -int G_CheckLedgeDive( gentity_t *self, float checkDist, vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp ) -{ +int G_CheckLedgeDive(gentity_t *self, float checkDist, vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp) { // Intelligent Ledge-Diving Deaths: // If I'm an NPC, check for nearby ledges and fall off it if possible // How should/would/could this interact with knockback if we already have some? // Ideally - apply knockback if there are no ledges or a ledge in that dir // But if there is a ledge and it's not in the dir of my knockback, fall off the ledge instead - if ( !self || !self->client ) - { + if (!self || !self->client) { return 0; } - vec3_t fallForwardDir, fallRightDir; - vec3_t angles = {0}; - int cliff_fall = 0; + vec3_t fallForwardDir, fallRightDir; + vec3_t angles = {0}; + int cliff_fall = 0; - if ( checkVel && !VectorCompare( checkVel, vec3_origin ) ) - {//already moving in a dir - angles[1] = vectoyaw( self->client->ps.velocity ); - AngleVectors( angles, fallForwardDir, fallRightDir, NULL ); - } - else - {//try forward first + if (checkVel && !VectorCompare(checkVel, vec3_origin)) { // already moving in a dir + angles[1] = vectoyaw(self->client->ps.velocity); + AngleVectors(angles, fallForwardDir, fallRightDir, NULL); + } else { // try forward first angles[1] = self->client->ps.viewangles[1]; - AngleVectors( angles, fallForwardDir, fallRightDir, NULL ); + AngleVectors(angles, fallForwardDir, fallRightDir, NULL); } - VectorNormalize( fallForwardDir ); - float fallDist = G_CheckForLedge( self, fallForwardDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallForwardDir, 85 ); + VectorNormalize(fallForwardDir); + float fallDist = G_CheckForLedge(self, fallForwardDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallForwardDir, 85); self->client->ps.velocity[2] = 100; self->client->ps.groundEntityNum = ENTITYNUM_NONE; - } - else if ( tryOpposite ) - { - VectorScale( fallForwardDir, -1, fallForwardDir ); - fallDist = G_CheckForLedge( self, fallForwardDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallForwardDir, 85 ); + } else if (tryOpposite) { + VectorScale(fallForwardDir, -1, fallForwardDir); + fallDist = G_CheckForLedge(self, fallForwardDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallForwardDir, 85); self->client->ps.velocity[2] = 100; self->client->ps.groundEntityNum = ENTITYNUM_NONE; } } - if ( !cliff_fall && tryPerp ) - {//try sides - VectorNormalize( fallRightDir ); - fallDist = G_CheckForLedge( self, fallRightDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallRightDir, 85 ); + if (!cliff_fall && tryPerp) { // try sides + VectorNormalize(fallRightDir); + fallDist = G_CheckForLedge(self, fallRightDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallRightDir, 85); self->client->ps.velocity[2] = 100; - } - else - { - VectorScale( fallRightDir, -1, fallRightDir ); - fallDist = G_CheckForLedge( self, fallRightDir, checkDist ); - if ( fallDist >= 128 ) - { - VectorClear( self->client->ps.velocity ); - G_Throw( self, fallRightDir, 85 ); + } else { + VectorScale(fallRightDir, -1, fallRightDir); + fallDist = G_CheckForLedge(self, fallRightDir, checkDist); + if (fallDist >= 128) { + VectorClear(self->client->ps.velocity); + G_Throw(self, fallRightDir, 85); self->client->ps.velocity[2] = 100; } } } - if ( fallDist >= 256 ) - { + if (fallDist >= 256) { cliff_fall = 2; - } - else if ( fallDist >= 128 ) - { + } else if (fallDist >= 128) { cliff_fall = 1; } return cliff_fall; @@ -3327,26 +2645,23 @@ int G_CheckLedgeDive( gentity_t *self, float checkDist, vec3_t checkVel, qboolea player_die ================== */ -void NPC_SetAnim(gentity_t *ent,int type,int anim,int priority); -extern void AI_DeleteSelfFromGroup( gentity_t *self ); -extern void AI_GroupMemberKilled( gentity_t *self ); -extern qboolean FlyingCreature( gentity_t *ent ); -extern void G_DrivableATSTDie( gentity_t *self ); -void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dflags, int hitLoc ) -{ - int anim; - int contents; - qboolean deathScript = qfalse; - qboolean lastInGroup = qfalse; - qboolean specialAnim = qfalse; - qboolean holdingSaber = qfalse; - int cliff_fall = 0; - - //FIXME: somehow people are sometimes not completely dying??? - if ( self->client->ps.pm_type == PM_DEAD && (meansOfDeath != MOD_SNIPER || (self->flags & FL_DISINTEGRATED)) ) - {//do dismemberment/twitching - if ( self->client->NPC_class == CLASS_MARK1 ) - { +void NPC_SetAnim(gentity_t *ent, int type, int anim, int priority); +extern void AI_DeleteSelfFromGroup(gentity_t *self); +extern void AI_GroupMemberKilled(gentity_t *self); +extern qboolean FlyingCreature(gentity_t *ent); +extern void G_DrivableATSTDie(gentity_t *self); +void player_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dflags, int hitLoc) { + int anim; + int contents; + qboolean deathScript = qfalse; + qboolean lastInGroup = qfalse; + qboolean specialAnim = qfalse; + qboolean holdingSaber = qfalse; + int cliff_fall = 0; + + // FIXME: somehow people are sometimes not completely dying??? + if (self->client->ps.pm_type == PM_DEAD && (meansOfDeath != MOD_SNIPER || (self->flags & FL_DISINTEGRATED))) { // do dismemberment/twitching + if (self->client->NPC_class == CLASS_MARK1) { DeathFX(self); self->takedamage = qfalse; self->client->ps.eFlags |= EF_NODRAW; @@ -3354,200 +2669,138 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int // G_FreeEntity( self ); // Is this safe? I can't see why we'd mark it nodraw and then just leave it around?? self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + FRAMETIME; - } - else - { - anim = G_PickDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); - if ( dflags & DAMAGE_DISMEMBER ) - { - G_DoDismemberment( self, self->pos1, meansOfDeath, damage, hitLoc ); + } else { + anim = G_PickDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); + if (dflags & DAMAGE_DISMEMBER) { + G_DoDismemberment(self, self->pos1, meansOfDeath, damage, hitLoc); } - if ( anim >= 0 ) - { - NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD); + if (anim >= 0) { + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); } } return; } #ifndef FINAL_BUILD - if ( d_saberCombat->integer && attacker && attacker->client ) - { - gi.Printf( S_COLOR_YELLOW"combatant %s died, killer anim = %s\n", self->targetname, animTable[attacker->client->ps.torsoAnim].name ); + if (d_saberCombat->integer && attacker && attacker->client) { + gi.Printf(S_COLOR_YELLOW "combatant %s died, killer anim = %s\n", self->targetname, animTable[attacker->client->ps.torsoAnim].name); } -#endif//FINAL_BUILD +#endif // FINAL_BUILD - if ( self->NPC ) - { - if ( self->client && Jedi_WaitingAmbush( self ) ) - {//ambushing trooper + if (self->NPC) { + if (self->client && Jedi_WaitingAmbush(self)) { // ambushing trooper self->client->noclip = qfalse; } - NPC_FreeCombatPoint( self->NPC->combatPoint ); - if ( self->NPC->group ) - { + NPC_FreeCombatPoint(self->NPC->combatPoint); + if (self->NPC->group) { lastInGroup = (qboolean)(self->NPC->group->numGroup < 2); - AI_GroupMemberKilled( self ); - AI_DeleteSelfFromGroup( self ); + AI_GroupMemberKilled(self); + AI_DeleteSelfFromGroup(self); } - if ( self->NPC->tempGoal ) - { - G_FreeEntity( self->NPC->tempGoal ); + if (self->NPC->tempGoal) { + G_FreeEntity(self->NPC->tempGoal); self->NPC->tempGoal = NULL; } - if ( self->s.eFlags & EF_LOCKED_TO_WEAPON ) - { + if (self->s.eFlags & EF_LOCKED_TO_WEAPON) { // dumb, just get the NPC out of the chair -extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); + extern void RunEmplacedWeapon(gentity_t * ent, usercmd_t * *ucmd); usercmd_t cmd, *ad_cmd; - memset( &cmd, 0, sizeof( usercmd_t )); + memset(&cmd, 0, sizeof(usercmd_t)); - //gentity_t *old = self->owner; + // gentity_t *old = self->owner; - if ( self->owner ) - { + if (self->owner) { self->owner->s.frame = self->owner->startFrame = self->owner->endFrame = 0; self->owner->svFlags &= ~SVF_ANIMATING; } cmd.buttons |= BUTTON_USE; ad_cmd = &cmd; - RunEmplacedWeapon( self, &ad_cmd ); - //self->owner = old; + RunEmplacedWeapon(self, &ad_cmd); + // self->owner = old; } } - if ( attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self ) - { + if (attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self) { attacker->NPC->group->enemy = NULL; } - if ( self->s.weapon == WP_SABER ) - { + if (self->s.weapon == WP_SABER) { holdingSaber = qtrue; } - if ( self->client->ps.saberEntityNum != ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0 ) - { - if ( self->client->ps.saberInFlight ) - {//just drop it + if (self->client->ps.saberEntityNum != ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0) { + if (self->client->ps.saberInFlight) { // just drop it self->client->ps.saberActive = qfalse; - } - else - { - if ( (hitLoc != HL_HAND_RT - || self->client->dismembered - || meansOfDeath != MOD_SABER )//if might get hand cut off, leave saber in hand - && holdingSaber - && ( Q_irand( 0, 1 ) - || meansOfDeath == MOD_EXPLOSIVE - || meansOfDeath == MOD_REPEATER_ALT - || meansOfDeath == MOD_FLECHETTE_ALT - || meansOfDeath == MOD_ROCKET - || meansOfDeath == MOD_ROCKET_ALT - || meansOfDeath == MOD_THERMAL - || meansOfDeath == MOD_THERMAL_ALT - || meansOfDeath == MOD_DETPACK - || meansOfDeath == MOD_LASERTRIP - || meansOfDeath == MOD_LASERTRIP_ALT - || meansOfDeath == MOD_MELEE - || meansOfDeath == MOD_FORCE_GRIP - || meansOfDeath == MOD_KNOCKOUT - || meansOfDeath == MOD_CRUSH - || meansOfDeath == MOD_IMPACT - || meansOfDeath == MOD_FALLING - || meansOfDeath == MOD_EXPLOSIVE_SPLASH ) ) - {//drop it - TossClientItems( self ); - } - else - {//just free it - if ( g_entities[self->client->ps.saberEntityNum].inuse ) - { - G_FreeEntity( &g_entities[self->client->ps.saberEntityNum] ); + } else { + if ((hitLoc != HL_HAND_RT || self->client->dismembered || meansOfDeath != MOD_SABER) // if might get hand cut off, leave saber in hand + && holdingSaber && + (Q_irand(0, 1) || meansOfDeath == MOD_EXPLOSIVE || meansOfDeath == MOD_REPEATER_ALT || meansOfDeath == MOD_FLECHETTE_ALT || + meansOfDeath == MOD_ROCKET || meansOfDeath == MOD_ROCKET_ALT || meansOfDeath == MOD_THERMAL || meansOfDeath == MOD_THERMAL_ALT || + meansOfDeath == MOD_DETPACK || meansOfDeath == MOD_LASERTRIP || meansOfDeath == MOD_LASERTRIP_ALT || meansOfDeath == MOD_MELEE || + meansOfDeath == MOD_FORCE_GRIP || meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_CRUSH || meansOfDeath == MOD_IMPACT || + meansOfDeath == MOD_FALLING || meansOfDeath == MOD_EXPLOSIVE_SPLASH)) { // drop it + TossClientItems(self); + } else { // just free it + if (g_entities[self->client->ps.saberEntityNum].inuse) { + G_FreeEntity(&g_entities[self->client->ps.saberEntityNum]); } self->client->ps.saberEntityNum = ENTITYNUM_NONE; } } } - if ( self->client->NPC_class == CLASS_SHADOWTROOPER ) - {//drop a force crystal - gitem_t *item; - item = FindItemForAmmo( AMMO_FORCE ); - Drop_Item( self, item, 0, qtrue ); + if (self->client->NPC_class == CLASS_SHADOWTROOPER) { // drop a force crystal + gitem_t *item; + item = FindItemForAmmo(AMMO_FORCE); + Drop_Item(self, item, 0, qtrue); } - //Use any target we had - if ( meansOfDeath != MOD_KNOCKOUT ) - { - G_UseTargets( self, self ); + // Use any target we had + if (meansOfDeath != MOD_KNOCKOUT) { + G_UseTargets(self, self); } - if ( attacker ) - { - if ( attacker->client && !attacker->s.number ) - { - if ( self->client ) - {//killed a client - if ( self->client->playerTeam == TEAM_ENEMY || (self->NPC && self->NPC->charmedTime > level.time) ) - {//killed an enemy + if (attacker) { + if (attacker->client && !attacker->s.number) { + if (self->client) { // killed a client + if (self->client->playerTeam == TEAM_ENEMY || (self->NPC && self->NPC->charmedTime > level.time)) { // killed an enemy attacker->client->sess.missionStats.enemiesKilled++; } } - if ( attacker != self ) - { - G_TrackWeaponUsage( attacker, inflictor, 30, meansOfDeath ); + if (attacker != self) { + G_TrackWeaponUsage(attacker, inflictor, 30, meansOfDeath); } } G_CheckVictoryScript(attacker); - //player killing a jedi with a lightsaber spawns a matrix-effect entity - if ( d_slowmodeath->integer ) - { - if ( !self->s.number ) - {//what the hell, always do slow-mo when player dies - //FIXME: don't do this when crushed to death? - if ( meansOfDeath == MOD_FALLING && self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//falling to death, have not hit yet - G_StartMatrixEffect( self, qtrue, 10000 ); - } - else if ( meansOfDeath != MOD_CRUSH ) - {//for all deaths except being crushed - G_StartMatrixEffect( self ); - } - } - else if ( d_slowmodeath->integer < 4 ) - {//any jedi killed by player-saber - if ( d_slowmodeath->integer < 3 ) - {//must be the last jedi in the room - if ( !G_JediInRoom( attacker->currentOrigin ) ) - { + // player killing a jedi with a lightsaber spawns a matrix-effect entity + if (d_slowmodeath->integer) { + if (!self->s.number) { // what the hell, always do slow-mo when player dies + // FIXME: don't do this when crushed to death? + if (meansOfDeath == MOD_FALLING && self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // falling to death, have not hit yet + G_StartMatrixEffect(self, qtrue, 10000); + } else if (meansOfDeath != MOD_CRUSH) { // for all deaths except being crushed + G_StartMatrixEffect(self); + } + } else if (d_slowmodeath->integer < 4) { // any jedi killed by player-saber + if (d_slowmodeath->integer < 3) { // must be the last jedi in the room + if (!G_JediInRoom(attacker->currentOrigin)) { lastInGroup = qtrue; - } - else - { + } else { lastInGroup = qfalse; } } - if ( !attacker->s.number - && holdingSaber - && meansOfDeath == MOD_SABER - && attacker->client - && attacker->client->ps.weapon == WP_SABER - && !attacker->client->ps.saberInFlight - && (d_slowmodeath->integer > 2||lastInGroup) )//either slow mo death level 3 (any jedi) or 2 and I was the last jedi in the room - {//Matrix! - G_StartMatrixEffect( self ); + if (!attacker->s.number && holdingSaber && meansOfDeath == MOD_SABER && attacker->client && attacker->client->ps.weapon == WP_SABER && + !attacker->client->ps.saberInFlight && + (d_slowmodeath->integer > 2 || lastInGroup)) // either slow mo death level 3 (any jedi) or 2 and I was the last jedi in the room + { // Matrix! + G_StartMatrixEffect(self); } - } - else - {//all player-saber kills - if ( !attacker->s.number - && meansOfDeath == MOD_SABER - && attacker->client - && attacker->client->ps.weapon == WP_SABER - && !attacker->client->ps.saberInFlight - && (d_slowmodeath->integer > 4||lastInGroup||holdingSaber))//either slow mo death level 5 (any enemy) or 4 and I was the last in my group or I'm a saber user - {//Matrix! - G_StartMatrixEffect( self ); + } else { // all player-saber kills + if (!attacker->s.number && meansOfDeath == MOD_SABER && attacker->client && attacker->client->ps.weapon == WP_SABER && + !attacker->client->ps.saberInFlight && + (d_slowmodeath->integer > 4 || lastInGroup || + holdingSaber)) // either slow mo death level 5 (any enemy) or 4 and I was the last in my group or I'm a saber user + { // Matrix! + G_StartMatrixEffect(self); } } } @@ -3557,95 +2810,72 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->client->renderInfo.lookTarget = ENTITYNUM_NONE; self->client->ps.persistant[PERS_KILLED]++; - if ( self->client->playerTeam == TEAM_PLAYER ) - {//FIXME: just HazTeam members in formation on away missions? - //or more controlled- via deathscripts? - // Don't count player - if (( g_entities[0].inuse && g_entities[0].client ) && (self->s.number != 0)) - {//add to the number of teammates lost + if (self->client->playerTeam == TEAM_PLAYER) { // FIXME: just HazTeam members in formation on away missions? + // or more controlled- via deathscripts? + // Don't count player + if ((g_entities[0].inuse && g_entities[0].client) && (self->s.number != 0)) { // add to the number of teammates lost g_entities[0].client->ps.persistant[PERS_TEAMMATES_KILLED]++; - } - else // Player died, fire off scoreboard soon + } else // Player died, fire off scoreboard soon { - cg.missionStatusDeadTime = level.time + 1000; // Too long?? Too short?? - cg.zoomMode = 0; // turn off zooming when we die + cg.missionStatusDeadTime = level.time + 1000; // Too long?? Too short?? + cg.zoomMode = 0; // turn off zooming when we die } } - if ( self->s.number == 0 && attacker ) - { -// G_SetMissionStatusText( attacker, meansOfDeath ); - //TEST: If player killed, unmark all teammates from being undying so they can buy it too - //NOTE: we want this to happen ONLY on our squad ONLY on missions... in the tutorial or on voyager levels this could be really weird. + if (self->s.number == 0 && attacker) { + // G_SetMissionStatusText( attacker, meansOfDeath ); + // TEST: If player killed, unmark all teammates from being undying so they can buy it too + // NOTE: we want this to happen ONLY on our squad ONLY on missions... in the tutorial or on voyager levels this could be really weird. G_MakeTeamVulnerable(); } - if ( attacker && attacker->client) - { - if ( attacker == self || OnSameTeam (self, attacker ) ) - { - AddScore( attacker, -1 ); - } - else - { - AddScore( attacker, 1 ); + if (attacker && attacker->client) { + if (attacker == self || OnSameTeam(self, attacker)) { + AddScore(attacker, -1); + } else { + AddScore(attacker, 1); } - } - else - { - AddScore( self, -1 ); + } else { + AddScore(self, -1); } // if client is in a nodrop area, don't drop anything - contents = gi.pointcontents( self->currentOrigin, -1 ); - if ( !holdingSaber + contents = gi.pointcontents(self->currentOrigin, -1); + if (!holdingSaber //&& self->s.number != 0 - && !( contents & CONTENTS_NODROP ) - && meansOfDeath != MOD_SNIPER - && (!self->client||self->client->NPC_class!=CLASS_GALAKMECH)) - { - TossClientItems( self ); + && !(contents & CONTENTS_NODROP) && meansOfDeath != MOD_SNIPER && (!self->client || self->client->NPC_class != CLASS_GALAKMECH)) { + TossClientItems(self); } - if ( meansOfDeath == MOD_SNIPER ) - {//I was disintegrated - if ( self->message ) - {//I was holding a key - //drop the key - G_DropKey( self ); + if (meansOfDeath == MOD_SNIPER) { // I was disintegrated + if (self->message) { // I was holding a key + // drop the key + G_DropKey(self); } } - - if ( holdingSaber ) - {//never drop a lightsaber! - if ( self->client->ps.saberActive ) - { - self->client->ps.saberActive = qfalse; - if ( self->client->playerTeam == TEAM_PLAYER ) - { - G_SoundOnEnt( self, CHAN_AUTO, "sound/weapons/saber/saberoff.wav" ); - } - else - { - G_SoundOnEnt( self, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav" ); + + if (holdingSaber) { // never drop a lightsaber! + if (self->client->ps.saberActive) { + self->client->ps.saberActive = qfalse; + if (self->client->playerTeam == TEAM_PLAYER) { + G_SoundOnEnt(self, CHAN_AUTO, "sound/weapons/saber/saberoff.wav"); + } else { + G_SoundOnEnt(self, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav"); } } - } - else if ( self->s.weapon != WP_BLASTER_PISTOL ) - {// Sigh...borg shouldn't drop their weapon attachments when they die.. + } else if (self->s.weapon != WP_BLASTER_PISTOL) { // Sigh...borg shouldn't drop their weapon attachments when they die.. self->s.weapon = WP_NONE; - if ( self->weaponModel >= 0 && self->ghoul2.size()) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->weaponModel ); + if (self->weaponModel >= 0 && self->ghoul2.size()) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel); self->weaponModel = -1; } } - self->s.powerups &= ~PW_REMOVE_AT_DEATH;//removes everything but electricity and force push + self->s.powerups &= ~PW_REMOVE_AT_DEATH; // removes everything but electricity and force push - //FIXME: do this on a callback? So people can't walk through long death anims? - //Maybe set on last frame? Would be cool for big blocking corpses if the never got set? - //self->contents = CONTENTS_CORPSE;//now done a second after death + // FIXME: do this on a callback? So people can't walk through long death anims? + // Maybe set on last frame? Would be cool for big blocking corpses if the never got set? + // self->contents = CONTENTS_CORPSE;//now done a second after death /* self->takedamage = qfalse; // no gibbing if ( self->client->playerTeam == TEAM_PARASITE ) @@ -3658,77 +2888,58 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->maxs[2] = -8; } */ - if ( !self->s.number ) - {//player + if (!self->s.number) { // player self->contents = CONTENTS_CORPSE; self->maxs[2] = -8; } - self->clipmask&=~(CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP);//so dead NPC can fly off ledges + self->clipmask &= ~(CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); // so dead NPC can fly off ledges - //FACING========================================================== - if ( attacker && self->s.number == 0 ) - { - self->client->ps.stats[STAT_DEAD_YAW] = AngleNormalize180( self->client->ps.viewangles[YAW] ); + // FACING========================================================== + if (attacker && self->s.number == 0) { + self->client->ps.stats[STAT_DEAD_YAW] = AngleNormalize180(self->client->ps.viewangles[YAW]); } self->currentAngles[PITCH] = 0; self->currentAngles[ROLL] = 0; - if ( self->NPC ) - { + if (self->NPC) { self->NPC->desiredYaw = 0; self->NPC->desiredPitch = 0; self->NPC->confusionTime = 0; self->NPC->charmedTime = 0; } - VectorCopy( self->currentAngles, self->client->ps.viewangles ); - //FACING========================================================== - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - {//I was the player's viewentity and I died, kick him back to his normal view - G_ClearViewEntity( player ); - } - else if ( !self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE ) - { - G_ClearViewEntity( self ); - } - else if ( !self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE ) - { - G_ClearViewEntity( self ); + VectorCopy(self->currentAngles, self->client->ps.viewangles); + // FACING========================================================== + if (player && player->client && + player->client->ps.viewEntity == self->s.number) { // I was the player's viewentity and I died, kick him back to his normal view + G_ClearViewEntity(player); + } else if (!self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE) { + G_ClearViewEntity(self); + } else if (!self->s.number && self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_NONE) { + G_ClearViewEntity(self); } self->s.loopSound = 0; // remove powerups - memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) ); - - if ( self->client->NPC_class == CLASS_MARK1 ) - { - Mark1_die( self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc ); - } - else if ( self->client->NPC_class == CLASS_INTERROGATOR ) - { - Interrogator_die( self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc ); - } - else if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//FIXME: need keyframed explosions? - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); - } - else if ( self->client->NPC_class == CLASS_ATST ) - {//FIXME: need keyframed explosions - if ( !self->s.number ) - { - G_DrivableATSTDie( self ); - } - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data - if ( anim != -1 ) - { - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } - else if ( self->s.number && self->message && meansOfDeath != MOD_SNIPER ) - {//imp with a key on his arm - //pick a death anim that leaves key visible - switch ( Q_irand( 0, 3 ) ) - { + memset(self->client->ps.powerups, 0, sizeof(self->client->ps.powerups)); + + if (self->client->NPC_class == CLASS_MARK1) { + Mark1_die(self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc); + } else if (self->client->NPC_class == CLASS_INTERROGATOR) { + Interrogator_die(self, inflictor, attacker, damage, meansOfDeath, dflags, hitLoc); + } else if (self->client->NPC_class == CLASS_GALAKMECH) { // FIXME: need keyframed explosions? + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); + } else if (self->client->NPC_class == CLASS_ATST) { // FIXME: need keyframed explosions + if (!self->s.number) { + G_DrivableATSTDie(self); + } + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data + if (anim != -1) { + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + } else if (self->s.number && self->message && meansOfDeath != MOD_SNIPER) { // imp with a key on his arm + // pick a death anim that leaves key visible + switch (Q_irand(0, 3)) { case 0: anim = BOTH_DEATH4; break; @@ -3743,134 +2954,91 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); anim = BOTH_DEATH18; break; } - //FIXME: verify we have this anim? - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); - } - } - else if ( meansOfDeath == MOD_FALLING || (self->client->ps.legsAnim == BOTH_FALLDEATH1INAIR && self->client->ps.torsoAnim == BOTH_FALLDEATH1INAIR) || (self->client->ps.legsAnim == BOTH_FALLDEATH1 && self->client->ps.torsoAnim == BOTH_FALLDEATH1) ) - { - //FIXME: no good way to predict you're going to fall to your death... need falling bushes/triggers? - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE //in the air - && self->client->ps.velocity[2] < 0 //falling - && self->client->ps.legsAnim != BOTH_FALLDEATH1INAIR //not already in falling loop - && self->client->ps.torsoAnim != BOTH_FALLDEATH1INAIR )//not already in falling loop - { - NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1INAIR, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - if ( !self->NPC ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - } - else if (!(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - //so we don't do this again + // FIXME: verify we have this anim? + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); + } + } else if (meansOfDeath == MOD_FALLING || (self->client->ps.legsAnim == BOTH_FALLDEATH1INAIR && self->client->ps.torsoAnim == BOTH_FALLDEATH1INAIR) || + (self->client->ps.legsAnim == BOTH_FALLDEATH1 && self->client->ps.torsoAnim == BOTH_FALLDEATH1)) { + // FIXME: no good way to predict you're going to fall to your death... need falling bushes/triggers? + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE // in the air + && self->client->ps.velocity[2] < 0 // falling + && self->client->ps.legsAnim != BOTH_FALLDEATH1INAIR // not already in falling loop + && self->client->ps.torsoAnim != BOTH_FALLDEATH1INAIR) // not already in falling loop + { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1INAIR, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (!self->NPC) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + } else if (!(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + // so we don't do this again self->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; - //self->client->ps.gravity *= 0.5;//Fall a bit slower + // self->client->ps.gravity *= 0.5;//Fall a bit slower self->client->ps.friction = 1; } - } - else - { - int deathAnim = BOTH_FALLDEATH1LAND; - if ( PM_InOnGroundAnim( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back - } - else - { - deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front - } - } - else if ( PM_InKnockDown( &self->client->ps ) ) - { - if ( AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0 ) - { - deathAnim = BOTH_DEATH_FALLING_UP; //# Death anim when falling on back - } - else - { - deathAnim = BOTH_DEATH_FALLING_DN; //# Death anim when falling on face - } - } - NPC_SetAnim(self, SETANIM_BOTH, deathAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - //HMM: check for nodrop? - G_SoundOnEnt( self, CHAN_BODY, "sound/player/fallsplat.wav" ); - if ( gi.VoiceVolume[self->s.number] - && self->NPC && (self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//I was talking, so cut it off... with a jump sound? - G_SoundOnEnt( self, CHAN_VOICE_ATTEN, "*pain100.wav" ); - } - } - } - else - {// normal death - anim = G_CheckSpecialDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); - if ( anim == -1 ) - { - if ( self->s.legsAnim == BOTH_RESTRAINED1 || self->s.legsAnim == BOTH_RESTRAINED1POINT ) - {//super special case, floating in air lying down + } else { + int deathAnim = BOTH_FALLDEATH1LAND; + if (PM_InOnGroundAnim(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_LYING_UP; //# Death anim when lying on back + } else { + deathAnim = BOTH_DEATH_LYING_DN; //# Death anim when lying on front + } + } else if (PM_InKnockDown(&self->client->ps)) { + if (AngleNormalize180(self->client->renderInfo.torsoAngles[PITCH]) < 0) { + deathAnim = BOTH_DEATH_FALLING_UP; //# Death anim when falling on back + } else { + deathAnim = BOTH_DEATH_FALLING_DN; //# Death anim when falling on face + } + } + NPC_SetAnim(self, SETANIM_BOTH, deathAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // HMM: check for nodrop? + G_SoundOnEnt(self, CHAN_BODY, "sound/player/fallsplat.wav"); + if (gi.VoiceVolume[self->s.number] && self->NPC && + (self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // I was talking, so cut it off... with a jump sound? + G_SoundOnEnt(self, CHAN_VOICE_ATTEN, "*pain100.wav"); + } + } + } else { // normal death + anim = G_CheckSpecialDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); + if (anim == -1) { + if (self->s.legsAnim == BOTH_RESTRAINED1 || self->s.legsAnim == BOTH_RESTRAINED1POINT) { // super special case, floating in air lying down anim = BOTH_RESTRAINED1; - } - else if ( PM_InOnGroundAnim( &self->client->ps ) && PM_HasAnimation( self, BOTH_LYINGDEATH1 ) ) - {//on ground, need different death anim + } else if (PM_InOnGroundAnim(&self->client->ps) && PM_HasAnimation(self, BOTH_LYINGDEATH1)) { // on ground, need different death anim anim = BOTH_LYINGDEATH1; - } - else if ( meansOfDeath == MOD_TRIGGER_HURT && (self->s.powerups&(1<s.powerups & (1 << PW_SHOCKED))) { // electrocuted anim = BOTH_DEATH17; - } - else if ( meansOfDeath == MOD_WATER ) - {//drowned + } else if (meansOfDeath == MOD_WATER) { // drowned anim = BOTH_DEATH17; - } - else if ( meansOfDeath != MOD_SNIPER ) - { - cliff_fall = G_CheckLedgeDive( self, 128, self->client->ps.velocity, qtrue, qfalse ); - if ( cliff_fall == 2 ) - { - if ( !FlyingCreature( self ) && g_gravity->value > 0 ) - { - if ( !self->NPC ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN - } - else if (!(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - G_SoundOnEnt( self, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN + } else if (meansOfDeath != MOD_SNIPER) { + cliff_fall = G_CheckLedgeDive(self, 128, self->client->ps.velocity, qtrue, qfalse); + if (cliff_fall == 2) { + if (!FlyingCreature(self) && g_gravity->value > 0) { + if (!self->NPC) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN + } else if (!(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + G_SoundOnEnt(self, CHAN_VOICE, "*falling1.wav"); // CHAN_VOICE_ATTEN self->NPC->aiFlags |= NPCAI_DIE_ON_IMPACT; self->client->ps.friction = 0; } } } - if ( self->client->ps.pm_time > 0 && self->client->ps.pm_flags & PMF_TIME_KNOCKBACK && self->client->ps.velocity[2] > 0 ) - { - float thrown, dot; - vec3_t throwdir, forward; + if (self->client->ps.pm_time > 0 && self->client->ps.pm_flags & PMF_TIME_KNOCKBACK && self->client->ps.velocity[2] > 0) { + float thrown, dot; + vec3_t throwdir, forward; AngleVectors(self->currentAngles, forward, NULL, NULL); thrown = VectorNormalize2(self->client->ps.velocity, throwdir); dot = DotProduct(forward, throwdir); - if ( thrown > 100 ) - { - if ( dot > 0.3 ) - {//falling forward - if ( cliff_fall == 2 && PM_HasAnimation( self, BOTH_FALLDEATH1 ) ) - { + if (thrown > 100) { + if (dot > 0.3) { // falling forward + if (cliff_fall == 2 && PM_HasAnimation(self, BOTH_FALLDEATH1)) { anim = BOTH_FALLDEATH1; - } - else - { - switch ( Q_irand( 0, 7 ) ) - { + } else { + switch (Q_irand(0, 7)) { case 0: case 1: case 2: @@ -3888,38 +3056,25 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); anim = BOTH_DEATH14; break; } - if ( PM_HasAnimation( self, anim )) - { + if (PM_HasAnimation(self, anim)) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { + } else { anim = -1; } } - } - else if ( dot < -0.3 ) - { - if ( thrown >= 250 && !Q_irand( 0, 3 ) ) - { - if ( Q_irand( 0, 1 ) ) - { + } else if (dot < -0.3) { + if (thrown >= 250 && !Q_irand(0, 3)) { + if (Q_irand(0, 1)) { anim = BOTH_DEATHBACKWARD1; - } - else - { + } else { anim = BOTH_DEATHBACKWARD2; } - } - else - { - switch ( Q_irand( 0, 7 ) ) - { + } else { + switch (Q_irand(0, 7)) { case 0: case 1: anim = BOTH_DEATH1; @@ -3938,27 +3093,19 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); break; } } - if ( PM_HasAnimation( self, anim ) ) - { + if (PM_HasAnimation(self, anim)) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } - } - else - { + } else { anim = -1; } - } - else - {//falling to one of the sides - if ( cliff_fall == 2 && PM_HasAnimation( self, BOTH_FALLDEATH1 ) ) - { + } else { // falling to one of the sides + if (cliff_fall == 2 && PM_HasAnimation(self, BOTH_FALLDEATH1)) { anim = BOTH_FALLDEATH1; - if ( self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100 ) - { + if (self->client->ps.velocity[2] > 0 && self->client->ps.velocity[2] < 100) { self->client->ps.velocity[2] = 100; } } @@ -3966,238 +3113,184 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); } } } - } - else - { + } else { specialAnim = qtrue; } - if ( anim == -1 ) - { - if ( meansOfDeath == MOD_ELECTROCUTE - || (meansOfDeath == MOD_CRUSH && self->s.eFlags&EF_FORCE_GRIPPED) ) - {//electrocuted or choked to death + if (anim == -1) { + if (meansOfDeath == MOD_ELECTROCUTE || (meansOfDeath == MOD_CRUSH && self->s.eFlags & EF_FORCE_GRIPPED)) { // electrocuted or choked to death anim = BOTH_DEATH17; - } - else - { - anim = G_PickDeathAnim( self, self->pos1, damage, meansOfDeath, hitLoc ); + } else { + anim = G_PickDeathAnim(self, self->pos1, damage, meansOfDeath, hitLoc); } } - if ( anim == -1 ) - { - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data - //TEMP HACK: these spinny deaths should happen less often - if ( ( anim == BOTH_DEATH8 || anim == BOTH_DEATH14 ) && Q_irand( 0, 1 ) ) - { - anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH25 ); //initialize to good data + if (anim == -1) { + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data + // TEMP HACK: these spinny deaths should happen less often + if ((anim == BOTH_DEATH8 || anim == BOTH_DEATH14) && Q_irand(0, 1)) { + anim = PM_PickAnim(self, BOTH_DEATH1, BOTH_DEATH25); // initialize to good data } } - - if ( meansOfDeath == MOD_KNOCKOUT ) - { - //FIXME: knock-out sound, and don't remove me - G_AddEvent( self, EV_JUMP, 0 ); - G_UseTargets2( self, self, self->target2 ); - G_AlertTeam( self, attacker, 512, 32 ); - if ( self->NPC ) - {//stick around for a while + if (meansOfDeath == MOD_KNOCKOUT) { + // FIXME: knock-out sound, and don't remove me + G_AddEvent(self, EV_JUMP, 0); + G_UseTargets2(self, self, self->target2); + G_AlertTeam(self, attacker, 512, 32); + if (self->NPC) { // stick around for a while self->NPC->timeOfDeath = level.time + 10000; } } - else if ( meansOfDeath == MOD_SNIPER ) - { - gentity_t *tent; - vec3_t spot; + else if (meansOfDeath == MOD_SNIPER) { + gentity_t *tent; + vec3_t spot; - VectorCopy( self->currentOrigin, spot ); + VectorCopy(self->currentOrigin, spot); self->flags |= FL_DISINTEGRATED; self->svFlags |= SVF_BROADCAST; - tent = G_TempEntity( spot, EV_DISINTEGRATION ); + tent = G_TempEntity(spot, EV_DISINTEGRATION); tent->s.eventParm = PW_DISRUPTION; tent->svFlags |= SVF_BROADCAST; tent->owner = self; - G_AlertTeam( self, attacker, 512, 88 ); + G_AlertTeam(self, attacker, 512, 88); - if ( self->playerModel >= 0 ) - { + if (self->playerModel >= 0) { // don't let 'em animate - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, cg.time ); - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->motionBone, cg.time ); - gi.G2API_PauseBoneAnimIndex( &self->ghoul2[self->playerModel], self->lowerLumbarBone, cg.time ); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, cg.time); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->motionBone, cg.time); + gi.G2API_PauseBoneAnimIndex(&self->ghoul2[self->playerModel], self->lowerLumbarBone, cg.time); anim = -1; } - //not solid anymore + // not solid anymore self->contents = 0; self->maxs[2] = -8; - if ( self->NPC ) - { - //need to pad deathtime some to stick around long enough for death effect to play + if (self->NPC) { + // need to pad deathtime some to stick around long enough for death effect to play self->NPC->timeOfDeath = level.time + 2000; } - } - else - { - if ( hitLoc == HL_HEAD - && !(dflags&DAMAGE_RADIUS) - && meansOfDeath!=MOD_REPEATER_ALT - && meansOfDeath!=MOD_FLECHETTE_ALT - && meansOfDeath!=MOD_ROCKET - && meansOfDeath!=MOD_ROCKET_ALT - && meansOfDeath!=MOD_THERMAL - && meansOfDeath!=MOD_THERMAL_ALT - && meansOfDeath!=MOD_DETPACK - && meansOfDeath!=MOD_LASERTRIP - && meansOfDeath!=MOD_LASERTRIP_ALT - && meansOfDeath!=MOD_EXPLOSIVE - && meansOfDeath!=MOD_EXPLOSIVE_SPLASH ) - {//no sound when killed by headshot (explosions don't count) - G_AlertTeam( self, attacker, 512, 0 ); - if ( gi.VoiceVolume[self->s.number] ) - {//I was talking, so cut it off... with a jump sound? - G_SoundOnEnt( self, CHAN_VOICE, "*jump1.wav" ); - } - } - else - { - if ( (self->client->ps.eFlags&EF_FORCE_GRIPPED) ) - {//killed while gripped - no loud scream - G_AlertTeam( self, attacker, 512, 32 ); + } else { + if (hitLoc == HL_HEAD && !(dflags & DAMAGE_RADIUS) && meansOfDeath != MOD_REPEATER_ALT && meansOfDeath != MOD_FLECHETTE_ALT && + meansOfDeath != MOD_ROCKET && meansOfDeath != MOD_ROCKET_ALT && meansOfDeath != MOD_THERMAL && meansOfDeath != MOD_THERMAL_ALT && + meansOfDeath != MOD_DETPACK && meansOfDeath != MOD_LASERTRIP && meansOfDeath != MOD_LASERTRIP_ALT && meansOfDeath != MOD_EXPLOSIVE && + meansOfDeath != MOD_EXPLOSIVE_SPLASH) { // no sound when killed by headshot (explosions don't count) + G_AlertTeam(self, attacker, 512, 0); + if (gi.VoiceVolume[self->s.number]) { // I was talking, so cut it off... with a jump sound? + G_SoundOnEnt(self, CHAN_VOICE, "*jump1.wav"); } - else if ( cliff_fall != 2 ) - { - if ( meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); + } else { + if ((self->client->ps.eFlags & EF_FORCE_GRIPPED)) { // killed while gripped - no loud scream + G_AlertTeam(self, attacker, 512, 32); + } else if (cliff_fall != 2) { + if (meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_MELEE) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_AddEvent(self, Q_irand(EV_DEATH1, EV_DEATH3), self->health); } - G_DeathAlert( self, attacker ); - } - else - {//screaming death is louder - G_AlertTeam( self, attacker, 512, 1024 ); + G_DeathAlert(self, attacker); + } else { // screaming death is louder + G_AlertTeam(self, attacker, 512, 1024); } } } - if ( attacker && attacker->s.number == 0 ) - {//killed by player - //FIXME: this should really be wherever my body comes to rest... - AddSightEvent( attacker, self->currentOrigin, 384, AEL_DISCOVERED, 10 ); - //FIXME: danger event so that others will run away from this area since it's obviously dangerous + if (attacker && attacker->s.number == 0) { // killed by player + // FIXME: this should really be wherever my body comes to rest... + AddSightEvent(attacker, self->currentOrigin, 384, AEL_DISCOVERED, 10); + // FIXME: danger event so that others will run away from this area since it's obviously dangerous } - if ( anim >= 0 )//can be -1 if it fails, -2 if it's already in a death anim + if (anim >= 0) // can be -1 if it fails, -2 if it's already in a death anim { - NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - //do any dismemberment if there's any to do... - if ( (dflags&DAMAGE_DISMEMBER) && G_DoDismemberment( self, self->pos1, meansOfDeath, damage, hitLoc ) && !specialAnim ) - {//we did dismemberment and our death anim is okay to override - if ( hitLoc == HL_HAND_RT && self->locationDamage[hitLoc] >= Q3_INFINITE && cliff_fall != 2 && self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//just lost our right hand and we're on the ground, use the special anim - NPC_SetAnim( self, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // do any dismemberment if there's any to do... + if ((dflags & DAMAGE_DISMEMBER) && G_DoDismemberment(self, self->pos1, meansOfDeath, damage, hitLoc) && + !specialAnim) { // we did dismemberment and our death anim is okay to override + if (hitLoc == HL_HAND_RT && self->locationDamage[hitLoc] >= Q3_INFINITE && cliff_fall != 2 && + self->client->ps.groundEntityNum != ENTITYNUM_NONE) { // just lost our right hand and we're on the ground, use the special anim + NPC_SetAnim(self, SETANIM_BOTH, BOTH_RIGHTHANDCHOPPEDOFF, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } // don't allow player to respawn for a few seconds - self->client->respawnTime = level.time + 2000;//self->client->ps.legsAnimTimer; + self->client->respawnTime = level.time + 2000; // self->client->ps.legsAnimTimer; - //lock it to this anim forever - if ( self->client ) - { - PM_SetLegsAnimTimer( self, &self->client->ps.legsAnimTimer, -1 ); - PM_SetTorsoAnimTimer( self, &self->client->ps.torsoAnimTimer, -1 ); + // lock it to this anim forever + if (self->client) { + PM_SetLegsAnimTimer(self, &self->client->ps.legsAnimTimer, -1); + PM_SetTorsoAnimTimer(self, &self->client->ps.torsoAnimTimer, -1); } - //Flying creatures should drop when killed - //FIXME: This may screw up certain things that expect to float even while dead + // Flying creatures should drop when killed + // FIXME: This may screw up certain things that expect to float even while dead self->svFlags &= ~SVF_CUSTOM_GRAVITY; self->client->ps.pm_type = PM_DEAD; - //need to update STAT_HEALTH here because ClientThink_real for self may happen before STAT_HEALTH is updated from self->health and pmove will stomp death anim with a move anim + // need to update STAT_HEALTH here because ClientThink_real for self may happen before STAT_HEALTH is updated from self->health and pmove will stomp death + // anim with a move anim self->client->ps.stats[STAT_HEALTH] = self->health; - if ( self->NPC ) - {//If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths + if (self->NPC) { // If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths self->NPC->nextBStateThink = level.time; } - if ( G_ActivateBehavior( self, BSET_DEATH ) ) - { + if (G_ActivateBehavior(self, BSET_DEATH)) { deathScript = qtrue; } - if ( self->NPC && (self->NPC->scriptFlags&SCF_FFDEATH) ) - { - if ( G_ActivateBehavior( self, BSET_FFDEATH ) ) - {//FIXME: should running this preclude running the normal deathscript? + if (self->NPC && (self->NPC->scriptFlags & SCF_FFDEATH)) { + if (G_ActivateBehavior(self, BSET_FFDEATH)) { // FIXME: should running this preclude running the normal deathscript? deathScript = qtrue; } - G_UseTargets2( self, self, self->target4 ); + G_UseTargets2(self, self, self->target4); } - if ( !deathScript && !(self->svFlags&SVF_KILLED_SELF) ) - { - //Should no longer run scripts - //WARNING!!! DO NOT DO THIS WHILE RUNNING A SCRIPT, ICARUS WILL CRASH!!! - //FIXME: shouldn't ICARUS handle this internally? + if (!deathScript && !(self->svFlags & SVF_KILLED_SELF)) { + // Should no longer run scripts + // WARNING!!! DO NOT DO THIS WHILE RUNNING A SCRIPT, ICARUS WILL CRASH!!! + // FIXME: shouldn't ICARUS handle this internally? ICARUS_FreeEnt(self); } // Free up any timers we may have on us. - TIMER_Clear( self ); + TIMER_Clear(self); // Set pending objectives to failed OBJ_SetPendingObjectives(self); - gi.linkentity (self); + gi.linkentity(self); self->bounceCount = -1; // This is a cheap hack for optimizing the pointcontents check in deadthink - if ( self->NPC ) - { - self->NPC->timeOfDeath = level.time;//this will change - used for debouncing post-death events - self->s.time = level.time;//this will not chage- this is actual time of death + if (self->NPC) { + self->NPC->timeOfDeath = level.time; // this will change - used for debouncing post-death events + self->s.time = level.time; // this will not chage- this is actual time of death } // Start any necessary death fx for this entity - DeathFX( self ); + DeathFX(self); } -qboolean G_CheckForStrongAttackMomentum( gentity_t *self ) -{//see if our saber attack has too much momentum to be interrupted - if ( PM_PowerLevelForSaberAnim( &self->client->ps ) > FORCE_LEVEL_2 ) - {//strong attacks can't be interrupted - if ( PM_InAnimForSaberMove( self->client->ps.torsoAnim, self->client->ps.saberMove ) ) - {//our saberMove was not already interupted by some other anim (like pain) - if ( PM_SaberInStart( self->client->ps.saberMove ) ) - { - float animLength = PM_AnimLength( self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.torsoAnim ); - if ( animLength - self->client->ps.torsoAnimTimer > 750 ) - {//start anim is already 3/4 of a second into it, can't interrupt it now +qboolean G_CheckForStrongAttackMomentum(gentity_t *self) { // see if our saber attack has too much momentum to be interrupted + if (PM_PowerLevelForSaberAnim(&self->client->ps) > FORCE_LEVEL_2) { // strong attacks can't be interrupted + if (PM_InAnimForSaberMove(self->client->ps.torsoAnim, + self->client->ps.saberMove)) { // our saberMove was not already interupted by some other anim (like pain) + if (PM_SaberInStart(self->client->ps.saberMove)) { + float animLength = PM_AnimLength(self->client->clientInfo.animFileIndex, (animNumber_t)self->client->ps.torsoAnim); + if (animLength - self->client->ps.torsoAnimTimer > 750) { // start anim is already 3/4 of a second into it, can't interrupt it now return qtrue; } - } - else if ( PM_SaberInReturn( self->client->ps.saberMove ) ) - { - if ( self->client->ps.torsoAnimTimer > 750 ) - {//still have a good amount of time left in the return anim, can't interrupt it + } else if (PM_SaberInReturn(self->client->ps.saberMove)) { + if (self->client->ps.torsoAnimTimer > 750) { // still have a good amount of time left in the return anim, can't interrupt it return qtrue; } - } - else - {//cannot interrupt actual transitions and attacks + } else { // cannot interrupt actual transitions and attacks return qtrue; } } @@ -4205,75 +3298,59 @@ qboolean G_CheckForStrongAttackMomentum( gentity_t *self ) return qfalse; } -void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc ) -{ - if ( self->client->NPC_class == CLASS_ATST ) - {//different kind of pain checking altogether - G_ATSTCheckPain( self, other, point, damage, mod, hitLoc ); - int blasterTest = gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head_light_blaster_cann" ); - int chargerTest = gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "head_concussion_charger" ); - if ( blasterTest && chargerTest ) - {//lost both side guns - //take away that weapon - self->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_ATST_SIDE ); - //switch to primary guns - if ( self->client->ps.weapon == WP_ATST_SIDE ) - { - CG_ChangeWeapon( WP_ATST_MAIN ); +void PlayerPain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + if (self->client->NPC_class == CLASS_ATST) { // different kind of pain checking altogether + G_ATSTCheckPain(self, other, point, damage, mod, hitLoc); + int blasterTest = gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head_light_blaster_cann"); + int chargerTest = gi.G2API_GetSurfaceRenderStatus(&self->ghoul2[self->playerModel], "head_concussion_charger"); + if (blasterTest && chargerTest) { // lost both side guns + // take away that weapon + self->client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_ATST_SIDE); + // switch to primary guns + if (self->client->ps.weapon == WP_ATST_SIDE) { + CG_ChangeWeapon(WP_ATST_MAIN); } } - } - else - { + } else { // play an apropriate pain sound - if ( level.time > self->painDebounceTime && !(self->flags & FL_GODMODE) ) - {//first time hit this frame and not in godmode + if (level.time > self->painDebounceTime && !(self->flags & FL_GODMODE)) { // first time hit this frame and not in godmode self->client->ps.damageEvent++; - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - if ( self->client->damage_blood ) - {//took damage myself, not just armor - G_AddEvent( self, EV_PAIN, self->health ); - } - } - } - if ( damage != -1 && (mod==MOD_MELEE || damage==0/*fake damage*/ || (Q_irand( 0, 10 ) <= damage && self->client->damage_blood)) ) - {//-1 == don't play pain anim - if ( ( ((mod==MOD_SABER||mod==MOD_MELEE)&&self->client->damage_blood) || mod == MOD_CRUSH ) && (self->s.weapon == WP_SABER||self->s.weapon==WP_MELEE) )//FIXME: not only if using saber, but if in third person at all? But then 1st/third person functionality is different... - {//FIXME: only strong-level saber attacks should make me play pain anim? - if ( !G_CheckForStrongAttackMomentum( self ) && !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - {//strong attacks and spins cannot be interrupted by pain, no pain when in knockdown - int parts = SETANIM_BOTH; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && - !PM_SpinningSaberAnim( self->client->ps.legsAnim ) && - !PM_FlippingAnim( self->client->ps.legsAnim ) && - !PM_InSpecialJump( self->client->ps.legsAnim ) && - !PM_RollingAnim( self->client->ps.legsAnim )&& - !PM_CrouchAnim( self->client->ps.legsAnim )&& - !PM_RunningAnim( self->client->ps.legsAnim )) - {//if on a surface and not in a spin or flip, play full body pain + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + if (self->client->damage_blood) { // took damage myself, not just armor + G_AddEvent(self, EV_PAIN, self->health); + } + } + } + if (damage != -1 && + (mod == MOD_MELEE || damage == 0 /*fake damage*/ || (Q_irand(0, 10) <= damage && self->client->damage_blood))) { //-1 == don't play pain anim + if ((((mod == MOD_SABER || mod == MOD_MELEE) && self->client->damage_blood) || mod == MOD_CRUSH) && + (self->s.weapon == WP_SABER || + self->s.weapon == + WP_MELEE)) // FIXME: not only if using saber, but if in third person at all? But then 1st/third person functionality is different... + { // FIXME: only strong-level saber attacks should make me play pain anim? + if (!G_CheckForStrongAttackMomentum(self) && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_SaberInSpecialAttack(self->client->ps.torsoAnim) && + !PM_InKnockDown(&self->client->ps)) { // strong attacks and spins cannot be interrupted by pain, no pain when in knockdown + int parts = SETANIM_BOTH; + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_InSpecialJump(self->client->ps.legsAnim) && + !PM_RollingAnim(self->client->ps.legsAnim) && !PM_CrouchAnim(self->client->ps.legsAnim) && + !PM_RunningAnim(self->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body pain parts = SETANIM_BOTH; - } - else - {//play pain just in torso + } else { // play pain just in torso parts = SETANIM_TORSO; } - if ( self->painDebounceTime < level.time ) - { - //temp HACK: these are the only 2 pain anims that look good when holding a saber - NPC_SetAnim( self, parts, PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = LS_READY;//don't finish whatever saber move you may have been in - //WTF - insn't working - if ( self->health < 10 && d_slowmodeath->integer > 5 ) - { - G_StartMatrixEffect( self ); + if (self->painDebounceTime < level.time) { + // temp HACK: these are the only 2 pain anims that look good when holding a saber + NPC_SetAnim(self, parts, PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3), SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = LS_READY; // don't finish whatever saber move you may have been in + // WTF - insn't working + if (self->health < 10 && d_slowmodeath->integer > 5) { + G_StartMatrixEffect(self); } } - if ( parts == SETANIM_BOTH && (damage > 30 || (self->painDebounceTime > level.time - && damage > 10)) ) - {//took a lot of damage in 1 hit //or took 2 hits in quick succession + if (parts == SETANIM_BOTH && (damage > 30 || (self->painDebounceTime > level.time && + damage > 10))) { // took a lot of damage in 1 hit //or took 2 hits in quick succession self->aimDebounceTime = level.time + self->client->ps.torsoAnimTimer; self->client->ps.pm_time = self->client->ps.torsoAnimTimer; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; @@ -4285,8 +3362,7 @@ void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t } } } - if ( self->painDebounceTime <= level.time ) - { + if (self->painDebounceTime <= level.time) { self->painDebounceTime = level.time + 700; } } @@ -4295,11 +3371,10 @@ void PlayerPain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t CheckArmor ================ */ -int CheckArmor (gentity_t *ent, int damage, int dflags) -{ - gclient_t *client; - int save; - int count; +int CheckArmor(gentity_t *ent, int damage, int dflags) { + gclient_t *client; + int save; + int count; if (!damage) return 0; @@ -4309,53 +3384,40 @@ int CheckArmor (gentity_t *ent, int damage, int dflags) if (!client) return 0; - if ( (dflags&DAMAGE_NO_ARMOR) ) + if ((dflags & DAMAGE_NO_ARMOR)) return 0; - if ( client->NPC_class == CLASS_GALAKMECH ) - {//special case - if ( client->ps.stats[STAT_ARMOR] <= 0 ) - {//no shields + if (client->NPC_class == CLASS_GALAKMECH) { // special case + if (client->ps.stats[STAT_ARMOR] <= 0) { // no shields client->ps.powerups[PW_GALAK_SHIELD] = 0; return 0; - } - else - {//shields take all the damage + } else { // shields take all the damage client->ps.stats[STAT_ARMOR] -= damage; - if ( client->ps.stats[STAT_ARMOR] <= 0 ) - { + if (client->ps.stats[STAT_ARMOR] <= 0) { client->ps.powerups[PW_GALAK_SHIELD] = 0; client->ps.stats[STAT_ARMOR] = 0; } return damage; } - } - else - { + } else { // armor count = client->ps.stats[STAT_ARMOR]; // No damage to entity until armor is at less than 50% strength - if (count > (client->ps.stats[STAT_MAX_HEALTH]/2)) // MAX_HEALTH is considered max armor. Or so I'm told. + if (count > (client->ps.stats[STAT_MAX_HEALTH] / 2)) // MAX_HEALTH is considered max armor. Or so I'm told. { save = damage; - } - else - { - if ( !ent->s.number && client->NPC_class == CLASS_ATST ) - {//player in ATST... armor takes *all* the damage + } else { + if (!ent->s.number && client->NPC_class == CLASS_ATST) { // player in ATST... armor takes *all* the damage save = damage; - } - else - { - save = ceil( (float) damage * ARMOR_PROTECTION ); + } else { + save = ceil((float)damage * ARMOR_PROTECTION); } } - //Always round up - if (damage == 1) - { - if ( client->ps.stats[STAT_ARMOR] > 0 ) + // Always round up + if (damage == 1) { + if (client->ps.stats[STAT_ARMOR] > 0) client->ps.stats[STAT_ARMOR] -= save; return 0; @@ -4373,68 +3435,48 @@ int CheckArmor (gentity_t *ent, int damage, int dflags) } } -extern void NPC_SetPainEvent( gentity_t *self ); -void G_Knockdown( gentity_t *self, gentity_t *attacker, vec3_t pushDir, float strength, qboolean breakSaberLock ) -{ - if ( !self || !self->client || !attacker || !attacker->client ) - { +extern void NPC_SetPainEvent(gentity_t *self); +void G_Knockdown(gentity_t *self, gentity_t *attacker, vec3_t pushDir, float strength, qboolean breakSaberLock) { + if (!self || !self->client || !attacker || !attacker->client) { return; } - //break out of a saberLock? - if ( breakSaberLock ) - { + // break out of a saberLock? + if (breakSaberLock) { self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; } - if ( self->health > 0 ) - { - if ( !self->s.number ) - { - NPC_SetPainEvent( self ); - } - else - { - GEntity_PainFunc( self, attacker, attacker, self->currentOrigin, 0, MOD_MELEE ); + if (self->health > 0) { + if (!self->s.number) { + NPC_SetPainEvent(self); + } else { + GEntity_PainFunc(self, attacker, attacker, self->currentOrigin, 0, MOD_MELEE); } - G_CheckLedgeDive( self, 72, pushDir, qfalse, qfalse ); + G_CheckLedgeDive(self, 72, pushDir, qfalse, qfalse); - if ( !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - { - int knockAnim = BOTH_KNOCKDOWN1;//default knockdown - if ( !self->s.number && ( !g_spskill->integer || strength < 300 ) ) - {//player only knocked down if pushed *hard* + if (!PM_SpinningSaberAnim(self->client->ps.legsAnim) && !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && + !PM_InKnockDown(&self->client->ps)) { + int knockAnim = BOTH_KNOCKDOWN1; // default knockdown + if (!self->s.number && (!g_spskill->integer || strength < 300)) { // player only knocked down if pushed *hard* return; - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - {//crouched knockdown + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { // crouched knockdown knockAnim = BOTH_KNOCKDOWN4; - } - else - {//plain old knockdown - vec3_t pLFwd, pLAngles = {0,self->client->ps.viewangles[YAW],0}; - AngleVectors( pLAngles, pLFwd, NULL, NULL ); - if ( DotProduct( pLFwd, pushDir ) > 0.2f ) - {//pushing him from behind + } else { // plain old knockdown + vec3_t pLFwd, pLAngles = {0, self->client->ps.viewangles[YAW], 0}; + AngleVectors(pLAngles, pLFwd, NULL, NULL); + if (DotProduct(pLFwd, pushDir) > 0.2f) { // pushing him from behind knockAnim = BOTH_KNOCKDOWN3; - } - else - {//pushing him from front + } else { // pushing him from front knockAnim = BOTH_KNOCKDOWN1; } } - if ( knockAnim == BOTH_KNOCKDOWN1 && strength > 150 ) - {//push *hard* + if (knockAnim == BOTH_KNOCKDOWN1 && strength > 150) { // push *hard* knockAnim = BOTH_KNOCKDOWN2; } - NPC_SetAnim( self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->s.number ) - {//randomize getup times - int addTime = Q_irand( -300, 1000 ); + NPC_SetAnim(self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (self->s.number) { // randomize getup times + int addTime = Q_irand(-300, 1000); self->client->ps.legsAnimTimer += addTime; self->client->ps.torsoAnimTimer += addTime; } @@ -4442,130 +3484,97 @@ void G_Knockdown( gentity_t *self, gentity_t *attacker, vec3_t pushDir, float st } } -void G_CheckKnockdown( gentity_t *targ, gentity_t *attacker, vec3_t newDir, int dflags, int mod ) -{ - if ( !targ || !attacker ) - { +void G_CheckKnockdown(gentity_t *targ, gentity_t *attacker, vec3_t newDir, int dflags, int mod) { + if (!targ || !attacker) { return; } - if ( !(dflags&DAMAGE_RADIUS) ) - {//not inherently explosive damage, check mod - if ( mod!=MOD_REPEATER_ALT - &&mod!=MOD_FLECHETTE_ALT - &&mod!=MOD_ROCKET - &&mod!=MOD_ROCKET_ALT - &&mod!=MOD_THERMAL - &&mod!=MOD_THERMAL_ALT - &&mod!=MOD_DETPACK - &&mod!=MOD_LASERTRIP - &&mod!=MOD_LASERTRIP_ALT - &&mod!=MOD_EXPLOSIVE - &&mod!=MOD_EXPLOSIVE_SPLASH ) - { + if (!(dflags & DAMAGE_RADIUS)) { // not inherently explosive damage, check mod + if (mod != MOD_REPEATER_ALT && mod != MOD_FLECHETTE_ALT && mod != MOD_ROCKET && mod != MOD_ROCKET_ALT && mod != MOD_THERMAL && mod != MOD_THERMAL_ALT && + mod != MOD_DETPACK && mod != MOD_LASERTRIP && mod != MOD_LASERTRIP_ALT && mod != MOD_EXPLOSIVE && mod != MOD_EXPLOSIVE_SPLASH) { return; } } - if ( !targ->client || targ->client->NPC_class == CLASS_PROTOCOL || !G_StandardHumanoid( targ->NPC_type ) ) - { + if (!targ->client || targ->client->NPC_class == CLASS_PROTOCOL || !G_StandardHumanoid(targ->NPC_type)) { return; } - if ( targ->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//already in air + if (targ->client->ps.groundEntityNum == ENTITYNUM_NONE) { // already in air return; } - if ( !targ->s.number ) - {//player less likely to be knocked down - if ( !g_spskill->integer ) - {//never in easy + if (!targ->s.number) { // player less likely to be knocked down + if (!g_spskill->integer) { // never in easy return; } - if ( !cg.renderingThirdPerson || cg.zoomMode ) - {//never if not in chase camera view (so more likely with saber out) + if (!cg.renderingThirdPerson || cg.zoomMode) { // never if not in chase camera view (so more likely with saber out) return; } - if ( g_spskill->integer == 1 ) - {//33% chance on medium - if ( Q_irand( 0, 2 ) ) - { + if (g_spskill->integer == 1) { // 33% chance on medium + if (Q_irand(0, 2)) { return; } - } - else - {//50% chance on hard - if ( Q_irand( 0, 1 ) ) - { + } else { // 50% chance on hard + if (Q_irand(0, 1)) { return; } } } - float strength = VectorLength( targ->client->ps.velocity ); - if ( targ->client->ps.velocity[2] > 100 && strength > Q_irand( 150, 350 ) )//600 ) ) - {//explosive concussion possibly do a knockdown? - G_Knockdown( targ, attacker, newDir, strength, qtrue ); + float strength = VectorLength(targ->client->ps.velocity); + if (targ->client->ps.velocity[2] > 100 && strength > Q_irand(150, 350)) // 600 ) ) + { // explosive concussion possibly do a knockdown? + G_Knockdown(targ, attacker, newDir, strength, qtrue); } } -void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) -{ - vec3_t kvel; - float mass; +void G_ApplyKnockback(gentity_t *targ, vec3_t newDir, float knockback) { + vec3_t kvel; + float mass; //--- TEMP TEST - if ( newDir[2] <= 0.0f ) - { + if (newDir[2] <= 0.0f) { - newDir[2] += (( 0.0f - newDir[2] ) * 1.2f ); + newDir[2] += ((0.0f - newDir[2]) * 1.2f); } knockback *= 2.0f; - if ( knockback > 120 ) - { + if (knockback > 120) { knockback = 120; } //--- TEMP TEST - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass mass = targ->physicsBounce; else mass = 200; - if ( g_gravity->value > 0 ) - { - VectorScale( newDir, g_knockback->value * (float)knockback / mass * 0.8, kvel ); - kvel[2] = newDir[2] * ( g_knockback->value * (float)knockback ) / ( mass * 1.5 ) + 20; - } - else - { - VectorScale( newDir, g_knockback->value * (float)knockback / mass, kvel ); + if (g_gravity->value > 0) { + VectorScale(newDir, g_knockback->value * (float)knockback / mass * 0.8, kvel); + kvel[2] = newDir[2] * (g_knockback->value * (float)knockback) / (mass * 1.5) + 20; + } else { + VectorScale(newDir, g_knockback->value * (float)knockback / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = knockback * 2; - if ( t < 50 ) { + if (t < 50) { t = 50; } - if ( t > 200 ) { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -4573,54 +3582,47 @@ void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) } } -static int G_CheckForLedge( gentity_t *self, vec3_t fallCheckDir, float checkDist ) -{ - vec3_t start, end; - trace_t tr; +static int G_CheckForLedge(gentity_t *self, vec3_t fallCheckDir, float checkDist) { + vec3_t start, end; + trace_t tr; - VectorMA( self->currentOrigin, checkDist, fallCheckDir, end ); - //Should have clip burshes masked out by now and have bbox resized to death size - gi.trace( &tr, self->currentOrigin, self->mins, self->maxs, end, self->s.number, self->clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + VectorMA(self->currentOrigin, checkDist, fallCheckDir, end); + // Should have clip burshes masked out by now and have bbox resized to death size + gi.trace(&tr, self->currentOrigin, self->mins, self->maxs, end, self->s.number, self->clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { return 0; } - VectorCopy( tr.endpos, start ); - VectorCopy( start, end ); + VectorCopy(tr.endpos, start); + VectorCopy(start, end); end[2] -= 256; - gi.trace( &tr, start, self->mins, self->maxs, end, self->s.number, self->clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + gi.trace(&tr, start, self->mins, self->maxs, end, self->s.number, self->clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { return 0; } - if ( tr.fraction >= 1.0 ) - { - return (start[2]-tr.endpos[2]); + if (tr.fraction >= 1.0) { + return (start[2] - tr.endpos[2]); } return 0; } -static void G_FriendlyFireReaction( gentity_t *self, gentity_t *other, int dflags ) -{ - if ( (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) - {//hit by a teammate - if ( other != self->enemy && self != other->enemy ) - {//we weren't already enemies - if ( self->enemy || other->enemy || (other->s.number&&other->s.number!=player->client->ps.viewEntity) ) - {//if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad (FIXME:accumulate anger+base on diff?) +static void G_FriendlyFireReaction(gentity_t *self, gentity_t *other, int dflags) { + if ((!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)) { // hit by a teammate + if (other != self->enemy && self != other->enemy) { // we weren't already enemies + if (self->enemy || other->enemy || + (other->s.number && + other->s.number != player->client->ps.viewEntity)) { // if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit + // by player or someone controlled by player OR player hit ally and didn't get 25% chance + // of getting mad (FIXME:accumulate anger+base on diff?) return; - } - else if ( self->NPC && !other->s.number )//should be assumed, but... - {//dammit, stop that! - if ( !(dflags&DAMAGE_RADIUS) ) - { - //if it's radius damage, ignore it - if ( self->NPC->ffireDebounce < level.time ) - { - //FIXME: way something? NEED DIALOGUE + } else if (self->NPC && !other->s.number) // should be assumed, but... + { // dammit, stop that! + if (!(dflags & DAMAGE_RADIUS)) { + // if it's radius damage, ignore it + if (self->NPC->ffireDebounce < level.time) { + // FIXME: way something? NEED DIALOGUE self->NPC->ffireCount++; - //Com_Printf( "incr: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); + // Com_Printf( "incr: %d < %d\n", self->NPC->ffireCount, 3+((2-g_spskill->integer)*2) ); self->NPC->ffireDebounce = level.time + 500; } } @@ -4629,52 +3631,46 @@ static void G_FriendlyFireReaction( gentity_t *self, gentity_t *other, int dflag } } -float damageModifier[HL_MAX] = -{ - 1.0f, //HL_NONE, - 0.25f, //HL_FOOT_RT, - 0.25f, //HL_FOOT_LT, - 0.75f, //HL_LEG_RT, - 0.75f, //HL_LEG_LT, - 1.0f, //HL_WAIST, - 1.0f, //HL_BACK_RT, - 1.0f, //HL_BACK_LT, - 1.0f, //HL_BACK, - 1.0f, //HL_CHEST_RT, - 1.0f, //HL_CHEST_LT, - 1.0f, //HL_CHEST, - 0.5f, //HL_ARM_RT, - 0.5f, //HL_ARM_LT, - 0.25f, //HL_HAND_RT, - 0.25f, //HL_HAND_LT, - 2.0f, //HL_HEAD, - 1.0f, //HL_GENERIC1, - 1.0f, //HL_GENERIC2, - 1.0f, //HL_GENERIC3, - 1.0f, //HL_GENERIC4, - 1.0f, //HL_GENERIC5, - 1.0f, //HL_GENERIC6, +float damageModifier[HL_MAX] = { + 1.0f, // HL_NONE, + 0.25f, // HL_FOOT_RT, + 0.25f, // HL_FOOT_LT, + 0.75f, // HL_LEG_RT, + 0.75f, // HL_LEG_LT, + 1.0f, // HL_WAIST, + 1.0f, // HL_BACK_RT, + 1.0f, // HL_BACK_LT, + 1.0f, // HL_BACK, + 1.0f, // HL_CHEST_RT, + 1.0f, // HL_CHEST_LT, + 1.0f, // HL_CHEST, + 0.5f, // HL_ARM_RT, + 0.5f, // HL_ARM_LT, + 0.25f, // HL_HAND_RT, + 0.25f, // HL_HAND_LT, + 2.0f, // HL_HEAD, + 1.0f, // HL_GENERIC1, + 1.0f, // HL_GENERIC2, + 1.0f, // HL_GENERIC3, + 1.0f, // HL_GENERIC4, + 1.0f, // HL_GENERIC5, + 1.0f, // HL_GENERIC6, }; -void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod ) -{ - if ( !self || !self->client || self->s.number ) - {//player only +void G_TrackWeaponUsage(gentity_t *self, gentity_t *inflictor, int add, int mod) { + if (!self || !self->client || self->s.number) { // player only return; } int weapon = WP_NONE; - //FIXME: need to check the MOD to find out what weapon (if *any*) actually did the killing - if ( inflictor && !inflictor->client && mod != MOD_SABER && inflictor->lastEnemy && inflictor->lastEnemy != self ) - {//a missile that was reflected, ie: not owned by me originally - if ( inflictor->owner == self && self->s.weapon == WP_SABER ) - {//we reflected it + // FIXME: need to check the MOD to find out what weapon (if *any*) actually did the killing + if (inflictor && !inflictor->client && mod != MOD_SABER && inflictor->lastEnemy && + inflictor->lastEnemy != self) { // a missile that was reflected, ie: not owned by me originally + if (inflictor->owner == self && self->s.weapon == WP_SABER) { // we reflected it weapon = WP_SABER; } } - if ( weapon == WP_NONE ) - { - switch ( mod ) - { + if (weapon == WP_NONE) { + switch (mod) { case MOD_SABER: weapon = WP_SABER; break; @@ -4722,41 +3718,24 @@ void G_TrackWeaponUsage( gentity_t *self, gentity_t *inflictor, int add, int mod weapon = WP_TRIP_MINE; break; case MOD_MELEE: - if ( self->s.weapon == WP_STUN_BATON ) - { + if (self->s.weapon == WP_STUN_BATON) { weapon = WP_STUN_BATON; - } - else if ( self->s.weapon == WP_MELEE ) - { + } else if (self->s.weapon == WP_MELEE) { weapon = WP_MELEE; } break; } } - if ( weapon != WP_NONE ) - { + if (weapon != WP_NONE) { self->client->sess.missionStats.weaponUsed[weapon] += add; } } -qboolean G_NonLocationSpecificDamage( int meansOfDeath ) -{ - if ( meansOfDeath == MOD_EXPLOSIVE - || meansOfDeath == MOD_REPEATER_ALT - || meansOfDeath == MOD_FLECHETTE_ALT - || meansOfDeath == MOD_ROCKET - || meansOfDeath == MOD_ROCKET_ALT - || meansOfDeath == MOD_THERMAL - || meansOfDeath == MOD_THERMAL_ALT - || meansOfDeath == MOD_DETPACK - || meansOfDeath == MOD_LASERTRIP - || meansOfDeath == MOD_LASERTRIP_ALT - || meansOfDeath == MOD_MELEE - || meansOfDeath == MOD_FORCE_GRIP - || meansOfDeath == MOD_KNOCKOUT - || meansOfDeath == MOD_CRUSH - || meansOfDeath == MOD_EXPLOSIVE_SPLASH ) - { +qboolean G_NonLocationSpecificDamage(int meansOfDeath) { + if (meansOfDeath == MOD_EXPLOSIVE || meansOfDeath == MOD_REPEATER_ALT || meansOfDeath == MOD_FLECHETTE_ALT || meansOfDeath == MOD_ROCKET || + meansOfDeath == MOD_ROCKET_ALT || meansOfDeath == MOD_THERMAL || meansOfDeath == MOD_THERMAL_ALT || meansOfDeath == MOD_DETPACK || + meansOfDeath == MOD_LASERTRIP || meansOfDeath == MOD_LASERTRIP_ALT || meansOfDeath == MOD_MELEE || meansOfDeath == MOD_FORCE_GRIP || + meansOfDeath == MOD_KNOCKOUT || meansOfDeath == MOD_CRUSH || meansOfDeath == MOD_EXPLOSIVE_SPLASH) { return qtrue; } return qfalse; @@ -4786,227 +3765,170 @@ dflags these flags are used to control how T_Damage works ============ */ -void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod, int hitLoc ) -{ - gclient_t *client; - int take; - int asave = 0; - int knockback; - vec3_t newDir; - qboolean alreadyDead = qfalse; +void G_Damage(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod, int hitLoc) { + gclient_t *client; + int take; + int asave = 0; + int knockback; + vec3_t newDir; + qboolean alreadyDead = qfalse; if (!targ->takedamage) { return; } - if ( targ->health <= 0 && !targ->client ) - { // allow corpses to be disintegrated - if( mod != MOD_SNIPER || (targ->flags & FL_DISINTEGRATED) ) - return; + if (targ->health <= 0 && !targ->client) { // allow corpses to be disintegrated + if (mod != MOD_SNIPER || (targ->flags & FL_DISINTEGRATED)) + return; } // if we are the player and we are locked to an emplaced gun, we have to reroute damage to the gun....sigh. - if ( targ->s.eFlags & EF_LOCKED_TO_WEAPON && targ->s.number == 0 && targ->owner && !( targ->owner->flags & FL_GODMODE )) - { + if (targ->s.eFlags & EF_LOCKED_TO_WEAPON && targ->s.number == 0 && targ->owner && !(targ->owner->flags & FL_GODMODE)) { // swapping the gun into our place to absorb our damage targ = targ->owner; } - if ( (targ->flags&FL_SHIELDED) && mod != MOD_SABER && !targ->client) - {//magnetically protected, this thing can only be damaged by lightsabers + if ((targ->flags & FL_SHIELDED) && mod != MOD_SABER && !targ->client) { // magnetically protected, this thing can only be damaged by lightsabers return; } - if ( (targ->flags&FL_DMG_BY_SABER_ONLY) && mod != MOD_SABER ) - {//can only be damaged by lightsabers (but no shield... yeah, it's redundant, but whattayagonnado?) + if ((targ->flags & FL_DMG_BY_SABER_ONLY) && + mod != MOD_SABER) { // can only be damaged by lightsabers (but no shield... yeah, it's redundant, but whattayagonnado?) return; } - if (( targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY ) && !( dflags & DAMAGE_HEAVY_WEAP_CLASS )) - { + if ((targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) && !(dflags & DAMAGE_HEAVY_WEAP_CLASS)) { // can only be damaged by an heavy type weapon...but impacting missile was in the heavy weap class...so we just aren't taking damage from this missile return; } - if ( targ->client && targ->client->NPC_class == CLASS_ATST ) - { + if (targ->client && targ->client->NPC_class == CLASS_ATST) { // extra checks can be done here - if ( mod == MOD_SNIPER || mod == MOD_DISRUPTOR ) - { + if (mod == MOD_SNIPER || mod == MOD_DISRUPTOR) { // disruptor does not hurt an atst return; } } - if ( mod == MOD_SABER ) - {//sabers do less damage to mark1's and atst's - if ( targ->client && (targ->client->NPC_class == CLASS_ATST || targ->client->NPC_class == CLASS_MARK1) ) - { + if (mod == MOD_SABER) { // sabers do less damage to mark1's and atst's + if (targ->client && (targ->client->NPC_class == CLASS_ATST || targ->client->NPC_class == CLASS_MARK1)) { // I guess always do 5 points of damage...feel free to tweak as needed - if ( damage > 5 ) - { + if (damage > 5) { damage = 5; } } } - if ( !inflictor ) { + if (!inflictor) { inflictor = &g_entities[ENTITYNUM_WORLD]; } - if ( !attacker ) { + if (!attacker) { attacker = &g_entities[ENTITYNUM_WORLD]; } // no more weakling allies! -// if ( attacker->s.number != 0 && damage >= 2 && targ->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) -// {//player-helpers do only half damage to enemies -// damage = ceil((float)damage/2.0f); -// } + // if ( attacker->s.number != 0 && damage >= 2 && targ->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_PLAYER ) + // {//player-helpers do only half damage to enemies + // damage = ceil((float)damage/2.0f); + // } client = targ->client; - if ( client ) { - if ( client->noclip && !targ->s.number ) { + if (client) { + if (client->noclip && !targ->s.number) { return; } } - if ( dflags&DAMAGE_NO_DAMAGE ) - { + if (dflags & DAMAGE_NO_DAMAGE) { damage = 0; } - if ( dir == NULL ) - { + if (dir == NULL) { dflags |= DAMAGE_NO_KNOCKBACK; - } - else - { - VectorNormalize2( dir, newDir ); + } else { + VectorNormalize2(dir, newDir); } - if ( targ->s.number != 0 ) - {//not the player - if ( (targ->flags&FL_GODMODE) || (targ->flags&FL_UNDYING) ) - {//have god or undying on, so ignore no protection flag + if (targ->s.number != 0) { // not the player + if ((targ->flags & FL_GODMODE) || (targ->flags & FL_UNDYING)) { // have god or undying on, so ignore no protection flag dflags &= ~DAMAGE_NO_PROTECTION; } } - if ( client && PM_InOnGroundAnim( &client->ps )) - { + if (client && PM_InOnGroundAnim(&client->ps)) { dflags |= DAMAGE_NO_KNOCKBACK; } - if ( !attacker->s.number && targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam ) - {//player doesn't do knockback against allies unless he kills them + if (!attacker->s.number && targ->client && attacker->client && + targ->client->playerTeam == attacker->client->playerTeam) { // player doesn't do knockback against allies unless he kills them dflags |= DAMAGE_DEATH_KNOCKBACK; } - if ( client && client->NPC_class == CLASS_GALAKMECH ) - {//hit Galak - if ( client->ps.stats[STAT_ARMOR] > 0 ) - {//shields are up - dflags &= ~DAMAGE_NO_ARMOR;//always affect armor - if ( mod == MOD_ELECTROCUTE - || mod == MOD_DEMP2 - || mod == MOD_DEMP2_ALT ) - {//shield protects us from this + if (client && client->NPC_class == CLASS_GALAKMECH) { // hit Galak + if (client->ps.stats[STAT_ARMOR] > 0) { // shields are up + dflags &= ~DAMAGE_NO_ARMOR; // always affect armor + if (mod == MOD_ELECTROCUTE || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { // shield protects us from this damage = 0; } - } - else - {//shields down - if ( mod == MOD_MELEE - || (mod == MOD_CRUSH && attacker && attacker->client) ) - {//Galak takes no impact damage + } else { // shields down + if (mod == MOD_MELEE || (mod == MOD_CRUSH && attacker && attacker->client)) { // Galak takes no impact damage return; } - if ( (dflags & DAMAGE_RADIUS) - || mod == MOD_REPEATER_ALT - || mod == MOD_FLECHETTE_ALT - || mod == MOD_ROCKET - || mod == MOD_ROCKET_ALT - || mod == MOD_THERMAL - || mod == MOD_THERMAL_ALT - || mod == MOD_DETPACK - || mod == MOD_LASERTRIP - || mod == MOD_LASERTRIP_ALT - || mod == MOD_EXPLOSIVE_SPLASH - || mod == MOD_ENERGY_SPLASH - || mod == MOD_SABER ) - {//galak without shields takes quarter damage from explosives and lightsaber - damage = ceil((float)damage/4.0f); + if ((dflags & DAMAGE_RADIUS) || mod == MOD_REPEATER_ALT || mod == MOD_FLECHETTE_ALT || mod == MOD_ROCKET || mod == MOD_ROCKET_ALT || + mod == MOD_THERMAL || mod == MOD_THERMAL_ALT || mod == MOD_DETPACK || mod == MOD_LASERTRIP || mod == MOD_LASERTRIP_ALT || + mod == MOD_EXPLOSIVE_SPLASH || mod == MOD_ENERGY_SPLASH || + mod == MOD_SABER) { // galak without shields takes quarter damage from explosives and lightsaber + damage = ceil((float)damage / 4.0f); } } } - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { - if ( client ) - { - if ( client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || - client->NPC_class == CLASS_R2D2 || client->NPC_class == CLASS_R5D2 || - client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { + if (client) { + if (client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || client->NPC_class == CLASS_R2D2 || + client->NPC_class == CLASS_R5D2 || client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK) { // DEMP2 does more damage to these guys. damage *= 2; - } - else if ( client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || - client->NPC_class == CLASS_MARK1 || client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || - client->NPC_class == CLASS_ATST ) - { + } else if (client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || client->NPC_class == CLASS_MARK1 || + client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || client->NPC_class == CLASS_ATST) { // DEMP2 does way more damage to these guys. damage *= 5; } - } - else if ( targ->s.weapon == WP_TURRET ) - { - damage *= 6;// more damage to turret things + } else if (targ->s.weapon == WP_TURRET) { + damage *= 6; // more damage to turret things } } knockback = damage; - //Attempt to apply extra knockback - if ( dflags & DAMAGE_EXTRA_KNOCKBACK ) - { + // Attempt to apply extra knockback + if (dflags & DAMAGE_EXTRA_KNOCKBACK) { knockback *= 2; } - if ( knockback > 200 ) { + if (knockback > 200) { knockback = 200; } - if ( mod == MOD_CRUSH ) - { + if (mod == MOD_CRUSH) { knockback = 0; - } - else if ( targ->flags & FL_NO_KNOCKBACK ) - { + } else if (targ->flags & FL_NO_KNOCKBACK) { knockback = 0; - } - else if ( targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam ) - { + } else if (targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam) { knockback = 0; - } - else if ( dflags & DAMAGE_NO_KNOCKBACK ) - { + } else if (dflags & DAMAGE_NO_KNOCKBACK) { knockback = 0; } // figure momentum add, even if the damage won't be taken - if ( knockback && !(dflags&DAMAGE_DEATH_KNOCKBACK) ) //&& targ->client + if (knockback && !(dflags & DAMAGE_DEATH_KNOCKBACK)) //&& targ->client { - G_ApplyKnockback( targ, newDir, knockback ); - G_CheckKnockdown( targ, attacker, newDir, dflags, mod ); + G_ApplyKnockback(targ, newDir, knockback); + G_CheckKnockdown(targ, attacker, newDir, dflags, mod); } // check for godmode, completely getting out of the damage - if ( targ->flags & FL_GODMODE && !(dflags&DAMAGE_NO_PROTECTION) ) - { - if ( targ->client - && attacker->client - && targ->client->playerTeam == attacker->client->playerTeam - && (!targ->NPC || !targ->NPC->charmedTime) ) - {//complain, but don't turn on them - G_FriendlyFireReaction( targ, attacker, dflags ); + if (targ->flags & FL_GODMODE && !(dflags & DAMAGE_NO_PROTECTION)) { + if (targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam && + (!targ->NPC || !targ->NPC->charmedTime)) { // complain, but don't turn on them + G_FriendlyFireReaction(targ, attacker, dflags); } return; } @@ -5045,18 +3967,18 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ */ // add to the attacker's hit counter - if ( attacker->client && targ != attacker && targ->health > 0 ) { - if ( OnSameTeam( targ, attacker ) ) { -// attacker->client->ps.persistant[PERS_HITS] -= damage; + if (attacker->client && targ != attacker && targ->health > 0) { + if (OnSameTeam(targ, attacker)) { + // attacker->client->ps.persistant[PERS_HITS] -= damage; } else { -// attacker->client->ps.persistant[PERS_HITS] += damage; + // attacker->client->ps.persistant[PERS_HITS] += damage; } } take = damage; - //FIXME: Do not use this method of difficulty changing - // Scale the amount of damage given to the player based on the skill setting + // FIXME: Do not use this method of difficulty changing + // Scale the amount of damage given to the player based on the skill setting /* if ( targ->s.number == 0 && targ != attacker ) { @@ -5067,324 +3989,257 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ take = 1; } */ - if ( client ) - { - //don't lose armor if on same team - // save some from armor - asave = CheckArmor (targ, take, dflags); - if ( !asave ) - {//all out of armor + if (client) { + // don't lose armor if on same team + // save some from armor + asave = CheckArmor(targ, take, dflags); + if (!asave) { // all out of armor targ->client->ps.powerups[PW_BATTLESUIT] = 0; - } - else - { + } else { targ->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; } take -= asave; } - if ( !(dflags&DAMAGE_NO_HIT_LOC) || !(dflags&DAMAGE_RADIUS)) - { - if ( !G_NonLocationSpecificDamage( mod ) ) - {//certain kinds of damage don't care about hitlocation - take = ceil( (float)take*damageModifier[hitLoc] ); + if (!(dflags & DAMAGE_NO_HIT_LOC) || !(dflags & DAMAGE_RADIUS)) { + if (!G_NonLocationSpecificDamage(mod)) { // certain kinds of damage don't care about hitlocation + take = ceil((float)take * damageModifier[hitLoc]); } } - if ( g_debugDamage->integer ) { - gi.Printf( "[%d]client:%i health:%i damage:%i armor:%i hitloc:%s\n", level.time, targ->s.number, targ->health, take, asave, hitLocName[hitLoc] ); + if (g_debugDamage->integer) { + gi.Printf("[%d]client:%i health:%i damage:%i armor:%i hitloc:%s\n", level.time, targ->s.number, targ->health, take, asave, hitLocName[hitLoc]); } // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame - if ( client ) { - client->ps.persistant[PERS_ATTACKER] = attacker->s.number; //attack can be the world ent + if (client) { + client->ps.persistant[PERS_ATTACKER] = attacker->s.number; // attack can be the world ent client->damage_armor += asave; client->damage_blood += take; client->damage_knockback += knockback; - if ( dir ) { //can't check newdir since it's local, newdir is dir normalized - VectorCopy ( newDir, client->damage_from ); + if (dir) { // can't check newdir since it's local, newdir is dir normalized + VectorCopy(newDir, client->damage_from); client->damage_fromWorld = qfalse; } else { - VectorCopy ( targ->currentOrigin, client->damage_from ); + VectorCopy(targ->currentOrigin, client->damage_from); client->damage_fromWorld = qtrue; } } // do the damage - if ( targ->health <= 0 ) - { + if (targ->health <= 0) { alreadyDead = qtrue; } - if ( attacker && attacker->client && !attacker->s.number ) - { - if ( !alreadyDead ) - { + if (attacker && attacker->client && !attacker->s.number) { + if (!alreadyDead) { int add; - if ( take > targ->health ) - { + if (take > targ->health) { add = targ->health; - } - else - { + } else { add = take; } add += asave; - add = ceil(add/10.0f); - if ( attacker != targ ) - { - G_TrackWeaponUsage( attacker, inflictor, add, mod ); + add = ceil(add / 10.0f); + if (attacker != targ) { + G_TrackWeaponUsage(attacker, inflictor, add, mod); } } } - if ( take || (dflags&DAMAGE_NO_DAMAGE) ) - { - if ( !targ->client || !attacker->client ) - { + if (take || (dflags & DAMAGE_NO_DAMAGE)) { + if (!targ->client || !attacker->client) { targ->health = targ->health - take; - if (targ->health < 0) - { + if (targ->health < 0) { targ->health = 0; } - if ( !alreadyDead && ( ((targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION)) || (dflags&DAMAGE_NO_KILL)) ) - { - if(targ->health < 1) - { - G_ActivateBehavior( targ, BSET_DEATH ); + if (!alreadyDead && (((targ->flags & FL_UNDYING) && !(dflags & DAMAGE_NO_PROTECTION)) || (dflags & DAMAGE_NO_KILL))) { + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } } - } - else - {//two clients - team_t targTeam = TEAM_FREE; - team_t attackerTeam = TEAM_FREE; + } else { // two clients + team_t targTeam = TEAM_FREE; + team_t attackerTeam = TEAM_FREE; - if ( player->client->ps.viewEntity && targ->s.number == player->client->ps.viewEntity ) - { + if (player->client->ps.viewEntity && targ->s.number == player->client->ps.viewEntity) { targTeam = player->client->playerTeam; - } - else if ( targ->client ) { + } else if (targ->client) { targTeam = targ->client->playerTeam; - } - else { + } else { targTeam = targ->noDamageTeam; } - // if ( targTeam == TEAM_DISGUISE ) { - // targTeam = TEAM_PLAYER; - // } - if ( player->client->ps.viewEntity && attacker->s.number == player->client->ps.viewEntity ) - { + // if ( targTeam == TEAM_DISGUISE ) { + // targTeam = TEAM_PLAYER; + // } + if (player->client->ps.viewEntity && attacker->s.number == player->client->ps.viewEntity) { attackerTeam = player->client->playerTeam; - } - else if ( attacker->client ) { + } else if (attacker->client) { attackerTeam = attacker->client->playerTeam; - } - else { + } else { attackerTeam = attacker->noDamageTeam; } - // if ( attackerTeam == TEAM_DISGUISE ) { - // attackerTeam = TEAM_PLAYER; - // } + // if ( attackerTeam == TEAM_DISGUISE ) { + // attackerTeam = TEAM_PLAYER; + // } - if ( targTeam != attackerTeam ) - {//on the same team + if (targTeam != attackerTeam) { // on the same team targ->health = targ->health - take; - //MCG - Falling should never kill player- only if a trigger_hurt does so. - if ( mod == MOD_FALLING && targ->s.number == 0 && targ->health < 1 ) - { + // MCG - Falling should never kill player- only if a trigger_hurt does so. + if (mod == MOD_FALLING && targ->s.number == 0 && targ->health < 1) { targ->health = 1; - } - else if (targ->health < 0) - { + } else if (targ->health < 0) { targ->health = 0; } - if ( !alreadyDead && ( ((targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION)) || (dflags&DAMAGE_NO_KILL) ) ) - { - if ( targ->health < 1 ) - { - G_ActivateBehavior( targ, BSET_DEATH ); + if (!alreadyDead && (((targ->flags & FL_UNDYING) && !(dflags & DAMAGE_NO_PROTECTION)) || (dflags & DAMAGE_NO_KILL))) { + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } - } - else if ( targ->health < 1 && attacker->client ) - { // The player or NPC just killed an enemy so increment the kills counter + } else if (targ->health < 1 && attacker->client) { // The player or NPC just killed an enemy so increment the kills counter attacker->client->ps.persistant[PERS_ENEMIES_KILLED]++; } - } - else if ( targTeam == TEAM_PLAYER ) - {//on the same team, and target is an ally + } else if (targTeam == TEAM_PLAYER) { // on the same team, and target is an ally qboolean takeDamage = qtrue; qboolean yellAtAttacker = qtrue; - //1) player doesn't take damage from teammates unless they're angry at him - if ( targ->s.number == 0 ) - {//the player - if ( attacker->enemy != targ && attacker != targ ) - {//an NPC shot the player by accident + // 1) player doesn't take damage from teammates unless they're angry at him + if (targ->s.number == 0) { // the player + if (attacker->enemy != targ && attacker != targ) { // an NPC shot the player by accident takeDamage = qfalse; } } - //2) NPCs don't take any damage from player during combat - else - {//an NPC - if ( ((dflags & DAMAGE_RADIUS)) && !(dflags&DAMAGE_IGNORE_TEAM) ) - {//An NPC got hit by player and this is during combat or it was slash damage - //NOTE: though it's not realistic to have teammates not take splash damage, + // 2) NPCs don't take any damage from player during combat + else { // an NPC + if (((dflags & DAMAGE_RADIUS)) && + !(dflags & DAMAGE_IGNORE_TEAM)) { // An NPC got hit by player and this is during combat or it was slash damage + // NOTE: though it's not realistic to have teammates not take splash damage, // even when not in combat, it feels really bad to have them able to // actually be killed by the player's splash damage takeDamage = qfalse; } - if ( (dflags & DAMAGE_RADIUS) ) - {//you're fighting and it's just radius damage, so don't even mention it + if ((dflags & DAMAGE_RADIUS)) { // you're fighting and it's just radius damage, so don't even mention it yellAtAttacker = qfalse; } } - if ( takeDamage ) - { + if (takeDamage) { targ->health = targ->health - take; - if ( !alreadyDead && (((targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION) && attacker->s.number != 0) || (dflags&DAMAGE_NO_KILL) ) ) - {//guy is marked undying and we're not the player or we're in combat - if ( targ->health < 1 ) - { - G_ActivateBehavior( targ, BSET_DEATH ); + if (!alreadyDead && (((targ->flags & FL_UNDYING) && !(dflags & DAMAGE_NO_PROTECTION) && attacker->s.number != 0) || + (dflags & DAMAGE_NO_KILL))) { // guy is marked undying and we're not the player or we're in combat + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } - } - else if ( !alreadyDead && (((targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION) && !attacker->s.number && !targ->s.number) || (dflags&DAMAGE_NO_KILL)) ) - {// player is undying and he's attacking himself, don't let him die - if ( targ->health < 1 ) - { - G_ActivateBehavior( targ, BSET_DEATH ); + } else if (!alreadyDead && (((targ->flags & FL_UNDYING) && !(dflags & DAMAGE_NO_PROTECTION) && !attacker->s.number && !targ->s.number) || + (dflags & DAMAGE_NO_KILL))) { // player is undying and he's attacking himself, don't let him die + if (targ->health < 1) { + G_ActivateBehavior(targ, BSET_DEATH); targ->health = 1; } - } - else if ( targ->health < 0 ) - { + } else if (targ->health < 0) { targ->health = 0; - if ( attacker->s.number == 0 && targ->NPC ) - { + if (attacker->s.number == 0 && targ->NPC) { targ->NPC->scriptFlags |= SCF_FFDEATH; } } } - if ( yellAtAttacker ) - { - if ( !targ->NPC || !targ->NPC->charmedTime ) - { - G_FriendlyFireReaction( targ, attacker, dflags ); + if (yellAtAttacker) { + if (!targ->NPC || !targ->NPC->charmedTime) { + G_FriendlyFireReaction(targ, attacker, dflags); } } } } - if ( targ->client ) { + if (targ->client) { targ->client->ps.stats[STAT_HEALTH] = targ->health; g_lastClientDamaged = targ; } - //TEMP HACK FOR PLAYER LOOK AT ENEMY CODE - //FIXME: move this to a player pain func? - if ( targ->s.number == 0 ) - { - if ( !targ->enemy //player does not have an enemy yet - || targ->enemy->s.weapon != WP_SABER //or player's enemy is not a jedi - || attacker->s.weapon == WP_SABER )//and attacker is a jedi - //keep enemy jedi over shooters + // TEMP HACK FOR PLAYER LOOK AT ENEMY CODE + // FIXME: move this to a player pain func? + if (targ->s.number == 0) { + if (!targ->enemy // player does not have an enemy yet + || targ->enemy->s.weapon != WP_SABER // or player's enemy is not a jedi + || attacker->s.weapon == WP_SABER) // and attacker is a jedi + // keep enemy jedi over shooters { - if ( attacker->enemy == targ || !OnSameTeam( targ, attacker ) ) - {//don't set player's enemy to teammates that hit him by accident + if (attacker->enemy == targ || !OnSameTeam(targ, attacker)) { // don't set player's enemy to teammates that hit him by accident targ->enemy = attacker; } - NPC_SetLookTarget( targ, attacker->s.number, level.time+1000 ); + NPC_SetLookTarget(targ, attacker->s.number, level.time + 1000); } - } - else if ( attacker->s.number == 0 && (!targ->NPC || !targ->NPC->timeOfDeath) && (mod == MOD_SABER || attacker->s.weapon != WP_SABER || !attacker->enemy || attacker->enemy->s.weapon != WP_SABER) )//keep enemy jedi over shooters - {//this looks dumb when they're on the ground and you keep hitting them, so only do this when first kill them - if ( !OnSameTeam( targ, attacker ) ) - {//don't set player's enemy to teammates that he hits by accident + } else if (attacker->s.number == 0 && (!targ->NPC || !targ->NPC->timeOfDeath) && + (mod == MOD_SABER || attacker->s.weapon != WP_SABER || !attacker->enemy || + attacker->enemy->s.weapon != WP_SABER)) // keep enemy jedi over shooters + { // this looks dumb when they're on the ground and you keep hitting them, so only do this when first kill them + if (!OnSameTeam(targ, attacker)) { // don't set player's enemy to teammates that he hits by accident attacker->enemy = targ; } - NPC_SetLookTarget( attacker, targ->s.number, level.time+1000 ); + NPC_SetLookTarget(attacker, targ->s.number, level.time + 1000); } - //TEMP HACK FOR PLAYER LOOK AT ENEMY CODE + // TEMP HACK FOR PLAYER LOOK AT ENEMY CODE - //add up the damage to the location - if ( targ->client ) - { - if ( targ->locationDamage[hitLoc] < Q3_INFINITE ) - { + // add up the damage to the location + if (targ->client) { + if (targ->locationDamage[hitLoc] < Q3_INFINITE) { targ->locationDamage[hitLoc] += take; } } - if ( targ->health > 0 && targ->NPC && targ->NPC->surrenderTime > level.time ) - {//he was surrendering, goes down with one hit + if (targ->health > 0 && targ->NPC && targ->NPC->surrenderTime > level.time) { // he was surrendering, goes down with one hit targ->health = 0; } - if ( targ->health <= 0 ) - { - if ( knockback && (dflags&DAMAGE_DEATH_KNOCKBACK) )//&& targ->client - {//only do knockback on death - if ( mod == MOD_FLECHETTE ) - {//special case because this is shotgun-ish damage, we need to multiply the knockback - knockback *= 12;//*6 for 6 flechette shots + if (targ->health <= 0) { + if (knockback && (dflags & DAMAGE_DEATH_KNOCKBACK)) //&& targ->client + { // only do knockback on death + if (mod == MOD_FLECHETTE) { // special case because this is shotgun-ish damage, we need to multiply the knockback + knockback *= 12; //*6 for 6 flechette shots } - G_ApplyKnockback( targ, newDir, knockback ); + G_ApplyKnockback(targ, newDir, knockback); } - if ( client ) + if (client) targ->flags |= FL_NO_KNOCKBACK; if (targ->health < -999) targ->health = -999; // If we are a breaking glass brush, store the damage point so we can do cool things with it. - if ( targ->svFlags & SVF_GLASS_BRUSH ) - { - VectorCopy( point, targ->pos1 ); - VectorCopy( dir, targ->pos2 ); + if (targ->svFlags & SVF_GLASS_BRUSH) { + VectorCopy(point, targ->pos1); + VectorCopy(dir, targ->pos2); } - if ( targ->client ) - {//HACK - if ( point ) - { - VectorCopy( point, targ->pos1 ); - } - else - { - VectorCopy( targ->currentOrigin, targ->pos1 ); + if (targ->client) { // HACK + if (point) { + VectorCopy(point, targ->pos1); + } else { + VectorCopy(targ->currentOrigin, targ->pos1); } } - if ( !alreadyDead && !targ->enemy ) - {//just killed and didn't have an enemy before + if (!alreadyDead && !targ->enemy) { // just killed and didn't have an enemy before targ->enemy = attacker; } - GEntity_DieFunc( targ, inflictor, attacker, take, mod, dflags, hitLoc ); - } - else - { - GEntity_PainFunc( targ, inflictor, attacker, point, take, mod, hitLoc ); - if ( targ->s.number == 0 ) - {//player run painscript - G_ActivateBehavior( targ, BSET_PAIN ); - if ( targ->health <= 25 ) - { - G_ActivateBehavior( targ, BSET_FLEE ); + GEntity_DieFunc(targ, inflictor, attacker, take, mod, dflags, hitLoc); + } else { + GEntity_PainFunc(targ, inflictor, attacker, point, take, mod, hitLoc); + if (targ->s.number == 0) { // player run painscript + G_ActivateBehavior(targ, BSET_PAIN); + if (targ->health <= 25) { + G_ActivateBehavior(targ, BSET_FLEE); } } } } } - /* ============ CanDamage @@ -5393,147 +4248,136 @@ Returns qtrue if the inflictor can directly damage the target. Used for explosions and melee attacks. ============ */ -qboolean CanDamage (gentity_t *targ, vec3_t origin) { - vec3_t dest; - trace_t tr; - vec3_t midpoint; +qboolean CanDamage(gentity_t *targ, vec3_t origin) { + vec3_t dest; + trace_t tr; + vec3_t midpoint; // use the midpoint of the bounds instead of the origin, because // bmodels may have their origin at 0,0,0 - VectorAdd (targ->absmin, targ->absmax, midpoint); - VectorScale (midpoint, 0.5, midpoint); + VectorAdd(targ->absmin, targ->absmax, midpoint); + VectorScale(midpoint, 0.5, midpoint); - VectorCopy (midpoint, dest); - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if (( tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number ) // if we also test the entitynum's we can bust up bbrushes better! + VectorCopy(midpoint, dest); + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + if ((tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || + tr.entityNum == targ->s.number) // if we also test the entitynum's we can bust up bbrushes better! return qtrue; // this should probably check in the plane of projection, // rather than in world coordinate, and also include Z - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] += 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if (( tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + if ((tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] -= 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if (( tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + if ((tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] += 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if (( tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + if ((tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] -= 15.0; - gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if (( tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number ) + gi.trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); + if ((tr.fraction == 1.0 && !(targ->contents & MASK_SOLID)) || tr.entityNum == targ->s.number) return qtrue; - return qfalse; } - /* ============ G_RadiusDamage ============ */ -void G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, float radius, - gentity_t *ignore, int mod) { - float points, dist; - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - vec3_t dir; - int i, e; - - if ( radius < 1 ) { +void G_RadiusDamage(vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, int mod) { + float points, dist; + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + vec3_t dir; + int i, e; + + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( ent == ignore ) + if (ent == ignore) continue; - if ( !ent->takedamage ) + if (!ent->takedamage) continue; - if ( !ent->contents ) + if (!ent->contents) continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) { - if ( origin[i] < ent->absmin[i] ) { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - origin[i]; - } else if ( origin[i] > ent->absmax[i] ) { + } else if (origin[i] > ent->absmax[i]) { v[i] = origin[i] - ent->absmax[i]; } else { v[i] = 0; } } - dist = VectorLength( v ); - if ( dist >= radius ) { + dist = VectorLength(v); + if (dist >= radius) { continue; } - points = damage * ( 1.0 - dist / radius ); + points = damage * (1.0 - dist / radius); - if (CanDamage (ent, origin)) - {//FIXME: still do a little damage in in PVS and close? - if ( ent->svFlags & (SVF_GLASS_BRUSH|SVF_BBRUSH) ) - { - VectorAdd( ent->absmin, ent->absmax, v ); - VectorScale( v, 0.5f, v ); - } - else - { - VectorCopy( ent->currentOrigin, v ); + if (CanDamage(ent, origin)) { // FIXME: still do a little damage in in PVS and close? + if (ent->svFlags & (SVF_GLASS_BRUSH | SVF_BBRUSH)) { + VectorAdd(ent->absmin, ent->absmax, v); + VectorScale(v, 0.5f, v); + } else { + VectorCopy(ent->currentOrigin, v); } - VectorSubtract( v, origin, dir); + VectorSubtract(v, origin, dir); // push the center of mass higher than the origin so players // get knocked into the air more dir[2] += 24; - if ( ent->svFlags & SVF_GLASS_BRUSH ) - { - if ( points > 1.0f ) - { + if (ent->svFlags & SVF_GLASS_BRUSH) { + if (points > 1.0f) { // we want to cap this at some point, otherwise it just gets crazy - if ( points > 6.0f ) - { - VectorScale( dir, 6.0f, dir ); - } - else - { - VectorScale( dir, points, dir ); + if (points > 6.0f) { + VectorScale(dir, 6.0f, dir); + } else { + VectorScale(dir, points, dir); } } - ent->splashRadius = radius;// * ( 1.0 - dist / radius ); + ent->splashRadius = radius; // * ( 1.0 - dist / radius ); } - G_Damage (ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod); + G_Damage(ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod); } } } diff --git a/codeJK2/game/g_functions.cpp b/codeJK2/game/g_functions.cpp index 5a95f8a263..8f6433884b 100644 --- a/codeJK2/game/g_functions.cpp +++ b/codeJK2/game/g_functions.cpp @@ -31,377 +31,379 @@ along with this program; if not, see . #include "../cgame/cg_local.h" #include "g_functions.h" -void GEntity_ThinkFunc(gentity_t *self) -{ +void GEntity_ThinkFunc(gentity_t *self) { //#define THINKCASE(blah) case thinkF_ ## blah: blah(self); OutputDebugString(va("%s\n",#blah));break; -#define THINKCASE(blah) case thinkF_ ## blah: blah(self); break; +#define THINKCASE(blah) \ + case thinkF_##blah: \ + blah(self); \ + break; - switch (self->e_ThinkFunc) - { - case thinkF_NULL: + switch (self->e_ThinkFunc) { + case thinkF_NULL: break; - THINKCASE( funcBBrushDieGo ) - THINKCASE( ExplodeDeath ) - THINKCASE( RespawnItem ) - THINKCASE( G_FreeEntity ) - THINKCASE( FinishSpawningItem ) - THINKCASE( locateCamera ) - THINKCASE( G_RunObject ) - THINKCASE( ReturnToPos1 ) - THINKCASE( Use_BinaryMover_Go ) - THINKCASE( Think_MatchTeam ) - THINKCASE( Think_BeginMoving ) - THINKCASE( Think_SetupTrainTargets ) - THINKCASE( Think_SpawnNewDoorTrigger ) - THINKCASE( ref_link ) - THINKCASE( Think_Target_Delay ) - THINKCASE( target_laser_think ) - THINKCASE( target_laser_start ) - THINKCASE( target_location_linkup ) - THINKCASE( scriptrunner_run ) - THINKCASE( multi_wait ) - THINKCASE( multi_trigger_run ) - THINKCASE( trigger_always_think ) - THINKCASE( AimAtTarget ) - THINKCASE( func_timer_think ) - THINKCASE( NPC_RemoveBody ) - THINKCASE( Disappear ) - THINKCASE( NPC_Think ) - THINKCASE( NPC_Spawn_Go ) - THINKCASE( NPC_Begin ) - THINKCASE( moverCallback ) - THINKCASE( anglerCallback ) - THINKCASE( RemoveOwner ) - THINKCASE( MakeOwnerInvis ) - THINKCASE( MakeOwnerEnergy ) - THINKCASE( func_usable_think ) - THINKCASE( misc_dlight_think ) - THINKCASE( health_think ) - THINKCASE( ammo_think ) - THINKCASE( trigger_teleporter_find_closest_portal ) - THINKCASE( thermalDetonatorExplode ) - THINKCASE( WP_ThermalThink ) - THINKCASE( trigger_hurt_reset ) - THINKCASE( turret_base_think ) - THINKCASE( turret_head_think ) - THINKCASE( laser_arm_fire ) - THINKCASE( laser_arm_start ) - THINKCASE( trigger_visible_check_player_visibility ) - THINKCASE( target_relay_use_go ) - THINKCASE( trigger_cleared_fire ) - THINKCASE( MoveOwner ) - THINKCASE( SolidifyOwner ) - THINKCASE( cycleCamera ) - THINKCASE( spawn_ammo_crystal_trigger ) - THINKCASE( NPC_ShySpawn ) - THINKCASE( func_wait_return_solid ) - THINKCASE( InflateOwner ) - THINKCASE( mega_ammo_think ) - THINKCASE( misc_replicator_item_finish_spawn ) - THINKCASE( fx_runner_link ) - THINKCASE( fx_runner_think ) - THINKCASE( removeBoltSurface) - THINKCASE( set_MiscAnim) - THINKCASE( LimbThink ) - THINKCASE( laserTrapThink ) - THINKCASE( TieFighterThink ) - THINKCASE( rocketThink ) - THINKCASE( prox_mine_think ) - THINKCASE( emplaced_blow ) - THINKCASE( WP_Explode ) - THINKCASE( pas_think ) // personal assault sentry - THINKCASE( ion_cannon_think ) - THINKCASE( maglock_link ) - THINKCASE( WP_flechette_alt_blow ) - THINKCASE( WP_prox_mine_think ) - THINKCASE( camera_aim ) - THINKCASE( fx_explosion_trail_link ) - THINKCASE( fx_explosion_trail_think ) - THINKCASE( fx_target_beam_link ) - THINKCASE( fx_target_beam_think ) - THINKCASE( spotlight_think ) - THINKCASE( spotlight_link ) - THINKCASE( trigger_push_checkclear ) - THINKCASE( DEMP2_AltDetonate ) - THINKCASE( DEMP2_AltRadiusDamage ) - THINKCASE( panel_turret_think ) - THINKCASE( welder_think ) - THINKCASE( gas_random_jet ) - THINKCASE( poll_converter ) // dumb loop sound handling - THINKCASE( spawn_rack_goods ) // delay spawn of goods to help on ents + THINKCASE(funcBBrushDieGo) + THINKCASE(ExplodeDeath) + THINKCASE(RespawnItem) + THINKCASE(G_FreeEntity) + THINKCASE(FinishSpawningItem) + THINKCASE(locateCamera) + THINKCASE(G_RunObject) + THINKCASE(ReturnToPos1) + THINKCASE(Use_BinaryMover_Go) + THINKCASE(Think_MatchTeam) + THINKCASE(Think_BeginMoving) + THINKCASE(Think_SetupTrainTargets) + THINKCASE(Think_SpawnNewDoorTrigger) + THINKCASE(ref_link) + THINKCASE(Think_Target_Delay) + THINKCASE(target_laser_think) + THINKCASE(target_laser_start) + THINKCASE(target_location_linkup) + THINKCASE(scriptrunner_run) + THINKCASE(multi_wait) + THINKCASE(multi_trigger_run) + THINKCASE(trigger_always_think) + THINKCASE(AimAtTarget) + THINKCASE(func_timer_think) + THINKCASE(NPC_RemoveBody) + THINKCASE(Disappear) + THINKCASE(NPC_Think) + THINKCASE(NPC_Spawn_Go) + THINKCASE(NPC_Begin) + THINKCASE(moverCallback) + THINKCASE(anglerCallback) + THINKCASE(RemoveOwner) + THINKCASE(MakeOwnerInvis) + THINKCASE(MakeOwnerEnergy) + THINKCASE(func_usable_think) + THINKCASE(misc_dlight_think) + THINKCASE(health_think) + THINKCASE(ammo_think) + THINKCASE(trigger_teleporter_find_closest_portal) + THINKCASE(thermalDetonatorExplode) + THINKCASE(WP_ThermalThink) + THINKCASE(trigger_hurt_reset) + THINKCASE(turret_base_think) + THINKCASE(turret_head_think) + THINKCASE(laser_arm_fire) + THINKCASE(laser_arm_start) + THINKCASE(trigger_visible_check_player_visibility) + THINKCASE(target_relay_use_go) + THINKCASE(trigger_cleared_fire) + THINKCASE(MoveOwner) + THINKCASE(SolidifyOwner) + THINKCASE(cycleCamera) + THINKCASE(spawn_ammo_crystal_trigger) + THINKCASE(NPC_ShySpawn) + THINKCASE(func_wait_return_solid) + THINKCASE(InflateOwner) + THINKCASE(mega_ammo_think) + THINKCASE(misc_replicator_item_finish_spawn) + THINKCASE(fx_runner_link) + THINKCASE(fx_runner_think) + THINKCASE(removeBoltSurface) + THINKCASE(set_MiscAnim) + THINKCASE(LimbThink) + THINKCASE(laserTrapThink) + THINKCASE(TieFighterThink) + THINKCASE(rocketThink) + THINKCASE(prox_mine_think) + THINKCASE(emplaced_blow) + THINKCASE(WP_Explode) + THINKCASE(pas_think) // personal assault sentry + THINKCASE(ion_cannon_think) + THINKCASE(maglock_link) + THINKCASE(WP_flechette_alt_blow) + THINKCASE(WP_prox_mine_think) + THINKCASE(camera_aim) + THINKCASE(fx_explosion_trail_link) + THINKCASE(fx_explosion_trail_think) + THINKCASE(fx_target_beam_link) + THINKCASE(fx_target_beam_think) + THINKCASE(spotlight_think) + THINKCASE(spotlight_link) + THINKCASE(trigger_push_checkclear) + THINKCASE(DEMP2_AltDetonate) + THINKCASE(DEMP2_AltRadiusDamage) + THINKCASE(panel_turret_think) + THINKCASE(welder_think) + THINKCASE(gas_random_jet) + THINKCASE(poll_converter) // dumb loop sound handling + THINKCASE(spawn_rack_goods) // delay spawn of goods to help on ents default: - Com_Error(ERR_DROP, "GEntity_ThinkFunc: case %d not handled!\n",self->e_ThinkFunc); + Com_Error(ERR_DROP, "GEntity_ThinkFunc: case %d not handled!\n", self->e_ThinkFunc); break; } } // note different switch-case code for CEntity as opposed to GEntity (CEntity goes through parent GEntity first)... // -void CEntity_ThinkFunc(centity_s *cent) -{ +void CEntity_ThinkFunc(centity_s *cent) { //#define CLTHINKCASE(blah) case clThinkF_ ## blah: blah(cent); OutputDebugString(va("%s\n",#blah));break; -#define CLTHINKCASE(blah) case clThinkF_ ## blah: blah(cent); break; +#define CLTHINKCASE(blah) \ + case clThinkF_##blah: \ + blah(cent); \ + break; - switch (cent->gent->e_clThinkFunc) - { + switch (cent->gent->e_clThinkFunc) { case clThinkF_NULL: break; - CLTHINKCASE( CG_DLightThink ) - CLTHINKCASE( CG_MatrixEffect ) - CLTHINKCASE( CG_Limb ) + CLTHINKCASE(CG_DLightThink) + CLTHINKCASE(CG_MatrixEffect) + CLTHINKCASE(CG_Limb) default: - Com_Error(ERR_DROP, "CEntity_ThinkFunc: case %d not handled!\n",cent->gent->e_clThinkFunc); + Com_Error(ERR_DROP, "CEntity_ThinkFunc: case %d not handled!\n", cent->gent->e_clThinkFunc); break; } } - -void GEntity_ReachedFunc(gentity_t *self) -{ +void GEntity_ReachedFunc(gentity_t *self) { //#define REACHEDCASE(blah) case reachedF_ ## blah: blah(self); OutputDebugString(va("%s\n",#blah));break; -#define REACHEDCASE(blah) case reachedF_ ## blah: blah(self); break; +#define REACHEDCASE(blah) \ + case reachedF_##blah: \ + blah(self); \ + break; - switch (self->e_ReachedFunc) - { + switch (self->e_ReachedFunc) { case reachedF_NULL: break; - REACHEDCASE( Reached_BinaryMover ) - REACHEDCASE( Reached_Train ) - REACHEDCASE( moverCallback ) - REACHEDCASE( moveAndRotateCallback ) + REACHEDCASE(Reached_BinaryMover) + REACHEDCASE(Reached_Train) + REACHEDCASE(moverCallback) + REACHEDCASE(moveAndRotateCallback) default: - Com_Error(ERR_DROP, "GEntity_ReachedFunc: case %d not handled!\n",self->e_ReachedFunc); + Com_Error(ERR_DROP, "GEntity_ReachedFunc: case %d not handled!\n", self->e_ReachedFunc); break; } } - - -void GEntity_BlockedFunc(gentity_t *self, gentity_t *other) -{ +void GEntity_BlockedFunc(gentity_t *self, gentity_t *other) { //#define BLOCKEDCASE(blah) case blockedF_ ## blah: blah(self,other); OutputDebugString(va("%s\n",#blah));break; -#define BLOCKEDCASE(blah) case blockedF_ ## blah: blah(self,other); break; +#define BLOCKEDCASE(blah) \ + case blockedF_##blah: \ + blah(self, other); \ + break; - switch (self->e_BlockedFunc) - { + switch (self->e_BlockedFunc) { case blockedF_NULL: break; - BLOCKEDCASE( Blocked_Door ) - BLOCKEDCASE( Blocked_Mover ) + BLOCKEDCASE(Blocked_Door) + BLOCKEDCASE(Blocked_Mover) default: - Com_Error(ERR_DROP, "GEntity_BlockedFunc: case %d not handled!\n",self->e_BlockedFunc); + Com_Error(ERR_DROP, "GEntity_BlockedFunc: case %d not handled!\n", self->e_BlockedFunc); break; } } -void GEntity_TouchFunc(gentity_t *self, gentity_t *other, trace_t *trace) -{ +void GEntity_TouchFunc(gentity_t *self, gentity_t *other, trace_t *trace) { //#define TOUCHCASE(blah) case touchF_ ## blah: blah(self,other,trace); OutputDebugString(va("%s\n",#blah));break; -#define TOUCHCASE(blah) case touchF_ ## blah: blah(self,other,trace); break; +#define TOUCHCASE(blah) \ + case touchF_##blah: \ + blah(self, other, trace); \ + break; - switch (self->e_TouchFunc) - { + switch (self->e_TouchFunc) { case touchF_NULL: break; - TOUCHCASE( Touch_Item ) - TOUCHCASE( teleporter_touch ) - TOUCHCASE( charge_stick ) - TOUCHCASE( Touch_DoorTrigger ) - TOUCHCASE( Touch_PlatCenterTrigger ) - TOUCHCASE( Touch_Plat ) - TOUCHCASE( Touch_Button ) - TOUCHCASE( Touch_Multi ) - TOUCHCASE( trigger_push_touch ) - TOUCHCASE( trigger_teleporter_touch ) - TOUCHCASE( hurt_touch ) - TOUCHCASE( NPC_Touch ) - TOUCHCASE( touch_ammo_crystal_tigger ) - TOUCHCASE( funcBBrushTouch ) - TOUCHCASE( touchLaserTrap ) - TOUCHCASE( prox_mine_stick ) - TOUCHCASE( func_rotating_touch ) + TOUCHCASE(Touch_Item) + TOUCHCASE(teleporter_touch) + TOUCHCASE(charge_stick) + TOUCHCASE(Touch_DoorTrigger) + TOUCHCASE(Touch_PlatCenterTrigger) + TOUCHCASE(Touch_Plat) + TOUCHCASE(Touch_Button) + TOUCHCASE(Touch_Multi) + TOUCHCASE(trigger_push_touch) + TOUCHCASE(trigger_teleporter_touch) + TOUCHCASE(hurt_touch) + TOUCHCASE(NPC_Touch) + TOUCHCASE(touch_ammo_crystal_tigger) + TOUCHCASE(funcBBrushTouch) + TOUCHCASE(touchLaserTrap) + TOUCHCASE(prox_mine_stick) + TOUCHCASE(func_rotating_touch) default: - Com_Error(ERR_DROP, "GEntity_TouchFunc: case %d not handled!\n",self->e_TouchFunc); + Com_Error(ERR_DROP, "GEntity_TouchFunc: case %d not handled!\n", self->e_TouchFunc); } } -void GEntity_UseFunc(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( !self || (self->svFlags&SVF_INACTIVE) ) - { +void GEntity_UseFunc(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!self || (self->svFlags & SVF_INACTIVE)) { return; } //#define USECASE(blah) case useF_ ## blah: blah(self,other,activator); OutputDebugString(va("%s\n",#blah));break; -#define USECASE(blah) case useF_ ## blah: blah(self,other,activator); break; +#define USECASE(blah) \ + case useF_##blah: \ + blah(self, other, activator); \ + break; - switch (self->e_UseFunc) - { + switch (self->e_UseFunc) { case useF_NULL: break; - USECASE( funcBBrushUse ) - USECASE( misc_model_use ) - USECASE( Use_Item ) - USECASE( Use_Shooter ) - USECASE( GoExplodeDeath ) - USECASE( Use_BinaryMover ) - USECASE( use_wall ) - USECASE( Use_Target_Give ) - USECASE( Use_Target_Delay ) - USECASE( Use_Target_Score ) - USECASE( Use_Target_Print ) - USECASE( Use_Target_Speaker ) - USECASE( target_laser_use ) - USECASE( target_relay_use ) - USECASE( target_kill_use ) - USECASE( target_counter_use ) - USECASE( target_random_use ) - USECASE( target_scriptrunner_use ) - USECASE( target_gravity_change_use ) - USECASE( target_friction_change_use ) - USECASE( target_teleporter_use ) - USECASE( Use_Multi ) - USECASE( Use_target_push ) - USECASE( hurt_use ) - USECASE( func_timer_use ) - USECASE( trigger_entdist_use ) - USECASE( func_usable_use ) - USECASE( target_activate_use ) - USECASE( target_deactivate_use ) - USECASE( NPC_Use ) - USECASE( NPC_Spawn ) - USECASE( misc_dlight_use ) - USECASE( health_use ) - USECASE( ammo_use ) - USECASE( mega_ammo_use ) - USECASE( target_level_change_use ) - USECASE( target_change_parm_use ) - USECASE( turret_base_use ) - USECASE( laser_arm_use ) - USECASE( func_static_use ) - USECASE( target_play_music_use ) - USECASE( misc_model_useup ) - USECASE( misc_portal_use ) - USECASE( target_autosave_use ) - USECASE( switch_models ) - USECASE( misc_replicator_item_spawn ) - USECASE( misc_replicator_item_remove ) - USECASE( target_secret_use) - USECASE( func_bobbing_use ) - USECASE( func_rotating_use ) - USECASE( fx_runner_use ) - USECASE( funcGlassUse ) - USECASE( TrainUse ) - USECASE( misc_trip_mine_activate ) - USECASE( emplaced_gun_use ) - USECASE( shield_power_converter_use ) - USECASE( ammo_power_converter_use ) - USECASE( security_panel_use ) - USECASE( ion_cannon_use ) - USECASE( camera_use ) - USECASE( fx_explosion_trail_use ) - USECASE( fx_target_beam_use ) - USECASE( sentry_use ) - USECASE( spotlight_use ) - USECASE( misc_atst_use ) - USECASE( panel_turret_use ) - USECASE( welder_use ) - USECASE( jabba_cam_use ) - USECASE( misc_use ) - USECASE( pas_use ) - USECASE( item_spawn_use ) + USECASE(funcBBrushUse) + USECASE(misc_model_use) + USECASE(Use_Item) + USECASE(Use_Shooter) + USECASE(GoExplodeDeath) + USECASE(Use_BinaryMover) + USECASE(use_wall) + USECASE(Use_Target_Give) + USECASE(Use_Target_Delay) + USECASE(Use_Target_Score) + USECASE(Use_Target_Print) + USECASE(Use_Target_Speaker) + USECASE(target_laser_use) + USECASE(target_relay_use) + USECASE(target_kill_use) + USECASE(target_counter_use) + USECASE(target_random_use) + USECASE(target_scriptrunner_use) + USECASE(target_gravity_change_use) + USECASE(target_friction_change_use) + USECASE(target_teleporter_use) + USECASE(Use_Multi) + USECASE(Use_target_push) + USECASE(hurt_use) + USECASE(func_timer_use) + USECASE(trigger_entdist_use) + USECASE(func_usable_use) + USECASE(target_activate_use) + USECASE(target_deactivate_use) + USECASE(NPC_Use) + USECASE(NPC_Spawn) + USECASE(misc_dlight_use) + USECASE(health_use) + USECASE(ammo_use) + USECASE(mega_ammo_use) + USECASE(target_level_change_use) + USECASE(target_change_parm_use) + USECASE(turret_base_use) + USECASE(laser_arm_use) + USECASE(func_static_use) + USECASE(target_play_music_use) + USECASE(misc_model_useup) + USECASE(misc_portal_use) + USECASE(target_autosave_use) + USECASE(switch_models) + USECASE(misc_replicator_item_spawn) + USECASE(misc_replicator_item_remove) + USECASE(target_secret_use) + USECASE(func_bobbing_use) + USECASE(func_rotating_use) + USECASE(fx_runner_use) + USECASE(funcGlassUse) + USECASE(TrainUse) + USECASE(misc_trip_mine_activate) + USECASE(emplaced_gun_use) + USECASE(shield_power_converter_use) + USECASE(ammo_power_converter_use) + USECASE(security_panel_use) + USECASE(ion_cannon_use) + USECASE(camera_use) + USECASE(fx_explosion_trail_use) + USECASE(fx_target_beam_use) + USECASE(sentry_use) + USECASE(spotlight_use) + USECASE(misc_atst_use) + USECASE(panel_turret_use) + USECASE(welder_use) + USECASE(jabba_cam_use) + USECASE(misc_use) + USECASE(pas_use) + USECASE(item_spawn_use) default: - Com_Error(ERR_DROP, "GEntity_UseFunc: case %d not handled!\n",self->e_UseFunc); + Com_Error(ERR_DROP, "GEntity_UseFunc: case %d not handled!\n", self->e_UseFunc); } } -void GEntity_PainFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod,int hitLoc) -{ +void GEntity_PainFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { //#define PAINCASE(blah) case painF_ ## blah: blah(self,attacker,damage); OutputDebugString(va("%s\n",#blah));break; -#define PAINCASE(blah) case painF_ ## blah: blah(self,inflictor,attacker,point,damage,mod,hitLoc); break; +#define PAINCASE(blah) \ + case painF_##blah: \ + blah(self, inflictor, attacker, point, damage, mod, hitLoc); \ + break; - switch (self->e_PainFunc) - { + switch (self->e_PainFunc) { case painF_NULL: break; - PAINCASE( funcBBrushPain ) - PAINCASE( misc_model_breakable_pain ) - PAINCASE( NPC_Pain ) - PAINCASE( station_pain ) - PAINCASE( func_usable_pain ) - PAINCASE( NPC_ATST_Pain ) - PAINCASE( NPC_ST_Pain ) - PAINCASE( NPC_Jedi_Pain ) - PAINCASE( NPC_Droid_Pain ) - PAINCASE( NPC_Probe_Pain ) - PAINCASE( NPC_MineMonster_Pain ) - PAINCASE( NPC_Howler_Pain ) - PAINCASE( NPC_Seeker_Pain ) - PAINCASE( NPC_Remote_Pain ) - PAINCASE( emplaced_gun_pain ) - PAINCASE( NPC_Mark1_Pain ) - PAINCASE( NPC_GM_Pain ) - PAINCASE( NPC_Sentry_Pain ) - PAINCASE( NPC_Mark2_Pain ) - PAINCASE( PlayerPain ) - PAINCASE( GasBurst ) - PAINCASE( CrystalCratePain ) - PAINCASE( TurretPain ) + PAINCASE(funcBBrushPain) + PAINCASE(misc_model_breakable_pain) + PAINCASE(NPC_Pain) + PAINCASE(station_pain) + PAINCASE(func_usable_pain) + PAINCASE(NPC_ATST_Pain) + PAINCASE(NPC_ST_Pain) + PAINCASE(NPC_Jedi_Pain) + PAINCASE(NPC_Droid_Pain) + PAINCASE(NPC_Probe_Pain) + PAINCASE(NPC_MineMonster_Pain) + PAINCASE(NPC_Howler_Pain) + PAINCASE(NPC_Seeker_Pain) + PAINCASE(NPC_Remote_Pain) + PAINCASE(emplaced_gun_pain) + PAINCASE(NPC_Mark1_Pain) + PAINCASE(NPC_GM_Pain) + PAINCASE(NPC_Sentry_Pain) + PAINCASE(NPC_Mark2_Pain) + PAINCASE(PlayerPain) + PAINCASE(GasBurst) + PAINCASE(CrystalCratePain) + PAINCASE(TurretPain) default: - Com_Error(ERR_DROP, "GEntity_PainFunc: case %d not handled!\n",self->e_PainFunc); + Com_Error(ERR_DROP, "GEntity_PainFunc: case %d not handled!\n", self->e_PainFunc); } } - -void GEntity_DieFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) -{ +void GEntity_DieFunc(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { //#define DIECASE(blah) case dieF_ ## blah: blah(self,inflictor,attacker,damage,mod); OutputDebugString(va("%s\n",#blah));break; -#define DIECASE(blah) case dieF_ ## blah: blah(self,inflictor,attacker,damage,mod,dFlags,hitLoc); break; +#define DIECASE(blah) \ + case dieF_##blah: \ + blah(self, inflictor, attacker, damage, mod, dFlags, hitLoc); \ + break; - switch (self->e_DieFunc) - { + switch (self->e_DieFunc) { case dieF_NULL: break; - DIECASE( funcBBrushDie ) - DIECASE( misc_model_breakable_die ) - DIECASE( misc_model_cargo_die ) - DIECASE( func_train_die ) - DIECASE( player_die ) - DIECASE( ExplodeDeath_Wait ) - DIECASE( ExplodeDeath ) - DIECASE( func_usable_die ) - DIECASE( turret_die ) - DIECASE( funcGlassDie ) -// DIECASE( laserTrapDelayedExplode ) - DIECASE( emplaced_gun_die ) - DIECASE( WP_ExplosiveDie ) - DIECASE( ion_cannon_die ) - DIECASE( maglock_die ) - DIECASE( camera_die ) - DIECASE( Mark1_die ) - DIECASE( Interrogator_die ) - DIECASE( misc_atst_die ) - DIECASE( misc_panel_turret_die ) - DIECASE( thermal_die ) + DIECASE(funcBBrushDie) + DIECASE(misc_model_breakable_die) + DIECASE(misc_model_cargo_die) + DIECASE(func_train_die) + DIECASE(player_die) + DIECASE(ExplodeDeath_Wait) + DIECASE(ExplodeDeath) + DIECASE(func_usable_die) + DIECASE(turret_die) + DIECASE(funcGlassDie) + // DIECASE( laserTrapDelayedExplode ) + DIECASE(emplaced_gun_die) + DIECASE(WP_ExplosiveDie) + DIECASE(ion_cannon_die) + DIECASE(maglock_die) + DIECASE(camera_die) + DIECASE(Mark1_die) + DIECASE(Interrogator_die) + DIECASE(misc_atst_die) + DIECASE(misc_panel_turret_die) + DIECASE(thermal_die) default: - Com_Error(ERR_DROP, "GEntity_DieFunc: case %d not handled!\n",self->e_DieFunc); + Com_Error(ERR_DROP, "GEntity_DieFunc: case %d not handled!\n", self->e_DieFunc); } } //////////////////// eof ///////////////////// - diff --git a/codeJK2/game/g_fx.cpp b/codeJK2/game/g_fx.cpp index 8dafdec821..620c7e2cf0 100644 --- a/codeJK2/game/g_fx.cpp +++ b/codeJK2/game/g_fx.cpp @@ -25,13 +25,13 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" -extern int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ); +extern int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create); #define FX_ENT_RADIUS 32 -extern int BMS_START; -extern int BMS_MID; -extern int BMS_END; +extern int BMS_START; +extern int BMS_MID; +extern int BMS_END; //---------------------------------------------------------- @@ -54,100 +54,84 @@ Runs the specified effect, can also be targeted at an info_notnull to orient the #define FX_RUNNER_RESERVED 0x800000 //---------------------------------------------------------- -void fx_runner_think( gentity_t *ent ) -{ +void fx_runner_think(gentity_t *ent) { vec3_t temp; - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); // call the effect with the desired position and orientation - G_AddEvent( ent, EV_PLAY_EFFECT, ent->fxID ); + G_AddEvent(ent, EV_PLAY_EFFECT, ent->fxID); // Assume angles, we'll do a cross product on the other end to finish up - AngleVectors( ent->currentAngles, ent->pos3, NULL, NULL ); - MakeNormalVectors( ent->pos3, ent->pos4, temp ); // there IS a reason this is done...it's so that it doesn't break every effect in the game... + AngleVectors(ent->currentAngles, ent->pos3, NULL, NULL); + MakeNormalVectors(ent->pos3, ent->pos4, temp); // there IS a reason this is done...it's so that it doesn't break every effect in the game... ent->nextthink = level.time + ent->delay + Q_flrand(0.0f, 1.0f) * ent->random; - if ( ent->spawnflags & 4 ) // damage + if (ent->spawnflags & 4) // damage { - G_RadiusDamage( ent->currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, MOD_UNKNOWN ); + G_RadiusDamage(ent->currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, MOD_UNKNOWN); } - if ( ent->target2 ) - { + if (ent->target2) { // let our target know that we have spawned an effect - G_UseTargets2( ent, ent, ent->target2 ); + G_UseTargets2(ent, ent, ent->target2); } - if ( !(ent->spawnflags & 2 ) && !ent->s.loopSound ) // NOT ONESHOT...this is an assy thing to do + if (!(ent->spawnflags & 2) && !ent->s.loopSound) // NOT ONESHOT...this is an assy thing to do { - if ( VALIDSTRING( ent->soundSet ) == true ) - { - ent->s.loopSound = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + if (VALIDSTRING(ent->soundSet) == true) { + ent->s.loopSound = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( ent->s.loopSound < 0 ) - { + if (ent->s.loopSound < 0) { ent->s.loopSound = 0; } } } - } //---------------------------------------------------------- -void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->spawnflags & 2 ) // ONESHOT +void fx_runner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->spawnflags & 2) // ONESHOT { // call the effect with the desired position and orientation, as a safety thing, // make sure we aren't thinking at all. - fx_runner_think( self ); + fx_runner_think(self); self->nextthink = -1; - if ( self->target2 ) - { + if (self->target2) { // let our target know that we have spawned an effect - G_UseTargets2( self, self, self->target2 ); + G_UseTargets2(self, self, self->target2); } - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); } - } - else - { + } else { // ensure we are working with the right think function self->e_ThinkFunc = thinkF_fx_runner_think; // toggle our state - if ( self->nextthink == -1 ) - { + if (self->nextthink == -1) { // NOTE: we fire the effect immediately on use, the fx_runner_think func will set // up the nextthink time. - fx_runner_think( self ); + fx_runner_think(self); - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - self->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + self->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); - if ( self->s.loopSound < 0 ) - { + if (self->s.loopSound < 0) { self->s.loopSound = 0; } } - } - else - { + } else { // turn off for now self->nextthink = -1; - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_END )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_END)); self->s.loopSound = 0; } } @@ -155,61 +139,50 @@ void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } //---------------------------------------------------------- -void fx_runner_link( gentity_t *ent ) -{ - vec3_t dir; +void fx_runner_link(gentity_t *ent) { + vec3_t dir; - if ( ent->target ) - { + if (ent->target) { // try to use the target to override the orientation - gentity_t *target = NULL; + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { + if (!target) { // Bah, no good, dump a warning, but continue on and use the UP vector - Com_Printf( "fx_runner_link: target specified but not found: %s\n", ent->target ); - Com_Printf( " -assuming UP orientation.\n" ); - } - else - { + Com_Printf("fx_runner_link: target specified but not found: %s\n", ent->target); + Com_Printf(" -assuming UP orientation.\n"); + } else { // Our target is valid so let's override the default UP vector - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); } } // don't really do anything with this right now other than do a check to warn the designers if the target2 is bogus - if ( ent->target2 ) - { - gentity_t *target = NULL; + if (ent->target2) { + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target2 ); + target = G_Find(target, FOFS(targetname), ent->target2); - if ( !target ) - { + if (!target) { // Target2 is bogus, but we can still continue - Com_Printf( "fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2 ); + Com_Printf("fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2); } } - G_SetAngles( ent, ent->s.angles ); + G_SetAngles(ent, ent->s.angles); - if ( ent->spawnflags & 1 || ent->spawnflags & 2 ) // STARTOFF || ONESHOT + if (ent->spawnflags & 1 || ent->spawnflags & 2) // STARTOFF || ONESHOT { // We won't even consider thinking until we are used ent->nextthink = -1; - } - else - { - if ( VALIDSTRING( ent->soundSet ) == true ) - { - ent->s.loopSound = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + } else { + if (VALIDSTRING(ent->soundSet) == true) { + ent->s.loopSound = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( ent->s.loopSound < 0 ) - { + if (ent->s.loopSound < 0) { ent->s.loopSound = 0; } } @@ -220,37 +193,33 @@ void fx_runner_link( gentity_t *ent ) } // make us useable if we can be targeted - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_fx_runner_use; } } //---------------------------------------------------------- -void SP_fx_runner( gentity_t *ent ) -{ +void SP_fx_runner(gentity_t *ent) { // Get our defaults - G_SpawnInt( "delay", "200", &ent->delay ); - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnInt( "splashRadius", "16", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "5", &ent->splashDamage ); + G_SpawnInt("delay", "200", &ent->delay); + G_SpawnFloat("random", "0", &ent->random); + G_SpawnInt("splashRadius", "16", &ent->splashRadius); + G_SpawnInt("splashDamage", "5", &ent->splashDamage); - if ( !G_SpawnAngleHack( "angle", "0", ent->s.angles )) - { + if (!G_SpawnAngleHack("angle", "0", ent->s.angles)) { // didn't have angles, so give us the default of up - VectorSet( ent->s.angles, -90, 0, 0 ); + VectorSet(ent->s.angles, -90, 0, 0); } - if ( !ent->fxFile ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin) ); - G_FreeEntity( ent ); + if (!ent->fxFile) { + gi.Printf(S_COLOR_RED "ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin)); + G_FreeEntity(ent); return; } // Try and associate an effect file, unfortunately we won't know if this worked or not // until the CGAME trys to register it... - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); ent->s.eType = ET_MOVER; @@ -259,34 +228,31 @@ void SP_fx_runner( gentity_t *ent ) ent->nextthink = level.time + 400; // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - /*QUAKED fx_snow (1 0 0) (-16 -16 -16) (16 16 16) This world effect will spawn snow globally into the level. "count" the number of snow particles (default of 1000) */ //---------------------------------------------------------- -void SP_CreateSnow( gentity_t *ent ) -{ - char temp[256]; +void SP_CreateSnow(gentity_t *ent) { + char temp[256]; - G_SpawnInt( "count", "1000", &ent->count ); + G_SpawnInt("count", "1000", &ent->count); - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); - if ( r_weatherScale->value > 0.0f ) - { - sprintf( temp, "snow init %i", (int)( ent->count * r_weatherScale->value )); + if (r_weatherScale->value > 0.0f) { + sprintf(temp, "snow init %i", (int)(ent->count * r_weatherScale->value)); - G_FindConfigstringIndex( temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue ); + G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); level.worldFlags |= WF_SNOWING; } @@ -298,92 +264,78 @@ This world effect will spawn rain globally into the level. "count" the number of rain particles (default of 500) */ //---------------------------------------------------------- -void SP_CreateRain( gentity_t *ent ) -{ - char temp[256]; +void SP_CreateRain(gentity_t *ent) { + char temp[256]; - G_SpawnInt( "count", "500", &ent->count ); + G_SpawnInt("count", "500", &ent->count); - cvar_t *r_weatherScale = gi.cvar( "r_weatherScale", "1", CVAR_ARCHIVE ); + cvar_t *r_weatherScale = gi.cvar("r_weatherScale", "1", CVAR_ARCHIVE); - if ( r_weatherScale->value > 0.0f ) - { - sprintf( temp, "rain init %i", (int)( ent->count * r_weatherScale->value )); + if (r_weatherScale->value > 0.0f) { + sprintf(temp, "rain init %i", (int)(ent->count * r_weatherScale->value)); - G_FindConfigstringIndex( temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue ); + G_FindConfigstringIndex(temp, CS_WORLD_FX, MAX_WORLD_FX, qtrue); level.worldFlags |= WF_RAINING; } } - //----------------- // Explosion Trail //----------------- //---------------------------------------------------------- -void fx_explosion_trail_think( gentity_t *ent ) -{ - vec3_t origin; - trace_t tr; +void fx_explosion_trail_think(gentity_t *ent) { + vec3_t origin; + trace_t tr; - if ( ent->spawnflags & 1 ) // gravity + if (ent->spawnflags & 1) // gravity { ent->s.pos.trType = TR_GRAVITY; - } - else - { + } else { ent->s.pos.trType = TR_LINEAR; } - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); - gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, - ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10 ); + gi.trace(&tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10); - if ( tr.fraction < 1.0f ) - { + if (tr.fraction < 1.0f) { // never explode or bounce on sky - if ( !( tr.surfaceFlags & SURF_NOIMPACT )) - { - if ( ent->splashDamage && ent->splashRadius ) - { - G_RadiusDamage( tr.endpos, ent, ent->splashDamage, ent->splashRadius, ent, MOD_EXPLOSIVE_SPLASH ); + if (!(tr.surfaceFlags & SURF_NOIMPACT)) { + if (ent->splashDamage && ent->splashRadius) { + G_RadiusDamage(tr.endpos, ent, ent->splashDamage, ent->splashRadius, ent, MOD_EXPLOSIVE_SPLASH); } } - if ( ent->fullName ) - { + if (ent->fullName) { // fxFile2....in other words, impact fx - G_PlayEffect( ent->fullName, tr.endpos, tr.plane.normal ); + G_PlayEffect(ent->fullName, tr.endpos, tr.plane.normal); } - if ( VALIDSTRING( ent->soundSet ) == true ) - { - G_AddEvent( ent, EV_BMODEL_SOUND, CAS_GetBModelSound( ent->soundSet, BMS_END )); + if (VALIDSTRING(ent->soundSet) == true) { + G_AddEvent(ent, EV_BMODEL_SOUND, CAS_GetBModelSound(ent->soundSet, BMS_END)); } - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } - G_RadiusDamage( origin, ent, ent->damage, ent->radius, ent, MOD_EXPLOSIVE_SPLASH ); + G_RadiusDamage(origin, ent, ent->damage, ent->radius, ent, MOD_EXPLOSIVE_SPLASH); // call the effect with the desired position and orientation - G_PlayEffect( ent->fxID, origin, ent->currentAngles ); + G_PlayEffect(ent->fxID, origin, ent->currentAngles); ent->nextthink = level.time + 50; - gi.linkentity( ent ); + gi.linkentity(ent); } //---------------------------------------------------------- -void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void fx_explosion_trail_use(gentity_t *self, gentity_t *other, gentity_t *activator) { gentity_t *missile = G_Spawn(); // We aren't a missile in the truest sense, rather we just move through the world and spawn effects - if ( missile ) - { + if (missile) { missile->classname = "fx_exp_trail"; missile->nextthink = level.time + 50; @@ -396,20 +348,18 @@ void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activ missile->s.modelindex = self->s.modelindex2; missile->s.pos.trTime = level.time; - G_SetOrigin( missile, self->currentOrigin ); - if ( self->spawnflags & 1 ) // gravity + G_SetOrigin(missile, self->currentOrigin); + if (self->spawnflags & 1) // gravity { missile->s.pos.trType = TR_GRAVITY; - } - else - { + } else { missile->s.pos.trType = TR_LINEAR; } missile->spawnflags = self->spawnflags; - G_SetAngles( missile, self->currentAngles ); - VectorScale( self->currentAngles, self->speed, missile->s.pos.trDelta ); + G_SetAngles(missile, self->currentAngles); + VectorScale(self->currentAngles, self->speed, missile->s.pos.trDelta); missile->s.pos.trTime = level.time; missile->radius = self->radius; missile->damage = self->damage; @@ -420,16 +370,14 @@ void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activ missile->clipmask = MASK_SHOT; - gi.linkentity( missile ); + gi.linkentity(missile); - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - missile->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + missile->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); missile->soundSet = self->soundSet; - if ( missile->s.loopSound < 0 ) - { + if (missile->s.loopSound < 0) { missile->s.loopSound = 0; } } @@ -437,38 +385,33 @@ void fx_explosion_trail_use( gentity_t *self, gentity_t *other, gentity_t *activ } //---------------------------------------------------------- -void fx_explosion_trail_link( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *target = NULL; +void fx_explosion_trail_link(gentity_t *ent) { + vec3_t dir; + gentity_t *target = NULL; // we ony activate when used ent->e_UseFunc = useF_fx_explosion_trail_use; - if ( ent->target ) - { + if (ent->target) { // try to use the target to override the orientation - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_explosion_trail %s could not find target %s\n", ent->targetname, ent->target ); - G_FreeEntity( ent ); + if (!target) { + gi.Printf(S_COLOR_RED "ERROR: fx_explosion_trail %s could not find target %s\n", ent->targetname, ent->target); + G_FreeEntity(ent); return; } // Our target is valid so lets use that - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - } - else - { + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + } else { // we are assuming that we have angles, but there are no checks to verify this - AngleVectors( ent->s.angles, dir, NULL, NULL ); + AngleVectors(ent->s.angles, dir, NULL, NULL); } // NOTE: this really isn't an angle, but rather an orientation vector - G_SetAngles( ent, dir ); + G_SetAngles(ent, dir); } /*QUAKED fx_explosion_trail (0 0 1) (-8 -8 -8) (8 8 8) GRAVITY @@ -494,33 +437,29 @@ Can also be used for something like a meteor, just add an impact effect ( fxFile */ //---------------------------------------------------------- -void SP_fx_explosion_trail( gentity_t *ent ) -{ +void SP_fx_explosion_trail(gentity_t *ent) { // We have to be useable, otherwise we won't spawn in - if ( !ent->targetname ) - { - gi.Printf( S_COLOR_RED"ERROR: fx_explosion_trail at %s has no targetname specified\n", vtos( ent->s.origin )); - G_FreeEntity( ent ); + if (!ent->targetname) { + gi.Printf(S_COLOR_RED "ERROR: fx_explosion_trail at %s has no targetname specified\n", vtos(ent->s.origin)); + G_FreeEntity(ent); return; } // Get our defaults - G_SpawnString( "fxFile", "env/exp_trail_comp", &ent->fxFile ); - G_SpawnInt( "damage", "128", &ent->damage ); - G_SpawnFloat( "radius", "128", &ent->radius ); - G_SpawnFloat( "speed", "350", &ent->speed ); + G_SpawnString("fxFile", "env/exp_trail_comp", &ent->fxFile); + G_SpawnInt("damage", "128", &ent->damage); + G_SpawnFloat("radius", "128", &ent->radius); + G_SpawnFloat("speed", "350", &ent->speed); // Try and associate an effect file, unfortunately we won't know if this worked or not until the CGAME trys to register it... - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); - if ( ent->fullName ) - { - G_EffectIndex( ent->fullName ); + if (ent->fullName) { + G_EffectIndex(ent->fullName); } - if ( ent->model ) - { - ent->s.modelindex2 = G_ModelIndex( ent->model ); + if (ent->model) { + ent->s.modelindex2 = G_ModelIndex(ent->model); } // Give us a bit of time to spawn in the other entities, since we may have to target one of 'em @@ -528,97 +467,75 @@ void SP_fx_explosion_trail( gentity_t *ent ) ent->nextthink = level.time + 500; // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - // // //------------------------------------------ -void fx_target_beam_set_debounce( gentity_t *self ) -{ - if ( self->wait >= FRAMETIME ) - { - self->attackDebounceTime = level.time + self->wait + Q_irand( -self->random, self->random ); - } - else if ( self->wait < 0 ) - { +void fx_target_beam_set_debounce(gentity_t *self) { + if (self->wait >= FRAMETIME) { + self->attackDebounceTime = level.time + self->wait + Q_irand(-self->random, self->random); + } else if (self->wait < 0) { self->e_UseFunc = useF_NULL; - } - else - { - self->attackDebounceTime = level.time + FRAMETIME + Q_irand( -self->random, self->random ); + } else { + self->attackDebounceTime = level.time + FRAMETIME + Q_irand(-self->random, self->random); } } //------------------------------------------ -void fx_target_beam_fire( gentity_t *ent ) -{ - trace_t trace; - vec3_t dir, org, end; - qboolean open; - - if ( !ent->enemy || !ent->enemy->inuse ) - {//info_null most likely +void fx_target_beam_fire(gentity_t *ent) { + trace_t trace; + vec3_t dir, org, end; + qboolean open; + + if (!ent->enemy || !ent->enemy->inuse) { // info_null most likely ent->enemy = NULL; - VectorCopy( ent->s.origin2, org ); - } - else - { - VectorCopy( ent->enemy->currentOrigin, org ); + VectorCopy(ent->s.origin2, org); + } else { + VectorCopy(ent->enemy->currentOrigin, org); } - VectorCopy( org, ent->s.origin2 ); - VectorSubtract( org, ent->s.origin, dir ); - VectorNormalize( dir ); + VectorCopy(org, ent->s.origin2); + VectorSubtract(org, ent->s.origin, dir); + VectorNormalize(dir); - gi.trace( &trace, ent->s.origin, NULL, NULL, org, ENTITYNUM_NONE, MASK_SHOT, G2_NOCOLLIDE, 0 );//ignore - if ( ent->spawnflags & 2 ) - { + gi.trace(&trace, ent->s.origin, NULL, NULL, org, ENTITYNUM_NONE, MASK_SHOT, G2_NOCOLLIDE, 0); // ignore + if (ent->spawnflags & 2) { open = qtrue; - VectorCopy( org, end ); - } - else - { + VectorCopy(org, end); + } else { open = qfalse; - VectorCopy( trace.endpos, end ); + VectorCopy(trace.endpos, end); } - if ( trace.fraction < 1.0 ) - { - if ( trace.entityNum < ENTITYNUM_WORLD ) - { + if (trace.fraction < 1.0) { + if (trace.entityNum < ENTITYNUM_WORLD) { gentity_t *victim = &g_entities[trace.entityNum]; - if ( victim && victim->takedamage ) - { - if ( ent->spawnflags & 4 ) // NO_KNOCKBACK - { - G_Damage( victim, ent, ent->activator, dir, trace.endpos, ent->damage, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN ); - } - else + if (victim && victim->takedamage) { + if (ent->spawnflags & 4) // NO_KNOCKBACK { - G_Damage( victim, ent, ent->activator, dir, trace.endpos, ent->damage, 0, MOD_UNKNOWN ); + G_Damage(victim, ent, ent->activator, dir, trace.endpos, ent->damage, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN); + } else { + G_Damage(victim, ent, ent->activator, dir, trace.endpos, ent->damage, 0, MOD_UNKNOWN); } } } } - G_AddEvent( ent, EV_TARGET_BEAM_DRAW, ent->fxID ); - VectorCopy( end, ent->s.origin2 ); + G_AddEvent(ent, EV_TARGET_BEAM_DRAW, ent->fxID); + VectorCopy(end, ent->s.origin2); - if ( open ) - { - VectorScale( dir, -1, ent->pos1 ); - } - else - { - VectorCopy( trace.plane.normal, ent->pos1 ); + if (open) { + VectorScale(dir, -1, ent->pos1); + } else { + VectorCopy(trace.plane.normal, ent->pos1); } ent->e_ThinkFunc = thinkF_fx_target_beam_think; @@ -626,92 +543,80 @@ void fx_target_beam_fire( gentity_t *ent ) } //------------------------------------------ -void fx_target_beam_fire_start( gentity_t *self ) -{ - fx_target_beam_set_debounce( self ); - self->e_ThinkFunc = thinkF_fx_target_beam_think; - self->nextthink = level.time + FRAMETIME; - self->painDebounceTime = level.time + self->speed + Q_irand( -500, 500 ); - fx_target_beam_fire( self ); +void fx_target_beam_fire_start(gentity_t *self) { + fx_target_beam_set_debounce(self); + self->e_ThinkFunc = thinkF_fx_target_beam_think; + self->nextthink = level.time + FRAMETIME; + self->painDebounceTime = level.time + self->speed + Q_irand(-500, 500); + fx_target_beam_fire(self); } //------------------------------------------ -void fx_target_beam_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->spawnflags & 8 ) // one shot - { - fx_target_beam_fire( self ); - self->e_ThinkFunc = thinkF_NULL; - } - else if ( self->e_ThinkFunc == thinkF_NULL ) - { - self->e_ThinkFunc = thinkF_fx_target_beam_think; - self->nextthink = level.time + 50; - } - else +void fx_target_beam_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->spawnflags & 8) // one shot { - self->e_ThinkFunc = thinkF_NULL; + fx_target_beam_fire(self); + self->e_ThinkFunc = thinkF_NULL; + } else if (self->e_ThinkFunc == thinkF_NULL) { + self->e_ThinkFunc = thinkF_fx_target_beam_think; + self->nextthink = level.time + 50; + } else { + self->e_ThinkFunc = thinkF_NULL; } self->activator = activator; } //------------------------------------------ -void fx_target_beam_think( gentity_t *ent ) -{ - if ( ent->attackDebounceTime > level.time ) - { +void fx_target_beam_think(gentity_t *ent) { + if (ent->attackDebounceTime > level.time) { ent->nextthink = level.time + FRAMETIME; return; } - fx_target_beam_fire_start( ent ); + fx_target_beam_fire_start(ent); } //------------------------------------------ -void fx_target_beam_link( gentity_t *ent ) -{ - gentity_t *target = NULL; - vec3_t dir; +void fx_target_beam_link(gentity_t *ent) { + gentity_t *target = NULL; + vec3_t dir; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - Com_Printf( "bolt_link: unable to find target %s\n", ent->target ); - G_FreeEntity( ent ); + if (!target) { + Com_Printf("bolt_link: unable to find target %s\n", ent->target); + G_FreeEntity(ent); return; } ent->attackDebounceTime = level.time; - if ( !target->classname || Q_stricmp( "info_null", target->classname ) ) - {//don't want to set enemy to something that's going to free itself... actually, this could be bad in other ways, too... ent pointer could be freed up and re-used by the time we check it next - G_SetEnemy( ent, target ); + if (!target->classname || + Q_stricmp("info_null", target->classname)) { // don't want to set enemy to something that's going to free itself... actually, this could be bad in other + // ways, too... ent pointer could be freed up and re-used by the time we check it next + G_SetEnemy(ent, target); } - VectorSubtract( target->s.origin, ent->s.origin, dir );//er, does it ever use dir? - VectorNormalize( dir );//er, does it use len or dir? - vectoangles( dir, ent->s.angles );//er, does it use s.angles? + VectorSubtract(target->s.origin, ent->s.origin, dir); // er, does it ever use dir? + VectorNormalize(dir); // er, does it use len or dir? + vectoangles(dir, ent->s.angles); // er, does it use s.angles? - VectorCopy( target->s.origin, ent->s.origin2 ); + VectorCopy(target->s.origin, ent->s.origin2); - if ( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { // Do nothing - ent->e_ThinkFunc = thinkF_NULL; - } - else - { - if ( !(ent->spawnflags & 8 )) // one_shot, only calls when used + ent->e_ThinkFunc = thinkF_NULL; + } else { + if (!(ent->spawnflags & 8)) // one_shot, only calls when used { // switch think functions to avoid doing the bolt_link every time ent->e_ThinkFunc = thinkF_fx_target_beam_think; - ent->nextthink = level.time + FRAMETIME; + ent->nextthink = level.time + FRAMETIME; } } ent->e_UseFunc = useF_fx_target_beam_use; - gi.linkentity( ent ); + gi.linkentity(ent); } /*QUAKED fx_target_beam (1 0.5 0.5) (-8 -8 -8) (8 8 8) STARTOFF OPEN NO_KNOCKBACK ONE_SHOT NO_IMPACT @@ -731,47 +636,42 @@ NO_KNOCKBACK - beam damage does no knockback "target" - ent to point at- you MUST have this. This can be anything you want, including a moving ent - for static beams, just use info_null */ //------------------------------------------ -void SP_fx_target_beam( gentity_t *ent ) -{ - G_SetOrigin( ent, ent->s.origin ); +void SP_fx_target_beam(gentity_t *ent) { + G_SetOrigin(ent, ent->s.origin); - ent->speed *= 1000; - ent->wait *= 1000; + ent->speed *= 1000; + ent->wait *= 1000; ent->random *= 1000; - if ( ent->speed < FRAMETIME ) - { + if (ent->speed < FRAMETIME) { ent->speed = FRAMETIME; } - G_SpawnInt( "damage", "0", &ent->damage ); - G_SpawnString( "fxFile", "env/targ_beam", &ent->fxFile ); + G_SpawnInt("damage", "0", &ent->damage); + G_SpawnString("fxFile", "env/targ_beam", &ent->fxFile); - if ( ent->spawnflags & 16 ) // NO_IMPACT FX + if (ent->spawnflags & 16) // NO_IMPACT FX { ent->delay = 0; - } - else - { - G_SpawnString( "fxFile2", "env/targ_beam_impact", &ent->fullName ); - ent->delay = G_EffectIndex( ent->fullName ); + } else { + G_SpawnString("fxFile2", "env/targ_beam_impact", &ent->fullName); + ent->delay = G_EffectIndex(ent->fullName); } - ent->fxID = G_EffectIndex( ent->fxFile ); + ent->fxID = G_EffectIndex(ent->fxFile); ent->activator = ent; - ent->owner = NULL; + ent->owner = NULL; ent->e_ThinkFunc = thinkF_fx_target_beam_link; - ent->nextthink = level.time + START_TIME_LINK_ENTS; + ent->nextthink = level.time + START_TIME_LINK_ENTS; - VectorSet( ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } - /*QUAKED fx_cloudlayer (1 0.3 0.5) (-8 -8 -8) (8 8 8) TUBE ALT Creates a scalable scrolling cloud layer, mostly for bespin undercity but could be used other places @@ -785,22 +685,21 @@ void SP_fx_target_beam( gentity_t *ent ) */ -void SP_fx_cloudlayer( gentity_t *ent ) -{ +void SP_fx_cloudlayer(gentity_t *ent) { // HACK: this effect is never played, rather it just caches the shaders I need cgame side - G_EffectIndex( "world/haze_cache" ); + G_EffectIndex("world/haze_cache"); - G_SpawnFloat( "radius", "2048", &ent->radius ); - G_SpawnFloat( "random", "128", &ent->random ); - G_SpawnFloat( "wait", "0", &ent->wait ); + G_SpawnFloat("radius", "2048", &ent->radius); + G_SpawnFloat("random", "128", &ent->random); + G_SpawnFloat("wait", "0", &ent->wait); ent->s.eType = ET_CLOUD; // dumb - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); ent->contents = 0; - VectorSet( ent->maxs, 200, 200, 200 ); - VectorScale( ent->maxs, -1, ent->mins ); + VectorSet(ent->maxs, 200, 200, 200); + VectorScale(ent->maxs, -1, ent->mins); - gi.linkentity( ent ); + gi.linkentity(ent); } \ No newline at end of file diff --git a/codeJK2/game/g_inventory.cpp b/codeJK2/game/g_inventory.cpp index 46afc0cfb2..fd8d57e0a9 100644 --- a/codeJK2/game/g_inventory.cpp +++ b/codeJK2/game/g_inventory.cpp @@ -31,48 +31,39 @@ along with this program; if not, see . Goodie Keys ================ */ -qboolean INV_GoodieKeyGive( gentity_t *target ) -{ - if ( !target || !target->client ) - { +qboolean INV_GoodieKeyGive(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } target->client->ps.inventory[INV_GOODIE_KEY]++; return (qtrue); - } -qboolean INV_GoodieKeyTake( gentity_t *target ) -{ - if ( !target || !target->client ) - { +qboolean INV_GoodieKeyTake(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } - if (target->client->ps.inventory[INV_GOODIE_KEY]) - { + if (target->client->ps.inventory[INV_GOODIE_KEY]) { target->client->ps.inventory[INV_GOODIE_KEY]--; return (qtrue); } - //had no keys + // had no keys return (qfalse); } -int INV_GoodieKeyCheck( gentity_t *target ) -{ - if ( !target || !target->client ) - { +int INV_GoodieKeyCheck(gentity_t *target) { + if (!target || !target->client) { return (qfalse); } - if ( target->client->ps.inventory[INV_GOODIE_KEY] ) - {//found a key + if (target->client->ps.inventory[INV_GOODIE_KEY]) { // found a key return (INV_GOODIE_KEY); } - //no keys + // no keys return (qfalse); } @@ -81,41 +72,31 @@ int INV_GoodieKeyCheck( gentity_t *target ) Security Keys ================ */ -qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ) -{ - if ( target == NULL || keyname == NULL || target->client == NULL ) - { +qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname) { + if (target == NULL || keyname == NULL || target->client == NULL) { return qfalse; } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.security_key_message[i][0] == '\0' ) - {//fill in the first empty slot we find with this key - target->client->ps.inventory[INV_SECURITY_KEY]++; // He got the key - Q_strncpyz(target->client->ps.security_key_message[i], keyname, - sizeof(target->client->ps.security_key_message[i]) ); + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.security_key_message[i][0] == '\0') { // fill in the first empty slot we find with this key + target->client->ps.inventory[INV_SECURITY_KEY]++; // He got the key + Q_strncpyz(target->client->ps.security_key_message[i], keyname, sizeof(target->client->ps.security_key_message[i])); return qtrue; } } - //couldn't find an empty slot + // couldn't find an empty slot return qfalse; } -void INV_SecurityKeyTake( gentity_t *target, const char *keyname ) -{ - if ( !target || !keyname || !target->client ) - { +void INV_SecurityKeyTake(gentity_t *target, const char *keyname) { + if (!target || !keyname || !target->client) { return; } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.security_key_message[i][0] != '\0' ) - { - if ( !Q_stricmp( keyname, target->client->ps.security_key_message[i] ) ) - { - target->client->ps.inventory[INV_SECURITY_KEY]--; // Take the key + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.security_key_message[i][0] != '\0') { + if (!Q_stricmp(keyname, target->client->ps.security_key_message[i])) { + target->client->ps.inventory[INV_SECURITY_KEY]--; // Take the key target->client->ps.security_key_message[i][0] = '\0'; return; } @@ -130,19 +111,14 @@ void INV_SecurityKeyTake( gentity_t *target, const char *keyname ) } } -qboolean INV_SecurityKeyCheck( gentity_t *target, const char *keyname ) -{ - if ( !target || !keyname || !target->client ) - { +qboolean INV_SecurityKeyCheck(gentity_t *target, const char *keyname) { + if (!target || !keyname || !target->client) { return (qfalse); } - for ( int i = 0; i < MAX_SECURITY_KEYS; i++ ) - { - if ( target->client->ps.inventory[INV_SECURITY_KEY] && target->client->ps.security_key_message[i][0] != '\0' ) - { - if ( !Q_stricmp( keyname, target->client->ps.security_key_message[i] ) ) - { + for (int i = 0; i < MAX_SECURITY_KEYS; i++) { + if (target->client->ps.inventory[INV_SECURITY_KEY] && target->client->ps.security_key_message[i][0] != '\0') { + if (!Q_stricmp(keyname, target->client->ps.security_key_message[i])) { return (qtrue); } } diff --git a/codeJK2/game/g_itemLoad.cpp b/codeJK2/game/g_itemLoad.cpp index d5329989b2..97e901dcf7 100644 --- a/codeJK2/game/g_itemLoad.cpp +++ b/codeJK2/game/g_itemLoad.cpp @@ -20,8 +20,8 @@ along with this program; if not, see . =========================================================================== */ -//g_itemLoad.cpp -//reads in ext_data\items.dat to bg_itemlist[] +// g_itemLoad.cpp +// reads in ext_data\items.dat to bg_itemlist[] #include "g_headers.h" @@ -30,24 +30,24 @@ along with this program; if not, see . #define PICKUPSOUND "sound/weapons/w_pkup.wav" -//qboolean COM_ParseInt( char **data, int *i ); -//qboolean COM_ParseString( char **data, char **s ); -//qboolean COM_ParseFloat( char **data, float *f ); +// qboolean COM_ParseInt( char **data, int *i ); +// qboolean COM_ParseString( char **data, char **s ); +// qboolean COM_ParseFloat( char **data, float *f ); -extern gitem_t bg_itemlist[]; +extern gitem_t bg_itemlist[]; static int itemNum; -static void IT_ClassName (const char **holdBuf); -static void IT_Count (const char **holdBuf); -static void IT_Icon (const char **holdBuf); -static void IT_Min (const char **holdBuf); -static void IT_Max (const char **holdBuf); -static void IT_Name (const char **holdBuf); -static void IT_PickupSound (const char **holdBuf); -static void IT_Tag (const char **holdBuf); -static void IT_Type (const char **holdBuf); -static void IT_WorldModel (const char **holdBuf); +static void IT_ClassName(const char **holdBuf); +static void IT_Count(const char **holdBuf); +static void IT_Icon(const char **holdBuf); +static void IT_Min(const char **holdBuf); +static void IT_Max(const char **holdBuf); +static void IT_Name(const char **holdBuf); +static void IT_PickupSound(const char **holdBuf); +static void IT_Tag(const char **holdBuf); +static void IT_Type(const char **holdBuf); +static void IT_WorldModel(const char **holdBuf); typedef struct itemParms_s { const char *parmName; @@ -57,19 +57,11 @@ typedef struct itemParms_s { #define IT_PARM_MAX 10 itemParms_t ItemParms[IT_PARM_MAX] = { - { "itemname", IT_Name }, - { "classname", IT_ClassName }, - { "count", IT_Count }, - { "icon", IT_Icon }, - { "min", IT_Min }, - { "max", IT_Max }, - { "pickupsound", IT_PickupSound }, - { "tag", IT_Tag }, - { "type", IT_Type }, - { "worldmodel", IT_WorldModel }, + {"itemname", IT_Name}, {"classname", IT_ClassName}, {"count", IT_Count}, {"icon", IT_Icon}, {"min", IT_Min}, + {"max", IT_Max}, {"pickupsound", IT_PickupSound}, {"tag", IT_Tag}, {"type", IT_Type}, {"worldmodel", IT_WorldModel}, }; -static void IT_SetDefaults( void ) { +static void IT_SetDefaults(void) { bg_itemlist[itemNum].mins[0] = -16; bg_itemlist[itemNum].mins[1] = -16; bg_itemlist[itemNum].mins[2] = -2; @@ -78,507 +70,390 @@ static void IT_SetDefaults( void ) { bg_itemlist[itemNum].maxs[1] = 16; bg_itemlist[itemNum].maxs[2] = 16; - bg_itemlist[itemNum].pickup_sound = PICKUPSOUND; //give it a default sound + bg_itemlist[itemNum].pickup_sound = PICKUPSOUND; // give it a default sound bg_itemlist[itemNum].precaches = NULL; bg_itemlist[itemNum].sounds = NULL; } -static void IT_Name( const char **holdBuf ) { +static void IT_Name(const char **holdBuf) { const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if ( !Q_stricmp( tokenStr, "ITM_NONE" ) ) { + if (!Q_stricmp(tokenStr, "ITM_NONE")) { itemNum = ITM_NONE; - } - else if ( !Q_stricmp( tokenStr, "ITM_STUN_BATON_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_STUN_BATON_PICKUP")) { itemNum = ITM_STUN_BATON_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SABER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SABER_PICKUP")) { itemNum = ITM_SABER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BRYAR_PISTOL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BRYAR_PISTOL_PICKUP")) { itemNum = ITM_BRYAR_PISTOL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BLASTER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BLASTER_PICKUP")) { itemNum = ITM_BLASTER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_DISRUPTOR_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_DISRUPTOR_PICKUP")) { itemNum = ITM_DISRUPTOR_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BOWCASTER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BOWCASTER_PICKUP")) { itemNum = ITM_BOWCASTER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_REPEATER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_REPEATER_PICKUP")) { itemNum = ITM_REPEATER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_DEMP2_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_DEMP2_PICKUP")) { itemNum = ITM_DEMP2_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FLECHETTE_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FLECHETTE_PICKUP")) { itemNum = ITM_FLECHETTE_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_ROCKET_LAUNCHER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_ROCKET_LAUNCHER_PICKUP")) { itemNum = ITM_ROCKET_LAUNCHER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_THERMAL_DET_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_THERMAL_DET_PICKUP")) { itemNum = ITM_THERMAL_DET_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_TRIP_MINE_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_TRIP_MINE_PICKUP")) { itemNum = ITM_TRIP_MINE_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_DET_PACK_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_DET_PACK_PICKUP")) { itemNum = ITM_DET_PACK_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BOT_LASER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BOT_LASER_PICKUP")) { itemNum = ITM_BOT_LASER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_EMPLACED_GUN_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_EMPLACED_GUN_PICKUP")) { itemNum = ITM_EMPLACED_GUN_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_TURRET_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_TURRET_PICKUP")) { itemNum = ITM_TURRET_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_MELEE" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_MELEE")) { itemNum = ITM_MELEE; - } - else if ( !Q_stricmp( tokenStr, "ITM_ATST_MAIN_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_ATST_MAIN_PICKUP")) { itemNum = ITM_ATST_MAIN_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_ATST_SIDE_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_ATST_SIDE_PICKUP")) { itemNum = ITM_ATST_SIDE_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_TIE_FIGHTER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_TIE_FIGHTER_PICKUP")) { itemNum = ITM_TIE_FIGHTER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_RAPID_FIRE_CONC_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_RAPID_FIRE_CONC_PICKUP")) { itemNum = ITM_RAPID_FIRE_CONC_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_FORCE_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_FORCE_PICKUP")) { itemNum = ITM_AMMO_FORCE_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_BLASTER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_BLASTER_PICKUP")) { itemNum = ITM_AMMO_BLASTER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_POWERCELL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_POWERCELL_PICKUP")) { itemNum = ITM_AMMO_POWERCELL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_METAL_BOLTS_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_METAL_BOLTS_PICKUP")) { itemNum = ITM_AMMO_METAL_BOLTS_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_ROCKETS_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_ROCKETS_PICKUP")) { itemNum = ITM_AMMO_ROCKETS_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_EMPLACED_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_EMPLACED_PICKUP")) { itemNum = ITM_AMMO_EMPLACED_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_THERMAL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_THERMAL_PICKUP")) { itemNum = ITM_AMMO_THERMAL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_TRIPMINE_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_TRIPMINE_PICKUP")) { itemNum = ITM_AMMO_TRIPMINE_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_AMMO_DETPACK_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_AMMO_DETPACK_PICKUP")) { itemNum = ITM_AMMO_DETPACK_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_HEAL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_HEAL_PICKUP")) { itemNum = ITM_FORCE_HEAL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_LEVITATION_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_LEVITATION_PICKUP")) { itemNum = ITM_FORCE_LEVITATION_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_SPEED_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_SPEED_PICKUP")) { itemNum = ITM_FORCE_SPEED_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_PUSH_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_PUSH_PICKUP")) { itemNum = ITM_FORCE_PUSH_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_PULL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_PULL_PICKUP")) { itemNum = ITM_FORCE_PULL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_TELEPATHY_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_TELEPATHY_PICKUP")) { itemNum = ITM_FORCE_TELEPATHY_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_GRIP_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_GRIP_PICKUP")) { itemNum = ITM_FORCE_GRIP_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_LIGHTNING_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_LIGHTNING_PICKUP")) { itemNum = ITM_FORCE_LIGHTNING_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_FORCE_SABERTHROW_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_FORCE_SABERTHROW_PICKUP")) { itemNum = ITM_FORCE_SABERTHROW_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BATTERY_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BATTERY_PICKUP")) { itemNum = ITM_BATTERY_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SEEKER_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SEEKER_PICKUP")) { itemNum = ITM_SEEKER_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SHIELD_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_PICKUP")) { itemNum = ITM_SHIELD_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BACTA_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BACTA_PICKUP")) { itemNum = ITM_BACTA_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_DATAPAD_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_DATAPAD_PICKUP")) { itemNum = ITM_DATAPAD_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BINOCULARS_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BINOCULARS_PICKUP")) { itemNum = ITM_BINOCULARS_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SENTRY_GUN_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SENTRY_GUN_PICKUP")) { itemNum = ITM_SENTRY_GUN_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_LA_GOGGLES_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_LA_GOGGLES_PICKUP")) { itemNum = ITM_LA_GOGGLES_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_BLASTER_PISTOL_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BLASTER_PISTOL_PICKUP")) { itemNum = ITM_BLASTER_PISTOL_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_MEDPAK_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_MEDPAK_PICKUP")) { itemNum = ITM_MEDPAK_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SHIELD_SM_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_SM_PICKUP")) { itemNum = ITM_SHIELD_SM_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SHIELD_LRG_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_LRG_PICKUP")) { itemNum = ITM_SHIELD_LRG_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_GOODIE_KEY_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_GOODIE_KEY_PICKUP")) { itemNum = ITM_GOODIE_KEY_PICKUP; - } - else if ( !Q_stricmp( tokenStr, "ITM_SECURITY_KEY_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SECURITY_KEY_PICKUP")) { itemNum = ITM_SECURITY_KEY_PICKUP; - } - else { + } else { itemNum = 0; - gi.Printf( "WARNING: bad itemname in external item data '%s'\n", tokenStr ); + gi.Printf("WARNING: bad itemname in external item data '%s'\n", tokenStr); } IT_SetDefaults(); } -static void IT_ClassName( const char **holdBuf ) { +static void IT_ClassName(const char **holdBuf) { int len; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ) + 1; - if ( len > 32 ) { + len = strlen(tokenStr) + 1; + if (len > 32) { len = 32; - gi.Printf( "WARNING: weaponclass too long in external ITEMS.DAT '%s'\n", tokenStr ); + gi.Printf("WARNING: weaponclass too long in external ITEMS.DAT '%s'\n", tokenStr); } - bg_itemlist[itemNum].classname = G_NewString( tokenStr ); + bg_itemlist[itemNum].classname = G_NewString(tokenStr); } -static void IT_WorldModel( const char **holdBuf ) { +static void IT_WorldModel(const char **holdBuf) { int len; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ) + 1; - if ( len > 64 ) { + len = strlen(tokenStr) + 1; + if (len > 64) { len = 64; - gi.Printf( "WARNING: world model too long in external ITEMS.DAT '%s'\n", tokenStr ); + gi.Printf("WARNING: world model too long in external ITEMS.DAT '%s'\n", tokenStr); } - bg_itemlist[itemNum].world_model = G_NewString( tokenStr ); + bg_itemlist[itemNum].world_model = G_NewString(tokenStr); } -static void IT_Tag( const char **holdBuf ) { +static void IT_Tag(const char **holdBuf) { int tag; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if ( !Q_stricmp( tokenStr, "WP_NONE" ) ) { + if (!Q_stricmp(tokenStr, "WP_NONE")) { tag = WP_NONE; - } - else if ( !Q_stricmp( tokenStr,"WP_STUN_BATON" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_STUN_BATON")) { tag = WP_STUN_BATON; - } - else if ( !Q_stricmp( tokenStr,"WP_SABER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_SABER")) { tag = WP_SABER; - } - else if ( !Q_stricmp( tokenStr,"WP_BRYAR_PISTOL" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_BRYAR_PISTOL")) { tag = WP_BRYAR_PISTOL; - } - else if ( !Q_stricmp( tokenStr,"WP_BLASTER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_BLASTER")) { tag = WP_BLASTER; - } - else if ( !Q_stricmp( tokenStr,"WP_DISRUPTOR" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_DISRUPTOR")) { tag = WP_DISRUPTOR; - } - else if ( !Q_stricmp( tokenStr,"WP_BOWCASTER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_BOWCASTER")) { tag = WP_BOWCASTER; - } - else if ( !Q_stricmp( tokenStr,"WP_REPEATER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_REPEATER")) { tag = WP_REPEATER; - } - else if ( !Q_stricmp( tokenStr,"WP_DEMP2" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_DEMP2")) { tag = WP_DEMP2; - } - else if ( !Q_stricmp( tokenStr,"WP_FLECHETTE" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_FLECHETTE")) { tag = WP_FLECHETTE; - } - else if ( !Q_stricmp( tokenStr,"WP_ROCKET_LAUNCHER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_ROCKET_LAUNCHER")) { tag = WP_ROCKET_LAUNCHER; - } - else if ( !Q_stricmp( tokenStr,"WP_THERMAL" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_THERMAL")) { tag = WP_THERMAL; - } - else if ( !Q_stricmp( tokenStr,"WP_TRIP_MINE" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_TRIP_MINE")) { tag = WP_TRIP_MINE; - } - else if ( !Q_stricmp( tokenStr,"WP_DET_PACK" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_DET_PACK")) { tag = WP_DET_PACK; - } - else if ( !Q_stricmp( tokenStr,"WP_BOT_LASER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_BOT_LASER")) { tag = WP_BOT_LASER; - } - else if ( !Q_stricmp( tokenStr,"WP_EMPLACED_GUN" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_EMPLACED_GUN")) { tag = WP_EMPLACED_GUN; - } - else if ( !Q_stricmp( tokenStr,"WP_MELEE" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_MELEE")) { tag = WP_MELEE; - } - else if ( !Q_stricmp( tokenStr,"WP_TURRET" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_TURRET")) { tag = WP_TURRET; - } - else if ( !Q_stricmp( tokenStr,"WP_ATST_MAIN" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_ATST_MAIN")) { tag = WP_ATST_MAIN; - } - else if ( !Q_stricmp( tokenStr,"WP_ATST_SIDE" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_ATST_SIDE")) { tag = WP_ATST_SIDE; - } - else if ( !Q_stricmp( tokenStr,"WP_TIE_FIGHTER" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_TIE_FIGHTER")) { tag = WP_TIE_FIGHTER; - } - else if ( !Q_stricmp( tokenStr,"WP_RAPID_FIRE_CONC" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_RAPID_FIRE_CONC")) { tag = WP_RAPID_FIRE_CONC; - } - else if ( !Q_stricmp( tokenStr,"WP_BLASTER_PISTOL" ) ) { + } else if (!Q_stricmp(tokenStr, "WP_BLASTER_PISTOL")) { tag = WP_BLASTER_PISTOL; - } - else if ( !Q_stricmp( tokenStr,"AMMO_FORCE" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_FORCE")) { tag = AMMO_FORCE; - } - else if ( !Q_stricmp( tokenStr,"AMMO_BLASTER" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_BLASTER")) { tag = AMMO_BLASTER; - } - else if ( !Q_stricmp( tokenStr,"AMMO_POWERCELL" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_POWERCELL")) { tag = AMMO_POWERCELL; - } - else if ( !Q_stricmp( tokenStr,"AMMO_METAL_BOLTS" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_METAL_BOLTS")) { tag = AMMO_METAL_BOLTS; - } - else if ( !Q_stricmp( tokenStr,"AMMO_ROCKETS" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_ROCKETS")) { tag = AMMO_ROCKETS; - } - else if ( !Q_stricmp( tokenStr,"AMMO_EMPLACED" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_EMPLACED")) { tag = AMMO_EMPLACED; - } - else if ( !Q_stricmp( tokenStr,"AMMO_THERMAL" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_THERMAL")) { tag = AMMO_THERMAL; - } - else if ( !Q_stricmp( tokenStr,"AMMO_TRIPMINE" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_TRIPMINE")) { tag = AMMO_TRIPMINE; - } - else if ( !Q_stricmp( tokenStr,"AMMO_DETPACK" ) ) { + } else if (!Q_stricmp(tokenStr, "AMMO_DETPACK")) { tag = AMMO_DETPACK; - } - else if ( !Q_stricmp( tokenStr,"FP_HEAL" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_HEAL")) { tag = FP_HEAL; - } - else if ( !Q_stricmp( tokenStr,"FP_LEVITATION" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_LEVITATION")) { tag = FP_LEVITATION; - } - else if ( !Q_stricmp( tokenStr,"FP_SPEED" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_SPEED")) { tag = FP_SPEED; - } - else if ( !Q_stricmp( tokenStr,"FP_PUSH" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_PUSH")) { tag = FP_PUSH; - } - else if ( !Q_stricmp( tokenStr,"FP_PULL" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_PULL")) { tag = FP_PULL; - } - else if ( !Q_stricmp( tokenStr,"FP_TELEPATHY" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_TELEPATHY")) { tag = FP_TELEPATHY; - } - else if ( !Q_stricmp( tokenStr,"FP_GRIP" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_GRIP")) { tag = FP_GRIP; - } - else if ( !Q_stricmp( tokenStr,"FP_LIGHTNING" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_LIGHTNING")) { tag = FP_LIGHTNING; - } - else if ( !Q_stricmp( tokenStr,"FP_SABERTHROW" ) ) { + } else if (!Q_stricmp(tokenStr, "FP_SABERTHROW")) { tag = FP_SABERTHROW; - } - else if ( !Q_stricmp( tokenStr,"ITM_BATTERY_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_BATTERY_PICKUP")) { tag = ITM_BATTERY_PICKUP; - } - else if ( !Q_stricmp( tokenStr,"INV_SEEKER" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_SEEKER")) { tag = INV_SEEKER; - } - else if ( !Q_stricmp( tokenStr,"ITM_SHIELD_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_PICKUP")) { tag = ITM_SHIELD_PICKUP; - } - else if ( !Q_stricmp( tokenStr,"INV_BACTA_CANISTER" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_BACTA_CANISTER")) { tag = INV_BACTA_CANISTER; - } - else if ( !Q_stricmp( tokenStr,"ITM_DATAPAD_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_DATAPAD_PICKUP")) { tag = ITM_DATAPAD_PICKUP; - } - else if ( !Q_stricmp( tokenStr,"INV_ELECTROBINOCULARS" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_ELECTROBINOCULARS")) { tag = INV_ELECTROBINOCULARS; - } - else if ( !Q_stricmp( tokenStr,"INV_SENTRY" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_SENTRY")) { tag = INV_SENTRY; - } - else if ( !Q_stricmp( tokenStr,"INV_LIGHTAMP_GOGGLES" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_LIGHTAMP_GOGGLES")) { tag = INV_LIGHTAMP_GOGGLES; - } - else if ( !Q_stricmp( tokenStr,"INV_GOODIE_KEY" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_GOODIE_KEY")) { tag = INV_GOODIE_KEY; - } - else if ( !Q_stricmp( tokenStr,"INV_SECURITY_KEY" ) ) { + } else if (!Q_stricmp(tokenStr, "INV_SECURITY_KEY")) { tag = INV_SECURITY_KEY; - } - else if ( !Q_stricmp( tokenStr,"ITM_MEDPAK_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_MEDPAK_PICKUP")) { tag = ITM_MEDPAK_PICKUP; - } - else if ( !Q_stricmp( tokenStr,"ITM_SHIELD_SM_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_SM_PICKUP")) { tag = ITM_SHIELD_SM_PICKUP; - } - else if ( !Q_stricmp( tokenStr,"ITM_SHIELD_LRG_PICKUP" ) ) { + } else if (!Q_stricmp(tokenStr, "ITM_SHIELD_LRG_PICKUP")) { tag = ITM_SHIELD_LRG_PICKUP; - } - else { + } else { tag = WP_BRYAR_PISTOL; - gi.Printf( "WARNING: bad tagname in external item data '%s'\n", tokenStr ); + gi.Printf("WARNING: bad tagname in external item data '%s'\n", tokenStr); } bg_itemlist[itemNum].giTag = tag; - } -static void IT_Type( const char **holdBuf ) { +static void IT_Type(const char **holdBuf) { int type; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if ( !Q_stricmp( tokenStr, "IT_BAD" ) ) { + if (!Q_stricmp(tokenStr, "IT_BAD")) { type = IT_BAD; - } - else if ( !Q_stricmp( tokenStr, "IT_WEAPON" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_WEAPON")) { type = IT_WEAPON; - } - else if ( !Q_stricmp( tokenStr, "IT_AMMO" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_AMMO")) { type = IT_AMMO; - } - else if ( !Q_stricmp( tokenStr, "IT_ARMOR" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_ARMOR")) { type = IT_ARMOR; - } - else if ( !Q_stricmp( tokenStr, "IT_HEALTH" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_HEALTH")) { type = IT_HEALTH; - } - else if ( !Q_stricmp( tokenStr, "IT_HOLDABLE" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_HOLDABLE")) { type = IT_HOLDABLE; - } - else if ( !Q_stricmp( tokenStr, "IT_BATTERY" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_BATTERY")) { type = IT_BATTERY; - } - else if ( !Q_stricmp( tokenStr, "IT_HOLOCRON" ) ) { + } else if (!Q_stricmp(tokenStr, "IT_HOLOCRON")) { type = IT_HOLOCRON; - } - else { + } else { type = IT_BAD; - gi.Printf( "WARNING: bad itemname in external item data '%s'\n", tokenStr ); + gi.Printf("WARNING: bad itemname in external item data '%s'\n", tokenStr); } bg_itemlist[itemNum].giType = (itemType_t)type; } -static void IT_Icon( const char **holdBuf ) { +static void IT_Icon(const char **holdBuf) { int len; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ) + 1; - if ( len > 32 ) { + len = strlen(tokenStr) + 1; + if (len > 32) { len = 32; - gi.Printf( "WARNING: icon too long in external ITEMS.DAT '%s'\n", tokenStr ); + gi.Printf("WARNING: icon too long in external ITEMS.DAT '%s'\n", tokenStr); } - bg_itemlist[itemNum].icon = G_NewString( tokenStr ); + bg_itemlist[itemNum].icon = G_NewString(tokenStr); } -static void IT_Count( const char **holdBuf ) { +static void IT_Count(const char **holdBuf) { int tokenInt; - if ( COM_ParseInt( holdBuf, &tokenInt ) ) { - SkipRestOfLine( holdBuf ); + if (COM_ParseInt(holdBuf, &tokenInt)) { + SkipRestOfLine(holdBuf); return; } - if ( tokenInt < 0 || tokenInt > 1000 ) { - gi.Printf( "WARNING: bad Count in external item data '%d'\n", tokenInt ); + if (tokenInt < 0 || tokenInt > 1000) { + gi.Printf("WARNING: bad Count in external item data '%d'\n", tokenInt); return; } bg_itemlist[itemNum].quantity = tokenInt; } -static void IT_Min( const char **holdBuf ) { +static void IT_Min(const char **holdBuf) { int tokenInt; - for ( int i = 0; i < 3; i++ ) { - if ( COM_ParseInt( holdBuf, &tokenInt ) ) { - SkipRestOfLine( holdBuf ); + for (int i = 0; i < 3; i++) { + if (COM_ParseInt(holdBuf, &tokenInt)) { + SkipRestOfLine(holdBuf); return; } bg_itemlist[itemNum].mins[i] = tokenInt; } } -static void IT_Max( const char **holdBuf ) { +static void IT_Max(const char **holdBuf) { int tokenInt; - for ( int i = 0; i < 3; i++ ) { - if ( COM_ParseInt( holdBuf, &tokenInt ) ) { - SkipRestOfLine( holdBuf ); + for (int i = 0; i < 3; i++) { + if (COM_ParseInt(holdBuf, &tokenInt)) { + SkipRestOfLine(holdBuf); return; } bg_itemlist[itemNum].maxs[i] = tokenInt; } } -static void IT_PickupSound( const char **holdBuf ) { +static void IT_PickupSound(const char **holdBuf) { int len; const char *tokenStr; - if ( COM_ParseString( holdBuf, &tokenStr ) ) { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ) + 1; - if ( len > 32 ) { + len = strlen(tokenStr) + 1; + if (len > 32) { len = 32; gi.Printf("WARNING: Pickup Sound too long in external ITEMS.DAT '%s'\n", tokenStr); } @@ -586,59 +461,57 @@ static void IT_PickupSound( const char **holdBuf ) { bg_itemlist[itemNum].pickup_sound = G_NewString(tokenStr); } -static void IT_ParseWeaponParms( const char **holdBuf ) { +static void IT_ParseWeaponParms(const char **holdBuf) { int i; - while ( holdBuf ) { - const char *token = COM_ParseExt( holdBuf, qtrue ); + while (holdBuf) { + const char *token = COM_ParseExt(holdBuf, qtrue); - if ( !Q_stricmp( token, "}" ) ) { + if (!Q_stricmp(token, "}")) { // end of data for this weapon break; } // loop through possible parameters - for ( i = 0; i < IT_PARM_MAX; i++ ) { - if ( !Q_stricmp( token, ItemParms[i].parmName ) ) { - ItemParms[i].func( holdBuf ); + for (i = 0; i < IT_PARM_MAX; i++) { + if (!Q_stricmp(token, ItemParms[i].parmName)) { + ItemParms[i].func(holdBuf); break; } } - if ( i < IT_PARM_MAX ) { + if (i < IT_PARM_MAX) { // find parameter??? continue; } - Com_Printf( S_COLOR_YELLOW "WARNING: bad parameter in external item data '%s'\n", token ); - SkipRestOfLine( holdBuf ); + Com_Printf(S_COLOR_YELLOW "WARNING: bad parameter in external item data '%s'\n", token); + SkipRestOfLine(holdBuf); } } -static void IT_ParseParms( const char *buffer ) { +static void IT_ParseParms(const char *buffer) { const char *holdBuf, *token; holdBuf = buffer; COM_BeginParseSession(); - while ( holdBuf ) { - token = COM_ParseExt( &holdBuf, qtrue ); + while (holdBuf) { + token = COM_ParseExt(&holdBuf, qtrue); - if ( !Q_stricmp( token, "{" ) ) { - IT_ParseWeaponParms( &holdBuf ); + if (!Q_stricmp(token, "{")) { + IT_ParseWeaponParms(&holdBuf); } - } COM_EndParseSession(); } - -void IT_LoadItemParms( void ) { +void IT_LoadItemParms(void) { char *buffer; - gi.FS_ReadFile( "ext_data/items.dat", (void **)&buffer ); + gi.FS_ReadFile("ext_data/items.dat", (void **)&buffer); - IT_ParseParms( buffer ); + IT_ParseParms(buffer); - gi.FS_FreeFile( buffer ); + gi.FS_FreeFile(buffer); } diff --git a/codeJK2/game/g_items.cpp b/codeJK2/game/g_items.cpp index 165e03e36e..e5d3ac3d59 100644 --- a/codeJK2/game/g_items.cpp +++ b/codeJK2/game/g_items.cpp @@ -29,18 +29,18 @@ along with this program; if not, see . #include "g_items.h" #include "wp_saber.h" -extern qboolean missionInfo_Updated; +extern qboolean missionInfo_Updated; extern void CrystalAmmoSettings(gentity_t *ent); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean PM_InGetUp( playerState_t *ps ); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean PM_InGetUp(playerState_t *ps); -extern cvar_t *g_spskill; +extern cvar_t *g_spskill; -#define MAX_BACTA_HEAL_AMOUNT 25 +#define MAX_BACTA_HEAL_AMOUNT 25 /* @@ -56,12 +56,12 @@ extern cvar_t *g_spskill; */ // Item Spawn flags -#define ITMSF_SUSPEND 1 -#define ITMSF_TEAM 2 -#define ITMSF_MONSTER 4 -#define ITMSF_NOTSOLID 8 -#define ITMSF_VERTICAL 16 -#define ITMSF_INVISIBLE 32 +#define ITMSF_SUSPEND 1 +#define ITMSF_TEAM 2 +#define ITMSF_MONSTER 4 +#define ITMSF_NOTSOLID 8 +#define ITMSF_VERTICAL 16 +#define ITMSF_INVISIBLE 32 //====================================================================== @@ -70,53 +70,42 @@ extern cvar_t *g_spskill; G_InventorySelectable =============== */ -qboolean G_InventorySelectable( int index,gentity_t *other) -{ - if (other->client->ps.inventory[index]) - { +qboolean G_InventorySelectable(int index, gentity_t *other) { + if (other->client->ps.inventory[index]) { return qtrue; } return qfalse; } -extern qboolean INV_GoodieKeyGive( gentity_t *target ); -extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); -int Pickup_Holdable( gentity_t *ent, gentity_t *other ) -{ - int i,original; - - other->client->ps.stats[STAT_ITEMS] |= (1<item->giTag); - - if ( ent->item->giTag == INV_SECURITY_KEY ) - {//give the key - //FIXME: temp message - gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SECURITY_KEY" ); - INV_SecurityKeyGive( other, ent->message ); - } - else if ( ent->item->giTag == INV_GOODIE_KEY ) - {//give the key - //FIXME: temp message - gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SUPPLY_KEY" ); - INV_GoodieKeyGive( other ); - } - else - {// Picking up a normal item? +extern qboolean INV_GoodieKeyGive(gentity_t *target); +extern qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname); +int Pickup_Holdable(gentity_t *ent, gentity_t *other) { + int i, original; + + other->client->ps.stats[STAT_ITEMS] |= (1 << ent->item->giTag); + + if (ent->item->giTag == INV_SECURITY_KEY) { // give the key + // FIXME: temp message + gi.SendServerCommand(0, "cp @INGAME_YOU_TOOK_SECURITY_KEY"); + INV_SecurityKeyGive(other, ent->message); + } else if (ent->item->giTag == INV_GOODIE_KEY) { // give the key + // FIXME: temp message + gi.SendServerCommand(0, "cp @INGAME_YOU_TOOK_SUPPLY_KEY"); + INV_GoodieKeyGive(other); + } else { // Picking up a normal item? other->client->ps.inventory[ent->item->giTag]++; } // Got a security key // Set the inventory select, just in case it hasn't original = cg.inventorySelect; - for ( i = 0 ; i < INV_MAX ; i++ ) - { - if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) - { + for (i = 0; i < INV_MAX; i++) { + if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX)) { cg.inventorySelect = (INV_MAX - 1); } - if ( G_InventorySelectable( cg.inventorySelect,other ) ) - { + if (G_InventorySelectable(cg.inventorySelect, other)) { return 60; } cg.inventorySelect++; @@ -127,132 +116,105 @@ int Pickup_Holdable( gentity_t *ent, gentity_t *other ) return 60; } - //====================================================================== -int Add_Ammo2 (gentity_t *ent, int ammoType, int count) -{ +int Add_Ammo2(gentity_t *ent, int ammoType, int count) { - if (ammoType != AMMO_FORCE) - { + if (ammoType != AMMO_FORCE) { ent->client->ps.ammo[ammoType] += count; // since the ammo is the weapon in this case, picking up ammo should actually give you the weapon - switch( ammoType ) - { + switch (ammoType) { case AMMO_THERMAL: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_THERMAL ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_THERMAL); break; case AMMO_DETPACK: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_DET_PACK ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_DET_PACK); break; case AMMO_TRIPMINE: - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_TRIP_MINE ); + ent->client->ps.stats[STAT_WEAPONS] |= (1 << WP_TRIP_MINE); break; } - if ( ent->client->ps.ammo[ammoType] > ammoData[ammoType].max ) - { + if (ent->client->ps.ammo[ammoType] > ammoData[ammoType].max) { ent->client->ps.ammo[ammoType] = ammoData[ammoType].max; return qfalse; } - } - else - { - if ( ent->client->ps.forcePower >= ammoData[ammoType].max ) - {//if have full force, just get 25 extra per crystal + } else { + if (ent->client->ps.forcePower >= ammoData[ammoType].max) { // if have full force, just get 25 extra per crystal ent->client->ps.forcePower += 25; - } - else - {//else if don't have full charge, give full amount, up to max + 25 + } else { // else if don't have full charge, give full amount, up to max + 25 ent->client->ps.forcePower += count; - if ( ent->client->ps.forcePower >= ammoData[ammoType].max + 25 ) - {//cap at max + 25 + if (ent->client->ps.forcePower >= ammoData[ammoType].max + 25) { // cap at max + 25 ent->client->ps.forcePower = ammoData[ammoType].max + 25; } } - if ( ent->client->ps.forcePower >= ammoData[ammoType].max*2 ) - {//always cap at twice a full charge - ent->client->ps.forcePower = ammoData[ammoType].max*2; - return qfalse; // can't hold any more + if (ent->client->ps.forcePower >= ammoData[ammoType].max * 2) { // always cap at twice a full charge + ent->client->ps.forcePower = ammoData[ammoType].max * 2; + return qfalse; // can't hold any more } } return qtrue; } //------------------------------------------------------- -void Add_Ammo (gentity_t *ent, int weapon, int count) -{ - Add_Ammo2(ent,weaponData[weapon].ammoIndex,count); -} +void Add_Ammo(gentity_t *ent, int weapon, int count) { Add_Ammo2(ent, weaponData[weapon].ammoIndex, count); } //------------------------------------------------------- -int Pickup_Ammo (gentity_t *ent, gentity_t *other) -{ - int quantity; +int Pickup_Ammo(gentity_t *ent, gentity_t *other) { + int quantity; - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; } - Add_Ammo2 (other, ent->item->giTag, quantity); + Add_Ammo2(other, ent->item->giTag, quantity); return 30; } //====================================================================== -void Add_Batteries( gentity_t *ent, int *count ) -{ - if ( ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count ) - { - if ( *count + ent->client->ps.batteryCharge > MAX_BATTERIES ) - { +void Add_Batteries(gentity_t *ent, int *count) { + if (ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count) { + if (*count + ent->client->ps.batteryCharge > MAX_BATTERIES) { // steal what we need, then leave the rest for later - *count -= ( MAX_BATTERIES - ent->client->ps.batteryCharge ); + *count -= (MAX_BATTERIES - ent->client->ps.batteryCharge); ent->client->ps.batteryCharge = MAX_BATTERIES; - } - else - { + } else { // just drain all of the batteries ent->client->ps.batteryCharge += *count; *count = 0; } - G_AddEvent( ent, EV_BATTERIES_CHARGED, 0 ); + G_AddEvent(ent, EV_BATTERIES_CHARGED, 0); } } //------------------------------------------------------- -int Pickup_Battery( gentity_t *ent, gentity_t *other ) -{ - int quantity; +int Pickup_Battery(gentity_t *ent, gentity_t *other) { + int quantity; - if ( ent->count ) - { + if (ent->count) { quantity = ent->count; - } - else - { + } else { quantity = ent->item->quantity; } // There may be some left over in quantity if the player is close to full, but with pickup items, this amount will just be lost - Add_Batteries( other, &quantity ); + Add_Batteries(other, &quantity); return 30; } //====================================================================== - -extern void WP_SaberInitBladeData( gentity_t *ent ); -extern void CG_ChangeWeapon( int num ); -int Pickup_Weapon (gentity_t *ent, gentity_t *other) -{ - int quantity; - qboolean hadWeapon = qfalse; +extern void WP_SaberInitBladeData(gentity_t *ent); +extern void CG_ChangeWeapon(int num); +int Pickup_Weapon(gentity_t *ent, gentity_t *other) { + int quantity; + qboolean hadWeapon = qfalse; /* if ( ent->count || (ent->activator && !ent->activator->s.number) ) @@ -266,64 +228,51 @@ int Pickup_Weapon (gentity_t *ent, gentity_t *other) */ // dropped items are always picked up - if ( ent->flags & FL_DROPPED_ITEM ) - { + if (ent->flags & FL_DROPPED_ITEM) { quantity = ent->count; - } - else - {//wasn't dropped - quantity = ent->item->quantity?ent->item->quantity:50; + } else { // wasn't dropped + quantity = ent->item->quantity ? ent->item->quantity : 50; } // add the weapon - if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) ) - { + if (other->client->ps.stats[STAT_WEAPONS] & (1 << ent->item->giTag)) { hadWeapon = qtrue; } - other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag ); + other->client->ps.stats[STAT_WEAPONS] |= (1 << ent->item->giTag); - if ( ent->item->giTag == WP_SABER && !hadWeapon ) - { - WP_SaberInitBladeData( other ); + if (ent->item->giTag == WP_SABER && !hadWeapon) { + WP_SaberInitBladeData(other); } - if ( other->s.number ) - {//NPC - if ( other->s.weapon == WP_NONE ) - {//NPC with no weapon picked up a weapon, change to this weapon - //FIXME: clear/set the alt-fire flag based on the picked up weapon and my class? + if (other->s.number) { // NPC + if (other->s.weapon == WP_NONE) { // NPC with no weapon picked up a weapon, change to this weapon + // FIXME: clear/set the alt-fire flag based on the picked up weapon and my class? other->client->ps.weapon = ent->item->giTag; other->client->ps.weaponstate = WEAPON_RAISING; - ChangeWeapon( other, ent->item->giTag ); - if ( ent->item->giTag == WP_SABER ) - { + ChangeWeapon(other, ent->item->giTag); + if (ent->item->giTag == WP_SABER) { other->client->ps.saberActive = qtrue; - G_CreateG2AttachedWeaponModel( other, other->client->ps.saberModel ); - } - else - { - G_CreateG2AttachedWeaponModel( other, weaponData[ent->item->giTag].weaponMdl ); + G_CreateG2AttachedWeaponModel(other, other->client->ps.saberModel); + } else { + G_CreateG2AttachedWeaponModel(other, weaponData[ent->item->giTag].weaponMdl); } } } - if ( quantity ) - { + if (quantity) { // Give ammo - Add_Ammo( other, ent->item->giTag, quantity ); + Add_Ammo(other, ent->item->giTag, quantity); } return 5; } - //====================================================================== -int ITM_AddHealth (gentity_t *ent, int count) -{ +int ITM_AddHealth(gentity_t *ent, int count) { ent->health += count; - if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health { ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; @@ -331,16 +280,15 @@ int ITM_AddHealth (gentity_t *ent, int count) } return qtrue; - } -int Pickup_Health (gentity_t *ent, gentity_t *other) { - int max; - int quantity; +int Pickup_Health(gentity_t *ent, gentity_t *other) { + int max; + int quantity; max = other->client->ps.stats[STAT_MAX_HEALTH]; - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; @@ -348,11 +296,11 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { other->health += quantity; - if (other->health > max ) { + if (other->health > max) { other->health = max; } - if ( ent->item->giTag == 100 ) { // mega health respawns slow + if (ent->item->giTag == 100) { // mega health respawns slow return 120; } @@ -361,13 +309,11 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { //====================================================================== -int ITM_AddArmor (gentity_t *ent, int count) -{ +int ITM_AddArmor(gentity_t *ent, int count) { ent->client->ps.stats[STAT_ARMOR] += count; - if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; return qfalse; } @@ -375,51 +321,44 @@ int ITM_AddArmor (gentity_t *ent, int count) return qtrue; } - -int Pickup_Armor( gentity_t *ent, gentity_t *other ) { +int Pickup_Armor(gentity_t *ent, gentity_t *other) { // make sure that the shield effect is on other->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; other->client->ps.stats[STAT_ARMOR] += ent->item->quantity; - if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] ) { + if (other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH]) { other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH]; } return 30; } - - //====================================================================== -int Pickup_Holocron( gentity_t *ent, gentity_t *other ) -{ +int Pickup_Holocron(gentity_t *ent, gentity_t *other) { int forcePower = ent->item->giTag; int forceLevel = ent->count; // check if out of range - if( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS ) - { - gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel ); + if (forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS) { + gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel); return 1; } // don't pick up if already known AND your level is higher than pickup level - if ( ( other->client->ps.forcePowersKnown & ( 1 << forcePower )) ) - { - //don't pickup if item is lower than current level - if( other->client->ps.forcePowerLevel[forcePower] >= forceLevel ) - { + if ((other->client->ps.forcePowersKnown & (1 << forcePower))) { + // don't pickup if item is lower than current level + if (other->client->ps.forcePowerLevel[forcePower] >= forceLevel) { return 1; } } other->client->ps.forcePowerLevel[forcePower] = forceLevel; - other->client->ps.forcePowersKnown |= ( 1 << forcePower ); + other->client->ps.forcePowersKnown |= (1 << forcePower); - missionInfo_Updated = qtrue; // Activate flashing text - gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine. - cg_updatedDataPadForcePower1.integer = forcePower+1; + missionInfo_Updated = qtrue; // Activate flashing text + gi.cvar_set("cg_updatedDataPadForcePower1", va("%d", forcePower + 1)); // The +1 is offset in the print routine. + cg_updatedDataPadForcePower1.integer = forcePower + 1; gi.cvar_set("cg_updatedDataPadForcePower2", "0"); // The +1 is offset in the print routine. cg_updatedDataPadForcePower2.integer = 0; gi.cvar_set("cg_updatedDataPadForcePower3", "0"); // The +1 is offset in the print routine. @@ -428,7 +367,6 @@ int Pickup_Holocron( gentity_t *ent, gentity_t *other ) return 1; } - //====================================================================== /* @@ -436,29 +374,20 @@ int Pickup_Holocron( gentity_t *ent, gentity_t *other ) RespawnItem =============== */ -void RespawnItem( gentity_t *ent ) { -} +void RespawnItem(gentity_t *ent) {} - -qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) -{ - if ( !item->item ) { +qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper) { + if (!item->item) { return qfalse; } - if ( item->item->giType == IT_HOLDABLE && - item->item->giTag == INV_SECURITY_KEY ) { + if (item->item->giType == IT_HOLDABLE && item->item->giTag == INV_SECURITY_KEY) { return qfalse; } - if ( (item->flags&FL_DROPPED_ITEM) - && item->activator != &g_entities[0] - && pickerupper->s.number - && pickerupper->s.weapon == WP_NONE - && pickerupper->enemy - && pickerupper->painDebounceTime < level.time - && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time //not surrendering - && !(pickerupper->NPC->scriptFlags&SCF_FORCED_MARCH) ) // not being forced to march - {//non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key - if ( level.time - item->s.time < 3000 )//was 5000 + if ((item->flags & FL_DROPPED_ITEM) && item->activator != &g_entities[0] && pickerupper->s.number && pickerupper->s.weapon == WP_NONE && + pickerupper->enemy && pickerupper->painDebounceTime < level.time && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time // not surrendering + && !(pickerupper->NPC->scriptFlags & SCF_FORCED_MARCH)) // not being forced to march + { // non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key + if (level.time - item->s.time < 3000) // was 5000 { return qfalse; } @@ -471,105 +400,83 @@ qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) Touch_Item =============== */ -extern cvar_t *g_timescale; -void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { - int respawn = 0; +extern cvar_t *g_timescale; +void Touch_Item(gentity_t *ent, gentity_t *other, trace_t *trace) { + int respawn = 0; if (!other->client) return; if (other->health < 1) - return; // dead people can't pickup + return; // dead people can't pickup - if ( other->client->ps.pm_time > 0 ) - {//cant pick up when out of control + if (other->client->ps.pm_time > 0) { // cant pick up when out of control return; } // Only monsters can pick it up - if ((ent->spawnflags & ITMSF_MONSTER) && (other->client->playerTeam == TEAM_PLAYER)) - { + if ((ent->spawnflags & ITMSF_MONSTER) && (other->client->playerTeam == TEAM_PLAYER)) { return; } // Only starfleet can pick it up - if ((ent->spawnflags & ITMSF_TEAM) && (other->client->playerTeam != TEAM_PLAYER)) - { + if ((ent->spawnflags & ITMSF_TEAM) && (other->client->playerTeam != TEAM_PLAYER)) { return; } - - if ( other->client->NPC_class == CLASS_ATST || - other->client->NPC_class == CLASS_GONK || - other->client->NPC_class == CLASS_MARK1 || - other->client->NPC_class == CLASS_MARK2 || - other->client->NPC_class == CLASS_MOUSE || - other->client->NPC_class == CLASS_PROBE || - other->client->NPC_class == CLASS_PROTOCOL || - other->client->NPC_class == CLASS_R2D2 || - other->client->NPC_class == CLASS_R5D2 || - other->client->NPC_class == CLASS_SEEKER || - other->client->NPC_class == CLASS_REMOTE || - other->client->NPC_class == CLASS_SENTRY ) - {//FIXME: some flag would be better - //droids can't pick up items/weapons! + if (other->client->NPC_class == CLASS_ATST || other->client->NPC_class == CLASS_GONK || other->client->NPC_class == CLASS_MARK1 || + other->client->NPC_class == CLASS_MARK2 || other->client->NPC_class == CLASS_MOUSE || other->client->NPC_class == CLASS_PROBE || + other->client->NPC_class == CLASS_PROTOCOL || other->client->NPC_class == CLASS_R2D2 || other->client->NPC_class == CLASS_R5D2 || + other->client->NPC_class == CLASS_SEEKER || other->client->NPC_class == CLASS_REMOTE || + other->client->NPC_class == CLASS_SENTRY) { // FIXME: some flag would be better + // droids can't pick up items/weapons! return; } - //FIXME: need to make them run toward a dropped weapon when fleeing without one? - //FIXME: need to make them come out of flee mode when pick up their old weapon? - if ( CheckItemCanBePickedUpByNPC( ent, other ) ) - { - if ( other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent ) - {//they were running to pick me up, they did, so clear goal + // FIXME: need to make them run toward a dropped weapon when fleeing without one? + // FIXME: need to make them come out of flee mode when pick up their old weapon? + if (CheckItemCanBePickedUpByNPC(ent, other)) { + if (other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent) { // they were running to pick me up, they did, so clear goal other->NPC->goalEntity = NULL; other->NPC->squadState = SQUAD_STAND_AND_SHOOT; } - } - else if (!(ent->spawnflags & ITMSF_TEAM) && !(ent->spawnflags & ITMSF_MONSTER)) - {// Only player can pick it up - if ( other->s.number != 0 ) // Not the player? + } else if (!(ent->spawnflags & ITMSF_TEAM) && !(ent->spawnflags & ITMSF_MONSTER)) { // Only player can pick it up + if (other->s.number != 0) // Not the player? { return; } } // the same pickup rules are used for client side and server side - if ( !BG_CanItemBeGrabbed( &ent->s, &other->client->ps ) ) { + if (!BG_CanItemBeGrabbed(&ent->s, &other->client->ps)) { return; } - if ( other->client ) - { - if ( other->client->ps.eFlags&EF_FORCE_GRIPPED ) - {//can't pick up anything while being gripped + if (other->client) { + if (other->client->ps.eFlags & EF_FORCE_GRIPPED) { // can't pick up anything while being gripped return; } - if ( PM_InKnockDown( &other->client->ps ) && !PM_InGetUp( &other->client->ps ) ) - {//can't pick up while in a knockdown + if (PM_InKnockDown(&other->client->ps) && !PM_InGetUp(&other->client->ps)) { // can't pick up while in a knockdown return; } } - if (!ent->item) { //not an item! - gi.Printf( "Touch_Item: %s is not an item!\n", ent->classname); + if (!ent->item) { // not an item! + gi.Printf("Touch_Item: %s is not an item!\n", ent->classname); return; } qboolean bHadWeapon = qfalse; // call the item-specific pickup function - switch( ent->item->giType ) - { + switch (ent->item->giType) { case IT_WEAPON: - if ( other->NPC && other->s.weapon == WP_NONE ) - {//Make them duck and sit here for a few seconds - int pickUpTime = Q_irand( 1000, 3000 ); - TIMER_Set( other, "duck", pickUpTime ); - TIMER_Set( other, "roamTime", pickUpTime ); - TIMER_Set( other, "stick", pickUpTime ); - TIMER_Set( other, "verifyCP", pickUpTime ); - TIMER_Set( other, "attackDelay", 600 ); + if (other->NPC && other->s.weapon == WP_NONE) { // Make them duck and sit here for a few seconds + int pickUpTime = Q_irand(1000, 3000); + TIMER_Set(other, "duck", pickUpTime); + TIMER_Set(other, "roamTime", pickUpTime); + TIMER_Set(other, "stick", pickUpTime); + TIMER_Set(other, "verifyCP", pickUpTime); + TIMER_Set(other, "attackDelay", 600); respawn = 0; } - if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) ) - { + if (other->client->ps.stats[STAT_WEAPONS] & (1 << ent->item->giTag)) { bHadWeapon = qtrue; } respawn = Pickup_Weapon(ent, other); @@ -587,49 +494,42 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { respawn = Pickup_Holdable(ent, other); break; case IT_BATTERY: - respawn = Pickup_Battery( ent, other ); + respawn = Pickup_Battery(ent, other); break; case IT_HOLOCRON: - respawn = Pickup_Holocron( ent, other ); + respawn = Pickup_Holocron(ent, other); break; default: return; } - if ( !respawn ) - { + if (!respawn) { return; } // play the normal pickup sound - if ( !other->s.number && g_timescale->value < 1.0f ) - {//SIGH... with timescale on, you lose events left and right -extern void CG_ItemPickup( int itemNum, qboolean bHadItem ); + if (!other->s.number && g_timescale->value < 1.0f) { // SIGH... with timescale on, you lose events left and right + extern void CG_ItemPickup(int itemNum, qboolean bHadItem); // but we're SP so we'll cheat - cgi_S_StartSound( NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound( ent->item->pickup_sound ) ); + cgi_S_StartSound(NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound(ent->item->pickup_sound)); // show icon and name on status bar - CG_ItemPickup( ent->s.modelindex, bHadWeapon ); - } - else - { - if ( bHadWeapon ) - { - G_AddEvent( other, EV_ITEM_PICKUP, -ent->s.modelindex ); - } - else - { - G_AddEvent( other, EV_ITEM_PICKUP, ent->s.modelindex ); + CG_ItemPickup(ent->s.modelindex, bHadWeapon); + } else { + if (bHadWeapon) { + G_AddEvent(other, EV_ITEM_PICKUP, -ent->s.modelindex); + } else { + G_AddEvent(other, EV_ITEM_PICKUP, ent->s.modelindex); } } // fire item targets - G_UseTargets (ent, other); + G_UseTargets(ent, other); // wait of -1 will not respawn -// if ( ent->wait == -1 ) + // if ( ent->wait == -1 ) { - //why not just remove me? - G_FreeEntity( ent ); + // why not just remove me? + G_FreeEntity(ent); /* //NOTE: used to do this: (for respawning?) ent->svFlags |= SVF_NOCLIENT; @@ -641,7 +541,6 @@ extern void CG_ItemPickup( int itemNum, qboolean bHadItem ); } } - //====================================================================== /* @@ -651,47 +550,40 @@ LaunchItem Spawns an item and tosses it forward ================ */ -gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, char *target ) { - gentity_t *dropped; +gentity_t *LaunchItem(gitem_t *item, vec3_t origin, vec3_t velocity, char *target) { + gentity_t *dropped; dropped = G_Spawn(); dropped->s.eType = ET_ITEM; - dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex - dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item + dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex + dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item dropped->classname = item->classname; dropped->item = item; // try using the "correct" mins/maxs first - VectorSet( dropped->mins, item->mins[0], item->mins[1], item->mins[2] ); - VectorSet( dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2] ); + VectorSet(dropped->mins, item->mins[0], item->mins[1], item->mins[2]); + VectorSet(dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2]); - if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) && - (!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2])) - { - VectorSet( dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS ); - VectorScale( dropped->maxs, -1, dropped->mins ); + if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) && (!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2])) { + VectorSet(dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); + VectorScale(dropped->maxs, -1, dropped->mins); } - dropped->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them + dropped->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; // CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them - if ( target && target[0] ) - { - dropped->target = G_NewString( target ); - } - else - { + if (target && target[0]) { + dropped->target = G_NewString(target); + } else { // if not targeting something, auto-remove after 30 seconds // only if it's NOT a security or goodie key - if (dropped->item->giTag != INV_SECURITY_KEY ) - { + if (dropped->item->giTag != INV_SECURITY_KEY) { dropped->e_ThinkFunc = thinkF_G_FreeEntity; dropped->nextthink = level.time + 30000; } - if ( dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE ) - { + if (dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE) { dropped->nextthink = -1; dropped->e_ThinkFunc = thinkF_NULL; } @@ -699,29 +591,24 @@ gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, char *targ dropped->e_TouchFunc = touchF_Touch_Item; - if ( item->giType == IT_WEAPON ) - { + if (item->giType == IT_WEAPON) { // give weapon items zero pitch, a random yaw, and rolled onto their sides...but would be bad to do this for a bowcaster - if ( item->giTag != WP_BOWCASTER - && item->giTag != WP_THERMAL - && item->giTag != WP_TRIP_MINE - && item->giTag != WP_DET_PACK ) - { - VectorSet( dropped->s.angles, 0, Q_flrand(-1.0f, 1.0f) * 180, 90.0f ); - G_SetAngles( dropped, dropped->s.angles ); + if (item->giTag != WP_BOWCASTER && item->giTag != WP_THERMAL && item->giTag != WP_TRIP_MINE && item->giTag != WP_DET_PACK) { + VectorSet(dropped->s.angles, 0, Q_flrand(-1.0f, 1.0f) * 180, 90.0f); + G_SetAngles(dropped, dropped->s.angles); } } - G_SetOrigin( dropped, origin ); + G_SetOrigin(dropped, origin); dropped->s.pos.trType = TR_GRAVITY; dropped->s.pos.trTime = level.time; - VectorCopy( velocity, dropped->s.pos.trDelta ); + VectorCopy(velocity, dropped->s.pos.trDelta); dropped->s.eFlags |= EF_BOUNCE_HALF; dropped->flags = FL_DROPPED_ITEM; - gi.linkentity (dropped); + gi.linkentity(dropped); return dropped; } @@ -733,34 +620,30 @@ Drop_Item Spawns an item and tosses it forward ================ */ -gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle, qboolean copytarget ) { - gentity_t *dropped = NULL; - vec3_t velocity; - vec3_t angles; +gentity_t *Drop_Item(gentity_t *ent, gitem_t *item, float angle, qboolean copytarget) { + gentity_t *dropped = NULL; + vec3_t velocity; + vec3_t angles; - VectorCopy( ent->s.apos.trBase, angles ); + VectorCopy(ent->s.apos.trBase, angles); angles[YAW] += angle; - angles[PITCH] = 0; // always forward + angles[PITCH] = 0; // always forward - AngleVectors( angles, velocity, NULL, NULL ); - VectorScale( velocity, 150, velocity ); + AngleVectors(angles, velocity, NULL, NULL); + VectorScale(velocity, 150, velocity); velocity[2] += 200 + Q_flrand(-1.0f, 1.0f) * 50; - if ( copytarget ) - { - dropped = LaunchItem( item, ent->s.pos.trBase, velocity, ent->opentarget ); - } - else - { - dropped = LaunchItem( item, ent->s.pos.trBase, velocity, NULL ); + if (copytarget) { + dropped = LaunchItem(item, ent->s.pos.trBase, velocity, ent->opentarget); + } else { + dropped = LaunchItem(item, ent->s.pos.trBase, velocity, NULL); } - dropped->activator = ent;//so we know who we belonged to so they can pick it back up later - dropped->s.time = level.time;//mark this time so we aren't picked up instantly by the guy who dropped us + dropped->activator = ent; // so we know who we belonged to so they can pick it back up later + dropped->s.time = level.time; // mark this time so we aren't picked up instantly by the guy who dropped us return dropped; } - /* ================ Use_Item @@ -768,26 +651,22 @@ Use_Item Respawn the item ================ */ -void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - if ( (ent->svFlags&SVF_PLAYER_USABLE) && other && !other->s.number ) - {//used directly by the player, pick me up - GEntity_TouchFunc( ent, other, NULL ); - } - else - {//use me - if ( ent->spawnflags & 32 ) // invisible +void Use_Item(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if ((ent->svFlags & SVF_PLAYER_USABLE) && other && !other->s.number) { // used directly by the player, pick me up + GEntity_TouchFunc(ent, other, NULL); + } else { // use me + if (ent->spawnflags & 32) // invisible { // If it was invisible, first use makes it visible.... ent->s.eFlags &= ~EF_NODRAW; - ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM; + ent->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; ent->spawnflags &= ~32; return; } - G_ActivateBehavior( ent, BSET_USE ); - RespawnItem( ent ); + G_ActivateBehavior(ent, BSET_USE); + RespawnItem(ent); } } @@ -804,153 +683,137 @@ free fall from their spawn points #ifndef FINAL_BUILD extern int delayedShutDown; #endif -void FinishSpawningItem( gentity_t *ent ) { - trace_t tr; - vec3_t dest; - gitem_t *item; - int itemNum; - - itemNum=1; - for ( item = bg_itemlist + 1 ; item->classname ; item++,itemNum++) - { - if (!strcmp(item->classname,ent->classname)) - { +void FinishSpawningItem(gentity_t *ent) { + trace_t tr; + vec3_t dest; + gitem_t *item; + int itemNum; + + itemNum = 1; + for (item = bg_itemlist + 1; item->classname; item++, itemNum++) { + if (!strcmp(item->classname, ent->classname)) { break; } } // Set bounding box for item - VectorSet( ent->mins, item->mins[0],item->mins[1] ,item->mins[2]); - VectorSet( ent->maxs, item->maxs[0],item->maxs[1] ,item->maxs[2]); + VectorSet(ent->mins, item->mins[0], item->mins[1], item->mins[2]); + VectorSet(ent->maxs, item->maxs[0], item->maxs[1], item->maxs[2]); - if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) && - (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2])) - { - VectorSet (ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2);//to match the comments in the items.dat file! - VectorSet (ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); + if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) && (!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2])) { + VectorSet(ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2); // to match the comments in the items.dat file! + VectorSet(ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); } - if ((item->quantity) && (item->giType == IT_AMMO)) - { + if ((item->quantity) && (item->giType == IT_AMMO)) { ent->count = item->quantity; } - if ((item->quantity) && (item->giType == IT_BATTERY)) - { + if ((item->quantity) && (item->giType == IT_BATTERY)) { ent->count = item->quantity; } - -// if ( item->giType == IT_WEAPON ) // NOTE: james thought it was ok to just always do this? + // if ( item->giType == IT_WEAPON ) // NOTE: james thought it was ok to just always do this? { ent->s.radius = 20; - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); - gi.G2API_InitGhoul2Model( ent->ghoul2, ent->item->world_model, G_ModelIndex( ent->item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0); + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); + gi.G2API_InitGhoul2Model(ent->ghoul2, ent->item->world_model, G_ModelIndex(ent->item->world_model), NULL_HANDLE, NULL_HANDLE, 0, 0); } // Set crystal ammo amount based on skill level -/* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) || - (itemNum == ITM_AMMO_CRYSTAL_DN) || - (itemNum == ITM_AMMO_CRYSTAL_FORGE) || - (itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) || - (itemNum == ITM_AMMO_CRYSTAL_STASIS)) - { - CrystalAmmoSettings(ent); - } -*/ + /* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) || + (itemNum == ITM_AMMO_CRYSTAL_DN) || + (itemNum == ITM_AMMO_CRYSTAL_FORGE) || + (itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) || + (itemNum == ITM_AMMO_CRYSTAL_STASIS)) + { + CrystalAmmoSettings(ent); + } + */ ent->s.eType = ET_ITEM; - ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex - ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item + ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex + ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item - ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_BODY;//CONTENTS_TRIGGER| + ent->contents = CONTENTS_TRIGGER | CONTENTS_ITEM; // CONTENTS_BODY;//CONTENTS_TRIGGER| ent->e_TouchFunc = touchF_Touch_Item; // useing an item causes it to respawn ent->e_UseFunc = useF_Use_Item; - ent->svFlags |= SVF_PLAYER_USABLE;//so player can pick it up + ent->svFlags |= SVF_PLAYER_USABLE; // so player can pick it up // Hang in air? - ent->s.origin[2] += 1;//just to get it off the damn ground because coplanar = insolid - if ( ent->spawnflags & ITMSF_SUSPEND) - { + ent->s.origin[2] += 1; // just to get it off the damn ground because coplanar = insolid + if (ent->spawnflags & ITMSF_SUSPEND) { // suspended - G_SetOrigin( ent, ent->s.origin ); - } - else - { + G_SetOrigin(ent, ent->s.origin); + } else { // drop to floor - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD ); - gi.trace( &tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID|CONTENTS_PLAYERCLIP, G2_NOCOLLIDE, 0 ); - if ( tr.startsolid ) - { - if ( g_entities[tr.entityNum].inuse ) - { - gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), g_entities[tr.entityNum].classname ); - } - else - { - gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin) ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD); + gi.trace(&tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID | CONTENTS_PLAYERCLIP, G2_NOCOLLIDE, 0); + if (tr.startsolid) { + if (g_entities[tr.entityNum].inuse) { + gi.Printf(S_COLOR_RED "FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), + g_entities[tr.entityNum].classname); + } else { + gi.Printf(S_COLOR_RED "FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin)); } - assert( 0 && "item starting in solid"); + assert(0 && "item starting in solid"); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region delayedShutDown = level.time + 100; } #endif - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } // allow to ride movers ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); } -/* ? don't need this - // team slaves and targeted items aren't present at start - if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) { - ent->s.eFlags |= EF_NODRAW; - ent->contents = 0; - return; - } -*/ - if ( ent->spawnflags & ITMSF_INVISIBLE ) // invisible + /* ? don't need this + // team slaves and targeted items aren't present at start + if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) { + ent->s.eFlags |= EF_NODRAW; + ent->contents = 0; + return; + } + */ + if (ent->spawnflags & ITMSF_INVISIBLE) // invisible { ent->s.eFlags |= EF_NODRAW; ent->contents = 0; } - if ( ent->spawnflags & ITMSF_NOTSOLID ) // not solid + if (ent->spawnflags & ITMSF_NOTSOLID) // not solid { ent->contents = 0; } - gi.linkentity (ent); + gi.linkentity(ent); } - -char itemRegistered[MAX_ITEMS+1]; - +char itemRegistered[MAX_ITEMS + 1]; /* ============== ClearRegisteredItems ============== */ -void ClearRegisteredItems( void ) { - for ( int i = 0; i < bg_numItems; i++ ) - { +void ClearRegisteredItems(void) { + for (int i = 0; i < bg_numItems; i++) { itemRegistered[i] = '0'; } - itemRegistered[ bg_numItems ] = 0; + itemRegistered[bg_numItems] = 0; - RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. - RegisterItem( FindItemForWeapon( WP_STUN_BATON ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. - RegisterItem( FindItemForInventory( INV_ELECTROBINOCULARS )); + RegisterItem(FindItemForWeapon(WP_BRYAR_PISTOL)); // these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. + RegisterItem(FindItemForWeapon(WP_STUN_BATON)); // these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts. + RegisterItem(FindItemForInventory(INV_ELECTROBINOCULARS)); // saber or baton is cached in SP_info_player_deathmatch now. -extern void Player_CacheFromPrevLevel(void);//g_client.cpp - Player_CacheFromPrevLevel(); //reads from transition carry-over; + extern void Player_CacheFromPrevLevel(void); // g_client.cpp + Player_CacheFromPrevLevel(); // reads from transition carry-over; } /* @@ -960,15 +823,14 @@ RegisterItem The item will be added to the precache list =============== */ -void RegisterItem( gitem_t *item ) { - if ( !item ) { - G_Error( "RegisterItem: NULL" ); +void RegisterItem(gitem_t *item) { + if (!item) { + G_Error("RegisterItem: NULL"); } - itemRegistered[ item - bg_itemlist ] = '1'; - gi.SetConfigstring(CS_ITEMS, itemRegistered); //Write the needed items to a config string + itemRegistered[item - bg_itemlist] = '1'; + gi.SetConfigstring(CS_ITEMS, itemRegistered); // Write the needed items to a config string } - /* =============== SaveRegisteredItems @@ -977,25 +839,25 @@ Write the needed items to a config string so the client will know which ones to precache =============== */ -void SaveRegisteredItems( void ) { -/* char string[MAX_ITEMS+1]; - int i; - int count; - - count = 0; - for ( i = 0 ; i < bg_numItems ; i++ ) { - if ( itemRegistered[i] ) { - count++; - string[i] = '1'; - } else { - string[i] = '0'; +void SaveRegisteredItems(void) { + /* char string[MAX_ITEMS+1]; + int i; + int count; + + count = 0; + for ( i = 0 ; i < bg_numItems ; i++ ) { + if ( itemRegistered[i] ) { + count++; + string[i] = '1'; + } else { + string[i] = '0'; + } } - } - string[ bg_numItems ] = 0; + string[ bg_numItems ] = 0; - gi.Printf( "%i items registered\n", count ); - gi.SetConfigstring(CS_ITEMS, string); -*/ + gi.Printf( "%i items registered\n", count ); + gi.SetConfigstring(CS_ITEMS, string); + */ gi.SetConfigstring(CS_ITEMS, itemRegistered); } @@ -1006,7 +868,7 @@ item_spawn_use if an item is given a targetname, it will be spawned in when used ============ */ -void item_spawn_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void item_spawn_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { self->nextthink = level.time + 50; @@ -1025,94 +887,85 @@ Items can't be immediately dropped to floor, because they might be on an entity that hasn't spawned yet. ============ */ -void G_SpawnItem (gentity_t *ent, gitem_t *item) { - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnFloat( "wait", "0", &ent->wait ); +void G_SpawnItem(gentity_t *ent, gitem_t *item) { + G_SpawnFloat("random", "0", &ent->random); + G_SpawnFloat("wait", "0", &ent->wait); - RegisterItem( item ); + RegisterItem(item); ent->item = item; // targetname indicates they want to spawn it later - if( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_item_spawn_use; - } - else - { // some movers spawn on the second frame, so delay item + } else { // some movers spawn on the second frame, so delay item // spawns until the third frame so they can ride trains ent->nextthink = level.time + START_TIME_MOVERS_SPAWNED + 50; ent->e_ThinkFunc = thinkF_FinishSpawningItem; } - ent->physicsBounce = 0.50; // items are bouncy + ent->physicsBounce = 0.50; // items are bouncy // Set a default infoString text color // NOTE: if we want to do cool cross-hair colors for items, we can just modify this, but for now, don't do it - VectorSet( ent->startRGBA, 1.0f, 1.0f, 1.0f ); + VectorSet(ent->startRGBA, 1.0f, 1.0f, 1.0f); } - /* ================ G_BounceItem ================ */ -void G_BounceItem( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceItem(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); // cut the velocity to keep from bouncing forever - VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta ); + VectorScale(ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta); // check for stop - if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) { - G_SetOrigin( ent, trace->endpos ); + if (trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40) { + G_SetOrigin(ent, trace->endpos); ent->s.groundEntityNum = trace->entityNum; return; } - VectorAdd( ent->currentOrigin, trace->plane.normal, ent->currentOrigin); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorAdd(ent->currentOrigin, trace->plane.normal, ent->currentOrigin); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } - /* ================ G_RunItem ================ */ -void G_RunItem( gentity_t *ent ) { - vec3_t origin; - trace_t tr; - int contents; - int mask; +void G_RunItem(gentity_t *ent) { + vec3_t origin; + trace_t tr; + int contents; + int mask; // if groundentity has been set to -1, it may have been pushed off an edge - if ( ent->s.groundEntityNum == ENTITYNUM_NONE ) - { - if ( ent->s.pos.trType != TR_GRAVITY ) - { + if (ent->s.groundEntityNum == ENTITYNUM_NONE) { + if (ent->s.pos.trType != TR_GRAVITY) { ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; } } - if ( ent->s.pos.trType == TR_STATIONARY ) - { + if (ent->s.pos.trType == TR_STATIONARY) { // check think function - G_RunThink( ent ); - if ( !g_gravity->value ) - { + G_RunThink(ent); + if (!g_gravity->value) { ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; ent->s.pos.trDelta[0] += Q_flrand(-1.0f, 1.0f) * 40.0f; // I dunno, just do this?? @@ -1123,58 +976,47 @@ void G_RunItem( gentity_t *ent ) { } // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); // trace a line from the previous position to the current position - if ( ent->clipmask ) - { + if (ent->clipmask) { mask = ent->clipmask; - } - else - { - mask = MASK_SOLID|CONTENTS_PLAYERCLIP;//shouldn't be able to get anywhere player can't + } else { + mask = MASK_SOLID | CONTENTS_PLAYERCLIP; // shouldn't be able to get anywhere player can't } int ignore = ENTITYNUM_NONE; - if ( ent->owner ) - { + if (ent->owner) { ignore = ent->owner->s.number; - } - else if ( ent->activator ) - { + } else if (ent->activator) { ignore = ent->activator->s.number; } - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, G2_NOCOLLIDE, 0); - VectorCopy( tr.endpos, ent->currentOrigin ); + VectorCopy(tr.endpos, ent->currentOrigin); - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( ent ); // FIXME: avoid this for stationary? + gi.linkentity(ent); // FIXME: avoid this for stationary? // check think function - G_RunThink( ent ); + G_RunThink(ent); - if ( tr.fraction == 1 ) - { - if ( g_gravity->value <= 0 ) - { - if ( ent->s.apos.trType != TR_LINEAR ) - { - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + if (tr.fraction == 1) { + if (g_gravity->value <= 0) { + if (ent->s.apos.trType != TR_LINEAR) { + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; - ent->s.apos.trDelta[1] = Q_flrand( -300, 300 ); - ent->s.apos.trDelta[0] = Q_flrand( -10, 10 ); - ent->s.apos.trDelta[2] = Q_flrand( -10, 10 ); + ent->s.apos.trDelta[1] = Q_flrand(-300, 300); + ent->s.apos.trDelta[0] = Q_flrand(-10, 10); + ent->s.apos.trDelta[2] = Q_flrand(-10, 10); ent->s.apos.trTime = level.time; } } - //friction in zero-G - if ( !g_gravity->value ) - { + // friction in zero-G + if (!g_gravity->value) { float friction = 0.975f; /*friction -= ent->mass/1000.0f; if ( friction < 0.1 ) @@ -1182,24 +1024,22 @@ void G_RunItem( gentity_t *ent ) { friction = 0.1f; } */ - VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(ent->s.pos.trDelta, friction, ent->s.pos.trDelta); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } return; } // if it is in a nodrop volume, remove it - contents = gi.pointcontents( ent->currentOrigin, -1 ); - if ( contents & CONTENTS_NODROP ) - { - G_FreeEntity( ent ); + contents = gi.pointcontents(ent->currentOrigin, -1); + if (contents & CONTENTS_NODROP) { + G_FreeEntity(ent); return; } - if ( !tr.startsolid ) - { - G_BounceItem( ent, &tr ); + if (!tr.startsolid) { + G_BounceItem(ent, &tr); } } @@ -1209,26 +1049,22 @@ ItemUse_Bacta ================ */ -void ItemUse_Bacta(gentity_t *ent) -{ - if (!ent || !ent->client) - { +void ItemUse_Bacta(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER] ) - { + if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER]) { return; } ent->health += MAX_BACTA_HEAL_AMOUNT; - if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } ent->client->ps.inventory[INV_BACTA_CANISTER]--; - G_SoundOnEnt( ent, CHAN_VOICE, va( "sound/weapons/force/heal%d.mp3", Q_irand( 1, 4 ) ) ); + G_SoundOnEnt(ent, CHAN_VOICE, va("sound/weapons/force/heal%d.mp3", Q_irand(1, 4))); } diff --git a/codeJK2/game/g_main.cpp b/codeJK2/game/g_main.cpp index 22135c231f..cb206fc9ab 100644 --- a/codeJK2/game/g_main.cpp +++ b/codeJK2/game/g_main.cpp @@ -33,104 +33,83 @@ along with this program; if not, see . #include "anims.h" #include "g_icarus.h" #include "objectives.h" -#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... +#include "../cgame/cg_local.h" // yeah I know this is naughty, but we're shipping soon... #include "time.h" #include "../code/qcommon/ojk_saved_game_helper.h" #include "qcommon/q_version.h" -extern CNavigator navigator; +extern CNavigator navigator; -static int navCalcPathTime = 0; -int eventClearTime = 0; +static int navCalcPathTime = 0; +int eventClearTime = 0; -#define STEPSIZE 18 +#define STEPSIZE 18 -level_locals_t level; -game_import_t gi; -game_export_t globals; -gentity_t g_entities[MAX_GENTITIES]; -unsigned int g_entityInUseBits[MAX_GENTITIES/32]; +level_locals_t level; +game_import_t gi; +game_export_t globals; +gentity_t g_entities[MAX_GENTITIES]; +unsigned int g_entityInUseBits[MAX_GENTITIES / 32]; void G_ASPreCacheFree(void); -void ClearAllInUse(void) -{ - memset(g_entityInUseBits,0,sizeof(g_entityInUseBits)); -} +void ClearAllInUse(void) { memset(g_entityInUseBits, 0, sizeof(g_entityInUseBits)); } -void SetInUse(gentity_t *ent) -{ - assert(((uintptr_t)ent)>=(uintptr_t)g_entities); - assert(((uintptr_t)ent)<=(uintptr_t)(g_entities+MAX_GENTITIES-1)); - unsigned int entNum=ent-g_entities; - g_entityInUseBits[entNum/32]|=((unsigned int)1)<<(entNum&0x1f); +void SetInUse(gentity_t *ent) { + assert(((uintptr_t)ent) >= (uintptr_t)g_entities); + assert(((uintptr_t)ent) <= (uintptr_t)(g_entities + MAX_GENTITIES - 1)); + unsigned int entNum = ent - g_entities; + g_entityInUseBits[entNum / 32] |= ((unsigned int)1) << (entNum & 0x1f); } -void ClearInUse(gentity_t *ent) -{ - assert(((uintptr_t)ent)>=(uintptr_t)g_entities); - assert(((uintptr_t)ent)<=(uintptr_t)(g_entities+MAX_GENTITIES-1)); - unsigned int entNum=ent-g_entities; - g_entityInUseBits[entNum/32]&=~(((unsigned int)1)<<(entNum&0x1f)); +void ClearInUse(gentity_t *ent) { + assert(((uintptr_t)ent) >= (uintptr_t)g_entities); + assert(((uintptr_t)ent) <= (uintptr_t)(g_entities + MAX_GENTITIES - 1)); + unsigned int entNum = ent - g_entities; + g_entityInUseBits[entNum / 32] &= ~(((unsigned int)1) << (entNum & 0x1f)); } -qboolean PInUse(unsigned int entNum) -{ - assert(entNum>=0); - assert(entNum= 0); + assert(entNum < MAX_GENTITIES); return (qboolean)((g_entityInUseBits[entNum / 32] & (1u << (entNum & 0x1f))) != 0); } -qboolean PInUse2(gentity_t *ent) -{ - assert(((uintptr_t)ent)>=(uintptr_t)g_entities); - assert(((uintptr_t)ent)<=(uintptr_t)(g_entities+MAX_GENTITIES-1)); - unsigned int entNum=ent-g_entities; +qboolean PInUse2(gentity_t *ent) { + assert(((uintptr_t)ent) >= (uintptr_t)g_entities); + assert(((uintptr_t)ent) <= (uintptr_t)(g_entities + MAX_GENTITIES - 1)); + unsigned int entNum = ent - g_entities; return (qboolean)((g_entityInUseBits[entNum / 32] & (1u << (entNum & 0x1f))) != 0); } -void WriteInUseBits() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void WriteInUseBits() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('I', 'N', 'U', 'S'), - ::g_entityInUseBits); + saved_game.write_chunk(INT_ID('I', 'N', 'U', 'S'), ::g_entityInUseBits); } -void ReadInUseBits() -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void ReadInUseBits() { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('I', 'N', 'U', 'S'), - ::g_entityInUseBits); + saved_game.read_chunk(INT_ID('I', 'N', 'U', 'S'), ::g_entityInUseBits); // This is only temporary. Once I have converted all the ent->inuse refs, // it won;t be needed -MW. - for(int i=0;iclient - || player->client->pers.teamState.state != TEAM_ACTIVE - || level.time - player->client->pers.enterTime < 100 ) - {//player hasn't spawned yet + if (!player->client || player->client->pers.teamState.state != TEAM_ACTIVE || + level.time - player->client->pers.enterTime < 100) { // player hasn't spawned yet return; } - if ( player->health <= 0 && player->max_health > 0 ) - {//defeat music - if ( level.dmState != DM_DEATH ) - { + if (player->health <= 0 && player->max_health > 0) { // defeat music + if (level.dmState != DM_DEATH) { level.dmState = DM_DEATH; } } - if ( level.dmState == DM_DEATH ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "death" ); + if (level.dmState == DM_DEATH) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "death"); return; } - if ( level.dmState == DM_BOSS ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "boss" ); + if (level.dmState == DM_BOSS) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "boss"); return; } - if ( level.dmState == DM_SILENCE ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "silence" ); + if (level.dmState == DM_SILENCE) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "silence"); return; } - if ( level.dmBeatTime > level.time ) - {//not on a beat + if (level.dmBeatTime > level.time) { // not on a beat return; } - level.dmBeatTime = level.time + 1000;//1 second beats + level.dmBeatTime = level.time + 1000; // 1 second beats - if ( player->health <= 20 ) - { + if (player->health <= 20) { danger = 1; } - //enemy-based - VectorCopy( player->currentOrigin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + // enemy-based + VectorCopy(player->currentOrigin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; - if ( !ent || !ent->inuse ) - { + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; + if (!ent || !ent->inuse) { continue; } - if ( !ent->client || !ent->NPC ) - { - if ( ent->classname && (!Q_stricmp( "PAS", ent->classname )||!Q_stricmp( "misc_turret", ent->classname )) ) - {//a turret + if (!ent->client || !ent->NPC) { + if (ent->classname && (!Q_stricmp("PAS", ent->classname) || !Q_stricmp("misc_turret", ent->classname))) { // a turret entTeam = ent->noDamageTeam; - } - else - { + } else { continue; } - } - else - {//an NPC + } else { // an NPC entTeam = ent->client->playerTeam; } - if ( entTeam == player->client->playerTeam ) - {//ally + if (entTeam == player->client->playerTeam) { // ally continue; } - if ( entTeam == TEAM_NEUTRAL && (!ent->enemy || !ent->enemy->client || ent->enemy->client->playerTeam != player->client->playerTeam) ) - {//a droid that is not mad at me or my allies + if (entTeam == TEAM_NEUTRAL && (!ent->enemy || !ent->enemy->client || + ent->enemy->client->playerTeam != player->client->playerTeam)) { // a droid that is not mad at me or my allies continue; } - if ( !gi.inPVS( player->currentOrigin, ent->currentOrigin ) ) - {//not potentially visible + if (!gi.inPVS(player->currentOrigin, ent->currentOrigin)) { // not potentially visible continue; } - if ( ent->client && ent->s.weapon == WP_NONE ) - {//they don't have a weapon... FIXME: only do this for droids? + if (ent->client && ent->s.weapon == WP_NONE) { // they don't have a weapon... FIXME: only do this for droids? continue; } LOScalced = clearLOS = qfalse; - if ( (ent->enemy==player&&(!ent->NPC||ent->NPC->confusionTimeclient&&ent->client->ps.weaponTime) || (!ent->client&&ent->attackDebounceTime>level.time)) - {//mad - if ( ent->health > 0 ) - {//alive - //FIXME: do I really need this check? - if ( ent->s.weapon == WP_SABER && ent->client && !ent->client->ps.saberActive && ent->enemy != player ) - {//a Jedi who has not yet gotten made at me + if ((ent->enemy == player && (!ent->NPC || ent->NPC->confusionTime < level.time)) || (ent->client && ent->client->ps.weaponTime) || + (!ent->client && ent->attackDebounceTime > level.time)) { // mad + if (ent->health > 0) { // alive + // FIXME: do I really need this check? + if (ent->s.weapon == WP_SABER && ent->client && !ent->client->ps.saberActive && + ent->enemy != player) { // a Jedi who has not yet gotten made at me continue; } - if ( ent->NPC && ent->NPC->behaviorState == BS_CINEMATIC ) - {//they're not actually going to do anything about being mad at me... + if (ent->NPC && ent->NPC->behaviorState == BS_CINEMATIC) { // they're not actually going to do anything about being mad at me... continue; } - //okay, they're in my PVS, but how close are they? Are they actively attacking me? - if ( !ent->client && ent->s.weapon == WP_TURRET && ent->fly_sound_debounce_time && ent->fly_sound_debounce_time - level.time < 10000 ) - {//a turret that shot at me less than ten seconds ago - } - else if ( ent->client && ent->client->ps.lastShotTime && ent->client->ps.lastShotTime - level.time < 10000 ) - {//an NPC that shot at me less than ten seconds ago - } - else - {//not actively attacking me lately, see how far away they are - distSq = DistanceSquared( ent->currentOrigin, player->currentOrigin ); - if ( distSq > 4194304/*2048*2048*/ ) - {//> 2048 away + // okay, they're in my PVS, but how close are they? Are they actively attacking me? + if (!ent->client && ent->s.weapon == WP_TURRET && ent->fly_sound_debounce_time && + ent->fly_sound_debounce_time - level.time < 10000) { // a turret that shot at me less than ten seconds ago + } else if (ent->client && ent->client->ps.lastShotTime && + ent->client->ps.lastShotTime - level.time < 10000) { // an NPC that shot at me less than ten seconds ago + } else { // not actively attacking me lately, see how far away they are + distSq = DistanceSquared(ent->currentOrigin, player->currentOrigin); + if (distSq > 4194304 /*2048*2048*/) { //> 2048 away continue; - } - else if ( distSq > 1048576/*1024*1024*/ ) - {//> 1024 away - clearLOS = G_ClearLOS( player, player->client->renderInfo.eyePoint, ent ); + } else if (distSq > 1048576 /*1024*1024*/) { //> 1024 away + clearLOS = G_ClearLOS(player, player->client->renderInfo.eyePoint, ent); LOScalced = qtrue; - if ( clearLOS == qfalse ) - {//No LOS + if (clearLOS == qfalse) { // No LOS continue; } } @@ -358,57 +305,48 @@ static void G_DynamicMusicUpdate( void ) } } - if ( level.dmState == DM_EXPLORE ) - {//only do these visibility checks if you're still in exploration mode - if ( !InFront( ent->currentOrigin, player->currentOrigin, player->client->ps.viewangles, 0.0f) ) - {//not in front + if (level.dmState == DM_EXPLORE) { // only do these visibility checks if you're still in exploration mode + if (!InFront(ent->currentOrigin, player->currentOrigin, player->client->ps.viewangles, 0.0f)) { // not in front continue; } - if ( !LOScalced ) - { - clearLOS = G_ClearLOS( player, player->client->renderInfo.eyePoint, ent ); + if (!LOScalced) { + clearLOS = G_ClearLOS(player, player->client->renderInfo.eyePoint, ent); } - if ( !clearLOS ) - {//can't see them directly + if (!clearLOS) { // can't see them directly continue; } } - if ( ent->health <= 0 ) - {//dead - if ( !ent->client || level.time - ent->s.time > 10000 ) - {//corpse has been dead for more than 10 seconds - //FIXME: coming across corpses should cause danger sounds too? + if (ent->health <= 0) { // dead + if (!ent->client || level.time - ent->s.time > 10000) { // corpse has been dead for more than 10 seconds + // FIXME: coming across corpses should cause danger sounds too? continue; } } - //we see enemies and/or corpses + // we see enemies and/or corpses danger++; } - if ( !battle ) - {//no active enemies, but look for missiles, shot impacts, etc... - int alert = G_CheckAlertEvents( player, qtrue, qtrue, 1024, 1024, -1, qfalse, AEL_SUSPICIOUS ); - if ( alert != -1 ) - {//FIXME: maybe tripwires and other FIXED things need their own sound, some kind of danger/caution theme - if ( G_CheckForDanger( player, alert ) ) - {//found danger near by + if (!battle) { // no active enemies, but look for missiles, shot impacts, etc... + int alert = G_CheckAlertEvents(player, qtrue, qtrue, 1024, 1024, -1, qfalse, AEL_SUSPICIOUS); + if (alert != -1) { // FIXME: maybe tripwires and other FIXED things need their own sound, some kind of danger/caution theme + if (G_CheckForDanger(player, alert)) { // found danger near by danger++; battle = 1; - } - else if ( level.alertEvents[alert].owner && (level.alertEvents[alert].owner == player->enemy || (level.alertEvents[alert].owner->client && level.alertEvents[alert].owner->client->playerTeam == player->client->enemyTeam) ) ) - {//NPC on enemy team of player made some noise - switch ( level.alertEvents[alert].level ) - { + } else if (level.alertEvents[alert].owner && + (level.alertEvents[alert].owner == player->enemy || + (level.alertEvents[alert].owner->client && + level.alertEvents[alert].owner->client->playerTeam == player->client->enemyTeam))) { // NPC on enemy team of player made some noise + switch (level.alertEvents[alert].level) { case AEL_DISCOVERED: - //dangerNear = qtrue; + // dangerNear = qtrue; break; case AEL_SUSPICIOUS: - //suspicious = qtrue; + // suspicious = qtrue; break; case AEL_MINOR: - //distraction = qtrue; + // distraction = qtrue; break; default: break; @@ -417,32 +355,22 @@ static void G_DynamicMusicUpdate( void ) } } - if ( battle ) - {//battle - this can interrupt level.dmDebounceTime of lower intensity levels - //play battle - if ( level.dmState != DM_ACTION ) - { - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "action" ); + if (battle) { // battle - this can interrupt level.dmDebounceTime of lower intensity levels + // play battle + if (level.dmState != DM_ACTION) { + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "action"); } level.dmState = DM_ACTION; - if ( battle > 5 ) - { - //level.dmDebounceTime = level.time + 8000;//don't change again for 5 seconds + if (battle > 5) { + // level.dmDebounceTime = level.time + 8000;//don't change again for 5 seconds + } else { + // level.dmDebounceTime = level.time + 3000 + 1000*battle; } - else - { - //level.dmDebounceTime = level.time + 3000 + 1000*battle; - } - } - else - { - if ( level.dmDebounceTime > level.time ) - {//not ready to switch yet + } else { + if (level.dmDebounceTime > level.time) { // not ready to switch yet return; - } - else - {//at least 1 second (for beats) - //level.dmDebounceTime = level.time + 1000;//FIXME: define beat time? + } else { // at least 1 second (for beats) + // level.dmDebounceTime = level.time + 1000;//FIXME: define beat time? } /* if ( danger || dangerNear ) @@ -463,18 +391,17 @@ static void G_DynamicMusicUpdate( void ) } else */ - {//still nothing dangerous going on - if ( level.dmState != DM_EXPLORE ) - {//just went to explore, hold it for a couple seconds at least - //level.dmDebounceTime = level.time + 2000; - gi.SetConfigstring( CS_DYNAMIC_MUSIC_STATE, "explore" ); + { // still nothing dangerous going on + if (level.dmState != DM_EXPLORE) { // just went to explore, hold it for a couple seconds at least + // level.dmDebounceTime = level.time + 2000; + gi.SetConfigstring(CS_DYNAMIC_MUSIC_STATE, "explore"); } level.dmState = DM_EXPLORE; - //FIXME: look for interest points and play "mysterious" music instead of exploration? - //FIXME: suspicious and distraction sounds should play some cue or change music in a subtle way? - //play exploration + // FIXME: look for interest points and play "mysterious" music instead of exploration? + // FIXME: suspicious and distraction sounds should play some cue or change music in a subtle way? + // play exploration } - //FIXME: when do we go to silence? + // FIXME: when do we go to silence? } } @@ -489,21 +416,20 @@ All but the first will have the FL_TEAMSLAVE flag set and teammaster field set All but the last will have the teamchain field set to the next one ================ */ -void G_FindTeams( void ) { - gentity_t *e, *e2; - int i, j; - int c, c2; +void G_FindTeams(void) { + gentity_t *e, *e2; + int i, j; + int c, c2; c = 0; c2 = 0; -// for ( i=1, e=g_entities,i ; i < globals.num_entities ; i++,e++ ) - for ( i=1 ; i < globals.num_entities ; i++ ) - { -// if (!e->inuse) -// continue; - if(!PInUse(i)) + // for ( i=1, e=g_entities,i ; i < globals.num_entities ; i++,e++ ) + for (i = 1; i < globals.num_entities; i++) { + // if (!e->inuse) + // continue; + if (!PInUse(i)) continue; - e=&g_entities[i]; + e = &g_entities[i]; if (!e->team) continue; @@ -512,21 +438,19 @@ void G_FindTeams( void ) { e->teammaster = e; c++; c2++; -// for (j=i+1, e2=e+1 ; j < globals.num_entities ; j++,e2++) - for (j=i+1; j < globals.num_entities ; j++) - { -// if (!e2->inuse) -// continue; - if(!PInUse(j)) + // for (j=i+1, e2=e+1 ; j < globals.num_entities ; j++,e2++) + for (j = i + 1; j < globals.num_entities; j++) { + // if (!e2->inuse) + // continue; + if (!PInUse(j)) continue; - e2=&g_entities[j]; + e2 = &g_entities[j]; if (!e2->team) continue; if (e2->flags & FL_TEAMSLAVE) continue; - if (!strcmp(e->team, e2->team)) - { + if (!strcmp(e->team, e2->team)) { c2++; e2->teamchain = e->teamchain; e->teamchain = e2; @@ -534,7 +458,7 @@ void G_FindTeams( void ) { e2->flags |= FL_TEAMSLAVE; // make sure that targets only point at the master - if ( e2->targetname ) { + if (e2->targetname) { e->targetname = e2->targetname; e2->targetname = NULL; } @@ -542,59 +466,58 @@ void G_FindTeams( void ) { } } - gi.Printf ("%i teams with %i entities\n", c, c2); + gi.Printf("%i teams with %i entities\n", c, c2); } - /* ============ G_InitCvars ============ */ -void G_InitCvars( void ) { +void G_InitCvars(void) { // don't override the cheat state set by the system - g_cheats = gi.cvar ("helpUsObi", "", 0); - g_developer = gi.cvar ("developer", "", 0); + g_cheats = gi.cvar("helpUsObi", "", 0); + g_developer = gi.cvar("developer", "", 0); // noset vars - gi.cvar( "gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_ROM ); - gi.cvar( "gamedate", SOURCE_DATE , CVAR_ROM ); - g_skippingcin = gi.cvar ("skippingCinematic", "0", CVAR_ROM); + gi.cvar("gamename", GAMEVERSION, CVAR_SERVERINFO | CVAR_ROM); + gi.cvar("gamedate", SOURCE_DATE, CVAR_ROM); + g_skippingcin = gi.cvar("skippingCinematic", "0", CVAR_ROM); // latched vars // change anytime vars - g_speed = gi.cvar( "g_speed", "250", CVAR_CHEAT ); - g_gravity = gi.cvar( "g_gravity", "800", CVAR_SAVEGAME|CVAR_ROM ); - g_sex = gi.cvar ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE|CVAR_SAVEGAME|CVAR_NORESTART ); - g_spskill = gi.cvar ("g_spskill", "0", CVAR_ARCHIVE | CVAR_SAVEGAME|CVAR_NORESTART); - g_knockback = gi.cvar( "g_knockback", "1000", CVAR_CHEAT ); - g_dismemberment = gi.cvar ( "g_dismemberment", "3", CVAR_ARCHIVE );//0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head, 4 = mega dismemberment - g_dismemberProbabilities = gi.cvar ( "g_dismemberProbabilities", "1", CVAR_ARCHIVE );//0 = ignore probabilities, 1 = use probabilities - g_synchSplitAnims = gi.cvar ( "g_synchSplitAnims", "1", 0 ); - - g_inactivity = gi.cvar ("g_inactivity", "0", 0); - g_debugMove = gi.cvar ("g_debugMove", "0", CVAR_CHEAT ); - g_debugDamage = gi.cvar ("g_debugDamage", "0", CVAR_CHEAT ); - g_ICARUSDebug = gi.cvar( "g_ICARUSDebug", "0", CVAR_CHEAT ); - g_timescale = gi.cvar( "timescale", "1", 0 ); - - g_subtitles = gi.cvar( "g_subtitles", "2", CVAR_ARCHIVE ); - com_buildScript = gi.cvar ("com_buildscript", "0", 0); - - g_saberAutoBlocking = gi.cvar( "g_saberAutoBlocking", "1", CVAR_ARCHIVE|CVAR_CHEAT );//must press +block button to do any blocking - g_saberRealisticCombat = gi.cvar( "g_saberRealisticCombat", "0", CVAR_ARCHIVE );//makes collision more precise, increases damage - g_saberMoveSpeed = gi.cvar( "g_saberMoveSpeed", "1", CVAR_ARCHIVE|CVAR_CHEAT );//how fast you run while attacking with a saber - g_saberAnimSpeed = gi.cvar( "g_saberAnimSpeed", "1", CVAR_ARCHIVE|CVAR_CHEAT );//how fast saber animations run - g_saberAutoAim = gi.cvar( "g_saberAutoAim", "1", CVAR_ARCHIVE|CVAR_CHEAT );//auto-aims at enemies when not moving or when just running forward - - g_AIsurrender = gi.cvar( "g_AIsurrender", "0", CVAR_CHEAT ); - g_numEntities = gi.cvar( "g_numEntities", "0", CVAR_CHEAT ); - - gi.cvar( "newTotalSecrets", "0", CVAR_ROM ); - gi.cvar_set("newTotalSecrets", "0");//used to carry over the count from SP_target_secret to ClientBegin - g_iscensored = gi.cvar( "ui_iscensored", "0", CVAR_ARCHIVE|CVAR_ROM|CVAR_INIT|CVAR_CHEAT|CVAR_NORESTART ); + g_speed = gi.cvar("g_speed", "250", CVAR_CHEAT); + g_gravity = gi.cvar("g_gravity", "800", CVAR_SAVEGAME | CVAR_ROM); + g_sex = gi.cvar("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_spskill = gi.cvar("g_spskill", "0", CVAR_ARCHIVE | CVAR_SAVEGAME | CVAR_NORESTART); + g_knockback = gi.cvar("g_knockback", "1000", CVAR_CHEAT); + g_dismemberment = gi.cvar("g_dismemberment", "3", CVAR_ARCHIVE); // 0 = none, 1 = arms and hands, 2 = legs, 3 = waist and head, 4 = mega dismemberment + g_dismemberProbabilities = gi.cvar("g_dismemberProbabilities", "1", CVAR_ARCHIVE); // 0 = ignore probabilities, 1 = use probabilities + g_synchSplitAnims = gi.cvar("g_synchSplitAnims", "1", 0); + + g_inactivity = gi.cvar("g_inactivity", "0", 0); + g_debugMove = gi.cvar("g_debugMove", "0", CVAR_CHEAT); + g_debugDamage = gi.cvar("g_debugDamage", "0", CVAR_CHEAT); + g_ICARUSDebug = gi.cvar("g_ICARUSDebug", "0", CVAR_CHEAT); + g_timescale = gi.cvar("timescale", "1", 0); + + g_subtitles = gi.cvar("g_subtitles", "2", CVAR_ARCHIVE); + com_buildScript = gi.cvar("com_buildscript", "0", 0); + + g_saberAutoBlocking = gi.cvar("g_saberAutoBlocking", "1", CVAR_ARCHIVE | CVAR_CHEAT); // must press +block button to do any blocking + g_saberRealisticCombat = gi.cvar("g_saberRealisticCombat", "0", CVAR_ARCHIVE); // makes collision more precise, increases damage + g_saberMoveSpeed = gi.cvar("g_saberMoveSpeed", "1", CVAR_ARCHIVE | CVAR_CHEAT); // how fast you run while attacking with a saber + g_saberAnimSpeed = gi.cvar("g_saberAnimSpeed", "1", CVAR_ARCHIVE | CVAR_CHEAT); // how fast saber animations run + g_saberAutoAim = gi.cvar("g_saberAutoAim", "1", CVAR_ARCHIVE | CVAR_CHEAT); // auto-aims at enemies when not moving or when just running forward + + g_AIsurrender = gi.cvar("g_AIsurrender", "0", CVAR_CHEAT); + g_numEntities = gi.cvar("g_numEntities", "0", CVAR_CHEAT); + + gi.cvar("newTotalSecrets", "0", CVAR_ROM); + gi.cvar_set("newTotalSecrets", "0"); // used to carry over the count from SP_target_secret to ClientBegin + g_iscensored = gi.cvar("ui_iscensored", "0", CVAR_ARCHIVE | CVAR_ROM | CVAR_INIT | CVAR_CHEAT | CVAR_NORESTART); } /* @@ -613,46 +536,42 @@ qboolean g_qbLoadTransition = qfalse; #ifndef FINAL_BUILD extern int fatalErrors; #endif -void InitGame( const char *mapname, const char *spawntarget, int checkSum, const char *entities, int levelTime, int randomSeed, int globalTime, SavedGameJustLoaded_e eSavedGameJustLoaded, qboolean qbLoadTransition ) -{ +void InitGame(const char *mapname, const char *spawntarget, int checkSum, const char *entities, int levelTime, int randomSeed, int globalTime, + SavedGameJustLoaded_e eSavedGameJustLoaded, qboolean qbLoadTransition) { giMapChecksum = checkSum; g_eSavedGameJustLoaded = eSavedGameJustLoaded; g_qbLoadTransition = qbLoadTransition; - gi.Printf ("------- Game Initialization -------\n"); - gi.Printf ("gamename: %s\n", GAMEVERSION); - gi.Printf ("gamedate: %s\n", SOURCE_DATE); + gi.Printf("------- Game Initialization -------\n"); + gi.Printf("gamename: %s\n", GAMEVERSION); + gi.Printf("gamedate: %s\n", SOURCE_DATE); - srand( randomSeed ); + srand(randomSeed); G_InitCvars(); G_InitMemory(); // set some level globals - memset( &level, 0, sizeof( level ) ); + memset(&level, 0, sizeof(level)); level.time = levelTime; level.globalTime = globalTime; - Q_strncpyz( level.mapname, mapname, sizeof(level.mapname) ); - if ( spawntarget != NULL && spawntarget[0] ) - { - Q_strncpyz( level.spawntarget, spawntarget, sizeof(level.spawntarget) ); - } - else - { + Q_strncpyz(level.mapname, mapname, sizeof(level.mapname)); + if (spawntarget != NULL && spawntarget[0]) { + Q_strncpyz(level.spawntarget, spawntarget, sizeof(level.spawntarget)); + } else { level.spawntarget[0] = 0; } - G_InitWorldSession(); // initialize all entities for this game - memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) ); + memset(g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0])); globals.gentities = g_entities; ClearAllInUse(); // initialize all clients for this game level.maxclients = 1; - level.clients = (gclient_t *) G_Alloc( level.maxclients * sizeof(level.clients[0]) ); + level.clients = (gclient_t *)G_Alloc(level.maxclients * sizeof(level.clients[0])); memset(level.clients, 0, level.maxclients * sizeof(level.clients[0])); // set client fields on player @@ -663,70 +582,66 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons // range are NEVER anything but clients globals.num_entities = MAX_CLIENTS; - //Set up NPC init data + // Set up NPC init data NPC_InitGame(); TIMER_Clear(); // - //ICARUS INIT START + // ICARUS INIT START gi.Printf("------ ICARUS Initialization ------\n"); gi.Printf("ICARUS version : %1.2f\n", ICARUS_VERSION); - Interface_Init( &interface_export ); + Interface_Init(&interface_export); ICARUS_Init(); - gi.Printf ("-----------------------------------\n"); + gi.Printf("-----------------------------------\n"); - //ICARUS INIT END + // ICARUS INIT END // - IT_LoadItemParms (); + IT_LoadItemParms(); ClearRegisteredItems(); - //FIXME: if this is from a loadgame, it needs to be sure to write this out whenever you do a savegame since the edges and routes are dynamic... - navCalculatePaths = ( navigator.Load( mapname, checkSum ) == qfalse ); + // FIXME: if this is from a loadgame, it needs to be sure to write this out whenever you do a savegame since the edges and routes are dynamic... + navCalculatePaths = (navigator.Load(mapname, checkSum) == qfalse); // parse the key/value pairs and spawn gentities - G_SpawnEntitiesFromString( entities ); + G_SpawnEntitiesFromString(entities); // general initialization G_FindTeams(); -// SaveRegisteredItems(); + // SaveRegisteredItems(); - gi.Printf ("-----------------------------------\n"); + gi.Printf("-----------------------------------\n"); - if ( navCalculatePaths ) - {//not loaded - need to calc paths - navCalcPathTime = level.time + START_TIME_NAV_CALC;//make sure all ents are in and linked - } - else - {//loaded - //FIXME: if this is from a loadgame, it needs to be sure to write this - //out whenever you do a savegame since the edges and routes are dynamic... - //OR: always do a navigator.CheckBlockedEdges() on map startup after nav-load/calc-paths - navigator.pathsCalculated = qtrue;//just to be safe? Does this get saved out? No... assumed - //need to do this, because combatpoint waypoints aren't saved out...? + if (navCalculatePaths) { // not loaded - need to calc paths + navCalcPathTime = level.time + START_TIME_NAV_CALC; // make sure all ents are in and linked + } else { // loaded + // FIXME: if this is from a loadgame, it needs to be sure to write this + // out whenever you do a savegame since the edges and routes are dynamic... + // OR: always do a navigator.CheckBlockedEdges() on map startup after nav-load/calc-paths + navigator.pathsCalculated = qtrue; // just to be safe? Does this get saved out? No... assumed + // need to do this, because combatpoint waypoints aren't saved out...? CP_FindCombatPointWaypoints(); navCalcPathTime = 0; - if ( g_eSavedGameJustLoaded == eNO ) - {//clear all the failed edges unless we just loaded the game (which would include failed edges) + if (g_eSavedGameJustLoaded == eNO) { // clear all the failed edges unless we just loaded the game (which would include failed edges) navigator.ClearAllFailedEdges(); } } player = &g_entities[0]; - //Init dynamic music + // Init dynamic music level.dmState = DM_EXPLORE; level.dmDebounceTime = 0; level.dmBeatTime = 0; - level.curAlertID = 1;//0 is default for lastAlertEvent, so... + level.curAlertID = 1; // 0 is default for lastAlertEvent, so... eventClearTime = 0; } @@ -735,42 +650,37 @@ void InitGame( const char *mapname, const char *spawntarget, int checkSum, cons ShutdownGame ================= */ -void ShutdownGame( void ) { - gi.Printf ("==== ShutdownGame ====\n"); +void ShutdownGame(void) { + gi.Printf("==== ShutdownGame ====\n"); - gi.Printf ("... ICARUS_Shutdown\n"); - ICARUS_Shutdown (); //Shut ICARUS down + gi.Printf("... ICARUS_Shutdown\n"); + ICARUS_Shutdown(); // Shut ICARUS down - gi.Printf ("... Reference Tags Cleared\n"); - TAG_Init(); //Clear the reference tags + gi.Printf("... Reference Tags Cleared\n"); + TAG_Init(); // Clear the reference tags - gi.Printf ("... Navigation Data Cleared\n"); + gi.Printf("... Navigation Data Cleared\n"); NAV_Shutdown(); // write all the client session data so we can get it back G_WriteSessionData(); -/* -Ghoul2 Insert Start -*/ - gi.Printf ("... Ghoul2 Models Shutdown\n"); - for (int i=0; is.number] ) - {//not playing a voice sound - //return task_complete - Q3_TaskIDComplete( ent, TID_CHAN_VOICE ); +static void G_CheckTasksCompleted(gentity_t *ent) { + if (Q3_TaskIDPending(ent, TID_CHAN_VOICE)) { + if (!gi.VoiceVolume[ent->s.number]) { // not playing a voice sound + // return task_complete + Q3_TaskIDComplete(ent, TID_CHAN_VOICE); } } - if ( Q3_TaskIDPending( ent, TID_LOCATION ) ) - { - char *currentLoc = G_GetLocationForEnt( ent ); + if (Q3_TaskIDPending(ent, TID_LOCATION)) { + char *currentLoc = G_GetLocationForEnt(ent); - if ( currentLoc && currentLoc[0] && Q_stricmp( ent->message, currentLoc ) == 0 ) - {//we're in the desired location - Q3_TaskIDComplete( ent, TID_LOCATION ); + if (currentLoc && currentLoc[0] && Q_stricmp(ent->message, currentLoc) == 0) { // we're in the desired location + Q3_TaskIDComplete(ent, TID_LOCATION); } - //FIXME: else see if were in other trigger_locations? + // FIXME: else see if were in other trigger_locations? } } -static void G_CheckSpecialPersistentEvents( gentity_t *ent ) -{//special-case alerts that would be a pain in the ass to have the ent's think funcs generate - if ( ent == NULL ) - { +static void G_CheckSpecialPersistentEvents(gentity_t *ent) { // special-case alerts that would be a pain in the ass to have the ent's think funcs generate + if (ent == NULL) { return; } - if ( ent->s.eType == ET_MISSILE && ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY ) - { - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); + if (ent->s.eType == ET_MISSILE && ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY) { + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER); } } - if ( ent->forcePushTime >= level.time ) - {//being pushed - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - //NOTE: presumes the player did the pushing, this is not always true, but shouldn't really matter? - if ( ent->item && ent->item->giTag == INV_SECURITY_KEY ) - { - AddSightEvent( player, ent->currentOrigin, 128, AEL_DISCOVERED );//security keys are more important - } - else - { - AddSightEvent( player, ent->currentOrigin, 128, AEL_SUSPICIOUS );//hmm... or should this always be discovered? + if (ent->forcePushTime >= level.time) { // being pushed + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + // NOTE: presumes the player did the pushing, this is not always true, but shouldn't really matter? + if (ent->item && ent->item->giTag == INV_SECURITY_KEY) { + AddSightEvent(player, ent->currentOrigin, 128, AEL_DISCOVERED); // security keys are more important + } else { + AddSightEvent(player, ent->currentOrigin, 128, AEL_SUSPICIOUS); // hmm... or should this always be discovered? } } } - if ( ent->contents == CONTENTS_LIGHTSABER && !Q_stricmp( "lightsaber", ent->classname ) ) - {//lightsaber - if( ent->owner && ent->owner->client ) - { - if ( ent->owner->client->ps.saberLength > 0 ) - {//it's on - //sight event - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED ); + if (ent->contents == CONTENTS_LIGHTSABER && !Q_stricmp("lightsaber", ent->classname)) { // lightsaber + if (ent->owner && ent->owner->client) { + if (ent->owner->client->ps.saberLength > 0) { // it's on + // sight event + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED); } } } @@ -955,9 +847,8 @@ G_RunThink Runs thinking code for this frame if necessary ============= */ -void G_RunThink (gentity_t *ent) -{ - float thinktime; +void G_RunThink(gentity_t *ent) { + float thinktime; /* if ( ent->NPC == NULL ) @@ -970,33 +861,29 @@ void G_RunThink (gentity_t *ent) */ thinktime = ent->nextthink; - if ( thinktime <= 0 ) - { + if (thinktime <= 0) { goto runicarus; } - if ( thinktime > level.time ) - { + if (thinktime > level.time) { goto runicarus; } ent->nextthink = 0; - if ( ent->e_ThinkFunc == thinkF_NULL ) // actually you don't need this if I check for it in the next function -slc + if (ent->e_ThinkFunc == thinkF_NULL) // actually you don't need this if I check for it in the next function -slc { - //gi.Error ( "NULL ent->think"); + // gi.Error ( "NULL ent->think"); goto runicarus; } - GEntity_ThinkFunc( ent ); // ent->think (ent); + GEntity_ThinkFunc(ent); // ent->think (ent); runicarus: - if ( ent->inuse ) // GEntity_ThinkFunc( ent ) can have freed up this ent if it was a type flier_child (stasis1 crash) + if (ent->inuse) // GEntity_ThinkFunc( ent ) can have freed up this ent if it was a type flier_child (stasis1 crash) { - if ( ent->NPC == NULL ) - { - if ( ent->taskManager && !stop_icarus ) - { - ent->taskManager->Update( ); + if (ent->NPC == NULL) { + if (ent->taskManager && !stop_icarus) { + ent->taskManager->Update(); } } } @@ -1008,46 +895,36 @@ G_Animate ------------------------- */ -void G_Animate ( gentity_t *self ) -{ - if ( self->s.eFlags & EF_SHADER_ANIM ) - { +void G_Animate(gentity_t *self) { + if (self->s.eFlags & EF_SHADER_ANIM) { return; } - if ( self->s.frame == self->endFrame ) - { - if ( self->svFlags & SVF_ANIMATING ) - { + if (self->s.frame == self->endFrame) { + if (self->svFlags & SVF_ANIMATING) { // ghoul2 requires some extra checks to see if the animation is done since it doesn't set the current frame directly - if ( self->ghoul2.size() ) - { + if (self->ghoul2.size()) { float frame, junk2; int junk; // I guess query ghoul2 to find out what the current frame is and see if we are done. - gi.G2API_GetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, - (cg.time?cg.time:level.time), &frame, &junk, &junk, &junk, &junk2, NULL ); + gi.G2API_GetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, (cg.time ? cg.time : level.time), &frame, &junk, &junk, &junk, + &junk2, NULL); // It NEVER seems to get to what you'd think the last frame would be, so I'm doing this to try and catch when the animation has stopped - if ( frame + 1 >= self->endFrame ) - { + if (frame + 1 >= self->endFrame) { self->svFlags &= ~SVF_ANIMATING; - Q3_TaskIDComplete( self, TID_ANIM_BOTH ); + Q3_TaskIDComplete(self, TID_ANIM_BOTH); } - } - else // not ghoul2 + } else // not ghoul2 { - if ( self->loopAnim ) - { + if (self->loopAnim) { self->s.frame = self->startFrame; - } - else - { + } else { self->svFlags &= ~SVF_ANIMATING; } - //Finished sequence - FIXME: only do this once even on looping anims? - Q3_TaskIDComplete( self, TID_ANIM_BOTH ); + // Finished sequence - FIXME: only do this once even on looping anims? + Q3_TaskIDComplete(self, TID_ANIM_BOTH); } } return; @@ -1056,39 +933,27 @@ void G_Animate ( gentity_t *self ) self->svFlags |= SVF_ANIMATING; // With ghoul2, we'll just set the desired start and end frame and let it do it's thing. - if ( self->ghoul2.size()) - { + if (self->ghoul2.size()) { self->s.frame = self->endFrame; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, - self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, + -1, -1); return; } - if ( self->startFrame < self->endFrame ) - { - if ( self->s.frame < self->startFrame || self->s.frame > self->endFrame ) - { + if (self->startFrame < self->endFrame) { + if (self->s.frame < self->startFrame || self->s.frame > self->endFrame) { self->s.frame = self->startFrame; - } - else - { + } else { self->s.frame++; } - } - else if ( self->startFrame > self->endFrame ) - { - if ( self->s.frame > self->startFrame || self->s.frame < self->endFrame ) - { + } else if (self->startFrame > self->endFrame) { + if (self->s.frame > self->startFrame || self->s.frame < self->endFrame) { self->s.frame = self->startFrame; - } - else - { + } else { self->s.frame--; } - } - else - { + } else { self->s.frame = self->endFrame; } } @@ -1168,71 +1033,60 @@ void UpdateTeamCounters( gentity_t *ent ) teamEnemyCount[ent->client->playerTeam]++; } */ -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -void G_PlayerGuiltDeath( void ) -{ - if ( player && player->client ) - {//simulate death +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +void G_PlayerGuiltDeath(void) { + if (player && player->client) { // simulate death player->client->ps.stats[STAT_HEALTH] = 0; - //turn off saber - if ( player->client->ps.weapon == WP_SABER && player->client->ps.saberActive ) - { - G_SoundOnEnt( player, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav" ); + // turn off saber + if (player->client->ps.weapon == WP_SABER && player->client->ps.saberActive) { + G_SoundOnEnt(player, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav"); player->client->ps.saberActive = qfalse; } - //play the "what have I done?!" anim - NPC_SetAnim( player, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // play the "what have I done?!" anim + NPC_SetAnim(player, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); player->client->ps.legsAnimTimer = player->client->ps.torsoAnimTimer = -1; - //look at yourself - player->client->ps.stats[STAT_DEAD_YAW] = player->client->ps.viewangles[YAW]+180; + // look at yourself + player->client->ps.stats[STAT_DEAD_YAW] = player->client->ps.viewangles[YAW] + 180; } } -extern void NPC_SetAnim(gentity_t *ent,int type,int anim,int priority); -extern void G_MakeTeamVulnerable( void ); +extern void NPC_SetAnim(gentity_t *ent, int type, int anim, int priority); +extern void G_MakeTeamVulnerable(void); int killPlayerTimer = 0; -void G_CheckEndLevelTimers( gentity_t *ent ) -{ - if ( killPlayerTimer && level.time > killPlayerTimer ) - { +void G_CheckEndLevelTimers(gentity_t *ent) { + if (killPlayerTimer && level.time > killPlayerTimer) { killPlayerTimer = 0; ent->health = 0; - if ( ent->client && ent->client->ps.stats[STAT_HEALTH] > 0 ) - { + if (ent->client && ent->client->ps.stats[STAT_HEALTH] > 0) { G_PlayerGuiltDeath(); - //cg.missionStatusShow = qtrue; + // cg.missionStatusShow = qtrue; statusTextIndex = MAX_MISSIONFAILED; - //debounce respawn time + // debounce respawn time ent->client->respawnTime = level.time + 2000; - //stop all scripts + // stop all scripts stop_icarus = qtrue; - //make the team killable + // make the team killable G_MakeTeamVulnerable(); } } } -void NAV_CheckCalcPaths( void ) -{ - if ( navCalcPathTime && navCalcPathTime < level.time ) - {//first time we've ever loaded this map... - //clear all the failed edges +void NAV_CheckCalcPaths(void) { + if (navCalcPathTime && navCalcPathTime < level.time) { // first time we've ever loaded this map... + // clear all the failed edges navigator.ClearAllFailedEdges(); - //Calculate all paths - NAV_CalculatePaths( level.mapname, giMapChecksum ); + // Calculate all paths + NAV_CalculatePaths(level.mapname, giMapChecksum); navigator.CalculatePaths(); #ifndef FINAL_BUILD - if ( fatalErrors ) - { - gi.Printf( S_COLOR_RED"Not saving .nav file due to fatal nav errors\n" ); - } - else + if (fatalErrors) { + gi.Printf(S_COLOR_RED "Not saving .nav file due to fatal nav errors\n"); + } else #endif - if ( navigator.Save( level.mapname, giMapChecksum ) == qfalse ) - { - gi.Printf("Unable to save navigations data for map \"%s\" (checksum:%d)\n", level.mapname, giMapChecksum ); + if (navigator.Save(level.mapname, giMapChecksum) == qfalse) { + gi.Printf("Unable to save navigations data for map \"%s\" (checksum:%d)\n", level.mapname, giMapChecksum); } navCalcPathTime = 0; } @@ -1245,278 +1099,222 @@ G_RunFrame Advances the non-player objects in the world ================ */ -#if AI_TIMERS +#if AI_TIMERS int AITime = 0; int navTime = 0; -#endif// AI_TIMERS +#endif // AI_TIMERS #ifndef FINAL_BUILD extern int delayedShutDown; #endif -void G_RunFrame( int levelTime ) { - int i; - gentity_t *ent; - int ents_inuse=0; // someone's gonna be pissed I put this here... -#if AI_TIMERS +void G_RunFrame(int levelTime) { + int i; + gentity_t *ent; + int ents_inuse = 0; // someone's gonna be pissed I put this here... +#if AI_TIMERS AITime = 0; navTime = 0; -#endif// AI_TIMERS +#endif // AI_TIMERS level.framenum++; level.previousTime = level.time; level.time = levelTime; - //msec = level.time - level.previousTime; + // msec = level.time - level.previousTime; NAV_CheckCalcPaths(); - //ResetTeamCounters(); + // ResetTeamCounters(); AI_UpdateGroups(); - if ( d_altRoutes->integer ) - { + if (d_altRoutes->integer) { navigator.CheckAllFailedEdges(); } navigator.ClearCheckedNodes(); - //remember last waypoint, clear current one -// for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) - for ( i = 0; i < globals.num_entities ; i++) - { -// if ( !ent->inuse ) -// continue; + // remember last waypoint, clear current one + // for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) + for (i = 0; i < globals.num_entities; i++) { + // if ( !ent->inuse ) + // continue; - if(!PInUse(i)) + if (!PInUse(i)) continue; ent = &g_entities[i]; - if ( ent->waypoint != WAYPOINT_NONE - && ent->noWaypointTime < level.time ) - { + if (ent->waypoint != WAYPOINT_NONE && ent->noWaypointTime < level.time) { ent->lastWaypoint = ent->waypoint; ent->waypoint = WAYPOINT_NONE; } - if ( d_altRoutes->integer ) - { - navigator.CheckFailedNodes( ent ); + if (d_altRoutes->integer) { + navigator.CheckFailedNodes(ent); } } - //Look to clear out old events + // Look to clear out old events ClearPlayerAlertEvents(); - //Run the frame for all entities -// for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) - for ( i = 0; i < globals.num_entities ; i++) - { -// if ( !ent->inuse ) -// continue; + // Run the frame for all entities + // for ( i = 0, ent = &g_entities[0]; i < globals.num_entities ; i++, ent++) + for (i = 0; i < globals.num_entities; i++) { + // if ( !ent->inuse ) + // continue; - if(!PInUse(i)) + if (!PInUse(i)) continue; ents_inuse++; ent = &g_entities[i]; // clear events that are too old - if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) { - if ( ent->s.event ) { - ent->s.event = 0; // &= EV_EVENT_BITS; - if ( ent->client ) { + if (level.time - ent->eventTime > EVENT_VALID_MSEC) { + if (ent->s.event) { + ent->s.event = 0; // &= EV_EVENT_BITS; + if (ent->client) { ent->client->ps.externalEvent = 0; } } - if ( ent->freeAfterEvent ) { + if (ent->freeAfterEvent) { // tempEntities or dropped items completely go away after their event - G_FreeEntity( ent ); + G_FreeEntity(ent); continue; - } else if ( ent->unlinkAfterEvent ) { + } else if (ent->unlinkAfterEvent) { // items that will respawn will hide themselves after their pickup event ent->unlinkAfterEvent = qfalse; - gi.unlinkentity( ent ); + gi.unlinkentity(ent); } } // temporary entities don't think - if ( ent->freeAfterEvent ) + if (ent->freeAfterEvent) continue; G_CheckTasksCompleted(ent); - G_Roff( ent ); + G_Roff(ent); - if( !ent->client ) - { - if ( !(ent->svFlags & SVF_SELF_ANIMATING) ) - {//FIXME: make sure this is done only for models with frames? - //Or just flag as animating? - if ( ent->s.eFlags & EF_ANIM_ONCE ) - { + if (!ent->client) { + if (!(ent->svFlags & SVF_SELF_ANIMATING)) { // FIXME: make sure this is done only for models with frames? + // Or just flag as animating? + if (ent->s.eFlags & EF_ANIM_ONCE) { ent->s.frame++; - } - else if ( !(ent->s.eFlags & EF_ANIM_ALLFAST) ) - { - G_Animate( ent ); + } else if (!(ent->s.eFlags & EF_ANIM_ALLFAST)) { + G_Animate(ent); } } } - G_CheckSpecialPersistentEvents( ent ); + G_CheckSpecialPersistentEvents(ent); - if ( ent->s.eType == ET_MISSILE ) - { - G_RunMissile( ent ); + if (ent->s.eType == ET_MISSILE) { + G_RunMissile(ent); continue; } - if ( ent->s.eType == ET_ITEM ) - { - G_RunItem( ent ); + if (ent->s.eType == ET_ITEM) { + G_RunItem(ent); continue; } - if ( ent->s.eType == ET_MOVER ) - { - if ( ent->model && Q_stricmp( "models/test/mikeg/tie_fighter.md3", ent->model ) == 0 ) - { - TieFighterThink( ent ); + if (ent->s.eType == ET_MOVER) { + if (ent->model && Q_stricmp("models/test/mikeg/tie_fighter.md3", ent->model) == 0) { + TieFighterThink(ent); } - G_RunMover( ent ); + G_RunMover(ent); continue; } - //The player - if ( i == 0 ) - { + // The player + if (i == 0) { // decay batteries if the goggles are active - if ( cg.zoomMode == 1 && ent->client->ps.batteryCharge > 0 ) - { + if (cg.zoomMode == 1 && ent->client->ps.batteryCharge > 0) { ent->client->ps.batteryCharge--; - } - else if ( cg.zoomMode == 3 && ent->client->ps.batteryCharge > 0 ) - { + } else if (cg.zoomMode == 3 && ent->client->ps.batteryCharge > 0) { ent->client->ps.batteryCharge -= 2; - if ( ent->client->ps.batteryCharge < 0 ) - { + if (ent->client->ps.batteryCharge < 0) { ent->client->ps.batteryCharge = 0; } } - G_CheckEndLevelTimers( ent ); - //Recalculate the nearest waypoint for the coming NPC updates + G_CheckEndLevelTimers(ent); + // Recalculate the nearest waypoint for the coming NPC updates NAV_FindPlayerWaypoint(); - if( ent->taskManager && !stop_icarus ) - { + if (ent->taskManager && !stop_icarus) { ent->taskManager->Update(); } - //dead - if ( ent->health <= 0 ) - { - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - pitch_roll_for_slope( ent, NULL ); + // dead + if (ent->health <= 0) { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // on the ground + pitch_roll_for_slope(ent, NULL); } } - continue; // players are ucmd driven + continue; // players are ucmd driven } - G_RunThink( ent ); // be aware that ent may be free after returning from here, at least one func frees them - ClearNPCGlobals(); // but these 2 funcs are ok - //UpdateTeamCounters( ent ); // to call anyway on a freed ent. + G_RunThink(ent); // be aware that ent may be free after returning from here, at least one func frees them + ClearNPCGlobals(); // but these 2 funcs are ok + // UpdateTeamCounters( ent ); // to call anyway on a freed ent. } // perform final fixups on the player ent = &g_entities[0]; - if ( ent->inuse ) - { - ClientEndFrame( ent ); + if (ent->inuse) { + ClientEndFrame(ent); } - if( g_numEntities->integer ) - { - gi.Printf( S_COLOR_WHITE"Number of Entities in use : %d\n", ents_inuse ); + if (g_numEntities->integer) { + gi.Printf(S_COLOR_WHITE "Number of Entities in use : %d\n", ents_inuse); } - //DEBUG STUFF + // DEBUG STUFF NAV_ShowDebugInfo(); NPC_ShowDebugInfo(); G_DynamicMusicUpdate(); -#if AI_TIMERS +#if AI_TIMERS AITime -= navTime; - if ( AITime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: total AI time: %d\n", AITime ); - } - else if ( AITime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: total AI time: %d\n", AITime ); - } - else if ( AITime > 2 ) - { - gi.Printf( S_COLOR_GREEN"total AI time: %d\n", AITime ); - } - if ( navTime > 20 ) - { - gi.Printf( S_COLOR_RED"ERROR: total nav time: %d\n", navTime ); - } - else if ( navTime > 10 ) - { - gi.Printf( S_COLOR_YELLOW"WARNING: total nav time: %d\n", navTime ); - } - else if ( navTime > 2 ) - { - gi.Printf( S_COLOR_GREEN"total nav time: %d\n", navTime ); - } -#endif// AI_TIMERS + if (AITime > 20) { + gi.Printf(S_COLOR_RED "ERROR: total AI time: %d\n", AITime); + } else if (AITime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: total AI time: %d\n", AITime); + } else if (AITime > 2) { + gi.Printf(S_COLOR_GREEN "total AI time: %d\n", AITime); + } + if (navTime > 20) { + gi.Printf(S_COLOR_RED "ERROR: total nav time: %d\n", navTime); + } else if (navTime > 10) { + gi.Printf(S_COLOR_YELLOW "WARNING: total nav time: %d\n", navTime); + } else if (navTime > 2) { + gi.Printf(S_COLOR_GREEN "total nav time: %d\n", navTime); + } +#endif // AI_TIMERS #ifndef FINAL_BUILD - if ( delayedShutDown != 0 && delayedShutDown < level.time ) - { - G_Error( "Game Errors. Scroll up the console to read them." ); + if (delayedShutDown != 0 && delayedShutDown < level.time) { + G_Error("Game Errors. Scroll up the console to read them."); } #endif #ifdef _DEBUG - if(!(level.framenum&0xff)) - { + if (!(level.framenum & 0xff)) { ValidateInUseBits(); } #endif } - - extern qboolean player_locked; -void G_LoadSave_WriteMiscData(void) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); +void G_LoadSave_WriteMiscData(void) { + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('L', 'C', 'K', 'D'), - ::player_locked); + saved_game.write_chunk(INT_ID('L', 'C', 'K', 'D'), ::player_locked); } +void G_LoadSave_ReadMiscData(void) { + ojk::SavedGameHelper saved_game(::gi.saved_game); - -void G_LoadSave_ReadMiscData(void) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.read_chunk( - INT_ID('L', 'C', 'K', 'D'), - ::player_locked); + saved_game.read_chunk(INT_ID('L', 'C', 'K', 'D'), ::player_locked); } +void PrintEntClassname(int gentNum) { Com_Printf("%d: %s in snapshot\n", gentNum, g_entities[gentNum].classname); } -void PrintEntClassname( int gentNum ) -{ - Com_Printf( "%d: %s in snapshot\n", gentNum, g_entities[gentNum].classname ); -} - -IGhoul2InfoArray &TheGameGhoul2InfoArray() -{ - return gi.TheGhoul2InfoArray(); -} +IGhoul2InfoArray &TheGameGhoul2InfoArray() { return gi.TheGhoul2InfoArray(); } diff --git a/codeJK2/game/g_mem.cpp b/codeJK2/game/g_mem.cpp index 4e46abd212..8c2efa3d6d 100644 --- a/codeJK2/game/g_mem.cpp +++ b/codeJK2/game/g_mem.cpp @@ -33,25 +33,22 @@ along with this program; if not, see . static char memoryPool[POOLSIZE]; */ -static int allocPoint; -static cvar_t *g_debugalloc; +static int allocPoint; +static cvar_t *g_debugalloc; -void *G_Alloc( int size ) { - if ( g_debugalloc->integer ) { - gi.Printf( "G_Alloc of %i bytes\n", size ); +void *G_Alloc(int size) { + if (g_debugalloc->integer) { + gi.Printf("G_Alloc of %i bytes\n", size); } - allocPoint += size; - + return gi.Malloc(size, TAG_G_ALLOC, qfalse); } -void G_InitMemory( void ) { +void G_InitMemory(void) { allocPoint = 0; - g_debugalloc = gi.cvar ("g_debugalloc", "0", 0); + g_debugalloc = gi.cvar("g_debugalloc", "0", 0); } -void Svcmd_GameMem_f( void ) { - gi.Printf( "Game memory status: %i allocated\n", allocPoint ); -} +void Svcmd_GameMem_f(void) { gi.Printf("Game memory status: %i allocated\n", allocPoint); } diff --git a/codeJK2/game/g_misc.cpp b/codeJK2/game/g_misc.cpp index 30af0d76eb..da70fe700a 100644 --- a/codeJK2/game/g_misc.cpp +++ b/codeJK2/game/g_misc.cpp @@ -30,44 +30,38 @@ along with this program; if not, see . #include "g_nav.h" #include "g_items.h" -extern gentity_t *G_FindDoorTrigger( gentity_t *door ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern void SetMiscModelDefaults( gentity_t *ent, useFunc_t use_func, char *material, int solid_mask,int animFlag, - qboolean take_damage, qboolean damage_model); +extern gentity_t *G_FindDoorTrigger(gentity_t *door); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern void SetMiscModelDefaults(gentity_t *ent, useFunc_t use_func, char *material, int solid_mask, int animFlag, qboolean take_damage, qboolean damage_model); #define MAX_AMMO_GIVE 4 - - /*QUAKED func_group (0 0 0) ? Used to group brushes together just for editor convenience. They are turned into normal brushes by the utilities. q3map_onlyvertexlighting 1 = brush only gets vertex lighting (reduces bsp size!) */ - /*QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay. */ -void SP_info_null( gentity_t *self ) { - //FIXME: store targetname and vector (origin) in a list for further reference... remove after 1st second of game? - G_SetOrigin( self, self->s.origin ); +void SP_info_null(gentity_t *self) { + // FIXME: store targetname and vector (origin) in a list for further reference... remove after 1st second of game? + G_SetOrigin(self, self->s.origin); self->e_ThinkFunc = thinkF_G_FreeEntity; - //Give other ents time to link + // Give other ents time to link self->nextthink = level.time + START_TIME_REMOVE_ENTS; } - /*QUAKED info_notnull (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. target_position does the same thing */ -void SP_info_notnull( gentity_t *self ){ - //FIXME: store in ref_tag system? - G_SetOrigin( self, self->s.origin ); +void SP_info_notnull(gentity_t *self) { + // FIXME: store in ref_tag system? + G_SetOrigin(self, self->s.origin); } - /*QUAKED light (0 1 0) (-8 -8 -8) (8 8 8) linear noIncidence START_OFF Non-displayed light. "light" overrides the default 300 intensity. - affects size @@ -79,9 +73,9 @@ Lights pointed at a target will be spotlights. "scale" multiplier for the light intensity - does not affect size (default 1) greater than 1 is brighter, between 0 and 1 is dimmer. "color" sets the light's color -"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, styles or start_off flag) -"style" to specify a specify light style, even for switchable lights! -"style_off" light style to use when switched off (Only for switchable lights) +"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, +styles or start_off flag) "style" to specify a specify light style, even for switchable lights! "style_off" light style to use when switched off (Only for +switchable lights) 1 FLICKER (first variety) 2 SLOW STRONG PULSE @@ -97,65 +91,57 @@ Lights pointed at a target will be spotlights. 12 FAST PULSE FOR JEREMY 13 Test Blending */ -static void misc_lightstyle_set ( gentity_t *ent) -{ +static void misc_lightstyle_set(gentity_t *ent) { const int mLightStyle = ent->count; const int mLightSwitchStyle = ent->bounceCount; const int mLightOffStyle = ent->fly_sound_debounce_time; - if (!ent->misc_dlight_active) - { //turn off - if (mLightOffStyle) //i have a light style i'd like to use when off + if (!ent->misc_dlight_active) { // turn off + if (mLightOffStyle) // i have a light style i'd like to use when off { char lightstyle[32]; - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+0, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); - - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+1, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); - - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+2, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - }else - { - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "a"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "a"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "a"); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 0, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); + + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 1, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); + + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 2, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "a"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "a"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "a"); } - } - else - { //Turn myself on now - if (mLightSwitchStyle) //i have a light style i'd like to use when on + } else { // Turn myself on now + if (mLightSwitchStyle) // i have a light style i'd like to use when on { char lightstyle[32]; - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+0, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); - - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+1, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); - - gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+2, lightstyle, 32); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - } - else - { - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "z"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "z"); - gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "z"); + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 0, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); + + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 1, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); + + gi.GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 2, lightstyle, 32); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "z"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "z"); + gi.SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "z"); } } } -void SP_light( gentity_t *self ) { - if (!self->targetname ) - {//if i don't have a light style switch, the i go away - G_FreeEntity( self ); +void SP_light(gentity_t *self) { + if (!self->targetname) { // if i don't have a light style switch, the i go away + G_FreeEntity(self); return; } - G_SpawnInt( "style", "0", &self->count ); - G_SpawnInt( "switch_style", "0", &self->bounceCount ); - G_SpawnInt( "style_off", "0", &self->fly_sound_debounce_time ); - G_SetOrigin( self, self->s.origin ); - gi.linkentity( self ); + G_SpawnInt("style", "0", &self->count); + G_SpawnInt("switch_style", "0", &self->bounceCount); + G_SpawnInt("style_off", "0", &self->fly_sound_debounce_time); + G_SetOrigin(self, self->s.origin); + gi.linkentity(self); self->e_UseFunc = useF_misc_dlight_use; self->e_clThinkFunc = clThinkF_NULL; @@ -164,22 +150,19 @@ void SP_light( gentity_t *self ) { self->misc_dlight_active = qfalse; self->svFlags |= SVF_NOCLIENT; - if ( !(self->spawnflags & 4) ) - { //turn myself on now + if (!(self->spawnflags & 4)) { // turn myself on now self->misc_dlight_active = qtrue; } - misc_lightstyle_set (self); + misc_lightstyle_set(self); } -void misc_dlight_use ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void misc_dlight_use(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - ent->misc_dlight_active = (qboolean)!ent->misc_dlight_active; //toggle - misc_lightstyle_set (ent); + ent->misc_dlight_active = (qboolean)!ent->misc_dlight_active; // toggle + misc_lightstyle_set(ent); } - /* ================================================================================= @@ -188,279 +171,241 @@ TELEPORTERS ================================================================================= */ -void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ) -{ - if ( player->NPC && ( player->NPC->aiFlags&NPCAI_FORM_TELE_NAV ) ) - { - //My leader teleported, I was trying to catch up, take this off +void TeleportPlayer(gentity_t *player, vec3_t origin, vec3_t angles) { + if (player->NPC && (player->NPC->aiFlags & NPCAI_FORM_TELE_NAV)) { + // My leader teleported, I was trying to catch up, take this off player->NPC->aiFlags &= ~NPCAI_FORM_TELE_NAV; - } // unlink to make sure it can't possibly interfere with G_KillBox - gi.unlinkentity (player); + gi.unlinkentity(player); - VectorCopy ( origin, player->client->ps.origin ); + VectorCopy(origin, player->client->ps.origin); player->client->ps.origin[2] += 1; - VectorCopy ( player->client->ps.origin, player->currentOrigin ); + VectorCopy(player->client->ps.origin, player->currentOrigin); // spit the player out - AngleVectors( angles, player->client->ps.velocity, NULL, NULL ); - VectorScale( player->client->ps.velocity, 0, player->client->ps.velocity ); - //player->client->ps.pm_time = 160; // hold time - //player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; + AngleVectors(angles, player->client->ps.velocity, NULL, NULL); + VectorScale(player->client->ps.velocity, 0, player->client->ps.velocity); + // player->client->ps.pm_time = 160; // hold time + // player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; // toggle the teleport bit so the client knows to not lerp player->client->ps.eFlags ^= EF_TELEPORT_BIT; // set angles - SetClientViewAngle( player, angles ); + SetClientViewAngle(player, angles); // kill anything at the destination - G_KillBox (player); + G_KillBox(player); // save results of pmove - PlayerStateToEntityState( &player->client->ps, &player->s ); + PlayerStateToEntityState(&player->client->ps, &player->s); - gi.linkentity (player); + gi.linkentity(player); } -void TeleportMover( gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle ) -{//FIXME: need an effect - vec3_t oldAngle, newAngle; - float speed; +void TeleportMover(gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle) { // FIXME: need an effect + vec3_t oldAngle, newAngle; + float speed; // unlink to make sure it can't possibly interfere with G_KillBox - gi.unlinkentity (mover); - - //reposition it - VectorCopy( origin, mover->s.pos.trBase ); - VectorCopy( origin, mover->currentOrigin ); - - //Maintain their previous speed, but adjusted for new direction - if ( snapAngle ) - {//not a diffAngle, actually an absolute angle - vec3_t dir; - - VectorCopy( diffAngles, newAngle ); - AngleVectors( newAngle, dir, NULL, NULL ); - VectorNormalize( dir );//necessary? - speed = VectorLength( mover->s.pos.trDelta ); - VectorScale( dir, speed, mover->s.pos.trDelta ); + gi.unlinkentity(mover); + + // reposition it + VectorCopy(origin, mover->s.pos.trBase); + VectorCopy(origin, mover->currentOrigin); + + // Maintain their previous speed, but adjusted for new direction + if (snapAngle) { // not a diffAngle, actually an absolute angle + vec3_t dir; + + VectorCopy(diffAngles, newAngle); + AngleVectors(newAngle, dir, NULL, NULL); + VectorNormalize(dir); // necessary? + speed = VectorLength(mover->s.pos.trDelta); + VectorScale(dir, speed, mover->s.pos.trDelta); mover->s.pos.trTime = level.time; - VectorSubtract( newAngle, mover->s.apos.trBase, diffAngles ); - VectorCopy( newAngle, mover->s.apos.trBase ); - } - else - { - speed = VectorNormalize( mover->s.pos.trDelta ); + VectorSubtract(newAngle, mover->s.apos.trBase, diffAngles); + VectorCopy(newAngle, mover->s.apos.trBase); + } else { + speed = VectorNormalize(mover->s.pos.trDelta); - vectoangles( mover->s.pos.trDelta, oldAngle ); - VectorAdd( oldAngle, diffAngles, newAngle ); + vectoangles(mover->s.pos.trDelta, oldAngle); + VectorAdd(oldAngle, diffAngles, newAngle); - AngleVectors( newAngle, mover->s.pos.trDelta, NULL, NULL ); - VectorNormalize( mover->s.pos.trDelta ); + AngleVectors(newAngle, mover->s.pos.trDelta, NULL, NULL); + VectorNormalize(mover->s.pos.trDelta); - VectorScale( mover->s.pos.trDelta, speed, mover->s.pos.trDelta ); + VectorScale(mover->s.pos.trDelta, speed, mover->s.pos.trDelta); mover->s.pos.trTime = level.time; - //Maintain their previous angles, but adjusted to new orientation - VectorAdd( mover->s.apos.trBase, diffAngles, mover->s.apos.trBase ); + // Maintain their previous angles, but adjusted to new orientation + VectorAdd(mover->s.apos.trBase, diffAngles, mover->s.apos.trBase); } - //Maintain their previous anglespeed, but adjusted to new orientation - speed = VectorNormalize( mover->s.apos.trDelta ); - VectorAdd( mover->s.apos.trDelta, diffAngles, mover->s.apos.trDelta ); - VectorNormalize( mover->s.apos.trDelta ); - VectorScale( mover->s.apos.trDelta, speed, mover->s.apos.trDelta ); + // Maintain their previous anglespeed, but adjusted to new orientation + speed = VectorNormalize(mover->s.apos.trDelta); + VectorAdd(mover->s.apos.trDelta, diffAngles, mover->s.apos.trDelta); + VectorNormalize(mover->s.apos.trDelta); + VectorScale(mover->s.apos.trDelta, speed, mover->s.apos.trDelta); mover->s.apos.trTime = level.time; - //Tell them it was teleported this move + // Tell them it was teleported this move mover->s.eFlags |= EF_TELEPORT_BIT; // kill anything at the destination - //G_KillBox (mover); - //FIXME: call touch func instead of killbox? + // G_KillBox (mover); + // FIXME: call touch func instead of killbox? - gi.linkentity (mover); + gi.linkentity(mover); } -void teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace) -{ - gentity_t *dest; +void teleporter_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *dest; if (!other->client) return; - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - gi.Printf ("Couldn't find teleporter destination\n"); + gi.Printf("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( other, dest->s.origin, dest->s.angles ); + TeleportPlayer(other, dest->s.origin, dest->s.angles); } /*QUAK-D misc_teleporter (1 0 0) (-32 -32 -24) (32 32 -16) Stepping onto this disc will teleport players to the targeted misc_teleporter_dest object. */ -void SP_misc_teleporter (gentity_t *ent) -{ - gentity_t *trig; +void SP_misc_teleporter(gentity_t *ent) { + gentity_t *trig; - if (!ent->target) - { - gi.Printf ("teleporter without a target.\n"); - G_FreeEntity( ent ); + if (!ent->target) { + gi.Printf("teleporter without a target.\n"); + G_FreeEntity(ent); return; } - ent->s.modelindex = G_ModelIndex( "models/objects/dmspot.md3" ); + ent->s.modelindex = G_ModelIndex("models/objects/dmspot.md3"); ent->s.clientNum = 1; -// ent->s.loopSound = G_SoundIndex("sound/world/amb10.wav"); + // ent->s.loopSound = G_SoundIndex("sound/world/amb10.wav"); ent->contents = CONTENTS_SOLID; - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet (ent->mins, -32, -32, -24); - VectorSet (ent->maxs, 32, 32, -16); - gi.linkentity (ent); + VectorSet(ent->mins, -32, -32, -24); + VectorSet(ent->maxs, 32, 32, -16); + gi.linkentity(ent); - trig = G_Spawn (); + trig = G_Spawn(); trig->e_TouchFunc = touchF_teleporter_touch; trig->contents = CONTENTS_TRIGGER; trig->target = ent->target; trig->owner = ent; - G_SetOrigin( trig, ent->s.origin ); - VectorSet (trig->mins, -8, -8, 8); - VectorSet (trig->maxs, 8, 8, 24); - gi.linkentity (trig); - + G_SetOrigin(trig, ent->s.origin); + VectorSet(trig->mins, -8, -8, 8); + VectorSet(trig->maxs, 8, 8, 24); + gi.linkentity(trig); } /*QUAK-D misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16) - - NODRAW Point teleporters at these. */ -void SP_misc_teleporter_dest( gentity_t *ent ) { - if ( ent->spawnflags & 4 ){ +void SP_misc_teleporter_dest(gentity_t *ent) { + if (ent->spawnflags & 4) { return; } - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - gi.linkentity (ent); + gi.linkentity(ent); } - //=========================================================== /*QUAKED misc_model (1 0 0) (-16 -16 -16) (16 16 16) "model" arbitrary .md3 or .ase file to display turns into map triangles - not solid */ -void SP_misc_model( gentity_t *ent ) { - G_FreeEntity( ent ); -} +void SP_misc_model(gentity_t *ent) { G_FreeEntity(ent); } //=========================================================== -void setCamera ( gentity_t *ent ) -{ - vec3_t dir; - gentity_t *target = 0; +void setCamera(gentity_t *ent) { + vec3_t dir; + gentity_t *target = 0; // frame holds the rotate speed - if ( ent->owner->spawnflags & 1 ) - { + if (ent->owner->spawnflags & 1) { ent->s.frame = 25; - } - else if ( ent->owner->spawnflags & 2 ) - { + } else if (ent->owner->spawnflags & 2) { ent->s.frame = 75; } // clientNum holds the rotate offset ent->s.clientNum = ent->owner->s.clientNum; - VectorCopy( ent->owner->s.origin, ent->s.origin2 ); + VectorCopy(ent->owner->s.origin, ent->s.origin2); // see if the portal_camera has a target if (ent->owner->target) { - target = G_PickTarget( ent->owner->target ); + target = G_PickTarget(ent->owner->target); } - if ( target ) - { - VectorSubtract( target->s.origin, ent->owner->s.origin, dir ); - VectorNormalize( dir ); - } - else - { - G_SetMovedir( ent->owner->s.angles, dir ); + if (target) { + VectorSubtract(target->s.origin, ent->owner->s.origin, dir); + VectorNormalize(dir); + } else { + G_SetMovedir(ent->owner->s.angles, dir); } - ent->s.eventParm = DirToByte( dir ); + ent->s.eventParm = DirToByte(dir); } -void cycleCamera( gentity_t *self ) -{ - self->owner = G_Find( self->owner, FOFS(targetname), self->target ); - if ( self->owner == NULL ) - { - //Uh oh! Not targeted at any ents! Or reached end of list? Which is it? - //for now assume reached end of list and are cycling - self->owner = G_Find( self->owner, FOFS(targetname), self->target ); - if ( self->owner == NULL ) - {//still didn't find one - gi.Printf( "Couldn't find target for misc_portal_surface\n" ); - G_FreeEntity( self ); +void cycleCamera(gentity_t *self) { + self->owner = G_Find(self->owner, FOFS(targetname), self->target); + if (self->owner == NULL) { + // Uh oh! Not targeted at any ents! Or reached end of list? Which is it? + // for now assume reached end of list and are cycling + self->owner = G_Find(self->owner, FOFS(targetname), self->target); + if (self->owner == NULL) { // still didn't find one + gi.Printf("Couldn't find target for misc_portal_surface\n"); + G_FreeEntity(self); return; } } - setCamera( self ); + setCamera(self); - if ( self->e_ThinkFunc == thinkF_cycleCamera ) - { - if ( self->owner->wait > 0 ) - { + if (self->e_ThinkFunc == thinkF_cycleCamera) { + if (self->owner->wait > 0) { self->nextthink = level.time + self->owner->wait; - } - else - { + } else { self->nextthink = level.time + self->wait; } } } -void misc_portal_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - cycleCamera( self ); -} +void misc_portal_use(gentity_t *self, gentity_t *other, gentity_t *activator) { cycleCamera(self); } -void locateCamera( gentity_t *ent ) -{//FIXME: make this fadeout with distance from misc_camera_portal +void locateCamera(gentity_t *ent) { // FIXME: make this fadeout with distance from misc_camera_portal ent->owner = G_Find(NULL, FOFS(targetname), ent->target); - if ( !ent->owner ) - { - gi.Printf( "Couldn't find target for misc_portal_surface\n" ); - G_FreeEntity( ent ); + if (!ent->owner) { + gi.Printf("Couldn't find target for misc_portal_surface\n"); + G_FreeEntity(ent); return; } - setCamera( ent ); + setCamera(ent); - if ( !ent->targetname ) - {//not targetted, so auto-cycle - if ( G_Find(ent->owner, FOFS(targetname), ent->target) != NULL ) - {//targeted at more than one thing + if (!ent->targetname) { // not targetted, so auto-cycle + if (G_Find(ent->owner, FOFS(targetname), ent->target) != NULL) { // targeted at more than one thing ent->e_ThinkFunc = thinkF_cycleCamera; - if ( ent->owner->wait > 0 ) - { + if (ent->owner->wait > 0) { ent->nextthink = level.time + ent->owner->wait; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } } @@ -476,27 +421,22 @@ wait - makes it auto-cycle between all cameras it's pointed at at intevervals of cameras will be cycled through in the order they were created on the map. */ -void SP_misc_portal_surface(gentity_t *ent) -{ - VectorClear( ent->mins ); - VectorClear( ent->maxs ); - gi.linkentity (ent); +void SP_misc_portal_surface(gentity_t *ent) { + VectorClear(ent->mins); + VectorClear(ent->maxs); + gi.linkentity(ent); ent->svFlags = SVF_PORTAL; ent->s.eType = ET_PORTAL; ent->wait *= 1000; - if ( !ent->target ) - {//mirror? - VectorCopy( ent->s.origin, ent->s.origin2 ); - } - else - { + if (!ent->target) { // mirror? + VectorCopy(ent->s.origin, ent->s.origin2); + } else { ent->e_ThinkFunc = thinkF_locateCamera; ent->nextthink = level.time + 100; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_portal_use; } } @@ -507,158 +447,132 @@ The target for a misc_portal_surface. You can set either angles or target anoth "roll" an angle modifier to orient the camera around the target vector; */ void SP_misc_portal_camera(gentity_t *ent) { - float roll; + float roll; - VectorClear( ent->mins ); - VectorClear( ent->maxs ); - gi.linkentity (ent); + VectorClear(ent->mins); + VectorClear(ent->maxs); + gi.linkentity(ent); - G_SpawnFloat( "roll", "0", &roll ); + G_SpawnFloat("roll", "0", &roll); - ent->s.clientNum = roll/360.0 * 256; + ent->s.clientNum = roll / 360.0 * 256; ent->wait *= 1000; } -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern void SP_fx_runner( gentity_t *ent ); -void camera_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - { - G_UseTargets2( self, player, self->target4 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern void SP_fx_runner(gentity_t *ent); +void camera_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (player && player->client && player->client->ps.viewEntity == self->s.number) { + G_UseTargets2(self, player, self->target4); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); } - G_UseTargets2( self, player, self->closetarget ); - //FIXME: explosion fx/sound - //leave sparks at origin- where base's pole is still at? + G_UseTargets2(self, player, self->closetarget); + // FIXME: explosion fx/sound + // leave sparks at origin- where base's pole is still at? gentity_t *sparks = G_Spawn(); - if ( sparks ) - { + if (sparks) { sparks->fxFile = "spark"; sparks->delay = 100; sparks->random = 500; - sparks->s.angles[0] = 180;//point down - VectorCopy( self->s.origin, sparks->s.origin ); - SP_fx_runner( sparks ); + sparks->s.angles[0] = 180; // point down + VectorCopy(self->s.origin, sparks->s.origin); + SP_fx_runner(sparks); } - //bye! + // bye! self->takedamage = qfalse; self->contents = 0; self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; } -void camera_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator || !activator->client || activator->s.number ) - {//really only usable by the player +void camera_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || !activator->client || activator->s.number) { // really only usable by the player return; } - self->painDebounceTime = level.time + (self->wait*1000);//FRAMETIME*5;//don't check for player buttons for 500 ms + self->painDebounceTime = level.time + (self->wait * 1000); // FRAMETIME*5;//don't check for player buttons for 500 ms // FIXME: I guess we are allowing them to switch to a dead camera. Maybe we should conditionally do this though? - if ( /*self->health <= 0 ||*/ (player && player->client && player->client->ps.viewEntity == self->s.number) ) - {//I'm already viewEntity, or I'm destroyed, find next + if (/*self->health <= 0 ||*/ (player && player->client && + player->client->ps.viewEntity == self->s.number)) { // I'm already viewEntity, or I'm destroyed, find next gentity_t *next = NULL; - if ( self->target2 != NULL ) - { - next = G_Find( NULL, FOFS(targetname), self->target2 ); + if (self->target2 != NULL) { + next = G_Find(NULL, FOFS(targetname), self->target2); } - if ( next ) - {//found another one - if ( !Q_stricmp( "misc_camera", next->classname ) ) - {//make sure it's another camera - camera_use( next, other, activator ); + if (next) { // found another one + if (!Q_stricmp("misc_camera", next->classname)) { // make sure it's another camera + camera_use(next, other, activator); } + } else // if ( self->health > 0 ) + { // I was the last (only?) one, clear out the viewentity + G_UseTargets2(self, activator, self->target4); + G_ClearViewEntity(activator); + G_Sound(activator, self->soundPos2); } - else //if ( self->health > 0 ) - {//I was the last (only?) one, clear out the viewentity - G_UseTargets2( self, activator, self->target4 ); - G_ClearViewEntity( activator ); - G_Sound( activator, self->soundPos2 ); - } - } - else - {//set me as view entity - G_UseTargets2( self, activator, self->target3 ); + } else { // set me as view entity + G_UseTargets2(self, activator, self->target3); self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; - G_SetViewEntity( activator, self ); - G_Sound( activator, self->soundPos1 ); + G_SetViewEntity(activator, self); + G_Sound(activator, self->soundPos1); } } -void camera_aim( gentity_t *self ) -{ +void camera_aim(gentity_t *self) { self->nextthink = level.time + FRAMETIME; - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - {//I am the viewEntity - if ( (player->client->usercmd.buttons&BUTTON_BLOCKING) || player->client->usercmd.forwardmove || player->client->usercmd.rightmove || player->client->usercmd.upmove ) - {//player wants to back out of camera - G_UseTargets2( self, player, self->target4 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); - self->painDebounceTime = level.time + (self->wait*1000);//FRAMETIME*5;//don't check for player buttons for 500 ms - if ( player->client->usercmd.upmove > 0 ) - {//stop player from doing anything for a half second after + if (player && player->client && player->client->ps.viewEntity == self->s.number) { // I am the viewEntity + if ((player->client->usercmd.buttons & BUTTON_BLOCKING) || player->client->usercmd.forwardmove || player->client->usercmd.rightmove || + player->client->usercmd.upmove) { // player wants to back out of camera + G_UseTargets2(self, player, self->target4); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); + self->painDebounceTime = level.time + (self->wait * 1000); // FRAMETIME*5;//don't check for player buttons for 500 ms + if (player->client->usercmd.upmove > 0) { // stop player from doing anything for a half second after player->aimDebounceTime = level.time + 500; } - } - else if ( self->painDebounceTime < level.time ) - {//check for use button - if ( (player->client->usercmd.buttons&BUTTON_USE) ) - {//player pressed use button, wants to cycle to next - camera_use( self, player, player ); + } else if (self->painDebounceTime < level.time) { // check for use button + if ((player->client->usercmd.buttons & BUTTON_USE)) { // player pressed use button, wants to cycle to next + camera_use(self, player, player); } - } - else - {//don't draw me when being looked through + } else { // don't draw me when being looked through self->s.eFlags |= EF_NODRAW; self->s.modelindex = 0; } - } - else if ( self->health > 0 ) - {//still alive, can draw me again + } else if (self->health > 0) { // still alive, can draw me again self->s.eFlags &= ~EF_NODRAW; self->s.modelindex = self->s.modelindex3; } - //update my aim - if ( self->target ) - { - gentity_t *targ = G_Find( NULL, FOFS(targetname), self->target ); - if ( targ ) - { + // update my aim + if (self->target) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), self->target); + if (targ) { vec3_t angles, dir; - VectorSubtract( targ->currentOrigin, self->currentOrigin, dir ); - vectoangles( dir, angles ); - //FIXME: if a G2 model, do a bone override..??? - VectorCopy( self->currentAngles, self->s.apos.trBase ); - - for( int i = 0; i < 3; i++ ) - { - angles[i] = AngleNormalize180( angles[i] ); - self->s.apos.trDelta[i] = AngleNormalize180( (angles[i]-self->currentAngles[i])*10 ); + VectorSubtract(targ->currentOrigin, self->currentOrigin, dir); + vectoangles(dir, angles); + // FIXME: if a G2 model, do a bone override..??? + VectorCopy(self->currentAngles, self->s.apos.trBase); + + for (int i = 0; i < 3; i++) { + angles[i] = AngleNormalize180(angles[i]); + self->s.apos.trDelta[i] = AngleNormalize180((angles[i] - self->currentAngles[i]) * 10); } - //VectorSubtract( angles, self->currentAngles, self->s.apos.trDelta ); - //VectorScale( self->s.apos.trDelta, 10, self->s.apos.trDelta ); + // VectorSubtract( angles, self->currentAngles, self->s.apos.trDelta ); + // VectorScale( self->s.apos.trDelta, 10, self->s.apos.trDelta ); self->s.apos.trTime = level.time; self->s.apos.trDuration = FRAMETIME; - VectorCopy( angles, self->currentAngles ); + VectorCopy(angles, self->currentAngles); - if ( DistanceSquared( self->currentAngles, self->lastAngles ) > 0.01f ) // if it moved at all, start a loop sound? not exactly the "bestest" solution - { - self->s.loopSound = G_SoundIndex( "sound/movers/objects/cameramove_lp2" ); - } - else + if (DistanceSquared(self->currentAngles, self->lastAngles) > 0.01f) // if it moved at all, start a loop sound? not exactly the "bestest" solution { + self->s.loopSound = G_SoundIndex("sound/movers/objects/cameramove_lp2"); + } else { self->s.loopSound = 0; // not moving so don't bother } - VectorCopy( self->currentAngles, self->lastAngles ); - //G_SetAngles( self, angles ); + VectorCopy(self->currentAngles, self->lastAngles); + // G_SetAngles( self, angles ); } } } @@ -676,38 +590,36 @@ VULNERABLE - allow camera to be destroyed "closetarget" - (sigh...) yet another target, fired this when it's destroyed "wait" - how long to wait between being used (default 0.5) */ -void SP_misc_camera( gentity_t *self ) -{ - G_SpawnFloat( "wait", "0.5", &self->wait ); +void SP_misc_camera(gentity_t *self) { + G_SpawnFloat("wait", "0.5", &self->wait); - //FIXME: spawn base, too + // FIXME: spawn base, too gentity_t *base = G_Spawn(); - if ( base ) - { - base->s.modelindex = G_ModelIndex( "models/map_objects/kejim/impcam_base.md3" ); - VectorCopy( self->s.origin, base->s.origin ); + if (base) { + base->s.modelindex = G_ModelIndex("models/map_objects/kejim/impcam_base.md3"); + VectorCopy(self->s.origin, base->s.origin); base->s.origin[2] += 16; - G_SetOrigin( base, base->s.origin ); - G_SetAngles( base, self->s.angles ); - gi.linkentity( base ); - } - self->s.modelindex3 = self->s.modelindex = G_ModelIndex( "models/map_objects/kejim/impcam.md3" ); - self->soundPos1 = G_SoundIndex( "sound/movers/camera_on.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/camera_off.mp3" ); - G_SoundIndex( "sound/movers/objects/cameramove_lp2" ); - - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); - self->s.apos.trType = TR_LINEAR_STOP;//TR_INTERPOLATE;// + G_SetOrigin(base, base->s.origin); + G_SetAngles(base, self->s.angles); + gi.linkentity(base); + } + self->s.modelindex3 = self->s.modelindex = G_ModelIndex("models/map_objects/kejim/impcam.md3"); + self->soundPos1 = G_SoundIndex("sound/movers/camera_on.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/camera_off.mp3"); + G_SoundIndex("sound/movers/objects/cameramove_lp2"); + + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); + self->s.apos.trType = TR_LINEAR_STOP; // TR_INTERPOLATE;// self->alt_fire = qtrue; - VectorSet( self->mins, -8, -8, -12 ); - VectorSet( self->maxs, 8, 8, 0 ); + VectorSet(self->mins, -8, -8, -12); + VectorSet(self->maxs, 8, 8, 0); self->contents = CONTENTS_SOLID; - gi.linkentity( self ); + gi.linkentity(self); - self->fxID = G_EffectIndex( "spark" ); + self->fxID = G_EffectIndex("spark"); - if ( self->spawnflags & 1 ) // VULNERABLE + if (self->spawnflags & 1) // VULNERABLE { self->takedamage = qtrue; } @@ -728,98 +640,91 @@ void SP_misc_camera( gentity_t *self ) ====================================================================== */ -void Use_Shooter( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ -/* vec3_t dir; - float deg; - vec3_t up, right; -*/ - G_ActivateBehavior(ent,BSET_USE); -/* - // see if we have a target - if ( ent->enemy ) { - VectorSubtract( ent->enemy->currentOrigin, ent->s.origin, dir ); - VectorNormalize( dir ); - } else { - VectorCopy( ent->movedir, dir ); - } +void Use_Shooter(gentity_t *ent, gentity_t *other, gentity_t *activator) { + /* vec3_t dir; + float deg; + vec3_t up, right; + */ + G_ActivateBehavior(ent, BSET_USE); + /* + // see if we have a target + if ( ent->enemy ) { + VectorSubtract( ent->enemy->currentOrigin, ent->s.origin, dir ); + VectorNormalize( dir ); + } else { + VectorCopy( ent->movedir, dir ); + } - // randomize a bit - PerpendicularVector( up, dir ); - CrossProduct( up, dir, right ); + // randomize a bit + PerpendicularVector( up, dir ); + CrossProduct( up, dir, right ); - deg = Q_flrand(-1.0f, 1.0f) * ent->random; - VectorMA( dir, deg, up, dir ); + deg = Q_flrand(-1.0f, 1.0f) * ent->random; + VectorMA( dir, deg, up, dir ); - deg = Q_flrand(-1.0f, 1.0f) * ent->random; - VectorMA( dir, deg, right, dir ); + deg = Q_flrand(-1.0f, 1.0f) * ent->random; + VectorMA( dir, deg, right, dir ); - VectorNormalize( dir ); + VectorNormalize( dir ); - switch ( ent->s.weapon ) - { - case WP_GRENADE_LAUNCHER: - fire_grenade( ent, ent->s.origin, dir ); - break; - case WP_ROCKET_LAUNCHER: - fire_rocket( ent, ent->s.origin, dir ); - break; - case WP_PLASMAGUN: - fire_plasma( ent, ent->s.origin, dir ); - break; - } + switch ( ent->s.weapon ) + { + case WP_GRENADE_LAUNCHER: + fire_grenade( ent, ent->s.origin, dir ); + break; + case WP_ROCKET_LAUNCHER: + fire_rocket( ent, ent->s.origin, dir ); + break; + case WP_PLASMAGUN: + fire_plasma( ent, ent->s.origin, dir ); + break; + } - G_AddEvent( ent, EV_FIRE_WEAPON, 0 ); -*/ + G_AddEvent( ent, EV_FIRE_WEAPON, 0 ); + */ } -void InitShooter( gentity_t *ent, int weapon ) { +void InitShooter(gentity_t *ent, int weapon) { ent->e_UseFunc = useF_Use_Shooter; ent->s.weapon = weapon; - RegisterItem( FindItemForWeapon( (weapon_t) weapon ) ); + RegisterItem(FindItemForWeapon((weapon_t)weapon)); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); - if ( !ent->random ) { + if (!ent->random) { ent->random = 1.0; } - ent->random = sin( M_PI * ent->random / 180 ); + ent->random = sin(M_PI * ent->random / 180); // target might be a moving object, so we can't set movedir for it - if ( ent->target ) { - G_SetEnemy(ent, G_PickTarget( ent->target )); + if (ent->target) { + G_SetEnemy(ent, G_PickTarget(ent->target)); } - gi.linkentity( ent ); + gi.linkentity(ent); } /*QUAK-ED shooter_rocket (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_rocket( gentity_t *ent ) -{ -// InitShooter( ent, WP_TETRION_DISRUPTOR ); +void SP_shooter_rocket(gentity_t *ent) { + // InitShooter( ent, WP_TETRION_DISRUPTOR ); } /*QUAK-ED shooter_plasma (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" is the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_plasma( gentity_t *ent ) -{ - InitShooter( ent, WP_BRYAR_PISTOL); -} +void SP_shooter_plasma(gentity_t *ent) { InitShooter(ent, WP_BRYAR_PISTOL); } /*QUAK-ED shooter_grenade (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" is the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_grenade( gentity_t *ent ) -{ -// InitShooter( ent, WP_GRENADE_LAUNCHER); +void SP_shooter_grenade(gentity_t *ent) { + // InitShooter( ent, WP_GRENADE_LAUNCHER); } - /*QUAKED object_cargo_barrel1 (1 0 0) (-16 -16 -16) (16 16 29) SMALLER KLINGON NO_SMOKE POWDERKEG Cargo Barrel if given a targetname, using it makes it explode @@ -833,66 +738,56 @@ health default = 20 splashDamage default = 100 splashRadius default = 200 */ -void SP_object_cargo_barrel1(gentity_t *ent) -{ - if(ent->spawnflags & 8) - { - //FIXME: make an index into an external string table for localization +void SP_object_cargo_barrel1(gentity_t *ent) { + if (ent->spawnflags & 8) { + // FIXME: make an index into an external string table for localization ent->fullName = "Powderkeg Barrel"; - ent->s.modelindex = G_ModelIndex( "/models/mapobjects/cargo/barrel_wood2.md3" ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode3.wav"); - } - else if(ent->spawnflags & 2) - { - //FIXME: make an index into an external string table for localization + ent->s.modelindex = G_ModelIndex("/models/mapobjects/cargo/barrel_wood2.md3"); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode3.wav"); + } else if (ent->spawnflags & 2) { + // FIXME: make an index into an external string table for localization ent->fullName = "Klingon Cargo Barrel"; - ent->s.modelindex = G_ModelIndex( "/models/mapobjects/scavenger/k_barrel.md3" ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode4.wav"); - } - else - { - //FIXME: make an index into an external string table for localization + ent->s.modelindex = G_ModelIndex("/models/mapobjects/scavenger/k_barrel.md3"); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode4.wav"); + } else { + // FIXME: make an index into an external string table for localization ent->fullName = "Federation Cargo Barrel"; - ent->s.modelindex = G_ModelIndex( va("/models/mapobjects/cargo/barrel%i.md3", Q_irand( 0, 2 )) ); -// ent->sounds = G_SoundIndex("sound/weapons/explosions/explode1.wav"); + ent->s.modelindex = G_ModelIndex(va("/models/mapobjects/cargo/barrel%i.md3", Q_irand(0, 2))); + // ent->sounds = G_SoundIndex("sound/weapons/explosions/explode1.wav"); } - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE; + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE; - if ( ent->spawnflags & 1 ) - { - VectorSet (ent->mins, -8, -8, -16); - VectorSet (ent->maxs, 8, 8, 8); - } - else - { - VectorSet (ent->mins, -16, -16, -16); - VectorSet (ent->maxs, 16, 16, 29); + if (ent->spawnflags & 1) { + VectorSet(ent->mins, -8, -8, -16); + VectorSet(ent->maxs, 8, 8, 8); + } else { + VectorSet(ent->mins, -16, -16, -16); + VectorSet(ent->maxs, 16, 16, 29); } - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); - if(!ent->health) + if (!ent->health) ent->health = 20; - if(!ent->splashDamage) + if (!ent->splashDamage) ent->splashDamage = 100; - if(!ent->splashRadius) + if (!ent->splashRadius) ent->splashRadius = 200; ent->takedamage = qtrue; ent->e_DieFunc = dieF_ExplodeDeath_Wait; - if(ent->targetname) + if (ent->targetname) ent->e_UseFunc = useF_GoExplodeDeath; - gi.linkentity (ent); + gi.linkentity(ent); } - /*QUAKED misc_dlight (0.2 0.8 0.2) (-4 -4 -4) (4 4 4) STARTOFF FADEON FADEOFF PULSE Dynamic light, toggles on and off when used @@ -913,63 +808,50 @@ starttime - how long to hold at start (seconds) TODO: Add random to speed/radius? */ -void SP_misc_dlight(gentity_t *ent) -{ - G_SetOrigin( ent, ent->s.origin ); - gi.linkentity( ent ); +void SP_misc_dlight(gentity_t *ent) { + G_SetOrigin(ent, ent->s.origin); + gi.linkentity(ent); ent->speed *= 1000; ent->wait *= 1000; ent->radius *= 1000; - //FIXME: attach self to a train or something? + // FIXME: attach self to a train or something? ent->e_UseFunc = useF_misc_dlight_use; ent->misc_dlight_active = qfalse; ent->e_clThinkFunc = clThinkF_NULL; ent->s.eType = ET_GENERAL; - //Delay first think so we can find owner - if ( ent->ownername ) - { + // Delay first think so we can find owner + if (ent->ownername) { ent->e_ThinkFunc = thinkF_misc_dlight_think; ent->nextthink = level.time + START_TIME_LINK_ENTS; } - if ( !(ent->spawnflags & 1) ) - {//Turn myself on now - GEntity_UseFunc( ent, ent, ent ); + if (!(ent->spawnflags & 1)) { // Turn myself on now + GEntity_UseFunc(ent, ent, ent); } } -void misc_dlight_use_old ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void misc_dlight_use_old(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - if ( ent->misc_dlight_active ) - {//We're on, turn off - if ( ent->spawnflags & 4 ) - {//fade off + if (ent->misc_dlight_active) { // We're on, turn off + if (ent->spawnflags & 4) { // fade off ent->pushDebounceTime = 3; - } - else - { + } else { ent->misc_dlight_active = qfalse; ent->e_clThinkFunc = clThinkF_NULL; ent->s.eType = ET_GENERAL; ent->svFlags &= ~SVF_BROADCAST; } - } - else - { - //Start at start regardless of when we were turned off - if ( ent->spawnflags & 4 ) - {//fade on + } else { + // Start at start regardless of when we were turned off + if (ent->spawnflags & 4) { // fade on ent->pushDebounceTime = 2; - } - else - {//Just start on + } else { // Just start on ent->pushDebounceTime = 0; } ent->painDebounceTime = level.time; @@ -982,35 +864,29 @@ void misc_dlight_use_old ( gentity_t *ent, gentity_t *other, gentity_t *activato ent->e_clThinkFunc = clThinkF_CG_DLightThink; ent->s.eType = ET_THINKER; - ent->svFlags |= SVF_BROADCAST;// Broadcast to all clients + ent->svFlags |= SVF_BROADCAST; // Broadcast to all clients } } -void misc_dlight_think ( gentity_t *ent ) -{ - //Stay Attached to owner - if ( ent->owner ) - { - G_SetOrigin( ent, ent->owner->currentOrigin ); - gi.linkentity( ent ); - } - else if ( ent->ownername ) - { - ent->owner = G_Find( NULL, FOFS(targetname), ent->ownername ); +void misc_dlight_think(gentity_t *ent) { + // Stay Attached to owner + if (ent->owner) { + G_SetOrigin(ent, ent->owner->currentOrigin); + gi.linkentity(ent); + } else if (ent->ownername) { + ent->owner = G_Find(NULL, FOFS(targetname), ent->ownername); ent->ownername = NULL; } ent->nextthink = level.time + FRAMETIME; } - -void station_pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) -{ -// self->s.modelindex = G_ModelIndex("/models/mapobjects/stasis/plugin2_in.md3"); -// self->s.eFlags &= ~ EF_ANIM_ALLFAST; -// self->s.eFlags |= EF_ANIM_ONCE; -// gi.linkentity (self); +void station_pain(gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc) { + // self->s.modelindex = G_ModelIndex("/models/mapobjects/stasis/plugin2_in.md3"); + // self->s.eFlags &= ~ EF_ANIM_ALLFAST; + // self->s.eFlags |= EF_ANIM_ONCE; + // gi.linkentity (self); self->s.modelindex = self->s.modelindex2; - gi.linkentity (self); + gi.linkentity(self); } // -------------------------------------------------------------------- @@ -1019,134 +895,107 @@ void station_pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3 // // -------------------------------------------------------------------- -void health_use( gentity_t *self, gentity_t *other, gentity_t *activator); -int ITM_AddArmor (gentity_t *ent, int count); -int ITM_AddHealth (gentity_t *ent, int count); +void health_use(gentity_t *self, gentity_t *other, gentity_t *activator); +int ITM_AddArmor(gentity_t *ent, int count); +int ITM_AddHealth(gentity_t *ent, int count); -void health_shutdown( gentity_t *self ) -{ - if (!(self->s.eFlags & EF_ANIM_ONCE)) - { - self->s.eFlags &= ~ EF_ANIM_ALLFAST; +void health_shutdown(gentity_t *self) { + if (!(self->s.eFlags & EF_ANIM_ONCE)) { + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; // Switch to and animate its used up model. - if (!Q_stricmp(self->model,"models/mapobjects/stasis/plugin2.md3")) - { + if (!Q_stricmp(self->model, "models/mapobjects/stasis/plugin2.md3")) { self->s.modelindex = self->s.modelindex2; - } - else if (!Q_stricmp(self->model,"models/mapobjects/borg/plugin2.md3")) - { + } else if (!Q_stricmp(self->model, "models/mapobjects/borg/plugin2.md3")) { self->s.modelindex = self->s.modelindex2; - } - else if (!Q_stricmp(self->model,"models/mapobjects/stasis/plugin2_floor.md3")) - { + } else if (!Q_stricmp(self->model, "models/mapobjects/stasis/plugin2_floor.md3")) { self->s.modelindex = self->s.modelindex2; -// G_Sound(self, G_SoundIndex("sound/ambience/stasis/shrinkage1.wav") ); - } - else if (!Q_stricmp(self->model,"models/mapobjects/forge/panels.md3")) - { + // G_Sound(self, G_SoundIndex("sound/ambience/stasis/shrinkage1.wav") ); + } else if (!Q_stricmp(self->model, "models/mapobjects/forge/panels.md3")) { self->s.modelindex = self->s.modelindex2; } - gi.linkentity (self); + gi.linkentity(self); } } -void health_think( gentity_t *ent ) -{ +void health_think(gentity_t *ent) { int dif; // He's dead, Jim. Don't give him health - if (ent->enemy->health<1) - { + if (ent->enemy->health < 1) { ent->count = 0; ent->e_ThinkFunc = thinkF_NULL; } // Still has power to give - if (ent->count > 0) - { + if (ent->count > 0) { // For every 3 points of health, you get 1 point of armor // BUT!!! after health is filled up, you get the full energy going to armor dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - ent->enemy->health; - if (dif > 3 ) - { - dif= 3; - } - else if (dif < 0) - { - dif= 0; + if (dif > 3) { + dif = 3; + } else if (dif < 0) { + dif = 0; } - if (dif > ent->count) // Can't give more than count + if (dif > ent->count) // Can't give more than count { dif = ent->count; } - if ((ITM_AddHealth (ent->enemy,dif)) && (dif>0)) - { - ITM_AddArmor (ent->enemy,1); // 1 armor for every 3 health + if ((ITM_AddHealth(ent->enemy, dif)) && (dif > 0)) { + ITM_AddArmor(ent->enemy, 1); // 1 armor for every 3 health - ent->count-=dif; + ent->count -= dif; ent->nextthink = level.time + 10; - } - else // User has taken all health he can hold, see about giving it all to armor + } else // User has taken all health he can hold, see about giving it all to armor { - dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - - ent->enemy->client->ps.stats[STAT_ARMOR]; + dif = ent->enemy->client->ps.stats[STAT_MAX_HEALTH] - ent->enemy->client->ps.stats[STAT_ARMOR]; - if (dif > 3) - { + if (dif > 3) { dif = 3; - } - else if (dif < 0) - { - dif= 0; + } else if (dif < 0) { + dif = 0; } - if (ent->count < dif) // Can't give more than count + if (ent->count < dif) // Can't give more than count { dif = ent->count; } - if ((!ITM_AddArmor(ent->enemy,dif)) || (dif<=0)) - { + if ((!ITM_AddArmor(ent->enemy, dif)) || (dif <= 0)) { ent->e_UseFunc = useF_health_use; ent->e_ThinkFunc = thinkF_NULL; - } - else - { - ent->count-=dif; + } else { + ent->count -= dif; ent->nextthink = level.time + 10; } } } - if (ent->count < 1) - { + if (ent->count < 1) { health_shutdown(ent); } } -void misc_model_useup( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void misc_model_useup(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - self->s.eFlags &= ~ EF_ANIM_ALLFAST; + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; // Switch to and animate its used up model. self->s.modelindex = self->s.modelindex2; - gi.linkentity (self); + gi.linkentity(self); // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; @@ -1154,78 +1003,64 @@ void misc_model_useup( gentity_t *self, gentity_t *other, gentity_t *activator) self->nextthink = -1; } -void health_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{//FIXME: Heal entire team? Or only those that are undying...? +void health_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // FIXME: Heal entire team? Or only those that are undying...? int dif; int dif2; int hold; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if (self->e_ThinkFunc != thinkF_NULL) - { + if (self->e_ThinkFunc != thinkF_NULL) { self->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { - if (other->client) - { + if (other->client) { // He's dead, Jim. Don't give him health - if (other->client->ps.stats[STAT_HEALTH]<1) - { + if (other->client->ps.stats[STAT_HEALTH] < 1) { dif = 1; self->count = 0; - } - else - { // Health + } else { // Health dif = other->client->ps.stats[STAT_MAX_HEALTH] - other->client->ps.stats[STAT_HEALTH]; // Armor dif2 = other->client->ps.stats[STAT_MAX_HEALTH] - other->client->ps.stats[STAT_ARMOR]; hold = (dif2 - dif); // For every 3 points of health, you get 1 point of armor // BUT!!! after health is filled up, you get the full energy going to armor - if (hold>0) // Need more armor than health + if (hold > 0) // Need more armor than health { // Calculate total amount of station energy needed. - hold = dif / 3; // For every 3 points of health, you get 1 point of armor + hold = dif / 3; // For every 3 points of health, you get 1 point of armor dif2 -= hold; dif2 += dif; dif = dif2; } } - } - else - { // Being triggered to be used up + } else { // Being triggered to be used up dif = 1; self->count = 0; } // Does player already have full health and full armor? - if (dif > 0) - { -// G_Sound(self, G_SoundIndex("sound/player/suithealth.wav") ); + if (dif > 0) { + // G_Sound(self, G_SoundIndex("sound/player/suithealth.wav") ); - if ((dif >= self->count) || (self->count<1)) // use it all up? + if ((dif >= self->count) || (self->count < 1)) // use it all up? { health_shutdown(self); } // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; self->enemy = other; self->e_ThinkFunc = thinkF_health_think; self->nextthink = level.time + 50; - } - else - { -// G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); + } else { + // G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); } } } @@ -1235,137 +1070,114 @@ void health_use( gentity_t *self, gentity_t *other, gentity_t *activator) // AMMO plugin functions // // -------------------------------------------------------------------- -void ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator); -int Add_Ammo2 (gentity_t *ent, int ammoType, int count); +void ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator); +int Add_Ammo2(gentity_t *ent, int ammoType, int count); -void ammo_shutdown( gentity_t *self ) -{ - if (!(self->s.eFlags & EF_ANIM_ONCE)) - { - self->s.eFlags &= ~ EF_ANIM_ALLFAST; +void ammo_shutdown(gentity_t *self) { + if (!(self->s.eFlags & EF_ANIM_ONCE)) { + self->s.eFlags &= ~EF_ANIM_ALLFAST; self->s.eFlags |= EF_ANIM_ONCE; - gi.linkentity (self); + gi.linkentity(self); } } -void ammo_think( gentity_t *ent ) -{ +void ammo_think(gentity_t *ent) { int dif; // Still has ammo to give - if (ent->count > 0 && ent->enemy ) - { - dif = ammoData[AMMO_BLASTER].max - ent->enemy->client->ps.ammo[AMMO_BLASTER]; + if (ent->count > 0 && ent->enemy) { + dif = ammoData[AMMO_BLASTER].max - ent->enemy->client->ps.ammo[AMMO_BLASTER]; - if (dif > 2 ) - { - dif= 2; - } - else if (dif < 0) - { - dif= 0; + if (dif > 2) { + dif = 2; + } else if (dif < 0) { + dif = 0; } - if (ent->count < dif) // Can't give more than count + if (ent->count < dif) // Can't give more than count { dif = ent->count; } // Give player ammo - if (Add_Ammo2(ent->enemy,AMMO_BLASTER,dif) && (dif!=0)) - { - ent->count-=dif; + if (Add_Ammo2(ent->enemy, AMMO_BLASTER, dif) && (dif != 0)) { + ent->count -= dif; ent->nextthink = level.time + 10; - } - else // User has taken all ammo he can hold + } else // User has taken all ammo he can hold { ent->e_UseFunc = useF_ammo_use; ent->e_ThinkFunc = thinkF_NULL; } } - if (ent->count < 1) - { + if (ent->count < 1) { ammo_shutdown(ent); } } //------------------------------------------------------------ -void ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ +void ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator) { int dif; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if (self->e_ThinkFunc != thinkF_NULL) - { - if (self->e_UseFunc != useF_NULL) - { + if (self->e_ThinkFunc != thinkF_NULL) { + if (self->e_UseFunc != useF_NULL) { self->e_ThinkFunc = thinkF_NULL; } - } - else - { - if (other->client) - { + } else { + if (other->client) { dif = ammoData[AMMO_BLASTER].max - other->client->ps.ammo[AMMO_BLASTER]; - } - else - { // Being triggered to be used up + } else { // Being triggered to be used up dif = 1; self->count = 0; } // Does player already have full ammo? - if (dif > 0) - { -// G_Sound(self, G_SoundIndex("sound/player/suitenergy.wav") ); + if (dif > 0) { + // G_Sound(self, G_SoundIndex("sound/player/suitenergy.wav") ); - if ((dif >= self->count) || (self->count<1)) // use it all up? + if ((dif >= self->count) || (self->count < 1)) // use it all up? { ammo_shutdown(self); } - } - else - { -// G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); + } else { + // G_Sound(self, G_SoundIndex("sound/weapons/noammo.wav") ); } // Use target when used - if (self->spawnflags & 8) - { - G_UseTargets( self, activator ); + if (self->spawnflags & 8) { + G_UseTargets(self, activator); } self->e_UseFunc = useF_NULL; - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->e_ThinkFunc = thinkF_ammo_think; self->nextthink = level.time + 50; } } //------------------------------------------------------------ -void mega_ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior( self, BSET_USE ); +void mega_ammo_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); // Use target when used - G_UseTargets( self, activator ); + G_UseTargets(self, activator); // first use, adjust the max ammo a person can hold for each type of ammo - ammoData[AMMO_BLASTER].max = 999; - ammoData[AMMO_POWERCELL].max = 999; + ammoData[AMMO_BLASTER].max = 999; + ammoData[AMMO_POWERCELL].max = 999; // Set up our count with whatever the max difference will be - if ( other->client->ps.ammo[AMMO_POWERCELL] > other->client->ps.ammo[AMMO_BLASTER] ) + if (other->client->ps.ammo[AMMO_POWERCELL] > other->client->ps.ammo[AMMO_BLASTER]) self->count = ammoData[AMMO_BLASTER].max - other->client->ps.ammo[AMMO_BLASTER]; else self->count = ammoData[AMMO_POWERCELL].max - other->client->ps.ammo[AMMO_POWERCELL]; -// G_Sound( self, G_SoundIndex("sound/player/superenergy.wav") ); + // G_Sound( self, G_SoundIndex("sound/player/superenergy.wav") ); // Clear our usefunc, then think until our ammo is full self->e_UseFunc = useF_NULL; - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->e_ThinkFunc = thinkF_mega_ammo_think; self->nextthink = level.time + 50; @@ -1374,82 +1186,72 @@ void mega_ammo_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } //------------------------------------------------------------ -void mega_ammo_think( gentity_t *self ) -{ - int ammo_add = 5; +void mega_ammo_think(gentity_t *self) { + int ammo_add = 5; // If the middle model is done animating, and we haven't switched to the last model yet... // chuck up the last model. - if (!Q_stricmp(self->model,"models/mapobjects/forge/power_up_boss.md3")) // Because the normal forge_ammo model can use this too + if (!Q_stricmp(self->model, "models/mapobjects/forge/power_up_boss.md3")) // Because the normal forge_ammo model can use this too { - if ( self->s.frame > 16 && self->s.modelindex != self->s.modelindex2 ) + if (self->s.frame > 16 && self->s.modelindex != self->s.modelindex2) self->s.modelindex = self->s.modelindex2; } - if ( self->enemy && self->count > 0 ) - { + if (self->enemy && self->count > 0) { // Add an equal ammount of ammo to each type - self->enemy->client->ps.ammo[AMMO_BLASTER] += ammo_add; - self->enemy->client->ps.ammo[AMMO_POWERCELL] += ammo_add; + self->enemy->client->ps.ammo[AMMO_BLASTER] += ammo_add; + self->enemy->client->ps.ammo[AMMO_POWERCELL] += ammo_add; // Now cap to prevent overflows - if ( self->enemy->client->ps.ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max ) + if (self->enemy->client->ps.ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max) self->enemy->client->ps.ammo[AMMO_BLASTER] = ammoData[AMMO_BLASTER].max; - if ( self->enemy->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) + if (self->enemy->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) self->enemy->client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; // Decrement the count given counter self->count -= ammo_add; // If we've given all we should, prevent giving any more, even if they player is no longer full - if ( self->count <= 0 ) - { + if (self->count <= 0) { self->count = 0; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - } - else + } else self->nextthink = 20; } } - //------------------------------------------------------------ -void switch_models( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void switch_models(gentity_t *self, gentity_t *other, gentity_t *activator) { // FIXME: need a sound here!! - if ( self->s.modelindex2 ) + if (self->s.modelindex2) self->s.modelindex = self->s.modelindex2; } //------------------------------------------------------------ -void touch_ammo_crystal_tigger( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if ( !other->client ) +void touch_ammo_crystal_tigger(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other->client) return; // dead people can't pick things up - if ( other->health < 1 ) + if (other->health < 1) return; // Only player can pick it up - if ( other->s.number != 0 ) - { + if (other->s.number != 0) { return; } - if ( other->client->ps.ammo[ AMMO_POWERCELL ] >= ammoData[AMMO_POWERCELL].max ) - { - return; // can't hold any more + if (other->client->ps.ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max) { + return; // can't hold any more } // Add the ammo other->client->ps.ammo[AMMO_POWERCELL] += self->owner->count; - if ( other->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) - { + if (other->client->ps.ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) { other->client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; } @@ -1460,71 +1262,64 @@ void touch_ammo_crystal_tigger( gentity_t *self, gentity_t *other, trace_t *trac self->owner->s.modelindex = self->owner->s.modelindex2; // play the normal pickup sound -// G_AddEvent( other, EV_ITEM_PICKUP, ITM_AMMO_CRYSTAL_BORG ); + // G_AddEvent( other, EV_ITEM_PICKUP, ITM_AMMO_CRYSTAL_BORG ); // fire item targets - G_UseTargets( self->owner, other ); + G_UseTargets(self->owner, other); } //------------------------------------------------------------ -void spawn_ammo_crystal_trigger( gentity_t *ent ) -{ - gentity_t *other; - vec3_t mins, maxs; +void spawn_ammo_crystal_trigger(gentity_t *ent) { + gentity_t *other; + vec3_t mins, maxs; // Set the base bounds - VectorCopy( ent->s.origin, mins ); - VectorCopy( ent->s.origin, maxs ); + VectorCopy(ent->s.origin, mins); + VectorCopy(ent->s.origin, maxs); // Now add an area of influence around the thing - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { maxs[i] += 48; mins[i] -= 48; } // create a trigger with this size - other = G_Spawn( ); + other = G_Spawn(); - VectorCopy( mins, other->mins ); - VectorCopy( maxs, other->maxs ); + VectorCopy(mins, other->mins); + VectorCopy(maxs, other->maxs); // set up the other bits that the engine needs to know other->owner = ent; other->contents = CONTENTS_TRIGGER; other->e_TouchFunc = touchF_touch_ammo_crystal_tigger; - gi.linkentity( other ); + gi.linkentity(other); } -void misc_replicator_item_remove ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void misc_replicator_item_remove(gentity_t *self, gentity_t *other, gentity_t *activator) { self->s.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->contents = 0; self->s.modelindex = 0; self->e_UseFunc = useF_misc_replicator_item_spawn; - //FIXME: pickup sound? - if ( activator->client ) - { + // FIXME: pickup sound? + if (activator->client) { activator->health += 5; - if ( activator->health > activator->client->ps.stats[STAT_MAX_HEALTH] ) // Past max health + if (activator->health > activator->client->ps.stats[STAT_MAX_HEALTH]) // Past max health { activator->health = activator->client->ps.stats[STAT_MAX_HEALTH]; } } } -void misc_replicator_item_finish_spawn( gentity_t *self ) -{ - //self->contents = CONTENTS_ITEM; - //FIXME: blinks out for a couple frames when transporter effect is done? +void misc_replicator_item_finish_spawn(gentity_t *self) { + // self->contents = CONTENTS_ITEM; + // FIXME: blinks out for a couple frames when transporter effect is done? self->e_UseFunc = useF_misc_replicator_item_remove; } -void misc_replicator_item_spawn ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - switch ( Q_irand( 1, self->count ) ) - { +void misc_replicator_item_spawn(gentity_t *self, gentity_t *other, gentity_t *activator) { + switch (Q_irand(1, self->count)) { case 1: self->s.modelindex = self->bounceCount; break; @@ -1540,16 +1335,16 @@ void misc_replicator_item_spawn ( gentity_t *self, gentity_t *other, gentity_t * case 5: self->s.modelindex = self->attackDebounceTime; break; - case 6://max + case 6: // max self->s.modelindex = self->pushDebounceTime; break; } self->s.eFlags &= ~EF_NODRAW; self->e_ThinkFunc = thinkF_misc_replicator_item_finish_spawn; - self->nextthink = level.time + 4000;//shorter? + self->nextthink = level.time + 4000; // shorter? self->e_UseFunc = useF_NULL; - gentity_t *tent = G_TempEntity( self->currentOrigin, EV_REPLICATOR ); + gentity_t *tent = G_TempEntity(self->currentOrigin, EV_REPLICATOR); tent->owner = self; } @@ -1565,37 +1360,31 @@ model4 - fourth random model key model5 - fifth random model key model6 - sixth random model key -NOTE: do not skip one of these model names, start with the lowest and fill in each next highest one with a value. A gap will cause the item to not work correctly. +NOTE: do not skip one of these model names, start with the lowest and fill in each next highest one with a value. A gap will cause the item to not work +correctly. NOTE: if you use an invalid model, it will still try to use it and show the NULL axis model (or nothing at all) targetname - how you refer to it for using it */ -void SP_misc_replicator_item ( gentity_t *self ) -{ - if ( self->model ) - { - self->bounceCount = G_ModelIndex( self->model ); +void SP_misc_replicator_item(gentity_t *self) { + if (self->model) { + self->bounceCount = G_ModelIndex(self->model); self->count++; - if ( self->model2 ) - { - self->fly_sound_debounce_time = G_ModelIndex( self->model2 ); + if (self->model2) { + self->fly_sound_debounce_time = G_ModelIndex(self->model2); self->count++; - if ( self->target ) - { - self->painDebounceTime = G_ModelIndex( self->target ); + if (self->target) { + self->painDebounceTime = G_ModelIndex(self->target); self->count++; - if ( self->target2 ) - { - self->disconnectDebounceTime = G_ModelIndex( self->target2 ); + if (self->target2) { + self->disconnectDebounceTime = G_ModelIndex(self->target2); self->count++; - if ( self->target3 ) - { - self->attackDebounceTime = G_ModelIndex( self->target3 ); + if (self->target3) { + self->attackDebounceTime = G_ModelIndex(self->target3); self->count++; - if ( self->target4 ) - { - self->pushDebounceTime = G_ModelIndex( self->target4 ); + if (self->target4) { + self->pushDebounceTime = G_ModelIndex(self->target4); self->count++; } } @@ -1603,18 +1392,18 @@ void SP_misc_replicator_item ( gentity_t *self ) } } } -// G_SoundIndex( "sound/movers/switches/replicator.wav" ); + // G_SoundIndex( "sound/movers/switches/replicator.wav" ); self->e_UseFunc = useF_misc_replicator_item_spawn; self->s.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->contents = 0; - VectorSet( self->mins, -4, -4, 0 ); - VectorSet( self->maxs, 4, 4, 8 ); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); + VectorSet(self->mins, -4, -4, 0); + VectorSet(self->maxs, 4, 4, 8); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); - gi.linkentity( self ); + gi.linkentity(self); } /*QUAKED misc_trip_mine (0.2 0.8 0.2) (-4 -4 -4) (4 4 4) START_ON BROADCAST @@ -1629,137 +1418,125 @@ targetname - starts off, when used, turns on (toggles) FIXME: sometimes we want these to not be shootable... maybe just put them behind a force field? */ -extern void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ); -extern void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ); +extern void touchLaserTrap(gentity_t *ent, gentity_t *other, trace_t *trace); +extern void CreateLaserTrap(gentity_t *laserTrap, vec3_t start, gentity_t *owner); -void misc_trip_mine_activate( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->e_ThinkFunc == thinkF_laserTrapThink ) - { +void misc_trip_mine_activate(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->e_ThinkFunc == thinkF_laserTrapThink) { self->s.eFlags &= ~EF_FIRING; self->s.loopSound = 0; self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - } - else - { + } else { self->e_ThinkFunc = thinkF_laserTrapThink; self->nextthink = level.time + FRAMETIME; } } -void SP_misc_trip_mine( gentity_t *self ) -{ - vec3_t forward, end; - trace_t trace; +void SP_misc_trip_mine(gentity_t *self) { + vec3_t forward, end; + trace_t trace; - AngleVectors( self->s.angles, forward, NULL, NULL ); - VectorMA( self->s.origin, 128, forward, end ); + AngleVectors(self->s.angles, forward, NULL, NULL); + VectorMA(self->s.origin, 128, forward, end); - gi.trace( &trace, self->s.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, self->s.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( trace.allsolid || trace.startsolid ) - { - Com_Error( ERR_DROP,"misc_trip_mine at %s in solid\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.allsolid || trace.startsolid) { + Com_Error(ERR_DROP, "misc_trip_mine at %s in solid\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( trace.fraction == 1.0 ) - { - Com_Error( ERR_DROP,"misc_trip_mine at %s pointed at no surface\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.fraction == 1.0) { + Com_Error(ERR_DROP, "misc_trip_mine at %s pointed at no surface\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - RegisterItem( FindItemForWeapon( WP_TRIP_MINE )); //precache the weapon + RegisterItem(FindItemForWeapon(WP_TRIP_MINE)); // precache the weapon - self->count = 2/*TRIPWIRE_STYLE*/; + self->count = 2 /*TRIPWIRE_STYLE*/; - vectoangles( trace.plane.normal, end ); - G_SetOrigin( self, trace.endpos ); - G_SetAngles( self, end ); + vectoangles(trace.plane.normal, end); + G_SetOrigin(self, trace.endpos); + G_SetAngles(self, end); - CreateLaserTrap( self, trace.endpos, self ); - touchLaserTrap( self, self, &trace ); + CreateLaserTrap(self, trace.endpos, self); + touchLaserTrap(self, self, &trace); self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - if ( !self->targetname || (self->spawnflags&1) ) - {//starts on - misc_trip_mine_activate( self, self, self ); + if (!self->targetname || (self->spawnflags & 1)) { // starts on + misc_trip_mine_activate(self, self, self); } - if ( self->targetname ) - { + if (self->targetname) { self->e_UseFunc = useF_misc_trip_mine_activate; } - if (( self->spawnflags & 2 )) // broadcast...should only be used in very rare cases. could fix networking, perhaps, but james suggested this because it's easier + if ((self->spawnflags & + 2)) // broadcast...should only be used in very rare cases. could fix networking, perhaps, but james suggested this because it's easier { self->svFlags |= SVF_BROADCAST; } - gi.linkentity( self ); + gi.linkentity(self); } /*QUAKED misc_maglock (0 .5 .8) (-8 -8 -8) (8 8 8) x x x x x x x x -Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door it's attached to +Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door +it's attached to NOTE: place these half-way in the door to make it flush with the door's surface. "target" thing to use when destoryed (not doors - it automatically unlocks the door it was angled at) "health" default is 10 */ -void maglock_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - //unlock our door if we're the last lock pointed at the door - if ( self->activator ) - { +void maglock_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + // unlock our door if we're the last lock pointed at the door + if (self->activator) { self->activator->lockCount--; - if ( !self->activator->lockCount ) - { + if (!self->activator->lockCount) { self->activator->svFlags &= ~SVF_INACTIVE; } } - //use targets - G_UseTargets( self, attacker ); - //die - WP_Explode( self ); + // use targets + G_UseTargets(self, attacker); + // die + WP_Explode(self); } -void SP_misc_maglock ( gentity_t *self ) -{ - //NOTE: May have to make these only work on doors that are either untargeted +void SP_misc_maglock(gentity_t *self) { + // NOTE: May have to make these only work on doors that are either untargeted // or are targeted by a trigger, not doors fired off by scripts, counters // or other such things? - self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - self->fxID = G_EffectIndex( "maglock/explosion" ); + self->s.modelindex = G_ModelIndex("models/map_objects/imp_detention/door_lock.md3"); + self->fxID = G_EffectIndex("maglock/explosion"); - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_ThinkFunc = thinkF_maglock_link; - //FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the START_TIME_FIND_LINKS - self->nextthink = level.time + START_TIME_FIND_LINKS+200;//START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! + // FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the + // START_TIME_FIND_LINKS + self->nextthink = + level.time + START_TIME_FIND_LINKS + 200; // START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! } -void maglock_link( gentity_t *self ) -{ - //find what we're supposed to be attached to - vec3_t forward, start, end; - trace_t trace; +void maglock_link(gentity_t *self) { + // find what we're supposed to be attached to + vec3_t forward, start, end; + trace_t trace; - AngleVectors( self->s.angles, forward, NULL, NULL ); - VectorMA( self->s.origin, 128, forward, end ); - VectorMA( self->s.origin, -4, forward, start ); + AngleVectors(self->s.angles, forward, NULL, NULL); + VectorMA(self->s.origin, 128, forward, end); + VectorMA(self->s.origin, -4, forward, start); - gi.trace( &trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( trace.allsolid || trace.startsolid ) - { - Com_Error( ERR_DROP,"misc_maglock at %s in solid\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.allsolid || trace.startsolid) { + Com_Error(ERR_DROP, "misc_maglock at %s in solid\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { self->e_ThinkFunc = thinkF_maglock_link; self->nextthink = level.time + 100; /* @@ -1769,45 +1546,43 @@ void maglock_link( gentity_t *self ) return; } gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp( "func_door", traceEnt->classname ) ) - { + if (trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp("func_door", traceEnt->classname)) { self->e_ThinkFunc = thinkF_maglock_link; self->nextthink = level.time + 100; - //Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); - //G_FreeEntity( self ); + // Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); + // G_FreeEntity( self ); return; } - //check the traceEnt, make sure it's a door and give it a lockCount and deactivate it - //find the trigger for the door - self->activator = G_FindDoorTrigger( traceEnt ); - if ( !self->activator ) - { + // check the traceEnt, make sure it's a door and give it a lockCount and deactivate it + // find the trigger for the door + self->activator = G_FindDoorTrigger(traceEnt); + if (!self->activator) { self->activator = traceEnt; } self->activator->lockCount++; self->activator->svFlags |= SVF_INACTIVE; - //now position and orient it - vectoangles( trace.plane.normal, end ); - G_SetOrigin( self, trace.endpos ); - G_SetAngles( self, end ); + // now position and orient it + vectoangles(trace.plane.normal, end); + G_SetOrigin(self, trace.endpos); + G_SetAngles(self, end); - //make it hittable - //FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? - //self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - VectorSet( self->mins, -8, -8, -8 ); - VectorSet( self->maxs, 8, 8, 8 ); + // make it hittable + // FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? + // self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); + VectorSet(self->mins, -8, -8, -8); + VectorSet(self->maxs, 8, 8, 8); self->contents = CONTENTS_CORPSE; - //make it destroyable - self->flags |= FL_SHIELDED;//only damagable by lightsabers + // make it destroyable + self->flags |= FL_SHIELDED; // only damagable by lightsabers self->takedamage = qtrue; self->health = 10; self->e_DieFunc = dieF_maglock_die; - //self->fxID = G_EffectIndex( "maglock/explosion" ); + // self->fxID = G_EffectIndex( "maglock/explosion" ); - gi.linkentity( self ); + gi.linkentity(self); } /* @@ -1815,22 +1590,19 @@ void maglock_link( gentity_t *self ) EnergyShieldStationSettings ================ */ -void EnergyShieldStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void EnergyShieldStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } @@ -1842,37 +1614,30 @@ void EnergyShieldStationSettings(gentity_t *ent) shield_power_converter_use ================ */ -void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int dif,add; +void shield_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int dif, add; - if ( !activator || activator->s.number != 0 ) - { - //only the player gets to use these + if (!activator || activator->s.number != 0) { + // only the player gets to use these return; } - G_ActivateBehavior( self,BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - if ( self->setTime < level.time ) - { + if (self->setTime < level.time) { self->setTime = level.time + 100; dif = 100 - activator->client->ps.stats[STAT_ARMOR]; // FIXME: define for max armor? - if ( dif > 0 && self->count ) // Already at full armor?..and do I even have anything to give + if (dif > 0 && self->count) // Already at full armor?..and do I even have anything to give { - if ( dif > MAX_AMMO_GIVE ) - { + if (dif > MAX_AMMO_GIVE) { add = MAX_AMMO_GIVE; - } - else - { + } else { add = dif; } - if ( self->count < add ) - { + if (self->count < add) { add = self->count; } @@ -1880,51 +1645,43 @@ void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *a activator->client->ps.stats[STAT_ARMOR] += add; - self->s.loopSound = G_SoundIndex( "sound/interface/shieldcon_run.wav" ); + self->s.loopSound = G_SoundIndex("sound/interface/shieldcon_run.wav"); } - if ( self->count <= 0 ) - { + if (self->count <= 0) { // play empty sound self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much - G_Sound( self, G_SoundIndex( "sound/interface/shieldcon_empty.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/shieldcon_empty.mp3")); self->s.loopSound = 0; - if ( self->s.eFlags & EF_SHADER_ANIM ) - { - self->s.frame = 1; + if (self->s.eFlags & EF_SHADER_ANIM) { + self->s.frame = 1; } - } - else if ( activator->client->ps.stats[STAT_ARMOR] >= 100 ) // FIXME: define for max + } else if (activator->client->ps.stats[STAT_ARMOR] >= 100) // FIXME: define for max { // play full sound - G_Sound( self, G_SoundIndex( "sound/interface/shieldcon_done.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/shieldcon_done.mp3")); self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much self->s.loopSound = 0; } } - if ( self->s.loopSound ) - { + if (self->s.loopSound) { // we will have to shut of the loop sound, so I guess try and do it intelligently...NOTE: this could get completely stomped every time through the loop // this is fine, since it just controls shutting off the sound when there are situations that could start the sound but not shut it off self->e_ThinkFunc = thinkF_poll_converter; self->nextthink = level.time + 500; - } - else - { + } else { // sound is already off, so we don't need to "think" about it. self->e_ThinkFunc = thinkF_NULL; self->nextthink = 0; } - if ( activator->client->ps.stats[STAT_ARMOR] > 0 ) - { + if (activator->client->ps.stats[STAT_ARMOR] > 0) { activator->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE; } } - /*QUAKED misc_model_shield_power_converter (1 0 0) (-16 -16 -16) (16 16 16) x x x USETARGET #MODELNAME="models/items/psd_big.md3" Gives shield energy when used. @@ -1938,9 +1695,8 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_model_shield_power_converter( gentity_t *ent ) -{ - SetMiscModelDefaults( ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); +void SP_misc_model_shield_power_converter(gentity_t *ent) { + SetMiscModelDefaults(ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -1950,7 +1706,7 @@ void SP_misc_model_shield_power_converter( gentity_t *ent ) G_SoundIndex("sound/interface/shieldcon_done.mp3"); G_SoundIndex("sound/interface/shieldcon_empty.mp3"); - ent->s.modelindex2 = G_ModelIndex("/models/items/psd_big.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("/models/items/psd_big.md3"); // Precache model } /*QUAKED misc_shield_floor_unit (1 0 0) (-16 -16 0) (16 16 32) x x x USETARGET @@ -1966,12 +1722,11 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_shield_floor_unit( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 32 ); +void SP_misc_shield_floor_unit(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 32); - SetMiscModelDefaults( ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_shield_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -1981,32 +1736,28 @@ void SP_misc_shield_floor_unit( gentity_t *ent ) G_SoundIndex("sound/interface/shieldcon_done.mp3"); G_SoundIndex("sound/interface/shieldcon_empty.mp3"); - ent->s.modelindex = G_ModelIndex( "models/items/a_shield_converter.md3" ); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/a_shield_converter.md3"); // Precache model ent->s.eFlags |= EF_SHADER_ANIM; } - /* ================ EnergyAmmoShieldStationSettings ================ */ -void EnergyAmmoStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void EnergyAmmoStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } @@ -2016,8 +1767,7 @@ void EnergyAmmoStationSettings(gentity_t *ent) // There has to be an easier way to turn off the looping sound...but // it's the night before beta and my brain is fried //------------------------------------------------------------------ -void poll_converter( gentity_t *self ) -{ +void poll_converter(gentity_t *self) { self->s.loopSound = 0; self->nextthink = 0; self->e_ThinkFunc = thinkF_NULL; @@ -2028,105 +1778,84 @@ void poll_converter( gentity_t *self ) ammo_power_converter_use ================ */ -void ammo_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int add; - int difBlaster,difPowerCell,difMetalBolts; +void ammo_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int add; + int difBlaster, difPowerCell, difMetalBolts; playerState_t *ps; - if ( !activator || activator->s.number != 0 ) - {//only the player gets to use these + if (!activator || activator->s.number != 0) { // only the player gets to use these return; } - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); ps = &activator->client->ps; - if ( self->setTime < level.time ) - { - difBlaster = ammoData[AMMO_BLASTER].max - ps->ammo[AMMO_BLASTER]; - difPowerCell = ammoData[AMMO_POWERCELL].max - ps->ammo[AMMO_POWERCELL]; - difMetalBolts = ammoData[AMMO_METAL_BOLTS].max - ps->ammo[AMMO_METAL_BOLTS]; + if (self->setTime < level.time) { + difBlaster = ammoData[AMMO_BLASTER].max - ps->ammo[AMMO_BLASTER]; + difPowerCell = ammoData[AMMO_POWERCELL].max - ps->ammo[AMMO_POWERCELL]; + difMetalBolts = ammoData[AMMO_METAL_BOLTS].max - ps->ammo[AMMO_METAL_BOLTS]; // Has it got any power left...and can we even use any of it? - if ( self->count && ( difBlaster > 0 || difPowerCell > 0 || difMetalBolts > 0 )) - { + if (self->count && (difBlaster > 0 || difPowerCell > 0 || difMetalBolts > 0)) { // at least one of the ammo types could stand to take on a bit more ammo self->setTime = level.time + 100; - self->s.loopSound = G_SoundIndex( "sound/interface/ammocon_run.wav" ); + self->s.loopSound = G_SoundIndex("sound/interface/ammocon_run.wav"); // dole out ammo in little packets - if ( self->count > MAX_AMMO_GIVE ) - { + if (self->count > MAX_AMMO_GIVE) { add = MAX_AMMO_GIVE; - } - else if ( self->count < 0 ) - { + } else if (self->count < 0) { add = 0; - } - else - { + } else { add = self->count; } // all weapons fill at same rate... - ps->ammo[AMMO_BLASTER] += add; - ps->ammo[AMMO_POWERCELL] += add; - ps->ammo[AMMO_METAL_BOLTS] += add; + ps->ammo[AMMO_BLASTER] += add; + ps->ammo[AMMO_POWERCELL] += add; + ps->ammo[AMMO_METAL_BOLTS] += add; // ...then get clamped to max - if ( ps->ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max ) - { + if (ps->ammo[AMMO_BLASTER] > ammoData[AMMO_BLASTER].max) { ps->ammo[AMMO_BLASTER] = ammoData[AMMO_BLASTER].max; } - if ( ps->ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max ) - { + if (ps->ammo[AMMO_POWERCELL] > ammoData[AMMO_POWERCELL].max) { ps->ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; } - if ( ps->ammo[AMMO_METAL_BOLTS] > ammoData[AMMO_METAL_BOLTS].max ) - { + if (ps->ammo[AMMO_METAL_BOLTS] > ammoData[AMMO_METAL_BOLTS].max) { ps->ammo[AMMO_METAL_BOLTS] = ammoData[AMMO_METAL_BOLTS].max; } self->count -= add; } - if ( self->count <= 0 ) - { + if (self->count <= 0) { // play empty sound self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much - G_Sound( self, G_SoundIndex( "sound/interface/ammocon_empty.mp3" )); + G_Sound(self, G_SoundIndex("sound/interface/ammocon_empty.mp3")); self->s.loopSound = 0; - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 1; } - } - else if ( ps->ammo[AMMO_BLASTER] >= ammoData[AMMO_BLASTER].max - && ps->ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max - && ps->ammo[AMMO_METAL_BOLTS] >= ammoData[AMMO_METAL_BOLTS].max ) - { + } else if (ps->ammo[AMMO_BLASTER] >= ammoData[AMMO_BLASTER].max && ps->ammo[AMMO_POWERCELL] >= ammoData[AMMO_POWERCELL].max && + ps->ammo[AMMO_METAL_BOLTS] >= ammoData[AMMO_METAL_BOLTS].max) { // play full sound - G_Sound( self, G_SoundIndex( "sound/interface/ammocon_done.wav" )); + G_Sound(self, G_SoundIndex("sound/interface/ammocon_done.wav")); self->setTime = level.time + 1000; // extra debounce so that the sounds don't overlap too much self->s.loopSound = 0; } } - - if ( self->s.loopSound ) - { + if (self->s.loopSound) { // we will have to shut of the loop sound, so I guess try and do it intelligently...NOTE: this could get completely stomped every time through the loop // this is fine, since it just controls shutting off the sound when there are situations that could start the sound but not shut it off self->e_ThinkFunc = thinkF_poll_converter; self->nextthink = level.time + 500; - } - else - { + } else { // sound is already off, so we don't need to "think" about it. self->e_ThinkFunc = thinkF_NULL; self->nextthink = 0; @@ -2146,9 +1875,8 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_model_ammo_power_converter( gentity_t *ent ) -{ - SetMiscModelDefaults( ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); +void SP_misc_model_ammo_power_converter(gentity_t *ent) { + SetMiscModelDefaults(ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2158,7 +1886,7 @@ void SP_misc_model_ammo_power_converter( gentity_t *ent ) G_SoundIndex("sound/interface/ammocon_done.mp3"); G_SoundIndex("sound/interface/ammocon_empty.mp3"); - ent->s.modelindex2 = G_ModelIndex("/models/items/power_converter.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("/models/items/power_converter.md3"); // Precache model } /*QUAKED misc_ammo_floor_unit (1 0 0) (-16 -16 0) (16 16 32) x x x USETARGET @@ -2174,12 +1902,11 @@ USETARGET - when used it fires off target "count" - the amount of ammo given when used (default 100) */ //------------------------------------------------------------ -void SP_misc_ammo_floor_unit( gentity_t *ent ) -{ - VectorSet( ent->mins, -16, -16, 0 ); - VectorSet( ent->maxs, 16, 16, 32 ); +void SP_misc_ammo_floor_unit(gentity_t *ent) { + VectorSet(ent->mins, -16, -16, 0); + VectorSet(ent->maxs, 16, 16, 32); - SetMiscModelDefaults( ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_ammo_power_converter_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; @@ -2189,51 +1916,44 @@ void SP_misc_ammo_floor_unit( gentity_t *ent ) G_SoundIndex("sound/interface/ammocon_done.mp3"); G_SoundIndex("sound/interface/ammocon_empty.mp3"); - ent->s.modelindex = G_ModelIndex("models/items/a_pwr_converter.md3"); // Precache model + ent->s.modelindex = G_ModelIndex("models/items/a_pwr_converter.md3"); // Precache model ent->s.eFlags |= EF_SHADER_ANIM; } - /* ================ welder_think ================ */ -void welder_think( gentity_t *self ) -{ +void welder_think(gentity_t *self) { self->nextthink = level.time + 200; - vec3_t org, - dir; - mdxaBone_t boltMatrix; + vec3_t org, dir; + mdxaBone_t boltMatrix; - if( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; } int newBolt; // could alternate between the two... or make it random... ? - newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash" ); -// newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash01" ); + newBolt = gi.G2API_AddBolt(&self->ghoul2[self->playerModel], "*flash"); + // newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash01" ); - if ( newBolt != -1 ) - { - G_Sound( self, self->noise_index ); - // G_PlayEffect( "blueWeldSparks", self->playerModel, newBolt, self->s.number); + if (newBolt != -1) { + G_Sound(self, self->noise_index); + // G_PlayEffect( "blueWeldSparks", self->playerModel, newBolt, self->s.number); // The welder gets rotated around a lot, and since the origin is offset by 352 I have to make this super expensive call to position the hurt... - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, newBolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, newBolt, &boltMatrix, self->currentAngles, self->currentOrigin, + (cg.time ? cg.time : level.time), NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - VectorSubtract( self->currentOrigin, org, dir ); - VectorNormalize( dir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + VectorSubtract(self->currentOrigin, org, dir); + VectorNormalize(dir); // we want the welder effect to face inwards.... - G_PlayEffect( "blueWeldSparks", org, dir ); - G_RadiusDamage( org, self, 10, 45, self, MOD_UNKNOWN ); + G_PlayEffect("blueWeldSparks", org, dir); + G_RadiusDamage(org, self, 10, 45, self, MOD_UNKNOWN); } - } /* @@ -2241,19 +1961,14 @@ void welder_think( gentity_t *self ) welder_use ================ */ -void welder_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void welder_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle on and off - if( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->nextthink = -1; } self->spawnflags = (self->spawnflags ^ 1); - } /*QUAKED misc_model_welder (1 0 0) (-16 -16 -16) (16 16 16) START_OFF @@ -2264,50 +1979,45 @@ START_OFF - welder starts off, using it toggles it on/off */ //------------------------------------------------------------ -void SP_misc_model_welder( gentity_t *ent ) -{ - VectorSet( ent->mins, 336, -16, 0 ); - VectorSet( ent->maxs, 368, 16, 32 ); +void SP_misc_model_welder(gentity_t *ent) { + VectorSet(ent->mins, 336, -16, 0); + VectorSet(ent->maxs, 368, 16, 32); - SetMiscModelDefaults( ent, useF_welder_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse ); + SetMiscModelDefaults(ent, useF_welder_use, "4", CONTENTS_SOLID, 0, qfalse, qfalse); ent->takedamage = qfalse; ent->contents = 0; - G_EffectIndex( "blueWeldSparks" ); - ent->noise_index = G_SoundIndex( "sound/movers/objects/welding.wav" ); + G_EffectIndex("blueWeldSparks"); + ent->noise_index = G_SoundIndex("sound/movers/objects/welding.wav"); - ent->s.modelindex = G_ModelIndex( "models/map_objects/cairn/welder.glm" ); -// ent->s.modelindex2 = G_ModelIndex( "models/map_objects/cairn/welder.md3" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/map_objects/cairn/welder.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->s.radius = 400.0f;// the origin of the welder is offset by approximately 352, so we need the big radius + ent->s.modelindex = G_ModelIndex("models/map_objects/cairn/welder.glm"); + // ent->s.modelindex2 = G_ModelIndex( "models/map_objects/cairn/welder.md3" ); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, "models/map_objects/cairn/welder.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->s.radius = 400.0f; // the origin of the welder is offset by approximately 352, so we need the big radius ent->e_ThinkFunc = thinkF_welder_think; ent->nextthink = level.time + 1000; - if( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { ent->nextthink = -1; } } - /* ================ jabba_cam_use ================ */ -void jabba_cam_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if( self->spawnflags & 1 ) - { +void jabba_cam_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->spawnflags & 1) { self->spawnflags &= ~1; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 15, 0, BONE_ANIM_OVERRIDE_FREEZE, -1.5f, (cg.time?cg.time:level.time), -1, 0 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 15, 0, BONE_ANIM_OVERRIDE_FREEZE, -1.5f, (cg.time ? cg.time : level.time), + -1, 0); - } - else - { + } else { self->spawnflags |= 1; - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 1.5f, (cg.time?cg.time:level.time), -1, 0 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 1.5f, (cg.time ? cg.time : level.time), + -1, 0); } } @@ -2322,41 +2032,38 @@ The eye camera that popped out of Jabba's front door */ //----------------------------------------------------- -void SP_misc_model_jabba_cam( gentity_t *ent ) +void SP_misc_model_jabba_cam(gentity_t *ent) //----------------------------------------------------- { - VectorSet( ent->mins, -60.0f, -8.0f, 0.0f ); - VectorSet( ent->maxs, 60.0f, 8.0f, 16.0f ); + VectorSet(ent->mins, -60.0f, -8.0f, 0.0f); + VectorSet(ent->maxs, 60.0f, 8.0f, 16.0f); - SetMiscModelDefaults( ent, useF_jabba_cam_use, "4", 0, 0, qfalse, qfalse ); - G_SetAngles( ent, ent->s.angles ); + SetMiscModelDefaults(ent, useF_jabba_cam_use, "4", 0, 0, qfalse, qfalse); + G_SetAngles(ent, ent->s.angles); - ent->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/jabacam/jabacam.glm" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/map_objects/nar_shaddar/jabacam/jabacam.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->s.radius = 150.0f; //...... - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); + ent->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/jabacam/jabacam.glm"); + ent->playerModel = + gi.G2API_InitGhoul2Model(ent->ghoul2, "models/map_objects/nar_shaddar/jabacam/jabacam.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->s.radius = 150.0f; //...... + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); ent->e_UseFunc = useF_jabba_cam_use; ent->takedamage = qfalse; // start extended.. - if ( ent->spawnflags & 1 ) - { - gi.G2API_SetBoneAnimIndex( &ent->ghoul2[ent->playerModel], ent->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); + if (ent->spawnflags & 1) { + gi.G2API_SetBoneAnimIndex(&ent->ghoul2[ent->playerModel], ent->rootBone, 0, 15, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1); } - gi.linkentity( ent ); + gi.linkentity(ent); } //------------------------------------------------------------------------ -void misc_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - misc_model_breakable_die( self, other, activator, 100, MOD_UNKNOWN ); -} +void misc_use(gentity_t *self, gentity_t *other, gentity_t *activator) { misc_model_breakable_die(self, other, activator, 100, MOD_UNKNOWN); } /*QUAKED misc_exploding_crate (1 0 0.25) (-24 -24 0) (24 24 64) #MODELNAME="models/map_objects/nar_shaddar/crate_xplode.md3" @@ -2372,33 +2079,31 @@ Basic exploding crate */ //------------------------------------------------------------ -void SP_misc_exploding_crate( gentity_t *ent ) -{ - G_SpawnInt( "health", "40", &ent->health ); - G_SpawnInt( "splashRadius", "128", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "50", &ent->splashDamage ); +void SP_misc_exploding_crate(gentity_t *ent) { + G_SpawnInt("health", "40", &ent->health); + G_SpawnInt("splashRadius", "128", &ent->splashRadius); + G_SpawnInt("splashDamage", "50", &ent->splashDamage); - ent->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/crate_xplode.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/crate_xplode.md3"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/metalexplode"); - VectorSet( ent->mins, -24, -24, 0 ); - VectorSet( ent->maxs, 24, 24, 64 ); + VectorSet(ent->mins, -24, -24, 0); + VectorSet(ent->maxs, 24, 24, 64); - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//CONTENTS_SOLID; + ent->contents = CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // CONTENTS_SOLID; ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } ent->material = MAT_CRATE1; - ent->e_DieFunc = dieF_misc_model_breakable_die;//ExplodeDeath; + ent->e_DieFunc = dieF_misc_model_breakable_die; // ExplodeDeath; } /*QUAKED misc_gas_tank (1 0 0.25) (-4 -4 0) (4 4 40) @@ -2415,63 +2120,59 @@ Basic exploding oxygen tank */ -void gas_random_jet( gentity_t *self ) -{ +void gas_random_jet(gentity_t *self) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 50; - G_PlayEffect( "env/mini_gasjet", pt ); + G_PlayEffect("env/mini_gasjet", pt); self->nextthink = level.time + Q_flrand(0.0f, 1.0f) * 16000 + 12000; // do this rarely } //------------------------------------------------------------ -void GasBurst( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc ) -{ +void GasBurst(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 46; - G_PlayEffect( "env/mini_flamejet", pt ); + G_PlayEffect("env/mini_flamejet", pt); // do some damage to anything that may be standing on top of it when it bursts into flame pt[2] += 32; - G_RadiusDamage( pt, self, 32, 32, self, MOD_UNKNOWN ); + G_RadiusDamage(pt, self, 32, 32, self, MOD_UNKNOWN); // only get one burst self->e_PainFunc = painF_NULL; } //------------------------------------------------------------ -void SP_misc_gas_tank( gentity_t *ent ) -{ - G_SpawnInt( "health", "20", &ent->health ); - G_SpawnInt( "splashRadius", "48", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "32", &ent->splashDamage ); +void SP_misc_gas_tank(gentity_t *ent) { + G_SpawnInt("health", "20", &ent->health); + G_SpawnInt("splashRadius", "48", &ent->splashRadius); + G_SpawnInt("splashDamage", "32", &ent->splashDamage); - ent->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/tank.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/tank.md3"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - G_EffectIndex( "chunks/metalexplode" ); - G_EffectIndex( "env/mini_flamejet" ); - G_EffectIndex( "env/mini_gasjet" ); + G_EffectIndex("chunks/metalexplode"); + G_EffectIndex("env/mini_flamejet"); + G_EffectIndex("env/mini_gasjet"); - VectorSet( ent->mins, -4, -4, 0 ); - VectorSet( ent->maxs, 4, 4, 40 ); + VectorSet(ent->mins, -4, -4, 0); + VectorSet(ent->maxs, 4, 4, 40); ent->contents = CONTENTS_SOLID; ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); ent->e_PainFunc = painF_GasBurst; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } @@ -2500,56 +2201,52 @@ NON_SOLID - can only be shot */ //------------------------------------------------------------ -void CrystalCratePain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc ) -{ +void CrystalCratePain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { vec3_t pt; - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] += 36; - G_PlayEffect( "env/crystal_crate", pt ); + G_PlayEffect("env/crystal_crate", pt); // do some damage, heh pt[2] += 32; - G_RadiusDamage( pt, self, 16, 32, self, MOD_UNKNOWN ); - + G_RadiusDamage(pt, self, 16, 32, self, MOD_UNKNOWN); } //------------------------------------------------------------ -void SP_misc_crystal_crate( gentity_t *ent ) -{ - G_SpawnInt( "health", "80", &ent->health ); - G_SpawnInt( "splashRadius", "80", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "40", &ent->splashDamage ); - - ent->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/crate_open.md3" ); - ent->fxID = G_EffectIndex( "thermal/explosion" ); // FIXME: temp - G_EffectIndex( "env/crystal_crate" ); +void SP_misc_crystal_crate(gentity_t *ent) { + G_SpawnInt("health", "80", &ent->health); + G_SpawnInt("splashRadius", "80", &ent->splashRadius); + G_SpawnInt("splashDamage", "40", &ent->splashDamage); + + ent->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/crate_open.md3"); + ent->fxID = G_EffectIndex("thermal/explosion"); // FIXME: temp + G_EffectIndex("env/crystal_crate"); G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); - VectorSet( ent->mins, -34, -34, 0 ); - VectorSet( ent->maxs, 34, 34, 44 ); + VectorSet(ent->mins, -34, -34, 0); + VectorSet(ent->maxs, 34, 34, 44); - //Blocks movement - ent->contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//Was CONTENTS_SOLID, but only architecture should be this + // Blocks movement + ent->contents = + CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // Was CONTENTS_SOLID, but only architecture should be this - if ( ent->spawnflags & 1 ) // non-solid - { // Override earlier contents flag... - //Can only be shot + if (ent->spawnflags & 1) // non-solid + { // Override earlier contents flag... + // Can only be shot ent->contents = CONTENTS_SHOTCLIP; } - ent->takedamage = qtrue; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); ent->e_PainFunc = painF_CrystalCratePain; - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_misc_use; } @@ -2567,225 +2264,202 @@ Drivable ATST, when used by player, they become the ATST. When the player hits "target" - what to use when it dies */ -void misc_atst_setanim( gentity_t *self, int bone, int anim ) -{ - if ( bone < 0 || anim < 0 ) - { +void misc_atst_setanim(gentity_t *self, int bone, int anim) { + if (bone < 0 || anim < 0) { return; } - int firstFrame = -1; - int lastFrame = -1; + int firstFrame = -1; + int lastFrame = -1; float animSpeed = 0; - //try to get anim ranges from the animation.cfg for an AT-ST - for ( int i = 0; i < level.numKnownAnimFileSets; i++ ) - { - if ( !Q_stricmp( "atst", level.knownAnimFileSets[i].filename ) ) - { + // try to get anim ranges from the animation.cfg for an AT-ST + for (int i = 0; i < level.numKnownAnimFileSets; i++) { + if (!Q_stricmp("atst", level.knownAnimFileSets[i].filename)) { firstFrame = level.knownAnimFileSets[i].animations[anim].firstFrame; - lastFrame = firstFrame+level.knownAnimFileSets[i].animations[anim].numFrames; + lastFrame = firstFrame + level.knownAnimFileSets[i].animations[anim].numFrames; animSpeed = 50.0f / level.knownAnimFileSets[i].animations[anim].frameLerp; break; } } - if ( firstFrame != -1 && lastFrame != -1 && animSpeed != 0 ) - { - if (!gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], bone, firstFrame, - lastFrame, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, animSpeed, - (cg.time?cg.time:level.time), -1, 150 )) - { - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], bone, firstFrame, - lastFrame, BONE_ANIM_OVERRIDE_FREEZE, animSpeed, - (cg.time?cg.time:level.time), -1, 150 ); + if (firstFrame != -1 && lastFrame != -1 && animSpeed != 0) { + if (!gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], bone, firstFrame, lastFrame, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, + (cg.time ? cg.time : level.time), -1, 150)) { + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], bone, firstFrame, lastFrame, BONE_ANIM_OVERRIDE_FREEZE, animSpeed, + (cg.time ? cg.time : level.time), -1, 150); } } } -void misc_atst_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{//ATST was destroyed while you weren't in it - //can't be used anymore +void misc_atst_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, + int hitLoc) { // ATST was destroyed while you weren't in it + // can't be used anymore self->e_UseFunc = useF_NULL; - //sigh... remove contents so we don't block the player's path... + // sigh... remove contents so we don't block the player's path... self->contents = CONTENTS_CORPSE; self->takedamage = qfalse; self->maxs[2] = 48; - //FIXME: match to slope + // FIXME: match to slope vec3_t effectPos; - VectorCopy( self->currentOrigin, effectPos ); + VectorCopy(self->currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffect( "droidexplosion1", effectPos ); -// G_PlayEffect( "small_chunks", effectPos ); - //set these to defaults that work in a worst-case scenario (according to current animation.cfg) - gi.G2API_StopBoneAnimIndex( &self->ghoul2[self->playerModel], self->craniumBone ); - misc_atst_setanim( self, self->rootBone, BOTH_DEATH1 ); -} - -extern void G_DriveATST( gentity_t *ent, gentity_t *atst ); -extern void SetClientViewAngle( gentity_t *ent, vec3_t angle ); -extern qboolean PM_InSlopeAnim( int anim ); -void misc_atst_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator || activator->s.number ) - {//only player can do this + G_PlayEffect("droidexplosion1", effectPos); + // G_PlayEffect( "small_chunks", effectPos ); + // set these to defaults that work in a worst-case scenario (according to current animation.cfg) + gi.G2API_StopBoneAnimIndex(&self->ghoul2[self->playerModel], self->craniumBone); + misc_atst_setanim(self, self->rootBone, BOTH_DEATH1); +} + +extern void G_DriveATST(gentity_t *ent, gentity_t *atst); +extern void SetClientViewAngle(gentity_t *ent, vec3_t angle); +extern qboolean PM_InSlopeAnim(int anim); +void misc_atst_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || activator->s.number) { // only player can do this return; } - int tempLocDmg[HL_MAX]; - int hl, tempHealth; + int tempLocDmg[HL_MAX]; + int hl, tempHealth; - if ( activator->client->NPC_class != CLASS_ATST ) - {//get in the ATST - if ( activator->client->ps.groundEntityNum != self->s.number ) - {//can only get in if on top of me... - //we *could* even check for the hatch surf...? + if (activator->client->NPC_class != CLASS_ATST) { // get in the ATST + if (activator->client->ps.groundEntityNum != self->s.number) { // can only get in if on top of me... + // we *could* even check for the hatch surf...? return; } - //copy origin - G_SetOrigin( activator, self->currentOrigin ); + // copy origin + G_SetOrigin(activator, self->currentOrigin); - //copy angles - VectorCopy( self->s.angles2, self->currentAngles ); - G_SetAngles( activator, self->currentAngles ); - SetClientViewAngle( activator, self->currentAngles ); + // copy angles + VectorCopy(self->s.angles2, self->currentAngles); + G_SetAngles(activator, self->currentAngles); + SetClientViewAngle(activator, self->currentAngles); - //set player to my g2 instance - gi.G2API_StopBoneAnimIndex( &self->ghoul2[self->playerModel], self->craniumBone ); - G_DriveATST( activator, self ); + // set player to my g2 instance + gi.G2API_StopBoneAnimIndex(&self->ghoul2[self->playerModel], self->craniumBone); + G_DriveATST(activator, self); activator->activator = self; self->s.eFlags |= EF_NODRAW; self->svFlags |= SVF_NOCLIENT; self->contents = 0; self->takedamage = qfalse; - //transfer armor + // transfer armor tempHealth = self->health; self->health = activator->client->ps.stats[STAT_ARMOR]; activator->client->ps.stats[STAT_ARMOR] = tempHealth; - //transfer locationDamage - for ( hl = HL_NONE; hl < HL_MAX; hl++ ) - { + // transfer locationDamage + for (hl = HL_NONE; hl < HL_MAX; hl++) { tempLocDmg[hl] = activator->locationDamage[hl]; activator->locationDamage[hl] = self->locationDamage[hl]; self->locationDamage[hl] = tempLocDmg[hl]; } - if ( !self->s.number ) - { - CG_CenterPrint( "@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + if (!self->s.number) { + CG_CenterPrint("@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } - } - else - {//get out of ATST + } else { // get out of ATST int legsAnim = activator->client->ps.legsAnim; - if ( legsAnim != BOTH_STAND1 - && !PM_InSlopeAnim( legsAnim ) - && legsAnim != BOTH_TURN_RIGHT1 && legsAnim != BOTH_TURN_LEFT1 ) - {//can't get out of it while it's still moving + if (legsAnim != BOTH_STAND1 && !PM_InSlopeAnim(legsAnim) && legsAnim != BOTH_TURN_RIGHT1 && + legsAnim != BOTH_TURN_LEFT1) { // can't get out of it while it's still moving return; } - //FIXME: after a load/save, this crashes, BAD... somewhere in G2 - G_SetOrigin( self, activator->currentOrigin ); - VectorSet( self->currentAngles, 0, activator->client->ps.legsYaw, 0 ); - //self->currentAngles[PITCH] = activator->currentAngles[ROLL] = 0; - G_SetAngles( self, self->currentAngles ); - VectorCopy( activator->currentAngles, self->s.angles2 ); - //remove my G2 - if ( self->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->playerModel ); + // FIXME: after a load/save, this crashes, BAD... somewhere in G2 + G_SetOrigin(self, activator->currentOrigin); + VectorSet(self->currentAngles, 0, activator->client->ps.legsYaw, 0); + // self->currentAngles[PITCH] = activator->currentAngles[ROLL] = 0; + G_SetAngles(self, self->currentAngles); + VectorCopy(activator->currentAngles, self->s.angles2); + // remove my G2 + if (self->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->playerModel); self->playerModel = -1; } - //copy player's - gi.G2API_CopyGhoul2Instance( activator->ghoul2, self->ghoul2, -1 ); - self->playerModel = 0;//assumption - //reset player to kyle - G_DriveATST( activator, NULL ); + // copy player's + gi.G2API_CopyGhoul2Instance(activator->ghoul2, self->ghoul2, -1); + self->playerModel = 0; // assumption + // reset player to kyle + G_DriveATST(activator, NULL); activator->activator = NULL; self->s.eFlags &= ~EF_NODRAW; self->svFlags &= ~SVF_NOCLIENT; - self->contents = CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + self->contents = CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; self->takedamage = qtrue; - //transfer armor + // transfer armor tempHealth = self->health; self->health = activator->client->ps.stats[STAT_ARMOR]; activator->client->ps.stats[STAT_ARMOR] = tempHealth; - //transfer locationDamage - for ( hl = HL_NONE; hl < HL_MAX; hl++ ) - { + // transfer locationDamage + for (hl = HL_NONE; hl < HL_MAX; hl++) { tempLocDmg[hl] = self->locationDamage[hl]; self->locationDamage[hl] = activator->locationDamage[hl]; activator->locationDamage[hl] = tempLocDmg[hl]; } - //link me back in - gi.linkentity ( self ); - //put activator on top of me? - vec3_t newOrg = {activator->currentOrigin[0], activator->currentOrigin[1], activator->currentOrigin[2] + (self->maxs[2]-self->mins[2]) + 1 }; - G_SetOrigin( activator, newOrg ); - //open the hatch - misc_atst_setanim( self, self->craniumBone, BOTH_STAND2 ); - gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "head_hatchcover_off", 0 ); - G_Sound( self, G_SoundIndex( "sound/chars/atst/atst_hatch_open" )); + // link me back in + gi.linkentity(self); + // put activator on top of me? + vec3_t newOrg = {activator->currentOrigin[0], activator->currentOrigin[1], activator->currentOrigin[2] + (self->maxs[2] - self->mins[2]) + 1}; + G_SetOrigin(activator, newOrg); + // open the hatch + misc_atst_setanim(self, self->craniumBone, BOTH_STAND2); + gi.G2API_SetSurfaceOnOff(&self->ghoul2[self->playerModel], "head_hatchcover_off", 0); + G_Sound(self, G_SoundIndex("sound/chars/atst/atst_hatch_open")); } } -void SP_misc_atst_drivable( gentity_t *ent ) -{ +void SP_misc_atst_drivable(gentity_t *ent) { extern void NPC_ATST_Precache(void); - extern void NPC_PrecacheAnimationCFG( const char *NPC_type ); - - ent->s.modelindex = G_ModelIndex( "models/players/atst/model.glm" ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, "models/players/atst/model.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); - ent->craniumBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "cranium", qtrue ); //FIXME: need to somehow set the anim/frame to the equivalent of BOTH_STAND1... use to be that BOTH_STAND1 was the first frame of the glm, but not anymore + extern void NPC_PrecacheAnimationCFG(const char *NPC_type); + + ent->s.modelindex = G_ModelIndex("models/players/atst/model.glm"); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, "models/players/atst/model.glm", ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); + ent->craniumBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "cranium", + qtrue); // FIXME: need to somehow set the anim/frame to the equivalent of BOTH_STAND1... use to be that + // BOTH_STAND1 was the first frame of the glm, but not anymore ent->s.radius = 320; - VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(ent->s.modelScale, 1.0f, 1.0f, 1.0f); - //register my weapons, sounds and model - RegisterItem( FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon - RegisterItem( FindItemForWeapon( WP_ATST_SIDE )); //precache the weapon - //HACKHACKHACKTEMP - until ATST gets real weapons of it's own? - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); //precache the weapon -// RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon -// RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon - //HACKHACKHACKTEMP - until ATST gets real weapons of it's own? + // register my weapons, sounds and model + RegisterItem(FindItemForWeapon(WP_ATST_MAIN)); // precache the weapon + RegisterItem(FindItemForWeapon(WP_ATST_SIDE)); // precache the weapon + // HACKHACKHACKTEMP - until ATST gets real weapons of it's own? + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); // precache the weapon + // RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon + // RegisterItem( FindItemForWeapon( WP_BOWCASTER )); //precache the weapon + // HACKHACKHACKTEMP - until ATST gets real weapons of it's own? - G_SoundIndex( "sound/chars/atst/atst_hatch_open" ); - G_SoundIndex( "sound/chars/atst/atst_hatch_close" ); + G_SoundIndex("sound/chars/atst/atst_hatch_open"); + G_SoundIndex("sound/chars/atst/atst_hatch_close"); NPC_ATST_Precache(); ent->NPC_type = "atst"; - NPC_PrecacheAnimationCFG( ent->NPC_type ); - //open the hatch - misc_atst_setanim( ent, ent->rootBone, BOTH_STAND2 ); - gi.G2API_SetSurfaceOnOff( &ent->ghoul2[ent->playerModel], "head_hatchcover_off", 0 ); + NPC_PrecacheAnimationCFG(ent->NPC_type); + // open the hatch + misc_atst_setanim(ent, ent->rootBone, BOTH_STAND2); + gi.G2API_SetSurfaceOnOff(&ent->ghoul2[ent->playerModel], "head_hatchcover_off", 0); - VectorSet( ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2 ); - VectorSet( ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2 ); + VectorSet(ent->mins, ATST_MINS0, ATST_MINS1, ATST_MINS2); + VectorSet(ent->maxs, ATST_MAXS0, ATST_MAXS1, ATST_MAXS2); - ent->contents = CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + ent->contents = CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; ent->flags |= FL_SHIELDED; ent->takedamage = qtrue; - if ( !ent->health ) - { + if (!ent->health) { ent->health = 800; } ent->max_health = ent->health; // cg_draw needs this - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - VectorCopy( ent->currentAngles, ent->s.angles2 ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + VectorCopy(ent->currentAngles, ent->s.angles2); - gi.linkentity ( ent ); + gi.linkentity(ent); - //FIXME: test the origin to make sure I'm clear? + // FIXME: test the origin to make sure I'm clear? ent->e_UseFunc = useF_misc_atst_use; ent->svFlags |= SVF_PLAYER_USABLE; - //make it able to take damage and die when you're not in it... - //do an explosion and play the death anim, remove use func. + // make it able to take damage and die when you're not in it... + // do an explosion and play the death anim, remove use func. ent->e_DieFunc = dieF_misc_atst_die; } -void SP_misc_cubemap( gentity_t *ent ) -{ - G_FreeEntity( ent ); -} +void SP_misc_cubemap(gentity_t *ent) { G_FreeEntity(ent); } diff --git a/codeJK2/game/g_misc_model.cpp b/codeJK2/game/g_misc_model.cpp index 657ed82378..a57dfb3f68 100644 --- a/codeJK2/game/g_misc_model.cpp +++ b/codeJK2/game/g_misc_model.cpp @@ -33,118 +33,106 @@ extern cvar_t *g_spskill; // Helper functions // //------------------------------------------------------------ -void SetMiscModelModels( char *modelNameString, gentity_t *ent, qboolean damage_model ) -{ - char damageModel[MAX_QPATH]; - char chunkModel[MAX_QPATH]; - int len; +void SetMiscModelModels(char *modelNameString, gentity_t *ent, qboolean damage_model) { + char damageModel[MAX_QPATH]; + char chunkModel[MAX_QPATH]; + int len; - //Main model - ent->s.modelindex = G_ModelIndex( modelNameString ); + // Main model + ent->s.modelindex = G_ModelIndex(modelNameString); - if ( damage_model ) - { - len = strlen( modelNameString ) - 4; // extract the extension + if (damage_model) { + len = strlen(modelNameString) - 4; // extract the extension - //Dead/damaged model - strncpy( damageModel, modelNameString, len ); + // Dead/damaged model + strncpy(damageModel, modelNameString, len); damageModel[len] = 0; - strncpy( chunkModel, damageModel, sizeof(chunkModel)); - strcat( damageModel, "_d1.md3" ); - ent->s.modelindex2 = G_ModelIndex( damageModel ); + strncpy(chunkModel, damageModel, sizeof(chunkModel)); + strcat(damageModel, "_d1.md3"); + ent->s.modelindex2 = G_ModelIndex(damageModel); ent->spawnflags |= 4; // deadsolid - //Chunk model - strcat( chunkModel, "_c1.md3" ); - ent->s.modelindex3 = G_ModelIndex( chunkModel ); + // Chunk model + strcat(chunkModel, "_c1.md3"); + ent->s.modelindex3 = G_ModelIndex(chunkModel); } } //------------------------------------------------------------ -void SetMiscModelDefaults( gentity_t *ent, useFunc_t use_func, char *material, int solid_mask,int animFlag, - qboolean take_damage, qboolean damage_model = qfalse ) -{ +void SetMiscModelDefaults(gentity_t *ent, useFunc_t use_func, char *material, int solid_mask, int animFlag, qboolean take_damage, + qboolean damage_model = qfalse) { // Apply damage and chunk models if they exist - SetMiscModelModels( ent->model, ent, damage_model ); + SetMiscModelModels(ent->model, ent, damage_model); ent->s.eFlags = animFlag; ent->svFlags |= SVF_PLAYER_USABLE; ent->contents = solid_mask; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - gi.linkentity (ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + gi.linkentity(ent); // Set a generic use function ent->e_UseFunc = use_func; -/* if (use_func == useF_health_use) - { - G_SoundIndex("sound/player/suithealth.wav"); - } - else if (use_func == useF_ammo_use ) - { - G_SoundIndex("sound/player/suitenergy.wav"); - } -*/ - G_SpawnInt( "material", material, (int *)&ent->material ); + /* if (use_func == useF_health_use) + { + G_SoundIndex("sound/player/suithealth.wav"); + } + else if (use_func == useF_ammo_use ) + { + G_SoundIndex("sound/player/suitenergy.wav"); + } + */ + G_SpawnInt("material", material, (int *)&ent->material); - if (ent->health) - { + if (ent->health) { ent->max_health = ent->health; ent->takedamage = take_damage; ent->e_PainFunc = painF_misc_model_breakable_pain; - ent->e_DieFunc = dieF_misc_model_breakable_die; + ent->e_DieFunc = dieF_misc_model_breakable_die; } } -void HealthStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); +void HealthStationSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 100; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 50; break; } } } +void CrystalAmmoSettings(gentity_t *ent) { + G_SpawnInt("count", "0", &ent->count); -void CrystalAmmoSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "0", &ent->count ); - - if (!ent->count) - { - switch (g_spskill->integer) - { - case 0: // EASY + if (!ent->count) { + switch (g_spskill->integer) { + case 0: // EASY ent->count = 75; break; - case 1: // MEDIUM + case 1: // MEDIUM ent->count = 75; break; - default : - case 2: // HARD + default: + case 2: // HARD ent->count = 75; break; } } } - //------------------------------------------------------------ //------------------------------------------------------------ @@ -154,83 +142,73 @@ void CrystalAmmoSettings(gentity_t *ent) */ //------------------------------------------------------------ #include "anims.h" -extern qboolean G_ParseAnimFileSet( const char *filename, const char *animCFG, int *animFileIndex ); +extern qboolean G_ParseAnimFileSet(const char *filename, const char *animCFG, int *animFileIndex); int temp_animFileIndex; -void set_MiscAnim( gentity_t *ent) -{ +void set_MiscAnim(gentity_t *ent) { animation_t *animations = level.knownAnimFileSets[temp_animFileIndex].animations; - if (ent->playerModel & 1) - { + if (ent->playerModel & 1) { int anim = BOTH_STAND3; float animSpeed = 50.0f / animations[anim].frameLerp; // yes, its the same animation, so work out where we are in the leg anim, and blend us - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND , animSpeed, (cg.time?cg.time:level.time), -1, 350); - } - else - { + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time ? cg.time : level.time), -1, 350); + } else { int anim = BOTH_PAIN3; float animSpeed = 50.0f / animations[anim].frameLerp; - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time?cg.time:level.time), -1, 350); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeed, (cg.time ? cg.time : level.time), -1, 350); } ent->nextthink = level.time + 900; ent->playerModel++; - } -void SP_misc_model_ghoul( gentity_t *ent ) -{ +void SP_misc_model_ghoul(gentity_t *ent) { #if 1 - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); gi.G2API_InitGhoul2Model(ent->ghoul2, ent->model, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); ent->s.radius = 50; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - qboolean bHasScale = G_SpawnVector( "modelscale_vec", "1 1 1", ent->s.modelScale ); - if ( !bHasScale ) { + qboolean bHasScale = G_SpawnVector("modelscale_vec", "1 1 1", ent->s.modelScale); + if (!bHasScale) { float temp; - G_SpawnFloat( "modelscale", "0", &temp ); - if ( temp != 0.0f ) { + G_SpawnFloat("modelscale", "0", &temp); + if (temp != 0.0f) { ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = temp; bHasScale = qtrue; } } - if ( bHasScale ) { - //scale the x axis of the bbox up. + if (bHasScale) { + // scale the x axis of the bbox up. ent->maxs[0] *= ent->s.modelScale[0]; ent->mins[0] *= ent->s.modelScale[0]; - //scale the y axis of the bbox up. + // scale the y axis of the bbox up. ent->maxs[1] *= ent->s.modelScale[1]; ent->mins[1] *= ent->s.modelScale[1]; - //scale the z axis of the bbox up and adjust origin accordingly + // scale the z axis of the bbox up and adjust origin accordingly ent->maxs[2] *= ent->s.modelScale[2]; float oldMins2 = ent->mins[2]; ent->mins[2] *= ent->s.modelScale[2]; ent->s.origin[2] += (oldMins2 - ent->mins[2]); } - gi.linkentity (ent); + gi.linkentity(ent); #else char name1[200] = "models/players/kyle/model.glm"; - ent->s.modelindex = G_ModelIndex( name1 ); + ent->s.modelindex = G_ModelIndex(name1); gi.G2API_InitGhoul2Model(ent->ghoul2, name1, ent->s.modelindex); ent->s.radius = 150; - // we found the model ok - load it's animation config - if ( !G_ParseAnimFileSet( "kyle", "_humanoid", &temp_animFileIndex ) ) - { - Com_Printf( S_COLOR_RED"Failed to load animation file set models/players/jedi/animation.cfg\n"); - } - + // we found the model ok - load it's animation config + if (!G_ParseAnimFileSet("kyle", "_humanoid", &temp_animFileIndex)) { + Com_Printf(S_COLOR_RED "Failed to load animation file set models/players/jedi/animation.cfg\n"); + } ent->s.angles[0] = 0; ent->s.angles[1] = 90; @@ -238,54 +216,51 @@ void SP_misc_model_ghoul( gentity_t *ent ) ent->s.origin[2] = 20; ent->s.origin[1] = 80; -// ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = 0.8f; - - VectorSet (ent->mins, -16, -16, -37); - VectorSet (ent->maxs, 16, 16, 32); -//#if _DEBUG -//loadsavecrash -// VectorCopy(ent->mins, ent->s.mins); -// VectorCopy(ent->maxs, ent->s.maxs); -//#endif + // ent->s.modelScale[0] = ent->s.modelScale[1] = ent->s.modelScale[2] = 0.8f; + + VectorSet(ent->mins, -16, -16, -37); + VectorSet(ent->maxs, 16, 16, 32); + //#if _DEBUG + // loadsavecrash + // VectorCopy(ent->mins, ent->s.mins); + // VectorCopy(ent->maxs, ent->s.maxs); + //#endif ent->contents = CONTENTS_BODY; ent->clipmask = MASK_NPCSOLID; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->health = 1000; -// ent->s.modelindex = G_ModelIndex( "models/weapons2/blaster_r/g2blaster_w.glm" ); -// gi.G2API_InitGhoul2Model(ent->ghoul2, "models/weapons2/blaster_r/g2blaster_w.glm", ent->s.modelindex); -// gi.G2API_AddBolt(&ent->ghoul2[0], "*weapon"); -// gi.G2API_AttachG2Model(&ent->ghoul2[1],&ent->ghoul2[0], 0, 0); + // ent->s.modelindex = G_ModelIndex( "models/weapons2/blaster_r/g2blaster_w.glm" ); + // gi.G2API_InitGhoul2Model(ent->ghoul2, "models/weapons2/blaster_r/g2blaster_w.glm", ent->s.modelindex); + // gi.G2API_AddBolt(&ent->ghoul2[0], "*weapon"); + // gi.G2API_AttachG2Model(&ent->ghoul2[1],&ent->ghoul2[0], 0, 0); - gi.linkentity (ent); + gi.linkentity(ent); animation_t *animations = level.knownAnimFileSets[temp_animFileIndex].animations; int anim = BOTH_STAND3; float animSpeed = 50.0f / animations[anim].frameLerp; - gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, - (animations[anim].numFrames -1 )+ animations[anim].firstFrame, - BONE_ANIM_OVERRIDE_FREEZE , animSpeed, cg.time); - -// int test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); -// gi.G2API_SetSurfaceOnOff(&ent->ghoul2[0], "l_arm",0x00000100); -// test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + gi.G2API_SetBoneAnim(&ent->ghoul2[0], "model_root", animations[anim].firstFrame, (animations[anim].numFrames - 1) + animations[anim].firstFrame, + BONE_ANIM_OVERRIDE_FREEZE, animSpeed, cg.time); -// gi.G2API_SetNewOrigin(&ent->ghoul2[0], gi.G2API_AddBolt(&ent->ghoul2[0], "rhang_tag_bone")); -// ent->s.apos.trDelta[1] = 10; -// ent->s.apos.trType = TR_LINEAR; + // int test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + // gi.G2API_SetSurfaceOnOff(&ent->ghoul2[0], "l_arm",0x00000100); + // test = gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[0], "l_hand"); + // gi.G2API_SetNewOrigin(&ent->ghoul2[0], gi.G2API_AddBolt(&ent->ghoul2[0], "rhang_tag_bone")); + // ent->s.apos.trDelta[1] = 10; + // ent->s.apos.trType = TR_LINEAR; ent->nextthink = level.time + 1000; ent->e_ThinkFunc = thinkF_set_MiscAnim; #endif } - -#define RACK_BLASTER 1 -#define RACK_REPEATER 2 -#define RACK_ROCKET 4 +#define RACK_BLASTER 1 +#define RACK_REPEATER 2 +#define RACK_ROCKET 4 /*QUAKED misc_model_gun_rack (1 0 0.25) (-14 -14 -4) (14 14 30) BLASTER REPEATER ROCKET #MODELNAME="models/map_objects/kejim/weaponsrack.md3" @@ -296,24 +271,20 @@ REPEATER - Puts one or more repeater guns on the rack. ROCKET - Puts one or more rocket launchers on the rack. */ -void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fright, float fup ) -{ - vec3_t fwd, right; - gentity_t *it_ent = G_Spawn(); - qboolean rotate = qtrue; +void GunRackAddItem(gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fright, float fup) { + vec3_t fwd, right; + gentity_t *it_ent = G_Spawn(); + qboolean rotate = qtrue; - AngleVectors( angs, fwd, right, NULL ); + AngleVectors(angs, fwd, right, NULL); - if ( it_ent && gun ) - { + if (it_ent && gun) { // FIXME: scaling the ammo will probably need to be tweaked to a reasonable amount...adjust as needed // Set base ammo per type - if ( gun->giType == IT_WEAPON ) - { - it_ent->spawnflags |= 16;// VERTICAL + if (gun->giType == IT_WEAPON) { + it_ent->spawnflags |= 16; // VERTICAL - switch( gun->giTag ) - { + switch (gun->giTag) { case WP_BLASTER: it_ent->count = 15; break; @@ -324,37 +295,30 @@ void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fr it_ent->count = 4; break; } - } - else - { + } else { rotate = qfalse; // must deliberately make it small, or else the objects will spawn inside of each other. - VectorSet( it_ent->maxs, 6.75f, 6.75f, 6.75f ); - VectorScale( it_ent->maxs, -1, it_ent->mins ); + VectorSet(it_ent->maxs, 6.75f, 6.75f, 6.75f); + VectorScale(it_ent->maxs, -1, it_ent->mins); } - it_ent->spawnflags |= 1;// ITMSF_SUSPEND + it_ent->spawnflags |= 1; // ITMSF_SUSPEND it_ent->classname = gun->classname; - G_SpawnItem( it_ent, gun ); + G_SpawnItem(it_ent, gun); // FinishSpawningItem handles everything, so clear the thinkFunc that was set in G_SpawnItem - FinishSpawningItem( it_ent ); + FinishSpawningItem(it_ent); - if ( gun->giType == IT_AMMO ) - { - if ( gun->giTag == AMMO_BLASTER ) // I guess this just has to use different logic?? + if (gun->giType == IT_AMMO) { + if (gun->giTag == AMMO_BLASTER) // I guess this just has to use different logic?? { - if ( g_spskill->integer >= 2 ) - { + if (g_spskill->integer >= 2) { it_ent->count += 10; // give more on higher difficulty because there will be more/harder enemies? } - } - else - { + } else { // scale ammo based on skill - switch ( g_spskill->integer ) - { + switch (g_spskill->integer) { case 0: // do default break; case 1: @@ -369,127 +333,110 @@ void GunRackAddItem( gitem_t *gun, vec3_t org, vec3_t angs, float ffwd, float fr it_ent->nextthink = 0; - VectorCopy( org, it_ent->s.origin ); - VectorMA( it_ent->s.origin, fright, right, it_ent->s.origin ); - VectorMA( it_ent->s.origin, ffwd, fwd, it_ent->s.origin ); + VectorCopy(org, it_ent->s.origin); + VectorMA(it_ent->s.origin, fright, right, it_ent->s.origin); + VectorMA(it_ent->s.origin, ffwd, fwd, it_ent->s.origin); it_ent->s.origin[2] += fup; - VectorCopy( angs, it_ent->s.angles ); + VectorCopy(angs, it_ent->s.angles); // by doing this, we can force the amount of ammo we desire onto the weapon for when it gets picked-up - it_ent->flags |= ( FL_DROPPED_ITEM | FL_FORCE_PULLABLE_ONLY ); + it_ent->flags |= (FL_DROPPED_ITEM | FL_FORCE_PULLABLE_ONLY); it_ent->physicsBounce = 0.1f; - for ( int t = 0; t < 3; t++ ) - { - if ( rotate ) - { - if ( t == YAW ) - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + 180 + Q_flrand(-1.0f, 1.0f) * 14 ); - } - else - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + Q_flrand(-1.0f, 1.0f) * 4 ); + for (int t = 0; t < 3; t++) { + if (rotate) { + if (t == YAW) { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + 180 + Q_flrand(-1.0f, 1.0f) * 14); + } else { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + Q_flrand(-1.0f, 1.0f) * 4); } - } - else - { - if ( t == YAW ) - { - it_ent->s.angles[t] = AngleNormalize180( it_ent->s.angles[t] + 90 + Q_flrand(-1.0f, 1.0f) * 4 ); + } else { + if (t == YAW) { + it_ent->s.angles[t] = AngleNormalize180(it_ent->s.angles[t] + 90 + Q_flrand(-1.0f, 1.0f) * 4); } } } - G_SetAngles( it_ent, it_ent->s.angles ); - G_SetOrigin( it_ent, it_ent->s.origin ); - gi.linkentity( it_ent ); + G_SetAngles(it_ent, it_ent->s.angles); + G_SetOrigin(it_ent, it_ent->s.origin); + gi.linkentity(it_ent); } } //--------------------------------------------- -void SP_misc_model_gun_rack( gentity_t *ent ) -{ - gitem_t *blaster = NULL, *repeater = NULL, *rocket = NULL; - int ct = 0; - float ofz[3]; - gitem_t *itemList[3]; +void SP_misc_model_gun_rack(gentity_t *ent) { + gitem_t *blaster = NULL, *repeater = NULL, *rocket = NULL; + int ct = 0; + float ofz[3]; + gitem_t *itemList[3]; // If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_REPEATER | RACK_ROCKET ))) - { - blaster = FindItemForWeapon( WP_BLASTER ); + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_REPEATER | RACK_ROCKET))) { + blaster = FindItemForWeapon(WP_BLASTER); } - if (( ent->spawnflags & RACK_REPEATER )) - { - repeater = FindItemForWeapon( WP_REPEATER ); + if ((ent->spawnflags & RACK_REPEATER)) { + repeater = FindItemForWeapon(WP_REPEATER); } - if (( ent->spawnflags & RACK_ROCKET )) - { - rocket = FindItemForWeapon( WP_ROCKET_LAUNCHER ); + if ((ent->spawnflags & RACK_ROCKET)) { + rocket = FindItemForWeapon(WP_ROCKET_LAUNCHER); } //---------weapon types - if ( blaster ) - { + if (blaster) { ofz[ct] = 23.0f; itemList[ct++] = blaster; } - if ( repeater ) - { + if (repeater) { ofz[ct] = 24.5f; itemList[ct++] = repeater; } - if ( rocket ) - { + if (rocket) { ofz[ct] = 25.5f; itemList[ct++] = rocket; } - if ( ct ) //..should always have at least one item on their, but just being safe + if (ct) //..should always have at least one item on their, but just being safe { - for ( ; ct < 3 ; ct++ ) - { + for (; ct < 3; ct++) { ofz[ct] = ofz[0]; itemList[ct] = itemList[0]; // first weapon ALWAYS propagates to fill up the shelf } } // now actually add the items to the shelf...validate that we have a list to add - if ( ct ) - { - for ( int i = 0; i < ct; i++ ) - { - GunRackAddItem( itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, ( i - 1 ) * 9 + Q_flrand(-1.0f, 1.0f) * 2, ofz[i] ); + if (ct) { + for (int i = 0; i < ct; i++) { + GunRackAddItem(itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, (i - 1) * 9 + Q_flrand(-1.0f, 1.0f) * 2, ofz[i]); } } - ent->s.modelindex = G_ModelIndex( "models/map_objects/kejim/weaponsrack.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/kejim/weaponsrack.md3"); - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); ent->contents = CONTENTS_SOLID; - gi.linkentity( ent ); + gi.linkentity(ent); } -#define RACK_METAL_BOLTS 2 -#define RACK_ROCKETS 4 -#define RACK_WEAPONS 8 -#define RACK_HEALTH 16 -#define RACK_PWR_CELL 32 -#define RACK_NO_FILL 64 +#define RACK_METAL_BOLTS 2 +#define RACK_ROCKETS 4 +#define RACK_WEAPONS 8 +#define RACK_HEALTH 16 +#define RACK_PWR_CELL 32 +#define RACK_NO_FILL 64 /*QUAKED misc_model_ammo_rack (1 0 0.25) (-14 -14 -4) (14 14 30) BLASTER METAL_BOLTS ROCKETS WEAPON HEALTH PWR_CELL NO_FILL #MODELNAME="models/map_objects/kejim/weaponsrung.md3" -NOTE: can mix and match these spawnflags to get multi-ammo racks. If only one type is checked the rack will be full of that ammo. Only three ammo packs max can be displayed. +NOTE: can mix and match these spawnflags to get multi-ammo racks. If only one type is checked the rack will be full of that ammo. Only three ammo packs max +can be displayed. BLASTER - Adds one or more ammo packs that are compatible with Blasters and the Bryar pistol. @@ -501,216 +448,177 @@ PWR_CELL - Adds one or more power cell packs that are compatible with the Disupt NO_FILL - Only puts selected ammo on the rack, it never fills up all three slots if only one or two items were checked */ -extern gitem_t *FindItemForAmmo( ammo_t ammo ); +extern gitem_t *FindItemForAmmo(ammo_t ammo); //--------------------------------------------- -void SP_misc_model_ammo_rack( gentity_t *ent ) -{ -// If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_BLASTER )); +void SP_misc_model_ammo_rack(gentity_t *ent) { + // If BLASTER is checked...or nothing is checked then we'll do blasters + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_BLASTER)); } - RegisterItem( FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(FindItemForAmmo(AMMO_BLASTER)); } - if (( ent->spawnflags & RACK_METAL_BOLTS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_REPEATER )); + if ((ent->spawnflags & RACK_METAL_BOLTS)) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_REPEATER)); } - RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS )); + RegisterItem(FindItemForAmmo(AMMO_METAL_BOLTS)); } - if (( ent->spawnflags & RACK_ROCKETS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - RegisterItem( FindItemForWeapon( WP_ROCKET_LAUNCHER )); + if ((ent->spawnflags & RACK_ROCKETS)) { + if (ent->spawnflags & RACK_WEAPONS) { + RegisterItem(FindItemForWeapon(WP_ROCKET_LAUNCHER)); } - RegisterItem( FindItemForAmmo( AMMO_ROCKETS )); + RegisterItem(FindItemForAmmo(AMMO_ROCKETS)); } - if (( ent->spawnflags & RACK_PWR_CELL )) - { - RegisterItem( FindItemForAmmo( AMMO_POWERCELL )); + if ((ent->spawnflags & RACK_PWR_CELL)) { + RegisterItem(FindItemForAmmo(AMMO_POWERCELL)); } - if (( ent->spawnflags & RACK_HEALTH )) - { - RegisterItem( FindItem( "item_medpak_instant" )); + if ((ent->spawnflags & RACK_HEALTH)) { + RegisterItem(FindItem("item_medpak_instant")); } ent->e_ThinkFunc = thinkF_spawn_rack_goods; ent->nextthink = level.time + 100; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - ent->contents = CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//CONTENTS_SOLID;//so use traces can go through them + ent->contents = CONTENTS_SHOTCLIP | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; // CONTENTS_SOLID;//so use traces can go through them - gi.linkentity( ent ); + gi.linkentity(ent); } // AMMO RACK!! -void spawn_rack_goods( gentity_t *ent ) -{ - float v_off = 0; - gitem_t *blaster = NULL, *metal_bolts = NULL, *rockets = NULL, *it = NULL; - gitem_t *am_blaster = NULL, *am_metal_bolts = NULL, *am_rockets = NULL, *am_pwr_cell = NULL; - gitem_t *health = NULL; - int pos = 0, ct = 0; - gitem_t *itemList[4]; // allocating 4, but we only use 3. done so I don't have to validate that the array isn't full before I add another +void spawn_rack_goods(gentity_t *ent) { + float v_off = 0; + gitem_t *blaster = NULL, *metal_bolts = NULL, *rockets = NULL, *it = NULL; + gitem_t *am_blaster = NULL, *am_metal_bolts = NULL, *am_rockets = NULL, *am_pwr_cell = NULL; + gitem_t *health = NULL; + int pos = 0, ct = 0; + gitem_t *itemList[4]; // allocating 4, but we only use 3. done so I don't have to validate that the array isn't full before I add another - gi.unlinkentity( ent ); + gi.unlinkentity(ent); // If BLASTER is checked...or nothing is checked then we'll do blasters - if (( ent->spawnflags & RACK_BLASTER ) || !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - blaster = FindItemForWeapon( WP_BLASTER ); + if ((ent->spawnflags & RACK_BLASTER) || !(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { + if (ent->spawnflags & RACK_WEAPONS) { + blaster = FindItemForWeapon(WP_BLASTER); } - am_blaster = FindItemForAmmo( AMMO_BLASTER ); + am_blaster = FindItemForAmmo(AMMO_BLASTER); } - if (( ent->spawnflags & RACK_METAL_BOLTS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - metal_bolts = FindItemForWeapon( WP_REPEATER ); + if ((ent->spawnflags & RACK_METAL_BOLTS)) { + if (ent->spawnflags & RACK_WEAPONS) { + metal_bolts = FindItemForWeapon(WP_REPEATER); } - am_metal_bolts = FindItemForAmmo( AMMO_METAL_BOLTS ); + am_metal_bolts = FindItemForAmmo(AMMO_METAL_BOLTS); } - if (( ent->spawnflags & RACK_ROCKETS )) - { - if ( ent->spawnflags & RACK_WEAPONS ) - { - rockets = FindItemForWeapon( WP_ROCKET_LAUNCHER ); + if ((ent->spawnflags & RACK_ROCKETS)) { + if (ent->spawnflags & RACK_WEAPONS) { + rockets = FindItemForWeapon(WP_ROCKET_LAUNCHER); } - am_rockets = FindItemForAmmo( AMMO_ROCKETS ); + am_rockets = FindItemForAmmo(AMMO_ROCKETS); } - if (( ent->spawnflags & RACK_PWR_CELL )) - { - am_pwr_cell = FindItemForAmmo( AMMO_POWERCELL ); + if ((ent->spawnflags & RACK_PWR_CELL)) { + am_pwr_cell = FindItemForAmmo(AMMO_POWERCELL); } - if (( ent->spawnflags & RACK_HEALTH )) - { - health = FindItem( "item_medpak_instant" ); - RegisterItem( health ); + if ((ent->spawnflags & RACK_HEALTH)) { + health = FindItem("item_medpak_instant"); + RegisterItem(health); } //---------Ammo types - if ( am_blaster ) - { + if (am_blaster) { itemList[ct++] = am_blaster; } - if ( am_metal_bolts ) - { + if (am_metal_bolts) { itemList[ct++] = am_metal_bolts; } - if ( am_pwr_cell ) - { + if (am_pwr_cell) { itemList[ct++] = am_pwr_cell; } - if ( am_rockets ) - { + if (am_rockets) { itemList[ct++] = am_rockets; } - if ( !(ent->spawnflags & RACK_NO_FILL) && ct ) //double negative..should always have at least one item on there, but just being safe + if (!(ent->spawnflags & RACK_NO_FILL) && ct) // double negative..should always have at least one item on there, but just being safe { - for ( ; ct < 3 ; ct++ ) - { + for (; ct < 3; ct++) { itemList[ct] = itemList[0]; // first item ALWAYS propagates to fill up the shelf } } // now actually add the items to the shelf...validate that we have a list to add - if ( ct ) - { - for ( int i = 0; i < ct; i++ ) - { - GunRackAddItem( itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (i-1)* 8, 7.0f ); + if (ct) { + for (int i = 0; i < ct; i++) { + GunRackAddItem(itemList[i], ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (i - 1) * 8, 7.0f); } } // -----Weapon option - if ( ent->spawnflags & RACK_WEAPONS ) - { - if ( !(ent->spawnflags & ( RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL ))) - { + if (ent->spawnflags & RACK_WEAPONS) { + if (!(ent->spawnflags & (RACK_BLASTER | RACK_METAL_BOLTS | RACK_ROCKETS | RACK_PWR_CELL))) { // nothing was selected, so we assume blaster pack it = blaster; - } - else - { + } else { // if weapon is checked...and so are one or more ammo types, then pick a random weapon to display..always give weaker weapons first - if ( blaster ) - { + if (blaster) { it = blaster; v_off = 25.5f; - } - else if ( metal_bolts ) - { + } else if (metal_bolts) { it = metal_bolts; v_off = 27.0f; - } - else if ( rockets ) - { + } else if (rockets) { it = rockets; v_off = 28.0f; } } - if ( it ) - { + if (it) { // since we may have to put up a health pack on the shelf, we should know where we randomly put // the gun so we don't put the pack on the same spot..so pick either the left or right side - pos = ( Q_flrand(0.0f, 1.0f) > .5 ) ? -1 : 1; + pos = (Q_flrand(0.0f, 1.0f) > .5) ? -1 : 1; - GunRackAddItem( it, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, ( Q_flrand(0.0f, 1.0f) * 6 + 4 ) * pos, v_off ); + GunRackAddItem(it, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 2, (Q_flrand(0.0f, 1.0f) * 6 + 4) * pos, v_off); } } // ------Medpack - if (( ent->spawnflags & RACK_HEALTH ) && health ) - { - if ( !pos ) - { + if ((ent->spawnflags & RACK_HEALTH) && health) { + if (!pos) { // we haven't picked a side already... - pos = ( Q_flrand(0.0f, 1.0f) > .5 ) ? -1 : 1; - } - else - { + pos = (Q_flrand(0.0f, 1.0f) > .5) ? -1 : 1; + } else { // switch to the opposite side pos *= -1; } - GunRackAddItem( health, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, ( Q_flrand(0.0f, 1.0f) * 4 + 4 ) * pos, 24 ); + GunRackAddItem(health, ent->s.origin, ent->s.angles, Q_flrand(-1.0f, 1.0f) * 0.5f, (Q_flrand(0.0f, 1.0f) * 4 + 4) * pos, 24); } - ent->s.modelindex = G_ModelIndex( "models/map_objects/kejim/weaponsrung.md3" ); + ent->s.modelindex = G_ModelIndex("models/map_objects/kejim/weaponsrung.md3"); - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - gi.linkentity( ent ); + gi.linkentity(ent); } -#define DROP_MEDPACK 1 -#define DROP_SHIELDS 2 -#define DROP_BACTA 4 -#define DROP_BATTERIES 8 +#define DROP_MEDPACK 1 +#define DROP_SHIELDS 2 +#define DROP_BACTA 4 +#define DROP_BATTERIES 8 /*QUAKED misc_model_cargo_small (1 0 0.25) (-14 -14 -4) (14 14 30) MEDPACK SHIELDS BACTA BATTERIES #MODELNAME="models/map_objects/kejim/cargo_small.md3" @@ -727,110 +635,96 @@ BATTERIES - "splashDamage" - damage to do within explode range ( default 1 ) */ -extern gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, char *target ); +extern gentity_t *LaunchItem(gitem_t *item, vec3_t origin, vec3_t velocity, char *target); -void misc_model_cargo_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - int flags; - vec3_t org, temp; +void misc_model_cargo_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + int flags; + vec3_t org, temp; gitem_t *health = NULL, *shields = NULL, *bacta = NULL, *batteries = NULL; // copy these for later flags = self->spawnflags; - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); // we already had spawn flags, but we don't care what they were...we just need to set up the flags we want for misc_model_breakable_die self->spawnflags = 8; // NO_DMODEL // pass through to get the effects and such - misc_model_breakable_die( self, inflictor, attacker, damage, mod ); + misc_model_breakable_die(self, inflictor, attacker, damage, mod); // now that the model is broken, we can safely spawn these in it's place without them being in solid temp[2] = org[2] + 16; // annoying, but spawn each thing in its own little quadrant so that they don't end up on top of each other - if (( flags & DROP_MEDPACK )) - { - health = FindItem( "item_medpak_instant" ); + if ((flags & DROP_MEDPACK)) { + health = FindItem("item_medpak_instant"); - if ( health ) - { + if (health) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 + 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 + 16; - LaunchItem( health, temp, (float *)vec3_origin, NULL ); + LaunchItem(health, temp, (float *)vec3_origin, NULL); } } - if (( flags & DROP_SHIELDS )) - { - shields = FindItem( "item_shield_sm_instant" ); + if ((flags & DROP_SHIELDS)) { + shields = FindItem("item_shield_sm_instant"); - if ( shields ) - { + if (shields) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 - 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 + 16; - LaunchItem( shields, temp, (float *)vec3_origin, NULL ); + LaunchItem(shields, temp, (float *)vec3_origin, NULL); } } - if (( flags & DROP_BACTA )) - { - bacta = FindItem( "item_bacta" ); + if ((flags & DROP_BACTA)) { + bacta = FindItem("item_bacta"); - if ( bacta ) - { + if (bacta) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 - 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 - 16; - LaunchItem( bacta, temp, (float *)vec3_origin, NULL ); + LaunchItem(bacta, temp, (float *)vec3_origin, NULL); } } - if (( flags & DROP_BATTERIES )) - { - batteries = FindItem( "item_battery" ); + if ((flags & DROP_BATTERIES)) { + batteries = FindItem("item_battery"); - if ( batteries ) - { + if (batteries) { temp[0] = org[0] + Q_flrand(-1.0f, 1.0f) * 8 + 16; temp[1] = org[1] + Q_flrand(-1.0f, 1.0f) * 8 - 16; - LaunchItem( batteries, temp, (float *)vec3_origin, NULL ); + LaunchItem(batteries, temp, (float *)vec3_origin, NULL); } } } //--------------------------------------------- -void SP_misc_model_cargo_small( gentity_t *ent ) -{ - G_SpawnInt( "splashRadius", "96", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "1", &ent->splashDamage ); +void SP_misc_model_cargo_small(gentity_t *ent) { + G_SpawnInt("splashRadius", "96", &ent->splashRadius); + G_SpawnInt("splashDamage", "1", &ent->splashDamage); - if (( ent->spawnflags & DROP_MEDPACK )) - { - RegisterItem( FindItem( "item_medpak_instant" )); + if ((ent->spawnflags & DROP_MEDPACK)) { + RegisterItem(FindItem("item_medpak_instant")); } - if (( ent->spawnflags & DROP_SHIELDS )) - { - RegisterItem( FindItem( "item_shield_sm_instant" )); + if ((ent->spawnflags & DROP_SHIELDS)) { + RegisterItem(FindItem("item_shield_sm_instant")); } - if (( ent->spawnflags & DROP_BACTA )) - { - RegisterItem( FindItem( "item_bacta" )); + if ((ent->spawnflags & DROP_BACTA)) { + RegisterItem(FindItem("item_bacta")); } - if (( ent->spawnflags & DROP_BATTERIES )) - { - RegisterItem( FindItem( "item_battery" )); + if ((ent->spawnflags & DROP_BATTERIES)) { + RegisterItem(FindItem("item_battery")); } - G_SpawnInt( "health", "25", &ent->health ); + G_SpawnInt("health", "25", &ent->health); - SetMiscModelDefaults( ent, useF_NULL, "11", CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, 0, qtrue, qfalse ); - ent->s.modelindex2 = G_ModelIndex("/models/map_objects/kejim/cargo_small.md3"); // Precache model + SetMiscModelDefaults(ent, useF_NULL, "11", CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, 0, qtrue, qfalse); + ent->s.modelindex2 = G_ModelIndex("/models/map_objects/kejim/cargo_small.md3"); // Precache model // we only take damage from a heavy weapon class missile ent->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; @@ -839,4 +733,3 @@ void SP_misc_model_cargo_small( gentity_t *ent ) ent->radius = 1.5f; // scale number of chunks spawned } - diff --git a/codeJK2/game/g_missile.cpp b/codeJK2/game/g_missile.cpp index b340f302aa..e0de7c5be1 100644 --- a/codeJK2/game/g_missile.cpp +++ b/codeJK2/game/g_missile.cpp @@ -26,83 +26,73 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" #include "wp_saber.h" -#include "bg_local.h" - -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ); -extern qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInSpecialAttack( int anim ); +#include "bg_local.h" + +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +qboolean LogAccuracyHit(gentity_t *target, gentity_t *attacker); +extern qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInSpecialAttack(int anim); //------------------------------------------------------------------------- -void G_MissileBounceEffect( gentity_t *ent, vec3_t org, vec3_t dir ) -{ - //FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect - switch( ent->s.weapon ) - { +void G_MissileBounceEffect(gentity_t *ent, vec3_t org, vec3_t dir) { + // FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect + switch (ent->s.weapon) { case WP_BOWCASTER: - G_PlayEffect( "bowcaster/deflect", ent->currentOrigin, dir ); + G_PlayEffect("bowcaster/deflect", ent->currentOrigin, dir); break; case WP_BLASTER: case WP_BRYAR_PISTOL: - G_PlayEffect( "blaster/deflect", ent->currentOrigin, dir ); - break; - default: - { - gentity_t *tent = G_TempEntity( org, EV_GRENADE_BOUNCE ); - VectorCopy( dir, tent->pos1 ); - tent->s.weapon = ent->s.weapon; - } + G_PlayEffect("blaster/deflect", ent->currentOrigin, dir); break; + default: { + gentity_t *tent = G_TempEntity(org, EV_GRENADE_BOUNCE); + VectorCopy(dir, tent->pos1); + tent->s.weapon = ent->s.weapon; + } break; } } -void G_MissileReflectEffect( gentity_t *ent, vec3_t org, vec3_t dir ) -{ - //FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect - switch( ent->s.weapon ) - { +void G_MissileReflectEffect(gentity_t *ent, vec3_t org, vec3_t dir) { + // FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect + switch (ent->s.weapon) { case WP_BOWCASTER: - G_PlayEffect( "bowcaster/deflect", ent->currentOrigin, dir ); + G_PlayEffect("bowcaster/deflect", ent->currentOrigin, dir); break; case WP_BLASTER: case WP_BRYAR_PISTOL: default: - G_PlayEffect( "blaster/deflect", ent->currentOrigin, dir ); + G_PlayEffect("blaster/deflect", ent->currentOrigin, dir); break; } } //------------------------------------------------------------------------- -static void G_MissileStick( gentity_t *missile, gentity_t *other, trace_t *tr ) -{ - if ( other->NPC || !Q_stricmp( other->classname, "misc_model_breakable" )) - { +static void G_MissileStick(gentity_t *missile, gentity_t *other, trace_t *tr) { + if (other->NPC || !Q_stricmp(other->classname, "misc_model_breakable")) { // we bounce off of NPC's and misc model breakables because sticking to them requires too much effort vec3_t velocity; - int hitTime = level.previousTime + ( level.time - level.previousTime ) * tr->fraction; + int hitTime = level.previousTime + (level.time - level.previousTime) * tr->fraction; - EvaluateTrajectoryDelta( &missile->s.pos, hitTime, velocity ); + EvaluateTrajectoryDelta(&missile->s.pos, hitTime, velocity); - float dot = DotProduct( velocity, tr->plane.normal ); - G_SetOrigin( missile, tr->endpos ); - VectorMA( velocity, -1.6f * dot, tr->plane.normal, missile->s.pos.trDelta ); - VectorMA( missile->s.pos.trDelta, 10, tr->plane.normal, missile->s.pos.trDelta ); + float dot = DotProduct(velocity, tr->plane.normal); + G_SetOrigin(missile, tr->endpos); + VectorMA(velocity, -1.6f * dot, tr->plane.normal, missile->s.pos.trDelta); + VectorMA(missile->s.pos.trDelta, 10, tr->plane.normal, missile->s.pos.trDelta); missile->s.pos.trTime = level.time - 10; // move a bit on the first frame // check for stop - if ( tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_WORLD && - tr->plane.normal[2] > 0.7 && missile->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_WORLD && tr->plane.normal[2] > 0.7 && + missile->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { missile->nextthink = level.time + 100; - } - else - { + } else { // fall till we hit the ground missile->s.pos.trType = TR_GRAVITY; } @@ -110,15 +100,13 @@ static void G_MissileStick( gentity_t *missile, gentity_t *other, trace_t *tr ) return; // don't stick yet } - if ( missile->e_TouchFunc != touchF_NULL ) - { - GEntity_TouchFunc( missile, other, tr ); + if (missile->e_TouchFunc != touchF_NULL) { + GEntity_TouchFunc(missile, other, tr); } - G_AddEvent( missile, EV_MISSILE_STICK, 0 ); + G_AddEvent(missile, EV_MISSILE_STICK, 0); - if ( other->s.eType == ET_MOVER || other->e_DieFunc == dieF_funcBBrushDie || other->e_DieFunc == dieF_funcGlassDie) - { + if (other->s.eType == ET_MOVER || other->e_DieFunc == dieF_funcBBrushDie || other->e_DieFunc == dieF_funcGlassDie) { // movers and breakable brushes need extra info...so sticky missiles can ride lifts and blow up when the thing they are attached to goes away. missile->s.groundEntityNum = tr->entityNum; } @@ -131,155 +119,116 @@ G_ReflectMissile Reflect the missile roughly back at it's owner ================ */ -extern gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float minDot ); -void G_ReflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ) -{ - vec3_t bounce_dir; - int i; - float speed; +extern gentity_t *Jedi_FindEnemyInCone(gentity_t *self, gentity_t *fallback, float minDot); +void G_ReflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward) { + vec3_t bounce_dir; + int i; + float speed; qboolean reflected = qfalse; - gentity_t *owner = ent; + gentity_t *owner = ent; - if ( ent->owner ) - { + if (ent->owner) { owner = ent->owner; } - //save the original speed - speed = VectorNormalize( missile->s.pos.trDelta ); + // save the original speed + speed = VectorNormalize(missile->s.pos.trDelta); - if ( ent && owner && owner->client && !owner->client->ps.saberInFlight && - (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 || (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_1&&!Q_irand( 0, 3 )) ) ) - {//if high enough defense skill and saber in-hand (100% at level 3, 25% at level 2, 0% at level 1), reflections are perfectly deflected toward an enemy + if (ent && owner && owner->client && !owner->client->ps.saberInFlight && + (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 || + (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && + !Q_irand(0, 3)))) { // if high enough defense skill and saber in-hand (100% at level 3, 25% at level 2, 0% at level 1), reflections are perfectly + // deflected toward an enemy gentity_t *enemy; - if ( owner->enemy && Q_irand( 0, 3 ) ) - {//toward current enemy 75% of the time + if (owner->enemy && Q_irand(0, 3)) { // toward current enemy 75% of the time enemy = owner->enemy; + } else { // find another enemy + enemy = Jedi_FindEnemyInCone(owner, owner->enemy, 0.3f); } - else - {//find another enemy - enemy = Jedi_FindEnemyInCone( owner, owner->enemy, 0.3f ); - } - if ( enemy ) - { - vec3_t bullseye; - CalcEntitySpot( enemy, SPOT_HEAD, bullseye ); - bullseye[0] += Q_irand( -4, 4 ); - bullseye[1] += Q_irand( -4, 4 ); - bullseye[2] += Q_irand( -16, 4 ); - VectorSubtract( bullseye, missile->currentOrigin, bounce_dir ); - VectorNormalize( bounce_dir ); - if ( !PM_SaberInParry( owner->client->ps.saberMove ) - && !PM_SaberInReflect( owner->client->ps.saberMove ) - && !PM_SaberInIdle( owner->client->ps.saberMove ) ) - {//a bit more wild - if ( PM_SaberInAttack( owner->client->ps.saberMove ) - || PM_SaberInTransitionAny( owner->client->ps.saberMove ) - || PM_SaberInSpecialAttack( owner->client->ps.torsoAnim ) ) - {//moderately more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + if (enemy) { + vec3_t bullseye; + CalcEntitySpot(enemy, SPOT_HEAD, bullseye); + bullseye[0] += Q_irand(-4, 4); + bullseye[1] += Q_irand(-4, 4); + bullseye[2] += Q_irand(-16, 4); + VectorSubtract(bullseye, missile->currentOrigin, bounce_dir); + VectorNormalize(bounce_dir); + if (!PM_SaberInParry(owner->client->ps.saberMove) && !PM_SaberInReflect(owner->client->ps.saberMove) && + !PM_SaberInIdle(owner->client->ps.saberMove)) { // a bit more wild + if (PM_SaberInAttack(owner->client->ps.saberMove) || PM_SaberInTransitionAny(owner->client->ps.saberMove) || + PM_SaberInSpecialAttack(owner->client->ps.torsoAnim)) { // moderately more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } - } - else - {//mildly more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.1f, 0.1f ); + } else { // mildly more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.1f, 0.1f); } } } - VectorNormalize( bounce_dir ); + VectorNormalize(bounce_dir); reflected = qtrue; } } - if ( !reflected ) - { - if ( missile->owner && missile->s.weapon != WP_SABER ) - {//bounce back at them if you can - VectorSubtract( missile->owner->currentOrigin, missile->currentOrigin, bounce_dir ); - VectorNormalize( bounce_dir ); - } - else - { + if (!reflected) { + if (missile->owner && missile->s.weapon != WP_SABER) { // bounce back at them if you can + VectorSubtract(missile->owner->currentOrigin, missile->currentOrigin, bounce_dir); + VectorNormalize(bounce_dir); + } else { vec3_t missile_dir; - VectorSubtract( ent->currentOrigin, missile->currentOrigin, missile_dir ); - VectorCopy( missile->s.pos.trDelta, bounce_dir ); - VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); - VectorNormalize( bounce_dir ); + VectorSubtract(ent->currentOrigin, missile->currentOrigin, missile_dir); + VectorCopy(missile->s.pos.trDelta, bounce_dir); + VectorScale(bounce_dir, DotProduct(forward, missile_dir), bounce_dir); + VectorNormalize(bounce_dir); } - if ( owner->s.weapon == WP_SABER && owner->client ) - {//saber - if ( owner->client->ps.saberInFlight ) - {//reflecting off a thrown saber is totally wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.8f, 0.8f ); + if (owner->s.weapon == WP_SABER && owner->client) { // saber + if (owner->client->ps.saberInFlight) { // reflecting off a thrown saber is totally wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.8f, 0.8f); } - } - else if ( owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1 ) - {// at level 1 - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.4f, 0.4f ); + } else if (owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] <= FORCE_LEVEL_1) { // at level 1 + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.4f, 0.4f); } - } - else - {// at level 2 - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + } else { // at level 2 + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } } - if ( !PM_SaberInParry( owner->client->ps.saberMove ) - && !PM_SaberInReflect( owner->client->ps.saberMove ) - && !PM_SaberInIdle( owner->client->ps.saberMove ) ) - {//a bit more wild - if ( PM_SaberInAttack( owner->client->ps.saberMove ) - || PM_SaberInTransitionAny( owner->client->ps.saberMove ) - || PM_SaberInSpecialAttack( owner->client->ps.torsoAnim ) ) - {//really wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.3f, 0.3f ); + if (!PM_SaberInParry(owner->client->ps.saberMove) && !PM_SaberInReflect(owner->client->ps.saberMove) && + !PM_SaberInIdle(owner->client->ps.saberMove)) { // a bit more wild + if (PM_SaberInAttack(owner->client->ps.saberMove) || PM_SaberInTransitionAny(owner->client->ps.saberMove) || + PM_SaberInSpecialAttack(owner->client->ps.torsoAnim)) { // really wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.3f, 0.3f); } - } - else - {//mildly more wild - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.1f, 0.1f ); + } else { // mildly more wild + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.1f, 0.1f); } } } - } - else - {//some other kind of reflection - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += Q_flrand( -0.2f, 0.2f ); + } else { // some other kind of reflection + for (i = 0; i < 3; i++) { + bounce_dir[i] += Q_flrand(-0.2f, 0.2f); } } } - VectorNormalize( bounce_dir ); - VectorScale( bounce_dir, speed, missile->s.pos.trDelta ); + VectorNormalize(bounce_dir); + VectorScale(bounce_dir, speed, missile->s.pos.trDelta); #ifdef _DEBUG - assert( !Q_isnan(missile->s.pos.trDelta[0])&&!Q_isnan(missile->s.pos.trDelta[1])&&!Q_isnan(missile->s.pos.trDelta[2])); -#endif// _DEBUG - missile->s.pos.trTime = level.time - 10; // move a bit on the very first frame - VectorCopy( missile->currentOrigin, missile->s.pos.trBase ); - if ( missile->s.weapon != WP_SABER ) - {//you are mine, now! - if ( !missile->lastEnemy ) - {//remember who originally shot this missile + assert(!Q_isnan(missile->s.pos.trDelta[0]) && !Q_isnan(missile->s.pos.trDelta[1]) && !Q_isnan(missile->s.pos.trDelta[2])); +#endif // _DEBUG + missile->s.pos.trTime = level.time - 10; // move a bit on the very first frame + VectorCopy(missile->currentOrigin, missile->s.pos.trBase); + if (missile->s.weapon != WP_SABER) { // you are mine, now! + if (!missile->lastEnemy) { // remember who originally shot this missile missile->lastEnemy = missile->owner; } missile->owner = owner; } - if ( missile->s.weapon == WP_ROCKET_LAUNCHER ) - {//stop homing + if (missile->s.weapon == WP_ROCKET_LAUNCHER) { // stop homing missile->e_ThinkFunc = thinkF_NULL; } } @@ -290,58 +239,53 @@ G_BounceRollMissile ================ */ -void G_BounceRollMissile( gentity_t *ent, trace_t *trace ) -{ - vec3_t velocity, normal; - float dot, speedXY, velocityZ, normalZ; - int hitTime; +void G_BounceRollMissile(gentity_t *ent, trace_t *trace) { + vec3_t velocity, normal; + float dot, speedXY, velocityZ, normalZ; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - //Do horizontal - //FIXME: Need to roll up, down slopes + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + // Do horizontal + // FIXME: Need to roll up, down slopes velocityZ = velocity[2]; velocity[2] = 0; - speedXY = VectorLength( velocity );//friction - VectorCopy( trace->plane.normal, normal ); + speedXY = VectorLength(velocity); // friction + VectorCopy(trace->plane.normal, normal); normalZ = normal[2]; normal[2] = 0; - dot = DotProduct( velocity, normal ); - VectorMA( velocity, -2*dot, normal, ent->s.pos.trDelta ); - //now do the z reflection - //FIXME: Bobbles when it stops - VectorSet( velocity, 0, 0, velocityZ ); - VectorSet( normal, 0, 0, normalZ ); - dot = DotProduct( velocity, normal )*-1; - if ( dot > 10 ) - { - ent->s.pos.trDelta[2] = dot*0.3f;//not very bouncy - } - else - { + dot = DotProduct(velocity, normal); + VectorMA(velocity, -2 * dot, normal, ent->s.pos.trDelta); + // now do the z reflection + // FIXME: Bobbles when it stops + VectorSet(velocity, 0, 0, velocityZ); + VectorSet(normal, 0, 0, normalZ); + dot = DotProduct(velocity, normal) * -1; + if (dot > 10) { + ent->s.pos.trDelta[2] = dot * 0.3f; // not very bouncy + } else { ent->s.pos.trDelta[2] = 0; } // check for stop - if ( speedXY <= 0 ) - { - G_SetOrigin( ent, trace->endpos ); - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + if (speedXY <= 0) { + G_SetOrigin(ent, trace->endpos); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trType = TR_STATIONARY; return; } - //FIXME: rolling needs to match direction - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorCopy( ent->s.pos.trDelta, ent->s.apos.trDelta ); + // FIXME: rolling needs to match direction + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorCopy(ent->s.pos.trDelta, ent->s.apos.trDelta); - //remember this spot - VectorCopy( trace->endpos, ent->currentOrigin ); + // remember this spot + VectorCopy(trace->endpos, ent->currentOrigin); ent->s.pos.trTime = hitTime - 10; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - //VectorCopy( trace->plane.normal, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + // VectorCopy( trace->plane.normal, ent->pos1 ); } /* @@ -350,51 +294,44 @@ G_BounceMissile ================ */ -void G_BounceMissile( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceMissile(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); - if ( ent->s.eFlags & EF_BOUNCE_SHRAPNEL ) - { - VectorScale( ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta ); + if (ent->s.eFlags & EF_BOUNCE_SHRAPNEL) { + VectorScale(ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta); ent->s.pos.trType = TR_GRAVITY; // check for stop - if ( trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - G_SetOrigin( ent, trace->endpos ); + G_SetOrigin(ent, trace->endpos); ent->nextthink = level.time + 100; return; } - } - else if ( ent->s.eFlags & EF_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); + } else if (ent->s.eFlags & EF_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta); // check for stop - if ( trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - if ( ent->s.weapon == WP_THERMAL ) - {//roll when you "stop" + if (ent->s.weapon == WP_THERMAL) { // roll when you "stop" ent->s.pos.trType = TR_INTERPOLATE; - } - else - { - G_SetOrigin( ent, trace->endpos ); + } else { + G_SetOrigin(ent, trace->endpos); ent->nextthink = level.time + 500; return; } } - if ( ent->s.weapon == WP_THERMAL ) - { + if (ent->s.weapon == WP_THERMAL) { ent->has_bounced = qtrue; } } @@ -407,30 +344,24 @@ void G_BounceMissile( gentity_t *ent, trace_t *trace ) { #else // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... - VectorAdd( trace->endpos, trace->plane.normal, ent->currentOrigin ); - if ( hitTime >= level.time ) - {//trace fraction must have been 1 + VectorAdd(trace->endpos, trace->plane.normal, ent->currentOrigin); + if (hitTime >= level.time) { // trace fraction must have been 1 ent->s.pos.trTime = level.time - 10; - } - else - { + } else { ent->s.pos.trTime = hitTime - 10; // this is kinda dumb hacking, but it pushes the missile away from the impact plane a bit } #endif - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorCopy( trace->plane.normal, ent->pos1 ); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorCopy(trace->plane.normal, ent->pos1); - if ( ent->s.weapon != WP_SABER - && ent->s.weapon != WP_THERMAL - && ent->e_clThinkFunc != clThinkF_CG_Limb - && ent->e_ThinkFunc != thinkF_LimbThink ) - {//not a saber, bouncing thermal or limb - //now you can damage the guy you came from + if (ent->s.weapon != WP_SABER && ent->s.weapon != WP_THERMAL && ent->e_clThinkFunc != clThinkF_CG_Limb && + ent->e_ThinkFunc != thinkF_LimbThink) { // not a saber, bouncing thermal or limb + // now you can damage the guy you came from ent->owner = NULL; } } - + /* ================ G_MissileImpact @@ -438,76 +369,64 @@ G_MissileImpact ================ */ -extern void WP_SaberBlock( gentity_t *saber, vec3_t hitloc, qboolean missleBlock ); -extern void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ); -extern qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ); -void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc=HL_NONE ) -{ +extern void WP_SaberBlock(gentity_t *saber, vec3_t hitloc, qboolean missleBlock); +extern void laserTrapStick(gentity_t *ent, vec3_t endpos, vec3_t normal); +extern qboolean W_AccuracyLoggableWeapon(int weapon, qboolean alt_fire, int mod); +void G_MissileImpacted(gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc = HL_NONE) { // impact damage - if ( other->takedamage ) - { + if (other->takedamage) { // FIXME: wrong damage direction? - if ( ent->damage ) - { - vec3_t velocity; + if (ent->damage) { + vec3_t velocity; - EvaluateTrajectoryDelta( &ent->s.pos, level.time, velocity ); - if ( VectorLength( velocity ) == 0 ) - { - velocity[2] = 1; // stepped on a grenade + EvaluateTrajectoryDelta(&ent->s.pos, level.time, velocity); + if (VectorLength(velocity) == 0) { + velocity[2] = 1; // stepped on a grenade } int damage = ent->damage; - if( other->client ) - { - class_t npc_class = other->client->NPC_class; + if (other->client) { + class_t npc_class = other->client->NPC_class; // If we are a robot and we aren't currently doing the full body electricity... - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || //npc_class == CLASS_PROTOCOL ||//no protocol, looks odd - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || npc_class == CLASS_MARK1 || + npc_class == CLASS_MARK2 || // npc_class == CLASS_PROTOCOL ||//no protocol, looks odd + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { // special droid only behaviors - if ( other->client->ps.powerups[PW_SHOCKED] < level.time + 100 ) - { + if (other->client->ps.powerups[PW_SHOCKED] < level.time + 100) { // ... do the effect for a split second for some more feedback - other->s.powerups |= ( 1 << PW_SHOCKED ); + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = level.time + 450; } - //FIXME: throw some sparks off droids,too + // FIXME: throw some sparks off droids,too } } - G_Damage( other, ent, ent->owner, velocity, - impactPos, damage, - ent->dflags, ent->methodOfDeath, hitLoc); + G_Damage(other, ent, ent->owner, velocity, impactPos, damage, ent->dflags, ent->methodOfDeath, hitLoc); } } // is it cheaper in bandwidth to just remove this ent and create a new // one, rather than changing the missile into the explosion? - //G_FreeEntity(ent); - - if ( (other->takedamage && other->client ) || (ent->s.weapon == WP_FLECHETTE && other->contents&CONTENTS_LIGHTSABER) ) - { - G_AddEvent( ent, EV_MISSILE_HIT, DirToByte( normal ) ); + // G_FreeEntity(ent); + + if ((other->takedamage && other->client) || (ent->s.weapon == WP_FLECHETTE && other->contents & CONTENTS_LIGHTSABER)) { + G_AddEvent(ent, EV_MISSILE_HIT, DirToByte(normal)); ent->s.otherEntityNum = other->s.number; - } - else - { - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( normal ) ); + } else { + G_AddEvent(ent, EV_MISSILE_MISS, DirToByte(normal)); ent->s.otherEntityNum = other->s.number; } - VectorCopy( normal, ent->pos1 ); + VectorCopy(normal, ent->pos1); - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - AddSoundEvent( ent->owner, ent->currentOrigin, 256, AEL_SUSPICIOUS ); - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75 ); + // Add the event + AddSoundEvent(ent->owner, ent->currentOrigin, 256, AEL_SUSPICIOUS); + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75); } ent->freeAfterEvent = qtrue; @@ -515,97 +434,74 @@ void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3 // change over to a normal entity right at the point of impact ent->s.eType = ET_GENERAL; - //SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth - VectorCopy( impactPos, ent->s.pos.trBase ); + // SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth + VectorCopy(impactPos, ent->s.pos.trBase); - G_SetOrigin( ent, impactPos ); + G_SetOrigin(ent, impactPos); // splash damage (doesn't apply to person directly hit) - if ( ent->splashDamage ) - { - G_RadiusDamage( impactPos, ent->owner, ent->splashDamage, ent->splashRadius, - other, ent->splashMethodOfDeath ); + if (ent->splashDamage) { + G_RadiusDamage(impactPos, ent->owner, ent->splashDamage, ent->splashRadius, other, ent->splashMethodOfDeath); } - gi.linkentity( ent ); + gi.linkentity(ent); } //------------------------------------------------ -static void G_MissileAddAlerts( gentity_t *ent ) -{ - //Add the event - if ( ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY ) - { - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, 20 ); - } - else - { - AddSoundEvent( ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED ); - AddSightEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 40 ); +static void G_MissileAddAlerts(gentity_t *ent) { + // Add the event + if (ent->s.weapon == WP_THERMAL && ent->s.pos.trType == TR_STATIONARY) { + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DANGER, 20); + } else { + AddSoundEvent(ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED); + AddSightEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 40); } } //------------------------------------------------------ -void G_MissileImpact( gentity_t *ent, trace_t *trace, int hitLoc=HL_NONE ) -{ - gentity_t *other; - vec3_t diff; +void G_MissileImpact(gentity_t *ent, trace_t *trace, int hitLoc = HL_NONE) { + gentity_t *other; + vec3_t diff; other = &g_entities[trace->entityNum]; - if ( other == ent ) - { - assert(0&&"missile hit itself!!!"); + if (other == ent) { + assert(0 && "missile hit itself!!!"); return; } - if ( trace->plane.normal[0] == 0.0f && - trace->plane.normal[1] == 0.0f && - trace->plane.normal[2] == 0.0f - ) - {//model moved into missile in flight probably... + if (trace->plane.normal[0] == 0.0f && trace->plane.normal[1] == 0.0f && trace->plane.normal[2] == 0.0f) { // model moved into missile in flight probably... trace->plane.normal[0] = -ent->s.pos.trDelta[0]; trace->plane.normal[1] = -ent->s.pos.trDelta[1]; trace->plane.normal[2] = -ent->s.pos.trDelta[2]; VectorNormalize(trace->plane.normal); } - if ( ent->owner && (other->takedamage||other->client) ) - { - if ( !ent->lastEnemy || ent->lastEnemy == ent->owner ) - {//a missile that was not reflected or, if so, still is owned by original owner - if( LogAccuracyHit( other, ent->owner ) ) - { + if (ent->owner && (other->takedamage || other->client)) { + if (!ent->lastEnemy || ent->lastEnemy == ent->owner) { // a missile that was not reflected or, if so, still is owned by original owner + if (LogAccuracyHit(other, ent->owner)) { ent->owner->client->ps.persistant[PERS_ACCURACY_HITS]++; } - if ( ent->owner->client && !ent->owner->s.number ) - { - if ( W_AccuracyLoggableWeapon( ent->s.weapon, qfalse, ent->methodOfDeath ) ) - { + if (ent->owner->client && !ent->owner->s.number) { + if (W_AccuracyLoggableWeapon(ent->s.weapon, qfalse, ent->methodOfDeath)) { ent->owner->client->sess.missionStats.hits++; } } } } // check for bounce - //OR: if the surfaceParm is has a reflect property (magnetic shielding) and the missile isn't an exploding missile - qboolean bounce = (qboolean)( - (!other->takedamage && (ent->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF))) || - (((trace->surfaceFlags & SURF_FORCEFIELD) || (other->flags & FL_SHIELDED)) && - !ent->splashDamage && - !ent->splashRadius)); - - if ( ent->dflags & DAMAGE_HEAVY_WEAP_CLASS ) - { + // OR: if the surfaceParm is has a reflect property (magnetic shielding) and the missile isn't an exploding missile + qboolean bounce = (qboolean)((!other->takedamage && (ent->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF))) || + (((trace->surfaceFlags & SURF_FORCEFIELD) || (other->flags & FL_SHIELDED)) && !ent->splashDamage && !ent->splashRadius)); + + if (ent->dflags & DAMAGE_HEAVY_WEAP_CLASS) { // heavy class missiles generally never bounce. bounce = qfalse; } - if ( other->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED )) - { + if (other->flags & (FL_DMG_BY_HEAVY_WEAP_ONLY | FL_SHIELDED)) { // Dumb assumption, but I guess we must be a shielded ion_cannon?? We should probably verify // if it's an ion_cannon that's Heavy Weapon only, we don't want to make it shielded do we...? - if ( (!strcmp( "misc_ion_cannon", other->classname )) && (other->flags & FL_SHIELDED) ) - { + if ((!strcmp("misc_ion_cannon", other->classname)) && (other->flags & FL_SHIELDED)) { // Anything will bounce off of us. bounce = qtrue; @@ -614,153 +510,137 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace, int hitLoc=HL_NONE ) } } - if ( ent->s.weapon == WP_DEMP2 ) - { + if (ent->s.weapon == WP_DEMP2) { // demp2 shots can never bounce bounce = qfalse; // in fact, alt-charge shots will not call the regular impact functions - if ( ent->alt_fire ) - { + if (ent->alt_fire) { // detonate at the trace end - VectorCopy( trace->endpos, ent->currentOrigin ); - VectorCopy( trace->plane.normal, ent->pos1 ); - DEMP2_AltDetonate( ent ); + VectorCopy(trace->endpos, ent->currentOrigin); + VectorCopy(trace->plane.normal, ent->pos1); + DEMP2_AltDetonate(ent); return; } } - if ( bounce ) - { + if (bounce) { // Check to see if there is a bounce count - if ( ent->bounceCount ) - { + if (ent->bounceCount) { // decrement number of bounces and then see if it should be done bouncing - if ( !(--ent->bounceCount) ) { + if (!(--ent->bounceCount)) { // He (or she) will bounce no more (after this current bounce, that is). - ent->s.eFlags &= ~( EF_BOUNCE | EF_BOUNCE_HALF ); + ent->s.eFlags &= ~(EF_BOUNCE | EF_BOUNCE_HALF); } } - if ( other->NPC ) - { - G_Damage( other, ent, ent->owner, ent->currentOrigin, ent->s.pos.trDelta, 0, DAMAGE_NO_DAMAGE, MOD_UNKNOWN ); + if (other->NPC) { + G_Damage(other, ent, ent->owner, ent->currentOrigin, ent->s.pos.trDelta, 0, DAMAGE_NO_DAMAGE, MOD_UNKNOWN); } - G_BounceMissile( ent, trace ); - - if ( ent->owner )//&& ent->owner->s.number == 0 ) + G_BounceMissile(ent, trace); + + if (ent->owner) //&& ent->owner->s.number == 0 ) { - G_MissileAddAlerts( ent ); + G_MissileAddAlerts(ent); } - G_MissileBounceEffect( ent, trace->endpos, trace->plane.normal ); + G_MissileBounceEffect(ent, trace->endpos, trace->plane.normal); return; } - - // I would glom onto the EF_BOUNCE code section above, but don't feel like risking breaking something else - if ( (!other->takedamage && ( ent->s.eFlags&(EF_BOUNCE_SHRAPNEL) ) ) - || ((trace->surfaceFlags&SURF_FORCEFIELD)&&!ent->splashDamage&&!ent->splashRadius) ) - { - if ( !(other->contents&CONTENTS_LIGHTSABER) - || g_spskill->integer <= 0//on easy, it reflects all shots - || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 )//on medium it won't reflect flechette or demp shots - || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && ent->s.weapon != WP_REPEATER )//on hard it won't reflect flechette, demp, repeater or bowcaster shots - ) - { - G_BounceMissile( ent, trace ); - if ( --ent->bounceCount < 0 ) - { + // I would glom onto the EF_BOUNCE code section above, but don't feel like risking breaking something else + if ((!other->takedamage && (ent->s.eFlags & (EF_BOUNCE_SHRAPNEL))) || + ((trace->surfaceFlags & SURF_FORCEFIELD) && !ent->splashDamage && !ent->splashRadius)) { + if (!(other->contents & CONTENTS_LIGHTSABER) || g_spskill->integer <= 0 // on easy, it reflects all shots + || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2) // on medium it won't reflect flechette or demp shots + || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && + ent->s.weapon != WP_REPEATER) // on hard it won't reflect flechette, demp, repeater or bowcaster shots + ) { + G_BounceMissile(ent, trace); + + if (--ent->bounceCount < 0) { ent->s.eFlags &= ~EF_BOUNCE_SHRAPNEL; } - G_MissileBounceEffect( ent, trace->endpos, trace->plane.normal ); + G_MissileBounceEffect(ent, trace->endpos, trace->plane.normal); return; } } - if ( (!other->takedamage || (other->client && other->health <= 0)) - && ent->s.weapon == WP_THERMAL - && !ent->alt_fire ) - {//rolling thermal det - FIXME: make this an eFlag like bounce & stick!!! - //G_BounceRollMissile( ent, trace ); - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if ((!other->takedamage || (other->client && other->health <= 0)) && ent->s.weapon == WP_THERMAL && + !ent->alt_fire) { // rolling thermal det - FIXME: make this an eFlag like bounce & stick!!! + // G_BounceRollMissile( ent, trace ); + if (ent->owner) //&& ent->owner->s.number == 0 ) { - G_MissileAddAlerts( ent ); + G_MissileAddAlerts(ent); } - //gi.linkentity( ent ); + // gi.linkentity( ent ); return; } // check for sticking - if ( ent->s.eFlags & EF_MISSILE_STICK ) - { - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->s.eFlags & EF_MISSILE_STICK) { + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - if ( ent->s.weapon == WP_TRIP_MINE ) - { - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius/2, AEL_DISCOVERED/*AEL_DANGER*/ ); - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DISCOVERED/*AEL_DANGER*/, 60 ); + // Add the event + if (ent->s.weapon == WP_TRIP_MINE) { + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius / 2, AEL_DISCOVERED /*AEL_DANGER*/); + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius * 2, AEL_DISCOVERED /*AEL_DANGER*/, 60); /* AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER, 60 ); */ - } - else - { - AddSoundEvent( ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED ); - AddSightEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 10 ); + } else { + AddSoundEvent(ent->owner, ent->currentOrigin, 128, AEL_DISCOVERED); + AddSightEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED, 10); } } - G_MissileStick( ent, other, trace ); + G_MissileStick(ent, other, trace); return; } // check for hitting a lightsaber - if ( other->contents & CONTENTS_LIGHTSABER ) - { - if ( other->owner && !other->owner->s.number && other->owner->client ) - { + if (other->contents & CONTENTS_LIGHTSABER) { + if (other->owner && !other->owner->s.number && other->owner->client) { other->owner->client->sess.missionStats.saberBlocksCnt++; } - if ( ( g_spskill->integer <= 0//on easy, it reflects all shots - || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 )//on medium it won't reflect flechette or demp shots - || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && ent->s.weapon != WP_REPEATER )//on hard it won't reflect flechette, demp, repeater or bowcaster shots - ) - && (!ent->splashDamage || !ent->splashRadius) )//this would be cool, though, to "bat" the thermal det away... - { - //FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? - if ( !other->owner || !other->owner->client || other->owner->client->ps.saberInFlight || InFront( ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, SABER_REFLECT_MISSILE_CONE ) )//other->owner->s.number != 0 || - {//Jedi cannot block shots from behind! - if ( (other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && Q_irand( 0, 3 )) - ||(other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && Q_irand( 0, 1 ))) - {//level 1 reflects 50% of the time, level 2 reflects 75% of the time + if ((g_spskill->integer <= 0 // on easy, it reflects all shots + || (g_spskill->integer == 1 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2) // on medium it won't reflect flechette or demp shots + || (g_spskill->integer >= 2 && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_BOWCASTER && + ent->s.weapon != WP_REPEATER) // on hard it won't reflect flechette, demp, repeater or bowcaster shots + ) && + (!ent->splashDamage || !ent->splashRadius)) // this would be cool, though, to "bat" the thermal det away... + { + // FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? + if (!other->owner || !other->owner->client || other->owner->client->ps.saberInFlight || + InFront(ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, + SABER_REFLECT_MISSILE_CONE)) // other->owner->s.number != 0 || + { // Jedi cannot block shots from behind! + if ((other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && Q_irand(0, 3)) || + (other->owner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && + Q_irand(0, 1))) { // level 1 reflects 50% of the time, level 2 reflects 75% of the time VectorSubtract(ent->currentOrigin, other->currentOrigin, diff); VectorNormalize(diff); - //FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? - G_ReflectMissile( other, ent, diff); - //WP_SaberBlock( other, ent->currentOrigin, qtrue ); - if ( other->owner && other->owner->client ) - { + // FIXME: take other's owner's FP_SABER_DEFENSE into account here somehow? + G_ReflectMissile(other, ent, diff); + // WP_SaberBlock( other, ent->currentOrigin, qtrue ); + if (other->owner && other->owner->client) { other->owner->client->ps.saberEventFlags |= SEF_DEFLECTED; } - //do the effect - VectorCopy( ent->s.pos.trDelta, diff ); - VectorNormalize( diff ); - G_MissileReflectEffect( ent, trace->endpos, trace->plane.normal ); + // do the effect + VectorCopy(ent->s.pos.trDelta, diff); + VectorNormalize(diff); + G_MissileReflectEffect(ent, trace->endpos, trace->plane.normal); return; } } - } - else - {//still do the bounce effect - G_MissileReflectEffect( ent, trace->endpos, trace->plane.normal ); + } else { // still do the bounce effect + G_MissileReflectEffect(ent, trace->endpos, trace->plane.normal); } } - G_MissileImpacted( ent, other, trace->endpos, trace->plane.normal, hitLoc ); + G_MissileImpacted(ent, other, trace->endpos, trace->plane.normal, hitLoc); } /* @@ -770,60 +650,53 @@ G_ExplodeMissile Explode a missile without an impact ================ */ -void G_ExplodeMissile( gentity_t *ent ) -{ - vec3_t dir; - vec3_t origin; +void G_ExplodeMissile(gentity_t *ent) { + vec3_t dir; + vec3_t origin; - EvaluateTrajectory( &ent->s.pos, level.time, origin ); - SnapVector( origin ); - G_SetOrigin( ent, origin ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); + SnapVector(origin); + G_SetOrigin(ent, origin); // we don't have a valid direction, so just point straight up dir[0] = dir[1] = 0; dir[2] = 1; - if ( ent->owner )//&& ent->owner->s.number == 0 ) + if (ent->owner) //&& ent->owner->s.number == 0 ) { - //Add the event - AddSoundEvent( ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED ); - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 100 ); + // Add the event + AddSoundEvent(ent->owner, ent->currentOrigin, 256, AEL_DISCOVERED); + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 100); } -/* ent->s.eType = ET_GENERAL; - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); + /* ent->s.eType = ET_GENERAL; + G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); - ent->freeAfterEvent = qtrue;*/ + ent->freeAfterEvent = qtrue;*/ // splash damage - if ( ent->splashDamage ) - { - G_RadiusDamage( ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL - , ent->splashMethodOfDeath ); + if (ent->splashDamage) { + G_RadiusDamage(ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, ent->splashMethodOfDeath); } G_FreeEntity(ent); - //gi.linkentity( ent ); + // gi.linkentity( ent ); } - -void G_RunStuckMissile( gentity_t *ent ) -{ - if ( ent->takedamage ) - { - if ( ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD ) - { +void G_RunStuckMissile(gentity_t *ent) { + if (ent->takedamage) { + if (ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD) { gentity_t *other = &g_entities[ent->s.groundEntityNum]; - if ( (!VectorCompare( vec3_origin, other->s.pos.trDelta ) && other->s.pos.trType != TR_STATIONARY) || - (!VectorCompare( vec3_origin, other->s.apos.trDelta ) && other->s.apos.trType != TR_STATIONARY) ) - {//thing I stuck to is moving or rotating now, kill me - G_Damage( ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH ); + if ((!VectorCompare(vec3_origin, other->s.pos.trDelta) && other->s.pos.trType != TR_STATIONARY) || + (!VectorCompare(vec3_origin, other->s.apos.trDelta) && + other->s.apos.trType != TR_STATIONARY)) { // thing I stuck to is moving or rotating now, kill me + G_Damage(ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH); return; } } } // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -833,45 +706,40 @@ G_GroundTrace ================== */ -int G_GroundTrace( gentity_t *ent, pml_t *pPml ) -{ - vec3_t point; - trace_t trace; +int G_GroundTrace(gentity_t *ent, pml_t *pPml) { + vec3_t point; + trace_t trace; point[0] = ent->currentOrigin[0]; point[1] = ent->currentOrigin[1]; point[2] = ent->currentOrigin[2] - 0.25; - gi.trace ( &trace, ent->currentOrigin, ent->mins, ent->maxs, point, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, point, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0); pPml->groundTrace = trace; // do something corrective if the trace starts in a solid... - if ( trace.allsolid ) - { + if (trace.allsolid) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } // if the trace didn't hit anything, we are in free fall - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } // check if getting thrown off the ground - if ( ent->s.pos.trDelta[2] > 0 && DotProduct( ent->s.pos.trDelta, trace.plane.normal ) > 10 ) - { + if (ent->s.pos.trDelta[2] > 0 && DotProduct(ent->s.pos.trDelta, trace.plane.normal) > 10) { pPml->groundPlane = qfalse; pPml->walking = qfalse; return ENTITYNUM_NONE; } - + // slopes that are too steep will not be considered onground - if ( trace.plane.normal[2] < MIN_WALK_NORMAL ) - { + if (trace.plane.normal[2] < MIN_WALK_NORMAL) { pPml->groundPlane = qtrue; pPml->walking = qfalse; return ENTITYNUM_NONE; @@ -881,7 +749,7 @@ int G_GroundTrace( gentity_t *ent, pml_t *pPml ) pPml->walking = qtrue; /* - if ( ent->s.groundEntityNum == ENTITYNUM_NONE ) + if ( ent->s.groundEntityNum == ENTITYNUM_NONE ) { // just hit the ground } @@ -895,69 +763,64 @@ int G_GroundTrace( gentity_t *ent, pml_t *pPml ) G_RollMissile -reworking the rolling object code, -still needs to stop bobbling up & down, -need to get roll angles right, -and need to maybe make the transfer of velocity happen on impacts? -Also need bounce sound for bounces off a floor. +reworking the rolling object code, +still needs to stop bobbling up & down, +need to get roll angles right, +and need to maybe make the transfer of velocity happen on impacts? +Also need bounce sound for bounces off a floor. Also need to not bounce as much off of enemies Also gets stuck inside thrower if looking down when thrown ================== */ -#define MAX_CLIP_PLANES 5 -#define BUMPCLIP 1.5f -void G_RollMissile( gentity_t *ent ) -{ - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity; - vec3_t clipVelocity; - int i, j, k; - trace_t trace; - vec3_t end; - float time_left; - float into; - vec3_t endVelocity; - vec3_t endClipVelocity; - pml_t objPML; - float bounceAmt = BUMPCLIP; - gentity_t *hitEnt = NULL; - - memset( &objPML, 0, sizeof( objPML ) ); - - G_GroundTrace( ent, &objPML ); - - objPML.frametime = (level.time - level.previousTime)*0.001; - +#define MAX_CLIP_PLANES 5 +#define BUMPCLIP 1.5f +void G_RollMissile(gentity_t *ent) { + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity; + vec3_t clipVelocity; + int i, j, k; + trace_t trace; + vec3_t end; + float time_left; + float into; + vec3_t endVelocity; + vec3_t endClipVelocity; + pml_t objPML; + float bounceAmt = BUMPCLIP; + gentity_t *hitEnt = NULL; + + memset(&objPML, 0, sizeof(objPML)); + + G_GroundTrace(ent, &objPML); + + objPML.frametime = (level.time - level.previousTime) * 0.001; + numbumps = 4; - VectorCopy ( ent->s.pos.trDelta, primal_velocity ); + VectorCopy(ent->s.pos.trDelta, primal_velocity); - VectorCopy( ent->s.pos.trDelta, endVelocity ); + VectorCopy(ent->s.pos.trDelta, endVelocity); endVelocity[2] -= g_gravity->value * objPML.frametime; - ent->s.pos.trDelta[2] = ( ent->s.pos.trDelta[2] + endVelocity[2] ) * 0.5; + ent->s.pos.trDelta[2] = (ent->s.pos.trDelta[2] + endVelocity[2]) * 0.5; primal_velocity[2] = endVelocity[2]; - if ( objPML.groundPlane ) - {//FIXME: never happens! + if (objPML.groundPlane) { // FIXME: never happens! // slide along the ground plane - PM_ClipVelocity( ent->s.pos.trDelta, objPML.groundTrace.plane.normal, ent->s.pos.trDelta, BUMPCLIP ); - VectorScale( ent->s.pos.trDelta, 0.9f, ent->s.pos.trDelta ); + PM_ClipVelocity(ent->s.pos.trDelta, objPML.groundTrace.plane.normal, ent->s.pos.trDelta, BUMPCLIP); + VectorScale(ent->s.pos.trDelta, 0.9f, ent->s.pos.trDelta); } time_left = objPML.frametime; // never turn against the ground plane - if ( objPML.groundPlane ) - { + if (objPML.groundPlane) { numplanes = 1; - VectorCopy( objPML.groundTrace.plane.normal, planes[0] ); - } - else - { + VectorCopy(objPML.groundTrace.plane.normal, planes[0]); + } else { numplanes = 0; } @@ -967,55 +830,48 @@ void G_RollMissile( gentity_t *ent ) numplanes++; */ - for ( bumpcount = 0; bumpcount < numbumps; bumpcount++ ) - { + for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { // calculate position we are trying to move to - VectorMA( ent->currentOrigin, time_left, ent->s.pos.trDelta, end ); + VectorMA(ent->currentOrigin, time_left, ent->s.pos.trDelta, end); // see if we can make it there - gi.trace ( &trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10 ); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, end, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10); - //TEMP HACK: - //had to move this up above the trace.allsolid check now that for some reason ghoul2 impacts tell me I'm allsolid?! - //this needs to be fixed, really - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit another ent + // TEMP HACK: + // had to move this up above the trace.allsolid check now that for some reason ghoul2 impacts tell me I'm allsolid?! + // this needs to be fixed, really + if (trace.entityNum < ENTITYNUM_WORLD) { // hit another ent hitEnt = &g_entities[trace.entityNum]; - if ( hitEnt && (hitEnt->takedamage || (hitEnt->contents&CONTENTS_LIGHTSABER) ) ) - { - G_MissileImpact( ent, &trace ); - if ( ent->s.eType == ET_GENERAL ) - {//exploded + if (hitEnt && (hitEnt->takedamage || (hitEnt->contents & CONTENTS_LIGHTSABER))) { + G_MissileImpact(ent, &trace); + if (ent->s.eType == ET_GENERAL) { // exploded return; } } } - if ( trace.allsolid ) - { + if (trace.allsolid) { // entity is completely trapped in another solid - //FIXME: this happens a lot now when we hit a G2 ent... WTF? - ent->s.pos.trDelta[2] = 0; // don't build up falling damage, but allow sideways acceleration - return;// qtrue; + // FIXME: this happens a lot now when we hit a G2 ent... WTF? + ent->s.pos.trDelta[2] = 0; // don't build up falling damage, but allow sideways acceleration + return; // qtrue; } - if ( trace.fraction > 0 ) - { + if (trace.fraction > 0) { // actually covered some distance - VectorCopy( trace.endpos, ent->currentOrigin ); + VectorCopy(trace.endpos, ent->currentOrigin); } - if ( trace.fraction == 1 ) - { - break; // moved the entire distance + if (trace.fraction == 1) { + break; // moved the entire distance } - //pm->ps->pm_flags |= PMF_BUMPED; + // pm->ps->pm_flags |= PMF_BUMPED; // save entity for contact - //PM_AddTouchEnt( trace.entityNum ); + // PM_AddTouchEnt( trace.entityNum ); - //Hit it + // Hit it /* if ( PM_ClientImpact( trace.entityNum, qtrue ) ) { @@ -1025,11 +881,10 @@ void G_RollMissile( gentity_t *ent ) time_left -= time_left * trace.fraction; - if ( numplanes >= MAX_CLIP_PLANES ) - { + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen - VectorClear( ent->s.pos.trDelta ); - return;// qtrue; + VectorClear(ent->s.pos.trDelta); + return; // qtrue; } // @@ -1037,124 +892,108 @@ void G_RollMissile( gentity_t *ent ) // out along it, which fixes some epsilon issues with // non-axial planes // - for ( i = 0 ; i < numplanes ; i++ ) - { - if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) - { - VectorAdd( trace.plane.normal, ent->s.pos.trDelta, ent->s.pos.trDelta ); + for (i = 0; i < numplanes; i++) { + if (DotProduct(trace.plane.normal, planes[i]) > 0.99) { + VectorAdd(trace.plane.normal, ent->s.pos.trDelta, ent->s.pos.trDelta); break; } } - if ( i < numplanes ) - { + if (i < numplanes) { continue; } - VectorCopy( trace.plane.normal, planes[numplanes] ); + VectorCopy(trace.plane.normal, planes[numplanes]); numplanes++; // // modify velocity so it parallels all of the clip planes // - if ( g_entities[trace.entityNum].inuse && g_entities[trace.entityNum].client ) - {//hit a person, bounce off much less + if (g_entities[trace.entityNum].inuse && g_entities[trace.entityNum].client) { // hit a person, bounce off much less bounceAmt = OVERCLIP; - } - else - { + } else { bounceAmt = BUMPCLIP; } // find a plane that it enters - for ( i = 0 ; i < numplanes ; i++ ) - { - into = DotProduct( ent->s.pos.trDelta, planes[i] ); - if ( into >= 0.1 ) - { - continue; // move doesn't interact with the plane + for (i = 0; i < numplanes; i++) { + into = DotProduct(ent->s.pos.trDelta, planes[i]); + if (into >= 0.1) { + continue; // move doesn't interact with the plane } // see how hard we are hitting things - if ( -into > pml.impactSpeed ) - { + if (-into > pml.impactSpeed) { pml.impactSpeed = -into; } // slide along the plane - PM_ClipVelocity( ent->s.pos.trDelta, planes[i], clipVelocity, bounceAmt ); + PM_ClipVelocity(ent->s.pos.trDelta, planes[i], clipVelocity, bounceAmt); // slide along the plane - PM_ClipVelocity( endVelocity, planes[i], endClipVelocity, bounceAmt ); + PM_ClipVelocity(endVelocity, planes[i], endClipVelocity, bounceAmt); // see if there is a second plane that the new move enters - for ( j = 0 ; j < numplanes ; j++ ) - { - if ( j == i ) - { + for (j = 0; j < numplanes; j++) { + if (j == i) { continue; } - if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) - { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[j]) >= 0.1) { + continue; // move doesn't interact with the plane } // try clipping the move to the plane - PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, bounceAmt ); - PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, bounceAmt ); + PM_ClipVelocity(clipVelocity, planes[j], clipVelocity, bounceAmt); + PM_ClipVelocity(endClipVelocity, planes[j], endClipVelocity, bounceAmt); // see if it goes back into the first clip plane - if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) - { + if (DotProduct(clipVelocity, planes[i]) >= 0) { continue; } // slide the original velocity along the crease - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, ent->s.pos.trDelta ); - VectorScale( dir, d, clipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, ent->s.pos.trDelta); + VectorScale(dir, d, clipVelocity); - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, endVelocity ); - VectorScale( dir, d, endClipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, endVelocity); + VectorScale(dir, d, endClipVelocity); // see if there is a third plane the the new move enters - for ( k = 0 ; k < numplanes ; k++ ) - { - if ( k == i || k == j ) - { + for (k = 0; k < numplanes; k++) { + if (k == i || k == j) { continue; } - if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) - { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[k]) >= 0.1) { + continue; // move doesn't interact with the plane } // stop dead at a triple plane interaction - VectorClear( ent->s.pos.trDelta ); - return;// qtrue; + VectorClear(ent->s.pos.trDelta); + return; // qtrue; } } // if we have fixed all interactions, try another move - VectorCopy( clipVelocity, ent->s.pos.trDelta ); - VectorCopy( endClipVelocity, endVelocity ); + VectorCopy(clipVelocity, ent->s.pos.trDelta); + VectorCopy(endClipVelocity, endVelocity); break; } - VectorScale( endVelocity, 0.975f, endVelocity ); + VectorScale(endVelocity, 0.975f, endVelocity); } - VectorCopy( endVelocity, ent->s.pos.trDelta ); + VectorCopy(endVelocity, ent->s.pos.trDelta); // don't change velocity if in a timer (FIXME: is this correct?) /* - if ( pm->ps->pm_time ) + if ( pm->ps->pm_time ) { VectorCopy( primal_velocity, ent->s.pos.trDelta ); } */ - return;// ( bumpcount != 0 ); + return; // ( bumpcount != 0 ); } /* ================ @@ -1162,82 +1001,74 @@ G_RunMissile ================ */ -void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); -void G_RunMissile( gentity_t *ent ) -{ - vec3_t origin, oldOrg; - trace_t tr; - int trHitLoc=HL_NONE; +void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg); +void G_RunMissile(gentity_t *ent) { + vec3_t origin, oldOrg; + trace_t tr; + int trHitLoc = HL_NONE; - VectorCopy( ent->currentOrigin, oldOrg ); + VectorCopy(ent->currentOrigin, oldOrg); // get current position - if ( ent->s.pos.trType == TR_INTERPOLATE ) - {//rolling missile? - //FIXME: WTF?!! Sticks to stick missiles? - //FIXME: they stick inside the player - G_RollMissile( ent ); - if ( ent->s.eType != ET_GENERAL ) - {//didn't explode - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - gi.trace( &tr, oldOrg, ent->mins, ent->maxs, ent->currentOrigin, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10 ); - if ( VectorCompare( ent->s.pos.trDelta, vec3_origin ) ) - { - //VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); - } - else - { - vec3_t ang, fwdDir, rtDir; - float speed; - + if (ent->s.pos.trType == TR_INTERPOLATE) { // rolling missile? + // FIXME: WTF?!! Sticks to stick missiles? + // FIXME: they stick inside the player + G_RollMissile(ent); + if (ent->s.eType != ET_GENERAL) { // didn't explode + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + gi.trace(&tr, oldOrg, ent->mins, ent->maxs, ent->currentOrigin, ent->s.number, ent->clipmask, G2_RETURNONHIT, 10); + if (VectorCompare(ent->s.pos.trDelta, vec3_origin)) { + // VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorClear(ent->s.apos.trDelta); + } else { + vec3_t ang, fwdDir, rtDir; + float speed; + ent->s.apos.trType = TR_INTERPOLATE; - VectorSet( ang, 0, ent->s.apos.trBase[1], 0 ); - AngleVectors( ang, fwdDir, rtDir, NULL ); - speed = VectorLength( ent->s.pos.trDelta )*4; + VectorSet(ang, 0, ent->s.apos.trBase[1], 0); + AngleVectors(ang, fwdDir, rtDir, NULL); + speed = VectorLength(ent->s.pos.trDelta) * 4; - //HMM, this works along an axis-aligned dir, but not along diagonals - //This is because when roll gets to 90, pitch becomes yaw, and vice-versa - //Maybe need to just set the angles directly? - ent->s.apos.trDelta[0] = DotProduct( fwdDir, ent->s.pos.trDelta ); - ent->s.apos.trDelta[1] = 0;//never spin! - ent->s.apos.trDelta[2] = DotProduct( rtDir, ent->s.pos.trDelta ); + // HMM, this works along an axis-aligned dir, but not along diagonals + // This is because when roll gets to 90, pitch becomes yaw, and vice-versa + // Maybe need to just set the angles directly? + ent->s.apos.trDelta[0] = DotProduct(fwdDir, ent->s.pos.trDelta); + ent->s.apos.trDelta[1] = 0; // never spin! + ent->s.apos.trDelta[2] = DotProduct(rtDir, ent->s.pos.trDelta); - VectorNormalize( ent->s.apos.trDelta ); - VectorScale( ent->s.apos.trDelta, speed, ent->s.apos.trDelta ); + VectorNormalize(ent->s.apos.trDelta); + VectorScale(ent->s.apos.trDelta, speed, ent->s.apos.trDelta); ent->s.apos.trTime = level.previousTime; } } - } - else - { - EvaluateTrajectory( &ent->s.pos, level.time, origin ); + } else { + EvaluateTrajectory(&ent->s.pos, level.time, origin); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner /* - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, + gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10 ); */ - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_COLLIDE, 10 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_COLLIDE, 10); /* if ( !VectorCompare( ent->mins, vec3_origin ) || !VectorCompare( ent->maxs, vec3_origin ) ) {//don't do ghoul trace if ent has size because g2 just ignores that anyway - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, + gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_NOCOLLIDE, 10 ); } else //Now we always do ghoul trace, regardless of bbox size of missile, this is presuming that non-point ghoul traces will be possible...? { - gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, + gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask, G2_RETURNONHIT, 10 ); } */ /* if ( tr.fraction == 0.0f && tr.plane.normal[2] == 1.0f && origin[2] < ent->currentOrigin[2] ) { - if ( ent->s.pos.trType == TR_GRAVITY && !(ent->s.eFlags&EF_BOUNCE) && !(ent->s.eFlags&EF_BOUNCE_HALF) && ent->s.weapon == WP_THERMAL )//FIXME: EF_ROLLING + if ( ent->s.pos.trType == TR_GRAVITY && !(ent->s.eFlags&EF_BOUNCE) && !(ent->s.eFlags&EF_BOUNCE_HALF) && ent->s.weapon == WP_THERMAL )//FIXME: + EF_ROLLING { //FIXME: Needs to stop sometime! ent->s.pos.trType = TR_LINEAR; @@ -1245,7 +1076,7 @@ void G_RunMissile( gentity_t *ent ) EvaluateTrajectory( &ent->s.pos, level.time, origin ); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, + gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ENTITYNUM_NONE, ent->clipmask | CONTENTS_GHOUL2 ); if ( tr.fraction == 1.0f ) { @@ -1258,121 +1089,115 @@ void G_RunMissile( gentity_t *ent ) } */ - if ( tr.entityNum != ENTITYNUM_NONE && &g_entities[tr.entityNum] != NULL ) - { + if (tr.entityNum != ENTITYNUM_NONE && &g_entities[tr.entityNum] != NULL) { gentity_t *other = &g_entities[tr.entityNum]; // check for hitting a lightsaber - if ( other->contents & CONTENTS_LIGHTSABER ) - {//hit a lightsaber bbox - if ( other->owner && other->owner->client && !other->owner->client->ps.saberInFlight && !InFront( ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, SABER_REFLECT_MISSILE_CONE ) )//other->owner->s.number == 0 && - {//Jedi cannot block shots from behind! - //re-trace from here, ignoring the lightsaber - gi.trace( &tr, tr.endpos, ent->mins, ent->maxs, origin, tr.entityNum, ent->clipmask, G2_RETURNONHIT, 10 ); + if (other->contents & CONTENTS_LIGHTSABER) { // hit a lightsaber bbox + if (other->owner && other->owner->client && !other->owner->client->ps.saberInFlight && + !InFront(ent->currentOrigin, other->owner->currentOrigin, other->owner->client->ps.viewangles, + SABER_REFLECT_MISSILE_CONE)) // other->owner->s.number == 0 && + { // Jedi cannot block shots from behind! + // re-trace from here, ignoring the lightsaber + gi.trace(&tr, tr.endpos, ent->mins, ent->maxs, origin, tr.entityNum, ent->clipmask, G2_RETURNONHIT, 10); } } } - VectorCopy( tr.endpos, ent->currentOrigin ); + VectorCopy(tr.endpos, ent->currentOrigin); } // get current angles - VectorMA( ent->s.apos.trBase, (level.time - ent->s.apos.trTime) * 0.001, ent->s.apos.trDelta, ent->s.apos.trBase ); + VectorMA(ent->s.apos.trBase, (level.time - ent->s.apos.trTime) * 0.001, ent->s.apos.trDelta, ent->s.apos.trBase); - //FIXME: Rolling things hitting G2 polys is weird + // FIXME: Rolling things hitting G2 polys is weird /////////////////////////////////////////////////////// -//? if ( tr.fraction != 1 ) + //? if ( tr.fraction != 1 ) { - // did we hit or go near a Ghoul2 model? -// qboolean hitModel = qfalse; - for (int i=0; i < MAX_G2_COLLISIONS; i++) - { - if (tr.G2CollisionMap[i].mEntityNum == -1) - { + // did we hit or go near a Ghoul2 model? + // qboolean hitModel = qfalse; + for (int i = 0; i < MAX_G2_COLLISIONS; i++) { + if (tr.G2CollisionMap[i].mEntityNum == -1) { break; } CCollisionRecord &coll = tr.G2CollisionMap[i]; - gentity_t *hitEnt = &g_entities[coll.mEntityNum]; - -/* Sorry...this was just getting in the way.... -#if _DEBUG - vec3_t delta; - VectorSubtract(origin, coll.mCollisionPosition, delta); - VectorNormalize(delta); - VectorScale(delta, 30, delta); - - if (coll.mFlags & G2_BACKFACE) - { - VectorAdd(delta, coll.mCollisionPosition, delta); - G_DebugLine(coll.mCollisionPosition, delta, 10000, 0x00ff0000, qtrue); - } - else - { - VectorSubtract(coll.mCollisionPosition, delta, delta); - G_DebugLine(coll.mCollisionPosition, delta, 10000, 0x0000ff00, qtrue); - } - -//loadsavecrash -// VectorCopy(hitEnt->mins, hitEnt->s.mins); -// VectorCopy(hitEnt->maxs, hitEnt->s.maxs); -#endif -*/ + gentity_t *hitEnt = &g_entities[coll.mEntityNum]; + + /* Sorry...this was just getting in the way.... + #if _DEBUG + vec3_t delta; + VectorSubtract(origin, coll.mCollisionPosition, delta); + VectorNormalize(delta); + VectorScale(delta, 30, delta); + + if (coll.mFlags & G2_BACKFACE) + { + VectorAdd(delta, coll.mCollisionPosition, delta); + G_DebugLine(coll.mCollisionPosition, delta, 10000, 0x00ff0000, qtrue); + } + else + { + VectorSubtract(coll.mCollisionPosition, delta, delta); + G_DebugLine(coll.mCollisionPosition, delta, 10000, 0x0000ff00, qtrue); + } + + //loadsavecrash + // VectorCopy(hitEnt->mins, hitEnt->s.mins); + // VectorCopy(hitEnt->maxs, hitEnt->s.maxs); + #endif + */ // process collision records here... // make sure we only do this once, not for all the entrance wounds we might generate - if ((coll.mFlags & G2_FRONTFACE)/* && !(hitModel)*/ && hitEnt->health) - { + if ((coll.mFlags & G2_FRONTFACE) /* && !(hitModel)*/ && hitEnt->health) { // create a new surface using the details of what poly/surface/model we hit -// int newSurface = gi.G2API_AddSurface(&hitEnt->ghoul2[coll.mModelIndex], coll.mSurfaceIndex, coll.mPolyIndex, coll.mBarycentricI, coll.mBarycentricJ, 10); -// surfaceInfo_t *newSuf = &hitEnt->ghoul2[coll.mModelIndex].mSlist[newSurface]; + // int newSurface = gi.G2API_AddSurface(&hitEnt->ghoul2[coll.mModelIndex], coll.mSurfaceIndex, coll.mPolyIndex, coll.mBarycentricI, + //coll.mBarycentricJ, 10); surfaceInfo_t *newSuf = &hitEnt->ghoul2[coll.mModelIndex].mSlist[newSurface]; // attach a bolt to this surface -// int newBolt = gi.G2API_AddBoltSurfNum(&hitEnt->ghoul2[coll.mModelIndex], newSurface); + // int newBolt = gi.G2API_AddBoltSurfNum(&hitEnt->ghoul2[coll.mModelIndex], newSurface); // now attach an effect to this new bolt -// Bolting on this effect just looks dumb and adds lots of unnecessary effects to the scene -// -// G_PlayEffect( G_EffectIndex( "blaster/smoke_bolton") , coll.mModelIndex, newBolt, hitEnt->s.number); -// -// + // Bolting on this effect just looks dumb and adds lots of unnecessary effects to the scene + // + // G_PlayEffect( G_EffectIndex( "blaster/smoke_bolton") , coll.mModelIndex, newBolt, hitEnt->s.number); + // + // -// G_SetBoltSurfaceRemoval(coll.mEntityNum, coll.mModelIndex, newBolt, newSurface, 10000); -// hitModel = qtrue; + // G_SetBoltSurfaceRemoval(coll.mEntityNum, coll.mModelIndex, newBolt, newSurface, 10000); + // hitModel = qtrue; - if (trHitLoc==HL_NONE) - { - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &trHitLoc, coll.mCollisionPosition, NULL, NULL, ent->methodOfDeath ); + if (trHitLoc == HL_NONE) { + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &trHitLoc, + coll.mCollisionPosition, NULL, NULL, ent->methodOfDeath); } break; // NOTE: the way this whole section was working, it would only get inside of this IF once anyway, might as well break out now } } } -///////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////// - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( ent ); + gi.linkentity(ent); - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//stuck missiles should check some special stuff - G_RunStuckMissile( ent ); + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // stuck missiles should check some special stuff + G_RunStuckMissile(ent); return; } // check think function - G_RunThink( ent ); + G_RunThink(ent); - if ( ent->s.eType != ET_MISSILE ) - { - return; // exploded + if (ent->s.eType != ET_MISSILE) { + return; // exploded } - if ( ent->mass ) - { - G_MoverTouchPushTriggers( ent, oldOrg ); + if (ent->mass) { + G_MoverTouchPushTriggers(ent, oldOrg); } /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) ) @@ -1389,44 +1214,32 @@ void G_RunMissile( gentity_t *ent ) } */ - AddSightEvent( ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75 );//wakes them up when see a shot passes in front of them - if ( !Q_irand( 0, 10 ) ) - {//not so often... - if ( ent->splashDamage && ent->splashRadius ) - {//I'm an exploder, let people around me know danger is coming - if ( ent->s.weapon == WP_TRIP_MINE ) - {//??? - } - else - { - if ( ent->s.weapon == WP_ROCKET_LAUNCHER && ent->e_ThinkFunc == thinkF_rocketThink ) - {//homing rocket- run like hell! - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER_GREAT, 50 ); - } - else - { - AddSightEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER, 50 ); + AddSightEvent(ent->owner, ent->currentOrigin, 512, AEL_DISCOVERED, 75); // wakes them up when see a shot passes in front of them + if (!Q_irand(0, 10)) { // not so often... + if (ent->splashDamage && ent->splashRadius) { // I'm an exploder, let people around me know danger is coming + if (ent->s.weapon == WP_TRIP_MINE) { //??? + } else { + if (ent->s.weapon == WP_ROCKET_LAUNCHER && ent->e_ThinkFunc == thinkF_rocketThink) { // homing rocket- run like hell! + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER_GREAT, 50); + } else { + AddSightEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER, 50); } - AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER ); + AddSoundEvent(ent->owner, ent->currentOrigin, ent->splashRadius, AEL_DANGER); } - } - else - {//makes them run from near misses - AddSightEvent( ent->owner, ent->currentOrigin, 48, AEL_DANGER, 50 ); + } else { // makes them run from near misses + AddSightEvent(ent->owner, ent->currentOrigin, 48, AEL_DANGER, 50); } } - if ( tr.fraction == 1 ) - { + if (tr.fraction == 1) { return; } // never explode or bounce on sky - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { - G_FreeEntity( ent ); + if (tr.surfaceFlags & SURF_NOIMPACT) { + G_FreeEntity(ent); return; } - G_MissileImpact( ent, &tr, trHitLoc ); + G_MissileImpact(ent, &tr, trHitLoc); } \ No newline at end of file diff --git a/codeJK2/game/g_mover.cpp b/codeJK2/game/g_mover.cpp index a4c27204fe..9cb135821d 100644 --- a/codeJK2/game/g_mover.cpp +++ b/codeJK2/game/g_mover.cpp @@ -27,21 +27,21 @@ along with this program; if not, see . #include "g_functions.h" #include "objectives.h" -#define MOVER_START_ON 1 -#define MOVER_FORCE_ACTIVATE 2 -#define MOVER_CRUSHER 4 -#define MOVER_TOGGLE 8 -#define MOVER_LOCKED 16 -#define MOVER_GOODIE 32 -#define MOVER_PLAYER_USE 64 -#define MOVER_INACTIVE 128 - -int BMS_START = 0; -int BMS_MID = 1; -int BMS_END = 2; - -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ); +#define MOVER_START_ON 1 +#define MOVER_FORCE_ACTIVATE 2 +#define MOVER_CRUSHER 4 +#define MOVER_TOGGLE 8 +#define MOVER_LOCKED 16 +#define MOVER_GOODIE 32 +#define MOVER_PLAYER_USE 64 +#define MOVER_INACTIVE 128 + +int BMS_START = 0; +int BMS_MID = 1; +int BMS_END = 2; + +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +void CalcTeamDoorCenter(gentity_t *ent, vec3_t center); /* =============================================================================== @@ -50,17 +50,16 @@ PUSHMOVE =============================================================================== */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ); +void MatchTeam(gentity_t *teamLeader, int moverState, int time); extern qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2); typedef struct { - gentity_t *ent; - vec3_t origin; - vec3_t angles; - float deltayaw; + gentity_t *ent; + vec3_t origin; + vec3_t angles; + float deltayaw; } pushed_t; -pushed_t pushed[MAX_GENTITIES], *pushed_p; - +pushed_t pushed[MAX_GENTITIES], *pushed_p; /* ------------------------- @@ -68,15 +67,13 @@ G_SetLoopSound ------------------------- */ -void G_PlayDoorLoopSound( gentity_t *ent ) -{ - if ( VALIDSTRING( ent->soundSet ) == false ) +void G_PlayDoorLoopSound(gentity_t *ent) { + if (VALIDSTRING(ent->soundSet) == false) return; - sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, BMS_MID ); + sfxHandle_t sfx = CAS_GetBModelSound(ent->soundSet, BMS_MID); - if ( sfx == -1 ) - { + if (sfx == -1) { ent->s.loopSound = 0; return; } @@ -90,24 +87,22 @@ G_PlayDoorSound ------------------------- */ -void G_PlayDoorSound( gentity_t *ent, int type ) -{ - if ( VALIDSTRING( ent->soundSet ) == false ) +void G_PlayDoorSound(gentity_t *ent, int type) { + if (VALIDSTRING(ent->soundSet) == false) return; - sfxHandle_t sfx = CAS_GetBModelSound( ent->soundSet, type ); + sfxHandle_t sfx = CAS_GetBModelSound(ent->soundSet, type); - if ( sfx == -1 ) + if (sfx == -1) return; - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSoundEvent( ent->activator, doorcenter, 128, AEL_MINOR ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSoundEvent(ent->activator, doorcenter, 128, AEL_MINOR); } - G_AddEvent( ent, EV_BMODEL_SOUND, sfx ); + G_AddEvent(ent, EV_BMODEL_SOUND, sfx); } /* @@ -116,41 +111,33 @@ G_TestEntityPosition ============ */ -gentity_t *G_TestEntityPosition( gentity_t *ent ) { - trace_t tr; - int mask; +gentity_t *G_TestEntityPosition(gentity_t *ent) { + trace_t tr; + int mask; - if ( (ent->client && ent->health <= 0) || !ent->clipmask ) - {//corpse or something with no clipmask + if ((ent->client && ent->health <= 0) || !ent->clipmask) { // corpse or something with no clipmask mask = MASK_SOLID; - } - else - { + } else { mask = ent->clipmask; } - if ( ent->client ) - { - gi.trace( &tr, ent->client->ps.origin, ent->mins, ent->maxs, ent->client->ps.origin, ent->s.number, mask, G2_NOCOLLIDE, 0 ); - } - else - { - if ( ent->s.eFlags & EF_MISSILE_STICK )//Arggh, this is dumb...but when it used the bbox, it was pretty much always in solid when it is riding something..which is wrong..so I changed it to basically be a point contents check - { - gi.trace( &tr, ent->s.pos.trBase, vec3_origin, vec3_origin, ent->s.pos.trBase, ent->s.number, mask, G2_NOCOLLIDE, 0 ); - } - else + if (ent->client) { + gi.trace(&tr, ent->client->ps.origin, ent->mins, ent->maxs, ent->client->ps.origin, ent->s.number, mask, G2_NOCOLLIDE, 0); + } else { + if (ent->s.eFlags & EF_MISSILE_STICK) // Arggh, this is dumb...but when it used the bbox, it was pretty much always in solid when it is riding + // something..which is wrong..so I changed it to basically be a point contents check { - gi.trace( &tr, ent->s.pos.trBase, ent->mins, ent->maxs, ent->s.pos.trBase, ent->s.number, mask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, ent->s.pos.trBase, vec3_origin, vec3_origin, ent->s.pos.trBase, ent->s.number, mask, G2_NOCOLLIDE, 0); + } else { + gi.trace(&tr, ent->s.pos.trBase, ent->mins, ent->maxs, ent->s.pos.trBase, ent->s.number, mask, G2_NOCOLLIDE, 0); } } if (tr.startsolid) - return &g_entities[ tr.entityNum ]; + return &g_entities[tr.entityNum]; return NULL; } - /* ================== G_TryPushingEntity @@ -158,10 +145,10 @@ G_TryPushingEntity Returns qfalse if the move is blocked ================== */ -qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) { - vec3_t forward, right, up; - vec3_t org, org2, move2; - gentity_t *block; +qboolean G_TryPushingEntity(gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove) { + vec3_t forward, right, up; + vec3_t org, org2, move2; + gentity_t *block; /* // EF_MOVER_STOP will just stop when contacting another entity @@ -174,42 +161,42 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v // save off the old position if (pushed_p > &pushed[MAX_GENTITIES]) { - G_Error( "pushed_p > &pushed[MAX_GENTITIES]" ); + G_Error("pushed_p > &pushed[MAX_GENTITIES]"); } pushed_p->ent = check; - VectorCopy (check->s.pos.trBase, pushed_p->origin); - VectorCopy (check->s.apos.trBase, pushed_p->angles); - if ( check->client ) { + VectorCopy(check->s.pos.trBase, pushed_p->origin); + VectorCopy(check->s.apos.trBase, pushed_p->angles); + if (check->client) { pushed_p->deltayaw = check->client->ps.delta_angles[YAW]; - VectorCopy (check->client->ps.origin, pushed_p->origin); + VectorCopy(check->client->ps.origin, pushed_p->origin); } pushed_p++; // we need this for pushing things later - VectorSubtract (vec3_origin, amove, org); - AngleVectors (org, forward, right, up); + VectorSubtract(vec3_origin, amove, org); + AngleVectors(org, forward, right, up); // try moving the contacted entity - VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase); + VectorAdd(check->s.pos.trBase, move, check->s.pos.trBase); if (check->client) { // make sure the client's view rotates when on a rotating mover check->client->ps.delta_angles[YAW] += ANGLE2SHORT(amove[YAW]); } // figure movement due to the pusher's amove - VectorSubtract (check->s.pos.trBase, pusher->currentOrigin, org); - org2[0] = DotProduct (org, forward); - org2[1] = -DotProduct (org, right); - org2[2] = DotProduct (org, up); - VectorSubtract (org2, org, move2); - VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase); - if ( check->client ) { - VectorAdd (check->client->ps.origin, move, check->client->ps.origin); - VectorAdd (check->client->ps.origin, move2, check->client->ps.origin); + VectorSubtract(check->s.pos.trBase, pusher->currentOrigin, org); + org2[0] = DotProduct(org, forward); + org2[1] = -DotProduct(org, right); + org2[2] = DotProduct(org, up); + VectorSubtract(org2, org, move2); + VectorAdd(check->s.pos.trBase, move2, check->s.pos.trBase); + if (check->client) { + VectorAdd(check->client->ps.origin, move, check->client->ps.origin); + VectorAdd(check->client->ps.origin, move2, check->client->ps.origin); } // may have pushed them off an edge - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { check->s.groundEntityNum = ENTITYNUM_NONE; } @@ -219,43 +206,41 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v return qtrue; } */ - block = G_TestEntityPosition( check ); + block = G_TestEntityPosition(check); if (!block) { // pushed ok - if ( check->client ) { - VectorCopy( check->client->ps.origin, check->currentOrigin ); + if (check->client) { + VectorCopy(check->client->ps.origin, check->currentOrigin); } else { - VectorCopy( check->s.pos.trBase, check->currentOrigin ); + VectorCopy(check->s.pos.trBase, check->currentOrigin); } - gi.linkentity (check); + gi.linkentity(check); return qtrue; } // if it is ok to leave in the old position, do it // this is only relevent for riding entities, not pushed // Sliding trapdoors can cause this. - VectorCopy( (pushed_p-1)->origin, check->s.pos.trBase); - if ( check->client ) { - VectorCopy( (pushed_p-1)->origin, check->client->ps.origin); + VectorCopy((pushed_p - 1)->origin, check->s.pos.trBase); + if (check->client) { + VectorCopy((pushed_p - 1)->origin, check->client->ps.origin); } - VectorCopy( (pushed_p-1)->angles, check->s.apos.trBase ); - block = G_TestEntityPosition (check); - if ( !block ) { + VectorCopy((pushed_p - 1)->angles, check->s.apos.trBase); + block = G_TestEntityPosition(check); + if (!block) { check->s.groundEntityNum = ENTITYNUM_NONE; pushed_p--; return qtrue; } // blocked - if ( pusher->damage ) - {//Do damage - G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH ); + if (pusher->damage) { // Do damage + G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH); } return qfalse; } - /* ============ G_MoverPush @@ -265,95 +250,79 @@ otherwise riders would continue to slide. If qfalse is returned, *obstacle will be the blocking entity ============ */ -qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle ) { - qboolean notMoving; - int i, e; - int listedEntities; - vec3_t mins, maxs; - vec3_t pusherMins, pusherMaxs, totalMins, totalMaxs; - pushed_t *p; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *check; +qboolean G_MoverPush(gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle) { + qboolean notMoving; + int i, e; + int listedEntities; + vec3_t mins, maxs; + vec3_t pusherMins, pusherMaxs, totalMins, totalMaxs; + pushed_t *p; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *check; *obstacle = NULL; - - if ( !pusher->bmodel ) - {//misc_model_breakable - VectorAdd( pusher->currentOrigin, pusher->mins, pusherMins ); - VectorAdd( pusher->currentOrigin, pusher->maxs, pusherMaxs ); + if (!pusher->bmodel) { // misc_model_breakable + VectorAdd(pusher->currentOrigin, pusher->mins, pusherMins); + VectorAdd(pusher->currentOrigin, pusher->maxs, pusherMaxs); } // mins/maxs are the bounds at the destination // totalMins / totalMaxs are the bounds for the entire move - if ( pusher->currentAngles[0] || pusher->currentAngles[1] || pusher->currentAngles[2] - || amove[0] || amove[1] || amove[2] ) - { - float radius; + if (pusher->currentAngles[0] || pusher->currentAngles[1] || pusher->currentAngles[2] || amove[0] || amove[1] || amove[2]) { + float radius; - radius = RadiusFromBounds( pusher->mins, pusher->maxs ); - for ( i = 0 ; i < 3 ; i++ ) - { + radius = RadiusFromBounds(pusher->mins, pusher->maxs); + for (i = 0; i < 3; i++) { mins[i] = pusher->currentOrigin[i] + move[i] - radius; maxs[i] = pusher->currentOrigin[i] + move[i] + radius; totalMins[i] = mins[i] - move[i]; totalMaxs[i] = maxs[i] - move[i]; } - } - else - { - for (i=0 ; i<3 ; i++) - { + } else { + for (i = 0; i < 3; i++) { mins[i] = pusher->absmin[i] + move[i]; maxs[i] = pusher->absmax[i] + move[i]; } - VectorCopy( pusher->absmin, totalMins ); - VectorCopy( pusher->absmax, totalMaxs ); - for (i=0 ; i<3 ; i++) - { - if ( move[i] > 0 ) - { + VectorCopy(pusher->absmin, totalMins); + VectorCopy(pusher->absmax, totalMaxs); + for (i = 0; i < 3; i++) { + if (move[i] > 0) { totalMaxs[i] += move[i]; - } - else - { + } else { totalMins[i] += move[i]; } } } // unlink the pusher so we don't get it in the entityList - gi.unlinkentity( pusher ); + gi.unlinkentity(pusher); - listedEntities = gi.EntitiesInBox( totalMins, totalMaxs, entityList, MAX_GENTITIES ); + listedEntities = gi.EntitiesInBox(totalMins, totalMaxs, entityList, MAX_GENTITIES); // move the pusher to it's final position - VectorAdd( pusher->currentOrigin, move, pusher->currentOrigin ); - VectorAdd( pusher->currentAngles, amove, pusher->currentAngles ); - gi.linkentity( pusher ); + VectorAdd(pusher->currentOrigin, move, pusher->currentOrigin); + VectorAdd(pusher->currentAngles, amove, pusher->currentAngles); + gi.linkentity(pusher); - notMoving = (qboolean)(VectorCompare( vec3_origin, move ) && VectorCompare( vec3_origin, amove )); + notMoving = (qboolean)(VectorCompare(vec3_origin, move) && VectorCompare(vec3_origin, amove)); // see if any solid entities are inside the final position - for ( e = 0 ; e < listedEntities ; e++ ) { - check = entityList[ e ]; + for (e = 0; e < listedEntities; e++) { + check = entityList[e]; - if (( check->s.eFlags & EF_MISSILE_STICK ) && (notMoving || check->s.groundEntityNum < 0 || check->s.groundEntityNum >= ENTITYNUM_NONE )) - { + if ((check->s.eFlags & EF_MISSILE_STICK) && (notMoving || check->s.groundEntityNum < 0 || check->s.groundEntityNum >= ENTITYNUM_NONE)) { // special case hack for sticky things, destroy it if we aren't attached to the thing that is moving, but the moving thing is pushing us - G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH ); + G_Damage(check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH); continue; } // only push items and players - if ( check->s.eType != ET_ITEM ) - { - //FIXME: however it allows items to be pushed through stuff, do same for corpses? - if ( check->s.eType != ET_PLAYER ) - { - if ( !( check->s.eFlags & EF_MISSILE_STICK )) - { + if (check->s.eType != ET_ITEM) { + // FIXME: however it allows items to be pushed through stuff, do same for corpses? + if (check->s.eType != ET_PLAYER) { + if (!(check->s.eFlags & EF_MISSILE_STICK)) { // cannot be pushed by this mover continue; } @@ -364,97 +333,77 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** continue; } */ - else if ( !pusher->bmodel ) - { - vec3_t checkMins, checkMaxs; + else if (!pusher->bmodel) { + vec3_t checkMins, checkMaxs; - VectorAdd( check->currentOrigin, check->mins, checkMins ); - VectorAdd( check->currentOrigin, check->maxs, checkMaxs ); + VectorAdd(check->currentOrigin, check->mins, checkMins); + VectorAdd(check->currentOrigin, check->maxs, checkMaxs); - if ( G_BoundsOverlap( checkMins, checkMaxs, pusherMins, pusherMaxs ) ) - {//They're inside me already, no push - FIXME: we're testing a moves spot, aren't we, so we could have just moved inside them? + if (G_BoundsOverlap(checkMins, checkMaxs, pusherMins, pusherMaxs)) { // They're inside me already, no push - FIXME: we're testing a moves spot, + // aren't we, so we could have just moved inside them? continue; } } } - - if ( check->maxs[0] - check->mins[0] <= 0 && - check->maxs[1] - check->mins[1] <= 0 && - check->maxs[2] - check->mins[2] <= 0 ) - {//no size, don't push + if (check->maxs[0] - check->mins[0] <= 0 && check->maxs[1] - check->mins[1] <= 0 && check->maxs[2] - check->mins[2] <= 0) { // no size, don't push continue; } // if the entity is standing on the pusher, it will definitely be moved - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { // see if the ent needs to be tested - if ( check->absmin[0] >= maxs[0] - || check->absmin[1] >= maxs[1] - || check->absmin[2] >= maxs[2] - || check->absmax[0] <= mins[0] - || check->absmax[1] <= mins[1] - || check->absmax[2] <= mins[2] ) { + if (check->absmin[0] >= maxs[0] || check->absmin[1] >= maxs[1] || check->absmin[2] >= maxs[2] || check->absmax[0] <= mins[0] || + check->absmax[1] <= mins[1] || check->absmax[2] <= mins[2]) { continue; } // see if the ent's bbox is inside the pusher's final position // this does allow a fast moving object to pass through a thin entity... - if ( G_TestEntityPosition( check ) != pusher ) - { + if (G_TestEntityPosition(check) != pusher) { continue; } } - if ( ((pusher->spawnflags&2)&&!Q_stricmp("func_breakable",pusher->classname)) - ||((pusher->spawnflags&16)&&!Q_stricmp("func_static",pusher->classname)) ) - {//ugh, avoid stricmp with a unique flag - //Damage on impact - if ( pusher->damage ) - {//Do damage - G_Damage( check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH ); - if ( pusher->health >= 0 && pusher->takedamage && !(pusher->spawnflags&1) ) - {//do some damage to me, too - G_Damage( pusher, check, pusher->activator, move, pusher->s.pos.trBase, floor(pusher->damage/4.0f), 0, MOD_CRUSH ); + if (((pusher->spawnflags & 2) && !Q_stricmp("func_breakable", pusher->classname)) || + ((pusher->spawnflags & 16) && !Q_stricmp("func_static", pusher->classname))) { // ugh, avoid stricmp with a unique flag + // Damage on impact + if (pusher->damage) { // Do damage + G_Damage(check, pusher, pusher->activator, move, check->currentOrigin, pusher->damage, 0, MOD_CRUSH); + if (pusher->health >= 0 && pusher->takedamage && !(pusher->spawnflags & 1)) { // do some damage to me, too + G_Damage(pusher, check, pusher->activator, move, pusher->s.pos.trBase, floor(pusher->damage / 4.0f), 0, MOD_CRUSH); } } } // really need a flag like MOVER_TOUCH that calls the ent's touch function here, instead of this stricmp crap - else if ( (pusher->spawnflags&2) && !Q_stricmp( "func_rotating", pusher->classname ) ) - { - GEntity_TouchFunc( pusher, check, NULL ); - continue; // don't want it blocking so skip past it + else if ((pusher->spawnflags & 2) && !Q_stricmp("func_rotating", pusher->classname)) { + GEntity_TouchFunc(pusher, check, NULL); + continue; // don't want it blocking so skip past it } vec3_t oldOrg; - VectorCopy( check->s.pos.trBase, oldOrg ); + VectorCopy(check->s.pos.trBase, oldOrg); // the entity needs to be pushed - if ( G_TryPushingEntity( check, pusher, move, amove ) ) - { + if (G_TryPushingEntity(check, pusher, move, amove)) { // the mover wasn't blocked - if ( check->s.eFlags & EF_MISSILE_STICK ) - { - if ( !VectorCompare( oldOrg, check->s.pos.trBase )) - { + if (check->s.eFlags & EF_MISSILE_STICK) { + if (!VectorCompare(oldOrg, check->s.pos.trBase)) { // and the rider was actually pushed, so interpolate position change to smooth out the ride check->s.pos.trType = TR_INTERPOLATE; continue; } - //else..the mover wasn't blocked & we are riding the mover & but the rider did not move even though the mover itself did...so + // else..the mover wasn't blocked & we are riding the mover & but the rider did not move even though the mover itself did...so // drop through and let it blow up the rider up - } - else - { + } else { continue; } } // the move was blocked even after pushing this rider - if ( check->s.eFlags & EF_MISSILE_STICK ) - { + if (check->s.eFlags & EF_MISSILE_STICK) { // so nuke 'em so they don't block us anymore - G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH ); + G_Damage(check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH); continue; } @@ -464,14 +413,14 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** // move back any entities we already moved // go backwards, so if the same entity was pushed // twice, it goes back to the original position - for ( p=pushed_p-1 ; p>=pushed ; p-- ) { - VectorCopy (p->origin, p->ent->s.pos.trBase); - VectorCopy (p->angles, p->ent->s.apos.trBase); - if ( p->ent->client ) { + for (p = pushed_p - 1; p >= pushed; p--) { + VectorCopy(p->origin, p->ent->s.pos.trBase); + VectorCopy(p->angles, p->ent->s.apos.trBase); + if (p->ent->client) { p->ent->client->ps.delta_angles[YAW] = p->deltayaw; - VectorCopy (p->origin, p->ent->client->ps.origin); + VectorCopy(p->origin, p->ent->client->ps.origin); } - gi.linkentity (p->ent); + gi.linkentity(p->ent); } return qfalse; } @@ -479,16 +428,15 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** return qtrue; } - /* ================= G_MoverTeam ================= */ -void G_MoverTeam( gentity_t *ent ) { - vec3_t move, amove; - gentity_t *part, *obstacle; - vec3_t origin, angles; +void G_MoverTeam(gentity_t *ent) { + vec3_t move, amove; + gentity_t *part, *obstacle; + vec3_t origin, angles; obstacle = NULL; @@ -496,52 +444,43 @@ void G_MoverTeam( gentity_t *ent ) { // any moves or calling any think functions // if the move is blocked, all moved objects will be backed out pushed_p = pushed; - for (part = ent ; part ; part=part->teamchain) - { + for (part = ent; part; part = part->teamchain) { // get current position part->s.eFlags &= ~EF_BLOCKED_MOVER; - EvaluateTrajectory( &part->s.pos, level.time, origin ); - EvaluateTrajectory( &part->s.apos, level.time, angles ); - VectorSubtract( origin, part->currentOrigin, move ); - VectorSubtract( angles, part->currentAngles, amove ); - if ( !G_MoverPush( part, move, amove, &obstacle ) ) - { - break; // move was blocked + EvaluateTrajectory(&part->s.pos, level.time, origin); + EvaluateTrajectory(&part->s.apos, level.time, angles); + VectorSubtract(origin, part->currentOrigin, move); + VectorSubtract(angles, part->currentAngles, amove); + if (!G_MoverPush(part, move, amove, &obstacle)) { + break; // move was blocked } } - if (part) - { + if (part) { // if the pusher has a "blocked" function, call it // go back to the previous position - for ( part = ent ; part ; part = part->teamchain ) - { - //Push up time so it doesn't wiggle when blocked + for (part = ent; part; part = part->teamchain) { + // Push up time so it doesn't wiggle when blocked part->s.pos.trTime += level.time - level.previousTime; part->s.apos.trTime += level.time - level.previousTime; - EvaluateTrajectory( &part->s.pos, level.time, part->currentOrigin ); - EvaluateTrajectory( &part->s.apos, level.time, part->currentAngles ); - gi.linkentity( part ); + EvaluateTrajectory(&part->s.pos, level.time, part->currentOrigin); + EvaluateTrajectory(&part->s.apos, level.time, part->currentAngles); + gi.linkentity(part); part->s.eFlags |= EF_BLOCKED_MOVER; } - if ( ent->e_BlockedFunc != blockedF_NULL ) - {// this check no longer necessary, done internally below, but it's here for reference - GEntity_BlockedFunc( ent, obstacle ); + if (ent->e_BlockedFunc != blockedF_NULL) { // this check no longer necessary, done internally below, but it's here for reference + GEntity_BlockedFunc(ent, obstacle); } return; } // the move succeeded - for ( part = ent ; part ; part = part->teamchain ) - { + for (part = ent; part; part = part->teamchain) { // call the reached function if time is at or past end point - if ( part->s.pos.trType == TR_LINEAR_STOP || - part->s.pos.trType == TR_NONLINEAR_STOP ) - { - if ( level.time >= part->s.pos.trTime + part->s.pos.trDuration ) - { - GEntity_ReachedFunc( part ); + if (part->s.pos.trType == TR_LINEAR_STOP || part->s.pos.trType == TR_NONLINEAR_STOP) { + if (level.time >= part->s.pos.trTime + part->s.pos.trDuration) { + GEntity_ReachedFunc(part); } } } @@ -553,26 +492,26 @@ G_RunMover ================ */ -//void rebolt_turret( gentity_t *base ); -void G_RunMover( gentity_t *ent ) { +// void rebolt_turret( gentity_t *base ); +void G_RunMover(gentity_t *ent) { // if not a team captain, don't do anything, because // the captain will handle everything - if ( ent->flags & FL_TEAMSLAVE ) { + if (ent->flags & FL_TEAMSLAVE) { return; } // if stationary at one of the positions, don't move anything - if ( ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY ) { - G_MoverTeam( ent ); + if (ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY) { + G_MoverTeam(ent); } -/* if ( ent->classname && Q_stricmp("misc_turret", ent->classname ) == 0 ) - { - rebolt_turret( ent ); - } -*/ + /* if ( ent->classname && Q_stricmp("misc_turret", ent->classname ) == 0 ) + { + rebolt_turret( ent ); + } + */ // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -591,20 +530,18 @@ CalcTeamDoorCenter Finds all the doors of a team and returns their center position */ -void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) -{ - vec3_t slavecenter; - gentity_t *slave; +void CalcTeamDoorCenter(gentity_t *ent, vec3_t center) { + vec3_t slavecenter; + gentity_t *slave; - //Start with our center + // Start with our center VectorAdd(ent->mins, ent->maxs, center); VectorScale(center, 0.5, center); - for ( slave = ent->teamchain ; slave ; slave = slave->teamchain ) - { - //Find slave's center + for (slave = ent->teamchain; slave; slave = slave->teamchain) { + // Find slave's center VectorAdd(slave->mins, slave->maxs, slavecenter); VectorScale(slavecenter, 0.5, slavecenter); - //Add that to our own, find middle + // Add that to our own, find middle VectorAdd(center, slavecenter, center); VectorScale(center, 0.5, center); } @@ -615,61 +552,54 @@ void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) SetMoverState =============== */ -void SetMoverState( gentity_t *ent, moverState_t moverState, int time ) { - vec3_t delta; - float f; +void SetMoverState(gentity_t *ent, moverState_t moverState, int time) { + vec3_t delta; + float f; ent->moverState = moverState; ent->s.pos.trTime = time; - if ( ent->s.pos.trDuration <= 0 ) - {//Don't allow divide by zero! + if (ent->s.pos.trDuration <= 0) { // Don't allow divide by zero! ent->s.pos.trDuration = 1; } - switch( moverState ) { + switch (moverState) { case MOVER_POS1: - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_POS2: - VectorCopy( ent->pos2, ent->s.pos.trBase ); + VectorCopy(ent->pos2, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_1TO2: - VectorCopy( ent->pos1, ent->s.pos.trBase ); - VectorSubtract( ent->pos2, ent->pos1, delta ); + VectorCopy(ent->pos1, ent->s.pos.trBase); + VectorSubtract(ent->pos2, ent->pos1, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; case MOVER_2TO1: - VectorCopy( ent->pos2, ent->s.pos.trBase ); - VectorSubtract( ent->pos1, ent->pos2, delta ); + VectorCopy(ent->pos2, ent->s.pos.trBase); + VectorSubtract(ent->pos1, ent->pos2, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; } - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); - gi.linkentity( ent ); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); + gi.linkentity(ent); } /* @@ -680,345 +610,289 @@ All entities in a mover team will move from pos1 to pos2 in the same amount of time ================ */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ) { - gentity_t *slave; +void MatchTeam(gentity_t *teamLeader, int moverState, int time) { + gentity_t *slave; - for ( slave = teamLeader ; slave ; slave = slave->teamchain ) { - SetMoverState( slave, (moverState_t) moverState, time ); + for (slave = teamLeader; slave; slave = slave->teamchain) { + SetMoverState(slave, (moverState_t)moverState, time); } } - - /* ================ ReturnToPos1 ================ */ -void ReturnToPos1( gentity_t *ent ) { +void ReturnToPos1(gentity_t *ent) { ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = 0; ent->s.time = level.time; - MatchTeam( ent, MOVER_2TO1, level.time ); + MatchTeam(ent, MOVER_2TO1, level.time); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? } - /* ================ Reached_BinaryMover ================ */ -void Reached_BinaryMover( gentity_t *ent ) -{ +void Reached_BinaryMover(gentity_t *ent) { // stop the looping sound ent->s.loopSound = 0; - if ( ent->moverState == MOVER_1TO2 ) - {//reached open + if (ent->moverState == MOVER_1TO2) { // reached open // reached pos2 - SetMoverState( ent, MOVER_POS2, level.time ); + SetMoverState(ent, MOVER_POS2, level.time); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); - if ( ent->wait < 0 ) - {//Done for good + if (ent->wait < 0) { // Done for good ent->e_ThinkFunc = thinkF_NULL; ent->nextthink = -1; ent->e_UseFunc = useF_NULL; - } - else - { + } else { // return to pos1 after a delay ent->e_ThinkFunc = thinkF_ReturnToPos1; - if(ent->spawnflags & 8) - {//Toggle, keep think, wait for next use? + if (ent->spawnflags & 8) { // Toggle, keep think, wait for next use? ent->nextthink = -1; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } } // fire targets - if ( !ent->activator ) - { + if (!ent->activator) { ent->activator = ent; } - G_UseTargets2( ent, ent->activator, ent->opentarget ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//closed + G_UseTargets2(ent, ent->activator, ent->opentarget); + } else if (ent->moverState == MOVER_2TO1) { // closed // reached pos1 - SetMoverState( ent, MOVER_POS1, level.time ); + SetMoverState(ent, MOVER_POS1, level.time); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); // close areaportals - if ( ent->teammaster == ent || !ent->teammaster ) - { - gi.AdjustAreaPortalState( ent, qfalse ); + if (ent->teammaster == ent || !ent->teammaster) { + gi.AdjustAreaPortalState(ent, qfalse); } - G_UseTargets2( ent, ent->activator, ent->closetarget ); - } - else - { - G_Error( "Reached_BinaryMover: bad moverState" ); + G_UseTargets2(ent, ent->activator, ent->closetarget); + } else { + G_Error("Reached_BinaryMover: bad moverState"); } } - /* ================ Use_BinaryMover_Go ================ */ -void Use_BinaryMover_Go( gentity_t *ent ) -{ - int total; - int partial; -// gentity_t *other = ent->enemy; - gentity_t *activator = ent->activator; +void Use_BinaryMover_Go(gentity_t *ent) { + int total; + int partial; + // gentity_t *other = ent->enemy; + gentity_t *activator = ent->activator; ent->activator = activator; - if ( ent->moverState == MOVER_POS1 ) - { + if (ent->moverState == MOVER_POS1) { // start moving 50 msec later, becase if this was player // triggered, level.time hasn't been advanced yet - MatchTeam( ent, MOVER_1TO2, level.time + 50 ); + MatchTeam(ent, MOVER_1TO2, level.time + 50); - vec3_t doorcenter; - CalcTeamDoorCenter( ent, doorcenter ); - if ( ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER ) - { - AddSightEvent( ent->activator, doorcenter, 256, AEL_MINOR, 1 ); + vec3_t doorcenter; + CalcTeamDoorCenter(ent, doorcenter); + if (ent->activator && ent->activator->client && ent->activator->client->playerTeam == TEAM_PLAYER) { + AddSightEvent(ent->activator, doorcenter, 256, AEL_MINOR, 1); } // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); ent->s.time = level.time; // open areaportal - if ( ent->teammaster == ent || !ent->teammaster ) { - gi.AdjustAreaPortalState( ent, qtrue ); + if (ent->teammaster == ent || !ent->teammaster) { + gi.AdjustAreaPortalState(ent, qtrue); } - G_UseTargets( ent, ent->activator ); + G_UseTargets(ent, ent->activator); return; } // if all the way up, just delay before coming down - if ( ent->moverState == MOVER_POS2 ) { - //have to do this because the delay sets our think to Use_BinaryMover_Go + if (ent->moverState == MOVER_POS2) { + // have to do this because the delay sets our think to Use_BinaryMover_Go ent->e_ThinkFunc = thinkF_ReturnToPos1; - if ( ent->spawnflags & 8 ) - {//TOGGLE doors don't use wait! + if (ent->spawnflags & 8) { // TOGGLE doors don't use wait! ent->nextthink = level.time + FRAMETIME; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } - G_UseTargets2( ent, ent->activator, ent->target2 ); + G_UseTargets2(ent, ent->activator, ent->target2); return; } // only partway down before reversing - if ( ent->moverState == MOVER_2TO1 ) - { - total = ent->s.pos.trDuration-50; - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_2TO1) { + total = ent->s.pos.trDuration - 50; + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; - VectorSubtract( ent->currentOrigin, ent->pos1, curDelta ); - float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + VectorSubtract(ent->currentOrigin, ent->pos1, curDelta); + float fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { - partial = level.time - ent->s.pos.trTime;//ent->s.time; + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { + partial = level.time - ent->s.pos.trTime; // ent->s.time; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; - MatchTeam( ent, MOVER_1TO2, ent->s.pos.trTime ); + MatchTeam(ent, MOVER_1TO2, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } // only partway up before reversing - if ( ent->moverState == MOVER_1TO2 ) - { - total = ent->s.pos.trDuration-50; - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_1TO2) { + total = ent->s.pos.trDuration - 50; + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; - VectorSubtract( ent->currentOrigin, ent->pos2, curDelta ); - float fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + VectorSubtract(ent->currentOrigin, ent->pos2, curDelta); + float fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { - partial = level.time - ent->s.pos.trTime;//ent->s.time; + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { + partial = level.time - ent->s.pos.trTime; // ent->s.time; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; - MatchTeam( ent, MOVER_2TO1, ent->s.pos.trTime ); + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; + MatchTeam(ent, MOVER_2TO1, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } } -void UnLockDoors(gentity_t *const ent) -{ - //noise? - //go through and unlock the door and all the slaves - gentity_t *slave = ent; - do - { // want to allow locked toggle doors, so keep the targetname - if( !(slave->spawnflags & MOVER_TOGGLE) ) - { - slave->targetname = NULL;//not usable ever again +void UnLockDoors(gentity_t *const ent) { + // noise? + // go through and unlock the door and all the slaves + gentity_t *slave = ent; + do { // want to allow locked toggle doors, so keep the targetname + if (!(slave->spawnflags & MOVER_TOGGLE)) { + slave->targetname = NULL; // not usable ever again } slave->spawnflags &= ~MOVER_LOCKED; - slave->s.frame = 1;//second stage of anim + slave->s.frame = 1; // second stage of anim slave = slave->teamchain; - } while ( slave ); + } while (slave); } -void LockDoors(gentity_t *const ent) -{ - //noise? - //go through and lock the door and all the slaves - gentity_t *slave = ent; - do - { +void LockDoors(gentity_t *const ent) { + // noise? + // go through and lock the door and all the slaves + gentity_t *slave = ent; + do { slave->spawnflags |= MOVER_LOCKED; - slave->s.frame = 0;//first stage of anim + slave->s.frame = 0; // first stage of anim slave = slave->teamchain; - } while ( slave ); + } while (slave); } /* ================ Use_BinaryMover ================ */ -void Use_BinaryMover( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - int key; +void Use_BinaryMover(gentity_t *ent, gentity_t *other, gentity_t *activator) { + int key; char *text; - if ( ent->e_UseFunc == useF_NULL ) - {//I cannot be used anymore, must be a door with a wait of -1 that's opened. + if (ent->e_UseFunc == useF_NULL) { // I cannot be used anymore, must be a door with a wait of -1 that's opened. return; } // only the master should be used - if ( ent->flags & FL_TEAMSLAVE ) - { - Use_BinaryMover( ent->teammaster, other, activator ); + if (ent->flags & FL_TEAMSLAVE) { + Use_BinaryMover(ent->teammaster, other, activator); return; } - if ( ent->svFlags & SVF_INACTIVE ) - { + if (ent->svFlags & SVF_INACTIVE) { return; } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, unlock it + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, unlock it UnLockDoors(ent); return; } - if ( ent->spawnflags & MOVER_GOODIE ) - { - if ( ent->fly_sound_debounce_time > level.time ) - { + if (ent->spawnflags & MOVER_GOODIE) { + if (ent->fly_sound_debounce_time > level.time) { return; - } - else - { - key = INV_GoodieKeyCheck( activator ); - if (key) - {//activator has a goodie key, remove it + } else { + key = INV_GoodieKeyCheck(activator); + if (key) { // activator has a goodie key, remove it activator->client->ps.inventory[key]--; - G_Sound( activator, G_SoundIndex( "sound/movers/goodie_pass.wav" ) ); + G_Sound(activator, G_SoundIndex("sound/movers/goodie_pass.wav")); // once the goodie mover has been used, it no longer requires a goodie key ent->spawnflags &= ~MOVER_GOODIE; - } - else - { //don't have a goodie key - G_Sound( activator, G_SoundIndex( "sound/movers/goodie_fail.wav" ) ); + } else { // don't have a goodie key + G_Sound(activator, G_SoundIndex("sound/movers/goodie_fail.wav")); ent->fly_sound_debounce_time = level.time + 5000; text = "cp @INGAME_NEED_KEY_TO_OPEN"; - //FIXME: temp message, only on certain difficulties?, graphic instead of text? - gi.SendServerCommand( 0, text ); + // FIXME: temp message, only on certain difficulties?, graphic instead of text? + gi.SendServerCommand(0, text); return; } } } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - G_SetEnemy( ent, other ); + G_SetEnemy(ent, other); ent->activator = activator; - if(ent->delay) - { + if (ent->delay) { ent->e_ThinkFunc = thinkF_Use_BinaryMover_Go; ent->nextthink = level.time + ent->delay; - } - else - { + } else { Use_BinaryMover_Go(ent); } } - - /* ================ InitMover @@ -1027,102 +901,90 @@ InitMover so the movement delta can be calculated ================ */ -void InitMoverTrData( gentity_t *ent ) -{ - vec3_t move; - float distance; +void InitMoverTrData(gentity_t *ent) { + vec3_t move; + float distance; ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); // calculate time to reach second position from speed - VectorSubtract( ent->pos2, ent->pos1, move ); - distance = VectorLength( move ); - if ( ! ent->speed ) - { + VectorSubtract(ent->pos2, ent->pos1, move); + distance = VectorLength(move); + if (!ent->speed) { ent->speed = 100; } - VectorScale( move, ent->speed, ent->s.pos.trDelta ); + VectorScale(move, ent->speed, ent->s.pos.trDelta); ent->s.pos.trDuration = distance * 1000 / ent->speed; - if ( ent->s.pos.trDuration <= 0 ) - { + if (ent->s.pos.trDuration <= 0) { ent->s.pos.trDuration = 1; } } -void InitMover( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +void InitMover(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 ) - { - if ( strstr( ent->model2, ".glm" )) - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, ent->model2, ent->s.modelindex2, NULL_HANDLE, NULL_HANDLE, 0, 0 ); - if ( ent->playerModel >= 0 ) - { - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "model_root", qtrue ); + if (ent->model2) { + if (strstr(ent->model2, ".glm")) { + ent->s.modelindex2 = G_ModelIndex(ent->model2); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, ent->model2, ent->s.modelindex2, NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->playerModel >= 0) { + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "model_root", qtrue); } ent->s.radius = 120; - } - else - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + } else { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } - ent->e_UseFunc = useF_Use_BinaryMover; + ent->e_UseFunc = useF_Use_BinaryMover; ent->e_ReachedFunc = reachedF_Reached_BinaryMover; ent->moverState = MOVER_POS1; ent->svFlags = SVF_USE_CURRENT_ORIGIN; - if ( ent->spawnflags & MOVER_INACTIVE ) - {// Make it inactive + if (ent->spawnflags & MOVER_INACTIVE) { // Make it inactive ent->svFlags |= SVF_INACTIVE; } - if(ent->spawnflags & MOVER_PLAYER_USE) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & MOVER_PLAYER_USE) { // Can be used by the player's BUTTON_USE ent->svFlags |= SVF_PLAYER_USABLE; } ent->s.eType = ET_MOVER; - VectorCopy( ent->pos1, ent->currentOrigin ); - gi.linkentity( ent ); + VectorCopy(ent->pos1, ent->currentOrigin); + gi.linkentity(ent); - InitMoverTrData( ent ); + InitMoverTrData(ent); } - /* =============================================================================== @@ -1139,63 +1001,55 @@ targeted by another entity. Blocked_Door ================ */ -void Blocked_Door( gentity_t *ent, gentity_t *other ) { +void Blocked_Door(gentity_t *ent, gentity_t *other) { // remove anything other than a client -- no longer the case // don't remove security keys or goodie keys - if ( (other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY) ) - { + if ((other->s.eType == ET_ITEM) && (other->item->giTag >= INV_GOODIE_KEY && other->item->giTag <= INV_SECURITY_KEY)) { // should we be doing anything special if a key blocks it... move it somehow..? } // if your not a client, or your a dead client remove yourself... - else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message)) ) - { - if ( !other->taskManager || !other->taskManager->IsRunning() ) - { + else if (other->s.number && (!other->client || (other->client && other->health <= 0 && other->contents == CONTENTS_CORPSE && !other->message))) { + if (!other->taskManager || !other->taskManager->IsRunning()) { // if an item or weapon can we do a little explosion..? - G_FreeEntity( other ); + G_FreeEntity(other); return; } } - if ( ent->damage ) { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } - if ( ent->spawnflags & MOVER_CRUSHER ) { - return; // crushers don't reverse + if (ent->spawnflags & MOVER_CRUSHER) { + return; // crushers don't reverse } // reverse direction - Use_BinaryMover( ent, ent, other ); + Use_BinaryMover(ent, ent, other); } - /* ================ Touch_DoorTrigger ================ */ -void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ - if ( ent->svFlags & SVF_INACTIVE ) - { +void Touch_DoorTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (ent->svFlags & SVF_INACTIVE) { return; } - if ( ent->owner->spawnflags & MOVER_LOCKED ) - {//don't even try to use the door if it's locked + if (ent->owner->spawnflags & MOVER_LOCKED) { // don't even try to use the door if it's locked return; } - if ( ent->owner->moverState != MOVER_1TO2 ) - {//Door is not already opening - //if ( ent->owner->moverState == MOVER_POS1 || ent->owner->moverState == MOVER_2TO1 ) + if (ent->owner->moverState != MOVER_1TO2) { // Door is not already opening + // if ( ent->owner->moverState == MOVER_POS1 || ent->owner->moverState == MOVER_2TO1 ) //{//only check these if closed or closing - //If door is closed, opening or open, check this - Use_BinaryMover( ent->owner, ent, other ); + // If door is closed, opening or open, check this + Use_BinaryMover(ent->owner, ent, other); } /* @@ -1214,34 +1068,31 @@ All of the parts of a door have been spawned, so create a trigger that encloses all of them ====================== */ -void Think_SpawnNewDoorTrigger( gentity_t *ent ) -{ - gentity_t *other; - vec3_t mins, maxs; - int i, best; +void Think_SpawnNewDoorTrigger(gentity_t *ent) { + gentity_t *other; + vec3_t mins, maxs; + int i, best; // set all of the slaves as shootable - if ( ent->takedamage ) - { - for ( other = ent ; other ; other = other->teamchain ) - { + if (ent->takedamage) { + for (other = ent; other; other = other->teamchain) { other->takedamage = qtrue; } } // find the bounds of everything on the team - VectorCopy (ent->absmin, mins); - VectorCopy (ent->absmax, maxs); + VectorCopy(ent->absmin, mins); + VectorCopy(ent->absmax, maxs); - for (other = ent->teamchain ; other ; other=other->teamchain) { - AddPointToBounds (other->absmin, mins, maxs); - AddPointToBounds (other->absmax, mins, maxs); + for (other = ent->teamchain; other; other = other->teamchain) { + AddPointToBounds(other->absmin, mins, maxs); + AddPointToBounds(other->absmax, mins, maxs); } // find the thinnest axis, which will be the one we expand best = 0; - for ( i = 1 ; i < 3 ; i++ ) { - if ( maxs[i] - mins[i] < maxs[best] - mins[best] ) { + for (i = 1; i < 3; i++) { + if (maxs[i] - mins[i] < maxs[best] - mins[best]) { best = i; } } @@ -1249,74 +1100,58 @@ void Think_SpawnNewDoorTrigger( gentity_t *ent ) mins[best] -= 120; // create a trigger with this size - other = G_Spawn (); - VectorCopy (mins, other->mins); - VectorCopy (maxs, other->maxs); + other = G_Spawn(); + VectorCopy(mins, other->mins); + VectorCopy(maxs, other->maxs); other->owner = ent; other->contents = CONTENTS_TRIGGER; other->e_TouchFunc = touchF_Touch_DoorTrigger; - gi.linkentity (other); + gi.linkentity(other); other->classname = "trigger_door"; - MatchTeam( ent, ent->moverState, level.time ); + MatchTeam(ent, ent->moverState, level.time); } -void Think_MatchTeam( gentity_t *ent ) -{ - MatchTeam( ent, ent->moverState, level.time ); -} +void Think_MatchTeam(gentity_t *ent) { MatchTeam(ent, ent->moverState, level.time); } -qboolean G_EntIsDoor( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_EntIsDoor(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } gentity_t *ent = &g_entities[entityNum]; - if ( ent && !Q_stricmp( "func_door", ent->classname ) ) - {//blocked by a door + if (ent && !Q_stricmp("func_door", ent->classname)) { // blocked by a door return qtrue; } return qfalse; } -gentity_t *G_FindDoorTrigger( gentity_t *ent ) -{ +gentity_t *G_FindDoorTrigger(gentity_t *ent) { gentity_t *owner = NULL; gentity_t *door = ent; - if ( door->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( door->teammaster && (door->flags&FL_TEAMSLAVE)) - { + if (door->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (door->teammaster && (door->flags & FL_TEAMSLAVE)) { door = door->teammaster; } } - if ( door->targetname ) - {//find out what is targeting it - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), door->targetname )) != NULL ) - { - if ( owner && (owner->contents&CONTENTS_TRIGGER) ) - { + if (door->targetname) { // find out what is targeting it + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), door->targetname)) != NULL) { + if (owner && (owner->contents & CONTENTS_TRIGGER)) { return owner; } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), door->targetname )) != NULL ) - { - if ( owner && (owner->contents&CONTENTS_TRIGGER) ) - { + while ((owner = G_Find(owner, FOFS(target2), door->targetname)) != NULL) { + if (owner && (owner->contents & CONTENTS_TRIGGER)) { return owner; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( classname ), "trigger_door" )) != NULL ) - { - if ( owner->owner == door ) - { + while ((owner = G_Find(owner, FOFS(classname), "trigger_door")) != NULL) { + if (owner->owner == door) { return owner; } } @@ -1324,66 +1159,50 @@ gentity_t *G_FindDoorTrigger( gentity_t *ent ) return NULL; } -qboolean G_TriggerActive( gentity_t *self ); -qboolean G_EntIsUnlockedDoor( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_TriggerActive(gentity_t *self); +qboolean G_EntIsUnlockedDoor(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } - if ( G_EntIsDoor( entityNum ) ) - { + if (G_EntIsDoor(entityNum)) { gentity_t *ent = &g_entities[entityNum]; gentity_t *owner = NULL; - if ( ent->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( ent->teammaster && (ent->flags&FL_TEAMSLAVE)) - { + if (ent->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (ent->teammaster && (ent->flags & FL_TEAMSLAVE)) { ent = ent->teammaster; } } - if ( ent->targetname ) - {//find out what is targetting it + if (ent->targetname) { // find out what is targetting it owner = NULL; - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too? + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname)) // FIXME: other triggers okay too? { - if ( G_TriggerActive( owner ) ) - { + if (G_TriggerActive(owner)) { return qtrue; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too? + while ((owner = G_Find(owner, FOFS(target2), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname)) // FIXME: other triggers okay too? { - if ( G_TriggerActive( owner ) ) - { + if (G_TriggerActive(owner)) { return qtrue; } } } return qfalse; - } - else - {//check the door's auto-created trigger instead - owner = G_FindDoorTrigger( ent ); - if ( owner && (owner->svFlags&SVF_INACTIVE) ) - {//owning auto-created trigger is inactive + } else { // check the door's auto-created trigger instead + owner = G_FindDoorTrigger(ent); + if (owner && (owner->svFlags & SVF_INACTIVE)) { // owning auto-created trigger is inactive return qfalse; } } - if ( !(ent->svFlags & SVF_INACTIVE) && //assumes that the reactivate trigger isn't right next to the door! - !ent->health && - !(ent->spawnflags & MOVER_PLAYER_USE) && - !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && - !(ent->spawnflags & MOVER_LOCKED)) - //FIXME: what about MOVER_GOODIE? + if (!(ent->svFlags & SVF_INACTIVE) && // assumes that the reactivate trigger isn't right next to the door! + !ent->health && !(ent->spawnflags & MOVER_PLAYER_USE) && !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && !(ent->spawnflags & MOVER_LOCKED)) + // FIXME: what about MOVER_GOODIE? { return qtrue; } @@ -1391,16 +1210,13 @@ qboolean G_EntIsUnlockedDoor( int entityNum ) return qfalse; } - /*QUAKED func_door (0 .5 .8) ? START_OPEN FORCE_ACTIVATE CRUSHER TOGGLE LOCKED GOODIE PLAYER_USE INACTIVE -START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors). -FORCE_ACTIVATE Can only be activated by a force push or pull -CRUSHER ? +START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when +triggered (not useful for touch or takedamage doors). FORCE_ACTIVATE Can only be activated by a force push or pull CRUSHER ? TOGGLE wait in both the start and end states for a trigger event - does NOT work on Trek doors. -LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates normally. Note that you cannot use the door again after this. -GOODIE Door will not work unless activator has a "goodie key" in his inventory -PLAYER_USE Player can use it with the use button -INACTIVE must be used by a target_activate before it can be used +LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates +normally. Note that you cannot use the door again after this. GOODIE Door will not work unless activator has a "goodie key" in his inventory PLAYER_USE +Player can use it with the use button INACTIVE must be used by a target_activate before it can be used "target" Door fires this when it starts moving from it's closed position to its open position. "opentarget" Door fires this after reaching its "open" position @@ -1421,19 +1237,17 @@ INACTIVE must be used by a target_activate before it can be used "linear" set to 1 and it will move linearly rather than with acceleration (default is 0) 0 - no sound (default) */ -void SP_func_door (gentity_t *ent) -{ - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_door(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; ent->e_BlockedFunc = blockedF_Blocked_Door; - if ( ent->spawnflags & MOVER_GOODIE ) - { - G_SoundIndex( "sound/movers/goodie_fail.wav" ); - G_SoundIndex( "sound/movers/goodie_pass.wav" ); + if (ent->spawnflags & MOVER_GOODIE) { + G_SoundIndex("sound/movers/goodie_fail.wav"); + G_SoundIndex("sound/movers/goodie_pass.wav"); } // default speed of 400 @@ -1448,65 +1262,57 @@ void SP_func_door (gentity_t *ent) ent->delay *= 1000; // default lip of 8 units - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("lip", "8", &lip); // default damage of 2 points - G_SpawnInt( "dmg", "2", &ent->damage ); - if ( ent->damage < 0 ) - { + G_SpawnInt("dmg", "2", &ent->damage); + if (ent->damage < 0) { ent->damage = 0; } // first position at start - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - gi.SetBrushModel( ent, ent->model ); - G_SetMovedir( ent->s.angles, ent->movedir ); - abs_movedir[0] = fabs( ent->movedir[0] ); - abs_movedir[1] = fabs( ent->movedir[1] ); - abs_movedir[2] = fabs( ent->movedir[2] ); - VectorSubtract( ent->maxs, ent->mins, size ); - distance = DotProduct( abs_movedir, size ) - lip; - VectorMA( ent->pos1, distance, ent->movedir, ent->pos2 ); + gi.SetBrushModel(ent, ent->model); + G_SetMovedir(ent->s.angles, ent->movedir); + abs_movedir[0] = fabs(ent->movedir[0]); + abs_movedir[1] = fabs(ent->movedir[1]); + abs_movedir[2] = fabs(ent->movedir[2]); + VectorSubtract(ent->maxs, ent->mins, size); + distance = DotProduct(abs_movedir, size) - lip; + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); // if "start_open", reverse position 1 and 2 - if ( ent->spawnflags & 1 ) - { - vec3_t temp; + if (ent->spawnflags & 1) { + vec3_t temp; - VectorCopy( ent->pos2, temp ); - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( temp, ent->pos1 ); + VectorCopy(ent->pos2, temp); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(temp, ent->pos1); } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, set up as locked until used directly - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, set up as locked until used directly + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim } - InitMover( ent ); + InitMover(ent); ent->nextthink = level.time + FRAMETIME; - if ( !(ent->flags&FL_TEAMSLAVE) ) - { + if (!(ent->flags & FL_TEAMSLAVE)) { int health; - G_SpawnInt( "health", "0", &health ); + G_SpawnInt("health", "0", &health); - if ( health ) - { + if (health) { ent->takedamage = qtrue; } - if ( !(ent->spawnflags&MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE) ) - { + if (!(ent->spawnflags & MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE)) { // non touch/shoot doors ent->e_ThinkFunc = thinkF_Think_MatchTeam; - } - else - {//locked doors still spawn a trigger + } else { // locked doors still spawn a trigger ent->e_ThinkFunc = thinkF_Think_SpawnNewDoorTrigger; } } @@ -1527,13 +1333,13 @@ Touch_Plat Don't allow decent if a living player is on it =============== */ -void Touch_Plat( gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client || other->client->ps.stats[STAT_HEALTH] <= 0 ) { +void Touch_Plat(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client || other->client->ps.stats[STAT_HEALTH] <= 0) { return; } // delay return-to-pos1 by one second - if ( ent->moverState == MOVER_POS2 ) { + if (ent->moverState == MOVER_POS2) { ent->nextthink = level.time + 1000; } } @@ -1545,17 +1351,16 @@ Touch_PlatCenterTrigger If the plat is at the bottom position, start it going up =============== */ -void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->owner->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent->owner, ent, other ); + if (ent->owner->moverState == MOVER_POS1) { + Use_BinaryMover(ent->owner, ent, other); } } - /* ================ SpawnPlatTrigger @@ -1565,9 +1370,9 @@ Elevator cars require that the trigger extend through the entire low position, not just sit on top of it. ================ */ -void SpawnPlatTrigger( gentity_t *ent ) { - gentity_t *trigger; - vec3_t tmin, tmax; +void SpawnPlatTrigger(gentity_t *ent) { + gentity_t *trigger; + vec3_t tmin, tmax; // the middle trigger will be a thin trigger just // above the starting position @@ -1584,22 +1389,21 @@ void SpawnPlatTrigger( gentity_t *ent ) { tmax[1] = ent->pos1[1] + ent->maxs[1] - 33; tmax[2] = ent->pos1[2] + ent->maxs[2] + 8; - if ( tmax[0] <= tmin[0] ) { - tmin[0] = ent->pos1[0] + (ent->mins[0] + ent->maxs[0]) *0.5; + if (tmax[0] <= tmin[0]) { + tmin[0] = ent->pos1[0] + (ent->mins[0] + ent->maxs[0]) * 0.5; tmax[0] = tmin[0] + 1; } - if ( tmax[1] <= tmin[1] ) { - tmin[1] = ent->pos1[1] + (ent->mins[1] + ent->maxs[1]) *0.5; + if (tmax[1] <= tmin[1]) { + tmin[1] = ent->pos1[1] + (ent->mins[1] + ent->maxs[1]) * 0.5; tmax[1] = tmin[1] + 1; } - VectorCopy (tmin, trigger->mins); - VectorCopy (tmax, trigger->maxs); + VectorCopy(tmin, trigger->mins); + VectorCopy(tmax, trigger->maxs); - gi.linkentity (trigger); + gi.linkentity(trigger); } - /*QUAKED func_plat (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used @@ -1614,34 +1418,34 @@ Plats are always drawn in the extended position so they will light correctly. "color" constantLight color "light" constantLight radius */ -void SP_func_plat (gentity_t *ent) { - float lip, height; +void SP_func_plat(gentity_t *ent) { + float lip, height; -// ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); -// ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); + // ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); + // ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); - VectorClear (ent->s.angles); + VectorClear(ent->s.angles); - G_SpawnFloat( "speed", "200", &ent->speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "wait", "1", &ent->wait ); - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("speed", "200", &ent->speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("wait", "1", &ent->wait); + G_SpawnFloat("lip", "8", &lip); ent->wait = 1000; // create second position - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); - if ( !G_SpawnFloat( "height", "0", &height ) ) { + if (!G_SpawnFloat("height", "0", &height)) { height = (ent->maxs[2] - ent->mins[2]) - lip; } // pos1 is the rest (bottom) position, pos2 is the top - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( ent->pos2, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(ent->pos2, ent->pos1); ent->pos1[2] -= height; - InitMover( ent ); + InitMover(ent); // touch function keeps the plat from returning while // a live player is standing on it @@ -1649,15 +1453,14 @@ void SP_func_plat (gentity_t *ent) { ent->e_BlockedFunc = blockedF_Blocked_Door; - ent->owner = ent; // so it can be treated as a door + ent->owner = ent; // so it can be treated as a door // spawn the trigger if one hasn't been custom made - if ( !ent->targetname ) { + if (!ent->targetname) { SpawnPlatTrigger(ent); } } - /* =============================================================================== @@ -1672,22 +1475,22 @@ Touch_Button =============== */ -void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent, other, other ); + if (ent->moverState == MOVER_POS1) { + Use_BinaryMover(ent, other, other); } } - /*QUAKED func_button (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used -When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again. +When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original +position where it can be triggered again. "model2" .md3 model to also draw "angle" determines the opening direction @@ -1699,38 +1502,38 @@ When a button is touched, it moves some distance in the direction of it's angle, "color" constantLight color "light" constantLight radius */ -void SP_func_button( gentity_t *ent ) { - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_button(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; -// ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); + // ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); - if ( !ent->speed ) { + if (!ent->speed) { ent->speed = 40; } - if ( !ent->wait ) { + if (!ent->wait) { ent->wait = 1; } ent->wait *= 1000; // first position - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); - G_SpawnFloat( "lip", "4", &lip ); + G_SpawnFloat("lip", "4", &lip); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); abs_movedir[0] = fabs(ent->movedir[0]); abs_movedir[1] = fabs(ent->movedir[1]); abs_movedir[2] = fabs(ent->movedir[2]); - VectorSubtract( ent->maxs, ent->mins, size ); + VectorSubtract(ent->maxs, ent->mins, size); distance = abs_movedir[0] * size[0] + abs_movedir[1] * size[1] + abs_movedir[2] * size[2] - lip; - VectorMA (ent->pos1, distance, ent->movedir, ent->pos2); + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); if (ent->health) { // shootable button @@ -1740,11 +1543,9 @@ void SP_func_button( gentity_t *ent ) { ent->e_TouchFunc = touchF_Touch_Button; } - InitMover( ent ); + InitMover(ent); } - - /* =============================================================================== @@ -1753,10 +1554,9 @@ TRAIN =============================================================================== */ - -#define TRAIN_START_ON 1 -#define TRAIN_TOGGLE 2 -#define TRAIN_BLOCK_STOPS 4 +#define TRAIN_START_ON 1 +#define TRAIN_TOGGLE 2 +#define TRAIN_BLOCK_STOPS 4 /* =============== @@ -1765,21 +1565,17 @@ Think_BeginMoving The wait time at a corner has completed, so start moving again =============== */ -void Think_BeginMoving( gentity_t *ent ) { +void Think_BeginMoving(gentity_t *ent) { - if ( ent->spawnflags & 2048 ) - { + if (ent->spawnflags & 2048) { // this tie fighter hack is done for doom_detention, where the shooting gallery takes place. let them draw again when they start moving ent->s.eFlags &= ~EF_NODRAW; } ent->s.pos.trTime = level.time; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } } @@ -1789,136 +1585,117 @@ void Think_BeginMoving( gentity_t *ent ) { Reached_Train =============== */ -void Reached_Train( gentity_t *ent ) { - gentity_t *next; - float speed; - vec3_t move; - float length; +void Reached_Train(gentity_t *ent) { + gentity_t *next; + float speed; + vec3_t move; + float length; // copy the apropriate values next = ent->nextTrain; - if ( !next || !next->nextTrain ) { - //FIXME: can we go backwards- say if we are toggle-able? - return; // just stop + if (!next || !next->nextTrain) { + // FIXME: can we go backwards- say if we are toggle-able? + return; // just stop } // fire all other targets - G_UseTargets( next, ent ); + G_UseTargets(next, ent); // set the new trajectory ent->nextTrain = next->nextTrain; - VectorCopy( next->s.origin, ent->pos1 ); - VectorCopy( next->nextTrain->s.origin, ent->pos2 ); + VectorCopy(next->s.origin, ent->pos1); + VectorCopy(next->nextTrain->s.origin, ent->pos2); // if the path_corner has a speed, use that - if ( next->speed ) { + if (next->speed) { speed = next->speed; } else { // otherwise use the train's speed speed = ent->speed; } - if ( speed < 1 ) { + if (speed < 1) { speed = 1; } // calculate duration - VectorSubtract( ent->pos2, ent->pos1, move ); - length = VectorLength( move ); + VectorSubtract(ent->pos2, ent->pos1, move); + length = VectorLength(move); ent->s.pos.trDuration = length * 1000 / speed; // looping sound -/* - if ( VALIDSTRING( next->soundSet ) ) - { - ent->s.loopSound = CAS_GetBModelSound( next->soundSet, BMS_MID );//ent->soundLoop; - } -*/ - G_PlayDoorLoopSound( ent ); + /* + if ( VALIDSTRING( next->soundSet ) ) + { + ent->s.loopSound = CAS_GetBModelSound( next->soundSet, BMS_MID );//ent->soundLoop; + } + */ + G_PlayDoorLoopSound(ent); // start it going - SetMoverState( ent, MOVER_1TO2, level.time ); + SetMoverState(ent, MOVER_1TO2, level.time); - if (( next->spawnflags & 1 )) - { + if ((next->spawnflags & 1)) { vec3_t angs; - vectoangles( move, angs ); - AnglesSubtract( angs, ent->currentAngles, angs ); + vectoangles(move, angs); + AnglesSubtract(angs, ent->currentAngles, angs); - for ( int i = 0; i < 3; i++ ) - { - AngleNormalize360( angs[i] ); + for (int i = 0; i < 3; i++) { + AngleNormalize360(angs[i]); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorScale( angs, 0.5f, ent->s.apos.trDelta ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorScale(angs, 0.5f, ent->s.apos.trDelta); ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 2000; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } - } - else - { - if (( next->spawnflags & 4 )) - {//yaw + } else { + if ((next->spawnflags & 4)) { // yaw vec3_t angs; - vectoangles( move, angs ); - AnglesSubtract( angs, ent->currentAngles, angs ); + vectoangles(move, angs); + AnglesSubtract(angs, ent->currentAngles, angs); - for ( int i = 0; i < 3; i++ ) - { - AngleNormalize360( angs[i] ); + for (int i = 0; i < 3; i++) { + AngleNormalize360(angs[i]); } - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trDelta[YAW] = angs[YAW] * 0.5f; - if (( next->spawnflags & 8 )) - {//roll, too + if ((next->spawnflags & 8)) { // roll, too ent->s.apos.trDelta[ROLL] = angs[YAW] * -0.1f; } ent->s.apos.trTime = level.time; ent->s.apos.trDuration = 2000; - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } } } - // This is for the tie fighter shooting gallery on doom detention, you could see them waiting under the bay, but the architecture couldn't easily be changed.. - if (( next->spawnflags & 2 )) - { + // This is for the tie fighter shooting gallery on doom detention, you could see them waiting under the bay, but the architecture couldn't easily be + // changed.. + if ((next->spawnflags & 2)) { ent->s.eFlags |= EF_NODRAW; // make us invisible until we start moving again } // if there is a "wait" value on the target, don't start moving yet - if ( next->wait ) - { + if (next->wait) { ent->nextthink = level.time + next->wait * 1000; ent->e_ThinkFunc = thinkF_Think_BeginMoving; ent->s.pos.trType = TR_STATIONARY; - } - else if (!( next->spawnflags & 2 )) - { + } else if (!(next->spawnflags & 2)) { // we aren't waiting to start, so let us draw right away ent->s.eFlags &= ~EF_NODRAW; } } -void TrainUse( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - Reached_Train( ent ); -} +void TrainUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { Reached_Train(ent); } /* =============== @@ -1927,32 +1704,31 @@ Think_SetupTrainTargets Link all the corners together =============== */ -void Think_SetupTrainTargets( gentity_t *ent ) { - gentity_t *path, *next, *start; - - ent->nextTrain = G_Find( NULL, FOFS(targetname), ent->target ); - if ( !ent->nextTrain ) { - gi.Printf( "func_train at %s with an unfound target\n", - vtos(ent->absmin) ); - //Free me?` +void Think_SetupTrainTargets(gentity_t *ent) { + gentity_t *path, *next, *start; + + ent->nextTrain = G_Find(NULL, FOFS(targetname), ent->target); + if (!ent->nextTrain) { + gi.Printf("func_train at %s with an unfound target\n", vtos(ent->absmin)); + // Free me?` return; } - //FIXME: this can go into an infinite loop if last path_corner doesn't link to first - //path_corner, like so: - // t1---->t2---->t3 - // ^ | - // \_____| + // FIXME: this can go into an infinite loop if last path_corner doesn't link to first + // path_corner, like so: + // t1---->t2---->t3 + // ^ | + // \_____| start = NULL; - for ( path = ent->nextTrain ; path != start ; path = next ) { - if ( !start ) { + for (path = ent->nextTrain; path != start; path = next) { + if (!start) { start = path; } - if ( !path->target ) { -// gi.Printf( "Train corner at %s without a target\n", -// vtos(path->s.origin) ); - //end of path + if (!path->target) { + // gi.Printf( "Train corner at %s without a target\n", + // vtos(path->s.origin) ); + // end of path break; } @@ -1961,38 +1737,30 @@ void Think_SetupTrainTargets( gentity_t *ent ) { // is reached next = NULL; do { - next = G_Find( next, FOFS(targetname), path->target ); - if ( !next ) { -// gi.Printf( "Train corner at %s without a target path_corner\n", -// vtos(path->s.origin) ); - //end of path + next = G_Find(next, FOFS(targetname), path->target); + if (!next) { + // gi.Printf( "Train corner at %s without a target path_corner\n", + // vtos(path->s.origin) ); + // end of path break; } - } while ( strcmp( next->classname, "path_corner" ) ); + } while (strcmp(next->classname, "path_corner")); - if ( next ) - { + if (next) { path->nextTrain = next; - } - else - { + } else { break; } } - if ( !ent->targetname || (ent->spawnflags&1) /*start on*/) - { + if (!ent->targetname || (ent->spawnflags & 1) /*start on*/) { // start the train moving from the first corner - Reached_Train( ent ); - } - else - { - G_SetOrigin( ent, ent->s.origin ); + Reached_Train(ent); + } else { + G_SetOrigin(ent, ent->s.origin); } } - - /*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8) TURN_TRAIN INVISIBLE YAW_TRAIN ROLL_TRAIN TURN_TRAIN func_train moving on this path will turn to face the next path_corner within 2 seconds @@ -2004,28 +1772,25 @@ Target: next path corner and other targets to fire "speed" speed to move to the next corner "wait" seconds to wait before behining move to next corner */ -void SP_path_corner( gentity_t *self ) { - if ( !self->targetname ) { - gi.Printf ("path_corner with no targetname at %s\n", vtos(self->s.origin)); - G_FreeEntity( self ); +void SP_path_corner(gentity_t *self) { + if (!self->targetname) { + gi.Printf("path_corner with no targetname at %s\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } // path corners don't need to be linked in VectorCopy(self->s.origin, self->currentOrigin); } - -void func_train_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - if ( self->target3 ) - { - G_UseTargets2( self, self, self->target3 ); +void func_train_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (self->target3) { + G_UseTargets2(self, self, self->target3); } - //HACKHACKHACKHACK - G_PlayEffect( "fighter_explosion2", self->currentOrigin ); - G_FreeEntity( self ); - //HACKHACKHACKHACK + // HACKHACKHACKHACK + G_PlayEffect("fighter_explosion2", self->currentOrigin); + G_FreeEntity(self); + // HACKHACKHACKHACK } /*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS x x LOOP PLAYER_USE INACTIVE TIE @@ -2052,8 +1817,8 @@ The train spawns at the first target it is pointing at. "startframe" default 0...ghoul2 animation start frame "endframe" default 0...ghoul2 animation end frame */ -void SP_func_train (gentity_t *self) { - VectorClear (self->s.angles); +void SP_func_train(gentity_t *self) { + VectorClear(self->s.angles); if (self->spawnflags & TRAIN_BLOCK_STOPS) { self->damage = 0; @@ -2063,49 +1828,46 @@ void SP_func_train (gentity_t *self) { } } - if ( !self->speed ) { + if (!self->speed) { self->speed = 100; } - if ( !self->target ) { - gi.Printf ("func_train without a target at %s\n", vtos(self->absmin)); - G_FreeEntity( self ); + if (!self->target) { + gi.Printf("func_train without a target at %s\n", vtos(self->absmin)); + G_FreeEntity(self); return; } char *noise; - G_SpawnInt( "startframe", "0", &self->startFrame ); - G_SpawnInt( "endframe", "0", &self->endFrame ); + G_SpawnInt("startframe", "0", &self->startFrame); + G_SpawnInt("endframe", "0", &self->endFrame); - if ( G_SpawnString( "noise", "", &noise ) ) - { - if ( VALIDSTRING( noise ) ) - { - self->s.loopSound = cgi_S_RegisterSound( noise );//G_SoundIndex( noise ); + if (G_SpawnString("noise", "", &noise)) { + if (VALIDSTRING(noise)) { + self->s.loopSound = cgi_S_RegisterSound(noise); // G_SoundIndex( noise ); } } - gi.SetBrushModel( self, self->model ); - InitMover( self ); + gi.SetBrushModel(self, self->model); + InitMover(self); - if ( self->spawnflags & 2048 ) // TIE HACK + if (self->spawnflags & 2048) // TIE HACK { - //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK - self->s.modelindex2 = G_ModelIndex( "models/map_objects/ships/tie_fighter.md3" ); - G_EffectIndex( "fighter_explosion2" ); + // HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK + self->s.modelindex2 = G_ModelIndex("models/map_objects/ships/tie_fighter.md3"); + G_EffectIndex("fighter_explosion2"); self->contents = CONTENTS_SHOTCLIP; self->takedamage = qtrue; - VectorSet( self->maxs, 112, 112, 112 ); - VectorSet( self->mins, -112, -112, -112 ); - self->e_DieFunc = dieF_func_train_die; - gi.linkentity( self ); - //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK + VectorSet(self->maxs, 112, 112, 112); + VectorSet(self->mins, -112, -112, -112); + self->e_DieFunc = dieF_func_train_die; + gi.linkentity(self); + // HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK } - if ( self->targetname ) - { + if (self->targetname) { self->e_UseFunc = useF_TrainUse; } @@ -2116,12 +1878,13 @@ void SP_func_train (gentity_t *self) { self->nextthink = level.time + START_TIME_LINK_ENTS; self->e_ThinkFunc = thinkF_Think_SetupTrainTargets; - - if ( self->playerModel >= 0 && self->spawnflags & 32 ) // loop...dunno, could support it on other things, but for now I need it for the glider...so...kill the flag + if (self->playerModel >= 0 && + self->spawnflags & 32) // loop...dunno, could support it on other things, but for now I need it for the glider...so...kill the flag { self->spawnflags &= ~32; // once only - gi.G2API_SetBoneAnim( &self->ghoul2[self->playerModel], "model_root", self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_LOOP, 1.0f + Q_flrand(-1.0f, 1.0f) * 0.1f, 0, -1, -1 ); + gi.G2API_SetBoneAnim(&self->ghoul2[self->playerModel], "model_root", self->startFrame, self->endFrame, BONE_ANIM_OVERRIDE_LOOP, + 1.0f + Q_flrand(-1.0f, 1.0f) * 0.1f, 0, -1, -1); self->endFrame = 0; // don't allow it to do anything with the animation function in G_main } } @@ -2151,43 +1914,38 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls "dmg" how much damage to do when it crushes (use with CRUSHER spawnflag) "linear" set to 1 and it will move linearly rather than with acceleration (default is 0) */ -void SP_func_static( gentity_t *ent ) -{ - gi.SetBrushModel( ent, ent->model ); +void SP_func_static(gentity_t *ent) { + gi.SetBrushModel(ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); + InitMover(ent); ent->e_UseFunc = useF_func_static_use; ent->e_ReachedFunc = reachedF_NULL; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - if( ent->spawnflags & 2048 ) - { // yes this is very very evil, but for now (pre-alpha) it's a solution + if (ent->spawnflags & 2048) { // yes this is very very evil, but for now (pre-alpha) it's a solution ent->svFlags |= SVF_BROADCAST; // I need to rotate something that is huge and it's touching too many area portals... } - if ( ent->spawnflags & 4/*SWITCH_SHADER*/ ) - { - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim + if (ent->spawnflags & 4 /*SWITCH_SHADER*/) { + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim } - gi.linkentity( ent ); + gi.linkentity(ent); } -void func_static_use ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior( self, BSET_USE ); +void func_static_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 4/*SWITCH_SHADER*/ ) - { - self->s.frame = self->s.frame ? 0 : 1;//toggle frame + if (self->spawnflags & 4 /*SWITCH_SHADER*/) { + self->s.frame = self->s.frame ? 0 : 1; // toggle frame } - G_UseTargets( self, activator ); + G_UseTargets(self, activator); } /* @@ -2197,49 +1955,40 @@ ROTATING =============================================================================== */ -void func_rotating_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ -// vec3_t spot; -// gentity_t *tent; - if( !other->client ) // don't want to disintegrate items or weapons, etc... +void func_rotating_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + // vec3_t spot; + // gentity_t *tent; + if (!other->client) // don't want to disintegrate items or weapons, etc... { return; } // yeah, this is a bit hacky... - if( self->s.apos.trType != TR_STATIONARY && !(other->flags & FL_DISINTEGRATED) ) // only damage if it's moving + if (self->s.apos.trType != TR_STATIONARY && !(other->flags & FL_DISINTEGRATED)) // only damage if it's moving { -// VectorCopy( self->currentOrigin, spot ); -// tent = G_TempEntity( spot, EV_DISINTEGRATION ); -// tent->s.eventParm = PW_DISRUPTION; -// tent->owner = self; + // VectorCopy( self->currentOrigin, spot ); + // tent = G_TempEntity( spot, EV_DISINTEGRATION ); + // tent->s.eventParm = PW_DISRUPTION; + // tent->owner = self; // let G_Damage call the fx instead, beside, this way you can disintegrate a corpse this way - G_Sound( other, G_SoundIndex( "sound/effects/energy_crackle.wav" ) ); - G_Damage( other, self, self, NULL, NULL, 10000, DAMAGE_NO_KNOCKBACK, MOD_SNIPER ); + G_Sound(other, G_SoundIndex("sound/effects/energy_crackle.wav")); + G_Damage(other, self, self, NULL, NULL, 10000, DAMAGE_NO_KNOCKBACK, MOD_SNIPER); } } - -void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if( self->s.apos.trType == TR_LINEAR ) - { +void func_rotating_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->s.apos.trType == TR_LINEAR) { self->s.apos.trType = TR_STATIONARY; // stop the sound if it stops moving self->s.loopSound = 0; // play stop sound too? - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_END )); + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_END)); } - } - else - { - if ( VALIDSTRING( self->soundSet ) == true ) - { - G_AddEvent( self, EV_BMODEL_SOUND, CAS_GetBModelSound( self->soundSet, BMS_START )); - self->s.loopSound = CAS_GetBModelSound( self->soundSet, BMS_MID ); - if ( self->s.loopSound < 0 ) - { + } else { + if (VALIDSTRING(self->soundSet) == true) { + G_AddEvent(self, EV_BMODEL_SOUND, CAS_GetBModelSound(self->soundSet, BMS_START)); + self->s.loopSound = CAS_GetBModelSound(self->soundSet, BMS_MID); + if (self->s.loopSound < 0) { self->s.loopSound = 0; } } @@ -2247,7 +1996,6 @@ void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator } } - /*QUAKED func_rotating (0 .5 .8) ? START_ON TOUCH_KILL X_AXIS Y_AXIS x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button TOUCH_KILL Inflicts massive damage upon touching it, disitegrates bodies @@ -2263,21 +2011,20 @@ check either the X_AXIS or Y_AXIS box to change that. "color" constantLight color "light" constantLight radius */ -void SP_func_rotating (gentity_t *ent) { - if ( !ent->speed ) { +void SP_func_rotating(gentity_t *ent) { + if (!ent->speed) { ent->speed = 100; } - ent->s.apos.trType = TR_STATIONARY; - if( ent->spawnflags & 1 ) // start on + if (ent->spawnflags & 1) // start on { ent->s.apos.trType = TR_LINEAR; } // set the axis of rotation - if ( ent->spawnflags & 4 ) { + if (ent->spawnflags & 4) { ent->s.apos.trDelta[2] = ent->speed; - } else if ( ent->spawnflags & 8 ) { + } else if (ent->spawnflags & 8) { ent->s.apos.trDelta[0] = ent->speed; } else { ent->s.apos.trDelta[1] = ent->speed; @@ -2287,28 +2034,24 @@ void SP_func_rotating (gentity_t *ent) { ent->damage = 2; } + gi.SetBrushModel(ent, ent->model); + InitMover(ent); - gi.SetBrushModel( ent, ent->model ); - InitMover( ent ); - - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_func_rotating_use; } - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); - VectorCopy( ent->s.apos.trBase, ent->currentAngles ); - if( ent->spawnflags & 2 ) - { + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); + VectorCopy(ent->s.apos.trBase, ent->currentAngles); + if (ent->spawnflags & 2) { ent->e_TouchFunc = touchF_func_rotating_touch; - G_SoundIndex( "sound/effects/energy_crackle.wav" ); + G_SoundIndex("sound/effects/energy_crackle.wav"); } - gi.linkentity( ent ); + gi.linkentity(ent); } - /* =============================================================================== @@ -2317,26 +2060,22 @@ BOBBING =============================================================================== */ -void func_bobbing_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void func_bobbing_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle our move state - if ( self->s.pos.trType == TR_SINE ) - { + if (self->s.pos.trType == TR_SINE) { self->s.pos.trType = TR_INTERPOLATE; // Save off roughly where we were - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); // Store the current phase value so we know how to start up where we left off. - self->radius = ( level.time - self->s.pos.trTime ) / (float)self->s.pos.trDuration; - } - else - { + self->radius = (level.time - self->s.pos.trTime) / (float)self->s.pos.trDuration; + } else { self->s.pos.trType = TR_SINE; // Set the time based on the saved phase value self->s.pos.trTime = level.time - self->s.pos.trDuration * self->radius; // Always make sure we are starting with a fresh base - VectorCopy( self->s.origin, self->s.pos.trBase ); + VectorCopy(self->s.origin, self->s.pos.trBase); } } @@ -2354,25 +2093,25 @@ Normally bobs on the Z axis "light" constantLight radius "targetname" turns on/off when used */ -void SP_func_bobbing (gentity_t *ent) { - float height; - float phase; +void SP_func_bobbing(gentity_t *ent) { + float height; + float phase; - G_SpawnFloat( "speed", "4", &ent->speed ); - G_SpawnFloat( "height", "32", &height ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "4", &ent->speed); + G_SpawnFloat("height", "32", &height); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - gi.SetBrushModel( ent, ent->model ); - InitMover( ent ); + gi.SetBrushModel(ent, ent->model); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // set the axis of bobbing - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.pos.trDelta[0] = height; - } else if ( ent->spawnflags & 2 ) { + } else if (ent->spawnflags & 2) { ent->s.pos.trDelta[1] = height; } else { ent->s.pos.trDelta[2] = height; @@ -2381,22 +2120,19 @@ void SP_func_bobbing (gentity_t *ent) { ent->s.pos.trDuration = ent->speed * 1000; ent->s.pos.trTime = ent->s.pos.trDuration * phase; - if ( ent->spawnflags & 4 ) // start_off + if (ent->spawnflags & 4) // start_off { ent->s.pos.trType = TR_INTERPOLATE; // Now use the phase to calculate where it should be at the start. ent->radius = phase; - phase = (float)sin( phase * M_PI * 2 ); - VectorMA( ent->s.pos.trBase, phase, ent->s.pos.trDelta, ent->s.pos.trBase ); + phase = (float)sin(phase * M_PI * 2); + VectorMA(ent->s.pos.trBase, phase, ent->s.pos.trDelta, ent->s.pos.trBase); - if ( ent->targetname ) - { + if (ent->targetname) { ent->e_UseFunc = useF_func_bobbing_use; } - } - else - { + } else { ent->s.pos.trType = TR_SINE; } } @@ -2409,7 +2145,6 @@ PENDULUM =============================================================================== */ - /*QUAKED func_pendulum (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used @@ -2425,33 +2160,33 @@ Pendulum frequency is a physical constant based on the length of the beam and gr "light" constantLight radius */ void SP_func_pendulum(gentity_t *ent) { - float freq; - float length; - float phase; - float speed; + float freq; + float length; + float phase; + float speed; - G_SpawnFloat( "speed", "30", &speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "30", &speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); // find pendulum length - length = fabs( ent->mins[2] ); - if ( length < 8 ) { + length = fabs(ent->mins[2]); + if (length < 8) { length = 8; } - freq = 1 / ( M_PI * 2 ) * sqrt( g_gravity->value / ( 3 * length ) ); + freq = 1 / (M_PI * 2) * sqrt(g_gravity->value / (3 * length)); - ent->s.pos.trDuration = ( 1000 / freq ); + ent->s.pos.trDuration = (1000 / freq); - InitMover( ent ); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->s.apos.trDuration = 1000 / freq; ent->s.apos.trTime = ent->s.apos.trDuration * phase; @@ -2468,38 +2203,32 @@ WALL =============================================================================== */ -//static -slc -void use_wall( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +// static -slc +void use_wall(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); // Not there so make it there - if (!(ent->contents & CONTENTS_SOLID)) - { + if (!(ent->contents & CONTENTS_SOLID)) { ent->svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; ent->contents = CONTENTS_SOLID; - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( ent, qfalse ); + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(ent, qfalse); } } // Make it go away - else - { + else { ent->contents = 0; ent->svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( ent, qtrue ); + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(ent, qtrue); } } } -#define FUNC_WALL_OFF 1 -#define FUNC_WALL_ANIM 2 - +#define FUNC_WALL_OFF 1 +#define FUNC_WALL_ANIM 2 /*QUAKED func_wall (0 .5 .8) ? START_OFF AUTOANIMATE x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button @@ -2513,74 +2242,60 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls START_OFF - the wall will not be there AUTOANIMATE - if a model is used it will animate */ -void SP_func_wall( gentity_t *ent ) -{ - gi.SetBrushModel( ent, ent->model ); +void SP_func_wall(gentity_t *ent) { + gi.SetBrushModel(ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + InitMover(ent); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // it must be START_OFF - if (ent->spawnflags & FUNC_WALL_OFF) - { + if (ent->spawnflags & FUNC_WALL_OFF) { ent->contents = 0; ent->svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; } - if (!(ent->spawnflags & FUNC_WALL_ANIM)) - { + if (!(ent->spawnflags & FUNC_WALL_ANIM)) { ent->s.eFlags |= EF_ANIM_ALLFAST; } ent->e_UseFunc = useF_use_wall; - gi.linkentity (ent); - + gi.linkentity(ent); } - -void security_panel_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( !activator ) - { +void security_panel_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator) { return; } - if ( INV_SecurityKeyCheck( activator, self->message ) ) - {//congrats! - gi.SendServerCommand( 0, "cp @INGAME_SECURITY_KEY_UNLOCKEDDOOR" ); - //use targets - G_UseTargets( self, activator ); - //take key - INV_SecurityKeyTake( activator, self->message ); - if ( activator->ghoul2.size() ) - { - gi.G2API_SetSurfaceOnOff( &activator->ghoul2[activator->playerModel], "l_arm_key", 0x00000002 ); - } - //FIXME: maybe set frame on me to have key sticking out? - //self->s.frame = 1; - //play sound - G_Sound( self, self->soundPos2 ); - //unusable + if (INV_SecurityKeyCheck(activator, self->message)) { // congrats! + gi.SendServerCommand(0, "cp @INGAME_SECURITY_KEY_UNLOCKEDDOOR"); + // use targets + G_UseTargets(self, activator); + // take key + INV_SecurityKeyTake(activator, self->message); + if (activator->ghoul2.size()) { + gi.G2API_SetSurfaceOnOff(&activator->ghoul2[activator->playerModel], "l_arm_key", 0x00000002); + } + // FIXME: maybe set frame on me to have key sticking out? + // self->s.frame = 1; + // play sound + G_Sound(self, self->soundPos2); + // unusable self->e_UseFunc = useF_NULL; - } - else - {//failure sound/display - if ( activator->message ) - {//have a key, just the wrong one - gi.SendServerCommand( 0, "cp @INGAME_INCORRECT_KEY" ); - } - else - {//don't have a key at all - gi.SendServerCommand( 0, "cp @INGAME_NEED_SECURITY_KEY" ); - } - G_UseTargets2( self, activator, self->target2 ); - //FIXME: change display? Maybe shader animmap change? - //play sound - G_Sound( self, self->soundPos1 ); + } else { // failure sound/display + if (activator->message) { // have a key, just the wrong one + gi.SendServerCommand(0, "cp @INGAME_INCORRECT_KEY"); + } else { // don't have a key at all + gi.SendServerCommand(0, "cp @INGAME_NEED_SECURITY_KEY"); + } + G_UseTargets2(self, activator, self->target2); + // FIXME: change display? Maybe shader animmap change? + // play sound + G_Sound(self, self->soundPos1); } } @@ -2594,22 +2309,20 @@ INACTIVE - Start off, has to be activated to be usable "target" thing to use when successfully opened "target2" thing to use when player uses the panel without the key */ -void SP_misc_security_panel ( gentity_t *self ) -{ - self->s.modelindex = G_ModelIndex( "models/map_objects/kejim/sec_panel.md3" ); - self->soundPos1 = G_SoundIndex( "sound/movers/sec_panel_fail.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/sec_panel_pass.mp3" ); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); - VectorSet( self->mins, -8, -8, -8 ); - VectorSet( self->maxs, 8, 8, 8 ); +void SP_misc_security_panel(gentity_t *self) { + self->s.modelindex = G_ModelIndex("models/map_objects/kejim/sec_panel.md3"); + self->soundPos1 = G_SoundIndex("sound/movers/sec_panel_fail.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/sec_panel_pass.mp3"); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); + VectorSet(self->mins, -8, -8, -8); + VectorSet(self->maxs, 8, 8, 8); self->contents = CONTENTS_SOLID; - gi.linkentity( self ); + gi.linkentity(self); - //NOTE: self->message is the key + // NOTE: self->message is the key self->svFlags |= SVF_PLAYER_USABLE; - if(self->spawnflags & 128) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } self->e_UseFunc = useF_security_panel_use; diff --git a/codeJK2/game/g_nav.cpp b/codeJK2/game/g_nav.cpp index 15cb157c59..18f0275ecd 100644 --- a/codeJK2/game/g_nav.cpp +++ b/codeJK2/game/g_nav.cpp @@ -26,69 +26,63 @@ along with this program; if not, see . #include "g_nav.h" #include "g_navigator.h" -//Global navigator -CNavigator navigator; - -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean G_EntIsBreakable( int entityNum ); -extern qboolean G_EntIsRemovableUsable( int entNum ); -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -//For debug graphics -extern void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ); -extern qboolean FlyingCreature( gentity_t *ent ); - -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ); -void NAV_StoreWaypoint( gentity_t *ent ); +// Global navigator +CNavigator navigator; + +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean G_EntIsBreakable(int entityNum); +extern qboolean G_EntIsRemovableUsable(int entNum); +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +// For debug graphics +extern void CG_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha); +extern qboolean FlyingCreature(gentity_t *ent); + +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask); +void NAV_StoreWaypoint(gentity_t *ent); extern vec3_t NPCDEBUG_RED; - /* ------------------------- NPC_Blocked ------------------------- */ - -void NPC_Blocked( gentity_t *self, gentity_t *blocker ) -{ - if ( self->NPC == NULL ) +void NPC_Blocked(gentity_t *self, gentity_t *blocker) { + if (self->NPC == NULL) return; - //Don't do this too often - if ( self->NPC->blockedSpeechDebounceTime > level.time ) + // Don't do this too often + if (self->NPC->blockedSpeechDebounceTime > level.time) return; - //Attempt to run any blocked scripts - if ( G_ActivateBehavior( self, BSET_BLOCKED ) ) - { + // Attempt to run any blocked scripts + if (G_ActivateBehavior(self, BSET_BLOCKED)) { return; } - //If this is one of our enemies, then just attack him - if ( blocker->client && ( blocker->client->playerTeam == self->client->enemyTeam ) ) - { - G_SetEnemy( self, blocker ); + // If this is one of our enemies, then just attack him + if (blocker->client && (blocker->client->playerTeam == self->client->enemyTeam)) { + G_SetEnemy(self, blocker); return; } - Debug_Printf( debugNPCAI, DEBUG_LEVEL_WARNING, "%s: Excuse me, %s %s!\n", self->targetname, blocker->classname, blocker->targetname ); + Debug_Printf(debugNPCAI, DEBUG_LEVEL_WARNING, "%s: Excuse me, %s %s!\n", self->targetname, blocker->classname, blocker->targetname); - //If we're being blocked by the player, say something to them - if ( ( blocker->s.number == 0 ) && ( ( blocker->client->playerTeam == self->client->playerTeam ) ) ) - { - //guys in formation are not trying to get to a critical point, - //don't make them yell at the player (unless they have an enemy and - //are in combat because BP thinks it sounds cool during battle) - //NOTE: only imperials, misc crewmen and hazard team have these wav files now - //G_AddVoiceEvent( self, Q_irand(EV_BLOCKED1, EV_BLOCKED3), 0 ); + // If we're being blocked by the player, say something to them + if ((blocker->s.number == 0) && ((blocker->client->playerTeam == self->client->playerTeam))) { + // guys in formation are not trying to get to a critical point, + // don't make them yell at the player (unless they have an enemy and + // are in combat because BP thinks it sounds cool during battle) + // NOTE: only imperials, misc crewmen and hazard team have these wav files now + // G_AddVoiceEvent( self, Q_irand(EV_BLOCKED1, EV_BLOCKED3), 0 ); } - self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + ( Q_flrand(0.0f, 1.0f) * 4000 ); + self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + (Q_flrand(0.0f, 1.0f) * 4000); self->NPC->blockingEntNum = blocker->s.number; } @@ -98,42 +92,35 @@ NPC_SetMoveGoal ------------------------- */ -void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt ) -{ - //Must be an NPC - if ( ent->NPC == NULL ) - { +void NPC_SetMoveGoal(gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt) { + // Must be an NPC + if (ent->NPC == NULL) { return; } - if ( ent->NPC->tempGoal == NULL ) - {//must still have a goal + if (ent->NPC->tempGoal == NULL) { // must still have a goal return; } - //Copy the origin - //VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! - VectorCopy( point, ent->NPC->tempGoal->currentOrigin ); + // Copy the origin + // VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! + VectorCopy(point, ent->NPC->tempGoal->currentOrigin); - //Copy the mins and maxs to the tempGoal - VectorCopy( ent->mins, ent->NPC->tempGoal->mins ); - VectorCopy( ent->mins, ent->NPC->tempGoal->maxs ); + // Copy the mins and maxs to the tempGoal + VectorCopy(ent->mins, ent->NPC->tempGoal->mins); + VectorCopy(ent->mins, ent->NPC->tempGoal->maxs); ent->NPC->tempGoal->target = NULL; ent->NPC->tempGoal->clipmask = ent->clipmask; ent->NPC->tempGoal->svFlags &= ~SVF_NAVGOAL; - if ( targetEnt && targetEnt->waypoint >= 0 ) - { + if (targetEnt && targetEnt->waypoint >= 0) { ent->NPC->tempGoal->waypoint = targetEnt->waypoint; - } - else - { + } else { ent->NPC->tempGoal->waypoint = WAYPOINT_NONE; } ent->NPC->tempGoal->noWaypointTime = 0; - if ( isNavGoal ) - { + if (isNavGoal) { assert(ent->NPC->tempGoal->owner); ent->NPC->tempGoal->svFlags |= SVF_NAVGOAL; } @@ -144,7 +131,7 @@ void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGo ent->NPC->goalEntity = ent->NPC->tempGoal; ent->NPC->goalRadius = radius; - gi.linkentity( ent->NPC->goalEntity ); + gi.linkentity(ent->NPC->goalEntity); } /* @@ -153,52 +140,44 @@ NAV_HitNavGoal ------------------------- */ -qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying ) -{ - vec3_t dmins, dmaxs, pmins, pmaxs; +qboolean NAV_HitNavGoal(vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying) { + vec3_t dmins, dmaxs, pmins, pmaxs; - if ( radius & NAVGOAL_USE_RADIUS ) - { + if (radius & NAVGOAL_USE_RADIUS) { radius &= ~NAVGOAL_USE_RADIUS; - //NOTE: This needs to do a DistanceSquared on navgoals that had + // NOTE: This needs to do a DistanceSquared on navgoals that had // a radius manually set! We can't do the smaller navgoals against // walls to get around this because player-sized traces to them // from angles will not work... - MCG - if ( !flying ) - {//Allow for a little z difference - vec3_t diff; - VectorSubtract( point, dest, diff ); - if ( fabs(diff[2]) <= 24 ) - { + if (!flying) { // Allow for a little z difference + vec3_t diff; + VectorSubtract(point, dest, diff); + if (fabs(diff[2]) <= 24) { diff[2] = 0; } - return (qboolean)( VectorLengthSquared( diff ) <= (radius*radius) ); + return (qboolean)(VectorLengthSquared(diff) <= (radius * radius)); + } else { // must hit exactly + return (qboolean)(DistanceSquared(dest, point) <= (radius * radius)); } - else - {//must hit exactly - return (qboolean)( DistanceSquared(dest, point) <= (radius*radius) ); - } - //There is probably a better way to do this, either by preserving the original + // There is probably a better way to do this, either by preserving the original // mins and maxs of the navgoal and doing this check ONLY if the radius // is non-zero (like the original implementation) or some boolean to // tell us to do this check rather than the fake bbox overlap check... - } - else - { - //Construct a dummy bounding box from our radius value - VectorSet( dmins, -radius, -radius, -radius ); - VectorSet( dmaxs, radius, radius, radius ); + } else { + // Construct a dummy bounding box from our radius value + VectorSet(dmins, -radius, -radius, -radius); + VectorSet(dmaxs, radius, radius, radius); - //Translate it - VectorAdd( dmins, dest, dmins ); - VectorAdd( dmaxs, dest, dmaxs ); + // Translate it + VectorAdd(dmins, dest, dmins); + VectorAdd(dmaxs, dest, dmaxs); - //Translate the starting box - VectorAdd( point, mins, pmins ); - VectorAdd( point, maxs, pmaxs ); + // Translate the starting box + VectorAdd(point, mins, pmins); + VectorAdd(point, maxs, pmaxs); - //See if they overlap - return G_BoundsOverlap( pmins, pmaxs, dmins, dmaxs ); + // See if they overlap + return G_BoundsOverlap(pmins, pmaxs, dmins, dmaxs); } } @@ -208,124 +187,102 @@ NAV_ClearPathToPoint ------------------------- */ -qboolean NAV_ClearPathToPoint( gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum ) -{ -// trace_t trace; -// return NAV_CheckAhead( self, point, trace, clipmask|CONTENTS_BOTCLIP ); +qboolean NAV_ClearPathToPoint(gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum) { + // trace_t trace; + // return NAV_CheckAhead( self, point, trace, clipmask|CONTENTS_BOTCLIP ); - vec3_t mins, maxs; - trace_t trace; + vec3_t mins, maxs; + trace_t trace; - //Test if they're even conceivably close to one another - if ( !gi.inPVS( self->currentOrigin, point ) ) + // Test if they're even conceivably close to one another + if (!gi.inPVS(self->currentOrigin, point)) return qfalse; - if ( self->svFlags & SVF_NAVGOAL ) - { - if ( !self->owner ) - { - //SHOULD NEVER HAPPEN!!! + if (self->svFlags & SVF_NAVGOAL) { + if (!self->owner) { + // SHOULD NEVER HAPPEN!!! assert(self->owner); return qfalse; } - VectorCopy( self->owner->mins, mins ); - VectorCopy( self->owner->maxs, maxs ); - } - else - { - VectorCopy( pmins, mins ); - VectorCopy( pmaxs, maxs ); + VectorCopy(self->owner->mins, mins); + VectorCopy(self->owner->maxs, maxs); + } else { + VectorCopy(pmins, mins); + VectorCopy(pmaxs, maxs); } - if ( self->client || ( self->svFlags & SVF_NAVGOAL ) ) - { - //Clients can step up things, or if this is a navgoal check, a client will be using this info + if (self->client || (self->svFlags & SVF_NAVGOAL)) { + // Clients can step up things, or if this is a navgoal check, a client will be using this info mins[2] += STEPSIZE; - //don't let box get inverted - if ( mins[2] > maxs[2] ) - { + // don't let box get inverted + if (mins[2] > maxs[2]) { mins[2] = maxs[2]; } } - if ( self->svFlags & SVF_NAVGOAL ) - { - //Trace from point to navgoal - gi.trace( &trace, point, mins, maxs, self->currentOrigin, self->owner->s.number, (clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP)&~CONTENTS_BODY, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (self->svFlags & SVF_NAVGOAL) { + // Trace from point to navgoal + gi.trace(&trace, point, mins, maxs, self->currentOrigin, self->owner->s.number, (clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP) & ~CONTENTS_BODY, + G2_NOCOLLIDE, 0); + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, point, mins, maxs, self->currentOrigin, self->owner->s.number, (clipmask|CONTENTS_MONSTERCLIP)&~CONTENTS_BODY, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, point, mins, maxs, self->currentOrigin, self->owner->s.number, (clipmask | CONTENTS_MONSTERCLIP) & ~CONTENTS_BODY, G2_NOCOLLIDE, + 0); } - if ( trace.startsolid || trace.allsolid ) - { + if (trace.startsolid || trace.allsolid) { return qfalse; } - //Made it - if ( trace.fraction == 1.0 ) - { + // Made it + if (trace.fraction == 1.0) { return qtrue; } - if ( okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum ) - { + if (okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum) { return qtrue; } - //Okay, didn't get all the way there, let's see if we got close enough: - if ( NAV_HitNavGoal( self->currentOrigin, self->owner->mins, self->owner->maxs, trace.endpos, NPCInfo->goalRadius, FlyingCreature( self->owner ) ) ) - { + // Okay, didn't get all the way there, let's see if we got close enough: + if (NAV_HitNavGoal(self->currentOrigin, self->owner->mins, self->owner->maxs, trace.endpos, NPCInfo->goalRadius, FlyingCreature(self->owner))) { return qtrue; - } - else - { - if ( NAVDEBUG_showCollision ) - { - if ( trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && !g_entities[trace.entityNum].bmodel ) - { - vec3_t p1, p2; - CG_DrawEdge( point, trace.endpos, EDGE_PATH ); + } else { + if (NAVDEBUG_showCollision) { + if (trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && !g_entities[trace.entityNum].bmodel) { + vec3_t p1, p2; + CG_DrawEdge(point, trace.endpos, EDGE_PATH); VectorAdd(g_entities[trace.entityNum].mins, g_entities[trace.entityNum].currentOrigin, p1); VectorAdd(g_entities[trace.entityNum].maxs, g_entities[trace.entityNum].currentOrigin, p2); - CG_CubeOutline( p1, p2, FRAMETIME, 0x0000ff, 0.5 ); + CG_CubeOutline(p1, p2, FRAMETIME, 0x0000ff, 0.5); } - //FIXME: if it is a bmodel, light up the surf? + // FIXME: if it is a bmodel, light up the surf? } } - } - else - { - gi.trace( &trace, self->currentOrigin, mins, maxs, point, self->s.number, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + } else { + gi.trace(&trace, self->currentOrigin, mins, maxs, point, self->s.number, clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, self->currentOrigin, mins, maxs, point, self->s.number, clipmask|CONTENTS_MONSTERCLIP, G2_NOCOLLIDE, 0); + gi.trace(&trace, self->currentOrigin, mins, maxs, point, self->s.number, clipmask | CONTENTS_MONSTERCLIP, G2_NOCOLLIDE, 0); } - if( ( ( trace.startsolid == qfalse ) && ( trace.allsolid == qfalse ) ) && ( trace.fraction == 1.0f ) ) - {//FIXME: check for drops + if (((trace.startsolid == qfalse) && (trace.allsolid == qfalse)) && (trace.fraction == 1.0f)) { // FIXME: check for drops return qtrue; } - if ( okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum ) - { + if (okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum) { return qtrue; } - if ( NAVDEBUG_showCollision ) - { - if ( trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && !g_entities[trace.entityNum].bmodel ) - { - vec3_t p1, p2; - CG_DrawEdge( self->currentOrigin, trace.endpos, EDGE_PATH ); + if (NAVDEBUG_showCollision) { + if (trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && !g_entities[trace.entityNum].bmodel) { + vec3_t p1, p2; + CG_DrawEdge(self->currentOrigin, trace.endpos, EDGE_PATH); VectorAdd(g_entities[trace.entityNum].mins, g_entities[trace.entityNum].currentOrigin, p1); VectorAdd(g_entities[trace.entityNum].maxs, g_entities[trace.entityNum].currentOrigin, p2); - CG_CubeOutline( p1, p2, FRAMETIME, 0x0000ff, 0.5 ); + CG_CubeOutline(p1, p2, FRAMETIME, 0x0000ff, 0.5); } - //FIXME: if it is a bmodel, light up the surf? + // FIXME: if it is a bmodel, light up the surf? } } @@ -338,60 +295,55 @@ NAV_FindClosestWaypointForEnt ------------------------- */ -int NAV_FindClosestWaypointForEnt( gentity_t *ent, int targWp ) -{ - //FIXME: Take the target into account - return navigator.GetNearestNode( ent, ent->waypoint, NF_CLEAR_PATH, targWp ); +int NAV_FindClosestWaypointForEnt(gentity_t *ent, int targWp) { + // FIXME: Take the target into account + return navigator.GetNearestNode(ent, ent->waypoint, NF_CLEAR_PATH, targWp); } -int NAV_FindClosestWaypointForPoint( gentity_t *ent, vec3_t point ) -{ - int bestWP; - //FIXME: can we make this a static ent? +int NAV_FindClosestWaypointForPoint(gentity_t *ent, vec3_t point) { + int bestWP; + // FIXME: can we make this a static ent? static gentity_t *marker = G_Spawn(); - if ( !marker ) - { + if (!marker) { return WAYPOINT_NONE; } - G_SetOrigin( marker, point ); + G_SetOrigin(marker, point); - VectorCopy( ent->mins, marker->mins );//stepsize? - VectorCopy( ent->mins, marker->maxs );//crouching? + VectorCopy(ent->mins, marker->mins); // stepsize? + VectorCopy(ent->mins, marker->maxs); // crouching? marker->clipmask = ent->clipmask; marker->waypoint = WAYPOINT_NONE; - bestWP = navigator.GetNearestNode( marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + bestWP = navigator.GetNearestNode(marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); - G_FreeEntity( marker ); + G_FreeEntity(marker); return bestWP; } -int NAV_FindClosestWaypointForPoint( vec3_t point ) -{ - int bestWP; - //FIXME: can we make this a static ent? +int NAV_FindClosestWaypointForPoint(vec3_t point) { + int bestWP; + // FIXME: can we make this a static ent? gentity_t *marker = G_Spawn(); - if ( !marker ) - { + if (!marker) { return WAYPOINT_NONE; } - G_SetOrigin( marker, point ); + G_SetOrigin(marker, point); - VectorSet( marker->mins, -16, -16, -6 );//includes stepsize - VectorSet( marker->maxs, 16, 16, 32 ); + VectorSet(marker->mins, -16, -16, -6); // includes stepsize + VectorSet(marker->maxs, 16, 16, 32); marker->clipmask = MASK_NPCSOLID; marker->waypoint = WAYPOINT_NONE; - bestWP = navigator.GetNearestNode( marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + bestWP = navigator.GetNearestNode(marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); - G_FreeEntity( marker ); + G_FreeEntity(marker); return bestWP; } @@ -402,8 +354,7 @@ NAV_ClearBlockedInfo ------------------------- */ -void NAV_ClearBlockedInfo( gentity_t *self ) -{ +void NAV_ClearBlockedInfo(gentity_t *self) { self->NPC->aiFlags &= ~NPCAI_BLOCKED; self->NPC->blockingEntNum = ENTITYNUM_WORLD; } @@ -414,8 +365,7 @@ NAV_SetBlockedInfo ------------------------- */ -void NAV_SetBlockedInfo( gentity_t *self, int entId ) -{ +void NAV_SetBlockedInfo(gentity_t *self, int entId) { self->NPC->aiFlags |= NPCAI_BLOCKED; self->NPC->blockingEntNum = entId; } @@ -426,49 +376,47 @@ NAV_Steer ------------------------- */ -int NAV_Steer( gentity_t *self, vec3_t dir, float distance ) -{ - vec3_t right_test, left_test; - vec3_t deviation; +int NAV_Steer(gentity_t *self, vec3_t dir, float distance) { + vec3_t right_test, left_test; + vec3_t deviation; - float right_ang = dir[YAW] + 45; - float left_ang = dir[YAW] - 45; + float right_ang = dir[YAW] + 45; + float left_ang = dir[YAW] - 45; - //Get the steering angles - VectorCopy( dir, deviation ); + // Get the steering angles + VectorCopy(dir, deviation); deviation[YAW] = right_ang; - AngleVectors( deviation, right_test, NULL, NULL ); + AngleVectors(deviation, right_test, NULL, NULL); deviation[YAW] = left_ang; - AngleVectors( deviation, left_test, NULL, NULL ); + AngleVectors(deviation, left_test, NULL, NULL); - //Find the end positions - VectorMA( self->currentOrigin, distance, right_test, right_test ); - VectorMA( self->currentOrigin, distance, left_test, left_test ); + // Find the end positions + VectorMA(self->currentOrigin, distance, right_test, right_test); + VectorMA(self->currentOrigin, distance, left_test, left_test); - //Draw for debug purposes - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, right_test, EDGE_PATH ); - CG_DrawEdge( self->currentOrigin, left_test, EDGE_PATH ); + // Draw for debug purposes + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, right_test, EDGE_PATH); + CG_DrawEdge(self->currentOrigin, left_test, EDGE_PATH); } - //Find the right influence - trace_t tr; - NAV_CheckAhead( self, right_test, tr, self->clipmask|CONTENTS_BOTCLIP ); + // Find the right influence + trace_t tr; + NAV_CheckAhead(self, right_test, tr, self->clipmask | CONTENTS_BOTCLIP); - float right_push = -45 * ( 1.0f - tr.fraction ); + float right_push = -45 * (1.0f - tr.fraction); - //Find the left influence - NAV_CheckAhead( self, left_test, tr, self->clipmask|CONTENTS_BOTCLIP ); + // Find the left influence + NAV_CheckAhead(self, left_test, tr, self->clipmask | CONTENTS_BOTCLIP); - float left_push = 45 * ( 1.0f - tr.fraction ); + float left_push = 45 * (1.0f - tr.fraction); - //Influence the mover to respond to the steering - VectorCopy( dir, deviation ); - deviation[YAW] += ( left_push + right_push ); + // Influence the mover to respond to the steering + VectorCopy(dir, deviation); + deviation[YAW] += (left_push + right_push); return deviation[YAW]; } @@ -479,48 +427,44 @@ NAV_CheckAhead ------------------------- */ -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ) -{ - vec3_t mins; +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask) { + vec3_t mins; - //Offset the step height - VectorSet( mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE); - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) return qtrue; - //See if we're too far above - if ( fabs( self->currentOrigin[2] - end[2] ) > 48 ) + // See if we're too far above + if (fabs(self->currentOrigin[2] - end[2]) > 48) return qfalse; - //This is a work around - float radius = ( self->maxs[0] > self->maxs[1] ) ? self->maxs[0] : self->maxs[1]; - float dist = Distance( self->currentOrigin, end ); - float tFrac = 1.0f - ( radius / dist ); + // This is a work around + float radius = (self->maxs[0] > self->maxs[1]) ? self->maxs[0] : self->maxs[1]; + float dist = Distance(self->currentOrigin, end); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; - //Do a special check for doors - if ( trace.entityNum < ENTITYNUM_WORLD ) - { - gentity_t *blocker = &g_entities[trace.entityNum]; + // Do a special check for doors + if (trace.entityNum < ENTITYNUM_WORLD) { + gentity_t *blocker = &g_entities[trace.entityNum]; - if VALIDSTRING( blocker->classname ) - { - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + if VALIDSTRING (blocker->classname) { + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { - //We're too close, try and avoid the door (most likely stuck on a lip) - if ( DistanceSquared( self->currentOrigin, trace.endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) + // We're too close, try and avoid the door (most likely stuck on a lip) + if (DistanceSquared(self->currentOrigin, trace.endpos) < MIN_DOOR_BLOCK_DIST_SQR) return qfalse; return qtrue; @@ -537,27 +481,24 @@ NAV_TestBypass ------------------------- */ -static qboolean NAV_TestBypass( gentity_t *self, float yaw, float blocked_dist, vec3_t movedir ) -{ - trace_t tr; - vec3_t avoidAngles; - vec3_t block_test, block_pos; +static qboolean NAV_TestBypass(gentity_t *self, float yaw, float blocked_dist, vec3_t movedir) { + trace_t tr; + vec3_t avoidAngles; + vec3_t block_test, block_pos; - VectorClear( avoidAngles ); + VectorClear(avoidAngles); avoidAngles[YAW] = yaw; - AngleVectors( avoidAngles, block_test, NULL, NULL ); - VectorMA( self->currentOrigin, blocked_dist, block_test, block_pos ); + AngleVectors(avoidAngles, block_test, NULL, NULL); + VectorMA(self->currentOrigin, blocked_dist, block_test, block_pos); - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, block_pos, EDGE_BLOCKED ); + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, block_pos, EDGE_BLOCKED); } - //See if we're clear to move in that direction - if ( NAV_CheckAhead( self, block_pos, tr, ( self->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - VectorCopy( block_test, movedir ); + // See if we're clear to move in that direction + if (NAV_CheckAhead(self, block_pos, tr, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + VectorCopy(block_test, movedir); return qtrue; } @@ -571,77 +512,72 @@ NAV_Bypass ------------------------- */ -qboolean NAV_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir ) -{ +qboolean NAV_Bypass(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir) { float dot; - vec3_t right; + vec3_t right; - //Draw debug info if requested - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, blocker->currentOrigin, EDGE_NORMAL ); + // Draw debug info if requested + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, blocker->currentOrigin, EDGE_NORMAL); } - AngleVectors( self->currentAngles, NULL, right, NULL ); + AngleVectors(self->currentAngles, NULL, right, NULL); - //Get the blocked direction - float yaw = vectoyaw( blocked_dir ); + // Get the blocked direction + float yaw = vectoyaw(blocked_dir); - //Get the avoid radius - float avoidRadius = sqrt( ( blocker->maxs[0] * blocker->maxs[0] ) + ( blocker->maxs[1] * blocker->maxs[1] ) ) + - sqrt( ( self->maxs[0] * self->maxs[0] ) + ( self->maxs[1] * self->maxs[1] ) ); + // Get the avoid radius + float avoidRadius = sqrt((blocker->maxs[0] * blocker->maxs[0]) + (blocker->maxs[1] * blocker->maxs[1])) + + sqrt((self->maxs[0] * self->maxs[0]) + (self->maxs[1] * self->maxs[1])); - //See if we're inside our avoidance radius - float arcAngle = ( blocked_dist <= avoidRadius ) ? 135 : ( ( avoidRadius / blocked_dist ) * 90 ); + // See if we're inside our avoidance radius + float arcAngle = (blocked_dist <= avoidRadius) ? 135 : ((avoidRadius / blocked_dist) * 90); - //FIXME: Although the below code will cause the NPC to take the "better" route, it can cause NPCs to become stuck on + // FIXME: Although the below code will cause the NPC to take the "better" route, it can cause NPCs to become stuck on // one another in certain situations where both decide to take the same direction. - //Check to see what dir the other guy is moving in (if any) and pick the opposite dir - if ( blocker->client && !VectorCompare( blocker->client->ps.velocity, vec3_origin ) ) - { + // Check to see what dir the other guy is moving in (if any) and pick the opposite dir + if (blocker->client && !VectorCompare(blocker->client->ps.velocity, vec3_origin)) { vec3_t blocker_movedir; - VectorNormalize2( blocker->client->ps.velocity, blocker_movedir ); - dot = DotProduct( blocker_movedir, blocked_dir ); - if ( dot < 0.35f && dot > -0.35f ) - {//he's moving to the side of me - vec3_t block_pos; - trace_t tr; - VectorScale( blocker_movedir, -1, blocker_movedir ); - VectorMA( self->currentOrigin, blocked_dist, blocker_movedir, block_pos ); - if ( NAV_CheckAhead( self, block_pos, tr, ( self->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - VectorCopy( blocker_movedir, movedir ); + VectorNormalize2(blocker->client->ps.velocity, blocker_movedir); + dot = DotProduct(blocker_movedir, blocked_dir); + if (dot < 0.35f && dot > -0.35f) { // he's moving to the side of me + vec3_t block_pos; + trace_t tr; + VectorScale(blocker_movedir, -1, blocker_movedir); + VectorMA(self->currentOrigin, blocked_dist, blocker_movedir, block_pos); + if (NAV_CheckAhead(self, block_pos, tr, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + VectorCopy(blocker_movedir, movedir); return qtrue; } } } - //FIXME: this makes NPCs stack up and ping-pong like crazy. + // FIXME: this makes NPCs stack up and ping-pong like crazy. // Need to keep track of this and stop trying after a while - dot = DotProduct( blocked_dir, right ); + dot = DotProduct(blocked_dir, right); - //Go right on the first try if that works better - if ( dot < 0.0f ) + // Go right on the first try if that works better + if (dot < 0.0f) arcAngle *= -1; - //Test full, best position first - if ( NAV_TestBypass( self, AngleNormalize360( yaw + arcAngle ), blocked_dist, movedir ) ) + // Test full, best position first + if (NAV_TestBypass(self, AngleNormalize360(yaw + arcAngle), blocked_dist, movedir)) return qtrue; - //Try a smaller arc - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( arcAngle * 0.5f ) ), blocked_dist, movedir ) ) + // Try a smaller arc + if (NAV_TestBypass(self, AngleNormalize360(yaw + (arcAngle * 0.5f)), blocked_dist, movedir)) return qtrue; - //Try the other direction - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( arcAngle * -1 ) ), blocked_dist, movedir ) ) + // Try the other direction + if (NAV_TestBypass(self, AngleNormalize360(yaw + (arcAngle * -1)), blocked_dist, movedir)) return qtrue; - //Try the other direction more precisely - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( ( arcAngle * -1 ) * 0.5f ) ), blocked_dist, movedir ) ) + // Try the other direction more precisely + if (NAV_TestBypass(self, AngleNormalize360(yaw + ((arcAngle * -1) * 0.5f)), blocked_dist, movedir)) return qtrue; - //Unable to go around + // Unable to go around return qfalse; } @@ -651,23 +587,22 @@ NAV_MoveBlocker ------------------------- */ -qboolean NAV_MoveBlocker( gentity_t *self, vec3_t shove_dir ) -{ - //FIXME: This is a temporary method for making blockers move +qboolean NAV_MoveBlocker(gentity_t *self, vec3_t shove_dir) { + // FIXME: This is a temporary method for making blockers move - //FIXME: This will, of course, push blockers off of cliffs, into walls and all over the place + // FIXME: This will, of course, push blockers off of cliffs, into walls and all over the place - vec3_t temp_dir, forward; + vec3_t temp_dir, forward; - vectoangles( shove_dir, temp_dir ); + vectoangles(shove_dir, temp_dir); temp_dir[YAW] += 45; - AngleVectors( temp_dir, forward, NULL, NULL ); + AngleVectors(temp_dir, forward, NULL, NULL); - VectorScale( forward, SHOVE_SPEED, self->client->ps.velocity ); + VectorScale(forward, SHOVE_SPEED, self->client->ps.velocity); self->client->ps.velocity[2] += SHOVE_LIFT; - //self->NPC->shoveDebounce = level.time + 100; + // self->NPC->shoveDebounce = level.time + 100; return qtrue; } @@ -678,15 +613,14 @@ NAV_ResolveBlock ------------------------- */ -qboolean NAV_ResolveBlock( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir ) -{ - //Stop double waiting - if ( ( blocker->NPC ) && ( blocker->NPC->blockingEntNum == self->s.number ) ) +qboolean NAV_ResolveBlock(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir) { + // Stop double waiting + if ((blocker->NPC) && (blocker->NPC->blockingEntNum == self->s.number)) return qtrue; - //For now, just complain about it - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker ); + // For now, just complain about it + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker); return qfalse; } @@ -697,37 +631,35 @@ NAV_TrueCollision ------------------------- */ -qboolean NAV_TrueCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t blocked_dir ) -{ - //TODO: Handle all ents - if ( blocker->client == NULL ) +qboolean NAV_TrueCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t blocked_dir) { + // TODO: Handle all ents + if (blocker->client == NULL) return qfalse; - vec3_t velocityDir; + vec3_t velocityDir; - //Get the player's move direction and speed - float speed = VectorNormalize2( self->client->ps.velocity, velocityDir ); + // Get the player's move direction and speed + float speed = VectorNormalize2(self->client->ps.velocity, velocityDir); - //See if it's even feasible - float dot = DotProduct( movedir, velocityDir ); + // See if it's even feasible + float dot = DotProduct(movedir, velocityDir); - if ( dot < 0.85 ) + if (dot < 0.85) return qfalse; - vec3_t testPos; - vec3_t ptmins, ptmaxs, tmins, tmaxs; + vec3_t testPos; + vec3_t ptmins, ptmaxs, tmins, tmaxs; - VectorMA( self->currentOrigin, speed*FRAMETIME, velocityDir, testPos ); + VectorMA(self->currentOrigin, speed * FRAMETIME, velocityDir, testPos); - VectorAdd( blocker->currentOrigin, blocker->mins, tmins ); - VectorAdd( blocker->currentOrigin, blocker->maxs, tmaxs ); + VectorAdd(blocker->currentOrigin, blocker->mins, tmins); + VectorAdd(blocker->currentOrigin, blocker->maxs, tmaxs); - VectorAdd( testPos, self->mins, ptmins ); - VectorAdd( testPos, self->maxs, ptmaxs ); + VectorAdd(testPos, self->mins, ptmins); + VectorAdd(testPos, self->maxs, ptmaxs); - if ( G_BoundsOverlap( ptmins, ptmaxs, tmins, tmaxs ) ) - { - VectorCopy( velocityDir, blocked_dir ); + if (G_BoundsOverlap(ptmins, ptmaxs, tmins, tmaxs)) { + VectorCopy(velocityDir, blocked_dir); return qtrue; } @@ -740,61 +672,56 @@ NAV_StackedCanyon ------------------------- */ -qboolean NAV_StackedCanyon( gentity_t *self, gentity_t *blocker, vec3_t pathDir ) -{ - vec3_t perp, cross, test; - float avoidRadius; - int extraClip = CONTENTS_BOTCLIP; +qboolean NAV_StackedCanyon(gentity_t *self, gentity_t *blocker, vec3_t pathDir) { + vec3_t perp, cross, test; + float avoidRadius; + int extraClip = CONTENTS_BOTCLIP; - PerpendicularVector( perp, pathDir ); - CrossProduct( pathDir, perp, cross ); + PerpendicularVector(perp, pathDir); + CrossProduct(pathDir, perp, cross); - avoidRadius = sqrt( ( blocker->maxs[0] * blocker->maxs[0] ) + ( blocker->maxs[1] * blocker->maxs[1] ) ) + - sqrt( ( self->maxs[0] * self->maxs[0] ) + ( self->maxs[1] * self->maxs[1] ) ); + avoidRadius = sqrt((blocker->maxs[0] * blocker->maxs[0]) + (blocker->maxs[1] * blocker->maxs[1])) + + sqrt((self->maxs[0] * self->maxs[0]) + (self->maxs[1] * self->maxs[1])); - VectorMA( blocker->currentOrigin, avoidRadius, cross, test ); + VectorMA(blocker->currentOrigin, avoidRadius, cross, test); - trace_t tr; - gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask|extraClip, G2_NOCOLLIDE, 0 ); - if ( tr.startsolid&&(tr.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + trace_t tr; + gi.trace(&tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask | extraClip, G2_NOCOLLIDE, 0); + if (tr.startsolid && (tr.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them extraClip &= ~CONTENTS_BOTCLIP; - gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask|extraClip, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask | extraClip, G2_NOCOLLIDE, 0); } - if ( NAVDEBUG_showCollision ) - { - vec3_t mins, maxs; - vec3_t RED = { 1.0f, 0.0f, 0.0f }; + if (NAVDEBUG_showCollision) { + vec3_t mins, maxs; + vec3_t RED = {1.0f, 0.0f, 0.0f}; - VectorAdd( test, self->mins, mins ); - VectorAdd( test, self->maxs, maxs ); - CG_Cube( mins, maxs, RED, 0.25 ); + VectorAdd(test, self->mins, mins); + VectorAdd(test, self->maxs, maxs); + CG_Cube(mins, maxs, RED, 0.25); } - if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) + if (tr.startsolid == qfalse && tr.allsolid == qfalse) return qfalse; - VectorMA( blocker->currentOrigin, -avoidRadius, cross, test ); + VectorMA(blocker->currentOrigin, -avoidRadius, cross, test); - gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask|extraClip, G2_NOCOLLIDE, 0 ); - if ( tr.startsolid&&(tr.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + gi.trace(&tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask | extraClip, G2_NOCOLLIDE, 0); + if (tr.startsolid && (tr.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them extraClip &= ~CONTENTS_BOTCLIP; - gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask|extraClip, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask | extraClip, G2_NOCOLLIDE, 0); } - if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) + if (tr.startsolid == qfalse && tr.allsolid == qfalse) return qfalse; - if ( NAVDEBUG_showCollision ) - { - vec3_t mins, maxs; - vec3_t RED = { 1.0f, 0.0f, 0.0f }; + if (NAVDEBUG_showCollision) { + vec3_t mins, maxs; + vec3_t RED = {1.0f, 0.0f, 0.0f}; - VectorAdd( test, self->mins, mins ); - VectorAdd( test, self->maxs, maxs ); - CG_Cube( mins, maxs, RED, 0.25 ); + VectorAdd(test, self->mins, mins); + VectorAdd(test, self->maxs, maxs); + CG_Cube(mins, maxs, RED, 0.25); } return qtrue; @@ -806,43 +733,40 @@ NAV_ResolveEntityCollision ------------------------- */ -qboolean NAV_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir ) -{ - vec3_t blocked_dir; +qboolean NAV_ResolveEntityCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir) { + vec3_t blocked_dir; - //Doors are ignored - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + // Doors are ignored + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { - if ( DistanceSquared( self->currentOrigin, blocker->currentOrigin ) > MIN_DOOR_BLOCK_DIST_SQR ) + if (DistanceSquared(self->currentOrigin, blocker->currentOrigin) > MIN_DOOR_BLOCK_DIST_SQR) return qtrue; } - VectorSubtract( blocker->currentOrigin, self->currentOrigin, blocked_dir ); - float blocked_dist = VectorNormalize( blocked_dir ); + VectorSubtract(blocker->currentOrigin, self->currentOrigin, blocked_dir); + float blocked_dist = VectorNormalize(blocked_dir); - //Make sure an actual collision is going to happen -// if ( NAV_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) -// return qtrue; + // Make sure an actual collision is going to happen + // if ( NAV_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) + // return qtrue; - //See if we can get around the blocker at all (only for player!) - if ( blocker->s.number == 0 ) - { - if ( NAV_StackedCanyon( self, blocker, pathDir ) ) - { - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker, qtrue ); + // See if we can get around the blocker at all (only for player!) + if (blocker->s.number == 0) { + if (NAV_StackedCanyon(self, blocker, pathDir)) { + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker, qtrue); return qfalse; } } - //First, attempt to walk around the blocker - if ( NAV_Bypass( self, blocker, blocked_dir, blocked_dist, movedir ) ) + // First, attempt to walk around the blocker + if (NAV_Bypass(self, blocker, blocked_dir, blocked_dist, movedir)) return qtrue; - //Second, attempt to calculate a good move position for the blocker - if ( NAV_ResolveBlock( self, blocker, blocked_dir ) ) + // Second, attempt to calculate a good move position for the blocker + if (NAV_ResolveBlock(self, blocker, blocked_dir)) return qtrue; return qfalse; @@ -854,22 +778,19 @@ NAV_TestForBlocked ------------------------- */ -qboolean NAV_TestForBlocked( gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int &flags ) -{ - if ( goal == NULL ) +qboolean NAV_TestForBlocked(gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int &flags) { + if (goal == NULL) return qfalse; - if ( blocker->s.eType == ET_ITEM ) + if (blocker->s.eType == ET_ITEM) return qfalse; - if ( NAV_HitNavGoal( blocker->currentOrigin, blocker->mins, blocker->maxs, goal->currentOrigin, 12, qfalse ) ) - { + if (NAV_HitNavGoal(blocker->currentOrigin, blocker->mins, blocker->maxs, goal->currentOrigin, 12, qfalse)) { flags |= NIF_BLOCKED; - if ( distance <= MIN_STOP_DIST ) - { - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker ); + if (distance <= MIN_STOP_DIST) { + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker); return qtrue; } } @@ -883,60 +804,56 @@ NAV_AvoidCollsion ------------------------- */ -qboolean NAV_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t &info ) -{ - vec3_t movedir; - vec3_t movepos; +qboolean NAV_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t &info) { + vec3_t movedir; + vec3_t movepos; - //Clear our block info for this frame - NAV_ClearBlockedInfo( NPC ); + // Clear our block info for this frame + NAV_ClearBlockedInfo(NPC); - //Cap our distance - if ( info.distance > MAX_COLL_AVOID_DIST ) - { + // Cap our distance + if (info.distance > MAX_COLL_AVOID_DIST) { info.distance = MAX_COLL_AVOID_DIST; } - //Get an end position - VectorMA( self->currentOrigin, info.distance, info.direction, movepos ); - VectorCopy( info.direction, movedir ); + // Get an end position + VectorMA(self->currentOrigin, info.distance, info.direction, movepos); + VectorCopy(info.direction, movedir); - //Now test against entities - if ( NAV_CheckAhead( self, movepos, info.trace, CONTENTS_BODY ) == qfalse ) - { - //Get the blocker - info.blocker = &g_entities[ info.trace.entityNum ]; + // Now test against entities + if (NAV_CheckAhead(self, movepos, info.trace, CONTENTS_BODY) == qfalse) { + // Get the blocker + info.blocker = &g_entities[info.trace.entityNum]; info.flags |= NIF_COLLISION; - //Ok to hit our goal entity - if ( goal == info.blocker ) + // Ok to hit our goal entity + if (goal == info.blocker) return qtrue; - //See if we're moving along with them - //if ( NAV_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) + // See if we're moving along with them + // if ( NAV_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) // return qtrue; - //Test for blocking by standing on goal - if ( NAV_TestForBlocked( self, goal, info.blocker, info.distance, info.flags ) == qtrue ) + // Test for blocking by standing on goal + if (NAV_TestForBlocked(self, goal, info.blocker, info.distance, info.flags) == qtrue) return qfalse; - //If the above function said we're blocked, don't do the extra checks - if ( info.flags & NIF_BLOCKED ) + // If the above function said we're blocked, don't do the extra checks + if (info.flags & NIF_BLOCKED) return qtrue; - //See if we can get that entity to move out of our way - if ( NAV_ResolveEntityCollision( self, info.blocker, movedir, info.pathDirection ) == qfalse ) + // See if we can get that entity to move out of our way + if (NAV_ResolveEntityCollision(self, info.blocker, movedir, info.pathDirection) == qfalse) return qfalse; - VectorCopy( movedir, info.direction ); + VectorCopy(movedir, info.direction); return qtrue; } - //Our path is clear, just move there - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, movepos, EDGE_PATH ); + // Our path is clear, just move there + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, movepos, EDGE_PATH); } return qtrue; @@ -948,109 +865,86 @@ NAV_TestBestNode ------------------------- */ -int NAV_TestBestNode( gentity_t *self, int startID, int endID, qboolean failEdge ) -{//check only against architectrure - vec3_t end; - trace_t trace; - vec3_t mins; - int clipmask = (NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP; +int NAV_TestBestNode(gentity_t *self, int startID, int endID, qboolean failEdge) { // check only against architectrure + vec3_t end; + trace_t trace; + vec3_t mins; + int clipmask = (NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP; - //get the position for the test choice - navigator.GetNodePosition( endID, end ); + // get the position for the test choice + navigator.GetNodePosition(endID, end); - //Offset the step height - VectorSet( mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE); - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask, G2_NOCOLLIDE, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) - {//it's clear + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) { // it's clear return endID; } - //See if we're too far above - if ( self->s.weapon != WP_SABER && fabs( self->currentOrigin[2] - end[2] ) > 48 ) - { - } - else - { - //This is a work around - float radius = ( self->maxs[0] > self->maxs[1] ) ? self->maxs[0] : self->maxs[1]; - float dist = Distance( self->currentOrigin, end ); - float tFrac = 1.0f - ( radius / dist ); + // See if we're too far above + if (self->s.weapon != WP_SABER && fabs(self->currentOrigin[2] - end[2]) > 48) { + } else { + // This is a work around + float radius = (self->maxs[0] > self->maxs[1]) ? self->maxs[0] : self->maxs[1]; + float dist = Distance(self->currentOrigin, end); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) - {//it's clear + if (trace.fraction >= tFrac) { // it's clear return endID; } } - //Do a special check for doors - if ( trace.entityNum < ENTITYNUM_WORLD ) - { - gentity_t *blocker = &g_entities[trace.entityNum]; - - if VALIDSTRING( blocker->classname ) - {//special case: doors are architecture, but are dynamic, like entitites - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) - {//it's unlocked, go for it - //We're too close, try and avoid the door (most likely stuck on a lip) - if ( DistanceSquared( self->currentOrigin, trace.endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) - { + // Do a special check for doors + if (trace.entityNum < ENTITYNUM_WORLD) { + gentity_t *blocker = &g_entities[trace.entityNum]; + + if VALIDSTRING (blocker->classname) { // special case: doors are architecture, but are dynamic, like entitites + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + { // it's unlocked, go for it + // We're too close, try and avoid the door (most likely stuck on a lip) + if (DistanceSquared(self->currentOrigin, trace.endpos) < MIN_DOOR_BLOCK_DIST_SQR) { return startID; } - //we can keep heading to the door, it should open - if ( self->s.weapon != WP_SABER && fabs( self->currentOrigin[2] - end[2] ) > 48 ) - {//too far above - } - else - { + // we can keep heading to the door, it should open + if (self->s.weapon != WP_SABER && fabs(self->currentOrigin[2] - end[2]) > 48) { // too far above + } else { return endID; } - } - else if ( G_EntIsDoor( blocker->s.number ) ) - {//a locked door! - //path is blocked by a locked door, mark it as such if instructed to do so - if ( failEdge ) - { - navigator.AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsDoor(blocker->s.number)) { // a locked door! + // path is blocked by a locked door, mark it as such if instructed to do so + if (failEdge) { + navigator.AddFailedEdge(self->s.number, startID, endID); } - } - else if ( G_EntIsBreakable( blocker->s.number ) ) - {//do same for breakable brushes/models/glass? - //path is blocked by a breakable, mark it as such if instructed to do so - if ( failEdge ) - { - navigator.AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsBreakable(blocker->s.number)) { // do same for breakable brushes/models/glass? + // path is blocked by a breakable, mark it as such if instructed to do so + if (failEdge) { + navigator.AddFailedEdge(self->s.number, startID, endID); } - } - else if ( G_EntIsRemovableUsable( blocker->s.number ) ) - {//and removable usables - //path is blocked by a removable usable, mark it as such if instructed to do so - if ( failEdge ) - { - navigator.AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsRemovableUsable(blocker->s.number)) { // and removable usables + // path is blocked by a removable usable, mark it as such if instructed to do so + if (failEdge) { + navigator.AddFailedEdge(self->s.number, startID, endID); } - } - else if ( blocker->targetname && blocker->s.solid == SOLID_BMODEL && ((blocker->contents&CONTENTS_MONSTERCLIP)|| (blocker->contents&CONTENTS_BOTCLIP)) ) - {//some other kind of do not enter entity brush that will probably be removed - //path is blocked by a removable brushent, mark it as such if instructed to do so - if ( failEdge ) - { - navigator.AddFailedEdge( self->s.number, startID, endID ); + } else if (blocker->targetname && blocker->s.solid == SOLID_BMODEL && + ((blocker->contents & CONTENTS_MONSTERCLIP) || + (blocker->contents & CONTENTS_BOTCLIP))) { // some other kind of do not enter entity brush that will probably be removed + // path is blocked by a removable brushent, mark it as such if instructed to do so + if (failEdge) { + navigator.AddFailedEdge(self->s.number, startID, endID); } } } } - //path is blocked - //use the fallback choice + // path is blocked + // use the fallback choice return startID; } @@ -1060,10 +954,7 @@ NAV_GetNearestNode ------------------------- */ -int NAV_GetNearestNode( gentity_t *self, int lastNode ) -{ - return navigator.GetNearestNode( self, lastNode, NF_CLEAR_PATH, WAYPOINT_NONE ); -} +int NAV_GetNearestNode(gentity_t *self, int lastNode) { return navigator.GetNearestNode(self, lastNode, NF_CLEAR_PATH, WAYPOINT_NONE); } /* ------------------------- @@ -1071,12 +962,9 @@ NAV_MicroError ------------------------- */ -qboolean NAV_MicroError( vec3_t start, vec3_t end ) -{ - if ( VectorCompare( start, end ) ) - { - if ( DistanceSquared( NPC->currentOrigin, start ) < (8*8) ) - { +qboolean NAV_MicroError(vec3_t start, vec3_t end) { + if (VectorCompare(start, end)) { + if (DistanceSquared(NPC->currentOrigin, start) < (8 * 8)) { return qtrue; } } @@ -1090,100 +978,91 @@ NAV_MoveToGoal ------------------------- */ -int NAV_MoveToGoal( gentity_t *self, navInfo_t &info ) -{ - //Must have a goal entity to move there - if( self->NPC->goalEntity == NULL ) +int NAV_MoveToGoal(gentity_t *self, navInfo_t &info) { + // Must have a goal entity to move there + if (self->NPC->goalEntity == NULL) return WAYPOINT_NONE; - //Check special player optimizations - if ( self->NPC->goalEntity->s.number == 0 ) - { - //If we couldn't find the point, then we won't be able to this turn - if ( self->NPC->goalEntity->waypoint == WAYPOINT_NONE ) + // Check special player optimizations + if (self->NPC->goalEntity->s.number == 0) { + // If we couldn't find the point, then we won't be able to this turn + if (self->NPC->goalEntity->waypoint == WAYPOINT_NONE) return WAYPOINT_NONE; - //NOTENOTE: Otherwise trust this waypoint for the whole frame (reduce all unnecessary calculations) - } - else - { - //Find the target's waypoint - if ( ( self->NPC->goalEntity->waypoint = NAV_GetNearestNode( self->NPC->goalEntity, self->NPC->goalEntity->waypoint ) ) == WAYPOINT_NONE ) + // NOTENOTE: Otherwise trust this waypoint for the whole frame (reduce all unnecessary calculations) + } else { + // Find the target's waypoint + if ((self->NPC->goalEntity->waypoint = NAV_GetNearestNode(self->NPC->goalEntity, self->NPC->goalEntity->waypoint)) == WAYPOINT_NONE) return WAYPOINT_NONE; } - //Find our waypoint - if ( ( self->waypoint = NAV_GetNearestNode( self, self->lastWaypoint ) ) == WAYPOINT_NONE ) + // Find our waypoint + if ((self->waypoint = NAV_GetNearestNode(self, self->lastWaypoint)) == WAYPOINT_NONE) return WAYPOINT_NONE; - int bestNode = navigator.GetBestNode( self->waypoint, self->NPC->goalEntity->waypoint ); + int bestNode = navigator.GetBestNode(self->waypoint, self->NPC->goalEntity->waypoint); - if ( bestNode == WAYPOINT_NONE ) - { - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t origin, torigin; + if (bestNode == WAYPOINT_NONE) { + if (NAVDEBUG_showEnemyPath) { + vec3_t origin, torigin; - navigator.GetNodePosition( self->NPC->goalEntity->waypoint, torigin ); - navigator.GetNodePosition( self->waypoint, origin ); + navigator.GetNodePosition(self->NPC->goalEntity->waypoint, torigin); + navigator.GetNodePosition(self->waypoint, origin); - CG_DrawNode( torigin, NODE_GOAL ); - CG_DrawNode( origin, NODE_GOAL ); - CG_DrawNode( self->NPC->goalEntity->currentOrigin, NODE_START ); + CG_DrawNode(torigin, NODE_GOAL); + CG_DrawNode(origin, NODE_GOAL); + CG_DrawNode(self->NPC->goalEntity->currentOrigin, NODE_START); } return WAYPOINT_NONE; } - //Check this node - bestNode = NAV_TestBestNode( self, bestNode, self->NPC->goalEntity->waypoint, qfalse ); + // Check this node + bestNode = NAV_TestBestNode(self, bestNode, self->NPC->goalEntity->waypoint, qfalse); - vec3_t origin, end; - //trace_t trace; + vec3_t origin, end; + // trace_t trace; - //Get this position - navigator.GetNodePosition( bestNode, origin ); - navigator.GetNodePosition( self->waypoint, end ); + // Get this position + navigator.GetNodePosition(bestNode, origin); + navigator.GetNodePosition(self->waypoint, end); - //Basically, see if the path we have isn't helping - //if ( NAV_MicroError( origin, end ) ) + // Basically, see if the path we have isn't helping + // if ( NAV_MicroError( origin, end ) ) // return WAYPOINT_NONE; - //Test the path connection from our current position to the best node - if ( NAV_CheckAhead( self, origin, info.trace, (self->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP ) == qfalse ) - { - //First attempt to move to the closest point on the line between the waypoints - G_FindClosestPointOnLineSegment( origin, end, self->currentOrigin, origin ); + // Test the path connection from our current position to the best node + if (NAV_CheckAhead(self, origin, info.trace, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP) == qfalse) { + // First attempt to move to the closest point on the line between the waypoints + G_FindClosestPointOnLineSegment(origin, end, self->currentOrigin, origin); - //See if we can go there - if ( NAV_CheckAhead( self, origin, info.trace, (self->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP ) == qfalse ) - { - //Just move towards our current waypoint + // See if we can go there + if (NAV_CheckAhead(self, origin, info.trace, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP) == qfalse) { + // Just move towards our current waypoint bestNode = self->waypoint; - navigator.GetNodePosition( bestNode, origin ); + navigator.GetNodePosition(bestNode, origin); } } - //Setup our new move information - VectorSubtract( origin, self->currentOrigin, info.direction ); - info.distance = VectorNormalize( info.direction ); + // Setup our new move information + VectorSubtract(origin, self->currentOrigin, info.direction); + info.distance = VectorNormalize(info.direction); - VectorSubtract( end, origin, info.pathDirection ); - VectorNormalize( info.pathDirection ); + VectorSubtract(end, origin, info.pathDirection); + VectorNormalize(info.pathDirection); - //Draw any debug info, if requested - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t dest, start; + // Draw any debug info, if requested + if (NAVDEBUG_showEnemyPath) { + vec3_t dest, start; - //Get the positions - navigator.GetNodePosition( self->NPC->goalEntity->waypoint, dest ); - navigator.GetNodePosition( bestNode, start ); + // Get the positions + navigator.GetNodePosition(self->NPC->goalEntity->waypoint, dest); + navigator.GetNodePosition(bestNode, start); - //Draw the route - CG_DrawNode( start, NODE_START ); - CG_DrawNode( dest, NODE_GOAL ); - navigator.ShowPath( self->waypoint, self->NPC->goalEntity->waypoint ); + // Draw the route + CG_DrawNode(start, NODE_START); + CG_DrawNode(dest, NODE_GOAL); + navigator.ShowPath(self->waypoint, self->NPC->goalEntity->waypoint); } return bestNode; @@ -1195,28 +1074,27 @@ waypoint_testDirection ------------------------- */ -unsigned int waypoint_testDirection( vec3_t origin, float yaw, unsigned int minDist ) -{ - vec3_t trace_dir, test_pos; - vec3_t maxs, mins; - trace_t tr; +unsigned int waypoint_testDirection(vec3_t origin, float yaw, unsigned int minDist) { + vec3_t trace_dir, test_pos; + vec3_t maxs, mins; + trace_t tr; - //Setup the mins and max - VectorSet( maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2 ); - VectorSet( mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE ); + // Setup the mins and max + VectorSet(maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); + VectorSet(mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE); - //Get our test direction - vec3_t angles = { 0, yaw, 0 }; - AngleVectors( angles, trace_dir, NULL, NULL ); + // Get our test direction + vec3_t angles = {0, yaw, 0}; + AngleVectors(angles, trace_dir, NULL, NULL); - //Move ahead -// VectorMA( origin, MAX_RADIUS_CHECK, trace_dir, test_pos ); - VectorMA( origin, minDist, trace_dir, test_pos ); + // Move ahead + // VectorMA( origin, MAX_RADIUS_CHECK, trace_dir, test_pos ); + VectorMA(origin, minDist, trace_dir, test_pos); - gi.trace( &tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, ( CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP ), G2_NOCOLLIDE, 0 ); + gi.trace(&tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, (CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP), G2_NOCOLLIDE, 0); - //return (unsigned int) ( (float) MAX_RADIUS_CHECK * tr.fraction ); - return (unsigned int) ( (float) minDist * tr.fraction ); + // return (unsigned int) ( (float) MAX_RADIUS_CHECK * tr.fraction ); + return (unsigned int)((float)minDist * tr.fraction); } /* @@ -1225,16 +1103,14 @@ waypoint_getRadius ------------------------- */ -unsigned int waypoint_getRadius( gentity_t *ent ) -{ - unsigned int minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; - unsigned int dist; +unsigned int waypoint_getRadius(gentity_t *ent) { + unsigned int minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; + unsigned int dist; - for ( int i = 0; i < YAW_ITERATIONS; i++ ) - { - dist = waypoint_testDirection( ent->currentOrigin, ((360.0f/YAW_ITERATIONS) * i), minDist ); + for (int i = 0; i < YAW_ITERATIONS; i++) { + dist = waypoint_testDirection(ent->currentOrigin, ((360.0f / YAW_ITERATIONS) * i), minDist); - if ( dist < minDist ) + if (dist < minDist) minDist = dist; } @@ -1244,34 +1120,31 @@ unsigned int waypoint_getRadius( gentity_t *ent ) /*QUAKED waypoint (0.7 0.7 0) (-16 -16 -24) (16 16 32) SOLID_OK a place to go. -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) radius is automatically calculated in-world. */ -void SP_waypoint ( gentity_t *ent ) -{ - if ( navCalculatePaths ) - { +void SP_waypoint(gentity_t *ent) { + if (navCalculatePaths) { VectorSet(ent->mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2); VectorSet(ent->maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); ent->contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; - gi.linkentity( ent ); + gi.linkentity(ent); ent->count = -1; ent->classname = "waypoint"; - if( !(ent->spawnflags&1) && G_CheckInSolid (ent, qtrue)) - {//if not SOLID_OK, and in solid + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { // if not SOLID_OK, and in solid ent->maxs[2] = CROUCH_MAXS_2; - if(G_CheckInSolid (ent, qtrue)) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (G_CheckInSolid(ent, qtrue)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0 && "Waypoint in solid!"); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif @@ -1280,10 +1153,10 @@ void SP_waypoint ( gentity_t *ent ) } } - unsigned int radius = waypoint_getRadius( ent ); + unsigned int radius = waypoint_getRadius(ent); - ent->health = navigator.AddRawPoint( ent->currentOrigin, ent->spawnflags, radius ); - NAV_StoreWaypoint( ent ); + ent->health = navigator.AddRawPoint(ent->currentOrigin, ent->spawnflags, radius); + NAV_StoreWaypoint(ent); G_FreeEntity(ent); return; } @@ -1292,32 +1165,29 @@ void SP_waypoint ( gentity_t *ent ) } /*QUAKED waypoint_small (0.7 0.7 0) (-2 -2 -24) (2 2 32) SOLID_OK -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) */ -void SP_waypoint_small (gentity_t *ent) -{ - if ( navCalculatePaths ) - { +void SP_waypoint_small(gentity_t *ent) { + if (navCalculatePaths) { VectorSet(ent->mins, -2, -2, DEFAULT_MINS_2); VectorSet(ent->maxs, 2, 2, DEFAULT_MAXS_2); ent->contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; - gi.linkentity( ent ); + gi.linkentity(ent); ent->count = -1; ent->classname = "waypoint"; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qtrue ) ) - { + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { ent->maxs[2] = CROUCH_MAXS_2; - if ( G_CheckInSolid( ent, qtrue ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (G_CheckInSolid(ent, qtrue)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_small %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif @@ -1326,8 +1196,8 @@ void SP_waypoint_small (gentity_t *ent) } } - ent->health = navigator.AddRawPoint( ent->currentOrigin, ent->spawnflags, 2 ); - NAV_StoreWaypoint( ent ); + ent->health = navigator.AddRawPoint(ent->currentOrigin, ent->spawnflags, 2); + NAV_StoreWaypoint(ent); G_FreeEntity(ent); return; } @@ -1335,12 +1205,12 @@ void SP_waypoint_small (gentity_t *ent) G_FreeEntity(ent); } - /*QUAKED waypoint_navgoal (0.3 1 0.3) (-16 -16 -24) (16 16 32) SOLID_OK A waypoint for script navgoals Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1351,34 +1221,33 @@ targetname - name you would use in script when setting a navgoal (like so:) radius - how far from the navgoal an ent can be before it thinks it reached it - default is "0" which means no radius check, just have to touch it */ -void SP_waypoint_navgoal( gentity_t *ent ) -{ - int radius = ( ent->radius ) ? (((int)ent->radius)|NAVGOAL_USE_RADIUS) : 12; +void SP_waypoint_navgoal(gentity_t *ent) { + int radius = (ent->radius) ? (((int)ent->radius) | NAVGOAL_USE_RADIUS) : 12; - VectorSet( ent->mins, -16, -16, -24 ); - VectorSet( ent->maxs, 16, 16, 32 ); + VectorSet(ent->mins, -16, -16, -24); + VectorSet(ent->maxs, 16, 16, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_8 (0.3 1 0.3) (-8 -8 -24) (8 8 32) SOLID_OK A waypoint for script navgoals, 8 x 8 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1388,33 +1257,32 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_8( gentity_t *ent ) -{ - VectorSet( ent->mins, -8, -8, -24 ); - VectorSet( ent->maxs, 8, 8, 32 ); +void SP_waypoint_navgoal_8(gentity_t *ent) { + VectorSet(ent->mins, -8, -8, -24); + VectorSet(ent->maxs, 8, 8, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal_8 %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 8, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 8, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_4 (0.3 1 0.3) (-4 -4 -24) (4 4 32) SOLID_OK A waypoint for script navgoals, 4 x 4 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1424,33 +1292,32 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_4( gentity_t *ent ) -{ - VectorSet( ent->mins, -4, -4, -24 ); - VectorSet( ent->maxs, 4, 4, 32 ); +void SP_waypoint_navgoal_4(gentity_t *ent) { + VectorSet(ent->mins, -4, -4, -24); + VectorSet(ent->maxs, 4, 4, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal_4 %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 4, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 4, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_2 (0.3 1 0.3) (-2 -2 -24) (2 2 32) SOLID_OK A waypoint for script navgoals, 2 x 2 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1460,33 +1327,32 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_2( gentity_t *ent ) -{ - VectorSet( ent->mins, -2, -2, -24 ); - VectorSet( ent->maxs, 2, 2, 32 ); +void SP_waypoint_navgoal_2(gentity_t *ent) { + VectorSet(ent->mins, -2, -2, -24); + VectorSet(ent->maxs, 2, 2, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal_2 %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 2, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 2, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_1 (0.3 1 0.3) (-1 -1 -24) (1 1 32) SOLID_OK A waypoint for script navgoals, 1 x 1 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1496,26 +1362,24 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_1( gentity_t *ent ) -{ - VectorSet( ent->mins, -1, -1, -24 ); - VectorSet( ent->maxs, 1, 1, 32 ); +void SP_waypoint_navgoal_1(gentity_t *ent) { + VectorSet(ent->mins, -1, -1, -24); + VectorSet(ent->maxs, 1, 1, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + gi.Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD - if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region + if (!g_entities[ENTITYNUM_WORLD].s.radius) { // not a region G_Error("Waypoint_navgoal_1 %s at %s in solid!", ent->targetname, vtos(ent->currentOrigin)); } #endif assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 1, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 1, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /* @@ -1524,95 +1388,68 @@ Svcmd_Nav_f ------------------------- */ -void Svcmd_Nav_f( void ) -{ - char *cmd = gi.argv( 1 ); +void Svcmd_Nav_f(void) { + char *cmd = gi.argv(1); - if ( Q_stricmp( cmd, "show" ) == 0 ) - { - cmd = gi.argv( 2 ); + if (Q_stricmp(cmd, "show") == 0) { + cmd = gi.argv(2); - if ( Q_stricmp( cmd, "all" ) == 0 ) - { + if (Q_stricmp(cmd, "all") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - //NOTENOTE: This causes the two states to sync up if they aren't already - NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = - NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = - NAVDEBUG_showEdges = NAVDEBUG_showRadius = NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "nodes" ) == 0 ) - { + // NOTENOTE: This causes the two states to sync up if they aren't already + NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = NAVDEBUG_showEdges = NAVDEBUG_showRadius = + NAVDEBUG_showNodes; + } else if (Q_stricmp(cmd, "nodes") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "radius" ) == 0 ) - { + } else if (Q_stricmp(cmd, "radius") == 0) { NAVDEBUG_showRadius = !NAVDEBUG_showRadius; - } - else if ( Q_stricmp( cmd, "edges" ) == 0 ) - { + } else if (Q_stricmp(cmd, "edges") == 0) { NAVDEBUG_showEdges = !NAVDEBUG_showEdges; - } - else if ( Q_stricmp( cmd, "testpath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "testpath") == 0) { NAVDEBUG_showTestPath = !NAVDEBUG_showTestPath; - } - else if ( Q_stricmp( cmd, "enemypath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "enemypath") == 0) { NAVDEBUG_showEnemyPath = !NAVDEBUG_showEnemyPath; - } - else if ( Q_stricmp( cmd, "combatpoints" ) == 0 ) - { + } else if (Q_stricmp(cmd, "combatpoints") == 0) { NAVDEBUG_showCombatPoints = !NAVDEBUG_showCombatPoints; - } - else if ( Q_stricmp( cmd, "navgoals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "navgoals") == 0) { NAVDEBUG_showNavGoals = !NAVDEBUG_showNavGoals; - } - else if ( Q_stricmp( cmd, "collision" ) == 0 ) - { + } else if (Q_stricmp(cmd, "collision") == 0) { NAVDEBUG_showCollision = !NAVDEBUG_showCollision; } - } - else if ( Q_stricmp( cmd, "set" ) == 0 ) - { - cmd = gi.argv( 2 ); + } else if (Q_stricmp(cmd, "set") == 0) { + cmd = gi.argv(2); - if ( Q_stricmp( cmd, "testgoal" ) == 0 ) - { - NAVDEBUG_curGoal = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + if (Q_stricmp(cmd, "testgoal") == 0) { + NAVDEBUG_curGoal = navigator.GetNearestNode(&g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); } - } - else if ( Q_stricmp( cmd, "totals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "totals") == 0) { Com_Printf("Navigation Totals:\n"); Com_Printf("------------------\n"); - Com_Printf("Total Nodes: %d\n", navigator.GetNumNodes() ); - Com_Printf("Total Combat Points: %d\n", level.numCombatPoints ); - } - else - { - //Print the available commands - Com_Printf("nav - valid commands\n---\n" ); + Com_Printf("Total Nodes: %d\n", navigator.GetNumNodes()); + Com_Printf("Total Combat Points: %d\n", level.numCombatPoints); + } else { + // Print the available commands + Com_Printf("nav - valid commands\n---\n"); Com_Printf("show\n - nodes\n - edges\n - testpath\n - enemypath\n - combatpoints\n - navgoals\n---\n"); - Com_Printf("set\n - testgoal\n---\n" ); + Com_Printf("set\n - testgoal\n---\n"); } } // -//JWEIER ADDITIONS START +// JWEIER ADDITIONS START -bool navCalculatePaths = false; +bool navCalculatePaths = false; -bool NAVDEBUG_showNodes = false; -bool NAVDEBUG_showRadius = false; -bool NAVDEBUG_showEdges = false; -bool NAVDEBUG_showTestPath = false; -bool NAVDEBUG_showEnemyPath = false; -bool NAVDEBUG_showCombatPoints = false; -bool NAVDEBUG_showNavGoals = false; -bool NAVDEBUG_showCollision = false; -int NAVDEBUG_curGoal = 0; +bool NAVDEBUG_showNodes = false; +bool NAVDEBUG_showRadius = false; +bool NAVDEBUG_showEdges = false; +bool NAVDEBUG_showTestPath = false; +bool NAVDEBUG_showEnemyPath = false; +bool NAVDEBUG_showCombatPoints = false; +bool NAVDEBUG_showNavGoals = false; +bool NAVDEBUG_showCollision = false; +int NAVDEBUG_curGoal = 0; /* ------------------------- @@ -1622,99 +1459,74 @@ NAV_CalculatePaths #ifndef FINAL_BUILD int fatalErrors = 0; char *fatalErrorPointer = NULL; -char fatalErrorString[4096]; -qboolean NAV_WaypointsTooFar( gentity_t *wp1, gentity_t *wp2 ) -{ - if ( Distance( wp1->currentOrigin, wp2->currentOrigin ) > 1024 ) - { - char temp[1024]; - int len; +char fatalErrorString[4096]; +qboolean NAV_WaypointsTooFar(gentity_t *wp1, gentity_t *wp2) { + if (Distance(wp1->currentOrigin, wp2->currentOrigin) > 1024) { + char temp[1024]; + int len; fatalErrors++; - if ( !wp1->targetname && !wp2->targetname ) - { - sprintf( temp, S_COLOR_RED"Waypoint conn %s->%s > 1024\n", vtos( wp1->currentOrigin ), vtos( wp2->currentOrigin ) ); - } - else if ( !wp1->targetname ) - { - sprintf( temp, S_COLOR_RED"Waypoint conn %s->%s > 1024\n", vtos( wp1->currentOrigin ), wp2->targetname ); - } - else if ( !wp2->targetname ) - { - sprintf( temp, S_COLOR_RED"Waypoint conn %s->%s > 1024\n", wp1->targetname, vtos( wp2->currentOrigin ) ); - } - else - {//they both have valid targetnames - sprintf( temp, S_COLOR_RED"Waypoint conn %s->%s > 1024\n", wp1->targetname, wp2->targetname ); + if (!wp1->targetname && !wp2->targetname) { + sprintf(temp, S_COLOR_RED "Waypoint conn %s->%s > 1024\n", vtos(wp1->currentOrigin), vtos(wp2->currentOrigin)); + } else if (!wp1->targetname) { + sprintf(temp, S_COLOR_RED "Waypoint conn %s->%s > 1024\n", vtos(wp1->currentOrigin), wp2->targetname); + } else if (!wp2->targetname) { + sprintf(temp, S_COLOR_RED "Waypoint conn %s->%s > 1024\n", wp1->targetname, vtos(wp2->currentOrigin)); + } else { // they both have valid targetnames + sprintf(temp, S_COLOR_RED "Waypoint conn %s->%s > 1024\n", wp1->targetname, wp2->targetname); } - len = strlen( temp ); - if ( (fatalErrorPointer-fatalErrorString)+len >= (int)sizeof( fatalErrorString ) ) - { - Com_Error( ERR_DROP, "%s%s%dTOO MANY FATAL NAV ERRORS!!!\n", fatalErrorString, temp, fatalErrors ); + len = strlen(temp); + if ((fatalErrorPointer - fatalErrorString) + len >= (int)sizeof(fatalErrorString)) { + Com_Error(ERR_DROP, "%s%s%dTOO MANY FATAL NAV ERRORS!!!\n", fatalErrorString, temp, fatalErrors); return qtrue; } - strcat( fatalErrorPointer, temp ); + strcat(fatalErrorPointer, temp); fatalErrorPointer += len; return qtrue; - } - else - { + } else { return qfalse; } } #endif static int numStoredWaypoints = 0; -static waypointData_t *tempWaypointList=0; +static waypointData_t *tempWaypointList = 0; -void NAV_StoreWaypoint( gentity_t *ent ) -{ - if ( !tempWaypointList ) - { - tempWaypointList = (waypointData_t *) gi.Malloc(sizeof(waypointData_t)*MAX_STORED_WAYPOINTS, TAG_TEMP_WORKSPACE, qtrue); +void NAV_StoreWaypoint(gentity_t *ent) { + if (!tempWaypointList) { + tempWaypointList = (waypointData_t *)gi.Malloc(sizeof(waypointData_t) * MAX_STORED_WAYPOINTS, TAG_TEMP_WORKSPACE, qtrue); } - if ( numStoredWaypoints >= MAX_STORED_WAYPOINTS ) - { - G_Error( "Too many waypoints! (%d > %d)", numStoredWaypoints, MAX_STORED_WAYPOINTS ); + if (numStoredWaypoints >= MAX_STORED_WAYPOINTS) { + G_Error("Too many waypoints! (%d > %d)", numStoredWaypoints, MAX_STORED_WAYPOINTS); return; } - if ( ent->targetname ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].targetname, ent->targetname, MAX_QPATH ); + if (ent->targetname) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].targetname, ent->targetname, MAX_QPATH); } - if ( ent->target ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target, ent->target, MAX_QPATH ); + if (ent->target) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target, ent->target, MAX_QPATH); } - if ( ent->target2 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target2, ent->target2, MAX_QPATH ); + if (ent->target2) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target2, ent->target2, MAX_QPATH); } - if ( ent->target3 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target3, ent->target3, MAX_QPATH ); + if (ent->target3) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target3, ent->target3, MAX_QPATH); } - if ( ent->target4 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target4, ent->target4, MAX_QPATH ); + if (ent->target4) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target4, ent->target4, MAX_QPATH); } tempWaypointList[numStoredWaypoints].nodeID = ent->health; numStoredWaypoints++; } -int NAV_GetStoredWaypoint( char *targetname ) -{ - if ( !tempWaypointList || !targetname || !targetname[0] ) - { +int NAV_GetStoredWaypoint(char *targetname) { + if (!tempWaypointList || !targetname || !targetname[0]) { return -1; } - for ( int i = 0; i < numStoredWaypoints; i++ ) - { - if ( tempWaypointList[i].targetname[0] ) - { - if ( !Q_stricmp( targetname, tempWaypointList[i].targetname ) ) - { + for (int i = 0; i < numStoredWaypoints; i++) { + if (tempWaypointList[i].targetname[0]) { + if (!Q_stricmp(targetname, tempWaypointList[i].targetname)) { return i; } } @@ -1722,91 +1534,76 @@ int NAV_GetStoredWaypoint( char *targetname ) return -1; } -void NAV_CalculatePaths( const char *filename, int checksum ) -{ +void NAV_CalculatePaths(const char *filename, int checksum) { int target = -1; - if ( !tempWaypointList ) - { + if (!tempWaypointList) { return; } #ifndef FINAL_BUILD fatalErrors = 0; - memset( fatalErrorString, 0, sizeof( fatalErrorString ) ); + memset(fatalErrorString, 0, sizeof(fatalErrorString)); fatalErrorPointer = &fatalErrorString[0]; #endif #if _HARD_CONNECT - //Find all connections and hard connect them - for ( int i = 0; i < numStoredWaypoints; i++ ) - { - //Find the first connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target ); + // Find all connections and hard connect them + for (int i = 0; i < numStoredWaypoints; i++) { + // Find the first connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - navigator.HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { navigator.HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible second connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target2 ); + // Find a possible second connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target2); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - navigator.HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { navigator.HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible third connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target3 ); + // Find a possible third connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target3); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - navigator.HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { navigator.HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible fourth connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target4 ); + // Find a possible fourth connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target4); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - navigator.HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { navigator.HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } } #endif - //Remove all waypoints now that they're done + // Remove all waypoints now that they're done gi.Free(tempWaypointList); - tempWaypointList=0; + tempWaypointList = 0; - //Now check all blocked edges, mark failed ones + // Now check all blocked edges, mark failed ones navigator.CheckBlockedEdges(); navigator.pathsCalculated = qfalse; - //Calculate the paths based on the supplied waypoints - //navigator.CalculatePaths(); + // Calculate the paths based on the supplied waypoints + // navigator.CalculatePaths(); - //Save the resulting information + // Save the resulting information /* if ( navigator.Save( filename, checksum ) == qfalse ) { @@ -1814,10 +1611,9 @@ void NAV_CalculatePaths( const char *filename, int checksum ) } */ #ifndef FINAL_BUILD - if ( fatalErrors ) - { - //Com_Error( ERR_DROP, "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); - gi.Printf( "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); + if (fatalErrors) { + // Com_Error( ERR_DROP, "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); + gi.Printf("%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors); } #endif } @@ -1828,10 +1624,7 @@ NAV_Shutdown ------------------------- */ -void NAV_Shutdown( void ) -{ - navigator.Free(); -} +void NAV_Shutdown(void) { navigator.Free(); } /* ------------------------- @@ -1839,49 +1632,42 @@ NAV_ShowDebugInfo ------------------------- */ -void NAV_ShowDebugInfo( void ) -{ - if ( NAVDEBUG_showNodes ) - { +void NAV_ShowDebugInfo(void) { + if (NAVDEBUG_showNodes) { navigator.ShowNodes(); } - if ( NAVDEBUG_showEdges ) - { + if (NAVDEBUG_showEdges) { navigator.ShowEdges(); } - if ( NAVDEBUG_showTestPath ) - { - //Get the nearest node to the player - int nearestNode = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_ANY, WAYPOINT_NONE ); - int testNode = navigator.GetBestNode( nearestNode, NAVDEBUG_curGoal ); + if (NAVDEBUG_showTestPath) { + // Get the nearest node to the player + int nearestNode = navigator.GetNearestNode(&g_entities[0], g_entities[0].waypoint, NF_ANY, WAYPOINT_NONE); + int testNode = navigator.GetBestNode(nearestNode, NAVDEBUG_curGoal); - nearestNode = NAV_TestBestNode( &g_entities[0], nearestNode, testNode, qfalse ); + nearestNode = NAV_TestBestNode(&g_entities[0], nearestNode, testNode, qfalse); - //Show the connection - vec3_t dest, start; + // Show the connection + vec3_t dest, start; - //Get the positions - navigator.GetNodePosition( NAVDEBUG_curGoal, dest ); - navigator.GetNodePosition( nearestNode, start ); + // Get the positions + navigator.GetNodePosition(NAVDEBUG_curGoal, dest); + navigator.GetNodePosition(nearestNode, start); - CG_DrawNode( start, NODE_START ); - CG_DrawNode( dest, NODE_GOAL ); - navigator.ShowPath( nearestNode, NAVDEBUG_curGoal ); + CG_DrawNode(start, NODE_START); + CG_DrawNode(dest, NODE_GOAL); + navigator.ShowPath(nearestNode, NAVDEBUG_curGoal); } - if ( NAVDEBUG_showCombatPoints ) - { - for ( int i = 0; i < level.numCombatPoints; i++ ) - { - CG_DrawCombatPoint( level.combatPoints[i].origin, 0 ); + if (NAVDEBUG_showCombatPoints) { + for (int i = 0; i < level.numCombatPoints; i++) { + CG_DrawCombatPoint(level.combatPoints[i].origin, 0); } } - if ( NAVDEBUG_showNavGoals ) - { - TAG_ShowTags( RTF_NAVGOAL ); + if (NAVDEBUG_showNavGoals) { + TAG_ShowTags(RTF_NAVGOAL); } } @@ -1891,10 +1677,9 @@ NAV_FindPlayerWaypoint ------------------------- */ -void NAV_FindPlayerWaypoint( void ) -{ - g_entities[0].waypoint = navigator.GetNearestNode( &g_entities[0], g_entities[0].lastWaypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); +void NAV_FindPlayerWaypoint(void) { + g_entities[0].waypoint = navigator.GetNearestNode(&g_entities[0], g_entities[0].lastWaypoint, NF_CLEAR_PATH, WAYPOINT_NONE); } // -//JWEIER ADDITIONS END \ No newline at end of file +// JWEIER ADDITIONS END \ No newline at end of file diff --git a/codeJK2/game/g_navigator.cpp b/codeJK2/game/g_navigator.cpp index 024b3fad47..17885fdcf3 100644 --- a/codeJK2/game/g_navigator.cpp +++ b/codeJK2/game/g_navigator.cpp @@ -28,19 +28,17 @@ along with this program; if not, see . #include "g_nav.h" extern int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask); -extern qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ); -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean G_EntIsBreakable( int entityNum ); -extern qboolean G_EntIsRemovableUsable( int entNum ); +extern qboolean NAV_CheckNodeFailedForEnt(gentity_t *ent, int nodeNum); +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean G_EntIsBreakable(int entityNum); +extern qboolean G_EntIsRemovableUsable(int entNum); -extern cvar_t *d_altRoutes; -extern cvar_t *d_patched; - - -static vec3_t wpMaxs = { 16, 16, 32 }; -static vec3_t wpMins = { -16, -16, -24+STEPSIZE };//WTF: was 16??!!! +extern cvar_t *d_altRoutes; +extern cvar_t *d_patched; +static vec3_t wpMaxs = {16, 16, 32}; +static vec3_t wpMins = {-16, -16, -24 + STEPSIZE}; // WTF: was 16??!!! static byte CHECKED_NO = 0; static byte CHECKED_FAILED = 1; @@ -52,21 +50,15 @@ CEdge ------------------------- */ -CEdge::CEdge( void ) -{ - CEdge( -1, -1, -1 ); -} +CEdge::CEdge(void) { CEdge(-1, -1, -1); } -CEdge::CEdge( int first, int second, int cost ) -{ - m_first = first; - m_second = second; - m_cost = cost; +CEdge::CEdge(int first, int second, int cost) { + m_first = first; + m_second = second; + m_cost = cost; } -CEdge::~CEdge( void ) -{ -} +CEdge::~CEdge(void) {} /* ------------------------- @@ -74,19 +66,17 @@ CNode ------------------------- */ -CNode::CNode( void ) -{ - m_numEdges = 0; - m_radius = 0; - m_ranks = NULL; +CNode::CNode(void) { + m_numEdges = 0; + m_radius = 0; + m_ranks = NULL; } -CNode::~CNode( void ) -{ +CNode::~CNode(void) { m_edges.clear(); - if ( m_ranks ) - delete [] m_ranks; + if (m_ranks) + delete[] m_ranks; } /* @@ -95,11 +85,10 @@ Create ------------------------- */ -CNode *CNode::Create( vec3_t position, int flags, int radius, int ID ) -{ - CNode *node = new CNode; +CNode *CNode::Create(vec3_t position, int flags, int radius, int ID) { + CNode *node = new CNode; - VectorCopy( position, node->m_position ); + VectorCopy(position, node->m_position); node->m_flags = flags; node->m_ID = ID; @@ -114,10 +103,7 @@ Create ------------------------- */ -CNode *CNode::Create( void ) -{ - return new CNode; -} +CNode *CNode::Create(void) { return new CNode; } /* ------------------------- @@ -125,34 +111,30 @@ AddEdge ------------------------- */ -void CNode::AddEdge( int ID, int cost, int flags ) -{ - if ( m_numEdges ) - {//already have at least 1 - //see if it exists already - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( (*ei).ID == ID ) - {//found it - (*ei).cost = cost; - (*ei).flags = flags; +void CNode::AddEdge(int ID, int cost, int flags) { + if (m_numEdges) { // already have at least 1 + // see if it exists already + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if ((*ei).ID == ID) { // found it + (*ei).cost = cost; + (*ei).flags = flags; return; } } } - edge_t edge; + edge_t edge; - edge.ID = ID; - edge.cost = cost; - edge.flags = flags; + edge.ID = ID; + edge.cost = cost; + edge.flags = flags; - STL_INSERT( m_edges, edge ); + STL_INSERT(m_edges, edge); m_numEdges++; - assert( m_numEdges < 9 );//8 is the max + assert(m_numEdges < 9); // 8 is the max } /* @@ -161,15 +143,12 @@ GetEdge ------------------------- */ -int CNode::GetEdgeNumToNode( int ID ) -{ +int CNode::GetEdgeNumToNode(int ID) { int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( (*ei).ID == ID ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if ((*ei).ID == ID) { return count; } @@ -184,11 +163,10 @@ AddRank ------------------------- */ -void CNode::AddRank( int ID, int rank ) -{ - assert( m_ranks ); +void CNode::AddRank(int ID, int rank) { + assert(m_ranks); - m_ranks[ ID ] = rank; + m_ranks[ID] = rank; } /* @@ -197,12 +175,10 @@ Draw ------------------------- */ -void CNode::Draw( qboolean showRadius ) -{ - CG_DrawNode( m_position, NODE_NORMAL ); - if( showRadius ) - { - CG_DrawRadius( m_position, m_radius, NODE_NORMAL ); +void CNode::Draw(qboolean showRadius) { + CG_DrawNode(m_position, NODE_NORMAL); + if (showRadius) { + CG_DrawRadius(m_position, m_radius, NODE_NORMAL); } } @@ -212,18 +188,15 @@ GetEdge ------------------------- */ -int CNode::GetEdge( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +int CNode::GetEdge(int edgeNum) { + if (edgeNum > m_numEdges) return -1; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).ID; } @@ -239,18 +212,15 @@ GetEdgeCost ------------------------- */ -int CNode::GetEdgeCost( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +int CNode::GetEdgeCost(int edgeNum) { + if (edgeNum > m_numEdges) return Q3_INFINITE; // return -1; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).cost; } @@ -266,18 +236,15 @@ GetEdgeFlags ------------------------- */ -unsigned char CNode::GetEdgeFlags( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +unsigned char CNode::GetEdgeFlags(int edgeNum) { + if (edgeNum > m_numEdges) return 0; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).flags; } @@ -293,25 +260,21 @@ SetEdgeFlags ------------------------- */ -void CNode::SetEdgeFlags( int edgeNum, int newFlags ) -{ - if ( edgeNum > m_numEdges ) +void CNode::SetEdgeFlags(int edgeNum, int newFlags) { + if (edgeNum > m_numEdges) return; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { (*ei).flags = newFlags; return; } count++; } - } /* ------------------------- @@ -319,18 +282,16 @@ InitRanks ------------------------- */ -void CNode::InitRanks( int size ) -{ - //Clear it if it's already allocated - if ( m_ranks != NULL ) - { - delete [] m_ranks; +void CNode::InitRanks(int size) { + // Clear it if it's already allocated + if (m_ranks != NULL) { + delete[] m_ranks; m_ranks = NULL; } m_ranks = new int[size]; - memset( m_ranks, -1, sizeof(int)*size ); + memset(m_ranks, -1, sizeof(int) * size); } /* @@ -339,51 +300,44 @@ GetRank ------------------------- */ -int CNode::GetRank( int ID ) -{ - assert( m_ranks ); +int CNode::GetRank(int ID) { + assert(m_ranks); - return m_ranks[ ID ]; + return m_ranks[ID]; } - /* ------------------------- Save ------------------------- */ -int CNode::Save( int numNodes, fileHandle_t file ) -{ +int CNode::Save(int numNodes, fileHandle_t file) { int i; - //Write out the header + // Write out the header unsigned long header = NODE_HEADER_ID; - gi.FS_Write( &header, sizeof( header ), file ); + gi.FS_Write(&header, sizeof(header), file); - //Write out the basic information - for ( i = 0; i < 3; i++ ) - gi.FS_Write( &m_position[i], sizeof( float ), file ); + // Write out the basic information + for (i = 0; i < 3; i++) + gi.FS_Write(&m_position[i], sizeof(float), file); - gi.FS_Write( &m_flags, sizeof( m_flags ), file ); - gi.FS_Write( &m_ID, sizeof( m_ID ), file ); - gi.FS_Write( &m_radius, sizeof( m_radius ), file ); + gi.FS_Write(&m_flags, sizeof(m_flags), file); + gi.FS_Write(&m_ID, sizeof(m_ID), file); + gi.FS_Write(&m_radius, sizeof(m_radius), file); - //Write out the edge information - gi.FS_Write( &m_numEdges, sizeof( m_numEdges ), file ); + // Write out the edge information + gi.FS_Write(&m_numEdges, sizeof(m_numEdges), file); - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - gi.FS_Write( &(*ei), sizeof( edge_t ), file ); - } + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { gi.FS_Write(&(*ei), sizeof(edge_t), file); } - //Write out the node ranks - gi.FS_Write( &numNodes, sizeof( numNodes ), file ); + // Write out the node ranks + gi.FS_Write(&numNodes, sizeof(numNodes), file); - for ( i = 0; i < numNodes; i++ ) - { - gi.FS_Write( &m_ranks[i], sizeof( int ), file ); + for (i = 0; i < numNodes; i++) { + gi.FS_Write(&m_ranks[i], sizeof(int), file); } return true; @@ -395,47 +349,44 @@ Load ------------------------- */ -int CNode::Load( int numNodes, fileHandle_t file ) -{ +int CNode::Load(int numNodes, fileHandle_t file) { unsigned long header; int i; - gi.FS_Read( &header, sizeof(header), file ); + gi.FS_Read(&header, sizeof(header), file); - //Validate the header - if ( header != NODE_HEADER_ID ) + // Validate the header + if (header != NODE_HEADER_ID) return false; - //Get the basic information - for ( i = 0; i < 3; i++ ) - gi.FS_Read( &m_position[i], sizeof( float ), file ); + // Get the basic information + for (i = 0; i < 3; i++) + gi.FS_Read(&m_position[i], sizeof(float), file); - gi.FS_Read( &m_flags, sizeof( m_flags ), file ); - gi.FS_Read( &m_ID, sizeof( m_ID ), file ); - gi.FS_Read( &m_radius, sizeof( m_radius ), file ); + gi.FS_Read(&m_flags, sizeof(m_flags), file); + gi.FS_Read(&m_ID, sizeof(m_ID), file); + gi.FS_Read(&m_radius, sizeof(m_radius), file); - //Get the edge information - gi.FS_Read( &m_numEdges, sizeof( m_numEdges ), file ); + // Get the edge information + gi.FS_Read(&m_numEdges, sizeof(m_numEdges), file); - for ( i = 0; i < m_numEdges; i++ ) - { - edge_t edge; + for (i = 0; i < m_numEdges; i++) { + edge_t edge; - gi.FS_Read( &edge, sizeof( edge_t ), file ); + gi.FS_Read(&edge, sizeof(edge_t), file); - STL_INSERT( m_edges, edge ); + STL_INSERT(m_edges, edge); } - //Read the node ranks - int numRanks; + // Read the node ranks + int numRanks; - gi.FS_Read( &numRanks, sizeof( numRanks ), file ); + gi.FS_Read(&numRanks, sizeof(numRanks), file); - //Allocate the memory - InitRanks( numRanks ); + // Allocate the memory + InitRanks(numRanks); - for ( i = 0; i < numRanks; i++ ) - { - gi.FS_Read( &m_ranks[i], sizeof( int ), file ); + for (i = 0; i < numRanks; i++) { + gi.FS_Read(&m_ranks[i], sizeof(int), file); } return true; @@ -447,13 +398,9 @@ CNavigator ------------------------- */ -CNavigator::CNavigator( void ) -{ -} +CNavigator::CNavigator(void) {} -CNavigator::~CNavigator( void ) -{ -} +CNavigator::~CNavigator(void) {} /* ------------------------- @@ -461,14 +408,10 @@ FlagAllNodes ------------------------- */ -void CNavigator::FlagAllNodes( int newFlag ) -{ - node_v::iterator ni; +void CNavigator::FlagAllNodes(int newFlag) { + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->AddFlag( newFlag ); - } + STL_ITERATE(ni, m_nodes) { (*ni)->AddFlag(newFlag); } } /* @@ -477,11 +420,10 @@ GetChar ------------------------- */ -char CNavigator::GetChar( fileHandle_t file ) -{ +char CNavigator::GetChar(fileHandle_t file) { char value; - gi.FS_Read( &value, sizeof( value ), file ); + gi.FS_Read(&value, sizeof(value), file); return value; } @@ -492,11 +434,10 @@ GetInt ------------------------- */ -int CNavigator::GetInt( fileHandle_t file ) -{ +int CNavigator::GetInt(fileHandle_t file) { int value; - gi.FS_Read( &value, sizeof( value ), file ); + gi.FS_Read(&value, sizeof(value), file); return value; } @@ -507,11 +448,10 @@ GetFloat ------------------------- */ -float CNavigator::GetFloat( fileHandle_t file ) -{ +float CNavigator::GetFloat(fileHandle_t file) { float value; - gi.FS_Read( &value, sizeof( value ), file ); + gi.FS_Read(&value, sizeof(value), file); return value; } @@ -522,11 +462,10 @@ GetLong ------------------------- */ -long CNavigator::GetLong( fileHandle_t file ) -{ +long CNavigator::GetLong(fileHandle_t file) { long value; - gi.FS_Read( &value, sizeof( value ), file ); + gi.FS_Read(&value, sizeof(value), file); return value; } @@ -537,10 +476,7 @@ Init ------------------------- */ -void CNavigator::Init( void ) -{ - Free(); -} +void CNavigator::Init(void) { Free(); } /* ------------------------- @@ -548,14 +484,10 @@ Free ------------------------- */ -void CNavigator::Free( void ) -{ - node_v::iterator ni; +void CNavigator::Free(void) { + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - delete (*ni); - } + STL_ITERATE(ni, m_nodes) { delete (*ni); } } /* @@ -564,59 +496,52 @@ Load ------------------------- */ -bool CNavigator::Load( const char *filename, int checksum ) -{ - fileHandle_t file; +bool CNavigator::Load(const char *filename, int checksum) { + fileHandle_t file; - //Attempt to load the file - gi.FS_FOpenFile( va( "maps/%s.nav", filename ), &file, FS_READ ); + // Attempt to load the file + gi.FS_FOpenFile(va("maps/%s.nav", filename), &file, FS_READ); - //See if we succeeded - if ( file == NULL_FILE ) + // See if we succeeded + if (file == NULL_FILE) return false; - //Check the header id - long navID = GetLong( file ); + // Check the header id + long navID = GetLong(file); - if ( navID != NAV_HEADER_ID ) - { - gi.FS_FCloseFile( file ); + if (navID != NAV_HEADER_ID) { + gi.FS_FCloseFile(file); return false; } - //Check the checksum to see if this file is out of date - int check = GetInt( file ); + // Check the checksum to see if this file is out of date + int check = GetInt(file); - if ( check != checksum ) - { - gi.FS_FCloseFile( file ); + if (check != checksum) { + gi.FS_FCloseFile(file); return false; } - int numNodes = GetInt( file ); + int numNodes = GetInt(file); - for ( int i = 0; i < numNodes; i++ ) - { - CNode *node = CNode::Create(); + for (int i = 0; i < numNodes; i++) { + CNode *node = CNode::Create(); - if ( node->Load( numNodes, file ) == false ) - { - gi.FS_FCloseFile( file ); + if (node->Load(numNodes, file) == false) { + gi.FS_FCloseFile(file); return false; } - STL_INSERT( m_nodes, node ); + STL_INSERT(m_nodes, node); } - //read in the failed edges - gi.FS_Read( &failedEdges, sizeof( failedEdges ), file ); - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { + // read in the failed edges + gi.FS_Read(&failedEdges, sizeof(failedEdges), file); + for (int j = 0; j < MAX_FAILED_EDGES; j++) { m_edgeLookupMap.insert(std::pair(failedEdges[j].startID, j)); } - - gi.FS_FCloseFile( file ); + gi.FS_FCloseFile(file); return true; } @@ -627,41 +552,37 @@ Save ------------------------- */ -bool CNavigator::Save( const char *filename, int checksum ) -{ - fileHandle_t file; +bool CNavigator::Save(const char *filename, int checksum) { + fileHandle_t file; - //Attempt to load the file - gi.FS_FOpenFile( va( "maps/%s.nav", filename ), &file, FS_WRITE ); + // Attempt to load the file + gi.FS_FOpenFile(va("maps/%s.nav", filename), &file, FS_WRITE); - if ( file == NULL_FILE ) + if (file == NULL_FILE) return false; - //Write out the header id + // Write out the header id unsigned long id = NAV_HEADER_ID; - gi.FS_Write( &id, sizeof (id), file ); + gi.FS_Write(&id, sizeof(id), file); - //Write out the checksum - gi.FS_Write( &checksum, sizeof( checksum ), file ); + // Write out the checksum + gi.FS_Write(&checksum, sizeof(checksum), file); - int numNodes = m_nodes.size(); + int numNodes = m_nodes.size(); - //Write out the number of nodes to follow - gi.FS_Write( &numNodes, sizeof(numNodes), file ); + // Write out the number of nodes to follow + gi.FS_Write(&numNodes, sizeof(numNodes), file); - //Write out all the nodes - node_v::iterator ni; + // Write out all the nodes + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->Save( numNodes, file ); - } + STL_ITERATE(ni, m_nodes) { (*ni)->Save(numNodes, file); } - //write out failed edges - gi.FS_Write( &failedEdges, sizeof( failedEdges ), file ); + // write out failed edges + gi.FS_Write(&failedEdges, sizeof(failedEdges), file); - gi.FS_FCloseFile( file ); + gi.FS_FCloseFile(file); return true; } @@ -672,20 +593,18 @@ AddRawPoint ------------------------- */ -int CNavigator::AddRawPoint( vec3_t point, int flags, int radius ) -{ - CNode *node = CNode::Create( point, flags, radius, m_nodes.size() ); +int CNavigator::AddRawPoint(vec3_t point, int flags, int radius) { + CNode *node = CNode::Create(point, flags, radius, m_nodes.size()); - if ( node == NULL ) - { - Com_Error( ERR_DROP, "Error adding node!\n" ); + if (node == NULL) { + Com_Error(ERR_DROP, "Error adding node!\n"); return -1; } - //TODO: Validate the position - //TODO: Correct stuck waypoints + // TODO: Validate the position + // TODO: Correct stuck waypoints - STL_INSERT( m_nodes, node ); + STL_INSERT(m_nodes, node); return node->GetID(); } @@ -696,52 +615,48 @@ GetEdgeCost ------------------------- */ -int CNavigator::GetEdgeCost( CNode *first, CNode *second ) -{ - trace_t trace; - vec3_t start, end; - vec3_t mins, maxs; +int CNavigator::GetEdgeCost(CNode *first, CNode *second) { + trace_t trace; + vec3_t start, end; + vec3_t mins, maxs; - //Setup the player size - VectorSet( mins, -8, -8, -8 ); - VectorSet( maxs, 8, 8, 8 ); + // Setup the player size + VectorSet(mins, -8, -8, -8); + VectorSet(maxs, 8, 8, 8); - //Setup the points - first->GetPosition( start ); - second->GetPosition( end ); + // Setup the points + first->GetPosition(start); + second->GetPosition(end); - gi.trace( &trace, start, mins, maxs, end, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, start, mins, maxs, end, ENTITYNUM_NONE, MASK_SOLID, G2_NOCOLLIDE, 0); - if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) return Q3_INFINITE; // return -1; - //Connection successful, return the cost - return Distance( start, end ); + // Connection successful, return the cost + return Distance(start, end); } -void CNavigator::SetEdgeCost( int ID1, int ID2, int cost ) -{ - if( (ID1 == -1) || (ID2 == -1) ) - {//not valid nodes, must have come from the ClearAllFailedEdges initization-type calls +void CNavigator::SetEdgeCost(int ID1, int ID2, int cost) { + if ((ID1 == -1) || (ID2 == -1)) { // not valid nodes, must have come from the ClearAllFailedEdges initization-type calls return; } - CNode *node1 = m_nodes[ID1]; - CNode *node2 = m_nodes[ID2]; + CNode *node1 = m_nodes[ID1]; + CNode *node2 = m_nodes[ID2]; - if ( cost == -1 ) - {//they want us to calc it - //FIXME: can we just remember this instead of recalcing every time? - vec3_t pos1, pos2; + if (cost == -1) { // they want us to calc it + // FIXME: can we just remember this instead of recalcing every time? + vec3_t pos1, pos2; - node1->GetPosition( pos1 ); - node2->GetPosition( pos2 ); - cost = Distance( pos1, pos2 ); + node1->GetPosition(pos1); + node2->GetPosition(pos2); + cost = Distance(pos1, pos2); } - //set it - node1->AddEdge( ID2, cost ); - node2->AddEdge( ID1, cost ); + // set it + node1->AddEdge(ID2, cost); + node2->AddEdge(ID1, cost); } /* @@ -750,23 +665,21 @@ AddNodeEdges ------------------------- */ -void CNavigator::AddNodeEdges( CNode *node, int addDist, edge_l &edgeList, bool *checkedNodes ) -{ - //Add all edge - for ( int i = 0; i < node->GetNumEdges(); i++ ) - { - //Make sure we don't add an old edge twice - if ( checkedNodes[ node->GetEdge( i ) ] == true ) +void CNavigator::AddNodeEdges(CNode *node, int addDist, edge_l &edgeList, bool *checkedNodes) { + // Add all edge + for (int i = 0; i < node->GetNumEdges(); i++) { + // Make sure we don't add an old edge twice + if (checkedNodes[node->GetEdge(i)] == true) continue; - //Get the node - CNode *nextNode = m_nodes[ node->GetEdge( i ) ]; + // Get the node + CNode *nextNode = m_nodes[node->GetEdge(i)]; - //This node has now been checked - checkedNodes[ nextNode->GetID() ] = true; + // This node has now been checked + checkedNodes[nextNode->GetID()] = true; - //Add it to the list - STL_INSERT( edgeList, CEdge( nextNode->GetID(), node->GetID(), addDist + ( node->GetEdgeCost( i ) ) ) ); + // Add it to the list + STL_INSERT(edgeList, CEdge(nextNode->GetID(), node->GetID(), addDist + (node->GetEdgeCost(i)))); } } @@ -776,67 +689,62 @@ CalculatePath ------------------------- */ -void CNavigator::CalculatePath( CNode *node ) -{ - int curRank = 0; - int i; +void CNavigator::CalculatePath(CNode *node) { + int curRank = 0; + int i; - CPriorityQueue *pathList = new CPriorityQueue(); - unsigned char *checked; + CPriorityQueue *pathList = new CPriorityQueue(); + unsigned char *checked; - //Init the completion table - checked = new unsigned char[ m_nodes.size() ]; - memset( checked, 0, m_nodes.size() ); + // Init the completion table + checked = new unsigned char[m_nodes.size()]; + memset(checked, 0, m_nodes.size()); - //Mark this node as checked - checked[ node->GetID() ] = true; - node->AddRank( node->GetID(), curRank++ ); + // Mark this node as checked + checked[node->GetID()] = true; + node->AddRank(node->GetID(), curRank++); - //Add all initial nodes - for ( i = 0; i < node->GetNumEdges(); i++ ) - { - CNode *nextNode = m_nodes[ node->GetEdge(i) ]; + // Add all initial nodes + for (i = 0; i < node->GetNumEdges(); i++) { + CNode *nextNode = m_nodes[node->GetEdge(i)]; assert(nextNode); - checked[ nextNode->GetID() ] = true; + checked[nextNode->GetID()] = true; - pathList->Push( new CEdge( nextNode->GetID(), nextNode->GetID(), node->GetEdgeCost(i) ) ); + pathList->Push(new CEdge(nextNode->GetID(), nextNode->GetID(), node->GetEdgeCost(i))); } CEdge *test; - //Now flood fill all the others - while ( !pathList->Empty() ) - { - test = pathList->Pop(); + // Now flood fill all the others + while (!pathList->Empty()) { + test = pathList->Pop(); - CNode *testNode = m_nodes[ (*test).m_first ]; - assert( testNode ); + CNode *testNode = m_nodes[(*test).m_first]; + assert(testNode); - node->AddRank( testNode->GetID(), curRank++ ); + node->AddRank(testNode->GetID(), curRank++); - //Add in all the new edges - for ( i = 0; i < testNode->GetNumEdges(); i++ ) - { - CNode *addNode = m_nodes[ testNode->GetEdge(i) ]; - assert( addNode ); + // Add in all the new edges + for (i = 0; i < testNode->GetNumEdges(); i++) { + CNode *addNode = m_nodes[testNode->GetEdge(i)]; + assert(addNode); - if ( checked[ addNode->GetID() ] ) + if (checked[addNode->GetID()]) continue; - int newDist = (*test).m_cost + testNode->GetEdgeCost(i); - pathList->Push( new CEdge( addNode->GetID(), (*test).m_second, newDist ) ); + int newDist = (*test).m_cost + testNode->GetEdgeCost(i); + pathList->Push(new CEdge(addNode->GetID(), (*test).m_second, newDist)); - checked[ addNode->GetID() ] = true; + checked[addNode->GetID()] = true; } delete test; - } - node->RemoveFlag( NF_RECALC ); + node->RemoveFlag(NF_RECALC); delete pathList; - delete [] checked; + delete[] checked; } /* @@ -844,36 +752,32 @@ void CNavigator::CalculatePath( CNode *node ) CalculatePaths ------------------------- */ -extern void CP_FindCombatPointWaypoints( void ); -void CNavigator::CalculatePaths( bool recalc ) -{ +extern void CP_FindCombatPointWaypoints(void); +void CNavigator::CalculatePaths(bool recalc) { #ifndef FINAL_BUILD - int startTime = gi.Milliseconds(); + int startTime = gi.Milliseconds(); #endif #if _HARD_CONNECT #else #endif int i; - for ( i = 0; i < (int)m_nodes.size(); i++ ) - { - //Allocate the needed memory - m_nodes[i]->InitRanks( m_nodes.size() ); + for (i = 0; i < (int)m_nodes.size(); i++) { + // Allocate the needed memory + m_nodes[i]->InitRanks(m_nodes.size()); } - for ( i = 0; i < (int)m_nodes.size(); i++ ) - { - CalculatePath( m_nodes[i] ); + for (i = 0; i < (int)m_nodes.size(); i++) { + CalculatePath(m_nodes[i]); } #ifndef FINAL_BUILD - if ( pathsCalculated ) - { - gi.Printf( S_COLOR_CYAN"%s recalced paths in %d ms\n", (NPC!=NULL?NPC->targetname:"NULL"), gi.Milliseconds()-startTime ); + if (pathsCalculated) { + gi.Printf(S_COLOR_CYAN "%s recalced paths in %d ms\n", (NPC != NULL ? NPC->targetname : "NULL"), gi.Milliseconds() - startTime); } #endif - if(!recalc) //Mike says doesn't need to happen on recalc + if (!recalc) // Mike says doesn't need to happen on recalc { CP_FindCombatPointWaypoints(); } @@ -887,38 +791,29 @@ ShowNodes ------------------------- */ -void CNavigator::ShowNodes( void ) -{ - node_v::iterator ni; +void CNavigator::ShowNodes(void) { + node_v::iterator ni; - vec3_t position; + vec3_t position; qboolean showRadius; - float dist, - radius; + float dist, radius; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->GetPosition( position ); + STL_ITERATE(ni, m_nodes) { + (*ni)->GetPosition(position); showRadius = qfalse; - if( NAVDEBUG_showRadius ) - { - dist = DistanceSquared( g_entities[0].currentOrigin, position ); + if (NAVDEBUG_showRadius) { + dist = DistanceSquared(g_entities[0].currentOrigin, position); radius = (*ni)->GetRadius(); // if player within node radius or 256, draw radius (sometimes the radius is really small, so we check for 256 to catch everything) - if( (dist <= radius*radius) || dist <= 65536 ) - { + if ((dist <= radius * radius) || dist <= 65536) { showRadius = qtrue; } + } else { + dist = DistanceSquared(g_entities[0].currentOrigin, position); } - else - { - dist = DistanceSquared( g_entities[0].currentOrigin, position ); - } - if ( dist < 1048576 ) - { - if ( gi.inPVS( g_entities[0].currentOrigin, position ) ) - { + if (dist < 1048576) { + if (gi.inPVS(g_entities[0].currentOrigin, position)) { (*ni)->Draw(showRadius); } } @@ -931,141 +826,120 @@ ShowEdges ------------------------- */ -typedef std::map < int, bool > drawMap_m; +typedef std::map drawMap_m; -void CNavigator::ShowEdges( void ) -{ - node_v::iterator ni; - vec3_t start, end; +void CNavigator::ShowEdges(void) { + node_v::iterator ni; + vec3_t start, end; - drawMap_m *drawMap; + drawMap_m *drawMap; - drawMap = new drawMap_m[ m_nodes.size() ]; + drawMap = new drawMap_m[m_nodes.size()]; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->GetPosition( start ); - if ( DistanceSquared( g_entities[0].currentOrigin, start ) >= 1048576 ) - { + STL_ITERATE(ni, m_nodes) { + (*ni)->GetPosition(start); + if (DistanceSquared(g_entities[0].currentOrigin, start) >= 1048576) { continue; } - if ( !gi.inPVSIgnorePortals( g_entities[0].currentOrigin, start ) ) - { + if (!gi.inPVSIgnorePortals(g_entities[0].currentOrigin, start)) { continue; } - //Attempt to draw each connection - for ( int i = 0; i < (*ni)->GetNumEdges(); i++ ) - { - int id = (*ni)->GetEdge( i ); + // Attempt to draw each connection + for (int i = 0; i < (*ni)->GetNumEdges(); i++) { + int id = (*ni)->GetEdge(i); - if ( id == -1 ) + if (id == -1) continue; - //Already drawn? - if ( drawMap[(*ni)->GetID()].find( id ) != drawMap[(*ni)->GetID()].end() ) + // Already drawn? + if (drawMap[(*ni)->GetID()].find(id) != drawMap[(*ni)->GetID()].end()) continue; - unsigned char flags = (*ni)->GetEdgeFlags( i ); + unsigned char flags = (*ni)->GetEdgeFlags(i); - CNode *node = m_nodes[id]; + CNode *node = m_nodes[id]; - node->GetPosition( end ); + node->GetPosition(end); - //Set this as drawn + // Set this as drawn drawMap[id][(*ni)->GetID()] = true; - if ( DistanceSquared( g_entities[0].currentOrigin, end ) >= 1048576 ) - { + if (DistanceSquared(g_entities[0].currentOrigin, end) >= 1048576) { continue; } - if ( !gi.inPVSIgnorePortals( g_entities[0].currentOrigin, end ) ) + if (!gi.inPVSIgnorePortals(g_entities[0].currentOrigin, end)) continue; - if ( EdgeFailed( id, (*ni)->GetID() ) != -1 )//flags & EFLAG_FAILED ) - CG_DrawEdge( start, end, EDGE_FAILED ); - else if ( flags & EFLAG_BLOCKED ) - CG_DrawEdge( start, end, EDGE_BLOCKED ); + if (EdgeFailed(id, (*ni)->GetID()) != -1) // flags & EFLAG_FAILED ) + CG_DrawEdge(start, end, EDGE_FAILED); + else if (flags & EFLAG_BLOCKED) + CG_DrawEdge(start, end, EDGE_BLOCKED); else - CG_DrawEdge( start, end, EDGE_NORMAL ); + CG_DrawEdge(start, end, EDGE_NORMAL); } } - delete [] drawMap; + delete[] drawMap; } -int CNavigator::GetNodeRadius( int nodeID ) -{ - if ( m_nodes.size() == 0 ) +int CNavigator::GetNodeRadius(int nodeID) { + if (m_nodes.size() == 0) return 0; return m_nodes[nodeID]->GetRadius(); } -void CNavigator::CheckBlockedEdges( void ) -{ - CNode *start, *end; - vec3_t p1, p2; - int flags, first, second; - trace_t trace; +void CNavigator::CheckBlockedEdges(void) { + CNode *start, *end; + vec3_t p1, p2; + int flags, first, second; + trace_t trace; qboolean failed; - int edgeNum; - node_v::iterator ni; - - //Go through all edges and test the ones that were blocked - STL_ITERATE( ni, m_nodes ) - { - //Attempt to draw each connection - for ( edgeNum = 0; edgeNum < (*ni)->GetNumEdges(); edgeNum++ ) - { - flags = (*ni)->GetEdgeFlags( edgeNum ); - if ( (flags&EFLAG_BLOCKED) ) - { - first = (*ni)->GetID(); - second = (*ni)->GetEdge( edgeNum ); - start = m_nodes[first]; - end = m_nodes[second]; - failed = qfalse; - - start->GetPosition( p1 ); - end->GetPosition( p2 ); - - //FIXME: can't we just store the trace.entityNum from the HardConnect trace? So we don't have to do another trace here... - gi.trace( &trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - - if ( trace.entityNum < ENTITYNUM_WORLD && (trace.fraction < 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue) ) - {//could be assumed, since failed before - if ( G_EntIsDoor( trace.entityNum ) ) - {//door - if ( !G_EntIsUnlockedDoor( trace.entityNum ) ) - {//locked door + int edgeNum; + node_v::iterator ni; + + // Go through all edges and test the ones that were blocked + STL_ITERATE(ni, m_nodes) { + // Attempt to draw each connection + for (edgeNum = 0; edgeNum < (*ni)->GetNumEdges(); edgeNum++) { + flags = (*ni)->GetEdgeFlags(edgeNum); + if ((flags & EFLAG_BLOCKED)) { + first = (*ni)->GetID(); + second = (*ni)->GetEdge(edgeNum); + start = m_nodes[first]; + end = m_nodes[second]; + failed = qfalse; + + start->GetPosition(p1); + end->GetPosition(p2); + + // FIXME: can't we just store the trace.entityNum from the HardConnect trace? So we don't have to do another trace here... + gi.trace(&trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + + if (trace.entityNum < ENTITYNUM_WORLD && + (trace.fraction < 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue)) { // could be assumed, since failed before + if (G_EntIsDoor(trace.entityNum)) { // door + if (!G_EntIsUnlockedDoor(trace.entityNum)) { // locked door failed = qtrue; } - } - else - { - if ( G_EntIsBreakable( trace.entityNum ) ) - {//do same for breakable brushes/models/glass? + } else { + if (G_EntIsBreakable(trace.entityNum)) { // do same for breakable brushes/models/glass? failed = qtrue; - } - else if ( G_EntIsRemovableUsable( trace.entityNum ) ) - { + } else if (G_EntIsRemovableUsable(trace.entityNum)) { failed = qtrue; - } - else if ( trace.allsolid || trace.startsolid ) - {//FIXME: the entitynum would be none here, so how do we know if this is stuck inside an ent or the world? - } - else - {//FIXME: what about func_plats and scripted movers? + } else if (trace.allsolid || + trace + .startsolid) { // FIXME: the entitynum would be none here, so how do we know if this is stuck inside an ent or the world? + } else { // FIXME: what about func_plats and scripted movers? } } } - if ( failed ) - { - //could add the EFLAG_FAILED to the two edges, but we stopped doing that since it was pointless - AddFailedEdge( ENTITYNUM_NONE, first, second ); + if (failed) { + // could add the EFLAG_FAILED to the two edges, but we stopped doing that since it was pointless + AddFailedEdge(ENTITYNUM_NONE, first, second); } } } @@ -1080,33 +954,31 @@ HardConnect ------------------------- */ -void CNavigator::HardConnect( int first, int second ) -{ - CNode *start, *end; +void CNavigator::HardConnect(int first, int second) { + CNode *start, *end; - start = m_nodes[first]; - end = m_nodes[second]; + start = m_nodes[first]; + end = m_nodes[second]; - vec3_t p1, p2; + vec3_t p1, p2; - start->GetPosition( p1 ); - end->GetPosition( p2 ); + start->GetPosition(p1); + end->GetPosition(p2); - trace_t trace; + trace_t trace; - int flags = EFLAG_NONE; + int flags = EFLAG_NONE; - gi.trace( &trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID|CONTENTS_BOTCLIP|CONTENTS_MONSTERCLIP, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID | CONTENTS_BOTCLIP | CONTENTS_MONSTERCLIP, G2_NOCOLLIDE, 0); - int cost = Distance( p1, p2 ); + int cost = Distance(p1, p2); - if ( trace.fraction != 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue ) - { + if (trace.fraction != 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue) { flags |= EFLAG_BLOCKED; } - start->AddEdge( second, cost, flags ); - end->AddEdge( first, cost, flags ); + start->AddEdge(second, cost, flags); + end->AddEdge(first, cost, flags); } #endif @@ -1117,16 +989,14 @@ TestNodePath ------------------------- */ -int CNavigator::TestNodePath( gentity_t *ent, int okToHitEntNum, vec3_t position, qboolean includeEnts ) -{ +int CNavigator::TestNodePath(gentity_t *ent, int okToHitEntNum, vec3_t position, qboolean includeEnts) { int clipmask = ent->clipmask; - if ( !includeEnts ) - { + if (!includeEnts) { clipmask &= ~CONTENTS_BODY; } - //Check the path - if ( NAV_ClearPathToPoint( ent, ent->mins, ent->maxs, position, clipmask, okToHitEntNum ) == false ) + // Check the path + if (NAV_ClearPathToPoint(ent, ent->mins, ent->maxs, position, clipmask, okToHitEntNum) == false) return false; return true; @@ -1138,10 +1008,7 @@ TestNodeLOS ------------------------- */ -int CNavigator::TestNodeLOS( gentity_t *ent, vec3_t position ) -{ - return NPC_ClearLOS( ent, position ); -} +int CNavigator::TestNodeLOS(gentity_t *ent, vec3_t position) { return NPC_ClearLOS(ent, position); } /* ------------------------- @@ -1149,56 +1016,49 @@ TestBestFirst ------------------------- */ -int CNavigator::TestBestFirst( gentity_t *ent, int lastID, int flags ) -{ - //Must be a valid one to begin with - if ( lastID == NODE_NONE ) +int CNavigator::TestBestFirst(gentity_t *ent, int lastID, int flags) { + // Must be a valid one to begin with + if (lastID == NODE_NONE) return NODE_NONE; - if ( lastID >= (int)m_nodes.size() ) + if (lastID >= (int)m_nodes.size()) return NODE_NONE; - //Get the info - vec3_t nodePos; - CNode *node = m_nodes[ lastID ]; - CNode *testNode; - int numEdges = node->GetNumEdges(); - float dist; + // Get the info + vec3_t nodePos; + CNode *node = m_nodes[lastID]; + CNode *testNode; + int numEdges = node->GetNumEdges(); + float dist; - node->GetPosition( nodePos ); + node->GetPosition(nodePos); - //Setup our last node as our root, and search for a closer one according to its edges - int bestNode = ( TestNodePath( ent, ENTITYNUM_NONE, nodePos, qtrue ) ) ? lastID : NODE_NONE; - float bestDist = ( bestNode == NODE_NONE ) ? Q3_INFINITE : DistanceSquared( ent->currentOrigin, nodePos ); + // Setup our last node as our root, and search for a closer one according to its edges + int bestNode = (TestNodePath(ent, ENTITYNUM_NONE, nodePos, qtrue)) ? lastID : NODE_NONE; + float bestDist = (bestNode == NODE_NONE) ? Q3_INFINITE : DistanceSquared(ent->currentOrigin, nodePos); - //Test all these edges first - for ( int i = 0; i < numEdges; i++ ) - { - //Get this node and its distance - testNode = m_nodes[ node->GetEdge(i) ]; + // Test all these edges first + for (int i = 0; i < numEdges; i++) { + // Get this node and its distance + testNode = m_nodes[node->GetEdge(i)]; - if ( NodeFailed( ent, testNode->GetID() ) ) - { + if (NodeFailed(ent, testNode->GetID())) { continue; } - testNode->GetPosition( nodePos ); + testNode->GetPosition(nodePos); - dist = DistanceSquared( ent->currentOrigin, nodePos ); + dist = DistanceSquared(ent->currentOrigin, nodePos); - //Test against current best - if ( dist < bestDist ) - { - //See if this node is valid - if ( CheckedNode(testNode->GetID(),ent->s.number) == CHECKED_PASSED || TestNodePath( ent, ENTITYNUM_NONE, nodePos, qtrue ) ) - { + // Test against current best + if (dist < bestDist) { + // See if this node is valid + if (CheckedNode(testNode->GetID(), ent->s.number) == CHECKED_PASSED || TestNodePath(ent, ENTITYNUM_NONE, nodePos, qtrue)) { bestDist = dist; bestNode = testNode->GetID(); - SetCheckedNode(testNode->GetID(),ent->s.number,CHECKED_PASSED); - } - else - { - SetCheckedNode(testNode->GetID(),ent->s.number,CHECKED_FAILED); + SetCheckedNode(testNode->GetID(), ent->s.number, CHECKED_PASSED); + } else { + SetCheckedNode(testNode->GetID(), ent->s.number, CHECKED_FAILED); } } } @@ -1212,61 +1072,55 @@ CollectNearestNodes ------------------------- */ -#define NODE_COLLECT_MAX 16 //Maximum # of nodes collected at any time -#define NODE_COLLECT_RADIUS 512 //Default radius to search for nodes in -#define NODE_COLLECT_RADIUS_SQR ( NODE_COLLECT_RADIUS * NODE_COLLECT_RADIUS ) - -int CNavigator::CollectNearestNodes( vec3_t origin, int radius, int maxCollect, nodeChain_l &nodeChain ) -{ - node_v::iterator ni; - float dist; - vec3_t position; - int collected = 0; - bool added = false; - - //Get a distance rating for each node in the system - STL_ITERATE( ni, m_nodes ) - { - //If we've got our quota, then stop looking - //Get the distance to the node - (*ni)->GetPosition( position ); - dist = DistanceSquared( position, origin ); - - //Must be within our radius range - if ( dist > (float) ( radius * radius ) ) +#define NODE_COLLECT_MAX 16 // Maximum # of nodes collected at any time +#define NODE_COLLECT_RADIUS 512 // Default radius to search for nodes in +#define NODE_COLLECT_RADIUS_SQR (NODE_COLLECT_RADIUS * NODE_COLLECT_RADIUS) + +int CNavigator::CollectNearestNodes(vec3_t origin, int radius, int maxCollect, nodeChain_l &nodeChain) { + node_v::iterator ni; + float dist; + vec3_t position; + int collected = 0; + bool added = false; + + // Get a distance rating for each node in the system + STL_ITERATE(ni, m_nodes) { + // If we've got our quota, then stop looking + // Get the distance to the node + (*ni)->GetPosition(position); + dist = DistanceSquared(position, origin); + + // Must be within our radius range + if (dist > (float)(radius * radius)) continue; - nodeList_t nChain; - nodeChain_l::iterator nci; + nodeList_t nChain; + nodeChain_l::iterator nci; - //Always add the first node - if ( nodeChain.size() == 0 ) - { + // Always add the first node + if (nodeChain.size() == 0) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nodeChain.begin(), nChain ); + nodeChain.insert(nodeChain.begin(), nChain); continue; } added = false; - //Compare it to what we already have - STL_ITERATE( nci, nodeChain ) - { - //If we're less, than this entry, then insert before it - if ( dist < (*nci).distance ) - { + // Compare it to what we already have + STL_ITERATE(nci, nodeChain) { + // If we're less, than this entry, then insert before it + if (dist < (*nci).distance) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nci, nChain ); + nodeChain.insert(nci, nChain); collected = nodeChain.size(); added = true; - //If we've hit our collection limit, throw off the oldest one - if ( (int)nodeChain.size() > maxCollect ) - { + // If we've hit our collection limit, throw off the oldest one + if ((int)nodeChain.size() > maxCollect) { nodeChain.pop_back(); } @@ -1274,188 +1128,160 @@ int CNavigator::CollectNearestNodes( vec3_t origin, int radius, int maxCollect, } } - //Otherwise, always pad out the collection if possible so we don't miss anything - if ( ( added == false ) && ( (int)nodeChain.size() < maxCollect ) ) - { + // Otherwise, always pad out the collection if possible so we don't miss anything + if ((added == false) && ((int)nodeChain.size() < maxCollect)) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nodeChain.end(), nChain ); + nodeChain.insert(nodeChain.end(), nChain); } } return collected; } -int CNavigator::GetBestPathBetweenEnts( gentity_t *ent, gentity_t *goal, int flags ) -{ - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetBestPathBetweenEnts(gentity_t *ent, gentity_t *goal, int flags) { + // Must have nodes + if (m_nodes.size() == 0) return NODE_NONE; -#define MAX_Z_DELTA 18 +#define MAX_Z_DELTA 18 - nodeChain_l nodeChain; - nodeChain_l::iterator nci; - nodeChain_l nodeChain2; - nodeChain_l::iterator nci2; + nodeChain_l nodeChain; + nodeChain_l::iterator nci; + nodeChain_l nodeChain2; + nodeChain_l::iterator nci2; - //Collect all nodes within a certain radius - CollectNearestNodes( ent->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain ); - CollectNearestNodes( goal->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain2 ); + // Collect all nodes within a certain radius + CollectNearestNodes(ent->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain); + CollectNearestNodes(goal->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain2); - vec3_t position; - vec3_t position2; - int radius; - int cost, pathCost, bestCost = Q3_INFINITE; - CNode *node, *node2; - int nodeNum, nodeNum2; - int nextNode = NODE_NONE, bestNode = NODE_NONE; - int nodeFlags = 0; -// bool recalc = false; + vec3_t position; + vec3_t position2; + int radius; + int cost, pathCost, bestCost = Q3_INFINITE; + CNode *node, *node2; + int nodeNum, nodeNum2; + int nextNode = NODE_NONE, bestNode = NODE_NONE; + int nodeFlags = 0; + // bool recalc = false; ent->waypoint = NODE_NONE; goal->waypoint = NODE_NONE; - //Look through all nodes - STL_ITERATE( nci, nodeChain ) - { + // Look through all nodes + STL_ITERATE(nci, nodeChain) { node = m_nodes[(*nci).nodeID]; nodeNum = (*nci).nodeID; - node->GetPosition( position ); + node->GetPosition(position); - if ( CheckedNode(nodeNum,ent->s.number) == CHECKED_FAILED ) - {//already checked this node against ent and it failed + if (CheckedNode(nodeNum, ent->s.number) == CHECKED_FAILED) { // already checked this node against ent and it failed continue; } - if ( CheckedNode(nodeNum,ent->s.number) == CHECKED_PASSED ) - {//already checked this node against ent and it passed - } - else - {//haven't checked this node against ent yet - if ( NodeFailed( ent, nodeNum ) ) - { - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + if (CheckedNode(nodeNum, ent->s.number) == CHECKED_PASSED) { // already checked this node against ent and it passed + } else { // haven't checked this node against ent yet + if (NodeFailed(ent, nodeNum)) { + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } - //okay, since we only have to do this once, let's check to see if this node is even usable (could help us short-circuit a whole loop of the dest nodes) - radius = node->GetRadius(); - - //If we're not within the known clear radius of this node OR out of Z height range... - if ( (signed)(*nci).distance >= (radius*radius) || ( fabs( position[2] - ent->currentOrigin[2] ) >= MAX_Z_DELTA ) ) - { - //We're not *within* this node, so check clear path, etc. - - //FIXME: any way to call G_FindClosestPointOnLineSegment and see if I can at least get to the waypoint's path - if ( flags & NF_CLEAR_PATH )//|| flags & NF_CLEAR_LOS ) - {//need a clear path or LOS - if ( !gi.inPVS( ent->currentOrigin, position ) ) - {//not even potentially clear - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + // okay, since we only have to do this once, let's check to see if this node is even usable (could help us short-circuit a whole loop of the dest + // nodes) + radius = node->GetRadius(); + + // If we're not within the known clear radius of this node OR out of Z height range... + if ((signed)(*nci).distance >= (radius * radius) || (fabs(position[2] - ent->currentOrigin[2]) >= MAX_Z_DELTA)) { + // We're not *within* this node, so check clear path, etc. + + // FIXME: any way to call G_FindClosestPointOnLineSegment and see if I can at least get to the waypoint's path + if (flags & NF_CLEAR_PATH) //|| flags & NF_CLEAR_LOS ) + { // need a clear path or LOS + if (!gi.inPVS(ent->currentOrigin, position)) { // not even potentially clear + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( ent, goal->s.number, position, qtrue ) == false ) - { - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(ent, goal->s.number, position, qtrue) == false) { + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } } - }//otherwise, inside the node so it must be clear (?) - SetCheckedNode( nodeNum, ent->s.number, CHECKED_PASSED ); + } // otherwise, inside the node so it must be clear (?) + SetCheckedNode(nodeNum, ent->s.number, CHECKED_PASSED); } - if ( d_altRoutes->integer ) - { - //calc the paths for this node if they're out of date + if (d_altRoutes->integer) { + // calc the paths for this node if they're out of date nodeFlags = node->GetFlags(); - if ( (nodeFlags&NF_RECALC) ) - { - //gi.Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", level.time, nodeNum ); - CalculatePath( node ); + if ((nodeFlags & NF_RECALC)) { + // gi.Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", level.time, nodeNum ); + CalculatePath(node); } } - STL_ITERATE( nci2, nodeChain2 ) - { + STL_ITERATE(nci2, nodeChain2) { node2 = m_nodes[(*nci2).nodeID]; nodeNum2 = (*nci2).nodeID; - if ( d_altRoutes->integer ) - { - //calc the paths for this node if they're out of date + if (d_altRoutes->integer) { + // calc the paths for this node if they're out of date nodeFlags = node2->GetFlags(); - if ( (nodeFlags&NF_RECALC) ) - { - //gi.Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", level.time, nodeNum2 ); - CalculatePath( node2 ); + if ((nodeFlags & NF_RECALC)) { + // gi.Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", level.time, nodeNum2 ); + CalculatePath(node2); } } - node2->GetPosition( position2 ); - //Okay, first get the entire path cost, including distance to first node from ents' positions - cost = floor(Distance( ent->currentOrigin, position ) + Distance( goal->currentOrigin, position2 )); + node2->GetPosition(position2); + // Okay, first get the entire path cost, including distance to first node from ents' positions + cost = floor(Distance(ent->currentOrigin, position) + Distance(goal->currentOrigin, position2)); - if ( d_altRoutes->integer ) - { - nextNode = GetBestNodeAltRoute( (*nci).nodeID, (*nci2).nodeID, &pathCost, bestNode ); + if (d_altRoutes->integer) { + nextNode = GetBestNodeAltRoute((*nci).nodeID, (*nci2).nodeID, &pathCost, bestNode); cost += pathCost; - } - else - { - cost += GetPathCost( (*nci).nodeID, (*nci2).nodeID ); + } else { + cost += GetPathCost((*nci).nodeID, (*nci2).nodeID); } - if ( cost >= bestCost ) - { + if (cost >= bestCost) { continue; } - //okay, this is the shortest path we've found yet, check clear path, etc. - if ( CheckedNode( nodeNum2, goal->s.number ) == CHECKED_FAILED ) - {//already checked this node against goal and it failed + // okay, this is the shortest path we've found yet, check clear path, etc. + if (CheckedNode(nodeNum2, goal->s.number) == CHECKED_FAILED) { // already checked this node against goal and it failed continue; } - if ( CheckedNode( nodeNum2, goal->s.number ) == CHECKED_PASSED ) - {//already checked this node against goal and it passed - } - else - {//haven't checked this node against goal yet - if ( NodeFailed( goal, nodeNum2 ) ) - { - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + if (CheckedNode(nodeNum2, goal->s.number) == CHECKED_PASSED) { // already checked this node against goal and it passed + } else { // haven't checked this node against goal yet + if (NodeFailed(goal, nodeNum2)) { + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } - radius = node2->GetRadius(); + radius = node2->GetRadius(); - //If we're not within the known clear radius of this node OR out of Z height range... - if ( (signed)(*nci2).distance >= (radius*radius) || ( fabs( position2[2] - goal->currentOrigin[2] ) >= MAX_Z_DELTA ) ) - { - //We're not *within* this node, so check clear path, etc. + // If we're not within the known clear radius of this node OR out of Z height range... + if ((signed)(*nci2).distance >= (radius * radius) || (fabs(position2[2] - goal->currentOrigin[2]) >= MAX_Z_DELTA)) { + // We're not *within* this node, so check clear path, etc. - if ( flags & NF_CLEAR_PATH )//|| flags & NF_CLEAR_LOS ) - {//need a clear path or LOS - if ( !gi.inPVS( goal->currentOrigin, position2 ) ) - {//not even potentially clear - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + if (flags & NF_CLEAR_PATH) //|| flags & NF_CLEAR_LOS ) + { // need a clear path or LOS + if (!gi.inPVS(goal->currentOrigin, position2)) { // not even potentially clear + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( goal, ent->s.number, position2, qfalse ) == false )//qtrue? + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(goal, ent->s.number, position2, qfalse) == false) // qtrue? { - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } } - }//otherwise, inside the node so it must be clear (?) - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_PASSED ); + } // otherwise, inside the node so it must be clear (?) + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_PASSED); } bestCost = cost; @@ -1465,11 +1291,9 @@ int CNavigator::GetBestPathBetweenEnts( gentity_t *ent, gentity_t *goal, int fla } } - if ( !d_altRoutes->integer ) - {//bestNode would not have been set by GetBestNodeAltRoute above, so get it here - if ( ent->waypoint != NODE_NONE && goal->waypoint != NODE_NONE ) - {//have 2 valid waypoints which means a valid path - bestNode = GetBestNodeAltRoute( ent->waypoint, goal->waypoint, &bestCost, NODE_NONE ); + if (!d_altRoutes->integer) { // bestNode would not have been set by GetBestNodeAltRoute above, so get it here + if (ent->waypoint != NODE_NONE && goal->waypoint != NODE_NONE) { // have 2 valid waypoints which means a valid path + bestNode = GetBestNodeAltRoute(ent->waypoint, goal->waypoint, &bestCost, NODE_NONE); } } return bestNode; @@ -1481,85 +1305,73 @@ GetNearestWaypoint ------------------------- */ -int CNavigator::GetNearestNode( gentity_t *ent, int lastID, int flags, int targetID ) -{ - int bestNode = NODE_NONE; - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetNearestNode(gentity_t *ent, int lastID, int flags, int targetID) { + int bestNode = NODE_NONE; + // Must have nodes + if (m_nodes.size() == 0) return NODE_NONE; - if ( targetID == NODE_NONE ) - { - //Try and find an early match using our last node - bestNode = TestBestFirst( ent, lastID, flags ); + if (targetID == NODE_NONE) { + // Try and find an early match using our last node + bestNode = TestBestFirst(ent, lastID, flags); - if ( bestNode != NODE_NONE ) + if (bestNode != NODE_NONE) return bestNode; - }//else can't rely on testing last, we want best to targetID + } // else can't rely on testing last, we want best to targetID -///////////////////////////////////////////////// + ///////////////////////////////////////////////// -#define MAX_Z_DELTA 18 +#define MAX_Z_DELTA 18 -///////////////////////////////////////////////// + ///////////////////////////////////////////////// - nodeChain_l nodeChain; - nodeChain_l::iterator nci; + nodeChain_l nodeChain; + nodeChain_l::iterator nci; - //Collect all nodes within a certain radius - CollectNearestNodes( ent->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain ); + // Collect all nodes within a certain radius + CollectNearestNodes(ent->currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain); - vec3_t position; - int radius; - int dist, bestDist = Q3_INFINITE; - CNode *node; + vec3_t position; + int radius; + int dist, bestDist = Q3_INFINITE; + CNode *node; - //Look through all nodes - STL_ITERATE( nci, nodeChain ) - { + // Look through all nodes + STL_ITERATE(nci, nodeChain) { node = m_nodes[(*nci).nodeID]; - node->GetPosition( position ); + node->GetPosition(position); - radius = node->GetRadius(); + radius = node->GetRadius(); - if ( NodeFailed( ent, (*nci).nodeID ) ) - { + if (NodeFailed(ent, (*nci).nodeID)) { continue; } - //Are we within the known clear radius of this node? - if ( (signed)(*nci).distance < (radius*radius) ) - { - //Do a z-difference sanity check - if ( fabs( position[2] - ent->currentOrigin[2] ) < MAX_Z_DELTA ) - { - //Found one + // Are we within the known clear radius of this node? + if ((signed)(*nci).distance < (radius * radius)) { + // Do a z-difference sanity check + if (fabs(position[2] - ent->currentOrigin[2]) < MAX_Z_DELTA) { + // Found one return (*nci).nodeID; } } - //We're not *within* this node, so... - if ( CheckedNode((*nci).nodeID,ent->s.number) == CHECKED_FAILED ) - { + // We're not *within* this node, so... + if (CheckedNode((*nci).nodeID, ent->s.number) == CHECKED_FAILED) { continue; - } - else if ( CheckedNode((*nci).nodeID,ent->s.number) == CHECKED_FAILED ) - { + } else if (CheckedNode((*nci).nodeID, ent->s.number) == CHECKED_FAILED) { continue; - } - else - { - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( ent, ENTITYNUM_NONE, position, qfalse ) == false )//qtrue? + } else { + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(ent, ENTITYNUM_NONE, position, qfalse) == false) // qtrue? { - SetCheckedNode((*nci).nodeID,ent->s.number,CHECKED_FAILED); + SetCheckedNode((*nci).nodeID, ent->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear line of sight? + // Do we need a clear line of sight? /* if ( flags & NF_CLEAR_LOS ) { @@ -1570,26 +1382,22 @@ int CNavigator::GetNearestNode( gentity_t *ent, int lastID, int flags, int targe } } */ - SetCheckedNode((*nci).nodeID,ent->s.number,CHECKED_PASSED); + SetCheckedNode((*nci).nodeID, ent->s.number, CHECKED_PASSED); } - if ( targetID != WAYPOINT_NONE ) - {//we want to find the one with the shortest route here - dist = GetPathCost( (*nci).nodeID, targetID ); - if ( dist < bestDist ) - { + if (targetID != WAYPOINT_NONE) { // we want to find the one with the shortest route here + dist = GetPathCost((*nci).nodeID, targetID); + if (dist < bestDist) { bestDist = dist; bestNode = (*nci).nodeID; } - } - else - {//first one we find is fine + } else { // first one we find is fine bestNode = (*nci).nodeID; break; } } - //Found one, we're done + // Found one, we're done return bestNode; } @@ -1599,208 +1407,176 @@ ShowPath ------------------------- */ -void CNavigator::ShowPath( int start, int end ) -{ - //Validate the start position - if ( ( start < 0 ) || ( start >= (int)m_nodes.size() ) ) +void CNavigator::ShowPath(int start, int end) { + // Validate the start position + if ((start < 0) || (start >= (int)m_nodes.size())) return; - //Validate the end position - if ( ( end < 0 ) || ( end >= (int)m_nodes.size() ) ) + // Validate the end position + if ((end < 0) || (end >= (int)m_nodes.size())) return; - CNode *startNode = m_nodes[ start ]; - CNode *endNode = m_nodes[ end ]; + CNode *startNode = m_nodes[start]; + CNode *endNode = m_nodes[end]; - CNode *moveNode = startNode; - CNode *testNode = NULL; + CNode *moveNode = startNode; + CNode *testNode = NULL; - int bestNode; - vec3_t startPos, endPos; + int bestNode; + vec3_t startPos, endPos; - int runAway = 0; + int runAway = 0; - //Draw out our path - while ( moveNode != endNode ) - { - bestNode = GetBestNode( moveNode->GetID(), end ); + // Draw out our path + while (moveNode != endNode) { + bestNode = GetBestNode(moveNode->GetID(), end); - //Some nodes may be fragmented - if ( bestNode == -1 ) - { - Com_Printf("No connection possible between node %d and %d\n", start, end ); + // Some nodes may be fragmented + if (bestNode == -1) { + Com_Printf("No connection possible between node %d and %d\n", start, end); return; } - //This is our next node on the path - testNode = m_nodes[ bestNode ]; + // This is our next node on the path + testNode = m_nodes[bestNode]; - //Get their origins - moveNode->GetPosition( startPos ); - testNode->GetPosition( endPos ); + // Get their origins + moveNode->GetPosition(startPos); + testNode->GetPosition(endPos); - //Draw the edge - CG_DrawEdge( startPos, endPos, EDGE_PATH ); + // Draw the edge + CG_DrawEdge(startPos, endPos, EDGE_PATH); - //Take a new best node + // Take a new best node moveNode = testNode; - if ( runAway++ > 64 ) - { + if (runAway++ > 64) { Com_Printf("Potential Run-away path!\n"); return; } } } -static std::map CheckedNodes; -void CNavigator::ClearCheckedNodes( void ) -{ - CheckedNodes.clear(); -} +static std::map CheckedNodes; +void CNavigator::ClearCheckedNodes(void) { CheckedNodes.clear(); } -byte CNavigator::CheckedNode(int wayPoint,int ent) -{ - assert(wayPoint>=0&&wayPoint=0&&ent::iterator f=CheckedNodes.find(wayPoint*MAX_GENTITIES+ent); - if (f!=CheckedNodes.end()) - { +byte CNavigator::CheckedNode(int wayPoint, int ent) { + assert(wayPoint >= 0 && wayPoint < MAX_STORED_WAYPOINTS); + assert(ent >= 0 && ent < MAX_GENTITIES); + std::map::iterator f = CheckedNodes.find(wayPoint * MAX_GENTITIES + ent); + if (f != CheckedNodes.end()) { return (*f).second; } return CHECKED_NO; } -void CNavigator::SetCheckedNode(int wayPoint,int ent,byte value) -{ - assert(wayPoint>=0&&wayPoint=0&&ent= 0 && wayPoint < MAX_STORED_WAYPOINTS); + assert(ent >= 0 && ent < MAX_GENTITIES); + assert(value == CHECKED_FAILED || value == CHECKED_PASSED); + CheckedNodes[wayPoint * MAX_GENTITIES + ent] = value; } -#define CHECK_FAILED_EDGE_INTERVAL 1000 -#define CHECK_FAILED_EDGE_INTITIAL 5000//10000 +#define CHECK_FAILED_EDGE_INTERVAL 1000 +#define CHECK_FAILED_EDGE_INTITIAL 5000 // 10000 -void CNavigator::CheckFailedNodes( gentity_t *ent ) -{ - vec3_t nodePos; - int j; +void CNavigator::CheckFailedNodes(gentity_t *ent) { + vec3_t nodePos; + int j; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - if ( ent->failedWaypointCheckTime && ent->failedWaypointCheckTime < level.time ) - { + if (ent->failedWaypointCheckTime && ent->failedWaypointCheckTime < level.time) { int failed = 0; - //do this only once every 1 second - for ( j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] != 0 ) - { + // do this only once every 1 second + for (j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] != 0) { failed++; //-1 because 0 is a valid node but also the default, so we add one when we add one - m_nodes[ent->failedWaypoints[j]-1]->GetPosition( nodePos ); - if ( !NAV_ClearPathToPoint( ent, ent->mins, ent->maxs, nodePos, (CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP), ENTITYNUM_NONE ) ) - {//no path clear of architecture, so clear this since we can't check against entities + m_nodes[ent->failedWaypoints[j] - 1]->GetPosition(nodePos); + if (!NAV_ClearPathToPoint(ent, ent->mins, ent->maxs, nodePos, (CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP), + ENTITYNUM_NONE)) { // no path clear of architecture, so clear this since we can't check against entities ent->failedWaypoints[j] = 0; failed--; } - //have clear architectural path, now check against ents only - else if ( NAV_ClearPathToPoint( ent, ent->mins, ent->maxs, nodePos, CONTENTS_BODY, ENTITYNUM_NONE ) ) - {//clear of ents, too, so all clear, clear this one out + // have clear architectural path, now check against ents only + else if (NAV_ClearPathToPoint(ent, ent->mins, ent->maxs, nodePos, CONTENTS_BODY, + ENTITYNUM_NONE)) { // clear of ents, too, so all clear, clear this one out ent->failedWaypoints[j] = 0; failed--; } } } - if ( !failed ) - { + if (!failed) { ent->failedWaypointCheckTime = 0; - } - else - { - ent->failedWaypointCheckTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + } else { + ent->failedWaypointCheckTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); } } } -void CNavigator::AddFailedNode( gentity_t *ent, int nodeID ) -{ +void CNavigator::AddFailedNode(gentity_t *ent, int nodeID) { int j; - for ( j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] == 0 ) - { - ent->failedWaypoints[j] = nodeID+1;//+1 because 0 is the default value and that's a valid node, so we take the +1 out when we check the node above - if ( !ent->failedWaypointCheckTime ) - { + for (j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] == 0) { + ent->failedWaypoints[j] = + nodeID + 1; //+1 because 0 is the default value and that's a valid node, so we take the +1 out when we check the node above + if (!ent->failedWaypointCheckTime) { ent->failedWaypointCheckTime = level.time + CHECK_FAILED_EDGE_INTITIAL; } return; } - if ( ent->failedWaypoints[j] == nodeID+1 ) - {//already have this one marked as failed + if (ent->failedWaypoints[j] == nodeID + 1) { // already have this one marked as failed return; } } - if ( j == MAX_FAILED_NODES )//check not needed, but... - {//ran out of failed nodes, get rid of first one, shift rest up - for ( j = 0; j < MAX_FAILED_NODES-1; j++ ) - { - ent->failedWaypoints[j] = ent->failedWaypoints[j+1]; + if (j == MAX_FAILED_NODES) // check not needed, but... + { // ran out of failed nodes, get rid of first one, shift rest up + for (j = 0; j < MAX_FAILED_NODES - 1; j++) { + ent->failedWaypoints[j] = ent->failedWaypoints[j + 1]; } } - ent->failedWaypoints[MAX_FAILED_NODES-1] = nodeID+1; - if ( !ent->failedWaypointCheckTime ) - { + ent->failedWaypoints[MAX_FAILED_NODES - 1] = nodeID + 1; + if (!ent->failedWaypointCheckTime) { ent->failedWaypointCheckTime = level.time + CHECK_FAILED_EDGE_INTITIAL; } } -qboolean CNavigator::NodeFailed( gentity_t *ent, int nodeID ) -{ - for ( int j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( (ent->failedWaypoints[j]-1) == nodeID ) - { +qboolean CNavigator::NodeFailed(gentity_t *ent, int nodeID) { + for (int j = 0; j < MAX_FAILED_NODES; j++) { + if ((ent->failedWaypoints[j] - 1) == nodeID) { return qtrue; } } return qfalse; } -qboolean CNavigator::NodesAreNeighbors( int startID, int endID ) -{//See if these 2 are neighbors - if ( startID == endID ) - { +qboolean CNavigator::NodesAreNeighbors(int startID, int endID) { // See if these 2 are neighbors + if (startID == endID) { return qfalse; } CNode *start = m_nodes[startID]; - int nextID = -1; - //NOTE: we only check start because we assume all connections are 2-way - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { + int nextID = -1; + // NOTE: we only check start because we assume all connections are 2-way + for (int i = 0; i < start->GetNumEdges(); i++) { nextID = start->GetEdge(i); - if ( nextID == endID ) - { + if (nextID == endID) { return qtrue; } } - //not neighbors + // not neighbors return qfalse; } -void CNavigator::ClearFailedEdge( failedEdge_t *failedEdge ) -{ - if ( !failedEdge ) - { +void CNavigator::ClearFailedEdge(failedEdge_t *failedEdge) { + if (!failedEdge) { return; } - //clear the edge failed flags + // clear the edge failed flags /* CNode *node = m_nodes[failedEdge->startID]; int edgeNum = node->GetEdgeNumToNode( failedEdge->endID ); @@ -1818,41 +1594,34 @@ void CNavigator::ClearFailedEdge( failedEdge_t *failedEdge ) node->SetEdgeFlags( edgeNum, flags ); } */ - //clear failedEdge info - SetEdgeCost( failedEdge->startID, failedEdge->endID, -1 ); + // clear failedEdge info + SetEdgeCost(failedEdge->startID, failedEdge->endID, -1); failedEdge->startID = failedEdge->endID = WAYPOINT_NONE; failedEdge->entID = ENTITYNUM_NONE; failedEdge->checkTime = 0; } -void CNavigator::ClearAllFailedEdges( void ) -{ - memset( &failedEdges, WAYPOINT_NONE, sizeof( failedEdges ) ); - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { - ClearFailedEdge( &failedEdges[j] ); +void CNavigator::ClearAllFailedEdges(void) { + memset(&failedEdges, WAYPOINT_NONE, sizeof(failedEdges)); + for (int j = 0; j < MAX_FAILED_EDGES; j++) { + ClearFailedEdge(&failedEdges[j]); } } -int CNavigator::EdgeFailed( int startID, int endID ) -{ - //OPTIMIZED WAY (bjg 01/02) - //find in lookup map - std::pair findValue; +int CNavigator::EdgeFailed(int startID, int endID) { + // OPTIMIZED WAY (bjg 01/02) + // find in lookup map + std::pair findValue; findValue = m_edgeLookupMap.equal_range(startID); - while ( findValue.first != findValue.second ) - { - if( failedEdges[findValue.first->second].endID == endID) - { + while (findValue.first != findValue.second) { + if (failedEdges[findValue.first->second].endID == endID) { return findValue.first->second; } ++findValue.first; } findValue = m_edgeLookupMap.equal_range(endID); - while ( findValue.first != findValue.second ) - { - if( failedEdges[findValue.first->second].endID == startID) - { + while (findValue.first != findValue.second) { + if (failedEdges[findValue.first->second].endID == startID) { return findValue.first->second; } ++findValue.first; @@ -1860,7 +1629,7 @@ int CNavigator::EdgeFailed( int startID, int endID ) return -1; - //Old way (linear search) + // Old way (linear search) /* for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) { @@ -1883,69 +1652,60 @@ int CNavigator::EdgeFailed( int startID, int endID ) */ } -void CNavigator::AddFailedEdge( int entID, int startID, int endID ) -{ - int j;//, nextID; +void CNavigator::AddFailedEdge(int entID, int startID, int endID) { + int j; //, nextID; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - if ( d_patched->integer ) - {//use patch-style navigation - if ( startID == endID ) - {//not an edge! + if (d_patched->integer) { // use patch-style navigation + if (startID == endID) { // not an edge! return; } } - //Validate the ent number - if ( ( entID < 0 ) || ( entID > ENTITYNUM_NONE ) ) - { + // Validate the ent number + if ((entID < 0) || (entID > ENTITYNUM_NONE)) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"NAV ERROR: envalid ent %d\n", entID ); - assert(0&&"invalid entID"); + gi.Printf(S_COLOR_RED "NAV ERROR: envalid ent %d\n", entID); + assert(0 && "invalid entID"); #endif return; } - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) - { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"NAV ERROR: tried to fail invalid waypoint %d\n", startID ); - assert(0&&"invalid failed edge"); + gi.Printf(S_COLOR_RED "NAV ERROR: tried to fail invalid waypoint %d\n", startID); + assert(0 && "invalid failed edge"); #endif return; } - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) - { + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) { #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"NAV ERROR: tried to fail invalid waypoint %d\n", endID ); - assert(0&&"invalid failed edge"); + gi.Printf(S_COLOR_RED "NAV ERROR: tried to fail invalid waypoint %d\n", endID); + assert(0 && "invalid failed edge"); #endif return; } - //First see if we already have this one - if ( (j = EdgeFailed( startID, endID )) != -1 ) - { - //just remember this guy instead + // First see if we already have this one + if ((j = EdgeFailed(startID, endID)) != -1) { + // just remember this guy instead failedEdges[j].entID = entID; return; } - //Okay, new one, find an empty slot - for ( j = 0; j < MAX_FAILED_EDGES; j++ ) - { - if ( failedEdges[j].startID == WAYPOINT_NONE ) - { + // Okay, new one, find an empty slot + for (j = 0; j < MAX_FAILED_EDGES; j++) { + if (failedEdges[j].startID == WAYPOINT_NONE) { failedEdges[j].startID = startID; failedEdges[j].endID = endID; - //Check one second from now to see if it's clear - failedEdges[j].checkTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + // Check one second from now to see if it's clear + failedEdges[j].checkTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); m_edgeLookupMap.insert(std::pair(startID, j)); @@ -1974,10 +1734,10 @@ void CNavigator::AddFailedEdge( int entID, int startID, int endID ) } */ - //Remember who needed it + // Remember who needed it failedEdges[j].entID = entID; - //set the edge failed flags + // set the edge failed flags /* CNode *node = m_nodes[startID]; int edgeNum = node->GetEdgeNumToNode( endID ); @@ -1996,216 +1756,181 @@ void CNavigator::AddFailedEdge( int entID, int startID, int endID ) } */ - //stuff the index to this one in our lookup map + // stuff the index to this one in our lookup map - //now recalc all the paths! - if ( pathsCalculated ) - { - //reconnect the nodes and mark every node's flag NF_RECALC - //gi.Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", level.time ); - SetEdgeCost( startID, endID, Q3_INFINITE ); - FlagAllNodes( NF_RECALC ); + // now recalc all the paths! + if (pathsCalculated) { + // reconnect the nodes and mark every node's flag NF_RECALC + // gi.Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", level.time ); + SetEdgeCost(startID, endID, Q3_INFINITE); + FlagAllNodes(NF_RECALC); } return; } } #ifndef FINAL_BUILD - gi.Printf( S_COLOR_RED"NAV ERROR: too many blocked waypoint connections (%d)!!!\n", j ); + gi.Printf(S_COLOR_RED "NAV ERROR: too many blocked waypoint connections (%d)!!!\n", j); #endif } -qboolean CNavigator::CheckFailedEdge( failedEdge_t *failedEdge ) -{ - if ( !failedEdge ) - { +qboolean CNavigator::CheckFailedEdge(failedEdge_t *failedEdge) { + if (!failedEdge) { return qfalse; } - //Every 1 second, see if our failed edges are clear - if ( failedEdge->checkTime < level.time ) - { - if ( failedEdge->startID != WAYPOINT_NONE ) - { - vec3_t start, end, mins, maxs; - int ignore, clipmask; - gentity_t *ent = (failedEdge->entIDentID]:NULL; - int hitEntNum; + // Every 1 second, see if our failed edges are clear + if (failedEdge->checkTime < level.time) { + if (failedEdge->startID != WAYPOINT_NONE) { + vec3_t start, end, mins, maxs; + int ignore, clipmask; + gentity_t *ent = (failedEdge->entID < ENTITYNUM_WORLD) ? &g_entities[failedEdge->entID] : NULL; + int hitEntNum; - if ( !ent || !ent->inuse || !ent->client || ent->health <= 0 ) - { - VectorSet( mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2+STEPSIZE ); - VectorSet( maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2 ); + if (!ent || !ent->inuse || !ent->client || ent->health <= 0) { + VectorSet(mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 + STEPSIZE); + VectorSet(maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); ignore = ENTITYNUM_NONE; clipmask = MASK_NPCSOLID; - } - else - { - VectorCopy( ent->mins, mins ); + } else { + VectorCopy(ent->mins, mins); mins[2] += STEPSIZE; - VectorCopy( ent->maxs, maxs ); + VectorCopy(ent->maxs, maxs); ignore = failedEdge->entID; clipmask = ent->clipmask; } - if ( maxs[2] < mins[2] ) - {//don't invert bounding box + if (maxs[2] < mins[2]) { // don't invert bounding box maxs[2] = mins[2]; } - m_nodes[failedEdge->startID]->GetPosition( start ); - m_nodes[failedEdge->endID]->GetPosition( end ); + m_nodes[failedEdge->startID]->GetPosition(start); + m_nodes[failedEdge->endID]->GetPosition(end); - //See if it's NAV_ClearPath... + // See if it's NAV_ClearPath... #if 0 hitEntNum = NAVNEW_ClearPathBetweenPoints( start, end, mins, maxs, ignore, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP );//NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? #else - trace_t trace; + trace_t trace; - //Test if they're even conceivably close to one another - if ( !gi.inPVSIgnorePortals( start, end ) ) - { + // Test if they're even conceivably close to one another + if (!gi.inPVSIgnorePortals(start, end)) { return qfalse; } - gi.trace( &trace, start, mins, maxs, end, ignore, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 );//NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? + gi.trace(&trace, start, mins, maxs, end, ignore, clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, G2_NOCOLLIDE, + 0); // NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? - if( trace.startsolid == qtrue || trace.allsolid == qtrue ) - { + if (trace.startsolid == qtrue || trace.allsolid == qtrue) { return qfalse; } hitEntNum = trace.entityNum; #endif - //if we did hit something, see if it's just an auto-door and allow it - if ( hitEntNum != ENTITYNUM_NONE && G_EntIsUnlockedDoor( hitEntNum ) ) - { + // if we did hit something, see if it's just an auto-door and allow it + if (hitEntNum != ENTITYNUM_NONE && G_EntIsUnlockedDoor(hitEntNum)) { hitEntNum = ENTITYNUM_NONE; - } - else if ( hitEntNum == failedEdge->entID ) - {//don't hit the person who initially marked the edge failed + } else if (hitEntNum == failedEdge->entID) { // don't hit the person who initially marked the edge failed hitEntNum = ENTITYNUM_NONE; } - if ( hitEntNum == ENTITYNUM_NONE ) - { - //If so, clear it - ClearFailedEdge( failedEdge ); + if (hitEntNum == ENTITYNUM_NONE) { + // If so, clear it + ClearFailedEdge(failedEdge); return qtrue; - } - else - { - //Check again in one second - failedEdge->checkTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + } else { + // Check again in one second + failedEdge->checkTime = level.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); } } } return qfalse; } -void CNavigator::CheckAllFailedEdges( void ) -{ - failedEdge_t *failedEdge; - qboolean clearedAny = qfalse; +void CNavigator::CheckAllFailedEdges(void) { + failedEdge_t *failedEdge; + qboolean clearedAny = qfalse; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { + for (int j = 0; j < MAX_FAILED_EDGES; j++) { failedEdge = &failedEdges[j]; - clearedAny = CheckFailedEdge( failedEdge )?qtrue:clearedAny; + clearedAny = CheckFailedEdge(failedEdge) ? qtrue : clearedAny; } - if ( clearedAny ) - {//need to recalc the paths - if ( pathsCalculated ) - { - //reconnect the nodes and mark every node's flag NF_RECALC - //gi.Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", level.time ); - FlagAllNodes( NF_RECALC ); + if (clearedAny) { // need to recalc the paths + if (pathsCalculated) { + // reconnect the nodes and mark every node's flag NF_RECALC + // gi.Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", level.time ); + FlagAllNodes(NF_RECALC); } } } -qboolean CNavigator::RouteBlocked( int startID, int testEdgeID, int endID, int rejectRank ) -{ - int nextID, edgeID, lastID, bestNextID = NODE_NONE; - int bestRank = rejectRank; - int testRank; - qboolean allEdgesFailed; - CNode *end; - CNode *next; +qboolean CNavigator::RouteBlocked(int startID, int testEdgeID, int endID, int rejectRank) { + int nextID, edgeID, lastID, bestNextID = NODE_NONE; + int bestRank = rejectRank; + int testRank; + qboolean allEdgesFailed; + CNode *end; + CNode *next; - - if ( EdgeFailed( startID, testEdgeID ) != -1 ) - { + if (EdgeFailed(startID, testEdgeID) != -1) { return qtrue; } - if ( testEdgeID == endID ) - {//Neighbors, checked out, all clear + if (testEdgeID == endID) { // Neighbors, checked out, all clear return qfalse; } - //Okay, first edge is clear, now check rest of route! - end = m_nodes[ endID ]; + // Okay, first edge is clear, now check rest of route! + end = m_nodes[endID]; nextID = testEdgeID; lastID = startID; - while( 1 ) - { - next = m_nodes[ nextID ]; + while (1) { + next = m_nodes[nextID]; allEdgesFailed = qtrue; - for ( int i = 0; i < next->GetNumEdges(); i++ ) - { + for (int i = 0; i < next->GetNumEdges(); i++) { edgeID = next->GetEdge(i); - if ( edgeID == lastID ) - {//Don't backtrack + if (edgeID == lastID) { // Don't backtrack continue; } - if ( edgeID == startID ) - {//Don't loop around + if (edgeID == startID) { // Don't loop around continue; } - if ( EdgeFailed( nextID, edgeID ) != -1 ) - { - //This edge blocked, check next + if (EdgeFailed(nextID, edgeID) != -1) { + // This edge blocked, check next continue; } - if ( edgeID == endID ) - {//We got there all clear! + if (edgeID == endID) { // We got there all clear! return qfalse; } - //Still going... - testRank = end->GetRank( edgeID ); + // Still going... + testRank = end->GetRank(edgeID); - if ( testRank < 0 ) - {//No route this way + if (testRank < 0) { // No route this way continue; } - //Is the rank good enough? - if ( testRank < bestRank ) - { + // Is the rank good enough? + if (testRank < bestRank) { bestNextID = edgeID; bestRank = testRank; allEdgesFailed = qfalse; } } - if ( allEdgesFailed ) - { - //This route has no clear way of getting to end + if (allEdgesFailed) { + // This route has no clear way of getting to end return qtrue; - } - else - { + } else { lastID = nextID; nextID = bestNextID; } @@ -2218,96 +1943,80 @@ GetBestNodeAltRoute ------------------------- */ -int CNavigator::GetBestNodeAltRoute( int startID, int endID, int *pathCost, int rejectID ) -{ - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetBestNodeAltRoute(int startID, int endID, int *pathCost, int rejectID) { + // Must have nodes + if (m_nodes.size() == 0) return WAYPOINT_NONE; - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Is it the same node? - if ( startID == endID ) - { - if ( !d_altRoutes->integer || EdgeFailed( startID, endID ) == -1 ) - { + // Is it the same node? + if (startID == endID) { + if (!d_altRoutes->integer || EdgeFailed(startID, endID) == -1) { return startID; - } - else - { + } else { return WAYPOINT_NONE; } } - CNode *start = m_nodes[ startID ]; + CNode *start = m_nodes[startID]; - int bestNode = -1; - int bestRank = Q3_INFINITE; - int testRank, rejectRank = Q3_INFINITE; - int bestCost = Q3_INFINITE; + int bestNode = -1; + int bestRank = Q3_INFINITE; + int testRank, rejectRank = Q3_INFINITE; + int bestCost = Q3_INFINITE; *pathCost = 0; - //Find the minimum rank of the edge(s) we want to reject as paths - if ( rejectID != WAYPOINT_NONE ) - { - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - if ( start->GetEdge(i) == rejectID ) - { - rejectRank = GetPathCost( startID, endID );//end->GetRank( start->GetEdge(i) ); + // Find the minimum rank of the edge(s) we want to reject as paths + if (rejectID != WAYPOINT_NONE) { + for (int i = 0; i < start->GetNumEdges(); i++) { + if (start->GetEdge(i) == rejectID) { + rejectRank = GetPathCost(startID, endID); // end->GetRank( start->GetEdge(i) ); break; } } } - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - testRank = GetPathCost( edgeID, endID );//end->GetRank( edgeID ); + testRank = GetPathCost(edgeID, endID); // end->GetRank( edgeID ); - //Make sure it's not worse than our reject rank - if ( testRank >= rejectRank ) + // Make sure it's not worse than our reject rank + if (testRank >= rejectRank) continue; - //Found one - if ( edgeID == endID ) - { - if ( !d_altRoutes->integer || !RouteBlocked( startID, edgeID, endID, rejectRank ) ) - { - *pathCost += start->GetEdgeCost( i ); + // Found one + if (edgeID == endID) { + if (!d_altRoutes->integer || !RouteBlocked(startID, edgeID, endID, rejectRank)) { + *pathCost += start->GetEdgeCost(i); return edgeID; - } - else - {//this is blocked, can't consider it + } else { // this is blocked, can't consider it continue; } } - //No possible connection - if ( testRank == NODE_NONE ) - { + // No possible connection + if (testRank == NODE_NONE) { *pathCost = Q3_INFINITE; return NODE_NONE; } - //Found a better one - if ( testRank < bestRank ) - { - //FIXME: make sure all the edges down from startID through edgeID to endID + // Found a better one + if (testRank < bestRank) { + // FIXME: make sure all the edges down from startID through edgeID to endID // does NOT include a failedEdge... - if ( !d_altRoutes->integer || !RouteBlocked( startID, edgeID, endID, rejectRank ) ) - { + if (!d_altRoutes->integer || !RouteBlocked(startID, edgeID, endID, rejectRank)) { bestNode = edgeID; bestRank = testRank; - bestCost = start->GetEdgeCost(i)+testRank; + bestCost = start->GetEdgeCost(i) + testRank; } } } @@ -2323,10 +2032,9 @@ overloaded so you don't have to pass a pathCost int pointer in ------------------------- */ -int CNavigator::GetBestNodeAltRoute( int startID, int endID, int rejectID ) -{ - int junk; - return GetBestNodeAltRoute( startID, endID, &junk, rejectID ); +int CNavigator::GetBestNodeAltRoute(int startID, int endID, int rejectID) { + int junk; + return GetBestNodeAltRoute(startID, endID, &junk, rejectID); } /* ------------------------- @@ -2334,59 +2042,53 @@ GetBestNode ------------------------- */ -int CNavigator::GetBestNode( int startID, int endID, int rejectID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +int CNavigator::GetBestNode(int startID, int endID, int rejectID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return WAYPOINT_NONE; - if ( startID == endID ) + if (startID == endID) return startID; - CNode *start = m_nodes[ startID ]; - CNode *end = m_nodes[ endID ]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - int bestNode = -1; - int bestRank = Q3_INFINITE; - int testRank, rejectRank = 0; + int bestNode = -1; + int bestRank = Q3_INFINITE; + int testRank, rejectRank = 0; - if ( rejectID != WAYPOINT_NONE ) - { - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - if ( start->GetEdge(i) == rejectID ) - { - rejectRank = end->GetRank( start->GetEdge(i) ); + if (rejectID != WAYPOINT_NONE) { + for (int i = 0; i < start->GetNumEdges(); i++) { + if (start->GetEdge(i) == rejectID) { + rejectRank = end->GetRank(start->GetEdge(i)); break; } } } - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - //Found one - if ( edgeID == endID ) + // Found one + if (edgeID == endID) return edgeID; - testRank = end->GetRank( edgeID ); + testRank = end->GetRank(edgeID); - //Found one - if ( testRank <= rejectRank ) + // Found one + if (testRank <= rejectRank) continue; - //No possible connection - if ( testRank == NODE_NONE ) + // No possible connection + if (testRank == NODE_NONE) return NODE_NONE; - //Found a better one - if ( testRank < bestRank ) - { + // Found a better one + if (testRank < bestRank) { bestNode = edgeID; bestRank = testRank; } @@ -2401,15 +2103,14 @@ GetNodePosition ------------------------- */ -int CNavigator::GetNodePosition( int nodeID, vec3_t out ) -{ - //Validate the number - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodePosition(int nodeID, vec3_t out) { + // Validate the number + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return false; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - node->GetPosition( out ); + node->GetPosition(out); return true; } @@ -2420,14 +2121,13 @@ GetNodeNumEdges ------------------------- */ -int CNavigator::GetNodeNumEdges( int nodeID ) -{ - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodeNumEdges(int nodeID) { + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return -1; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - assert( node ); + assert(node); return node->GetNumEdges(); } @@ -2438,16 +2138,15 @@ GetNodeEdge ------------------------- */ -int CNavigator::GetNodeEdge( int nodeID, int edge ) -{ - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodeEdge(int nodeID, int edge) { + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return -1; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - assert( node ); + assert(node); - return node->GetEdge( edge ); + return node->GetEdge(edge); } /* @@ -2456,31 +2155,29 @@ Connected ------------------------- */ -bool CNavigator::Connected( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +bool CNavigator::Connected(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return false; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return false; - if ( startID == endID ) + if (startID == endID) return true; - CNode *start = m_nodes[ startID ]; - CNode *end = m_nodes[ endID ]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - //Found one - if ( edgeID == endID ) + // Found one + if (edgeID == endID) return true; - if ( ( end->GetRank( edgeID ) ) != NODE_NONE ) + if ((end->GetRank(edgeID)) != NODE_NONE) return true; } @@ -2493,72 +2190,65 @@ GetPathCost ------------------------- */ -unsigned int CNavigator::GetPathCost( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +unsigned int CNavigator::GetPathCost(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - CNode *startNode = m_nodes[ startID ]; + CNode *startNode = m_nodes[startID]; - if ( !startNode->GetNumEdges() ) - {//WTF? Solitary waypoint! Bad designer! - return Q3_INFINITE; // return 0; + if (!startNode->GetNumEdges()) { // WTF? Solitary waypoint! Bad designer! + return Q3_INFINITE; // return 0; } - CNode *endNode = m_nodes[ endID ]; + CNode *endNode = m_nodes[endID]; - CNode *moveNode = startNode; + CNode *moveNode = startNode; - int bestNode; - int pathCost = 0; - int bestCost; + int bestNode; + int pathCost = 0; + int bestCost; - int bestRank; - int testRank; + int bestRank; + int testRank; - //Draw out our path - while ( moveNode != endNode ) - { + // Draw out our path + while (moveNode != endNode) { bestRank = WORLD_SIZE; bestNode = -1; bestCost = 0; - for ( int i = 0; i < moveNode->GetNumEdges(); i++ ) - { - int edgeID = moveNode->GetEdge(i); + for (int i = 0; i < moveNode->GetNumEdges(); i++) { + int edgeID = moveNode->GetEdge(i); - //Done - if ( edgeID == endID ) - { - return pathCost + moveNode->GetEdgeCost( i ); + // Done + if (edgeID == endID) { + return pathCost + moveNode->GetEdgeCost(i); } - testRank = endNode->GetRank( edgeID ); + testRank = endNode->GetRank(edgeID); - //No possible connection - if ( testRank == NODE_NONE ) - { + // No possible connection + if (testRank == NODE_NONE) { return Q3_INFINITE; // return 0; } - //Found a better one - if ( testRank < bestRank ) - { + // Found a better one + if (testRank < bestRank) { bestNode = edgeID; bestRank = testRank; - bestCost = moveNode->GetEdgeCost( i ); + bestCost = moveNode->GetEdgeCost(i); } } pathCost += bestCost; - //Take a new best node - moveNode = m_nodes[ bestNode ]; + // Take a new best node + moveNode = m_nodes[bestNode]; } return pathCost; @@ -2570,20 +2260,19 @@ GetEdgeCost ------------------------- */ -unsigned int CNavigator::GetEdgeCost( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +unsigned int CNavigator::GetEdgeCost(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - CNode *start = m_nodes[startID]; - CNode *end = m_nodes[endID]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - return GetEdgeCost( start, end ); + return GetEdgeCost(start, end); } /* @@ -2592,45 +2281,42 @@ GetProjectedNode ------------------------- */ -int CNavigator::GetProjectedNode( vec3_t origin, int nodeID ) -{ - //Validate the start position - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetProjectedNode(vec3_t origin, int nodeID) { + // Validate the start position + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return NODE_NONE; - CNode *node = m_nodes[nodeID]; - CNode *tempNode; + CNode *node = m_nodes[nodeID]; + CNode *tempNode; - float bestDot = 0.0f; - int bestNode = NODE_NONE; + float bestDot = 0.0f; + int bestNode = NODE_NONE; - vec3_t targetDir, basePos, tempDir, tempPos; - float dot; + vec3_t targetDir, basePos, tempDir, tempPos; + float dot; - //Setup our target direction - node->GetPosition( basePos ); + // Setup our target direction + node->GetPosition(basePos); - VectorSubtract( origin, basePos, targetDir ); - VectorNormalize( targetDir ); + VectorSubtract(origin, basePos, targetDir); + VectorNormalize(targetDir); - //Go through all the edges - for ( int i = 0; i < node->GetNumEdges(); i++ ) - { + // Go through all the edges + for (int i = 0; i < node->GetNumEdges(); i++) { tempNode = m_nodes[node->GetEdge(i)]; - tempNode->GetPosition( tempPos ); + tempNode->GetPosition(tempPos); - VectorSubtract( tempPos, basePos, tempDir ); - VectorNormalize( tempDir ); //FIXME: Retain the length here if you want it + VectorSubtract(tempPos, basePos, tempDir); + VectorNormalize(tempDir); // FIXME: Retain the length here if you want it - dot = DotProduct( targetDir, tempDir ); + dot = DotProduct(targetDir, tempDir); - if ( dot < 0.0f ) + if (dot < 0.0f) continue; - if ( dot > bestDot ) - { - bestDot = dot; - bestNode = tempNode->GetID(); + if (dot > bestDot) { + bestDot = dot; + bestNode = tempNode->GetID(); } } @@ -2642,22 +2328,16 @@ int CNavigator::GetProjectedNode( vec3_t origin, int nodeID ) ////////////////////////////////////////////////////////////////// // Helper pop_mHeap algorithm class ////////////////////////////////////////////////////////////////// -class NodeTotalGreater -{ -public: - bool operator()( CEdge * first, CEdge * second ) const { - return( first->m_cost > second->m_cost ); - } +class NodeTotalGreater { + public: + bool operator()(CEdge *first, CEdge *second) const { return (first->m_cost > second->m_cost); } }; - ////////////////////////////////////////////////////////////////// // Destructor - Deallocate any remaining pointers in the queue ////////////////////////////////////////////////////////////////// -CPriorityQueue::~CPriorityQueue() -{ - while (!Empty()) - { +CPriorityQueue::~CPriorityQueue() { + while (!Empty()) { delete Pop(); } } @@ -2665,12 +2345,9 @@ CPriorityQueue::~CPriorityQueue() ////////////////////////////////////////////////////////////////// // Standard Iterative Search ////////////////////////////////////////////////////////////////// -CEdge* CPriorityQueue::Find(int npNum) -{ - for(std::vector::iterator HeapIter=mHeap.begin(); HeapIter!=mHeap.end(); HeapIter++) - { - if ((*HeapIter)->m_first == npNum) - { +CEdge *CPriorityQueue::Find(int npNum) { + for (std::vector::iterator HeapIter = mHeap.begin(); HeapIter != mHeap.end(); HeapIter++) { + if ((*HeapIter)->m_first == npNum) { return *HeapIter; } } @@ -2680,56 +2357,47 @@ CEdge* CPriorityQueue::Find(int npNum) ////////////////////////////////////////////////////////////////// // Remove Node And Resort ////////////////////////////////////////////////////////////////// -CEdge* CPriorityQueue::Pop() -{ - CEdge *edge = mHeap.front(); +CEdge *CPriorityQueue::Pop() { + CEdge *edge = mHeap.front(); - //pop_mHeap will move the node at the front to the position N - //and then sort the mHeap to make positions 1 through N-1 correct - //(STL makes no assumptions about your data and doesn't want to change - //the size of the container.) - std::pop_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater() ); + // pop_mHeap will move the node at the front to the position N + // and then sort the mHeap to make positions 1 through N-1 correct + //(STL makes no assumptions about your data and doesn't want to change + // the size of the container.) + std::pop_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater()); - //pop_back() will actually remove the last element from the mHeap - //now the mHeap is sorted for positions 1 through N - mHeap.pop_back(); + // pop_back() will actually remove the last element from the mHeap + // now the mHeap is sorted for positions 1 through N + mHeap.pop_back(); - return( edge ); + return (edge); } ////////////////////////////////////////////////////////////////// // Add New Node And Resort ////////////////////////////////////////////////////////////////// -void CPriorityQueue::Push(CEdge* theEdge ) -{ - //Pushes the node onto the back of the mHeap - mHeap.push_back( theEdge ); +void CPriorityQueue::Push(CEdge *theEdge) { + // Pushes the node onto the back of the mHeap + mHeap.push_back(theEdge); - //Sorts the new element into the mHeap - std::push_heap( mHeap.begin(), mHeap.end(), NodeTotalGreater() ); + // Sorts the new element into the mHeap + std::push_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater()); } ////////////////////////////////////////////////////////////////// // Find The Node In Question And Resort mHeap Around It ////////////////////////////////////////////////////////////////// -void CPriorityQueue::Update( CEdge* edge ) -{ - for(std::vector::iterator i=mHeap.begin(); i!=mHeap.end(); i++) - { - if( (*i)->m_first == edge->m_first ) - { //Found node - resort from this position in the mHeap - //(its total value was changed before this function was called) - std::push_heap( mHeap.begin(), i+1, NodeTotalGreater() ); - return; - } - } +void CPriorityQueue::Update(CEdge *edge) { + for (std::vector::iterator i = mHeap.begin(); i != mHeap.end(); i++) { + if ((*i)->m_first == edge->m_first) { // Found node - resort from this position in the mHeap + //(its total value was changed before this function was called) + std::push_heap(mHeap.begin(), i + 1, NodeTotalGreater()); + return; + } + } } ////////////////////////////////////////////////////////////////// // Just a wrapper for stl empty function. ////////////////////////////////////////////////////////////////// -bool CPriorityQueue::Empty() -{ - return( mHeap.empty() ); -}; - +bool CPriorityQueue::Empty() { return (mHeap.empty()); }; diff --git a/codeJK2/game/g_navnew.cpp b/codeJK2/game/g_navnew.cpp index d5d2b208ff..a1dc26935c 100644 --- a/codeJK2/game/g_navnew.cpp +++ b/codeJK2/game/g_navnew.cpp @@ -26,23 +26,21 @@ along with this program; if not, see . #include "g_nav.h" #include "g_navigator.h" -//Global navigator -extern CNavigator navigator; -extern cvar_t *d_altRoutes; -extern cvar_t *d_patched; +// Global navigator +extern CNavigator navigator; +extern cvar_t *d_altRoutes; +extern cvar_t *d_patched; extern vec3_t playerMins; extern vec3_t playerMaxs; -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ); -qboolean NAV_TestForBlocked( gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int &flags ); +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t &trace, int clipmask); +qboolean NAV_TestForBlocked(gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int &flags); -qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ) -{ - //FIXME: must be a better way to do this - for ( int j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] == nodeNum+1 )//+1 because 0 is a valid nodeNum, but also the default - {//we failed against this node +qboolean NAV_CheckNodeFailedForEnt(gentity_t *ent, int nodeNum) { + // FIXME: must be a better way to do this + for (int j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] == nodeNum + 1) //+1 because 0 is a valid nodeNum, but also the default + { // we failed against this node return qtrue; } } @@ -53,22 +51,20 @@ qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ) NPC_UnBlocked ------------------------- */ -void NPC_ClearBlocked( gentity_t *self ) -{ - if ( self->NPC == NULL ) +void NPC_ClearBlocked(gentity_t *self) { + if (self->NPC == NULL) return; - //self->NPC->aiFlags &= ~NPCAI_BLOCKED; + // self->NPC->aiFlags &= ~NPCAI_BLOCKED; self->NPC->blockingEntNum = ENTITYNUM_NONE; } -void NPC_SetBlocked( gentity_t *self, gentity_t *blocker ) -{ - if ( self->NPC == NULL ) +void NPC_SetBlocked(gentity_t *self, gentity_t *blocker) { + if (self->NPC == NULL) return; - //self->NPC->aiFlags |= NPCAI_BLOCKED; - self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + ( Q_flrand(0.0f, 1.0f) * 4000 ); + // self->NPC->aiFlags |= NPCAI_BLOCKED; + self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + (Q_flrand(0.0f, 1.0f) * 4000); self->NPC->blockingEntNum = blocker->s.number; } @@ -77,25 +73,23 @@ void NPC_SetBlocked( gentity_t *self, gentity_t *blocker ) NAVNEW_ClearPathBetweenPoints ------------------------- */ -int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask) -{ - trace_t trace; +int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask) { + trace_t trace; - //Test if they're even conceivably close to one another - if ( !gi.inPVSIgnorePortals( start, end ) ) - { + // Test if they're even conceivably close to one another + if (!gi.inPVSIgnorePortals(start, end)) { return ENTITYNUM_WORLD; } - gi.trace( &trace, start, mins, maxs, end, ignore, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&trace, start, mins, maxs, end, ignore, clipmask, G2_NOCOLLIDE, 0); - //if( ( ( trace.startsolid == false ) && ( trace.allsolid == false ) ) && ( trace.fraction < 1.0f ) ) + // if( ( ( trace.startsolid == false ) && ( trace.allsolid == false ) ) && ( trace.fraction < 1.0f ) ) //{//FIXME: check for drops? - //FIXME: if startsolid or allsolid, then the path isn't clear... but returning ENTITYNUM_NONE indicates to CheckFailedEdge that is is clear...? - return trace.entityNum; + // FIXME: if startsolid or allsolid, then the path isn't clear... but returning ENTITYNUM_NONE indicates to CheckFailedEdge that is is clear...? + return trace.entityNum; //} - //return ENTITYNUM_NONE; + // return ENTITYNUM_NONE; } /* @@ -103,91 +97,71 @@ int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t NAVNEW_PushBlocker ------------------------- */ -void NAVNEW_PushBlocker( gentity_t *self, gentity_t *blocker, vec3_t right, qboolean setBlockedInfo ) -{//try pushing blocker to one side - if ( self->NPC->shoveCount > 30 ) - {//don't push for more than 3 seconds; +void NAVNEW_PushBlocker(gentity_t *self, gentity_t *blocker, vec3_t right, qboolean setBlockedInfo) { // try pushing blocker to one side + if (self->NPC->shoveCount > 30) { // don't push for more than 3 seconds; return; } - if ( !blocker->s.number ) - {//never push the player + if (!blocker->s.number) { // never push the player return; } - if ( !blocker->client || !VectorCompare( blocker->client->pushVec, vec3_origin ) ) - {//someone else is pushing him, wait until they give up? + if (!blocker->client || !VectorCompare(blocker->client->pushVec, vec3_origin)) { // someone else is pushing him, wait until they give up? return; } - trace_t tr; - vec3_t mins, end; - float rightSucc, leftSucc, moveamt; + trace_t tr; + vec3_t mins, end; + float rightSucc, leftSucc, moveamt; - VectorCopy( blocker->mins, mins ); + VectorCopy(blocker->mins, mins); mins[2] += STEPSIZE; - moveamt = (self->maxs[1] + blocker->maxs[1]) * 1.2;//yes, magic number + moveamt = (self->maxs[1] + blocker->maxs[1]) * 1.2; // yes, magic number - VectorMA( blocker->currentOrigin, -moveamt, right, end ); - gi.trace( &tr, blocker->currentOrigin, mins, blocker->maxs, end, blocker->s.number, blocker->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid ) - { + VectorMA(blocker->currentOrigin, -moveamt, right, end); + gi.trace(&tr, blocker->currentOrigin, mins, blocker->maxs, end, blocker->s.number, blocker->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + if (!tr.startsolid && !tr.allsolid) { leftSucc = tr.fraction; - } - else - { + } else { leftSucc = 0.0f; } - if ( leftSucc >= 1.0f ) - {//it's clear, shove him that way - VectorScale( right, -moveamt, blocker->client->pushVec ); + if (leftSucc >= 1.0f) { // it's clear, shove him that way + VectorScale(right, -moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; - } - else - { - VectorMA( blocker->currentOrigin, moveamt, right, end ); - gi.trace( &tr, blocker->currentOrigin, mins, blocker->maxs, end, blocker->s.number, blocker->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); - if ( !tr.startsolid && !tr.allsolid ) - { + } else { + VectorMA(blocker->currentOrigin, moveamt, right, end); + gi.trace(&tr, blocker->currentOrigin, mins, blocker->maxs, end, blocker->s.number, blocker->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); + if (!tr.startsolid && !tr.allsolid) { rightSucc = tr.fraction; - } - else - { + } else { rightSucc = 0.0f; } - if ( leftSucc == 0.0f && rightSucc == 0.0f ) - {//both sides failed - if ( d_patched->integer ) - {//use patch-style navigation + if (leftSucc == 0.0f && rightSucc == 0.0f) { // both sides failed + if (d_patched->integer) { // use patch-style navigation blocker->client->pushVecTime = 0; } return; } - if ( rightSucc >= 1.0f ) - {//it's clear, shove him that way - VectorScale( right, moveamt, blocker->client->pushVec ); + if (rightSucc >= 1.0f) { // it's clear, shove him that way + VectorScale(right, moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; } - //if neither are enough, we probably can't get around him, but keep trying - else if ( leftSucc >= rightSucc ) - {//favor the left, all things being equal - VectorScale( right, -moveamt, blocker->client->pushVec ); + // if neither are enough, we probably can't get around him, but keep trying + else if (leftSucc >= rightSucc) { // favor the left, all things being equal + VectorScale(right, -moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; - } - else - { - VectorScale( right, moveamt, blocker->client->pushVec ); + } else { + VectorScale(right, moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; } } - if ( setBlockedInfo ) - { - //we tried pushing + if (setBlockedInfo) { + // we tried pushing self->NPC->shoveCount++; } } @@ -197,27 +171,22 @@ void NAVNEW_PushBlocker( gentity_t *self, gentity_t *blocker, vec3_t right, qboo NAVNEW_DanceWithBlocker ------------------------- */ -qboolean NAVNEW_DanceWithBlocker( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t right ) -{//sees if blocker has any lateral movement - if ( blocker->client && !VectorCompare( blocker->client->ps.velocity, vec3_origin ) ) - { +qboolean NAVNEW_DanceWithBlocker(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t right) { // sees if blocker has any lateral movement + if (blocker->client && !VectorCompare(blocker->client->ps.velocity, vec3_origin)) { vec3_t blocker_movedir; - VectorCopy( blocker->client->ps.velocity, blocker_movedir ); - blocker_movedir[2] = 0;//cancel any vertical motion - float dot = DotProduct( blocker_movedir, right ); - if ( dot > 50.0f ) - {//he's moving to the right of me at a relatively good speed - //go to my left - VectorMA( movedir, -1, right, movedir ); - VectorNormalize( movedir ); + VectorCopy(blocker->client->ps.velocity, blocker_movedir); + blocker_movedir[2] = 0; // cancel any vertical motion + float dot = DotProduct(blocker_movedir, right); + if (dot > 50.0f) { // he's moving to the right of me at a relatively good speed + // go to my left + VectorMA(movedir, -1, right, movedir); + VectorNormalize(movedir); return qtrue; - } - else if ( dot > -50.0f ) - {//he's moving to the left of me at a relatively good speed - //go to my right - VectorAdd( right, movedir, movedir ); - VectorNormalize( movedir ); + } else if (dot > -50.0f) { // he's moving to the left of me at a relatively good speed + // go to my right + VectorAdd(right, movedir, movedir); + VectorNormalize(movedir); return qtrue; } /* @@ -240,25 +209,25 @@ qboolean NAVNEW_DanceWithBlocker( gentity_t *self, gentity_t *blocker, vec3_t mo NAVNEW_SidestepBlocker ------------------------- */ -qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, vec3_t right ) -{//trace to sides of blocker and see if either is clear - trace_t tr; - vec3_t avoidAngles; - vec3_t avoidRight_dir, avoidLeft_dir, block_pos, mins; - float rightSucc, leftSucc; - - VectorCopy( self->mins, mins ); +qboolean NAVNEW_SidestepBlocker(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, + vec3_t right) { // trace to sides of blocker and see if either is clear + trace_t tr; + vec3_t avoidAngles; + vec3_t avoidRight_dir, avoidLeft_dir, block_pos, mins; + float rightSucc, leftSucc; + + VectorCopy(self->mins, mins); mins[2] += STEPSIZE; - //Get the blocked direction - float yaw = vectoyaw( blocked_dir ); + // Get the blocked direction + float yaw = vectoyaw(blocked_dir); - //Get the avoid radius - float avoidRadius = sqrt( ( blocker->maxs[0] * blocker->maxs[0] ) + ( blocker->maxs[1] * blocker->maxs[1] ) ) + - sqrt( ( self->maxs[0] * self->maxs[0] ) + ( self->maxs[1] * self->maxs[1] ) ); + // Get the avoid radius + float avoidRadius = sqrt((blocker->maxs[0] * blocker->maxs[0]) + (blocker->maxs[1] * blocker->maxs[1])) + + sqrt((self->maxs[0] * self->maxs[0]) + (self->maxs[1] * self->maxs[1])); - //See if we're inside our avoidance radius - float arcAngle = ( blocked_dist <= avoidRadius ) ? 135 : ( ( avoidRadius / blocked_dist ) * 90 ); + // See if we're inside our avoidance radius + float arcAngle = (blocked_dist <= avoidRadius) ? 135 : ((avoidRadius / blocked_dist) * 90); /* float dot = DotProduct( blocked_dir, right ); @@ -268,95 +237,81 @@ qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blo arcAngle *= -1; */ - VectorClear( avoidAngles ); + VectorClear(avoidAngles); - //need to stop it from ping-ponging, so we have a bit of a debounce time on which side you try - if ( self->NPC->sideStepHoldTime > level.time ) - { - if ( self->NPC->lastSideStepSide == -1 )//left + // need to stop it from ping-ponging, so we have a bit of a debounce time on which side you try + if (self->NPC->sideStepHoldTime > level.time) { + if (self->NPC->lastSideStepSide == -1) // left { arcAngle *= -1; - }//else right - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, movedir, NULL, NULL ); - VectorMA( self->currentOrigin, blocked_dist, movedir, block_pos ); - gi.trace( &tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); + } // else right + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, movedir, NULL, NULL); + VectorMA(self->currentOrigin, blocked_dist, movedir, block_pos); + gi.trace(&tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); return (qboolean)(tr.fraction == 1.0f && !tr.allsolid && !tr.startsolid); } - //test right - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, avoidRight_dir, NULL, NULL ); + // test right + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, avoidRight_dir, NULL, NULL); - VectorMA( self->currentOrigin, blocked_dist, avoidRight_dir, block_pos ); + VectorMA(self->currentOrigin, blocked_dist, avoidRight_dir, block_pos); - gi.trace( &tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); - if ( !tr.allsolid && !tr.startsolid ) - { - if ( tr.fraction >= 1.0f ) - {//all clear, go for it (favor the right if both are equal) - VectorCopy( avoidRight_dir, movedir ); + if (!tr.allsolid && !tr.startsolid) { + if (tr.fraction >= 1.0f) { // all clear, go for it (favor the right if both are equal) + VectorCopy(avoidRight_dir, movedir); self->NPC->lastSideStepSide = 1; self->NPC->sideStepHoldTime = level.time + 2000; return qtrue; } rightSucc = tr.fraction; - } - else - { + } else { rightSucc = 0.0f; } - //now test left + // now test left arcAngle *= -1; - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, avoidLeft_dir, NULL, NULL ); + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, avoidLeft_dir, NULL, NULL); - VectorMA( self->currentOrigin, blocked_dist, avoidLeft_dir, block_pos ); + VectorMA(self->currentOrigin, blocked_dist, avoidLeft_dir, block_pos); - gi.trace( &tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, self->currentOrigin, mins, self->maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, G2_NOCOLLIDE, 0); - if ( !tr.allsolid && !tr.startsolid ) - { - if ( tr.fraction >= 1.0f ) - {//all clear, go for it (right side would have already succeeded if as good as this) - VectorCopy( avoidLeft_dir, movedir ); + if (!tr.allsolid && !tr.startsolid) { + if (tr.fraction >= 1.0f) { // all clear, go for it (right side would have already succeeded if as good as this) + VectorCopy(avoidLeft_dir, movedir); self->NPC->lastSideStepSide = -1; self->NPC->sideStepHoldTime = level.time + 2000; return qtrue; } leftSucc = tr.fraction; - } - else - { + } else { leftSucc = 0.0f; } - if ( leftSucc == 0.0f && rightSucc == 0.0f ) - {//both sides failed + if (leftSucc == 0.0f && rightSucc == 0.0f) { // both sides failed return qfalse; } - if ( rightSucc*blocked_dist >= avoidRadius || leftSucc*blocked_dist >= avoidRadius ) - {//the traces hit something, but got a relatively good distance - if ( rightSucc >= leftSucc ) - {//favor the right, all things being equal - VectorCopy( avoidRight_dir, movedir ); + if (rightSucc * blocked_dist >= avoidRadius || leftSucc * blocked_dist >= avoidRadius) { // the traces hit something, but got a relatively good distance + if (rightSucc >= leftSucc) { // favor the right, all things being equal + VectorCopy(avoidRight_dir, movedir); self->NPC->lastSideStepSide = 1; self->NPC->sideStepHoldTime = level.time + 2000; - } - else - { - VectorCopy( avoidLeft_dir, movedir ); + } else { + VectorCopy(avoidLeft_dir, movedir); self->NPC->lastSideStepSide = -1; self->NPC->sideStepHoldTime = level.time + 2000; } return qtrue; } - //if neither are enough, we probably can't get around him + // if neither are enough, we probably can't get around him return qfalse; } @@ -365,34 +320,30 @@ qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blo NAVNEW_Bypass ------------------------- */ -qboolean NAVNEW_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, qboolean setBlockedInfo ) -{ - //Draw debug info if requested - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, blocker->currentOrigin, EDGE_NORMAL ); +qboolean NAVNEW_Bypass(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, qboolean setBlockedInfo) { + // Draw debug info if requested + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, blocker->currentOrigin, EDGE_NORMAL); } - vec3_t moveangles, right; + vec3_t moveangles, right; - vectoangles( movedir, moveangles ); + vectoangles(movedir, moveangles); moveangles[2] = 0; - AngleVectors( moveangles, NULL, right, NULL ); + AngleVectors(moveangles, NULL, right, NULL); - //Check to see what dir the other guy is moving in (if any) and pick the opposite dir - if ( NAVNEW_DanceWithBlocker( self, blocker, movedir, right ) ) - { + // Check to see what dir the other guy is moving in (if any) and pick the opposite dir + if (NAVNEW_DanceWithBlocker(self, blocker, movedir, right)) { return qtrue; } - //Okay, so he's not moving to my side, see which side of him is most clear - if ( NAVNEW_SidestepBlocker( self, blocker, blocked_dir, blocked_dist, movedir, right ) ) - { + // Okay, so he's not moving to my side, see which side of him is most clear + if (NAVNEW_SidestepBlocker(self, blocker, blocked_dir, blocked_dist, movedir, right)) { return qtrue; } - //Neither side is clear, tell him to step aside - NAVNEW_PushBlocker( self, blocker, right, setBlockedInfo ); + // Neither side is clear, tell him to step aside + NAVNEW_PushBlocker(self, blocker, right, setBlockedInfo); return qfalse; } @@ -402,10 +353,9 @@ qboolean NAVNEW_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, NAVNEW_CheckDoubleBlock ------------------------- */ -qboolean NAVNEW_CheckDoubleBlock( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir ) -{ - //Stop double waiting - if ( ( blocker->NPC ) && ( blocker->NPC->blockingEntNum == self->s.number ) ) +qboolean NAVNEW_CheckDoubleBlock(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir) { + // Stop double waiting + if ((blocker->NPC) && (blocker->NPC->blockingEntNum == self->s.number)) return qtrue; return qfalse; @@ -416,39 +366,36 @@ qboolean NAVNEW_CheckDoubleBlock( gentity_t *self, gentity_t *blocker, vec3_t bl NAVNEW_ResolveEntityCollision ------------------------- */ -extern void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ); -qboolean NAVNEW_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir, qboolean setBlockedInfo ) -{ - vec3_t blocked_dir; - - //Doors are ignored - if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) - { +extern void CalcTeamDoorCenter(gentity_t *ent, vec3_t center); +qboolean NAVNEW_ResolveEntityCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir, qboolean setBlockedInfo) { + vec3_t blocked_dir; + + // Doors are ignored + if (Q_stricmp(blocker->classname, "func_door") == 0) { vec3_t center; - CalcTeamDoorCenter ( blocker, center ); - if ( DistanceSquared( self->currentOrigin, center ) > MIN_DOOR_BLOCK_DIST_SQR ) + CalcTeamDoorCenter(blocker, center); + if (DistanceSquared(self->currentOrigin, center) > MIN_DOOR_BLOCK_DIST_SQR) return qtrue; } - VectorSubtract( blocker->currentOrigin, self->currentOrigin, blocked_dir ); - float blocked_dist = VectorNormalize( blocked_dir ); + VectorSubtract(blocker->currentOrigin, self->currentOrigin, blocked_dir); + float blocked_dist = VectorNormalize(blocked_dir); - //Make sure an actual collision is going to happen -// if ( NAVNEW_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) -// return qtrue; + // Make sure an actual collision is going to happen + // if ( NAVNEW_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) + // return qtrue; - //First, attempt to walk around the blocker or shove him out of the way - if ( NAVNEW_Bypass( self, blocker, blocked_dir, blocked_dist, movedir, setBlockedInfo ) ) + // First, attempt to walk around the blocker or shove him out of the way + if (NAVNEW_Bypass(self, blocker, blocked_dir, blocked_dist, movedir, setBlockedInfo)) return qtrue; - //Can't get around him... see if I'm blocking him too... if so, I need to just keep moving? - if ( NAVNEW_CheckDoubleBlock( self, blocker, blocked_dir ) ) + // Can't get around him... see if I'm blocking him too... if so, I need to just keep moving? + if (NAVNEW_CheckDoubleBlock(self, blocker, blocked_dir)) return qtrue; - if ( setBlockedInfo ) - { - //Complain about it if we can - NPC_SetBlocked( self, blocker ); + if (setBlockedInfo) { + // Complain about it if we can + NPC_SetBlocked(self, blocker); } return qfalse; @@ -459,131 +406,113 @@ qboolean NAVNEW_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec NAVNEW_AvoidCollision ------------------------- */ -qboolean NAVNEW_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t &info, qboolean setBlockedInfo, int blockedMovesLimit ) -{ - vec3_t movedir; - vec3_t movepos; - - //Cap our distance - if ( info.distance > MAX_COLL_AVOID_DIST ) - { +qboolean NAVNEW_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t &info, qboolean setBlockedInfo, int blockedMovesLimit) { + vec3_t movedir; + vec3_t movepos; + + // Cap our distance + if (info.distance > MAX_COLL_AVOID_DIST) { info.distance = MAX_COLL_AVOID_DIST; } - //Get an end position - VectorMA( self->currentOrigin, info.distance, info.direction, movepos ); - VectorCopy( info.direction, movedir ); + // Get an end position + VectorMA(self->currentOrigin, info.distance, info.direction, movepos); + VectorCopy(info.direction, movedir); - //Now test against entities - if ( NAV_CheckAhead( self, movepos, info.trace, CONTENTS_BODY ) == qfalse ) - { - //Get the blocker - info.blocker = &g_entities[ info.trace.entityNum ]; + // Now test against entities + if (NAV_CheckAhead(self, movepos, info.trace, CONTENTS_BODY) == qfalse) { + // Get the blocker + info.blocker = &g_entities[info.trace.entityNum]; info.flags |= NIF_COLLISION; - //Ok to hit our goal entity - if ( goal == info.blocker ) + // Ok to hit our goal entity + if (goal == info.blocker) return qtrue; - if ( setBlockedInfo ) - { - if ( self->NPC->consecutiveBlockedMoves > blockedMovesLimit ) - { - if ( d_patched->integer ) - {//use patch-style navigation + if (setBlockedInfo) { + if (self->NPC->consecutiveBlockedMoves > blockedMovesLimit) { + if (d_patched->integer) { // use patch-style navigation self->NPC->consecutiveBlockedMoves++; } - NPC_SetBlocked( self, info.blocker ); + NPC_SetBlocked(self, info.blocker); return qfalse; } self->NPC->consecutiveBlockedMoves++; } - //See if we're moving along with them - //if ( NAVNEW_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) + // See if we're moving along with them + // if ( NAVNEW_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) // return qtrue; - //Test for blocking by standing on goal - if ( NAV_TestForBlocked( self, goal, info.blocker, info.distance, info.flags ) == qtrue ) + // Test for blocking by standing on goal + if (NAV_TestForBlocked(self, goal, info.blocker, info.distance, info.flags) == qtrue) return qfalse; - //If the above function said we're blocked, don't do the extra checks + // If the above function said we're blocked, don't do the extra checks /* if ( info.flags & NIF_BLOCKED ) return qtrue; */ - //See if we can get that entity to move out of our way - if ( NAVNEW_ResolveEntityCollision( self, info.blocker, movedir, info.pathDirection, setBlockedInfo ) == qfalse ) + // See if we can get that entity to move out of our way + if (NAVNEW_ResolveEntityCollision(self, info.blocker, movedir, info.pathDirection, setBlockedInfo) == qfalse) return qfalse; - VectorCopy( movedir, info.direction ); + VectorCopy(movedir, info.direction); return qtrue; - } - else - { - if ( setBlockedInfo ) - { + } else { + if (setBlockedInfo) { self->NPC->consecutiveBlockedMoves = 0; } } - //Our path is clear, just move there - if ( NAVDEBUG_showCollision ) - { - CG_DrawEdge( self->currentOrigin, movepos, EDGE_MOVEDIR ); + // Our path is clear, just move there + if (NAVDEBUG_showCollision) { + CG_DrawEdge(self->currentOrigin, movepos, EDGE_MOVEDIR); } return qtrue; } -qboolean NAVNEW_TestNodeConnectionBlocked( int wp1, int wp2, gentity_t *ignoreEnt, int goalEntNum, qboolean checkWorld, qboolean checkEnts ) -{//see if the direct path between 2 nodes is blocked by architecture or an ent - vec3_t pos1, pos2, mins, maxs; - trace_t trace; - int clipmask = MASK_NPCSOLID|CONTENTS_BOTCLIP; +qboolean NAVNEW_TestNodeConnectionBlocked(int wp1, int wp2, gentity_t *ignoreEnt, int goalEntNum, qboolean checkWorld, + qboolean checkEnts) { // see if the direct path between 2 nodes is blocked by architecture or an ent + vec3_t pos1, pos2, mins, maxs; + trace_t trace; + int clipmask = MASK_NPCSOLID | CONTENTS_BOTCLIP; int ignoreEntNum; - if ( !checkWorld && !checkEnts ) - {//duh, nothing to trace against + if (!checkWorld && !checkEnts) { // duh, nothing to trace against return qfalse; } - navigator.GetNodePosition( wp1, pos1 ); - navigator.GetNodePosition( wp2, pos2 ); + navigator.GetNodePosition(wp1, pos1); + navigator.GetNodePosition(wp2, pos2); - if ( !checkWorld ) - { - clipmask &= ~(CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP); + if (!checkWorld) { + clipmask &= ~(CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); } - if ( !checkEnts ) - { + if (!checkEnts) { clipmask &= ~CONTENTS_BODY; } - if ( ignoreEnt ) - { - VectorCopy( ignoreEnt->mins, mins ); - VectorCopy( ignoreEnt->maxs, maxs ); + if (ignoreEnt) { + VectorCopy(ignoreEnt->mins, mins); + VectorCopy(ignoreEnt->maxs, maxs); ignoreEntNum = ignoreEnt->s.number; - } - else - { - VectorCopy( playerMins, mins ); - VectorCopy( playerMaxs, maxs ); + } else { + VectorCopy(playerMins, mins); + VectorCopy(playerMaxs, maxs); ignoreEntNum = ENTITYNUM_NONE; } mins[2] += STEPSIZE; - //don't let box get inverted - if ( mins[2] > maxs[2] ) - { + // don't let box get inverted + if (mins[2] > maxs[2]) { mins[2] = maxs[2]; } - gi.trace( &trace, pos1, mins, maxs, pos2, ignoreEntNum, clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.fraction >= 1.0f || trace.entityNum == goalEntNum ) - {//clear or hit goal + gi.trace(&trace, pos1, mins, maxs, pos2, ignoreEntNum, clipmask, G2_NOCOLLIDE, 0); + if (trace.fraction >= 1.0f || trace.entityNum == goalEntNum) { // clear or hit goal return qfalse; } - //hit something we weren't supposed to + // hit something we weren't supposed to return qtrue; } /* @@ -591,70 +520,59 @@ qboolean NAVNEW_TestNodeConnectionBlocked( int wp1, int wp2, gentity_t *ignoreEn NAVNEW_MoveToGoal ------------------------- */ -int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t &info ) -{ - int bestNode = WAYPOINT_NONE; - qboolean foundClearPath = qfalse; - vec3_t origin; - navInfo_t tempInfo; - qboolean setBlockedInfo = qtrue; - qboolean inGoalWP; - int numTries = 0; - - memcpy( &tempInfo, &info, sizeof( tempInfo ) ); - - //Must have a goal entity to move there - if( self->NPC->goalEntity == NULL ) +int NAVNEW_MoveToGoal(gentity_t *self, navInfo_t &info) { + int bestNode = WAYPOINT_NONE; + qboolean foundClearPath = qfalse; + vec3_t origin; + navInfo_t tempInfo; + qboolean setBlockedInfo = qtrue; + qboolean inGoalWP; + int numTries = 0; + + memcpy(&tempInfo, &info, sizeof(tempInfo)); + + // Must have a goal entity to move there + if (self->NPC->goalEntity == NULL) return WAYPOINT_NONE; - if ( self->waypoint == WAYPOINT_NONE && self->noWaypointTime > level.time ) - {//didn't have a valid one in about the past second, don't look again just yet + if (self->waypoint == WAYPOINT_NONE && self->noWaypointTime > level.time) { // didn't have a valid one in about the past second, don't look again just yet return WAYPOINT_NONE; } - if ( self->NPC->goalEntity->waypoint == WAYPOINT_NONE && self->NPC->goalEntity->noWaypointTime > level.time ) - {//didn't have a valid one in about the past second, don't look again just yet + if (self->NPC->goalEntity->waypoint == WAYPOINT_NONE && + self->NPC->goalEntity->noWaypointTime > level.time) { // didn't have a valid one in about the past second, don't look again just yet return WAYPOINT_NONE; } - if ( self->noWaypointTime > level.time && - self->NPC->goalEntity->noWaypointTime > level.time ) - {//just use current waypoints - bestNode = navigator.GetBestNodeAltRoute( self->waypoint, self->NPC->goalEntity->waypoint, bestNode ); + if (self->noWaypointTime > level.time && self->NPC->goalEntity->noWaypointTime > level.time) { // just use current waypoints + bestNode = navigator.GetBestNodeAltRoute(self->waypoint, self->NPC->goalEntity->waypoint, bestNode); } - //FIXME!!!!: this is making them wiggle back and forth between waypoints - else if ( (bestNode = navigator.GetBestPathBetweenEnts( self, self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( self, qtrue ) ) - {//one of us didn't have a valid waypoint! - if ( self->waypoint == NODE_NONE ) - {//don't even try to find one again for a bit - self->noWaypointTime = level.time + Q_irand( 500, 1500 ); + // FIXME!!!!: this is making them wiggle back and forth between waypoints + else if ((bestNode = navigator.GetBestPathBetweenEnts(self, self->NPC->goalEntity, NF_CLEAR_PATH)) == NODE_NONE) //! NAVNEW_GetWaypoints( self, qtrue ) ) + { // one of us didn't have a valid waypoint! + if (self->waypoint == NODE_NONE) { // don't even try to find one again for a bit + self->noWaypointTime = level.time + Q_irand(500, 1500); } - if ( self->NPC->goalEntity->waypoint == NODE_NONE ) - {//don't even try to find one again for a bit - self->NPC->goalEntity->noWaypointTime = level.time + Q_irand( 500, 1500 ); + if (self->NPC->goalEntity->waypoint == NODE_NONE) { // don't even try to find one again for a bit + self->NPC->goalEntity->noWaypointTime = level.time + Q_irand(500, 1500); } return WAYPOINT_NONE; - } - else - { - if ( self->NPC->goalEntity->noWaypointTime < level.time ) - { - self->NPC->goalEntity->noWaypointTime = level.time + Q_irand( 500, 1500 ); + } else { + if (self->NPC->goalEntity->noWaypointTime < level.time) { + self->NPC->goalEntity->noWaypointTime = level.time + Q_irand(500, 1500); } } - while( !foundClearPath ) - { - /*inBestWP = */inGoalWP = qfalse; + while (!foundClearPath) { + /*inBestWP = */ inGoalWP = qfalse; /* bestNode = navigator.GetBestNodeAltRoute( self->waypoint, self->NPC->goalEntity->waypoint, bestNode ); */ - if ( bestNode == WAYPOINT_NONE ) - { + if (bestNode == WAYPOINT_NONE) { goto failed; } - //see if we can get directly to the next node off bestNode en route to goal's node... - //NOTE: shouldn't be necc. now + // see if we can get directly to the next node off bestNode en route to goal's node... + // NOTE: shouldn't be necc. now /* int oldBestNode = bestNode; bestNode = NAV_TestBestNode( self, self->waypoint, bestNode, qtrue );//, self->NPC->goalEntity->waypoint );// @@ -668,7 +586,7 @@ int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t &info ) } } */ - navigator.GetNodePosition( bestNode, origin ); + navigator.GetNodePosition(bestNode, origin); /* if ( !goalWPFailed ) {//we haven't already tried to go straight to goal or goal's wp @@ -686,180 +604,150 @@ int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t &info ) } } */ - if ( !inGoalWP ) - {//not heading straight for goal - if ( bestNode == self->waypoint ) - {//we know it's clear or architecture - //navigator.GetNodePosition( self->waypoint, origin ); + if (!inGoalWP) { // not heading straight for goal + if (bestNode == self->waypoint) { // we know it's clear or architecture + // navigator.GetNodePosition( self->waypoint, origin ); /* if ( NAV_HitNavGoal( self->currentOrigin, self->mins, self->maxs, origin, navigator.GetNodeRadius( bestNode ), FlyingCreature( self ) ) ) {//we're in the wp we're heading for already inBestWP = qtrue; } */ - } - else - {//heading to an edge off our confirmed clear waypoint... make sure it's clear - //it it's not, bestNode will fall back to our waypoint + } else { // heading to an edge off our confirmed clear waypoint... make sure it's clear + // it it's not, bestNode will fall back to our waypoint int oldBestNode = bestNode; - bestNode = NAV_TestBestNode( self, self->waypoint, bestNode, qtrue ); - if ( bestNode == self->waypoint ) - {//we fell back to our waypoint, reset the origin + bestNode = NAV_TestBestNode(self, self->waypoint, bestNode, qtrue); + if (bestNode == self->waypoint) { // we fell back to our waypoint, reset the origin self->NPC->aiFlags |= NPCAI_BLOCKED; - navigator.GetNodePosition( oldBestNode, NPCInfo->blockedDest ); - navigator.GetNodePosition( bestNode, origin ); + navigator.GetNodePosition(oldBestNode, NPCInfo->blockedDest); + navigator.GetNodePosition(bestNode, origin); } } } - //Com_Printf( "goalwp = %d, mywp = %d, node = %d, origin = %s\n", self->NPC->goalEntity->waypoint, self->waypoint, bestNode, vtos(origin) ); + // Com_Printf( "goalwp = %d, mywp = %d, node = %d, origin = %s\n", self->NPC->goalEntity->waypoint, self->waypoint, bestNode, vtos(origin) ); - memcpy( &tempInfo, &info, sizeof( tempInfo ) ); - VectorSubtract( origin, self->currentOrigin, tempInfo.direction ); - VectorNormalize( tempInfo.direction ); + memcpy(&tempInfo, &info, sizeof(tempInfo)); + VectorSubtract(origin, self->currentOrigin, tempInfo.direction); + VectorNormalize(tempInfo.direction); - //NOTE: One very important thing NAVNEW_AvoidCollision does is + // NOTE: One very important thing NAVNEW_AvoidCollision does is // it actually CHANGES the value of "direction" - it changes it to // whatever dir you need to go in to avoid the obstacle... - foundClearPath = NAVNEW_AvoidCollision( self, self->NPC->goalEntity, tempInfo, setBlockedInfo, 5 ); - - if ( !foundClearPath ) - {//blocked by an ent - if ( inGoalWP ) - {//we were heading straight for the goal, head for the goal's wp instead - navigator.GetNodePosition( bestNode, origin ); - foundClearPath = NAVNEW_AvoidCollision( self, self->NPC->goalEntity, tempInfo, setBlockedInfo, 5 ); + foundClearPath = NAVNEW_AvoidCollision(self, self->NPC->goalEntity, tempInfo, setBlockedInfo, 5); + + if (!foundClearPath) { // blocked by an ent + if (inGoalWP) { // we were heading straight for the goal, head for the goal's wp instead + navigator.GetNodePosition(bestNode, origin); + foundClearPath = NAVNEW_AvoidCollision(self, self->NPC->goalEntity, tempInfo, setBlockedInfo, 5); } } - if ( foundClearPath ) - {//clear! - //If we got set to blocked, clear it - NPC_ClearBlocked( self ); - //Take the dir - memcpy( &info, &tempInfo, sizeof( info ) ); - if ( self->s.weapon == WP_SABER ) - {//jedi - if ( info.direction[2] * info.distance > 64 ) - { + if (foundClearPath) { // clear! + // If we got set to blocked, clear it + NPC_ClearBlocked(self); + // Take the dir + memcpy(&info, &tempInfo, sizeof(info)); + if (self->s.weapon == WP_SABER) { // jedi + if (info.direction[2] * info.distance > 64) { self->NPC->aiFlags |= NPCAI_BLOCKED; - VectorCopy( origin, NPCInfo->blockedDest ); + VectorCopy(origin, NPCInfo->blockedDest); goto failed; } } - } - else - {//blocked by ent! - if ( setBlockedInfo ) - { + } else { // blocked by ent! + if (setBlockedInfo) { self->NPC->aiFlags |= NPCAI_BLOCKED; - navigator.GetNodePosition( bestNode, NPCInfo->blockedDest ); + navigator.GetNodePosition(bestNode, NPCInfo->blockedDest); } - //Only set blocked info first time + // Only set blocked info first time setBlockedInfo = qfalse; - if ( inGoalWP ) - {//we headed for our goal and failed and our goal's WP and failed - if ( self->waypoint == self->NPC->goalEntity->waypoint ) - {//our waypoint is our goal's waypoint, nothing we can do - //remember that this node is blocked - navigator.AddFailedNode( self, self->waypoint ); + if (inGoalWP) { // we headed for our goal and failed and our goal's WP and failed + if (self->waypoint == self->NPC->goalEntity->waypoint) { // our waypoint is our goal's waypoint, nothing we can do + // remember that this node is blocked + navigator.AddFailedNode(self, self->waypoint); goto failed; - } - else - {//try going for our waypoint this time - //goalWPFailed = qtrue; + } else { // try going for our waypoint this time + // goalWPFailed = qtrue; inGoalWP = qfalse; } - } - else if ( bestNode != self->waypoint ) - {//we headed toward our next waypoint (instead of our waypoint) and failed - if ( d_altRoutes->integer ) - {//mark this edge failed and try our waypoint - //NOTE: don't assume there is something blocking the direct path + } else if (bestNode != self->waypoint) { // we headed toward our next waypoint (instead of our waypoint) and failed + if (d_altRoutes->integer) { // mark this edge failed and try our waypoint + // NOTE: don't assume there is something blocking the direct path // between my waypoint and the bestNode... I could be off // that path because of collision avoidance... - if ( d_patched->integer &&//use patch-style navigation - ( !navigator.NodesAreNeighbors( self->waypoint, bestNode ) - || NAVNEW_TestNodeConnectionBlocked( self->waypoint, bestNode, self, self->NPC->goalEntity->s.number, qfalse, qtrue ) ) ) - {//the direct path between these 2 nodes is blocked by an ent - navigator.AddFailedEdge( self->s.number, self->waypoint, bestNode ); + if (d_patched->integer && // use patch-style navigation + (!navigator.NodesAreNeighbors(self->waypoint, bestNode) || + NAVNEW_TestNodeConnectionBlocked(self->waypoint, bestNode, self, self->NPC->goalEntity->s.number, qfalse, + qtrue))) { // the direct path between these 2 nodes is blocked by an ent + navigator.AddFailedEdge(self->s.number, self->waypoint, bestNode); } bestNode = self->waypoint; - } - else - { - //we should stop + } else { + // we should stop goto failed; } - } - else - {//we headed for *our* waypoint and couldn't get to it - if ( d_altRoutes->integer ) - { - //remember that this node is blocked - navigator.AddFailedNode( self, self->waypoint ); - //Now we should get our waypoints again - //FIXME: cache the trace-data for subsequent calls as only the route info would have changed - //if ( (bestNode = navigator.GetBestPathBetweenEnts( self, self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( self, qfalse ) ) - {//one of our waypoints is WAYPOINT_NONE now + } else { // we headed for *our* waypoint and couldn't get to it + if (d_altRoutes->integer) { + // remember that this node is blocked + navigator.AddFailedNode(self, self->waypoint); + // Now we should get our waypoints again + // FIXME: cache the trace-data for subsequent calls as only the route info would have changed + // if ( (bestNode = navigator.GetBestPathBetweenEnts( self, self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( + // self, qfalse ) ) + { // one of our waypoints is WAYPOINT_NONE now goto failed; } - } - else - { - //we should stop + } else { + // we should stop goto failed; } } - if ( ++numTries >= 10 ) - { + if (++numTries >= 10) { goto failed; } } } -//finish: - //Draw any debug info, if requested - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t dest, start; + // finish: + // Draw any debug info, if requested + if (NAVDEBUG_showEnemyPath) { + vec3_t dest, start; - //Get the positions - navigator.GetNodePosition( self->NPC->goalEntity->waypoint, dest ); - navigator.GetNodePosition( bestNode, start ); + // Get the positions + navigator.GetNodePosition(self->NPC->goalEntity->waypoint, dest); + navigator.GetNodePosition(bestNode, start); - //Draw the route - CG_DrawNode( start, NODE_START ); - if ( bestNode != self->waypoint ) - { - vec3_t wpPos; - navigator.GetNodePosition( self->waypoint, wpPos ); - CG_DrawNode( wpPos, NODE_NAVGOAL ); + // Draw the route + CG_DrawNode(start, NODE_START); + if (bestNode != self->waypoint) { + vec3_t wpPos; + navigator.GetNodePosition(self->waypoint, wpPos); + CG_DrawNode(wpPos, NODE_NAVGOAL); } - CG_DrawNode( dest, NODE_GOAL ); - CG_DrawEdge( dest, self->NPC->goalEntity->currentOrigin, EDGE_PATH ); - CG_DrawNode( self->NPC->goalEntity->currentOrigin, NODE_GOAL ); - navigator.ShowPath( bestNode, self->NPC->goalEntity->waypoint ); + CG_DrawNode(dest, NODE_GOAL); + CG_DrawEdge(dest, self->NPC->goalEntity->currentOrigin, EDGE_PATH); + CG_DrawNode(self->NPC->goalEntity->currentOrigin, NODE_GOAL); + navigator.ShowPath(bestNode, self->NPC->goalEntity->waypoint); } self->NPC->shoveCount = 0; - //let me keep this waypoint for a while - if ( self->noWaypointTime < level.time ) - { - self->noWaypointTime = level.time + Q_irand( 500, 1500 ); + // let me keep this waypoint for a while + if (self->noWaypointTime < level.time) { + self->noWaypointTime = level.time + Q_irand(500, 1500); } return bestNode; failed: - //FIXME: What we should really do here is have a list of the goal's and our + // FIXME: What we should really do here is have a list of the goal's and our // closest clearpath waypoints, ranked. If the first set fails, try the rest // until there are no alternatives. - navigator.GetNodePosition( self->waypoint, origin ); + navigator.GetNodePosition(self->waypoint, origin); - //do this to avoid ping-ponging? + // do this to avoid ping-ponging? return WAYPOINT_NONE; /* //this was causing ping-ponging diff --git a/codeJK2/game/g_object.cpp b/codeJK2/game/g_object.cpp index 100c93965d..125b018fd9 100644 --- a/codeJK2/game/g_object.cpp +++ b/codeJK2/game/g_object.cpp @@ -25,8 +25,8 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" -extern void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); -void G_StopObjectMoving( gentity_t *object ); +extern void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg); +void G_StopObjectMoving(gentity_t *object); /* ================ @@ -34,37 +34,36 @@ G_BounceMissile ================ */ -void G_BounceObject( gentity_t *ent, trace_t *trace ) -{ - vec3_t velocity; - float dot; - int hitTime; +void G_BounceObject(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - float bounceFactor = 60/ent->mass; - if ( bounceFactor > 1.0f ) - { + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + float bounceFactor = 60 / ent->mass; + if (bounceFactor > 1.0f) { bounceFactor = 1.0f; } - VectorMA( velocity, -2*dot*bounceFactor, trace->plane.normal, ent->s.pos.trDelta ); + VectorMA(velocity, -2 * dot * bounceFactor, trace->plane.normal, ent->s.pos.trDelta); - //FIXME: customized or material-based impact/bounce sounds - if ( ent->s.eFlags & EF_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); + // FIXME: customized or material-based impact/bounce sounds + if (ent->s.eFlags & EF_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta); // check for stop - if ( ((trace->plane.normal[2] > 0.7&&g_gravity->value>0) || (trace->plane.normal[2]<-0.7&&g_gravity->value<0)) && ((ent->s.pos.trDelta[2]<40&&g_gravity->value>0)||(ent->s.pos.trDelta[2]>-40&&g_gravity->value<0)) ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (((trace->plane.normal[2] > 0.7 && g_gravity->value > 0) || (trace->plane.normal[2] < -0.7 && g_gravity->value < 0)) && + ((ent->s.pos.trDelta[2] < 40 && g_gravity->value > 0) || + (ent->s.pos.trDelta[2] > -40 && g_gravity->value < 0))) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - //G_SetOrigin( ent, trace->endpos ); - //ent->nextthink = level.time + 500; + // G_SetOrigin( ent, trace->endpos ); + // ent->nextthink = level.time + 500; ent->s.apos.trType = TR_STATIONARY; - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - VectorCopy( trace->endpos, ent->currentOrigin ); - VectorCopy( trace->endpos, ent->s.pos.trBase ); + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + VectorCopy(trace->endpos, ent->currentOrigin); + VectorCopy(trace->endpos, ent->s.pos.trBase); ent->s.pos.trTime = level.time; return; } @@ -73,11 +72,11 @@ void G_BounceObject( gentity_t *ent, trace_t *trace ) // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... // FIXME: Should we still consider adding the normal though?? - VectorCopy( trace->endpos, ent->currentOrigin ); + VectorCopy(trace->endpos, ent->currentOrigin); ent->s.pos.trTime = hitTime; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorCopy( trace->plane.normal, ent->pos1 );//??? + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorCopy(trace->plane.normal, ent->pos1); //??? } /* @@ -88,55 +87,49 @@ G_RunObject TODO: When free-floating in air, apply some friction to your trDelta (based on mass?) ================ */ -extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ); -extern void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); -void G_RunObject( gentity_t *ent ) -{ - vec3_t origin, oldOrg; - trace_t tr; - gentity_t *traceEnt = NULL; - - //FIXME: floaters need to stop floating up after a while, even if gravity stays negative? - if ( ent->s.pos.trType == TR_STATIONARY )//g_gravity->value <= 0 && +extern void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf); +extern void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope); +void G_RunObject(gentity_t *ent) { + vec3_t origin, oldOrg; + trace_t tr; + gentity_t *traceEnt = NULL; + + // FIXME: floaters need to stop floating up after a while, even if gravity stays negative? + if (ent->s.pos.trType == TR_STATIONARY) // g_gravity->value <= 0 && { ent->s.pos.trType = TR_GRAVITY; - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - ent->s.pos.trTime = level.previousTime;//?necc? - if ( !g_gravity->value ) - { + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + ent->s.pos.trTime = level.previousTime; //?necc? + if (!g_gravity->value) { ent->s.pos.trDelta[2] += 100; } } ent->nextthink = level.time + FRAMETIME; - VectorCopy( ent->currentOrigin, oldOrg ); + VectorCopy(ent->currentOrigin, oldOrg); // get current position - EvaluateTrajectory( &ent->s.pos, level.time, origin ); - //Get current angles? - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); + EvaluateTrajectory(&ent->s.pos, level.time, origin); + // Get current angles? + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); - if ( VectorCompare( ent->currentOrigin, origin ) ) - {//error - didn't move at all! + if (VectorCompare(ent->currentOrigin, origin)) { // error - didn't move at all! return; } // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, - ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ent->owner ? ent->owner->s.number : ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction ) - { - VectorCopy( tr.endpos, ent->currentOrigin ); - gi.linkentity( ent ); - } - else - //if ( tr.startsolid ) + if (!tr.startsolid && !tr.allsolid && tr.fraction) { + VectorCopy(tr.endpos, ent->currentOrigin); + gi.linkentity(ent); + } else + // if ( tr.startsolid ) { tr.fraction = 0; } - G_MoverTouchPushTriggers( ent, oldOrg ); + G_MoverTouchPushTriggers(ent, oldOrg); /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) && !(ent->svFlags & SVF_NO_TELEPORT) ) { @@ -152,23 +145,19 @@ void G_RunObject( gentity_t *ent ) } */ - if ( tr.fraction == 1 ) - { - if ( g_gravity->value <= 0 ) - { - if ( ent->s.apos.trType == TR_STATIONARY ) - { - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + if (tr.fraction == 1) { + if (g_gravity->value <= 0) { + if (ent->s.apos.trType == TR_STATIONARY) { + VectorCopy(ent->currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; - ent->s.apos.trDelta[1] = Q_flrand( -300, 300 ); - ent->s.apos.trDelta[0] = Q_flrand( -10, 10 ); - ent->s.apos.trDelta[2] = Q_flrand( -10, 10 ); + ent->s.apos.trDelta[1] = Q_flrand(-300, 300); + ent->s.apos.trDelta[0] = Q_flrand(-10, 10); + ent->s.apos.trDelta[2] = Q_flrand(-10, 10); ent->s.apos.trTime = level.time; } } - //friction in zero-G - if ( !g_gravity->value ) - { + // friction in zero-G + if (!g_gravity->value) { float friction = 0.975f; /*friction -= ent->mass/1000.0f; if ( friction < 0.1 ) @@ -176,94 +165,77 @@ void G_RunObject( gentity_t *ent ) friction = 0.1f; } */ - VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(ent->s.pos.trDelta, friction, ent->s.pos.trDelta); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } return; } - //hit something + // hit something - //Do impact damage + // Do impact damage traceEnt = &g_entities[tr.entityNum]; - if ( tr.fraction || (traceEnt && traceEnt->takedamage) ) - { - if ( !VectorCompare( ent->currentOrigin, oldOrg ) ) - {//moved and impacted - if ( (traceEnt && traceEnt->takedamage) ) - {//hurt someone - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHurt.wav" ) ); + if (tr.fraction || (traceEnt && traceEnt->takedamage)) { + if (!VectorCompare(ent->currentOrigin, oldOrg)) { // moved and impacted + if ((traceEnt && traceEnt->takedamage)) { // hurt someone + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectHurt.wav")); } - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHit.wav" ) ); + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectHit.wav")); } - DoImpact( ent, traceEnt, (qboolean)(!(tr.surfaceFlags & SURF_NODAMAGE)) ); + DoImpact(ent, traceEnt, (qboolean)(!(tr.surfaceFlags & SURF_NODAMAGE))); } - if ( !ent || (ent->takedamage&&ent->health <= 0) ) - {//been destroyed by impact - //chunks? - G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectBreak.wav" ) ); + if (!ent || (ent->takedamage && ent->health <= 0)) { // been destroyed by impact + // chunks? + G_Sound(ent, G_SoundIndex("sound/movers/objects/objectBreak.wav")); return; } - //do impact physics - if ( ent->s.pos.trType == TR_GRAVITY )//tr.fraction < 1.0 && - {//FIXME: only do this if no trDelta - if ( g_gravity->value <= 0 || tr.plane.normal[2] < 0.7 ) - { - if ( ent->s.eFlags&(EF_BOUNCE|EF_BOUNCE_HALF) ) - { - if ( tr.fraction <= 0.0f ) - { - VectorCopy( tr.endpos, ent->currentOrigin ); - VectorCopy( tr.endpos, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + // do impact physics + if (ent->s.pos.trType == TR_GRAVITY) // tr.fraction < 1.0 && + { // FIXME: only do this if no trDelta + if (g_gravity->value <= 0 || tr.plane.normal[2] < 0.7) { + if (ent->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF)) { + if (tr.fraction <= 0.0f) { + VectorCopy(tr.endpos, ent->currentOrigin); + VectorCopy(tr.endpos, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; + } else { + G_BounceObject(ent, &tr); } - else - { - G_BounceObject( ent, &tr ); - } + } else { // slide down? + // FIXME: slide off the slope } - else - {//slide down? - //FIXME: slide off the slope - } - } - else - { + } else { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->currentAngles[0] = 0;//FIXME: match to slope - //ent->currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); - //okay, we hit the floor, might as well stop or prediction will - //make us go through the floor! - //FIXME: this means we can't fall if something is pulled out from under us... - G_StopObjectMoving( ent ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->currentAngles[0] = 0;//FIXME: match to slope + // ent->currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->currentAngles, ent->s.apos.trBase); + // okay, we hit the floor, might as well stop or prediction will + // make us go through the floor! + // FIXME: this means we can't fall if something is pulled out from under us... + G_StopObjectMoving(ent); } - } - else - { + } else { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->currentAngles[0] = 0;//FIXME: match to slope - //ent->currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->currentAngles, ent->s.apos.trBase ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->currentAngles[0] = 0;//FIXME: match to slope + // ent->currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->currentAngles, ent->s.apos.trBase); } - - //call touch func - GEntity_TouchFunc( ent, &g_entities[tr.entityNum], &tr ); + // call touch func + GEntity_TouchFunc(ent, &g_entities[tr.entityNum], &tr); } -void G_StopObjectMoving( gentity_t *object ) -{ +void G_StopObjectMoving(gentity_t *object) { object->s.pos.trType = TR_STATIONARY; - VectorCopy( object->currentOrigin, object->s.origin ); - VectorCopy( object->currentOrigin, object->s.pos.trBase ); - VectorClear( object->s.pos.trDelta ); + VectorCopy(object->currentOrigin, object->s.origin); + VectorCopy(object->currentOrigin, object->s.pos.trBase); + VectorClear(object->s.pos.trDelta); /* //Stop spinning @@ -274,14 +246,13 @@ void G_StopObjectMoving( gentity_t *object ) */ } -void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t trType ) -{ - VectorNormalize (dir); +void G_StartObjectMoving(gentity_t *object, vec3_t dir, float speed, trType_t trType) { + VectorNormalize(dir); - //object->s.eType = ET_GENERAL; + // object->s.eType = ET_GENERAL; object->s.pos.trType = trType; - VectorCopy( object->currentOrigin, object->s.pos.trBase ); - VectorScale(dir, speed, object->s.pos.trDelta ); + VectorCopy(object->currentOrigin, object->s.pos.trBase); + VectorScale(dir, speed, object->s.pos.trDelta); object->s.pos.trTime = level.time; /* @@ -292,69 +263,64 @@ void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t t object->s.apos.trTime = level.time; */ - //FIXME: make these objects go through G_RunObject automatically, like missiles do - if ( object->e_ThinkFunc == thinkF_NULL ) - { + // FIXME: make these objects go through G_RunObject automatically, like missiles do + if (object->e_ThinkFunc == thinkF_NULL) { object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; - } - else - {//You're responsible for calling RunObject + } else { // You're responsible for calling RunObject } } -gentity_t *G_CreateObject ( gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType ) -{ - gentity_t *object; +gentity_t *G_CreateObject(gentity_t *owner, vec3_t origin, vec3_t angles, int modelIndex, int frame, trType_t trType) { + gentity_t *object; object = G_Spawn(); - if ( object == NULL ) - { + if (object == NULL) { return NULL; } - object->classname = "object";//? + object->classname = "object"; //? object->nextthink = level.time + FRAMETIME; object->e_ThinkFunc = thinkF_G_RunObject; object->s.eType = ET_GENERAL; - object->s.eFlags |= EF_AUTO_SIZE;//CG_Ents will create the mins & max itself based on model bounds + object->s.eFlags |= EF_AUTO_SIZE; // CG_Ents will create the mins & max itself based on model bounds object->s.modelindex = modelIndex; - //FIXME: allow to set a targetname/script_targetname and animation info? + // FIXME: allow to set a targetname/script_targetname and animation info? object->s.frame = object->startFrame = object->endFrame = frame; object->owner = owner; - //object->damage = 100; - //object->splashDamage = 200; - //object->splashRadius = 200; - //object->methodOfDeath = MOD_EXPLOSIVE; - //object->splashMethodOfDeath = MOD_EXPLOSIVE_SPLASH; - object->clipmask = MASK_SOLID;//? - //object->e_TouchFunc = touchF_charge_stick; - - //Give it SOME size for now - VectorSet( object->mins, -4, -4, -4 ); - VectorSet( object->maxs, 4, 4, 4 ); - - //Origin - G_SetOrigin( object, origin ); + // object->damage = 100; + // object->splashDamage = 200; + // object->splashRadius = 200; + // object->methodOfDeath = MOD_EXPLOSIVE; + // object->splashMethodOfDeath = MOD_EXPLOSIVE_SPLASH; + object->clipmask = MASK_SOLID; //? + // object->e_TouchFunc = touchF_charge_stick; + + // Give it SOME size for now + VectorSet(object->mins, -4, -4, -4); + VectorSet(object->maxs, 4, 4, 4); + + // Origin + G_SetOrigin(object, origin); object->s.pos.trType = trType; - VectorCopy( origin, object->s.pos.trBase ); - //Velocity - VectorClear( object->s.pos.trDelta ); + VectorCopy(origin, object->s.pos.trBase); + // Velocity + VectorClear(object->s.pos.trDelta); object->s.pos.trTime = level.time; - //VectorScale( dir, 300, object->s.pos.trDelta ); - //object->s.pos.trTime = level.time; - - //Angles - VectorCopy( angles, object->s.angles ); - VectorCopy( object->s.angles, object->s.apos.trBase ); - //Angular Velocity - VectorClear( object->s.apos.trDelta ); + // VectorScale( dir, 300, object->s.pos.trDelta ); + // object->s.pos.trTime = level.time; + + // Angles + VectorCopy(angles, object->s.angles); + VectorCopy(object->s.angles, object->s.apos.trBase); + // Angular Velocity + VectorClear(object->s.apos.trDelta); object->s.apos.trTime = level.time; - //VectorSet( object->s.apos.trDelta, 300, 0, 0 ); - //object->s.apos.trTime = level.time; + // VectorSet( object->s.apos.trDelta, 300, 0, 0 ); + // object->s.apos.trTime = level.time; - gi.linkentity( object ); + gi.linkentity(object); return object; } diff --git a/codeJK2/game/g_objectives.cpp b/codeJK2/game/g_objectives.cpp index c5291543c9..220b0605d7 100644 --- a/codeJK2/game/g_objectives.cpp +++ b/codeJK2/game/g_objectives.cpp @@ -22,34 +22,29 @@ along with this program; if not, see . #include "g_headers.h" -//g_objectives.cpp -//reads in ext_data\objectives.dat to objectives[] +// g_objectives.cpp +// reads in ext_data\objectives.dat to objectives[] #include "g_local.h" #include "g_items.h" -#define G_OBJECTIVES_CPP +#define G_OBJECTIVES_CPP #include "objectives.h" #include "../code/qcommon/ojk_saved_game_helper.h" -qboolean missionInfo_Updated; - +qboolean missionInfo_Updated; /* ============ OBJ_SetPendingObjectives ============ */ -void OBJ_SetPendingObjectives(gentity_t *ent) -{ +void OBJ_SetPendingObjectives(gentity_t *ent) { int i; - for (i=0;iclient->sess.mission_objectives[i].status == OBJECTIVE_STAT_PENDING) && - (ent->client->sess.mission_objectives[i].display)) - { + for (i = 0; i < MAX_OBJECTIVES; ++i) { + if ((ent->client->sess.mission_objectives[i].status == OBJECTIVE_STAT_PENDING) && (ent->client->sess.mission_objectives[i].display)) { ent->client->sess.mission_objectives[i].status = OBJECTIVE_STAT_FAILED; } } @@ -60,29 +55,23 @@ void OBJ_SetPendingObjectives(gentity_t *ent) OBJ_SaveMissionObjectives ============ */ -void OBJ_SaveMissionObjectives( gclient_t *client ) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.write_chunk( - INT_ID('O', 'B', 'J', 'T'), - client->sess.mission_objectives); -} +void OBJ_SaveMissionObjectives(gclient_t *client) { + ojk::SavedGameHelper saved_game(::gi.saved_game); + saved_game.write_chunk(INT_ID('O', 'B', 'J', 'T'), client->sess.mission_objectives); +} /* ============ OBJ_SaveObjectiveData ============ */ -void OBJ_SaveObjectiveData(void) -{ +void OBJ_SaveObjectiveData(void) { gclient_t *client; client = &level.clients[0]; - OBJ_SaveMissionObjectives( client ); + OBJ_SaveMissionObjectives(client); } /* @@ -90,27 +79,21 @@ void OBJ_SaveObjectiveData(void) OBJ_LoadMissionObjectives ============ */ -void OBJ_LoadMissionObjectives( gclient_t *client ) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - saved_game.read_chunk( - INT_ID('O', 'B', 'J', 'T'), - client->sess.mission_objectives); -} +void OBJ_LoadMissionObjectives(gclient_t *client) { + ojk::SavedGameHelper saved_game(::gi.saved_game); + saved_game.read_chunk(INT_ID('O', 'B', 'J', 'T'), client->sess.mission_objectives); +} /* ============ OBJ_LoadObjectiveData ============ */ -void OBJ_LoadObjectiveData(void) -{ +void OBJ_LoadObjectiveData(void) { gclient_t *client; client = &level.clients[0]; - OBJ_LoadMissionObjectives( client ); + OBJ_LoadMissionObjectives(client); } diff --git a/codeJK2/game/g_ref.cpp b/codeJK2/game/g_ref.cpp index f54a2c9d2b..9a541aa378 100644 --- a/codeJK2/game/g_ref.cpp +++ b/codeJK2/game/g_ref.cpp @@ -27,20 +27,19 @@ along with this program; if not, see . #include "g_functions.h" #include "g_nav.h" -#define TAG_GENERIC_NAME "__WORLD__" //If a designer chooses this name, cut a finger off as an example to the others +#define TAG_GENERIC_NAME "__WORLD__" // If a designer chooses this name, cut a finger off as an example to the others -typedef std::vector < reference_tag_t * > refTag_v; -typedef std::map < std::string, reference_tag_t * > refTag_m; +typedef std::vector refTag_v; +typedef std::map refTag_m; -typedef struct tagOwner_s -{ - refTag_v tags; - refTag_m tagMap; +typedef struct tagOwner_s { + refTag_v tags; + refTag_m tagMap; } tagOwner_t; -typedef std::map < std::string, tagOwner_t * > refTagOwner_m; +typedef std::map refTagOwner_m; -refTagOwner_m refTagOwnerMap; +refTagOwner_m refTagOwnerMap; /* ------------------------- @@ -48,19 +47,15 @@ TAG_ShowTags ------------------------- */ -void TAG_ShowTags( int flags ) -{ - refTagOwner_m::iterator rtoi; - - STL_ITERATE( rtoi, refTagOwnerMap ) - { - refTag_v::iterator rti; - STL_ITERATE( rti, (((*rtoi).second)->tags) ) - { - if ( (*rti)->flags & RTF_NAVGOAL ) - { - if ( gi.inPVS( g_entities[0].currentOrigin, (*rti)->origin ) ) - CG_DrawNode( (*rti)->origin, NODE_NAVGOAL ); +void TAG_ShowTags(int flags) { + refTagOwner_m::iterator rtoi; + + STL_ITERATE(rtoi, refTagOwnerMap) { + refTag_v::iterator rti; + STL_ITERATE(rti, (((*rtoi).second)->tags)) { + if ((*rti)->flags & RTF_NAVGOAL) { + if (gi.inPVS(g_entities[0].currentOrigin, (*rti)->origin)) + CG_DrawNode((*rti)->origin, NODE_NAVGOAL); } } } @@ -72,43 +67,38 @@ TAG_Init ------------------------- */ -void TAG_Init( void ) -{ - refTagOwner_m::iterator rtoi; +void TAG_Init(void) { + refTagOwner_m::iterator rtoi; - //Delete all owners - for ( rtoi = refTagOwnerMap.begin(); rtoi != refTagOwnerMap.end(); ++rtoi ) - { - if ( (*rtoi).second == NULL ) - { - assert( 0 ); //FIXME: This is not good + // Delete all owners + for (rtoi = refTagOwnerMap.begin(); rtoi != refTagOwnerMap.end(); ++rtoi) { + if ((*rtoi).second == NULL) { + assert(0); // FIXME: This is not good continue; } - refTag_v::iterator rti; + refTag_v::iterator rti; - //Delete all tags within the owner's scope - for ( rti = ((*rtoi).second)->tags.begin(); rti != ((*rtoi).second)->tags.end(); ++rti ) - { - if ( (*rti) == NULL ) - { - assert( 0 ); //FIXME: Bad bad + // Delete all tags within the owner's scope + for (rti = ((*rtoi).second)->tags.begin(); rti != ((*rtoi).second)->tags.end(); ++rti) { + if ((*rti) == NULL) { + assert(0); // FIXME: Bad bad continue; } - //Free it + // Free it delete (*rti); } - //Clear the containers + // Clear the containers ((*rtoi).second)->tags.clear(); ((*rtoi).second)->tagMap.clear(); - //Delete the owner + // Delete the owner delete ((*rtoi).second); } - //Clear the container + // Clear the container refTagOwnerMap.clear(); } @@ -118,13 +108,12 @@ TAG_FindOwner ------------------------- */ -tagOwner_t *TAG_FindOwner( const char *owner ) -{ - refTagOwner_m::iterator rtoi; +tagOwner_t *TAG_FindOwner(const char *owner) { + refTagOwner_m::iterator rtoi; - rtoi = refTagOwnerMap.find( owner ); + rtoi = refTagOwnerMap.find(owner); - if ( rtoi == refTagOwnerMap.end() ) + if (rtoi == refTagOwnerMap.end()) return NULL; return (*rtoi).second; @@ -136,41 +125,38 @@ TAG_Find ------------------------- */ -reference_tag_t *TAG_Find( const char *owner, const char *name ) -{ - tagOwner_t *tagOwner; +reference_tag_t *TAG_Find(const char *owner, const char *name) { + tagOwner_t *tagOwner; - tagOwner = VALIDSTRING( owner ) ? TAG_FindOwner( owner ) : TAG_FindOwner( TAG_GENERIC_NAME ); + tagOwner = VALIDSTRING(owner) ? TAG_FindOwner(owner) : TAG_FindOwner(TAG_GENERIC_NAME); - //Not found... - if ( tagOwner == NULL ) - { - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + // Not found... + if (tagOwner == NULL) { + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if ( tagOwner == NULL ) + if (tagOwner == NULL) return NULL; } - refTag_m::iterator rti; + refTag_m::iterator rti; - rti = tagOwner->tagMap.find( name ); + rti = tagOwner->tagMap.find(name); - if ( rti == tagOwner->tagMap.end() ) - { - //Try the generic owner instead - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + if (rti == tagOwner->tagMap.end()) { + // Try the generic owner instead + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if ( tagOwner == NULL ) + if (tagOwner == NULL) return NULL; - char tempName[ MAX_REFNAME ]; + char tempName[MAX_REFNAME]; - Q_strncpyz( (char *) tempName, name, MAX_REFNAME ); - Q_strlwr( (char *) tempName ); //NOTENOTE: For case insensitive searches on a map + Q_strncpyz((char *)tempName, name, MAX_REFNAME); + Q_strlwr((char *)tempName); // NOTENOTE: For case insensitive searches on a map - rti = tagOwner->tagMap.find( tempName ); + rti = tagOwner->tagMap.find(tempName); - if ( rti == tagOwner->tagMap.end() ) + if (rti == tagOwner->tagMap.end()) return NULL; } @@ -183,65 +169,58 @@ TAG_Add ------------------------- */ -reference_tag_t *TAG_Add( const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags ) -{ - reference_tag_t *tag = new reference_tag_t; - VALIDATEP( tag ); +reference_tag_t *TAG_Add(const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags) { + reference_tag_t *tag = new reference_tag_t; + VALIDATEP(tag); - //Copy the information - VectorCopy( origin, tag->origin ); - VectorCopy( angles, tag->angles ); + // Copy the information + VectorCopy(origin, tag->origin); + VectorCopy(angles, tag->angles); tag->radius = radius; - tag->flags = flags; + tag->flags = flags; - if ( VALIDSTRING( name ) == false ) - { - //gi.Error("Nameless ref_tag found at (%i %i %i)", (int)origin[0], (int)origin[1], (int)origin[2]); - gi.Printf(S_COLOR_RED"ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); + if (VALIDSTRING(name) == false) { + // gi.Error("Nameless ref_tag found at (%i %i %i)", (int)origin[0], (int)origin[1], (int)origin[2]); + gi.Printf(S_COLOR_RED "ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); delete tag; return NULL; } - //Copy the name - Q_strncpyz( (char *) tag->name, name, MAX_REFNAME ); - Q_strlwr( (char *) tag->name ); //NOTENOTE: For case insensitive searches on a map + // Copy the name + Q_strncpyz((char *)tag->name, name, MAX_REFNAME); + Q_strlwr((char *)tag->name); // NOTENOTE: For case insensitive searches on a map - //Make sure this tag's name isn't alread in use - if ( TAG_Find( owner, name ) ) - { - gi.Printf(S_COLOR_RED"Duplicate tag name \"%s\"\n", name ); + // Make sure this tag's name isn't alread in use + if (TAG_Find(owner, name)) { + gi.Printf(S_COLOR_RED "Duplicate tag name \"%s\"\n", name); delete tag; return NULL; } - //Attempt to add this to the owner's list - if ( VALIDSTRING( owner ) == false ) - { - //If the owner isn't found, use the generic world name + // Attempt to add this to the owner's list + if (VALIDSTRING(owner) == false) { + // If the owner isn't found, use the generic world name owner = TAG_GENERIC_NAME; } - tagOwner_t *tagOwner = TAG_FindOwner( owner ); + tagOwner_t *tagOwner = TAG_FindOwner(owner); - //If the owner is valid, add this tag to it - if VALID( tagOwner ) - { - tagOwner->tags.insert( tagOwner->tags.end(), tag ); - tagOwner->tagMap[ (char*) &tag->name ] = tag; - } - else - { - //Create a new owner list - tagOwner_t *tagOwner = new tagOwner_t; + // If the owner is valid, add this tag to it + if VALID (tagOwner) { + tagOwner->tags.insert(tagOwner->tags.end(), tag); + tagOwner->tagMap[(char *)&tag->name] = tag; + } else { + // Create a new owner list + tagOwner_t *tagOwner = new tagOwner_t; - VALIDATEP( tagOwner ); + VALIDATEP(tagOwner); - //Insert the information - tagOwner->tags.insert( tagOwner->tags.end(), tag ); - tagOwner->tagMap[ (char *) tag->name ] = tag; + // Insert the information + tagOwner->tags.insert(tagOwner->tags.end(), tag); + tagOwner->tagMap[(char *)tag->name] = tag; - //Map it - refTagOwnerMap[ owner ] = tagOwner; + // Map it + refTagOwnerMap[owner] = tagOwner; } return tag; @@ -253,19 +232,17 @@ TAG_GetOrigin ------------------------- */ -int TAG_GetOrigin( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { VectorClear(origin); return false; } - VALIDATEB( tag ); + VALIDATEB(tag); - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return true; } @@ -277,16 +254,14 @@ Had to get rid of that damn assert for dev ------------------------- */ -int TAG_GetOrigin2( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin2(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if( tag == NULL ) - { + if (tag == NULL) { return qfalse; } - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return qtrue; } @@ -296,13 +271,12 @@ TAG_GetAngles ------------------------- */ -int TAG_GetAngles( const char *owner, const char *name, vec3_t angles ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetAngles(const char *owner, const char *name, vec3_t angles) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); - VectorCopy( tag->angles, angles ); + VectorCopy(tag->angles, angles); return true; } @@ -313,11 +287,10 @@ TAG_GetRadius ------------------------- */ -int TAG_GetRadius( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetRadius(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); return tag->radius; } @@ -328,11 +301,10 @@ TAG_GetFlags ------------------------- */ -int TAG_GetFlags( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetFlags(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - VALIDATEB( tag ); + VALIDATEB(tag); return tag->flags; } @@ -371,47 +343,38 @@ ownername - the owner of this tag target - use to point the tag at something for angles */ -void ref_link ( gentity_t *ent ) -{ - if ( ent->target ) - { - //TODO: Find the target and set our angles to that direction - gentity_t *target = G_Find( NULL, FOFS(targetname), ent->target ); - vec3_t dir; - - if ( target ) - { - //Find the direction to the target - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); - - //FIXME: Does pitch get flipped? - } - else - { - gi.Printf( S_COLOR_RED"ERROR: ref_tag (%s) has invalid target (%s)\n", ent->targetname, ent->target ); +void ref_link(gentity_t *ent) { + if (ent->target) { + // TODO: Find the target and set our angles to that direction + gentity_t *target = G_Find(NULL, FOFS(targetname), ent->target); + vec3_t dir; + + if (target) { + // Find the direction to the target + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); + + // FIXME: Does pitch get flipped? + } else { + gi.Printf(S_COLOR_RED "ERROR: ref_tag (%s) has invalid target (%s)\n", ent->targetname, ent->target); } } - //Add the tag - TAG_Add( ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0 ); + // Add the tag + TAG_Add(ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0); - //Delete immediately, cannot be refered to as an entity again - //NOTE: this means if you wanted to link them in a chain for, say, a path, you can't - G_FreeEntity( ent ); + // Delete immediately, cannot be refered to as an entity again + // NOTE: this means if you wanted to link them in a chain for, say, a path, you can't + G_FreeEntity(ent); } -void SP_reference_tag ( gentity_t *ent ) -{ - if ( ent->target ) - { - //Init cannot occur until all entities have been spawned +void SP_reference_tag(gentity_t *ent) { + if (ent->target) { + // Init cannot occur until all entities have been spawned ent->e_ThinkFunc = thinkF_ref_link; ent->nextthink = level.time + START_TIME_LINK_ENTS; - } - else - { - ref_link( ent ); + } else { + ref_link(ent); } } \ No newline at end of file diff --git a/codeJK2/game/g_roff.cpp b/codeJK2/game/g_roff.cpp index b1c9539e26..14993234e0 100644 --- a/codeJK2/game/g_roff.cpp +++ b/codeJK2/game/g_roff.cpp @@ -28,13 +28,12 @@ along with this program; if not, see . #include "../code/qcommon/ojk_saved_game_helper.h" // The list of precached ROFFs -roff_list_t roffs[MAX_ROFFS]; -int num_roffs = 0; +roff_list_t roffs[MAX_ROFFS]; +int num_roffs = 0; -extern void Q3_TaskIDComplete( gentity_t *ent, taskID_t taskType ); +extern void Q3_TaskIDComplete(gentity_t *ent, taskID_t taskType); -void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) -{ +void G_RoffNotetrackCallback(gentity_t *cent, const char *notetrack) { int i = 0, r = 0, r2 = 0, objectID = 0, anglesGathered = 0, posoffsetGathered = 0; char type[256]; char argument[512]; @@ -45,32 +44,27 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) int addlArgs = 0; vec3_t parsedAngles, parsedOffset, useAngles, useOrigin, forward, right, up; - if (!cent || !notetrack) - { + if (!cent || !notetrack) { return; } - //notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; + // notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (notetrack[i] != ' ') - { //didn't pass in a valid notetrack type, or forgot the argument for it + if (notetrack[i] != ' ') { // didn't pass in a valid notetrack type, or forgot the argument for it return; } i++; - while (notetrack[i] && notetrack[i] != ' ') - { - if (notetrack[i] != '\n' && notetrack[i] != '\r') - { //don't read line ends for an argument + while (notetrack[i] && notetrack[i] != ' ') { + if (notetrack[i] != '\n' && notetrack[i] != '\r') { // don't read line ends for an argument argument[r] = notetrack[i]; r++; } @@ -78,19 +72,16 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) } argument[r] = '\0'; - if (!r) - { + if (!r) { return; } - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -98,29 +89,24 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "effect") == 0) - { - if (!addlArgs) - { + if (strcmp(type, "effect") == 0) { + if (!addlArgs) { VectorClear(parsedOffset); goto defaultoffsetposition; } i = 0; - while (posoffsetGathered < 3) - { + while (posoffsetGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') - { + while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') { t[r] = addlArg[i]; r++; i++; } t[r] = '\0'; i++; - if (!r) - { //failure.. + if (!r) { // failure.. VectorClear(parsedOffset); i = 0; goto defaultoffsetposition; @@ -129,41 +115,35 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) posoffsetGathered++; } - if (posoffsetGathered < 3) - { + if (posoffsetGathered < 3) { sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); goto functionend; } i--; - if (addlArg[i] != ' ') - { + if (addlArg[i] != ' ') { addlArgs = 0; } -defaultoffsetposition: + defaultoffsetposition: r = 0; - if (argument[r] == '/') - { + if (argument[r] == '/') { r++; } - while (argument[r] && argument[r] != '/') - { + while (argument[r] && argument[r] != '/') { teststr[r2] = argument[r]; r2++; r++; } teststr[r2] = '\0'; - if (r2 && strstr(teststr, "effects")) - { //get rid of the leading "effects" since it's auto-inserted + if (r2 && strstr(teststr, "effects")) { // get rid of the leading "effects" since it's auto-inserted r++; r2 = 0; - while (argument[r]) - { + while (argument[r]) { teststr[r2] = argument[r]; r2++; r++; @@ -176,16 +156,12 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) objectID = G_EffectIndex(argument); r = 0; - if (objectID) - { - if (addlArgs) - { //if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE + if (objectID) { + if (addlArgs) { // if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE i++; - while (anglesGathered < 3) - { + while (anglesGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '-') - { + while (addlArg[i] && addlArg[i] != '-') { t[r] = addlArg[i]; r++; i++; @@ -193,8 +169,7 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) t[r] = '\0'; i++; - if (!r) - { //failed to get a new part of the vector + if (!r) { // failed to get a new part of the vector anglesGathered = 0; break; } @@ -203,17 +178,12 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) anglesGathered++; } - if (anglesGathered) - { + if (anglesGathered) { VectorCopy(parsedAngles, useAngles); - } - else - { //failed to parse angles from the extra argument provided.. + } else { // failed to parse angles from the extra argument provided.. VectorCopy(cent->s.apos.trBase, useAngles); } - } - else - { //if no constant angles, play in direction entity is facing + } else { // if no constant angles, play in direction entity is facing VectorCopy(cent->s.apos.trBase, useAngles); } @@ -221,38 +191,32 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) VectorCopy(cent->s.pos.trBase, useOrigin); - //forward - useOrigin[0] += forward[0]*parsedOffset[0]; - useOrigin[1] += forward[1]*parsedOffset[0]; - useOrigin[2] += forward[2]*parsedOffset[0]; + // forward + useOrigin[0] += forward[0] * parsedOffset[0]; + useOrigin[1] += forward[1] * parsedOffset[0]; + useOrigin[2] += forward[2] * parsedOffset[0]; - //right - useOrigin[0] += right[0]*parsedOffset[1]; - useOrigin[1] += right[1]*parsedOffset[1]; - useOrigin[2] += right[2]*parsedOffset[1]; + // right + useOrigin[0] += right[0] * parsedOffset[1]; + useOrigin[1] += right[1] * parsedOffset[1]; + useOrigin[2] += right[2] * parsedOffset[1]; - //up - useOrigin[0] += up[0]*parsedOffset[2]; - useOrigin[1] += up[1]*parsedOffset[2]; - useOrigin[2] += up[2]*parsedOffset[2]; + // up + useOrigin[0] += up[0] * parsedOffset[2]; + useOrigin[1] += up[1] * parsedOffset[2]; + useOrigin[2] += up[2] * parsedOffset[2]; G_PlayEffect(objectID, useOrigin, useAngles); } - } - else if (strcmp(type, "sound") == 0) - { + } else if (strcmp(type, "sound") == 0) { objectID = G_SoundIndex(argument); cgi_S_StartSound(cent->s.pos.trBase, cent->s.number, CHAN_BODY, objectID); } - //else if ... - else - { - if (type[0]) - { + // else if ... + else { + if (type[0]) { Com_Printf("Warning: \"%s\" is an invalid ROFF notetrack function\n", type); - } - else - { + } else { Com_Printf("Warning: Notetrack is missing function and/or arguments\n"); } } @@ -264,16 +228,13 @@ void G_RoffNotetrackCallback( gentity_t *cent, const char *notetrack) return; } -qboolean G_ValidRoff( roff_hdr2_t *header ) -{ - if ( !strncmp( header->mHeader, "ROFF", 4 )) - { - if ( LittleLong(header->mVersion) == ROFF_VERSION2 && LittleLong(header->mCount) > 0 ) - { +qboolean G_ValidRoff(roff_hdr2_t *header) { + if (!strncmp(header->mHeader, "ROFF", 4)) { + if (LittleLong(header->mVersion) == ROFF_VERSION2 && LittleLong(header->mCount) > 0) { return qtrue; - } - else if ( LittleLong(header->mVersion) == ROFF_VERSION && LittleFloat(((roff_hdr_t*)header)->mCount) > 0.0f ) - { // version 1 defines the count as a float, so we best do the count check as a float or we'll get bogus results + } else if (LittleLong(header->mVersion) == ROFF_VERSION && + LittleFloat(((roff_hdr_t *)header)->mCount) > + 0.0f) { // version 1 defines the count as a float, so we best do the count check as a float or we'll get bogus results return qtrue; } } @@ -281,36 +242,32 @@ qboolean G_ValidRoff( roff_hdr2_t *header ) return qfalse; } -qboolean G_InitRoff( char *file, unsigned char *data ) -{ +qboolean G_InitRoff(char *file, unsigned char *data) { roff_hdr_t *header = (roff_hdr_t *)data; - int count; + int count; int i; - roffs[num_roffs].fileName = G_NewString( file ); + roffs[num_roffs].fileName = G_NewString(file); - if ( LittleLong(header->mVersion) == ROFF_VERSION ) - { + if (LittleLong(header->mVersion) == ROFF_VERSION) { count = (int)LittleFloat(header->mCount); // We are Old School(tm) - roffs[num_roffs].data = (void *) G_Alloc( count * sizeof( move_rotate_t ) ); - move_rotate_t *mem = (move_rotate_t *)roffs[num_roffs].data; + roffs[num_roffs].data = (void *)G_Alloc(count * sizeof(move_rotate_t)); + move_rotate_t *mem = (move_rotate_t *)roffs[num_roffs].data; roffs[num_roffs].mFrameTime = 100; // old school ones have a hard-coded frame time roffs[num_roffs].mLerp = 10; - if ( mem ) - { + if (mem) { // The allocation worked, so stash this stuff off so we can reference the data later if needed - roffs[num_roffs].frames = count; + roffs[num_roffs].frames = count; // Step past the header to get to the goods - move_rotate_t *roff_data = ( move_rotate_t *)&header[1]; + move_rotate_t *roff_data = (move_rotate_t *)&header[1]; // Copy all of the goods into our ROFF cache - for ( i = 0; i < count; i++, roff_data++, mem++ ) - { + for (i = 0; i < count; i++, roff_data++, mem++) { // Copy just the delta position and orientation which can be applied to anything at a later point #ifdef Q3_BIG_ENDIAN mem->origin_delta[0] = LittleFloat(roff_data->origin_delta[0]); @@ -320,40 +277,34 @@ qboolean G_InitRoff( char *file, unsigned char *data ) mem->rotate_delta[1] = LittleFloat(roff_data->rotate_delta[1]); mem->rotate_delta[2] = LittleFloat(roff_data->rotate_delta[2]); #else - VectorCopy( roff_data->origin_delta, mem->origin_delta ); - VectorCopy( roff_data->rotate_delta, mem->rotate_delta ); + VectorCopy(roff_data->origin_delta, mem->origin_delta); + VectorCopy(roff_data->rotate_delta, mem->rotate_delta); #endif } - } - else - { + } else { return qfalse; } - } - else - { + } else { // Version 2.0, heck yeah! roff_hdr2_t *hdr = (roff_hdr2_t *)data; count = LittleLong(hdr->mCount); - roffs[num_roffs].frames = count; - roffs[num_roffs].data = (void *) G_Alloc( count * sizeof( move_rotate2_t )); - move_rotate2_t *mem = (move_rotate2_t *)roffs[num_roffs].data; + roffs[num_roffs].frames = count; + roffs[num_roffs].data = (void *)G_Alloc(count * sizeof(move_rotate2_t)); + move_rotate2_t *mem = (move_rotate2_t *)roffs[num_roffs].data; - if ( mem ) - { - roffs[num_roffs].mFrameTime = LittleLong(hdr->mFrameRate); - roffs[num_roffs].mLerp = 1000 / LittleLong(hdr->mFrameRate); - roffs[num_roffs].mNumNoteTracks = LittleLong(hdr->mNumNotes); + if (mem) { + roffs[num_roffs].mFrameTime = LittleLong(hdr->mFrameRate); + roffs[num_roffs].mLerp = 1000 / LittleLong(hdr->mFrameRate); + roffs[num_roffs].mNumNoteTracks = LittleLong(hdr->mNumNotes); - // Step past the header to get to the goods - move_rotate2_t *roff_data = ( move_rotate2_t *)&hdr[1]; + // Step past the header to get to the goods + move_rotate2_t *roff_data = (move_rotate2_t *)&hdr[1]; - roffs[num_roffs].type = 2; //rww - any reason this wasn't being set already? + roffs[num_roffs].type = 2; // rww - any reason this wasn't being set already? // Copy all of the goods into our ROFF cache - for ( i = 0; i < count; i++ ) - { + for (i = 0; i < count; i++) { #ifdef Q3_BIG_ENDIAN mem[i].origin_delta[0] = LittleFloat(roff_data[i].origin_delta[0]); mem[i].origin_delta[1] = LittleFloat(roff_data[i].origin_delta[1]); @@ -362,24 +313,22 @@ qboolean G_InitRoff( char *file, unsigned char *data ) mem[i].rotate_delta[1] = LittleFloat(roff_data[i].rotate_delta[1]); mem[i].rotate_delta[2] = LittleFloat(roff_data[i].rotate_delta[2]); #else - VectorCopy( roff_data[i].origin_delta, mem[i].origin_delta ); - VectorCopy( roff_data[i].rotate_delta, mem[i].rotate_delta ); + VectorCopy(roff_data[i].origin_delta, mem[i].origin_delta); + VectorCopy(roff_data[i].rotate_delta, mem[i].rotate_delta); #endif mem[i].mStartNote = LittleLong(roff_data[i].mStartNote); mem[i].mNumNotes = LittleLong(roff_data[i].mNumNotes); } - if ( LittleLong(hdr->mNumNotes) ) - { - int size; - char *ptr, *start; + if (LittleLong(hdr->mNumNotes)) { + int size; + char *ptr, *start; ptr = start = (char *)&roff_data[i]; size = 0; - for( i = 0; i < LittleLong(hdr->mNumNotes); i++ ) - { + for (i = 0; i < LittleLong(hdr->mNumNotes); i++) { size += strlen(ptr) + 1; ptr += strlen(ptr) + 1; } @@ -389,15 +338,12 @@ qboolean G_InitRoff( char *file, unsigned char *data ) ptr = roffs[num_roffs].mNoteTrackIndexes[0] = new char[size]; memcpy(roffs[num_roffs].mNoteTrackIndexes[0], start, size); - for( i = 1; i < LittleLong(hdr->mNumNotes); i++ ) - { + for (i = 1; i < LittleLong(hdr->mNumNotes); i++) { ptr += strlen(ptr) + 1; roffs[num_roffs].mNoteTrackIndexes[i] = ptr; } } - } - else - { + } else { return qfalse; } } @@ -413,42 +359,37 @@ qboolean G_InitRoff( char *file, unsigned char *data ) // ID to the cached file. //------------------------------------------------------- -int G_LoadRoff( const char *fileName ) -{ - char file[MAX_QPATH]; - byte *data; - int len, i, roff_id = 0; +int G_LoadRoff(const char *fileName) { + char file[MAX_QPATH]; + byte *data; + int len, i, roff_id = 0; // Before even bothering with all of this, make sure we have a place to store it. - if ( num_roffs >= MAX_ROFFS ) - { - Com_Printf( S_COLOR_RED"MAX_ROFFS count exceeded. Skipping load of .ROF '%s'\n", fileName ); + if (num_roffs >= MAX_ROFFS) { + Com_Printf(S_COLOR_RED "MAX_ROFFS count exceeded. Skipping load of .ROF '%s'\n", fileName); return roff_id; } // The actual path - sprintf( file, "%s/%s.rof", Q3_SCRIPT_DIR, fileName ); + sprintf(file, "%s/%s.rof", Q3_SCRIPT_DIR, fileName); // See if I'm already precached - for ( i = 0; i < num_roffs; i++ ) - { - if ( Q_stricmp( file, roffs[i].fileName ) == 0 ) - { + for (i = 0; i < num_roffs; i++) { + if (Q_stricmp(file, roffs[i].fileName) == 0) { // Good, just return me...avoid zero index return i + 1; } } #ifdef _DEBUG - Com_Printf( S_COLOR_GREEN"Caching ROF: '%s'\n", file ); + Com_Printf(S_COLOR_GREEN "Caching ROF: '%s'\n", file); #endif // Read the file in one fell swoop - len = gi.FS_ReadFile( file, (void**) &data); + len = gi.FS_ReadFile(file, (void **)&data); - if ( len <= 0 ) - { - Com_Printf( S_COLOR_RED"Could not open .ROF file '%s'\n", fileName ); + if (len <= 0) { + Com_Printf(S_COLOR_RED "Could not open .ROF file '%s'\n", fileName); return roff_id; } @@ -456,238 +397,191 @@ int G_LoadRoff( const char *fileName ) roff_hdr2_t *header = (roff_hdr2_t *)data; // ..and make sure it's reasonably valid - if ( !G_ValidRoff( header )) - { - Com_Printf( S_COLOR_RED"Invalid roff format '%s'\n", fileName ); - } - else - { - G_InitRoff( file, data ); + if (!G_ValidRoff(header)) { + Com_Printf(S_COLOR_RED "Invalid roff format '%s'\n", fileName); + } else { + G_InitRoff(file, data); // Done loading this roff, so save off an id to it..increment first to avoid zero index roff_id = ++num_roffs; } - gi.FS_FreeFile( data ); + gi.FS_FreeFile(data); return roff_id; } - //------------------------------------------------------- // G_Roff // // Handles applying the roff data to the specified ent //------------------------------------------------------- -void G_Roff( gentity_t *ent ) -{ - if ( !ent->next_roff_time ) - { +void G_Roff(gentity_t *ent) { + if (!ent->next_roff_time) { return; } - - if ( ent->next_roff_time > level.time ) - {// either I don't think or it's just not time to have me think yet + + if (ent->next_roff_time > level.time) { // either I don't think or it's just not time to have me think yet return; } - const int roff_id = G_LoadRoff( ent->roff ); + const int roff_id = G_LoadRoff(ent->roff); - if ( !roff_id ) - { // Couldn't cache this rof + if (!roff_id) { // Couldn't cache this rof return; } // The ID is one higher than the array index - const roff_list_t * roff = &roffs[ roff_id - 1 ]; - vec3_t org, ang; - - if ( roff->type == 2 ) - { - move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ ent->roff_ctr ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); - if (data->mStartNote != -1 || data->mNumNotes) - { + const roff_list_t *roff = &roffs[roff_id - 1]; + vec3_t org, ang; + + if (roff->type == 2) { + move_rotate2_t *data = &((move_rotate2_t *)roff->data)[ent->roff_ctr]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); + if (data->mStartNote != -1 || data->mNumNotes) { G_RoffNotetrackCallback(ent, roffs[roff_id - 1].mNoteTrackIndexes[data->mStartNote]); } - } - else - { - move_rotate_t *data = &((move_rotate_t *)roff->data)[ ent->roff_ctr ]; - VectorCopy( data->origin_delta, org ); - VectorCopy( data->rotate_delta, ang ); + } else { + move_rotate_t *data = &((move_rotate_t *)roff->data)[ent->roff_ctr]; + VectorCopy(data->origin_delta, org); + VectorCopy(data->rotate_delta, ang); } #ifdef _DEBUG - if ( g_developer->integer ) - { - Com_Printf( S_COLOR_GREEN"ROFF dat: num: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", - ent->roff_ctr, - org[0], org[1], org[2], - ang[0], ang[1], ang[2] ); + if (g_developer->integer) { + Com_Printf(S_COLOR_GREEN "ROFF dat: num: %d o:<%.2f %.2f %.2f> a:<%.2f %.2f %.2f>\n", ent->roff_ctr, org[0], org[1], org[2], ang[0], ang[1], ang[2]); } #endif - if ( ent->client ) - { + if (ent->client) { // Set up the angle interpolation //------------------------------------- - VectorAdd( ent->s.apos.trBase, ang, ent->s.apos.trBase ); + VectorAdd(ent->s.apos.trBase, ang, ent->s.apos.trBase); ent->s.apos.trTime = level.time; ent->s.apos.trType = TR_INTERPOLATE; // Store what the next apos->trBase should be - VectorCopy( ent->s.apos.trBase, ent->client->ps.viewangles ); - VectorCopy( ent->s.apos.trBase, ent->currentAngles ); - VectorCopy( ent->s.apos.trBase, ent->s.angles ); - if ( ent->NPC ) - { - //ent->NPC->desiredPitch = ent->s.apos.trBase[PITCH]; + VectorCopy(ent->s.apos.trBase, ent->client->ps.viewangles); + VectorCopy(ent->s.apos.trBase, ent->currentAngles); + VectorCopy(ent->s.apos.trBase, ent->s.angles); + if (ent->NPC) { + // ent->NPC->desiredPitch = ent->s.apos.trBase[PITCH]; ent->NPC->desiredYaw = ent->s.apos.trBase[YAW]; } // Set up the origin interpolation //------------------------------------- - VectorAdd( ent->s.pos.trBase, org, ent->s.pos.trBase ); + VectorAdd(ent->s.pos.trBase, org, ent->s.pos.trBase); ent->s.pos.trTime = level.time; ent->s.pos.trType = TR_INTERPOLATE; // Store what the next pos->trBase should be - VectorCopy( ent->s.pos.trBase, ent->client->ps.origin ); - VectorCopy( ent->s.pos.trBase, ent->currentOrigin ); - //VectorCopy( ent->s.pos.trBase, ent->s.origin ); - } - else - { + VectorCopy(ent->s.pos.trBase, ent->client->ps.origin); + VectorCopy(ent->s.pos.trBase, ent->currentOrigin); + // VectorCopy( ent->s.pos.trBase, ent->s.origin ); + } else { // Set up the angle interpolation //------------------------------------- - VectorScale( ang, roff->mLerp, ent->s.apos.trDelta ); - VectorCopy( ent->pos2, ent->s.apos.trBase ); + VectorScale(ang, roff->mLerp, ent->s.apos.trDelta); + VectorCopy(ent->pos2, ent->s.apos.trBase); ent->s.apos.trTime = level.time; ent->s.apos.trType = TR_LINEAR; // Store what the next apos->trBase should be - VectorAdd( ent->pos2, ang, ent->pos2 ); + VectorAdd(ent->pos2, ang, ent->pos2); // Set up the origin interpolation //------------------------------------- - VectorScale( org, roff->mLerp, ent->s.pos.trDelta ); - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorScale(org, roff->mLerp, ent->s.pos.trDelta); + VectorCopy(ent->pos1, ent->s.pos.trBase); ent->s.pos.trTime = level.time; ent->s.pos.trType = TR_LINEAR; // Store what the next apos->trBase should be - VectorAdd( ent->pos1, org, ent->pos1 ); + VectorAdd(ent->pos1, org, ent->pos1); - //make it true linear... FIXME: sticks around after ROFF is done, but do we really care? + // make it true linear... FIXME: sticks around after ROFF is done, but do we really care? ent->alt_fire = qtrue; - if ( !ent->e_ThinkFunc - && ent->s.eType != ET_MISSILE - && ent->s.eType != ET_ITEM - && ent->s.eType != ET_MOVER ) - {//will never set currentAngles & currentOrigin itself - EvaluateTrajectory( &ent->s.apos, level.time, ent->currentAngles ); - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); + if (!ent->e_ThinkFunc && ent->s.eType != ET_MISSILE && ent->s.eType != ET_ITEM && + ent->s.eType != ET_MOVER) { // will never set currentAngles & currentOrigin itself + EvaluateTrajectory(&ent->s.apos, level.time, ent->currentAngles); + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); } } // See if the ROFF playback is done //------------------------------------- - if ( ++ent->roff_ctr >= roff->frames ) - { + if (++ent->roff_ctr >= roff->frames) { // We are done, so let me think no more, then tell the task that we're done. ent->next_roff_time = 0; // Stop any rotation or movement. - VectorClear( ent->s.pos.trDelta ); - VectorClear( ent->s.apos.trDelta ); + VectorClear(ent->s.pos.trDelta); + VectorClear(ent->s.apos.trDelta); - Q3_TaskIDComplete( ent, TID_MOVE_NAV ); + Q3_TaskIDComplete(ent, TID_MOVE_NAV); return; } // Lock me to a 20hz update rate ent->next_roff_time = level.time + roff->mFrameTime; - assert( roff->mFrameTime >= 50 );//HAS to be at least 50 + assert(roff->mFrameTime >= 50); // HAS to be at least 50 } - //------------------------------------------------------- // G_SaveCachedRoffs // // Really fun savegame stuff //------------------------------------------------------- -void G_SaveCachedRoffs() -{ +void G_SaveCachedRoffs() { int i, len; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // Write out the number of cached ROFFs - saved_game.write_chunk( - INT_ID('R', 'O', 'F', 'F'), - ::num_roffs); + saved_game.write_chunk(INT_ID('R', 'O', 'F', 'F'), ::num_roffs); // Now dump out the cached ROFF file names in order so they can be loaded on the other end - for ( i = 0; i < num_roffs; i++ ) - { + for (i = 0; i < num_roffs; i++) { // Dump out the string length to make things a bit easier on the other end...heh heh. - len = strlen( roffs[i].fileName ) + 1; + len = strlen(roffs[i].fileName) + 1; - saved_game.write_chunk( - INT_ID('S', 'L', 'E', 'N'), - len); + saved_game.write_chunk(INT_ID('S', 'L', 'E', 'N'), len); - saved_game.write_chunk( - INT_ID('R', 'S', 'T', 'R'), - ::roffs[i].fileName, - len); + saved_game.write_chunk(INT_ID('R', 'S', 'T', 'R'), ::roffs[i].fileName, len); } } - //------------------------------------------------------- // G_LoadCachedRoffs // // Really fun loadgame stuff //------------------------------------------------------- -void G_LoadCachedRoffs() -{ - int i, count = 0, len = 0; - char buffer[MAX_QPATH]; +void G_LoadCachedRoffs() { + int i, count = 0, len = 0; + char buffer[MAX_QPATH]; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // Get the count of goodies we need to revive - saved_game.read_chunk( - INT_ID('R', 'O', 'F', 'F'), - count); + saved_game.read_chunk(INT_ID('R', 'O', 'F', 'F'), count); // Now bring 'em back to life - for ( i = 0; i < count; i++ ) - { - saved_game.read_chunk( - INT_ID('S', 'L', 'E', 'N'), - len); - - if (len < 0 || static_cast(len) >= sizeof(buffer)) - { + for (i = 0; i < count; i++) { + saved_game.read_chunk(INT_ID('S', 'L', 'E', 'N'), len); + + if (len < 0 || static_cast(len) >= sizeof(buffer)) { ::G_Error("invalid length for RSTR string in save game: %d bytes\n", len); } - saved_game.read_chunk( - INT_ID('R', 'S', 'T', 'R'), - buffer, - len); + saved_game.read_chunk(INT_ID('R', 'S', 'T', 'R'), buffer, len); - G_LoadRoff( buffer ); + G_LoadRoff(buffer); } } diff --git a/codeJK2/game/g_savegame.cpp b/codeJK2/game/g_savegame.cpp index 672f6de4ba..b67b721319 100644 --- a/codeJK2/game/g_savegame.cpp +++ b/codeJK2/game/g_savegame.cpp @@ -37,86 +37,75 @@ along with this program; if not, see . extern void OBJ_LoadTacticalInfo(void); -extern int Q3_VariableSave( void ); -extern int Q3_VariableLoad( void ); +extern int Q3_VariableSave(void); +extern int Q3_VariableLoad(void); extern void G_LoadSave_WriteMiscData(void); extern void G_LoadSave_ReadMiscData(void); - -static const field_t savefields_gEntity[] = -{ - {strFOFS(client), F_GCLIENT}, - {strFOFS(owner), F_GENTITY}, - {strFOFS(classname), F_STRING}, - {strFOFS(model), F_STRING}, - {strFOFS(model2), F_STRING}, -// {strFOFS(model3), F_STRING}, - MCG - {strFOFS(nextTrain), F_GENTITY}, - {strFOFS(prevTrain), F_GENTITY}, - {strFOFS(message), F_STRING}, - {strFOFS(target), F_STRING}, - {strFOFS(target2), F_STRING}, - {strFOFS(target3), F_STRING}, - {strFOFS(target4), F_STRING}, - {strFOFS(targetname), F_STRING}, - {strFOFS(team), F_STRING}, - {strFOFS(roff), F_STRING}, -// {strFOFS(target_ent), F_GENTITY}, - MCG - {strFOFS(chain), F_GENTITY}, - {strFOFS(enemy), F_GENTITY}, - {strFOFS(activator), F_GENTITY}, - {strFOFS(teamchain), F_GENTITY}, - {strFOFS(teammaster), F_GENTITY}, - {strFOFS(item), F_ITEM}, - {strFOFS(NPC_type), F_STRING}, - {strFOFS(closetarget), F_STRING}, - {strFOFS(opentarget), F_STRING}, - {strFOFS(paintarget), F_STRING}, - {strFOFS(NPC_targetname), F_STRING}, - {strFOFS(NPC_target), F_STRING}, - {strFOFS(ownername), F_STRING}, - {strFOFS(lastEnemy), F_GENTITY}, - {strFOFS(behaviorSet), F_BEHAVIORSET}, - {strFOFS(script_targetname),F_STRING}, - {strFOFS(sequencer), F_NULL}, // CSequencer *sequencer; - {strFOFS(taskManager), F_NULL}, // CTaskManager *taskManager; - {strFOFS(NPC), F_BOOLPTR}, - {strFOFS(soundSet), F_STRING}, - {strFOFS(cameraGroup), F_STRING}, - {strFOFS(parms), F_BOOLPTR}, - {strFOFS(fullName), F_STRING}, -// {strFOFS(timers), F_BOOLPTR}, // handled directly - - {NULL, 0, F_IGNORE} -}; - -static const field_t savefields_gNPC[] = -{ -// {strNPCOFS(pendingEnemy), F_GENTITY}, - {strNPCOFS(touchedByPlayer), F_GENTITY}, - {strNPCOFS(aimingBeam), F_GENTITY}, - {strNPCOFS(eventOwner), F_GENTITY}, - {strNPCOFS(coverTarg), F_GENTITY}, - {strNPCOFS(tempGoal), F_GENTITY}, - {strNPCOFS(goalEntity), F_GENTITY}, - {strNPCOFS(lastGoalEntity), F_GENTITY}, - {strNPCOFS(eventualGoal), F_GENTITY}, - {strNPCOFS(captureGoal), F_GENTITY}, - {strNPCOFS(defendEnt), F_GENTITY}, - {strNPCOFS(greetEnt), F_GENTITY}, - {strNPCOFS(group), F_GROUP}, - - {NULL, 0, F_IGNORE} -}; - -static const field_t savefields_LevelLocals[] = -{ - {strLLOFS(locationHead), F_GENTITY}, - {strLLOFS(alertEvents), F_ALERTEVENT}, - {strLLOFS(groups), F_AIGROUPS}, - {NULL, 0, F_IGNORE} -}; +static const field_t savefields_gEntity[] = {{strFOFS(client), F_GCLIENT}, + {strFOFS(owner), F_GENTITY}, + {strFOFS(classname), F_STRING}, + {strFOFS(model), F_STRING}, + {strFOFS(model2), F_STRING}, + // {strFOFS(model3), F_STRING}, - MCG + {strFOFS(nextTrain), F_GENTITY}, + {strFOFS(prevTrain), F_GENTITY}, + {strFOFS(message), F_STRING}, + {strFOFS(target), F_STRING}, + {strFOFS(target2), F_STRING}, + {strFOFS(target3), F_STRING}, + {strFOFS(target4), F_STRING}, + {strFOFS(targetname), F_STRING}, + {strFOFS(team), F_STRING}, + {strFOFS(roff), F_STRING}, + // {strFOFS(target_ent), F_GENTITY}, - MCG + {strFOFS(chain), F_GENTITY}, + {strFOFS(enemy), F_GENTITY}, + {strFOFS(activator), F_GENTITY}, + {strFOFS(teamchain), F_GENTITY}, + {strFOFS(teammaster), F_GENTITY}, + {strFOFS(item), F_ITEM}, + {strFOFS(NPC_type), F_STRING}, + {strFOFS(closetarget), F_STRING}, + {strFOFS(opentarget), F_STRING}, + {strFOFS(paintarget), F_STRING}, + {strFOFS(NPC_targetname), F_STRING}, + {strFOFS(NPC_target), F_STRING}, + {strFOFS(ownername), F_STRING}, + {strFOFS(lastEnemy), F_GENTITY}, + {strFOFS(behaviorSet), F_BEHAVIORSET}, + {strFOFS(script_targetname), F_STRING}, + {strFOFS(sequencer), F_NULL}, // CSequencer *sequencer; + {strFOFS(taskManager), F_NULL}, // CTaskManager *taskManager; + {strFOFS(NPC), F_BOOLPTR}, + {strFOFS(soundSet), F_STRING}, + {strFOFS(cameraGroup), F_STRING}, + {strFOFS(parms), F_BOOLPTR}, + {strFOFS(fullName), F_STRING}, + // {strFOFS(timers), F_BOOLPTR}, // handled directly + + {NULL, 0, F_IGNORE}}; + +static const field_t savefields_gNPC[] = { + // {strNPCOFS(pendingEnemy), F_GENTITY}, + {strNPCOFS(touchedByPlayer), F_GENTITY}, + {strNPCOFS(aimingBeam), F_GENTITY}, + {strNPCOFS(eventOwner), F_GENTITY}, + {strNPCOFS(coverTarg), F_GENTITY}, + {strNPCOFS(tempGoal), F_GENTITY}, + {strNPCOFS(goalEntity), F_GENTITY}, + {strNPCOFS(lastGoalEntity), F_GENTITY}, + {strNPCOFS(eventualGoal), F_GENTITY}, + {strNPCOFS(captureGoal), F_GENTITY}, + {strNPCOFS(defendEnt), F_GENTITY}, + {strNPCOFS(greetEnt), F_GENTITY}, + {strNPCOFS(group), F_GROUP}, + + {NULL, 0, F_IGNORE}}; + +static const field_t savefields_LevelLocals[] = { + {strLLOFS(locationHead), F_GENTITY}, {strLLOFS(alertEvents), F_ALERTEVENT}, {strLLOFS(groups), F_AIGROUPS}, {NULL, 0, F_IGNORE}}; /* struct gclient_s { @@ -136,61 +125,48 @@ ok renderInfo_t renderInfo; */ // I'll keep a blank one for now in case I need to add anything... // -static const field_t savefields_gClient[] = -{ - {strCLOFS(ps.saberModel), F_STRING}, - {strCLOFS(squadname), F_STRING}, - {strCLOFS(team_leader), F_GENTITY}, - {strCLOFS(leader), F_GENTITY}, - {strCLOFS(follower), F_GENTITY}, - {strCLOFS(formationGoal), F_GENTITY}, - {strCLOFS(clientInfo.customBasicSoundDir),F_STRING}, - {strCLOFS(clientInfo.customCombatSoundDir),F_STRING}, - {strCLOFS(clientInfo.customExtraSoundDir),F_STRING}, - {strCLOFS(clientInfo.customJediSoundDir),F_STRING}, - - {NULL, 0, F_IGNORE} -}; - +static const field_t savefields_gClient[] = {{strCLOFS(ps.saberModel), F_STRING}, + {strCLOFS(squadname), F_STRING}, + {strCLOFS(team_leader), F_GENTITY}, + {strCLOFS(leader), F_GENTITY}, + {strCLOFS(follower), F_GENTITY}, + {strCLOFS(formationGoal), F_GENTITY}, + {strCLOFS(clientInfo.customBasicSoundDir), F_STRING}, + {strCLOFS(clientInfo.customCombatSoundDir), F_STRING}, + {strCLOFS(clientInfo.customExtraSoundDir), F_STRING}, + {strCLOFS(clientInfo.customJediSoundDir), F_STRING}, + + {NULL, 0, F_IGNORE}}; static std::list strList; - /////////// char * ///////////// // // -int GetStringNum(const char *psString) -{ - assert( psString != (char *)0xcdcdcdcd ); +int GetStringNum(const char *psString) { + assert(psString != (char *)0xcdcdcdcd); // NULL ptrs I'll write out as a strlen of -1... // - if (!psString) - { + if (!psString) { return -1; } - strList.push_back( psString ); - return strlen(psString) + 1; // this gives us the chunk length for the reader later + strList.push_back(psString); + return strlen(psString) + 1; // this gives us the chunk length for the reader later } -char *GetStringPtr(int iStrlen, char *psOriginal/*may be NULL*/) -{ - if (iStrlen != -1) - { - static char sString[768]; // arb, inc if nec. +char *GetStringPtr(int iStrlen, char *psOriginal /*may be NULL*/) { + if (iStrlen != -1) { + static char sString[768]; // arb, inc if nec. - memset(sString,0, sizeof(sString)); + memset(sString, 0, sizeof(sString)); - assert(iStrlen+1<=(int)sizeof(sString)); + assert(iStrlen + 1 <= (int)sizeof(sString)); - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('S', 'T', 'R', 'G'), - sString, - iStrlen); + saved_game.read_chunk(INT_ID('S', 'T', 'R', 'G'), sString, iStrlen); // we can't do string recycling with the new g_alloc pool dumping, so just always alloc here... // @@ -203,18 +179,13 @@ char *GetStringPtr(int iStrlen, char *psOriginal/*may be NULL*/) // //////////////////////////////// - - - /////////// gentity_t * //////// // // -intptr_t GetGEntityNum(gentity_t* ent) -{ - assert( ent != (gentity_t *) 0xcdcdcdcd); +intptr_t GetGEntityNum(gentity_t *ent) { + assert(ent != (gentity_t *)0xcdcdcdcd); - if (ent == NULL) - { + if (ent == NULL) { return -1; } @@ -224,17 +195,14 @@ intptr_t GetGEntityNum(gentity_t* ent) // intptr_t iReturnIndex = ent - g_entities; - if (iReturnIndex < 0 || iReturnIndex >= MAX_GENTITIES) - { - iReturnIndex = -1; // will get a NULL ptr on reload + if (iReturnIndex < 0 || iReturnIndex >= MAX_GENTITIES) { + iReturnIndex = -1; // will get a NULL ptr on reload } return iReturnIndex; } -gentity_t *GetGEntityPtr(intptr_t iEntNum) -{ - if (iEntNum == -1) - { +gentity_t *GetGEntityPtr(intptr_t iEntNum) { + if (iEntNum == -1) { return NULL; } assert(iEntNum >= 0); @@ -242,60 +210,48 @@ gentity_t *GetGEntityPtr(intptr_t iEntNum) return (g_entities + iEntNum); } -static intptr_t GetGroupNumber(AIGroupInfo_t *pGroup) -{ - assert( pGroup != (AIGroupInfo_t *) 0xcdcdcdcd); +static intptr_t GetGroupNumber(AIGroupInfo_t *pGroup) { + assert(pGroup != (AIGroupInfo_t *)0xcdcdcdcd); - if (pGroup == NULL) - { + if (pGroup == NULL) { return -1; } int iReturnIndex = pGroup - level.groups; - if (iReturnIndex < 0 || iReturnIndex >= (int)(sizeof(level.groups) / sizeof(level.groups[0])) ) - { - iReturnIndex = -1; // will get a NULL ptr on reload + if (iReturnIndex < 0 || iReturnIndex >= (int)(sizeof(level.groups) / sizeof(level.groups[0]))) { + iReturnIndex = -1; // will get a NULL ptr on reload } return iReturnIndex; } -static AIGroupInfo_t *GetGroupPtr(intptr_t iGroupNum) -{ - if (iGroupNum == -1) - { +static AIGroupInfo_t *GetGroupPtr(intptr_t iGroupNum) { + if (iGroupNum == -1) { return NULL; } assert(iGroupNum >= 0); - assert( iGroupNum < (int)ARRAY_LEN( level.groups ) ); + assert(iGroupNum < (int)ARRAY_LEN(level.groups)); return (level.groups + iGroupNum); } - - /////////// gclient_t * //////// // // -intptr_t GetGClientNum(gclient_t *c) -{ +intptr_t GetGClientNum(gclient_t *c) { assert(c != (gclient_t *)0xcdcdcdcd); - if (c == NULL) - { + if (c == NULL) { return -1; } return (c - level.clients); } -gclient_t *GetGClientPtr(intptr_t c) -{ - if (c == -1) - { +gclient_t *GetGClientPtr(intptr_t c) { + if (c == -1) { return NULL; } - if (c == -2) - { - return (gclient_t *) -2; // preserve this value so that I know to load in one of Mike's private NPC clients later + if (c == -2) { + return (gclient_t *)-2; // preserve this value so that I know to load in one of Mike's private NPC clients later } assert(c >= 0); @@ -306,26 +262,21 @@ gclient_t *GetGClientPtr(intptr_t c) // //////////////////////////////// - /////////// gitem_t * ////////// // // -int GetGItemNum (gitem_t *pItem) -{ - assert(pItem != (gitem_t*) 0xcdcdcdcd); +int GetGItemNum(gitem_t *pItem) { + assert(pItem != (gitem_t *)0xcdcdcdcd); - if (pItem == NULL) - { + if (pItem == NULL) { return -1; } return pItem - bg_itemlist; } -gitem_t *GetGItemPtr(int iItem) -{ - if (iItem == -1) - { +gitem_t *GetGItemPtr(int iItem) { + if (iItem == -1) { return NULL; } @@ -337,13 +288,10 @@ gitem_t *GetGItemPtr(int iItem) // //////////////////////////////// - -void EnumerateField(const field_t *pField, byte *pbBase) -{ +void EnumerateField(const field_t *pField, byte *pbBase) { void *pv = (void *)(pbBase + pField->iOffset); - switch (pField->eFieldType) - { + switch (pField->eFieldType) { case F_STRING: *(intptr_t *)pv = GetStringNum(*(char **)pv); break; @@ -356,79 +304,67 @@ void EnumerateField(const field_t *pField, byte *pbBase) *(intptr_t *)pv = GetGroupNumber(*(AIGroupInfo_t **)pv); break; - case F_GCLIENT: - { + case F_GCLIENT: { // unfortunately, I now need to see if this is a 'real' client (and therefore resolve to an enum), or // whether it's one of Mike G's private clients that needs saving here (thanks Mike...) // - gentity_t *ent = (gentity_t *) pbBase; + gentity_t *ent = (gentity_t *)pbBase; - if (ent->NPC == NULL) - { + if (ent->NPC == NULL) { // regular client... // *(intptr_t *)pv = GetGClientNum(*(gclient_t **)pv); break; - } - else - { + } else { // this must be one of Mike's, so mark it as special... // - *(intptr_t *)pv = -2; // yeuch, but distinguishes it from a valid 0 index, or -1 for client==NULL + *(intptr_t *)pv = -2; // yeuch, but distinguishes it from a valid 0 index, or -1 for client==NULL } - } - break; + } break; case F_ITEM: *(intptr_t *)pv = GetGItemNum(*(gitem_t **)pv); break; - case F_BEHAVIORSET: - { - const char **p = (const char **) pv; - for (int i=0; i -static void EnumerateFields( - const field_t* pFields, - T* src_instance, - unsigned int ulChid) -{ +template static void EnumerateFields(const field_t *pFields, T *src_instance, unsigned int ulChid) { strList.clear(); - byte* pbData = reinterpret_cast( - src_instance); + byte *pbData = reinterpret_cast(src_instance); // enumerate all the fields... // - if (pFields) - { - for (auto pField = pFields; pField->psName; ++pField) - { + if (pFields) { + for (auto pField = pFields; pField->psName; ++pField) { assert(pField->iOffset < sizeof(T)); ::EnumerateField(pField, pbData); } } - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); // save out raw data... // saved_game.reset_buffer(); - src_instance->sg_export( - saved_game); + src_instance->sg_export(saved_game); - saved_game.write_chunk( - ulChid); + saved_game.write_chunk(ulChid); // save out any associated strings.. // - for (const auto& it : strList) - { - saved_game.write_chunk( - INT_ID('S', 'T', 'R', 'G'), - it.c_str(), - static_cast(it.length() + 1)); + for (const auto &it : strList) { + saved_game.write_chunk(INT_ID('S', 'T', 'R', 'G'), it.c_str(), static_cast(it.length() + 1)); } } -static void EvaluateField(const field_t *pField, byte *pbBase, byte *pbOriginalRefData/* may be NULL*/) -{ - void *pv = (void *)(pbBase + pField->iOffset); +static void EvaluateField(const field_t *pField, byte *pbBase, byte *pbOriginalRefData /* may be NULL*/) { + void *pv = (void *)(pbBase + pField->iOffset); void *pvOriginal = (void *)(pbOriginalRefData + pField->iOffset); - switch (pField->eFieldType) - { + switch (pField->eFieldType) { case F_STRING: - *(char **)pv = GetStringPtr(*(intptr_t *)pv, pbOriginalRefData?*(char**)pvOriginal:NULL); + *(char **)pv = GetStringPtr(*(intptr_t *)pv, pbOriginalRefData ? *(char **)pvOriginal : NULL); break; case F_GENTITY: @@ -521,53 +440,45 @@ static void EvaluateField(const field_t *pField, byte *pbBase, byte *pbOriginalR *(gitem_t **)pv = GetGItemPtr(*(intptr_t *)pv); break; - case F_BEHAVIORSET: - { - char **p = (char **) pv; - char **pO= (char **) pvOriginal; - for (int i=0; iui = BigLong( chid ); + ba->ui = BigLong(chid); chidtext[4] = '\0'; return chidtext; } -template -static void EvaluateFields( - const field_t* pFields, - T* pbData, - T* pbOriginalRefData, - unsigned int ulChid) -{ - ojk::SavedGameHelper saved_game( - ::gi.saved_game); - - if (!saved_game.try_read_chunk( - ulChid, - *pbData)) - { - ::G_Error( - ::va("EvaluateFields(): variable-sized chunk '%s' without handler!", - ::SG_GetChidText(ulChid))); +template static void EvaluateFields(const field_t *pFields, T *pbData, T *pbOriginalRefData, unsigned int ulChid) { + ojk::SavedGameHelper saved_game(::gi.saved_game); + + if (!saved_game.try_read_chunk(ulChid, *pbData)) { + ::G_Error(::va("EvaluateFields(): variable-sized chunk '%s' without handler!", ::SG_GetChidText(ulChid))); } - if (pFields) - { - for (auto pField = pFields; pField->psName; ++pField) - { - ::EvaluateField( - pField, - reinterpret_cast(pbData), - reinterpret_cast(pbOriginalRefData)); + if (pFields) { + for (auto pField = pFields; pField->psName; ++pField) { + ::EvaluateField(pField, reinterpret_cast(pbData), reinterpret_cast(pbOriginalRefData)); } } } @@ -632,12 +524,11 @@ WriteLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ -static void WriteLevelLocals () -{ +static void WriteLevelLocals() { level_locals_t *temp = (level_locals_t *)gi.Malloc(sizeof(level_locals_t), TAG_TEMP_WORKSPACE, qfalse); - *temp = level; // copy out all data into a temp space + *temp = level; // copy out all data into a temp space - EnumerateFields(savefields_LevelLocals, temp, INT_ID('L','V','L','C')); + EnumerateFields(savefields_LevelLocals, temp, INT_ID('L', 'V', 'L', 'C')); gi.Free(temp); } @@ -648,85 +539,69 @@ ReadLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ -static void ReadLevelLocals () -{ +static void ReadLevelLocals() { // preserve client ptr either side of the load, because clients are already saved/loaded through Read/Writegame... // - gclient_t *pClients = level.clients; // save clients + gclient_t *pClients = level.clients; // save clients level_locals_t *temp = (level_locals_t *)gi.Malloc(sizeof(level_locals_t), TAG_TEMP_WORKSPACE, qfalse); *temp = level; - EvaluateFields(savefields_LevelLocals, temp, &level, INT_ID('L','V','L','C')); - level = *temp; // struct copy + EvaluateFields(savefields_LevelLocals, temp, &level, INT_ID('L', 'V', 'L', 'C')); + level = *temp; // struct copy - level.clients = pClients; // restore clients + level.clients = pClients; // restore clients gi.Free(temp); } -static void WriteGEntities(qboolean qbAutosave) -{ +static void WriteGEntities(qboolean qbAutosave) { int iCount = 0; int i; - for (i=0; i<(qbAutosave?1:globals.num_entities); i++) - { - gentity_t* ent = &g_entities[i]; + for (i = 0; i < (qbAutosave ? 1 : globals.num_entities); i++) { + gentity_t *ent = &g_entities[i]; - if ( ent->inuse ) - { + if (ent->inuse) { iCount++; } } - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('N', 'M', 'E', 'D'), - iCount); + saved_game.write_chunk(INT_ID('N', 'M', 'E', 'D'), iCount); - for (i=0; i<(qbAutosave?1:globals.num_entities); i++) - { - gentity_t* ent = &g_entities[i]; + for (i = 0; i < (qbAutosave ? 1 : globals.num_entities); i++) { + gentity_t *ent = &g_entities[i]; - if ( ent->inuse) - { - saved_game.write_chunk( - INT_ID('E', 'D', 'N', 'M'), - i); + if (ent->inuse) { + saved_game.write_chunk(INT_ID('E', 'D', 'N', 'M'), i); qboolean qbLinked = ent->linked; - gi.unlinkentity( ent ); - gentity_t tempEnt = *ent; // make local copy + gi.unlinkentity(ent); + gentity_t tempEnt = *ent; // make local copy tempEnt.linked = qbLinked; - if (qbLinked) - { - gi.linkentity( ent ); + if (qbLinked) { + gi.linkentity(ent); } - EnumerateFields(savefields_gEntity, &tempEnt, INT_ID('G','E','N','T')); + EnumerateFields(savefields_gEntity, &tempEnt, INT_ID('G', 'E', 'N', 'T')); // now for any fiddly bits that would be rather awkward to build into the enumerator... // - if (tempEnt.NPC) - { - gNPC_t npc = *ent->NPC; // NOT *tempEnt.NPC; !! :-) + if (tempEnt.NPC) { + gNPC_t npc = *ent->NPC; // NOT *tempEnt.NPC; !! :-) - EnumerateFields(savefields_gNPC, &npc, INT_ID('G','N','P','C')); + EnumerateFields(savefields_gNPC, &npc, INT_ID('G', 'N', 'P', 'C')); } - if (tempEnt.client == (gclient_t *)-2) // I know, I know... + if (tempEnt.client == (gclient_t *)-2) // I know, I know... { - gclient_t client = *ent->client; // NOT *tempEnt.client!! - EnumerateFields(savefields_gClient, &client, INT_ID('G','C','L','I')); + gclient_t client = *ent->client; // NOT *tempEnt.client!! + EnumerateFields(savefields_gClient, &client, INT_ID('G', 'C', 'L', 'I')); } - if (tempEnt.parms) - { - saved_game.write_chunk( - INT_ID('P', 'A', 'R', 'M'), - *ent->parms); + if (tempEnt.parms) { + saved_game.write_chunk(INT_ID('P', 'A', 'R', 'M'), *ent->parms); } // the scary ghoul2 saver stuff... (fingers crossed) @@ -736,12 +611,11 @@ static void WriteGEntities(qboolean qbAutosave) } } - //Write out all entity timers - TIMER_Save();//WriteEntityTimers(); + // Write out all entity timers + TIMER_Save(); // WriteEntityTimers(); - if (!qbAutosave) - { - //Save out ICARUS information + if (!qbAutosave) { + // Save out ICARUS information iICARUS->Save(); // this marker needs to be here, it lets me know if Icarus doesn't load everything back later, @@ -750,47 +624,35 @@ static void WriteGEntities(qboolean qbAutosave) // static int iBlah = 1234; - saved_game.write_chunk( - INT_ID('I', 'C', 'O', 'K'), - iBlah); + saved_game.write_chunk(INT_ID('I', 'C', 'O', 'K'), iBlah); } - if (!qbAutosave )//really shouldn't need to write these bits at all, just restore them from the ents... + if (!qbAutosave) // really shouldn't need to write these bits at all, just restore them from the ents... { WriteInUseBits(); } } -static void ReadGEntities(qboolean qbAutosave) -{ - int iCount = 0; - int i; +static void ReadGEntities(qboolean qbAutosave) { + int iCount = 0; + int i; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('N', 'M', 'E', 'D'), - iCount); + saved_game.read_chunk(INT_ID('N', 'M', 'E', 'D'), iCount); int iPreviousEntRead = -1; - for (i=0; i( - INT_ID('E', 'D', 'N', 'M'), - iEntIndex); + saved_game.read_chunk(INT_ID('E', 'D', 'N', 'M'), iEntIndex); - if (iEntIndex >= globals.num_entities) - { + if (iEntIndex >= globals.num_entities) { globals.num_entities = iEntIndex + 1; } - if (iPreviousEntRead != iEntIndex-1) - { - for (int j=iPreviousEntRead+1; j!=iEntIndex; j++) - { - if ( g_entities[j].inuse ) // not actually necessary + if (iPreviousEntRead != iEntIndex - 1) { + for (int j = iPreviousEntRead + 1; j != iEntIndex; j++) { + if (g_entities[j].inuse) // not actually necessary { G_FreeEntity(&g_entities[j]); } @@ -800,107 +662,95 @@ static void ReadGEntities(qboolean qbAutosave) // slightly naff syntax here, but makes a few ops clearer later... // - gentity_t entity; -// gentity_t* pEntOriginal = &g_entities[iEntIndex]; -// gentity_t* pEnt = &entity; - gentity_t* pEntOriginal = &entity; - gentity_t* pEnt = &g_entities[iEntIndex]; - *pEntOriginal = *pEnt; // struct copy, so we can refer to original + gentity_t entity; + // gentity_t* pEntOriginal = &g_entities[iEntIndex]; + // gentity_t* pEnt = &entity; + gentity_t *pEntOriginal = &entity; + gentity_t *pEnt = &g_entities[iEntIndex]; + *pEntOriginal = *pEnt; // struct copy, so we can refer to original pEntOriginal->ghoul2.kill(); gi.unlinkentity(pEnt); - ICARUS_FreeEnt (pEnt); + ICARUS_FreeEnt(pEnt); // // sneaky: destroy the ghoul2 object within this struct before binary-loading over the top of it... // gi.G2API_LoadSaveCodeDestructGhoul2Info(pEnt->ghoul2); pEnt->ghoul2.kill(); - EvaluateFields(savefields_gEntity, pEnt, pEntOriginal, INT_ID('G','E','N','T')); + EvaluateFields(savefields_gEntity, pEnt, pEntOriginal, INT_ID('G', 'E', 'N', 'T')); pEnt->ghoul2.kill(); // now for any fiddly bits... // - if (pEnt->NPC) // will be qtrue/qfalse + if (pEnt->NPC) // will be qtrue/qfalse { gNPC_t tempNPC; - EvaluateFields(savefields_gNPC, &tempNPC,pEntOriginal->NPC, INT_ID('G','N','P','C')); + EvaluateFields(savefields_gNPC, &tempNPC, pEntOriginal->NPC, INT_ID('G', 'N', 'P', 'C')); // so can we pinch the original's one or do we have to alloc a new one?... // - if (pEntOriginal->NPC) - { + if (pEntOriginal->NPC) { // pinch this G_Alloc handle... // pEnt->NPC = pEntOriginal->NPC; - } - else - { + } else { // original didn't have one (hmmm...), so make a new one... // - //assert(0); // I want to know about this, though not in release - pEnt->NPC = (gNPC_t *) G_Alloc(sizeof(*pEnt->NPC)); + // assert(0); // I want to know about this, though not in release + pEnt->NPC = (gNPC_t *)G_Alloc(sizeof(*pEnt->NPC)); } // copy over the one we've just loaded... // - *pEnt->NPC = tempNPC; // struct copy - + *pEnt->NPC = tempNPC; // struct copy } - if (pEnt->client == (gclient_t*) -2) // one of Mike G's NPC clients? + if (pEnt->client == (gclient_t *)-2) // one of Mike G's NPC clients? { gclient_t tempGClient; - EvaluateFields(savefields_gClient, &tempGClient, pEntOriginal->client, INT_ID('G','C','L','I')); + EvaluateFields(savefields_gClient, &tempGClient, pEntOriginal->client, INT_ID('G', 'C', 'L', 'I')); // can we pinch the original's client handle or do we have to alloc a new one?... // - if (pEntOriginal->client) - { + if (pEntOriginal->client) { // pinch this G_Alloc handle... // pEnt->client = pEntOriginal->client; - } - else - { + } else { // original didn't have one (hmmm...) so make a new one... // - pEnt->client = (gclient_t *) G_Alloc(sizeof(*pEnt->client)); + pEnt->client = (gclient_t *)G_Alloc(sizeof(*pEnt->client)); } // copy over the one we've just loaded.... // - *pEnt->client = tempGClient; // struct copy + *pEnt->client = tempGClient; // struct copy } // Some Icarus thing... (probably) // - if (pEnt->parms) // will be qtrue/qfalse + if (pEnt->parms) // will be qtrue/qfalse { parms_t tempParms; - saved_game.read_chunk( - INT_ID('P', 'A', 'R', 'M'), - tempParms); + saved_game.read_chunk(INT_ID('P', 'A', 'R', 'M'), tempParms); // so can we pinch the original's one or do we have to alloc a new one?... // - if (pEntOriginal->parms) - { + if (pEntOriginal->parms) { // pinch this G_Alloc handle... // pEnt->parms = pEntOriginal->parms; - } - else - { + } else { // original didn't have one, so make a new one... // - pEnt->parms = (parms_t *) G_Alloc(sizeof(*pEnt->parms)); + pEnt->parms = (parms_t *)G_Alloc(sizeof(*pEnt->parms)); } // copy over the one we've just loaded... // - *pEnt->parms = tempParms; // struct copy + *pEnt->parms = tempParms; // struct copy } // the scary ghoul2 stuff... (fingers crossed) @@ -908,38 +758,31 @@ static void ReadGEntities(qboolean qbAutosave) { #ifdef JK2_MODE // Skip GL2 data size - saved_game.read_chunk( - INT_ID('G', 'L', '2', 'S')); + saved_game.read_chunk(INT_ID('G', 'L', '2', 'S')); #endif // JK2_MODE - saved_game.read_chunk( - INT_ID('G', 'H', 'L', '2')); + saved_game.read_chunk(INT_ID('G', 'H', 'L', '2')); - gi.G2API_LoadGhoul2Models( - pEnt->ghoul2, - nullptr); + gi.G2API_LoadGhoul2Models(pEnt->ghoul2, nullptr); } -// gi.unlinkentity (pEntOriginal); -// ICARUS_FreeEnt( pEntOriginal ); -// *pEntOriginal = *pEnt; // struct copy -// qboolean qbLinked = pEntOriginal->linked; -// pEntOriginal->linked = qfalse; -// if (qbLinked) -// { -// gi.linkentity (pEntOriginal); -// } + // gi.unlinkentity (pEntOriginal); + // ICARUS_FreeEnt( pEntOriginal ); + // *pEntOriginal = *pEnt; // struct copy + // qboolean qbLinked = pEntOriginal->linked; + // pEntOriginal->linked = qfalse; + // if (qbLinked) + // { + // gi.linkentity (pEntOriginal); + // } // because the sytem stores sfx_t handles directly instead of the set, we have to reget the set's sfx_t... // - if (pEnt->s.eType == ET_MOVER && pEnt->s.loopSound>0) - { - if ( VALIDSTRING( pEnt->soundSet )) - { - extern int BMS_MID; // from g_mover - pEnt->s.loopSound = CAS_GetBModelSound( pEnt->soundSet, BMS_MID ); - if (pEnt->s.loopSound == -1) - { + if (pEnt->s.eType == ET_MOVER && pEnt->s.loopSound > 0) { + if (VALIDSTRING(pEnt->soundSet)) { + extern int BMS_MID; // from g_mover + pEnt->s.loopSound = CAS_GetBModelSound(pEnt->soundSet, BMS_MID); + if (pEnt->s.loopSound == -1) { pEnt->s.loopSound = 0; } } @@ -947,29 +790,26 @@ static void ReadGEntities(qboolean qbAutosave) qboolean qbLinked = pEnt->linked; pEnt->linked = qfalse; - if (qbLinked) - { - gi.linkentity (pEnt); + if (qbLinked) { + gi.linkentity(pEnt); } } - //Read in all the entity timers - TIMER_Load();//ReadEntityTimers(); + // Read in all the entity timers + TIMER_Load(); // ReadEntityTimers(); - if (!qbAutosave) - { + if (!qbAutosave) { // now zap any g_ents that were inuse when the level was loaded, but are no longer in use in the saved version // that we've just loaded... // - for (i=iPreviousEntRead+1; iLoad(); @@ -977,27 +817,22 @@ static void ReadGEntities(qboolean qbAutosave) // static int iBlah = 1234; - saved_game.read_chunk( - INT_ID('I', 'C', 'O', 'K'), - iBlah); + saved_game.read_chunk(INT_ID('I', 'C', 'O', 'K'), iBlah); } - if (!qbAutosave) - { - ReadInUseBits();//really shouldn't need to read these bits in at all, just restore them from the ents... + if (!qbAutosave) { + ReadInUseBits(); // really shouldn't need to read these bits in at all, just restore them from the ents... } } - -void WriteLevel(qboolean qbAutosave) -{ +void WriteLevel(qboolean qbAutosave) { if (!qbAutosave) //-always save the client { // write out one client - us! // - assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way ReadGame works + assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way ReadGame works gclient_t client = level.clients[0]; - EnumerateFields(savefields_gClient, &client, INT_ID('G','C','L','I')); - WriteLevelLocals(); // level_locals_t level + EnumerateFields(savefields_gClient, &client, INT_ID('G', 'C', 'L', 'I')); + WriteLevelLocals(); // level_locals_t level } OBJ_SaveObjectiveData(); @@ -1016,55 +851,46 @@ void WriteLevel(qboolean qbAutosave) // static int iDONE = 1234; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.write_chunk( - INT_ID('D', 'O', 'N', 'E'), - iDONE); + saved_game.write_chunk(INT_ID('D', 'O', 'N', 'E'), iDONE); } -void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) -{ - if ( qbLoadTransition ) - { - //loadtransitions do not need to read the objectives and client data from the level they're going to - //In a loadtransition, client data is carried over on the server and will be stomped later anyway. - //The objective info (in client->sess data), however, is read in from G_ReadSessionData which is called before this func, - //we do NOT want to stomp that session data when doing a load transition +void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) { + if (qbLoadTransition) { + // loadtransitions do not need to read the objectives and client data from the level they're going to + // In a loadtransition, client data is carried over on the server and will be stomped later anyway. + // The objective info (in client->sess data), however, is read in from G_ReadSessionData which is called before this func, + // we do NOT want to stomp that session data when doing a load transition - //However, we should still save this info out because these savegames may need to be - //loaded normally later- perhaps if you die and need to respawn, perhaps as some kind - //of emergency savegame for resuming, etc. + // However, we should still save this info out because these savegames may need to be + // loaded normally later- perhaps if you die and need to respawn, perhaps as some kind + // of emergency savegame for resuming, etc. - //SO: We read it in, but throw it away. + // SO: We read it in, but throw it away. - //Read & throw away gclient info + // Read & throw away gclient info gclient_t junkClient; - EvaluateFields(savefields_gClient, &junkClient, &level.clients[0], INT_ID('G','C','L','I')); + EvaluateFields(savefields_gClient, &junkClient, &level.clients[0], INT_ID('G', 'C', 'L', 'I')); - //Read & throw away objective info - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + // Read & throw away objective info + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('O', 'B', 'J', 'T')); + saved_game.read_chunk(INT_ID('O', 'B', 'J', 'T')); - ReadLevelLocals(); // level_locals_t level - } - else - { - if (!qbAutosave )//always load the client unless it's an autosave + ReadLevelLocals(); // level_locals_t level + } else { + if (!qbAutosave) // always load the client unless it's an autosave { - assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way things work + assert(level.maxclients == 1); // I'll need to know if this changes, otherwise I'll need to change the way things work gclient_t GClient; - EvaluateFields(savefields_gClient, &GClient, &level.clients[0], INT_ID('G','C','L','I')); - level.clients[0] = GClient; // struct copy - ReadLevelLocals(); // level_locals_t level + EvaluateFields(savefields_gClient, &GClient, &level.clients[0], INT_ID('G', 'C', 'L', 'I')); + level.clients[0] = GClient; // struct copy + ReadLevelLocals(); // level_locals_t level } - OBJ_LoadObjectiveData();//loads mission objectives AND tactical info + OBJ_LoadObjectiveData(); // loads mission objectives AND tactical info } ///////////// @@ -1082,18 +908,12 @@ void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition) // static int iDONE = 1234; - ojk::SavedGameHelper saved_game( - ::gi.saved_game); + ojk::SavedGameHelper saved_game(::gi.saved_game); - saved_game.read_chunk( - INT_ID('D', 'O', 'N', 'E'), - iDONE); + saved_game.read_chunk(INT_ID('D', 'O', 'N', 'E'), iDONE); } extern int killPlayerTimer; -qboolean GameAllowedToSaveHere(void) -{ - return (qboolean)(!in_camera && !killPlayerTimer); -} +qboolean GameAllowedToSaveHere(void) { return (qboolean)(!in_camera && !killPlayerTimer); } //////////////////// eof ///////////////////// diff --git a/codeJK2/game/g_session.cpp b/codeJK2/game/g_session.cpp index 1499dfa09d..75fc5f4cae 100644 --- a/codeJK2/game/g_session.cpp +++ b/codeJK2/game/g_session.cpp @@ -43,63 +43,47 @@ G_WriteClientSessionData Called on game shutdown ================ */ -void G_WriteClientSessionData( gclient_t *client ) { - const char *s; - const char *s2; - const char *var; - int i; +void G_WriteClientSessionData(gclient_t *client) { + const char *s; + const char *s2; + const char *var; + int i; - s = va("%i", client->sess.sessionTeam ); - var = va( "session%i", client - level.clients ); - gi.cvar_set( var, s ); + s = va("%i", client->sess.sessionTeam); + var = va("session%i", client - level.clients); + gi.cvar_set(var, s); s2 = ""; // Throw all status info into a string - for (i=0;i< MAX_OBJECTIVES; i++) - { - s2 = va("%s %i %i", s2, client->sess.mission_objectives[i].display, client->sess.mission_objectives[i].status); + for (i = 0; i < MAX_OBJECTIVES; i++) { + s2 = va("%s %i %i", s2, client->sess.mission_objectives[i].display, client->sess.mission_objectives[i].status); } - var = va( "sessionobj%i", client - level.clients ); - gi.cvar_set( var, s2 ); + var = va("sessionobj%i", client - level.clients); + gi.cvar_set(var, s2); // Throw all mission stats in to a string - s2 = va("%i %i %i %i %i %i %i %i %i %i %i %i", - client->sess.missionStats.secretsFound, - client->sess.missionStats.totalSecrets, - client->sess.missionStats.shotsFired, - client->sess.missionStats.hits, - client->sess.missionStats.enemiesSpawned, - client->sess.missionStats.enemiesKilled, - client->sess.missionStats.saberThrownCnt, - client->sess.missionStats.saberBlocksCnt, - client->sess.missionStats.legAttacksCnt, - client->sess.missionStats.armAttacksCnt, - client->sess.missionStats.torsoAttacksCnt, - client->sess.missionStats.otherAttacksCnt - ); - - var = va( "missionstats%i", client - level.clients ); - gi.cvar_set( var, s2 ); + s2 = va("%i %i %i %i %i %i %i %i %i %i %i %i", client->sess.missionStats.secretsFound, client->sess.missionStats.totalSecrets, + client->sess.missionStats.shotsFired, client->sess.missionStats.hits, client->sess.missionStats.enemiesSpawned, + client->sess.missionStats.enemiesKilled, client->sess.missionStats.saberThrownCnt, client->sess.missionStats.saberBlocksCnt, + client->sess.missionStats.legAttacksCnt, client->sess.missionStats.armAttacksCnt, client->sess.missionStats.torsoAttacksCnt, + client->sess.missionStats.otherAttacksCnt); + var = va("missionstats%i", client - level.clients); + gi.cvar_set(var, s2); s2 = ""; - for (i=0;i< NUM_FORCE_POWERS; i++) - { - s2 = va("%s %i",s2, client->sess.missionStats.forceUsed[i]); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + s2 = va("%s %i", s2, client->sess.missionStats.forceUsed[i]); } - var = va( "sessionpowers%i", client - level.clients ); - gi.cvar_set( var, s2 ); - + var = va("sessionpowers%i", client - level.clients); + gi.cvar_set(var, s2); s2 = ""; - for (i=0;i< WP_NUM_WEAPONS; i++) - { - s2 = va("%s %i",s2, client->sess.missionStats.weaponUsed[i]); + for (i = 0; i < WP_NUM_WEAPONS; i++) { + s2 = va("%s %i", s2, client->sess.missionStats.weaponUsed[i]); } - var = va( "sessionweapons%i", client - level.clients ); - gi.cvar_set( var, s2 ); - - + var = va("sessionweapons%i", client - level.clients); + gi.cvar_set(var, s2); } /* @@ -109,78 +93,63 @@ G_ReadSessionData Called on a reconnect ================ */ -void G_ReadSessionData( gclient_t *client ) { - char s[MAX_STRING_CHARS]; - const char *var; - int i; +void G_ReadSessionData(gclient_t *client) { + char s[MAX_STRING_CHARS]; + const char *var; + int i; - var = va( "session%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); + var = va("session%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); int tmp; - sscanf( s, "%i", &tmp ); + sscanf(s, "%i", &tmp); client->sess.sessionTeam = (team_t)tmp; - var = va( "sessionobj%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); + var = va("sessionobj%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); var = s; var++; - for (i=0;i< MAX_OBJECTIVES; i++) - { - sscanf( var, "%i %i", - &client->sess.mission_objectives[i].display, - &client->sess.mission_objectives[i].status); - var+=4; + for (i = 0; i < MAX_OBJECTIVES; i++) { + sscanf(var, "%i %i", &client->sess.mission_objectives[i].display, &client->sess.mission_objectives[i].status); + var += 4; } - var = va( "missionstats%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - sscanf( s, "%i %i %i %i %i %i %i %i %i %i %i %i", - &client->sess.missionStats.secretsFound, - &client->sess.missionStats.totalSecrets, - &client->sess.missionStats.shotsFired, - &client->sess.missionStats.hits, - &client->sess.missionStats.enemiesSpawned, - &client->sess.missionStats.enemiesKilled, - &client->sess.missionStats.saberThrownCnt, - &client->sess.missionStats.saberBlocksCnt, - &client->sess.missionStats.legAttacksCnt, - &client->sess.missionStats.armAttacksCnt, - &client->sess.missionStats.torsoAttacksCnt, - &client->sess.missionStats.otherAttacksCnt); - - - var = va( "sessionpowers%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->sess.missionStats.forceUsed[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + var = va("missionstats%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + sscanf(s, "%i %i %i %i %i %i %i %i %i %i %i %i", &client->sess.missionStats.secretsFound, &client->sess.missionStats.totalSecrets, + &client->sess.missionStats.shotsFired, &client->sess.missionStats.hits, &client->sess.missionStats.enemiesSpawned, + &client->sess.missionStats.enemiesKilled, &client->sess.missionStats.saberThrownCnt, &client->sess.missionStats.saberBlocksCnt, + &client->sess.missionStats.legAttacksCnt, &client->sess.missionStats.armAttacksCnt, &client->sess.missionStats.torsoAttacksCnt, + &client->sess.missionStats.otherAttacksCnt); + + var = va("sessionpowers%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->sess.missionStats.forceUsed[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==NUM_FORCE_POWERS); - - var = va( "sessionweapons%i", client - level.clients ); - gi.Cvar_VariableStringBuffer( var, s, sizeof(s) ); - - i=0; - var = strtok( s, " " ); - while( var != NULL ) - { - /* While there are tokens in "s" */ - client->sess.missionStats.weaponUsed[i++] = atoi(var); - /* Get next token: */ - var = strtok( NULL, " " ); + assert(i == NUM_FORCE_POWERS); + + var = va("sessionweapons%i", client - level.clients); + gi.Cvar_VariableStringBuffer(var, s, sizeof(s)); + + i = 0; + var = strtok(s, " "); + while (var != NULL) { + /* While there are tokens in "s" */ + client->sess.missionStats.weaponUsed[i++] = atoi(var); + /* Get next token: */ + var = strtok(NULL, " "); } - assert (i==WP_NUM_WEAPONS); + assert(i == WP_NUM_WEAPONS); } - /* ================ G_InitSessionData @@ -188,25 +157,23 @@ G_InitSessionData Called on a first-time connect ================ */ -void G_InitSessionData( gclient_t *client, char *userinfo ) { - clientSession_t *sess; +void G_InitSessionData(gclient_t *client, char *userinfo) { + clientSession_t *sess; sess = &client->sess; sess->sessionTeam = TEAM_FREE; - G_WriteClientSessionData( client ); + G_WriteClientSessionData(client); } - /* ================== G_InitWorldSession ================== */ -void G_InitWorldSession( void ) { -} +void G_InitWorldSession(void) {} /* ================== @@ -214,14 +181,14 @@ G_WriteSessionData ================== */ -void G_WriteSessionData( void ) { - int i; +void G_WriteSessionData(void) { + int i; - gi.cvar_set( "session", 0) ; + gi.cvar_set("session", 0); - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected == CON_CONNECTED ) { - G_WriteClientSessionData( &level.clients[i] ); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { + G_WriteClientSessionData(&level.clients[i]); } } } diff --git a/codeJK2/game/g_spawn.cpp b/codeJK2/game/g_spawn.cpp index 9e3672d21e..2b5c5b9e02 100644 --- a/codeJK2/game/g_spawn.cpp +++ b/codeJK2/game/g_spawn.cpp @@ -30,28 +30,28 @@ extern cvar_t *g_spskill; // these vars I moved here out of the level_locals_t struct simply because it's pointless to try saving them, // and the level_locals_t struct is included in the save process... -slc // -qboolean spawning = qfalse; // the G_Spawn*() functions are valid (only turned on during one function) -int numSpawnVars; -char *spawnVars[MAX_SPAWN_VARS][2]; // key / value pairs -int numSpawnVarChars; -char spawnVarChars[MAX_SPAWN_VARS_CHARS]; +qboolean spawning = qfalse; // the G_Spawn*() functions are valid (only turned on during one function) +int numSpawnVars; +char *spawnVars[MAX_SPAWN_VARS][2]; // key / value pairs +int numSpawnVarChars; +char spawnVarChars[MAX_SPAWN_VARS_CHARS]; #include "../../code/qcommon/sstring.h" -//NOTENOTE: Be sure to change the mirrored code in cgmain.cpp -typedef std::map< sstring_t, unsigned char, std::less > namePrecache_m; -namePrecache_m *as_preCacheMap; +// NOTENOTE: Be sure to change the mirrored code in cgmain.cpp +typedef std::map> namePrecache_m; +namePrecache_m *as_preCacheMap; -qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) { - int i; +qboolean G_SpawnString(const char *key, const char *defaultString, char **out) { + int i; - if ( !spawning ) { + if (!spawning) { *out = (char *)defaultString; -// G_Error( "G_SpawnString() called while not spawning" ); + // G_Error( "G_SpawnString() called while not spawning" ); } - for ( i = 0 ; i < numSpawnVars ; i++ ) { - if ( !strcmp( key, spawnVars[i][0] ) ) { + for (i = 0; i < numSpawnVars; i++) { + if (!strcmp(key, spawnVars[i][0])) { *out = spawnVars[i][1]; return qtrue; } @@ -61,56 +61,50 @@ qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) return qfalse; } -qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnFloat(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atof( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atof(s); return present; } -qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ) { - char *s; - qboolean present; +qboolean G_SpawnInt(const char *key, const char *defaultString, int *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atoi( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atoi(s); return present; } -qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnVector(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f %f %f", &out[0], &out[1], &out[2]); return present; } -qboolean G_SpawnVector4( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnVector4(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f %f %f %f", &out[0], &out[1], &out[2], &out[3] ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f %f %f %f", &out[0], &out[1], &out[2], &out[3]); return present; } -qboolean G_SpawnFlag( const char *key, int flag, int *out ) -{ - //find that key - for ( int i = 0 ; i < numSpawnVars ; i++ ) - { - if ( !strcmp( key, spawnVars[i][0] ) ) - { - //found the key - if ( atoi( spawnVars[i][1] ) != 0 ) - {//if it's non-zero, and in the flag +qboolean G_SpawnFlag(const char *key, int flag, int *out) { + // find that key + for (int i = 0; i < numSpawnVars; i++) { + if (!strcmp(key, spawnVars[i][0])) { + // found the key + if (atoi(spawnVars[i][1]) != 0) { // if it's non-zero, and in the flag *out |= flag; - } - else - {//if it's zero, or out the flag + } else { // if it's zero, or out the flag *out &= ~flag; } return qtrue; @@ -120,14 +114,13 @@ qboolean G_SpawnFlag( const char *key, int flag, int *out ) return qfalse; } -qboolean G_SpawnAngleHack( const char *key, const char *defaultString, float *out ) -{ - char *s; - qboolean present; - float temp = 0; +qboolean G_SpawnAngleHack(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; + float temp = 0; - present = G_SpawnString( key, defaultString, &s ); - sscanf( s, "%f", &temp ); + present = G_SpawnString(key, defaultString, &s); + sscanf(s, "%f", &temp); out[0] = 0; out[1] = temp; @@ -136,62 +129,58 @@ qboolean G_SpawnAngleHack( const char *key, const char *defaultString, float *ou return present; } -stringID_table_t flagTable [] = -{ - { "noTED", EF_NO_TED }, - //stringID_table_t Must end with a null entry - { "", 0 } -}; +stringID_table_t flagTable[] = {{"noTED", EF_NO_TED}, + // stringID_table_t Must end with a null entry + {"", 0}}; // // fields are needed for spawning from the entity string // typedef enum { - F_INT, + F_INT, F_FLOAT, - F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL - F_GSTRING, // string on disk, pointer in memory, TAG_GAME + F_LSTRING, // string on disk, pointer in memory, TAG_LEVEL + F_GSTRING, // string on disk, pointer in memory, TAG_GAME F_VECTOR, F_VECTOR4, F_ANGLEHACK, - F_ENTITY, // index on disk, pointer in memory - F_ITEM, // index on disk, pointer in memory - F_CLIENT, // index on disk, pointer in memory - F_PARM1, // Special case for parms - F_PARM2, // Special case for parms - F_PARM3, // Special case for parms - F_PARM4, // Special case for parms - F_PARM5, // Special case for parms - F_PARM6, // Special case for parms - F_PARM7, // Special case for parms - F_PARM8, // Special case for parms - F_PARM9, // Special case for parms - F_PARM10, // Special case for parms - F_PARM11, // Special case for parms - F_PARM12, // Special case for parms - F_PARM13, // Special case for parms - F_PARM14, // Special case for parms - F_PARM15, // Special case for parms - F_PARM16, // Special case for parms - F_FLAG, // special case for flags + F_ENTITY, // index on disk, pointer in memory + F_ITEM, // index on disk, pointer in memory + F_CLIENT, // index on disk, pointer in memory + F_PARM1, // Special case for parms + F_PARM2, // Special case for parms + F_PARM3, // Special case for parms + F_PARM4, // Special case for parms + F_PARM5, // Special case for parms + F_PARM6, // Special case for parms + F_PARM7, // Special case for parms + F_PARM8, // Special case for parms + F_PARM9, // Special case for parms + F_PARM10, // Special case for parms + F_PARM11, // Special case for parms + F_PARM12, // Special case for parms + F_PARM13, // Special case for parms + F_PARM14, // Special case for parms + F_PARM15, // Special case for parms + F_PARM16, // Special case for parms + F_FLAG, // special case for flags F_IGNORE } fieldtype_t; -typedef struct -{ - char *name; - size_t ofs; - fieldtype_t type; - int flags; +typedef struct { + char *name; + size_t ofs; + fieldtype_t type; + int flags; } field_t; field_t fields[] = { - //Fields for benefit of Radiant only + // Fields for benefit of Radiant only {"autobound", FOFS(classname), F_IGNORE}, {"groupname", FOFS(classname), F_IGNORE}, - {"noBasicSounds", FOFS(classname), F_IGNORE},//will be looked at separately - {"noCombatSounds", FOFS(classname), F_IGNORE},//will be looked at separately - {"noExtraSounds", FOFS(classname), F_IGNORE},//will be looked at separately + {"noBasicSounds", FOFS(classname), F_IGNORE}, // will be looked at separately + {"noCombatSounds", FOFS(classname), F_IGNORE}, // will be looked at separately + {"noExtraSounds", FOFS(classname), F_IGNORE}, // will be looked at separately {"classname", FOFS(classname), F_LSTRING}, {"origin", FOFS(s.origin), F_VECTOR}, @@ -199,14 +188,14 @@ field_t fields[] = { {"maxs", FOFS(maxs), F_VECTOR}, {"model", FOFS(model), F_LSTRING}, {"model2", FOFS(model2), F_LSTRING}, - {"model3", FOFS(target), F_LSTRING},//for misc_replicator_item only!!! - {"model4", FOFS(target2), F_LSTRING},//for misc_replicator_item only!!! - {"model5", FOFS(target3), F_LSTRING},//for misc_replicator_item only!!! - {"model6", FOFS(target4), F_LSTRING},//for misc_replicator_item only!!! + {"model3", FOFS(target), F_LSTRING}, // for misc_replicator_item only!!! + {"model4", FOFS(target2), F_LSTRING}, // for misc_replicator_item only!!! + {"model5", FOFS(target3), F_LSTRING}, // for misc_replicator_item only!!! + {"model6", FOFS(target4), F_LSTRING}, // for misc_replicator_item only!!! {"spawnflags", FOFS(spawnflags), F_INT}, {"speed", FOFS(speed), F_FLOAT}, - {"duration", FOFS(speed), F_FLOAT},//for psycho jism - {"interest", FOFS(health), F_INT},//For target_interest + {"duration", FOFS(speed), F_FLOAT}, // for psycho jism + {"interest", FOFS(health), F_INT}, // For target_interest {"target", FOFS(target), F_LSTRING}, {"target2", FOFS(target2), F_LSTRING}, {"target3", FOFS(target3), F_LSTRING}, @@ -217,28 +206,28 @@ field_t fields[] = { {"team", FOFS(team), F_LSTRING}, {"mapname", FOFS(message), F_LSTRING}, {"wait", FOFS(wait), F_FLOAT}, - {"finaltime", FOFS(wait), F_FLOAT},//For dlight + {"finaltime", FOFS(wait), F_FLOAT}, // For dlight {"random", FOFS(random), F_FLOAT}, - {"FOV", FOFS(random), F_FLOAT},//for ref_tags and trigger_visibles + {"FOV", FOFS(random), F_FLOAT}, // for ref_tags and trigger_visibles {"count", FOFS(count), F_INT}, {"health", FOFS(health), F_INT}, - {"friction", FOFS(health), F_INT},//For target_friction_change + {"friction", FOFS(health), F_INT}, // For target_friction_change {"light", 0, F_IGNORE}, {"dmg", FOFS(damage), F_INT}, {"angles", FOFS(s.angles), F_VECTOR}, {"angle", FOFS(s.angles), F_ANGLEHACK}, {"cameraGroup", FOFS(cameraGroup), F_LSTRING}, {"radius", FOFS(radius), F_FLOAT}, - {"hiderange", FOFS(radius), F_FLOAT},//for triggers only - {"starttime", FOFS(radius), F_FLOAT},//for dlight - {"type", FOFS(count), F_FLOAT},//for fx_crew_beam_in + {"hiderange", FOFS(radius), F_FLOAT}, // for triggers only + {"starttime", FOFS(radius), F_FLOAT}, // for dlight + {"type", FOFS(count), F_FLOAT}, // for fx_crew_beam_in {"fullName", FOFS(fullName), F_LSTRING}, {"fxfile", FOFS(fxFile), F_LSTRING}, {"fxfile2", FOFS(fullName), F_LSTRING}, - {"endFrame", FOFS(endFrame), F_INT},//for func_usable shader animation - {"linear", FOFS(alt_fire), F_INT},//for movers to use linear movement + {"endFrame", FOFS(endFrame), F_INT}, // for func_usable shader animation + {"linear", FOFS(alt_fire), F_INT}, // for movers to use linear movement -//Script parms - will this handle clamping to 16 or whatever length of parm[0] is? + // Script parms - will this handle clamping to 16 or whatever length of parm[0] is? {"parm1", 0, F_PARM1}, {"parm2", 0, F_PARM2}, {"parm3", 0, F_PARM3}, @@ -257,48 +246,48 @@ field_t fields[] = { {"parm16", 0, F_PARM16}, {"noTED", FOFS(s.eFlags), F_FLAG}, -//MCG - Begin - //extra fields for ents + // MCG - Begin + // extra fields for ents {"delay", FOFS(delay), F_INT}, {"sounds", FOFS(sounds), F_INT}, - {"closetarget", FOFS(closetarget), F_LSTRING},//for doors - {"opentarget", FOFS(opentarget), F_LSTRING},//for doors - {"paintarget", FOFS(paintarget), F_LSTRING},//for doors - {"soundGroup", FOFS(paintarget), F_LSTRING},//for target_speakers - {"backwardstarget", FOFS(paintarget), F_LSTRING},//for trigger_bidirectional + {"closetarget", FOFS(closetarget), F_LSTRING}, // for doors + {"opentarget", FOFS(opentarget), F_LSTRING}, // for doors + {"paintarget", FOFS(paintarget), F_LSTRING}, // for doors + {"soundGroup", FOFS(paintarget), F_LSTRING}, // for target_speakers + {"backwardstarget", FOFS(paintarget), F_LSTRING}, // for trigger_bidirectional {"splashDamage", FOFS(splashDamage), F_INT}, {"splashRadius", FOFS(splashRadius), F_INT}, - //Script stuff - {"spawnscript", FOFS(behaviorSet[BSET_SPAWN]), F_LSTRING},//name of script to run - {"usescript", FOFS(behaviorSet[BSET_USE]), F_LSTRING},//name of script to run - {"awakescript", FOFS(behaviorSet[BSET_AWAKE]), F_LSTRING},//name of script to run - {"angerscript", FOFS(behaviorSet[BSET_ANGER]), F_LSTRING},//name of script to run - {"attackscript", FOFS(behaviorSet[BSET_ATTACK]), F_LSTRING},//name of script to run - {"victoryscript", FOFS(behaviorSet[BSET_VICTORY]), F_LSTRING},//name of script to run - {"lostenemyscript", FOFS(behaviorSet[BSET_LOSTENEMY]), F_LSTRING},//name of script to run - {"painscript", FOFS(behaviorSet[BSET_PAIN]), F_LSTRING},//name of script to run - {"fleescript", FOFS(behaviorSet[BSET_FLEE]), F_LSTRING},//name of script to run - {"deathscript", FOFS(behaviorSet[BSET_DEATH]), F_LSTRING},//name of script to run - {"delayscript", FOFS(behaviorSet[BSET_DELAYED]), F_LSTRING},//name of script to run - {"delayscripttime", FOFS(delayScriptTime), F_INT},//name of script to run - {"blockedscript", FOFS(behaviorSet[BSET_BLOCKED]), F_LSTRING},//name of script to run - {"ffirescript", FOFS(behaviorSet[BSET_FFIRE]), F_LSTRING},//name of script to run - {"ffdeathscript", FOFS(behaviorSet[BSET_FFDEATH]), F_LSTRING},//name of script to run - {"mindtrickscript", FOFS(behaviorSet[BSET_MINDTRICK]), F_LSTRING},//name of script to run - {"script_targetname", FOFS(script_targetname), F_LSTRING},//scripts look for this when "affecting" - //For NPCs + // Script stuff + {"spawnscript", FOFS(behaviorSet[BSET_SPAWN]), F_LSTRING}, // name of script to run + {"usescript", FOFS(behaviorSet[BSET_USE]), F_LSTRING}, // name of script to run + {"awakescript", FOFS(behaviorSet[BSET_AWAKE]), F_LSTRING}, // name of script to run + {"angerscript", FOFS(behaviorSet[BSET_ANGER]), F_LSTRING}, // name of script to run + {"attackscript", FOFS(behaviorSet[BSET_ATTACK]), F_LSTRING}, // name of script to run + {"victoryscript", FOFS(behaviorSet[BSET_VICTORY]), F_LSTRING}, // name of script to run + {"lostenemyscript", FOFS(behaviorSet[BSET_LOSTENEMY]), F_LSTRING}, // name of script to run + {"painscript", FOFS(behaviorSet[BSET_PAIN]), F_LSTRING}, // name of script to run + {"fleescript", FOFS(behaviorSet[BSET_FLEE]), F_LSTRING}, // name of script to run + {"deathscript", FOFS(behaviorSet[BSET_DEATH]), F_LSTRING}, // name of script to run + {"delayscript", FOFS(behaviorSet[BSET_DELAYED]), F_LSTRING}, // name of script to run + {"delayscripttime", FOFS(delayScriptTime), F_INT}, // name of script to run + {"blockedscript", FOFS(behaviorSet[BSET_BLOCKED]), F_LSTRING}, // name of script to run + {"ffirescript", FOFS(behaviorSet[BSET_FFIRE]), F_LSTRING}, // name of script to run + {"ffdeathscript", FOFS(behaviorSet[BSET_FFDEATH]), F_LSTRING}, // name of script to run + {"mindtrickscript", FOFS(behaviorSet[BSET_MINDTRICK]), F_LSTRING}, // name of script to run + {"script_targetname", FOFS(script_targetname), F_LSTRING}, // scripts look for this when "affecting" + // For NPCs //{"playerTeam", FOFS(playerTeam), F_INT}, //{"enemyTeam", FOFS(enemyTeam), F_INT}, {"NPC_targetname", FOFS(NPC_targetname), F_LSTRING}, {"NPC_target", FOFS(NPC_target), F_LSTRING}, - {"NPC_target2", FOFS(target2), F_LSTRING},//NPC_spawner only - {"NPC_target4", FOFS(target4), F_LSTRING},//NPC_spawner only + {"NPC_target2", FOFS(target2), F_LSTRING}, // NPC_spawner only + {"NPC_target4", FOFS(target4), F_LSTRING}, // NPC_spawner only {"NPC_type", FOFS(NPC_type), F_LSTRING}, {"ownername", FOFS(ownername), F_LSTRING}, - //freaky camera shit + // freaky camera shit {"startRGBA", FOFS(startRGBA), F_VECTOR4}, {"finalRGBA", FOFS(finalRGBA), F_VECTOR4}, -//MCG - End + // MCG - End {"soundSet", FOFS(soundSet), F_LSTRING}, {"scale", 0, F_IGNORE}, @@ -308,390 +297,384 @@ field_t fields[] = { {"switch_style", 0, F_IGNORE}, {"height", 0, F_IGNORE}, - - {NULL} -}; - + {NULL}}; typedef struct { - char *name; - void (*spawn)(gentity_t *ent); + char *name; + void (*spawn)(gentity_t *ent); } spawn_t; -void SP_info_player_start (gentity_t *ent); -void SP_info_player_deathmatch (gentity_t *ent); -void SP_info_player_intermission (gentity_t *ent); +void SP_info_player_start(gentity_t *ent); +void SP_info_player_deathmatch(gentity_t *ent); +void SP_info_player_intermission(gentity_t *ent); void SP_info_firstplace(gentity_t *ent); void SP_info_secondplace(gentity_t *ent); void SP_info_thirdplace(gentity_t *ent); -void SP_func_plat (gentity_t *ent); -void SP_func_static (gentity_t *ent); -void SP_func_rotating (gentity_t *ent); -void SP_func_bobbing (gentity_t *ent); -void SP_func_breakable (gentity_t *self); -void SP_func_glass( gentity_t *self ); -void SP_func_pendulum( gentity_t *ent ); -void SP_func_button (gentity_t *ent); -void SP_func_door (gentity_t *ent); -void SP_func_train (gentity_t *ent); -void SP_func_timer (gentity_t *self); -void SP_func_wall (gentity_t *ent); -void SP_func_usable( gentity_t *self ); - - -void SP_trigger_always (gentity_t *ent); -void SP_trigger_multiple (gentity_t *ent); -void SP_trigger_once (gentity_t *ent); -void SP_trigger_push (gentity_t *ent); -void SP_trigger_teleport (gentity_t *ent); -void SP_trigger_hurt (gentity_t *ent); -void SP_trigger_bidirectional (gentity_t *ent); -void SP_trigger_entdist (gentity_t *self); -void SP_trigger_location( gentity_t *ent ); -void SP_trigger_visible( gentity_t *self ); - -void SP_target_give (gentity_t *ent); -void SP_target_delay (gentity_t *ent); -void SP_target_speaker (gentity_t *ent); -void SP_target_print (gentity_t *ent); -void SP_target_laser (gentity_t *self); -void SP_target_character (gentity_t *ent); -void SP_target_score( gentity_t *ent ); -void SP_target_teleporter( gentity_t *ent ); -void SP_target_relay (gentity_t *ent); -void SP_target_kill (gentity_t *ent); -void SP_target_position (gentity_t *ent); -void SP_target_location (gentity_t *ent); -void SP_target_push (gentity_t *ent); -void SP_target_random (gentity_t *self); -void SP_target_counter (gentity_t *self); -void SP_target_scriptrunner (gentity_t *self); -void SP_target_interest (gentity_t *self); -void SP_target_activate (gentity_t *self); -void SP_target_deactivate (gentity_t *self); -void SP_target_gravity_change( gentity_t *self ); -void SP_target_friction_change( gentity_t *self ); -void SP_target_level_change( gentity_t *self ); -void SP_target_change_parm( gentity_t *self ); -void SP_target_play_music( gentity_t *self ); -void SP_target_autosave( gentity_t *self ); -void SP_target_secret( gentity_t *self ); - -void SP_light (gentity_t *self); -void SP_info_null (gentity_t *self); -void SP_info_notnull (gentity_t *self); -void SP_path_corner (gentity_t *self); - -void SP_misc_teleporter (gentity_t *self); -void SP_misc_teleporter_dest (gentity_t *self); +void SP_func_plat(gentity_t *ent); +void SP_func_static(gentity_t *ent); +void SP_func_rotating(gentity_t *ent); +void SP_func_bobbing(gentity_t *ent); +void SP_func_breakable(gentity_t *self); +void SP_func_glass(gentity_t *self); +void SP_func_pendulum(gentity_t *ent); +void SP_func_button(gentity_t *ent); +void SP_func_door(gentity_t *ent); +void SP_func_train(gentity_t *ent); +void SP_func_timer(gentity_t *self); +void SP_func_wall(gentity_t *ent); +void SP_func_usable(gentity_t *self); + +void SP_trigger_always(gentity_t *ent); +void SP_trigger_multiple(gentity_t *ent); +void SP_trigger_once(gentity_t *ent); +void SP_trigger_push(gentity_t *ent); +void SP_trigger_teleport(gentity_t *ent); +void SP_trigger_hurt(gentity_t *ent); +void SP_trigger_bidirectional(gentity_t *ent); +void SP_trigger_entdist(gentity_t *self); +void SP_trigger_location(gentity_t *ent); +void SP_trigger_visible(gentity_t *self); + +void SP_target_give(gentity_t *ent); +void SP_target_delay(gentity_t *ent); +void SP_target_speaker(gentity_t *ent); +void SP_target_print(gentity_t *ent); +void SP_target_laser(gentity_t *self); +void SP_target_character(gentity_t *ent); +void SP_target_score(gentity_t *ent); +void SP_target_teleporter(gentity_t *ent); +void SP_target_relay(gentity_t *ent); +void SP_target_kill(gentity_t *ent); +void SP_target_position(gentity_t *ent); +void SP_target_location(gentity_t *ent); +void SP_target_push(gentity_t *ent); +void SP_target_random(gentity_t *self); +void SP_target_counter(gentity_t *self); +void SP_target_scriptrunner(gentity_t *self); +void SP_target_interest(gentity_t *self); +void SP_target_activate(gentity_t *self); +void SP_target_deactivate(gentity_t *self); +void SP_target_gravity_change(gentity_t *self); +void SP_target_friction_change(gentity_t *self); +void SP_target_level_change(gentity_t *self); +void SP_target_change_parm(gentity_t *self); +void SP_target_play_music(gentity_t *self); +void SP_target_autosave(gentity_t *self); +void SP_target_secret(gentity_t *self); + +void SP_light(gentity_t *self); +void SP_info_null(gentity_t *self); +void SP_info_notnull(gentity_t *self); +void SP_path_corner(gentity_t *self); + +void SP_misc_teleporter(gentity_t *self); +void SP_misc_teleporter_dest(gentity_t *self); void SP_misc_model(gentity_t *ent); -void SP_misc_turret (gentity_t *base); -void SP_misc_ns_turret (gentity_t *base); -void SP_laser_arm (gentity_t *base); -void SP_misc_ion_cannon( gentity_t *ent ); -void SP_misc_maglock( gentity_t *ent ); -void SP_misc_panel_turret( gentity_t *ent ); -void SP_misc_model_welder( gentity_t *ent ); -void SP_misc_model_jabba_cam( gentity_t *ent ); - -void SP_misc_model_shield_power_converter( gentity_t *ent ); -void SP_misc_model_ammo_power_converter( gentity_t *ent ); - -void SP_misc_shield_floor_unit( gentity_t *ent ); -void SP_misc_ammo_floor_unit( gentity_t *ent ); - -void SP_misc_model_gun_rack( gentity_t *ent ); -void SP_misc_model_ammo_rack( gentity_t *ent ); -void SP_misc_model_cargo_small( gentity_t *ent ); - -void SP_misc_exploding_crate( gentity_t *ent ); -void SP_misc_gas_tank( gentity_t *ent ); -void SP_misc_crystal_crate( gentity_t *ent ); -void SP_misc_atst_drivable( gentity_t *ent ); - -void SP_misc_model_breakable(gentity_t *ent);//stays as an ent -void SP_misc_model_ghoul(gentity_t *ent);//stays as an ent +void SP_misc_turret(gentity_t *base); +void SP_misc_ns_turret(gentity_t *base); +void SP_laser_arm(gentity_t *base); +void SP_misc_ion_cannon(gentity_t *ent); +void SP_misc_maglock(gentity_t *ent); +void SP_misc_panel_turret(gentity_t *ent); +void SP_misc_model_welder(gentity_t *ent); +void SP_misc_model_jabba_cam(gentity_t *ent); + +void SP_misc_model_shield_power_converter(gentity_t *ent); +void SP_misc_model_ammo_power_converter(gentity_t *ent); + +void SP_misc_shield_floor_unit(gentity_t *ent); +void SP_misc_ammo_floor_unit(gentity_t *ent); + +void SP_misc_model_gun_rack(gentity_t *ent); +void SP_misc_model_ammo_rack(gentity_t *ent); +void SP_misc_model_cargo_small(gentity_t *ent); + +void SP_misc_exploding_crate(gentity_t *ent); +void SP_misc_gas_tank(gentity_t *ent); +void SP_misc_crystal_crate(gentity_t *ent); +void SP_misc_atst_drivable(gentity_t *ent); + +void SP_misc_model_breakable(gentity_t *ent); // stays as an ent +void SP_misc_model_ghoul(gentity_t *ent); // stays as an ent void SP_misc_portal_camera(gentity_t *ent); void SP_misc_portal_surface(gentity_t *ent); -void SP_misc_camera_focus (gentity_t *self); -void SP_misc_camera_track (gentity_t *self); -void SP_misc_dlight (gentity_t *ent); -void SP_misc_security_panel (gentity_t *ent); -void SP_misc_camera( gentity_t *ent ); -void SP_misc_spotlight( gentity_t *ent ); - -void SP_misc_cubemap( gentity_t *ent ); - -void SP_shooter_rocket( gentity_t *ent ); -void SP_shooter_plasma( gentity_t *ent ); -void SP_shooter_grenade( gentity_t *ent ); -void SP_misc_replicator_item( gentity_t *ent ); -void SP_misc_trip_mine( gentity_t *self ); -void SP_PAS( gentity_t *ent ); - -//New spawn functions -void SP_reference_tag ( gentity_t *ent ); - -void SP_NPC_spawner( gentity_t *self ); - -void SP_NPC_Kyle( gentity_t *self ); -void SP_NPC_Lando( gentity_t *self ); -void SP_NPC_Jan( gentity_t *self ); -void SP_NPC_Luke( gentity_t *self ); -void SP_NPC_MonMothma( gentity_t *self ); -void SP_NPC_Tavion( gentity_t *self ); -void SP_NPC_Reelo( gentity_t *self ); -void SP_NPC_Galak( gentity_t *self ); -void SP_NPC_Desann( gentity_t *self ); -void SP_NPC_Bartender( gentity_t *self ); -void SP_NPC_MorganKatarn( gentity_t *self ); -void SP_NPC_Jedi( gentity_t *self ); -void SP_NPC_Prisoner( gentity_t *self ); -void SP_NPC_Rebel( gentity_t *self ); -void SP_NPC_Stormtrooper( gentity_t *self ); -void SP_NPC_StormtrooperOfficer( gentity_t *self ); -void SP_NPC_Tie_Pilot( gentity_t *self ); -void SP_NPC_Ugnaught( gentity_t *self ); -void SP_NPC_Gran( gentity_t *self ); -void SP_NPC_Rodian( gentity_t *self ); -void SP_NPC_Weequay( gentity_t *self ); -void SP_NPC_Trandoshan( gentity_t *self ); -void SP_NPC_SwampTrooper( gentity_t *self ); -void SP_NPC_Imperial( gentity_t *self ); -void SP_NPC_ImpWorker( gentity_t *self ); -void SP_NPC_BespinCop( gentity_t *self ); -void SP_NPC_Reborn( gentity_t *self ); -void SP_NPC_ShadowTrooper( gentity_t *self ); -void SP_NPC_Monster_Murjj( gentity_t *self ); -void SP_NPC_Monster_Swamp( gentity_t *self ); -void SP_NPC_Monster_Howler( gentity_t *self ); -void SP_NPC_Monster_Claw( gentity_t *self ); -void SP_NPC_Monster_Glider( gentity_t *self ); -void SP_NPC_Monster_Flier2( gentity_t *self ); -void SP_NPC_Monster_Lizard( gentity_t *self ); -void SP_NPC_Monster_Fish( gentity_t *self ); -void SP_NPC_MineMonster( gentity_t *self ); -void SP_NPC_Droid_Interrogator( gentity_t *self ); -void SP_NPC_Droid_Probe( gentity_t *self ); -void SP_NPC_Droid_Mark1( gentity_t *self ); -void SP_NPC_Droid_Mark2( gentity_t *self ); -void SP_NPC_Droid_ATST( gentity_t *self ); -void SP_NPC_Droid_Seeker( gentity_t *self ); -void SP_NPC_Droid_Remote( gentity_t *self ); -void SP_NPC_Droid_Sentry( gentity_t *self ); -void SP_NPC_Droid_Gonk( gentity_t *self ); -void SP_NPC_Droid_Mouse( gentity_t *self ); -void SP_NPC_Droid_R2D2( gentity_t *self ); -void SP_NPC_Droid_R5D2( gentity_t *self ); -void SP_NPC_Droid_Protocol( gentity_t *self ); - -void SP_waypoint (gentity_t *ent); -void SP_waypoint_small (gentity_t *ent); -void SP_waypoint_navgoal (gentity_t *ent); -void SP_waypoint_navgoal_8 (gentity_t *ent); -void SP_waypoint_navgoal_4 (gentity_t *ent); -void SP_waypoint_navgoal_2 (gentity_t *ent); -void SP_waypoint_navgoal_1 (gentity_t *ent); - -void SP_fx_runner( gentity_t *ent ); -void SP_fx_explosion_trail( gentity_t *ent ); -void SP_fx_target_beam( gentity_t *ent ); -void SP_fx_cloudlayer( gentity_t *ent ); - -void SP_CreateSnow( gentity_t *ent ); -void SP_CreateRain( gentity_t *ent ); - -void SP_object_cargo_barrel1( gentity_t *ent ); - -void SP_point_combat (gentity_t *self); - -void SP_emplaced_gun( gentity_t *self ); - -spawn_t spawns[] = { - {"info_player_start", SP_info_player_start}, - {"info_player_deathmatch", SP_info_player_deathmatch}, - - {"func_plat", SP_func_plat}, - {"func_button", SP_func_button}, - {"func_door", SP_func_door}, - {"func_static", SP_func_static}, - {"func_rotating", SP_func_rotating}, - {"func_bobbing", SP_func_bobbing}, - {"func_breakable", SP_func_breakable}, - {"func_pendulum", SP_func_pendulum}, - {"func_train", SP_func_train}, - {"func_timer", SP_func_timer}, // rename trigger_timer? - {"func_wall", SP_func_wall}, - {"func_usable", SP_func_usable}, - {"func_glass", SP_func_glass}, - - {"trigger_always", SP_trigger_always}, - {"trigger_multiple", SP_trigger_multiple}, - {"trigger_once", SP_trigger_once}, - {"trigger_push", SP_trigger_push}, - {"trigger_teleport", SP_trigger_teleport}, - {"trigger_hurt", SP_trigger_hurt}, - {"trigger_bidirectional", SP_trigger_bidirectional}, - {"trigger_entdist", SP_trigger_entdist}, - {"trigger_location", SP_trigger_location}, - {"trigger_visible", SP_trigger_visible}, - - {"target_give", SP_target_give}, - {"target_delay", SP_target_delay}, - {"target_speaker", SP_target_speaker}, - {"target_print", SP_target_print}, - {"target_laser", SP_target_laser}, - {"target_score", SP_target_score}, - {"target_teleporter", SP_target_teleporter}, - {"target_relay", SP_target_relay}, - {"target_kill", SP_target_kill}, - {"target_position", SP_target_position}, - {"target_location", SP_target_location}, - {"target_push", SP_target_push}, - {"target_random", SP_target_random}, - {"target_counter", SP_target_counter}, - {"target_scriptrunner", SP_target_scriptrunner}, - {"target_interest", SP_target_interest}, - {"target_activate", SP_target_activate}, - {"target_deactivate", SP_target_deactivate}, - {"target_gravity_change", SP_target_gravity_change}, - {"target_friction_change", SP_target_friction_change}, - {"target_level_change", SP_target_level_change}, - {"target_change_parm", SP_target_change_parm}, - {"target_play_music", SP_target_play_music}, - {"target_autosave", SP_target_autosave}, - {"target_secret", SP_target_secret}, - - {"light", SP_light}, - {"info_null", SP_info_null}, - {"func_group", SP_info_null}, - {"info_notnull", SP_info_notnull}, // use target_position instead - {"path_corner", SP_path_corner}, - - {"misc_teleporter", SP_misc_teleporter}, - {"misc_teleporter_dest", SP_misc_teleporter_dest}, - {"misc_model", SP_misc_model}, - {"misc_turret", SP_misc_turret}, - {"misc_ns_turret", SP_misc_ns_turret}, - {"misc_laser_arm", SP_laser_arm}, - {"misc_ion_cannon", SP_misc_ion_cannon}, - {"misc_sentry_turret", SP_PAS}, - {"misc_maglock", SP_misc_maglock}, - - {"misc_model_ghoul", SP_misc_model_ghoul}, - {"misc_model_breakable", SP_misc_model_breakable}, - {"misc_portal_surface", SP_misc_portal_surface}, - {"misc_portal_camera", SP_misc_portal_camera}, - {"misc_camera_focus", SP_misc_camera_focus}, - {"misc_camera_track", SP_misc_camera_track}, - {"misc_dlight", SP_misc_dlight}, - {"misc_replicator_item", SP_misc_replicator_item}, - {"misc_trip_mine", SP_misc_trip_mine}, - {"misc_security_panel", SP_misc_security_panel}, - {"misc_camera", SP_misc_camera}, - {"misc_spotlight", SP_misc_spotlight}, - {"misc_panel_turret", SP_misc_panel_turret}, - {"misc_model_welder", SP_misc_model_welder}, - {"misc_model_jabba_cam", SP_misc_model_jabba_cam}, - {"misc_model_shield_power_converter", SP_misc_model_shield_power_converter}, - {"misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter}, - {"misc_shield_floor_unit", SP_misc_shield_floor_unit}, - {"misc_ammo_floor_unit", SP_misc_ammo_floor_unit}, - - {"misc_model_gun_rack", SP_misc_model_gun_rack}, - {"misc_model_ammo_rack", SP_misc_model_ammo_rack}, - {"misc_model_cargo_small", SP_misc_model_cargo_small}, - - {"misc_exploding_crate", SP_misc_exploding_crate}, - {"misc_gas_tank", SP_misc_gas_tank}, - {"misc_crystal_crate", SP_misc_crystal_crate}, - {"misc_atst_drivable", SP_misc_atst_drivable}, - - {"misc_cubemap", SP_misc_cubemap}, - - {"shooter_rocket", SP_shooter_rocket}, - {"shooter_grenade", SP_shooter_grenade}, - {"shooter_plasma", SP_shooter_plasma}, - - {"ref_tag", SP_reference_tag}, - - //new NPC ents - {"NPC_spawner", SP_NPC_spawner}, - - {"NPC_Kyle", SP_NPC_Kyle }, - {"NPC_Lando", SP_NPC_Lando }, - {"NPC_Jan", SP_NPC_Jan }, - {"NPC_Luke", SP_NPC_Luke }, - {"NPC_MonMothma", SP_NPC_MonMothma }, - {"NPC_Tavion", SP_NPC_Tavion }, - {"NPC_Reelo", SP_NPC_Reelo }, - {"NPC_Galak", SP_NPC_Galak }, - {"NPC_Desann", SP_NPC_Desann }, - {"NPC_Bartender", SP_NPC_Bartender }, - {"NPC_MorganKatarn", SP_NPC_MorganKatarn }, - {"NPC_Jedi", SP_NPC_Jedi }, - {"NPC_Prisoner", SP_NPC_Prisoner }, - {"NPC_Rebel", SP_NPC_Rebel }, - {"NPC_Stormtrooper", SP_NPC_Stormtrooper }, - {"NPC_StormtrooperOfficer", SP_NPC_StormtrooperOfficer }, - {"NPC_Tie_Pilot", SP_NPC_Tie_Pilot }, - {"NPC_Ugnaught", SP_NPC_Ugnaught }, - {"NPC_Gran", SP_NPC_Gran }, - {"NPC_Rodian", SP_NPC_Rodian }, - {"NPC_Weequay", SP_NPC_Weequay }, - {"NPC_Trandoshan", SP_NPC_Trandoshan }, - {"NPC_SwampTrooper", SP_NPC_SwampTrooper }, - {"NPC_Imperial", SP_NPC_Imperial }, - {"NPC_ImpWorker", SP_NPC_ImpWorker }, - {"NPC_BespinCop", SP_NPC_BespinCop }, - {"NPC_Reborn", SP_NPC_Reborn }, - {"NPC_ShadowTrooper", SP_NPC_ShadowTrooper }, - {"NPC_Monster_Murjj", SP_NPC_Monster_Murjj }, - {"NPC_Monster_Swamp", SP_NPC_Monster_Swamp }, - {"NPC_Monster_Howler", SP_NPC_Monster_Howler }, - {"NPC_MineMonster", SP_NPC_MineMonster }, - {"NPC_Monster_Claw", SP_NPC_Monster_Claw }, - {"NPC_Monster_Glider", SP_NPC_Monster_Glider }, - {"NPC_Monster_Flier2", SP_NPC_Monster_Flier2 }, - {"NPC_Monster_Lizard", SP_NPC_Monster_Lizard }, - {"NPC_Monster_Fish", SP_NPC_Monster_Fish }, - {"NPC_Droid_Interrogator", SP_NPC_Droid_Interrogator }, - {"NPC_Droid_Probe", SP_NPC_Droid_Probe }, - {"NPC_Droid_Mark1", SP_NPC_Droid_Mark1 }, - {"NPC_Droid_Mark2", SP_NPC_Droid_Mark2 }, - {"NPC_Droid_ATST", SP_NPC_Droid_ATST }, - {"NPC_Droid_Seeker", SP_NPC_Droid_Seeker }, - {"NPC_Droid_Remote", SP_NPC_Droid_Remote }, - {"NPC_Droid_Sentry", SP_NPC_Droid_Sentry }, - {"NPC_Droid_Gonk", SP_NPC_Droid_Gonk }, - {"NPC_Droid_Mouse", SP_NPC_Droid_Mouse }, - {"NPC_Droid_R2D2", SP_NPC_Droid_R2D2 }, - {"NPC_Droid_R5D2", SP_NPC_Droid_R5D2 }, - {"NPC_Droid_Protocol", SP_NPC_Droid_Protocol }, - - {"waypoint", SP_waypoint}, - {"waypoint_small", SP_waypoint_small}, - {"waypoint_navgoal", SP_waypoint_navgoal}, - {"waypoint_navgoal_8", SP_waypoint_navgoal_8}, - {"waypoint_navgoal_4", SP_waypoint_navgoal_4}, - {"waypoint_navgoal_2", SP_waypoint_navgoal_2}, - {"waypoint_navgoal_1", SP_waypoint_navgoal_1}, - - {"fx_runner", SP_fx_runner}, - {"fx_explosion_trail", SP_fx_explosion_trail}, - {"fx_target_beam", SP_fx_target_beam}, - {"fx_cloudlayer", SP_fx_cloudlayer}, - {"fx_rain", SP_CreateRain}, - {"fx_snow", SP_CreateSnow}, - - {"object_cargo_barrel1", SP_object_cargo_barrel1}, - {"point_combat", SP_point_combat}, - - {"emplaced_gun", SP_emplaced_gun}, - - {NULL, NULL} -}; +void SP_misc_camera_focus(gentity_t *self); +void SP_misc_camera_track(gentity_t *self); +void SP_misc_dlight(gentity_t *ent); +void SP_misc_security_panel(gentity_t *ent); +void SP_misc_camera(gentity_t *ent); +void SP_misc_spotlight(gentity_t *ent); + +void SP_misc_cubemap(gentity_t *ent); + +void SP_shooter_rocket(gentity_t *ent); +void SP_shooter_plasma(gentity_t *ent); +void SP_shooter_grenade(gentity_t *ent); +void SP_misc_replicator_item(gentity_t *ent); +void SP_misc_trip_mine(gentity_t *self); +void SP_PAS(gentity_t *ent); + +// New spawn functions +void SP_reference_tag(gentity_t *ent); + +void SP_NPC_spawner(gentity_t *self); + +void SP_NPC_Kyle(gentity_t *self); +void SP_NPC_Lando(gentity_t *self); +void SP_NPC_Jan(gentity_t *self); +void SP_NPC_Luke(gentity_t *self); +void SP_NPC_MonMothma(gentity_t *self); +void SP_NPC_Tavion(gentity_t *self); +void SP_NPC_Reelo(gentity_t *self); +void SP_NPC_Galak(gentity_t *self); +void SP_NPC_Desann(gentity_t *self); +void SP_NPC_Bartender(gentity_t *self); +void SP_NPC_MorganKatarn(gentity_t *self); +void SP_NPC_Jedi(gentity_t *self); +void SP_NPC_Prisoner(gentity_t *self); +void SP_NPC_Rebel(gentity_t *self); +void SP_NPC_Stormtrooper(gentity_t *self); +void SP_NPC_StormtrooperOfficer(gentity_t *self); +void SP_NPC_Tie_Pilot(gentity_t *self); +void SP_NPC_Ugnaught(gentity_t *self); +void SP_NPC_Gran(gentity_t *self); +void SP_NPC_Rodian(gentity_t *self); +void SP_NPC_Weequay(gentity_t *self); +void SP_NPC_Trandoshan(gentity_t *self); +void SP_NPC_SwampTrooper(gentity_t *self); +void SP_NPC_Imperial(gentity_t *self); +void SP_NPC_ImpWorker(gentity_t *self); +void SP_NPC_BespinCop(gentity_t *self); +void SP_NPC_Reborn(gentity_t *self); +void SP_NPC_ShadowTrooper(gentity_t *self); +void SP_NPC_Monster_Murjj(gentity_t *self); +void SP_NPC_Monster_Swamp(gentity_t *self); +void SP_NPC_Monster_Howler(gentity_t *self); +void SP_NPC_Monster_Claw(gentity_t *self); +void SP_NPC_Monster_Glider(gentity_t *self); +void SP_NPC_Monster_Flier2(gentity_t *self); +void SP_NPC_Monster_Lizard(gentity_t *self); +void SP_NPC_Monster_Fish(gentity_t *self); +void SP_NPC_MineMonster(gentity_t *self); +void SP_NPC_Droid_Interrogator(gentity_t *self); +void SP_NPC_Droid_Probe(gentity_t *self); +void SP_NPC_Droid_Mark1(gentity_t *self); +void SP_NPC_Droid_Mark2(gentity_t *self); +void SP_NPC_Droid_ATST(gentity_t *self); +void SP_NPC_Droid_Seeker(gentity_t *self); +void SP_NPC_Droid_Remote(gentity_t *self); +void SP_NPC_Droid_Sentry(gentity_t *self); +void SP_NPC_Droid_Gonk(gentity_t *self); +void SP_NPC_Droid_Mouse(gentity_t *self); +void SP_NPC_Droid_R2D2(gentity_t *self); +void SP_NPC_Droid_R5D2(gentity_t *self); +void SP_NPC_Droid_Protocol(gentity_t *self); + +void SP_waypoint(gentity_t *ent); +void SP_waypoint_small(gentity_t *ent); +void SP_waypoint_navgoal(gentity_t *ent); +void SP_waypoint_navgoal_8(gentity_t *ent); +void SP_waypoint_navgoal_4(gentity_t *ent); +void SP_waypoint_navgoal_2(gentity_t *ent); +void SP_waypoint_navgoal_1(gentity_t *ent); + +void SP_fx_runner(gentity_t *ent); +void SP_fx_explosion_trail(gentity_t *ent); +void SP_fx_target_beam(gentity_t *ent); +void SP_fx_cloudlayer(gentity_t *ent); + +void SP_CreateSnow(gentity_t *ent); +void SP_CreateRain(gentity_t *ent); + +void SP_object_cargo_barrel1(gentity_t *ent); + +void SP_point_combat(gentity_t *self); + +void SP_emplaced_gun(gentity_t *self); + +spawn_t spawns[] = {{"info_player_start", SP_info_player_start}, + {"info_player_deathmatch", SP_info_player_deathmatch}, + + {"func_plat", SP_func_plat}, + {"func_button", SP_func_button}, + {"func_door", SP_func_door}, + {"func_static", SP_func_static}, + {"func_rotating", SP_func_rotating}, + {"func_bobbing", SP_func_bobbing}, + {"func_breakable", SP_func_breakable}, + {"func_pendulum", SP_func_pendulum}, + {"func_train", SP_func_train}, + {"func_timer", SP_func_timer}, // rename trigger_timer? + {"func_wall", SP_func_wall}, + {"func_usable", SP_func_usable}, + {"func_glass", SP_func_glass}, + + {"trigger_always", SP_trigger_always}, + {"trigger_multiple", SP_trigger_multiple}, + {"trigger_once", SP_trigger_once}, + {"trigger_push", SP_trigger_push}, + {"trigger_teleport", SP_trigger_teleport}, + {"trigger_hurt", SP_trigger_hurt}, + {"trigger_bidirectional", SP_trigger_bidirectional}, + {"trigger_entdist", SP_trigger_entdist}, + {"trigger_location", SP_trigger_location}, + {"trigger_visible", SP_trigger_visible}, + + {"target_give", SP_target_give}, + {"target_delay", SP_target_delay}, + {"target_speaker", SP_target_speaker}, + {"target_print", SP_target_print}, + {"target_laser", SP_target_laser}, + {"target_score", SP_target_score}, + {"target_teleporter", SP_target_teleporter}, + {"target_relay", SP_target_relay}, + {"target_kill", SP_target_kill}, + {"target_position", SP_target_position}, + {"target_location", SP_target_location}, + {"target_push", SP_target_push}, + {"target_random", SP_target_random}, + {"target_counter", SP_target_counter}, + {"target_scriptrunner", SP_target_scriptrunner}, + {"target_interest", SP_target_interest}, + {"target_activate", SP_target_activate}, + {"target_deactivate", SP_target_deactivate}, + {"target_gravity_change", SP_target_gravity_change}, + {"target_friction_change", SP_target_friction_change}, + {"target_level_change", SP_target_level_change}, + {"target_change_parm", SP_target_change_parm}, + {"target_play_music", SP_target_play_music}, + {"target_autosave", SP_target_autosave}, + {"target_secret", SP_target_secret}, + + {"light", SP_light}, + {"info_null", SP_info_null}, + {"func_group", SP_info_null}, + {"info_notnull", SP_info_notnull}, // use target_position instead + {"path_corner", SP_path_corner}, + + {"misc_teleporter", SP_misc_teleporter}, + {"misc_teleporter_dest", SP_misc_teleporter_dest}, + {"misc_model", SP_misc_model}, + {"misc_turret", SP_misc_turret}, + {"misc_ns_turret", SP_misc_ns_turret}, + {"misc_laser_arm", SP_laser_arm}, + {"misc_ion_cannon", SP_misc_ion_cannon}, + {"misc_sentry_turret", SP_PAS}, + {"misc_maglock", SP_misc_maglock}, + + {"misc_model_ghoul", SP_misc_model_ghoul}, + {"misc_model_breakable", SP_misc_model_breakable}, + {"misc_portal_surface", SP_misc_portal_surface}, + {"misc_portal_camera", SP_misc_portal_camera}, + {"misc_camera_focus", SP_misc_camera_focus}, + {"misc_camera_track", SP_misc_camera_track}, + {"misc_dlight", SP_misc_dlight}, + {"misc_replicator_item", SP_misc_replicator_item}, + {"misc_trip_mine", SP_misc_trip_mine}, + {"misc_security_panel", SP_misc_security_panel}, + {"misc_camera", SP_misc_camera}, + {"misc_spotlight", SP_misc_spotlight}, + {"misc_panel_turret", SP_misc_panel_turret}, + {"misc_model_welder", SP_misc_model_welder}, + {"misc_model_jabba_cam", SP_misc_model_jabba_cam}, + {"misc_model_shield_power_converter", SP_misc_model_shield_power_converter}, + {"misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter}, + {"misc_shield_floor_unit", SP_misc_shield_floor_unit}, + {"misc_ammo_floor_unit", SP_misc_ammo_floor_unit}, + + {"misc_model_gun_rack", SP_misc_model_gun_rack}, + {"misc_model_ammo_rack", SP_misc_model_ammo_rack}, + {"misc_model_cargo_small", SP_misc_model_cargo_small}, + + {"misc_exploding_crate", SP_misc_exploding_crate}, + {"misc_gas_tank", SP_misc_gas_tank}, + {"misc_crystal_crate", SP_misc_crystal_crate}, + {"misc_atst_drivable", SP_misc_atst_drivable}, + + {"misc_cubemap", SP_misc_cubemap}, + + {"shooter_rocket", SP_shooter_rocket}, + {"shooter_grenade", SP_shooter_grenade}, + {"shooter_plasma", SP_shooter_plasma}, + + {"ref_tag", SP_reference_tag}, + + // new NPC ents + {"NPC_spawner", SP_NPC_spawner}, + + {"NPC_Kyle", SP_NPC_Kyle}, + {"NPC_Lando", SP_NPC_Lando}, + {"NPC_Jan", SP_NPC_Jan}, + {"NPC_Luke", SP_NPC_Luke}, + {"NPC_MonMothma", SP_NPC_MonMothma}, + {"NPC_Tavion", SP_NPC_Tavion}, + {"NPC_Reelo", SP_NPC_Reelo}, + {"NPC_Galak", SP_NPC_Galak}, + {"NPC_Desann", SP_NPC_Desann}, + {"NPC_Bartender", SP_NPC_Bartender}, + {"NPC_MorganKatarn", SP_NPC_MorganKatarn}, + {"NPC_Jedi", SP_NPC_Jedi}, + {"NPC_Prisoner", SP_NPC_Prisoner}, + {"NPC_Rebel", SP_NPC_Rebel}, + {"NPC_Stormtrooper", SP_NPC_Stormtrooper}, + {"NPC_StormtrooperOfficer", SP_NPC_StormtrooperOfficer}, + {"NPC_Tie_Pilot", SP_NPC_Tie_Pilot}, + {"NPC_Ugnaught", SP_NPC_Ugnaught}, + {"NPC_Gran", SP_NPC_Gran}, + {"NPC_Rodian", SP_NPC_Rodian}, + {"NPC_Weequay", SP_NPC_Weequay}, + {"NPC_Trandoshan", SP_NPC_Trandoshan}, + {"NPC_SwampTrooper", SP_NPC_SwampTrooper}, + {"NPC_Imperial", SP_NPC_Imperial}, + {"NPC_ImpWorker", SP_NPC_ImpWorker}, + {"NPC_BespinCop", SP_NPC_BespinCop}, + {"NPC_Reborn", SP_NPC_Reborn}, + {"NPC_ShadowTrooper", SP_NPC_ShadowTrooper}, + {"NPC_Monster_Murjj", SP_NPC_Monster_Murjj}, + {"NPC_Monster_Swamp", SP_NPC_Monster_Swamp}, + {"NPC_Monster_Howler", SP_NPC_Monster_Howler}, + {"NPC_MineMonster", SP_NPC_MineMonster}, + {"NPC_Monster_Claw", SP_NPC_Monster_Claw}, + {"NPC_Monster_Glider", SP_NPC_Monster_Glider}, + {"NPC_Monster_Flier2", SP_NPC_Monster_Flier2}, + {"NPC_Monster_Lizard", SP_NPC_Monster_Lizard}, + {"NPC_Monster_Fish", SP_NPC_Monster_Fish}, + {"NPC_Droid_Interrogator", SP_NPC_Droid_Interrogator}, + {"NPC_Droid_Probe", SP_NPC_Droid_Probe}, + {"NPC_Droid_Mark1", SP_NPC_Droid_Mark1}, + {"NPC_Droid_Mark2", SP_NPC_Droid_Mark2}, + {"NPC_Droid_ATST", SP_NPC_Droid_ATST}, + {"NPC_Droid_Seeker", SP_NPC_Droid_Seeker}, + {"NPC_Droid_Remote", SP_NPC_Droid_Remote}, + {"NPC_Droid_Sentry", SP_NPC_Droid_Sentry}, + {"NPC_Droid_Gonk", SP_NPC_Droid_Gonk}, + {"NPC_Droid_Mouse", SP_NPC_Droid_Mouse}, + {"NPC_Droid_R2D2", SP_NPC_Droid_R2D2}, + {"NPC_Droid_R5D2", SP_NPC_Droid_R5D2}, + {"NPC_Droid_Protocol", SP_NPC_Droid_Protocol}, + + {"waypoint", SP_waypoint}, + {"waypoint_small", SP_waypoint_small}, + {"waypoint_navgoal", SP_waypoint_navgoal}, + {"waypoint_navgoal_8", SP_waypoint_navgoal_8}, + {"waypoint_navgoal_4", SP_waypoint_navgoal_4}, + {"waypoint_navgoal_2", SP_waypoint_navgoal_2}, + {"waypoint_navgoal_1", SP_waypoint_navgoal_1}, + + {"fx_runner", SP_fx_runner}, + {"fx_explosion_trail", SP_fx_explosion_trail}, + {"fx_target_beam", SP_fx_target_beam}, + {"fx_cloudlayer", SP_fx_cloudlayer}, + {"fx_rain", SP_CreateRain}, + {"fx_snow", SP_CreateSnow}, + + {"object_cargo_barrel1", SP_object_cargo_barrel1}, + {"point_combat", SP_point_combat}, + + {"emplaced_gun", SP_emplaced_gun}, + + {NULL, NULL}}; /* =============== @@ -701,33 +684,33 @@ Finds the spawn function for the entity and calls it, returning qfalse if not found =============== */ -qboolean G_CallSpawn( gentity_t *ent ) { - spawn_t *s; - gitem_t *item; +qboolean G_CallSpawn(gentity_t *ent) { + spawn_t *s; + gitem_t *item; - if ( !ent->classname ) { - gi.Printf (S_COLOR_RED"G_CallSpawn: NULL classname\n"); + if (!ent->classname) { + gi.Printf(S_COLOR_RED "G_CallSpawn: NULL classname\n"); return qfalse; } // check item spawn functions - for ( item=bg_itemlist+1 ; item->classname ; item++ ) { - if ( !strcmp(item->classname, ent->classname) ) { + for (item = bg_itemlist + 1; item->classname; item++) { + if (!strcmp(item->classname, ent->classname)) { // found it - G_SpawnItem( ent, item ); + G_SpawnItem(ent, item); return qtrue; } } // check normal spawn functions - for ( s=spawns ; s->name ; s++ ) { - if ( !strcmp(s->name, ent->classname) ) { + for (s = spawns; s->name; s++) { + if (!strcmp(s->name, ent->classname)) { // found it s->spawn(ent); return qtrue; } } - gi.Printf (S_COLOR_RED"%s doesn't have a spawn function\n", ent->classname); + gi.Printf(S_COLOR_RED "%s doesn't have a spawn function\n", ent->classname); return qfalse; } @@ -739,25 +722,24 @@ Builds a copy of the string, translating \n to real linefeeds so message texts can be multi-line ============= */ -char *G_NewString( const char *string ) { - char *newb, *new_p; - int i,l; +char *G_NewString(const char *string) { + char *newb, *new_p; + int i, l; - if(!string || !string[0]) - { - //gi.Printf(S_COLOR_RED"Error: G_NewString called with NULL string!\n"); + if (!string || !string[0]) { + // gi.Printf(S_COLOR_RED"Error: G_NewString called with NULL string!\n"); return (char *)string; } l = strlen(string) + 1; - newb = (char *) G_Alloc( l ); + newb = (char *)G_Alloc(l); new_p = newb; // turn \n into a real linefeed - for ( i=0 ; i< l ; i++ ) { - if (string[i] == '\\' && i < l-1) { + for (i = 0; i < l; i++) { + if (string[i] == '\\' && i < l - 1) { i++; if (string[i] == 'n') { *new_p++ = '\n'; @@ -768,13 +750,10 @@ char *G_NewString( const char *string ) { *new_p++ = string[i]; } } - + return newb; } - - - /* =============== G_ParseField @@ -783,65 +762,61 @@ Takes a key/value pair and sets the binary values in a gentity =============== */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue); -void G_ParseField( const char *key, const char *value, gentity_t *ent ) { - field_t *f; - byte *b; - float v; - vec3_t vec; - vec4_t vec4; - - for ( f=fields ; f->name ; f++ ) { - if ( !Q_stricmp(f->name, key) ) { +void Q3_SetParm(int entID, int parmNum, const char *parmValue); +void G_ParseField(const char *key, const char *value, gentity_t *ent) { + field_t *f; + byte *b; + float v; + vec3_t vec; + vec4_t vec4; + + for (f = fields; f->name; f++) { + if (!Q_stricmp(f->name, key)) { // found it b = (byte *)ent; - switch( f->type ) { + switch (f->type) { case F_LSTRING: - *(char **)(b+f->ofs) = G_NewString (value); + *(char **)(b + f->ofs) = G_NewString(value); break; - case F_VECTOR: - { - int _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - assert(_iFieldsRead==3); - if (_iFieldsRead!=3) - { + case F_VECTOR: { + int _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + assert(_iFieldsRead == 3); + if (_iFieldsRead != 3) { #ifndef FINAL_BUILD - gi.Printf (S_COLOR_YELLOW"G_ParseField: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + gi.Printf(S_COLOR_YELLOW "G_ParseField: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); #endif } - ((float *)(b+f->ofs))[0] = vec[0]; - ((float *)(b+f->ofs))[1] = vec[1]; - ((float *)(b+f->ofs))[2] = vec[2]; + ((float *)(b + f->ofs))[0] = vec[0]; + ((float *)(b + f->ofs))[1] = vec[1]; + ((float *)(b + f->ofs))[2] = vec[2]; break; } - case F_VECTOR4: - { - int _iFieldsRead = sscanf (value, "%f %f %f %f", &vec4[0], &vec4[1], &vec4[2], &vec4[3]); - assert(_iFieldsRead==4); - if (_iFieldsRead!=4) - { + case F_VECTOR4: { + int _iFieldsRead = sscanf(value, "%f %f %f %f", &vec4[0], &vec4[1], &vec4[2], &vec4[3]); + assert(_iFieldsRead == 4); + if (_iFieldsRead != 4) { #ifndef FINAL_BUILD - gi.Printf (S_COLOR_YELLOW"G_ParseField: VEC4 sscanf() failed to read 4 floats\n"); + gi.Printf(S_COLOR_YELLOW "G_ParseField: VEC4 sscanf() failed to read 4 floats\n"); #endif } - ((float *)(b+f->ofs))[0] = vec4[0]; - ((float *)(b+f->ofs))[1] = vec4[1]; - ((float *)(b+f->ofs))[2] = vec4[2]; - ((float *)(b+f->ofs))[3] = vec4[3]; + ((float *)(b + f->ofs))[0] = vec4[0]; + ((float *)(b + f->ofs))[1] = vec4[1]; + ((float *)(b + f->ofs))[2] = vec4[2]; + ((float *)(b + f->ofs))[3] = vec4[3]; break; } case F_INT: - *(int *)(b+f->ofs) = atoi(value); + *(int *)(b + f->ofs) = atoi(value); break; case F_FLOAT: - *(float *)(b+f->ofs) = atof(value); + *(float *)(b + f->ofs) = atof(value); break; case F_ANGLEHACK: v = atof(value); - ((float *)(b+f->ofs))[0] = 0; - ((float *)(b+f->ofs))[1] = v; - ((float *)(b+f->ofs))[2] = 0; + ((float *)(b + f->ofs))[0] = 0; + ((float *)(b + f->ofs))[1] = v; + ((float *)(b + f->ofs))[2] = 0; break; case F_PARM1: case F_PARM2: @@ -859,24 +834,19 @@ void G_ParseField( const char *key, const char *value, gentity_t *ent ) { case F_PARM14: case F_PARM15: case F_PARM16: - Q3_SetParm( ent->s.number, (f->type - F_PARM1), (char *) value ); + Q3_SetParm(ent->s.number, (f->type - F_PARM1), (char *)value); break; - case F_FLAG: - {//try to find the proper flag for that key: - int flag = GetIDForString ( flagTable, key ); - - if ( flag > 0 ) - { - G_SpawnFlag( key, flag, (int *)(b+f->ofs) ); - } - else - { + case F_FLAG: { // try to find the proper flag for that key: + int flag = GetIDForString(flagTable, key); + + if (flag > 0) { + G_SpawnFlag(key, flag, (int *)(b + f->ofs)); + } else { #ifndef FINAL_BUILD - gi.Printf (S_COLOR_YELLOW"WARNING: G_ParseField: can't find flag for key %s\n", key); + gi.Printf(S_COLOR_YELLOW "WARNING: G_ParseField: can't find flag for key %s\n", key); #endif - } } - break; + } break; default: case F_IGNORE: break; @@ -885,18 +855,17 @@ void G_ParseField( const char *key, const char *value, gentity_t *ent ) { } } #ifndef FINAL_BUILD - //didn't find it? - gi.Printf ( S_COLOR_YELLOW"WARNING: G_ParseField: no such field: %s\n", key ); + // didn't find it? + gi.Printf(S_COLOR_YELLOW "WARNING: G_ParseField: no such field: %s\n", key); #endif } -static qboolean SpawnForCurrentDifficultySetting( gentity_t *ent ) -{ -extern cvar_t *com_buildScript; - if (com_buildScript->integer) { //always spawn when building a pak file +static qboolean SpawnForCurrentDifficultySetting(gentity_t *ent) { + extern cvar_t *com_buildScript; + if (com_buildScript->integer) { // always spawn when building a pak file return qtrue; } - if ( ent->spawnflags & ( 1 << (8 + g_spskill->integer )) ) {// easy -256 medium -512 hard -1024 + if (ent->spawnflags & (1 << (8 + g_spskill->integer))) { // easy -256 medium -512 hard -1024 return qfalse; } else { return qtrue; @@ -912,66 +881,61 @@ level.spawnVars[], then call the class specfic spawn function =================== */ -void G_SpawnGEntityFromSpawnVars( void ) { - int i; - gentity_t *ent; +void G_SpawnGEntityFromSpawnVars(void) { + int i; + gentity_t *ent; // get the next free entity ent = G_Spawn(); - for ( i = 0 ; i < numSpawnVars ; i++ ) { - G_ParseField( spawnVars[i][0], spawnVars[i][1], ent ); + for (i = 0; i < numSpawnVars; i++) { + G_ParseField(spawnVars[i][0], spawnVars[i][1], ent); } - G_SpawnInt( "notsingle", "0", &i ); - if ( i || !SpawnForCurrentDifficultySetting( ent ) ) { - G_FreeEntity( ent ); + G_SpawnInt("notsingle", "0", &i); + if (i || !SpawnForCurrentDifficultySetting(ent)) { + G_FreeEntity(ent); return; } // move editor origin to pos - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->currentOrigin); // if we didn't get a classname, don't bother spawning anything - if ( !G_CallSpawn( ent ) ) { - G_FreeEntity( ent ); + if (!G_CallSpawn(ent)) { + G_FreeEntity(ent); return; } - //Tag on the ICARUS scripting information only to valid recipients - if ( ICARUS_ValidEnt( ent ) ) - { - ICARUS_InitEnt( ent ); + // Tag on the ICARUS scripting information only to valid recipients + if (ICARUS_ValidEnt(ent)) { + ICARUS_InitEnt(ent); - if ( ent->classname && ent->classname[0] ) - { - if ( strncmp( "NPC_", ent->classname, 4 ) != 0 ) - {//Not an NPC_spawner - G_ActivateBehavior( ent, BSET_SPAWN ); + if (ent->classname && ent->classname[0]) { + if (strncmp("NPC_", ent->classname, 4) != 0) { // Not an NPC_spawner + G_ActivateBehavior(ent, BSET_SPAWN); } } } } - - /* ==================== G_AddSpawnVarToken ==================== */ -char *G_AddSpawnVarToken( const char *string ) { - int l; - char *dest; +char *G_AddSpawnVarToken(const char *string) { + int l; + char *dest; - l = strlen( string ); - if ( numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) { - G_Error( "G_AddSpawnVarToken: MAX_SPAWN_VARS" ); + l = strlen(string); + if (numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS) { + G_Error("G_AddSpawnVarToken: MAX_SPAWN_VARS"); } dest = spawnVarChars + numSpawnVarChars; - memcpy( dest, string, l+1 ); + memcpy(dest, string, l + 1); numSpawnVarChars += l + 1; @@ -988,56 +952,56 @@ level's entity strings into level.spawnVars[] This does not actually spawn an entity. ==================== */ -qboolean G_ParseSpawnVars( const char **data ) { - char keyname[MAX_STRING_CHARS]; - const char *com_token; +qboolean G_ParseSpawnVars(const char **data) { + char keyname[MAX_STRING_CHARS]; + const char *com_token; numSpawnVars = 0; numSpawnVarChars = 0; // parse the opening brace COM_BeginParseSession(); - com_token = COM_Parse( data ); - if ( !*data ) { + com_token = COM_Parse(data); + if (!*data) { // end of spawn string COM_EndParseSession(); return qfalse; } - if ( com_token[0] != '{' ) { + if (com_token[0] != '{') { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: found %s when expecting {",com_token ); + G_Error("G_ParseSpawnVars: found %s when expecting {", com_token); } // go through all the key / value pairs - while ( 1 ) { + while (1) { // parse key - com_token = COM_Parse( data ); - if ( com_token[0] == '}' ) { + com_token = COM_Parse(data); + if (com_token[0] == '}') { break; } - if ( !data ) { + if (!data) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: EOF without closing brace" ); + G_Error("G_ParseSpawnVars: EOF without closing brace"); } - Q_strncpyz( keyname, com_token, sizeof(keyname) ); - - // parse value - com_token = COM_Parse( data ); - if ( com_token[0] == '}' ) { + Q_strncpyz(keyname, com_token, sizeof(keyname)); + + // parse value + com_token = COM_Parse(data); + if (com_token[0] == '}') { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: closing brace without data" ); + G_Error("G_ParseSpawnVars: closing brace without data"); } - if ( !data ) { + if (!data) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: EOF without closing brace" ); + G_Error("G_ParseSpawnVars: EOF without closing brace"); } - if ( numSpawnVars == MAX_SPAWN_VARS ) { + if (numSpawnVars == MAX_SPAWN_VARS) { COM_EndParseSession(); - G_Error( "G_ParseSpawnVars: MAX_SPAWN_VARS" ); + G_Error("G_ParseSpawnVars: MAX_SPAWN_VARS"); } - spawnVars[ numSpawnVars ][0] = G_AddSpawnVarToken( keyname ); - spawnVars[ numSpawnVars ][1] = G_AddSpawnVarToken( com_token ); + spawnVars[numSpawnVars][0] = G_AddSpawnVarToken(keyname); + spawnVars[numSpawnVars][1] = G_AddSpawnVarToken(com_token); numSpawnVars++; } @@ -1045,170 +1009,72 @@ qboolean G_ParseSpawnVars( const char **data ) { return qtrue; } -static char *defaultStyles[LS_NUM_STYLES][3] = -{ - { // 0 normal - "z", - "z", - "z" - }, - { // 1 FLICKER (first variety) - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo" - }, - { // 2 SLOW STRONG PULSE - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb" - }, - { // 3 CANDLE (first variety) - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg" - }, - { // 4 FAST STROBE - "mamamamamama", - "mamamamamama", - "mamamamamama" - }, - { // 5 GENTLE PULSE 1 - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj" - }, - { // 6 FLICKER (second variety) - "nmonqnmomnmomomno", - "nmonqnmomnmomomno", - "nmonqnmomnmomomno" - }, - { // 7 CANDLE (second variety) - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm" - }, - { // 8 CANDLE (third variety) - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa" - }, - { // 9 SLOW STROBE (fourth variety) - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz" - }, - { // 10 FLUORESCENT FLICKER - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma" - }, - { // 11 SLOW PULSE NOT FADE TO BLACK - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba" - }, - { // 12 FAST PULSE FOR JEREMY - "mkigegik", - "mkigegik", - "mkigegik" - }, - { // 13 Test Blending - "abcdefghijklmqrstuvwxyz", - "zyxwvutsrqmlkjihgfedcba", - "aammbbzzccllcckkffyyggp" - }, - { // 14 - "", - "", - "" - }, - { // 15 - "", - "", - "" - }, - { // 16 - "", - "", - "" - }, - { // 17 - "", - "", - "" - }, - { // 18 - "", - "", - "" - }, - { // 19 - "", - "", - "" - }, - { // 20 - "", - "", - "" - }, - { // 21 - "", - "", - "" - }, - { // 22 - "", - "", - "" - }, - { // 23 - "", - "", - "" - }, - { // 24 - "", - "", - "" - }, - { // 25 - "", - "", - "" - }, - { // 26 - "", - "", - "" - }, - { // 27 - "", - "", - "" - }, - { // 28 - "", - "", - "" - }, - { // 29 - "", - "", - "" - }, - { // 30 - "", - "", - "" - }, - { // 31 - "", - "", - "" - } -}; - +static char *defaultStyles[LS_NUM_STYLES][3] = { + {// 0 normal + "z", "z", "z"}, + {// 1 FLICKER (first variety) + "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo"}, + {// 2 SLOW STRONG PULSE + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb"}, + {// 3 CANDLE (first variety) + "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg"}, + {// 4 FAST STROBE + "mamamamamama", "mamamamamama", "mamamamamama"}, + {// 5 GENTLE PULSE 1 + "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj"}, + {// 6 FLICKER (second variety) + "nmonqnmomnmomomno", "nmonqnmomnmomomno", "nmonqnmomnmomomno"}, + {// 7 CANDLE (second variety) + "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm"}, + {// 8 CANDLE (third variety) + "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa"}, + {// 9 SLOW STROBE (fourth variety) + "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz"}, + {// 10 FLUORESCENT FLICKER + "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma"}, + {// 11 SLOW PULSE NOT FADE TO BLACK + "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba"}, + {// 12 FAST PULSE FOR JEREMY + "mkigegik", "mkigegik", "mkigegik"}, + {// 13 Test Blending + "abcdefghijklmqrstuvwxyz", "zyxwvutsrqmlkjihgfedcba", "aammbbzzccllcckkffyyggp"}, + {// 14 + "", "", ""}, + {// 15 + "", "", ""}, + {// 16 + "", "", ""}, + {// 17 + "", "", ""}, + {// 18 + "", "", ""}, + {// 19 + "", "", ""}, + {// 20 + "", "", ""}, + {// 21 + "", "", ""}, + {// 22 + "", "", ""}, + {// 23 + "", "", ""}, + {// 24 + "", "", ""}, + {// 25 + "", "", ""}, + {// 26 + "", "", ""}, + {// 27 + "", "", ""}, + {// 28 + "", "", ""}, + {// 29 + "", "", ""}, + {// 30 + "", "", ""}, + {// 31 + "", "", ""}}; /*QUAKED worldspawn (0 0 0) ? Every map should have exactly one worldspawn. @@ -1228,76 +1094,69 @@ BSP Options "ls_Xg" green (valid patterns are "a-z") "ls_Xb" blue (a is OFF, z is ON) */ -void SP_worldspawn( void ) { - char *s; - int i; - - gi.cvar_set( "region", "0" ); - for ( i = 0 ; i < numSpawnVars ; i++ ) - { - if ( Q_stricmp( "spawnscript", spawnVars[i][0] ) == 0 ) - {//ONly let them set spawnscript, we don't want them setting an angle or something on the world. - G_ParseField( spawnVars[i][0], spawnVars[i][1], &g_entities[ENTITYNUM_WORLD] ); +void SP_worldspawn(void) { + char *s; + int i; + + gi.cvar_set("region", "0"); + for (i = 0; i < numSpawnVars; i++) { + if (Q_stricmp("spawnscript", spawnVars[i][0]) == 0) { // ONly let them set spawnscript, we don't want them setting an angle or something on the world. + G_ParseField(spawnVars[i][0], spawnVars[i][1], &g_entities[ENTITYNUM_WORLD]); } - if ( Q_stricmp( "region", spawnVars[i][0] ) == 0 ) - { + if (Q_stricmp("region", spawnVars[i][0]) == 0) { g_entities[ENTITYNUM_WORLD].s.radius = atoi(spawnVars[i][1]); - gi.cvar_set( "region", spawnVars[i][1] ); + gi.cvar_set("region", spawnVars[i][1]); } } - G_SpawnString( "classname", "", &s ); - if ( Q_stricmp( s, "worldspawn" ) ) { - G_Error( "SP_worldspawn: The first entity isn't 'worldspawn'" ); + G_SpawnString("classname", "", &s); + if (Q_stricmp(s, "worldspawn")) { + G_Error("SP_worldspawn: The first entity isn't 'worldspawn'"); } // make some data visible to connecting client - G_SpawnString( "music", "", &s ); - gi.SetConfigstring( CS_MUSIC, s ); + G_SpawnString("music", "", &s); + gi.SetConfigstring(CS_MUSIC, s); - G_SpawnString( "message", "", &s ); - gi.SetConfigstring( CS_MESSAGE, s ); // map specific message + G_SpawnString("message", "", &s); + gi.SetConfigstring(CS_MESSAGE, s); // map specific message - G_SpawnString( "gravity", "800", &s ); + G_SpawnString("gravity", "800", &s); extern SavedGameJustLoaded_e g_eSavedGameJustLoaded; - if (g_eSavedGameJustLoaded != eFULL) - { - gi.cvar_set( "g_gravity", s ); + if (g_eSavedGameJustLoaded != eFULL) { + gi.cvar_set("g_gravity", s); } - G_SpawnString( "soundSet", "default", &s ); - gi.SetConfigstring( CS_AMBIENT_SET, s ); + G_SpawnString("soundSet", "default", &s); + gi.SetConfigstring(CS_AMBIENT_SET, s); -//Lightstyles - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+0, defaultStyles[0][0]); - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+1, defaultStyles[0][1]); - gi.SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+2, defaultStyles[0][2]); + // Lightstyles + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 0, defaultStyles[0][0]); + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 1, defaultStyles[0][1]); + gi.SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 2, defaultStyles[0][2]); - for(i=1;iclear(); - for ( int i = 0; i < globals.num_entities; i++ ) - { + for (int i = 0; i < globals.num_entities; i++) { ent = &g_entities[i]; - if VALIDSTRING( ent->soundSet ) - { - (*as_preCacheMap)[ (char *) ent->soundSet ] = 1; + if VALIDSTRING (ent->soundSet) { + (*as_preCacheMap)[(char *)ent->soundSet] = 1; } } } -void G_ASPreCacheFree(void) -{ - if(as_preCacheMap) { +void G_ASPreCacheFree(void) { + if (as_preCacheMap) { delete as_preCacheMap; as_preCacheMap = NULL; } @@ -1347,13 +1202,13 @@ Parses textual entity definitions out of an entstring and spawns gentities. ============== */ extern int num_waypoints; -extern void RG_RouteGen(void); +extern void RG_RouteGen(void); extern qboolean NPCsPrecached; #ifndef FINAL_BUILD int delayedShutDown = 0; #endif -void G_SpawnEntitiesFromString( const char *entityString ) { - const char *entities; +void G_SpawnEntitiesFromString(const char *entityString) { + const char *entities; entities = entityString; @@ -1365,51 +1220,45 @@ void G_SpawnEntitiesFromString( const char *entityString ) { // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) - if ( !G_ParseSpawnVars( &entities ) ) { - G_Error( "SpawnEntities: no entities" ); + if (!G_ParseSpawnVars(&entities)) { + G_Error("SpawnEntities: no entities"); } - + SP_worldspawn(); // parse ents - while( G_ParseSpawnVars( &entities ) ) - { + while (G_ParseSpawnVars(&entities)) { G_SpawnGEntityFromSpawnVars(); - } + } - //Search the entities for precache information + // Search the entities for precache information G_ParsePrecaches(); - - if( g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0] ) - {//World has a spawn script, but we don't want the world in ICARUS and running scripts, - //so make a scriptrunner and start it going. + if (g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && + g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0]) { // World has a spawn script, but we don't want the world in ICARUS and running scripts, + // so make a scriptrunner and start it going. gentity_t *script_runner = G_Spawn(); - if ( script_runner ) - { + if (script_runner) { script_runner->behaviorSet[BSET_USE] = g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN]; script_runner->count = 1; script_runner->e_ThinkFunc = thinkF_scriptrunner_run; script_runner->nextthink = level.time + 100; - if ( ICARUS_ValidEnt( script_runner ) ) - { - ICARUS_InitEnt( script_runner ); + if (ICARUS_ValidEnt(script_runner)) { + ICARUS_InitEnt(script_runner); } } } - //gi.Printf(S_COLOR_YELLOW"Total waypoints: %d\n", num_waypoints); - //Automatically run routegen - //RG_RouteGen(); + // gi.Printf(S_COLOR_YELLOW"Total waypoints: %d\n", num_waypoints); + // Automatically run routegen + // RG_RouteGen(); - spawning = qfalse; // any future calls to G_Spawn*() will be errors + spawning = qfalse; // any future calls to G_Spawn*() will be errors #ifndef FINAL_BUILD - if ( delayedShutDown ) - { - G_Error( "Errors loading map, check the console for them." ); + if (delayedShutDown) { + G_Error("Errors loading map, check the console for them."); } #endif } - diff --git a/codeJK2/game/g_svcmds.cpp b/codeJK2/game/g_svcmds.cpp index 40d45801dc..ba592da57a 100644 --- a/codeJK2/game/g_svcmds.cpp +++ b/codeJK2/game/g_svcmds.cpp @@ -27,209 +27,179 @@ along with this program; if not, see . #include "wp_saber.h" extern void Q3_SetViewEntity(int entID, const char *name); -extern qboolean G_ClearViewEntity( gentity_t *ent ); +extern qboolean G_ClearViewEntity(gentity_t *ent); -extern team_t TranslateTeamName( const char *name ); -extern char *TeamNames[TEAM_NUM_TEAMS]; +extern team_t TranslateTeamName(const char *name); +extern char *TeamNames[TEAM_NUM_TEAMS]; /* =================== Svcmd_EntityList_f =================== */ -void Svcmd_EntityList_f (void) { - int e; - gentity_t *check; +void Svcmd_EntityList_f(void) { + int e; + gentity_t *check; check = g_entities; - for (e = 0; e < globals.num_entities ; e++, check++) { - if ( !check->inuse ) { + for (e = 0; e < globals.num_entities; e++, check++) { + if (!check->inuse) { continue; } gi.Printf("%3i:", e); - switch ( check->s.eType ) { + switch (check->s.eType) { case ET_GENERAL: - gi.Printf( "ET_GENERAL " ); + gi.Printf("ET_GENERAL "); break; case ET_PLAYER: - gi.Printf( "ET_PLAYER " ); + gi.Printf("ET_PLAYER "); break; case ET_ITEM: - gi.Printf( "ET_ITEM " ); + gi.Printf("ET_ITEM "); break; case ET_MISSILE: - gi.Printf( "ET_MISSILE " ); + gi.Printf("ET_MISSILE "); break; case ET_MOVER: - gi.Printf( "ET_MOVER " ); + gi.Printf("ET_MOVER "); break; case ET_BEAM: - gi.Printf( "ET_BEAM " ); + gi.Printf("ET_BEAM "); break; case ET_PORTAL: - gi.Printf( "ET_PORTAL " ); + gi.Printf("ET_PORTAL "); break; case ET_SPEAKER: - gi.Printf( "ET_SPEAKER " ); + gi.Printf("ET_SPEAKER "); break; case ET_PUSH_TRIGGER: - gi.Printf( "ET_PUSH_TRIGGER " ); + gi.Printf("ET_PUSH_TRIGGER "); break; case ET_TELEPORT_TRIGGER: - gi.Printf( "ET_TELEPORT_TRIGGER " ); + gi.Printf("ET_TELEPORT_TRIGGER "); break; case ET_INVISIBLE: - gi.Printf( "ET_INVISIBLE " ); + gi.Printf("ET_INVISIBLE "); break; case ET_THINKER: - gi.Printf( "ET_THINKER " ); + gi.Printf("ET_THINKER "); break; case ET_CLOUD: - gi.Printf( "ET_CLOUD " ); + gi.Printf("ET_CLOUD "); break; default: - gi.Printf( "%-3i ", check->s.eType ); + gi.Printf("%-3i ", check->s.eType); break; } - if ( check->classname ) { + if (check->classname) { gi.Printf("%s", check->classname); } gi.Printf("\n"); } } -gclient_t *ClientForString( const char *s ) { - gclient_t *cl; - int i; - int idnum; +gclient_t *ClientForString(const char *s) { + gclient_t *cl; + int i; + int idnum; // numeric values are just slot numbers - if ( s[0] >= '0' && s[0] <= '9' ) { - idnum = atoi( s ); - if ( idnum < 0 || idnum >= level.maxclients ) { - Com_Printf( "Bad client slot: %i\n", idnum ); + if (s[0] >= '0' && s[0] <= '9') { + idnum = atoi(s); + if (idnum < 0 || idnum >= level.maxclients) { + Com_Printf("Bad client slot: %i\n", idnum); return NULL; } cl = &level.clients[idnum]; - if ( cl->pers.connected == CON_DISCONNECTED ) { - gi.Printf( "Client %i is not connected\n", idnum ); + if (cl->pers.connected == CON_DISCONNECTED) { + gi.Printf("Client %i is not connected\n", idnum); return NULL; } return cl; } // check for a name match - for ( i=0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { cl = &level.clients[i]; - if ( cl->pers.connected == CON_DISCONNECTED ) { + if (cl->pers.connected == CON_DISCONNECTED) { continue; } - if ( !Q_stricmp( cl->pers.netname, s ) ) { + if (!Q_stricmp(cl->pers.netname, s)) { return cl; } } - gi.Printf( "User %s is not on the server\n", s ); + gi.Printf("User %s is not on the server\n", s); return NULL; } //--------------------------- -extern void G_StopCinematicSkip( void ); -extern void G_StartCinematicSkip( void ); -extern void ExitEmplacedWeapon( gentity_t *ent ); -static void Svcmd_ExitView_f( void ) -{ -extern cvar_t *g_skippingcin; +extern void G_StopCinematicSkip(void); +extern void G_StartCinematicSkip(void); +extern void ExitEmplacedWeapon(gentity_t *ent); +static void Svcmd_ExitView_f(void) { + extern cvar_t *g_skippingcin; static int exitViewDebounce = 0; - if ( exitViewDebounce > level.time ) - { + if (exitViewDebounce > level.time) { return; } exitViewDebounce = level.time + 500; - if ( in_camera ) - {//see if we need to exit an in-game cinematic - if ( g_skippingcin->integer ) // already doing cinematic skip? - {// yes... so stop skipping... + if (in_camera) { // see if we need to exit an in-game cinematic + if (g_skippingcin->integer) // already doing cinematic skip? + { // yes... so stop skipping... G_StopCinematicSkip(); - } - else - {// no... so start skipping... + } else { // no... so start skipping... G_StartCinematicSkip(); } - } - else if ( !G_ClearViewEntity( player ) ) - {//didn't exit control of a droid or turret - //okay, now try exiting emplaced guns or AT-ST's - if ( player->s.eFlags & EF_LOCKED_TO_WEAPON ) - {//get out of emplaced gun - ExitEmplacedWeapon( player ); - } - else if ( player->client && player->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST - GEntity_UseFunc( player->activator, player, player ); + } else if (!G_ClearViewEntity(player)) { // didn't exit control of a droid or turret + // okay, now try exiting emplaced guns or AT-ST's + if (player->s.eFlags & EF_LOCKED_TO_WEAPON) { // get out of emplaced gun + ExitEmplacedWeapon(player); + } else if (player->client && player->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + GEntity_UseFunc(player->activator, player, player); } } } -gentity_t *G_GetSelfForPlayerCmd( void ) -{ - if ( g_entities[0].client->ps.viewEntity > 0 - && g_entities[0].client->ps.viewEntity < ENTITYNUM_WORLD - && g_entities[g_entities[0].client->ps.viewEntity].client - && g_entities[g_entities[0].client->ps.viewEntity].s.weapon == WP_SABER ) - {//you're controlling another NPC +gentity_t *G_GetSelfForPlayerCmd(void) { + if (g_entities[0].client->ps.viewEntity > 0 && g_entities[0].client->ps.viewEntity < ENTITYNUM_WORLD && + g_entities[g_entities[0].client->ps.viewEntity].client && + g_entities[g_entities[0].client->ps.viewEntity].s.weapon == WP_SABER) { // you're controlling another NPC return (&g_entities[g_entities[0].client->ps.viewEntity]); - } - else - { + } else { return (&g_entities[0]); } } -static void Svcmd_SaberColor_f() -{ +static void Svcmd_SaberColor_f() { const char *color = gi.argv(1); - if ( !VALIDSTRING( color )) - { - gi.Printf( "Usage: saberColor \n" ); - gi.Printf( "valid colors: red, orange, yellow, green, blue, and purple\n" ); + if (!VALIDSTRING(color)) { + gi.Printf("Usage: saberColor \n"); + gi.Printf("valid colors: red, orange, yellow, green, blue, and purple\n"); return; } - + gentity_t *self = G_GetSelfForPlayerCmd(); - if ( !Q_stricmp( color, "red" )) - { + if (!Q_stricmp(color, "red")) { self->client->ps.saberColor = SABER_RED; - } - else if ( !Q_stricmp( color, "green" )) - { + } else if (!Q_stricmp(color, "green")) { self->client->ps.saberColor = SABER_GREEN; - } - else if ( !Q_stricmp( color, "yellow" )) - { + } else if (!Q_stricmp(color, "yellow")) { self->client->ps.saberColor = SABER_YELLOW; - } - else if ( !Q_stricmp( color, "orange" )) - { + } else if (!Q_stricmp(color, "orange")) { self->client->ps.saberColor = SABER_ORANGE; - } - else if ( !Q_stricmp( color, "purple" )) - { + } else if (!Q_stricmp(color, "purple")) { self->client->ps.saberColor = SABER_PURPLE; - } - else if ( !Q_stricmp( color, "blue" )) - { + } else if (!Q_stricmp(color, "blue")) { self->client->ps.saberColor = SABER_BLUE; - } - else - { - gi.Printf( "Usage: saberColor \n" ); - gi.Printf( "valid colors: red, orange, yellow, green, blue, and purple\n" ); + } else { + gi.Printf("Usage: saberColor \n"); + gi.Printf("valid colors: red, orange, yellow, green, blue, and purple\n"); } } @@ -240,257 +210,189 @@ struct SetForceCmd { }; SetForceCmd SetForceTable[] = { - { "forceHeal", "setForceHeal", FORCE_LEVEL_3 }, - { "forceJump", "setForceJump", FORCE_LEVEL_3 }, - { "forceSpeed", "setForceSpeed", FORCE_LEVEL_3 }, - { "forcePush", "setForcePush", FORCE_LEVEL_3 }, - { "forcePull", "setForcePull", FORCE_LEVEL_3 }, - { "forceMindTrick", "setForceMindTrick", FORCE_LEVEL_4 }, - { "forceGrip", "setForceGrip", FORCE_LEVEL_3 }, - { "forceLightning", "setForceLightning", FORCE_LEVEL_3 }, - { "saberThrow", "setSaberThrow", FORCE_LEVEL_3 }, - { "saberDefense", "setSaberDefense", FORCE_LEVEL_3 }, - { "saberOffense", "setSaberOffense", FORCE_LEVEL_5 }, + {"forceHeal", "setForceHeal", FORCE_LEVEL_3}, {"forceJump", "setForceJump", FORCE_LEVEL_3}, + {"forceSpeed", "setForceSpeed", FORCE_LEVEL_3}, {"forcePush", "setForcePush", FORCE_LEVEL_3}, + {"forcePull", "setForcePull", FORCE_LEVEL_3}, {"forceMindTrick", "setForceMindTrick", FORCE_LEVEL_4}, + {"forceGrip", "setForceGrip", FORCE_LEVEL_3}, {"forceLightning", "setForceLightning", FORCE_LEVEL_3}, + {"saberThrow", "setSaberThrow", FORCE_LEVEL_3}, {"saberDefense", "setSaberDefense", FORCE_LEVEL_3}, + {"saberOffense", "setSaberOffense", FORCE_LEVEL_5}, }; -static void Svcmd_ForceSetLevel_f( int forcePower ) -{ - if ( !&g_entities[0] || !g_entities[0].client ) - { +static void Svcmd_ForceSetLevel_f(int forcePower) { + if (!&g_entities[0] || !g_entities[0].client) { return; } - if ( !g_cheats->integer ) - { - gi.SendServerCommand( 0, "print \"Cheats are not enabled on this server.\n\""); + if (!g_cheats->integer) { + gi.SendServerCommand(0, "print \"Cheats are not enabled on this server.\n\""); return; } const char *newVal = gi.argv(1); - if ( !VALIDSTRING( newVal ) ) - { - gi.Printf( "Current %s level is %d\n", SetForceTable[forcePower].desc, g_entities[0].client->ps.forcePowerLevel[forcePower] ); - gi.Printf( "Usage: %s (0 - %i)\n", SetForceTable[forcePower].cmdname, SetForceTable[forcePower].maxlevel ); + if (!VALIDSTRING(newVal)) { + gi.Printf("Current %s level is %d\n", SetForceTable[forcePower].desc, g_entities[0].client->ps.forcePowerLevel[forcePower]); + gi.Printf("Usage: %s (0 - %i)\n", SetForceTable[forcePower].cmdname, SetForceTable[forcePower].maxlevel); return; } int val = atoi(newVal); - if ( val > FORCE_LEVEL_0 ) - { - g_entities[0].client->ps.forcePowersKnown |= ( 1 << forcePower ); - } - else - { - g_entities[0].client->ps.forcePowersKnown &= ~( 1 << forcePower ); + if (val > FORCE_LEVEL_0) { + g_entities[0].client->ps.forcePowersKnown |= (1 << forcePower); + } else { + g_entities[0].client->ps.forcePowersKnown &= ~(1 << forcePower); } g_entities[0].client->ps.forcePowerLevel[forcePower] = val; - if ( g_entities[0].client->ps.forcePowerLevel[forcePower] < FORCE_LEVEL_0 ) - { + if (g_entities[0].client->ps.forcePowerLevel[forcePower] < FORCE_LEVEL_0) { g_entities[0].client->ps.forcePowerLevel[forcePower] = FORCE_LEVEL_0; - } - else if ( g_entities[0].client->ps.forcePowerLevel[forcePower] > SetForceTable[forcePower].maxlevel ) - { + } else if (g_entities[0].client->ps.forcePowerLevel[forcePower] > SetForceTable[forcePower].maxlevel) { g_entities[0].client->ps.forcePowerLevel[forcePower] = SetForceTable[forcePower].maxlevel; } } -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInAttack( int move ); -void Svcmd_SaberAttackCycle_f( void ) -{ - if ( !&g_entities[0] || !g_entities[0].client ) - { +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInAttack(int move); +void Svcmd_SaberAttackCycle_f(void) { + if (!&g_entities[0] || !g_entities[0].client) { return; } gentity_t *self = G_GetSelfForPlayerCmd(); - if ( self->s.weapon != WP_SABER ) - { + if (self->s.weapon != WP_SABER) { return; } - int saberAnimLevel; - if ( !self->s.number ) - { + int saberAnimLevel; + if (!self->s.number) { saberAnimLevel = cg.saberAnimLevelPending; - } - else - { + } else { saberAnimLevel = self->client->ps.saberAnimLevel; } saberAnimLevel++; - if ( self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] == FORCE_LEVEL_1 ) - { + if (self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] == FORCE_LEVEL_1) { saberAnimLevel = FORCE_LEVEL_2; - } - else if ( self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] == FORCE_LEVEL_2 ) - { - if ( saberAnimLevel > FORCE_LEVEL_2 ) - { + } else if (self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] == FORCE_LEVEL_2) { + if (saberAnimLevel > FORCE_LEVEL_2) { saberAnimLevel = FORCE_LEVEL_1; } - } - else - {//level 3 - if ( saberAnimLevel > self->client->ps.forcePowerLevel[FP_SABER_OFFENSE] ) - {//wrap around + } else { // level 3 + if (saberAnimLevel > self->client->ps.forcePowerLevel[FP_SABER_OFFENSE]) { // wrap around saberAnimLevel = FORCE_LEVEL_1; } } - if ( !self->s.number ) - { + if (!self->s.number) { cg.saberAnimLevelPending = saberAnimLevel; - } - else - { + } else { self->client->ps.saberAnimLevel = saberAnimLevel; } #ifndef FINAL_BUILD - switch ( saberAnimLevel ) - { + switch (saberAnimLevel) { case FORCE_LEVEL_1: - gi.Printf( S_COLOR_BLUE "Lightsaber Combat Style: Fast\n" ); - //LIGHTSABERCOMBATSTYLE_FAST + gi.Printf(S_COLOR_BLUE "Lightsaber Combat Style: Fast\n"); + // LIGHTSABERCOMBATSTYLE_FAST break; case FORCE_LEVEL_2: - gi.Printf( S_COLOR_YELLOW "Lightsaber Combat Style: Medium\n" ); - //LIGHTSABERCOMBATSTYLE_MEDIUM + gi.Printf(S_COLOR_YELLOW "Lightsaber Combat Style: Medium\n"); + // LIGHTSABERCOMBATSTYLE_MEDIUM break; case FORCE_LEVEL_3: - gi.Printf( S_COLOR_RED "Lightsaber Combat Style: Strong\n" ); - //LIGHTSABERCOMBATSTYLE_STRONG + gi.Printf(S_COLOR_RED "Lightsaber Combat Style: Strong\n"); + // LIGHTSABERCOMBATSTYLE_STRONG break; case FORCE_LEVEL_4: - gi.Printf( S_COLOR_CYAN "Lightsaber Combat Style: Desann\n" ); - //LIGHTSABERCOMBATSTYLE_DESANN + gi.Printf(S_COLOR_CYAN "Lightsaber Combat Style: Desann\n"); + // LIGHTSABERCOMBATSTYLE_DESANN break; case FORCE_LEVEL_5: - gi.Printf( S_COLOR_MAGENTA "Lightsaber Combat Style: Tavion\n" ); - //LIGHTSABERCOMBATSTYLE_TAVION + gi.Printf(S_COLOR_MAGENTA "Lightsaber Combat Style: Tavion\n"); + // LIGHTSABERCOMBATSTYLE_TAVION break; } - //gi.Printf("\n"); + // gi.Printf("\n"); #endif } -template -static void Svcmd_ForceSetLevel_f(void) -{ - Svcmd_ForceSetLevel_f(power); -} +template static void Svcmd_ForceSetLevel_f(void) { Svcmd_ForceSetLevel_f(power); } -static void Svcmd_SetForceAll_f(void) -{ - for ( int i = FP_HEAL; i <= FP_SABER_OFFENSE; i++ ) - { - Svcmd_ForceSetLevel_f( i ); +static void Svcmd_SetForceAll_f(void) { + for (int i = FP_HEAL; i <= FP_SABER_OFFENSE; i++) { + Svcmd_ForceSetLevel_f(i); } } -static void Svcmd_SetSaberAll_f(void) -{ - Svcmd_ForceSetLevel_f( FP_SABERTHROW ); - Svcmd_ForceSetLevel_f( FP_SABER_DEFENSE ); - Svcmd_ForceSetLevel_f( FP_SABER_OFFENSE ); +static void Svcmd_SetSaberAll_f(void) { + Svcmd_ForceSetLevel_f(FP_SABERTHROW); + Svcmd_ForceSetLevel_f(FP_SABER_DEFENSE); + Svcmd_ForceSetLevel_f(FP_SABER_OFFENSE); } -static void Svcmd_RunScript_f(void) -{ +static void Svcmd_RunScript_f(void) { const char *cmd2 = gi.argv(1); - if ( cmd2 && cmd2[0] ) - { + if (cmd2 && cmd2[0]) { const char *cmd3 = gi.argv(2); - if ( cmd3 && cmd3[0] ) - { + if (cmd3 && cmd3[0]) { gentity_t *found = NULL; - if ( (found = G_Find(NULL, FOFS(targetname), cmd2 ) ) != NULL ) - { - ICARUS_RunScript( found, cmd3 ); + if ((found = G_Find(NULL, FOFS(targetname), cmd2)) != NULL) { + ICARUS_RunScript(found, cmd3); + } else { + // can't find cmd2 + gi.Printf(S_COLOR_RED "runscript: can't find targetname %s\n", cmd2); } - else - { - //can't find cmd2 - gi.Printf( S_COLOR_RED "runscript: can't find targetname %s\n", cmd2 ); - } - } - else - { - ICARUS_RunScript( &g_entities[0], cmd2 ); + } else { + ICARUS_RunScript(&g_entities[0], cmd2); } - } - else - { - gi.Printf( S_COLOR_RED "usage: runscript scriptname\n" ); + } else { + gi.Printf(S_COLOR_RED "usage: runscript scriptname\n"); } } -static void Svcmd_PlayerTeam_f(void) -{ +static void Svcmd_PlayerTeam_f(void) { const char *cmd2 = gi.argv(1); - if ( !*cmd2 || !cmd2[0] ) - { - gi.Printf( S_COLOR_RED "'playerteam' - change player team, requires a team name!\n" ); - gi.Printf( S_COLOR_RED "Current team is: %s\n", TeamNames[g_entities[0].client->playerTeam] ); - gi.Printf( S_COLOR_RED "Valid team names are:\n"); - for ( int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED "%s\n", TeamNames[n] ); + if (!*cmd2 || !cmd2[0]) { + gi.Printf(S_COLOR_RED "'playerteam' - change player team, requires a team name!\n"); + gi.Printf(S_COLOR_RED "Current team is: %s\n", TeamNames[g_entities[0].client->playerTeam]); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (int n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - } - else - { - team_t team = TranslateTeamName( cmd2 ); - - if ( team == TEAM_FREE ) - { - gi.Printf( S_COLOR_RED "'playerteam' unrecognized team name %s!\n", cmd2 ); - gi.Printf( S_COLOR_RED "Current team is: %s\n", TeamNames[g_entities[0].client->playerTeam] ); - gi.Printf( S_COLOR_RED "Valid team names are:\n"); - for ( int n = TEAM_FREE; n < TEAM_NUM_TEAMS; n++ ) - { - gi.Printf( S_COLOR_RED "%s\n", TeamNames[n] ); + } else { + team_t team = TranslateTeamName(cmd2); + + if (team == TEAM_FREE) { + gi.Printf(S_COLOR_RED "'playerteam' unrecognized team name %s!\n", cmd2); + gi.Printf(S_COLOR_RED "Current team is: %s\n", TeamNames[g_entities[0].client->playerTeam]); + gi.Printf(S_COLOR_RED "Valid team names are:\n"); + for (int n = TEAM_FREE; n < TEAM_NUM_TEAMS; n++) { + gi.Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - } - else - { + } else { g_entities[0].client->playerTeam = team; - //FIXME: convert Imperial, Malon, Hirogen and Klingon to Scavenger? + // FIXME: convert Imperial, Malon, Hirogen and Klingon to Scavenger? } } } -static void Svcmd_Control_f(void) -{ - const char *cmd2 = gi.argv(1); - if ( !*cmd2 || !cmd2[0] ) - { - if ( !G_ClearViewEntity( &g_entities[0] ) ) - { - gi.Printf( S_COLOR_RED "control \n", cmd2 ); +static void Svcmd_Control_f(void) { + const char *cmd2 = gi.argv(1); + if (!*cmd2 || !cmd2[0]) { + if (!G_ClearViewEntity(&g_entities[0])) { + gi.Printf(S_COLOR_RED "control \n", cmd2); } - } - else - { - Q3_SetViewEntity( 0, cmd2 ); + } else { + Q3_SetViewEntity(0, cmd2); } } -static void Svcmd_Secrets_f(void) -{ +static void Svcmd_Secrets_f(void) { const gentity_t *pl = &g_entities[0]; - if(pl->client->sess.missionStats.totalSecrets < 1) - { - gi.Printf( "There are" S_COLOR_RED " NO " S_COLOR_WHITE "secrets on this map!\n" ); - } - else if(pl->client->sess.missionStats.secretsFound == pl->client->sess.missionStats.totalSecrets) - { - gi.Printf( "You've found all " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets on this map!\n", pl->client->sess.missionStats.secretsFound ); - } - else - { - gi.Printf( "You've found " S_COLOR_GREEN "%i" S_COLOR_WHITE " out of " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets!\n", pl->client->sess.missionStats.secretsFound, pl->client->sess.missionStats.totalSecrets ); + if (pl->client->sess.missionStats.totalSecrets < 1) { + gi.Printf("There are" S_COLOR_RED " NO " S_COLOR_WHITE "secrets on this map!\n"); + } else if (pl->client->sess.missionStats.secretsFound == pl->client->sess.missionStats.totalSecrets) { + gi.Printf("You've found all " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets on this map!\n", pl->client->sess.missionStats.secretsFound); + } else { + gi.Printf("You've found " S_COLOR_GREEN "%i" S_COLOR_WHITE " out of " S_COLOR_GREEN "%i" S_COLOR_WHITE " secrets!\n", + pl->client->sess.missionStats.secretsFound, pl->client->sess.missionStats.totalSecrets); } } @@ -500,129 +402,106 @@ static void Svcmd_Secrets_f(void) // JEDI MASTER - g_spskill 2 + cg_crosshairForceHint 0 + handicap 50 extern cvar_t *g_spskill; -static void Svcmd_Difficulty_f(void) -{ - if(gi.argc() == 1) - { - if(g_spskill->integer == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Padawan" S_COLOR_WHITE "\n" ); - } - else if(g_spskill->integer == 1) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi" S_COLOR_WHITE "\n" ); - } - else if(g_spskill->integer == 2) - { +static void Svcmd_Difficulty_f(void) { + if (gi.argc() == 1) { + if (g_spskill->integer == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Padawan" S_COLOR_WHITE "\n"); + } else if (g_spskill->integer == 1) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi" S_COLOR_WHITE "\n"); + } else if (g_spskill->integer == 2) { int crosshairHint = gi.Cvar_VariableIntegerValue("cg_crosshairForceHint"); int handicap = gi.Cvar_VariableIntegerValue("handicap"); - if(handicap == 100 && crosshairHint == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Knight" S_COLOR_WHITE "\n" ); - } - else if(handicap == 50 && crosshairHint == 0) - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Master" S_COLOR_WHITE "\n" ); + if (handicap == 100 && crosshairHint == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Knight" S_COLOR_WHITE "\n"); + } else if (handicap == 50 && crosshairHint == 0) { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Master" S_COLOR_WHITE "\n"); + } else { + gi.Printf(S_COLOR_GREEN "Current Difficulty: Jedi Knight (Custom)" S_COLOR_WHITE "\n"); + gi.Printf(S_COLOR_GREEN "Crosshair Force Hint: %i" S_COLOR_WHITE "\n", crosshairHint != 0 ? 1 : 0); + gi.Printf(S_COLOR_GREEN "Handicap: %i" S_COLOR_WHITE "\n", handicap); } - else - { - gi.Printf( S_COLOR_GREEN "Current Difficulty: Jedi Knight (Custom)" S_COLOR_WHITE "\n" ); - gi.Printf( S_COLOR_GREEN "Crosshair Force Hint: %i" S_COLOR_WHITE "\n", crosshairHint != 0 ? 1 : 0 ); - gi.Printf( S_COLOR_GREEN "Handicap: %i" S_COLOR_WHITE "\n", handicap ); - } - } - else - { - gi.Printf( S_COLOR_RED "Invalid difficulty cvar set! g_spskill (%i) [0-2] is valid range only" S_COLOR_WHITE "\n", g_spskill->integer ); + } else { + gi.Printf(S_COLOR_RED "Invalid difficulty cvar set! g_spskill (%i) [0-2] is valid range only" S_COLOR_WHITE "\n", g_spskill->integer); } } } -#define CMD_NONE (0x00000000u) -#define CMD_CHEAT (0x00000001u) -#define CMD_ALIVE (0x00000002u) +#define CMD_NONE (0x00000000u) +#define CMD_CHEAT (0x00000001u) +#define CMD_ALIVE (0x00000002u) typedef struct svcmd_s { - const char *name; - void (*func)(void); - uint32_t flags; + const char *name; + void (*func)(void); + uint32_t flags; } svcmd_t; -static int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((svcmd_t*)b)->name ); -} +static int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((svcmd_t *)b)->name); } // FIXME some of these should be made CMD_ALIVE too! static svcmd_t svcmds[] = { - { "entitylist", Svcmd_EntityList_f, CMD_NONE }, - { "game_memory", Svcmd_GameMem_f, CMD_NONE }, - - { "nav", Svcmd_Nav_f, CMD_CHEAT }, - { "npc", Svcmd_NPC_f, CMD_CHEAT }, - { "use", Svcmd_Use_f, CMD_CHEAT }, - { "ICARUS", Svcmd_ICARUS_f, CMD_CHEAT }, - - { "saberColor", Svcmd_SaberColor_f, CMD_CHEAT }, - - { "setForceJump", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberThrow", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceHeal", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForcePush", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForcePull", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceSpeed", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceGrip", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceLightning", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setMindTrick", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberDefense", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setSaberOffense", Svcmd_ForceSetLevel_f, CMD_CHEAT }, - { "setForceAll", Svcmd_SetForceAll_f, CMD_CHEAT }, - { "setSaberAll", Svcmd_SetSaberAll_f, CMD_CHEAT }, - - { "saberAttackCycle", Svcmd_SaberAttackCycle_f, CMD_NONE }, - - { "runscript", Svcmd_RunScript_f, CMD_CHEAT }, - - { "playerTeam", Svcmd_PlayerTeam_f, CMD_CHEAT }, - - { "control", Svcmd_Control_f, CMD_CHEAT }, - - { "exitview", Svcmd_ExitView_f, CMD_NONE }, - - { "secrets", Svcmd_Secrets_f, CMD_NONE }, - { "difficulty", Svcmd_Difficulty_f, CMD_NONE }, - + {"entitylist", Svcmd_EntityList_f, CMD_NONE}, + {"game_memory", Svcmd_GameMem_f, CMD_NONE}, + + {"nav", Svcmd_Nav_f, CMD_CHEAT}, + {"npc", Svcmd_NPC_f, CMD_CHEAT}, + {"use", Svcmd_Use_f, CMD_CHEAT}, + {"ICARUS", Svcmd_ICARUS_f, CMD_CHEAT}, + + {"saberColor", Svcmd_SaberColor_f, CMD_CHEAT}, + + {"setForceJump", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberThrow", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceHeal", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForcePush", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForcePull", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceSpeed", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceGrip", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceLightning", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setMindTrick", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberDefense", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setSaberOffense", Svcmd_ForceSetLevel_f, CMD_CHEAT}, + {"setForceAll", Svcmd_SetForceAll_f, CMD_CHEAT}, + {"setSaberAll", Svcmd_SetSaberAll_f, CMD_CHEAT}, + + {"saberAttackCycle", Svcmd_SaberAttackCycle_f, CMD_NONE}, + + {"runscript", Svcmd_RunScript_f, CMD_CHEAT}, + + {"playerTeam", Svcmd_PlayerTeam_f, CMD_CHEAT}, + + {"control", Svcmd_Control_f, CMD_CHEAT}, + + {"exitview", Svcmd_ExitView_f, CMD_NONE}, + + {"secrets", Svcmd_Secrets_f, CMD_NONE}, + {"difficulty", Svcmd_Difficulty_f, CMD_NONE}, + //{ "say", Svcmd_Say_f, qtrue }, //{ "toggleallowvote", Svcmd_ToggleAllowVote_f, qfalse }, //{ "toggleuserinfovalidation", Svcmd_ToggleUserinfoValidation_f, qfalse }, }; -static const size_t numsvcmds = ARRAY_LEN( svcmds ); +static const size_t numsvcmds = ARRAY_LEN(svcmds); /* ================= ConsoleCommand ================= */ -qboolean ConsoleCommand( void ) { +qboolean ConsoleCommand(void) { const char *cmd = gi.argv(0); - const svcmd_t *command = (const svcmd_t *)Q_LinearSearch( cmd, svcmds, numsvcmds, sizeof( svcmds[0] ), svcmdcmp ); + const svcmd_t *command = (const svcmd_t *)Q_LinearSearch(cmd, svcmds, numsvcmds, sizeof(svcmds[0]), svcmdcmp); - if ( !command ) + if (!command) return qfalse; - - if ( (command->flags & CMD_CHEAT) - && !g_cheats->integer ) - { - gi.Printf( "Cheats are not enabled on this server.\n" ); + + if ((command->flags & CMD_CHEAT) && !g_cheats->integer) { + gi.Printf("Cheats are not enabled on this server.\n"); return qtrue; - } - else if ( (command->flags & CMD_ALIVE) - && (g_entities[0].health <= 0) ) - { - gi.Printf( "You must be alive to use this command.\n" ); + } else if ((command->flags & CMD_ALIVE) && (g_entities[0].health <= 0)) { + gi.Printf("You must be alive to use this command.\n"); return qtrue; - } - else + } else command->func(); return qtrue; } - diff --git a/codeJK2/game/g_target.cpp b/codeJK2/game/g_target.cpp index 495a4f96b4..50cb9c17ea 100644 --- a/codeJK2/game/g_target.cpp +++ b/codeJK2/game/g_target.cpp @@ -26,45 +26,43 @@ along with this program; if not, see . #include "g_functions.h" #include "g_icarus.h" //#include "Q3_Interface.h" -extern void Q3_DebugPrint( int level, const char *format, ... ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); +extern void Q3_DebugPrint(int level, const char *format, ...); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); //========================================================== /*QUAKED target_give (1 0 0) (-8 -8 -8) (8 8 8) Gives the activator all the items pointed to. */ -void Use_Target_Give( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - gentity_t *t; - trace_t trace; +void Use_Target_Give(gentity_t *ent, gentity_t *other, gentity_t *activator) { + gentity_t *t; + trace_t trace; - if ( !activator->client ) { + if (!activator->client) { return; } - if ( !ent->target ) { + if (!ent->target) { return; } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - memset( &trace, 0, sizeof( trace ) ); + memset(&trace, 0, sizeof(trace)); t = NULL; - while ( (t = G_Find (t, FOFS(targetname), ent->target)) != NULL ) { - if ( !t->item ) { + while ((t = G_Find(t, FOFS(targetname), ent->target)) != NULL) { + if (!t->item) { continue; } - Touch_Item( t, activator, &trace ); + Touch_Item(t, activator, &trace); // make sure it isn't going to respawn or show any events t->nextthink = 0; - gi.unlinkentity( t ); + gi.unlinkentity(t); } } -void SP_target_give( gentity_t *ent ) { - ent->e_UseFunc = useF_Use_Target_Give; -} +void SP_target_give(gentity_t *ent) { ent->e_UseFunc = useF_Use_Target_Give; } //========================================================== @@ -72,37 +70,29 @@ void SP_target_give( gentity_t *ent ) { "wait" seconds to pause before firing targets. "random" delay variance, total delay = delay +/- random seconds */ -void Think_Target_Delay( gentity_t *ent ) -{ - G_UseTargets( ent, ent->activator ); -} +void Think_Target_Delay(gentity_t *ent) { G_UseTargets(ent, ent->activator); } -void Use_Target_Delay( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Delay(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->e_ThinkFunc = thinkF_Think_Target_Delay; ent->activator = activator; } -void SP_target_delay( gentity_t *ent ) -{ +void SP_target_delay(gentity_t *ent) { // check delay for backwards compatability - if ( !G_SpawnFloat( "delay", "0", &ent->wait ) ) - { - G_SpawnFloat( "wait", "1", &ent->wait ); + if (!G_SpawnFloat("delay", "0", &ent->wait)) { + G_SpawnFloat("wait", "1", &ent->wait); } - if ( !ent->wait ) - { + if (!ent->wait) { ent->wait = 1; } ent->e_UseFunc = useF_Use_Target_Delay; } - //========================================================== /*QUAKED target_score (1 0 0) (-8 -8 -8) (8 8 8) @@ -110,49 +100,42 @@ void SP_target_delay( gentity_t *ent ) The activator is given this many points. */ -void Use_Target_Score (gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Score(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - AddScore( activator, ent->count ); + AddScore(activator, ent->count); } -void SP_target_score( gentity_t *ent ) { - if ( !ent->count ) { +void SP_target_score(gentity_t *ent) { + if (!ent->count) { ent->count = 1; } ent->e_UseFunc = useF_Use_Target_Score; } - //========================================================== /*QUAKED target_print (1 0 0) (-8 -8 -8) (8 8 8) "message" text to print If "private", only the activator gets the message. If no checks, all clients get the message. */ -void Use_Target_Print (gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Print(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - if ( activator->client ) { - gi.SendServerCommand( activator-g_entities, "cp \"%s\"", ent->message ); + if (activator->client) { + gi.SendServerCommand(activator - g_entities, "cp \"%s\"", ent->message); } } -void SP_target_print( gentity_t *ent ) { - ent->e_UseFunc = useF_Use_Target_Print; -} - +void SP_target_print(gentity_t *ent) { ent->e_UseFunc = useF_Use_Target_Print; } //========================================================== - /*QUAKED target_speaker (1 0 0) (-8 -8 -8) (8 8 8) looped-on looped-off global activator "noise" wav file to play -"sounds" va() min max, so if your sound string is borgtalk%d.wav, and you set a "sounds" value of 4, it will randomly play borgtalk1.wav - borgtalk4.wav when triggered -to use this, you must store the wav name in "soundGroup", NOT "noise" +"sounds" va() min max, so if your sound string is borgtalk%d.wav, and you set a "sounds" value of 4, it will randomly play borgtalk1.wav - borgtalk4.wav when +triggered to use this, you must store the wav name in "soundGroup", NOT "noise" A global sound will play full volume throughout the level. Activator sounds will play on the player that activated the target. @@ -163,78 +146,68 @@ Multiple identical looping sounds will just increase volume without any speed co "wait" : Seconds between triggerings, 0 = don't auto trigger "random" wait variance, default is 0 */ -void Use_Target_Speaker (gentity_t *ent, gentity_t *other, gentity_t *activator) { - if(ent->painDebounceTime > level.time) - { +void Use_Target_Speaker(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (ent->painDebounceTime > level.time) { return; } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); - if ( ent->sounds ) - { - ent->noise_index = G_SoundIndex( va( ent->paintarget, Q_irand(1, ent->sounds ) ) ); + if (ent->sounds) { + ent->noise_index = G_SoundIndex(va(ent->paintarget, Q_irand(1, ent->sounds))); } - if (ent->spawnflags & 3) { // looping sound toggles + if (ent->spawnflags & 3) { // looping sound toggles gentity_t *looper = ent; - if ( ent->spawnflags & 8 ) { + if (ent->spawnflags & 8) { looper = activator; } if (looper->s.loopSound) - looper->s.loopSound = 0; // turn it off + looper->s.loopSound = 0; // turn it off else - looper->s.loopSound = ent->noise_index; // start it - }else { // normal sound - if ( ent->spawnflags & 8 ) { - G_AddEvent( activator, EV_GENERAL_SOUND, ent->noise_index ); + looper->s.loopSound = ent->noise_index; // start it + } else { // normal sound + if (ent->spawnflags & 8) { + G_AddEvent(activator, EV_GENERAL_SOUND, ent->noise_index); } else if (ent->spawnflags & 4) { - G_AddEvent( ent, EV_GLOBAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GLOBAL_SOUND, ent->noise_index); } else { - G_AddEvent( ent, EV_GENERAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GENERAL_SOUND, ent->noise_index); } } - if(ent->wait < 0) - {//BYE! + if (ent->wait < 0) { // BYE! ent->e_UseFunc = useF_NULL; - } - else - { + } else { ent->painDebounceTime = level.time + ent->wait; } } -void SP_target_speaker( gentity_t *ent ) { - char buffer[MAX_QPATH]; - char *s; - int i; +void SP_target_speaker(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + int i; - if ( VALIDSTRING( ent->soundSet ) ) - { - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - gi.linkentity (ent); + if (VALIDSTRING(ent->soundSet)) { + VectorCopy(ent->s.origin, ent->s.pos.trBase); + gi.linkentity(ent); return; } - G_SpawnFloat( "wait", "0", &ent->wait ); - G_SpawnFloat( "random", "0", &ent->random ); + G_SpawnFloat("wait", "0", &ent->wait); + G_SpawnFloat("random", "0", &ent->random); - if(!ent->sounds) - { - if ( !G_SpawnString( "noise", "*NOSOUND*", &s ) ) { - G_Error( "target_speaker without a noise key at %s", vtos( ent->s.origin ) ); + if (!ent->sounds) { + if (!G_SpawnString("noise", "*NOSOUND*", &s)) { + G_Error("target_speaker without a noise key at %s", vtos(ent->s.origin)); } - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); - } - else - {//Precache all possible sounds - for( i = 0; i < ent->sounds; i++ ) - { - ent->noise_index = G_SoundIndex( va( ent->paintarget, i+1 ) ); + } else { // Precache all possible sounds + for (i = 0; i < ent->sounds; i++) { + ent->noise_index = G_SoundIndex(va(ent->paintarget, i + 1)); } } @@ -247,7 +220,7 @@ void SP_target_speaker( gentity_t *ent ) { ent->wait *= 1000; // check for prestarted looping sound - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.loopSound = ent->noise_index; } @@ -257,134 +230,125 @@ void SP_target_speaker( gentity_t *ent ) { ent->svFlags |= SVF_BROADCAST; } - VectorCopy( ent->s.origin, ent->s.pos.trBase ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); // must link the entity so we get areas and clusters so // the server can determine who to send updates to - gi.linkentity (ent); + gi.linkentity(ent); } - - //========================================================== /*QUAKED target_laser (0 .5 .8) (-8 -8 -8) (8 8 8) START_ON When triggered, fires a laser. You can either set a target or a direction. */ -void target_laser_think (gentity_t *self) { - vec3_t end; - trace_t tr; - vec3_t point; +void target_laser_think(gentity_t *self) { + vec3_t end; + trace_t tr; + vec3_t point; // if pointed at another entity, set movedir to point at it - if ( self->enemy ) { - VectorMA (self->enemy->s.origin, 0.5, self->enemy->mins, point); - VectorMA (point, 0.5, self->enemy->maxs, point); - VectorSubtract (point, self->s.origin, self->movedir); - VectorNormalize (self->movedir); + if (self->enemy) { + VectorMA(self->enemy->s.origin, 0.5, self->enemy->mins, point); + VectorMA(point, 0.5, self->enemy->maxs, point); + VectorSubtract(point, self->s.origin, self->movedir); + VectorNormalize(self->movedir); } // fire forward and see what we hit - VectorMA (self->s.origin, 2048, self->movedir, end); + VectorMA(self->s.origin, 2048, self->movedir, end); - gi.trace( &tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE, G2_NOCOLLIDE, 0); + gi.trace(&tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_CORPSE, G2_NOCOLLIDE, 0); - if ( tr.entityNum ) { + if (tr.entityNum) { // hurt it if we can - G_Damage ( &g_entities[tr.entityNum], self, self->activator, self->movedir, - tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_ENERGY ); + G_Damage(&g_entities[tr.entityNum], self, self->activator, self->movedir, tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_ENERGY); } - VectorCopy (tr.endpos, self->s.origin2); + VectorCopy(tr.endpos, self->s.origin2); - gi.linkentity( self ); + gi.linkentity(self); self->nextthink = level.time + FRAMETIME; } -void target_laser_on (gentity_t *self) -{ +void target_laser_on(gentity_t *self) { if (!self->activator) self->activator = self; - target_laser_think (self); + target_laser_think(self); } -void target_laser_off (gentity_t *self) -{ - gi.unlinkentity( self ); +void target_laser_off(gentity_t *self) { + gi.unlinkentity(self); self->nextthink = 0; } -void target_laser_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_laser_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); self->activator = activator; - if ( self->nextthink > 0 ) - target_laser_off (self); + if (self->nextthink > 0) + target_laser_off(self); else - target_laser_on (self); + target_laser_on(self); } -void target_laser_start (gentity_t *self) -{ +void target_laser_start(gentity_t *self) { gentity_t *ent; self->s.eType = ET_BEAM; if (self->target) { - ent = G_Find (NULL, FOFS(targetname), self->target); + ent = G_Find(NULL, FOFS(targetname), self->target); if (!ent) { - gi.Printf ("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); + gi.Printf("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); } - G_SetEnemy( self, ent ); + G_SetEnemy(self, ent); } else { - G_SetMovedir (self->s.angles, self->movedir); + G_SetMovedir(self->s.angles, self->movedir); } - self->e_UseFunc = useF_target_laser_use; + self->e_UseFunc = useF_target_laser_use; self->e_ThinkFunc = thinkF_target_laser_think; - if ( !self->damage ) { + if (!self->damage) { self->damage = 1; } if (self->spawnflags & 1) - target_laser_on (self); + target_laser_on(self); else - target_laser_off (self); + target_laser_off(self); } -void SP_target_laser (gentity_t *self) -{ +void SP_target_laser(gentity_t *self) { // let everything else get spawned before we start firing self->e_ThinkFunc = thinkF_target_laser_start; self->nextthink = level.time + START_TIME_LINK_ENTS; } - //========================================================== -void target_teleporter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { - gentity_t *dest; +void target_teleporter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + gentity_t *dest; if (!activator->client) return; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - gi.Printf ("Couldn't find teleporter destination\n"); + gi.Printf("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( activator, dest->s.origin, dest->s.angles ); + TeleportPlayer(activator, dest->s.origin, dest->s.angles); } /*QUAK-ED target_teleporter (1 0 0) (-8 -8 -8) (8 8 8) The activator will be teleported away. */ -void SP_target_teleporter( gentity_t *self ) { +void SP_target_teleporter(gentity_t *self) { if (!self->targetname) gi.Printf("untargeted %s at %s\n", self->classname, vtos(self->s.origin)); @@ -393,7 +357,6 @@ void SP_target_teleporter( gentity_t *self ) { //========================================================== - /*QUAKED target_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) RED_ONLY BLUE_ONLY RANDOM x x x x INACTIVE This doesn't perform any actions except fire its targets. The activator can be forced to be from a certain team. @@ -404,135 +367,108 @@ INACTIVE Can't be used until activated "delay" - Will actually fire this many seconds after being used "wait" - Cannot be fired again until this many seconds after the last time it was used */ -void target_relay_use_go (gentity_t *self ) -{ - G_ActivateBehavior( self, BSET_USE ); - - if ( self->spawnflags & 4 ) - { - gentity_t *ent; +void target_relay_use_go(gentity_t *self) { + G_ActivateBehavior(self, BSET_USE); + + if (self->spawnflags & 4) { + gentity_t *ent; - ent = G_PickTarget( self->target ); - if ( ent && (ent->e_UseFunc != useF_NULL) ) - { // e_UseFunc check can be omitted - GEntity_UseFunc( ent, self, self->activator ); + ent = G_PickTarget(self->target); + if (ent && (ent->e_UseFunc != useF_NULL)) { // e_UseFunc check can be omitted + GEntity_UseFunc(ent, self, self->activator); } return; } - G_UseTargets( self, self->activator ); + G_UseTargets(self, self->activator); } -void target_relay_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( ( self->spawnflags & 1 ) && activator->client ) - {//&& activator->client->ps.persistant[PERS_TEAM] != TEAM_RED ) { +void target_relay_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if ((self->spawnflags & 1) && activator->client) { //&& activator->client->ps.persistant[PERS_TEAM] != TEAM_RED ) { return; } - if ( ( self->spawnflags & 2 ) && activator->client ) - {//&& activator->client->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { + if ((self->spawnflags & 2) && activator->client) { //&& activator->client->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { return; } - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if ( self->painDebounceTime > level.time ) - { + if (self->painDebounceTime > level.time) { return; } - G_SetEnemy( self, other ); + G_SetEnemy(self, other); self->activator = activator; - if ( self->delay ) - { + if (self->delay) { self->e_ThinkFunc = thinkF_target_relay_use_go; self->nextthink = level.time + self->delay; return; } - target_relay_use_go( self ); + target_relay_use_go(self); - if ( self->wait < 0 ) - { + if (self->wait < 0) { self->e_UseFunc = useF_NULL; - } - else - { + } else { self->painDebounceTime = level.time + self->wait; } } -void SP_target_relay (gentity_t *self) -{ +void SP_target_relay(gentity_t *self) { self->e_UseFunc = useF_target_relay_use; self->wait *= 1000; self->delay *= 1000; - if ( self->spawnflags&128 ) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } } - //========================================================== /*QUAKED target_kill (.5 .5 .5) (-8 -8 -8) (8 8 8) FALLING ELECTRICAL Kills the activator. */ -void target_kill_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void target_kill_use(gentity_t *self, gentity_t *other, gentity_t *activator) { - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 1 ) - {//falling death - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_FALLING ); - if ( !activator->s.number && activator->health <= 0 && 1 ) - { - extern void CGCam_Fade( vec4_t source, vec4_t dest, float duration ); - float src[4] = {0,0,0,0},dst[4]={0,0,0,1}; - CGCam_Fade( src, dst, 10000 ); + if (self->spawnflags & 1) { // falling death + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_FALLING); + if (!activator->s.number && activator->health <= 0 && 1) { + extern void CGCam_Fade(vec4_t source, vec4_t dest, float duration); + float src[4] = {0, 0, 0, 0}, dst[4] = {0, 0, 0, 1}; + CGCam_Fade(src, dst, 10000); } - } - else if ( self->spawnflags & 2 ) // electrical + } else if (self->spawnflags & 2) // electrical { - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_ELECTROCUTE ); - - if ( activator->client ) - { - activator->s.powerups |= ( 1 << PW_SHOCKED ); + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_ELECTROCUTE); + + if (activator->client) { + activator->s.powerups |= (1 << PW_SHOCKED); activator->client->ps.powerups[PW_SHOCKED] = level.time + 4000; } - } - else - { - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); + } else { + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } } -void SP_target_kill( gentity_t *self ) -{ - self->e_UseFunc = useF_target_kill_use; -} +void SP_target_kill(gentity_t *self) { self->e_UseFunc = useF_target_kill_use; } /*QUAKED target_position (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. info_notnull does the same thing */ -void SP_target_position( gentity_t *self ){ - G_SetOrigin( self, self->s.origin ); -} +void SP_target_position(gentity_t *self) { G_SetOrigin(self, self->s.origin); } -//static -slc -void target_location_linkup(gentity_t *ent) -{ +// static -slc +void target_location_linkup(gentity_t *ent) { int i; - if (level.locationLinked) + if (level.locationLinked) return; level.locationLinked = qtrue; @@ -557,11 +493,11 @@ Set "count" to 0-7 for color. Closest target_location in sight used for the location, if none in site, closest in distance */ -void SP_target_location( gentity_t *self ){ +void SP_target_location(gentity_t *self) { self->e_ThinkFunc = thinkF_target_location_linkup; - self->nextthink = level.time + 1000; // Let them all spawn first + self->nextthink = level.time + 1000; // Let them all spawn first - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); } //===NEW=================================================================== @@ -578,64 +514,54 @@ After the counter has been triggered "count" times (default 2), it will fire all bounceCount - number of times the counter should reset to it's full count when it's done */ -void target_counter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->count == 0 ) - { +void target_counter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->count == 0) { return; } - - //gi.Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + + // gi.Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); self->count--; - if ( activator ) - { - Q3_DebugPrint( WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, (self->max_health-self->count), self->max_health ); + if (activator) { + Q3_DebugPrint(WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, (self->max_health - self->count), + self->max_health); } - if ( self->count ) - { - if ( self->target2 ) - { - //gi.Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); - G_UseTargets2( self, activator, self->target2 ); + if (self->count) { + if (self->target2) { + // gi.Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + G_UseTargets2(self, activator, self->target2); } return; } - - G_ActivateBehavior( self,BSET_USE ); - if ( self->spawnflags & 128 ) - { + G_ActivateBehavior(self, BSET_USE); + + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } self->activator = activator; - G_UseTargets( self, activator ); + G_UseTargets(self, activator); - if ( self->count == 0 ) - { - if ( self->bounceCount == 0 ) - { + if (self->count == 0) { + if (self->bounceCount == 0) { return; } self->count = self->max_health; - if ( self->bounceCount > 0 ) - {//-1 means bounce back forever - self->bounceCount--; + if (self->bounceCount > 0) { //-1 means bounce back forever + self->bounceCount--; } } } -void SP_target_counter (gentity_t *self) -{ +void SP_target_counter(gentity_t *self) { self->wait = -1; - if (!self->count) - { + if (!self->count) { self->count = 2; } - //if ( self->bounceCount > 0 )//let's always set this anyway - {//we will reset when we use up our count, remember our initial count + // if ( self->bounceCount > 0 )//let's always set this anyway + { // we will reset when we use up our count, remember our initial count self->max_health = self->count; } @@ -648,84 +574,66 @@ Randomly fires off only one of it's targets each time used USEONCE set to never fire again */ -void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int t_count = 0, pick; - gentity_t *t = NULL; +void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int t_count = 0, pick; + gentity_t *t = NULL; - //gi.Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); - G_ActivateBehavior(self,BSET_USE); + // gi.Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); + G_ActivateBehavior(self, BSET_USE); - if(self->spawnflags & 1) - { + if (self->spawnflags & 1) { self->e_UseFunc = useF_NULL; } - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; } } - if(!t_count) - { + if (!t_count) { return; } - if(t_count == 1) - { - G_UseTargets (self, activator); + if (t_count == 1) { + G_UseTargets(self, activator); return; } - //FIXME: need a seed + // FIXME: need a seed pick = Q_irand(1, t_count); t_count = 0; - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; - } - else - { + } else { continue; } - - if (t == self) - { -// gi.Printf ("WARNING: Entity used itself.\n"); - } - else if(t_count == pick) - { - if (t->e_UseFunc != useF_NULL) // check can be omitted + + if (t == self) { + // gi.Printf ("WARNING: Entity used itself.\n"); + } else if (t_count == pick) { + if (t->e_UseFunc != useF_NULL) // check can be omitted { GEntity_UseFunc(t, self, activator); return; } } - if (!self->inuse) - { + if (!self->inuse) { gi.Printf("entity was removed while using targets\n"); return; } } } -void SP_target_random (gentity_t *self) -{ - self->e_UseFunc = useF_target_random_use; -} +void SP_target_random(gentity_t *self) { self->e_UseFunc = useF_target_random_use; } -int numNewICARUSEnts = 0; -void scriptrunner_run (gentity_t *self) -{ +int numNewICARUSEnts = 0; +void scriptrunner_run(gentity_t *self) { /* if (self->behaviorSet[BSET_USE]) - { + { char newname[MAX_FILENAME_LENGTH]; sprintf((char *) &newname, "%s/%s", Q3_SCRIPT_DIR, self->behaviorSet[BSET_USE] ); @@ -734,85 +642,64 @@ void scriptrunner_run (gentity_t *self) } */ - if ( self->count != -1 ) - { - if ( self->count <= 0 ) - { + if (self->count != -1) { + if (self->count <= 0) { self->e_UseFunc = useF_NULL; self->behaviorSet[BSET_USE] = NULL; return; - } - else - { + } else { --self->count; } } - if (self->behaviorSet[BSET_USE]) - { - if ( self->spawnflags & 1 ) - { - if ( !self->activator ) - { - Q3_DebugPrint( WL_ERROR, "target_scriptrunner tried to run on invalid entity!\n"); + if (self->behaviorSet[BSET_USE]) { + if (self->spawnflags & 1) { + if (!self->activator) { + Q3_DebugPrint(WL_ERROR, "target_scriptrunner tried to run on invalid entity!\n"); return; } - if ( !self->activator->sequencer || !self->activator->taskManager ) - {//Need to be initialized through ICARUS - if ( !self->activator->script_targetname || !self->activator->script_targetname[0] ) - { - //We don't have a script_targetname, so create a new one - self->activator->script_targetname = va( "newICARUSEnt%d", numNewICARUSEnts++ ); + if (!self->activator->sequencer || !self->activator->taskManager) { // Need to be initialized through ICARUS + if (!self->activator->script_targetname || !self->activator->script_targetname[0]) { + // We don't have a script_targetname, so create a new one + self->activator->script_targetname = va("newICARUSEnt%d", numNewICARUSEnts++); } - if ( ICARUS_ValidEnt( self->activator ) ) - { - ICARUS_InitEnt( self->activator ); - } - else - { - Q3_DebugPrint( WL_ERROR, "target_scriptrunner tried to run on invalid ICARUS activator!\n"); + if (ICARUS_ValidEnt(self->activator)) { + ICARUS_InitEnt(self->activator); + } else { + Q3_DebugPrint(WL_ERROR, "target_scriptrunner tried to run on invalid ICARUS activator!\n"); return; } } - Q3_DebugPrint( WL_VERBOSE, "target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], self->activator->targetname ); - ICARUS_RunScript( self->activator, va( "%s/%s", Q3_SCRIPT_DIR, self->behaviorSet[BSET_USE] ) ); - } - else - { - if ( self->activator ) - { - Q3_DebugPrint( WL_VERBOSE, "target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname ); + Q3_DebugPrint(WL_VERBOSE, "target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], self->activator->targetname); + ICARUS_RunScript(self->activator, va("%s/%s", Q3_SCRIPT_DIR, self->behaviorSet[BSET_USE])); + } else { + if (self->activator) { + Q3_DebugPrint(WL_VERBOSE, "target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname); } - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); } } - if ( self->wait ) - { + if (self->wait) { self->nextthink = level.time + self->wait; } } -void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->nextthink > level.time ) - { +void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->nextthink > level.time) { return; } self->activator = activator; - G_SetEnemy( self, other ); - if ( self->delay ) - {//delay before firing scriptrunner + G_SetEnemy(self, other); + if (self->delay) { // delay before firing scriptrunner self->e_ThinkFunc = thinkF_scriptrunner_run; self->nextthink = level.time + self->delay; - } - else - { - scriptrunner_run (self); + } else { + scriptrunner_run(self); } } @@ -828,16 +715,13 @@ wait - can't be used again in this amount of seconds (Default is 1 second if it' delay - how long to wait after use to run script */ -void SP_target_scriptrunner( gentity_t *self ) -{ - if ( self->spawnflags & 128 ) - { +void SP_target_scriptrunner(gentity_t *self) { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } - if ( !self->count ) - { - self->count = 1;//default 1 use only + if (!self->count) { + self->count = 1; // default 1 use only } /* else if ( !self->wait ) @@ -845,28 +729,25 @@ void SP_target_scriptrunner( gentity_t *self ) self->wait = 1;//default wait of 1 sec } */ - // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be able to set less than a second delays - // no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next project + // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be + // able to set less than a second delays no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next + // project self->radius = 0.0f; - G_SpawnFloat( "delay", "0", &self->radius ); - self->delay = self->radius * 1000;//sec to ms - self->wait *= 1000;//sec to ms + G_SpawnFloat("delay", "0", &self->radius); + self->delay = self->radius * 1000; // sec to ms + self->wait *= 1000; // sec to ms - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_scriptrunner_use; } -void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { gi.cvar_set("g_gravity", va("%f", self->speed)); - } - else if ( activator->client ) - { - int grav = floor(self->speed); + } else if (activator->client) { + int grav = floor(self->speed); /* if ( activator->client->ps.gravity != grav ) { @@ -875,7 +756,7 @@ void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *act */ activator->client->ps.gravity = grav; activator->svFlags |= SVF_CUSTOM_GRAVITY; - //FIXME: need a way to set this back to normal? + // FIXME: need a way to set this back to normal? } } @@ -885,23 +766,18 @@ void target_gravity_change_use(gentity_t *self, gentity_t *other, gentity_t *act GLOBAL - Apply to entire world, not just the activator */ -void SP_target_gravity_change( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); - G_SpawnFloat( "gravity", "0", &self->speed ); +void SP_target_gravity_change(gentity_t *self) { + G_SetOrigin(self, self->s.origin); + G_SpawnFloat("gravity", "0", &self->speed); self->e_UseFunc = useF_target_gravity_change_use; } -void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if(self->spawnflags & 1) - {//FIXME - make a global? - //gi.Cvar_Set("g_friction", va("%d", self->health)); - } - else if(activator->client) - { + if (self->spawnflags & 1) { // FIXME - make a global? + // gi.Cvar_Set("g_friction", va("%d", self->health)); + } else if (activator->client) { activator->client->ps.friction = self->health; } } @@ -911,32 +787,24 @@ void target_friction_change_use(gentity_t *self, gentity_t *other, gentity_t *ac "friction" Normal = 6, Valid range 0 - 10 */ -void SP_target_friction_change( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_friction_change(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_friction_change_use; } - -extern void G_ChangeMap (const char *mapname, const char *spawntarget, qboolean hub); //g_utils -void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - if( self->message && !Q_stricmp( "disconnect", self->message ) ) - { - gi.SendConsoleCommand( "disconnect\n"); - } - else - { - G_ChangeMap( self->message, self->target, (qboolean)(self->spawnflags & 1) ); +extern void G_ChangeMap(const char *mapname, const char *spawntarget, qboolean hub); // g_utils +void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + if (self->message && !Q_stricmp("disconnect", self->message)) { + gi.SendConsoleCommand("disconnect\n"); + } else { + G_ChangeMap(self->message, self->target, (qboolean)(self->spawnflags & 1)); } - if (self->spawnflags&2) //HIDEINFO + if (self->spawnflags & 2) // HIDEINFO { gi.cvar_set("cg_missionstatusscreen", "0"); - } - else - { - gi.cvar_set("cg_missionstatusscreen", "1"); //turn it on! + } else { + gi.cvar_set("cg_missionstatusscreen", "1"); // turn it on! } } @@ -946,14 +814,12 @@ HUB - Will save the current map's status and load the next map with any saved st "mapname" - Name of map to change to "target" - Name of spawnpoint to start at in the new map */ -void SP_target_level_change( gentity_t *self ) -{ - if ( !self->message ) - { - G_Error( "target_level_change with no mapname!"); +void SP_target_level_change(gentity_t *self) { + if (!self->message) { + G_Error("target_level_change with no mapname!"); return; } - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_level_change_use; } @@ -976,41 +842,33 @@ parm14 parm15 parm16 */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue); -void target_change_parm_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( !activator || !self ) - { +void Q3_SetParm(int entID, int parmNum, const char *parmValue); +void target_change_parm_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator || !self) { return; } - //FIXME: call capyparms - if ( self->parms ) - { - for ( int parmNum = 0; parmNum < MAX_PARMS; parmNum++ ) - { - if ( self->parms->parm[parmNum] && self->parms->parm[parmNum][0] ) - { - Q3_SetParm( activator->s.number, parmNum, self->parms->parm[parmNum] ); + // FIXME: call capyparms + if (self->parms) { + for (int parmNum = 0; parmNum < MAX_PARMS; parmNum++) { + if (self->parms->parm[parmNum] && self->parms->parm[parmNum][0]) { + Q3_SetParm(activator->s.number, parmNum, self->parms->parm[parmNum]); } } } } -void SP_target_change_parm( gentity_t *self ) -{ - if ( !self->parms ) - {//ERROR! +void SP_target_change_parm(gentity_t *self) { + if (!self->parms) { // ERROR! return; } - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_change_parm_use; } -void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - gi.SetConfigstring( CS_MUSIC, self->message ); +void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + gi.SetConfigstring(CS_MUSIC, self->message); } /*QUAKED target_play_music (1 0 0) (-4 -4 -4) (4 4 4) @@ -1024,80 +882,71 @@ If an intro file and loop file are specified, the intro plays first, then the lo portion will start and loop indefinetly. If no introfile is entered, only the loopfile will play. */ -void SP_target_play_music( gentity_t *self ) -{ +void SP_target_play_music(gentity_t *self) { char *s; - G_SetOrigin( self, self->s.origin ); - if (!G_SpawnString( "music", "", &s )) { - G_Error( "target_play_music without a music key at %s", vtos( self->s.origin ) ); + G_SetOrigin(self, self->s.origin); + if (!G_SpawnString("music", "", &s)) { + G_Error("target_play_music without a music key at %s", vtos(self->s.origin)); } - self->message = G_NewString (s); + self->message = G_NewString(s); self->e_UseFunc = useF_target_play_music_use; -extern cvar_t *com_buildScript; - //Precache! - if (com_buildScript->integer) {//copy this puppy over + extern cvar_t *com_buildScript; + // Precache! + if (com_buildScript->integer) { // copy this puppy over char buffer[MAX_QPATH]; - fileHandle_t hFile; + fileHandle_t hFile; + + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".mp3"); - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".mp3"); - gi.FS_FOpenFile(buffer, &hFile, FS_READ); if (hFile) { - gi.FS_FCloseFile( hFile ); + gi.FS_FCloseFile(hFile); } } } -void target_autosave_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - //gi.SendServerCommand( 0, "cp @INGAME_CHECKPOINT" ); - CG_CenterPrint( "@INGAME_CHECKPOINT", SCREEN_HEIGHT * 0.25 ); //jump the network +void target_autosave_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + // gi.SendServerCommand( 0, "cp @INGAME_CHECKPOINT" ); + CG_CenterPrint("@INGAME_CHECKPOINT", SCREEN_HEIGHT * 0.25); // jump the network -// if (self->spawnflags & 1) - gi.SendConsoleCommand( "wait 2;save auto\n" ); + // if (self->spawnflags & 1) + gi.SendConsoleCommand("wait 2;save auto\n"); } /*QUAKED target_autosave (1 0 0) (-4 -4 -4) (4 4 4) Auto save the game right now. Might be a slight chug to capture the thumbnail. Make sure it won't trigger during dialogue or cinematic or it will stutter! */ -void SP_target_autosave( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_autosave(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_autosave_use; } -void target_secret_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - //we'll assume that the activator is the player - gclient_t* const client = &level.clients[0]; +void target_secret_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + // we'll assume that the activator is the player + gclient_t *const client = &level.clients[0]; client->sess.missionStats.secretsFound++; - if ( activator ) - { - G_Sound( activator, self->noise_index ); - } - else - { - G_Sound( self, self->noise_index ); + if (activator) { + G_Sound(activator, self->noise_index); + } else { + G_Sound(self, self->noise_index); } - gi.SendServerCommand( 0, "cp @INGAME_SECRET_AREA" ); + gi.SendServerCommand(0, "cp @INGAME_SECRET_AREA"); assert(client->sess.missionStats.totalSecrets); } /*QUAKED target_secret (1 0 1) (-4 -4 -4) (4 4 4) You found a Secret! "count" - how many secrets on this level, - if more than one on a level, be sure they all have the same count! + if more than one on a level, be sure they all have the same count! */ -void SP_target_secret( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_secret(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_secret_use; self->noise_index = G_SoundIndex("sound/interface/secret_area"); - if (self->count) - { - gi.cvar_set("newTotalSecrets", va("%i",self->count)); + if (self->count) { + gi.cvar_set("newTotalSecrets", va("%i", self->count)); } } diff --git a/codeJK2/game/g_trigger.cpp b/codeJK2/game/g_trigger.cpp index 6e6e7ac6af..9ad4bc34f1 100644 --- a/codeJK2/game/g_trigger.cpp +++ b/codeJK2/game/g_trigger.cpp @@ -26,326 +26,255 @@ along with this program; if not, see . #include "b_local.h" #include "anims.h" -#define ENTDIST_PLAYER 1 -#define ENTDIST_NPC 2 +#define ENTDIST_PLAYER 1 +#define ENTDIST_NPC 2 -extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); -extern qboolean G_ClearTrace( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -extern qboolean PM_CrouchAnim( int anim ); +extern qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs); +extern qboolean G_ClearTrace(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +extern qboolean PM_CrouchAnim(int anim); -void InitTrigger( gentity_t *self ) { - if (!VectorCompare (self->s.angles, vec3_origin)) - G_SetMovedir (self->s.angles, self->movedir); +void InitTrigger(gentity_t *self) { + if (!VectorCompare(self->s.angles, vec3_origin)) + G_SetMovedir(self->s.angles, self->movedir); - gi.SetBrushModel( self, self->model ); - self->contents = CONTENTS_TRIGGER; // replaces the -1 from gi.SetBrushModel + gi.SetBrushModel(self, self->model); + self->contents = CONTENTS_TRIGGER; // replaces the -1 from gi.SetBrushModel self->svFlags = SVF_NOCLIENT; - if(self->spawnflags & 128) - { + if (self->spawnflags & 128) { self->svFlags |= SVF_INACTIVE; } } - // the wait time has passed, so set back up for another activation -void multi_wait( gentity_t *ent ) { - ent->nextthink = 0; -} - +void multi_wait(gentity_t *ent) { ent->nextthink = 0; } // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing -void multi_trigger_run( gentity_t *ent ) -{ +void multi_trigger_run(gentity_t *ent) { ent->e_ThinkFunc = thinkF_NULL; - G_ActivateBehavior( ent, BSET_USE ); + G_ActivateBehavior(ent, BSET_USE); - if ( ent->soundSet && ent->soundSet[0] ) - { - gi.SetConfigstring( CS_AMBIENT_SET, ent->soundSet ); + if (ent->soundSet && ent->soundSet[0]) { + gi.SetConfigstring(CS_AMBIENT_SET, ent->soundSet); } - G_UseTargets (ent, ent->activator); - if ( ent->noise_index ) - { - G_Sound( ent->activator, ent->noise_index ); + G_UseTargets(ent, ent->activator); + if (ent->noise_index) { + G_Sound(ent->activator, ent->noise_index); } - if ( ent->target2 && ent->target2[0] && ent->wait >= 0 ) - { + if (ent->target2 && ent->target2[0] && ent->wait >= 0) { ent->e_ThinkFunc = thinkF_trigger_cleared_fire; ent->nextthink = level.time + ent->speed; - } - else if ( ent->wait > 0 ) - { - if ( ent->painDebounceTime != level.time ) - {//first ent to touch it this frame - //ent->e_ThinkFunc = thinkF_multi_wait; - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + } else if (ent->wait > 0) { + if (ent->painDebounceTime != level.time) { // first ent to touch it this frame + // ent->e_ThinkFunc = thinkF_multi_wait; + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->painDebounceTime = level.time; } - } - else if ( ent->wait < 0 ) - { + } else if (ent->wait < 0) { // we can't just remove (self) here, because this is a touch function // called while looping through area links... - ent->contents &= ~CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + ent->contents &= ~CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me ent->e_TouchFunc = touchF_NULL; ent->e_UseFunc = useF_NULL; - //Don't remove, Icarus may barf? - //ent->nextthink = level.time + FRAMETIME; - //ent->think = G_FreeEntity; + // Don't remove, Icarus may barf? + // ent->nextthink = level.time + FRAMETIME; + // ent->think = G_FreeEntity; } - if( ent->activator && ent->activator->s.number == 0 ) - { // mark the trigger as being touched by the player + if (ent->activator && ent->activator->s.number == 0) { // mark the trigger as being touched by the player ent->aimDebounceTime = level.time; } } - -void multi_trigger( gentity_t *ent, gentity_t *activator ) -{ - if ( ent->e_ThinkFunc == thinkF_multi_trigger_run ) - {//already triggered, just waiting to run +void multi_trigger(gentity_t *ent, gentity_t *activator) { + if (ent->e_ThinkFunc == thinkF_multi_trigger_run) { // already triggered, just waiting to run return; } - if ( ent->nextthink > level.time ) - { - if( ent->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in a single frame + if (ent->nextthink > level.time) { + if (ent->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in a single frame { - if ( ent->painDebounceTime && ent->painDebounceTime != level.time ) - {//this should still allow subsequent ents to fire this trigger in the current frame - return; // can't retrigger until the wait is over + if (ent->painDebounceTime && + ent->painDebounceTime != level.time) { // this should still allow subsequent ents to fire this trigger in the current frame + return; // can't retrigger until the wait is over } - } - else - { + } else { return; } - } // if the player has already activated this trigger this frame - if( activator && !activator->s.number && ent->aimDebounceTime == level.time ) - { - return; + if (activator && !activator->s.number && ent->aimDebounceTime == level.time) { + return; } - if ( ent->svFlags & SVF_INACTIVE ) - {//Not active at this time + if (ent->svFlags & SVF_INACTIVE) { // Not active at this time return; } ent->activator = activator; - if(ent->delay && ent->painDebounceTime < (level.time + ent->delay) ) - {//delay before firing trigger + if (ent->delay && ent->painDebounceTime < (level.time + ent->delay)) { // delay before firing trigger ent->e_ThinkFunc = thinkF_multi_trigger_run; ent->nextthink = level.time + ent->delay; ent->painDebounceTime = level.time; - - } - else - { - multi_trigger_run (ent); + + } else { + multi_trigger_run(ent); } } -void Use_Multi( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - multi_trigger( ent, activator ); -} +void Use_Multi(gentity_t *ent, gentity_t *other, gentity_t *activator) { multi_trigger(ent, activator); } -void Touch_Multi( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if( !other->client ) - { +void Touch_Multi(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if( self->noDamageTeam ) - { - if ( other->client->playerTeam != self->noDamageTeam ) - { + if (self->noDamageTeam) { + if (other->client->playerTeam != self->noDamageTeam) { return; } } -// moved to just above multi_trigger because up here it just checks if the trigger is not being touched -// we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" -// if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) -// {//We're waiting to fire our target2 first -// self->nextthink = level.time + self->speed; -// return; -// } + // moved to just above multi_trigger because up here it just checks if the trigger is not being touched + // we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" + // if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) + // {//We're waiting to fire our target2 first + // self->nextthink = level.time + self->speed; + // return; + // } - if ( self->spawnflags & 1 ) - { - if ( other->s.number != 0 ) - { + if (self->spawnflags & 1) { + if (other->s.number != 0) { return; } - } - else - { - if ( self->spawnflags & 16 ) - {//NPCONLY - if ( other->NPC == NULL ) - { + } else { + if (self->spawnflags & 16) { // NPCONLY + if (other->NPC == NULL) { return; } } - if ( self->NPC_targetname && self->NPC_targetname[0] ) - { - if ( other->script_targetname && other->script_targetname[0] ) - { - if ( Q_stricmp( self->NPC_targetname, other->script_targetname ) != 0 ) - {//not the right guy to fire me off + if (self->NPC_targetname && self->NPC_targetname[0]) { + if (other->script_targetname && other->script_targetname[0]) { + if (Q_stricmp(self->NPC_targetname, other->script_targetname) != 0) { // not the right guy to fire me off return; } - } - else - { + } else { return; } } } - if ( self->spawnflags & 2 ) - {//FACING - vec3_t forward; + if (self->spawnflags & 2) { // FACING + vec3_t forward; - if ( other->client ) - { - AngleVectors( other->client->ps.viewangles, forward, NULL, NULL ); - } - else - { - AngleVectors( other->currentAngles, forward, NULL, NULL ); + if (other->client) { + AngleVectors(other->client->ps.viewangles, forward, NULL, NULL); + } else { + AngleVectors(other->currentAngles, forward, NULL, NULL); } - if ( DotProduct( self->movedir, forward ) < 0.5 ) - {//Not Within 45 degrees + if (DotProduct(self->movedir, forward) < 0.5) { // Not Within 45 degrees return; } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - if ( !other->client ) - { + if (self->spawnflags & 4) { // USE_BUTTON + if (!other->client) { return; } - if( !( other->client->usercmd.buttons & BUTTON_USE ) ) - {//not pressing use button + if (!(other->client->usercmd.buttons & BUTTON_USE)) { // not pressing use button return; } } - if ( self->spawnflags & 8 ) - {//FIRE_BUTTON - if ( !other->client ) - { + if (self->spawnflags & 8) { // FIRE_BUTTON + if (!other->client) { return; } - if( !( other->client->ps.eFlags & EF_FIRING /*usercmd.buttons & BUTTON_ATTACK*/ ) && - !( other->client->ps.eFlags & EF_ALT_FIRING/*usercmd.buttons & BUTTON_ALT_ATTACK*/ ) ) - {//not pressing fire button or altfire button + if (!(other->client->ps.eFlags & EF_FIRING /*usercmd.buttons & BUTTON_ATTACK*/) && + !(other->client->ps.eFlags & EF_ALT_FIRING /*usercmd.buttons & BUTTON_ALT_ATTACK*/)) { // not pressing fire button or altfire button return; } - //FIXME: do we care about the sniper rifle or not? + // FIXME: do we care about the sniper rifle or not? - if( other->s.number == 0 && ( other->client->ps.weapon > MAX_PLAYER_WEAPONS || other->client->ps.weapon <= WP_NONE ) ) - {//don't care about non-player weapons if this is the player + if (other->s.number == 0 && (other->client->ps.weapon > MAX_PLAYER_WEAPONS || + other->client->ps.weapon <= WP_NONE)) { // don't care about non-player weapons if this is the player return; } } - if ( other->client && self->radius ) - { - vec3_t eyeSpot; + if (other->client && self->radius) { + vec3_t eyeSpot; - //Only works if your head is in it, but we allow leaning out - //NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this - //to be reliant on the physical model the player uses. + // Only works if your head is in it, but we allow leaning out + // NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this + // to be reliant on the physical model the player uses. VectorCopy(other->currentOrigin, eyeSpot); eyeSpot[2] += other->client->ps.viewheight; - if ( G_PointInBounds( eyeSpot, self->absmin, self->absmax ) ) - { - if( !( other->client->ps.eFlags & EF_FIRING ) && - !( other->client->ps.eFlags & EF_ALT_FIRING ) ) - {//not attacking, so hiding bonus - //FIXME: should really have sound events clear the hiddenDist + if (G_PointInBounds(eyeSpot, self->absmin, self->absmax)) { + if (!(other->client->ps.eFlags & EF_FIRING) && !(other->client->ps.eFlags & EF_ALT_FIRING)) { // not attacking, so hiding bonus + // FIXME: should really have sound events clear the hiddenDist other->client->hiddenDist = self->radius; - //NOTE: movedir HAS to be normalized! - if ( VectorLength( self->movedir ) ) - {//They can only be hidden from enemies looking in this direction - VectorCopy( self->movedir, other->client->hiddenDir ); - } - else - { - VectorClear( other->client->hiddenDir ); + // NOTE: movedir HAS to be normalized! + if (VectorLength(self->movedir)) { // They can only be hidden from enemies looking in this direction + VectorCopy(self->movedir, other->client->hiddenDir); + } else { + VectorClear(other->client->hiddenDir); } } } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - NPC_SetAnim( other, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->spawnflags & 4) { // USE_BUTTON + NPC_SetAnim(other, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); /* if ( !VectorLengthSquared( other->client->ps.velocity ) && !PM_CrouchAnim( other->client->ps.legsAnim ) ) { NPC_SetAnim( other, SETANIM_LEGS, BOTH_BUTTON_HOLD, SETANIM_FLAG_NORMAL|SETANIM_FLAG_HOLD ); } */ - //other->client->ps.weaponTime = other->client->ps.torsoAnimTimer; + // other->client->ps.weaponTime = other->client->ps.torsoAnimTimer; } - - if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) - {//We're waiting to fire our target2 first + + if (self->e_ThinkFunc == thinkF_trigger_cleared_fire) { // We're waiting to fire our target2 first self->nextthink = level.time + self->speed; return; } - multi_trigger( self, other ); + multi_trigger(self, other); } -void trigger_cleared_fire (gentity_t *self) -{ - G_UseTargets2( self, self->activator, self->target2 ); +void trigger_cleared_fire(gentity_t *self) { + G_UseTargets2(self, self->activator, self->target2); self->e_ThinkFunc = thinkF_NULL; // should start the wait timer now, because the trigger's just been cleared, so we must "wait" from this point - if ( self->wait > 0 ) - { - self->nextthink = level.time + ( self->wait + self->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + if (self->wait > 0) { + self->nextthink = level.time + (self->wait + self->random * Q_flrand(-1.0f, 1.0f)) * 1000; } } -qboolean G_TriggerActive( gentity_t *self ) -{ - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +qboolean G_TriggerActive(gentity_t *self) { + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return qfalse; } - if ( self->spawnflags & 1 ) - {//player only + if (self->spawnflags & 1) { // player only return qfalse; } @@ -388,8 +317,10 @@ MULTIPLE - multiple entities can touch this trigger in a single frame *and* if n "wait" Seconds between triggerings, 0 default, number < 0 means one time only. "random" wait variance, default is 0 "delay" how many seconds to wait to fire targets after tripped -"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but not standing should be 48 tall. -"target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') +"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from +enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but +not standing should be 48 tall. "target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the +conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') "speed" How many seconds to wait to fire the target2, default is 1 "noise" Sound to play when the trigger fires (plays at activator's origin) @@ -405,48 +336,41 @@ so, the basic time between firing is a random time between "soundSet" Ambient sound set to play when this trigger is activated */ -team_t TranslateTeamName( const char *name ); -void SP_trigger_multiple( gentity_t *ent ) -{ - char buffer[MAX_QPATH]; - char *s; - if ( G_SpawnString( "noise", "*NOSOUND*", &s ) ) - { - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); +team_t TranslateTeamName(const char *name); +void SP_trigger_multiple(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + if (G_SpawnString("noise", "*NOSOUND*", &s)) { + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); } - - G_SpawnFloat( "wait", "0", &ent->wait );//was 0.5 ... but that means wait can never be zero... we should probably put it back to 0.5, though... - G_SpawnFloat( "random", "0", &ent->random ); + G_SpawnFloat("wait", "0", &ent->wait); // was 0.5 ... but that means wait can never be zero... we should probably put it back to 0.5, though... + G_SpawnFloat("random", "0", &ent->random); - if ( (ent->wait > 0) && (ent->random >= ent->wait) ) { + if ((ent->wait > 0) && (ent->random >= ent->wait)) { ent->random = ent->wait - FRAMETIME; - gi.Printf(S_COLOR_YELLOW"trigger_multiple has random >= wait\n"); + gi.Printf(S_COLOR_YELLOW "trigger_multiple has random >= wait\n"); } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec - if ( !ent->speed && ent->target2 && ent->target2[0] ) - { + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec + if (!ent->speed && ent->target2 && ent->target2[0]) { ent->speed = 1000; - } - else - { + } else { ent->speed *= 1000; } ent->e_TouchFunc = touchF_Touch_Multi; - ent->e_UseFunc = useF_Use_Multi; + ent->e_UseFunc = useF_Use_Multi; - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = TranslateTeamName( ent->team ); + if (ent->team && ent->team[0]) { + ent->noDamageTeam = TranslateTeamName(ent->team); ent->team = NULL; } - InitTrigger( ent ); - gi.linkentity (ent); + InitTrigger(ent); + gi.linkentity(ent); } /*QUAKED trigger_once (.5 1 .5) ? PLAYERONLY FACING USE_BUTTON FIRE_BUTTON NPCONLY x x INACTIVE MULTIPLE @@ -473,35 +397,31 @@ so, the basic time between firing is a random time between "soundSet" Ambient sound set to play when this trigger is activated */ -void SP_trigger_once( gentity_t *ent ) -{ - char buffer[MAX_QPATH]; - char *s; - if ( G_SpawnString( "noise", "*NOSOUND*", &s ) ) - { - Q_strncpyz( buffer, s, sizeof(buffer) ); - COM_DefaultExtension( buffer, sizeof(buffer), ".wav"); +void SP_trigger_once(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; + if (G_SpawnString("noise", "*NOSOUND*", &s)) { + Q_strncpyz(buffer, s, sizeof(buffer)); + COM_DefaultExtension(buffer, sizeof(buffer), ".wav"); ent->noise_index = G_SoundIndex(buffer); } ent->wait = -1; ent->e_TouchFunc = touchF_Touch_Multi; - ent->e_UseFunc = useF_Use_Multi; + ent->e_UseFunc = useF_Use_Multi; - if ( ent->team && ent->team[0] ) - { - ent->noDamageTeam = TranslateTeamName( ent->team ); + if (ent->team && ent->team[0]) { + ent->noDamageTeam = TranslateTeamName(ent->team); ent->team = NULL; } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - InitTrigger( ent ); - gi.linkentity (ent); + InitTrigger(ent); + gi.linkentity(ent); } - /*QUAKED trigger_bidirectional (.1 .5 .1) ? PLAYER_ONLY x x x x x x INACTIVE NOT IMPLEMENTED INACTIVE - Start off, has to be activated to be touchable/usable @@ -517,41 +437,37 @@ Fires "backwardstarget" when someone moves through it in the opposite direction TODO: count */ -void SP_trigger_bidirectional( gentity_t *ent ) -{ +void SP_trigger_bidirectional(gentity_t *ent) { G_FreeEntity(ent); - //FIXME: Implement -/* if(!ent->wait) - { - ent->wait = -1; - } + // FIXME: Implement + /* if(!ent->wait) + { + ent->wait = -1; + } - ent->touch = Touch_Multi; - ent->use = Use_Multi; - - InitTrigger( ent ); - gi.linkentity (ent); -*/ + ent->touch = Touch_Multi; + ent->use = Use_Multi; + + InitTrigger( ent ); + gi.linkentity (ent); + */ } -/*QUAKED trigger_location (.1 .5 .1) ? +/*QUAKED trigger_location (.1 .5 .1) ? When an ent is asked for it's location, it will return this ent's "message" field if it is in it. "message" - location name NOTE: always rectangular */ -char *G_GetLocationForEnt( gentity_t *ent ) -{ - vec3_t mins, maxs; - gentity_t *found = NULL; +char *G_GetLocationForEnt(gentity_t *ent) { + vec3_t mins, maxs; + gentity_t *found = NULL; - VectorAdd( ent->currentOrigin, ent->mins, mins ); - VectorAdd( ent->currentOrigin, ent->maxs, maxs ); + VectorAdd(ent->currentOrigin, ent->mins, mins); + VectorAdd(ent->currentOrigin, ent->maxs, maxs); - while( (found = G_Find(found, FOFS(classname), "trigger_location")) != NULL ) - { - if ( gi.EntityContact( mins, maxs, found ) ) - { + while ((found = G_Find(found, FOFS(classname), "trigger_location")) != NULL) { + if (gi.EntityContact(mins, maxs, found)) { return found->message; } } @@ -559,20 +475,18 @@ char *G_GetLocationForEnt( gentity_t *ent ) return NULL; } -void SP_trigger_location( gentity_t *ent ) -{ - if ( !ent->message || !ent->message[0] ) - { +void SP_trigger_location(gentity_t *ent) { + if (!ent->message || !ent->message[0]) { gi.Printf("WARNING: trigger_location with no message!\n"); G_FreeEntity(ent); return; } - gi.SetBrushModel( ent, ent->model ); + gi.SetBrushModel(ent, ent->model); ent->contents = 0; ent->svFlags = SVF_NOCLIENT; - gi.linkentity (ent); + gi.linkentity(ent); } /* ============================================================================== @@ -582,21 +496,20 @@ trigger_always ============================================================================== */ -void trigger_always_think( gentity_t *ent ) { +void trigger_always_think(gentity_t *ent) { G_UseTargets(ent, ent); - G_FreeEntity( ent ); + G_FreeEntity(ent); } /*QUAKED trigger_always (.1 .5 .1) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ -void SP_trigger_always (gentity_t *ent) { +void SP_trigger_always(gentity_t *ent) { // we must have some delay to make sure our use targets are present ent->nextthink = level.time + 300; ent->e_ThinkFunc = thinkF_trigger_always_think; } - /* ============================================================================== @@ -604,111 +517,88 @@ trigger_push ============================================================================== */ -#define PUSH_CONVEYOR 32 -void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +#define PUSH_CONVEYOR 32 +void trigger_push_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - if( level.time < self->painDebounceTime + self->wait ) // normal 'wait' check + if (level.time < self->painDebounceTime + self->wait) // normal 'wait' check { - if( self->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in one frame + if (self->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in one frame { - if ( self->painDebounceTime && level.time > self->painDebounceTime ) // if we haven't reached the next frame continue to let ents touch the trigger + if (self->painDebounceTime && level.time > self->painDebounceTime) // if we haven't reached the next frame continue to let ents touch the trigger { return; } - } - else // only allowing one ent per frame to touch trigger + } else // only allowing one ent per frame to touch trigger { return; } } // if the player has already activated this trigger this frame - if( other && !other->s.number && self->aimDebounceTime == level.time ) - { - return; + if (other && !other->s.number && self->aimDebounceTime == level.time) { + return; } - - - if( self->spawnflags & PUSH_CONVEYOR ) - { // only push player if he's on the ground - if( other->s.groundEntityNum == ENTITYNUM_NONE ) - { + + if (self->spawnflags & PUSH_CONVEYOR) { // only push player if he's on the ground + if (other->s.groundEntityNum == ENTITYNUM_NONE) { return; } } - if ( self->spawnflags & 1 ) - {//PLAYERONLY - if ( other->s.number != 0 ) - { + if (self->spawnflags & 1) { // PLAYERONLY + if (other->s.number != 0) { return; } - } - else - { - if ( self->spawnflags & 8 ) - {//NPCONLY - if ( other->NPC == NULL ) - { + } else { + if (self->spawnflags & 8) { // NPCONLY + if (other->NPC == NULL) { return; } } } - if ( !other->client ) { - if ( other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && VectorLengthSquared( other->s.pos.trDelta ) ) - {//already moving - VectorCopy( other->currentOrigin, other->s.pos.trBase ); - VectorCopy( self->s.origin2, other->s.pos.trDelta ); + if (!other->client) { + if (other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && + VectorLengthSquared(other->s.pos.trDelta)) { // already moving + VectorCopy(other->currentOrigin, other->s.pos.trBase); + VectorCopy(self->s.origin2, other->s.pos.trDelta); other->s.pos.trTime = level.time; } return; } - if ( other->client->ps.pm_type != PM_NORMAL ) { + if (other->client->ps.pm_type != PM_NORMAL) { return; } - - if ( (self->spawnflags&16) ) - {//relative, dir to it * speed + + if ((self->spawnflags & 16)) { // relative, dir to it * speed vec3_t dir; - VectorSubtract( self->s.origin2, other->currentOrigin, dir ); - if ( self->speed ) - { - VectorNormalize( dir ); - VectorScale( dir, self->speed, dir ); + VectorSubtract(self->s.origin2, other->currentOrigin, dir); + if (self->speed) { + VectorNormalize(dir); + VectorScale(dir, self->speed, dir); } - VectorCopy( dir, other->client->ps.velocity ); - } - else if ( (self->spawnflags&4) ) - {//linear dir * speed - VectorScale( self->s.origin2, self->speed, other->client->ps.velocity ); - } - else - { - VectorCopy( self->s.origin2, other->client->ps.velocity ); + VectorCopy(dir, other->client->ps.velocity); + } else if ((self->spawnflags & 4)) { // linear dir * speed + VectorScale(self->s.origin2, self->speed, other->client->ps.velocity); + } else { + VectorCopy(self->s.origin2, other->client->ps.velocity); } - //so we don't take damage unless we land lower than we start here... + // so we don't take damage unless we land lower than we start here... other->client->ps.forceJumpZStart = 0; - other->client->ps.pm_flags |= PMF_TRIGGER_PUSHED;//pushed by a trigger + other->client->ps.pm_flags |= PMF_TRIGGER_PUSHED; // pushed by a trigger other->client->ps.jumpZStart = other->client->ps.origin[2]; - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->e_TouchFunc = touchF_NULL; - } - else if ( self->wait > 0 ) - { + } else if (self->wait > 0) { self->painDebounceTime = level.time; - } - if( other && !other->s.number ) - { // mark that the player has activated this trigger this frame - self->aimDebounceTime =level.time; + if (other && !other->s.number) { // mark that the player has activated this trigger this frame + self->aimDebounceTime = level.time; } } @@ -721,105 +611,90 @@ AimAtTarget Calculate origin2 so the target apogee will be hit ================= */ -void AimAtTarget( gentity_t *self ) -{ - gentity_t *ent; - vec3_t origin; - float height, gravity, time, forward; - float dist; - - VectorAdd( self->absmin, self->absmax, origin ); - VectorScale ( origin, 0.5, origin ); - - ent = G_PickTarget( self->target ); - if ( !ent ) - { - G_FreeEntity( self ); +void AimAtTarget(gentity_t *self) { + gentity_t *ent; + vec3_t origin; + float height, gravity, time, forward; + float dist; + + VectorAdd(self->absmin, self->absmax, origin); + VectorScale(origin, 0.5, origin); + + ent = G_PickTarget(self->target); + if (!ent) { + G_FreeEntity(self); return; } - if ( self->classname && !Q_stricmp( "trigger_push", self->classname ) ) - { - if ( (self->spawnflags&2) ) - {//check once a second to see if we should activate or deactivate ourselves + if (self->classname && !Q_stricmp("trigger_push", self->classname)) { + if ((self->spawnflags & 2)) { // check once a second to see if we should activate or deactivate ourselves self->e_ThinkFunc = thinkF_trigger_push_checkclear; self->nextthink = level.time + FRAMETIME; } - if ( (self->spawnflags&16) ) - {//relative, not an arc or linear - VectorCopy( ent->currentOrigin, self->s.origin2 ); + if ((self->spawnflags & 16)) { // relative, not an arc or linear + VectorCopy(ent->currentOrigin, self->s.origin2); return; - } - else if ( (self->spawnflags&4) ) - {//linear, not an arc - VectorSubtract( ent->currentOrigin, origin, self->s.origin2 ); - VectorNormalize( self->s.origin2 ); + } else if ((self->spawnflags & 4)) { // linear, not an arc + VectorSubtract(ent->currentOrigin, origin, self->s.origin2); + VectorNormalize(self->s.origin2); return; } } - if ( self->classname && !Q_stricmp( "target_push", self->classname ) ) - { - if( self->spawnflags & PUSH_CONSTANT ) - { - VectorSubtract ( ent->s.origin, self->s.origin, self->s.origin2 ); - VectorNormalize( self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + if (self->classname && !Q_stricmp("target_push", self->classname)) { + if (self->spawnflags & PUSH_CONSTANT) { + VectorSubtract(ent->s.origin, self->s.origin, self->s.origin2); + VectorNormalize(self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); return; } } height = ent->s.origin[2] - origin[2]; - if ( height < 0 ) - {//sqrt of negative is bad! + if (height < 0) { // sqrt of negative is bad! height = 0; } gravity = g_gravity->value; - if ( gravity < 0 ) - { + if (gravity < 0) { gravity = 0; } - time = sqrt( height / ( .5 * gravity ) ); - if ( !time ) { - G_FreeEntity( self ); + time = sqrt(height / (.5 * gravity)); + if (!time) { + G_FreeEntity(self); return; } // set s.origin2 to the push velocity - VectorSubtract ( ent->s.origin, origin, self->s.origin2 ); + VectorSubtract(ent->s.origin, origin, self->s.origin2); self->s.origin2[2] = 0; - dist = VectorNormalize( self->s.origin2); + dist = VectorNormalize(self->s.origin2); forward = dist / time; - VectorScale( self->s.origin2, forward, self->s.origin2 ); + VectorScale(self->s.origin2, forward, self->s.origin2); self->s.origin2[2] = time * gravity; } -void trigger_push_checkclear( gentity_t *self ) -{ - trace_t trace; - vec3_t center; +void trigger_push_checkclear(gentity_t *self) { + trace_t trace; + vec3_t center; self->nextthink = level.time + 500; - VectorAdd( self->absmin, self->absmax, center ); - VectorScale( center, 0.5, center ); + VectorAdd(self->absmin, self->absmax, center); + VectorScale(center, 0.5, center); - gentity_t *target = G_Find( NULL, FOFS(targetname), self->target ); - gi.trace( &trace, center, vec3_origin, vec3_origin, target->currentOrigin, ENTITYNUM_NONE, CONTENTS_SOLID, G2_NOCOLLIDE, 0 ); + gentity_t *target = G_Find(NULL, FOFS(targetname), self->target); + gi.trace(&trace, center, vec3_origin, vec3_origin, target->currentOrigin, ENTITYNUM_NONE, CONTENTS_SOLID, G2_NOCOLLIDE, 0); - if ( trace.fraction >= 1.0f ) - {//can trace, turn on - self->contents |= CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + if (trace.fraction >= 1.0f) { // can trace, turn on + self->contents |= CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me self->e_TouchFunc = touchF_trigger_push_touch; - gi.linkentity( self ); - } - else - {//no trace, turn off - self->contents &= ~CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + gi.linkentity(self); + } else { // no trace, turn off + self->contents &= ~CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me self->e_TouchFunc = touchF_NULL; - gi.unlinkentity( self ); + gi.unlinkentity(self); } } /*QUAKED trigger_push (.1 .5 .1) ? PLAYERONLY CHECKCLEAR LINEAR NPCONLY RELATIVE CONVEYOR x INACTIVE MULTIPLE @@ -827,21 +702,20 @@ Must point at a target_position, which will be the apex of the leap. This will be client side predicted, unlike target_push PLAYERONLY - only the player is affected LINEAR - Instead of tossing the client at the target_position, it will push them towards it. Must set a "speed" (see below) -CHECKCLEAR - Every 1 second, it will check to see if it can trace to the target_position, if it can, the trigger is touchable, if it can't, the trigger is not touchable -NPCONLY - only NPCs are affected -RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the target_position, it pushes *you* toward the target position, relative to your current location (can use with "speed"... if don't set a speed, it will use the distance from you to the target_position) -CONVEYOR - acts like a conveyor belt, will only push if player is on the ground ( should probably use RELATIVE also, if you want a true conveyor belt ) -INACTIVE - not active until targeted by a target_activate -MULTIPLE - multiple entities can touch this trigger in a single frame *and* if needed, the trigger can have a wait of > 0 +CHECKCLEAR - Every 1 second, it will check to see if it can trace to the target_position, if it can, the trigger is touchable, if it can't, the trigger is not +touchable NPCONLY - only NPCs are affected RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the +target_position, it pushes *you* toward the target position, relative to your current location (can use with "speed"... if don't set a speed, it will use the +distance from you to the target_position) CONVEYOR - acts like a conveyor belt, will only push if player is on the ground ( should probably use RELATIVE also, +if you want a true conveyor belt ) INACTIVE - not active until targeted by a target_activate MULTIPLE - multiple entities can touch this trigger in a single +frame *and* if needed, the trigger can have a wait of > 0 wait - how long to wait between pushes: -1 = push only once speed - when used with the LINEAR spawnflag, pushes the client toward the position at a constant speed (default is 1000) */ -void SP_trigger_push( gentity_t *self ) { - InitTrigger (self); +void SP_trigger_push(gentity_t *self) { + InitTrigger(self); - if ( self->wait > 0 ) - { + if (self->wait > 0) { self->wait *= 1000; } @@ -849,50 +723,47 @@ void SP_trigger_push( gentity_t *self ) { self->svFlags &= ~SVF_NOCLIENT; self->s.eType = ET_PUSH_TRIGGER; - if ( !(self->spawnflags&2) ) - {//start on + if (!(self->spawnflags & 2)) { // start on self->e_TouchFunc = touchF_trigger_push_touch; } - if ( self->spawnflags & 4 ) - {//linear + if (self->spawnflags & 4) { // linear self->speed = 1000; } self->e_ThinkFunc = thinkF_AimAtTarget; self->nextthink = level.time + START_TIME_LINK_ENTS; - gi.linkentity (self); + gi.linkentity(self); } -void Use_target_push( gentity_t *self, gentity_t *other, gentity_t *activator ) { - if ( !activator->client ) { +void Use_target_push(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator->client) { return; } - if ( activator->client->ps.pm_type != PM_NORMAL ) { + if (activator->client->ps.pm_type != PM_NORMAL) { return; } - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - VectorCopy( self->s.origin2, activator->client->ps.velocity ); + VectorCopy(self->s.origin2, activator->client->ps.velocity); - if( self->spawnflags & 4 ) // lower + if (self->spawnflags & 4) // lower { // reset this so I don't take falling damage when I land activator->client->ps.jumpZStart = activator->currentOrigin[2]; } - //so we don't take damage unless we land lower than we start here... + // so we don't take damage unless we land lower than we start here... activator->client->ps.forceJumpZStart = 0; - activator->client->ps.pm_flags |= PMF_TRIGGER_PUSHED;//pushed by a trigger + activator->client->ps.pm_flags |= PMF_TRIGGER_PUSHED; // pushed by a trigger // play fly sound every 1.5 seconds - if ( self->noise_index && activator->fly_sound_debounce_time < level.time ) { + if (self->noise_index && activator->fly_sound_debounce_time < level.time) { activator->fly_sound_debounce_time = level.time + 1500; - G_Sound( activator, self->noise_index ); + G_Sound(activator, self->noise_index); } } - /*QUAKED target_push (.5 .5 .5) (-8 -8 -8) (8 8 8) ENERGYNOISE CONSTANT NO_DAMAGE When triggered, pushes the activator in the direction of angles "speed" defaults to 1000 @@ -900,25 +771,23 @@ ENERGYNOISE plays energy noise CONSTANT will push activator in direction of 'target' at constant 'speed' NO_DAMAGE the activator won't take falling damage after being pushed */ -void SP_target_push( gentity_t *self ) { - - +void SP_target_push(gentity_t *self) { + if (!self->speed) { self->speed = 1000; } - G_SetMovedir (self->s.angles, self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + G_SetMovedir(self->s.angles, self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); - if ( self->spawnflags & 1 ) { - //self->noise_index = G_SoundIndex("sound/ambience/forge/antigrav.wav"); + if (self->spawnflags & 1) { + // self->noise_index = G_SoundIndex("sound/ambience/forge/antigrav.wav"); } - if ( self->target ) { + if (self->target) { - VectorCopy( self->s.origin, self->absmin ); - VectorCopy( self->s.origin, self->absmax ); + VectorCopy(self->s.origin, self->absmin); + VectorCopy(self->s.origin, self->absmax); self->e_ThinkFunc = thinkF_AimAtTarget; self->nextthink = level.time + START_TIME_LINK_ENTS; - } self->e_UseFunc = useF_Use_target_push; } @@ -932,91 +801,76 @@ trigger_teleport */ #define SNAP_ANGLES 1 #define NO_MISSILES 2 -#define NO_NPCS 4 -#define TTSF_STASIS 8 -#define TTSF_DEAD_OK 16 -void TeleportMover( gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle ); -void trigger_teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace ) -{ - gentity_t *dest; - - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate +#define NO_NPCS 4 +#define TTSF_STASIS 8 +#define TTSF_DEAD_OK 16 +void TeleportMover(gentity_t *mover, vec3_t origin, vec3_t diffAngles, qboolean snapAngle); +void trigger_teleporter_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *dest; + + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - - dest = G_PickTarget( self->target ); - if (!dest) - { - gi.Printf ("Couldn't find teleporter destination\n"); + + dest = G_PickTarget(self->target); + if (!dest) { + gi.Printf("Couldn't find teleporter destination\n"); return; } - if ( other->client ) - { - if ( other->client->ps.pm_type == PM_DEAD ) - { - if ( !(self->spawnflags&TTSF_DEAD_OK) ) - {//dead men can't teleport + if (other->client) { + if (other->client->ps.pm_type == PM_DEAD) { + if (!(self->spawnflags & TTSF_DEAD_OK)) { // dead men can't teleport return; } } - if ( other->NPC ) - { - if ( self->spawnflags & NO_NPCS ) - { + if (other->NPC) { + if (self->spawnflags & NO_NPCS) { return; } } - if ( other->client->playerTeam != TEAM_FREE && SpotWouldTelefrag2( other, dest->currentOrigin ) )//SpotWouldTelefrag( dest, other->client->playerTeam ) ) - {//Don't go through if something blocking on the other side + if (other->client->playerTeam != TEAM_FREE && SpotWouldTelefrag2(other, dest->currentOrigin)) // SpotWouldTelefrag( dest, other->client->playerTeam ) ) + { // Don't go through if something blocking on the other side return; } - - TeleportPlayer( other, dest->s.origin, dest->s.angles ); + + TeleportPlayer(other, dest->s.origin, dest->s.angles); } - //FIXME: check for SVF_NO_TELEPORT - else if ( !(self->svFlags & SVF_NO_TELEPORT) && !(self->spawnflags & NO_MISSILES) && VectorLengthSquared( other->s.pos.trDelta ) ) - {//It's a mover of some sort and is currently moving - vec3_t diffAngles = {0, 0, 0}; - qboolean snap = qfalse; + // FIXME: check for SVF_NO_TELEPORT + else if (!(self->svFlags & SVF_NO_TELEPORT) && !(self->spawnflags & NO_MISSILES) && + VectorLengthSquared(other->s.pos.trDelta)) { // It's a mover of some sort and is currently moving + vec3_t diffAngles = {0, 0, 0}; + qboolean snap = qfalse; - if ( self->lastEnemy ) - { - VectorSubtract( dest->s.angles, self->lastEnemy->s.angles, diffAngles ); - } - else - {//snaps to angle - VectorSubtract( dest->s.angles, other->currentAngles, diffAngles ); + if (self->lastEnemy) { + VectorSubtract(dest->s.angles, self->lastEnemy->s.angles, diffAngles); + } else { // snaps to angle + VectorSubtract(dest->s.angles, other->currentAngles, diffAngles); snap = qtrue; } - TeleportMover( other, dest->s.origin, diffAngles, snap ); + TeleportMover(other, dest->s.origin, diffAngles, snap); } } -void trigger_teleporter_find_closest_portal( gentity_t *self ) -{ +void trigger_teleporter_find_closest_portal(gentity_t *self) { gentity_t *found = NULL; - vec3_t org, vec; - float dist, bestDist = 64*64; - - VectorAdd( self->mins, self->maxs, org ); - VectorScale( org, 0.5, org ); - while ( (found = G_Find( found, FOFS(classname), "misc_portal_surface" )) != NULL ) - { - VectorSubtract( found->currentOrigin, org, vec ); - dist = VectorLengthSquared( vec ); - if ( dist < bestDist ) - { + vec3_t org, vec; + float dist, bestDist = 64 * 64; + + VectorAdd(self->mins, self->maxs, org); + VectorScale(org, 0.5, org); + while ((found = G_Find(found, FOFS(classname), "misc_portal_surface")) != NULL) { + VectorSubtract(found->currentOrigin, org, vec); + dist = VectorLengthSquared(vec); + if (dist < bestDist) { self->lastEnemy = found; bestDist = dist; } } - if ( self->lastEnemy ) - { + if (self->lastEnemy) { gi.Printf("trigger_teleporter found misc_portal_surface\n"); } self->e_ThinkFunc = thinkF_NULL; @@ -1032,9 +886,8 @@ NO_NPCS - NPCs cannot pass through STASIS - will play stasis teleport sound and fx instead of starfleet DEAD_OK - even if dead, you will teleport */ -void SP_trigger_teleport( gentity_t *self ) -{ - InitTrigger (self); +void SP_trigger_teleport(gentity_t *self) { + InitTrigger(self); // unlike other triggers, we need to send this one to the client self->svFlags &= ~SVF_NOCLIENT; @@ -1045,11 +898,9 @@ void SP_trigger_teleport( gentity_t *self ) self->e_ThinkFunc = thinkF_trigger_teleporter_find_closest_portal; self->nextthink = level.time + START_TIME_LINK_ENTS; - gi.linkentity (self); + gi.linkentity(self); } - - /* ============================================================================== @@ -1078,207 +929,173 @@ MULTIPLE multiple entities can touch this trigger in a single frame *and* "NPC_targetname" - If set, only an NPC with a matching NPC_targetname will trip this trigger "noise" sound to play when it hurts something ( default: "sound/world/electro" ) */ -void hurt_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void hurt_use(gentity_t *self, gentity_t *other, gentity_t *activator) { - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - //FIXME: Targeting the trigger will toggle its on / off state??? - if ( self->linked ) { - gi.unlinkentity( self ); + // FIXME: Targeting the trigger will toggle its on / off state??? + if (self->linked) { + gi.unlinkentity(self); } else { - gi.linkentity( self ); + gi.linkentity(self); } } -void trigger_hurt_reset (gentity_t *self) -{ +void trigger_hurt_reset(gentity_t *self) { self->attackDebounceTime = 0; self->e_ThinkFunc = thinkF_NULL; } -void hurt_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - int dflags; - int actualDmg = self->damage; +void hurt_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + int dflags; + int actualDmg = self->damage; - if ( self->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (self->svFlags & SVF_INACTIVE) { // set by target_deactivate return; } - - if ( !other->takedamage ) - { + + if (!other->takedamage) { return; } - - if( level.time < self->painDebounceTime + self->wait ) // normal 'wait' check + + if (level.time < self->painDebounceTime + self->wait) // normal 'wait' check { - if( self->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in one frame + if (self->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in one frame { - if ( self->painDebounceTime && level.time > self->painDebounceTime ) // if we haven't reached the next frame continue to let ents touch the trigger + if (self->painDebounceTime && level.time > self->painDebounceTime) // if we haven't reached the next frame continue to let ents touch the trigger { return; } - } - else // only allowing one ent per frame to touch trigger + } else // only allowing one ent per frame to touch trigger { return; } } // if the player has already activated this trigger this frame - if( other && !other->s.number && self->aimDebounceTime == level.time ) - { - return; + if (other && !other->s.number && self->aimDebounceTime == level.time) { + return; } - - if ( self->spawnflags & 2 ) - {//player only - if ( other->s.number ) - { + if (self->spawnflags & 2) { // player only + if (other->s.number) { return; } } - if ( self->NPC_targetname && self->NPC_targetname[0] ) - {//I am for you, Kirk - if ( other->script_targetname && other->script_targetname[0] ) - {//must have a name - if ( Q_stricmp( self->NPC_targetname, other->script_targetname ) != 0 ) - {//not the right guy to fire me off + if (self->NPC_targetname && self->NPC_targetname[0]) { // I am for you, Kirk + if (other->script_targetname && other->script_targetname[0]) { // must have a name + if (Q_stricmp(self->NPC_targetname, other->script_targetname) != 0) { // not the right guy to fire me off return; } - } - else - {//no name? No trigger. + } else { // no name? No trigger. return; } } // play sound - if ( !(self->spawnflags & 4) ) - { - G_Sound( other, self->noise_index ); + if (!(self->spawnflags & 4)) { + G_Sound(other, self->noise_index); } - if ( self->spawnflags & 8 ) - { + if (self->spawnflags & 8) { dflags = DAMAGE_NO_PROTECTION; - } - else - { + } else { dflags = 0; } - - if ( self->delay ) - {//Increase dmg over time - if ( self->attackDebounceTime < self->delay ) - {//FIXME: this is for the entire trigger, not per person, so if someone else jumped in after you were in it for 5 seconds, they'd get damaged faster - actualDmg = floor( (double)(self->damage * self->attackDebounceTime / self->delay) ); + + if (self->delay) { // Increase dmg over time + if (self->attackDebounceTime < self->delay) { // FIXME: this is for the entire trigger, not per person, so if someone else jumped in after you were in + // it for 5 seconds, they'd get damaged faster + actualDmg = floor((double)(self->damage * self->attackDebounceTime / self->delay)); } self->attackDebounceTime += FRAMETIME; self->e_ThinkFunc = thinkF_trigger_hurt_reset; - self->nextthink = level.time + FRAMETIME*2; + self->nextthink = level.time + FRAMETIME * 2; } - if ( actualDmg ) - { - if (( self->spawnflags & 64 ) && other->client )//electrical damage + if (actualDmg) { + if ((self->spawnflags & 64) && other->client) // electrical damage { // zap effect - other->s.powerups |= ( 1 << PW_SHOCKED ); + other->s.powerups |= (1 << PW_SHOCKED); other->client->ps.powerups[PW_SHOCKED] = level.time + 1000; } - if ( self->spawnflags & 32 ) - {//falling death - G_Damage (other, self, self, NULL, NULL, actualDmg, dflags|DAMAGE_NO_ARMOR, MOD_FALLING); + if (self->spawnflags & 32) { // falling death + G_Damage(other, self, self, NULL, NULL, actualDmg, dflags | DAMAGE_NO_ARMOR, MOD_FALLING); // G_Damage will free this ent, which makes it s.number 0, so we must check inuse... - if ( !other->s.number && other->health <= 0 ) - { - if ( self->count ) - { - extern void CGCam_Fade( vec4_t source, vec4_t dest, float duration ); - float src[4] = {0,0,0,0},dst[4]={0,0,0,1}; - CGCam_Fade( src, dst, self->count ); + if (!other->s.number && other->health <= 0) { + if (self->count) { + extern void CGCam_Fade(vec4_t source, vec4_t dest, float duration); + float src[4] = {0, 0, 0, 0}, dst[4] = {0, 0, 0, 1}; + CGCam_Fade(src, dst, self->count); } - if ( self->spawnflags & 16 ) - {//lock cam + if (self->spawnflags & 16) { // lock cam cg.overrides.active |= CG_OVERRIDE_3RD_PERSON_CDP; cg.overrides.thirdPersonCameraDamp = 0; } - if ( other->client ) - { + if (other->client) { other->client->ps.pm_flags |= PMF_SLOW_MO_FALL; } - //G_SoundOnEnt( other, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN? + // G_SoundOnEnt( other, CHAN_VOICE, "*falling1.wav" );//CHAN_VOICE_ATTEN? } + } else { + G_Damage(other, self, self, NULL, NULL, actualDmg, dflags, MOD_TRIGGER_HURT); } - else - { - G_Damage (other, self, self, NULL, NULL, actualDmg, dflags, MOD_TRIGGER_HURT); - } - if( other && !other->s.number ) - { + if (other && !other->s.number) { self->aimDebounceTime = level.time; } - if (( self->spawnflags & 64 ) && other->client && other->health <= 0 )//electrical damage - {//just killed them, make the effect last longer since dead clients don't touch triggers + if ((self->spawnflags & 64) && other->client && other->health <= 0) // electrical damage + { // just killed them, make the effect last longer since dead clients don't touch triggers other->client->ps.powerups[PW_SHOCKED] = level.time + 10000; } self->painDebounceTime = level.time; } - if ( self->wait < 0 ) - { + if (self->wait < 0) { self->e_TouchFunc = touchF_NULL; } } -void SP_trigger_hurt( gentity_t *self ) -{ - char buffer[MAX_QPATH]; - char *s; +void SP_trigger_hurt(gentity_t *self) { + char buffer[MAX_QPATH]; + char *s; - InitTrigger (self); + InitTrigger(self); - if ( !( self->spawnflags & 4 )) - { - G_SpawnString( "noise", "sound/world/electro", &s ); + if (!(self->spawnflags & 4)) { + G_SpawnString("noise", "sound/world/electro", &s); - Q_strncpyz( buffer, s, sizeof(buffer) ); + Q_strncpyz(buffer, s, sizeof(buffer)); self->noise_index = G_SoundIndex(buffer); } self->e_TouchFunc = touchF_hurt_touch; - if ( !self->damage ) { + if (!self->damage) { self->damage = 5; } - + self->delay *= 1000; self->wait *= 1000; self->contents = CONTENTS_TRIGGER; - if ( self->targetname ) {//NOTE: for some reason, this used to be: if(self->spawnflags&2) + if (self->targetname) { // NOTE: for some reason, this used to be: if(self->spawnflags&2) self->e_UseFunc = useF_hurt_use; } // link in to the world if starting active - if ( !(self->spawnflags & 1) ) - { - gi.linkentity (self); - } - else // triggers automatically get linked into the world by SetBrushModel, so we have to unlink it here + if (!(self->spawnflags & 1)) { + gi.linkentity(self); + } else // triggers automatically get linked into the world by SetBrushModel, so we have to unlink it here { gi.unlinkentity(self); } } - /* ============================================================================== @@ -1287,7 +1104,6 @@ timer ============================================================================== */ - /*QUAKED func_timer (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) START_ON This should be renamed trigger_timer... Repeatedly fires its targets. @@ -1299,41 +1115,40 @@ so, the basic time between firing is a random time between (wait - random) and (wait + random) */ -void func_timer_think( gentity_t *self ) { - G_UseTargets (self, self->activator); +void func_timer_think(gentity_t *self) { + G_UseTargets(self, self->activator); // set time before next firing - self->nextthink = level.time + 1000 * ( self->wait + Q_flrand(-1.0f, 1.0f) * self->random ); + self->nextthink = level.time + 1000 * (self->wait + Q_flrand(-1.0f, 1.0f) * self->random); } -void func_timer_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void func_timer_use(gentity_t *self, gentity_t *other, gentity_t *activator) { self->activator = activator; - G_ActivateBehavior(self,BSET_USE); - + G_ActivateBehavior(self, BSET_USE); // if on, turn it off - if ( self->nextthink ) { + if (self->nextthink) { self->nextthink = 0; return; } // turn it on - func_timer_think (self); + func_timer_think(self); } -void SP_func_timer( gentity_t *self ) { - G_SpawnFloat( "random", "1", &self->random); - G_SpawnFloat( "wait", "1", &self->wait ); +void SP_func_timer(gentity_t *self) { + G_SpawnFloat("random", "1", &self->random); + G_SpawnFloat("wait", "1", &self->wait); - self->e_UseFunc = useF_func_timer_use; + self->e_UseFunc = useF_func_timer_use; self->e_ThinkFunc = thinkF_func_timer_think; - if ( self->random >= self->wait ) { + if (self->random >= self->wait) { self->random = self->wait - FRAMETIME; - gi.Printf( "func_timer at %s has random >= wait\n", vtos( self->s.origin ) ); + gi.Printf("func_timer at %s has random >= wait\n", vtos(self->s.origin)); } - if ( self->spawnflags & 1 ) { + if (self->spawnflags & 1) { self->nextthink = level.time + FRAMETIME; self->activator = self; } @@ -1349,7 +1164,6 @@ timer ============================================================================== */ - /*QUAKED trigger_entdist (.1 .5 .1) (-8 -8 -8) (8 8 8) PLAYER NPC fires if the given entity is within the given distance. Sets itself inactive after one use. ----- KEYS ----- @@ -1362,32 +1176,29 @@ ownername - If any, who to calc the distance from- default is the trigger_entdis example: target "biessman telsia" will look for the biessman and telsia NPC if it finds either of these within distance it will fire. - todo - + todo - add delay, count add monster classnames????? add LOS to it??? */ -void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - vec3_t diff; - gentity_t *found = NULL; - gentity_t *owner = NULL; - qboolean useflag; - const char *token, *holdString; +void trigger_entdist_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + vec3_t diff; + gentity_t *found = NULL; + gentity_t *owner = NULL; + qboolean useflag; + const char *token, *holdString; - if ( self->svFlags & SVF_INACTIVE ) // Don't use INACTIVE + if (self->svFlags & SVF_INACTIVE) // Don't use INACTIVE return; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if(self->ownername && self->ownername[0]) - { + if (self->ownername && self->ownername[0]) { owner = G_Find(NULL, FOFS(targetname), self->ownername); } - if(owner == NULL) - { + if (owner == NULL) { owner = self; } @@ -1395,39 +1206,35 @@ void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activato useflag = qfalse; - self->svFlags |= SVF_INACTIVE; // Make it inactive after one use + self->svFlags |= SVF_INACTIVE; // Make it inactive after one use - if (self->spawnflags & ENTDIST_PLAYER) // Look for player??? + if (self->spawnflags & ENTDIST_PLAYER) // Look for player??? { found = &g_entities[0]; - if (found) - { + if (found) { VectorSubtract(owner->currentOrigin, found->currentOrigin, diff); - if(VectorLength(diff) < self->count) - { + if (VectorLength(diff) < self->count) { useflag = qtrue; } } } - if ((self->spawnflags & ENTDIST_NPC) && (!useflag)) - { + if ((self->spawnflags & ENTDIST_NPC) && (!useflag)) { holdString = self->NPC_target; - while (holdString) - { - token = COM_Parse( &holdString); - if ( !token ) // Nothing left to look at + while (holdString) { + token = COM_Parse(&holdString); + if (!token) // Nothing left to look at { break; } - found = G_Find(found, FOFS(targetname), token); // Look for the specified NPC - if (found) //Found??? - { + found = G_Find(found, FOFS(targetname), token); // Look for the specified NPC + if (found) // Found??? + { VectorSubtract(owner->currentOrigin, found->currentOrigin, diff); - if(VectorLength(diff) < self->count) // Within distance + if (VectorLength(diff) < self->count) // Within distance { useflag = qtrue; break; @@ -1436,77 +1243,60 @@ void trigger_entdist_use( gentity_t *self, gentity_t *other, gentity_t *activato } } - if (useflag) - { - G_UseTargets2 (self, self->activator, self->target); - } - else if (self->target2) - { + if (useflag) { + G_UseTargets2(self, self->activator, self->target); + } else if (self->target2) { // This is the negative target - G_UseTargets2 (self, self->activator, self->target2); - } - - + G_UseTargets2(self, self->activator, self->target2); + } } -void SP_trigger_entdist( gentity_t *self ) -{ - G_SpawnInt( "distance", "0", &self->count); +void SP_trigger_entdist(gentity_t *self) { + G_SpawnInt("distance", "0", &self->count); self->e_UseFunc = useF_trigger_entdist_use; - } +void trigger_visible_check_player_visibility(gentity_t *self) { + // Check every FRAMETIME*2 + self->nextthink = level.time + FRAMETIME * 2; - -void trigger_visible_check_player_visibility( gentity_t *self ) -{ - //Check every FRAMETIME*2 - self->nextthink = level.time + FRAMETIME*2; - - if ( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; } - vec3_t dir; - float dist; - gentity_t *player = &g_entities[0]; + vec3_t dir; + float dist; + gentity_t *player = &g_entities[0]; - if (!player || !player->client ) - { + if (!player || !player->client) { return; } - //1: see if player is within 512*512 range - VectorSubtract( self->currentOrigin, player->client->renderInfo.eyePoint, dir ); - dist = VectorNormalize( dir ); - if ( dist < self->radius ) - {//Within range - vec3_t forward; - float dot; - //2: see if dot to us and player viewangles is > 0.7 - AngleVectors( player->client->renderInfo.eyeAngles, forward, NULL, NULL ); - dot = DotProduct( forward, dir ); - if ( dot > self->random ) - {//Within the desired FOV - //3: see if player is in PVS - if ( gi.inPVS( self->currentOrigin, player->client->renderInfo.eyePoint ) ) - { - vec3_t mins = {-1, -1, -1}; - vec3_t maxs = {1, 1, 1}; - //4: If needbe, trace to see if there is clear LOS from player viewpos - if ( (self->spawnflags&1) || G_ClearTrace( player->client->renderInfo.eyePoint, mins, maxs, self->currentOrigin, 0, MASK_OPAQUE ) ) - { - //5: Fire! - G_UseTargets( self, player ); - //6: Remove yourself - G_FreeEntity( self ); + // 1: see if player is within 512*512 range + VectorSubtract(self->currentOrigin, player->client->renderInfo.eyePoint, dir); + dist = VectorNormalize(dir); + if (dist < self->radius) { // Within range + vec3_t forward; + float dot; + // 2: see if dot to us and player viewangles is > 0.7 + AngleVectors(player->client->renderInfo.eyeAngles, forward, NULL, NULL); + dot = DotProduct(forward, dir); + if (dot > self->random) { // Within the desired FOV + // 3: see if player is in PVS + if (gi.inPVS(self->currentOrigin, player->client->renderInfo.eyePoint)) { + vec3_t mins = {-1, -1, -1}; + vec3_t maxs = {1, 1, 1}; + // 4: If needbe, trace to see if there is clear LOS from player viewpos + if ((self->spawnflags & 1) || G_ClearTrace(player->client->renderInfo.eyePoint, mins, maxs, self->currentOrigin, 0, MASK_OPAQUE)) { + // 5: Fire! + G_UseTargets(self, player); + // 6: Remove yourself + G_FreeEntity(self); } } } } - } /*QUAKED trigger_visible (.1 .5 .1) (-8 -8 -8) (8 8 8) NOTRACE x x x x x x INACTIVE @@ -1517,34 +1307,29 @@ void trigger_visible_check_player_visibility( gentity_t *self ) INACTIVE - won't check for player visibility until activated radius - how far this ent can be from player's eyes, max, and still be considered "seen" - FOV - how far off to the side of the player's field of view this can be, max, and still be considered "seen". Player FOV is 80, so the default for this value is 30. + FOV - how far off to the side of the player's field of view this can be, max, and still be considered "seen". Player FOV is 80, so the default for this value + is 30. "target" - What to use when it fires. */ -void SP_trigger_visible( gentity_t *self ) -{ - if ( self->radius <= 0 ) - { +void SP_trigger_visible(gentity_t *self) { + if (self->radius <= 0) { self->radius = 512; } - if ( self->random <= 0 ) - {//about 30 degrees + if (self->random <= 0) { // about 30 degrees self->random = 0.7f; - } - else - {//convert from FOV degrees to number meaningful for dot products - self->random = 1.0f - (self->random/90.0f); + } else { // convert from FOV degrees to number meaningful for dot products + self->random = 1.0f - (self->random / 90.0f); } - if ( self->spawnflags & 128 ) - {// Make it inactive - self->svFlags |= SVF_INACTIVE; + if (self->spawnflags & 128) { // Make it inactive + self->svFlags |= SVF_INACTIVE; } - G_SetOrigin( self, self->s.origin ); - gi.linkentity( self ); + G_SetOrigin(self, self->s.origin); + gi.linkentity(self); self->e_ThinkFunc = thinkF_trigger_visible_check_player_visibility; - self->nextthink = level.time + FRAMETIME*2; + self->nextthink = level.time + FRAMETIME * 2; } \ No newline at end of file diff --git a/codeJK2/game/g_turret.cpp b/codeJK2/game/g_turret.cpp index 5e09128580..979402253f 100644 --- a/codeJK2/game/g_turret.cpp +++ b/codeJK2/game/g_turret.cpp @@ -25,113 +25,103 @@ along with this program; if not, see . #include "g_functions.h" #include "b_local.h" -extern team_t TranslateTeamName( const char *name ); -extern cvar_t *g_spskill; +extern team_t TranslateTeamName(const char *name); +extern cvar_t *g_spskill; -void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -void finish_spawning_turret( gentity_t *base ); -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +void G_SetEnemy(gentity_t *self, gentity_t *enemy); +void finish_spawning_turret(gentity_t *base); +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -#define ARM_ANGLE_RANGE 60 -#define HEAD_ANGLE_RANGE 90 +#define ARM_ANGLE_RANGE 60 +#define HEAD_ANGLE_RANGE 90 //------------------------------------------------------------------------------------------------------------ -void TurretPain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc ) +void TurretPain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) //------------------------------------------------------------------------------------------------------------ { vec3_t dir; - VectorSubtract( point, self->currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(point, self->currentOrigin, dir); + VectorNormalize(dir); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { // DEMP2 makes the turret stop shooting for a bit..and does extra feedback self->attackDebounceTime = level.time + 800 + Q_flrand(0.0f, 1.0f) * 500; - G_PlayEffect( "spark_exp_nosnd", point, dir ); + G_PlayEffect("spark_exp_nosnd", point, dir); } - G_PlayEffect( "spark_exp_nosnd", point, dir ); + G_PlayEffect("spark_exp_nosnd", point, dir); } //------------------------------------------------------------------------------------------------------------ -void turret_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) +void turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) //------------------------------------------------------------------------------------------------------------ { - vec3_t forward = { 0,0,-1 }, pos; + vec3_t forward = {0, 0, -1}, pos; // Turn off the thinking of the base & use it's targets self->e_ThinkFunc = thinkF_NULL; self->e_UseFunc = useF_NULL; // clear my data - self->e_DieFunc = dieF_NULL; + self->e_DieFunc = dieF_NULL; self->takedamage = qfalse; self->health = 0; self->s.loopSound = 0; // hack the effect angle so that explode death can orient the effect properly - if ( self->spawnflags & 2 ) - { - VectorSet( forward, 0, 0, 1 ); + if (self->spawnflags & 2) { + VectorSet(forward, 0, 0, 1); } -// VectorCopy( self->currentOrigin, self->s.pos.trBase ); + // VectorCopy( self->currentOrigin, self->s.pos.trBase ); - if ( self->fxID > 0 ) - { - VectorMA( self->currentOrigin, 12, forward, pos ); - G_PlayEffect( self->fxID, pos, forward ); + if (self->fxID > 0) { + VectorMA(self->currentOrigin, 12, forward, pos); + G_PlayEffect(self->fxID, pos, forward); } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 1; // black } self->s.weapon = 0; // crosshair code uses this to mark crosshair red - if ( self->s.modelindex2 ) - { + if (self->s.modelindex2) { // switch to damage model if we should self->s.modelindex = self->s.modelindex2; - VectorCopy( self->currentAngles, self->s.apos.trBase ); - VectorClear( self->s.apos.trDelta ); + VectorCopy(self->currentAngles, self->s.apos.trBase); + VectorClear(self->s.apos.trDelta); - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - } - else - { - ObjectDie( self, inflictor, attacker, damage, meansOfDeath ); + } else { + ObjectDie(self, inflictor, attacker, damage, meansOfDeath); } } #define START_DIS 15 //---------------------------------------------------------------- -static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) +static void turret_fire(gentity_t *ent, vec3_t start, vec3_t dir) //---------------------------------------------------------------- { - vec3_t org; - gentity_t *bolt; + vec3_t org; + gentity_t *bolt; - if ( gi.pointcontents( start, MASK_SHOT )) - { + if (gi.pointcontents(start, MASK_SHOT)) { return; } - VectorMA( start, -START_DIS, dir, org ); // dumb.... - G_PlayEffect( "blaster/muzzle_flash", org, dir ); + VectorMA(start, -START_DIS, dir, org); // dumb.... + G_PlayEffect("blaster/muzzle_flash", org, dir); bolt = G_Spawn(); @@ -142,173 +132,145 @@ static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) bolt->s.weapon = WP_BLASTER; bolt->owner = ent; bolt->damage = ent->damage; - bolt->dflags = DAMAGE_NO_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; bolt->methodOfDeath = MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - bolt->trigger_formation = qfalse; // don't draw tail on first frame + bolt->trigger_formation = qfalse; // don't draw tail on first frame - VectorSet( bolt->maxs, 1.5, 1.5, 1.5 ); - VectorScale( bolt->maxs, -1, bolt->mins ); + VectorSet(bolt->maxs, 1.5, 1.5, 1.5); + VectorScale(bolt->maxs, -1, bolt->mins); bolt->s.pos.trType = TR_LINEAR; bolt->s.pos.trTime = level.time; - VectorCopy( start, bolt->s.pos.trBase ); - VectorScale( dir, 1100, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( start, bolt->currentOrigin); + VectorCopy(start, bolt->s.pos.trBase); + VectorScale(dir, 1100, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->currentOrigin); } //----------------------------------------------------- -void turret_head_think( gentity_t *self ) +void turret_head_think(gentity_t *self) //----------------------------------------------------- { // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time - if ( self->enemy && self->pushDebounceTime < level.time && self->attackDebounceTime < level.time ) - { + if (self->enemy && self->pushDebounceTime < level.time && self->attackDebounceTime < level.time) { // set up our next fire time self->pushDebounceTime = level.time + self->wait; - vec3_t fwd, org; - mdxaBone_t boltMatrix; + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->currentAngles, self->currentOrigin, + (cg.time ? cg.time : level.time), NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); - VectorMA( org, START_DIS, fwd, org ); + VectorMA(org, START_DIS, fwd, org); - turret_fire( self, org, fwd ); - self->fly_sound_debounce_time = level.time;//used as lastShotTime + turret_fire(self, org, fwd); + self->fly_sound_debounce_time = level.time; // used as lastShotTime } } //----------------------------------------------------- -static void turret_aim( gentity_t *self ) +static void turret_aim(gentity_t *self) //----------------------------------------------------- { - vec3_t enemyDir, org, org2; - vec3_t desiredAngles, setAngle; - float diffYaw = 0.0f, diffPitch = 0.0f; + vec3_t enemyDir, org, org2; + vec3_t desiredAngles, setAngle; + float diffYaw = 0.0f, diffPitch = 0.0f; // move our gun base yaw to where we should be at this time.... - EvaluateTrajectory( &self->s.apos, level.time, self->currentAngles ); - self->currentAngles[YAW] = AngleNormalize360( self->currentAngles[YAW] ); - self->speed = AngleNormalize360( self->speed ); + EvaluateTrajectory(&self->s.apos, level.time, self->currentAngles); + self->currentAngles[YAW] = AngleNormalize360(self->currentAngles[YAW]); + self->speed = AngleNormalize360(self->speed); - if ( self->enemy ) - { + if (self->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->currentOrigin, org); } - else - { - VectorCopy( self->enemy->currentOrigin, org ); - } - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] -= 5; } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Getting the "eye" here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->currentAngles, self->s.origin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->currentAngles, self->s.origin, + (cg.time ? cg.time : level.time), NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - VectorSubtract( org, org2, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, org2, enemyDir); + vectoangles(enemyDir, desiredAngles); - diffYaw = AngleSubtract( self->currentAngles[YAW], desiredAngles[YAW] ); - diffPitch = AngleSubtract( self->speed, desiredAngles[PITCH] ); - } - else - { + diffYaw = AngleSubtract(self->currentAngles[YAW], desiredAngles[YAW]); + diffPitch = AngleSubtract(self->speed, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one -// diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. + // diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. } - if ( diffYaw ) - { + if (diffYaw) { // cap max speed.... - if ( fabs(diffYaw) > 14.0f ) - { - diffYaw = ( diffYaw >= 0 ? 14.0f : -14.0f ); + if (fabs(diffYaw) > 14.0f) { + diffYaw = (diffYaw >= 0 ? 14.0f : -14.0f); } // ...then set up our desired yaw - VectorSet( setAngle, 0.0f, diffYaw, 0.0f ); + VectorSet(setAngle, 0.0f, diffYaw, 0.0f); - VectorCopy( self->currentAngles, self->s.apos.trBase ); - VectorScale( setAngle,- 5, self->s.apos.trDelta ); + VectorCopy(self->currentAngles, self->s.apos.trBase); + VectorScale(setAngle, -5, self->s.apos.trDelta); self->s.apos.trTime = level.time; self->s.apos.trType = TR_LINEAR; } - if ( diffPitch ) - { - if ( fabs(diffPitch) > 3.0f ) - { + if (diffPitch) { + if (fabs(diffPitch) > 3.0f) { // cap max speed self->speed += (diffPitch > 0.0f) ? -3.0f : 3.0f; - } - else - { + } else { // small enough, so just add half the diff so we smooth out the stopping - self->speed -= ( diffPitch );//desiredAngles[PITCH]; + self->speed -= (diffPitch); // desiredAngles[PITCH]; } // Note that this is NOT interpolated, so it will be less smooth...On the other hand, it does use Ghoul2 to blend, so it may smooth it out a bit? - if ( self->spawnflags & 2 ) - { - VectorSet( desiredAngles, self->speed, 0.0f, 0.0f ); - } - else - { - VectorSet( desiredAngles, -self->speed, 0.0f, 0.0f ); + if (self->spawnflags & 2) { + VectorSet(desiredAngles, self->speed, 0.0f, 0.0f); + } else { + VectorSet(desiredAngles, -self->speed, 0.0f, 0.0f); } - gi.G2API_SetBoneAngles( &self->ghoul2[0], "Bone_body", desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time ); + gi.G2API_SetBoneAngles(&self->ghoul2[0], "Bone_body", desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time); } - if ( diffYaw || diffPitch ) - { - self->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); - } - else - { + if (diffYaw || diffPitch) { + self->s.loopSound = G_SoundIndex("sound/chars/turret/move.wav"); + } else { self->s.loopSound = 0; } } //----------------------------------------------------- -static void turret_turnoff( gentity_t *self ) +static void turret_turnoff(gentity_t *self) //----------------------------------------------------- { - if ( self->enemy == NULL ) - { + if (self->enemy == NULL) { // we don't need to turnoff return; } // shut-down sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/shutdown.wav")); // make turret play ping sound for 5 seconds self->aimDebounceTime = level.time + 5000; @@ -318,87 +280,73 @@ static void turret_turnoff( gentity_t *self ) } //----------------------------------------------------- -static qboolean turret_find_enemies( gentity_t *self ) +static qboolean turret_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; - - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + qboolean found = qfalse; + int count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; + + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - G_Sound(self, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + G_Sound(self, G_SoundIndex("sound/chars/turret/ping.wav")); self->painDebounceTime = level.time + 1000; } } - VectorCopy( self->currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 20; - } - else - { + } else { org2[2] -= 20; } - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { // only attack clients continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client->playerTeam == self->noDamageTeam ) - { + if (target->client->playerTeam == self->noDamageTeam) { // A bot we don't want to shoot continue; } - if ( !gi.inPVS( org2, target->currentOrigin )) - { + if (!gi.inPVS(org2, target->currentOrigin)) { continue; } - VectorCopy( target->client->renderInfo.eyePoint, org ); + VectorCopy(target->client->renderInfo.eyePoint, org); - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] += 5; } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist )// all things equal, keep current + if (enemyDist < bestDist) // all things equal, keep current { - if ( self->attackDebounceTime < level.time ) - { + if (self->attackDebounceTime < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/startup.wav")); // Wind up turrets for a bit self->attackDebounceTime = level.time + 1400; @@ -411,17 +359,14 @@ static qboolean turret_find_enemies( gentity_t *self ) } } - if ( found ) - { - if ( !self->enemy ) - {//just aquired one - AddSoundEvent( bestTarget, self->currentOrigin, 256, AEL_DISCOVERED ); - AddSightEvent( bestTarget, self->currentOrigin, 512, AEL_DISCOVERED, 20 ); + if (found) { + if (!self->enemy) { // just aquired one + AddSoundEvent(bestTarget, self->currentOrigin, 256, AEL_DISCOVERED); + AddSightEvent(bestTarget, self->currentOrigin, 512, AEL_DISCOVERED, 20); } - G_SetEnemy( self, bestTarget ); - if ( VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + G_SetEnemy(self, bestTarget); + if (VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } } @@ -429,118 +374,95 @@ static qboolean turret_find_enemies( gentity_t *self ) } //----------------------------------------------------- -void turret_base_think( gentity_t *self ) +void turret_base_think(gentity_t *self) //----------------------------------------------------- { - qboolean turnOff = qtrue; - float enemyDist; - vec3_t enemyDir, org, org2; + qboolean turnOff = qtrue; + float enemyDist; + vec3_t enemyDir, org, org2; self->nextthink = level.time + FRAMETIME; - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { // not turned on - turret_turnoff( self ); - turret_aim( self ); + turret_turnoff(self); + turret_aim(self); // No target self->flags |= FL_NOTARGET; return; - } - else - { + } else { // I'm all hot and bothered self->flags &= ~FL_NOTARGET; } - if ( !self->enemy ) - { - if ( turret_find_enemies( self )) - { + if (!self->enemy) { + if (turret_find_enemies(self)) { turnOff = qfalse; } - } - else - { - if ( self->enemy->health > 0 ) - { + } else { + if (self->enemy->health > 0) { // enemy is alive - VectorSubtract( self->enemy->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(self->enemy->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < self->radius * self->radius ) - { + if (enemyDist < self->radius * self->radius) { // was in valid radius - if ( gi.inPVS( self->currentOrigin, self->enemy->currentOrigin ) ) - { + if (gi.inPVS(self->currentOrigin, self->enemy->currentOrigin)) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); - } - else - { - VectorCopy( self->enemy->currentOrigin, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->currentOrigin, org); } - VectorCopy( self->currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 10; - } - else - { + } else { org2[2] -= 10; } - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( !tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number ) - { - turnOff = qfalse; // Can see our enemy + if (!tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number) { + turnOff = qfalse; // Can see our enemy } } } } - turret_head_think( self ); + turret_head_think(self); } - if ( turnOff ) - { - if ( self->bounceCount < level.time ) // bounceCount is used to keep the thing from ping-ponging from on to off + if (turnOff) { + if (self->bounceCount < level.time) // bounceCount is used to keep the thing from ping-ponging from on to off { - turret_turnoff( self ); + turret_turnoff(self); } - } - else - { + } else { // keep our enemy for a minimum of 2 seconds from now self->bounceCount = level.time + 2000 + Q_flrand(0.0f, 1.0f) * 150; } - turret_aim( self ); + turret_aim(self); } //----------------------------------------------------------------------------- -void turret_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void turret_base_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); - if (( self->s.eFlags & EF_SHADER_ANIM ) && ( self->spawnflags & 1 )) // Start_Off + if ((self->s.eFlags & EF_SHADER_ANIM) && (self->spawnflags & 1)) // Start_Off { self->s.frame = 1; // black - } - else - { + } else { self->s.frame = 0; // glow } } - /*QUAKED misc_turret (1 0 0) (-8 -8 -22) (8 8 0) START_OFF UPSIDE_DOWN Turret that hangs from the ceiling, will aim and shoot at enemies @@ -566,43 +488,40 @@ Turret that hangs from the ceiling, will aim and shoot at enemies "neutral" */ //----------------------------------------------------- -void SP_misc_turret( gentity_t *base ) +void SP_misc_turret(gentity_t *base) //----------------------------------------------------- { - base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/turret_canon.glm" ); - base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/turret_damage.md3" ); - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/turret_canon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/turret_canon.glm"); + base->s.modelindex2 = G_ModelIndex("models/map_objects/imp_mine/turret_damage.md3"); + base->playerModel = + gi.G2API_InitGhoul2Model(base->ghoul2, "models/map_objects/imp_mine/turret_canon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 80.0f; - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash03" ); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash03"); - finish_spawning_turret( base ); + finish_spawning_turret(base); - if (( base->spawnflags & 1 )) // Start_Off + if ((base->spawnflags & 1)) // Start_Off { base->s.frame = 1; // black - } - else - { + } else { base->s.frame = 0; // glow } base->s.eFlags |= EF_SHADER_ANIM; } //----------------------------------------------------- -void finish_spawning_turret( gentity_t *base ) -{ - vec3_t fwd; +void finish_spawning_turret(gentity_t *base) { + vec3_t fwd; - if ( base->spawnflags & 2 ) - { + if (base->spawnflags & 2) { base->s.angles[ROLL] += 180; base->s.origin[2] -= 22.0f; } - G_SetAngles( base, base->s.angles ); - AngleVectors( base->currentAngles, fwd, NULL, NULL ); + G_SetAngles(base, base->s.angles); + AngleVectors(base->currentAngles, fwd, NULL, NULL); G_SetOrigin(base, base->s.origin); @@ -610,15 +529,14 @@ void finish_spawning_turret( gentity_t *base ) base->s.eType = ET_GENERAL; - if ( base->team && base->team[0] ) - { - base->noDamageTeam = TranslateTeamName( base->team ); + if (base->team && base->team[0]) { + base->noDamageTeam = TranslateTeamName(base->team); base->team = NULL; } // Set up our explosion effect for the ExplodeDeath code.... - base->fxID = G_EffectIndex( "turret/explode" ); - G_EffectIndex( "spark_exp_nosnd" ); + base->fxID = G_EffectIndex("turret/explode"); + G_EffectIndex("spark_exp_nosnd"); base->e_UseFunc = useF_turret_base_use; base->e_PainFunc = painF_TurretPain; @@ -633,71 +551,62 @@ void finish_spawning_turret( gentity_t *base ) // this is a random time offset for the no-enemy-search-around-mode base->count = Q_flrand(0.0f, 1.0f) * 9000; - if ( !base->health ) - { + if (!base->health) { base->health = 100; } // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 512; } // How quickly to fire - if ( !base->wait ) - { + if (!base->wait) { base->wait = 150 + Q_flrand(0.0f, 1.0f) * 55; } - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 10; } - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 25; } // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 5; } - if ( base->spawnflags & 2 ) - {//upside-down, invert mins and maxe - VectorSet( base->maxs, 10.0f, 10.0f, 30.0f ); - VectorSet( base->mins, -10.0f, -10.0f, 0.0f ); - } - else - { - VectorSet( base->maxs, 10.0f, 10.0f, 0.0f ); - VectorSet( base->mins, -10.0f, -10.0f, -30.0f ); + if (base->spawnflags & 2) { // upside-down, invert mins and maxe + VectorSet(base->maxs, 10.0f, 10.0f, 30.0f); + VectorSet(base->mins, -10.0f, -10.0f, 0.0f); + } else { + VectorSet(base->maxs, 10.0f, 10.0f, 0.0f); + VectorSet(base->mins, -10.0f, -10.0f, -30.0f); } // Precache moving sounds - G_SoundIndex( "sound/chars/turret/startup.wav" ); - G_SoundIndex( "sound/chars/turret/shutdown.wav" ); - G_SoundIndex( "sound/chars/turret/ping.wav" ); - G_SoundIndex( "sound/chars/turret/move.wav" ); + G_SoundIndex("sound/chars/turret/startup.wav"); + G_SoundIndex("sound/chars/turret/shutdown.wav"); + G_SoundIndex("sound/chars/turret/ping.wav"); + G_SoundIndex("sound/chars/turret/move.wav"); - base->contents = CONTENTS_BODY|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_SHOTCLIP; + base->contents = CONTENTS_BODY | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_SHOTCLIP; base->max_health = base->health; base->takedamage = qtrue; - base->e_DieFunc = dieF_turret_die; + base->e_DieFunc = dieF_turret_die; base->material = MAT_METAL; - base->svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; + base->svFlags |= SVF_NO_TELEPORT | SVF_NONNPC_ENEMY | SVF_SELF_ANIMATING; // Register this so that we can use it for the missile effect - RegisterItem( FindItemForWeapon( WP_BLASTER )); + RegisterItem(FindItemForWeapon(WP_BLASTER)); // But set us as a turret so that we can be identified as a turret base->s.weapon = WP_TURRET; - gi.linkentity( base ); + gi.linkentity(base); } /*QUAKED misc_ns_turret (1 0 0) (-8 -8 -32) (8 8 29) START_OFF @@ -723,132 +632,121 @@ NS turret that only hangs from the ceiling, will aim and shoot at enemies "neutral" */ //----------------------------------------------------- -void SP_misc_ns_turret( gentity_t *base ) +void SP_misc_ns_turret(gentity_t *base) //----------------------------------------------------- { - base->s.modelindex = G_ModelIndex( "models/map_objects/nar_shaddar/turret/turret.glm" ); - base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/turret_damage.md3" ); // FIXME! - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/nar_shaddar/turret/turret.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/map_objects/nar_shaddar/turret/turret.glm"); + base->s.modelindex2 = G_ModelIndex("models/map_objects/imp_mine/turret_damage.md3"); // FIXME! + base->playerModel = + gi.G2API_InitGhoul2Model(base->ghoul2, "models/map_objects/nar_shaddar/turret/turret.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 80.0f; - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); - finish_spawning_turret( base ); + finish_spawning_turret(base); } //-------------------------------------- -void laser_arm_fire (gentity_t *ent) -{ - vec3_t start, end, fwd, rt, up; - trace_t trace; +void laser_arm_fire(gentity_t *ent) { + vec3_t start, end, fwd, rt, up; + trace_t trace; - if ( ent->attackDebounceTime < level.time && ent->alt_fire ) - { + if (ent->attackDebounceTime < level.time && ent->alt_fire) { // If I'm firing the laser and it's time to quit....then quit! ent->alt_fire = qfalse; -// ent->e_ThinkFunc = thinkF_NULL; -// return; + // ent->e_ThinkFunc = thinkF_NULL; + // return; } ent->nextthink = level.time + FRAMETIME; // If a fool gets in the laser path, fry 'em - AngleVectors( ent->currentAngles, fwd, rt, up ); + AngleVectors(ent->currentAngles, fwd, rt, up); - VectorMA( ent->currentOrigin, 20, fwd, start ); - //VectorMA( start, -6, rt, start ); - //VectorMA( start, -3, up, start ); - VectorMA( start, 4096, fwd, end ); + VectorMA(ent->currentOrigin, 20, fwd, start); + // VectorMA( start, -6, rt, start ); + // VectorMA( start, -3, up, start ); + VectorMA(start, 4096, fwd, end); - gi.trace( &trace, start, NULL, NULL, end, ENTITYNUM_NONE, MASK_SHOT, G2_NOCOLLIDE, 0 );//ignore - ent->fly_sound_debounce_time = level.time;//used as lastShotTime + gi.trace(&trace, start, NULL, NULL, end, ENTITYNUM_NONE, MASK_SHOT, G2_NOCOLLIDE, 0); // ignore + ent->fly_sound_debounce_time = level.time; // used as lastShotTime // Only deal damage when in alt-fire mode - if ( trace.fraction < 1.0 && ent->alt_fire ) - { - if ( trace.entityNum < ENTITYNUM_WORLD ) - { + if (trace.fraction < 1.0 && ent->alt_fire) { + if (trace.entityNum < ENTITYNUM_WORLD) { gentity_t *hapless_victim = &g_entities[trace.entityNum]; - if ( hapless_victim && hapless_victim->takedamage && ent->damage ) - { - G_Damage( hapless_victim, ent, ent->nextTrain->activator, fwd, trace.endpos, ent->damage, DAMAGE_IGNORE_TEAM, MOD_UNKNOWN ); + if (hapless_victim && hapless_victim->takedamage && ent->damage) { + G_Damage(hapless_victim, ent, ent->nextTrain->activator, fwd, trace.endpos, ent->damage, DAMAGE_IGNORE_TEAM, MOD_UNKNOWN); } } } - if ( ent->alt_fire ) - { -// CG_FireLaser( start, trace.endpos, trace.plane.normal, ent->nextTrain->startRGBA, qfalse ); - } - else - { -// CG_AimLaser( start, trace.endpos, trace.plane.normal ); + if (ent->alt_fire) { + // CG_FireLaser( start, trace.endpos, trace.plane.normal, ent->nextTrain->startRGBA, qfalse ); + } else { + // CG_AimLaser( start, trace.endpos, trace.plane.normal ); } } -void laser_arm_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - vec3_t newAngles; +void laser_arm_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + vec3_t newAngles; self->activator = activator; - switch( self->count ) - { + switch (self->count) { case 0: default: - //Fire - //gi.Printf("FIRE!\n"); -// self->lastEnemy->lastEnemy->e_ThinkFunc = thinkF_laser_arm_fire; -// self->lastEnemy->lastEnemy->nextthink = level.time + FRAMETIME; - //For 3 seconds + // Fire + // gi.Printf("FIRE!\n"); + // self->lastEnemy->lastEnemy->e_ThinkFunc = thinkF_laser_arm_fire; + // self->lastEnemy->lastEnemy->nextthink = level.time + FRAMETIME; + // For 3 seconds self->lastEnemy->lastEnemy->alt_fire = qtrue; // Let 'er rip! self->lastEnemy->lastEnemy->attackDebounceTime = level.time + self->lastEnemy->lastEnemy->wait; G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/fire.wav")); break; case 1: - //Yaw left - //gi.Printf("LEFT...\n"); - VectorCopy( self->lastEnemy->currentAngles, newAngles ); + // Yaw left + // gi.Printf("LEFT...\n"); + VectorCopy(self->lastEnemy->currentAngles, newAngles); newAngles[1] += self->speed; - G_SetAngles( self->lastEnemy, newAngles ); -// bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); - G_Sound( self->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy, newAngles); + // bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_Sound(self->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 2: - //Yaw right - //gi.Printf("RIGHT...\n"); - VectorCopy( self->lastEnemy->currentAngles, newAngles ); + // Yaw right + // gi.Printf("RIGHT...\n"); + VectorCopy(self->lastEnemy->currentAngles, newAngles); newAngles[1] -= self->speed; - G_SetAngles( self->lastEnemy, newAngles ); -// bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); - G_Sound( self->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy, newAngles); + // bolt_head_to_arm( self->lastEnemy, self->lastEnemy->lastEnemy, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_Sound(self->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 3: - //pitch up - //gi.Printf("UP...\n"); - //FIXME: Clamp - VectorCopy( self->lastEnemy->lastEnemy->currentAngles, newAngles ); + // pitch up + // gi.Printf("UP...\n"); + // FIXME: Clamp + VectorCopy(self->lastEnemy->lastEnemy->currentAngles, newAngles); newAngles[0] -= self->speed; - if ( newAngles[0] < -45 ) - { + if (newAngles[0] < -45) { newAngles[0] = -45; } - G_SetAngles( self->lastEnemy->lastEnemy, newAngles ); - G_Sound( self->lastEnemy->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy->lastEnemy, newAngles); + G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; case 4: - //pitch down - //gi.Printf("DOWN...\n"); - //FIXME: Clamp - VectorCopy( self->lastEnemy->lastEnemy->currentAngles, newAngles ); + // pitch down + // gi.Printf("DOWN...\n"); + // FIXME: Clamp + VectorCopy(self->lastEnemy->lastEnemy->currentAngles, newAngles); newAngles[0] += self->speed; - if ( newAngles[0] > 90 ) - { + if (newAngles[0] > 90) { newAngles[0] = 90; } - G_SetAngles( self->lastEnemy->lastEnemy, newAngles ); - G_Sound( self->lastEnemy->lastEnemy, G_SoundIndex( "sound/chars/l_arm/move.wav" ) ); + G_SetAngles(self->lastEnemy->lastEnemy, newAngles); + G_Sound(self->lastEnemy->lastEnemy, G_SoundIndex("sound/chars/l_arm/move.wav")); break; } } @@ -871,116 +769,99 @@ What it does when used depends on it's "count" (can be set by a script) "startRGBA" - laser color, Red Green Blue Alpha, range 0 to 1 (default 1.0 0.85 0.15 0.75 = Yellow-Orange) */ -void laser_arm_start (gentity_t *base) -{ - vec3_t armAngles; - vec3_t headAngles; +void laser_arm_start(gentity_t *base) { + vec3_t armAngles; + vec3_t headAngles; base->e_ThinkFunc = thinkF_NULL; - //We're the base, spawn the arm and head + // We're the base, spawn the arm and head gentity_t *arm = G_Spawn(); gentity_t *head = G_Spawn(); - VectorCopy( base->s.angles, armAngles ); - VectorCopy( base->s.angles, headAngles ); - if ( base->target && base->target[0] ) - {//Start out pointing at something - gentity_t *targ = G_Find( NULL, FOFS(targetname), base->target ); - if ( !targ ) - {//couldn't find it! + VectorCopy(base->s.angles, armAngles); + VectorCopy(base->s.angles, headAngles); + if (base->target && base->target[0]) { // Start out pointing at something + gentity_t *targ = G_Find(NULL, FOFS(targetname), base->target); + if (!targ) { // couldn't find it! Com_Printf(S_COLOR_RED "ERROR : laser_arm can't find target %s!\n", base->target); - } - else - {//point at it - vec3_t dir, angles; + } else { // point at it + vec3_t dir, angles; - VectorSubtract(targ->currentOrigin, base->s.origin, dir ); - vectoangles( dir, angles ); + VectorSubtract(targ->currentOrigin, base->s.origin, dir); + vectoangles(dir, angles); armAngles[1] = angles[1]; headAngles[0] = angles[0]; headAngles[1] = angles[1]; } } - //Base - //Base does the looking for enemies and pointing the arm and head - G_SetAngles( base, base->s.angles ); - //base->s.origin[2] += 4; + // Base + // Base does the looking for enemies and pointing the arm and head + G_SetAngles(base, base->s.angles); + // base->s.origin[2] += 4; G_SetOrigin(base, base->s.origin); gi.linkentity(base); - //FIXME: need an actual model + // FIXME: need an actual model base->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_base.md3"); base->s.eType = ET_GENERAL; - G_SpawnVector4( "startRGBA", "1.0 0.85 0.15 0.75", (float *)&base->startRGBA ); - //anglespeed - how fast it can track the player, entered in degrees per second, so we divide by FRAMETIME/1000 - if ( !base->speed ) - { + G_SpawnVector4("startRGBA", "1.0 0.85 0.15 0.75", (float *)&base->startRGBA); + // anglespeed - how fast it can track the player, entered in degrees per second, so we divide by FRAMETIME/1000 + if (!base->speed) { base->speed = 3.0f; - } - else - { - base->speed *= FRAMETIME/1000.0f; + } else { + base->speed *= FRAMETIME / 1000.0f; } base->e_UseFunc = useF_laser_arm_use; base->nextthink = level.time + FRAMETIME; - //Arm - //Does nothing, not solid, gets removed when head explodes - G_SetOrigin( arm, base->s.origin ); + // Arm + // Does nothing, not solid, gets removed when head explodes + G_SetOrigin(arm, base->s.origin); gi.linkentity(arm); - G_SetAngles( arm, armAngles ); -// bolt_head_to_arm( arm, head, LARM_FOFS, LARM_ROFS, LARM_UOFS ); + G_SetAngles(arm, armAngles); + // bolt_head_to_arm( arm, head, LARM_FOFS, LARM_ROFS, LARM_UOFS ); arm->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_arm.md3"); - //Head - //Fires when enemy detected, animates, can be blown up - //Need to normalize the headAngles pitch for the clamping later - if ( headAngles[0] < -180 ) - { + // Head + // Fires when enemy detected, animates, can be blown up + // Need to normalize the headAngles pitch for the clamping later + if (headAngles[0] < -180) { headAngles[0] += 360; - } - else if ( headAngles[0] > 180 ) - { + } else if (headAngles[0] > 180) { headAngles[0] -= 360; } - G_SetAngles( head, headAngles ); + G_SetAngles(head, headAngles); head->s.modelindex = G_ModelIndex("models/mapobjects/dn/laser_head.md3"); head->s.eType = ET_GENERAL; -// head->svFlags |= SVF_BROADCAST;// Broadcast to all clients - VectorSet( head->mins, -8, -8, -8 ); - VectorSet( head->maxs, 8, 8, 8 ); + // head->svFlags |= SVF_BROADCAST;// Broadcast to all clients + VectorSet(head->mins, -8, -8, -8); + VectorSet(head->maxs, 8, 8, 8); head->contents = CONTENTS_BODY; - //FIXME: make an index into an external string table for localization + // FIXME: make an index into an external string table for localization head->fullName = "Surgical Laser"; gi.linkentity(head); - //dmg - if ( !base->damage ) - { + // dmg + if (!base->damage) { head->damage = 5; - } - else - { + } else { head->damage = base->damage; } base->damage = 0; - //lifespan of beam - if ( !base->wait ) - { + // lifespan of beam + if (!base->wait) { head->wait = 3000; - } - else - { + } else { head->wait = base->wait * 1000; } base->wait = 0; - //Precache firing and explode sounds + // Precache firing and explode sounds G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); G_SoundIndex("sound/chars/l_arm/fire.wav"); G_SoundIndex("sound/chars/l_arm/move.wav"); - //Link them up + // Link them up base->lastEnemy = arm; arm->lastEnemy = head; head->owner = arm; @@ -992,8 +873,7 @@ void laser_arm_start (gentity_t *base) head->alt_fire = qfalse; // Don't do damage until told to } -void SP_laser_arm (gentity_t *base) -{ +void SP_laser_arm(gentity_t *base) { base->e_ThinkFunc = thinkF_laser_arm_start; base->nextthink = level.time + START_TIME_LINK_ENTS; } @@ -1002,46 +882,41 @@ void SP_laser_arm (gentity_t *base) // PERSONAL ASSAULT SENTRY //-------------------------- -#define PAS_DAMAGE 2 +#define PAS_DAMAGE 2 //----------------------------------------------------------------------------- -void pas_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void pas_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { self->nextthink = 0; // turn off and do nothing self->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { self->nextthink = level.time + 50; self->e_ThinkFunc = thinkF_pas_think; } } //---------------------------------------------------------------- -void pas_fire( gentity_t *ent ) +void pas_fire(gentity_t *ent) //---------------------------------------------------------------- { - vec3_t fwd, org; - mdxaBone_t boltMatrix; + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->torsoBolt, - &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->torsoBolt, &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); - G_PlayEffect( "turret/muzzle_flash", org, fwd ); + G_PlayEffect("turret/muzzle_flash", org, fwd); - gentity_t *bolt; + gentity_t *bolt; bolt = G_Spawn(); @@ -1052,181 +927,157 @@ void pas_fire( gentity_t *ent ) bolt->s.weapon = WP_TURRET; bolt->owner = ent; bolt->damage = PAS_DAMAGE; - bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming + bolt->dflags = DAMAGE_NO_KNOCKBACK; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = 0; bolt->splashRadius = 0; bolt->methodOfDeath = MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - VectorSet( bolt->maxs, 1, 1, 1 ); - VectorScale( bolt->maxs, -1, bolt->mins ); + VectorSet(bolt->maxs, 1, 1, 1); + VectorScale(bolt->maxs, -1, bolt->mins); bolt->s.pos.trType = TR_LINEAR; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( org, bolt->s.pos.trBase ); - VectorScale( fwd, 900, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( org, bolt->currentOrigin); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(org, bolt->s.pos.trBase); + VectorScale(fwd, 900, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(org, bolt->currentOrigin); } //----------------------------------------------------- -static qboolean pas_find_enemies( gentity_t *self ) +static qboolean pas_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target; - - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + qboolean found = qfalse; + int count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target; + + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - G_Sound(self, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + G_Sound(self, G_SoundIndex("sound/chars/turret/ping.wav")); self->painDebounceTime = level.time + 1000; } } - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; // Getting the "eye" here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->currentAngles, self->s.origin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->currentAngles, self->s.origin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client->playerTeam == self->noDamageTeam ) - { + if (target->client->playerTeam == self->noDamageTeam) { // A bot we don't want to shoot continue; } - if ( !gi.inPVS( org2, target->currentOrigin )) - { + if (!gi.inPVS(org2, target->currentOrigin)) { continue; } - if ( target->client ) - { - VectorCopy( target->client->renderInfo.eyePoint, org ); + if (target->client) { + VectorCopy(target->client->renderInfo.eyePoint, org); org[2] -= 15; - } - else - { - VectorCopy( target->currentOrigin, org ); + } else { + VectorCopy(target->currentOrigin, org); } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->currentOrigin, self->currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->currentOrigin, self->currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( target->s.number ) // don't do this for the player + if (target->s.number) // don't do this for the player { - G_StartFlee( target, self, self->currentOrigin, AEL_DANGER, 3000, 5000 ); + G_StartFlee(target, self, self->currentOrigin, AEL_DANGER, 3000, 5000); } - if ( enemyDist < bestDist )// all things equal, keep current + if (enemyDist < bestDist) // all things equal, keep current { - if ( self->attackDebounceTime + 2000 < level.time ) - { + if (self->attackDebounceTime + 2000 < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - G_Sound( self, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(self, G_SoundIndex("sound/chars/turret/startup.wav")); // Wind up turrets for a bit self->attackDebounceTime = level.time + 900 + Q_flrand(0.0f, 1.0f) * 200; } - G_SetEnemy( self, target ); + G_SetEnemy(self, target); bestDist = enemyDist; found = qtrue; } } } - if ( found && VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + if (found && VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } return found; } //--------------------------------- -void pas_adjust_enemy( gentity_t *ent ) +void pas_adjust_enemy(gentity_t *ent) //--------------------------------- { qboolean keep = qtrue; - if ( ent->enemy->health <= 0 ) - { + if (ent->enemy->health <= 0) { keep = qfalse; - } - else// if ( Q_flrand(0.0f, 1.0f) > 0.5f ) + } else // if ( Q_flrand(0.0f, 1.0f) > 0.5f ) { // do a trace every now and then. - mdxaBone_t boltMatrix; - vec3_t org, org2; + mdxaBone_t boltMatrix; + vec3_t org, org2; // Getting the "eye" here - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->torsoBolt, - &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->torsoBolt, &boltMatrix, ent->currentAngles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org2); - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->renderInfo.eyePoint, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->renderInfo.eyePoint, org); org[2] -= 15; - } - else - { - VectorCopy( ent->enemy->currentOrigin, org ); + } else { + VectorCopy(ent->enemy->currentOrigin, org); } - trace_t tr; - gi.trace( &tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + trace_t tr; + gi.trace(&tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( tr.allsolid || tr.startsolid || tr.entityNum != ent->enemy->s.number ) - { + if (tr.allsolid || tr.startsolid || tr.entityNum != ent->enemy->s.number) { // trace failed keep = qfalse; } } - if ( keep ) - { + if (keep) { ent->bounceCount = level.time + 500 + Q_flrand(0.0f, 1.0f) * 150; - } - else if ( ent->bounceCount < level.time ) // don't ping pong on and off + } else if (ent->bounceCount < level.time) // don't ping pong on and off { ent->enemy = NULL; // shut-down sound - G_Sound( ent, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(ent, G_SoundIndex("sound/chars/turret/shutdown.wav")); // make turret play ping sound for 5 seconds ent->aimDebounceTime = level.time + 5000; @@ -1234,138 +1085,112 @@ void pas_adjust_enemy( gentity_t *ent ) } //--------------------------------- -void pas_think( gentity_t *ent ) +void pas_think(gentity_t *ent) //--------------------------------- { - if ( !ent->damage ) - { + if (!ent->damage) { // let us do our animation, then we are good to go in terms of pounding the crap out of enemies. ent->damage = 1; - gi.G2API_SetBoneAnimIndex( &ent->ghoul2[ent->playerModel], ent->rootBone, 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&ent->ghoul2[ent->playerModel], ent->rootBone, 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, -1, -1); ent->nextthink = level.time + 1200; return; } - if ( !ent->count ) - { + if (!ent->count) { // turrets that have no ammo may as well do nothing return; } ent->nextthink = level.time + FRAMETIME; - if ( ent->enemy ) - { + if (ent->enemy) { // make sure that the enemy is still valid - pas_adjust_enemy( ent ); + pas_adjust_enemy(ent); } - if ( !ent->enemy ) - { - pas_find_enemies( ent ); + if (!ent->enemy) { + pas_find_enemies(ent); } - qboolean moved = qfalse; - float diffYaw = 0.0f, diffPitch = 0.0f; - vec3_t enemyDir, org; - vec3_t frontAngles, backAngles; - vec3_t desiredAngles; + qboolean moved = qfalse; + float diffYaw = 0.0f, diffPitch = 0.0f; + vec3_t enemyDir, org; + vec3_t frontAngles, backAngles; + vec3_t desiredAngles; - ent->speed = AngleNormalize360( ent->speed ); - ent->random = AngleNormalize360( ent->random ); + ent->speed = AngleNormalize360(ent->speed); + ent->random = AngleNormalize360(ent->random); - if ( ent->enemy ) - { + if (ent->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->renderInfo.eyePoint, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->renderInfo.eyePoint, org); org[2] -= 40; - } - else - { - VectorCopy( ent->enemy->currentOrigin, org ); + } else { + VectorCopy(ent->enemy->currentOrigin, org); } - VectorSubtract( org, ent->currentOrigin, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, ent->currentOrigin, enemyDir); + vectoangles(enemyDir, desiredAngles); - diffYaw = AngleSubtract( ent->speed, desiredAngles[YAW] ); - diffPitch = AngleSubtract( ent->random, desiredAngles[PITCH] ); - } - else - { + diffYaw = AngleSubtract(ent->speed, desiredAngles[YAW]); + diffPitch = AngleSubtract(ent->random, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one - diffYaw = sin( level.time * 0.0001f + ent->count ) * 2.0f; + diffYaw = sin(level.time * 0.0001f + ent->count) * 2.0f; } - if ( fabs(diffYaw) > 0.25f ) - { + if (fabs(diffYaw) > 0.25f) { moved = qtrue; - if ( fabs(diffYaw) > 10.0f ) - { + if (fabs(diffYaw) > 10.0f) { // cap max speed ent->speed += (diffYaw > 0.0f) ? -10.0f : 10.0f; - } - else - { + } else { // small enough ent->speed -= diffYaw; } } - - if ( fabs(diffPitch) > 0.25f ) - { + if (fabs(diffPitch) > 0.25f) { moved = qtrue; - if ( fabs(diffPitch) > 4.0f ) - { + if (fabs(diffPitch) > 4.0f) { // cap max speed ent->random += (diffPitch > 0.0f) ? -4.0f : 4.0f; - } - else - { + } else { // small enough ent->random -= diffPitch; } } // the bone axes are messed up, so hence some dumbness here - VectorSet( frontAngles, -ent->random, 0.0f, 0.0f ); - VectorSet( backAngles, 0.0f, 0.0f, ent->speed - ent->s.angles[YAW] ); - - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_barrel", frontAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL,100,cg.time); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_gback", frontAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL,100,cg.time); - gi.G2API_SetBoneAngles( &ent->ghoul2[ent->playerModel], "bone_hinge", backAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL,100,cg.time); - - if ( moved ) - { - //ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); - } - else - { + VectorSet(frontAngles, -ent->random, 0.0f, 0.0f); + VectorSet(backAngles, 0.0f, 0.0f, ent->speed - ent->s.angles[YAW]); + + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_barrel", frontAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL, 100, + cg.time); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_gback", frontAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, NEGATIVE_X, NULL, 100, + cg.time); + gi.G2API_SetBoneAngles(&ent->ghoul2[ent->playerModel], "bone_hinge", backAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, + cg.time); + + if (moved) { + // ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); + } else { ent->s.loopSound = 0; } - if ( ent->enemy && ent->attackDebounceTime < level.time && Q_flrand(0.0f, 1.0f) > 0.3f ) - { + if (ent->enemy && ent->attackDebounceTime < level.time && Q_flrand(0.0f, 1.0f) > 0.3f) { ent->count--; - if ( ent->count ) - { - pas_fire( ent ); - ent->fly_sound_debounce_time = level.time;//used as lastShotTime - } - else - { + if (ent->count) { + pas_fire(ent); + ent->fly_sound_debounce_time = level.time; // used as lastShotTime + } else { ent->nextthink = 0; - G_Sound( ent, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(ent, G_SoundIndex("sound/chars/turret/shutdown.wav")); } } } @@ -1394,36 +1219,34 @@ personal assault sentry, like the ones you can carry in your inventory */ //--------------------------------- -void SP_PAS( gentity_t *base ) +void SP_PAS(gentity_t *base) //--------------------------------- { base->classname = "PAS"; - G_SetOrigin( base, base->s.origin ); - G_SetAngles( base, base->s.angles ); + G_SetOrigin(base, base->s.origin); + G_SetAngles(base, base->s.angles); base->speed = base->s.angles[YAW]; - base->s.modelindex = G_ModelIndex( "models/items/psgun.glm" ); - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/items/psgun.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/items/psgun.glm"); + base->playerModel = gi.G2API_InitGhoul2Model(base->ghoul2, "models/items/psgun.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 30.0f; - VectorSet( base->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(base->s.modelScale, 1.0f, 1.0f, 1.0f); - base->rootBone = gi.G2API_GetBoneIndex( &base->ghoul2[base->playerModel], "model_root", qtrue ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); - gi.G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); + base->rootBone = gi.G2API_GetBoneIndex(&base->ghoul2[base->playerModel], "model_root", qtrue); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + gi.G2API_SetBoneAngles(&base->ghoul2[base->playerModel], "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); base->s.eType = ET_GENERAL; - if ( !base->radius ) - { + if (!base->radius) { base->radius = 512; } - if ( base->count == 0 ) - { + if (base->count == 0) { // give ammo base->count = 150; } @@ -1432,29 +1255,28 @@ void SP_PAS( gentity_t *base ) base->damage = 0; // start animation flag - base->contents = CONTENTS_SHOTCLIP|CONTENTS_CORPSE;//for certain traces - VectorSet( base->mins, -8, -8, 0 ); - VectorSet( base->maxs, 8, 8, 18 ); + base->contents = CONTENTS_SHOTCLIP | CONTENTS_CORPSE; // for certain traces + VectorSet(base->mins, -8, -8, 0); + VectorSet(base->maxs, 8, 8, 18); - if ( !(base->spawnflags & 1 )) // START_OFF + if (!(base->spawnflags & 1)) // START_OFF { base->nextthink = level.time + 1000; // we aren't starting off, so start working right away base->e_ThinkFunc = thinkF_pas_think; } // Set up our explosion effect for the ExplodeDeath code.... - base->fxID = G_EffectIndex( "turret/explode" ); - G_EffectIndex( "spark_exp_nosnd" ); + base->fxID = G_EffectIndex("turret/explode"); + G_EffectIndex("spark_exp_nosnd"); - if ( !base->health ) - { + if (!base->health) { base->health = 50; } base->max_health = base->health; base->takedamage = qtrue; base->e_PainFunc = painF_TurretPain; - base->e_DieFunc = dieF_turret_die; + base->e_DieFunc = dieF_turret_die; // hack this flag on so that when it calls the turret die code, it will orient the effect up // HACK @@ -1462,70 +1284,66 @@ void SP_PAS( gentity_t *base ) base->spawnflags |= 2; // Use this for our missile effect - RegisterItem( FindItemForWeapon( WP_TURRET )); + RegisterItem(FindItemForWeapon(WP_TURRET)); base->s.weapon = WP_TURRET; base->svFlags |= SVF_NONNPC_ENEMY; base->noDamageTeam = TEAM_NEUTRAL; - if ( base->team && base->team[0] ) - { - base->noDamageTeam = TranslateTeamName( base->team ); + if (base->team && base->team[0]) { + base->noDamageTeam = TranslateTeamName(base->team); base->team = NULL; } - gi.linkentity( base ); + gi.linkentity(base); } //------------------------------------------------------------------------ -qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t angs ) +qboolean place_portable_assault_sentry(gentity_t *self, vec3_t origin, vec3_t angs) //------------------------------------------------------------------------ { - vec3_t fwd, pos; - vec3_t mins, maxs; - trace_t tr; - gentity_t *pas; + vec3_t fwd, pos; + vec3_t mins, maxs; + trace_t tr; + gentity_t *pas; - VectorSet( maxs, 9, 9, 0 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 9, 9, 0); + VectorScale(maxs, -1, mins); angs[PITCH] = 0; angs[ROLL] = 0; - AngleVectors( angs, fwd, NULL, NULL ); + AngleVectors(angs, fwd, NULL, NULL); // and move a consistent distance away from us so we don't have the dumb thing spawning inside of us. - VectorMA( origin, 30, fwd, pos ); - gi.trace( &tr, origin, NULL, NULL, pos, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + VectorMA(origin, 30, fwd, pos); + gi.trace(&tr, origin, NULL, NULL, pos, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); // find the ground tr.endpos[2] += 20; - VectorCopy( tr.endpos, pos ); + VectorCopy(tr.endpos, pos); pos[2] -= 64; - gi.trace( &tr, tr.endpos, mins, maxs, pos, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, tr.endpos, mins, maxs, pos, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); // check for a decent surface, meaning mostly flat...should probably also check surface parms so we don't set us down on lava or something. - if ( !tr.startsolid && !tr.allsolid && tr.fraction < 1.0f && tr.plane.normal[2] > 0.9f && tr.entityNum >= ENTITYNUM_WORLD ) - { + if (!tr.startsolid && !tr.allsolid && tr.fraction < 1.0f && tr.plane.normal[2] > 0.9f && tr.entityNum >= ENTITYNUM_WORLD) { // Then spawn us if it seems cool. pas = G_Spawn(); - if ( pas ) - { - VectorCopy( tr.endpos, pas->s.origin ); - SP_PAS( pas ); + if (pas) { + VectorCopy(tr.endpos, pas->s.origin); + SP_PAS(pas); pas->contents |= CONTENTS_PLAYERCLIP; // player placed ones can block players but not npcs pas->e_UseFunc = useF_NULL; // placeable ones never need to be used // we don't hurt us or anyone who belongs to the same team as us. - if ( self->client ) - { + if (self->client) { pas->noDamageTeam = self->client->playerTeam; } - G_Sound( self, G_SoundIndex( "sound/player/use_sentry" )); + G_Sound(self, G_SoundIndex("sound/player/use_sentry")); pas->activator = self; return qtrue; } @@ -1533,123 +1351,106 @@ qboolean place_portable_assault_sentry( gentity_t *self, vec3_t origin, vec3_t a return qfalse; } - //------------- // ION CANNON //------------- - //---------------------------------------- -void ion_cannon_think( gentity_t *self ) +void ion_cannon_think(gentity_t *self) //---------------------------------------- { - if ( self->spawnflags & 2 ) - { - if ( self->count ) - { + if (self->spawnflags & 2) { + if (self->count) { // still have bursts left, so keep going self->count--; - } - else - { + } else { // done with burst, so wait delay amount, plus a random bit - self->nextthink = level.time + ( self->delay + Q_flrand(-1.0f, 1.0f) * self->random ); - self->count = Q_irand(0,5); // 0-5 bursts + self->nextthink = level.time + (self->delay + Q_flrand(-1.0f, 1.0f) * self->random); + self->count = Q_irand(0, 5); // 0-5 bursts // Not firing this time return; } } - if ( self->fxID ) - { - vec3_t fwd, org; - mdxaBone_t boltMatrix; + if (self->fxID) { + vec3_t fwd, org; + mdxaBone_t boltMatrix; // Getting the flash bolt here - gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, - self->torsoBolt, - &boltMatrix, self->s.angles, self->s.origin, (cg.time?cg.time:level.time), - NULL, self->s.modelScale ); + gi.G2API_GetBoltMatrix(self->ghoul2, self->playerModel, self->torsoBolt, &boltMatrix, self->s.angles, self->s.origin, (cg.time ? cg.time : level.time), + NULL, self->s.modelScale); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, POSITIVE_Y, fwd); - G_PlayEffect( self->fxID, org, fwd ); + G_PlayEffect(self->fxID, org, fwd); } - if ( self->target2 ) - { + if (self->target2) { // If we have a target2 fire it off in sync with our gun firing - G_UseTargets2( self, self, self->target2 ); + G_UseTargets2(self, self, self->target2); } - gi.G2API_SetBoneAnimIndex( &self->ghoul2[self->playerModel], self->rootBone, 0, 8, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1 ); + gi.G2API_SetBoneAnimIndex(&self->ghoul2[self->playerModel], self->rootBone, 0, 8, BONE_ANIM_OVERRIDE_FREEZE, 0.6f, cg.time, -1, -1); self->nextthink = level.time + self->wait + Q_flrand(-1.0f, 1.0f) * self->random; } //---------------------------------------------------------------------------------------------- -void ion_cannon_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) +void ion_cannon_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) //---------------------------------------------------------------------------------------------- { vec3_t org; // dead, so nuke the ghoul model and put in the damage md3 version - if ( self->playerModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( self->ghoul2, self->playerModel ); + if (self->playerModel >= 0) { + gi.G2API_RemoveGhoul2Model(self->ghoul2, self->playerModel); } self->s.modelindex = self->s.modelindex2; self->s.modelindex2 = 0; - // Turn off the thinking of the base & use it's targets + // Turn off the thinking of the base & use it's targets self->e_ThinkFunc = thinkF_NULL; self->e_UseFunc = useF_NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } // clear my data - self->e_DieFunc = dieF_NULL; + self->e_DieFunc = dieF_NULL; self->takedamage = qfalse; self->health = 0; - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops self->s.loopSound = 0; // not solid anymore self->contents = 0; - VectorCopy( self->currentOrigin, self->s.pos.trBase ); + VectorCopy(self->currentOrigin, self->s.pos.trBase); - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 20; - G_PlayEffect( "env/ion_cannon_explosion", org ); + G_PlayEffect("env/ion_cannon_explosion", org); - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, - attacker, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN); } - gi.linkentity( self ); + gi.linkentity(self); } //---------------------------------------------------------------------------- -void ion_cannon_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void ion_cannon_use(gentity_t *self, gentity_t *other, gentity_t *activator) //---------------------------------------------------------------------------- { // toggle - if ( self->e_ThinkFunc == thinkF_NULL ) - { + if (self->e_ThinkFunc == thinkF_NULL) { // start thinking now self->e_ThinkFunc = thinkF_ion_cannon_think; self->nextthink = level.time + FRAMETIME; // fires right on being used - } - else - { + } else { self->e_ThinkFunc = thinkF_NULL; } } @@ -1674,141 +1475,122 @@ Huge ion cannon, like the ones at the rebel base on Hoth. target2 - What to use when it fires a shot. */ //----------------------------------------------------- -void SP_misc_ion_cannon( gentity_t *base ) +void SP_misc_ion_cannon(gentity_t *base) //----------------------------------------------------- { - G_SetAngles( base, base->s.angles ); + G_SetAngles(base, base->s.angles); G_SetOrigin(base, base->s.origin); - base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/ion_cannon.glm" ); - base->playerModel = gi.G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/ion_cannon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + base->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/ion_cannon.glm"); + base->playerModel = + gi.G2API_InitGhoul2Model(base->ghoul2, "models/map_objects/imp_mine/ion_cannon.glm", base->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); base->s.radius = 320.0f; - VectorSet( base->s.modelScale, 1.0f, 1.0f, 1.0f ); + VectorSet(base->s.modelScale, 1.0f, 1.0f, 1.0f); - base->rootBone = gi.G2API_GetBoneIndex( &base->ghoul2[base->playerModel], "model_root", qtrue ); - base->torsoBolt = gi.G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash02" ); + base->rootBone = gi.G2API_GetBoneIndex(&base->ghoul2[base->playerModel], "model_root", qtrue); + base->torsoBolt = gi.G2API_AddBolt(&base->ghoul2[base->playerModel], "*flash02"); // register damage model - base->s.modelindex2 = G_ModelIndex( "models/map_objects/imp_mine/ion_cannon_damage.md3" ); + base->s.modelindex2 = G_ModelIndex("models/map_objects/imp_mine/ion_cannon_damage.md3"); base->e_UseFunc = useF_ion_cannon_use; // How quickly to fire - if ( base->wait == 0.0f ) - { + if (base->wait == 0.0f) { base->wait = 1500.0f; - } - else if ( base->wait < 500.0f ) - { + } else if (base->wait < 500.0f) { base->wait = 500.0f; } - if ( base->random == 0.0f ) - { + if (base->random == 0.0f) { base->random = 400.0f; } - if ( base->delay == 0 ) - { + if (base->delay == 0) { base->delay = 6000; - } - else if ( base->delay < 1000 ) - { + } else if (base->delay < 1000) { base->delay = 1000; } // we only take damage from a heavy weapon class missile base->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; - if ( base->spawnflags & 4 )//shielded + if (base->spawnflags & 4) // shielded { - base->flags |= FL_SHIELDED; //technically, this would only take damage from a lightsaber, but the other flag just above would cancel that out too. + base->flags |= FL_SHIELDED; // technically, this would only take damage from a lightsaber, but the other flag just above would cancel that out too. } - G_SpawnInt( "health", "2000", &base->health ); + G_SpawnInt("health", "2000", &base->health); base->e_DieFunc = dieF_ion_cannon_die; base->takedamage = qtrue; // Start Off? - if ( base->spawnflags & 1 ) - { + if (base->spawnflags & 1) { base->e_ThinkFunc = thinkF_NULL; - } - else - { + } else { // start thinking now, otherwise, we'll wait until we are used base->e_ThinkFunc = thinkF_ion_cannon_think; base->nextthink = level.time + base->wait + Q_flrand(-1.0f, 1.0f) * base->random; } // Bursts? - if ( base->spawnflags & 2 ) - { - base->count = Q_irand(0,5); // 0-5 bursts + if (base->spawnflags & 2) { + base->count = Q_irand(0, 5); // 0-5 bursts } // precache - base->fxID = G_EffectIndex( "env/ion_cannon" ); + base->fxID = G_EffectIndex("env/ion_cannon"); // Set up our explosion effect for the ExplodeDeath code.... - G_EffectIndex( "env/ion_cannon_explosion" ); + G_EffectIndex("env/ion_cannon_explosion"); base->contents = CONTENTS_BODY; - VectorSet( base->mins, -141.0f, -148.0f, 0.0f ); - VectorSet( base->maxs, 142.0f, 135.0f, 245.0f ); + VectorSet(base->mins, -141.0f, -148.0f, 0.0f); + VectorSet(base->maxs, 142.0f, 135.0f, 245.0f); - gi.linkentity( base ); + gi.linkentity(base); } - //----------------------------------------------------- -void spotlight_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->e_ThinkFunc == thinkF_NULL ) - { +void spotlight_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->e_ThinkFunc == thinkF_NULL) { // start thinking now, otherwise, we'll wait until we are used self->e_ThinkFunc = thinkF_spotlight_think; self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->e_ThinkFunc = thinkF_NULL; self->s.eFlags &= ~EF_ALT_FIRING; } } //----------------------------------------------------- -void spotlight_think( gentity_t *ent ) -{ - vec3_t dir, end; - trace_t tr; +void spotlight_think(gentity_t *ent) { + vec3_t dir, end; + trace_t tr; // dumb hack flag so that we can draw an interpolated light cone cgame side. ent->s.eFlags |= EF_ALT_FIRING; - VectorSubtract( ent->enemy->currentOrigin, ent->currentOrigin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.apos.trBase ); + VectorSubtract(ent->enemy->currentOrigin, ent->currentOrigin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.apos.trBase); ent->s.apos.trType = TR_INTERPOLATE; - VectorMA( ent->currentOrigin, 2048, dir, end ); // just pick some max trace distance - gi.trace( &tr, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID, G2_NOCOLLIDE, 0 ); + VectorMA(ent->currentOrigin, 2048, dir, end); // just pick some max trace distance + gi.trace(&tr, ent->currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID, G2_NOCOLLIDE, 0); ent->radius = tr.fraction * 2048.0f; - if ( tr.fraction < 1 ) - { - if ( DistanceSquared( tr.endpos, g_entities[0].currentOrigin ) < 140 * 140 ) - { + if (tr.fraction < 1) { + if (DistanceSquared(tr.endpos, g_entities[0].currentOrigin) < 140 * 140) { // hit player--use target2 - G_UseTargets2( ent, &g_entities[0], ent->target2 ); + G_UseTargets2(ent, &g_entities[0], ent->target2); #ifndef FINAL_BUILD - if ( g_developer->integer == PRINT_DEVELOPER ) - { - Com_Printf( S_COLOR_MAGENTA "Spotlight hit player at time: %d!!!\n", level.time ); + if (g_developer->integer == PRINT_DEVELOPER) { + Com_Printf(S_COLOR_MAGENTA "Spotlight hit player at time: %d!!!\n", level.time); } #endif } @@ -1818,29 +1600,24 @@ void spotlight_think( gentity_t *ent ) } //----------------------------------------------------- -void spotlight_link( gentity_t *ent ) -{ +void spotlight_link(gentity_t *ent) { gentity_t *target = 0; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { - Com_Printf( S_COLOR_RED "ERROR: spotlight_link: bogus target %s\n", ent->target ); - G_FreeEntity( ent ); + if (!target) { + Com_Printf(S_COLOR_RED "ERROR: spotlight_link: bogus target %s\n", ent->target); + G_FreeEntity(ent); return; } ent->enemy = target; // Start Off? - if ( ent->spawnflags & 1 ) - { + if (ent->spawnflags & 1) { ent->e_ThinkFunc = thinkF_NULL; ent->s.eFlags &= ~EF_ALT_FIRING; - } - else - { + } else { // start thinking now, otherwise, we'll wait until we are used ent->e_ThinkFunc = thinkF_spotlight_think; ent->nextthink = level.time + FRAMETIME; @@ -1860,25 +1637,24 @@ Uses its target2 when it detects the player */ //----------------------------------------------------- -void SP_misc_spotlight( gentity_t *base ) +void SP_misc_spotlight(gentity_t *base) //----------------------------------------------------- { - if ( !base->target ) - { - Com_Printf( S_COLOR_RED "ERROR: misc_spotlight must have a target\n" ); - G_FreeEntity( base ); + if (!base->target) { + Com_Printf(S_COLOR_RED "ERROR: misc_spotlight must have a target\n"); + G_FreeEntity(base); return; } - G_SetAngles( base, base->s.angles ); - G_SetOrigin( base, base->s.origin ); + G_SetAngles(base, base->s.angles); + G_SetOrigin(base, base->s.origin); - base->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/spotlight.md3" ); + base->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/spotlight.md3"); - G_SpawnInt( "health", "300", &base->health ); + G_SpawnInt("health", "300", &base->health); // Set up our lightcone effect, though we will have it draw cgame side so it looks better - G_EffectIndex( "env/light_cone" ); + G_EffectIndex("env/light_cone"); base->contents = CONTENTS_BODY; base->e_UseFunc = useF_spotlight_use; @@ -1887,7 +1663,7 @@ void SP_misc_spotlight( gentity_t *base ) base->e_ThinkFunc = thinkF_spotlight_link; base->nextthink = level.time + 100; - gi.linkentity( base ); + gi.linkentity(base); } /*QUAKED misc_panel_turret (0 0 1) (-8 -8 -12) (8 8 16) HEALTH @@ -1908,20 +1684,19 @@ Creates a turret that, when the player uses a panel, takes control of this turre heatlh - how much heatlh the thing has, (default 200) only works if HEALTH is checked, otherwise it can't be destroyed. */ -extern gentity_t *player; -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); +extern gentity_t *player; +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse); -void panel_turret_shoot( gentity_t *self, vec3_t org, vec3_t dir) -{ - gentity_t *missile = CreateMissile( org, dir, self->speed, 10000, self ); +void panel_turret_shoot(gentity_t *self, vec3_t org, vec3_t dir) { + gentity_t *missile = CreateMissile(org, dir, self->speed, 10000, self); missile->classname = "b_proj"; missile->s.weapon = WP_EMPLACED_GUN; - VectorSet( missile->maxs, 7, 7, 7 ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, 7, 7, 7); + VectorScale(missile->maxs, -1, missile->mins); missile->bounceCount = 0; @@ -1930,105 +1705,93 @@ void panel_turret_shoot( gentity_t *self, vec3_t org, vec3_t dir) missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - G_SoundOnEnt( self, CHAN_AUTO, "sound/movers/objects/ladygun_fire" ); + G_SoundOnEnt(self, CHAN_AUTO, "sound/movers/objects/ladygun_fire"); - VectorMA( org, 32, dir, org ); + VectorMA(org, 32, dir, org); org[2] -= 5; - G_PlayEffect( "emplaced/muzzle_flash", org, dir ); + G_PlayEffect("emplaced/muzzle_flash", org, dir); } //----------------------------------------- -void misc_panel_turret_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) -{ - if ( self->target3 ) - { - G_UseTargets2( self, player, self->target3 ); +void misc_panel_turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { + if (self->target3) { + G_UseTargets2(self, player, self->target3); } // FIXME: might need some other kind of logic or functionality in here?? - G_UseTargets2( self, player, self->target2 ); - G_ClearViewEntity( player ); + G_UseTargets2(self, player, self->target2); + G_ClearViewEntity(player); cg.overrides.active &= ~CG_OVERRIDE_FOV; cg.overrides.fov = 0; } //----------------------------------------- -void panel_turret_think( gentity_t *self ) -{ +void panel_turret_think(gentity_t *self) { // Ensure that I am the viewEntity - if ( player && player->client && player->client->ps.viewEntity == self->s.number ) - { + if (player && player->client && player->client->ps.viewEntity == self->s.number) { usercmd_t *ucmd = &player->client->usercmd; // We are the viewEnt so update our new viewangles based on the sum of our start angles and the ucmd angles - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { // convert our base angle to a short, add with the usercmd.angle ( a short ), then switch use back to a real angle - self->s.apos.trBase[i] = AngleNormalize180( SHORT2ANGLE( ucmd->angles[i] + ANGLE2SHORT( self->s.angles[i] ) + self->pos3[i] )); + self->s.apos.trBase[i] = AngleNormalize180(SHORT2ANGLE(ucmd->angles[i] + ANGLE2SHORT(self->s.angles[i]) + self->pos3[i])); } // Only clamp if we have a PITCH clamp - if ( self->random != 0.0f ) + if (self->random != 0.0f) // Angle clamping -- PITCH { - if ( self->s.apos.trBase[PITCH] > self->random ) // random is PITCH + if (self->s.apos.trBase[PITCH] > self->random) // random is PITCH { - self->pos3[PITCH] += ANGLE2SHORT( AngleNormalize180( self->random - self->s.apos.trBase[PITCH])); + self->pos3[PITCH] += ANGLE2SHORT(AngleNormalize180(self->random - self->s.apos.trBase[PITCH])); self->s.apos.trBase[PITCH] = self->random; - } - else if ( self->s.apos.trBase[PITCH] < -self->random ) - { - self->pos3[PITCH] -= ANGLE2SHORT( AngleNormalize180( self->random + self->s.apos.trBase[PITCH])); + } else if (self->s.apos.trBase[PITCH] < -self->random) { + self->pos3[PITCH] -= ANGLE2SHORT(AngleNormalize180(self->random + self->s.apos.trBase[PITCH])); self->s.apos.trBase[PITCH] = -self->random; } } // Only clamp if we have a YAW clamp - if ( self->radius != 0.0f ) - { - float yawDif = AngleSubtract( self->s.apos.trBase[YAW], self->s.angles[YAW] ); + if (self->radius != 0.0f) { + float yawDif = AngleSubtract(self->s.apos.trBase[YAW], self->s.angles[YAW]); // Angle clamping -- YAW - if ( yawDif > self->radius ) // radius is YAW + if (yawDif > self->radius) // radius is YAW { - self->pos3[YAW] += ANGLE2SHORT( self->radius - yawDif ); - self->s.apos.trBase[YAW] = AngleNormalize180( self->s.angles[YAW] + self->radius ); - } - else if ( yawDif < -self->radius ) // radius is YAW + self->pos3[YAW] += ANGLE2SHORT(self->radius - yawDif); + self->s.apos.trBase[YAW] = AngleNormalize180(self->s.angles[YAW] + self->radius); + } else if (yawDif < -self->radius) // radius is YAW { - self->pos3[YAW] -= ANGLE2SHORT( self->radius + yawDif ); - self->s.apos.trBase[YAW] = AngleNormalize180( self->s.angles[YAW] - self->radius ); + self->pos3[YAW] -= ANGLE2SHORT(self->radius + yawDif); + self->s.apos.trBase[YAW] = AngleNormalize180(self->s.angles[YAW] - self->radius); } } // Let cgame interpolation smooth out the angle changes self->s.apos.trType = TR_INTERPOLATE; - self->s.pos.trType = TR_INTERPOLATE; // not really moving, but this fixes an interpolation bug in cg_ents. + self->s.pos.trType = TR_INTERPOLATE; // not really moving, but this fixes an interpolation bug in cg_ents. // Check for backing out of turret - if ( ( self->useDebounceTime < level.time ) && ((ucmd->buttons & BUTTON_BLOCKING) || (ucmd->buttons & BUTTON_USE) || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove) ) - { + if ((self->useDebounceTime < level.time) && + ((ucmd->buttons & BUTTON_BLOCKING) || (ucmd->buttons & BUTTON_USE) || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove)) { self->useDebounceTime = level.time + 200; - G_UseTargets2( self, player, self->target2 ); - G_ClearViewEntity( player ); - G_Sound( player, self->soundPos2 ); + G_UseTargets2(self, player, self->target2); + G_ClearViewEntity(player); + G_Sound(player, self->soundPos2); cg.overrides.active &= ~CG_OVERRIDE_FOV; cg.overrides.fov = 0; - if ( ucmd->upmove > 0 ) - {//stop player from doing anything for a half second after + if (ucmd->upmove > 0) { // stop player from doing anything for a half second after player->aimDebounceTime = level.time + 500; } // can be drawn -// self->s.eFlags &= ~EF_NODRAW; - } - else - { + // self->s.eFlags &= ~EF_NODRAW; + } else { // don't draw me when being looked through -// self->s.eFlags |= EF_NODRAW; -// self->s.modelindex = 0; + // self->s.eFlags |= EF_NODRAW; + // self->s.modelindex = 0; // we only need to think when we are being used self->nextthink = level.time + 50; @@ -2037,17 +1800,15 @@ void panel_turret_think( gentity_t *self ) cg.overrides.fov = 50; } - if ( ucmd->buttons & BUTTON_ATTACK || ucmd->buttons & BUTTON_ALT_ATTACK ) - { - if ( self->attackDebounceTime < level.time ) - { + if (ucmd->buttons & BUTTON_ATTACK || ucmd->buttons & BUTTON_ALT_ATTACK) { + if (self->attackDebounceTime < level.time) { vec3_t dir, pt; - AngleVectors( self->s.apos.trBase, dir, NULL, NULL ); + AngleVectors(self->s.apos.trBase, dir, NULL, NULL); - VectorCopy( self->currentOrigin, pt ); + VectorCopy(self->currentOrigin, pt); pt[2] -= 4; - panel_turret_shoot( self, pt, dir ); + panel_turret_shoot(self, pt, dir); self->attackDebounceTime = level.time + self->delay; } @@ -2056,83 +1817,79 @@ void panel_turret_think( gentity_t *self ) } //----------------------------------------- -void panel_turret_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void panel_turret_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // really only usable by the player - if ( !activator || !activator->client || activator->s.number ) - { + if (!activator || !activator->client || activator->s.number) { return; } - if ( self->useDebounceTime > level.time ) - { + if (self->useDebounceTime > level.time) { // can't use it again right away. return; } - if ( self->spawnflags & 1 ) // health...presumably the lady luck gun + if (self->spawnflags & 1) // health...presumably the lady luck gun { - G_Sound( self, G_SoundIndex( "sound/movers/objects/ladygun_on" )); + G_Sound(self, G_SoundIndex("sound/movers/objects/ladygun_on")); } self->useDebounceTime = level.time + 200; // Compensating for the difference between the players view at the time of use and the start angles that the gun object has - self->pos3[PITCH] = -activator->client->usercmd.angles[PITCH]; - self->pos3[YAW] = -activator->client->usercmd.angles[YAW]; - self->pos3[ROLL] = 0; + self->pos3[PITCH] = -activator->client->usercmd.angles[PITCH]; + self->pos3[YAW] = -activator->client->usercmd.angles[YAW]; + self->pos3[ROLL] = 0; // set me as view entity - G_UseTargets2( self, activator, self->target ); - G_SetViewEntity( activator, self ); + G_UseTargets2(self, activator, self->target); + G_SetViewEntity(activator, self); - G_Sound( activator, self->soundPos1 ); + G_Sound(activator, self->soundPos1); self->e_ThinkFunc = thinkF_panel_turret_think; -// panel_turret_think( self ); + // panel_turret_think( self ); self->nextthink = level.time + 150; } //----------------------------------------- -void SP_misc_panel_turret( gentity_t *self ) -{ - G_SpawnFloat( "radius", "90", &self->radius ); // yaw - G_SpawnFloat( "random", "60", &self->random ); // pitch - G_SpawnFloat( "speed" , "3000", &self->speed ); - G_SpawnInt( "delay", "200", &self->delay ); - G_SpawnInt( "damage", "50", &self->damage ); +void SP_misc_panel_turret(gentity_t *self) { + G_SpawnFloat("radius", "90", &self->radius); // yaw + G_SpawnFloat("random", "60", &self->random); // pitch + G_SpawnFloat("speed", "3000", &self->speed); + G_SpawnInt("delay", "200", &self->delay); + G_SpawnInt("damage", "50", &self->damage); - VectorSet( self->pos3, 0.0f, 0.0f, 0.0f ); + VectorSet(self->pos3, 0.0f, 0.0f, 0.0f); - if ( self->spawnflags & 1 ) // heatlh + if (self->spawnflags & 1) // heatlh { self->takedamage = qtrue; self->contents = CONTENTS_SHOTCLIP; - G_SpawnInt( "health", "200", &self->health ); + G_SpawnInt("health", "200", &self->health); self->max_health = self->health; self->dflags |= DAMAGE_CUSTOM_HUD; // dumb, but we draw a custom hud - G_SoundIndex( "sound/movers/objects/ladygun_on" ); + G_SoundIndex("sound/movers/objects/ladygun_on"); } - self->s.modelindex = G_ModelIndex( "models/map_objects/imp_mine/ladyluck_gun.md3" ); + self->s.modelindex = G_ModelIndex("models/map_objects/imp_mine/ladyluck_gun.md3"); - self->soundPos1 = G_SoundIndex( "sound/movers/camera_on.mp3" ); - self->soundPos2 = G_SoundIndex( "sound/movers/camera_off.mp3" ); + self->soundPos1 = G_SoundIndex("sound/movers/camera_on.mp3"); + self->soundPos2 = G_SoundIndex("sound/movers/camera_off.mp3"); - G_SoundIndex( "sound/movers/objects/ladygun_fire" ); + G_SoundIndex("sound/movers/objects/ladygun_fire"); - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); - VectorSet( self->mins, -8, -8, -12 ); - VectorSet( self->maxs, 8, 8, 0 ); + VectorSet(self->mins, -8, -8, -12); + VectorSet(self->maxs, 8, 8, 0); self->contents = CONTENTS_SOLID; self->s.weapon = WP_TURRET; - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); - gi.linkentity( self ); + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); + gi.linkentity(self); self->e_UseFunc = useF_panel_turret_use; self->e_DieFunc = dieF_misc_panel_turret_die; diff --git a/codeJK2/game/g_usable.cpp b/codeJK2/game/g_usable.cpp index 9b5fc7a77c..4170bff9bf 100644 --- a/codeJK2/game/g_usable.cpp +++ b/codeJK2/game/g_usable.cpp @@ -26,127 +26,101 @@ along with this program; if not, see . #include "g_local.h" #include "g_functions.h" -extern void InitMover( gentity_t *ent ); - -extern gentity_t *G_TestEntityPosition( gentity_t *ent ); -void func_wait_return_solid( gentity_t *self ) -{ - //once a frame, see if it's clear. - self->clipmask = CONTENTS_BODY;//|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; - if ( !(self->spawnflags&16) || G_TestEntityPosition( self ) == NULL ) - { - gi.SetBrushModel( self, self->model ); - VectorCopy( self->currentOrigin, self->pos1 ); - InitMover( self ); +extern void InitMover(gentity_t *ent); + +extern gentity_t *G_TestEntityPosition(gentity_t *ent); +void func_wait_return_solid(gentity_t *self) { + // once a frame, see if it's clear. + self->clipmask = CONTENTS_BODY; //|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP; + if (!(self->spawnflags & 16) || G_TestEntityPosition(self) == NULL) { + gi.SetBrushModel(self, self->model); + VectorCopy(self->currentOrigin, self->pos1); + InitMover(self); /* VectorCopy( self->s.origin, self->s.pos.trBase ); VectorCopy( self->s.origin, self->currentOrigin ); */ - //if we moved, we want the *current* origin, not our start origin! - VectorCopy( self->currentOrigin, self->s.pos.trBase ); - gi.linkentity( self ); + // if we moved, we want the *current* origin, not our start origin! + VectorCopy(self->currentOrigin, self->s.pos.trBase); + gi.linkentity(self); self->svFlags &= ~SVF_NOCLIENT; self->s.eFlags &= ~EF_NODRAW; self->e_UseFunc = useF_func_usable_use; self->clipmask = 0; - if ( self->target2 && self->target2[0] ) - { - G_UseTargets2( self, self->activator, self->target2 ); + if (self->target2 && self->target2[0]) { + G_UseTargets2(self, self->activator, self->target2); } - if ( self->s.eFlags & EF_ANIM_ONCE ) - {//Start our anim + if (self->s.eFlags & EF_ANIM_ONCE) { // Start our anim self->s.frame = 0; } - if ( !(self->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( self, qfalse ); + if (!(self->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(self, qfalse); } - } - else - { + } else { self->clipmask = 0; self->e_ThinkFunc = thinkF_func_wait_return_solid; self->nextthink = level.time + FRAMETIME; } } -void func_usable_think( gentity_t *self ) -{ - if ( self->spawnflags & 8 ) - { - self->svFlags |= SVF_PLAYER_USABLE; //Replace the usable flag +void func_usable_think(gentity_t *self) { + if (self->spawnflags & 8) { + self->svFlags |= SVF_PLAYER_USABLE; // Replace the usable flag self->e_UseFunc = useF_func_usable_use; self->e_ThinkFunc = thinkF_NULL; } } -qboolean G_EntIsRemovableUsable( int entNum ) -{ +qboolean G_EntIsRemovableUsable(int entNum) { gentity_t *ent = &g_entities[entNum]; - if ( ent->classname && !Q_stricmp( "func_usable", ent->classname ) ) - { - if ( !(ent->s.eFlags&EF_SHADER_ANIM) && !(ent->spawnflags&8) && ent->targetname ) - {//not just a shader-animator and not ALWAYS_ON, so it must be removable somehow + if (ent->classname && !Q_stricmp("func_usable", ent->classname)) { + if (!(ent->s.eFlags & EF_SHADER_ANIM) && !(ent->spawnflags & 8) && + ent->targetname) { // not just a shader-animator and not ALWAYS_ON, so it must be removable somehow return qtrue; } } return qfalse; } -void func_usable_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{//Toggle on and off - if ( other == activator ) - {//directly used by use button trace - if ( (self->spawnflags&32) ) - {//only usable by NPCs - if ( activator->NPC == NULL ) - {//Not an NPC +void func_usable_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle on and off + if (other == activator) { // directly used by use button trace + if ((self->spawnflags & 32)) { // only usable by NPCs + if (activator->NPC == NULL) { // Not an NPC return; } } } - G_ActivateBehavior( self, BSET_USE ); - if ( self->s.eFlags & EF_SHADER_ANIM ) - {//animate shader when used - self->s.frame++;//inc frame - if ( self->s.frame > self->endFrame ) - {//wrap around + G_ActivateBehavior(self, BSET_USE); + if (self->s.eFlags & EF_SHADER_ANIM) { // animate shader when used + self->s.frame++; // inc frame + if (self->s.frame > self->endFrame) { // wrap around self->s.frame = 0; } - if ( self->target && self->target[0] ) - { - G_UseTargets( self, activator ); + if (self->target && self->target[0]) { + G_UseTargets(self, activator); } - } - else if ( self->spawnflags & 8 ) - {//ALWAYS_ON - //Remove the ability to use the entity directly + } else if (self->spawnflags & 8) { // ALWAYS_ON + // Remove the ability to use the entity directly self->svFlags &= ~SVF_PLAYER_USABLE; - //also remove ability to call any use func at all! + // also remove ability to call any use func at all! self->e_UseFunc = useF_NULL; - - if(self->target && self->target[0]) - { + + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - - if ( self->wait ) - { + + if (self->wait) { self->e_ThinkFunc = thinkF_func_usable_think; - self->nextthink = level.time + ( self->wait * 1000 ); + self->nextthink = level.time + (self->wait * 1000); } return; - } - else if ( !self->count ) - {//become solid again + } else if (!self->count) { // become solid again self->count = 1; self->activator = activator; - func_wait_return_solid( self ); - } - else - { + func_wait_return_solid(self); + } else { self->s.solid = 0; self->contents = 0; self->clipmask = 0; @@ -154,33 +128,29 @@ void func_usable_use( gentity_t *self, gentity_t *other, gentity_t *activator ) self->s.eFlags |= EF_NODRAW; self->count = 0; - if(self->target && self->target[0]) - { + if (self->target && self->target[0]) { G_UseTargets(self, activator); } self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - if ( !(self->spawnflags&1) ) - {//START_OFF doesn't effect area portals - gi.AdjustAreaPortalState( self, qtrue ); + if (!(self->spawnflags & 1)) { // START_OFF doesn't effect area portals + gi.AdjustAreaPortalState(self, qtrue); } } } -void func_usable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod,int hitLoc) -{ - GEntity_UseFunc( self, attacker, attacker ); +void func_usable_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { + GEntity_UseFunc(self, attacker, attacker); } -void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc) -{ +void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { self->takedamage = qfalse; - GEntity_UseFunc( self, inflictor, attacker ); + GEntity_UseFunc(self, inflictor, attacker); } /*QUAKED func_usable (0 .5 .8) ? STARTOFF AUTOANIMATE ANIM_ONCE ALWAYS_ON BLOCKCHECK NPC_USE PLAYER_USE INACTIVE START_OFF - the wall will not be there -AUTOANIMATE - if a model is used it will animate +AUTOANIMATE - if a model is used it will animate ANIM_ONCE - When turned on, goes through anim once ALWAYS_ON - Doesn't toggle on and off when used, just runs usescript and fires target NPC_ONLY - Only NPCs can directly use this @@ -201,17 +171,15 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls "endframe" Will make it animate to next shader frame when used, not turn on/off... set this to number of frames in the shader, minus 1 */ -void SP_func_usable( gentity_t *self ) -{ - gi.SetBrushModel( self, self->model ); - InitMover( self ); - VectorCopy( self->s.origin, self->s.pos.trBase ); - VectorCopy( self->s.origin, self->currentOrigin ); - VectorCopy( self->s.origin, self->pos1 ); +void SP_func_usable(gentity_t *self) { + gi.SetBrushModel(self, self->model); + InitMover(self); + VectorCopy(self->s.origin, self->s.pos.trBase); + VectorCopy(self->s.origin, self->currentOrigin); + VectorCopy(self->s.origin, self->pos1); self->count = 1; - if (self->spawnflags & 1) - { + if (self->spawnflags & 1) { self->s.solid = 0; self->contents = 0; self->clipmask = 0; @@ -220,30 +188,26 @@ void SP_func_usable( gentity_t *self ) self->count = 0; } - if (self->spawnflags & 2) - { + if (self->spawnflags & 2) { self->s.eFlags |= EF_ANIM_ALLFAST; } - if (self->spawnflags & 4) - {//FIXME: need to be able to do change to something when it's done? Or not be usable until it's done? + if (self->spawnflags & 4) { // FIXME: need to be able to do change to something when it's done? Or not be usable until it's done? self->s.eFlags |= EF_ANIM_ONCE; } self->e_UseFunc = useF_func_usable_use; - if ( self->health ) - { + if (self->health) { self->takedamage = qtrue; self->e_DieFunc = dieF_func_usable_die; self->e_PainFunc = painF_func_usable_pain; } - if ( self->endFrame > 0 ) - { + if (self->endFrame > 0) { self->s.frame = self->startFrame = 0; self->s.eFlags |= EF_SHADER_ANIM; } - gi.linkentity (self); + gi.linkentity(self); } \ No newline at end of file diff --git a/codeJK2/game/g_utils.cpp b/codeJK2/game/g_utils.cpp index 95a70c62f2..f7f05a3618 100644 --- a/codeJK2/game/g_utils.cpp +++ b/codeJK2/game/g_utils.cpp @@ -33,10 +33,10 @@ along with this program; if not, see . #include "anims.h" #include "../../code/rd-common/mdx_format.h" -#define ACT_ACTIVE qtrue -#define ACT_INACTIVE qfalse -extern void NPC_UseResponse ( gentity_t *self, gentity_t *user, qboolean useWhenDone ); -extern qboolean PM_CrouchAnim( int anim ); +#define ACT_ACTIVE qtrue +#define ACT_INACTIVE qfalse +extern void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone); +extern qboolean PM_CrouchAnim(int anim); /* ========================================================================= @@ -51,34 +51,34 @@ G_FindConfigstringIndex ================ */ -extern void ForceTelepathy( gentity_t *self ); -int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ) { - int i; - char s[MAX_STRING_CHARS]; +extern void ForceTelepathy(gentity_t *self); +int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create) { + int i; + char s[MAX_STRING_CHARS]; - if ( !name || !name[0] ) { + if (!name || !name[0]) { return 0; } - for ( i=1 ; is.eventParm = fxID; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); - VectorCopy( fwd, tent->pos3 ); + VectorCopy(fwd, tent->pos3); // Assume angles, we'll do a cross product on the other end to finish up - MakeNormalVectors( fwd, tent->pos4, temp ); - gi.linkentity( tent ); + MakeNormalVectors(fwd, tent->pos4, temp); + gi.linkentity(tent); } // Play an effect at the origin of the specified entity //---------------------------- -void G_PlayEffect( int fxID, int entNum, vec3_t fwd ) -{ - gentity_t *tent; - vec3_t temp; +void G_PlayEffect(int fxID, int entNum, vec3_t fwd) { + gentity_t *tent; + vec3_t temp; - tent = G_TempEntity( g_entities[entNum].currentOrigin, EV_PLAY_EFFECT ); + tent = G_TempEntity(g_entities[entNum].currentOrigin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; tent->s.otherEntityNum = entNum; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); - VectorCopy( fwd, tent->pos3 ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); + VectorCopy(fwd, tent->pos3); // Assume angles, we'll do a cross product on the other end to finish up - MakeNormalVectors( fwd, tent->pos4, temp ); + MakeNormalVectors(fwd, tent->pos4, temp); } // Play an effect bolted onto the muzzle of the specified client //---------------------------- -void G_PlayEffect( const char *name, int clientNum ) -{ - gentity_t *tent; +void G_PlayEffect(const char *name, int clientNum) { + gentity_t *tent; - tent = G_TempEntity( g_entities[clientNum].currentOrigin, EV_PLAY_MUZZLE_EFFECT ); - tent->s.eventParm = G_EffectIndex( name ); + tent = G_TempEntity(g_entities[clientNum].currentOrigin, EV_PLAY_MUZZLE_EFFECT); + tent->s.eventParm = G_EffectIndex(name); tent->s.otherEntityNum = clientNum; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); } //----------------------------- -void G_PlayEffect( int fxID, vec3_t origin, vec3_t axis[3] ) -{ - gentity_t *tent; +void G_PlayEffect(int fxID, vec3_t origin, vec3_t axis[3]) { + gentity_t *tent; - tent = G_TempEntity( origin, EV_PLAY_EFFECT ); + tent = G_TempEntity(origin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; - VectorSet( tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( tent->maxs, -1, tent->mins ); + VectorSet(tent->maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(tent->maxs, -1, tent->mins); // We can just assume axis[2] from doing a cross product on these. - VectorCopy( axis[0], tent->pos3 ); - VectorCopy( axis[1], tent->pos4 ); + VectorCopy(axis[0], tent->pos3); + VectorCopy(axis[1], tent->pos4); } // Effect playing utilities - bolt an effect to a ghoul2 models bolton point //----------------------------- -void G_PlayEffect( int fxID, const int modelIndex, const int boltIndex, const int entNum) -{ - gentity_t *tent; - vec3_t origin = {0,0,0}; +void G_PlayEffect(int fxID, const int modelIndex, const int boltIndex, const int entNum) { + gentity_t *tent; + vec3_t origin = {0, 0, 0}; - tent = G_TempEntity( origin, EV_PLAY_EFFECT ); + tent = G_TempEntity(origin, EV_PLAY_EFFECT); tent->s.eventParm = fxID; - tent->svFlags |=SVF_BROADCAST; + tent->svFlags |= SVF_BROADCAST; gi.G2API_AttachEnt(&tent->s.boltInfo, &g_entities[entNum].ghoul2[modelIndex], boltIndex, entNum, modelIndex); } //----------------------------- -void G_PlayEffect( const char *name, vec3_t origin ) -{ - vec3_t up = {0, 0, 1}; +void G_PlayEffect(const char *name, vec3_t origin) { + vec3_t up = {0, 0, 1}; - G_PlayEffect( G_EffectIndex( name ), origin, up ); + G_PlayEffect(G_EffectIndex(name), origin, up); } //----------------------------- -void G_PlayEffect( const char *name, vec3_t origin, vec3_t fwd ) -{ - G_PlayEffect( G_EffectIndex( name ), origin, fwd ); -} +void G_PlayEffect(const char *name, vec3_t origin, vec3_t fwd) { G_PlayEffect(G_EffectIndex(name), origin, fwd); } //----------------------------- -void G_PlayEffect( const char *name, vec3_t origin, vec3_t axis[3] ) -{ - G_PlayEffect( G_EffectIndex( name ), origin, axis ); -} +void G_PlayEffect(const char *name, vec3_t origin, vec3_t axis[3]) { G_PlayEffect(G_EffectIndex(name), origin, axis); } //----------------------------- -void G_PlayEffect( const char *name, const int modelIndex, const int boltIndex, const int entNum ) -{ - G_PlayEffect( G_EffectIndex( name ), modelIndex, boltIndex, entNum ); +void G_PlayEffect(const char *name, const int modelIndex, const int boltIndex, const int entNum) { + G_PlayEffect(G_EffectIndex(name), modelIndex, boltIndex, entNum); } //===Bypass network for sounds on specific channels==================== -extern void cgi_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); -#include "../cgame/cg_media.h" //access to cgs -extern void CG_TryPlayCustomSound( vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet ); -//NOTE: Do NOT Try to use this before the cgame DLL is valid, it will NOT work! -void G_SoundOnEnt (gentity_t *ent, soundChannel_t channel, const char *soundPath) -{ - int index = G_SoundIndex( (char *)soundPath ); +extern void cgi_S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); +#include "../cgame/cg_media.h" //access to cgs +extern void CG_TryPlayCustomSound(vec3_t origin, int entityNum, soundChannel_t channel, const char *soundName, int customSoundSet); +// NOTE: Do NOT Try to use this before the cgame DLL is valid, it will NOT work! +void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath) { + int index = G_SoundIndex((char *)soundPath); - if ( !ent ) - { + if (!ent) { return; } - cgi_S_UpdateEntityPosition( ent->s.number, ent->currentOrigin ); - if ( cgs.sound_precache[ index ] ) - { - cgi_S_StartSound( NULL, ent->s.number, channel, cgs.sound_precache[ index ] ); - } - else - { - CG_TryPlayCustomSound( NULL, ent->s.number, channel, soundPath, -1 ); + cgi_S_UpdateEntityPosition(ent->s.number, ent->currentOrigin); + if (cgs.sound_precache[index]) { + cgi_S_StartSound(NULL, ent->s.number, channel, cgs.sound_precache[index]); + } else { + CG_TryPlayCustomSound(NULL, ent->s.number, channel, soundPath, -1); } } -void G_SpeechEvent( gentity_t *self, int event ) -{ - //update entity pos, too - cgi_S_UpdateEntityPosition( self->s.number, self->currentOrigin ); - switch ( event ) - { - case EV_ANGER1: //Say when acquire an enemy when didn't have one before +void G_SpeechEvent(gentity_t *self, int event) { + // update entity pos, too + cgi_S_UpdateEntityPosition(self->s.number, self->currentOrigin); + switch (event) { + case EV_ANGER1: // Say when acquire an enemy when didn't have one before case EV_ANGER2: case EV_ANGER3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1), CS_COMBAT); break; - case EV_VICTORY1: //Say when killed an enemy + case EV_VICTORY1: // Say when killed an enemy case EV_VICTORY2: case EV_VICTORY3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1), CS_COMBAT); break; - case EV_CONFUSE1: //Say when confused + case EV_CONFUSE1: // Say when confused case EV_CONFUSE2: case EV_CONFUSE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1), CS_COMBAT); break; - case EV_PUSHED1: //Say when pushed + case EV_PUSHED1: // Say when pushed case EV_PUSHED2: case EV_PUSHED3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1), CS_COMBAT); break; - case EV_CHOKE1: //Say when choking + case EV_CHOKE1: // Say when choking case EV_CHOKE2: case EV_CHOKE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1), CS_COMBAT); break; - case EV_FFWARN: //Warn ally to stop shooting you - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT ); + case EV_FFWARN: // Warn ally to stop shooting you + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*ffwarn.wav", CS_COMBAT); break; - case EV_FFTURN: //Turn on ally after being shot by them - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT ); + case EV_FFTURN: // Turn on ally after being shot by them + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*ffturn.wav", CS_COMBAT); break; - //extra sounds for ST + // extra sounds for ST case EV_CHASE1: case EV_CHASE2: case EV_CHASE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1), CS_EXTRA); break; case EV_COVER1: case EV_COVER2: case EV_COVER3: case EV_COVER4: case EV_COVER5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1), CS_EXTRA); break; case EV_DETECTED1: case EV_DETECTED2: case EV_DETECTED3: case EV_DETECTED4: case EV_DETECTED5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1), CS_EXTRA); break; case EV_GIVEUP1: case EV_GIVEUP2: case EV_GIVEUP3: case EV_GIVEUP4: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1), CS_EXTRA); break; case EV_LOOK1: case EV_LOOK2: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1), CS_EXTRA); break; case EV_LOST1: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*lost1.wav", CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*lost1.wav", CS_EXTRA); break; case EV_OUTFLANK1: case EV_OUTFLANK2: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1), CS_EXTRA); break; case EV_ESCAPING1: case EV_ESCAPING2: case EV_ESCAPING3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1), CS_EXTRA); break; case EV_SIGHT1: case EV_SIGHT2: case EV_SIGHT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1), CS_EXTRA); break; case EV_SOUND1: case EV_SOUND2: case EV_SOUND3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1), CS_EXTRA); break; case EV_SUSPICIOUS1: case EV_SUSPICIOUS2: case EV_SUSPICIOUS3: case EV_SUSPICIOUS4: case EV_SUSPICIOUS5: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1), CS_EXTRA); break; - //extra sounds for Jedi + // extra sounds for Jedi case EV_COMBAT1: case EV_COMBAT2: case EV_COMBAT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1), CS_JEDI); break; case EV_JDETECTED1: case EV_JDETECTED2: case EV_JDETECTED3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1), CS_JEDI); break; case EV_TAUNT1: case EV_TAUNT2: case EV_TAUNT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1), CS_JEDI); break; case EV_JCHASE1: case EV_JCHASE2: case EV_JCHASE3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1), CS_JEDI); break; case EV_JLOST1: case EV_JLOST2: case EV_JLOST3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1), CS_JEDI); break; case EV_DEFLECT1: case EV_DEFLECT2: case EV_DEFLECT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1), CS_JEDI); break; case EV_GLOAT1: case EV_GLOAT2: case EV_GLOAT3: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1), CS_JEDI); break; case EV_PUSHFAIL: - CG_TryPlayCustomSound( NULL, self->s.number, CHAN_VOICE, "*pushfail.wav", CS_JEDI ); + CG_TryPlayCustomSound(NULL, self->s.number, CHAN_VOICE, "*pushfail.wav", CS_JEDI); break; } } //===================================================================== - - /* ============= G_Find @@ -405,12 +378,10 @@ NULL will be returned if the end of the list is reached. ============= */ -gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match) -{ - char *s; +gentity_t *G_Find(gentity_t *from, int fieldofs, const char *match) { + char *s; - if(!match || !match[0]) - { + if (!match || !match[0]) { return NULL; } @@ -419,93 +390,80 @@ gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match) else from++; -// for ( ; from < &g_entities[globals.num_entities] ; from++) - int i=from-g_entities; - for ( ; i < globals.num_entities ; i++) - { -// if (!from->inuse) - if(!PInUse(i)) + // for ( ; from < &g_entities[globals.num_entities] ; from++) + int i = from - g_entities; + for (; i < globals.num_entities; i++) { + // if (!from->inuse) + if (!PInUse(i)) continue; - from=&g_entities[i]; - s = *(char **) ((byte *)from + fieldofs); + from = &g_entities[i]; + s = *(char **)((byte *)from + fieldofs); if (!s) continue; - if (!Q_stricmp (s, match)) + if (!Q_stricmp(s, match)) return from; } return NULL; } - /* ============ G_RadiusList - given an origin and a radius, return all entities that are in use that are within the list ============ */ -int G_RadiusList ( vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) -{ - float dist; - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - - if ( radius < 1 ) - { +int G_RadiusList(vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) { + float dist; + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if ((ent == ignore) || !(ent->inuse) || ent->takedamage != takeDamage) continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( origin[i] < ent->absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - origin[i]; - } else if ( origin[i] > ent->absmax[i] ) - { + } else if (origin[i] > ent->absmax[i]) { v[i] = origin[i] - ent->absmax[i]; - } else - { + } else { v[i] = 0; } } - dist = VectorLength( v ); - if ( dist >= radius ) - { + dist = VectorLength(v); + if (dist >= radius) { continue; } // ok, we are within the radius, add us to the incoming list ent_list[ent_count] = ent; ent_count++; - } // we are done, return how many we found - return(ent_count); + return (ent_count); } - /* ============= G_PickTarget @@ -513,23 +471,20 @@ G_PickTarget Selects a random entity from among the targets ============= */ -#define MAXCHOICES 32 +#define MAXCHOICES 32 -gentity_t *G_PickTarget (char *targetname) -{ - gentity_t *ent = NULL; - int num_choices = 0; - gentity_t *choice[MAXCHOICES]; +gentity_t *G_PickTarget(char *targetname) { + gentity_t *ent = NULL; + int num_choices = 0; + gentity_t *choice[MAXCHOICES]; - if (!targetname) - { + if (!targetname) { gi.Printf("G_PickTarget called with NULL targetname\n"); return NULL; } - while(1) - { - ent = G_Find (ent, FOFS(targetname), targetname); + while (1) { + ent = G_Find(ent, FOFS(targetname), targetname); if (!ent) break; choice[num_choices++] = ent; @@ -537,8 +492,7 @@ gentity_t *G_PickTarget (char *targetname) break; } - if (!num_choices) - { + if (!num_choices) { gi.Printf("G_PickTarget: target %s not found\n", targetname); return NULL; } @@ -546,29 +500,24 @@ gentity_t *G_PickTarget (char *targetname) return choice[rand() % num_choices]; } -void G_UseTargets2 (gentity_t *ent, gentity_t *activator, const char *string) -{ - gentity_t *t; +void G_UseTargets2(gentity_t *ent, gentity_t *activator, const char *string) { + gentity_t *t; -// -// fire targets -// - if (string) - { + // + // fire targets + // + if (string) { t = NULL; - while ( (t = G_Find (t, FOFS(targetname), (char *) string)) != NULL ) - { - if (t == ent) - { -// gi.Printf ("WARNING: Entity used itself.\n"); + while ((t = G_Find(t, FOFS(targetname), (char *)string)) != NULL) { + if (t == ent) { + // gi.Printf ("WARNING: Entity used itself.\n"); } - if (t->e_UseFunc != useF_NULL) // check can be omitted + if (t->e_UseFunc != useF_NULL) // check can be omitted { GEntity_UseFunc(t, ent, activator); } - if (!ent->inuse) - { + if (!ent->inuse) { gi.Printf("entity was removed while using targets\n"); return; } @@ -587,15 +536,13 @@ match (string)self.target and call their .use function ============================== */ -void G_UseTargets (gentity_t *ent, gentity_t *activator) -{ -// -// fire targets -// - G_UseTargets2 (ent, activator, ent->target); +void G_UseTargets(gentity_t *ent, gentity_t *activator) { + // + // fire targets + // + G_UseTargets2(ent, activator, ent->target); } - /* ============= TempVector @@ -604,15 +551,15 @@ This is just a convenience function for making temporary vectors for function calls ============= */ -float *tv( float x, float y, float z ) { - static int index; - static vec3_t vecs[8]; - float *v; +float *tv(float x, float y, float z) { + static int index; + static vec3_t vecs[8]; + float *v; // use an array so that multiple tempvectors won't collide // for a while v = vecs[index]; - index = (index + 1)&7; + index = (index + 1) & 7; v[0] = x; v[1] = y; @@ -621,7 +568,6 @@ float *tv( float x, float y, float z ) { return v; } - /* ============= VectorToString @@ -630,21 +576,20 @@ This is just a convenience function for printing vectors ============= */ -char *vtos( const vec3_t v ) { - static int index; - static char str[8][32]; - char *s; +char *vtos(const vec3_t v) { + static int index; + static char str[8][32]; + char *s; // use an array so that multiple vtos won't collide s = str[index]; - index = (index + 1)&7; + index = (index + 1) & 7; - Com_sprintf (s, 32, "(%4.2f %4.2f %4.2f)", v[0], v[1], v[2]); + Com_sprintf(s, 32, "(%4.2f %4.2f %4.2f)", v[0], v[1], v[2]); return s; } - /* =============== G_SetMovedir @@ -655,31 +600,30 @@ Angles will be cleared, because it is being used to represent a direction instead of an orientation. =============== */ -void G_SetMovedir( vec3_t angles, vec3_t movedir ) { - static vec3_t VEC_UP = {0, -1, 0}; - static vec3_t MOVEDIR_UP = {0, 0, 1}; - static vec3_t VEC_DOWN = {0, -2, 0}; - static vec3_t MOVEDIR_DOWN = {0, 0, -1}; - - if ( VectorCompare (angles, VEC_UP) ) { - VectorCopy (MOVEDIR_UP, movedir); - } else if ( VectorCompare (angles, VEC_DOWN) ) { - VectorCopy (MOVEDIR_DOWN, movedir); +void G_SetMovedir(vec3_t angles, vec3_t movedir) { + static vec3_t VEC_UP = {0, -1, 0}; + static vec3_t MOVEDIR_UP = {0, 0, 1}; + static vec3_t VEC_DOWN = {0, -2, 0}; + static vec3_t MOVEDIR_DOWN = {0, 0, -1}; + + if (VectorCompare(angles, VEC_UP)) { + VectorCopy(MOVEDIR_UP, movedir); + } else if (VectorCompare(angles, VEC_DOWN)) { + VectorCopy(MOVEDIR_DOWN, movedir); } else { - AngleVectors (angles, movedir, NULL, NULL); + AngleVectors(angles, movedir, NULL, NULL); } - VectorClear( angles ); + VectorClear(angles); } - -float vectoyaw( const vec3_t vec ) { - float yaw; +float vectoyaw(const vec3_t vec) { + float yaw; if (vec[YAW] == 0 && vec[PITCH] == 0) { yaw = 0; } else { if (vec[PITCH]) { - yaw = ( atan2( vec[YAW], vec[PITCH]) * 180 / M_PI ); + yaw = (atan2(vec[YAW], vec[PITCH]) * 180 / M_PI); } else if (vec[YAW] > 0) { yaw = 90; } else { @@ -693,23 +637,21 @@ float vectoyaw( const vec3_t vec ) { return yaw; } - -void G_InitGentity( gentity_t *e ) -{ +void G_InitGentity(gentity_t *e) { e->inuse = qtrue; SetInUse(e); e->classname = "noclass"; e->s.number = e - g_entities; - ICARUS_FreeEnt( e ); //ICARUS information must be added after this point + ICARUS_FreeEnt(e); // ICARUS information must be added after this point // remove any ghoul2 models here - //let not gi.G2API_CleanGhoul2Models(e->ghoul2); + // let not gi.G2API_CleanGhoul2Models(e->ghoul2); - //Navigational setups - e->waypoint = WAYPOINT_NONE; - e->lastWaypoint = WAYPOINT_NONE; - e->lastValidWaypoint = WAYPOINT_NONE; + // Navigational setups + e->waypoint = WAYPOINT_NONE; + e->lastWaypoint = WAYPOINT_NONE; + e->lastValidWaypoint = WAYPOINT_NONE; } /* @@ -727,88 +669,81 @@ instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ -gentity_t *G_Spawn( void ) -{ - int i, force; - gentity_t *e; - - e = NULL; // shut up warning - i = 0; // shut up warning - for ( force = 0 ; force < 2 ; force++ ) - { +gentity_t *G_Spawn(void) { + int i, force; + gentity_t *e; + + e = NULL; // shut up warning + i = 0; // shut up warning + for (force = 0; force < 2; force++) { // if we go through all entities and can't find one to free, // override the normal minimum times before use e = &g_entities[MAX_CLIENTS]; -// for ( i = MAX_CLIENTS ; iinuse ) -// { -// continue; -// } - for ( i = MAX_CLIENTS ; iinuse ) + // { + // continue; + // } + for (i = MAX_CLIENTS; i < globals.num_entities; i++) { + if (PInUse(i)) { continue; } - e=&g_entities[i]; + e = &g_entities[i]; // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy - if ( !force && e->freetime > 2000 && level.time - e->freetime < 1000 ) { + if (!force && e->freetime > 2000 && level.time - e->freetime < 1000) { continue; } // reuse this slot - G_InitGentity( e ); + G_InitGentity(e); return e; } - e=&g_entities[i]; - if ( i != ENTITYNUM_MAX_NORMAL ) - { + e = &g_entities[i]; + if (i != ENTITYNUM_MAX_NORMAL) { break; } } - if ( i == ENTITYNUM_MAX_NORMAL ) - { -/* - e = &g_entities[0]; - -//--------------Use this to dump directly to a file - char buff[256]; - FILE *fp; - - fp = fopen( "c:/dump.txt", "w" ); - for ( i = 0 ; iclassname ) - { - sprintf( buff, "%d: %s\n", i, e->classname ); - } - - fputs( buff, fp ); - } - fclose( fp ); -//---------------Or use this to dump to the console -- beware though, the console will fill quickly and you probably won't see the full list - for ( i = 0 ; iclassname ) - { - Com_Printf( "%d: %s\n", i, e->classname ); - - } - } -*/ - G_Error( "G_Spawn: no free entities" ); + if (i == ENTITYNUM_MAX_NORMAL) { + /* + e = &g_entities[0]; + + //--------------Use this to dump directly to a file + char buff[256]; + FILE *fp; + + fp = fopen( "c:/dump.txt", "w" ); + for ( i = 0 ; iclassname ) + { + sprintf( buff, "%d: %s\n", i, e->classname ); + } + + fputs( buff, fp ); + } + fclose( fp ); + //---------------Or use this to dump to the console -- beware though, the console will fill quickly and you probably won't see the full list + for ( i = 0 ; iclassname ) + { + Com_Printf( "%d: %s\n", i, e->classname ); + + } + } + */ + G_Error("G_Spawn: no free entities"); } // open up a new slot globals.num_entities++; - G_InitGentity( e ); + G_InitGentity(e); return e; } - /* ================= G_FreeEntity @@ -816,10 +751,10 @@ G_FreeEntity Marks the entity as free ================= */ -void G_FreeEntity( gentity_t *ed ) { - gi.unlinkentity (ed); // unlink from world +void G_FreeEntity(gentity_t *ed) { + gi.unlinkentity(ed); // unlink from world - ICARUS_FreeEnt( ed ); + ICARUS_FreeEnt(ed); /*if ( ed->neverFree ) { return; @@ -828,8 +763,8 @@ void G_FreeEntity( gentity_t *ed ) { // remove any ghoul2 models here gi.G2API_CleanGhoul2Models(ed->ghoul2); - memset (ed, 0, sizeof(*ed)); - //FIXME: This sets the entity number to zero, which is the player. + memset(ed, 0, sizeof(*ed)); + // FIXME: This sets the entity number to zero, which is the player. // This is really fucking stupid and has caused us no end of // trouble!!! Change it to set the s.number to the proper index // (ed - g_entities) *OR* ENTITYNUM_NONE!!! @@ -849,9 +784,9 @@ The origin will be snapped to save net bandwidth, so care must be taken if the origin is right on a surface (snap towards start vector first) ================= */ -gentity_t *G_TempEntity( vec3_t origin, int event ) { - gentity_t *e; - vec3_t snapped; +gentity_t *G_TempEntity(vec3_t origin, int event) { + gentity_t *e; + vec3_t snapped; e = G_Spawn(); e->s.eType = ET_EVENTS + event; @@ -860,18 +795,16 @@ gentity_t *G_TempEntity( vec3_t origin, int event ) { e->eventTime = level.time; e->freeAfterEvent = qtrue; - VectorCopy( origin, snapped ); - SnapVector( snapped ); // save network bandwidth - G_SetOrigin( e, snapped ); + VectorCopy(origin, snapped); + SnapVector(snapped); // save network bandwidth + G_SetOrigin(e, snapped); // find cluster for PVS - gi.linkentity( e ); + gi.linkentity(e); return e; } - - /* ============================================================================== @@ -888,52 +821,43 @@ Kills all entities that would touch the proposed new positioning of ent. Ent should be unlinked before calling this! ================= */ -void G_KillBox (gentity_t *ent) { - int i, num; - gentity_t *touch[MAX_GENTITIES], *hit; - vec3_t mins, maxs; +void G_KillBox(gentity_t *ent) { + int i, num; + gentity_t *touch[MAX_GENTITIES], *hit; + vec3_t mins, maxs; - VectorAdd( ent->client->ps.origin, ent->mins, mins ); - VectorAdd( ent->client->ps.origin, ent->maxs, maxs ); - num = gi.EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(ent->client->ps.origin, ent->mins, mins); + VectorAdd(ent->client->ps.origin, ent->maxs, maxs); + num = gi.EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient ) { + if (!hit->client) { continue; } - if ( hit == ent ) { + if (hit == ent) { continue; } - if ( ent->s.number && hit->client->ps.stats[STAT_HEALTH] <= 0 ) - {//NPC + if (ent->s.number && hit->client->ps.stats[STAT_HEALTH] <= 0) { // NPC continue; } - if ( ent->s.number ) - {//NPC - if ( !(hit->contents&CONTENTS_BODY) ) - { + if (ent->s.number) { // NPC + if (!(hit->contents & CONTENTS_BODY)) { continue; } - } - else - {//player - if ( !(hit->contents & ent->contents) ) - { + } else { // player + if (!(hit->contents & ent->contents)) { continue; } } // nail it - G_Damage ( hit, ent, ent, NULL, NULL, - 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); + G_Damage(hit, ent, ent, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } - } //============================================================================== - /* =============== G_AddEvent @@ -941,11 +865,11 @@ G_AddEvent Adds an event+parm and twiddles the event counter =============== */ -void G_AddEvent( gentity_t *ent, int event, int eventParm ) { - int bits; +void G_AddEvent(gentity_t *ent, int event, int eventParm) { + int bits; - if ( !event ) { - gi.Printf( "G_AddEvent: zero event added for entity %i\n", ent->s.number ); + if (!event) { + gi.Printf("G_AddEvent: zero event added for entity %i\n", ent->s.number); return; } @@ -970,7 +894,7 @@ void G_AddEvent( gentity_t *ent, int event, int eventParm ) { #endif // clients need to add the event in playerState_t instead of entityState_t - if ( !ent->s.number ) //only one client + if (!ent->s.number) // only one client { #if 0 bits = ent->client->ps.externalEvent & EV_EVENT_BITS; @@ -979,38 +903,32 @@ void G_AddEvent( gentity_t *ent, int event, int eventParm ) { ent->client->ps.externalEventParm = eventParm; ent->client->ps.externalEventTime = level.time; #endif - if ( eventParm > 255 ) - { - if ( event == EV_PAIN ) - {//must have cheated, in undying? + if (eventParm > 255) { + if (event == EV_PAIN) { // must have cheated, in undying? eventParm = 255; - } - else - { - assert( eventParm < 256 ); + } else { + assert(eventParm < 256); } } - AddEventToPlayerstate( event, eventParm, &ent->client->ps ); + AddEventToPlayerstate(event, eventParm, &ent->client->ps); } else { bits = ent->s.event & EV_EVENT_BITS; - bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS; + bits = (bits + EV_EVENT_BIT1) & EV_EVENT_BITS; ent->s.event = event | bits; ent->s.eventParm = eventParm; } ent->eventTime = level.time; } - /* ============= G_Sound ============= */ -void G_Sound( gentity_t *ent, int soundIndex ) -{ - gentity_t *te; +void G_Sound(gentity_t *ent, int soundIndex) { + gentity_t *te; - te = G_TempEntity( ent->currentOrigin, EV_GENERAL_SOUND ); + te = G_TempEntity(ent->currentOrigin, EV_GENERAL_SOUND); te->s.eventParm = soundIndex; } @@ -1019,11 +937,10 @@ void G_Sound( gentity_t *ent, int soundIndex ) G_Sound ============= */ -void G_SoundAtSpot( vec3_t org, int soundIndex ) -{ - gentity_t *te; +void G_SoundAtSpot(vec3_t org, int soundIndex) { + gentity_t *te; - te = G_TempEntity( org, EV_GENERAL_SOUND ); + te = G_TempEntity(org, EV_GENERAL_SOUND); te->s.eventParm = soundIndex; } @@ -1034,11 +951,10 @@ G_SoundBroadcast Plays sound that can permeate PVS blockage ============= */ -void G_SoundBroadcast( gentity_t *ent, int soundIndex ) -{ - gentity_t *te; +void G_SoundBroadcast(gentity_t *ent, int soundIndex) { + gentity_t *te; - te = G_TempEntity( ent->currentOrigin, EV_GLOBAL_SOUND ); //full volume + te = G_TempEntity(ent->currentOrigin, EV_GLOBAL_SOUND); // full volume te->s.eventParm = soundIndex; te->svFlags |= SVF_BROADCAST; } @@ -1052,30 +968,25 @@ G_SetOrigin Sets the pos trajectory for a fixed position ================ */ -void G_SetOrigin( gentity_t *ent, const vec3_t origin ) -{ - VectorCopy( origin, ent->s.pos.trBase ); - if(ent->client) - { - VectorCopy( origin, ent->client->ps.origin ); - VectorCopy( origin, ent->s.origin ); - } - else - { +void G_SetOrigin(gentity_t *ent, const vec3_t origin) { + VectorCopy(origin, ent->s.pos.trBase); + if (ent->client) { + VectorCopy(origin, ent->client->ps.origin); + VectorCopy(origin, ent->s.origin); + } else { ent->s.pos.trType = TR_STATIONARY; } ent->s.pos.trTime = 0; ent->s.pos.trDuration = 0; - VectorClear( ent->s.pos.trDelta ); + VectorClear(ent->s.pos.trDelta); - VectorCopy( origin, ent->currentOrigin ); + VectorCopy(origin, ent->currentOrigin); } //=============================================================================== -qboolean G_CheckInSolid (gentity_t *self, qboolean fix) -{ - trace_t trace; - vec3_t end, mins; +qboolean G_CheckInSolid(gentity_t *self, qboolean fix) { + trace_t trace; + vec3_t end, mins; VectorCopy(self->currentOrigin, end); end[2] += self->mins[2]; @@ -1083,16 +994,13 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) mins[2] = 0; gi.trace(&trace, self->currentOrigin, mins, self->maxs, end, self->s.number, self->clipmask, G2_NOCOLLIDE, 0); - if(trace.allsolid || trace.startsolid) - { + if (trace.allsolid || trace.startsolid) { return qtrue; } - if(trace.fraction < 1.0) - { - if(fix) - {//Put them at end of trace and check again - vec3_t neworg; + if (trace.fraction < 1.0) { + if (fix) { // Put them at end of trace and check again + vec3_t neworg; VectorCopy(trace.endpos, neworg); neworg[2] -= self->mins[2]; @@ -1100,9 +1008,7 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) gi.linkentity(self); return G_CheckInSolid(self, qfalse); - } - else - { + } else { return qtrue; } } @@ -1110,10 +1016,9 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) return qfalse; } -qboolean infront(gentity_t *from, gentity_t *to) -{ - vec3_t angles, dir, forward; - float dot; +qboolean infront(gentity_t *from, gentity_t *to) { + vec3_t angles, dir, forward; + float dot; angles[PITCH] = angles[ROLL] = 0; angles[YAW] = from->s.angles[YAW]; @@ -1123,105 +1028,84 @@ qboolean infront(gentity_t *from, gentity_t *to) VectorNormalize(dir); dot = DotProduct(forward, dir); - if(dot < 0.0f) - { + if (dot < 0.0f) { return qfalse; } return qtrue; } -void Svcmd_Use_f( void ) -{ - char *cmd1 = gi.argv(1); +void Svcmd_Use_f(void) { + char *cmd1 = gi.argv(1); - if ( !cmd1 || !cmd1[0] ) - { - //FIXME: warning message - gi.Printf( "'use' takes targetname of ent or 'list' (lists all usable ents)\n" ); + if (!cmd1 || !cmd1[0]) { + // FIXME: warning message + gi.Printf("'use' takes targetname of ent or 'list' (lists all usable ents)\n"); return; - } - else if ( !Q_stricmp("list", cmd1) ) - { - gentity_t *ent; + } else if (!Q_stricmp("list", cmd1)) { + gentity_t *ent; gi.Printf("Listing all usable entities:\n"); - for ( int i = 1; i < ENTITYNUM_WORLD; i++ ) - { - ent = &g_entities[i]; - if ( ent ) - { - if ( ent->targetname && ent->targetname[0] ) - { - if ( ent->e_UseFunc != useF_NULL ) - { - if ( ent->NPC ) - { - gi.Printf( "%s (NPC)\n", ent->targetname ); - } - else - { - gi.Printf( "%s\n", ent->targetname ); - } - } - } - } + for (int i = 1; i < ENTITYNUM_WORLD; i++) { + ent = &g_entities[i]; + if (ent) { + if (ent->targetname && ent->targetname[0]) { + if (ent->e_UseFunc != useF_NULL) { + if (ent->NPC) { + gi.Printf("%s (NPC)\n", ent->targetname); + } else { + gi.Printf("%s\n", ent->targetname); + } + } + } + } } gi.Printf("End of list.\n"); - } - else - { - G_UseTargets2( &g_entities[0], &g_entities[0], cmd1 ); + } else { + G_UseTargets2(&g_entities[0], &g_entities[0], cmd1); } } //====================================================== -void G_SetActiveState(char *targetstring, qboolean actState) -{ - gentity_t *target = NULL; - while( NULL != (target = G_Find(target, FOFS(targetname), targetstring)) ) - { - target->svFlags = actState ? (target->svFlags&~SVF_INACTIVE) : (target->svFlags|SVF_INACTIVE); +void G_SetActiveState(char *targetstring, qboolean actState) { + gentity_t *target = NULL; + while (NULL != (target = G_Find(target, FOFS(targetname), targetstring))) { + target->svFlags = actState ? (target->svFlags & ~SVF_INACTIVE) : (target->svFlags | SVF_INACTIVE); } } -void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_ACTIVE); } -void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_INACTIVE); } -//FIXME: make these apply to doors, etc too? +// FIXME: make these apply to doors, etc too? /*QUAKED target_activate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be usable/triggerable */ -void SP_target_activate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_activate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_activate_use; } /*QUAKED target_deactivate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be non-usable/triggerable */ -void SP_target_deactivate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_deactivate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->e_UseFunc = useF_target_deactivate_use; } - //====================================================== /* @@ -1231,26 +1115,21 @@ ValidUseTarget Returns whether or not the targeted entity is useable ============== */ -qboolean ValidUseTarget( gentity_t *ent ) -{ - if ( ent->e_UseFunc == useF_NULL ) - { +qboolean ValidUseTarget(gentity_t *ent) { + if (ent->e_UseFunc == useF_NULL) { return qfalse; } - if ( ent->svFlags & SVF_INACTIVE ) - {//set by target_deactivate + if (ent->svFlags & SVF_INACTIVE) { // set by target_deactivate return qfalse; } - if ( !(ent->svFlags & SVF_PLAYER_USABLE) ) - {//Check for flag that denotes BUTTON_USE useability + if (!(ent->svFlags & SVF_PLAYER_USABLE)) { // Check for flag that denotes BUTTON_USE useability return qfalse; } - //FIXME: This is only a temp fix.. - if ( !strncmp( ent->classname, "trigger", 7) ) - { + // FIXME: This is only a temp fix.. + if (!strncmp(ent->classname, "trigger", 7)) { return qfalse; } @@ -1265,33 +1144,31 @@ Try and use an entity in the world, directly ahead of us ============== */ -#define USE_DISTANCE 64.0f +#define USE_DISTANCE 64.0f -void TryUse( gentity_t *ent ) -{ - gentity_t *target; - trace_t trace; - vec3_t src, dest, vf; +void TryUse(gentity_t *ent) { + gentity_t *target; + trace_t trace; + vec3_t src, dest, vf; - if ( ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST ) - {//a player trying to get out of his ATST - GEntity_UseFunc( ent->activator, ent, ent ); + if (ent->s.number == 0 && ent->client->NPC_class == CLASS_ATST) { // a player trying to get out of his ATST + GEntity_UseFunc(ent->activator, ent, ent); return; } - //FIXME: this does not match where the new accurate crosshair aims... - //cg.refdef.vieworg, basically - VectorCopy( ent->client->renderInfo.eyePoint, src ); + // FIXME: this does not match where the new accurate crosshair aims... + // cg.refdef.vieworg, basically + VectorCopy(ent->client->renderInfo.eyePoint, src); - AngleVectors( ent->client->ps.viewangles, vf, NULL, NULL );//ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically - //extend to find end of use trace - VectorMA( src, USE_DISTANCE, vf, dest ); + AngleVectors(ent->client->ps.viewangles, vf, NULL, NULL); // ent->client->renderInfo.eyeAngles was cg.refdef.viewangles, basically + // extend to find end of use trace + VectorMA(src, USE_DISTANCE, vf, dest); - //Trace ahead to find a valid target - gi.trace( &trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, G2_NOCOLLIDE, 0 ); + // Trace ahead to find a valid target + gi.trace(&trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, + G2_NOCOLLIDE, 0); - if ( trace.fraction == 1.0f || trace.entityNum < 1 ) - { - //TODO: Play a failure sound + if (trace.fraction == 1.0f || trace.entityNum < 1) { + // TODO: Play a failure sound /* if ( ent->s.number == 0 ) {//if nothing else, try the force telepathy power @@ -1303,28 +1180,22 @@ void TryUse( gentity_t *ent ) target = &g_entities[trace.entityNum]; - //Check for a use command - if ( ValidUseTarget( target ) ) - { - NPC_SetAnim( ent, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // Check for a use command + if (ValidUseTarget(target)) { + NPC_SetAnim(ent, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); /* if ( !VectorLengthSquared( ent->client->ps.velocity ) && !PM_CrouchAnim( ent->client->ps.legsAnim ) ) { NPC_SetAnim( ent, SETANIM_LEGS, BOTH_BUTTON_HOLD, SETANIM_FLAG_NORMAL|SETANIM_FLAG_HOLD ); } */ - //ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; - GEntity_UseFunc( target, ent, ent ); + // ent->client->ps.weaponTime = ent->client->ps.torsoAnimTimer; + GEntity_UseFunc(target, ent, ent); return; - } - else if ( target->client - && target->client->ps.pm_type < PM_DEAD - && target->NPC!=NULL - && target->client->playerTeam - && (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) - && !(target->NPC->scriptFlags&SCF_NO_RESPONSE) ) - { - NPC_UseResponse ( target, ent, qfalse ); + } else if (target->client && target->client->ps.pm_type < PM_DEAD && target->NPC != NULL && target->client->playerTeam && + (target->client->playerTeam == ent->client->playerTeam || target->client->playerTeam == TEAM_NEUTRAL) && + !(target->NPC->scriptFlags & SCF_NO_RESPONSE)) { + NPC_UseResponse(target, ent, qfalse); return; } /* @@ -1336,40 +1207,31 @@ void TryUse( gentity_t *ent ) } extern int killPlayerTimer; -void G_ChangeMap (const char *mapname, const char *spawntarget, qboolean hub) -{ -// gi.Printf("Loading..."); - //ignore if player is dead +void G_ChangeMap(const char *mapname, const char *spawntarget, qboolean hub) { + // gi.Printf("Loading..."); + // ignore if player is dead if (g_entities[0].client->ps.pm_type == PM_DEAD) return; - if ( killPlayerTimer ) - {//can't go to next map if your allies have turned on you + if (killPlayerTimer) { // can't go to next map if your allies have turned on you return; } - if ( spawntarget == NULL ) { - spawntarget = ""; //prevent it from becoming "(null)" - } - if ( hub == qtrue ) - { - gi.SendConsoleCommand( va("loadtransition %s %s\n", mapname, spawntarget) ); + if (spawntarget == NULL) { + spawntarget = ""; // prevent it from becoming "(null)" } - else - { - gi.SendConsoleCommand( va("maptransition %s %s\n", mapname, spawntarget) ); + if (hub == qtrue) { + gi.SendConsoleCommand(va("loadtransition %s %s\n", mapname, spawntarget)); + } else { + gi.SendConsoleCommand(va("maptransition %s %s\n", mapname, spawntarget)); } } -qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ) -{ - for(int i = 0; i < 3; i++ ) - { - if ( point[i] < mins[i] ) - { +qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs) { + for (int i = 0; i < 3; i++) { + if (point[i] < mins[i]) { return qfalse; } - if ( point[i] > maxs[i] ) - { + if (point[i] > maxs[i]) { return qfalse; } } @@ -1377,61 +1239,55 @@ qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t ma return qtrue; } -qboolean G_BoxInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs, const vec3_t boundsMins, const vec3_t boundsMaxs ) -{ +qboolean G_BoxInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs, const vec3_t boundsMins, const vec3_t boundsMaxs) { vec3_t boxMins; vec3_t boxMaxs; - VectorAdd( point, mins, boxMins ); - VectorAdd( point, maxs, boxMaxs ); + VectorAdd(point, mins, boxMins); + VectorAdd(point, maxs, boxMaxs); - if(boxMaxs[0]>boundsMaxs[0]) + if (boxMaxs[0] > boundsMaxs[0]) return qfalse; - if(boxMaxs[1]>boundsMaxs[1]) + if (boxMaxs[1] > boundsMaxs[1]) return qfalse; - if(boxMaxs[2]>boundsMaxs[2]) + if (boxMaxs[2] > boundsMaxs[2]) return qfalse; - if(boxMins[0]currentAngles ); - VectorCopy( angles, ent->s.angles ); - VectorCopy( angles, ent->s.apos.trBase ); +void G_SetAngles(gentity_t *ent, const vec3_t angles) { + VectorCopy(angles, ent->currentAngles); + VectorCopy(angles, ent->s.angles); + VectorCopy(angles, ent->s.apos.trBase); } -qboolean G_ClearTrace( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask ) -{ - static trace_t tr; +qboolean G_ClearTrace(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int ignore, int clipmask) { + static trace_t tr; - gi.trace( &tr, start, mins, maxs, end, ignore, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, start, mins, maxs, end, ignore, clipmask, G2_NOCOLLIDE, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 1.0 ) - { + if (tr.allsolid || tr.startsolid || tr.fraction < 1.0) { return qfalse; } return qtrue; } -extern void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int radius); -void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteornot) -{ +extern void CG_TestLine(vec3_t start, vec3_t end, int time, unsigned int color, int radius); +void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteornot) { /* gentity_t *tent = G_TempEntity( A, EV_DEBUG_LINE ); VectorCopy(B, tent->s.origin2 ); @@ -1441,70 +1297,58 @@ void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteorn tent->freeAfterEvent = deleteornot; */ - CG_TestLine( A, B, duration, color, 1 ); + CG_TestLine(A, B, duration, color, 1); } -qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ) -{ - trace_t tr; - vec3_t start, end; +qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask) { + trace_t tr; + vec3_t start, end; - VectorCopy( point, start ); + VectorCopy(point, start); - for ( int i = 0; i < 3; i++ ) - { - VectorCopy( start, end ); + for (int i = 0; i < 3; i++) { + VectorCopy(start, end); end[i] += mins[i]; - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { - VectorCopy( start, end ); - end[i] += maxs[i]-(mins[i]*tr.fraction); - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + if (tr.fraction < 1.0) { + VectorCopy(start, end); + end[i] += maxs[i] - (mins[i] * tr.fraction); + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { + if (tr.fraction < 1.0) { return qfalse; } - VectorCopy( end, start ); + VectorCopy(end, start); } } - //expanded it, now see if it's all clear - gi.trace( &tr, start, mins, maxs, start, ignore, clipmask, G2_NOCOLLIDE, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + // expanded it, now see if it's all clear + gi.trace(&tr, start, mins, maxs, start, ignore, clipmask, G2_NOCOLLIDE, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - VectorCopy( start, point ); + VectorCopy(start, point); return qtrue; } /* Ghoul2 Insert Start */ -void removeBoltSurface( gentity_t *ent) -{ - gentity_t *hitEnt = &g_entities[ent->cantHitEnemyCounter]; +void removeBoltSurface(gentity_t *ent) { + gentity_t *hitEnt = &g_entities[ent->cantHitEnemyCounter]; // check first to be sure the bolt is still there on the model - if ((hitEnt->ghoul2.size() > ent->damage) && - (hitEnt->ghoul2[ent->damage].mModelindex != -1) && - ((int)hitEnt->ghoul2[ent->damage].mSlist.size() > ent->aimDebounceTime) && - (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].surface != -1) && - (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].offFlags == G2SURFACEFLAG_GENERATED)) - { + if ((hitEnt->ghoul2.size() > ent->damage) && (hitEnt->ghoul2[ent->damage].mModelindex != -1) && + ((int)hitEnt->ghoul2[ent->damage].mSlist.size() > ent->aimDebounceTime) && (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].surface != -1) && + (hitEnt->ghoul2[ent->damage].mSlist[ent->aimDebounceTime].offFlags == G2SURFACEFLAG_GENERATED)) { // remove the bolt gi.G2API_RemoveBolt(&hitEnt->ghoul2[ent->damage], ent->attackDebounceTime); // now remove a surface if there is one - if (ent->aimDebounceTime != -1) - { + if (ent->aimDebounceTime != -1) { gi.G2API_RemoveSurface(&hitEnt->ghoul2[ent->damage], ent->aimDebounceTime); } } @@ -1512,9 +1356,9 @@ void removeBoltSurface( gentity_t *ent) G_FreeEntity(ent); } -void G_SetBoltSurfaceRemoval( const int entNum, const int modelIndex, const int boltIndex, const int surfaceIndex , float duration ) { - gentity_t *e; - vec3_t snapped = {0,0,0}; +void G_SetBoltSurfaceRemoval(const int entNum, const int modelIndex, const int boltIndex, const int surfaceIndex, float duration) { + gentity_t *e; + vec3_t snapped = {0, 0, 0}; e = G_Spawn(); @@ -1524,17 +1368,15 @@ void G_SetBoltSurfaceRemoval( const int entNum, const int modelIndex, const int e->attackDebounceTime = boltIndex; e->aimDebounceTime = surfaceIndex; - G_SetOrigin( e, snapped ); + G_SetOrigin(e, snapped); // find cluster for PVS - gi.linkentity( e ); + gi.linkentity(e); e->nextthink = level.time + duration; e->e_ThinkFunc = thinkF_removeBoltSurface; - } /* Ghoul2 Insert End */ - diff --git a/codeJK2/game/g_weapon.cpp b/codeJK2/game/g_weapon.cpp index 4fb25bbf22..affff77078 100644 --- a/codeJK2/game/g_weapon.cpp +++ b/codeJK2/game/g_weapon.cpp @@ -32,57 +32,54 @@ along with this program; if not, see . #include "b_local.h" #include "w_local.h" -vec3_t wpFwd, wpVright, wpUp; -vec3_t wpMuzzle; +vec3_t wpFwd, wpVright, wpUp; +vec3_t wpMuzzle; gentity_t *ent_list[MAX_GENTITIES]; // some naughty little things that are used cg side int g_rocketLockEntNum = ENTITYNUM_NONE; int g_rocketLockTime = 0; -int g_rocketSlackTime = 0; +int g_rocketSlackTime = 0; // Weapon Helper Functions //----------------------------------------------------------------------------- -void WP_TraceSetStart( const gentity_t *ent, vec3_t start, const vec3_t mins, const vec3_t maxs ) +void WP_TraceSetStart(const gentity_t *ent, vec3_t start, const vec3_t mins, const vec3_t maxs) //----------------------------------------------------------------------------- { - //make sure our start point isn't on the other side of a wall - trace_t tr; - vec3_t entMins, newstart; - vec3_t entMaxs; + // make sure our start point isn't on the other side of a wall + trace_t tr; + vec3_t entMins, newstart; + vec3_t entMaxs; - VectorSet( entMaxs, 5, 5, 5 ); - VectorScale( entMaxs, -1, entMins ); + VectorSet(entMaxs, 5, 5, 5); + VectorScale(entMaxs, -1, entMins); - if ( !ent->client ) - { + if (!ent->client) { return; } - VectorCopy( ent->currentOrigin, newstart ); + VectorCopy(ent->currentOrigin, newstart); newstart[2] = start[2]; // force newstart to be on the same plane as the wpMuzzle ( start ) - gi.trace( &tr, newstart, entMins, entMaxs, start, ent->s.number, MASK_SOLID|CONTENTS_SHOTCLIP, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, newstart, entMins, entMaxs, start, ent->s.number, MASK_SOLID | CONTENTS_SHOTCLIP, G2_NOCOLLIDE, 0); - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { // there is a problem here.. return; } - if ( tr.fraction < 1.0f ) - { - VectorCopy( tr.endpos, start ); + if (tr.fraction < 1.0f) { + VectorCopy(tr.endpos, start); } } //----------------------------------------------------------------------------- -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire ) +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire) //----------------------------------------------------------------------------- { - gentity_t *missile; + gentity_t *missile; missile = G_Spawn(); @@ -94,80 +91,73 @@ gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t missile->alt_fire = altFire; missile->s.pos.trType = TR_LINEAR; - missile->s.pos.trTime = level.time;// - 10; // move a bit on the very first frame - VectorCopy( org, missile->s.pos.trBase ); - VectorScale( dir, vel, missile->s.pos.trDelta ); - VectorCopy( org, missile->currentOrigin); - gi.linkentity( missile ); + missile->s.pos.trTime = level.time; // - 10; // move a bit on the very first frame + VectorCopy(org, missile->s.pos.trBase); + VectorScale(dir, vel, missile->s.pos.trDelta); + VectorCopy(org, missile->currentOrigin); + gi.linkentity(missile); return missile; } - //----------------------------------------------------------------------------- -void WP_Stick( gentity_t *missile, trace_t *trace, float fudge_distance ) +void WP_Stick(gentity_t *missile, trace_t *trace, float fudge_distance) //----------------------------------------------------------------------------- { vec3_t org, ang; // not moving or rotating missile->s.pos.trType = TR_STATIONARY; - VectorClear( missile->s.pos.trDelta ); - VectorClear( missile->s.apos.trDelta ); + VectorClear(missile->s.pos.trDelta); + VectorClear(missile->s.apos.trDelta); // so we don't stick into the wall - VectorMA( trace->endpos, fudge_distance, trace->plane.normal, org ); - G_SetOrigin( missile, org ); + VectorMA(trace->endpos, fudge_distance, trace->plane.normal, org); + G_SetOrigin(missile, org); - vectoangles( trace->plane.normal, ang ); - G_SetAngles( missile, ang ); + vectoangles(trace->plane.normal, ang); + G_SetAngles(missile, ang); // I guess explode death wants me as the normal? -// VectorCopy( trace->plane.normal, missile->pos1 ); - gi.linkentity( missile ); + // VectorCopy( trace->plane.normal, missile->pos1 ); + gi.linkentity(missile); } // This version shares is in the thinkFunc format //----------------------------------------------------------------------------- -void WP_Explode( gentity_t *self ) +void WP_Explode(gentity_t *self) //----------------------------------------------------------------------------- { - gentity_t *attacker = self; - vec3_t wpFwd; + gentity_t *attacker = self; + vec3_t wpFwd; // stop chain reaction runaway loops self->takedamage = qfalse; self->s.loopSound = 0; -// VectorCopy( self->currentOrigin, self->s.pos.trBase ); - AngleVectors( self->s.angles, wpFwd, NULL, NULL ); + // VectorCopy( self->currentOrigin, self->s.pos.trBase ); + AngleVectors(self->s.angles, wpFwd, NULL, NULL); - if ( self->fxID > 0 ) - { - G_PlayEffect( self->fxID, self->currentOrigin, wpFwd ); + if (self->fxID > 0) { + G_PlayEffect(self->fxID, self->currentOrigin, wpFwd); } - if ( self->owner ) - { + if (self->owner) { attacker = self->owner; - } - else if ( self->activator ) - { + } else if (self->activator) { attacker = self->activator; } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_EXPLOSIVE_SPLASH ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_EXPLOSIVE_SPLASH); } - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_SetOrigin( self, self->currentOrigin ); + G_SetOrigin(self, self->currentOrigin); self->nextthink = level.time + 50; self->e_ThinkFunc = thinkF_G_FreeEntity; @@ -175,13 +165,12 @@ void WP_Explode( gentity_t *self ) // We need to have a dieFunc, otherwise G_Damage won't actually make us die. I could modify G_Damage, but that entails too many changes //----------------------------------------------------------------------------- -void WP_ExplosiveDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ) +void WP_ExplosiveDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath, int dFlags, int hitLoc) //----------------------------------------------------------------------------- { self->enemy = attacker; - if ( attacker && !attacker->s.number ) - { + if (attacker && !attacker->s.number) { // less damage when shot by player self->splashDamage /= 3; self->splashRadius /= 3; @@ -189,19 +178,17 @@ void WP_ExplosiveDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker self->s.eFlags &= ~EF_FIRING; // don't draw beam if we are dead - WP_Explode( self ); + WP_Explode(self); } //--------------------------------------------------------- void AddLeanOfs(const gentity_t *const ent, vec3_t point) //--------------------------------------------------------- { - if(ent->client) - { - if(ent->client->ps.leanofs) - { - vec3_t right; - //add leaning offset + if (ent->client) { + if (ent->client->ps.leanofs) { + vec3_t right; + // add leaning offset AngleVectors(ent->client->ps.viewangles, NULL, right, NULL); VectorMA(point, (float)ent->client->ps.leanofs, right, point); } @@ -212,14 +199,12 @@ void AddLeanOfs(const gentity_t *const ent, vec3_t point) void SubtractLeanOfs(const gentity_t *const ent, vec3_t point) //--------------------------------------------------------- { - if(ent->client) - { - if(ent->client->ps.leanofs) - { - vec3_t right; - //add leaning offset - AngleVectors( ent->client->ps.viewangles, NULL, right, NULL ); - VectorMA( point, ent->client->ps.leanofs*-1, right, point ); + if (ent->client) { + if (ent->client->ps.leanofs) { + vec3_t right; + // add leaning offset + AngleVectors(ent->client->ps.viewangles, NULL, right, NULL); + VectorMA(point, ent->client->ps.leanofs * -1, right, point); } } } @@ -228,38 +213,32 @@ void SubtractLeanOfs(const gentity_t *const ent, vec3_t point) void ViewHeightFix(const gentity_t *const ent) //--------------------------------------------------------- { - //FIXME: this is hacky and doesn't need to be here. Was only put here to make up - //for the times a crouch anim would be used but not actually crouching. - //When we start calcing eyepos (SPOT_HEAD) from the tag_eyes, we won't need - //this (or viewheight at all?) - if ( !ent ) + // FIXME: this is hacky and doesn't need to be here. Was only put here to make up + // for the times a crouch anim would be used but not actually crouching. + // When we start calcing eyepos (SPOT_HEAD) from the tag_eyes, we won't need + // this (or viewheight at all?) + if (!ent) return; - if ( !ent->client || !ent->NPC ) + if (!ent->client || !ent->NPC) return; - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) - return;//dead + if (ent->client->ps.stats[STAT_HEALTH] <= 0) + return; // dead - if ( ent->client->ps.legsAnim == BOTH_CROUCH1IDLE || ent->client->ps.legsAnim == BOTH_CROUCH1 || ent->client->ps.legsAnim == BOTH_CROUCH1WALK ) - { - if ( ent->client->ps.viewheight!=ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET ) + if (ent->client->ps.legsAnim == BOTH_CROUCH1IDLE || ent->client->ps.legsAnim == BOTH_CROUCH1 || ent->client->ps.legsAnim == BOTH_CROUCH1WALK) { + if (ent->client->ps.viewheight != ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET) ent->client->ps.viewheight = ent->client->crouchheight + STANDARD_VIEWHEIGHT_OFFSET; - } - else - { - if ( ent->client->ps.viewheight!=ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET ) + } else { + if (ent->client->ps.viewheight != ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET) ent->client->ps.viewheight = ent->client->standheight + STANDARD_VIEWHEIGHT_OFFSET; } } -qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) -{ - if ( mod != MOD_UNKNOWN ) - { - switch( mod ) - { - //standard weapons +qboolean W_AccuracyLoggableWeapon(int weapon, qboolean alt_fire, int mod) { + if (mod != MOD_UNKNOWN) { + switch (mod) { + // standard weapons case MOD_BRYAR: case MOD_BRYAR_ALT: case MOD_BLASTER: @@ -272,30 +251,26 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) case MOD_ROCKET_ALT: return qtrue; break; - //non-alt standard + // non-alt standard case MOD_REPEATER: case MOD_DEMP2: case MOD_FLECHETTE: return qtrue; break; - //emplaced gun + // emplaced gun case MOD_EMPLACED: return qtrue; break; - //atst + // atst case MOD_ENERGY: case MOD_EXPLOSIVE: - if ( weapon == WP_ATST_MAIN || weapon == WP_ATST_SIDE ) - { + if (weapon == WP_ATST_MAIN || weapon == WP_ATST_SIDE) { return qtrue; } break; } - } - else if ( weapon != WP_NONE ) - { - switch( weapon ) - { + } else if (weapon != WP_NONE) { + switch (weapon) { case WP_BRYAR_PISTOL: case WP_BLASTER: case WP_DISRUPTOR: @@ -303,20 +278,19 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) case WP_ROCKET_LAUNCHER: return qtrue; break; - //non-alt standard + // non-alt standard case WP_REPEATER: case WP_DEMP2: case WP_FLECHETTE: - if ( !alt_fire ) - { + if (!alt_fire) { return qtrue; } break; - //emplaced gun + // emplaced gun case WP_EMPLACED_GUN: return qtrue; break; - //atst + // atst case WP_ATST_MAIN: case WP_ATST_SIDE: return qtrue; @@ -331,28 +305,28 @@ qboolean W_AccuracyLoggableWeapon( int weapon, qboolean alt_fire, int mod ) LogAccuracyHit =============== */ -qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) { - if( !target->takedamage ) { +qboolean LogAccuracyHit(gentity_t *target, gentity_t *attacker) { + if (!target->takedamage) { return qfalse; } - if ( target == attacker ) { + if (target == attacker) { return qfalse; } - if( !target->client ) { + if (!target->client) { return qfalse; } - if( !attacker->client ) { + if (!attacker->client) { return qfalse; } - if( target->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (target->client->ps.stats[STAT_HEALTH] <= 0) { return qfalse; } - if ( OnSameTeam( target, attacker ) ) { + if (OnSameTeam(target, attacker)) { return qfalse; } @@ -360,96 +334,83 @@ qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) { } //--------------------------------------------------------- -void CalcMuzzlePoint( gentity_t *const ent, vec3_t wpFwd, vec3_t right, vec3_t wpUp, vec3_t muzzlePoint, float lead_in ) +void CalcMuzzlePoint(gentity_t *const ent, vec3_t wpFwd, vec3_t right, vec3_t wpUp, vec3_t muzzlePoint, float lead_in) //--------------------------------------------------------- { - vec3_t org; - mdxaBone_t boltMatrix; + vec3_t org; + mdxaBone_t boltMatrix; - if( !lead_in ) //&& ent->s.number != 0 - {//Not players or melee - if( ent->client ) - { - if ( ent->client->renderInfo.mPCalcTime >= level.time - FRAMETIME*2 ) - {//Our muzz point was calced no more than 2 frames ago + if (!lead_in) //&& ent->s.number != 0 + { // Not players or melee + if (ent->client) { + if (ent->client->renderInfo.mPCalcTime >= level.time - FRAMETIME * 2) { // Our muzz point was calced no more than 2 frames ago VectorCopy(ent->client->renderInfo.muzzlePoint, muzzlePoint); return; } } } - VectorCopy( ent->currentOrigin, muzzlePoint ); + VectorCopy(ent->currentOrigin, muzzlePoint); - switch( ent->s.weapon ) - { + switch (ent->s.weapon) { case WP_BRYAR_PISTOL: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 16; - VectorMA( muzzlePoint, 28, wpFwd, muzzlePoint ); - VectorMA( muzzlePoint, 6, wpVright, muzzlePoint ); + VectorMA(muzzlePoint, 28, wpFwd, muzzlePoint); + VectorMA(muzzlePoint, 6, wpVright, muzzlePoint); break; case WP_ROCKET_LAUNCHER: case WP_THERMAL: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 2; break; case WP_BLASTER: ViewHeightFix(ent); - muzzlePoint[2] += ent->client->ps.viewheight;//By eyes + muzzlePoint[2] += ent->client->ps.viewheight; // By eyes muzzlePoint[2] -= 1; - if ( ent->s.number == 0 ) - VectorMA( muzzlePoint, 12, wpFwd, muzzlePoint ); // player, don't set this any lower otherwise the projectile will impact immediately when your back is to a wall + if (ent->s.number == 0) + VectorMA(muzzlePoint, 12, wpFwd, + muzzlePoint); // player, don't set this any lower otherwise the projectile will impact immediately when your back is to a wall else - VectorMA( muzzlePoint, 2, wpFwd, muzzlePoint ); // NPC, don't set too far wpFwd otherwise the projectile can go through doors + VectorMA(muzzlePoint, 2, wpFwd, muzzlePoint); // NPC, don't set too far wpFwd otherwise the projectile can go through doors - VectorMA( muzzlePoint, 1, wpVright, muzzlePoint ); + VectorMA(muzzlePoint, 1, wpVright, muzzlePoint); break; case WP_SABER: - if(ent->NPC!=NULL && - (ent->client->ps.torsoAnim == TORSO_WEAPONREADY2 || - ent->client->ps.torsoAnim == BOTH_ATTACK2))//Sniper pose + if (ent->NPC != NULL && (ent->client->ps.torsoAnim == TORSO_WEAPONREADY2 || ent->client->ps.torsoAnim == BOTH_ATTACK2)) // Sniper pose { ViewHeightFix(ent); - wpMuzzle[2] += ent->client->ps.viewheight;//By eyes - } - else - { + wpMuzzle[2] += ent->client->ps.viewheight; // By eyes + } else { muzzlePoint[2] += 16; } - VectorMA( muzzlePoint, 8, wpFwd, muzzlePoint ); - VectorMA( muzzlePoint, 16, wpVright, muzzlePoint ); + VectorMA(muzzlePoint, 8, wpFwd, muzzlePoint); + VectorMA(muzzlePoint, 16, wpVright, muzzlePoint); break; case WP_BOT_LASER: - muzzlePoint[2] -= 16; // + muzzlePoint[2] -= 16; // break; case WP_ATST_MAIN: - if (ent->count > 0) - { + if (ent->count > 0) { ent->count = 0; - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->handLBolt, - &boltMatrix, ent->s.angles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); - } - else - { + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handLBolt, &boltMatrix, ent->s.angles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); + } else { ent->count = 1; - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, - ent->handRBolt, - &boltMatrix, ent->s.angles, ent->s.origin, (cg.time?cg.time:level.time), - NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, ent->handRBolt, &boltMatrix, ent->s.angles, ent->s.origin, (cg.time ? cg.time : level.time), + NULL, ent->s.modelScale); } - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, org); - VectorCopy(org,muzzlePoint); + VectorCopy(org, muzzlePoint); break; } @@ -458,7 +419,7 @@ void CalcMuzzlePoint( gentity_t *const ent, vec3_t wpFwd, vec3_t right, vec3_t w } //--------------------------------------------------------- -void FireWeapon( gentity_t *ent, qboolean alt_fire ) +void FireWeapon(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { float alert = 256; @@ -467,52 +428,36 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) ent->client->ps.persistant[PERS_ACCURACY_SHOTS]++; // set aiming directions - if ( ent->s.weapon == WP_DISRUPTOR && alt_fire ) - { - if ( ent->NPC ) - { - //snipers must use the angles they actually did their shot trace with - AngleVectors( ent->lastAngles, wpFwd, wpVright, wpUp ); + if (ent->s.weapon == WP_DISRUPTOR && alt_fire) { + if (ent->NPC) { + // snipers must use the angles they actually did their shot trace with + AngleVectors(ent->lastAngles, wpFwd, wpVright, wpUp); } - } - else if ( ent->s.weapon == WP_ATST_SIDE || ent->s.weapon == WP_ATST_MAIN ) - { - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; - - VectorCopy( ent->client->renderInfo.muzzlePoint, muzzle1 ); - - if ( !ent->s.number ) - {//player driving an AT-ST - //SIGH... because we can't anticipate alt-fire, must calc muzzle here and now - mdxaBone_t boltMatrix; - int bolt; - - if ( ent->client->ps.weapon == WP_ATST_MAIN ) - {//FIXME: alt_fire should fire both barrels, but slower? - if ( ent->alt_fire ) - { + } else if (ent->s.weapon == WP_ATST_SIDE || ent->s.weapon == WP_ATST_MAIN) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; + + VectorCopy(ent->client->renderInfo.muzzlePoint, muzzle1); + + if (!ent->s.number) { // player driving an AT-ST + // SIGH... because we can't anticipate alt-fire, must calc muzzle here and now + mdxaBone_t boltMatrix; + int bolt; + + if (ent->client->ps.weapon == WP_ATST_MAIN) { // FIXME: alt_fire should fire both barrels, but slower? + if (ent->alt_fire) { bolt = ent->handRBolt; - } - else - { + } else { bolt = ent->handLBolt; } - } - else - {// ATST SIDE weapons - if ( ent->alt_fire ) - { - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], "head_light_blaster_cann" ) ) - {//don't have it! + } else { // ATST SIDE weapons + if (ent->alt_fire) { + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], "head_light_blaster_cann")) { // don't have it! return; } bolt = ent->genericBolt2; - } - else - { - if ( gi.G2API_GetSurfaceRenderStatus( &ent->ghoul2[ent->playerModel], "head_concussion_charger" ) ) - {//don't have it! + } else { + if (gi.G2API_GetSurfaceRenderStatus(&ent->ghoul2[ent->playerModel], "head_concussion_charger")) { // don't have it! return; } bolt = ent->genericBolt1; @@ -520,58 +465,49 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) } vec3_t yawOnlyAngles = {0, ent->currentAngles[YAW], 0}; - if ( ent->currentAngles[YAW] != ent->client->ps.legsYaw ) - { + if (ent->currentAngles[YAW] != ent->client->ps.legsYaw) { yawOnlyAngles[YAW] = ent->client->ps.legsYaw; } - gi.G2API_GetBoltMatrix( ent->ghoul2, ent->playerModel, bolt, &boltMatrix, yawOnlyAngles, ent->currentOrigin, (cg.time?cg.time:level.time), NULL, ent->s.modelScale ); + gi.G2API_GetBoltMatrix(ent->ghoul2, ent->playerModel, bolt, &boltMatrix, yawOnlyAngles, ent->currentOrigin, (cg.time ? cg.time : level.time), NULL, + ent->s.modelScale); // work the matrix axis stuff into the original axis and origins used. - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, ent->client->renderInfo.muzzlePoint ); - gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, ent->client->renderInfo.muzzleDir ); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, ORIGIN, ent->client->renderInfo.muzzlePoint); + gi.G2API_GiveMeVectorFromMatrix(boltMatrix, NEGATIVE_Y, ent->client->renderInfo.muzzleDir); ent->client->renderInfo.mPCalcTime = level.time; - AngleVectors( ent->client->ps.viewangles, wpFwd, wpVright, wpUp ); - //CalcMuzzlePoint( ent, wpFwd, vright, wpUp, wpMuzzle, 0 ); - } - else if ( !ent->enemy ) - {//an NPC with no enemy to auto-aim at - VectorCopy( ent->client->renderInfo.muzzleDir, wpFwd ); - } - else - {//NPC, auto-aim at enemy - CalcEntitySpot( ent->enemy, SPOT_HEAD, enemy_org1 ); + AngleVectors(ent->client->ps.viewangles, wpFwd, wpVright, wpUp); + // CalcMuzzlePoint( ent, wpFwd, vright, wpUp, wpMuzzle, 0 ); + } else if (!ent->enemy) { // an NPC with no enemy to auto-aim at + VectorCopy(ent->client->renderInfo.muzzleDir, wpFwd); + } else { // NPC, auto-aim at enemy + CalcEntitySpot(ent->enemy, SPOT_HEAD, enemy_org1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, wpFwd, wpVright, wpUp); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, wpFwd, wpVright, wpUp); } - } - else if ( ent->s.weapon == WP_BOT_LASER && ent->enemy ) - { - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; + } else if (ent->s.weapon == WP_BOT_LASER && ent->enemy) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; - CalcEntitySpot( ent->enemy, SPOT_HEAD, enemy_org1 ); - CalcEntitySpot( ent, SPOT_WEAPON, muzzle1 ); + CalcEntitySpot(ent->enemy, SPOT_HEAD, enemy_org1); + CalcEntitySpot(ent, SPOT_WEAPON, muzzle1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, wpFwd, wpVright, wpUp); - } - else - { - AngleVectors( ent->client->ps.viewangles, wpFwd, wpVright, wpUp ); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, wpFwd, wpVright, wpUp); + } else { + AngleVectors(ent->client->ps.viewangles, wpFwd, wpVright, wpUp); } ent->alt_fire = alt_fire; - CalcMuzzlePoint ( ent, wpFwd, wpVright, wpUp, wpMuzzle , 0); + CalcMuzzlePoint(ent, wpFwd, wpVright, wpUp, wpMuzzle, 0); // fire the specific weapon - switch( ent->s.weapon ) - { + switch (ent->s.weapon) { // Player weapons //----------------- case WP_SABER: @@ -579,86 +515,80 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) break; case WP_BRYAR_PISTOL: - WP_FireBryarPistol( ent, alt_fire ); + WP_FireBryarPistol(ent, alt_fire); break; case WP_BLASTER: - WP_FireBlaster( ent, alt_fire ); + WP_FireBlaster(ent, alt_fire); break; case WP_DISRUPTOR: alert = 50; // if you want it to alert enemies, remove this - WP_FireDisruptor( ent, alt_fire ); + WP_FireDisruptor(ent, alt_fire); break; case WP_BOWCASTER: - WP_FireBowcaster( ent, alt_fire ); + WP_FireBowcaster(ent, alt_fire); break; case WP_REPEATER: - WP_FireRepeater( ent, alt_fire ); + WP_FireRepeater(ent, alt_fire); break; case WP_DEMP2: - WP_FireDEMP2( ent, alt_fire ); + WP_FireDEMP2(ent, alt_fire); break; case WP_FLECHETTE: - WP_FireFlechette( ent, alt_fire ); + WP_FireFlechette(ent, alt_fire); break; case WP_ROCKET_LAUNCHER: - WP_FireRocket( ent, alt_fire ); + WP_FireRocket(ent, alt_fire); break; case WP_THERMAL: - WP_FireThermalDetonator( ent, alt_fire ); + WP_FireThermalDetonator(ent, alt_fire); break; case WP_TRIP_MINE: alert = 0; // if you want it to alert enemies, remove this - WP_PlaceLaserTrap( ent, alt_fire ); + WP_PlaceLaserTrap(ent, alt_fire); break; case WP_DET_PACK: alert = 0; // if you want it to alert enemies, remove this - WP_FireDetPack( ent, alt_fire ); + WP_FireDetPack(ent, alt_fire); break; case WP_BOT_LASER: - WP_BotLaser( ent ); + WP_BotLaser(ent); break; case WP_EMPLACED_GUN: // doesn't care about whether it's alt-fire or not. We can do an alt-fire if needed - WP_EmplacedFire( ent ); + WP_EmplacedFire(ent); break; case WP_MELEE: alert = 0; // if you want it to alert enemies, remove this - WP_Melee( ent ); + WP_Melee(ent); break; case WP_ATST_MAIN: - WP_ATSTMainFire( ent ); + WP_ATSTMainFire(ent); break; case WP_ATST_SIDE: // TEMP - if ( alt_fire ) - { -// WP_FireRocket( ent, qfalse ); + if (alt_fire) { + // WP_FireRocket( ent, qfalse ); WP_ATSTSideAltFire(ent); - } - else - { - if ( ent->s.number == 0 && ent->client->ps.vehicleModel ) - { - WP_ATSTMainFire( ent ); - } - else - { + } else { + if (ent->s.number == 0 && ent->client->ps.vehicleModel) { + WP_ATSTMainFire(ent); + } else { WP_ATSTSideFire(ent); } } @@ -666,27 +596,24 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) case WP_TIE_FIGHTER: // TEMP - WP_EmplacedFire( ent ); + WP_EmplacedFire(ent); break; case WP_RAPID_FIRE_CONC: // TEMP - if ( alt_fire ) - { - WP_FireRepeater( ent, alt_fire ); - } - else - { - WP_EmplacedFire( ent ); + if (alt_fire) { + WP_FireRepeater(ent, alt_fire); + } else { + WP_EmplacedFire(ent); } break; case WP_STUN_BATON: - WP_FireStunBaton( ent, alt_fire ); + WP_FireStunBaton(ent, alt_fire); break; - case WP_BLASTER_PISTOL: // enemy version - WP_FireBryarPistol( ent, qfalse ); // never an alt-fire? + case WP_BLASTER_PISTOL: // enemy version + WP_FireBryarPistol(ent, qfalse); // never an alt-fire? break; default: @@ -694,28 +621,24 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) break; } - if ( !ent->s.number ) - { - if ( ent->s.weapon == WP_FLECHETTE || (ent->s.weapon == WP_BOWCASTER && !alt_fire) ) - {//these can fire multiple shots, count them individually within the firing functions - } - else if ( W_AccuracyLoggableWeapon( ent->s.weapon, alt_fire, MOD_UNKNOWN ) ) - { + if (!ent->s.number) { + if (ent->s.weapon == WP_FLECHETTE || + (ent->s.weapon == WP_BOWCASTER && !alt_fire)) { // these can fire multiple shots, count them individually within the firing functions + } else if (W_AccuracyLoggableWeapon(ent->s.weapon, alt_fire, MOD_UNKNOWN)) { ent->client->sess.missionStats.shotsFired++; } } // We should probably just use this as a default behavior, in special cases, just set alert to false. - if ( ent->s.number == 0 && alert > 0 ) - { - AddSoundEvent( ent, wpMuzzle, alert, AEL_DISCOVERED ); - AddSightEvent( ent, wpMuzzle, alert*2, AEL_DISCOVERED, 20 ); + if (ent->s.number == 0 && alert > 0) { + AddSoundEvent(ent, wpMuzzle, alert, AEL_DISCOVERED); + AddSightEvent(ent, wpMuzzle, alert * 2, AEL_DISCOVERED, 20); } } // spawnflag -#define EMPLACED_INACTIVE 1 -#define EMPLACED_FACING 2 -#define EMPLACED_VULNERABLE 4 +#define EMPLACED_INACTIVE 1 +#define EMPLACED_FACING 2 +#define EMPLACED_VULNERABLE 4 //---------------------------------------------------------- @@ -734,120 +657,106 @@ void FireWeapon( gentity_t *ent, qboolean alt_fire ) */ //---------------------------------------------------------- -void emplaced_gun_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ +void emplaced_gun_use(gentity_t *self, gentity_t *other, gentity_t *activator) { vec3_t fwd1, fwd2; - if ( self->health <= 0 ) - { + if (self->health <= 0) { // can't use a dead gun. return; } - if ( self->svFlags & SVF_INACTIVE ) - { + if (self->svFlags & SVF_INACTIVE) { return; // can't use inactive gun } - if ( !activator->client ) - { + if (!activator->client) { return; // only a client can use it. } - if ( self->activator ) - { + if (self->activator) { // someone is already in the gun. return; } // We'll just let the designers duke this one out....I mean, as to whether they even want to limit such a thing. - if ( self->spawnflags & EMPLACED_FACING ) - { + if (self->spawnflags & EMPLACED_FACING) { // Let's get some direction vectors for the users - AngleVectors( activator->client->ps.viewangles, fwd1, NULL, NULL ); + AngleVectors(activator->client->ps.viewangles, fwd1, NULL, NULL); // Get the guns direction vector - AngleVectors( self->pos1, fwd2, NULL, NULL ); + AngleVectors(self->pos1, fwd2, NULL, NULL); - float dot = DotProduct( fwd1, fwd2 ); + float dot = DotProduct(fwd1, fwd2); // Must be reasonably facing the way the gun points ( 90 degrees or so ), otherwise we don't allow to use it. - if ( dot < 0.0f ) - { + if (dot < 0.0f) { return; } } // don't allow using it again for half a second - if ( self->delay + 500 < level.time ) - { - int oldWeapon = activator->s.weapon; + if (self->delay + 500 < level.time) { + int oldWeapon = activator->s.weapon; - if ( oldWeapon == WP_SABER ) - { + if (oldWeapon == WP_SABER) { self->alt_fire = activator->client->ps.saberActive; } // swap the users weapon with the emplaced gun and add the ammo the gun has to the player activator->client->ps.weapon = self->s.weapon; - Add_Ammo( activator, WP_EMPLACED_GUN, self->count ); - activator->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_EMPLACED_GUN ); + Add_Ammo(activator, WP_EMPLACED_GUN, self->count); + activator->client->ps.stats[STAT_WEAPONS] |= (1 << WP_EMPLACED_GUN); // Allow us to point from one to the other activator->owner = self; // kind of dumb, but when we are locked to the weapon, we are owned by it. self->activator = activator; - if ( activator->weaponModel >= 0 ) - { + if (activator->weaponModel >= 0) { // rip that gun out of their hands.... - gi.G2API_RemoveGhoul2Model( activator->ghoul2, activator->weaponModel ); + gi.G2API_RemoveGhoul2Model(activator->ghoul2, activator->weaponModel); activator->weaponModel = -1; } -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - if ( activator->NPC ) - { - if ( activator->weaponModel >= 0 ) - { + extern void ChangeWeapon(gentity_t * ent, int newWeapon); + if (activator->NPC) { + if (activator->weaponModel >= 0) { // rip that gun out of their hands.... - gi.G2API_RemoveGhoul2Model( activator->ghoul2, activator->weaponModel ); + gi.G2API_RemoveGhoul2Model(activator->ghoul2, activator->weaponModel); activator->weaponModel = -1; -// Doesn't work? -// activator->maxs[2] += 35; // make it so you can potentially shoot their head -// activator->s.radius += 10; // increase ghoul radius so we can collide with the enemy more accurately -// gi.linkentity( activator ); + // Doesn't work? + // activator->maxs[2] += 35; // make it so you can potentially shoot their head + // activator->s.radius += 10; // increase ghoul radius so we can collide with the enemy more accurately + // gi.linkentity( activator ); } - ChangeWeapon( activator, WP_EMPLACED_GUN ); - } - else if ( activator->s.number == 0 ) - { + ChangeWeapon(activator, WP_EMPLACED_GUN); + } else if (activator->s.number == 0) { // we don't want for it to draw the weapon select stuff cg.weaponSelect = WP_EMPLACED_GUN; - CG_CenterPrint( "@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95 ); + CG_CenterPrint("@INGAME_EXIT_VIEW", SCREEN_HEIGHT * 0.95); } - // Since we move the activator inside of the gun, we reserve a solid spot where they were standing in order to be able to get back out without being in solid - if ( self->nextTrain ) - {//you never know - G_FreeEntity( self->nextTrain ); + // Since we move the activator inside of the gun, we reserve a solid spot where they were standing in order to be able to get back out without being in + // solid + if (self->nextTrain) { // you never know + G_FreeEntity(self->nextTrain); } self->nextTrain = G_Spawn(); - //self->nextTrain->classname = "emp_placeholder"; - self->nextTrain->contents = CONTENTS_MONSTERCLIP|CONTENTS_PLAYERCLIP;//hmm... playerclip too now that we're doing it for NPCs? - G_SetOrigin( self->nextTrain, activator->client->ps.origin ); - VectorCopy( activator->mins, self->nextTrain->mins ); - VectorCopy( activator->maxs, self->nextTrain->maxs ); - gi.linkentity( self->nextTrain ); + // self->nextTrain->classname = "emp_placeholder"; + self->nextTrain->contents = CONTENTS_MONSTERCLIP | CONTENTS_PLAYERCLIP; // hmm... playerclip too now that we're doing it for NPCs? + G_SetOrigin(self->nextTrain, activator->client->ps.origin); + VectorCopy(activator->mins, self->nextTrain->mins); + VectorCopy(activator->maxs, self->nextTrain->maxs); + gi.linkentity(self->nextTrain); - //need to inflate the activator's mins/maxs since the gunsit anim puts them outside of their bbox - VectorSet( activator->mins, -24, -24, -24 ); - VectorSet( activator->maxs, 24, 24, 40 ); + // need to inflate the activator's mins/maxs since the gunsit anim puts them outside of their bbox + VectorSet(activator->mins, -24, -24, -24); + VectorSet(activator->maxs, 24, 24, 40); // Move the activator into the center of the gun. For NPC's the only way the can get out of the gun is to die. - VectorCopy( self->s.origin, activator->client->ps.origin ); + VectorCopy(self->s.origin, activator->client->ps.origin); activator->client->ps.origin[2] += 30; // move them up so they aren't standing in the floor - gi.linkentity( activator ); + gi.linkentity(activator); // the gun will track which weapon we used to have self->s.weapon = oldWeapon; @@ -864,53 +773,45 @@ extern void ChangeWeapon( gentity_t *ent, int newWeapon ); // FIXME: don't do this, we'll try and actually put the player in this beast // move the player to the center of the gun -// activator->contents = 0; -// VectorCopy( self->currentOrigin, activator->client->ps.origin ); + // activator->contents = 0; + // VectorCopy( self->currentOrigin, activator->client->ps.origin ); - SetClientViewAngle( activator, self->pos1 ); + SetClientViewAngle(activator, self->pos1); - //FIXME: should really wait a bit after spawn and get this just once? - self->waypoint = NAV_FindClosestWaypointForEnt( self, WAYPOINT_NONE ); + // FIXME: should really wait a bit after spawn and get this just once? + self->waypoint = NAV_FindClosestWaypointForEnt(self, WAYPOINT_NONE); #ifdef _DEBUG - if ( self->waypoint == -1 ) - { - gi.Printf( S_COLOR_RED"ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin) ); + if (self->waypoint == -1) { + gi.Printf(S_COLOR_RED "ERROR: no waypoint for emplaced_gun %s at %s\n", self->targetname, vtos(self->currentOrigin)); } #endif - G_Sound( self, G_SoundIndex( "sound/weapons/emplaced/emplaced_mount.mp3" )); + G_Sound(self, G_SoundIndex("sound/weapons/emplaced/emplaced_mount.mp3")); } } //---------------------------------------------------------- -void emplaced_gun_pain( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod,int hitLoc ) -{ - if ( self->health <= 0 ) - { +void emplaced_gun_pain(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, vec3_t point, int damage, int mod, int hitLoc) { + if (self->health <= 0) { // play pain effect? - } - else - { - if ( self->paintarget ) - { - G_UseTargets2( self, self->activator, self->paintarget ); + } else { + if (self->paintarget) { + G_UseTargets2(self, self->activator, self->paintarget); } // Don't do script if dead - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); } } //---------------------------------------------------------- -void emplaced_blow( gentity_t *ent ) -{ +void emplaced_blow(gentity_t *ent) { ent->e_DieFunc = dieF_NULL; - emplaced_gun_die( ent, ent->lastEnemy, ent->lastEnemy, 0, MOD_UNKNOWN ); + emplaced_gun_die(ent, ent->lastEnemy, ent->lastEnemy, 0, MOD_UNKNOWN); } //---------------------------------------------------------- -void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void emplaced_gun_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { vec3_t org; // turn off any firing animations it may have been doing @@ -918,28 +819,25 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->svFlags &= ~SVF_ANIMATING; self->health = 0; -// self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon + // self->s.weapon = WP_EMPLACED_GUN; // we need to be able to switch back to the old weapon self->takedamage = qfalse; self->lastEnemy = attacker; // we defer explosion so the player has time to get out - if ( self->e_DieFunc ) - { + if (self->e_DieFunc) { self->e_ThinkFunc = thinkF_emplaced_blow; self->nextthink = level.time + 3000; // don't blow for a couple of seconds return; } - if ( self->activator && self->activator->client ) - { - if ( self->activator->NPC ) - { + if (self->activator && self->activator->client) { + if (self->activator->NPC) { vec3_t right; // radius damage seems to throw them, but add an extra bit to throw them away from the weapon - AngleVectors( self->currentAngles, NULL, right, NULL ); - VectorMA( self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity ); + AngleVectors(self->currentAngles, NULL, right, NULL); + VectorMA(self->activator->client->ps.velocity, 140, right, self->activator->client->ps.velocity); self->activator->client->ps.velocity[2] = -100; // kill them @@ -954,12 +852,11 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->e_PainFunc = painF_NULL; self->e_ThinkFunc = thinkF_NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_RadiusDamage( self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN ); + G_RadiusDamage(self->currentOrigin, self, self->splashDamage, self->splashRadius, self, MOD_UNKNOWN); // when the gun is dead, add some ugliness to it. vec3_t ugly; @@ -967,61 +864,58 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke ugly[YAW] = 4; ugly[PITCH] = self->lastAngles[PITCH] * 0.8f + Q_flrand(-1.0f, 1.0f) * 6; ugly[ROLL] = Q_flrand(-1.0f, 1.0f) * 7; - gi.G2API_SetBoneAnglesIndex( &self->ghoul2[self->playerModel], self->lowerLumbarBone, ugly, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0 ); + gi.G2API_SetBoneAnglesIndex(&self->ghoul2[self->playerModel], self->lowerLumbarBone, ugly, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, + 0, 0); - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 20; - G_PlayEffect( "emplaced/explode", org ); + G_PlayEffect("emplaced/explode", org); // create some persistent smoke by using a dynamically created fx runner gentity_t *ent = G_Spawn(); - if ( ent ) - { + if (ent) { ent->delay = 200; ent->random = 100; - ent->fxID = G_EffectIndex( "emplaced/dead_smoke" ); + ent->fxID = G_EffectIndex("emplaced/dead_smoke"); ent->e_ThinkFunc = thinkF_fx_runner_think; ent->nextthink = level.time + 50; // move up above the gun origin - VectorCopy( self->currentOrigin, org ); + VectorCopy(self->currentOrigin, org); org[2] += 35; - G_SetOrigin( ent, org ); - VectorCopy( org, ent->s.origin ); + G_SetOrigin(ent, org); + VectorCopy(org, ent->s.origin); - VectorSet( ent->s.angles, -90, 0, 0 ); // up - G_SetAngles( ent, ent->s.angles ); + VectorSet(ent->s.angles, -90, 0, 0); // up + G_SetAngles(ent, ent->s.angles); - gi.linkentity( ent ); + gi.linkentity(ent); } - G_ActivateBehavior( self, BSET_DEATH ); + G_ActivateBehavior(self, BSET_DEATH); } //---------------------------------------------------------- -void SP_emplaced_gun( gentity_t *ent ) -{ +void SP_emplaced_gun(gentity_t *ent) { char name[] = "models/map_objects/imp_mine/turret_chair.glm"; ent->svFlags |= SVF_PLAYER_USABLE; - ent->contents = CONTENTS_BODY;//CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP;//CONTENTS_SOLID; + ent->contents = CONTENTS_BODY; // CONTENTS_SHOTCLIP|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP;//CONTENTS_SOLID; - if ( ent->spawnflags & EMPLACED_INACTIVE ) - { + if (ent->spawnflags & EMPLACED_INACTIVE) { ent->svFlags |= SVF_INACTIVE; } - VectorSet( ent->mins, -30, -30, -5 ); - VectorSet( ent->maxs, 30, 30, 60 ); + VectorSet(ent->mins, -30, -30, -5); + VectorSet(ent->maxs, 30, 30, 60); ent->takedamage = qtrue; - if ( !( ent->spawnflags & EMPLACED_VULNERABLE )) - { + if (!(ent->spawnflags & EMPLACED_VULNERABLE)) { ent->flags |= FL_GODMODE; } @@ -1030,48 +924,48 @@ void SP_emplaced_gun( gentity_t *ent ) ent->e_ThinkFunc = thinkF_NULL; ent->e_PainFunc = painF_emplaced_gun_pain; - ent->e_DieFunc = dieF_emplaced_gun_die; + ent->e_DieFunc = dieF_emplaced_gun_die; - G_EffectIndex( "emplaced/explode" ); - G_EffectIndex( "emplaced/dead_smoke" ); + G_EffectIndex("emplaced/explode"); + G_EffectIndex("emplaced/dead_smoke"); - G_SoundIndex( "sound/weapons/emplaced/emplaced_mount.mp3" ); - G_SoundIndex( "sound/weapons/emplaced/emplaced_dismount.mp3" ); - G_SoundIndex( "sound/weapons/emplaced/emplaced_move_lp.wav" ); + G_SoundIndex("sound/weapons/emplaced/emplaced_mount.mp3"); + G_SoundIndex("sound/weapons/emplaced/emplaced_dismount.mp3"); + G_SoundIndex("sound/weapons/emplaced/emplaced_move_lp.wav"); // Set up our defaults and override with custom amounts as necessary - G_SpawnInt( "count", "999", &ent->count ); - G_SpawnInt( "health", "250", &ent->health ); - G_SpawnInt( "splashDamage", "80", &ent->splashDamage ); - G_SpawnInt( "splashRadius", "128", &ent->splashRadius ); - G_SpawnFloat( "delay", "200", &ent->random ); // NOTE: spawning into a different field!! - G_SpawnFloat( "wait", "800", &ent->wait ); + G_SpawnInt("count", "999", &ent->count); + G_SpawnInt("health", "250", &ent->health); + G_SpawnInt("splashDamage", "80", &ent->splashDamage); + G_SpawnInt("splashRadius", "128", &ent->splashRadius); + G_SpawnFloat("delay", "200", &ent->random); // NOTE: spawning into a different field!! + G_SpawnFloat("wait", "800", &ent->wait); ent->max_health = ent->health; ent->dflags |= DAMAGE_CUSTOM_HUD; // dumb, but we draw a custom hud - ent->s.modelindex = G_ModelIndex( name ); - ent->playerModel = gi.G2API_InitGhoul2Model( ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + ent->s.modelindex = G_ModelIndex(name); + ent->playerModel = gi.G2API_InitGhoul2Model(ent->ghoul2, name, ent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); // Activate our tags and bones - ent->headBolt = gi.G2API_AddBolt( &ent->ghoul2[0], "*seat" ); - ent->handLBolt = gi.G2API_AddBolt( &ent->ghoul2[0], "*flash01" ); - ent->handRBolt = gi.G2API_AddBolt( &ent->ghoul2[0], "*flash02" ); - ent->rootBone = gi.G2API_GetBoneIndex( &ent->ghoul2[ent->playerModel], "base_bone", qtrue ); - ent->lowerLumbarBone = gi.G2API_GetBoneIndex( &ent->ghoul2[0], "swivel_bone", qtrue ); - gi.G2API_SetBoneAngles( &ent->ghoul2[0], "swivel_bone", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); - - RegisterItem( FindItemForWeapon( WP_EMPLACED_GUN )); + ent->headBolt = gi.G2API_AddBolt(&ent->ghoul2[0], "*seat"); + ent->handLBolt = gi.G2API_AddBolt(&ent->ghoul2[0], "*flash01"); + ent->handRBolt = gi.G2API_AddBolt(&ent->ghoul2[0], "*flash02"); + ent->rootBone = gi.G2API_GetBoneIndex(&ent->ghoul2[ent->playerModel], "base_bone", qtrue); + ent->lowerLumbarBone = gi.G2API_GetBoneIndex(&ent->ghoul2[0], "swivel_bone", qtrue); + gi.G2API_SetBoneAngles(&ent->ghoul2[0], "swivel_bone", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 0, 0); + + RegisterItem(FindItemForWeapon(WP_EMPLACED_GUN)); ent->s.weapon = WP_EMPLACED_GUN; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - VectorCopy( ent->s.angles, ent->lastAngles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + VectorCopy(ent->s.angles, ent->lastAngles); // store base angles for later - VectorCopy( ent->s.angles, ent->pos1 ); + VectorCopy(ent->s.angles, ent->pos1); ent->e_UseFunc = useF_emplaced_gun_use; - gi.linkentity (ent); + gi.linkentity(ent); } diff --git a/codeJK2/game/g_weaponLoad.cpp b/codeJK2/game/g_weaponLoad.cpp index 034a7b82ef..473401125e 100644 --- a/codeJK2/game/g_weaponLoad.cpp +++ b/codeJK2/game/g_weaponLoad.cpp @@ -26,104 +26,101 @@ along with this program; if not, see . #include "g_local.h" typedef struct { - const char *name; - void (*func)(centity_t *cent, const struct weaponInfo_s *weapon ); + const char *name; + void (*func)(centity_t *cent, const struct weaponInfo_s *weapon); } func_t; // Bryar -void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BryarProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_BryarAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Blaster -void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BlasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_BlasterAltFireThink(centity_t *cent, const struct weaponInfo_s *weapon); // Bowcaster -void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_BowcasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Heavy Repeater -void FX_RepeaterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_RepeaterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_RepeaterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_RepeaterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // DEMP2 -void FX_DEMP2_ProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_DEMP2_AltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_DEMP2_ProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_DEMP2_AltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Golan Arms Flechette -void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_FlechetteAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_FlechetteProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_FlechetteAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Personal Rocket Launcher -void FX_RocketProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_RocketAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_RocketProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_RocketAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Emplaced weapon -void FX_EmplacedProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_EmplacedProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Turret weapon -void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_TurretProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // ATST Main weapon -void FX_ATSTMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_ATSTMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // ATST Side weapons -void FX_ATSTSideMainProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); -void FX_ATSTSideAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ); +void FX_ATSTSideMainProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); +void FX_ATSTSideAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon); // Table used to attach an extern missile function string to the actual cgame function -func_t funcs[] = { - {"bryar_func", FX_BryarProjectileThink}, - {"bryar_alt_func", FX_BryarAltProjectileThink}, - {"blaster_func", FX_BlasterProjectileThink}, - {"blaster_alt_func", FX_BlasterAltFireThink}, - {"bowcaster_func", FX_BowcasterProjectileThink}, - {"repeater_func", FX_RepeaterProjectileThink}, - {"repeater_alt_func", FX_RepeaterAltProjectileThink}, - {"demp2_func", FX_DEMP2_ProjectileThink}, - {"demp2_alt_func", FX_DEMP2_AltProjectileThink}, - {"flechette_func", FX_FlechetteProjectileThink}, - {"flechette_alt_func", FX_FlechetteAltProjectileThink}, - {"rocket_func", FX_RocketProjectileThink}, - {"rocket_alt_func", FX_RocketAltProjectileThink}, - {"emplaced_func", FX_EmplacedProjectileThink}, - {"turret_func", FX_TurretProjectileThink}, - {"atstmain_func", FX_ATSTMainProjectileThink}, - {"atst_side_alt_func", FX_ATSTSideAltProjectileThink}, - {"atst_side_main_func", FX_ATSTSideMainProjectileThink}, - {NULL, NULL} -}; - -//qboolean COM_ParseInt( char **data, int *i ); -//qboolean COM_ParseString( char **data, char **s ); -//qboolean COM_ParseFloat( char **data, float *f ); - -struct wpnParms_s -{ - int weaponNum; // Current weapon number - int ammoNum; +func_t funcs[] = {{"bryar_func", FX_BryarProjectileThink}, + {"bryar_alt_func", FX_BryarAltProjectileThink}, + {"blaster_func", FX_BlasterProjectileThink}, + {"blaster_alt_func", FX_BlasterAltFireThink}, + {"bowcaster_func", FX_BowcasterProjectileThink}, + {"repeater_func", FX_RepeaterProjectileThink}, + {"repeater_alt_func", FX_RepeaterAltProjectileThink}, + {"demp2_func", FX_DEMP2_ProjectileThink}, + {"demp2_alt_func", FX_DEMP2_AltProjectileThink}, + {"flechette_func", FX_FlechetteProjectileThink}, + {"flechette_alt_func", FX_FlechetteAltProjectileThink}, + {"rocket_func", FX_RocketProjectileThink}, + {"rocket_alt_func", FX_RocketAltProjectileThink}, + {"emplaced_func", FX_EmplacedProjectileThink}, + {"turret_func", FX_TurretProjectileThink}, + {"atstmain_func", FX_ATSTMainProjectileThink}, + {"atst_side_alt_func", FX_ATSTSideAltProjectileThink}, + {"atst_side_main_func", FX_ATSTSideMainProjectileThink}, + {NULL, NULL}}; + +// qboolean COM_ParseInt( char **data, int *i ); +// qboolean COM_ParseString( char **data, char **s ); +// qboolean COM_ParseFloat( char **data, float *f ); + +struct wpnParms_s { + int weaponNum; // Current weapon number + int ammoNum; } wpnParms; -void WPN_Ammo (const char **holdBuf); -void WPN_AmmoIcon (const char **holdBuf); -void WPN_AmmoMax (const char **holdBuf); -void WPN_AmmoLowCnt (const char **holdBuf); -void WPN_AmmoType (const char **holdBuf); -void WPN_EnergyPerShot (const char **holdBuf); -void WPN_FireTime (const char **holdBuf); -void WPN_FiringSnd (const char **holdBuf); -void WPN_AltFiringSnd(const char **holdBuf ); -void WPN_StopSnd( const char **holdBuf ); -void WPN_ChargeSnd (const char **holdBuf); -void WPN_AltChargeSnd (const char **holdBuf); -void WPN_SelectSnd (const char **holdBuf); -void WPN_Range (const char **holdBuf); -void WPN_WeaponClass ( const char **holdBuf); -void WPN_WeaponIcon (const char **holdBuf); -void WPN_WeaponModel (const char **holdBuf); -void WPN_WeaponType (const char **holdBuf); -void WPN_AltEnergyPerShot (const char **holdBuf); -void WPN_AltFireTime (const char **holdBuf); -void WPN_AltRange (const char **holdBuf); +void WPN_Ammo(const char **holdBuf); +void WPN_AmmoIcon(const char **holdBuf); +void WPN_AmmoMax(const char **holdBuf); +void WPN_AmmoLowCnt(const char **holdBuf); +void WPN_AmmoType(const char **holdBuf); +void WPN_EnergyPerShot(const char **holdBuf); +void WPN_FireTime(const char **holdBuf); +void WPN_FiringSnd(const char **holdBuf); +void WPN_AltFiringSnd(const char **holdBuf); +void WPN_StopSnd(const char **holdBuf); +void WPN_ChargeSnd(const char **holdBuf); +void WPN_AltChargeSnd(const char **holdBuf); +void WPN_SelectSnd(const char **holdBuf); +void WPN_Range(const char **holdBuf); +void WPN_WeaponClass(const char **holdBuf); +void WPN_WeaponIcon(const char **holdBuf); +void WPN_WeaponModel(const char **holdBuf); +void WPN_WeaponType(const char **holdBuf); +void WPN_AltEnergyPerShot(const char **holdBuf); +void WPN_AltFireTime(const char **holdBuf); +void WPN_AltRange(const char **holdBuf); void WPN_BarrelCount(const char **holdBuf); void WPN_MissileName(const char **holdBuf); void WPN_AltMissileName(const char **holdBuf); @@ -152,376 +149,355 @@ void WPN_AltSplashRadius(const char **holdBuf); // Legacy weapons.dat force fields void WPN_FuncSkip(const char **holdBuf); -typedef struct -{ - const char *parmName; - void (*func)(const char **holdBuf); +typedef struct { + const char *parmName; + void (*func)(const char **holdBuf); } wpnParms_t; // This is used as a fallback for each new field, in case they're using base files --eez const int defaultDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL - BLASTER_DAMAGE, // WP_BLASTER - DISRUPTOR_MAIN_DAMAGE, // WP_DISRUPTOR - BOWCASTER_DAMAGE, // WP_BOWCASTER - REPEATER_DAMAGE, // WP_REPEATER - DEMP2_DAMAGE, // WP_DEMP2 - FLECHETTE_DAMAGE, // WP_FLECHETTE - ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER - TD_DAMAGE, // WP_THERMAL - LT_DAMAGE, // WP_TRIP_MINE - FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - STUN_BATON_DAMAGE, // WP_STUN_BATON - 0, // WP_MELEE // handled by the melee attack function - EMPLACED_DAMAGE, // WP_EMPLACED - BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - ATST_MAIN_DAMAGE, // WP_ATST_MAIN - ATST_SIDE_MAIN_DAMAGE, // WP_ATST_SIDE - EMPLACED_DAMAGE, // WP_TIE_FIGHTER - EMPLACED_DAMAGE, // WP_RAPID_FIRE_CONC - BRYAR_PISTOL_DAMAGE // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL + BLASTER_DAMAGE, // WP_BLASTER + DISRUPTOR_MAIN_DAMAGE, // WP_DISRUPTOR + BOWCASTER_DAMAGE, // WP_BOWCASTER + REPEATER_DAMAGE, // WP_REPEATER + DEMP2_DAMAGE, // WP_DEMP2 + FLECHETTE_DAMAGE, // WP_FLECHETTE + ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER + TD_DAMAGE, // WP_THERMAL + LT_DAMAGE, // WP_TRIP_MINE + FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + STUN_BATON_DAMAGE, // WP_STUN_BATON + 0, // WP_MELEE // handled by the melee attack function + EMPLACED_DAMAGE, // WP_EMPLACED + BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + ATST_MAIN_DAMAGE, // WP_ATST_MAIN + ATST_SIDE_MAIN_DAMAGE, // WP_ATST_SIDE + EMPLACED_DAMAGE, // WP_TIE_FIGHTER + EMPLACED_DAMAGE, // WP_RAPID_FIRE_CONC + BRYAR_PISTOL_DAMAGE // WP_BLASTER_PISTOL }; const int defaultAltDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL - BLASTER_DAMAGE, // WP_BLASTER - DISRUPTOR_ALT_DAMAGE, // WP_DISRUPTOR - BOWCASTER_DAMAGE, // WP_BOWCASTER - REPEATER_ALT_DAMAGE, // WP_REPEATER - DEMP2_ALT_DAMAGE, // WP_DEMP2 - FLECHETTE_ALT_DAMAGE, // WP_FLECHETTE - ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER - TD_ALT_DAMAGE, // WP_THERMAL - LT_DAMAGE, // WP_TRIP_MINE - FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - STUN_BATON_ALT_DAMAGE, // WP_STUN_BATON - 0, // WP_MELEE // handled by the melee attack function - EMPLACED_DAMAGE, // WP_EMPLACED - BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - ATST_MAIN_DAMAGE, // WP_ATST_MAIN - ATST_SIDE_ALT_DAMAGE, // WP_ATST_SIDE - EMPLACED_DAMAGE, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC // repeater alt damage is used instead - BRYAR_PISTOL_DAMAGE // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + BRYAR_PISTOL_DAMAGE, // WP_BRYAR_PISTOL + BLASTER_DAMAGE, // WP_BLASTER + DISRUPTOR_ALT_DAMAGE, // WP_DISRUPTOR + BOWCASTER_DAMAGE, // WP_BOWCASTER + REPEATER_ALT_DAMAGE, // WP_REPEATER + DEMP2_ALT_DAMAGE, // WP_DEMP2 + FLECHETTE_ALT_DAMAGE, // WP_FLECHETTE + ROCKET_DAMAGE, // WP_ROCKET_LAUNCHER + TD_ALT_DAMAGE, // WP_THERMAL + LT_DAMAGE, // WP_TRIP_MINE + FLECHETTE_MINE_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + STUN_BATON_ALT_DAMAGE, // WP_STUN_BATON + 0, // WP_MELEE // handled by the melee attack function + EMPLACED_DAMAGE, // WP_EMPLACED + BRYAR_PISTOL_DAMAGE, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + ATST_MAIN_DAMAGE, // WP_ATST_MAIN + ATST_SIDE_ALT_DAMAGE, // WP_ATST_SIDE + EMPLACED_DAMAGE, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC // repeater alt damage is used instead + BRYAR_PISTOL_DAMAGE // WP_BLASTER_PISTOL }; const int defaultSplashDamage[] = { - 0, // WP_NONE - 0, // WP_SABER - 0, // WP_BRYAR_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER - 0, // WP_REPEATER - 0, // WP_DEMP2 - 0, // WP_FLECHETTE - ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER - TD_SPLASH_DAM, // WP_THERMAL - LT_SPLASH_DAM, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - 0, // WP_STUN_BATON - 0, // WP_MELEE - 0, // WP_EMPLACED - 0, // WP_BOT_LASER - 0, // WP_TURRET - 0, // WP_ATST_MAIN - ATST_SIDE_MAIN_SPLASH_DAMAGE, // WP_ATST_SIDE - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - 0 // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER + 0, // WP_BRYAR_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER + 0, // WP_REPEATER + 0, // WP_DEMP2 + 0, // WP_FLECHETTE + ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER + TD_SPLASH_DAM, // WP_THERMAL + LT_SPLASH_DAM, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + 0, // WP_STUN_BATON + 0, // WP_MELEE + 0, // WP_EMPLACED + 0, // WP_BOT_LASER + 0, // WP_TURRET + 0, // WP_ATST_MAIN + ATST_SIDE_MAIN_SPLASH_DAMAGE, // WP_ATST_SIDE + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + 0 // WP_BLASTER_PISTOL }; const float defaultSplashRadius[] = { - 0, // WP_NONE - 0, // WP_SABER - 0, // WP_BRYAR_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER - 0, // WP_REPEATER - 0, // WP_DEMP2 - 0, // WP_FLECHETTE - ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER - TD_SPLASH_RAD, // WP_THERMAL - LT_SPLASH_RAD, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_RADIUS, // WP_DET_PACK // HACK, this is what the code sez. - 0, // WP_STUN_BATON - 0, // WP_MELEE - 0, // WP_EMPLACED - 0, // WP_BOT_LASER - 0, // WP_TURRET - 0, // WP_ATST_MAIN - ATST_SIDE_MAIN_SPLASH_RADIUS, // WP_ATST_SIDE - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - 0 // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER + 0, // WP_BRYAR_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER + 0, // WP_REPEATER + 0, // WP_DEMP2 + 0, // WP_FLECHETTE + ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER + TD_SPLASH_RAD, // WP_THERMAL + LT_SPLASH_RAD, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_RADIUS, // WP_DET_PACK // HACK, this is what the code sez. + 0, // WP_STUN_BATON + 0, // WP_MELEE + 0, // WP_EMPLACED + 0, // WP_BOT_LASER + 0, // WP_TURRET + 0, // WP_ATST_MAIN + ATST_SIDE_MAIN_SPLASH_RADIUS, // WP_ATST_SIDE + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + 0 // WP_BLASTER_PISTOL }; const int defaultAltSplashDamage[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - 0, // WP_BRYAR_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER - REPEATER_ALT_SPLASH_DAMAGE, // WP_REPEATER - DEMP2_ALT_DAMAGE, // WP_DEMP2 - FLECHETTE_ALT_SPLASH_DAM, // WP_FLECHETTE - ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER - TD_ALT_SPLASH_DAM, // WP_THERMAL - TD_ALT_SPLASH_DAM, // WP_TRIP_MINE - FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. - 0, // WP_STUN_BATON - 0, // WP_MELEE // handled by the melee attack function - 0, // WP_EMPLACED - 0, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - 0, // WP_ATST_MAIN - ATST_SIDE_ALT_SPLASH_DAMAGE, // WP_ATST_SIDE - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - 0 // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + 0, // WP_BRYAR_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_DAMAGE, // WP_BOWCASTER + REPEATER_ALT_SPLASH_DAMAGE, // WP_REPEATER + DEMP2_ALT_DAMAGE, // WP_DEMP2 + FLECHETTE_ALT_SPLASH_DAM, // WP_FLECHETTE + ROCKET_SPLASH_DAMAGE, // WP_ROCKET_LAUNCHER + TD_ALT_SPLASH_DAM, // WP_THERMAL + TD_ALT_SPLASH_DAM, // WP_TRIP_MINE + FLECHETTE_MINE_SPLASH_DAMAGE, // WP_DET_PACK // HACK, this is what the code sez. + 0, // WP_STUN_BATON + 0, // WP_MELEE // handled by the melee attack function + 0, // WP_EMPLACED + 0, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + 0, // WP_ATST_MAIN + ATST_SIDE_ALT_SPLASH_DAMAGE, // WP_ATST_SIDE + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + 0 // WP_BLASTER_PISTOL }; const float defaultAltSplashRadius[] = { - 0, // WP_NONE - 0, // WP_SABER // handled elsewhere - 0, // WP_BRYAR_PISTOL - 0, // WP_BLASTER - 0, // WP_DISRUPTOR - BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER - REPEATER_ALT_SPLASH_RADIUS, // WP_REPEATER - DEMP2_ALT_SPLASHRADIUS, // WP_DEMP2 - FLECHETTE_ALT_SPLASH_RAD, // WP_FLECHETTE - ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER - TD_ALT_SPLASH_RAD, // WP_THERMAL - LT_SPLASH_RAD, // WP_TRIP_MINE - FLECHETTE_ALT_SPLASH_RAD, // WP_DET_PACK // HACK, this is what the code sez. - 0, // WP_STUN_BATON - 0, // WP_MELEE // handled by the melee attack function - 0, // WP_EMPLACED - 0, // WP_BOT_LASER - 0, // WP_TURRET // handled elsewhere - 0, // WP_ATST_MAIN - ATST_SIDE_ALT_SPLASH_RADIUS,// WP_ATST_SIDE - 0, // WP_TIE_FIGHTER - 0, // WP_RAPID_FIRE_CONC - 0 // WP_BLASTER_PISTOL + 0, // WP_NONE + 0, // WP_SABER // handled elsewhere + 0, // WP_BRYAR_PISTOL + 0, // WP_BLASTER + 0, // WP_DISRUPTOR + BOWCASTER_SPLASH_RADIUS, // WP_BOWCASTER + REPEATER_ALT_SPLASH_RADIUS, // WP_REPEATER + DEMP2_ALT_SPLASHRADIUS, // WP_DEMP2 + FLECHETTE_ALT_SPLASH_RAD, // WP_FLECHETTE + ROCKET_SPLASH_RADIUS, // WP_ROCKET_LAUNCHER + TD_ALT_SPLASH_RAD, // WP_THERMAL + LT_SPLASH_RAD, // WP_TRIP_MINE + FLECHETTE_ALT_SPLASH_RAD, // WP_DET_PACK // HACK, this is what the code sez. + 0, // WP_STUN_BATON + 0, // WP_MELEE // handled by the melee attack function + 0, // WP_EMPLACED + 0, // WP_BOT_LASER + 0, // WP_TURRET // handled elsewhere + 0, // WP_ATST_MAIN + ATST_SIDE_ALT_SPLASH_RADIUS, // WP_ATST_SIDE + 0, // WP_TIE_FIGHTER + 0, // WP_RAPID_FIRE_CONC + 0 // WP_BLASTER_PISTOL }; -wpnParms_t WpnParms[] = -{ - { "ammo", WPN_Ammo }, //ammo - { "ammoicon", WPN_AmmoIcon }, - { "ammomax", WPN_AmmoMax }, - { "ammolowcount", WPN_AmmoLowCnt }, //weapons - { "ammotype", WPN_AmmoType }, - { "energypershot", WPN_EnergyPerShot }, - { "fireTime", WPN_FireTime }, - { "firingsound", WPN_FiringSnd }, - { "altfiringsound", WPN_AltFiringSnd }, - { "stopsound", WPN_StopSnd }, - { "chargesound", WPN_ChargeSnd }, - { "altchargesound", WPN_AltChargeSnd }, - { "selectsound", WPN_SelectSnd }, - { "range", WPN_Range }, - { "weaponclass", WPN_WeaponClass }, - { "weaponicon", WPN_WeaponIcon }, - { "weaponmodel", WPN_WeaponModel }, - { "weapontype", WPN_WeaponType }, - { "altenergypershot", WPN_AltEnergyPerShot }, - { "altfireTime", WPN_AltFireTime }, - { "altrange", WPN_AltRange }, - { "barrelcount", WPN_BarrelCount }, - { "missileModel", WPN_MissileName }, - { "altmissileModel", WPN_AltMissileName }, - { "missileSound", WPN_MissileSound }, - { "altmissileSound", WPN_AltMissileSound }, - { "missileLight", WPN_MissileLight }, - { "altmissileLight", WPN_AltMissileLight }, - { "missileLightColor",WPN_MissileLightColor }, - { "altmissileLightColor", WPN_AltMissileLightColor }, - { "missileFuncName", WPN_FuncName }, - { "altmissileFuncName", WPN_AltFuncName }, - { "missileHitSound", WPN_MissileHitSound }, - { "altmissileHitSound", WPN_AltMissileHitSound }, - { "muzzleEffect", WPN_MuzzleEffect }, - { "altmuzzleEffect", WPN_AltMuzzleEffect }, +wpnParms_t WpnParms[] = { + {"ammo", WPN_Ammo}, // ammo + {"ammoicon", WPN_AmmoIcon}, + {"ammomax", WPN_AmmoMax}, + {"ammolowcount", WPN_AmmoLowCnt}, // weapons + {"ammotype", WPN_AmmoType}, + {"energypershot", WPN_EnergyPerShot}, + {"fireTime", WPN_FireTime}, + {"firingsound", WPN_FiringSnd}, + {"altfiringsound", WPN_AltFiringSnd}, + {"stopsound", WPN_StopSnd}, + {"chargesound", WPN_ChargeSnd}, + {"altchargesound", WPN_AltChargeSnd}, + {"selectsound", WPN_SelectSnd}, + {"range", WPN_Range}, + {"weaponclass", WPN_WeaponClass}, + {"weaponicon", WPN_WeaponIcon}, + {"weaponmodel", WPN_WeaponModel}, + {"weapontype", WPN_WeaponType}, + {"altenergypershot", WPN_AltEnergyPerShot}, + {"altfireTime", WPN_AltFireTime}, + {"altrange", WPN_AltRange}, + {"barrelcount", WPN_BarrelCount}, + {"missileModel", WPN_MissileName}, + {"altmissileModel", WPN_AltMissileName}, + {"missileSound", WPN_MissileSound}, + {"altmissileSound", WPN_AltMissileSound}, + {"missileLight", WPN_MissileLight}, + {"altmissileLight", WPN_AltMissileLight}, + {"missileLightColor", WPN_MissileLightColor}, + {"altmissileLightColor", WPN_AltMissileLightColor}, + {"missileFuncName", WPN_FuncName}, + {"altmissileFuncName", WPN_AltFuncName}, + {"missileHitSound", WPN_MissileHitSound}, + {"altmissileHitSound", WPN_AltMissileHitSound}, + {"muzzleEffect", WPN_MuzzleEffect}, + {"altmuzzleEffect", WPN_AltMuzzleEffect}, // OPENJK NEW FIELDS - { "damage", WPN_Damage }, - { "altdamage", WPN_AltDamage }, - { "splashDamage", WPN_SplashDamage }, - { "splashRadius", WPN_SplashRadius }, - { "altSplashDamage", WPN_AltSplashDamage }, - { "altSplashRadius", WPN_AltSplashRadius }, + {"damage", WPN_Damage}, + {"altdamage", WPN_AltDamage}, + {"splashDamage", WPN_SplashDamage}, + {"splashRadius", WPN_SplashRadius}, + {"altSplashDamage", WPN_AltSplashDamage}, + {"altSplashRadius", WPN_AltSplashRadius}, // Old legacy files contain these, so we skip them to shut up warnings - { "firingforce", WPN_FuncSkip }, - { "chargeforce", WPN_FuncSkip }, - { "altchargeforce", WPN_FuncSkip }, - { "selectforce", WPN_FuncSkip }, + {"firingforce", WPN_FuncSkip}, + {"chargeforce", WPN_FuncSkip}, + {"altchargeforce", WPN_FuncSkip}, + {"selectforce", WPN_FuncSkip}, }; static const size_t numWpnParms = ARRAY_LEN(WpnParms); -void WPN_FuncSkip( const char **holdBuf) -{ - SkipRestOfLine(holdBuf); -} +void WPN_FuncSkip(const char **holdBuf) { SkipRestOfLine(holdBuf); } -void WPN_WeaponType( const char **holdBuf) -{ +void WPN_WeaponType(const char **holdBuf) { int weaponNum; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } // FIXME : put this in an array (maybe a weaponDataInternal array???) - if (!Q_stricmp(tokenStr,"WP_NONE")) + if (!Q_stricmp(tokenStr, "WP_NONE")) weaponNum = WP_NONE; - else if (!Q_stricmp(tokenStr,"WP_SABER")) + else if (!Q_stricmp(tokenStr, "WP_SABER")) weaponNum = WP_SABER; - else if (!Q_stricmp(tokenStr,"WP_BRYAR_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BRYAR_PISTOL")) weaponNum = WP_BRYAR_PISTOL; - else if (!Q_stricmp(tokenStr,"WP_BLASTER")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER")) weaponNum = WP_BLASTER; - else if (!Q_stricmp(tokenStr,"WP_DISRUPTOR")) + else if (!Q_stricmp(tokenStr, "WP_DISRUPTOR")) weaponNum = WP_DISRUPTOR; - else if (!Q_stricmp(tokenStr,"WP_BOWCASTER")) + else if (!Q_stricmp(tokenStr, "WP_BOWCASTER")) weaponNum = WP_BOWCASTER; - else if (!Q_stricmp(tokenStr,"WP_REPEATER")) + else if (!Q_stricmp(tokenStr, "WP_REPEATER")) weaponNum = WP_REPEATER; - else if (!Q_stricmp(tokenStr,"WP_DEMP2")) + else if (!Q_stricmp(tokenStr, "WP_DEMP2")) weaponNum = WP_DEMP2; - else if (!Q_stricmp(tokenStr,"WP_FLECHETTE")) + else if (!Q_stricmp(tokenStr, "WP_FLECHETTE")) weaponNum = WP_FLECHETTE; - else if (!Q_stricmp(tokenStr,"WP_ROCKET_LAUNCHER")) + else if (!Q_stricmp(tokenStr, "WP_ROCKET_LAUNCHER")) weaponNum = WP_ROCKET_LAUNCHER; - else if (!Q_stricmp(tokenStr,"WP_THERMAL")) + else if (!Q_stricmp(tokenStr, "WP_THERMAL")) weaponNum = WP_THERMAL; - else if (!Q_stricmp(tokenStr,"WP_TRIP_MINE")) + else if (!Q_stricmp(tokenStr, "WP_TRIP_MINE")) weaponNum = WP_TRIP_MINE; - else if (!Q_stricmp(tokenStr,"WP_DET_PACK")) + else if (!Q_stricmp(tokenStr, "WP_DET_PACK")) weaponNum = WP_DET_PACK; - else if (!Q_stricmp(tokenStr,"WP_STUN_BATON")) + else if (!Q_stricmp(tokenStr, "WP_STUN_BATON")) weaponNum = WP_STUN_BATON; - else if (!Q_stricmp(tokenStr,"WP_BOT_LASER")) + else if (!Q_stricmp(tokenStr, "WP_BOT_LASER")) weaponNum = WP_BOT_LASER; - else if (!Q_stricmp(tokenStr,"WP_EMPLACED_GUN")) + else if (!Q_stricmp(tokenStr, "WP_EMPLACED_GUN")) weaponNum = WP_EMPLACED_GUN; - else if (!Q_stricmp(tokenStr,"WP_MELEE")) + else if (!Q_stricmp(tokenStr, "WP_MELEE")) weaponNum = WP_MELEE; - else if (!Q_stricmp(tokenStr,"WP_TURRET")) + else if (!Q_stricmp(tokenStr, "WP_TURRET")) weaponNum = WP_TURRET; - else if (!Q_stricmp(tokenStr,"WP_ATST_MAIN")) + else if (!Q_stricmp(tokenStr, "WP_ATST_MAIN")) weaponNum = WP_ATST_MAIN; - else if (!Q_stricmp(tokenStr,"WP_ATST_SIDE")) + else if (!Q_stricmp(tokenStr, "WP_ATST_SIDE")) weaponNum = WP_ATST_SIDE; - else if (!Q_stricmp(tokenStr,"WP_TIE_FIGHTER")) + else if (!Q_stricmp(tokenStr, "WP_TIE_FIGHTER")) weaponNum = WP_TIE_FIGHTER; - else if (!Q_stricmp(tokenStr,"WP_RAPID_FIRE_CONC")) + else if (!Q_stricmp(tokenStr, "WP_RAPID_FIRE_CONC")) weaponNum = WP_RAPID_FIRE_CONC; - else if (!Q_stricmp(tokenStr,"WP_BLASTER_PISTOL")) + else if (!Q_stricmp(tokenStr, "WP_BLASTER_PISTOL")) weaponNum = WP_BLASTER_PISTOL; - else - { + else { weaponNum = 0; - gi.Printf(S_COLOR_YELLOW"WARNING: bad weapontype in external weapon data '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: bad weapontype in external weapon data '%s'\n", tokenStr); } wpnParms.weaponNum = weaponNum; } //-------------------------------------------- -void WPN_WeaponClass(const char **holdBuf) -{ +void WPN_WeaponClass(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if (COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 32) - { + if (len > 32) { len = 32; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponclass too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponclass too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].classname,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].classname, tokenStr, len); } - //-------------------------------------------- -void WPN_WeaponModel(const char **holdBuf) -{ +void WPN_WeaponModel(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponMdl too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponMdl too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].weaponMdl,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].weaponMdl, tokenStr, len); } //-------------------------------------------- -void WPN_WeaponIcon(const char **holdBuf) -{ +void WPN_WeaponIcon(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: weaponIcon too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: weaponIcon too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].weaponIcon,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].weaponIcon, tokenStr, len); } //-------------------------------------------- -void WPN_AmmoType(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoType(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < AMMO_NONE ) || (tokenInt >= AMMO_MAX )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammotype in external weapon data '%d'\n", tokenInt); + if ((tokenInt < AMMO_NONE) || (tokenInt >= AMMO_MAX)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammotype in external weapon data '%d'\n", tokenInt); return; } @@ -529,19 +505,17 @@ void WPN_AmmoType(const char **holdBuf) } //-------------------------------------------- -void WPN_AmmoLowCnt(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoLowCnt(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 100 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 100)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammolowcount in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammolowcount in external weapon data '%d'\n", tokenInt); return; } @@ -549,171 +523,149 @@ void WPN_AmmoLowCnt(const char **holdBuf) } //-------------------------------------------- -void WPN_FiringSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_FiringSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: firingSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: firingSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].firingSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].firingSnd, tokenStr, len); } //-------------------------------------------- -void WPN_AltFiringSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_AltFiringSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: altFiringSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: altFiringSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altFiringSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altFiringSnd, tokenStr, len); } //-------------------------------------------- -void WPN_StopSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_StopSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: stopSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: stopSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].stopSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].stopSnd, tokenStr, len); } //-------------------------------------------- -void WPN_ChargeSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_ChargeSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: chargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: chargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].chargeSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].chargeSnd, tokenStr, len); } //-------------------------------------------- -void WPN_AltChargeSnd(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_AltChargeSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: altChargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: altChargeSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altChargeSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altChargeSnd, tokenStr, len); } //-------------------------------------------- -void WPN_SelectSnd( const char **holdBuf ) -{ - const char *tokenStr; - int len; +void WPN_SelectSnd(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString( holdBuf,&tokenStr )) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - len = strlen( tokenStr ); + len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: selectSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: selectSnd too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz( weaponData[wpnParms.weaponNum].selectSnd,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].selectSnd, tokenStr, len); } //-------------------------------------------- -void WPN_FireTime(const char **holdBuf) -{ - int tokenInt; +void WPN_FireTime(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Firetime in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Firetime in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].fireTime = tokenInt; } //-------------------------------------------- -void WPN_Range(const char **holdBuf) -{ - int tokenInt; +void WPN_Range(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Range in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad Range in external weapon data '%d'\n", tokenInt); return; } @@ -721,57 +673,51 @@ void WPN_Range(const char **holdBuf) } //-------------------------------------------- -void WPN_EnergyPerShot(const char **holdBuf) -{ - int tokenInt; +void WPN_EnergyPerShot(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 1000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad EnergyPerShot in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad EnergyPerShot in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].energyPerShot = tokenInt; } //-------------------------------------------- -void WPN_AltFireTime(const char **holdBuf) -{ - int tokenInt; +void WPN_AltFireTime(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altFireTime in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad altFireTime in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].altFireTime = tokenInt; } //-------------------------------------------- -void WPN_AltRange(const char **holdBuf) -{ - int tokenInt; +void WPN_AltRange(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 10000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 10000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad AltRange in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad AltRange in external weapon data '%d'\n", tokenInt); return; } @@ -779,490 +725,415 @@ void WPN_AltRange(const char **holdBuf) } //-------------------------------------------- -void WPN_AltEnergyPerShot(const char **holdBuf) -{ - int tokenInt; +void WPN_AltEnergyPerShot(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) // FIXME :What are the right values? + if ((tokenInt < 0) || (tokenInt > 1000)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad AltEnergyPerShot in external weapon data '%d'\n", tokenInt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad AltEnergyPerShot in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].altEnergyPerShot = tokenInt; } //-------------------------------------------- -void WPN_Ammo(const char **holdBuf) -{ - const char *tokenStr; +void WPN_Ammo(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } - if (!Q_stricmp(tokenStr,"AMMO_NONE")) + if (!Q_stricmp(tokenStr, "AMMO_NONE")) wpnParms.ammoNum = AMMO_NONE; - else if (!Q_stricmp(tokenStr,"AMMO_FORCE")) + else if (!Q_stricmp(tokenStr, "AMMO_FORCE")) wpnParms.ammoNum = AMMO_FORCE; - else if (!Q_stricmp(tokenStr,"AMMO_BLASTER")) + else if (!Q_stricmp(tokenStr, "AMMO_BLASTER")) wpnParms.ammoNum = AMMO_BLASTER; - else if (!Q_stricmp(tokenStr,"AMMO_POWERCELL")) + else if (!Q_stricmp(tokenStr, "AMMO_POWERCELL")) wpnParms.ammoNum = AMMO_POWERCELL; - else if (!Q_stricmp(tokenStr,"AMMO_METAL_BOLTS")) + else if (!Q_stricmp(tokenStr, "AMMO_METAL_BOLTS")) wpnParms.ammoNum = AMMO_METAL_BOLTS; - else if (!Q_stricmp(tokenStr,"AMMO_ROCKETS")) + else if (!Q_stricmp(tokenStr, "AMMO_ROCKETS")) wpnParms.ammoNum = AMMO_ROCKETS; - else if (!Q_stricmp(tokenStr,"AMMO_EMPLACED")) + else if (!Q_stricmp(tokenStr, "AMMO_EMPLACED")) wpnParms.ammoNum = AMMO_EMPLACED; - else if (!Q_stricmp(tokenStr,"AMMO_THERMAL")) + else if (!Q_stricmp(tokenStr, "AMMO_THERMAL")) wpnParms.ammoNum = AMMO_THERMAL; - else if (!Q_stricmp(tokenStr,"AMMO_TRIPMINE")) + else if (!Q_stricmp(tokenStr, "AMMO_TRIPMINE")) wpnParms.ammoNum = AMMO_TRIPMINE; - else if (!Q_stricmp(tokenStr,"AMMO_DETPACK")) + else if (!Q_stricmp(tokenStr, "AMMO_DETPACK")) wpnParms.ammoNum = AMMO_DETPACK; - else - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad ammotype in external weapon data '%s'\n", tokenStr); + else { + gi.Printf(S_COLOR_YELLOW "WARNING: bad ammotype in external weapon data '%s'\n", tokenStr); wpnParms.ammoNum = 0; } } //-------------------------------------------- -void WPN_AmmoIcon(const char **holdBuf) -{ - const char *tokenStr; - int len; +void WPN_AmmoIcon(const char **holdBuf) { + const char *tokenStr; + int len; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: ammoicon too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: ammoicon too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(ammoData[wpnParms.ammoNum].icon,tokenStr,len); - + Q_strncpyz(ammoData[wpnParms.ammoNum].icon, tokenStr, len); } //-------------------------------------------- -void WPN_AmmoMax(const char **holdBuf) -{ - int tokenInt; +void WPN_AmmoMax(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 1000 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Ammo Max in external weapon data '%d'\n", tokenInt); + if ((tokenInt < 0) || (tokenInt > 1000)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Ammo Max in external weapon data '%d'\n", tokenInt); return; } ammoData[wpnParms.ammoNum].max = tokenInt; } //-------------------------------------------- -void WPN_BarrelCount(const char **holdBuf) -{ - int tokenInt; +void WPN_BarrelCount(const char **holdBuf) { + int tokenInt; - if ( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } - if ((tokenInt < 0) || (tokenInt > 4 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad Range in external weapon data '%d'\n", tokenInt); + if ((tokenInt < 0) || (tokenInt > 4)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad Range in external weapon data '%d'\n", tokenInt); return; } weaponData[wpnParms.weaponNum].numBarrels = tokenInt; } - //-------------------------------------------- -static void WP_ParseWeaponParms(const char **holdBuf) -{ - const char *token; - size_t i; +static void WP_ParseWeaponParms(const char **holdBuf) { + const char *token; + size_t i; - while (holdBuf) - { - token = COM_ParseExt( holdBuf, qtrue ); + while (holdBuf) { + token = COM_ParseExt(holdBuf, qtrue); - if (!Q_stricmp( token, "}" )) // End of data for this weapon + if (!Q_stricmp(token, "}")) // End of data for this weapon break; // Loop through possible parameters - for (i=0;i 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileMdl,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].missileMdl, tokenStr, len); } //-------------------------------------------- -void WPN_AltMissileName(const char **holdBuf) -{ +void WPN_AltMissileName(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileName too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileMdl,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileMdl, tokenStr, len); } - //-------------------------------------------- -void WPN_MissileHitSound(const char **holdBuf) -{ +void WPN_MissileHitSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileHitSound,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].missileHitSound, tokenStr, len); } //-------------------------------------------- -void WPN_AltMissileHitSound(const char **holdBuf) -{ +void WPN_AltMissileHitSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileHitSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].altmissileHitSound,tokenStr,len); + Q_strncpyz(weaponData[wpnParms.weaponNum].altmissileHitSound, tokenStr, len); } //-------------------------------------------- -void WPN_MissileSound(const char **holdBuf) -{ +void WPN_MissileSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].missileSound,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].missileSound, tokenStr, len); } - //-------------------------------------------- -void WPN_AltMissileSound(const char **holdBuf) -{ +void WPN_AltMissileSound(const char **holdBuf) { int len; - const char *tokenStr; + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMissileSound too long in external WEAPONS.DAT '%s'\n", tokenStr); } - Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileSound,tokenStr,len); - + Q_strncpyz(weaponData[wpnParms.weaponNum].alt_missileSound, tokenStr, len); } //-------------------------------------------- -void WPN_MissileLightColor(const char **holdBuf) -{ +void WPN_MissileLightColor(const char **holdBuf) { int i; - float tokenFlt; + float tokenFlt; - for (i=0;i<3;++i) - { - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); continue; } - if ((tokenFlt < 0) || (tokenFlt > 1 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad missilelightcolor in external weapon data '%f'\n", tokenFlt); + if ((tokenFlt < 0) || (tokenFlt > 1)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad missilelightcolor in external weapon data '%f'\n", tokenFlt); continue; } weaponData[wpnParms.weaponNum].missileDlightColor[i] = tokenFlt; } - } //-------------------------------------------- -void WPN_AltMissileLightColor(const char **holdBuf) -{ +void WPN_AltMissileLightColor(const char **holdBuf) { int i; - float tokenFlt; + float tokenFlt; - for (i=0;i<3;++i) - { - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + for (i = 0; i < 3; ++i) { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); continue; } - if ((tokenFlt < 0) || (tokenFlt > 1 )) - { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altmissilelightcolor in external weapon data '%f'\n", tokenFlt); + if ((tokenFlt < 0) || (tokenFlt > 1)) { + gi.Printf(S_COLOR_YELLOW "WARNING: bad altmissilelightcolor in external weapon data '%f'\n", tokenFlt); continue; } weaponData[wpnParms.weaponNum].alt_missileDlightColor[i] = tokenFlt; } - } - //-------------------------------------------- -void WPN_MissileLight(const char **holdBuf) -{ - float tokenFlt; +void WPN_MissileLight(const char **holdBuf) { + float tokenFlt; - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); } - if ((tokenFlt < 0) || (tokenFlt > 255 )) // FIXME :What are the right values? + if ((tokenFlt < 0) || (tokenFlt > 255)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad missilelight in external weapon data '%f'\n", tokenFlt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad missilelight in external weapon data '%f'\n", tokenFlt); } weaponData[wpnParms.weaponNum].missileDlight = tokenFlt; } //-------------------------------------------- -void WPN_AltMissileLight(const char **holdBuf) -{ - float tokenFlt; +void WPN_AltMissileLight(const char **holdBuf) { + float tokenFlt; - if ( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); } - if ((tokenFlt < 0) || (tokenFlt > 255 )) // FIXME :What are the right values? + if ((tokenFlt < 0) || (tokenFlt > 255)) // FIXME :What are the right values? { - gi.Printf(S_COLOR_YELLOW"WARNING: bad altmissilelight in external weapon data '%f'\n", tokenFlt); + gi.Printf(S_COLOR_YELLOW "WARNING: bad altmissilelight in external weapon data '%f'\n", tokenFlt); } weaponData[wpnParms.weaponNum].alt_missileDlight = tokenFlt; } - //-------------------------------------------- -void WPN_FuncName(const char **holdBuf) -{ - const char *tokenStr; +void WPN_FuncName(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: FuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: FuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); } - for ( func_t* s=funcs ; s->name ; s++ ) { - if ( !Q_stricmp(s->name, tokenStr) ) { + for (func_t *s = funcs; s->name; s++) { + if (!Q_stricmp(s->name, tokenStr)) { // found it - weaponData[wpnParms.weaponNum].func = (void*)s->func; + weaponData[wpnParms.weaponNum].func = (void *)s->func; return; } } - gi.Printf(S_COLOR_YELLOW"WARNING: FuncName '%s' in external WEAPONS.DAT does not exist\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: FuncName '%s' in external WEAPONS.DAT does not exist\n", tokenStr); } - //-------------------------------------------- -void WPN_AltFuncName(const char **holdBuf) -{ - const char *tokenStr; +void WPN_AltFuncName(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltFuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltFuncName '%s' too long in external WEAPONS.DAT\n", tokenStr); } - for ( func_t* s=funcs ; s->name ; s++ ) { - if ( !Q_stricmp(s->name, tokenStr) ) { + for (func_t *s = funcs; s->name; s++) { + if (!Q_stricmp(s->name, tokenStr)) { // found it - weaponData[wpnParms.weaponNum].altfunc = (void*)s->func; + weaponData[wpnParms.weaponNum].altfunc = (void *)s->func; return; } } - gi.Printf(S_COLOR_YELLOW"WARNING: AltFuncName %s in external WEAPONS.DAT does not exist\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltFuncName %s in external WEAPONS.DAT does not exist\n", tokenStr); } //-------------------------------------------- -void WPN_MuzzleEffect(const char **holdBuf) -{ - const char *tokenStr; +void WPN_MuzzleEffect(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: MuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: MuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); } - G_EffectIndex( tokenStr ); - Q_strncpyz(weaponData[wpnParms.weaponNum].mMuzzleEffect,tokenStr,len); + G_EffectIndex(tokenStr); + Q_strncpyz(weaponData[wpnParms.weaponNum].mMuzzleEffect, tokenStr, len); } //-------------------------------------------- -void WPN_AltMuzzleEffect(const char **holdBuf) -{ - const char *tokenStr; +void WPN_AltMuzzleEffect(const char **holdBuf) { + const char *tokenStr; - if ( COM_ParseString(holdBuf,&tokenStr)) - { + if (COM_ParseString(holdBuf, &tokenStr)) { return; } size_t len = strlen(tokenStr); len++; - if (len > 64) - { + if (len > 64) { len = 64; - gi.Printf(S_COLOR_YELLOW"WARNING: AltMuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); + gi.Printf(S_COLOR_YELLOW "WARNING: AltMuzzleEffect '%s' too long in external WEAPONS.DAT\n", tokenStr); } - G_EffectIndex( tokenStr ); - Q_strncpyz(weaponData[wpnParms.weaponNum].mAltMuzzleEffect,tokenStr,len); + G_EffectIndex(tokenStr); + Q_strncpyz(weaponData[wpnParms.weaponNum].mAltMuzzleEffect, tokenStr, len); } //-------------------------------------------- -void WPN_Damage(const char **holdBuf) -{ - int tokenInt; +void WPN_Damage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1272,12 +1143,10 @@ void WPN_Damage(const char **holdBuf) //-------------------------------------------- -void WPN_AltDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_AltDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1287,12 +1156,10 @@ void WPN_AltDamage(const char **holdBuf) //-------------------------------------------- -void WPN_SplashDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_SplashDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1302,12 +1169,10 @@ void WPN_SplashDamage(const char **holdBuf) //-------------------------------------------- -void WPN_SplashRadius(const char **holdBuf) -{ - float tokenFlt; +void WPN_SplashRadius(const char **holdBuf) { + float tokenFlt; - if( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); return; } @@ -1317,12 +1182,10 @@ void WPN_SplashRadius(const char **holdBuf) //-------------------------------------------- -void WPN_AltSplashDamage(const char **holdBuf) -{ - int tokenInt; +void WPN_AltSplashDamage(const char **holdBuf) { + int tokenInt; - if( COM_ParseInt(holdBuf,&tokenInt)) - { + if (COM_ParseInt(holdBuf, &tokenInt)) { SkipRestOfLine(holdBuf); return; } @@ -1332,12 +1195,10 @@ void WPN_AltSplashDamage(const char **holdBuf) //-------------------------------------------- -void WPN_AltSplashRadius(const char **holdBuf) -{ - float tokenFlt; +void WPN_AltSplashRadius(const char **holdBuf) { + float tokenFlt; - if( COM_ParseFloat(holdBuf,&tokenFlt)) - { + if (COM_ParseFloat(holdBuf, &tokenFlt)) { SkipRestOfLine(holdBuf); return; } @@ -1346,42 +1207,35 @@ void WPN_AltSplashRadius(const char **holdBuf) } //-------------------------------------------- -static void WP_ParseParms(const char *buffer) -{ - const char *holdBuf; - const char *token; +static void WP_ParseParms(const char *buffer) { + const char *holdBuf; + const char *token; holdBuf = buffer; COM_BeginParseSession(); - while ( holdBuf ) - { - token = COM_ParseExt( &holdBuf, qtrue ); + while (holdBuf) { + token = COM_ParseExt(&holdBuf, qtrue); - if ( !Q_stricmp( token, "{" ) ) - { + if (!Q_stricmp(token, "{")) { WP_ParseWeaponParms(&holdBuf); } - } - COM_EndParseSession( ); - + COM_EndParseSession(); } //-------------------------------------------- -void WP_LoadWeaponParms (void) -{ +void WP_LoadWeaponParms(void) { char *buffer; - gi.FS_ReadFile("ext_data/weapons.dat",(void **) &buffer); + gi.FS_ReadFile("ext_data/weapons.dat", (void **)&buffer); // initialise the data area memset(weaponData, 0, sizeof(weaponData)); // put in the default values, because backwards compatibility is awesome! - for(int i = 0; i < WP_NUM_WEAPONS; i++) - { + for (int i = 0; i < WP_NUM_WEAPONS; i++) { weaponData[i].damage = defaultDamage[i]; weaponData[i].altDamage = defaultAltDamage[i]; weaponData[i].splashDamage = defaultSplashDamage[i]; @@ -1392,5 +1246,5 @@ void WP_LoadWeaponParms (void) WP_ParseParms(buffer); - gi.FS_FreeFile( buffer ); //let go of the buffer + gi.FS_FreeFile(buffer); // let go of the buffer } \ No newline at end of file diff --git a/codeJK2/game/genericparser2.cpp b/codeJK2/game/genericparser2.cpp index f893395ca8..f73567efed 100644 --- a/codeJK2/game/genericparser2.cpp +++ b/codeJK2/game/genericparser2.cpp @@ -32,53 +32,42 @@ along with this program; if not, see . #include #include - -static void skipWhitespace( gsl::cstring_span& text, const bool allowLineBreaks ) -{ +static void skipWhitespace(gsl::cstring_span &text, const bool allowLineBreaks) { gsl::cstring_span::iterator whitespaceEnd = text.begin(); - while ( whitespaceEnd != text.end() // No EOF - && std::isspace( *whitespaceEnd ) // No End of Whitespace - && (allowLineBreaks || *whitespaceEnd != '\n') ) // No unwanted newline + while (whitespaceEnd != text.end() // No EOF + && std::isspace(*whitespaceEnd) // No End of Whitespace + && (allowLineBreaks || *whitespaceEnd != '\n')) // No unwanted newline { ++whitespaceEnd; } - text = { whitespaceEnd, text.end() }; + text = {whitespaceEnd, text.end()}; } -static void skipWhitespaceAndComments( gsl::cstring_span& text, const bool allowLineBreaks ) -{ - skipWhitespace( text, allowLineBreaks ); +static void skipWhitespaceAndComments(gsl::cstring_span &text, const bool allowLineBreaks) { + skipWhitespace(text, allowLineBreaks); // skip single line comment - if ( text.size() >= 2 && text[0] == '/' && text[1] == '/' ) - { - auto commentEnd = std::find( text.begin() + 2, text.end(), '\n' ); - if ( commentEnd == text.end() ) - { - text = { text.end(), text.end() }; + if (text.size() >= 2 && text[0] == '/' && text[1] == '/') { + auto commentEnd = std::find(text.begin() + 2, text.end(), '\n'); + if (commentEnd == text.end()) { + text = {text.end(), text.end()}; return; - } - else - { - text = { commentEnd, text.end() }; - skipWhitespaceAndComments( text, allowLineBreaks ); + } else { + text = {commentEnd, text.end()}; + skipWhitespaceAndComments(text, allowLineBreaks); return; } } // skip multi line comments - if ( text.size() >= 2 && text[0] == '/' && text[1] == '*' ) - { - static const std::array< char, 2 > endStr{ '*', '/' }; - auto commentEnd = std::search( text.begin(), text.end(), endStr.begin(), endStr.end() ); - if ( commentEnd == text.end() ) - { - text = { text.end(), text.end() }; + if (text.size() >= 2 && text[0] == '/' && text[1] == '*') { + static const std::array endStr{'*', '/'}; + auto commentEnd = std::search(text.begin(), text.end(), endStr.begin(), endStr.end()); + if (commentEnd == text.end()) { + text = {text.end(), text.end()}; return; - } - else - { - text = { commentEnd + endStr.size(), text.end() }; - skipWhitespace( text, allowLineBreaks ); + } else { + text = {commentEnd + endStr.size(), text.end()}; + skipWhitespace(text, allowLineBreaks); return; } } @@ -87,15 +76,10 @@ static void skipWhitespaceAndComments( gsl::cstring_span& text, const bool allow return; } -static gsl::cstring_span removeTrailingWhitespace( const gsl::cstring_span& text ) -{ - return{ - text.begin(), - std::find_if_not( - std::reverse_iterator< const char *>( text.end() ), std::reverse_iterator< const char* >( text.begin() ), - static_cast< int( *)(int) >(std::isspace) - ).base() - }; +static gsl::cstring_span removeTrailingWhitespace(const gsl::cstring_span &text) { + return {text.begin(), std::find_if_not(std::reverse_iterator(text.end()), std::reverse_iterator(text.begin()), + static_cast(std::isspace)) + .base()}; } /** @@ -106,129 +90,71 @@ A token can be: - EOL- or comment-delimited (if readToEOL == true); i.e. reads to end of line or the first // or /* @param text adjusted to start beyond the read token */ -static gsl::cstring_span GetToken( gsl::cstring_span& text, bool allowLineBreaks, bool readToEOL = false ) -{ - skipWhitespaceAndComments( text, allowLineBreaks ); +static gsl::cstring_span GetToken(gsl::cstring_span &text, bool allowLineBreaks, bool readToEOL = false) { + skipWhitespaceAndComments(text, allowLineBreaks); // EOF - if ( text.empty() ) - { - return{}; + if (text.empty()) { + return {}; } // string. ignores readToEOL. - if ( text[0] == '"' ) - { + if (text[0] == '"') { // there are no escapes, string just ends at the next " - auto tokenEnd = std::find( text.begin() + 1, text.end(), '"' ); - if ( tokenEnd == text.end() ) - { - gsl::cstring_span token = { text.begin() + 1, text.end() }; - text = { text.end(), text.end() }; + auto tokenEnd = std::find(text.begin() + 1, text.end(), '"'); + if (tokenEnd == text.end()) { + gsl::cstring_span token = {text.begin() + 1, text.end()}; + text = {text.end(), text.end()}; return token; - } - else - { - gsl::cstring_span token = { text.begin() + 1, tokenEnd }; - text = { tokenEnd + 1, text.end() }; + } else { + gsl::cstring_span token = {text.begin() + 1, tokenEnd}; + text = {tokenEnd + 1, text.end()}; return token; } - } - else if ( readToEOL ) - { + } else if (readToEOL) { // find the first of '\n', "//" or "/*"; that's end of token - auto tokenEnd = std::find( text.begin(), text.end(), '\n' ); - static const std::array< char, 2 > commentPatterns[]{ - { { '/', '*' } }, - { { '/', '/' } } - }; - for ( auto& pattern : commentPatterns ) - { - tokenEnd = std::min( - tokenEnd, - std::search( - text.begin(), tokenEnd, - pattern.begin(), pattern.end() - ) - ); + auto tokenEnd = std::find(text.begin(), text.end(), '\n'); + static const std::array commentPatterns[]{{{'/', '*'}}, {{'/', '/'}}}; + for (auto &pattern : commentPatterns) { + tokenEnd = std::min(tokenEnd, std::search(text.begin(), tokenEnd, pattern.begin(), pattern.end())); } - gsl::cstring_span token{ text.begin(), tokenEnd }; - text = { tokenEnd, text.end() }; - return removeTrailingWhitespace( token ); - } - else - { + gsl::cstring_span token{text.begin(), tokenEnd}; + text = {tokenEnd, text.end()}; + return removeTrailingWhitespace(token); + } else { // consume until first whitespace (if allowLineBreaks == false, that may be text.begin(); in that case token is empty.) - auto tokenEnd = std::find_if( text.begin(), text.end(), static_cast< int( *)(int) >(std::isspace) ); - gsl::cstring_span token{ text.begin(), tokenEnd }; - text = { tokenEnd, text.end() }; + auto tokenEnd = std::find_if(text.begin(), text.end(), static_cast(std::isspace)); + gsl::cstring_span token{text.begin(), tokenEnd}; + text = {tokenEnd, text.end()}; return token; } } - - - - -CGPProperty::CGPProperty( gsl::cstring_span initKey, gsl::cstring_span initValue ) - : mKey( initKey ) -{ - if ( !initValue.empty() ) - { - mValues.push_back( initValue ); +CGPProperty::CGPProperty(gsl::cstring_span initKey, gsl::cstring_span initValue) : mKey(initKey) { + if (!initValue.empty()) { + mValues.push_back(initValue); } } -void CGPProperty::AddValue( gsl::cstring_span newValue ) -{ - mValues.push_back( newValue ); -} - - - - - - - - - - - +void CGPProperty::AddValue(gsl::cstring_span newValue) { mValues.push_back(newValue); } +CGPGroup::CGPGroup(const gsl::cstring_span &initName) : mName(initName) {} +bool CGPGroup::Parse(gsl::cstring_span &data, const bool topLevel) { + while (true) { + gsl::cstring_span token = GetToken(data, true); - - -CGPGroup::CGPGroup( const gsl::cstring_span& initName ) - : mName( initName ) -{} - -bool CGPGroup::Parse( gsl::cstring_span& data, const bool topLevel ) -{ - while ( true ) - { - gsl::cstring_span token = GetToken( data, true ); - - if ( token.empty() ) - { - if ( topLevel ) - { + if (token.empty()) { + if (topLevel) { // top level parse; there was no opening "{", so there should be no closing one either. return true; - } - else - { + } else { // end of data - error! return false; } - } - else if ( token == CSTRING_VIEW( "}" ) ) - { - if ( topLevel ) - { + } else if (token == CSTRING_VIEW("}")) { + if (topLevel) { // top-level group; there was no opening "{" so there should be no closing one, either. return false; - } - else - { + } else { // ending brace for this group return true; } @@ -236,74 +162,44 @@ bool CGPGroup::Parse( gsl::cstring_span& data, const bool topLevel ) gsl::cstring_span lastToken = token; // read ahead to see what we are doing - token = GetToken( data, true, true ); - if ( token == CSTRING_VIEW( "{" ) ) - { + token = GetToken(data, true, true); + if (token == CSTRING_VIEW("{")) { // new sub group - mSubGroups.emplace_back( lastToken ); - if ( !mSubGroups.back().Parse( data, false ) ) - { + mSubGroups.emplace_back(lastToken); + if (!mSubGroups.back().Parse(data, false)) { return false; } - } - else if ( token == CSTRING_VIEW( "[" ) ) - { + } else if (token == CSTRING_VIEW("[")) { // new list - mProperties.emplace_back( lastToken ); - CGPProperty& list = mProperties.back(); - while ( true ) - { - token = GetToken( data, true, true ); - if ( token.empty() ) - { + mProperties.emplace_back(lastToken); + CGPProperty &list = mProperties.back(); + while (true) { + token = GetToken(data, true, true); + if (token.empty()) { return false; } - if ( token == CSTRING_VIEW( "]" ) ) - { + if (token == CSTRING_VIEW("]")) { break; } - list.AddValue( token ); + list.AddValue(token); } - } - else - { + } else { // new value - mProperties.emplace_back( lastToken, token ); + mProperties.emplace_back(lastToken, token); } } } - - - - - - - - - - - - - -bool CGenericParser2::Parse( gsl::czstring filename ) -{ +bool CGenericParser2::Parse(gsl::czstring filename) { Clear(); - mFileContent = FS::ReadFile( filename ); - if ( !mFileContent.valid() ) - { + mFileContent = FS::ReadFile(filename); + if (!mFileContent.valid()) { return false; } auto view = mFileContent.view(); - return mTopLevel.Parse( view ); + return mTopLevel.Parse(view); } -void CGenericParser2::Clear() NOEXCEPT -{ - mTopLevel.Clear(); -} - - +void CGenericParser2::Clear() NOEXCEPT { mTopLevel.Clear(); } //////////////////// eof ///////////////////// - diff --git a/codeJK2/game/wp_atst.cpp b/codeJK2/game/wp_atst.cpp index b47aaa429f..ec2128c42f 100644 --- a/codeJK2/game/wp_atst.cpp +++ b/codeJK2/game/wp_atst.cpp @@ -30,53 +30,50 @@ along with this program; if not, see . // ATST Main //--------------------------------------------------------- -void WP_ATSTMainFire( gentity_t *ent ) +void WP_ATSTMainFire(gentity_t *ent) //--------------------------------------------------------- { float vel = ATST_MAIN_VEL; -// if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) -// { -// vel = 4500.0f; -// } + // if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) + // { + // vel = 4500.0f; + // } - if ( !ent->s.number ) - { + if (!ent->s.number) { // player shoots faster vel *= 1.6f; } - gentity_t *missile = CreateMissile( wpMuzzle, wpFwd, vel, 10000, ent ); + gentity_t *missile = CreateMissile(wpMuzzle, wpFwd, vel, 10000, ent); missile->classname = "atst_main_proj"; missile->s.weapon = WP_ATST_MAIN; missile->damage = weaponData[WP_ATST_MAIN].damage; - missile->dflags = DAMAGE_DEATH_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS; + missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->owner = ent; - VectorSet( missile->maxs, ATST_MAIN_SIZE, ATST_MAIN_SIZE, ATST_MAIN_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); - + VectorSet(missile->maxs, ATST_MAIN_SIZE, ATST_MAIN_SIZE, ATST_MAIN_SIZE); + VectorScale(missile->maxs, -1, missile->mins); } // ATST Alt Side //--------------------------------------------------------- -void WP_ATSTSideAltFire( gentity_t *ent ) +void WP_ATSTSideAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_ATST_SIDE].altDamage; - float vel = ATST_SIDE_ALT_NPC_VELOCITY; + int damage = weaponData[WP_ATST_SIDE].altDamage; + float vel = ATST_SIDE_ALT_NPC_VELOCITY; - if ( ent->client && (ent->client->ps.eFlags & EF_IN_ATST )) - { + if (ent->client && (ent->client->ps.eFlags & EF_IN_ATST)) { vel = ATST_SIDE_ALT_VELOCITY; } - gentity_t *missile = CreateMissile( wpMuzzle, wpFwd, vel, 10000, ent, qtrue ); + gentity_t *missile = CreateMissile(wpMuzzle, wpFwd, vel, 10000, ent, qtrue); missile->classname = "atst_rocket"; missile->s.weapon = WP_ATST_SIDE; @@ -84,27 +81,21 @@ void WP_ATSTSideAltFire( gentity_t *ent ) missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ATST_SIDE_ROCKET_NPC_DAMAGE_HARD; } } - VectorCopy( wpFwd, missile->movedir ); + VectorCopy(wpFwd, missile->movedir); // Make it easier to hit things - VectorSet( missile->maxs, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE, ATST_SIDE_ALT_ROCKET_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; @@ -113,7 +104,7 @@ void WP_ATSTSideAltFire( gentity_t *ent ) missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // Scale damage down a bit if it is coming from an NPC - missile->splashDamage = weaponData[WP_ATST_SIDE].altSplashDamage * ( ent->s.number == 0 ? 1.0f : ATST_SIDE_ALT_ROCKET_SPLASH_SCALE ); + missile->splashDamage = weaponData[WP_ATST_SIDE].altSplashDamage * (ent->s.number == 0 ? 1.0f : ATST_SIDE_ALT_ROCKET_SPLASH_SCALE); missile->splashRadius = weaponData[WP_ATST_SIDE].altSplashRadius; // we don't want it to ever bounce @@ -122,42 +113,36 @@ void WP_ATSTSideAltFire( gentity_t *ent ) // ATST Side //--------------------------------------------------------- -void WP_ATSTSideFire( gentity_t *ent ) +void WP_ATSTSideFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_ATST_SIDE].damage; + int damage = weaponData[WP_ATST_SIDE].damage; - gentity_t *missile = CreateMissile( wpMuzzle, wpFwd, ATST_SIDE_MAIN_VELOCITY, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(wpMuzzle, wpFwd, ATST_SIDE_MAIN_VELOCITY, 10000, ent, qfalse); missile->classname = "atst_side_proj"; missile->s.weapon = WP_ATST_SIDE; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ATST_SIDE_MAIN_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ATST_SIDE_MAIN_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ATST_SIDE_MAIN_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE, ATST_SIDE_MAIN_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; - missile->dflags = DAMAGE_DEATH_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS; + missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - missile->splashDamage = weaponData[WP_ATST_SIDE].splashDamage * ( ent->s.number == 0 ? 1.0f : 0.6f ); + missile->splashDamage = weaponData[WP_ATST_SIDE].splashDamage * (ent->s.number == 0 ? 1.0f : 0.6f); missile->splashRadius = weaponData[WP_ATST_SIDE].splashRadius; // we don't want it to bounce diff --git a/codeJK2/game/wp_blaster_rifle.cpp b/codeJK2/game/wp_blaster_rifle.cpp index 21eaaac51a..fde6cf11ce 100644 --- a/codeJK2/game/wp_blaster_rifle.cpp +++ b/codeJK2/game/wp_blaster_rifle.cpp @@ -33,67 +33,54 @@ along with this program; if not, see . //--------------- //--------------------------------------------------------- -static void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire ) +static void WP_FireBlasterMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire) //--------------------------------------------------------- { - int velocity = BLASTER_VELOCITY; - int damage = !altFire ? weaponData[WP_BLASTER].damage : weaponData[WP_BLASTER].altDamage; + int velocity = BLASTER_VELOCITY; + int damage = !altFire ? weaponData[WP_BLASTER].damage : weaponData[WP_BLASTER].altDamage; // If an enemy is shooting at us, lower the velocity so you have a chance to evade - if ( ent->client && ent->client->ps.clientNum != 0 ) - { - if ( g_spskill->integer < 2 ) - { + if (ent->client && ent->client->ps.clientNum != 0) { + if (g_spskill->integer < 2) { velocity *= BLASTER_NPC_VEL_CUT; - } - else - { + } else { velocity *= BLASTER_NPC_HARD_VEL_CUT; } } - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + gentity_t *missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "blaster_proj"; missile->s.weapon = WP_BLASTER; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = BLASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BLASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BLASTER_NPC_DAMAGE_HARD; } } -// if ( ent->client ) -// { -// if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } -// } + // if ( ent->client ) + // { + // if ( ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( altFire ) - { + if (altFire) { missile->methodOfDeath = MOD_BLASTER_ALT; - } - else - { + } else { missile->methodOfDeath = MOD_BLASTER; } missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; @@ -103,40 +90,32 @@ static void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qbo } //--------------------------------------------------------- -void WP_FireBlaster( gentity_t *ent, qboolean alt_fire ) +void WP_FireBlaster(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( wpFwd, angs ); + vectoangles(wpFwd, angs); - if ( alt_fire ) - { + if (alt_fire) { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; - } - else - { + angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_ALT_SPREAD; + } else { // Troopers use their aim values as well as the gun's inherent inaccuracy // so check for all classes of stormtroopers and anyone else that has aim error - if ( ent->client && ent->NPC && - ( ent->client->NPC_class == CLASS_STORMTROOPER || - ent->client->NPC_class == CLASS_SWAMPTROOPER ) ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - } - else - { + if (ent->client && ent->NPC && (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER)) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + } else { // add some slop to the main-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_MAIN_SPREAD; } } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - WP_FireBlasterMissile( ent, wpMuzzle, dir, alt_fire ); + WP_FireBlasterMissile(ent, wpMuzzle, dir, alt_fire); } \ No newline at end of file diff --git a/codeJK2/game/wp_bot_laser.cpp b/codeJK2/game/wp_bot_laser.cpp index 3aee2449ea..ce9ff701f4 100644 --- a/codeJK2/game/wp_bot_laser.cpp +++ b/codeJK2/game/wp_bot_laser.cpp @@ -30,10 +30,10 @@ along with this program; if not, see . // Bot Laser //--------------------------------------------------------- -void WP_BotLaser( gentity_t *ent ) +void WP_BotLaser(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *missile = CreateMissile( wpMuzzle, wpFwd, BRYAR_PISTOL_VEL, 10000, ent ); + gentity_t *missile = CreateMissile(wpMuzzle, wpFwd, BRYAR_PISTOL_VEL, 10000, ent); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; diff --git a/codeJK2/game/wp_bowcaster.cpp b/codeJK2/game/wp_bowcaster.cpp index c4072a0777..5318505ff2 100644 --- a/codeJK2/game/wp_bowcaster.cpp +++ b/codeJK2/game/wp_bowcaster.cpp @@ -32,87 +32,75 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_BowcasterMainFire( gentity_t *ent ) +static void WP_BowcasterMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_BOWCASTER].damage, count; - float vel; - vec3_t angs, dir, start; - gentity_t *missile; + int damage = weaponData[WP_BOWCASTER].damage, count; + float vel; + vec3_t angs, dir, start; + gentity_t *missile; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = BOWCASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BOWCASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BOWCASTER_NPC_DAMAGE_HARD; } } - count = ( level.time - ent->client->ps.weaponChargeTime ) / BOWCASTER_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / BOWCASTER_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if ( !(count & 1 )) - { + if (!(count & 1)) { // if we aren't odd, knock us down a level count--; } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - for ( int i = 0; i < count; i++ ) - { + for (int i = 0; i < count; i++) { // create a range of different velocities - vel = BOWCASTER_VELOCITY * ( Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f ); + vel = BOWCASTER_VELOCITY * (Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f); - vectoangles( wpFwd, angs ); + vectoangles(wpFwd, angs); // add some slop to the fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BOWCASTER_ALT_SPREAD * 0.2f; - angs[YAW] += ((i+0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD ); - if ( ent->NPC ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); + angs[YAW] += ((i + 0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD); + if (ent->NPC) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); } - - AngleVectors( angs, dir, NULL, NULL ); - missile = CreateMissile( start, dir, vel, 10000, ent ); + AngleVectors(angs, dir, NULL, NULL); + + missile = CreateMissile(start, dir, vel, 10000, ent); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// missile->flags |= FL_OVERCHARGED; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // missile->flags |= FL_OVERCHARGED; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -128,46 +116,40 @@ static void WP_BowcasterMainFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_BowcasterAltFire( gentity_t *ent ) +static void WP_BowcasterAltFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_BOWCASTER].altDamage; + vec3_t start; + int damage = weaponData[WP_BOWCASTER].altDamage; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, wpFwd, BOWCASTER_VELOCITY, 10000, ent, qtrue ); + gentity_t *missile = CreateMissile(start, wpFwd, BOWCASTER_VELOCITY, 10000, ent, qtrue); missile->classname = "bowcaster_alt_proj"; missile->s.weapon = WP_BOWCASTER; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = BOWCASTER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = BOWCASTER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = BOWCASTER_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->s.eFlags |= EF_BOUNCE; missile->bounceCount = 3; @@ -181,15 +163,12 @@ static void WP_BowcasterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireBowcaster( gentity_t *ent, qboolean alt_fire ) +void WP_FireBowcaster(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_BowcasterAltFire( ent ); - } - else - { - WP_BowcasterMainFire( ent ); + if (alt_fire) { + WP_BowcasterAltFire(ent); + } else { + WP_BowcasterMainFire(ent); } } \ No newline at end of file diff --git a/codeJK2/game/wp_bryar_pistol.cpp b/codeJK2/game/wp_bryar_pistol.cpp index c81c4f18d8..c0d39b3021 100644 --- a/codeJK2/game/wp_bryar_pistol.cpp +++ b/codeJK2/game/wp_bryar_pistol.cpp @@ -33,50 +33,42 @@ along with this program; if not, see . //--------------- //--------------------------------------------------------- -void WP_FireBryarPistol( gentity_t *ent, qboolean alt_fire ) +void WP_FireBryarPistol(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - int damage = !alt_fire ? weaponData[ent->s.weapon].damage : weaponData[ent->s.weapon].altDamage; + vec3_t start; + int damage = !alt_fire ? weaponData[ent->s.weapon].damage : weaponData[ent->s.weapon].altDamage; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - if ( ent->NPC && ent->NPC->currentAim < 5 ) - { - vec3_t angs; + if (ent->NPC && ent->NPC->currentAim < 5) { + vec3_t angs; - vectoangles( wpFwd, angs ); + vectoangles(wpFwd, angs); - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - {//*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f));//was 0.5f - } - else - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * ((5-ent->NPC->currentAim)*0.25f) ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { //*sigh*, hack to make impworkers less accurate without affecteing imperial officer accuracy + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (BLASTER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); // was 0.5f + } else { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * ((5 - ent->NPC->currentAim) * 0.25f)); } - AngleVectors( angs, wpFwd, NULL, NULL ); + AngleVectors(angs, wpFwd, NULL, NULL); } - gentity_t *missile = CreateMissile( start, wpFwd, BRYAR_PISTOL_VEL, 10000, ent, alt_fire ); + gentity_t *missile = CreateMissile(start, wpFwd, BRYAR_PISTOL_VEL, 10000, ent, alt_fire); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; - if ( alt_fire ) - { - int count = ( level.time - ent->client->ps.weaponChargeTime ) / BRYAR_CHARGE_UNIT; + if (alt_fire) { + int count = (level.time - ent->client->ps.weaponChargeTime) / BRYAR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } @@ -84,22 +76,19 @@ void WP_FireBryarPistol( gentity_t *ent, qboolean alt_fire ) missile->count = count; // this will get used in the projectile rendering code to make a beefier effect } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( alt_fire ) - { + if (alt_fire) { missile->methodOfDeath = MOD_BRYAR_ALT; - } - else - { + } else { missile->methodOfDeath = MOD_BRYAR; } diff --git a/codeJK2/game/wp_demp2.cpp b/codeJK2/game/wp_demp2.cpp index b7cca42dc2..364f54656c 100644 --- a/codeJK2/game/wp_demp2.cpp +++ b/codeJK2/game/wp_demp2.cpp @@ -33,46 +33,40 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_DEMP2_MainFire( gentity_t *ent ) +static void WP_DEMP2_MainFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_DEMP2].damage; + vec3_t start; + int damage = weaponData[WP_DEMP2].damage; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, wpFwd, DEMP2_VELOCITY, 10000, ent ); + gentity_t *missile = CreateMissile(start, wpFwd, DEMP2_VELOCITY, 10000, ent); missile->classname = "demp2_proj"; missile->s.weapon = WP_DEMP2; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = DEMP2_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = DEMP2_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = DEMP2_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE); + VectorScale(missile->maxs, -1, missile->mins); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -85,50 +79,40 @@ static void WP_DEMP2_MainFire( gentity_t *ent ) // NOTE: this is 100% for the demp2 alt-fire effect, so changes to the visual effect will affect game side demp2 code //-------------------------------------------------- -void DEMP2_AltRadiusDamage( gentity_t *ent ) -{ - float frac = ( level.time - ent->fx_time ) / 1300.0f; // synchronize with demp2 effect - float dist, radius; - gentity_t *gent; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities, i, e; - vec3_t mins, maxs; - vec3_t v, dir; +void DEMP2_AltRadiusDamage(gentity_t *ent) { + float frac = (level.time - ent->fx_time) / 1300.0f; // synchronize with demp2 effect + float dist, radius; + gentity_t *gent; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities, i, e; + vec3_t mins, maxs; + vec3_t v, dir; frac *= frac * frac; // yes, this is completely ridiculous...but it causes the shell to grow slowly then "explode" at the end - + radius = frac * 200.0f; // 200 is max radius...the model is aprox. 100 units tall...the fx draw code mults. this by 2. - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = ent->currentOrigin[i] - radius; maxs[i] = ent->currentOrigin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - gent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + gent = entityList[e]; - if ( !gent->takedamage || !gent->contents ) - { + if (!gent->takedamage || !gent->contents) { continue; } // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( ent->currentOrigin[i] < gent->absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (ent->currentOrigin[i] < gent->absmin[i]) { v[i] = gent->absmin[i] - ent->currentOrigin[i]; - } - else if ( ent->currentOrigin[i] > gent->absmax[i] ) - { + } else if (ent->currentOrigin[i] > gent->absmax[i]) { v[i] = ent->currentOrigin[i] - gent->absmax[i]; - } - else - { + } else { v[i] = 0; } } @@ -136,54 +120,51 @@ void DEMP2_AltRadiusDamage( gentity_t *ent ) // shape is an ellipsoid, so cut vertical distance in half` v[2] *= 0.5f; - dist = VectorLength( v ); + dist = VectorLength(v); - if ( dist >= radius ) - { + if (dist >= radius) { // shockwave hasn't hit them yet continue; } - if ( dist < ent->radius ) - { + if (dist < ent->radius) { // shockwave has already hit this thing... continue; } - VectorCopy( gent->currentOrigin, v ); - VectorSubtract( v, ent->currentOrigin, dir); + VectorCopy(gent->currentOrigin, v); + VectorSubtract(v, ent->currentOrigin, dir); // push the center of mass higher than the origin so players get knocked into the air more dir[2] += 12; - G_Damage( gent, ent, ent->owner, dir, ent->currentOrigin, weaponData[WP_DEMP2].altDamage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath ); - if ( gent->takedamage && gent->client ) - { - gent->s.powerups |= ( 1 << PW_SHOCKED ); + G_Damage(gent, ent, ent->owner, dir, ent->currentOrigin, weaponData[WP_DEMP2].altDamage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath); + if (gent->takedamage && gent->client) { + gent->s.powerups |= (1 << PW_SHOCKED); gent->client->ps.powerups[PW_SHOCKED] = level.time + 2000; } } - // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge is + // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge + // is ent->radius = radius; - if ( frac < 1.0f ) - { + if (frac < 1.0f) { // shock is still happening so continue letting it expand ent->nextthink = level.time + 50; } } - //--------------------------------------------------------- -void DEMP2_AltDetonate( gentity_t *ent ) +void DEMP2_AltDetonate(gentity_t *ent) //--------------------------------------------------------- { - G_SetOrigin( ent, ent->currentOrigin ); + G_SetOrigin(ent, ent->currentOrigin); - // start the effects, unfortunately, I wanted to do some custom things that I couldn't easily do with the fx system, so part of it uses an event and localEntities - G_PlayEffect( "demp2/altDetonate", ent->currentOrigin, ent->pos1 ); - G_AddEvent( ent, EV_DEMP2_ALT_IMPACT, ent->count * 2 ); + // start the effects, unfortunately, I wanted to do some custom things that I couldn't easily do with the fx system, so part of it uses an event and + // localEntities + G_PlayEffect("demp2/altDetonate", ent->currentOrigin, ent->pos1); + G_AddEvent(ent, EV_DEMP2_ALT_IMPACT, ent->count * 2); ent->fx_time = level.time; ent->radius = 0; @@ -193,39 +174,36 @@ void DEMP2_AltDetonate( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_DEMP2_AltFire( gentity_t *ent ) +static void WP_DEMP2_AltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_DEMP2].altDamage; - int count; - vec3_t start; - trace_t tr; + int damage = weaponData[WP_DEMP2].altDamage; + int count; + vec3_t start; + trace_t tr; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - count = ( level.time - ent->client->ps.weaponChargeTime ) / DEMP2_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / DEMP2_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 3 ) - { + } else if (count > 3) { count = 3; } - damage *= ( 1 + ( count * ( count - 1 )));// yields damage of 12,36,84...gives a higher bonus for longer charge + damage *= (1 + (count * (count - 1))); // yields damage of 12,36,84...gives a higher bonus for longer charge // the shot can travel a whopping 4096 units in 1 second. Note that the shot will auto-detonate at 4096 units...we'll see if this looks cool or not - gentity_t *missile = CreateMissile( start, wpFwd, DEMP2_ALT_RANGE, 1000, ent, qtrue ); + gentity_t *missile = CreateMissile(start, wpFwd, DEMP2_ALT_RANGE, 1000, ent, qtrue); // letting it know what the charge size is. missile->count = count; -// missile->speed = missile->nextthink; - VectorCopy( tr.plane.normal, missile->pos1 ); + // missile->speed = missile->nextthink; + VectorCopy(tr.plane.normal, missile->pos1); missile->classname = "demp2_alt_proj"; missile->s.weapon = WP_DEMP2; @@ -244,15 +222,12 @@ static void WP_DEMP2_AltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireDEMP2( gentity_t *ent, qboolean alt_fire ) +void WP_FireDEMP2(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_DEMP2_AltFire( ent ); - } - else - { - WP_DEMP2_MainFire( ent ); + if (alt_fire) { + WP_DEMP2_AltFire(ent); + } else { + WP_DEMP2_MainFire(ent); } } \ No newline at end of file diff --git a/codeJK2/game/wp_det_pack.cpp b/codeJK2/game/wp_det_pack.cpp index fadbd1bfde..00b20b679e 100644 --- a/codeJK2/game/wp_det_pack.cpp +++ b/codeJK2/game/wp_det_pack.cpp @@ -33,7 +33,7 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) +void charge_stick(gentity_t *self, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { self->s.eType = ET_GENERAL; @@ -46,8 +46,8 @@ void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->e_DieFunc = dieF_WP_ExplosiveDie; - VectorSet( self->maxs, 10, 10, 10 ); - VectorScale( self->maxs, -1, self->mins ); + VectorSet(self->maxs, 10, 10, 10); + VectorScale(self->maxs, -1, self->mins); self->activator = self->owner; self->owner = NULL; @@ -56,25 +56,25 @@ void charge_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->e_ThinkFunc = thinkF_NULL; self->nextthink = -1; - WP_Stick( self, trace, 1.0f ); + WP_Stick(self, trace, 1.0f); } //--------------------------------------------------------- -static void WP_DropDetPack( gentity_t *self, vec3_t start, vec3_t dir ) +static void WP_DropDetPack(gentity_t *self, vec3_t start, vec3_t dir) //--------------------------------------------------------- { // Chucking a new one - AngleVectors( self->client->ps.viewangles, wpFwd, wpVright, wpUp ); - CalcMuzzlePoint( self, wpFwd, wpVright, wpUp, wpMuzzle, 0 ); - VectorNormalize( wpFwd ); - VectorMA( wpMuzzle, -4, wpFwd, wpMuzzle ); + AngleVectors(self->client->ps.viewangles, wpFwd, wpVright, wpUp); + CalcMuzzlePoint(self, wpFwd, wpVright, wpUp, wpMuzzle, 0); + VectorNormalize(wpFwd); + VectorMA(wpMuzzle, -4, wpFwd, wpMuzzle); - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( self, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(self, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, wpFwd, 300, 10000, self, qfalse ); + gentity_t *missile = CreateMissile(start, wpFwd, 300, 10000, self, qfalse); - missile->fxID = G_EffectIndex( "detpack/explosion" ); // if we set an explosion effect, explode death can use that instead + missile->fxID = G_EffectIndex("detpack/explosion"); // if we set an explosion effect, explode death can use that instead missile->classname = "detpack"; missile->s.weapon = WP_DET_PACK; @@ -89,58 +89,52 @@ static void WP_DropDetPack( gentity_t *self, vec3_t start, vec3_t dir ) missile->splashDamage = weaponData[WP_DET_PACK].splashDamage; missile->splashRadius = weaponData[WP_DET_PACK].splashRadius; - missile->splashMethodOfDeath = MOD_DETPACK;// ?SPLASH; + missile->splashMethodOfDeath = MOD_DETPACK; // ?SPLASH; - missile->clipmask = (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP);//MASK_SHOT; + missile->clipmask = (CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP); // MASK_SHOT; // we don't want it to ever bounce missile->bounceCount = 0; missile->s.radius = 30; - VectorSet( missile->s.modelScale, 1.0f, 1.0f, 1.0f ); - gi.G2API_InitGhoul2Model( missile->ghoul2, weaponData[WP_DET_PACK].missileMdl, G_ModelIndex( weaponData[WP_DET_PACK].missileMdl ), NULL_HANDLE, NULL_HANDLE, 0, 0); + VectorSet(missile->s.modelScale, 1.0f, 1.0f, 1.0f); + gi.G2API_InitGhoul2Model(missile->ghoul2, weaponData[WP_DET_PACK].missileMdl, G_ModelIndex(weaponData[WP_DET_PACK].missileMdl), NULL_HANDLE, NULL_HANDLE, 0, + 0); - AddSoundEvent( NULL, missile->currentOrigin, 128, AEL_MINOR, qtrue ); - AddSightEvent( NULL, missile->currentOrigin, 128, AEL_SUSPICIOUS, 10 ); + AddSoundEvent(NULL, missile->currentOrigin, 128, AEL_MINOR, qtrue); + AddSightEvent(NULL, missile->currentOrigin, 128, AEL_SUSPICIOUS, 10); } //--------------------------------------------------------- -void WP_FireDetPack( gentity_t *ent, qboolean alt_fire ) +void WP_FireDetPack(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - if ( alt_fire ) - { - if ( ent->client->ps.eFlags & EF_PLANTED_CHARGE ) - { + if (alt_fire) { + if (ent->client->ps.eFlags & EF_PLANTED_CHARGE) { gentity_t *found = NULL; // loop through all ents and blow the crap out of them! - while (( found = G_Find( found, FOFS( classname ), "detpack" )) != NULL ) - { - if ( found->activator == ent ) - { - VectorCopy( found->currentOrigin, found->s.origin ); + while ((found = G_Find(found, FOFS(classname), "detpack")) != NULL) { + if (found->activator == ent) { + VectorCopy(found->currentOrigin, found->s.origin); found->e_ThinkFunc = thinkF_WP_Explode; found->nextthink = level.time + 100 + Q_flrand(0.0f, 1.0f) * 100; - G_Sound( found, G_SoundIndex( "sound/weapons/detpack/warning.wav" )); + G_Sound(found, G_SoundIndex("sound/weapons/detpack/warning.wav")); // would be nice if this actually worked? - AddSoundEvent( NULL, found->currentOrigin, found->splashRadius*2, AEL_DANGER ); - AddSightEvent( NULL, found->currentOrigin, found->splashRadius*2, AEL_DISCOVERED, 100 ); + AddSoundEvent(NULL, found->currentOrigin, found->splashRadius * 2, AEL_DANGER); + AddSightEvent(NULL, found->currentOrigin, found->splashRadius * 2, AEL_DISCOVERED, 100); } } ent->client->ps.eFlags &= ~EF_PLANTED_CHARGE; } - } - else - { - WP_DropDetPack( ent, wpMuzzle, wpFwd ); + } else { + WP_DropDetPack(ent, wpMuzzle, wpFwd); ent->client->ps.eFlags |= EF_PLANTED_CHARGE; } diff --git a/codeJK2/game/wp_disruptor.cpp b/codeJK2/game/wp_disruptor.cpp index 4cea823d87..f7e20e590f 100644 --- a/codeJK2/game/wp_disruptor.cpp +++ b/codeJK2/game/wp_disruptor.cpp @@ -31,22 +31,20 @@ along with this program; if not, see . //--------------------- // Tenloss Disruptor //--------------------- -extern qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ); -int G_GetHitLocFromTrace( trace_t *trace, int mod ) -{ +extern qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod); +int G_GetHitLocFromTrace(trace_t *trace, int mod) { int hitLoc = HL_NONE; - for (int i=0; i < MAX_G2_COLLISIONS; i++) - { - if ( trace->G2CollisionMap[i].mEntityNum == -1 ) - { + for (int i = 0; i < MAX_G2_COLLISIONS; i++) { + if (trace->G2CollisionMap[i].mEntityNum == -1) { break; } CCollisionRecord &coll = trace->G2CollisionMap[i]; - if ( (coll.mFlags & G2_FRONTFACE) ) - { - G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &hitLoc, coll.mCollisionPosition, NULL, NULL, mod ); - //we only want the first "entrance wound", so break + if ((coll.mFlags & G2_FRONTFACE)) { + G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), &hitLoc, + coll.mCollisionPosition, NULL, NULL, mod); + // we only want the first "entrance wound", so break break; } } @@ -54,20 +52,18 @@ int G_GetHitLocFromTrace( trace_t *trace, int mod ) } //--------------------------------------------------------- -static void WP_DisruptorMainFire( gentity_t *ent ) +static void WP_DisruptorMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_DISRUPTOR].damage; - qboolean render_impact = qtrue; - vec3_t start, end, spot; - trace_t tr; - gentity_t *traceEnt = NULL, *tent; - float dist, shotDist, shotRange = 8192; - - if ( ent->NPC ) - { - switch ( g_spskill->integer ) - { + int damage = weaponData[WP_DISRUPTOR].damage; + qboolean render_impact = qtrue; + vec3_t start, end, spot; + trace_t tr; + gentity_t *traceEnt = NULL, *tent; + float dist, shotDist, shotRange = 8192; + + if (ent->NPC) { + switch (g_spskill->integer) { case 0: damage = DISRUPTOR_NPC_MAIN_DAMAGE_EASY; break; @@ -81,108 +77,94 @@ static void WP_DisruptorMainFire( gentity_t *ent ) } } - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - VectorMA( start, shotRange, wpFwd, end ); + VectorMA(start, shotRange, wpFwd, end); int ignore = ent->s.number; int traces = 0; - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - gi.trace( &tr, start, NULL, NULL, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0 ); + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + gi.trace(&tr, start, NULL, NULL, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0); traceEnt = &g_entities[tr.entityNum]; - if ( traceEnt && traceEnt->s.weapon == WP_SABER )//&& traceEnt->NPC - {//FIXME: need a more reliable way to know we hit a jedi? - if ( Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + if (traceEnt && traceEnt->s.weapon == WP_SABER) //&& traceEnt->NPC + { // FIXME: need a more reliable way to know we hit a jedi? + if (Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE)) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_MAIN_SHOT ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_MAIN_SHOT); tent->svFlags |= SVF_BROADCAST; - VectorCopy( wpMuzzle, tent->s.origin2 ); + VectorCopy(wpMuzzle, tent->s.origin2); - if ( render_impact ) - { - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { + if (render_impact) { + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "disruptor/flesh_impact" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("disruptor/flesh_impact"), tr.endpos, tr.plane.normal); - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - { + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { ent->client->ps.persistant[PERS_ACCURACY_HITS]++; - } - - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_DISRUPTOR ); - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, wpFwd, tr.endpos, 3, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc ); } - else - { - G_Damage( traceEnt, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc ); + + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_DISRUPTOR); + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, wpFwd, tr.endpos, 3, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc); + } else { + G_Damage(traceEnt, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_DEATH_KNOCKBACK, MOD_DISRUPTOR, hitLoc); } - } - else - { - G_PlayEffect( G_EffectIndex( "disruptor/wall_impact" ), tr.endpos, tr.plane.normal ); + } else { + G_PlayEffect(G_EffectIndex("disruptor/wall_impact"), tr.endpos, tr.plane.normal); } } shotDist = shotRange * tr.fraction; - for ( dist = 0; dist < shotDist; dist += 64 ) - { - //FIXME: on a really long shot, this could make a LOT of alerts in one frame... - VectorMA( start, dist, wpFwd, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + for (dist = 0; dist < shotDist; dist += 64) { + // FIXME: on a really long shot, this could make a LOT of alerts in one frame... + VectorMA(start, dist, wpFwd, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } - VectorMA( start, shotDist-4, wpFwd, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + VectorMA(start, shotDist - 4, wpFwd, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } //--------------------------------------------------------- -void WP_DisruptorAltFire( gentity_t *ent ) +void WP_DisruptorAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = weaponData[WP_DISRUPTOR].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; - qboolean render_impact = qtrue; - vec3_t start, end; - vec3_t muzzle2, spot, dir; - trace_t tr; - gentity_t *traceEnt, *tent; - float dist, shotDist, shotRange = 8192; - qboolean hitDodged = qfalse, fullCharge = qfalse; + int damage = weaponData[WP_DISRUPTOR].altDamage, skip, traces = DISRUPTOR_ALT_TRACES; + qboolean render_impact = qtrue; + vec3_t start, end; + vec3_t muzzle2, spot, dir; + trace_t tr; + gentity_t *traceEnt, *tent; + float dist, shotDist, shotRange = 8192; + qboolean hitDodged = qfalse, fullCharge = qfalse; - VectorCopy( wpMuzzle, muzzle2 ); // making a backup copy + VectorCopy(wpMuzzle, muzzle2); // making a backup copy // The trace start will originate at the eye so we can ensure that it hits the crosshair. - if ( ent->NPC ) - { - switch ( g_spskill->integer ) - { + if (ent->NPC) { + switch (g_spskill->integer) { case 0: damage = DISRUPTOR_NPC_ALT_DAMAGE_EASY; break; @@ -194,169 +176,147 @@ void WP_DisruptorAltFire( gentity_t *ent ) damage = DISRUPTOR_NPC_ALT_DAMAGE_HARD; break; } - VectorCopy( wpMuzzle, start ); + VectorCopy(wpMuzzle, start); fullCharge = qtrue; - } - else - { - VectorCopy( ent->client->renderInfo.eyePoint, start ); - AngleVectors( ent->client->renderInfo.eyeAngles, wpFwd, NULL, NULL ); + } else { + VectorCopy(ent->client->renderInfo.eyePoint, start); + AngleVectors(ent->client->renderInfo.eyeAngles, wpFwd, NULL, NULL); // don't let NPC's do charging - int count = ( level.time - ent->client->ps.weaponChargeTime - 50 ) / DISRUPTOR_CHARGE_UNIT; + int count = (level.time - ent->client->ps.weaponChargeTime - 50) / DISRUPTOR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count >= 10 ) - { + } else if (count >= 10) { count = 10; fullCharge = qtrue; } // more powerful charges go through more things - if ( count < 3 ) - { + if (count < 3) { traces = 1; - } - else if ( count < 6 ) - { + } else if (count < 6) { traces = 2; } - //else do full traces + // else do full traces damage = damage * count + weaponData[WP_DISRUPTOR].damage * 0.5f; // give a boost to low charge shots } skip = ent->s.number; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - for ( int i = 0; i < traces; i++ ) - { - VectorMA( start, shotRange, wpFwd, end ); + for (int i = 0; i < traces; i++) { + VectorMA(start, shotRange, wpFwd, end); - //NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" - //alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter - gi.trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); + // NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" + // alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter + gi.trace(&tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10); // G2_RETURNONHIT, 0 ); - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } - if ( tr.entityNum == ent->s.number ) - { + if (tr.entityNum == ent->s.number) { // should never happen, but basically we don't want to consider a hit to ourselves? // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; #ifdef _DEBUG - gi.Printf( "BAD! Disruptor gun shot somehow traced back and hit the owner!\n" ); + gi.Printf("BAD! Disruptor gun shot somehow traced back and hit the owner!\n"); #endif continue; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_SHOT); tent->svFlags |= SVF_BROADCAST; tent->alt_fire = fullCharge; // mark us so we can alter the effect - VectorCopy( muzzle2, tent->s.origin2 ); + VectorCopy(muzzle2, tent->s.origin2); - if ( tr.fraction >= 1.0f ) - { + if (tr.fraction >= 1.0f) { // draw the beam but don't do anything else break; } traceEnt = &g_entities[tr.entityNum]; - if ( traceEnt && traceEnt->s.weapon == WP_SABER )//&& traceEnt->NPC - {//FIXME: need a more reliable way to know we hit a jedi? - hitDodged = Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ); - //acts like we didn't even hit him + if (traceEnt && traceEnt->s.weapon == WP_SABER) //&& traceEnt->NPC + { // FIXME: need a more reliable way to know we hit a jedi? + hitDodged = Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE); + // acts like we didn't even hit him } - if ( !hitDodged ) - { - if ( render_impact ) - { - if (( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) || !Q_stricmp( traceEnt->classname, "misc_model_breakable" ) - || traceEnt->s.eType == ET_MOVER ) - { + if (!hitDodged) { + if (render_impact) { + if ((tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) || !Q_stricmp(traceEnt->classname, "misc_model_breakable") || + traceEnt->s.eType == ET_MOVER) { // Create a simple impact type mark that doesn't last long in the world - G_PlayEffect( G_EffectIndex( "disruptor/alt_hit" ), tr.endpos, tr.plane.normal ); + G_PlayEffect(G_EffectIndex("disruptor/alt_hit"), tr.endpos, tr.plane.normal); - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - {//NOTE: hitting multiple ents can still get you over 100% accuracy + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { // NOTE: hitting multiple ents can still get you over 100% accuracy ent->client->ps.persistant[PERS_ACCURACY_HITS]++; - } + } - int hitLoc = G_GetHitLocFromTrace( &tr, MOD_DISRUPTOR ); - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, wpFwd, tr.endpos, 10, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc ); + int hitLoc = G_GetHitLocFromTrace(&tr, MOD_DISRUPTOR); + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, wpFwd, tr.endpos, 10, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, + hitLoc); break; } - G_Damage( traceEnt, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, hitLoc ); - } - else - { - // we only make this mark on things that can't break or move - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_MISS ); + G_Damage(traceEnt, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, fullCharge ? MOD_SNIPER : MOD_DISRUPTOR, + hitLoc); + } else { + // we only make this mark on things that can't break or move + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_MISS); tent->svFlags |= SVF_BROADCAST; - VectorCopy( tr.plane.normal, tent->pos1 ); + VectorCopy(tr.plane.normal, tent->pos1); break; // hit solid, but doesn't take damage, so stop the shot...we _could_ allow it to shoot through walls, might be cool? } - } - else // not rendering impact, must be a skybox or other similar thing? + } else // not rendering impact, must be a skybox or other similar thing? { break; // don't try anymore traces } } // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle2); + VectorCopy(tr.endpos, start); skip = tr.entityNum; hitDodged = qfalse; } // now go along the trail and make sight events - VectorSubtract( tr.endpos, wpMuzzle, dir ); + VectorSubtract(tr.endpos, wpMuzzle, dir); - shotDist = VectorNormalize( dir ); + shotDist = VectorNormalize(dir); - //FIXME: if shoot *really* close to someone, the alert could be way out of their FOV - for ( dist = 0; dist < shotDist; dist += 64 ) - { - //FIXME: on a really long shot, this could make a LOT of alerts in one frame... - VectorMA( wpMuzzle, dist, dir, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + // FIXME: if shoot *really* close to someone, the alert could be way out of their FOV + for (dist = 0; dist < shotDist; dist += 64) { + // FIXME: on a really long shot, this could make a LOT of alerts in one frame... + VectorMA(wpMuzzle, dist, dir, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } - //FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? - VectorMA( start, shotDist-4, wpFwd, spot ); - AddSightEvent( ent, spot, 256, AEL_DISCOVERED, 50 ); + // FIXME: spawn a temp ent that continuously spawns sight alerts here? And 1 sound alert to draw their attention? + VectorMA(start, shotDist - 4, wpFwd, spot); + AddSightEvent(ent, spot, 256, AEL_DISCOVERED, 50); } //--------------------------------------------------------- -void WP_FireDisruptor( gentity_t *ent, qboolean alt_fire ) +void WP_FireDisruptor(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_DisruptorAltFire( ent ); - } - else - { - WP_DisruptorMainFire( ent ); + if (alt_fire) { + WP_DisruptorAltFire(ent); + } else { + WP_DisruptorMainFire(ent); } - G_PlayEffect( G_EffectIndex( "disruptor/line_cap" ), wpMuzzle, wpFwd ); + G_PlayEffect(G_EffectIndex("disruptor/line_cap"), wpMuzzle, wpFwd); } \ No newline at end of file diff --git a/codeJK2/game/wp_emplaced_gun.cpp b/codeJK2/game/wp_emplaced_gun.cpp index 25758823d5..de56343aa4 100644 --- a/codeJK2/game/wp_emplaced_gun.cpp +++ b/codeJK2/game/wp_emplaced_gun.cpp @@ -30,18 +30,18 @@ along with this program; if not, see . // Emplaced Gun //--------------------------------------------------------- -void WP_EmplacedFire( gentity_t *ent ) +void WP_EmplacedFire(gentity_t *ent) //--------------------------------------------------------- { - float damage = weaponData[WP_EMPLACED_GUN].damage * ( ent->NPC ? 0.1f : 1.0f ); - float vel = EMPLACED_VEL * ( ent->NPC ? 0.4f : 1.0f ); + float damage = weaponData[WP_EMPLACED_GUN].damage * (ent->NPC ? 0.1f : 1.0f); + float vel = EMPLACED_VEL * (ent->NPC ? 0.4f : 1.0f); - gentity_t *missile = CreateMissile( wpMuzzle, wpFwd, vel, 10000, ent ); + gentity_t *missile = CreateMissile(wpMuzzle, wpFwd, vel, 10000, ent); missile->classname = "emplaced_proj"; missile->s.weapon = WP_EMPLACED_GUN; - missile->damage = damage; + missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS; missile->methodOfDeath = MOD_EMPLACED; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; @@ -49,8 +49,8 @@ void WP_EmplacedFire( gentity_t *ent ) // do some weird switchery on who the real owner is, we do this so the projectiles don't hit the gun object missile->owner = ent->owner; - VectorSet( missile->maxs, EMPLACED_SIZE, EMPLACED_SIZE, EMPLACED_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, EMPLACED_SIZE, EMPLACED_SIZE, EMPLACED_SIZE); + VectorScale(missile->maxs, -1, missile->mins); // alternate wpMuzzles ent->fxID = !ent->fxID; diff --git a/codeJK2/game/wp_flechette.cpp b/codeJK2/game/wp_flechette.cpp index 79130363a9..af471d1f4d 100644 --- a/codeJK2/game/wp_flechette.cpp +++ b/codeJK2/game/wp_flechette.cpp @@ -33,67 +33,62 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -static void WP_FlechetteMainFire( gentity_t *ent ) +static void WP_FlechetteMainFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t fwd, angs, start; - gentity_t *missile; - float damage = weaponData[WP_FLECHETTE].damage, vel = FLECHETTE_VEL; + vec3_t fwd, angs, start; + gentity_t *missile; + float damage = weaponData[WP_FLECHETTE].damage, vel = FLECHETTE_VEL; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall // If we aren't the player, we will cut the velocity and damage of the shots - if ( ent->s.number ) - { + if (ent->s.number) { damage *= 0.75f; vel *= 0.5f; } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } - for ( int i = 0; i < FLECHETTE_SHOTS; i++ ) - { - vectoangles( wpFwd, angs ); + for (int i = 0; i < FLECHETTE_SHOTS; i++) { + vectoangles(wpFwd, angs); - if ( i == 0 && ent->s.number == 0 ) - { + if (i == 0 && ent->s.number == 0) { // do nothing on the first shot for the player, this one will hit the crosshairs - } - else - { + } else { angs[PITCH] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; } - AngleVectors( angs, fwd, NULL, NULL ); + AngleVectors(angs, fwd, NULL, NULL); - missile = CreateMissile( start, fwd, vel, 10000, ent ); + missile = CreateMissile(start, fwd, vel, 10000, ent); missile->classname = "flech_proj"; missile->s.weapon = WP_FLECHETTE; - VectorSet( missile->maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// missile->flags |= FL_OVERCHARGED; -// } - - missile->dflags = (DAMAGE_DEATH_KNOCKBACK|DAMAGE_EXTRA_KNOCKBACK); - + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // missile->flags |= FL_OVERCHARGED; + // } + + missile->dflags = (DAMAGE_DEATH_KNOCKBACK | DAMAGE_EXTRA_KNOCKBACK); + missile->methodOfDeath = MOD_FLECHETTE; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // we don't want it to bounce forever - missile->bounceCount = Q_irand(1,2); + missile->bounceCount = Q_irand(1, 2); missile->s.eFlags |= EF_BOUNCE_SHRAPNEL; ent->client->sess.missionStats.shotsFired++; @@ -101,47 +96,39 @@ static void WP_FlechetteMainFire( gentity_t *ent ) } //--------------------------------------------------------- -void prox_mine_think( gentity_t *ent ) +void prox_mine_think(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // if it isn't time to auto-explode, do a small proximity check - if ( ent->delay > level.time ) - { - count = G_RadiusList( ent->currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list ); - - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number ) - { + if (ent->delay > level.time) { + count = G_RadiusList(ent->currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list); + + for (int i = 0; i < count; i++) { + if (ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number) { blow = qtrue; break; } } - } - else - { + } else { // well, we must die now blow = qtrue; } - if ( blow ) - { -// G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); + if (blow) { + // G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); ent->e_ThinkFunc = thinkF_WP_Explode; ent->nextthink = level.time + 200; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + 500; } } //--------------------------------------------------------- -void prox_mine_stick( gentity_t *self, gentity_t *other, trace_t *trace ) +void prox_mine_stick(gentity_t *self, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { // turn us into a generic entity so we aren't running missile code @@ -155,21 +142,21 @@ void prox_mine_stick( gentity_t *self, gentity_t *other, trace_t *trace ) self->health = 5; self->e_DieFunc = dieF_WP_ExplosiveDie; - VectorSet( self->maxs, 5, 5, 5 ); - VectorScale( self->maxs, -1, self->mins ); + VectorSet(self->maxs, 5, 5, 5); + VectorScale(self->maxs, -1, self->mins); self->activator = self->owner; self->owner = NULL; - WP_Stick( self, trace ); - + WP_Stick(self, trace); + self->e_ThinkFunc = thinkF_prox_mine_think; self->nextthink = level.time + 450; // sticks for twenty seconds, then auto blows. self->delay = level.time + 20000; - gi.linkentity( self ); + gi.linkentity(self); } /* Old Flechette alt-fire code.... //--------------------------------------------------------- @@ -198,27 +185,27 @@ static void WP_FlechetteProxMine( gentity_t *ent ) missile->clipmask = MASK_SHOT; // we don't want it to bounce forever - missile->bounceCount = 0; + missile->bounceCount = 0; } */ //---------------------------------------------- -void WP_flechette_alt_blow( gentity_t *ent ) +void WP_flechette_alt_blow(gentity_t *ent) //---------------------------------------------- { - EvaluateTrajectory( &ent->s.pos, level.time, ent->currentOrigin ); // Not sure if this is even necessary, but correct origins are cool? + EvaluateTrajectory(&ent->s.pos, level.time, ent->currentOrigin); // Not sure if this is even necessary, but correct origins are cool? - G_RadiusDamage( ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, MOD_EXPLOSIVE_SPLASH ); - G_PlayEffect( "flechette/alt_blow", ent->currentOrigin ); + G_RadiusDamage(ent->currentOrigin, ent->owner, ent->splashDamage, ent->splashRadius, NULL, MOD_EXPLOSIVE_SPLASH); + G_PlayEffect("flechette/alt_blow", ent->currentOrigin); - G_FreeEntity( ent ); + G_FreeEntity(ent); } //------------------------------------------------------------------------------ -static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t *self ) +static void WP_CreateFlechetteBouncyThing(vec3_t start, vec3_t fwd, gentity_t *self) //------------------------------------------------------------------------------ { - gentity_t *missile = CreateMissile( start, fwd, 950 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue ); - + gentity_t *missile = CreateMissile(start, fwd, 950 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue); + missile->e_ThinkFunc = thinkF_WP_flechette_alt_blow; missile->s.weapon = WP_FLECHETTE; @@ -226,8 +213,8 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->mass = 4; // How 'bout we give this thing a size... - VectorSet( missile->mins, -3.0f, -3.0f, -3.0f ); - VectorSet( missile->maxs, 3.0f, 3.0f, 3.0f ); + VectorSet(missile->mins, -3.0f, -3.0f, -3.0f); + VectorSet(missile->maxs, 3.0f, 3.0f, 3.0f); missile->clipmask = MASK_SHOT; missile->clipmask &= ~CONTENTS_CORPSE; @@ -246,43 +233,39 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->methodOfDeath = MOD_FLECHETTE_ALT; missile->splashMethodOfDeath = MOD_FLECHETTE_ALT; - VectorCopy( start, missile->pos2 ); + VectorCopy(start, missile->pos2); } //--------------------------------------------------------- -static void WP_FlechetteAltFire( gentity_t *self ) +static void WP_FlechetteAltFire(gentity_t *self) //--------------------------------------------------------- { - vec3_t dir, fwd, start, angs; + vec3_t dir, fwd, start, angs; - vectoangles( wpFwd, angs ); - VectorCopy( wpMuzzle, start ); + vectoangles(wpFwd, angs); + VectorCopy(wpMuzzle, start); - WP_TraceSetStart( self, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(self, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - for ( int i = 0; i < 2; i++ ) - { - VectorCopy( angs, dir ); + for (int i = 0; i < 2; i++) { + VectorCopy(angs, dir); dir[PITCH] -= Q_flrand(0.0f, 1.0f) * 4 + 8; // make it fly upwards dir[YAW] += Q_flrand(-1.0f, 1.0f) * 2; - AngleVectors( dir, fwd, NULL, NULL ); + AngleVectors(dir, fwd, NULL, NULL); - WP_CreateFlechetteBouncyThing( start, fwd, self ); + WP_CreateFlechetteBouncyThing(start, fwd, self); self->client->sess.missionStats.shotsFired++; } } //--------------------------------------------------------- -void WP_FireFlechette( gentity_t *ent, qboolean alt_fire ) +void WP_FireFlechette(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - if ( alt_fire ) - { - WP_FlechetteAltFire( ent ); - } - else - { - WP_FlechetteMainFire( ent ); + if (alt_fire) { + WP_FlechetteAltFire(ent); + } else { + WP_FlechetteMainFire(ent); } } \ No newline at end of file diff --git a/codeJK2/game/wp_melee.cpp b/codeJK2/game/wp_melee.cpp index a6237c4a3f..4b84c540a3 100644 --- a/codeJK2/game/wp_melee.cpp +++ b/codeJK2/game/wp_melee.cpp @@ -30,44 +30,38 @@ along with this program; if not, see . // Temp melee attack damage routine //--------------------------------------------------------- -void WP_Melee( gentity_t *ent ) +void WP_Melee(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end; - int damage = ent->s.number ? (g_spskill->integer*2)+1 : 3; - float range = ent->s.number ? 64 : 32; + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end; + int damage = ent->s.number ? (g_spskill->integer * 2) + 1 : 3; + float range = ent->s.number ? 64 : 32; - VectorMA( wpMuzzle, range, wpFwd, end ); + VectorMA(wpMuzzle, range, wpFwd, end); - VectorSet( maxs, 6, 6, 6 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 6, 6, 6); + VectorScale(maxs, -1, mins); - gi.trace ( &tr, wpMuzzle, mins, maxs, end, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, wpMuzzle, mins, maxs, end, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); - if ( tr.entityNum >= ENTITYNUM_WORLD ) - { + if (tr.entityNum >= ENTITYNUM_WORLD) { return; } tr_ent = &g_entities[tr.entityNum]; - if ( ent->client && !PM_DroidMelee( ent->client->NPC_class ) ) - { - if ( ent->s.number || ent->alt_fire ) - { - damage *= Q_irand( 2, 3 ); - } - else - { - damage *= Q_irand( 1, 2 ); + if (ent->client && !PM_DroidMelee(ent->client->NPC_class)) { + if (ent->s.number || ent->alt_fire) { + damage *= Q_irand(2, 3); + } else { + damage *= Q_irand(1, 2); } } - if ( tr_ent && tr_ent->takedamage ) - { - G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); - G_Damage( tr_ent, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (tr_ent && tr_ent->takedamage) { + G_Sound(tr_ent, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); + G_Damage(tr_ent, ent, ent, wpFwd, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); } } \ No newline at end of file diff --git a/codeJK2/game/wp_repeater.cpp b/codeJK2/game/wp_repeater.cpp index 9bdddf087b..56358f0a9a 100644 --- a/codeJK2/game/wp_repeater.cpp +++ b/codeJK2/game/wp_repeater.cpp @@ -33,43 +33,37 @@ along with this program; if not, see . //------------------- //--------------------------------------------------------- -static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) +static void WP_RepeaterMainFire(gentity_t *ent, vec3_t dir) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_REPEATER].damage; + vec3_t start; + int damage = weaponData[WP_REPEATER].damage; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, dir, REPEATER_VELOCITY, 10000, ent ); + gentity_t *missile = CreateMissile(start, dir, REPEATER_VELOCITY, 10000, ent); missile->classname = "repeater_proj"; missile->s.weapon = WP_REPEATER; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = REPEATER_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = REPEATER_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = REPEATER_NPC_DAMAGE_HARD; } } -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -81,23 +75,20 @@ static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) } //--------------------------------------------------------- -static void WP_RepeaterAltFire( gentity_t *ent ) +static void WP_RepeaterAltFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_REPEATER].altDamage; + vec3_t start; + int damage = weaponData[WP_REPEATER].altDamage; gentity_t *missile = NULL; - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - if ( ent->client && ent->client->NPC_class == CLASS_GALAKMECH ) - { - missile = CreateMissile( start, ent->client->hiddenDir, ent->client->hiddenDist, 10000, ent, qtrue ); - } - else - { - missile = CreateMissile( start, wpFwd, REPEATER_ALT_VELOCITY, 10000, ent, qtrue ); + if (ent->client && ent->client->NPC_class == CLASS_GALAKMECH) { + missile = CreateMissile(start, ent->client->hiddenDir, ent->client->hiddenDist, 10000, ent, qtrue); + } else { + missile = CreateMissile(start, wpFwd, REPEATER_ALT_VELOCITY, 10000, ent, qtrue); } missile->classname = "repeater_alt_proj"; @@ -105,33 +96,27 @@ static void WP_RepeaterAltFire( gentity_t *ent ) missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = REPEATER_ALT_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = REPEATER_ALT_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = REPEATER_ALT_NPC_DAMAGE_HARD; } } - VectorSet( missile->maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->s.pos.trType = TR_GRAVITY; - missile->s.pos.trDelta[2] += 40.0f; //give a slight boost in the upward direction + missile->s.pos.trDelta[2] += 40.0f; // give a slight boost in the upward direction -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// missile->flags |= FL_OVERCHARGED; -// damage *= 2; -// } + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // missile->flags |= FL_OVERCHARGED; + // damage *= 2; + // } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -146,39 +131,31 @@ static void WP_RepeaterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -void WP_FireRepeater( gentity_t *ent, qboolean alt_fire ) +void WP_FireRepeater(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( wpFwd, angs ); + vectoangles(wpFwd, angs); - if ( alt_fire ) - { - WP_RepeaterAltFire( ent ); - } - else - { + if (alt_fire) { + WP_RepeaterAltFire(ent); + } else { // Troopers use their aim values as well as the gun's inherent inaccuracy // so check for all classes of stormtroopers and anyone else that has aim error - if ( ent->client && ent->NPC && - ( ent->client->NPC_class == CLASS_STORMTROOPER || - ent->client->NPC_class == CLASS_SWAMPTROOPER || - ent->client->NPC_class == CLASS_SHADOWTROOPER ) ) - { - angs[PITCH] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - angs[YAW] += ( Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD+(6-ent->NPC->currentAim)*0.25f) ); - } - else - { + if (ent->client && ent->NPC && + (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_SHADOWTROOPER)) { + angs[PITCH] += (Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + angs[YAW] += (Q_flrand(-1.0f, 1.0f) * (REPEATER_NPC_SPREAD + (6 - ent->NPC->currentAim) * 0.25f)); + } else { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - WP_RepeaterMainFire( ent, dir ); + WP_RepeaterMainFire(ent, dir); } } \ No newline at end of file diff --git a/codeJK2/game/wp_rocket_launcher.cpp b/codeJK2/game/wp_rocket_launcher.cpp index cf7c7b89d5..d55bdaed97 100644 --- a/codeJK2/game/wp_rocket_launcher.cpp +++ b/codeJK2/game/wp_rocket_launcher.cpp @@ -33,25 +33,21 @@ along with this program; if not, see . //----------------------- //--------------------------------------------------------- -void rocketThink( gentity_t *ent ) +void rocketThink(gentity_t *ent) //--------------------------------------------------------- { - vec3_t newdir, targetdir, - wpUp={0,0,1}, right; - vec3_t org; + vec3_t newdir, targetdir, wpUp = {0, 0, 1}, right; + vec3_t org; float dot, dot2; - if ( ent->enemy && ent->enemy->inuse ) - { + if (ent->enemy && ent->enemy->inuse) { float vel = ROCKET_VELOCITY; - VectorCopy( ent->enemy->currentOrigin, org ); + VectorCopy(ent->enemy->currentOrigin, org); org[2] += (ent->enemy->mins[2] + ent->enemy->maxs[2]) * 0.5f; - if ( ent->enemy->client ) - { - switch( ent->enemy->client->NPC_class ) - { + if (ent->enemy->client) { + switch (ent->enemy->client->NPC_class) { case CLASS_ATST: org[2] += 80; break; @@ -66,50 +62,41 @@ void rocketThink( gentity_t *ent ) } } - VectorSubtract( org, ent->currentOrigin, targetdir ); - VectorNormalize( targetdir ); + VectorSubtract(org, ent->currentOrigin, targetdir); + VectorNormalize(targetdir); // Now the rocket can't do a 180 in space, so we'll limit the turn to about 45 degrees. - dot = DotProduct( targetdir, ent->movedir ); + dot = DotProduct(targetdir, ent->movedir); // a dot of 1.0 means right-on-target. - if ( dot < 0.0f ) - { + if (dot < 0.0f) { // Go in the direction opposite, start a 180. - CrossProduct( ent->movedir, wpUp, right ); - dot2 = DotProduct( targetdir, right ); + CrossProduct(ent->movedir, wpUp, right); + dot2 = DotProduct(targetdir, right); - if ( dot2 > 0 ) - { + if (dot2 > 0) { // Turn 45 degrees right. - VectorMA( ent->movedir, 0.3f, right, newdir ); - } - else - { + VectorMA(ent->movedir, 0.3f, right, newdir); + } else { // Turn 45 degrees left. VectorMA(ent->movedir, -0.3f, right, newdir); } // Yeah we've adjusted horizontally, but let's split the difference vertically, so we kinda try to move towards it. - newdir[2] = ( targetdir[2] + ent->movedir[2] ) * 0.5; + newdir[2] = (targetdir[2] + ent->movedir[2]) * 0.5; // slowing down coupled with fairly tight turns can lead us to orbit an enemy..looks bad so don't do it! -// vel *= 0.5f; - } - else if ( dot < 0.70f ) - { + // vel *= 0.5f; + } else if (dot < 0.70f) { // Still a bit off, so we turn a bit softer - VectorMA( ent->movedir, 0.5f, targetdir, newdir ); - } - else - { + VectorMA(ent->movedir, 0.5f, targetdir, newdir); + } else { // getting close, so turn a bit harder - VectorMA( ent->movedir, 0.9f, targetdir, newdir ); + VectorMA(ent->movedir, 0.9f, targetdir, newdir); } // add crazy drunkenness - for ( int i = 0; i < 3; i++ ) - { + for (int i = 0; i < 3; i++) { newdir[i] += Q_flrand(-1.0f, 1.0f) * ent->random * 0.25f; } @@ -117,117 +104,101 @@ void rocketThink( gentity_t *ent ) ent->random *= 0.9f; // Try to crash into the ground if we get close enough to do splash damage - float dis = Distance( ent->currentOrigin, org ); + float dis = Distance(ent->currentOrigin, org); - if ( dis < 128 ) - { + if (dis < 128) { // the closer we get, the more we push the rocket down, heh heh. newdir[2] -= (1.0f - (dis / 128.0f)) * 0.6f; } - VectorNormalize( newdir ); + VectorNormalize(newdir); - VectorScale( newdir, vel * 0.5f, ent->s.pos.trDelta ); - VectorCopy( newdir, ent->movedir ); - SnapVector( ent->s.pos.trDelta ); // save net bandwidth - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorScale(newdir, vel * 0.5f, ent->s.pos.trDelta); + VectorCopy(newdir, ent->movedir); + SnapVector(ent->s.pos.trDelta); // save net bandwidth + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } - ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. + ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. return; } //--------------------------------------------------------- -void WP_FireRocket( gentity_t *ent, qboolean alt_fire ) +void WP_FireRocket(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - int damage = weaponData[WP_ROCKET_LAUNCHER].damage; - float vel = ROCKET_VELOCITY; + vec3_t start; + int damage = weaponData[WP_ROCKET_LAUNCHER].damage; + float vel = ROCKET_VELOCITY; - if ( alt_fire ) - { + if (alt_fire) { vel *= 0.5f; } - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - gentity_t *missile = CreateMissile( start, wpFwd, vel, 10000, ent, alt_fire ); + gentity_t *missile = CreateMissile(start, wpFwd, vel, 10000, ent, alt_fire); missile->classname = "rocket_proj"; missile->s.weapon = WP_ROCKET_LAUNCHER; missile->mass = 10; // Do the damages - if ( ent->s.number != 0 ) - { - if ( g_spskill->integer == 0 ) - { + if (ent->s.number != 0) { + if (g_spskill->integer == 0) { damage = ROCKET_NPC_DAMAGE_EASY; - } - else if ( g_spskill->integer == 1 ) - { + } else if (g_spskill->integer == 1) { damage = ROCKET_NPC_DAMAGE_NORMAL; - } - else - { + } else { damage = ROCKET_NPC_DAMAGE_HARD; } } - if ( alt_fire ) - { - int lockEntNum, lockTime; - if ( ent->NPC && ent->enemy ) - { + if (alt_fire) { + int lockEntNum, lockTime; + if (ent->NPC && ent->enemy) { lockEntNum = ent->enemy->s.number; - lockTime = Q_irand( 600, 1200 ); - } - else - { + lockTime = Q_irand(600, 1200); + } else { lockEntNum = g_rocketLockEntNum; lockTime = g_rocketLockTime; } // we'll consider attempting to lock this little poochie onto some baddie. - if ( (lockEntNum > 0 || (ent->NPC && lockEntNum >= 0)) && lockEntNum < ENTITYNUM_WORLD && lockTime > 0 ) - { + if ((lockEntNum > 0 || (ent->NPC && lockEntNum >= 0)) && lockEntNum < ENTITYNUM_WORLD && lockTime > 0) { // take our current lock time and divide that by 8 wedge slices to get the current lock amount - int dif = ( level.time - lockTime ) / ( 1200.0f / 8.0f ); + int dif = (level.time - lockTime) / (1200.0f / 8.0f); - if ( dif < 0 ) - { + if (dif < 0) { dif = 0; - } - else if ( dif > 8 ) - { + } else if (dif > 8) { dif = 8; } - // if we are fully locked, always take on the enemy. - // Also give a slight advantage to higher, but not quite full charges. + // if we are fully locked, always take on the enemy. + // Also give a slight advantage to higher, but not quite full charges. // Finally, just give any amount of charge a very slight random chance of locking. - if ( dif == 8 || Q_flrand(0.0f, 1.0f) * dif > 2 || Q_flrand(0.0f, 1.0f) > 0.97f ) - { + if (dif == 8 || Q_flrand(0.0f, 1.0f) * dif > 2 || Q_flrand(0.0f, 1.0f) > 0.97f) { missile->enemy = &g_entities[lockEntNum]; - if ( missile->enemy && missile->enemy->inuse )//&& DistanceSquared( missile->currentOrigin, missile->enemy->currentOrigin ) < 262144 && InFOV( missile->currentOrigin, missile->enemy->currentOrigin, missile->enemy->client->ps.viewangles, 45, 45 ) ) + if (missile->enemy && + missile->enemy->inuse) //&& DistanceSquared( missile->currentOrigin, missile->enemy->currentOrigin ) < 262144 && InFOV( + //missile->currentOrigin, missile->enemy->currentOrigin, missile->enemy->client->ps.viewangles, 45, 45 ) ) { vec3_t dir, dir2; - AngleVectors( missile->enemy->currentAngles, dir, NULL, NULL ); - AngleVectors( ent->client->renderInfo.eyeAngles, dir2, NULL, NULL ); + AngleVectors(missile->enemy->currentAngles, dir, NULL, NULL); + AngleVectors(ent->client->renderInfo.eyeAngles, dir2, NULL, NULL); - if ( DotProduct( dir, dir2 ) < 0.0f ) - { - G_StartFlee( missile->enemy, ent, missile->enemy->currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); + if (DotProduct(dir, dir2) < 0.0f) { + G_StartFlee(missile->enemy, ent, missile->enemy->currentOrigin, AEL_DANGER_GREAT, 3000, 5000); } } } } - VectorCopy( wpFwd, missile->movedir ); + VectorCopy(wpFwd, missile->movedir); missile->e_ThinkFunc = thinkF_rocketThink; missile->random = 1.0f; @@ -235,21 +206,18 @@ void WP_FireRocket( gentity_t *ent, qboolean alt_fire ) } // Make it easier to hit things - VectorSet( missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE ); - VectorScale( missile->maxs, -1, missile->mins ); + VectorSet(missile->maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE); + VectorScale(missile->maxs, -1, missile->mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if ( alt_fire ) - { + if (alt_fire) { missile->methodOfDeath = MOD_ROCKET_ALT; - missile->splashMethodOfDeath = MOD_ROCKET_ALT;// ?SPLASH; - } - else - { + missile->splashMethodOfDeath = MOD_ROCKET_ALT; // ?SPLASH; + } else { missile->methodOfDeath = MOD_ROCKET; - missile->splashMethodOfDeath = MOD_ROCKET;// ?SPLASH; + missile->splashMethodOfDeath = MOD_ROCKET; // ?SPLASH; } missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; diff --git a/codeJK2/game/wp_saber.cpp b/codeJK2/game/wp_saber.cpp index 04c5aa2557..a830ce8967 100644 --- a/codeJK2/game/wp_saber.cpp +++ b/codeJK2/game/wp_saber.cpp @@ -31,330 +31,245 @@ along with this program; if not, see . #include "../../code/qcommon/tri_coll_test.h" #define MAX_SABER_VICTIMS 16 -static int victimEntityNum[MAX_SABER_VICTIMS]; -static float totalDmg[MAX_SABER_VICTIMS]; -static vec3_t dmgDir[MAX_SABER_VICTIMS]; -static vec3_t dmgSpot[MAX_SABER_VICTIMS]; -static float dmgFraction[MAX_SABER_VICTIMS]; -static int hitLoc[MAX_SABER_VICTIMS]; -static qboolean hitDismember[MAX_SABER_VICTIMS]; -static int hitDismemberLoc[MAX_SABER_VICTIMS]; -static vec3_t saberHitLocation, saberHitNormal={0,0,1.0}; -static float saberHitFraction; -static float sabersCrossed; -static int saberHitEntity; -static int numVictims = 0; +static int victimEntityNum[MAX_SABER_VICTIMS]; +static float totalDmg[MAX_SABER_VICTIMS]; +static vec3_t dmgDir[MAX_SABER_VICTIMS]; +static vec3_t dmgSpot[MAX_SABER_VICTIMS]; +static float dmgFraction[MAX_SABER_VICTIMS]; +static int hitLoc[MAX_SABER_VICTIMS]; +static qboolean hitDismember[MAX_SABER_VICTIMS]; +static int hitDismemberLoc[MAX_SABER_VICTIMS]; +static vec3_t saberHitLocation, saberHitNormal = {0, 0, 1.0}; +static float saberHitFraction; +static float sabersCrossed; +static int saberHitEntity; +static int numVictims = 0; #define SABER_PITCH_HACK 90 - -extern cvar_t *g_timescale; -extern cvar_t *g_dismemberment; - -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern qboolean G_ClearViewEntity( gentity_t *ent ); -extern void G_SetViewEntity( gentity_t *self, gentity_t *viewEntity ); -extern qboolean G_ControlledByPlayer( gentity_t *self ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void CG_ChangeWeapon( int num ); -extern void G_AngerAlert( gentity_t *self ); -extern void G_ReflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ); -extern int G_CheckLedgeDive( gentity_t *self, float checkDist, vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp ); -extern void G_BounceMissile( gentity_t *ent, trace_t *trace ); -extern qboolean G_PointInBounds( const vec3_t point, const vec3_t mins, const vec3_t maxs ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ); -extern void WP_FireDreadnoughtBeam( gentity_t *ent ); -extern void G_MissileImpacted( gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc=HL_NONE ); -extern evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f ); -extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); -extern void NPC_SetPainEvent( gentity_t *self ); -extern qboolean PM_SwimmingAnim( int anim ); -extern qboolean PM_InAnimForSaberMove( int anim, int saberMove ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SaberInSpecialAttack( int anim ); -extern qboolean PM_SaberInAttack( int move ); -extern qboolean PM_SaberInTransition( int move ); -extern qboolean PM_SaberInStart( int move ); -extern qboolean PM_SaberInTransitionAny( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern int PM_SaberBounceForAttack( int move ); -extern int PM_BrokenParryForAttack( int move ); -extern int PM_KnockawayForParry( int move ); -extern qboolean PM_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_CrouchAnim( int anim ); -extern qboolean PM_SaberInIdle( int move ); -extern qboolean PM_SaberInReflect( int move ); -extern qboolean PM_InSpecialJump( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern int PM_PowerLevelForSaberAnim( playerState_t *ps ); -extern void PM_VelocityForSaberMove( playerState_t *ps, vec3_t throwDir ); -extern qboolean PM_VelocityForBlockedMove( playerState_t *ps, vec3_t throwDir ); -extern int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ); -extern qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ); -extern void Jedi_PlayDeflectSound( gentity_t *self ); -extern void Jedi_PlayBlockedPushSound( gentity_t *self ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern void Jedi_Ambush( gentity_t *self ); -extern qboolean Jedi_SaberBusy( gentity_t *self ); - -void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_SaberInFlightReflectCheck( gentity_t *self, usercmd_t *ucmd ); - -void WP_SaberDrop( gentity_t *self, gentity_t *saber ); -qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ); -void WP_SaberReturn( gentity_t *self, gentity_t *saber ); -void WP_SaberBlock( gentity_t *saber, vec3_t hitloc, qboolean missleBlock ); -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ); -void ForceThrow( gentity_t *self, qboolean pull ); -qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); - -extern cvar_t *g_saberAutoBlocking; -extern cvar_t *g_saberRealisticCombat; +extern cvar_t *g_timescale; +extern cvar_t *g_dismemberment; + +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern qboolean G_ClearViewEntity(gentity_t *ent); +extern void G_SetViewEntity(gentity_t *self, gentity_t *viewEntity); +extern qboolean G_ControlledByPlayer(gentity_t *self); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void CG_ChangeWeapon(int num); +extern void G_AngerAlert(gentity_t *self); +extern void G_ReflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward); +extern int G_CheckLedgeDive(gentity_t *self, float checkDist, vec3_t checkVel, qboolean tryOpposite, qboolean tryPerp); +extern void G_BounceMissile(gentity_t *ent, trace_t *trace); +extern qboolean G_PointInBounds(const vec3_t point, const vec3_t mins, const vec3_t maxs); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone); +extern void WP_FireDreadnoughtBeam(gentity_t *ent); +extern void G_MissileImpacted(gentity_t *ent, gentity_t *other, vec3_t impactPos, vec3_t normal, int hitLoc = HL_NONE); +extern evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist = 0.0f); +extern int PM_PickAnim(gentity_t *self, int minAnim, int maxAnim); +extern void NPC_SetPainEvent(gentity_t *self); +extern qboolean PM_SwimmingAnim(int anim); +extern qboolean PM_InAnimForSaberMove(int anim, int saberMove); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SaberInSpecialAttack(int anim); +extern qboolean PM_SaberInAttack(int move); +extern qboolean PM_SaberInTransition(int move); +extern qboolean PM_SaberInStart(int move); +extern qboolean PM_SaberInTransitionAny(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SpinningSaberAnim(int anim); +extern int PM_SaberBounceForAttack(int move); +extern int PM_BrokenParryForAttack(int move); +extern int PM_KnockawayForParry(int move); +extern qboolean PM_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_CrouchAnim(int anim); +extern qboolean PM_SaberInIdle(int move); +extern qboolean PM_SaberInReflect(int move); +extern qboolean PM_InSpecialJump(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern int PM_PowerLevelForSaberAnim(playerState_t *ps); +extern void PM_VelocityForSaberMove(playerState_t *ps, vec3_t throwDir); +extern qboolean PM_VelocityForBlockedMove(playerState_t *ps, vec3_t throwDir); +extern int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType); +extern qboolean Jedi_DodgeEvasion(gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc); +extern void Jedi_PlayDeflectSound(gentity_t *self); +extern void Jedi_PlayBlockedPushSound(gentity_t *self); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern void Jedi_Ambush(gentity_t *self); +extern qboolean Jedi_SaberBusy(gentity_t *self); + +void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_SaberInFlightReflectCheck(gentity_t *self, usercmd_t *ucmd); + +void WP_SaberDrop(gentity_t *self, gentity_t *saber); +qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir); +void WP_SaberReturn(gentity_t *self, gentity_t *saber); +void WP_SaberBlock(gentity_t *saber, vec3_t hitloc, qboolean missleBlock); +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock); +void ForceThrow(gentity_t *self, qboolean pull); +qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt); + +extern cvar_t *g_saberAutoBlocking; +extern cvar_t *g_saberRealisticCombat; extern int g_crosshairEntNum; -int g_saberFlashTime = 0; -vec3_t g_saberFlashPos = {0,0,0}; - -int forcePowerNeeded[NUM_FORCE_POWERS] = -{ - 0,//FP_HEAL,//instant - 10,//FP_LEVITATION,//hold/duration - 50,//FP_SPEED,//duration - 15,//FP_PUSH,//hold/duration - 15,//FP_PULL,//hold/duration - 20,//FP_TELEPATHY,//instant - 1,//FP_GRIP,//hold/duration - FIXME: 30? - 1,//FP_LIGHTNING,//hold/duration - 20,//FP_SABERTHROW, - 1,//FP_SABER_DEFENSE, - 0,//FP_SABER_OFFENSE, - //NUM_FORCE_POWERS +int g_saberFlashTime = 0; +vec3_t g_saberFlashPos = {0, 0, 0}; + +int forcePowerNeeded[NUM_FORCE_POWERS] = { + 0, // FP_HEAL,//instant + 10, // FP_LEVITATION,//hold/duration + 50, // FP_SPEED,//duration + 15, // FP_PUSH,//hold/duration + 15, // FP_PULL,//hold/duration + 20, // FP_TELEPATHY,//instant + 1, // FP_GRIP,//hold/duration - FIXME: 30? + 1, // FP_LIGHTNING,//hold/duration + 20, // FP_SABERTHROW, + 1, // FP_SABER_DEFENSE, + 0, // FP_SABER_OFFENSE, + // NUM_FORCE_POWERS }; -float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = -{ - JUMP_VELOCITY,//normal jump - 420, - 590, - 840 -}; +float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = {JUMP_VELOCITY, // normal jump + 420, 590, 840}; -float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = -{ - 32,//normal jump (+stepheight+crouchdiff = 66) - 96,//(+stepheight+crouchdiff = 130) - 192,//(+stepheight+crouchdiff = 226) - 384//(+stepheight+crouchdiff = 418) +float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = { + 32, // normal jump (+stepheight+crouchdiff = 66) + 96, //(+stepheight+crouchdiff = 130) + 192, //(+stepheight+crouchdiff = 226) + 384 //(+stepheight+crouchdiff = 418) }; -float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = -{ - 66,//normal jump (32+stepheight(18)+crouchdiff(24) = 74) - 130,//(96+stepheight(18)+crouchdiff(24) = 138) - 226,//(192+stepheight(18)+crouchdiff(24) = 234) - 418//(384+stepheight(18)+crouchdiff(24) = 426) +float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = { + 66, // normal jump (32+stepheight(18)+crouchdiff(24) = 74) + 130, //(96+stepheight(18)+crouchdiff(24) = 138) + 226, //(192+stepheight(18)+crouchdiff(24) = 234) + 418 //(384+stepheight(18)+crouchdiff(24) = 426) }; -float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 384,//256, - 448,//384, - 512 -}; +float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = {0, // none + 384, // 256, + 448, // 384, + 512}; -float forcePushCone[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 1.0f, - 0.8f, - 0.6f -}; +float forcePushCone[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 1.0f, 0.8f, 0.6f}; -float forcePullCone[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 1.0f, - 1.0f, - 0.8f -}; +float forcePullCone[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 1.0f, 1.0f, 0.8f}; -float forceSpeedValue[NUM_FORCE_POWER_LEVELS] = -{ - 1.0f,//none - 0.75f, - 0.5f, - 0.25f -}; +float forceSpeedValue[NUM_FORCE_POWER_LEVELS] = {1.0f, // none + 0.75f, 0.5f, 0.25f}; -float forceSpeedRangeMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//none - 30.0f, - 45.0f, - 60.0f -}; +float forceSpeedRangeMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // none + 30.0f, 45.0f, 60.0f}; -float forceSpeedFOVMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//none - 20.0f, - 30.0f, - 40.0f -}; +float forceSpeedFOVMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // none + 20.0f, 30.0f, 40.0f}; -int forceGripDamage[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 0, - 6, - 9 -}; +int forceGripDamage[NUM_FORCE_POWER_LEVELS] = {0, // none + 0, 6, 9}; -int mindTrickTime[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 5000, - 10000, - 15000 -}; +int mindTrickTime[NUM_FORCE_POWER_LEVELS] = {0, // none + 5000, 10000, 15000}; -//NOTE: keep in synch with table below!!! -int saberThrowDist[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 256, - 400, - 400 -}; +// NOTE: keep in synch with table below!!! +int saberThrowDist[NUM_FORCE_POWER_LEVELS] = {0, // none + 256, 400, 400}; -//NOTE: keep in synch with table above!!! -int saberThrowDistSquared[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 65536, - 160000, - 160000 -}; +// NOTE: keep in synch with table above!!! +int saberThrowDistSquared[NUM_FORCE_POWER_LEVELS] = {0, // none + 65536, 160000, 160000}; -int parryDebounce[NUM_FORCE_POWER_LEVELS] = -{ - 1000000,//if don't even have defense, can't use defense! - 300, - 150, - 50 -}; +int parryDebounce[NUM_FORCE_POWER_LEVELS] = {1000000, // if don't even have defense, can't use defense! + 300, 150, 50}; -float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS] = -{ - 0.0f,//if don't even have offense, can't use offense! - 0.75f, - 1.0f, - 2.0f -}; -//SABER INITIALIZATION====================================================================== +float saberAnimSpeedMod[NUM_FORCE_POWER_LEVELS] = {0.0f, // if don't even have offense, can't use offense! + 0.75f, 1.0f, 2.0f}; +// SABER INITIALIZATION====================================================================== -void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *psWeaponModel ) -{ - if (!psWeaponModel) - { - assert (psWeaponModel); +void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *psWeaponModel) { + if (!psWeaponModel) { + assert(psWeaponModel); return; } - if ( ent && ent->client && ent->client->NPC_class == CLASS_GALAKMECH ) - {//hack for galakmech, no weaponmodel + if (ent && ent->client && ent->client->NPC_class == CLASS_GALAKMECH) { // hack for galakmech, no weaponmodel ent->weaponModel = -1; return; } char weaponModel[MAX_QPATH]; Q_strncpyz(weaponModel, psWeaponModel, sizeof(weaponModel)); - if (char *spot = (char*)Q_stristr(weaponModel, ".md3") ) { - *spot = 0; - spot = (char*)Q_stristr(weaponModel, "_w");//i'm using the in view weapon array instead of scanning the item list, so put the _w back on - if (!spot&&!Q_stristr(weaponModel, "noweap")) - { - Q_strcat (weaponModel, sizeof(weaponModel), "_w"); + if (char *spot = (char *)Q_stristr(weaponModel, ".md3")) { + *spot = 0; + spot = (char *)Q_stristr(weaponModel, "_w"); // i'm using the in view weapon array instead of scanning the item list, so put the _w back on + if (!spot && !Q_stristr(weaponModel, "noweap")) { + Q_strcat(weaponModel, sizeof(weaponModel), "_w"); } - Q_strcat (weaponModel, sizeof(weaponModel), ".glm"); //and change to ghoul2 + Q_strcat(weaponModel, sizeof(weaponModel), ".glm"); // and change to ghoul2 } - if ( ent->playerModel == -1 ) - { + if (ent->playerModel == -1) { return; } // give us a sabre model - ent->weaponModel = gi.G2API_InitGhoul2Model(ent->ghoul2, weaponModel, G_ModelIndex( weaponModel ), NULL_HANDLE, NULL_HANDLE, 0, 0); - if ( ent->weaponModel != -1 ) - { + ent->weaponModel = gi.G2API_InitGhoul2Model(ent->ghoul2, weaponModel, G_ModelIndex(weaponModel), NULL_HANDLE, NULL_HANDLE, 0, 0); + if (ent->weaponModel != -1) { // attach it to the hand - gi.G2API_AttachG2Model(&ent->ghoul2[ent->weaponModel], &ent->ghoul2[ent->playerModel], - ent->handRBolt, ent->playerModel); + gi.G2API_AttachG2Model(&ent->ghoul2[ent->weaponModel], &ent->ghoul2[ent->playerModel], ent->handRBolt, ent->playerModel); // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 gi.G2API_AddBolt(&ent->ghoul2[ent->weaponModel], "*flash"); - //gi.G2API_SetLodBias( &ent->ghoul2[ent->weaponModel], 0 ); + // gi.G2API_SetLodBias( &ent->ghoul2[ent->weaponModel], 0 ); } } //---------------------------------------------------------- -void G_Throw( gentity_t *targ, vec3_t newDir, float push ) +void G_Throw(gentity_t *targ, vec3_t newDir, float push) //---------------------------------------------------------- { - vec3_t kvel; - float mass; + vec3_t kvel; + float mass; - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass { mass = targ->physicsBounce; - } - else - { + } else { mass = 200; } - if ( g_gravity->value > 0 ) - { - VectorScale( newDir, g_knockback->value * (float)push / mass * 0.8, kvel ); + if (g_gravity->value > 0) { + VectorScale(newDir, g_knockback->value * (float)push / mass * 0.8, kvel); kvel[2] = newDir[2] * g_knockback->value * (float)push / mass * 1.5; - } - else - { - VectorScale( newDir, g_knockback->value * (float)push / mass, kvel ); + } else { + VectorScale(newDir, g_knockback->value * (float)push / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = push * 2; - if ( t < 50 ) - { + if (t < 50) { t = 50; } - if ( t > 200 ) - { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -362,125 +277,93 @@ void G_Throw( gentity_t *targ, vec3_t newDir, float push ) } } -int WP_SetSaberModel( gclient_t *client, class_t npcClass ) -{ - if ( client ) - { - switch ( npcClass ) - { - case CLASS_DESANN://Desann +int WP_SetSaberModel(gclient_t *client, class_t npcClass) { + if (client) { + switch (npcClass) { + case CLASS_DESANN: // Desann client->ps.saberModel = "models/weapons2/saber_desann/saber_w.glm"; break; - case CLASS_LUKE://Luke + case CLASS_LUKE: // Luke client->ps.saberModel = "models/weapons2/saber_luke/saber_w.glm"; break; - case CLASS_KYLE://Kyle NPC and player + case CLASS_KYLE: // Kyle NPC and player client->ps.saberModel = "models/weapons2/saber/saber_w.glm"; break; - default://reborn and tavion and everyone else + default: // reborn and tavion and everyone else client->ps.saberModel = "models/weapons2/saber_reborn/saber_w.glm"; break; } - return ( G_ModelIndex( client->ps.saberModel ) ); - } - else - { - switch ( npcClass ) - { - case CLASS_DESANN://Desann - return ( G_ModelIndex( "models/weapons2/saber_desann/saber_w.glm" ) ); + return (G_ModelIndex(client->ps.saberModel)); + } else { + switch (npcClass) { + case CLASS_DESANN: // Desann + return (G_ModelIndex("models/weapons2/saber_desann/saber_w.glm")); break; - case CLASS_LUKE://Luke - return ( G_ModelIndex( "models/weapons2/saber_luke/saber_w.glm" ) ); + case CLASS_LUKE: // Luke + return (G_ModelIndex("models/weapons2/saber_luke/saber_w.glm")); break; - case CLASS_KYLE://Kyle NPC and player - return ( G_ModelIndex( "models/weapons2/saber/saber_w.glm" ) ); + case CLASS_KYLE: // Kyle NPC and player + return (G_ModelIndex("models/weapons2/saber/saber_w.glm")); break; - default://reborn and tavion and everyone else - return ( G_ModelIndex( "models/weapons2/saber_reborn/saber_w.glm" ) ); + default: // reborn and tavion and everyone else + return (G_ModelIndex("models/weapons2/saber_reborn/saber_w.glm")); break; } } } -void WP_SaberInitBladeData( gentity_t *ent ) -{ +void WP_SaberInitBladeData(gentity_t *ent) { gentity_t *saberent; - if ( ent->client ) - { - VectorClear( ent->client->renderInfo.muzzlePoint ); - VectorClear( ent->client->renderInfo.muzzlePointOld ); - //VectorClear( ent->client->renderInfo.muzzlePointNext ); - VectorClear( ent->client->renderInfo.muzzleDir ); - VectorClear( ent->client->renderInfo.muzzleDirOld ); - //VectorClear( ent->client->renderInfo.muzzleDirNext ); + if (ent->client) { + VectorClear(ent->client->renderInfo.muzzlePoint); + VectorClear(ent->client->renderInfo.muzzlePointOld); + // VectorClear( ent->client->renderInfo.muzzlePointNext ); + VectorClear(ent->client->renderInfo.muzzleDir); + VectorClear(ent->client->renderInfo.muzzleDirOld); + // VectorClear( ent->client->renderInfo.muzzleDirNext ); ent->client->ps.saberLengthOld = ent->client->ps.saberLength = 0; ent->client->ps.saberLockEnemy = ENTITYNUM_NONE; ent->client->ps.saberLockTime = 0; - if ( ent->s.number ) - { - if ( ent->client->NPC_class == CLASS_DESANN ) - { + if (ent->s.number) { + if (ent->client->NPC_class == CLASS_DESANN) { ent->client->ps.saberAnimLevel = FORCE_LEVEL_4; - } - else if ( ent->client->NPC_class == CLASS_TAVION ) - { + } else if (ent->client->NPC_class == CLASS_TAVION) { ent->client->ps.saberAnimLevel = FORCE_LEVEL_5; - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && (ent->NPC->rank == RANK_CIVILIAN || ent->NPC->rank == RANK_LT_JG) ) - {//grunt and fencer always uses quick attacks + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && + (ent->NPC->rank == RANK_CIVILIAN || ent->NPC->rank == RANK_LT_JG)) { // grunt and fencer always uses quick attacks ent->client->ps.saberAnimLevel = FORCE_LEVEL_1; - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && (ent->NPC->rank == RANK_CREWMAN || ent->NPC->rank == RANK_ENSIGN) ) - {//acrobat & force-users always use medium attacks + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && + (ent->NPC->rank == RANK_CREWMAN || ent->NPC->rank == RANK_ENSIGN)) { // acrobat & force-users always use medium attacks ent->client->ps.saberAnimLevel = FORCE_LEVEL_2; - } - else if ( ent->client->playerTeam == TEAM_ENEMY && ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//shadowtroopers - ent->client->ps.saberAnimLevel = Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ); - } - else if ( ent->NPC && ent->client->playerTeam == TEAM_ENEMY && ent->NPC->rank == RANK_LT ) - {//boss always starts with strong attacks + } else if (ent->client->playerTeam == TEAM_ENEMY && ent->client->NPC_class == CLASS_SHADOWTROOPER) { // shadowtroopers + ent->client->ps.saberAnimLevel = Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3); + } else if (ent->NPC && ent->client->playerTeam == TEAM_ENEMY && ent->NPC->rank == RANK_LT) { // boss always starts with strong attacks ent->client->ps.saberAnimLevel = FORCE_LEVEL_3; - } - else if ( ent->client->NPC_class == CLASS_KYLE ) - { + } else if (ent->client->NPC_class == CLASS_KYLE) { ent->client->ps.saberAnimLevel = g_entities[0].client->ps.saberAnimLevel; + } else { //? + ent->client->ps.saberAnimLevel = Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3); } - else - {//? - ent->client->ps.saberAnimLevel = Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ); - } - } - else - { - if ( !ent->client->ps.saberAnimLevel ) - {//initialize, but don't reset + } else { + if (!ent->client->ps.saberAnimLevel) { // initialize, but don't reset ent->client->ps.saberAnimLevel = FORCE_LEVEL_2; } cg.saberAnimLevelPending = ent->client->ps.saberAnimLevel; - if ( ent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0 ) - {//let missionStats know that we actually do have the saber, even if we never use it + if (ent->client->sess.missionStats.weaponUsed[WP_SABER] <= 0) { // let missionStats know that we actually do have the saber, even if we never use it ent->client->sess.missionStats.weaponUsed[WP_SABER] = 1; } } ent->client->ps.saberAttackChainCount = 0; - if ( ent->client->NPC_class == CLASS_DESANN ) - {//longer saber + if (ent->client->NPC_class == CLASS_DESANN) { // longer saber ent->client->ps.saberLengthMax = 48; - } - else if ( ent->client->NPC_class == CLASS_REBORN ) - {//shorter saber + } else if (ent->client->NPC_class == CLASS_REBORN) { // shorter saber ent->client->ps.saberLengthMax = 32; - } - else - {//standard saber length + } else { // standard saber length ent->client->ps.saberLengthMax = 40; } - if ( ent->client->ps.saberEntityNum <= 0 || ent->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - { + if (ent->client->ps.saberEntityNum <= 0 || ent->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { saberent = G_Spawn(); ent->client->ps.saberEntityNum = saberent->s.number; saberent->classname = "lightsaber"; @@ -492,27 +375,27 @@ void WP_SaberInitBladeData( gentity_t *ent ) saberent->s.otherEntityNum = ent->s.number; saberent->clipmask = MASK_SOLID | CONTENTS_LIGHTSABER; - saberent->contents = CONTENTS_LIGHTSABER;//|CONTENTS_SHOTCLIP; + saberent->contents = CONTENTS_LIGHTSABER; //|CONTENTS_SHOTCLIP; - VectorSet( saberent->mins, -3.0f, -3.0f, -3.0f ); - VectorSet( saberent->maxs, 3.0f, 3.0f, 3.0f ); - saberent->mass = 10;//necc? + VectorSet(saberent->mins, -3.0f, -3.0f, -3.0f); + VectorSet(saberent->maxs, 3.0f, 3.0f, 3.0f); + saberent->mass = 10; // necc? saberent->s.eFlags |= EF_NODRAW; saberent->svFlags |= SVF_NOCLIENT; -/* -Ghoul2 Insert Start -*/ - //FIXME: get saberModel from NPCs.cfg for NPCs? - saberent->s.modelindex = WP_SetSaberModel( ent->client, ent->client->NPC_class ); - gi.G2API_InitGhoul2Model( saberent->ghoul2, ent->client->ps.saberModel, saberent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0 ); + /* + Ghoul2 Insert Start + */ + // FIXME: get saberModel from NPCs.cfg for NPCs? + saberent->s.modelindex = WP_SetSaberModel(ent->client, ent->client->NPC_class); + gi.G2API_InitGhoul2Model(saberent->ghoul2, ent->client->ps.saberModel, saberent->s.modelindex, NULL_HANDLE, NULL_HANDLE, 0, 0); // set up a bolt on the end so we can get where the sabre muzzle is - we can assume this is always bolt 0 - gi.G2API_AddBolt( &saberent->ghoul2[0], "*flash" ); - //gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); + gi.G2API_AddBolt(&saberent->ghoul2[0], "*flash"); + // gi.G2API_SetLodBias( &saberent->ghoul2[0], 0 ); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ ent->client->ps.saberInFlight = qfalse; ent->client->ps.saberEntityDist = 0; @@ -520,11 +403,9 @@ Ghoul2 Insert End ent->client->ps.saberMove = 0; - //FIXME: need a think function to create alerts when turned on or is on, etc. + // FIXME: need a think function to create alerts when turned on or is on, etc. } - } - else - { + } else { ent->client->ps.saberEntityNum = ENTITYNUM_NONE; ent->client->ps.saberInFlight = qfalse; ent->client->ps.saberEntityDist = 0; @@ -532,369 +413,286 @@ Ghoul2 Insert End } } -void WP_SaberUpdateOldBladeData( gentity_t *ent ) -{ - if ( ent->client ) - { - VectorCopy( ent->client->renderInfo.muzzlePoint, ent->client->renderInfo.muzzlePointOld ); - VectorCopy( ent->client->renderInfo.muzzleDir, ent->client->renderInfo.muzzleDirOld ); - if ( ent->client->ps.saberLengthOld <= 0 && ent->client->ps.saberLength > 0 ) - {//just turned on - //do sound event - vec3_t saberOrg; - VectorCopy( g_entities[ent->client->ps.saberEntityNum].currentOrigin, saberOrg ); - AddSoundEvent( ent, saberOrg, 256, AEL_SUSPICIOUS ); +void WP_SaberUpdateOldBladeData(gentity_t *ent) { + if (ent->client) { + VectorCopy(ent->client->renderInfo.muzzlePoint, ent->client->renderInfo.muzzlePointOld); + VectorCopy(ent->client->renderInfo.muzzleDir, ent->client->renderInfo.muzzleDirOld); + if (ent->client->ps.saberLengthOld <= 0 && ent->client->ps.saberLength > 0) { // just turned on + // do sound event + vec3_t saberOrg; + VectorCopy(g_entities[ent->client->ps.saberEntityNum].currentOrigin, saberOrg); + AddSoundEvent(ent, saberOrg, 256, AEL_SUSPICIOUS); } ent->client->ps.saberLengthOld = ent->client->ps.saberLength; } } - - -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -//SABER DAMAGE============================================================================== -int WPDEBUG_SaberColor( saber_colors_t saberColor ) -{ - switch( (int)(saberColor) ) - { - case SABER_RED: - return 0x000000ff; - break; - case SABER_ORANGE: - return 0x000088ff; - break; - case SABER_YELLOW: - return 0x0000ffff; - break; - case SABER_GREEN: - return 0x0000ff00; - break; - case SABER_BLUE: - return 0x00ff0000; - break; - case SABER_PURPLE: - return 0x00ff00ff; - break; - default: - return 0x00ffffff;//white - break; +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +// SABER DAMAGE============================================================================== +int WPDEBUG_SaberColor(saber_colors_t saberColor) { + switch ((int)(saberColor)) { + case SABER_RED: + return 0x000000ff; + break; + case SABER_ORANGE: + return 0x000088ff; + break; + case SABER_YELLOW: + return 0x0000ffff; + break; + case SABER_GREEN: + return 0x0000ff00; + break; + case SABER_BLUE: + return 0x00ff0000; + break; + case SABER_PURPLE: + return 0x00ff00ff; + break; + default: + return 0x00ffffff; // white + break; } } -qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity_t *defender ) -{ - vec3_t temp, att_SaberBase, att_StartPos, saberMidNext, att_HitDir, att_HitPos, def_BladeDir; - float att_SaberHitLength, hitDot; +qboolean WP_GetSaberDeflectionAngle(gentity_t *attacker, gentity_t *defender) { + vec3_t temp, att_SaberBase, att_StartPos, saberMidNext, att_HitDir, att_HitPos, def_BladeDir; + float att_SaberHitLength, hitDot; - if ( !attacker || !attacker->client || attacker->client->ps.saberInFlight || attacker->client->ps.saberLength <= 0 ) - { + if (!attacker || !attacker->client || attacker->client->ps.saberInFlight || attacker->client->ps.saberLength <= 0) { return qfalse; } - if ( !defender || !defender->client || defender->client->ps.saberInFlight || defender->client->ps.saberLength <= 0 ) - { + if (!defender || !defender->client || defender->client->ps.saberInFlight || defender->client->ps.saberLength <= 0) { return qfalse; } attacker->client->ps.saberBounceMove = LS_NONE; - //get the attacker's saber base pos at time of impact - VectorSubtract( attacker->client->renderInfo.muzzlePoint, attacker->client->renderInfo.muzzlePointOld, temp ); - VectorMA( attacker->client->renderInfo.muzzlePointOld, saberHitFraction, temp, att_SaberBase ); - - //get the position along the length of the blade where the hit occured - att_SaberHitLength = Distance( saberHitLocation, att_SaberBase )/attacker->client->ps.saberLength; - - //now get the start of that midpoint in the swing and the actual impact point in the swing (shouldn't the latter just be saberHitLocation?) - VectorMA( attacker->client->renderInfo.muzzlePointOld, att_SaberHitLength, attacker->client->renderInfo.muzzleDirOld, att_StartPos ); - VectorMA( attacker->client->renderInfo.muzzlePoint, att_SaberHitLength, attacker->client->renderInfo.muzzleDir, saberMidNext ); - VectorSubtract( saberMidNext, att_StartPos, att_HitDir ); - VectorMA( att_StartPos, saberHitFraction, att_HitDir, att_HitPos ); - VectorNormalize( att_HitDir ); - - //get the defender's saber dir at time of impact - VectorSubtract( defender->client->renderInfo.muzzleDirOld, defender->client->renderInfo.muzzleDir, temp ); - VectorMA( defender->client->renderInfo.muzzleDirOld, saberHitFraction, temp, def_BladeDir ); - - //now compare - hitDot = DotProduct( att_HitDir, def_BladeDir ); - if ( hitDot < 0.25f && hitDot > -0.25f ) - {//hit pretty much perpendicular, pop straight back - attacker->client->ps.saberBounceMove = PM_SaberBounceForAttack( attacker->client->ps.saberMove ); + // get the attacker's saber base pos at time of impact + VectorSubtract(attacker->client->renderInfo.muzzlePoint, attacker->client->renderInfo.muzzlePointOld, temp); + VectorMA(attacker->client->renderInfo.muzzlePointOld, saberHitFraction, temp, att_SaberBase); + + // get the position along the length of the blade where the hit occured + att_SaberHitLength = Distance(saberHitLocation, att_SaberBase) / attacker->client->ps.saberLength; + + // now get the start of that midpoint in the swing and the actual impact point in the swing (shouldn't the latter just be saberHitLocation?) + VectorMA(attacker->client->renderInfo.muzzlePointOld, att_SaberHitLength, attacker->client->renderInfo.muzzleDirOld, att_StartPos); + VectorMA(attacker->client->renderInfo.muzzlePoint, att_SaberHitLength, attacker->client->renderInfo.muzzleDir, saberMidNext); + VectorSubtract(saberMidNext, att_StartPos, att_HitDir); + VectorMA(att_StartPos, saberHitFraction, att_HitDir, att_HitPos); + VectorNormalize(att_HitDir); + + // get the defender's saber dir at time of impact + VectorSubtract(defender->client->renderInfo.muzzleDirOld, defender->client->renderInfo.muzzleDir, temp); + VectorMA(defender->client->renderInfo.muzzleDirOld, saberHitFraction, temp, def_BladeDir); + + // now compare + hitDot = DotProduct(att_HitDir, def_BladeDir); + if (hitDot < 0.25f && hitDot > -0.25f) { // hit pretty much perpendicular, pop straight back + attacker->client->ps.saberBounceMove = PM_SaberBounceForAttack(attacker->client->ps.saberMove); return qfalse; - } - else - {//a deflection - vec3_t att_Right, att_Up, att_DeflectionDir; - float swingRDot, swingUDot; - - //get the direction of the deflection - VectorScale( def_BladeDir, hitDot, att_DeflectionDir ); - //get our bounce straight back direction - VectorScale( att_HitDir, -1.0f, temp ); - //add the bounce back and deflection - VectorAdd( att_DeflectionDir, temp, att_DeflectionDir ); - //normalize the result to determine what direction our saber should bounce back toward - VectorNormalize( att_DeflectionDir ); - - //need to know the direction of the deflectoin relative to the attacker's facing - VectorSet( temp, 0, attacker->client->ps.viewangles[YAW], 0 );//presumes no pitch! - AngleVectors( temp, NULL, att_Right, att_Up ); - swingRDot = DotProduct( att_Right, att_DeflectionDir ); - swingUDot = DotProduct( att_Up, att_DeflectionDir ); - - if ( swingRDot > 0.25f ) - {//deflect to right - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // a deflection + vec3_t att_Right, att_Up, att_DeflectionDir; + float swingRDot, swingUDot; + + // get the direction of the deflection + VectorScale(def_BladeDir, hitDot, att_DeflectionDir); + // get our bounce straight back direction + VectorScale(att_HitDir, -1.0f, temp); + // add the bounce back and deflection + VectorAdd(att_DeflectionDir, temp, att_DeflectionDir); + // normalize the result to determine what direction our saber should bounce back toward + VectorNormalize(att_DeflectionDir); + + // need to know the direction of the deflectoin relative to the attacker's facing + VectorSet(temp, 0, attacker->client->ps.viewangles[YAW], 0); // presumes no pitch! + AngleVectors(temp, NULL, att_Right, att_Up); + swingRDot = DotProduct(att_Right, att_DeflectionDir); + swingUDot = DotProduct(att_Up, att_DeflectionDir); + + if (swingRDot > 0.25f) { // deflect to right + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_TR; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_BR; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberBounceMove = LS_D1__R; } - } - else if ( swingRDot < -0.25f ) - {//deflect to left - if ( swingUDot > 0.25f ) - {//deflect to top + } else if (swingRDot < -0.25f) { // deflect to left + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_TL; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_BL; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberBounceMove = LS_D1__L; } - } - else - {//deflect in middle - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // deflect in middle + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberBounceMove = LS_D1_T_; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberBounceMove = LS_D1_B_; - } - else - {//deflect horizontally? Well, no such thing as straight back in my face, so use top - if ( swingRDot > 0 ) - { + } else { // deflect horizontally? Well, no such thing as straight back in my face, so use top + if (swingRDot > 0) { attacker->client->ps.saberBounceMove = LS_D1_TR; - } - else if ( swingRDot < 0 ) - { + } else if (swingRDot < 0) { attacker->client->ps.saberBounceMove = LS_D1_TL; - } - else - { + } else { attacker->client->ps.saberBounceMove = LS_D1_T_; } } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_BLUE"%s deflected from %s to %s\n", attacker->targetname, saberMoveData[attacker->client->ps.saberMove].name, saberMoveData[attacker->client->ps.saberBounceMove].name ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_BLUE "%s deflected from %s to %s\n", attacker->targetname, saberMoveData[attacker->client->ps.saberMove].name, + saberMoveData[attacker->client->ps.saberBounceMove].name); } #endif return qtrue; } } - -void WP_SaberClearDamageForEntNum( int entityNum ) -{ +void WP_SaberClearDamageForEntNum(int entityNum) { #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( entityNum ) - { - Com_Printf( "clearing damage for entnum %d\n", entityNum ); + if (d_saberCombat->integer) { + if (entityNum) { + Com_Printf("clearing damage for entnum %d\n", entityNum); } } -#endif// FINAL_BUILD - if ( g_saberRealisticCombat->integer > 1 ) - { +#endif // FINAL_BUILD + if (g_saberRealisticCombat->integer > 1) { return; } - for ( int i = 0; i < numVictims; i++ ) - { - if ( victimEntityNum[i] == entityNum ) - { - totalDmg[i] = 0;//no damage + for (int i = 0; i < numVictims; i++) { + if (victimEntityNum[i] == entityNum) { + totalDmg[i] = 0; // no damage hitLoc[i] = HL_NONE; hitDismemberLoc[i] = HL_NONE; hitDismember[i] = qfalse; - victimEntityNum[i] = ENTITYNUM_NONE;//like we never hit him + victimEntityNum[i] = ENTITYNUM_NONE; // like we never hit him } } } extern float damageModifier[]; extern float hitLocHealthPercentage[]; -qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, qboolean brokenParry ) -{ - qboolean didDamage = qfalse; - gentity_t *victim; - int dFlags = baseDFlags; - float maxDmg; - +qboolean WP_SaberApplyDamage(gentity_t *ent, float baseDamage, int baseDFlags, qboolean brokenParry) { + qboolean didDamage = qfalse; + gentity_t *victim; + int dFlags = baseDFlags; + float maxDmg; - if ( !numVictims ) - { + if (!numVictims) { return qfalse; } - for ( int i = 0; i < numVictims; i++ ) - { - dFlags = baseDFlags|DAMAGE_DEATH_KNOCKBACK|DAMAGE_NO_HIT_LOC; - if ( victimEntityNum[i] != ENTITYNUM_NONE && &g_entities[victimEntityNum[i]] != NULL ) - { // Don't bother with this damage if the fraction is higher than the saber's fraction - if ( dmgFraction[i] < saberHitFraction || brokenParry ) - { + for (int i = 0; i < numVictims; i++) { + dFlags = baseDFlags | DAMAGE_DEATH_KNOCKBACK | DAMAGE_NO_HIT_LOC; + if (victimEntityNum[i] != ENTITYNUM_NONE && + &g_entities[victimEntityNum[i]] != NULL) { // Don't bother with this damage if the fraction is higher than the saber's fraction + if (dmgFraction[i] < saberHitFraction || brokenParry) { victim = &g_entities[victimEntityNum[i]]; - if ( !victim ) - { + if (!victim) { continue; } - if ( victim->e_DieFunc == dieF_maglock_die ) - {//*sigh*, special check for maglocks + if (victim->e_DieFunc == dieF_maglock_die) { //*sigh*, special check for maglocks vec3_t testFrom; - if ( ent->client->ps.saberInFlight ) - { - VectorCopy( g_entities[ent->client->ps.saberEntityNum].currentOrigin, testFrom ); - } - else - { - VectorCopy( ent->currentOrigin, testFrom ); + if (ent->client->ps.saberInFlight) { + VectorCopy(g_entities[ent->client->ps.saberEntityNum].currentOrigin, testFrom); + } else { + VectorCopy(ent->currentOrigin, testFrom); } testFrom[2] = victim->currentOrigin[2]; trace_t testTrace; - gi.trace( &testTrace, testFrom, vec3_origin, vec3_origin, victim->currentOrigin, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( testTrace.entityNum != victim->s.number ) - {//can only damage maglocks if have a clear trace to the thing's origin + gi.trace(&testTrace, testFrom, vec3_origin, vec3_origin, victim->currentOrigin, ent->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (testTrace.entityNum != victim->s.number) { // can only damage maglocks if have a clear trace to the thing's origin continue; } } - if ( totalDmg[i] > 0 ) - {//actually want to do *some* damage here - if ( victim->s.weapon == WP_SABER && victim->client && !g_saberRealisticCombat->integer ) - {//dmg vs other saber fighters is modded by hitloc and capped + if (totalDmg[i] > 0) { // actually want to do *some* damage here + if (victim->s.weapon == WP_SABER && victim->client && + !g_saberRealisticCombat->integer) { // dmg vs other saber fighters is modded by hitloc and capped totalDmg[i] *= damageModifier[hitLoc[i]]; - if ( hitLoc[i] == HL_NONE ) - { - maxDmg = 33*baseDamage; - } - else - { - maxDmg = 50*hitLocHealthPercentage[hitLoc[i]]*baseDamage;//*victim->client->ps.stats[STAT_MAX_HEALTH]*2.0f; + if (hitLoc[i] == HL_NONE) { + maxDmg = 33 * baseDamage; + } else { + maxDmg = 50 * hitLocHealthPercentage[hitLoc[i]] * baseDamage; //*victim->client->ps.stats[STAT_MAX_HEALTH]*2.0f; } - if ( maxDmg < totalDmg[i] ) - { + if (maxDmg < totalDmg[i]) { totalDmg[i] = maxDmg; } - //dFlags |= DAMAGE_NO_HIT_LOC; + // dFlags |= DAMAGE_NO_HIT_LOC; } - //clamp the dmg - if ( victim->s.weapon != WP_SABER ) - {//clamp the dmg between 25 and maxhealth + // clamp the dmg + if (victim->s.weapon != WP_SABER) { // clamp the dmg between 25 and maxhealth /* if ( totalDmg[i] > victim->max_health ) { totalDmg[i] = victim->max_health; } - else */if ( totalDmg[i] < 25 ) - { + else */ + if (totalDmg[i] < 25) { totalDmg[i] = 25; } - if ( totalDmg[i] > 100 )//+(50*g_spskill->integer) ) - {//clamp using same adjustment as in NPC_Begin - totalDmg[i] = 100;//+(50*g_spskill->integer); + if (totalDmg[i] > 100) //+(50*g_spskill->integer) ) + { // clamp using same adjustment as in NPC_Begin + totalDmg[i] = 100; //+(50*g_spskill->integer); } - } - else - {//clamp the dmg between 5 and 100 - if ( !victim->s.number && totalDmg[i] > 50 ) - {//never do more than half full health damage to player - //prevents one-hit kills + } else { // clamp the dmg between 5 and 100 + if (!victim->s.number && totalDmg[i] > 50) { // never do more than half full health damage to player + // prevents one-hit kills totalDmg[i] = 50; - } - else if ( totalDmg[i] > 100 ) - { + } else if (totalDmg[i] > 100) { totalDmg[i] = 100; - } - else - { - if ( totalDmg[i] < 5 ) - { + } else { + if (totalDmg[i] < 5) { totalDmg[i] = 5; } } } - if ( totalDmg[i] > 0 ) - { + if (totalDmg[i] > 0) { didDamage = qtrue; - if( victim->client ) - { - if ( victim->client->ps.pm_time > 0 && victim->client->ps.pm_flags & PMF_TIME_KNOCKBACK && victim->client->ps.velocity[2] > 0 ) - {//already being knocked around + if (victim->client) { + if (victim->client->ps.pm_time > 0 && victim->client->ps.pm_flags & PMF_TIME_KNOCKBACK && + victim->client->ps.velocity[2] > 0) { // already being knocked around dFlags |= DAMAGE_NO_KNOCKBACK; } - if ( g_dismemberment->integer >= 11381138 || g_saberRealisticCombat->integer ) - { + if (g_dismemberment->integer >= 11381138 || g_saberRealisticCombat->integer) { dFlags |= DAMAGE_DISMEMBER; - if ( hitDismember[i] ) - { + if (hitDismember[i]) { victim->client->dismembered = qfalse; } - } - else if ( hitDismember[i] ) - { + } else if (hitDismember[i]) { dFlags |= DAMAGE_DISMEMBER; } - if ( baseDamage <= 1.0f ) - {//very mild damage - if ( victim->s.number == 0 || victim->client->ps.weapon == WP_SABER || victim->client->NPC_class == CLASS_GALAKMECH ) - {//if it's the player or a saber-user, don't kill them with this blow + if (baseDamage <= 1.0f) { // very mild damage + if (victim->s.number == 0 || victim->client->ps.weapon == WP_SABER || + victim->client->NPC_class == CLASS_GALAKMECH) { // if it's the player or a saber-user, don't kill them with this blow dFlags |= DAMAGE_NO_KILL; } } - } - else - { - if ( victim->takedamage ) - {//some other breakable thing - //create a flash here - g_saberFlashTime = level.time-50; - VectorCopy( dmgSpot[i], g_saberFlashPos ); + } else { + if (victim->takedamage) { // some other breakable thing + // create a flash here + g_saberFlashTime = level.time - 50; + VectorCopy(dmgSpot[i], g_saberFlashPos); } } - //victim->hitLoc = hitLoc[i]; + // victim->hitLoc = hitLoc[i]; - dFlags |= DAMAGE_NO_KNOCKBACK;//okay, let's try no knockback whatsoever... + dFlags |= DAMAGE_NO_KNOCKBACK; // okay, let's try no knockback whatsoever... dFlags &= ~DAMAGE_DEATH_KNOCKBACK; - if ( g_saberRealisticCombat->integer ) - { + if (g_saberRealisticCombat->integer) { dFlags |= DAMAGE_NO_KNOCKBACK; dFlags &= ~DAMAGE_DEATH_KNOCKBACK; dFlags &= ~DAMAGE_NO_KILL; } - if ( ent->client && !ent->s.number ) - { - switch( hitLoc[i] ) - { + if (ent->client && !ent->s.number) { + switch (hitLoc[i]) { case HL_FOOT_RT: case HL_FOOT_LT: case HL_LEG_RT: @@ -921,28 +719,22 @@ qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, break; } } - G_Damage( victim, ent, ent, dmgDir[i], dmgSpot[i], ceil(totalDmg[i]), dFlags, MOD_SABER, hitDismemberLoc[i] ); + G_Damage(victim, ent, ent, dmgDir[i], dmgSpot[i], ceil(totalDmg[i]), dFlags, MOD_SABER, hitDismemberLoc[i]); #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_RED"damage: %4.2f, hitLoc %d\n", totalDmg[i], hitLoc[i] ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_RED "damage: %4.2f, hitLoc %d\n", totalDmg[i], hitLoc[i]); } #endif - //do the effect - //G_PlayEffect( G_EffectIndex( "blood_sparks" ), dmgSpot[i], dmgDir[i] ); - if ( ent->s.number == 0 ) - { - AddSoundEvent( victim->owner, dmgSpot[i], 256, AEL_DISCOVERED ); - AddSightEvent( victim->owner, dmgSpot[i], 512, AEL_DISCOVERED, 50 ); + // do the effect + // G_PlayEffect( G_EffectIndex( "blood_sparks" ), dmgSpot[i], dmgDir[i] ); + if (ent->s.number == 0) { + AddSoundEvent(victim->owner, dmgSpot[i], 256, AEL_DISCOVERED); + AddSightEvent(victim->owner, dmgSpot[i], 512, AEL_DISCOVERED, 50); } - if ( ent->client ) - { - if ( ent->enemy && ent->enemy == victim ) - {//just so Jedi knows that he hit his enemy + if (ent->client) { + if (ent->enemy && ent->enemy == victim) { // just so Jedi knows that he hit his enemy ent->client->ps.saberEventFlags |= SEF_HITENEMY; - } - else - { + } else { ent->client->ps.saberEventFlags |= SEF_HITOBJECT; } } @@ -954,67 +746,58 @@ qboolean WP_SaberApplyDamage( gentity_t *ent, float baseDamage, int baseDFlags, return didDamage; } -void WP_SaberDamageAdd( float trDmg, int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgSpot, float dmg, float fraction, int trHitLoc, qboolean trDismember, int trDismemberLoc ) -{ +void WP_SaberDamageAdd(float trDmg, int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgSpot, float dmg, float fraction, int trHitLoc, qboolean trDismember, + int trDismemberLoc) { int curVictim = 0; int i; - if ( trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD ) - { + if (trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD) { return; } - if ( trDmg * dmg < 10.0f ) - {//too piddly an amount of damage to really count? - //FIXME: but already did the effect, didn't we... sigh... - //return; + if (trDmg * dmg < 10.0f) { // too piddly an amount of damage to really count? + // FIXME: but already did the effect, didn't we... sigh... + // return; } - if ( trDmg ) - {//did some damage to something - for ( i = 0; i < numVictims; i++ ) - { - if ( victimEntityNum[i] == trVictimEntityNum ) - {//already hit this guy before + if (trDmg) { // did some damage to something + for (i = 0; i < numVictims; i++) { + if (victimEntityNum[i] == trVictimEntityNum) { // already hit this guy before curVictim = i; break; } } - if ( i == numVictims ) - {//haven't hit his guy before - if ( numVictims + 1 >= MAX_SABER_VICTIMS ) - {//can't add another victim at this time + if (i == numVictims) { // haven't hit his guy before + if (numVictims + 1 >= MAX_SABER_VICTIMS) { // can't add another victim at this time return; } - //add a new victim to the list + // add a new victim to the list curVictim = numVictims; victimEntityNum[numVictims++] = trVictimEntityNum; } - float addDmg = trDmg*dmg; - if ( trHitLoc!=HL_NONE && (hitLoc[curVictim]==HL_NONE||hitLocHealthPercentage[trHitLoc]>hitLocHealthPercentage[hitLoc[curVictim]]) ) - {//this hitLoc is more critical than the previous one this frame + float addDmg = trDmg * dmg; + if (trHitLoc != HL_NONE && + (hitLoc[curVictim] == HL_NONE || + hitLocHealthPercentage[trHitLoc] > hitLocHealthPercentage[hitLoc[curVictim]])) { // this hitLoc is more critical than the previous one this frame hitLoc[curVictim] = trHitLoc; } totalDmg[curVictim] += addDmg; - if ( !VectorLengthSquared( dmgDir[curVictim] ) ) - { - VectorCopy( trDmgDir, dmgDir[curVictim] ); + if (!VectorLengthSquared(dmgDir[curVictim])) { + VectorCopy(trDmgDir, dmgDir[curVictim]); } - if ( !VectorLengthSquared( dmgSpot[curVictim] ) ) - { - VectorCopy( trDmgSpot, dmgSpot[curVictim] ); + if (!VectorLengthSquared(dmgSpot[curVictim])) { + VectorCopy(trDmgSpot, dmgSpot[curVictim]); } // Make sure we keep track of the fraction. Why? // Well, if the saber hits something that stops it, the damage isn't done past that point. dmgFraction[curVictim] = fraction; - if ( (trDismemberLoc != HL_NONE && hitDismemberLoc[curVictim] == HL_NONE) - || (!hitDismember[curVictim] && trDismember) ) - {//either this is the first dismember loc we got or we got a loc before, but it wasn't a dismember loc, so take the new one + if ((trDismemberLoc != HL_NONE && hitDismemberLoc[curVictim] == HL_NONE) || + (!hitDismember[curVictim] && + trDismember)) { // either this is the first dismember loc we got or we got a loc before, but it wasn't a dismember loc, so take the new one hitDismemberLoc[curVictim] = trDismemberLoc; } - if ( trDismember ) - {//we scored a dismemberment hit... + if (trDismember) { // we scored a dismemberment hit... hitDismember[curVictim] = trDismember; } } @@ -1026,14 +809,14 @@ WP_SabersIntersect Breaks the two saber paths into 2 tris each and tests each tri for the first saber path against each of the other saber path's tris FIXME: subdivide the arc into a consistant increment -FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different times)? +FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different +times)? */ -extern qboolean tri_tri_intersect(vec3_t V0,vec3_t V1,vec3_t V2,vec3_t U0,vec3_t U1,vec3_t U2); -qboolean WP_SabersIntersect( gentity_t *ent1, gentity_t *ent2, qboolean checkDir ) -{ - vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; - vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; - vec3_t dir; +extern qboolean tri_tri_intersect(vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2); +qboolean WP_SabersIntersect(gentity_t *ent1, gentity_t *ent2, qboolean checkDir) { + vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; + vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; + vec3_t dir; /* #ifndef FINAL_BUILD @@ -1044,34 +827,31 @@ qboolean WP_SabersIntersect( gentity_t *ent1, gentity_t *ent2, qboolean checkDir #endif */ - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0 ) - { + if (ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0) { return qfalse; } - //if ( ent1->client->ps.saberInFlight ) + // if ( ent1->client->ps.saberInFlight ) { - VectorCopy( ent1->client->renderInfo.muzzlePointOld, saberBase1 ); - VectorCopy( ent1->client->renderInfo.muzzlePoint, saberBaseNext1 ); + VectorCopy(ent1->client->renderInfo.muzzlePointOld, saberBase1); + VectorCopy(ent1->client->renderInfo.muzzlePoint, saberBaseNext1); - VectorSubtract( ent1->client->renderInfo.muzzlePoint, ent1->client->renderInfo.muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1 ); + VectorSubtract(ent1->client->renderInfo.muzzlePoint, ent1->client->renderInfo.muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1); - VectorMA( saberBase1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDirOld, saberTip1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1 ); + VectorMA(saberBase1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDirOld, saberTip1); + VectorMA(saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1); - VectorSubtract( saberTipNext1, saberTip1, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1 ); + VectorSubtract(saberTipNext1, saberTip1, dir); + VectorNormalize(dir); + VectorMA(saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1); } /* else @@ -1083,21 +863,21 @@ qboolean WP_SabersIntersect( gentity_t *ent1, gentity_t *ent2, qboolean checkDir } */ - //if ( ent2->client->ps.saberInFlight ) + // if ( ent2->client->ps.saberInFlight ) { - VectorCopy( ent2->client->renderInfo.muzzlePointOld, saberBase2 ); - VectorCopy( ent2->client->renderInfo.muzzlePoint, saberBaseNext2 ); + VectorCopy(ent2->client->renderInfo.muzzlePointOld, saberBase2); + VectorCopy(ent2->client->renderInfo.muzzlePoint, saberBaseNext2); - VectorSubtract( ent2->client->renderInfo.muzzlePoint, ent2->client->renderInfo.muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2 ); + VectorSubtract(ent2->client->renderInfo.muzzlePoint, ent2->client->renderInfo.muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2); - VectorMA( saberBase2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDirOld, saberTip2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2 ); + VectorMA(saberBase2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDirOld, saberTip2); + VectorMA(saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2); - VectorSubtract( saberTipNext2, saberTip2, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2 ); + VectorSubtract(saberTipNext2, saberTip2, dir); + VectorNormalize(dir); + VectorMA(saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2); } /* else @@ -1108,49 +888,41 @@ qboolean WP_SabersIntersect( gentity_t *ent1, gentity_t *ent2, qboolean checkDir VectorMA( saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDirNext, saberTipNext2 ); } */ - if ( checkDir ) - {//check the direction of the two swings to make sure the sabers are swinging towards each other + if (checkDir) { // check the direction of the two swings to make sure the sabers are swinging towards each other vec3_t saberDir1, saberDir2; - VectorSubtract( saberTipNext1, saberTip1, saberDir1 ); - VectorSubtract( saberTipNext2, saberTip2, saberDir2 ); - VectorNormalize( saberDir1 ); - VectorNormalize( saberDir2 ); - if ( DotProduct( saberDir1, saberDir2 ) > 0.6f ) - {//sabers moving in same dir, probably didn't actually hit + VectorSubtract(saberTipNext1, saberTip1, saberDir1); + VectorSubtract(saberTipNext2, saberTip2, saberDir2); + VectorNormalize(saberDir1); + VectorNormalize(saberDir2); + if (DotProduct(saberDir1, saberDir2) > 0.6f) { // sabers moving in same dir, probably didn't actually hit return qfalse; } - //now check orientation of sabers, make sure they're not parallel or close to it - float dot = DotProduct( ent1->client->renderInfo.muzzleDir, ent2->client->renderInfo.muzzleDir ); - if ( dot > 0.9f || dot < -0.9f ) - {//too parallel to really block effectively? + // now check orientation of sabers, make sure they're not parallel or close to it + float dot = DotProduct(ent1->client->renderInfo.muzzleDir, ent2->client->renderInfo.muzzleDir); + if (dot > 0.9f || dot < -0.9f) { // too parallel to really block effectively? return qfalse; } } - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } return qfalse; } -float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) -{ - vec3_t saberBaseNext1, saberTipNext1, saberPoint1; - vec3_t saberBaseNext2, saberTipNext2, saberPoint2; +float WP_SabersDistance(gentity_t *ent1, gentity_t *ent2) { + vec3_t saberBaseNext1, saberTipNext1, saberPoint1; + vec3_t saberBaseNext2, saberTipNext2, saberPoint2; /* #ifndef FINAL_BUILD @@ -1161,23 +933,20 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) #endif */ - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0 ) - { + if (ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0) { return qfalse; } - //if ( ent1->client->ps.saberInFlight ) + // if ( ent1->client->ps.saberInFlight ) { - VectorCopy( ent1->client->renderInfo.muzzlePoint, saberBaseNext1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1 ); + VectorCopy(ent1->client->renderInfo.muzzlePoint, saberBaseNext1); + VectorMA(saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1); } /* else @@ -1187,10 +956,10 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) } */ - //if ( ent2->client->ps.saberInFlight ) + // if ( ent2->client->ps.saberInFlight ) { - VectorCopy( ent2->client->renderInfo.muzzlePoint, saberBaseNext2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2 ); + VectorCopy(ent2->client->renderInfo.muzzlePoint, saberBaseNext2); + VectorMA(saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2); } /* else @@ -1200,9 +969,9 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) } */ - float sabersDist = ShortestLineSegBewteen2LineSegs( saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2 ); + float sabersDist = ShortestLineSegBewteen2LineSegs(saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2); - //okay, this is a super hack, but makes saber collisions look better from the player point of view + // okay, this is a super hack, but makes saber collisions look better from the player point of view /* if ( sabersDist < 16.0f ) { @@ -1223,76 +992,69 @@ float WP_SabersDistance( gentity_t *ent1, gentity_t *ent2 ) */ #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 2 ) - { - G_DebugLine( saberPoint1, saberPoint2, FRAMETIME, 0x00ffffff, qtrue ); + if (d_saberCombat->integer > 2) { + G_DebugLine(saberPoint1, saberPoint2, FRAMETIME, 0x00ffffff, qtrue); } #endif return sabersDist; } -qboolean WP_SabersIntersection( gentity_t *ent1, gentity_t *ent2, vec3_t intersect ) -{ - vec3_t saberBaseNext1, saberTipNext1, saberPoint1; - vec3_t saberBaseNext2, saberTipNext2, saberPoint2; +qboolean WP_SabersIntersection(gentity_t *ent1, gentity_t *ent2, vec3_t intersect) { + vec3_t saberBaseNext1, saberTipNext1, saberPoint1; + vec3_t saberBaseNext2, saberTipNext2, saberPoint2; - if ( !ent1 || !ent2 ) - { + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0 ) - { + if (ent1->client->ps.saberLength <= 0 || ent2->client->ps.saberLength <= 0) { return qfalse; } - VectorCopy( ent1->client->renderInfo.muzzlePoint, saberBaseNext1 ); - VectorMA( saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1 ); + VectorCopy(ent1->client->renderInfo.muzzlePoint, saberBaseNext1); + VectorMA(saberBaseNext1, ent1->client->ps.saberLength, ent1->client->renderInfo.muzzleDir, saberTipNext1); - VectorCopy( ent2->client->renderInfo.muzzlePoint, saberBaseNext2 ); - VectorMA( saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2 ); + VectorCopy(ent2->client->renderInfo.muzzlePoint, saberBaseNext2); + VectorMA(saberBaseNext2, ent2->client->ps.saberLength, ent2->client->renderInfo.muzzleDir, saberTipNext2); - ShortestLineSegBewteen2LineSegs( saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2 ); - VectorAdd( saberPoint1, saberPoint2, intersect ); - VectorScale( intersect, 0.5, intersect ); + ShortestLineSegBewteen2LineSegs(saberBaseNext1, saberTipNext1, saberBaseNext2, saberTipNext2, saberPoint1, saberPoint2); + VectorAdd(saberPoint1, saberPoint2, intersect); + VectorScale(intersect, 0.5, intersect); return qtrue; } char *hit_blood_sparks = "blood_sparks"; char *hit_sparks = "saber_cut"; -extern qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ); -qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, float dmg, vec3_t dmgDir, vec3_t bladeDir, int enemyTeam ) -{ - - int hitEntNum[MAX_G2_COLLISIONS] = {ENTITYNUM_NONE}; - float hitEntDmgAdd[MAX_G2_COLLISIONS] = {0}; - float hitEntDmgSub[MAX_G2_COLLISIONS] = {0}; - vec3_t hitEntPoint[MAX_G2_COLLISIONS]; - vec3_t hitEntDir[MAX_G2_COLLISIONS]; - float hitEntStartFrac[MAX_G2_COLLISIONS] = {0}; - int trHitLoc = HL_NONE; - int trDismemberLoc = HL_NONE; - qboolean trDismember = qfalse; - int i,z; - int numHitEnts = 0; - float distFromStart,doDmg; - char *hitEffect; - gentity_t *hitEnt; - - for (z=0; z < MAX_G2_COLLISIONS; z++) - { - if ( tr->G2CollisionMap[z].mEntityNum == -1 ) - {//actually, completely break out of this for loop since nothing after this in the aray should ever be valid either - continue;//break;// - } - - CCollisionRecord &coll = tr->G2CollisionMap[z]; - //distFromStart = Distance( start, coll.mCollisionPosition ); - distFromStart = coll.mDistance; +extern qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod); +qboolean WP_SaberDamageEffects(trace_t *tr, const vec3_t start, float length, float dmg, vec3_t dmgDir, vec3_t bladeDir, int enemyTeam) { + + int hitEntNum[MAX_G2_COLLISIONS] = {ENTITYNUM_NONE}; + float hitEntDmgAdd[MAX_G2_COLLISIONS] = {0}; + float hitEntDmgSub[MAX_G2_COLLISIONS] = {0}; + vec3_t hitEntPoint[MAX_G2_COLLISIONS]; + vec3_t hitEntDir[MAX_G2_COLLISIONS]; + float hitEntStartFrac[MAX_G2_COLLISIONS] = {0}; + int trHitLoc = HL_NONE; + int trDismemberLoc = HL_NONE; + qboolean trDismember = qfalse; + int i, z; + int numHitEnts = 0; + float distFromStart, doDmg; + char *hitEffect; + gentity_t *hitEnt; + + for (z = 0; z < MAX_G2_COLLISIONS; z++) { + if (tr->G2CollisionMap[z].mEntityNum == + -1) { // actually, completely break out of this for loop since nothing after this in the aray should ever be valid either + continue; // break;// + } + + CCollisionRecord &coll = tr->G2CollisionMap[z]; + // distFromStart = Distance( start, coll.mCollisionPosition ); + distFromStart = coll.mDistance; /* //FIXME: (distFromStart/length) is not guaranteed to be from 0 to 1... *sigh*... @@ -1308,175 +1070,147 @@ qboolean WP_SaberDamageEffects( trace_t *tr, const vec3_t start, float length, f } */ - for ( i = 0; i < numHitEnts; i++ ) - { - if ( hitEntNum[i] != ENTITYNUM_NONE ) - {//we hit this ent before - //we'll want to add this dist + for (i = 0; i < numHitEnts; i++) { + if (hitEntNum[i] != ENTITYNUM_NONE) { // we hit this ent before + // we'll want to add this dist hitEntDmgAdd[i] = distFromStart; break; } } - if ( i == numHitEnts ) - {//first time we hit this ent - if ( numHitEnts == MAX_G2_COLLISIONS ) - {//hit too many damn ents! + if (i == numHitEnts) { // first time we hit this ent + if (numHitEnts == MAX_G2_COLLISIONS) { // hit too many damn ents! continue; } hitEntNum[numHitEnts] = coll.mEntityNum; - if ( !coll.mFlags ) - {//hmm, we came out first, so we must have started inside - //we'll want to subtract this dist + if (!coll.mFlags) { // hmm, we came out first, so we must have started inside + // we'll want to subtract this dist hitEntDmgAdd[numHitEnts] = distFromStart; - } - else - {//we're entering the model - //we'll want to subtract this dist + } else { // we're entering the model + // we'll want to subtract this dist hitEntDmgSub[numHitEnts] = distFromStart; } - //keep track of how far in the damage was done - hitEntStartFrac[numHitEnts] = hitEntDmgSub[numHitEnts]/length; - //remember the entrance point - VectorCopy( coll.mCollisionPosition, hitEntPoint[numHitEnts] ); - //remember the entrance dir - VectorCopy( coll.mCollisionNormal, hitEntDir[numHitEnts] ); - VectorNormalize( hitEntDir[numHitEnts] ); + // keep track of how far in the damage was done + hitEntStartFrac[numHitEnts] = hitEntDmgSub[numHitEnts] / length; + // remember the entrance point + VectorCopy(coll.mCollisionPosition, hitEntPoint[numHitEnts]); + // remember the entrance dir + VectorCopy(coll.mCollisionNormal, hitEntDir[numHitEnts]); + VectorNormalize(hitEntDir[numHitEnts]); - //do the effect + // do the effect - //FIXME: check material rather than team? + // FIXME: check material rather than team? hitEnt = &g_entities[hitEntNum[numHitEnts]]; hitEffect = hit_blood_sparks; - if ( hitEnt != NULL ) - { - if ( hitEnt->client ) - { + if (hitEnt != NULL) { + if (hitEnt->client) { class_t npc_class = hitEnt->client->NPC_class; - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || + npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || + npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || + npc_class == CLASS_SENTRY) { hitEffect = hit_sparks; } - } - else - { + } else { hitEffect = hit_sparks; } } - //FIXME: play less if damage is less? - G_PlayEffect( hitEffect, coll.mCollisionPosition, coll.mCollisionNormal ); + // FIXME: play less if damage is less? + G_PlayEffect(hitEffect, coll.mCollisionPosition, coll.mCollisionNormal); - //Get the hit location based on surface name - if ( (hitLoc[numHitEnts] == HL_NONE && trHitLoc == HL_NONE) - || (hitDismemberLoc[numHitEnts] == HL_NONE && trDismemberLoc == HL_NONE) - || (!hitDismember[numHitEnts] && !trDismember) ) - {//no hit loc set for this ent this damage cycle yet - //FIXME: find closest impact surf *first* (per ent), then call G_GetHitLocFromSurfName? - trDismember = G_GetHitLocFromSurfName( &g_entities[coll.mEntityNum], gi.G2API_GetSurfaceName( &g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex ), &trHitLoc, coll.mCollisionPosition, dmgDir, bladeDir, MOD_SABER ); + // Get the hit location based on surface name + if ((hitLoc[numHitEnts] == HL_NONE && trHitLoc == HL_NONE) || (hitDismemberLoc[numHitEnts] == HL_NONE && trDismemberLoc == HL_NONE) || + (!hitDismember[numHitEnts] && !trDismember)) { // no hit loc set for this ent this damage cycle yet + // FIXME: find closest impact surf *first* (per ent), then call G_GetHitLocFromSurfName? + trDismember = G_GetHitLocFromSurfName(&g_entities[coll.mEntityNum], + gi.G2API_GetSurfaceName(&g_entities[coll.mEntityNum].ghoul2[coll.mModelIndex], coll.mSurfaceIndex), + &trHitLoc, coll.mCollisionPosition, dmgDir, bladeDir, MOD_SABER); trDismemberLoc = trHitLoc; } numHitEnts++; } } - //now go through all the ents we hit and do the damage - for ( i = 0; i < numHitEnts; i++ ) - { + // now go through all the ents we hit and do the damage + for (i = 0; i < numHitEnts; i++) { doDmg = dmg; - if ( hitEntNum[i] != ENTITYNUM_NONE ) - { - if ( doDmg < 10 ) - {//base damage is less than 10 - if ( hitEntNum[i] != 0 ) - {//not the player + if (hitEntNum[i] != ENTITYNUM_NONE) { + if (doDmg < 10) { // base damage is less than 10 + if (hitEntNum[i] != 0) { // not the player hitEnt = &g_entities[hitEntNum[i]]; - if ( !hitEnt->client || (hitEnt->client->ps.weapon!=WP_SABER&&hitEnt->client->NPC_class!=CLASS_GALAKMECH&&hitEnt->client->playerTeam==enemyTeam) ) - {//did *not* hit a jedi and did *not* hit the player - //make sure the base damage is high against non-jedi, feels better + if (!hitEnt->client || (hitEnt->client->ps.weapon != WP_SABER && hitEnt->client->NPC_class != CLASS_GALAKMECH && + hitEnt->client->playerTeam == enemyTeam)) { // did *not* hit a jedi and did *not* hit the player + // make sure the base damage is high against non-jedi, feels better doDmg = 10; } } } - if ( !hitEntDmgAdd[i] && !hitEntDmgSub[i] ) - {//spent entire time in model - //NOTE: will we even get a collision then? + if (!hitEntDmgAdd[i] && !hitEntDmgSub[i]) { // spent entire time in model + // NOTE: will we even get a collision then? doDmg *= length; - } - else if ( hitEntDmgAdd[i] && hitEntDmgSub[i] ) - {//we did enter and exit + } else if (hitEntDmgAdd[i] && hitEntDmgSub[i]) { // we did enter and exit doDmg *= hitEntDmgAdd[i] - hitEntDmgSub[i]; - } - else if ( !hitEntDmgAdd[i] ) - {//we didn't exit, just entered + } else if (!hitEntDmgAdd[i]) { // we didn't exit, just entered doDmg *= length - hitEntDmgSub[i]; - } - else if ( !hitEntDmgSub[i] ) - {//we didn't enter, only exited + } else if (!hitEntDmgSub[i]) { // we didn't enter, only exited doDmg *= hitEntDmgAdd[i]; } - if ( doDmg > 0 ) - { - WP_SaberDamageAdd( 1.0, hitEntNum[i], hitEntDir[i], hitEntPoint[i], ceil(doDmg), hitEntStartFrac[i], trHitLoc, trDismember, trDismemberLoc ); + if (doDmg > 0) { + WP_SaberDamageAdd(1.0, hitEntNum[i], hitEntDir[i], hitEntPoint[i], ceil(doDmg), hitEntStartFrac[i], trHitLoc, trDismember, trDismemberLoc); } } } return (qboolean)(numHitEnts > 0); } -void WP_SaberKnockaway( gentity_t *attacker, trace_t *tr ) -{ - WP_SaberDrop( attacker, &g_entities[attacker->client->ps.saberEntityNum] ); - G_Sound( &g_entities[attacker->client->ps.saberEntityNum], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - G_PlayEffect( "saber_block", tr->endpos ); +void WP_SaberKnockaway(gentity_t *attacker, trace_t *tr) { + WP_SaberDrop(attacker, &g_entities[attacker->client->ps.saberEntityNum]); + G_Sound(&g_entities[attacker->client->ps.saberEntityNum], G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); + G_PlayEffect("saber_block", tr->endpos); saberHitFraction = tr->fraction; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_MAGENTA"WP_SaberKnockaway: saberHitFraction %4.2f\n", saberHitFraction ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_MAGENTA "WP_SaberKnockaway: saberHitFraction %4.2f\n", saberHitFraction); } #endif - VectorCopy( tr->endpos, saberHitLocation ); + VectorCopy(tr->endpos, saberHitLocation); saberHitEntity = tr->entityNum; - g_saberFlashTime = level.time-50; - VectorCopy( saberHitLocation, g_saberFlashPos ); + g_saberFlashTime = level.time - 50; + VectorCopy(saberHitLocation, g_saberFlashPos); - //FIXME: make hitEnt play an attack anim or some other special anim when this happens - //gentity_t *hitEnt = &g_entities[tr->entityNum]; - //NPC_SetAnim( hitEnt, SETANIM_BOTH, BOTH_KNOCKSABER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // FIXME: make hitEnt play an attack anim or some other special anim when this happens + // gentity_t *hitEnt = &g_entities[tr->entityNum]; + // NPC_SetAnim( hitEnt, SETANIM_BOTH, BOTH_KNOCKSABER, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } -#define SABER_COLLISION_DIST 6//was 2//was 4//was 8//was 16 -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f ); -qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg, - vec3_t bladeDir, qboolean noGhoul, int attackStrength, - qboolean extrapolate = qtrue ) -{ - trace_t tr; - vec3_t dir; - int mask = (MASK_SHOT|CONTENTS_LIGHTSABER); - gentity_t *attacker = &g_entities[ignore]; - - vec3_t end2; - VectorCopy( end, end2 ); - if ( extrapolate ) - { - //NOTE: since we can no longer use the predicted point, extrapolate the trace some. +#define SABER_COLLISION_DIST 6 // was 2//was 4//was 8//was 16 +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold = 0.0f); +qboolean WP_SaberDamageForTrace(int ignore, vec3_t start, vec3_t end, float dmg, vec3_t bladeDir, qboolean noGhoul, int attackStrength, + qboolean extrapolate = qtrue) { + trace_t tr; + vec3_t dir; + int mask = (MASK_SHOT | CONTENTS_LIGHTSABER); + gentity_t *attacker = &g_entities[ignore]; + + vec3_t end2; + VectorCopy(end, end2); + if (extrapolate) { + // NOTE: since we can no longer use the predicted point, extrapolate the trace some. // this may allow saber hits that aren't actually hits, but it doesn't look too bad vec3_t diff; - VectorSubtract( end, start, diff ); - VectorNormalize( diff ); - VectorMA( end2, SABER_EXTRAPOLATE_DIST, diff, end2 ); + VectorSubtract(end, start, diff); + VectorNormalize(diff); + VectorMA(end2, SABER_EXTRAPOLATE_DIST, diff, end2); } - if ( !noGhoul ) - { - if ( !attacker->s.number || (attacker->client&&(attacker->client->playerTeam==TEAM_PLAYER||attacker->client->NPC_class==CLASS_SHADOWTROOPER||attacker->client->NPC_class==CLASS_TAVION||attacker->client->NPC_class==CLASS_DESANN) ) )//&&attackStrength==FORCE_LEVEL_3) - {//player,. player allies, shadowtroopers, tavion and desann use larger traces - vec3_t traceMins = {-2,-2,-2}, traceMaxs = {2,2,2}; - gi.trace( &tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX + if (!noGhoul) { + if (!attacker->s.number || (attacker->client && (attacker->client->playerTeam == TEAM_PLAYER || attacker->client->NPC_class == CLASS_SHADOWTROOPER || + attacker->client->NPC_class == CLASS_TAVION || + attacker->client->NPC_class == CLASS_DESANN))) //&&attackStrength==FORCE_LEVEL_3) + { // player,. player allies, shadowtroopers, tavion and desann use larger traces + vec3_t traceMins = {-2, -2, -2}, traceMaxs = {2, 2, 2}; + gi.trace(&tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10); // G2_SUPERSIZEDBBOX } /* else if ( !attacker->s.number ) @@ -1485,46 +1219,35 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg gi.trace( &tr, start, traceMins, traceMaxs, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX } */ - else - {//reborn use smaller traces - gi.trace( &tr, start, NULL, NULL, end2, ignore, mask, G2_COLLIDE, 10 );//G2_SUPERSIZEDBBOX + else { // reborn use smaller traces + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask, G2_COLLIDE, 10); // G2_SUPERSIZEDBBOX } + } else { + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask, G2_NOCOLLIDE, 10); } - else - { - gi.trace( &tr, start, NULL, NULL, end2, ignore, mask, G2_NOCOLLIDE, 10 ); - } - #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( attacker != NULL && attacker->client != NULL ) - { - G_DebugLine(start, end2, FRAMETIME, WPDEBUG_SaberColor( attacker->client->ps.saberColor ), qtrue); + if (d_saberCombat->integer > 1) { + if (attacker != NULL && attacker->client != NULL) { + G_DebugLine(start, end2, FRAMETIME, WPDEBUG_SaberColor(attacker->client->ps.saberColor), qtrue); } } #endif - if ( tr.entityNum == ENTITYNUM_NONE ) - { + if (tr.entityNum == ENTITYNUM_NONE) { return qfalse; } - if ( tr.entityNum == ENTITYNUM_WORLD ) - { + if (tr.entityNum == ENTITYNUM_WORLD) { return qtrue; } - if ( &g_entities[tr.entityNum] ) - { + if (&g_entities[tr.entityNum]) { gentity_t *hitEnt = &g_entities[tr.entityNum]; gentity_t *owner = g_entities[tr.entityNum].owner; - if ( hitEnt->contents & CONTENTS_LIGHTSABER ) - { - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - {//thrown saber hit something - if ( owner + if (hitEnt->contents & CONTENTS_LIGHTSABER) { + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { // thrown saber hit something + if ( owner && owner->s.number && owner->client && owner->NPC @@ -1534,65 +1257,54 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg || (Q_irand( -5, owner->NPC->rank ) > RANK_CIVILIAN && !Q_irand( 0, g_spskill->integer*3 ))*/ ) ) {//Tavion can toss a blocked thrown saber aside - WP_SaberKnockaway( attacker, &tr ); - Jedi_PlayDeflectSound( owner ); + WP_SaberKnockaway(attacker, &tr); + Jedi_PlayDeflectSound(owner); return qfalse; - } + } } - //FIXME: take target FP_SABER_DEFENSE and attacker FP_SABER_OFFENSE into account here somehow? - qboolean sabersIntersect = WP_SabersIntersect( attacker, owner, qfalse );//qtrue ); + // FIXME: take target FP_SABER_DEFENSE and attacker FP_SABER_OFFENSE into account here somehow? + qboolean sabersIntersect = WP_SabersIntersect(attacker, owner, qfalse); // qtrue ); float sabersDist; - if ( attacker && attacker->client && attacker->client->ps.saberInFlight - && owner && owner->s.number == 0 && (g_saberAutoBlocking->integer||attacker->client->ps.saberBlockingTime>level.time) )//NPC flying saber hit player's saber bounding box - {//players have g_saberAutoBlocking, do the more generous check against flying sabers - //FIXME: instead of hitting the player's saber bounding box - //and picking an anim afterwards, have him use AI similar - //to the AI the jedi use for picking a saber melee block...? + if (attacker && attacker->client && attacker->client->ps.saberInFlight && owner && owner->s.number == 0 && + (g_saberAutoBlocking->integer || attacker->client->ps.saberBlockingTime > level.time)) // NPC flying saber hit player's saber bounding box + { // players have g_saberAutoBlocking, do the more generous check against flying sabers + // FIXME: instead of hitting the player's saber bounding box + // and picking an anim afterwards, have him use AI similar + // to the AI the jedi use for picking a saber melee block...? sabersDist = 0; - } - else - {//sabers must actually collide with the attacking saber - sabersDist = WP_SabersDistance( attacker, owner ); - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - { + } else { // sabers must actually collide with the attacking saber + sabersDist = WP_SabersDistance(attacker, owner); + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { sabersDist /= 2.0f; - if ( sabersDist <= 16.0f ) - { + if (sabersDist <= 16.0f) { sabersIntersect = qtrue; } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - gi.Printf( "sabersDist: %4.2f\n", sabersDist ); + if (d_saberCombat->integer > 1) { + gi.Printf("sabersDist: %4.2f\n", sabersDist); } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } - if ( sabersCrossed == -1 || sabersCrossed > sabersDist ) - { + if (sabersCrossed == -1 || sabersCrossed > sabersDist) { sabersCrossed = sabersDist; } - float collisionDist; - if ( g_saberRealisticCombat->integer ) - { + float collisionDist; + if (g_saberRealisticCombat->integer) { collisionDist = SABER_COLLISION_DIST; - } - else - { - collisionDist = SABER_COLLISION_DIST+6+g_spskill->integer*4; - } - if ( owner && owner->client && (attacker != NULL) - && (sabersDist > collisionDist )//|| !InFront( attacker->currentOrigin, owner->currentOrigin, owner->client->ps.viewangles, 0.35f )) - && !sabersIntersect )//was qtrue, but missed too much? - {//swing came from behind and/or was not stopped by a lightsaber - //re-try the trace without checking for lightsabers - gi.trace ( &tr, start, NULL, NULL, end2, ignore, mask&~CONTENTS_LIGHTSABER, G2_NOCOLLIDE, 10 ); - if ( tr.entityNum == ENTITYNUM_WORLD ) - { - return qtrue; + } else { + collisionDist = SABER_COLLISION_DIST + 6 + g_spskill->integer * 4; + } + if (owner && owner->client && (attacker != NULL) && + (sabersDist > collisionDist) //|| !InFront( attacker->currentOrigin, owner->currentOrigin, owner->client->ps.viewangles, 0.35f )) + && !sabersIntersect) // was qtrue, but missed too much? + { // swing came from behind and/or was not stopped by a lightsaber + // re-try the trace without checking for lightsabers + gi.trace(&tr, start, NULL, NULL, end2, ignore, mask & ~CONTENTS_LIGHTSABER, G2_NOCOLLIDE, 10); + if (tr.entityNum == ENTITYNUM_WORLD) { + return qtrue; } - if ( tr.entityNum == ENTITYNUM_NONE || &g_entities[tr.entityNum] == NULL ) - {//didn't hit the owner + if (tr.entityNum == ENTITYNUM_NONE || &g_entities[tr.entityNum] == NULL) { // didn't hit the owner /* if ( attacker && attacker->client @@ -1618,74 +1330,57 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg } } */ - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_MAGENTA"%d saber hit owner through saber %4.2f, dist = %4.2f\n", level.time, saberHitFraction, sabersDist ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_MAGENTA "%d saber hit owner through saber %4.2f, dist = %4.2f\n", level.time, saberHitFraction, sabersDist); } } -#endif//FINAL_BUILD +#endif // FINAL_BUILD hitEnt = &g_entities[tr.entityNum]; owner = g_entities[tr.entityNum].owner; - } - else - {//hit a lightsaber - if ( (tr.fraction < saberHitFraction || tr.startsolid) - && sabersDist < (8.0f+g_spskill->value)*4.0f// 50.0f//16.0f - && (sabersIntersect || sabersDist < (4.0f+g_spskill->value)*2.0f) )//32.0f) ) - { // This saber hit closer than the last one. - if ( (tr.allsolid || tr.startsolid) && owner && owner->client ) - {//tr.fraction will be 0, unreliable... so calculate actual - float dist = Distance( start, end2 ); - if ( dist ) - { - float hitFrac = WP_SabersDistance( attacker, owner )/dist; - if ( hitFrac > 1.0f ) - {//umm... minimum distance between sabers was longer than trace...? + } else { // hit a lightsaber + if ((tr.fraction < saberHitFraction || tr.startsolid) && sabersDist < (8.0f + g_spskill->value) * 4.0f // 50.0f//16.0f + && (sabersIntersect || sabersDist < (4.0f + g_spskill->value) * 2.0f)) // 32.0f) ) + { // This saber hit closer than the last one. + if ((tr.allsolid || tr.startsolid) && owner && owner->client) { // tr.fraction will be 0, unreliable... so calculate actual + float dist = Distance(start, end2); + if (dist) { + float hitFrac = WP_SabersDistance(attacker, owner) / dist; + if (hitFrac > 1.0f) { // umm... minimum distance between sabers was longer than trace...? hitFrac = 1.0f; } - if ( hitFrac < saberHitFraction ) - { + if (hitFrac < saberHitFraction) { saberHitFraction = hitFrac; } - } - else - { + } else { saberHitFraction = 0.0f; } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_GREEN"%d saber hit saber dist %4.2f allsolid %4.2f\n", level.time, sabersDist, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_GREEN "%d saber hit saber dist %4.2f allsolid %4.2f\n", level.time, sabersDist, saberHitFraction); } } -#endif//FINAL_BUILD - } - else - { +#endif // FINAL_BUILD + } else { #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_BLUE"%d saber hit saber dist %4.2f, frac %4.2f\n", level.time, sabersDist, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_BLUE "%d saber hit saber dist %4.2f, frac %4.2f\n", level.time, sabersDist, saberHitFraction); } saberHitFraction = tr.fraction; } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_MAGENTA"hit saber: saberHitFraction %4.2f, allsolid %d, startsolid %d\n", saberHitFraction, tr.allsolid, tr.startsolid ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_MAGENTA "hit saber: saberHitFraction %4.2f, allsolid %d, startsolid %d\n", saberHitFraction, tr.allsolid, + tr.startsolid); } -#endif//FINAL_BUILD +#endif // FINAL_BUILD VectorCopy(tr.endpos, saberHitLocation); saberHitEntity = tr.entityNum; } @@ -1716,118 +1411,94 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg } } */ - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } - } - else - { + } else { #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !attacker->s.number ) - { - gi.Printf( S_COLOR_RED"%d saber hit owner directly %4.2f\n", level.time, saberHitFraction ); + if (d_saberCombat->integer > 1) { + if (!attacker->s.number) { + gi.Printf(S_COLOR_RED "%d saber hit owner directly %4.2f\n", level.time, saberHitFraction); } } -#endif//FINAL_BUILD +#endif // FINAL_BUILD } - if ( attacker && attacker->client && attacker->client->ps.saberInFlight ) - {//thrown saber hit something - if ( ( hitEnt && hitEnt->client && hitEnt->health > 0 && ( hitEnt->client->NPC_class == CLASS_DESANN || hitEnt->client->NPC_class == CLASS_LUKE || (hitEnt->client->NPC_class == CLASS_GALAKMECH&&hitEnt->client->ps.powerups[PW_GALAK_SHIELD] > 0) ) ) || - ( owner && owner->client && owner->health > 0 && ( owner->client->NPC_class == CLASS_DESANN || owner->client->NPC_class == CLASS_LUKE || (owner->client->NPC_class==CLASS_GALAKMECH&&owner->client->ps.powerups[PW_GALAK_SHIELD] > 0) ) ) ) - {//Luke and Desann slap thrown sabers aside - //FIXME: control the direction of the thrown saber... if hit Galak's shield, bounce directly away from his origin? - WP_SaberKnockaway( attacker, &tr ); - if ( hitEnt->client ) - { - Jedi_PlayDeflectSound( hitEnt ); - } - else - { - Jedi_PlayDeflectSound( owner ); + if (attacker && attacker->client && attacker->client->ps.saberInFlight) { // thrown saber hit something + if ((hitEnt && hitEnt->client && hitEnt->health > 0 && + (hitEnt->client->NPC_class == CLASS_DESANN || hitEnt->client->NPC_class == CLASS_LUKE || + (hitEnt->client->NPC_class == CLASS_GALAKMECH && hitEnt->client->ps.powerups[PW_GALAK_SHIELD] > 0))) || + (owner && owner->client && owner->health > 0 && + (owner->client->NPC_class == CLASS_DESANN || owner->client->NPC_class == CLASS_LUKE || + (owner->client->NPC_class == CLASS_GALAKMECH && + owner->client->ps.powerups[PW_GALAK_SHIELD] > 0)))) { // Luke and Desann slap thrown sabers aside + // FIXME: control the direction of the thrown saber... if hit Galak's shield, bounce directly away from his origin? + WP_SaberKnockaway(attacker, &tr); + if (hitEnt->client) { + Jedi_PlayDeflectSound(hitEnt); + } else { + Jedi_PlayDeflectSound(owner); } - return qfalse; // Exit, but we didn't hit the wall. + return qfalse; // Exit, but we didn't hit the wall. } } - if ( hitEnt->takedamage ) - { - //no team damage: if ( !hitEnt->client || attacker == NULL || !attacker->client || (hitEnt->client->playerTeam != attacker->client->playerTeam) ) + if (hitEnt->takedamage) { + // no team damage: if ( !hitEnt->client || attacker == NULL || !attacker->client || (hitEnt->client->playerTeam != attacker->client->playerTeam) ) { - //multiply the damage by the total distance of the swipe - VectorSubtract( end2, start, dir ); - float len = VectorNormalize( dir );//VectorLength( dir ); - if ( noGhoul || !hitEnt->ghoul2.size() ) - {//we weren't doing a ghoul trace - char *hitEffect; - if ( dmg >= 1.0 && hitEnt->bmodel ) - { + // multiply the damage by the total distance of the swipe + VectorSubtract(end2, start, dir); + float len = VectorNormalize(dir); // VectorLength( dir ); + if (noGhoul || !hitEnt->ghoul2.size()) { // we weren't doing a ghoul trace + char *hitEffect; + if (dmg >= 1.0 && hitEnt->bmodel) { dmg = 1.0; } - if ( len > 1 ) - { + if (len > 1) { dmg *= len; } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 1 ) - { - if ( !(hitEnt->contents & CONTENTS_LIGHTSABER) ) - { - gi.Printf( S_COLOR_GREEN"Hit ent, but no ghoul collisions\n" ); + if (d_saberCombat->integer > 1) { + if (!(hitEnt->contents & CONTENTS_LIGHTSABER)) { + gi.Printf(S_COLOR_GREEN "Hit ent, but no ghoul collisions\n"); } } #endif - float trFrac, dmgFrac; - if ( tr.allsolid ) - {//totally inside them + float trFrac, dmgFrac; + if (tr.allsolid) { // totally inside them trFrac = 1.0; dmgFrac = 0.0; - } - else if ( tr.startsolid ) - {//started inside them - //we don't know how much was inside, we know it's less than all, so use half? + } else if (tr.startsolid) { // started inside them + // we don't know how much was inside, we know it's less than all, so use half? trFrac = 0.5; dmgFrac = 0.0; - } - else - {//started outside them and hit them - //yeah. this doesn't account for coming out the other wide, but we can worry about that later (use ghoul2) + } else { // started outside them and hit them + // yeah. this doesn't account for coming out the other wide, but we can worry about that later (use ghoul2) trFrac = (1.0f - tr.fraction); dmgFrac = tr.fraction; } - WP_SaberDamageAdd( trFrac, tr.entityNum, dir, tr.endpos, dmg, dmgFrac, HL_NONE, qfalse, HL_NONE ); - if ( !tr.allsolid && !tr.startsolid ) - { - VectorScale( dir, -1, dir ); + WP_SaberDamageAdd(trFrac, tr.entityNum, dir, tr.endpos, dmg, dmgFrac, HL_NONE, qfalse, HL_NONE); + if (!tr.allsolid && !tr.startsolid) { + VectorScale(dir, -1, dir); } - //FIXME: don't do blood sparks on non-living things + // FIXME: don't do blood sparks on non-living things hitEffect = hit_blood_sparks; - if ( hitEnt != NULL ) - { - if ( hitEnt->client ) - { + if (hitEnt != NULL) { + if (hitEnt->client) { class_t npc_class = hitEnt->client->NPC_class; - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || npc_class == CLASS_PROTOCOL || + npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || + npc_class == CLASS_SENTRY) { hitEffect = hit_sparks; } - } - else - { + } else { hitEffect = hit_sparks; } } - G_PlayEffect( hitEffect, tr.endpos, dir );//"saber_cut" - } - else - {//we were doing a ghoul trace - if ( !WP_SaberDamageEffects( &tr, start, len, dmg, dir, bladeDir, attacker->client->enemyTeam ) ) - {//didn't hit a ghoul ent + G_PlayEffect(hitEffect, tr.endpos, dir); //"saber_cut" + } else { // we were doing a ghoul trace + if (!WP_SaberDamageEffects(&tr, start, len, dmg, dir, bladeDir, attacker->client->enemyTeam)) { // didn't hit a ghoul ent /* if ( && hitEnt->ghoul2.size() ) {//it was a ghoul2 model so we should have hit it @@ -1843,36 +1514,22 @@ qboolean WP_SaberDamageForTrace( int ignore, vec3_t start, vec3_t end, float dmg return qfalse; } -typedef enum -{ - LOCK_FIRST = 0, - LOCK_TOP = LOCK_FIRST, - LOCK_DIAG_TR, - LOCK_DIAG_TL, - LOCK_DIAG_BR, - LOCK_DIAG_BL, - LOCK_R, - LOCK_L, - LOCK_RANDOM -} sabersLockMode_t; +typedef enum { LOCK_FIRST = 0, LOCK_TOP = LOCK_FIRST, LOCK_DIAG_TR, LOCK_DIAG_TL, LOCK_DIAG_BR, LOCK_DIAG_BL, LOCK_R, LOCK_L, LOCK_RANDOM } sabersLockMode_t; #define LOCK_IDEAL_DIST_TOP 32.0f #define LOCK_IDEAL_DIST_CIRCLE 48.0f -extern void PM_SetAnimFrame( gentity_t *gent, int frame, qboolean torso, qboolean legs ); -extern qboolean ValidAnimFileIndex ( int index ); -qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ) -{ +extern void PM_SetAnimFrame(gentity_t *gent, int frame, qboolean torso, qboolean legs); +extern qboolean ValidAnimFileIndex(int index); +qboolean WP_SabersCheckLock2(gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode) { animation_t *anim; - int attAnim, defAnim, advance = 0; - float attStart = 0.5f; - float idealDist = 48.0f; - //MATCH ANIMS - if ( lockMode == LOCK_RANDOM ) - { - lockMode = (sabersLockMode_t)Q_irand( (int)LOCK_FIRST, (int)(LOCK_RANDOM)-1 ); - } - switch ( lockMode ) - { + int attAnim, defAnim, advance = 0; + float attStart = 0.5f; + float idealDist = 48.0f; + // MATCH ANIMS + if (lockMode == LOCK_RANDOM) { + lockMode = (sabersLockMode_t)Q_irand((int)LOCK_FIRST, (int)(LOCK_RANDOM)-1); + } + switch (lockMode) { case LOCK_TOP: attAnim = BOTH_BF2LOCK; defAnim = BOTH_BF1LOCK; @@ -1919,242 +1576,185 @@ qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLo return qfalse; break; } - NPC_SetAnim( attacker, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - NPC_SetAnim( defender, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if( ValidAnimFileIndex( attacker->client->clientInfo.animFileIndex ) ) - { + NPC_SetAnim(attacker, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + NPC_SetAnim(defender, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (ValidAnimFileIndex(attacker->client->clientInfo.animFileIndex)) { anim = &level.knownAnimFileSets[attacker->client->clientInfo.animFileIndex].animations[attAnim]; - advance = floor( anim->numFrames*attStart ); - PM_SetAnimFrame( attacker, anim->firstFrame + advance, qtrue, qtrue ); + advance = floor(anim->numFrames * attStart); + PM_SetAnimFrame(attacker, anim->firstFrame + advance, qtrue, qtrue); #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - Com_Printf( "%s starting saber lock, anim = %s, %d frames to go!\n", attacker->NPC_type, animTable[attAnim].name, anim->numFrames-advance ); + if (d_saberCombat->integer) { + Com_Printf("%s starting saber lock, anim = %s, %d frames to go!\n", attacker->NPC_type, animTable[attAnim].name, anim->numFrames - advance); } #endif } - if( ValidAnimFileIndex( defender->client->clientInfo.animFileIndex ) ) - { + if (ValidAnimFileIndex(defender->client->clientInfo.animFileIndex)) { anim = &level.knownAnimFileSets[defender->client->clientInfo.animFileIndex].animations[defAnim]; - PM_SetAnimFrame( defender, anim->firstFrame + advance, qtrue, qtrue );//was anim->firstFrame + anim->numFrames - advance, but that's wrong since they are matched anims + PM_SetAnimFrame(defender, anim->firstFrame + advance, qtrue, + qtrue); // was anim->firstFrame + anim->numFrames - advance, but that's wrong since they are matched anims #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - Com_Printf( "%s starting saber lock, anim = %s, %d frames to go!\n", defender->NPC_type, animTable[defAnim].name, advance ); + if (d_saberCombat->integer) { + Com_Printf("%s starting saber lock, anim = %s, %d frames to go!\n", defender->NPC_type, animTable[defAnim].name, advance); } #endif } - VectorClear( attacker->client->ps.velocity ); - VectorClear( defender->client->ps.velocity ); + VectorClear(attacker->client->ps.velocity); + VectorClear(defender->client->ps.velocity); attacker->client->ps.saberLockTime = defender->client->ps.saberLockTime = level.time + SABER_LOCK_TIME; - attacker->client->ps.legsAnimTimer = attacker->client->ps.torsoAnimTimer = defender->client->ps.legsAnimTimer = defender->client->ps.torsoAnimTimer = SABER_LOCK_TIME; - //attacker->client->ps.weaponTime = defender->client->ps.weaponTime = SABER_LOCK_TIME; + attacker->client->ps.legsAnimTimer = attacker->client->ps.torsoAnimTimer = defender->client->ps.legsAnimTimer = defender->client->ps.torsoAnimTimer = + SABER_LOCK_TIME; + // attacker->client->ps.weaponTime = defender->client->ps.weaponTime = SABER_LOCK_TIME; attacker->client->ps.saberLockEnemy = defender->s.number; defender->client->ps.saberLockEnemy = attacker->s.number; - //MATCH ANGLES - //FIXME: if zDiff in elevation, make lower look up and upper look down and move them closer? - float defPitchAdd = 0, zDiff = ((attacker->currentOrigin[2]+attacker->client->standheight)-(defender->currentOrigin[2]+defender->client->standheight)); - if ( zDiff > 24 ) - { + // MATCH ANGLES + // FIXME: if zDiff in elevation, make lower look up and upper look down and move them closer? + float defPitchAdd = 0, + zDiff = ((attacker->currentOrigin[2] + attacker->client->standheight) - (defender->currentOrigin[2] + defender->client->standheight)); + if (zDiff > 24) { defPitchAdd = -30; - } - else if ( zDiff < -24 ) - { + } else if (zDiff < -24) { defPitchAdd = 30; + } else { + defPitchAdd = zDiff / 24.0f * -30.0f; } - else - { - defPitchAdd = zDiff/24.0f*-30.0f; - } - if ( attacker->NPC && defender->NPC ) - {//if 2 NPCs, just set pitch to 0 + if (attacker->NPC && defender->NPC) { // if 2 NPCs, just set pitch to 0 attacker->client->ps.viewangles[PITCH] = -defPitchAdd; defender->client->ps.viewangles[PITCH] = defPitchAdd; - } - else - {//if a player is involved, clamp player's pitch and match NPC's to player - if ( !attacker->s.number ) - { - //clamp to defPitch - if ( attacker->client->ps.viewangles[PITCH] > -defPitchAdd + 10 ) - { + } else { // if a player is involved, clamp player's pitch and match NPC's to player + if (!attacker->s.number) { + // clamp to defPitch + if (attacker->client->ps.viewangles[PITCH] > -defPitchAdd + 10) { attacker->client->ps.viewangles[PITCH] = -defPitchAdd + 10; + } else if (attacker->client->ps.viewangles[PITCH] < -defPitchAdd - 10) { + attacker->client->ps.viewangles[PITCH] = -defPitchAdd - 10; } - else if ( attacker->client->ps.viewangles[PITCH] < -defPitchAdd-10 ) - { - attacker->client->ps.viewangles[PITCH] = -defPitchAdd-10; - } - //clamp to sane numbers - if ( attacker->client->ps.viewangles[PITCH] > 50 ) - { + // clamp to sane numbers + if (attacker->client->ps.viewangles[PITCH] > 50) { attacker->client->ps.viewangles[PITCH] = 50; - } - else if ( attacker->client->ps.viewangles[PITCH] < -50 ) - { + } else if (attacker->client->ps.viewangles[PITCH] < -50) { attacker->client->ps.viewangles[PITCH] = -50; } - defender->client->ps.viewangles[PITCH] = attacker->client->ps.viewangles[PITCH]*-1; + defender->client->ps.viewangles[PITCH] = attacker->client->ps.viewangles[PITCH] * -1; defPitchAdd = defender->client->ps.viewangles[PITCH]; - } - else if ( !defender->s.number ) - { - //clamp to defPitch - if ( defender->client->ps.viewangles[PITCH] > defPitchAdd + 10 ) - { + } else if (!defender->s.number) { + // clamp to defPitch + if (defender->client->ps.viewangles[PITCH] > defPitchAdd + 10) { defender->client->ps.viewangles[PITCH] = defPitchAdd + 10; + } else if (defender->client->ps.viewangles[PITCH] < defPitchAdd - 10) { + defender->client->ps.viewangles[PITCH] = defPitchAdd - 10; } - else if ( defender->client->ps.viewangles[PITCH] < defPitchAdd-10 ) - { - defender->client->ps.viewangles[PITCH] = defPitchAdd-10; - } - //clamp to sane numbers - if ( defender->client->ps.viewangles[PITCH] > 50 ) - { + // clamp to sane numbers + if (defender->client->ps.viewangles[PITCH] > 50) { defender->client->ps.viewangles[PITCH] = 50; - } - else if ( defender->client->ps.viewangles[PITCH] < -50 ) - { + } else if (defender->client->ps.viewangles[PITCH] < -50) { defender->client->ps.viewangles[PITCH] = -50; } defPitchAdd = defender->client->ps.viewangles[PITCH]; - attacker->client->ps.viewangles[PITCH] = defender->client->ps.viewangles[PITCH]*-1; + attacker->client->ps.viewangles[PITCH] = defender->client->ps.viewangles[PITCH] * -1; } } - vec3_t attAngles, defAngles, defDir; - VectorSubtract( defender->currentOrigin, attacker->currentOrigin, defDir ); - VectorCopy( attacker->client->ps.viewangles, attAngles ); - attAngles[YAW] = vectoyaw( defDir ); - SetClientViewAngle( attacker, attAngles ); - defAngles[PITCH] = attAngles[PITCH]*-1; - defAngles[YAW] = AngleNormalize180( attAngles[YAW] + 180); + vec3_t attAngles, defAngles, defDir; + VectorSubtract(defender->currentOrigin, attacker->currentOrigin, defDir); + VectorCopy(attacker->client->ps.viewangles, attAngles); + attAngles[YAW] = vectoyaw(defDir); + SetClientViewAngle(attacker, attAngles); + defAngles[PITCH] = attAngles[PITCH] * -1; + defAngles[YAW] = AngleNormalize180(attAngles[YAW] + 180); defAngles[ROLL] = 0; - SetClientViewAngle( defender, defAngles ); + SetClientViewAngle(defender, defAngles); - //MATCH POSITIONS - vec3_t newOrg; + // MATCH POSITIONS + vec3_t newOrg; /* idealDist -= fabs(defPitchAdd)/8.0f; */ - float scale = VectorLength( attacker->s.modelScale ); - if ( scale ) - { - idealDist += 8*(scale-1.0f); - } - scale = VectorLength( defender->s.modelScale ); - if ( scale ) - { - idealDist += 8*(scale-1.0f); - } - - float diff = VectorNormalize( defDir ) - idealDist;//diff will be the total error in dist - //try to move attacker half the diff towards the defender - VectorMA( attacker->currentOrigin, diff*0.5f, defDir, newOrg ); - trace_t trace; - gi.trace( &trace, attacker->currentOrigin, attacker->mins, attacker->maxs, newOrg, attacker->s.number, attacker->clipmask, G2_NOCOLLIDE, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - G_SetOrigin( attacker, trace.endpos ); - gi.linkentity( attacker ); - } - //now get the defender's dist and do it for him too - vec3_t attDir; - VectorSubtract( attacker->currentOrigin, defender->currentOrigin, attDir ); - diff = VectorNormalize( attDir ) - idealDist;//diff will be the total error in dist - //try to move defender all of the remaining diff towards the attacker - VectorMA( defender->currentOrigin, diff, attDir, newOrg ); - gi.trace( &trace, defender->currentOrigin, defender->mins, defender->maxs, newOrg, defender->s.number, defender->clipmask, G2_NOCOLLIDE, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - G_SetOrigin( defender, trace.endpos ); - gi.linkentity( defender ); - } - - //DONE! + float scale = VectorLength(attacker->s.modelScale); + if (scale) { + idealDist += 8 * (scale - 1.0f); + } + scale = VectorLength(defender->s.modelScale); + if (scale) { + idealDist += 8 * (scale - 1.0f); + } + + float diff = VectorNormalize(defDir) - idealDist; // diff will be the total error in dist + // try to move attacker half the diff towards the defender + VectorMA(attacker->currentOrigin, diff * 0.5f, defDir, newOrg); + trace_t trace; + gi.trace(&trace, attacker->currentOrigin, attacker->mins, attacker->maxs, newOrg, attacker->s.number, attacker->clipmask, G2_NOCOLLIDE, 0); + if (!trace.startsolid && !trace.allsolid) { + G_SetOrigin(attacker, trace.endpos); + gi.linkentity(attacker); + } + // now get the defender's dist and do it for him too + vec3_t attDir; + VectorSubtract(attacker->currentOrigin, defender->currentOrigin, attDir); + diff = VectorNormalize(attDir) - idealDist; // diff will be the total error in dist + // try to move defender all of the remaining diff towards the attacker + VectorMA(defender->currentOrigin, diff, attDir, newOrg); + gi.trace(&trace, defender->currentOrigin, defender->mins, defender->maxs, newOrg, defender->s.number, defender->clipmask, G2_NOCOLLIDE, 0); + if (!trace.startsolid && !trace.allsolid) { + G_SetOrigin(defender, trace.endpos); + gi.linkentity(defender); + } + + // DONE! return qtrue; } -qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) -{ - if ( ent1->client->playerTeam == ent2->client->playerTeam ) - { +qboolean WP_SabersCheckLock(gentity_t *ent1, gentity_t *ent2) { + if (ent1->client->playerTeam == ent2->client->playerTeam) { return qfalse; } - if ( ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || - ent2->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + if (ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || ent2->client->ps.groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - if ( ent1->painDebounceTime > level.time-1000 || ent2->painDebounceTime > level.time-1000 ) - {//can't saberlock if you're not ready + if (ent1->painDebounceTime > level.time - 1000 || ent2->painDebounceTime > level.time - 1000) { // can't saberlock if you're not ready return qfalse; } - if ( fabs( ent1->currentOrigin[2]-ent2->currentOrigin[2]) > 18 ) - { + if (fabs(ent1->currentOrigin[2] - ent2->currentOrigin[2]) > 18) { return qfalse; } - float dist = DistanceSquared(ent1->currentOrigin,ent2->currentOrigin); - if ( dist < 64 || dist > 6400 )//( dist < 128 || dist > 2304 ) - {//between 8 and 80 from each other//was 16 and 48 + float dist = DistanceSquared(ent1->currentOrigin, ent2->currentOrigin); + if (dist < 64 || dist > 6400) //( dist < 128 || dist > 2304 ) + { // between 8 and 80 from each other//was 16 and 48 return qfalse; } - if ( !InFOV( ent1, ent2, 40, 180 ) || !InFOV( ent2, ent1, 40, 180 ) ) - { + if (!InFOV(ent1, ent2, 40, 180) || !InFOV(ent2, ent1, 40, 180)) { return qfalse; } - //Check for certain anims that *cannot* lock - //FIXME: there should probably be a whole *list* of these, but I'll put them in as they come up - if ( ent1->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent1->client->ps.torsoAnimTimer > 300 ) - {//can't lock when saber is behind you + // Check for certain anims that *cannot* lock + // FIXME: there should probably be a whole *list* of these, but I'll put them in as they come up + if (ent1->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent1->client->ps.torsoAnimTimer > 300) { // can't lock when saber is behind you return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent2->client->ps.torsoAnimTimer > 300 ) - {//can't lock when saber is behind you + if (ent2->client->ps.torsoAnim == BOTH_A2_STABBACK1 && ent2->client->ps.torsoAnimTimer > 300) { // can't lock when saber is behind you return qfalse; } - //BR to TL lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A5_BR_TL ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BR ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A5_BR_TL ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BR ); - } - //BL to TR lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A5_BL_TR ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BL ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A5_BL_TR ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BL ); - } - //L to R lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__L__R || - ent1->client->ps.torsoAnim == BOTH_A2__L__R || - ent1->client->ps.torsoAnim == BOTH_A3__L__R || - ent1->client->ps.torsoAnim == BOTH_A4__L__R || - ent1->client->ps.torsoAnim == BOTH_A5__L__R ) - {//ent1 is attacking l to r - return WP_SabersCheckLock2( ent1, ent2, LOCK_L ); + // BR to TL lock + if (ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || ent1->client->ps.torsoAnim == BOTH_A5_BR_TL) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BR); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || ent2->client->ps.torsoAnim == BOTH_A5_BR_TL) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BR); + } + // BL to TR lock + if (ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || ent1->client->ps.torsoAnim == BOTH_A5_BL_TR) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BL); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || ent2->client->ps.torsoAnim == BOTH_A5_BL_TR) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BL); + } + // L to R lock + if (ent1->client->ps.torsoAnim == BOTH_A1__L__R || ent1->client->ps.torsoAnim == BOTH_A2__L__R || ent1->client->ps.torsoAnim == BOTH_A3__L__R || + ent1->client->ps.torsoAnim == BOTH_A4__L__R || ent1->client->ps.torsoAnim == BOTH_A5__L__R) { // ent1 is attacking l to r + return WP_SabersCheckLock2(ent1, ent2, LOCK_L); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -2176,13 +1776,9 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1__L__R || - ent2->client->ps.torsoAnim == BOTH_A2__L__R || - ent2->client->ps.torsoAnim == BOTH_A3__L__R || - ent2->client->ps.torsoAnim == BOTH_A4__L__R || - ent2->client->ps.torsoAnim == BOTH_A5__L__R ) - {//ent2 is attacking l to r - return WP_SabersCheckLock2( ent2, ent1, LOCK_L ); + if (ent2->client->ps.torsoAnim == BOTH_A1__L__R || ent2->client->ps.torsoAnim == BOTH_A2__L__R || ent2->client->ps.torsoAnim == BOTH_A3__L__R || + ent2->client->ps.torsoAnim == BOTH_A4__L__R || ent2->client->ps.torsoAnim == BOTH_A5__L__R) { // ent2 is attacking l to r + return WP_SabersCheckLock2(ent2, ent1, LOCK_L); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -2204,14 +1800,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //R to L lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__R__L || - ent1->client->ps.torsoAnim == BOTH_A2__R__L || - ent1->client->ps.torsoAnim == BOTH_A3__R__L || - ent1->client->ps.torsoAnim == BOTH_A4__R__L || - ent1->client->ps.torsoAnim == BOTH_A5__R__L ) - {//ent1 is attacking r to l - return WP_SabersCheckLock2( ent1, ent2, LOCK_R ); + // R to L lock + if (ent1->client->ps.torsoAnim == BOTH_A1__R__L || ent1->client->ps.torsoAnim == BOTH_A2__R__L || ent1->client->ps.torsoAnim == BOTH_A3__R__L || + ent1->client->ps.torsoAnim == BOTH_A4__R__L || ent1->client->ps.torsoAnim == BOTH_A5__R__L) { // ent1 is attacking r to l + return WP_SabersCheckLock2(ent1, ent2, LOCK_R); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -2233,13 +1825,9 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1__R__L || - ent2->client->ps.torsoAnim == BOTH_A2__R__L || - ent2->client->ps.torsoAnim == BOTH_A3__R__L || - ent2->client->ps.torsoAnim == BOTH_A4__R__L || - ent2->client->ps.torsoAnim == BOTH_A5__R__L ) - {//ent2 is attacking r to l - return WP_SabersCheckLock2( ent2, ent1, LOCK_R ); + if (ent2->client->ps.torsoAnim == BOTH_A1__R__L || ent2->client->ps.torsoAnim == BOTH_A2__R__L || ent2->client->ps.torsoAnim == BOTH_A3__R__L || + ent2->client->ps.torsoAnim == BOTH_A4__R__L || ent2->client->ps.torsoAnim == BOTH_A5__R__L) { // ent2 is attacking r to l + return WP_SabersCheckLock2(ent2, ent1, LOCK_R); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -2261,14 +1849,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //TR to BL lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A5_TR_BL ) - {//ent1 is attacking diagonally - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TR ); + // TR to BL lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || ent1->client->ps.torsoAnim == BOTH_A5_TR_BL) { // ent1 is attacking diagonally + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TR); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -2299,13 +1883,9 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A5_TR_BL ) - {//ent2 is attacking diagonally - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TR ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || ent2->client->ps.torsoAnim == BOTH_A5_TR_BL) { // ent2 is attacking diagonally + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TR); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -2336,14 +1916,10 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - //TL to BR lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A5_TL_BR ) - {//ent1 is attacking diagonally - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TL ); + // TL to BR lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || ent1->client->ps.torsoAnim == BOTH_A5_TL_BR) { // ent1 is attacking diagonally + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TL); /* if ( ent2BlockingPlayer ) {//player will block this anyway @@ -2374,13 +1950,9 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) */ } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A5_TL_BR ) - {//ent2 is attacking diagonally - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TL ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || ent2->client->ps.torsoAnim == BOTH_A5_TL_BR) { // ent2 is attacking diagonally + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TL); /* if ( ent1BlockingPlayer ) {//player will block this anyway @@ -2410,34 +1982,26 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) } */ } - //T to B lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A5_T__B_ ) - {//ent1 is attacking top-down + // T to B lock + if (ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || ent1->client->ps.torsoAnim == BOTH_A5_T__B_) { // ent1 is attacking top-down /* if ( ent2->client->ps.torsoAnim == BOTH_P1_S1_T_ || ent2->client->ps.torsoAnim == BOTH_K1_S1_T_ ) */ - {//ent2 is blocking at top - return WP_SabersCheckLock2( ent1, ent2, LOCK_TOP ); + { // ent2 is blocking at top + return WP_SabersCheckLock2(ent1, ent2, LOCK_TOP); } } - if ( ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A5_T__B_ ) - {//ent2 is attacking top-down + if (ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || ent2->client->ps.torsoAnim == BOTH_A5_T__B_) { // ent2 is attacking top-down /* if ( ent1->client->ps.torsoAnim == BOTH_P1_S1_T_ || ent1->client->ps.torsoAnim == BOTH_K1_S1_T_ ) */ - {//ent1 is blocking at top - return WP_SabersCheckLock2( ent2, ent1, LOCK_TOP ); + { // ent1 is blocking at top + return WP_SabersCheckLock2(ent2, ent1, LOCK_TOP); } } /* @@ -2449,57 +2013,44 @@ qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) return qfalse; } -qboolean WP_SaberParry( gentity_t *victim, gentity_t *attacker ) -{ - if ( !victim || !victim->client || !attacker ) - { +qboolean WP_SaberParry(gentity_t *victim, gentity_t *attacker) { + if (!victim || !victim->client || !attacker) { return qfalse; } - if ( victim->s.number || g_saberAutoBlocking->integer || victim->client->ps.saberBlockingTime > level.time ) - {//either an NPC or a player who is blocking - if ( !PM_SaberInTransitionAny( victim->client->ps.saberMove ) - && !PM_SaberInBounce( victim->client->ps.saberMove ) - && !PM_SaberInKnockaway( victim->client->ps.saberMove ) ) - {//I'm not attacking, in transition or in a bounce or knockaway, so play a parry - WP_SaberBlockNonRandom( victim, saberHitLocation, qfalse ); + if (victim->s.number || g_saberAutoBlocking->integer || victim->client->ps.saberBlockingTime > level.time) { // either an NPC or a player who is blocking + if (!PM_SaberInTransitionAny(victim->client->ps.saberMove) && !PM_SaberInBounce(victim->client->ps.saberMove) && + !PM_SaberInKnockaway(victim->client->ps.saberMove)) { // I'm not attacking, in transition or in a bounce or knockaway, so play a parry + WP_SaberBlockNonRandom(victim, saberHitLocation, qfalse); } victim->client->ps.saberEventFlags |= SEF_PARRIED; - //since it was parried, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( victim->s.number ); + // since it was parried, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(victim->s.number); - //tell the victim to get mad at me - if ( victim->enemy != attacker && victim->client->playerTeam != attacker->client->playerTeam ) - {//they're not mad at me and they're not on my team - G_ClearEnemy( victim ); - G_SetEnemy( victim, attacker ); + // tell the victim to get mad at me + if (victim->enemy != attacker && victim->client->playerTeam != attacker->client->playerTeam) { // they're not mad at me and they're not on my team + G_ClearEnemy(victim); + G_SetEnemy(victim, attacker); } return qtrue; } return qfalse; } -qboolean WP_BrokenParryKnockDown( gentity_t *victim ) -{ - if ( !victim || !victim->client ) - { +qboolean WP_BrokenParryKnockDown(gentity_t *victim) { + if (!victim || !victim->client) { return qfalse; } - if ( victim->client->ps.saberMove == LS_PARRY_UP - || victim->client->ps.saberMove == LS_PARRY_UR - || victim->client->ps.saberMove == LS_PARRY_UL - || victim->client->ps.saberMove == LS_H1_BR - || victim->client->ps.saberMove == LS_H1_B_ - || victim->client->ps.saberMove == LS_H1_BL ) - {//knock their asses down! + if (victim->client->ps.saberMove == LS_PARRY_UP || victim->client->ps.saberMove == LS_PARRY_UR || victim->client->ps.saberMove == LS_PARRY_UL || + victim->client->ps.saberMove == LS_H1_BR || victim->client->ps.saberMove == LS_H1_B_ || + victim->client->ps.saberMove == LS_H1_BL) { // knock their asses down! int knockAnim = BOTH_KNOCKDOWN1; - if ( PM_CrouchAnim( victim->client->ps.legsAnim ) ) - { + if (PM_CrouchAnim(victim->client->ps.legsAnim)) { knockAnim = BOTH_KNOCKDOWN4; } - NPC_SetAnim( victim, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_AddEvent( victim, EV_PAIN, victim->health ); + NPC_SetAnim(victim, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(victim, EV_PAIN, victim->health); return qtrue; } return qfalse; @@ -2514,163 +2065,126 @@ void WP_SaberDamageTrace( gentity_t *ent ) --------------------------------------------------------- */ #define MAX_SABER_SWING_INC 0.33f -void WP_SaberDamageTrace( gentity_t *ent ) -{ - vec3_t mp1, mp2, md1, md2, baseOld, baseNew, baseDiff, endOld, endNew, bladePointOld, bladePointNew; - float tipDmgMod = 1.0f; - float baseDamage; - int baseDFlags = 0; - qboolean hit_wall = qfalse; - qboolean brokenParry = qfalse; - - for ( int ven = 0; ven < MAX_SABER_VICTIMS; ven++ ) - { +void WP_SaberDamageTrace(gentity_t *ent) { + vec3_t mp1, mp2, md1, md2, baseOld, baseNew, baseDiff, endOld, endNew, bladePointOld, bladePointNew; + float tipDmgMod = 1.0f; + float baseDamage; + int baseDFlags = 0; + qboolean hit_wall = qfalse; + qboolean brokenParry = qfalse; + + for (int ven = 0; ven < MAX_SABER_VICTIMS; ven++) { victimEntityNum[ven] = ENTITYNUM_NONE; } - memset( totalDmg, 0, sizeof( totalDmg) ); - memset( dmgDir, 0, sizeof( dmgDir ) ); - memset( dmgSpot, 0, sizeof( dmgSpot ) ); - memset( dmgFraction, 0, sizeof( dmgFraction ) ); - memset( hitLoc, HL_NONE, sizeof( hitLoc ) ); - memset( hitDismemberLoc, HL_NONE, sizeof( hitDismemberLoc ) ); - memset( hitDismember, qfalse, sizeof( hitDismember ) ); + memset(totalDmg, 0, sizeof(totalDmg)); + memset(dmgDir, 0, sizeof(dmgDir)); + memset(dmgSpot, 0, sizeof(dmgSpot)); + memset(dmgFraction, 0, sizeof(dmgFraction)); + memset(hitLoc, HL_NONE, sizeof(hitLoc)); + memset(hitDismemberLoc, HL_NONE, sizeof(hitDismemberLoc)); + memset(hitDismember, qfalse, sizeof(hitDismember)); numVictims = 0; VectorClear(saberHitLocation); VectorClear(saberHitNormal); - saberHitFraction = 1.0; // Closest saber hit. The saber can do no damage past this point. + saberHitFraction = 1.0; // Closest saber hit. The saber can do no damage past this point. saberHitEntity = ENTITYNUM_NONE; sabersCrossed = -1; - if ( !ent->client ) - { + if (!ent->client) { return; } - if ( !ent->s.number ) - {//player never uses these + if (!ent->s.number) { // player never uses these ent->client->ps.saberEventFlags &= ~SEF_EVENTS; } - if ( ent->client->ps.saberLength <= 1 )//cen get down to 1 when in a wall - {//saber is not on + if (ent->client->ps.saberLength <= 1) // cen get down to 1 when in a wall + { // saber is not on return; } - if ( VectorCompare( ent->client->renderInfo.muzzlePointOld, vec3_origin ) || VectorCompare( ent->client->renderInfo.muzzleDirOld, vec3_origin ) ) - { - //just started up the saber? + if (VectorCompare(ent->client->renderInfo.muzzlePointOld, vec3_origin) || VectorCompare(ent->client->renderInfo.muzzleDirOld, vec3_origin)) { + // just started up the saber? return; } - int saberContents = gi.pointcontents( ent->client->renderInfo.muzzlePoint, ent->client->ps.saberEntityNum ); - if ( (saberContents&CONTENTS_WATER)|| - (saberContents&CONTENTS_SLIME)|| - (saberContents&CONTENTS_LAVA) ) - {//um... turn off? Or just set length to 1? - //FIXME: short-out effect/sound? + int saberContents = gi.pointcontents(ent->client->renderInfo.muzzlePoint, ent->client->ps.saberEntityNum); + if ((saberContents & CONTENTS_WATER) || (saberContents & CONTENTS_SLIME) || (saberContents & CONTENTS_LAVA)) { // um... turn off? Or just set length to 1? + // FIXME: short-out effect/sound? ent->client->ps.saberActive = qfalse; return; - } - else if ( saberContents&CONTENTS_OUTSIDE ) - { - if ( (level.worldFlags&WF_RAINING) ) - { - //add steam in rain - if ( Q_flrand( 0, 500 ) < ent->client->ps.saberLength ) - { - vec3_t end, normal = {0,0,1};//FIXME: opposite of rain angles? - VectorMA( ent->client->renderInfo.muzzlePoint, ent->client->ps.saberLength*Q_flrand(0, 1), ent->client->renderInfo.muzzleDir, end ); - G_PlayEffect( "saber/fizz", end, normal ); + } else if (saberContents & CONTENTS_OUTSIDE) { + if ((level.worldFlags & WF_RAINING)) { + // add steam in rain + if (Q_flrand(0, 500) < ent->client->ps.saberLength) { + vec3_t end, normal = {0, 0, 1}; // FIXME: opposite of rain angles? + VectorMA(ent->client->renderInfo.muzzlePoint, ent->client->ps.saberLength * Q_flrand(0, 1), ent->client->renderInfo.muzzleDir, end); + G_PlayEffect("saber/fizz", end, normal); } } } - //FIXMEFIXMEFIXME: When in force speed (esp. lvl 3), need to interpolate this because + // FIXMEFIXMEFIXME: When in force speed (esp. lvl 3), need to interpolate this because // we animate so much faster that the arc is pretty much flat... int entPowerLevel; - if ( !ent->s.number && (ent->client->ps.forcePowersActive&(1<s.number && (ent->client->ps.forcePowersActive & (1 << FP_SPEED))) { entPowerLevel = FORCE_LEVEL_3; - } - else - { - entPowerLevel = PM_PowerLevelForSaberAnim( &ent->client->ps ); + } else { + entPowerLevel = PM_PowerLevelForSaberAnim(&ent->client->ps); } - if ( ent->client->ps.saberInFlight ) - {//flying sabers are much more deadly - //unless you're dead - if ( ent->health <= 0 && !g_saberRealisticCombat->integer ) - {//so enemies don't keep trying to block it - //FIXME: still do damage, just not to humanoid clients who should try to avoid it - //baseDamage = 0.0f; + if (ent->client->ps.saberInFlight) { // flying sabers are much more deadly + // unless you're dead + if (ent->health <= 0 && !g_saberRealisticCombat->integer) { // so enemies don't keep trying to block it + // FIXME: still do damage, just not to humanoid clients who should try to avoid it + // baseDamage = 0.0f; return; } - //or unless returning - else if ( ent->client->ps.saberEntityState == SES_RETURNING ) - {//special case, since we're returning, chances are if we hit something - //it's going to be butt-first. So do less damage. + // or unless returning + else if (ent->client->ps.saberEntityState == SES_RETURNING) { // special case, since we're returning, chances are if we hit something + // it's going to be butt-first. So do less damage. baseDamage = 0.1f; - } - else - { - if ( !ent->s.number ) - {//cheat for player + } else { + if (!ent->s.number) { // cheat for player baseDamage = 10.0f; - } - else - { + } else { baseDamage = 2.5f; } } - //Use old to current since can't predict it - VectorCopy( ent->client->renderInfo.muzzlePointOld, mp1 ); - VectorCopy( ent->client->renderInfo.muzzleDirOld, md1 ); - VectorCopy( ent->client->renderInfo.muzzlePoint, mp2 ); - VectorCopy( ent->client->renderInfo.muzzleDir, md2 ); - } - else - { - if ( ent->client->ps.saberMove == LS_READY ) - {//just do effects - if ( g_saberRealisticCombat->integer < 2 ) - {//don't kill with this hit + // Use old to current since can't predict it + VectorCopy(ent->client->renderInfo.muzzlePointOld, mp1); + VectorCopy(ent->client->renderInfo.muzzleDirOld, md1); + VectorCopy(ent->client->renderInfo.muzzlePoint, mp2); + VectorCopy(ent->client->renderInfo.muzzleDir, md2); + } else { + if (ent->client->ps.saberMove == LS_READY) { // just do effects + if (g_saberRealisticCombat->integer < 2) { // don't kill with this hit baseDFlags = DAMAGE_NO_KILL; } baseDamage = 0; - } - else if ( ent->client->ps.saberLockTime > level.time ) - {//just do effects + } else if (ent->client->ps.saberLockTime > level.time) { // just do effects baseDamage = 0; - } - else if ( ent->client->ps.saberBlocked > BLOCKED_NONE - || ( !PM_SaberInAttack( ent->client->ps.saberMove ) - && !PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - && !PM_SaberInTransitionAny( ent->client->ps.saberMove ) - ) - ) - {//don't do damage if parrying/reflecting/bouncing/deflecting or not actually attacking or in a transition to/from/between attacks + } else if (ent->client->ps.saberBlocked > BLOCKED_NONE || + (!PM_SaberInAttack(ent->client->ps.saberMove) && !PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) && + !PM_SaberInTransitionAny(ent->client->ps.saberMove))) { // don't do damage if parrying/reflecting/bouncing/deflecting or not actually + // attacking or in a transition to/from/between attacks baseDamage = 0; - } - else - {//okay, in a saberMove that does damage - //make sure we're in the right anim - if ( !PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - && !PM_InAnimForSaberMove( ent->client->ps.torsoAnim, ent->client->ps.saberMove ) ) - {//forced into some other animation somehow, like a pain or death? + } else { // okay, in a saberMove that does damage + // make sure we're in the right anim + if (!PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) && + !PM_InAnimForSaberMove(ent->client->ps.torsoAnim, + ent->client->ps.saberMove)) { // forced into some other animation somehow, like a pain or death? baseDamage = 0; - } - else if ( ent->client->ps.weaponstate == WEAPON_FIRING && ent->client->ps.saberBlocked == BLOCKED_NONE && - ( PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) || PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || entPowerLevel > FORCE_LEVEL_2 ) ) - {//normal attack swing swinging/spinning (or if using strong set), do normal damage - //FIXME: more damage for higher attack power levels? + } else if (ent->client->ps.weaponstate == WEAPON_FIRING && ent->client->ps.saberBlocked == BLOCKED_NONE && + (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || + entPowerLevel > FORCE_LEVEL_2)) { // normal attack swing swinging/spinning (or if using strong set), do normal damage + // FIXME: more damage for higher attack power levels? // More damage based on length/color of saber? - //FIXME: Desann does double damage? - if ( g_saberRealisticCombat->integer ) - { - switch ( entPowerLevel ) - { + // FIXME: Desann does double damage? + if (g_saberRealisticCombat->integer) { + switch (entPowerLevel) { case FORCE_LEVEL_3: baseDamage = 10.0f; break; @@ -2682,21 +2196,14 @@ void WP_SaberDamageTrace( gentity_t *ent ) baseDamage = 2.5f; break; } - } - else - { + } else { baseDamage = 2.5f * (float)entPowerLevel; } - } - else - {//saber is transitioning, defending or idle, don't do as much damage - //FIXME: strong attacks and returns should do damage and be unblockable - if ( g_timescale->value < 1.0 ) - {//in slow mo or force speed, we need to do damage during the transitions - if ( g_saberRealisticCombat->integer ) - { - switch ( entPowerLevel ) - { + } else { // saber is transitioning, defending or idle, don't do as much damage + // FIXME: strong attacks and returns should do damage and be unblockable + if (g_timescale->value < 1.0) { // in slow mo or force speed, we need to do damage during the transitions + if (g_saberRealisticCombat->integer) { + switch (entPowerLevel) { case FORCE_LEVEL_3: baseDamage = 10.0f; break; @@ -2708,14 +2215,11 @@ void WP_SaberDamageTrace( gentity_t *ent ) baseDamage = 2.5f; break; } - } - else - { + } else { baseDamage = 2.5f * (float)entPowerLevel; } - } - else// if ( !ent->s.number ) - {//I have to do *some* damage in transitions or else you feel like a total gimp + } else // if ( !ent->s.number ) + { // I have to do *some* damage in transitions or else you feel like a total gimp baseDamage = 0.1f; } /* @@ -2727,52 +2231,47 @@ void WP_SaberDamageTrace( gentity_t *ent ) } } - //Use current to next since can predict it - //FIXME: if they're closer than the saber blade start, we don't want the + // Use current to next since can predict it + // FIXME: if they're closer than the saber blade start, we don't want the // arm to pass through them without any damage... so check the radius // and push them away (do pain & knockback) - //FIXME: if going into/coming from a parry/reflection or going into a deflection, don't use old mp & dir? Otherwise, deflections will cut through? - //VectorCopy( ent->client->renderInfo.muzzlePoint, mp1 ); - //VectorCopy( ent->client->renderInfo.muzzleDir, md1 ); - //VectorCopy( ent->client->renderInfo.muzzlePointNext, mp2 ); - //VectorCopy( ent->client->renderInfo.muzzleDirNext, md2 ); - //prediction was causing gaps in swing (G2 problem) so *don't* predict - VectorCopy( ent->client->renderInfo.muzzlePointOld, mp1 ); - VectorCopy( ent->client->renderInfo.muzzleDirOld, md1 ); - VectorCopy( ent->client->renderInfo.muzzlePoint, mp2 ); - VectorCopy( ent->client->renderInfo.muzzleDir, md2 ); - - //NOTE: this is a test, may not be necc, as I can still swing right through someone without hitting them, somehow... - //see if anyone is so close that they're within the dist from my origin to the start of the saber - if ( ent->health > 0 && !ent->client->ps.saberLockTime ) - { + // FIXME: if going into/coming from a parry/reflection or going into a deflection, don't use old mp & dir? Otherwise, deflections will cut through? + // VectorCopy( ent->client->renderInfo.muzzlePoint, mp1 ); + // VectorCopy( ent->client->renderInfo.muzzleDir, md1 ); + // VectorCopy( ent->client->renderInfo.muzzlePointNext, mp2 ); + // VectorCopy( ent->client->renderInfo.muzzleDirNext, md2 ); + // prediction was causing gaps in swing (G2 problem) so *don't* predict + VectorCopy(ent->client->renderInfo.muzzlePointOld, mp1); + VectorCopy(ent->client->renderInfo.muzzleDirOld, md1); + VectorCopy(ent->client->renderInfo.muzzlePoint, mp2); + VectorCopy(ent->client->renderInfo.muzzleDir, md2); + + // NOTE: this is a test, may not be necc, as I can still swing right through someone without hitting them, somehow... + // see if anyone is so close that they're within the dist from my origin to the start of the saber + if (ent->health > 0 && !ent->client->ps.saberLockTime) { trace_t trace; - gi.trace( &trace, ent->currentOrigin, vec3_origin, vec3_origin, mp1, ent->s.number, (MASK_SHOT&~(CONTENTS_CORPSE|CONTENTS_ITEM)), G2_NOCOLLIDE, 0 ); - if ( trace.entityNum < ENTITYNUM_WORLD && (trace.entityNum > 0||ent->client->NPC_class == CLASS_DESANN) )//NPCs don't push player away, unless it's Desann - {//a valid ent + gi.trace(&trace, ent->currentOrigin, vec3_origin, vec3_origin, mp1, ent->s.number, (MASK_SHOT & ~(CONTENTS_CORPSE | CONTENTS_ITEM)), G2_NOCOLLIDE, + 0); + if (trace.entityNum < ENTITYNUM_WORLD && + (trace.entityNum > 0 || ent->client->NPC_class == CLASS_DESANN)) // NPCs don't push player away, unless it's Desann + { // a valid ent gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt - && traceEnt->client - && traceEnt->health > 0 - && traceEnt->client->playerTeam != ent->client->playerTeam - && !PM_InKnockDown( &traceEnt->client->ps ) ) - {//enemy client, push them away - if ( !traceEnt->client->ps.saberLockTime && !traceEnt->message ) - {//don't push people in saberlock or with security keys + if (traceEnt && traceEnt->client && traceEnt->health > 0 && traceEnt->client->playerTeam != ent->client->playerTeam && + !PM_InKnockDown(&traceEnt->client->ps)) { // enemy client, push them away + if (!traceEnt->client->ps.saberLockTime && !traceEnt->message) { // don't push people in saberlock or with security keys vec3_t hitDir; - VectorSubtract( trace.endpos, ent->currentOrigin, hitDir ); - float totalDist = Distance( mp1, ent->currentOrigin ); - float knockback = (totalDist-VectorNormalize( hitDir ))/totalDist * 200.0f; + VectorSubtract(trace.endpos, ent->currentOrigin, hitDir); + float totalDist = Distance(mp1, ent->currentOrigin); + float knockback = (totalDist - VectorNormalize(hitDir)) / totalDist * 200.0f; hitDir[2] = 0; - //FIXME: do we need to call G_Throw? Seems unfair to put actual knockback on them, stops the attack - //G_Throw( traceEnt, hitDir, knockback ); - VectorMA( traceEnt->client->ps.velocity, knockback, hitDir, traceEnt->client->ps.velocity ); + // FIXME: do we need to call G_Throw? Seems unfair to put actual knockback on them, stops the attack + // G_Throw( traceEnt, hitDir, knockback ); + VectorMA(traceEnt->client->ps.velocity, knockback, hitDir, traceEnt->client->ps.velocity); traceEnt->client->ps.pm_time = 200; traceEnt->client->ps.pm_flags |= PMF_TIME_NOFRICTION; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( "%s pushing away %s at %s\n", ent->NPC_type, traceEnt->NPC_type, vtos( traceEnt->client->ps.velocity ) ); + if (d_saberCombat->integer) { + gi.Printf("%s pushing away %s at %s\n", ent->NPC_type, traceEnt->NPC_type, vtos(traceEnt->client->ps.velocity)); } #endif } @@ -2781,184 +2280,148 @@ void WP_SaberDamageTrace( gentity_t *ent ) } } - if ( g_saberRealisticCombat->integer > 1 ) - {//always do damage, and lots of it - if ( g_saberRealisticCombat->integer > 2 ) - {//always do damage, and lots of it + if (g_saberRealisticCombat->integer > 1) { // always do damage, and lots of it + if (g_saberRealisticCombat->integer > 2) { // always do damage, and lots of it baseDamage = 25.0f; - } - else if ( baseDamage > 0.1f ) - {//only do super damage if we would have done damage according to normal rules + } else if (baseDamage > 0.1f) { // only do super damage if we would have done damage according to normal rules baseDamage = 25.0f; } - } - else if ( (!ent->s.number&&ent->client->ps.forcePowersActive&(1<value); + } else if ((!ent->s.number && ent->client->ps.forcePowersActive & (1 << FP_SPEED))) { + baseDamage *= (1.0f - g_timescale->value); } // Get the old state of the blade - VectorCopy( mp1, baseOld ); - VectorMA( baseOld, ent->client->ps.saberLength, md1, endOld ); + VectorCopy(mp1, baseOld); + VectorMA(baseOld, ent->client->ps.saberLength, md1, endOld); // Get the future state of the blade - VectorCopy( mp2, baseNew ); - VectorMA( baseNew, ent->client->ps.saberLength, md2, endNew ); + VectorCopy(mp2, baseNew); + VectorMA(baseNew, ent->client->ps.saberLength, md2, endNew); sabersCrossed = -1; - if ( VectorCompare2( baseOld, baseNew ) && VectorCompare2( endOld, endNew ) ) - { - hit_wall = WP_SaberDamageForTrace( ent->s.number, mp2, endNew, baseDamage*4, md2, qfalse, entPowerLevel, qfalse ); - } - else - { + if (VectorCompare2(baseOld, baseNew) && VectorCompare2(endOld, endNew)) { + hit_wall = WP_SaberDamageForTrace(ent->s.number, mp2, endNew, baseDamage * 4, md2, qfalse, entPowerLevel, qfalse); + } else { float aveLength, step = 8, stepsize = 8; - vec3_t ma1, ma2, md2ang, curBase1, curBase2; - int xx; - //do the trace at the base first - hit_wall = WP_SaberDamageForTrace( ent->s.number, baseOld, baseNew, baseDamage, md2, qfalse, entPowerLevel ); - - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0 ) - { - //adjust muzzleDir... + vec3_t ma1, ma2, md2ang, curBase1, curBase2; + int xx; + // do the trace at the base first + hit_wall = WP_SaberDamageForTrace(ent->s.number, baseOld, baseNew, baseDamage, md2, qfalse, entPowerLevel); + + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0) { + // adjust muzzleDir... vec3_t ma1, ma2; - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], saberHitFraction ); + vectoangles(md1, ma1); + vectoangles(md2, ma2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], saberHitFraction); } - AngleVectors( md2ang, md2, NULL, NULL ); - //shorten the base pos - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, ent->client->ps.saberLength, md2, endNew ); + AngleVectors(md2ang, md2, NULL, NULL); + // shorten the base pos + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, ent->client->ps.saberLength, md2, endNew); } - //If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc + // If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc float dirInc, curDirFrac; - if ( PM_SaberInAttack( ent->client->ps.saberMove ) - || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) - || PM_SpinningSaberAnim( ent->client->ps.torsoAnim ) - || PM_InSpecialJump( ent->client->ps.torsoAnim ) - || (g_timescale->value<1.0f&&PM_SaberInTransitionAny( ent->client->ps.saberMove )) ) - { - curDirFrac = DotProduct( md1, md2 ); - } - else - { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + PM_SpinningSaberAnim(ent->client->ps.torsoAnim) || PM_InSpecialJump(ent->client->ps.torsoAnim) || + (g_timescale->value < 1.0f && PM_SaberInTransitionAny(ent->client->ps.saberMove))) { + curDirFrac = DotProduct(md1, md2); + } else { curDirFrac = 1.0f; } - //NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! - if ( fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC ) - {//the saber blade spun more than 33 degrees since the last damage trace - curDirFrac = dirInc = 1.0f/((1.0f - curDirFrac)/MAX_SABER_SWING_INC); - } - else - { + // NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! + if (fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC) { // the saber blade spun more than 33 degrees since the last damage trace + curDirFrac = dirInc = 1.0f / ((1.0f - curDirFrac) / MAX_SABER_SWING_INC); + } else { curDirFrac = 1.0f; dirInc = 0.0f; } qboolean hit_saber = qfalse; - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); - - vec3_t curMD1, curMD2;//, mdDiff, dirDiff; - //VectorSubtract( md2, md1, mdDiff ); - VectorCopy( md1, curMD2 ); - VectorCopy( baseOld, curBase2 ); - - while ( 1 ) - { - VectorCopy( curMD2, curMD1 ); - VectorCopy( curBase2, curBase1 ); - if ( curDirFrac >= 1.0f ) - { - VectorCopy( md2, curMD2 ); - VectorCopy( baseNew, curBase2 ); - } - else - { - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], curDirFrac ); - } - AngleVectors( md2ang, curMD2, NULL, NULL ); - //VectorMA( md1, curDirFrac, mdDiff, curMD2 ); - VectorSubtract( baseNew, baseOld, baseDiff ); - VectorMA( baseOld, curDirFrac, baseDiff, curBase2 ); + vectoangles(md1, ma1); + vectoangles(md2, ma2); + + vec3_t curMD1, curMD2; //, mdDiff, dirDiff; + // VectorSubtract( md2, md1, mdDiff ); + VectorCopy(md1, curMD2); + VectorCopy(baseOld, curBase2); + + while (1) { + VectorCopy(curMD2, curMD1); + VectorCopy(curBase2, curBase1); + if (curDirFrac >= 1.0f) { + VectorCopy(md2, curMD2); + VectorCopy(baseNew, curBase2); + } else { + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], curDirFrac); + } + AngleVectors(md2ang, curMD2, NULL, NULL); + // VectorMA( md1, curDirFrac, mdDiff, curMD2 ); + VectorSubtract(baseNew, baseOld, baseDiff); + VectorMA(baseOld, curDirFrac, baseDiff, curBase2); } // Move up the blade in intervals of stepsize - for ( step = stepsize; step < ent->client->ps.saberLength && step < ent->client->ps.saberLengthOld; step+=12 ) - { - VectorMA( curBase1, step, curMD1, bladePointOld ); - VectorMA( curBase2, step, curMD2, bladePointNew ); - if ( WP_SaberDamageForTrace( ent->s.number, bladePointOld, bladePointNew, baseDamage, curMD2, qfalse, entPowerLevel ) ) - { + for (step = stepsize; step < ent->client->ps.saberLength && step < ent->client->ps.saberLengthOld; step += 12) { + VectorMA(curBase1, step, curMD1, bladePointOld); + VectorMA(curBase2, step, curMD2, bladePointNew); + if (WP_SaberDamageForTrace(ent->s.number, bladePointOld, bladePointNew, baseDamage, curMD2, qfalse, entPowerLevel)) { hit_wall = qtrue; } - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0 ) - { - //adjust muzzle endpoint - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, ent->client->ps.saberLength, curMD2, endNew ); - //adjust muzzleDir... + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0) { + // adjust muzzle endpoint + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, ent->client->ps.saberLength, curMD2, endNew); + // adjust muzzleDir... vec3_t curMA1, curMA2; - vectoangles( curMD1, curMA1 ); - vectoangles( curMD2, curMA2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( curMA1[xx], curMA2[xx], saberHitFraction ); + vectoangles(curMD1, curMA1); + vectoangles(curMD2, curMA2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(curMA1[xx], curMA2[xx], saberHitFraction); } - AngleVectors( md2ang, curMD2, NULL, NULL ); + AngleVectors(md2ang, curMD2, NULL, NULL); /* VectorSubtract( curMD2, curMD1, dirDiff ); VectorMA( curMD1, saberHitFraction, dirDiff, curMD2 ); */ hit_saber = qtrue; } - if (hit_wall) - { + if (hit_wall) { break; } } - if ( hit_wall || hit_saber ) - { + if (hit_wall || hit_saber) { break; } - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { break; - } - else - { + } else { curDirFrac += dirInc; - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { curDirFrac = 1.0f; } } } - //do the trace at the end last - //Special check- adjust for length of blade not being a multiple of 12 - aveLength = (ent->client->ps.saberLengthOld + ent->client->ps.saberLength)/2; - if ( step > aveLength ) - {//less dmg if the last interval was not stepsize - tipDmgMod = (stepsize-(step-aveLength))/stepsize; + // do the trace at the end last + // Special check- adjust for length of blade not being a multiple of 12 + aveLength = (ent->client->ps.saberLengthOld + ent->client->ps.saberLength) / 2; + if (step > aveLength) { // less dmg if the last interval was not stepsize + tipDmgMod = (stepsize - (step - aveLength)) / stepsize; } - //NOTE: since this is the tip, we do not extrapolate the extra 16 - if ( WP_SaberDamageForTrace( ent->s.number, endOld, endNew, tipDmgMod*baseDamage, md2, qfalse, entPowerLevel, qfalse ) ) - { + // NOTE: since this is the tip, we do not extrapolate the extra 16 + if (WP_SaberDamageForTrace(ent->s.number, endOld, endNew, tipDmgMod * baseDamage, md2, qfalse, entPowerLevel, qfalse)) { hit_wall = qtrue; } } - if ( (saberHitFraction < 1.0f||(sabersCrossed>=0&&sabersCrossed<=32.0f)) && (ent->client->ps.weaponstate == WEAPON_FIRING || ent->client->ps.saberInFlight) ) - {// The saber (in-hand) hit another saber, mano. + if ((saberHitFraction < 1.0f || (sabersCrossed >= 0 && sabersCrossed <= 32.0f)) && + (ent->client->ps.weaponstate == WEAPON_FIRING || ent->client->ps.saberInFlight)) { // The saber (in-hand) hit another saber, mano. qboolean inFlightSaberBlocked = qfalse; qboolean collisionResolved = qfalse; qboolean deflected = qfalse; @@ -2967,248 +2430,209 @@ void WP_SaberDamageTrace( gentity_t *ent ) gentity_t *hitOwner = NULL; int hitOwnerPowerLevel = FORCE_LEVEL_0; - if ( hitEnt ) - { + if (hitEnt) { hitOwner = hitEnt->owner; } - if ( hitOwner && hitOwner->client ) - { - hitOwnerPowerLevel = PM_PowerLevelForSaberAnim( &hitOwner->client->ps ); - if ( entPowerLevel == FORCE_LEVEL_3 && PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) ) - {//a special "unblockable" attack - if ( hitOwner->client->NPC_class == CLASS_DESANN - || hitOwner->client->NPC_class == CLASS_TAVION - || hitOwner->client->NPC_class == CLASS_LUKE ) - {//these masters can even block unblockables (stops cheap kills) + if (hitOwner && hitOwner->client) { + hitOwnerPowerLevel = PM_PowerLevelForSaberAnim(&hitOwner->client->ps); + if (entPowerLevel == FORCE_LEVEL_3 && PM_SaberInSpecialAttack(ent->client->ps.torsoAnim)) { // a special "unblockable" attack + if (hitOwner->client->NPC_class == CLASS_DESANN || hitOwner->client->NPC_class == CLASS_TAVION || + hitOwner->client->NPC_class == CLASS_LUKE) { // these masters can even block unblockables (stops cheap kills) entPowerLevel = FORCE_LEVEL_2; } } } - //FIXME: check for certain anims, facing, etc, to make them lock into a sabers-locked pose - //SEF_LOCKED + // FIXME: check for certain anims, facing, etc, to make them lock into a sabers-locked pose + // SEF_LOCKED - if ( ent->client->ps.saberInFlight && - ent->client->ps.saberActive && - ent->client->ps.saberEntityNum != ENTITYNUM_NONE && - ent->client->ps.saberEntityState != SES_RETURNING ) - {//saber was blocked, return it + if (ent->client->ps.saberInFlight && ent->client->ps.saberActive && ent->client->ps.saberEntityNum != ENTITYNUM_NONE && + ent->client->ps.saberEntityState != SES_RETURNING) { // saber was blocked, return it inFlightSaberBlocked = qtrue; } - //FIXME: based on strength, position and angle of attack & defense, decide if: + // FIXME: based on strength, position and angle of attack & defense, decide if: // defender and attacker lock sabers // *defender's parry should hold and attack bounces (or deflects, based on angle of sabers) // *defender's parry is somewhat broken and both bounce (or deflect) // *defender's parry is broken and they bounce while attacker's attack deflects or carries through (especially if they're dead) // defender is knocked down and attack goes through - //Check deflections and broken parries - if ( hitOwner && hitOwner->health > 0 && ent->health > 0 //both are alive - && !inFlightSaberBlocked && hitOwner->client && !hitOwner->client->ps.saberInFlight && !ent->client->ps.saberInFlight//both have sabers in-hand - && ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN - && ent->client->ps.saberLockTime < level.time - && hitOwner->client->ps.saberLockTime < level.time ) - {//2 in-hand sabers hit - //FIXME: defender should not parry or block at all if not in a saber anim... like, if in a roll or knockdown... - if ( baseDamage ) - {//there is damage involved, not just effects + // Check deflections and broken parries + if (hitOwner && hitOwner->health > 0 && ent->health > 0 // both are alive + && !inFlightSaberBlocked && hitOwner->client && !hitOwner->client->ps.saberInFlight && !ent->client->ps.saberInFlight // both have sabers in-hand + && ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN && ent->client->ps.saberLockTime < level.time && + hitOwner->client->ps.saberLockTime < level.time) { // 2 in-hand sabers hit + // FIXME: defender should not parry or block at all if not in a saber anim... like, if in a roll or knockdown... + if (baseDamage) { // there is damage involved, not just effects qboolean entAttacking = qfalse; qboolean hitOwnerAttacking = qfalse; qboolean entDefending = qfalse; qboolean hitOwnerDefending = qfalse; - if ( PM_SaberInAttack( ent->client->ps.saberMove ) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) ) - { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim)) { entAttacking = qtrue; - } - else if ( entPowerLevel > FORCE_LEVEL_2 ) - { - if ( PM_SaberInAttack( ent->client->ps.saberMove ) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) || PM_SaberInTransitionAny( ent->client->ps.saberMove ) ) - { + } else if (entPowerLevel > FORCE_LEVEL_2) { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + PM_SaberInTransitionAny(ent->client->ps.saberMove)) { entAttacking = qtrue; } } - if ( PM_SaberInParry( ent->client->ps.saberMove ) - || ent->client->ps.saberMove == LS_READY ) - { + if (PM_SaberInParry(ent->client->ps.saberMove) || ent->client->ps.saberMove == LS_READY) { entDefending = qtrue; } - if ( PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) ) - { + if (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim)) { hitOwnerAttacking = qtrue; - } - else if ( hitOwnerPowerLevel > FORCE_LEVEL_2 ) - { - if ( PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) || PM_SaberInTransitionAny( hitOwner->client->ps.saberMove ) ) - { + } else if (hitOwnerPowerLevel > FORCE_LEVEL_2) { + if (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim) || + PM_SaberInTransitionAny(hitOwner->client->ps.saberMove)) { hitOwnerAttacking = qtrue; } } - if ( PM_SaberInParry( hitOwner->client->ps.saberMove ) - || hitOwner->client->ps.saberMove == LS_READY ) - { + if (PM_SaberInParry(hitOwner->client->ps.saberMove) || hitOwner->client->ps.saberMove == LS_READY) { hitOwnerDefending = qtrue; } - if ( entAttacking - && hitOwnerAttacking - && ( entPowerLevel == hitOwnerPowerLevel - || (entPowerLevel > FORCE_LEVEL_2 && hitOwnerPowerLevel > FORCE_LEVEL_2 ) - || (entPowerLevel < FORCE_LEVEL_3 && hitOwnerPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && Q_irand( 0, 2 )) - || (entPowerLevel < FORCE_LEVEL_2 && hitOwnerPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && Q_irand( 0, 1 )) - || (hitOwnerPowerLevel < FORCE_LEVEL_3 && entPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && !Q_irand( 0, 1 )) - || (hitOwnerPowerLevel < FORCE_LEVEL_2 && entPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && !Q_irand( 0, 1 ))) - && WP_SabersCheckLock( ent, hitOwner ) ) - { + if (entAttacking && hitOwnerAttacking && + (entPowerLevel == hitOwnerPowerLevel || (entPowerLevel > FORCE_LEVEL_2 && hitOwnerPowerLevel > FORCE_LEVEL_2) || + (entPowerLevel < FORCE_LEVEL_3 && hitOwnerPowerLevel < FORCE_LEVEL_3 && + hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && Q_irand(0, 2)) || + (entPowerLevel < FORCE_LEVEL_2 && hitOwnerPowerLevel < FORCE_LEVEL_3 && + hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && Q_irand(0, 1)) || + (hitOwnerPowerLevel < FORCE_LEVEL_3 && entPowerLevel < FORCE_LEVEL_3 && + ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_2 && !Q_irand(0, 1)) || + (hitOwnerPowerLevel < FORCE_LEVEL_2 && entPowerLevel < FORCE_LEVEL_3 && + ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] > FORCE_LEVEL_1 && !Q_irand(0, 1))) && + WP_SabersCheckLock(ent, hitOwner)) { collisionResolved = qtrue; - } - else if ( hitOwnerAttacking - && entDefending - && !Q_irand( 0, 2 ) - && (ent->client->ps.saberMove != LS_READY || (hitOwnerPowerLevel-ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand( -6, 0 ) ) - && ((hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 )|| - (hitOwnerPowerLevel < FORCE_LEVEL_2 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 )|| - (hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && !Q_irand( 0, (hitOwnerPowerLevel-ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]+1)*2 ))) - && WP_SabersCheckLock( hitOwner, ent ) ) - { + } else if (hitOwnerAttacking && entDefending && !Q_irand(0, 2) && + (ent->client->ps.saberMove != LS_READY || + (hitOwnerPowerLevel - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand(-6, 0)) && + ((hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2) || + (hitOwnerPowerLevel < FORCE_LEVEL_2 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1) || + (hitOwnerPowerLevel < FORCE_LEVEL_3 && ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && + !Q_irand(0, (hitOwnerPowerLevel - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] + 1) * 2))) && + WP_SabersCheckLock(hitOwner, ent)) { collisionResolved = qtrue; - } - else if ( entAttacking && hitOwnerDefending ) - {//I'm attacking hit, they're parrying - qboolean activeDefense = (qboolean)( - hitOwner->s.number || - g_saberAutoBlocking->integer || - hitOwner->client->ps.saberBlockingTime > level.time); - - if ( !Q_irand( 0, 2 ) - && activeDefense - && (hitOwner->client->ps.saberMove != LS_READY || (entPowerLevel-hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand( -6, 0 ) ) - && ( ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 ) - || ( entPowerLevel < FORCE_LEVEL_2 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 ) - || ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && !Q_irand( 0, (entPowerLevel-hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]+1)*2 )) ) - && WP_SabersCheckLock( ent, hitOwner ) ) - { + } else if (entAttacking && hitOwnerDefending) { // I'm attacking hit, they're parrying + qboolean activeDefense = + (qboolean)(hitOwner->s.number || g_saberAutoBlocking->integer || hitOwner->client->ps.saberBlockingTime > level.time); + + if (!Q_irand(0, 2) && activeDefense && + (hitOwner->client->ps.saberMove != LS_READY || + (entPowerLevel - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]) < Q_irand(-6, 0)) && + ((entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2) || + (entPowerLevel < FORCE_LEVEL_2 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1) || + (entPowerLevel < FORCE_LEVEL_3 && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_0 && + !Q_irand(0, (entPowerLevel - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] + 1) * 2))) && + WP_SabersCheckLock(ent, hitOwner)) { collisionResolved = qtrue; - } - else if ( saberHitFraction < 1.0f ) - {//an actual collision - if ( entPowerLevel < FORCE_LEVEL_3 && activeDefense ) - {//strong attacks cannot be deflected - //based on angle of attack & angle of defensive saber, see if I should deflect off in another dir rather than bounce back - deflected = WP_GetSaberDeflectionAngle( ent, hitOwner ); - //just so Jedi knows that he was blocked + } else if (saberHitFraction < 1.0f) { // an actual collision + if (entPowerLevel < FORCE_LEVEL_3 && activeDefense) { // strong attacks cannot be deflected + // based on angle of attack & angle of defensive saber, see if I should deflect off in another dir rather than bounce back + deflected = WP_GetSaberDeflectionAngle(ent, hitOwner); + // just so Jedi knows that he was blocked ent->client->ps.saberEventFlags |= SEF_BLOCKED; } - //base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE - if ( entPowerLevel < FORCE_LEVEL_3 - //&& ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_3//if you have high saber offense, you cannot have your attack knocked away, regardless of what style you're using? - && hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 - && activeDefense - && (hitOwnerPowerLevel > FORCE_LEVEL_2||(hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_2&&Q_irand(0,hitOwner->client->ps.saberAnimLevel))) ) - {//knockaways can make fast-attacker go into a broken parry anim if the ent is using fast or med (but not Tavion) - //make me parry - WP_SaberParry( hitOwner, ent ); - //turn the parry into a knockaway - hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry( hitOwner->client->ps.saberBlocked ); - //make them go into a broken parry - ent->client->ps.saberBounceMove = PM_BrokenParryForAttack( ent->client->ps.saberMove ); + // base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE + if (entPowerLevel < FORCE_LEVEL_3 + //&& ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_3//if you have high saber offense, you cannot have your attack + //knocked away, regardless of what style you're using? + && hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 && activeDefense && + (hitOwnerPowerLevel > FORCE_LEVEL_2 || + (hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 && + Q_irand(0, hitOwner->client->ps.saberAnimLevel)))) { // knockaways can make fast-attacker go into a broken parry anim if the ent + // is using fast or med (but not Tavion) + // make me parry + WP_SaberParry(hitOwner, ent); + // turn the parry into a knockaway + hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry(hitOwner->client->ps.saberBlocked); + // make them go into a broken parry + ent->client->ps.saberBounceMove = PM_BrokenParryForAttack(ent->client->ps.saberMove); ent->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; - if ( ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 - && (ent->s.number||g_saberRealisticCombat->integer) )//&& !Q_irand( 0, 3 ) ) - {//knocked the saber right out of his hand! (never happens to player) - //Get a good velocity to send the saber in based on my parry move - vec3_t throwDir; - if ( !PM_VelocityForBlockedMove( &hitOwner->client->ps, throwDir ) ) - { - PM_VelocityForSaberMove( &ent->client->ps, throwDir ); + if (ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 && + (ent->s.number || g_saberRealisticCombat->integer)) //&& !Q_irand( 0, 3 ) ) + { // knocked the saber right out of his hand! (never happens to player) + // Get a good velocity to send the saber in based on my parry move + vec3_t throwDir; + if (!PM_VelocityForBlockedMove(&hitOwner->client->ps, throwDir)) { + PM_VelocityForSaberMove(&ent->client->ps, throwDir); } - WP_SaberLose( ent, throwDir ); + WP_SaberLose(ent, throwDir); } - //just so Jedi knows that he was blocked + // just so Jedi knows that he was blocked ent->client->ps.saberEventFlags |= SEF_BLOCKED; #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( S_COLOR_RED"%s knockaway %s's attack, new move = %s, anim = %s\n", hitOwner->NPC_type, ent->NPC_type, saberMoveData[ent->client->ps.saberBounceMove].name, animTable[saberMoveData[ent->client->ps.saberBounceMove].animToUse].name ); + if (d_saberCombat->integer) { + gi.Printf(S_COLOR_RED "%s knockaway %s's attack, new move = %s, anim = %s\n", hitOwner->NPC_type, ent->NPC_type, + saberMoveData[ent->client->ps.saberBounceMove].name, + animTable[saberMoveData[ent->client->ps.saberBounceMove].animToUse].name); } #endif - } - else if ( entPowerLevel > FORCE_LEVEL_2 - || !activeDefense - || (!deflected && Q_irand( 0, PM_PowerLevelForSaberAnim( &ent->client->ps ) - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE]/*PM_PowerLevelForSaberAnim( &hitOwner->client->ps )*/ ) > 0 ) ) - {//broke their parry altogether - if ( entPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) ) - {//chance of continuing with the attack (not bouncing back) + } else if (entPowerLevel > FORCE_LEVEL_2 || !activeDefense || + (!deflected && + Q_irand(0, + PM_PowerLevelForSaberAnim(&ent->client->ps) - + hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] /*PM_PowerLevelForSaberAnim( &hitOwner->client->ps )*/) > + 0)) { // broke their parry altogether + if (entPowerLevel > FORCE_LEVEL_2 || + Q_irand( + 0, + ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - + hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE])) { // chance of continuing with the attack (not bouncing back) ent->client->ps.saberEventFlags &= ~SEF_BLOCKED; ent->client->ps.saberBounceMove = LS_NONE; brokenParry = qtrue; } - //do some time-consuming saber-knocked-aside broken parry anim + // do some time-consuming saber-knocked-aside broken parry anim hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; hitOwner->client->ps.saberBounceMove = LS_NONE; - if ( hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 - && (ent->s.number||g_saberRealisticCombat->integer) - && !Q_irand( 0, 2 ) ) - {//knocked the saber right out of his hand! - //get the right velocity for my attack direction - vec3_t throwDir; - PM_VelocityForSaberMove( &ent->client->ps, throwDir ); - WP_SaberLose( hitOwner, throwDir ); - if ( (ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0,3) ) - || ( ent->client->ps.saberAnimLevel==FORCE_LEVEL_4&&!Q_irand(0,1) ) ) - {// a strong attack - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + if (hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_2 && (ent->s.number || g_saberRealisticCombat->integer) && + !Q_irand(0, 2)) { // knocked the saber right out of his hand! + // get the right velocity for my attack direction + vec3_t throwDir; + PM_VelocityForSaberMove(&ent->client->ps, throwDir); + WP_SaberLose(hitOwner, throwDir); + if ((ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0, 3)) || + (ent->client->ps.saberAnimLevel == FORCE_LEVEL_4 && !Q_irand(0, 1))) { // a strong attack + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } } - } - else - { - if ( (ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0,5) ) - || ( ent->client->ps.saberAnimLevel==FORCE_LEVEL_4&&!Q_irand(0,3) ) ) - {// a strong attack - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + } else { + if ((ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0, 5)) || + (ent->client->ps.saberAnimLevel == FORCE_LEVEL_4 && !Q_irand(0, 3))) { // a strong attack + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( ent->client->ps.saberEventFlags&SEF_BLOCKED ) - { - gi.Printf( S_COLOR_RED"%s parry broken (bounce/deflect)!\n", hitOwner->targetname ); - } - else - { - gi.Printf( S_COLOR_RED"%s parry broken (follow-through)!\n", hitOwner->targetname ); + if (d_saberCombat->integer) { + if (ent->client->ps.saberEventFlags & SEF_BLOCKED) { + gi.Printf(S_COLOR_RED "%s parry broken (bounce/deflect)!\n", hitOwner->targetname); + } else { + gi.Printf(S_COLOR_RED "%s parry broken (follow-through)!\n", hitOwner->targetname); } } #endif - } - else - { - WP_SaberParry( hitOwner, ent ); - if ( PM_SaberInBounce( ent->client->ps.saberMove ) //FIXME: saberMove not set until pmove! - && activeDefense - && hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_1 && hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 - && hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 ) - {//attacker bounced off, and defender has ability to do knockaways, so do one unless we're using fast attacks - //turn the parry into a knockaway - hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry( hitOwner->client->ps.saberBlocked ); - } - else if ( (ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0,6) ) - || ( ent->client->ps.saberAnimLevel==FORCE_LEVEL_4 && !Q_irand(0,3) ) ) - {// a strong attack can sometimes do a knockdown - //HMM... maybe only if they're moving backwards? - if ( WP_BrokenParryKnockDown( hitOwner ) ) - { + } else { + WP_SaberParry(hitOwner, ent); + if (PM_SaberInBounce(ent->client->ps.saberMove) // FIXME: saberMove not set until pmove! + && activeDefense && hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_1 && + hitOwner->client->ps.saberAnimLevel != FORCE_LEVEL_5 && + hitOwner->client->ps.forcePowerLevel[FP_SABER_DEFENSE] > + FORCE_LEVEL_2) { // attacker bounced off, and defender has ability to do knockaways, so do one unless we're using fast + // attacks + // turn the parry into a knockaway + hitOwner->client->ps.saberBounceMove = PM_KnockawayForParry(hitOwner->client->ps.saberBlocked); + } else if ((ent->client->ps.saberAnimLevel == FORCE_LEVEL_3 && !Q_irand(0, 6)) || + (ent->client->ps.saberAnimLevel == FORCE_LEVEL_4 && !Q_irand(0, 3))) { // a strong attack can sometimes do a knockdown + // HMM... maybe only if they're moving backwards? + if (WP_BrokenParryKnockDown(hitOwner)) { hitOwner->client->ps.saberBlocked = BLOCKED_NONE; hitOwner->client->ps.saberBounceMove = LS_NONE; } @@ -3228,9 +2652,11 @@ void WP_SaberDamageTrace( gentity_t *ent ) hitOwner->client->ps.saberEventFlags |= SEF_BLOCKED; } //FIXME: base parry breaks on animation (saber attack level), not FP_SABER_OFFENSE - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || (!deflected && Q_irand( 0, PM_PowerLevelForSaberAnim( &hitOwner->client->ps ) - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) > 0 ) ) + if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || (!deflected && Q_irand( 0, PM_PowerLevelForSaberAnim( &hitOwner->client->ps ) - +ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) > 0 ) ) {//broke my parry altogether - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) ) + if ( hitOwnerPowerLevel > FORCE_LEVEL_2 || Q_irand( 0, hitOwner->client->ps.forcePowerLevel[FP_SABER_OFFENSE] - +ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] ) ) {//chance of continuing with the attack (not bouncing back) hitOwner->client->ps.saberEventFlags &= ~SEF_BLOCKED; hitOwner->client->ps.saberBounceMove = LS_NONE; @@ -3258,42 +2684,31 @@ void WP_SaberDamageTrace( gentity_t *ent ) collisionResolved = qtrue; } */ - else - {//some other kind of in-hand saber collision + else { // some other kind of in-hand saber collision } } - } - else - {//some kind of in-flight collision + } else { // some kind of in-flight collision } - if ( saberHitFraction < 1.0f ) - { - if ( !collisionResolved && baseDamage ) - {//some other kind of in-hand saber collision - //handle my reaction - if ( !ent->client->ps.saberInFlight - && ent->client->ps.saberLockTime < level.time ) - {//my saber is in hand - if ( ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { - if ( PM_SaberInAttack( ent->client->ps.saberMove ) || PM_SaberInSpecialAttack( ent->client->ps.torsoAnim ) || - (entPowerLevel > FORCE_LEVEL_2&&!PM_SaberInIdle(ent->client->ps.saberMove)&&!PM_SaberInParry(ent->client->ps.saberMove)&&!PM_SaberInReflect(ent->client->ps.saberMove)) ) - {//in the middle of attacking - if ( entPowerLevel < FORCE_LEVEL_3 && hitOwner->health > 0 ) - {//don't deflect/bounce in strong attack or when enemy is dead - WP_GetSaberDeflectionAngle( ent, hitOwner ); + if (saberHitFraction < 1.0f) { + if (!collisionResolved && baseDamage) { // some other kind of in-hand saber collision + // handle my reaction + if (!ent->client->ps.saberInFlight && ent->client->ps.saberLockTime < level.time) { // my saber is in hand + if (ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { + if (PM_SaberInAttack(ent->client->ps.saberMove) || PM_SaberInSpecialAttack(ent->client->ps.torsoAnim) || + (entPowerLevel > FORCE_LEVEL_2 && !PM_SaberInIdle(ent->client->ps.saberMove) && !PM_SaberInParry(ent->client->ps.saberMove) && + !PM_SaberInReflect(ent->client->ps.saberMove))) { // in the middle of attacking + if (entPowerLevel < FORCE_LEVEL_3 && hitOwner->health > 0) { // don't deflect/bounce in strong attack or when enemy is dead + WP_GetSaberDeflectionAngle(ent, hitOwner); ent->client->ps.saberEventFlags |= SEF_BLOCKED; - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( hitOwner->s.number ); + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(hitOwner->s.number); } - } - else - {//saber collided when not attacking, parry it - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( hitOwner->s.number ); + } else { // saber collided when not attacking, parry it + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(hitOwner->s.number); /* if ( ent->s.number || g_saberAutoBlocking->integer || ent->client->ps.saberBlockingTime > level.time ) {//either an NPC or a player who has blocking @@ -3306,27 +2721,20 @@ void WP_SaberDamageTrace( gentity_t *ent ) } */ } + } else { + // since it was blocked/deflected, take away any damage done + // FIXME: what if the damage was done before the parry? + WP_SaberClearDamageForEntNum(hitOwner->s.number); } - else - { - //since it was blocked/deflected, take away any damage done - //FIXME: what if the damage was done before the parry? - WP_SaberClearDamageForEntNum( hitOwner->s.number ); - } - } - else - {//nothing happens to *me* when my inFlight saber hits something - } - //handle their reaction - if ( hitOwner - && hitOwner->health > 0 - && hitOwner->client - && !hitOwner->client->ps.saberInFlight - && hitOwner->client->ps.saberLockTime < level.time ) - {//their saber is in hand - if ( PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) || - (hitOwner->client->ps.saberAnimLevel > FORCE_LEVEL_2&&!PM_SaberInIdle(hitOwner->client->ps.saberMove)&&!PM_SaberInParry(hitOwner->client->ps.saberMove)&&!PM_SaberInReflect(hitOwner->client->ps.saberMove)) ) - {//in the middle of attacking + } else { // nothing happens to *me* when my inFlight saber hits something + } + // handle their reaction + if (hitOwner && hitOwner->health > 0 && hitOwner->client && !hitOwner->client->ps.saberInFlight && + hitOwner->client->ps.saberLockTime < level.time) { // their saber is in hand + if (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim) || + (hitOwner->client->ps.saberAnimLevel > FORCE_LEVEL_2 && !PM_SaberInIdle(hitOwner->client->ps.saberMove) && + !PM_SaberInParry(hitOwner->client->ps.saberMove) && + !PM_SaberInReflect(hitOwner->client->ps.saberMove))) { // in the middle of attacking /* if ( hitOwner->client->ps.saberAnimLevel < FORCE_LEVEL_3 ) {//don't deflect/bounce in strong attack @@ -3334,29 +2742,21 @@ void WP_SaberDamageTrace( gentity_t *ent ) hitOwner->client->ps.saberEventFlags |= SEF_BLOCKED; } */ - } - else - {//saber collided when not attacking, parry it - if ( !PM_SaberInBrokenParry( hitOwner->client->ps.saberMove ) ) - {//not currently in a broken parry - if ( !WP_SaberParry( hitOwner, ent ) ) - {//FIXME: hitOwner can't parry, do some time-consuming saber-knocked-aside broken parry anim? - //hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; + } else { // saber collided when not attacking, parry it + if (!PM_SaberInBrokenParry(hitOwner->client->ps.saberMove)) { // not currently in a broken parry + if (!WP_SaberParry(hitOwner, ent)) { // FIXME: hitOwner can't parry, do some time-consuming saber-knocked-aside broken parry anim? + // hitOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; } } } - } - else - {//nothing happens to *hitOwner* when their inFlight saber hits something + } else { // nothing happens to *hitOwner* when their inFlight saber hits something } } - //collision must have been handled by now - //Set the blocked attack bounce value in saberBlocked so we actually play our saberBounceMove anim - if ( ent->client->ps.saberEventFlags & SEF_BLOCKED ) - { - if ( ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { + // collision must have been handled by now + // Set the blocked attack bounce value in saberBlocked so we actually play our saberBounceMove anim + if (ent->client->ps.saberEventFlags & SEF_BLOCKED) { + if (ent->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { ent->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; } } @@ -3368,133 +2768,105 @@ void WP_SaberDamageTrace( gentity_t *ent ) */ } - if ( saberHitFraction < 1.0f || collisionResolved ) - {//either actually hit or locked - if ( ent->client->ps.saberLockTime < level.time ) - { - if ( inFlightSaberBlocked ) - {//FIXME: never hear this sound - G_Sound( &g_entities[ent->client->ps.saberEntityNum], G_SoundIndex( va( "sound/weapons/saber/saberbounce%d.wav", Q_irand(1,3) ) ) ); - } - else - { - if ( deflected ) - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberbounce%d.wav", Q_irand(1,3) ) ) ); - } - else - { - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + if (saberHitFraction < 1.0f || collisionResolved) { // either actually hit or locked + if (ent->client->ps.saberLockTime < level.time) { + if (inFlightSaberBlocked) { // FIXME: never hear this sound + G_Sound(&g_entities[ent->client->ps.saberEntityNum], G_SoundIndex(va("sound/weapons/saber/saberbounce%d.wav", Q_irand(1, 3)))); + } else { + if (deflected) { + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberbounce%d.wav", Q_irand(1, 3)))); + } else { + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); } } - G_PlayEffect( "saber_block", saberHitLocation, saberHitNormal ); + G_PlayEffect("saber_block", saberHitLocation, saberHitNormal); } // Set the little screen flash - only when an attack is blocked - g_saberFlashTime = level.time-50; - VectorCopy( saberHitLocation, g_saberFlashPos ); - } - - if ( saberHitFraction < 1.0f ) - { - if ( inFlightSaberBlocked ) - {//we threw a saber and it was blocked, do any effects, etc. - int knockAway = 5; - if ( hitEnt - && hitOwner - && hitOwner->client - && (PM_SaberInAttack( hitOwner->client->ps.saberMove ) || PM_SaberInSpecialAttack( hitOwner->client->ps.torsoAnim ) || PM_SpinningSaberAnim( hitOwner->client->ps.torsoAnim )) ) - {//if hit someone who was in an attack or spin anim, more likely to have in-flight saber knocked away - if ( hitOwnerPowerLevel > FORCE_LEVEL_2 ) - {//string attacks almost always knock it aside! + g_saberFlashTime = level.time - 50; + VectorCopy(saberHitLocation, g_saberFlashPos); + } + + if (saberHitFraction < 1.0f) { + if (inFlightSaberBlocked) { // we threw a saber and it was blocked, do any effects, etc. + int knockAway = 5; + if (hitEnt && hitOwner && hitOwner->client && + (PM_SaberInAttack(hitOwner->client->ps.saberMove) || PM_SaberInSpecialAttack(hitOwner->client->ps.torsoAnim) || + PM_SpinningSaberAnim(hitOwner->client->ps.torsoAnim))) { // if hit someone who was in an attack or spin anim, more likely to have in-flight + // saber knocked away + if (hitOwnerPowerLevel > FORCE_LEVEL_2) { // string attacks almost always knock it aside! knockAway = 1; - } - else - {//33% chance + } else { // 33% chance knockAway = 2; } } - if ( !Q_irand( 0, knockAway ) || //random - ( hitOwner && hitOwner->client && - (hitOwner->client->NPC_class==CLASS_DESANN||hitOwner->client->NPC_class==CLASS_TAVION||hitOwner->client->NPC_class==CLASS_LUKE) - ) //or if blocked by a Boss character FIXME: or base on defense level? - )//FIXME: player should not auto-block a flying saber, let him override the parry with an attack to knock the saber from the air, rather than this random chance - {//knock it aside and turn it off - G_PlayEffect( "saber_cut", saberHitLocation, saberHitNormal ); - if ( hitEnt ) - { + if (!Q_irand(0, knockAway) || // random + (hitOwner && hitOwner->client && + (hitOwner->client->NPC_class == CLASS_DESANN || hitOwner->client->NPC_class == CLASS_TAVION || + hitOwner->client->NPC_class == CLASS_LUKE)) // or if blocked by a Boss character FIXME: or base on defense level? + ) // FIXME: player should not auto-block a flying saber, let him override the parry with an attack to knock the saber from the air, rather + // than this random chance + { // knock it aside and turn it off + G_PlayEffect("saber_cut", saberHitLocation, saberHitNormal); + if (hitEnt) { vec3_t newDir; - VectorSubtract( g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir ); - VectorNormalize( newDir ); - G_ReflectMissile( ent, &g_entities[ent->client->ps.saberEntityNum], newDir ); + VectorSubtract(g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir); + VectorNormalize(newDir); + G_ReflectMissile(ent, &g_entities[ent->client->ps.saberEntityNum], newDir); } - Jedi_PlayDeflectSound( hitOwner ); - WP_SaberDrop( ent, &g_entities[ent->client->ps.saberEntityNum] ); - } - else - { - if ( !Q_irand( 0, 2 ) && hitEnt ) - { + Jedi_PlayDeflectSound(hitOwner); + WP_SaberDrop(ent, &g_entities[ent->client->ps.saberEntityNum]); + } else { + if (!Q_irand(0, 2) && hitEnt) { vec3_t newDir; - VectorSubtract( g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir ); - VectorNormalize( newDir ); - G_ReflectMissile( ent, &g_entities[ent->client->ps.saberEntityNum], newDir ); + VectorSubtract(g_entities[ent->client->ps.saberEntityNum].currentOrigin, hitEnt->currentOrigin, newDir); + VectorNormalize(newDir); + G_ReflectMissile(ent, &g_entities[ent->client->ps.saberEntityNum], newDir); } - WP_SaberReturn( ent, &g_entities[ent->client->ps.saberEntityNum] ); + WP_SaberReturn(ent, &g_entities[ent->client->ps.saberEntityNum]); } } } } - if ( ent->client->ps.saberLockTime > level.time - && ent->s.number < ent->client->ps.saberLockEnemy - && !Q_irand( 0, 3 ) ) - {//need to make some kind of effect - vec3_t hitNorm = {0,0,1}; - if ( WP_SabersIntersection( ent, &g_entities[ent->client->ps.saberLockEnemy], g_saberFlashPos ) ) - { - if ( Q_irand( 0, 10 ) ) - { - G_PlayEffect( "saber_block", g_saberFlashPos, hitNorm ); - } - else - { - g_saberFlashTime = level.time-50; - G_PlayEffect( "saber_cut", g_saberFlashPos, hitNorm ); + if (ent->client->ps.saberLockTime > level.time && ent->s.number < ent->client->ps.saberLockEnemy && !Q_irand(0, 3)) { // need to make some kind of effect + vec3_t hitNorm = {0, 0, 1}; + if (WP_SabersIntersection(ent, &g_entities[ent->client->ps.saberLockEnemy], g_saberFlashPos)) { + if (Q_irand(0, 10)) { + G_PlayEffect("saber_block", g_saberFlashPos, hitNorm); + } else { + g_saberFlashTime = level.time - 50; + G_PlayEffect("saber_cut", g_saberFlashPos, hitNorm); } - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); } } - if ( WP_SaberApplyDamage( ent, baseDamage, baseDFlags, brokenParry ) ) - {//actually did damage to something + if (WP_SaberApplyDamage(ent, baseDamage, baseDFlags, brokenParry)) { // actually did damage to something #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - gi.Printf( "base damage was %4.2f\n", baseDamage ); + if (d_saberCombat->integer) { + gi.Printf("base damage was %4.2f\n", baseDamage); } #endif - G_Sound( ent, G_SoundIndex( va( "sound/weapons/saber/saberhit%d.wav", Q_irand( 1, 3 ) ) ) ); + G_Sound(ent, G_SoundIndex(va("sound/weapons/saber/saberhit%d.wav", Q_irand(1, 3)))); } - if ( hit_wall ) - { - //just so Jedi knows that he hit a wall + if (hit_wall) { + // just so Jedi knows that he hit a wall ent->client->ps.saberEventFlags |= SEF_HITWALL; - if ( ent->s.number == 0 ) - { - AddSoundEvent( ent, ent->currentOrigin, 128, AEL_DISCOVERED ); - AddSightEvent( ent, ent->currentOrigin, 256, AEL_DISCOVERED, 50 ); + if (ent->s.number == 0) { + AddSoundEvent(ent, ent->currentOrigin, 128, AEL_DISCOVERED); + AddSightEvent(ent, ent->currentOrigin, 256, AEL_DISCOVERED, 50); } } } -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ -//SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ +// SABER THROWING============================================================================ /* ================ @@ -3502,417 +2874,356 @@ WP_SaberImpact ================ */ -void WP_SaberImpact( gentity_t *owner, gentity_t *saber, trace_t *trace ) -{ - gentity_t *other; +void WP_SaberImpact(gentity_t *owner, gentity_t *saber, trace_t *trace) { + gentity_t *other; other = &g_entities[trace->entityNum]; - if ( other->takedamage && (other->svFlags&SVF_BBRUSH) ) - {//a breakable brush? break it! + if (other->takedamage && (other->svFlags & SVF_BBRUSH)) { // a breakable brush? break it! vec3_t dir; - VectorCopy( saber->s.pos.trDelta, dir ); - VectorNormalize( dir ); + VectorCopy(saber->s.pos.trDelta, dir); + VectorNormalize(dir); - int dmg = other->health*2; - if ( other->health > 50 && dmg > 20 && !(other->svFlags&SVF_GLASS_BRUSH) ) - { + int dmg = other->health * 2; + if (other->health > 50 && dmg > 20 && !(other->svFlags & SVF_GLASS_BRUSH)) { dmg = 20; } - G_Damage( other, owner, saber, dir, trace->endpos, dmg, 0, MOD_SABER ); - G_PlayEffect( "saber_cut", trace->endpos, dir ); - if ( owner->s.number == 0 ) - { - AddSoundEvent( owner, trace->endpos, 256, AEL_DISCOVERED ); - AddSightEvent( owner, trace->endpos, 512, AEL_DISCOVERED, 50 ); + G_Damage(other, owner, saber, dir, trace->endpos, dmg, 0, MOD_SABER); + G_PlayEffect("saber_cut", trace->endpos, dir); + if (owner->s.number == 0) { + AddSoundEvent(owner, trace->endpos, 256, AEL_DISCOVERED); + AddSightEvent(owner, trace->endpos, 512, AEL_DISCOVERED, 50); } return; } - if ( saber->s.pos.trType == TR_LINEAR ) - { - //hit a wall? send it back - WP_SaberReturn( saber->owner, saber ); + if (saber->s.pos.trType == TR_LINEAR) { + // hit a wall? send it back + WP_SaberReturn(saber->owner, saber); } - if ( other && !other->client && (other->contents&CONTENTS_LIGHTSABER) )//&& other->s.weapon == WP_SABER ) - {//2 in-flight sabers collided! - //Big flash - //FIXME: bigger effect/sound? - //FIXME: STILL DOESNT WORK!!! - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - G_PlayEffect( "saber_block", trace->endpos ); - g_saberFlashTime = level.time-50; - VectorCopy( trace->endpos, g_saberFlashPos ); + if (other && !other->client && (other->contents & CONTENTS_LIGHTSABER)) //&& other->s.weapon == WP_SABER ) + { // 2 in-flight sabers collided! + // Big flash + // FIXME: bigger effect/sound? + // FIXME: STILL DOESNT WORK!!! + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); + G_PlayEffect("saber_block", trace->endpos); + g_saberFlashTime = level.time - 50; + VectorCopy(trace->endpos, g_saberFlashPos); } - if ( owner && owner->s.number == 0 && owner->client ) - { - //Add the event - if ( owner->client->ps.saberLength > 0 ) - {//saber is on, very suspicious - AddSoundEvent( owner, saber->currentOrigin, 128, AEL_DISCOVERED ); - AddSightEvent( owner, saber->currentOrigin, 256, AEL_DISCOVERED, 50 ); - } - else - {//saber is off, not as suspicious - AddSoundEvent( owner, saber->currentOrigin, 128, AEL_SUSPICIOUS ); - AddSightEvent( owner, saber->currentOrigin, 256, AEL_SUSPICIOUS ); + if (owner && owner->s.number == 0 && owner->client) { + // Add the event + if (owner->client->ps.saberLength > 0) { // saber is on, very suspicious + AddSoundEvent(owner, saber->currentOrigin, 128, AEL_DISCOVERED); + AddSightEvent(owner, saber->currentOrigin, 256, AEL_DISCOVERED, 50); + } else { // saber is off, not as suspicious + AddSoundEvent(owner, saber->currentOrigin, 128, AEL_SUSPICIOUS); + AddSightEvent(owner, saber->currentOrigin, 256, AEL_SUSPICIOUS); } } // check for bounce - if ( !other->takedamage && ( saber->s.eFlags & ( EF_BOUNCE | EF_BOUNCE_HALF ) ) ) - { + if (!other->takedamage && (saber->s.eFlags & (EF_BOUNCE | EF_BOUNCE_HALF))) { // Check to see if there is a bounce count - if ( saber->bounceCount ) { + if (saber->bounceCount) { // decrement number of bounces and then see if it should be done bouncing - if ( --saber->bounceCount <= 0 ) { + if (--saber->bounceCount <= 0) { // He (or she) will bounce no more (after this current bounce, that is). saber->s.eFlags &= ~(EF_BOUNCE | EF_BOUNCE_HALF); - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - { - WP_SaberDrop( saber->owner, saber ); + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING) { + WP_SaberDrop(saber->owner, saber); } return; - } - else - {//bounced and still have bounces left - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - {//under telekinetic control - if ( !gi.inPVS( saber->currentOrigin, owner->client->renderInfo.handRPoint ) ) - {//not in the PVS of my master + } else { // bounced and still have bounces left + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && + owner->client->ps.saberEntityState == SES_RETURNING) { // under telekinetic control + if (!gi.inPVS(saber->currentOrigin, owner->client->renderInfo.handRPoint)) { // not in the PVS of my master saber->bounceCount -= 25; } } } } - if ( saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING ) - { - //don't home for a few frames so we can get around this thing - trace_t bounceTr; - vec3_t end; - float owner_dist = Distance( owner->client->renderInfo.handRPoint, saber->currentOrigin ); - - VectorMA( saber->currentOrigin, 10, trace->plane.normal, end ); - gi.trace( &bounceTr, saber->currentOrigin, saber->mins, saber->maxs, end, owner->s.number, saber->clipmask, G2_NOCOLLIDE, 0 ); - VectorCopy( bounceTr.endpos, saber->currentOrigin ); - if ( owner_dist > 0 ) - { - if ( owner_dist > 50 ) - { - owner->client->ps.saberEntityDist = owner_dist-50; - } - else - { + if (saber->s.pos.trType == TR_LINEAR && owner && owner->client && owner->client->ps.saberEntityState == SES_RETURNING) { + // don't home for a few frames so we can get around this thing + trace_t bounceTr; + vec3_t end; + float owner_dist = Distance(owner->client->renderInfo.handRPoint, saber->currentOrigin); + + VectorMA(saber->currentOrigin, 10, trace->plane.normal, end); + gi.trace(&bounceTr, saber->currentOrigin, saber->mins, saber->maxs, end, owner->s.number, saber->clipmask, G2_NOCOLLIDE, 0); + VectorCopy(bounceTr.endpos, saber->currentOrigin); + if (owner_dist > 0) { + if (owner_dist > 50) { + owner->client->ps.saberEntityDist = owner_dist - 50; + } else { owner->client->ps.saberEntityDist = 0; } } return; } - G_BounceMissile( saber, trace ); + G_BounceMissile(saber, trace); - if ( saber->s.pos.trType == TR_GRAVITY ) - {//bounced - //play a bounce sound - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); - //change rotation - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); + if (saber->s.pos.trType == TR_GRAVITY) { // bounced + // play a bounce sound + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); + // change rotation + VectorCopy(saber->currentAngles, saber->s.apos.trBase); saber->s.apos.trType = TR_LINEAR; saber->s.apos.trTime = level.time; - VectorSet( saber->s.apos.trDelta, Q_irand( -300, 300 ), Q_irand( -300, 300 ), Q_irand( -300, 300 ) ); - } - //see if we stopped - else if ( saber->s.pos.trType == TR_STATIONARY ) - {//stopped - //play a bounce sound - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/bounce%d.wav", Q_irand( 1, 3 ) ) ) ); - //stop rotation - VectorClear( saber->s.apos.trDelta ); + VectorSet(saber->s.apos.trDelta, Q_irand(-300, 300), Q_irand(-300, 300), Q_irand(-300, 300)); + } + // see if we stopped + else if (saber->s.pos.trType == TR_STATIONARY) { // stopped + // play a bounce sound + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/bounce%d.wav", Q_irand(1, 3)))); + // stop rotation + VectorClear(saber->s.apos.trDelta); saber->currentAngles[0] = SABER_PITCH_HACK; - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); - //remember when it fell so it can return automagically + VectorCopy(saber->currentAngles, saber->s.apos.trBase); + // remember when it fell so it can return automagically saber->aimDebounceTime = level.time; } - } - else if ( other->client && other->health > 0 - && ( other->client->NPC_class == CLASS_DESANN || other->client->NPC_class == CLASS_TAVION || other->client->NPC_class == CLASS_LUKE || ( other->client->NPC_class == CLASS_GALAKMECH && other->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) ) ) - {//Luke, Desann and Tavion slap thrown sabers aside - WP_SaberDrop( owner, saber ); - G_Sound( saber, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - G_PlayEffect( "saber_block", trace->endpos ); - g_saberFlashTime = level.time-50; - VectorCopy( trace->endpos, g_saberFlashPos ); - //FIXME: make Luke/Desann/Tavion play an attack anim or some other special anim when this happens - Jedi_PlayDeflectSound( other ); + } else if (other->client && other->health > 0 && + (other->client->NPC_class == CLASS_DESANN || other->client->NPC_class == CLASS_TAVION || other->client->NPC_class == CLASS_LUKE || + (other->client->NPC_class == CLASS_GALAKMECH && + other->client->ps.powerups[PW_GALAK_SHIELD] > 0))) { // Luke, Desann and Tavion slap thrown sabers aside + WP_SaberDrop(owner, saber); + G_Sound(saber, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); + G_PlayEffect("saber_block", trace->endpos); + g_saberFlashTime = level.time - 50; + VectorCopy(trace->endpos, g_saberFlashPos); + // FIXME: make Luke/Desann/Tavion play an attack anim or some other special anim when this happens + Jedi_PlayDeflectSound(other); } } -extern float G_PointDistFromLineSegment( const vec3_t start, const vec3_t end, const vec3_t from ); -void WP_SaberInFlightReflectCheck( gentity_t *self, usercmd_t *ucmd ) -{ - gentity_t *ent; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *missile_list[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - int i, e; - int ent_count = 0; - int radius = 180; - vec3_t center, forward; - vec3_t tip; - vec3_t up = {0,0,1}; - - if ( self->NPC && (self->NPC->scriptFlags&SCF_IGNORE_ALERTS) ) - {//don't react to things flying at me... +extern float G_PointDistFromLineSegment(const vec3_t start, const vec3_t end, const vec3_t from); +void WP_SaberInFlightReflectCheck(gentity_t *self, usercmd_t *ucmd) { + gentity_t *ent; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *missile_list[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + int i, e; + int ent_count = 0; + int radius = 180; + vec3_t center, forward; + vec3_t tip; + vec3_t up = {0, 0, 1}; + + if (self->NPC && (self->NPC->scriptFlags & SCF_IGNORE_ALERTS)) { // don't react to things flying at me... return; } - //sanity checks: make sure we actually have a saberent - if ( self->client->ps.weapon != WP_SABER ) - { + // sanity checks: make sure we actually have a saberent + if (self->client->ps.weapon != WP_SABER) { return; } - if ( !self->client->ps.saberInFlight ) - { + if (!self->client->ps.saberInFlight) { return; } - if ( !self->client->ps.saberLength ) - { + if (!self->client->ps.saberLength) { return; } - if ( self->client->ps.saberEntityNum == ENTITYNUM_NONE ) - { + if (self->client->ps.saberEntityNum == ENTITYNUM_NONE) { return; } gentity_t *saberent = &g_entities[self->client->ps.saberEntityNum]; - if ( !saberent ) - { + if (!saberent) { return; } - //okay, enough damn sanity checks + // okay, enough damn sanity checks - VectorCopy( saberent->currentOrigin, center ); + VectorCopy(saberent->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - //FIXME: check visibility? - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + // FIXME: check visibility? + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType != ET_MISSILE ) - { - if ( ent->client || ent->s.weapon != WP_SABER ) - {//FIXME: wake up bad guys? + if (ent->s.eType != ET_MISSILE) { + if (ent->client || ent->s.weapon != WP_SABER) { // FIXME: wake up bad guys? continue; } - if ( ent->s.eFlags & EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber continue; } - } - else - {//FIXME: make exploding missiles explode? - if ( ent->s.pos.trType == TR_STATIONARY ) - {//nothing you can do with a stationary missile + } else { // FIXME: make exploding missiles explode? + if (ent->s.pos.trType == TR_STATIONARY) { // nothing you can do with a stationary missile continue; } - if ( ent->splashDamage || ent->splashRadius ) - {//can't deflect exploding missiles - if ( DistanceSquared( ent->currentOrigin, center ) < 256 )//16 squared + if (ent->splashDamage || ent->splashRadius) { // can't deflect exploding missiles + if (DistanceSquared(ent->currentOrigin, center) < 256) // 16 squared { - G_MissileImpacted( ent, saberent, ent->currentOrigin, up ); + G_MissileImpacted(ent, saberent, ent->currentOrigin, up); } continue; } } - //don't deflect it if it's not within 16 units of the blade - VectorMA( self->client->renderInfo.muzzlePoint, self->client->ps.saberLength, self->client->renderInfo.muzzleDir, tip ); + // don't deflect it if it's not within 16 units of the blade + VectorMA(self->client->renderInfo.muzzlePoint, self->client->ps.saberLength, self->client->renderInfo.muzzleDir, tip); - if( G_PointDistFromLineSegment( self->client->renderInfo.muzzlePoint, tip, ent->currentOrigin ) > 32 ) - { + if (G_PointDistFromLineSegment(self->client->renderInfo.muzzlePoint, tip, ent->currentOrigin) > 32) { continue; } // ok, we are within the radius, add us to the incoming list missile_list[ent_count] = ent; ent_count++; - } - if ( ent_count ) - { - vec3_t fx_dir; + if (ent_count) { + vec3_t fx_dir; // we are done, do we have any to deflect? - if ( ent_count ) - { - for ( int x = 0; x < ent_count; x++ ) - { - if ( missile_list[x]->s.weapon == WP_SABER ) - {//just send it back - if ( missile_list[x]->owner && missile_list[x]->owner->client && missile_list[x]->owner->client->ps.saberActive && missile_list[x]->s.pos.trType == TR_LINEAR && missile_list[x]->owner->client->ps.saberEntityState != SES_RETURNING ) - {//it's on and being controlled - //FIXME: prevent it from damaging me? - WP_SaberReturn( missile_list[x]->owner, missile_list[x] ); - VectorNormalize2( missile_list[x]->s.pos.trDelta, fx_dir ); - G_PlayEffect( "saber_block", missile_list[x]->currentOrigin, fx_dir ); - if ( missile_list[x]->owner->client->ps.saberInFlight && self->client->ps.saberInFlight ) - { - G_Sound( missile_list[x], G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) ) ) ); - g_saberFlashTime = level.time-50; + if (ent_count) { + for (int x = 0; x < ent_count; x++) { + if (missile_list[x]->s.weapon == WP_SABER) { // just send it back + if (missile_list[x]->owner && missile_list[x]->owner->client && missile_list[x]->owner->client->ps.saberActive && + missile_list[x]->s.pos.trType == TR_LINEAR && + missile_list[x]->owner->client->ps.saberEntityState != SES_RETURNING) { // it's on and being controlled + // FIXME: prevent it from damaging me? + WP_SaberReturn(missile_list[x]->owner, missile_list[x]); + VectorNormalize2(missile_list[x]->s.pos.trDelta, fx_dir); + G_PlayEffect("saber_block", missile_list[x]->currentOrigin, fx_dir); + if (missile_list[x]->owner->client->ps.saberInFlight && self->client->ps.saberInFlight) { + G_Sound(missile_list[x], G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9)))); + g_saberFlashTime = level.time - 50; gentity_t *saber = &g_entities[self->client->ps.saberEntityNum]; - vec3_t org; - VectorSubtract( missile_list[x]->currentOrigin, saber->currentOrigin, org ); - VectorMA( saber->currentOrigin, 0.5, org, org ); - VectorCopy( org, g_saberFlashPos ); + vec3_t org; + VectorSubtract(missile_list[x]->currentOrigin, saber->currentOrigin, org); + VectorMA(saber->currentOrigin, 0.5, org, org); + VectorCopy(org, g_saberFlashPos); } } - } - else - {//bounce it - if ( self->client && !self->s.number ) - { + } else { // bounce it + if (self->client && !self->s.number) { self->client->sess.missionStats.saberBlocksCnt++; } - G_ReflectMissile( self, missile_list[x], forward ); - //do an effect - VectorNormalize2( missile_list[x]->s.pos.trDelta, fx_dir ); - G_PlayEffect( "blaster/deflect", missile_list[x]->currentOrigin, fx_dir ); + G_ReflectMissile(self, missile_list[x], forward); + // do an effect + VectorNormalize2(missile_list[x]->s.pos.trDelta, fx_dir); + G_PlayEffect("blaster/deflect", missile_list[x]->currentOrigin, fx_dir); } } } } } -qboolean WP_SaberValidateEnemy( gentity_t *self, gentity_t *enemy ) -{ - if ( !enemy ) - { +qboolean WP_SaberValidateEnemy(gentity_t *self, gentity_t *enemy) { + if (!enemy) { return qfalse; } - if ( !enemy || enemy == self || !enemy->inuse || !enemy->client ) - {//not valid + if (!enemy || enemy == self || !enemy->inuse || !enemy->client) { // not valid return qfalse; } - if ( enemy->health <= 0 ) - {//corpse + if (enemy->health <= 0) { // corpse return qfalse; } - if ( DistanceSquared( self->client->renderInfo.handRPoint, enemy->currentOrigin ) > saberThrowDistSquared[self->client->ps.forcePowerLevel[FP_SABERTHROW]] ) - {//too far + if (DistanceSquared(self->client->renderInfo.handRPoint, enemy->currentOrigin) > + saberThrowDistSquared[self->client->ps.forcePowerLevel[FP_SABERTHROW]]) { // too far return qfalse; } - if ( (!InFront( enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || !G_ClearLOS( self, self->client->renderInfo.eyePoint, enemy ) ) - && ( DistanceHorizontalSquared( enemy->currentOrigin, self->currentOrigin ) > 65536 || fabs(enemy->currentOrigin[2]-self->currentOrigin[2]) > 384 ) ) - {//(not in front or not clear LOS) & greater than 256 away + if ((!InFront(enemy->currentOrigin, self->currentOrigin, self->client->ps.viewangles, 0.0f) || + !G_ClearLOS(self, self->client->renderInfo.eyePoint, enemy)) && + (DistanceHorizontalSquared(enemy->currentOrigin, self->currentOrigin) > 65536 || + fabs(enemy->currentOrigin[2] - self->currentOrigin[2]) > 384)) { //(not in front or not clear LOS) & greater than 256 away return qfalse; } - if ( enemy->client->playerTeam == self->client->playerTeam ) - {//on same team + if (enemy->client->playerTeam == self->client->playerTeam) { // on same team return qfalse; } - //LOS? + // LOS? return qtrue; } -float WP_SaberRateEnemy( gentity_t *enemy, vec3_t center, vec3_t forward, float radius ) -{ +float WP_SaberRateEnemy(gentity_t *enemy, vec3_t center, vec3_t forward, float radius) { float rating; - vec3_t dir; + vec3_t dir; - VectorSubtract( enemy->currentOrigin, center, dir ); - rating = (1.0f-(VectorNormalize( dir )/radius)); - rating *= DotProduct( forward, dir ); + VectorSubtract(enemy->currentOrigin, center, dir); + rating = (1.0f - (VectorNormalize(dir) / radius)); + rating *= DotProduct(forward, dir); return rating; } -gentity_t *WP_SaberFindEnemy( gentity_t *self, gentity_t *saber ) -{ -//FIXME: should be a more intelligent way of doing this, like auto aim? -//closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? - gentity_t *ent, *bestEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t center, mins, maxs, fwdangles, forward; - int i, e; - float radius = 400; - float rating, bestRating = 0.0f; - - //FIXME: no need to do this in 1st person? +gentity_t *WP_SaberFindEnemy(gentity_t *self, gentity_t *saber) { + // FIXME: should be a more intelligent way of doing this, like auto aim? + // closest, most in front... did damage to... took damage from? How do we know who the player is focusing on? + gentity_t *ent, *bestEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t center, mins, maxs, fwdangles, forward; + int i, e; + float radius = 400; + float rating, bestRating = 0.0f; + + // FIXME: no need to do this in 1st person? fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - VectorCopy( saber->currentOrigin, center ); + VectorCopy(saber->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - if ( WP_SaberValidateEnemy( self, self->enemy ) ) - { + if (WP_SaberValidateEnemy(self, self->enemy)) { bestEnt = self->enemy; - bestRating = WP_SaberRateEnemy( bestEnt, center, forward, radius ); + bestRating = WP_SaberRateEnemy(bestEnt, center, forward, radius); } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - if ( !numListedEntities ) - {//should we clear the enemy? + if (!numListedEntities) { // should we clear the enemy? return bestEnt; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; - if ( ent == self || ent == saber || ent == bestEnt ) - { + if (ent == self || ent == saber || ent == bestEnt) { continue; } - if ( !WP_SaberValidateEnemy( self, ent ) ) - {//doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call + if (!WP_SaberValidateEnemy( + self, ent)) { // doesn't meet criteria of valid look enemy (don't check current since we would have done that before this func's call continue; } - if ( !gi.inPVS( self->currentOrigin, ent->currentOrigin ) ) - {//not even potentially visible + if (!gi.inPVS(self->currentOrigin, ent->currentOrigin)) { // not even potentially visible continue; } - if ( !G_ClearLOS( self, self->client->renderInfo.eyePoint, ent ) ) - {//can't see him + if (!G_ClearLOS(self, self->client->renderInfo.eyePoint, ent)) { // can't see him continue; } - //rate him based on how close & how in front he is - rating = WP_SaberRateEnemy( ent, center, forward, radius ); - if ( rating > bestRating ) - { + // rate him based on how close & how in front he is + rating = WP_SaberRateEnemy(ent, center, forward, radius); + if (rating > bestRating) { bestEnt = ent; bestRating = rating; } @@ -3920,120 +3231,95 @@ gentity_t *WP_SaberFindEnemy( gentity_t *self, gentity_t *saber ) return bestEnt; } -void WP_RunSaber( gentity_t *self, gentity_t *saber ) -{ - vec3_t origin, oldOrg; - trace_t tr; +void WP_RunSaber(gentity_t *self, gentity_t *saber) { + vec3_t origin, oldOrg; + trace_t tr; - VectorCopy( saber->currentOrigin, oldOrg ); + VectorCopy(saber->currentOrigin, oldOrg); // get current position - EvaluateTrajectory( &saber->s.pos, level.time, origin ); + EvaluateTrajectory(&saber->s.pos, level.time, origin); // get current angles - EvaluateTrajectory( &saber->s.apos, level.time, saber->currentAngles ); + EvaluateTrajectory(&saber->s.apos, level.time, saber->currentAngles); // trace a line from the previous position to the current position, // ignoring interactions with the missile owner int clipmask = saber->clipmask; - if ( !self || !self->client || self->client->ps.saberLength <= 0 ) - {//don't keep hitting other sabers when turned off + if (!self || !self->client || self->client->ps.saberLength <= 0) { // don't keep hitting other sabers when turned off clipmask &= ~CONTENTS_LIGHTSABER; } - gi.trace( &tr, saber->currentOrigin, saber->mins, saber->maxs, origin, - saber->owner ? saber->owner->s.number : ENTITYNUM_NONE, clipmask, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, saber->currentOrigin, saber->mins, saber->maxs, origin, saber->owner ? saber->owner->s.number : ENTITYNUM_NONE, clipmask, G2_NOCOLLIDE, 0); - VectorCopy( tr.endpos, saber->currentOrigin ); + VectorCopy(tr.endpos, saber->currentOrigin); - if ( self->client->ps.saberActive ) - { - if ( self->client->ps.saberInFlight || (self->client->ps.weaponTime&&!Q_irand( 0, 100 )) ) - {//make enemies run from a lit saber in flight or from me when I'm attacking - if ( !Q_irand( 0, 10 ) ) - {//not so often... - AddSightEvent( self, saber->currentOrigin, self->client->ps.saberLength*3, AEL_DANGER, 100 ); + if (self->client->ps.saberActive) { + if (self->client->ps.saberInFlight || + (self->client->ps.weaponTime && !Q_irand(0, 100))) { // make enemies run from a lit saber in flight or from me when I'm attacking + if (!Q_irand(0, 10)) { // not so often... + AddSightEvent(self, saber->currentOrigin, self->client->ps.saberLength * 3, AEL_DANGER, 100); } } } - if ( tr.startsolid ) - { + if (tr.startsolid) { tr.fraction = 0; } - gi.linkentity( saber ); + gi.linkentity(saber); - //touch push triggers? + // touch push triggers? - if ( tr.fraction != 1 ) - { - WP_SaberImpact( self, saber, &tr ); + if (tr.fraction != 1) { + WP_SaberImpact(self, saber, &tr); } - if ( saber->s.pos.trType == TR_LINEAR ) - {//home - //figure out where saber should be - vec3_t forward, saberHome, saberDest, fwdangles = {0}; + if (saber->s.pos.trType == TR_LINEAR) { // home + // figure out where saber should be + vec3_t forward, saberHome, saberDest, fwdangles = {0}; - VectorCopy( self->client->ps.viewangles, fwdangles ); - if ( self->s.number ) - { + VectorCopy(self->client->ps.viewangles, fwdangles); + if (self->s.number) { fwdangles[0] -= 8; - } - else if ( cg.renderingThirdPerson ) - { + } else if (cg.renderingThirdPerson) { fwdangles[0] -= 5; } - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 - || self->client->ps.saberEntityState == SES_RETURNING - || VectorCompare( saber->s.pos.trDelta, vec3_origin ) ) - {//control if it's returning or just starting - float saberSpeed = 500;//FIXME: based on force level? - float dist; + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 || self->client->ps.saberEntityState == SES_RETURNING || + VectorCompare(saber->s.pos.trDelta, vec3_origin)) { // control if it's returning or just starting + float saberSpeed = 500; // FIXME: based on force level? + float dist; gentity_t *enemy = NULL; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - if ( self->client->ps.saberEntityDist < 100 ) - {//make the saber head to my hand- the bolt it was attached to - VectorCopy( self->client->renderInfo.handRPoint, saberHome ); + if (self->client->ps.saberEntityDist < 100) { // make the saber head to my hand- the bolt it was attached to + VectorCopy(self->client->renderInfo.handRPoint, saberHome); + } else { // aim saber from eyes + VectorCopy(self->client->renderInfo.eyePoint, saberHome); } - else - {//aim saber from eyes - VectorCopy( self->client->renderInfo.eyePoint, saberHome ); - } - VectorMA( saberHome, self->client->ps.saberEntityDist, forward, saberDest ); + VectorMA(saberHome, self->client->ps.saberEntityDist, forward, saberDest); - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING ) - {//max level - //pick an enemy - enemy = WP_SaberFindEnemy( self, saber ); - if ( enemy ) - {//home in on enemy - float enemyDist = Distance( self->client->renderInfo.handRPoint, enemy->currentOrigin ); - VectorCopy( enemy->currentOrigin, saberDest ); - saberDest[2] += enemy->maxs[2]/2.0f;//FIXME: when in a knockdown anim, the saber float above them... do we care? + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING) { // max level + // pick an enemy + enemy = WP_SaberFindEnemy(self, saber); + if (enemy) { // home in on enemy + float enemyDist = Distance(self->client->renderInfo.handRPoint, enemy->currentOrigin); + VectorCopy(enemy->currentOrigin, saberDest); + saberDest[2] += enemy->maxs[2] / 2.0f; // FIXME: when in a knockdown anim, the saber float above them... do we care? self->client->ps.saberEntityDist = enemyDist; } } - - //Make the saber head there - VectorSubtract( saberDest, saber->currentOrigin, saber->s.pos.trDelta ); - dist = VectorNormalize( saber->s.pos.trDelta ); - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING && !enemy ) - { - if ( dist < 200 ) - { - saberSpeed = 400 - (dist*2); + // Make the saber head there + VectorSubtract(saberDest, saber->currentOrigin, saber->s.pos.trDelta); + dist = VectorNormalize(saber->s.pos.trDelta); + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 && self->client->ps.saberEntityState == SES_LEAVING && !enemy) { + if (dist < 200) { + saberSpeed = 400 - (dist * 2); } - } - else if ( self->client->ps.saberEntityState == SES_LEAVING && dist < 50 ) - { + } else if (self->client->ps.saberEntityState == SES_LEAVING && dist < 50) { saberSpeed = dist * 2 + 30; - if ( (enemy && dist > enemy->maxs[0]) || (!enemy && dist > 24) ) - {//auto-tracking an enemy and we can't hit him - if ( saberSpeed < 120 ) - {//clamp to a minimum speed + if ((enemy && dist > enemy->maxs[0]) || (!enemy && dist > 24)) { // auto-tracking an enemy and we can't hit him + if (saberSpeed < 120) { // clamp to a minimum speed saberSpeed = 120; } } @@ -4048,107 +3334,88 @@ void WP_RunSaber( gentity_t *self, gentity_t *saber ) } } */ - VectorScale( saber->s.pos.trDelta, saberSpeed, saber->s.pos.trDelta ); - //SnapVector( saber->s.pos.trDelta ); // save net bandwidth - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + VectorScale(saber->s.pos.trDelta, saberSpeed, saber->s.pos.trDelta); + // SnapVector( saber->s.pos.trDelta ); // save net bandwidth + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; - } - else - { - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + } else { + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; } - //if it's heading back, point it's base at us - if ( self->client->ps.saberEntityState == SES_RETURNING ) - { + // if it's heading back, point it's base at us + if (self->client->ps.saberEntityState == SES_RETURNING) { fwdangles[0] += SABER_PITCH_HACK; - VectorCopy( fwdangles, saber->s.apos.trBase ); + VectorCopy(fwdangles, saber->s.apos.trBase); saber->s.apos.trTime = level.time; saber->s.apos.trType = TR_INTERPOLATE; - VectorClear( saber->s.apos.trDelta ); + VectorClear(saber->s.apos.trDelta); } } } +qboolean WP_SaberLaunch(gentity_t *self, gentity_t *saber, qboolean thrown) { // FIXME: probably need a debounce time + vec3_t saberMins = {-3.0f, -3.0f, -3.0f}; + vec3_t saberMaxs = {3.0f, 3.0f, 3.0f}; + trace_t trace; -qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown ) -{//FIXME: probably need a debounce time - vec3_t saberMins={-3.0f,-3.0f,-3.0f}; - vec3_t saberMaxs={3.0f,3.0f,3.0f}; - trace_t trace; - - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - { - if ( !WP_ForcePowerUsable( self, FP_SABERTHROW, 20 ) ) - { + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { + if (!WP_ForcePowerUsable(self, FP_SABERTHROW, 20)) { return qfalse; } - } - else - { - if ( !WP_ForcePowerUsable( self, FP_SABERTHROW, 0 ) ) - { + } else { + if (!WP_ForcePowerUsable(self, FP_SABERTHROW, 0)) { return qfalse; } } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't saber throw when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't saber throw when zoomed in or in cinematic return qfalse; } - //make sure it won't start in solid - gi.trace( &trace, self->client->renderInfo.handRPoint, saberMins, saberMaxs, self->client->renderInfo.handRPoint, saber->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid || trace.allsolid ) - { + // make sure it won't start in solid + gi.trace(&trace, self->client->renderInfo.handRPoint, saberMins, saberMaxs, self->client->renderInfo.handRPoint, saber->s.number, MASK_SOLID, G2_NOCOLLIDE, + 0); + if (trace.startsolid || trace.allsolid) { return qfalse; } - //make sure I'm not throwing it on the other side of a door or wall or whatever - gi.trace( &trace, self->currentOrigin, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); - if ( trace.startsolid || trace.allsolid || trace.fraction < 1.0f ) - { + // make sure I'm not throwing it on the other side of a door or wall or whatever + gi.trace(&trace, self->currentOrigin, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); + if (trace.startsolid || trace.allsolid || trace.fraction < 1.0f) { return qfalse; } - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - {//at max skill, the cost increases as keep it out - WP_ForcePowerStart( self, FP_SABERTHROW, 10 ); - } - else - { - WP_ForcePowerStart( self, FP_SABERTHROW, 0 ); + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { // at max skill, the cost increases as keep it out + WP_ForcePowerStart(self, FP_SABERTHROW, 10); + } else { + WP_ForcePowerStart(self, FP_SABERTHROW, 0); } - //draw it + // draw it saber->s.eFlags &= ~EF_NODRAW; saber->svFlags |= SVF_BROADCAST; saber->svFlags &= ~SVF_NOCLIENT; - //place it - VectorCopy( self->client->renderInfo.handRPoint, saber->currentOrigin );//muzzlePoint - VectorCopy( saber->currentOrigin, saber->s.pos.trBase ); + // place it + VectorCopy(self->client->renderInfo.handRPoint, saber->currentOrigin); // muzzlePoint + VectorCopy(saber->currentOrigin, saber->s.pos.trBase); saber->s.pos.trTime = level.time; saber->s.pos.trType = TR_LINEAR; - VectorClear( saber->s.pos.trDelta ); - gi.linkentity( saber ); + VectorClear(saber->s.pos.trDelta); + gi.linkentity(saber); - //spin it - VectorClear( saber->s.apos.trBase ); + // spin it + VectorClear(saber->s.apos.trBase); saber->s.apos.trTime = level.time; saber->s.apos.trType = TR_LINEAR; - if ( self->health > 0 && thrown ) - {//throwing it + if (self->health > 0 && thrown) { // throwing it saber->s.apos.trBase[1] = self->client->ps.viewangles[1]; saber->s.apos.trBase[0] = SABER_PITCH_HACK; + } else { // dropping it + vectoangles(self->client->renderInfo.muzzleDir, saber->s.apos.trBase); } - else - {//dropping it - vectoangles( self->client->renderInfo.muzzleDir, saber->s.apos.trBase ); - } - VectorClear( saber->s.apos.trDelta ); + VectorClear(saber->s.apos.trDelta); - switch ( self->client->ps.forcePowerLevel[FP_SABERTHROW] ) - {//FIXME: make a table? + switch (self->client->ps.forcePowerLevel[FP_SABERTHROW]) { // FIXME: make a table? default: case FORCE_LEVEL_1: saber->s.apos.trDelta[1] = 600; @@ -4161,32 +3428,31 @@ qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown ) break; } - //Take it out of my hand + // Take it out of my hand self->client->ps.saberInFlight = qtrue; self->client->ps.saberEntityState = SES_LEAVING; self->client->ps.saberEntityDist = saberThrowDist[self->client->ps.forcePowerLevel[FP_SABERTHROW]]; self->client->ps.saberThrowTime = level.time; - //if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) + // if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) { - self->client->ps.forcePowerDebounce[FP_SABERTHROW] = level.time + 1000;//so we can keep it out for a minimum amount of time + self->client->ps.forcePowerDebounce[FP_SABERTHROW] = level.time + 1000; // so we can keep it out for a minimum amount of time } - //if it's not active, turn it on + // if it's not active, turn it on self->client->ps.saberActive = qtrue; - //turn on the saber trail + // turn on the saber trail self->client->saberTrail.inAction = qtrue; self->client->saberTrail.duration = 150; - //reset the mins - VectorCopy( saberMins, saber->mins ); - VectorCopy( saberMaxs, saber->maxs ); - saber->contents = 0;//CONTENTS_LIGHTSABER; + // reset the mins + VectorCopy(saberMins, saber->mins); + VectorCopy(saberMaxs, saber->maxs); + saber->contents = 0; // CONTENTS_LIGHTSABER; saber->clipmask = MASK_SOLID | CONTENTS_LIGHTSABER; // remove the ghoul2 sabre model on the player - if ( self->weaponModel >= 0 ) - { + if (self->weaponModel >= 0) { gi.G2API_RemoveGhoul2Model(self->ghoul2, self->weaponModel); self->weaponModel = -1; } @@ -4194,393 +3460,302 @@ qboolean WP_SaberLaunch( gentity_t *self, gentity_t *saber, qboolean thrown ) return qtrue; } -qboolean WP_SaberLose( gentity_t *self, vec3_t throwDir ) -{ - if ( !self || !self->client || self->client->ps.saberEntityNum <= 0 ) - {//WTF?!! We lost it already? +qboolean WP_SaberLose(gentity_t *self, vec3_t throwDir) { + if (!self || !self->client || self->client->ps.saberEntityNum <= 0) { // WTF?!! We lost it already? return qfalse; } gentity_t *dropped = &g_entities[self->client->ps.saberEntityNum]; - if ( !self->client->ps.saberInFlight ) - {//not alreay in air - //make it so we can throw it - self->client->ps.forcePowersKnown |= (1<client->ps.saberInFlight) { // not alreay in air + // make it so we can throw it + self->client->ps.forcePowersKnown |= (1 << FP_SABERTHROW); self->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_1; - //throw it - if ( !WP_SaberLaunch( self, dropped, qfalse ) ) - {//couldn't throw it + // throw it + if (!WP_SaberLaunch(self, dropped, qfalse)) { // couldn't throw it return qfalse; } } - if ( self->client->ps.saberActive ) - {//on - //drop it instantly - WP_SaberDrop( self, dropped ); + if (self->client->ps.saberActive) { // on + // drop it instantly + WP_SaberDrop(self, dropped); } - //optionally give it some thrown velocity - if ( throwDir && !VectorCompare( throwDir, vec3_origin ) ) - { - VectorCopy( throwDir, dropped->s.pos.trDelta ); + // optionally give it some thrown velocity + if (throwDir && !VectorCompare(throwDir, vec3_origin)) { + VectorCopy(throwDir, dropped->s.pos.trDelta); } - //don't pull it back on the next frame - if ( self->NPC ) - { + // don't pull it back on the next frame + if (self->NPC) { self->NPC->last_ucmd.buttons &= ~BUTTON_ATTACK; } return qtrue; } -void WP_SaberCatch( gentity_t *self, gentity_t *saber, qboolean switchToSaber ) -{//FIXME: probably need a debounce time - if ( self->health > 0 && !PM_SaberInBrokenParry( self->client->ps.saberMove ) && self->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - { - //don't draw it +void WP_SaberCatch(gentity_t *self, gentity_t *saber, qboolean switchToSaber) { // FIXME: probably need a debounce time + if (self->health > 0 && !PM_SaberInBrokenParry(self->client->ps.saberMove) && self->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { + // don't draw it saber->s.eFlags |= EF_NODRAW; saber->svFlags &= SVF_BROADCAST; saber->svFlags |= SVF_NOCLIENT; - //take off any gravity stuff if we'd dropped it + // take off any gravity stuff if we'd dropped it saber->s.pos.trType = TR_LINEAR; saber->s.eFlags &= ~EF_BOUNCE_HALF; - //Put it in my hand + // Put it in my hand self->client->ps.saberInFlight = qfalse; self->client->ps.saberEntityState = SES_LEAVING; - //turn off the saber trail + // turn off the saber trail self->client->saberTrail.inAction = qfalse; self->client->saberTrail.duration = 75; - //reset its contents/clipmask - saber->contents = CONTENTS_LIGHTSABER;// | CONTENTS_SHOTCLIP; + // reset its contents/clipmask + saber->contents = CONTENTS_LIGHTSABER; // | CONTENTS_SHOTCLIP; saber->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - //play catch sound - G_Sound( saber, G_SoundIndex( "sound/weapons/saber/saber_catch.wav" ) ); - //FIXME: if an NPC, don't turn it back on if no enemy or enemy is dead... - //if it's not our current weapon, make it our current weapon - if ( self->client->ps.weapon == WP_SABER ) - { - G_CreateG2AttachedWeaponModel( self, self->client->ps.saberModel ); - } - if ( switchToSaber ) - { - if ( self->client->ps.weapon != WP_SABER ) - { - CG_ChangeWeapon( WP_SABER ); - } - else - {//if it's not active, turn it on + // play catch sound + G_Sound(saber, G_SoundIndex("sound/weapons/saber/saber_catch.wav")); + // FIXME: if an NPC, don't turn it back on if no enemy or enemy is dead... + // if it's not our current weapon, make it our current weapon + if (self->client->ps.weapon == WP_SABER) { + G_CreateG2AttachedWeaponModel(self, self->client->ps.saberModel); + } + if (switchToSaber) { + if (self->client->ps.weapon != WP_SABER) { + CG_ChangeWeapon(WP_SABER); + } else { // if it's not active, turn it on self->client->ps.saberActive = qtrue; } } } } - -void WP_SaberReturn( gentity_t *self, gentity_t *saber ) -{ - if ( PM_SaberInBrokenParry( self->client->ps.saberMove ) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { +void WP_SaberReturn(gentity_t *self, gentity_t *saber) { + if (PM_SaberInBrokenParry(self->client->ps.saberMove) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { return; } - if ( self && self->client ) - {//still alive and stuff - //FIXME: when it's returning, flies butt first, but seems to do a lot of damage when going through people... hmm... + if (self && self->client) { // still alive and stuff + // FIXME: when it's returning, flies butt first, but seems to do a lot of damage when going through people... hmm... self->client->ps.saberEntityState = SES_RETURNING; - //turn down the saber trail + // turn down the saber trail self->client->saberTrail.inAction = qfalse; self->client->saberTrail.duration = 75; } - if ( !(saber->s.eFlags&EF_BOUNCE) ) - { + if (!(saber->s.eFlags & EF_BOUNCE)) { saber->s.eFlags |= EF_BOUNCE; saber->bounceCount = 300; } } - -void WP_SaberDrop( gentity_t *self, gentity_t *saber ) -{ +void WP_SaberDrop(gentity_t *self, gentity_t *saber) { saber->s.eFlags &= ~EF_BOUNCE; saber->bounceCount = 0; - //make it fall + // make it fall saber->s.pos.trType = TR_GRAVITY; - //make it bounce some + // make it bounce some saber->s.eFlags |= EF_BOUNCE_HALF; - //make it spin - VectorCopy( saber->currentAngles, saber->s.apos.trBase ); + // make it spin + VectorCopy(saber->currentAngles, saber->s.apos.trBase); saber->s.apos.trType = TR_LINEAR; saber->s.apos.trTime = level.time; - VectorSet( saber->s.apos.trDelta, Q_irand( -300, 300 ), saber->s.apos.trDelta[1], Q_irand( -300, 300 ) ); - if ( !saber->s.apos.trDelta[1] ) - { - saber->s.apos.trDelta[1] = Q_irand( -300, 300 ); + VectorSet(saber->s.apos.trDelta, Q_irand(-300, 300), saber->s.apos.trDelta[1], Q_irand(-300, 300)); + if (!saber->s.apos.trDelta[1]) { + saber->s.apos.trDelta[1] = Q_irand(-300, 300); } - //force it to be ready to return + // force it to be ready to return self->client->ps.saberEntityDist = 0; self->client->ps.saberEntityState = SES_RETURNING; - //turn it off + // turn it off self->client->ps.saberActive = qfalse; - //turn off the saber trail + // turn off the saber trail self->client->saberTrail.inAction = qfalse; self->client->saberTrail.duration = 75; - //play the saber turning off sound - if ( self->client->playerTeam == TEAM_PLAYER ) - { - G_SoundOnEnt( saber, CHAN_AUTO, "sound/weapons/saber/saberoff.wav" ); - } - else - { - G_SoundOnEnt( saber, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav" ); + // play the saber turning off sound + if (self->client->playerTeam == TEAM_PLAYER) { + G_SoundOnEnt(saber, CHAN_AUTO, "sound/weapons/saber/saberoff.wav"); + } else { + G_SoundOnEnt(saber, CHAN_AUTO, "sound/weapons/saber/enemy_saber_off.wav"); } - if ( self->health <= 0 ) - {//owner is dead! - saber->s.time = level.time;//will make us free ourselves after a time + if (self->health <= 0) { // owner is dead! + saber->s.time = level.time; // will make us free ourselves after a time } } - -void WP_SaberPull( gentity_t *self, gentity_t *saber ) -{ - if ( PM_SaberInBrokenParry( self->client->ps.saberMove ) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { +void WP_SaberPull(gentity_t *self, gentity_t *saber) { + if (PM_SaberInBrokenParry(self->client->ps.saberMove) || self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { return; } - if ( self->health > 0 ) - { - //take off gravity + if (self->health > 0) { + // take off gravity saber->s.pos.trType = TR_LINEAR; - //take off bounce + // take off bounce saber->s.eFlags &= EF_BOUNCE_HALF; - //play sound - G_Sound( self, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); + // play sound + G_Sound(self, G_SoundIndex("sound/weapons/force/pull.wav")); } } - // Check if we are throwing it, launch it if needed, update position if needed. -void WP_SaberThrow( gentity_t *self, usercmd_t *ucmd ) -{ - vec3_t saberDiff; - trace_t tr; - //static float SABER_SPEED = 10; +void WP_SaberThrow(gentity_t *self, usercmd_t *ucmd) { + vec3_t saberDiff; + trace_t tr; + // static float SABER_SPEED = 10; gentity_t *saberent; - if ( self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//WTF?!! We lost it? + if (self->client->ps.saberEntityNum <= 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { // WTF?!! We lost it? return; } saberent = &g_entities[self->client->ps.saberEntityNum]; - VectorSubtract( self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff ); + VectorSubtract(self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff); - //is our saber in flight? - if ( !self->client->ps.saberInFlight ) - {//saber is not in flight right now - if ( self->client->ps.weapon != WP_SABER ) - {//don't even have it out + // is our saber in flight? + if (!self->client->ps.saberInFlight) { // saber is not in flight right now + if (self->client->ps.weapon != WP_SABER) { // don't even have it out return; - } - else if ( ucmd->buttons & BUTTON_ALT_ATTACK && !(self->client->ps.pm_flags&PMF_ALT_ATTACK_HELD) ) - {//still holding it, not still holding attack from a previous throw, so throw it. - if ( !(self->client->ps.saberEventFlags&SEF_INWATER) && WP_SaberLaunch( self, saberent, qtrue ) ) - { - if ( self->client && !self->s.number ) - { + } else if (ucmd->buttons & BUTTON_ALT_ATTACK && + !(self->client->ps.pm_flags & PMF_ALT_ATTACK_HELD)) { // still holding it, not still holding attack from a previous throw, so throw it. + if (!(self->client->ps.saberEventFlags & SEF_INWATER) && WP_SaberLaunch(self, saberent, qtrue)) { + if (self->client && !self->s.number) { self->client->sess.missionStats.saberThrownCnt++; } - //need to recalc this because we just moved it - VectorSubtract( self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff ); - } - else - {//couldn't throw it + // need to recalc this because we just moved it + VectorSubtract(self->client->renderInfo.handRPoint, saberent->currentOrigin, saberDiff); + } else { // couldn't throw it return; } - } - else - {//holding it, don't want to throw it, go away. + } else { // holding it, don't want to throw it, go away. return; } - } - else - {//inflight - //is our saber currently on it's way back to us? - if ( self->client->ps.saberEntityState == SES_RETURNING ) - {//see if we're close enough to pick it up - if ( VectorLengthSquared( saberDiff ) <= 256 )//16 squared//G_BoundsOverlap( self->absmin, self->absmax, saberent->absmin, saberent->absmax ) )// - {//caught it - vec3_t axisPoint; - trace_t trace; - VectorCopy( self->currentOrigin, axisPoint ); + } else { // inflight + // is our saber currently on it's way back to us? + if (self->client->ps.saberEntityState == SES_RETURNING) { // see if we're close enough to pick it up + if (VectorLengthSquared(saberDiff) <= 256) // 16 squared//G_BoundsOverlap( self->absmin, self->absmax, saberent->absmin, saberent->absmax ) )// + { // caught it + vec3_t axisPoint; + trace_t trace; + VectorCopy(self->currentOrigin, axisPoint); axisPoint[2] = self->client->renderInfo.handRPoint[2]; - gi.trace( &trace, axisPoint, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); - if ( !trace.startsolid && trace.fraction >= 1.0f ) - {//our hand isn't through a wall - WP_SaberCatch( self, saberent, qtrue ); - NPC_SetAnim( self, SETANIM_TORSO, TORSO_HANDRETRACT1, SETANIM_FLAG_OVERRIDE ); + gi.trace(&trace, axisPoint, vec3_origin, vec3_origin, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0); + if (!trace.startsolid && trace.fraction >= 1.0f) { // our hand isn't through a wall + WP_SaberCatch(self, saberent, qtrue); + NPC_SetAnim(self, SETANIM_TORSO, TORSO_HANDRETRACT1, SETANIM_FLAG_OVERRIDE); } return; } } - if ( saberent->s.pos.trType != TR_STATIONARY ) - {//saber is in flight, lerp it - WP_RunSaber( self, saberent ); - } - else - {//it fell on the ground - if ( self->health <= 0 && level.time > saberent->s.time + 5000 ) - {//make us free ourselves after a time - G_FreeEntity( saberent ); + if (saberent->s.pos.trType != TR_STATIONARY) { // saber is in flight, lerp it + WP_RunSaber(self, saberent); + } else { // it fell on the ground + if (self->health <= 0 && level.time > saberent->s.time + 5000) { // make us free ourselves after a time + G_FreeEntity(saberent); self->client->ps.saberEntityNum = ENTITYNUM_NONE; return; } - if ( (!self->s.number && level.time - saberent->aimDebounceTime > 15000) - || (self->s.number && level.time - saberent->aimDebounceTime > 5000) ) - {//(only for player) been missing for 15 seconds, automagicially return - WP_SaberCatch( self, saberent, qfalse ); + if ((!self->s.number && level.time - saberent->aimDebounceTime > 15000) || + (self->s.number && level.time - saberent->aimDebounceTime > 5000)) { //(only for player) been missing for 15 seconds, automagicially return + WP_SaberCatch(self, saberent, qfalse); return; } } } - //are we still trying to use the saber? - if ( self->client->ps.weapon != WP_SABER ) - {//switched away - if ( !self->client->ps.saberInFlight ) - {//wasn't throwing saber + // are we still trying to use the saber? + if (self->client->ps.weapon != WP_SABER) { // switched away + if (!self->client->ps.saberInFlight) { // wasn't throwing saber return; - } - else if ( saberent->s.pos.trType == TR_LINEAR ) - {//switched away while controlling it, just drop the saber - WP_SaberDrop( self, saberent ); + } else if (saberent->s.pos.trType == TR_LINEAR) { // switched away while controlling it, just drop the saber + WP_SaberDrop(self, saberent); return; - } - else - {//it's on the ground, see if it's inside us (touching) - if ( G_PointInBounds( saberent->currentOrigin, self->absmin, self->absmax ) ) - {//it's in us, pick it up automatically - WP_SaberPull( self, saberent ); + } else { // it's on the ground, see if it's inside us (touching) + if (G_PointInBounds(saberent->currentOrigin, self->absmin, self->absmax)) { // it's in us, pick it up automatically + WP_SaberPull(self, saberent); } } - } - else if ( saberent->s.pos.trType != TR_LINEAR ) - {//weapon is saber and not flying - if ( self->client->ps.saberInFlight ) - {//we dropped it - if ( ucmd->buttons & BUTTON_ATTACK )//|| self->client->ps.weaponstate == WEAPON_RAISING )//ucmd->buttons & BUTTON_ALT_ATTACK || - {//we actively want to pick it up or we just switched to it, so pull it back - gi.trace( &tr, saberent->currentOrigin, saberent->mins, saberent->maxs, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, G2_NOCOLLIDE, 0 ); + } else if (saberent->s.pos.trType != TR_LINEAR) { // weapon is saber and not flying + if (self->client->ps.saberInFlight) { // we dropped it + if (ucmd->buttons & BUTTON_ATTACK) //|| self->client->ps.weaponstate == WEAPON_RAISING )//ucmd->buttons & BUTTON_ALT_ATTACK || + { // we actively want to pick it up or we just switched to it, so pull it back + gi.trace(&tr, saberent->currentOrigin, saberent->mins, saberent->maxs, self->client->renderInfo.handRPoint, self->s.number, MASK_SOLID, + G2_NOCOLLIDE, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 1.0f ) - {//can't pick it up yet, no LOS + if (tr.allsolid || tr.startsolid || tr.fraction < 1.0f) { // can't pick it up yet, no LOS return; } - //clear LOS, pick it up - WP_SaberPull( self, saberent ); - } - else - {//see if it's inside us (touching) - if ( G_PointInBounds( saberent->currentOrigin, self->absmin, self->absmax ) ) - {//it's in us, pick it up automatically - WP_SaberPull( self, saberent ); + // clear LOS, pick it up + WP_SaberPull(self, saberent); + } else { // see if it's inside us (touching) + if (G_PointInBounds(saberent->currentOrigin, self->absmin, self->absmax)) { // it's in us, pick it up automatically + WP_SaberPull(self, saberent); } } } - } - else if ( self->health <= 0 && self->client->ps.saberInFlight ) - {//we died, drop it - WP_SaberDrop( self, saberent ); + } else if (self->health <= 0 && self->client->ps.saberInFlight) { // we died, drop it + WP_SaberDrop(self, saberent); return; - } - else if ( !self->client->ps.saberActive && self->client->ps.saberEntityState != SES_RETURNING ) - {//we turned it off, drop it - WP_SaberDrop( self, saberent ); + } else if (!self->client->ps.saberActive && self->client->ps.saberEntityState != SES_RETURNING) { // we turned it off, drop it + WP_SaberDrop(self, saberent); return; } - //TODO: if deactivate saber in flight, should it drop? + // TODO: if deactivate saber in flight, should it drop? - if ( saberent->s.pos.trType != TR_LINEAR ) - {//don't home + if (saberent->s.pos.trType != TR_LINEAR) { // don't home return; } - float saberDist = VectorLength( saberDiff ); - if ( self->client->ps.saberEntityState == SES_LEAVING ) - {//saber still flying forward - if ( self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2 ) - {//still holding it out - if ( !(ucmd->buttons&BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time ) - {//done throwing, return to me - if ( self->client->ps.saberActive ) - {//still on - WP_SaberReturn( self, saberent ); + float saberDist = VectorLength(saberDiff); + if (self->client->ps.saberEntityState == SES_LEAVING) { // saber still flying forward + if (self->client->ps.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_2) { // still holding it out + if (!(ucmd->buttons & BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time) { // done throwing, return to me + if (self->client->ps.saberActive) { // still on + WP_SaberReturn(self, saberent); } - } - else if ( level.time - self->client->ps.saberThrowTime >= 100 ) - { - if ( WP_ForcePowerAvailable( self, FP_SABERTHROW, 1 ) ) - { - WP_ForcePowerDrain( self, FP_SABERTHROW, 1 ); + } else if (level.time - self->client->ps.saberThrowTime >= 100) { + if (WP_ForcePowerAvailable(self, FP_SABERTHROW, 1)) { + WP_ForcePowerDrain(self, FP_SABERTHROW, 1); self->client->ps.saberThrowTime = level.time; - } - else - {//out of force power, return to me - WP_SaberReturn( self, saberent ); + } else { // out of force power, return to me + WP_SaberReturn(self, saberent); } } - } - else - { - if ( !(ucmd->buttons&BUTTON_ALT_ATTACK) && self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time ) - {//not holding button and has been out at least 1 second, return to me - if ( self->client->ps.saberActive ) - {//still on - WP_SaberReturn( self, saberent ); + } else { + if (!(ucmd->buttons & BUTTON_ALT_ATTACK) && + self->client->ps.forcePowerDebounce[FP_SABERTHROW] < level.time) { // not holding button and has been out at least 1 second, return to me + if (self->client->ps.saberActive) { // still on + WP_SaberReturn(self, saberent); } - } - else if ( level.time - self->client->ps.saberThrowTime > 3000 - || (self->client->ps.forcePowerLevel[FP_SABERTHROW]==FORCE_LEVEL_1&&saberDist>=self->client->ps.saberEntityDist) ) - {//been out too long, or saber throw 1 went too far, return to me - if ( self->client->ps.saberActive ) - {//still on - WP_SaberReturn( self, saberent ); + } else if (level.time - self->client->ps.saberThrowTime > 3000 || + (self->client->ps.forcePowerLevel[FP_SABERTHROW] == FORCE_LEVEL_1 && + saberDist >= self->client->ps.saberEntityDist)) { // been out too long, or saber throw 1 went too far, return to me + if (self->client->ps.saberActive) { // still on + WP_SaberReturn(self, saberent); } } } } - if ( self->client->ps.saberEntityState == SES_RETURNING ) - { - if ( self->client->ps.saberEntityDist > 0 ) - { + if (self->client->ps.saberEntityState == SES_RETURNING) { + if (self->client->ps.saberEntityDist > 0) { self->client->ps.saberEntityDist -= 25; } - if ( self->client->ps.saberEntityDist < 0 ) - { + if (self->client->ps.saberEntityDist < 0) { self->client->ps.saberEntityDist = 0; - } - else if ( saberDist < self->client->ps.saberEntityDist ) - {//if it's coming back to me, never push it away + } else if (saberDist < self->client->ps.saberEntityDist) { // if it's coming back to me, never push it away self->client->ps.saberEntityDist = saberDist; } } } - -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -//SABER BLOCKING============================================================================ -int WP_MissileBlockForBlock( int saberBlock ) -{ - switch( saberBlock ) - { +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +// SABER BLOCKING============================================================================ +int WP_MissileBlockForBlock(int saberBlock) { + switch (saberBlock) { case BLOCKED_UPPER_RIGHT: return BLOCKED_UPPER_RIGHT_PROJ; break; @@ -4600,103 +3775,80 @@ int WP_MissileBlockForBlock( int saberBlock ) return saberBlock; } -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ) -{ - vec3_t diff, fwdangles={0,0,0}, right; +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock) { + vec3_t diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - if ( self->client->ps.weaponstate == WEAPON_DROPPING || - self->client->ps.weaponstate == WEAPON_RAISING ) - {//don't block while changing weapons + if (self->client->ps.weaponstate == WEAPON_DROPPING || self->client->ps.weaponstate == WEAPON_RAISING) { // don't block while changing weapons return; } - //NPCs don't auto-block - if ( !missileBlock && self->s.number != 0 && self->client->ps.saberBlocked != BLOCKED_NONE ) - { + // NPCs don't auto-block + if (!missileBlock && self->s.number != 0 && self->client->ps.saberBlocked != BLOCKED_NONE) { return; } - VectorSubtract( hitloc, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(hitloc, self->client->renderInfo.eyePoint, diff); diff[2] = 0; - VectorNormalize( diff ); + VectorNormalize(diff); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); rightdot = DotProduct(right, diff); zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2]; - //FIXME: take torsoAngles into account? - if ( zdiff > -5 )//0 )//40 ) + // FIXME: take torsoAngles into account? + if (zdiff > -5) // 0 )//40 ) { - if ( rightdot > 0.3 ) - { + if (rightdot > 0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.3 ) - { + } else if (rightdot < -0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else if ( zdiff > -22 )//-20 )//20 ) + } else if (zdiff > -22) //-20 )//20 ) { - if ( zdiff < -10 )//30 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - //NPC should duck, but NPC should never get here + if (zdiff < -10) // 30 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck + // NPC should duck, but NPC should never get here } - if ( rightdot > 0.1 ) - { + if (rightdot > 0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.1 ) - { + } else if (rightdot < -0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - {//FIXME: this looks really weird if the shot is too low! + } else { // FIXME: this looks really weird if the shot is too low! self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else - { - if ( rightdot >= 0 ) - { + } else { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } #ifndef FINAL_BUILD - if ( d_saberCombat->integer ) - { - if ( !self->s.number ) - { - gi.Printf( "EyeZ: %4.2f HitZ: %4.2f zdiff: %4.2f rdot: %4.2f\n", self->client->renderInfo.eyePoint[2], hitloc[2], zdiff, rightdot ); - switch ( self->client->ps.saberBlocked ) - { + if (d_saberCombat->integer) { + if (!self->s.number) { + gi.Printf("EyeZ: %4.2f HitZ: %4.2f zdiff: %4.2f rdot: %4.2f\n", self->client->renderInfo.eyePoint[2], hitloc[2], zdiff, rightdot); + switch (self->client->ps.saberBlocked) { case BLOCKED_TOP: - gi.Printf( "BLOCKED_TOP\n" ); + gi.Printf("BLOCKED_TOP\n"); break; case BLOCKED_UPPER_RIGHT: - gi.Printf( "BLOCKED_UPPER_RIGHT\n" ); + gi.Printf("BLOCKED_UPPER_RIGHT\n"); break; case BLOCKED_UPPER_LEFT: - gi.Printf( "BLOCKED_UPPER_LEFT\n" ); + gi.Printf("BLOCKED_UPPER_LEFT\n"); break; case BLOCKED_LOWER_RIGHT: - gi.Printf( "BLOCKED_LOWER_RIGHT\n" ); + gi.Printf("BLOCKED_LOWER_RIGHT\n"); break; case BLOCKED_LOWER_LEFT: - gi.Printf( "BLOCKED_LOWER_LEFT\n" ); + gi.Printf("BLOCKED_LOWER_LEFT\n"); break; default: break; @@ -4705,49 +3857,38 @@ void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlo } #endif - if ( missileBlock ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (missileBlock) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } - if ( self->client->ps.saberBlocked != BLOCKED_NONE ) - { - int parryReCalcTime = Jedi_ReCalcParryTime( self, EVASION_PARRY ); - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + if (self->client->ps.saberBlocked != BLOCKED_NONE) { + int parryReCalcTime = Jedi_ReCalcParryTime(self, EVASION_PARRY); + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } } } -void WP_SaberBlock( gentity_t *saber, vec3_t hitloc, qboolean missileBlock ) -{ +void WP_SaberBlock(gentity_t *saber, vec3_t hitloc, qboolean missileBlock) { gentity_t *playerent; - vec3_t diff, fwdangles={0,0,0}, right; + vec3_t diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - if (saber && saber->owner) - { + if (saber && saber->owner) { playerent = saber->owner; - if (!playerent->client) - { + if (!playerent->client) { return; } - if ( playerent->client->ps.weaponstate == WEAPON_DROPPING || - playerent->client->ps.weaponstate == WEAPON_RAISING ) - {//don't block while changing weapons + if (playerent->client->ps.weaponstate == WEAPON_DROPPING || playerent->client->ps.weaponstate == WEAPON_RAISING) { // don't block while changing weapons return; } - } - else - { // Bad entity passed. + } else { // Bad entity passed. return; } - //temporarily disabling auto-blocking for NPCs... - if ( !missileBlock && playerent->s.number != 0 && playerent->client->ps.saberBlocked != BLOCKED_NONE ) - { + // temporarily disabling auto-blocking for NPCs... + if (!missileBlock && playerent->s.number != 0 && playerent->client->ps.saberBlocked != BLOCKED_NONE) { return; } @@ -4756,40 +3897,27 @@ void WP_SaberBlock( gentity_t *saber, vec3_t hitloc, qboolean missileBlock ) fwdangles[1] = playerent->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); - rightdot = DotProduct(right, diff) + Q_flrand(-0.2f,0.2f); - zdiff = hitloc[2] - playerent->currentOrigin[2] + Q_irand(-8,8); + rightdot = DotProduct(right, diff) + Q_flrand(-0.2f, 0.2f); + zdiff = hitloc[2] - playerent->currentOrigin[2] + Q_irand(-8, 8); // Figure out what quadrant the block was in. - if (zdiff > 24) - { // Attack from above - if (Q_irand(0,1)) - { + if (zdiff > 24) { // Attack from above + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_TOP; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; } - } - else if (zdiff > 13) - { // The upper half has three viable blocks... - if (rightdot > 0.25) - { // In the right quadrant... - if (Q_irand(0,1)) - { + } else if (zdiff > 13) { // The upper half has three viable blocks... + if (rightdot > 0.25) { // In the right quadrant... + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } - } - else - { - switch(Q_irand(0,3)) - { + } else { + switch (Q_irand(0, 3)) { case 0: playerent->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; break; @@ -4802,443 +3930,358 @@ void WP_SaberBlock( gentity_t *saber, vec3_t hitloc, qboolean missileBlock ) break; } } - } - else - { // The lower half is a bit iffy as far as block coverage. Pick one of the "low" ones at random. - if (Q_irand(0,1)) - { + } else { // The lower half is a bit iffy as far as block coverage. Pick one of the "low" ones at random. + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - if ( missileBlock ) - { - playerent->client->ps.saberBlocked = WP_MissileBlockForBlock( playerent->client->ps.saberBlocked ); + if (missileBlock) { + playerent->client->ps.saberBlocked = WP_MissileBlockForBlock(playerent->client->ps.saberBlocked); } } -void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) -{ - float dist; - gentity_t *ent, *incoming = NULL; - gentity_t *entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - int i, e; - float closestDist, radius = 256; - vec3_t forward, dir, missile_dir, fwdangles = {0}; - trace_t trace; - vec3_t traceTo, entDir; - - - if ( self->client->ps.weapon != WP_SABER ) - { +void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd) { + float dist; + gentity_t *ent, *incoming = NULL; + gentity_t *entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + int i, e; + float closestDist, radius = 256; + vec3_t forward, dir, missile_dir, fwdangles = {0}; + trace_t trace; + vec3_t traceTo, entDir; + + if (self->client->ps.weapon != WP_SABER) { return; } - if ( self->client->ps.saberInFlight ) - { + if (self->client->ps.saberInFlight) { return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_LIGHTNING)) { // can't block while zapping return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & (1 << FP_PUSH)) { // can't block while shoving return; } - if ( self->client->ps.forcePowersActive&(1<client->ps.forcePowersActive & + (1 << FP_GRIP)) { // can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) return; } - if ( self->health <= 0 ) - {//dead don't try to block (NOTE: actual deflection happens in missile code) + if (self->health <= 0) { // dead don't try to block (NOTE: actual deflection happens in missile code) return; } - if ( PM_InKnockDown( &self->client->ps ) ) - {//can't block when knocked down + if (PM_InKnockDown(&self->client->ps)) { // can't block when knocked down return; } - if ( !self->client->ps.saberLength ) - { - if ( self->s.number == 0 ) - {//player doesn't auto-activate + if (!self->client->ps.saberLength) { + if (self->s.number == 0) { // player doesn't auto-activate return; } } - if ( !self->s.number ) - {//don't do this if already attacking! - if ( ucmd->buttons & BUTTON_ATTACK - || PM_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || PM_SaberInTransitionAny( self->client->ps.saberMove )) - { + if (!self->s.number) { // don't do this if already attacking! + if (ucmd->buttons & BUTTON_ATTACK || PM_SaberInAttack(self->client->ps.saberMove) || PM_SaberInSpecialAttack(self->client->ps.torsoAnim) || + PM_SaberInTransitionAny(self->client->ps.saberMove)) { return; } } - if ( self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) + if (self->client->ps.forcePowerDebounce[FP_SABER_DEFENSE] > + level.time) { // can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) return; } - if ( !self->s.number && !g_saberAutoBlocking->integer && self->client->ps.saberBlockingTimes.number && !g_saberAutoBlocking->integer && self->client->ps.saberBlockingTime < level.time) { return; } fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = self->currentOrigin[i] - radius; maxs[i] = self->currentOrigin[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); closestDist = radius; - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; if (ent->owner == self) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType != ET_MISSILE && !(ent->s.eFlags&EF_MISSILE_STICK) ) - {//not a normal projectile - if ( ent->client || ent->s.weapon != WP_SABER ) - {//FIXME: wake up bad guys? + if (ent->s.eType != ET_MISSILE && !(ent->s.eFlags & EF_MISSILE_STICK)) { // not a normal projectile + if (ent->client || ent->s.weapon != WP_SABER) { // FIXME: wake up bad guys? continue; } - if ( ent->s.eFlags & EF_NODRAW ) - { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber - //FIXME: what about general objects that are small in size- like rocks, etc... + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber + // FIXME: what about general objects that are small in size- like rocks, etc... continue; } - //a lightsaber.. make sure it's on and inFlight - if ( !ent->owner || !ent->owner->client ) - { + // a lightsaber.. make sure it's on and inFlight + if (!ent->owner || !ent->owner->client) { continue; } - if ( !ent->owner->client->ps.saberInFlight ) - {//not in flight + if (!ent->owner->client->ps.saberInFlight) { // not in flight continue; } - if ( ent->owner->client->ps.saberLength <= 0 ) - {//not on + if (ent->owner->client->ps.saberLength <= 0) { // not on continue; } - if ( ent->owner->health <= 0 && !g_saberRealisticCombat->integer ) - {//it's not doing damage, so ignore it + if (ent->owner->health <= 0 && !g_saberRealisticCombat->integer) { // it's not doing damage, so ignore it continue; } - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && !self->s.number ) - {//nothing you can do with a stationary missile if you're the player + } else { + if (ent->s.pos.trType == TR_STATIONARY && !self->s.number) { // nothing you can do with a stationary missile if you're the player continue; } } - float dot1, dot2; - //see if they're in front of me - VectorSubtract( ent->currentOrigin, self->currentOrigin, dir ); - dist = VectorNormalize( dir ); - //FIXME: handle detpacks, proximity mines and tripmines - if ( ent->s.weapon == WP_THERMAL ) - {//thermal detonator! - if ( self->NPC && dist < ent->splashRadius ) - { - if ( dist < ent->splashRadius && - ent->nextthink < level.time + 600 && - ent->count && - self->client->ps.groundEntityNum != ENTITYNUM_NONE && - (ent->s.pos.trType == TR_STATIONARY|| - ent->s.pos.trType == TR_INTERPOLATE|| - (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE|| - !WP_ForcePowerUsable( self, FP_PUSH, 0 )) ) - {//TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and about to blow up, or I don't have force-push so force-jump! - //FIXME: sometimes this might make me just jump into it...? + float dot1, dot2; + // see if they're in front of me + VectorSubtract(ent->currentOrigin, self->currentOrigin, dir); + dist = VectorNormalize(dir); + // FIXME: handle detpacks, proximity mines and tripmines + if (ent->s.weapon == WP_THERMAL) { // thermal detonator! + if (self->NPC && dist < ent->splashRadius) { + if (dist < ent->splashRadius && ent->nextthink < level.time + 600 && ent->count && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (ent->s.pos.trType == TR_STATIONARY || ent->s.pos.trType == TR_INTERPOLATE || + (dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE || + !WP_ForcePowerUsable(self, FP_PUSH, 0))) { // TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and + // about to blow up, or I don't have force-push so force-jump! + // FIXME: sometimes this might make me just jump into it...? self->client->ps.forceJumpCharge = 480; - } - else - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( self, qfalse ); + } else { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(self, qfalse); } } continue; - } - else if ( ent->splashDamage && ent->splashRadius ) - {//exploding missile - //FIXME: handle tripmines and detpacks somehow... + } else if (ent->splashDamage && ent->splashRadius) { // exploding missile + // FIXME: handle tripmines and detpacks somehow... // maybe do a force-gesture that makes them explode? // But what if we're within it's splashradius? - if ( !self->s.number ) - {//players don't auto-handle these at all + if (!self->s.number) { // players don't auto-handle these at all continue; - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//a placed explosive like a tripmine or detpack - if ( InFOV( ent->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90 ) ) - {//in front of me - if ( G_ClearLOS( self, ent ) ) - {//can see it + } else { + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // a placed explosive like a tripmine or detpack + if (InFOV(ent->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90)) { // in front of me + if (G_ClearLOS(self, ent)) { // can see it vec3_t throwDir; - //make the gesture - ForceThrow( self, qfalse ); - //take it off the wall and toss it + // make the gesture + ForceThrow(self, qfalse); + // take it off the wall and toss it ent->s.pos.trType = TR_GRAVITY; ent->s.eType = ET_MISSILE; ent->s.eFlags &= ~EF_MISSILE_STICK; ent->s.eFlags |= EF_BOUNCE_HALF; - AngleVectors( ent->currentAngles, throwDir, NULL, NULL ); - VectorMA( ent->currentOrigin, ent->maxs[0]+4, throwDir, ent->currentOrigin ); - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); - VectorScale( throwDir, 300, ent->s.pos.trDelta ); + AngleVectors(ent->currentAngles, throwDir, NULL, NULL); + VectorMA(ent->currentOrigin, ent->maxs[0] + 4, throwDir, ent->currentOrigin); + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); + VectorScale(throwDir, 300, ent->s.pos.trDelta); ent->s.pos.trDelta[2] += 150; - VectorMA( ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta ); - ent->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( ent->currentOrigin, ent->s.pos.trBase ); + VectorMA(ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta); + ent->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(ent->currentOrigin, ent->s.pos.trBase); ent->owner = self; // make it explode, but with less damage ent->splashDamage /= 3; ent->splashRadius /= 3; ent->e_ThinkFunc = thinkF_WP_Explode; - ent->nextthink = level.time + Q_irand( 500, 3000 ); + ent->nextthink = level.time + Q_irand(500, 3000); } } - } - else if ( dist < ent->splashRadius && - self->client->ps.groundEntityNum != ENTITYNUM_NONE && - (DotProduct( dir, forward ) < SABER_REFLECT_MISSILE_CONE|| - !WP_ForcePowerUsable( self, FP_PUSH, 0 )) ) - {//NPCs try to evade it + } else if (dist < ent->splashRadius && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (DotProduct(dir, forward) < SABER_REFLECT_MISSILE_CONE || !WP_ForcePowerUsable(self, FP_PUSH, 0))) { // NPCs try to evade it self->client->ps.forceJumpCharge = 480; - } - else - {//else, try to force-throw it away - //FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( self, qfalse ); + } else { // else, try to force-throw it away + // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(self, qfalse); } } - //otherwise, can't block it, so we're screwed + // otherwise, can't block it, so we're screwed continue; } - if ( ent->s.weapon != WP_SABER ) - {//only block shots coming from behind - if ( (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE ) + if (ent->s.weapon != WP_SABER) { // only block shots coming from behind + if ((dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE) continue; - } - else if ( !self->s.number ) - {//player never auto-blocks thrown sabers + } else if (!self->s.number) { // player never auto-blocks thrown sabers continue; - }//NPCs always try to block sabers coming from behind! + } // NPCs always try to block sabers coming from behind! - //see if they're heading towards me - VectorCopy( ent->s.pos.trDelta, missile_dir ); - VectorNormalize( missile_dir ); - if ( (dot2 = DotProduct( dir, missile_dir )) > 0 ) + // see if they're heading towards me + VectorCopy(ent->s.pos.trDelta, missile_dir); + VectorNormalize(missile_dir); + if ((dot2 = DotProduct(dir, missile_dir)) > 0) continue; - //FIXME: must have a clear trace to me, too... - if ( dist < closestDist ) - { - VectorCopy( self->currentOrigin, traceTo ); + // FIXME: must have a clear trace to me, too... + if (dist < closestDist) { + VectorCopy(self->currentOrigin, traceTo); traceTo[2] = self->absmax[2] - 4; - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//okay, try one more check - VectorNormalize2( ent->s.pos.trDelta, entDir ); - VectorMA( ent->currentOrigin, radius, entDir, traceTo ); - gi.trace( &trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//can't hit me, ignore it + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // okay, try one more check + VectorNormalize2(ent->s.pos.trDelta, entDir); + VectorMA(ent->currentOrigin, radius, entDir, traceTo); + gi.trace(&trace, ent->currentOrigin, ent->mins, ent->maxs, traceTo, ent->s.number, ent->clipmask, G2_NOCOLLIDE, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // can't hit me, ignore it continue; } } - if ( self->s.number != 0 ) - {//An NPC - if ( self->NPC && !self->enemy && ent->owner ) - { - if ( ent->owner->health >= 0 && (!ent->owner->client || ent->owner->client->playerTeam != self->client->playerTeam) ) - { - G_SetEnemy( self, ent->owner ); + if (self->s.number != 0) { // An NPC + if (self->NPC && !self->enemy && ent->owner) { + if (ent->owner->health >= 0 && (!ent->owner->client || ent->owner->client->playerTeam != self->client->playerTeam)) { + G_SetEnemy(self, ent->owner); } } } - //FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box (+/-saberLength?), don't try to deflect unless it does? + // FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box + // (+/-saberLength?), don't try to deflect unless it does? closestDist = dist; incoming = ent; } } - if ( incoming ) - { - if ( self->NPC && !G_ControlledByPlayer( self ) ) - { - if ( Jedi_WaitingAmbush( self ) ) - { - Jedi_Ambush( self ); + if (incoming) { + if (self->NPC && !G_ControlledByPlayer(self)) { + if (Jedi_WaitingAmbush(self)) { + Jedi_Ambush(self); } - if ( Jedi_SaberBlockGo( self, &self->NPC->last_ucmd, NULL, NULL, incoming ) != EVASION_NONE ) - {//make sure to turn on your saber if it's not on + if (Jedi_SaberBlockGo(self, &self->NPC->last_ucmd, NULL, NULL, incoming) != EVASION_NONE) { // make sure to turn on your saber if it's not on self->client->ps.saberActive = qtrue; } - } - else//player + } else // player { - WP_SaberBlockNonRandom( self, incoming->currentOrigin, qtrue ); - if ( incoming->owner && incoming->owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER) )//keep enemy jedi over shooters + WP_SaberBlockNonRandom(self, incoming->currentOrigin, qtrue); + if (incoming->owner && incoming->owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER)) // keep enemy jedi over shooters { self->enemy = incoming->owner; - NPC_SetLookTarget( self, incoming->owner->s.number, level.time+1000 ); + NPC_SetLookTarget(self, incoming->owner->s.number, level.time + 1000); } } } } +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ +// GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ -//GENERAL SABER============================================================================ - - -void WP_SetSaberMove(gentity_t *self, short blocked) -{ - self->client->ps.saberBlocked = blocked; -} +void WP_SetSaberMove(gentity_t *self, short blocked) { self->client->ps.saberBlocked = blocked; } -extern void CG_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ); -void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ) -{ - //float swap; - float minsize = 16; +extern void CG_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha); +void WP_SaberUpdate(gentity_t *self, usercmd_t *ucmd) { + // float swap; + float minsize = 16; - if(0)// if ( self->s.number != 0 ) - {//for now only the player can do this // not anymore + if (0) // if ( self->s.number != 0 ) + { // for now only the player can do this // not anymore return; } - if ( !self->client ) - { + if (!self->client) { return; } - if ( self->client->ps.saberEntityNum < 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD ) - {//never got one + if (self->client->ps.saberEntityNum < 0 || self->client->ps.saberEntityNum >= ENTITYNUM_WORLD) { // never got one return; } // Check if we are throwing it, launch it if needed, update position if needed. WP_SaberThrow(self, ucmd); - - //vec3_t saberloc; - //vec3_t sabermins={-8,-8,-8}, sabermaxs={8,8,8}; + // vec3_t saberloc; + // vec3_t sabermins={-8,-8,-8}, sabermaxs={8,8,8}; gentity_t *saberent; - if (self->client->ps.saberEntityNum <= 0) - {//WTF?!! We lost it? + if (self->client->ps.saberEntityNum <= 0) { // WTF?!! We lost it? return; } saberent = &g_entities[self->client->ps.saberEntityNum]; - //FIXME: Based on difficulty level/jedi saber combat skill, make this bounding box fatter/smaller - if ( self->client->ps.saberBlocked != BLOCKED_NONE ) - {//we're blocking, increase min size + // FIXME: Based on difficulty level/jedi saber combat skill, make this bounding box fatter/smaller + if (self->client->ps.saberBlocked != BLOCKED_NONE) { // we're blocking, increase min size minsize = 32; } - //is our saber in flight? - if ( !self->client->ps.saberInFlight ) - { // It isn't, which means we can update its position as we will. - if ( !self->client->ps.saberActive || PM_InKnockDown( &self->client->ps ) ) - {//can't block if saber isn't on + // is our saber in flight? + if (!self->client->ps.saberInFlight) { // It isn't, which means we can update its position as we will. + if (!self->client->ps.saberActive || PM_InKnockDown(&self->client->ps)) { // can't block if saber isn't on VectorClear(saberent->mins); VectorClear(saberent->maxs); G_SetOrigin(saberent, self->currentOrigin); - } - else if ( self->client->ps.saberBlocking == BLK_TIGHT || self->client->ps.saberBlocking == BLK_WIDE ) - {//FIXME: keep bbox in front of player, even when wide? - vec3_t saberOrg; - if ( ( (self->s.number&&!Jedi_SaberBusy(self)&&!g_saberRealisticCombat->integer) || (self->s.number == 0 && self->client->ps.saberBlocking == BLK_WIDE && (g_saberAutoBlocking->integer||self->client->ps.saberBlockingTime>level.time)) ) - && self->client->ps.weaponTime <= 0 ) - {//full-size blocking for non-attacking player with g_saberAutoBlocking on - vec3_t saberang={0,0,0}, fwd, sabermins={-8,-8,-8}, sabermaxs={8,8,8}; + } else if (self->client->ps.saberBlocking == BLK_TIGHT || + self->client->ps.saberBlocking == BLK_WIDE) { // FIXME: keep bbox in front of player, even when wide? + vec3_t saberOrg; + if (((self->s.number && !Jedi_SaberBusy(self) && !g_saberRealisticCombat->integer) || + (self->s.number == 0 && self->client->ps.saberBlocking == BLK_WIDE && + (g_saberAutoBlocking->integer || self->client->ps.saberBlockingTime > level.time))) && + self->client->ps.weaponTime <= 0) { // full-size blocking for non-attacking player with g_saberAutoBlocking on + vec3_t saberang = {0, 0, 0}, fwd, sabermins = {-8, -8, -8}, sabermaxs = {8, 8, 8}; saberang[YAW] = self->client->ps.viewangles[YAW]; - AngleVectors( saberang, fwd, NULL, NULL ); + AngleVectors(saberang, fwd, NULL, NULL); - VectorMA( self->currentOrigin, 12, fwd, saberOrg ); + VectorMA(self->currentOrigin, 12, fwd, saberOrg); - VectorAdd( self->mins, sabermins, saberent->mins ); - VectorAdd( self->maxs, sabermaxs, saberent->maxs ); + VectorAdd(self->mins, sabermins, saberent->mins); + VectorAdd(self->maxs, sabermaxs, saberent->maxs); saberent->contents = CONTENTS_LIGHTSABER; - G_SetOrigin( saberent, saberOrg ); - } - else - { - vec3_t saberTip; - VectorMA( self->client->renderInfo.muzzlePoint, self->client->ps.saberLength, self->client->renderInfo.muzzleDir, saberTip ); - VectorMA( self->client->renderInfo.muzzlePoint, self->client->ps.saberLength*0.5, self->client->renderInfo.muzzleDir, saberOrg ); - for ( int i = 0; i < 3; i++ ) - { - if ( saberTip[i] > self->client->renderInfo.muzzlePoint[i] ) - { - saberent->maxs[i] = saberTip[i] - saberOrg[i] + 8;//self->client->renderInfo.muzzlePoint[i]; + G_SetOrigin(saberent, saberOrg); + } else { + vec3_t saberTip; + VectorMA(self->client->renderInfo.muzzlePoint, self->client->ps.saberLength, self->client->renderInfo.muzzleDir, saberTip); + VectorMA(self->client->renderInfo.muzzlePoint, self->client->ps.saberLength * 0.5, self->client->renderInfo.muzzleDir, saberOrg); + for (int i = 0; i < 3; i++) { + if (saberTip[i] > self->client->renderInfo.muzzlePoint[i]) { + saberent->maxs[i] = saberTip[i] - saberOrg[i] + 8; // self->client->renderInfo.muzzlePoint[i]; saberent->mins[i] = self->client->renderInfo.muzzlePoint[i] - saberOrg[i] - 8; - } - else //if ( saberTip[i] < self->client->renderInfo.muzzlePoint[i] ) + } else // if ( saberTip[i] < self->client->renderInfo.muzzlePoint[i] ) { saberent->maxs[i] = self->client->renderInfo.muzzlePoint[i] - saberOrg[i] + 8; - saberent->mins[i] = saberTip[i] - saberOrg[i] - 8;//self->client->renderInfo.muzzlePoint[i]; + saberent->mins[i] = saberTip[i] - saberOrg[i] - 8; // self->client->renderInfo.muzzlePoint[i]; } - if ( self->client->ps.weaponTime > 0 || self->s.number || g_saberAutoBlocking->integer || self->client->ps.saberBlockingTime > level.time ) - {//if attacking or blocking (or an NPC), inflate to a minimum size - if ( saberent->maxs[i] < minsize ) - { + if (self->client->ps.weaponTime > 0 || self->s.number || g_saberAutoBlocking->integer || + self->client->ps.saberBlockingTime > level.time) { // if attacking or blocking (or an NPC), inflate to a minimum size + if (saberent->maxs[i] < minsize) { saberent->maxs[i] = minsize; } - if ( saberent->mins[i] > -minsize ) - { + if (saberent->mins[i] > -minsize) { saberent->mins[i] = -minsize; } } } saberent->contents = CONTENTS_LIGHTSABER; - G_SetOrigin( saberent, saberOrg ); + G_SetOrigin(saberent, saberOrg); } } /* @@ -5297,280 +4340,212 @@ void WP_SaberUpdate( gentity_t *self, usercmd_t *ucmd ) G_SetOrigin( saberent, saberloc); } */ - else - { // Otherwise there is no blocking possible. + else { // Otherwise there is no blocking possible. VectorClear(saberent->mins); VectorClear(saberent->maxs); G_SetOrigin(saberent, self->currentOrigin); } saberent->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; gi.linkentity(saberent); - } - else - { - WP_SaberInFlightReflectCheck( self, ucmd ); + } else { + WP_SaberInFlightReflectCheck(self, ucmd); } #ifndef FINAL_BUILD - if ( d_saberCombat->integer > 2 ) - { - CG_CubeOutline( saberent->absmin, saberent->absmax, 50, WPDEBUG_SaberColor( self->client->ps.saberColor ), 1 ); + if (d_saberCombat->integer > 2) { + CG_CubeOutline(saberent->absmin, saberent->absmax, 50, WPDEBUG_SaberColor(self->client->ps.saberColor), 1); } #endif } - -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -//OTHER JEDI POWERS========================================================================= -extern gentity_t *TossClientItems( gentity_t *self ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -void WP_DropWeapon( gentity_t *dropper, vec3_t velocity ) -{ - if ( !dropper || !dropper->client ) - { +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +// OTHER JEDI POWERS========================================================================= +extern gentity_t *TossClientItems(gentity_t *self); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +void WP_DropWeapon(gentity_t *dropper, vec3_t velocity) { + if (!dropper || !dropper->client) { return; } - int replaceWeap = WP_NONE; + int replaceWeap = WP_NONE; int oldWeap = dropper->s.weapon; - gentity_t *weapon = TossClientItems( dropper ); - if ( oldWeap == WP_THERMAL && dropper->NPC ) - {//Hmm, maybe all NPCs should go into melee? Not too many, though, or they mob you and look silly + gentity_t *weapon = TossClientItems(dropper); + if (oldWeap == WP_THERMAL && dropper->NPC) { // Hmm, maybe all NPCs should go into melee? Not too many, though, or they mob you and look silly replaceWeap = WP_MELEE; } - if (dropper->ghoul2.IsValid()&& dropper->weaponModel >= 0 ) - { - gi.G2API_RemoveGhoul2Model( dropper->ghoul2, dropper->weaponModel ); + if (dropper->ghoul2.IsValid() && dropper->weaponModel >= 0) { + gi.G2API_RemoveGhoul2Model(dropper->ghoul2, dropper->weaponModel); dropper->weaponModel = -1; } - //FIXME: does this work on the player? - dropper->client->ps.stats[STAT_WEAPONS] |= ( 1 << replaceWeap ); - if ( !dropper->s.number ) - { - if ( oldWeap == WP_THERMAL ) - { + // FIXME: does this work on the player? + dropper->client->ps.stats[STAT_WEAPONS] |= (1 << replaceWeap); + if (!dropper->s.number) { + if (oldWeap == WP_THERMAL) { dropper->client->ps.ammo[weaponData[oldWeap].ammoIndex] -= weaponData[oldWeap].energyPerShot; + } else { + dropper->client->ps.stats[STAT_WEAPONS] &= ~(1 << oldWeap); } - else - { - dropper->client->ps.stats[STAT_WEAPONS] &= ~( 1 << oldWeap ); - } - CG_ChangeWeapon( replaceWeap ); - } - else - { - dropper->client->ps.stats[STAT_WEAPONS] &= ~( 1 << oldWeap ); + CG_ChangeWeapon(replaceWeap); + } else { + dropper->client->ps.stats[STAT_WEAPONS] &= ~(1 << oldWeap); } - ChangeWeapon( dropper, replaceWeap ); + ChangeWeapon(dropper, replaceWeap); dropper->s.weapon = replaceWeap; - if ( dropper->NPC ) - { + if (dropper->NPC) { dropper->NPC->last_ucmd.weapon = replaceWeap; } - if ( weapon != NULL && velocity && !VectorCompare( velocity, vec3_origin ) ) - {//weapon should have a direction to it's throw - VectorScale( velocity, 3, weapon->s.pos.trDelta );//NOTE: Presumes it is moving already...? - if ( weapon->s.pos.trDelta[2] < 150 ) - {//this is presuming you don't want them to drop the weapon down on you... + if (weapon != NULL && velocity && !VectorCompare(velocity, vec3_origin)) { // weapon should have a direction to it's throw + VectorScale(velocity, 3, weapon->s.pos.trDelta); // NOTE: Presumes it is moving already...? + if (weapon->s.pos.trDelta[2] < 150) { // this is presuming you don't want them to drop the weapon down on you... weapon->s.pos.trDelta[2] = 150; } - //FIXME: gets stuck inside it's former owner... + // FIXME: gets stuck inside it's former owner... weapon->forcePushTime = level.time + 600; // let the push effect last for 600 ms } } -void WP_KnockdownTurret( gentity_t *self, gentity_t *pas ) -{ - //knock it over - VectorCopy( pas->currentOrigin, pas->s.pos.trBase ); +void WP_KnockdownTurret(gentity_t *self, gentity_t *pas) { + // knock it over + VectorCopy(pas->currentOrigin, pas->s.pos.trBase); pas->s.pos.trType = TR_LINEAR_STOP; pas->s.pos.trDuration = 250; pas->s.pos.trTime = level.time; - pas->s.pos.trDelta[2] = ( 12.0f / ( pas->s.pos.trDuration * 0.001f ) ); + pas->s.pos.trDelta[2] = (12.0f / (pas->s.pos.trDuration * 0.001f)); - VectorCopy( pas->currentAngles, pas->s.apos.trBase ); + VectorCopy(pas->currentAngles, pas->s.apos.trBase); pas->s.apos.trType = TR_LINEAR_STOP; pas->s.apos.trDuration = 250; pas->s.apos.trTime = level.time; - //FIXME: pick pitch/roll that always tilts it directly away from pusher - pas->s.apos.trDelta[PITCH] = ( 100.0f / ( pas->s.apos.trDuration * 0.001f ) ); + // FIXME: pick pitch/roll that always tilts it directly away from pusher + pas->s.apos.trDelta[PITCH] = (100.0f / (pas->s.apos.trDuration * 0.001f)); - //kill it + // kill it pas->count = 0; pas->nextthink = -1; - G_Sound( pas, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); - //push effect? + G_Sound(pas, G_SoundIndex("sound/chars/turret/shutdown.wav")); + // push effect? pas->forcePushTime = level.time + 600; // let the push effect last for 600 ms } -void WP_ResistForcePush( gentity_t *self, gentity_t *pusher, qboolean noPenalty ) -{ +void WP_ResistForcePush(gentity_t *self, gentity_t *pusher, qboolean noPenalty) { int parts; qboolean runningResist = qfalse; - if ( !self || self->health <= 0 || !self->client || !pusher || !pusher->client ) - { + if (!self || self->health <= 0 || !self->client || !pusher || !pusher->client) { return; } - if ( (!self->s.number || self->client->NPC_class == CLASS_DESANN || self->client->NPC_class == CLASS_LUKE) - && (VectorLengthSquared( self->client->ps.velocity ) > 10000 || self->client->ps.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 ) ) - { + if ((!self->s.number || self->client->NPC_class == CLASS_DESANN || self->client->NPC_class == CLASS_LUKE) && + (VectorLengthSquared(self->client->ps.velocity) > 10000 || self->client->ps.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || + self->client->ps.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3)) { runningResist = qtrue; } - if ( !runningResist - && self->client->ps.groundEntityNum != ENTITYNUM_NONE - && !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) - && !PM_CrouchAnim( self->client->ps.legsAnim )) - {//if on a surface and not in a spin or flip, play full body resist + if (!runningResist && self->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(self->client->ps.legsAnim) && + !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && !PM_InKnockDown(&self->client->ps) && + !PM_CrouchAnim(self->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body resist parts = SETANIM_BOTH; - } - else - {//play resist just in torso + } else { // play resist just in torso parts = SETANIM_TORSO; } - NPC_SetAnim( self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( !noPenalty ) - { - if ( !runningResist ) - { - VectorClear( self->client->ps.velocity ); - //still stop them from attacking or moving for a bit, though - //FIXME: maybe push just a little (like, slide)? + NPC_SetAnim(self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (!noPenalty) { + if (!runningResist) { + VectorClear(self->client->ps.velocity); + // still stop them from attacking or moving for a bit, though + // FIXME: maybe push just a little (like, slide)? self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } self->client->ps.pm_time = self->client->ps.weaponTime; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //play the full body push effect on me + // play the full body push effect on me self->forcePushTime = level.time + 600; // let the push effect last for 600 ms - } - else - { + } else { self->client->ps.weaponTime = 600; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } } - //play my force push effect on my hand + // play my force push effect on my hand self->client->ps.powerups[PW_FORCE_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; - Jedi_PlayBlockedPushSound( self ); + Jedi_PlayBlockedPushSound(self); } -void WP_ForceKnockdown( gentity_t *self, gentity_t *pusher, qboolean pull, qboolean strongKnockdown, qboolean breakSaberLock ) -{ - if ( !self || !self->client || !pusher || !pusher->client ) - { +void WP_ForceKnockdown(gentity_t *self, gentity_t *pusher, qboolean pull, qboolean strongKnockdown, qboolean breakSaberLock) { + if (!self || !self->client || !pusher || !pusher->client) { return; } - //break out of a saberLock? - if ( breakSaberLock ) - { + // break out of a saberLock? + if (breakSaberLock) { self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; } - if ( self->health > 0 ) - { - if ( !self->s.number ) - { - NPC_SetPainEvent( self ); + if (self->health > 0) { + if (!self->s.number) { + NPC_SetPainEvent(self); + } else { + GEntity_PainFunc(self, pusher, pusher, self->currentOrigin, 0, MOD_MELEE); } - else - { - GEntity_PainFunc( self, pusher, pusher, self->currentOrigin, 0, MOD_MELEE ); - } - vec3_t pushDir; - if ( pull ) - { - VectorSubtract( pusher->currentOrigin, self->currentOrigin, pushDir ); + vec3_t pushDir; + if (pull) { + VectorSubtract(pusher->currentOrigin, self->currentOrigin, pushDir); + } else { + VectorSubtract(self->currentOrigin, pusher->currentOrigin, pushDir); } - else - { - VectorSubtract( self->currentOrigin, pusher->currentOrigin, pushDir ); - } - G_CheckLedgeDive( self, 72, pushDir, qfalse, qfalse ); + G_CheckLedgeDive(self, 72, pushDir, qfalse, qfalse); - if ( !PM_SpinningSaberAnim( self->client->ps.legsAnim ) - && !PM_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) ) - { - int knockAnim = BOTH_KNOCKDOWN1;//default knockdown - if ( pusher->client->NPC_class == CLASS_DESANN && self->client->NPC_class != CLASS_LUKE ) - {//desann always knocks down, unless you're Luke + if (!PM_SpinningSaberAnim(self->client->ps.legsAnim) && !PM_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && + !PM_InKnockDown(&self->client->ps)) { + int knockAnim = BOTH_KNOCKDOWN1; // default knockdown + if (pusher->client->NPC_class == CLASS_DESANN && self->client->NPC_class != CLASS_LUKE) { // desann always knocks down, unless you're Luke strongKnockdown = qtrue; } - if ( !self->s.number - && !strongKnockdown - && ( (!pull&&(self->client->ps.forcePowerLevel[FP_PUSH]>FORCE_LEVEL_1||!g_spskill->integer)) || (pull&&(self->client->ps.forcePowerLevel[FP_PULL]>FORCE_LEVEL_1||!g_spskill->integer)) ) ) - {//player only knocked down if pushed *hard* - if ( self->s.weapon == WP_SABER ) - {//temp HACK: these are the only 2 pain anims that look good when holding a saber - knockAnim = PM_PickAnim( self, BOTH_PAIN2, BOTH_PAIN3 ); + if (!self->s.number && !strongKnockdown && + ((!pull && (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1 || !g_spskill->integer)) || + (pull && (self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 || !g_spskill->integer)))) { // player only knocked down if pushed *hard* + if (self->s.weapon == WP_SABER) { // temp HACK: these are the only 2 pain anims that look good when holding a saber + knockAnim = PM_PickAnim(self, BOTH_PAIN2, BOTH_PAIN3); + } else { + knockAnim = PM_PickAnim(self, BOTH_PAIN1, BOTH_PAIN19); } - else - { - knockAnim = PM_PickAnim( self, BOTH_PAIN1, BOTH_PAIN19 ); - } - } - else if ( PM_CrouchAnim( self->client->ps.legsAnim ) ) - {//crouched knockdown + } else if (PM_CrouchAnim(self->client->ps.legsAnim)) { // crouched knockdown knockAnim = BOTH_KNOCKDOWN4; - } - else - {//plain old knockdown - vec3_t pLFwd, pLAngles = {0,self->client->ps.viewangles[YAW],0}; - vec3_t sFwd, sAngles = {0,pusher->client->ps.viewangles[YAW],0}; - AngleVectors( pLAngles, pLFwd, NULL, NULL ); - AngleVectors( sAngles, sFwd, NULL, NULL ); - if ( DotProduct( sFwd, pLFwd ) > 0.2f ) - {//pushing him from behind - //FIXME: check to see if we're aiming below or above the waist? - if ( pull ) - { + } else { // plain old knockdown + vec3_t pLFwd, pLAngles = {0, self->client->ps.viewangles[YAW], 0}; + vec3_t sFwd, sAngles = {0, pusher->client->ps.viewangles[YAW], 0}; + AngleVectors(pLAngles, pLFwd, NULL, NULL); + AngleVectors(sAngles, sFwd, NULL, NULL); + if (DotProduct(sFwd, pLFwd) > 0.2f) { // pushing him from behind + // FIXME: check to see if we're aiming below or above the waist? + if (pull) { knockAnim = BOTH_KNOCKDOWN1; - } - else - { + } else { knockAnim = BOTH_KNOCKDOWN3; } - } - else - {//pushing him from front - if ( pull ) - { + } else { // pushing him from front + if (pull) { knockAnim = BOTH_KNOCKDOWN3; - } - else - { + } else { knockAnim = BOTH_KNOCKDOWN1; } } } - if ( knockAnim == BOTH_KNOCKDOWN1 && strongKnockdown ) - {//push *hard* + if (knockAnim == BOTH_KNOCKDOWN1 && strongKnockdown) { // push *hard* knockAnim = BOTH_KNOCKDOWN2; } - NPC_SetAnim( self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( self->s.number ) - {//randomize getup times - int addTime = Q_irand( -300, 1000 ); + NPC_SetAnim(self, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (self->s.number) { // randomize getup times + int addTime = Q_irand(-300, 1000); self->client->ps.legsAnimTimer += addTime; self->client->ps.torsoAnimTimer += addTime; } // - if ( pusher->NPC && pusher->enemy == self ) - {//pushed pushed down his enemy - G_AddVoiceEvent( pusher, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 3000 ); + if (pusher->NPC && pusher->enemy == self) { // pushed pushed down his enemy + G_AddVoiceEvent(pusher, Q_irand(EV_GLOAT1, EV_GLOAT3), 3000); pusher->NPC->blockedSpeechDebounceTime = level.time + 3000; } } @@ -5578,153 +4553,128 @@ void WP_ForceKnockdown( gentity_t *self, gentity_t *pusher, qboolean pull, qbool self->forcePushTime = level.time + 600; // let the push effect last for 600 ms } -void ForceThrow( gentity_t *self, qboolean pull ) -{//FIXME: pass in a target ent so we (an NPC) can push/pull just one targeted ent. - //shove things in front of you away - float dist; - gentity_t *ent, *forwardEnt = NULL; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *push_list[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - int radius; - vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; - float dot1, cone; - trace_t tr; - int anim, hold, soundIndex, cost, actualCost; - - if ( self->health <= 0 ) - { +void ForceThrow(gentity_t *self, qboolean pull) { // FIXME: pass in a target ent so we (an NPC) can push/pull just one targeted ent. + // shove things in front of you away + float dist; + gentity_t *ent, *forwardEnt = NULL; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *push_list[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + int radius; + vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; + float dot1, cone; + trace_t tr; + int anim, hold, soundIndex, cost, actualCost; + + if (self->health <= 0) { return; } - if ( self->client->ps.leanofs ) - {//can't force-throw while leaning + if (self->client->ps.leanofs) { // can't force-throw while leaning return; } - if ( self->client->ps.forcePowerDebounce[FP_PUSH] > level.time )//self->client->ps.powerups[PW_FORCE_PUSH] > level.time ) - {//already pushing- now you can't haul someone across the room, sorry + if (self->client->ps.forcePowerDebounce[FP_PUSH] > level.time) // self->client->ps.powerups[PW_FORCE_PUSH] > level.time ) + { // already pushing- now you can't haul someone across the room, sorry return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force throw/pull when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force throw/pull when zoomed in or in cinematic return; } - if ( self->client->ps.saberLockTime > level.time ) - { - if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - {//this can be a way to break out + if (self->client->ps.saberLockTime > level.time) { + if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3) { // this can be a way to break out return; } - //else, I'm breaking my half of the saberlock + // else, I'm breaking my half of the saberlock self->client->ps.saberLockTime = 0; self->client->ps.saberLockEnemy = ENTITYNUM_NONE; } - if ( self->client->ps.legsAnim == BOTH_KNOCKDOWN3 - || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F1 && self->client->ps.torsoAnimTimer > 400) - || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F2 && self->client->ps.torsoAnimTimer > 900) - || (self->client->ps.torsoAnim == BOTH_GETUP3 && self->client->ps.torsoAnimTimer > 500) - || (self->client->ps.torsoAnim == BOTH_GETUP4 && self->client->ps.torsoAnimTimer > 300) - || (self->client->ps.torsoAnim == BOTH_GETUP5 && self->client->ps.torsoAnimTimer > 500) ) - {//we're face-down, so we'd only be force-push/pulling the floor + if (self->client->ps.legsAnim == BOTH_KNOCKDOWN3 || (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F1 && self->client->ps.torsoAnimTimer > 400) || + (self->client->ps.torsoAnim == BOTH_FORCE_GETUP_F2 && self->client->ps.torsoAnimTimer > 900) || + (self->client->ps.torsoAnim == BOTH_GETUP3 && self->client->ps.torsoAnimTimer > 500) || + (self->client->ps.torsoAnim == BOTH_GETUP4 && self->client->ps.torsoAnimTimer > 300) || + (self->client->ps.torsoAnim == BOTH_GETUP5 && self->client->ps.torsoAnimTimer > 500)) { // we're face-down, so we'd only be force-push/pulling the floor return; } - if ( pull ) - { + if (pull) { radius = forcePushPullRadius[self->client->ps.forcePowerLevel[FP_PULL]]; - } - else - { + } else { radius = forcePushPullRadius[self->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( !radius ) - {//no ability to do this yet + if (!radius) { // no ability to do this yet return; } - if ( pull ) - { + if (pull) { cost = forcePowerNeeded[FP_PULL]; - if ( !WP_ForcePowerUsable( self, FP_PULL, cost ) ) - { + if (!WP_ForcePowerUsable(self, FP_PULL, cost)) { return; } - //make sure this plays and that you cannot press fire for about 200ms after this + // make sure this plays and that you cannot press fire for about 200ms after this anim = BOTH_FORCEPULL; - soundIndex = G_SoundIndex( "sound/weapons/force/pull.wav" ); + soundIndex = G_SoundIndex("sound/weapons/force/pull.wav"); hold = 200; - } - else - { + } else { cost = forcePowerNeeded[FP_PUSH]; - if ( !WP_ForcePowerUsable( self, FP_PUSH, cost ) ) - { + if (!WP_ForcePowerUsable(self, FP_PUSH, cost)) { return; } - //make sure this plays and that you cannot press fire for about 1 second after this + // make sure this plays and that you cannot press fire for about 1 second after this anim = BOTH_FORCEPUSH; - soundIndex = G_SoundIndex( "sound/weapons/force/push.wav" ); + soundIndex = G_SoundIndex("sound/weapons/force/push.wav"); hold = 650; } int parts = SETANIM_TORSO; - if ( !PM_InKnockDown( &self->client->ps ) ) - { - if ( self->client->ps.saberLockTime > level.time ) - { + if (!PM_InKnockDown(&self->client->ps)) { + if (self->client->ps.saberLockTime > level.time) { self->client->ps.saberLockTime = 0; self->painDebounceTime = level.time + 2000; hold += 1000; parts = SETANIM_BOTH; - } - else if ( !VectorLengthSquared( self->client->ps.velocity ) && !(self->client->ps.pm_flags&PMF_DUCKED)) - { + } else if (!VectorLengthSquared(self->client->ps.velocity) && !(self->client->ps.pm_flags & PMF_DUCKED)) { parts = SETANIM_BOTH; } } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - if ( self->client->ps.forcePowersActive&(1<value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + hold = floor(hold * g_timescale->value); } - self->client->ps.weaponTime = hold;//was 1000, but want to swing sooner - //do effect... FIXME: build-up or delay this until in proper part of anim + self->client->ps.weaponTime = hold; // was 1000, but want to swing sooner + // do effect... FIXME: build-up or delay this until in proper part of anim self->client->ps.powerups[PW_FORCE_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; - G_Sound( self, soundIndex ); + G_Sound(self, soundIndex); - VectorCopy( self->client->ps.viewangles, fwdangles ); - //fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, right, NULL ); - VectorCopy( self->currentOrigin, center ); + VectorCopy(self->client->ps.viewangles, fwdangles); + // fwdangles[1] = self->client->ps.viewangles[1]; + AngleVectors(fwdangles, forward, right, NULL); + VectorCopy(self->currentOrigin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - if ( pull ) - { + if (pull) { cone = forcePullCone[self->client->ps.forcePowerLevel[FP_PULL]]; - } - else - { + } else { cone = forcePushCone[self->client->ps.forcePowerLevel[FP_PUSH]]; } - if ( cone >= 1.0f ) - {//must be pointing right at them - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, G2_NOCOLLIDE, 0 );//was MASK_SHOT, changed to match crosshair trace + if (cone >= 1.0f) { // must be pointing right at them + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, G2_NOCOLLIDE, + 0); // was MASK_SHOT, changed to match crosshair trace /* //FIXME: can't just return, need to be able to push missiles if ( tr.entityNum >= ENTITYNUM_WORLD ) @@ -5735,231 +4685,167 @@ void ForceThrow( gentity_t *self, qboolean pull ) forwardEnt = &g_entities[tr.entityNum]; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + ent = entityList[e]; if (ent == self) continue; - if ( ent->owner == self && ent->s.weapon != WP_THERMAL )//can push your own thermals + if (ent->owner == self && ent->s.weapon != WP_THERMAL) // can push your own thermals continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->NPC && ent->NPC->scriptFlags & SCF_NO_FORCE ) - { - if ( ent->s.weapon == WP_SABER ) - {//Hmm, should jedi do the resist behavior? If this is on, perhaps it's because of a cinematic? - WP_ResistForcePush( ent, self, qtrue ); + if (ent->NPC && ent->NPC->scriptFlags & SCF_NO_FORCE) { + if (ent->s.weapon == WP_SABER) { // Hmm, should jedi do the resist behavior? If this is on, perhaps it's because of a cinematic? + WP_ResistForcePush(ent, self, qtrue); } continue; } - if ( (ent->flags&FL_FORCE_PULLABLE_ONLY) && !pull ) - {//simple HACK: cannot force-push ammo rack items (because they may start in solid) + if ((ent->flags & FL_FORCE_PULLABLE_ONLY) && !pull) { // simple HACK: cannot force-push ammo rack items (because they may start in solid) continue; } - //FIXME: don't push it if I already pushed it a little while ago - if ( ent->s.eType != ET_MISSILE ) - { - if ( cone >= 1.0f ) - {//must be pointing right at them - if ( ent != forwardEnt ) - {//must be the person I'm looking right at - if ( ent->client && !pull - && ent->client->ps.forceGripEntityNum == self->s.number - && (self->s.eFlags&EF_FORCE_GRIPPED) ) - {//this is the guy that's force-gripping me, use a wider cone regardless of force power level - } - else - { + // FIXME: don't push it if I already pushed it a little while ago + if (ent->s.eType != ET_MISSILE) { + if (cone >= 1.0f) { // must be pointing right at them + if (ent != forwardEnt) { // must be the person I'm looking right at + if (ent->client && !pull && ent->client->ps.forceGripEntityNum == self->s.number && + (self->s.eFlags & EF_FORCE_GRIPPED)) { // this is the guy that's force-gripping me, use a wider cone regardless of force power level + } else { continue; } } } - if ( ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject )//|| !(ent->flags&FL_DROPPED_ITEM) )//was only dropped items + if (ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject) //|| !(ent->flags&FL_DROPPED_ITEM) )//was only dropped items { - //FIXME: need pushable objects - if ( ent->s.eFlags & EF_NODRAW ) - { + // FIXME: need pushable objects + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( !ent->client ) - { - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber - if ( !(ent->svFlags&SVF_GLASS_BRUSH) ) - {//and not glass - if ( Q_stricmp( "func_door", ent->classname ) != 0 || !(ent->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/) ) - {//not a force-usable door - if ( Q_stricmp( "func_static", ent->classname ) != 0 || (!(ent->spawnflags&1/*F_PUSH*/)&&!(ent->spawnflags&2/*F_PULL*/)) ) - {//not a force-usable func_static - if ( Q_stricmp( "limb", ent->classname ) ) - {//not a limb - if ( ent->s.weapon == WP_TURRET && !Q_stricmp( "PAS", ent->classname ) && ent->s.apos.trType == TR_STATIONARY ) - {//can knock over placed turrets - if ( !self->s.number || self->enemy != ent ) - {//only NPCs who are actively mad at this turret can push it over + if (!ent->client) { + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber + if (!(ent->svFlags & SVF_GLASS_BRUSH)) { // and not glass + if (Q_stricmp("func_door", ent->classname) != 0 || !(ent->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/)) { // not a force-usable door + if (Q_stricmp("func_static", ent->classname) != 0 || + (!(ent->spawnflags & 1 /*F_PUSH*/) && !(ent->spawnflags & 2 /*F_PULL*/))) { // not a force-usable func_static + if (Q_stricmp("limb", ent->classname)) { // not a limb + if (ent->s.weapon == WP_TURRET && !Q_stricmp("PAS", ent->classname) && + ent->s.apos.trType == TR_STATIONARY) { // can knock over placed turrets + if (!self->s.number || self->enemy != ent) { // only NPCs who are actively mad at this turret can push it over continue; } - } - else - { + } else { continue; } } } - } - else if ( ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2 ) - {//not at rest + } else if (ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2) { // not at rest continue; } } } - //continue; - } - else if ( ent->client->NPC_class == CLASS_MARK1 ) - {//can't push Mark1 unless push 3 - if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - { + // continue; + } else if (ent->client->NPC_class == CLASS_MARK1) { // can't push Mark1 unless push 3 + if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3) { continue; } - } - else if ( ent->client->NPC_class == CLASS_GALAKMECH || ent->client->NPC_class == CLASS_ATST ) - {//can't push ATST or Galak + } else if (ent->client->NPC_class == CLASS_GALAKMECH || ent->client->NPC_class == CLASS_ATST) { // can't push ATST or Galak continue; - } - else if ( ent->s.weapon == WP_EMPLACED_GUN ) - {//FIXME: maybe can pull them out? + } else if (ent->s.weapon == WP_EMPLACED_GUN) { // FIXME: maybe can pull them out? continue; - } - else if ( ent->client->playerTeam == self->client->playerTeam && self->enemy && self->enemy != ent ) - {//can't accidently push a teammate while in combat + } else if (ent->client->playerTeam == self->client->playerTeam && self->enemy && + self->enemy != ent) { // can't accidently push a teammate while in combat continue; } - } - else if ( ent->s.eType == ET_ITEM - && ent->item - && ent->item->giType == IT_HOLDABLE - && ent->item->giTag == INV_SECURITY_KEY ) - //&& (ent->flags&FL_DROPPED_ITEM) ??? - {//dropped security keys can't be pushed? But placed ones can...? does this make any sense? - if ( !pull || self->s.number ) - {//can't push, NPC's can't do anything to it + } else if (ent->s.eType == ET_ITEM && ent->item && ent->item->giType == IT_HOLDABLE && ent->item->giTag == INV_SECURITY_KEY) + //&& (ent->flags&FL_DROPPED_ITEM) ??? + { // dropped security keys can't be pushed? But placed ones can...? does this make any sense? + if (!pull || self->s.number) { // can't push, NPC's can't do anything to it continue; - } - else - { - if ( g_crosshairEntNum != ent->s.number ) - {//player can pull it if looking *right* at it - if ( cone >= 1.0f ) - {//we did a forwardEnt trace - if ( forwardEnt != ent ) - {//must be pointing right at them + } else { + if (g_crosshairEntNum != ent->s.number) { // player can pull it if looking *right* at it + if (cone >= 1.0f) { // we did a forwardEnt trace + if (forwardEnt != ent) { // must be pointing right at them continue; } - } - else - {//do a forwardEnt trace - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, G2_NOCOLLIDE, 0 );//was MASK_SHOT, changed to match crosshair trace - if ( tr.entityNum != ent->s.number ) - {//last chance + } else { // do a forwardEnt trace + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, + MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, G2_NOCOLLIDE, + 0); // was MASK_SHOT, changed to match crosshair trace + if (tr.entityNum != ent->s.number) { // last chance continue; } } } } } - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//can't force-push/pull stuck missiles (detpacks, tripmines) + } else { + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // can't force-push/pull stuck missiles (detpacks, tripmines) continue; } - if ( ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL ) - {//only thermal detonators can be pushed once stopped + if (ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL) { // only thermal detonators can be pushed once stopped continue; } } - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < ent->absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < ent->absmin[i]) { v[i] = ent->absmin[i] - center[i]; - } else if ( center[i] > ent->absmax[i] ) - { + } else if (center[i] > ent->absmax[i]) { v[i] = center[i] - ent->absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( ent->absmax, ent->absmin, size ); - VectorMA( ent->absmin, 0.5, size, ent_org ); + VectorSubtract(ent->absmax, ent->absmin, size); + VectorMA(ent->absmin, 0.5, size, ent_org); - //see if they're in front of me - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( cone < 1.0f ) - {//must be within the forward cone - if ( ent->client && !pull - && ent->client->ps.forceGripEntityNum == self->s.number - && self->s.eFlags&EF_FORCE_GRIPPED ) - {//this is the guy that's force-gripping me, use a wider cone regardless of force power level - if ( (dot1 = DotProduct( dir, forward )) < cone-0.3f ) + // see if they're in front of me + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if (cone < 1.0f) { // must be within the forward cone + if (ent->client && !pull && ent->client->ps.forceGripEntityNum == self->s.number && + self->s.eFlags & EF_FORCE_GRIPPED) { // this is the guy that's force-gripping me, use a wider cone regardless of force power level + if ((dot1 = DotProduct(dir, forward)) < cone - 0.3f) continue; - } - else if ( ent->s.eType == ET_MISSILE )//&& ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject ) - {//missiles are easier to force-push, never require direct trace (FIXME: maybe also items and general physics objects) - if ( (dot1 = DotProduct( dir, forward )) < cone-0.3f ) + } else if (ent->s.eType == ET_MISSILE) //&& ent->s.eType != ET_ITEM && ent->e_ThinkFunc != thinkF_G_RunObject ) + { // missiles are easier to force-push, never require direct trace (FIXME: maybe also items and general physics objects) + if ((dot1 = DotProduct(dir, forward)) < cone - 0.3f) continue; - } - else if ( (dot1 = DotProduct( dir, forward )) < cone ) - { + } else if ((dot1 = DotProduct(dir, forward)) < cone) { continue; } - } - else if ( ent->s.eType == ET_MISSILE ) - {//a missile and we're at force level 1... just use a small cone, but not ridiculously small - if ( (dot1 = DotProduct( dir, forward )) < 0.75f ) - { + } else if (ent->s.eType == ET_MISSILE) { // a missile and we're at force level 1... just use a small cone, but not ridiculously small + if ((dot1 = DotProduct(dir, forward)) < 0.75f) { continue; } - }//else is an NPC or brush entity that our forward trace would have to hit + } // else is an NPC or brush entity that our forward trace would have to hit - dist = VectorLength( v ); + dist = VectorLength(v); - //Now check and see if we can actually deflect it - //method1 - //if within a certain range, deflect it - if ( ent->s.eType == ET_MISSILE && cone >= 1.0f ) - {//smaller radius on missile checks at force push 1 - if ( dist >= 192 ) - { + // Now check and see if we can actually deflect it + // method1 + // if within a certain range, deflect it + if (ent->s.eType == ET_MISSILE && cone >= 1.0f) { // smaller radius on missile checks at force push 1 + if (dist >= 192) { continue; } - } - else if ( dist >= radius ) - { + } else if (dist >= radius) { continue; } - //in PVS? - if ( !ent->bmodel && !gi.inPVS( ent_org, self->client->renderInfo.eyePoint ) ) - {//must be in PVS + // in PVS? + if (!ent->bmodel && !gi.inPVS(ent_org, self->client->renderInfo.eyePoint)) { // must be in PVS continue; } - if ( ent != forwardEnt ) - {//don't need to trace against forwardEnt again - //really should have a clear LOS to this thing... - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_OPAQUE|CONTENTS_SOLID, G2_NOCOLLIDE, 0 );//was MASK_SHOT, but changed to match above trace and crosshair trace - if ( tr.fraction < 1.0f && tr.entityNum != ent->s.number ) - {//must have clear LOS + if (ent != forwardEnt) { // don't need to trace against forwardEnt again + // really should have a clear LOS to this thing... + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_OPAQUE | CONTENTS_SOLID, G2_NOCOLLIDE, + 0); // was MASK_SHOT, but changed to match above trace and crosshair trace + if (tr.fraction < 1.0f && tr.entityNum != ent->s.number) { // must have clear LOS continue; } } @@ -5969,272 +4855,214 @@ void ForceThrow( gentity_t *self, qboolean pull ) ent_count++; } - if ( ent_count ) - { - for ( int x = 0; x < ent_count; x++ ) - { - if ( push_list[x]->client ) - { - vec3_t pushDir; - float knockback = pull?0:200; - -//FIXMEFIXMEFIXMEFIXMEFIXME: extern a lot of this common code when I have the time!!! - - //First, if this is the player we're push/pulling, see if he can counter it - if ( !push_list[x]->s.number ) - {//player - if ( push_list[x]->health > 0 //alive - && push_list[x]->client //client - && push_list[x]->client->ps.torsoAnim != BOTH_FORCEGRIP_HOLD// BOTH_FORCEGRIP1//wasn't trying to grip anyone - && (self->client->NPC_class != CLASS_DESANN || !Q_irand( 0, 2 ) )//only 30% chance of resisting a Desann push - && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE//on the ground - && !PM_InKnockDown( &push_list[x]->client->ps )//not knocked down already - && push_list[x]->client->ps.saberLockTime < level.time//not involved in a saberLock - && push_list[x]->client->ps.weaponTime < level.time//not attacking or otherwise busy - && (push_list[x]->client->ps.weapon == WP_SABER||push_list[x]->client->ps.weapon == WP_MELEE) )//using saber or fists - {//trying to push or pull the player! - if ( push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time//player was pushing/pulling too - ||( pull && Q_irand( 0, (push_list[x]->client->ps.forcePowerLevel[FP_PULL] - self->client->ps.forcePowerLevel[FP_PULL])*2+1 ) > 0 )//player's pull is high enough - ||( !pull && Q_irand( 0, (push_list[x]->client->ps.forcePowerLevel[FP_PUSH] - self->client->ps.forcePowerLevel[FP_PUSH])*2+1 ) > 0 ) )//player's push is high enough - {//player's force push/pull is high enough to try to stop me - if ( InFront( self->currentOrigin, push_list[x]->client->renderInfo.eyePoint, push_list[x]->client->ps.viewangles, 0.3f ) ) - {//I'm in front of player - WP_ResistForcePush( push_list[x], self, qfalse ); - push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + if (ent_count) { + for (int x = 0; x < ent_count; x++) { + if (push_list[x]->client) { + vec3_t pushDir; + float knockback = pull ? 0 : 200; + + // FIXMEFIXMEFIXMEFIXMEFIXME: extern a lot of this common code when I have the time!!! + + // First, if this is the player we're push/pulling, see if he can counter it + if (!push_list[x]->s.number) { // player + if (push_list[x]->health > 0 // alive + && push_list[x]->client // client + && push_list[x]->client->ps.torsoAnim != BOTH_FORCEGRIP_HOLD // BOTH_FORCEGRIP1//wasn't trying to grip anyone + && (self->client->NPC_class != CLASS_DESANN || !Q_irand(0, 2)) // only 30% chance of resisting a Desann push + && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE // on the ground + && !PM_InKnockDown(&push_list[x]->client->ps) // not knocked down already + && push_list[x]->client->ps.saberLockTime < level.time // not involved in a saberLock + && push_list[x]->client->ps.weaponTime < level.time // not attacking or otherwise busy + && (push_list[x]->client->ps.weapon == WP_SABER || push_list[x]->client->ps.weapon == WP_MELEE)) // using saber or fists + { // trying to push or pull the player! + if (push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time // player was pushing/pulling too + || (pull && Q_irand(0, (push_list[x]->client->ps.forcePowerLevel[FP_PULL] - self->client->ps.forcePowerLevel[FP_PULL]) * 2 + 1) > + 0) // player's pull is high enough + || (!pull && Q_irand(0, (push_list[x]->client->ps.forcePowerLevel[FP_PUSH] - self->client->ps.forcePowerLevel[FP_PUSH]) * 2 + 1) > + 0)) // player's push is high enough + { // player's force push/pull is high enough to try to stop me + if (InFront(self->currentOrigin, push_list[x]->client->renderInfo.eyePoint, push_list[x]->client->ps.viewangles, + 0.3f)) { // I'm in front of player + WP_ResistForcePush(push_list[x], self, qfalse); + push_list[x]->client->ps.saberMove = push_list[x]->client->ps.saberBounceMove = + LS_READY; // don't finish whatever saber anim you may have been in push_list[x]->client->ps.saberBlocked = BLOCKED_NONE; continue; } } } - } - else if ( push_list[x]->client && Jedi_WaitingAmbush( push_list[x] ) ) - { - WP_ForceKnockdown( push_list[x], self, pull, qtrue, qfalse ); + } else if (push_list[x]->client && Jedi_WaitingAmbush(push_list[x])) { + WP_ForceKnockdown(push_list[x], self, pull, qtrue, qfalse); continue; } - - //okay, everyone else (or player who couldn't resist it)... - if ( ((self->s.number == 0 && Q_irand( 0, 2 ) ) || Q_irand( 0, 2 ) ) && push_list[x]->client && push_list[x]->health > 0 //a living client - && push_list[x]->client->ps.weapon == WP_SABER //Jedi - && push_list[x]->health > 0 //alive - && (self->client->NPC_class != CLASS_DESANN || !Q_irand( 0, 2 ) )//only 30% chance of resisting a Desann push - && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE //on the ground - && InFront( self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.3f ) //I'm in front of him - && ( push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time ||//he's pushing too - (push_list[x]->s.number != 0 && push_list[x]->client->ps.weaponTime < level.time)//not the player and not attacking (NPC jedi auto-defend against pushes) - ) - ) - {//Jedi don't get pushed, they resist as long as they aren't already attacking and are on the ground - if ( push_list[x]->client->ps.saberLockTime > level.time ) - {//they're in a lock - if ( push_list[x]->client->ps.saberLockEnemy != self->s.number ) - {//they're not in a lock with me + // okay, everyone else (or player who couldn't resist it)... + if (((self->s.number == 0 && Q_irand(0, 2)) || Q_irand(0, 2)) && push_list[x]->client && push_list[x]->health > 0 // a living client + && push_list[x]->client->ps.weapon == WP_SABER // Jedi + && push_list[x]->health > 0 // alive + && (self->client->NPC_class != CLASS_DESANN || !Q_irand(0, 2)) // only 30% chance of resisting a Desann push + && push_list[x]->client->ps.groundEntityNum != ENTITYNUM_NONE // on the ground + && InFront(self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.3f) // I'm in front of him + && (push_list[x]->client->ps.powerups[PW_FORCE_PUSH] > level.time || // he's pushing too + (push_list[x]->s.number != 0 && + push_list[x]->client->ps.weaponTime < level.time) // not the player and not attacking (NPC jedi auto-defend against pushes) + )) { // Jedi don't get pushed, they resist as long as they aren't already attacking and are on the ground + if (push_list[x]->client->ps.saberLockTime > level.time) { // they're in a lock + if (push_list[x]->client->ps.saberLockEnemy != self->s.number) { // they're not in a lock with me continue; - } - else if ( pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 || - push_list[x]->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//they're in a lock with me, but my push is too weak + } else if (pull || self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 || + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // they're in a lock with me, but my push is too weak continue; - } - else - {//we will knock them down + } else { // we will knock them down self->painDebounceTime = 0; self->client->ps.weaponTime = 500; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } } - if ( !pull && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && !Q_irand(0,2) && - push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3 ) - {//a level 3 push can even knock down a jedi - if ( PM_InKnockDown( &push_list[x]->client->ps ) ) - {//can't knock them down again + if (!pull && self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && !Q_irand(0, 2) && + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_3) { // a level 3 push can even knock down a jedi + if (PM_InKnockDown(&push_list[x]->client->ps)) { // can't knock them down again continue; } - WP_ForceKnockdown( push_list[x], self, pull, qfalse, qtrue ); - } - else - { - WP_ResistForcePush( push_list[x], self, qfalse ); + WP_ForceKnockdown(push_list[x], self, pull, qfalse, qtrue); + } else { + WP_ResistForcePush(push_list[x], self, qfalse); } - } - else - { - //UGH: FIXME: for enemy jedi, they should probably always do force pull 3, and not your weapon (if player?)! - //shove them - if ( push_list[x]->s.number && push_list[x]->message ) - {//an NPC who has a key - //don't push me... FIXME: maybe can pull the key off me? - WP_ForceKnockdown( push_list[x], self, pull, qfalse, qfalse ); + } else { + // UGH: FIXME: for enemy jedi, they should probably always do force pull 3, and not your weapon (if player?)! + // shove them + if (push_list[x]->s.number && push_list[x]->message) { // an NPC who has a key + // don't push me... FIXME: maybe can pull the key off me? + WP_ForceKnockdown(push_list[x], self, pull, qfalse, qfalse); continue; } - if ( pull ) - { - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, pushDir ); - if ( self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 - && push_list[x]->s.weapon != WP_SABER - && push_list[x]->s.weapon != WP_MELEE - && push_list[x]->s.weapon != WP_THERMAL ) - {//yank the weapon - NOTE: level 1 just knocks them down, not take weapon - //FIXME: weapon yank anim if not a knockdown? - if ( InFront( self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, 0.0f ) ) - {//enemy has to be facing me, too... - WP_DropWeapon( push_list[x], pushDir ); + if (pull) { + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, pushDir); + if (self->client->ps.forcePowerLevel[FP_PULL] > FORCE_LEVEL_1 && push_list[x]->s.weapon != WP_SABER && + push_list[x]->s.weapon != WP_MELEE && + push_list[x]->s.weapon != WP_THERMAL) { // yank the weapon - NOTE: level 1 just knocks them down, not take weapon + // FIXME: weapon yank anim if not a knockdown? + if (InFront(self->currentOrigin, push_list[x]->currentOrigin, push_list[x]->client->ps.viewangles, + 0.0f)) { // enemy has to be facing me, too... + WP_DropWeapon(push_list[x], pushDir); } } - knockback += VectorNormalize( pushDir ); - if ( knockback > 200 ) - { + knockback += VectorNormalize(pushDir); + if (knockback > 200) { knockback = 200; } - if ( self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_3 ) - {//maybe just knock them down + if (self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_3) { // maybe just knock them down knockback /= 3; } - } - else - { - VectorSubtract( push_list[x]->currentOrigin, self->currentOrigin, pushDir ); - knockback -= VectorNormalize( pushDir ); - if ( knockback < 100 ) - { + } else { + VectorSubtract(push_list[x]->currentOrigin, self->currentOrigin, pushDir); + knockback -= VectorNormalize(pushDir); + if (knockback < 100) { knockback = 100; } - //scale for push level - if ( self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 ) - {//maybe just knock them down + // scale for push level + if (self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2) { // maybe just knock them down knockback /= 3; - } - else if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//super-hard push - //Hmm, maybe in this case can even nudge/knockdown a jedi? Especially if close? - //knockback *= 5; + } else if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // super-hard push + // Hmm, maybe in this case can even nudge/knockdown a jedi? + // Especially if close? knockback *= 5; } } - //actually push/pull the enemy - G_Throw( push_list[x], pushDir, knockback ); - //make it so they don't actually hurt me when pulled at me... + // actually push/pull the enemy + G_Throw(push_list[x], pushDir, knockback); + // make it so they don't actually hurt me when pulled at me... push_list[x]->forcePuller = self->s.number; - if ( push_list[x]->client->ps.velocity[2] < knockback ) - { + if (push_list[x]->client->ps.velocity[2] < knockback) { push_list[x]->client->ps.velocity[2] = knockback; } - if ( push_list[x]->health > 0 ) - {//target is still alive - if ( (push_list[x]->s.number||(cg.renderingThirdPerson&&!cg.zoomMode)) //NPC or 3rd person player - && ((!pull&&self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 && push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) //level 1 push - || (pull && self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_2 && push_list[x]->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_1)) )//level 1 pull - {//NPC or third person player (without force push/pull skill), and force push/pull level is at 1 - WP_ForceKnockdown( - push_list[x], self, pull, - (qboolean)(!pull && knockback > 150), qfalse ); - } - else if ( !push_list[x]->s.number ) - {//player, have to force an anim on him - WP_ForceKnockdown( - push_list[x], self, pull, - (qboolean)(!pull && knockback > 150), qfalse ); - } - else - {//NPC and force-push/pull at level 2 or higher - WP_ForceKnockdown( - push_list[x], self, pull, - (qboolean)(!pull && knockback > 100), qfalse ); + if (push_list[x]->health > 0) { // target is still alive + if ((push_list[x]->s.number || (cg.renderingThirdPerson && !cg.zoomMode)) // NPC or 3rd person player + && ((!pull && self->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_2 && + push_list[x]->client->ps.forcePowerLevel[FP_PUSH] < FORCE_LEVEL_1) // level 1 push + || (pull && self->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_2 && + push_list[x]->client->ps.forcePowerLevel[FP_PULL] < FORCE_LEVEL_1))) // level 1 pull + { // NPC or third person player (without force push/pull skill), and force push/pull level is at 1 + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 150), qfalse); + } else if (!push_list[x]->s.number) { // player, have to force an anim on him + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 150), qfalse); + } else { // NPC and force-push/pull at level 2 or higher + WP_ForceKnockdown(push_list[x], self, pull, (qboolean)(!pull && knockback > 100), qfalse); } } push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms } - } - else if ( push_list[x]->s.weapon == WP_SABER && (push_list[x]->contents&CONTENTS_LIGHTSABER) ) - {//a thrown saber, just send it back + } else if (push_list[x]->s.weapon == WP_SABER && (push_list[x]->contents & CONTENTS_LIGHTSABER)) { // a thrown saber, just send it back /* if ( pull ) {//steal it? } - else */if ( push_list[x]->owner && push_list[x]->owner->client && push_list[x]->owner->client->ps.saberActive && push_list[x]->s.pos.trType == TR_LINEAR && push_list[x]->owner->client->ps.saberEntityState != SES_RETURNING ) - {//it's on and being controlled - //FIXME: prevent it from damaging me? - if ( self->s.number == 0 || Q_irand( 0, 2 ) ) - {//certain chance of throwing it aside and turning it off? - //give it some velocity away from me - //FIXME: maybe actually push or pull it? - if ( Q_irand( 0, 1 ) ) - { - VectorScale( right, -1, right ); + else */ + if (push_list[x]->owner && push_list[x]->owner->client && push_list[x]->owner->client->ps.saberActive && + push_list[x]->s.pos.trType == TR_LINEAR && + push_list[x]->owner->client->ps.saberEntityState != SES_RETURNING) { // it's on and being controlled + // FIXME: prevent it from damaging me? + if (self->s.number == 0 || Q_irand(0, 2)) { // certain chance of throwing it aside and turning it off? + // give it some velocity away from me + // FIXME: maybe actually push or pull it? + if (Q_irand(0, 1)) { + VectorScale(right, -1, right); } - G_ReflectMissile( self, push_list[x], right ); - //FIXME: isn't turning off!!! - WP_SaberDrop( push_list[x]->owner, push_list[x] ); + G_ReflectMissile(self, push_list[x], right); + // FIXME: isn't turning off!!! + WP_SaberDrop(push_list[x]->owner, push_list[x]); + } else { + WP_SaberReturn(push_list[x]->owner, push_list[x]); } - else - { - WP_SaberReturn( push_list[x]->owner, push_list[x] ); - } - //different effect? + // different effect? } - } - else if ( push_list[x]->s.eType == ET_MISSILE - && push_list[x]->s.pos.trType != TR_STATIONARY - && (push_list[x]->s.pos.trType != TR_INTERPOLATE||push_list[x]->s.weapon != WP_THERMAL) )//rolling and stationary thermal detonators are dealt with below + } else if (push_list[x]->s.eType == ET_MISSILE && push_list[x]->s.pos.trType != TR_STATIONARY && + (push_list[x]->s.pos.trType != TR_INTERPOLATE || + push_list[x]->s.weapon != WP_THERMAL)) // rolling and stationary thermal detonators are dealt with below { vec3_t dir2Me; - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, dir2Me ); - float dot = DotProduct( push_list[x]->s.pos.trDelta, dir2Me ); - if ( pull ) - {//deflect rather than reflect? - } - else - { - if ( push_list[x]->s.eFlags&EF_MISSILE_STICK ) - {//caught a sticky in-air + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, dir2Me); + float dot = DotProduct(push_list[x]->s.pos.trDelta, dir2Me); + if (pull) { // deflect rather than reflect? + } else { + if (push_list[x]->s.eFlags & EF_MISSILE_STICK) { // caught a sticky in-air push_list[x]->s.eType = ET_MISSILE; push_list[x]->s.eFlags &= ~EF_MISSILE_STICK; push_list[x]->s.eFlags |= EF_BOUNCE_HALF; push_list[x]->splashDamage /= 3; push_list[x]->splashRadius /= 3; push_list[x]->e_ThinkFunc = thinkF_WP_Explode; - push_list[x]->nextthink = level.time + Q_irand( 500, 3000 ); + push_list[x]->nextthink = level.time + Q_irand(500, 3000); } - if ( dot >= 0 ) - {//it's heading towards me - G_ReflectMissile( self, push_list[x], forward ); + if (dot >= 0) { // it's heading towards me + G_ReflectMissile(self, push_list[x], forward); + } else { + VectorScale(push_list[x]->s.pos.trDelta, 1.25f, push_list[x]->s.pos.trDelta); } - else - { - VectorScale( push_list[x]->s.pos.trDelta, 1.25f, push_list[x]->s.pos.trDelta ); - } - //deflect sound - //G_Sound( push_list[x], G_SoundIndex( va("sound/weapons/blaster/reflect%d.wav", Q_irand( 1, 3 ) ) ) ); - //push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms + // deflect sound + // G_Sound( push_list[x], G_SoundIndex( va("sound/weapons/blaster/reflect%d.wav", Q_irand( 1, 3 ) ) ) ); + // push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms } - } - else if ( push_list[x]->svFlags & SVF_GLASS_BRUSH ) - {//break the glass + } else if (push_list[x]->svFlags & SVF_GLASS_BRUSH) { // break the glass trace_t tr; - vec3_t pushDir; - float damage = 800; - - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - {//must be pointing right at it + vec3_t pushDir; + float damage = 800; + + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { // must be pointing right at it continue; } - if ( pull ) - { - VectorSubtract( self->client->renderInfo.eyePoint, tr.endpos, pushDir ); - } - else - { - VectorSubtract( tr.endpos, self->client->renderInfo.eyePoint, pushDir ); + if (pull) { + VectorSubtract(self->client->renderInfo.eyePoint, tr.endpos, pushDir); + } else { + VectorSubtract(tr.endpos, self->client->renderInfo.eyePoint, pushDir); } /* VectorSubtract( push_list[x]->absmax, push_list[x]->absmin, size ); @@ -6248,337 +5076,243 @@ void ForceThrow( gentity_t *self, qboolean pull ) VectorSubtract( center, self->client->renderInfo.eyePoint, pushDir ); } */ - damage -= VectorNormalize( pushDir ); - if ( damage < 200 ) - { + damage -= VectorNormalize(pushDir); + if (damage < 200) { damage = 200; } - VectorScale( pushDir, damage, pushDir ); + VectorScale(pushDir, damage, pushDir); - G_Damage( push_list[x], self, self, pushDir, tr.endpos, damage, 0, MOD_UNKNOWN ); - } - else if ( !Q_stricmp( "func_static", push_list[x]->classname ) ) - {//force-usable func_static - if ( !pull && (push_list[x]->spawnflags&1/*F_PUSH*/) ) - { - GEntity_UseFunc( push_list[x], self, self ); - } - else if ( pull && (push_list[x]->spawnflags&2/*F_PULL*/) ) - { - GEntity_UseFunc( push_list[x], self, self ); + G_Damage(push_list[x], self, self, pushDir, tr.endpos, damage, 0, MOD_UNKNOWN); + } else if (!Q_stricmp("func_static", push_list[x]->classname)) { // force-usable func_static + if (!pull && (push_list[x]->spawnflags & 1 /*F_PUSH*/)) { + GEntity_UseFunc(push_list[x], self, self); + } else if (pull && (push_list[x]->spawnflags & 2 /*F_PULL*/)) { + GEntity_UseFunc(push_list[x], self, self); } - } - else if ( !Q_stricmp( "func_door", push_list[x]->classname ) && (push_list[x]->spawnflags&2/*MOVER_FORCE_ACTIVATE*/) ) - {//push/pull the door - vec3_t pos1, pos2; + } else if (!Q_stricmp("func_door", push_list[x]->classname) && (push_list[x]->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/)) { // push/pull the door + vec3_t pos1, pos2; - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, radius, forward, end ); - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - {//must be pointing right at it + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, radius, forward, end); + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { // must be pointing right at it continue; } - if ( VectorCompare( vec3_origin, push_list[x]->s.origin ) ) - {//does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center - VectorSubtract( push_list[x]->absmax, push_list[x]->absmin, size ); - VectorMA( push_list[x]->absmin, 0.5, size, center ); - if ( (push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS1 ) - {//if at pos1 and started open, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos1, center ); + if (VectorCompare(vec3_origin, + push_list[x]->s.origin)) { // does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center + VectorSubtract(push_list[x]->absmax, push_list[x]->absmin, size); + VectorMA(push_list[x]->absmin, 0.5, size, center); + if ((push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS1) { // if at pos1 and started open, make sure we get the center where it *started* because we're + // going to add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos1, center); + } else if (!(push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS2) { // if at pos2, make sure we get the center where it *started* because we're going to + // add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos2, center); } - else if ( !(push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS2 ) - {//if at pos2, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos2, center ); - } - VectorAdd( center, push_list[x]->pos1, pos1 ); - VectorAdd( center, push_list[x]->pos2, pos2 ); - } - else - {//actually has an origin, pos1 and pos2 are absolute - VectorCopy( push_list[x]->currentOrigin, center ); - VectorCopy( push_list[x]->pos1, pos1 ); - VectorCopy( push_list[x]->pos2, pos2 ); + VectorAdd(center, push_list[x]->pos1, pos1); + VectorAdd(center, push_list[x]->pos2, pos2); + } else { // actually has an origin, pos1 and pos2 are absolute + VectorCopy(push_list[x]->currentOrigin, center); + VectorCopy(push_list[x]->pos1, pos1); + VectorCopy(push_list[x]->pos2, pos2); } - if ( Distance( pos1, self->client->renderInfo.eyePoint ) < Distance( pos2, self->client->renderInfo.eyePoint ) ) - {//pos1 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + if (Distance(pos1, self->client->renderInfo.eyePoint) < Distance(pos2, self->client->renderInfo.eyePoint)) { // pos1 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } } - } - else - {//pos2 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else { // pos2 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } } } - GEntity_UseFunc( push_list[x], self, self ); - } - else if ( push_list[x]->s.eType == ET_MISSILE/*thermal resting on ground*/ - || push_list[x]->s.eType == ET_ITEM - || push_list[x]->e_ThinkFunc == thinkF_G_RunObject || Q_stricmp( "limb", push_list[x]->classname ) == 0 ) - {//general object, toss it - vec3_t pushDir, kvel; - float knockback = pull?0:200; - float mass = 200; - if ( pull ) - { - if ( push_list[x]->s.eType == ET_ITEM ) - {//pull it to a little higher point - vec3_t adjustedOrg; - VectorCopy( self->currentOrigin, adjustedOrg ); - adjustedOrg[2] += self->maxs[2]/3; - VectorSubtract( adjustedOrg, push_list[x]->currentOrigin, pushDir ); + GEntity_UseFunc(push_list[x], self, self); + } else if (push_list[x]->s.eType == ET_MISSILE /*thermal resting on ground*/ + || push_list[x]->s.eType == ET_ITEM || push_list[x]->e_ThinkFunc == thinkF_G_RunObject || + Q_stricmp("limb", push_list[x]->classname) == 0) { // general object, toss it + vec3_t pushDir, kvel; + float knockback = pull ? 0 : 200; + float mass = 200; + if (pull) { + if (push_list[x]->s.eType == ET_ITEM) { // pull it to a little higher point + vec3_t adjustedOrg; + VectorCopy(self->currentOrigin, adjustedOrg); + adjustedOrg[2] += self->maxs[2] / 3; + VectorSubtract(adjustedOrg, push_list[x]->currentOrigin, pushDir); + } else { + VectorSubtract(self->currentOrigin, push_list[x]->currentOrigin, pushDir); } - else - { - VectorSubtract( self->currentOrigin, push_list[x]->currentOrigin, pushDir ); - } - knockback += VectorNormalize( pushDir ); - if ( knockback > 200 ) - { + knockback += VectorNormalize(pushDir); + if (knockback > 200) { knockback = 200; } - if ( push_list[x]->s.eType == ET_ITEM - && push_list[x]->item - && push_list[x]->item->giType == IT_HOLDABLE - && push_list[x]->item->giTag == INV_SECURITY_KEY ) - {//security keys are pulled with less enthusiasm - if ( knockback > 100 ) - { + if (push_list[x]->s.eType == ET_ITEM && push_list[x]->item && push_list[x]->item->giType == IT_HOLDABLE && + push_list[x]->item->giTag == INV_SECURITY_KEY) { // security keys are pulled with less enthusiasm + if (knockback > 100) { knockback = 100; } - } - else if ( knockback > 200 ) - { + } else if (knockback > 200) { knockback = 200; } - } - else - { - //HMM, if I have an auto-enemy & he's in front of me, push it toward him? - VectorSubtract( push_list[x]->currentOrigin, self->currentOrigin, pushDir ); - knockback -= VectorNormalize( pushDir ); - if ( knockback < 100 ) - { + } else { + // HMM, if I have an auto-enemy & he's in front of me, push it toward him? + VectorSubtract(push_list[x]->currentOrigin, self->currentOrigin, pushDir); + knockback -= VectorNormalize(pushDir); + if (knockback < 100) { knockback = 100; } } - //FIXME: if pull a FL_FORCE_PULLABLE_ONLY, clear the flag, assuming it's no longer in solid? or check? - VectorCopy( push_list[x]->currentOrigin, push_list[x]->s.pos.trBase ); - push_list[x]->s.pos.trTime = level.time; // move a bit on the very first frame - if ( push_list[x]->s.pos.trType != TR_INTERPOLATE ) - {//don't do this to rolling missiles + // FIXME: if pull a FL_FORCE_PULLABLE_ONLY, clear the flag, assuming it's no longer in solid? or check? + VectorCopy(push_list[x]->currentOrigin, push_list[x]->s.pos.trBase); + push_list[x]->s.pos.trTime = level.time; // move a bit on the very first frame + if (push_list[x]->s.pos.trType != TR_INTERPOLATE) { // don't do this to rolling missiles push_list[x]->s.pos.trType = TR_GRAVITY; } - if ( push_list[x]->e_ThinkFunc == thinkF_G_RunObject && push_list[x]->physicsBounce ) - { + if (push_list[x]->e_ThinkFunc == thinkF_G_RunObject && push_list[x]->physicsBounce) { mass = push_list[x]->physicsBounce; } - if ( mass < 50 ) - {//??? + if (mass < 50) { //??? mass = 50; } - if ( g_gravity->value > 0 ) - { - VectorScale( pushDir, g_knockback->value * knockback / mass * 0.8, kvel ); + if (g_gravity->value > 0) { + VectorScale(pushDir, g_knockback->value * knockback / mass * 0.8, kvel); kvel[2] = pushDir[2] * g_knockback->value * knockback / mass * 1.5; + } else { + VectorScale(pushDir, g_knockback->value * knockback / mass, kvel); } - else - { - VectorScale( pushDir, g_knockback->value * knockback / mass, kvel ); - } - VectorAdd( push_list[x]->s.pos.trDelta, kvel, push_list[x]->s.pos.trDelta ); - if ( g_gravity->value > 0 ) - { - if ( push_list[x]->s.pos.trDelta[2] < knockback ) - { + VectorAdd(push_list[x]->s.pos.trDelta, kvel, push_list[x]->s.pos.trDelta); + if (g_gravity->value > 0) { + if (push_list[x]->s.pos.trDelta[2] < knockback) { push_list[x]->s.pos.trDelta[2] = knockback; } } - //no trDuration? - if ( push_list[x]->e_ThinkFunc != thinkF_G_RunObject ) - {//objects spin themselves? - //spin it - //FIXME: messing with roll ruins the rotational center??? + // no trDuration? + if (push_list[x]->e_ThinkFunc != thinkF_G_RunObject) { // objects spin themselves? + // spin it + // FIXME: messing with roll ruins the rotational center??? push_list[x]->s.apos.trTime = level.time; push_list[x]->s.apos.trType = TR_LINEAR; - VectorClear( push_list[x]->s.apos.trDelta ); - push_list[x]->s.apos.trDelta[1] = Q_irand( -800, 800 ); + VectorClear(push_list[x]->s.apos.trDelta); + push_list[x]->s.apos.trDelta[1] = Q_irand(-800, 800); } - if ( Q_stricmp( "limb", push_list[x]->classname ) == 0 ) - {//make sure it runs it's physics + if (Q_stricmp("limb", push_list[x]->classname) == 0) { // make sure it runs it's physics push_list[x]->e_ThinkFunc = thinkF_LimbThink; push_list[x]->nextthink = level.time + FRAMETIME; } push_list[x]->forcePushTime = level.time + 600; // let the push effect last for 600 ms - if ( push_list[x]->item && push_list[x]->item->giTag == INV_SECURITY_KEY ) - { - AddSightEvent( player, push_list[x]->currentOrigin, 128, AEL_DISCOVERED );//security keys are more important + if (push_list[x]->item && push_list[x]->item->giTag == INV_SECURITY_KEY) { + AddSightEvent(player, push_list[x]->currentOrigin, 128, AEL_DISCOVERED); // security keys are more important + } else { + AddSightEvent(player, push_list[x]->currentOrigin, 128, AEL_SUSPICIOUS); // hmm... or should this always be discovered? } - else - { - AddSightEvent( player, push_list[x]->currentOrigin, 128, AEL_SUSPICIOUS );//hmm... or should this always be discovered? - } - } - else if ( push_list[x]->s.weapon == WP_TURRET - && !Q_stricmp( "PAS", push_list[x]->classname ) - && push_list[x]->s.apos.trType == TR_STATIONARY ) - {//a portable turret - WP_KnockdownTurret( self, push_list[x] ); + } else if (push_list[x]->s.weapon == WP_TURRET && !Q_stricmp("PAS", push_list[x]->classname) && + push_list[x]->s.apos.trType == TR_STATIONARY) { // a portable turret + WP_KnockdownTurret(self, push_list[x]); } } - if ( pull ) - { - if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//at level 3, can pull multiple, so it costs more - actualCost = forcePowerNeeded[FP_PUSH]*ent_count; - if ( actualCost > 50 ) - { + if (pull) { + if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // at level 3, can pull multiple, so it costs more + actualCost = forcePowerNeeded[FP_PUSH] * ent_count; + if (actualCost > 50) { actualCost = 50; - } - else if ( actualCost < cost ) - { + } else if (actualCost < cost) { actualCost = cost; } - } - else - { + } else { actualCost = cost; } - WP_ForcePowerStart( self, FP_PULL, actualCost ); - } - else - { - if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 ) - {//at level 3, can push multiple, so costs more - actualCost = forcePowerNeeded[FP_PUSH]*ent_count; - if ( actualCost > 50 ) - { + WP_ForcePowerStart(self, FP_PULL, actualCost); + } else { + if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2) { // at level 3, can push multiple, so costs more + actualCost = forcePowerNeeded[FP_PUSH] * ent_count; + if (actualCost > 50) { actualCost = 50; - } - else if ( actualCost < cost ) - { + } else if (actualCost < cost) { actualCost = cost; } - } - else if ( self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1 ) - {//at level 3, can push multiple, so costs more - actualCost = floor(forcePowerNeeded[FP_PUSH]*ent_count/1.5f); - if ( actualCost > 50 ) - { + } else if (self->client->ps.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_1) { // at level 3, can push multiple, so costs more + actualCost = floor(forcePowerNeeded[FP_PUSH] * ent_count / 1.5f); + if (actualCost > 50) { actualCost = 50; - } - else if ( actualCost < cost ) - { + } else if (actualCost < cost) { actualCost = cost; } - } - else - { + } else { actualCost = cost; } - WP_ForcePowerStart( self, FP_PUSH, actualCost ); + WP_ForcePowerStart(self, FP_PUSH, actualCost); } - } - else - {//didn't push or pull anything? don't penalize them too much - if ( pull ) - { - WP_ForcePowerStart( self, FP_PULL, 5 ); - } - else - { - WP_ForcePowerStart( self, FP_PUSH, 5 ); + } else { // didn't push or pull anything? don't penalize them too much + if (pull) { + WP_ForcePowerStart(self, FP_PULL, 5); + } else { + WP_ForcePowerStart(self, FP_PUSH, 5); } } - if ( self->NPC ) - {//NPCs can push more often - //FIXME: vary by rank and game skill? + if (self->NPC) { // NPCs can push more often + // FIXME: vary by rank and game skill? self->client->ps.forcePowerDebounce[FP_PUSH] = level.time + 200; - } - else - { + } else { self->client->ps.forcePowerDebounce[FP_PUSH] = level.time + self->client->ps.torsoAnimTimer + 500; } } -void ForceSpeed( gentity_t *self, int duration ) -{ - if ( self->health <= 0 ) - { +void ForceSpeed(gentity_t *self, int duration) { + if (self->health <= 0) { return; } - if ( !WP_ForcePowerUsable( self, FP_SPEED, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_SPEED, 0)) { return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - if ( !self->s.number && in_camera ) - {//player can't use force powers in cinematic + if (!self->s.number && in_camera) { // player can't use force powers in cinematic return; } - WP_ForcePowerStart( self, FP_SPEED, 0 ); - if ( duration ) - { + WP_ForcePowerStart(self, FP_SPEED, 0); + if (duration) { self->client->ps.forcePowerDuration[FP_SPEED] = level.time + duration; } - G_Sound( self, G_SoundIndex( "sound/weapons/force/speed.wav" ) ); + G_Sound(self, G_SoundIndex("sound/weapons/force/speed.wav")); } -void ForceHeal( gentity_t *self ) -{ - if ( self->health <= 0 || self->client->ps.stats[STAT_MAX_HEALTH] <= self->health ) - { +void ForceHeal(gentity_t *self) { + if (self->health <= 0 || self->client->ps.stats[STAT_MAX_HEALTH] <= self->health) { return; } - if ( !WP_ForcePowerUsable( self, FP_HEAL, 20 ) ) - {//must have enough force power for at least 5 points of health + if (!WP_ForcePowerUsable(self, FP_HEAL, 20)) { // must have enough force power for at least 5 points of health return; } - if ( self->painDebounceTime > level.time || (self->client->ps.weaponTime&&self->client->ps.weapon!=WP_NONE) ) - {//can't initiate a heal while taking pain or attacking + if (self->painDebounceTime > level.time || + (self->client->ps.weaponTime && self->client->ps.weapon != WP_NONE)) { // can't initiate a heal while taking pain or attacking return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - if ( !self->s.number && in_camera ) - {//player can't use force powers in cinematic + if (!self->s.number && in_camera) { // player can't use force powers in cinematic return; } /* @@ -6601,32 +5335,25 @@ void ForceHeal( gentity_t *self ) else */ { - //start health going up - //NPC_SetAnim( self, SETANIM_TORSO, ?, SETANIM_FLAG_OVERRIDE ); - WP_ForcePowerStart( self, FP_HEAL, 0 ); - if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 ) - {//must meditate - //FIXME: holster weapon (select WP_NONE?) - //FIXME: BOTH_FORCEHEAL_START - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // start health going up + // NPC_SetAnim( self, SETANIM_TORSO, ?, SETANIM_FLAG_OVERRIDE ); + WP_ForcePowerStart(self, FP_HEAL, 0); + if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2) { // must meditate + // FIXME: holster weapon (select WP_NONE?) + // FIXME: BOTH_FORCEHEAL_START + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FORCEHEAL_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - self->client->ps.torsoAnimTimer = self->client->ps.legsAnimTimer = FORCE_HEAL_INTERVAL*MAX_FORCE_HEAL + 2000;//??? - if ( self->client->ps.saberActive ) - { - self->client->ps.saberActive = qfalse;//turn off saber when meditating - if ( self->client->playerTeam == TEAM_PLAYER ) - { - G_SoundOnEnt( self, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav" ); - } - else - { - G_SoundOnEnt( self, CHAN_WEAPON, "sound/weapons/saber/enemy_saber_off.wav" ); + self->client->ps.torsoAnimTimer = self->client->ps.legsAnimTimer = FORCE_HEAL_INTERVAL * MAX_FORCE_HEAL + 2000; //??? + if (self->client->ps.saberActive) { + self->client->ps.saberActive = qfalse; // turn off saber when meditating + if (self->client->playerTeam == TEAM_PLAYER) { + G_SoundOnEnt(self, CHAN_WEAPON, "sound/weapons/saber/saberoff.wav"); + } else { + G_SoundOnEnt(self, CHAN_WEAPON, "sound/weapons/saber/enemy_saber_off.wav"); } } - } - else - {//just a quick gesture + } else { // just a quick gesture /* //Can't get an anim that looks good... NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEHEAL_QUICK, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); @@ -6636,45 +5363,34 @@ void ForceHeal( gentity_t *self ) } } - //FIXME: always play healing effect - G_SoundOnEnt( self, CHAN_ITEM, "sound/weapons/force/heal.mp3" ); + // FIXME: always play healing effect + G_SoundOnEnt(self, CHAN_ITEM, "sound/weapons/force/heal.mp3"); } -extern void NPC_PlayConfusionSound( gentity_t *self ); -extern void NPC_Jedi_PlayConfusionSound( gentity_t *self ); -qboolean WP_CheckBreakControl( gentity_t *self ) -{ - if ( !self ) - { +extern void NPC_PlayConfusionSound(gentity_t *self); +extern void NPC_Jedi_PlayConfusionSound(gentity_t *self); +qboolean WP_CheckBreakControl(gentity_t *self) { + if (!self) { return qfalse; } - if ( !self->s.number ) - {//player - if ( self->client && self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control-level - if ( self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//we are in a viewentity + if (!self->s.number) { // player + if (self->client && self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control-level + if (self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD) { // we are in a viewentity gentity_t *controlled = &g_entities[self->client->ps.viewEntity]; - if ( controlled->NPC && controlled->NPC->controlledTime > level.time ) - {//it is an NPC we controlled - //clear it and return - G_ClearViewEntity( self ); + if (controlled->NPC && controlled->NPC->controlledTime > level.time) { // it is an NPC we controlled + // clear it and return + G_ClearViewEntity(self); return qtrue; } } } - } - else - {//NPC - if ( self->NPC && self->NPC->controlledTime > level.time ) - {//being controlled + } else { // NPC + if (self->NPC && self->NPC->controlledTime > level.time) { // being controlled gentity_t *controller = &g_entities[0]; - if ( controller->client && controller->client->ps.viewEntity == self->s.number ) - {//we are being controlled by player - if ( controller->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control-level mind trick - //clear the control and return - G_ClearViewEntity( controller ); + if (controller->client && controller->client->ps.viewEntity == self->s.number) { // we are being controlled by player + if (controller->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control-level mind trick + // clear the control and return + G_ClearViewEntity(controller); return qtrue; } } @@ -6683,65 +5399,54 @@ qboolean WP_CheckBreakControl( gentity_t *self ) return qfalse; } -void ForceTelepathy( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; - qboolean targetLive = qfalse; +void ForceTelepathy(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; + qboolean targetLive = qfalse; - if ( WP_CheckBreakControl( self ) ) - { + if (WP_CheckBreakControl(self)) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - //FIXME: if mind trick 3 and aiming at an enemy need more force power - if ( !WP_ForcePowerUsable( self, FP_TELEPATHY, 0 ) ) - { + // FIXME: if mind trick 3 and aiming at an enemy need more force power + if (!WP_ForcePowerUsable(self, FP_TELEPATHY, 0)) { return; } - if ( self->client->ps.weaponTime >= 800 ) - {//just did one! + if (self->client->ps.weaponTime >= 800) { // just did one! return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - if ( !self->s.number && in_camera ) - {//player can't use force powers in cinematic + if (!self->s.number && in_camera) { // player can't use force powers in cinematic return; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.eyePoint, 2048, forward, end ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.eyePoint, 2048, forward, end); - //Cause a distraction if enemy is not fighting - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE|CONTENTS_BODY, G2_NOCOLLIDE, 0 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + // Cause a distraction if enemy is not fighting + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, end, self->s.number, MASK_OPAQUE | CONTENTS_BODY, G2_NOCOLLIDE, 0); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; - if( traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE ) - { + if (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) { return; } - if ( traceEnt && traceEnt->client ) - { - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grip him, he's in armor - case CLASS_ATST://much too big to grip! - //no droids either + if (traceEnt && traceEnt->client) { + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grip him, he's in armor + case CLASS_ATST: // much too big to grip! + // no droids either case CLASS_PROBE: case CLASS_GONK: case CLASS_R2D2: @@ -6758,230 +5463,188 @@ void ForceTelepathy( gentity_t *self ) break; } } - if ( targetLive && traceEnt->NPC ) - {//hit an organic non-player - if ( G_ActivateBehavior( traceEnt, BSET_MINDTRICK ) ) - {//activated a script on him - //FIXME: do the visual sparkles effect on their heads, still? - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); - } - else if ( traceEnt->client->playerTeam != self->client->playerTeam ) - {//an enemy + if (targetLive && traceEnt->NPC) { // hit an organic non-player + if (G_ActivateBehavior(traceEnt, BSET_MINDTRICK)) { // activated a script on him + // FIXME: do the visual sparkles effect on their heads, still? + WP_ForcePowerStart(self, FP_TELEPATHY, 0); + } else if (traceEnt->client->playerTeam != self->client->playerTeam) { // an enemy int override = 0; - if ( (traceEnt->NPC->scriptFlags&SCF_NO_MIND_TRICK) ) - { - if ( traceEnt->client->NPC_class == CLASS_GALAKMECH ) - { - G_AddVoiceEvent( NPC, Q_irand( EV_CONFUSE1, EV_CONFUSE3 ), Q_irand( 3000, 5000 ) ); + if ((traceEnt->NPC->scriptFlags & SCF_NO_MIND_TRICK)) { + if (traceEnt->client->NPC_class == CLASS_GALAKMECH) { + G_AddVoiceEvent(NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE3), Q_irand(3000, 5000)); } - } - else if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3 ) - {//control them, even jedi - G_SetViewEntity( self, traceEnt ); + } else if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_3) { // control them, even jedi + G_SetViewEntity(self, traceEnt); traceEnt->NPC->controlledTime = level.time + 30000; - } - else if ( traceEnt->s.weapon != WP_SABER ) - {//haha! Jedi aren't easily confused! - if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2 ) - {//turn them to our side - //if mind trick 3 and aiming at an enemy need more force power + } else if (traceEnt->s.weapon != WP_SABER) { // haha! Jedi aren't easily confused! + if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2) { // turn them to our side + // if mind trick 3 and aiming at an enemy need more force power override = 50; - if ( self->client->ps.forcePower < 50 ) - { + if (self->client->ps.forcePower < 50) { return; } - if ( traceEnt->s.weapon != WP_NONE ) - {//don't charm people who aren't capable of fighting... like ugnaughts and droids - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); + if (traceEnt->s.weapon != WP_NONE) { // don't charm people who aren't capable of fighting... like ugnaughts and droids + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); } - if ( traceEnt->NPC ) - { - //traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; + if (traceEnt->NPC) { + // traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; traceEnt->client->leader = self; } - //FIXME: maybe pick an enemy right here? - team_t saveTeam = traceEnt->client->enemyTeam; + // FIXME: maybe pick an enemy right here? + team_t saveTeam = traceEnt->client->enemyTeam; traceEnt->client->enemyTeam = traceEnt->client->playerTeam; traceEnt->client->playerTeam = saveTeam; - //FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when done? + // FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when + // done? traceEnt->NPC->charmedTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]]; } - } - else - {//just confuse them - //somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them pick one up for a while unless shot? - traceEnt->NPC->confusionTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]];//confused for about 10 seconds - NPC_PlayConfusionSound( traceEnt ); - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); + } else { // just confuse them + // somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them + // pick one up for a while unless shot? + traceEnt->NPC->confusionTime = level.time + mindTrickTime[self->client->ps.forcePowerLevel[FP_TELEPATHY]]; // confused for about 10 seconds + NPC_PlayConfusionSound(traceEnt); + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); } } - } - else - { - NPC_Jedi_PlayConfusionSound( traceEnt ); - } - WP_ForcePowerStart( self, FP_TELEPATHY, override ); - } - else if ( traceEnt->client->playerTeam == self->client->playerTeam ) - {//an ally - //maybe just have him look at you? Respond? Take your enemy? - if ( traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC!=NULL && !(traceEnt->NPC->scriptFlags&SCF_NO_RESPONSE) ) - { - NPC_UseResponse( traceEnt, self, qfalse ); - WP_ForcePowerStart( self, FP_TELEPATHY, 1 ); - } - }//NOTE: no effect on TEAM_NEUTRAL? - vec3_t eyeDir; - AngleVectors( traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL ); - VectorNormalize( eyeDir ); - G_PlayEffect( "force_touch", traceEnt->client->renderInfo.eyePoint, eyeDir ); - - //make sure this plays and that you cannot press fire for about 1 second after this - //FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT - NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); - //FIXME: build-up or delay this until in proper part of anim - } - else - { - if ( self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && tr.fraction * 2048 > 64 ) - {//don't create a diversion less than 64 from you of if at power level 1 - //use distraction anim instead - G_PlayEffect( G_EffectIndex( "force_touch" ), tr.endpos, tr.plane.normal ); - //FIXME: these events don't seem to always be picked up...? - AddSoundEvent( self, tr.endpos, 512, AEL_SUSPICIOUS, qtrue ); - AddSightEvent( self, tr.endpos, 512, AEL_SUSPICIOUS, 50 ); - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); - } - NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); - } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + } else { + NPC_Jedi_PlayConfusionSound(traceEnt); + } + WP_ForcePowerStart(self, FP_TELEPATHY, override); + } else if (traceEnt->client->playerTeam == self->client->playerTeam) { // an ally + // maybe just have him look at you? Respond? Take your enemy? + if (traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC != NULL && !(traceEnt->NPC->scriptFlags & SCF_NO_RESPONSE)) { + NPC_UseResponse(traceEnt, self, qfalse); + WP_ForcePowerStart(self, FP_TELEPATHY, 1); + } + } // NOTE: no effect on TEAM_NEUTRAL? + vec3_t eyeDir; + AngleVectors(traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL); + VectorNormalize(eyeDir); + G_PlayEffect("force_touch", traceEnt->client->renderInfo.eyePoint, eyeDir); + + // make sure this plays and that you cannot press fire for about 1 second after this + // FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT + NPC_SetAnim(self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + // FIXME: build-up or delay this until in proper part of anim + } else { + if (self->client->ps.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && + tr.fraction * 2048 > 64) { // don't create a diversion less than 64 from you of if at power level 1 + // use distraction anim instead + G_PlayEffect(G_EffectIndex("force_touch"), tr.endpos, tr.plane.normal); + // FIXME: these events don't seem to always be picked up...? + AddSoundEvent(self, tr.endpos, 512, AEL_SUSPICIOUS, qtrue); + AddSightEvent(self, tr.endpos, 512, AEL_SUSPICIOUS, 50); + WP_ForcePowerStart(self, FP_TELEPATHY, 0); + } + NPC_SetAnim(self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD); + } + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } -void ForceGrip( gentity_t *self ) -{//FIXME: make enemy Jedi able to use this - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt = NULL; +void ForceGrip(gentity_t *self) { // FIXME: make enemy Jedi able to use this + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt = NULL; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force grip when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force grip when zoomed in or in cinematic return; } - if ( self->client->ps.leanofs ) - {//can't force-grip while leaning + if (self->client->ps.leanofs) { // can't force-grip while leaning return; } - if ( self->client->ps.forceGripEntityNum <= ENTITYNUM_WORLD ) - {//already gripping - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - { + if (self->client->ps.forceGripEntityNum <= ENTITYNUM_WORLD) { // already gripping + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { self->client->ps.forcePowerDuration[FP_GRIP] = level.time + 100; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } } return; } - if ( !WP_ForcePowerUsable( self, FP_GRIP, 0 ) ) - {//can't use it right now + if (!WP_ForcePowerUsable(self, FP_GRIP, 0)) { // can't use it right now return; } - if ( self->client->ps.forcePower < 26 ) - {//need 20 to start, 6 to hold it for any decent amount of time... + if (self->client->ps.forcePower < 26) { // need 20 to start, 6 to hold it for any decent amount of time... return; } - if ( self->client->ps.weaponTime ) - {//busy + if (self->client->ps.weaponTime) { // busy return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - //Cause choking anim + health drain in ent in front of me - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // Cause choking anim + health drain in ent in front of me + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; - if ( self->client->ps.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * g_timescale->value ); + if (self->client->ps.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * g_timescale->value); } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( self->client->renderInfo.handLPoint, FORCE_GRIP_DIST, forward, end ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(self->client->renderInfo.handLPoint, FORCE_GRIP_DIST, forward, end); - if ( self->enemy && (self->s.number || InFront( self->enemy->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 0.2f ) ) ) - {//NPCs can always lift enemy since we assume they're looking at them, players need to be facing the enemy - if ( gi.inPVS( self->enemy->currentOrigin, self->client->renderInfo.eyePoint ) ) - {//must be in PVS - gi.trace( &tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, self->enemy->currentOrigin, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.fraction == 1.0f || tr.entityNum == self->enemy->s.number ) - {//must have clear LOS + if (self->enemy && + (self->s.number || InFront(self->enemy->currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, + 0.2f))) { // NPCs can always lift enemy since we assume they're looking at them, players need to be facing the enemy + if (gi.inPVS(self->enemy->currentOrigin, self->client->renderInfo.eyePoint)) { // must be in PVS + gi.trace(&tr, self->client->renderInfo.eyePoint, vec3_origin, vec3_origin, self->enemy->currentOrigin, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.fraction == 1.0f || tr.entityNum == self->enemy->s.number) { // must have clear LOS traceEnt = self->enemy; } } } - if ( !traceEnt ) - {//okay, trace straight ahead and see what's there - gi.trace( &tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + if (!traceEnt) { // okay, trace straight ahead and see what's there + gi.trace(&tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.entityNum >= ENTITYNUM_WORLD || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; } - if ( !traceEnt || traceEnt == self/*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) ) - { + if (!traceEnt || traceEnt == self /*???*/ || traceEnt->bmodel || (traceEnt->health <= 0 && traceEnt->takedamage) || + (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE)) { return; } - if ( traceEnt->client ) - { - if ( traceEnt->client->ps.forceJumpZStart ) - {//can't catch them in mid force jump - FIXME: maybe base it on velocity? + if (traceEnt->client) { + if (traceEnt->client->ps.forceJumpZStart) { // can't catch them in mid force jump - FIXME: maybe base it on velocity? return; } - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grip him, he's in armor - G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand( 3000, 5000 ) ); + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grip him, he's in armor + G_AddVoiceEvent(traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), Q_irand(3000, 5000)); return; break; - case CLASS_ATST://much too big to grip! + case CLASS_ATST: // much too big to grip! return; - //no droids either...? + // no droids either...? case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: case CLASS_MARK1: case CLASS_MARK2: - case CLASS_MOUSE://? + case CLASS_MOUSE: //? case CLASS_PROTOCOL: //*sigh*... in JK3, you'll be able to grab and move *anything*... return; @@ -6994,9 +5657,9 @@ void ForceGrip( gentity_t *self ) //*sigh*... in JK3, you'll be able to grab and move *anything*... return; break; - case CLASS_DESANN://Desann cannot be gripped, he just pushes you back instantly - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + case CLASS_DESANN: // Desann cannot be gripped, he just pushes you back instantly + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return; break; case CLASS_REBORN: @@ -7004,54 +5667,45 @@ void ForceGrip( gentity_t *self ) case CLASS_TAVION: case CLASS_JEDI: case CLASS_LUKE: - if ( traceEnt->NPC && traceEnt->NPC->rank > RANK_CIVILIAN && self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - { - Jedi_PlayDeflectSound( traceEnt ); - ForceThrow( traceEnt, qfalse ); + if (traceEnt->NPC && traceEnt->NPC->rank > RANK_CIVILIAN && self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { + Jedi_PlayDeflectSound(traceEnt); + ForceThrow(traceEnt, qfalse); return; } break; default: break; } - if ( traceEnt->s.weapon == WP_EMPLACED_GUN ) - {//FIXME: maybe can pull them out? + if (traceEnt->s.weapon == WP_EMPLACED_GUN) { // FIXME: maybe can pull them out? return; } - if ( self->enemy && traceEnt != self->enemy && traceEnt->client->playerTeam == self->client->playerTeam ) - {//can't accidently grip your teammate in combat + if (self->enemy && traceEnt != self->enemy && + traceEnt->client->playerTeam == self->client->playerTeam) { // can't accidently grip your teammate in combat return; } - } - else - {//can't grip non-clients... right? + } else { // can't grip non-clients... right? return; } - WP_ForcePowerStart( self, FP_GRIP, 20 ); - //FIXME: rule out other things? - //FIXME: Jedi resist, like the push and pull? + WP_ForcePowerStart(self, FP_GRIP, 20); + // FIXME: rule out other things? + // FIXME: Jedi resist, like the push and pull? self->client->ps.forceGripEntityNum = traceEnt->s.number; - //if ( traceEnt->client ) - { - G_AddVoiceEvent( traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 || traceEnt->s.weapon == WP_SABER ) - {//if we pick up & carry, drop their weap - if ( traceEnt->s.weapon ) - { - if ( traceEnt->s.weapon != WP_SABER ) - { - WP_DropWeapon( traceEnt, NULL ); - } - else - { - //turn it off? + // if ( traceEnt->client ) + { + G_AddVoiceEvent(traceEnt, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 || traceEnt->s.weapon == WP_SABER) { // if we pick up & carry, drop their weap + if (traceEnt->s.weapon) { + if (traceEnt->s.weapon != WP_SABER) { + WP_DropWeapon(traceEnt, NULL); + } else { + // turn it off? traceEnt->client->ps.saberActive = qfalse; - G_SoundOnEnt( traceEnt, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav" ); + G_SoundOnEnt(traceEnt, CHAN_WEAPON, "sound/weapons/saber/saberoffquick.wav"); } } } - //else FIXME: need a one-armed choke if we're not on a high enough level to make them drop their gun - VectorCopy( traceEnt->client->renderInfo.headPoint, self->client->ps.forceGripOrg ); + // else FIXME: need a one-armed choke if we're not on a high enough level to make them drop their gun + VectorCopy(traceEnt->client->renderInfo.headPoint, self->client->ps.forceGripOrg); } /* else @@ -7059,20 +5713,16 @@ void ForceGrip( gentity_t *self ) VectorCopy( traceEnt->currentOrigin, self->client->ps.forceGripOrg ); } */ - self->client->ps.forceGripOrg[2] += 48;//FIXME: define? - if ( self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//just a duration + self->client->ps.forceGripOrg[2] += 48; // FIXME: define? + if (self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // just a duration self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 250; self->client->ps.forcePowerDuration[FP_GRIP] = level.time + 5000; - traceEnt->s.loopSound = G_SoundIndex( "sound/weapons/force/grip.mp3" ); - } - else - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 ) - {//lifting sound? or always? + traceEnt->s.loopSound = G_SoundIndex("sound/weapons/force/grip.mp3"); + } else { + if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2) { // lifting sound? or always? } - //if ( traceEnt->s.number ) - {//picks them up for a second first + // if ( traceEnt->s.number ) + { // picks them up for a second first self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 1000; } /* @@ -7081,154 +5731,118 @@ void ForceGrip( gentity_t *self ) self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + 250; } */ - self->s.loopSound = G_SoundIndex( "sound/weapons/force/grip.mp3" ); + self->s.loopSound = G_SoundIndex("sound/weapons/force/grip.mp3"); } } -void ForceLightning( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceLightning(gentity_t *self) { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force lightning when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force lightning when zoomed in or in cinematic return; } - if ( self->client->ps.leanofs ) - {//can't force-lightning while leaning + if (self->client->ps.leanofs) { // can't force-lightning while leaning return; } - if ( self->client->ps.forcePower < 25 || !WP_ForcePowerUsable( self, FP_LIGHTNING, 0 ) ) - { + if (self->client->ps.forcePower < 25 || !WP_ForcePowerUsable(self, FP_LIGHTNING, 0)) { return; } - if ( self->client->ps.forcePowerDebounce[FP_LIGHTNING] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.forcePowerDebounce[FP_LIGHTNING] > level.time) { // stops it while using it and also after using it, up to 3 second delay return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - //Shoot lightning from hand - //make sure this plays and that you cannot press fire for about 1 second after this - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // Shoot lightning from hand + // make sure this plays and that you cannot press fire for about 1 second after this + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - {//short burst - //G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); - } - else - {//holding it - self->s.loopSound = G_SoundIndex( "sound/weapons/force/lightning2.wav" ); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/lightning.wav"); + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2) { // short burst + // G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/lightning.wav" ); + } else { // holding it + self->s.loopSound = G_SoundIndex("sound/weapons/force/lightning2.wav"); } - //FIXME: build-up or delay this until in proper part of anim + // FIXME: build-up or delay this until in proper part of anim self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - WP_ForcePowerStart( self, FP_LIGHTNING, self->client->ps.torsoAnimTimer ); + WP_ForcePowerStart(self, FP_LIGHTNING, self->client->ps.torsoAnimTimer); } -void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, float dist, float dot, vec3_t impactPoint ) -{ - if( traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE ) - { +void ForceLightningDamage(gentity_t *self, gentity_t *traceEnt, vec3_t dir, float dist, float dot, vec3_t impactPoint) { + if (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) { return; } - if ( traceEnt && traceEnt->takedamage ) - { - if ( !traceEnt->client || traceEnt->client->playerTeam != self->client->playerTeam || self->enemy == traceEnt || traceEnt->enemy == self ) - {//an enemy or object - int dmg; - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//more damage if closer and more in front + if (traceEnt && traceEnt->takedamage) { + if (!traceEnt->client || traceEnt->client->playerTeam != self->client->playerTeam || self->enemy == traceEnt || + traceEnt->enemy == self) { // an enemy or object + int dmg; + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // more damage if closer and more in front dmg = 1; - if ( dist < 100 ) - { + if (dist < 100) { dmg += 2; - } - else if ( dist < 200 ) - { + } else if (dist < 200) { dmg += 1; } - if ( dot > 0.9f ) - { + if (dot > 0.9f) { dmg += 2; - } - else if ( dot > 0.7f ) - { + } else if (dot > 0.7f) { dmg += 1; } + } else { + dmg = Q_irand(1, 3); //*self->client->ps.forcePowerLevel[FP_LIGHTNING]; } - else - { - dmg = Q_irand( 1, 3 );//*self->client->ps.forcePowerLevel[FP_LIGHTNING]; - } - if ( traceEnt->client && traceEnt->health > 0 && ( traceEnt->client->NPC_class == CLASS_DESANN || traceEnt->client->NPC_class == CLASS_LUKE ) ) - {//Luke and Desann can shield themselves from the attack - //FIXME: shield effect or something? + if (traceEnt->client && traceEnt->health > 0 && + (traceEnt->client->NPC_class == CLASS_DESANN || + traceEnt->client->NPC_class == CLASS_LUKE)) { // Luke and Desann can shield themselves from the attack + // FIXME: shield effect or something? int parts; - if ( traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim( traceEnt->client->ps.legsAnim ) && !PM_FlippingAnim( traceEnt->client->ps.legsAnim ) && !PM_RollingAnim( traceEnt->client->ps.legsAnim ) ) - {//if on a surface and not in a spin or flip, play full body resist + if (traceEnt->client->ps.groundEntityNum != ENTITYNUM_NONE && !PM_SpinningSaberAnim(traceEnt->client->ps.legsAnim) && + !PM_FlippingAnim(traceEnt->client->ps.legsAnim) && + !PM_RollingAnim(traceEnt->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body resist parts = SETANIM_BOTH; - } - else - {//play resist just in torso + } else { // play resist just in torso parts = SETANIM_TORSO; } - NPC_SetAnim( traceEnt, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - Jedi_PlayDeflectSound( traceEnt ); + NPC_SetAnim(traceEnt, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + Jedi_PlayDeflectSound(traceEnt); dmg = 0; - } - else if ( traceEnt->s.weapon == WP_SABER ) - { - if ( Q_irand( 0, 1 ) ) - {//jedi less likely to be damaged + } else if (traceEnt->s.weapon == WP_SABER) { + if (Q_irand(0, 1)) { // jedi less likely to be damaged dmg = 0; - } - else - { + } else { dmg = 1; } } - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAK ) - { - if ( traceEnt->client->ps.powerups[PW_GALAK_SHIELD] ) - {//has shield up + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAK) { + if (traceEnt->client->ps.powerups[PW_GALAK_SHIELD]) { // has shield up dmg = 0; } } - G_Damage( traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_ELECTROCUTE ); - if ( traceEnt->client ) - { - if ( !Q_irand( 0, 2 ) ) - { - G_Sound( traceEnt, G_SoundIndex( va( "sound/weapons/force/lightninghit%d.wav", Q_irand( 1, 3 ) ) ) ); + G_Damage(traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_ELECTROCUTE); + if (traceEnt->client) { + if (!Q_irand(0, 2)) { + G_Sound(traceEnt, G_SoundIndex(va("sound/weapons/force/lightninghit%d.wav", Q_irand(1, 3)))); } - traceEnt->s.powerups |= ( 1 << PW_SHOCKED ); + traceEnt->s.powerups |= (1 << PW_SHOCKED); // If we are dead or we are a bot, we can do the full version class_t npc_class = traceEnt->client->NPC_class; - if ( traceEnt->health <= 0 || ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || - npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || - npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST ) || - npc_class == CLASS_SENTRY ) - { + if (traceEnt->health <= 0 || + (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_REMOTE || npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || + npc_class == CLASS_MARK2 || npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST) || + npc_class == CLASS_SENTRY) { traceEnt->client->ps.powerups[PW_SHOCKED] = level.time + 4000; - } - else //short version + } else // short version { traceEnt->client->ps.powerups[PW_SHOCKED] = level.time + 500; } @@ -7237,329 +5851,259 @@ void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, flo } } -void ForceShootLightning( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; +void ForceShootLightning(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && cg.zoomMode ) - {//can't force lightning when zoomed in + if (!self->s.number && cg.zoomMode) { // can't force lightning when zoomed in return; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); - //FIXME: if lightning hits water, do water-only-flagged radius damage from that point - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t center, mins, maxs, dir, ent_org, size, v; - float radius = 512, dot, dist; - gentity_t *entityList[MAX_GENTITIES]; - int e, numListedEntities, i; + // FIXME: if lightning hits water, do water-only-flagged radius damage from that point + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t center, mins, maxs, dir, ent_org, size, v; + float radius = 512, dot, dist; + gentity_t *entityList[MAX_GENTITIES]; + int e, numListedEntities, i; - VectorCopy( self->currentOrigin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + VectorCopy(self->currentOrigin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = gi.EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { traceEnt = entityList[e]; - if ( !traceEnt ) + if (!traceEnt) continue; - if ( traceEnt == self ) + if (traceEnt == self) continue; - if ( traceEnt->owner == self && traceEnt->s.weapon != WP_THERMAL )//can push your own thermals + if (traceEnt->owner == self && traceEnt->s.weapon != WP_THERMAL) // can push your own thermals continue; - if ( !traceEnt->inuse ) + if (!traceEnt->inuse) continue; - if ( !traceEnt->takedamage ) + if (!traceEnt->takedamage) continue; - if ( traceEnt->health <= 0 )//no torturing corpses + if (traceEnt->health <= 0) // no torturing corpses continue; - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < traceEnt->absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < traceEnt->absmin[i]) { v[i] = traceEnt->absmin[i] - center[i]; - } else if ( center[i] > traceEnt->absmax[i] ) - { + } else if (center[i] > traceEnt->absmax[i]) { v[i] = center[i] - traceEnt->absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( traceEnt->absmax, traceEnt->absmin, size ); - VectorMA( traceEnt->absmin, 0.5, size, ent_org ); + VectorSubtract(traceEnt->absmax, traceEnt->absmin, size); + VectorMA(traceEnt->absmin, 0.5, size, ent_org); - //see if they're in front of me - //must be within the forward cone - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot = DotProduct( dir, forward )) < 0.5 ) + // see if they're in front of me + // must be within the forward cone + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot = DotProduct(dir, forward)) < 0.5) continue; - //must be close enough - dist = VectorLength( v ); - if ( dist >= radius ) - { + // must be close enough + dist = VectorLength(v); + if (dist >= radius) { continue; } - //in PVS? - if ( !traceEnt->bmodel && !gi.inPVS( ent_org, self->client->renderInfo.handLPoint ) ) - {//must be in PVS + // in PVS? + if (!traceEnt->bmodel && !gi.inPVS(ent_org, self->client->renderInfo.handLPoint)) { // must be in PVS continue; } - //Now check and see if we can actually hit it - gi.trace( &tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number ) - {//must have clear LOS + // Now check and see if we can actually hit it + gi.trace(&tr, self->client->renderInfo.handLPoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, G2_NOCOLLIDE, 0); + if (tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number) { // must have clear LOS continue; } // ok, we are within the radius, add us to the incoming list - //FIXME: maybe add up the ents and do more damage the less ents there are + // FIXME: maybe add up the ents and do more damage the less ents there are // as if we're spreading out the damage? - ForceLightningDamage( self, traceEnt, dir, dist, dot, ent_org ); + ForceLightningDamage(self, traceEnt, dir, dist, dot, ent_org); } - } - else - {//trace-line + } else { // trace-line int ignore = self->s.number; int traces = 0; - vec3_t start; + vec3_t start; - VectorCopy( self->client->renderInfo.handLPoint, start ); - VectorMA( self->client->renderInfo.handLPoint, 2048, forward, end ); + VectorCopy(self->client->renderInfo.handLPoint, start); + VectorMA(self->client->renderInfo.handLPoint, 2048, forward, end); - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - gi.trace( &tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + gi.trace(&tr, start, vec3_origin, vec3_origin, end, ignore, MASK_SHOT, G2_RETURNONHIT, 0); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; - //NOTE: only NPCs do this auto-dodge - if ( traceEnt && traceEnt->s.number && traceEnt->s.weapon == WP_SABER )//&& traceEnt->NPC - {//FIXME: need a more reliable way to know we hit a jedi? - if ( !Jedi_DodgeEvasion( traceEnt, self, &tr, HL_NONE ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + // NOTE: only NPCs do this auto-dodge + if (traceEnt && traceEnt->s.number && traceEnt->s.weapon == WP_SABER) //&& traceEnt->NPC + { // FIXME: need a more reliable way to know we hit a jedi? + if (!Jedi_DodgeEvasion(traceEnt, self, &tr, HL_NONE)) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } traceEnt = &g_entities[tr.entityNum]; - ForceLightningDamage( self, traceEnt, forward, 0, 0, tr.endpos ); + ForceLightningDamage(self, traceEnt, forward, 0, 0, tr.endpos); } } -void ForceJumpCharge( gentity_t *self, usercmd_t *ucmd ) -{ - float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME/FRAMETIME); +void ForceJumpCharge(gentity_t *self, usercmd_t *ucmd) { + float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && cg.zoomMode ) - {//can't force jump when zoomed in + if (!self->s.number && cg.zoomMode) { // can't force jump when zoomed in return; } - //need to play sound - if ( !self->client->ps.forceJumpCharge ) - {//FIXME: this should last only as long as the actual charge-up - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jumpbuild.wav" ); + // need to play sound + if (!self->client->ps.forceJumpCharge) { // FIXME: this should last only as long as the actual charge-up + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jumpbuild.wav"); } - //Increment + // Increment self->client->ps.forceJumpCharge += forceJumpChargeInterval; - //clamp to max strength for current level - if ( self->client->ps.forceJumpCharge > forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]] ) - { + // clamp to max strength for current level + if (self->client->ps.forceJumpCharge > forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]) { self->client->ps.forceJumpCharge = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]; } - //clamp to max available force power - if ( self->client->ps.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[FP_LEVITATION] > self->client->ps.forcePower ) - {//can't use more than you have - self->client->ps.forceJumpCharge = self->client->ps.forcePower*forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + // clamp to max available force power + if (self->client->ps.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * forcePowerNeeded[FP_LEVITATION] > + self->client->ps.forcePower) { // can't use more than you have + self->client->ps.forceJumpCharge = self->client->ps.forcePower * forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); } - //FIXME: a simple tap should always do at least a normal height's jump? + // FIXME: a simple tap should always do at least a normal height's jump? } -int WP_GetVelocityForForceJump( gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd ) -{ +int WP_GetVelocityForForceJump(gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd) { float pushFwd = 0, pushRt = 0; - vec3_t view, forward, right; - VectorCopy( self->client->ps.viewangles, view ); + vec3_t view, forward, right; + VectorCopy(self->client->ps.viewangles, view); view[0] = 0; - AngleVectors( view, forward, right, NULL ); - if ( ucmd->forwardmove && ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + AngleVectors(view, forward, right, NULL); + if (ucmd->forwardmove && ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 50; - } - else - { + } else { pushFwd = -50; } - if ( ucmd->rightmove > 0 ) - { + if (ucmd->rightmove > 0) { pushRt = 50; - } - else - { + } else { pushRt = -50; } - } - else if ( ucmd->forwardmove || ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + } else if (ucmd->forwardmove || ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 100; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { pushFwd = -100; - } - else if ( ucmd->rightmove > 0 ) - { + } else if (ucmd->rightmove > 0) { pushRt = 100; - } - else if ( ucmd->rightmove < 0 ) - { + } else if (ucmd->rightmove < 0) { pushRt = -100; } } - VectorMA( self->client->ps.velocity, pushFwd, forward, jumpVel ); - VectorMA( self->client->ps.velocity, pushRt, right, jumpVel ); - jumpVel[2] += self->client->ps.forceJumpCharge;//forceJumpStrength; - if ( pushFwd > 0 && self->client->ps.forceJumpCharge > 200 ) - { + VectorMA(self->client->ps.velocity, pushFwd, forward, jumpVel); + VectorMA(self->client->ps.velocity, pushRt, right, jumpVel); + jumpVel[2] += self->client->ps.forceJumpCharge; // forceJumpStrength; + if (pushFwd > 0 && self->client->ps.forceJumpCharge > 200) { return FJ_FORWARD; - } - else if ( pushFwd < 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushFwd < 0 && self->client->ps.forceJumpCharge > 200) { return FJ_BACKWARD; - } - else if ( pushRt > 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushRt > 0 && self->client->ps.forceJumpCharge > 200) { return FJ_RIGHT; - } - else if ( pushRt < 0 && self->client->ps.forceJumpCharge > 200 ) - { + } else if (pushRt < 0 && self->client->ps.forceJumpCharge > 200) { return FJ_LEFT; - } - else - {//FIXME: jump straight up anim + } else { // FIXME: jump straight up anim return FJ_UP; } } -void ForceJump( gentity_t *self, usercmd_t *ucmd ) -{ - if ( self->client->ps.forcePowerDuration[FP_LEVITATION] > level.time ) - { +void ForceJump(gentity_t *self, usercmd_t *ucmd) { + if (self->client->ps.forcePowerDuration[FP_LEVITATION] > level.time) { return; } - if ( !WP_ForcePowerUsable( self, FP_LEVITATION, 0 ) ) - { + if (!WP_ForcePowerUsable(self, FP_LEVITATION, 0)) { return; } - if ( self->s.groundEntityNum == ENTITYNUM_NONE ) - { + if (self->s.groundEntityNum == ENTITYNUM_NONE) { return; } - if ( self->client->ps.pm_flags&PMF_JUMP_HELD ) - { + if (self->client->ps.pm_flags & PMF_JUMP_HELD) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !self->s.number && (cg.zoomMode || in_camera) ) - {//can't force jump when zoomed in or in cinematic + if (!self->s.number && (cg.zoomMode || in_camera)) { // can't force jump when zoomed in or in cinematic return; } - if ( self->client->ps.saberLockTime > level.time ) - {//FIXME: can this be a way to break out? + if (self->client->ps.saberLockTime > level.time) { // FIXME: can this be a way to break out? return; } - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); - float forceJumpChargeInterval = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]]/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + float forceJumpChargeInterval = forceJumpStrength[self->client->ps.forcePowerLevel[FP_LEVITATION]] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); int anim; - vec3_t jumpVel; + vec3_t jumpVel; - switch( WP_GetVelocityForForceJump( self, jumpVel, ucmd ) ) - { + switch (WP_GetVelocityForForceJump(self, jumpVel, ucmd)) { case FJ_FORWARD: - if ( self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG ) - {//can't do acrobatics + if (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG) { // can't do acrobatics anim = BOTH_FORCEJUMP1; - } - else - { + } else { anim = BOTH_FLIP_F; } break; case FJ_BACKWARD: - if ( self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG ) - {//can't do acrobatics + if (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG) { // can't do acrobatics anim = BOTH_FORCEJUMPBACK1; - } - else - { + } else { anim = BOTH_FLIP_B; } break; case FJ_RIGHT: - if ( self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG ) - {//can't do acrobatics + if (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG) { // can't do acrobatics anim = BOTH_FORCEJUMPRIGHT1; - } - else - { + } else { anim = BOTH_FLIP_R; } break; case FJ_LEFT: - if ( self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG ) - {//can't do acrobatics + if (self->NPC && self->NPC->rank != RANK_CREWMAN && self->NPC->rank <= RANK_LT_JG) { // can't do acrobatics anim = BOTH_FORCEJUMPLEFT1; - } - else - { + } else { anim = BOTH_FLIP_L; } break; @@ -7569,94 +6113,82 @@ void ForceJump( gentity_t *self, usercmd_t *ucmd ) break; } - int parts = SETANIM_BOTH; - if ( self->client->ps.weaponTime ) - {//FIXME: really only care if we're in a saber attack anim.. maybe trail length? + int parts = SETANIM_BOTH; + if (self->client->ps.weaponTime) { // FIXME: really only care if we're in a saber attack anim.. maybe trail length? parts = SETANIM_LEGS; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - //FIXME: sound effect - self->client->ps.forceJumpZStart = self->currentOrigin[2];//remember this for when we land - VectorCopy( jumpVel, self->client->ps.velocity ); - //wasn't allowing them to attack when jumping, but that was annoying - //self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; + // FIXME: sound effect + self->client->ps.forceJumpZStart = self->currentOrigin[2]; // remember this for when we land + VectorCopy(jumpVel, self->client->ps.velocity); + // wasn't allowing them to attack when jumping, but that was annoying + // self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - WP_ForcePowerStart( self, FP_LEVITATION, self->client->ps.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[FP_LEVITATION] ); - //self->client->ps.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; + WP_ForcePowerStart(self, FP_LEVITATION, + self->client->ps.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * forcePowerNeeded[FP_LEVITATION]); + // self->client->ps.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; self->client->ps.forceJumpCharge = 0; } -void WP_ForcePowerRegenerate( gentity_t *self, int overrideAmt ) -{ - if ( !self->client ) - { +void WP_ForcePowerRegenerate(gentity_t *self, int overrideAmt) { + if (!self->client) { return; } - if ( self->client->ps.forcePower < self->client->ps.forcePowerMax ) - { - if ( overrideAmt ) - { + if (self->client->ps.forcePower < self->client->ps.forcePowerMax) { + if (overrideAmt) { self->client->ps.forcePower += overrideAmt; - } - else - { + } else { self->client->ps.forcePower++; } - if ( self->client->ps.forcePower > self->client->ps.forcePowerMax ) - { + if (self->client->ps.forcePower > self->client->ps.forcePowerMax) { self->client->ps.forcePower = self->client->ps.forcePowerMax; } } } -void WP_ForcePowerDrain( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - if ( self->NPC ) - {//For now, NPCs have infinite force power +void WP_ForcePowerDrain(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + if (self->NPC) { // For now, NPCs have infinite force power return; } - //take away the power - int drain = overrideAmt; - if ( !drain ) - { + // take away the power + int drain = overrideAmt; + if (!drain) { drain = forcePowerNeeded[forcePower]; } - if ( !drain ) - { + if (!drain) { return; } self->client->ps.forcePower -= drain; - if ( self->client->ps.forcePower < 0 ) - { + if (self->client->ps.forcePower < 0) { self->client->ps.forcePower = 0; } } -void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - int duration = 0; +void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + int duration = 0; - //FIXME: debounce some of these + // FIXME: debounce some of these - //and it in - //set up duration time - switch( (int)forcePower ) - { + // and it in + // set up duration time + switch ((int)forcePower) { case FP_HEAL: - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); self->client->ps.forceHealCount = 0; break; case FP_LEVITATION: - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; case FP_SPEED: - //duration is always 5 seconds, player time - duration = ceil(FORCE_SPEED_DURATION*forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]);//FIXME: because the timescale scales down (not instant), this doesn't end up being exactly right... - self->client->ps.forcePowersActive |= ( 1 << forcePower ); - self->s.loopSound = G_SoundIndex( "sound/weapons/force/speedloop.wav" ); + // duration is always 5 seconds, player time + duration = + ceil(FORCE_SPEED_DURATION * forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]); // FIXME: because the timescale scales down (not instant), + // this doesn't end up being exactly right... + self->client->ps.forcePowersActive |= (1 << forcePower); + self->s.loopSound = G_SoundIndex("sound/weapons/force/speedloop.wav"); break; case FP_PUSH: break; @@ -7666,75 +6198,63 @@ void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int override break; case FP_GRIP: duration = 1000; - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; case FP_LIGHTNING: duration = overrideAmt; overrideAmt = 0; - self->client->ps.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.forcePowersActive |= (1 << forcePower); break; default: break; } - if ( duration ) - { + if (duration) { self->client->ps.forcePowerDuration[forcePower] = level.time + duration; - } - else - { + } else { self->client->ps.forcePowerDuration[forcePower] = 0; } self->client->ps.forcePowerDebounce[forcePower] = 0; - WP_ForcePowerDrain( self, forcePower, overrideAmt ); + WP_ForcePowerDrain(self, forcePower, overrideAmt); - if ( !self->s.number ) - { + if (!self->s.number) { self->client->sess.missionStats.forceUsed[(int)forcePower]++; } } -qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - if ( forcePower == FP_LEVITATION ) - { +qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + if (forcePower == FP_LEVITATION) { return qtrue; } - int drain = overrideAmt?overrideAmt:forcePowerNeeded[forcePower]; - if ( !drain ) - { + int drain = overrideAmt ? overrideAmt : forcePowerNeeded[forcePower]; + if (!drain) { return qtrue; } - if ( self->client->ps.forcePower < drain ) - { - //G_AddEvent( self, EV_NOAMMO, 0 ); + if (self->client->ps.forcePower < drain) { + // G_AddEvent( self, EV_NOAMMO, 0 ); return qfalse; } return qtrue; } -extern void CG_PlayerLockedWeaponSpeech( int jumping ); -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ +extern void CG_PlayerLockedWeaponSpeech(int jumping); +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { - if ( !(self->client->ps.forcePowersKnown & ( 1 << forcePower )) ) - {//don't know this power + if (!(self->client->ps.forcePowersKnown & (1 << forcePower))) { // don't know this power return qfalse; } - if ( self->client->ps.forcePowerLevel[forcePower] <= 0 ) - {//can't use this power + if (self->client->ps.forcePowerLevel[forcePower] <= 0) { // can't use this power return qfalse; } - if( self->flags & FL_LOCK_PLAYER_WEAPONS ) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one + if (self->flags & FL_LOCK_PLAYER_WEAPONS) // yes this locked weapons check also includes force powers, if we need a separate check later I'll make one { - CG_PlayerLockedWeaponSpeech( qfalse ); + CG_PlayerLockedWeaponSpeech(qfalse); return qfalse; } - if ( (self->client->ps.forcePowersActive & ( 1 << forcePower )) ) - {//already using this power + if ((self->client->ps.forcePowersActive & (1 << forcePower))) { // already using this power return qfalse; } /* @@ -7743,49 +6263,40 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower, int ove return qfalse; } */ - if ( self->client->NPC_class == CLASS_ATST ) - {//Doh! No force powers in an AT-ST! + if (self->client->NPC_class == CLASS_ATST) { // Doh! No force powers in an AT-ST! return qfalse; } - if ( self->client->ps.vehicleModel != 0 ) - {//Doh! No force powers when flying a vehicle! + if (self->client->ps.vehicleModel != 0) { // Doh! No force powers when flying a vehicle! return qfalse; } - if ( self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD ) - {//Doh! No force powers when controlling an NPC + if (self->client->ps.viewEntity > 0 && self->client->ps.viewEntity < ENTITYNUM_WORLD) { // Doh! No force powers when controlling an NPC return qfalse; } - if ( self->client->ps.eFlags & EF_LOCKED_TO_WEAPON ) - {//Doh! No force powers when in an emplaced gun! + if (self->client->ps.eFlags & EF_LOCKED_TO_WEAPON) { // Doh! No force powers when in an emplaced gun! return qfalse; } - return WP_ForcePowerAvailable( self, forcePower, overrideAmt ); + return WP_ForcePowerAvailable(self, forcePower, overrideAmt); } -void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) -{ - gentity_t *gripEnt; +void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower) { + gentity_t *gripEnt; - self->client->ps.forcePowersActive &= ~( 1 << forcePower ); + self->client->ps.forcePowersActive &= ~(1 << forcePower); - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: - //if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 ) - {//wasn't an instant heal and heal is now done - if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 ) - {//if in meditation pose, must come out of it - //FIXME: BOTH_FORCEHEAL_STOP - if ( self->client->ps.legsAnim == BOTH_FORCEHEAL_START ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 ) + { // wasn't an instant heal and heal is now done + if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2) { // if in meditation pose, must come out of it + // FIXME: BOTH_FORCEHEAL_STOP + if (self->client->ps.legsAnim == BOTH_FORCEHEAL_START) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_FORCEHEAL_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCEHEAL_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEHEAL_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY; // don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; } } @@ -7794,14 +6305,12 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->client->ps.forcePowerDebounce[FP_LEVITATION] = 0; break; case FP_SPEED: - if ( !self->s.number ) - {//player using force speed - if ( g_timescale->value != 1.0 ) - { + if (!self->s.number) { // player using force speed + if (g_timescale->value != 1.0) { gi.cvar_set("timescale", "1"); } } - //FIXME: reset my current anim, keeping current frame, but with proper anim speed + // FIXME: reset my current anim, keeping current frame, but with proper anim speed // otherwise, the anim will continue playing at high speed self->s.loopSound = 0; break; @@ -7812,101 +6321,73 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) case FP_TELEPATHY: break; case FP_GRIP: - if ( self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD ) - { + if (self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD) { gripEnt = &g_entities[self->client->ps.forceGripEntityNum]; - if ( gripEnt ) - { + if (gripEnt) { gripEnt->s.loopSound = 0; - if ( gripEnt->client ) - { + if (gripEnt->client) { gripEnt->client->ps.eFlags &= ~EF_FORCE_GRIPPED; - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//sanity-cap the velocity - float gripVel = VectorNormalize( gripEnt->client->ps.velocity ); - if ( gripVel > 500.0f ) - { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // sanity-cap the velocity + float gripVel = VectorNormalize(gripEnt->client->ps.velocity); + if (gripVel > 500.0f) { gripVel = 500.0f; } - VectorScale( gripEnt->client->ps.velocity, gripVel, gripEnt->client->ps.velocity ); + VectorScale(gripEnt->client->ps.velocity, gripVel, gripEnt->client->ps.velocity); } - //FIXME: they probably dropped their weapon, should we make them flee? Or should AI handle no-weapon behavior? - if ( gripEnt->health > 0 ) - { - int holdTime = 500; - G_AddEvent( gripEnt, EV_WATER_CLEAR, 0 ); - if ( gripEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time ) - {//they probably pushed out of it + // FIXME: they probably dropped their weapon, should we make them flee? Or should AI handle no-weapon behavior? + if (gripEnt->health > 0) { + int holdTime = 500; + G_AddEvent(gripEnt, EV_WATER_CLEAR, 0); + if (gripEnt->client->ps.forcePowerDebounce[FP_PUSH] > level.time) { // they probably pushed out of it holdTime = 0; + } else if (gripEnt->s.weapon == WP_SABER) { // jedi recover faster + holdTime = self->client->ps.forcePowerLevel[FP_GRIP] * 200; + } else { + holdTime = self->client->ps.forcePowerLevel[FP_GRIP] * 500; } - else if ( gripEnt->s.weapon == WP_SABER ) - {//jedi recover faster - holdTime = self->client->ps.forcePowerLevel[FP_GRIP]*200; - } - else - { - holdTime = self->client->ps.forcePowerLevel[FP_GRIP]*500; - } - //stop the anims soon, keep them locked in place for a bit - if ( gripEnt->client->ps.torsoAnim == BOTH_CHOKE1 || gripEnt->client->ps.torsoAnim == BOTH_CHOKE3 ) - {//stop choking anim on torso - if ( gripEnt->client->ps.torsoAnimTimer > holdTime ) - { + // stop the anims soon, keep them locked in place for a bit + if (gripEnt->client->ps.torsoAnim == BOTH_CHOKE1 || gripEnt->client->ps.torsoAnim == BOTH_CHOKE3) { // stop choking anim on torso + if (gripEnt->client->ps.torsoAnimTimer > holdTime) { gripEnt->client->ps.torsoAnimTimer = holdTime; } } - if ( gripEnt->client->ps.legsAnim == BOTH_CHOKE1 || gripEnt->client->ps.legsAnim == BOTH_CHOKE3 ) - {//stop choking anim on legs + if (gripEnt->client->ps.legsAnim == BOTH_CHOKE1 || gripEnt->client->ps.legsAnim == BOTH_CHOKE3) { // stop choking anim on legs gripEnt->client->ps.legsAnimTimer = 0; - if ( holdTime ) - { - //lock them in place for a bit + if (holdTime) { + // lock them in place for a bit gripEnt->client->ps.pm_time = gripEnt->client->ps.torsoAnimTimer; gripEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( gripEnt->s.number ) - {//NPC + if (gripEnt->s.number) { // NPC gripEnt->painDebounceTime = level.time + gripEnt->client->ps.torsoAnimTimer; - } - else - {//player + } else { // player gripEnt->aimDebounceTime = level.time + gripEnt->client->ps.torsoAnimTimer; } } } - if ( gripEnt->NPC ) - { - if ( !(gripEnt->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//not falling to their death + if (gripEnt->NPC) { + if (!(gripEnt->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // not falling to their death gripEnt->NPC->nextBStateThink = level.time + holdTime; } - //if still alive after stopped gripping, let them wake others up - G_AngerAlert( gripEnt ); + // if still alive after stopped gripping, let them wake others up + G_AngerAlert(gripEnt); } } - } - else - { + } else { gripEnt->s.eFlags &= ~EF_FORCE_GRIPPED; - if ( gripEnt->s.eType == ET_MISSILE ) - {//continue normal movement - if ( gripEnt->s.weapon == WP_THERMAL ) - { + if (gripEnt->s.eType == ET_MISSILE) { // continue normal movement + if (gripEnt->s.weapon == WP_THERMAL) { gripEnt->s.pos.trType = TR_INTERPOLATE; + } else { + gripEnt->s.pos.trType = TR_LINEAR; // FIXME: what about gravity-effected projectiles? } - else - { - gripEnt->s.pos.trType = TR_LINEAR;//FIXME: what about gravity-effected projectiles? - } - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); gripEnt->s.pos.trTime = level.time; - } - else - {//drop it + } else { // drop it gripEnt->e_ThinkFunc = thinkF_G_RunObject; gripEnt->nextthink = level.time + FRAMETIME; gripEnt->s.pos.trType = TR_GRAVITY; - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); gripEnt->s.pos.trTime = level.time; } } @@ -7914,24 +6395,19 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->s.loopSound = 0; self->client->ps.forceGripEntityNum = ENTITYNUM_NONE; } - if ( self->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD ) - { - NPC_SetAnim( self, BOTH_FORCEGRIP_RELEASE, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCEGRIP_HOLD) { + NPC_SetAnim(self, BOTH_FORCEGRIP_RELEASE, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } break; case FP_LIGHTNING: - if ( self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_HOLD - || self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - {//don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) - self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 3000;//FIXME: define? - } - else - {//stop the looping sound - self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 1000;//FIXME: define? + if (self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_HOLD || self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_RELEASE, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] < + FORCE_LEVEL_2) { // don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) + self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 3000; // FIXME: define? + } else { // stop the looping sound + self->client->ps.forcePowerDebounce[FP_LIGHTNING] = level.time + 1000; // FIXME: define? self->s.loopSound = 0; } break; @@ -7940,105 +6416,77 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) } } -extern qboolean PM_ForceJumpingUp( gentity_t *gent ); -static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd ) -{ - float speed, newSpeed; - gentity_t *gripEnt; - vec3_t angles, dir, gripOrg, gripEntOrg; - float dist; - extern usercmd_t ucmd; +extern qboolean PM_ForceJumpingUp(gentity_t *gent); +static void WP_ForcePowerRun(gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd) { + float speed, newSpeed; + gentity_t *gripEnt; + vec3_t angles, dir, gripOrg, gripEntOrg; + float dist; + extern usercmd_t ucmd; - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: - if ( self->client->ps.forceHealCount >= MAX_FORCE_HEAL || self->health >= self->client->ps.stats[STAT_MAX_HEALTH] ) - {//fully healed or used up all 25 - if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - { - G_SoundOnEnt( self, CHAN_VOICE, va( "sound/weapons/force/heal%d.mp3", Q_irand( 1, 4 ) ) ); - } - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 && ( (cmd->buttons&BUTTON_ATTACK) || (cmd->buttons&BUTTON_ALT_ATTACK) || self->painDebounceTime > level.time || (self->client->ps.weaponTime&&self->client->ps.weapon!=WP_NONE) ) ) - {//attacked or was hit while healing... - //stop healing - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 && ( cmd->rightmove || cmd->forwardmove || cmd->upmove > 0 ) ) - {//moved while healing... FIXME: also, in WP_ForcePowerStart, stop healing if any other force power is used - //stop healing - WP_ForcePowerStop( self, forcePower ); - } - else if ( self->client->ps.forcePowerDebounce[FP_HEAL] < level.time ) - {//time to heal again - if ( WP_ForcePowerAvailable( self, forcePower, 4 ) ) - {//have available power + if (self->client->ps.forceHealCount >= MAX_FORCE_HEAL || self->health >= self->client->ps.stats[STAT_MAX_HEALTH]) { // fully healed or used up all 25 + if (!Q3_TaskIDPending(self, TID_CHAN_VOICE)) { + G_SoundOnEnt(self, CHAN_VOICE, va("sound/weapons/force/heal%d.mp3", Q_irand(1, 4))); + } + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3 && + ((cmd->buttons & BUTTON_ATTACK) || (cmd->buttons & BUTTON_ALT_ATTACK) || self->painDebounceTime > level.time || + (self->client->ps.weaponTime && self->client->ps.weapon != WP_NONE))) { // attacked or was hit while healing... + // stop healing + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2 && + (cmd->rightmove || cmd->forwardmove || + cmd->upmove > 0)) { // moved while healing... FIXME: also, in WP_ForcePowerStart, stop healing if any other force power is used + // stop healing + WP_ForcePowerStop(self, forcePower); + } else if (self->client->ps.forcePowerDebounce[FP_HEAL] < level.time) { // time to heal again + if (WP_ForcePowerAvailable(self, forcePower, 4)) { // have available power self->health++; self->client->ps.forceHealCount++; - if ( self->client->ps.forcePowerLevel[FP_HEAL] > FORCE_LEVEL_2 ) - { + if (self->client->ps.forcePowerLevel[FP_HEAL] > FORCE_LEVEL_2) { self->client->ps.forcePowerDebounce[FP_HEAL] = level.time + 50; - } - else - { + } else { self->client->ps.forcePowerDebounce[FP_HEAL] = level.time + FORCE_HEAL_INTERVAL; } - WP_ForcePowerDrain( self, forcePower, 4 ); - } - else - {//stop - WP_ForcePowerStop( self, forcePower ); + WP_ForcePowerDrain(self, forcePower, 4); + } else { // stop + WP_ForcePowerStop(self, forcePower); } } break; case FP_LEVITATION: - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceJumpZStart ) - {//done with jump - WP_ForcePowerStop( self, forcePower ); - } - else - { - if ( PM_ForceJumpingUp( self ) ) - {//holding jump in air - if ( cmd->upmove > 10 ) - {//still trying to go up - if ( WP_ForcePowerAvailable( self, FP_LEVITATION, 1 ) ) - { - if ( self->client->ps.forcePowerDebounce[FP_LEVITATION] < level.time ) - { - WP_ForcePowerDrain( self, FP_LEVITATION, 5 ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceJumpZStart) { // done with jump + WP_ForcePowerStop(self, forcePower); + } else { + if (PM_ForceJumpingUp(self)) { // holding jump in air + if (cmd->upmove > 10) { // still trying to go up + if (WP_ForcePowerAvailable(self, FP_LEVITATION, 1)) { + if (self->client->ps.forcePowerDebounce[FP_LEVITATION] < level.time) { + WP_ForcePowerDrain(self, FP_LEVITATION, 5); self->client->ps.forcePowerDebounce[FP_LEVITATION] = level.time + 100; } - self->client->ps.forcePowersActive |= ( 1 << FP_LEVITATION ); - self->client->ps.forceJumpCharge = 1;//just used as a flag for the player, cleared when he lands - } - else - {//cut the jump short - WP_ForcePowerStop( self, forcePower ); + self->client->ps.forcePowersActive |= (1 << FP_LEVITATION); + self->client->ps.forceJumpCharge = 1; // just used as a flag for the player, cleared when he lands + } else { // cut the jump short + WP_ForcePowerStop(self, forcePower); } + } else { // cut the jump short + WP_ForcePowerStop(self, forcePower); } - else - {//cut the jump short - WP_ForcePowerStop( self, forcePower ); - } - } - else - { - WP_ForcePowerStop( self, forcePower ); + } else { + WP_ForcePowerStop(self, forcePower); } } break; case FP_SPEED: speed = forceSpeedValue[self->client->ps.forcePowerLevel[FP_SPEED]]; - if ( !self->s.number ) - {//player using force speed + if (!self->s.number) { // player using force speed gi.cvar_set("timescale", va("%4.2f", speed)); - if ( g_timescale->value > speed ) - { + if (g_timescale->value > speed) { newSpeed = g_timescale->value - 0.05; - if ( newSpeed < speed ) - { + if (newSpeed < speed) { newSpeed = speed; } gi.cvar_set("timescale", va("%4.2f", newSpeed)); @@ -8052,148 +6500,113 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd case FP_TELEPATHY: break; case FP_GRIP: - if ( !WP_ForcePowerAvailable( self, FP_GRIP, 0 ) - || (self->client->ps.forcePowerLevel[FP_GRIP]>FORCE_LEVEL_1&&!self->s.number&&!(cmd->buttons&BUTTON_FORCEGRIP)) ) - { - WP_ForcePowerStop( self, FP_GRIP ); + if (!WP_ForcePowerAvailable(self, FP_GRIP, 0) || + (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 && !self->s.number && !(cmd->buttons & BUTTON_FORCEGRIP))) { + WP_ForcePowerStop(self, FP_GRIP); return; - } - else if ( self->client->ps.forceGripEntityNum >= 0 && self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD ) - { + } else if (self->client->ps.forceGripEntityNum >= 0 && self->client->ps.forceGripEntityNum < ENTITYNUM_WORLD) { gripEnt = &g_entities[self->client->ps.forceGripEntityNum]; - if ( !gripEnt || (gripEnt->health <= 0&&gripEnt->takedamage) )//FIXME: what about things that never had health or lose takedamage when they die? - {//either invalid ent, or dead ent - WP_ForcePowerStop( self, FP_GRIP ); + if (!gripEnt || (gripEnt->health <= 0 && gripEnt->takedamage)) // FIXME: what about things that never had health or lose takedamage when they die? + { // either invalid ent, or dead ent + WP_ForcePowerStop(self, FP_GRIP); return; - } - else if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_1 - && gripEnt->client - && gripEnt->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { - WP_ForcePowerStop( self, FP_GRIP ); + } else if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_1 && gripEnt->client && gripEnt->client->ps.groundEntityNum == ENTITYNUM_NONE) { + WP_ForcePowerStop(self, FP_GRIP); return; - } - else if ( gripEnt->s.weapon == WP_SABER && gripEnt->NPC && gripEnt->client && gripEnt->client->ps.forcePowersKnown&(1<NPC->stats.evasion*10)-(g_spskill->integer*10) ) ) - {//a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? - ForceThrow( gripEnt, qfalse ); - //FIXME: I need to go into some pushed back anim... - WP_ForcePowerStop( self, FP_GRIP ); + } else if (gripEnt->s.weapon == WP_SABER && gripEnt->NPC && gripEnt->client && gripEnt->client->ps.forcePowersKnown & (1 << FP_PUSH) && + !Q_irand(0, 100 - (gripEnt->NPC->stats.evasion * 10) - + (g_spskill->integer * 10))) { // a jedi who broke free FIXME: maybe have some minimum grip length- a reaction time? + ForceThrow(gripEnt, qfalse); + // FIXME: I need to go into some pushed back anim... + WP_ForcePowerStop(self, FP_GRIP); return; - } - else - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//holding it - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // holding it + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCEGRIP_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //get their org - VectorCopy( self->client->ps.viewangles, angles ); + // get their org + VectorCopy(self->client->ps.viewangles, angles); angles[0] -= 10; - AngleVectors( angles, dir, NULL, NULL ); - if ( gripEnt->client ) - {//move - VectorCopy( gripEnt->client->renderInfo.headPoint, gripEntOrg ); - } - else - { - VectorCopy( gripEnt->currentOrigin, gripEntOrg ); - } - - //how far are they - dist = Distance( self->client->renderInfo.handLPoint, gripEntOrg ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 && - (!InFront( gripEntOrg, self->client->renderInfo.handLPoint, self->client->ps.viewangles, 0.3f ) || - DistanceSquared( gripEntOrg, self->client->renderInfo.handLPoint ) > FORCE_GRIP_DIST_SQUARED)) - {//must face them - WP_ForcePowerStop( self, FP_GRIP ); + AngleVectors(angles, dir, NULL, NULL); + if (gripEnt->client) { // move + VectorCopy(gripEnt->client->renderInfo.headPoint, gripEntOrg); + } else { + VectorCopy(gripEnt->currentOrigin, gripEntOrg); + } + + // how far are they + dist = Distance(self->client->renderInfo.handLPoint, gripEntOrg); + if (self->client->ps.forcePowerLevel[FP_GRIP] == FORCE_LEVEL_2 && + (!InFront(gripEntOrg, self->client->renderInfo.handLPoint, self->client->ps.viewangles, 0.3f) || + DistanceSquared(gripEntOrg, self->client->renderInfo.handLPoint) > FORCE_GRIP_DIST_SQUARED)) { // must face them + WP_ForcePowerStop(self, FP_GRIP); return; } - //check for lift or carry - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 ) - {//carry - //cap dist - if ( dist > 256 ) - { + // check for lift or carry + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2) { // carry + // cap dist + if (dist > 256) { dist = 256; - } - else if ( dist < 128 ) - { + } else if (dist < 128) { dist = 128; } - VectorMA( self->client->renderInfo.handLPoint, dist, dir, gripOrg ); - } - else if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//just lift - VectorCopy( self->client->ps.forceGripOrg, gripOrg ); - } - else - { - VectorCopy( gripEnt->currentOrigin, gripOrg ); - } - //now move them - if ( gripEnt->client ) - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - VectorSubtract( gripOrg, gripEntOrg, gripEnt->client->ps.velocity ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 ) - {//level 2 just lifts them - float gripDist = VectorNormalize( gripEnt->client->ps.velocity )/3.0f; - if ( gripDist < 5.0f ) - { + VectorMA(self->client->renderInfo.handLPoint, dist, dir, gripOrg); + } else if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // just lift + VectorCopy(self->client->ps.forceGripOrg, gripOrg); + } else { + VectorCopy(gripEnt->currentOrigin, gripOrg); + } + // now move them + if (gripEnt->client) { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + VectorSubtract(gripOrg, gripEntOrg, gripEnt->client->ps.velocity); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2) { // level 2 just lifts them + float gripDist = VectorNormalize(gripEnt->client->ps.velocity) / 3.0f; + if (gripDist < 5.0f) { gripDist = 5.0f; } - VectorScale( gripEnt->client->ps.velocity, (gripDist*gripDist), gripEnt->client->ps.velocity ); + VectorScale(gripEnt->client->ps.velocity, (gripDist * gripDist), gripEnt->client->ps.velocity); } } - //stop them from thinking + // stop them from thinking gripEnt->client->ps.pm_time = 2000; gripEnt->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - if ( gripEnt->NPC ) - { - if ( !(gripEnt->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - {//not falling to their death + if (gripEnt->NPC) { + if (!(gripEnt->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { // not falling to their death gripEnt->NPC->nextBStateThink = level.time + 2000; } - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - vectoangles( dir, angles ); - gripEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW]+180); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + vectoangles(dir, angles); + gripEnt->NPC->desiredYaw = AngleNormalize180(angles[YAW] + 180); gripEnt->NPC->desiredPitch = -angles[PITCH]; SaveNPCGlobals(); - SetNPCGlobals( gripEnt ); - NPC_UpdateAngles( qtrue, qtrue ); + SetNPCGlobals(gripEnt); + NPC_UpdateAngles(qtrue, qtrue); gripEnt->NPC->last_ucmd.angles[0] = ucmd.angles[0]; gripEnt->NPC->last_ucmd.angles[1] = ucmd.angles[1]; gripEnt->NPC->last_ucmd.angles[2] = ucmd.angles[2]; RestoreNPCGlobals(); - //FIXME: why does he turn back to his original angles once he dies or is let go? + // FIXME: why does he turn back to his original angles once he dies or is let go? } - } - else if ( !gripEnt->s.number ) - { - //vectoangles( dir, angles ); - //gripEnt->client->ps.viewangles[0] = -angles[0]; - //gripEnt->client->ps.viewangles[1] = AngleNormalize180(angles[YAW]+180); + } else if (!gripEnt->s.number) { + // vectoangles( dir, angles ); + // gripEnt->client->ps.viewangles[0] = -angles[0]; + // gripEnt->client->ps.viewangles[1] = AngleNormalize180(angles[YAW]+180); gripEnt->enemy = self; - NPC_SetLookTarget( gripEnt, self->s.number, level.time+1000 ); + NPC_SetLookTarget(gripEnt, self->s.number, level.time + 1000); } gripEnt->client->ps.eFlags |= EF_FORCE_GRIPPED; - //dammit! Make sure that saber stays off! + // dammit! Make sure that saber stays off! gripEnt->client->ps.saberActive = qfalse; - } - else - {//move - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//level 1 just holds them - VectorCopy( gripEnt->currentOrigin, gripEnt->s.pos.trBase ); - VectorSubtract( gripOrg, gripEntOrg, gripEnt->s.pos.trDelta ); - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 ) - {//level 2 just lifts them - VectorScale( gripEnt->s.pos.trDelta, 10, gripEnt->s.pos.trDelta ); + } else { // move + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // level 1 just holds them + VectorCopy(gripEnt->currentOrigin, gripEnt->s.pos.trBase); + VectorSubtract(gripOrg, gripEntOrg, gripEnt->s.pos.trDelta); + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2) { // level 2 just lifts them + VectorScale(gripEnt->s.pos.trDelta, 10, gripEnt->s.pos.trDelta); } gripEnt->s.pos.trType = TR_LINEAR; gripEnt->s.pos.trTime = level.time; @@ -8202,57 +6615,42 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd gripEnt->s.eFlags |= EF_FORCE_GRIPPED; } - //Shouldn't this be discovered? - //AddSightEvent( self, gripOrg, 128, AEL_DANGER, 20 ); - AddSightEvent( self, gripOrg, 128, AEL_DISCOVERED, 20 ); + // Shouldn't this be discovered? + // AddSightEvent( self, gripOrg, 128, AEL_DANGER, 20 ); + AddSightEvent(self, gripOrg, 128, AEL_DISCOVERED, 20); - if ( self->client->ps.forcePowerDebounce[FP_GRIP] < level.time ) - { - //GEntity_PainFunc( gripEnt, self, self, gripOrg, 0, MOD_CRUSH ); + if (self->client->ps.forcePowerDebounce[FP_GRIP] < level.time) { + // GEntity_PainFunc( gripEnt, self, self, gripOrg, 0, MOD_CRUSH ); gripEnt->painDebounceTime = 0; - G_Damage( gripEnt, self, self, dir, gripOrg, forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]], DAMAGE_NO_ARMOR, MOD_CRUSH );//MOD_??? - if ( gripEnt->s.number ) - { - if ( self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2 ) - {//do damage faster at level 3 - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 150, 750 ); - } - else - { - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 250, 1000 ); + G_Damage(gripEnt, self, self, dir, gripOrg, forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]], DAMAGE_NO_ARMOR, + MOD_CRUSH); // MOD_??? + if (gripEnt->s.number) { + if (self->client->ps.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_2) { // do damage faster at level 3 + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(150, 750); + } else { + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(250, 1000); } + } else { // player takes damage faster + self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand(100, 600); } - else - {//player takes damage faster - self->client->ps.forcePowerDebounce[FP_GRIP] = level.time + Q_irand( 100, 600 ); - } - if ( forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]] > 0 ) - {//no damage at level 1 - WP_ForcePowerDrain( self, FP_GRIP, 3 ); + if (forceGripDamage[self->client->ps.forcePowerLevel[FP_GRIP]] > 0) { // no damage at level 1 + WP_ForcePowerDrain(self, FP_GRIP, 3); } - } - else - { - //WP_ForcePowerDrain( self, FP_GRIP, 0 ); - if ( !gripEnt->enemy ) - { - G_SetEnemy( gripEnt, self ); + } else { + // WP_ForcePowerDrain( self, FP_GRIP, 0 ); + if (!gripEnt->enemy) { + G_SetEnemy(gripEnt, self); } } - if ( gripEnt->client && gripEnt->health > 0 ) - { - int anim = BOTH_CHOKE3; //left-handed choke - if ( gripEnt->client->ps.weapon == WP_NONE || gripEnt->client->ps.weapon == WP_MELEE ) - { - anim = BOTH_CHOKE1; //two-handed choke - } - if ( self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//still on ground, only set anim on torso - NPC_SetAnim( gripEnt, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (gripEnt->client && gripEnt->health > 0) { + int anim = BOTH_CHOKE3; // left-handed choke + if (gripEnt->client->ps.weapon == WP_NONE || gripEnt->client->ps.weapon == WP_MELEE) { + anim = BOTH_CHOKE1; // two-handed choke } - else - {//in air, set on whole body - NPC_SetAnim( gripEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // still on ground, only set anim on torso + NPC_SetAnim(gripEnt, SETANIM_TORSO, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // in air, set on whole body + NPC_SetAnim(gripEnt, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } gripEnt->painDebounceTime = level.time + 2000; } @@ -8260,36 +6658,25 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } break; case FP_LIGHTNING: - if ( self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//higher than level 1 - if ( cmd->buttons & BUTTON_FORCE_LIGHTNING ) - {//holding it keeps it going + if (self->client->ps.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // higher than level 1 + if (cmd->buttons & BUTTON_FORCE_LIGHTNING) { // holding it keeps it going self->client->ps.forcePowerDuration[FP_LIGHTNING] = level.time + 500; - if ( self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START ) - { - if ( !self->client->ps.torsoAnimTimer ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_START, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_FORCELIGHTNING_START) { + if (!self->client->ps.torsoAnimTimer) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_START, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) ) - { - WP_ForcePowerStop( self, forcePower ); - } - else - { - ForceShootLightning( self ); - WP_ForcePowerDrain( self, forcePower, 0 ); + if (!WP_ForcePowerAvailable(self, forcePower, 0)) { + WP_ForcePowerStop(self, forcePower); + } else { + ForceShootLightning(self); + WP_ForcePowerDrain(self, forcePower, 0); } break; default: @@ -8297,131 +6684,102 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } } -void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) -{ - qboolean usingForce = qfalse; - int i; - //see if any force powers are running - if ( !self ) - { +void WP_ForcePowersUpdate(gentity_t *self, usercmd_t *ucmd) { + qboolean usingForce = qfalse; + int i; + // see if any force powers are running + if (!self) { return; } - if ( !self->client ) - { + if (!self->client) { return; } - if ( self->health <= 0 ) - {//if dead, deactivate any active force powers - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.forcePowerDuration[i] || (self->client->ps.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerStop( self, (forcePowers_t)i ); + if (self->health <= 0) { // if dead, deactivate any active force powers + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.forcePowerDuration[i] || (self->client->ps.forcePowersActive & (1 << i))) { + WP_ForcePowerStop(self, (forcePowers_t)i); self->client->ps.forcePowerDuration[i] = 0; } } return; } - if ( !self->s.number ) - {//player uses different kind of force-jump - } - else - { + if (!self->s.number) { // player uses different kind of force-jump + } else { /* if ( ucmd->buttons & BUTTON_FORCEJUMP ) {//just charging up ForceJumpCharge( self, ucmd ); } else */ - if ( self->client->ps.forceJumpCharge ) - {//let go of charge button, have charge - //if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE - && !PM_SwimmingAnim( self->client->ps.legsAnim ) ) - {//FIXME: stop sound? - //self->client->ps.forceJumpCharge = 0; - //FIXME: actually, we want this to still be cleared... don't clear it if the button isn't being pressed, but clear it if not holding button and not on ground. - } - else - {//still on ground, so jump - ForceJump( self, ucmd ); + if (self->client->ps.forceJumpCharge) { // let go of charge button, have charge + // if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE && + !PM_SwimmingAnim(self->client->ps.legsAnim)) { // FIXME: stop sound? + // self->client->ps.forceJumpCharge = 0; + // FIXME: actually, we want this to still be cleared... don't clear it if the button isn't being + // pressed, but clear it if not holding button and not on ground. + } else { // still on ground, so jump + ForceJump(self, ucmd); return; } } } - if ( ucmd->buttons & BUTTON_FORCEGRIP ) - { - ForceGrip( self ); + if (ucmd->buttons & BUTTON_FORCEGRIP) { + ForceGrip(self); } - if ( ucmd->buttons & BUTTON_FORCE_LIGHTNING ) - { - ForceLightning( self ); + if (ucmd->buttons & BUTTON_FORCE_LIGHTNING) { + ForceLightning(self); } - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.forcePowerDuration[i] ) - { - if ( self->client->ps.forcePowerDuration[i] < level.time ) - { - if ( (self->client->ps.forcePowersActive&( 1 << i )) ) - {//turn it off - WP_ForcePowerStop( self, (forcePowers_t)i ); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.forcePowerDuration[i]) { + if (self->client->ps.forcePowerDuration[i] < level.time) { + if ((self->client->ps.forcePowersActive & (1 << i))) { // turn it off + WP_ForcePowerStop(self, (forcePowers_t)i); } self->client->ps.forcePowerDuration[i] = 0; } } - if ( (self->client->ps.forcePowersActive&( 1 << i )) ) - { + if ((self->client->ps.forcePowersActive & (1 << i))) { usingForce = qtrue; - WP_ForcePowerRun( self, (forcePowers_t)i, ucmd ); + WP_ForcePowerRun(self, (forcePowers_t)i, ucmd); } } - if ( self->client->ps.saberInFlight ) - {//don't regen force power while throwing saber - if ( self->client->ps.saberEntityNum < ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( &g_entities[self->client->ps.saberEntityNum] != NULL && g_entities[self->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR ) - {//fell to the ground and we're trying to pull it back + if (self->client->ps.saberInFlight) { // don't regen force power while throwing saber + if (self->client->ps.saberEntityNum < ENTITYNUM_NONE && self->client->ps.saberEntityNum > 0) // player is 0 + { // + if (&g_entities[self->client->ps.saberEntityNum] != NULL && + g_entities[self->client->ps.saberEntityNum].s.pos.trType == TR_LINEAR) { // fell to the ground and we're trying to pull it back usingForce = qtrue; } } } - if ( !usingForce ) - {//when not using the force, regenerate at 10 points per second - if ( self->client->ps.forcePowerRegenDebounceTime < level.time ) - { - WP_ForcePowerRegenerate( self, 0 ); + if (!usingForce) { // when not using the force, regenerate at 10 points per second + if (self->client->ps.forcePowerRegenDebounceTime < level.time) { + WP_ForcePowerRegenerate(self, 0); self->client->ps.forcePowerRegenDebounceTime = level.time + 100; } } } -void WP_InitForcePowers( gentity_t *ent ) -{ - if ( !ent || !ent->client ) - { +void WP_InitForcePowers(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if( ent->client->NPC_class == CLASS_TAVION || - ent->client->NPC_class == CLASS_REBORN || - ent->client->NPC_class == CLASS_DESANN || - ent->client->NPC_class == CLASS_SHADOWTROOPER || - ent->client->NPC_class == CLASS_JEDI || - ent->client->NPC_class == CLASS_LUKE ) - {//an NPC jedi + if (ent->client->NPC_class == CLASS_TAVION || ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_DESANN || + ent->client->NPC_class == CLASS_SHADOWTROOPER || ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_LUKE) { // an NPC jedi ent->client->ps.forcePower = ent->client->ps.forcePowerMax = FORCE_POWER_MAX; ent->client->ps.forcePowerRegenDebounceTime = 0; ent->client->ps.forceGripEntityNum = ENTITYNUM_NONE; - if ( ent->client->NPC_class == CLASS_DESANN ) - { - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_GRIP )|( 1 << FP_LIGHTNING)|( 1 << FP_SABERTHROW)|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + if (ent->client->NPC_class == CLASS_DESANN) { + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_GRIP) | (1 << FP_LIGHTNING) | + (1 << FP_SABERTHROW) | (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PULL] = FORCE_LEVEL_3; @@ -8431,10 +6789,9 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - } - else if ( ent->client->NPC_class == CLASS_LUKE ) - { - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_SABERTHROW)|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->client->NPC_class == CLASS_LUKE) { + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_SABERTHROW) | (1 << FP_SPEED) | + (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PULL] = FORCE_LEVEL_3; @@ -8442,10 +6799,10 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - } - else if ( ent->client->NPC_class == CLASS_TAVION || ( ent->client->NPC_class == CLASS_JEDI && ent->NPC->rank == RANK_COMMANDER ) ) - {//Tavia or trainer Jedi - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_SABERTHROW)|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->client->NPC_class == CLASS_TAVION || + (ent->client->NPC_class == CLASS_JEDI && ent->NPC->rank == RANK_COMMANDER)) { // Tavia or trainer Jedi + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_SABERTHROW) | (1 << FP_SPEED) | + (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PULL] = FORCE_LEVEL_2; @@ -8453,16 +6810,14 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - if ( ent->client->NPC_class == CLASS_TAVION ) - { - ent->client->ps.forcePowersKnown |= ( 1 << FP_LIGHTNING)|( 1 << FP_GRIP ); + if (ent->client->NPC_class == CLASS_TAVION) { + ent->client->ps.forcePowersKnown |= (1 << FP_LIGHTNING) | (1 << FP_GRIP); ent->client->ps.forcePowerLevel[FP_LIGHTNING] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_GRIP] = FORCE_LEVEL_2; } - } - else if ( ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//Shadow Trooper - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_SABERTHROW)|( 1 << FP_GRIP )|( 1 << FP_LIGHTNING)|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->client->NPC_class == CLASS_SHADOWTROOPER) { // Shadow Trooper + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_SABERTHROW) | (1 << FP_GRIP) | + (1 << FP_LIGHTNING) | (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_3; @@ -8472,10 +6827,9 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - } - else if ( ent->NPC->rank == RANK_LT || ent->client->NPC_class == CLASS_JEDI ) - {//Reborn Boss or ally Jedi - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_SABERTHROW)|( 1 << FP_GRIP )|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->NPC->rank == RANK_LT || ent->client->NPC_class == CLASS_JEDI) { // Reborn Boss or ally Jedi + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_SABERTHROW) | (1 << FP_GRIP) | + (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_2; @@ -8483,52 +6837,43 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - if ( ent->client->NPC_class != CLASS_JEDI ) - { - ent->client->ps.forcePowersKnown |= ( 1 << FP_GRIP ); + if (ent->client->NPC_class != CLASS_JEDI) { + ent->client->ps.forcePowersKnown |= (1 << FP_GRIP); ent->client->ps.forcePowerLevel[FP_GRIP] = FORCE_LEVEL_2; } - } - else if ( ent->NPC->rank == RANK_LT_JG ) - {//Reborn Fencer - ent->client->ps.forcePowersKnown = ( 1 << FP_PUSH )|( 1 << FP_SABERTHROW )|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); - ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_2;//FIXME: maybe make him only use it in defense- to throw away grenades + } else if (ent->NPC->rank == RANK_LT_JG) { // Reborn Fencer + ent->client->ps.forcePowersKnown = (1 << FP_PUSH) | (1 << FP_SABERTHROW) | (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); + ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_2; // FIXME: maybe make him only use it in defense- to throw away grenades ent->client->ps.forcePowerLevel[FP_SABERTHROW] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_2; - } - else if ( ent->NPC->rank == RANK_ENSIGN ) - {//Force User - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->NPC->rank == RANK_ENSIGN) { // Force User + ent->client->ps.forcePowersKnown = + (1 << FP_LEVITATION) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_PUSH] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_PULL] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_1; - } - else if ( ent->NPC->rank == RANK_CREWMAN ) - {//Acrobat - ent->client->ps.forcePowersKnown = ( 1 << FP_LEVITATION )|( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->NPC->rank == RANK_CREWMAN) { // Acrobat + ent->client->ps.forcePowersKnown = (1 << FP_LEVITATION) | (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_2; - } - else if ( ent->NPC->rank == RANK_CIVILIAN ) - {//Grunt (NOTE: grunt turns slower and has less health) - ent->client->ps.forcePowersKnown = ( 1 << FP_SPEED)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else if (ent->NPC->rank == RANK_CIVILIAN) { // Grunt (NOTE: grunt turns slower and has less health) + ent->client->ps.forcePowersKnown = (1 << FP_SPEED) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SPEED] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; } - } - else - {//player - ent->client->ps.forcePowersKnown = ( 1 << FP_HEAL )|( 1 << FP_LEVITATION )|( 1 << FP_SPEED )|( 1 << FP_PUSH )|( 1 << FP_PULL )|( 1 << FP_TELEPATHY )|( 1 << FP_GRIP )|( 1 << FP_LIGHTNING)|( 1 << FP_SABERTHROW)|( 1 << FP_SABER_DEFENSE )|( 1 << FP_SABER_OFFENSE ); + } else { // player + ent->client->ps.forcePowersKnown = (1 << FP_HEAL) | (1 << FP_LEVITATION) | (1 << FP_SPEED) | (1 << FP_PUSH) | (1 << FP_PULL) | (1 << FP_TELEPATHY) | + (1 << FP_GRIP) | (1 << FP_LIGHTNING) | (1 << FP_SABERTHROW) | (1 << FP_SABER_DEFENSE) | (1 << FP_SABER_OFFENSE); ent->client->ps.forcePower = ent->client->ps.forcePowerMax = FORCE_POWER_MAX; ent->client->ps.forcePowerRegenDebounceTime = 0; ent->client->ps.forcePowerLevel[FP_HEAL] = FORCE_LEVEL_2; @@ -8541,12 +6886,9 @@ void WP_InitForcePowers( gentity_t *ent ) ent->client->ps.forcePowerLevel[FP_TELEPATHY] = FORCE_LEVEL_2; ent->client->ps.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_3; ent->client->ps.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_3; - if ( ent->NPC ) - {//??? + if (ent->NPC) { //??? ent->client->ps.forcePowerLevel[FP_GRIP] = FORCE_LEVEL_3; - } - else - { + } else { ent->client->ps.forcePowerLevel[FP_GRIP] = FORCE_LEVEL_2; } ent->client->ps.forceGripEntityNum = ENTITYNUM_NONE; diff --git a/codeJK2/game/wp_stun_baton.cpp b/codeJK2/game/wp_stun_baton.cpp index c8ee189623..6797788794 100644 --- a/codeJK2/game/wp_stun_baton.cpp +++ b/codeJK2/game/wp_stun_baton.cpp @@ -29,43 +29,39 @@ along with this program; if not, see . #include "g_functions.h" //--------------------------------------------------------- -void WP_FireStunBaton( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end, start; +void WP_FireStunBaton(gentity_t *ent, qboolean alt_fire) { + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end, start; - G_Sound( ent, G_SoundIndex( "sound/weapons/baton/fire" )); + G_Sound(ent, G_SoundIndex("sound/weapons/baton/fire")); - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); - VectorMA( start, STUN_BATON_RANGE, wpFwd, end ); + VectorMA(start, STUN_BATON_RANGE, wpFwd, end); - VectorSet( maxs, 5, 5, 5 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 5, 5, 5); + VectorScale(maxs, -1, mins); - gi.trace ( &tr, start, mins, maxs, end, ent->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP, G2_NOCOLLIDE, 0 ); + gi.trace(&tr, start, mins, maxs, end, ent->s.number, CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP, G2_NOCOLLIDE, 0); - if ( tr.entityNum >= ENTITYNUM_WORLD || tr.entityNum < 0 ) - { + if (tr.entityNum >= ENTITYNUM_WORLD || tr.entityNum < 0) { return; } tr_ent = &g_entities[tr.entityNum]; - if ( tr_ent && tr_ent->takedamage && tr_ent->client ) - { - G_PlayEffect( "stunBaton/flesh_impact", tr.endpos, tr.plane.normal ); + if (tr_ent && tr_ent->takedamage && tr_ent->client) { + G_PlayEffect("stunBaton/flesh_impact", tr.endpos, tr.plane.normal); // TEMP! -// G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + // G_Sound( tr_ent, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); tr_ent->client->ps.powerups[PW_SHOCKED] = level.time + 1500; - G_Damage( tr_ent, ent, ent, wpFwd, tr.endpos, weaponData[WP_STUN_BATON].damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else if ( tr_ent->svFlags & SVF_GLASS_BRUSH || ( tr_ent->svFlags & SVF_BBRUSH && tr_ent->material == 12 )) // material grate...we are breaking a grate! + G_Damage(tr_ent, ent, ent, wpFwd, tr.endpos, weaponData[WP_STUN_BATON].damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else if (tr_ent->svFlags & SVF_GLASS_BRUSH || (tr_ent->svFlags & SVF_BBRUSH && tr_ent->material == 12)) // material grate...we are breaking a grate! { - G_Damage( tr_ent, ent, ent, wpFwd, tr.endpos, 999, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); // smash that puppy + G_Damage(tr_ent, ent, ent, wpFwd, tr.endpos, 999, DAMAGE_NO_KNOCKBACK, MOD_MELEE); // smash that puppy } } \ No newline at end of file diff --git a/codeJK2/game/wp_thermal.cpp b/codeJK2/game/wp_thermal.cpp index bd8049d13e..b22193e191 100644 --- a/codeJK2/game/wp_thermal.cpp +++ b/codeJK2/game/wp_thermal.cpp @@ -33,268 +33,220 @@ along with this program; if not, see . //--------------------- //--------------------------------------------------------- -void thermalDetonatorExplode( gentity_t *ent ) +void thermalDetonatorExplode(gentity_t *ent) //--------------------------------------------------------- { - if ( !ent->count ) - { - G_Sound( ent, G_SoundIndex( "sound/weapons/thermal/warning.wav" ) ); + if (!ent->count) { + G_Sound(ent, G_SoundIndex("sound/weapons/thermal/warning.wav")); ent->count = 1; ent->nextthink = level.time + 800; - ent->svFlags |= SVF_BROADCAST;//so everyone hears/sees the explosion? - } - else - { - vec3_t pos; + ent->svFlags |= SVF_BROADCAST; // so everyone hears/sees the explosion? + } else { + vec3_t pos; - VectorSet( pos, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + 8 ); + VectorSet(pos, ent->currentOrigin[0], ent->currentOrigin[1], ent->currentOrigin[2] + 8); ent->takedamage = qfalse; // don't allow double deaths! - G_RadiusDamage( ent->currentOrigin, ent->owner, weaponData[WP_THERMAL].splashDamage, weaponData[WP_THERMAL].splashRadius, NULL, MOD_EXPLOSIVE_SPLASH ); + G_RadiusDamage(ent->currentOrigin, ent->owner, weaponData[WP_THERMAL].splashDamage, weaponData[WP_THERMAL].splashRadius, NULL, MOD_EXPLOSIVE_SPLASH); - G_PlayEffect( "thermal/explosion", ent->currentOrigin ); - G_PlayEffect( "thermal/shockwave", ent->currentOrigin ); + G_PlayEffect("thermal/explosion", ent->currentOrigin); + G_PlayEffect("thermal/shockwave", ent->currentOrigin); - G_FreeEntity( ent ); + G_FreeEntity(ent); } } //------------------------------------------------------------------------------------------------------------- -void thermal_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc ) +void thermal_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) //------------------------------------------------------------------------------------------------------------- { - thermalDetonatorExplode( self ); + thermalDetonatorExplode(self); } //--------------------------------------------------------- -qboolean WP_LobFire( gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, - vec3_t velocity, qboolean tracePath, int ignoreEntNum, int enemyNum, - float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit ) +qboolean WP_LobFire(gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, vec3_t velocity, qboolean tracePath, int ignoreEntNum, + int enemyNum, float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit) //--------------------------------------------------------- { - float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, - vec3_t targetDir, shotVel, failCase = { 0.0f }; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; - vec3_t lastPos, testPos; - gentity_t *traceEnt; - - if ( !idealSpeed ) - { + float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, + vec3_t targetDir, shotVel, failCase = {0.0f}; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; + vec3_t lastPos, testPos; + gentity_t *traceEnt; + + if (!idealSpeed) { idealSpeed = 300; - } - else if ( idealSpeed < speedInc ) - { + } else if (idealSpeed < speedInc) { idealSpeed = speedInc; } shotSpeed = idealSpeed; - skipNum = (idealSpeed-speedInc)/speedInc; - if ( !minSpeed ) - { + skipNum = (idealSpeed - speedInc) / speedInc; + if (!minSpeed) { minSpeed = 100; } - if ( !maxSpeed ) - { + if (!maxSpeed) { maxSpeed = 900; } - while ( hitCount < maxHits ) - { - VectorSubtract( target, start, targetDir ); - targetDist = VectorNormalize( targetDir ); + while (hitCount < maxHits) { + VectorSubtract(target, start, targetDir); + targetDist = VectorNormalize(targetDir); - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * g_gravity->value; - if ( !hitCount ) - {//save the first (ideal) one as the failCase (fallback value) - if ( !mustHit ) - {//default is fine as a return value - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first (ideal) one as the failCase (fallback value) + if (!mustHit) { // default is fine as a return value + VectorCopy(shotVel, failCase); } } - if ( tracePath ) - {//do a rough trace of the path + if (tracePath) { // do a rough trace of the path blocked = qfalse; - VectorCopy( start, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(start, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( start, lastPos ); - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); + VectorCopy(start, lastPos); + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace + // just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - gi.trace( &trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, G2_NOCOLLIDE, 0 ); + EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + gi.trace(&trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, G2_NOCOLLIDE, 0); - if ( trace.allsolid || trace.startsolid ) - { + if (trace.allsolid || trace.startsolid) { blocked = qtrue; break; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.entityNum == enemyNum ) - {//hit the enemy, that's perfect! + if (trace.fraction < 1.0f) { // hit something + if (trace.entityNum == enemyNum) { // hit the enemy, that's perfect! break; - } - else if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, target ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + } else if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, target) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, target ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, target); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; - //see if we should store this as the failCase - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit an ent + // see if we should store this as the failCase + if (trace.entityNum < ENTITYNUM_WORLD) { // hit an ent traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && traceEnt->takedamage && !OnSameTeam( self, traceEnt ) ) - {//hit something breakable, so that's okay - //we haven't found a clear shot yet so use this as the failcase - VectorCopy( shotVel, failCase ); + if (traceEnt && traceEnt->takedamage && !OnSameTeam(self, traceEnt)) { // hit something breakable, so that's okay + // we haven't found a clear shot yet so use this as the failcase + VectorCopy(shotVel, failCase); } } break; } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear + if (elapsedTime == floor(travelTime)) { // reached end, all clear break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - shotSpeed = idealSpeed + ((hitCount-skipNum) * speedInc);//from min to max (skipping ideal) - if ( hitCount >= skipNum ) - {//skip ideal since that was the first value we tested + shotSpeed = idealSpeed + ((hitCount - skipNum) * speedInc); // from min to max (skipping ideal) + if (hitCount >= skipNum) { // skip ideal since that was the first value we tested shotSpeed += speedInc; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) - VectorCopy( failCase, velocity ); + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + VectorCopy(failCase, velocity); return qfalse; } - VectorCopy( shotVel, velocity ); + VectorCopy(shotVel, velocity); return qtrue; } //--------------------------------------------------------- -void WP_ThermalThink( gentity_t *ent ) +void WP_ThermalThink(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // Thermal detonators for the player do occasional radius checks and blow up if there are entities in the blast radius // This is done so that the main fire is actually useful as an attack. We explode anyway after delay expires. - if ( ent->delay > level.time ) - { + if (ent->delay > level.time) { // Finally, we force it to bounce at least once before doing the special checks, otherwise it's just too easy for the player? - if ( ent->has_bounced ) - { - count = G_RadiusList( ent->currentOrigin, TD_TEST_RAD, ent, qtrue, ent_list ); - - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->s.number == 0 ) - { + if (ent->has_bounced) { + count = G_RadiusList(ent->currentOrigin, TD_TEST_RAD, ent, qtrue, ent_list); + + for (int i = 0; i < count; i++) { + if (ent_list[i]->s.number == 0) { // avoid deliberately blowing up next to the player, no matter how close any enemy is.. // ...if the delay time expires though, there is no saving the player...muwhaaa haa ha blow = qfalse; break; - } - else if ( ent_list[i]->client && ent_list[i]->health > 0 ) - { + } else if (ent_list[i]->client && ent_list[i]->health > 0) { // sometimes the ent_list order changes, so we should make sure that the player isn't anywhere in this list blow = qtrue; } } } - } - else - { + } else { // our death time has arrived, even if nothing is near us blow = qtrue; } - if ( blow ) - { + if (blow) { ent->e_ThinkFunc = thinkF_thermalDetonatorExplode; ent->nextthink = level.time + 50; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + TD_THINK_TIME; } } //--------------------------------------------------------- -gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) +gentity_t *WP_FireThermalDetonator(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - gentity_t *bolt; - vec3_t dir, start; - float damageScale = 1.0f; + gentity_t *bolt; + vec3_t dir, start; + float damageScale = 1.0f; - VectorCopy( wpFwd, dir ); - VectorCopy( wpMuzzle, start ); + VectorCopy(wpFwd, dir); + VectorCopy(wpMuzzle, start); bolt = G_Spawn(); bolt->classname = "thermal_detonator"; - if ( ent->s.number != 0 ) - { + if (ent->s.number != 0) { // If not the player, cut the damage a bit so we don't get pounded on so much damageScale = TD_NPC_DAMAGE_CUT; } - if ( !alt_fire && ent->s.number == 0 ) - { + if (!alt_fire && ent->s.number == 0) { // Main fires for the players do a little bit of extra thinking bolt->e_ThinkFunc = thinkF_WP_ThermalThink; bolt->nextthink = level.time + TD_THINK_TIME; bolt->delay = level.time + TD_TIME; // How long 'til she blows - } - else - { + } else { bolt->e_ThinkFunc = thinkF_thermalDetonatorExplode; bolt->nextthink = level.time + TD_TIME; // How long 'til she blows } @@ -302,8 +254,8 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->mass = 10; // How 'bout we give this thing a size... - VectorSet( bolt->mins, -4.0f, -4.0f, -4.0f ); - VectorSet( bolt->maxs, 4.0f, 4.0f, 4.0f ); + VectorSet(bolt->mins, -4.0f, -4.0f, -4.0f); + VectorSet(bolt->maxs, 4.0f, 4.0f, 4.0f); bolt->clipmask = MASK_SHOT; bolt->clipmask &= ~CONTENTS_CORPSE; bolt->contents = CONTENTS_SHOTCLIP; @@ -311,67 +263,57 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->health = 15; bolt->e_DieFunc = dieF_thermal_die; - WP_TraceSetStart( ent, start, bolt->mins, bolt->maxs );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, bolt->mins, bolt->maxs); // make sure our start point isn't on the other side of a wall float chargeAmount = 1.0f; // default of full charge - if ( ent->client ) - { + if (ent->client) { chargeAmount = level.time - ent->client->ps.weaponChargeTime; } // get charge amount chargeAmount = chargeAmount / (float)TD_VELOCITY; - if ( chargeAmount > 1.0f ) - { + if (chargeAmount > 1.0f) { chargeAmount = 1.0f; - } - else if ( chargeAmount < TD_MIN_CHARGE ) - { + } else if (chargeAmount < TD_MIN_CHARGE) { chargeAmount = TD_MIN_CHARGE; } // normal ones bounce, alt ones explode on impact bolt->s.pos.trType = TR_GRAVITY; bolt->owner = ent; - VectorScale( dir, TD_VELOCITY * chargeAmount, bolt->s.pos.trDelta ); + VectorScale(dir, TD_VELOCITY * chargeAmount, bolt->s.pos.trDelta); - if ( ent->health > 0 ) - { + if (ent->health > 0) { bolt->s.pos.trDelta[2] += 120; - if ( ent->NPC && ent->enemy ) - {//FIXME: we're assuming he's actually facing this direction... - vec3_t target; - - VectorCopy( ent->enemy->currentOrigin, target ); - if ( target[2] <= start[2] ) - { - vec3_t vec; - VectorSubtract( target, start, vec ); - VectorNormalize( vec ); - VectorMA( target, Q_flrand( 0, -32 ), vec, target );//throw a little short + if (ent->NPC && ent->enemy) { // FIXME: we're assuming he's actually facing this direction... + vec3_t target; + + VectorCopy(ent->enemy->currentOrigin, target); + if (target[2] <= start[2]) { + vec3_t vec; + VectorSubtract(target, start, vec); + VectorNormalize(vec); + VectorMA(target, Q_flrand(0, -32), vec, target); // throw a little short } - target[0] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); - target[1] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); - target[2] += Q_flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-ent->NPC->currentAim)*2); + target[0] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); + target[1] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); + target[2] += Q_flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - ent->NPC->currentAim) * 2); - WP_LobFire( ent, start, target, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number ); + WP_LobFire(ent, start, target, bolt->mins, bolt->maxs, bolt->clipmask, bolt->s.pos.trDelta, qtrue, ent->s.number, ent->enemy->s.number); } } - if ( alt_fire ) - { + if (alt_fire) { bolt->alt_fire = qtrue; - } - else - { + } else { bolt->s.eFlags |= EF_BOUNCE_HALF; } - bolt->s.loopSound = G_SoundIndex( "sound/weapons/thermal/thermloop.wav" ); + bolt->s.loopSound = G_SoundIndex("sound/weapons/thermal/thermloop.wav"); bolt->damage = weaponData[WP_THERMAL].damage * damageScale; bolt->dflags = 0; @@ -382,33 +324,30 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean alt_fire ) bolt->svFlags = SVF_USE_CURRENT_ORIGIN; bolt->s.weapon = WP_THERMAL; - if ( alt_fire ) - { + if (alt_fire) { bolt->methodOfDeath = MOD_THERMAL_ALT; - bolt->splashMethodOfDeath = MOD_THERMAL_ALT;//? SPLASH; - } - else - { + bolt->splashMethodOfDeath = MOD_THERMAL_ALT; //? SPLASH; + } else { bolt->methodOfDeath = MOD_THERMAL; - bolt->splashMethodOfDeath = MOD_THERMAL;//? SPLASH; + bolt->splashMethodOfDeath = MOD_THERMAL; //? SPLASH; } - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, bolt->s.pos.trBase ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, bolt->s.pos.trBase); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy (start, bolt->currentOrigin); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->currentOrigin); - VectorCopy( start, bolt->pos2 ); + VectorCopy(start, bolt->pos2); return bolt; } //--------------------------------------------------------- -gentity_t *WP_DropThermal( gentity_t *ent ) +gentity_t *WP_DropThermal(gentity_t *ent) //--------------------------------------------------------- { - AngleVectors( ent->client->ps.viewangles, wpFwd, wpVright, wpUp ); - CalcEntitySpot( ent, SPOT_WEAPON, wpMuzzle ); - return (WP_FireThermalDetonator( ent, qfalse )); + AngleVectors(ent->client->ps.viewangles, wpFwd, wpVright, wpUp); + CalcEntitySpot(ent, SPOT_WEAPON, wpMuzzle); + return (WP_FireThermalDetonator(ent, qfalse)); } \ No newline at end of file diff --git a/codeJK2/game/wp_trip_mine.cpp b/codeJK2/game/wp_trip_mine.cpp index 1b50019d98..ce62b99f60 100644 --- a/codeJK2/game/wp_trip_mine.cpp +++ b/codeJK2/game/wp_trip_mine.cpp @@ -33,20 +33,20 @@ along with this program; if not, see . //----------------------- #define PROXIMITY_STYLE 1 -#define TRIPWIRE_STYLE 2 +#define TRIPWIRE_STYLE 2 //--------------------------------------------------------- -void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) +void touchLaserTrap(gentity_t *ent, gentity_t *other, trace_t *trace) //--------------------------------------------------------- { ent->s.eType = ET_GENERAL; // a tripwire so add draw line flag - VectorCopy( trace->plane.normal, ent->movedir ); + VectorCopy(trace->plane.normal, ent->movedir); // make it shootable - VectorSet( ent->mins, -4, -4, -4 ); - VectorSet( ent->maxs, 4, 4, 4 ); + VectorSet(ent->mins, -4, -4, -4); + VectorSet(ent->maxs, 4, 4, 4); ent->clipmask = MASK_SHOT; ent->contents = CONTENTS_SHOTCLIP; @@ -60,20 +60,17 @@ void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) ent->activator = ent->owner; ent->owner = NULL; - WP_Stick( ent, trace ); + WP_Stick(ent, trace); - if ( ent->count == TRIPWIRE_STYLE ) - { - vec3_t mins = {-4,-4,-4}, maxs = {4,4,4};//FIXME: global these - trace_t tr; - VectorMA( ent->currentOrigin, 32, ent->movedir, ent->s.origin2 ); - gi.trace( &tr, ent->s.origin2, mins, maxs, ent->currentOrigin, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); - VectorCopy( tr.endpos, ent->s.origin2 ); + if (ent->count == TRIPWIRE_STYLE) { + vec3_t mins = {-4, -4, -4}, maxs = {4, 4, 4}; // FIXME: global these + trace_t tr; + VectorMA(ent->currentOrigin, 32, ent->movedir, ent->s.origin2); + gi.trace(&tr, ent->s.origin2, mins, maxs, ent->currentOrigin, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0); + VectorCopy(tr.endpos, ent->s.origin2); ent->e_ThinkFunc = thinkF_laserTrapThink; - } - else - { + } else { ent->e_ThinkFunc = thinkF_WP_prox_mine_think; } @@ -82,68 +79,58 @@ void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) // copied from flechette prox above...which will not be used if this gets approved //--------------------------------------------------------- -void WP_prox_mine_think( gentity_t *ent ) +void WP_prox_mine_think(gentity_t *ent) //--------------------------------------------------------- { - int count; - qboolean blow = qfalse; + int count; + qboolean blow = qfalse; // first time through? - if ( ent->count ) - { + if (ent->count) { // play activated warning ent->count = 0; ent->s.eFlags |= EF_PROX_TRIP; - G_Sound( ent, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" )); + G_Sound(ent, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); } // if it isn't time to auto-explode, do a small proximity check - if ( ent->delay > level.time ) - { - count = G_RadiusList( ent->currentOrigin, PROX_MINE_RADIUS_CHECK, ent, qtrue, ent_list ); + if (ent->delay > level.time) { + count = G_RadiusList(ent->currentOrigin, PROX_MINE_RADIUS_CHECK, ent, qtrue, ent_list); - for ( int i = 0; i < count; i++ ) - { - if ( ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number ) - { + for (int i = 0; i < count; i++) { + if (ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number) { blow = qtrue; break; } } - } - else - { + } else { // well, we must die now blow = qtrue; } - if ( blow ) - { -// G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); + if (blow) { + // G_Sound( ent, G_SoundIndex( "sound/weapons/flechette/warning.wav" )); ent->e_ThinkFunc = thinkF_WP_Explode; ent->nextthink = level.time + 200; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + 500; } } //--------------------------------------------------------- -void laserTrapThink( gentity_t *ent ) +void laserTrapThink(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *traceEnt; - vec3_t end, mins = {-4,-4,-4}, maxs = {4,4,4}; - trace_t tr; + gentity_t *traceEnt; + vec3_t end, mins = {-4, -4, -4}, maxs = {4, 4, 4}; + trace_t tr; // turn on the beam effect - if ( !(ent->s.eFlags & EF_FIRING )) - { + if (!(ent->s.eFlags & EF_FIRING)) { // arm me - G_Sound( ent, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" )); - ent->s.loopSound = G_SoundIndex( "sound/weapons/laser_trap/hum_loop.wav" ); + G_Sound(ent, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); + ent->s.loopSound = G_SoundIndex("sound/weapons/laser_trap/hum_loop.wav"); ent->s.eFlags |= EF_FIRING; } @@ -151,22 +138,19 @@ void laserTrapThink( gentity_t *ent ) ent->nextthink = level.time + FRAMETIME; // Find the main impact point - VectorMA( ent->s.pos.trBase, 2048, ent->movedir, end ); - gi.trace( &tr, ent->s.origin2, mins, maxs, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0 ); + VectorMA(ent->s.pos.trBase, 2048, ent->movedir, end); + gi.trace(&tr, ent->s.origin2, mins, maxs, end, ent->s.number, MASK_SHOT, G2_RETURNONHIT, 0); - traceEnt = &g_entities[ tr.entityNum ]; + traceEnt = &g_entities[tr.entityNum]; // Adjust this so that the effect has a relatively fresh endpoint - VectorCopy( tr.endpos, ent->pos4 ); + VectorCopy(tr.endpos, ent->pos4); - if ( traceEnt->client || tr.startsolid ) - { + if (traceEnt->client || tr.startsolid) { // go boom - WP_Explode( ent ); + WP_Explode(ent); ent->s.eFlags &= ~EF_FIRING; // don't draw beam if we are dead - } - else - { + } else { /* // FIXME: they need to avoid the beam! AddSoundEvent( ent->owner, ent->currentOrigin, ent->splashRadius*2, AEL_DANGER ); @@ -176,11 +160,10 @@ void laserTrapThink( gentity_t *ent ) } //--------------------------------------------------------- -void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) +void CreateLaserTrap(gentity_t *laserTrap, vec3_t start, gentity_t *owner) //--------------------------------------------------------- { - if ( !VALIDSTRING( laserTrap->classname )) - { + if (!VALIDSTRING(laserTrap->classname)) { // since we may be coming from a map placed trip mine, we don't want to override that class name.... // That would be bad because the player drop code tries to limit number of placed items...so it would have removed map placed ones as well. laserTrap->classname = "tripmine"; @@ -190,46 +173,46 @@ void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) laserTrap->splashRadius = weaponData[WP_TRIP_MINE].splashRadius; laserTrap->damage = weaponData[WP_TRIP_MINE].damage; laserTrap->methodOfDeath = MOD_LASERTRIP; - laserTrap->splashMethodOfDeath = MOD_LASERTRIP;//? SPLASH; + laserTrap->splashMethodOfDeath = MOD_LASERTRIP; //? SPLASH; laserTrap->s.eType = ET_MISSILE; laserTrap->svFlags = SVF_USE_CURRENT_ORIGIN; laserTrap->s.weapon = WP_TRIP_MINE; laserTrap->owner = owner; -// VectorSet( laserTrap->mins, -LT_SIZE, -LT_SIZE, -LT_SIZE ); -// VectorSet( laserTrap->maxs, LT_SIZE, LT_SIZE, LT_SIZE ); - laserTrap->clipmask = (CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_SHOTCLIP);//MASK_SHOT; + // VectorSet( laserTrap->mins, -LT_SIZE, -LT_SIZE, -LT_SIZE ); + // VectorSet( laserTrap->maxs, LT_SIZE, LT_SIZE, LT_SIZE ); + laserTrap->clipmask = (CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_SHOTCLIP); // MASK_SHOT; - laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, laserTrap->s.pos.trBase ); - VectorCopy( start, laserTrap->currentOrigin); + laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, laserTrap->s.pos.trBase); + VectorCopy(start, laserTrap->currentOrigin); - VectorCopy( start, laserTrap->pos2 ); // ?? wtf ? + VectorCopy(start, laserTrap->pos2); // ?? wtf ? - laserTrap->fxID = G_EffectIndex( "tripMine/explosion" ); + laserTrap->fxID = G_EffectIndex("tripMine/explosion"); laserTrap->e_TouchFunc = touchF_touchLaserTrap; laserTrap->s.radius = 60; - VectorSet( laserTrap->s.modelScale, 1.0f, 1.0f, 1.0f ); - gi.G2API_InitGhoul2Model( laserTrap->ghoul2, weaponData[WP_TRIP_MINE].missileMdl, G_ModelIndex( weaponData[WP_TRIP_MINE].missileMdl ), NULL_HANDLE, NULL_HANDLE, 0, 0); + VectorSet(laserTrap->s.modelScale, 1.0f, 1.0f, 1.0f); + gi.G2API_InitGhoul2Model(laserTrap->ghoul2, weaponData[WP_TRIP_MINE].missileMdl, G_ModelIndex(weaponData[WP_TRIP_MINE].missileMdl), NULL_HANDLE, + NULL_HANDLE, 0, 0); } //--------------------------------------------------------- -static void WP_RemoveOldTraps( gentity_t *ent ) +static void WP_RemoveOldTraps(gentity_t *ent) //--------------------------------------------------------- { - gentity_t *found = NULL; - int trapcount = 0, i; - int foundLaserTraps[MAX_GENTITIES] = {ENTITYNUM_NONE}; - int trapcount_org, lowestTimeStamp; - int removeMe; + gentity_t *found = NULL; + int trapcount = 0, i; + int foundLaserTraps[MAX_GENTITIES] = {ENTITYNUM_NONE}; + int trapcount_org, lowestTimeStamp; + int removeMe; // see how many there are now - while (( found = G_Find( found, FOFS(classname), "tripmine" )) != NULL ) - { - if ( found->activator != ent ) // activator is really the owner? + while ((found = G_Find(found, FOFS(classname), "tripmine")) != NULL) { + if (found->activator != ent) // activator is really the owner? { continue; } @@ -241,80 +224,66 @@ static void WP_RemoveOldTraps( gentity_t *ent ) trapcount_org = trapcount; lowestTimeStamp = level.time; - while ( trapcount > 9 ) - { + while (trapcount > 9) { removeMe = -1; - for ( i = 0; i < trapcount_org; i++ ) - { - if ( foundLaserTraps[i] == ENTITYNUM_NONE ) - { + for (i = 0; i < trapcount_org; i++) { + if (foundLaserTraps[i] == ENTITYNUM_NONE) { continue; } found = &g_entities[foundLaserTraps[i]]; - if ( found->setTime < lowestTimeStamp ) - { + if (found->setTime < lowestTimeStamp) { removeMe = i; lowestTimeStamp = found->setTime; } } - if ( removeMe != -1 ) - { - //remove it... or blow it? - if ( &g_entities[foundLaserTraps[removeMe]] == NULL ) - { + if (removeMe != -1) { + // remove it... or blow it? + if (&g_entities[foundLaserTraps[removeMe]] == NULL) { break; - } - else - { - G_FreeEntity( &g_entities[foundLaserTraps[removeMe]] ); + } else { + G_FreeEntity(&g_entities[foundLaserTraps[removeMe]]); } foundLaserTraps[removeMe] = ENTITYNUM_NONE; trapcount--; - } - else - { + } else { break; } } } //--------------------------------------------------------- -void WP_PlaceLaserTrap( gentity_t *ent, qboolean alt_fire ) +void WP_PlaceLaserTrap(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { - vec3_t start; - gentity_t *laserTrap; + vec3_t start; + gentity_t *laserTrap; // limit to 10 placed at any one time - WP_RemoveOldTraps( ent ); + WP_RemoveOldTraps(ent); - //FIXME: surface must be within 64 + // FIXME: surface must be within 64 laserTrap = G_Spawn(); - if ( laserTrap ) - { + if (laserTrap) { // now make the new one - VectorCopy( wpMuzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(wpMuzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - CreateLaserTrap( laserTrap, start, ent ); + CreateLaserTrap(laserTrap, start, ent); // set player-created-specific fields - laserTrap->setTime = level.time;//remember when we placed it + laserTrap->setTime = level.time; // remember when we placed it laserTrap->s.eFlags |= EF_MISSILE_STICK; laserTrap->s.pos.trType = TR_GRAVITY; - VectorScale( wpFwd, LT_VELOCITY, laserTrap->s.pos.trDelta ); + VectorScale(wpFwd, LT_VELOCITY, laserTrap->s.pos.trDelta); - if ( alt_fire ) - { + if (alt_fire) { laserTrap->count = PROXIMITY_STYLE; laserTrap->delay = level.time + 40000; // will auto-blow in 40 seconds. laserTrap->methodOfDeath = MOD_LASERTRIP_ALT; - laserTrap->splashMethodOfDeath = MOD_LASERTRIP_ALT;//? SPLASH; - } - else - { + laserTrap->splashMethodOfDeath = MOD_LASERTRIP_ALT; //? SPLASH; + } else { laserTrap->count = TRIPWIRE_STYLE; } } diff --git a/codeJK2/icarus/BlockStream.cpp b/codeJK2/icarus/BlockStream.cpp index af8976518d..1873b8286d 100644 --- a/codeJK2/icarus/BlockStream.cpp +++ b/codeJK2/icarus/BlockStream.cpp @@ -39,17 +39,13 @@ along with this program; if not, see . =================================================================================================== */ -CBlockMember::CBlockMember( void ) -{ +CBlockMember::CBlockMember(void) { m_id = -1; m_size = -1; m_data = NULL; } -CBlockMember::~CBlockMember( void ) -{ - Free(); -} +CBlockMember::~CBlockMember(void) { Free(); } /* ------------------------- @@ -57,11 +53,9 @@ Free ------------------------- */ -void CBlockMember::Free( void ) -{ - if ( m_data != NULL ) - { - ICARUS_Free ( m_data ); +void CBlockMember::Free(void) { + if (m_data != NULL) { + ICARUS_Free(m_data); m_data = NULL; m_id = m_size = -1; @@ -74,8 +68,7 @@ GetInfo ------------------------- */ -void CBlockMember::GetInfo( int *id, int *size, void **data ) -{ +void CBlockMember::GetInfo(int *id, int *size, void **data) { *id = m_id; *size = m_size; *data = m_data; @@ -87,23 +80,16 @@ SetData overloads ------------------------- */ -void CBlockMember::SetData( const char *data ) -{ - WriteDataPointer( data, strlen(data)+1 ); -} +void CBlockMember::SetData(const char *data) { WriteDataPointer(data, strlen(data) + 1); } -void CBlockMember::SetData( vector_t data ) -{ - WriteDataPointer( data, 3 ); -} +void CBlockMember::SetData(vector_t data) { WriteDataPointer(data, 3); } -void CBlockMember::SetData( void *data, int size ) -{ - if ( m_data ) - ICARUS_Free( m_data ); +void CBlockMember::SetData(void *data, int size) { + if (m_data) + ICARUS_Free(m_data); - m_data = ICARUS_Malloc( size ); - memcpy( m_data, data, size ); + m_data = ICARUS_Malloc(size); + memcpy(m_data, data, size); m_size = size; } @@ -115,25 +101,22 @@ ReadMember ------------------------- */ -int CBlockMember::ReadMember( char **stream, int *streamPos ) -{ - m_id = LittleLong(*(int *) (*stream + *((int *)streamPos))); - *streamPos += sizeof( int ); +int CBlockMember::ReadMember(char **stream, int *streamPos) { + m_id = LittleLong(*(int *)(*stream + *((int *)streamPos))); + *streamPos += sizeof(int); - if ( m_id == ID_RANDOM ) - {//special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time random is checked when inside a wait - m_size = sizeof( float ); - *streamPos += sizeof( int ); - m_data = ICARUS_Malloc( m_size ); + if (m_id == ID_RANDOM) { // special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time random is + // checked when inside a wait + m_size = sizeof(float); + *streamPos += sizeof(int); + m_data = ICARUS_Malloc(m_size); float infinite = Q3_INFINITE; - memcpy( m_data, &infinite, m_size ); - } - else - { - m_size = LittleLong(*(int *) (*stream + *streamPos)); - *streamPos += sizeof( int ); - m_data = ICARUS_Malloc( m_size ); - memcpy( m_data, (*stream + *streamPos), m_size ); + memcpy(m_data, &infinite, m_size); + } else { + m_size = LittleLong(*(int *)(*stream + *streamPos)); + *streamPos += sizeof(int); + m_data = ICARUS_Malloc(m_size); + memcpy(m_data, (*stream + *streamPos), m_size); #ifdef Q3_BIG_ENDIAN // only TK_INT, TK_VECTOR and TK_FLOAT has to be swapped, but just in case if (m_size == 4 && m_id != TK_STRING && m_id != TK_IDENTIFIER && m_id != TK_CHAR) @@ -141,7 +124,7 @@ int CBlockMember::ReadMember( char **stream, int *streamPos ) #endif } *streamPos += m_size; - + return true; } @@ -151,11 +134,10 @@ WriteMember ------------------------- */ -int CBlockMember::WriteMember( FILE *m_fileHandle ) -{ - fwrite( &m_id, sizeof(m_id), 1, m_fileHandle ); - fwrite( &m_size, sizeof(m_size), 1, m_fileHandle ); - fwrite( m_data, m_size, 1, m_fileHandle ); +int CBlockMember::WriteMember(FILE *m_fileHandle) { + fwrite(&m_id, sizeof(m_id), 1, m_fileHandle); + fwrite(&m_size, sizeof(m_size), 1, m_fileHandle); + fwrite(m_data, m_size, 1, m_fileHandle); return true; } @@ -166,16 +148,15 @@ Duplicate ------------------------- */ -CBlockMember *CBlockMember::Duplicate( void ) -{ - CBlockMember *newblock = new CBlockMember; +CBlockMember *CBlockMember::Duplicate(void) { + CBlockMember *newblock = new CBlockMember; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->SetData( m_data, m_size ); - newblock->SetSize( m_size ); - newblock->SetID( m_id ); + newblock->SetData(m_data, m_size); + newblock->SetSize(m_size); + newblock->SetID(m_id); return newblock; } @@ -188,16 +169,12 @@ CBlockMember *CBlockMember::Duplicate( void ) =================================================================================================== */ -CBlock::CBlock( void ) -{ - m_flags = 0; - m_id = 0; +CBlock::CBlock(void) { + m_flags = 0; + m_id = 0; } -CBlock::~CBlock( void ) -{ - Free(); -} +CBlock::~CBlock(void) { Free(); } /* ------------------------- @@ -205,10 +182,9 @@ Init ------------------------- */ -int CBlock::Init( void ) -{ - m_flags = 0; - m_id = 0; +int CBlock::Init(void) { + m_flags = 0; + m_id = 0; return true; } @@ -219,8 +195,7 @@ Create ------------------------- */ -int CBlock::Create( int block_id ) -{ +int CBlock::Create(int block_id) { Init(); m_id = block_id; @@ -234,14 +209,12 @@ Free ------------------------- */ -int CBlock::Free( void ) -{ - int numMembers = GetNumMembers(); - CBlockMember *bMember; +int CBlock::Free(void) { + int numMembers = GetNumMembers(); + CBlockMember *bMember; - while ( numMembers-- ) - { - bMember = GetMember( numMembers ); + while (numMembers--) { + bMember = GetMember(numMembers); if (!bMember) return false; @@ -249,7 +222,7 @@ int CBlock::Free( void ) delete bMember; } - m_members.clear(); //List of all CBlockMembers owned by this list + m_members.clear(); // List of all CBlockMembers owned by this list return true; } @@ -262,67 +235,61 @@ Write ------------------------- */ -int CBlock::Write( int member_id, const char *member_data ) -{ +int CBlock::Write(int member_id, const char *member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - - bMember->SetData( member_data ); - bMember->SetSize( strlen(member_data) + 1 ); + bMember->SetID(member_id); - AddMember( bMember ); + bMember->SetData(member_data); + bMember->SetSize(strlen(member_data) + 1); + + AddMember(bMember); return true; } -int CBlock::Write( int member_id, vector_t member_data ) -{ - CBlockMember *bMember; +int CBlock::Write(int member_id, vector_t member_data) { + CBlockMember *bMember; bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->SetData( member_data ); - bMember->SetSize( sizeof(vector_t) ); + bMember->SetID(member_id); + bMember->SetData(member_data); + bMember->SetSize(sizeof(vector_t)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, float member_data ) -{ +int CBlock::Write(int member_id, float member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data ); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, int member_data ) -{ +int CBlock::Write(int member_id, int member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data ); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } +int CBlock::Write(CBlockMember *bMember) { + // findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); -int CBlock::Write( CBlockMember *bMember ) -{ -// findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); - - AddMember( bMember ); + AddMember(bMember); return true; } @@ -335,9 +302,8 @@ AddMember ------------------------- */ -int CBlock::AddMember( CBlockMember *member ) -{ - m_members.insert( m_members.end(), member ); +int CBlock::AddMember(CBlockMember *member) { + m_members.insert(m_members.end(), member); return true; } @@ -347,13 +313,11 @@ GetMember ------------------------- */ -CBlockMember *CBlock::GetMember( int memberNum ) -{ - if ( memberNum >= GetNumMembers() ) - { +CBlockMember *CBlock::GetMember(int memberNum) { + if (memberNum >= GetNumMembers()) { return NULL; } - return m_members[ memberNum ]; + return m_members[memberNum]; } /* @@ -362,13 +326,11 @@ GetMemberData ------------------------- */ -void *CBlock::GetMemberData( int memberNum ) -{ - if ( memberNum >= GetNumMembers() ) - { +void *CBlock::GetMemberData(int memberNum) { + if (memberNum >= GetNumMembers()) { return NULL; } - return (void *) ((GetMember( memberNum ))->GetData()); + return (void *)((GetMember(memberNum))->GetData()); } /* @@ -377,22 +339,20 @@ Duplicate ------------------------- */ -CBlock *CBlock::Duplicate( void ) -{ - blockMember_v::iterator mi; - CBlock *newblock; +CBlock *CBlock::Duplicate(void) { + blockMember_v::iterator mi; + CBlock *newblock; newblock = new CBlock; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->Create( m_id ); + newblock->Create(m_id); - //Duplicate entire block and return the cc - for ( mi = m_members.begin(); mi != m_members.end(); ++mi ) - { - newblock->AddMember( (*mi)->Duplicate() ); + // Duplicate entire block and return the cc + for (mi = m_members.begin(); mi != m_members.end(); ++mi) { + newblock->AddMember((*mi)->Duplicate()); } return newblock; @@ -406,15 +366,12 @@ CBlock *CBlock::Duplicate( void ) =================================================================================================== */ -CBlockStream::CBlockStream( void ) -{ +CBlockStream::CBlockStream(void) { m_stream = NULL; m_streamPos = 0; } -CBlockStream::~CBlockStream( void ) -{ -} +CBlockStream::~CBlockStream(void) {} /* ------------------------- @@ -422,12 +379,11 @@ GetChar ------------------------- */ -char CBlockStream::GetChar( void ) -{ +char CBlockStream::GetChar(void) { char data; - data = *(char*) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(char *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -438,12 +394,11 @@ GetUnsignedInteger ------------------------- */ -unsigned CBlockStream::GetUnsignedInteger( void ) -{ +unsigned CBlockStream::GetUnsignedInteger(void) { unsigned data; - data = *(unsigned *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(unsigned *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -454,12 +409,11 @@ GetInteger ------------------------- */ -int CBlockStream::GetInteger( void ) -{ +int CBlockStream::GetInteger(void) { int data; - data = *(int *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(int *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -470,12 +424,11 @@ GetLong ------------------------- */ -long CBlockStream::GetLong( void ) -{ +long CBlockStream::GetLong(void) { long data; - data = *(int *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(int *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -486,12 +439,11 @@ GetFloat ------------------------- */ -float CBlockStream::GetFloat( void ) -{ +float CBlockStream::GetFloat(void) { float data; - data = *(float *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(float *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -502,9 +454,8 @@ Free ------------------------- */ -int CBlockStream::Free( void ) -{ - //NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call +int CBlockStream::Free(void) { + // NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call // That's why this doesn't free the memory, it only clears its internal pointer m_stream = NULL; @@ -519,22 +470,20 @@ Create ------------------------- */ -int CBlockStream::Create( char *filename ) -{ - char *id_header = IBI_HEADER_ID; - float version = IBI_VERSION; +int CBlockStream::Create(char *filename) { + char *id_header = IBI_HEADER_ID; + float version = IBI_VERSION; - //Strip the extension and add the BLOCK_EXT extension - COM_StripExtension( filename, m_fileName, sizeof(m_fileName) ); - COM_DefaultExtension( m_fileName, sizeof(m_fileName), IBI_EXT ); + // Strip the extension and add the BLOCK_EXT extension + COM_StripExtension(filename, m_fileName, sizeof(m_fileName)); + COM_DefaultExtension(m_fileName, sizeof(m_fileName), IBI_EXT); - if ( (m_fileHandle = fopen(m_fileName, "wb")) == NULL ) - { + if ((m_fileHandle = fopen(m_fileName, "wb")) == NULL) { return false; } - fwrite( id_header, IBI_HEADER_ID_LENGTH, 1, m_fileHandle ); - fwrite( &version, sizeof(version), 1, m_fileHandle ); + fwrite(id_header, IBI_HEADER_ID_LENGTH, 1, m_fileHandle); + fwrite(&version, sizeof(version), 1, m_fileHandle); return true; } @@ -545,8 +494,7 @@ Init ------------------------- */ -int CBlockStream::Init( void ) -{ +int CBlockStream::Init(void) { m_fileHandle = NULL; memset(m_fileName, 0, sizeof(m_fileName)); @@ -564,21 +512,19 @@ WriteBlock ------------------------- */ -int CBlockStream::WriteBlock( CBlock *block ) -{ - CBlockMember *bMember; - int id = block->GetBlockID(); - int numMembers = block->GetNumMembers(); - unsigned char flags = block->GetFlags(); - - fwrite ( &id, sizeof(id), 1, m_fileHandle ); - fwrite ( &numMembers, sizeof(numMembers), 1, m_fileHandle ); - fwrite ( &flags, sizeof( flags ), 1, m_fileHandle ); - - for ( int i = 0; i < numMembers; i++ ) - { - bMember = block->GetMember( i ); - bMember->WriteMember( m_fileHandle ); +int CBlockStream::WriteBlock(CBlock *block) { + CBlockMember *bMember; + int id = block->GetBlockID(); + int numMembers = block->GetNumMembers(); + unsigned char flags = block->GetFlags(); + + fwrite(&id, sizeof(id), 1, m_fileHandle); + fwrite(&numMembers, sizeof(numMembers), 1, m_fileHandle); + fwrite(&flags, sizeof(flags), 1, m_fileHandle); + + for (int i = 0; i < numMembers; i++) { + bMember = block->GetMember(i); + bMember->WriteMember(m_fileHandle); } block->Free(); @@ -592,9 +538,8 @@ BlockAvailable ------------------------- */ -int CBlockStream::BlockAvailable( void ) -{ - if ( m_streamPos >= m_fileSize ) +int CBlockStream::BlockAvailable(void) { + if (m_streamPos >= m_fileSize) return false; return true; @@ -606,30 +551,28 @@ ReadBlock ------------------------- */ -int CBlockStream::ReadBlock( CBlock *get ) -{ - CBlockMember *bMember; - int b_id, numMembers; - unsigned char flags; +int CBlockStream::ReadBlock(CBlock *get) { + CBlockMember *bMember; + int b_id, numMembers; + unsigned char flags; if (!BlockAvailable()) return false; - b_id = LittleLong(GetInteger()); - numMembers = LittleLong(GetInteger()); - flags = (unsigned char) GetChar(); + b_id = LittleLong(GetInteger()); + numMembers = LittleLong(GetInteger()); + flags = (unsigned char)GetChar(); if (numMembers < 0) return false; - get->Create( b_id ); - get->SetFlags( flags ); + get->Create(b_id); + get->SetFlags(flags); - while ( numMembers-- > 0) - { + while (numMembers-- > 0) { bMember = new CBlockMember; - bMember->ReadMember( &m_stream, &m_streamPos ); - get->AddMember( bMember ); + bMember->ReadMember(&m_stream, &m_streamPos); + get->AddMember(bMember); } return true; @@ -641,35 +584,31 @@ Open ------------------------- */ -int CBlockStream::Open( char *buffer, long size ) -{ - char id_header[IBI_HEADER_ID_LENGTH]; - float version; - +int CBlockStream::Open(char *buffer, long size) { + char id_header[IBI_HEADER_ID_LENGTH]; + float version; + Init(); m_fileSize = size; m_stream = buffer; - for ( size_t i = 0; i < sizeof( id_header ); i++ ) - { + for (size_t i = 0; i < sizeof(id_header); i++) { id_header[i] = GetChar(); } version = GetFloat(); version = LittleFloat(version); - //Check for valid header - if ( strcmp( id_header, IBI_HEADER_ID ) ) - { + // Check for valid header + if (strcmp(id_header, IBI_HEADER_ID)) { Free(); return false; } - //Check for valid version - if ( version != IBI_VERSION ) - { + // Check for valid version + if (version != IBI_VERSION) { Free(); return false; } diff --git a/codeJK2/icarus/Instance.cpp b/codeJK2/icarus/Instance.cpp index 7aec690b14..6d0985d21b 100644 --- a/codeJK2/icarus/Instance.cpp +++ b/codeJK2/icarus/Instance.cpp @@ -33,27 +33,23 @@ along with this program; if not, see . // Instance -ICARUS_Instance::ICARUS_Instance( void ) -{ +ICARUS_Instance::ICARUS_Instance(void) { m_GUID = 0; #ifdef _DEBUG - m_DEBUG_NumSequencerAlloc = 0; - m_DEBUG_NumSequencerFreed = 0; - m_DEBUG_NumSequencerResidual = 0; + m_DEBUG_NumSequencerAlloc = 0; + m_DEBUG_NumSequencerFreed = 0; + m_DEBUG_NumSequencerResidual = 0; - m_DEBUG_NumSequenceAlloc = 0; - m_DEBUG_NumSequenceFreed = 0; - m_DEBUG_NumSequenceResidual = 0; - -#endif + m_DEBUG_NumSequenceAlloc = 0; + m_DEBUG_NumSequenceFreed = 0; + m_DEBUG_NumSequenceResidual = 0; +#endif } -ICARUS_Instance::~ICARUS_Instance( void ) -{ -} +ICARUS_Instance::~ICARUS_Instance(void) {} /* ------------------------- @@ -61,13 +57,12 @@ Create ------------------------- */ -ICARUS_Instance *ICARUS_Instance::Create( interface_export_t *ie ) -{ +ICARUS_Instance *ICARUS_Instance::Create(interface_export_t *ie) { ICARUS_Instance *instance = new ICARUS_Instance; instance->m_interface = ie; #ifdef _DEBUG - Com_Printf( "ICARUS Instance successfully created\n" ); + Com_Printf("ICARUS Instance successfully created\n"); #endif return instance; @@ -79,31 +74,27 @@ Free ------------------------- */ -int ICARUS_Instance::Free( void ) -{ - sequencer_l::iterator sri; +int ICARUS_Instance::Free(void) { + sequencer_l::iterator sri; - //Delete any residual sequencers - STL_ITERATE( sri, m_sequencers ) - { + // Delete any residual sequencers + STL_ITERATE(sri, m_sequencers) { delete (*sri); - + #ifdef _DEBUG m_DEBUG_NumSequencerResidual++; #endif - } m_sequencers.clear(); m_signals.clear(); - sequence_l::iterator si; + sequence_l::iterator si; - //Delete any residual sequences - STL_ITERATE( si, m_sequences ) - { + // Delete any residual sequences + STL_ITERATE(si, m_sequences) { delete (*si); #ifdef _DEBUG @@ -111,7 +102,6 @@ int ICARUS_Instance::Free( void ) m_DEBUG_NumSequenceResidual++; #endif - } m_sequences.clear(); @@ -125,20 +115,19 @@ Delete ------------------------- */ -int ICARUS_Instance::Delete( void ) -{ +int ICARUS_Instance::Delete(void) { Free(); #ifdef _DEBUG - Com_Printf( "\nICARUS Instance Debug Info:\n---------------------------\n" ); - Com_Printf( "Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc ); - Com_Printf( "Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed ); - Com_Printf( "Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual ); - Com_Printf( "Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc ); - Com_Printf( "Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed ); - Com_Printf( "Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual ); - Com_Printf( "\n" ); + Com_Printf("\nICARUS Instance Debug Info:\n---------------------------\n"); + Com_Printf("Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc); + Com_Printf("Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed); + Com_Printf("Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual); + Com_Printf("Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc); + Com_Printf("Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed); + Com_Printf("Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual); + Com_Printf("\n"); #endif delete this; @@ -152,16 +141,15 @@ GetSequencer ------------------------- */ -CSequencer *ICARUS_Instance::GetSequencer( int ownerID ) -{ - CSequencer *sequencer = CSequencer::Create(); - CTaskManager *taskManager = CTaskManager::Create(); +CSequencer *ICARUS_Instance::GetSequencer(int ownerID) { + CSequencer *sequencer = CSequencer::Create(); + CTaskManager *taskManager = CTaskManager::Create(); - sequencer->Init( ownerID, m_interface, taskManager, this ); + sequencer->Init(ownerID, m_interface, taskManager, this); - taskManager->Init( sequencer ); + taskManager->Init(sequencer); - STL_INSERT( m_sequencers, sequencer ); + STL_INSERT(m_sequencers, sequencer); #ifdef _DEBUG @@ -178,20 +166,18 @@ DeleteSequencer ------------------------- */ -void ICARUS_Instance::DeleteSequencer( CSequencer *sequencer ) -{ +void ICARUS_Instance::DeleteSequencer(CSequencer *sequencer) { // added 2/12/2 to properly delete blocks that were passed to the task manager sequencer->Recall(); - CTaskManager *taskManager = sequencer->GetTaskManager(); + CTaskManager *taskManager = sequencer->GetTaskManager(); - if ( taskManager ) - { + if (taskManager) { taskManager->Free(); delete taskManager; } - m_sequencers.remove( sequencer ); + m_sequencers.remove(sequencer); sequencer->Free(); delete sequencer; @@ -201,7 +187,6 @@ void ICARUS_Instance::DeleteSequencer( CSequencer *sequencer ) m_DEBUG_NumSequencerFreed++; #endif - } /* @@ -210,21 +195,20 @@ GetSequence ------------------------- */ -CSequence *ICARUS_Instance::GetSequence( void ) -{ - CSequence *sequence = CSequence::Create(); +CSequence *ICARUS_Instance::GetSequence(void) { + CSequence *sequence = CSequence::Create(); - //Assign the GUID - sequence->SetID( m_GUID++ ); - sequence->SetOwner( this ); + // Assign the GUID + sequence->SetID(m_GUID++); + sequence->SetOwner(this); - STL_INSERT( m_sequences, sequence ); + STL_INSERT(m_sequences, sequence); #ifdef _DEBUG m_DEBUG_NumSequenceAlloc++; -#endif +#endif return sequence; } @@ -235,12 +219,10 @@ GetSequence ------------------------- */ -CSequence *ICARUS_Instance::GetSequence( int id ) -{ - sequence_l::iterator si; - STL_ITERATE( si, m_sequences ) - { - if ( (*si)->GetID() == id ) +CSequence *ICARUS_Instance::GetSequence(int id) { + sequence_l::iterator si; + STL_ITERATE(si, m_sequences) { + if ((*si)->GetID() == id) return (*si); } @@ -253,9 +235,8 @@ DeleteSequence ------------------------- */ -void ICARUS_Instance::DeleteSequence( CSequence *sequence ) -{ - m_sequences.remove( sequence ); +void ICARUS_Instance::DeleteSequence(CSequence *sequence) { + m_sequences.remove(sequence); delete sequence; @@ -263,7 +244,7 @@ void ICARUS_Instance::DeleteSequence( CSequence *sequence ) m_DEBUG_NumSequenceFreed++; -#endif +#endif } /* @@ -272,22 +253,20 @@ AllocateSequences ------------------------- */ -int ICARUS_Instance::AllocateSequences( int numSequences, int *idTable ) -{ - CSequence *sequence; +int ICARUS_Instance::AllocateSequences(int numSequences, int *idTable) { + CSequence *sequence; - for ( int i = 0; i < numSequences; i++ ) - { - //If the GUID of this sequence is higher than the current, take this a the "current" GUID - if ( idTable[i] > m_GUID ) + for (int i = 0; i < numSequences; i++) { + // If the GUID of this sequence is higher than the current, take this a the "current" GUID + if (idTable[i] > m_GUID) m_GUID = idTable[i]; - //Allocate the container sequence - if ( ( sequence = GetSequence() ) == NULL ) + // Allocate the container sequence + if ((sequence = GetSequence()) == NULL) return false; - //Override the given GUID with the real one - sequence->SetID( idTable[i] ); + // Override the given GUID with the real one + sequence->SetID(idTable[i]); } return true; @@ -299,37 +278,27 @@ SaveSequenceIDTable ------------------------- */ -int ICARUS_Instance::SaveSequenceIDTable( void ) -{ - //Save out the number of sequences to follow - int numSequences = m_sequences.size(); +int ICARUS_Instance::SaveSequenceIDTable(void) { + // Save out the number of sequences to follow + int numSequences = m_sequences.size(); - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.write_chunk( - INT_ID('#', 'S', 'E', 'Q'), - numSequences); + saved_game.write_chunk(INT_ID('#', 'S', 'E', 'Q'), numSequences); - //Sequences are saved first, by ID and information - sequence_l::iterator sqi; + // Sequences are saved first, by ID and information + sequence_l::iterator sqi; - //First pass, save all sequences ID for reconstruction - int *idTable = new int[ numSequences ]; - int itr = 0; + // First pass, save all sequences ID for reconstruction + int *idTable = new int[numSequences]; + int itr = 0; - if ( idTable == NULL ) + if (idTable == NULL) return false; - STL_ITERATE( sqi, m_sequences ) - { - idTable[itr++] = (*sqi)->GetID(); - } + STL_ITERATE(sqi, m_sequences) { idTable[itr++] = (*sqi)->GetID(); } - saved_game.write_chunk( - INT_ID('S', 'Q', 'T', 'B'), - idTable, - numSequences); + saved_game.write_chunk(INT_ID('S', 'Q', 'T', 'B'), idTable, numSequences); delete[] idTable; @@ -342,17 +311,13 @@ SaveSequences ------------------------- */ -int ICARUS_Instance::SaveSequences( void ) -{ - //Save out a listing of all the used sequences by ID +int ICARUS_Instance::SaveSequences(void) { + // Save out a listing of all the used sequences by ID SaveSequenceIDTable(); - //Save all the information in order - sequence_l::iterator sqi; - STL_ITERATE( sqi, m_sequences ) - { - (*sqi)->Save(); - } + // Save all the information in order + sequence_l::iterator sqi; + STL_ITERATE(sqi, m_sequences) { (*sqi)->Save(); } return true; } @@ -363,24 +328,17 @@ SaveSequencers ------------------------- */ -int ICARUS_Instance::SaveSequencers( void ) -{ - //Save out the number of sequences to follow - int numSequencers = m_sequencers.size(); +int ICARUS_Instance::SaveSequencers(void) { + // Save out the number of sequences to follow + int numSequencers = m_sequencers.size(); - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.write_chunk( - INT_ID('#', 'S', 'Q', 'R'), - numSequencers); + saved_game.write_chunk(INT_ID('#', 'S', 'Q', 'R'), numSequencers); - //The sequencers are then saved - sequencer_l::iterator si; - STL_ITERATE( si, m_sequencers ) - { - (*si)->Save(); - } + // The sequencers are then saved + sequencer_l::iterator si; + STL_ITERATE(si, m_sequencers) { (*si)->Save(); } return true; } @@ -391,38 +349,28 @@ SaveSignals ------------------------- */ -int ICARUS_Instance::SaveSignals( void ) -{ - int numSignals = m_signals.size(); +int ICARUS_Instance::SaveSignals(void) { + int numSignals = m_signals.size(); - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.write_chunk( - INT_ID('I', 'S', 'I', 'G'), - numSignals); + saved_game.write_chunk(INT_ID('I', 'S', 'I', 'G'), numSignals); - signal_m::iterator si; - STL_ITERATE( si, m_signals ) - { - //m_interface->I_WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); + signal_m::iterator si; + STL_ITERATE(si, m_signals) { + // m_interface->I_WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); const char *name = ((*si).first).c_str(); - - //Make sure this is a valid string - assert( ( name != NULL ) && ( name[0] != '\0' ) ); - - int length = strlen( name ) + 1; - - //Save out the string size - saved_game.write_chunk( - INT_ID('S', 'I', 'G', '#'), - length); - - //Write out the string - saved_game.write_chunk( - INT_ID('S', 'I', 'G', 'N'), - name, - length); + + // Make sure this is a valid string + assert((name != NULL) && (name[0] != '\0')); + + int length = strlen(name) + 1; + + // Save out the string size + saved_game.write_chunk(INT_ID('S', 'I', 'G', '#'), length); + + // Write out the string + saved_game.write_chunk(INT_ID('S', 'I', 'G', 'N'), name, length); } return true; @@ -434,33 +382,27 @@ Save ------------------------- */ -int ICARUS_Instance::Save( void ) -{ - //Save out a ICARUS save block header with the ICARUS version - double version = ICARUS_VERSION; +int ICARUS_Instance::Save(void) { + // Save out a ICARUS save block header with the ICARUS version + double version = ICARUS_VERSION; - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.write_chunk( - INT_ID('I', 'C', 'A', 'R'), - version); + saved_game.write_chunk(INT_ID('I', 'C', 'A', 'R'), version); - //Save out the signals - if ( SaveSignals() == false ) + // Save out the signals + if (SaveSignals() == false) return false; - //Save out the sequences - if ( SaveSequences() == false ) + // Save out the sequences + if (SaveSequences() == false) return false; - //Save out the sequencers - if ( SaveSequencers() == false ) + // Save out the sequencers + if (SaveSequencers() == false) return false; - saved_game.write_chunk( - INT_ID('I', 'E', 'N', 'D'), - version); + saved_game.write_chunk(INT_ID('I', 'E', 'N', 'D'), version); return true; } @@ -471,37 +413,27 @@ LoadSignals ------------------------- */ -int ICARUS_Instance::LoadSignals( void ) -{ +int ICARUS_Instance::LoadSignals(void) { int numSignals = 0; - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.read_chunk( - INT_ID('I', 'S', 'I', 'G'), - numSignals); + saved_game.read_chunk(INT_ID('I', 'S', 'I', 'G'), numSignals); - for ( int i = 0; i < numSignals; i++ ) - { - char buffer[1024]; - int length = 0; + for (int i = 0; i < numSignals; i++) { + char buffer[1024]; + int length = 0; - //Get the size of the string - saved_game.read_chunk( - INT_ID('S', 'I', 'G', '#'), - length); + // Get the size of the string + saved_game.read_chunk(INT_ID('S', 'I', 'G', '#'), length); - assert( length < (int)sizeof( buffer ) ); + assert(length < (int)sizeof(buffer)); - //Get the string - saved_game.read_chunk( - INT_ID('S', 'I', 'G', 'N'), - buffer, - length); + // Get the string + saved_game.read_chunk(INT_ID('S', 'I', 'G', 'N'), buffer, length); - //Turn it on and add it to the system - Signal( (const char *) &buffer ); + // Turn it on and add it to the system + Signal((const char *)&buffer); } return true; @@ -513,15 +445,14 @@ LoadSequence ------------------------- */ -int ICARUS_Instance::LoadSequence( void ) -{ - CSequence *sequence = GetSequence(); +int ICARUS_Instance::LoadSequence(void) { + CSequence *sequence = GetSequence(); - //Load the sequence back in + // Load the sequence back in sequence->Load(); - //If this sequence had a higher GUID than the current, save it - if ( sequence->GetID() > m_GUID ) + // If this sequence had a higher GUID than the current, save it + if (sequence->GetID() > m_GUID) m_GUID = sequence->GetID(); return true; @@ -533,47 +464,39 @@ LoadSequence ------------------------- */ -int ICARUS_Instance::LoadSequences( void ) -{ - CSequence *sequence; - int numSequences = 0; +int ICARUS_Instance::LoadSequences(void) { + CSequence *sequence; + int numSequences = 0; - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - //Get the number of sequences to read in - saved_game.read_chunk( - INT_ID('#', 'S', 'E', 'Q'), - numSequences); + // Get the number of sequences to read in + saved_game.read_chunk(INT_ID('#', 'S', 'E', 'Q'), numSequences); - int *idTable = new int[ numSequences ]; + int *idTable = new int[numSequences]; - if ( idTable == NULL ) + if (idTable == NULL) return false; - //Load the sequencer ID table - saved_game.read_chunk( - INT_ID('S', 'Q', 'T', 'B'), - idTable, - numSequences); + // Load the sequencer ID table + saved_game.read_chunk(INT_ID('S', 'Q', 'T', 'B'), idTable, numSequences); - //First pass, allocate all container sequences and give them their proper IDs - if ( AllocateSequences( numSequences, idTable ) == false ) + // First pass, allocate all container sequences and give them their proper IDs + if (AllocateSequences(numSequences, idTable) == false) return false; - //Second pass, load all sequences - for ( int i = 0; i < numSequences; i++ ) - { - //Get the proper sequence for this load - if ( ( sequence = GetSequence( idTable[i] ) ) == NULL ) + // Second pass, load all sequences + for (int i = 0; i < numSequences; i++) { + // Get the proper sequence for this load + if ((sequence = GetSequence(idTable[i])) == NULL) return false; - //Load the sequence - if ( ( sequence->Load() ) == false ) + // Load the sequence + if ((sequence->Load()) == false) return false; } - //Free the idTable + // Free the idTable delete[] idTable; return true; @@ -585,27 +508,22 @@ LoadSequencers ------------------------- */ -int ICARUS_Instance::LoadSequencers( void ) -{ - CSequencer *sequencer; - int numSequencers = 0; - - ojk::SavedGameHelper saved_game( - m_interface->saved_game); - - //Get the number of sequencers to load - saved_game.read_chunk( - INT_ID('#', 'S', 'Q', 'R'), - numSequencers); - - //Load all sequencers - for ( int i = 0; i < numSequencers; i++ ) - { - //NOTENOTE: The ownerID will be replaced in the loading process - if ( ( sequencer = GetSequencer( -1 ) ) == NULL ) +int ICARUS_Instance::LoadSequencers(void) { + CSequencer *sequencer; + int numSequencers = 0; + + ojk::SavedGameHelper saved_game(m_interface->saved_game); + + // Get the number of sequencers to load + saved_game.read_chunk(INT_ID('#', 'S', 'Q', 'R'), numSequencers); + + // Load all sequencers + for (int i = 0; i < numSequencers; i++) { + // NOTENOTE: The ownerID will be replaced in the loading process + if ((sequencer = GetSequencer(-1)) == NULL) return false; - if ( sequencer->Load() == false ) + if (sequencer->Load() == false) return false; } @@ -618,52 +536,42 @@ Load ------------------------- */ -int ICARUS_Instance::Load( void ) -{ - //Clear out any old information +int ICARUS_Instance::Load(void) { + // Clear out any old information Free(); - //Check to make sure we're at the ICARUS save block - double version = 0.0; + // Check to make sure we're at the ICARUS save block + double version = 0.0; - ojk::SavedGameHelper saved_game( - m_interface->saved_game); + ojk::SavedGameHelper saved_game(m_interface->saved_game); - saved_game.read_chunk( - INT_ID('I', 'C', 'A', 'R'), - version); + saved_game.read_chunk(INT_ID('I', 'C', 'A', 'R'), version); - //Versions must match! - if ( version != ICARUS_VERSION ) - { - m_interface->I_DPrintf( WL_ERROR, "save game data contains outdated ICARUS version information!\n"); + // Versions must match! + if (version != ICARUS_VERSION) { + m_interface->I_DPrintf(WL_ERROR, "save game data contains outdated ICARUS version information!\n"); return false; } - //Load all signals - if ( LoadSignals() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load signals from save game!\n"); + // Load all signals + if (LoadSignals() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load signals from save game!\n"); return false; } - //Load in all sequences - if ( LoadSequences() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load sequences from save game!\n"); + // Load in all sequences + if (LoadSequences() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load sequences from save game!\n"); return false; } - //Load in all sequencers - if ( LoadSequencers() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load sequencers from save game!\n"); + // Load in all sequencers + if (LoadSequencers() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load sequencers from save game!\n"); return false; } - saved_game.read_chunk( - INT_ID('I', 'E', 'N', 'D'), - version); + saved_game.read_chunk(INT_ID('I', 'E', 'N', 'D'), version); return true; } @@ -674,10 +582,7 @@ Signal ------------------------- */ -void ICARUS_Instance::Signal( const char *identifier ) -{ - m_signals[ identifier ] = 1; -} +void ICARUS_Instance::Signal(const char *identifier) { m_signals[identifier] = 1; } /* ------------------------- @@ -685,13 +590,12 @@ CheckSignal ------------------------- */ -bool ICARUS_Instance::CheckSignal( const char *identifier ) -{ - signal_m::iterator smi; +bool ICARUS_Instance::CheckSignal(const char *identifier) { + signal_m::iterator smi; - smi = m_signals.find( identifier ); + smi = m_signals.find(identifier); - if ( smi == m_signals.end() ) + if (smi == m_signals.end()) return false; return true; @@ -703,7 +607,4 @@ ClearSignal ------------------------- */ -void ICARUS_Instance::ClearSignal( const char *identifier ) -{ - m_signals.erase( identifier ); -} +void ICARUS_Instance::ClearSignal(const char *identifier) { m_signals.erase(identifier); } diff --git a/codeJK2/icarus/Interface.cpp b/codeJK2/icarus/Interface.cpp index 106a6d8d36..9f1336b88c 100644 --- a/codeJK2/icarus/Interface.cpp +++ b/codeJK2/icarus/Interface.cpp @@ -1,18 +1,17 @@ // ICARUS Engine Interface File // -// This file is the only section of the ICARUS systems that +// This file is the only section of the ICARUS systems that // is not directly portable from engine to engine. // // -- jweier #include "Interface.h" -void Interface_Init( interface_export_t *pe ) -{ +void Interface_Init(interface_export_t *pe) { - //TODO: This is where you link up all your functions to the engine + // TODO: This is where you link up all your functions to the engine - //Example: + // Example: // - // pe->I_GetEntityByName = ENGINE_GetEntityByName; + // pe->I_GetEntityByName = ENGINE_GetEntityByName; } diff --git a/codeJK2/icarus/Interpreter.cpp b/codeJK2/icarus/Interpreter.cpp index 2fe1f01c78..df2109561c 100644 --- a/codeJK2/icarus/Interpreter.cpp +++ b/codeJK2/icarus/Interpreter.cpp @@ -3,11 +3,11 @@ // -- jweier #ifdef _WIN32 - #include //For getcwd() - #include //For getch() +#include //For getcwd() +#include //For getch() #else - #include - #include +#include +#include #endif #include @@ -24,110 +24,110 @@ =================================================================================================== */ -//FIXME: The following tables should be passed in to the interpreter for flexibility - -//Symbol Table - -keywordArray_t CInterpreter::m_symbolKeywords[] = -{ - //Blocks - "{", TK_BLOCK_START, - "}", TK_BLOCK_END, - - //Vectors - "<", TK_VECTOR_START, - ">", TK_VECTOR_END, - - //Groups - "(", TK_OPEN_PARENTHESIS, - ")", TK_CLOSED_PARENTHESIS, - - "=", TK_EQUALS, - "!", TK_NOT, - - //End - "", TK_EOF, +// FIXME: The following tables should be passed in to the interpreter for flexibility + +// Symbol Table + +keywordArray_t CInterpreter::m_symbolKeywords[] = { + // Blocks + "{", + TK_BLOCK_START, + "}", + TK_BLOCK_END, + + // Vectors + "<", + TK_VECTOR_START, + ">", + TK_VECTOR_END, + + // Groups + "(", + TK_OPEN_PARENTHESIS, + ")", + TK_CLOSED_PARENTHESIS, + + "=", + TK_EQUALS, + "!", + TK_NOT, + + // End + "", + TK_EOF, }; -keywordArray_t CInterpreter::m_conditionalKeywords[] = -{ - "", TK_EOF, +keywordArray_t CInterpreter::m_conditionalKeywords[] = { + "", + TK_EOF, }; -//ID Table - -keywordArray_t CInterpreter::m_IDKeywords[] = -{ - "AFFECT", ID_AFFECT, - "SOUND", ID_SOUND, - "MOVE", ID_MOVE, - "ROTATE", ID_ROTATE, - "WAIT", ID_WAIT, - "SET", ID_SET, - "LOOP", ID_LOOP, - "PRINT", ID_PRINT, - "TAG", ID_TAG, - "USE", ID_USE, - "FLUSH", ID_FLUSH, - "RUN", ID_RUN, - "KILL", ID_KILL, - "REMOVE", ID_REMOVE, - "CAMERA", ID_CAMERA, - "GET", ID_GET, - "RANDOM", ID_RANDOM, - "IF", ID_IF, - "ELSE", ID_ELSE, - "REM", ID_REM, - "FLOAT", TK_FLOAT, - "VECTOR", TK_VECTOR, - "STRING", TK_STRING, - "TASK", ID_TASK, - "DO", ID_DO, - "DECLARE", ID_DECLARE, - "FREE", ID_FREE, - "DOWAIT", ID_DOWAIT, - "SIGNAL", ID_SIGNAL, - "WAITSIGNAL", ID_WAITSIGNAL, - "PLAY", ID_PLAY, - - "", ID_EOF, -}; +// ID Table + +keywordArray_t CInterpreter::m_IDKeywords[] = { + "AFFECT", ID_AFFECT, "SOUND", ID_SOUND, "MOVE", ID_MOVE, "ROTATE", ID_ROTATE, "WAIT", ID_WAIT, "SET", ID_SET, "LOOP", + ID_LOOP, "PRINT", ID_PRINT, "TAG", ID_TAG, "USE", ID_USE, "FLUSH", ID_FLUSH, "RUN", ID_RUN, "KILL", ID_KILL, + "REMOVE", ID_REMOVE, "CAMERA", ID_CAMERA, "GET", ID_GET, "RANDOM", ID_RANDOM, "IF", ID_IF, "ELSE", ID_ELSE, "REM", + ID_REM, "FLOAT", TK_FLOAT, "VECTOR", TK_VECTOR, "STRING", TK_STRING, "TASK", ID_TASK, "DO", ID_DO, "DECLARE", ID_DECLARE, + "FREE", ID_FREE, "DOWAIT", ID_DOWAIT, "SIGNAL", ID_SIGNAL, "WAITSIGNAL", ID_WAITSIGNAL, "PLAY", ID_PLAY, -//Type Table - -keywordArray_t CInterpreter::m_typeKeywords[] = -{ - //Set types - "ANGLES", TYPE_ANGLES, - "ORIGIN", TYPE_ORIGIN, - - //Affect types - "INSERT", TYPE_INSERT, - "FLUSH", TYPE_FLUSH, - - //Get types - "FLOAT", TK_FLOAT, - "INT", TK_INT, - "VECTOR", TK_VECTOR, - "STRING", TK_STRING, - - "PAN", TYPE_PAN, - "ZOOM", TYPE_ZOOM, - "MOVE", TYPE_MOVE, - "FADE", TYPE_FADE, - "PATH", TYPE_PATH, - "ENABLE", TYPE_ENABLE, - "DISABLE", TYPE_DISABLE, - "SHAKE", TYPE_SHAKE, - "ROLL", TYPE_ROLL, - "TRACK", TYPE_TRACK, - "FOLLOW", TYPE_FOLLOW, - "DISTANCE", TYPE_DISTANCE, - - //End - "", TYPE_EOF, + "", ID_EOF, }; +// Type Table + +keywordArray_t CInterpreter::m_typeKeywords[] = { + // Set types + "ANGLES", + TYPE_ANGLES, + "ORIGIN", + TYPE_ORIGIN, + + // Affect types + "INSERT", + TYPE_INSERT, + "FLUSH", + TYPE_FLUSH, + + // Get types + "FLOAT", + TK_FLOAT, + "INT", + TK_INT, + "VECTOR", + TK_VECTOR, + "STRING", + TK_STRING, + + "PAN", + TYPE_PAN, + "ZOOM", + TYPE_ZOOM, + "MOVE", + TYPE_MOVE, + "FADE", + TYPE_FADE, + "PATH", + TYPE_PATH, + "ENABLE", + TYPE_ENABLE, + "DISABLE", + TYPE_DISABLE, + "SHAKE", + TYPE_SHAKE, + "ROLL", + TYPE_ROLL, + "TRACK", + TYPE_TRACK, + "FOLLOW", + TYPE_FOLLOW, + "DISTANCE", + TYPE_DISTANCE, + + // End + "", + TYPE_EOF, +}; /* =================================================================================================== @@ -137,13 +137,9 @@ keywordArray_t CInterpreter::m_typeKeywords[] = =================================================================================================== */ -CInterpreter::CInterpreter() -{ -} +CInterpreter::CInterpreter() {} -CInterpreter::~CInterpreter() -{ -} +CInterpreter::~CInterpreter() {} /* =================================================================================================== @@ -153,45 +149,39 @@ CInterpreter::~CInterpreter() =================================================================================================== */ -int CInterpreter::Error( char *format, ... ) -{ - va_list argptr; - char *error_file, error_msg[1024]="", work_dir[1024]="", out_msg[1024]=""; - int error_line = m_iCurrentLine; // m_tokenizer->GetCurLine(); +int CInterpreter::Error(char *format, ...) { + va_list argptr; + char *error_file, error_msg[1024] = "", work_dir[1024] = "", out_msg[1024] = ""; + int error_line = m_iCurrentLine; // m_tokenizer->GetCurLine(); - m_tokenizer->GetCurFilename( &error_file ); - if (!error_file) - { + m_tokenizer->GetCurFilename(&error_file); + if (!error_file) { // 99% of the time we'll get here now, because of pushed parse streams // error_file = (char *)m_sCurrentFile.c_str(); } - va_start (argptr, format); - vsprintf (error_msg, format, argptr); - va_end (argptr); + va_start(argptr, format); + vsprintf(error_msg, format, argptr); + va_end(argptr); - strcpy((char *) work_dir, getcwd( (char *) &work_dir, 1024 ) ); + strcpy((char *)work_dir, getcwd((char *)&work_dir, 1024)); - if (error_file[1] == ':') - { - sprintf((char *) out_msg, "%s (%d) : error: %s\n", error_file, error_line, error_msg); - } - else - { - sprintf((char *) out_msg, "%s\\%s (%d) : error: %s\n", work_dir, error_file, error_line, error_msg); + if (error_file[1] == ':') { + sprintf((char *)out_msg, "%s (%d) : error: %s\n", error_file, error_line, error_msg); + } else { + sprintf((char *)out_msg, "%s\\%s (%d) : error: %s\n", work_dir, error_file, error_line, error_msg); } - if (m_sCurrentLine.length()) - { + if (m_sCurrentLine.length()) { strcat(out_msg, "\nLine:\n\n"); strcat(out_msg, m_sCurrentLine.c_str()); strcat(out_msg, "\n"); } -#ifdef __POP_UPS__ +#ifdef __POP_UPS__ - MessageBox( NULL, out_msg, "Error", MB_OK ); + MessageBox(NULL, out_msg, "Error", MB_OK); #else @@ -205,8 +195,7 @@ int CInterpreter::Error( char *format, ... ) // This'll mean that technically it's saying block 1 is wrong, rather than the one in between them, but I can // live with that. // - if (m_iBadCBlockNumber == 0) - { + if (m_iBadCBlockNumber == 0) { m_iBadCBlockNumber = 1; } return false; @@ -226,8 +215,7 @@ InitVars ------------------------- */ -void CInterpreter::InitVars( void ) -{ +void CInterpreter::InitVars(void) { m_vars.clear(); m_varMap.clear(); } @@ -238,12 +226,10 @@ FreeVars ------------------------- */ -void CInterpreter::FreeVars( void ) -{ - variable_v::iterator vi; +void CInterpreter::FreeVars(void) { + variable_v::iterator vi; - for ( vi = m_vars.begin(); vi != m_vars.end(); ++vi ) - { + for (vi = m_vars.begin(); vi != m_vars.end(); ++vi) { delete (*vi); } @@ -256,23 +242,22 @@ AddVar ------------------------- */ -variable_t *CInterpreter::AddVar( const char *name, int type ) -{ - variable_t *var; +variable_t *CInterpreter::AddVar(const char *name, int type) { + variable_t *var; var = new variable_t; - if ( var == NULL ) + if (var == NULL) return NULL; - //Specify the type + // Specify the type var->type = type; - //Retain the name internally - strncpy( (char *) var->name, name, MAX_VAR_NAME ); + // Retain the name internally + strncpy((char *)var->name, name, MAX_VAR_NAME); - //Associate it - m_varMap[ name ] = var; + // Associate it + m_varMap[name] = var; return var; } @@ -283,13 +268,12 @@ FindVar ------------------------- */ -variable_t *CInterpreter::FindVar( const char *name ) -{ - variable_m::iterator vmi; +variable_t *CInterpreter::FindVar(const char *name) { + variable_m::iterator vmi; - vmi = m_varMap.find( name ); + vmi = m_varMap.find(name); - if ( vmi == m_varMap.end() ) + if (vmi == m_varMap.end()) return NULL; return (*vmi).second; @@ -301,35 +285,34 @@ GetVariable ------------------------- */ -int CInterpreter::GetVariable( int type ) -{ - const char *varName; - variable_t *var; - CToken *token; +int CInterpreter::GetVariable(int type) { + const char *varName; + variable_t *var; + CToken *token; - //Get the variable's name - token = m_tokenizer->GetToken( 0, 0 ); + // Get the variable's name + token = m_tokenizer->GetToken(0, 0); varName = token->GetStringValue(); - //See if we already have a variable by this name - var = FindVar( varName ); + // See if we already have a variable by this name + var = FindVar(varName); - //Variable names must be unique on creation - if ( var ) - return Error( "\"%s\" : already exists\n", varName ); + // Variable names must be unique on creation + if (var) + return Error("\"%s\" : already exists\n", varName); - //Add the variable - AddVar( varName, type ); + // Add the variable + AddVar(varName, type); - //Insert the variable into the stream + // Insert the variable into the stream - CBlock block; + CBlock block; - block.Create( TYPE_VARIABLE ); - block.Write( TK_FLOAT, (float) type ); - block.Write( TK_STRING, varName ); + block.Create(TYPE_VARIABLE); + block.Write(TK_FLOAT, (float)type); + block.Write(TK_STRING, varName); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); token->Delete(); @@ -344,30 +327,25 @@ int CInterpreter::GetVariable( int type ) =================================================================================================== */ -int CInterpreter::GetVector( CBlock *block ) -{ - //Look for a tag - if ( MatchTag() ) - { - return GetTag( block ); +int CInterpreter::GetVector(CBlock *block) { + // Look for a tag + if (MatchTag()) { + return GetTag(block); } - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - if ( Match( TK_VECTOR_START ) ) - { - //Get the vector - block->Write( TK_VECTOR, (float) TK_VECTOR ); + if (Match(TK_VECTOR_START)) { + // Get the vector + block->Write(TK_VECTOR, (float)TK_VECTOR); - for (int i=0; i<3; i++) - GetFloat( block ); + for (int i = 0; i < 3; i++) + GetFloat(block); - if (!Match( TK_VECTOR_END )) - { + if (!Match(TK_VECTOR_END)) { return Error("syntax error : expected end of vector"); } @@ -387,20 +365,18 @@ int CInterpreter::GetVector( CBlock *block ) =================================================================================================== */ -int CInterpreter::MatchTag( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchTag(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_TAG ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_TAG) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -418,20 +394,18 @@ int CInterpreter::MatchTag( void ) =================================================================================================== */ -int CInterpreter::MatchGet( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchGet(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_GET ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_GET) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -449,20 +423,18 @@ int CInterpreter::MatchGet( void ) =================================================================================================== */ -int CInterpreter::MatchRandom( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchRandom(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_RANDOM ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_RANDOM) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -480,12 +452,10 @@ int CInterpreter::MatchRandom( void ) =================================================================================================== */ -int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) -{ +int CInterpreter::FindSymbol(const char *name, keywordArray_t *table) { keywordArray_t *ids; - for (ids = table; (strcmp(ids->m_keyword, "")); ids++) - { + for (ids = table; (strcmp(ids->m_keyword, "")); ids++) { if (!stricmp(name, ids->m_keyword)) return ids->m_tokenvalue; } @@ -493,7 +463,6 @@ int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) return -1; } - /* =================================================================================================== @@ -504,19 +473,17 @@ int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) =================================================================================================== */ -//NOTENOTE: LookAhead() was separated from Match() for clarity +// NOTENOTE: LookAhead() was separated from Match() for clarity -int CInterpreter::Match( int token_id ) -{ - CToken *token; +int CInterpreter::Match(int token_id) { + CToken *token; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); + + if (token->GetType() != token_id) { + // This may have been a check, so don't loose the token + m_tokenizer->PutBackToken(token); - if ( token->GetType() != token_id ) - { - //This may have been a check, so don't loose the token - m_tokenizer->PutBackToken( token ); - return false; } @@ -529,12 +496,11 @@ GetNextType ------------------------- */ -int CInterpreter::GetNextType( void ) -{ - CToken *token = m_tokenizer->GetToken( 0, 0 ); - int id = token->GetType(); +int CInterpreter::GetNextType(void) { + CToken *token = m_tokenizer->GetToken(0, 0); + int id = token->GetType(); - m_tokenizer->PutBackToken( token ); + m_tokenizer->PutBackToken(token); return id; } @@ -549,20 +515,18 @@ int CInterpreter::GetNextType( void ) =================================================================================================== */ -int CInterpreter::LookAhead( int token_id ) -{ - CToken *token; +int CInterpreter::LookAhead(int token_id) { + CToken *token; + + token = m_tokenizer->GetToken(0, 0); - token = m_tokenizer->GetToken( 0, 0 ); + if (token->GetType() != token_id) { + m_tokenizer->PutBackToken(token); - if ( token->GetType() != token_id ) - { - m_tokenizer->PutBackToken( token ); - return false; } - m_tokenizer->PutBackToken( token ); + m_tokenizer->PutBackToken(token); return true; } @@ -577,10 +541,8 @@ int CInterpreter::LookAhead( int token_id ) =================================================================================================== */ -const char *CInterpreter::GetTokenName( int token_id ) -{ - switch ( token_id ) - { +const char *CInterpreter::GetTokenName(int token_id) { + switch (token_id) { case TK_STRING: return "STRING"; break; @@ -625,39 +587,32 @@ const char *CInterpreter::GetTokenName( int token_id ) =================================================================================================== */ -int CInterpreter::GetFloat( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetFloat(CBlock *block) { + CToken *token; + int type; - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - //Look for a random - if ( MatchRandom() ) - { - return GetRandom( block ); + // Look for a random + if (MatchRandom()) { + return GetRandom(block); } - token = m_tokenizer->GetToken(0,0); + token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - //Floats can accept either int or float values - if ( ( type != TK_FLOAT ) && ( type != TK_INT ) ) - { - return Error("syntax error : expected float; found %s", GetTokenName(type) ); - } - - if (type == TK_FLOAT) - { - block->Write( TK_FLOAT, (float) token->GetFloatValue() ); + // Floats can accept either int or float values + if ((type != TK_FLOAT) && (type != TK_INT)) { + return Error("syntax error : expected float; found %s", GetTokenName(type)); } - else - { - block->Write( TK_FLOAT, (float) token->GetIntValue() ); + + if (type == TK_FLOAT) { + block->Write(TK_FLOAT, (float)token->GetFloatValue()); + } else { + block->Write(TK_FLOAT, (float)token->GetIntValue()); } token->Delete(); @@ -675,10 +630,7 @@ int CInterpreter::GetFloat( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetInteger( CBlock *block ) -{ - return GetFloat( block ); -} +int CInterpreter::GetInteger(CBlock *block) { return GetFloat(block); } /* =================================================================================================== @@ -690,59 +642,53 @@ int CInterpreter::GetInteger( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetString( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetString(CBlock *block) { + CToken *token; + int type; - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - //Look for a random - if ( MatchRandom() ) - { - return GetRandom( block ); + // Look for a random + if (MatchRandom()) { + return GetRandom(block); } token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( (type != TK_STRING) && (type != TK_CHAR) ) - { + if ((type != TK_STRING) && (type != TK_CHAR)) { return Error("syntax error : expected string; found %s", GetTokenName(type)); } -//UGLY HACK!!! + // UGLY HACK!!! - const char *temptr; - char temp[1024]; + const char *temptr; + char temp[1024]; temptr = token->GetStringValue(); - if ( strlen(temptr)+1 > sizeof( temp ) ) - { + if (strlen(temptr) + 1 > sizeof(temp)) { return false; } - for ( int i = 0; i < strlen( temptr ); i++ ) - { - if ( temptr[i] == '#' ) + for (int i = 0; i < strlen(temptr); i++) { + if (temptr[i] == '#') temp[i] = '\n'; else temp[i] = temptr[i]; } - - temp[ strlen( temptr ) ] = 0; -//UGLY HACK END!!! + temp[strlen(temptr)] = 0; - block->Write( TK_STRING, (const char *) &temp ); + // UGLY HACK END!!! + + block->Write(TK_STRING, (const char *)&temp); token->Delete(); - + return true; } @@ -756,15 +702,13 @@ int CInterpreter::GetString( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetIdentifier( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetIdentifier(CBlock *block) { + CToken *token; + int type; - //FIXME: Should identifiers do this? - if ( MatchGet() ) - { - if ( GetGet( block ) == false ) + // FIXME: Should identifiers do this? + if (MatchGet()) { + if (GetGet(block) == false) return false; return true; @@ -773,15 +717,14 @@ int CInterpreter::GetIdentifier( CBlock *block ) token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( type != TK_IDENTIFIER ) - { + if (type != TK_IDENTIFIER) { return Error("syntax error : expected indentifier; found %s", GetTokenName(type)); } - block->Write( TK_IDENTIFIER, (const char *) token->GetStringValue() ); + block->Write(TK_IDENTIFIER, (const char *)token->GetStringValue()); token->Delete(); - + return true; } @@ -795,23 +738,21 @@ int CInterpreter::GetIdentifier( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetEvaluator( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetEvaluator(CBlock *block) { + CToken *token; + int type; - if ( MatchGet() ) + if (MatchGet()) return false; - if ( MatchRandom() ) + if (MatchRandom()) return false; token = m_tokenizer->GetToken(0, 0); type = token->GetType(); token->Delete(); - switch ( type ) - { + switch (type) { case TK_GREATER_THAN: case TK_LESS_THAN: case TK_EQUALS: @@ -827,10 +768,10 @@ int CInterpreter::GetEvaluator( CBlock *block ) break; default: - return Error("syntax error : expected operator type, found %s", GetTokenName( type ) ); + return Error("syntax error : expected operator type, found %s", GetTokenName(type)); } - block->Write( type, 0 ); + block->Write(type, 0); return true; } @@ -845,30 +786,26 @@ int CInterpreter::GetEvaluator( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetAny( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetAny(CBlock *block) { + CToken *token; + int type; - if ( MatchGet() ) - { - if ( GetGet( block ) == false ) + if (MatchGet()) { + if (GetGet(block) == false) return false; return true; } - if ( MatchRandom() ) - { - if ( GetRandom( block ) == false ) + if (MatchRandom()) { + if (GetRandom(block) == false) return false; return true; } - if ( MatchTag() ) - { - if ( GetTag( block ) == false ) + if (MatchTag()) { + if (GetTag(block) == false) return false; return true; @@ -877,40 +814,39 @@ int CInterpreter::GetAny( CBlock *block ) token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - switch ( type ) - { + switch (type) { case TK_FLOAT: - m_tokenizer->PutBackToken( token ); - if ( GetFloat( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetFloat(block) == false) return false; break; case TK_INT: - m_tokenizer->PutBackToken( token ); - if ( GetInteger( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetInteger(block) == false) return false; break; case TK_VECTOR_START: - m_tokenizer->PutBackToken( token ); - if ( GetVector( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetVector(block) == false) return false; break; case TK_STRING: case TK_CHAR: - m_tokenizer->PutBackToken( token ); - if ( GetString( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetString(block) == false) return false; break; case TK_IDENTIFIER: - m_tokenizer->PutBackToken( token ); - if ( GetIdentifier( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetIdentifier(block) == false) return false; break; @@ -932,24 +868,21 @@ int CInterpreter::GetAny( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetType( char *get ) -{ - CToken *token; - char *string; - int type; +int CInterpreter::GetType(char *get) { + CToken *token; + char *string; + int type; token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( type != TK_IDENTIFIER ) - { + if (type != TK_IDENTIFIER) { return Error("syntax error : expected identifier; found %s", GetTokenName(type)); } - string = (char *) token->GetStringValue(); + string = (char *)token->GetStringValue(); - if ( (strlen(string) + 1) > MAX_STRING_LENGTH) - { + if ((strlen(string) + 1) > MAX_STRING_LENGTH) { Error("string exceeds 256 character limit"); return false; } @@ -969,35 +902,33 @@ int CInterpreter::GetType( char *get ) =================================================================================================== */ -//FIXME: This should use an externally defined table to match ID and functions +// FIXME: This should use an externally defined table to match ID and functions -int CInterpreter::GetID( char *id_name ) -{ - int id; +int CInterpreter::GetID(char *id_name) { + int id; - id = FindSymbol( id_name, m_IDKeywords ); + id = FindSymbol(id_name, m_IDKeywords); - if ( id == -1 ) + if (id == -1) return Error("'%s' : unknown identifier", id_name); - //FIXME: Function pointers would be awfully nice.. but not inside a class! Weee!! + // FIXME: Function pointers would be awfully nice.. but not inside a class! Weee!! - switch (id) - { - - //Affect takes control of an entity + switch (id) { + + // Affect takes control of an entity case ID_AFFECT: return GetAffect(); break; - //Wait for a specified amount of time + // Wait for a specified amount of time case ID_WAIT: return GetWait(); break; - //Generic set call + // Generic set call case ID_SET: return GetSet(); @@ -1018,7 +949,7 @@ int CInterpreter::GetID( char *id_name ) case ID_FLUSH: return GetFlush(); break; - + case ID_RUN: return GetRun(); break; @@ -1052,8 +983,8 @@ int CInterpreter::GetID( char *id_name ) break; case ID_ELSE: - //return Error("syntax error : else without matching if"); - return GetElse(); //FIXME: Protect this call so that floating else's aren't allowed + // return Error("syntax error : else without matching if"); + return GetElse(); // FIXME: Protect this call so that floating else's aren't allowed break; case ID_GET: @@ -1097,18 +1028,18 @@ int CInterpreter::GetID( char *id_name ) break; case ID_PLAY: - GetPlay(); //Bad eighties slang joke... yeah, it's not really funny, I know... + GetPlay(); // Bad eighties slang joke... yeah, it's not really funny, I know... break; - //Local variable types + // Local variable types case TK_FLOAT: case TK_INT: case TK_STRING: case TK_VECTOR: - GetVariable( id ); + GetVariable(id); break; - //Unknown ID + // Unknown ID default: case -1: @@ -1133,69 +1064,65 @@ GetDeclare ------------------------- */ -int CInterpreter::GetDeclare( void ) -{ - CBlock block; - char typeName[MAX_STRING_LENGTH]; - int type; +int CInterpreter::GetDeclare(void) { + CBlock block; + char typeName[MAX_STRING_LENGTH]; + int type; - block.Create( ID_DECLARE ); + block.Create(ID_DECLARE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TK_FLOAT: case TK_VECTOR: case TK_STRING: - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); break; default: - return Error("unknown identifier %s", typeName ); + return Error("unknown identifier %s", typeName); break; } - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("declare : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } - /* ------------------------- GetFree ------------------------- */ -int CInterpreter::GetFree( void ) -{ - CBlock block; +int CInterpreter::GetFree(void) { + CBlock block; - block.Create( ID_FREE ); + block.Create(ID_FREE); - if ( Match( TK_OPEN_PARENTHESIS ) == false ) + if (Match(TK_OPEN_PARENTHESIS) == false) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if ( Match( TK_CLOSED_PARENTHESIS ) == false ) + if (Match(TK_CLOSED_PARENTHESIS) == false) return Error("free : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1212,28 +1139,27 @@ int CInterpreter::GetFree( void ) // if ( STRING ? STRING ) -int CInterpreter::GetIf( void ) -{ - CBlock block; +int CInterpreter::GetIf(void) { + CBlock block; - block.Create( ID_IF ); + block.Create(ID_IF); - if ( Match( TK_OPEN_PARENTHESIS ) == false ) + if (Match(TK_OPEN_PARENTHESIS) == false) return Error("syntax error : '(' not found"); - if ( GetAny( &block ) == false ) + if (GetAny(&block) == false) return false; - if ( GetEvaluator( &block ) == false ) + if (GetEvaluator(&block) == false) return false; - if ( GetAny( &block ) == false ) + if (GetAny(&block) == false) return false; - if ( Match( TK_CLOSED_PARENTHESIS ) == false ) + if (Match(TK_CLOSED_PARENTHESIS) == false) return Error("if : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1250,11 +1176,10 @@ int CInterpreter::GetIf( void ) // else -int CInterpreter::GetElse( void ) -{ - CBlock block; +int CInterpreter::GetElse(void) { + CBlock block; - block.Create( ID_ELSE ); + block.Create(ID_ELSE); /* if ( Match( TK_OPEN_PARENTHESIS ) == false ) @@ -1277,7 +1202,7 @@ int CInterpreter::GetElse( void ) return Error("sound : too many parameters"); */ - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1292,27 +1217,25 @@ int CInterpreter::GetElse( void ) =================================================================================================== */ -//task ( name ) { } +// task ( name ) { } -int CInterpreter::GetTask( void ) -{ - CBlock block; +int CInterpreter::GetTask(void) { + CBlock block; - block.Create( ID_TASK ); + block.Create(ID_TASK); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("GetTask: too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; - } /* @@ -1325,24 +1248,23 @@ int CInterpreter::GetTask( void ) =================================================================================================== */ -//do ( taskName ) +// do ( taskName ) -int CInterpreter::GetDo( void ) -{ - CBlock block; +int CInterpreter::GetDo(void) { + CBlock block; - block.Create( ID_DO ); + block.Create(ID_DO); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("do : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1359,39 +1281,37 @@ int CInterpreter::GetDo( void ) // get( TYPE, NAME ); -int CInterpreter::GetGet( CBlock *block ) -{ - char typeName[MAX_STRING_LENGTH]; - int type; +int CInterpreter::GetGet(CBlock *block) { + char typeName[MAX_STRING_LENGTH]; + int type; - block->Write( ID_GET, (float) ID_GET ); + block->Write(ID_GET, (float)ID_GET); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TK_FLOAT: case TK_INT: case TK_VECTOR: case TK_STRING: - block->Write( TK_FLOAT, (float) type ); + block->Write(TK_FLOAT, (float)type); break; default: - return Error("unknown identifier %s", typeName ); + return Error("unknown identifier %s", typeName); break; } - if ( GetString( block ) == false ) + if (GetString(block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); return true; @@ -1409,20 +1329,19 @@ int CInterpreter::GetGet( CBlock *block ) // random( low, high ); -int CInterpreter::GetRandom( CBlock *block ) -{ - block->Write( ID_RANDOM, (float) ID_RANDOM ); +int CInterpreter::GetRandom(CBlock *block) { + block->Write(ID_RANDOM, (float)ID_RANDOM); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetFloat( block ) == false ) + if (GetFloat(block) == false) return false; - if ( GetFloat( block ) == false ) + if (GetFloat(block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); return true; @@ -1440,25 +1359,24 @@ int CInterpreter::GetRandom( CBlock *block ) // sound( NAME ); -int CInterpreter::GetSound( void ) -{ - CBlock block; +int CInterpreter::GetSound(void) { + CBlock block; - block.Create( ID_SOUND ); + block.Create(ID_SOUND); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetIdentifier( &block ) == false ) + if (GetIdentifier(&block) == false) return false; - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("sound : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1475,32 +1393,30 @@ int CInterpreter::GetSound( void ) // move( ORIGIN, ANGLES, DURATION ); -int CInterpreter::GetMove( void ) -{ - CBlock block; +int CInterpreter::GetMove(void) { + CBlock block; - block.Create( ID_MOVE ); + block.Create(ID_MOVE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - //Angles are optional - if ( LookAhead( TK_VECTOR_START ) || LookAhead( TK_IDENTIFIER ) ) - { - if ( GetVector( &block ) == false ) + // Angles are optional + if (LookAhead(TK_VECTOR_START) || LookAhead(TK_IDENTIFIER)) { + if (GetVector(&block) == false) return false; } - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("move : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1517,25 +1433,24 @@ int CInterpreter::GetMove( void ) // move( ANGLES, DURATION ); -int CInterpreter::GetRotate( void ) -{ - CBlock block; +int CInterpreter::GetRotate(void) { + CBlock block; - block.Create( ID_ROTATE ); + block.Create(ID_ROTATE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("move : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1550,54 +1465,51 @@ int CInterpreter::GetRotate( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetAffect( void ) -{ - CBlock block; - char typeName[MAX_STRING_SIZE]; - int type; +int CInterpreter::GetAffect(void) { + CBlock block; + char typeName[MAX_STRING_SIZE]; + int type; - block.Create( ID_AFFECT ); + block.Create(ID_AFFECT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!LookAhead( TK_IDENTIFIER )) + if (!LookAhead(TK_IDENTIFIER)) return Error("syntax error : identifier not found"); - if ( MatchGet() ) + if (MatchGet()) return Error("syntax error : illegal use of \"get\""); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TYPE_INSERT: case TYPE_FLUSH: - - block.Write( TK_FLOAT, (float) type ); + + block.Write(TK_FLOAT, (float)type); break; default: - return Error("'%s': unknown affect type", typeName ); + return Error("'%s': unknown affect type", typeName); break; - } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); - if (!LookAhead( TK_BLOCK_START )) + if (!LookAhead(TK_BLOCK_START)) return Error("syntax error : '{' not found"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1612,32 +1524,28 @@ int CInterpreter::GetAffect( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetWait( void ) -{ - CBlock block; +int CInterpreter::GetWait(void) { + CBlock block; - block.Create( ID_WAIT ); + block.Create(ID_WAIT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( LookAhead( TK_STRING ) ) - { - if ( GetString( &block ) == false ) + if (LookAhead(TK_STRING)) { + if (GetString(&block) == false) return false; - } - else - { - if ( GetFloat( &block ) == false ) + } else { + if (GetFloat(&block) == false) return false; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("wait : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1652,69 +1560,62 @@ int CInterpreter::GetWait( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetSet( void ) -{ - CBlock block; +int CInterpreter::GetSet(void) { + CBlock block; - block.Create( ID_SET ); + block.Create(ID_SET); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - //Check for get placement - if ( MatchGet() ) - { - if ( GetGet( &block ) == false ) + // Check for get placement + if (MatchGet()) { + if (GetGet(&block) == false) return false; - } - else - { - switch( GetNextType() ) - { + } else { + switch (GetNextType()) { case TK_INT: - - if ( GetInteger( &block ) == false ) + + if (GetInteger(&block) == false) return false; break; case TK_FLOAT: - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; case TK_STRING: - - if ( GetString( &block ) == false ) + + if (GetString(&block) == false) return false; break; case TK_VECTOR_START: - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; break; - + default: - if ( MatchTag() ) - { - GetTag( &block ); + if (MatchTag()) { + GetTag(&block); break; } - - if ( MatchRandom() ) - { - GetRandom( &block ); + + if (MatchRandom()) { + GetRandom(&block); break; } @@ -1723,10 +1624,10 @@ int CInterpreter::GetSet( void ) } } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("set : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1741,30 +1642,26 @@ int CInterpreter::GetSet( void ) =================================================================================================== */ -int CInterpreter::GetLoop( void ) -{ - CBlock block; +int CInterpreter::GetLoop(void) { + CBlock block; - block.Create( ID_LOOP ); + block.Create(ID_LOOP); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( LookAhead( TK_CLOSED_PARENTHESIS ) ) - { + if (LookAhead(TK_CLOSED_PARENTHESIS)) { //-1 denotes an infinite loop - block.Write( TK_FLOAT, (float) -1); - } - else - { - if ( GetInteger( &block ) == false ) + block.Write(TK_FLOAT, (float)-1); + } else { + if (GetInteger(&block) == false) return false; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("GetLoop : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1779,22 +1676,21 @@ int CInterpreter::GetLoop( void ) =================================================================================================== */ -int CInterpreter::GetPrint( void ) -{ - CBlock block; +int CInterpreter::GetPrint(void) { + CBlock block; - block.Create( ID_PRINT ); + block.Create(ID_PRINT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("print : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1809,22 +1705,21 @@ int CInterpreter::GetPrint( void ) =================================================================================================== */ -int CInterpreter::GetUse( void ) -{ - CBlock block; +int CInterpreter::GetUse(void) { + CBlock block; - block.Create( ID_USE ); + block.Create(ID_USE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("use : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1839,19 +1734,18 @@ int CInterpreter::GetUse( void ) =================================================================================================== */ -int CInterpreter::GetFlush( void ) -{ - CBlock block; +int CInterpreter::GetFlush(void) { + CBlock block; - block.Create( ID_FLUSH ); + block.Create(ID_FLUSH); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("flush : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1866,22 +1760,21 @@ int CInterpreter::GetFlush( void ) =================================================================================================== */ -int CInterpreter::GetRun( void ) -{ - CBlock block; +int CInterpreter::GetRun(void) { + CBlock block; - block.Create( ID_RUN ); + block.Create(ID_RUN); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("run : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1896,22 +1789,21 @@ int CInterpreter::GetRun( void ) =================================================================================================== */ -int CInterpreter::GetKill( void ) -{ - CBlock block; +int CInterpreter::GetKill(void) { + CBlock block; - block.Create( ID_KILL ); + block.Create(ID_KILL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("kill : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1926,22 +1818,21 @@ int CInterpreter::GetKill( void ) =================================================================================================== */ -int CInterpreter::GetRemove( void ) -{ - CBlock block; +int CInterpreter::GetRemove(void) { + CBlock block; - block.Create( ID_REMOVE ); + block.Create(ID_REMOVE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("remove : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1958,29 +1849,27 @@ int CInterpreter::GetRemove( void ) // this is just so people can put comments in scripts in BehavEd and not have them lost as normal comments would be. // -int CInterpreter::GetRem( void ) -{ - CBlock block; +int CInterpreter::GetRem(void) { + CBlock block; - block.Create( ID_REM ); + block.Create(ID_REM); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); // optional string? - if (Match( TK_CLOSED_PARENTHESIS )) + if (Match(TK_CLOSED_PARENTHESIS)) return true; - GetString( &block ); + GetString(&block); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("rem : function only takes 1 optional parameter"); return true; } - /* =================================================================================================== @@ -1991,91 +1880,89 @@ int CInterpreter::GetRem( void ) =================================================================================================== */ -int CInterpreter::GetCamera( void ) -{ - CBlock block; - char typeName[MAX_STRING_SIZE]; - int type; +int CInterpreter::GetCamera(void) { + CBlock block; + char typeName[MAX_STRING_SIZE]; + int type; - block.Create( ID_CAMERA ); + block.Create(ID_CAMERA); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { - case TYPE_PAN: //PAN ( ANGLES, DURATION ) + switch (type) { + case TYPE_PAN: // PAN ( ANGLES, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; - case TYPE_ZOOM: //ZOOM ( FOV, DURATION ) - - block.Write( TK_FLOAT, (float) type ); + case TYPE_ZOOM: // ZOOM ( FOV, DURATION ) + + block.Write(TK_FLOAT, (float)type); - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - - if ( GetFloat( &block ) == false ) + + if (GetFloat(&block) == false) return false; break; - - case TYPE_MOVE: //MOVE ( ORIGIN, DURATION ) - block.Write( TK_FLOAT, (float) type ); + case TYPE_MOVE: // MOVE ( ORIGIN, DURATION ) + + block.Write(TK_FLOAT, (float)type); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; - - case TYPE_FADE: //FADE ( SOURCE(R,G,B,A), DEST(R,G,B,A), DURATION ) - - block.Write( TK_FLOAT, (float) type ); - //Source color - if ( GetVector( &block ) == false ) + case TYPE_FADE: // FADE ( SOURCE(R,G,B,A), DEST(R,G,B,A), DURATION ) + + block.Write(TK_FLOAT, (float)type); + + // Source color + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - //Dest color - if ( GetVector( &block ) == false ) + // Dest color + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - //Duration - if ( GetFloat( &block ) == false ) + // Duration + if (GetFloat(&block) == false) return false; break; - case TYPE_PATH: //PATH ( FILENAME ) + case TYPE_PATH: // PATH ( FILENAME ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Filename - if ( GetString( &block ) == false ) + // Filename + if (GetString(&block) == false) return false; break; @@ -2083,92 +1970,92 @@ int CInterpreter::GetCamera( void ) case TYPE_ENABLE: case TYPE_DISABLE: - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); break; - case TYPE_SHAKE: //SHAKE ( INTENSITY, DURATION ) + case TYPE_SHAKE: // SHAKE ( INTENSITY, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Intensity - if ( GetFloat( &block ) == false ) + // Intensity + if (GetFloat(&block) == false) return false; - //Duration - if ( GetFloat( &block ) == false ) + // Duration + if (GetFloat(&block) == false) return false; break; - case TYPE_ROLL: //ROLL ( ANGLE, TIME ) + case TYPE_ROLL: // ROLL ( ANGLE, TIME ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Angle - if ( GetFloat( &block ) == false ) + // Angle + if (GetFloat(&block) == false) return false; - //Time - if ( GetFloat( &block ) == false ) + // Time + if (GetFloat(&block) == false) return false; break; - case TYPE_TRACK: //TRACK ( TARGETNAME, SPEED, INITLERP ) + case TYPE_TRACK: // TRACK ( TARGETNAME, SPEED, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Target name - if ( GetString( &block ) == false ) + // Target name + if (GetString(&block) == false) return false; - //Speed - if ( GetFloat( &block ) == false ) + // Speed + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; - case TYPE_FOLLOW: //FOLLOW ( CAMERAGROUP, SPEED, INITLERP ) + case TYPE_FOLLOW: // FOLLOW ( CAMERAGROUP, SPEED, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Camera group - if ( GetString( &block ) == false ) + // Camera group + if (GetString(&block) == false) return false; - //Speed - if ( GetFloat( &block ) == false ) + // Speed + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; - case TYPE_DISTANCE: //DISTANCE ( DISTANCE, INITLERP ) + case TYPE_DISTANCE: // DISTANCE ( DISTANCE, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Distance - if ( GetFloat( &block ) == false ) + // Distance + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("camera : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2179,33 +2066,32 @@ GetDoWait ------------------------- */ -int CInterpreter::GetDoWait( void ) -{ - CBlock block; +int CInterpreter::GetDoWait(void) { + CBlock block; - //Write out the "do" portion - block.Create( ID_DO ); + // Write out the "do" portion + block.Create(ID_DO); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("do : too many parameters"); - //Write out the accompanying "wait" - char *str = (char *) block.GetMemberData( 0 ); + // Write out the accompanying "wait" + char *str = (char *)block.GetMemberData(0); - CBlock block2; + CBlock block2; - block2.Create( ID_WAIT ); + block2.Create(ID_WAIT); - block2.Write( TK_STRING, (char *) str ); + block2.Write(TK_STRING, (char *)str); - m_blockStream->WriteBlock( &block ); - m_blockStream->WriteBlock( &block2 ); + m_blockStream->WriteBlock(&block); + m_blockStream->WriteBlock(&block2); return true; } @@ -2216,22 +2102,21 @@ GetSignal ------------------------- */ -int CInterpreter::GetSignal( void ) -{ - CBlock block; +int CInterpreter::GetSignal(void) { + CBlock block; - block.Create( ID_SIGNAL ); + block.Create(ID_SIGNAL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("signal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2242,22 +2127,21 @@ GetSignal ------------------------- */ -int CInterpreter::GetWaitSignal( void ) -{ - CBlock block; +int CInterpreter::GetWaitSignal(void) { + CBlock block; - block.Create( ID_WAITSIGNAL ); + block.Create(ID_WAITSIGNAL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("waitsignal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2268,25 +2152,24 @@ GetPlay ------------------------- */ -int CInterpreter::GetPlay( void ) -{ - CBlock block; +int CInterpreter::GetPlay(void) { + CBlock block; - block.Create( ID_PLAY ); + block.Create(ID_PLAY); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("waitsignal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2301,37 +2184,35 @@ int CInterpreter::GetPlay( void ) =================================================================================================== */ -//NOTENOTE: The tag's information is included as block members, not as a separate block. +// NOTENOTE: The tag's information is included as block members, not as a separate block. -int CInterpreter::GetTag( CBlock *block ) -{ - char typeName[MAX_STRING_SIZE]; - int typeID; +int CInterpreter::GetTag(CBlock *block) { + char typeName[MAX_STRING_SIZE]; + int typeID; - //Mark as a tag - block->Write( ID_TAG, (float) ID_TAG ); + // Mark as a tag + block->Write(ID_TAG, (float)ID_TAG); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - //Get the tag name - if ( GetString( block ) == false ) + // Get the tag name + if (GetString(block) == false) return false; - //Get the lookup ID - GetType( (char *) typeName ); + // Get the lookup ID + GetType((char *)typeName); - typeID = FindSymbol( (char *) typeName, m_typeKeywords); + typeID = FindSymbol((char *)typeName, m_typeKeywords); - //Tags only contain origin and angles lookups - if ( (typeID != TYPE_ORIGIN) && (typeID != TYPE_ANGLES) ) - { - return Error("syntax error : 'tag' : %s is not a valid look up identifier", typeName ); + // Tags only contain origin and angles lookups + if ((typeID != TYPE_ORIGIN) && (typeID != TYPE_ANGLES)) { + return Error("syntax error : 'tag' : %s is not a valid look up identifier", typeName); } - block->Write( TK_FLOAT, (float) typeID ); + block->Write(TK_FLOAT, (float)typeID); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("tag : too many parameters"); return true; @@ -2350,31 +2231,28 @@ int CInterpreter::GetTag( CBlock *block ) // I also return -ve block numbers for errors between blocks. Eg if you read 3 good blocks, then find an unexpected // float in the script between blocks 3 & 4 then I return -3 to indicate the error is after that, but not block 4 // -int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, char *filename ) -{ - CBlock block; - CToken *token; - int type, blockLevel = 0, parenthesisLevel = 0; +int CInterpreter::Interpret(CTokenizer *Tokenizer, CBlockStream *BlockStream, char *filename) { + CBlock block; + CToken *token; + int type, blockLevel = 0, parenthesisLevel = 0; - m_sCurrentFile = filename; // used during error reporting because you can't ask tokenizer for pushed streams - - m_tokenizer = Tokenizer; - m_blockStream = BlockStream; + m_sCurrentFile = filename; // used during error reporting because you can't ask tokenizer for pushed streams + + m_tokenizer = Tokenizer; + m_blockStream = BlockStream; m_iCurrentLine = m_tokenizer->GetCurLine(); - token = m_tokenizer->GetToEndOfLine(TK_STRING); - m_sCurrentLine = token->GetStringValue(); + token = m_tokenizer->GetToEndOfLine(TK_STRING); + m_sCurrentLine = token->GetStringValue(); m_tokenizer->PutBackToken(token, false, NULL, true); - + m_iBadCBlockNumber = 0; - while (m_tokenizer->GetRemainingSize() > 0) - { - token = m_tokenizer->GetToken( TKF_USES_EOL, 0 ); + while (m_tokenizer->GetRemainingSize() > 0) { + token = m_tokenizer->GetToken(TKF_USES_EOL, 0); type = token->GetType(); - switch ( type ) - { + switch (type) { case TK_UNDEFINED: token->Delete(); m_iBadCBlockNumber = -m_iBadCBlockNumber; @@ -2389,11 +2267,11 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c // read the next line, then put it back token->Delete(); m_iCurrentLine = m_tokenizer->GetCurLine(); - token = m_tokenizer->GetToEndOfLine(TK_STRING); - m_sCurrentLine = token->GetStringValue(); + token = m_tokenizer->GetToEndOfLine(TK_STRING); + m_sCurrentLine = token->GetStringValue(); m_tokenizer->PutBackToken(token, false, NULL, true); break; - + case TK_CHAR: case TK_STRING: token->Delete(); @@ -2401,35 +2279,33 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c Error("syntax error : unexpected string"); return m_iBadCBlockNumber; break; - + case TK_INT: token->Delete(); - m_iBadCBlockNumber = -m_iBadCBlockNumber; + m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : unexpected integer"); return m_iBadCBlockNumber; break; - + case TK_FLOAT: token->Delete(); m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : unexpected float"); return m_iBadCBlockNumber; break; - + case TK_IDENTIFIER: m_iBadCBlockNumber++; - if (!GetID( (char *) token->GetStringValue() )) - { + if (!GetID((char *)token->GetStringValue())) { token->Delete(); return m_iBadCBlockNumber; } token->Delete(); break; - + case TK_BLOCK_START: token->Delete(); - if (parenthesisLevel) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : brace inside parenthesis"); return m_iBadCBlockNumber; @@ -2440,15 +2316,14 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c case TK_BLOCK_END: token->Delete(); - if (parenthesisLevel) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : brace inside parenthesis"); return m_iBadCBlockNumber; } - - block.Create( ID_BLOCK_END ); - m_blockStream->WriteBlock( &block ); + + block.Create(ID_BLOCK_END); + m_blockStream->WriteBlock(&block); block.Free(); blockLevel--; @@ -2465,8 +2340,7 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c blockLevel--; parenthesisLevel--; - if (parenthesisLevel<0) - { + if (parenthesisLevel < 0) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : closed parenthesis with no opening match"); return m_iBadCBlockNumber; @@ -2489,24 +2363,21 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c } } - if ( blockLevel ) - { + if (blockLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("error : open brace was not closed"); return m_iBadCBlockNumber; } - if ( parenthesisLevel ) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("error: open parenthesis"); return m_iBadCBlockNumber; } - //Release all the variable information, because it's already been written out + // Release all the variable information, because it's already been written out FreeVars(); m_iBadCBlockNumber = 0; - return m_iBadCBlockNumber; //true; + return m_iBadCBlockNumber; // true; } - diff --git a/codeJK2/icarus/Sequence.cpp b/codeJK2/icarus/Sequence.cpp index f2ab7507e4..87ed074505 100644 --- a/codeJK2/icarus/Sequence.cpp +++ b/codeJK2/icarus/Sequence.cpp @@ -30,21 +30,17 @@ along with this program; if not, see . #include #include "../code/qcommon/ojk_saved_game_helper.h" -CSequence::CSequence( void ) -{ - m_numCommands = 0; - m_numChildren = 0; - m_flags = 0; - m_iterations = 1; - - m_parent = NULL; - m_return = NULL; +CSequence::CSequence(void) { + m_numCommands = 0; + m_numChildren = 0; + m_flags = 0; + m_iterations = 1; + + m_parent = NULL; + m_return = NULL; } -CSequence::~CSequence( void ) -{ - Delete(); -} +CSequence::~CSequence(void) { Delete(); } /* ------------------------- @@ -52,16 +48,15 @@ Create ------------------------- */ -CSequence *CSequence::Create( void ) -{ +CSequence *CSequence::Create(void) { CSequence *seq = new CSequence; - //TODO: Emit warning + // TODO: Emit warning assert(seq); - if ( seq == NULL ) + if (seq == NULL) return NULL; - seq->SetFlag( SQ_COMMON ); + seq->SetFlag(SQ_COMMON); return seq; } @@ -72,51 +67,44 @@ Delete ------------------------- */ -void CSequence::Delete( void ) -{ - block_l::iterator bi; +void CSequence::Delete(void) { + block_l::iterator bi; sequence_l::iterator si; - //Notify the parent of the deletion - if ( m_parent ) - { - m_parent->RemoveChild( this ); + // Notify the parent of the deletion + if (m_parent) { + m_parent->RemoveChild(this); } - //Clear all children - if ( m_numChildren > 0 ) - { - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->SetParent( NULL ); + // Clear all children + if (m_numChildren > 0) { + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->SetParent(NULL); } } - //Clear all held commands - for ( bi = m_commands.begin(); bi != m_commands.end(); ++bi ) - { - delete (*bi); //Free() handled internally + // Clear all held commands + for (bi = m_commands.begin(); bi != m_commands.end(); ++bi) { + delete (*bi); // Free() handled internally } m_commands.clear(); m_children.clear(); } - /* ------------------------- AddChild ------------------------- */ -void CSequence::AddChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::AddChild(CSequence *child) { + assert(child); + if (child == NULL) return; - m_children.insert( m_children.end(), child ); - m_childrenMap[ m_numChildren ] = child; + m_children.insert(m_children.end(), child); + m_childrenMap[m_numChildren] = child; m_numChildren++; } @@ -126,14 +114,13 @@ RemoveChild ------------------------- */ -void CSequence::RemoveChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::RemoveChild(CSequence *child) { + assert(child); + if (child == NULL) return; - - //Remove the child - m_children.remove( child ); + + // Remove the child + m_children.remove(child); m_numChildren--; } @@ -143,16 +130,14 @@ HasChild ------------------------- */ -bool CSequence::HasChild( CSequence *sequence ) -{ - sequence_l::iterator ci; +bool CSequence::HasChild(CSequence *sequence) { + sequence_l::iterator ci; - for ( ci = m_children.begin(); ci != m_children.end(); ++ci ) - { - if ( (*ci) == sequence ) + for (ci = m_children.begin(); ci != m_children.end(); ++ci) { + if ((*ci) == sequence) return true; - if ( (*ci)->HasChild( sequence ) ) + if ((*ci)->HasChild(sequence)) return true; } @@ -165,19 +150,18 @@ SetParent ------------------------- */ -void CSequence::SetParent( CSequence *parent ) -{ +void CSequence::SetParent(CSequence *parent) { m_parent = parent; - if ( parent == NULL ) + if (parent == NULL) return; - //Inherit the parent's properties (this avoids messy tree walks later on) - if ( parent->m_flags & SQ_RETAIN ) + // Inherit the parent's properties (this avoids messy tree walks later on) + if (parent->m_flags & SQ_RETAIN) m_flags |= SQ_RETAIN; - if ( parent->m_flags & SQ_PENDING ) - m_flags |= SQ_PENDING; + if (parent->m_flags & SQ_PENDING) + m_flags |= SQ_PENDING; } /* @@ -186,24 +170,22 @@ PopCommand ------------------------- */ -CBlock *CSequence::PopCommand( int type ) -{ - CBlock *command = NULL; +CBlock *CSequence::PopCommand(int type) { + CBlock *command = NULL; - //Make sure everything is ok - assert( (type == POP_FRONT) || (type == POP_BACK) ); + // Make sure everything is ok + assert((type == POP_FRONT) || (type == POP_BACK)); - if ( m_commands.empty() ) + if (m_commands.empty()) return NULL; - switch ( type ) - { + switch (type) { case POP_FRONT: command = m_commands.front(); m_commands.pop_front(); m_numCommands--; - + return command; break; @@ -212,12 +194,12 @@ CBlock *CSequence::PopCommand( int type ) command = m_commands.back(); m_commands.pop_back(); m_numCommands--; - + return command; break; } - //Invalid flag + // Invalid flag return NULL; } @@ -227,17 +209,15 @@ PushCommand ------------------------- */ -int CSequence::PushCommand( CBlock *block, int type ) -{ - //Make sure everything is ok - assert( (type == PUSH_FRONT) || (type == PUSH_BACK) ); - assert( block ); +int CSequence::PushCommand(CBlock *block, int type) { + // Make sure everything is ok + assert((type == PUSH_FRONT) || (type == PUSH_BACK)); + assert(block); - switch ( type ) - { + switch (type) { case PUSH_FRONT: - - m_commands.push_front( block ); + + m_commands.push_front(block); m_numCommands++; return true; @@ -245,14 +225,14 @@ int CSequence::PushCommand( CBlock *block, int type ) case PUSH_BACK: - m_commands.push_back( block ); + m_commands.push_back(block); m_numCommands++; return true; break; } - //Invalid flag + // Invalid flag return false; } @@ -262,10 +242,7 @@ SetFlag ------------------------- */ -void CSequence::SetFlag( int flag ) -{ - m_flags |= flag; -} +void CSequence::SetFlag(int flag) { m_flags |= flag; } /* ------------------------- @@ -273,17 +250,14 @@ RemoveFlag ------------------------- */ -void CSequence::RemoveFlag( int flag, bool children ) -{ +void CSequence::RemoveFlag(int flag, bool children) { m_flags &= ~flag; - if ( children ) - { - sequence_l::iterator si; + if (children) { + sequence_l::iterator si; - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->RemoveFlag( flag, true ); + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->RemoveFlag(flag, true); } } } @@ -294,10 +268,7 @@ HasFlag ------------------------- */ -int CSequence::HasFlag( int flag ) -{ - return (m_flags & flag); -} +int CSequence::HasFlag(int flag) { return (m_flags & flag); } /* ------------------------- @@ -305,9 +276,8 @@ SetReturn ------------------------- */ -void CSequence::SetReturn ( CSequence *sequence ) -{ - assert( sequence != this ); +void CSequence::SetReturn(CSequence *sequence) { + assert(sequence != this); m_return = sequence; } @@ -317,15 +287,14 @@ GetChild ------------------------- */ -CSequence *CSequence::GetChild( int id ) -{ - if ( id < 0 ) +CSequence *CSequence::GetChild(int id) { + if (id < 0) return NULL; - //NOTENOTE: Done for safety reasons, I don't know what this template will return on underflow ( sigh... ) - sequenceID_m::iterator mi = m_childrenMap.find( id ); + // NOTENOTE: Done for safety reasons, I don't know what this template will return on underflow ( sigh... ) + sequenceID_m::iterator mi = m_childrenMap.find(id); - if ( mi == m_childrenMap.end() ) + if (mi == m_childrenMap.end()) return NULL; return (*mi).second; @@ -337,61 +306,45 @@ SaveCommand ------------------------- */ -int CSequence::SaveCommand( CBlock *block ) -{ - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; +int CSequence::SaveCommand(CBlock *block) { + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - saved_game.write_chunk( - INT_ID('B', 'L', 'I', 'D'), - bID); + saved_game.write_chunk(INT_ID('B', 'L', 'I', 'D'), bID); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - saved_game.write_chunk( - INT_ID('B', 'F', 'L', 'G'), - flags); + saved_game.write_chunk(INT_ID('B', 'F', 'L', 'G'), flags); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - saved_game.write_chunk( - INT_ID('B', 'N', 'U', 'M'), - numMembers); + saved_game.write_chunk(INT_ID('B', 'N', 'U', 'M'), numMembers); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - saved_game.write_chunk( - INT_ID('B', 'M', 'I', 'D'), - bID); - - //Save out the data size + saved_game.write_chunk(INT_ID('B', 'M', 'I', 'D'), bID); + + // Save out the data size size = bm->GetSize(); - saved_game.write_chunk( - INT_ID('B', 'S', 'I', 'Z'), - size); - - //Save out the raw data - const uint8_t* raw_data = static_cast(bm->GetData()); - - saved_game.write_chunk( - INT_ID('B', 'M', 'E', 'M'), - raw_data, - size); + saved_game.write_chunk(INT_ID('B', 'S', 'I', 'Z'), size); + + // Save out the raw data + const uint8_t *raw_data = static_cast(bm->GetData()); + + saved_game.write_chunk(INT_ID('B', 'M', 'E', 'M'), raw_data, size); } return true; @@ -403,64 +356,44 @@ Save ------------------------- */ -int CSequence::Save( void ) -{ - sequence_l::iterator ci; - block_l::iterator bi; - int id; - - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); - - //Save the parent (by GUID) - id = ( m_parent != NULL ) ? m_parent->GetID() : -1; - - saved_game.write_chunk( - INT_ID('S', 'P', 'I', 'D'), - id); - - //Save the return (by GUID) - id = ( m_return != NULL ) ? m_return->GetID() : -1; - - saved_game.write_chunk( - INT_ID('S', 'R', 'I', 'D'), - id); - - //Save the number of children - saved_game.write_chunk( - INT_ID('S', 'N', 'C', 'H'), - m_numChildren); - - //Save out the children (only by GUID) - STL_ITERATE( ci, m_children ) - { +int CSequence::Save(void) { + sequence_l::iterator ci; + block_l::iterator bi; + int id; + + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); + + // Save the parent (by GUID) + id = (m_parent != NULL) ? m_parent->GetID() : -1; + + saved_game.write_chunk(INT_ID('S', 'P', 'I', 'D'), id); + + // Save the return (by GUID) + id = (m_return != NULL) ? m_return->GetID() : -1; + + saved_game.write_chunk(INT_ID('S', 'R', 'I', 'D'), id); + + // Save the number of children + saved_game.write_chunk(INT_ID('S', 'N', 'C', 'H'), m_numChildren); + + // Save out the children (only by GUID) + STL_ITERATE(ci, m_children) { id = (*ci)->GetID(); - saved_game.write_chunk( - INT_ID('S', 'C', 'H', 'D'), - id); + saved_game.write_chunk(INT_ID('S', 'C', 'H', 'D'), id); } - //Save flags - saved_game.write_chunk( - INT_ID('S', 'F', 'L', 'G'), - m_flags); - - //Save iterations - saved_game.write_chunk( - INT_ID('S', 'I', 'T', 'R'), - m_iterations); - - //Save the number of commands - saved_game.write_chunk( - INT_ID('S', 'N', 'M', 'C'), - m_numCommands); - - //Save the commands - STL_ITERATE( bi, m_commands ) - { - SaveCommand( (*bi) ); - } + // Save flags + saved_game.write_chunk(INT_ID('S', 'F', 'L', 'G'), m_flags); + + // Save iterations + saved_game.write_chunk(INT_ID('S', 'I', 'T', 'R'), m_iterations); + + // Save the number of commands + saved_game.write_chunk(INT_ID('S', 'N', 'M', 'C'), m_numCommands); + + // Save the commands + STL_ITERATE(bi, m_commands) { SaveCommand((*bi)); } return true; } @@ -471,171 +404,135 @@ Load ------------------------- */ -int CSequence::Load( void ) -{ - unsigned char flags = 0; - CSequence *sequence; - CBlock *block; - int id = 0, numMembers = 0; - int i; - - int bID, bSize; - void *bData; - - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); - - //Get the parent sequence - saved_game.read_chunk( - INT_ID('S', 'P', 'I', 'D'), - id); - - m_parent = ( id != -1 ) ? m_owner->GetSequence( id ) : NULL; - - //Get the return sequence - saved_game.read_chunk( - INT_ID('S', 'R', 'I', 'D'), - id); - - m_return = ( id != -1 ) ? m_owner->GetSequence( id ) : NULL; - - //Get the number of children - saved_game.read_chunk( - INT_ID('S', 'N', 'C', 'H'), - m_numChildren); - - //Reload all children - for ( i = 0; i < m_numChildren; i++ ) - { - //Get the child sequence ID - saved_game.read_chunk( - INT_ID('S', 'C', 'H', 'D'), - id); - - //Get the desired sequence - if ( ( sequence = m_owner->GetSequence( id ) ) == NULL ) +int CSequence::Load(void) { + unsigned char flags = 0; + CSequence *sequence; + CBlock *block; + int id = 0, numMembers = 0; + int i; + + int bID, bSize; + void *bData; + + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); + + // Get the parent sequence + saved_game.read_chunk(INT_ID('S', 'P', 'I', 'D'), id); + + m_parent = (id != -1) ? m_owner->GetSequence(id) : NULL; + + // Get the return sequence + saved_game.read_chunk(INT_ID('S', 'R', 'I', 'D'), id); + + m_return = (id != -1) ? m_owner->GetSequence(id) : NULL; + + // Get the number of children + saved_game.read_chunk(INT_ID('S', 'N', 'C', 'H'), m_numChildren); + + // Reload all children + for (i = 0; i < m_numChildren; i++) { + // Get the child sequence ID + saved_game.read_chunk(INT_ID('S', 'C', 'H', 'D'), id); + + // Get the desired sequence + if ((sequence = m_owner->GetSequence(id)) == NULL) return false; - - //Insert this into the list - STL_INSERT( m_children, sequence ); - //Restore the connection in the child / ID map - m_childrenMap[ i ] = sequence; + // Insert this into the list + STL_INSERT(m_children, sequence); + + // Restore the connection in the child / ID map + m_childrenMap[i] = sequence; } - - //Get the sequence flags - saved_game.read_chunk( - INT_ID('S', 'F', 'L', 'G'), - m_flags); + // Get the sequence flags + saved_game.read_chunk(INT_ID('S', 'F', 'L', 'G'), m_flags); - //Get the number of iterations - saved_game.read_chunk( - INT_ID('S', 'I', 'T', 'R'), - m_iterations); + // Get the number of iterations + saved_game.read_chunk(INT_ID('S', 'I', 'T', 'R'), m_iterations); - int numCommands = 0; + int numCommands = 0; - //Get the number of commands - saved_game.read_chunk( - INT_ID('S', 'N', 'M', 'C'), - numCommands); + // Get the number of commands + saved_game.read_chunk(INT_ID('S', 'N', 'M', 'C'), numCommands); - //Get all the commands - for ( i = 0; i < numCommands; i++ ) - { - //Get the block ID and create a new container - saved_game.read_chunk( - INT_ID('B', 'L', 'I', 'D'), - id); + // Get all the commands + for (i = 0; i < numCommands; i++) { + // Get the block ID and create a new container + saved_game.read_chunk(INT_ID('B', 'L', 'I', 'D'), id); block = new CBlock; - - block->Create( id ); - - //Read the block's flags - saved_game.read_chunk( - INT_ID('B', 'F', 'L', 'G'), - flags); - block->SetFlags( flags ); + block->Create(id); + + // Read the block's flags + saved_game.read_chunk(INT_ID('B', 'F', 'L', 'G'), flags); + + block->SetFlags(flags); numMembers = 0; - //Get the number of block members - saved_game.read_chunk( - INT_ID('B', 'N', 'U', 'M'), - numMembers); - - for ( int j = 0; j < numMembers; j++ ) - { + // Get the number of block members + saved_game.read_chunk(INT_ID('B', 'N', 'U', 'M'), numMembers); + + for (int j = 0; j < numMembers; j++) { bID = 0; - //Get the member ID - saved_game.read_chunk( - INT_ID('B', 'M', 'I', 'D'), - bID); + // Get the member ID + saved_game.read_chunk(INT_ID('B', 'M', 'I', 'D'), bID); bSize = 0; - //Get the member size - saved_game.read_chunk( - INT_ID('B', 'S', 'I', 'Z'), - bSize); + // Get the member size + saved_game.read_chunk(INT_ID('B', 'S', 'I', 'Z'), bSize); - //Get the member's data - if ( ( bData = ICARUS_Malloc( bSize ) ) == NULL ) + // Get the member's data + if ((bData = ICARUS_Malloc(bSize)) == NULL) return false; - //Get the actual raw data - saved_game.read_chunk( - INT_ID('B', 'M', 'E', 'M'), - static_cast(bData), - bSize); - - //Write out the correct type - switch ( bID ) - { - case TK_INT: - { - assert(0); - int data = *(int *) bData; - block->Write( TK_FLOAT, (float) data ); - } - break; + // Get the actual raw data + saved_game.read_chunk(INT_ID('B', 'M', 'E', 'M'), static_cast(bData), bSize); + + // Write out the correct type + switch (bID) { + case TK_INT: { + assert(0); + int data = *(int *)bData; + block->Write(TK_FLOAT, (float)data); + } break; case TK_FLOAT: - block->Write( TK_FLOAT, *(float *) bData ); + block->Write(TK_FLOAT, *(float *)bData); break; case TK_STRING: case TK_IDENTIFIER: case TK_CHAR: - block->Write( TK_STRING, (char *) bData ); + block->Write(TK_STRING, (char *)bData); break; case TK_VECTOR: case TK_VECTOR_START: - block->Write( TK_VECTOR, *(vec3_t *) bData ); + block->Write(TK_VECTOR, *(vec3_t *)bData); break; case ID_TAG: - block->Write( ID_TAG, (float) ID_TAG ); + block->Write(ID_TAG, (float)ID_TAG); break; case ID_GET: - block->Write( ID_GET, (float) ID_GET ); + block->Write(ID_GET, (float)ID_GET); break; case ID_RANDOM: - block->Write( ID_RANDOM, *(float *) bData );//(float) ID_RANDOM ); + block->Write(ID_RANDOM, *(float *)bData); //(float) ID_RANDOM ); break; - + case TK_EQUALS: case TK_GREATER_THAN: case TK_LESS_THAN: case TK_NOT: - block->Write( bID, 0 ); + block->Write(bID, 0); break; default: @@ -643,14 +540,14 @@ int CSequence::Load( void ) return false; break; } - - //Get rid of the temp memory - ICARUS_Free( bData ); + + // Get rid of the temp memory + ICARUS_Free(bData); } - //Save the block - //STL_INSERT( m_commands, block ); - PushCommand( block, PUSH_BACK ); + // Save the block + // STL_INSERT( m_commands, block ); + PushCommand(block, PUSH_BACK); } return true; diff --git a/codeJK2/icarus/Sequencer.cpp b/codeJK2/icarus/Sequencer.cpp index fb6f3db1d9..7929e36c75 100644 --- a/codeJK2/icarus/Sequencer.cpp +++ b/codeJK2/icarus/Sequencer.cpp @@ -32,14 +32,13 @@ along with this program; if not, see . #include "assert.h" #include "../code/qcommon/ojk_saved_game_helper.h" -// Sequencer +// Sequencer -CSequencer::CSequencer( void ) -{ - m_numCommands = 0; +CSequencer::CSequencer(void) { + m_numCommands = 0; - m_curStream = NULL; - m_curSequence = NULL; + m_curStream = NULL; + m_curSequence = NULL; m_elseValid = 0; m_elseOwner = NULL; @@ -47,9 +46,8 @@ CSequencer::CSequencer( void ) m_curGroup = NULL; } -CSequencer::~CSequencer( void ) -{ - Free(); //Safe even if already freed +CSequencer::~CSequencer(void) { + Free(); // Safe even if already freed } /* @@ -60,8 +58,7 @@ Static creation function ======================== */ -CSequencer *CSequencer::Create ( void ) -{ +CSequencer *CSequencer::Create(void) { CSequencer *sequencer = new CSequencer; return sequencer; @@ -74,12 +71,11 @@ Init Initializes the sequencer ======================== */ -int CSequencer::Init( int ownerID, interface_export_t *ie, CTaskManager *taskManager, ICARUS_Instance *iICARUS ) -{ - m_ownerID = ownerID; - m_owner = iICARUS; - m_taskManager = taskManager; - m_ie = ie; +int CSequencer::Init(int ownerID, interface_export_t *ie, CTaskManager *taskManager, ICARUS_Instance *iICARUS) { + m_ownerID = ownerID; + m_owner = iICARUS; + m_taskManager = taskManager; + m_ie = ie; return SEQ_OK; } @@ -91,27 +87,24 @@ Free Releases all resources and re-inits the sequencer ======================== */ -int CSequencer::Free( void ) -{ - sequence_l::iterator sli; +int CSequencer::Free(void) { + sequence_l::iterator sli; - //Flush the sequences - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ++sli ) - { - m_owner->DeleteSequence( (*sli) ); + // Flush the sequences + for (sli = m_sequences.begin(); sli != m_sequences.end(); ++sli) { + m_owner->DeleteSequence((*sli)); } m_sequences.clear(); m_sequenceMap.clear(); m_taskSequences.clear(); - //Clean up any other info + // Clean up any other info m_numCommands = 0; m_curSequence = NULL; bstream_t *streamToDel; - while(!m_streamsCreated.empty()) - { + while (!m_streamsCreated.empty()) { streamToDel = m_streamsCreated.back(); DeleteStream(streamToDel); } @@ -125,38 +118,35 @@ Flush ------------------------- */ -int CSequencer::Flush( CSequence *owner ) -{ - if ( owner == NULL ) +int CSequencer::Flush(CSequence *owner) { + if (owner == NULL) return SEQ_FAILED; - + Recall(); - sequence_l::iterator sli; + sequence_l::iterator sli; - //Flush the sequences - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ) - { - if ( ( (*sli) == owner ) || ( owner->HasChild( (*sli) ) ) || ( (*sli)->HasFlag( SQ_PENDING ) ) || ( (*sli)->HasFlag( SQ_TASK ) ) ) - { + // Flush the sequences + for (sli = m_sequences.begin(); sli != m_sequences.end();) { + if (((*sli) == owner) || (owner->HasChild((*sli))) || ((*sli)->HasFlag(SQ_PENDING)) || ((*sli)->HasFlag(SQ_TASK))) { ++sli; continue; } - //Remove it from the map - m_sequenceMap.erase( (*sli)->GetID() ); - - //Delete it, and remove all references - RemoveSequence( (*sli) ); - m_owner->DeleteSequence( (*sli) ); - - //Delete from the sequence list and move on - sli = m_sequences.erase( sli ); + // Remove it from the map + m_sequenceMap.erase((*sli)->GetID()); + + // Delete it, and remove all references + RemoveSequence((*sli)); + m_owner->DeleteSequence((*sli)); + + // Delete from the sequence list and move on + sli = m_sequences.erase(sli); } - //Make sure this owner knows it's now the root sequence - owner->SetParent( NULL ); - owner->SetReturn( NULL ); + // Make sure this owner knows it's now the root sequence + owner->SetParent(NULL); + owner->SetReturn(NULL); return SEQ_OK; } @@ -169,12 +159,11 @@ Creates a stream for parsing ======================== */ -bstream_t *CSequencer::AddStream( void ) -{ - bstream_t *stream; +bstream_t *CSequencer::AddStream(void) { + bstream_t *stream; - stream = new bstream_t; //deleted in Route() - stream->stream = new CBlockStream; //deleted in Route() + stream = new bstream_t; // deleted in Route() + stream->stream = new CBlockStream; // deleted in Route() stream->last = m_curStream; m_streamsCreated.push_back(stream); @@ -189,16 +178,14 @@ DeleteStream Deletes parsing stream ======================== */ -void CSequencer::DeleteStream( bstream_t *bstream ) -{ - std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); - if(finder != m_streamsCreated.end()) - { +void CSequencer::DeleteStream(bstream_t *bstream) { + std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); + if (finder != m_streamsCreated.end()) { m_streamsCreated.erase(finder); } bstream->stream->Free(); - + delete bstream->stream; delete bstream; @@ -211,10 +198,7 @@ AddTaskSequence ------------------------- */ -void CSequencer::AddTaskSequence( CSequence *sequence, CTaskGroup *group ) -{ - m_taskSequences[ group ] = sequence; -} +void CSequencer::AddTaskSequence(CSequence *sequence, CTaskGroup *group) { m_taskSequences[group] = sequence; } /* ------------------------- @@ -222,13 +206,12 @@ GetTaskSequence ------------------------- */ -CSequence *CSequencer::GetTaskSequence( CTaskGroup *group ) -{ - taskSequence_m::iterator tsi; +CSequence *CSequencer::GetTaskSequence(CTaskGroup *group) { + taskSequence_m::iterator tsi; - tsi = m_taskSequences.find( group ); + tsi = m_taskSequences.find(group); - if ( tsi == m_taskSequences.end() ) + if (tsi == m_taskSequences.end()) return NULL; return (*tsi).second; @@ -242,44 +225,42 @@ Creates and adds a sequence to the sequencer ======================== */ -CSequence *CSequencer::AddSequence( void ) -{ - CSequence *sequence = m_owner->GetSequence(); +CSequence *CSequencer::AddSequence(void) { + CSequence *sequence = m_owner->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //The rest is handled internally to the class - m_sequenceMap[ sequence->GetID() ] = sequence; + // The rest is handled internally to the class + m_sequenceMap[sequence->GetID()] = sequence; - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); - //FIXME: Temp fix - sequence->SetFlag( SQ_PENDING ); + // FIXME: Temp fix + sequence->SetFlag(SQ_PENDING); return sequence; } -CSequence *CSequencer::AddSequence( CSequence *parent, CSequence *returnSeq, int flags ) -{ - CSequence *sequence = m_owner->GetSequence(); +CSequence *CSequencer::AddSequence(CSequence *parent, CSequence *returnSeq, int flags) { + CSequence *sequence = m_owner->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //The rest is handled internally to the class - m_sequenceMap[ sequence->GetID() ] = sequence; + // The rest is handled internally to the class + m_sequenceMap[sequence->GetID()] = sequence; - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); + + sequence->SetFlags(flags); + sequence->SetParent(parent); + sequence->SetReturn(returnSeq); - sequence->SetFlags( flags ); - sequence->SetParent( parent ); - sequence->SetReturn( returnSeq ); - return sequence; } @@ -291,15 +272,14 @@ Retrieves a sequence by its ID ======================== */ -CSequence *CSequencer::GetSequence( int id ) -{ +CSequence *CSequencer::GetSequence(int id) { sequenceID_m::iterator mi; - - mi = m_sequenceMap.find( id ); - if ( mi == m_sequenceMap.end() ) + mi = m_sequenceMap.find(id); + + if (mi == m_sequenceMap.end()) return NULL; - + return (*mi).second; } @@ -309,15 +289,14 @@ Interrupt ------------------------- */ -void CSequencer::Interrupt( void ) -{ - CBlock *command = m_taskManager->GetCurrentTask(); +void CSequencer::Interrupt(void) { + CBlock *command = m_taskManager->GetCurrentTask(); - if ( command == NULL ) + if (command == NULL) return; - //Save it - PushCommand( command, PUSH_BACK ); + // Save it + PushCommand(command, PUSH_BACK); } /* @@ -327,28 +306,25 @@ Run Runs a script ======================== */ -int CSequencer::Run( char *buffer, long size ) -{ - bstream_t *blockStream; - +int CSequencer::Run(char *buffer, long size) { + bstream_t *blockStream; + Recall(); - //Create a new stream + // Create a new stream blockStream = AddStream(); - - //Open the stream as an IBI stream - if (!blockStream->stream->Open( buffer, size )) - { - m_ie->I_DPrintf( WL_ERROR, "invalid stream" ); + + // Open the stream as an IBI stream + if (!blockStream->stream->Open(buffer, size)) { + m_ie->I_DPrintf(WL_ERROR, "invalid stream"); return SEQ_FAILED; } - CSequence *sequence = AddSequence( NULL, m_curSequence, SQ_COMMON ); + CSequence *sequence = AddSequence(NULL, m_curSequence, SQ_COMMON); - // Interpret the command blocks and route them properly - if ( S_FAILED( Route( sequence, blockStream )) ) - { - //Error code is set inside of Route() + // Interpret the command blocks and route them properly + if (S_FAILED(Route(sequence, blockStream))) { + // Error code is set inside of Route() return SEQ_FAILED; } @@ -363,49 +339,45 @@ Parses a user triggered run command ======================== */ -int CSequencer::ParseRun( CBlock *block ) -{ - CSequence *new_sequence; - bstream_t *new_stream; - char *buffer; - char newname[ MAX_STRING_SIZE ]; - int buffer_size; +int CSequencer::ParseRun(CBlock *block) { + CSequence *new_sequence; + bstream_t *new_stream; + char *buffer; + char newname[MAX_STRING_SIZE]; + int buffer_size; - //Get the name and format it - COM_StripExtension( (char*) block->GetMemberData( 0 ), (char *) newname, sizeof(newname) ); + // Get the name and format it + COM_StripExtension((char *)block->GetMemberData(0), (char *)newname, sizeof(newname)); - //Get the file from the game engine - buffer_size = m_ie->I_LoadFile( newname, (void **) &buffer ); + // Get the file from the game engine + buffer_size = m_ie->I_LoadFile(newname, (void **)&buffer); - if ( buffer_size <= 0 ) - { - m_ie->I_DPrintf( WL_ERROR, "'%s' : could not open file\n", (char*) block->GetMemberData( 0 )); + if (buffer_size <= 0) { + m_ie->I_DPrintf(WL_ERROR, "'%s' : could not open file\n", (char *)block->GetMemberData(0)); delete block; block = NULL; return SEQ_FAILED; } - //Create a new stream for this file + // Create a new stream for this file new_stream = AddStream(); - //Begin streaming the file - if (!new_stream->stream->Open( buffer, buffer_size )) - { - m_ie->I_DPrintf( WL_ERROR, "invalid stream" ); + // Begin streaming the file + if (!new_stream->stream->Open(buffer, buffer_size)) { + m_ie->I_DPrintf(WL_ERROR, "invalid stream"); delete block; block = NULL; return SEQ_FAILED; } - //Create a new sequence - new_sequence = AddSequence( m_curSequence, m_curSequence, ( SQ_RUN | SQ_PENDING ) ); + // Create a new sequence + new_sequence = AddSequence(m_curSequence, m_curSequence, (SQ_RUN | SQ_PENDING)); - m_curSequence->AddChild( new_sequence ); + m_curSequence->AddChild(new_sequence); - // Interpret the command blocks and route them properly - if ( S_FAILED( Route( new_sequence, new_stream )) ) - { - //Error code is set inside of Route() + // Interpret the command blocks and route them properly + if (S_FAILED(Route(new_sequence, new_stream))) { + // Error code is set inside of Route() delete block; block = NULL; return SEQ_FAILED; @@ -413,10 +385,10 @@ int CSequencer::ParseRun( CBlock *block ) m_curSequence = m_curSequence->GetReturn(); - assert( m_curSequence ); + assert(m_curSequence); - block->Write( TK_FLOAT, (float) new_sequence->GetID() ); - PushCommand( block, PUSH_FRONT ); + block->Write(TK_FLOAT, (float)new_sequence->GetID()); + PushCommand(block, PUSH_FRONT); return SEQ_OK; } @@ -429,32 +401,30 @@ Parses an if statement ======================== */ -int CSequencer::ParseIf( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; - - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_CONDITIONAL ); - - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseIf: failed to allocate container sequence" ); +int CSequencer::ParseIf(CBlock *block, bstream_t *bstream) { + CSequence *sequence; + + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_CONDITIONAL); + + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseIf: failed to allocate container sequence"); delete block; block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); + + // Add a unique conditional identifier to the block for reference later + block->Write(TK_FLOAT, (float)sequence->GetID()); - //Add a unique conditional identifier to the block for reference later - block->Write( TK_FLOAT, (float) sequence->GetID() ); + // Push this onto the stack to mark the conditional entrance + PushCommand(block, PUSH_FRONT); - //Push this onto the stack to mark the conditional entrance - PushCommand( block, PUSH_FRONT ); - - //Recursively obtain the conditional body - Route( sequence, bstream ); + // Recursively obtain the conditional body + Route(sequence, bstream); m_elseValid = 2; m_elseOwner = block; @@ -470,40 +440,37 @@ Parses an else statement ======================== */ -int CSequencer::ParseElse( CBlock *block, bstream_t *bstream ) -{ - //The else is not retained +int CSequencer::ParseElse(CBlock *block, bstream_t *bstream) { + // The else is not retained delete block; block = NULL; - - CSequence *sequence; - - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_CONDITIONAL ); - - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseIf: failed to allocate container sequence" ); + + CSequence *sequence; + + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_CONDITIONAL); + + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseIf: failed to allocate container sequence"); return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Add a unique conditional identifier to the block for reference later - //TODO: Emit warning - if ( m_elseOwner == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Invalid 'else' found!\n" ); + // Add a unique conditional identifier to the block for reference later + // TODO: Emit warning + if (m_elseOwner == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - m_elseOwner->Write( TK_FLOAT, (float) sequence->GetID() ); - - m_elseOwner->SetFlag( BF_ELSE ); + m_elseOwner->Write(TK_FLOAT, (float)sequence->GetID()); + + m_elseOwner->SetFlag(BF_ELSE); - //Recursively obtain the conditional body - Route( sequence, bstream ); + // Recursively obtain the conditional body + Route(sequence, bstream); m_elseValid = 0; m_elseOwner = NULL; @@ -519,54 +486,49 @@ Parses a loop command ======================== */ -int CSequencer::ParseLoop( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; - CBlockMember *bm; - float min, max; - int rIter; - int memberNum = 0; - - //Set the parent - sequence = AddSequence( m_curSequence, m_curSequence, ( SQ_LOOP | SQ_RETAIN ) ); - - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseLoop : failed to allocate container sequence" ); +int CSequencer::ParseLoop(CBlock *block, bstream_t *bstream) { + CSequence *sequence; + CBlockMember *bm; + float min, max; + int rIter; + int memberNum = 0; + + // Set the parent + sequence = AddSequence(m_curSequence, m_curSequence, (SQ_LOOP | SQ_RETAIN)); + + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseLoop : failed to allocate container sequence"); delete block; - block = NULL; + block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Set the number of iterations of this sequence - - bm = block->GetMember( memberNum++ ); + // Set the number of iterations of this sequence - if ( bm->GetID() == ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); - - rIter = (int) m_ie->I_Random( min, max ); - sequence->SetIterations( rIter ); - } - else - { - sequence->SetIterations ( (int) (*(float *) bm->GetData()) ); + bm = block->GetMember(memberNum++); + + if (bm->GetID() == ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); + + rIter = (int)m_ie->I_Random(min, max); + sequence->SetIterations(rIter); + } else { + sequence->SetIterations((int)(*(float *)bm->GetData())); } - - //Add a unique loop identifier to the block for reference later - block->Write( TK_FLOAT, (float) sequence->GetID() ); - //Push this onto the stack to mark the loop entrance - PushCommand( block, PUSH_FRONT ); - - //Recursively obtain the loop - Route( sequence, bstream ); + // Add a unique loop identifier to the block for reference later + block->Write(TK_FLOAT, (float)sequence->GetID()); + + // Push this onto the stack to mark the loop entrance + PushCommand(block, PUSH_FRONT); + + // Recursively obtain the loop + Route(sequence, bstream); return SEQ_OK; } @@ -579,31 +541,29 @@ Adds a sequence that is saved until the affect is called by the parent ======================== */ -int CSequencer::AddAffect( bstream_t *bstream, int retain, int *id ) -{ - CSequence *sequence = AddSequence(); - bstream_t new_stream; +int CSequencer::AddAffect(bstream_t *bstream, int retain, int *id) { + CSequence *sequence = AddSequence(); + bstream_t new_stream; - sequence->SetFlag( SQ_AFFECT | SQ_PENDING ); + sequence->SetFlag(SQ_AFFECT | SQ_PENDING); - if ( retain ) - sequence->SetFlag( SQ_RETAIN ); + if (retain) + sequence->SetFlag(SQ_RETAIN); - //This will be replaced once it's actually used, but this will restore the route state properly - sequence->SetReturn( m_curSequence ); - - //We need this as a temp holder + // This will be replaced once it's actually used, but this will restore the route state properly + sequence->SetReturn(m_curSequence); + + // We need this as a temp holder new_stream.last = m_curStream; new_stream.stream = bstream->stream; - if S_FAILED( Route( sequence, &new_stream ) ) - { + if S_FAILED (Route(sequence, &new_stream)) { return SEQ_FAILED; } *id = sequence->GetID(); - sequence->SetReturn( NULL ); + sequence->SetReturn(NULL); return SEQ_OK; } @@ -616,130 +576,121 @@ Parses an affect command ======================== */ -int CSequencer::ParseAffect( CBlock *block, bstream_t *bstream ) -{ - CSequencer *stream_sequencer = NULL; - char *entname = NULL; - int ret; - gentity_t *ent = 0; +int CSequencer::ParseAffect(CBlock *block, bstream_t *bstream) { + CSequencer *stream_sequencer = NULL; + char *entname = NULL; + int ret; + gentity_t *ent = 0; - entname = (char*) block->GetMemberData( 0 ); - ent = m_ie->I_GetEntityByName( entname ); + entname = (char *)block->GetMemberData(0); + ent = m_ie->I_GetEntityByName(entname); - if( !ent ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (!ent) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' - - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + // try to parse a 'get' command that is embeded in this 'affect' + + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - - switch ( id ) - { - // these 3 cases probably aren't necessary - case TK_STRING: - case TK_IDENTIFIER: - case TK_CHAR: - p1 = (char *) bm->GetData(); + + switch (id) { + // these 3 cases probably aren't necessary + case TK_STRING: + case TK_IDENTIFIER: + case TK_CHAR: + p1 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; + case ID_GET: { + int type; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( 1 )); - name = (char *) block->GetMemberData( 2 ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(1)); + name = (char *)block->GetMemberData(2); - switch ( type ) // what type are they attempting to get - { - - case TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - { - delete block; - block = NULL; - return false; - } - break; - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _1" ); - delete block; - block = NULL; - return false; - break; - } + switch (type) // what type are they attempting to get + { + case TK_STRING: + // only string is acceptable for affect, store result in p1 + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) { + delete block; + block = NULL; + return false; + } break; - } - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _1"); delete block; block = NULL; return false; break; - }//end id switch + } - if(p1) - { - ent = m_ie->I_GetEntityByName( p1 ); + break; } - if(!ent) - { // a valid entity name was not returned from the get command - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n"); + + default: + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _2"); + delete block; + block = NULL; + return false; + break; + } // end id switch + + if (p1) { + ent = m_ie->I_GetEntityByName(p1); + } + if (!ent) { // a valid entity name was not returned from the get command + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n"); } - + } // end if(!ent) - if( ent ) - { + if (ent) { stream_sequencer = ent->sequencer; } - if (stream_sequencer == NULL) - { - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n", entname ); - - //Fast-forward out of this affect block onto the next valid code + if (stream_sequencer == NULL) { + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n", entname); + + // Fast-forward out of this affect block onto the next valid code CSequence *backSeq = m_curSequence; CSequence *trashSeq = m_owner->GetSequence(); - Route( trashSeq, bstream ); + Route(trashSeq, bstream); Recall(); - DestroySequence( trashSeq ); + DestroySequence(trashSeq); m_curSequence = backSeq; delete block; block = NULL; return SEQ_OK; } - if S_FAILED ( stream_sequencer->AddAffect( bstream, (int) m_curSequence->HasFlag( SQ_RETAIN ), &ret ) ) - { + if S_FAILED (stream_sequencer->AddAffect(bstream, (int)m_curSequence->HasFlag(SQ_RETAIN), &ret)) { delete block; block = NULL; return SEQ_FAILED; } - //Hold onto the id for later use - //FIXME: If the target sequence is freed, what then? (!suspect!) + // Hold onto the id for later use + // FIXME: If the target sequence is freed, what then? (!suspect!) - block->Write( TK_FLOAT, (float) ret ); - - PushCommand( block, PUSH_FRONT ); + block->Write(TK_FLOAT, (float)ret); + + PushCommand(block, PUSH_FRONT); /* //Don't actually do these right now, we're just pre-processing (parsing) the affect if( ent ) - { // ents need to update upon being affected + { // ents need to update upon being affected ent->taskManager->Update(); } */ @@ -753,43 +704,41 @@ ParseTask ------------------------- */ -int CSequencer::ParseTask( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; - CTaskGroup *group; - const char *taskName; +int CSequencer::ParseTask(CBlock *block, bstream_t *bstream) { + CSequence *sequence; + CTaskGroup *group; + const char *taskName; - //Setup the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_TASK | SQ_RETAIN ); - m_curSequence->AddChild( sequence ); + // Setup the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_TASK | SQ_RETAIN); + m_curSequence->AddChild(sequence); - //Get the name of this task for reference later - taskName = (const char *) block->GetMemberData( 0 ); + // Get the name of this task for reference later + taskName = (const char *)block->GetMemberData(0); - //Get a new task group from the task manager - group = m_taskManager->AddTaskGroup( taskName ); + // Get a new task group from the task manager + group = m_taskManager->AddTaskGroup(taskName); - if ( group == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "error : unable to allocate a new task group" ); + if (group == NULL) { + m_ie->I_DPrintf(WL_ERROR, "error : unable to allocate a new task group"); delete block; block = NULL; return SEQ_FAILED; } - //The current group is set to this group, all subsequent commands (until a block end) will fall into this task group - group->SetParent( m_curGroup ); + // The current group is set to this group, all subsequent commands (until a block end) will fall into this task group + group->SetParent(m_curGroup); m_curGroup = group; - - //Keep an association between this task and the container sequence - AddTaskSequence( sequence, group ); - //PushCommand( block, PUSH_FRONT ); + // Keep an association between this task and the container sequence + AddTaskSequence(sequence, group); + + // PushCommand( block, PUSH_FRONT ); delete block; block = NULL; - //Recursively obtain the loop - Route( sequence, bstream ); + // Recursively obtain the loop + Route(sequence, bstream); return SEQ_OK; } @@ -802,111 +751,105 @@ Properly handles and routes commands to the sequencer ======================== */ -//FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently +// FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently -//FIXME: A sequencer cannot properly affect itself +// FIXME: A sequencer cannot properly affect itself -int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) -{ - CBlockStream *stream; - CBlock *block; +int CSequencer::Route(CSequence *sequence, bstream_t *bstream) { + CBlockStream *stream; + CBlock *block; - //Take the stream as the current stream + // Take the stream as the current stream m_curStream = bstream; stream = bstream->stream; m_curSequence = sequence; - //Obtain all blocks - while ( stream->BlockAvailable() ) - { - block = new CBlock; //deleted in Free() - stream->ReadBlock( block ); + // Obtain all blocks + while (stream->BlockAvailable()) { + block = new CBlock; // deleted in Free() + stream->ReadBlock(block); - //TEMP: HACK! - if ( m_elseValid ) + // TEMP: HACK! + if (m_elseValid) m_elseValid--; - switch( block->GetBlockID() ) - { - //Marks the end of a blocked section + switch (block->GetBlockID()) { + // Marks the end of a blocked section case ID_BLOCK_END: - - //Save this as a pre-process marker - PushCommand( block, PUSH_FRONT ); - - if ( m_curSequence->HasFlag( SQ_RUN ) || m_curSequence->HasFlag( SQ_AFFECT ) ) - { - //Go back to the last stream + + // Save this as a pre-process marker + PushCommand(block, PUSH_FRONT); + + if (m_curSequence->HasFlag(SQ_RUN) || m_curSequence->HasFlag(SQ_AFFECT)) { + // Go back to the last stream m_curStream = bstream->last; } - if ( m_curSequence->HasFlag( SQ_TASK ) ) - { - //Go back to the last stream + if (m_curSequence->HasFlag(SQ_TASK)) { + // Go back to the last stream m_curStream = bstream->last; m_curGroup = m_curGroup->GetParent(); } - + m_curSequence = m_curSequence->GetReturn(); return SEQ_OK; break; - //Affect pre-processor + // Affect pre-processor case ID_AFFECT: - if S_FAILED( ParseAffect( block, bstream ) ) + if S_FAILED (ParseAffect(block, bstream)) return SEQ_FAILED; break; - //Run pre-processor + // Run pre-processor case ID_RUN: - if S_FAILED( ParseRun( block ) ) + if S_FAILED (ParseRun(block)) return SEQ_FAILED; break; - //Loop pre-processor + // Loop pre-processor case ID_LOOP: - - if S_FAILED( ParseLoop( block, bstream ) ) + + if S_FAILED (ParseLoop(block, bstream)) return SEQ_FAILED; break; - //Conditional pre-processor + // Conditional pre-processor case ID_IF: - if S_FAILED( ParseIf( block, bstream ) ) + if S_FAILED (ParseIf(block, bstream)) return SEQ_FAILED; break; case ID_ELSE: - //TODO: Emit warning - if ( m_elseValid == 0 ) - { - m_ie->I_DPrintf( WL_ERROR, "Invalid 'else' found!\n" ); + // TODO: Emit warning + if (m_elseValid == 0) { + m_ie->I_DPrintf(WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - if S_FAILED( ParseElse( block, bstream ) ) + if S_FAILED (ParseElse(block, bstream)) return SEQ_FAILED; break; case ID_TASK: - - if S_FAILED( ParseTask( block, bstream ) ) + + if S_FAILED (ParseTask(block, bstream)) return SEQ_FAILED; break; - //FIXME: For now this is to catch problems, but can ultimately be removed + // FIXME: For now this is to catch problems, but can ultimately be removed case ID_WAIT: case ID_PRINT: case ID_SOUND: @@ -925,26 +868,25 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) case ID_WAITSIGNAL: case ID_PLAY: - //Commands go directly into the sequence without pre-process - PushCommand( block, PUSH_FRONT ); + // Commands go directly into the sequence without pre-process + PushCommand(block, PUSH_FRONT); break; - //Error + // Error default: - - m_ie->I_DPrintf( WL_ERROR, "'%d' : invalid block ID", block->GetBlockID() ); - + + m_ie->I_DPrintf(WL_ERROR, "'%d' : invalid block ID", block->GetBlockID()); + return SEQ_FAILED; break; } } - //Check for a run sequence, it must be marked - if ( m_curSequence->HasFlag( SQ_RUN ) ) - { + // Check for a run sequence, it must be marked + if (m_curSequence->HasFlag(SQ_RUN)) { block = new CBlock; - block->Create( ID_BLOCK_END ); - PushCommand( block, PUSH_FRONT ); //mark the end of the run + block->Create(ID_BLOCK_END); + PushCommand(block, PUSH_FRONT); // mark the end of the run /* //Free the stream @@ -955,18 +897,17 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) return SEQ_OK; } - //Check to start the communication - if ( ( bstream->last == NULL ) && ( m_numCommands > 0 ) ) - { - //Everything is routed, so get it all rolling - Prime( m_taskManager, PopCommand( POP_BACK ) ); + // Check to start the communication + if ((bstream->last == NULL) && (m_numCommands > 0)) { + // Everything is routed, so get it all rolling + Prime(m_taskManager, PopCommand(POP_BACK)); } m_curStream = bstream->last; - //Free the stream - DeleteStream( bstream ); - + // Free the stream + DeleteStream(bstream); + return SEQ_OK; } @@ -978,81 +919,69 @@ Checks for run command pre-processing ======================== */ -//Directly changes the parameter to avoid excess push/pop +// Directly changes the parameter to avoid excess push/pop -void CSequencer::CheckRun( CBlock **command ) -{ - CBlock *block = *command; +void CSequencer::CheckRun(CBlock **command) { + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - //Check for a run command - if ( block->GetBlockID() == ID_RUN ) - { - int id = (int) (*(float *) block->GetMemberData( 1 )); + // Check for a run command + if (block->GetBlockID() == ID_RUN) { + int id = (int)(*(float *)block->GetMemberData(1)); - m_ie->I_DPrintf( WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *) block->GetMemberData(0), m_ie->I_GetTime() ); + m_ie->I_DPrintf(WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *)block->GetMemberData(0), m_ie->I_GetTime()); - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_curSequence = GetSequence( id ); - - //TODO: Emit warning - assert( m_curSequence ); - if ( m_curSequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find 'run' sequence!\n" ); + m_curSequence = GetSequence(id); + + // TODO: Emit warning + assert(m_curSequence); + if (m_curSequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find 'run' sequence!\n"); *command = NULL; return; } - if ( m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( POP_BACK ); - - Prep( command ); //Account for any other pre-processes + if (m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(POP_BACK); + + Prep(command); // Account for any other pre-processes return; } return; } - - //Check for the end of a run - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_RUN ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + + // Check for the end of a run + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_RUN))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_curSequence = ReturnSequence( m_curSequence ); + m_curSequence = ReturnSequence(m_curSequence); - if ( m_curSequence && m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( POP_BACK ); - - Prep( command ); //Account for any other pre-processes + if (m_curSequence && m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(POP_BACK); + + Prep(command); // Account for any other pre-processes return; - } + } - //FIXME: Check this... + // FIXME: Check this... } } @@ -1062,45 +991,42 @@ EvaluateConditional ------------------------- */ -//FIXME: This function will be written better later once the functionality of the ideas here are tested +// FIXME: This function will be written better later once the functionality of the ideas here are tested -int CSequencer::EvaluateConditional( CBlock *block ) -{ - CBlockMember *bm; - char tempString1[128], tempString2[128]; - vector_t vec; - int id, i, oper, memberNum = 0; - char *p1 = NULL, *p2 = NULL; - int t1, t2; +int CSequencer::EvaluateConditional(CBlock *block) { + CBlockMember *bm; + char tempString1[128], tempString2[128]; + vector_t vec; + int id, i, oper, memberNum = 0; + char *p1 = NULL, *p2 = NULL; + int t1, t2; // // Get the first parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t1 = id; - switch ( id ) - { + switch (id) { case TK_FLOAT: - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f", *(float *) bm->GetData() ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", *(float *)bm->GetData()); + p1 = (char *)tempString1; break; case TK_VECTOR: tempString1[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; break; @@ -1108,115 +1034,106 @@ int CSequencer::EvaluateConditional( CBlock *block ) case TK_IDENTIFIER: case TK_CHAR: - p1 = (char *) bm->GetData(); + p1 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; - char *name; + case ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t1 = type; + // Get the type returned and hold onto it + t1 = type; - switch ( type ) - { - case TK_FLOAT: - { - float fVal; + switch (type) { + case TK_FLOAT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f", fVal ); - p1 = (char *) tempString1; - } - - break; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", fVal); + p1 = (char *)tempString1; + } - case TK_INT: - { - float fVal; + break; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + case TK_INT: { + float fVal; - Com_sprintf( tempString1, sizeof( tempString1 ), "%d", (int) fVal ); - p1 = (char *) tempString1; - } - break; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - case TK_STRING: + Com_sprintf(tempString1, sizeof(tempString1), "%d", (int)fVal); + p1 = (char *)tempString1; + } break; - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - return false; - - break; + case TK_STRING: - case TK_VECTOR: - { - vector_t vVal; + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) + return false; - if ( m_ie->I_GetVector( m_ownerID, type, name, vVal ) == false) - return false; + break; - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p1 = (char *) tempString1; - } - - break; + case TK_VECTOR: { + vector_t vVal; + + if (m_ie->I_GetVector(m_ownerID, type, name, vVal) == false) + return false; + + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p1 = (char *)tempString1; + } + + break; } break; } - case ID_RANDOM: - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements + case ID_RANDOM: { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - //A float value is returned from the function - t1 = TK_FLOAT; + // A float value is returned from the function + t1 = TK_FLOAT; - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f", m_ie->I_Random( min, max ) ); - p1 = (char *) tempString1; - } + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", m_ie->I_Random(min, max)); + p1 = (char *)tempString1; + } - break; + break; - case ID_TAG: - { - char *name; - float type; + case ID_TAG: { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t1 = TK_VECTOR; + t1 = TK_VECTOR; - //TODO: Emit warning - if ( m_ie->I_GetTag( m_ownerID, name, (int) type, vec ) == false) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (m_ie->I_GetTag(m_ownerID, name, (int)type, vec) == false) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - Com_sprintf( tempString1, sizeof( tempString1 ), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on conditional"); return false; break; } @@ -1225,11 +1142,10 @@ int CSequencer::EvaluateConditional( CBlock *block ) // Get the comparison operator // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); - switch ( id ) - { + switch (id) { case TK_EQUALS: case TK_GREATER_THAN: case TK_LESS_THAN: @@ -1238,8 +1154,8 @@ int CSequencer::EvaluateConditional( CBlock *block ) break; default: - m_ie->I_DPrintf( WL_ERROR, "Invalid operator type found on conditional!\n" ); - return false; //FIXME: Emit warning + m_ie->I_DPrintf(WL_ERROR, "Invalid operator type found on conditional!\n"); + return false; // FIXME: Emit warning break; } @@ -1247,30 +1163,28 @@ int CSequencer::EvaluateConditional( CBlock *block ) // Get the second parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t2 = id; - switch ( id ) - { + switch (id) { case TK_FLOAT: - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f", *(float *) bm->GetData() ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", *(float *)bm->GetData()); + p2 = (char *)tempString2; break; case TK_VECTOR: tempString2[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; break; @@ -1278,122 +1192,115 @@ int CSequencer::EvaluateConditional( CBlock *block ) case TK_IDENTIFIER: case TK_CHAR: - p2 = (char *) bm->GetData(); + p2 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; - char *name; + case ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t2 = type; + // Get the type returned and hold onto it + t2 = type; - switch ( type ) - { - case TK_FLOAT: - { - float fVal; + switch (type) { + case TK_FLOAT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f", fVal ); - p2 = (char *) tempString2; - } - - break; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", fVal); + p2 = (char *)tempString2; + } - case TK_INT: - { - float fVal; + break; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + case TK_INT: { + float fVal; - Com_sprintf( tempString2, sizeof( tempString2 ), "%d", (int) fVal ); - p2 = (char *) tempString2; - } - break; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - case TK_STRING: + Com_sprintf(tempString2, sizeof(tempString2), "%d", (int)fVal); + p2 = (char *)tempString2; + } break; - if ( m_ie->I_GetString( m_ownerID, type, name, &p2 ) == false) - return false; - - break; + case TK_STRING: - case TK_VECTOR: - { - vector_t vVal; + if (m_ie->I_GetString(m_ownerID, type, name, &p2) == false) + return false; - if ( m_ie->I_GetVector( m_ownerID, type, name, vVal ) == false) - return false; + break; - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p2 = (char *) tempString2; - } - - break; + case TK_VECTOR: { + vector_t vVal; + + if (m_ie->I_GetVector(m_ownerID, type, name, vVal) == false) + return false; + + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p2 = (char *)tempString2; + } + + break; } break; } case ID_RANDOM: - - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - //A float value is returned from the function - t2 = TK_FLOAT; + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f", m_ie->I_Random( min, max ) ); - p2 = (char *) tempString2; - } + // A float value is returned from the function + t2 = TK_FLOAT; - break; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", m_ie->I_Random(min, max)); + p2 = (char *)tempString2; + } + + break; case ID_TAG: - { - char *name; - float type; + { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t2 = TK_VECTOR; + t2 = TK_VECTOR; - //TODO: Emit warning - if ( m_ie->I_GetTag( m_ownerID, name, (int) type, vec ) == false) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (m_ie->I_GetTag(m_ownerID, name, (int)type, vec) == false) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - Com_sprintf( tempString2, sizeof( tempString2 ), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on conditional"); return false; break; } - return m_ie->I_Evaluate( t1, p1, t2, p2, oper ); + return m_ie->I_Evaluate(t1, p1, t2, p2, oper); } /* @@ -1404,149 +1311,125 @@ Checks for if statement pre-processing ======================== */ -void CSequencer::CheckIf( CBlock **command ) -{ - CBlock *block = *command; - int successID, failureID; - CSequence *successSeq, *failureSeq; +void CSequencer::CheckIf(CBlock **command) { + CBlock *block = *command; + int successID, failureID; + CSequence *successSeq, *failureSeq; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_IF ) - { - int ret = EvaluateConditional( block ); + if (block->GetBlockID() == ID_IF) { + int ret = EvaluateConditional(block); - if ( ret /*TRUE*/ ) - { - if ( block->HasFlag( BF_ELSE ) ) - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 2 )); - } - else - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); + if (ret /*TRUE*/) { + if (block->HasFlag(BF_ELSE)) { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 2)); + } else { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); } - successSeq = GetSequence( successID ); + successSeq = GetSequence(successID); - //TODO: Emit warning - assert( successSeq ); - if ( successSeq == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find conditional success sequence!\n" ); + // TODO: Emit warning + assert(successSeq); + if (successSeq == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find conditional success sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - + m_curSequence = successSeq; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); - - return; + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); + + return; } - if ( ( ret == false ) && ( block->HasFlag( BF_ELSE ) ) ) - { - failureID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); - failureSeq = GetSequence( failureID ); + if ((ret == false) && (block->HasFlag(BF_ELSE))) { + failureID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); + failureSeq = GetSequence(failureID); - //TODO: Emit warning - assert( failureSeq ); - if ( failureSeq == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find conditional failure sequence!\n" ); + // TODO: Emit warning + assert(failureSeq); + if (failureSeq == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find conditional failure sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - + m_curSequence = failureSeq; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); - - return; - } + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); + return; } - else - { + + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Conditional failed, just move on to the next command - *command = PopCommand( POP_BACK ); - Prep( command ); - - return; + // Conditional failed, just move on to the next command + *command = PopCommand(POP_BACK); + Prep(command); + + return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_CONDITIONAL ) ) ) - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_CONDITIONAL))) { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - - //Back out of the conditional and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); - - //This can safely happen - if ( m_curSequence == NULL ) - { + + // Back out of the conditional and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); + + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } @@ -1558,132 +1441,113 @@ Checks for loop command pre-processing ======================== */ -void CSequencer::CheckLoop( CBlock **command ) -{ - CBlockMember *bm; - CBlock *block = *command; - float min, max; - int iterations; - int loopID; - int memberNum = 0; - - if ( block == NULL ) +void CSequencer::CheckLoop(CBlock **command) { + CBlockMember *bm; + CBlock *block = *command; + float min, max; + int iterations; + int loopID; + int memberNum = 0; + + if (block == NULL) return; - //Check for a loop - if ( block->GetBlockID() == ID_LOOP ) - { - //Get the loop ID - bm = block->GetMember( memberNum++ ); + // Check for a loop + if (block->GetBlockID() == ID_LOOP) { + // Get the loop ID + bm = block->GetMember(memberNum++); - if ( bm->GetID() == ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); - - iterations = (int) m_ie->I_Random( min, max ); - } - else - { - iterations = (int) (*(float *) bm->GetData()); + if (bm->GetID() == ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); + + iterations = (int)m_ie->I_Random(min, max); + } else { + iterations = (int)(*(float *)bm->GetData()); } - - loopID = (int) (*(float *) block->GetMemberData( memberNum++ )); - - CSequence *loop = GetSequence( loopID ); - - //TODO: Emit warning - assert( loop ); - if ( loop == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find 'loop' sequence!\n" ); + + loopID = (int)(*(float *)block->GetMemberData(memberNum++)); + + CSequence *loop = GetSequence(loopID); + + // TODO: Emit warning + assert(loop); + if (loop == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find 'loop' sequence!\n"); *command = NULL; return; } - assert( loop->GetParent() ); - if ( loop->GetParent() == NULL ) - { + assert(loop->GetParent()); + if (loop->GetParent() == NULL) { *command = NULL; return; } - //Restore the count if it has been lost - loop->SetIterations( iterations ); + // Restore the count if it has been lost + loop->SetIterations(iterations); - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - + m_curSequence = loop; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); - + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); + return; } - - //Check for the end of the loop - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_LOOP ) ) ) - { - //We don't want to decrement -1 - if ( m_curSequence->GetIterations() > 0 ) - m_curSequence->SetIterations( m_curSequence->GetIterations()-1 ); //Nice, eh? - //Either there's another iteration, or it's infinite - if ( m_curSequence->GetIterations() != 0 ) - { - //Another iteration is going to happen, so this will need to be considered again - PushCommand( block, PUSH_FRONT ); - - *command = PopCommand( POP_BACK ); - Prep( command ); - + // Check for the end of the loop + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_LOOP))) { + // We don't want to decrement -1 + if (m_curSequence->GetIterations() > 0) + m_curSequence->SetIterations(m_curSequence->GetIterations() - 1); // Nice, eh? + + // Either there's another iteration, or it's infinite + if (m_curSequence->GetIterations() != 0) { + // Another iteration is going to happen, so this will need to be considered again + PushCommand(block, PUSH_FRONT); + + *command = PopCommand(POP_BACK); + Prep(command); + return; - } - else - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + } else { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - - //Back out of the loop and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); - - //This can safely happen - if ( m_curSequence == NULL ) - { + + // Back out of the loop and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); + + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } } @@ -1696,33 +1560,28 @@ Checks for flush command pre-processing ======================== */ -void CSequencer::CheckFlush( CBlock **command ) -{ - sequence_l::iterator sli; - CBlock *block = *command; +void CSequencer::CheckFlush(CBlock **command) { + sequence_l::iterator sli; + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_FLUSH ) - { - //Flush the sequence - Flush( m_curSequence ); + if (block->GetBlockID() == ID_FLUSH) { + // Flush the sequence + Flush(m_curSequence); - //Check to retain it - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); return; } @@ -1736,163 +1595,141 @@ Checks for affect command pre-processing ======================== */ -void CSequencer::CheckAffect( CBlock **command ) -{ +void CSequencer::CheckAffect(CBlock **command) { CBlock *block = *command; - gentity_t *ent = NULL; - char *entname = NULL; - int memberNum = 0; + gentity_t *ent = NULL; + char *entname = NULL; + int memberNum = 0; - if ( block == NULL ) - { + if (block == NULL) { return; } - if ( block->GetBlockID() == ID_AFFECT ) - { - CSequencer *sequencer = NULL; - entname = (char*) block->GetMemberData( memberNum++ ); - ent = m_ie->I_GetEntityByName( entname ); - - if( !ent ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (block->GetBlockID() == ID_AFFECT) { + CSequencer *sequencer = NULL; + entname = (char *)block->GetMemberData(memberNum++); + ent = m_ie->I_GetEntityByName(entname); + + if (!ent) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' - - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + // try to parse a 'get' command that is embeded in this 'affect' + + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - - switch ( id ) - { - // these 3 cases probably aren't necessary - case TK_STRING: - case TK_IDENTIFIER: - case TK_CHAR: - p1 = (char *) bm->GetData(); + + switch (id) { + // these 3 cases probably aren't necessary + case TK_STRING: + case TK_IDENTIFIER: + case TK_CHAR: + p1 = (char *)bm->GetData(); break; - case ID_GET: + case ID_GET: { + int type; + + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); + + switch (type) // what type are they attempting to get { - int type; - - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); - - switch ( type ) // what type are they attempting to get - { - - case TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - { - return; - } - break; - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _1" ); - return; - break; - } + case TK_STRING: + // only string is acceptable for affect, store result in p1 + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) { + return; + } break; - } - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _1"); return; break; - }//end id switch + } - if(p1) - { - ent = m_ie->I_GetEntityByName( p1 ); + break; } - if(!ent) - { // a valid entity name was not returned from the get command - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n"); + + default: + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _2"); + return; + break; + } // end id switch + + if (p1) { + ent = m_ie->I_GetEntityByName(p1); + } + if (!ent) { // a valid entity name was not returned from the get command + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n"); } - + } // end if(!ent) - if( ent ) - { + if (ent) { sequencer = ent->sequencer; } - if(memberNum == 0) - { //there was no get, increment manually before next step + if (memberNum == 0) { // there was no get, increment manually before next step memberNum++; } - int type = (int) (*(float *) block->GetMemberData( memberNum )); - int id = (int) (*(float *) block->GetMemberData( memberNum+1 )); - - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + int type = (int)(*(float *)block->GetMemberData(memberNum)); + int id = (int)(*(float *)block->GetMemberData(memberNum + 1)); + + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - - //NOTENOTE: If this isn't found, continue on to the next command - if ( sequencer == NULL ) - { - *command = PopCommand( POP_BACK ); - Prep( command ); + + // NOTENOTE: If this isn't found, continue on to the next command + if (sequencer == NULL) { + *command = PopCommand(POP_BACK); + Prep(command); return; } - sequencer->Affect( id, type ); + sequencer->Affect(id, type); - *command = PopCommand( POP_BACK ); - Prep( command ); - if( ent ) - { // ents need to update upon being affected + *command = PopCommand(POP_BACK); + Prep(command); + if (ent) { // ents need to update upon being affected ent->taskManager->Update(); } return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_AFFECT ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_AFFECT))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - - m_curSequence = ReturnSequence( m_curSequence ); - if ( m_curSequence == NULL ) - { + m_curSequence = ReturnSequence(m_curSequence); + + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); - if( ent ) - { // ents need to update upon being affected + *command = PopCommand(POP_BACK); + Prep(command); + if (ent) { // ents need to update upon being affected ent->taskManager->Update(); } - } } @@ -1902,97 +1739,85 @@ CheckDo ------------------------- */ -void CSequencer::CheckDo( CBlock **command ) -{ +void CSequencer::CheckDo(CBlock **command) { CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_DO ) - { - //Get the sequence - const char *groupName = (const char *) block->GetMemberData( 0 ); - CTaskGroup *group = m_taskManager->GetTaskGroup( groupName ); - CSequence *sequence = GetTaskSequence( group ); - - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - m_ie->I_DPrintf( WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName ); + if (block->GetBlockID() == ID_DO) { + // Get the sequence + const char *groupName = (const char *)block->GetMemberData(0); + CTaskGroup *group = m_taskManager->GetTaskGroup(groupName); + CSequence *sequence = GetTaskSequence(group); + + // TODO: Emit warning + assert(group); + if (group == NULL) { + // TODO: Give name/number of entity trying to execute, too + m_ie->I_DPrintf(WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName); *command = NULL; return; } - //TODO: Emit warning - assert( sequence ); - if ( sequence == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - m_ie->I_DPrintf( WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName ); + // TODO: Emit warning + assert(sequence); + if (sequence == NULL) { + // TODO: Give name/number of entity trying to execute, too + m_ie->I_DPrintf(WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName); *command = NULL; return; } - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Set this to our current sequence - sequence->SetReturn( m_curSequence ); + // Set this to our current sequence + sequence->SetReturn(m_curSequence); m_curSequence = sequence; - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - //Mark all the following commands as being in the task - m_taskManager->MarkTask( group->GetGUID(), TASK_START ); + // Mark all the following commands as being in the task + m_taskManager->MarkTask(group->GetGUID(), TASK_START); + + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); - return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_TASK ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_TASK))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - - m_taskManager->MarkTask( m_curGroup->GetGUID(), TASK_END ); + + m_taskManager->MarkTask(m_curGroup->GetGUID(), TASK_END); m_curGroup = m_curGroup->GetParent(); - CSequence *returnSeq = ReturnSequence( m_curSequence ); - m_curSequence->SetReturn( NULL ); + CSequence *returnSeq = ReturnSequence(m_curSequence); + m_curSequence->SetReturn(NULL); m_curSequence = returnSeq; - if ( m_curSequence == NULL ) - { + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } @@ -2004,15 +1829,14 @@ Handles internal sequencer maintenance ======================== */ -void CSequencer::Prep( CBlock **command ) -{ - //Check all pre-processes - CheckAffect( command ); - CheckFlush( command ); - CheckLoop( command ); - CheckRun( command ); - CheckIf( command ); - CheckDo( command ); +void CSequencer::Prep(CBlock **command) { + // Check all pre-processes + CheckAffect(command); + CheckFlush(command); + CheckLoop(command); + CheckRun(command); + CheckIf(command); + CheckDo(command); } /* @@ -2023,13 +1847,11 @@ Starts communication between the task manager and this sequencer ======================== */ -int CSequencer::Prime( CTaskManager *taskManager, CBlock *command ) -{ - Prep( &command ); +int CSequencer::Prime(CTaskManager *taskManager, CBlock *command) { + Prep(&command); - if ( command ) - { - taskManager->SetCommand( command, PUSH_BACK ); + if (command) { + taskManager->SetCommand(command, PUSH_BACK); } return SEQ_OK; @@ -2043,51 +1865,45 @@ Handles a completed task and returns a new task to be completed ======================== */ -int CSequencer::Callback( CTaskManager *taskManager, CBlock *block, int returnCode ) -{ - CBlock *command; +int CSequencer::Callback(CTaskManager *taskManager, CBlock *block, int returnCode) { + CBlock *command; - if (returnCode == TASK_RETURN_COMPLETE) - { - //There are no more pending commands - if ( m_curSequence == NULL ) - { + if (returnCode == TASK_RETURN_COMPLETE) { + // There are no more pending commands + if (m_curSequence == NULL) { delete block; block = NULL; return SEQ_OK; } - //Check to retain the command - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) //This isn't true for affect sequences...? - { - PushCommand( block, PUSH_FRONT ); - } - else + // Check to retain the command + if (m_curSequence->HasFlag(SQ_RETAIN)) // This isn't true for affect sequences...? { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; } - //Check for pending commands - if ( m_curSequence->GetNumCommands() <= 0 ) - { - if ( m_curSequence->GetReturn() == NULL) + // Check for pending commands + if (m_curSequence->GetNumCommands() <= 0) { + if (m_curSequence->GetReturn() == NULL) return SEQ_OK; m_curSequence = m_curSequence->GetReturn(); } - command = PopCommand( POP_BACK ); - Prep( &command ); + command = PopCommand(POP_BACK); + Prep(&command); - if ( command ) - taskManager->SetCommand( command, PUSH_FRONT ); + if (command) + taskManager->SetCommand(command, PUSH_FRONT); return SEQ_OK; } - //FIXME: This could be more descriptive - m_ie->I_DPrintf( WL_ERROR, "command could not be called back\n" ); + // FIXME: This could be more descriptive + m_ie->I_DPrintf(WL_ERROR, "command could not be called back\n"); assert(0); return SEQ_FAILED; @@ -2099,18 +1915,13 @@ Recall ------------------------- */ -int CSequencer::Recall( void ) -{ - CBlock *block = NULL; +int CSequencer::Recall(void) { + CBlock *block = NULL; - while ( ( block = m_taskManager->RecallTask() ) != NULL ) - { - if (m_curSequence) - { - PushCommand( block, PUSH_BACK ); - } - else - { + while ((block = m_taskManager->RecallTask()) != NULL) { + if (m_curSequence) { + PushCommand(block, PUSH_BACK); + } else { delete block; block = NULL; } @@ -2125,48 +1936,44 @@ Affect ------------------------- */ -int CSequencer::Affect( int id, int type ) -{ - CSequence *sequence = GetSequence( id ); +int CSequencer::Affect(int id, int type) { + CSequence *sequence = GetSequence(id); - if ( sequence == NULL ) - { + if (sequence == NULL) { return SEQ_FAILED; } - switch ( type ) - { + switch (type) { case TYPE_FLUSH: - //Get rid of all old code - Flush( sequence ); + // Get rid of all old code + Flush(sequence); + + sequence->RemoveFlag(SQ_PENDING, true); - sequence->RemoveFlag( SQ_PENDING, true ); - m_curSequence = sequence; - Prime( m_taskManager, PopCommand( POP_BACK ) ); + Prime(m_taskManager, PopCommand(POP_BACK)); break; - + case TYPE_INSERT: Recall(); - - sequence->SetReturn( m_curSequence ); - - sequence->RemoveFlag( SQ_PENDING, true ); - + + sequence->SetReturn(m_curSequence); + + sequence->RemoveFlag(SQ_PENDING, true); + m_curSequence = sequence; - Prime( m_taskManager, PopCommand( POP_BACK ) ); + Prime(m_taskManager, PopCommand(POP_BACK)); break; - default: - m_ie->I_DPrintf( WL_ERROR, "unknown affect type found" ); + m_ie->I_DPrintf(WL_ERROR, "unknown affect type found"); break; } @@ -2181,17 +1988,16 @@ Pushes a commands onto the current sequence ======================== */ -int CSequencer::PushCommand( CBlock *command, int flag ) -{ - //Make sure everything is ok - assert( m_curSequence ); - if ( m_curSequence == NULL ) +int CSequencer::PushCommand(CBlock *command, int flag) { + // Make sure everything is ok + assert(m_curSequence); + if (m_curSequence == NULL) return SEQ_FAILED; - m_curSequence->PushCommand( command, flag ); + m_curSequence->PushCommand(command, flag); m_numCommands++; - - //Invalid flag + + // Invalid flag return SEQ_OK; } @@ -2203,16 +2009,15 @@ Pops a command off the current sequence ======================== */ -CBlock *CSequencer::PopCommand( int flag ) -{ - //Make sure everything is ok - assert( m_curSequence ); - if ( m_curSequence == NULL ) +CBlock *CSequencer::PopCommand(int flag) { + // Make sure everything is ok + assert(m_curSequence); + if (m_curSequence == NULL) return NULL; - CBlock *block = m_curSequence->PopCommand( flag ); + CBlock *block = m_curSequence->PopCommand(flag); - if ( block != NULL ) + if (block != NULL) m_numCommands--; return block; @@ -2224,70 +2029,59 @@ RemoveSequence ------------------------- */ -//NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) +// NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) -int CSequencer::RemoveSequence( CSequence *sequence ) -{ +int CSequencer::RemoveSequence(CSequence *sequence) { CSequence *temp; int numChildren = sequence->GetNumChildren(); - //Add all the children - for ( int i = 0; i < numChildren; i++ ) - { - temp = sequence->GetChild( i ); + // Add all the children + for (int i = 0; i < numChildren; i++) { + temp = sequence->GetChild(i); - //TODO: Emit warning - assert( temp ); - if ( temp == NULL ) - { - m_ie->I_DPrintf( WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n" ); + // TODO: Emit warning + assert(temp); + if (temp == NULL) { + m_ie->I_DPrintf(WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n"); continue; } - //Remove the references to this sequence - temp->SetParent( NULL ); - temp->SetReturn( NULL ); - + // Remove the references to this sequence + temp->SetParent(NULL); + temp->SetReturn(NULL); } - + return SEQ_OK; } -int CSequencer::DestroySequence( CSequence *sequence ) -{ - m_sequenceMap.erase( sequence->GetID() ); - m_sequences.remove( sequence ); +int CSequencer::DestroySequence(CSequence *sequence) { + m_sequenceMap.erase(sequence->GetID()); + m_sequences.remove(sequence); - taskSequence_m::iterator tsi; - for ( tsi = m_taskSequences.begin(); tsi != m_taskSequences.end(); ) - { - if((*tsi).second == sequence) - { + taskSequence_m::iterator tsi; + for (tsi = m_taskSequences.begin(); tsi != m_taskSequences.end();) { + if ((*tsi).second == sequence) { m_taskSequences.erase(tsi++); - } - else - { + } else { ++tsi; } } - CSequence* parent = sequence->GetParent(); - if ( parent ) - { - parent->RemoveChild( sequence ); + CSequence *parent = sequence->GetParent(); + if (parent) { + parent->RemoveChild(sequence); parent = NULL; } int curChild = sequence->GetNumChildren(); - while(curChild) - { + while (curChild) { curChild--; - DestroySequence(sequence->GetChild( curChild )); + DestroySequence(sequence->GetChild(curChild)); } - m_owner->DeleteSequence( sequence ); - + m_owner->DeleteSequence(sequence); + return SEQ_OK; } @@ -2297,23 +2091,21 @@ ReturnSequence ------------------------- */ -inline CSequence *CSequencer::ReturnSequence( CSequence *sequence ) -{ - while ( sequence->GetReturn() ) - { - assert(sequence != sequence->GetReturn() ); - if ( sequence == sequence->GetReturn() ) +inline CSequence *CSequencer::ReturnSequence(CSequence *sequence) { + while (sequence->GetReturn()) { + assert(sequence != sequence->GetReturn()); + if (sequence == sequence->GetReturn()) return NULL; sequence = sequence->GetReturn(); - if ( sequence->GetNumCommands() > 0 ) + if (sequence->GetNumCommands() > 0) return sequence; } return NULL; } -//Save / Load +// Save / Load /* ------------------------- @@ -2321,82 +2113,61 @@ Save ------------------------- */ -int CSequencer::Save( void ) -{ - sequence_l::iterator si; - taskSequence_m::iterator ti; - int numSequences = 0, id, numTasks; +int CSequencer::Save(void) { + sequence_l::iterator si; + taskSequence_m::iterator ti; + int numSequences = 0, id, numTasks; - //Get the number of sequences to save out + // Get the number of sequences to save out numSequences = m_sequences.size(); - ojk::SavedGameHelper saved_game( - m_ie->saved_game); + ojk::SavedGameHelper saved_game(m_ie->saved_game); - //Save out the owner sequence - saved_game.write_chunk( - INT_ID('S', 'Q', 'R', 'E'), - m_ownerID); + // Save out the owner sequence + saved_game.write_chunk(INT_ID('S', 'Q', 'R', 'E'), m_ownerID); - //Write out the number of sequences we need to read - saved_game.write_chunk( - INT_ID('S', 'Q', 'R', '#'), - numSequences); + // Write out the number of sequences we need to read + saved_game.write_chunk(INT_ID('S', 'Q', 'R', '#'), numSequences); - //Second pass, save out all sequences, in order - STL_ITERATE( si, m_sequences ) - { + // Second pass, save out all sequences, in order + STL_ITERATE(si, m_sequences) { id = (*si)->GetID(); - saved_game.write_chunk( - INT_ID('S', 'Q', 'R', 'I'), - id); + saved_game.write_chunk(INT_ID('S', 'Q', 'R', 'I'), id); } - //Save out the taskManager + // Save out the taskManager m_taskManager->Save(); - //Save out the task sequences mapping the name to the GUIDs + // Save out the task sequences mapping the name to the GUIDs numTasks = m_taskSequences.size(); - saved_game.write_chunk( - INT_ID('S', 'Q', 'T', '#'), - numTasks); + saved_game.write_chunk(INT_ID('S', 'Q', 'T', '#'), numTasks); - STL_ITERATE( ti, m_taskSequences ) - { - //Save the task group's ID + STL_ITERATE(ti, m_taskSequences) { + // Save the task group's ID id = ((*ti).first)->GetGUID(); - saved_game.write_chunk( - INT_ID('S', 'T', 'I', 'D'), - id); + saved_game.write_chunk(INT_ID('S', 'T', 'I', 'D'), id); - //Save the sequence's ID + // Save the sequence's ID id = ((*ti).second)->GetID(); - saved_game.write_chunk( - INT_ID('S', 'S', 'I', 'D'), - id); + saved_game.write_chunk(INT_ID('S', 'S', 'I', 'D'), id); } - int curGroupID = ( m_curGroup == NULL ) ? -1 : m_curGroup->GetGUID(); + int curGroupID = (m_curGroup == NULL) ? -1 : m_curGroup->GetGUID(); - saved_game.write_chunk( - INT_ID('S', 'Q', 'C', 'T'), - curGroupID); + saved_game.write_chunk(INT_ID('S', 'Q', 'C', 'T'), curGroupID); - //Output the number of commands - saved_game.write_chunk( - INT_ID('S', 'Q', '#', 'C'), - m_numCommands); //FIXME: This can be reconstructed + // Output the number of commands + saved_game.write_chunk(INT_ID('S', 'Q', '#', 'C'), + m_numCommands); // FIXME: This can be reconstructed - //Output the ID of the current sequence - id = ( m_curSequence != NULL ) ? m_curSequence->GetID() : -1; + // Output the ID of the current sequence + id = (m_curSequence != NULL) ? m_curSequence->GetID() : -1; - saved_game.write_chunk( - INT_ID('S', 'Q', 'C', 'S'), - id); + saved_game.write_chunk(INT_ID('S', 'Q', 'C', 'S'), id); return true; } @@ -2407,101 +2178,79 @@ Load ------------------------- */ -int CSequencer::Load( void ) -{ +int CSequencer::Load(void) { int i; - ojk::SavedGameHelper saved_game( - m_ie->saved_game); + ojk::SavedGameHelper saved_game(m_ie->saved_game); - //Get the owner of this sequencer - saved_game.read_chunk( - INT_ID('S', 'Q', 'R', 'E'), - m_ownerID); + // Get the owner of this sequencer + saved_game.read_chunk(INT_ID('S', 'Q', 'R', 'E'), m_ownerID); - //Link the entity back to the sequencer - m_ie->I_LinkEntity( m_ownerID, this, m_taskManager ); + // Link the entity back to the sequencer + m_ie->I_LinkEntity(m_ownerID, this, m_taskManager); - CTaskGroup *taskGroup; - CSequence *seq; - int numSequences = 0, seqID = 0, taskID = 0, numTasks = 0; + CTaskGroup *taskGroup; + CSequence *seq; + int numSequences = 0, seqID = 0, taskID = 0, numTasks = 0; - //Get the number of sequences to read - saved_game.read_chunk( - INT_ID('S', 'Q', 'R', '#'), - numSequences); + // Get the number of sequences to read + saved_game.read_chunk(INT_ID('S', 'Q', 'R', '#'), numSequences); - //Read in all the sequences - for ( i = 0; i < numSequences; i++ ) - { - saved_game.read_chunk( - INT_ID('S', 'Q', 'R', 'I'), - seqID); + // Read in all the sequences + for (i = 0; i < numSequences; i++) { + saved_game.read_chunk(INT_ID('S', 'Q', 'R', 'I'), seqID); - seq = m_owner->GetSequence( seqID ); + seq = m_owner->GetSequence(seqID); - assert( seq ); + assert(seq); - STL_INSERT( m_sequences, seq ); - m_sequenceMap[ seqID ] = seq; + STL_INSERT(m_sequences, seq); + m_sequenceMap[seqID] = seq; } - //Setup the task manager - m_taskManager->Init( this ); + // Setup the task manager + m_taskManager->Init(this); - //Load the task manager + // Load the task manager m_taskManager->Load(); - //Get the number of tasks in the map - saved_game.read_chunk( - INT_ID('S', 'Q', 'T', '#'), - numTasks); + // Get the number of tasks in the map + saved_game.read_chunk(INT_ID('S', 'Q', 'T', '#'), numTasks); - //Read in, and reassociate the tasks to the sequences - for ( i = 0; i < numTasks; i++ ) - { - //Read in the task's ID - saved_game.read_chunk( - INT_ID('S', 'T', 'I', 'D'), - taskID); - - //Read in the sequence's ID - saved_game.read_chunk( - INT_ID('S', 'S', 'I', 'D'), - seqID); + // Read in, and reassociate the tasks to the sequences + for (i = 0; i < numTasks; i++) { + // Read in the task's ID + saved_game.read_chunk(INT_ID('S', 'T', 'I', 'D'), taskID); + + // Read in the sequence's ID + saved_game.read_chunk(INT_ID('S', 'S', 'I', 'D'), seqID); - taskGroup = m_taskManager->GetTaskGroup( taskID ); + taskGroup = m_taskManager->GetTaskGroup(taskID); - assert( taskGroup ); + assert(taskGroup); - seq = m_owner->GetSequence( seqID ); + seq = m_owner->GetSequence(seqID); - assert( seq ); + assert(seq); - //Associate the values - m_taskSequences[ taskGroup ] = seq; + // Associate the values + m_taskSequences[taskGroup] = seq; } - int curGroupID = 0; + int curGroupID = 0; - //Get the current task group - saved_game.read_chunk( - INT_ID('S', 'Q', 'C', 'T'), - curGroupID); + // Get the current task group + saved_game.read_chunk(INT_ID('S', 'Q', 'C', 'T'), curGroupID); - m_curGroup = ( curGroupID == -1 ) ? NULL : m_taskManager->GetTaskGroup( curGroupID ); + m_curGroup = (curGroupID == -1) ? NULL : m_taskManager->GetTaskGroup(curGroupID); - //Get the number of commands - saved_game.read_chunk( - INT_ID('S', 'Q', '#', 'C'), - m_numCommands); + // Get the number of commands + saved_game.read_chunk(INT_ID('S', 'Q', '#', 'C'), m_numCommands); - //Get the current sequence - saved_game.read_chunk( - INT_ID('S', 'Q', 'C', 'S'), - seqID); + // Get the current sequence + saved_game.read_chunk(INT_ID('S', 'Q', 'C', 'S'), seqID); - m_curSequence = ( seqID != -1 ) ? m_owner->GetSequence( seqID ) : NULL; + m_curSequence = (seqID != -1) ? m_owner->GetSequence(seqID) : NULL; return true; } diff --git a/codeJK2/icarus/TaskManager.cpp b/codeJK2/icarus/TaskManager.cpp index feb0014b33..4d441290e4 100644 --- a/codeJK2/icarus/TaskManager.cpp +++ b/codeJK2/icarus/TaskManager.cpp @@ -20,20 +20,20 @@ along with this program; if not, see . =========================================================================== */ -// Task Manager +// Task Manager // // -- jweier - // this include must remain at the top of every Icarus CPP file #include "icarus.h" #include "g_local.h" - #include #include "../code/qcommon/ojk_saved_game_helper.h" -#define ICARUS_VALIDATE(a) if ( a == false ) return TASK_FAILED; +#define ICARUS_VALIDATE(a) \ + if (a == false) \ + return TASK_FAILED; /* ================================================= @@ -43,26 +43,21 @@ CTask ================================================= */ -CTask::CTask( void ) -{ -} +CTask::CTask(void) {} -CTask::~CTask( void ) -{ -} +CTask::~CTask(void) {} -CTask *CTask::Create( int GUID, CBlock *block ) -{ +CTask *CTask::Create(int GUID, CBlock *block) { CTask *task = new CTask; - //TODO: Emit warning - assert( task ); - if ( task == NULL ) + // TODO: Emit warning + assert(task); + if (task == NULL) return NULL; - task->SetTimeStamp( 0 ); - task->SetBlock( block ); - task->SetGUID( GUID ); + task->SetTimeStamp(0); + task->SetBlock(block); + task->SetGUID(GUID); return task; } @@ -73,9 +68,8 @@ Free ------------------------- */ -void CTask::Free( void ) -{ - //NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up +void CTask::Free(void) { + // NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up delete this; } @@ -87,18 +81,14 @@ CTaskGroup ================================================= */ -CTaskGroup::CTaskGroup( void ) -{ +CTaskGroup::CTaskGroup(void) { Init(); - m_GUID = 0; - m_parent = NULL; + m_GUID = 0; + m_parent = NULL; } -CTaskGroup::~CTaskGroup( void ) -{ - m_completedTasks.clear(); -} +CTaskGroup::~CTaskGroup(void) { m_completedTasks.clear(); } /* ------------------------- @@ -106,10 +96,7 @@ SetGUID ------------------------- */ -void CTaskGroup::SetGUID( int GUID ) -{ - m_GUID = GUID; -} +void CTaskGroup::SetGUID(int GUID) { m_GUID = GUID; } /* ------------------------- @@ -117,12 +104,11 @@ Init ------------------------- */ -void CTaskGroup::Init( void ) -{ +void CTaskGroup::Init(void) { m_completedTasks.clear(); - m_numCompleted = 0; - m_parent = NULL; + m_numCompleted = 0; + m_parent = NULL; } /* @@ -131,10 +117,9 @@ Add ------------------------- */ -int CTaskGroup::Add( CTask *task ) -{ - m_completedTasks[ task->GetGUID() ] = false; - return TASK_OK; +int CTaskGroup::Add(CTask *task) { + m_completedTasks[task->GetGUID()] = false; + return TASK_OK; } /* @@ -143,11 +128,9 @@ MarkTaskComplete ------------------------- */ -bool CTaskGroup::MarkTaskComplete( int id ) -{ - if ( (m_completedTasks.find( id )) != m_completedTasks.end() ) - { - m_completedTasks[ id ] = true; +bool CTaskGroup::MarkTaskComplete(int id) { + if ((m_completedTasks.find(id)) != m_completedTasks.end()) { + m_completedTasks[id] = true; m_numCompleted++; return true; @@ -164,13 +147,9 @@ CTaskManager ================================================= */ -CTaskManager::CTaskManager( void ) -{ -} +CTaskManager::CTaskManager(void) {} -CTaskManager::~CTaskManager( void ) -{ -} +CTaskManager::~CTaskManager(void) {} /* ------------------------- @@ -178,10 +157,7 @@ Create ------------------------- */ -CTaskManager *CTaskManager::Create( void ) -{ - return new CTaskManager; -} +CTaskManager *CTaskManager::Create(void) { return new CTaskManager; } /* ------------------------- @@ -189,18 +165,17 @@ Init ------------------------- */ -int CTaskManager::Init( CSequencer *owner ) -{ - //TODO: Emit warning - if ( owner == NULL ) +int CTaskManager::Init(CSequencer *owner) { + // TODO: Emit warning + if (owner == NULL) return TASK_FAILED; m_tasks.clear(); - m_owner = owner; - m_ownerID = owner->GetOwnerID(); - m_curGroup = NULL; - m_GUID = 0; - m_resident = false; + m_owner = owner; + m_ownerID = owner->GetOwnerID(); + m_curGroup = NULL; + m_GUID = 0; + m_resident = false; return TASK_OK; } @@ -211,25 +186,22 @@ Free ------------------------- */ -int CTaskManager::Free( void ) -{ - taskGroup_v::iterator gi; - tasks_l::iterator ti; +int CTaskManager::Free(void) { + taskGroup_v::iterator gi; + tasks_l::iterator ti; - //Clear out all pending tasks - for ( ti = m_tasks.begin(); ti != m_tasks.end(); ++ti ) - { + // Clear out all pending tasks + for (ti = m_tasks.begin(); ti != m_tasks.end(); ++ti) { (*ti)->Free(); } m_tasks.clear(); - //Clear out all taskGroups - for ( gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi ) - { + // Clear out all taskGroups + for (gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi) { delete (*gi); } - + m_taskGroups.clear(); m_taskGroupNameMap.clear(); m_taskGroupIDMap.clear(); @@ -243,10 +215,9 @@ Flush ------------------------- */ -int CTaskManager::Flush( void ) -{ - //FIXME: Rewrite - +int CTaskManager::Flush(void) { + // FIXME: Rewrite + return true; } @@ -256,42 +227,40 @@ AddTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::AddTaskGroup( const char *name ) -{ +CTaskGroup *CTaskManager::AddTaskGroup(const char *name) { CTaskGroup *group; - //Collect any garbage - taskGroupName_m::iterator tgni; - tgni = m_taskGroupNameMap.find( name ); + // Collect any garbage + taskGroupName_m::iterator tgni; + tgni = m_taskGroupNameMap.find(name); - if ( tgni != m_taskGroupNameMap.end() ) - { + if (tgni != m_taskGroupNameMap.end()) { group = (*tgni).second; - - //Clear it and just move on + + // Clear it and just move on group->Init(); - + return group; } - //Allocate a new one - group = new CTaskGroup;; + // Allocate a new one + group = new CTaskGroup; + ; - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate task group \"%s\"\n", name ); + // TODO: Emit warning + assert(group); + if (group == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to allocate task group \"%s\"\n", name); return NULL; } - //Setup the internal information - group->SetGUID( m_GUID++ ); + // Setup the internal information + group->SetGUID(m_GUID++); - //Add it to the list and associate it for retrieval later - m_taskGroups.insert( m_taskGroups.end(), group ); - m_taskGroupNameMap[ name ] = group; - m_taskGroupIDMap[ group->GetGUID() ] = group; + // Add it to the list and associate it for retrieval later + m_taskGroups.insert(m_taskGroups.end(), group); + m_taskGroupNameMap[name] = group; + m_taskGroupIDMap[group->GetGUID()] = group; return group; } @@ -302,30 +271,26 @@ GetTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::GetTaskGroup( const char *name ) -{ - taskGroupName_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(const char *name) { + taskGroupName_m::iterator tgi; - tgi = m_taskGroupNameMap.find( name ); + tgi = m_taskGroupNameMap.find(name); - if ( tgi == m_taskGroupNameMap.end() ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%s\"\n", name ); + if (tgi == m_taskGroupNameMap.end()) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Could not find task group \"%s\"\n", name); return NULL; } return (*tgi).second; } -CTaskGroup *CTaskManager::GetTaskGroup( int id ) -{ - taskGroupID_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(int id) { + taskGroupID_m::iterator tgi; - tgi = m_taskGroupIDMap.find( id ); + tgi = m_taskGroupIDMap.find(id); - if ( tgi == m_taskGroupIDMap.end() ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%d\"\n", id ); + if (tgi == m_taskGroupIDMap.end()) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Could not find task group \"%d\"\n", id); return NULL; } @@ -338,13 +303,11 @@ Update ------------------------- */ -int CTaskManager::Update( void ) -{ - if ( (g_entities[m_ownerID].svFlags&SVF_ICARUS_FREEZE) ) - { +int CTaskManager::Update(void) { + if ((g_entities[m_ownerID].svFlags & SVF_ICARUS_FREEZE)) { return TASK_FAILED; } - m_count = 0; //Needed for runaway init + m_count = 0; // Needed for runaway init m_resident = true; int returnVal = Go(); @@ -360,19 +323,15 @@ IsRunning ------------------------- */ -qboolean CTaskManager::IsRunning( void ) -{ - return (qboolean)!m_tasks.empty(); -} +qboolean CTaskManager::IsRunning(void) { return (qboolean)!m_tasks.empty(); } /* ------------------------- Check ------------------------- */ -inline bool CTaskManager::Check( int targetID, CBlock *block, int memberNum ) -{ - if ( (block->GetMember( memberNum ))->GetID() == targetID ) +inline bool CTaskManager::Check(int targetID, CBlock *block, int memberNum) { + if ((block->GetMember(memberNum))->GetID() == targetID) return true; return false; @@ -384,67 +343,57 @@ GetFloat ------------------------- */ -int CTaskManager::GetFloat( int entID, CBlock *block, int &memberNum, float &value ) -{ - char *name; - int type; +int CTaskManager::GetFloat(int entID, CBlock *block, int &memberNum, float &value) { + char *name; + int type; - //See if this is a get() command replacement - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != TK_FLOAT ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n" ); - return false; + // TODO: Emit warning + if (type != TK_FLOAT) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n"); + return false; } - return (m_owner->GetInterface())->I_GetFloat( entID, type, name, &value ); + return (m_owner->GetInterface())->I_GetFloat(entID, type, name, &value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - value = (m_owner->GetInterface())->I_Random( min, max ); + value = (m_owner->GetInterface())->I_Random(min, max); return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n" ); + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n"); return false; } - CBlockMember *bm = block->GetMember( memberNum ); - - if ( bm->GetID() == TK_INT ) - { - value = (float) (*(int *) block->GetMemberData( memberNum++ )); - } - else if ( bm->GetID() == TK_FLOAT ) - { - value = *(float *) block->GetMemberData( memberNum++ ); - } - else - { + CBlockMember *bm = block->GetMember(memberNum); + + if (bm->GetID() == TK_INT) { + value = (float)(*(int *)block->GetMemberData(memberNum++)); + } else if (bm->GetID() == TK_FLOAT) { + value = *(float *)block->GetMemberData(memberNum++); + } else { assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type FLOAT\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Unexpected value; expected type FLOAT\n"); return false; } @@ -457,82 +406,73 @@ GetVector ------------------------- */ -int CTaskManager::GetVector( int entID, CBlock *block, int &memberNum, vector_t &value ) -{ - char *name; - int type, i; +int CTaskManager::GetVector(int entID, CBlock *block, int &memberNum, vector_t &value) { + char *name; + int type, i; - //See if this is a get() command replacement - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != TK_VECTOR ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n" ); + // TODO: Emit warning + if (type != TK_VECTOR) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n"); } - return (m_owner->GetInterface())->I_GetVector( entID, type, name, value ); + return (m_owner->GetInterface())->I_GetVector(entID, type, name, value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - for ( i = 0; i < 3; i++ ) - { - value[i] = (float) (m_owner->GetInterface())->I_Random( min, max ); //FIXME: Just truncating it for now.. should be fine though + for (i = 0; i < 3; i++) { + value[i] = (float)(m_owner->GetInterface())->I_Random(min, max); // FIXME: Just truncating it for now.. should be fine though } return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { - char *tagName; - float tagLookup; + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { + char *tagName; + float tagLookup; memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup)); - if ( (m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, value ) == false) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if ((m_owner->GetInterface())->I_GetTag(entID, tagName, (int)tagLookup, value) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0); return TASK_FAILED; - } + } return true; } - //Check for a real vector here - type = (int) (*(float *) block->GetMemberData( memberNum )); + // Check for a real vector here + type = (int)(*(float *)block->GetMemberData(memberNum)); - if ( type != TK_VECTOR ) - { -// (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); + if (type != TK_VECTOR) { + // (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); return false; } memberNum++; - for ( i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, value[i] ) == false ) + for (i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, value[i]) == false) return false; } @@ -545,165 +485,146 @@ Get ------------------------- */ -int CTaskManager::Get( int entID, CBlock *block, int &memberNum, char **value ) -{ - static char tempBuffer[128]; //FIXME: EEEK! - vector_t vector; - char *name, *tagName; - float tagLookup; - int type; +int CTaskManager::Get(int entID, CBlock *block, int &memberNum, char **value) { + static char tempBuffer[128]; // FIXME: EEEK! + vector_t vector; + char *name, *tagName; + float tagLookup; + int type; - //Look for a get() inline call - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // Look for a get() inline call + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Format the return properly - //FIXME: This is probably doing double formatting in certain cases... - //FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! - switch ( type ) - { + // Format the return properly + // FIXME: This is probably doing double formatting in certain cases... + // FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! + switch (type) { case TK_STRING: - if ( ( m_owner->GetInterface())->I_GetString( entID, type, name, value ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); + if ((m_owner->GetInterface())->I_GetString(entID, type, name, value) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); return false; } - + return true; break; - case TK_FLOAT: - { - float temp; - - if ( (m_owner->GetInterface())->I_GetFloat( entID, type, name, &temp ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case TK_FLOAT: { + float temp; - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f", temp ); - *value = (char *) tempBuffer; + if ((m_owner->GetInterface())->I_GetFloat(entID, type, name, &temp) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } - + + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", temp); + *value = (char *)tempBuffer; + } + return true; break; - case TK_VECTOR: - { - vector_t vval; - - if ( (m_owner->GetInterface())->I_GetVector( entID, type, name, vval ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case TK_VECTOR: { + vector_t vval; - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + if ((m_owner->GetInterface())->I_GetVector(entID, type, name, vval) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } - + + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; + } + return true; break; default: - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return an unknown type!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return an unknown type!\n"); return false; break; } } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max, ret; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max, ret; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - ret = ( m_owner->GetInterface())->I_Random( min, max ); + ret = (m_owner->GetInterface())->I_Random(min, max); - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f", ret ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", ret); + *value = (char *)tempBuffer; return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup)); - if ( ( m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, vector ) == false) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if ((m_owner->GetInterface())->I_GetTag(entID, tagName, (int)tagLookup, vector) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0 && "Unable to find tag"); return false; } - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f %f %f", vector[0], vector[1], vector[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vector[0], vector[1], vector[2]); + *value = (char *)tempBuffer; return true; } - //Get an actual piece of data + // Get an actual piece of data - CBlockMember *bm = block->GetMember( memberNum ); + CBlockMember *bm = block->GetMember(memberNum); - if ( bm->GetID() == TK_INT ) - { - float fval = (float) (*(int *) block->GetMemberData( memberNum++ )); - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f", fval ); - *value = (char *) tempBuffer; + if (bm->GetID() == TK_INT) { + float fval = (float)(*(int *)block->GetMemberData(memberNum++)); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == TK_FLOAT ) - { - float fval = *(float *) block->GetMemberData( memberNum++ ); - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f", fval ); - *value = (char *) tempBuffer; + } else if (bm->GetID() == TK_FLOAT) { + float fval = *(float *)block->GetMemberData(memberNum++); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == TK_VECTOR ) - { - vector_t vval; + } else if (bm->GetID() == TK_VECTOR) { + vector_t vval; memberNum++; - for ( int i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, vval[i] ) == false ) + for (int i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, vval[i]) == false) return false; } - Com_sprintf( tempBuffer, sizeof( tempBuffer ), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; return true; - } - else if ( ( bm->GetID() == TK_STRING ) || ( bm->GetID() == TK_IDENTIFIER ) ) - { - *value = (char *) block->GetMemberData( memberNum++ ); + } else if ((bm->GetID() == TK_STRING) || (bm->GetID() == TK_IDENTIFIER)) { + *value = (char *)block->GetMemberData(memberNum++); return true; } - - //TODO: Emit warning - assert( 0 ); - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type STRING\n" ); + + // TODO: Emit warning + assert(0); + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Unexpected value; expected type STRING\n"); return false; } @@ -714,138 +635,131 @@ Go ------------------------- */ -int CTaskManager::Go( void ) -{ - CTask *task = NULL; - bool completed = false; +int CTaskManager::Go(void) { + CTask *task = NULL; + bool completed = false; - //Check for run away scripts - if ( m_count++ > RUNAWAY_LIMIT ) - { + // Check for run away scripts + if (m_count++ > RUNAWAY_LIMIT) { assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Runaway loop detected!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Runaway loop detected!\n"); return TASK_FAILED; } - //If there are tasks to complete, do so - if ( m_tasks.empty() == false ) - { - //Get the next task - task = PopTask( POP_BACK ); + // If there are tasks to complete, do so + if (m_tasks.empty() == false) { + // Get the next task + task = PopTask(POP_BACK); - assert( task ); - if ( task == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Invalid task found in Go()!\n" ); + assert(task); + if (task == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Invalid task found in Go()!\n"); return TASK_FAILED; } - - //If this hasn't been stamped, do so - if ( task->GetTimeStamp() == 0 ) - task->SetTimeStamp( ( m_owner->GetInterface())->I_GetTime() ); - - //Switch and call the proper function - switch( task->GetID() ) - { + + // If this hasn't been stamped, do so + if (task->GetTimeStamp() == 0) + task->SetTimeStamp((m_owner->GetInterface())->I_GetTime()); + + // Switch and call the proper function + switch (task->GetID()) { case ID_WAIT: - - Wait( task, completed ); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, PUSH_BACK ); + Wait(task, completed); + + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; case ID_WAITSIGNAL: - - WaitSignal( task, completed ); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, PUSH_BACK ); + WaitSignal(task, completed); + + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; - - case ID_PRINT: //print( STRING ) - Print( task ); + + case ID_PRINT: // print( STRING ) + Print(task); break; - case ID_SOUND: //sound( name ) - Sound( task ); + case ID_SOUND: // sound( name ) + Sound(task); break; - case ID_MOVE: //move ( ORIGIN, ANGLES, DURATION ) - Move( task ); + case ID_MOVE: // move ( ORIGIN, ANGLES, DURATION ) + Move(task); break; - case ID_ROTATE: //rotate( ANGLES, DURATION ) - Rotate( task ); + case ID_ROTATE: // rotate( ANGLES, DURATION ) + Rotate(task); break; - case ID_KILL: //kill( NAME ) - Kill( task ); + case ID_KILL: // kill( NAME ) + Kill(task); break; - case ID_REMOVE: //remove( NAME ) - Remove( task ); + case ID_REMOVE: // remove( NAME ) + Remove(task); break; - case ID_CAMERA: //camera( ? ) - Camera( task ); + case ID_CAMERA: // camera( ? ) + Camera(task); break; - case ID_SET: //set( NAME, ? ) - Set( task ); + case ID_SET: // set( NAME, ? ) + Set(task); break; - case ID_USE: //use( NAME ) - Use( task ); + case ID_USE: // use( NAME ) + Use(task); break; - case ID_DECLARE://declare( TYPE, NAME ) - DeclareVariable( task ); + case ID_DECLARE: // declare( TYPE, NAME ) + DeclareVariable(task); break; - case ID_FREE: //free( NAME ) - FreeVariable( task ); + case ID_FREE: // free( NAME ) + FreeVariable(task); break; - case ID_SIGNAL: //signal( NAME ) - Signal( task ); + case ID_SIGNAL: // signal( NAME ) + Signal(task); break; - case ID_PLAY: //play ( NAME ) - Play( task ); + case ID_PLAY: // play ( NAME ) + Play(task); break; default: assert(0); task->Free(); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Found unknown task type!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Found unknown task type!\n"); return TASK_FAILED; break; } - //Pump the sequencer for another task - CallbackCommand( task, TASK_RETURN_COMPLETE ); + // Pump the sequencer for another task + CallbackCommand(task, TASK_RETURN_COMPLETE); task->Free(); } - - //FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't + + // FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't // execute too many commands in one cycle. This may, however, cause timing errors to surface. - + return TASK_OK; } @@ -855,25 +769,22 @@ SetCommand ------------------------- */ -int CTaskManager::SetCommand( CBlock *command, int type ) -{ - CTask *task = CTask::Create( m_GUID++, command ); +int CTaskManager::SetCommand(CBlock *command, int type) { + CTask *task = CTask::Create(m_GUID++, command); - //If this is part of a task group, add it in - if ( m_curGroup ) - { - m_curGroup->Add( task ); + // If this is part of a task group, add it in + if (m_curGroup) { + m_curGroup->Add(task); } - //TODO: Emit warning - assert( task ); - if ( task == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate new task!\n" ); + // TODO: Emit warning + assert(task); + if (task == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to allocate new task!\n"); return TASK_FAILED; } - PushTask( task, type ); + PushTask(task, type); return TASK_OK; } @@ -884,35 +795,30 @@ MarkTask ------------------------- */ -int CTaskManager::MarkTask( int id, int operation ) -{ - CTaskGroup *group = GetTaskGroup( id ); +int CTaskManager::MarkTask(int id, int operation) { + CTaskGroup *group = GetTaskGroup(id); - assert( group ); + assert(group); - if ( group == NULL ) + if (group == NULL) return TASK_FAILED; - if ( operation == TASK_START ) - { - //Reset all the completion information + if (operation == TASK_START) { + // Reset all the completion information group->Init(); - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - } - else if ( operation == TASK_END ) - { - assert( m_curGroup ); - if ( m_curGroup == NULL ) + } else if (operation == TASK_END) { + assert(m_curGroup); + if (m_curGroup == NULL) return TASK_FAILED; m_curGroup = m_curGroup->GetParent(); } #ifdef _DEBUG - else - { + else { assert(0); } #endif @@ -926,15 +832,13 @@ Completed ------------------------- */ -int CTaskManager::Completed( int id ) -{ - taskGroup_v::iterator tgi; +int CTaskManager::Completed(int id) { + taskGroup_v::iterator tgi; - //Mark the task as completed - for ( tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi ) - { - //If this returns true, then the task was marked properly - if ( (*tgi)->MarkTaskComplete( id ) ) + // Mark the task as completed + for (tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi) { + // If this returns true, then the task was marked properly + if ((*tgi)->MarkTaskComplete(id)) break; } @@ -947,14 +851,13 @@ CallbackCommand ------------------------- */ -int CTaskManager::CallbackCommand( CTask *task, int returnCode ) -{ - if ( m_owner->Callback( this, task->GetBlock(), returnCode ) == SEQ_OK ) - return Go( ); +int CTaskManager::CallbackCommand(CTask *task, int returnCode) { + if (m_owner->Callback(this, task->GetBlock(), returnCode) == SEQ_OK) + return Go(); assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Command callback failure!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Command callback failure!\n"); return TASK_FAILED; } @@ -964,20 +867,18 @@ RecallTask ------------------------- */ -CBlock *CTaskManager::RecallTask( void ) -{ - CTask *task; +CBlock *CTaskManager::RecallTask(void) { + CTask *task; - task = PopTask( POP_BACK ); + task = PopTask(POP_BACK); - if ( task ) - { - // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) - CBlock* retBlock = task->GetBlock(); + if (task) { + // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; - // return task->GetBlock(); + // return task->GetBlock(); } return NULL; @@ -989,12 +890,10 @@ PushTask ------------------------- */ -int CTaskManager::PushTask( CTask *task, int flag ) -{ - assert( (flag == PUSH_FRONT) || (flag == PUSH_BACK) ); +int CTaskManager::PushTask(CTask *task, int flag) { + assert((flag == PUSH_FRONT) || (flag == PUSH_BACK)); - switch ( flag ) - { + switch (flag) { case PUSH_FRONT: m_tasks.insert(m_tasks.begin(), task); @@ -1008,7 +907,7 @@ int CTaskManager::PushTask( CTask *task, int flag ) break; } - //Invalid flag + // Invalid flag return SEQ_FAILED; } @@ -1018,33 +917,31 @@ PopTask ------------------------- */ -CTask *CTaskManager::PopTask( int flag ) -{ - CTask *task; +CTask *CTaskManager::PopTask(int flag) { + CTask *task; - assert( (flag == POP_FRONT) || (flag == POP_BACK) ); + assert((flag == POP_FRONT) || (flag == POP_BACK)); - if ( m_tasks.empty() ) + if (m_tasks.empty()) return NULL; - switch ( flag ) - { + switch (flag) { case POP_FRONT: task = m_tasks.front(); m_tasks.pop_front(); - + return task; break; case POP_BACK: task = m_tasks.back(); m_tasks.pop_back(); - + return task; break; } - //Invalid flag + // Invalid flag return NULL; } @@ -1054,18 +951,17 @@ GetCurrentTask ------------------------- */ -CBlock *CTaskManager::GetCurrentTask( void ) -{ - CTask *task = PopTask( POP_BACK ); +CBlock *CTaskManager::GetCurrentTask(void) { + CTask *task = PopTask(POP_BACK); - if ( task == NULL ) + if (task == NULL) return NULL; -// fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) - CBlock* retBlock = task->GetBlock(); + // fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; -// return task->GetBlock(); + // return task->GetBlock(); } /* @@ -1076,77 +972,65 @@ CBlock *CTaskManager::GetCurrentTask( void ) ================================================= */ -int CTaskManager::Wait( CTask *task, bool &completed ) -{ - CBlockMember *bm; - CBlock *block = task->GetBlock(); - char *sVal; - float dwtime; - int memberNum = 0; +int CTaskManager::Wait(CTask *task, bool &completed) { + CBlockMember *bm; + CBlock *block = task->GetBlock(); + char *sVal; + float dwtime; + int memberNum = 0; completed = false; - bm = block->GetMember( 0 ); + bm = block->GetMember(0); - //Check if this is a task completion wait - if ( bm->GetID() == TK_STRING ) - { - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + // Check if this is a task completion wait + if (bm->GetID() == TK_STRING) { + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - CTaskGroup *group = GetTaskGroup( sVal ); + CTaskGroup *group = GetTaskGroup(sVal); - if ( group == NULL ) - { - //TODO: Emit warning + if (group == NULL) { + // TODO: Emit warning completed = false; return TASK_FAILED; } completed = group->Complete(); - } - else //Otherwise it's a time completion wait + } else // Otherwise it's a time completion wait { - if ( Check( ID_RANDOM, block, memberNum ) ) - {//get it random only the first time - float min, max; + if (Check(ID_RANDOM, block, memberNum)) { // get it random only the first time + float min, max; - dwtime = *(float *) block->GetMemberData( memberNum++ ); - if ( dwtime == Q3_INFINITE ) - {//we have not evaluated this random yet - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + dwtime = *(float *)block->GetMemberData(memberNum++); + if (dwtime == Q3_INFINITE) { // we have not evaluated this random yet + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - dwtime = (m_owner->GetInterface())->I_Random( min, max ); + dwtime = (m_owner->GetInterface())->I_Random(min, max); - //store the result in the first member - bm->SetData( &dwtime, sizeof( dwtime ) ); + // store the result in the first member + bm->SetData(&dwtime, sizeof(dwtime)); } + } else { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, dwtime)); } - else - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, dwtime ) ); - } - - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int) dwtime, task->GetTimeStamp() ); + + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int)dwtime, task->GetTimeStamp()); } - if ( (task->GetTimeStamp() + dwtime) < ((m_owner->GetInterface())->I_GetTime()) ) - { + if ((task->GetTimeStamp() + dwtime) < ((m_owner->GetInterface())->I_GetTime())) { completed = true; memberNum = 0; - if ( Check( ID_RANDOM, block, memberNum ) ) - {//set the data back to 0 so it will be re-randomized next time + if (Check(ID_RANDOM, block, memberNum)) { // set the data back to 0 so it will be re-randomized next time dwtime = Q3_INFINITE; - bm->SetData( &dwtime, sizeof( dwtime ) ); + bm->SetData(&dwtime, sizeof(dwtime)); } } } @@ -1160,26 +1044,23 @@ WaitSignal ------------------------- */ -int CTaskManager::WaitSignal( CTask *task, bool &completed ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::WaitSignal(CTask *task, bool &completed) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; completed = false; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - if ( (m_owner->GetOwner())->CheckSignal( sVal ) ) - { + if ((m_owner->GetOwner())->CheckSignal(sVal)) { completed = true; - (m_owner->GetOwner())->ClearSignal( sVal ); + (m_owner->GetOwner())->ClearSignal(sVal); } return TASK_OK; @@ -1191,20 +1072,19 @@ Print ------------------------- */ -int CTaskManager::Print( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Print(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; + + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_CenterPrint(sVal); - (m_owner->GetInterface())->I_CenterPrint( sVal ); + Completed(task->GetGUID()); - Completed( task->GetGUID() ); - return TASK_OK; } @@ -1214,21 +1094,20 @@ Sound ------------------------- */ -int CTaskManager::Sound( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Sound(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + + // Only instantly complete if the user has requested it + if ((m_owner->GetInterface())->I_PlaySound(task->GetGUID(), m_ownerID, sVal2, sVal)) + Completed(task->GetGUID()); - //Only instantly complete if the user has requested it - if( (m_owner->GetInterface())->I_PlaySound( task->GetGUID(), m_ownerID, sVal2, sVal ) ) - Completed( task->GetGUID() ); - return TASK_OK; } @@ -1238,42 +1117,38 @@ Rotate ------------------------- */ -int CTaskManager::Rotate( CTask *task ) -{ - vector_t vector; - CBlock *block = task->GetBlock(); - char *tagName; - float tagLookup, duration; - int memberNum = 0; +int CTaskManager::Rotate(CTask *task) { + vector_t vector; + CBlock *block = task->GetBlock(); + char *tagName; + float tagLookup, duration; + int memberNum = 0; - //Check for a tag reference - if ( Check( ID_TAG, block, memberNum ) ) - { + // Check for a tag reference + if (Check(ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, tagLookup)); - if ( (m_owner->GetInterface())->I_GetTag( m_ownerID, tagName, (int) tagLookup, vector ) == false ) - { - //TODO: Emit warning - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if ((m_owner->GetInterface())->I_GetTag(m_ownerID, tagName, (int)tagLookup, vector) == false) { + // TODO: Emit warning + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0); return TASK_FAILED; } + } else { + // Get a normal vector + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); } - else - { - //Get a normal vector - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - } - //Find the duration - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); + // Find the duration + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); + + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int)duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Angles(task->GetGUID(), m_ownerID, vector, duration); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int) duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Angles( task->GetGUID(), m_ownerID, vector, duration ); - return TASK_OK; } @@ -1283,19 +1158,18 @@ Remove ------------------------- */ -int CTaskManager::Remove( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Remove(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Remove( m_ownerID, sVal ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Remove(m_ownerID, sVal); + + Completed(task->GetGUID()); - Completed( task->GetGUID() ); - return TASK_OK; } @@ -1305,130 +1179,133 @@ Camera ------------------------- */ -int CTaskManager::Camera( CTask *task ) -{ - interface_export_t *ie = ( m_owner->GetInterface() ); - CBlock *block = task->GetBlock(); - vector_t vector, vector2; - float type, fVal, fVal2, fVal3; - char *sVal; - int memberNum = 0; +int CTaskManager::Camera(CTask *task) { + interface_export_t *ie = (m_owner->GetInterface()); + CBlock *block = task->GetBlock(); + vector_t vector, vector2; + float type, fVal, fVal2, fVal3; + char *sVal; + int memberNum = 0; - //Get the camera function type - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, type ) ); + // Get the camera function type + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, type)); - switch ( (int) type ) - { + switch ((int)type) { case TYPE_PAN: - - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], fVal, task->GetTimeStamp() ); - ie->I_CameraPan( vector, vector2, fVal ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], + vector2[2], fVal, task->GetTimeStamp()); + ie->I_CameraPan(vector, vector2, fVal); break; case TYPE_ZOOM: - - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraZoom( fVal, fVal2 ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); + + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraZoom(fVal, fVal2); break; case TYPE_MOVE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp() ); - ie->I_CameraMove( vector, fVal ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp()); + ie->I_CameraMove(vector, fVal); break; case TYPE_ROLL: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraRoll( fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraRoll(fVal, fVal2); break; case TYPE_FOLLOW: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraFollow( (const char *) sVal, fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraFollow((const char *)sVal, fVal, fVal2); break; case TYPE_TRACK: - - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraTrack( (const char *) sVal, fVal, fVal2 ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); + + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraTrack((const char *)sVal, fVal, fVal2); break; case TYPE_DISTANCE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); - - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraDistance( fVal, fVal2 ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); + + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraDistance(fVal, fVal2); break; case TYPE_FADE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); - - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal3 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal3)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp() ); - ie->I_CameraFade( vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3 ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], + vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp()); + ie->I_CameraFade(vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3); break; case TYPE_PATH: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - ie->I_CameraPath( sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + ie->I_CameraPath(sVal); break; case TYPE_ENABLE: - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp()); ie->I_CameraEnable(); break; case TYPE_DISABLE: - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp()); ie->I_CameraDisable(); break; - + case TYPE_SHAKE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraShake( fVal, (int) fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraShake(fVal, (int)fVal2); break; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1439,34 +1316,34 @@ Move ------------------------- */ -int CTaskManager::Move( CTask *task ) -{ - vector_t vector, vector2; - CBlock *block = task->GetBlock(); - float duration; - int memberNum = 0; +int CTaskManager::Move(CTask *task) { + vector_t vector, vector2; + CBlock *block = task->GetBlock(); + float duration; + int memberNum = 0; - //Get the goal position - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); + // Get the goal position + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); - //Check for possible angles field - if ( GetVector( m_ownerID, block, memberNum, vector2 ) == false ) - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); - - - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, NULL, duration ); + // Check for possible angles field + if (GetVector(m_ownerID, block, memberNum, vector2) == false) { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); + + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Pos(task->GetGUID(), m_ownerID, vector, NULL, duration); return TASK_OK; } - //Get the duration and make the call - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); - - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, vector2, duration ); - + // Get the duration and make the call + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); + + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], + duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Pos(task->GetGUID(), m_ownerID, vector, vector2, duration); + return TASK_OK; } @@ -1476,18 +1353,17 @@ Kill ------------------------- */ -int CTaskManager::Kill( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Kill(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Kill( m_ownerID, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Kill(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1498,17 +1374,16 @@ Set ------------------------- */ -int CTaskManager::Set( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Set(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Set( task->GetGUID(), m_ownerID, sVal, sVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Set(task->GetGUID(), m_ownerID, sVal, sVal2); return TASK_OK; } @@ -1519,18 +1394,17 @@ Use ------------------------- */ -int CTaskManager::Use( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Use(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Use( m_ownerID, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Use(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1541,23 +1415,21 @@ DeclareVariable ------------------------- */ -int CTaskManager::DeclareVariable( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; - float fVal; +int CTaskManager::DeclareVariable(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; + float fVal; - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int) fVal, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_DeclareVariable( (int) fVal, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int)fVal, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_DeclareVariable((int)fVal, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1566,21 +1438,19 @@ FreeVariable ------------------------- */ -int CTaskManager::FreeVariable( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::FreeVariable(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_FreeVariable( sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_FreeVariable(sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1589,18 +1459,17 @@ Signal ------------------------- */ -int CTaskManager::Signal( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Signal(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - m_owner->GetOwner()->Signal( (const char *) sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + m_owner->GetOwner()->Signal((const char *)sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1611,17 +1480,16 @@ Play ------------------------- */ -int CTaskManager::Play( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Play(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Play( task->GetGUID(), m_ownerID, (const char *) sVal, (const char *) sVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Play(task->GetGUID(), m_ownerID, (const char *)sVal, (const char *)sVal2); return TASK_OK; } @@ -1632,63 +1500,47 @@ SaveCommand ------------------------- */ -//FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... +// FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... -int CTaskManager::SaveCommand( CBlock *block ) -{ - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; +int CTaskManager::SaveCommand(CBlock *block) { + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - saved_game.write_chunk( - INT_ID('B', 'L', 'I', 'D'), - bID); + saved_game.write_chunk(INT_ID('B', 'L', 'I', 'D'), bID); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - saved_game.write_chunk( - INT_ID('B', 'F', 'L', 'G'), - flags); + saved_game.write_chunk(INT_ID('B', 'F', 'L', 'G'), flags); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - saved_game.write_chunk( - INT_ID('B', 'N', 'U', 'M'), - numMembers); + saved_game.write_chunk(INT_ID('B', 'N', 'U', 'M'), numMembers); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - saved_game.write_chunk( - INT_ID('B', 'M', 'I', 'D'), - bID); - - //Save out the data size + saved_game.write_chunk(INT_ID('B', 'M', 'I', 'D'), bID); + + // Save out the data size size = bm->GetSize(); - saved_game.write_chunk( - INT_ID('B', 'S', 'I', 'Z'), - size); - - //Save out the raw data - const uint8_t* raw_data = static_cast(bm->GetData()); - - saved_game.write_chunk( - INT_ID('B', 'M', 'E', 'M'), - raw_data, - size); + saved_game.write_chunk(INT_ID('B', 'S', 'I', 'Z'), size); + + // Save out the raw data + const uint8_t *raw_data = static_cast(bm->GetData()); + + saved_game.write_chunk(INT_ID('B', 'M', 'E', 'M'), raw_data, size); } return true; @@ -1700,172 +1552,135 @@ Save ------------------------- */ -void CTaskManager::Save( void ) -{ - CTaskGroup *taskGroup; - const char *name; - CBlock *block; - uint32_t timeStamp; - bool completed; - int id, numCommands; - int numWritten; - - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); - - //Save the taskmanager's GUID - saved_game.write_chunk( - INT_ID('T', 'M', 'I', 'D'), - m_GUID); //FIXME: This can be reconstructed - - //Save out the number of tasks that will follow +void CTaskManager::Save(void) { + CTaskGroup *taskGroup; + const char *name; + CBlock *block; + uint32_t timeStamp; + bool completed; + int id, numCommands; + int numWritten; + + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); + + // Save the taskmanager's GUID + saved_game.write_chunk(INT_ID('T', 'M', 'I', 'D'), + m_GUID); // FIXME: This can be reconstructed + + // Save out the number of tasks that will follow int iNumTasks = m_tasks.size(); - saved_game.write_chunk( - INT_ID('T', 'S', 'K', '#'), - iNumTasks); + saved_game.write_chunk(INT_ID('T', 'S', 'K', '#'), iNumTasks); - //Save out all the tasks - tasks_l::iterator ti; - - STL_ITERATE( ti, m_tasks ) - { - //Save the GUID + // Save out all the tasks + tasks_l::iterator ti; + + STL_ITERATE(ti, m_tasks) { + // Save the GUID id = (*ti)->GetGUID(); - saved_game.write_chunk( - INT_ID('T', 'K', 'I', 'D'), - id); + saved_game.write_chunk(INT_ID('T', 'K', 'I', 'D'), id); - //Save the timeStamp (FIXME: Although, this is going to be worthless if time is not consistent...) + // Save the timeStamp (FIXME: Although, this is going to be worthless if time is not consistent...) timeStamp = (*ti)->GetTimeStamp(); - saved_game.write_chunk( - INT_ID('T', 'K', 'T', 'S'), - timeStamp); + saved_game.write_chunk(INT_ID('T', 'K', 'T', 'S'), timeStamp); - //Save out the block + // Save out the block block = (*ti)->GetBlock(); - SaveCommand( block ); + SaveCommand(block); } - //Save out the number of task groups + // Save out the number of task groups int numTaskGroups = m_taskGroups.size(); - saved_game.write_chunk( - INT_ID('T', 'G', '#', 'G'), - numTaskGroups); + saved_game.write_chunk(INT_ID('T', 'G', '#', 'G'), numTaskGroups); - //Save out the IDs of all the task groups + // Save out the IDs of all the task groups numWritten = 0; - taskGroup_v::iterator tgi; - STL_ITERATE( tgi, m_taskGroups ) - { + taskGroup_v::iterator tgi; + STL_ITERATE(tgi, m_taskGroups) { id = (*tgi)->GetGUID(); - saved_game.write_chunk( - INT_ID('T', 'K', 'G', '#'), - id); + saved_game.write_chunk(INT_ID('T', 'K', 'G', '#'), id); numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); - //Save out the task groups + // Save out the task groups numWritten = 0; - STL_ITERATE( tgi, m_taskGroups ) - { - //Save out the parent - id = ( (*tgi)->GetParent() == NULL ) ? -1 : ((*tgi)->GetParent())->GetGUID(); + STL_ITERATE(tgi, m_taskGroups) { + // Save out the parent + id = ((*tgi)->GetParent() == NULL) ? -1 : ((*tgi)->GetParent())->GetGUID(); - saved_game.write_chunk( - INT_ID('T', 'K', 'G', 'P'), - id); + saved_game.write_chunk(INT_ID('T', 'K', 'G', 'P'), id); - //Save out the number of commands + // Save out the number of commands numCommands = (*tgi)->m_completedTasks.size(); - saved_game.write_chunk( - INT_ID('T', 'G', 'N', 'C'), - numCommands); + saved_game.write_chunk(INT_ID('T', 'G', 'N', 'C'), numCommands); + + // Save out the command map + CTaskGroup::taskCallback_m::iterator tci; - //Save out the command map - CTaskGroup::taskCallback_m::iterator tci; - - STL_ITERATE( tci, (*tgi)->m_completedTasks ) - { - //Write out the ID + STL_ITERATE(tci, (*tgi)->m_completedTasks) { + // Write out the ID id = (*tci).first; - saved_game.write_chunk( - INT_ID('G', 'M', 'I', 'D'), - id); + saved_game.write_chunk(INT_ID('G', 'M', 'I', 'D'), id); - //Write out the state of completion + // Write out the state of completion completed = (*tci).second; - saved_game.write_chunk( - INT_ID('G', 'M', 'D', 'N'), - completed); + saved_game.write_chunk(INT_ID('G', 'M', 'D', 'N'), completed); } - //Save out the number of completed commands + // Save out the number of completed commands id = (*tgi)->m_numCompleted; - saved_game.write_chunk( - INT_ID('T', 'G', 'D', 'N'), - id); //FIXME: This can be reconstructed + saved_game.write_chunk(INT_ID('T', 'G', 'D', 'N'), + id); // FIXME: This can be reconstructed numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); - //Only bother if we've got tasks present - if ( m_taskGroups.size() ) - { - //Save out the currently active group - int curGroupID = ( m_curGroup == NULL ) ? -1 : m_curGroup->GetGUID(); + // Only bother if we've got tasks present + if (m_taskGroups.size()) { + // Save out the currently active group + int curGroupID = (m_curGroup == NULL) ? -1 : m_curGroup->GetGUID(); - saved_game.write_chunk( - INT_ID('T', 'G', 'C', 'G'), - curGroupID); + saved_game.write_chunk(INT_ID('T', 'G', 'C', 'G'), curGroupID); } - //Save out the task group name maps - taskGroupName_m::iterator tmi; + // Save out the task group name maps + taskGroupName_m::iterator tmi; numWritten = 0; - STL_ITERATE( tmi, m_taskGroupNameMap ) - { + STL_ITERATE(tmi, m_taskGroupNameMap) { name = ((*tmi).first).c_str(); - - //Make sure this is a valid string - assert( ( name != NULL ) && ( name[0] != '\0' ) ); - int length = strlen( name ) + 1; + // Make sure this is a valid string + assert((name != NULL) && (name[0] != '\0')); + + int length = strlen(name) + 1; - //Save out the string size - saved_game.write_chunk( - INT_ID('T', 'G', 'N', 'L'), - length); + // Save out the string size + saved_game.write_chunk(INT_ID('T', 'G', 'N', 'L'), length); - //Write out the string - saved_game.write_chunk( - INT_ID('T', 'G', 'N', 'S'), - name, - length); + // Write out the string + saved_game.write_chunk(INT_ID('T', 'G', 'N', 'S'), name, length); taskGroup = (*tmi).second; id = taskGroup->GetGUID(); - //Write out the ID - saved_game.write_chunk( - INT_ID('T', 'G', 'N', 'I'), - id); + // Write out the ID + saved_game.write_chunk(INT_ID('T', 'G', 'N', 'I'), id); numWritten++; } - assert (numWritten == numTaskGroups); + assert(numWritten == numTaskGroups); } /* @@ -1874,259 +1689,205 @@ Load ------------------------- */ -void CTaskManager::Load( void ) -{ - unsigned char flags = 0; - CTaskGroup *taskGroup; - CBlock *block; - CTask *task; - uint32_t timeStamp = 0; - bool completed = false; - void *bData; - int id = 0, numTasks = 0, numMembers = 0; - int bID = 0, bSize = 0; - int i; - - ojk::SavedGameHelper saved_game( - m_owner->GetInterface()->saved_game); - - //Get the GUID - saved_game.read_chunk( - INT_ID('T', 'M', 'I', 'D'), - m_GUID); - - //Get the number of tasks to follow - saved_game.read_chunk( - INT_ID('T', 'S', 'K', '#'), - numTasks); - - //Reload all the tasks - for ( i = 0; i < numTasks; i++ ) - { +void CTaskManager::Load(void) { + unsigned char flags = 0; + CTaskGroup *taskGroup; + CBlock *block; + CTask *task; + uint32_t timeStamp = 0; + bool completed = false; + void *bData; + int id = 0, numTasks = 0, numMembers = 0; + int bID = 0, bSize = 0; + int i; + + ojk::SavedGameHelper saved_game(m_owner->GetInterface()->saved_game); + + // Get the GUID + saved_game.read_chunk(INT_ID('T', 'M', 'I', 'D'), m_GUID); + + // Get the number of tasks to follow + saved_game.read_chunk(INT_ID('T', 'S', 'K', '#'), numTasks); + + // Reload all the tasks + for (i = 0; i < numTasks; i++) { task = new CTask; - assert( task ); + assert(task); - //Get the GUID - saved_game.read_chunk( - INT_ID('T', 'K', 'I', 'D'), - id); + // Get the GUID + saved_game.read_chunk(INT_ID('T', 'K', 'I', 'D'), id); - task->SetGUID( id ); + task->SetGUID(id); - //Get the time stamp - saved_game.read_chunk( - INT_ID('T', 'K', 'T', 'S'), - timeStamp); + // Get the time stamp + saved_game.read_chunk(INT_ID('T', 'K', 'T', 'S'), timeStamp); - task->SetTimeStamp( timeStamp ); + task->SetTimeStamp(timeStamp); // // BLOCK LOADING // - //Get the block ID and create a new container - saved_game.read_chunk( - INT_ID('B', 'L', 'I', 'D'), - id); + // Get the block ID and create a new container + saved_game.read_chunk(INT_ID('B', 'L', 'I', 'D'), id); block = new CBlock; - - block->Create( id ); - - //Read the block's flags - saved_game.read_chunk( - INT_ID('B', 'F', 'L', 'G'), - flags); - - block->SetFlags( flags ); - - //Get the number of block members - saved_game.read_chunk( - INT_ID('B', 'N', 'U', 'M'), - numMembers); - - for ( int j = 0; j < numMembers; j++ ) - { - //Get the member ID - saved_game.read_chunk( - INT_ID('B', 'M', 'I', 'D'), - bID); - - //Get the member size - saved_game.read_chunk( - INT_ID('B', 'S', 'I', 'Z'), - bSize); - - //Get the member's data - if ( ( bData = ICARUS_Malloc( bSize ) ) == NULL ) - { - assert( 0 ); + + block->Create(id); + + // Read the block's flags + saved_game.read_chunk(INT_ID('B', 'F', 'L', 'G'), flags); + + block->SetFlags(flags); + + // Get the number of block members + saved_game.read_chunk(INT_ID('B', 'N', 'U', 'M'), numMembers); + + for (int j = 0; j < numMembers; j++) { + // Get the member ID + saved_game.read_chunk(INT_ID('B', 'M', 'I', 'D'), bID); + + // Get the member size + saved_game.read_chunk(INT_ID('B', 'S', 'I', 'Z'), bSize); + + // Get the member's data + if ((bData = ICARUS_Malloc(bSize)) == NULL) { + assert(0); return; } - //Get the actual raw data - saved_game.read_chunk( - INT_ID('B', 'M', 'E', 'M'), - static_cast(bData), - bSize); + // Get the actual raw data + saved_game.read_chunk(INT_ID('B', 'M', 'E', 'M'), static_cast(bData), bSize); - //Write out the correct type - switch ( bID ) - { + // Write out the correct type + switch (bID) { case TK_FLOAT: - block->Write( TK_FLOAT, *(float *) bData ); + block->Write(TK_FLOAT, *(float *)bData); break; case TK_IDENTIFIER: - block->Write( TK_IDENTIFIER, (char *) bData ); + block->Write(TK_IDENTIFIER, (char *)bData); break; case TK_STRING: - block->Write( TK_STRING, (char *) bData ); + block->Write(TK_STRING, (char *)bData); break; case TK_VECTOR: - block->Write( TK_VECTOR, *(vec3_t *) bData ); + block->Write(TK_VECTOR, *(vec3_t *)bData); break; case ID_RANDOM: - block->Write( ID_RANDOM, *(float *) bData );//ID_RANDOM ); + block->Write(ID_RANDOM, *(float *)bData); // ID_RANDOM ); break; case ID_TAG: - block->Write( ID_TAG, (float) ID_TAG ); + block->Write(ID_TAG, (float)ID_TAG); break; case ID_GET: - block->Write( ID_GET, (float) ID_GET ); + block->Write(ID_GET, (float)ID_GET); break; default: - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Invalid Block id %d\n", bID); - assert( 0 ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Invalid Block id %d\n", bID); + assert(0); break; } - - //Get rid of the temp memory - ICARUS_Free( bData ); + + // Get rid of the temp memory + ICARUS_Free(bData); } - - task->SetBlock( block ); - STL_INSERT( m_tasks, task ); + task->SetBlock(block); + + STL_INSERT(m_tasks, task); } - //Load the task groups + // Load the task groups int numTaskGroups = 0; - - saved_game.read_chunk( - INT_ID('T', 'G', '#', 'G'), - numTaskGroups); - if ( numTaskGroups == 0 ) + saved_game.read_chunk(INT_ID('T', 'G', '#', 'G'), numTaskGroups); + + if (numTaskGroups == 0) return; - int *taskIDs = new int[ numTaskGroups ]; + int *taskIDs = new int[numTaskGroups]; - //Get the task group IDs - for ( i = 0; i < numTaskGroups; i++ ) - { - //Creat a new task group + // Get the task group IDs + for (i = 0; i < numTaskGroups; i++) { + // Creat a new task group taskGroup = new CTaskGroup; - assert( taskGroup ); + assert(taskGroup); - //Get this task group's ID - saved_game.read_chunk( - INT_ID('T', 'K', 'G', '#'), - taskIDs[i]); + // Get this task group's ID + saved_game.read_chunk(INT_ID('T', 'K', 'G', '#'), taskIDs[i]); taskGroup->m_GUID = taskIDs[i]; - - m_taskGroupIDMap[ taskIDs[i] ] = taskGroup; - STL_INSERT( m_taskGroups, taskGroup ); + m_taskGroupIDMap[taskIDs[i]] = taskGroup; + + STL_INSERT(m_taskGroups, taskGroup); } - //Recreate and load the task groups - for ( i = 0; i < numTaskGroups; i++ ) - { - taskGroup = GetTaskGroup( taskIDs[i] ); - assert( taskGroup ); - - //Load the parent ID - saved_game.read_chunk( - INT_ID('T', 'K', 'G', 'P'), - id); - - if ( id != -1 ) - taskGroup->m_parent = ( GetTaskGroup( id ) != NULL ) ? GetTaskGroup( id ) : NULL; - - //Get the number of commands in this group - saved_game.read_chunk( - INT_ID('T', 'G', 'N', 'C'), - numMembers); - - //Get each command and its completion state - for ( int j = 0; j < numMembers; j++ ) - { - //Get the ID - saved_game.read_chunk( - INT_ID('G', 'M', 'I', 'D'), - id); - - //Write out the state of completion - saved_game.read_chunk( - INT_ID('G', 'M', 'D', 'N'), - completed); - - //Save it out - taskGroup->m_completedTasks[ id ] = completed; + // Recreate and load the task groups + for (i = 0; i < numTaskGroups; i++) { + taskGroup = GetTaskGroup(taskIDs[i]); + assert(taskGroup); + + // Load the parent ID + saved_game.read_chunk(INT_ID('T', 'K', 'G', 'P'), id); + + if (id != -1) + taskGroup->m_parent = (GetTaskGroup(id) != NULL) ? GetTaskGroup(id) : NULL; + + // Get the number of commands in this group + saved_game.read_chunk(INT_ID('T', 'G', 'N', 'C'), numMembers); + + // Get each command and its completion state + for (int j = 0; j < numMembers; j++) { + // Get the ID + saved_game.read_chunk(INT_ID('G', 'M', 'I', 'D'), id); + + // Write out the state of completion + saved_game.read_chunk(INT_ID('G', 'M', 'D', 'N'), completed); + + // Save it out + taskGroup->m_completedTasks[id] = completed; } - //Get the number of completed tasks - saved_game.read_chunk( - INT_ID('T', 'G', 'D', 'N'), - taskGroup->m_numCompleted); + // Get the number of completed tasks + saved_game.read_chunk(INT_ID('T', 'G', 'D', 'N'), taskGroup->m_numCompleted); } - //Reload the currently active group + // Reload the currently active group int curGroupID; - saved_game.read_chunk( - INT_ID('T', 'G', 'C', 'G'), - curGroupID); + saved_game.read_chunk(INT_ID('T', 'G', 'C', 'G'), curGroupID); - //Reload the map entries - for ( i = 0; i < numTaskGroups; i++ ) - { - char name[1024]; - int length = 0; - - //Get the size of the string - saved_game.read_chunk( - INT_ID('T', 'G', 'N', 'L'), - length); - - //Get the string - saved_game.read_chunk( - INT_ID('T', 'G', 'N', 'S'), - name, - length); - - //Get the id - saved_game.read_chunk( - INT_ID('T', 'G', 'N', 'I'), - id); - - taskGroup = GetTaskGroup( id ); - assert( taskGroup ); - - m_taskGroupNameMap[ name ] = taskGroup; - m_taskGroupIDMap[ taskGroup->GetGUID() ] = taskGroup; + // Reload the map entries + for (i = 0; i < numTaskGroups; i++) { + char name[1024]; + int length = 0; + + // Get the size of the string + saved_game.read_chunk(INT_ID('T', 'G', 'N', 'L'), length); + + // Get the string + saved_game.read_chunk(INT_ID('T', 'G', 'N', 'S'), name, length); + + // Get the id + saved_game.read_chunk(INT_ID('T', 'G', 'N', 'I'), id); + + taskGroup = GetTaskGroup(id); + assert(taskGroup); + + m_taskGroupNameMap[name] = taskGroup; + m_taskGroupIDMap[taskGroup->GetGUID()] = taskGroup; } - m_curGroup = ( curGroupID == -1 ) ? NULL : m_taskGroupIDMap[curGroupID]; + m_curGroup = (curGroupID == -1) ? NULL : m_taskGroupIDMap[curGroupID]; delete[] taskIDs; } diff --git a/codeJK2/icarus/Tokenizer.cpp b/codeJK2/icarus/Tokenizer.cpp index 3324355931..43673cab96 100644 --- a/codeJK2/icarus/Tokenizer.cpp +++ b/codeJK2/icarus/Tokenizer.cpp @@ -1,7 +1,7 @@ // Tokenizer.cpp #ifndef NOT_USING_MODULES // !!! if you are not using modules, read BELOW !!! -#include "module.h" // if you are not using modules, +#include "module.h" // if you are not using modules, // create an empty Module.h in your // project -- use of modules allows // the error handler to be overridden @@ -10,12 +10,11 @@ #include "tokenizer.h" #ifdef WIN32_FILE_IO - #include - #include +#include +#include #endif -enum -{ +enum { DIR_INCLUDE = TK_USERDEF, DIR_IFDEF, DIR_IFNDEF, @@ -25,78 +24,77 @@ enum DIR_UNDEFINE, }; -keywordArray_t CTokenizer::directiveKeywords[] = -{ - "include", DIR_INCLUDE, - "ifdef", DIR_IFDEF, - "ifndef", DIR_IFNDEF, - "endif", DIR_ENDIF, - "else", DIR_ELSE, - "define", DIR_DEFINE, - "undefine", DIR_UNDEFINE, - "", TK_EOF, +keywordArray_t CTokenizer::directiveKeywords[] = { + "include", DIR_INCLUDE, "ifdef", DIR_IFDEF, "ifndef", DIR_IFNDEF, "endif", DIR_ENDIF, + "else", DIR_ELSE, "define", DIR_DEFINE, "undefine", DIR_UNDEFINE, "", TK_EOF, }; -keywordArray_t CTokenizer::errorMessages[] = -{ - "No Error", TKERR_NONE, - "Unknown Error", TKERR_UNKNOWN, - "Buffer creation failed", TKERR_BUFFERCREATE, - "Unrecognized symbol", TKERR_UNRECOGNIZEDSYMBOL, - "Duplicate symbol", TKERR_DUPLICATESYMBOL, - "String length exceeded", TKERR_STRINGLENGTHEXCEEDED, - "Identifier length exceeded", TKERR_IDENTIFIERLENGTHEXCEEDED, - "Expected integer", TKERR_EXPECTED_INTEGER, - "Expected identifier", TKERR_EXPECTED_IDENTIFIER, - "Expected string", TKERR_EXPECTED_STRING, - "Expected char", TKERR_EXPECTED_CHAR, - "Expected float", TKERR_EXPECTED_FLOAT, - "Unexpected token", TKERR_UNEXPECTED_TOKEN, - "Invalid directive", TKERR_INVALID_DIRECTIVE, - "Include file not found", TKERR_INCLUDE_FILE_NOTFOUND, - "Unmatched directive", TKERR_UNMATCHED_DIRECTIVE, - "", TKERR_USERERROR, +keywordArray_t CTokenizer::errorMessages[] = { + "No Error", + TKERR_NONE, + "Unknown Error", + TKERR_UNKNOWN, + "Buffer creation failed", + TKERR_BUFFERCREATE, + "Unrecognized symbol", + TKERR_UNRECOGNIZEDSYMBOL, + "Duplicate symbol", + TKERR_DUPLICATESYMBOL, + "String length exceeded", + TKERR_STRINGLENGTHEXCEEDED, + "Identifier length exceeded", + TKERR_IDENTIFIERLENGTHEXCEEDED, + "Expected integer", + TKERR_EXPECTED_INTEGER, + "Expected identifier", + TKERR_EXPECTED_IDENTIFIER, + "Expected string", + TKERR_EXPECTED_STRING, + "Expected char", + TKERR_EXPECTED_CHAR, + "Expected float", + TKERR_EXPECTED_FLOAT, + "Unexpected token", + TKERR_UNEXPECTED_TOKEN, + "Invalid directive", + TKERR_INVALID_DIRECTIVE, + "Include file not found", + TKERR_INCLUDE_FILE_NOTFOUND, + "Unmatched directive", + TKERR_UNMATCHED_DIRECTIVE, + "", + TKERR_USERERROR, }; // // CSymbol // -CSymbol::CSymbol() -{ -} +CSymbol::CSymbol() {} -CSymbol::~CSymbol() -{ -} +CSymbol::~CSymbol() {} -CSymbol* CSymbol::Create(LPCTSTR symbolName) -{ - CSymbol* retval = new CSymbol(); +CSymbol *CSymbol::Create(LPCTSTR symbolName) { + CSymbol *retval = new CSymbol(); retval->Init(symbolName); return retval; } -LPCTSTR CSymbol::GetName() -{ - if (m_symbolName == NULL) - { +LPCTSTR CSymbol::GetName() { + if (m_symbolName == NULL) { return ""; } return m_symbolName; } -void CSymbol::InitBaseSymbol(LPCTSTR symbolName) -{ - m_symbolName = (char*)malloc(strlen(symbolName) + 1); -// ASSERT(m_symbolName); +void CSymbol::InitBaseSymbol(LPCTSTR symbolName) { + m_symbolName = (char *)malloc(strlen(symbolName) + 1); + // ASSERT(m_symbolName); strcpy(m_symbolName, symbolName); } -void CSymbol::Delete() -{ - if (m_symbolName != NULL) - { +void CSymbol::Delete() { + if (m_symbolName != NULL) { free(m_symbolName); m_symbolName = NULL; } @@ -107,258 +105,174 @@ void CSymbol::Delete() // CDirectiveSymbol // -CDirectiveSymbol::CDirectiveSymbol() -{ -} +CDirectiveSymbol::CDirectiveSymbol() {} -CDirectiveSymbol::~CDirectiveSymbol() -{ -} +CDirectiveSymbol::~CDirectiveSymbol() {} -CDirectiveSymbol* CDirectiveSymbol::Create(LPCTSTR symbolName) -{ - CDirectiveSymbol* retval = new CDirectiveSymbol(); +CDirectiveSymbol *CDirectiveSymbol::Create(LPCTSTR symbolName) { + CDirectiveSymbol *retval = new CDirectiveSymbol(); retval->Init(symbolName); return retval; } -void CDirectiveSymbol::Init(LPCTSTR symbolName) -{ +void CDirectiveSymbol::Init(LPCTSTR symbolName) { CSymbol::InitBaseSymbol(symbolName); m_value = NULL; } -void CDirectiveSymbol::Delete() -{ - if (m_value != NULL) - { +void CDirectiveSymbol::Delete() { + if (m_value != NULL) { free(m_value); m_value = NULL; } CSymbol::Delete(); } -void CDirectiveSymbol::SetValue(LPCTSTR value) -{ - if (m_value != NULL) - { +void CDirectiveSymbol::SetValue(LPCTSTR value) { + if (m_value != NULL) { free(m_value); } - m_value = (char*)malloc(strlen(value) + 1); + m_value = (char *)malloc(strlen(value) + 1); strcpy(m_value, value); } -LPCTSTR CDirectiveSymbol::GetValue() -{ - return m_value; -} +LPCTSTR CDirectiveSymbol::GetValue() { return m_value; } // // CIntSymbol // -CIntSymbol::CIntSymbol() -{ -} +CIntSymbol::CIntSymbol() {} -CIntSymbol* CIntSymbol::Create(LPCTSTR symbolName, int value) -{ - CIntSymbol* retval = new CIntSymbol(); +CIntSymbol *CIntSymbol::Create(LPCTSTR symbolName, int value) { + CIntSymbol *retval = new CIntSymbol(); retval->Init(symbolName, value); return retval; } -void CIntSymbol::Delete() -{ - CSymbol::Delete(); -} +void CIntSymbol::Delete() { CSymbol::Delete(); } -void CIntSymbol::Init(LPCTSTR symbolName, int value) -{ +void CIntSymbol::Init(LPCTSTR symbolName, int value) { CSymbol::InitBaseSymbol(symbolName); m_value = value; } -int CIntSymbol::GetValue() -{ - return m_value; -} +int CIntSymbol::GetValue() { return m_value; } // // CSymbolTable // -CSymbolTable::CSymbolTable() -{ - Init(); -} +CSymbolTable::CSymbolTable() { Init(); } -CSymbolTable::~CSymbolTable() -{ -} +CSymbolTable::~CSymbolTable() {} -CSymbolTable* CSymbolTable::Create() -{ - CSymbolTable* retval = new CSymbolTable(); +CSymbolTable *CSymbolTable::Create() { + CSymbolTable *retval = new CSymbolTable(); retval->Init(); return retval; } -void CSymbolTable::Init() -{ -} +void CSymbolTable::Init() {} -void CSymbolTable::DiscardSymbols() -{ - for (symbolmap_t::iterator isymbol = m_symbols.begin(); isymbol != m_symbols.end(); ++isymbol) - { +void CSymbolTable::DiscardSymbols() { + for (symbolmap_t::iterator isymbol = m_symbols.begin(); isymbol != m_symbols.end(); ++isymbol) { (*isymbol).second->Delete(); } m_symbols.erase(m_symbols.begin(), m_symbols.end()); } -void CSymbolTable::Delete() -{ +void CSymbolTable::Delete() { DiscardSymbols(); delete this; } -bool CSymbolTable::AddSymbol(CSymbol* theSymbol) -{ +bool CSymbolTable::AddSymbol(CSymbol *theSymbol) { LPCTSTR name = theSymbol->GetName(); - + symbolmap_t::iterator iter = m_symbols.find(name); - if (iter != m_symbols.end()) - { + if (iter != m_symbols.end()) { return false; } m_symbols.insert(symbolmap_t::value_type(name, theSymbol)); return true; } -CSymbol* CSymbolTable::FindSymbol(LPCTSTR symbolName) -{ +CSymbol *CSymbolTable::FindSymbol(LPCTSTR symbolName) { symbolmap_t::iterator iter = m_symbols.find(symbolName); - if (iter != m_symbols.end()) - { + if (iter != m_symbols.end()) { return (*iter).second; } return NULL; } -CSymbol* CSymbolTable::ExtractSymbol(LPCTSTR symbolName) -{ +CSymbol *CSymbolTable::ExtractSymbol(LPCTSTR symbolName) { symbolmap_t::iterator iter = m_symbols.find(symbolName); - if (iter != m_symbols.end()) - { - CSymbol* retval = (*iter).second; + if (iter != m_symbols.end()) { + CSymbol *retval = (*iter).second; m_symbols.erase(iter); } return NULL; } -void CSymbolTable::RemoveSymbol(LPCTSTR symbolName) -{ - m_symbols.erase(symbolName); -} +void CSymbolTable::RemoveSymbol(LPCTSTR symbolName) { m_symbols.erase(symbolName); } // // CParseStream // -CParseStream::CParseStream() -{ -} +CParseStream::CParseStream() {} -CParseStream::~CParseStream() -{ -} +CParseStream::~CParseStream() {} -CParseStream* CParseStream::Create() -{ - return NULL; -} +CParseStream *CParseStream::Create() { return NULL; } -void CParseStream::Delete() -{ - delete this; -} +void CParseStream::Delete() { delete this; } -bool CParseStream::InitBaseStream() -{ +bool CParseStream::InitBaseStream() { m_next = NULL; return true; } -bool CParseStream::NextChar(byte& theByte) -{ - return false; -} +bool CParseStream::NextChar(byte &theByte) { return false; } -long CParseStream::GetRemainingSize() -{ - return 0; -} +long CParseStream::GetRemainingSize() { return 0; } -CParseStream* CParseStream::GetNext() -{ - return m_next; -} +CParseStream *CParseStream::GetNext() { return m_next; } -void CParseStream::SetNext(CParseStream* next) -{ - m_next = next; -} +void CParseStream::SetNext(CParseStream *next) { m_next = next; } -int CParseStream::GetCurLine() -{ - return 0; -} +int CParseStream::GetCurLine() { return 0; } -void CParseStream::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseStream::GetCurFilename(char **theBuff) { *theBuff = NULL; } -bool CParseStream::IsThisDefinition(void* theDefinition) -{ - return false; -} +bool CParseStream::IsThisDefinition(void *theDefinition) { return false; } // // CParsePutBack // -CParsePutBack::CParsePutBack() -{ -} +CParsePutBack::CParsePutBack() {} -CParsePutBack::~CParsePutBack() -{ -} +CParsePutBack::~CParsePutBack() {} -CParsePutBack* CParsePutBack::Create(byte theByte, int curLine, LPCTSTR filename) -{ - CParsePutBack* curParsePutBack = new CParsePutBack(); +CParsePutBack *CParsePutBack::Create(byte theByte, int curLine, LPCTSTR filename) { + CParsePutBack *curParsePutBack = new CParsePutBack(); curParsePutBack->Init(theByte, curLine, filename); return curParsePutBack; } -void CParsePutBack::Delete() -{ - if (m_curFile != NULL) - { +void CParsePutBack::Delete() { + if (m_curFile != NULL) { free(m_curFile); m_curFile = NULL; } delete this; } -bool CParsePutBack::NextChar(byte& theByte) -{ - if (m_consumed) - { +bool CParsePutBack::NextChar(byte &theByte) { + if (m_consumed) { return false; } theByte = m_byte; @@ -366,48 +280,35 @@ bool CParsePutBack::NextChar(byte& theByte) return true; } -void CParsePutBack::Init(byte theByte, int curLine, LPCTSTR filename) -{ +void CParsePutBack::Init(byte theByte, int curLine, LPCTSTR filename) { CParseStream::InitBaseStream(); m_consumed = false; m_byte = theByte; m_curLine = curLine; - if (filename != NULL) - { - m_curFile = (char*)malloc(strlen(filename) + 1); + if (filename != NULL) { + m_curFile = (char *)malloc(strlen(filename) + 1); strcpy(m_curFile, filename); - } - else - { + } else { m_curFile = NULL; } } -long CParsePutBack::GetRemainingSize() -{ - if (m_consumed) - { +long CParsePutBack::GetRemainingSize() { + if (m_consumed) { return 0; - } - else - { + } else { return 1; } } -int CParsePutBack::GetCurLine() -{ - return m_curLine; -} +int CParsePutBack::GetCurLine() { return m_curLine; } -void CParsePutBack::GetCurFilename(char** theBuff) -{ - if (m_curFile == NULL) - { +void CParsePutBack::GetCurFilename(char **theBuff) { + if (m_curFile == NULL) { *theBuff = NULL; return; } - *theBuff = (char*)malloc(strlen(m_curFile) + 1); + *theBuff = (char *)malloc(strlen(m_curFile) + 1); strcpy(*theBuff, m_curFile); } @@ -415,20 +316,14 @@ void CParsePutBack::GetCurFilename(char** theBuff) // CParseFile // -CParseFile::CParseFile() -{ -} +CParseFile::CParseFile() {} -CParseFile::~CParseFile() -{ -} +CParseFile::~CParseFile() {} + +CParseFile *CParseFile::Create() { + CParseFile *theParseFile = new CParseFile(); -CParseFile* CParseFile::Create() -{ - CParseFile* theParseFile = new CParseFile(); - - if ( !theParseFile->Init() ) - { + if (!theParseFile->Init()) { delete theParseFile; return NULL; } @@ -436,42 +331,36 @@ CParseFile* CParseFile::Create() return theParseFile; } -CParseFile* CParseFile::Create(LPCTSTR filename, CTokenizer* tokenizer) -{ - CParseFile* theParseFile = new CParseFile(); - - if ( theParseFile->Init(filename, tokenizer) ) +CParseFile *CParseFile::Create(LPCTSTR filename, CTokenizer *tokenizer) { + CParseFile *theParseFile = new CParseFile(); + + if (theParseFile->Init(filename, tokenizer)) return theParseFile; return NULL; } -void CParseFile::Delete() -{ - if (m_buff != NULL) - { +void CParseFile::Delete() { + if (m_buff != NULL) { free(m_buff); m_buff = NULL; } - if (m_ownsFile && (m_fileHandle != NULL)) - { + if (m_ownsFile && (m_fileHandle != NULL)) { #ifdef WIN32_FILE_IO CloseHandle(m_fileHandle); #else - fclose( m_fileHandle ); + fclose(m_fileHandle); #endif m_fileHandle = NULL; } - if (m_fileName != NULL) - { + if (m_fileName != NULL) { free(m_fileName); m_fileName = NULL; } delete this; } -bool CParseFile::Init() -{ +bool CParseFile::Init() { m_fileHandle = NULL; m_buff = NULL; m_ownsFile = false; @@ -481,34 +370,31 @@ bool CParseFile::Init() return CParseStream::InitBaseStream(); } -unsigned int CParseFile::GetFileSize() -{ +unsigned int CParseFile::GetFileSize() { #ifdef WIN32_FILE_IO unsigned int dwCur = SetFilePointer(m_fileHandle, 0L, NULL, FILE_CURRENT); unsigned int dwLen = SetFilePointer(m_fileHandle, 0, NULL, FILE_END); SetFilePointer(m_fileHandle, dwCur, NULL, FILE_BEGIN); #else - fseek( m_fileHandle, 0L, SEEK_END ); - unsigned int dwLen = ftell( m_fileHandle ); - fseek( m_fileHandle, 0L, SEEK_SET ); + fseek(m_fileHandle, 0L, SEEK_END); + unsigned int dwLen = ftell(m_fileHandle); + fseek(m_fileHandle, 0L, SEEK_SET); #endif return dwLen; } -void CParseFile::Read(void* buff, UINT buffsize) -{ +void CParseFile::Read(void *buff, UINT buffsize) { unsigned int bytesRead; #ifdef WIN32_FILE_IO ReadFile(m_fileHandle, buff, buffsize, &bytesRead, NULL); #else - fread( buff, buffsize, 1, m_fileHandle ); + fread(buff, buffsize, 1, m_fileHandle); #endif } -bool CParseFile::Init(LPCTSTR filename, CTokenizer* tokenizer) -{ +bool CParseFile::Init(LPCTSTR filename, CTokenizer *tokenizer) { CParseStream::InitBaseStream(); - m_fileName = (char*)malloc(strlen(filename) + 1); + m_fileName = (char *)malloc(strlen(filename) + 1); strcpy(m_fileName, filename); #ifdef WIN32_FILE_IO DWORD dwAccess = GENERIC_READ; @@ -521,26 +407,24 @@ bool CParseFile::Init(LPCTSTR filename, CTokenizer* tokenizer) m_fileHandle = CreateFile(filename, dwAccess, dwShareMode, &sa, dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL); - if (m_fileHandle == (HANDLE)-1) - { + if (m_fileHandle == (HANDLE)-1) { tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); Init(); return false; } #else - m_fileHandle = fopen( filename, "r+" ); + m_fileHandle = fopen(filename, "r+"); - if ( !m_fileHandle ) { - tokenizer->Error( TKERR_INCLUDE_FILE_NOTFOUND ); + if (!m_fileHandle) { + tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); Init(); return false; } #endif m_filesize = GetFileSize(); - m_buff = (byte*)malloc(m_filesize); - if (m_buff == NULL) - { + m_buff = (byte *)malloc(m_filesize); + if (m_buff == NULL) { tokenizer->Error(TKERR_BUFFERCREATE); Init(); return false; @@ -554,44 +438,29 @@ bool CParseFile::Init(LPCTSTR filename, CTokenizer* tokenizer) return true; } -long CParseFile::GetRemainingSize() -{ - return m_filesize - m_curByte; -} +long CParseFile::GetRemainingSize() { return m_filesize - m_curByte; } -bool CParseFile::NextChar(byte& theByte) -{ - if (m_curByte < m_filesize) - { - if (m_buff[m_curByte] == '\n') - { +bool CParseFile::NextChar(byte &theByte) { + if (m_curByte < m_filesize) { + if (m_buff[m_curByte] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_buff[m_curByte++]; return true; - } - else - { + } else { return false; } } -int CParseFile::GetCurLine() -{ - return m_curLine; -} +int CParseFile::GetCurLine() { return m_curLine; } -void CParseFile::GetCurFilename(char** theBuff) -{ +void CParseFile::GetCurFilename(char **theBuff) { *theBuff = NULL; - if (m_fileName != NULL) - { - *theBuff = (char*)malloc(strlen(m_fileName) + 1); + if (m_fileName != NULL) { + *theBuff = (char *)malloc(strlen(m_fileName) + 1); strcpy(*theBuff, m_fileName); } } @@ -600,50 +469,34 @@ void CParseFile::GetCurFilename(char** theBuff) // CParseMemory // -CParseMemory::CParseMemory() -{ -} +CParseMemory::CParseMemory() {} -CParseMemory::~CParseMemory() -{ -} +CParseMemory::~CParseMemory() {} -CParseMemory* CParseMemory::Create(byte* data, long datasize) -{ - CParseMemory* curParse = new CParseMemory(); +CParseMemory *CParseMemory::Create(byte *data, long datasize) { + CParseMemory *curParse = new CParseMemory(); curParse->Init(data, datasize); return curParse; } -void CParseMemory::Delete() -{ - delete this; -} +void CParseMemory::Delete() { delete this; } -bool CParseMemory::NextChar(byte& theByte) -{ - if (m_offset < m_datasize) - { - if (m_data[m_offset] == '\n') - { +bool CParseMemory::NextChar(byte &theByte) { + if (m_offset < m_datasize) { + if (m_data[m_offset] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_data[m_offset++]; return true; - } - else - { + } else { return false; } } -void CParseMemory::Init(byte* data, long datasize) -{ +void CParseMemory::Init(byte *data, long datasize) { m_data = data; m_curLine = 1; m_curPos = 1; @@ -651,53 +504,36 @@ void CParseMemory::Init(byte* data, long datasize) m_datasize = datasize; } -long CParseMemory::GetRemainingSize() -{ - return m_datasize - m_offset; -} +long CParseMemory::GetRemainingSize() { return m_datasize - m_offset; } -int CParseMemory::GetCurLine() -{ - return m_curLine; -} +int CParseMemory::GetCurLine() { return m_curLine; } -void CParseMemory::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseMemory::GetCurFilename(char **theBuff) { *theBuff = NULL; } // // CParseBlock // -CParseBlock::CParseBlock() -{ -} +CParseBlock::CParseBlock() {} -CParseBlock::~CParseBlock() -{ -} +CParseBlock::~CParseBlock() {} -CParseBlock* CParseBlock::Create(byte* data, long datasize) -{ - CParseBlock* curParse = new CParseBlock(); +CParseBlock *CParseBlock::Create(byte *data, long datasize) { + CParseBlock *curParse = new CParseBlock(); curParse->Init(data, datasize); return curParse; } -void CParseBlock::Delete() -{ - if (m_data != NULL) - { +void CParseBlock::Delete() { + if (m_data != NULL) { free(m_data); m_data = NULL; } delete this; } -void CParseBlock::Init(byte* data, long datasize) -{ - m_data = (byte*)malloc(datasize); +void CParseBlock::Init(byte *data, long datasize) { + m_data = (byte *)malloc(datasize); memcpy(m_data, data, datasize); m_curLine = 1; m_curPos = 1; @@ -709,64 +545,46 @@ void CParseBlock::Init(byte* data, long datasize) // CParseToken // -CParseToken::CParseToken() -{ -} +CParseToken::CParseToken() {} -CParseToken::~CParseToken() -{ -} +CParseToken::~CParseToken() {} -CParseToken* CParseToken::Create(CToken* token) -{ - CParseToken* curParse = new CParseToken(); +CParseToken *CParseToken::Create(CToken *token) { + CParseToken *curParse = new CParseToken(); curParse->Init(token); return curParse; } -void CParseToken::Delete() -{ - if (m_data != NULL) - { +void CParseToken::Delete() { + if (m_data != NULL) { free(m_data); m_data = NULL; } delete this; } -bool CParseToken::NextChar(byte& theByte) -{ - if (m_offset < m_datasize) - { - if (m_data[m_offset] == '\n') - { +bool CParseToken::NextChar(byte &theByte) { + if (m_offset < m_datasize) { + if (m_data[m_offset] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_data[m_offset++]; return true; - } - else - { + } else { return false; } } -void CParseToken::Init(CToken* token) -{ +void CParseToken::Init(CToken *token) { LPCTSTR tokenString = token->GetStringValue(); m_datasize = strlen(tokenString); - if (m_datasize > 0) - { - m_data = (byte*) malloc(m_datasize); + if (m_datasize > 0) { + m_data = (byte *)malloc(m_datasize); memcpy(m_data, tokenString, m_datasize); - } - else - { + } else { m_data = NULL; } m_curLine = 1; @@ -775,294 +593,203 @@ void CParseToken::Init(CToken* token) token->Delete(); } -long CParseToken::GetRemainingSize() -{ - return m_datasize - m_offset; -} +long CParseToken::GetRemainingSize() { return m_datasize - m_offset; } -int CParseToken::GetCurLine() -{ - return m_curLine; -} +int CParseToken::GetCurLine() { return m_curLine; } -void CParseToken::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseToken::GetCurFilename(char **theBuff) { *theBuff = NULL; } // // CParseDefine // -CParseDefine::CParseDefine() -{ -} +CParseDefine::CParseDefine() {} -CParseDefine::~CParseDefine() -{ -} +CParseDefine::~CParseDefine() {} -CParseDefine* CParseDefine::Create(CDirectiveSymbol* definesymbol) -{ - CParseDefine* retval = new CParseDefine(); +CParseDefine *CParseDefine::Create(CDirectiveSymbol *definesymbol) { + CParseDefine *retval = new CParseDefine(); retval->Init(definesymbol); return retval; } -void CParseDefine::Delete() -{ - CParseMemory::Delete(); -} +void CParseDefine::Delete() { CParseMemory::Delete(); } -void CParseDefine::Init(CDirectiveSymbol* definesymbol) -{ - CParseMemory::Init((byte*)definesymbol->GetValue(), strlen(definesymbol->GetValue())); +void CParseDefine::Init(CDirectiveSymbol *definesymbol) { + CParseMemory::Init((byte *)definesymbol->GetValue(), strlen(definesymbol->GetValue())); m_defineSymbol = definesymbol; } -bool CParseDefine::IsThisDefinition(void* theDefinition) -{ - return (CDirectiveSymbol*)theDefinition == m_defineSymbol; -} +bool CParseDefine::IsThisDefinition(void *theDefinition) { return (CDirectiveSymbol *)theDefinition == m_defineSymbol; } // // CToken // -CToken::CToken() -{ -} +CToken::CToken() {} -CToken::~CToken() -{ -} +CToken::~CToken() {} -CToken* CToken::Create() -{ - CToken* theToken = new CToken(); +CToken *CToken::Create() { + CToken *theToken = new CToken(); theToken->InitBaseToken(); return theToken; } -void CToken::Delete() -{ - if (m_string != NULL) - { +void CToken::Delete() { + if (m_string != NULL) { free(m_string); m_string = NULL; } delete this; } -void CToken::Init() -{ +void CToken::Init() { m_next = NULL; m_string = NULL; } -void CToken::SetNext(CToken* theToken) -{ - m_next = theToken; -} +void CToken::SetNext(CToken *theToken) { m_next = theToken; } -CToken* CToken::GetNext() -{ - return m_next; -} +CToken *CToken::GetNext() { return m_next; } -int CToken::GetType() -{ - return TK_EOF; -} +int CToken::GetType() { return TK_EOF; } -int CToken::GetIntValue() -{ - return 0; -} +int CToken::GetIntValue() { return 0; } -LPCTSTR CToken::GetStringValue() -{ - if (m_string == NULL) - { +LPCTSTR CToken::GetStringValue() { + if (m_string == NULL) { return ""; } return m_string; } -float CToken::GetFloatValue() -{ - return 0.0; -} +float CToken::GetFloatValue() { return 0.0; } // // CCharToken // -CCharToken::CCharToken() -{ -} +CCharToken::CCharToken() {} -CCharToken::~CCharToken() -{ -} +CCharToken::~CCharToken() {} -CCharToken* CCharToken::Create(byte theByte) -{ - CCharToken* theToken = new CCharToken(); +CCharToken *CCharToken::Create(byte theByte) { + CCharToken *theToken = new CCharToken(); theToken->Init(theByte); return theToken; } -void CCharToken::Delete() -{ - CToken::Delete(); -} +void CCharToken::Delete() { CToken::Delete(); } -void CCharToken::Init(byte theByte) -{ +void CCharToken::Init(byte theByte) { CToken::InitBaseToken(); char charString[10]; - switch(theByte) - { - case '\0': - strcpy(charString, "\\0"); - break; - case '\n': - strcpy(charString, "\\n"); - break; - case '\\': - strcpy(charString, "\\\\"); - break; - case '\'': - strcpy(charString, "\\'"); - break; - case '\?': - strcpy(charString, "\\?"); - break; - case '\a': - strcpy(charString, "\\a"); - break; - case '\b': - strcpy(charString, "\\b"); - break; - case '\f': - strcpy(charString, "\\f"); - break; - case '\r': - strcpy(charString, "\\r"); - break; - case '\t': - strcpy(charString, "\\t"); - break; - case '\v': - strcpy(charString, "\\v"); - break; - default: - charString[0] = (char)theByte; - charString[1] = '\0'; - break; + switch (theByte) { + case '\0': + strcpy(charString, "\\0"); + break; + case '\n': + strcpy(charString, "\\n"); + break; + case '\\': + strcpy(charString, "\\\\"); + break; + case '\'': + strcpy(charString, "\\'"); + break; + case '\?': + strcpy(charString, "\\?"); + break; + case '\a': + strcpy(charString, "\\a"); + break; + case '\b': + strcpy(charString, "\\b"); + break; + case '\f': + strcpy(charString, "\\f"); + break; + case '\r': + strcpy(charString, "\\r"); + break; + case '\t': + strcpy(charString, "\\t"); + break; + case '\v': + strcpy(charString, "\\v"); + break; + default: + charString[0] = (char)theByte; + charString[1] = '\0'; + break; } - m_string = (char*)malloc(strlen(charString) + 1); + m_string = (char *)malloc(strlen(charString) + 1); strcpy(m_string, charString); } -int CCharToken::GetType() -{ - return TK_CHAR; -} +int CCharToken::GetType() { return TK_CHAR; } // // CStringToken // -CStringToken::CStringToken() -{ -} +CStringToken::CStringToken() {} -CStringToken::~CStringToken() -{ -} +CStringToken::~CStringToken() {} -CStringToken* CStringToken::Create(LPCTSTR theString) -{ - CStringToken* theToken = new CStringToken(); +CStringToken *CStringToken::Create(LPCTSTR theString) { + CStringToken *theToken = new CStringToken(); theToken->Init(theString); return theToken; } -void CStringToken::Delete() -{ - CToken::Delete(); -} +void CStringToken::Delete() { CToken::Delete(); } -void CStringToken::Init(LPCTSTR theString) -{ +void CStringToken::Init(LPCTSTR theString) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(theString) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(theString) + 1); + // ASSERT(m_string); strcpy(m_string, theString); } -int CStringToken::GetType() -{ - return TK_STRING; -} +int CStringToken::GetType() { return TK_STRING; } // // CIntToken // -CIntToken::CIntToken() -{ -} +CIntToken::CIntToken() {} -CIntToken::~CIntToken() -{ -} +CIntToken::~CIntToken() {} -CIntToken* CIntToken::Create(long value) -{ - CIntToken* theToken = new CIntToken(); +CIntToken *CIntToken::Create(long value) { + CIntToken *theToken = new CIntToken(); theToken->Init(value); return theToken; } -void CIntToken::Delete() -{ - CToken::Delete(); -} +void CIntToken::Delete() { CToken::Delete(); } -void CIntToken::Init(long value) -{ +void CIntToken::Init(long value) { CToken::InitBaseToken(); m_value = value; } -int CIntToken::GetType() -{ - return TK_INT; -} +int CIntToken::GetType() { return TK_INT; } -int CIntToken::GetIntValue() -{ - return m_value; -} +int CIntToken::GetIntValue() { return m_value; } -float CIntToken::GetFloatValue() -{ - return (float)m_value; -} +float CIntToken::GetFloatValue() { return (float)m_value; } -LPCTSTR CIntToken::GetStringValue() -{ - if (m_string != NULL) - { +LPCTSTR CIntToken::GetStringValue() { + if (m_string != NULL) { free(m_string); m_string = NULL; } char temp[128]; sprintf(temp, "%d", m_value); - m_string = (char*)malloc(strlen(temp) + 1); + m_string = (char *)malloc(strlen(temp) + 1); strcpy(m_string, temp); return m_string; } @@ -1071,52 +798,35 @@ LPCTSTR CIntToken::GetStringValue() // CFloatToken // -CFloatToken::CFloatToken() -{ -} +CFloatToken::CFloatToken() {} -CFloatToken::~CFloatToken() -{ -} +CFloatToken::~CFloatToken() {} -CFloatToken* CFloatToken::Create(float value) -{ - CFloatToken* theToken = new CFloatToken(); +CFloatToken *CFloatToken::Create(float value) { + CFloatToken *theToken = new CFloatToken(); theToken->Init(value); return theToken; } -void CFloatToken::Delete() -{ - CToken::Delete(); -} +void CFloatToken::Delete() { CToken::Delete(); } -void CFloatToken::Init(float value) -{ +void CFloatToken::Init(float value) { CToken::InitBaseToken(); m_value = value; } -int CFloatToken::GetType() -{ - return TK_FLOAT; -} +int CFloatToken::GetType() { return TK_FLOAT; } -float CFloatToken::GetFloatValue() -{ - return m_value; -} +float CFloatToken::GetFloatValue() { return m_value; } -LPCTSTR CFloatToken::GetStringValue() -{ - if (m_string != NULL) - { +LPCTSTR CFloatToken::GetStringValue() { + if (m_string != NULL) { free(m_string); m_string = NULL; } char temp[128]; sprintf(temp, "%g", m_value); - m_string = (char*)malloc(strlen(temp) + 1); + m_string = (char *)malloc(strlen(temp) + 1); strcpy(m_string, temp); return m_string; } @@ -1125,238 +835,157 @@ LPCTSTR CFloatToken::GetStringValue() // CIdentifierToken // -CIdentifierToken::CIdentifierToken() -{ -} +CIdentifierToken::CIdentifierToken() {} -CIdentifierToken::~CIdentifierToken() -{ -} +CIdentifierToken::~CIdentifierToken() {} -CIdentifierToken* CIdentifierToken::Create(LPCTSTR name) -{ - CIdentifierToken* theToken = new CIdentifierToken(); +CIdentifierToken *CIdentifierToken::Create(LPCTSTR name) { + CIdentifierToken *theToken = new CIdentifierToken(); theToken->Init(name); return theToken; } -void CIdentifierToken::Delete() -{ - CToken::Delete(); -} +void CIdentifierToken::Delete() { CToken::Delete(); } -void CIdentifierToken::Init(LPCTSTR name) -{ +void CIdentifierToken::Init(LPCTSTR name) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(name) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(name) + 1); + // ASSERT(m_string); strcpy(m_string, name); } -int CIdentifierToken::GetType() -{ - return TK_IDENTIFIER; -} +int CIdentifierToken::GetType() { return TK_IDENTIFIER; } // // CCommentToken // -CCommentToken::CCommentToken() -{ -} +CCommentToken::CCommentToken() {} -CCommentToken::~CCommentToken() -{ -} +CCommentToken::~CCommentToken() {} -CCommentToken* CCommentToken::Create(LPCTSTR name) -{ - CCommentToken* theToken = new CCommentToken(); +CCommentToken *CCommentToken::Create(LPCTSTR name) { + CCommentToken *theToken = new CCommentToken(); theToken->Init(name); return theToken; } -void CCommentToken::Delete() -{ - CToken::Delete(); -} +void CCommentToken::Delete() { CToken::Delete(); } -void CCommentToken::Init(LPCTSTR name) -{ +void CCommentToken::Init(LPCTSTR name) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(name) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(name) + 1); + // ASSERT(m_string); strcpy(m_string, name); } -int CCommentToken::GetType() -{ - return TK_COMMENT; -} +int CCommentToken::GetType() { return TK_COMMENT; } // // CUserToken // -CUserToken::CUserToken() -{ -} +CUserToken::CUserToken() {} -CUserToken::~CUserToken() -{ -} +CUserToken::~CUserToken() {} -CUserToken* CUserToken::Create(int value, LPCTSTR string) -{ - CUserToken* theToken = new CUserToken(); +CUserToken *CUserToken::Create(int value, LPCTSTR string) { + CUserToken *theToken = new CUserToken(); theToken->Init(value, string); return theToken; } -void CUserToken::Delete() -{ - CToken::Delete(); -} +void CUserToken::Delete() { CToken::Delete(); } -void CUserToken::Init(int value, LPCTSTR string) -{ +void CUserToken::Init(int value, LPCTSTR string) { CToken::InitBaseToken(); m_value = value; - m_string = (char*)malloc(strlen(string) + 1); + m_string = (char *)malloc(strlen(string) + 1); strcpy(m_string, string); } -int CUserToken::GetType() -{ - return m_value; -} +int CUserToken::GetType() { return m_value; } // // CUndefinedToken // -CUndefinedToken::CUndefinedToken() -{ -} +CUndefinedToken::CUndefinedToken() {} -CUndefinedToken::~CUndefinedToken() -{ -} +CUndefinedToken::~CUndefinedToken() {} -CUndefinedToken* CUndefinedToken::Create(LPCTSTR string) -{ - CUndefinedToken* theToken = new CUndefinedToken(); +CUndefinedToken *CUndefinedToken::Create(LPCTSTR string) { + CUndefinedToken *theToken = new CUndefinedToken(); theToken->Init(string); return theToken; } -void CUndefinedToken::Delete() -{ - CToken::Delete(); -} +void CUndefinedToken::Delete() { CToken::Delete(); } -void CUndefinedToken::Init(LPCTSTR string) -{ +void CUndefinedToken::Init(LPCTSTR string) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(string) + 1); + m_string = (char *)malloc(strlen(string) + 1); strcpy(m_string, string); } -int CUndefinedToken::GetType() -{ - return TK_UNDEFINED; -} +int CUndefinedToken::GetType() { return TK_UNDEFINED; } // // CTokenizerState // -CTokenizerState::CTokenizerState() -{ -} +CTokenizerState::CTokenizerState() {} -CTokenizerState::~CTokenizerState() -{ -} +CTokenizerState::~CTokenizerState() {} -CTokenizerState* CTokenizerState::Create(bool skip) -{ - CTokenizerState* retval = new CTokenizerState(); +CTokenizerState *CTokenizerState::Create(bool skip) { + CTokenizerState *retval = new CTokenizerState(); retval->Init(skip); return retval; } -void CTokenizerState::Init(bool skip) -{ +void CTokenizerState::Init(bool skip) { m_next = NULL; m_skip = skip; m_elseHit = false; } -void CTokenizerState::Delete() -{ - delete this; -} +void CTokenizerState::Delete() { delete this; } -CTokenizerState* CTokenizerState::GetNext() -{ - return m_next; -} +CTokenizerState *CTokenizerState::GetNext() { return m_next; } -bool CTokenizerState::ProcessElse() -{ - if (!m_elseHit) - { +bool CTokenizerState::ProcessElse() { + if (!m_elseHit) { m_elseHit = true; m_skip = !m_skip; } return m_elseHit; } -void CTokenizerState::SetNext(CTokenizerState* next) -{ - m_next = next; -} +void CTokenizerState::SetNext(CTokenizerState *next) { m_next = next; } -bool CTokenizerState::Skipping() -{ - return m_skip; -} +bool CTokenizerState::Skipping() { return m_skip; } // // CTokenizerHolderState // -CTokenizerHolderState::CTokenizerHolderState() -{ -} +CTokenizerHolderState::CTokenizerHolderState() {} -CTokenizerHolderState::~CTokenizerHolderState() -{ -} +CTokenizerHolderState::~CTokenizerHolderState() {} -CTokenizerHolderState* CTokenizerHolderState::Create() -{ - CTokenizerHolderState* retval = new CTokenizerHolderState(); +CTokenizerHolderState *CTokenizerHolderState::Create() { + CTokenizerHolderState *retval = new CTokenizerHolderState(); retval->Init(); return retval; } -void CTokenizerHolderState::Init() -{ - CTokenizerState::Init(true); -} +void CTokenizerHolderState::Init() { CTokenizerState::Init(true); } -void CTokenizerHolderState::Delete() -{ - delete this; -} +void CTokenizerHolderState::Delete() { delete this; } -bool CTokenizerHolderState::ProcessElse() -{ - if (!m_elseHit) - { +bool CTokenizerHolderState::ProcessElse() { + if (!m_elseHit) { m_elseHit = true; } return m_elseHit; @@ -1366,143 +995,112 @@ bool CTokenizerHolderState::ProcessElse() // CKeywordTable // -CKeywordTable::CKeywordTable(CTokenizer* tokenizer, keywordArray_t* keywords) -{ +CKeywordTable::CKeywordTable(CTokenizer *tokenizer, keywordArray_t *keywords) { m_tokenizer = tokenizer; m_holdKeywords = tokenizer->SetKeywords(keywords); } -CKeywordTable::~CKeywordTable() -{ - m_tokenizer->SetKeywords(m_holdKeywords); -} +CKeywordTable::~CKeywordTable() { m_tokenizer->SetKeywords(m_holdKeywords); } // // CTokenizer // -CTokenizer::CTokenizer() -{ -} +CTokenizer::CTokenizer() {} -CTokenizer::~CTokenizer() -{ -} +CTokenizer::~CTokenizer() {} -CTokenizer* CTokenizer::Create(UINT dwFlags) -{ - CTokenizer* theTokenizer = new CTokenizer(); +CTokenizer *CTokenizer::Create(UINT dwFlags) { + CTokenizer *theTokenizer = new CTokenizer(); theTokenizer->Init(dwFlags); return theTokenizer; } -void CTokenizer::Delete() -{ - while (m_curParseStream != NULL) - { - CParseStream* curStream = m_curParseStream; +void CTokenizer::Delete() { + while (m_curParseStream != NULL) { + CParseStream *curStream = m_curParseStream; m_curParseStream = curStream->GetNext(); curStream->Delete(); } - if (m_symbolLookup != NULL) - { + if (m_symbolLookup != NULL) { m_symbolLookup->Delete(); m_symbolLookup = NULL; } - while (m_nextToken != NULL) - { - CToken* curToken = m_nextToken; + while (m_nextToken != NULL) { + CToken *curToken = m_nextToken; m_nextToken = curToken->GetNext(); curToken->Delete(); } - while (m_state != NULL) - { + while (m_state != NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); - CTokenizerState* curState = m_state; + CTokenizerState *curState = m_state; m_state = curState->GetNext(); curState->Delete(); } -/* if (m_lastErrMsg != NULL) - { - free(m_lastErrMsg); - m_lastErrMsg = NULL; - }*/ + /* if (m_lastErrMsg != NULL) + { + free(m_lastErrMsg); + m_lastErrMsg = NULL; + }*/ delete this; } -void CTokenizer::Error(int theError) -{ +void CTokenizer::Error(int theError) { char errString[128]; char lookupstring[128]; int i = 0; - while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) - { + while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) { i++; } - if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) - { + if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) { i = 0; - while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) - { + while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) { i++; } strcpy(lookupstring, m_errors[i].m_keyword); - } - else - { + } else { strcpy(lookupstring, errorMessages[i].m_keyword); } sprintf(errString, "Error -- %d, %s", theError, lookupstring); Error(errString, theError); } -void CTokenizer::Error(int theError, LPCTSTR errString) -{ +void CTokenizer::Error(int theError, LPCTSTR errString) { char errstring[128]; char lookupstring[128]; int i = 0; - while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) - { + while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) { i++; } - if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) - { + if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) { i = 0; - while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) - { + while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) { i++; } strcpy(lookupstring, m_errors[i].m_keyword); - } - else - { + } else { strcpy(lookupstring, errorMessages[i].m_keyword); } sprintf(errstring, "Error -- %d, %s - %s", theError, lookupstring, errString); Error(errstring, theError); } -void CTokenizer::Error(LPCTSTR errString, int theError) -{ - if (m_errorProc != NULL) - { +void CTokenizer::Error(LPCTSTR errString, int theError) { + if (m_errorProc != NULL) { m_errorProc(errString); } #ifdef USES_MODULES - else - { + else { ReportError(theError, errString); } #endif } -bool CTokenizer::AddParseFile(LPCTSTR filename) -{ - CParseStream* newStream = CParseFile::Create(filename, this); +bool CTokenizer::AddParseFile(LPCTSTR filename) { + CParseStream *newStream = CParseFile::Create(filename, this); - if ( newStream != NULL ) - { + if (newStream != NULL) { newStream->SetNext(m_curParseStream); m_curParseStream = newStream; return true; @@ -1511,41 +1109,33 @@ bool CTokenizer::AddParseFile(LPCTSTR filename) return false; } -void CTokenizer::AddParseStream(byte* data, long datasize) -{ - CParseStream* newStream = CParseMemory::Create(data, datasize); +void CTokenizer::AddParseStream(byte *data, long datasize) { + CParseStream *newStream = CParseMemory::Create(data, datasize); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; } -long CTokenizer::GetRemainingSize() -{ +long CTokenizer::GetRemainingSize() { long retval = 0; - CParseStream* curStream = m_curParseStream; - while (curStream != NULL) - { + CParseStream *curStream = m_curParseStream; + while (curStream != NULL) { retval += curStream->GetRemainingSize(); curStream = curStream->GetNext(); } return retval; } -LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t* theTable) -{ - if (theTable == NULL) - { +LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t *theTable) { + if (theTable == NULL) { theTable = m_keywords; } - if (theTable == NULL) - { + if (theTable == NULL) { return NULL; } int i = 0; - while (theTable[i].m_tokenvalue != TK_EOF) - { - if (theTable[i].m_tokenvalue == tokenID) - { + while (theTable[i].m_tokenvalue != TK_EOF) { + if (theTable[i].m_tokenvalue == tokenID) { return theTable[i].m_keyword; } i++; @@ -1553,34 +1143,30 @@ LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t* theTable) return NULL; } -void CTokenizer::PutBackToken(CToken* theToken, bool commented, LPCTSTR addedChars, bool bIgnoreThisTokenType) -{ - if (commented) - { - CParseToken* newStream = CParseToken::Create(theToken); +void CTokenizer::PutBackToken(CToken *theToken, bool commented, LPCTSTR addedChars, bool bIgnoreThisTokenType) { + if (commented) { + CParseToken *newStream = CParseToken::Create(theToken); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; - if (addedChars != NULL) - { - CParsePutBack* spacer = CParsePutBack::Create(' ', 0, NULL); + if (addedChars != NULL) { + CParsePutBack *spacer = CParsePutBack::Create(' ', 0, NULL); spacer->SetNext(m_curParseStream); m_curParseStream = spacer; - CParseBlock* newBlock = CParseBlock::Create((byte*)addedChars, strlen(addedChars)); + CParseBlock *newBlock = CParseBlock::Create((byte *)addedChars, strlen(addedChars)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; } char temp[] = "// * "; - CParseBlock* newBlock = CParseBlock::Create((byte*)temp, strlen(temp)); + CParseBlock *newBlock = CParseBlock::Create((byte *)temp, strlen(temp)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; return; } - switch(theToken->GetType()) - { + switch (theToken->GetType()) { case TK_INT: case TK_EOF: case TK_UNDEFINED: @@ -1589,57 +1175,48 @@ void CTokenizer::PutBackToken(CToken* theToken, bool commented, LPCTSTR addedCha case TK_STRING: case TK_EOL: case TK_COMMENT: - if (!bIgnoreThisTokenType) - { + if (!bIgnoreThisTokenType) { theToken->SetNext(m_nextToken); m_nextToken = theToken; break; } default: - CParseToken* newStream = CParseToken::Create(theToken); + CParseToken *newStream = CParseToken::Create(theToken); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; break; } - if (addedChars != NULL) - { - CParseBlock* newBlock = CParseBlock::Create((byte*)addedChars, strlen(addedChars)); + if (addedChars != NULL) { + CParseBlock *newBlock = CParseBlock::Create((byte *)addedChars, strlen(addedChars)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; } } -CToken* CTokenizer::GetToken(keywordArray_t* keywords, UINT onFlags, UINT offFlags) -{ - keywordArray_t* holdKeywords = SetKeywords(keywords); - CToken* retval = GetToken(onFlags, offFlags); +CToken *CTokenizer::GetToken(keywordArray_t *keywords, UINT onFlags, UINT offFlags) { + keywordArray_t *holdKeywords = SetKeywords(keywords); + CToken *retval = GetToken(onFlags, offFlags); SetKeywords(holdKeywords); return retval; } -CToken* CTokenizer::GetToken(UINT onFlags, UINT offFlags) -{ +CToken *CTokenizer::GetToken(UINT onFlags, UINT offFlags) { UINT holdFlags = m_flags; m_flags |= onFlags; m_flags &= (~offFlags); - CToken* theToken = NULL; - while (theToken == NULL) - { + CToken *theToken = NULL; + while (theToken == NULL) { theToken = FetchToken(); - if (theToken == NULL) - { + if (theToken == NULL) { continue; } - if (theToken->GetType() == TK_EOF) - { + if (theToken->GetType() == TK_EOF) { break; } - if (m_state != NULL) - { - if (m_state->Skipping()) - { + if (m_state != NULL) { + if (m_state->Skipping()) { theToken->Delete(); theToken = NULL; } @@ -1650,60 +1227,47 @@ CToken* CTokenizer::GetToken(UINT onFlags, UINT offFlags) return theToken; } -CToken* CTokenizer::GetToEndOfLine(int tokenType) -{ +CToken *CTokenizer::GetToEndOfLine(int tokenType) { // update, if you just want the whole line returned as a string, then allow a much bigger size than // the default string size of only 128 chars... // - if (tokenType == TK_STRING) - { - #define iRETURN_STRING_SIZE 2048 + if (tokenType == TK_STRING) { +#define iRETURN_STRING_SIZE 2048 char theString[iRETURN_STRING_SIZE]; theString[0] = ' '; - for (int i = 1; i < iRETURN_STRING_SIZE; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '\n') - { + for (int i = 1; i < iRETURN_STRING_SIZE; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '\n') { continue; } PutBackChar(theString[i]); } theString[i] = '\0'; - return CStringToken::Create(theString); + return CStringToken::Create(theString); } // line would maks a string too big to fit in buffer... - // + // Error(TKERR_STRINGLENGTHEXCEEDED); - } - else - { + } else { char theString[MAX_IDENTIFIER_LENGTH]; theString[0] = ' '; - while (theString[0] == ' ') - { - if (!NextChar((byte&)theString[0])) - { + while (theString[0] == ' ') { + if (!NextChar((byte &)theString[0])) { return NULL; } } - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '\n') - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '\n') { continue; } PutBackChar(theString[i]); } theString[i] = '\0'; - switch(tokenType) - { + switch (tokenType) { case TK_COMMENT: return CCommentToken::Create(theString); case TK_IDENTIFIER: @@ -1712,59 +1276,45 @@ CToken* CTokenizer::GetToEndOfLine(int tokenType) } } Error(TKERR_IDENTIFIERLENGTHEXCEEDED); - } + } return NULL; } -void CTokenizer::SkipToLineEnd() -{ +void CTokenizer::SkipToLineEnd() { byte theByte; - while(NextChar(theByte)) - { - if (theByte == '\n') - { + while (NextChar(theByte)) { + if (theByte == '\n') { break; } } } -CToken* CTokenizer::FetchToken() -{ - if (m_nextToken != NULL) - { - CToken* curToken = m_nextToken; +CToken *CTokenizer::FetchToken() { + if (m_nextToken != NULL) { + CToken *curToken = m_nextToken; m_nextToken = curToken->GetNext(); curToken->SetNext(NULL); return curToken; } byte theByte; - CToken* theToken = NULL; + CToken *theToken = NULL; - while (true) - { - if (!NextChar(theByte)) - { + while (true) { + if (!NextChar(theByte)) { return CToken::Create(); } - if (theByte <= ' ') - { - if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) - { + if (theByte <= ' ') { + if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) { return CUserToken::Create(TK_EOL, "-EOLN-"); } continue; } - switch(theByte) - { + switch (theByte) { case '#': - if ((m_flags & TKF_IGNOREDIRECTIVES) == 0) - { + if ((m_flags & TKF_IGNOREDIRECTIVES) == 0) { theToken = HandleDirective(); - } - else - { - if ((m_flags & TKF_NODIRECTIVES) != 0) - { + } else { + if ((m_flags & TKF_NODIRECTIVES) != 0) { return HandleSymbol('#'); } SkipToLineEnd(); @@ -1780,89 +1330,65 @@ CToken* CTokenizer::FetchToken() theToken = HandleQuote(); break; default: - if (((theByte >= 'a') && (theByte <= 'z')) - || ((theByte >= 'A') && (theByte <= 'Z')) - || ((theByte == '_') && ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0))) - { + if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || + ((theByte == '_') && ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0))) { theToken = HandleIdentifier(theByte); - } - else if (((m_flags & TKF_NUMERICIDENTIFIERSTART) != 0) && (theByte >= '0') && (theByte <= '9')) - { + } else if (((m_flags & TKF_NUMERICIDENTIFIERSTART) != 0) && (theByte >= '0') && (theByte <= '9')) { theToken = HandleIdentifier(theByte); - } - else if (((theByte >= '0') && (theByte <= '9')) || (theByte == '-')) - { + } else if (((theByte >= '0') && (theByte <= '9')) || (theByte == '-')) { theToken = HandleNumeric(theByte); - } - else if (theByte == '.') - { + } else if (theByte == '.') { theToken = HandleDecimal(); - } - else if (theByte <= ' ') - { + } else if (theByte <= ' ') { break; - } - else - { + } else { theToken = HandleSymbol(theByte); } } - if (theToken != NULL) - { + if (theToken != NULL) { return theToken; } } } -bool CTokenizer::NextChar(byte& theByte) -{ - while (m_curParseStream != NULL) - { - if (m_curParseStream->NextChar(theByte)) - { +bool CTokenizer::NextChar(byte &theByte) { + while (m_curParseStream != NULL) { + if (m_curParseStream->NextChar(theByte)) { return true; } - CParseStream* curParseStream = m_curParseStream; + CParseStream *curParseStream = m_curParseStream; m_curParseStream = curParseStream->GetNext(); curParseStream->Delete(); } return false; } -bool CTokenizer::RequireToken(int tokenType) -{ - CToken* theToken = GetToken(); +bool CTokenizer::RequireToken(int tokenType) { + CToken *theToken = GetToken(); bool retValue = theToken->GetType() == tokenType; theToken->Delete(); return retValue; } -void CTokenizer::ScanUntilToken(int tokenType) -{ - CToken* curToken; +void CTokenizer::ScanUntilToken(int tokenType) { + CToken *curToken; int tokenValue = TK_UNDEFINED; - while (tokenValue != tokenType) - { + while (tokenValue != tokenType) { curToken = GetToken(); tokenValue = curToken->GetType(); - if (tokenValue == TK_EOF) - { + if (tokenValue == TK_EOF) { PutBackToken(curToken); break; } - if (tokenValue == tokenType) - { + if (tokenValue == tokenType) { PutBackToken(curToken); - } - else - { + } else { curToken->Delete(); } } } -void CTokenizer::Init(UINT dwFlags) -{ +void CTokenizer::Init(UINT dwFlags) { m_symbolLookup = NULL; m_nextToken = NULL; m_curParseStream = NULL; @@ -1874,64 +1400,48 @@ void CTokenizer::Init(UINT dwFlags) m_errorProc = NULL; } -void CTokenizer::SetErrorProc(LPTokenizerErrorProc errorProc) -{ - m_errorProc = errorProc; -} +void CTokenizer::SetErrorProc(LPTokenizerErrorProc errorProc) { m_errorProc = errorProc; } -void CTokenizer::SetAdditionalErrors(keywordArray_t* theErrors) -{ - m_errors = theErrors; -} +void CTokenizer::SetAdditionalErrors(keywordArray_t *theErrors) { m_errors = theErrors; } -keywordArray_t* CTokenizer::SetKeywords(keywordArray_t* theKeywords) -{ - keywordArray_t* retval = m_keywords; +keywordArray_t *CTokenizer::SetKeywords(keywordArray_t *theKeywords) { + keywordArray_t *retval = m_keywords; m_keywords = theKeywords; return retval; } -void CTokenizer::SetSymbols(keywordArray_t* theSymbols) -{ +void CTokenizer::SetSymbols(keywordArray_t *theSymbols) { m_symbols = theSymbols; - if (m_symbolLookup != NULL) - { + if (m_symbolLookup != NULL) { m_symbolLookup->Delete(); m_symbolLookup = NULL; } int i = 0; - if (theSymbols == NULL) - { + if (theSymbols == NULL) { return; } - while(theSymbols[i].m_tokenvalue != TK_EOF) - { + while (theSymbols[i].m_tokenvalue != TK_EOF) { InsertSymbol(theSymbols[i].m_keyword, theSymbols[i].m_tokenvalue); i++; } } -void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) -{ - CSymbolLookup** curHead = &m_symbolLookup; - CSymbolLookup* curParent = NULL; - CSymbolLookup* curLookup = NULL; +void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) { + CSymbolLookup **curHead = &m_symbolLookup; + CSymbolLookup *curParent = NULL; + CSymbolLookup *curLookup = NULL; - for (UINT i = 0; i < strlen(theSymbol); i++) - { + for (UINT i = 0; i < strlen(theSymbol); i++) { bool found = false; curLookup = *curHead; - while (curLookup != NULL) - { - if (curLookup->GetByte() == theSymbol[i]) - { + while (curLookup != NULL) { + if (curLookup->GetByte() == theSymbol[i]) { found = true; break; } curLookup = curLookup->GetNext(); } - if (!found) - { + if (!found) { curLookup = CSymbolLookup::Create(theSymbol[i]); curLookup->SetParent(curParent); curLookup->SetNext(*curHead); @@ -1940,29 +1450,23 @@ void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) curHead = curLookup->GetChildAddress(); curParent = curLookup; } - if (curLookup->GetValue() != -1) - { + if (curLookup->GetValue() != -1) { Error(TKERR_DUPLICATESYMBOL); } curLookup->SetValue(theValue); } -CToken* CTokenizer::HandleString() -{ +CToken *CTokenizer::HandleString() { char theString[MAX_STRING_LENGTH]; - for (int i = 0; i < MAX_STRING_LENGTH; i++) - { - if (!NextChar((byte&)theString[i])) - { + for (int i = 0; i < MAX_STRING_LENGTH; i++) { + if (!NextChar((byte &)theString[i])) { return NULL; } - if (theString[i] == '"') - { + if (theString[i] == '"') { theString[i] = '\0'; return CStringToken::Create(theString); } - if (theString[i] == '\\') - { + if (theString[i] == '\\') { theString[i] = Escapement(); } } @@ -1970,55 +1474,43 @@ CToken* CTokenizer::HandleString() return NULL; } -void CTokenizer::GetCurFilename(char** filename) -{ - if (m_curParseStream == NULL) - { - *filename = (char*)malloc(1); +void CTokenizer::GetCurFilename(char **filename) { + if (m_curParseStream == NULL) { + *filename = (char *)malloc(1); *filename[0] = '\0'; return; } m_curParseStream->GetCurFilename(filename); } -int CTokenizer::GetCurLine() -{ - if (m_curParseStream == NULL) - { +int CTokenizer::GetCurLine() { + if (m_curParseStream == NULL) { return 0; } return m_curParseStream->GetCurLine(); } -void CTokenizer::PutBackChar(byte theByte, int curLine, LPCTSTR filename) -{ - CParseStream* newStream; - if (filename == NULL) - { +void CTokenizer::PutBackChar(byte theByte, int curLine, LPCTSTR filename) { + CParseStream *newStream; + if (filename == NULL) { curLine = m_curParseStream->GetCurLine(); - char* theFile = NULL; + char *theFile = NULL; m_curParseStream->GetCurFilename(&theFile); newStream = CParsePutBack::Create(theByte, curLine, theFile); - if (theFile != NULL) - { + if (theFile != NULL) { free(theFile); } - } - else - { + } else { newStream = CParsePutBack::Create(theByte, curLine, filename); } newStream->SetNext(m_curParseStream); m_curParseStream = newStream; } -byte CTokenizer::Escapement() -{ +byte CTokenizer::Escapement() { byte theByte; - if (NextChar(theByte)) - { - switch(theByte) - { + if (NextChar(theByte)) { + switch (theByte) { case 'n': return '\n'; case '\\': @@ -2049,53 +1541,39 @@ byte CTokenizer::Escapement() return '\\'; } -bool CTokenizer::AddDefineSymbol(CDirectiveSymbol* definesymbol) -{ - CParseStream* curStream = m_curParseStream; - while(curStream != NULL) - { - if (curStream->IsThisDefinition(definesymbol)) - { +bool CTokenizer::AddDefineSymbol(CDirectiveSymbol *definesymbol) { + CParseStream *curStream = m_curParseStream; + while (curStream != NULL) { + if (curStream->IsThisDefinition(definesymbol)) { return false; } curStream = curStream->GetNext(); } - CParseStream* newStream = CParseDefine::Create(definesymbol); + CParseStream *newStream = CParseDefine::Create(definesymbol); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; return true; } -CToken* CTokenizer::TokenFromName(LPCTSTR name) -{ - CDirectiveSymbol* defineSymbol = (CDirectiveSymbol*)m_defines.FindSymbol(name); - if (defineSymbol != NULL) - { - if (AddDefineSymbol(defineSymbol)) - { +CToken *CTokenizer::TokenFromName(LPCTSTR name) { + CDirectiveSymbol *defineSymbol = (CDirectiveSymbol *)m_defines.FindSymbol(name); + if (defineSymbol != NULL) { + if (AddDefineSymbol(defineSymbol)) { return FetchToken(); } } - if ((m_keywords != NULL) && ((m_flags & TKF_IGNOREKEYWORDS) == 0)) - { + if ((m_keywords != NULL) && ((m_flags & TKF_IGNOREKEYWORDS) == 0)) { int i = 0; - if ((m_flags & TKF_NOCASEKEYWORDS) == 0) - { - while (m_keywords[i].m_tokenvalue != TK_EOF) - { - if (strcmp(m_keywords[i].m_keyword, name) == 0) - { + if ((m_flags & TKF_NOCASEKEYWORDS) == 0) { + while (m_keywords[i].m_tokenvalue != TK_EOF) { + if (strcmp(m_keywords[i].m_keyword, name) == 0) { return CUserToken::Create(m_keywords[i].m_tokenvalue, name); } i++; } - } - else - { - while (m_keywords[i].m_tokenvalue != TK_EOF) - { - if (stricmp(m_keywords[i].m_keyword, name) == 0) - { + } else { + while (m_keywords[i].m_tokenvalue != TK_EOF) { + if (stricmp(m_keywords[i].m_keyword, name) == 0) { return CUserToken::Create(m_keywords[i].m_tokenvalue, name); } i++; @@ -2105,15 +1583,11 @@ CToken* CTokenizer::TokenFromName(LPCTSTR name) return CIdentifierToken::Create(name); } -int CTokenizer::DirectiveFromName(LPCTSTR name) -{ - if (directiveKeywords != NULL) - { +int CTokenizer::DirectiveFromName(LPCTSTR name) { + if (directiveKeywords != NULL) { int i = 0; - while (directiveKeywords[i].m_tokenvalue != TK_EOF) - { - if (strcmp(directiveKeywords[i].m_keyword, name) == 0) - { + while (directiveKeywords[i].m_tokenvalue != TK_EOF) { + if (strcmp(directiveKeywords[i].m_keyword, name) == 0) { return directiveKeywords[i].m_tokenvalue; } i++; @@ -2122,22 +1596,15 @@ int CTokenizer::DirectiveFromName(LPCTSTR name) return -1; } -CToken* CTokenizer::HandleIdentifier(byte theByte) -{ +CToken *CTokenizer::HandleIdentifier(byte theByte) { char theString[MAX_IDENTIFIER_LENGTH]; theString[0] = theByte; - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { if (((theString[i] != '_') || ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0)) && - ((theString[i] != '-') || ((m_flags & TKF_NODASHINIDENTIFIER) == 0))) - { - if (((theString[i] >= 'A') && (theString[i] <= 'Z')) - || ((theString[i] >= 'a') && (theString[i] <= 'z')) - || ((theString[i] >= '0') && (theString[i] <= '9')) - || (theString[i] == '_') || (theString[i] == '-')) - { + ((theString[i] != '-') || ((m_flags & TKF_NODASHINIDENTIFIER) == 0))) { + if (((theString[i] >= 'A') && (theString[i] <= 'Z')) || ((theString[i] >= 'a') && (theString[i] <= 'z')) || + ((theString[i] >= '0') && (theString[i] <= '9')) || (theString[i] == '_') || (theString[i] == '-')) { continue; } } @@ -2150,48 +1617,35 @@ CToken* CTokenizer::HandleIdentifier(byte theByte) return NULL; } -CToken* CTokenizer::HandleSlash() -{ +CToken *CTokenizer::HandleSlash() { byte theByte; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { return NULL; } - if (theByte == '/') - { - if (m_flags & TKF_COMMENTTOKENS) - { + if (theByte == '/') { + if (m_flags & TKF_COMMENTTOKENS) { return GetToEndOfLine(TK_COMMENT); } SkipToLineEnd(); return NULL; } - if (theByte == '*') - { - if (m_flags & TKF_COMMENTTOKENS) - { + if (theByte == '*') { + if (m_flags & TKF_COMMENTTOKENS) { char theString[MAX_IDENTIFIER_LENGTH + 1]; theString[0] = ' '; - while (theString[0] == ' ') - { - if (!NextChar((byte&)theString[0])) - { + while (theString[0] == ' ') { + if (!NextChar((byte &)theString[0])) { return NULL; } } - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '*') - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '*') { continue; } i++; - if (NextChar((byte&)theString[i])) - { - if (theString[i] == '/') - { + if (NextChar((byte &)theString[i])) { + if (theString[i] == '/') { i--; theString[i] = '\0'; return CCommentToken::Create(theString); @@ -2202,16 +1656,12 @@ CToken* CTokenizer::HandleSlash() Error(TKERR_IDENTIFIERLENGTHEXCEEDED); return NULL; } - while(NextChar(theByte)) - { - while(theByte == '*') - { - if (!NextChar(theByte)) - { + while (NextChar(theByte)) { + while (theByte == '*') { + if (!NextChar(theByte)) { break; } - if (theByte == '/') - { + if (theByte == '/') { return NULL; } } @@ -2222,101 +1672,77 @@ CToken* CTokenizer::HandleSlash() return HandleSymbol('/'); } -CToken* CTokenizer::HandleNumeric(byte theByte) -{ +CToken *CTokenizer::HandleNumeric(byte theByte) { bool thesign = theByte == '-'; - if (thesign) - { - if (!NextChar(theByte)) - { + if (thesign) { + if (!NextChar(theByte)) { return HandleSymbol('-'); } - if (theByte == '.') - { + if (theByte == '.') { return HandleDecimal(thesign); } - if ((theByte < '0') || (theByte > '9')) - { + if ((theByte < '0') || (theByte > '9')) { PutBackChar(theByte); return HandleSymbol('-'); } } - if (theByte == '0') - { + if (theByte == '0') { return HandleOctal(thesign); } long value = 0; bool digithit = false; - while((theByte >= '0') && (theByte <= '9')) - { + while ((theByte >= '0') && (theByte <= '9')) { value = (value * 10) + (theByte - '0'); - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); } digithit = true; } - if (theByte == '.') - { - if (digithit) - { + if (theByte == '.') { + if (digithit) { return HandleFloat(thesign, value); } - if (thesign) - { + if (thesign) { PutBackChar(theByte); theByte = '-'; } return HandleSymbol(theByte); } PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); } -CToken* CTokenizer::HandleOctal(bool thesign) -{ +CToken *CTokenizer::HandleOctal(bool thesign) { byte theByte; int value = 0; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { return CIntToken::Create(value); } - if (theByte == '.') - { + if (theByte == '.') { return HandleDecimal(thesign); } - if ((theByte == 'x') || (theByte == 'X')) - { + if ((theByte == 'x') || (theByte == 'X')) { return HandleHex(thesign); } - while(true) - { - if((theByte >= '0') && (theByte <='7')) - { + while (true) { + if ((theByte >= '0') && (theByte <= '7')) { value = (value * 8) + (theByte - '0'); - } - else - { + } else { PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); } - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); @@ -2324,23 +1750,18 @@ CToken* CTokenizer::HandleOctal(bool thesign) } } -CToken* CTokenizer::HandleHex(bool thesign) -{ +CToken *CTokenizer::HandleHex(bool thesign) { int value = 0; - while (true) - { + while (true) { byte theByte; - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); } - switch (theByte) - { + switch (theByte) { case '0': case '1': case '2': @@ -2371,8 +1792,7 @@ CToken* CTokenizer::HandleHex(bool thesign) break; default: PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); @@ -2381,44 +1801,34 @@ CToken* CTokenizer::HandleHex(bool thesign) } } -CToken* CTokenizer::HandleDecimal(bool thesign) -{ +CToken *CTokenizer::HandleDecimal(bool thesign) { byte theByte; - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { PutBackChar('.'); return HandleSymbol('-'); } HandleSymbol('.'); } PutBackChar(theByte); - if ((theByte <= '9') && (theByte >= '0')) - { + if ((theByte <= '9') && (theByte >= '0')) { return HandleFloat(thesign); } - if (thesign) - { + if (thesign) { PutBackChar('.'); theByte = '-'; - } - else - { + } else { theByte = '.'; } return HandleSymbol(theByte); } -CToken* CTokenizer::HandleFloat(bool thesign, long value) -{ +CToken *CTokenizer::HandleFloat(bool thesign, long value) { float lower = 1.0; float newValue = (float)value; byte theByte; - while(NextChar(theByte)) - { - if ((theByte >= '0') && (theByte <= '9')) - { + while (NextChar(theByte)) { + if ((theByte >= '0') && (theByte <= '9')) { lower = lower / 10; newValue = newValue + ((theByte - '0') * lower); continue; @@ -2426,33 +1836,27 @@ CToken* CTokenizer::HandleFloat(bool thesign, long value) PutBackChar(theByte); break; } - if (thesign) - { + if (thesign) { newValue = -newValue; } return CFloatToken::Create(newValue); } -CToken* CTokenizer::HandleQuote() -{ +CToken *CTokenizer::HandleQuote() { byte theByte; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { Error(TKERR_EXPECTED_CHAR); return NULL; } - if (theByte == '\\') - { + if (theByte == '\\') { theByte = Escapement(); } byte dummy; - if (!NextChar(dummy)) - { + if (!NextChar(dummy)) { Error(TKERR_EXPECTED_CHAR); return NULL; } - if (dummy != '\'') - { + if (dummy != '\'') { PutBackChar(dummy); PutBackChar(theByte); Error(TKERR_EXPECTED_CHAR); @@ -2461,47 +1865,33 @@ CToken* CTokenizer::HandleQuote() return CCharToken::Create(theByte); } -void CTokenizer::SetFlags(UINT flags) -{ - m_flags = flags; -} +void CTokenizer::SetFlags(UINT flags) { m_flags = flags; } -UINT CTokenizer::GetFlags() -{ - return m_flags; -} +UINT CTokenizer::GetFlags() { return m_flags; } -CToken* CTokenizer::HandleSymbol(byte theByte) -{ +CToken *CTokenizer::HandleSymbol(byte theByte) { char symbolString[128]; int curStrLen = 0; symbolString[0] = '\0'; bool consumed = false; - CSymbolLookup* curLookup; - if ((m_flags & TKF_RAWSYMBOLSONLY) == 0) - { + CSymbolLookup *curLookup; + if ((m_flags & TKF_RAWSYMBOLSONLY) == 0) { curLookup = m_symbolLookup; - } - else - { + } else { curLookup = NULL; } - CSymbolLookup* lastLookup = NULL; - while(curLookup != NULL) - { - if (curLookup->GetByte() == theByte) - { + CSymbolLookup *lastLookup = NULL; + while (curLookup != NULL) { + if (curLookup->GetByte() == theByte) { symbolString[curStrLen++] = theByte; symbolString[curStrLen] = '\0'; lastLookup = curLookup; consumed = true; - if (curLookup->GetChild() == NULL) - { + if (curLookup->GetChild() == NULL) { break; } - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { PutBackToken(CToken::Create()); break; } @@ -2511,60 +1901,44 @@ CToken* CTokenizer::HandleSymbol(byte theByte) } curLookup = curLookup->GetNext(); } - if ((!consumed) && (lastLookup != NULL)) - { + if ((!consumed) && (lastLookup != NULL)) { PutBackChar(theByte); } - while ((lastLookup != NULL) && (lastLookup->GetValue() == -1)) - { + while ((lastLookup != NULL) && (lastLookup->GetValue() == -1)) { curStrLen--; symbolString[curStrLen] = '\0'; - // symbolString = symbolString.Left(symbolString.GetLength() - 1); - if (lastLookup->GetParent() == NULL) - { - if ((m_flags & TKF_WANTUNDEFINED) == 0) - { + // symbolString = symbolString.Left(symbolString.GetLength() - 1); + if (lastLookup->GetParent() == NULL) { + if ((m_flags & TKF_WANTUNDEFINED) == 0) { Error(TKERR_UNRECOGNIZEDSYMBOL); } - } - else - { + } else { PutBackChar(lastLookup->GetByte()); } lastLookup = lastLookup->GetParent(); } - if (lastLookup == NULL) - { - if ((m_flags & TKF_WANTUNDEFINED) == 0) - { + if (lastLookup == NULL) { + if ((m_flags & TKF_WANTUNDEFINED) == 0) { return NULL; } curStrLen = 0; symbolString[curStrLen++] = char(theByte); symbolString[curStrLen] = '\0'; - if ((m_flags & TKF_WIDEUNDEFINEDSYMBOLS) != 0) - { - while (true) - { - if (!NextChar(theByte)) - { + if ((m_flags & TKF_WIDEUNDEFINEDSYMBOLS) != 0) { + while (true) { + if (!NextChar(theByte)) { PutBackToken(CToken::Create()); break; } - if (theByte == ' ') - { + if (theByte == ' ') { break; } - if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || - ((theByte >= '0') && (theByte <= '9'))) - { + if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || ((theByte >= '0') && (theByte <= '9'))) { PutBackChar(theByte); break; } - if (theByte < ' ') - { - if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) - { + if (theByte < ' ') { + if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) { PutBackToken(CUserToken::Create(TK_EOL, "-EOLN-")); break; } @@ -2579,37 +1953,31 @@ CToken* CTokenizer::HandleSymbol(byte theByte) return CUserToken::Create(lastLookup->GetValue(), symbolString); } -CToken* CTokenizer::HandleDirective() -{ +CToken *CTokenizer::HandleDirective() { int tokenValue = 0; - CToken* theToken = FetchToken(); - if (theToken->GetType() == TK_EOF) - { + CToken *theToken = FetchToken(); + if (theToken->GetType() == TK_EOF) { return theToken; } - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_INVALID_DIRECTIVE); theToken->Delete(); SkipToLineEnd(); return NULL; } - CDirectiveSymbol* curSymbol; - CTokenizerState* state; + CDirectiveSymbol *curSymbol; + CTokenizerState *state; int theDirective = DirectiveFromName(theToken->GetStringValue()); theToken->Delete(); byte theByte; - switch(theDirective) - { + switch (theDirective) { case DIR_INCLUDE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_STRING) - { + if (theToken->GetType() != TK_STRING) { Error(TKERR_INCLUDE_FILE_NOTFOUND); theToken->Delete(); SkipToLineEnd(); @@ -2619,16 +1987,14 @@ CToken* CTokenizer::HandleDirective() theToken->Delete(); break; case DIR_IFDEF: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { state = CTokenizerHolderState::Create(); state->SetNext(m_state); m_state = state; break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2640,16 +2006,14 @@ CToken* CTokenizer::HandleDirective() m_state = state; break; case DIR_IFNDEF: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { state = CTokenizerHolderState::Create(); state->SetNext(m_state); m_state = state; break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2661,8 +2025,7 @@ CToken* CTokenizer::HandleDirective() m_state = state; break; case DIR_ENDIF: - if (m_state == NULL) - { + if (m_state == NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } @@ -2671,25 +2034,21 @@ CToken* CTokenizer::HandleDirective() state->Delete(); break; case DIR_ELSE: - if (m_state == NULL) - { + if (m_state == NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } - if (!m_state->ProcessElse()) - { + if (!m_state->ProcessElse()) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } break; case DIR_DEFINE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2700,30 +2059,25 @@ CToken* CTokenizer::HandleDirective() curSymbol = CDirectiveSymbol::Create(theToken->GetStringValue()); char temp[128]; int tempsize = 0; - while(NextChar(theByte)) - { - if (theByte == '\n') - { + while (NextChar(theByte)) { + if (theByte == '\n') { break; } temp[tempsize++] = char(theByte); } temp[tempsize] = '\0'; curSymbol->SetValue(temp); - if (!m_defines.AddSymbol(curSymbol)) - { + if (!m_defines.AddSymbol(curSymbol)) { curSymbol->Delete(); } } break; case DIR_UNDEFINE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2739,11 +2093,9 @@ CToken* CTokenizer::HandleDirective() return NULL; } -COLORREF CTokenizer::ParseRGB() -{ - CToken* theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { +COLORREF CTokenizer::ParseRGB() { + CToken *theToken = GetToken(); + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2751,8 +2103,7 @@ COLORREF CTokenizer::ParseRGB() int red = theToken->GetIntValue(); theToken->Delete(); theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2760,8 +2111,7 @@ COLORREF CTokenizer::ParseRGB() int green = theToken->GetIntValue(); theToken->Delete(); theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2775,38 +2125,29 @@ COLORREF CTokenizer::ParseRGB() // CSymbolLookup // -CSymbolLookup::CSymbolLookup() -{ -} +CSymbolLookup::CSymbolLookup() {} -CSymbolLookup::~CSymbolLookup() -{ -} +CSymbolLookup::~CSymbolLookup() {} -CSymbolLookup* CSymbolLookup::Create(byte theByte) -{ - CSymbolLookup* curLookup = new CSymbolLookup(); +CSymbolLookup *CSymbolLookup::Create(byte theByte) { + CSymbolLookup *curLookup = new CSymbolLookup(); curLookup->Init(theByte); return curLookup; } -void CSymbolLookup::Delete() -{ - if (m_sibling != NULL) - { +void CSymbolLookup::Delete() { + if (m_sibling != NULL) { m_sibling->Delete(); m_sibling = NULL; } - if (m_child != NULL) - { + if (m_child != NULL) { m_child->Delete(); m_child = NULL; } delete this; } -void CSymbolLookup::Init(byte theByte) -{ +void CSymbolLookup::Init(byte theByte) { m_parent = NULL; m_child = NULL; m_sibling = NULL; @@ -2814,47 +2155,20 @@ void CSymbolLookup::Init(byte theByte) m_byte = theByte; } -CSymbolLookup* CSymbolLookup::GetNext() -{ - return m_sibling; -} +CSymbolLookup *CSymbolLookup::GetNext() { return m_sibling; } -void CSymbolLookup::SetNext(CSymbolLookup* next) -{ - m_sibling = next; -} +void CSymbolLookup::SetNext(CSymbolLookup *next) { m_sibling = next; } -void CSymbolLookup::SetParent(CSymbolLookup* parent) -{ - m_parent = parent; -} +void CSymbolLookup::SetParent(CSymbolLookup *parent) { m_parent = parent; } -void CSymbolLookup::SetValue(int value) -{ - m_value = value; -} +void CSymbolLookup::SetValue(int value) { m_value = value; } -int CSymbolLookup::GetValue() -{ - return m_value; -} +int CSymbolLookup::GetValue() { return m_value; } -byte CSymbolLookup::GetByte() -{ - return m_byte; -} +byte CSymbolLookup::GetByte() { return m_byte; } -CSymbolLookup** CSymbolLookup::GetChildAddress() -{ - return &m_child; -} +CSymbolLookup **CSymbolLookup::GetChildAddress() { return &m_child; } -CSymbolLookup* CSymbolLookup::GetChild() -{ - return m_child; -} +CSymbolLookup *CSymbolLookup::GetChild() { return m_child; } -CSymbolLookup* CSymbolLookup::GetParent() -{ - return m_parent; -} +CSymbolLookup *CSymbolLookup::GetParent() { return m_parent; } diff --git a/codemp/botlib/be_aas_bspq3.cpp b/codemp/botlib/be_aas_bspq3.cpp index 522b8250e2..d7a8819ecb 100644 --- a/codemp/botlib/be_aas_bspq3.cpp +++ b/codemp/botlib/be_aas_bspq3.cpp @@ -49,96 +49,84 @@ extern botlib_import_t botimport; //#define TRACE_DEBUG -#define ON_EPSILON 0.005 +#define ON_EPSILON 0.005 -#define MAX_BSPENTITIES 2048 +#define MAX_BSPENTITIES 2048 -typedef struct rgb_s -{ +typedef struct rgb_s { int red; int green; int blue; } rgb_t; -//bsp entity epair -typedef struct bsp_epair_s -{ +// bsp entity epair +typedef struct bsp_epair_s { char *key; char *value; struct bsp_epair_s *next; } bsp_epair_t; -//bsp data entity -typedef struct bsp_entity_s -{ +// bsp data entity +typedef struct bsp_entity_s { bsp_epair_t *epairs; } bsp_entity_t; -//id Sofware BSP data -typedef struct bsp_s -{ - //true when bsp file is loaded +// id Sofware BSP data +typedef struct bsp_s { + // true when bsp file is loaded int loaded; - //entity data + // entity data int entdatasize; char *dentdata; - //bsp entities + // bsp entities int numentities; bsp_entity_t entities[MAX_BSPENTITIES]; } bsp_t; -//global bsp +// global bsp bsp_t bspworld; - #ifdef BSP_DEBUG -typedef struct cname_s -{ +typedef struct cname_s { int value; char *name; } cname_t; -cname_t contentnames[] = -{ - {CONTENTS_SOLID,"CONTENTS_SOLID"}, - {CONTENTS_WINDOW,"CONTENTS_WINDOW"}, - {CONTENTS_AUX,"CONTENTS_AUX"}, - {CONTENTS_LAVA,"CONTENTS_LAVA"}, - {CONTENTS_SLIME,"CONTENTS_SLIME"}, - {CONTENTS_WATER,"CONTENTS_WATER"}, - {CONTENTS_MIST,"CONTENTS_MIST"}, - {LAST_VISIBLE_CONTENTS,"LAST_VISIBLE_CONTENTS"}, - - {CONTENTS_AREAPORTAL,"CONTENTS_AREAPORTAL"}, - {CONTENTS_PLAYERCLIP,"CONTENTS_PLAYERCLIP"}, - {CONTENTS_MONSTERCLIP,"CONTENTS_MONSTERCLIP"}, - {CONTENTS_CURRENT_0,"CONTENTS_CURRENT_0"}, - {CONTENTS_CURRENT_90,"CONTENTS_CURRENT_90"}, - {CONTENTS_CURRENT_180,"CONTENTS_CURRENT_180"}, - {CONTENTS_CURRENT_270,"CONTENTS_CURRENT_270"}, - {CONTENTS_CURRENT_UP,"CONTENTS_CURRENT_UP"}, - {CONTENTS_CURRENT_DOWN,"CONTENTS_CURRENT_DOWN"}, - {CONTENTS_ORIGIN,"CONTENTS_ORIGIN"}, - {CONTENTS_MONSTER,"CONTENTS_MONSTER"}, - {CONTENTS_DEADMONSTER,"CONTENTS_DEADMONSTER"}, - {CONTENTS_DETAIL,"CONTENTS_DETAIL"}, - {CONTENTS_TRANSLUCENT,"CONTENTS_TRANSLUCENT"}, - {CONTENTS_LADDER,"CONTENTS_LADDER"}, - {0, 0} -}; - -void PrintContents(int contents) -{ +cname_t contentnames[] = {{CONTENTS_SOLID, "CONTENTS_SOLID"}, + {CONTENTS_WINDOW, "CONTENTS_WINDOW"}, + {CONTENTS_AUX, "CONTENTS_AUX"}, + {CONTENTS_LAVA, "CONTENTS_LAVA"}, + {CONTENTS_SLIME, "CONTENTS_SLIME"}, + {CONTENTS_WATER, "CONTENTS_WATER"}, + {CONTENTS_MIST, "CONTENTS_MIST"}, + {LAST_VISIBLE_CONTENTS, "LAST_VISIBLE_CONTENTS"}, + + {CONTENTS_AREAPORTAL, "CONTENTS_AREAPORTAL"}, + {CONTENTS_PLAYERCLIP, "CONTENTS_PLAYERCLIP"}, + {CONTENTS_MONSTERCLIP, "CONTENTS_MONSTERCLIP"}, + {CONTENTS_CURRENT_0, "CONTENTS_CURRENT_0"}, + {CONTENTS_CURRENT_90, "CONTENTS_CURRENT_90"}, + {CONTENTS_CURRENT_180, "CONTENTS_CURRENT_180"}, + {CONTENTS_CURRENT_270, "CONTENTS_CURRENT_270"}, + {CONTENTS_CURRENT_UP, "CONTENTS_CURRENT_UP"}, + {CONTENTS_CURRENT_DOWN, "CONTENTS_CURRENT_DOWN"}, + {CONTENTS_ORIGIN, "CONTENTS_ORIGIN"}, + {CONTENTS_MONSTER, "CONTENTS_MONSTER"}, + {CONTENTS_DEADMONSTER, "CONTENTS_DEADMONSTER"}, + {CONTENTS_DETAIL, "CONTENTS_DETAIL"}, + {CONTENTS_TRANSLUCENT, "CONTENTS_TRANSLUCENT"}, + {CONTENTS_LADDER, "CONTENTS_LADDER"}, + {0, 0}}; + +void PrintContents(int contents) { int i; - for (i = 0; contentnames[i].value; i++) - { - if (contents & contentnames[i].value) - { + for (i = 0; contentnames[i].value; i++) { + if (contents & contentnames[i].value) { botimport.Print(PRT_MESSAGE, "%s\n", contentnames[i].name); - } //end if - } //end for -} //end of the function PrintContents + } // end if + } // end for +} // end of the function PrintContents #endif // BSP_DEBUG //=========================================================================== @@ -148,12 +136,11 @@ void PrintContents(int contents) // Returns: - // Changes Globals: - //=========================================================================== -bsp_trace_t AAS_Trace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask) -{ +bsp_trace_t AAS_Trace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int passent, int contentmask) { bsp_trace_t bsptrace; botimport.Trace(&bsptrace, start, mins, maxs, end, passent, contentmask); return bsptrace; -} //end of the function AAS_Trace +} // end of the function AAS_Trace //=========================================================================== // returns the contents at the given point // @@ -161,30 +148,23 @@ bsp_trace_t AAS_Trace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int pa // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PointContents(vec3_t point) -{ - return botimport.PointContents(point); -} //end of the function AAS_PointContents +int AAS_PointContents(vec3_t point) { return botimport.PointContents(point); } // end of the function AAS_PointContents //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_EntityCollision(int entnum, - vec3_t start, vec3_t boxmins, vec3_t boxmaxs, vec3_t end, - int contentmask, bsp_trace_t *trace) -{ +qboolean AAS_EntityCollision(int entnum, vec3_t start, vec3_t boxmins, vec3_t boxmaxs, vec3_t end, int contentmask, bsp_trace_t *trace) { bsp_trace_t enttrace; botimport.EntityTrace(&enttrace, start, boxmins, boxmaxs, end, entnum, contentmask); - if (enttrace.fraction < trace->fraction) - { + if (enttrace.fraction < trace->fraction) { Com_Memcpy(trace, &enttrace, sizeof(bsp_trace_t)); return qtrue; - } //end if + } // end if return qfalse; -} //end of the function AAS_EntityCollision +} // end of the function AAS_EntityCollision //=========================================================================== // returns true if in Potentially Hearable Set // @@ -192,10 +172,7 @@ qboolean AAS_EntityCollision(int entnum, // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_inPVS(vec3_t p1, vec3_t p2) -{ - return (qboolean)botimport.inPVS(p1, p2); -} //end of the function AAS_InPVS +qboolean AAS_inPVS(vec3_t p1, vec3_t p2) { return (qboolean)botimport.inPVS(p1, p2); } // end of the function AAS_InPVS //=========================================================================== // returns true if in Potentially Visible Set // @@ -203,20 +180,16 @@ qboolean AAS_inPVS(vec3_t p1, vec3_t p2) // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_inPHS(vec3_t p1, vec3_t p2) -{ - return qtrue; -} //end of the function AAS_inPHS +qboolean AAS_inPHS(vec3_t p1, vec3_t p2) { return qtrue; } // end of the function AAS_inPHS //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin) -{ +void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t maxs, vec3_t origin) { botimport.BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin); -} //end of the function AAS_BSPModelMinsMaxs +} // end of the function AAS_BSPModelMinsMaxs //=========================================================================== // unlinks the entity from all leaves // @@ -224,254 +197,231 @@ void AAS_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t mins, vec3_t // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves) -{ -} //end of the function AAS_UnlinkFromBSPLeaves +void AAS_UnlinkFromBSPLeaves(bsp_link_t *leaves) {} // end of the function AAS_UnlinkFromBSPLeaves //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum, int modelnum) -{ - return NULL; -} //end of the function AAS_BSPLinkEntity +bsp_link_t *AAS_BSPLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum, int modelnum) { return NULL; } // end of the function AAS_BSPLinkEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount) -{ - return 0; -} //end of the function AAS_BoxEntities +int AAS_BoxEntities(vec3_t absmins, vec3_t absmaxs, int *list, int maxcount) { return 0; } // end of the function AAS_BoxEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NextBSPEntity(int ent) -{ +int AAS_NextBSPEntity(int ent) { ent++; - if (ent >= 1 && ent < bspworld.numentities) return ent; + if (ent >= 1 && ent < bspworld.numentities) + return ent; return 0; -} //end of the function AAS_NextBSPEntity +} // end of the function AAS_NextBSPEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BSPEntityInRange(int ent) -{ - if (ent <= 0 || ent >= bspworld.numentities) - { +int AAS_BSPEntityInRange(int ent) { + if (ent <= 0 || ent >= bspworld.numentities) { botimport.Print(PRT_MESSAGE, "bsp entity out of range\n"); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function AAS_BSPEntityInRange +} // end of the function AAS_BSPEntityInRange //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) -{ +int AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) { bsp_epair_t *epair; value[0] = '\0'; - if (!AAS_BSPEntityInRange(ent)) return qfalse; - for (epair = bspworld.entities[ent].epairs; epair; epair = epair->next) - { - if (!strcmp(epair->key, key)) - { - strncpy(value, epair->value, size-1); - value[size-1] = '\0'; + if (!AAS_BSPEntityInRange(ent)) + return qfalse; + for (epair = bspworld.entities[ent].epairs; epair; epair = epair->next) { + if (!strcmp(epair->key, key)) { + strncpy(value, epair->value, size - 1); + value[size - 1] = '\0'; return qtrue; - } //end if - } //end for + } // end if + } // end for return qfalse; -} //end of the function AAS_FindBSPEpair +} // end of the function AAS_FindBSPEpair //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) -{ +int AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) { char buf[MAX_EPAIRKEY]; double v1, v2, v3; VectorClear(v); - if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse; - //scanf into doubles, then assign, so it is float size independent + if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) + return qfalse; + // scanf into doubles, then assign, so it is float size independent v1 = v2 = v3 = 0; sscanf(buf, "%lf %lf %lf", &v1, &v2, &v3); v[0] = v1; v[1] = v2; v[2] = v3; return qtrue; -} //end of the function AAS_VectorForBSPEpairKey +} // end of the function AAS_VectorForBSPEpairKey //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FloatForBSPEpairKey(int ent, char *key, float *value) -{ +int AAS_FloatForBSPEpairKey(int ent, char *key, float *value) { char buf[MAX_EPAIRKEY]; *value = 0; - if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse; + if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) + return qfalse; *value = atof(buf); return qtrue; -} //end of the function AAS_FloatForBSPEpairKey +} // end of the function AAS_FloatForBSPEpairKey //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_IntForBSPEpairKey(int ent, char *key, int *value) -{ +int AAS_IntForBSPEpairKey(int ent, char *key, int *value) { char buf[MAX_EPAIRKEY]; *value = 0; - if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) return qfalse; + if (!AAS_ValueForBSPEpairKey(ent, key, buf, MAX_EPAIRKEY)) + return qfalse; *value = atoi(buf); return qtrue; -} //end of the function AAS_IntForBSPEpairKey +} // end of the function AAS_IntForBSPEpairKey //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeBSPEntities(void) -{ +void AAS_FreeBSPEntities(void) { int i; bsp_entity_t *ent; bsp_epair_t *epair, *nextepair; - for (i = 1; i < bspworld.numentities; i++) - { + for (i = 1; i < bspworld.numentities; i++) { ent = &bspworld.entities[i]; - for (epair = ent->epairs; epair; epair = nextepair) - { + for (epair = ent->epairs; epair; epair = nextepair) { nextepair = epair->next; // - if (epair->key) FreeMemory(epair->key); - if (epair->value) FreeMemory(epair->value); + if (epair->key) + FreeMemory(epair->key); + if (epair->value) + FreeMemory(epair->value); FreeMemory(epair); - } //end for - } //end for + } // end for + } // end for bspworld.numentities = 0; -} //end of the function AAS_FreeBSPEntities +} // end of the function AAS_FreeBSPEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ParseBSPEntities(void) -{ +void AAS_ParseBSPEntities(void) { script_t *script; token_t token; bsp_entity_t *ent; bsp_epair_t *epair; script = LoadScriptMemory(bspworld.dentdata, bspworld.entdatasize, "entdata"); - SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES|SCFL_NOSTRINGESCAPECHARS);//SCFL_PRIMITIVE); + SetScriptFlags(script, SCFL_NOSTRINGWHITESPACES | SCFL_NOSTRINGESCAPECHARS); // SCFL_PRIMITIVE); bspworld.numentities = 1; - while(PS_ReadToken(script, &token)) - { - if (strcmp(token.string, "{")) - { + while (PS_ReadToken(script, &token)) { + if (strcmp(token.string, "{")) { ScriptError(script, "invalid %s", token.string); AAS_FreeBSPEntities(); FreeScript(script); return; - } //end if - if (bspworld.numentities >= MAX_BSPENTITIES) - { + } // end if + if (bspworld.numentities >= MAX_BSPENTITIES) { botimport.Print(PRT_MESSAGE, "too many entities in BSP file\n"); break; - } //end if + } // end if ent = &bspworld.entities[bspworld.numentities]; bspworld.numentities++; ent->epairs = NULL; - while(PS_ReadToken(script, &token)) - { - if (!strcmp(token.string, "}")) break; - epair = (bsp_epair_t *) GetClearedHunkMemory(sizeof(bsp_epair_t)); + while (PS_ReadToken(script, &token)) { + if (!strcmp(token.string, "}")) + break; + epair = (bsp_epair_t *)GetClearedHunkMemory(sizeof(bsp_epair_t)); epair->next = ent->epairs; ent->epairs = epair; - if (token.type != TT_STRING) - { + if (token.type != TT_STRING) { ScriptError(script, "invalid %s", token.string); AAS_FreeBSPEntities(); FreeScript(script); return; - } //end if + } // end if StripDoubleQuotes(token.string); - epair->key = (char *) GetHunkMemory(strlen(token.string) + 1); + epair->key = (char *)GetHunkMemory(strlen(token.string) + 1); strcpy(epair->key, token.string); - if (!PS_ExpectTokenType(script, TT_STRING, 0, &token)) - { + if (!PS_ExpectTokenType(script, TT_STRING, 0, &token)) { AAS_FreeBSPEntities(); FreeScript(script); return; - } //end if + } // end if StripDoubleQuotes(token.string); - epair->value = (char *) GetHunkMemory(strlen(token.string) + 1); + epair->value = (char *)GetHunkMemory(strlen(token.string) + 1); strcpy(epair->value, token.string); - } //end while - if (strcmp(token.string, "}")) - { + } // end while + if (strcmp(token.string, "}")) { ScriptError(script, "missing }"); AAS_FreeBSPEntities(); FreeScript(script); return; - } //end if - } //end while + } // end if + } // end while FreeScript(script); -} //end of the function AAS_ParseBSPEntities +} // end of the function AAS_ParseBSPEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BSPTraceLight(vec3_t start, vec3_t end, vec3_t endpos, int *red, int *green, int *blue) -{ - return 0; -} //end of the function AAS_BSPTraceLight +int AAS_BSPTraceLight(vec3_t start, vec3_t end, vec3_t endpos, int *red, int *green, int *blue) { return 0; } // end of the function AAS_BSPTraceLight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DumpBSPData(void) -{ +void AAS_DumpBSPData(void) { AAS_FreeBSPEntities(); - if (bspworld.dentdata) FreeMemory(bspworld.dentdata); + if (bspworld.dentdata) + FreeMemory(bspworld.dentdata); bspworld.dentdata = NULL; bspworld.entdatasize = 0; // bspworld.loaded = qfalse; - Com_Memset( &bspworld, 0, sizeof(bspworld) ); -} //end of the function AAS_DumpBSPData + Com_Memset(&bspworld, 0, sizeof(bspworld)); +} // end of the function AAS_DumpBSPData //=========================================================================== // load a .bsp file // @@ -479,13 +429,12 @@ void AAS_DumpBSPData(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_LoadBSPFile(void) -{ +int AAS_LoadBSPFile(void) { AAS_DumpBSPData(); bspworld.entdatasize = strlen(botimport.BSPEntityData()) + 1; - bspworld.dentdata = (char *) GetClearedHunkMemory(bspworld.entdatasize); + bspworld.dentdata = (char *)GetClearedHunkMemory(bspworld.entdatasize); Com_Memcpy(bspworld.dentdata, botimport.BSPEntityData(), bspworld.entdatasize); AAS_ParseBSPEntities(); bspworld.loaded = qtrue; return BLERR_NOERROR; -} //end of the function AAS_LoadBSPFile +} // end of the function AAS_LoadBSPFile diff --git a/codemp/botlib/be_aas_cluster.cpp b/codemp/botlib/be_aas_cluster.cpp index c4b3152f4c..dd01520df3 100644 --- a/codemp/botlib/be_aas_cluster.cpp +++ b/codemp/botlib/be_aas_cluster.cpp @@ -50,11 +50,11 @@ along with this program; if not, see . extern botlib_import_t botimport; -#define AAS_MAX_PORTALS 65536 -#define AAS_MAX_PORTALINDEXSIZE 65536 -#define AAS_MAX_CLUSTERS 65536 +#define AAS_MAX_PORTALS 65536 +#define AAS_MAX_PORTALINDEXSIZE 65536 +#define AAS_MAX_CLUSTERS 65536 // -#define MAX_PORTALAREAS 1024 +#define MAX_PORTALAREAS 1024 // do not flood through area faces, only use reachabilities int nofaceflood = qtrue; @@ -65,186 +65,165 @@ int nofaceflood = qtrue; // Returns: - // Changes Globals: - //=========================================================================== -void AAS_RemoveClusterAreas(void) -{ +void AAS_RemoveClusterAreas(void) { int i; - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { aasworld.areasettings[i].cluster = 0; - } //end for -} //end of the function AAS_RemoveClusterAreas + } // end for +} // end of the function AAS_RemoveClusterAreas //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ClearCluster(int clusternum) -{ +void AAS_ClearCluster(int clusternum) { int i; - for (i = 1; i < aasworld.numareas; i++) - { - if (aasworld.areasettings[i].cluster == clusternum) - { + for (i = 1; i < aasworld.numareas; i++) { + if (aasworld.areasettings[i].cluster == clusternum) { aasworld.areasettings[i].cluster = 0; - } //end if - } //end for -} //end of the function AAS_ClearCluster + } // end if + } // end for +} // end of the function AAS_ClearCluster //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_RemovePortalsClusterReference(int clusternum) -{ +void AAS_RemovePortalsClusterReference(int clusternum) { int portalnum; - for (portalnum = 1; portalnum < aasworld.numportals; portalnum++) - { - if (aasworld.portals[portalnum].frontcluster == clusternum) - { + for (portalnum = 1; portalnum < aasworld.numportals; portalnum++) { + if (aasworld.portals[portalnum].frontcluster == clusternum) { aasworld.portals[portalnum].frontcluster = 0; - } //end if - if (aasworld.portals[portalnum].backcluster == clusternum) - { + } // end if + if (aasworld.portals[portalnum].backcluster == clusternum) { aasworld.portals[portalnum].backcluster = 0; - } //end if - } //end for -} //end of the function AAS_RemovePortalsClusterReference + } // end if + } // end for +} // end of the function AAS_RemovePortalsClusterReference //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_UpdatePortal(int areanum, int clusternum) -{ +int AAS_UpdatePortal(int areanum, int clusternum) { int portalnum; aas_portal_t *portal; aas_cluster_t *cluster; - //find the portal of the area - for (portalnum = 1; portalnum < aasworld.numportals; portalnum++) - { - if (aasworld.portals[portalnum].areanum == areanum) break; - } //end for + // find the portal of the area + for (portalnum = 1; portalnum < aasworld.numportals; portalnum++) { + if (aasworld.portals[portalnum].areanum == areanum) + break; + } // end for // - if (portalnum == aasworld.numportals) - { + if (portalnum == aasworld.numportals) { AAS_Error("no portal of area %d\n", areanum); return qtrue; - } //end if + } // end if // portal = &aasworld.portals[portalnum]; - //if the portal is already fully updated - if (portal->frontcluster == clusternum) return qtrue; - if (portal->backcluster == clusternum) return qtrue; - //if the portal has no front cluster yet - if (!portal->frontcluster) - { + // if the portal is already fully updated + if (portal->frontcluster == clusternum) + return qtrue; + if (portal->backcluster == clusternum) + return qtrue; + // if the portal has no front cluster yet + if (!portal->frontcluster) { portal->frontcluster = clusternum; - } //end if - //if the portal has no back cluster yet - else if (!portal->backcluster) - { + } // end if + // if the portal has no back cluster yet + else if (!portal->backcluster) { portal->backcluster = clusternum; - } //end else if - else - { - //remove the cluster portal flag contents + } // end else if + else { + // remove the cluster portal flag contents aasworld.areasettings[areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL; Log_Write("portal area %d is separating more than two clusters\r\n", areanum); return qfalse; - } //end else - if (aasworld.portalindexsize >= AAS_MAX_PORTALINDEXSIZE) - { + } // end else + if (aasworld.portalindexsize >= AAS_MAX_PORTALINDEXSIZE) { AAS_Error("AAS_MAX_PORTALINDEXSIZE\n"); return qtrue; - } //end if - //set the area cluster number to the negative portal number + } // end if + // set the area cluster number to the negative portal number aasworld.areasettings[areanum].cluster = -portalnum; - //add the portal to the cluster using the portal index + // add the portal to the cluster using the portal index cluster = &aasworld.clusters[clusternum]; aasworld.portalindex[cluster->firstportal + cluster->numportals] = portalnum; aasworld.portalindexsize++; cluster->numportals++; return qtrue; -} //end of the function AAS_UpdatePortal +} // end of the function AAS_UpdatePortal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FloodClusterAreas_r(int areanum, int clusternum) -{ +int AAS_FloodClusterAreas_r(int areanum, int clusternum) { aas_area_t *area; aas_face_t *face; int facenum, i; // - if (areanum <= 0 || areanum >= aasworld.numareas) - { + if (areanum <= 0 || areanum >= aasworld.numareas) { AAS_Error("AAS_FloodClusterAreas_r: areanum out of range\n"); return qfalse; - } //end if - //if the area is already part of a cluster - if (aasworld.areasettings[areanum].cluster > 0) - { - if (aasworld.areasettings[areanum].cluster == clusternum) return qtrue; + } // end if + // if the area is already part of a cluster + if (aasworld.areasettings[areanum].cluster > 0) { + if (aasworld.areasettings[areanum].cluster == clusternum) + return qtrue; // - //there's a reachability going from one cluster to another only in one direction + // there's a reachability going from one cluster to another only in one direction // - AAS_Error("cluster %d touched cluster %d at area %d\n", - clusternum, aasworld.areasettings[areanum].cluster, areanum); + AAS_Error("cluster %d touched cluster %d at area %d\n", clusternum, aasworld.areasettings[areanum].cluster, areanum); return qfalse; - } //end if - //don't add the cluster portal areas to the clusters - if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) - { + } // end if + // don't add the cluster portal areas to the clusters + if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) { return AAS_UpdatePortal(areanum, clusternum); - } //end if - //set the area cluster number + } // end if + // set the area cluster number aasworld.areasettings[areanum].cluster = clusternum; - aasworld.areasettings[areanum].clusterareanum = - aasworld.clusters[clusternum].numareas; - //the cluster has an extra area + aasworld.areasettings[areanum].clusterareanum = aasworld.clusters[clusternum].numareas; + // the cluster has an extra area aasworld.clusters[clusternum].numareas++; area = &aasworld.areas[areanum]; - //use area faces to flood into adjacent areas - if (!nofaceflood) - { - for (i = 0; i < area->numfaces; i++) - { + // use area faces to flood into adjacent areas + if (!nofaceflood) { + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); face = &aasworld.faces[facenum]; - if (face->frontarea == areanum) - { - if (face->backarea) if (!AAS_FloodClusterAreas_r(face->backarea, clusternum)) return qfalse; - } //end if - else - { - if (face->frontarea) if (!AAS_FloodClusterAreas_r(face->frontarea, clusternum)) return qfalse; - } //end else - } //end for - } //end if - //use the reachabilities to flood into other areas - for (i = 0; i < aasworld.areasettings[areanum].numreachableareas; i++) - { - if (!aasworld.reachability[ - aasworld.areasettings[areanum].firstreachablearea + i].areanum) - { + if (face->frontarea == areanum) { + if (face->backarea) + if (!AAS_FloodClusterAreas_r(face->backarea, clusternum)) + return qfalse; + } // end if + else { + if (face->frontarea) + if (!AAS_FloodClusterAreas_r(face->frontarea, clusternum)) + return qfalse; + } // end else + } // end for + } // end if + // use the reachabilities to flood into other areas + for (i = 0; i < aasworld.areasettings[areanum].numreachableareas; i++) { + if (!aasworld.reachability[aasworld.areasettings[areanum].firstreachablearea + i].areanum) { continue; - } //end if - if (!AAS_FloodClusterAreas_r(aasworld.reachability[ - aasworld.areasettings[areanum].firstreachablearea + i].areanum, clusternum)) return qfalse; - } //end for + } // end if + if (!AAS_FloodClusterAreas_r(aasworld.reachability[aasworld.areasettings[areanum].firstreachablearea + i].areanum, clusternum)) + return qfalse; + } // end for return qtrue; -} //end of the function AAS_FloodClusterAreas_r +} // end of the function AAS_FloodClusterAreas_r //=========================================================================== // try to flood from all areas without cluster into areas with a cluster set // @@ -252,218 +231,199 @@ int AAS_FloodClusterAreas_r(int areanum, int clusternum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FloodClusterAreasUsingReachabilities(int clusternum) -{ +int AAS_FloodClusterAreasUsingReachabilities(int clusternum) { int i, j, areanum; - for (i = 1; i < aasworld.numareas; i++) - { - //if this area already has a cluster set + for (i = 1; i < aasworld.numareas; i++) { + // if this area already has a cluster set if (aasworld.areasettings[i].cluster) continue; - //if this area is a cluster portal + // if this area is a cluster portal if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) continue; - //loop over the reachable areas from this area - for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++) - { - //the reachable area + // loop over the reachable areas from this area + for (j = 0; j < aasworld.areasettings[i].numreachableareas; j++) { + // the reachable area areanum = aasworld.reachability[aasworld.areasettings[i].firstreachablearea + j].areanum; - //if this area is a cluster portal + // if this area is a cluster portal if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) continue; - //if this area has a cluster set - if (aasworld.areasettings[areanum].cluster) - { + // if this area has a cluster set + if (aasworld.areasettings[areanum].cluster) { if (!AAS_FloodClusterAreas_r(i, clusternum)) return qfalse; i = 0; break; - } //end if - } //end for - } //end for + } // end if + } // end for + } // end for return qtrue; -} //end of the function AAS_FloodClusterAreasUsingReachabilities +} // end of the function AAS_FloodClusterAreasUsingReachabilities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_NumberClusterPortals(int clusternum) -{ +void AAS_NumberClusterPortals(int clusternum) { int i, portalnum; aas_cluster_t *cluster; aas_portal_t *portal; cluster = &aasworld.clusters[clusternum]; - for (i = 0; i < cluster->numportals; i++) - { + for (i = 0; i < cluster->numportals; i++) { portalnum = aasworld.portalindex[cluster->firstportal + i]; portal = &aasworld.portals[portalnum]; - if (portal->frontcluster == clusternum) - { + if (portal->frontcluster == clusternum) { portal->clusterareanum[0] = cluster->numareas++; - } //end if - else - { + } // end if + else { portal->clusterareanum[1] = cluster->numareas++; - } //end else - } //end for -} //end of the function AAS_NumberClusterPortals + } // end else + } // end for +} // end of the function AAS_NumberClusterPortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_NumberClusterAreas(int clusternum) -{ +void AAS_NumberClusterAreas(int clusternum) { int i, portalnum; aas_cluster_t *cluster; aas_portal_t *portal; aasworld.clusters[clusternum].numareas = 0; aasworld.clusters[clusternum].numreachabilityareas = 0; - //number all areas in this cluster WITH reachabilities - for (i = 1; i < aasworld.numareas; i++) - { + // number all areas in this cluster WITH reachabilities + for (i = 1; i < aasworld.numareas; i++) { // - if (aasworld.areasettings[i].cluster != clusternum) continue; + if (aasworld.areasettings[i].cluster != clusternum) + continue; // - if (!AAS_AreaReachability(i)) continue; + if (!AAS_AreaReachability(i)) + continue; // aasworld.areasettings[i].clusterareanum = aasworld.clusters[clusternum].numareas; - //the cluster has an extra area + // the cluster has an extra area aasworld.clusters[clusternum].numareas++; aasworld.clusters[clusternum].numreachabilityareas++; - } //end for - //number all portals in this cluster WITH reachabilities + } // end for + // number all portals in this cluster WITH reachabilities cluster = &aasworld.clusters[clusternum]; - for (i = 0; i < cluster->numportals; i++) - { + for (i = 0; i < cluster->numportals; i++) { portalnum = aasworld.portalindex[cluster->firstportal + i]; portal = &aasworld.portals[portalnum]; - if (!AAS_AreaReachability(portal->areanum)) continue; - if (portal->frontcluster == clusternum) - { + if (!AAS_AreaReachability(portal->areanum)) + continue; + if (portal->frontcluster == clusternum) { portal->clusterareanum[0] = cluster->numareas++; aasworld.clusters[clusternum].numreachabilityareas++; - } //end if - else - { + } // end if + else { portal->clusterareanum[1] = cluster->numareas++; aasworld.clusters[clusternum].numreachabilityareas++; - } //end else - } //end for - //number all areas in this cluster WITHOUT reachabilities - for (i = 1; i < aasworld.numareas; i++) - { + } // end else + } // end for + // number all areas in this cluster WITHOUT reachabilities + for (i = 1; i < aasworld.numareas; i++) { // - if (aasworld.areasettings[i].cluster != clusternum) continue; + if (aasworld.areasettings[i].cluster != clusternum) + continue; // - if (AAS_AreaReachability(i)) continue; + if (AAS_AreaReachability(i)) + continue; // aasworld.areasettings[i].clusterareanum = aasworld.clusters[clusternum].numareas; - //the cluster has an extra area + // the cluster has an extra area aasworld.clusters[clusternum].numareas++; - } //end for - //number all portals in this cluster WITHOUT reachabilities + } // end for + // number all portals in this cluster WITHOUT reachabilities cluster = &aasworld.clusters[clusternum]; - for (i = 0; i < cluster->numportals; i++) - { + for (i = 0; i < cluster->numportals; i++) { portalnum = aasworld.portalindex[cluster->firstportal + i]; portal = &aasworld.portals[portalnum]; - if (AAS_AreaReachability(portal->areanum)) continue; - if (portal->frontcluster == clusternum) - { + if (AAS_AreaReachability(portal->areanum)) + continue; + if (portal->frontcluster == clusternum) { portal->clusterareanum[0] = cluster->numareas++; - } //end if - else - { + } // end if + else { portal->clusterareanum[1] = cluster->numareas++; - } //end else - } //end for -} //end of the function AAS_NumberClusterAreas + } // end else + } // end for +} // end of the function AAS_NumberClusterAreas //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FindClusters(void) -{ +int AAS_FindClusters(void) { int i; aas_cluster_t *cluster; AAS_RemoveClusterAreas(); // - for (i = 1; i < aasworld.numareas; i++) - { - //if the area is already part of a cluster + for (i = 1; i < aasworld.numareas; i++) { + // if the area is already part of a cluster if (aasworld.areasettings[i].cluster) continue; // if not flooding through faces only use areas that have reachabilities - if (nofaceflood) - { + if (nofaceflood) { if (!aasworld.areasettings[i].numreachableareas) continue; - } //end if - //if the area is a cluster portal + } // end if + // if the area is a cluster portal if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) continue; - if (aasworld.numclusters >= AAS_MAX_CLUSTERS) - { + if (aasworld.numclusters >= AAS_MAX_CLUSTERS) { AAS_Error("AAS_MAX_CLUSTERS\n"); return qfalse; - } //end if + } // end if cluster = &aasworld.clusters[aasworld.numclusters]; cluster->numareas = 0; cluster->numreachabilityareas = 0; cluster->firstportal = aasworld.portalindexsize; cluster->numportals = 0; - //flood the areas in this cluster + // flood the areas in this cluster if (!AAS_FloodClusterAreas_r(i, aasworld.numclusters)) return qfalse; if (!AAS_FloodClusterAreasUsingReachabilities(aasworld.numclusters)) return qfalse; - //number the cluster areas - //AAS_NumberClusterPortals(aasworld.numclusters); + // number the cluster areas + // AAS_NumberClusterPortals(aasworld.numclusters); AAS_NumberClusterAreas(aasworld.numclusters); - //Log_Write("cluster %d has %d areas\r\n", aasworld.numclusters, cluster->numareas); + // Log_Write("cluster %d has %d areas\r\n", aasworld.numclusters, cluster->numareas); aasworld.numclusters++; - } //end for + } // end for return qtrue; -} //end of the function AAS_FindClusters +} // end of the function AAS_FindClusters //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CreatePortals(void) -{ +void AAS_CreatePortals(void) { int i; aas_portal_t *portal; - for (i = 1; i < aasworld.numareas; i++) - { - //if the area is a cluster portal - if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) - { - if (aasworld.numportals >= AAS_MAX_PORTALS) - { + for (i = 1; i < aasworld.numareas; i++) { + // if the area is a cluster portal + if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) { + if (aasworld.numportals >= AAS_MAX_PORTALS) { AAS_Error("AAS_MAX_PORTALS\n"); return; - } //end if + } // end if portal = &aasworld.portals[aasworld.numportals]; portal->areanum = i; portal->frontcluster = 0; portal->backcluster = 0; aasworld.numportals++; - } //end if - } //end for -} //end of the function AAS_CreatePortals + } // end if + } // end for +} // end of the function AAS_CreatePortals /* //=========================================================================== // @@ -689,56 +649,60 @@ qboolean AAS_CanMergeFaces(int *facenums, int numfaces, int planenum) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ConnectedAreas_r(int *areanums, int numareas, int *connectedareas, int curarea) -{ +void AAS_ConnectedAreas_r(int *areanums, int numareas, int *connectedareas, int curarea) { int i, j, otherareanum, facenum; aas_area_t *area; aas_face_t *face; connectedareas[curarea] = qtrue; area = &aasworld.areas[areanums[curarea]]; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); face = &aasworld.faces[facenum]; - //if the face is solid - if (face->faceflags & FACE_SOLID) continue; - //get the area at the other side of the face - if (face->frontarea != areanums[curarea]) otherareanum = face->frontarea; - else otherareanum = face->backarea; - //check if the face is leading to one of the other areas - for (j = 0; j < numareas; j++) - { - if (areanums[j] == otherareanum) break; - } //end for - //if the face isn't leading to one of the other areas - if (j == numareas) continue; - //if the other area is already connected - if (connectedareas[j]) continue; - //recursively proceed with the other area + // if the face is solid + if (face->faceflags & FACE_SOLID) + continue; + // get the area at the other side of the face + if (face->frontarea != areanums[curarea]) + otherareanum = face->frontarea; + else + otherareanum = face->backarea; + // check if the face is leading to one of the other areas + for (j = 0; j < numareas; j++) { + if (areanums[j] == otherareanum) + break; + } // end for + // if the face isn't leading to one of the other areas + if (j == numareas) + continue; + // if the other area is already connected + if (connectedareas[j]) + continue; + // recursively proceed with the other area AAS_ConnectedAreas_r(areanums, numareas, connectedareas, j); - } //end for -} //end of the function AAS_ConnectedAreas_r + } // end for +} // end of the function AAS_ConnectedAreas_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_ConnectedAreas(int *areanums, int numareas) -{ +qboolean AAS_ConnectedAreas(int *areanums, int numareas) { int connectedareas[MAX_PORTALAREAS], i; Com_Memset(connectedareas, 0, sizeof(connectedareas)); - if (numareas < 1) return qfalse; - if (numareas == 1) return qtrue; + if (numareas < 1) + return qfalse; + if (numareas == 1) + return qtrue; AAS_ConnectedAreas_r(areanums, numareas, connectedareas, 0); - for (i = 0; i < numareas; i++) - { - if (!connectedareas[i]) return qfalse; - } //end for + for (i = 0; i < numareas; i++) { + if (!connectedareas[i]) + return qfalse; + } // end for return qtrue; -} //end of the function AAS_ConnectedAreas +} // end of the function AAS_ConnectedAreas //=========================================================================== // gets adjacent areas with less presence types recursively // @@ -746,8 +710,7 @@ qboolean AAS_ConnectedAreas(int *areanums, int numareas) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_GetAdjacentAreasWithLessPresenceTypes_r(int *areanums, int numareas, int curareanum) -{ +int AAS_GetAdjacentAreasWithLessPresenceTypes_r(int *areanums, int numareas, int curareanum) { int i, j, presencetype, otherpresencetype, otherareanum, facenum; aas_area_t *area; aas_face_t *face; @@ -755,48 +718,45 @@ int AAS_GetAdjacentAreasWithLessPresenceTypes_r(int *areanums, int numareas, int areanums[numareas++] = curareanum; area = &aasworld.areas[curareanum]; presencetype = aasworld.areasettings[curareanum].presencetype; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); face = &aasworld.faces[facenum]; - //if the face is solid - if (face->faceflags & FACE_SOLID) continue; - //the area at the other side of the face - if (face->frontarea != curareanum) otherareanum = face->frontarea; - else otherareanum = face->backarea; + // if the face is solid + if (face->faceflags & FACE_SOLID) + continue; + // the area at the other side of the face + if (face->frontarea != curareanum) + otherareanum = face->frontarea; + else + otherareanum = face->backarea; // otherpresencetype = aasworld.areasettings[otherareanum].presencetype; - //if the other area has less presence types - if ((presencetype & ~otherpresencetype) && - !(otherpresencetype & ~presencetype)) - { - //check if the other area isn't already in the list - for (j = 0; j < numareas; j++) - { - if (otherareanum == areanums[j]) break; - } //end for - //if the other area isn't already in the list - if (j == numareas) - { - if (numareas >= MAX_PORTALAREAS) - { + // if the other area has less presence types + if ((presencetype & ~otherpresencetype) && !(otherpresencetype & ~presencetype)) { + // check if the other area isn't already in the list + for (j = 0; j < numareas; j++) { + if (otherareanum == areanums[j]) + break; + } // end for + // if the other area isn't already in the list + if (j == numareas) { + if (numareas >= MAX_PORTALAREAS) { AAS_Error("MAX_PORTALAREAS\n"); return numareas; - } //end if + } // end if numareas = AAS_GetAdjacentAreasWithLessPresenceTypes_r(areanums, numareas, otherareanum); - } //end if - } //end if - } //end for + } // end if + } // end if + } // end for return numareas; -} //end of the function AAS_GetAdjacentAreasWithLessPresenceTypes_r +} // end of the function AAS_GetAdjacentAreasWithLessPresenceTypes_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_CheckAreaForPossiblePortals(int areanum) -{ +int AAS_CheckAreaForPossiblePortals(int areanum) { int i, j, k, fen, ben, frontedgenum, backedgenum, facenum; int areanums[MAX_PORTALAREAS], numareas, otherareanum; int numareafrontfaces[MAX_PORTALAREAS], numareabackfaces[MAX_PORTALAREAS]; @@ -808,146 +768,149 @@ int AAS_CheckAreaForPossiblePortals(int areanum) aas_area_t *area; aas_face_t *frontface, *backface, *face; - //if it isn't already a portal - if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) return 0; - //it must be a grounded area - if (!(aasworld.areasettings[areanum].areaflags & AREA_GROUNDED)) return 0; + // if it isn't already a portal + if (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL) + return 0; + // it must be a grounded area + if (!(aasworld.areasettings[areanum].areaflags & AREA_GROUNDED)) + return 0; // Com_Memset(numareafrontfaces, 0, sizeof(numareafrontfaces)); Com_Memset(numareabackfaces, 0, sizeof(numareabackfaces)); numareas = numfrontfaces = numbackfaces = 0; numfrontareas = numbackareas = 0; frontplanenum = backplanenum = -1; - //add any adjacent areas with less presence types + // add any adjacent areas with less presence types numareas = AAS_GetAdjacentAreasWithLessPresenceTypes_r(areanums, 0, areanum); // - for (i = 0; i < numareas; i++) - { + for (i = 0; i < numareas; i++) { area = &aasworld.areas[areanums[i]]; - for (j = 0; j < area->numfaces; j++) - { + for (j = 0; j < area->numfaces; j++) { facenum = abs(aasworld.faceindex[area->firstface + j]); face = &aasworld.faces[facenum]; - //if the face is solid - if (face->faceflags & FACE_SOLID) continue; - //check if the face is shared with one of the other areas - for (k = 0; k < numareas; k++) - { - if (k == i) continue; - if (face->frontarea == areanums[k] || face->backarea == areanums[k]) break; - } //end for - //if the face is shared - if (k != numareas) continue; - //the number of the area at the other side of the face - if (face->frontarea == areanums[i]) otherareanum = face->backarea; - else otherareanum = face->frontarea; - //if the other area already is a cluter portal - if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) return 0; - //number of the plane of the area + // if the face is solid + if (face->faceflags & FACE_SOLID) + continue; + // check if the face is shared with one of the other areas + for (k = 0; k < numareas; k++) { + if (k == i) + continue; + if (face->frontarea == areanums[k] || face->backarea == areanums[k]) + break; + } // end for + // if the face is shared + if (k != numareas) + continue; + // the number of the area at the other side of the face + if (face->frontarea == areanums[i]) + otherareanum = face->backarea; + else + otherareanum = face->frontarea; + // if the other area already is a cluter portal + if (aasworld.areasettings[otherareanum].contents & AREACONTENTS_CLUSTERPORTAL) + return 0; + // number of the plane of the area faceplanenum = face->planenum & ~1; // - if (frontplanenum < 0 || faceplanenum == frontplanenum) - { + if (frontplanenum < 0 || faceplanenum == frontplanenum) { frontplanenum = faceplanenum; frontfacenums[numfrontfaces++] = facenum; - for (k = 0; k < numfrontareas; k++) - { - if (frontareanums[k] == otherareanum) break; - } //end for - if (k == numfrontareas) frontareanums[numfrontareas++] = otherareanum; + for (k = 0; k < numfrontareas; k++) { + if (frontareanums[k] == otherareanum) + break; + } // end for + if (k == numfrontareas) + frontareanums[numfrontareas++] = otherareanum; numareafrontfaces[i]++; - } //end if - else if (backplanenum < 0 || faceplanenum == backplanenum) - { + } // end if + else if (backplanenum < 0 || faceplanenum == backplanenum) { backplanenum = faceplanenum; backfacenums[numbackfaces++] = facenum; - for (k = 0; k < numbackareas; k++) - { - if (backareanums[k] == otherareanum) break; - } //end for - if (k == numbackareas) backareanums[numbackareas++] = otherareanum; + for (k = 0; k < numbackareas; k++) { + if (backareanums[k] == otherareanum) + break; + } // end for + if (k == numbackareas) + backareanums[numbackareas++] = otherareanum; numareabackfaces[i]++; - } //end else - else - { + } // end else + else { return 0; - } //end else - } //end for - } //end for - //every area should have at least one front face and one back face - for (i = 0; i < numareas; i++) - { - if (!numareafrontfaces[i] || !numareabackfaces[i]) return 0; - } //end for - //the front areas should all be connected - if (!AAS_ConnectedAreas(frontareanums, numfrontareas)) return 0; - //the back areas should all be connected - if (!AAS_ConnectedAreas(backareanums, numbackareas)) return 0; - //none of the front faces should have a shared edge with a back face - for (i = 0; i < numfrontfaces; i++) - { + } // end else + } // end for + } // end for + // every area should have at least one front face and one back face + for (i = 0; i < numareas; i++) { + if (!numareafrontfaces[i] || !numareabackfaces[i]) + return 0; + } // end for + // the front areas should all be connected + if (!AAS_ConnectedAreas(frontareanums, numfrontareas)) + return 0; + // the back areas should all be connected + if (!AAS_ConnectedAreas(backareanums, numbackareas)) + return 0; + // none of the front faces should have a shared edge with a back face + for (i = 0; i < numfrontfaces; i++) { frontface = &aasworld.faces[frontfacenums[i]]; - for (fen = 0; fen < frontface->numedges; fen++) - { + for (fen = 0; fen < frontface->numedges; fen++) { frontedgenum = abs(aasworld.edgeindex[frontface->firstedge + fen]); - for (j = 0; j < numbackfaces; j++) - { + for (j = 0; j < numbackfaces; j++) { backface = &aasworld.faces[backfacenums[j]]; - for (ben = 0; ben < backface->numedges; ben++) - { + for (ben = 0; ben < backface->numedges; ben++) { backedgenum = abs(aasworld.edgeindex[backface->firstedge + ben]); - if (frontedgenum == backedgenum) break; - } //end for - if (ben != backface->numedges) break; - } //end for - if (j != numbackfaces) break; - } //end for - if (fen != frontface->numedges) break; - } //end for - if (i != numfrontfaces) return 0; - //set the cluster portal contents - for (i = 0; i < numareas; i++) - { + if (frontedgenum == backedgenum) + break; + } // end for + if (ben != backface->numedges) + break; + } // end for + if (j != numbackfaces) + break; + } // end for + if (fen != frontface->numedges) + break; + } // end for + if (i != numfrontfaces) + return 0; + // set the cluster portal contents + for (i = 0; i < numareas; i++) { aasworld.areasettings[areanums[i]].contents |= AREACONTENTS_CLUSTERPORTAL; - //this area can be used as a route portal + // this area can be used as a route portal aasworld.areasettings[areanums[i]].contents |= AREACONTENTS_ROUTEPORTAL; Log_Write("possible portal: %d\r\n", areanums[i]); - } //end for + } // end for // return numareas; -} //end of the function AAS_CheckAreaForPossiblePortals +} // end of the function AAS_CheckAreaForPossiblePortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FindPossiblePortals(void) -{ +void AAS_FindPossiblePortals(void) { int i, numpossibleportals; numpossibleportals = 0; - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { numpossibleportals += AAS_CheckAreaForPossiblePortals(i); - } //end for + } // end for botimport.Print(PRT_MESSAGE, "\r%6d possible portal areas\n", numpossibleportals); -} //end of the function AAS_FindPossiblePortals +} // end of the function AAS_FindPossiblePortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_RemoveAllPortals(void) -{ +void AAS_RemoveAllPortals(void) { int i; - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { aasworld.areasettings[i].contents &= ~AREACONTENTS_CLUSTERPORTAL; - } //end for -} //end of the function AAS_RemoveAllPortals + } // end for +} // end of the function AAS_RemoveAllPortals #if 0 //=========================================================================== @@ -1374,167 +1337,152 @@ void AAS_AddTeleporterPortals(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_TestPortals(void) -{ +int AAS_TestPortals(void) { int i; aas_portal_t *portal; - for (i = 1; i < aasworld.numportals; i++) - { + for (i = 1; i < aasworld.numportals; i++) { portal = &aasworld.portals[i]; - if (!portal->frontcluster) - { + if (!portal->frontcluster) { aasworld.areasettings[portal->areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL; Log_Write("portal area %d has no front cluster\r\n", portal->areanum); return qfalse; - } //end if - if (!portal->backcluster) - { + } // end if + if (!portal->backcluster) { aasworld.areasettings[portal->areanum].contents &= ~AREACONTENTS_CLUSTERPORTAL; Log_Write("portal area %d has no back cluster\r\n", portal->areanum); return qfalse; - } //end if - } //end for + } // end if + } // end for return qtrue; -} //end of the function +} // end of the function //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CountForcedClusterPortals(void) -{ +void AAS_CountForcedClusterPortals(void) { int num, i; num = 0; - for (i = 1; i < aasworld.numareas; i++) - { - if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) - { + for (i = 1; i < aasworld.numareas; i++) { + if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) { Log_Write("area %d is a forced portal area\r\n", i); num++; - } //end if - } //end for + } // end if + } // end for botimport.Print(PRT_MESSAGE, "%6d forced portal areas\n", num); -} //end of the function AAS_CountForcedClusterPortals +} // end of the function AAS_CountForcedClusterPortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CreateViewPortals(void) -{ +void AAS_CreateViewPortals(void) { int i; - for (i = 1; i < aasworld.numareas; i++) - { - if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) - { + for (i = 1; i < aasworld.numareas; i++) { + if (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL) { aasworld.areasettings[i].contents |= AREACONTENTS_VIEWPORTAL; - } //end if - } //end for -} //end of the function AAS_CreateViewPortals + } // end if + } // end for +} // end of the function AAS_CreateViewPortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_SetViewPortalsAsClusterPortals(void) -{ +void AAS_SetViewPortalsAsClusterPortals(void) { int i; - for (i = 1; i < aasworld.numareas; i++) - { - if (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL) - { + for (i = 1; i < aasworld.numareas; i++) { + if (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL) { aasworld.areasettings[i].contents |= AREACONTENTS_CLUSTERPORTAL; - } //end if - } //end for -} //end of the function AAS_SetViewPortalsAsClusterPortals + } // end if + } // end for +} // end of the function AAS_SetViewPortalsAsClusterPortals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitClustering(void) -{ +void AAS_InitClustering(void) { int i, removedPortalAreas; int n, total, numreachabilityareas; - if (!aasworld.loaded) return; - //if there are clusters - if (aasworld.numclusters >= 1) - { + if (!aasworld.loaded) + return; + // if there are clusters + if (aasworld.numclusters >= 1) { #ifndef BSPC - //if clustering isn't forced - if (!((int)LibVarGetValue("forceclustering")) && - !((int)LibVarGetValue("forcereachability"))) return; + // if clustering isn't forced + if (!((int)LibVarGetValue("forceclustering")) && !((int)LibVarGetValue("forcereachability"))) + return; #endif - } //end if - //set all view portals as cluster portals in case we re-calculate the reachabilities and clusters (with -reach) + } // end if + // set all view portals as cluster portals in case we re-calculate the reachabilities and clusters (with -reach) AAS_SetViewPortalsAsClusterPortals(); - //count the number of forced cluster portals + // count the number of forced cluster portals AAS_CountForcedClusterPortals(); - //remove all area cluster marks + // remove all area cluster marks AAS_RemoveClusterAreas(); - //find possible cluster portals + // find possible cluster portals AAS_FindPossiblePortals(); - //craete portals to for the bot view + // craete portals to for the bot view AAS_CreateViewPortals(); - //remove all portals that are not closing a cluster - //AAS_RemoveNotClusterClosingPortals(); - //initialize portal memory - if (aasworld.portals) FreeMemory(aasworld.portals); - aasworld.portals = (aas_portal_t *) GetClearedMemory(AAS_MAX_PORTALS * sizeof(aas_portal_t)); - //initialize portal index memory - if (aasworld.portalindex) FreeMemory(aasworld.portalindex); - aasworld.portalindex = (aas_portalindex_t *) GetClearedMemory(AAS_MAX_PORTALINDEXSIZE * sizeof(aas_portalindex_t)); - //initialize cluster memory - if (aasworld.clusters) FreeMemory(aasworld.clusters); - aasworld.clusters = (aas_cluster_t *) GetClearedMemory(AAS_MAX_CLUSTERS * sizeof(aas_cluster_t)); + // remove all portals that are not closing a cluster + // AAS_RemoveNotClusterClosingPortals(); + // initialize portal memory + if (aasworld.portals) + FreeMemory(aasworld.portals); + aasworld.portals = (aas_portal_t *)GetClearedMemory(AAS_MAX_PORTALS * sizeof(aas_portal_t)); + // initialize portal index memory + if (aasworld.portalindex) + FreeMemory(aasworld.portalindex); + aasworld.portalindex = (aas_portalindex_t *)GetClearedMemory(AAS_MAX_PORTALINDEXSIZE * sizeof(aas_portalindex_t)); + // initialize cluster memory + if (aasworld.clusters) + FreeMemory(aasworld.clusters); + aasworld.clusters = (aas_cluster_t *)GetClearedMemory(AAS_MAX_CLUSTERS * sizeof(aas_cluster_t)); // removedPortalAreas = 0; botimport.Print(PRT_MESSAGE, "\r%6d removed portal areas", removedPortalAreas); - while(1) - { + while (1) { botimport.Print(PRT_MESSAGE, "\r%6d", removedPortalAreas); - //initialize the number of portals and clusters - aasworld.numportals = 1; //portal 0 is a dummy + // initialize the number of portals and clusters + aasworld.numportals = 1; // portal 0 is a dummy aasworld.portalindexsize = 0; - aasworld.numclusters = 1; //cluster 0 is a dummy - //create the portals from the portal areas + aasworld.numclusters = 1; // cluster 0 is a dummy + // create the portals from the portal areas AAS_CreatePortals(); // removedPortalAreas++; - //find the clusters + // find the clusters if (!AAS_FindClusters()) continue; - //test the portals + // test the portals if (!AAS_TestPortals()) continue; // break; - } //end while + } // end while botimport.Print(PRT_MESSAGE, "\n"); - //the AAS file should be saved + // the AAS file should be saved aasworld.savefile = qtrue; - //write the portal areas to the log file - for (i = 1; i < aasworld.numportals; i++) - { + // write the portal areas to the log file + for (i = 1; i < aasworld.numportals; i++) { Log_Write("portal %d: area %d\r\n", i, aasworld.portals[i].areanum); - } //end for + } // end for // report cluster info botimport.Print(PRT_MESSAGE, "%6d portals created\n", aasworld.numportals); botimport.Print(PRT_MESSAGE, "%6d clusters created\n", aasworld.numclusters); - for (i = 1; i < aasworld.numclusters; i++) - { - botimport.Print(PRT_MESSAGE, "cluster %d has %d reachability areas\n", i, - aasworld.clusters[i].numreachabilityareas); - } //end for + for (i = 1; i < aasworld.numclusters; i++) { + botimport.Print(PRT_MESSAGE, "cluster %d has %d reachability areas\n", i, aasworld.clusters[i].numreachabilityareas); + } // end for // report AAS file efficiency numreachabilityareas = 0; total = 0; @@ -1547,4 +1495,4 @@ void AAS_InitClustering(void) // botimport.Print(PRT_MESSAGE, "%6i total reachability areas\n", numreachabilityareas); botimport.Print(PRT_MESSAGE, "%6i AAS memory/CPU usage (the lower the better)\n", total * 3); -} //end of the function AAS_InitClustering +} // end of the function AAS_InitClustering diff --git a/codemp/botlib/be_aas_debug.cpp b/codemp/botlib/be_aas_debug.cpp index 855d25638b..2939a1d0e6 100644 --- a/codemp/botlib/be_aas_debug.cpp +++ b/codemp/botlib/be_aas_debug.cpp @@ -47,8 +47,8 @@ along with this program; if not, see . #include "be_aas_funcs.h" #include "be_aas_def.h" -#define MAX_DEBUGLINES 1024 -#define MAX_DEBUGPOLYGONS 8192 +#define MAX_DEBUGLINES 1024 +#define MAX_DEBUGPOLYGONS 8192 int debuglines[MAX_DEBUGLINES]; int debuglinevisible[MAX_DEBUGLINES]; @@ -62,117 +62,103 @@ static int debugpolygons[MAX_DEBUGPOLYGONS]; // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ClearShownPolygons(void) -{ +void AAS_ClearShownPolygons(void) { int i; -//* - for (i = 0; i < MAX_DEBUGPOLYGONS; i++) - { - if (debugpolygons[i]) botimport.DebugPolygonDelete(debugpolygons[i]); + //* + for (i = 0; i < MAX_DEBUGPOLYGONS; i++) { + if (debugpolygons[i]) + botimport.DebugPolygonDelete(debugpolygons[i]); debugpolygons[i] = 0; - } //end for -//*/ -/* - for (i = 0; i < MAX_DEBUGPOLYGONS; i++) - { - botimport.DebugPolygonDelete(i); - debugpolygons[i] = 0; - } //end for -*/ -} //end of the function AAS_ClearShownPolygons + } // end for + //*/ + /* + for (i = 0; i < MAX_DEBUGPOLYGONS; i++) + { + botimport.DebugPolygonDelete(i); + debugpolygons[i] = 0; + } //end for + */ +} // end of the function AAS_ClearShownPolygons //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowPolygon(int color, int numpoints, vec3_t *points) -{ +void AAS_ShowPolygon(int color, int numpoints, vec3_t *points) { int i; - for (i = 0; i < MAX_DEBUGPOLYGONS; i++) - { - if (!debugpolygons[i]) - { + for (i = 0; i < MAX_DEBUGPOLYGONS; i++) { + if (!debugpolygons[i]) { debugpolygons[i] = botimport.DebugPolygonCreate(color, numpoints, points); break; - } //end if - } //end for -} //end of the function AAS_ShowPolygon + } // end if + } // end for +} // end of the function AAS_ShowPolygon //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ClearShownDebugLines(void) -{ +void AAS_ClearShownDebugLines(void) { int i; - //make all lines invisible - for (i = 0; i < MAX_DEBUGLINES; i++) - { - if (debuglines[i]) - { - //botimport.DebugLineShow(debuglines[i], NULL, NULL, LINECOLOR_NONE); + // make all lines invisible + for (i = 0; i < MAX_DEBUGLINES; i++) { + if (debuglines[i]) { + // botimport.DebugLineShow(debuglines[i], NULL, NULL, LINECOLOR_NONE); botimport.DebugLineDelete(debuglines[i]); debuglines[i] = 0; debuglinevisible[i] = qfalse; - } //end if - } //end for -} //end of the function AAS_ClearShownDebugLines + } // end if + } // end for +} // end of the function AAS_ClearShownDebugLines //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DebugLine(vec3_t start, vec3_t end, int color) -{ +void AAS_DebugLine(vec3_t start, vec3_t end, int color) { int line; - for (line = 0; line < MAX_DEBUGLINES; line++) - { - if (!debuglines[line]) - { + for (line = 0; line < MAX_DEBUGLINES; line++) { + if (!debuglines[line]) { debuglines[line] = botimport.DebugLineCreate(); debuglinevisible[line] = qfalse; numdebuglines++; - } //end if - if (!debuglinevisible[line]) - { + } // end if + if (!debuglinevisible[line]) { botimport.DebugLineShow(debuglines[line], start, end, color); debuglinevisible[line] = qtrue; return; - } //end else - } //end for -} //end of the function AAS_DebugLine + } // end else + } // end for +} // end of the function AAS_DebugLine //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_PermanentLine(vec3_t start, vec3_t end, int color) -{ +void AAS_PermanentLine(vec3_t start, vec3_t end, int color) { int line; line = botimport.DebugLineCreate(); botimport.DebugLineShow(line, start, end, color); -} //end of the function AAS_PermenentLine +} // end of the function AAS_PermenentLine //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DrawPermanentCross(vec3_t origin, float size, int color) -{ +void AAS_DrawPermanentCross(vec3_t origin, float size, int color) { int i, debugline; vec3_t start, end; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { VectorCopy(origin, start); start[i] += size; VectorCopy(origin, end); @@ -180,20 +166,19 @@ void AAS_DrawPermanentCross(vec3_t origin, float size, int color) AAS_DebugLine(start, end, color); debugline = botimport.DebugLineCreate(); botimport.DebugLineShow(debugline, start, end, color); - } //end for -} //end of the function AAS_DrawPermanentCross + } // end for +} // end of the function AAS_DrawPermanentCross //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int color) -{ +void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int color) { int n0, n1, n2, j, line, lines[2]; vec3_t start1, end1, start2, end2; - //make a cross in the hit plane at the hit point + // make a cross in the hit plane at the hit point VectorCopy(point, start1); VectorCopy(point, end1); VectorCopy(point, start2); @@ -211,46 +196,38 @@ void AAS_DrawPlaneCross(vec3_t point, vec3_t normal, float dist, int type, int c end2[n1] -= 6; end2[n2] += 6; - start1[n0] = (dist - (start1[n1] * normal[n1] + - start1[n2] * normal[n2])) / normal[n0]; - end1[n0] = (dist - (end1[n1] * normal[n1] + - end1[n2] * normal[n2])) / normal[n0]; - start2[n0] = (dist - (start2[n1] * normal[n1] + - start2[n2] * normal[n2])) / normal[n0]; - end2[n0] = (dist - (end2[n1] * normal[n1] + - end2[n2] * normal[n2])) / normal[n0]; - - for (j = 0, line = 0; j < 2 && line < MAX_DEBUGLINES; line++) - { - if (!debuglines[line]) - { + start1[n0] = (dist - (start1[n1] * normal[n1] + start1[n2] * normal[n2])) / normal[n0]; + end1[n0] = (dist - (end1[n1] * normal[n1] + end1[n2] * normal[n2])) / normal[n0]; + start2[n0] = (dist - (start2[n1] * normal[n1] + start2[n2] * normal[n2])) / normal[n0]; + end2[n0] = (dist - (end2[n1] * normal[n1] + end2[n2] * normal[n2])) / normal[n0]; + + for (j = 0, line = 0; j < 2 && line < MAX_DEBUGLINES; line++) { + if (!debuglines[line]) { debuglines[line] = botimport.DebugLineCreate(); lines[j++] = debuglines[line]; debuglinevisible[line] = qtrue; numdebuglines++; - } //end if - else if (!debuglinevisible[line]) - { + } // end if + else if (!debuglinevisible[line]) { lines[j++] = debuglines[line]; debuglinevisible[line] = qtrue; - } //end else - } //end for + } // end else + } // end for botimport.DebugLineShow(lines[0], start1, end1, color); botimport.DebugLineShow(lines[1], start2, end2, color); -} //end of the function AAS_DrawPlaneCross +} // end of the function AAS_DrawPlaneCross //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs) -{ +void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs) { vec3_t bboxcorners[8]; int lines[3]; int i, j, line; - //upper corners + // upper corners bboxcorners[0][0] = origin[0] + maxs[0]; bboxcorners[0][1] = origin[1] + maxs[1]; bboxcorners[0][2] = origin[2] + maxs[2]; @@ -266,46 +243,39 @@ void AAS_ShowBoundingBox(vec3_t origin, vec3_t mins, vec3_t maxs) bboxcorners[3][0] = origin[0] + maxs[0]; bboxcorners[3][1] = origin[1] + mins[1]; bboxcorners[3][2] = origin[2] + maxs[2]; - //lower corners + // lower corners Com_Memcpy(bboxcorners[4], bboxcorners[0], sizeof(vec3_t) * 4); - for (i = 0; i < 4; i++) bboxcorners[4 + i][2] = origin[2] + mins[2]; - //draw bounding box for (i = 0; i < 4; i++) - { - for (j = 0, line = 0; j < 3 && line < MAX_DEBUGLINES; line++) - { - if (!debuglines[line]) - { + bboxcorners[4 + i][2] = origin[2] + mins[2]; + // draw bounding box + for (i = 0; i < 4; i++) { + for (j = 0, line = 0; j < 3 && line < MAX_DEBUGLINES; line++) { + if (!debuglines[line]) { debuglines[line] = botimport.DebugLineCreate(); lines[j++] = debuglines[line]; debuglinevisible[line] = qtrue; numdebuglines++; - } //end if - else if (!debuglinevisible[line]) - { + } // end if + else if (!debuglinevisible[line]) { lines[j++] = debuglines[line]; debuglinevisible[line] = qtrue; - } //end else - } //end for - //top plane - botimport.DebugLineShow(lines[0], bboxcorners[i], - bboxcorners[(i+1)&3], LINECOLOR_RED); - //bottom plane - botimport.DebugLineShow(lines[1], bboxcorners[4+i], - bboxcorners[4+((i+1)&3)], LINECOLOR_RED); - //vertical lines - botimport.DebugLineShow(lines[2], bboxcorners[i], - bboxcorners[4+i], LINECOLOR_RED); - } //end for -} //end of the function AAS_ShowBoundingBox + } // end else + } // end for + // top plane + botimport.DebugLineShow(lines[0], bboxcorners[i], bboxcorners[(i + 1) & 3], LINECOLOR_RED); + // bottom plane + botimport.DebugLineShow(lines[1], bboxcorners[4 + i], bboxcorners[4 + ((i + 1) & 3)], LINECOLOR_RED); + // vertical lines + botimport.DebugLineShow(lines[2], bboxcorners[i], bboxcorners[4 + i], LINECOLOR_RED); + } // end for +} // end of the function AAS_ShowBoundingBox //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowFace(int facenum) -{ +void AAS_ShowFace(int facenum) { int i, color, edgenum; aas_edge_t *edge; aas_face_t *face; @@ -313,91 +283,83 @@ void AAS_ShowFace(int facenum) vec3_t start, end; color = LINECOLOR_YELLOW; - //check if face number is in range - if (facenum >= aasworld.numfaces) - { + // check if face number is in range + if (facenum >= aasworld.numfaces) { botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum); - } //end if + } // end if face = &aasworld.faces[facenum]; - //walk through the edges of the face - for (i = 0; i < face->numedges; i++) - { - //edge number + // walk through the edges of the face + for (i = 0; i < face->numedges; i++) { + // edge number edgenum = abs(aasworld.edgeindex[face->firstedge + i]); - //check if edge number is in range - if (edgenum >= aasworld.numedges) - { + // check if edge number is in range + if (edgenum >= aasworld.numedges) { botimport.Print(PRT_ERROR, "edgenum %d out of range\n", edgenum); - } //end if + } // end if edge = &aasworld.edges[edgenum]; - if (color == LINECOLOR_RED) color = LINECOLOR_GREEN; - else if (color == LINECOLOR_GREEN) color = LINECOLOR_BLUE; - else if (color == LINECOLOR_BLUE) color = LINECOLOR_YELLOW; - else color = LINECOLOR_RED; - AAS_DebugLine(aasworld.vertexes[edge->v[0]], - aasworld.vertexes[edge->v[1]], - color); - } //end for + if (color == LINECOLOR_RED) + color = LINECOLOR_GREEN; + else if (color == LINECOLOR_GREEN) + color = LINECOLOR_BLUE; + else if (color == LINECOLOR_BLUE) + color = LINECOLOR_YELLOW; + else + color = LINECOLOR_RED; + AAS_DebugLine(aasworld.vertexes[edge->v[0]], aasworld.vertexes[edge->v[1]], color); + } // end for plane = &aasworld.planes[face->planenum]; edgenum = abs(aasworld.edgeindex[face->firstedge]); edge = &aasworld.edges[edgenum]; VectorCopy(aasworld.vertexes[edge->v[0]], start); VectorMA(start, 20, plane->normal, end); AAS_DebugLine(start, end, LINECOLOR_RED); -} //end of the function AAS_ShowFace +} // end of the function AAS_ShowFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowFacePolygon(int facenum, int color, int flip) -{ +void AAS_ShowFacePolygon(int facenum, int color, int flip) { int i, edgenum, numpoints; vec3_t points[128]; aas_edge_t *edge; aas_face_t *face; - //check if face number is in range - if (facenum >= aasworld.numfaces) - { + // check if face number is in range + if (facenum >= aasworld.numfaces) { botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum); - } //end if + } // end if face = &aasworld.faces[facenum]; - //walk through the edges of the face + // walk through the edges of the face numpoints = 0; - if (flip) - { - for (i = face->numedges-1; i >= 0; i--) - { - //edge number + if (flip) { + for (i = face->numedges - 1; i >= 0; i--) { + // edge number edgenum = aasworld.edgeindex[face->firstedge + i]; edge = &aasworld.edges[abs(edgenum)]; VectorCopy(aasworld.vertexes[edge->v[edgenum < 0]], points[numpoints]); numpoints++; - } //end for - } //end if - else - { - for (i = 0; i < face->numedges; i++) - { - //edge number + } // end for + } // end if + else { + for (i = 0; i < face->numedges; i++) { + // edge number edgenum = aasworld.edgeindex[face->firstedge + i]; edge = &aasworld.edges[abs(edgenum)]; VectorCopy(aasworld.vertexes[edge->v[edgenum < 0]], points[numpoints]); numpoints++; - } //end for - } //end else + } // end for + } // end else AAS_ShowPolygon(color, numpoints, points); -} //end of the function AAS_ShowFacePolygon +} // end of the function AAS_ShowFacePolygon //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowArea(int areanum, int groundfacesonly) -{ +void AAS_ShowArea(int areanum, int groundfacesonly) { int areaedges[MAX_DEBUGLINES]; int numareaedges, i, j, n, color = 0, line; int facenum, edgenum; @@ -408,189 +370,206 @@ void AAS_ShowArea(int areanum, int groundfacesonly) // numareaedges = 0; // - if (areanum < 0 || areanum >= aasworld.numareas) - { - botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n", - areanum, aasworld.numareas); + if (areanum < 0 || areanum >= aasworld.numareas) { + botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n", areanum, aasworld.numareas); return; - } //end if - //pointer to the convex area + } // end if + // pointer to the convex area area = &aasworld.areas[areanum]; - //walk through the faces of the area - for (i = 0; i < area->numfaces; i++) - { + // walk through the faces of the area + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); - //check if face number is in range - if (facenum >= aasworld.numfaces) - { + // check if face number is in range + if (facenum >= aasworld.numfaces) { botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum); - } //end if + } // end if face = &aasworld.faces[facenum]; - //ground faces only - if (groundfacesonly) - { - if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) continue; - } //end if - //walk through the edges of the face - for (j = 0; j < face->numedges; j++) - { - //edge number + // ground faces only + if (groundfacesonly) { + if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) + continue; + } // end if + // walk through the edges of the face + for (j = 0; j < face->numedges; j++) { + // edge number edgenum = abs(aasworld.edgeindex[face->firstedge + j]); - //check if edge number is in range - if (edgenum >= aasworld.numedges) - { + // check if edge number is in range + if (edgenum >= aasworld.numedges) { botimport.Print(PRT_ERROR, "edgenum %d out of range\n", edgenum); - } //end if - //check if the edge is stored already - for (n = 0; n < numareaedges; n++) - { - if (areaedges[n] == edgenum) break; - } //end for - if (n == numareaedges && numareaedges < MAX_DEBUGLINES) - { + } // end if + // check if the edge is stored already + for (n = 0; n < numareaedges; n++) { + if (areaedges[n] == edgenum) + break; + } // end for + if (n == numareaedges && numareaedges < MAX_DEBUGLINES) { areaedges[numareaedges++] = edgenum; - } //end if - } //end for - //AAS_ShowFace(facenum); - } //end for - //draw all the edges - for (n = 0; n < numareaedges; n++) - { - for (line = 0; line < MAX_DEBUGLINES; line++) - { - if (!debuglines[line]) - { + } // end if + } // end for + // AAS_ShowFace(facenum); + } // end for + // draw all the edges + for (n = 0; n < numareaedges; n++) { + for (line = 0; line < MAX_DEBUGLINES; line++) { + if (!debuglines[line]) { debuglines[line] = botimport.DebugLineCreate(); debuglinevisible[line] = qfalse; numdebuglines++; - } //end if - if (!debuglinevisible[line]) - { + } // end if + if (!debuglinevisible[line]) { break; - } //end else - } //end for - if (line >= MAX_DEBUGLINES) return; + } // end else + } // end for + if (line >= MAX_DEBUGLINES) + return; edge = &aasworld.edges[areaedges[n]]; - if (color == LINECOLOR_RED) color = LINECOLOR_BLUE; - else if (color == LINECOLOR_BLUE) color = LINECOLOR_GREEN; - else if (color == LINECOLOR_GREEN) color = LINECOLOR_YELLOW; - else color = LINECOLOR_RED; - botimport.DebugLineShow(debuglines[line], - aasworld.vertexes[edge->v[0]], - aasworld.vertexes[edge->v[1]], - color); + if (color == LINECOLOR_RED) + color = LINECOLOR_BLUE; + else if (color == LINECOLOR_BLUE) + color = LINECOLOR_GREEN; + else if (color == LINECOLOR_GREEN) + color = LINECOLOR_YELLOW; + else + color = LINECOLOR_RED; + botimport.DebugLineShow(debuglines[line], aasworld.vertexes[edge->v[0]], aasworld.vertexes[edge->v[1]], color); debuglinevisible[line] = qtrue; - } //end for*/ -} //end of the function AAS_ShowArea + } // end for*/ +} // end of the function AAS_ShowArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowAreaPolygons(int areanum, int color, int groundfacesonly) -{ +void AAS_ShowAreaPolygons(int areanum, int color, int groundfacesonly) { int i, facenum; aas_area_t *area; aas_face_t *face; // - if (areanum < 0 || areanum >= aasworld.numareas) - { - botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n", - areanum, aasworld.numareas); + if (areanum < 0 || areanum >= aasworld.numareas) { + botimport.Print(PRT_ERROR, "area %d out of range [0, %d]\n", areanum, aasworld.numareas); return; - } //end if - //pointer to the convex area + } // end if + // pointer to the convex area area = &aasworld.areas[areanum]; - //walk through the faces of the area - for (i = 0; i < area->numfaces; i++) - { + // walk through the faces of the area + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); - //check if face number is in range - if (facenum >= aasworld.numfaces) - { + // check if face number is in range + if (facenum >= aasworld.numfaces) { botimport.Print(PRT_ERROR, "facenum %d out of range\n", facenum); - } //end if + } // end if face = &aasworld.faces[facenum]; - //ground faces only - if (groundfacesonly) - { - if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) continue; - } //end if + // ground faces only + if (groundfacesonly) { + if (!(face->faceflags & (FACE_GROUND | FACE_LADDER))) + continue; + } // end if AAS_ShowFacePolygon(facenum, color, face->frontarea != areanum); - } //end for -} //end of the function AAS_ShowAreaPolygons + } // end for +} // end of the function AAS_ShowAreaPolygons //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DrawCross(vec3_t origin, float size, int color) -{ +void AAS_DrawCross(vec3_t origin, float size, int color) { int i; vec3_t start, end; - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { VectorCopy(origin, start); start[i] += size; VectorCopy(origin, end); end[i] -= size; AAS_DebugLine(start, end, color); - } //end for -} //end of the function AAS_DrawCross + } // end for +} // end of the function AAS_DrawCross //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_PrintTravelType(int traveltype) -{ +void AAS_PrintTravelType(int traveltype) { #ifdef DEBUG char *str; // - switch(traveltype & TRAVELTYPE_MASK) - { - case TRAVEL_INVALID: str = "TRAVEL_INVALID"; break; - case TRAVEL_WALK: str = "TRAVEL_WALK"; break; - case TRAVEL_CROUCH: str = "TRAVEL_CROUCH"; break; - case TRAVEL_BARRIERJUMP: str = "TRAVEL_BARRIERJUMP"; break; - case TRAVEL_JUMP: str = "TRAVEL_JUMP"; break; - case TRAVEL_LADDER: str = "TRAVEL_LADDER"; break; - case TRAVEL_WALKOFFLEDGE: str = "TRAVEL_WALKOFFLEDGE"; break; - case TRAVEL_SWIM: str = "TRAVEL_SWIM"; break; - case TRAVEL_WATERJUMP: str = "TRAVEL_WATERJUMP"; break; - case TRAVEL_TELEPORT: str = "TRAVEL_TELEPORT"; break; - case TRAVEL_ELEVATOR: str = "TRAVEL_ELEVATOR"; break; - case TRAVEL_ROCKETJUMP: str = "TRAVEL_ROCKETJUMP"; break; - case TRAVEL_BFGJUMP: str = "TRAVEL_BFGJUMP"; break; - case TRAVEL_GRAPPLEHOOK: str = "TRAVEL_GRAPPLEHOOK"; break; - case TRAVEL_JUMPPAD: str = "TRAVEL_JUMPPAD"; break; - case TRAVEL_FUNCBOB: str = "TRAVEL_FUNCBOB"; break; - default: str = "UNKNOWN TRAVEL TYPE"; break; - } //end switch + switch (traveltype & TRAVELTYPE_MASK) { + case TRAVEL_INVALID: + str = "TRAVEL_INVALID"; + break; + case TRAVEL_WALK: + str = "TRAVEL_WALK"; + break; + case TRAVEL_CROUCH: + str = "TRAVEL_CROUCH"; + break; + case TRAVEL_BARRIERJUMP: + str = "TRAVEL_BARRIERJUMP"; + break; + case TRAVEL_JUMP: + str = "TRAVEL_JUMP"; + break; + case TRAVEL_LADDER: + str = "TRAVEL_LADDER"; + break; + case TRAVEL_WALKOFFLEDGE: + str = "TRAVEL_WALKOFFLEDGE"; + break; + case TRAVEL_SWIM: + str = "TRAVEL_SWIM"; + break; + case TRAVEL_WATERJUMP: + str = "TRAVEL_WATERJUMP"; + break; + case TRAVEL_TELEPORT: + str = "TRAVEL_TELEPORT"; + break; + case TRAVEL_ELEVATOR: + str = "TRAVEL_ELEVATOR"; + break; + case TRAVEL_ROCKETJUMP: + str = "TRAVEL_ROCKETJUMP"; + break; + case TRAVEL_BFGJUMP: + str = "TRAVEL_BFGJUMP"; + break; + case TRAVEL_GRAPPLEHOOK: + str = "TRAVEL_GRAPPLEHOOK"; + break; + case TRAVEL_JUMPPAD: + str = "TRAVEL_JUMPPAD"; + break; + case TRAVEL_FUNCBOB: + str = "TRAVEL_FUNCBOB"; + break; + default: + str = "UNKNOWN TRAVEL TYPE"; + break; + } // end switch botimport.Print(PRT_MESSAGE, "%s", str); #endif -} //end of the function AAS_PrintTravelType +} // end of the function AAS_PrintTravelType //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor) -{ +void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor) { vec3_t dir, cross, p1, p2, up = {0, 0, 1}; float dot; VectorSubtract(end, start, dir); VectorNormalize(dir); dot = DotProduct(dir, up); - if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0); - else CrossProduct(dir, up, cross); + if (dot > 0.99 || dot < -0.99) + VectorSet(cross, 1, 0, 0); + else + CrossProduct(dir, up, cross); VectorMA(end, -6, dir, p1); VectorCopy(p1, p2); @@ -600,123 +579,109 @@ void AAS_DrawArrow(vec3_t start, vec3_t end, int linecolor, int arrowcolor) AAS_DebugLine(start, end, linecolor); AAS_DebugLine(p1, end, arrowcolor); AAS_DebugLine(p2, end, arrowcolor); -} //end of the function AAS_DrawArrow +} // end of the function AAS_DrawArrow //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowReachability(aas_reachability_t *reach) -{ +void AAS_ShowReachability(aas_reachability_t *reach) { vec3_t dir, cmdmove, velocity; float speed, zvel; aas_clientmove_t move; AAS_ShowAreaPolygons(reach->areanum, 5, qtrue); - //AAS_ShowArea(reach->areanum, qtrue); + // AAS_ShowArea(reach->areanum, qtrue); AAS_DrawArrow(reach->start, reach->end, LINECOLOR_BLUE, LINECOLOR_YELLOW); // - if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP || - (reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE) - { + if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP || (reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE) { AAS_HorizontalVelocityForJump(aassettings.phys_jumpvel, reach->start, reach->end, &speed); // VectorSubtract(reach->end, reach->start, dir); dir[2] = 0; VectorNormalize(dir); - //set the velocity + // set the velocity VectorScale(dir, speed, velocity); - //set the command movement + // set the command movement VectorClear(cmdmove); cmdmove[2] = aassettings.phys_jumpvel; // - AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 3, 30, 0.1f, - SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE, 0, qtrue); + AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 3, 30, 0.1f, + SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE, 0, qtrue); // - if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP) - { + if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMP) { AAS_JumpReachRunStart(reach, dir); AAS_DrawCross(dir, 4, LINECOLOR_BLUE); - } //end if - } //end if - else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) - { + } // end if + } // end if + else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) { zvel = AAS_RocketJumpZVelocity(reach->start); AAS_HorizontalVelocityForJump(zvel, reach->start, reach->end, &speed); // VectorSubtract(reach->end, reach->start, dir); dir[2] = 0; VectorNormalize(dir); - //get command movement + // get command movement VectorScale(dir, speed, cmdmove); VectorSet(velocity, 0, 0, zvel); // - AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 30, 30, 0.1f, - SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE| - SE_TOUCHJUMPPAD|SE_HITGROUNDAREA, reach->areanum, qtrue); - } //end else if - else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) - { + AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 30, 30, 0.1f, + SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_HITGROUNDAREA, reach->areanum, + qtrue); + } // end else if + else if ((reach->traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) { VectorSet(cmdmove, 0, 0, 0); // VectorSubtract(reach->end, reach->start, dir); dir[2] = 0; VectorNormalize(dir); - //set the velocity - //NOTE: the edgenum is the horizontal velocity + // set the velocity + // NOTE: the edgenum is the horizontal velocity VectorScale(dir, reach->edgenum, velocity); - //NOTE: the facenum is the Z velocity + // NOTE: the facenum is the Z velocity velocity[2] = reach->facenum; // - AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 30, 30, 0.1f, - SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE| - SE_TOUCHJUMPPAD|SE_HITGROUNDAREA, reach->areanum, qtrue); - } //end else if -} //end of the function AAS_ShowReachability + AAS_PredictClientMovement(&move, -1, reach->start, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 30, 30, 0.1f, + SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_HITGROUNDAREA, reach->areanum, + qtrue); + } // end else if +} // end of the function AAS_ShowReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShowReachableAreas(int areanum) -{ +void AAS_ShowReachableAreas(int areanum) { aas_areasettings_t *settings; static aas_reachability_t reach; static int index, lastareanum; static float lasttime; - if (areanum != lastareanum) - { + if (areanum != lastareanum) { index = 0; lastareanum = areanum; - } //end if + } // end if settings = &aasworld.areasettings[areanum]; // - if (!settings->numreachableareas) return; + if (!settings->numreachableareas) + return; // - if (index >= settings->numreachableareas) index = 0; + if (index >= settings->numreachableareas) + index = 0; // - if (AAS_Time() - lasttime > 1.5) - { + if (AAS_Time() - lasttime > 1.5) { Com_Memcpy(&reach, &aasworld.reachability[settings->firstreachablearea + index], sizeof(aas_reachability_t)); index++; lasttime = AAS_Time(); AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); botimport.Print(PRT_MESSAGE, "\n"); - } //end if + } // end if AAS_ShowReachability(&reach); -} //end of the function ShowReachableAreas +} // end of the function ShowReachableAreas -void AAS_FloodAreas_r(int areanum, int cluster, int *done) -{ +void AAS_FloodAreas_r(int areanum, int cluster, int *done) { int nextareanum, i, facenum; aas_area_t *area; aas_face_t *face; @@ -724,12 +689,11 @@ void AAS_FloodAreas_r(int areanum, int cluster, int *done) aas_reachability_t *reach; AAS_ShowAreaPolygons(areanum, 1, qtrue); - //pointer to the convex area + // pointer to the convex area area = &aasworld.areas[areanum]; settings = &aasworld.areasettings[areanum]; - //walk through the faces of the area - for (i = 0; i < area->numfaces; i++) - { + // walk through the faces of the area + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); face = &aasworld.faces[facenum]; if (face->frontarea == areanum) @@ -746,10 +710,9 @@ void AAS_FloodAreas_r(int areanum, int cluster, int *done) if (AAS_AreaCluster(nextareanum) != cluster) continue; AAS_FloodAreas_r(nextareanum, cluster, done); - } //end for + } // end for // - for (i = 0; i < settings->numreachableareas; i++) - { + for (i = 0; i < settings->numreachableareas; i++) { reach = &aasworld.reachability[settings->firstreachablearea + i]; nextareanum = reach->areanum; if (!nextareanum) @@ -771,11 +734,10 @@ void AAS_FloodAreas_r(int areanum, int cluster, int *done) } } -void AAS_FloodAreas(vec3_t origin) -{ +void AAS_FloodAreas(vec3_t origin) { int areanum, cluster, *done; - done = (int *) GetClearedMemory(aasworld.numareas * sizeof(int)); + done = (int *)GetClearedMemory(aasworld.numareas * sizeof(int)); areanum = AAS_PointAreaNum(origin); cluster = AAS_AreaCluster(areanum); AAS_FloodAreas_r(areanum, cluster, done); diff --git a/codemp/botlib/be_aas_entity.cpp b/codemp/botlib/be_aas_entity.cpp index 4ca8bdf7bd..d288e51901 100644 --- a/codemp/botlib/be_aas_entity.cpp +++ b/codemp/botlib/be_aas_entity.cpp @@ -48,16 +48,10 @@ along with this program; if not, see . #include "be_interface.h" #include "be_aas_def.h" -#define MASK_SOLID CONTENTS_PLAYERCLIP +#define MASK_SOLID CONTENTS_PLAYERCLIP -//FIXME: these might change -enum { - ET_GENERAL, - ET_PLAYER, - ET_ITEM, - ET_MISSILE, - ET_MOVER -}; +// FIXME: these might change +enum { ET_GENERAL, ET_PLAYER, ET_ITEM, ET_MISSILE, ET_MOVER }; //=========================================================================== // @@ -65,24 +59,22 @@ enum { // Returns: - // Changes Globals: - //=========================================================================== -int AAS_UpdateEntity(int entnum, bot_entitystate_t *state) -{ +int AAS_UpdateEntity(int entnum, bot_entitystate_t *state) { int relink; aas_entity_t *ent; vec3_t absmins, absmaxs; - if (!aasworld.loaded) - { + if (!aasworld.loaded) { botimport.Print(PRT_MESSAGE, "AAS_UpdateEntity: not loaded\n"); return BLERR_NOAASFILE; - } //end if + } // end if ent = &aasworld.entities[entnum]; if (!state) { - //unlink the entity + // unlink the entity AAS_UnlinkFromAreas(ent->areas); - //unlink the entity from the BSP leaves + // unlink the entity from the BSP leaves AAS_UnlinkFromBSPLeaves(ent->leaves); // ent->areas = NULL; @@ -108,210 +100,189 @@ int AAS_UpdateEntity(int entnum, bot_entitystate_t *state) ent->i.weapon = state->weapon; ent->i.legsAnim = state->legsAnim; ent->i.torsoAnim = state->torsoAnim; - //number of the entity + // number of the entity ent->i.number = entnum; - //updated so set valid flag + // updated so set valid flag ent->i.valid = qtrue; - //link everything the first frame - if (aasworld.numframes == 1) relink = qtrue; - else relink = qfalse; + // link everything the first frame + if (aasworld.numframes == 1) + relink = qtrue; + else + relink = qfalse; // - if (ent->i.solid == SOLID_BSP) - { - //if the angles of the model changed - if (!VectorCompare(state->angles, ent->i.angles)) - { + if (ent->i.solid == SOLID_BSP) { + // if the angles of the model changed + if (!VectorCompare(state->angles, ent->i.angles)) { VectorCopy(state->angles, ent->i.angles); relink = qtrue; - } //end if - //get the mins and maxs of the model - //FIXME: rotate mins and maxs + } // end if + // get the mins and maxs of the model + // FIXME: rotate mins and maxs AAS_BSPModelMinsMaxsOrigin(ent->i.modelindex, ent->i.angles, ent->i.mins, ent->i.maxs, NULL); - } //end if - else if (ent->i.solid == SOLID_BBOX) - { - //if the bounding box size changed - if (!VectorCompare(state->mins, ent->i.mins) || - !VectorCompare(state->maxs, ent->i.maxs)) - { + } // end if + else if (ent->i.solid == SOLID_BBOX) { + // if the bounding box size changed + if (!VectorCompare(state->mins, ent->i.mins) || !VectorCompare(state->maxs, ent->i.maxs)) { VectorCopy(state->mins, ent->i.mins); VectorCopy(state->maxs, ent->i.maxs); relink = qtrue; - } //end if + } // end if VectorCopy(state->angles, ent->i.angles); - } //end if - //if the origin changed - if (!VectorCompare(state->origin, ent->i.origin)) - { + } // end if + // if the origin changed + if (!VectorCompare(state->origin, ent->i.origin)) { VectorCopy(state->origin, ent->i.origin); relink = qtrue; - } //end if - //if the entity should be relinked - if (relink) - { - //don't link the world model - if (entnum != ENTITYNUM_WORLD) - { - //absolute mins and maxs + } // end if + // if the entity should be relinked + if (relink) { + // don't link the world model + if (entnum != ENTITYNUM_WORLD) { + // absolute mins and maxs VectorAdd(ent->i.mins, ent->i.origin, absmins); VectorAdd(ent->i.maxs, ent->i.origin, absmaxs); - //unlink the entity + // unlink the entity AAS_UnlinkFromAreas(ent->areas); - //relink the entity to the AAS areas (use the larges bbox) + // relink the entity to the AAS areas (use the larges bbox) ent->areas = AAS_LinkEntityClientBBox(absmins, absmaxs, entnum, PRESENCE_NORMAL); - //unlink the entity from the BSP leaves + // unlink the entity from the BSP leaves AAS_UnlinkFromBSPLeaves(ent->leaves); - //link the entity to the world BSP tree + // link the entity to the world BSP tree ent->leaves = AAS_BSPLinkEntity(absmins, absmaxs, entnum, 0); - } //end if - } //end if + } // end if + } // end if return BLERR_NOERROR; -} //end of the function AAS_UpdateEntity +} // end of the function AAS_UpdateEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_EntityInfo(int entnum, aas_entityinfo_t *info) -{ - if (!aasworld.initialized) - { +void AAS_EntityInfo(int entnum, aas_entityinfo_t *info) { + if (!aasworld.initialized) { botimport.Print(PRT_FATAL, "AAS_EntityInfo: aasworld not initialized\n"); Com_Memset(info, 0, sizeof(aas_entityinfo_t)); return; - } //end if + } // end if - if (entnum < 0 || entnum >= aasworld.maxentities) - { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntityInfo: entnum %d out of range\n", entnum); Com_Memset(info, 0, sizeof(aas_entityinfo_t)); return; - } //end if + } // end if Com_Memcpy(info, &aasworld.entities[entnum].i, sizeof(aas_entityinfo_t)); -} //end of the function AAS_EntityInfo +} // end of the function AAS_EntityInfo //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_EntityOrigin(int entnum, vec3_t origin) -{ - if (entnum < 0 || entnum >= aasworld.maxentities) - { +void AAS_EntityOrigin(int entnum, vec3_t origin) { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntityOrigin: entnum %d out of range\n", entnum); VectorClear(origin); return; - } //end if + } // end if VectorCopy(aasworld.entities[entnum].i.origin, origin); -} //end of the function AAS_EntityOrigin +} // end of the function AAS_EntityOrigin //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_EntityModelindex(int entnum) -{ - if (entnum < 0 || entnum >= aasworld.maxentities) - { +int AAS_EntityModelindex(int entnum) { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntityModelindex: entnum %d out of range\n", entnum); return 0; - } //end if + } // end if return aasworld.entities[entnum].i.modelindex; -} //end of the function AAS_EntityModelindex +} // end of the function AAS_EntityModelindex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_EntityType(int entnum) -{ - if (!aasworld.initialized) return 0; +int AAS_EntityType(int entnum) { + if (!aasworld.initialized) + return 0; - if (entnum < 0 || entnum >= aasworld.maxentities) - { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntityType: entnum %d out of range\n", entnum); return 0; - } //end if + } // end if return aasworld.entities[entnum].i.type; -} //end of the AAS_EntityType +} // end of the AAS_EntityType //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_EntityModelNum(int entnum) -{ - if (!aasworld.initialized) return 0; +int AAS_EntityModelNum(int entnum) { + if (!aasworld.initialized) + return 0; - if (entnum < 0 || entnum >= aasworld.maxentities) - { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntityModelNum: entnum %d out of range\n", entnum); return 0; - } //end if + } // end if return aasworld.entities[entnum].i.modelindex; -} //end of the function AAS_EntityModelNum +} // end of the function AAS_EntityModelNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_OriginOfMoverWithModelNum(int modelnum, vec3_t origin) -{ +int AAS_OriginOfMoverWithModelNum(int modelnum, vec3_t origin) { int i; aas_entity_t *ent; - for (i = 0; i < aasworld.maxentities; i++) - { + for (i = 0; i < aasworld.maxentities; i++) { ent = &aasworld.entities[i]; - if (ent->i.type == ET_MOVER) - { - if (ent->i.modelindex == modelnum) - { + if (ent->i.type == ET_MOVER) { + if (ent->i.modelindex == modelnum) { VectorCopy(ent->i.origin, origin); return qtrue; - } //end if - } //end if - } //end for + } // end if + } // end if + } // end for return qfalse; -} //end of the function AAS_OriginOfMoverWithModelNum +} // end of the function AAS_OriginOfMoverWithModelNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_EntitySize(int entnum, vec3_t mins, vec3_t maxs) -{ +void AAS_EntitySize(int entnum, vec3_t mins, vec3_t maxs) { aas_entity_t *ent; - if (!aasworld.initialized) return; + if (!aasworld.initialized) + return; - if (entnum < 0 || entnum >= aasworld.maxentities) - { + if (entnum < 0 || entnum >= aasworld.maxentities) { botimport.Print(PRT_FATAL, "AAS_EntitySize: entnum %d out of range\n", entnum); return; - } //end if + } // end if ent = &aasworld.entities[entnum]; VectorCopy(ent->i.mins, mins); VectorCopy(ent->i.maxs, maxs); -} //end of the function AAS_EntitySize +} // end of the function AAS_EntitySize //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata) -{ +void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata) { aas_entity_t *ent; ent = &aasworld.entities[entnum]; @@ -321,68 +292,60 @@ void AAS_EntityBSPData(int entnum, bsp_entdata_t *entdata) VectorAdd(ent->i.origin, ent->i.maxs, entdata->absmaxs); entdata->solid = ent->i.solid; entdata->modelnum = ent->i.modelindex - 1; -} //end of the function AAS_EntityBSPData +} // end of the function AAS_EntityBSPData //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ResetEntityLinks(void) -{ +void AAS_ResetEntityLinks(void) { int i; - for (i = 0; i < aasworld.maxentities; i++) - { + for (i = 0; i < aasworld.maxentities; i++) { aasworld.entities[i].areas = NULL; aasworld.entities[i].leaves = NULL; - } //end for -} //end of the function AAS_ResetEntityLinks + } // end for +} // end of the function AAS_ResetEntityLinks //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InvalidateEntities(void) -{ +void AAS_InvalidateEntities(void) { int i; - for (i = 0; i < aasworld.maxentities; i++) - { + for (i = 0; i < aasworld.maxentities; i++) { aasworld.entities[i].i.valid = qfalse; aasworld.entities[i].i.number = i; - } //end for -} //end of the function AAS_InvalidateEntities + } // end for +} // end of the function AAS_InvalidateEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UnlinkInvalidEntities(void) -{ +void AAS_UnlinkInvalidEntities(void) { int i; aas_entity_t *ent; - for (i = 0; i < aasworld.maxentities; i++) - { + for (i = 0; i < aasworld.maxentities; i++) { ent = &aasworld.entities[i]; - if (!ent->i.valid) - { - AAS_UnlinkFromAreas( ent->areas ); + if (!ent->i.valid) { + AAS_UnlinkFromAreas(ent->areas); ent->areas = NULL; - AAS_UnlinkFromBSPLeaves( ent->leaves ); + AAS_UnlinkFromBSPLeaves(ent->leaves); ent->leaves = NULL; - } //end for - } //end for -} //end of the function AAS_UnlinkInvalidEntities + } // end for + } // end for +} // end of the function AAS_UnlinkInvalidEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NearestEntity(vec3_t origin, int modelindex) -{ +int AAS_NearestEntity(vec3_t origin, int modelindex) { int i, bestentnum; float dist, bestdist; aas_entity_t *ent; @@ -390,53 +353,50 @@ int AAS_NearestEntity(vec3_t origin, int modelindex) bestentnum = 0; bestdist = 99999; - for (i = 0; i < aasworld.maxentities; i++) - { + for (i = 0; i < aasworld.maxentities; i++) { ent = &aasworld.entities[i]; - if (ent->i.modelindex != modelindex) continue; + if (ent->i.modelindex != modelindex) + continue; VectorSubtract(ent->i.origin, origin, dir); - if (fabs(dir[0]) < 40) - { - if (fabs(dir[1]) < 40) - { + if (fabs(dir[0]) < 40) { + if (fabs(dir[1]) < 40) { dist = VectorLength(dir); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; bestentnum = i; - } //end if - } //end if - } //end if - } //end for + } // end if + } // end if + } // end if + } // end for return bestentnum; -} //end of the function AAS_NearestEntity +} // end of the function AAS_NearestEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BestReachableEntityArea(int entnum) -{ +int AAS_BestReachableEntityArea(int entnum) { aas_entity_t *ent; ent = &aasworld.entities[entnum]; return AAS_BestReachableLinkArea(ent->areas); -} //end of the function AAS_BestReachableEntityArea +} // end of the function AAS_BestReachableEntityArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NextEntity(int entnum) -{ - if (!aasworld.loaded) return 0; +int AAS_NextEntity(int entnum) { + if (!aasworld.loaded) + return 0; - if (entnum < 0) entnum = -1; - while(++entnum < aasworld.maxentities) - { - if (aasworld.entities[entnum].i.valid) return entnum; - } //end while + if (entnum < 0) + entnum = -1; + while (++entnum < aasworld.maxentities) { + if (aasworld.entities[entnum].i.valid) + return entnum; + } // end while return 0; -} //end of the function AAS_NextEntity +} // end of the function AAS_NextEntity diff --git a/codemp/botlib/be_aas_file.cpp b/codemp/botlib/be_aas_file.cpp index 9f9a2fa02c..540d0526ff 100644 --- a/codemp/botlib/be_aas_file.cpp +++ b/codemp/botlib/be_aas_file.cpp @@ -56,76 +56,64 @@ along with this program; if not, see . // Returns: - // Changes Globals: - //=========================================================================== -void AAS_SwapAASData(void) -{ +void AAS_SwapAASData(void) { int i, j; - //bounding boxes - for (i = 0; i < aasworld.numbboxes; i++) - { + // bounding boxes + for (i = 0; i < aasworld.numbboxes; i++) { aasworld.bboxes[i].presencetype = LittleLong(aasworld.bboxes[i].presencetype); aasworld.bboxes[i].flags = LittleLong(aasworld.bboxes[i].flags); - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { aasworld.bboxes[i].mins[j] = LittleLong(aasworld.bboxes[i].mins[j]); aasworld.bboxes[i].maxs[j] = LittleLong(aasworld.bboxes[i].maxs[j]); - } //end for - } //end for - //vertexes - for (i = 0; i < aasworld.numvertexes; i++) - { + } // end for + } // end for + // vertexes + for (i = 0; i < aasworld.numvertexes; i++) { for (j = 0; j < 3; j++) aasworld.vertexes[i][j] = LittleFloat(aasworld.vertexes[i][j]); - } //end for - //planes - for (i = 0; i < aasworld.numplanes; i++) - { + } // end for + // planes + for (i = 0; i < aasworld.numplanes; i++) { for (j = 0; j < 3; j++) aasworld.planes[i].normal[j] = LittleFloat(aasworld.planes[i].normal[j]); aasworld.planes[i].dist = LittleFloat(aasworld.planes[i].dist); aasworld.planes[i].type = LittleLong(aasworld.planes[i].type); - } //end for - //edges - for (i = 0; i < aasworld.numedges; i++) - { + } // end for + // edges + for (i = 0; i < aasworld.numedges; i++) { aasworld.edges[i].v[0] = LittleLong(aasworld.edges[i].v[0]); aasworld.edges[i].v[1] = LittleLong(aasworld.edges[i].v[1]); - } //end for - //edgeindex - for (i = 0; i < aasworld.edgeindexsize; i++) - { + } // end for + // edgeindex + for (i = 0; i < aasworld.edgeindexsize; i++) { aasworld.edgeindex[i] = LittleLong(aasworld.edgeindex[i]); - } //end for - //faces - for (i = 0; i < aasworld.numfaces; i++) - { + } // end for + // faces + for (i = 0; i < aasworld.numfaces; i++) { aasworld.faces[i].planenum = LittleLong(aasworld.faces[i].planenum); aasworld.faces[i].faceflags = LittleLong(aasworld.faces[i].faceflags); aasworld.faces[i].numedges = LittleLong(aasworld.faces[i].numedges); aasworld.faces[i].firstedge = LittleLong(aasworld.faces[i].firstedge); aasworld.faces[i].frontarea = LittleLong(aasworld.faces[i].frontarea); aasworld.faces[i].backarea = LittleLong(aasworld.faces[i].backarea); - } //end for - //face index - for (i = 0; i < aasworld.faceindexsize; i++) - { + } // end for + // face index + for (i = 0; i < aasworld.faceindexsize; i++) { aasworld.faceindex[i] = LittleLong(aasworld.faceindex[i]); - } //end for - //convex areas - for (i = 0; i < aasworld.numareas; i++) - { + } // end for + // convex areas + for (i = 0; i < aasworld.numareas; i++) { aasworld.areas[i].areanum = LittleLong(aasworld.areas[i].areanum); aasworld.areas[i].numfaces = LittleLong(aasworld.areas[i].numfaces); aasworld.areas[i].firstface = LittleLong(aasworld.areas[i].firstface); - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { aasworld.areas[i].mins[j] = LittleFloat(aasworld.areas[i].mins[j]); aasworld.areas[i].maxs[j] = LittleFloat(aasworld.areas[i].maxs[j]); aasworld.areas[i].center[j] = LittleFloat(aasworld.areas[i].center[j]); - } //end for - } //end for - //area settings - for (i = 0; i < aasworld.numareasettings; i++) - { + } // end for + } // end for + // area settings + for (i = 0; i < aasworld.numareasettings; i++) { aasworld.areasettings[i].contents = LittleLong(aasworld.areasettings[i].contents); aasworld.areasettings[i].areaflags = LittleLong(aasworld.areasettings[i].areaflags); aasworld.areasettings[i].presencetype = LittleLong(aasworld.areasettings[i].presencetype); @@ -133,51 +121,45 @@ void AAS_SwapAASData(void) aasworld.areasettings[i].clusterareanum = LittleLong(aasworld.areasettings[i].clusterareanum); aasworld.areasettings[i].numreachableareas = LittleLong(aasworld.areasettings[i].numreachableareas); aasworld.areasettings[i].firstreachablearea = LittleLong(aasworld.areasettings[i].firstreachablearea); - } //end for - //area reachability - for (i = 0; i < aasworld.reachabilitysize; i++) - { + } // end for + // area reachability + for (i = 0; i < aasworld.reachabilitysize; i++) { aasworld.reachability[i].areanum = LittleLong(aasworld.reachability[i].areanum); aasworld.reachability[i].facenum = LittleLong(aasworld.reachability[i].facenum); aasworld.reachability[i].edgenum = LittleLong(aasworld.reachability[i].edgenum); - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { aasworld.reachability[i].start[j] = LittleFloat(aasworld.reachability[i].start[j]); aasworld.reachability[i].end[j] = LittleFloat(aasworld.reachability[i].end[j]); - } //end for + } // end for aasworld.reachability[i].traveltype = LittleLong(aasworld.reachability[i].traveltype); aasworld.reachability[i].traveltime = LittleShort(aasworld.reachability[i].traveltime); - } //end for - //nodes - for (i = 0; i < aasworld.numnodes; i++) - { + } // end for + // nodes + for (i = 0; i < aasworld.numnodes; i++) { aasworld.nodes[i].planenum = LittleLong(aasworld.nodes[i].planenum); aasworld.nodes[i].children[0] = LittleLong(aasworld.nodes[i].children[0]); aasworld.nodes[i].children[1] = LittleLong(aasworld.nodes[i].children[1]); - } //end for - //cluster portals - for (i = 0; i < aasworld.numportals; i++) - { + } // end for + // cluster portals + for (i = 0; i < aasworld.numportals; i++) { aasworld.portals[i].areanum = LittleLong(aasworld.portals[i].areanum); aasworld.portals[i].frontcluster = LittleLong(aasworld.portals[i].frontcluster); aasworld.portals[i].backcluster = LittleLong(aasworld.portals[i].backcluster); aasworld.portals[i].clusterareanum[0] = LittleLong(aasworld.portals[i].clusterareanum[0]); aasworld.portals[i].clusterareanum[1] = LittleLong(aasworld.portals[i].clusterareanum[1]); - } //end for - //cluster portal index - for (i = 0; i < aasworld.portalindexsize; i++) - { + } // end for + // cluster portal index + for (i = 0; i < aasworld.portalindexsize; i++) { aasworld.portalindex[i] = LittleLong(aasworld.portalindex[i]); - } //end for - //cluster - for (i = 0; i < aasworld.numclusters; i++) - { + } // end for + // cluster + for (i = 0; i < aasworld.numclusters; i++) { aasworld.clusters[i].numareas = LittleLong(aasworld.clusters[i].numareas); aasworld.clusters[i].numreachabilityareas = LittleLong(aasworld.clusters[i].numreachabilityareas); aasworld.clusters[i].numportals = LittleLong(aasworld.clusters[i].numportals); aasworld.clusters[i].firstportal = LittleLong(aasworld.clusters[i].firstportal); - } //end for -} //end of the function AAS_SwapAASData + } // end for +} // end of the function AAS_SwapAASData //=========================================================================== // dump the current loaded aas file // @@ -185,56 +167,69 @@ void AAS_SwapAASData(void) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DumpAASData(void) -{ +void AAS_DumpAASData(void) { aasworld.numbboxes = 0; - if (aasworld.bboxes) FreeMemory(aasworld.bboxes); + if (aasworld.bboxes) + FreeMemory(aasworld.bboxes); aasworld.bboxes = NULL; aasworld.numvertexes = 0; - if (aasworld.vertexes) FreeMemory(aasworld.vertexes); + if (aasworld.vertexes) + FreeMemory(aasworld.vertexes); aasworld.vertexes = NULL; aasworld.numplanes = 0; - if (aasworld.planes) FreeMemory(aasworld.planes); + if (aasworld.planes) + FreeMemory(aasworld.planes); aasworld.planes = NULL; aasworld.numedges = 0; - if (aasworld.edges) FreeMemory(aasworld.edges); + if (aasworld.edges) + FreeMemory(aasworld.edges); aasworld.edges = NULL; aasworld.edgeindexsize = 0; - if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex); + if (aasworld.edgeindex) + FreeMemory(aasworld.edgeindex); aasworld.edgeindex = NULL; aasworld.numfaces = 0; - if (aasworld.faces) FreeMemory(aasworld.faces); + if (aasworld.faces) + FreeMemory(aasworld.faces); aasworld.faces = NULL; aasworld.faceindexsize = 0; - if (aasworld.faceindex) FreeMemory(aasworld.faceindex); + if (aasworld.faceindex) + FreeMemory(aasworld.faceindex); aasworld.faceindex = NULL; aasworld.numareas = 0; - if (aasworld.areas) FreeMemory(aasworld.areas); + if (aasworld.areas) + FreeMemory(aasworld.areas); aasworld.areas = NULL; aasworld.numareasettings = 0; - if (aasworld.areasettings) FreeMemory(aasworld.areasettings); + if (aasworld.areasettings) + FreeMemory(aasworld.areasettings); aasworld.areasettings = NULL; aasworld.reachabilitysize = 0; - if (aasworld.reachability) FreeMemory(aasworld.reachability); + if (aasworld.reachability) + FreeMemory(aasworld.reachability); aasworld.reachability = NULL; aasworld.numnodes = 0; - if (aasworld.nodes) FreeMemory(aasworld.nodes); + if (aasworld.nodes) + FreeMemory(aasworld.nodes); aasworld.nodes = NULL; aasworld.numportals = 0; - if (aasworld.portals) FreeMemory(aasworld.portals); + if (aasworld.portals) + FreeMemory(aasworld.portals); aasworld.portals = NULL; aasworld.numportals = 0; - if (aasworld.portalindex) FreeMemory(aasworld.portalindex); + if (aasworld.portalindex) + FreeMemory(aasworld.portalindex); aasworld.portalindex = NULL; aasworld.portalindexsize = 0; - if (aasworld.clusters) FreeMemory(aasworld.clusters); + if (aasworld.clusters) + FreeMemory(aasworld.clusters); aasworld.clusters = NULL; aasworld.numclusters = 0; // aasworld.loaded = qfalse; aasworld.initialized = qfalse; aasworld.savefile = qfalse; -} //end of the function AAS_DumpAASData +} // end of the function AAS_DumpAASData //=========================================================================== // // Parameter: - @@ -242,8 +237,7 @@ void AAS_DumpAASData(void) // Changes Globals: - //=========================================================================== #ifdef AASFILEDEBUG -void AAS_FileInfo(void) -{ +void AAS_FileInfo(void) { int i, n, optimized; botimport.Print(PRT_MESSAGE, "version = %d\n", AASVERSION); @@ -261,10 +255,10 @@ void AAS_FileInfo(void) botimport.Print(PRT_MESSAGE, "portalindexsize = %d\n", aasworld.portalindexsize); botimport.Print(PRT_MESSAGE, "numclusters = %d\n", aasworld.numclusters); // - for (n = 0, i = 0; i < aasworld.numareasettings; i++) - { - if (aasworld.areasettings[i].areaflags & AREA_GROUNDED) n++; - } //end for + for (n = 0, i = 0; i < aasworld.numareasettings; i++) { + if (aasworld.areasettings[i].areaflags & AREA_GROUNDED) + n++; + } // end for botimport.Print(PRT_MESSAGE, "num grounded areas = %d\n", n); // botimport.Print(PRT_MESSAGE, "planes size %d bytes\n", aasworld.numplanes * sizeof(aas_plane_t)); @@ -275,16 +269,12 @@ void AAS_FileInfo(void) botimport.Print(PRT_MESSAGE, "portals size %d bytes\n", aasworld.numportals * sizeof(aas_portal_t)); botimport.Print(PRT_MESSAGE, "clusters size %d bytes\n", aasworld.numclusters * sizeof(aas_cluster_t)); - optimized = aasworld.numplanes * sizeof(aas_plane_t) + - aasworld.numareas * sizeof(aas_area_t) + - aasworld.numareasettings * sizeof(aas_areasettings_t) + - aasworld.numnodes * sizeof(aas_node_t) + - aasworld.reachabilitysize * sizeof(aas_reachability_t) + - aasworld.numportals * sizeof(aas_portal_t) + - aasworld.numclusters * sizeof(aas_cluster_t); + optimized = aasworld.numplanes * sizeof(aas_plane_t) + aasworld.numareas * sizeof(aas_area_t) + aasworld.numareasettings * sizeof(aas_areasettings_t) + + aasworld.numnodes * sizeof(aas_node_t) + aasworld.reachabilitysize * sizeof(aas_reachability_t) + aasworld.numportals * sizeof(aas_portal_t) + + aasworld.numclusters * sizeof(aas_cluster_t); botimport.Print(PRT_MESSAGE, "optimzed size %d KB\n", optimized >> 10); -} //end of the function AAS_FileInfo -#endif //AASFILEDEBUG +} // end of the function AAS_FileInfo +#endif // AASFILEDEBUG //=========================================================================== // allocate memory and read a lump of a AAS file // @@ -292,52 +282,45 @@ void AAS_FileInfo(void) // Returns: - // Changes Globals: - //=========================================================================== -char *AAS_LoadAASLump(fileHandle_t fp, int offset, int length, int *lastoffset, int size) -{ +char *AAS_LoadAASLump(fileHandle_t fp, int offset, int length, int *lastoffset, int size) { char *buf; // - if (!length) - { - //just alloc a dummy - return (char *) GetClearedHunkMemory(size+1); - } //end if - //seek to the data - if (offset != *lastoffset) - { + if (!length) { + // just alloc a dummy + return (char *)GetClearedHunkMemory(size + 1); + } // end if + // seek to the data + if (offset != *lastoffset) { botimport.Print(PRT_WARNING, "AAS file not sequentially read\n"); - if (botimport.FS_Seek(fp, offset, FS_SEEK_SET)) - { + if (botimport.FS_Seek(fp, offset, FS_SEEK_SET)) { AAS_Error("can't seek to aas lump\n"); AAS_DumpAASData(); botimport.FS_FCloseFile(fp); return 0; - } //end if - } //end if - //allocate memory - buf = (char *) GetClearedHunkMemory(length+1); - //read the data - if (length) - { - botimport.FS_Read(buf, length, fp ); + } // end if + } // end if + // allocate memory + buf = (char *)GetClearedHunkMemory(length + 1); + // read the data + if (length) { + botimport.FS_Read(buf, length, fp); *lastoffset += length; - } //end if + } // end if return buf; -} //end of the function AAS_LoadAASLump +} // end of the function AAS_LoadAASLump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DData(unsigned char *data, int size) -{ +void AAS_DData(unsigned char *data, int size) { int i; - for (i = 0; i < size; i++) - { - data[i] ^= (unsigned char) i * 119; - } //end for -} //end of the function AAS_DData + for (i = 0; i < size; i++) { + data[i] ^= (unsigned char)i * 119; + } // end for +} // end of the function AAS_DData //=========================================================================== // load an aas file // @@ -345,153 +328,161 @@ void AAS_DData(unsigned char *data, int size) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_LoadAASFile(char *filename) -{ +int AAS_LoadAASFile(char *filename) { fileHandle_t fp; aas_header_t header; int offset, length, lastoffset; botimport.Print(PRT_MESSAGE, "trying to load %s\n", filename); - //dump current loaded aas file + // dump current loaded aas file AAS_DumpAASData(); - //open the file - botimport.FS_FOpenFile( filename, &fp, FS_READ ); - if (!fp) - { + // open the file + botimport.FS_FOpenFile(filename, &fp, FS_READ); + if (!fp) { AAS_Error("can't open %s\n", filename); return BLERR_CANNOTOPENAASFILE; - } //end if - //read the header - botimport.FS_Read(&header, sizeof(aas_header_t), fp ); + } // end if + // read the header + botimport.FS_Read(&header, sizeof(aas_header_t), fp); lastoffset = sizeof(aas_header_t); - //check header identification + // check header identification header.ident = LittleLong(header.ident); - if (header.ident != AASID) - { + if (header.ident != AASID) { AAS_Error("%s is not an AAS file\n", filename); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEID; - } //end if - //check the version + } // end if + // check the version header.version = LittleLong(header.version); // - if (header.version != AASVERSION_OLD && header.version != AASVERSION) - { + if (header.version != AASVERSION_OLD && header.version != AASVERSION) { AAS_Error("aas file %s is version %i, not %i\n", filename, header.version, AASVERSION); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEVERSION; - } //end if + } // end if // - if (header.version == AASVERSION) - { - AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8); - } //end if + if (header.version == AASVERSION) { + AAS_DData((unsigned char *)&header + 8, sizeof(aas_header_t) - 8); + } // end if // - aasworld.bspchecksum = atoi(LibVarGetString( "sv_mapChecksum")); - if (LittleLong(header.bspchecksum) != aasworld.bspchecksum) - { + aasworld.bspchecksum = atoi(LibVarGetString("sv_mapChecksum")); + if (LittleLong(header.bspchecksum) != aasworld.bspchecksum) { AAS_Error("aas file %s is out of date\n", filename); botimport.FS_FCloseFile(fp); return BLERR_WRONGAASFILEVERSION; - } //end if - //load the lumps: - //bounding boxes + } // end if + // load the lumps: + // bounding boxes offset = LittleLong(header.lumps[AASLUMP_BBOXES].fileofs); length = LittleLong(header.lumps[AASLUMP_BBOXES].filelen); - aasworld.bboxes = (aas_bbox_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_bbox_t)); + aasworld.bboxes = (aas_bbox_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_bbox_t)); aasworld.numbboxes = length / sizeof(aas_bbox_t); - if (aasworld.numbboxes && !aasworld.bboxes) return BLERR_CANNOTREADAASLUMP; - //vertexes + if (aasworld.numbboxes && !aasworld.bboxes) + return BLERR_CANNOTREADAASLUMP; + // vertexes offset = LittleLong(header.lumps[AASLUMP_VERTEXES].fileofs); length = LittleLong(header.lumps[AASLUMP_VERTEXES].filelen); - aasworld.vertexes = (aas_vertex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_vertex_t)); + aasworld.vertexes = (aas_vertex_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_vertex_t)); aasworld.numvertexes = length / sizeof(aas_vertex_t); - if (aasworld.numvertexes && !aasworld.vertexes) return BLERR_CANNOTREADAASLUMP; - //planes + if (aasworld.numvertexes && !aasworld.vertexes) + return BLERR_CANNOTREADAASLUMP; + // planes offset = LittleLong(header.lumps[AASLUMP_PLANES].fileofs); length = LittleLong(header.lumps[AASLUMP_PLANES].filelen); - aasworld.planes = (aas_plane_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_plane_t)); + aasworld.planes = (aas_plane_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_plane_t)); aasworld.numplanes = length / sizeof(aas_plane_t); - if (aasworld.numplanes && !aasworld.planes) return BLERR_CANNOTREADAASLUMP; - //edges + if (aasworld.numplanes && !aasworld.planes) + return BLERR_CANNOTREADAASLUMP; + // edges offset = LittleLong(header.lumps[AASLUMP_EDGES].fileofs); length = LittleLong(header.lumps[AASLUMP_EDGES].filelen); - aasworld.edges = (aas_edge_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edge_t)); + aasworld.edges = (aas_edge_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edge_t)); aasworld.numedges = length / sizeof(aas_edge_t); - if (aasworld.numedges && !aasworld.edges) return BLERR_CANNOTREADAASLUMP; - //edgeindex + if (aasworld.numedges && !aasworld.edges) + return BLERR_CANNOTREADAASLUMP; + // edgeindex offset = LittleLong(header.lumps[AASLUMP_EDGEINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_EDGEINDEX].filelen); - aasworld.edgeindex = (aas_edgeindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edgeindex_t)); + aasworld.edgeindex = (aas_edgeindex_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_edgeindex_t)); aasworld.edgeindexsize = length / sizeof(aas_edgeindex_t); - if (aasworld.edgeindexsize && !aasworld.edgeindex) return BLERR_CANNOTREADAASLUMP; - //faces + if (aasworld.edgeindexsize && !aasworld.edgeindex) + return BLERR_CANNOTREADAASLUMP; + // faces offset = LittleLong(header.lumps[AASLUMP_FACES].fileofs); length = LittleLong(header.lumps[AASLUMP_FACES].filelen); - aasworld.faces = (aas_face_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_face_t)); + aasworld.faces = (aas_face_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_face_t)); aasworld.numfaces = length / sizeof(aas_face_t); - if (aasworld.numfaces && !aasworld.faces) return BLERR_CANNOTREADAASLUMP; - //faceindex + if (aasworld.numfaces && !aasworld.faces) + return BLERR_CANNOTREADAASLUMP; + // faceindex offset = LittleLong(header.lumps[AASLUMP_FACEINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_FACEINDEX].filelen); - aasworld.faceindex = (aas_faceindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_faceindex_t)); + aasworld.faceindex = (aas_faceindex_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_faceindex_t)); aasworld.faceindexsize = length / sizeof(aas_faceindex_t); - if (aasworld.faceindexsize && !aasworld.faceindex) return BLERR_CANNOTREADAASLUMP; - //convex areas + if (aasworld.faceindexsize && !aasworld.faceindex) + return BLERR_CANNOTREADAASLUMP; + // convex areas offset = LittleLong(header.lumps[AASLUMP_AREAS].fileofs); length = LittleLong(header.lumps[AASLUMP_AREAS].filelen); - aasworld.areas = (aas_area_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_area_t)); + aasworld.areas = (aas_area_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_area_t)); aasworld.numareas = length / sizeof(aas_area_t); - if (aasworld.numareas && !aasworld.areas) return BLERR_CANNOTREADAASLUMP; - //area settings + if (aasworld.numareas && !aasworld.areas) + return BLERR_CANNOTREADAASLUMP; + // area settings offset = LittleLong(header.lumps[AASLUMP_AREASETTINGS].fileofs); length = LittleLong(header.lumps[AASLUMP_AREASETTINGS].filelen); - aasworld.areasettings = (aas_areasettings_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_areasettings_t)); + aasworld.areasettings = (aas_areasettings_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_areasettings_t)); aasworld.numareasettings = length / sizeof(aas_areasettings_t); - if (aasworld.numareasettings && !aasworld.areasettings) return BLERR_CANNOTREADAASLUMP; - //reachability list + if (aasworld.numareasettings && !aasworld.areasettings) + return BLERR_CANNOTREADAASLUMP; + // reachability list offset = LittleLong(header.lumps[AASLUMP_REACHABILITY].fileofs); length = LittleLong(header.lumps[AASLUMP_REACHABILITY].filelen); - aasworld.reachability = (aas_reachability_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_reachability_t)); + aasworld.reachability = (aas_reachability_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_reachability_t)); aasworld.reachabilitysize = length / sizeof(aas_reachability_t); - if (aasworld.reachabilitysize && !aasworld.reachability) return BLERR_CANNOTREADAASLUMP; - //nodes + if (aasworld.reachabilitysize && !aasworld.reachability) + return BLERR_CANNOTREADAASLUMP; + // nodes offset = LittleLong(header.lumps[AASLUMP_NODES].fileofs); length = LittleLong(header.lumps[AASLUMP_NODES].filelen); - aasworld.nodes = (aas_node_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_node_t)); + aasworld.nodes = (aas_node_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_node_t)); aasworld.numnodes = length / sizeof(aas_node_t); - if (aasworld.numnodes && !aasworld.nodes) return BLERR_CANNOTREADAASLUMP; - //cluster portals + if (aasworld.numnodes && !aasworld.nodes) + return BLERR_CANNOTREADAASLUMP; + // cluster portals offset = LittleLong(header.lumps[AASLUMP_PORTALS].fileofs); length = LittleLong(header.lumps[AASLUMP_PORTALS].filelen); - aasworld.portals = (aas_portal_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portal_t)); + aasworld.portals = (aas_portal_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portal_t)); aasworld.numportals = length / sizeof(aas_portal_t); - if (aasworld.numportals && !aasworld.portals) return BLERR_CANNOTREADAASLUMP; - //cluster portal index + if (aasworld.numportals && !aasworld.portals) + return BLERR_CANNOTREADAASLUMP; + // cluster portal index offset = LittleLong(header.lumps[AASLUMP_PORTALINDEX].fileofs); length = LittleLong(header.lumps[AASLUMP_PORTALINDEX].filelen); - aasworld.portalindex = (aas_portalindex_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portalindex_t)); + aasworld.portalindex = (aas_portalindex_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_portalindex_t)); aasworld.portalindexsize = length / sizeof(aas_portalindex_t); - if (aasworld.portalindexsize && !aasworld.portalindex) return BLERR_CANNOTREADAASLUMP; - //clusters + if (aasworld.portalindexsize && !aasworld.portalindex) + return BLERR_CANNOTREADAASLUMP; + // clusters offset = LittleLong(header.lumps[AASLUMP_CLUSTERS].fileofs); length = LittleLong(header.lumps[AASLUMP_CLUSTERS].filelen); - aasworld.clusters = (aas_cluster_t *) AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_cluster_t)); + aasworld.clusters = (aas_cluster_t *)AAS_LoadAASLump(fp, offset, length, &lastoffset, sizeof(aas_cluster_t)); aasworld.numclusters = length / sizeof(aas_cluster_t); - if (aasworld.numclusters && !aasworld.clusters) return BLERR_CANNOTREADAASLUMP; - //swap everything + if (aasworld.numclusters && !aasworld.clusters) + return BLERR_CANNOTREADAASLUMP; + // swap everything AAS_SwapAASData(); - //aas file is loaded + // aas file is loaded aasworld.loaded = qtrue; - //close the file + // close the file botimport.FS_FCloseFile(fp); // #ifdef AASFILEDEBUG AAS_FileInfo(); -#endif //AASFILEDEBUG +#endif // AASFILEDEBUG // return BLERR_NOERROR; -} //end of the function AAS_LoadAASFile +} // end of the function AAS_LoadAASFile //=========================================================================== // // Parameter: - @@ -500,24 +491,22 @@ int AAS_LoadAASFile(char *filename) //=========================================================================== static int AAS_WriteAASLump_offset; -int AAS_WriteAASLump(fileHandle_t fp, aas_header_t *h, int lumpnum, void *data, int length) -{ +int AAS_WriteAASLump(fileHandle_t fp, aas_header_t *h, int lumpnum, void *data, int length) { aas_lump_t *lump; lump = &h->lumps[lumpnum]; - lump->fileofs = LittleLong(AAS_WriteAASLump_offset); //LittleLong(ftell(fp)); + lump->fileofs = LittleLong(AAS_WriteAASLump_offset); // LittleLong(ftell(fp)); lump->filelen = LittleLong(length); - if (length > 0) - { - botimport.FS_Write(data, length, fp ); - } //end if + if (length > 0) { + botimport.FS_Write(data, length, fp); + } // end if AAS_WriteAASLump_offset += length; return qtrue; -} //end of the function AAS_WriteAASLump +} // end of the function AAS_WriteAASLump //=========================================================================== // aas data is useless after writing to file because it is byte swapped // @@ -525,63 +514,61 @@ int AAS_WriteAASLump(fileHandle_t fp, aas_header_t *h, int lumpnum, void *data, // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_WriteAASFile(char *filename) -{ +qboolean AAS_WriteAASFile(char *filename) { aas_header_t header; fileHandle_t fp; botimport.Print(PRT_MESSAGE, "writing %s\n", filename); - //swap the aas data + // swap the aas data AAS_SwapAASData(); - //initialize the file header + // initialize the file header Com_Memset(&header, 0, sizeof(aas_header_t)); header.ident = LittleLong(AASID); header.version = LittleLong(AASVERSION); header.bspchecksum = LittleLong(aasworld.bspchecksum); - //open a new file - botimport.FS_FOpenFile( filename, &fp, FS_WRITE ); - if (!fp) - { + // open a new file + botimport.FS_FOpenFile(filename, &fp, FS_WRITE); + if (!fp) { botimport.Print(PRT_ERROR, "error opening %s\n", filename); return qfalse; - } //end if - //write the header + } // end if + // write the header botimport.FS_Write(&header, sizeof(aas_header_t), fp); AAS_WriteAASLump_offset = sizeof(aas_header_t); - //add the data lumps to the file - if (!AAS_WriteAASLump(fp, &header, AASLUMP_BBOXES, aasworld.bboxes, - aasworld.numbboxes * sizeof(aas_bbox_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_VERTEXES, aasworld.vertexes, - aasworld.numvertexes * sizeof(aas_vertex_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_PLANES, aasworld.planes, - aasworld.numplanes * sizeof(aas_plane_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGES, aasworld.edges, - aasworld.numedges * sizeof(aas_edge_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGEINDEX, aasworld.edgeindex, - aasworld.edgeindexsize * sizeof(aas_edgeindex_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACES, aasworld.faces, - aasworld.numfaces * sizeof(aas_face_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACEINDEX, aasworld.faceindex, - aasworld.faceindexsize * sizeof(aas_faceindex_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREAS, aasworld.areas, - aasworld.numareas * sizeof(aas_area_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREASETTINGS, aasworld.areasettings, - aasworld.numareasettings * sizeof(aas_areasettings_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_REACHABILITY, aasworld.reachability, - aasworld.reachabilitysize * sizeof(aas_reachability_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_NODES, aasworld.nodes, - aasworld.numnodes * sizeof(aas_node_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALS, aasworld.portals, - aasworld.numportals * sizeof(aas_portal_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALINDEX, aasworld.portalindex, - aasworld.portalindexsize * sizeof(aas_portalindex_t))) return qfalse; - if (!AAS_WriteAASLump(fp, &header, AASLUMP_CLUSTERS, aasworld.clusters, - aasworld.numclusters * sizeof(aas_cluster_t))) return qfalse; - //rewrite the header with the added lumps + // add the data lumps to the file + if (!AAS_WriteAASLump(fp, &header, AASLUMP_BBOXES, aasworld.bboxes, aasworld.numbboxes * sizeof(aas_bbox_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_VERTEXES, aasworld.vertexes, aasworld.numvertexes * sizeof(aas_vertex_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_PLANES, aasworld.planes, aasworld.numplanes * sizeof(aas_plane_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGES, aasworld.edges, aasworld.numedges * sizeof(aas_edge_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_EDGEINDEX, aasworld.edgeindex, aasworld.edgeindexsize * sizeof(aas_edgeindex_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACES, aasworld.faces, aasworld.numfaces * sizeof(aas_face_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_FACEINDEX, aasworld.faceindex, aasworld.faceindexsize * sizeof(aas_faceindex_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREAS, aasworld.areas, aasworld.numareas * sizeof(aas_area_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_AREASETTINGS, aasworld.areasettings, aasworld.numareasettings * sizeof(aas_areasettings_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_REACHABILITY, aasworld.reachability, aasworld.reachabilitysize * sizeof(aas_reachability_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_NODES, aasworld.nodes, aasworld.numnodes * sizeof(aas_node_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALS, aasworld.portals, aasworld.numportals * sizeof(aas_portal_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_PORTALINDEX, aasworld.portalindex, aasworld.portalindexsize * sizeof(aas_portalindex_t))) + return qfalse; + if (!AAS_WriteAASLump(fp, &header, AASLUMP_CLUSTERS, aasworld.clusters, aasworld.numclusters * sizeof(aas_cluster_t))) + return qfalse; + // rewrite the header with the added lumps botimport.FS_Seek(fp, 0, FS_SEEK_SET); - AAS_DData((unsigned char *) &header + 8, sizeof(aas_header_t) - 8); + AAS_DData((unsigned char *)&header + 8, sizeof(aas_header_t) - 8); botimport.FS_Write(&header, sizeof(aas_header_t), fp); - //close the file + // close the file botimport.FS_FCloseFile(fp); return qtrue; -} //end of the function AAS_WriteAASFile +} // end of the function AAS_WriteAASFile diff --git a/codemp/botlib/be_aas_main.cpp b/codemp/botlib/be_aas_main.cpp index 60093cba75..cf540a8ecc 100644 --- a/codemp/botlib/be_aas_main.cpp +++ b/codemp/botlib/be_aas_main.cpp @@ -59,8 +59,7 @@ libvar_t *saveroutingcache; // Returns: - // Changes Globals: - //=========================================================================== -void QDECL AAS_Error(char *fmt, ...) -{ +void QDECL AAS_Error(char *fmt, ...) { char str[1024]; va_list arglist; @@ -68,81 +67,74 @@ void QDECL AAS_Error(char *fmt, ...) Q_vsnprintf(str, sizeof(str), fmt, arglist); va_end(arglist); botimport.Print(PRT_FATAL, "%s", str); -} //end of the function AAS_Error +} // end of the function AAS_Error //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Loaded(void) -{ - return aasworld.loaded; -} //end of the function AAS_Loaded +int AAS_Loaded(void) { return aasworld.loaded; } // end of the function AAS_Loaded //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Initialized(void) -{ - return aasworld.initialized; -} //end of the function AAS_Initialized +int AAS_Initialized(void) { return aasworld.initialized; } // end of the function AAS_Initialized //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_SetInitialized(void) -{ +void AAS_SetInitialized(void) { aasworld.initialized = qtrue; botimport.Print(PRT_MESSAGE, "AAS initialized.\n"); #ifdef DEBUG - //create all the routing cache - //AAS_CreateAllRoutingCache(); + // create all the routing cache + // AAS_CreateAllRoutingCache(); // - //AAS_RoutingInfo(); + // AAS_RoutingInfo(); #endif -} //end of the function AAS_SetInitialized +} // end of the function AAS_SetInitialized //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ContinueInit(float time) -{ - //if no AAS file loaded - if (!aasworld.loaded) return; - //if AAS is already initialized - if (aasworld.initialized) return; - //calculate reachability, if not finished return - if (AAS_ContinueInitReachability(time)) return; - //initialize clustering for the new map +void AAS_ContinueInit(float time) { + // if no AAS file loaded + if (!aasworld.loaded) + return; + // if AAS is already initialized + if (aasworld.initialized) + return; + // calculate reachability, if not finished return + if (AAS_ContinueInitReachability(time)) + return; + // initialize clustering for the new map AAS_InitClustering(); - //if reachability has been calculated and an AAS file should be written - //or there is a forced data optimization - if (aasworld.savefile || ((int)LibVarGetValue("forcewrite"))) - { - //optimize the AAS data - if ((int)LibVarValue("aasoptimize", "0")) AAS_Optimize(); - //save the AAS file - if (AAS_WriteAASFile(aasworld.filename)) - { + // if reachability has been calculated and an AAS file should be written + // or there is a forced data optimization + if (aasworld.savefile || ((int)LibVarGetValue("forcewrite"))) { + // optimize the AAS data + if ((int)LibVarValue("aasoptimize", "0")) + AAS_Optimize(); + // save the AAS file + if (AAS_WriteAASFile(aasworld.filename)) { botimport.Print(PRT_MESSAGE, "%s written successfully\n", aasworld.filename); - } //end if - else - { + } // end if + else { botimport.Print(PRT_ERROR, "couldn't write %s\n", aasworld.filename); - } //end else - } //end if - //initialize the routing + } // end else + } // end if + // initialize the routing AAS_InitRouting(); - //at this point AAS is initialized + // at this point AAS is initialized AAS_SetInitialized(); -} //end of the function AAS_ContinueInit +} // end of the function AAS_ContinueInit //=========================================================================== // called at the start of every frame // @@ -150,93 +142,82 @@ void AAS_ContinueInit(float time) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_StartFrame(float time) -{ +int AAS_StartFrame(float time) { aasworld.time = time; - //unlink all entities that were not updated last frame + // unlink all entities that were not updated last frame AAS_UnlinkInvalidEntities(); - //invalidate the entities + // invalidate the entities AAS_InvalidateEntities(); - //initialize AAS + // initialize AAS AAS_ContinueInit(time); // aasworld.frameroutingupdates = 0; // - if (botDeveloper) - { - if (LibVarGetValue("showcacheupdates")) - { + if (botDeveloper) { + if (LibVarGetValue("showcacheupdates")) { AAS_RoutingInfo(); LibVarSet("showcacheupdates", "0"); - } //end if - if (LibVarGetValue("showmemoryusage")) - { + } // end if + if (LibVarGetValue("showmemoryusage")) { PrintUsedMemorySize(); LibVarSet("showmemoryusage", "0"); - } //end if - if (LibVarGetValue("memorydump")) - { + } // end if + if (LibVarGetValue("memorydump")) { PrintMemoryLabels(); LibVarSet("memorydump", "0"); - } //end if - } //end if + } // end if + } // end if // - if (saveroutingcache->value) - { + if (saveroutingcache->value) { AAS_WriteRouteCache(); LibVarSet("saveroutingcache", "0"); - } //end if + } // end if // aasworld.numframes++; return BLERR_NOERROR; -} //end of the function AAS_StartFrame +} // end of the function AAS_StartFrame //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float AAS_Time(void) -{ - return aasworld.time; -} //end of the function AAS_Time +float AAS_Time(void) { return aasworld.time; } // end of the function AAS_Time //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj ) -{ +void AAS_ProjectPointOntoVector(vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj) { vec3_t pVec, vec; - VectorSubtract( point, vStart, pVec ); - VectorSubtract( vEnd, vStart, vec ); - VectorNormalize( vec ); + VectorSubtract(point, vStart, pVec); + VectorSubtract(vEnd, vStart, vec); + VectorNormalize(vec); // project onto the directional vector for this segment - VectorMA( vStart, DotProduct( pVec, vec ), vec, vProj ); -} //end of the function AAS_ProjectPointOntoVector + VectorMA(vStart, DotProduct(pVec, vec), vec, vProj); +} // end of the function AAS_ProjectPointOntoVector //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_LoadFiles(const char *mapname) -{ +int AAS_LoadFiles(const char *mapname) { int errnum; char aasfile[MAX_PATH]; -// char bspfile[MAX_PATH]; + // char bspfile[MAX_PATH]; strcpy(aasworld.mapname, mapname); - //NOTE: first reset the entity links into the AAS areas and BSP leaves - // the AAS link heap and BSP link heap are reset after respectively the - // AAS file and BSP file are loaded + // NOTE: first reset the entity links into the AAS areas and BSP leaves + // the AAS link heap and BSP link heap are reset after respectively the + // AAS file and BSP file are loaded AAS_ResetEntityLinks(); // load bsp info AAS_LoadBSPFile(); - //load the aas file + // load the aas file Com_sprintf(aasfile, MAX_PATH, "maps/%s.aas", mapname); errnum = AAS_LoadAASFile(aasfile); if (errnum != BLERR_NOERROR) @@ -245,7 +226,7 @@ int AAS_LoadFiles(const char *mapname) botimport.Print(PRT_MESSAGE, "loaded %s\n", aasfile); strncpy(aasworld.filename, aasfile, MAX_PATH); return BLERR_NOERROR; -} //end of the function AAS_LoadFiles +} // end of the function AAS_LoadFiles //=========================================================================== // called everytime a map changes // @@ -253,41 +234,38 @@ int AAS_LoadFiles(const char *mapname) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_LoadMap(const char *mapname) -{ - int errnum; +int AAS_LoadMap(const char *mapname) { + int errnum; - //if no mapname is provided then the string indexes are updated - if (!mapname) - { + // if no mapname is provided then the string indexes are updated + if (!mapname) { return 0; - } //end if + } // end if // aasworld.initialized = qfalse; - //NOTE: free the routing caches before loading a new map because - // to free the caches the old number of areas, number of clusters - // and number of areas in a clusters must be available + // NOTE: free the routing caches before loading a new map because + // to free the caches the old number of areas, number of clusters + // and number of areas in a clusters must be available AAS_FreeRoutingCaches(); - //load the map + // load the map errnum = AAS_LoadFiles(mapname); - if (errnum != BLERR_NOERROR) - { + if (errnum != BLERR_NOERROR) { aasworld.loaded = qfalse; return errnum; - } //end if + } // end if // AAS_InitSettings(); - //initialize the AAS link heap for the new map + // initialize the AAS link heap for the new map AAS_InitAASLinkHeap(); - //initialize the AAS linked entities for the new map + // initialize the AAS linked entities for the new map AAS_InitAASLinkedEntities(); - //initialize reachability for the new map + // initialize reachability for the new map AAS_InitReachability(); - //initialize the alternative routing + // initialize the alternative routing AAS_InitAlternativeRouting(); - //everything went ok + // everything went ok return 0; -} //end of the function AAS_LoadMap +} // end of the function AAS_LoadMap //=========================================================================== // called when the library is first loaded // @@ -295,50 +273,50 @@ int AAS_LoadMap(const char *mapname) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Setup(void) -{ - aasworld.maxclients = (int) LibVarValue("maxclients", "128"); - aasworld.maxentities = (int) LibVarValue("maxentities", "1024"); +int AAS_Setup(void) { + aasworld.maxclients = (int)LibVarValue("maxclients", "128"); + aasworld.maxentities = (int)LibVarValue("maxentities", "1024"); // as soon as it's set to 1 the routing cache will be saved saveroutingcache = LibVar("saveroutingcache", "0"); - //allocate memory for the entities - if (aasworld.entities) FreeMemory(aasworld.entities); - aasworld.entities = (aas_entity_t *) GetClearedHunkMemory(aasworld.maxentities * sizeof(aas_entity_t)); - //invalidate all the entities + // allocate memory for the entities + if (aasworld.entities) + FreeMemory(aasworld.entities); + aasworld.entities = (aas_entity_t *)GetClearedHunkMemory(aasworld.maxentities * sizeof(aas_entity_t)); + // invalidate all the entities AAS_InvalidateEntities(); - //force some recalculations - //LibVarSet("forceclustering", "1"); //force clustering calculation - //LibVarSet("forcereachability", "1"); //force reachability calculation + // force some recalculations + // LibVarSet("forceclustering", "1"); //force clustering calculation + // LibVarSet("forcereachability", "1"); //force reachability calculation aasworld.numframes = 0; return BLERR_NOERROR; -} //end of the function AAS_Setup +} // end of the function AAS_Setup //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Shutdown(void) -{ +void AAS_Shutdown(void) { AAS_ShutdownAlternativeRouting(); // AAS_DumpBSPData(); - //free routing caches + // free routing caches AAS_FreeRoutingCaches(); - //free aas link heap + // free aas link heap AAS_FreeAASLinkHeap(); - //free aas linked entities + // free aas linked entities AAS_FreeAASLinkedEntities(); - //free the aas data + // free the aas data AAS_DumpAASData(); - //free the entities - if (aasworld.entities) FreeMemory(aasworld.entities); - //clear the aasworld structure + // free the entities + if (aasworld.entities) + FreeMemory(aasworld.entities); + // clear the aasworld structure Com_Memset(&aasworld, 0, sizeof(aas_t)); - //aas has not been initialized + // aas has not been initialized aasworld.initialized = qfalse; - //NOTE: as soon as a new .bsp file is loaded the .bsp file memory is - // freed and reallocated, so there's no need to free that memory here - //print shutdown -// botimport.Print(PRT_MESSAGE, "AAS shutdown.\n"); -} //end of the function AAS_Shutdown + // NOTE: as soon as a new .bsp file is loaded the .bsp file memory is + // freed and reallocated, so there's no need to free that memory here + // print shutdown + // botimport.Print(PRT_MESSAGE, "AAS shutdown.\n"); +} // end of the function AAS_Shutdown diff --git a/codemp/botlib/be_aas_move.cpp b/codemp/botlib/be_aas_move.cpp index bcfcd01802..f23eb636be 100644 --- a/codemp/botlib/be_aas_move.cpp +++ b/codemp/botlib/be_aas_move.cpp @@ -58,66 +58,65 @@ aas_settings_t aassettings; // Returns: - // Changes Globals: - //=========================================================================== -int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs) -{ +int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs) { vec3_t end; bsp_trace_t trace; VectorCopy(origin, end); end[2] -= 100; trace = AAS_Trace(origin, mins, maxs, end, 0, CONTENTS_SOLID); - if (trace.startsolid) return qfalse; + if (trace.startsolid) + return qfalse; VectorCopy(trace.endpos, origin); return qtrue; -} //end of the function AAS_DropToFloor +} // end of the function AAS_DropToFloor //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitSettings(void) -{ - aassettings.phys_gravitydirection[0] = 0; - aassettings.phys_gravitydirection[1] = 0; - aassettings.phys_gravitydirection[2] = -1; - aassettings.phys_friction = LibVarValue("phys_friction", "6"); - aassettings.phys_stopspeed = LibVarValue("phys_stopspeed", "100"); - aassettings.phys_gravity = LibVarValue("phys_gravity", "800"); - aassettings.phys_waterfriction = LibVarValue("phys_waterfriction", "1"); - aassettings.phys_watergravity = LibVarValue("phys_watergravity", "400"); - aassettings.phys_maxvelocity = LibVarValue("phys_maxvelocity", "320"); - aassettings.phys_maxwalkvelocity = LibVarValue("phys_maxwalkvelocity", "320"); - aassettings.phys_maxcrouchvelocity = LibVarValue("phys_maxcrouchvelocity", "100"); - aassettings.phys_maxswimvelocity = LibVarValue("phys_maxswimvelocity", "150"); - aassettings.phys_walkaccelerate = LibVarValue("phys_walkaccelerate", "10"); - aassettings.phys_airaccelerate = LibVarValue("phys_airaccelerate", "1"); - aassettings.phys_swimaccelerate = LibVarValue("phys_swimaccelerate", "4"); - aassettings.phys_maxstep = LibVarValue("phys_maxstep", "19"); - aassettings.phys_maxsteepness = LibVarValue("phys_maxsteepness", "0.7"); - aassettings.phys_maxwaterjump = LibVarValue("phys_maxwaterjump", "18"); - aassettings.phys_maxbarrier = LibVarValue("phys_maxbarrier", "33"); - aassettings.phys_jumpvel = LibVarValue("phys_jumpvel", "270"); - aassettings.phys_falldelta5 = LibVarValue("phys_falldelta5", "40"); - aassettings.phys_falldelta10 = LibVarValue("phys_falldelta10", "60"); - aassettings.rs_waterjump = LibVarValue("rs_waterjump", "400"); - aassettings.rs_teleport = LibVarValue("rs_teleport", "50"); - aassettings.rs_barrierjump = LibVarValue("rs_barrierjump", "100"); - aassettings.rs_startcrouch = LibVarValue("rs_startcrouch", "300"); - aassettings.rs_startgrapple = LibVarValue("rs_startgrapple", "500"); - aassettings.rs_startwalkoffledge = LibVarValue("rs_startwalkoffledge", "70"); - aassettings.rs_startjump = LibVarValue("rs_startjump", "300"); - aassettings.rs_rocketjump = LibVarValue("rs_rocketjump", "500"); - aassettings.rs_bfgjump = LibVarValue("rs_bfgjump", "500"); - aassettings.rs_jumppad = LibVarValue("rs_jumppad", "250"); - aassettings.rs_aircontrolledjumppad = LibVarValue("rs_aircontrolledjumppad", "300"); - aassettings.rs_funcbob = LibVarValue("rs_funcbob", "300"); - aassettings.rs_startelevator = LibVarValue("rs_startelevator", "50"); - aassettings.rs_falldamage5 = LibVarValue("rs_falldamage5", "300"); - aassettings.rs_falldamage10 = LibVarValue("rs_falldamage10", "500"); - aassettings.rs_maxfallheight = LibVarValue("rs_maxfallheight", "0"); - aassettings.rs_maxjumpfallheight = LibVarValue("rs_maxjumpfallheight", "450"); -} //end of the function AAS_InitSettings +void AAS_InitSettings(void) { + aassettings.phys_gravitydirection[0] = 0; + aassettings.phys_gravitydirection[1] = 0; + aassettings.phys_gravitydirection[2] = -1; + aassettings.phys_friction = LibVarValue("phys_friction", "6"); + aassettings.phys_stopspeed = LibVarValue("phys_stopspeed", "100"); + aassettings.phys_gravity = LibVarValue("phys_gravity", "800"); + aassettings.phys_waterfriction = LibVarValue("phys_waterfriction", "1"); + aassettings.phys_watergravity = LibVarValue("phys_watergravity", "400"); + aassettings.phys_maxvelocity = LibVarValue("phys_maxvelocity", "320"); + aassettings.phys_maxwalkvelocity = LibVarValue("phys_maxwalkvelocity", "320"); + aassettings.phys_maxcrouchvelocity = LibVarValue("phys_maxcrouchvelocity", "100"); + aassettings.phys_maxswimvelocity = LibVarValue("phys_maxswimvelocity", "150"); + aassettings.phys_walkaccelerate = LibVarValue("phys_walkaccelerate", "10"); + aassettings.phys_airaccelerate = LibVarValue("phys_airaccelerate", "1"); + aassettings.phys_swimaccelerate = LibVarValue("phys_swimaccelerate", "4"); + aassettings.phys_maxstep = LibVarValue("phys_maxstep", "19"); + aassettings.phys_maxsteepness = LibVarValue("phys_maxsteepness", "0.7"); + aassettings.phys_maxwaterjump = LibVarValue("phys_maxwaterjump", "18"); + aassettings.phys_maxbarrier = LibVarValue("phys_maxbarrier", "33"); + aassettings.phys_jumpvel = LibVarValue("phys_jumpvel", "270"); + aassettings.phys_falldelta5 = LibVarValue("phys_falldelta5", "40"); + aassettings.phys_falldelta10 = LibVarValue("phys_falldelta10", "60"); + aassettings.rs_waterjump = LibVarValue("rs_waterjump", "400"); + aassettings.rs_teleport = LibVarValue("rs_teleport", "50"); + aassettings.rs_barrierjump = LibVarValue("rs_barrierjump", "100"); + aassettings.rs_startcrouch = LibVarValue("rs_startcrouch", "300"); + aassettings.rs_startgrapple = LibVarValue("rs_startgrapple", "500"); + aassettings.rs_startwalkoffledge = LibVarValue("rs_startwalkoffledge", "70"); + aassettings.rs_startjump = LibVarValue("rs_startjump", "300"); + aassettings.rs_rocketjump = LibVarValue("rs_rocketjump", "500"); + aassettings.rs_bfgjump = LibVarValue("rs_bfgjump", "500"); + aassettings.rs_jumppad = LibVarValue("rs_jumppad", "250"); + aassettings.rs_aircontrolledjumppad = LibVarValue("rs_aircontrolledjumppad", "300"); + aassettings.rs_funcbob = LibVarValue("rs_funcbob", "300"); + aassettings.rs_startelevator = LibVarValue("rs_startelevator", "50"); + aassettings.rs_falldamage5 = LibVarValue("rs_falldamage5", "300"); + aassettings.rs_falldamage10 = LibVarValue("rs_falldamage10", "500"); + aassettings.rs_maxfallheight = LibVarValue("rs_maxfallheight", "0"); + aassettings.rs_maxjumpfallheight = LibVarValue("rs_maxjumpfallheight", "450"); +} // end of the function AAS_InitSettings //=========================================================================== // returns qtrue if the bot is against a ladder // @@ -125,8 +124,7 @@ void AAS_InitSettings(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AgainstLadder(vec3_t origin) -{ +int AAS_AgainstLadder(vec3_t origin) { int areanum, i, facenum, side; vec3_t org; aas_plane_t *plane; @@ -135,51 +133,50 @@ int AAS_AgainstLadder(vec3_t origin) VectorCopy(origin, org); areanum = AAS_PointAreaNum(org); - if (!areanum) - { + if (!areanum) { org[0] += 1; areanum = AAS_PointAreaNum(org); - if (!areanum) - { + if (!areanum) { org[1] += 1; areanum = AAS_PointAreaNum(org); - if (!areanum) - { + if (!areanum) { org[0] -= 2; areanum = AAS_PointAreaNum(org); - if (!areanum) - { + if (!areanum) { org[1] -= 2; areanum = AAS_PointAreaNum(org); - } //end if - } //end if - } //end if - } //end if - //if in solid... wrrr shouldn't happen - if (!areanum) return qfalse; - //if not in a ladder area - if (!(aasworld.areasettings[areanum].areaflags & AREA_LADDER)) return qfalse; - //if a crouch only area - if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) return qfalse; + } // end if + } // end if + } // end if + } // end if + // if in solid... wrrr shouldn't happen + if (!areanum) + return qfalse; + // if not in a ladder area + if (!(aasworld.areasettings[areanum].areaflags & AREA_LADDER)) + return qfalse; + // if a crouch only area + if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) + return qfalse; // area = &aasworld.areas[areanum]; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = aasworld.faceindex[area->firstface + i]; side = facenum < 0; face = &aasworld.faces[abs(facenum)]; - //if the face isn't a ladder face - if (!(face->faceflags & FACE_LADDER)) continue; - //get the plane the face is in + // if the face isn't a ladder face + if (!(face->faceflags & FACE_LADDER)) + continue; + // get the plane the face is in plane = &aasworld.planes[face->planenum ^ side]; - //if the origin is pretty close to the plane - if (fabs(DotProduct(plane->normal, origin) - plane->dist) < 3) - { - if (AAS_PointInsideFace(abs(facenum), origin, 0.1f)) return qtrue; - } //end if - } //end for + // if the origin is pretty close to the plane + if (fabs(DotProduct(plane->normal, origin) - plane->dist) < 3) { + if (AAS_PointInsideFace(abs(facenum), origin, 0.1f)) + return qtrue; + } // end if + } // end for return qfalse; -} //end of the function AAS_AgainstLadder +} // end of the function AAS_AgainstLadder //=========================================================================== // returns qtrue if the bot is on the ground // @@ -187,8 +184,7 @@ int AAS_AgainstLadder(vec3_t origin) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_OnGround(vec3_t origin, int presencetype, int passent) -{ +int AAS_OnGround(vec3_t origin, int presencetype, int passent) { aas_trace_t trace; vec3_t end, up = {0, 0, 1}; aas_plane_t *plane; @@ -198,18 +194,22 @@ int AAS_OnGround(vec3_t origin, int presencetype, int passent) trace = AAS_TraceClientBBox(origin, end, presencetype, passent); - //if in solid - if (trace.startsolid) return qfalse; - //if nothing hit at all - if (trace.fraction >= 1.0) return qfalse; - //if too far from the hit plane - if (origin[2] - trace.endpos[2] > 10) return qfalse; - //check if the plane isn't too steep + // if in solid + if (trace.startsolid) + return qfalse; + // if nothing hit at all + if (trace.fraction >= 1.0) + return qfalse; + // if too far from the hit plane + if (origin[2] - trace.endpos[2] > 10) + return qfalse; + // check if the plane isn't too steep plane = AAS_PlaneFromNum(trace.planenum); - if (DotProduct(plane->normal, up) < aassettings.phys_maxsteepness) return qfalse; - //the bot is on the ground + if (DotProduct(plane->normal, up) < aassettings.phys_maxsteepness) + return qfalse; + // the bot is on the ground return qtrue; -} //end of the function AAS_OnGround +} // end of the function AAS_OnGround //=========================================================================== // returns qtrue if a bot at the given position is swimming // @@ -217,49 +217,44 @@ int AAS_OnGround(vec3_t origin, int presencetype, int passent) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Swimming(vec3_t origin) -{ +int AAS_Swimming(vec3_t origin) { vec3_t testorg; VectorCopy(origin, testorg); testorg[2] -= 2; - if (AAS_PointContents(testorg) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) return qtrue; + if (AAS_PointContents(testorg) & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) + return qtrue; return qfalse; -} //end of the function AAS_Swimming +} // end of the function AAS_Swimming //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -static vec3_t VEC_UP = {0, -1, 0}; -static vec3_t MOVEDIR_UP = {0, 0, 1}; -static vec3_t VEC_DOWN = {0, -2, 0}; -static vec3_t MOVEDIR_DOWN = {0, 0, -1}; +static vec3_t VEC_UP = {0, -1, 0}; +static vec3_t MOVEDIR_UP = {0, 0, 1}; +static vec3_t VEC_DOWN = {0, -2, 0}; +static vec3_t MOVEDIR_DOWN = {0, 0, -1}; -void AAS_SetMovedir(vec3_t angles, vec3_t movedir) -{ - if (VectorCompare(angles, VEC_UP)) - { +void AAS_SetMovedir(vec3_t angles, vec3_t movedir) { + if (VectorCompare(angles, VEC_UP)) { VectorCopy(MOVEDIR_UP, movedir); - } //end if - else if (VectorCompare(angles, VEC_DOWN)) - { + } // end if + else if (VectorCompare(angles, VEC_DOWN)) { VectorCopy(MOVEDIR_DOWN, movedir); - } //end else if - else - { + } // end else if + else { AngleVectors(angles, movedir, NULL, NULL); - } //end else -} //end of the function AAS_SetMovedir + } // end else +} // end of the function AAS_SetMovedir //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart) -{ +void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart) { vec3_t hordir, start, cmdmove; aas_clientmove_t move; @@ -268,23 +263,20 @@ void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart) hordir[1] = reach->start[1] - reach->end[1]; hordir[2] = 0; VectorNormalize(hordir); - //start point + // start point VectorCopy(reach->start, start); start[2] += 1; - //get command movement + // get command movement VectorScale(hordir, 400, cmdmove); // - AAS_PredictClientMovement(&move, -1, start, PRESENCE_NORMAL, qtrue, - vec3_origin, cmdmove, 1, 2, 0.1f, - SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA| - SE_HITGROUNDDAMAGE|SE_GAP, 0, qfalse); + AAS_PredictClientMovement(&move, -1, start, PRESENCE_NORMAL, qtrue, vec3_origin, cmdmove, 1, 2, 0.1f, + SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_GAP, 0, qfalse); VectorCopy(move.endpos, runstart); - //don't enter slime or lava and don't fall from too high - if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE)) - { + // don't enter slime or lava and don't fall from too high + if (move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE)) { VectorCopy(start, runstart); - } //end if -} //end of the function AAS_JumpReachRunStart + } // end if +} // end of the function AAS_JumpReachRunStart //=========================================================================== // returns the Z velocity when rocket jumping at the origin // @@ -292,73 +284,71 @@ void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_WeaponJumpZVelocity(vec3_t origin, float radiusdamage) -{ +float AAS_WeaponJumpZVelocity(vec3_t origin, float radiusdamage) { vec3_t kvel, v, start, end, forward, right, viewangles, dir; - float mass, knockback, points; + float mass, knockback, points; vec3_t rocketoffset = {8, 8, -8}; vec3_t botmins = {-16, -16, -24}; vec3_t botmaxs = {16, 16, 32}; bsp_trace_t bsptrace; - //look down (90 degrees) + // look down (90 degrees) viewangles[PITCH] = 90; viewangles[YAW] = 0; viewangles[ROLL] = 0; - //get the start point shooting from + // get the start point shooting from VectorCopy(origin, start); - start[2] += 8; //view offset Z + start[2] += 8; // view offset Z AngleVectors(viewangles, forward, right, NULL); start[0] += forward[0] * rocketoffset[0] + right[0] * rocketoffset[1]; start[1] += forward[1] * rocketoffset[0] + right[1] * rocketoffset[1]; start[2] += forward[2] * rocketoffset[0] + right[2] * rocketoffset[1] + rocketoffset[2]; - //end point of the trace + // end point of the trace VectorMA(start, 500, forward, end); - //trace a line to get the impact point + // trace a line to get the impact point bsptrace = AAS_Trace(start, NULL, NULL, end, 1, CONTENTS_SOLID); - //calculate the damage the bot will get from the rocket impact + // calculate the damage the bot will get from the rocket impact VectorAdd(botmins, botmaxs, v); VectorMA(origin, 0.5, v, v); VectorSubtract(bsptrace.endpos, v, v); // points = radiusdamage - 0.5 * VectorLength(v); - if (points < 0) points = 0; - //the owner of the rocket gets half the damage + if (points < 0) + points = 0; + // the owner of the rocket gets half the damage points *= 0.5; - //mass of the bot (p_client.c: PutClientInServer) + // mass of the bot (p_client.c: PutClientInServer) mass = 200; - //knockback is the same as the damage points + // knockback is the same as the damage points knockback = points; - //direction of the damage (from trace.endpos to bot origin) + // direction of the damage (from trace.endpos to bot origin) VectorSubtract(origin, bsptrace.endpos, dir); VectorNormalize(dir); - //damage velocity - VectorScale(dir, 1600.0 * (float)knockback / mass, kvel); //the rocket jump hack... - //rocket impact velocity + jump velocity + // damage velocity + VectorScale(dir, 1600.0 * (float)knockback / mass, kvel); // the rocket jump hack... + // rocket impact velocity + jump velocity return kvel[2] + aassettings.phys_jumpvel; -} //end of the function AAS_WeaponJumpZVelocity +} // end of the function AAS_WeaponJumpZVelocity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float AAS_RocketJumpZVelocity(vec3_t origin) -{ - //rocket radius damage is 120 (p_weapon.c: Weapon_RocketLauncher_Fire) +float AAS_RocketJumpZVelocity(vec3_t origin) { + // rocket radius damage is 120 (p_weapon.c: Weapon_RocketLauncher_Fire) return AAS_WeaponJumpZVelocity(origin, 120); -} //end of the function AAS_RocketJumpZVelocity +} // end of the function AAS_RocketJumpZVelocity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float AAS_BFGJumpZVelocity(vec3_t origin) -{ - //bfg radius damage is 1000 (p_weapon.c: weapon_bfg_fire) +float AAS_BFGJumpZVelocity(vec3_t origin) { + // bfg radius damage is 1000 (p_weapon.c: weapon_bfg_fire) return AAS_WeaponJumpZVelocity(origin, 120); -} //end of the function AAS_BFGJumpZVelocity +} // end of the function AAS_BFGJumpZVelocity //=========================================================================== // applies ground friction to the given velocity // @@ -366,26 +356,25 @@ float AAS_BFGJumpZVelocity(vec3_t origin) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Accelerate(vec3_t velocity, float frametime, vec3_t wishdir, float wishspeed, float accel) -{ +void AAS_Accelerate(vec3_t velocity, float frametime, vec3_t wishdir, float wishspeed, float accel) { // q2 style - int i; - float addspeed, accelspeed, currentspeed; + int i; + float addspeed, accelspeed, currentspeed; currentspeed = DotProduct(velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0) { return; } - accelspeed = accel*frametime*wishspeed; + accelspeed = accel * frametime * wishspeed; if (accelspeed > addspeed) { accelspeed = addspeed; } - for (i=0 ; i<3 ; i++) { - velocity[i] += accelspeed*wishdir[i]; + for (i = 0; i < 3; i++) { + velocity[i] += accelspeed * wishdir[i]; } -} //end of the function AAS_Accelerate +} // end of the function AAS_Accelerate //=========================================================================== // applies ground friction to the given velocity // @@ -393,31 +382,28 @@ void AAS_Accelerate(vec3_t velocity, float frametime, vec3_t wishdir, float wish // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ApplyFriction(vec3_t vel, float friction, float stopspeed, - float frametime) -{ +void AAS_ApplyFriction(vec3_t vel, float friction, float stopspeed, float frametime) { float speed, control, newspeed; - //horizontal speed + // horizontal speed speed = sqrt(vel[0] * vel[0] + vel[1] * vel[1]); - if (speed) - { + if (speed) { control = speed < stopspeed ? stopspeed : speed; newspeed = speed - frametime * control * friction; - if (newspeed < 0) newspeed = 0; + if (newspeed < 0) + newspeed = 0; newspeed /= speed; vel[0] *= newspeed; vel[1] *= newspeed; - } //end if -} //end of the function AAS_ApplyFriction + } // end if +} // end of the function AAS_ApplyFriction //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetype, vec3_t mins, vec3_t maxs) -{ +int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetype, vec3_t mins, vec3_t maxs) { int i, j, side; float front, back, frac, planedist; vec3_t bboxmins, bboxmaxs, absmins, absmaxs, dir, mid; @@ -428,55 +414,57 @@ int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetyp // VectorCopy(end, trace->endpos); trace->fraction = 1; - for (i = 0; i < 3; i++) - { - if (start[i] < absmins[i] && end[i] < absmins[i]) return qfalse; - if (start[i] > absmaxs[i] && end[i] > absmaxs[i]) return qfalse; - } //end for - //check bounding box collision + for (i = 0; i < 3; i++) { + if (start[i] < absmins[i] && end[i] < absmins[i]) + return qfalse; + if (start[i] > absmaxs[i] && end[i] > absmaxs[i]) + return qfalse; + } // end for + // check bounding box collision VectorSubtract(end, start, dir); frac = 1; - for (i = 0; i < 3; i++) - { - //get plane to test collision with for the current axis direction - if (dir[i] > 0) planedist = absmins[i]; - else planedist = absmaxs[i]; - //calculate collision fraction + for (i = 0; i < 3; i++) { + // get plane to test collision with for the current axis direction + if (dir[i] > 0) + planedist = absmins[i]; + else + planedist = absmaxs[i]; + // calculate collision fraction front = start[i] - planedist; back = end[i] - planedist; - frac = front / (front-back); - //check if between bounding planes of next axis + frac = front / (front - back); + // check if between bounding planes of next axis side = i + 1; - if (side > 2) side = 0; + if (side > 2) + side = 0; mid[side] = start[side] + dir[side] * frac; - if (mid[side] > absmins[side] && mid[side] < absmaxs[side]) - { - //check if between bounding planes of next axis + if (mid[side] > absmins[side] && mid[side] < absmaxs[side]) { + // check if between bounding planes of next axis side++; - if (side > 2) side = 0; + if (side > 2) + side = 0; mid[side] = start[side] + dir[side] * frac; - if (mid[side] > absmins[side] && mid[side] < absmaxs[side]) - { + if (mid[side] > absmins[side] && mid[side] < absmaxs[side]) { mid[i] = planedist; break; - } //end if - } //end if - } //end for - //if there was a collision - if (i != 3) - { + } // end if + } // end if + } // end for + // if there was a collision + if (i != 3) { trace->startsolid = qfalse; trace->fraction = frac; trace->ent = 0; trace->planenum = 0; trace->area = 0; trace->lastarea = 0; - //trace endpos - for (j = 0; j < 3; j++) trace->endpos[j] = start[j] + dir[j] * frac; + // trace endpos + for (j = 0; j < 3; j++) + trace->endpos[j] = start[j] + dir[j] * frac; return qtrue; - } //end if + } // end if return qfalse; -} //end of the function AAS_ClipToBBox +} // end of the function AAS_ClipToBBox //=========================================================================== // predicts the movement // assumes regular bounding box sizes @@ -495,23 +483,16 @@ int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetyp // Returns: aas_clientmove_t // Changes Globals: - //=========================================================================== -int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, - int entnum, vec3_t origin, - int presencetype, int onground, - vec3_t velocity, vec3_t cmdmove, - int cmdframes, - int maxframes, float frametime, - int stopevent, int stopareanum, - vec3_t mins, vec3_t maxs, int visualize) -{ +int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, + int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, vec3_t mins, vec3_t maxs, int visualize) { float phys_friction, phys_stopspeed, phys_gravity, phys_waterfriction; float phys_watergravity; float phys_walkaccelerate, phys_airaccelerate, phys_swimaccelerate; float phys_maxwalkvelocity, phys_maxcrouchvelocity, phys_maxswimvelocity; float phys_maxstep, phys_maxsteepness, phys_jumpvel, friction; float gravity, delta, maxvel, wishspeed, accelerate; - //float velchange, newvel; - //int ax; + // float velchange, newvel; + // int ax; int n, i, j, pc, step, swimming, crouch, event, jump_frame, areanum; int areas[20], numareas; vec3_t points[20]; @@ -521,16 +502,17 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, aas_plane_t *plane, *plane2; aas_trace_t trace, steptrace; - if (frametime <= 0) frametime = 0.1f; + if (frametime <= 0) + frametime = 0.1f; // phys_friction = aassettings.phys_friction; phys_stopspeed = aassettings.phys_stopspeed; phys_gravity = aassettings.phys_gravity; phys_waterfriction = aassettings.phys_waterfriction; phys_watergravity = aassettings.phys_watergravity; - phys_maxwalkvelocity = aassettings.phys_maxwalkvelocity;// * frametime; - phys_maxcrouchvelocity = aassettings.phys_maxcrouchvelocity;// * frametime; - phys_maxswimvelocity = aassettings.phys_maxswimvelocity;// * frametime; + phys_maxwalkvelocity = aassettings.phys_maxwalkvelocity; // * frametime; + phys_maxcrouchvelocity = aassettings.phys_maxcrouchvelocity; // * frametime; + phys_maxswimvelocity = aassettings.phys_maxswimvelocity; // * frametime; phys_walkaccelerate = aassettings.phys_walkaccelerate; phys_airaccelerate = aassettings.phys_airaccelerate; phys_swimaccelerate = aassettings.phys_swimaccelerate; @@ -540,74 +522,66 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, // Com_Memset(move, 0, sizeof(aas_clientmove_t)); Com_Memset(&trace, 0, sizeof(aas_trace_t)); - //start at the current origin + // start at the current origin VectorCopy(origin, org); org[2] += 0.25; - //velocity to test for the first frame + // velocity to test for the first frame VectorScale(velocity, frametime, frame_test_vel); // jump_frame = -1; - //predict a maximum of 'maxframes' ahead - for (n = 0; n < maxframes; n++) - { + // predict a maximum of 'maxframes' ahead + for (n = 0; n < maxframes; n++) { swimming = AAS_Swimming(org); - //get gravity depending on swimming or not + // get gravity depending on swimming or not gravity = swimming ? phys_watergravity : phys_gravity; - //apply gravity at the START of the frame + // apply gravity at the START of the frame frame_test_vel[2] = frame_test_vel[2] - (gravity * 0.1 * frametime); - //if on the ground or swimming - if (onground || swimming) - { + // if on the ground or swimming + if (onground || swimming) { friction = swimming ? phys_friction : phys_waterfriction; - //apply friction - VectorScale(frame_test_vel, 1/frametime, frame_test_vel); + // apply friction + VectorScale(frame_test_vel, 1 / frametime, frame_test_vel); AAS_ApplyFriction(frame_test_vel, friction, phys_stopspeed, frametime); VectorScale(frame_test_vel, frametime, frame_test_vel); - } //end if + } // end if crouch = qfalse; - //apply command movement - if (n < cmdframes) - { - //ax = 0; + // apply command movement + if (n < cmdframes) { + // ax = 0; maxvel = phys_maxwalkvelocity; accelerate = phys_airaccelerate; VectorCopy(cmdmove, wishdir); - if (onground) - { - if (cmdmove[2] < -300) - { + if (onground) { + if (cmdmove[2] < -300) { crouch = qtrue; maxvel = phys_maxcrouchvelocity; - } //end if - //if not swimming and upmove is positive then jump - if (!swimming && cmdmove[2] > 1) - { - //jump velocity minus the gravity for one frame + 5 for safety + } // end if + // if not swimming and upmove is positive then jump + if (!swimming && cmdmove[2] > 1) { + // jump velocity minus the gravity for one frame + 5 for safety frame_test_vel[2] = phys_jumpvel - (gravity * 0.1 * frametime) + 5; jump_frame = n; - //jumping so air accelerate + // jumping so air accelerate accelerate = phys_airaccelerate; - } //end if - else - { + } // end if + else { accelerate = phys_walkaccelerate; - } //end else - //ax = 2; - } //end if - if (swimming) - { + } // end else + // ax = 2; + } // end if + if (swimming) { maxvel = phys_maxswimvelocity; accelerate = phys_swimaccelerate; - //ax = 3; - } //end if - else - { + // ax = 3; + } // end if + else { wishdir[2] = 0; - } //end else + } // end else // wishspeed = VectorNormalize(wishdir); - if (wishspeed > maxvel) wishspeed = maxvel; - VectorScale(frame_test_vel, 1/frametime, frame_test_vel); + if (wishspeed > maxvel) + wishspeed = maxvel; + VectorScale(frame_test_vel, 1 / frametime, frame_test_vel); AAS_Accelerate(frame_test_vel, frametime, wishdir, wishspeed, accelerate); VectorScale(frame_test_vel, frametime, frame_test_vel); /* @@ -623,48 +597,40 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, else frame_test_vel[i] = newvel; } //end for */ - } //end if - if (crouch) - { + } // end if + if (crouch) { presencetype = PRESENCE_CROUCH; - } //end if - else if (presencetype == PRESENCE_CROUCH) - { - if (AAS_PointPresenceType(org) & PRESENCE_NORMAL) - { + } // end if + else if (presencetype == PRESENCE_CROUCH) { + if (AAS_PointPresenceType(org) & PRESENCE_NORMAL) { presencetype = PRESENCE_NORMAL; - } //end if - } //end else - //save the current origin + } // end if + } // end else + // save the current origin VectorCopy(org, lastorg); - //move linear during one frame + // move linear during one frame VectorCopy(frame_test_vel, left_test_vel); j = 0; - do - { + do { VectorAdd(org, left_test_vel, end); - //trace a bounding box + // trace a bounding box trace = AAS_TraceClientBBox(org, end, presencetype, entnum); // -//#ifdef AAS_MOVE_DEBUG - if (visualize) - { - if (trace.startsolid) botimport.Print(PRT_MESSAGE, "PredictMovement: start solid\n"); + //#ifdef AAS_MOVE_DEBUG + if (visualize) { + if (trace.startsolid) + botimport.Print(PRT_MESSAGE, "PredictMovement: start solid\n"); AAS_DebugLine(org, trace.endpos, LINECOLOR_RED); - } //end if -//#endif //AAS_MOVE_DEBUG + } // end if + //#endif //AAS_MOVE_DEBUG // - if (stopevent & (SE_ENTERAREA|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER|SE_TOUCHCLUSTERPORTAL)) - { + if (stopevent & (SE_ENTERAREA | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER | SE_TOUCHCLUSTERPORTAL)) { numareas = AAS_TraceAreas(org, trace.endpos, areas, points, 20); - for (i = 0; i < numareas; i++) - { - if (stopevent & SE_ENTERAREA) - { - if (areas[i] == stopareanum) - { + for (i = 0; i < numareas; i++) { + if (stopevent & SE_ENTERAREA) { + if (areas[i] == stopareanum) { VectorCopy(points[i], move->endpos); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->endarea = areas[i]; move->trace = trace; move->stopevent = SE_ENTERAREA; @@ -673,15 +639,13 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - //NOTE: if not the first frame - if ((stopevent & SE_TOUCHJUMPPAD) && n) - { - if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_JUMPPAD) - { + } // end if + } // end if + // NOTE: if not the first frame + if ((stopevent & SE_TOUCHJUMPPAD) && n) { + if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_JUMPPAD) { VectorCopy(points[i], move->endpos); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->endarea = areas[i]; move->trace = trace; move->stopevent = SE_TOUCHJUMPPAD; @@ -690,15 +654,13 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - if (stopevent & SE_TOUCHTELEPORTER) - { - if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_TELEPORTER) - { + } // end if + } // end if + if (stopevent & SE_TOUCHTELEPORTER) { + if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_TELEPORTER) { VectorCopy(points[i], move->endpos); move->endarea = areas[i]; - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_TOUCHTELEPORTER; move->presencetype = presencetype; @@ -706,15 +668,13 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - if (stopevent & SE_TOUCHCLUSTERPORTAL) - { - if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_CLUSTERPORTAL) - { + } // end if + } // end if + if (stopevent & SE_TOUCHCLUSTERPORTAL) { + if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_CLUSTERPORTAL) { VectorCopy(points[i], move->endpos); move->endarea = areas[i]; - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_TOUCHCLUSTERPORTAL; move->presencetype = presencetype; @@ -722,18 +682,16 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - } //end for - } //end if + } // end if + } // end if + } // end for + } // end if // - if (stopevent & SE_HITBOUNDINGBOX) - { - if (AAS_ClipToBBox(&trace, org, trace.endpos, presencetype, mins, maxs)) - { + if (stopevent & SE_HITBOUNDINGBOX) { + if (AAS_ClipToBBox(&trace, org, trace.endpos, presencetype, mins, maxs)) { VectorCopy(trace.endpos, move->endpos); move->endarea = AAS_PointAreaNum(move->endpos); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_HITBOUNDINGBOX; move->presencetype = presencetype; @@ -741,27 +699,23 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - //move the entity to the trace end point + } // end if + } // end if + // move the entity to the trace end point VectorCopy(trace.endpos, org); - //if there was a collision - if (trace.fraction < 1.0) - { - //get the plane the bounding box collided with + // if there was a collision + if (trace.fraction < 1.0) { + // get the plane the bounding box collided with plane = AAS_PlaneFromNum(trace.planenum); // - if (stopevent & SE_HITGROUNDAREA) - { - if (DotProduct(plane->normal, up) > phys_maxsteepness) - { + if (stopevent & SE_HITGROUNDAREA) { + if (DotProduct(plane->normal, up) > phys_maxsteepness) { VectorCopy(org, start); start[2] += 0.5; - if (AAS_PointAreaNum(start) == stopareanum) - { + if (AAS_PointAreaNum(start) == stopareanum) { VectorCopy(start, move->endpos); move->endarea = stopareanum; - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_HITGROUNDAREA; move->presencetype = presencetype; @@ -769,88 +723,73 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - } //end if - //assume there's no step + } // end if + } // end if + } // end if + // assume there's no step step = qfalse; - //if it is a vertical plane and the bot didn't jump recently - if (plane->normal[2] == 0 && (jump_frame < 0 || n - jump_frame > 2)) - { - //check for a step + // if it is a vertical plane and the bot didn't jump recently + if (plane->normal[2] == 0 && (jump_frame < 0 || n - jump_frame > 2)) { + // check for a step VectorMA(org, -0.25, plane->normal, start); VectorCopy(start, stepend); start[2] += phys_maxstep; steptrace = AAS_TraceClientBBox(start, stepend, presencetype, entnum); // - if (!steptrace.startsolid) - { + if (!steptrace.startsolid) { plane2 = AAS_PlaneFromNum(steptrace.planenum); - if (DotProduct(plane2->normal, up) > phys_maxsteepness) - { + if (DotProduct(plane2->normal, up) > phys_maxsteepness) { VectorSubtract(end, steptrace.endpos, left_test_vel); left_test_vel[2] = 0; frame_test_vel[2] = 0; -//#ifdef AAS_MOVE_DEBUG - if (visualize) - { - if (steptrace.endpos[2] - org[2] > 0.125) - { + //#ifdef AAS_MOVE_DEBUG + if (visualize) { + if (steptrace.endpos[2] - org[2] > 0.125) { VectorCopy(org, start); start[2] = steptrace.endpos[2]; AAS_DebugLine(org, start, LINECOLOR_BLUE); - } //end if - } //end if -//#endif //AAS_MOVE_DEBUG + } // end if + } // end if + //#endif //AAS_MOVE_DEBUG org[2] = steptrace.endpos[2]; step = qtrue; - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if // - if (!step) - { - //velocity left to test for this frame is the projection - //of the current test velocity into the hit plane - VectorMA(left_test_vel, -DotProduct(left_test_vel, plane->normal), - plane->normal, left_test_vel); - //store the old velocity for landing check + if (!step) { + // velocity left to test for this frame is the projection + // of the current test velocity into the hit plane + VectorMA(left_test_vel, -DotProduct(left_test_vel, plane->normal), plane->normal, left_test_vel); + // store the old velocity for landing check VectorCopy(frame_test_vel, old_frame_test_vel); - //test velocity for the next frame is the projection - //of the velocity of the current frame into the hit plane - VectorMA(frame_test_vel, -DotProduct(frame_test_vel, plane->normal), - plane->normal, frame_test_vel); - //check for a landing on an almost horizontal floor - if (DotProduct(plane->normal, up) > phys_maxsteepness) - { + // test velocity for the next frame is the projection + // of the velocity of the current frame into the hit plane + VectorMA(frame_test_vel, -DotProduct(frame_test_vel, plane->normal), plane->normal, frame_test_vel); + // check for a landing on an almost horizontal floor + if (DotProduct(plane->normal, up) > phys_maxsteepness) { onground = qtrue; - } //end if - if (stopevent & SE_HITGROUNDDAMAGE) - { + } // end if + if (stopevent & SE_HITGROUNDDAMAGE) { delta = 0; - if (old_frame_test_vel[2] < 0 && - frame_test_vel[2] > old_frame_test_vel[2] && - !onground) - { + if (old_frame_test_vel[2] < 0 && frame_test_vel[2] > old_frame_test_vel[2] && !onground) { delta = old_frame_test_vel[2]; - } //end if - else if (onground) - { + } // end if + else if (onground) { delta = frame_test_vel[2] - old_frame_test_vel[2]; - } //end else - if (delta) - { + } // end else + if (delta) { delta = delta * 10; delta = delta * delta * 0.0001; - if (swimming) delta = 0; + if (swimming) + delta = 0; // never take falling damage if completely underwater /* if (ent->waterlevel == 3) return; if (ent->waterlevel == 2) delta *= 0.25; if (ent->waterlevel == 1) delta *= 0.5; */ - if (delta > 40) - { + if (delta > 40) { VectorCopy(org, move->endpos); move->endarea = AAS_PointAreaNum(org); VectorCopy(frame_test_vel, move->velocity); @@ -861,27 +800,30 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - } //end if - } //end if - } //end if - //extra check to prevent endless loop - if (++j > 20) return qfalse; - //while there is a plane hit - } while(trace.fraction < 1.0); - //if going down - if (frame_test_vel[2] <= 10) - { - //check for a liquid at the feet of the bot + } // end if + } // end if + } // end if + } // end if + } // end if + // extra check to prevent endless loop + if (++j > 20) + return qfalse; + // while there is a plane hit + } while (trace.fraction < 1.0); + // if going down + if (frame_test_vel[2] <= 10) { + // check for a liquid at the feet of the bot VectorCopy(org, feet); feet[2] -= 22; pc = AAS_PointContents(feet); - //get event from pc + // get event from pc event = SE_NONE; - if (pc & CONTENTS_LAVA) event |= SE_ENTERLAVA; - if (pc & CONTENTS_SLIME) event |= SE_ENTERSLIME; - if (pc & CONTENTS_WATER) event |= SE_ENTERWATER; + if (pc & CONTENTS_LAVA) + event |= SE_ENTERLAVA; + if (pc & CONTENTS_SLIME) + event |= SE_ENTERSLIME; + if (pc & CONTENTS_WATER) + event |= SE_ENTERWATER; // areanum = AAS_PointAreaNum(org); if (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA) @@ -890,30 +832,27 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, event |= SE_ENTERSLIME; if (aasworld.areasettings[areanum].contents & AREACONTENTS_WATER) event |= SE_ENTERWATER; - //if in lava or slime - if (event & stopevent) - { + // if in lava or slime + if (event & stopevent) { VectorCopy(org, move->endpos); move->endarea = areanum; - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->stopevent = event & stopevent; move->presencetype = presencetype; move->endcontents = pc; move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if + } // end if + } // end if // onground = AAS_OnGround(org, presencetype, entnum); - //if onground and on the ground for at least one whole frame - if (onground) - { - if (stopevent & SE_HITGROUND) - { + // if onground and on the ground for at least one whole frame + if (onground) { + if (stopevent & SE_HITGROUND) { VectorCopy(org, move->endpos); move->endarea = AAS_PointAreaNum(org); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_HITGROUND; move->presencetype = presencetype; @@ -921,13 +860,12 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - else if (stopevent & SE_LEAVEGROUND) - { + } // end if + } // end if + else if (stopevent & SE_LEAVEGROUND) { VectorCopy(org, move->endpos); move->endarea = AAS_PointAreaNum(org); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_LEAVEGROUND; move->presencetype = presencetype; @@ -935,26 +873,22 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end else if - else if (stopevent & SE_GAP) - { + } // end else if + else if (stopevent & SE_GAP) { aas_trace_t gaptrace; VectorCopy(org, start); VectorCopy(start, end); end[2] -= 48 + aassettings.phys_maxbarrier; gaptrace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - //if solid is found the bot cannot walk any further and will not fall into a gap - if (!gaptrace.startsolid) - { - //if it is a gap (lower than one step height) - if (gaptrace.endpos[2] < org[2] - aassettings.phys_maxstep - 1) - { - if (!(AAS_PointContents(end) & CONTENTS_WATER)) - { + // if solid is found the bot cannot walk any further and will not fall into a gap + if (!gaptrace.startsolid) { + // if it is a gap (lower than one step height) + if (gaptrace.endpos[2] < org[2] - aassettings.phys_maxstep - 1) { + if (!(AAS_PointContents(end) & CONTENTS_WATER)) { VectorCopy(lastorg, move->endpos); move->endarea = AAS_PointAreaNum(lastorg); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->trace = trace; move->stopevent = SE_GAP; move->presencetype = presencetype; @@ -962,15 +896,15 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->time = n * frametime; move->frames = n; return qtrue; - } //end if - } //end if - } //end if - } //end else if - } //end for + } // end if + } // end if + } // end if + } // end else if + } // end for // VectorCopy(org, move->endpos); move->endarea = AAS_PointAreaNum(org); - VectorScale(frame_test_vel, 1/frametime, move->velocity); + VectorScale(frame_test_vel, 1 / frametime, move->velocity); move->stopevent = SE_NONE; move->presencetype = presencetype; move->endcontents = 0; @@ -978,70 +912,52 @@ int AAS_ClientMovementPrediction(struct aas_clientmove_s *move, move->frames = n; // return qtrue; -} //end of the function AAS_ClientMovementPrediction +} // end of the function AAS_ClientMovementPrediction //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PredictClientMovement(struct aas_clientmove_s *move, - int entnum, vec3_t origin, - int presencetype, int onground, - vec3_t velocity, vec3_t cmdmove, - int cmdframes, - int maxframes, float frametime, - int stopevent, int stopareanum, int visualize) -{ +int AAS_PredictClientMovement(struct aas_clientmove_s *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, + int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize) { vec3_t mins, maxs; - return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground, - velocity, cmdmove, cmdframes, maxframes, - frametime, stopevent, stopareanum, - mins, maxs, visualize); -} //end of the function AAS_PredictClientMovement + return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, frametime, stopevent, + stopareanum, mins, maxs, visualize); +} // end of the function AAS_PredictClientMovement //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move, - int entnum, vec3_t origin, - int presencetype, int onground, - vec3_t velocity, vec3_t cmdmove, - int cmdframes, - int maxframes, float frametime, - vec3_t mins, vec3_t maxs, int visualize) -{ - return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground, - velocity, cmdmove, cmdframes, maxframes, - frametime, SE_HITBOUNDINGBOX, 0, +int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, + int cmdframes, int maxframes, float frametime, vec3_t mins, vec3_t maxs, int visualize) { + return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, frametime, SE_HITBOUNDINGBOX, 0, mins, maxs, visualize); -} //end of the function AAS_ClientMovementHitBBox +} // end of the function AAS_ClientMovementHitBBox //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir) -{ +void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir) { vec3_t velocity, cmdmove; aas_clientmove_t move; VectorClear(velocity); - if (!AAS_Swimming(origin)) dir[2] = 0; + if (!AAS_Swimming(origin)) + dir[2] = 0; VectorNormalize(dir); VectorScale(dir, 400, cmdmove); cmdmove[2] = 224; AAS_ClearShownDebugLines(); - AAS_PredictClientMovement(&move, entnum, origin, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 13, 13, 0.1f, SE_HITGROUND, 0, qtrue);//SE_LEAVEGROUND); - if (move.stopevent & SE_LEAVEGROUND) - { + AAS_PredictClientMovement(&move, entnum, origin, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 13, 13, 0.1f, SE_HITGROUND, 0, qtrue); // SE_LEAVEGROUND); + if (move.stopevent & SE_LEAVEGROUND) { botimport.Print(PRT_MESSAGE, "leave ground\n"); - } //end if -} //end of the function TestMovementPrediction + } // end if +} // end of the function TestMovementPrediction //=========================================================================== // calculates the horizontal velocity needed to perform a jump from start // to end @@ -1053,8 +969,7 @@ void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir) // Returns: qfalse if too high or too far from start to end // Changes Globals: - //=========================================================================== -int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity) -{ +int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity) { float phys_gravity, phys_maxvelocity; float maxjump, height2fall, t, top; vec3_t dir; @@ -1062,34 +977,32 @@ int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *v phys_gravity = aassettings.phys_gravity; phys_maxvelocity = aassettings.phys_maxvelocity; - //maximum height a player can jump with the given initial z velocity + // maximum height a player can jump with the given initial z velocity maxjump = 0.5 * phys_gravity * (zvel / phys_gravity) * (zvel / phys_gravity); - //top of the parabolic jump + // top of the parabolic jump top = start[2] + maxjump; - //height the bot will fall from the top + // height the bot will fall from the top height2fall = top - end[2]; - //if the goal is to high to jump to - if (height2fall < 0) - { + // if the goal is to high to jump to + if (height2fall < 0) { *velocity = phys_maxvelocity; return 0; - } //end if - //time a player takes to fall the height + } // end if + // time a player takes to fall the height t = sqrt(height2fall / (0.5 * phys_gravity)); - //direction from start to end + // direction from start to end VectorSubtract(end, start, dir); // - if ( (t + zvel / phys_gravity) == 0.0f ) { + if ((t + zvel / phys_gravity) == 0.0f) { *velocity = phys_maxvelocity; return 0; } - //calculate horizontal speed - *velocity = sqrt(dir[0]*dir[0] + dir[1]*dir[1]) / (t + zvel / phys_gravity); - //the horizontal speed must be lower than the max speed - if (*velocity > phys_maxvelocity) - { + // calculate horizontal speed + *velocity = sqrt(dir[0] * dir[0] + dir[1] * dir[1]) / (t + zvel / phys_gravity); + // the horizontal speed must be lower than the max speed + if (*velocity > phys_maxvelocity) { *velocity = phys_maxvelocity; return 0; - } //end if + } // end if return 1; -} //end of the function AAS_HorizontalVelocityForJump +} // end of the function AAS_HorizontalVelocityForJump diff --git a/codemp/botlib/be_aas_optimize.cpp b/codemp/botlib/be_aas_optimize.cpp index 6a8508bf97..72afc9ed6c 100644 --- a/codemp/botlib/be_aas_optimize.cpp +++ b/codemp/botlib/be_aas_optimize.cpp @@ -48,24 +48,23 @@ along with this program; if not, see . #include "be_interface.h" #include "be_aas_def.h" -typedef struct optimized_s -{ - //vertexes +typedef struct optimized_s { + // vertexes int numvertexes; aas_vertex_t *vertexes; - //edges + // edges int numedges; aas_edge_t *edges; - //edge index + // edge index int edgeindexsize; aas_edgeindex_t *edgeindex; - //faces + // faces int numfaces; aas_face_t *faces; - //face index + // face index int faceindexsize; aas_faceindex_t *faceindex; - //convex areas + // convex areas int numareas; aas_area_t *areas; // @@ -80,119 +79,117 @@ typedef struct optimized_s // Returns: - // Changes Globals: - //=========================================================================== -int AAS_KeepEdge(aas_edge_t *edge) -{ - return 1; -} //end of the function AAS_KeepFace +int AAS_KeepEdge(aas_edge_t *edge) { return 1; } // end of the function AAS_KeepFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_OptimizeEdge(optimized_t *optimized, int edgenum) -{ +int AAS_OptimizeEdge(optimized_t *optimized, int edgenum) { int i, optedgenum; aas_edge_t *edge, *optedge; edge = &aasworld.edges[abs(edgenum)]; - if (!AAS_KeepEdge(edge)) return 0; + if (!AAS_KeepEdge(edge)) + return 0; optedgenum = optimized->edgeoptimizeindex[abs(edgenum)]; - if (optedgenum) - { - //keep the edge reversed sign - if (edgenum > 0) return optedgenum; - else return -optedgenum; - } //end if + if (optedgenum) { + // keep the edge reversed sign + if (edgenum > 0) + return optedgenum; + else + return -optedgenum; + } // end if optedge = &optimized->edges[optimized->numedges]; - for (i = 0; i < 2; i++) - { - if (optimized->vertexoptimizeindex[edge->v[i]]) - { + for (i = 0; i < 2; i++) { + if (optimized->vertexoptimizeindex[edge->v[i]]) { optedge->v[i] = optimized->vertexoptimizeindex[edge->v[i]]; - } //end if - else - { + } // end if + else { VectorCopy(aasworld.vertexes[edge->v[i]], optimized->vertexes[optimized->numvertexes]); optedge->v[i] = optimized->numvertexes; optimized->vertexoptimizeindex[edge->v[i]] = optimized->numvertexes; optimized->numvertexes++; - } //end else - } //end for + } // end else + } // end for optimized->edgeoptimizeindex[abs(edgenum)] = optimized->numedges; optedgenum = optimized->numedges; optimized->numedges++; - //keep the edge reversed sign - if (edgenum > 0) return optedgenum; - else return -optedgenum; -} //end of the function AAS_OptimizeEdge + // keep the edge reversed sign + if (edgenum > 0) + return optedgenum; + else + return -optedgenum; +} // end of the function AAS_OptimizeEdge //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_KeepFace(aas_face_t *face) -{ - if (!(face->faceflags & FACE_LADDER)) return 0; - else return 1; -} //end of the function AAS_KeepFace +int AAS_KeepFace(aas_face_t *face) { + if (!(face->faceflags & FACE_LADDER)) + return 0; + else + return 1; +} // end of the function AAS_KeepFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_OptimizeFace(optimized_t *optimized, int facenum) -{ +int AAS_OptimizeFace(optimized_t *optimized, int facenum) { int i, edgenum, optedgenum, optfacenum; aas_face_t *face, *optface; face = &aasworld.faces[abs(facenum)]; - if (!AAS_KeepFace(face)) return 0; + if (!AAS_KeepFace(face)) + return 0; optfacenum = optimized->faceoptimizeindex[abs(facenum)]; - if (optfacenum) - { - //keep the face side sign - if (facenum > 0) return optfacenum; - else return -optfacenum; - } //end if + if (optfacenum) { + // keep the face side sign + if (facenum > 0) + return optfacenum; + else + return -optfacenum; + } // end if optface = &optimized->faces[optimized->numfaces]; Com_Memcpy(optface, face, sizeof(aas_face_t)); optface->numedges = 0; optface->firstedge = optimized->edgeindexsize; - for (i = 0; i < face->numedges; i++) - { + for (i = 0; i < face->numedges; i++) { edgenum = aasworld.edgeindex[face->firstedge + i]; optedgenum = AAS_OptimizeEdge(optimized, edgenum); - if (optedgenum) - { + if (optedgenum) { optimized->edgeindex[optface->firstedge + optface->numedges] = optedgenum; optface->numedges++; optimized->edgeindexsize++; - } //end if - } //end for + } // end if + } // end for optimized->faceoptimizeindex[abs(facenum)] = optimized->numfaces; optfacenum = optimized->numfaces; optimized->numfaces++; - //keep the face side sign - if (facenum > 0) return optfacenum; - else return -optfacenum; -} //end of the function AAS_OptimizeFace + // keep the face side sign + if (facenum > 0) + return optfacenum; + else + return -optfacenum; +} // end of the function AAS_OptimizeFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_OptimizeArea(optimized_t *optimized, int areanum) -{ +void AAS_OptimizeArea(optimized_t *optimized, int areanum) { int i, facenum, optfacenum; aas_area_t *area, *optarea; @@ -202,116 +199,120 @@ void AAS_OptimizeArea(optimized_t *optimized, int areanum) optarea->numfaces = 0; optarea->firstface = optimized->faceindexsize; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = aasworld.faceindex[area->firstface + i]; optfacenum = AAS_OptimizeFace(optimized, facenum); - if (optfacenum) - { + if (optfacenum) { optimized->faceindex[optarea->firstface + optarea->numfaces] = optfacenum; optarea->numfaces++; optimized->faceindexsize++; - } //end if - } //end for -} //end of the function AAS_OptimizeArea + } // end if + } // end for +} // end of the function AAS_OptimizeArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_OptimizeAlloc(optimized_t *optimized) -{ - optimized->vertexes = (aas_vertex_t *) GetClearedMemory(aasworld.numvertexes * sizeof(aas_vertex_t)); +void AAS_OptimizeAlloc(optimized_t *optimized) { + optimized->vertexes = (aas_vertex_t *)GetClearedMemory(aasworld.numvertexes * sizeof(aas_vertex_t)); optimized->numvertexes = 0; - optimized->edges = (aas_edge_t *) GetClearedMemory(aasworld.numedges * sizeof(aas_edge_t)); - optimized->numedges = 1; //edge zero is a dummy - optimized->edgeindex = (aas_edgeindex_t *) GetClearedMemory(aasworld.edgeindexsize * sizeof(aas_edgeindex_t)); + optimized->edges = (aas_edge_t *)GetClearedMemory(aasworld.numedges * sizeof(aas_edge_t)); + optimized->numedges = 1; // edge zero is a dummy + optimized->edgeindex = (aas_edgeindex_t *)GetClearedMemory(aasworld.edgeindexsize * sizeof(aas_edgeindex_t)); optimized->edgeindexsize = 0; - optimized->faces = (aas_face_t *) GetClearedMemory(aasworld.numfaces * sizeof(aas_face_t)); - optimized->numfaces = 1; //face zero is a dummy - optimized->faceindex = (aas_faceindex_t *) GetClearedMemory(aasworld.faceindexsize * sizeof(aas_faceindex_t)); + optimized->faces = (aas_face_t *)GetClearedMemory(aasworld.numfaces * sizeof(aas_face_t)); + optimized->numfaces = 1; // face zero is a dummy + optimized->faceindex = (aas_faceindex_t *)GetClearedMemory(aasworld.faceindexsize * sizeof(aas_faceindex_t)); optimized->faceindexsize = 0; - optimized->areas = (aas_area_t *) GetClearedMemory(aasworld.numareas * sizeof(aas_area_t)); + optimized->areas = (aas_area_t *)GetClearedMemory(aasworld.numareas * sizeof(aas_area_t)); optimized->numareas = aasworld.numareas; // - optimized->vertexoptimizeindex = (int *) GetClearedMemory(aasworld.numvertexes * sizeof(int)); - optimized->edgeoptimizeindex = (int *) GetClearedMemory(aasworld.numedges * sizeof(int)); - optimized->faceoptimizeindex = (int *) GetClearedMemory(aasworld.numfaces * sizeof(int)); -} //end of the function AAS_OptimizeAlloc + optimized->vertexoptimizeindex = (int *)GetClearedMemory(aasworld.numvertexes * sizeof(int)); + optimized->edgeoptimizeindex = (int *)GetClearedMemory(aasworld.numedges * sizeof(int)); + optimized->faceoptimizeindex = (int *)GetClearedMemory(aasworld.numfaces * sizeof(int)); +} // end of the function AAS_OptimizeAlloc //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_OptimizeStore(optimized_t *optimized) -{ - //store the optimized vertexes - if (aasworld.vertexes) FreeMemory(aasworld.vertexes); +void AAS_OptimizeStore(optimized_t *optimized) { + // store the optimized vertexes + if (aasworld.vertexes) + FreeMemory(aasworld.vertexes); aasworld.vertexes = optimized->vertexes; aasworld.numvertexes = optimized->numvertexes; - //store the optimized edges - if (aasworld.edges) FreeMemory(aasworld.edges); + // store the optimized edges + if (aasworld.edges) + FreeMemory(aasworld.edges); aasworld.edges = optimized->edges; aasworld.numedges = optimized->numedges; - //store the optimized edge index - if (aasworld.edgeindex) FreeMemory(aasworld.edgeindex); + // store the optimized edge index + if (aasworld.edgeindex) + FreeMemory(aasworld.edgeindex); aasworld.edgeindex = optimized->edgeindex; aasworld.edgeindexsize = optimized->edgeindexsize; - //store the optimized faces - if (aasworld.faces) FreeMemory(aasworld.faces); + // store the optimized faces + if (aasworld.faces) + FreeMemory(aasworld.faces); aasworld.faces = optimized->faces; aasworld.numfaces = optimized->numfaces; - //store the optimized face index - if (aasworld.faceindex) FreeMemory(aasworld.faceindex); + // store the optimized face index + if (aasworld.faceindex) + FreeMemory(aasworld.faceindex); aasworld.faceindex = optimized->faceindex; aasworld.faceindexsize = optimized->faceindexsize; - //store the optimized areas - if (aasworld.areas) FreeMemory(aasworld.areas); + // store the optimized areas + if (aasworld.areas) + FreeMemory(aasworld.areas); aasworld.areas = optimized->areas; aasworld.numareas = optimized->numareas; - //free optimize indexes + // free optimize indexes FreeMemory(optimized->vertexoptimizeindex); FreeMemory(optimized->edgeoptimizeindex); FreeMemory(optimized->faceoptimizeindex); -} //end of the function AAS_OptimizeStore +} // end of the function AAS_OptimizeStore //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Optimize(void) -{ +void AAS_Optimize(void) { int i, sign; optimized_t optimized; AAS_OptimizeAlloc(&optimized); - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { AAS_OptimizeArea(&optimized, i); - } //end for - //reset the reachability face pointers - for (i = 0; i < aasworld.reachabilitysize; i++) - { - //NOTE: for TRAVEL_ELEVATOR the facenum is the model number of + } // end for + // reset the reachability face pointers + for (i = 0; i < aasworld.reachabilitysize; i++) { + // NOTE: for TRAVEL_ELEVATOR the facenum is the model number of // the elevator - if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) continue; - //NOTE: for TRAVEL_JUMPPAD the facenum is the Z velocity and the edgenum is the hor velocity - if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) continue; - //NOTE: for TRAVEL_FUNCBOB the facenum and edgenum contain other coded information - if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) continue; + if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) + continue; + // NOTE: for TRAVEL_JUMPPAD the facenum is the Z velocity and the edgenum is the hor velocity + if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) + continue; + // NOTE: for TRAVEL_FUNCBOB the facenum and edgenum contain other coded information + if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) + continue; // sign = aasworld.reachability[i].facenum; aasworld.reachability[i].facenum = optimized.faceoptimizeindex[abs(aasworld.reachability[i].facenum)]; - if (sign < 0) aasworld.reachability[i].facenum = -aasworld.reachability[i].facenum; + if (sign < 0) + aasworld.reachability[i].facenum = -aasworld.reachability[i].facenum; sign = aasworld.reachability[i].edgenum; aasworld.reachability[i].edgenum = optimized.edgeoptimizeindex[abs(aasworld.reachability[i].edgenum)]; - if (sign < 0) aasworld.reachability[i].edgenum = -aasworld.reachability[i].edgenum; - } //end for - //store the optimized AAS data into aasworld + if (sign < 0) + aasworld.reachability[i].edgenum = -aasworld.reachability[i].edgenum; + } // end for + // store the optimized AAS data into aasworld AAS_OptimizeStore(&optimized); - //print some nice stuff :) + // print some nice stuff :) botimport.Print(PRT_MESSAGE, "AAS data optimized.\n"); -} //end of the function AAS_Optimize +} // end of the function AAS_Optimize diff --git a/codemp/botlib/be_aas_reach.cpp b/codemp/botlib/be_aas_reach.cpp index 4c393b1813..abc7ea044c 100644 --- a/codemp/botlib/be_aas_reach.cpp +++ b/codemp/botlib/be_aas_reach.cpp @@ -49,62 +49,60 @@ along with this program; if not, see . extern int Sys_MilliSeconds(void); - extern botlib_import_t botimport; //#define REACH_DEBUG -//NOTE: all travel times are in hundreth of a second -//maximum number of reachability links -#define AAS_MAX_REACHABILITYSIZE 65536 -//number of areas reachability is calculated for each frame -#define REACHABILITYAREASPERCYCLE 15 -//number of units reachability points are placed inside the areas -#define INSIDEUNITS 2 -#define INSIDEUNITS_WALKEND 5 -#define INSIDEUNITS_WALKSTART 0.1 -#define INSIDEUNITS_WATERJUMP 15 -//area flag used for weapon jumping -#define AREA_WEAPONJUMP 8192 //valid area to weapon jump to -//number of reachabilities of each type -int reach_swim; //swim -int reach_equalfloor; //walk on floors with equal height -int reach_step; //step up -int reach_walk; //walk of step -int reach_barrier; //jump up to a barrier -int reach_waterjump; //jump out of water -int reach_walkoffledge; //walk of a ledge -int reach_jump; //jump -int reach_ladder; //climb or descent a ladder -int reach_teleport; //teleport -int reach_elevator; //use an elevator -int reach_funcbob; //use a func bob -int reach_grapple; //grapple hook -int reach_doublejump; //double jump -int reach_rampjump; //ramp jump -int reach_strafejump; //strafe jump (just normal jump but further) -int reach_rocketjump; //rocket jump -int reach_bfgjump; //bfg jump -int reach_jumppad; //jump pads -//if true grapple reachabilities are skipped +// NOTE: all travel times are in hundreth of a second +// maximum number of reachability links +#define AAS_MAX_REACHABILITYSIZE 65536 +// number of areas reachability is calculated for each frame +#define REACHABILITYAREASPERCYCLE 15 +// number of units reachability points are placed inside the areas +#define INSIDEUNITS 2 +#define INSIDEUNITS_WALKEND 5 +#define INSIDEUNITS_WALKSTART 0.1 +#define INSIDEUNITS_WATERJUMP 15 +// area flag used for weapon jumping +#define AREA_WEAPONJUMP 8192 // valid area to weapon jump to +// number of reachabilities of each type +int reach_swim; // swim +int reach_equalfloor; // walk on floors with equal height +int reach_step; // step up +int reach_walk; // walk of step +int reach_barrier; // jump up to a barrier +int reach_waterjump; // jump out of water +int reach_walkoffledge; // walk of a ledge +int reach_jump; // jump +int reach_ladder; // climb or descent a ladder +int reach_teleport; // teleport +int reach_elevator; // use an elevator +int reach_funcbob; // use a func bob +int reach_grapple; // grapple hook +int reach_doublejump; // double jump +int reach_rampjump; // ramp jump +int reach_strafejump; // strafe jump (just normal jump but further) +int reach_rocketjump; // rocket jump +int reach_bfgjump; // bfg jump +int reach_jumppad; // jump pads +// if true grapple reachabilities are skipped int calcgrapplereach; -//linked reachability -typedef struct aas_lreachability_s -{ - int areanum; //number of the reachable area - int facenum; //number of the face towards the other area - int edgenum; //number of the edge towards the other area - vec3_t start; //start point of inter area movement - vec3_t end; //end point of inter area movement - int traveltype; //type of travel required to get to the area - unsigned short int traveltime; //travel time of the inter area movement +// linked reachability +typedef struct aas_lreachability_s { + int areanum; // number of the reachable area + int facenum; // number of the face towards the other area + int edgenum; // number of the edge towards the other area + vec3_t start; // start point of inter area movement + vec3_t end; // end point of inter area movement + int traveltype; // type of travel required to get to the area + unsigned short int traveltime; // travel time of the inter area movement // struct aas_lreachability_s *next; } aas_lreachability_t; -//temporary reachabilities -aas_lreachability_t *reachabilityheap; //heap with reachabilities -aas_lreachability_t *nextreachability; //next free reachability from the heap -aas_lreachability_t **areareachability; //reachability links for every area +// temporary reachabilities +aas_lreachability_t *reachabilityheap; // heap with reachabilities +aas_lreachability_t *nextreachability; // next free reachability from the heap +aas_lreachability_t **areareachability; // reachability links for every area int numlreachabilities; //=========================================================================== @@ -114,8 +112,7 @@ int numlreachabilities; // Returns: - // Changes Globals: - //=========================================================================== -float AAS_FaceArea(aas_face_t *face) -{ +float AAS_FaceArea(aas_face_t *face) { int i, edgenum, side; float total; float *v; @@ -128,8 +125,7 @@ float AAS_FaceArea(aas_face_t *face) v = aasworld.vertexes[edge->v[side]]; total = 0; - for (i = 1; i < face->numedges - 1; i++) - { + for (i = 1; i < face->numedges - 1; i++) { edgenum = aasworld.edgeindex[face->firstedge + i]; side = edgenum < 0; edge = &aasworld.edges[abs(edgenum)]; @@ -137,9 +133,9 @@ float AAS_FaceArea(aas_face_t *face) VectorSubtract(aasworld.vertexes[edge->v[!side]], v, d2); CrossProduct(d1, d2, cross); total += 0.5 * VectorLength(cross); - } //end for + } // end for return total; -} //end of the function AAS_FaceArea +} // end of the function AAS_FaceArea //=========================================================================== // returns the volume of an area // @@ -147,8 +143,7 @@ float AAS_FaceArea(aas_face_t *face) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_AreaVolume(int areanum) -{ +float AAS_AreaVolume(int areanum) { int i, edgenum, facenum, side; float d, a, volume; vec3_t corner; @@ -165,58 +160,53 @@ float AAS_AreaVolume(int areanum) // VectorCopy(aasworld.vertexes[edge->v[0]], corner); - //make tetrahedrons to all other faces + // make tetrahedrons to all other faces volume = 0; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = abs(aasworld.faceindex[area->firstface + i]); face = &aasworld.faces[facenum]; side = face->backarea != areanum; plane = &aasworld.planes[face->planenum ^ side]; - d = -(DotProduct (corner, plane->normal) - plane->dist); + d = -(DotProduct(corner, plane->normal) - plane->dist); a = AAS_FaceArea(face); volume += d * a; - } //end for + } // end for volume /= 3; return volume; -} //end of the function AAS_AreaVolume +} // end of the function AAS_AreaVolume //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BestReachableLinkArea(aas_link_t *areas) -{ +int AAS_BestReachableLinkArea(aas_link_t *areas) { aas_link_t *link; - for (link = areas; link; link = link->next_area) - { - if (AAS_AreaGrounded(link->areanum) || AAS_AreaSwim(link->areanum)) - { + for (link = areas; link; link = link->next_area) { + if (AAS_AreaGrounded(link->areanum) || AAS_AreaSwim(link->areanum)) { return link->areanum; - } //end if - } //end for + } // end if + } // end for // - for (link = areas; link; link = link->next_area) - { - if (link->areanum) return link->areanum; - //FIXME: this is a bad idea when the reachability is not yet - // calculated when the level items are loaded + for (link = areas; link; link = link->next_area) { + if (link->areanum) + return link->areanum; + // FIXME: this is a bad idea when the reachability is not yet + // calculated when the level items are loaded if (AAS_AreaReachability(link->areanum)) return link->areanum; - } //end for + } // end for return 0; -} //end of the function AAS_BestReachableLinkArea +} // end of the function AAS_BestReachableLinkArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_GetJumpPadInfo(int ent, vec3_t areastart, vec3_t absmins, vec3_t absmaxs, vec3_t velocity) -{ +int AAS_GetJumpPadInfo(int ent, vec3_t areastart, vec3_t absmins, vec3_t absmaxs, vec3_t velocity) { int modelnum, ent2; float speed, height, gravity, time, dist, forward; vec3_t origin, angles, teststart, ent2origin; @@ -226,74 +216,73 @@ int AAS_GetJumpPadInfo(int ent, vec3_t areastart, vec3_t absmins, vec3_t absmaxs // AAS_FloatForBSPEpairKey(ent, "speed", &speed); - if (!speed) speed = 1000; + if (!speed) + speed = 1000; VectorClear(angles); - //get the mins, maxs and origin of the model + // get the mins, maxs and origin of the model AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY); - if (model[0]) modelnum = atoi(model+1); - else modelnum = 0; + if (model[0]) + modelnum = atoi(model + 1); + else + modelnum = 0; AAS_BSPModelMinsMaxsOrigin(modelnum, angles, absmins, absmaxs, origin); VectorAdd(origin, absmins, absmins); VectorAdd(origin, absmaxs, absmaxs); VectorAdd(absmins, absmaxs, origin); - VectorScale (origin, 0.5, origin); + VectorScale(origin, 0.5, origin); - //get the start areas + // get the start areas VectorCopy(origin, teststart); teststart[2] += 64; trace = AAS_TraceClientBBox(teststart, origin, PRESENCE_CROUCH, -1); - if (trace.startsolid) - { + if (trace.startsolid) { botimport.Print(PRT_MESSAGE, "trigger_push start solid\n"); VectorCopy(origin, areastart); - } //end if - else - { + } // end if + else { VectorCopy(trace.endpos, areastart); - } //end else + } // end else areastart[2] += 0.125; // - //AAS_DrawPermanentCross(origin, 4, 4); - //get the target entity + // AAS_DrawPermanentCross(origin, 4, 4); + // get the target entity AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY); - for (ent2 = AAS_NextBSPEntity(0); ent2; ent2 = AAS_NextBSPEntity(ent2)) - { - if (!AAS_ValueForBSPEpairKey(ent2, "targetname", targetname, MAX_EPAIRKEY)) continue; - if (!strcmp(targetname, target)) break; - } //end for - if (!ent2) - { + for (ent2 = AAS_NextBSPEntity(0); ent2; ent2 = AAS_NextBSPEntity(ent2)) { + if (!AAS_ValueForBSPEpairKey(ent2, "targetname", targetname, MAX_EPAIRKEY)) + continue; + if (!strcmp(targetname, target)) + break; + } // end for + if (!ent2) { botimport.Print(PRT_MESSAGE, "trigger_push without target entity %s\n", target); return qfalse; - } //end if + } // end if AAS_VectorForBSPEpairKey(ent2, "origin", ent2origin); // height = ent2origin[2] - origin[2]; gravity = aassettings.phys_gravity; - time = sqrt( height / ( 0.5 * gravity ) ); - if (!time) - { + time = sqrt(height / (0.5 * gravity)); + if (!time) { botimport.Print(PRT_MESSAGE, "trigger_push without time\n"); return qfalse; - } //end if + } // end if // set s.origin2 to the push velocity - VectorSubtract ( ent2origin, origin, velocity); - dist = VectorNormalize( velocity); + VectorSubtract(ent2origin, origin, velocity); + dist = VectorNormalize(velocity); forward = dist / time; - //FIXME: why multiply by 1.1 + // FIXME: why multiply by 1.1 forward *= 1.1f; VectorScale(velocity, forward, velocity); velocity[2] = time * gravity; return qtrue; -} //end of the function AAS_GetJumpPadInfo +} // end of the function AAS_GetJumpPadInfo //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs) -{ +int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs) { int ent, bot_visualizejumppads, bestareanum; float volume, bestareavolume; vec3_t areastart, cmdmove, bboxmins, bboxmaxs; @@ -309,116 +298,106 @@ int AAS_BestReachableFromJumpPadArea(vec3_t origin, vec3_t mins, vec3_t maxs) #endif VectorAdd(origin, mins, bboxmins); VectorAdd(origin, maxs, bboxmaxs); - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (strcmp(classname, "trigger_push")) continue; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (strcmp(classname, "trigger_push")) + continue; // - if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) continue; - //get the areas the jump pad brush is in + if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) + continue; + // get the areas the jump pad brush is in areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH); - for (link = areas; link; link = link->next_area) - { - if (AAS_AreaJumpPad(link->areanum)) break; - } //end for - if (!link) - { + for (link = areas; link; link = link->next_area) { + if (AAS_AreaJumpPad(link->areanum)) + break; + } // end for + if (!link) { botimport.Print(PRT_MESSAGE, "trigger_push not in any jump pad area\n"); AAS_UnlinkFromAreas(areas); continue; - } //end if + } // end if // - //botimport.Print(PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2]); + // botimport.Print(PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2]); // VectorSet(cmdmove, 0, 0, 0); Com_Memset(&move, 0, sizeof(aas_clientmove_t)); - AAS_ClientMovementHitBBox(&move, -1, areastart, PRESENCE_NORMAL, qfalse, - velocity, cmdmove, 0, 30, 0.1f, bboxmins, bboxmaxs, bot_visualizejumppads); - if (move.frames < 30) - { + AAS_ClientMovementHitBBox(&move, -1, areastart, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 0, 30, 0.1f, bboxmins, bboxmaxs, bot_visualizejumppads); + if (move.frames < 30) { bestareanum = 0; bestareavolume = 0; - for (link = areas; link; link = link->next_area) - { - if (!AAS_AreaJumpPad(link->areanum)) continue; + for (link = areas; link; link = link->next_area) { + if (!AAS_AreaJumpPad(link->areanum)) + continue; volume = AAS_AreaVolume(link->areanum); - if (volume >= bestareavolume) - { + if (volume >= bestareavolume) { bestareanum = link->areanum; bestareavolume = volume; - } //end if - } //end if + } // end if + } // end if AAS_UnlinkFromAreas(areas); return bestareanum; - } //end if + } // end if AAS_UnlinkFromAreas(areas); - } //end for + } // end for return 0; -} //end of the function AAS_BestReachableFromJumpPadArea +} // end of the function AAS_BestReachableFromJumpPadArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin) -{ +int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin) { int areanum, i, j, k, l; aas_link_t *areas; vec3_t absmins, absmaxs; - //vec3_t bbmins, bbmaxs; + // vec3_t bbmins, bbmaxs; vec3_t start, end; aas_trace_t trace; - if (!aasworld.loaded) - { + if (!aasworld.loaded) { botimport.Print(PRT_ERROR, "AAS_BestReachableArea: aas not loaded\n"); return 0; - } //end if - //find a point in an area + } // end if + // find a point in an area VectorCopy(origin, start); areanum = AAS_PointAreaNum(start); - //while no area found fudge around a little - for (i = 0; i < 5 && !areanum; i++) - { - for (j = 0; j < 5 && !areanum; j++) - { - for (k = -1; k <= 1 && !areanum; k++) - { - for (l = -1; l <= 1 && !areanum; l++) - { + // while no area found fudge around a little + for (i = 0; i < 5 && !areanum; i++) { + for (j = 0; j < 5 && !areanum; j++) { + for (k = -1; k <= 1 && !areanum; k++) { + for (l = -1; l <= 1 && !areanum; l++) { VectorCopy(origin, start); - start[0] += (float) j * 4 * k; - start[1] += (float) j * 4 * l; - start[2] += (float) i * 4; + start[0] += (float)j * 4 * k; + start[1] += (float)j * 4 * l; + start[2] += (float)i * 4; areanum = AAS_PointAreaNum(start); - } //end for - } //end for - } //end for - } //end for - //if an area was found - if (areanum) - { - //drop client bbox down and try again + } // end for + } // end for + } // end for + } // end for + // if an area was found + if (areanum) { + // drop client bbox down and try again VectorCopy(start, end); start[2] += 0.25; end[2] -= 50; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - if (!trace.startsolid) - { + if (!trace.startsolid) { areanum = AAS_PointAreaNum(trace.endpos); VectorCopy(trace.endpos, goalorigin); - //FIXME: cannot enable next line right now because the reachability - // does not have to be calculated when the level items are loaded - //if the origin is in an area with reachability - //if (AAS_AreaReachability(areanum)) return areanum; - if (areanum) return areanum; - } //end if - else - { - //it can very well happen that the AAS_PointAreaNum function tells that - //a point is in an area and that starting an AAS_TraceClientBBox from that - //point will return trace.startsolid qtrue + // FIXME: cannot enable next line right now because the reachability + // does not have to be calculated when the level items are loaded + // if the origin is in an area with reachability + // if (AAS_AreaReachability(areanum)) return areanum; + if (areanum) + return areanum; + } // end if + else { + // it can very well happen that the AAS_PointAreaNum function tells that + // a point is in an area and that starting an AAS_TraceClientBBox from that + // point will return trace.startsolid qtrue #if 0 if (AAS_PointAreaNum(start)) { @@ -429,59 +408,55 @@ int AAS_BestReachableArea(vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalor #endif VectorCopy(start, goalorigin); return areanum; - } //end else - } //end if + } // end else + } // end if // - //AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bbmins, bbmaxs); - //NOTE: the goal origin does not have to be in the goal area + // AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bbmins, bbmaxs); + // NOTE: the goal origin does not have to be in the goal area // because the bot will have to move towards the item origin anyway VectorCopy(origin, goalorigin); // VectorAdd(origin, mins, absmins); VectorAdd(origin, maxs, absmaxs); - //add bounding box size - //VectorSubtract(absmins, bbmaxs, absmins); - //VectorSubtract(absmaxs, bbmins, absmaxs); - //link an invalid (-1) entity + // add bounding box size + // VectorSubtract(absmins, bbmaxs, absmins); + // VectorSubtract(absmaxs, bbmins, absmaxs); + // link an invalid (-1) entity areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH); - //get the reachable link arae + // get the reachable link arae areanum = AAS_BestReachableLinkArea(areas); - //unlink the invalid entity + // unlink the invalid entity AAS_UnlinkFromAreas(areas); // return areanum; -} //end of the function AAS_BestReachableArea +} // end of the function AAS_BestReachableArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_SetupReachabilityHeap(void) -{ +void AAS_SetupReachabilityHeap(void) { int i; - reachabilityheap = (aas_lreachability_t *) GetClearedMemory( - AAS_MAX_REACHABILITYSIZE * sizeof(aas_lreachability_t)); - for (i = 0; i < AAS_MAX_REACHABILITYSIZE-1; i++) - { - reachabilityheap[i].next = &reachabilityheap[i+1]; - } //end for - reachabilityheap[AAS_MAX_REACHABILITYSIZE-1].next = NULL; + reachabilityheap = (aas_lreachability_t *)GetClearedMemory(AAS_MAX_REACHABILITYSIZE * sizeof(aas_lreachability_t)); + for (i = 0; i < AAS_MAX_REACHABILITYSIZE - 1; i++) { + reachabilityheap[i].next = &reachabilityheap[i + 1]; + } // end for + reachabilityheap[AAS_MAX_REACHABILITYSIZE - 1].next = NULL; nextreachability = reachabilityheap; numlreachabilities = 0; -} //end of the function AAS_InitReachabilityHeap +} // end of the function AAS_InitReachabilityHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShutDownReachabilityHeap(void) -{ +void AAS_ShutDownReachabilityHeap(void) { FreeMemory(reachabilityheap); numlreachabilities = 0; -} //end of the function AAS_ShutDownReachabilityHeap +} // end of the function AAS_ShutDownReachabilityHeap //=========================================================================== // returns a reachability link // @@ -489,19 +464,20 @@ void AAS_ShutDownReachabilityHeap(void) // Returns: - // Changes Globals: - //=========================================================================== -aas_lreachability_t *AAS_AllocReachability(void) -{ +aas_lreachability_t *AAS_AllocReachability(void) { aas_lreachability_t *r; - if (!nextreachability) return NULL; - //make sure the error message only shows up once - if (!nextreachability->next) AAS_Error("AAS_MAX_REACHABILITYSIZE\n"); + if (!nextreachability) + return NULL; + // make sure the error message only shows up once + if (!nextreachability->next) + AAS_Error("AAS_MAX_REACHABILITYSIZE\n"); // r = nextreachability; nextreachability = nextreachability->next; numlreachabilities++; return r; -} //end of the function AAS_AllocReachability +} // end of the function AAS_AllocReachability //=========================================================================== // frees a reachability link // @@ -509,14 +485,13 @@ aas_lreachability_t *AAS_AllocReachability(void) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeReachability(aas_lreachability_t *lreach) -{ +void AAS_FreeReachability(aas_lreachability_t *lreach) { Com_Memset(lreach, 0, sizeof(aas_lreachability_t)); lreach->next = nextreachability; nextreachability = lreach; numlreachabilities--; -} //end of the function AAS_FreeReachability +} // end of the function AAS_FreeReachability //=========================================================================== // returns qtrue if the area has reachability links // @@ -524,15 +499,13 @@ void AAS_FreeReachability(aas_lreachability_t *lreach) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaReachability(int areanum) -{ - if (areanum < 0 || areanum >= aasworld.numareas) - { +int AAS_AreaReachability(int areanum) { + if (areanum < 0 || areanum >= aasworld.numareas) { AAS_Error("AAS_AreaReachability: areanum %d out of range\n", areanum); return 0; - } //end if + } // end if return aasworld.areasettings[areanum].numreachableareas; -} //end of the function AAS_AreaReachability +} // end of the function AAS_AreaReachability //=========================================================================== // returns the surface area of all ground faces together of the area // @@ -540,8 +513,7 @@ int AAS_AreaReachability(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_AreaGroundFaceArea(int areanum) -{ +float AAS_AreaGroundFaceArea(int areanum) { int i; float total; aas_area_t *area; @@ -549,15 +521,15 @@ float AAS_AreaGroundFaceArea(int areanum) total = 0; area = &aasworld.areas[areanum]; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])]; - if (!(face->faceflags & FACE_GROUND)) continue; + if (!(face->faceflags & FACE_GROUND)) + continue; // total += AAS_FaceArea(face); - } //end for + } // end for return total; -} //end of the function AAS_AreaGroundFaceArea +} // end of the function AAS_AreaGroundFaceArea //=========================================================================== // returns the center of a face // @@ -565,8 +537,7 @@ float AAS_AreaGroundFaceArea(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FaceCenter(int facenum, vec3_t center) -{ +void AAS_FaceCenter(int facenum, vec3_t center) { int i; float scale; aas_face_t *face; @@ -575,15 +546,14 @@ void AAS_FaceCenter(int facenum, vec3_t center) face = &aasworld.faces[facenum]; VectorClear(center); - for (i = 0; i < face->numedges; i++) - { + for (i = 0; i < face->numedges; i++) { edge = &aasworld.edges[abs(aasworld.edgeindex[face->firstedge + i])]; VectorAdd(center, aasworld.vertexes[edge->v[0]], center); VectorAdd(center, aasworld.vertexes[edge->v[1]], center); - } //end for + } // end for scale = 0.5 / face->numedges; VectorScale(center, scale, center); -} //end of the function AAS_FaceCenter +} // end of the function AAS_FaceCenter //=========================================================================== // returns the maximum distance a player can fall before being damaged // damage = deltavelocity*deltavelocity * 0.0001 @@ -592,15 +562,14 @@ void AAS_FaceCenter(int facenum, vec3_t center) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FallDamageDistance(void) -{ +int AAS_FallDamageDistance(void) { float maxzvelocity, gravity, t; maxzvelocity = sqrt((float)(30 * 10000)); gravity = aassettings.phys_gravity; t = maxzvelocity / gravity; return 0.5 * gravity * t * t; -} //end of the function AAS_FallDamageDistance +} // end of the function AAS_FallDamageDistance //=========================================================================== // distance = 0.5 * gravity * t * t // vel = t * gravity @@ -610,29 +579,27 @@ int AAS_FallDamageDistance(void) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_FallDelta(float distance) -{ +float AAS_FallDelta(float distance) { float t, delta, gravity; gravity = aassettings.phys_gravity; t = sqrt(fabs(distance) * 2 / gravity); delta = t * gravity; return delta * delta * 0.0001; -} //end of the function AAS_FallDelta +} // end of the function AAS_FallDelta //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float AAS_MaxJumpHeight(float phys_jumpvel) -{ +float AAS_MaxJumpHeight(float phys_jumpvel) { float phys_gravity; phys_gravity = aassettings.phys_gravity; - //maximum height a player can jump with the given initial z velocity + // maximum height a player can jump with the given initial z velocity return 0.5 * phys_gravity * (phys_jumpvel / phys_gravity) * (phys_jumpvel / phys_gravity); -} //end of the function MaxJumpHeight +} // end of the function MaxJumpHeight //=========================================================================== // returns true if a player can only crouch in the area // @@ -640,17 +607,16 @@ float AAS_MaxJumpHeight(float phys_jumpvel) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_MaxJumpDistance(float phys_jumpvel) -{ +float AAS_MaxJumpDistance(float phys_jumpvel) { float phys_gravity, phys_maxvelocity, t; phys_gravity = aassettings.phys_gravity; phys_maxvelocity = aassettings.phys_maxvelocity; - //time a player takes to fall the height + // time a player takes to fall the height t = sqrt(aassettings.rs_maxjumpfallheight / (0.5 * phys_gravity)); - //maximum distance + // maximum distance return phys_maxvelocity * (t + phys_jumpvel / phys_gravity); -} //end of the function AAS_MaxJumpDistance +} // end of the function AAS_MaxJumpDistance //=========================================================================== // returns true if a player can only crouch in the area // @@ -658,11 +624,12 @@ float AAS_MaxJumpDistance(float phys_jumpvel) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaCrouch(int areanum) -{ - if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) return qtrue; - else return qfalse; -} //end of the function AAS_AreaCrouch +int AAS_AreaCrouch(int areanum) { + if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) + return qtrue; + else + return qfalse; +} // end of the function AAS_AreaCrouch //=========================================================================== // returns qtrue if it is possible to swim in the area // @@ -670,11 +637,12 @@ int AAS_AreaCrouch(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaSwim(int areanum) -{ - if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) return qtrue; - else return qfalse; -} //end of the function AAS_AreaSwim +int AAS_AreaSwim(int areanum) { + if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) + return qtrue; + else + return qfalse; +} // end of the function AAS_AreaSwim //=========================================================================== // returns qtrue if the area contains a liquid // @@ -682,31 +650,26 @@ int AAS_AreaSwim(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaLiquid(int areanum) -{ - if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) return qtrue; - else return qfalse; -} //end of the function AAS_AreaLiquid +int AAS_AreaLiquid(int areanum) { + if (aasworld.areasettings[areanum].areaflags & AREA_LIQUID) + return qtrue; + else + return qfalse; +} // end of the function AAS_AreaLiquid //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaLava(int areanum) -{ - return (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA); -} //end of the function AAS_AreaLava +int AAS_AreaLava(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA); } // end of the function AAS_AreaLava //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaSlime(int areanum) -{ - return (aasworld.areasettings[areanum].contents & AREACONTENTS_SLIME); -} //end of the function AAS_AreaSlime +int AAS_AreaSlime(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_SLIME); } // end of the function AAS_AreaSlime //=========================================================================== // returns qtrue if the area contains ground faces // @@ -714,10 +677,7 @@ int AAS_AreaSlime(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaGrounded(int areanum) -{ - return (aasworld.areasettings[areanum].areaflags & AREA_GROUNDED); -} //end of the function AAS_AreaGround +int AAS_AreaGrounded(int areanum) { return (aasworld.areasettings[areanum].areaflags & AREA_GROUNDED); } // end of the function AAS_AreaGround //=========================================================================== // returns true if the area contains ladder faces // @@ -725,50 +685,37 @@ int AAS_AreaGrounded(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaLadder(int areanum) -{ - return (aasworld.areasettings[areanum].areaflags & AREA_LADDER); -} //end of the function AAS_AreaLadder +int AAS_AreaLadder(int areanum) { return (aasworld.areasettings[areanum].areaflags & AREA_LADDER); } // end of the function AAS_AreaLadder //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaJumpPad(int areanum) -{ - return (aasworld.areasettings[areanum].contents & AREACONTENTS_JUMPPAD); -} //end of the function AAS_AreaJumpPad +int AAS_AreaJumpPad(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_JUMPPAD); } // end of the function AAS_AreaJumpPad //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaTeleporter(int areanum) -{ - return (aasworld.areasettings[areanum].contents & AREACONTENTS_TELEPORTER); -} //end of the function AAS_AreaTeleporter +int AAS_AreaTeleporter(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_TELEPORTER); } // end of the function AAS_AreaTeleporter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaClusterPortal(int areanum) -{ +int AAS_AreaClusterPortal(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_CLUSTERPORTAL); -} //end of the function AAS_AreaClusterPortal +} // end of the function AAS_AreaClusterPortal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaDoNotEnter(int areanum) -{ - return (aasworld.areasettings[areanum].contents & AREACONTENTS_DONOTENTER); -} //end of the function AAS_AreaDoNotEnter +int AAS_AreaDoNotEnter(int areanum) { return (aasworld.areasettings[areanum].contents & AREACONTENTS_DONOTENTER); } // end of the function AAS_AreaDoNotEnter //=========================================================================== // returns the time it takes perform a barrier jump // @@ -776,10 +723,9 @@ int AAS_AreaDoNotEnter(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -unsigned short int AAS_BarrierJumpTravelTime(void) -{ +unsigned short int AAS_BarrierJumpTravelTime(void) { return aassettings.phys_jumpvel / (aassettings.phys_gravity * 0.1); -} //end op the function AAS_BarrierJumpTravelTime +} // end op the function AAS_BarrierJumpTravelTime //=========================================================================== // returns true if there already exists a reachability from area1 to area2 // @@ -787,16 +733,15 @@ unsigned short int AAS_BarrierJumpTravelTime(void) // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_ReachabilityExists(int area1num, int area2num) -{ +qboolean AAS_ReachabilityExists(int area1num, int area2num) { aas_lreachability_t *r; - for (r = areareachability[area1num]; r; r = r->next) - { - if (r->areanum == area2num) return qtrue; - } //end for + for (r = areareachability[area1num]; r; r = r->next) { + if (r->areanum == area2num) + return qtrue; + } // end for return qfalse; -} //end of the function AAS_ReachabilityExists +} // end of the function AAS_ReachabilityExists //=========================================================================== // returns true if there is a solid just after the end point when going // from start to end @@ -805,8 +750,7 @@ qboolean AAS_ReachabilityExists(int area1num, int area2num) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NearbySolidOrGap(vec3_t start, vec3_t end) -{ +int AAS_NearbySolidOrGap(vec3_t start, vec3_t end) { vec3_t dir, testpoint; int areanum; @@ -816,20 +760,20 @@ int AAS_NearbySolidOrGap(vec3_t start, vec3_t end) VectorMA(end, 48, dir, testpoint); areanum = AAS_PointAreaNum(testpoint); - if (!areanum) - { + if (!areanum) { testpoint[2] += 16; areanum = AAS_PointAreaNum(testpoint); - if (!areanum) return qtrue; - } //end if + if (!areanum) + return qtrue; + } // end if VectorMA(end, 64, dir, testpoint); areanum = AAS_PointAreaNum(testpoint); - if (areanum) - { - if (!AAS_AreaSwim(areanum) && !AAS_AreaGrounded(areanum)) return qtrue; - } //end if + if (areanum) { + if (!AAS_AreaSwim(areanum) && !AAS_AreaGrounded(areanum)) + return qtrue; + } // end if return qfalse; -} //end of the function AAS_SolidGapTime +} // end of the function AAS_SolidGapTime //=========================================================================== // searches for swim reachabilities between adjacent areas // @@ -837,8 +781,7 @@ int AAS_NearbySolidOrGap(vec3_t start, vec3_t end) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_Swim(int area1num, int area2num) -{ +int AAS_Reachability_Swim(int area1num, int area2num) { int i, j, face1num, face2num, side1; aas_area_t *area1, *area2; aas_lreachability_t *lreach; @@ -846,41 +789,41 @@ int AAS_Reachability_Swim(int area1num, int area2num) aas_plane_t *plane; vec3_t start; - if (!AAS_AreaSwim(area1num) || !AAS_AreaSwim(area2num)) return qfalse; - //if the second area is crouch only - if (!(aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL)) return qfalse; + if (!AAS_AreaSwim(area1num) || !AAS_AreaSwim(area2num)) + return qfalse; + // if the second area is crouch only + if (!(aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL)) + return qfalse; area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - //if the areas are not near anough - for (i = 0; i < 3; i++) - { - if (area1->mins[i] > area2->maxs[i] + 10) return qfalse; - if (area1->maxs[i] < area2->mins[i] - 10) return qfalse; - } //end for - //find a shared face and create a reachability link - for (i = 0; i < area1->numfaces; i++) - { + // if the areas are not near anough + for (i = 0; i < 3; i++) { + if (area1->mins[i] > area2->maxs[i] + 10) + return qfalse; + if (area1->maxs[i] < area2->mins[i] - 10) + return qfalse; + } // end for + // find a shared face and create a reachability link + for (i = 0; i < area1->numfaces; i++) { face1num = aasworld.faceindex[area1->firstface + i]; side1 = face1num < 0; face1num = abs(face1num); // - for (j = 0; j < area2->numfaces; j++) - { + for (j = 0; j < area2->numfaces; j++) { face2num = abs(aasworld.faceindex[area2->firstface + j]); // - if (face1num == face2num) - { + if (face1num == face2num) { AAS_FaceCenter(face1num, start); // - if (AAS_PointContents(start) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) - { + if (AAS_PointContents(start) & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) { // face1 = &aasworld.faces[face1num]; - //create a new reachability link + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = face1num; lreach->edgenum = 0; @@ -889,21 +832,21 @@ int AAS_Reachability_Swim(int area1num, int area2num) VectorMA(lreach->start, -INSIDEUNITS, plane->normal, lreach->end); lreach->traveltype = TRAVEL_SWIM; lreach->traveltime = 1; - //if the volume of the area is rather small + // if the volume of the area is rather small if (AAS_AreaVolume(area2num) < 800) lreach->traveltime += 200; - //if (!(AAS_PointContents(start) & MASK_WATER)) lreach->traveltime += 500; - //link the reachability + // if (!(AAS_PointContents(start) & MASK_WATER)) lreach->traveltime += 500; + // link the reachability lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; reach_swim++; return qtrue; - } //end if - } //end if - } //end for - } //end for + } // end if + } // end if + } // end for + } // end for return qfalse; -} //end of the function AAS_Reachability_Swim +} // end of the function AAS_Reachability_Swim //=========================================================================== // searches for reachabilities between adjacent areas with equal floor // heights @@ -912,8 +855,7 @@ int AAS_Reachability_Swim(int area1num, int area2num) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) -{ +int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) { int i, j, edgenum, edgenum1, edgenum2, foundreach, side; float height, bestheight, length, bestlength; vec3_t dir, start, end, normal, invgravity, gravitydirection = {0, 0, -1}; @@ -924,18 +866,21 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) aas_plane_t *plane2; aas_lreachability_t lr, *lreach; - if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) return qfalse; + if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) + return qfalse; area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - //if the areas are not near anough in the x-y direction - for (i = 0; i < 2; i++) - { - if (area1->mins[i] > area2->maxs[i] + 10) return qfalse; - if (area1->maxs[i] < area2->mins[i] - 10) return qfalse; - } //end for - //if area 2 is too high above area 1 - if (area2->mins[2] > area1->maxs[2]) return qfalse; + // if the areas are not near anough in the x-y direction + for (i = 0; i < 2; i++) { + if (area1->mins[i] > area2->maxs[i] + 10) + return qfalse; + if (area1->maxs[i] < area2->mins[i] - 10) + return qfalse; + } // end for + // if area 2 is too high above area 1 + if (area2->mins[2] > area1->maxs[2]) + return qfalse; // VectorCopy(gravitydirection, invgravity); VectorInverse(invgravity); @@ -943,67 +888,59 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) bestheight = 99999; bestlength = 0; foundreach = qfalse; - Com_Memset(&lr, 0, sizeof(aas_lreachability_t)); //make the compiler happy + Com_Memset(&lr, 0, sizeof(aas_lreachability_t)); // make the compiler happy // - //check if the areas have ground faces with a common edge - //if existing use the lowest common edge for a reachability link - for (i = 0; i < area1->numfaces; i++) - { + // check if the areas have ground faces with a common edge + // if existing use the lowest common edge for a reachability link + for (i = 0; i < area1->numfaces; i++) { face1 = &aasworld.faces[abs(aasworld.faceindex[area1->firstface + i])]; - if (!(face1->faceflags & FACE_GROUND)) continue; + if (!(face1->faceflags & FACE_GROUND)) + continue; // - for (j = 0; j < area2->numfaces; j++) - { + for (j = 0; j < area2->numfaces; j++) { face2 = &aasworld.faces[abs(aasworld.faceindex[area2->firstface + j])]; - if (!(face2->faceflags & FACE_GROUND)) continue; - //if there is a common edge - for (edgenum1 = 0; edgenum1 < face1->numedges; edgenum1++) - { - for (edgenum2 = 0; edgenum2 < face2->numedges; edgenum2++) - { - if (abs(aasworld.edgeindex[face1->firstedge + edgenum1]) != - abs(aasworld.edgeindex[face2->firstedge + edgenum2])) - continue; + if (!(face2->faceflags & FACE_GROUND)) + continue; + // if there is a common edge + for (edgenum1 = 0; edgenum1 < face1->numedges; edgenum1++) { + for (edgenum2 = 0; edgenum2 < face2->numedges; edgenum2++) { + if (abs(aasworld.edgeindex[face1->firstedge + edgenum1]) != abs(aasworld.edgeindex[face2->firstedge + edgenum2])) + continue; edgenum = aasworld.edgeindex[face1->firstedge + edgenum1]; side = edgenum < 0; edge = &aasworld.edges[abs(edgenum)]; - //get the length of the edge - VectorSubtract(aasworld.vertexes[edge->v[1]], - aasworld.vertexes[edge->v[0]], dir); + // get the length of the edge + VectorSubtract(aasworld.vertexes[edge->v[1]], aasworld.vertexes[edge->v[0]], dir); length = VectorLength(dir); - //get the start point - VectorAdd(aasworld.vertexes[edge->v[0]], - aasworld.vertexes[edge->v[1]], start); + // get the start point + VectorAdd(aasworld.vertexes[edge->v[0]], aasworld.vertexes[edge->v[1]], start); VectorScale(start, 0.5, start); VectorCopy(start, end); - //get the end point several units inside area2 - //and the start point several units inside area1 - //NOTE: normal is pointing into area2 because the - //face edges are stored counter clockwise - VectorSubtract(aasworld.vertexes[edge->v[side]], - aasworld.vertexes[edge->v[!side]], edgevec); + // get the end point several units inside area2 + // and the start point several units inside area1 + // NOTE: normal is pointing into area2 because the + // face edges are stored counter clockwise + VectorSubtract(aasworld.vertexes[edge->v[side]], aasworld.vertexes[edge->v[!side]], edgevec); plane2 = &aasworld.planes[face2->planenum]; CrossProduct(edgevec, plane2->normal, normal); VectorNormalize(normal); // - //VectorMA(start, -1, normal, start); + // VectorMA(start, -1, normal, start); VectorMA(end, INSIDEUNITS_WALKEND, normal, end); VectorMA(start, INSIDEUNITS_WALKSTART, normal, start); end[2] += 0.125; // height = DotProduct(invgravity, start); - //NOTE: if there's nearby solid or a gap area after this area - //disabled this crap - //if (AAS_NearbySolidOrGap(start, end)) height += 200; - //NOTE: disabled because it disables reachabilities to very small areas - //if (AAS_PointAreaNum(end) != area2num) continue; - //get the longest lowest edge - if (height < bestheight || - (height < bestheight + 1 && length > bestlength)) - { + // NOTE: if there's nearby solid or a gap area after this area + // disabled this crap + // if (AAS_NearbySolidOrGap(start, end)) height += 200; + // NOTE: disabled because it disables reachabilities to very small areas + // if (AAS_PointAreaNum(end) != area2num) continue; + // get the longest lowest edge + if (height < bestheight || (height < bestheight + 1 && length > bestlength)) { bestheight = height; bestlength = length; - //create a new reachability link + // create a new reachability link lr.areanum = area2num; lr.facenum = 0; lr.edgenum = edgenum; @@ -1012,16 +949,16 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) lr.traveltype = TRAVEL_WALK; lr.traveltime = 1; foundreach = qtrue; - } //end if - } //end for - } //end for - } //end for - } //end for - if (foundreach) - { - //create a new reachability link + } // end if + } // end for + } // end for + } // end for + } // end for + if (foundreach) { + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = lr.areanum; lreach->facenum = lr.facenum; lreach->edgenum = lr.edgenum; @@ -1031,11 +968,10 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) lreach->traveltime = lr.traveltime; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //if going into a crouch area - if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num)) - { + // if going into a crouch area + if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num)) { lreach->traveltime += aassettings.rs_startcrouch; - } //end if + } // end if /* //NOTE: if there's nearby solid or a gap area after this area if (!AAS_NearbySolidOrGap(lreach->start, lreach->end)) @@ -1043,14 +979,14 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) lreach->traveltime += 100; } //end if */ - //avoid rather small areas - //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; + // avoid rather small areas + // if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; // reach_equalfloor++; return qtrue; - } //end if + } // end if return qfalse; -} //end of the function AAS_Reachability_EqualFloorHeight +} // end of the function AAS_Reachability_EqualFloorHeight //=========================================================================== // searches step, barrier, waterjump and walk off ledge reachabilities // @@ -1058,14 +994,13 @@ int AAS_Reachability_EqualFloorHeight(int area1num, int area2num) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2num) -{ +int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2num) { int i, j, k, l, edge1num, edge2num, areas[10], numareas; int ground_bestarea2groundedgenum, ground_foundreach; int water_bestarea2groundedgenum, water_foundreach; int side1, area1swim, faceside1, groundface1num; float dist, dist1, dist2, diff, ortdot; - //float invgravitydot; + // float invgravitydot; float x1, x2, x3, x4, y1, y2, y3, y4, tmp, y; float length, ground_bestlength, water_bestlength, ground_bestdist, water_bestdist; vec3_t v1, v2, v3, v4, tmpv, p1area1, p1area2, p2area1, p2area2; @@ -1081,21 +1016,24 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 aas_lreachability_t *lreach; aas_trace_t trace; - //must be able to walk or swim in the first area - if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) return qfalse; + // must be able to walk or swim in the first area + if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) + return qfalse; // - if (!AAS_AreaGrounded(area2num) && !AAS_AreaSwim(area2num)) return qfalse; + if (!AAS_AreaGrounded(area2num) && !AAS_AreaSwim(area2num)) + return qfalse; // area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - //if the first area contains a liquid + // if the first area contains a liquid area1swim = AAS_AreaSwim(area1num); - //if the areas are not near enough in the x-y direction - for (i = 0; i < 2; i++) - { - if (area1->mins[i] > area2->maxs[i] + 10) return qfalse; - if (area1->maxs[i] < area2->mins[i] - 10) return qfalse; - } //end for + // if the areas are not near enough in the x-y direction + for (i = 0; i < 2; i++) { + if (area1->mins[i] > area2->maxs[i] + 10) + return qfalse; + if (area1->maxs[i] < area2->mins[i] - 10) + return qfalse; + } // end for // ground_foundreach = qfalse; ground_bestdist = 99999; @@ -1107,236 +1045,227 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 water_bestlength = 0; water_bestarea2groundedgenum = 0; // - for (i = 0; i < area1->numfaces; i++) - { + for (i = 0; i < area1->numfaces; i++) { groundface1num = aasworld.faceindex[area1->firstface + i]; faceside1 = groundface1num < 0; groundface1 = &aasworld.faces[abs(groundface1num)]; - //if this isn't a ground face - if (!(groundface1->faceflags & FACE_GROUND)) - { - //if we can swim in the first area - if (area1swim) - { - //face plane must be more or less horizontal + // if this isn't a ground face + if (!(groundface1->faceflags & FACE_GROUND)) { + // if we can swim in the first area + if (area1swim) { + // face plane must be more or less horizontal plane = &aasworld.planes[groundface1->planenum ^ (!faceside1)]; - if (DotProduct(plane->normal, invgravity) < 0.7) continue; - } //end if - else - { - //if we can't swim in the area it must be a ground face + if (DotProduct(plane->normal, invgravity) < 0.7) + continue; + } // end if + else { + // if we can't swim in the area it must be a ground face continue; - } //end else - } //end if + } // end else + } // end if // - for (k = 0; k < groundface1->numedges; k++) - { + for (k = 0; k < groundface1->numedges; k++) { edge1num = aasworld.edgeindex[groundface1->firstedge + k]; side1 = (edge1num < 0); - //NOTE: for water faces we must take the side area 1 is - // on into account because the face is shared and doesn't - // have to be oriented correctly - if (!(groundface1->faceflags & FACE_GROUND)) side1 = (side1 == faceside1); + // NOTE: for water faces we must take the side area 1 is + // on into account because the face is shared and doesn't + // have to be oriented correctly + if (!(groundface1->faceflags & FACE_GROUND)) + side1 = (side1 == faceside1); edge1num = abs(edge1num); edge1 = &aasworld.edges[edge1num]; - //vertexes of the edge + // vertexes of the edge VectorCopy(aasworld.vertexes[edge1->v[!side1]], v1); VectorCopy(aasworld.vertexes[edge1->v[side1]], v2); - //get a vertical plane through the edge - //NOTE: normal is pointing into area 2 because the - //face edges are stored counter clockwise + // get a vertical plane through the edge + // NOTE: normal is pointing into area 2 because the + // face edges are stored counter clockwise VectorSubtract(v2, v1, edgevec); CrossProduct(edgevec, invgravity, normal); VectorNormalize(normal); dist = DotProduct(normal, v1); - //check the faces from the second area - for (j = 0; j < area2->numfaces; j++) - { + // check the faces from the second area + for (j = 0; j < area2->numfaces; j++) { groundface2 = &aasworld.faces[abs(aasworld.faceindex[area2->firstface + j])]; - //must be a ground face - if (!(groundface2->faceflags & FACE_GROUND)) continue; - //check the edges of this ground face - for (l = 0; l < groundface2->numedges; l++) - { + // must be a ground face + if (!(groundface2->faceflags & FACE_GROUND)) + continue; + // check the edges of this ground face + for (l = 0; l < groundface2->numedges; l++) { edge2num = abs(aasworld.edgeindex[groundface2->firstedge + l]); edge2 = &aasworld.edges[edge2num]; - //vertexes of the edge + // vertexes of the edge VectorCopy(aasworld.vertexes[edge2->v[0]], v3); VectorCopy(aasworld.vertexes[edge2->v[1]], v4); - //check the distance between the two points and the vertical plane - //through the edge of area1 + // check the distance between the two points and the vertical plane + // through the edge of area1 diff = DotProduct(normal, v3) - dist; - if (diff < -0.1 || diff > 0.1) continue; + if (diff < -0.1 || diff > 0.1) + continue; diff = DotProduct(normal, v4) - dist; - if (diff < -0.1 || diff > 0.1) continue; + if (diff < -0.1 || diff > 0.1) + continue; // - //project the two ground edges into the step side plane - //and calculate the shortest distance between the two - //edges if they overlap in the direction orthogonal to - //the gravity direction + // project the two ground edges into the step side plane + // and calculate the shortest distance between the two + // edges if they overlap in the direction orthogonal to + // the gravity direction CrossProduct(invgravity, normal, ort); - //invgravitydot = DotProduct(invgravity, invgravity); + // invgravitydot = DotProduct(invgravity, invgravity); ortdot = DotProduct(ort, ort); - //projection into the step plane - //NOTE: since gravity is vertical this is just the z coordinate - y1 = v1[2];//DotProduct(v1, invgravity) / invgravitydot; - y2 = v2[2];//DotProduct(v2, invgravity) / invgravitydot; - y3 = v3[2];//DotProduct(v3, invgravity) / invgravitydot; - y4 = v4[2];//DotProduct(v4, invgravity) / invgravitydot; + // projection into the step plane + // NOTE: since gravity is vertical this is just the z coordinate + y1 = v1[2]; // DotProduct(v1, invgravity) / invgravitydot; + y2 = v2[2]; // DotProduct(v2, invgravity) / invgravitydot; + y3 = v3[2]; // DotProduct(v3, invgravity) / invgravitydot; + y4 = v4[2]; // DotProduct(v4, invgravity) / invgravitydot; // x1 = DotProduct(v1, ort) / ortdot; x2 = DotProduct(v2, ort) / ortdot; x3 = DotProduct(v3, ort) / ortdot; x4 = DotProduct(v4, ort) / ortdot; // - if (x1 > x2) - { - tmp = x1; x1 = x2; x2 = tmp; - tmp = y1; y1 = y2; y2 = tmp; - VectorCopy(v1, tmpv); VectorCopy(v2, v1); VectorCopy(tmpv, v2); - } //end if - if (x3 > x4) - { - tmp = x3; x3 = x4; x4 = tmp; - tmp = y3; y3 = y4; y4 = tmp; - VectorCopy(v3, tmpv); VectorCopy(v4, v3); VectorCopy(tmpv, v4); - } //end if - //if the two projected edge lines have no overlap - if (x2 <= x3 || x4 <= x1) - { -// Log_Write("lines no overlap: from area %d to %d\r\n", area1num, area2num); + if (x1 > x2) { + tmp = x1; + x1 = x2; + x2 = tmp; + tmp = y1; + y1 = y2; + y2 = tmp; + VectorCopy(v1, tmpv); + VectorCopy(v2, v1); + VectorCopy(tmpv, v2); + } // end if + if (x3 > x4) { + tmp = x3; + x3 = x4; + x4 = tmp; + tmp = y3; + y3 = y4; + y4 = tmp; + VectorCopy(v3, tmpv); + VectorCopy(v4, v3); + VectorCopy(tmpv, v4); + } // end if + // if the two projected edge lines have no overlap + if (x2 <= x3 || x4 <= x1) { + // Log_Write("lines no overlap: from area %d to %d\r\n", area1num, area2num); continue; - } //end if - //if the two lines fully overlap - if ((x1 - 0.5 < x3 && x4 < x2 + 0.5) && - (x3 - 0.5 < x1 && x2 < x4 + 0.5)) - { + } // end if + // if the two lines fully overlap + if ((x1 - 0.5 < x3 && x4 < x2 + 0.5) && (x3 - 0.5 < x1 && x2 < x4 + 0.5)) { dist1 = y3 - y1; dist2 = y4 - y2; VectorCopy(v1, p1area1); VectorCopy(v2, p2area1); VectorCopy(v3, p1area2); VectorCopy(v4, p2area2); - } //end if - else - { - //if the points are equal - if (x1 > x3 - 0.1 && x1 < x3 + 0.1) - { + } // end if + else { + // if the points are equal + if (x1 > x3 - 0.1 && x1 < x3 + 0.1) { dist1 = y3 - y1; VectorCopy(v1, p1area1); VectorCopy(v3, p1area2); - } //end if - else if (x1 < x3) - { + } // end if + else if (x1 < x3) { y = y1 + (x3 - x1) * (y2 - y1) / (x2 - x1); dist1 = y3 - y; VectorCopy(v3, p1area1); p1area1[2] = y; VectorCopy(v3, p1area2); - } //end if - else - { + } // end if + else { y = y3 + (x1 - x3) * (y4 - y3) / (x4 - x3); dist1 = y - y1; VectorCopy(v1, p1area1); VectorCopy(v1, p1area2); p1area2[2] = y; - } //end if - //if the points are equal - if (x2 > x4 - 0.1 && x2 < x4 + 0.1) - { + } // end if + // if the points are equal + if (x2 > x4 - 0.1 && x2 < x4 + 0.1) { dist2 = y4 - y2; VectorCopy(v2, p2area1); VectorCopy(v4, p2area2); - } //end if - else if (x2 < x4) - { + } // end if + else if (x2 < x4) { y = y3 + (x2 - x3) * (y4 - y3) / (x4 - x3); dist2 = y - y2; VectorCopy(v2, p2area1); VectorCopy(v2, p2area2); p2area2[2] = y; - } //end if - else - { + } // end if + else { y = y1 + (x4 - x1) * (y2 - y1) / (x2 - x1); dist2 = y4 - y; VectorCopy(v4, p2area1); p2area1[2] = y; VectorCopy(v4, p2area2); - } //end else - } //end else - //if both distances are pretty much equal - //then we take the middle of the points - if (dist1 > dist2 - 1 && dist1 < dist2 + 1) - { + } // end else + } // end else + // if both distances are pretty much equal + // then we take the middle of the points + if (dist1 > dist2 - 1 && dist1 < dist2 + 1) { dist = dist1; VectorAdd(p1area1, p2area1, start); VectorScale(start, 0.5, start); VectorAdd(p1area2, p2area2, end); VectorScale(end, 0.5, end); - } //end if - else if (dist1 < dist2) - { + } // end if + else if (dist1 < dist2) { dist = dist1; VectorCopy(p1area1, start); VectorCopy(p1area2, end); - } //end else if - else - { + } // end else if + else { dist = dist2; VectorCopy(p2area1, start); VectorCopy(p2area2, end); - } //end else - //get the length of the overlapping part of the edges of the two areas + } // end else + // get the length of the overlapping part of the edges of the two areas VectorSubtract(p2area2, p1area2, dir); length = VectorLength(dir); // - if (groundface1->faceflags & FACE_GROUND) - { - //if the vertical distance is smaller + if (groundface1->faceflags & FACE_GROUND) { + // if the vertical distance is smaller if (dist < ground_bestdist || - //or the vertical distance is pretty much the same - //but the overlapping part of the edges is longer - (dist < ground_bestdist + 1 && length > ground_bestlength)) - { + // or the vertical distance is pretty much the same + // but the overlapping part of the edges is longer + (dist < ground_bestdist + 1 && length > ground_bestlength)) { ground_bestdist = dist; ground_bestlength = length; ground_foundreach = qtrue; ground_bestarea2groundedgenum = edge1num; - //best point towards area1 + // best point towards area1 VectorCopy(start, ground_beststart); - //normal is pointing into area2 + // normal is pointing into area2 VectorCopy(normal, ground_bestnormal); - //best point towards area2 + // best point towards area2 VectorCopy(end, ground_bestend); - } //end if - } //end if - else - { - //if the vertical distance is smaller + } // end if + } // end if + else { + // if the vertical distance is smaller if (dist < water_bestdist || - //or the vertical distance is pretty much the same - //but the overlapping part of the edges is longer - (dist < water_bestdist + 1 && length > water_bestlength)) - { + // or the vertical distance is pretty much the same + // but the overlapping part of the edges is longer + (dist < water_bestdist + 1 && length > water_bestlength)) { water_bestdist = dist; water_bestlength = length; water_foundreach = qtrue; water_bestarea2groundedgenum = edge1num; - //best point towards area1 + // best point towards area1 VectorCopy(start, water_beststart); - //normal is pointing into area2 + // normal is pointing into area2 VectorCopy(normal, water_bestnormal); - //best point towards area2 + // best point towards area2 VectorCopy(end, water_bestend); - } //end if - } //end else - } //end for - } //end for - } //end for - } //end for + } // end if + } // end else + } // end for + } // end for + } // end for + } // end for // // NOTE: swim reachabilities are already filtered out // @@ -1355,44 +1284,42 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 // | step height and low water up to the step -> TRAVEL_WALK //--------| // - //check for a step reachability - if (ground_foundreach) - { - //if area2 is higher but lower than the maximum step height - //NOTE: ground_bestdist >= 0 also catches equal floor reachabilities - if (ground_bestdist >= 0 && ground_bestdist < aassettings.phys_maxstep) - { - //create walk reachability from area1 to area2 + // check for a step reachability + if (ground_foundreach) { + // if area2 is higher but lower than the maximum step height + // NOTE: ground_bestdist >= 0 also catches equal floor reachabilities + if (ground_bestdist >= 0 && ground_bestdist < aassettings.phys_maxstep) { + // create walk reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorMA(ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start); VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end); lreach->traveltype = TRAVEL_WALK; - lreach->traveltime = 0;//1; - //if going into a crouch area - if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num)) - { + lreach->traveltime = 0; // 1; + // if going into a crouch area + if (!AAS_AreaCrouch(area1num) && AAS_AreaCrouch(area2num)) { lreach->traveltime += aassettings.rs_startcrouch; - } //end if + } // end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //NOTE: if there's nearby solid or a gap area after this area + // NOTE: if there's nearby solid or a gap area after this area /* if (!AAS_NearbySolidOrGap(lreach->start, lreach->end)) { lreach->traveltime += 100; } //end if */ - //avoid rather small areas - //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; + // avoid rather small areas + // if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; // reach_step++; return qtrue; - } //end if - } //end if + } // end if + } // end if // // Water Jumps // @@ -1411,27 +1338,23 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 // | higher than step height and low water up to the step -> TRAVEL_WATERJUMP //--------| // - //check for a waterjump reachability - if (water_foundreach) - { - //get a test point a little bit towards area1 + // check for a waterjump reachability + if (water_foundreach) { + // get a test point a little bit towards area1 VectorMA(water_bestend, -INSIDEUNITS, water_bestnormal, testpoint); - //go down the maximum waterjump height + // go down the maximum waterjump height testpoint[2] -= aassettings.phys_maxwaterjump; - //if there IS water the sv_maxwaterjump height below the bestend point - if (aasworld.areasettings[AAS_PointAreaNum(testpoint)].areaflags & AREA_LIQUID) - { - //don't create rediculous water jump reachabilities from areas very far below - //the water surface - if (water_bestdist < aassettings.phys_maxwaterjump + 24) - { - //waterjumping from or towards a crouch only area is not possible in Quake2 - if ((aasworld.areasettings[area1num].presencetype & PRESENCE_NORMAL) && - (aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL)) - { - //create water jump reachability from area1 to area2 + // if there IS water the sv_maxwaterjump height below the bestend point + if (aasworld.areasettings[AAS_PointAreaNum(testpoint)].areaflags & AREA_LIQUID) { + // don't create rediculous water jump reachabilities from areas very far below + // the water surface + if (water_bestdist < aassettings.phys_maxwaterjump + 24) { + // waterjumping from or towards a crouch only area is not possible in Quake2 + if ((aasworld.areasettings[area1num].presencetype & PRESENCE_NORMAL) && (aasworld.areasettings[area2num].presencetype & PRESENCE_NORMAL)) { + // create water jump reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = water_bestarea2groundedgenum; @@ -1441,13 +1364,13 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 lreach->traveltime = aassettings.rs_waterjump; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //we've got another waterjump reachability + // we've got another waterjump reachability reach_waterjump++; return qtrue; - } //end if - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if + } // end if // // Barrier Jumps // @@ -1465,37 +1388,34 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 //~~~~~~~~| higher than step height lower than barrier height //--------| and a thin layer of water in the area to jump from -> TRAVEL_BARRIERJUMP // - //check for a barrier jump reachability - if (ground_foundreach) - { - //if area2 is higher but lower than the maximum barrier jump height - if (ground_bestdist > 0 && ground_bestdist < aassettings.phys_maxbarrier) - { - //if no water in area1 or a very thin layer of water on the ground - if (!water_foundreach || (ground_bestdist - water_bestdist < 16)) - { - //cannot perform a barrier jump towards or from a crouch area in Quake2 - if (!AAS_AreaCrouch(area1num) && !AAS_AreaCrouch(area2num)) - { - //create barrier jump reachability from area1 to area2 + // check for a barrier jump reachability + if (ground_foundreach) { + // if area2 is higher but lower than the maximum barrier jump height + if (ground_bestdist > 0 && ground_bestdist < aassettings.phys_maxbarrier) { + // if no water in area1 or a very thin layer of water on the ground + if (!water_foundreach || (ground_bestdist - water_bestdist < 16)) { + // cannot perform a barrier jump towards or from a crouch area in Quake2 + if (!AAS_AreaCrouch(area1num) && !AAS_AreaCrouch(area2num)) { + // create barrier jump reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorMA(ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start); VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end); lreach->traveltype = TRAVEL_BARRIERJUMP; - lreach->traveltime = aassettings.rs_barrierjump;//AAS_BarrierJumpTravelTime(); + lreach->traveltime = aassettings.rs_barrierjump; // AAS_BarrierJumpTravelTime(); lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //we've got another barrierjump reachability + // we've got another barrierjump reachability reach_barrier++; return qtrue; - } //end if - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if + } // end if // // Walk and Walk Off Ledge // @@ -1517,16 +1437,14 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 // | cannot step back but can waterjump back -> TRAVEL_WALKOFFLEDGE // --------- FIXME: create TRAVEL_WALK reach?? // - //check for a walk or walk off ledge reachability - if (ground_foundreach) - { - if (ground_bestdist < 0) - { - if (ground_bestdist > -aassettings.phys_maxstep) - { - //create walk reachability from area1 to area2 + // check for a walk or walk off ledge reachability + if (ground_foundreach) { + if (ground_bestdist < 0) { + if (ground_bestdist > -aassettings.phys_maxstep) { + // create walk reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; @@ -1536,36 +1454,34 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 lreach->traveltime = 1; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //we've got another walk reachability + // we've got another walk reachability reach_walk++; return qtrue; - } //end if + } // end if // if no maximum fall height set or less than the max if (!aassettings.rs_maxfallheight || fabs(ground_bestdist) < aassettings.rs_maxfallheight) { - //trace a bounding box vertically to check for solids + // trace a bounding box vertically to check for solids VectorMA(ground_bestend, INSIDEUNITS, ground_bestnormal, ground_bestend); VectorCopy(ground_bestend, start); start[2] = ground_beststart[2]; VectorCopy(ground_bestend, end); end[2] += 4; trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1); - //if no solids were found - if (!trace.startsolid && trace.fraction >= 1.0) - { - //the trace end point must be in the goal area + // if no solids were found + if (!trace.startsolid && trace.fraction >= 1.0) { + // the trace end point must be in the goal area trace.endpos[2] += 1; - if (AAS_PointAreaNum(trace.endpos) == area2num) - { - //if not going through a cluster portal + if (AAS_PointAreaNum(trace.endpos) == area2num) { + // if not going through a cluster portal numareas = AAS_TraceAreas(start, end, areas, NULL, ARRAY_LEN(areas)); for (i = 0; i < numareas; i++) if (AAS_AreaClusterPortal(areas[i])) break; - if (i >= numareas) - { - //create a walk off ledge reachability from area1 to area2 + if (i >= numareas) { + // create a walk off ledge reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; @@ -1573,34 +1489,31 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 VectorCopy(ground_bestend, lreach->end); lreach->traveltype = TRAVEL_WALKOFFLEDGE; lreach->traveltime = aassettings.rs_startwalkoffledge + fabs(ground_bestdist) * 50 / aassettings.phys_gravity; - //if falling from too high and not falling into water - if (!AAS_AreaSwim(area2num) && !AAS_AreaJumpPad(area2num)) - { - if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta5) - { + // if falling from too high and not falling into water + if (!AAS_AreaSwim(area2num) && !AAS_AreaJumpPad(area2num)) { + if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta5) { lreach->traveltime += aassettings.rs_falldamage5; - } //end if - if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta10) - { + } // end if + if (AAS_FallDelta(ground_bestdist) > aassettings.phys_falldelta10) { lreach->traveltime += aassettings.rs_falldamage10; - } //end if - } //end if + } // end if + } // end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_walkoffledge++; - //NOTE: don't create a weapon (rl, bfg) jump reachability here - //because it interferes with other reachabilities - //like the ladder reachability + // NOTE: don't create a weapon (rl, bfg) jump reachability here + // because it interferes with other reachabilities + // like the ladder reachability return qtrue; - } //end if - } //end if - } //end if - } //end if - } //end else - } //end if + } // end if + } // end if + } // end if + } // end if + } // end else + } // end if return qfalse; -} //end of the function AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge +} // end of the function AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge //=========================================================================== // returns the distance between the two vectors // @@ -1608,13 +1521,12 @@ int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(int area1num, int area2 // Returns: - // Changes Globals: - //=========================================================================== -float VectorDistance(vec3_t v1, vec3_t v2) -{ +float VectorDistance(vec3_t v1, vec3_t v2) { vec3_t dir; VectorSubtract(v2, v1, dir); return VectorLength(dir); -} //end of the function VectorDistance +} // end of the function VectorDistance //=========================================================================== // returns true if the first vector is between the last two vectors // @@ -1622,14 +1534,13 @@ float VectorDistance(vec3_t v1, vec3_t v2) // Returns: - // Changes Globals: - //=========================================================================== -int VectorBetweenVectors(vec3_t v, vec3_t v1, vec3_t v2) -{ +int VectorBetweenVectors(vec3_t v, vec3_t v1, vec3_t v2) { vec3_t dir1, dir2; VectorSubtract(v, v1, dir1); VectorSubtract(v, v2, dir2); return (DotProduct(dir1, dir2) <= 0); -} //end of the function VectorBetweenVectors +} // end of the function VectorBetweenVectors //=========================================================================== // returns the mid point between the two vectors // @@ -1637,11 +1548,10 @@ int VectorBetweenVectors(vec3_t v, vec3_t v1, vec3_t v2) // Returns: - // Changes Globals: - //=========================================================================== -void VectorMiddle(vec3_t v1, vec3_t v2, vec3_t middle) -{ +void VectorMiddle(vec3_t v1, vec3_t v2, vec3_t middle) { VectorAdd(v1, v2, middle); VectorScale(middle, 0.5, middle); -} //end of the function VectorMiddle +} // end of the function VectorMiddle //=========================================================================== // calculate a range of points closest to each other on both edges // @@ -1829,19 +1739,16 @@ float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, return bestdist; } //end of the function AAS_ClosestEdgePoints*/ -float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, - aas_plane_t *plane1, aas_plane_t *plane2, - vec3_t beststart1, vec3_t bestend1, - vec3_t beststart2, vec3_t bestend2, float bestdist) -{ +float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, aas_plane_t *plane1, aas_plane_t *plane2, vec3_t beststart1, vec3_t bestend1, + vec3_t beststart2, vec3_t bestend2, float bestdist) { vec3_t dir1, dir2, p1, p2, p3, p4; float a1, a2, b1, b2, dist, dist1, dist2; int founddist; - //edge vectors + // edge vectors VectorSubtract(v2, v1, dir1); VectorSubtract(v4, v3, dir2); - //get the horizontal directions + // get the horizontal directions dir1[2] = 0; dir2[2] = 0; // @@ -1850,54 +1757,50 @@ float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, // p3 = point on an edge vector of area1 closest to v3 // p4 = point on an edge vector of area1 closest to v4 // - if (dir2[0]) - { + if (dir2[0]) { a2 = dir2[1] / dir2[0]; b2 = v3[1] - a2 * v3[0]; - //point on the edge vector of area2 closest to v1 + // point on the edge vector of area2 closest to v1 p1[0] = (DotProduct(v1, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0]; p1[1] = a2 * p1[0] + b2; - //point on the edge vector of area2 closest to v2 + // point on the edge vector of area2 closest to v2 p2[0] = (DotProduct(v2, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0]; p2[1] = a2 * p2[0] + b2; - } //end if - else - { - //point on the edge vector of area2 closest to v1 + } // end if + else { + // point on the edge vector of area2 closest to v1 p1[0] = v3[0]; p1[1] = v1[1]; - //point on the edge vector of area2 closest to v2 + // point on the edge vector of area2 closest to v2 p2[0] = v3[0]; p2[1] = v2[1]; - } //end else + } // end else // - if (dir1[0]) - { + if (dir1[0]) { // a1 = dir1[1] / dir1[0]; b1 = v1[1] - a1 * v1[0]; - //point on the edge vector of area1 closest to v3 + // point on the edge vector of area1 closest to v3 p3[0] = (DotProduct(v3, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0]; p3[1] = a1 * p3[0] + b1; - //point on the edge vector of area1 closest to v4 + // point on the edge vector of area1 closest to v4 p4[0] = (DotProduct(v4, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0]; p4[1] = a1 * p4[0] + b1; - } //end if - else - { - //point on the edge vector of area1 closest to v3 + } // end if + else { + // point on the edge vector of area1 closest to v3 p3[0] = v1[0]; p3[1] = v3[1]; - //point on the edge vector of area1 closest to v4 + // point on the edge vector of area1 closest to v4 p4[0] = v1[0]; p4[1] = v4[1]; - } //end else - //start with zero z-coordinates + } // end else + // start with zero z-coordinates p1[2] = 0; p2[2] = 0; p3[2] = 0; p4[2] = 0; - //calculate the z-coordinates from the ground planes + // calculate the z-coordinates from the ground planes p1[2] = (plane2->dist - DotProduct(plane2->normal, p1)) / plane2->normal[2]; p2[2] = (plane2->dist - DotProduct(plane2->normal, p2)) / plane2->normal[2]; p3[2] = (plane1->dist - DotProduct(plane1->normal, p3)) / plane1->normal[2]; @@ -1905,193 +1808,176 @@ float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, // founddist = qfalse; // - if (VectorBetweenVectors(p1, v3, v4)) - { + if (VectorBetweenVectors(p1, v3, v4)) { dist = VectorDistance(v1, p1); - if (dist > bestdist - 0.5 && dist < bestdist + 0.5) - { + if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { dist1 = VectorDistance(beststart1, v1); dist2 = VectorDistance(beststart2, v1); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(v1, beststart2); - } //end if - else - { - if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(v1, beststart1); - } //end else + if (dist1 > dist2) { + if (dist1 > VectorDistance(beststart1, beststart2)) + VectorCopy(v1, beststart2); + } // end if + else { + if (dist2 > VectorDistance(beststart1, beststart2)) + VectorCopy(v1, beststart1); + } // end else dist1 = VectorDistance(bestend1, p1); dist2 = VectorDistance(bestend2, p1); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(p1, bestend2); - } //end if - else - { - if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(p1, bestend1); - } //end else - } //end if - else if (dist < bestdist) - { + if (dist1 > dist2) { + if (dist1 > VectorDistance(bestend1, bestend2)) + VectorCopy(p1, bestend2); + } // end if + else { + if (dist2 > VectorDistance(bestend1, bestend2)) + VectorCopy(p1, bestend1); + } // end else + } // end if + else if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart1); VectorCopy(v1, beststart2); VectorCopy(p1, bestend1); VectorCopy(p1, bestend2); - } //end if + } // end if founddist = qtrue; - } //end if - if (VectorBetweenVectors(p2, v3, v4)) - { + } // end if + if (VectorBetweenVectors(p2, v3, v4)) { dist = VectorDistance(v2, p2); - if (dist > bestdist - 0.5 && dist < bestdist + 0.5) - { + if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { dist1 = VectorDistance(beststart1, v2); dist2 = VectorDistance(beststart2, v2); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(v2, beststart2); - } //end if - else - { - if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(v2, beststart1); - } //end else + if (dist1 > dist2) { + if (dist1 > VectorDistance(beststart1, beststart2)) + VectorCopy(v2, beststart2); + } // end if + else { + if (dist2 > VectorDistance(beststart1, beststart2)) + VectorCopy(v2, beststart1); + } // end else dist1 = VectorDistance(bestend1, p2); dist2 = VectorDistance(bestend2, p2); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(p2, bestend2); - } //end if - else - { - if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(p2, bestend1); - } //end else - } //end if - else if (dist < bestdist) - { + if (dist1 > dist2) { + if (dist1 > VectorDistance(bestend1, bestend2)) + VectorCopy(p2, bestend2); + } // end if + else { + if (dist2 > VectorDistance(bestend1, bestend2)) + VectorCopy(p2, bestend1); + } // end else + } // end if + else if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart1); VectorCopy(v2, beststart2); VectorCopy(p2, bestend1); VectorCopy(p2, bestend2); - } //end if + } // end if founddist = qtrue; - } //end else if - if (VectorBetweenVectors(p3, v1, v2)) - { + } // end else if + if (VectorBetweenVectors(p3, v1, v2)) { dist = VectorDistance(v3, p3); - if (dist > bestdist - 0.5 && dist < bestdist + 0.5) - { + if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { dist1 = VectorDistance(beststart1, p3); dist2 = VectorDistance(beststart2, p3); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(p3, beststart2); - } //end if - else - { - if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(p3, beststart1); - } //end else + if (dist1 > dist2) { + if (dist1 > VectorDistance(beststart1, beststart2)) + VectorCopy(p3, beststart2); + } // end if + else { + if (dist2 > VectorDistance(beststart1, beststart2)) + VectorCopy(p3, beststart1); + } // end else dist1 = VectorDistance(bestend1, v3); dist2 = VectorDistance(bestend2, v3); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(v3, bestend2); - } //end if - else - { - if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(v3, bestend1); - } //end else - } //end if - else if (dist < bestdist) - { + if (dist1 > dist2) { + if (dist1 > VectorDistance(bestend1, bestend2)) + VectorCopy(v3, bestend2); + } // end if + else { + if (dist2 > VectorDistance(bestend1, bestend2)) + VectorCopy(v3, bestend1); + } // end else + } // end if + else if (dist < bestdist) { bestdist = dist; VectorCopy(p3, beststart1); VectorCopy(p3, beststart2); VectorCopy(v3, bestend1); VectorCopy(v3, bestend2); - } //end if + } // end if founddist = qtrue; - } //end else if - if (VectorBetweenVectors(p4, v1, v2)) - { + } // end else if + if (VectorBetweenVectors(p4, v1, v2)) { dist = VectorDistance(v4, p4); - if (dist > bestdist - 0.5 && dist < bestdist + 0.5) - { + if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { dist1 = VectorDistance(beststart1, p4); dist2 = VectorDistance(beststart2, p4); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(beststart1, beststart2)) VectorCopy(p4, beststart2); - } //end if - else - { - if (dist2 > VectorDistance(beststart1, beststart2)) VectorCopy(p4, beststart1); - } //end else + if (dist1 > dist2) { + if (dist1 > VectorDistance(beststart1, beststart2)) + VectorCopy(p4, beststart2); + } // end if + else { + if (dist2 > VectorDistance(beststart1, beststart2)) + VectorCopy(p4, beststart1); + } // end else dist1 = VectorDistance(bestend1, v4); dist2 = VectorDistance(bestend2, v4); - if (dist1 > dist2) - { - if (dist1 > VectorDistance(bestend1, bestend2)) VectorCopy(v4, bestend2); - } //end if - else - { - if (dist2 > VectorDistance(bestend1, bestend2)) VectorCopy(v4, bestend1); - } //end else - } //end if - else if (dist < bestdist) - { + if (dist1 > dist2) { + if (dist1 > VectorDistance(bestend1, bestend2)) + VectorCopy(v4, bestend2); + } // end if + else { + if (dist2 > VectorDistance(bestend1, bestend2)) + VectorCopy(v4, bestend1); + } // end else + } // end if + else if (dist < bestdist) { bestdist = dist; VectorCopy(p4, beststart1); VectorCopy(p4, beststart2); VectorCopy(v4, bestend1); VectorCopy(v4, bestend2); - } //end if + } // end if founddist = qtrue; - } //end else if - //if no shortest distance was found the shortest distance - //is between one of the vertexes of edge1 and one of edge2 - if (!founddist) - { + } // end else if + // if no shortest distance was found the shortest distance + // is between one of the vertexes of edge1 and one of edge2 + if (!founddist) { dist = VectorDistance(v1, v3); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart1); VectorCopy(v1, beststart2); VectorCopy(v3, bestend1); VectorCopy(v3, bestend2); - } //end if + } // end if dist = VectorDistance(v1, v4); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart1); VectorCopy(v1, beststart2); VectorCopy(v4, bestend1); VectorCopy(v4, bestend2); - } //end if + } // end if dist = VectorDistance(v2, v3); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart1); VectorCopy(v2, beststart2); VectorCopy(v3, bestend1); VectorCopy(v3, bestend2); - } //end if + } // end if dist = VectorDistance(v2, v4); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart1); VectorCopy(v2, beststart2); VectorCopy(v4, bestend1); VectorCopy(v4, bestend2); - } //end if - } //end if + } // end if + } // end if return bestdist; -} //end of the function AAS_ClosestEdgePoints +} // end of the function AAS_ClosestEdgePoints //=========================================================================== // creates possible jump reachabilities between the areas // @@ -2107,8 +1993,7 @@ float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_Jump(int area1num, int area2num) -{ +int AAS_Reachability_Jump(int area1num, int area2num) { int i, j, k, l, face1num, face2num, edge1num, edge2num, traveltype; int stopevent, areas[10], numareas; float phys_jumpvel, maxjumpdistance, maxjumpheight, height, bestdist, speed; @@ -2123,100 +2008,96 @@ int AAS_Reachability_Jump(int area1num, int area2num) aas_clientmove_t move; aas_lreachability_t *lreach; - if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) return qfalse; - //cannot jump from or to a crouch area - if (AAS_AreaCrouch(area1num) || AAS_AreaCrouch(area2num)) return qfalse; + if (!AAS_AreaGrounded(area1num) || !AAS_AreaGrounded(area2num)) + return qfalse; + // cannot jump from or to a crouch area + if (AAS_AreaCrouch(area1num) || AAS_AreaCrouch(area2num)) + return qfalse; // area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; // phys_jumpvel = aassettings.phys_jumpvel; - //maximum distance a player can jump + // maximum distance a player can jump maxjumpdistance = 2 * AAS_MaxJumpDistance(phys_jumpvel); - //maximum height a player can jump with the given initial z velocity + // maximum height a player can jump with the given initial z velocity maxjumpheight = AAS_MaxJumpHeight(phys_jumpvel); - //if the areas are not near anough in the x-y direction - for (i = 0; i < 2; i++) - { - if (area1->mins[i] > area2->maxs[i] + maxjumpdistance) return qfalse; - if (area1->maxs[i] < area2->mins[i] - maxjumpdistance) return qfalse; - } //end for - //if area2 is way to high to jump up to - if (area2->mins[2] > area1->maxs[2] + maxjumpheight) return qfalse; + // if the areas are not near anough in the x-y direction + for (i = 0; i < 2; i++) { + if (area1->mins[i] > area2->maxs[i] + maxjumpdistance) + return qfalse; + if (area1->maxs[i] < area2->mins[i] - maxjumpdistance) + return qfalse; + } // end for + // if area2 is way to high to jump up to + if (area2->mins[2] > area1->maxs[2] + maxjumpheight) + return qfalse; // bestdist = 999999; // - for (i = 0; i < area1->numfaces; i++) - { + for (i = 0; i < area1->numfaces; i++) { face1num = aasworld.faceindex[area1->firstface + i]; face1 = &aasworld.faces[abs(face1num)]; - //if not a ground face - if (!(face1->faceflags & FACE_GROUND)) continue; + // if not a ground face + if (!(face1->faceflags & FACE_GROUND)) + continue; // - for (j = 0; j < area2->numfaces; j++) - { + for (j = 0; j < area2->numfaces; j++) { face2num = aasworld.faceindex[area2->firstface + j]; face2 = &aasworld.faces[abs(face2num)]; - //if not a ground face - if (!(face2->faceflags & FACE_GROUND)) continue; + // if not a ground face + if (!(face2->faceflags & FACE_GROUND)) + continue; // - for (k = 0; k < face1->numedges; k++) - { + for (k = 0; k < face1->numedges; k++) { edge1num = abs(aasworld.edgeindex[face1->firstedge + k]); edge1 = &aasworld.edges[edge1num]; - for (l = 0; l < face2->numedges; l++) - { + for (l = 0; l < face2->numedges; l++) { edge2num = abs(aasworld.edgeindex[face2->firstedge + l]); edge2 = &aasworld.edges[edge2num]; - //calculate the minimum distance between the two edges + // calculate the minimum distance between the two edges v1 = aasworld.vertexes[edge1->v[0]]; v2 = aasworld.vertexes[edge1->v[1]]; v3 = aasworld.vertexes[edge2->v[0]]; v4 = aasworld.vertexes[edge2->v[1]]; - //get the ground planes + // get the ground planes plane1 = &aasworld.planes[face1->planenum]; plane2 = &aasworld.planes[face2->planenum]; // - bestdist = AAS_ClosestEdgePoints(v1, v2, v3, v4, plane1, plane2, - beststart, bestend, - beststart2, bestend2, bestdist); - } //end for - } //end for - } //end for - } //end for + bestdist = AAS_ClosestEdgePoints(v1, v2, v3, v4, plane1, plane2, beststart, bestend, beststart2, bestend2, bestdist); + } // end for + } // end for + } // end for + } // end for VectorMiddle(beststart, beststart2, beststart); VectorMiddle(bestend, bestend2, bestend); - if (bestdist > 4 && bestdist < maxjumpdistance) - { -// Log_Write("shortest distance between %d and %d is %f\r\n", area1num, area2num, bestdist); + if (bestdist > 4 && bestdist < maxjumpdistance) { + // Log_Write("shortest distance between %d and %d is %f\r\n", area1num, area2num, bestdist); // if very close and almost no height difference then the bot can walk - if (bestdist <= 48 && fabs(beststart[2] - bestend[2]) < 8) - { + if (bestdist <= 48 && fabs(beststart[2] - bestend[2]) < 8) { speed = 400; traveltype = TRAVEL_WALKOFFLEDGE; - } //end if - else if (AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed)) - { - //FIXME: why multiply with 1.2??? + } // end if + else if (AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed)) { + // FIXME: why multiply with 1.2??? speed *= 1.2f; traveltype = TRAVEL_WALKOFFLEDGE; - } //end else if - else - { - //get the horizontal speed for the jump, if it isn't possible to calculate this - //speed (the jump is not possible) then there's no jump reachability created + } // end else if + else { + // get the horizontal speed for the jump, if it isn't possible to calculate this + // speed (the jump is not possible) then there's no jump reachability created if (!AAS_HorizontalVelocityForJump(phys_jumpvel, beststart, bestend, &speed)) return qfalse; speed *= 1.05f; traveltype = TRAVEL_JUMP; // - //NOTE: test if the horizontal distance isn't too small + // NOTE: test if the horizontal distance isn't too small VectorSubtract(bestend, beststart, dir); dir[2] = 0; if (VectorLength(dir) < 10) return qfalse; - } //end if + } // end if // VectorSubtract(bestend, beststart, dir); VectorNormalize(dir); @@ -2228,20 +2109,17 @@ int AAS_Reachability_Jump(int area1num, int area2num) // if (trace.startsolid) return qfalse; - if (trace.fraction < 1) - { + if (trace.fraction < 1) { plane = &aasworld.planes[trace.planenum]; // if the bot can stand on the surface - if (DotProduct(plane->normal, up) >= 0.7) - { + if (DotProduct(plane->normal, up) >= 0.7) { // if no lava or slime below - if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA|CONTENTS_SLIME))) - { + if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA | CONTENTS_SLIME))) { if (teststart[2] - trace.endpos[2] <= aassettings.phys_maxbarrier) return qfalse; - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if // VectorMA(bestend, -1, dir, teststart); // @@ -2251,20 +2129,17 @@ int AAS_Reachability_Jump(int area1num, int area2num) // if (trace.startsolid) return qfalse; - if (trace.fraction < 1) - { + if (trace.fraction < 1) { plane = &aasworld.planes[trace.planenum]; // if the bot can stand on the surface - if (DotProduct(plane->normal, up) >= 0.7) - { + if (DotProduct(plane->normal, up) >= 0.7) { // if no lava or slime below - if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA|CONTENTS_SLIME))) - { + if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA | CONTENTS_SLIME))) { if (teststart[2] - trace.endpos[2] <= aassettings.phys_maxbarrier) return qfalse; - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if // // get command movement VectorClear(cmdmove); @@ -2278,12 +2153,11 @@ int AAS_Reachability_Jump(int area1num, int area2num) VectorNormalize(dir); CrossProduct(dir, up, sidewards); // - stopevent = SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE; + stopevent = SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE; if (!AAS_AreaClusterPortal(area1num) && !AAS_AreaClusterPortal(area2num)) stopevent |= SE_TOUCHCLUSTERPORTAL; // - for (i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { // if (i == 1) VectorAdd(testend, sidewards, testend); @@ -2296,41 +2170,39 @@ int AAS_Reachability_Jump(int area1num, int area2num) VectorNormalize(dir); VectorScale(dir, speed, velocity); // - AAS_PredictClientMovement(&move, -1, beststart, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 3, 30, 0.1f, - stopevent, 0, qfalse); + AAS_PredictClientMovement(&move, -1, beststart, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 3, 30, 0.1f, stopevent, 0, qfalse); // if prediction time wasn't enough to fully predict the movement if (move.frames >= 30) return qfalse; // don't enter slime or lava and don't fall from too high - if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA)) + if (move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA)) return qfalse; // never jump or fall through a cluster portal if (move.stopevent & SE_TOUCHCLUSTERPORTAL) return qfalse; - //the end position should be in area2, also test a little bit back - //because the predicted jump could have rushed through the area + // the end position should be in area2, also test a little bit back + // because the predicted jump could have rushed through the area VectorMA(move.endpos, -64, dir, teststart); teststart[2] += 1; numareas = AAS_TraceAreas(move.endpos, teststart, areas, NULL, ARRAY_LEN(areas)); - for (j = 0; j < numareas; j++) - { + for (j = 0; j < numareas; j++) { if (areas[j] == area2num) break; - } //end for + } // end for if (j < numareas) break; } if (i >= 3) return qfalse; - // + // #ifdef REACH_DEBUG - //create the reachability + // create the reachability Log_Write("jump reachability between %d and %d\r\n", area1num, area2num); -#endif //REACH_DEBUG - //create a new reachability link +#endif // REACH_DEBUG + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; @@ -2341,26 +2213,20 @@ int AAS_Reachability_Jump(int area1num, int area2num) VectorSubtract(bestend, beststart, dir); height = dir[2]; dir[2] = 0; - if ((traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE && height > VectorLength(dir)) - { + if ((traveltype & TRAVELTYPE_MASK) == TRAVEL_WALKOFFLEDGE && height > VectorLength(dir)) { lreach->traveltime = aassettings.rs_startwalkoffledge + height * 50 / aassettings.phys_gravity; - } - else - { + } else { lreach->traveltime = aassettings.rs_startjump + VectorDistance(bestend, beststart) * 240 / aassettings.phys_maxwalkvelocity; - } //end if + } // end if // - if (!AAS_AreaJumpPad(area2num)) - { - if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta5) - { + if (!AAS_AreaJumpPad(area2num)) { + if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta5) { lreach->traveltime += aassettings.rs_falldamage5; - } //end if - else if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta10) - { + } // end if + else if (AAS_FallDelta(beststart[2] - bestend[2]) > aassettings.phys_falldelta10) { lreach->traveltime += aassettings.rs_falldamage10; - } //end if - } //end if + } // end if + } // end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // @@ -2368,9 +2234,9 @@ int AAS_Reachability_Jump(int area1num, int area2num) reach_jump++; else reach_walkoffledge++; - } //end if + } // end if return qfalse; -} //end of the function AAS_Reachability_Jump +} // end of the function AAS_Reachability_Jump //=========================================================================== // create a possible ladder reachability from area1 to area2 // @@ -2378,8 +2244,7 @@ int AAS_Reachability_Jump(int area1num, int area2num) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_Ladder(int area1num, int area2num) -{ +int AAS_Reachability_Ladder(int area1num, int area2num) { int i, j, k, l, edge1num, edge2num, sharededgenum = 0, lowestedgenum = 0; int face1num, face2num, ladderface1num = 0, ladderface2num = 0; int ladderface1vertical, ladderface2vertical, firstv; @@ -2394,42 +2259,39 @@ int AAS_Reachability_Ladder(int area1num, int area2num) aas_lreachability_t *lreach; aas_trace_t trace; - if (!AAS_AreaLadder(area1num) || !AAS_AreaLadder(area2num)) return qfalse; + if (!AAS_AreaLadder(area1num) || !AAS_AreaLadder(area2num)) + return qfalse; // phys_jumpvel = aassettings.phys_jumpvel; - //maximum height a player can jump with the given initial z velocity + // maximum height a player can jump with the given initial z velocity maxjumpheight = AAS_MaxJumpHeight(phys_jumpvel); area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - for (i = 0; i < area1->numfaces; i++) - { + for (i = 0; i < area1->numfaces; i++) { face1num = aasworld.faceindex[area1->firstface + i]; face1 = &aasworld.faces[abs(face1num)]; - //if not a ladder face - if (!(face1->faceflags & FACE_LADDER)) continue; + // if not a ladder face + if (!(face1->faceflags & FACE_LADDER)) + continue; // - for (j = 0; j < area2->numfaces; j++) - { + for (j = 0; j < area2->numfaces; j++) { face2num = aasworld.faceindex[area2->firstface + j]; face2 = &aasworld.faces[abs(face2num)]; - //if not a ladder face - if (!(face2->faceflags & FACE_LADDER)) continue; - //check if the faces share an edge - for (k = 0; k < face1->numedges; k++) - { + // if not a ladder face + if (!(face2->faceflags & FACE_LADDER)) + continue; + // check if the faces share an edge + for (k = 0; k < face1->numedges; k++) { edge1num = aasworld.edgeindex[face1->firstedge + k]; - for (l = 0; l < face2->numedges; l++) - { + for (l = 0; l < face2->numedges; l++) { edge2num = aasworld.edgeindex[face2->firstedge + l]; - if (abs(edge1num) == abs(edge2num)) - { - //get the face with the largest area + if (abs(edge1num) == abs(edge2num)) { + // get the face with the largest area face1area = AAS_FaceArea(face1); face2area = AAS_FaceArea(face2); - if (face1area > bestface1area && face2area > bestface2area) - { + if (face1area > bestface1area && face2area > bestface2area) { bestface1area = face1area; bestface2area = face2area; ladderface1 = face1; @@ -2437,18 +2299,18 @@ int AAS_Reachability_Ladder(int area1num, int area2num) ladderface1num = face1num; ladderface2num = face2num; sharededgenum = edge1num; - } //end if + } // end if break; - } //end if - } //end for - if (l != face2->numedges) break; - } //end for - } //end for - } //end for + } // end if + } // end for + if (l != face2->numedges) + break; + } // end for + } // end for + } // end for // - if (ladderface1 && ladderface2) - { - //get the middle of the shared edge + if (ladderface1 && ladderface2) { + // get the middle of the shared edge sharededge = &aasworld.edges[abs(sharededgenum)]; firstv = sharededgenum < 0; // @@ -2458,37 +2320,39 @@ int AAS_Reachability_Ladder(int area1num, int area2num) VectorScale(area1point, 0.5, area1point); VectorCopy(area1point, area2point); // - //if the face plane in area 1 is pretty much vertical + // if the face plane in area 1 is pretty much vertical plane1 = &aasworld.planes[ladderface1->planenum ^ (ladderface1num < 0)]; plane2 = &aasworld.planes[ladderface2->planenum ^ (ladderface2num < 0)]; // - //get the points really into the areas + // get the points really into the areas VectorSubtract(v2, v1, sharededgevec); CrossProduct(plane1->normal, sharededgevec, dir); VectorNormalize(dir); - //NOTE: 32 because that's larger than 16 (bot bbox x,y) + // NOTE: 32 because that's larger than 16 (bot bbox x,y) VectorMA(area1point, -32, dir, area1point); VectorMA(area2point, 32, dir, area2point); // ladderface1vertical = fabs(DotProduct(plane1->normal, up)) < 0.1; ladderface2vertical = fabs(DotProduct(plane2->normal, up)) < 0.1; - //there's only reachability between vertical ladder faces - if (!ladderface1vertical && !ladderface2vertical) return qfalse; - //if both vertical ladder faces - if (ladderface1vertical && ladderface2vertical - //and the ladder faces do not make a sharp corner - && DotProduct(plane1->normal, plane2->normal) > 0.7 - //and the shared edge is not too vertical - && fabs(DotProduct(sharededgevec, up)) < 0.7) - { - //create a new reachability link + // there's only reachability between vertical ladder faces + if (!ladderface1vertical && !ladderface2vertical) + return qfalse; + // if both vertical ladder faces + if (ladderface1vertical && + ladderface2vertical + // and the ladder faces do not make a sharp corner + && DotProduct(plane1->normal, plane2->normal) > 0.7 + // and the shared edge is not too vertical + && fabs(DotProduct(sharededgevec, up)) < 0.7) { + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = abs(sharededgenum); VectorCopy(area1point, lreach->start); - //VectorCopy(area2point, lreach->end); + // VectorCopy(area2point, lreach->end); VectorMA(area2point, -3, plane1->normal, lreach->end); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; @@ -2496,14 +2360,15 @@ int AAS_Reachability_Ladder(int area1num, int area2num) areareachability[area1num] = lreach; // reach_ladder++; - //create a new reachability link + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area1num; lreach->facenum = ladderface2num; lreach->edgenum = abs(sharededgenum); VectorCopy(area2point, lreach->start); - //VectorCopy(area1point, lreach->end); + // VectorCopy(area1point, lreach->end); VectorMA(area1point, -3, plane1->normal, lreach->end); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; @@ -2513,15 +2378,15 @@ int AAS_Reachability_Ladder(int area1num, int area2num) reach_ladder++; // return qtrue; - } //end if - //if the second ladder face is also a ground face - //create ladder end (just ladder) reachability and - //walk off a ladder (ledge) reachability - if (ladderface1vertical && (ladderface2->faceflags & FACE_GROUND)) - { - //create a new reachability link + } // end if + // if the second ladder face is also a ground face + // create ladder end (just ladder) reachability and + // walk off a ladder (ledge) reachability + if (ladderface1vertical && (ladderface2->faceflags & FACE_GROUND)) { + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = abs(sharededgenum); @@ -2535,9 +2400,10 @@ int AAS_Reachability_Ladder(int area1num, int area2num) areareachability[area1num] = lreach; // reach_ladder++; - //create a new reachability link + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area1num; lreach->facenum = ladderface2num; lreach->edgenum = abs(sharededgenum); @@ -2551,14 +2417,12 @@ int AAS_Reachability_Ladder(int area1num, int area2num) reach_walkoffledge++; // return qtrue; - } //end if + } // end if // - if (ladderface1vertical) - { - //find lowest edge of the ladder face + if (ladderface1vertical) { + // find lowest edge of the ladder face lowestpoint[2] = 99999; - for (i = 0; i < ladderface1->numedges; i++) - { + for (i = 0; i < ladderface1->numedges; i++) { edge1num = abs(aasworld.edgeindex[ladderface1->firstedge + i]); edge1 = &aasworld.edges[edge1num]; // @@ -2568,57 +2432,52 @@ int AAS_Reachability_Ladder(int area1num, int area2num) VectorAdd(v1, v2, mid); VectorScale(mid, 0.5, mid); // - if (mid[2] < lowestpoint[2]) - { + if (mid[2] < lowestpoint[2]) { VectorCopy(mid, lowestpoint); lowestedgenum = edge1num; - } //end if - } //end for + } // end if + } // end for // plane1 = &aasworld.planes[ladderface1->planenum]; - //trace down in the middle of this edge + // trace down in the middle of this edge VectorMA(lowestpoint, 5, plane1->normal, start); VectorCopy(start, end); start[2] += 5; end[2] -= 100; - //trace without entity collision + // trace without entity collision trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1); // // #ifdef REACH_DEBUG - if (trace.startsolid) - { + if (trace.startsolid) { Log_Write("trace from area %d started in solid\r\n", area1num); - } //end if -#endif //REACH_DEBUG - // + } // end if +#endif // REACH_DEBUG + // trace.endpos[2] += 1; area2num = AAS_PointAreaNum(trace.endpos); // area2 = &aasworld.areas[area2num]; - for (i = 0; i < area2->numfaces; i++) - { + for (i = 0; i < area2->numfaces; i++) { face2num = aasworld.faceindex[area2->firstface + i]; face2 = &aasworld.faces[abs(face2num)]; // - if (face2->faceflags & FACE_LADDER) - { + if (face2->faceflags & FACE_LADDER) { plane2 = &aasworld.planes[face2->planenum]; - if (fabs(DotProduct(plane2->normal, up)) < 0.1) break; - } //end if - } //end for - //if from another area without vertical ladder faces + if (fabs(DotProduct(plane2->normal, up)) < 0.1) + break; + } // end if + } // end for + // if from another area without vertical ladder faces if (i >= area2->numfaces && area2num != area1num && - //the reachabilities shouldn't exist already - !AAS_ReachabilityExists(area1num, area2num) && - !AAS_ReachabilityExists(area2num, area1num)) - { - //if the height is jumpable - if (start[2] - trace.endpos[2] < maxjumpheight) - { - //create a new reachability link + // the reachabilities shouldn't exist already + !AAS_ReachabilityExists(area1num, area2num) && !AAS_ReachabilityExists(area2num, area1num)) { + // if the height is jumpable + if (start[2] - trace.endpos[2] < maxjumpheight) { + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = lowestedgenum; @@ -2630,16 +2489,17 @@ int AAS_Reachability_Ladder(int area1num, int area2num) areareachability[area1num] = lreach; // reach_ladder++; - //create a new reachability link + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area1num; lreach->facenum = ladderface1num; lreach->edgenum = lowestedgenum; VectorCopy(trace.endpos, lreach->start); - //get the end point a little bit into the ladder + // get the end point a little bit into the ladder VectorMA(lowestpoint, -5, plane1->normal, lreach->end); - //get the end point a little higher + // get the end point a little higher lreach->end[2] += 10; lreach->traveltype = TRAVEL_JUMP; lreach->traveltime = 10; @@ -2651,12 +2511,13 @@ int AAS_Reachability_Ladder(int area1num, int area2num) return qtrue; #ifdef REACH_DEBUG Log_Write("jump up to ladder reach between %d and %d\r\n", area2num, area1num); -#endif //REACH_DEBUG - } //end if +#endif // REACH_DEBUG + } // end if #ifdef REACH_DEBUG - else Log_Write("jump too high between area %d and %d\r\n", area2num, area1num); -#endif //REACH_DEBUG - } //end if + else + Log_Write("jump too high between area %d and %d\r\n", area2num, area1num); +#endif // REACH_DEBUG + } // end if /*//if slime or lava below the ladder //try jump reachability from far towards the ladder if (aasworld.areasettings[area2num].contents & (AREACONTENTS_SLIME @@ -2702,18 +2563,17 @@ int AAS_Reachability_Ladder(int area1num, int area2num) break; } //end for } //end if*/ - } //end if - } //end if + } // end if + } // end if return qfalse; -} //end of the function AAS_Reachability_Ladder +} // end of the function AAS_Reachability_Ladder //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_TravelFlagsForTeam(int ent) -{ +int AAS_TravelFlagsForTeam(int ent) { int notteam; if (!AAS_IntForBSPEpairKey(ent, "bot_notteam", ¬team)) @@ -2723,7 +2583,7 @@ int AAS_TravelFlagsForTeam(int ent) if (notteam == 2) return TRAVELFLAG_NOTTEAM2; return 0; -} //end of the function AAS_TravelFlagsForTeam +} // end of the function AAS_TravelFlagsForTeam //=========================================================================== // create possible teleporter reachabilities // this is very game dependent.... :( @@ -2742,8 +2602,7 @@ int AAS_TravelFlagsForTeam(int ent) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Reachability_Teleport(void) -{ +void AAS_Reachability_Teleport(void) { int area1num, area2num; char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY]; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; @@ -2756,103 +2615,86 @@ void AAS_Reachability_Teleport(void) aas_trace_t trace; aas_link_t *areas, *link; - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (!strcmp(classname, "trigger_multiple")) - { + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (!strcmp(classname, "trigger_multiple")) { AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY); -//#ifdef REACH_DEBUG + //#ifdef REACH_DEBUG botimport.Print(PRT_MESSAGE, "trigger_multiple model = \"%s\"\n", model); -//#endif REACH_DEBUG + //#endif REACH_DEBUG VectorClear(angles); - AAS_BSPModelMinsMaxsOrigin(atoi(model+1), angles, mins, maxs, origin); + AAS_BSPModelMinsMaxsOrigin(atoi(model + 1), angles, mins, maxs, origin); // - if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY)) - { - botimport.Print(PRT_ERROR, "trigger_multiple at %1.0f %1.0f %1.0f without target\n", - origin[0], origin[1], origin[2]); + if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY)) { + botimport.Print(PRT_ERROR, "trigger_multiple at %1.0f %1.0f %1.0f without target\n", origin[0], origin[1], origin[2]); continue; - } //end if - for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest)) - { - if (!AAS_ValueForBSPEpairKey(dest, "classname", classname, MAX_EPAIRKEY)) continue; - if (!strcmp(classname, "target_teleporter")) - { - if (!AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY)) continue; - if (!strcmp(targetname, target)) - { + } // end if + for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest)) { + if (!AAS_ValueForBSPEpairKey(dest, "classname", classname, MAX_EPAIRKEY)) + continue; + if (!strcmp(classname, "target_teleporter")) { + if (!AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY)) + continue; + if (!strcmp(targetname, target)) { break; - } //end if - } //end if - } //end for - if (!dest) - { + } // end if + } // end if + } // end for + if (!dest) { continue; - } //end if - if (!AAS_ValueForBSPEpairKey(dest, "target", target, MAX_EPAIRKEY)) - { + } // end if + if (!AAS_ValueForBSPEpairKey(dest, "target", target, MAX_EPAIRKEY)) { botimport.Print(PRT_ERROR, "target_teleporter without target\n"); continue; - } //end if - } //end else - else if (!strcmp(classname, "trigger_teleport")) - { + } // end if + } // end else + else if (!strcmp(classname, "trigger_teleport")) { AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY); -//#ifdef REACH_DEBUG + //#ifdef REACH_DEBUG botimport.Print(PRT_MESSAGE, "trigger_teleport model = \"%s\"\n", model); -//#endif REACH_DEBUG + //#endif REACH_DEBUG VectorClear(angles); - AAS_BSPModelMinsMaxsOrigin(atoi(model+1), angles, mins, maxs, origin); + AAS_BSPModelMinsMaxsOrigin(atoi(model + 1), angles, mins, maxs, origin); // - if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY)) - { - botimport.Print(PRT_ERROR, "trigger_teleport at %1.0f %1.0f %1.0f without target\n", - origin[0], origin[1], origin[2]); + if (!AAS_ValueForBSPEpairKey(ent, "target", target, MAX_EPAIRKEY)) { + botimport.Print(PRT_ERROR, "trigger_teleport at %1.0f %1.0f %1.0f without target\n", origin[0], origin[1], origin[2]); continue; - } //end if - } //end if - else - { + } // end if + } // end if + else { continue; - } //end else + } // end else // - for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest)) - { - //classname should be misc_teleporter_dest - //but I've also seen target_position and actually any - //entity could be used... burp - if (AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY)) - { - if (!strcmp(targetname, target)) - { + for (dest = AAS_NextBSPEntity(0); dest; dest = AAS_NextBSPEntity(dest)) { + // classname should be misc_teleporter_dest + // but I've also seen target_position and actually any + // entity could be used... burp + if (AAS_ValueForBSPEpairKey(dest, "targetname", targetname, MAX_EPAIRKEY)) { + if (!strcmp(targetname, target)) { break; - } //end if - } //end if - } //end for - if (!dest) - { + } // end if + } // end if + } // end for + if (!dest) { botimport.Print(PRT_ERROR, "teleporter without misc_teleporter_dest (%s)\n", target); continue; - } //end if - if (!AAS_VectorForBSPEpairKey(dest, "origin", destorigin)) - { + } // end if + if (!AAS_VectorForBSPEpairKey(dest, "origin", destorigin)) { botimport.Print(PRT_ERROR, "teleporter destination (%s) without origin\n", target); continue; - } //end if + } // end if // area2num = AAS_PointAreaNum(destorigin); - //if not teleported into a teleporter or into a jumppad - if (!AAS_AreaTeleporter(area2num) && !AAS_AreaJumpPad(area2num)) - { + // if not teleported into a teleporter or into a jumppad + if (!AAS_AreaTeleporter(area2num) && !AAS_AreaJumpPad(area2num)) { VectorCopy(destorigin, end); end[2] -= 64; trace = AAS_TraceClientBBox(destorigin, end, PRESENCE_CROUCH, -1); - if (trace.startsolid) - { + if (trace.startsolid) { botimport.Print(PRT_ERROR, "teleporter destination (%s) in solid\n", target); continue; - } //end if + } // end if /* area2num = AAS_PointAreaNum(trace.endpos); // @@ -2864,53 +2706,52 @@ void AAS_Reachability_Teleport(void) } else*/ { - //predict where you'll end up + // predict where you'll end up AAS_FloatForBSPEpairKey(dest, "angle", &angle); - if (angle) - { + if (angle) { VectorSet(angles, 0, angle, 0); AngleVectors(angles, velocity, NULL, NULL); VectorScale(velocity, 400, velocity); - } //end if - else - { + } // end if + else { VectorClear(velocity); - } //end else + } // end else VectorClear(cmdmove); - AAS_PredictClientMovement(&move, -1, destorigin, PRESENCE_NORMAL, qfalse, - velocity, cmdmove, 0, 30, 0.1f, - SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER, 0, qfalse); //qtrue); + AAS_PredictClientMovement(&move, -1, destorigin, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 0, 30, 0.1f, + SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | + SE_TOUCHTELEPORTER, + 0, qfalse); // qtrue); area2num = AAS_PointAreaNum(move.endpos); - if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA)) - { + if (move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA)) { botimport.Print(PRT_WARNING, "teleported into slime or lava at dest %s\n", target); - } //end if + } // end if VectorCopy(move.endpos, destorigin); - } //end else - } //end if + } // end else + } // end if // - //botimport.Print(PRT_MESSAGE, "teleporter brush origin at %f %f %f\n", origin[0], origin[1], origin[2]); - //botimport.Print(PRT_MESSAGE, "teleporter brush mins = %f %f %f\n", mins[0], mins[1], mins[2]); - //botimport.Print(PRT_MESSAGE, "teleporter brush maxs = %f %f %f\n", maxs[0], maxs[1], maxs[2]); + // botimport.Print(PRT_MESSAGE, "teleporter brush origin at %f %f %f\n", origin[0], origin[1], origin[2]); + // botimport.Print(PRT_MESSAGE, "teleporter brush mins = %f %f %f\n", mins[0], mins[1], mins[2]); + // botimport.Print(PRT_MESSAGE, "teleporter brush maxs = %f %f %f\n", maxs[0], maxs[1], maxs[2]); VectorAdd(origin, mins, mins); VectorAdd(origin, maxs, maxs); // VectorAdd(mins, maxs, mid); VectorScale(mid, 0.5, mid); - //link an invalid (-1) entity + // link an invalid (-1) entity areas = AAS_LinkEntityClientBBox(mins, maxs, -1, PRESENCE_CROUCH); - if (!areas) botimport.Print(PRT_MESSAGE, "trigger_multiple not in any area\n"); + if (!areas) + botimport.Print(PRT_MESSAGE, "trigger_multiple not in any area\n"); // - for (link = areas; link; link = link->next_area) - { - //if (!AAS_AreaGrounded(link->areanum)) continue; - if (!AAS_AreaTeleporter(link->areanum)) continue; + for (link = areas; link; link = link->next_area) { + // if (!AAS_AreaGrounded(link->areanum)) continue; + if (!AAS_AreaTeleporter(link->areanum)) + continue; // area1num = link->areanum; - //create a new reachability link + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) break; + if (!lreach) + break; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; @@ -2923,11 +2764,11 @@ void AAS_Reachability_Teleport(void) areareachability[area1num] = lreach; // reach_teleport++; - } //end for - //unlink the invalid entity + } // end for + // unlink the invalid entity AAS_UnlinkFromAreas(areas); - } //end for -} //end of the function AAS_Reachability_Teleport + } // end for +} // end of the function AAS_Reachability_Teleport //=========================================================================== // create possible elevator (func_plat) reachabilities // this is very game dependent.... :( @@ -2936,8 +2777,7 @@ void AAS_Reachability_Teleport(void) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Reachability_Elevator(void) -{ +void AAS_Reachability_Elevator(void) { int area1num, area2num, modelnum, i, j, k, l, n, p; float lip, height, speed; char model[MAX_EPAIRKEY], classname[MAX_EPAIRKEY]; @@ -2951,53 +2791,53 @@ void AAS_Reachability_Elevator(void) #ifdef REACH_DEBUG Log_Write("AAS_Reachability_Elevator\r\n"); -#endif //REACH_DEBUG - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (!strcmp(classname, "func_plat")) - { +#endif // REACH_DEBUG + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (!strcmp(classname, "func_plat")) { #ifdef REACH_DEBUG Log_Write("found func plat\r\n"); -#endif //REACH_DEBUG - if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) - { +#endif // REACH_DEBUG + if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) { botimport.Print(PRT_ERROR, "func_plat without model\n"); continue; - } //end if - //get the model number, and skip the leading * - modelnum = atoi(model+1); - if (modelnum <= 0) - { + } // end if + // get the model number, and skip the leading * + modelnum = atoi(model + 1); + if (modelnum <= 0) { botimport.Print(PRT_ERROR, "func_plat with invalid model number\n"); continue; - } //end if - //get the mins, maxs and origin of the model - //NOTE: the origin is usually (0,0,0) and the mins and maxs - // are the absolute mins and maxs + } // end if + // get the mins, maxs and origin of the model + // NOTE: the origin is usually (0,0,0) and the mins and maxs + // are the absolute mins and maxs AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin); // AAS_VectorForBSPEpairKey(ent, "origin", origin); - //pos1 is the top position, pos2 is the bottom + // pos1 is the top position, pos2 is the bottom VectorCopy(origin, pos1); VectorCopy(origin, pos2); - //get the lip of the plat + // get the lip of the plat AAS_FloatForBSPEpairKey(ent, "lip", &lip); - if (!lip) lip = 8; - //get the movement height of the plat + if (!lip) + lip = 8; + // get the movement height of the plat AAS_FloatForBSPEpairKey(ent, "height", &height); - if (!height) height = (maxs[2] - mins[2]) - lip; - //get the speed of the plat + if (!height) + height = (maxs[2] - mins[2]) - lip; + // get the speed of the plat AAS_FloatForBSPEpairKey(ent, "speed", &speed); - if (!speed) speed = 200; - //get bottom position below pos1 + if (!speed) + speed = 200; + // get bottom position below pos1 pos2[2] -= height; // - //get a point just above the plat in the bottom position + // get a point just above the plat in the bottom position VectorAdd(mins, maxs, mids); VectorMA(pos2, 0.5, mids, platbottom); platbottom[2] = maxs[2] - (pos1[2] - pos2[2]) + 2; - //get a point just above the plat in the top position + // get a point just above the plat in the top position VectorAdd(mins, maxs, mids); VectorMA(pos2, 0.5, mids, plattop); plattop[2] = maxs[2] + 2; @@ -3007,105 +2847,125 @@ void AAS_Reachability_Elevator(void) Log_Write("no grounded area near plat bottom\r\n"); continue; } //end if*/ - //get the mins and maxs a little larger - for (i = 0; i < 3; i++) - { + // get the mins and maxs a little larger + for (i = 0; i < 3; i++) { mins[i] -= 1; maxs[i] += 1; - } //end for + } // end for // - //botimport.Print(PRT_MESSAGE, "platbottom[2] = %1.1f plattop[2] = %1.1f\n", platbottom[2], plattop[2]); + // botimport.Print(PRT_MESSAGE, "platbottom[2] = %1.1f plattop[2] = %1.1f\n", platbottom[2], plattop[2]); // VectorAdd(mins, maxs, mids); VectorScale(mids, 0.5, mids); // - xvals[0] = mins[0]; xvals[1] = mids[0]; xvals[2] = maxs[0]; xvals[3] = mids[0]; - yvals[0] = mids[1]; yvals[1] = maxs[1]; yvals[2] = mids[1]; yvals[3] = mins[1]; + xvals[0] = mins[0]; + xvals[1] = mids[0]; + xvals[2] = maxs[0]; + xvals[3] = mids[0]; + yvals[0] = mids[1]; + yvals[1] = maxs[1]; + yvals[2] = mids[1]; + yvals[3] = mins[1]; // - xvals[4] = mins[0]; xvals[5] = maxs[0]; xvals[6] = maxs[0]; xvals[7] = mins[0]; - yvals[4] = maxs[1]; yvals[5] = maxs[1]; yvals[6] = mins[1]; yvals[7] = mins[1]; - //find adjacent areas around the bottom of the plat - for (i = 0; i < 9; i++) - { - if (i < 8) //check at the sides of the plat + xvals[4] = mins[0]; + xvals[5] = maxs[0]; + xvals[6] = maxs[0]; + xvals[7] = mins[0]; + yvals[4] = maxs[1]; + yvals[5] = maxs[1]; + yvals[6] = mins[1]; + yvals[7] = mins[1]; + // find adjacent areas around the bottom of the plat + for (i = 0; i < 9; i++) { + if (i < 8) // check at the sides of the plat { bottomorg[0] = origin[0] + xvals[i]; bottomorg[1] = origin[1] + yvals[i]; bottomorg[2] = platbottom[2] + 16; - //get a grounded or swim area near the plat in the bottom position + // get a grounded or swim area near the plat in the bottom position area1num = AAS_PointAreaNum(bottomorg); - for (k = 0; k < 16; k++) - { - if (area1num) - { - if (AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) break; - } //end if + for (k = 0; k < 16; k++) { + if (area1num) { + if (AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) + break; + } // end if bottomorg[2] += 4; area1num = AAS_PointAreaNum(bottomorg); - } //end if - //if in solid - if (k >= 16) - { + } // end if + // if in solid + if (k >= 16) { continue; - } //end if - } //end if - else //at the middle of the plat + } // end if + } // end if + else // at the middle of the plat { VectorCopy(plattop, bottomorg); bottomorg[2] += 24; area1num = AAS_PointAreaNum(bottomorg); - if (!area1num) continue; + if (!area1num) + continue; VectorCopy(platbottom, bottomorg); bottomorg[2] += 24; - } //end else - //look at adjacent areas around the top of the plat - //make larger steps to outside the plat everytime - for (n = 0; n < 3; n++) - { - for (k = 0; k < 3; k++) - { + } // end else + // look at adjacent areas around the top of the plat + // make larger steps to outside the plat everytime + for (n = 0; n < 3; n++) { + for (k = 0; k < 3; k++) { mins[k] -= 4; maxs[k] += 4; - } //end for - xvals_top[0] = mins[0]; xvals_top[1] = mids[0]; xvals_top[2] = maxs[0]; xvals_top[3] = mids[0]; - yvals_top[0] = mids[1]; yvals_top[1] = maxs[1]; yvals_top[2] = mids[1]; yvals_top[3] = mins[1]; + } // end for + xvals_top[0] = mins[0]; + xvals_top[1] = mids[0]; + xvals_top[2] = maxs[0]; + xvals_top[3] = mids[0]; + yvals_top[0] = mids[1]; + yvals_top[1] = maxs[1]; + yvals_top[2] = mids[1]; + yvals_top[3] = mins[1]; // - xvals_top[4] = mins[0]; xvals_top[5] = maxs[0]; xvals_top[6] = maxs[0]; xvals_top[7] = mins[0]; - yvals_top[4] = maxs[1]; yvals_top[5] = maxs[1]; yvals_top[6] = mins[1]; yvals_top[7] = mins[1]; + xvals_top[4] = mins[0]; + xvals_top[5] = maxs[0]; + xvals_top[6] = maxs[0]; + xvals_top[7] = mins[0]; + yvals_top[4] = maxs[1]; + yvals_top[5] = maxs[1]; + yvals_top[6] = mins[1]; + yvals_top[7] = mins[1]; // - for (j = 0; j < 8; j++) - { + for (j = 0; j < 8; j++) { toporg[0] = origin[0] + xvals_top[j]; toporg[1] = origin[1] + yvals_top[j]; toporg[2] = plattop[2] + 16; - //get a grounded or swim area near the plat in the top position + // get a grounded or swim area near the plat in the top position area2num = AAS_PointAreaNum(toporg); - for (l = 0; l < 16; l++) - { - if (area2num) - { - if (AAS_AreaGrounded(area2num) || AAS_AreaSwim(area2num)) - { + for (l = 0; l < 16; l++) { + if (area2num) { + if (AAS_AreaGrounded(area2num) || AAS_AreaSwim(area2num)) { VectorCopy(plattop, start); start[2] += 32; VectorCopy(toporg, end); end[2] += 1; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - if (trace.fraction >= 1) break; - } //end if - } //end if + if (trace.fraction >= 1) + break; + } // end if + } // end if toporg[2] += 4; area2num = AAS_PointAreaNum(toporg); - } //end if - //if in solid - if (l >= 16) continue; - //never create a reachability in the same area - if (area2num == area1num) continue; - //if the area isn't grounded - if (!AAS_AreaGrounded(area2num)) continue; - //if there already exists reachability between the areas - if (AAS_ReachabilityExists(area1num, area2num)) continue; - //if the reachability start is within the elevator bounding box + } // end if + // if in solid + if (l >= 16) + continue; + // never create a reachability in the same area + if (area2num == area1num) + continue; + // if the area isn't grounded + if (!AAS_AreaGrounded(area2num)) + continue; + // if there already exists reachability between the areas + if (AAS_ReachabilityExists(area1num, area2num)) + continue; + // if the reachability start is within the elevator bounding box VectorSubtract(bottomorg, platbottom, dir); VectorNormalize(dir); dir[0] = bottomorg[0] + 24 * dir[0]; @@ -3113,16 +2973,19 @@ void AAS_Reachability_Elevator(void) dir[2] = bottomorg[2]; // for (p = 0; p < 3; p++) - if (dir[p] < origin[p] + mins[p] || dir[p] > origin[p] + maxs[p]) break; - if (p >= 3) continue; - //create a new reachability link + if (dir[p] < origin[p] + mins[p] || dir[p] > origin[p] + maxs[p]) + break; + if (p >= 3) + continue; + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) continue; + if (!lreach) + continue; lreach->areanum = area2num; - //the facenum is the model number + // the facenum is the model number lreach->facenum = modelnum; - //the edgenum is the height - lreach->edgenum = (int) height; + // the edgenum is the height + lreach->edgenum = (int)height; // VectorCopy(dir, lreach->start); VectorCopy(toporg, lreach->end); @@ -3131,28 +2994,27 @@ void AAS_Reachability_Elevator(void) lreach->traveltime = aassettings.rs_startelevator + height * 100 / speed; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; - //don't go any further to the outside + // don't go any further to the outside n = 9999; // #ifdef REACH_DEBUG Log_Write("elevator reach from %d to %d\r\n", area1num, area2num); -#endif //REACH_DEBUG - // +#endif // REACH_DEBUG + // reach_elevator++; - } //end for - } //end for - } //end for - } //end if - } //end for -} //end of the function AAS_Reachability_Elevator + } // end for + } // end for + } // end for + } // end if + } // end for +} // end of the function AAS_Reachability_Elevator //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_lreachability_t *AAS_FindFaceReachabilities(vec3_t *facepoints, int numpoints, aas_plane_t *plane, int towardsface) -{ +aas_lreachability_t *AAS_FindFaceReachabilities(vec3_t *facepoints, int numpoints, aas_plane_t *plane, int towardsface) { int i, j, k, l; int facenum, edgenum, bestfacenum; float *v1, *v2, *v3, *v4; @@ -3169,89 +3031,89 @@ aas_lreachability_t *AAS_FindFaceReachabilities(vec3_t *facepoints, int numpoint bestfacenum = 0; bestfaceplane = NULL; // - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { area = &aasworld.areas[i]; // get the shortest distance between one of the func_bob start edges and // one of the face edges of area1 bestdist = 999999; - for (j = 0; j < area->numfaces; j++) - { + for (j = 0; j < area->numfaces; j++) { facenum = aasworld.faceindex[area->firstface + j]; face = &aasworld.faces[abs(facenum)]; - //if not a ground face - if (!(face->faceflags & FACE_GROUND)) continue; - //get the ground planes + // if not a ground face + if (!(face->faceflags & FACE_GROUND)) + continue; + // get the ground planes faceplane = &aasworld.planes[face->planenum]; // - for (k = 0; k < face->numedges; k++) - { + for (k = 0; k < face->numedges; k++) { edgenum = abs(aasworld.edgeindex[face->firstedge + k]); edge = &aasworld.edges[edgenum]; - //calculate the minimum distance between the two edges + // calculate the minimum distance between the two edges v1 = aasworld.vertexes[edge->v[0]]; v2 = aasworld.vertexes[edge->v[1]]; // - for (l = 0; l < numpoints; l++) - { + for (l = 0; l < numpoints; l++) { v3 = facepoints[l]; - v4 = facepoints[(l+1) % numpoints]; - dist = AAS_ClosestEdgePoints(v1, v2, v3, v4, faceplane, plane, - beststart, bestend, - beststart2, bestend2, bestdist); - if (dist < bestdist) - { + v4 = facepoints[(l + 1) % numpoints]; + dist = AAS_ClosestEdgePoints(v1, v2, v3, v4, faceplane, plane, beststart, bestend, beststart2, bestend2, bestdist); + if (dist < bestdist) { bestfacenum = facenum; bestfaceplane = faceplane; bestdist = dist; - } //end if - } //end for - } //end for - } //end for + } // end if + } // end for + } // end for + } // end for // - if (bestdist > 192) continue; + if (bestdist > 192) + continue; // VectorMiddle(beststart, beststart2, beststart); VectorMiddle(bestend, bestend2, bestend); // - if (!towardsface) - { + if (!towardsface) { VectorCopy(beststart, tmp); VectorCopy(bestend, beststart); VectorCopy(tmp, bestend); - } //end if + } // end if // VectorSubtract(bestend, beststart, hordir); hordir[2] = 0; hordist = VectorLength(hordir); // - if (hordist > 2 * AAS_MaxJumpDistance(aassettings.phys_jumpvel)) continue; - //the end point should not be significantly higher than the start point - if (bestend[2] - 32 > beststart[2]) continue; - //don't fall down too far - if (bestend[2] < beststart[2] - 128) continue; - //the distance should not be too far - if (hordist > 32) - { - //check for walk off ledge - if (!AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed)) continue; - } //end if + if (hordist > 2 * AAS_MaxJumpDistance(aassettings.phys_jumpvel)) + continue; + // the end point should not be significantly higher than the start point + if (bestend[2] - 32 > beststart[2]) + continue; + // don't fall down too far + if (bestend[2] < beststart[2] - 128) + continue; + // the distance should not be too far + if (hordist > 32) { + // check for walk off ledge + if (!AAS_HorizontalVelocityForJump(0, beststart, bestend, &speed)) + continue; + } // end if // beststart[2] += 1; bestend[2] += 1; // - if (towardsface) VectorCopy(bestend, testpoint); - else VectorCopy(beststart, testpoint); + if (towardsface) + VectorCopy(bestend, testpoint); + else + VectorCopy(beststart, testpoint); testpoint[2] = 0; testpoint[2] = (bestfaceplane->dist - DotProduct(bestfaceplane->normal, testpoint)) / bestfaceplane->normal[2]; // - if (!AAS_PointInsideFace(bestfacenum, testpoint, 0.1f)) - { - //if the faces are not overlapping then only go down - if (bestend[2] - 16 > beststart[2]) continue; - } //end if + if (!AAS_PointInsideFace(bestfacenum, testpoint, 0.1f)) { + // if the faces are not overlapping then only go down + if (bestend[2] - 16 > beststart[2]) + continue; + } // end if lreach = AAS_AllocReachability(); - if (!lreach) return lreachabilities; + if (!lreach) + return lreachabilities; lreach->areanum = i; lreach->facenum = 0; lreach->edgenum = 0; @@ -3262,20 +3124,21 @@ aas_lreachability_t *AAS_FindFaceReachabilities(vec3_t *facepoints, int numpoint lreach->next = lreachabilities; lreachabilities = lreach; #ifndef BSPC - if (towardsface) AAS_PermanentLine(lreach->start, lreach->end, 1); - else AAS_PermanentLine(lreach->start, lreach->end, 2); + if (towardsface) + AAS_PermanentLine(lreach->start, lreach->end, 1); + else + AAS_PermanentLine(lreach->start, lreach->end, 2); #endif - } //end for + } // end for return lreachabilities; -} //end of the function AAS_FindFaceReachabilities +} // end of the function AAS_FindFaceReachabilities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Reachability_FuncBobbing(void) -{ +void AAS_Reachability_FuncBobbing(void) { int ent, spawnflags, modelnum, axis; int i, numareas, areas[10]; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; @@ -3288,26 +3151,26 @@ void AAS_Reachability_FuncBobbing(void) aas_lreachability_t *startreach, *endreach, *nextstartreach, *nextendreach, *lreach; aas_lreachability_t *firststartreach, *firstendreach; - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (strcmp(classname, "func_bobbing")) continue; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (strcmp(classname, "func_bobbing")) + continue; AAS_FloatForBSPEpairKey(ent, "height", &height); - if (!height) height = 32; + if (!height) + height = 32; // - if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) - { + if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) { botimport.Print(PRT_ERROR, "func_bobbing without model\n"); continue; - } //end if - //get the model number, and skip the leading * - modelnum = atoi(model+1); - if (modelnum <= 0) - { + } // end if + // get the model number, and skip the leading * + modelnum = atoi(model + 1); + if (modelnum <= 0) { botimport.Print(PRT_ERROR, "func_bobbing with invalid model number\n"); continue; - } //end if - //if the entity has an origin set then use it + } // end if + // if the entity has an origin set then use it if (!AAS_VectorForBSPEpairKey(ent, "origin", origin)) VectorSet(origin, 0, 0, 0); // @@ -3325,15 +3188,18 @@ void AAS_Reachability_FuncBobbing(void) // AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags); // set the axis of bobbing - if (spawnflags & 1) axis = 0; - else if (spawnflags & 2) axis = 1; - else axis = 2; + if (spawnflags & 1) + axis = 0; + else if (spawnflags & 2) + axis = 1; + else + axis = 2; // move_start[axis] -= height; move_end[axis] += height; // - Log_Write("funcbob model %d, start = {%1.1f, %1.1f, %1.1f} end = {%1.1f, %1.1f, %1.1f}\n", - modelnum, move_start[0], move_start[1], move_start[2], move_end[0], move_end[1], move_end[2]); + Log_Write("funcbob model %d, start = {%1.1f, %1.1f, %1.1f} end = {%1.1f, %1.1f, %1.1f}\n", modelnum, move_start[0], move_start[1], move_start[2], + move_end[0], move_end[1], move_end[2]); // #ifndef BSPC /* @@ -3342,12 +3208,11 @@ void AAS_Reachability_FuncBobbing(void) */ #endif // - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { VectorCopy(move_start, start_edgeverts[i]); start_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z - start_edgeverts[i][2] += 24; //+ player origin to ground dist - } //end for + start_edgeverts[i][2] += 24; //+ player origin to ground dist + } // end for start_edgeverts[0][0] += maxs[0] - mid[0]; start_edgeverts[0][1] += maxs[1] - mid[1]; start_edgeverts[1][0] += maxs[0] - mid[0]; @@ -3360,12 +3225,11 @@ void AAS_Reachability_FuncBobbing(void) start_plane.dist = start_edgeverts[0][2]; VectorSet(start_plane.normal, 0, 0, 1); // - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { VectorCopy(move_end, end_edgeverts[i]); end_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z - end_edgeverts[i][2] += 24; //+ player origin to ground dist - } //end for + end_edgeverts[i][2] += 24; //+ player origin to ground dist + } // end for end_edgeverts[0][0] += maxs[0] - mid[0]; end_edgeverts[0][1] += maxs[1] - mid[1]; end_edgeverts[1][0] += maxs[0] - mid[0]; @@ -3392,43 +3256,42 @@ void AAS_Reachability_FuncBobbing(void) VectorCopy(move_end, move_end_top); move_end_top[2] += maxs[2] - mid[2] + 24; //+ bbox maxs z // - if (!AAS_PointAreaNum(move_start_top)) continue; - if (!AAS_PointAreaNum(move_end_top)) continue; + if (!AAS_PointAreaNum(move_start_top)) + continue; + if (!AAS_PointAreaNum(move_end_top)) + continue; // - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { // - if (i == 0) - { + if (i == 0) { firststartreach = AAS_FindFaceReachabilities(start_edgeverts, 4, &start_plane, qtrue); firstendreach = AAS_FindFaceReachabilities(end_edgeverts, 4, &end_plane, qfalse); - } //end if - else - { + } // end if + else { firststartreach = AAS_FindFaceReachabilities(end_edgeverts, 4, &end_plane, qtrue); firstendreach = AAS_FindFaceReachabilities(start_edgeverts, 4, &start_plane, qfalse); - } //end else + } // end else // - //create reachabilities from start to end - for (startreach = firststartreach; startreach; startreach = nextstartreach) - { + // create reachabilities from start to end + for (startreach = firststartreach; startreach; startreach = nextstartreach) { nextstartreach = startreach->next; // - //trace = AAS_TraceClientBBox(startreach->start, move_start_top, PRESENCE_NORMAL, -1); - //if (trace.fraction < 1) continue; + // trace = AAS_TraceClientBBox(startreach->start, move_start_top, PRESENCE_NORMAL, -1); + // if (trace.fraction < 1) continue; // - for (endreach = firstendreach; endreach; endreach = nextendreach) - { + for (endreach = firstendreach; endreach; endreach = nextendreach) { nextendreach = endreach->next; // - //trace = AAS_TraceClientBBox(endreach->end, move_end_top, PRESENCE_NORMAL, -1); - //if (trace.fraction < 1) continue; + // trace = AAS_TraceClientBBox(endreach->end, move_end_top, PRESENCE_NORMAL, -1); + // if (trace.fraction < 1) continue; // Log_Write("funcbob reach from area %d to %d\n", startreach->areanum, endreach->areanum); // // - if (i == 0) VectorCopy(move_start_top, org); - else VectorCopy(move_end_top, org); + if (i == 0) + VectorCopy(move_start_top, org); + else + VectorCopy(move_end_top, org); VectorSubtract(startreach->start, org, dir); dir[2] = 0; VectorNormalize(dir); @@ -3439,17 +3302,24 @@ void AAS_Reachability_FuncBobbing(void) end[2] += 1; // numareas = AAS_TraceAreas(start, end, areas, points, 10); - if (numareas <= 0) continue; - if (numareas > 1) VectorCopy(points[1], startreach->start); - else VectorCopy(end, startreach->start); + if (numareas <= 0) + continue; + if (numareas > 1) + VectorCopy(points[1], startreach->start); + else + VectorCopy(end, startreach->start); // - if (!AAS_PointAreaNum(startreach->start)) continue; - if (!AAS_PointAreaNum(endreach->end)) continue; + if (!AAS_PointAreaNum(startreach->start)) + continue; + if (!AAS_PointAreaNum(endreach->end)) + continue; // lreach = AAS_AllocReachability(); lreach->areanum = endreach->areanum; - if (i == 0) lreach->edgenum = ((int)move_start[axis] << 16) | ((int) move_end[axis] & 0x0000ffff); - else lreach->edgenum = ((int)move_end[axis] << 16) | ((int) move_start[axis] & 0x0000ffff); + if (i == 0) + lreach->edgenum = ((int)move_start[axis] << 16) | ((int)move_end[axis] & 0x0000ffff); + else + lreach->edgenum = ((int)move_end[axis] << 16) | ((int)move_start[axis] & 0x0000ffff); lreach->facenum = (spawnflags << 16) | modelnum; VectorCopy(startreach->start, lreach->start); VectorCopy(endreach->end, lreach->end); @@ -3464,46 +3334,44 @@ void AAS_Reachability_FuncBobbing(void) lreach->next = areareachability[startreach->areanum]; areareachability[startreach->areanum] = lreach; // - } //end for - } //end for - for (startreach = firststartreach; startreach; startreach = nextstartreach) - { + } // end for + } // end for + for (startreach = firststartreach; startreach; startreach = nextstartreach) { nextstartreach = startreach->next; AAS_FreeReachability(startreach); - } //end for - for (endreach = firstendreach; endreach; endreach = nextendreach) - { + } // end for + for (endreach = firstendreach; endreach; endreach = nextendreach) { nextendreach = endreach->next; AAS_FreeReachability(endreach); - } //end for - //only go up with func_bobbing entities that go up and down - if (!(spawnflags & 1) && !(spawnflags & 2)) break; - } //end for - } //end for -} //end of the function AAS_Reachability_FuncBobbing + } // end for + // only go up with func_bobbing entities that go up and down + if (!(spawnflags & 1) && !(spawnflags & 2)) + break; + } // end for + } // end for +} // end of the function AAS_Reachability_FuncBobbing //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Reachability_JumpPad(void) -{ +void AAS_Reachability_JumpPad(void) { int face2num, i, ret, area2num, visualize, ent, bot_visualizejumppads; - //int modelnum, ent2; - //float dist, time, height, gravity, forward; + // int modelnum, ent2; + // float dist, time, height, gravity, forward; float speed, zvel; - //float hordist; + // float hordist; aas_face_t *face2; aas_area_t *area2; aas_lreachability_t *lreach; vec3_t areastart, facecenter, dir, cmdmove; vec3_t velocity, absmins, absmaxs; - //vec3_t origin, ent2origin, angles, teststart; + // vec3_t origin, ent2origin, angles, teststart; aas_clientmove_t move; - //aas_trace_t trace; + // aas_trace_t trace; aas_link_t *areas, *link; - //char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; + // char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; char classname[MAX_EPAIRKEY]; #ifdef BSPC @@ -3511,12 +3379,14 @@ void AAS_Reachability_JumpPad(void) #else bot_visualizejumppads = LibVarValue("bot_visualizejumppads", "0"); #endif - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (strcmp(classname, "trigger_push")) continue; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (strcmp(classname, "trigger_push")) + continue; // - if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) continue; + if (!AAS_GetJumpPadInfo(ent, areastart, absmins, absmaxs, velocity)) + continue; /* // AAS_FloatForBSPEpairKey(ent, "speed", &speed); @@ -3587,7 +3457,7 @@ void AAS_Reachability_JumpPad(void) VectorScale(velocity, forward, velocity); velocity[2] = time * gravity; */ - //get the areas the jump pad brush is in + // get the areas the jump pad brush is in areas = AAS_LinkEntityClientBBox(absmins, absmaxs, -1, PRESENCE_CROUCH); /* for (link = areas; link; link = link->next_area) @@ -3597,60 +3467,58 @@ void AAS_Reachability_JumpPad(void) ret = qfalse; } } - */ - for (link = areas; link; link = link->next_area) - { - if (AAS_AreaJumpPad(link->areanum)) break; - } //end for - if (!link) - { + */ + for (link = areas; link; link = link->next_area) { + if (AAS_AreaJumpPad(link->areanum)) + break; + } // end for + if (!link) { botimport.Print(PRT_MESSAGE, "trigger_push not in any jump pad area\n"); AAS_UnlinkFromAreas(areas); continue; - } //end if + } // end if // botimport.Print(PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2]); - //if there is a horizontal velocity check for a reachability without air control - if (velocity[0] || velocity[1]) - { + // if there is a horizontal velocity check for a reachability without air control + if (velocity[0] || velocity[1]) { VectorSet(cmdmove, 0, 0, 0); - //VectorCopy(velocity, cmdmove); - //cmdmove[2] = 0; + // VectorCopy(velocity, cmdmove); + // cmdmove[2] = 0; Com_Memset(&move, 0, sizeof(aas_clientmove_t)); area2num = 0; - for (i = 0; i < 20; i++) - { - AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse, - velocity, cmdmove, 0, 30, 0.1f, - SE_HITGROUND|SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER, 0, bot_visualizejumppads); + for (i = 0; i < 20; i++) { + AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 0, 30, 0.1f, + SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | + SE_TOUCHTELEPORTER, + 0, bot_visualizejumppads); area2num = move.endarea; - for (link = areas; link; link = link->next_area) - { - if (!AAS_AreaJumpPad(link->areanum)) continue; - if (link->areanum == area2num) break; - } //end if - if (!link) break; + for (link = areas; link; link = link->next_area) { + if (!AAS_AreaJumpPad(link->areanum)) + continue; + if (link->areanum == area2num) + break; + } // end if + if (!link) + break; VectorCopy(move.endpos, areastart); VectorCopy(move.velocity, velocity); - } //end for - if (area2num && i < 20) - { - for (link = areas; link; link = link->next_area) - { - if (!AAS_AreaJumpPad(link->areanum)) continue; - if (AAS_ReachabilityExists(link->areanum, area2num)) continue; - //create a rocket or bfg jump reachability from area1 to area2 + } // end for + if (area2num && i < 20) { + for (link = areas; link; link = link->next_area) { + if (!AAS_AreaJumpPad(link->areanum)) + continue; + if (AAS_ReachabilityExists(link->areanum, area2num)) + continue; + // create a rocket or bfg jump reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) - { + if (!lreach) { AAS_UnlinkFromAreas(areas); return; - } //end if + } // end if lreach->areanum = area2num; - //NOTE: the facenum is the Z velocity + // NOTE: the facenum is the Z velocity lreach->facenum = velocity[2]; - //NOTE: the edgenum is the horizontal velocity + // NOTE: the edgenum is the horizontal velocity lreach->edgenum = sqrt(velocity[0] * velocity[0] + velocity[1] * velocity[1]); VectorCopy(areastart, lreach->start); VectorCopy(move.endpos, lreach->end); @@ -3661,14 +3529,14 @@ void AAS_Reachability_JumpPad(void) areareachability[link->areanum] = lreach; // reach_jumppad++; - } //end for - } //end if - } //end if + } // end for + } // end if + } // end if // - if (fabs(velocity[0]) > 100 || fabs(velocity[1]) > 100) continue; - //check for areas we can reach with air control - for (area2num = 1; area2num < aasworld.numareas; area2num++) - { + if (fabs(velocity[0]) > 100 || fabs(velocity[1]) > 100) + continue; + // check for areas we can reach with air control + for (area2num = 1; area2num < aasworld.numareas; area2num++) { visualize = qfalse; /* if (area2num == 3568) @@ -3682,78 +3550,75 @@ void AAS_Reachability_JumpPad(void) } //end if } //end for } //end if*/ - //never try to go back to one of the original jumppad areas - //and don't create reachabilities if they already exist - for (link = areas; link; link = link->next_area) - { - if (AAS_ReachabilityExists(link->areanum, area2num)) break; - if (AAS_AreaJumpPad(link->areanum)) - { - if (link->areanum == area2num) break; - } //end if - } //end if - if (link) continue; + // never try to go back to one of the original jumppad areas + // and don't create reachabilities if they already exist + for (link = areas; link; link = link->next_area) { + if (AAS_ReachabilityExists(link->areanum, area2num)) + break; + if (AAS_AreaJumpPad(link->areanum)) { + if (link->areanum == area2num) + break; + } // end if + } // end if + if (link) + continue; // area2 = &aasworld.areas[area2num]; - for (i = 0; i < area2->numfaces; i++) - { + for (i = 0; i < area2->numfaces; i++) { face2num = aasworld.faceindex[area2->firstface + i]; face2 = &aasworld.faces[abs(face2num)]; - //if it is not a ground face - if (!(face2->faceflags & FACE_GROUND)) continue; - //get the center of the face + // if it is not a ground face + if (!(face2->faceflags & FACE_GROUND)) + continue; + // get the center of the face AAS_FaceCenter(face2num, facecenter); - //only go higher up - if (facecenter[2] < areastart[2]) continue; - //get the jumppad jump z velocity + // only go higher up + if (facecenter[2] < areastart[2]) + continue; + // get the jumppad jump z velocity zvel = velocity[2]; - //get the horizontal speed for the jump, if it isn't possible to calculate this - //speed + // get the horizontal speed for the jump, if it isn't possible to calculate this + // speed ret = AAS_HorizontalVelocityForJump(zvel, areastart, facecenter, &speed); - if (ret && speed < 150) - { - //direction towards the face center + if (ret && speed < 150) { + // direction towards the face center VectorSubtract(facecenter, areastart, dir); dir[2] = 0; - //hordist = VectorNormalize(dir); - //if (hordist < 1.6 * facecenter[2] - areastart[2]) + // hordist = VectorNormalize(dir); + // if (hordist < 1.6 * facecenter[2] - areastart[2]) { - //get command movement + // get command movement VectorScale(dir, speed, cmdmove); // - AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse, - velocity, cmdmove, 30, 30, 0.1f, - SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE| - SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER|SE_HITGROUNDAREA, area2num, visualize); - //if prediction time wasn't enough to fully predict the movement - //don't enter slime or lava and don't fall from too high - if (move.frames < 30 && - !(move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE)) - && (move.stopevent & (SE_HITGROUNDAREA|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER))) - { - //never go back to the same jumppad - for (link = areas; link; link = link->next_area) - { - if (link->areanum == move.endarea) break; + AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 30, 30, 0.1f, + SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER | + SE_HITGROUNDAREA, + area2num, visualize); + // if prediction time wasn't enough to fully predict the movement + // don't enter slime or lava and don't fall from too high + if (move.frames < 30 && !(move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE)) && + (move.stopevent & (SE_HITGROUNDAREA | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER))) { + // never go back to the same jumppad + for (link = areas; link; link = link->next_area) { + if (link->areanum == move.endarea) + break; } - if (!link) - { - for (link = areas; link; link = link->next_area) - { - if (!AAS_AreaJumpPad(link->areanum)) continue; - if (AAS_ReachabilityExists(link->areanum, area2num)) continue; - //create a jumppad reachability from area1 to area2 + if (!link) { + for (link = areas; link; link = link->next_area) { + if (!AAS_AreaJumpPad(link->areanum)) + continue; + if (AAS_ReachabilityExists(link->areanum, area2num)) + continue; + // create a jumppad reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) - { + if (!lreach) { AAS_UnlinkFromAreas(areas); return; - } //end if + } // end if lreach->areanum = move.endarea; - //NOTE: the facenum is the Z velocity + // NOTE: the facenum is the Z velocity lreach->facenum = velocity[2]; - //NOTE: the edgenum is the horizontal velocity + // NOTE: the edgenum is the horizontal velocity lreach->edgenum = sqrt(cmdmove[0] * cmdmove[0] + cmdmove[1] * cmdmove[1]); VectorCopy(areastart, lreach->start); VectorCopy(facecenter, lreach->end); @@ -3764,16 +3629,16 @@ void AAS_Reachability_JumpPad(void) areareachability[link->areanum] = lreach; // reach_jumppad++; - } //end for + } // end for } - } //end if - } //end if - } //end for - } //end for - } //end for + } // end if + } // end if + } // end for + } // end for + } // end for AAS_UnlinkFromAreas(areas); - } //end for -} //end of the function AAS_Reachability_JumpPad + } // end for +} // end of the function AAS_Reachability_JumpPad //=========================================================================== // never point at ground faces // always a higher and pretty far area @@ -3782,8 +3647,7 @@ void AAS_Reachability_JumpPad(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_Grapple(int area1num, int area2num) -{ +int AAS_Reachability_Grapple(int area1num, int area2num) { int face2num, i, j, areanum, numareas, areas[20]; float mingrappleangle, z, hordist; bsp_trace_t bsptrace; @@ -3794,117 +3658,135 @@ int AAS_Reachability_Grapple(int area1num, int area2num) vec3_t areastart, facecenter, start, end, dir, down = {0, 0, -1}; float *v; - //only grapple when on the ground or swimming - if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) return qfalse; - //don't grapple from a crouch area - if (!(AAS_AreaPresenceType(area1num) & PRESENCE_NORMAL)) return qfalse; - //NOTE: disabled area swim it doesn't work right - if (AAS_AreaSwim(area1num)) return qfalse; + // only grapple when on the ground or swimming + if (!AAS_AreaGrounded(area1num) && !AAS_AreaSwim(area1num)) + return qfalse; + // don't grapple from a crouch area + if (!(AAS_AreaPresenceType(area1num) & PRESENCE_NORMAL)) + return qfalse; + // NOTE: disabled area swim it doesn't work right + if (AAS_AreaSwim(area1num)) + return qfalse; // area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - //don't grapple towards way lower areas - if (area2->maxs[2] < area1->mins[2]) return qfalse; + // don't grapple towards way lower areas + if (area2->maxs[2] < area1->mins[2]) + return qfalse; // VectorCopy(aasworld.areas[area1num].center, start); - //if not a swim area - if (!AAS_AreaSwim(area1num)) - { - if (!AAS_PointAreaNum(start)) Log_Write("area %d center %f %f %f in solid?\r\n", area1num, - start[0], start[1], start[2]); + // if not a swim area + if (!AAS_AreaSwim(area1num)) { + if (!AAS_PointAreaNum(start)) + Log_Write("area %d center %f %f %f in solid?\r\n", area1num, start[0], start[1], start[2]); VectorCopy(start, end); end[2] -= 1000; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - if (trace.startsolid) return qfalse; + if (trace.startsolid) + return qfalse; VectorCopy(trace.endpos, areastart); - } //end if - else - { - if (!(AAS_PointContents(start) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) return qfalse; - } //end else + } // end if + else { + if (!(AAS_PointContents(start) & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER))) + return qfalse; + } // end else // - //start is now the start point + // start is now the start point // - for (i = 0; i < area2->numfaces; i++) - { + for (i = 0; i < area2->numfaces; i++) { face2num = aasworld.faceindex[area2->firstface + i]; face2 = &aasworld.faces[abs(face2num)]; - //if it is not a solid face - if (!(face2->faceflags & FACE_SOLID)) continue; - //direction towards the first vertex of the face + // if it is not a solid face + if (!(face2->faceflags & FACE_SOLID)) + continue; + // direction towards the first vertex of the face v = aasworld.vertexes[aasworld.edges[abs(aasworld.edgeindex[face2->firstedge])].v[0]]; VectorSubtract(v, areastart, dir); - //if the face plane is facing away - if (DotProduct(aasworld.planes[face2->planenum].normal, dir) > 0) continue; - //get the center of the face + // if the face plane is facing away + if (DotProduct(aasworld.planes[face2->planenum].normal, dir) > 0) + continue; + // get the center of the face AAS_FaceCenter(face2num, facecenter); - //only go higher up with the grapple - if (facecenter[2] < areastart[2] + 64) continue; - //only use vertical faces or downward facing faces - if (DotProduct(aasworld.planes[face2->planenum].normal, down) < 0) continue; - //direction towards the face center + // only go higher up with the grapple + if (facecenter[2] < areastart[2] + 64) + continue; + // only use vertical faces or downward facing faces + if (DotProduct(aasworld.planes[face2->planenum].normal, down) < 0) + continue; + // direction towards the face center VectorSubtract(facecenter, areastart, dir); // z = dir[2]; dir[2] = 0; hordist = VectorLength(dir); - if (!hordist) continue; - //if too far - if (hordist > 2000) continue; - //check the minimal angle of the movement - mingrappleangle = 15; //15 degrees - if (z / hordist < tan(2 * M_PI * mingrappleangle / 360)) continue; + if (!hordist) + continue; + // if too far + if (hordist > 2000) + continue; + // check the minimal angle of the movement + mingrappleangle = 15; // 15 degrees + if (z / hordist < tan(2 * M_PI * mingrappleangle / 360)) + continue; // VectorCopy(facecenter, start); VectorMA(facecenter, -500, aasworld.planes[face2->planenum].normal, end); // bsptrace = AAS_Trace(start, NULL, NULL, end, 0, CONTENTS_SOLID); - //the grapple won't stick to the sky and the grapple point should be near the AAS wall - if ((bsptrace.surface.flags & SURF_SKY) || (bsptrace.fraction * 500 > 32)) continue; - //trace a full bounding box from the area center on the ground to - //the center of the face + // the grapple won't stick to the sky and the grapple point should be near the AAS wall + if ((bsptrace.surface.flags & SURF_SKY) || (bsptrace.fraction * 500 > 32)) + continue; + // trace a full bounding box from the area center on the ground to + // the center of the face VectorSubtract(facecenter, areastart, dir); VectorNormalize(dir); VectorMA(areastart, 4, dir, start); VectorCopy(bsptrace.endpos, end); trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1); VectorSubtract(trace.endpos, facecenter, dir); - if (VectorLength(dir) > 24) continue; + if (VectorLength(dir) > 24) + continue; // VectorCopy(trace.endpos, start); VectorCopy(trace.endpos, end); end[2] -= AAS_FallDamageDistance(); trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1); - if (trace.fraction >= 1) continue; - //area to end in + if (trace.fraction >= 1) + continue; + // area to end in areanum = AAS_PointAreaNum(trace.endpos); - //if not in lava or slime - if (aasworld.areasettings[areanum].contents & (AREACONTENTS_SLIME|AREACONTENTS_LAVA)) - { + // if not in lava or slime + if (aasworld.areasettings[areanum].contents & (AREACONTENTS_SLIME | AREACONTENTS_LAVA)) { continue; - } //end if - //do not go the the source area - if (areanum == area1num) continue; - //don't create reachabilities if they already exist - if (AAS_ReachabilityExists(area1num, areanum)) continue; - //only end in areas we can stand - if (!AAS_AreaGrounded(areanum)) continue; - //never go through cluster portals!! + } // end if + // do not go the the source area + if (areanum == area1num) + continue; + // don't create reachabilities if they already exist + if (AAS_ReachabilityExists(area1num, areanum)) + continue; + // only end in areas we can stand + if (!AAS_AreaGrounded(areanum)) + continue; + // never go through cluster portals!! numareas = AAS_TraceAreas(areastart, bsptrace.endpos, areas, NULL, 20); - if (numareas >= 20) continue; - for (j = 0; j < numareas; j++) - { - if (aasworld.areasettings[areas[j]].contents & AREACONTENTS_CLUSTERPORTAL) break; - } //end for - if (j < numareas) continue; - //create a new reachability link + if (numareas >= 20) + continue; + for (j = 0; j < numareas; j++) { + if (aasworld.areasettings[areas[j]].contents & AREACONTENTS_CLUSTERPORTAL) + break; + } // end for + if (j < numareas) + continue; + // create a new reachability link lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = areanum; lreach->facenum = face2num; lreach->edgenum = 0; VectorCopy(areastart, lreach->start); - //VectorCopy(facecenter, lreach->end); + // VectorCopy(facecenter, lreach->end); VectorCopy(bsptrace.endpos, lreach->end); lreach->traveltype = TRAVEL_GRAPPLEHOOK; VectorSubtract(lreach->end, lreach->start, dir); @@ -3913,18 +3795,17 @@ int AAS_Reachability_Grapple(int area1num, int area2num) areareachability[area1num] = lreach; // reach_grapple++; - } //end for + } // end for // return qfalse; -} //end of the function AAS_Reachability_Grapple +} // end of the function AAS_Reachability_Grapple //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_SetWeaponJumpAreaFlags(void) -{ +void AAS_SetWeaponJumpAreaFlags(void) { int ent, i; vec3_t mins = {-15, -15, -15}, maxs = {15, 15, 15}; vec3_t origin; @@ -3932,53 +3813,41 @@ void AAS_SetWeaponJumpAreaFlags(void) char classname[MAX_EPAIRKEY]; weaponjumpareas = 0; - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if ( - !strcmp(classname, "item_armor_body") || - !strcmp(classname, "item_health") || - !strcmp(classname, "weapon_disruptor") || - !strcmp(classname, "weapon_repeater") || - !strcmp(classname, "weapon_demp2") || - !strcmp(classname, "weapon_flechette") || - !strcmp(classname, "weapon_rocket_launcher")) - { - if (AAS_VectorForBSPEpairKey(ent, "origin", origin)) - { + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (!strcmp(classname, "item_armor_body") || !strcmp(classname, "item_health") || !strcmp(classname, "weapon_disruptor") || + !strcmp(classname, "weapon_repeater") || !strcmp(classname, "weapon_demp2") || !strcmp(classname, "weapon_flechette") || + !strcmp(classname, "weapon_rocket_launcher")) { + if (AAS_VectorForBSPEpairKey(ent, "origin", origin)) { spawnflags = 0; AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags); - //if not a stationary item - if (!(spawnflags & 1)) - { - if (!AAS_DropToFloor(origin, mins, maxs)) - { - botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", - classname, origin[0], origin[1], origin[2]); - } //end if - } //end if - //areanum = AAS_PointAreaNum(origin); + // if not a stationary item + if (!(spawnflags & 1)) { + if (!AAS_DropToFloor(origin, mins, maxs)) { + botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2]); + } // end if + } // end if + // areanum = AAS_PointAreaNum(origin); areanum = AAS_BestReachableArea(origin, mins, maxs, origin); - //the bot may rocket jump towards this area + // the bot may rocket jump towards this area aasworld.areasettings[areanum].areaflags |= AREA_WEAPONJUMP; // - //if (!AAS_AreaGrounded(areanum)) + // if (!AAS_AreaGrounded(areanum)) // botimport.Print(PRT_MESSAGE, "area not grounded\n"); // weaponjumpareas++; - } //end if - } //end if - } //end for - for (i = 1; i < aasworld.numareas; i++) - { - if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) - { + } // end if + } // end if + } // end for + for (i = 1; i < aasworld.numareas; i++) { + if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) { aasworld.areasettings[i].areaflags |= AREA_WEAPONJUMP; weaponjumpareas++; - } //end if - } //end for + } // end if + } // end for botimport.Print(PRT_MESSAGE, "%d weapon jump areas\n", weaponjumpareas); -} //end of the function AAS_SetWeaponJumpAreaFlags +} // end of the function AAS_SetWeaponJumpAreaFlags //=========================================================================== // create a possible weapon jump reachability from area1 to area2 // @@ -3990,74 +3859,79 @@ void AAS_SetWeaponJumpAreaFlags(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_Reachability_WeaponJump(int area1num, int area2num) -{ +int AAS_Reachability_WeaponJump(int area1num, int area2num) { int face2num, i, n, ret, visualize; float speed, zvel; - //float hordist; + // float hordist; aas_face_t *face2; aas_area_t *area1, *area2; aas_lreachability_t *lreach; - vec3_t areastart, facecenter, start, end, dir, cmdmove;// teststart; + vec3_t areastart, facecenter, start, end, dir, cmdmove; // teststart; vec3_t velocity; aas_clientmove_t move; aas_trace_t trace; visualize = qfalse; -// if (area1num == 4436 && area2num == 4318) -// { -// visualize = qtrue; -// } - if (!AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) return qfalse; - if (!AAS_AreaGrounded(area2num)) return qfalse; - //NOTE: only weapon jump towards areas with an interesting item in it?? - if (!(aasworld.areasettings[area2num].areaflags & AREA_WEAPONJUMP)) return qfalse; + // if (area1num == 4436 && area2num == 4318) + // { + // visualize = qtrue; + // } + if (!AAS_AreaGrounded(area1num) || AAS_AreaSwim(area1num)) + return qfalse; + if (!AAS_AreaGrounded(area2num)) + return qfalse; + // NOTE: only weapon jump towards areas with an interesting item in it?? + if (!(aasworld.areasettings[area2num].areaflags & AREA_WEAPONJUMP)) + return qfalse; // area1 = &aasworld.areas[area1num]; area2 = &aasworld.areas[area2num]; - //don't weapon jump towards way lower areas - if (area2->maxs[2] < area1->mins[2]) return qfalse; + // don't weapon jump towards way lower areas + if (area2->maxs[2] < area1->mins[2]) + return qfalse; // VectorCopy(aasworld.areas[area1num].center, start); - //if not a swim area - if (!AAS_PointAreaNum(start)) Log_Write("area %d center %f %f %f in solid?\r\n", area1num, - start[0], start[1], start[2]); + // if not a swim area + if (!AAS_PointAreaNum(start)) + Log_Write("area %d center %f %f %f in solid?\r\n", area1num, start[0], start[1], start[2]); VectorCopy(start, end); end[2] -= 1000; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - if (trace.startsolid) return qfalse; + if (trace.startsolid) + return qfalse; VectorCopy(trace.endpos, areastart); // - //areastart is now the start point + // areastart is now the start point // - for (i = 0; i < area2->numfaces; i++) - { + for (i = 0; i < area2->numfaces; i++) { face2num = aasworld.faceindex[area2->firstface + i]; face2 = &aasworld.faces[abs(face2num)]; - //if it is not a solid face - if (!(face2->faceflags & FACE_GROUND)) continue; - //get the center of the face + // if it is not a solid face + if (!(face2->faceflags & FACE_GROUND)) + continue; + // get the center of the face AAS_FaceCenter(face2num, facecenter); - //only go higher up with weapon jumps - if (facecenter[2] < areastart[2] + 64) continue; - //NOTE: set to 2 to allow bfg jump reachabilities - for (n = 0; n < 1/*2*/; n++) - { - //get the rocket jump z velocity - if (n) zvel = AAS_BFGJumpZVelocity(areastart); - else zvel = AAS_RocketJumpZVelocity(areastart); - //get the horizontal speed for the jump, if it isn't possible to calculate this - //speed (the jump is not possible) then there's no jump reachability created + // only go higher up with weapon jumps + if (facecenter[2] < areastart[2] + 64) + continue; + // NOTE: set to 2 to allow bfg jump reachabilities + for (n = 0; n < 1 /*2*/; n++) { + // get the rocket jump z velocity + if (n) + zvel = AAS_BFGJumpZVelocity(areastart); + else + zvel = AAS_RocketJumpZVelocity(areastart); + // get the horizontal speed for the jump, if it isn't possible to calculate this + // speed (the jump is not possible) then there's no jump reachability created ret = AAS_HorizontalVelocityForJump(zvel, areastart, facecenter, &speed); - if (ret && speed < 300) - { - //direction towards the face center + if (ret && speed < 300) { + // direction towards the face center VectorSubtract(facecenter, areastart, dir); dir[2] = 0; - //hordist = VectorNormalize(dir); - //if (hordist < 1.6 * (facecenter[2] - areastart[2])) + // hordist = VectorNormalize(dir); + // if (hordist < 1.6 * (facecenter[2] - areastart[2])) { - //get command movement + // get command movement VectorScale(dir, speed, cmdmove); VectorSet(velocity, 0, 0, zvel); /* @@ -4067,48 +3941,44 @@ int AAS_Reachability_WeaponJump(int area1num, int area2num) VectorSet(cmdmove, 0, 0, 0); */ // - AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qtrue, - velocity, cmdmove, 30, 30, 0.1f, - SE_ENTERWATER|SE_ENTERSLIME| - SE_ENTERLAVA|SE_HITGROUNDDAMAGE| - SE_TOUCHJUMPPAD|SE_HITGROUND|SE_HITGROUNDAREA, area2num, visualize); - //if prediction time wasn't enough to fully predict the movement - //don't enter slime or lava and don't fall from too high - if (move.frames < 30 && - !(move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE)) - && (move.stopevent & (SE_HITGROUNDAREA|SE_TOUCHJUMPPAD))) - { - //create a rocket or bfg jump reachability from area1 to area2 + AAS_PredictClientMovement(&move, -1, areastart, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 30, 30, 0.1f, + SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_HITGROUND | + SE_HITGROUNDAREA, + area2num, visualize); + // if prediction time wasn't enough to fully predict the movement + // don't enter slime or lava and don't fall from too high + if (move.frames < 30 && !(move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE)) && + (move.stopevent & (SE_HITGROUNDAREA | SE_TOUCHJUMPPAD))) { + // create a rocket or bfg jump reachability from area1 to area2 lreach = AAS_AllocReachability(); - if (!lreach) return qfalse; + if (!lreach) + return qfalse; lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; VectorCopy(areastart, lreach->start); VectorCopy(facecenter, lreach->end); - if (n) - { + if (n) { lreach->traveltype = TRAVEL_BFGJUMP; lreach->traveltime = aassettings.rs_bfgjump; - } //end if - else - { + } // end if + else { lreach->traveltype = TRAVEL_ROCKETJUMP; lreach->traveltime = aassettings.rs_rocketjump; - } //end else + } // end else lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_rocketjump++; return qtrue; - } //end if - } //end if - } //end if - } //end for - } //end for + } // end if + } // end if + } // end if + } // end for + } // end for // return qfalse; -} //end of the function AAS_Reachability_WeaponJump +} // end of the function AAS_Reachability_WeaponJump //=========================================================================== // calculates additional walk off ledge reachabilities for the given area // @@ -4116,8 +3986,7 @@ int AAS_Reachability_WeaponJump(int area1num, int area2num) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_Reachability_WalkOffLedge(int areanum) -{ +void AAS_Reachability_WalkOffLedge(int areanum) { int i, j, k, l, m, n, p, areas[10], numareas; int face1num, face2num, face3num, edge1num, edge2num, edge3num; int otherareanum, gap, reachareanum, side; @@ -4130,78 +3999,75 @@ void AAS_Reachability_WalkOffLedge(int areanum) aas_lreachability_t *lreach; aas_trace_t trace; - if (!AAS_AreaGrounded(areanum) || AAS_AreaSwim(areanum)) return; + if (!AAS_AreaGrounded(areanum) || AAS_AreaSwim(areanum)) + return; // area = &aasworld.areas[areanum]; // - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { face1num = aasworld.faceindex[area->firstface + i]; face1 = &aasworld.faces[abs(face1num)]; - //face 1 must be a ground face - if (!(face1->faceflags & FACE_GROUND)) continue; - //go through all the edges of this ground face - for (k = 0; k < face1->numedges; k++) - { + // face 1 must be a ground face + if (!(face1->faceflags & FACE_GROUND)) + continue; + // go through all the edges of this ground face + for (k = 0; k < face1->numedges; k++) { edge1num = aasworld.edgeindex[face1->firstedge + k]; - //find another not ground face using this same edge - for (j = 0; j < area->numfaces; j++) - { + // find another not ground face using this same edge + for (j = 0; j < area->numfaces; j++) { face2num = aasworld.faceindex[area->firstface + j]; face2 = &aasworld.faces[abs(face2num)]; - //face 2 may not be a ground face - if (face2->faceflags & FACE_GROUND) continue; - //compare all the edges - for (l = 0; l < face2->numedges; l++) - { + // face 2 may not be a ground face + if (face2->faceflags & FACE_GROUND) + continue; + // compare all the edges + for (l = 0; l < face2->numedges; l++) { edge2num = aasworld.edgeindex[face2->firstedge + l]; - if (abs(edge1num) == abs(edge2num)) - { - //get the area at the other side of the face - if (face2->frontarea == areanum) otherareanum = face2->backarea; - else otherareanum = face2->frontarea; + if (abs(edge1num) == abs(edge2num)) { + // get the area at the other side of the face + if (face2->frontarea == areanum) + otherareanum = face2->backarea; + else + otherareanum = face2->frontarea; // area2 = &aasworld.areas[otherareanum]; - //if the other area is grounded! - if (aasworld.areasettings[otherareanum].areaflags & AREA_GROUNDED) - { - //check for a possible gap + // if the other area is grounded! + if (aasworld.areasettings[otherareanum].areaflags & AREA_GROUNDED) { + // check for a possible gap gap = qfalse; - for (n = 0; n < area2->numfaces; n++) - { + for (n = 0; n < area2->numfaces; n++) { face3num = aasworld.faceindex[area2->firstface + n]; - //may not be the shared face of the two areas - if (abs(face3num) == abs(face2num)) continue; + // may not be the shared face of the two areas + if (abs(face3num) == abs(face2num)) + continue; // face3 = &aasworld.faces[abs(face3num)]; - //find an edge shared by all three faces - for (m = 0; m < face3->numedges; m++) - { + // find an edge shared by all three faces + for (m = 0; m < face3->numedges; m++) { edge3num = aasworld.edgeindex[face3->firstedge + m]; - //but the edge should be shared by all three faces - if (abs(edge3num) == abs(edge1num)) - { - if (!(face3->faceflags & FACE_SOLID)) - { + // but the edge should be shared by all three faces + if (abs(edge3num) == abs(edge1num)) { + if (!(face3->faceflags & FACE_SOLID)) { gap = qtrue; break; - } //end if + } // end if // - if (face3->faceflags & FACE_GROUND) - { + if (face3->faceflags & FACE_GROUND) { gap = qfalse; break; - } //end if - //FIXME: there are more situations to be handled + } // end if + // FIXME: there are more situations to be handled gap = qtrue; break; - } //end if - } //end for - if (m < face3->numedges) break; - } //end for - if (!gap) break; - } //end if - //check for a walk off ledge reachability + } // end if + } // end for + if (m < face3->numedges) + break; + } // end for + if (!gap) + break; + } // end if + // check for a walk off ledge reachability edge = &aasworld.edges[abs(edge1num)]; side = edge1num < 0; // @@ -4209,7 +4075,7 @@ void AAS_Reachability_WalkOffLedge(int areanum) v2 = aasworld.vertexes[edge->v[!side]]; // plane = &aasworld.planes[face1->planenum]; - //get the points really into the areas + // get the points really into the areas VectorSubtract(v2, v1, sharededgevec); CrossProduct(plane->normal, sharededgevec, dir); VectorNormalize(dir); @@ -4222,35 +4088,29 @@ void AAS_Reachability_WalkOffLedge(int areanum) testend[2] -= 1000; trace = AAS_TraceClientBBox(mid, testend, PRESENCE_CROUCH, -1); // - if (trace.startsolid) - { - //Log_Write("area %d: trace.startsolid\r\n", areanum); + if (trace.startsolid) { + // Log_Write("area %d: trace.startsolid\r\n", areanum); break; - } //end if + } // end if reachareanum = AAS_PointAreaNum(trace.endpos); - if (reachareanum == areanum) - { - //Log_Write("area %d: same area\r\n", areanum); + if (reachareanum == areanum) { + // Log_Write("area %d: same area\r\n", areanum); break; - } //end if - if (AAS_ReachabilityExists(areanum, reachareanum)) - { - //Log_Write("area %d: reachability already exists\r\n", areanum); + } // end if + if (AAS_ReachabilityExists(areanum, reachareanum)) { + // Log_Write("area %d: reachability already exists\r\n", areanum); break; - } //end if - if (!AAS_AreaGrounded(reachareanum) && !AAS_AreaSwim(reachareanum)) - { - //Log_Write("area %d, reach area %d: not grounded and not swim\r\n", areanum, reachareanum); + } // end if + if (!AAS_AreaGrounded(reachareanum) && !AAS_AreaSwim(reachareanum)) { + // Log_Write("area %d, reach area %d: not grounded and not swim\r\n", areanum, reachareanum); break; - } //end if + } // end if // - if (aasworld.areasettings[reachareanum].contents & (AREACONTENTS_SLIME - | AREACONTENTS_LAVA)) - { - //Log_Write("area %d, reach area %d: lava or slime\r\n", areanum, reachareanum); + if (aasworld.areasettings[reachareanum].contents & (AREACONTENTS_SLIME | AREACONTENTS_LAVA)) { + // Log_Write("area %d, reach area %d: lava or slime\r\n", areanum, reachareanum); break; - } //end if - //if not going through a cluster portal + } // end if + // if not going through a cluster portal numareas = AAS_TraceAreas(mid, testend, areas, NULL, ARRAY_LEN(areas)); for (p = 0; p < numareas; p++) if (AAS_AreaClusterPortal(areas[p])) @@ -4262,7 +4122,8 @@ void AAS_Reachability_WalkOffLedge(int areanum) break; // lreach = AAS_AllocReachability(); - if (!lreach) break; + if (!lreach) + break; lreach->areanum = reachareanum; lreach->facenum = 0; lreach->edgenum = edge1num; @@ -4270,52 +4131,46 @@ void AAS_Reachability_WalkOffLedge(int areanum) VectorCopy(trace.endpos, lreach->end); lreach->traveltype = TRAVEL_WALKOFFLEDGE; lreach->traveltime = aassettings.rs_startwalkoffledge + fabs(mid[2] - trace.endpos[2]) * 50 / aassettings.phys_gravity; - if (!AAS_AreaSwim(reachareanum) && !AAS_AreaJumpPad(reachareanum)) - { - if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta5) - { + if (!AAS_AreaSwim(reachareanum) && !AAS_AreaJumpPad(reachareanum)) { + if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta5) { lreach->traveltime += aassettings.rs_falldamage5; - } //end if - else if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta10) - { + } // end if + else if (AAS_FallDelta(mid[2] - trace.endpos[2]) > aassettings.phys_falldelta10) { lreach->traveltime += aassettings.rs_falldamage10; - } //end if - } //end if + } // end if + } // end if lreach->next = areareachability[areanum]; areareachability[areanum] = lreach; - //we've got another walk off ledge reachability + // we've got another walk off ledge reachability reach_walkoffledge++; - } //end if - } //end for - } //end for - } //end for - } //end for -} //end of the function AAS_Reachability_WalkOffLedge + } // end if + } // end for + } // end for + } // end for + } // end for +} // end of the function AAS_Reachability_WalkOffLedge //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_StoreReachability(void) -{ +void AAS_StoreReachability(void) { int i; aas_areasettings_t *areasettings; aas_lreachability_t *lreach; aas_reachability_t *reach; - if (aasworld.reachability) FreeMemory(aasworld.reachability); - aasworld.reachability = (aas_reachability_t *) GetClearedMemory((numlreachabilities + 10) * sizeof(aas_reachability_t)); + if (aasworld.reachability) + FreeMemory(aasworld.reachability); + aasworld.reachability = (aas_reachability_t *)GetClearedMemory((numlreachabilities + 10) * sizeof(aas_reachability_t)); aasworld.reachabilitysize = 1; - for (i = 0; i < aasworld.numareas; i++) - { + for (i = 0; i < aasworld.numareas; i++) { areasettings = &aasworld.areasettings[i]; areasettings->firstreachablearea = aasworld.reachabilitysize; areasettings->numreachableareas = 0; - for (lreach = areareachability[i]; lreach; lreach = lreach->next) - { - reach = &aasworld.reachability[areasettings->firstreachablearea + - areasettings->numreachableareas]; + for (lreach = areareachability[i]; lreach; lreach = lreach->next) { + reach = &aasworld.reachability[areasettings->firstreachablearea + areasettings->numreachableareas]; reach->areanum = lreach->areanum; reach->facenum = lreach->facenum; reach->edgenum = lreach->edgenum; @@ -4325,10 +4180,10 @@ void AAS_StoreReachability(void) reach->traveltime = lreach->traveltime; // areasettings->numreachableareas++; - } //end for + } // end for aasworld.reachabilitysize += areasettings->numreachableareas; - } //end for -} //end of the function AAS_StoreReachability + } // end for +} // end of the function AAS_StoreReachability //=========================================================================== // // TRAVEL_WALK 100% equal floor height + steps @@ -4354,108 +4209,109 @@ void AAS_StoreReachability(void) // Returns: true if NOT finished // Changes Globals: - //=========================================================================== -int AAS_ContinueInitReachability(float time) -{ +int AAS_ContinueInitReachability(float time) { int i, j, todo, start_time; static float framereachability, reachability_delay; static int lastpercentage; - if (!aasworld.loaded) return qfalse; - //if reachability is calculated for all areas - if (aasworld.numreachabilityareas >= aasworld.numareas + 2) return qfalse; - //if starting with area 1 (area 0 is a dummy) - if (aasworld.numreachabilityareas == 1) - { + if (!aasworld.loaded) + return qfalse; + // if reachability is calculated for all areas + if (aasworld.numreachabilityareas >= aasworld.numareas + 2) + return qfalse; + // if starting with area 1 (area 0 is a dummy) + if (aasworld.numreachabilityareas == 1) { botimport.Print(PRT_MESSAGE, "calculating reachability...\n"); lastpercentage = 0; framereachability = 2000; reachability_delay = 1000; - } //end if - //number of areas to calculate reachability for this cycle - todo = aasworld.numreachabilityareas + (int) framereachability; + } // end if + // number of areas to calculate reachability for this cycle + todo = aasworld.numreachabilityareas + (int)framereachability; start_time = Sys_MilliSeconds(); - //loop over the areas - for (i = aasworld.numreachabilityareas; i < aasworld.numareas && i < todo; i++) - { + // loop over the areas + for (i = aasworld.numreachabilityareas; i < aasworld.numareas && i < todo; i++) { aasworld.numreachabilityareas++; - //only create jumppad reachabilities from jumppad areas - if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) - { + // only create jumppad reachabilities from jumppad areas + if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) { continue; - } //end if - //loop over the areas - for (j = 1; j < aasworld.numareas; j++) - { - if (i == j) continue; - //never create reachabilities from teleporter or jumppad areas to regular areas - if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD)) - { - if (!(aasworld.areasettings[j].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD))) - { + } // end if + // loop over the areas + for (j = 1; j < aasworld.numareas; j++) { + if (i == j) + continue; + // never create reachabilities from teleporter or jumppad areas to regular areas + if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD)) { + if (!(aasworld.areasettings[j].contents & (AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD))) { continue; - } //end if - } //end if - //if there already is a reachability link from area i to j - if (AAS_ReachabilityExists(i, j)) continue; - //check for a swim reachability - if (AAS_Reachability_Swim(i, j)) continue; - //check for a simple walk on equal floor height reachability - if (AAS_Reachability_EqualFloorHeight(i, j)) continue; - //check for step, barrier, waterjump and walk off ledge reachabilities - if (AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(i, j)) continue; - //check for ladder reachabilities - if (AAS_Reachability_Ladder(i, j)) continue; - //check for a jump reachability - if (AAS_Reachability_Jump(i, j)) continue; - } //end for - //never create these reachabilities from teleporter or jumppad areas - if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER|AREACONTENTS_JUMPPAD)) - { + } // end if + } // end if + // if there already is a reachability link from area i to j + if (AAS_ReachabilityExists(i, j)) + continue; + // check for a swim reachability + if (AAS_Reachability_Swim(i, j)) + continue; + // check for a simple walk on equal floor height reachability + if (AAS_Reachability_EqualFloorHeight(i, j)) + continue; + // check for step, barrier, waterjump and walk off ledge reachabilities + if (AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge(i, j)) + continue; + // check for ladder reachabilities + if (AAS_Reachability_Ladder(i, j)) + continue; + // check for a jump reachability + if (AAS_Reachability_Jump(i, j)) + continue; + } // end for + // never create these reachabilities from teleporter or jumppad areas + if (aasworld.areasettings[i].contents & (AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD)) { continue; - } //end if - //loop over the areas - for (j = 1; j < aasworld.numareas; j++) - { - if (i == j) continue; + } // end if + // loop over the areas + for (j = 1; j < aasworld.numareas; j++) { + if (i == j) + continue; // - if (AAS_ReachabilityExists(i, j)) continue; - //check for a grapple hook reachability - if (calcgrapplereach) AAS_Reachability_Grapple(i, j); - //check for a weapon jump reachability + if (AAS_ReachabilityExists(i, j)) + continue; + // check for a grapple hook reachability + if (calcgrapplereach) + AAS_Reachability_Grapple(i, j); + // check for a weapon jump reachability AAS_Reachability_WeaponJump(i, j); - } //end for - //if the calculation took more time than the max reachability delay - if (Sys_MilliSeconds() - start_time > (int) reachability_delay) break; + } // end for + // if the calculation took more time than the max reachability delay + if (Sys_MilliSeconds() - start_time > (int)reachability_delay) + break; // - if (aasworld.numreachabilityareas * 1000 / aasworld.numareas > lastpercentage) break; - } //end for + if (aasworld.numreachabilityareas * 1000 / aasworld.numareas > lastpercentage) + break; + } // end for // - if (aasworld.numreachabilityareas == aasworld.numareas) - { - botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float) 100.0); + if (aasworld.numreachabilityareas == aasworld.numareas) { + botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float)100.0); botimport.Print(PRT_MESSAGE, "\nplease wait while storing reachability...\n"); aasworld.numreachabilityareas++; - } //end if - //if this is the last step in the reachability calculations - else if (aasworld.numreachabilityareas == aasworld.numareas + 1) - { - //create additional walk off ledge reachabilities for every area - for (i = 1; i < aasworld.numareas; i++) - { - //only create jumppad reachabilities from jumppad areas - if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) - { + } // end if + // if this is the last step in the reachability calculations + else if (aasworld.numreachabilityareas == aasworld.numareas + 1) { + // create additional walk off ledge reachabilities for every area + for (i = 1; i < aasworld.numareas; i++) { + // only create jumppad reachabilities from jumppad areas + if (aasworld.areasettings[i].contents & AREACONTENTS_JUMPPAD) { continue; - } //end if + } // end if AAS_Reachability_WalkOffLedge(i); - } //end for - //create jump pad reachabilities + } // end for + // create jump pad reachabilities AAS_Reachability_JumpPad(); - //create teleporter reachabilities + // create teleporter reachabilities AAS_Reachability_Teleport(); - //create elevator (func_plat) reachabilities + // create elevator (func_plat) reachabilities AAS_Reachability_Elevator(); - //create func_bobbing reachabilities + // create func_bobbing reachabilities AAS_Reachability_FuncBobbing(); // #ifdef DEBUG @@ -4476,9 +4332,9 @@ int AAS_ContinueInitReachability(float time) botimport.Print(PRT_MESSAGE, "%6d reach jumppad\n", reach_jumppad); #endif //*/ - //store all the reachabilities + // store all the reachabilities AAS_StoreReachability(); - //free the reachability link heap + // free the reachability link heap AAS_ShutDownReachabilityHeap(); // FreeMemory(areareachability); @@ -4486,50 +4342,46 @@ int AAS_ContinueInitReachability(float time) aasworld.numreachabilityareas++; // botimport.Print(PRT_MESSAGE, "calculating clusters...\n"); - } //end if - else - { + } // end if + else { lastpercentage = aasworld.numreachabilityareas * 1000 / aasworld.numareas; - botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float) lastpercentage / 10); - } //end else - //not yet finished + botimport.Print(PRT_MESSAGE, "\r%6.1f%%", (float)lastpercentage / 10); + } // end else + // not yet finished return qtrue; -} //end of the function AAS_ContinueInitReachability +} // end of the function AAS_ContinueInitReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitReachability(void) -{ - if (!aasworld.loaded) return; +void AAS_InitReachability(void) { + if (!aasworld.loaded) + return; - if (aasworld.reachabilitysize) - { + if (aasworld.reachabilitysize) { #ifndef BSPC - if (!((int)LibVarGetValue("forcereachability"))) - { + if (!((int)LibVarGetValue("forcereachability"))) { aasworld.numreachabilityareas = aasworld.numareas + 2; return; - } //end if + } // end if #else aasworld.numreachabilityareas = aasworld.numareas + 2; return; -#endif //BSPC - } //end if +#endif // BSPC + } // end if #ifndef BSPC calcgrapplereach = LibVarGetValue("grapplereach"); #endif aasworld.savefile = qtrue; - //start with area 1 because area zero is a dummy + // start with area 1 because area zero is a dummy aasworld.numreachabilityareas = 1; ////aasworld.numreachabilityareas = aasworld.numareas + 1; //only calculate entity reachabilities - //setup the heap with reachability links + // setup the heap with reachability links AAS_SetupReachabilityHeap(); - //allocate area reachability link array - areareachability = (aas_lreachability_t **) GetClearedMemory( - aasworld.numareas * sizeof(aas_lreachability_t *)); + // allocate area reachability link array + areareachability = (aas_lreachability_t **)GetClearedMemory(aasworld.numareas * sizeof(aas_lreachability_t *)); // AAS_SetWeaponJumpAreaFlags(); -} //end of the function AAS_InitReachable +} // end of the function AAS_InitReachable diff --git a/codemp/botlib/be_aas_route.cpp b/codemp/botlib/be_aas_route.cpp index e00e067909..abfe200ec2 100644 --- a/codemp/botlib/be_aas_route.cpp +++ b/codemp/botlib/be_aas_route.cpp @@ -52,17 +52,16 @@ along with this program; if not, see . #define ROUTING_DEBUG -//travel time in hundreths of a second = distance * 100 / speed -#define DISTANCEFACTOR_CROUCH 1.3f //crouch speed = 100 -#define DISTANCEFACTOR_SWIM 1 //should be 0.66, swim speed = 150 -#define DISTANCEFACTOR_WALK 0.33f //walk speed = 300 +// travel time in hundreths of a second = distance * 100 / speed +#define DISTANCEFACTOR_CROUCH 1.3f // crouch speed = 100 +#define DISTANCEFACTOR_SWIM 1 // should be 0.66, swim speed = 150 +#define DISTANCEFACTOR_WALK 0.33f // walk speed = 300 -//cache refresh time -#define CACHE_REFRESHTIME 15.0f //15 seconds refresh time - -//maximum number of routing updates each frame -#define MAX_FRAMEROUTINGUPDATES 10 +// cache refresh time +#define CACHE_REFRESHTIME 15.0f // 15 seconds refresh time +// maximum number of routing updates each frame +#define MAX_FRAMEROUTINGUPDATES 10 /* @@ -84,7 +83,7 @@ along with this program; if not, see . #ifdef ROUTING_DEBUG int numareacacheupdates; int numportalcacheupdates; -#endif //ROUTING_DEBUG +#endif // ROUTING_DEBUG int routingcachesize; int max_routingcachesize; @@ -96,13 +95,12 @@ int max_routingcachesize; // Changes Globals: - //=========================================================================== #ifdef ROUTING_DEBUG -void AAS_RoutingInfo(void) -{ +void AAS_RoutingInfo(void) { botimport.Print(PRT_MESSAGE, "%d area cache updates\n", numareacacheupdates); botimport.Print(PRT_MESSAGE, "%d portal cache updates\n", numportalcacheupdates); botimport.Print(PRT_MESSAGE, "%d bytes routing cache\n", routingcachesize); -} //end of the function AAS_RoutingInfo -#endif //ROUTING_DEBUG +} // end of the function AAS_RoutingInfo +#endif // ROUTING_DEBUG //=========================================================================== // returns the number of the area in the cluster // assumes the given area is in the given cluster or a portal of the cluster @@ -111,40 +109,37 @@ void AAS_RoutingInfo(void) // Returns: - // Changes Globals: - //=========================================================================== -static QINLINE int AAS_ClusterAreaNum(int cluster, int areanum) -{ +static QINLINE int AAS_ClusterAreaNum(int cluster, int areanum) { int side, areacluster; areacluster = aasworld.areasettings[areanum].cluster; - if (areacluster > 0) return aasworld.areasettings[areanum].clusterareanum; - else - { -/*#ifdef ROUTING_DEBUG - if (aasworld.portals[-areacluster].frontcluster != cluster && - aasworld.portals[-areacluster].backcluster != cluster) - { - botimport.Print(PRT_ERROR, "portal %d: does not belong to cluster %d\n" - , -areacluster, cluster); - } //end if -#endif //ROUTING_DEBUG*/ + if (areacluster > 0) + return aasworld.areasettings[areanum].clusterareanum; + else { + /*#ifdef ROUTING_DEBUG + if (aasworld.portals[-areacluster].frontcluster != cluster && + aasworld.portals[-areacluster].backcluster != cluster) + { + botimport.Print(PRT_ERROR, "portal %d: does not belong to cluster %d\n" + , -areacluster, cluster); + } //end if + #endif //ROUTING_DEBUG*/ side = aasworld.portals[-areacluster].frontcluster != cluster; return aasworld.portals[-areacluster].clusterareanum[side]; - } //end else -} //end of the function AAS_ClusterAreaNum + } // end else +} // end of the function AAS_ClusterAreaNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitTravelFlagFromType(void) -{ +void AAS_InitTravelFlagFromType(void) { int i; - for (i = 0; i < MAX_TRAVELTYPES; i++) - { + for (i = 0; i < MAX_TRAVELTYPES; i++) { aasworld.travelflagfortype[i] = TFL_INVALID; - } //end for + } // end for aasworld.travelflagfortype[TRAVEL_INVALID] = TFL_INVALID; aasworld.travelflagfortype[TRAVEL_WALK] = TFL_WALK; aasworld.travelflagfortype[TRAVEL_CROUCH] = TFL_CROUCH; @@ -164,15 +159,14 @@ void AAS_InitTravelFlagFromType(void) aasworld.travelflagfortype[TRAVEL_STRAFEJUMP] = TFL_STRAFEJUMP; aasworld.travelflagfortype[TRAVEL_JUMPPAD] = TFL_JUMPPAD; aasworld.travelflagfortype[TRAVEL_FUNCBOB] = TFL_FUNCBOB; -} //end of the function AAS_InitTravelFlagFromType +} // end of the function AAS_InitTravelFlagFromType //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -static QINLINE int AAS_TravelFlagForType_inline(int traveltype) -{ +static QINLINE int AAS_TravelFlagForType_inline(int traveltype) { int tfl; tfl = 0; @@ -185,73 +179,68 @@ static QINLINE int AAS_TravelFlagForType_inline(int traveltype) return TFL_INVALID; tfl |= aasworld.travelflagfortype[traveltype]; return tfl; -} //end of the function AAS_TravelFlagForType_inline +} // end of the function AAS_TravelFlagForType_inline //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_TravelFlagForType(int traveltype) -{ - return AAS_TravelFlagForType_inline(traveltype); -} //end of the function AAS_TravelFlagForType_inline +int AAS_TravelFlagForType(int traveltype) { return AAS_TravelFlagForType_inline(traveltype); } // end of the function AAS_TravelFlagForType_inline //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UnlinkCache(aas_routingcache_t *cache) -{ - if (cache->time_next) cache->time_next->time_prev = cache->time_prev; - else aasworld.newestcache = cache->time_prev; - if (cache->time_prev) cache->time_prev->time_next = cache->time_next; - else aasworld.oldestcache = cache->time_next; +void AAS_UnlinkCache(aas_routingcache_t *cache) { + if (cache->time_next) + cache->time_next->time_prev = cache->time_prev; + else + aasworld.newestcache = cache->time_prev; + if (cache->time_prev) + cache->time_prev->time_next = cache->time_next; + else + aasworld.oldestcache = cache->time_next; cache->time_next = NULL; cache->time_prev = NULL; -} //end of the function AAS_UnlinkCache +} // end of the function AAS_UnlinkCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_LinkCache(aas_routingcache_t *cache) -{ - if (aasworld.newestcache) - { +void AAS_LinkCache(aas_routingcache_t *cache) { + if (aasworld.newestcache) { aasworld.newestcache->time_next = cache; cache->time_prev = aasworld.newestcache; - } //end if - else - { + } // end if + else { aasworld.oldestcache = cache; cache->time_prev = NULL; - } //end else + } // end else cache->time_next = NULL; aasworld.newestcache = cache; -} //end of the function AAS_LinkCache +} // end of the function AAS_LinkCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeRoutingCache(aas_routingcache_t *cache) -{ +void AAS_FreeRoutingCache(aas_routingcache_t *cache) { AAS_UnlinkCache(cache); routingcachesize -= cache->size; FreeMemory(cache); -} //end of the function AAS_FreeRoutingCache +} // end of the function AAS_FreeRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_RemoveRoutingCacheInCluster( int clusternum ) -{ +void AAS_RemoveRoutingCacheInCluster(int clusternum) { int i; aas_routingcache_t *cache, *nextcache; aas_cluster_t *cluster; @@ -259,69 +248,59 @@ void AAS_RemoveRoutingCacheInCluster( int clusternum ) if (!aasworld.clusterareacache) return; cluster = &aasworld.clusters[clusternum]; - for (i = 0; i < cluster->numareas; i++) - { - for (cache = aasworld.clusterareacache[clusternum][i]; cache; cache = nextcache) - { + for (i = 0; i < cluster->numareas; i++) { + for (cache = aasworld.clusterareacache[clusternum][i]; cache; cache = nextcache) { nextcache = cache->next; AAS_FreeRoutingCache(cache); - } //end for + } // end for aasworld.clusterareacache[clusternum][i] = NULL; - } //end for -} //end of the function AAS_RemoveRoutingCacheInCluster + } // end for +} // end of the function AAS_RemoveRoutingCacheInCluster //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_RemoveRoutingCacheUsingArea( int areanum ) -{ +void AAS_RemoveRoutingCacheUsingArea(int areanum) { int i, clusternum; aas_routingcache_t *cache, *nextcache; clusternum = aasworld.areasettings[areanum].cluster; - if (clusternum > 0) - { - //remove all the cache in the cluster the area is in - AAS_RemoveRoutingCacheInCluster( clusternum ); - } //end if - else - { + if (clusternum > 0) { + // remove all the cache in the cluster the area is in + AAS_RemoveRoutingCacheInCluster(clusternum); + } // end if + else { // if this is a portal remove all cache in both the front and back cluster - AAS_RemoveRoutingCacheInCluster( aasworld.portals[-clusternum].frontcluster ); - AAS_RemoveRoutingCacheInCluster( aasworld.portals[-clusternum].backcluster ); - } //end else + AAS_RemoveRoutingCacheInCluster(aasworld.portals[-clusternum].frontcluster); + AAS_RemoveRoutingCacheInCluster(aasworld.portals[-clusternum].backcluster); + } // end else // remove all portal cache - for (i = 0; i < aasworld.numareas; i++) - { - //refresh portal cache - for (cache = aasworld.portalcache[i]; cache; cache = nextcache) - { + for (i = 0; i < aasworld.numareas; i++) { + // refresh portal cache + for (cache = aasworld.portalcache[i]; cache; cache = nextcache) { nextcache = cache->next; AAS_FreeRoutingCache(cache); - } //end for + } // end for aasworld.portalcache[i] = NULL; - } //end for -} //end of the function AAS_RemoveRoutingCacheUsingArea + } // end for +} // end of the function AAS_RemoveRoutingCacheUsingArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_EnableRoutingArea(int areanum, int enable) -{ +int AAS_EnableRoutingArea(int areanum, int enable) { int flags; - if (areanum <= 0 || areanum >= aasworld.numareas) - { - if (botDeveloper) - { + if (areanum <= 0 || areanum >= aasworld.numareas) { + if (botDeveloper) { botimport.Print(PRT_ERROR, "AAS_EnableRoutingArea: areanum %d out of range\n", areanum); - } //end if + } // end if return 0; - } //end if + } // end if flags = aasworld.areasettings[areanum].areaflags & AREA_DISABLED; if (enable < 0) return !flags; @@ -331,31 +310,26 @@ int AAS_EnableRoutingArea(int areanum, int enable) else aasworld.areasettings[areanum].areaflags |= AREA_DISABLED; // if the status of the area changed - if ( (flags & AREA_DISABLED) != (aasworld.areasettings[areanum].areaflags & AREA_DISABLED) ) - { - //remove all routing cache involving this area - AAS_RemoveRoutingCacheUsingArea( areanum ); - } //end if + if ((flags & AREA_DISABLED) != (aasworld.areasettings[areanum].areaflags & AREA_DISABLED)) { + // remove all routing cache involving this area + AAS_RemoveRoutingCacheUsingArea(areanum); + } // end if return !flags; -} //end of the function AAS_EnableRoutingArea +} // end of the function AAS_EnableRoutingArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -static QINLINE float AAS_RoutingTime(void) -{ - return AAS_Time(); -} //end of the function AAS_RoutingTime +static QINLINE float AAS_RoutingTime(void) { return AAS_Time(); } // end of the function AAS_RoutingTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_GetAreaContentsTravelFlags(int areanum) -{ +int AAS_GetAreaContentsTravelFlags(int areanum) { int contents, tfl; contents = aasworld.areasettings[areanum].contents; @@ -377,52 +351,47 @@ int AAS_GetAreaContentsTravelFlags(int areanum) if (aasworld.areasettings[areanum].areaflags & AREA_BRIDGE) tfl |= TFL_BRIDGE; return tfl; -} //end of the function AAS_GetAreaContentsTravelFlags +} // end of the function AAS_GetAreaContentsTravelFlags //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -static QINLINE int AAS_AreaContentsTravelFlags_inline(int areanum) -{ +static QINLINE int AAS_AreaContentsTravelFlags_inline(int areanum) { return aasworld.areacontentstravelflags[areanum]; -} //end of the function AAS_AreaContentsTravelFlags +} // end of the function AAS_AreaContentsTravelFlags //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaContentsTravelFlags(int areanum) -{ - return aasworld.areacontentstravelflags[areanum]; -} //end of the function AAS_AreaContentsTravelFlags +int AAS_AreaContentsTravelFlags(int areanum) { return aasworld.areacontentstravelflags[areanum]; } // end of the function AAS_AreaContentsTravelFlags //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitAreaContentsTravelFlags(void) -{ +void AAS_InitAreaContentsTravelFlags(void) { int i; - if (aasworld.areacontentstravelflags) FreeMemory(aasworld.areacontentstravelflags); - aasworld.areacontentstravelflags = (int *) GetClearedMemory(aasworld.numareas * sizeof(int)); + if (aasworld.areacontentstravelflags) + FreeMemory(aasworld.areacontentstravelflags); + aasworld.areacontentstravelflags = (int *)GetClearedMemory(aasworld.numareas * sizeof(int)); // for (i = 0; i < aasworld.numareas; i++) { aasworld.areacontentstravelflags[i] = AAS_GetAreaContentsTravelFlags(i); } -} //end of the function AAS_InitAreaContentsTravelFlags +} // end of the function AAS_InitAreaContentsTravelFlags //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CreateReversedReachability(void) -{ +void AAS_CreateReversedReachability(void) { int i, n; aas_reversedlink_t *revlink; aas_reachability_t *reach; @@ -433,30 +402,28 @@ void AAS_CreateReversedReachability(void) starttime = Sys_MilliSeconds(); #endif - //free reversed links that have already been created - if (aasworld.reversedreachability) FreeMemory(aasworld.reversedreachability); - //allocate memory for the reversed reachability links - ptr = (char *) GetClearedMemory(aasworld.numareas * sizeof(aas_reversedreachability_t) + - aasworld.reachabilitysize * sizeof(aas_reversedlink_t)); + // free reversed links that have already been created + if (aasworld.reversedreachability) + FreeMemory(aasworld.reversedreachability); + // allocate memory for the reversed reachability links + ptr = (char *)GetClearedMemory(aasworld.numareas * sizeof(aas_reversedreachability_t) + aasworld.reachabilitysize * sizeof(aas_reversedlink_t)); // - aasworld.reversedreachability = (aas_reversedreachability_t *) ptr; - //pointer to the memory for the reversed links + aasworld.reversedreachability = (aas_reversedreachability_t *)ptr; + // pointer to the memory for the reversed links ptr += aasworld.numareas * sizeof(aas_reversedreachability_t); - //check all reachabilities of all areas - for (i = 1; i < aasworld.numareas; i++) - { - //settings of the area + // check all reachabilities of all areas + for (i = 1; i < aasworld.numareas; i++) { + // settings of the area settings = &aasworld.areasettings[i]; // if (settings->numreachableareas >= 128) botimport.Print(PRT_WARNING, "area %d has more than 128 reachabilities\n", i); - //create reversed links for the reachabilities - for (n = 0; n < settings->numreachableareas && n < 128; n++) - { - //reachability link + // create reversed links for the reachabilities + for (n = 0; n < settings->numreachableareas && n < 128; n++) { + // reachability link reach = &aasworld.reachability[settings->firstreachablearea + n]; // - revlink = (aas_reversedlink_t *) ptr; + revlink = (aas_reversedlink_t *)ptr; ptr += sizeof(aas_reversedlink_t); // revlink->areanum = i; @@ -464,46 +431,48 @@ void AAS_CreateReversedReachability(void) revlink->next = aasworld.reversedreachability[reach->areanum].first; aasworld.reversedreachability[reach->areanum].first = revlink; aasworld.reversedreachability[reach->areanum].numlinks++; - } //end for - } //end for + } // end for + } // end for #ifdef DEBUG botimport.Print(PRT_MESSAGE, "reversed reachability %d msec\n", Sys_MilliSeconds() - starttime); #endif -} //end of the function AAS_CreateReversedReachability +} // end of the function AAS_CreateReversedReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end) -{ +unsigned short int AAS_AreaTravelTime(int areanum, vec3_t start, vec3_t end) { int intdist; float dist; vec3_t dir; VectorSubtract(start, end, dir); dist = VectorLength(dir); - //if crouch only area - if (AAS_AreaCrouch(areanum)) dist *= DISTANCEFACTOR_CROUCH; - //if swim area - else if (AAS_AreaSwim(areanum)) dist *= DISTANCEFACTOR_SWIM; - //normal walk area - else dist *= DISTANCEFACTOR_WALK; + // if crouch only area + if (AAS_AreaCrouch(areanum)) + dist *= DISTANCEFACTOR_CROUCH; + // if swim area + else if (AAS_AreaSwim(areanum)) + dist *= DISTANCEFACTOR_SWIM; + // normal walk area + else + dist *= DISTANCEFACTOR_WALK; // - intdist = (int) dist; - //make sure the distance isn't zero - if (intdist <= 0) intdist = 1; + intdist = (int)dist; + // make sure the distance isn't zero + if (intdist <= 0) + intdist = 1; return intdist; -} //end of the function AAS_AreaTravelTime +} // end of the function AAS_AreaTravelTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CalculateAreaTravelTimes(void) -{ +void AAS_CalculateAreaTravelTimes(void) { int i, l, n, size; char *ptr; vec3_t end; @@ -516,63 +485,58 @@ void AAS_CalculateAreaTravelTimes(void) starttime = Sys_MilliSeconds(); #endif - //if there are still area travel times, free the memory - if (aasworld.areatraveltimes) FreeMemory(aasworld.areatraveltimes); - //get the total size of all the area travel times + // if there are still area travel times, free the memory + if (aasworld.areatraveltimes) + FreeMemory(aasworld.areatraveltimes); + // get the total size of all the area travel times size = aasworld.numareas * sizeof(unsigned short **); - for (i = 0; i < aasworld.numareas; i++) - { + for (i = 0; i < aasworld.numareas; i++) { revreach = &aasworld.reversedreachability[i]; - //settings of the area + // settings of the area settings = &aasworld.areasettings[i]; // size += settings->numreachableareas * sizeof(unsigned short *); // - size += settings->numreachableareas * - PAD(revreach->numlinks, sizeof(long)) * sizeof(unsigned short); - } //end for - //allocate memory for the area travel times - ptr = (char *) GetClearedMemory(size); - aasworld.areatraveltimes = (unsigned short ***) ptr; + size += settings->numreachableareas * PAD(revreach->numlinks, sizeof(long)) * sizeof(unsigned short); + } // end for + // allocate memory for the area travel times + ptr = (char *)GetClearedMemory(size); + aasworld.areatraveltimes = (unsigned short ***)ptr; ptr += aasworld.numareas * sizeof(unsigned short **); - //calcluate the travel times for all the areas - for (i = 0; i < aasworld.numareas; i++) - { - //reversed reachabilities of this area + // calcluate the travel times for all the areas + for (i = 0; i < aasworld.numareas; i++) { + // reversed reachabilities of this area revreach = &aasworld.reversedreachability[i]; - //settings of the area + // settings of the area settings = &aasworld.areasettings[i]; // - aasworld.areatraveltimes[i] = (unsigned short **) ptr; + aasworld.areatraveltimes[i] = (unsigned short **)ptr; ptr += settings->numreachableareas * sizeof(unsigned short *); // - for (l = 0; l < settings->numreachableareas; l++) - { - aasworld.areatraveltimes[i][l] = (unsigned short *) ptr; + for (l = 0; l < settings->numreachableareas; l++) { + aasworld.areatraveltimes[i][l] = (unsigned short *)ptr; ptr += PAD(revreach->numlinks, sizeof(long)) * sizeof(unsigned short); - //reachability link + // reachability link reach = &aasworld.reachability[settings->firstreachablearea + l]; // - for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++) - { + for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++) { VectorCopy(aasworld.reachability[revlink->linknum].end, end); // aasworld.areatraveltimes[i][l][n] = AAS_AreaTravelTime(i, end, reach->start); - } //end for - } //end for - } //end for + } // end for + } // end for + } // end for #ifdef DEBUG botimport.Print(PRT_MESSAGE, "area travel times %d msec\n", Sys_MilliSeconds() - starttime); #endif -} //end of the function AAS_CalculateAreaTravelTimes +} // end of the function AAS_CalculateAreaTravelTimes //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PortalMaxTravelTime(int portalnum) -{ +int AAS_PortalMaxTravelTime(int portalnum) { int l, n, t, maxt; aas_portal_t *portal; aas_reversedreachability_t *revreach; @@ -580,45 +544,41 @@ int AAS_PortalMaxTravelTime(int portalnum) aas_areasettings_t *settings; portal = &aasworld.portals[portalnum]; - //reversed reachabilities of this portal area + // reversed reachabilities of this portal area revreach = &aasworld.reversedreachability[portal->areanum]; - //settings of the portal area + // settings of the portal area settings = &aasworld.areasettings[portal->areanum]; // maxt = 0; - for (l = 0; l < settings->numreachableareas; l++) - { - for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++) - { + for (l = 0; l < settings->numreachableareas; l++) { + for (n = 0, revlink = revreach->first; revlink; revlink = revlink->next, n++) { t = aasworld.areatraveltimes[portal->areanum][l][n]; - if (t > maxt) - { + if (t > maxt) { maxt = t; - } //end if - } //end for - } //end for + } // end if + } // end for + } // end for return maxt; -} //end of the function AAS_PortalMaxTravelTime +} // end of the function AAS_PortalMaxTravelTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitPortalMaxTravelTimes(void) -{ +void AAS_InitPortalMaxTravelTimes(void) { int i; - if (aasworld.portalmaxtraveltimes) FreeMemory(aasworld.portalmaxtraveltimes); + if (aasworld.portalmaxtraveltimes) + FreeMemory(aasworld.portalmaxtraveltimes); - aasworld.portalmaxtraveltimes = (int *) GetClearedMemory(aasworld.numportals * sizeof(int)); + aasworld.portalmaxtraveltimes = (int *)GetClearedMemory(aasworld.numportals * sizeof(int)); - for (i = 0; i < aasworld.numportals; i++) - { + for (i = 0; i < aasworld.numportals; i++) { aasworld.portalmaxtraveltimes[i] = AAS_PortalMaxTravelTime(i); - //botimport.Print(PRT_MESSAGE, "portal %d max tt = %d\n", i, aasworld.portalmaxtraveltimes[i]); - } //end for -} //end of the function AAS_InitPortalMaxTravelTimes + // botimport.Print(PRT_MESSAGE, "portal %d max tt = %d\n", i, aasworld.portalmaxtraveltimes[i]); + } // end for +} // end of the function AAS_InitPortalMaxTravelTimes //=========================================================================== // // Parameter: - @@ -700,8 +660,7 @@ int AAS_FreeOldestCache(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_FreeOldestCache(void) -{ +int AAS_FreeOldestCache(void) { int clusterareanum; aas_routingcache_t *cache; @@ -715,204 +674,190 @@ int AAS_FreeOldestCache(void) if (cache) { // unlink the cache if (cache->type == CACHETYPE_AREA) { - //number of the area in the cluster + // number of the area in the cluster clusterareanum = AAS_ClusterAreaNum(cache->cluster, cache->areanum); // unlink from cluster area cache - if (cache->prev) cache->prev->next = cache->next; - else aasworld.clusterareacache[cache->cluster][clusterareanum] = cache->next; - if (cache->next) cache->next->prev = cache->prev; - } - else { + if (cache->prev) + cache->prev->next = cache->next; + else + aasworld.clusterareacache[cache->cluster][clusterareanum] = cache->next; + if (cache->next) + cache->next->prev = cache->prev; + } else { // unlink from portal cache - if (cache->prev) cache->prev->next = cache->next; - else aasworld.portalcache[cache->areanum] = cache->next; - if (cache->next) cache->next->prev = cache->prev; + if (cache->prev) + cache->prev->next = cache->next; + else + aasworld.portalcache[cache->areanum] = cache->next; + if (cache->next) + cache->next->prev = cache->prev; } AAS_FreeRoutingCache(cache); return qtrue; } return qfalse; -} //end of the function AAS_FreeOldestCache +} // end of the function AAS_FreeOldestCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_routingcache_t *AAS_AllocRoutingCache(int numtraveltimes) -{ +aas_routingcache_t *AAS_AllocRoutingCache(int numtraveltimes) { aas_routingcache_t *cache; int size; // - size = sizeof(aas_routingcache_t) - + numtraveltimes * sizeof(unsigned short int) - + numtraveltimes * sizeof(unsigned char); + size = sizeof(aas_routingcache_t) + numtraveltimes * sizeof(unsigned short int) + numtraveltimes * sizeof(unsigned char); // routingcachesize += size; // - cache = (aas_routingcache_t *) GetClearedMemory(size); - cache->reachabilities = (unsigned char *) cache + sizeof(aas_routingcache_t) - + numtraveltimes * sizeof(unsigned short int); + cache = (aas_routingcache_t *)GetClearedMemory(size); + cache->reachabilities = (unsigned char *)cache + sizeof(aas_routingcache_t) + numtraveltimes * sizeof(unsigned short int); cache->size = size; return cache; -} //end of the function AAS_AllocRoutingCache +} // end of the function AAS_AllocRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeAllClusterAreaCache(void) -{ +void AAS_FreeAllClusterAreaCache(void) { int i, j; aas_routingcache_t *cache, *nextcache; aas_cluster_t *cluster; - //free all cluster cache if existing - if (!aasworld.clusterareacache) return; - //free caches - for (i = 0; i < aasworld.numclusters; i++) - { + // free all cluster cache if existing + if (!aasworld.clusterareacache) + return; + // free caches + for (i = 0; i < aasworld.numclusters; i++) { cluster = &aasworld.clusters[i]; - for (j = 0; j < cluster->numareas; j++) - { - for (cache = aasworld.clusterareacache[i][j]; cache; cache = nextcache) - { + for (j = 0; j < cluster->numareas; j++) { + for (cache = aasworld.clusterareacache[i][j]; cache; cache = nextcache) { nextcache = cache->next; AAS_FreeRoutingCache(cache); - } //end for + } // end for aasworld.clusterareacache[i][j] = NULL; - } //end for - } //end for - //free the cluster cache array + } // end for + } // end for + // free the cluster cache array FreeMemory(aasworld.clusterareacache); aasworld.clusterareacache = NULL; -} //end of the function AAS_FreeAllClusterAreaCache +} // end of the function AAS_FreeAllClusterAreaCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitClusterAreaCache(void) -{ +void AAS_InitClusterAreaCache(void) { int i, size; char *ptr; // - for (size = 0, i = 0; i < aasworld.numclusters; i++) - { + for (size = 0, i = 0; i < aasworld.numclusters; i++) { size += aasworld.clusters[i].numareas; - } //end for - //two dimensional array with pointers for every cluster to routing cache - //for every area in that cluster - ptr = (char *) GetClearedMemory( - aasworld.numclusters * sizeof(aas_routingcache_t **) + - size * sizeof(aas_routingcache_t *)); - aasworld.clusterareacache = (aas_routingcache_t ***) ptr; + } // end for + // two dimensional array with pointers for every cluster to routing cache + // for every area in that cluster + ptr = (char *)GetClearedMemory(aasworld.numclusters * sizeof(aas_routingcache_t **) + size * sizeof(aas_routingcache_t *)); + aasworld.clusterareacache = (aas_routingcache_t ***)ptr; ptr += aasworld.numclusters * sizeof(aas_routingcache_t **); - for (i = 0; i < aasworld.numclusters; i++) - { - aasworld.clusterareacache[i] = (aas_routingcache_t **) ptr; + for (i = 0; i < aasworld.numclusters; i++) { + aasworld.clusterareacache[i] = (aas_routingcache_t **)ptr; ptr += aasworld.clusters[i].numareas * sizeof(aas_routingcache_t *); - } //end for -} //end of the function AAS_InitClusterAreaCache + } // end for +} // end of the function AAS_InitClusterAreaCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeAllPortalCache(void) -{ +void AAS_FreeAllPortalCache(void) { int i; aas_routingcache_t *cache, *nextcache; - //free all portal cache if existing - if (!aasworld.portalcache) return; - //free portal caches - for (i = 0; i < aasworld.numareas; i++) - { - for (cache = aasworld.portalcache[i]; cache; cache = nextcache) - { + // free all portal cache if existing + if (!aasworld.portalcache) + return; + // free portal caches + for (i = 0; i < aasworld.numareas; i++) { + for (cache = aasworld.portalcache[i]; cache; cache = nextcache) { nextcache = cache->next; AAS_FreeRoutingCache(cache); - } //end for + } // end for aasworld.portalcache[i] = NULL; - } //end for + } // end for FreeMemory(aasworld.portalcache); aasworld.portalcache = NULL; -} //end of the function AAS_FreeAllPortalCache +} // end of the function AAS_FreeAllPortalCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitPortalCache(void) -{ +void AAS_InitPortalCache(void) { // - aasworld.portalcache = (aas_routingcache_t **) GetClearedMemory( - aasworld.numareas * sizeof(aas_routingcache_t *)); -} //end of the function AAS_InitPortalCache + aasworld.portalcache = (aas_routingcache_t **)GetClearedMemory(aasworld.numareas * sizeof(aas_routingcache_t *)); +} // end of the function AAS_InitPortalCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitRoutingUpdate(void) -{ +void AAS_InitRoutingUpdate(void) { int i, maxreachabilityareas; - //free routing update fields if already existing - if (aasworld.areaupdate) FreeMemory(aasworld.areaupdate); + // free routing update fields if already existing + if (aasworld.areaupdate) + FreeMemory(aasworld.areaupdate); // maxreachabilityareas = 0; - for (i = 0; i < aasworld.numclusters; i++) - { - if (aasworld.clusters[i].numreachabilityareas > maxreachabilityareas) - { + for (i = 0; i < aasworld.numclusters; i++) { + if (aasworld.clusters[i].numreachabilityareas > maxreachabilityareas) { maxreachabilityareas = aasworld.clusters[i].numreachabilityareas; - } //end if - } //end for - //allocate memory for the routing update fields - aasworld.areaupdate = (aas_routingupdate_t *) GetClearedMemory( - maxreachabilityareas * sizeof(aas_routingupdate_t)); + } // end if + } // end for + // allocate memory for the routing update fields + aasworld.areaupdate = (aas_routingupdate_t *)GetClearedMemory(maxreachabilityareas * sizeof(aas_routingupdate_t)); // - if (aasworld.portalupdate) FreeMemory(aasworld.portalupdate); - //allocate memory for the portal update fields - aasworld.portalupdate = (aas_routingupdate_t *) GetClearedMemory( - (aasworld.numportals+1) * sizeof(aas_routingupdate_t)); -} //end of the function AAS_InitRoutingUpdate + if (aasworld.portalupdate) + FreeMemory(aasworld.portalupdate); + // allocate memory for the portal update fields + aasworld.portalupdate = (aas_routingupdate_t *)GetClearedMemory((aasworld.numportals + 1) * sizeof(aas_routingupdate_t)); +} // end of the function AAS_InitRoutingUpdate //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_CreateAllRoutingCache(void) -{ +void AAS_CreateAllRoutingCache(void) { int i, j; - //int t; + // int t; aasworld.initialized = qtrue; botimport.Print(PRT_MESSAGE, "AAS_CreateAllRoutingCache\n"); - for (i = 1; i < aasworld.numareas; i++) - { - if (!AAS_AreaReachability(i)) continue; - for (j = 1; j < aasworld.numareas; j++) - { - if (i == j) continue; - if (!AAS_AreaReachability(j)) continue; + for (i = 1; i < aasworld.numareas; i++) { + if (!AAS_AreaReachability(i)) + continue; + for (j = 1; j < aasworld.numareas; j++) { + if (i == j) + continue; + if (!AAS_AreaReachability(j)) + continue; AAS_AreaTravelTimeToGoalArea(i, aasworld.areas[i].center, j, TFL_DEFAULT); - //t = AAS_AreaTravelTimeToGoalArea(i, aasworld.areas[i].center, j, TFL_DEFAULT); - //Log_Write("traveltime from %d to %d is %d", i, j, t); - } //end for - } //end for + // t = AAS_AreaTravelTimeToGoalArea(i, aasworld.areas[i].center, j, TFL_DEFAULT); + // Log_Write("traveltime from %d to %d is %d", i, j, t); + } // end for + } // end for aasworld.initialized = qfalse; -} //end of the function AAS_CreateAllRoutingCache +} // end of the function AAS_CreateAllRoutingCache //=========================================================================== // // Parameter: - @@ -920,11 +865,10 @@ void AAS_CreateAllRoutingCache(void) // Changes Globals: - //=========================================================================== -//the route cache header -//this header is followed by numportalcache + numareacache aas_routingcache_t -//structures that store routing cache -typedef struct routecacheheader_s -{ +// the route cache header +// this header is followed by numportalcache + numareacache aas_routingcache_t +// structures that store routing cache +typedef struct routecacheheader_s { int ident; int version; int numareas; @@ -935,11 +879,10 @@ typedef struct routecacheheader_s int numareacache; } routecacheheader_t; -#define RCID (('C'<<24)+('R'<<16)+('E'<<8)+'M') -#define RCVERSION 2 +#define RCID (('C' << 24) + ('R' << 16) + ('E' << 8) + 'M') +#define RCVERSION 2 -void AAS_WriteRouteCache(void) -{ +void AAS_WriteRouteCache(void) { int i, j, numportalcache, numareacache, totalsize; aas_routingcache_t *cache; aas_cluster_t *cluster; @@ -948,67 +891,56 @@ void AAS_WriteRouteCache(void) routecacheheader_t routecacheheader; numportalcache = 0; - for (i = 0; i < aasworld.numareas; i++) - { - for (cache = aasworld.portalcache[i]; cache; cache = cache->next) - { + for (i = 0; i < aasworld.numareas; i++) { + for (cache = aasworld.portalcache[i]; cache; cache = cache->next) { numportalcache++; - } //end for - } //end for + } // end for + } // end for numareacache = 0; - for (i = 0; i < aasworld.numclusters; i++) - { + for (i = 0; i < aasworld.numclusters; i++) { cluster = &aasworld.clusters[i]; - for (j = 0; j < cluster->numareas; j++) - { - for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next) - { + for (j = 0; j < cluster->numareas; j++) { + for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next) { numareacache++; - } //end for - } //end for - } //end for + } // end for + } // end for + } // end for // open the file for writing Com_sprintf(filename, MAX_QPATH, "maps/%s.rcd", aasworld.mapname); - botimport.FS_FOpenFile( filename, &fp, FS_WRITE ); - if (!fp) - { + botimport.FS_FOpenFile(filename, &fp, FS_WRITE); + if (!fp) { AAS_Error("Unable to open file: %s\n", filename); return; - } //end if - //create the header + } // end if + // create the header routecacheheader.ident = RCID; routecacheheader.version = RCVERSION; routecacheheader.numareas = aasworld.numareas; routecacheheader.numclusters = aasworld.numclusters; - routecacheheader.areacrc = CRC_ProcessString( (unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas ); - routecacheheader.clustercrc = CRC_ProcessString( (unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters ); + routecacheheader.areacrc = CRC_ProcessString((unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas); + routecacheheader.clustercrc = CRC_ProcessString((unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters); routecacheheader.numportalcache = numportalcache; routecacheheader.numareacache = numareacache; - //write the header + // write the header botimport.FS_Write(&routecacheheader, sizeof(routecacheheader_t), fp); // totalsize = 0; - //write all the cache - for (i = 0; i < aasworld.numareas; i++) - { - for (cache = aasworld.portalcache[i]; cache; cache = cache->next) - { + // write all the cache + for (i = 0; i < aasworld.numareas; i++) { + for (cache = aasworld.portalcache[i]; cache; cache = cache->next) { botimport.FS_Write(cache, cache->size, fp); totalsize += cache->size; - } //end for - } //end for - for (i = 0; i < aasworld.numclusters; i++) - { + } // end for + } // end for + for (i = 0; i < aasworld.numclusters; i++) { cluster = &aasworld.clusters[i]; - for (j = 0; j < cluster->numareas; j++) - { - for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next) - { + for (j = 0; j < cluster->numareas; j++) { + for (cache = aasworld.clusterareacache[i][j]; cache; cache = cache->next) { botimport.FS_Write(cache, cache->size, fp); totalsize += cache->size; - } //end for - } //end for - } //end for + } // end for + } // end for + } // end for // write the visareas /* for (i = 0; i < aasworld.numareas; i++) @@ -1028,92 +960,79 @@ void AAS_WriteRouteCache(void) botimport.FS_FCloseFile(fp); botimport.Print(PRT_MESSAGE, "\nroute cache written to %s\n", filename); botimport.Print(PRT_MESSAGE, "written %d bytes of routing cache\n", totalsize); -} //end of the function AAS_WriteRouteCache +} // end of the function AAS_WriteRouteCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_routingcache_t *AAS_ReadCache(fileHandle_t fp) -{ +aas_routingcache_t *AAS_ReadCache(fileHandle_t fp) { int size; aas_routingcache_t *cache; botimport.FS_Read(&size, sizeof(size), fp); - cache = (aas_routingcache_t *) GetMemory(size); + cache = (aas_routingcache_t *)GetMemory(size); cache->size = size; botimport.FS_Read((unsigned char *)cache + sizeof(size), size - sizeof(size), fp); - cache->reachabilities = (unsigned char *) cache + sizeof(aas_routingcache_t) - sizeof(unsigned short) + - (size - sizeof(aas_routingcache_t) + sizeof(unsigned short)) / 3 * 2; + cache->reachabilities = + (unsigned char *)cache + sizeof(aas_routingcache_t) - sizeof(unsigned short) + (size - sizeof(aas_routingcache_t) + sizeof(unsigned short)) / 3 * 2; return cache; -} //end of the function AAS_ReadCache +} // end of the function AAS_ReadCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_ReadRouteCache(void) -{ - int i, clusterareanum;//, size; +int AAS_ReadRouteCache(void) { + int i, clusterareanum; //, size; fileHandle_t fp; char filename[MAX_QPATH]; routecacheheader_t routecacheheader; aas_routingcache_t *cache; Com_sprintf(filename, MAX_QPATH, "maps/%s.rcd", aasworld.mapname); - botimport.FS_FOpenFile( filename, &fp, FS_READ ); - if (!fp) - { + botimport.FS_FOpenFile(filename, &fp, FS_READ); + if (!fp) { return qfalse; - } //end if - botimport.FS_Read(&routecacheheader, sizeof(routecacheheader_t), fp ); - if (routecacheheader.ident != RCID) - { + } // end if + botimport.FS_Read(&routecacheheader, sizeof(routecacheheader_t), fp); + if (routecacheheader.ident != RCID) { AAS_Error("%s is not a route cache dump\n", filename); return qfalse; - } //end if - if (routecacheheader.version != RCVERSION) - { + } // end if + if (routecacheheader.version != RCVERSION) { AAS_Error("route cache dump has wrong version %d, should be %d", routecacheheader.version, RCVERSION); return qfalse; - } //end if - if (routecacheheader.numareas != aasworld.numareas) - { - //AAS_Error("route cache dump has wrong number of areas\n"); + } // end if + if (routecacheheader.numareas != aasworld.numareas) { + // AAS_Error("route cache dump has wrong number of areas\n"); return qfalse; - } //end if - if (routecacheheader.numclusters != aasworld.numclusters) - { - //AAS_Error("route cache dump has wrong number of clusters\n"); + } // end if + if (routecacheheader.numclusters != aasworld.numclusters) { + // AAS_Error("route cache dump has wrong number of clusters\n"); return qfalse; - } //end if - if (routecacheheader.areacrc != - CRC_ProcessString( (unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas )) - { - //AAS_Error("route cache dump area CRC incorrect\n"); + } // end if + if (routecacheheader.areacrc != CRC_ProcessString((unsigned char *)aasworld.areas, sizeof(aas_area_t) * aasworld.numareas)) { + // AAS_Error("route cache dump area CRC incorrect\n"); return qfalse; - } //end if - if (routecacheheader.clustercrc != - CRC_ProcessString( (unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters )) - { - //AAS_Error("route cache dump cluster CRC incorrect\n"); + } // end if + if (routecacheheader.clustercrc != CRC_ProcessString((unsigned char *)aasworld.clusters, sizeof(aas_cluster_t) * aasworld.numclusters)) { + // AAS_Error("route cache dump cluster CRC incorrect\n"); return qfalse; - } //end if - //read all the portal cache - for (i = 0; i < routecacheheader.numportalcache; i++) - { + } // end if + // read all the portal cache + for (i = 0; i < routecacheheader.numportalcache; i++) { cache = AAS_ReadCache(fp); cache->next = aasworld.portalcache[cache->areanum]; cache->prev = NULL; if (aasworld.portalcache[cache->areanum]) aasworld.portalcache[cache->areanum]->prev = cache; aasworld.portalcache[cache->areanum] = cache; - } //end for - //read all the cluster area cache - for (i = 0; i < routecacheheader.numareacache; i++) - { + } // end for + // read all the cluster area cache + for (i = 0; i < routecacheheader.numareacache; i++) { cache = AAS_ReadCache(fp); clusterareanum = AAS_ClusterAreaNum(cache->cluster, cache->areanum); cache->next = aasworld.clusterareacache[cache->cluster][clusterareanum]; @@ -1121,7 +1040,7 @@ int AAS_ReadRouteCache(void) if (aasworld.clusterareacache[cache->cluster][clusterareanum]) aasworld.clusterareacache[cache->cluster][clusterareanum]->prev = cache; aasworld.clusterareacache[cache->cluster][clusterareanum] = cache; - } //end for + } // end for // read the visareas /* aasworld.areavisibility = (byte **) GetClearedMemory(aasworld.numareas * sizeof(byte *)); @@ -1138,17 +1057,16 @@ int AAS_ReadRouteCache(void) // botimport.FS_FCloseFile(fp); return qtrue; -} //end of the function AAS_ReadRouteCache +} // end of the function AAS_ReadRouteCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -#define MAX_REACHABILITYPASSAREAS 32 +#define MAX_REACHABILITYPASSAREAS 32 -void AAS_InitReachabilityAreas(void) -{ +void AAS_InitReachabilityAreas(void) { int i, j, numareas, areas[MAX_REACHABILITYPASSAREAS]; int numreachareas; aas_reachability_t *reach; @@ -1159,132 +1077,145 @@ void AAS_InitReachabilityAreas(void) if (aasworld.reachabilityareaindex) FreeMemory(aasworld.reachabilityareaindex); - aasworld.reachabilityareas = (aas_reachabilityareas_t *) - GetClearedMemory(aasworld.reachabilitysize * sizeof(aas_reachabilityareas_t)); - aasworld.reachabilityareaindex = (int *) - GetClearedMemory(aasworld.reachabilitysize * MAX_REACHABILITYPASSAREAS * sizeof(int)); + aasworld.reachabilityareas = (aas_reachabilityareas_t *)GetClearedMemory(aasworld.reachabilitysize * sizeof(aas_reachabilityareas_t)); + aasworld.reachabilityareaindex = (int *)GetClearedMemory(aasworld.reachabilitysize * MAX_REACHABILITYPASSAREAS * sizeof(int)); numreachareas = 0; - for (i = 0; i < aasworld.reachabilitysize; i++) - { + for (i = 0; i < aasworld.reachabilitysize; i++) { reach = &aasworld.reachability[i]; numareas = 0; - switch(reach->traveltype & TRAVELTYPE_MASK) - { - //trace areas from start to end - case TRAVEL_BARRIERJUMP: - case TRAVEL_WATERJUMP: - VectorCopy(reach->start, end); - end[2] = reach->end[2]; - numareas = AAS_TraceAreas(reach->start, end, areas, NULL, MAX_REACHABILITYPASSAREAS); - break; - case TRAVEL_WALKOFFLEDGE: - VectorCopy(reach->end, start); - start[2] = reach->start[2]; - numareas = AAS_TraceAreas(start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS); - break; - case TRAVEL_GRAPPLEHOOK: - numareas = AAS_TraceAreas(reach->start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS); - break; - - //trace arch - case TRAVEL_JUMP: break; - case TRAVEL_ROCKETJUMP: break; - case TRAVEL_BFGJUMP: break; - case TRAVEL_JUMPPAD: break; - - //trace from reach->start to entity center, along entity movement - //and from entity center to reach->end - case TRAVEL_ELEVATOR: break; - case TRAVEL_FUNCBOB: break; - - //no areas in between - case TRAVEL_WALK: break; - case TRAVEL_CROUCH: break; - case TRAVEL_LADDER: break; - case TRAVEL_SWIM: break; - case TRAVEL_TELEPORT: break; - default: break; - } //end switch + switch (reach->traveltype & TRAVELTYPE_MASK) { + // trace areas from start to end + case TRAVEL_BARRIERJUMP: + case TRAVEL_WATERJUMP: + VectorCopy(reach->start, end); + end[2] = reach->end[2]; + numareas = AAS_TraceAreas(reach->start, end, areas, NULL, MAX_REACHABILITYPASSAREAS); + break; + case TRAVEL_WALKOFFLEDGE: + VectorCopy(reach->end, start); + start[2] = reach->start[2]; + numareas = AAS_TraceAreas(start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS); + break; + case TRAVEL_GRAPPLEHOOK: + numareas = AAS_TraceAreas(reach->start, reach->end, areas, NULL, MAX_REACHABILITYPASSAREAS); + break; + + // trace arch + case TRAVEL_JUMP: + break; + case TRAVEL_ROCKETJUMP: + break; + case TRAVEL_BFGJUMP: + break; + case TRAVEL_JUMPPAD: + break; + + // trace from reach->start to entity center, along entity movement + // and from entity center to reach->end + case TRAVEL_ELEVATOR: + break; + case TRAVEL_FUNCBOB: + break; + + // no areas in between + case TRAVEL_WALK: + break; + case TRAVEL_CROUCH: + break; + case TRAVEL_LADDER: + break; + case TRAVEL_SWIM: + break; + case TRAVEL_TELEPORT: + break; + default: + break; + } // end switch aasworld.reachabilityareas[i].firstarea = numreachareas; aasworld.reachabilityareas[i].numareas = numareas; - for (j = 0; j < numareas; j++) - { + for (j = 0; j < numareas; j++) { aasworld.reachabilityareaindex[numreachareas++] = areas[j]; - } //end for - } //end for -} //end of the function AAS_InitReachabilityAreas + } // end for + } // end for +} // end of the function AAS_InitReachabilityAreas //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitRouting(void) -{ +void AAS_InitRouting(void) { AAS_InitTravelFlagFromType(); // AAS_InitAreaContentsTravelFlags(); - //initialize the routing update fields + // initialize the routing update fields AAS_InitRoutingUpdate(); - //create reversed reachability links used by the routing update algorithm + // create reversed reachability links used by the routing update algorithm AAS_CreateReversedReachability(); - //initialize the cluster cache + // initialize the cluster cache AAS_InitClusterAreaCache(); - //initialize portal cache + // initialize portal cache AAS_InitPortalCache(); - //initialize the area travel times + // initialize the area travel times AAS_CalculateAreaTravelTimes(); - //calculate the maximum travel times through portals + // calculate the maximum travel times through portals AAS_InitPortalMaxTravelTimes(); - //get the areas reachabilities go through + // get the areas reachabilities go through AAS_InitReachabilityAreas(); // #ifdef ROUTING_DEBUG numareacacheupdates = 0; numportalcacheupdates = 0; -#endif //ROUTING_DEBUG +#endif // ROUTING_DEBUG // routingcachesize = 0; - max_routingcachesize = 1024 * (int) LibVarValue("max_routingcache", "4096"); + max_routingcachesize = 1024 * (int)LibVarValue("max_routingcache", "4096"); // read any routing cache if available AAS_ReadRouteCache(); -} //end of the function AAS_InitRouting +} // end of the function AAS_InitRouting //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeRoutingCaches(void) -{ +void AAS_FreeRoutingCaches(void) { // free all the existing cluster area cache AAS_FreeAllClusterAreaCache(); // free all the existing portal cache AAS_FreeAllPortalCache(); // free cached travel times within areas - if (aasworld.areatraveltimes) FreeMemory(aasworld.areatraveltimes); + if (aasworld.areatraveltimes) + FreeMemory(aasworld.areatraveltimes); aasworld.areatraveltimes = NULL; // free cached maximum travel time through cluster portals - if (aasworld.portalmaxtraveltimes) FreeMemory(aasworld.portalmaxtraveltimes); + if (aasworld.portalmaxtraveltimes) + FreeMemory(aasworld.portalmaxtraveltimes); aasworld.portalmaxtraveltimes = NULL; // free reversed reachability links - if (aasworld.reversedreachability) FreeMemory(aasworld.reversedreachability); + if (aasworld.reversedreachability) + FreeMemory(aasworld.reversedreachability); aasworld.reversedreachability = NULL; // free routing algorithm memory - if (aasworld.areaupdate) FreeMemory(aasworld.areaupdate); + if (aasworld.areaupdate) + FreeMemory(aasworld.areaupdate); aasworld.areaupdate = NULL; - if (aasworld.portalupdate) FreeMemory(aasworld.portalupdate); + if (aasworld.portalupdate) + FreeMemory(aasworld.portalupdate); aasworld.portalupdate = NULL; // free lists with areas the reachabilities go through - if (aasworld.reachabilityareas) FreeMemory(aasworld.reachabilityareas); + if (aasworld.reachabilityareas) + FreeMemory(aasworld.reachabilityareas); aasworld.reachabilityareas = NULL; // free the reachability area index - if (aasworld.reachabilityareaindex) FreeMemory(aasworld.reachabilityareaindex); + if (aasworld.reachabilityareaindex) + FreeMemory(aasworld.reachabilityareaindex); aasworld.reachabilityareaindex = NULL; // free area contents travel flags look up table - if (aasworld.areacontentstravelflags) FreeMemory(aasworld.areacontentstravelflags); + if (aasworld.areacontentstravelflags) + FreeMemory(aasworld.areacontentstravelflags); aasworld.areacontentstravelflags = NULL; -} //end of the function AAS_FreeRoutingCaches +} // end of the function AAS_FreeRoutingCaches //=========================================================================== // update the given routing cache // @@ -1292,11 +1223,10 @@ void AAS_FreeRoutingCaches(void) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UpdateAreaRoutingCache(aas_routingcache_t *areacache) -{ +void AAS_UpdateAreaRoutingCache(aas_routingcache_t *areacache) { int i, nextareanum, cluster, badtravelflags, clusterareanum, linknum; int numreachabilityareas; - unsigned short int t, startareatraveltimes[128]; //NOTE: not more than 128 reachabilities per area allowed + unsigned short int t, startareatraveltimes[128]; // NOTE: not more than 128 reachabilities per area allowed aas_routingupdate_t *updateliststart, *updatelistend, *curupdate, *nextupdate; aas_reachability_t *reach; aas_reversedreachability_t *revreach; @@ -1304,123 +1234,124 @@ void AAS_UpdateAreaRoutingCache(aas_routingcache_t *areacache) #ifdef ROUTING_DEBUG numareacacheupdates++; -#endif //ROUTING_DEBUG - //number of reachability areas within this cluster +#endif // ROUTING_DEBUG + // number of reachability areas within this cluster numreachabilityareas = aasworld.clusters[areacache->cluster].numreachabilityareas; // aasworld.frameroutingupdates++; - //clear the routing update fields -// Com_Memset(aasworld.areaupdate, 0, aasworld.numareas * sizeof(aas_routingupdate_t)); + // clear the routing update fields + // Com_Memset(aasworld.areaupdate, 0, aasworld.numareas * sizeof(aas_routingupdate_t)); // badtravelflags = ~areacache->travelflags; // clusterareanum = AAS_ClusterAreaNum(areacache->cluster, areacache->areanum); - if (clusterareanum >= numreachabilityareas) return; + if (clusterareanum >= numreachabilityareas) + return; // Com_Memset(startareatraveltimes, 0, sizeof(startareatraveltimes)); // curupdate = &aasworld.areaupdate[clusterareanum]; curupdate->areanum = areacache->areanum; - //VectorCopy(areacache->origin, curupdate->start); + // VectorCopy(areacache->origin, curupdate->start); curupdate->areatraveltimes = startareatraveltimes; curupdate->tmptraveltime = areacache->starttraveltime; // areacache->traveltimes[clusterareanum] = areacache->starttraveltime; - //put the area to start with in the current read list + // put the area to start with in the current read list curupdate->next = NULL; curupdate->prev = NULL; updateliststart = curupdate; updatelistend = curupdate; - //while there are updates in the current list - while (updateliststart) - { + // while there are updates in the current list + while (updateliststart) { curupdate = updateliststart; // - if (curupdate->next) curupdate->next->prev = NULL; - else updatelistend = NULL; + if (curupdate->next) + curupdate->next->prev = NULL; + else + updatelistend = NULL; updateliststart = curupdate->next; // curupdate->inlist = qfalse; - //check all reversed reachability links + // check all reversed reachability links revreach = &aasworld.reversedreachability[curupdate->areanum]; // - for (i = 0, revlink = revreach->first; revlink; revlink = revlink->next, i++) - { + for (i = 0, revlink = revreach->first; revlink; revlink = revlink->next, i++) { linknum = revlink->linknum; reach = &aasworld.reachability[linknum]; - //if there is used an undesired travel type - if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) continue; - //if not allowed to enter the next area - if (aasworld.areasettings[reach->areanum].areaflags & AREA_DISABLED) continue; - //if the next area has a not allowed travel flag - if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) continue; - //number of the area the reversed reachability leads to + // if there is used an undesired travel type + if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) + continue; + // if not allowed to enter the next area + if (aasworld.areasettings[reach->areanum].areaflags & AREA_DISABLED) + continue; + // if the next area has a not allowed travel flag + if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) + continue; + // number of the area the reversed reachability leads to nextareanum = revlink->areanum; - //get the cluster number of the area + // get the cluster number of the area cluster = aasworld.areasettings[nextareanum].cluster; - //don't leave the cluster - if (cluster > 0 && cluster != areacache->cluster) continue; - //get the number of the area in the cluster + // don't leave the cluster + if (cluster > 0 && cluster != areacache->cluster) + continue; + // get the number of the area in the cluster clusterareanum = AAS_ClusterAreaNum(areacache->cluster, nextareanum); - if (clusterareanum >= numreachabilityareas) continue; - //time already travelled plus the traveltime through - //the current area plus the travel time from the reachability + if (clusterareanum >= numreachabilityareas) + continue; + // time already travelled plus the traveltime through + // the current area plus the travel time from the reachability t = curupdate->tmptraveltime + - //AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->end) + - curupdate->areatraveltimes[i] + - reach->traveltime; + // AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->end) + + curupdate->areatraveltimes[i] + reach->traveltime; // - if (!areacache->traveltimes[clusterareanum] || - areacache->traveltimes[clusterareanum] > t) - { + if (!areacache->traveltimes[clusterareanum] || areacache->traveltimes[clusterareanum] > t) { areacache->traveltimes[clusterareanum] = t; areacache->reachabilities[clusterareanum] = linknum - aasworld.areasettings[nextareanum].firstreachablearea; nextupdate = &aasworld.areaupdate[clusterareanum]; nextupdate->areanum = nextareanum; nextupdate->tmptraveltime = t; - //VectorCopy(reach->start, nextupdate->start); - nextupdate->areatraveltimes = aasworld.areatraveltimes[nextareanum][linknum - - aasworld.areasettings[nextareanum].firstreachablearea]; - if (!nextupdate->inlist) - { + // VectorCopy(reach->start, nextupdate->start); + nextupdate->areatraveltimes = aasworld.areatraveltimes[nextareanum][linknum - aasworld.areasettings[nextareanum].firstreachablearea]; + if (!nextupdate->inlist) { // we add the update to the end of the list // we could also use a B+ tree to have a real sorted list // on travel time which makes for faster routing updates nextupdate->next = NULL; nextupdate->prev = updatelistend; - if (updatelistend) updatelistend->next = nextupdate; - else updateliststart = nextupdate; + if (updatelistend) + updatelistend->next = nextupdate; + else + updateliststart = nextupdate; updatelistend = nextupdate; nextupdate->inlist = qtrue; - } //end if - } //end if - } //end for - } //end while -} //end of the function AAS_UpdateAreaRoutingCache + } // end if + } // end if + } // end for + } // end while +} // end of the function AAS_UpdateAreaRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_routingcache_t *AAS_GetAreaRoutingCache(int clusternum, int areanum, int travelflags) -{ +aas_routingcache_t *AAS_GetAreaRoutingCache(int clusternum, int areanum, int travelflags) { int clusterareanum; aas_routingcache_t *cache, *clustercache; - //number of the area in the cluster + // number of the area in the cluster clusterareanum = AAS_ClusterAreaNum(clusternum, areanum); - //pointer to the cache for the area in the cluster + // pointer to the cache for the area in the cluster clustercache = aasworld.clusterareacache[clusternum][clusterareanum]; - //find the cache without undesired travel flags - for (cache = clustercache; cache; cache = cache->next) - { - //if there aren't used any undesired travel types for the cache - if (cache->travelflags == travelflags) break; - } //end for - //if there was no cache - if (!cache) - { + // find the cache without undesired travel flags + for (cache = clustercache; cache; cache = cache->next) { + // if there aren't used any undesired travel types for the cache + if (cache->travelflags == travelflags) + break; + } // end for + // if there was no cache + if (!cache) { cache = AAS_AllocRoutingCache(aasworld.clusters[clusternum].numreachabilityareas); cache->cluster = clusternum; cache->areanum = areanum; @@ -1429,28 +1360,27 @@ aas_routingcache_t *AAS_GetAreaRoutingCache(int clusternum, int areanum, int tra cache->travelflags = travelflags; cache->prev = NULL; cache->next = clustercache; - if (clustercache) clustercache->prev = cache; + if (clustercache) + clustercache->prev = cache; aasworld.clusterareacache[clusternum][clusterareanum] = cache; AAS_UpdateAreaRoutingCache(cache); - } //end if - else - { + } // end if + else { AAS_UnlinkCache(cache); - } //end else - //the cache has been accessed + } // end else + // the cache has been accessed cache->time = AAS_RoutingTime(); cache->type = CACHETYPE_AREA; AAS_LinkCache(cache); return cache; -} //end of the function AAS_GetAreaRoutingCache +} // end of the function AAS_GetAreaRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UpdatePortalRoutingCache(aas_routingcache_t *portalcache) -{ +void AAS_UpdatePortalRoutingCache(aas_routingcache_t *portalcache) { int i, portalnum, clusterareanum, clusternum; unsigned short int t; aas_portal_t *portal; @@ -1460,137 +1390,132 @@ void AAS_UpdatePortalRoutingCache(aas_routingcache_t *portalcache) #ifdef ROUTING_DEBUG numportalcacheupdates++; -#endif //ROUTING_DEBUG - //clear the routing update fields -// Com_Memset(aasworld.portalupdate, 0, (aasworld.numportals+1) * sizeof(aas_routingupdate_t)); +#endif // ROUTING_DEBUG + // clear the routing update fields + // Com_Memset(aasworld.portalupdate, 0, (aasworld.numportals+1) * sizeof(aas_routingupdate_t)); // curupdate = &aasworld.portalupdate[aasworld.numportals]; curupdate->cluster = portalcache->cluster; curupdate->areanum = portalcache->areanum; curupdate->tmptraveltime = portalcache->starttraveltime; - //if the start area is a cluster portal, store the travel time for that portal + // if the start area is a cluster portal, store the travel time for that portal clusternum = aasworld.areasettings[portalcache->areanum].cluster; - if (clusternum < 0) - { + if (clusternum < 0) { portalcache->traveltimes[-clusternum] = portalcache->starttraveltime; - } //end if - //put the area to start with in the current read list + } // end if + // put the area to start with in the current read list curupdate->next = NULL; curupdate->prev = NULL; updateliststart = curupdate; updatelistend = curupdate; - //while there are updates in the current list - while (updateliststart) - { + // while there are updates in the current list + while (updateliststart) { curupdate = updateliststart; - //remove the current update from the list - if (curupdate->next) curupdate->next->prev = NULL; - else updatelistend = NULL; + // remove the current update from the list + if (curupdate->next) + curupdate->next->prev = NULL; + else + updatelistend = NULL; updateliststart = curupdate->next; - //current update is removed from the list + // current update is removed from the list curupdate->inlist = qfalse; // cluster = &aasworld.clusters[curupdate->cluster]; // - cache = AAS_GetAreaRoutingCache(curupdate->cluster, - curupdate->areanum, portalcache->travelflags); - //take all portals of the cluster - for (i = 0; i < cluster->numportals; i++) - { + cache = AAS_GetAreaRoutingCache(curupdate->cluster, curupdate->areanum, portalcache->travelflags); + // take all portals of the cluster + for (i = 0; i < cluster->numportals; i++) { portalnum = aasworld.portalindex[cluster->firstportal + i]; portal = &aasworld.portals[portalnum]; - //if this is the portal of the current update continue - if (portal->areanum == curupdate->areanum) continue; + // if this is the portal of the current update continue + if (portal->areanum == curupdate->areanum) + continue; // clusterareanum = AAS_ClusterAreaNum(curupdate->cluster, portal->areanum); - if (clusterareanum >= cluster->numreachabilityareas) continue; + if (clusterareanum >= cluster->numreachabilityareas) + continue; // t = cache->traveltimes[clusterareanum]; - if (!t) continue; + if (!t) + continue; t += curupdate->tmptraveltime; // - if (!portalcache->traveltimes[portalnum] || - portalcache->traveltimes[portalnum] > t) - { + if (!portalcache->traveltimes[portalnum] || portalcache->traveltimes[portalnum] > t) { portalcache->traveltimes[portalnum] = t; nextupdate = &aasworld.portalupdate[portalnum]; - if (portal->frontcluster == curupdate->cluster) - { + if (portal->frontcluster == curupdate->cluster) { nextupdate->cluster = portal->backcluster; - } //end if - else - { + } // end if + else { nextupdate->cluster = portal->frontcluster; - } //end else + } // end else nextupdate->areanum = portal->areanum; - //add travel time through the actual portal area for the next update + // add travel time through the actual portal area for the next update nextupdate->tmptraveltime = t + aasworld.portalmaxtraveltimes[portalnum]; - if (!nextupdate->inlist) - { + if (!nextupdate->inlist) { // we add the update to the end of the list // we could also use a B+ tree to have a real sorted list // on travel time which makes for faster routing updates nextupdate->next = NULL; nextupdate->prev = updatelistend; - if (updatelistend) updatelistend->next = nextupdate; - else updateliststart = nextupdate; + if (updatelistend) + updatelistend->next = nextupdate; + else + updateliststart = nextupdate; updatelistend = nextupdate; nextupdate->inlist = qtrue; - } //end if - } //end if - } //end for - } //end while -} //end of the function AAS_UpdatePortalRoutingCache + } // end if + } // end if + } // end for + } // end while +} // end of the function AAS_UpdatePortalRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_routingcache_t *AAS_GetPortalRoutingCache(int clusternum, int areanum, int travelflags) -{ +aas_routingcache_t *AAS_GetPortalRoutingCache(int clusternum, int areanum, int travelflags) { aas_routingcache_t *cache; - //find the cached portal routing if existing - for (cache = aasworld.portalcache[areanum]; cache; cache = cache->next) - { - if (cache->travelflags == travelflags) break; - } //end for - //if the portal routing isn't cached - if (!cache) - { + // find the cached portal routing if existing + for (cache = aasworld.portalcache[areanum]; cache; cache = cache->next) { + if (cache->travelflags == travelflags) + break; + } // end for + // if the portal routing isn't cached + if (!cache) { cache = AAS_AllocRoutingCache(aasworld.numportals); cache->cluster = clusternum; cache->areanum = areanum; VectorCopy(aasworld.areas[areanum].center, cache->origin); cache->starttraveltime = 1; cache->travelflags = travelflags; - //add the cache to the cache list + // add the cache to the cache list cache->prev = NULL; cache->next = aasworld.portalcache[areanum]; - if (aasworld.portalcache[areanum]) aasworld.portalcache[areanum]->prev = cache; + if (aasworld.portalcache[areanum]) + aasworld.portalcache[areanum]->prev = cache; aasworld.portalcache[areanum] = cache; - //update the cache + // update the cache AAS_UpdatePortalRoutingCache(cache); - } //end if - else - { + } // end if + else { AAS_UnlinkCache(cache); - } //end else - //the cache has been accessed + } // end else + // the cache has been accessed cache->time = AAS_RoutingTime(); cache->type = CACHETYPE_PORTAL; AAS_LinkCache(cache); return cache; -} //end of the function AAS_GetPortalRoutingCache +} // end of the function AAS_GetPortalRoutingCache //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaRouteToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags, int *traveltime, int *reachnum) -{ +int AAS_AreaRouteToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags, int *traveltime, int *reachnum) { int clusternum, goalclusternum, portalnum, i, clusterareanum, bestreachnum; unsigned short int t, besttime; aas_portal_t *portal; @@ -1598,41 +1523,37 @@ int AAS_AreaRouteToGoalArea(int areanum, vec3_t origin, int goalareanum, int tra aas_routingcache_t *areacache, *portalcache; aas_reachability_t *reach; - if (!aasworld.initialized) return qfalse; + if (!aasworld.initialized) + return qfalse; - if (areanum == goalareanum) - { + if (areanum == goalareanum) { *traveltime = 1; *reachnum = 0; return qtrue; } // - if (areanum <= 0 || areanum >= aasworld.numareas) - { - if (botDeveloper) - { + if (areanum <= 0 || areanum >= aasworld.numareas) { + if (botDeveloper) { botimport.Print(PRT_ERROR, "AAS_AreaTravelTimeToGoalArea: areanum %d out of range\n", areanum); - } //end if + } // end if return qfalse; - } //end if - if (goalareanum <= 0 || goalareanum >= aasworld.numareas) - { - if (botDeveloper) - { + } // end if + if (goalareanum <= 0 || goalareanum >= aasworld.numareas) { + if (botDeveloper) { botimport.Print(PRT_ERROR, "AAS_AreaTravelTimeToGoalArea: goalareanum %d out of range\n", goalareanum); - } //end if + } // end if return qfalse; - } //end if + } // end if // make sure the routing cache doesn't grow to large - while(AvailableMemory() < 1 * 1024 * 1024) { - if (!AAS_FreeOldestCache()) break; + while (AvailableMemory() < 1 * 1024 * 1024) { + if (!AAS_FreeOldestCache()) + break; } // - if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goalareanum)) - { + if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goalareanum)) { travelflags |= TFL_DONOTENTER; - } //end if - //NOTE: the number of routing updates is limited per frame + } // end if + // NOTE: the number of routing updates is limited per frame /* if (aasworld.frameroutingupdates > MAX_FRAMEROUTINGUPDATES) { @@ -1645,158 +1566,141 @@ int AAS_AreaRouteToGoalArea(int areanum, vec3_t origin, int goalareanum, int tra // clusternum = aasworld.areasettings[areanum].cluster; goalclusternum = aasworld.areasettings[goalareanum].cluster; - //check if the area is a portal of the goal area cluster - if (clusternum < 0 && goalclusternum > 0) - { + // check if the area is a portal of the goal area cluster + if (clusternum < 0 && goalclusternum > 0) { portal = &aasworld.portals[-clusternum]; - if (portal->frontcluster == goalclusternum || - portal->backcluster == goalclusternum) - { + if (portal->frontcluster == goalclusternum || portal->backcluster == goalclusternum) { clusternum = goalclusternum; - } //end if - } //end if - //check if the goalarea is a portal of the area cluster - else if (clusternum > 0 && goalclusternum < 0) - { + } // end if + } // end if + // check if the goalarea is a portal of the area cluster + else if (clusternum > 0 && goalclusternum < 0) { portal = &aasworld.portals[-goalclusternum]; - if (portal->frontcluster == clusternum || - portal->backcluster == clusternum) - { + if (portal->frontcluster == clusternum || portal->backcluster == clusternum) { goalclusternum = clusternum; - } //end if - } //end if - //if both areas are in the same cluster - //NOTE: there might be a shorter route via another cluster!!! but we don't care - if (clusternum > 0 && goalclusternum > 0 && clusternum == goalclusternum) - { + } // end if + } // end if + // if both areas are in the same cluster + // NOTE: there might be a shorter route via another cluster!!! but we don't care + if (clusternum > 0 && goalclusternum > 0 && clusternum == goalclusternum) { // areacache = AAS_GetAreaRoutingCache(clusternum, goalareanum, travelflags); - //the number of the area in the cluster + // the number of the area in the cluster clusterareanum = AAS_ClusterAreaNum(clusternum, areanum); - //the cluster the area is in + // the cluster the area is in cluster = &aasworld.clusters[clusternum]; - //if the area is NOT a reachability area - if (clusterareanum >= cluster->numreachabilityareas) return 0; - //if it is possible to travel to the goal area through this cluster - if (areacache->traveltimes[clusterareanum] != 0) - { - *reachnum = aasworld.areasettings[areanum].firstreachablearea + - areacache->reachabilities[clusterareanum]; + // if the area is NOT a reachability area + if (clusterareanum >= cluster->numreachabilityareas) + return 0; + // if it is possible to travel to the goal area through this cluster + if (areacache->traveltimes[clusterareanum] != 0) { + *reachnum = aasworld.areasettings[areanum].firstreachablearea + areacache->reachabilities[clusterareanum]; if (!origin) { *traveltime = areacache->traveltimes[clusterareanum]; return qtrue; } reach = &aasworld.reachability[*reachnum]; - *traveltime = areacache->traveltimes[clusterareanum] + - AAS_AreaTravelTime(areanum, origin, reach->start); + *traveltime = areacache->traveltimes[clusterareanum] + AAS_AreaTravelTime(areanum, origin, reach->start); // return qtrue; - } //end if - } //end if + } // end if + } // end if // clusternum = aasworld.areasettings[areanum].cluster; goalclusternum = aasworld.areasettings[goalareanum].cluster; - //if the goal area is a portal - if (goalclusternum < 0) - { - //just assume the goal area is part of the front cluster + // if the goal area is a portal + if (goalclusternum < 0) { + // just assume the goal area is part of the front cluster portal = &aasworld.portals[-goalclusternum]; goalclusternum = portal->frontcluster; - } //end if - //get the portal routing cache + } // end if + // get the portal routing cache portalcache = AAS_GetPortalRoutingCache(goalclusternum, goalareanum, travelflags); - //if the area is a cluster portal, read directly from the portal cache - if (clusternum < 0) - { + // if the area is a cluster portal, read directly from the portal cache + if (clusternum < 0) { *traveltime = portalcache->traveltimes[-clusternum]; - *reachnum = aasworld.areasettings[areanum].firstreachablearea + - portalcache->reachabilities[-clusternum]; + *reachnum = aasworld.areasettings[areanum].firstreachablearea + portalcache->reachabilities[-clusternum]; return qtrue; - } //end if + } // end if // besttime = 0; bestreachnum = -1; - //the cluster the area is in + // the cluster the area is in cluster = &aasworld.clusters[clusternum]; - //find the portal of the area cluster leading towards the goal area - for (i = 0; i < cluster->numportals; i++) - { + // find the portal of the area cluster leading towards the goal area + for (i = 0; i < cluster->numportals; i++) { portalnum = aasworld.portalindex[cluster->firstportal + i]; - //if the goal area isn't reachable from the portal - if (!portalcache->traveltimes[portalnum]) continue; + // if the goal area isn't reachable from the portal + if (!portalcache->traveltimes[portalnum]) + continue; // portal = &aasworld.portals[portalnum]; - //get the cache of the portal area + // get the cache of the portal area areacache = AAS_GetAreaRoutingCache(clusternum, portal->areanum, travelflags); - //current area inside the current cluster + // current area inside the current cluster clusterareanum = AAS_ClusterAreaNum(clusternum, areanum); - //if the area is NOT a reachability area - if (clusterareanum >= cluster->numreachabilityareas) continue; - //if the portal is NOT reachable from this area - if (!areacache->traveltimes[clusterareanum]) continue; - //total travel time is the travel time the portal area is from - //the goal area plus the travel time towards the portal area + // if the area is NOT a reachability area + if (clusterareanum >= cluster->numreachabilityareas) + continue; + // if the portal is NOT reachable from this area + if (!areacache->traveltimes[clusterareanum]) + continue; + // total travel time is the travel time the portal area is from + // the goal area plus the travel time towards the portal area t = portalcache->traveltimes[portalnum] + areacache->traveltimes[clusterareanum]; - //FIXME: add the exact travel time through the actual portal area - //NOTE: for now we just add the largest travel time through the portal area + // FIXME: add the exact travel time through the actual portal area + // NOTE: for now we just add the largest travel time through the portal area // because we can't directly calculate the exact travel time // to be more specific we don't know which reachability was used to travel // into the portal area t += aasworld.portalmaxtraveltimes[portalnum]; // - if (origin) - { - *reachnum = aasworld.areasettings[areanum].firstreachablearea + - areacache->reachabilities[clusterareanum]; + if (origin) { + *reachnum = aasworld.areasettings[areanum].firstreachablearea + areacache->reachabilities[clusterareanum]; reach = aasworld.reachability + *reachnum; t += AAS_AreaTravelTime(areanum, origin, reach->start); - } //end if - //if the time is better than the one already found - if (!besttime || t < besttime) - { + } // end if + // if the time is better than the one already found + if (!besttime || t < besttime) { bestreachnum = *reachnum; besttime = t; - } //end if - } //end for + } // end if + } // end for if (bestreachnum < 0) { return qfalse; } *reachnum = bestreachnum; *traveltime = besttime; return qtrue; -} //end of the function AAS_AreaRouteToGoalArea +} // end of the function AAS_AreaRouteToGoalArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) -{ +int AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) { int traveltime, reachnum = 0; - if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum)) - { + if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum)) { return traveltime; } return 0; -} //end of the function AAS_AreaTravelTimeToGoalArea +} // end of the function AAS_AreaTravelTimeToGoalArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaReachabilityToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) -{ +int AAS_AreaReachabilityToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) { int traveltime, reachnum = 0; - if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum)) - { + if (AAS_AreaRouteToGoalArea(areanum, origin, goalareanum, travelflags, &traveltime, &reachnum)) { return reachnum; } return 0; -} //end of the function AAS_AreaReachabilityToGoalArea +} // end of the function AAS_AreaReachabilityToGoalArea //=========================================================================== // predict the route and stop on one of the stop events // @@ -1804,16 +1708,14 @@ int AAS_AreaReachabilityToGoalArea(int areanum, vec3_t origin, int goalareanum, // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origin, - int goalareanum, int travelflags, int maxareas, int maxtime, - int stopevent, int stopcontents, int stoptfl, int stopareanum) -{ +int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, + int stopcontents, int stoptfl, int stopareanum) { int curareanum, reachnum, i, j, testareanum; vec3_t curorigin; aas_reachability_t *reach; aas_reachabilityareas_t *reachareas; - //init output + // init output route->stopevent = RSE_NONE; route->endarea = goalareanum; route->endcontents = 0; @@ -1824,29 +1726,24 @@ int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origi curareanum = areanum; VectorCopy(origin, curorigin); - for (i = 0; curareanum != goalareanum && (!maxareas || i < maxareas) && i < aasworld.numareas; i++) - { + for (i = 0; curareanum != goalareanum && (!maxareas || i < maxareas) && i < aasworld.numareas; i++) { reachnum = AAS_AreaReachabilityToGoalArea(curareanum, curorigin, goalareanum, travelflags); - if (!reachnum) - { + if (!reachnum) { route->stopevent = RSE_NOROUTE; return qfalse; - } //end if + } // end if reach = &aasworld.reachability[reachnum]; // - if (stopevent & RSE_USETRAVELTYPE) - { - if (AAS_TravelFlagForType_inline(reach->traveltype) & stoptfl) - { + if (stopevent & RSE_USETRAVELTYPE) { + if (AAS_TravelFlagForType_inline(reach->traveltype) & stoptfl) { route->stopevent = RSE_USETRAVELTYPE; route->endarea = curareanum; route->endcontents = aasworld.areasettings[curareanum].contents; route->endtravelflags = AAS_TravelFlagForType_inline(reach->traveltype); VectorCopy(reach->start, route->endpos); return qtrue; - } //end if - if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & stoptfl) - { + } // end if + if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & stoptfl) { route->stopevent = RSE_USETRAVELTYPE; route->endarea = reach->areanum; route->endcontents = aasworld.areasettings[reach->areanum].contents; @@ -1855,19 +1752,16 @@ int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origi route->time += AAS_AreaTravelTime(areanum, origin, reach->start); route->time += reach->traveltime; return qtrue; - } //end if - } //end if + } // end if + } // end if reachareas = &aasworld.reachabilityareas[reachnum]; - for (j = 0; j < reachareas->numareas + 1; j++) - { + for (j = 0; j < reachareas->numareas + 1; j++) { if (j >= reachareas->numareas) testareanum = reach->areanum; else testareanum = aasworld.reachabilityareaindex[reachareas->firstarea + j]; - if (stopevent & RSE_ENTERCONTENTS) - { - if (aasworld.areasettings[testareanum].contents & stopcontents) - { + if (stopevent & RSE_ENTERCONTENTS) { + if (aasworld.areasettings[testareanum].contents & stopcontents) { route->stopevent = RSE_ENTERCONTENTS; route->endarea = testareanum; route->endcontents = aasworld.areasettings[testareanum].contents; @@ -1875,20 +1769,18 @@ int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origi route->time += AAS_AreaTravelTime(areanum, origin, reach->start); route->time += reach->traveltime; return qtrue; - } //end if - } //end if - if (stopevent & RSE_ENTERAREA) - { - if (testareanum == stopareanum) - { + } // end if + } // end if + if (stopevent & RSE_ENTERAREA) { + if (testareanum == stopareanum) { route->stopevent = RSE_ENTERAREA; route->endarea = testareanum; route->endcontents = aasworld.areasettings[testareanum].contents; VectorCopy(reach->start, route->endpos); return qtrue; - } //end if - } //end if - } //end for + } // end if + } // end if + } // end for route->time += AAS_AreaTravelTime(areanum, origin, reach->start); route->time += reach->traveltime; @@ -1902,190 +1794,173 @@ int AAS_PredictRoute(struct aas_predictroute_s *route, int areanum, vec3_t origi // if (maxtime && route->time > maxtime) break; - } //end while + } // end while if (curareanum != goalareanum) return qfalse; return qtrue; -} //end of the function AAS_PredictRoute +} // end of the function AAS_PredictRoute //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BridgeWalkable(int areanum) -{ - return qfalse; -} //end of the function AAS_BridgeWalkable +int AAS_BridgeWalkable(int areanum) { return qfalse; } // end of the function AAS_BridgeWalkable //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ReachabilityFromNum(int num, struct aas_reachability_s *reach) -{ - if (!aasworld.initialized) - { +void AAS_ReachabilityFromNum(int num, struct aas_reachability_s *reach) { + if (!aasworld.initialized) { Com_Memset(reach, 0, sizeof(aas_reachability_t)); return; - } //end if - if (num < 0 || num >= aasworld.reachabilitysize) - { + } // end if + if (num < 0 || num >= aasworld.reachabilitysize) { Com_Memset(reach, 0, sizeof(aas_reachability_t)); return; - } //end if - Com_Memcpy(reach, &aasworld.reachability[num], sizeof(aas_reachability_t));; -} //end of the function AAS_ReachabilityFromNum + } // end if + Com_Memcpy(reach, &aasworld.reachability[num], sizeof(aas_reachability_t)); + ; +} // end of the function AAS_ReachabilityFromNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NextAreaReachability(int areanum, int reachnum) -{ +int AAS_NextAreaReachability(int areanum, int reachnum) { aas_areasettings_t *settings; - if (!aasworld.initialized) return 0; + if (!aasworld.initialized) + return 0; - if (areanum <= 0 || areanum >= aasworld.numareas) - { + if (areanum <= 0 || areanum >= aasworld.numareas) { botimport.Print(PRT_ERROR, "AAS_NextAreaReachability: areanum %d out of range\n", areanum); return 0; - } //end if + } // end if settings = &aasworld.areasettings[areanum]; - if (!reachnum) - { + if (!reachnum) { return settings->firstreachablearea; - } //end if - if (reachnum < settings->firstreachablearea) - { + } // end if + if (reachnum < settings->firstreachablearea) { botimport.Print(PRT_FATAL, "AAS_NextAreaReachability: reachnum < settings->firstreachableara"); return 0; - } //end if + } // end if reachnum++; - if (reachnum >= settings->firstreachablearea + settings->numreachableareas) - { + if (reachnum >= settings->firstreachablearea + settings->numreachableareas) { return 0; - } //end if + } // end if return reachnum; -} //end of the function AAS_NextAreaReachability +} // end of the function AAS_NextAreaReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NextModelReachability(int num, int modelnum) -{ +int AAS_NextModelReachability(int num, int modelnum) { int i; - if (num <= 0) num = 1; - else if (num >= aasworld.reachabilitysize) return 0; - else num++; + if (num <= 0) + num = 1; + else if (num >= aasworld.reachabilitysize) + return 0; + else + num++; // - for (i = num; i < aasworld.reachabilitysize; i++) - { - if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) - { - if (aasworld.reachability[i].facenum == modelnum) return i; - } //end if - else if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) - { - if ((aasworld.reachability[i].facenum & 0x0000FFFF) == modelnum) return i; - } //end if - } //end for + for (i = num; i < aasworld.reachabilitysize; i++) { + if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) { + if (aasworld.reachability[i].facenum == modelnum) + return i; + } // end if + else if ((aasworld.reachability[i].traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) { + if ((aasworld.reachability[i].facenum & 0x0000FFFF) == modelnum) + return i; + } // end if + } // end for return 0; -} //end of the function AAS_NextModelReachability +} // end of the function AAS_NextModelReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_RandomGoalArea(int areanum, int travelflags, int *goalareanum, vec3_t goalorigin) -{ +int AAS_RandomGoalArea(int areanum, int travelflags, int *goalareanum, vec3_t goalorigin) { int i, n, t; vec3_t start, end; aas_trace_t trace; - //if the area has no reachabilities - if (!AAS_AreaReachability(areanum)) return qfalse; + // if the area has no reachabilities + if (!AAS_AreaReachability(areanum)) + return qfalse; // n = aasworld.numareas * Q_flrand(0.0f, 1.0f); - for (i = 0; i < aasworld.numareas; i++) - { - if (n <= 0) n = 1; - if (n >= aasworld.numareas) n = 1; - if (AAS_AreaReachability(n)) - { + for (i = 0; i < aasworld.numareas; i++) { + if (n <= 0) + n = 1; + if (n >= aasworld.numareas) + n = 1; + if (AAS_AreaReachability(n)) { t = AAS_AreaTravelTimeToGoalArea(areanum, aasworld.areas[areanum].center, n, travelflags); - //if the goal is reachable - if (t > 0) - { - if (AAS_AreaSwim(n)) - { + // if the goal is reachable + if (t > 0) { + if (AAS_AreaSwim(n)) { *goalareanum = n; VectorCopy(aasworld.areas[n].center, goalorigin); - //botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum); + // botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum); return qtrue; - } //end if + } // end if VectorCopy(aasworld.areas[n].center, start); if (!AAS_PointAreaNum(start)) Log_Write("area %d center %f %f %f in solid?", n, start[0], start[1], start[2]); VectorCopy(start, end); end[2] -= 300; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1); - if (!trace.startsolid && trace.fraction < 1 && AAS_PointAreaNum(trace.endpos) == n) - { - if (AAS_AreaGroundFaceArea(n) > 300) - { + if (!trace.startsolid && trace.fraction < 1 && AAS_PointAreaNum(trace.endpos) == n) { + if (AAS_AreaGroundFaceArea(n) > 300) { *goalareanum = n; VectorCopy(trace.endpos, goalorigin); - //botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum); + // botimport.Print(PRT_MESSAGE, "found random goal area %d\n", *goalareanum); return qtrue; - } //end if - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if + } // end if n++; - } //end for + } // end for return qfalse; -} //end of the function AAS_RandomGoalArea +} // end of the function AAS_RandomGoalArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaVisible(int srcarea, int destarea) -{ - return qfalse; -} //end of the function AAS_AreaVisible +int AAS_AreaVisible(int srcarea, int destarea) { return qfalse; } // end of the function AAS_AreaVisible //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float DistancePointToLine(vec3_t v1, vec3_t v2, vec3_t point) -{ +float DistancePointToLine(vec3_t v1, vec3_t v2, vec3_t point) { vec3_t vec, p2; AAS_ProjectPointOntoVector(point, v1, v2, p2); VectorSubtract(point, p2, vec); return VectorLength(vec); -} //end of the function DistancePointToLine +} // end of the function DistancePointToLine //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, vec3_t enemyorigin, int enemyareanum, int travelflags) -{ +int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, vec3_t enemyorigin, int enemyareanum, int travelflags) { int i, j, nextareanum, badtravelflags, numreach, bestarea; unsigned short int t, besttraveltime; static unsigned short int *hidetraveltimes; @@ -2096,17 +1971,15 @@ int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, ve qboolean startVisible; // - if (!hidetraveltimes) - { - hidetraveltimes = (unsigned short int *) GetClearedMemory(aasworld.numareas * sizeof(unsigned short int)); - } //end if - else - { + if (!hidetraveltimes) { + hidetraveltimes = (unsigned short int *)GetClearedMemory(aasworld.numareas * sizeof(unsigned short int)); + } // end if + else { Com_Memset(hidetraveltimes, 0, aasworld.numareas * sizeof(unsigned short int)); - } //end else + } // end else besttraveltime = 0; bestarea = 0; - //assume visible + // assume visible startVisible = qtrue; // badtravelflags = ~travelflags; @@ -2116,64 +1989,62 @@ int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, ve VectorCopy(origin, curupdate->start); curupdate->areatraveltimes = aasworld.areatraveltimes[areanum][0]; curupdate->tmptraveltime = 0; - //put the area to start with in the current read list + // put the area to start with in the current read list curupdate->next = NULL; curupdate->prev = NULL; updateliststart = curupdate; updatelistend = curupdate; - //while there are updates in the list - while (updateliststart) - { + // while there are updates in the list + while (updateliststart) { curupdate = updateliststart; // - if (curupdate->next) curupdate->next->prev = NULL; - else updatelistend = NULL; + if (curupdate->next) + curupdate->next->prev = NULL; + else + updatelistend = NULL; updateliststart = curupdate->next; // curupdate->inlist = qfalse; - //check all reversed reachability links + // check all reversed reachability links numreach = aasworld.areasettings[curupdate->areanum].numreachableareas; reach = &aasworld.reachability[aasworld.areasettings[curupdate->areanum].firstreachablearea]; // - for (i = 0; i < numreach; i++, reach++) - { - //if an undesired travel type is used - if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) continue; + for (i = 0; i < numreach; i++, reach++) { + // if an undesired travel type is used + if (AAS_TravelFlagForType_inline(reach->traveltype) & badtravelflags) + continue; // - if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) continue; - //number of the area the reachability leads to + if (AAS_AreaContentsTravelFlags_inline(reach->areanum) & badtravelflags) + continue; + // number of the area the reachability leads to nextareanum = reach->areanum; // if this moves us into the enemies area, skip it - if (nextareanum == enemyareanum) continue; - //time already travelled plus the traveltime through - //the current area plus the travel time from the reachability - t = curupdate->tmptraveltime + - AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->start) + - reach->traveltime; + if (nextareanum == enemyareanum) + continue; + // time already travelled plus the traveltime through + // the current area plus the travel time from the reachability + t = curupdate->tmptraveltime + AAS_AreaTravelTime(curupdate->areanum, curupdate->start, reach->start) + reach->traveltime; - //avoid going near the enemy + // avoid going near the enemy AAS_ProjectPointOntoVector(enemyorigin, curupdate->start, reach->end, p); for (j = 0; j < 3; j++) - if ((p[j] > curupdate->start[j] && p[j] > reach->end[j]) || - (p[j] < curupdate->start[j] && p[j] < reach->end[j])) + if ((p[j] > curupdate->start[j] && p[j] > reach->end[j]) || (p[j] < curupdate->start[j] && p[j] < reach->end[j])) break; - if (j < 3) - { + if (j < 3) { VectorSubtract(enemyorigin, reach->end, v2); - } //end if - else - { + } // end if + else { VectorSubtract(enemyorigin, p, v2); - } //end else + } // end else dist2 = VectorLength(v2); - //never go through the enemy - if (dist2 < 40) continue; + // never go through the enemy + if (dist2 < 40) + continue; // VectorSubtract(enemyorigin, curupdate->start, v1); dist1 = VectorLength(v1); // - if (dist2 < dist1) - { + if (dist2 < dist1) { t += (dist1 - dist2) * 10; } // if we weren't visible when starting, make sure we don't move into their view @@ -2181,36 +2052,35 @@ int AAS_NearestHideArea(int srcnum, vec3_t origin, int areanum, int enemynum, ve continue; } // - if (besttraveltime && t >= besttraveltime) continue; + if (besttraveltime && t >= besttraveltime) + continue; // - if (!hidetraveltimes[nextareanum] || - hidetraveltimes[nextareanum] > t) - { - //if the nextarea is not visible from the enemy area - if (!AAS_AreaVisible(enemyareanum, nextareanum)) - { + if (!hidetraveltimes[nextareanum] || hidetraveltimes[nextareanum] > t) { + // if the nextarea is not visible from the enemy area + if (!AAS_AreaVisible(enemyareanum, nextareanum)) { besttraveltime = t; bestarea = nextareanum; - } //end if + } // end if hidetraveltimes[nextareanum] = t; nextupdate = &aasworld.areaupdate[nextareanum]; nextupdate->areanum = nextareanum; nextupdate->tmptraveltime = t; - //remember where we entered this area + // remember where we entered this area VectorCopy(reach->end, nextupdate->start); - //if this update is not in the list yet - if (!nextupdate->inlist) - { - //add the new update to the end of the list + // if this update is not in the list yet + if (!nextupdate->inlist) { + // add the new update to the end of the list nextupdate->next = NULL; nextupdate->prev = updatelistend; - if (updatelistend) updatelistend->next = nextupdate; - else updateliststart = nextupdate; + if (updatelistend) + updatelistend->next = nextupdate; + else + updateliststart = nextupdate; updatelistend = nextupdate; nextupdate->inlist = qtrue; - } //end if - } //end if - } //end for - } //end while + } // end if + } // end if + } // end for + } // end while return bestarea; -} //end of the function AAS_NearestHideArea +} // end of the function AAS_NearestHideArea diff --git a/codemp/botlib/be_aas_routealt.cpp b/codemp/botlib/be_aas_routealt.cpp index 4017597f61..80e7484c55 100644 --- a/codemp/botlib/be_aas_routealt.cpp +++ b/codemp/botlib/be_aas_routealt.cpp @@ -51,8 +51,7 @@ along with this program; if not, see . #define ENABLE_ALTROUTING //#define ALTROUTE_DEBUG -typedef struct midrangearea_s -{ +typedef struct midrangearea_s { int valid; unsigned short starttime; unsigned short goaltime; @@ -68,43 +67,43 @@ int numclusterareas; // Returns: - // Changes Globals: - //=========================================================================== -void AAS_AltRoutingFloodCluster_r(int areanum) -{ +void AAS_AltRoutingFloodCluster_r(int areanum) { int i, otherareanum; aas_area_t *area; aas_face_t *face; - //add the current area to the areas of the current cluster + // add the current area to the areas of the current cluster clusterareas[numclusterareas] = areanum; numclusterareas++; - //remove the area from the mid range areas + // remove the area from the mid range areas midrangeareas[areanum].valid = qfalse; - //flood to other areas through the faces of this area + // flood to other areas through the faces of this area area = &aasworld.areas[areanum]; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { face = &aasworld.faces[abs(aasworld.faceindex[area->firstface + i])]; - //get the area at the other side of the face - if (face->frontarea == areanum) otherareanum = face->backarea; - else otherareanum = face->frontarea; - //if there is an area at the other side of this face - if (!otherareanum) continue; - //if the other area is not a midrange area - if (!midrangeareas[otherareanum].valid) continue; + // get the area at the other side of the face + if (face->frontarea == areanum) + otherareanum = face->backarea; + else + otherareanum = face->frontarea; + // if there is an area at the other side of this face + if (!otherareanum) + continue; + // if the other area is not a midrange area + if (!midrangeareas[otherareanum].valid) + continue; // AAS_AltRoutingFloodCluster_r(otherareanum); - } //end for -} //end of the function AAS_AltRoutingFloodCluster_r + } // end for +} // end of the function AAS_AltRoutingFloodCluster_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, - aas_altroutegoal_t *altroutegoals, int maxaltroutegoals, - int type) -{ +int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, aas_altroutegoal_t *altroutegoals, + int maxaltroutegoals, int type) { #ifndef ENABLE_ALTROUTING return 0; #else @@ -121,125 +120,124 @@ int AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int g if (!startareanum || !goalareanum) return 0; - //travel time towards the goal area + // travel time towards the goal area goaltraveltime = AAS_AreaTravelTimeToGoalArea(startareanum, start, goalareanum, travelflags); - //clear the midrange areas + // clear the midrange areas Com_Memset(midrangeareas, 0, aasworld.numareas * sizeof(midrangearea_t)); numaltroutegoals = 0; // nummidrangeareas = 0; // - for (i = 1; i < aasworld.numareas; i++) - { + for (i = 1; i < aasworld.numareas; i++) { // - if (!(type & ALTROUTEGOAL_ALL)) - { - if (!(type & ALTROUTEGOAL_CLUSTERPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL))) - { - if (!(type & ALTROUTEGOAL_VIEWPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL))) - { + if (!(type & ALTROUTEGOAL_ALL)) { + if (!(type & ALTROUTEGOAL_CLUSTERPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_CLUSTERPORTAL))) { + if (!(type & ALTROUTEGOAL_VIEWPORTALS && (aasworld.areasettings[i].contents & AREACONTENTS_VIEWPORTAL))) { continue; - } //end if - } //end if - } //end if - //if the area has no reachabilities - if (!AAS_AreaReachability(i)) continue; - //tavel time from the area to the start area + } // end if + } // end if + } // end if + // if the area has no reachabilities + if (!AAS_AreaReachability(i)) + continue; + // tavel time from the area to the start area starttime = AAS_AreaTravelTimeToGoalArea(startareanum, start, i, travelflags); - if (!starttime) continue; - //if the travel time from the start to the area is greater than the shortest goal travel time - if (starttime > (float) 1.1 * goaltraveltime) continue; - //travel time from the area to the goal area + if (!starttime) + continue; + // if the travel time from the start to the area is greater than the shortest goal travel time + if (starttime > (float)1.1 * goaltraveltime) + continue; + // travel time from the area to the goal area goaltime = AAS_AreaTravelTimeToGoalArea(i, NULL, goalareanum, travelflags); - if (!goaltime) continue; - //if the travel time from the area to the goal is greater than the shortest goal travel time - if (goaltime > (float) 0.8 * goaltraveltime) continue; - //this is a mid range area + if (!goaltime) + continue; + // if the travel time from the area to the goal is greater than the shortest goal travel time + if (goaltime > (float)0.8 * goaltraveltime) + continue; + // this is a mid range area midrangeareas[i].valid = qtrue; midrangeareas[i].starttime = starttime; midrangeareas[i].goaltime = goaltime; Log_Write("%d midrange area %d", nummidrangeareas, i); nummidrangeareas++; - } //end for + } // end for // - for (i = 1; i < aasworld.numareas; i++) - { - if (!midrangeareas[i].valid) continue; - //get the areas in one cluster + for (i = 1; i < aasworld.numareas; i++) { + if (!midrangeareas[i].valid) + continue; + // get the areas in one cluster numclusterareas = 0; AAS_AltRoutingFloodCluster_r(i); - //now we've got a cluster with areas through which an alternative route could go - //get the 'center' of the cluster + // now we've got a cluster with areas through which an alternative route could go + // get the 'center' of the cluster VectorClear(mid); - for (j = 0; j < numclusterareas; j++) - { + for (j = 0; j < numclusterareas; j++) { VectorAdd(mid, aasworld.areas[clusterareas[j]].center, mid); - } //end for + } // end for VectorScale(mid, 1.0 / numclusterareas, mid); - //get the area closest to the center of the cluster + // get the area closest to the center of the cluster bestdist = 999999; bestareanum = 0; - for (j = 0; j < numclusterareas; j++) - { + for (j = 0; j < numclusterareas; j++) { VectorSubtract(mid, aasworld.areas[clusterareas[j]].center, dir); dist = VectorLength(dir); - if (dist < bestdist) - { + if (dist < bestdist) { bestdist = dist; bestareanum = clusterareas[j]; - } //end if - } //end for - //now we've got an area for an alternative route - //FIXME: add alternative goal origin + } // end if + } // end for + // now we've got an area for an alternative route + // FIXME: add alternative goal origin VectorCopy(aasworld.areas[bestareanum].center, altroutegoals[numaltroutegoals].origin); altroutegoals[numaltroutegoals].areanum = bestareanum; altroutegoals[numaltroutegoals].starttraveltime = midrangeareas[bestareanum].starttime; altroutegoals[numaltroutegoals].goaltraveltime = midrangeareas[bestareanum].goaltime; - altroutegoals[numaltroutegoals].extratraveltime = - (midrangeareas[bestareanum].starttime + midrangeareas[bestareanum].goaltime) - - goaltraveltime; + altroutegoals[numaltroutegoals].extratraveltime = (midrangeareas[bestareanum].starttime + midrangeareas[bestareanum].goaltime) - goaltraveltime; numaltroutegoals++; // #ifdef ALTROUTE_DEBUG AAS_ShowAreaPolygons(bestareanum, 1, qtrue); #endif - //don't return more than the maximum alternative route goals - if (numaltroutegoals >= maxaltroutegoals) break; - } //end for + // don't return more than the maximum alternative route goals + if (numaltroutegoals >= maxaltroutegoals) + break; + } // end for #ifdef ALTROUTE_DEBUG botimport.Print(PRT_MESSAGE, "alternative route goals in %d msec\n", Sys_MilliSeconds() - startmillisecs); #endif return numaltroutegoals; #endif -} //end of the function AAS_AlternativeRouteGoals +} // end of the function AAS_AlternativeRouteGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitAlternativeRouting(void) -{ +void AAS_InitAlternativeRouting(void) { #ifdef ENABLE_ALTROUTING - if (midrangeareas) FreeMemory(midrangeareas); - midrangeareas = (midrangearea_t *) GetMemory(aasworld.numareas * sizeof(midrangearea_t)); - if (clusterareas) FreeMemory(clusterareas); - clusterareas = (int *) GetMemory(aasworld.numareas * sizeof(int)); + if (midrangeareas) + FreeMemory(midrangeareas); + midrangeareas = (midrangearea_t *)GetMemory(aasworld.numareas * sizeof(midrangearea_t)); + if (clusterareas) + FreeMemory(clusterareas); + clusterareas = (int *)GetMemory(aasworld.numareas * sizeof(int)); #endif -} //end of the function AAS_InitAlternativeRouting +} // end of the function AAS_InitAlternativeRouting //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_ShutdownAlternativeRouting(void) -{ +void AAS_ShutdownAlternativeRouting(void) { #ifdef ENABLE_ALTROUTING - if (midrangeareas) FreeMemory(midrangeareas); + if (midrangeareas) + FreeMemory(midrangeareas); midrangeareas = NULL; - if (clusterareas) FreeMemory(clusterareas); + if (clusterareas) + FreeMemory(clusterareas); clusterareas = NULL; numclusterareas = 0; #endif -} //end of the function AAS_ShutdownAlternativeRouting +} // end of the function AAS_ShutdownAlternativeRouting diff --git a/codemp/botlib/be_aas_sample.cpp b/codemp/botlib/be_aas_sample.cpp index 64d8cdabb1..30da4f1fae 100644 --- a/codemp/botlib/be_aas_sample.cpp +++ b/codemp/botlib/be_aas_sample.cpp @@ -53,18 +53,17 @@ extern botlib_import_t botimport; //#define AAS_SAMPLE_DEBUG -#define BBOX_NORMAL_EPSILON 0.001 +#define BBOX_NORMAL_EPSILON 0.001 -#define ON_EPSILON 0 //0.0005 +#define ON_EPSILON 0 // 0.0005 -#define TRACEPLANE_EPSILON 0.125 +#define TRACEPLANE_EPSILON 0.125 -typedef struct aas_tracestack_s -{ - vec3_t start; //start point of the piece of line to trace - vec3_t end; //end point of the piece of line to trace - int planenum; //last plane used as splitter - int nodenum; //node found after splitting with planenum +typedef struct aas_tracestack_s { + vec3_t start; // start point of the piece of line to trace + vec3_t end; // end point of the piece of line to trace + int planenum; // last plane used as splitter + int nodenum; // node found after splitting with planenum } aas_tracestack_t; int numaaslinks; @@ -75,139 +74,137 @@ int numaaslinks; // Returns: - // Changes Globals: - //=========================================================================== -void AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) -{ +void AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) { int index; - //bounding box size for each presence type + // bounding box size for each presence type vec3_t boxmins[3] = {{0, 0, 0}, {-15, -15, -24}, {-15, -15, -24}}; - vec3_t boxmaxs[3] = {{0, 0, 0}, { 15, 15, 32}, { 15, 15, 8}}; + vec3_t boxmaxs[3] = {{0, 0, 0}, {15, 15, 32}, {15, 15, 8}}; - if (presencetype == PRESENCE_NORMAL) index = 1; - else if (presencetype == PRESENCE_CROUCH) index = 2; - else - { + if (presencetype == PRESENCE_NORMAL) + index = 1; + else if (presencetype == PRESENCE_CROUCH) + index = 2; + else { botimport.Print(PRT_FATAL, "AAS_PresenceTypeBoundingBox: unknown presence type\n"); index = 2; - } //end if + } // end if VectorCopy(boxmins[index], mins); VectorCopy(boxmaxs[index], maxs); -} //end of the function AAS_PresenceTypeBoundingBox +} // end of the function AAS_PresenceTypeBoundingBox //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitAASLinkHeap(void) -{ +void AAS_InitAASLinkHeap(void) { int i, max_aaslinks; max_aaslinks = aasworld.linkheapsize; - //if there's no link heap present - if (!aasworld.linkheap) - { + // if there's no link heap present + if (!aasworld.linkheap) { #ifdef BSPC max_aaslinks = 6144; #else - max_aaslinks = (int) LibVarValue("max_aaslinks", "6144"); + max_aaslinks = (int)LibVarValue("max_aaslinks", "6144"); #endif - if (max_aaslinks < 0) max_aaslinks = 0; + if (max_aaslinks < 0) + max_aaslinks = 0; aasworld.linkheapsize = max_aaslinks; - aasworld.linkheap = (aas_link_t *) GetHunkMemory(max_aaslinks * sizeof(aas_link_t)); - } //end if - //link the links on the heap + aasworld.linkheap = (aas_link_t *)GetHunkMemory(max_aaslinks * sizeof(aas_link_t)); + } // end if + // link the links on the heap aasworld.linkheap[0].prev_ent = NULL; aasworld.linkheap[0].next_ent = &aasworld.linkheap[1]; - for (i = 1; i < max_aaslinks-1; i++) - { + for (i = 1; i < max_aaslinks - 1; i++) { aasworld.linkheap[i].prev_ent = &aasworld.linkheap[i - 1]; aasworld.linkheap[i].next_ent = &aasworld.linkheap[i + 1]; - } //end for - aasworld.linkheap[max_aaslinks-1].prev_ent = &aasworld.linkheap[max_aaslinks-2]; - aasworld.linkheap[max_aaslinks-1].next_ent = NULL; - //pointer to the first free link + } // end for + aasworld.linkheap[max_aaslinks - 1].prev_ent = &aasworld.linkheap[max_aaslinks - 2]; + aasworld.linkheap[max_aaslinks - 1].next_ent = NULL; + // pointer to the first free link aasworld.freelinks = &aasworld.linkheap[0]; // numaaslinks = max_aaslinks; -} //end of the function AAS_InitAASLinkHeap +} // end of the function AAS_InitAASLinkHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeAASLinkHeap(void) -{ - if (aasworld.linkheap) FreeMemory(aasworld.linkheap); +void AAS_FreeAASLinkHeap(void) { + if (aasworld.linkheap) + FreeMemory(aasworld.linkheap); aasworld.linkheap = NULL; aasworld.linkheapsize = 0; -} //end of the function AAS_FreeAASLinkHeap +} // end of the function AAS_FreeAASLinkHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_link_t *AAS_AllocAASLink(void) -{ +aas_link_t *AAS_AllocAASLink(void) { aas_link_t *link; link = aasworld.freelinks; - if (!link) - { + if (!link) { #ifndef BSPC if (botDeveloper) #endif { botimport.Print(PRT_FATAL, "empty aas link heap\n"); - } //end if + } // end if return NULL; - } //end if - if (aasworld.freelinks) aasworld.freelinks = aasworld.freelinks->next_ent; - if (aasworld.freelinks) aasworld.freelinks->prev_ent = NULL; + } // end if + if (aasworld.freelinks) + aasworld.freelinks = aasworld.freelinks->next_ent; + if (aasworld.freelinks) + aasworld.freelinks->prev_ent = NULL; numaaslinks--; return link; -} //end of the function AAS_AllocAASLink +} // end of the function AAS_AllocAASLink //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_DeAllocAASLink(aas_link_t *link) -{ - if (aasworld.freelinks) aasworld.freelinks->prev_ent = link; +void AAS_DeAllocAASLink(aas_link_t *link) { + if (aasworld.freelinks) + aasworld.freelinks->prev_ent = link; link->prev_ent = NULL; link->next_ent = aasworld.freelinks; link->prev_area = NULL; link->next_area = NULL; aasworld.freelinks = link; numaaslinks++; -} //end of the function AAS_DeAllocAASLink +} // end of the function AAS_DeAllocAASLink //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_InitAASLinkedEntities(void) -{ - if (!aasworld.loaded) return; - if (aasworld.arealinkedentities) FreeMemory(aasworld.arealinkedentities); - aasworld.arealinkedentities = (aas_link_t **) GetClearedHunkMemory( - aasworld.numareas * sizeof(aas_link_t *)); -} //end of the function AAS_InitAASLinkedEntities +void AAS_InitAASLinkedEntities(void) { + if (!aasworld.loaded) + return; + if (aasworld.arealinkedentities) + FreeMemory(aasworld.arealinkedentities); + aasworld.arealinkedentities = (aas_link_t **)GetClearedHunkMemory(aasworld.numareas * sizeof(aas_link_t *)); +} // end of the function AAS_InitAASLinkedEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FreeAASLinkedEntities(void) -{ - if (aasworld.arealinkedentities) FreeMemory(aasworld.arealinkedentities); +void AAS_FreeAASLinkedEntities(void) { + if (aasworld.arealinkedentities) + FreeMemory(aasworld.arealinkedentities); aasworld.arealinkedentities = NULL; -} //end of the function AAS_InitAASLinkedEntities +} // end of the function AAS_InitAASLinkedEntities //=========================================================================== // returns the AAS area the point is in // @@ -215,110 +212,99 @@ void AAS_FreeAASLinkedEntities(void) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PointAreaNum(vec3_t point) -{ +int AAS_PointAreaNum(vec3_t point) { int nodenum; - float dist; + float dist; aas_node_t *node; aas_plane_t *plane; - if (!aasworld.loaded) - { + if (!aasworld.loaded) { botimport.Print(PRT_ERROR, "AAS_PointAreaNum: aas not loaded\n"); return 0; - } //end if + } // end if - //start with node 1 because node zero is a dummy used for solid leafs + // start with node 1 because node zero is a dummy used for solid leafs nodenum = 1; - while (nodenum > 0) - { + while (nodenum > 0) { // botimport.Print(PRT_MESSAGE, "[%d]", nodenum); #ifdef AAS_SAMPLE_DEBUG - if (nodenum >= aasworld.numnodes) - { + if (nodenum >= aasworld.numnodes) { botimport.Print(PRT_ERROR, "nodenum = %d >= aasworld.numnodes = %d\n", nodenum, aasworld.numnodes); return 0; - } //end if -#endif //AAS_SAMPLE_DEBUG + } // end if +#endif // AAS_SAMPLE_DEBUG node = &aasworld.nodes[nodenum]; #ifdef AAS_SAMPLE_DEBUG - if (node->planenum < 0 || node->planenum >= aasworld.numplanes) - { + if (node->planenum < 0 || node->planenum >= aasworld.numplanes) { botimport.Print(PRT_ERROR, "node->planenum = %d >= aasworld.numplanes = %d\n", node->planenum, aasworld.numplanes); return 0; - } //end if -#endif //AAS_SAMPLE_DEBUG + } // end if +#endif // AAS_SAMPLE_DEBUG plane = &aasworld.planes[node->planenum]; dist = DotProduct(point, plane->normal) - plane->dist; - if (dist > 0) nodenum = node->children[0]; - else nodenum = node->children[1]; - } //end while - if (!nodenum) - { + if (dist > 0) + nodenum = node->children[0]; + else + nodenum = node->children[1]; + } // end while + if (!nodenum) { #ifdef AAS_SAMPLE_DEBUG botimport.Print(PRT_MESSAGE, "in solid\n"); -#endif //AAS_SAMPLE_DEBUG +#endif // AAS_SAMPLE_DEBUG return 0; - } //end if + } // end if return -nodenum; -} //end of the function AAS_PointAreaNum +} // end of the function AAS_PointAreaNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PointReachabilityAreaIndex( vec3_t origin ) -{ +int AAS_PointReachabilityAreaIndex(vec3_t origin) { int areanum, cluster, i, index; if (!aasworld.initialized) return 0; - if ( !origin ) - { + if (!origin) { index = 0; - for (i = 0; i < aasworld.numclusters; i++) - { + for (i = 0; i < aasworld.numclusters; i++) { index += aasworld.clusters[i].numreachabilityareas; - } //end for + } // end for return index; - } //end if + } // end if - areanum = AAS_PointAreaNum( origin ); - if ( !areanum || !AAS_AreaReachability(areanum) ) + areanum = AAS_PointAreaNum(origin); + if (!areanum || !AAS_AreaReachability(areanum)) return 0; cluster = aasworld.areasettings[areanum].cluster; areanum = aasworld.areasettings[areanum].clusterareanum; - if (cluster < 0) - { + if (cluster < 0) { cluster = aasworld.portals[-cluster].frontcluster; areanum = aasworld.portals[-cluster].clusterareanum[0]; - } //end if + } // end if index = 0; - for (i = 0; i < cluster; i++) - { + for (i = 0; i < cluster; i++) { index += aasworld.clusters[i].numreachabilityareas; - } //end for + } // end for index += areanum; return index; -} //end of the function AAS_PointReachabilityAreaIndex +} // end of the function AAS_PointReachabilityAreaIndex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaCluster(int areanum) -{ - if (areanum <= 0 || areanum >= aasworld.numareas) - { +int AAS_AreaCluster(int areanum) { + if (areanum <= 0 || areanum >= aasworld.numareas) { botimport.Print(PRT_ERROR, "AAS_AreaCluster: invalid area number\n"); return 0; - } //end if + } // end if return aasworld.areasettings[areanum].cluster; -} //end of the function AAS_AreaCluster +} // end of the function AAS_AreaCluster //=========================================================================== // returns the presence types of the given area // @@ -326,16 +312,15 @@ int AAS_AreaCluster(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaPresenceType(int areanum) -{ - if (!aasworld.loaded) return 0; - if (areanum <= 0 || areanum >= aasworld.numareas) - { +int AAS_AreaPresenceType(int areanum) { + if (!aasworld.loaded) + return 0; + if (areanum <= 0 || areanum >= aasworld.numareas) { botimport.Print(PRT_ERROR, "AAS_AreaPresenceType: invalid area number\n"); return 0; - } //end if + } // end if return aasworld.areasettings[areanum].presencetype; -} //end of the function AAS_AreaPresenceType +} // end of the function AAS_AreaPresenceType //=========================================================================== // returns the presence type at the given point // @@ -343,16 +328,17 @@ int AAS_AreaPresenceType(int areanum) // Returns: - // Changes Globals: - //=========================================================================== -int AAS_PointPresenceType(vec3_t point) -{ +int AAS_PointPresenceType(vec3_t point) { int areanum; - if (!aasworld.loaded) return 0; + if (!aasworld.loaded) + return 0; areanum = AAS_PointAreaNum(point); - if (!areanum) return PRESENCE_NONE; + if (!areanum) + return PRESENCE_NONE; return aasworld.areasettings[areanum].presencetype; -} //end of the function AAS_PointPresenceType +} // end of the function AAS_PointPresenceType //=========================================================================== // calculates the minimum distance between the origin of the box and the // given plane when both will collide on the given side of the plane @@ -368,49 +354,48 @@ int AAS_PointPresenceType(vec3_t point) // Returns: - // Changes Globals: - //=========================================================================== -float AAS_BoxOriginDistanceFromPlane(vec3_t normal, vec3_t mins, vec3_t maxs, int side) -{ +float AAS_BoxOriginDistanceFromPlane(vec3_t normal, vec3_t mins, vec3_t maxs, int side) { vec3_t v1, v2; int i; - //swap maxs and mins when on the other side of the plane - if (side) - { - //get a point of the box that would be one of the first - //to collide with the plane - for (i = 0; i < 3; i++) - { - if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = maxs[i]; - else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = mins[i]; - else v1[i] = 0; - } //end for - } //end if - else - { - //get a point of the box that would be one of the first - //to collide with the plane - for (i = 0; i < 3; i++) - { - if (normal[i] > BBOX_NORMAL_EPSILON) v1[i] = mins[i]; - else if (normal[i] < -BBOX_NORMAL_EPSILON) v1[i] = maxs[i]; - else v1[i] = 0; - } //end for - } //end else + // swap maxs and mins when on the other side of the plane + if (side) { + // get a point of the box that would be one of the first + // to collide with the plane + for (i = 0; i < 3; i++) { + if (normal[i] > BBOX_NORMAL_EPSILON) + v1[i] = maxs[i]; + else if (normal[i] < -BBOX_NORMAL_EPSILON) + v1[i] = mins[i]; + else + v1[i] = 0; + } // end for + } // end if + else { + // get a point of the box that would be one of the first + // to collide with the plane + for (i = 0; i < 3; i++) { + if (normal[i] > BBOX_NORMAL_EPSILON) + v1[i] = mins[i]; + else if (normal[i] < -BBOX_NORMAL_EPSILON) + v1[i] = maxs[i]; + else + v1[i] = 0; + } // end for + } // end else // VectorCopy(normal, v2); VectorInverse(v2); -// VectorNegate(normal, v2); + // VectorNegate(normal, v2); return DotProduct(v1, v2); -} //end of the function AAS_BoxOriginDistanceFromPlane +} // end of the function AAS_BoxOriginDistanceFromPlane //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_AreaEntityCollision(int areanum, vec3_t start, vec3_t end, - int presencetype, int passent, aas_trace_t *trace) -{ +qboolean AAS_AreaEntityCollision(int areanum, vec3_t start, vec3_t end, int presencetype, int passent, aas_trace_t *trace) { int collision; vec3_t boxmins, boxmaxs; aas_link_t *link; @@ -418,32 +403,29 @@ qboolean AAS_AreaEntityCollision(int areanum, vec3_t start, vec3_t end, AAS_PresenceTypeBoundingBox(presencetype, boxmins, boxmaxs); - Com_Memset(&bsptrace, 0, sizeof(bsp_trace_t)); //make compiler happy - //assume no collision + Com_Memset(&bsptrace, 0, sizeof(bsp_trace_t)); // make compiler happy + // assume no collision bsptrace.fraction = 1; collision = qfalse; - for (link = aasworld.arealinkedentities[areanum]; link; link = link->next_ent) - { - //ignore the pass entity - if (link->entnum == passent) continue; + for (link = aasworld.arealinkedentities[areanum]; link; link = link->next_ent) { + // ignore the pass entity + if (link->entnum == passent) + continue; // - if (AAS_EntityCollision(link->entnum, start, boxmins, boxmaxs, end, - CONTENTS_SOLID|CONTENTS_PLAYERCLIP, &bsptrace)) - { + if (AAS_EntityCollision(link->entnum, start, boxmins, boxmaxs, end, CONTENTS_SOLID | CONTENTS_PLAYERCLIP, &bsptrace)) { collision = qtrue; - } //end if - } //end for - if (collision) - { + } // end if + } // end for + if (collision) { trace->startsolid = bsptrace.startsolid; trace->ent = bsptrace.ent; VectorCopy(bsptrace.endpos, trace->endpos); trace->area = 0; trace->planenum = 0; return qtrue; - } //end if + } // end if return qfalse; -} //end of the function AAS_AreaEntityCollision +} // end of the function AAS_AreaEntityCollision //=========================================================================== // recursive subdivision of the line by the BSP tree. // @@ -451,9 +433,7 @@ qboolean AAS_AreaEntityCollision(int areanum, vec3_t start, vec3_t end, // Returns: - // Changes Globals: - //=========================================================================== -aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, - int passent) -{ +aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, int passent) { int side, nodenum, tmpplanenum; float front, back, frac; vec3_t cur_start, cur_end, cur_mid, v1, v2; @@ -463,264 +443,242 @@ aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, aas_plane_t *plane; aas_trace_t trace; - //clear the trace structure + // clear the trace structure Com_Memset(&trace, 0, sizeof(aas_trace_t)); - if (!aasworld.loaded) return trace; + if (!aasworld.loaded) + return trace; tstack_p = tracestack; - //we start with the whole line on the stack + // we start with the whole line on the stack VectorCopy(start, tstack_p->start); VectorCopy(end, tstack_p->end); tstack_p->planenum = 0; - //start with node 1 because node zero is a dummy for a solid leaf - tstack_p->nodenum = 1; //starting at the root of the tree + // start with node 1 because node zero is a dummy for a solid leaf + tstack_p->nodenum = 1; // starting at the root of the tree tstack_p++; - while (1) - { - //pop up the stack + while (1) { + // pop up the stack tstack_p--; - //if the trace stack is empty (ended up with a piece of the - //line to be traced in an area) - if (tstack_p < tracestack) - { + // if the trace stack is empty (ended up with a piece of the + // line to be traced in an area) + if (tstack_p < tracestack) { tstack_p++; - //nothing was hit + // nothing was hit trace.startsolid = qfalse; trace.fraction = 1.0; - //endpos is the end of the line + // endpos is the end of the line VectorCopy(end, trace.endpos); - //nothing hit + // nothing hit trace.ent = 0; trace.area = 0; trace.planenum = 0; return trace; - } //end if - //number of the current node to test the line against + } // end if + // number of the current node to test the line against nodenum = tstack_p->nodenum; - //if it is an area - if (nodenum < 0) - { + // if it is an area + if (nodenum < 0) { #ifdef AAS_SAMPLE_DEBUG - if (-nodenum > aasworld.numareasettings) - { + if (-nodenum > aasworld.numareasettings) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: -nodenum out of range\n"); return trace; - } //end if -#endif //AAS_SAMPLE_DEBUG - //botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start)); - //if can't enter the area because it hasn't got the right presence type - if (!(aasworld.areasettings[-nodenum].presencetype & presencetype)) - { - //if the start point is still the initial start point - //NOTE: no need for epsilons because the points will be - //exactly the same when they're both the start point - if (tstack_p->start[0] == start[0] && - tstack_p->start[1] == start[1] && - tstack_p->start[2] == start[2]) - { + } // end if +#endif // AAS_SAMPLE_DEBUG + // botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start)); + // if can't enter the area because it hasn't got the right presence type + if (!(aasworld.areasettings[-nodenum].presencetype & presencetype)) { + // if the start point is still the initial start point + // NOTE: no need for epsilons because the points will be + // exactly the same when they're both the start point + if (tstack_p->start[0] == start[0] && tstack_p->start[1] == start[1] && tstack_p->start[2] == start[2]) { trace.startsolid = qtrue; trace.fraction = 0.0; VectorClear(v1); - } //end if - else - { + } // end if + else { trace.startsolid = qfalse; VectorSubtract(end, start, v1); VectorSubtract(tstack_p->start, start, v2); trace.fraction = VectorLength(v2) / VectorNormalize(v1); VectorMA(tstack_p->start, -0.125, v1, tstack_p->start); - } //end else + } // end else VectorCopy(tstack_p->start, trace.endpos); trace.ent = 0; trace.area = -nodenum; -// VectorSubtract(end, start, v1); + // VectorSubtract(end, start, v1); trace.planenum = tstack_p->planenum; - //always take the plane with normal facing towards the trace start + // always take the plane with normal facing towards the trace start plane = &aasworld.planes[trace.planenum]; - if (DotProduct(v1, plane->normal) > 0) trace.planenum ^= 1; + if (DotProduct(v1, plane->normal) > 0) + trace.planenum ^= 1; return trace; - } //end if - else - { - if (passent >= 0) - { - if (AAS_AreaEntityCollision(-nodenum, tstack_p->start, - tstack_p->end, presencetype, passent, - &trace)) - { - if (!trace.startsolid) - { + } // end if + else { + if (passent >= 0) { + if (AAS_AreaEntityCollision(-nodenum, tstack_p->start, tstack_p->end, presencetype, passent, &trace)) { + if (!trace.startsolid) { VectorSubtract(end, start, v1); VectorSubtract(trace.endpos, start, v2); trace.fraction = VectorLength(v2) / VectorLength(v1); - } //end if + } // end if return trace; - } //end if - } //end if - } //end else + } // end if + } // end if + } // end else trace.lastarea = -nodenum; continue; - } //end if - //if it is a solid leaf - if (!nodenum) - { - //if the start point is still the initial start point - //NOTE: no need for epsilons because the points will be - //exactly the same when they're both the start point - if (tstack_p->start[0] == start[0] && - tstack_p->start[1] == start[1] && - tstack_p->start[2] == start[2]) - { + } // end if + // if it is a solid leaf + if (!nodenum) { + // if the start point is still the initial start point + // NOTE: no need for epsilons because the points will be + // exactly the same when they're both the start point + if (tstack_p->start[0] == start[0] && tstack_p->start[1] == start[1] && tstack_p->start[2] == start[2]) { trace.startsolid = qtrue; trace.fraction = 0.0; VectorClear(v1); - } //end if - else - { + } // end if + else { trace.startsolid = qfalse; VectorSubtract(end, start, v1); VectorSubtract(tstack_p->start, start, v2); trace.fraction = VectorLength(v2) / VectorNormalize(v1); VectorMA(tstack_p->start, -0.125, v1, tstack_p->start); - } //end else + } // end else VectorCopy(tstack_p->start, trace.endpos); trace.ent = 0; - trace.area = 0; //hit solid leaf -// VectorSubtract(end, start, v1); + trace.area = 0; // hit solid leaf + // VectorSubtract(end, start, v1); trace.planenum = tstack_p->planenum; - //always take the plane with normal facing towards the trace start + // always take the plane with normal facing towards the trace start plane = &aasworld.planes[trace.planenum]; - if (DotProduct(v1, plane->normal) > 0) trace.planenum ^= 1; + if (DotProduct(v1, plane->normal) > 0) + trace.planenum ^= 1; return trace; - } //end if + } // end if #ifdef AAS_SAMPLE_DEBUG - if (nodenum > aasworld.numnodes) - { + if (nodenum > aasworld.numnodes) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: nodenum out of range\n"); return trace; - } //end if -#endif //AAS_SAMPLE_DEBUG - //the node to test against + } // end if +#endif // AAS_SAMPLE_DEBUG + // the node to test against aasnode = &aasworld.nodes[nodenum]; - //start point of current line to test against node + // start point of current line to test against node VectorCopy(tstack_p->start, cur_start); - //end point of the current line to test against node + // end point of the current line to test against node VectorCopy(tstack_p->end, cur_end); - //the current node plane + // the current node plane plane = &aasworld.planes[aasnode->planenum]; -// switch(plane->type) - {/*FIXME: wtf doesn't this work? obviously the axial node planes aren't always facing positive!!! - //check for axial planes - case PLANE_X: - { - front = cur_start[0] - plane->dist; - back = cur_end[0] - plane->dist; - break; - } //end case - case PLANE_Y: - { - front = cur_start[1] - plane->dist; - back = cur_end[1] - plane->dist; - break; - } //end case - case PLANE_Z: - { - front = cur_start[2] - plane->dist; - back = cur_end[2] - plane->dist; - break; - } //end case*/ -// default: //gee it's not an axial plane + // switch(plane->type) + { /*FIXME: wtf doesn't this work? obviously the axial node planes aren't always facing positive!!! + //check for axial planes + case PLANE_X: + { + front = cur_start[0] - plane->dist; + back = cur_end[0] - plane->dist; + break; + } //end case + case PLANE_Y: + { + front = cur_start[1] - plane->dist; + back = cur_end[1] - plane->dist; + break; + } //end case + case PLANE_Z: + { + front = cur_start[2] - plane->dist; + back = cur_end[2] - plane->dist; + break; + } //end case*/ + // default: //gee it's not an axial plane { front = DotProduct(cur_start, plane->normal) - plane->dist; back = DotProduct(cur_end, plane->normal) - plane->dist; -// break; - } //end default - } //end switch + // break; + } // end default + } // end switch // bk010221 - old location of FPE hack and divide by zero expression - //if the whole to be traced line is totally at the front of this node - //only go down the tree with the front child - if ((front >= -ON_EPSILON && back >= -ON_EPSILON)) - { - //keep the current start and end point on the stack - //and go down the tree with the front child + // if the whole to be traced line is totally at the front of this node + // only go down the tree with the front child + if ((front >= -ON_EPSILON && back >= -ON_EPSILON)) { + // keep the current start and end point on the stack + // and go down the tree with the front child tstack_p->nodenum = aasnode->children[0]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n"); return trace; - } //end if - } //end if - //if the whole to be traced line is totally at the back of this node - //only go down the tree with the back child - else if ((front < ON_EPSILON && back < ON_EPSILON)) - { - //keep the current start and end point on the stack - //and go down the tree with the back child + } // end if + } // end if + // if the whole to be traced line is totally at the back of this node + // only go down the tree with the back child + else if ((front < ON_EPSILON && back < ON_EPSILON)) { + // keep the current start and end point on the stack + // and go down the tree with the back child tstack_p->nodenum = aasnode->children[1]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n"); return trace; - } //end if - } //end if - //go down the tree both at the front and back of the node - else - { + } // end if + } // end if + // go down the tree both at the front and back of the node + else { tmpplanenum = tstack_p->planenum; // bk010221 - new location of divide by zero (see above) - if ( front == back ) front -= 0.001f; // bk0101022 - hack/FPE - //calculate the hitpoint with the node (split point of the line) - //put the crosspoint TRACEPLANE_EPSILON pixels on the near side - if (front < 0) frac = (front + TRACEPLANE_EPSILON)/(front-back); - else frac = (front - TRACEPLANE_EPSILON)/(front-back); // bk010221 + if (front == back) + front -= 0.001f; // bk0101022 - hack/FPE + // calculate the hitpoint with the node (split point of the line) + // put the crosspoint TRACEPLANE_EPSILON pixels on the near side + if (front < 0) + frac = (front + TRACEPLANE_EPSILON) / (front - back); + else + frac = (front - TRACEPLANE_EPSILON) / (front - back); // bk010221 // if (frac < 0) - frac = 0.001f; //0 + frac = 0.001f; // 0 else if (frac > 1) - frac = 0.999f; //1 - //frac = front / (front-back); + frac = 0.999f; // 1 + // frac = front / (front-back); // cur_mid[0] = cur_start[0] + (cur_end[0] - cur_start[0]) * frac; cur_mid[1] = cur_start[1] + (cur_end[1] - cur_start[1]) * frac; cur_mid[2] = cur_start[2] + (cur_end[2] - cur_start[2]) * frac; -// AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED); - //side the front part of the line is on + // AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED); + // side the front part of the line is on side = front < 0; - //first put the end part of the line on the stack (back side) + // first put the end part of the line on the stack (back side) VectorCopy(cur_mid, tstack_p->start); - //not necesary to store because still on stack - //VectorCopy(cur_end, tstack_p->end); + // not necesary to store because still on stack + // VectorCopy(cur_end, tstack_p->end); tstack_p->planenum = aasnode->planenum; tstack_p->nodenum = aasnode->children[!side]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n"); return trace; - } //end if - //now put the part near the start of the line on the stack so we will - //continue with thats part first. This way we'll find the first - //hit of the bbox + } // end if + // now put the part near the start of the line on the stack so we will + // continue with thats part first. This way we'll find the first + // hit of the bbox VectorCopy(cur_start, tstack_p->start); VectorCopy(cur_mid, tstack_p->end); tstack_p->planenum = tmpplanenum; tstack_p->nodenum = aasnode->children[side]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceBoundingBox: stack overflow\n"); return trace; - } //end if - } //end else - } //end while -// return trace; -} //end of the function AAS_TraceClientBBox + } // end if + } // end else + } // end while + // return trace; +} // end of the function AAS_TraceClientBBox //=========================================================================== // recursive subdivision of the line by the BSP tree. // @@ -728,8 +686,7 @@ aas_trace_t AAS_TraceClientBBox(vec3_t start, vec3_t end, int presencetype, // Returns: - // Changes Globals: - //=========================================================================== -int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) -{ +int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) { int side, nodenum, tmpplanenum; int numareas; float front, back, frac; @@ -741,172 +698,166 @@ int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int max numareas = 0; areas[0] = 0; - if (!aasworld.loaded) return numareas; + if (!aasworld.loaded) + return numareas; tstack_p = tracestack; - //we start with the whole line on the stack + // we start with the whole line on the stack VectorCopy(start, tstack_p->start); VectorCopy(end, tstack_p->end); tstack_p->planenum = 0; - //start with node 1 because node zero is a dummy for a solid leaf - tstack_p->nodenum = 1; //starting at the root of the tree + // start with node 1 because node zero is a dummy for a solid leaf + tstack_p->nodenum = 1; // starting at the root of the tree tstack_p++; - while (1) - { - //pop up the stack + while (1) { + // pop up the stack tstack_p--; - //if the trace stack is empty (ended up with a piece of the - //line to be traced in an area) - if (tstack_p < tracestack) - { + // if the trace stack is empty (ended up with a piece of the + // line to be traced in an area) + if (tstack_p < tracestack) { return numareas; - } //end if - //number of the current node to test the line against + } // end if + // number of the current node to test the line against nodenum = tstack_p->nodenum; - //if it is an area - if (nodenum < 0) - { + // if it is an area + if (nodenum < 0) { #ifdef AAS_SAMPLE_DEBUG - if (-nodenum > aasworld.numareasettings) - { + if (-nodenum > aasworld.numareasettings) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: -nodenum = %d out of range\n", -nodenum); return numareas; - } //end if -#endif //AAS_SAMPLE_DEBUG - //botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start)); + } // end if +#endif // AAS_SAMPLE_DEBUG + // botimport.Print(PRT_MESSAGE, "areanum = %d, must be %d\n", -nodenum, AAS_PointAreaNum(start)); areas[numareas] = -nodenum; - if (points) VectorCopy(tstack_p->start, points[numareas]); + if (points) + VectorCopy(tstack_p->start, points[numareas]); numareas++; - if (numareas >= maxareas) return numareas; + if (numareas >= maxareas) + return numareas; continue; - } //end if - //if it is a solid leaf - if (!nodenum) - { + } // end if + // if it is a solid leaf + if (!nodenum) { continue; - } //end if + } // end if #ifdef AAS_SAMPLE_DEBUG - if (nodenum > aasworld.numnodes) - { + if (nodenum > aasworld.numnodes) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: nodenum out of range\n"); return numareas; - } //end if -#endif //AAS_SAMPLE_DEBUG - //the node to test against + } // end if +#endif // AAS_SAMPLE_DEBUG + // the node to test against aasnode = &aasworld.nodes[nodenum]; - //start point of current line to test against node + // start point of current line to test against node VectorCopy(tstack_p->start, cur_start); - //end point of the current line to test against node + // end point of the current line to test against node VectorCopy(tstack_p->end, cur_end); - //the current node plane + // the current node plane plane = &aasworld.planes[aasnode->planenum]; -// switch(plane->type) - {/*FIXME: wtf doesn't this work? obviously the node planes aren't always facing positive!!! - //check for axial planes - case PLANE_X: - { - front = cur_start[0] - plane->dist; - back = cur_end[0] - plane->dist; - break; - } //end case - case PLANE_Y: - { - front = cur_start[1] - plane->dist; - back = cur_end[1] - plane->dist; - break; - } //end case - case PLANE_Z: - { - front = cur_start[2] - plane->dist; - back = cur_end[2] - plane->dist; - break; - } //end case*/ -// default: //gee it's not an axial plane + // switch(plane->type) + { /*FIXME: wtf doesn't this work? obviously the node planes aren't always facing positive!!! + //check for axial planes + case PLANE_X: + { + front = cur_start[0] - plane->dist; + back = cur_end[0] - plane->dist; + break; + } //end case + case PLANE_Y: + { + front = cur_start[1] - plane->dist; + back = cur_end[1] - plane->dist; + break; + } //end case + case PLANE_Z: + { + front = cur_start[2] - plane->dist; + back = cur_end[2] - plane->dist; + break; + } //end case*/ + // default: //gee it's not an axial plane { front = DotProduct(cur_start, plane->normal) - plane->dist; back = DotProduct(cur_end, plane->normal) - plane->dist; -// break; - } //end default - } //end switch + // break; + } // end default + } // end switch - //if the whole to be traced line is totally at the front of this node - //only go down the tree with the front child - if (front > 0 && back > 0) - { - //keep the current start and end point on the stack - //and go down the tree with the front child + // if the whole to be traced line is totally at the front of this node + // only go down the tree with the front child + if (front > 0 && back > 0) { + // keep the current start and end point on the stack + // and go down the tree with the front child tstack_p->nodenum = aasnode->children[0]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n"); return numareas; - } //end if - } //end if - //if the whole to be traced line is totally at the back of this node - //only go down the tree with the back child - else if (front <= 0 && back <= 0) - { - //keep the current start and end point on the stack - //and go down the tree with the back child + } // end if + } // end if + // if the whole to be traced line is totally at the back of this node + // only go down the tree with the back child + else if (front <= 0 && back <= 0) { + // keep the current start and end point on the stack + // and go down the tree with the back child tstack_p->nodenum = aasnode->children[1]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n"); return numareas; - } //end if - } //end if - //go down the tree both at the front and back of the node - else - { + } // end if + } // end if + // go down the tree both at the front and back of the node + else { tmpplanenum = tstack_p->planenum; - //calculate the hitpoint with the node (split point of the line) - //put the crosspoint TRACEPLANE_EPSILON pixels on the near side - if (front < 0) frac = (front)/(front-back); - else frac = (front)/(front-back); - if (frac < 0) frac = 0; - else if (frac > 1) frac = 1; - //frac = front / (front-back); + // calculate the hitpoint with the node (split point of the line) + // put the crosspoint TRACEPLANE_EPSILON pixels on the near side + if (front < 0) + frac = (front) / (front - back); + else + frac = (front) / (front - back); + if (frac < 0) + frac = 0; + else if (frac > 1) + frac = 1; + // frac = front / (front-back); // cur_mid[0] = cur_start[0] + (cur_end[0] - cur_start[0]) * frac; cur_mid[1] = cur_start[1] + (cur_end[1] - cur_start[1]) * frac; cur_mid[2] = cur_start[2] + (cur_end[2] - cur_start[2]) * frac; -// AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED); - //side the front part of the line is on + // AAS_DrawPlaneCross(cur_mid, plane->normal, plane->dist, plane->type, LINECOLOR_RED); + // side the front part of the line is on side = front < 0; - //first put the end part of the line on the stack (back side) + // first put the end part of the line on the stack (back side) VectorCopy(cur_mid, tstack_p->start); - //not necesary to store because still on stack - //VectorCopy(cur_end, tstack_p->end); + // not necesary to store because still on stack + // VectorCopy(cur_end, tstack_p->end); tstack_p->planenum = aasnode->planenum; tstack_p->nodenum = aasnode->children[!side]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n"); return numareas; - } //end if - //now put the part near the start of the line on the stack so we will - //continue with thats part first. This way we'll find the first - //hit of the bbox + } // end if + // now put the part near the start of the line on the stack so we will + // continue with thats part first. This way we'll find the first + // hit of the bbox VectorCopy(cur_start, tstack_p->start); VectorCopy(cur_mid, tstack_p->end); tstack_p->planenum = tmpplanenum; tstack_p->nodenum = aasnode->children[side]; tstack_p++; - if (tstack_p >= &tracestack[127]) - { + if (tstack_p >= &tracestack[127]) { botimport.Print(PRT_ERROR, "AAS_TraceAreas: stack overflow\n"); return numareas; - } //end if - } //end else - } //end while -// return numareas; -} //end of the function AAS_TraceAreas + } // end if + } // end else + } // end while + // return numareas; +} // end of the function AAS_TraceAreas //=========================================================================== // a simple cross product // @@ -915,9 +866,9 @@ int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int max // Changes Globals: - //=========================================================================== // void AAS_OrthogonalToVectors(vec3_t v1, vec3_t v2, vec3_t res) -#define AAS_OrthogonalToVectors(v1, v2, res) \ - (res)[0] = ((v1)[1] * (v2)[2]) - ((v1)[2] * (v2)[1]);\ - (res)[1] = ((v1)[2] * (v2)[0]) - ((v1)[0] * (v2)[2]);\ +#define AAS_OrthogonalToVectors(v1, v2, res) \ + (res)[0] = ((v1)[1] * (v2)[2]) - ((v1)[2] * (v2)[1]); \ + (res)[1] = ((v1)[2] * (v2)[0]) - ((v1)[0] * (v2)[2]); \ (res)[2] = ((v1)[0] * (v2)[1]) - ((v1)[1] * (v2)[0]); //=========================================================================== // tests if the given point is within the face boundaries @@ -928,60 +879,58 @@ int AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int max // Returns: qtrue if the point is within the face boundaries // Changes Globals: - //=========================================================================== -qboolean AAS_InsideFace(aas_face_t *face, vec3_t pnormal, vec3_t point, float epsilon) -{ +qboolean AAS_InsideFace(aas_face_t *face, vec3_t pnormal, vec3_t point, float epsilon) { int i, firstvertex, edgenum; vec3_t v0; vec3_t edgevec, pointvec, sepnormal; aas_edge_t *edge; #ifdef AAS_SAMPLE_DEBUG int lastvertex = 0; -#endif //AAS_SAMPLE_DEBUG +#endif // AAS_SAMPLE_DEBUG - if (!aasworld.loaded) return qfalse; + if (!aasworld.loaded) + return qfalse; - for (i = 0; i < face->numedges; i++) - { + for (i = 0; i < face->numedges; i++) { edgenum = aasworld.edgeindex[face->firstedge + i]; edge = &aasworld.edges[abs(edgenum)]; - //get the first vertex of the edge + // get the first vertex of the edge firstvertex = edgenum < 0; VectorCopy(aasworld.vertexes[edge->v[firstvertex]], v0); - //edge vector + // edge vector VectorSubtract(aasworld.vertexes[edge->v[!firstvertex]], v0, edgevec); // #ifdef AAS_SAMPLE_DEBUG - if (lastvertex && lastvertex != edge->v[firstvertex]) - { + if (lastvertex && lastvertex != edge->v[firstvertex]) { botimport.Print(PRT_MESSAGE, "winding not counter clockwise\n"); - } //end if + } // end if lastvertex = edge->v[!firstvertex]; -#endif //AAS_SAMPLE_DEBUG - //vector from first edge point to point possible in face +#endif // AAS_SAMPLE_DEBUG + // vector from first edge point to point possible in face VectorSubtract(point, v0, pointvec); - //get a vector pointing inside the face orthogonal to both the - //edge vector and the normal vector of the plane the face is in - //this vector defines a plane through the origin (first vertex of - //edge) and through both the edge vector and the normal vector - //of the plane + // get a vector pointing inside the face orthogonal to both the + // edge vector and the normal vector of the plane the face is in + // this vector defines a plane through the origin (first vertex of + // edge) and through both the edge vector and the normal vector + // of the plane AAS_OrthogonalToVectors(edgevec, pnormal, sepnormal); - //check on wich side of the above plane the point is - //this is done by checking the sign of the dot product of the - //vector orthogonal vector from above and the vector from the - //origin (first vertex of edge) to the point - //if the dotproduct is smaller than zero the point is outside the face - if (DotProduct(pointvec, sepnormal) < -epsilon) return qfalse; - } //end for + // check on wich side of the above plane the point is + // this is done by checking the sign of the dot product of the + // vector orthogonal vector from above and the vector from the + // origin (first vertex of edge) to the point + // if the dotproduct is smaller than zero the point is outside the face + if (DotProduct(pointvec, sepnormal) < -epsilon) + return qfalse; + } // end for return qtrue; -} //end of the function AAS_InsideFace +} // end of the function AAS_InsideFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon) -{ +qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon) { int i, firstvertex, edgenum; float *v1, *v2; vec3_t edgevec, pointvec, sepnormal; @@ -989,30 +938,31 @@ qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon) aas_plane_t *plane; aas_face_t *face; - if (!aasworld.loaded) return qfalse; + if (!aasworld.loaded) + return qfalse; face = &aasworld.faces[facenum]; plane = &aasworld.planes[face->planenum]; // - for (i = 0; i < face->numedges; i++) - { + for (i = 0; i < face->numedges; i++) { edgenum = aasworld.edgeindex[face->firstedge + i]; edge = &aasworld.edges[abs(edgenum)]; - //get the first vertex of the edge + // get the first vertex of the edge firstvertex = edgenum < 0; v1 = aasworld.vertexes[edge->v[firstvertex]]; v2 = aasworld.vertexes[edge->v[!firstvertex]]; - //edge vector + // edge vector VectorSubtract(v2, v1, edgevec); - //vector from first edge point to point possible in face + // vector from first edge point to point possible in face VectorSubtract(point, v1, pointvec); // CrossProduct(edgevec, plane->normal, sepnormal); // - if (DotProduct(pointvec, sepnormal) < -epsilon) return qfalse; - } //end for + if (DotProduct(pointvec, sepnormal) < -epsilon) + return qfalse; + } // end for return qtrue; -} //end of the function AAS_PointInsideFace +} // end of the function AAS_PointInsideFace //=========================================================================== // returns the ground face the given point is above in the given area // @@ -1020,33 +970,34 @@ qboolean AAS_PointInsideFace(int facenum, vec3_t point, float epsilon) // Returns: - // Changes Globals: - //=========================================================================== -aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point) -{ +aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point) { int i, facenum; vec3_t up = {0, 0, 1}; vec3_t normal; aas_area_t *area; aas_face_t *face; - if (!aasworld.loaded) return NULL; + if (!aasworld.loaded) + return NULL; area = &aasworld.areas[areanum]; - for (i = 0; i < area->numfaces; i++) - { + for (i = 0; i < area->numfaces; i++) { facenum = aasworld.faceindex[area->firstface + i]; face = &aasworld.faces[abs(facenum)]; - //if this is a ground face - if (face->faceflags & FACE_GROUND) - { - //get the up or down normal - if (aasworld.planes[face->planenum].normal[2] < 0) VectorNegate(up, normal); - else VectorCopy(up, normal); - //check if the point is in the face - if (AAS_InsideFace(face, normal, point, 0.01f)) return face; - } //end if - } //end for + // if this is a ground face + if (face->faceflags & FACE_GROUND) { + // get the up or down normal + if (aasworld.planes[face->planenum].normal[2] < 0) + VectorNegate(up, normal); + else + VectorCopy(up, normal); + // check if the point is in the face + if (AAS_InsideFace(face, normal, point, 0.01f)) + return face; + } // end if + } // end for return NULL; -} //end of the function AAS_AreaGroundFace +} // end of the function AAS_AreaGroundFace //=========================================================================== // returns the face the trace end position is situated in // @@ -1054,14 +1005,13 @@ aas_face_t *AAS_AreaGroundFace(int areanum, vec3_t point) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_FacePlane(int facenum, vec3_t normal, float *dist) -{ +void AAS_FacePlane(int facenum, vec3_t normal, float *dist) { aas_plane_t *plane; plane = &aasworld.planes[aasworld.faces[facenum].planenum]; VectorCopy(plane->normal, normal); *dist = plane->dist; -} //end of the function AAS_FacePlane +} // end of the function AAS_FacePlane //=========================================================================== // returns the face the trace end position is situated in // @@ -1069,124 +1019,100 @@ void AAS_FacePlane(int facenum, vec3_t normal, float *dist) // Returns: - // Changes Globals: - //=========================================================================== -aas_face_t *AAS_TraceEndFace(aas_trace_t *trace) -{ +aas_face_t *AAS_TraceEndFace(aas_trace_t *trace) { int i, facenum; aas_area_t *area; aas_face_t *face, *firstface = NULL; - if (!aasworld.loaded) return NULL; + if (!aasworld.loaded) + return NULL; - //if started in solid no face was hit - if (trace->startsolid) return NULL; - //trace->lastarea is the last area the trace was in + // if started in solid no face was hit + if (trace->startsolid) + return NULL; + // trace->lastarea is the last area the trace was in area = &aasworld.areas[trace->lastarea]; - //check which face the trace.endpos was in - for (i = 0; i < area->numfaces; i++) - { + // check which face the trace.endpos was in + for (i = 0; i < area->numfaces; i++) { facenum = aasworld.faceindex[area->firstface + i]; face = &aasworld.faces[abs(facenum)]; - //if the face is in the same plane as the trace end point - if ((face->planenum & ~1) == (trace->planenum & ~1)) - { - //firstface is used for optimization, if theres only one - //face in the plane then it has to be the good one - //if there are more faces in the same plane then always - //check the one with the fewest edges first -/* if (firstface) - { - if (firstface->numedges < face->numedges) - { - if (AAS_InsideFace(firstface, - aasworld.planes[face->planenum].normal, trace->endpos)) - { - return firstface; - } //end if - firstface = face; - } //end if - else - { - if (AAS_InsideFace(face, - aasworld.planes[face->planenum].normal, trace->endpos)) - { - return face; - } //end if - } //end else - } //end if - else - { - firstface = face; - } //end else*/ - if (AAS_InsideFace(face, - aasworld.planes[face->planenum].normal, trace->endpos, 0.01f)) return face; - } //end if - } //end for + // if the face is in the same plane as the trace end point + if ((face->planenum & ~1) == (trace->planenum & ~1)) { + // firstface is used for optimization, if theres only one + // face in the plane then it has to be the good one + // if there are more faces in the same plane then always + // check the one with the fewest edges first + /* if (firstface) + { + if (firstface->numedges < face->numedges) + { + if (AAS_InsideFace(firstface, + aasworld.planes[face->planenum].normal, trace->endpos)) + { + return firstface; + } //end if + firstface = face; + } //end if + else + { + if (AAS_InsideFace(face, + aasworld.planes[face->planenum].normal, trace->endpos)) + { + return face; + } //end if + } //end else + } //end if + else + { + firstface = face; + } //end else*/ + if (AAS_InsideFace(face, aasworld.planes[face->planenum].normal, trace->endpos, 0.01f)) + return face; + } // end if + } // end for return firstface; -} //end of the function AAS_TraceEndFace +} // end of the function AAS_TraceEndFace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BoxOnPlaneSide2(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p) -{ +int AAS_BoxOnPlaneSide2(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p) { int i, sides; float dist1, dist2; vec3_t corners[2]; - for (i = 0; i < 3; i++) - { - if (p->normal[i] < 0) - { + for (i = 0; i < 3; i++) { + if (p->normal[i] < 0) { corners[0][i] = absmins[i]; corners[1][i] = absmaxs[i]; - } //end if - else - { + } // end if + else { corners[1][i] = absmins[i]; corners[0][i] = absmaxs[i]; - } //end else - } //end for + } // end else + } // end for dist1 = DotProduct(p->normal, corners[0]) - p->dist; dist2 = DotProduct(p->normal, corners[1]) - p->dist; sides = 0; - if (dist1 >= 0) sides = 1; - if (dist2 < 0) sides |= 2; + if (dist1 >= 0) + sides = 1; + if (dist2 < 0) + sides |= 2; return sides; -} //end of the function AAS_BoxOnPlaneSide2 +} // end of the function AAS_BoxOnPlaneSide2 //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -//int AAS_BoxOnPlaneSide(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p) -#define AAS_BoxOnPlaneSide(absmins, absmaxs, p) (\ - ( (p)->type < 3) ?\ - (\ - ( (p)->dist <= (absmins)[(p)->type]) ?\ - (\ - 1\ - )\ - :\ - (\ - ( (p)->dist >= (absmaxs)[(p)->type]) ?\ - (\ - 2\ - )\ - :\ - (\ - 3\ - )\ - )\ - )\ - :\ - (\ - AAS_BoxOnPlaneSide2((absmins), (absmaxs), (p))\ - )\ -) //end of the function AAS_BoxOnPlaneSide +// int AAS_BoxOnPlaneSide(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p) +#define AAS_BoxOnPlaneSide(absmins, absmaxs, p) \ + (((p)->type < 3) ? (((p)->dist <= (absmins)[(p)->type]) ? (1) : (((p)->dist >= (absmaxs)[(p)->type]) ? (2) : (3))) \ + : (AAS_BoxOnPlaneSide2((absmins), (absmaxs), (p)))) // end of the function AAS_BoxOnPlaneSide //=========================================================================== // remove the links to this entity from all areas // @@ -1194,22 +1120,23 @@ int AAS_BoxOnPlaneSide2(vec3_t absmins, vec3_t absmaxs, aas_plane_t *p) // Returns: - // Changes Globals: - //=========================================================================== -void AAS_UnlinkFromAreas(aas_link_t *areas) -{ +void AAS_UnlinkFromAreas(aas_link_t *areas) { aas_link_t *link, *nextlink; - for (link = areas; link; link = nextlink) - { - //next area the entity is linked in + for (link = areas; link; link = nextlink) { + // next area the entity is linked in nextlink = link->next_area; - //remove the entity from the linked list of this area - if (link->prev_ent) link->prev_ent->next_ent = link->next_ent; - else aasworld.arealinkedentities[link->areanum] = link->next_ent; - if (link->next_ent) link->next_ent->prev_ent = link->prev_ent; - //deallocate the link structure + // remove the entity from the linked list of this area + if (link->prev_ent) + link->prev_ent->next_ent = link->next_ent; + else + aasworld.arealinkedentities[link->areanum] = link->next_ent; + if (link->next_ent) + link->next_ent->prev_ent = link->prev_ent; + // deallocate the link structure AAS_DeAllocAASLink(link); - } //end for -} //end of the function AAS_UnlinkFromAreas + } // end for +} // end of the function AAS_UnlinkFromAreas //=========================================================================== // link the entity to the areas the bounding box is totally or partly // situated in. This is done with recursion down the tree using the @@ -1221,11 +1148,10 @@ void AAS_UnlinkFromAreas(aas_link_t *areas) //=========================================================================== typedef struct aas_linkstack_s { - int nodenum; //node found after splitting + int nodenum; // node found after splitting } aas_linkstack_t; -aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum) -{ +aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum) { int side, nodenum; aas_linkstack_t linkstack[128]; aas_linkstack_t *lstack_p; @@ -1233,147 +1159,140 @@ aas_link_t *AAS_AASLinkEntity(vec3_t absmins, vec3_t absmaxs, int entnum) aas_plane_t *plane; aas_link_t *link, *areas; - if (!aasworld.loaded) - { + if (!aasworld.loaded) { botimport.Print(PRT_ERROR, "AAS_LinkEntity: aas not loaded\n"); return NULL; - } //end if + } // end if areas = NULL; // lstack_p = linkstack; - //we start with the whole line on the stack - //start with node 1 because node zero is a dummy used for solid leafs - lstack_p->nodenum = 1; //starting at the root of the tree + // we start with the whole line on the stack + // start with node 1 because node zero is a dummy used for solid leafs + lstack_p->nodenum = 1; // starting at the root of the tree lstack_p++; - while (1) - { - //pop up the stack + while (1) { + // pop up the stack lstack_p--; - //if the trace stack is empty (ended up with a piece of the - //line to be traced in an area) - if (lstack_p < linkstack) break; - //number of the current node to test the line against + // if the trace stack is empty (ended up with a piece of the + // line to be traced in an area) + if (lstack_p < linkstack) + break; + // number of the current node to test the line against nodenum = lstack_p->nodenum; - //if it is an area - if (nodenum < 0) - { - //NOTE: the entity might have already been linked into this area - // because several node children can point to the same area - for (link = aasworld.arealinkedentities[-nodenum]; link; link = link->next_ent) - { - if (link->entnum == entnum) break; - } //end for - if (link) continue; + // if it is an area + if (nodenum < 0) { + // NOTE: the entity might have already been linked into this area + // because several node children can point to the same area + for (link = aasworld.arealinkedentities[-nodenum]; link; link = link->next_ent) { + if (link->entnum == entnum) + break; + } // end for + if (link) + continue; // link = AAS_AllocAASLink(); - if (!link) return areas; + if (!link) + return areas; link->entnum = entnum; link->areanum = -nodenum; - //put the link into the double linked area list of the entity + // put the link into the double linked area list of the entity link->prev_area = NULL; link->next_area = areas; - if (areas) areas->prev_area = link; + if (areas) + areas->prev_area = link; areas = link; - //put the link into the double linked entity list of the area + // put the link into the double linked entity list of the area link->prev_ent = NULL; link->next_ent = aasworld.arealinkedentities[-nodenum]; if (aasworld.arealinkedentities[-nodenum]) - aasworld.arealinkedentities[-nodenum]->prev_ent = link; + aasworld.arealinkedentities[-nodenum]->prev_ent = link; aasworld.arealinkedentities[-nodenum] = link; // continue; - } //end if - //if solid leaf - if (!nodenum) continue; - //the node to test against + } // end if + // if solid leaf + if (!nodenum) + continue; + // the node to test against aasnode = &aasworld.nodes[nodenum]; - //the current node plane + // the current node plane plane = &aasworld.planes[aasnode->planenum]; - //get the side(s) the box is situated relative to the plane + // get the side(s) the box is situated relative to the plane side = AAS_BoxOnPlaneSide2(absmins, absmaxs, plane); - //if on the front side of the node - if (side & 1) - { + // if on the front side of the node + if (side & 1) { lstack_p->nodenum = aasnode->children[0]; lstack_p++; - } //end if - if (lstack_p >= &linkstack[127]) - { + } // end if + if (lstack_p >= &linkstack[127]) { botimport.Print(PRT_ERROR, "AAS_LinkEntity: stack overflow\n"); break; - } //end if - //if on the back side of the node - if (side & 2) - { + } // end if + // if on the back side of the node + if (side & 2) { lstack_p->nodenum = aasnode->children[1]; lstack_p++; - } //end if - if (lstack_p >= &linkstack[127]) - { + } // end if + if (lstack_p >= &linkstack[127]) { botimport.Print(PRT_ERROR, "AAS_LinkEntity: stack overflow\n"); break; - } //end if - } //end while + } // end if + } // end while return areas; -} //end of the function AAS_AASLinkEntity +} // end of the function AAS_AASLinkEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_link_t *AAS_LinkEntityClientBBox(vec3_t absmins, vec3_t absmaxs, int entnum, int presencetype) -{ +aas_link_t *AAS_LinkEntityClientBBox(vec3_t absmins, vec3_t absmaxs, int entnum, int presencetype) { vec3_t mins, maxs; vec3_t newabsmins, newabsmaxs; AAS_PresenceTypeBoundingBox(presencetype, mins, maxs); VectorSubtract(absmins, maxs, newabsmins); VectorSubtract(absmaxs, mins, newabsmaxs); - //relink the entity + // relink the entity return AAS_AASLinkEntity(newabsmins, newabsmaxs, entnum); -} //end of the function AAS_LinkEntityClientBBox +} // end of the function AAS_LinkEntityClientBBox //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) -{ +int AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) { aas_link_t *linkedareas, *link; int num; linkedareas = AAS_AASLinkEntity(absmins, absmaxs, -1); num = 0; - for (link = linkedareas; link; link = link->next_area) - { + for (link = linkedareas; link; link = link->next_area) { areas[num] = link->areanum; num++; if (num >= maxareas) break; - } //end for + } // end for AAS_UnlinkFromAreas(linkedareas); return num; -} //end of the function AAS_BBoxAreas +} // end of the function AAS_BBoxAreas //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AAS_AreaInfo( int areanum, aas_areainfo_t *info ) -{ +int AAS_AreaInfo(int areanum, aas_areainfo_t *info) { aas_areasettings_t *settings; if (!info) return 0; - if (areanum <= 0 || areanum >= aasworld.numareas) - { + if (areanum <= 0 || areanum >= aasworld.numareas) { botimport.Print(PRT_ERROR, "AAS_AreaInfo: areanum %d out of range\n", areanum); return 0; - } //end if + } // end if settings = &aasworld.areasettings[areanum]; info->cluster = settings->cluster; info->contents = settings->contents; @@ -1383,16 +1302,16 @@ int AAS_AreaInfo( int areanum, aas_areainfo_t *info ) VectorCopy(aasworld.areas[areanum].maxs, info->maxs); VectorCopy(aasworld.areas[areanum].center, info->center); return sizeof(aas_areainfo_t); -} //end of the function AAS_AreaInfo +} // end of the function AAS_AreaInfo //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -aas_plane_t *AAS_PlaneFromNum(int planenum) -{ - if (!aasworld.loaded) return 0; +aas_plane_t *AAS_PlaneFromNum(int planenum) { + if (!aasworld.loaded) + return 0; return &aasworld.planes[planenum]; -} //end of the function AAS_PlaneFromNum +} // end of the function AAS_PlaneFromNum diff --git a/codemp/botlib/be_ai_char.cpp b/codemp/botlib/be_ai_char.cpp index 413d83e29c..392d03c1e3 100644 --- a/codemp/botlib/be_ai_char.cpp +++ b/codemp/botlib/be_ai_char.cpp @@ -49,34 +49,31 @@ along with this program; if not, see . #include "be_interface.h" #include "be_ai_char.h" -#define MAX_CHARACTERISTICS 80 +#define MAX_CHARACTERISTICS 80 -#define CT_INTEGER 1 -#define CT_FLOAT 2 -#define CT_STRING 3 +#define CT_INTEGER 1 +#define CT_FLOAT 2 +#define CT_STRING 3 -#define DEFAULT_CHARACTER "bots/default_c.c" +#define DEFAULT_CHARACTER "bots/default_c.c" -//characteristic value -union cvalue -{ +// characteristic value +union cvalue { int integer; float _float; char *string; }; -//a characteristic -typedef struct bot_characteristic_s -{ - char type; //characteristic type - union cvalue value; //characteristic value +// a characteristic +typedef struct bot_characteristic_s { + char type; // characteristic type + union cvalue value; // characteristic value } bot_characteristic_t; -//a bot character -typedef struct bot_character_s -{ +// a bot character +typedef struct bot_character_s { char filename[MAX_QPATH]; float skill; - bot_characteristic_t c[1]; //variable sized + bot_characteristic_t c[1]; // variable sized } bot_character_t; bot_character_t *botcharacters[MAX_CLIENTS + 1]; @@ -87,439 +84,390 @@ bot_character_t *botcharacters[MAX_CLIENTS + 1]; // Returns: - // Changes Globals: - //======================================================================== -bot_character_t *BotCharacterFromHandle(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +bot_character_t *BotCharacterFromHandle(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "character handle %d out of range\n", handle); return NULL; - } //end if - if (!botcharacters[handle]) - { + } // end if + if (!botcharacters[handle]) { botimport.Print(PRT_FATAL, "invalid character %d\n", handle); return NULL; - } //end if + } // end if return botcharacters[handle]; -} //end of the function BotCharacterFromHandle +} // end of the function BotCharacterFromHandle //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpCharacter(bot_character_t *ch) -{ +void BotDumpCharacter(bot_character_t *ch) { int i; Log_Write("%s\n", ch->filename); Log_Write("skill %.1f\n", ch->skill); Log_Write("{\n"); - for (i = 0; i < MAX_CHARACTERISTICS; i++) - { - switch(ch->c[i].type) - { - case CT_INTEGER: Log_Write(" %4d %d\n", i, ch->c[i].value.integer); break; - case CT_FLOAT: Log_Write(" %4d %f\n", i, ch->c[i].value._float); break; - case CT_STRING: Log_Write(" %4d %s\n", i, ch->c[i].value.string); break; - } //end case - } //end for + for (i = 0; i < MAX_CHARACTERISTICS; i++) { + switch (ch->c[i].type) { + case CT_INTEGER: + Log_Write(" %4d %d\n", i, ch->c[i].value.integer); + break; + case CT_FLOAT: + Log_Write(" %4d %f\n", i, ch->c[i].value._float); + break; + case CT_STRING: + Log_Write(" %4d %s\n", i, ch->c[i].value.string); + break; + } // end case + } // end for Log_Write("}\n"); -} //end of the function BotDumpCharacter +} // end of the function BotDumpCharacter //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeCharacterStrings(bot_character_t *ch) -{ +void BotFreeCharacterStrings(bot_character_t *ch) { int i; - for (i = 0; i < MAX_CHARACTERISTICS; i++) - { - if (ch->c[i].type == CT_STRING) - { + for (i = 0; i < MAX_CHARACTERISTICS; i++) { + if (ch->c[i].type == CT_STRING) { FreeMemory(ch->c[i].value.string); - } //end if - } //end for -} //end of the function BotFreeCharacterStrings + } // end if + } // end for +} // end of the function BotFreeCharacterStrings //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeCharacter2(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +void BotFreeCharacter2(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "character handle %d out of range\n", handle); return; - } //end if - if (!botcharacters[handle]) - { + } // end if + if (!botcharacters[handle]) { botimport.Print(PRT_FATAL, "invalid character %d\n", handle); return; - } //end if + } // end if BotFreeCharacterStrings(botcharacters[handle]); FreeMemory(botcharacters[handle]); botcharacters[handle] = NULL; -} //end of the function BotFreeCharacter2 +} // end of the function BotFreeCharacter2 //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeCharacter(int handle) -{ - if (!LibVarGetValue("bot_reloadcharacters")) return; +void BotFreeCharacter(int handle) { + if (!LibVarGetValue("bot_reloadcharacters")) + return; BotFreeCharacter2(handle); -} //end of the function BotFreeCharacter +} // end of the function BotFreeCharacter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDefaultCharacteristics(bot_character_t *ch, bot_character_t *defaultch) -{ +void BotDefaultCharacteristics(bot_character_t *ch, bot_character_t *defaultch) { int i; - for (i = 0; i < MAX_CHARACTERISTICS; i++) - { - if (ch->c[i].type) continue; + for (i = 0; i < MAX_CHARACTERISTICS; i++) { + if (ch->c[i].type) + continue; // - if (defaultch->c[i].type == CT_FLOAT) - { + if (defaultch->c[i].type == CT_FLOAT) { ch->c[i].type = CT_FLOAT; ch->c[i].value._float = defaultch->c[i].value._float; - } //end if - else if (defaultch->c[i].type == CT_INTEGER) - { + } // end if + else if (defaultch->c[i].type == CT_INTEGER) { ch->c[i].type = CT_INTEGER; ch->c[i].value.integer = defaultch->c[i].value.integer; - } //end else if - else if (defaultch->c[i].type == CT_STRING) - { + } // end else if + else if (defaultch->c[i].type == CT_STRING) { ch->c[i].type = CT_STRING; - ch->c[i].value.string = (char *) GetMemory(strlen(defaultch->c[i].value.string)+1); + ch->c[i].value.string = (char *)GetMemory(strlen(defaultch->c[i].value.string) + 1); strcpy(ch->c[i].value.string, defaultch->c[i].value.string); - } //end else if - } //end for -} //end of the function BotDefaultCharacteristics + } // end else if + } // end for +} // end of the function BotDefaultCharacteristics //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_character_t *BotLoadCharacterFromFile(char *charfile, int skill) -{ +bot_character_t *BotLoadCharacterFromFile(char *charfile, int skill) { int indent, index, foundcharacter; bot_character_t *ch; source_t *source; token_t token; foundcharacter = qfalse; - //a bot character is parsed in two phases + // a bot character is parsed in two phases PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(charfile); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", charfile); return NULL; - } //end if - ch = (bot_character_t *) GetClearedMemory(sizeof(bot_character_t) + - MAX_CHARACTERISTICS * sizeof(bot_characteristic_t)); + } // end if + ch = (bot_character_t *)GetClearedMemory(sizeof(bot_character_t) + MAX_CHARACTERISTICS * sizeof(bot_characteristic_t)); strcpy(ch->filename, charfile); - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "skill")) - { - if (!PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) - { + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "skill")) { + if (!PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) { FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - if (!PC_ExpectTokenString(source, "{")) - { + } // end if + if (!PC_ExpectTokenString(source, "{")) { FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - //if it's the correct skill - if (skill < 0 || (int)token.intvalue == skill) - { + } // end if + // if it's the correct skill + if (skill < 0 || (int)token.intvalue == skill) { foundcharacter = qtrue; ch->skill = token.intvalue; - while(PC_ExpectAnyToken(source, &token)) - { - if (!strcmp(token.string, "}")) break; - if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER)) - { + while (PC_ExpectAnyToken(source, &token)) { + if (!strcmp(token.string, "}")) + break; + if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER)) { SourceError(source, "expected integer index, found %s", token.string); FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if + } // end if index = token.intvalue; - if (index < 0 || index > MAX_CHARACTERISTICS) - { + if (index < 0 || index > MAX_CHARACTERISTICS) { SourceError(source, "characteristic index out of range [0, %d]", MAX_CHARACTERISTICS); FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - if (ch->c[index].type) - { + } // end if + if (ch->c[index].type) { SourceError(source, "characteristic %d already initialized", index); FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - if (!PC_ExpectAnyToken(source, &token)) - { + } // end if + if (!PC_ExpectAnyToken(source, &token)) { FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - if (token.type == TT_NUMBER) - { - if (token.subtype & TT_FLOAT) - { + } // end if + if (token.type == TT_NUMBER) { + if (token.subtype & TT_FLOAT) { ch->c[index].value._float = token.floatvalue; ch->c[index].type = CT_FLOAT; - } //end if - else - { + } // end if + else { ch->c[index].value.integer = token.intvalue; ch->c[index].type = CT_INTEGER; - } //end else - } //end if - else if (token.type == TT_STRING) - { + } // end else + } // end if + else if (token.type == TT_STRING) { StripDoubleQuotes(token.string); - ch->c[index].value.string = (char *)GetMemory(strlen(token.string)+1); + ch->c[index].value.string = (char *)GetMemory(strlen(token.string) + 1); strcpy(ch->c[index].value.string, token.string); ch->c[index].type = CT_STRING; - } //end else if - else - { + } // end else if + else { SourceError(source, "expected integer, float or string, found %s", token.string); FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end else - } //end if + } // end else + } // end if break; - } //end if - else - { + } // end if + else { indent = 1; - while(indent) - { - if (!PC_ExpectAnyToken(source, &token)) - { + while (indent) { + if (!PC_ExpectAnyToken(source, &token)) { FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if - if (!strcmp(token.string, "{")) indent++; - else if (!strcmp(token.string, "}")) indent--; - } //end while - } //end else - } //end if - else - { + } // end if + if (!strcmp(token.string, "{")) + indent++; + else if (!strcmp(token.string, "}")) + indent--; + } // end while + } // end else + } // end if + else { SourceError(source, "unknown definition %s", token.string); FreeSource(source); BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end else - } //end while + } // end else + } // end while FreeSource(source); // - if (!foundcharacter) - { + if (!foundcharacter) { BotFreeCharacterStrings(ch); FreeMemory(ch); return NULL; - } //end if + } // end if return ch; -} //end of the function BotLoadCharacterFromFile +} // end of the function BotLoadCharacterFromFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotFindCachedCharacter(char *charfile, float skill) -{ +int BotFindCachedCharacter(char *charfile, float skill) { int handle; - for (handle = 1; handle <= MAX_CLIENTS; handle++) - { - if ( !botcharacters[handle] ) continue; - if ( strcmp( botcharacters[handle]->filename, charfile ) == 0 && - (skill < 0 || fabs(botcharacters[handle]->skill - skill) < 0.01) ) - { + for (handle = 1; handle <= MAX_CLIENTS; handle++) { + if (!botcharacters[handle]) + continue; + if (strcmp(botcharacters[handle]->filename, charfile) == 0 && (skill < 0 || fabs(botcharacters[handle]->skill - skill) < 0.01)) { return handle; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotFindCachedCharacter +} // end of the function BotFindCachedCharacter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadCachedCharacter(char *charfile, float skill, int reload) -{ +int BotLoadCachedCharacter(char *charfile, float skill, int reload) { int handle, cachedhandle, intskill; bot_character_t *ch = NULL; #ifdef DEBUG int starttime; starttime = Sys_MilliSeconds(); -#endif //DEBUG - - //find a free spot for a character - for (handle = 1; handle <= MAX_CLIENTS; handle++) - { - if (!botcharacters[handle]) break; - } //end for - if (handle > MAX_CLIENTS) return 0; - //try to load a cached character with the given skill - if (!reload) - { +#endif // DEBUG + + // find a free spot for a character + for (handle = 1; handle <= MAX_CLIENTS; handle++) { + if (!botcharacters[handle]) + break; + } // end for + if (handle > MAX_CLIENTS) + return 0; + // try to load a cached character with the given skill + if (!reload) { cachedhandle = BotFindCachedCharacter(charfile, skill); - if (cachedhandle) - { + if (cachedhandle) { botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", skill, charfile); return cachedhandle; - } //end if - } //end else + } // end if + } // end else // - intskill = (int) (skill + 0.5); - //try to load the character with the given skill + intskill = (int)(skill + 0.5); + // try to load the character with the given skill ch = BotLoadCharacterFromFile(charfile, intskill); - if (ch) - { + if (ch) { botcharacters[handle] = ch; // botimport.Print(PRT_MESSAGE, "loaded skill %d from %s\n", intskill, charfile); #ifdef DEBUG - if (botDeveloper) - { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "skill %d loaded in %d msec from %s\n", intskill, Sys_MilliSeconds() - starttime, charfile); - } //end if -#endif //DEBUG + } // end if +#endif // DEBUG return handle; - } //end if + } // end if // botimport.Print(PRT_WARNING, "couldn't find skill %d in %s\n", intskill, charfile); // - if (!reload) - { - //try to load a cached default character with the given skill + if (!reload) { + // try to load a cached default character with the given skill cachedhandle = BotFindCachedCharacter(DEFAULT_CHARACTER, skill); - if (cachedhandle) - { + if (cachedhandle) { botimport.Print(PRT_MESSAGE, "loaded cached default skill %d from %s\n", intskill, charfile); return cachedhandle; - } //end if - } //end if - //try to load the default character with the given skill + } // end if + } // end if + // try to load the default character with the given skill ch = BotLoadCharacterFromFile(DEFAULT_CHARACTER, intskill); - if (ch) - { + if (ch) { botcharacters[handle] = ch; botimport.Print(PRT_MESSAGE, "loaded default skill %d from %s\n", intskill, charfile); return handle; - } //end if + } // end if // - if (!reload) - { - //try to load a cached character with any skill + if (!reload) { + // try to load a cached character with any skill cachedhandle = BotFindCachedCharacter(charfile, -1); - if (cachedhandle) - { + if (cachedhandle) { botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", botcharacters[cachedhandle]->skill, charfile); return cachedhandle; - } //end if - } //end if - //try to load a character with any skill + } // end if + } // end if + // try to load a character with any skill ch = BotLoadCharacterFromFile(charfile, -1); - if (ch) - { + if (ch) { botcharacters[handle] = ch; botimport.Print(PRT_MESSAGE, "loaded skill %f from %s\n", ch->skill, charfile); return handle; - } //end if + } // end if // - if (!reload) - { - //try to load a cached character with any skill + if (!reload) { + // try to load a cached character with any skill cachedhandle = BotFindCachedCharacter(DEFAULT_CHARACTER, -1); - if (cachedhandle) - { + if (cachedhandle) { botimport.Print(PRT_MESSAGE, "loaded cached default skill %f from %s\n", botcharacters[cachedhandle]->skill, charfile); return cachedhandle; - } //end if - } //end if - //try to load a character with any skill + } // end if + } // end if + // try to load a character with any skill ch = BotLoadCharacterFromFile(DEFAULT_CHARACTER, -1); - if (ch) - { + if (ch) { botcharacters[handle] = ch; botimport.Print(PRT_MESSAGE, "loaded default skill %f from %s\n", ch->skill, charfile); return handle; - } //end if + } // end if // botimport.Print(PRT_WARNING, "couldn't load any skill from %s\n", charfile); - //couldn't load any character + // couldn't load any character return 0; -} //end of the function BotLoadCachedCharacter +} // end of the function BotLoadCachedCharacter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadCharacterSkill(char *charfile, float skill) -{ +int BotLoadCharacterSkill(char *charfile, float skill) { int ch, defaultch; defaultch = BotLoadCachedCharacter(DEFAULT_CHARACTER, skill, qfalse); ch = BotLoadCachedCharacter(charfile, skill, LibVarGetValue("bot_reloadcharacters")); - if (defaultch && ch) - { + if (defaultch && ch) { BotDefaultCharacteristics(botcharacters[ch], botcharacters[defaultch]); - } //end if + } // end if return ch; -} //end of the function BotLoadCharacterSkill +} // end of the function BotLoadCharacterSkill //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotInterpolateCharacters(int handle1, int handle2, float desiredskill) -{ +int BotInterpolateCharacters(int handle1, int handle2, float desiredskill) { bot_character_t *ch1, *ch2, *out; int i, handle; float scale; @@ -528,268 +476,256 @@ int BotInterpolateCharacters(int handle1, int handle2, float desiredskill) ch2 = BotCharacterFromHandle(handle2); if (!ch1 || !ch2) return 0; - //find a free spot for a character - for (handle = 1; handle <= MAX_CLIENTS; handle++) - { - if (!botcharacters[handle]) break; - } //end for - if (handle > MAX_CLIENTS) return 0; - out = (bot_character_t *) GetClearedMemory(sizeof(bot_character_t) + - MAX_CHARACTERISTICS * sizeof(bot_characteristic_t)); + // find a free spot for a character + for (handle = 1; handle <= MAX_CLIENTS; handle++) { + if (!botcharacters[handle]) + break; + } // end for + if (handle > MAX_CLIENTS) + return 0; + out = (bot_character_t *)GetClearedMemory(sizeof(bot_character_t) + MAX_CHARACTERISTICS * sizeof(bot_characteristic_t)); out->skill = desiredskill; strcpy(out->filename, ch1->filename); botcharacters[handle] = out; - scale = (float) (desiredskill - ch1->skill) / (ch2->skill - ch1->skill); - for (i = 0; i < MAX_CHARACTERISTICS; i++) - { + scale = (float)(desiredskill - ch1->skill) / (ch2->skill - ch1->skill); + for (i = 0; i < MAX_CHARACTERISTICS; i++) { // - if (ch1->c[i].type == CT_FLOAT && ch2->c[i].type == CT_FLOAT) - { + if (ch1->c[i].type == CT_FLOAT && ch2->c[i].type == CT_FLOAT) { out->c[i].type = CT_FLOAT; - out->c[i].value._float = ch1->c[i].value._float + - (ch2->c[i].value._float - ch1->c[i].value._float) * scale; - } //end if - else if (ch1->c[i].type == CT_INTEGER) - { + out->c[i].value._float = ch1->c[i].value._float + (ch2->c[i].value._float - ch1->c[i].value._float) * scale; + } // end if + else if (ch1->c[i].type == CT_INTEGER) { out->c[i].type = CT_INTEGER; out->c[i].value.integer = ch1->c[i].value.integer; - } //end else if - else if (ch1->c[i].type == CT_STRING) - { + } // end else if + else if (ch1->c[i].type == CT_STRING) { out->c[i].type = CT_STRING; - out->c[i].value.string = (char *) GetMemory(strlen(ch1->c[i].value.string)+1); + out->c[i].value.string = (char *)GetMemory(strlen(ch1->c[i].value.string) + 1); strcpy(out->c[i].value.string, ch1->c[i].value.string); - } //end else if - } //end for + } // end else if + } // end for return handle; -} //end of the function BotInterpolateCharacters +} // end of the function BotInterpolateCharacters //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadCharacter(char *charfile, float skill) -{ +int BotLoadCharacter(char *charfile, float skill) { int firstskill, secondskill, handle; - //make sure the skill is in the valid range - if (skill < 1.0) skill = 1.0; - else if (skill > 5.0) skill = 5.0; - //skill 1, 4 and 5 should be available in the character files - if (skill == 1.0 || skill == 4.0 || skill == 5.0) - { + // make sure the skill is in the valid range + if (skill < 1.0) + skill = 1.0; + else if (skill > 5.0) + skill = 5.0; + // skill 1, 4 and 5 should be available in the character files + if (skill == 1.0 || skill == 4.0 || skill == 5.0) { return BotLoadCharacterSkill(charfile, skill); - } //end if - //check if there's a cached skill + } // end if + // check if there's a cached skill handle = BotFindCachedCharacter(charfile, skill); - if (handle) - { + if (handle) { botimport.Print(PRT_MESSAGE, "loaded cached skill %f from %s\n", skill, charfile); return handle; - } //end if - if (skill < 4.0) - { - //load skill 1 and 4 + } // end if + if (skill < 4.0) { + // load skill 1 and 4 firstskill = BotLoadCharacterSkill(charfile, 1); - if (!firstskill) return 0; + if (!firstskill) + return 0; secondskill = BotLoadCharacterSkill(charfile, 4); - if (!secondskill) return firstskill; - } //end if - else - { - //load skill 4 and 5 + if (!secondskill) + return firstskill; + } // end if + else { + // load skill 4 and 5 firstskill = BotLoadCharacterSkill(charfile, 4); - if (!firstskill) return 0; + if (!firstskill) + return 0; secondskill = BotLoadCharacterSkill(charfile, 5); - if (!secondskill) return firstskill; - } //end else - //interpolate between the two skills + if (!secondskill) + return firstskill; + } // end else + // interpolate between the two skills handle = BotInterpolateCharacters(firstskill, secondskill, skill); - if (!handle) return 0; - //write the character to the log file + if (!handle) + return 0; + // write the character to the log file BotDumpCharacter(botcharacters[handle]); // return handle; -} //end of the function BotLoadCharacter +} // end of the function BotLoadCharacter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int CheckCharacteristicIndex(int character, int index) -{ +int CheckCharacteristicIndex(int character, int index) { bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return qfalse; - if (index < 0 || index >= MAX_CHARACTERISTICS) - { + if (!ch) + return qfalse; + if (index < 0 || index >= MAX_CHARACTERISTICS) { botimport.Print(PRT_ERROR, "characteristic %d does not exist\n", index); return qfalse; - } //end if - if (!ch->c[index].type) - { + } // end if + if (!ch->c[index].type) { botimport.Print(PRT_ERROR, "characteristic %d is not initialized\n", index); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function CheckCharacteristicIndex +} // end of the function CheckCharacteristicIndex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float Characteristic_Float(int character, int index) -{ +float Characteristic_Float(int character, int index) { bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return 0; - //check if the index is in range - if (!CheckCharacteristicIndex(character, index)) return 0; - //an integer will be converted to a float - if (ch->c[index].type == CT_INTEGER) - { - return (float) ch->c[index].value.integer; - } //end if - //floats are just returned - else if (ch->c[index].type == CT_FLOAT) - { + if (!ch) + return 0; + // check if the index is in range + if (!CheckCharacteristicIndex(character, index)) + return 0; + // an integer will be converted to a float + if (ch->c[index].type == CT_INTEGER) { + return (float)ch->c[index].value.integer; + } // end if + // floats are just returned + else if (ch->c[index].type == CT_FLOAT) { return ch->c[index].value._float; - } //end else if - //cannot convert a string pointer to a float - else - { + } // end else if + // cannot convert a string pointer to a float + else { botimport.Print(PRT_ERROR, "characteristic %d is not a float\n", index); return 0; - } //end else if -// return 0; -} //end of the function Characteristic_Float + } // end else if + // return 0; +} // end of the function Characteristic_Float //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float Characteristic_BFloat(int character, int index, float min, float max) -{ +float Characteristic_BFloat(int character, int index, float min, float max) { float value; bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return 0; - if (min > max) - { + if (!ch) + return 0; + if (min > max) { botimport.Print(PRT_ERROR, "cannot bound characteristic %d between %f and %f\n", index, min, max); return 0; - } //end if + } // end if value = Characteristic_Float(character, index); - if (value < min) return min; - if (value > max) return max; + if (value < min) + return min; + if (value > max) + return max; return value; -} //end of the function Characteristic_BFloat +} // end of the function Characteristic_BFloat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Characteristic_Integer(int character, int index) -{ +int Characteristic_Integer(int character, int index) { bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return 0; - //check if the index is in range - if (!CheckCharacteristicIndex(character, index)) return 0; - //an integer will just be returned - if (ch->c[index].type == CT_INTEGER) - { + if (!ch) + return 0; + // check if the index is in range + if (!CheckCharacteristicIndex(character, index)) + return 0; + // an integer will just be returned + if (ch->c[index].type == CT_INTEGER) { return ch->c[index].value.integer; - } //end if - //floats are casted to integers - else if (ch->c[index].type == CT_FLOAT) - { - return (int) ch->c[index].value._float; - } //end else if - else - { + } // end if + // floats are casted to integers + else if (ch->c[index].type == CT_FLOAT) { + return (int)ch->c[index].value._float; + } // end else if + else { botimport.Print(PRT_ERROR, "characteristic %d is not an integer\n", index); return 0; - } //end else if -// return 0; -} //end of the function Characteristic_Integer + } // end else if + // return 0; +} // end of the function Characteristic_Integer //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Characteristic_BInteger(int character, int index, int min, int max) -{ +int Characteristic_BInteger(int character, int index, int min, int max) { int value; bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return 0; - if (min > max) - { + if (!ch) + return 0; + if (min > max) { botimport.Print(PRT_ERROR, "cannot bound characteristic %d between %d and %d\n", index, min, max); return 0; - } //end if + } // end if value = Characteristic_Integer(character, index); - if (value < min) return min; - if (value > max) return max; + if (value < min) + return min; + if (value > max) + return max; return value; -} //end of the function Characteristic_BInteger +} // end of the function Characteristic_BInteger //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void Characteristic_String(int character, int index, char *buf, int size) -{ +void Characteristic_String(int character, int index, char *buf, int size) { bot_character_t *ch; ch = BotCharacterFromHandle(character); - if (!ch) return; - //check if the index is in range - if (!CheckCharacteristicIndex(character, index)) return; - //an integer will be converted to a float - if (ch->c[index].type == CT_STRING) - { - strncpy(buf, ch->c[index].value.string, size-1); - buf[size-1] = '\0'; + if (!ch) return; - } //end if - else - { + // check if the index is in range + if (!CheckCharacteristicIndex(character, index)) + return; + // an integer will be converted to a float + if (ch->c[index].type == CT_STRING) { + strncpy(buf, ch->c[index].value.string, size - 1); + buf[size - 1] = '\0'; + return; + } // end if + else { botimport.Print(PRT_ERROR, "characteristic %d is not a string\n", index); return; - } //end else if + } // end else if return; -} //end of the function Characteristic_String +} // end of the function Characteristic_String //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownCharacters(void) -{ +void BotShutdownCharacters(void) { int handle; - for (handle = 1; handle <= MAX_CLIENTS; handle++) - { - if (botcharacters[handle]) - { + for (handle = 1; handle <= MAX_CLIENTS; handle++) { + if (botcharacters[handle]) { BotFreeCharacter2(handle); - } //end if - } //end for -} //end of the function BotShutdownCharacters - + } // end if + } // end for +} // end of the function BotShutdownCharacters diff --git a/codemp/botlib/be_ai_chat.cpp b/codemp/botlib/be_ai_chat.cpp index fb29c53660..2b576d7baa 100644 --- a/codemp/botlib/be_ai_chat.cpp +++ b/codemp/botlib/be_ai_chat.cpp @@ -50,101 +50,90 @@ along with this program; if not, see . #include "be_ea.h" #include "be_ai_chat.h" - -//escape character -#define ESCAPE_CHAR 0x01 //'_' +// escape character +#define ESCAPE_CHAR 0x01 //'_' // // "hi ", people, " ", 0, " entered the game" -//becomes: +// becomes: // "hi _rpeople_ _v0_ entered the game" // -//match piece types -#define MT_VARIABLE 1 //variable match piece -#define MT_STRING 2 //string match piece -//reply chat key flags -#define RCKFL_AND 1 //key must be present -#define RCKFL_NOT 2 //key must be absent -#define RCKFL_NAME 4 //name of bot must be present -#define RCKFL_STRING 8 //key is a string -#define RCKFL_VARIABLES 16 //key is a match template -#define RCKFL_BOTNAMES 32 //key is a series of botnames -#define RCKFL_GENDERFEMALE 64 //bot must be female -#define RCKFL_GENDERMALE 128 //bot must be male -#define RCKFL_GENDERLESS 256 //bot must be genderless -//time to ignore a chat message after using it -#define CHATMESSAGE_RECENTTIME 20 - -//the actuall chat messages -typedef struct bot_chatmessage_s -{ - char *chatmessage; //chat message string - float time; //last time used - struct bot_chatmessage_s *next; //next chat message in a list +// match piece types +#define MT_VARIABLE 1 // variable match piece +#define MT_STRING 2 // string match piece +// reply chat key flags +#define RCKFL_AND 1 // key must be present +#define RCKFL_NOT 2 // key must be absent +#define RCKFL_NAME 4 // name of bot must be present +#define RCKFL_STRING 8 // key is a string +#define RCKFL_VARIABLES 16 // key is a match template +#define RCKFL_BOTNAMES 32 // key is a series of botnames +#define RCKFL_GENDERFEMALE 64 // bot must be female +#define RCKFL_GENDERMALE 128 // bot must be male +#define RCKFL_GENDERLESS 256 // bot must be genderless +// time to ignore a chat message after using it +#define CHATMESSAGE_RECENTTIME 20 + +// the actuall chat messages +typedef struct bot_chatmessage_s { + char *chatmessage; // chat message string + float time; // last time used + struct bot_chatmessage_s *next; // next chat message in a list } bot_chatmessage_t; -//bot chat type with chat lines -typedef struct bot_chattype_s -{ +// bot chat type with chat lines +typedef struct bot_chattype_s { char name[MAX_CHATTYPE_NAME]; int numchatmessages; bot_chatmessage_t *firstchatmessage; struct bot_chattype_s *next; } bot_chattype_t; -//bot chat lines -typedef struct bot_chat_s -{ +// bot chat lines +typedef struct bot_chat_s { bot_chattype_t *types; } bot_chat_t; -//random string -typedef struct bot_randomstring_s -{ +// random string +typedef struct bot_randomstring_s { char *string; struct bot_randomstring_s *next; } bot_randomstring_t; -//list with random strings -typedef struct bot_randomlist_s -{ +// list with random strings +typedef struct bot_randomlist_s { char *string; int numstrings; bot_randomstring_t *firstrandomstring; struct bot_randomlist_s *next; } bot_randomlist_t; -//synonym -typedef struct bot_synonym_s -{ +// synonym +typedef struct bot_synonym_s { char *string; float weight; struct bot_synonym_s *next; } bot_synonym_t; -//list with synonyms -typedef struct bot_synonymlist_s -{ +// list with synonyms +typedef struct bot_synonymlist_s { unsigned long int context; float totalweight; bot_synonym_t *firstsynonym; struct bot_synonymlist_s *next; } bot_synonymlist_t; -//fixed match string -typedef struct bot_matchstring_s -{ +// fixed match string +typedef struct bot_matchstring_s { char *string; struct bot_matchstring_s *next; } bot_matchstring_t; -//piece of a match template -typedef struct bot_matchpiece_s -{ +// piece of a match template +typedef struct bot_matchpiece_s { int type; bot_matchstring_t *firststring; int variable; struct bot_matchpiece_s *next; } bot_matchpiece_t; -//match template -typedef struct bot_matchtemplate_s -{ +// match template +typedef struct bot_matchtemplate_s { unsigned long int context; int type; int subtype; @@ -152,17 +141,15 @@ typedef struct bot_matchtemplate_s struct bot_matchtemplate_s *next; } bot_matchtemplate_t; -//reply chat key -typedef struct bot_replychatkey_s -{ +// reply chat key +typedef struct bot_replychatkey_s { int flags; char *string; bot_matchpiece_t *match; struct bot_replychatkey_s *next; } bot_replychatkey_t; -//reply chat -typedef struct bot_replychat_s -{ +// reply chat +typedef struct bot_replychat_s { bot_replychatkey_t *keys; float priority; int numchatmessages; @@ -170,49 +157,47 @@ typedef struct bot_replychat_s struct bot_replychat_s *next; } bot_replychat_t; -//string list -typedef struct bot_stringlist_s -{ +// string list +typedef struct bot_stringlist_s { char *string; struct bot_stringlist_s *next; } bot_stringlist_t; -//chat state of a bot -typedef struct bot_chatstate_s -{ - int gender; //0=it, 1=female, 2=male - int client; //client number - char name[32]; //name of the bot +// chat state of a bot +typedef struct bot_chatstate_s { + int gender; // 0=it, 1=female, 2=male + int client; // client number + char name[32]; // name of the bot char chatmessage[MAX_MESSAGE_SIZE]; int handle; - //the console messages visible to the bot - bot_consolemessage_t *firstmessage; //first message is the first typed message - bot_consolemessage_t *lastmessage; //last message is the last typed message, bottom of console - //number of console messages stored in the state + // the console messages visible to the bot + bot_consolemessage_t *firstmessage; // first message is the first typed message + bot_consolemessage_t *lastmessage; // last message is the last typed message, bottom of console + // number of console messages stored in the state int numconsolemessages; - //the bot chat lines + // the bot chat lines bot_chat_t *chat; } bot_chatstate_t; typedef struct bot_ichatdata_s { - bot_chat_t *chat; - char filename[MAX_QPATH]; - char chatname[MAX_QPATH]; + bot_chat_t *chat; + char filename[MAX_QPATH]; + char chatname[MAX_QPATH]; } bot_ichatdata_t; -bot_ichatdata_t *ichatdata[MAX_CLIENTS]; +bot_ichatdata_t *ichatdata[MAX_CLIENTS]; -bot_chatstate_t *botchatstates[MAX_CLIENTS+1]; -//console message heap +bot_chatstate_t *botchatstates[MAX_CLIENTS + 1]; +// console message heap bot_consolemessage_t *consolemessageheap = NULL; bot_consolemessage_t *freeconsolemessages = NULL; -//list with match strings +// list with match strings bot_matchtemplate_t *matchtemplates = NULL; -//list with synonyms +// list with synonyms bot_synonymlist_t *synonyms = NULL; -//list with random strings +// list with random strings bot_randomlist_t *randomstrings = NULL; -//reply chats +// reply chats bot_replychat_t *replychats = NULL; //======================================================================== @@ -221,20 +206,17 @@ bot_replychat_t *replychats = NULL; // Returns: - // Changes Globals: - //======================================================================== -bot_chatstate_t *BotChatStateFromHandle(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +bot_chatstate_t *BotChatStateFromHandle(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "chat state handle %d out of range\n", handle); return NULL; - } //end if - if (!botchatstates[handle]) - { + } // end if + if (!botchatstates[handle]) { botimport.Print(PRT_FATAL, "invalid chat state %d\n", handle); return NULL; - } //end if + } // end if return botchatstates[handle]; -} //end of the function BotChatStateFromHandle +} // end of the function BotChatStateFromHandle //=========================================================================== // initialize the heap with unused console messages // @@ -242,27 +224,25 @@ bot_chatstate_t *BotChatStateFromHandle(int handle) // Returns: - // Changes Globals: - //=========================================================================== -void InitConsoleMessageHeap(void) -{ +void InitConsoleMessageHeap(void) { int i, max_messages; - if (consolemessageheap) FreeMemory(consolemessageheap); + if (consolemessageheap) + FreeMemory(consolemessageheap); // - max_messages = (int) LibVarValue("max_messages", "1024"); - consolemessageheap = (bot_consolemessage_t *) GetClearedHunkMemory(max_messages * - sizeof(bot_consolemessage_t)); + max_messages = (int)LibVarValue("max_messages", "1024"); + consolemessageheap = (bot_consolemessage_t *)GetClearedHunkMemory(max_messages * sizeof(bot_consolemessage_t)); consolemessageheap[0].prev = NULL; consolemessageheap[0].next = &consolemessageheap[1]; - for (i = 1; i < max_messages-1; i++) - { + for (i = 1; i < max_messages - 1; i++) { consolemessageheap[i].prev = &consolemessageheap[i - 1]; consolemessageheap[i].next = &consolemessageheap[i + 1]; - } //end for - consolemessageheap[max_messages-1].prev = &consolemessageheap[max_messages-2]; - consolemessageheap[max_messages-1].next = NULL; - //pointer to the free console messages + } // end for + consolemessageheap[max_messages - 1].prev = &consolemessageheap[max_messages - 2]; + consolemessageheap[max_messages - 1].next = NULL; + // pointer to the free console messages freeconsolemessages = consolemessageheap; -} //end of the function InitConsoleMessageHeap +} // end of the function InitConsoleMessageHeap //=========================================================================== // allocate one console message from the heap // @@ -270,14 +250,15 @@ void InitConsoleMessageHeap(void) // Returns: - // Changes Globals: - //=========================================================================== -bot_consolemessage_t *AllocConsoleMessage(void) -{ +bot_consolemessage_t *AllocConsoleMessage(void) { bot_consolemessage_t *message; message = freeconsolemessages; - if (freeconsolemessages) freeconsolemessages = freeconsolemessages->next; - if (freeconsolemessages) freeconsolemessages->prev = NULL; + if (freeconsolemessages) + freeconsolemessages = freeconsolemessages->next; + if (freeconsolemessages) + freeconsolemessages->prev = NULL; return message; -} //end of the function AllocConsoleMessage +} // end of the function AllocConsoleMessage //=========================================================================== // deallocate one console message from the heap // @@ -285,104 +266,102 @@ bot_consolemessage_t *AllocConsoleMessage(void) // Returns: - // Changes Globals: - //=========================================================================== -void FreeConsoleMessage(bot_consolemessage_t *message) -{ - if (freeconsolemessages) freeconsolemessages->prev = message; +void FreeConsoleMessage(bot_consolemessage_t *message) { + if (freeconsolemessages) + freeconsolemessages->prev = message; message->prev = NULL; message->next = freeconsolemessages; freeconsolemessages = message; -} //end of the function FreeConsoleMessage +} // end of the function FreeConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotRemoveConsoleMessage(int chatstate, int handle) -{ +void BotRemoveConsoleMessage(int chatstate, int handle) { bot_consolemessage_t *m, *nextm; bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; + if (!cs) + return; - for (m = cs->firstmessage; m; m = nextm) - { + for (m = cs->firstmessage; m; m = nextm) { nextm = m->next; - if (m->handle == handle) - { - if (m->next) m->next->prev = m->prev; - else cs->lastmessage = m->prev; - if (m->prev) m->prev->next = m->next; - else cs->firstmessage = m->next; + if (m->handle == handle) { + if (m->next) + m->next->prev = m->prev; + else + cs->lastmessage = m->prev; + if (m->prev) + m->prev->next = m->next; + else + cs->firstmessage = m->next; FreeConsoleMessage(m); cs->numconsolemessages--; break; - } //end if - } //end for -} //end of the function BotRemoveConsoleMessage + } // end if + } // end for +} // end of the function BotRemoveConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotQueueConsoleMessage(int chatstate, int type, char *message) -{ +void BotQueueConsoleMessage(int chatstate, int type, char *message) { bot_consolemessage_t *m; bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; + if (!cs) + return; m = AllocConsoleMessage(); - if (!m) - { + if (!m) { botimport.Print(PRT_ERROR, "empty console message heap\n"); return; - } //end if + } // end if cs->handle++; - if (cs->handle <= 0 || cs->handle > 8192) cs->handle = 1; + if (cs->handle <= 0 || cs->handle > 8192) + cs->handle = 1; m->handle = cs->handle; m->time = AAS_Time(); m->type = type; strncpy(m->message, message, MAX_MESSAGE_SIZE); m->next = NULL; - if (cs->lastmessage) - { + if (cs->lastmessage) { cs->lastmessage->next = m; m->prev = cs->lastmessage; cs->lastmessage = m; - } //end if - else - { + } // end if + else { cs->lastmessage = m; cs->firstmessage = m; m->prev = NULL; - } //end if + } // end if cs->numconsolemessages++; -} //end of the function BotQueueConsoleMessage +} // end of the function BotQueueConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm) -{ +int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm) { bot_chatstate_t *cs; bot_consolemessage_t *firstmsg; cs = BotChatStateFromHandle(chatstate); - if (!cs) return 0; - if ((firstmsg = cs->firstmessage)) - { + if (!cs) + return 0; + if ((firstmsg = cs->firstmessage)) { cm->handle = firstmsg->handle; cm->time = firstmsg->time; cm->type = firstmsg->type; - Q_strncpyz(cm->message, firstmsg->message, - sizeof(cm->message)); + Q_strncpyz(cm->message, firstmsg->message, sizeof(cm->message)); /* We omit setting the two pointers in cm because pointer * size in the VM differs between the size in the engine on @@ -393,225 +372,207 @@ int BotNextConsoleMessage(int chatstate, bot_consolemessage_t *cm) */ return cm->handle; - } //end if + } // end if return 0; -} //end of the function BotConsoleMessage +} // end of the function BotConsoleMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotNumConsoleMessages(int chatstate) -{ +int BotNumConsoleMessages(int chatstate) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return 0; + if (!cs) + return 0; return cs->numconsolemessages; -} //end of the function BotNumConsoleMessages +} // end of the function BotNumConsoleMessages //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int IsWhiteSpace(char c) -{ - if ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || (c >= '0' && c <= '9') - || c == '(' || c == ')' - || c == '?' || c == ':' - || c == '\''|| c == '/' - || c == ',' || c == '.' - || c == '[' || c == ']' - || c == '-' || c == '_' - || c == '+' || c == '=') return qfalse; +int IsWhiteSpace(char c) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '(' || c == ')' || c == '?' || c == ':' || c == '\'' || c == '/' || + c == ',' || c == '.' || c == '[' || c == ']' || c == '-' || c == '_' || c == '+' || c == '=') + return qfalse; return qtrue; -} //end of the function IsWhiteSpace +} // end of the function IsWhiteSpace //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotRemoveTildes(char *message) -{ +void BotRemoveTildes(char *message) { int i; - //remove all tildes from the chat message - for (i = 0; message[i]; i++) - { - if (message[i] == '~') - { - memmove(&message[i], &message[i+1], strlen(&message[i+1])+1); - } //end if - } //end for -} //end of the function BotRemoveTildes + // remove all tildes from the chat message + for (i = 0; message[i]; i++) { + if (message[i] == '~') { + memmove(&message[i], &message[i + 1], strlen(&message[i + 1]) + 1); + } // end if + } // end for +} // end of the function BotRemoveTildes //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void UnifyWhiteSpaces(char *string) -{ +void UnifyWhiteSpaces(char *string) { char *ptr, *oldptr; - for (ptr = oldptr = string; *ptr; oldptr = ptr) - { - while(*ptr && IsWhiteSpace(*ptr)) ptr++; - if (ptr > oldptr) - { - //if not at the start and not at the end of the string - //write only one space - if (oldptr > string && *ptr) *oldptr++ = ' '; - //remove all other white spaces - if (ptr > oldptr) memmove(oldptr, ptr, strlen(ptr)+1); - } //end if - while(*ptr && !IsWhiteSpace(*ptr)) ptr++; - } //end while -} //end of the function UnifyWhiteSpaces + for (ptr = oldptr = string; *ptr; oldptr = ptr) { + while (*ptr && IsWhiteSpace(*ptr)) + ptr++; + if (ptr > oldptr) { + // if not at the start and not at the end of the string + // write only one space + if (oldptr > string && *ptr) + *oldptr++ = ' '; + // remove all other white spaces + if (ptr > oldptr) + memmove(oldptr, ptr, strlen(ptr) + 1); + } // end if + while (*ptr && !IsWhiteSpace(*ptr)) + ptr++; + } // end while +} // end of the function UnifyWhiteSpaces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int StringContains(char *str1, char *str2, int casesensitive) -{ +int StringContains(char *str1, char *str2, int casesensitive) { int len, i, j, index; - if (str1 == NULL || str2 == NULL) return -1; + if (str1 == NULL || str2 == NULL) + return -1; len = strlen(str1) - strlen(str2); index = 0; - for (i = 0; i <= len; i++, str1++, index++) - { - for (j = 0; str2[j]; j++) - { - if (casesensitive) - { - if (str1[j] != str2[j]) break; - } //end if - else - { - if (toupper(str1[j]) != toupper(str2[j])) break; - } //end else - } //end for - if (!str2[j]) return index; - } //end for + for (i = 0; i <= len; i++, str1++, index++) { + for (j = 0; str2[j]; j++) { + if (casesensitive) { + if (str1[j] != str2[j]) + break; + } // end if + else { + if (toupper(str1[j]) != toupper(str2[j])) + break; + } // end else + } // end for + if (!str2[j]) + return index; + } // end for return -1; -} //end of the function StringContains +} // end of the function StringContains //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -char *StringContainsWord(char *str1, char *str2, int casesensitive) -{ +char *StringContainsWord(char *str1, char *str2, int casesensitive) { int len, i, j; len = strlen(str1) - strlen(str2); - for (i = 0; i <= len; i++, str1++) - { - //if not at the start of the string - if (i) - { - //skip to the start of the next word - while(*str1 && *str1 != ' ' && *str1 != '.' && *str1 != ',' && *str1 != '!') str1++; - if (!*str1) break; + for (i = 0; i <= len; i++, str1++) { + // if not at the start of the string + if (i) { + // skip to the start of the next word + while (*str1 && *str1 != ' ' && *str1 != '.' && *str1 != ',' && *str1 != '!') + str1++; + if (!*str1) + break; str1++; - } //end for - //compare the word - for (j = 0; str2[j]; j++) - { - if (casesensitive) - { - if (str1[j] != str2[j]) break; - } //end if - else - { - if (toupper(str1[j]) != toupper(str2[j])) break; - } //end else - } //end for - //if there was a word match - if (!str2[j]) - { - //if the first string has an end of word - if (!str1[j] || str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '!') return str1; - } //end if - } //end for + } // end for + // compare the word + for (j = 0; str2[j]; j++) { + if (casesensitive) { + if (str1[j] != str2[j]) + break; + } // end if + else { + if (toupper(str1[j]) != toupper(str2[j])) + break; + } // end else + } // end for + // if there was a word match + if (!str2[j]) { + // if the first string has an end of word + if (!str1[j] || str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '!') + return str1; + } // end if + } // end for return NULL; -} //end of the function StringContainsWord +} // end of the function StringContainsWord //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void StringReplaceWords(char *string, char *synonym, char *replacement) -{ +void StringReplaceWords(char *string, char *synonym, char *replacement) { char *str, *str2; - //find the synonym in the string + // find the synonym in the string str = StringContainsWord(string, synonym, qfalse); - //if the synonym occured in the string - while(str) - { - //if the synonym isn't part of the replacement which is already in the string - //usefull for abreviations + // if the synonym occured in the string + while (str) { + // if the synonym isn't part of the replacement which is already in the string + // usefull for abreviations str2 = StringContainsWord(string, replacement, qfalse); - while(str2) - { - if (str2 <= str && str < str2 + strlen(replacement)) break; - str2 = StringContainsWord(str2+1, replacement, qfalse); - } //end while - if (!str2) - { - memmove(str + strlen(replacement), str+strlen(synonym), strlen(str+strlen(synonym))+1); - //append the synonum replacement + while (str2) { + if (str2 <= str && str < str2 + strlen(replacement)) + break; + str2 = StringContainsWord(str2 + 1, replacement, qfalse); + } // end while + if (!str2) { + memmove(str + strlen(replacement), str + strlen(synonym), strlen(str + strlen(synonym)) + 1); + // append the synonum replacement Com_Memcpy(str, replacement, strlen(replacement)); - } //end if - //find the next synonym in the string - str = StringContainsWord(str+strlen(replacement), synonym, qfalse); - } //end if -} //end of the function StringReplaceWords + } // end if + // find the next synonym in the string + str = StringContainsWord(str + strlen(replacement), synonym, qfalse); + } // end if +} // end of the function StringReplaceWords //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpSynonymList(bot_synonymlist_t *synlist) -{ +void BotDumpSynonymList(bot_synonymlist_t *synlist) { FILE *fp; bot_synonymlist_t *syn; bot_synonym_t *synonym; fp = Log_FilePointer(); - if (!fp) return; - for (syn = synlist; syn; syn = syn->next) - { - fprintf(fp, "%ld : [", syn->context); - for (synonym = syn->firstsynonym; synonym; synonym = synonym->next) - { + if (!fp) + return; + for (syn = synlist; syn; syn = syn->next) { + fprintf(fp, "%ld : [", syn->context); + for (synonym = syn->firstsynonym; synonym; synonym = synonym->next) { fprintf(fp, "(\"%s\", %1.2f)", synonym->string, synonym->weight); - if (synonym->next) fprintf(fp, ", "); - } //end for + if (synonym->next) + fprintf(fp, ", "); + } // end for fprintf(fp, "]\n"); - } //end for -} //end of the function BotDumpSynonymList + } // end for +} // end of the function BotDumpSynonymList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_synonymlist_t *BotLoadSynonyms(char *filename) -{ +bot_synonymlist_t *BotLoadSynonyms(char *filename) { int pass, size, contextlevel, numsynonyms; unsigned long int context, contextstack[32]; char *ptr = NULL; @@ -621,157 +582,139 @@ bot_synonymlist_t *BotLoadSynonyms(char *filename) bot_synonym_t *synonym, *lastsynonym; size = 0; - synlist = NULL; //make compiler happy - syn = NULL; //make compiler happy - synonym = NULL; //make compiler happy - //the synonyms are parsed in two phases - for (pass = 0; pass < 2; pass++) - { + synlist = NULL; // make compiler happy + syn = NULL; // make compiler happy + synonym = NULL; // make compiler happy + // the synonyms are parsed in two phases + for (pass = 0; pass < 2; pass++) { // - if (pass && size) ptr = (char *) GetClearedHunkMemory(size); + if (pass && size) + ptr = (char *)GetClearedHunkMemory(size); // PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(filename); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", filename); return NULL; - } //end if + } // end if // context = 0; contextlevel = 0; - synlist = NULL; //list synonyms - lastsyn = NULL; //last synonym in the list + synlist = NULL; // list synonyms + lastsyn = NULL; // last synonym in the list // - while(PC_ReadToken(source, &token)) - { - if (token.type == TT_NUMBER) - { + while (PC_ReadToken(source, &token)) { + if (token.type == TT_NUMBER) { context |= token.intvalue; contextstack[contextlevel] = token.intvalue; contextlevel++; - if (contextlevel >= 32) - { + if (contextlevel >= 32) { SourceError(source, "more than 32 context levels"); FreeSource(source); return NULL; - } //end if - if (!PC_ExpectTokenString(source, "{")) - { + } // end if + if (!PC_ExpectTokenString(source, "{")) { FreeSource(source); return NULL; - } //end if - } //end if - else if (token.type == TT_PUNCTUATION) - { - if (!strcmp(token.string, "}")) - { + } // end if + } // end if + else if (token.type == TT_PUNCTUATION) { + if (!strcmp(token.string, "}")) { contextlevel--; - if (contextlevel < 0) - { + if (contextlevel < 0) { SourceError(source, "too many }"); FreeSource(source); return NULL; - } //end if + } // end if context &= ~contextstack[contextlevel]; - } //end if - else if (!strcmp(token.string, "[")) - { + } // end if + else if (!strcmp(token.string, "[")) { size += sizeof(bot_synonymlist_t); - if (pass) - { - syn = (bot_synonymlist_t *) ptr; + if (pass) { + syn = (bot_synonymlist_t *)ptr; ptr += sizeof(bot_synonymlist_t); syn->context = context; syn->firstsynonym = NULL; syn->next = NULL; - if (lastsyn) lastsyn->next = syn; - else synlist = syn; + if (lastsyn) + lastsyn->next = syn; + else + synlist = syn; lastsyn = syn; - } //end if + } // end if numsynonyms = 0; lastsynonym = NULL; - while(1) - { + while (1) { size_t len; - if (!PC_ExpectTokenString(source, "(") || - !PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + if (!PC_ExpectTokenString(source, "(") || !PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - if (strlen(token.string) <= 0) - { + if (strlen(token.string) <= 0) { SourceError(source, "empty string"); FreeSource(source); return NULL; - } //end if + } // end if len = strlen(token.string) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_synonym_t) + len; - if (pass) - { - synonym = (bot_synonym_t *) ptr; + if (pass) { + synonym = (bot_synonym_t *)ptr; ptr += sizeof(bot_synonym_t); synonym->string = ptr; ptr += len; strcpy(synonym->string, token.string); // - if (lastsynonym) lastsynonym->next = synonym; - else syn->firstsynonym = synonym; + if (lastsynonym) + lastsynonym->next = synonym; + else + syn->firstsynonym = synonym; lastsynonym = synonym; - } //end if + } // end if numsynonyms++; - if (!PC_ExpectTokenString(source, ",") || - !PC_ExpectTokenType(source, TT_NUMBER, 0, &token) || - !PC_ExpectTokenString(source, ")")) - { + if (!PC_ExpectTokenString(source, ",") || !PC_ExpectTokenType(source, TT_NUMBER, 0, &token) || !PC_ExpectTokenString(source, ")")) { FreeSource(source); return NULL; - } //end if - if (pass) - { + } // end if + if (pass) { synonym->weight = token.floatvalue; syn->totalweight += synonym->weight; - } //end if - if (PC_CheckTokenString(source, "]")) break; - if (!PC_ExpectTokenString(source, ",")) - { + } // end if + if (PC_CheckTokenString(source, "]")) + break; + if (!PC_ExpectTokenString(source, ",")) { FreeSource(source); return NULL; - } //end if - } //end while - if (numsynonyms < 2) - { + } // end if + } // end while + if (numsynonyms < 2) { SourceError(source, "synonym must have at least two entries"); FreeSource(source); return NULL; - } //end if - } //end else - else - { + } // end if + } // end else + else { SourceError(source, "unexpected %s", token.string); FreeSource(source); return NULL; - } //end if - } //end else if - } //end while + } // end if + } // end else if + } // end while // FreeSource(source); // - if (contextlevel > 0) - { + if (contextlevel > 0) { SourceError(source, "missing }"); return NULL; - } //end if - } //end for + } // end if + } // end for botimport.Print(PRT_MESSAGE, "loaded %s\n", filename); // - //BotDumpSynonymList(synlist); + // BotDumpSynonymList(synlist); // return synlist; -} //end of the function BotLoadSynonyms +} // end of the function BotLoadSynonyms //=========================================================================== // replace all the synonyms in the string // @@ -779,192 +722,187 @@ bot_synonymlist_t *BotLoadSynonyms(char *filename) // Returns: - // Changes Globals: - //=========================================================================== -void BotReplaceSynonyms(char *string, unsigned long int context) -{ +void BotReplaceSynonyms(char *string, unsigned long int context) { bot_synonymlist_t *syn; bot_synonym_t *synonym; - for (syn = synonyms; syn; syn = syn->next) - { - if (!(syn->context & context)) continue; - for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next) - { + for (syn = synonyms; syn; syn = syn->next) { + if (!(syn->context & context)) + continue; + for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next) { StringReplaceWords(string, synonym->string, syn->firstsynonym->string); - } //end for - } //end for -} //end of the function BotReplaceSynonyms + } // end for + } // end for +} // end of the function BotReplaceSynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotReplaceWeightedSynonyms(char *string, unsigned long int context) -{ +void BotReplaceWeightedSynonyms(char *string, unsigned long int context) { bot_synonymlist_t *syn; bot_synonym_t *synonym, *replacement; float weight, curweight; - for (syn = synonyms; syn; syn = syn->next) - { - if (!(syn->context & context)) continue; - //choose a weighted random replacement synonym + for (syn = synonyms; syn; syn = syn->next) { + if (!(syn->context & context)) + continue; + // choose a weighted random replacement synonym weight = Q_flrand(0.0f, 1.0f) * syn->totalweight; - if (!weight) continue; + if (!weight) + continue; curweight = 0; - for (replacement = syn->firstsynonym; replacement; replacement = replacement->next) - { + for (replacement = syn->firstsynonym; replacement; replacement = replacement->next) { curweight += replacement->weight; - if (weight < curweight) break; - } //end for - if (!replacement) continue; - //replace all synonyms with the replacement - for (synonym = syn->firstsynonym; synonym; synonym = synonym->next) - { - if (synonym == replacement) continue; + if (weight < curweight) + break; + } // end for + if (!replacement) + continue; + // replace all synonyms with the replacement + for (synonym = syn->firstsynonym; synonym; synonym = synonym->next) { + if (synonym == replacement) + continue; StringReplaceWords(string, synonym->string, replacement->string); - } //end for - } //end for -} //end of the function BotReplaceWeightedSynonyms + } // end for + } // end for +} // end of the function BotReplaceWeightedSynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotReplaceReplySynonyms(char *string, unsigned long int context) -{ +void BotReplaceReplySynonyms(char *string, unsigned long int context) { char *str1, *str2, *replacement; bot_synonymlist_t *syn; bot_synonym_t *synonym; - for (str1 = string; *str1; ) - { - //go to the start of the next word - while(*str1 && *str1 <= ' ') str1++; - if (!*str1) break; + for (str1 = string; *str1;) { + // go to the start of the next word + while (*str1 && *str1 <= ' ') + str1++; + if (!*str1) + break; // - for (syn = synonyms; syn; syn = syn->next) - { - if (!(syn->context & context)) continue; - for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next) - { - //if the synonym is not at the front of the string continue + for (syn = synonyms; syn; syn = syn->next) { + if (!(syn->context & context)) + continue; + for (synonym = syn->firstsynonym->next; synonym; synonym = synonym->next) { + // if the synonym is not at the front of the string continue str2 = StringContainsWord(str1, synonym->string, qfalse); - if (!str2 || str2 != str1) continue; + if (!str2 || str2 != str1) + continue; // replacement = syn->firstsynonym->string; - //if the replacement IS in front of the string continue + // if the replacement IS in front of the string continue str2 = StringContainsWord(str1, replacement, qfalse); - if (str2 && str2 == str1) continue; + if (str2 && str2 == str1) + continue; // - memmove(str1 + strlen(replacement), str1+strlen(synonym->string), - strlen(str1+strlen(synonym->string)) + 1); - //append the synonum replacement + memmove(str1 + strlen(replacement), str1 + strlen(synonym->string), strlen(str1 + strlen(synonym->string)) + 1); + // append the synonum replacement Com_Memcpy(str1, replacement, strlen(replacement)); // break; - } //end for - //if a synonym has been replaced - if (synonym) break; - } //end for - //skip over this word - while(*str1 && *str1 > ' ') str1++; - if (!*str1) break; - } //end while -} //end of the function BotReplaceReplySynonyms + } // end for + // if a synonym has been replaced + if (synonym) + break; + } // end for + // skip over this word + while (*str1 && *str1 > ' ') + str1++; + if (!*str1) + break; + } // end while +} // end of the function BotReplaceReplySynonyms //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadChatMessage(source_t *source, char *chatmessagestring) -{ +int BotLoadChatMessage(source_t *source, char *chatmessagestring) { char *ptr; token_t token; ptr = chatmessagestring; *ptr = 0; // - while(1) - { - if (!PC_ExpectAnyToken(source, &token)) return qfalse; - //fixed string - if (token.type == TT_STRING) - { + while (1) { + if (!PC_ExpectAnyToken(source, &token)) + return qfalse; + // fixed string + if (token.type == TT_STRING) { StripDoubleQuotes(token.string); - if (strlen(ptr) + strlen(token.string) + 1 > MAX_MESSAGE_SIZE) - { + if (strlen(ptr) + strlen(token.string) + 1 > MAX_MESSAGE_SIZE) { SourceError(source, "chat message too long"); return qfalse; - } //end if + } // end if strcat(ptr, token.string); - } //end else if - //variable string - else if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER)) - { - if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE) - { + } // end else if + // variable string + else if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER)) { + if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE) { SourceError(source, "chat message too long"); return qfalse; - } //end if + } // end if sprintf(&ptr[strlen(ptr)], "%cv%ld%c", ESCAPE_CHAR, token.intvalue, ESCAPE_CHAR); - } //end if - //random string - else if (token.type == TT_NAME) - { - if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE) - { + } // end if + // random string + else if (token.type == TT_NAME) { + if (strlen(ptr) + 7 > MAX_MESSAGE_SIZE) { SourceError(source, "chat message too long"); return qfalse; - } //end if + } // end if sprintf(&ptr[strlen(ptr)], "%cr%s%c", ESCAPE_CHAR, token.string, ESCAPE_CHAR); - } //end else if - else - { + } // end else if + else { SourceError(source, "unknown message component %s", token.string); return qfalse; - } //end else - if (PC_CheckTokenString(source, ";")) break; - if (!PC_ExpectTokenString(source, ",")) return qfalse; - } //end while + } // end else + if (PC_CheckTokenString(source, ";")) + break; + if (!PC_ExpectTokenString(source, ",")) + return qfalse; + } // end while // return qtrue; -} //end of the function BotLoadChatMessage +} // end of the function BotLoadChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpRandomStringList(bot_randomlist_t *randomlist) -{ +void BotDumpRandomStringList(bot_randomlist_t *randomlist) { FILE *fp; bot_randomlist_t *random; bot_randomstring_t *rs; fp = Log_FilePointer(); - if (!fp) return; - for (random = randomlist; random; random = random->next) - { + if (!fp) + return; + for (random = randomlist; random; random = random->next) { fprintf(fp, "%s = {", random->string); - for (rs = random->firstrandomstring; rs; rs = rs->next) - { + for (rs = random->firstrandomstring; rs; rs = rs->next) { fprintf(fp, "\"%s\"", rs->string); - if (rs->next) fprintf(fp, ", "); - else fprintf(fp, "}\n"); - } //end for - } //end for -} //end of the function BotDumpRandomStringList + if (rs->next) + fprintf(fp, ", "); + else + fprintf(fp, "}\n"); + } // end for + } // end for +} // end of the function BotDumpRandomStringList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_randomlist_t *BotLoadRandomStrings(char *filename) -{ +bot_randomlist_t *BotLoadRandomStrings(char *filename) { int pass, size; char *ptr = NULL, chatmessagestring[MAX_MESSAGE_SIZE]; source_t *source; @@ -974,43 +912,39 @@ bot_randomlist_t *BotLoadRandomStrings(char *filename) #ifdef DEBUG int starttime = Sys_MilliSeconds(); -#endif //DEBUG +#endif // DEBUG size = 0; randomlist = NULL; random = NULL; - //the synonyms are parsed in two phases - for (pass = 0; pass < 2; pass++) - { + // the synonyms are parsed in two phases + for (pass = 0; pass < 2; pass++) { // - if (pass && size) ptr = (char *) GetClearedHunkMemory(size); + if (pass && size) + ptr = (char *)GetClearedHunkMemory(size); // PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(filename); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", filename); return NULL; - } //end if + } // end if // - randomlist = NULL; //list - lastrandom = NULL; //last + randomlist = NULL; // list + lastrandom = NULL; // last // - while(PC_ReadToken(source, &token)) - { + while (PC_ReadToken(source, &token)) { size_t len; - if (token.type != TT_NAME) - { + if (token.type != TT_NAME) { SourceError(source, "unknown random %s", token.string); FreeSource(source); return NULL; - } //end if + } // end if len = strlen(token.string) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_randomlist_t) + len; - if (pass) - { - random = (bot_randomlist_t *) ptr; + if (pass) { + random = (bot_randomlist_t *)ptr; ptr += sizeof(bot_randomlist_t); random->string = ptr; ptr += len; @@ -1018,30 +952,27 @@ bot_randomlist_t *BotLoadRandomStrings(char *filename) random->firstrandomstring = NULL; random->numstrings = 0; // - if (lastrandom) lastrandom->next = random; - else randomlist = random; + if (lastrandom) + lastrandom->next = random; + else + randomlist = random; lastrandom = random; - } //end if - if (!PC_ExpectTokenString(source, "=") || - !PC_ExpectTokenString(source, "{")) - { + } // end if + if (!PC_ExpectTokenString(source, "=") || !PC_ExpectTokenString(source, "{")) { FreeSource(source); return NULL; - } //end if - while(!PC_CheckTokenString(source, "}")) - { + } // end if + while (!PC_CheckTokenString(source, "}")) { size_t len; - if (!BotLoadChatMessage(source, chatmessagestring)) - { + if (!BotLoadChatMessage(source, chatmessagestring)) { FreeSource(source); return NULL; - } //end if + } // end if len = strlen(chatmessagestring) + 1; len = PAD(len, sizeof(long)); size += sizeof(bot_randomstring_t) + len; - if (pass) - { - randomstring = (bot_randomstring_t *) ptr; + if (pass) { + randomstring = (bot_randomstring_t *)ptr; ptr += sizeof(bot_randomstring_t); randomstring->string = ptr; ptr += len; @@ -1050,120 +981,108 @@ bot_randomlist_t *BotLoadRandomStrings(char *filename) random->numstrings++; randomstring->next = random->firstrandomstring; random->firstrandomstring = randomstring; - } //end if - } //end while - } //end while - //free the source after one pass + } // end if + } // end while + } // end while + // free the source after one pass FreeSource(source); - } //end for + } // end for botimport.Print(PRT_MESSAGE, "loaded %s\n", filename); // #ifdef DEBUG botimport.Print(PRT_MESSAGE, "random strings %d msec\n", Sys_MilliSeconds() - starttime); - //BotDumpRandomStringList(randomlist); -#endif //DEBUG + // BotDumpRandomStringList(randomlist); +#endif // DEBUG // return randomlist; -} //end of the function BotLoadRandomStrings +} // end of the function BotLoadRandomStrings //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -char *RandomString(char *name) -{ +char *RandomString(char *name) { bot_randomlist_t *random; bot_randomstring_t *rs; int i; - for (random = randomstrings; random; random = random->next) - { - if (!strcmp(random->string, name)) - { + for (random = randomstrings; random; random = random->next) { + if (!strcmp(random->string, name)) { i = Q_flrand(0.0f, 1.0f) * random->numstrings; - for (rs = random->firstrandomstring; rs; rs = rs->next) - { - if (--i < 0) break; - } //end for - if (rs) - { + for (rs = random->firstrandomstring; rs; rs = rs->next) { + if (--i < 0) + break; + } // end for + if (rs) { return rs->string; - } //end if - } //end for - } //end for + } // end if + } // end for + } // end for return NULL; -} //end of the function RandomString +} // end of the function RandomString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpMatchTemplates(bot_matchtemplate_t *matches) -{ +void BotDumpMatchTemplates(bot_matchtemplate_t *matches) { FILE *fp; bot_matchtemplate_t *mt; bot_matchpiece_t *mp; bot_matchstring_t *ms; fp = Log_FilePointer(); - if (!fp) return; - for (mt = matches; mt; mt = mt->next) - { - fprintf(fp, "{ " ); - for (mp = mt->first; mp; mp = mp->next) - { - if (mp->type == MT_STRING) - { - for (ms = mp->firststring; ms; ms = ms->next) - { + if (!fp) + return; + for (mt = matches; mt; mt = mt->next) { + fprintf(fp, "{ "); + for (mp = mt->first; mp; mp = mp->next) { + if (mp->type == MT_STRING) { + for (ms = mp->firststring; ms; ms = ms->next) { fprintf(fp, "\"%s\"", ms->string); - if (ms->next) fprintf(fp, "|"); - } //end for - } //end if - else if (mp->type == MT_VARIABLE) - { + if (ms->next) + fprintf(fp, "|"); + } // end for + } // end if + else if (mp->type == MT_VARIABLE) { fprintf(fp, "%d", mp->variable); - } //end else if - if (mp->next) fprintf(fp, ", "); - } //end for + } // end else if + if (mp->next) + fprintf(fp, ", "); + } // end for fprintf(fp, " = (%d, %d);}\n", mt->type, mt->subtype); - } //end for -} //end of the function BotDumpMatchTemplates + } // end for +} // end of the function BotDumpMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeMatchPieces(bot_matchpiece_t *matchpieces) -{ +void BotFreeMatchPieces(bot_matchpiece_t *matchpieces) { bot_matchpiece_t *mp, *nextmp; bot_matchstring_t *ms, *nextms; - for (mp = matchpieces; mp; mp = nextmp) - { + for (mp = matchpieces; mp; mp = nextmp) { nextmp = mp->next; - if (mp->type == MT_STRING) - { - for (ms = mp->firststring; ms; ms = nextms) - { + if (mp->type == MT_STRING) { + for (ms = mp->firststring; ms; ms = nextms) { nextms = ms->next; FreeMemory(ms); - } //end for - } //end if + } // end for + } // end if FreeMemory(mp); - } //end for -} //end of the function BotFreeMatchPieces + } // end for +} // end of the function BotFreeMatchPieces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_matchpiece_t *BotLoadMatchPieces(source_t *source, char *endtoken) -{ +bot_matchpiece_t *BotLoadMatchPieces(source_t *source, char *endtoken) { int lastwasvariable, emptystring; token_t token; bot_matchpiece_t *matchpiece, *firstpiece, *lastpiece; @@ -1174,115 +1093,111 @@ bot_matchpiece_t *BotLoadMatchPieces(source_t *source, char *endtoken) // lastwasvariable = qfalse; // - while(PC_ReadToken(source, &token)) - { - if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER)) - { - if (token.intvalue >= MAX_MATCHVARIABLES) - { + while (PC_ReadToken(source, &token)) { + if (token.type == TT_NUMBER && (token.subtype & TT_INTEGER)) { + if (token.intvalue >= MAX_MATCHVARIABLES) { SourceError(source, "can't have more than %d match variables", MAX_MATCHVARIABLES); FreeSource(source); BotFreeMatchPieces(firstpiece); return NULL; - } //end if - if (lastwasvariable) - { + } // end if + if (lastwasvariable) { SourceError(source, "not allowed to have adjacent variables"); FreeSource(source); BotFreeMatchPieces(firstpiece); return NULL; - } //end if + } // end if lastwasvariable = qtrue; // - matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory(sizeof(bot_matchpiece_t)); + matchpiece = (bot_matchpiece_t *)GetClearedHunkMemory(sizeof(bot_matchpiece_t)); matchpiece->type = MT_VARIABLE; matchpiece->variable = token.intvalue; matchpiece->next = NULL; - if (lastpiece) lastpiece->next = matchpiece; - else firstpiece = matchpiece; + if (lastpiece) + lastpiece->next = matchpiece; + else + firstpiece = matchpiece; lastpiece = matchpiece; - } //end if - else if (token.type == TT_STRING) - { + } // end if + else if (token.type == TT_STRING) { // - matchpiece = (bot_matchpiece_t *) GetClearedHunkMemory(sizeof(bot_matchpiece_t)); + matchpiece = (bot_matchpiece_t *)GetClearedHunkMemory(sizeof(bot_matchpiece_t)); matchpiece->firststring = NULL; matchpiece->type = MT_STRING; matchpiece->variable = 0; matchpiece->next = NULL; - if (lastpiece) lastpiece->next = matchpiece; - else firstpiece = matchpiece; + if (lastpiece) + lastpiece->next = matchpiece; + else + firstpiece = matchpiece; lastpiece = matchpiece; // lastmatchstring = NULL; emptystring = qfalse; // - do - { - if (matchpiece->firststring) - { - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + do { + if (matchpiece->firststring) { + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeSource(source); BotFreeMatchPieces(firstpiece); return NULL; - } //end if - } //end if + } // end if + } // end if StripDoubleQuotes(token.string); - matchstring = (bot_matchstring_t *) GetClearedHunkMemory(sizeof(bot_matchstring_t) + strlen(token.string) + 1); - matchstring->string = (char *) matchstring + sizeof(bot_matchstring_t); + matchstring = (bot_matchstring_t *)GetClearedHunkMemory(sizeof(bot_matchstring_t) + strlen(token.string) + 1); + matchstring->string = (char *)matchstring + sizeof(bot_matchstring_t); strcpy(matchstring->string, token.string); - if (!strlen(token.string)) emptystring = qtrue; + if (!strlen(token.string)) + emptystring = qtrue; matchstring->next = NULL; - if (lastmatchstring) lastmatchstring->next = matchstring; - else matchpiece->firststring = matchstring; + if (lastmatchstring) + lastmatchstring->next = matchstring; + else + matchpiece->firststring = matchstring; lastmatchstring = matchstring; - } while(PC_CheckTokenString(source, "|")); - //if there was no empty string found - if (!emptystring) lastwasvariable = qfalse; - } //end if - else - { + } while (PC_CheckTokenString(source, "|")); + // if there was no empty string found + if (!emptystring) + lastwasvariable = qfalse; + } // end if + else { SourceError(source, "invalid token %s", token.string); FreeSource(source); BotFreeMatchPieces(firstpiece); return NULL; - } //end else - if (PC_CheckTokenString(source, endtoken)) break; - if (!PC_ExpectTokenString(source, ",")) - { + } // end else + if (PC_CheckTokenString(source, endtoken)) + break; + if (!PC_ExpectTokenString(source, ",")) { FreeSource(source); BotFreeMatchPieces(firstpiece); return NULL; - } //end if - } //end while + } // end if + } // end while return firstpiece; -} //end of the function BotLoadMatchPieces +} // end of the function BotLoadMatchPieces //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeMatchTemplates(bot_matchtemplate_t *mt) -{ +void BotFreeMatchTemplates(bot_matchtemplate_t *mt) { bot_matchtemplate_t *nextmt; - for (; mt; mt = nextmt) - { + for (; mt; mt = nextmt) { nextmt = mt->next; BotFreeMatchPieces(mt->first); FreeMemory(mt); - } //end for -} //end of the function BotFreeMatchTemplates + } // end for +} // end of the function BotFreeMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_matchtemplate_t *BotLoadMatchTemplates(char *matchfile) -{ +bot_matchtemplate_t *BotLoadMatchTemplates(char *matchfile) { source_t *source; token_t token; bot_matchtemplate_t *matchtemplate, *matches, *lastmatch; @@ -1290,254 +1205,224 @@ bot_matchtemplate_t *BotLoadMatchTemplates(char *matchfile) PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(matchfile); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", matchfile); return NULL; - } //end if + } // end if // - matches = NULL; //list with matches - lastmatch = NULL; //last match in the list + matches = NULL; // list with matches + lastmatch = NULL; // last match in the list - while(PC_ReadToken(source, &token)) - { - if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER)) - { + while (PC_ReadToken(source, &token)) { + if (token.type != TT_NUMBER || !(token.subtype & TT_INTEGER)) { SourceError(source, "expected integer, found %s", token.string); BotFreeMatchTemplates(matches); FreeSource(source); return NULL; - } //end if - //the context + } // end if + // the context context = token.intvalue; // - if (!PC_ExpectTokenString(source, "{")) - { + if (!PC_ExpectTokenString(source, "{")) { BotFreeMatchTemplates(matches); FreeSource(source); return NULL; - } //end if + } // end if // - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "}")) break; + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "}")) + break; // PC_UnreadLastToken(source); // - matchtemplate = (bot_matchtemplate_t *) GetClearedHunkMemory(sizeof(bot_matchtemplate_t)); + matchtemplate = (bot_matchtemplate_t *)GetClearedHunkMemory(sizeof(bot_matchtemplate_t)); matchtemplate->context = context; matchtemplate->next = NULL; - //add the match template to the list - if (lastmatch) lastmatch->next = matchtemplate; - else matches = matchtemplate; + // add the match template to the list + if (lastmatch) + lastmatch->next = matchtemplate; + else + matches = matchtemplate; lastmatch = matchtemplate; - //load the match template + // load the match template matchtemplate->first = BotLoadMatchPieces(source, "="); - if (!matchtemplate->first) - { + if (!matchtemplate->first) { BotFreeMatchTemplates(matches); return NULL; - } //end if - //read the match type - if (!PC_ExpectTokenString(source, "(") || - !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) - { + } // end if + // read the match type + if (!PC_ExpectTokenString(source, "(") || !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) { BotFreeMatchTemplates(matches); FreeSource(source); return NULL; - } //end if + } // end if matchtemplate->type = token.intvalue; - //read the match subtype - if (!PC_ExpectTokenString(source, ",") || - !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) - { + // read the match subtype + if (!PC_ExpectTokenString(source, ",") || !PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) { BotFreeMatchTemplates(matches); FreeSource(source); return NULL; - } //end if + } // end if matchtemplate->subtype = token.intvalue; - //read trailing punctuations - if (!PC_ExpectTokenString(source, ")") || - !PC_ExpectTokenString(source, ";")) - { + // read trailing punctuations + if (!PC_ExpectTokenString(source, ")") || !PC_ExpectTokenString(source, ";")) { BotFreeMatchTemplates(matches); FreeSource(source); return NULL; - } //end if - } //end while - } //end while - //free the source + } // end if + } // end while + } // end while + // free the source FreeSource(source); botimport.Print(PRT_MESSAGE, "loaded %s\n", matchfile); // - //BotDumpMatchTemplates(matches); + // BotDumpMatchTemplates(matches); // return matches; -} //end of the function BotLoadMatchTemplates +} // end of the function BotLoadMatchTemplates //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int StringsMatch(bot_matchpiece_t *pieces, bot_match_t *match) -{ +int StringsMatch(bot_matchpiece_t *pieces, bot_match_t *match) { int lastvariable, index; char *strptr, *newstrptr; bot_matchpiece_t *mp; bot_matchstring_t *ms; - //no last variable + // no last variable lastvariable = -1; - //pointer to the string to compare the match string with + // pointer to the string to compare the match string with strptr = match->string; - //Log_Write("match: %s", strptr); - //compare the string with the current match string - for (mp = pieces; mp; mp = mp->next) - { - //if it is a piece of string - if (mp->type == MT_STRING) - { + // Log_Write("match: %s", strptr); + // compare the string with the current match string + for (mp = pieces; mp; mp = mp->next) { + // if it is a piece of string + if (mp->type == MT_STRING) { newstrptr = NULL; - for (ms = mp->firststring; ms; ms = ms->next) - { - if (!strlen(ms->string)) - { + for (ms = mp->firststring; ms; ms = ms->next) { + if (!strlen(ms->string)) { newstrptr = strptr; break; - } //end if - //Log_Write("MT_STRING: %s", mp->string); + } // end if + // Log_Write("MT_STRING: %s", mp->string); index = StringContains(strptr, ms->string, qfalse); - if (index >= 0) - { + if (index >= 0) { newstrptr = strptr + index; - if (lastvariable >= 0) - { - match->variables[lastvariable].length = - (newstrptr - match->string) - match->variables[lastvariable].offset; - //newstrptr - match->variables[lastvariable].ptr; + if (lastvariable >= 0) { + match->variables[lastvariable].length = (newstrptr - match->string) - match->variables[lastvariable].offset; + // newstrptr - match->variables[lastvariable].ptr; lastvariable = -1; break; - } //end if - else if (index == 0) - { + } // end if + else if (index == 0) { break; - } //end else + } // end else newstrptr = NULL; - } //end if - } //end for - if (!newstrptr) return qfalse; + } // end if + } // end for + if (!newstrptr) + return qfalse; strptr = newstrptr + strlen(ms->string); - } //end if - //if it is a variable piece of string - else if (mp->type == MT_VARIABLE) - { - //Log_Write("MT_VARIABLE"); + } // end if + // if it is a variable piece of string + else if (mp->type == MT_VARIABLE) { + // Log_Write("MT_VARIABLE"); match->variables[mp->variable].offset = strptr - match->string; lastvariable = mp->variable; - } //end else if - } //end for - //if a match was found - if (!mp && (lastvariable >= 0 || !strlen(strptr))) - { - //if the last piece was a variable string - if (lastvariable >= 0) - { - assert( match->variables[lastvariable].offset >= 0 ); // bk001204 - match->variables[lastvariable].length = - strlen(&match->string[ (int) match->variables[lastvariable].offset]); - } //end if + } // end else if + } // end for + // if a match was found + if (!mp && (lastvariable >= 0 || !strlen(strptr))) { + // if the last piece was a variable string + if (lastvariable >= 0) { + assert(match->variables[lastvariable].offset >= 0); // bk001204 + match->variables[lastvariable].length = strlen(&match->string[(int)match->variables[lastvariable].offset]); + } // end if return qtrue; - } //end if + } // end if return qfalse; -} //end of the function StringsMatch +} // end of the function StringsMatch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotFindMatch(char *str, bot_match_t *match, unsigned long int context) -{ +int BotFindMatch(char *str, bot_match_t *match, unsigned long int context) { int i; bot_matchtemplate_t *ms; strncpy(match->string, str, MAX_MESSAGE_SIZE); - //remove any trailing enters - while(strlen(match->string) && - match->string[strlen(match->string)-1] == '\n') - { - match->string[strlen(match->string)-1] = '\0'; - } //end while - //compare the string with all the match strings - for (ms = matchtemplates; ms; ms = ms->next) - { - if (!(ms->context & context)) continue; - //reset the match variable offsets - for (i = 0; i < MAX_MATCHVARIABLES; i++) match->variables[i].offset = -1; + // remove any trailing enters + while (strlen(match->string) && match->string[strlen(match->string) - 1] == '\n') { + match->string[strlen(match->string) - 1] = '\0'; + } // end while + // compare the string with all the match strings + for (ms = matchtemplates; ms; ms = ms->next) { + if (!(ms->context & context)) + continue; + // reset the match variable offsets + for (i = 0; i < MAX_MATCHVARIABLES; i++) + match->variables[i].offset = -1; // - if (StringsMatch(ms->first, match)) - { + if (StringsMatch(ms->first, match)) { match->type = ms->type; match->subtype = ms->subtype; return qtrue; - } //end if - } //end for + } // end if + } // end for return qfalse; -} //end of the function BotFindMatch +} // end of the function BotFindMatch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotMatchVariable(bot_match_t *match, int variable, char *buf, int size) -{ - if (variable < 0 || variable >= MAX_MATCHVARIABLES) - { +void BotMatchVariable(bot_match_t *match, int variable, char *buf, int size) { + if (variable < 0 || variable >= MAX_MATCHVARIABLES) { botimport.Print(PRT_FATAL, "BotMatchVariable: variable out of range\n"); strcpy(buf, ""); return; - } //end if + } // end if - if (match->variables[variable].offset >= 0) - { + if (match->variables[variable].offset >= 0) { if (match->variables[variable].length < size) - size = match->variables[variable].length+1; - assert( match->variables[variable].offset >= 0 ); // bk001204 - strncpy(buf, &match->string[ (int) match->variables[variable].offset], size-1); - buf[size-1] = '\0'; - } //end if - else - { + size = match->variables[variable].length + 1; + assert(match->variables[variable].offset >= 0); // bk001204 + strncpy(buf, &match->string[(int)match->variables[variable].offset], size - 1); + buf[size - 1] = '\0'; + } // end if + else { strcpy(buf, ""); - } //end else + } // end else return; -} //end of the function BotMatchVariable +} // end of the function BotMatchVariable //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_stringlist_t *BotFindStringInList(bot_stringlist_t *list, char *string) -{ +bot_stringlist_t *BotFindStringInList(bot_stringlist_t *list, char *string) { bot_stringlist_t *s; - for (s = list; s; s = s->next) - { - if (!strcmp(s->string, string)) return s; - } //end for + for (s = list; s; s = s->next) { + if (!strcmp(s->string, string)) + return s; + } // end for return NULL; -} //end of the function BotFindStringInList +} // end of the function BotFindStringInList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_stringlist_t *BotCheckChatMessageIntegrety(char *message, bot_stringlist_t *stringlist) -{ +bot_stringlist_t *BotCheckChatMessageIntegrety(char *message, bot_stringlist_t *stringlist) { int i; char *msgptr; char temp[MAX_MESSAGE_SIZE]; @@ -1545,122 +1430,108 @@ bot_stringlist_t *BotCheckChatMessageIntegrety(char *message, bot_stringlist_t * msgptr = message; // - while(*msgptr) - { - if (*msgptr == ESCAPE_CHAR) - { + while (*msgptr) { + if (*msgptr == ESCAPE_CHAR) { msgptr++; - switch(*msgptr) + switch (*msgptr) { + case 'v': // variable { - case 'v': //variable - { - //step over the 'v' + // step over the 'v' + msgptr++; + while (*msgptr && *msgptr != ESCAPE_CHAR) msgptr++; - while(*msgptr && *msgptr != ESCAPE_CHAR) msgptr++; - //step over the trailing escape char - if (*msgptr) msgptr++; - break; - } //end case - case 'r': //random - { - //step over the 'r' + // step over the trailing escape char + if (*msgptr) msgptr++; - for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++) - { - temp[i] = *msgptr++; - } //end while - temp[i] = '\0'; - //step over the trailing escape char - if (*msgptr) msgptr++; - //find the random keyword - if (!RandomString(temp)) - { - if (!BotFindStringInList(stringlist, temp)) - { - Log_Write("%s = {\"%s\"} //MISSING RANDOM\r\n", temp, temp); - s = (struct bot_stringlist_s *)GetClearedMemory(sizeof(bot_stringlist_t) + strlen(temp) + 1); - s->string = (char *) s + sizeof(bot_stringlist_t); - strcpy(s->string, temp); - s->next = stringlist; - stringlist = s; - } //end if - } //end if - break; - } //end case - default: - { - botimport.Print(PRT_FATAL, "BotCheckChatMessageIntegrety: message \"%s\" invalid escape char\n", message); - break; - } //end default - } //end switch - } //end if - else - { + break; + } // end case + case 'r': // random + { + // step over the 'r' + msgptr++; + for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++) { + temp[i] = *msgptr++; + } // end while + temp[i] = '\0'; + // step over the trailing escape char + if (*msgptr) + msgptr++; + // find the random keyword + if (!RandomString(temp)) { + if (!BotFindStringInList(stringlist, temp)) { + Log_Write("%s = {\"%s\"} //MISSING RANDOM\r\n", temp, temp); + s = (struct bot_stringlist_s *)GetClearedMemory(sizeof(bot_stringlist_t) + strlen(temp) + 1); + s->string = (char *)s + sizeof(bot_stringlist_t); + strcpy(s->string, temp); + s->next = stringlist; + stringlist = s; + } // end if + } // end if + break; + } // end case + default: { + botimport.Print(PRT_FATAL, "BotCheckChatMessageIntegrety: message \"%s\" invalid escape char\n", message); + break; + } // end default + } // end switch + } // end if + else { msgptr++; - } //end else - } //end while + } // end else + } // end while return stringlist; -} //end of the function BotCheckChatMessageIntegrety +} // end of the function BotCheckChatMessageIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotCheckInitialChatIntegrety(bot_chat_t *chat) -{ +void BotCheckInitialChatIntegrety(bot_chat_t *chat) { bot_chattype_t *t; bot_chatmessage_t *cm; bot_stringlist_t *stringlist, *s, *nexts; stringlist = NULL; - for (t = chat->types; t; t = t->next) - { - for (cm = t->firstchatmessage; cm; cm = cm->next) - { + for (t = chat->types; t; t = t->next) { + for (cm = t->firstchatmessage; cm; cm = cm->next) { stringlist = BotCheckChatMessageIntegrety(cm->chatmessage, stringlist); - } //end for - } //end for - for (s = stringlist; s; s = nexts) - { + } // end for + } // end for + for (s = stringlist; s; s = nexts) { nexts = s->next; FreeMemory(s); - } //end for -} //end of the function BotCheckInitialChatIntegrety + } // end for +} // end of the function BotCheckInitialChatIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotCheckReplyChatIntegrety(bot_replychat_t *replychat) -{ +void BotCheckReplyChatIntegrety(bot_replychat_t *replychat) { bot_replychat_t *rp; bot_chatmessage_t *cm; bot_stringlist_t *stringlist, *s, *nexts; stringlist = NULL; - for (rp = replychat; rp; rp = rp->next) - { - for (cm = rp->firstchatmessage; cm; cm = cm->next) - { + for (rp = replychat; rp; rp = rp->next) { + for (cm = rp->firstchatmessage; cm; cm = cm->next) { stringlist = BotCheckChatMessageIntegrety(cm->chatmessage, stringlist); - } //end for - } //end for - for (s = stringlist; s; s = nexts) - { + } // end for + } // end for + for (s = stringlist; s; s = nexts) { nexts = s->next; FreeMemory(s); - } //end for -} //end of the function BotCheckReplyChatIntegrety + } // end for +} // end of the function BotCheckReplyChatIntegrety //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpReplyChat(bot_replychat_t *replychat) -{ +void BotDumpReplyChat(bot_replychat_t *replychat) { FILE *fp; bot_replychat_t *rp; bot_replychatkey_t *key; @@ -1668,84 +1539,87 @@ void BotDumpReplyChat(bot_replychat_t *replychat) bot_matchpiece_t *mp; fp = Log_FilePointer(); - if (!fp) return; + if (!fp) + return; fprintf(fp, "BotDumpReplyChat:\n"); - for (rp = replychat; rp; rp = rp->next) - { + for (rp = replychat; rp; rp = rp->next) { fprintf(fp, "["); - for (key = rp->keys; key; key = key->next) - { - if (key->flags & RCKFL_AND) fprintf(fp, "&"); - else if (key->flags & RCKFL_NOT) fprintf(fp, "!"); + for (key = rp->keys; key; key = key->next) { + if (key->flags & RCKFL_AND) + fprintf(fp, "&"); + else if (key->flags & RCKFL_NOT) + fprintf(fp, "!"); // - if (key->flags & RCKFL_NAME) fprintf(fp, "name"); - else if (key->flags & RCKFL_GENDERFEMALE) fprintf(fp, "female"); - else if (key->flags & RCKFL_GENDERMALE) fprintf(fp, "male"); - else if (key->flags & RCKFL_GENDERLESS) fprintf(fp, "it"); - else if (key->flags & RCKFL_VARIABLES) - { + if (key->flags & RCKFL_NAME) + fprintf(fp, "name"); + else if (key->flags & RCKFL_GENDERFEMALE) + fprintf(fp, "female"); + else if (key->flags & RCKFL_GENDERMALE) + fprintf(fp, "male"); + else if (key->flags & RCKFL_GENDERLESS) + fprintf(fp, "it"); + else if (key->flags & RCKFL_VARIABLES) { fprintf(fp, "("); - for (mp = key->match; mp; mp = mp->next) - { - if (mp->type == MT_STRING) fprintf(fp, "\"%s\"", mp->firststring->string); - else fprintf(fp, "%d", mp->variable); - if (mp->next) fprintf(fp, ", "); - } //end for + for (mp = key->match; mp; mp = mp->next) { + if (mp->type == MT_STRING) + fprintf(fp, "\"%s\"", mp->firststring->string); + else + fprintf(fp, "%d", mp->variable); + if (mp->next) + fprintf(fp, ", "); + } // end for fprintf(fp, ")"); - } //end if - else if (key->flags & RCKFL_STRING) - { + } // end if + else if (key->flags & RCKFL_STRING) { fprintf(fp, "\"%s\"", key->string); - } //end if - if (key->next) fprintf(fp, ", "); - else fprintf(fp, "] = %1.0f\n", rp->priority); - } //end for + } // end if + if (key->next) + fprintf(fp, ", "); + else + fprintf(fp, "] = %1.0f\n", rp->priority); + } // end for fprintf(fp, "{\n"); - for (cm = rp->firstchatmessage; cm; cm = cm->next) - { + for (cm = rp->firstchatmessage; cm; cm = cm->next) { fprintf(fp, "\t\"%s\";\n", cm->chatmessage); - } //end for + } // end for fprintf(fp, "}\n"); - } //end for -} //end of the function BotDumpReplyChat + } // end for +} // end of the function BotDumpReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeReplyChat(bot_replychat_t *replychat) -{ +void BotFreeReplyChat(bot_replychat_t *replychat) { bot_replychat_t *rp, *nextrp; bot_replychatkey_t *key, *nextkey; bot_chatmessage_t *cm, *nextcm; - for (rp = replychat; rp; rp = nextrp) - { + for (rp = replychat; rp; rp = nextrp) { nextrp = rp->next; - for (key = rp->keys; key; key = nextkey) - { + for (key = rp->keys; key; key = nextkey) { nextkey = key->next; - if (key->match) BotFreeMatchPieces(key->match); - if (key->string) FreeMemory(key->string); + if (key->match) + BotFreeMatchPieces(key->match); + if (key->string) + FreeMemory(key->string); FreeMemory(key); - } //end for - for (cm = rp->firstchatmessage; cm; cm = nextcm) - { + } // end for + for (cm = rp->firstchatmessage; cm; cm = nextcm) { nextcm = cm->next; FreeMemory(cm); - } //end for + } // end for FreeMemory(rp); - } //end for -} //end of the function BotFreeReplyChat + } // end for +} // end of the function BotFreeReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotCheckValidReplyChatKeySet(source_t *source, bot_replychatkey_t *keys) -{ +void BotCheckValidReplyChatKeySet(source_t *source, bot_replychatkey_t *keys) { int allprefixed, hasvariableskey, hasstringkey; bot_matchpiece_t *m; bot_matchstring_t *ms; @@ -1754,105 +1628,91 @@ void BotCheckValidReplyChatKeySet(source_t *source, bot_replychatkey_t *keys) // allprefixed = qtrue; hasvariableskey = hasstringkey = qfalse; - for (key = keys; key; key = key->next) - { - if (!(key->flags & (RCKFL_AND|RCKFL_NOT))) - { + for (key = keys; key; key = key->next) { + if (!(key->flags & (RCKFL_AND | RCKFL_NOT))) { allprefixed = qfalse; - if (key->flags & RCKFL_VARIABLES) - { - for (m = key->match; m; m = m->next) - { - if (m->type == MT_VARIABLE) hasvariableskey = qtrue; - } //end for - } //end if - else if (key->flags & RCKFL_STRING) - { + if (key->flags & RCKFL_VARIABLES) { + for (m = key->match; m; m = m->next) { + if (m->type == MT_VARIABLE) + hasvariableskey = qtrue; + } // end for + } // end if + else if (key->flags & RCKFL_STRING) { hasstringkey = qtrue; - } //end else if - } //end if - else if ((key->flags & RCKFL_AND) && (key->flags & RCKFL_STRING)) - { - for (key2 = keys; key2; key2 = key2->next) - { - if (key2 == key) continue; - if (key2->flags & RCKFL_NOT) continue; - if (key2->flags & RCKFL_VARIABLES) - { - for (m = key2->match; m; m = m->next) - { - if (m->type == MT_STRING) - { - for (ms = m->firststring; ms; ms = ms->next) - { - if (StringContains(ms->string, key->string, qfalse) != -1) - { + } // end else if + } // end if + else if ((key->flags & RCKFL_AND) && (key->flags & RCKFL_STRING)) { + for (key2 = keys; key2; key2 = key2->next) { + if (key2 == key) + continue; + if (key2->flags & RCKFL_NOT) + continue; + if (key2->flags & RCKFL_VARIABLES) { + for (m = key2->match; m; m = m->next) { + if (m->type == MT_STRING) { + for (ms = m->firststring; ms; ms = ms->next) { + if (StringContains(ms->string, key->string, qfalse) != -1) { break; - } //end if - } //end for - if (ms) break; - } //end if - else if (m->type == MT_VARIABLE) - { + } // end if + } // end for + if (ms) + break; + } // end if + else if (m->type == MT_VARIABLE) { break; - } //end if - } //end for - if (!m) - { - SourceWarning(source, "one of the match templates does not " - "leave space for the key %s with the & prefix", key->string); - } //end if - } //end if - } //end for - } //end else - if ((key->flags & RCKFL_NOT) && (key->flags & RCKFL_STRING)) - { - for (key2 = keys; key2; key2 = key2->next) - { - if (key2 == key) continue; - if (key2->flags & RCKFL_NOT) continue; - if (key2->flags & RCKFL_STRING) - { - if (StringContains(key2->string, key->string, qfalse) != -1) - { + } // end if + } // end for + if (!m) { + SourceWarning(source, + "one of the match templates does not " + "leave space for the key %s with the & prefix", + key->string); + } // end if + } // end if + } // end for + } // end else + if ((key->flags & RCKFL_NOT) && (key->flags & RCKFL_STRING)) { + for (key2 = keys; key2; key2 = key2->next) { + if (key2 == key) + continue; + if (key2->flags & RCKFL_NOT) + continue; + if (key2->flags & RCKFL_STRING) { + if (StringContains(key2->string, key->string, qfalse) != -1) { SourceWarning(source, "the key %s with prefix ! is inside the key %s", key->string, key2->string); - } //end if - } //end if - else if (key2->flags & RCKFL_VARIABLES) - { - for (m = key2->match; m; m = m->next) - { - if (m->type == MT_STRING) - { - for (ms = m->firststring; ms; ms = ms->next) - { - if (StringContains(ms->string, key->string, qfalse) != -1) - { - SourceWarning(source, "the key %s with prefix ! is inside " - "the match template string %s", key->string, ms->string); - } //end if - } //end for - } //end if - } //end for - } //end else if - } //end for - } //end if - } //end for - if (allprefixed) SourceWarning(source, "all keys have a & or ! prefix"); - if (hasvariableskey && hasstringkey) - { + } // end if + } // end if + else if (key2->flags & RCKFL_VARIABLES) { + for (m = key2->match; m; m = m->next) { + if (m->type == MT_STRING) { + for (ms = m->firststring; ms; ms = ms->next) { + if (StringContains(ms->string, key->string, qfalse) != -1) { + SourceWarning(source, + "the key %s with prefix ! is inside " + "the match template string %s", + key->string, ms->string); + } // end if + } // end for + } // end if + } // end for + } // end else if + } // end for + } // end if + } // end for + if (allprefixed) + SourceWarning(source, "all keys have a & or ! prefix"); + if (hasvariableskey && hasstringkey) { SourceWarning(source, "variables from the match template(s) could be " - "invalid when outputting one of the chat messages"); - } //end if -} //end of the function BotCheckValidReplyChatKeySet + "invalid when outputting one of the chat messages"); + } // end if +} // end of the function BotCheckValidReplyChatKeySet //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_replychat_t *BotLoadReplyChat(char *filename) -{ +bot_replychat_t *BotLoadReplyChat(char *filename) { char chatmessagestring[MAX_MESSAGE_SIZE]; char namebuffer[MAX_MESSAGE_SIZE]; source_t *source; @@ -1863,181 +1723,170 @@ bot_replychat_t *BotLoadReplyChat(char *filename) PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(filename); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", filename); return NULL; - } //end if + } // end if // replychatlist = NULL; // - while(PC_ReadToken(source, &token)) - { - if (strcmp(token.string, "[")) - { + while (PC_ReadToken(source, &token)) { + if (strcmp(token.string, "[")) { SourceError(source, "expected [, found %s", token.string); BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if + } // end if // replychat = (struct bot_replychat_s *)GetClearedHunkMemory(sizeof(bot_replychat_t)); replychat->keys = NULL; replychat->next = replychatlist; replychatlist = replychat; - //read the keys, there must be at least one key - do - { - //allocate a key - key = (bot_replychatkey_t *) GetClearedHunkMemory(sizeof(bot_replychatkey_t)); + // read the keys, there must be at least one key + do { + // allocate a key + key = (bot_replychatkey_t *)GetClearedHunkMemory(sizeof(bot_replychatkey_t)); key->flags = 0; key->string = NULL; key->match = NULL; key->next = replychat->keys; replychat->keys = key; - //check for MUST BE PRESENT and MUST BE ABSENT keys - if (PC_CheckTokenString(source, "&")) key->flags |= RCKFL_AND; - else if (PC_CheckTokenString(source, "!")) key->flags |= RCKFL_NOT; - //special keys - if (PC_CheckTokenString(source, "name")) key->flags |= RCKFL_NAME; - else if (PC_CheckTokenString(source, "female")) key->flags |= RCKFL_GENDERFEMALE; - else if (PC_CheckTokenString(source, "male")) key->flags |= RCKFL_GENDERMALE; - else if (PC_CheckTokenString(source, "it")) key->flags |= RCKFL_GENDERLESS; - else if (PC_CheckTokenString(source, "(")) //match key + // check for MUST BE PRESENT and MUST BE ABSENT keys + if (PC_CheckTokenString(source, "&")) + key->flags |= RCKFL_AND; + else if (PC_CheckTokenString(source, "!")) + key->flags |= RCKFL_NOT; + // special keys + if (PC_CheckTokenString(source, "name")) + key->flags |= RCKFL_NAME; + else if (PC_CheckTokenString(source, "female")) + key->flags |= RCKFL_GENDERFEMALE; + else if (PC_CheckTokenString(source, "male")) + key->flags |= RCKFL_GENDERMALE; + else if (PC_CheckTokenString(source, "it")) + key->flags |= RCKFL_GENDERLESS; + else if (PC_CheckTokenString(source, "(")) // match key { key->flags |= RCKFL_VARIABLES; key->match = BotLoadMatchPieces(source, ")"); - if (!key->match) - { + if (!key->match) { BotFreeReplyChat(replychatlist); return NULL; - } //end if - } //end else if - else if (PC_CheckTokenString(source, "<")) //bot names + } // end if + } // end else if + else if (PC_CheckTokenString(source, "<")) // bot names { key->flags |= RCKFL_BOTNAMES; strcpy(namebuffer, ""); - do - { - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + do { + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - if (strlen(namebuffer)) strcat(namebuffer, "\\"); + if (strlen(namebuffer)) + strcat(namebuffer, "\\"); strcat(namebuffer, token.string); - } while(PC_CheckTokenString(source, ",")); - if (!PC_ExpectTokenString(source, ">")) - { + } while (PC_CheckTokenString(source, ",")); + if (!PC_ExpectTokenString(source, ">")) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if - key->string = (char *) GetClearedHunkMemory(strlen(namebuffer) + 1); + } // end if + key->string = (char *)GetClearedHunkMemory(strlen(namebuffer) + 1); strcpy(key->string, namebuffer); - } //end else if - else //normal string key + } // end else if + else // normal string key { key->flags |= RCKFL_STRING; - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - key->string = (char *) GetClearedHunkMemory(strlen(token.string) + 1); + key->string = (char *)GetClearedHunkMemory(strlen(token.string) + 1); strcpy(key->string, token.string); - } //end else + } // end else // PC_CheckTokenString(source, ","); - } while(!PC_CheckTokenString(source, "]")); + } while (!PC_CheckTokenString(source, "]")); // BotCheckValidReplyChatKeySet(source, replychat->keys); - //read the = sign and the priority - if (!PC_ExpectTokenString(source, "=") || - !PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) - { + // read the = sign and the priority + if (!PC_ExpectTokenString(source, "=") || !PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if + } // end if replychat->priority = token.floatvalue; - //read the leading { - if (!PC_ExpectTokenString(source, "{")) - { + // read the leading { + if (!PC_ExpectTokenString(source, "{")) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if + } // end if replychat->numchatmessages = 0; - //while the trailing } is not found - while(!PC_CheckTokenString(source, "}")) - { - if (!BotLoadChatMessage(source, chatmessagestring)) - { + // while the trailing } is not found + while (!PC_CheckTokenString(source, "}")) { + if (!BotLoadChatMessage(source, chatmessagestring)) { BotFreeReplyChat(replychatlist); FreeSource(source); return NULL; - } //end if - chatmessage = (bot_chatmessage_t *) GetClearedHunkMemory(sizeof(bot_chatmessage_t) + strlen(chatmessagestring) + 1); - chatmessage->chatmessage = (char *) chatmessage + sizeof(bot_chatmessage_t); + } // end if + chatmessage = (bot_chatmessage_t *)GetClearedHunkMemory(sizeof(bot_chatmessage_t) + strlen(chatmessagestring) + 1); + chatmessage->chatmessage = (char *)chatmessage + sizeof(bot_chatmessage_t); strcpy(chatmessage->chatmessage, chatmessagestring); - chatmessage->time = -2*CHATMESSAGE_RECENTTIME; + chatmessage->time = -2 * CHATMESSAGE_RECENTTIME; chatmessage->next = replychat->firstchatmessage; - //add the chat message to the reply chat + // add the chat message to the reply chat replychat->firstchatmessage = chatmessage; replychat->numchatmessages++; - } //end while - } //end while + } // end while + } // end while FreeSource(source); botimport.Print(PRT_MESSAGE, "loaded %s\n", filename); // - //BotDumpReplyChat(replychatlist); - if (botDeveloper) - { + // BotDumpReplyChat(replychatlist); + if (botDeveloper) { BotCheckReplyChatIntegrety(replychatlist); - } //end if + } // end if // - if (!replychatlist) botimport.Print(PRT_MESSAGE, "no rchats\n"); + if (!replychatlist) + botimport.Print(PRT_MESSAGE, "no rchats\n"); // return replychatlist; -} //end of the function BotLoadReplyChat +} // end of the function BotLoadReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpInitialChat(bot_chat_t *chat) -{ +void BotDumpInitialChat(bot_chat_t *chat) { bot_chattype_t *t; bot_chatmessage_t *m; Log_Write("{"); - for (t = chat->types; t; t = t->next) - { + for (t = chat->types; t; t = t->next) { Log_Write(" type \"%s\"", t->name); Log_Write(" {"); Log_Write(" numchatmessages = %d", t->numchatmessages); - for (m = t->firstchatmessage; m; m = m->next) - { + for (m = t->firstchatmessage; m; m = m->next) { Log_Write(" \"%s\"", m->chatmessage); - } //end for + } // end for Log_Write(" }"); - } //end for + } // end for Log_Write("}"); -} //end of the function BotDumpInitialChat +} // end of the function BotDumpInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_chat_t *BotLoadInitialChat(char *chatfile, char *chatname) -{ +bot_chat_t *BotLoadInitialChat(char *chatfile, char *chatname) { int pass, foundchat, indent, size; char *ptr = NULL; char chatmessagestring[MAX_MESSAGE_SIZE]; @@ -2050,243 +1899,221 @@ bot_chat_t *BotLoadInitialChat(char *chatfile, char *chatname) int starttime; starttime = Sys_MilliSeconds(); -#endif //DEBUG +#endif // DEBUG // size = 0; foundchat = qfalse; - //a bot chat is parsed in two phases - for (pass = 0; pass < 2; pass++) - { - //allocate memory - if (pass && size) ptr = (char *) GetClearedMemory(size); - //load the source file + // a bot chat is parsed in two phases + for (pass = 0; pass < 2; pass++) { + // allocate memory + if (pass && size) + ptr = (char *)GetClearedMemory(size); + // load the source file PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(chatfile); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", chatfile); return NULL; - } //end if - //chat structure - if (pass) - { - chat = (bot_chat_t *) ptr; + } // end if + // chat structure + if (pass) { + chat = (bot_chat_t *)ptr; ptr += sizeof(bot_chat_t); - } //end if + } // end if size = sizeof(bot_chat_t); // - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "chat")) - { - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "chat")) { + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - //after the chat name we expect an opening brace - if (!PC_ExpectTokenString(source, "{")) - { + // after the chat name we expect an opening brace + if (!PC_ExpectTokenString(source, "{")) { FreeSource(source); return NULL; - } //end if - //if the chat name is found - if (!Q_stricmp(token.string, chatname)) - { + } // end if + // if the chat name is found + if (!Q_stricmp(token.string, chatname)) { foundchat = qtrue; - //read the chat types - while(1) - { - if (!PC_ExpectAnyToken(source, &token)) - { + // read the chat types + while (1) { + if (!PC_ExpectAnyToken(source, &token)) { FreeSource(source); return NULL; - } //end if - if (!strcmp(token.string, "}")) break; - if (strcmp(token.string, "type")) - { + } // end if + if (!strcmp(token.string, "}")) + break; + if (strcmp(token.string, "type")) { SourceError(source, "expected type found %s", token.string); FreeSource(source); return NULL; - } //end if - //expect the chat type name - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token) || - !PC_ExpectTokenString(source, "{")) - { + } // end if + // expect the chat type name + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token) || !PC_ExpectTokenString(source, "{")) { FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - if (pass) - { - chattype = (bot_chattype_t *) ptr; + if (pass) { + chattype = (bot_chattype_t *)ptr; strncpy(chattype->name, token.string, MAX_CHATTYPE_NAME); chattype->firstchatmessage = NULL; - //add the chat type to the chat + // add the chat type to the chat chattype->next = chat->types; chat->types = chattype; // ptr += sizeof(bot_chattype_t); - } //end if + } // end if size += sizeof(bot_chattype_t); - //read the chat messages - while(!PC_CheckTokenString(source, "}")) - { + // read the chat messages + while (!PC_CheckTokenString(source, "}")) { size_t len; - if (!BotLoadChatMessage(source, chatmessagestring)) - { + if (!BotLoadChatMessage(source, chatmessagestring)) { FreeSource(source); return NULL; - } //end if + } // end if len = strlen(chatmessagestring) + 1; len = PAD(len, sizeof(long)); - if (pass) - { - chatmessage = (bot_chatmessage_t *) ptr; - chatmessage->time = -2*CHATMESSAGE_RECENTTIME; - //put the chat message in the list + if (pass) { + chatmessage = (bot_chatmessage_t *)ptr; + chatmessage->time = -2 * CHATMESSAGE_RECENTTIME; + // put the chat message in the list chatmessage->next = chattype->firstchatmessage; chattype->firstchatmessage = chatmessage; - //store the chat message + // store the chat message ptr += sizeof(bot_chatmessage_t); chatmessage->chatmessage = ptr; strcpy(chatmessage->chatmessage, chatmessagestring); ptr += len; - //the number of chat messages increased + // the number of chat messages increased chattype->numchatmessages++; - } //end if + } // end if size += sizeof(bot_chatmessage_t) + len; - } //end if - } //end while - } //end if - else //skip the bot chat + } // end if + } // end while + } // end if + else // skip the bot chat { indent = 1; - while(indent) - { - if (!PC_ExpectAnyToken(source, &token)) - { + while (indent) { + if (!PC_ExpectAnyToken(source, &token)) { FreeSource(source); return NULL; - } //end if - if (!strcmp(token.string, "{")) indent++; - else if (!strcmp(token.string, "}")) indent--; - } //end while - } //end else - } //end if - else - { + } // end if + if (!strcmp(token.string, "{")) + indent++; + else if (!strcmp(token.string, "}")) + indent--; + } // end while + } // end else + } // end if + else { SourceError(source, "unknown definition %s", token.string); FreeSource(source); return NULL; - } //end else - } //end while - //free the source + } // end else + } // end while + // free the source FreeSource(source); - //if the requested character is not found - if (!foundchat) - { + // if the requested character is not found + if (!foundchat) { botimport.Print(PRT_ERROR, "couldn't find chat %s in %s\n", chatname, chatfile); return NULL; - } //end if - } //end for + } // end if + } // end for // botimport.Print(PRT_MESSAGE, "loaded %s from %s\n", chatname, chatfile); // - //BotDumpInitialChat(chat); - if (botDeveloper) - { + // BotDumpInitialChat(chat); + if (botDeveloper) { BotCheckInitialChatIntegrety(chat); - } //end if + } // end if #ifdef DEBUG botimport.Print(PRT_MESSAGE, "initial chats loaded in %d msec\n", Sys_MilliSeconds() - starttime); -#endif //DEBUG - //character was read successfully +#endif // DEBUG + // character was read successfully return chat; -} //end of the function BotLoadInitialChat +} // end of the function BotLoadInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeChatFile(int chatstate) -{ +void BotFreeChatFile(int chatstate) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; - if (cs->chat) FreeMemory(cs->chat); + if (!cs) + return; + if (cs->chat) + FreeMemory(cs->chat); cs->chat = NULL; -} //end of the function BotFreeChatFile +} // end of the function BotFreeChatFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadChatFile(int chatstate, char *chatfile, char *chatname) -{ +int BotLoadChatFile(int chatstate, char *chatfile, char *chatname) { bot_chatstate_t *cs; int n, avail = 0; cs = BotChatStateFromHandle(chatstate); - if (!cs) return BLERR_CANNOTLOADICHAT; + if (!cs) + return BLERR_CANNOTLOADICHAT; BotFreeChatFile(chatstate); - if (!LibVarGetValue("bot_reloadcharacters")) - { + if (!LibVarGetValue("bot_reloadcharacters")) { avail = -1; - for( n = 0; n < MAX_CLIENTS; n++ ) { - if( !ichatdata[n] ) { - if( avail == -1 ) { + for (n = 0; n < MAX_CLIENTS; n++) { + if (!ichatdata[n]) { + if (avail == -1) { avail = n; } continue; } - if( strcmp( chatfile, ichatdata[n]->filename ) != 0 ) { + if (strcmp(chatfile, ichatdata[n]->filename) != 0) { continue; } - if( strcmp( chatname, ichatdata[n]->chatname ) != 0 ) { + if (strcmp(chatname, ichatdata[n]->chatname) != 0) { continue; } cs->chat = ichatdata[n]->chat; - // botimport.Print( PRT_MESSAGE, "retained %s from %s\n", chatname, chatfile ); + // botimport.Print( PRT_MESSAGE, "retained %s from %s\n", chatname, chatfile ); return BLERR_NOERROR; } - if( avail == -1 ) { + if (avail == -1) { botimport.Print(PRT_FATAL, "ichatdata table full; couldn't load chat %s from %s\n", chatname, chatfile); return BLERR_CANNOTLOADICHAT; } } cs->chat = BotLoadInitialChat(chatfile, chatname); - if (!cs->chat) - { + if (!cs->chat) { botimport.Print(PRT_FATAL, "couldn't load chat %s from %s\n", chatname, chatfile); return BLERR_CANNOTLOADICHAT; - } //end if - if (!LibVarGetValue("bot_reloadcharacters")) - { - ichatdata[avail] = (bot_ichatdata_t *)GetClearedMemory( sizeof(bot_ichatdata_t) ); + } // end if + if (!LibVarGetValue("bot_reloadcharacters")) { + ichatdata[avail] = (bot_ichatdata_t *)GetClearedMemory(sizeof(bot_ichatdata_t)); ichatdata[avail]->chat = cs->chat; - Q_strncpyz( ichatdata[avail]->chatname, chatname, sizeof(ichatdata[avail]->chatname) ); - Q_strncpyz( ichatdata[avail]->filename, chatfile, sizeof(ichatdata[avail]->filename) ); - } //end if + Q_strncpyz(ichatdata[avail]->chatname, chatname, sizeof(ichatdata[avail]->chatname)); + Q_strncpyz(ichatdata[avail]->filename, chatfile, sizeof(ichatdata[avail]->filename)); + } // end if return BLERR_NOERROR; -} //end of the function BotLoadChatFile +} // end of the function BotLoadChatFile //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotExpandChatMessage(char *outmessage, char *message, unsigned long mcontext, - bot_match_t *match, unsigned long vcontext, int reply) -{ +int BotExpandChatMessage(char *outmessage, char *message, unsigned long mcontext, bot_match_t *match, unsigned long vcontext, int reply) { int num, len, i, expansion; char *outputbuf, *ptr, *msgptr; char temp[MAX_MESSAGE_SIZE]; @@ -2296,136 +2123,117 @@ int BotExpandChatMessage(char *outmessage, char *message, unsigned long mcontext outputbuf = outmessage; len = 0; // - while(*msgptr) - { - if (*msgptr == ESCAPE_CHAR) - { + while (*msgptr) { + if (*msgptr == ESCAPE_CHAR) { msgptr++; - switch(*msgptr) + switch (*msgptr) { + case 'v': // variable { - case 'v': //variable - { + msgptr++; + num = 0; + while (*msgptr && *msgptr != ESCAPE_CHAR) { + num = num * 10 + (*msgptr++) - '0'; + } // end while + // step over the trailing escape char + if (*msgptr) msgptr++; - num = 0; - while(*msgptr && *msgptr != ESCAPE_CHAR) - { - num = num * 10 + (*msgptr++) - '0'; - } //end while - //step over the trailing escape char - if (*msgptr) msgptr++; - if (num > MAX_MATCHVARIABLES) - { - botimport.Print(PRT_ERROR, "BotConstructChat: message %s variable %d out of range\n", message, num); + if (num > MAX_MATCHVARIABLES) { + botimport.Print(PRT_ERROR, "BotConstructChat: message %s variable %d out of range\n", message, num); + return qfalse; + } // end if + if (match->variables[num].offset >= 0) { + assert(match->variables[num].offset >= 0); // bk001204 + ptr = &match->string[(int)match->variables[num].offset]; + for (i = 0; i < match->variables[num].length; i++) { + temp[i] = ptr[i]; + } // end for + temp[i] = 0; + // if it's a reply message + if (reply) { + // replace the reply synonyms in the variables + BotReplaceReplySynonyms(temp, vcontext); + } // end if + else { + // replace synonyms in the variable context + BotReplaceSynonyms(temp, vcontext); + } // end else + // + if (len + strlen(temp) >= MAX_MESSAGE_SIZE) { + botimport.Print(PRT_ERROR, "BotConstructChat: message %s too long\n", message); return qfalse; - } //end if - if (match->variables[num].offset >= 0) - { - assert( match->variables[num].offset >= 0 ); // bk001204 - ptr = &match->string[ (int) match->variables[num].offset]; - for (i = 0; i < match->variables[num].length; i++) - { - temp[i] = ptr[i]; - } //end for - temp[i] = 0; - //if it's a reply message - if (reply) - { - //replace the reply synonyms in the variables - BotReplaceReplySynonyms(temp, vcontext); - } //end if - else - { - //replace synonyms in the variable context - BotReplaceSynonyms(temp, vcontext); - } //end else - // - if (len + strlen(temp) >= MAX_MESSAGE_SIZE) - { - botimport.Print(PRT_ERROR, "BotConstructChat: message %s too long\n", message); - return qfalse; - } //end if - strcpy(&outputbuf[len], temp); - len += strlen(temp); - } //end if - break; - } //end case - case 'r': //random - { + } // end if + strcpy(&outputbuf[len], temp); + len += strlen(temp); + } // end if + break; + } // end case + case 'r': // random + { + msgptr++; + for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++) { + temp[i] = *msgptr++; + } // end while + temp[i] = '\0'; + // step over the trailing escape char + if (*msgptr) msgptr++; - for (i = 0; (*msgptr && *msgptr != ESCAPE_CHAR); i++) - { - temp[i] = *msgptr++; - } //end while - temp[i] = '\0'; - //step over the trailing escape char - if (*msgptr) msgptr++; - //find the random keyword - ptr = RandomString(temp); - if (!ptr) - { - botimport.Print(PRT_ERROR, "BotConstructChat: unknown random string %s\n", temp); - return qfalse; - } //end if - if (len + strlen(ptr) >= MAX_MESSAGE_SIZE) - { - botimport.Print(PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message); - return qfalse; - } //end if - strcpy(&outputbuf[len], ptr); - len += strlen(ptr); - expansion = qtrue; - break; - } //end case - default: - { - botimport.Print(PRT_FATAL, "BotConstructChat: message \"%s\" invalid escape char\n", message); - break; - } //end default - } //end switch - } //end if - else - { + // find the random keyword + ptr = RandomString(temp); + if (!ptr) { + botimport.Print(PRT_ERROR, "BotConstructChat: unknown random string %s\n", temp); + return qfalse; + } // end if + if (len + strlen(ptr) >= MAX_MESSAGE_SIZE) { + botimport.Print(PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message); + return qfalse; + } // end if + strcpy(&outputbuf[len], ptr); + len += strlen(ptr); + expansion = qtrue; + break; + } // end case + default: { + botimport.Print(PRT_FATAL, "BotConstructChat: message \"%s\" invalid escape char\n", message); + break; + } // end default + } // end switch + } // end if + else { outputbuf[len++] = *msgptr++; - if (len >= MAX_MESSAGE_SIZE) - { + if (len >= MAX_MESSAGE_SIZE) { botimport.Print(PRT_ERROR, "BotConstructChat: message \"%s\" too long\n", message); break; - } //end if - } //end else - } //end while + } // end if + } // end else + } // end while outputbuf[len] = '\0'; - //replace synonyms weighted in the message context + // replace synonyms weighted in the message context BotReplaceWeightedSynonyms(outputbuf, mcontext); - //return true if a random was expanded + // return true if a random was expanded return expansion; -} //end of the function BotExpandChatMessage +} // end of the function BotExpandChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotConstructChatMessage(bot_chatstate_t *chatstate, char *message, unsigned long mcontext, - bot_match_t *match, unsigned long vcontext, int reply) -{ +void BotConstructChatMessage(bot_chatstate_t *chatstate, char *message, unsigned long mcontext, bot_match_t *match, unsigned long vcontext, int reply) { int i; char srcmessage[MAX_MESSAGE_SIZE]; strcpy(srcmessage, message); - for (i = 0; i < 10; i++) - { - if (!BotExpandChatMessage(chatstate->chatmessage, srcmessage, mcontext, match, vcontext, reply)) - { + for (i = 0; i < 10; i++) { + if (!BotExpandChatMessage(chatstate->chatmessage, srcmessage, mcontext, match, vcontext, reply)) { break; - } //end if + } // end if strcpy(srcmessage, chatstate->chatmessage); - } //end for - if (i >= 10) - { + } // end for + if (i >= 10) { botimport.Print(PRT_WARNING, "too many expansions in chat message\n"); botimport.Print(PRT_WARNING, "%s\n", chatstate->chatmessage); - } //end if -} //end of the function BotConstructChatMessage + } // end if +} // end of the function BotConstructChatMessage //=========================================================================== // randomly chooses one of the chat message of the given type // @@ -2433,8 +2241,7 @@ void BotConstructChatMessage(bot_chatstate_t *chatstate, char *message, unsigned // Returns: - // Changes Globals: - //=========================================================================== -char *BotChooseInitialChatMessage(bot_chatstate_t *cs, char *type) -{ +char *BotChooseInitialChatMessage(bot_chatstate_t *cs, char *type) { int n, numchatmessages; float besttime; bot_chattype_t *t; @@ -2442,206 +2249,205 @@ char *BotChooseInitialChatMessage(bot_chatstate_t *cs, char *type) bot_chat_t *chat; chat = cs->chat; - for (t = chat->types; t; t = t->next) - { - if (!Q_stricmp(t->name, type)) - { + for (t = chat->types; t; t = t->next) { + if (!Q_stricmp(t->name, type)) { numchatmessages = 0; - for (m = t->firstchatmessage; m; m = m->next) - { - if (m->time > AAS_Time()) continue; + for (m = t->firstchatmessage; m; m = m->next) { + if (m->time > AAS_Time()) + continue; numchatmessages++; - } //end if - //if all chat messages have been used recently - if (numchatmessages <= 0) - { + } // end if + // if all chat messages have been used recently + if (numchatmessages <= 0) { besttime = 0; bestchatmessage = NULL; - for (m = t->firstchatmessage; m; m = m->next) - { - if (!besttime || m->time < besttime) - { + for (m = t->firstchatmessage; m; m = m->next) { + if (!besttime || m->time < besttime) { bestchatmessage = m; besttime = m->time; - } //end if - } //end for - if (bestchatmessage) return bestchatmessage->chatmessage; - } //end if - else //choose a chat message randomly + } // end if + } // end for + if (bestchatmessage) + return bestchatmessage->chatmessage; + } // end if + else // choose a chat message randomly { n = Q_flrand(0.0f, 1.0f) * numchatmessages; - for (m = t->firstchatmessage; m; m = m->next) - { - if (m->time > AAS_Time()) continue; - if (--n < 0) - { + for (m = t->firstchatmessage; m; m = m->next) { + if (m->time > AAS_Time()) + continue; + if (--n < 0) { m->time = AAS_Time() + CHATMESSAGE_RECENTTIME; return m->chatmessage; - } //end if - } //end for - } //end else + } // end if + } // end for + } // end else return NULL; - } //end if - } //end for + } // end if + } // end for return NULL; -} //end of the function BotChooseInitialChatMessage +} // end of the function BotChooseInitialChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotNumInitialChats(int chatstate, char *type) -{ +int BotNumInitialChats(int chatstate, char *type) { bot_chatstate_t *cs; bot_chattype_t *t; cs = BotChatStateFromHandle(chatstate); - if (!cs) return 0; + if (!cs) + return 0; - for (t = cs->chat->types; t; t = t->next) - { - if (!Q_stricmp(t->name, type)) - { + for (t = cs->chat->types; t; t = t->next) { + if (!Q_stricmp(t->name, type)) { if (LibVarGetValue("bot_testichat")) { botimport.Print(PRT_MESSAGE, "%s has %d chat lines\n", type, t->numchatmessages); botimport.Print(PRT_MESSAGE, "-------------------\n"); } return t->numchatmessages; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotNumInitialChats +} // end of the function BotNumInitialChats //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7) -{ +void BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7) { char *message; int index; bot_match_t match; bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; - //if no chat file is loaded - if (!cs->chat) return; - //choose a chat message randomly of the given type + if (!cs) + return; + // if no chat file is loaded + if (!cs->chat) + return; + // choose a chat message randomly of the given type message = BotChooseInitialChatMessage(cs, type); - //if there's no message of the given type - if (!message) - { + // if there's no message of the given type + if (!message) { #ifdef DEBUG botimport.Print(PRT_MESSAGE, "no chat messages of type %s\n", type); -#endif //DEBUG +#endif // DEBUG return; - } //end if + } // end if // Com_Memset(&match, 0, sizeof(match)); index = 0; - if( var0 ) { + if (var0) { strcat(match.string, var0); match.variables[0].offset = index; match.variables[0].length = strlen(var0); index += strlen(var0); } - if( var1 ) { + if (var1) { strcat(match.string, var1); match.variables[1].offset = index; match.variables[1].length = strlen(var1); index += strlen(var1); } - if( var2 ) { + if (var2) { strcat(match.string, var2); match.variables[2].offset = index; match.variables[2].length = strlen(var2); index += strlen(var2); } - if( var3 ) { + if (var3) { strcat(match.string, var3); match.variables[3].offset = index; match.variables[3].length = strlen(var3); index += strlen(var3); } - if( var4 ) { + if (var4) { strcat(match.string, var4); match.variables[4].offset = index; match.variables[4].length = strlen(var4); index += strlen(var4); } - if( var5 ) { + if (var5) { strcat(match.string, var5); match.variables[5].offset = index; match.variables[5].length = strlen(var5); index += strlen(var5); } - if( var6 ) { + if (var6) { strcat(match.string, var6); match.variables[6].offset = index; match.variables[6].length = strlen(var6); index += strlen(var6); } - if( var7 ) { + if (var7) { strcat(match.string, var7); match.variables[7].offset = index; match.variables[7].length = strlen(var7); index += strlen(var7); } - // + // BotConstructChatMessage(cs, message, mcontext, &match, 0, qfalse); -} //end of the function BotInitialChat +} // end of the function BotInitialChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotPrintReplyChatKeys(bot_replychat_t *replychat) -{ +void BotPrintReplyChatKeys(bot_replychat_t *replychat) { bot_replychatkey_t *key; bot_matchpiece_t *mp; botimport.Print(PRT_MESSAGE, "["); - for (key = replychat->keys; key; key = key->next) - { - if (key->flags & RCKFL_AND) botimport.Print(PRT_MESSAGE, "&"); - else if (key->flags & RCKFL_NOT) botimport.Print(PRT_MESSAGE, "!"); + for (key = replychat->keys; key; key = key->next) { + if (key->flags & RCKFL_AND) + botimport.Print(PRT_MESSAGE, "&"); + else if (key->flags & RCKFL_NOT) + botimport.Print(PRT_MESSAGE, "!"); // - if (key->flags & RCKFL_NAME) botimport.Print(PRT_MESSAGE, "name"); - else if (key->flags & RCKFL_GENDERFEMALE) botimport.Print(PRT_MESSAGE, "female"); - else if (key->flags & RCKFL_GENDERMALE) botimport.Print(PRT_MESSAGE, "male"); - else if (key->flags & RCKFL_GENDERLESS) botimport.Print(PRT_MESSAGE, "it"); - else if (key->flags & RCKFL_VARIABLES) - { + if (key->flags & RCKFL_NAME) + botimport.Print(PRT_MESSAGE, "name"); + else if (key->flags & RCKFL_GENDERFEMALE) + botimport.Print(PRT_MESSAGE, "female"); + else if (key->flags & RCKFL_GENDERMALE) + botimport.Print(PRT_MESSAGE, "male"); + else if (key->flags & RCKFL_GENDERLESS) + botimport.Print(PRT_MESSAGE, "it"); + else if (key->flags & RCKFL_VARIABLES) { botimport.Print(PRT_MESSAGE, "("); - for (mp = key->match; mp; mp = mp->next) - { - if (mp->type == MT_STRING) botimport.Print(PRT_MESSAGE, "\"%s\"", mp->firststring->string); - else botimport.Print(PRT_MESSAGE, "%d", mp->variable); - if (mp->next) botimport.Print(PRT_MESSAGE, ", "); - } //end for + for (mp = key->match; mp; mp = mp->next) { + if (mp->type == MT_STRING) + botimport.Print(PRT_MESSAGE, "\"%s\"", mp->firststring->string); + else + botimport.Print(PRT_MESSAGE, "%d", mp->variable); + if (mp->next) + botimport.Print(PRT_MESSAGE, ", "); + } // end for botimport.Print(PRT_MESSAGE, ")"); - } //end if - else if (key->flags & RCKFL_STRING) - { + } // end if + else if (key->flags & RCKFL_STRING) { botimport.Print(PRT_MESSAGE, "\"%s\"", key->string); - } //end if - if (key->next) botimport.Print(PRT_MESSAGE, ", "); - else botimport.Print(PRT_MESSAGE, "] = %1.0f\n", replychat->priority); - } //end for + } // end if + if (key->next) + botimport.Print(PRT_MESSAGE, ", "); + else + botimport.Print(PRT_MESSAGE, "] = %1.0f\n", replychat->priority); + } // end for botimport.Print(PRT_MESSAGE, "{\n"); -} //end of the function BotPrintReplyChatKeys +} // end of the function BotPrintReplyChatKeys //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7) -{ +int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, + char *var7) { bot_replychat_t *rchat, *bestrchat; bot_replychatkey_t *key; bot_chatmessage_t *m, *bestchatmessage; @@ -2650,338 +2456,324 @@ int BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return qfalse; + if (!cs) + return qfalse; Com_Memset(&match, 0, sizeof(bot_match_t)); strcpy(match.string, message); bestpriority = -1; bestchatmessage = NULL; bestrchat = NULL; - //go through all the reply chats - for (rchat = replychats; rchat; rchat = rchat->next) - { + // go through all the reply chats + for (rchat = replychats; rchat; rchat = rchat->next) { found = qfalse; - for (key = rchat->keys; key; key = key->next) - { + for (key = rchat->keys; key; key = key->next) { res = qfalse; - //get the match result - if (key->flags & RCKFL_NAME) res = (StringContains(message, cs->name, qfalse) != -1); - else if (key->flags & RCKFL_BOTNAMES) res = (StringContains(key->string, cs->name, qfalse) != -1); - else if (key->flags & RCKFL_GENDERFEMALE) res = (cs->gender == CHAT_GENDERFEMALE); - else if (key->flags & RCKFL_GENDERMALE) res = (cs->gender == CHAT_GENDERMALE); - else if (key->flags & RCKFL_GENDERLESS) res = (cs->gender == CHAT_GENDERLESS); - else if (key->flags & RCKFL_VARIABLES) res = StringsMatch(key->match, &match); - else if (key->flags & RCKFL_STRING) res = (StringContainsWord(message, key->string, qfalse) != NULL); - //if the key must be present - if (key->flags & RCKFL_AND) - { - if (!res) - { + // get the match result + if (key->flags & RCKFL_NAME) + res = (StringContains(message, cs->name, qfalse) != -1); + else if (key->flags & RCKFL_BOTNAMES) + res = (StringContains(key->string, cs->name, qfalse) != -1); + else if (key->flags & RCKFL_GENDERFEMALE) + res = (cs->gender == CHAT_GENDERFEMALE); + else if (key->flags & RCKFL_GENDERMALE) + res = (cs->gender == CHAT_GENDERMALE); + else if (key->flags & RCKFL_GENDERLESS) + res = (cs->gender == CHAT_GENDERLESS); + else if (key->flags & RCKFL_VARIABLES) + res = StringsMatch(key->match, &match); + else if (key->flags & RCKFL_STRING) + res = (StringContainsWord(message, key->string, qfalse) != NULL); + // if the key must be present + if (key->flags & RCKFL_AND) { + if (!res) { found = qfalse; break; - } //end if - } //end else if - //if the key must be absent - else if (key->flags & RCKFL_NOT) - { - if (res) - { + } // end if + } // end else if + // if the key must be absent + else if (key->flags & RCKFL_NOT) { + if (res) { found = qfalse; break; - } //end if - } //end if - else if (res) - { + } // end if + } // end if + else if (res) { found = qtrue; - } //end else - } //end for + } // end else + } // end for // - if (found) - { - if (rchat->priority > bestpriority) - { + if (found) { + if (rchat->priority > bestpriority) { numchatmessages = 0; - for (m = rchat->firstchatmessage; m; m = m->next) - { - if (m->time > AAS_Time()) continue; + for (m = rchat->firstchatmessage; m; m = m->next) { + if (m->time > AAS_Time()) + continue; numchatmessages++; - } //end if + } // end if num = Q_flrand(0.0f, 1.0f) * numchatmessages; - for (m = rchat->firstchatmessage; m; m = m->next) - { - if (--num < 0) break; - if (m->time > AAS_Time()) continue; - } //end for - //if the reply chat has a message - if (m) - { + for (m = rchat->firstchatmessage; m; m = m->next) { + if (--num < 0) + break; + if (m->time > AAS_Time()) + continue; + } // end for + // if the reply chat has a message + if (m) { Com_Memcpy(&bestmatch, &match, sizeof(bot_match_t)); bestchatmessage = m; bestrchat = rchat; bestpriority = rchat->priority; - } //end if - } //end if - } //end if - } //end for - if (bestchatmessage) - { + } // end if + } // end if + } // end if + } // end for + if (bestchatmessage) { index = strlen(bestmatch.string); - if( var0 ) { + if (var0) { strcat(bestmatch.string, var0); bestmatch.variables[0].offset = index; bestmatch.variables[0].length = strlen(var0); index += strlen(var0); } - if( var1 ) { + if (var1) { strcat(bestmatch.string, var1); bestmatch.variables[1].offset = index; bestmatch.variables[1].length = strlen(var1); index += strlen(var1); } - if( var2 ) { + if (var2) { strcat(bestmatch.string, var2); bestmatch.variables[2].offset = index; bestmatch.variables[2].length = strlen(var2); index += strlen(var2); } - if( var3 ) { + if (var3) { strcat(bestmatch.string, var3); bestmatch.variables[3].offset = index; bestmatch.variables[3].length = strlen(var3); index += strlen(var3); } - if( var4 ) { + if (var4) { strcat(bestmatch.string, var4); bestmatch.variables[4].offset = index; bestmatch.variables[4].length = strlen(var4); index += strlen(var4); } - if( var5 ) { + if (var5) { strcat(bestmatch.string, var5); bestmatch.variables[5].offset = index; bestmatch.variables[5].length = strlen(var5); index += strlen(var5); } - if( var6 ) { + if (var6) { strcat(bestmatch.string, var6); bestmatch.variables[6].offset = index; bestmatch.variables[6].length = strlen(var6); index += strlen(var6); } - if( var7 ) { + if (var7) { strcat(bestmatch.string, var7); bestmatch.variables[7].offset = index; bestmatch.variables[7].length = strlen(var7); index += strlen(var7); } - if (LibVarGetValue("bot_testrchat")) - { - for (m = bestrchat->firstchatmessage; m; m = m->next) - { + if (LibVarGetValue("bot_testrchat")) { + for (m = bestrchat->firstchatmessage; m; m = m->next) { BotConstructChatMessage(cs, m->chatmessage, mcontext, &bestmatch, vcontext, qtrue); BotRemoveTildes(cs->chatmessage); botimport.Print(PRT_MESSAGE, "%s\n", cs->chatmessage); - } //end if - } //end if - else - { + } // end if + } // end if + else { bestchatmessage->time = AAS_Time() + CHATMESSAGE_RECENTTIME; BotConstructChatMessage(cs, bestchatmessage->chatmessage, mcontext, &bestmatch, vcontext, qtrue); - } //end else + } // end else return qtrue; - } //end if + } // end if return qfalse; -} //end of the function BotReplyChat +} // end of the function BotReplyChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotChatLength(int chatstate) -{ +int BotChatLength(int chatstate) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return 0; + if (!cs) + return 0; return strlen(cs->chatmessage); -} //end of the function BotChatLength +} // end of the function BotChatLength //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotEnterChat(int chatstate, int clientto, int sendto) -{ +void BotEnterChat(int chatstate, int clientto, int sendto) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; + if (!cs) + return; - if (strlen(cs->chatmessage)) - { + if (strlen(cs->chatmessage)) { BotRemoveTildes(cs->chatmessage); if (LibVarGetValue("bot_testichat")) { botimport.Print(PRT_MESSAGE, "%s\n", cs->chatmessage); - } - else { - switch(sendto) { - case CHAT_TEAM: - EA_Command(cs->client, va("say_team %s", cs->chatmessage)); - break; - case CHAT_TELL: - EA_Command(cs->client, va("tell %d %s", clientto, cs->chatmessage)); - break; - default: //CHAT_ALL - EA_Command(cs->client, va("say %s", cs->chatmessage)); - break; + } else { + switch (sendto) { + case CHAT_TEAM: + EA_Command(cs->client, va("say_team %s", cs->chatmessage)); + break; + case CHAT_TELL: + EA_Command(cs->client, va("tell %d %s", clientto, cs->chatmessage)); + break; + default: // CHAT_ALL + EA_Command(cs->client, va("say %s", cs->chatmessage)); + break; } } - //clear the chat message from the state + // clear the chat message from the state strcpy(cs->chatmessage, ""); - } //end if -} //end of the function BotEnterChat + } // end if +} // end of the function BotEnterChat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotGetChatMessage(int chatstate, char *buf, int size) -{ +void BotGetChatMessage(int chatstate, char *buf, int size) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; + if (!cs) + return; BotRemoveTildes(cs->chatmessage); - strncpy(buf, cs->chatmessage, size-1); - buf[size-1] = '\0'; - //clear the chat message from the state + strncpy(buf, cs->chatmessage, size - 1); + buf[size - 1] = '\0'; + // clear the chat message from the state strcpy(cs->chatmessage, ""); -} //end of the function BotGetChatMessage +} // end of the function BotGetChatMessage //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotSetChatGender(int chatstate, int gender) -{ +void BotSetChatGender(int chatstate, int gender) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; - switch(gender) - { - case CHAT_GENDERFEMALE: cs->gender = CHAT_GENDERFEMALE; break; - case CHAT_GENDERMALE: cs->gender = CHAT_GENDERMALE; break; - default: cs->gender = CHAT_GENDERLESS; break; - } //end switch -} //end of the function BotSetChatGender + if (!cs) + return; + switch (gender) { + case CHAT_GENDERFEMALE: + cs->gender = CHAT_GENDERFEMALE; + break; + case CHAT_GENDERMALE: + cs->gender = CHAT_GENDERMALE; + break; + default: + cs->gender = CHAT_GENDERLESS; + break; + } // end switch +} // end of the function BotSetChatGender //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotSetChatName(int chatstate, char *name, int client) -{ +void BotSetChatName(int chatstate, char *name, int client) { bot_chatstate_t *cs; cs = BotChatStateFromHandle(chatstate); - if (!cs) return; + if (!cs) + return; cs->client = client; Com_Memset(cs->name, 0, sizeof(cs->name)); strncpy(cs->name, name, sizeof(cs->name)); - cs->name[sizeof(cs->name)-1] = '\0'; -} //end of the function BotSetChatName + cs->name[sizeof(cs->name) - 1] = '\0'; +} // end of the function BotSetChatName //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetChatAI(void) -{ +void BotResetChatAI(void) { bot_replychat_t *rchat; bot_chatmessage_t *m; - for (rchat = replychats; rchat; rchat = rchat->next) - { - for (m = rchat->firstchatmessage; m; m = m->next) - { + for (rchat = replychats; rchat; rchat = rchat->next) { + for (m = rchat->firstchatmessage; m; m = m->next) { m->time = 0; - } //end for - } //end for -} //end of the function BotResetChatAI + } // end for + } // end for +} // end of the function BotResetChatAI //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -int BotAllocChatState(void) -{ +int BotAllocChatState(void) { int i; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (!botchatstates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (!botchatstates[i]) { botchatstates[i] = (struct bot_chatstate_s *)GetClearedMemory(sizeof(bot_chatstate_t)); return i; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotAllocChatState +} // end of the function BotAllocChatState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeChatState(int handle) -{ +void BotFreeChatState(int handle) { bot_consolemessage_t m; int h; - if (handle <= 0 || handle > MAX_CLIENTS) - { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "chat state handle %d out of range\n", handle); return; - } //end if - if (!botchatstates[handle]) - { + } // end if + if (!botchatstates[handle]) { botimport.Print(PRT_FATAL, "invalid chat state %d\n", handle); return; - } //end if - if (LibVarGetValue("bot_reloadcharacters")) - { + } // end if + if (LibVarGetValue("bot_reloadcharacters")) { BotFreeChatFile(handle); - } //end if - //free all the console messages left in the chat state - for (h = BotNextConsoleMessage(handle, &m); h; h = BotNextConsoleMessage(handle, &m)) - { - //remove the console message + } // end if + // free all the console messages left in the chat state + for (h = BotNextConsoleMessage(handle, &m); h; h = BotNextConsoleMessage(handle, &m)) { + // remove the console message BotRemoveConsoleMessage(handle, h); - } //end for + } // end for FreeMemory(botchatstates[handle]); botchatstates[handle] = NULL; -} //end of the function BotFreeChatState +} // end of the function BotFreeChatState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotSetupChatAI(void) -{ +int BotSetupChatAI(void) { char *file; #ifdef DEBUG int starttime = Sys_MilliSeconds(); -#endif //DEBUG +#endif // DEBUG file = LibVarString("synfile", "syn.c"); synonyms = BotLoadSynonyms(file); @@ -2990,55 +2782,54 @@ int BotSetupChatAI(void) file = LibVarString("matchfile", "match.c"); matchtemplates = BotLoadMatchTemplates(file); // - if (!LibVarValue("nochat", "0")) - { + if (!LibVarValue("nochat", "0")) { file = LibVarString("rchatfile", "rchat.c"); replychats = BotLoadReplyChat(file); - } //end if + } // end if InitConsoleMessageHeap(); #ifdef DEBUG botimport.Print(PRT_MESSAGE, "setup chat AI %d msec\n", Sys_MilliSeconds() - starttime); -#endif //DEBUG +#endif // DEBUG return BLERR_NOERROR; -} //end of the function BotSetupChatAI +} // end of the function BotSetupChatAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownChatAI(void) -{ +void BotShutdownChatAI(void) { int i; - //free all remaining chat states - for(i = 0; i < MAX_CLIENTS; i++) - { - if (botchatstates[i]) - { + // free all remaining chat states + for (i = 0; i < MAX_CLIENTS; i++) { + if (botchatstates[i]) { BotFreeChatState(i); - } //end if - } //end for - //free all cached chats - for(i = 0; i < MAX_CLIENTS; i++) - { - if (ichatdata[i]) - { + } // end if + } // end for + // free all cached chats + for (i = 0; i < MAX_CLIENTS; i++) { + if (ichatdata[i]) { FreeMemory(ichatdata[i]->chat); FreeMemory(ichatdata[i]); ichatdata[i] = NULL; - } //end if - } //end for - if (consolemessageheap) FreeMemory(consolemessageheap); + } // end if + } // end for + if (consolemessageheap) + FreeMemory(consolemessageheap); consolemessageheap = NULL; - if (matchtemplates) BotFreeMatchTemplates(matchtemplates); + if (matchtemplates) + BotFreeMatchTemplates(matchtemplates); matchtemplates = NULL; - if (randomstrings) FreeMemory(randomstrings); + if (randomstrings) + FreeMemory(randomstrings); randomstrings = NULL; - if (synonyms) FreeMemory(synonyms); + if (synonyms) + FreeMemory(synonyms); synonyms = NULL; - if (replychats) BotFreeReplyChat(replychats); + if (replychats) + BotFreeReplyChat(replychats); replychats = NULL; -} //end of the function BotShutdownChatAI +} // end of the function BotShutdownChatAI diff --git a/codemp/botlib/be_ai_gen.cpp b/codemp/botlib/be_ai_gen.cpp index d3871b51ef..cf6470b770 100644 --- a/codemp/botlib/be_ai_gen.cpp +++ b/codemp/botlib/be_ai_gen.cpp @@ -54,86 +54,83 @@ along with this program; if not, see . // Returns: - // Changes Globals: - //=========================================================================== -int GeneticSelection(int numranks, float *rankings) -{ +int GeneticSelection(int numranks, float *rankings) { float sum; int i, index; sum = 0; - for (i = 0; i < numranks; i++) - { - if (rankings[i] < 0) continue; + for (i = 0; i < numranks; i++) { + if (rankings[i] < 0) + continue; sum += rankings[i]; - } //end for - if (sum > 0) - { - //select a bot where the ones with the higest rankings have - //the highest chance of being selected - //sum *= Q_flrand(0.0f, 1.0f); - for (i = 0; i < numranks; i++) - { - if (rankings[i] < 0) continue; + } // end for + if (sum > 0) { + // select a bot where the ones with the higest rankings have + // the highest chance of being selected + // sum *= Q_flrand(0.0f, 1.0f); + for (i = 0; i < numranks; i++) { + if (rankings[i] < 0) + continue; sum -= rankings[i]; - if (sum <= 0) return i; - } //end for - } //end if - //select a bot randomly + if (sum <= 0) + return i; + } // end for + } // end if + // select a bot randomly index = Q_flrand(0.0f, 1.0f) * numranks; - for (i = 0; i < numranks; i++) - { - if (rankings[index] >= 0) return index; + for (i = 0; i < numranks; i++) { + if (rankings[index] >= 0) + return index; index = (index + 1) % numranks; - } //end for + } // end for return 0; -} //end of the function GeneticSelection +} // end of the function GeneticSelection //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) -{ +int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) { float rankings[256], max; int i; - if (numranks > 256) - { + if (numranks > 256) { botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too many bots\n"); *parent1 = *parent2 = *child = 0; return qfalse; - } //end if - for (max = 0, i = 0; i < numranks; i++) - { - if (ranks[i] < 0) continue; + } // end if + for (max = 0, i = 0; i < numranks; i++) { + if (ranks[i] < 0) + continue; max++; - } //end for - if (max < 3) - { + } // end for + if (max < 3) { botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too few valid bots\n"); *parent1 = *parent2 = *child = 0; return qfalse; - } //end if + } // end if Com_Memcpy(rankings, ranks, sizeof(float) * numranks); - //select first parent + // select first parent *parent1 = GeneticSelection(numranks, rankings); rankings[*parent1] = -1; - //select second parent + // select second parent *parent2 = GeneticSelection(numranks, rankings); rankings[*parent2] = -1; - //reverse the rankings + // reverse the rankings max = 0; - for (i = 0; i < numranks; i++) - { - if (rankings[i] < 0) continue; - if (rankings[i] > max) max = rankings[i]; - } //end for - for (i = 0; i < numranks; i++) - { - if (rankings[i] < 0) continue; + for (i = 0; i < numranks; i++) { + if (rankings[i] < 0) + continue; + if (rankings[i] > max) + max = rankings[i]; + } // end for + for (i = 0; i < numranks; i++) { + if (rankings[i] < 0) + continue; rankings[i] = max - rankings[i]; - } //end for - //select child + } // end for + // select child *child = GeneticSelection(numranks, rankings); return qtrue; -} //end of the function GeneticParentsAndChildSelection +} // end of the function GeneticParentsAndChildSelection diff --git a/codemp/botlib/be_ai_goal.cpp b/codemp/botlib/be_ai_goal.cpp index 88c882f6b8..795d58a4da 100644 --- a/codemp/botlib/be_ai_goal.cpp +++ b/codemp/botlib/be_ai_goal.cpp @@ -54,35 +54,33 @@ along with this program; if not, see . //#define DEBUG_AI_GOAL #ifdef RANDOMIZE #define UNDECIDEDFUZZY -#endif //RANDOMIZE +#endif // RANDOMIZE #define DROPPEDWEIGHT -//minimum avoid goal time -#define AVOID_MINIMUM_TIME 10 -//default avoid goal time -#define AVOID_DEFAULT_TIME 30 -//avoid dropped goal time -#define AVOID_DROPPED_TIME 10 +// minimum avoid goal time +#define AVOID_MINIMUM_TIME 10 +// default avoid goal time +#define AVOID_DEFAULT_TIME 30 +// avoid dropped goal time +#define AVOID_DROPPED_TIME 10 // -#define TRAVELTIME_SCALE 0.01 -//item flags -#define IFL_NOTFREE 1 //not in free for all -#define IFL_NOTTEAM 2 //not in team play -#define IFL_NOTSINGLE 4 //not in single player -#define IFL_NOTBOT 8 //bot should never go for this -#define IFL_ROAM 16 //bot roam goal - -//location in the map "target_location" -typedef struct maplocation_s -{ +#define TRAVELTIME_SCALE 0.01 +// item flags +#define IFL_NOTFREE 1 // not in free for all +#define IFL_NOTTEAM 2 // not in team play +#define IFL_NOTSINGLE 4 // not in single player +#define IFL_NOTBOT 8 // bot should never go for this +#define IFL_ROAM 16 // bot roam goal + +// location in the map "target_location" +typedef struct maplocation_s { vec3_t origin; int areanum; char name[MAX_EPAIRKEY]; struct maplocation_s *next; } maplocation_t; -//camp spots "info_camp" -typedef struct campspot_s -{ +// camp spots "info_camp" +typedef struct campspot_s { vec3_t origin; int areanum; char name[MAX_EPAIRKEY]; @@ -93,110 +91,100 @@ typedef struct campspot_s struct campspot_s *next; } campspot_t; -//FIXME: these are game specific +// FIXME: these are game specific enum { - GT_FFA, // free for all - GT_HOLOCRON, // holocron match - GT_JEDIMASTER, // jedi master - GT_DUEL, // one on one tournament + GT_FFA, // free for all + GT_HOLOCRON, // holocron match + GT_JEDIMASTER, // jedi master + GT_DUEL, // one on one tournament GT_POWERDUEL, - GT_SINGLE_PLAYER, // single player tournament + GT_SINGLE_PLAYER, // single player tournament //-- team games go after this -- - GT_TEAM, // team deathmatch - GT_SIEGE, // siege - GT_CTF, // capture the flag + GT_TEAM, // team deathmatch + GT_SIEGE, // siege + GT_CTF, // capture the flag GT_CTY, GT_MAX_GAME_TYPE }; typedef int gametype_t; -typedef struct levelitem_s -{ - int number; //number of the level item - int iteminfo; //index into the item info - int flags; //item flags - float weight; //fixed roam weight - vec3_t origin; //origin of the item - int goalareanum; //area the item is in - vec3_t goalorigin; //goal origin within the area - int entitynum; //entity number - float timeout; //item is removed after this time +typedef struct levelitem_s { + int number; // number of the level item + int iteminfo; // index into the item info + int flags; // item flags + float weight; // fixed roam weight + vec3_t origin; // origin of the item + int goalareanum; // area the item is in + vec3_t goalorigin; // goal origin within the area + int entitynum; // entity number + float timeout; // item is removed after this time struct levelitem_s *prev, *next; } levelitem_t; -typedef struct iteminfo_s -{ - char classname[32]; //classname of the item - char name[MAX_STRINGFIELD]; //name of the item - char model[MAX_STRINGFIELD]; //model of the item - int modelindex; //model index - int type; //item type - int index; //index in the inventory - float respawntime; //respawn time - vec3_t mins; //mins of the item - vec3_t maxs; //maxs of the item - int number; //number of the item info +typedef struct iteminfo_s { + char classname[32]; // classname of the item + char name[MAX_STRINGFIELD]; // name of the item + char model[MAX_STRINGFIELD]; // model of the item + int modelindex; // model index + int type; // item type + int index; // index in the inventory + float respawntime; // respawn time + vec3_t mins; // mins of the item + vec3_t maxs; // maxs of the item + int number; // number of the item info } iteminfo_t; -#define ITEMINFO_OFS(x) offsetof(iteminfo_t, x) - -fielddef_t iteminfo_fields[] = -{ -{"name", ITEMINFO_OFS(name), FT_STRING}, -{"model", ITEMINFO_OFS(model), FT_STRING}, -{"modelindex", ITEMINFO_OFS(modelindex), FT_INT}, -{"type", ITEMINFO_OFS(type), FT_INT}, -{"index", ITEMINFO_OFS(index), FT_INT}, -{"respawntime", ITEMINFO_OFS(respawntime), FT_FLOAT}, -{"mins", ITEMINFO_OFS(mins), FT_FLOAT|FT_ARRAY, 3}, -{"maxs", ITEMINFO_OFS(maxs), FT_FLOAT|FT_ARRAY, 3}, -{NULL, 0, 0} -}; +#define ITEMINFO_OFS(x) offsetof(iteminfo_t, x) -structdef_t iteminfo_struct = -{ - sizeof(iteminfo_t), iteminfo_fields -}; +fielddef_t iteminfo_fields[] = {{"name", ITEMINFO_OFS(name), FT_STRING}, + {"model", ITEMINFO_OFS(model), FT_STRING}, + {"modelindex", ITEMINFO_OFS(modelindex), FT_INT}, + {"type", ITEMINFO_OFS(type), FT_INT}, + {"index", ITEMINFO_OFS(index), FT_INT}, + {"respawntime", ITEMINFO_OFS(respawntime), FT_FLOAT}, + {"mins", ITEMINFO_OFS(mins), FT_FLOAT | FT_ARRAY, 3}, + {"maxs", ITEMINFO_OFS(maxs), FT_FLOAT | FT_ARRAY, 3}, + {NULL, 0, 0}}; -typedef struct itemconfig_s -{ +structdef_t iteminfo_struct = {sizeof(iteminfo_t), iteminfo_fields}; + +typedef struct itemconfig_s { int numiteminfo; iteminfo_t *iteminfo; } itemconfig_t; -//goal state -typedef struct bot_goalstate_s -{ - struct weightconfig_s *itemweightconfig; //weight config - int *itemweightindex; //index from item to weight +// goal state +typedef struct bot_goalstate_s { + struct weightconfig_s *itemweightconfig; // weight config + int *itemweightindex; // index from item to weight // - int client; //client using this goal state - int lastreachabilityarea; //last area with reachabilities the bot was in + int client; // client using this goal state + int lastreachabilityarea; // last area with reachabilities the bot was in // - bot_goal_t goalstack[MAX_GOALSTACK]; //goal stack - int goalstacktop; //the top of the goal stack + bot_goal_t goalstack[MAX_GOALSTACK]; // goal stack + int goalstacktop; // the top of the goal stack // - int avoidgoals[MAX_AVOIDGOALS]; //goals to avoid - float avoidgoaltimes[MAX_AVOIDGOALS]; //times to avoid the goals + int avoidgoals[MAX_AVOIDGOALS]; // goals to avoid + float avoidgoaltimes[MAX_AVOIDGOALS]; // times to avoid the goals } bot_goalstate_t; bot_goalstate_t *botgoalstates[MAX_CLIENTS + 1]; // bk001206 - FIXME: init? -//item configuration +// item configuration itemconfig_t *itemconfig = NULL; // bk001206 - init -//level items -levelitem_t *levelitemheap = NULL; // bk001206 - init +// level items +levelitem_t *levelitemheap = NULL; // bk001206 - init levelitem_t *freelevelitems = NULL; // bk001206 - init -levelitem_t *levelitems = NULL; // bk001206 - init +levelitem_t *levelitems = NULL; // bk001206 - init int numlevelitems = 0; -//map locations +// map locations maplocation_t *maplocations = NULL; // bk001206 - init -//camp spots +// camp spots campspot_t *campspots = NULL; // bk001206 - init -//the game type +// the game type int g_gametype = 0; // bk001206 - init -//additional dropped item weight +// additional dropped item weight libvar_t *droppedweight = NULL; // bk001206 - init //======================================================================== @@ -205,73 +193,65 @@ libvar_t *droppedweight = NULL; // bk001206 - init // Returns: - // Changes Globals: - //======================================================================== -bot_goalstate_t *BotGoalStateFromHandle(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +bot_goalstate_t *BotGoalStateFromHandle(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle); return NULL; - } //end if - if (!botgoalstates[handle]) - { + } // end if + if (!botgoalstates[handle]) { botimport.Print(PRT_FATAL, "invalid goal state %d\n", handle); return NULL; - } //end if + } // end if return botgoalstates[handle]; -} //end of the function BotGoalStateFromHandle +} // end of the function BotGoalStateFromHandle //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) -{ +void BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { bot_goalstate_t *p1, *p2, *c; p1 = BotGoalStateFromHandle(parent1); p2 = BotGoalStateFromHandle(parent2); c = BotGoalStateFromHandle(child); - InterbreedWeightConfigs(p1->itemweightconfig, p2->itemweightconfig, - c->itemweightconfig); -} //end of the function BotInterbreedingGoalFuzzyLogic + InterbreedWeightConfigs(p1->itemweightconfig, p2->itemweightconfig, c->itemweightconfig); +} // end of the function BotInterbreedingGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotSaveGoalFuzzyLogic(int goalstate, char *filename) -{ - //bot_goalstate_t *gs; +void BotSaveGoalFuzzyLogic(int goalstate, char *filename) { + // bot_goalstate_t *gs; - //gs = BotGoalStateFromHandle(goalstate); + // gs = BotGoalStateFromHandle(goalstate); - //WriteWeightConfig(filename, gs->itemweightconfig); -} //end of the function BotSaveGoalFuzzyLogic + // WriteWeightConfig(filename, gs->itemweightconfig); +} // end of the function BotSaveGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotMutateGoalFuzzyLogic(int goalstate, float range) -{ +void BotMutateGoalFuzzyLogic(int goalstate, float range) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); EvolveWeightConfig(gs->itemweightconfig); -} //end of the function BotMutateGoalFuzzyLogic +} // end of the function BotMutateGoalFuzzyLogic //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -itemconfig_t *LoadItemConfig(char *filename) -{ +itemconfig_t *LoadItemConfig(char *filename) { int max_iteminfo; token_t token; char path[MAX_PATH]; @@ -279,71 +259,64 @@ itemconfig_t *LoadItemConfig(char *filename) itemconfig_t *ic; iteminfo_t *ii; - max_iteminfo = (int) LibVarValue("max_iteminfo", "256"); - if (max_iteminfo < 0) - { + max_iteminfo = (int)LibVarValue("max_iteminfo", "256"); + if (max_iteminfo < 0) { botimport.Print(PRT_ERROR, "max_iteminfo = %d\n", max_iteminfo); max_iteminfo = 256; - LibVarSet( "max_iteminfo", "256" ); + LibVarSet("max_iteminfo", "256"); } - strncpy( path, filename, MAX_PATH ); + strncpy(path, filename, MAX_PATH); PC_SetBaseFolder(BOTFILESBASEFOLDER); - source = LoadSourceFile( path ); - if( !source ) { - botimport.Print( PRT_ERROR, "counldn't load %s\n", path ); + source = LoadSourceFile(path); + if (!source) { + botimport.Print(PRT_ERROR, "counldn't load %s\n", path); return NULL; - } //end if - //initialize item config - ic = (itemconfig_t *) GetClearedHunkMemory(sizeof(itemconfig_t) + - max_iteminfo * sizeof(iteminfo_t)); - ic->iteminfo = (iteminfo_t *) ((char *) ic + sizeof(itemconfig_t)); + } // end if + // initialize item config + ic = (itemconfig_t *)GetClearedHunkMemory(sizeof(itemconfig_t) + max_iteminfo * sizeof(iteminfo_t)); + ic->iteminfo = (iteminfo_t *)((char *)ic + sizeof(itemconfig_t)); ic->numiteminfo = 0; - //parse the item config file - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "iteminfo")) - { - if (ic->numiteminfo >= max_iteminfo) - { + // parse the item config file + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "iteminfo")) { + if (ic->numiteminfo >= max_iteminfo) { SourceError(source, "more than %d item info defined", max_iteminfo); FreeMemory(ic); FreeSource(source); return NULL; - } //end if + } // end if ii = &ic->iteminfo[ic->numiteminfo]; Com_Memset(ii, 0, sizeof(iteminfo_t)); - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeMemory(ic); FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - strncpy(ii->classname, token.string, sizeof(ii->classname)-1); - if (!ReadStructure(source, &iteminfo_struct, (char *) ii)) - { + strncpy(ii->classname, token.string, sizeof(ii->classname) - 1); + if (!ReadStructure(source, &iteminfo_struct, (char *)ii)) { FreeMemory(ic); FreeSource(source); return NULL; - } //end if + } // end if ii->number = ic->numiteminfo; ic->numiteminfo++; - } //end if - else - { + } // end if + else { SourceError(source, "unknown definition %s", token.string); FreeMemory(ic); FreeSource(source); return NULL; - } //end else - } //end while + } // end else + } // end while FreeSource(source); // - if (!ic->numiteminfo) botimport.Print(PRT_WARNING, "no item info loaded\n"); + if (!ic->numiteminfo) + botimport.Print(PRT_WARNING, "no item info loaded\n"); botimport.Print(PRT_MESSAGE, "loaded %s\n", path); return ic; -} //end of the function LoadItemConfig +} // end of the function LoadItemConfig //=========================================================================== // index to find the weight function of an iteminfo // @@ -351,135 +324,126 @@ itemconfig_t *LoadItemConfig(char *filename) // Returns: - // Changes Globals: - //=========================================================================== -int *ItemWeightIndex(weightconfig_t *iwc, itemconfig_t *ic) -{ +int *ItemWeightIndex(weightconfig_t *iwc, itemconfig_t *ic) { int *index, i; - //initialize item weight index - index = (int *) GetClearedMemory(sizeof(int) * ic->numiteminfo); + // initialize item weight index + index = (int *)GetClearedMemory(sizeof(int) * ic->numiteminfo); - for (i = 0; i < ic->numiteminfo; i++) - { + for (i = 0; i < ic->numiteminfo; i++) { index[i] = FindFuzzyWeight(iwc, ic->iteminfo[i].classname); - if (index[i] < 0) - { + if (index[i] < 0) { Log_Write("item info %d \"%s\" has no fuzzy weight\r\n", i, ic->iteminfo[i].classname); - } //end if - } //end for + } // end if + } // end for return index; -} //end of the function ItemWeightIndex +} // end of the function ItemWeightIndex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void InitLevelItemHeap(void) -{ +void InitLevelItemHeap(void) { int i, max_levelitems; - if (levelitemheap) FreeMemory(levelitemheap); + if (levelitemheap) + FreeMemory(levelitemheap); - max_levelitems = (int) LibVarValue("max_levelitems", "256"); - levelitemheap = (levelitem_t *) GetClearedMemory(max_levelitems * sizeof(levelitem_t)); + max_levelitems = (int)LibVarValue("max_levelitems", "256"); + levelitemheap = (levelitem_t *)GetClearedMemory(max_levelitems * sizeof(levelitem_t)); - for (i = 0; i < max_levelitems-1; i++) - { + for (i = 0; i < max_levelitems - 1; i++) { levelitemheap[i].next = &levelitemheap[i + 1]; - } //end for - levelitemheap[max_levelitems-1].next = NULL; + } // end for + levelitemheap[max_levelitems - 1].next = NULL; // freelevelitems = levelitemheap; -} //end of the function InitLevelItemHeap +} // end of the function InitLevelItemHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -levelitem_t *AllocLevelItem(void) -{ +levelitem_t *AllocLevelItem(void) { levelitem_t *li; li = freelevelitems; - if (!li) - { + if (!li) { botimport.Print(PRT_FATAL, "out of level items\n"); return NULL; - } //end if + } // end if // freelevelitems = freelevelitems->next; Com_Memset(li, 0, sizeof(levelitem_t)); return li; -} //end of the function AllocLevelItem +} // end of the function AllocLevelItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeLevelItem(levelitem_t *li) -{ +void FreeLevelItem(levelitem_t *li) { li->next = freelevelitems; freelevelitems = li; -} //end of the function FreeLevelItem +} // end of the function FreeLevelItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void AddLevelItemToList(levelitem_t *li) -{ - if (levelitems) levelitems->prev = li; +void AddLevelItemToList(levelitem_t *li) { + if (levelitems) + levelitems->prev = li; li->prev = NULL; li->next = levelitems; levelitems = li; -} //end of the function AddLevelItemToList +} // end of the function AddLevelItemToList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void RemoveLevelItemFromList(levelitem_t *li) -{ - if (li->prev) li->prev->next = li->next; - else levelitems = li->next; - if (li->next) li->next->prev = li->prev; -} //end of the function RemoveLevelItemFromList +void RemoveLevelItemFromList(levelitem_t *li) { + if (li->prev) + li->prev->next = li->next; + else + levelitems = li->next; + if (li->next) + li->next->prev = li->prev; +} // end of the function RemoveLevelItemFromList //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeInfoEntities(void) -{ +void BotFreeInfoEntities(void) { maplocation_t *ml, *nextml; campspot_t *cs, *nextcs; - for (ml = maplocations; ml; ml = nextml) - { + for (ml = maplocations; ml; ml = nextml) { nextml = ml->next; FreeMemory(ml); - } //end for + } // end for maplocations = NULL; - for (cs = campspots; cs; cs = nextcs) - { + for (cs = campspots; cs; cs = nextcs) { nextcs = cs->next; FreeMemory(cs); - } //end for + } // end for campspots = NULL; -} //end of the function BotFreeInfoEntities +} // end of the function BotFreeInfoEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotInitInfoEntities(void) -{ +void BotInitInfoEntities(void) { char classname[MAX_EPAIRKEY]; maplocation_t *ml; campspot_t *cs; @@ -489,59 +453,54 @@ void BotInitInfoEntities(void) // numlocations = 0; numcampspots = 0; - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; - //map locations - if (!strcmp(classname, "target_location")) - { - ml = (maplocation_t *) GetClearedMemory(sizeof(maplocation_t)); + // map locations + if (!strcmp(classname, "target_location")) { + ml = (maplocation_t *)GetClearedMemory(sizeof(maplocation_t)); AAS_VectorForBSPEpairKey(ent, "origin", ml->origin); AAS_ValueForBSPEpairKey(ent, "message", ml->name, sizeof(ml->name)); ml->areanum = AAS_PointAreaNum(ml->origin); ml->next = maplocations; maplocations = ml; numlocations++; - } //end if - //camp spots - else if (!strcmp(classname, "info_camp")) - { - cs = (campspot_t *) GetClearedMemory(sizeof(campspot_t)); + } // end if + // camp spots + else if (!strcmp(classname, "info_camp")) { + cs = (campspot_t *)GetClearedMemory(sizeof(campspot_t)); AAS_VectorForBSPEpairKey(ent, "origin", cs->origin); - //cs->origin[2] += 16; + // cs->origin[2] += 16; AAS_ValueForBSPEpairKey(ent, "message", cs->name, sizeof(cs->name)); AAS_FloatForBSPEpairKey(ent, "range", &cs->range); AAS_FloatForBSPEpairKey(ent, "weight", &cs->weight); AAS_FloatForBSPEpairKey(ent, "wait", &cs->wait); AAS_FloatForBSPEpairKey(ent, "random", &cs->random); cs->areanum = AAS_PointAreaNum(cs->origin); - if (!cs->areanum) - { + if (!cs->areanum) { botimport.Print(PRT_MESSAGE, "camp spot at %1.1f %1.1f %1.1f in solid\n", cs->origin[0], cs->origin[1], cs->origin[2]); FreeMemory(cs); continue; - } //end if + } // end if cs->next = campspots; campspots = cs; - //AAS_DrawPermanentCross(cs->origin, 4, LINECOLOR_YELLOW); + // AAS_DrawPermanentCross(cs->origin, 4, LINECOLOR_YELLOW); numcampspots++; - } //end else if - } //end for - if (botDeveloper) - { + } // end else if + } // end for + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "%d map locations\n", numlocations); botimport.Print(PRT_MESSAGE, "%d camp spots\n", numcampspots); - } //end if -} //end of the function BotInitInfoEntities + } // end if +} // end of the function BotInitInfoEntities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotInitLevelItems(void) -{ +void BotInitLevelItems(void) { int i, spawnflags, value; char classname[MAX_EPAIRKEY]; vec3_t origin, end; @@ -550,76 +509,73 @@ void BotInitLevelItems(void) levelitem_t *li; bsp_trace_t trace; - //initialize the map locations and camp spots + // initialize the map locations and camp spots BotInitInfoEntities(); - //initialize the level item heap + // initialize the level item heap InitLevelItemHeap(); levelitems = NULL; numlevelitems = 0; // ic = itemconfig; - if (!ic) return; + if (!ic) + return; - //if there's no AAS file loaded - if (!AAS_Loaded()) return; + // if there's no AAS file loaded + if (!AAS_Loaded()) + return; - //validate the modelindexes of the item info - for (i = 0; i < ic->numiteminfo; i++) - { - if (!ic->iteminfo[i].modelindex) - { + // validate the modelindexes of the item info + for (i = 0; i < ic->numiteminfo; i++) { + if (!ic->iteminfo[i].modelindex) { Log_Write("item %s has modelindex 0", ic->iteminfo[i].classname); - } //end if - } //end for + } // end if + } // end for - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; // spawnflags = 0; AAS_IntForBSPEpairKey(ent, "spawnflags", &spawnflags); // - for (i = 0; i < ic->numiteminfo; i++) - { - if (!strcmp(classname, ic->iteminfo[i].classname)) break; - } //end for - if (i >= ic->numiteminfo) - { + for (i = 0; i < ic->numiteminfo; i++) { + if (!strcmp(classname, ic->iteminfo[i].classname)) + break; + } // end for + if (i >= ic->numiteminfo) { Log_Write("entity %s unknown item\r\n", classname); continue; - } //end if - //get the origin of the item - if (!AAS_VectorForBSPEpairKey(ent, "origin", origin)) - { + } // end if + // get the origin of the item + if (!AAS_VectorForBSPEpairKey(ent, "origin", origin)) { botimport.Print(PRT_ERROR, "item %s without origin\n", classname); continue; - } //end else + } // end else // goalareanum = 0; - //if it is a floating item - if (spawnflags & 1) - { - //if the item is not floating in water - if (!(AAS_PointContents(origin) & CONTENTS_WATER)) - { + // if it is a floating item + if (spawnflags & 1) { + // if the item is not floating in water + if (!(AAS_PointContents(origin) & CONTENTS_WATER)) { VectorCopy(origin, end); end[2] -= 32; - trace = AAS_Trace(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, end, -1, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - //if the item not near the ground - if (trace.fraction >= 1) - { - //if the item is not reachable from a jumppad + trace = AAS_Trace(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, end, -1, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + // if the item not near the ground + if (trace.fraction >= 1) { + // if the item is not reachable from a jumppad goalareanum = AAS_BestReachableFromJumpPadArea(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs); Log_Write("item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum); - //botimport.Print(PRT_MESSAGE, "item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum); - if (!goalareanum) continue; - } //end if - } //end if - } //end if + // botimport.Print(PRT_MESSAGE, "item %s reachable from jumppad area %d\r\n", ic->iteminfo[i].classname, goalareanum); + if (!goalareanum) + continue; + } // end if + } // end if + } // end if li = AllocLevelItem(); - if (!li) return; + if (!li) + return; // li->number = ++numlevelitems; li->timeout = 0; @@ -627,218 +583,194 @@ void BotInitLevelItems(void) // li->flags = 0; AAS_IntForBSPEpairKey(ent, "notfree", &value); - if (value) li->flags |= IFL_NOTFREE; + if (value) + li->flags |= IFL_NOTFREE; AAS_IntForBSPEpairKey(ent, "notteam", &value); - if (value) li->flags |= IFL_NOTTEAM; + if (value) + li->flags |= IFL_NOTTEAM; AAS_IntForBSPEpairKey(ent, "notsingle", &value); - if (value) li->flags |= IFL_NOTSINGLE; + if (value) + li->flags |= IFL_NOTSINGLE; AAS_IntForBSPEpairKey(ent, "notbot", &value); - if (value) li->flags |= IFL_NOTBOT; - if (!strcmp(classname, "item_botroam")) - { + if (value) + li->flags |= IFL_NOTBOT; + if (!strcmp(classname, "item_botroam")) { li->flags |= IFL_ROAM; AAS_FloatForBSPEpairKey(ent, "weight", &li->weight); - } //end if - //if not a stationary item - if (!(spawnflags & 1)) - { - if (!AAS_DropToFloor(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs)) - { - botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", - classname, origin[0], origin[1], origin[2]); - } //end if - } //end if - //item info of the level item + } // end if + // if not a stationary item + if (!(spawnflags & 1)) { + if (!AAS_DropToFloor(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs)) { + botimport.Print(PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2]); + } // end if + } // end if + // item info of the level item li->iteminfo = i; - //origin of the item + // origin of the item VectorCopy(origin, li->origin); // - if (goalareanum) - { + if (goalareanum) { li->goalareanum = goalareanum; VectorCopy(origin, li->goalorigin); - } //end if - else - { - //get the item goal area and goal origin - li->goalareanum = AAS_BestReachableArea(origin, - ic->iteminfo[i].mins, ic->iteminfo[i].maxs, - li->goalorigin); - if (!li->goalareanum) - { - botimport.Print(PRT_MESSAGE, "%s not reachable for bots at (%1.1f %1.1f %1.1f)\n", - classname, origin[0], origin[1], origin[2]); - } //end if - } //end else + } // end if + else { + // get the item goal area and goal origin + li->goalareanum = AAS_BestReachableArea(origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, li->goalorigin); + if (!li->goalareanum) { + botimport.Print(PRT_MESSAGE, "%s not reachable for bots at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2]); + } // end if + } // end else // AddLevelItemToList(li); - } //end for + } // end for botimport.Print(PRT_MESSAGE, "found %d level items\n", numlevelitems); -} //end of the function BotInitLevelItems +} // end of the function BotInitLevelItems //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotGoalName(int number, char *name, int size) -{ +void BotGoalName(int number, char *name, int size) { levelitem_t *li; - if (!itemconfig) return; + if (!itemconfig) + return; // - for (li = levelitems; li; li = li->next) - { - if (li->number == number) - { - strncpy(name, itemconfig->iteminfo[li->iteminfo].name, size-1); - name[size-1] = '\0'; + for (li = levelitems; li; li = li->next) { + if (li->number == number) { + strncpy(name, itemconfig->iteminfo[li->iteminfo].name, size - 1); + name[size - 1] = '\0'; return; - } //end for - } //end for + } // end for + } // end for strcpy(name, ""); return; -} //end of the function BotGoalName +} // end of the function BotGoalName //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetAvoidGoals(int goalstate) -{ +void BotResetAvoidGoals(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; + if (!gs) + return; Com_Memset(gs->avoidgoals, 0, MAX_AVOIDGOALS * sizeof(int)); Com_Memset(gs->avoidgoaltimes, 0, MAX_AVOIDGOALS * sizeof(float)); -} //end of the function BotResetAvoidGoals +} // end of the function BotResetAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpAvoidGoals(int goalstate) -{ +void BotDumpAvoidGoals(int goalstate) { int i; bot_goalstate_t *gs; char name[32]; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - for (i = 0; i < MAX_AVOIDGOALS; i++) - { - if (gs->avoidgoaltimes[i] >= AAS_Time()) - { + if (!gs) + return; + for (i = 0; i < MAX_AVOIDGOALS; i++) { + if (gs->avoidgoaltimes[i] >= AAS_Time()) { BotGoalName(gs->avoidgoals[i], name, 32); - Log_Write("avoid goal %s, number %d for %f seconds", name, - gs->avoidgoals[i], gs->avoidgoaltimes[i] - AAS_Time()); - } //end if - } //end for -} //end of the function BotDumpAvoidGoals + Log_Write("avoid goal %s, number %d for %f seconds", name, gs->avoidgoals[i], gs->avoidgoaltimes[i] - AAS_Time()); + } // end if + } // end for +} // end of the function BotDumpAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotAddToAvoidGoals(bot_goalstate_t *gs, int number, float avoidtime) -{ +void BotAddToAvoidGoals(bot_goalstate_t *gs, int number, float avoidtime) { int i; - for (i = 0; i < MAX_AVOIDGOALS; i++) - { - //if the avoid goal is already stored - if (gs->avoidgoals[i] == number) - { + for (i = 0; i < MAX_AVOIDGOALS; i++) { + // if the avoid goal is already stored + if (gs->avoidgoals[i] == number) { gs->avoidgoals[i] = number; gs->avoidgoaltimes[i] = AAS_Time() + avoidtime; return; - } //end if - } //end for + } // end if + } // end for - for (i = 0; i < MAX_AVOIDGOALS; i++) - { - //if this avoid goal has expired - if (gs->avoidgoaltimes[i] < AAS_Time()) - { + for (i = 0; i < MAX_AVOIDGOALS; i++) { + // if this avoid goal has expired + if (gs->avoidgoaltimes[i] < AAS_Time()) { gs->avoidgoals[i] = number; gs->avoidgoaltimes[i] = AAS_Time() + avoidtime; return; - } //end if - } //end for -} //end of the function BotAddToAvoidGoals + } // end if + } // end for +} // end of the function BotAddToAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotRemoveFromAvoidGoals(int goalstate, int number) -{ +void BotRemoveFromAvoidGoals(int goalstate, int number) { int i; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - //don't use the goals the bot wants to avoid - for (i = 0; i < MAX_AVOIDGOALS; i++) - { - if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) - { + if (!gs) + return; + // don't use the goals the bot wants to avoid + for (i = 0; i < MAX_AVOIDGOALS; i++) { + if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) { gs->avoidgoaltimes[i] = 0; return; - } //end if - } //end for -} //end of the function BotRemoveFromAvoidGoals + } // end if + } // end for +} // end of the function BotRemoveFromAvoidGoals //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float BotAvoidGoalTime(int goalstate, int number) -{ +float BotAvoidGoalTime(int goalstate, int number) { int i; bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return 0; - //don't use the goals the bot wants to avoid - for (i = 0; i < MAX_AVOIDGOALS; i++) - { - if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) - { + if (!gs) + return 0; + // don't use the goals the bot wants to avoid + for (i = 0; i < MAX_AVOIDGOALS; i++) { + if (gs->avoidgoals[i] == number && gs->avoidgoaltimes[i] >= AAS_Time()) { return gs->avoidgoaltimes[i] - AAS_Time(); - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotAvoidGoalTime +} // end of the function BotAvoidGoalTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) -{ +void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { bot_goalstate_t *gs; levelitem_t *li; gs = BotGoalStateFromHandle(goalstate); if (!gs) return; - if (avoidtime < 0) - { + if (avoidtime < 0) { if (!itemconfig) return; // - for (li = levelitems; li; li = li->next) - { - if (li->number == number) - { + for (li = levelitems; li; li = li->next) { + if (li->number == number) { avoidtime = itemconfig->iteminfo[li->iteminfo].respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; @@ -846,54 +778,50 @@ void BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) avoidtime = AVOID_MINIMUM_TIME; BotAddToAvoidGoals(gs, number, avoidtime); return; - } //end for - } //end for + } // end for + } // end for return; - } //end if - else - { + } // end if + else { BotAddToAvoidGoals(gs, number, avoidtime); - } //end else -} //end of the function BotSetAvoidGoalTime + } // end else +} // end of the function BotSetAvoidGoalTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetLevelItemGoal(int index, char *name, bot_goal_t *goal) -{ +int BotGetLevelItemGoal(int index, char *name, bot_goal_t *goal) { levelitem_t *li; - if (!itemconfig) return -1; + if (!itemconfig) + return -1; li = levelitems; - if (index >= 0) - { - for (; li; li = li->next) - { - if (li->number == index) - { + if (index >= 0) { + for (; li; li = li->next) { + if (li->number == index) { li = li->next; break; - } //end if - } //end for - } //end for - for (; li; li = li->next) - { + } // end if + } // end for + } // end for + for (; li; li = li->next) { // if (g_gametype == GT_SINGLE_PLAYER) { - if (li->flags & IFL_NOTSINGLE) continue; - } - else if (g_gametype >= GT_TEAM) { - if (li->flags & IFL_NOTTEAM) continue; - } - else { - if (li->flags & IFL_NOTFREE) continue; + if (li->flags & IFL_NOTSINGLE) + continue; + } else if (g_gametype >= GT_TEAM) { + if (li->flags & IFL_NOTTEAM) + continue; + } else { + if (li->flags & IFL_NOTFREE) + continue; } - if (li->flags & IFL_NOTBOT) continue; + if (li->flags & IFL_NOTBOT) + continue; // - if (!Q_stricmp(name, itemconfig->iteminfo[li->iteminfo].name)) - { + if (!Q_stricmp(name, itemconfig->iteminfo[li->iteminfo].name)) { goal->areanum = li->goalareanum; VectorCopy(li->goalorigin, goal->origin); goal->entitynum = li->entitynum; @@ -901,106 +829,99 @@ int BotGetLevelItemGoal(int index, char *name, bot_goal_t *goal) VectorCopy(itemconfig->iteminfo[li->iteminfo].maxs, goal->maxs); goal->number = li->number; goal->flags = GFL_ITEM; - if (li->timeout) goal->flags |= GFL_DROPPED; - //botimport.Print(PRT_MESSAGE, "found li %s\n", itemconfig->iteminfo[li->iteminfo].name); + if (li->timeout) + goal->flags |= GFL_DROPPED; + // botimport.Print(PRT_MESSAGE, "found li %s\n", itemconfig->iteminfo[li->iteminfo].name); return li->number; - } //end if - } //end for + } // end if + } // end for return -1; -} //end of the function BotGetLevelItemGoal +} // end of the function BotGetLevelItemGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetMapLocationGoal(char *name, bot_goal_t *goal) -{ +int BotGetMapLocationGoal(char *name, bot_goal_t *goal) { maplocation_t *ml; vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8}; - for (ml = maplocations; ml; ml = ml->next) - { - if (!Q_stricmp(ml->name, name)) - { + for (ml = maplocations; ml; ml = ml->next) { + if (!Q_stricmp(ml->name, name)) { goal->areanum = ml->areanum; VectorCopy(ml->origin, goal->origin); goal->entitynum = 0; VectorCopy(mins, goal->mins); VectorCopy(maxs, goal->maxs); return qtrue; - } //end if - } //end for + } // end if + } // end for return qfalse; -} //end of the function BotGetMapLocationGoal +} // end of the function BotGetMapLocationGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetNextCampSpotGoal(int num, bot_goal_t *goal) -{ +int BotGetNextCampSpotGoal(int num, bot_goal_t *goal) { int i; campspot_t *cs; vec3_t mins = {-8, -8, -8}, maxs = {8, 8, 8}; - if (num < 0) num = 0; + if (num < 0) + num = 0; i = num; - for (cs = campspots; cs; cs = cs->next) - { - if (--i < 0) - { + for (cs = campspots; cs; cs = cs->next) { + if (--i < 0) { goal->areanum = cs->areanum; VectorCopy(cs->origin, goal->origin); goal->entitynum = 0; VectorCopy(mins, goal->mins); VectorCopy(maxs, goal->maxs); - return num+1; - } //end if - } //end for + return num + 1; + } // end if + } // end for return 0; -} //end of the function BotGetNextCampSpotGoal +} // end of the function BotGetNextCampSpotGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFindEntityForLevelItem(levelitem_t *li) -{ +void BotFindEntityForLevelItem(levelitem_t *li) { int ent, modelindex; itemconfig_t *ic; aas_entityinfo_t entinfo; vec3_t dir; ic = itemconfig; - if (!itemconfig) return; - for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) - { - //get the model index of the entity + if (!itemconfig) + return; + for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) { + // get the model index of the entity modelindex = AAS_EntityModelindex(ent); // - if (!modelindex) continue; - //get info about the entity + if (!modelindex) + continue; + // get info about the entity AAS_EntityInfo(ent, &entinfo); - //if the entity is still moving - if (entinfo.origin[0] != entinfo.lastvisorigin[0] || - entinfo.origin[1] != entinfo.lastvisorigin[1] || - entinfo.origin[2] != entinfo.lastvisorigin[2]) continue; + // if the entity is still moving + if (entinfo.origin[0] != entinfo.lastvisorigin[0] || entinfo.origin[1] != entinfo.lastvisorigin[1] || entinfo.origin[2] != entinfo.lastvisorigin[2]) + continue; // - if (ic->iteminfo[li->iteminfo].modelindex == modelindex) - { - //check if the entity is very close + if (ic->iteminfo[li->iteminfo].modelindex == modelindex) { + // check if the entity is very close VectorSubtract(li->origin, entinfo.origin, dir); - if (VectorLength(dir) < 30) - { - //found an entity for this level item + if (VectorLength(dir) < 30) { + // found an entity for this level item li->entitynum = ent; - } //end if - } //end if - } //end for -} //end of the function BotFindEntityForLevelItem + } // end if + } // end if + } // end for +} // end of the function BotFindEntityForLevelItem //=========================================================================== // // Parameter: - @@ -1008,167 +929,148 @@ void BotFindEntityForLevelItem(levelitem_t *li) // Changes Globals: - //=========================================================================== -//NOTE: enum entityType_t in bg_public.h -#define ET_ITEM 2 +// NOTE: enum entityType_t in bg_public.h +#define ET_ITEM 2 -void BotUpdateEntityItems(void) -{ +void BotUpdateEntityItems(void) { int ent, i, modelindex; vec3_t dir; levelitem_t *li, *nextli; aas_entityinfo_t entinfo; itemconfig_t *ic; - //timeout current entity items if necessary - for (li = levelitems; li; li = nextli) - { + // timeout current entity items if necessary + for (li = levelitems; li; li = nextli) { nextli = li->next; - //if it is an item that will time out - if (li->timeout) - { - //timeout the item - if (li->timeout < AAS_Time()) - { + // if it is an item that will time out + if (li->timeout) { + // timeout the item + if (li->timeout < AAS_Time()) { RemoveLevelItemFromList(li); FreeLevelItem(li); - } //end if - } //end if - } //end for - //find new entity items + } // end if + } // end if + } // end for + // find new entity items ic = itemconfig; - if (!itemconfig) return; + if (!itemconfig) + return; // - for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) - { - if (AAS_EntityType(ent) != ET_ITEM) continue; - //get the model index of the entity + for (ent = AAS_NextEntity(0); ent; ent = AAS_NextEntity(ent)) { + if (AAS_EntityType(ent) != ET_ITEM) + continue; + // get the model index of the entity modelindex = AAS_EntityModelindex(ent); // - if (!modelindex) continue; - //get info about the entity + if (!modelindex) + continue; + // get info about the entity AAS_EntityInfo(ent, &entinfo); - //FIXME: don't do this - //skip all floating items for now - //if (entinfo.groundent != ENTITYNUM_WORLD) continue; - //if the entity is still moving - if (entinfo.origin[0] != entinfo.lastvisorigin[0] || - entinfo.origin[1] != entinfo.lastvisorigin[1] || - entinfo.origin[2] != entinfo.lastvisorigin[2]) continue; - //check if the entity is already stored as a level item - for (li = levelitems; li; li = li->next) - { - //if the level item is linked to an entity - if (li->entitynum && li->entitynum == ent) - { - //the entity is re-used if the models are different - if (ic->iteminfo[li->iteminfo].modelindex != modelindex) - { - //remove this level item + // FIXME: don't do this + // skip all floating items for now + // if (entinfo.groundent != ENTITYNUM_WORLD) continue; + // if the entity is still moving + if (entinfo.origin[0] != entinfo.lastvisorigin[0] || entinfo.origin[1] != entinfo.lastvisorigin[1] || entinfo.origin[2] != entinfo.lastvisorigin[2]) + continue; + // check if the entity is already stored as a level item + for (li = levelitems; li; li = li->next) { + // if the level item is linked to an entity + if (li->entitynum && li->entitynum == ent) { + // the entity is re-used if the models are different + if (ic->iteminfo[li->iteminfo].modelindex != modelindex) { + // remove this level item RemoveLevelItemFromList(li); FreeLevelItem(li); li = NULL; break; - } //end if - else - { - if (entinfo.origin[0] != li->origin[0] || - entinfo.origin[1] != li->origin[1] || - entinfo.origin[2] != li->origin[2]) - { + } // end if + else { + if (entinfo.origin[0] != li->origin[0] || entinfo.origin[1] != li->origin[1] || entinfo.origin[2] != li->origin[2]) { VectorCopy(entinfo.origin, li->origin); - //also update the goal area number - li->goalareanum = AAS_BestReachableArea(li->origin, - ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, - li->goalorigin); - } //end if + // also update the goal area number + li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, li->goalorigin); + } // end if break; - } //end else - } //end if - } //end for - if (li) continue; - //try to link the entity to a level item - for (li = levelitems; li; li = li->next) - { - //if this level item is already linked - if (li->entitynum) continue; + } // end else + } // end if + } // end for + if (li) + continue; + // try to link the entity to a level item + for (li = levelitems; li; li = li->next) { + // if this level item is already linked + if (li->entitynum) + continue; // if (g_gametype == GT_SINGLE_PLAYER) { - if (li->flags & IFL_NOTSINGLE) continue; - } - else if (g_gametype >= GT_TEAM) { - if (li->flags & IFL_NOTTEAM) continue; - } - else { - if (li->flags & IFL_NOTFREE) continue; + if (li->flags & IFL_NOTSINGLE) + continue; + } else if (g_gametype >= GT_TEAM) { + if (li->flags & IFL_NOTTEAM) + continue; + } else { + if (li->flags & IFL_NOTFREE) + continue; } - //if the model of the level item and the entity are the same - if (ic->iteminfo[li->iteminfo].modelindex == modelindex) - { - //check if the entity is very close + // if the model of the level item and the entity are the same + if (ic->iteminfo[li->iteminfo].modelindex == modelindex) { + // check if the entity is very close VectorSubtract(li->origin, entinfo.origin, dir); - if (VectorLength(dir) < 30) - { - //found an entity for this level item + if (VectorLength(dir) < 30) { + // found an entity for this level item li->entitynum = ent; - //if the origin is different - if (entinfo.origin[0] != li->origin[0] || - entinfo.origin[1] != li->origin[1] || - entinfo.origin[2] != li->origin[2]) - { - //update the level item origin + // if the origin is different + if (entinfo.origin[0] != li->origin[0] || entinfo.origin[1] != li->origin[1] || entinfo.origin[2] != li->origin[2]) { + // update the level item origin VectorCopy(entinfo.origin, li->origin); - //also update the goal area number - li->goalareanum = AAS_BestReachableArea(li->origin, - ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, - li->goalorigin); - } //end if + // also update the goal area number + li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[li->iteminfo].mins, ic->iteminfo[li->iteminfo].maxs, li->goalorigin); + } // end if #ifdef DEBUG Log_Write("linked item %s to an entity", ic->iteminfo[li->iteminfo].classname); -#endif //DEBUG +#endif // DEBUG break; - } //end if - } //end else - } //end for - if (li) continue; - //check if the model is from a known item - for (i = 0; i < ic->numiteminfo; i++) - { - if (ic->iteminfo[i].modelindex == modelindex) - { + } // end if + } // end else + } // end for + if (li) + continue; + // check if the model is from a known item + for (i = 0; i < ic->numiteminfo; i++) { + if (ic->iteminfo[i].modelindex == modelindex) { break; - } //end if - } //end for - //if the model is not from a known item - if (i >= ic->numiteminfo) continue; - //allocate a new level item + } // end if + } // end for + // if the model is not from a known item + if (i >= ic->numiteminfo) + continue; + // allocate a new level item li = AllocLevelItem(); // - if (!li) continue; - //entity number of the level item + if (!li) + continue; + // entity number of the level item li->entitynum = ent; - //number for the level item + // number for the level item li->number = numlevelitems + ent; - //set the item info index for the level item + // set the item info index for the level item li->iteminfo = i; - //origin of the item + // origin of the item VectorCopy(entinfo.origin, li->origin); - //get the item goal area and goal origin - li->goalareanum = AAS_BestReachableArea(li->origin, - ic->iteminfo[i].mins, ic->iteminfo[i].maxs, - li->goalorigin); - //never go for items dropped into jumppads - if (AAS_AreaJumpPad(li->goalareanum)) - { + // get the item goal area and goal origin + li->goalareanum = AAS_BestReachableArea(li->origin, ic->iteminfo[i].mins, ic->iteminfo[i].maxs, li->goalorigin); + // never go for items dropped into jumppads + if (AAS_AreaJumpPad(li->goalareanum)) { FreeLevelItem(li); continue; - } //end if - //time this item out after 30 seconds - //dropped items disappear after 30 seconds + } // end if + // time this item out after 30 seconds + // dropped items disappear after 30 seconds li->timeout = AAS_Time() + 30; - //add the level item to the list + // add the level item to the list AddLevelItemToList(li); - //botimport.Print(PRT_MESSAGE, "found new level item %s\n", ic->iteminfo[i].classname); - } //end for + // botimport.Print(PRT_MESSAGE, "found new level item %s\n", ic->iteminfo[i].classname); + } // end for /* for (li = levelitems; li; li = li->next) { @@ -1177,108 +1079,109 @@ void BotUpdateEntityItems(void) BotFindEntityForLevelItem(li); } //end if } //end for*/ -} //end of the function BotUpdateEntityItems +} // end of the function BotUpdateEntityItems //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotDumpGoalStack(int goalstate) -{ +void BotDumpGoalStack(int goalstate) { int i; bot_goalstate_t *gs; char name[32]; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - for (i = 1; i <= gs->goalstacktop; i++) - { + if (!gs) + return; + for (i = 1; i <= gs->goalstacktop; i++) { BotGoalName(gs->goalstack[i].number, name, 32); Log_Write("%d: %s", i, name); - } //end for -} //end of the function BotDumpGoalStack + } // end for +} // end of the function BotDumpGoalStack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotPushGoal(int goalstate, bot_goal_t *goal) -{ +void BotPushGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - if (gs->goalstacktop >= MAX_GOALSTACK-1) - { + if (!gs) + return; + if (gs->goalstacktop >= MAX_GOALSTACK - 1) { botimport.Print(PRT_ERROR, "goal heap overflow\n"); BotDumpGoalStack(goalstate); return; - } //end if + } // end if gs->goalstacktop++; Com_Memcpy(&gs->goalstack[gs->goalstacktop], goal, sizeof(bot_goal_t)); -} //end of the function BotPushGoal +} // end of the function BotPushGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotPopGoal(int goalstate) -{ +void BotPopGoal(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - if (gs->goalstacktop > 0) gs->goalstacktop--; -} //end of the function BotPopGoal + if (!gs) + return; + if (gs->goalstacktop > 0) + gs->goalstacktop--; +} // end of the function BotPopGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotEmptyGoalStack(int goalstate) -{ +void BotEmptyGoalStack(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; + if (!gs) + return; gs->goalstacktop = 0; -} //end of the function BotEmptyGoalStack +} // end of the function BotEmptyGoalStack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetTopGoal(int goalstate, bot_goal_t *goal) -{ +int BotGetTopGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return qfalse; - if (!gs->goalstacktop) return qfalse; + if (!gs) + return qfalse; + if (!gs->goalstacktop) + return qfalse; Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop], sizeof(bot_goal_t)); return qtrue; -} //end of the function BotGetTopGoal +} // end of the function BotGetTopGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetSecondGoal(int goalstate, bot_goal_t *goal) -{ +int BotGetSecondGoal(int goalstate, bot_goal_t *goal) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return qfalse; - if (gs->goalstacktop <= 1) return qfalse; - Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop-1], sizeof(bot_goal_t)); + if (!gs) + return qfalse; + if (gs->goalstacktop <= 1) + return qfalse; + Com_Memcpy(goal, &gs->goalstack[gs->goalstacktop - 1], sizeof(bot_goal_t)); return qtrue; -} //end of the function BotGetSecondGoal +} // end of the function BotGetSecondGoal //=========================================================================== // pops a new long term goal on the goal stack in the goalstate // @@ -1286,8 +1189,7 @@ int BotGetSecondGoal(int goalstate, bot_goal_t *goal) // Returns: - // Changes Globals: - //=========================================================================== -int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) -{ +int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) { int areanum, t, weightnum; float weight, bestweight, avoidtime; iteminfo_t *iteminfo; @@ -1301,51 +1203,47 @@ int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelfla return qfalse; if (!gs->itemweightconfig) return qfalse; - //get the area the bot is in + // get the area the bot is in areanum = BotReachabilityArea(origin, gs->client); - //if the bot is in solid or if the area the bot is in has no reachability links - if (!areanum || !AAS_AreaReachability(areanum)) - { - //use the last valid area the bot was in + // if the bot is in solid or if the area the bot is in has no reachability links + if (!areanum || !AAS_AreaReachability(areanum)) { + // use the last valid area the bot was in areanum = gs->lastreachabilityarea; - } //end if - //remember the last area with reachabilities the bot was in + } // end if + // remember the last area with reachabilities the bot was in gs->lastreachabilityarea = areanum; - //if still in solid + // if still in solid if (!areanum) return qfalse; - //the item configuration + // the item configuration ic = itemconfig; if (!itemconfig) return qfalse; - //best weight and item so far + // best weight and item so far bestweight = 0; bestitem = NULL; Com_Memset(&goal, 0, sizeof(bot_goal_t)); - //go through the items in the level - for (li = levelitems; li; li = li->next) - { + // go through the items in the level + for (li = levelitems; li; li = li->next) { if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; - } - else if (g_gametype >= GT_TEAM) { + } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; - } - else { + } else { if (li->flags & IFL_NOTFREE) continue; } if (li->flags & IFL_NOTBOT) continue; - //if the item is not in a possible goal area + // if the item is not in a possible goal area if (!li->goalareanum) continue; - //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) + // FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) if (!li->entitynum && !(li->flags & IFL_ROAM)) continue; - //get the fuzzy weight function for this item + // get the fuzzy weight function for this item iteminfo = &ic->iteminfo[li->iteminfo]; weightnum = gs->itemweightindex[iteminfo->number]; if (weightnum < 0) @@ -1355,40 +1253,37 @@ int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelfla weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum); #else weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum); -#endif //UNDECIDEDFUZZY +#endif // UNDECIDEDFUZZY #ifdef DROPPEDWEIGHT - //HACK: to make dropped items more attractive + // HACK: to make dropped items more attractive if (li->timeout) weight += droppedweight->value; -#endif //DROPPEDWEIGHT - //use weight scale for item_botroam - if (li->flags & IFL_ROAM) weight *= li->weight; +#endif // DROPPEDWEIGHT + // use weight scale for item_botroam + if (li->flags & IFL_ROAM) + weight *= li->weight; // - if (weight > 0) - { - //get the travel time towards the goal area + if (weight > 0) { + // get the travel time towards the goal area t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags); - //if the goal is reachable - if (t > 0) - { - //if this item won't respawn before we get there + // if the goal is reachable + if (t > 0) { + // if this item won't respawn before we get there avoidtime = BotAvoidGoalTime(goalstate, li->number); if (avoidtime - t * 0.009 > 0) continue; // - weight /= (float) t * TRAVELTIME_SCALE; + weight /= (float)t * TRAVELTIME_SCALE; // - if (weight > bestweight) - { + if (weight > bestweight) { bestweight = weight; bestitem = li; - } //end if - } //end if - } //end if - } //end for - //if no goal item found - if (!bestitem) - { + } // end if + } // end if + } // end if + } // end for + // if no goal item found + if (!bestitem) { /* //if not in lava or slime if (!AAS_AreaLava(areanum) && !AAS_AreaSlime(areanum)) @@ -1412,8 +1307,8 @@ int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelfla } //end if */ return qfalse; - } //end if - //create a bot goal for this item + } // end if + // create a bot goal for this item iteminfo = &ic->iteminfo[bestitem->iteminfo]; VectorCopy(bestitem->goalorigin, goal.origin); VectorCopy(iteminfo->mins, goal.mins); @@ -1427,35 +1322,31 @@ int BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelfla if (bestitem->flags & IFL_ROAM) goal.flags |= GFL_ROAM; goal.iteminfo = bestitem->iteminfo; - //if it's a dropped item - if (bestitem->timeout) - { + // if it's a dropped item + if (bestitem->timeout) { avoidtime = AVOID_DROPPED_TIME; - } //end if - else - { + } // end if + else { avoidtime = iteminfo->respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; if (avoidtime < AVOID_MINIMUM_TIME) avoidtime = AVOID_MINIMUM_TIME; - } //end else - //add the chosen goal to the goals to avoid for a while + } // end else + // add the chosen goal to the goals to avoid for a while BotAddToAvoidGoals(gs, bestitem->number, avoidtime); - //push the goal on the stack + // push the goal on the stack BotPushGoal(goalstate, &goal); // return qtrue; -} //end of the function BotChooseLTGItem +} // end of the function BotChooseLTGItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, - bot_goal_t *ltg, float maxtime) -{ +int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, bot_goal_t *ltg, float maxtime) { int areanum, t, weightnum, ltg_time; float weight, bestweight, avoidtime; iteminfo_t *iteminfo; @@ -1469,108 +1360,102 @@ int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelfla return qfalse; if (!gs->itemweightconfig) return qfalse; - //get the area the bot is in + // get the area the bot is in areanum = BotReachabilityArea(origin, gs->client); - //if the bot is in solid or if the area the bot is in has no reachability links - if (!areanum || !AAS_AreaReachability(areanum)) - { - //use the last valid area the bot was in + // if the bot is in solid or if the area the bot is in has no reachability links + if (!areanum || !AAS_AreaReachability(areanum)) { + // use the last valid area the bot was in areanum = gs->lastreachabilityarea; - } //end if - //remember the last area with reachabilities the bot was in + } // end if + // remember the last area with reachabilities the bot was in gs->lastreachabilityarea = areanum; - //if still in solid + // if still in solid if (!areanum) return qfalse; // - if (ltg) ltg_time = AAS_AreaTravelTimeToGoalArea(areanum, origin, ltg->areanum, travelflags); - else ltg_time = 99999; - //the item configuration + if (ltg) + ltg_time = AAS_AreaTravelTimeToGoalArea(areanum, origin, ltg->areanum, travelflags); + else + ltg_time = 99999; + // the item configuration ic = itemconfig; if (!itemconfig) return qfalse; - //best weight and item so far + // best weight and item so far bestweight = 0; bestitem = NULL; Com_Memset(&goal, 0, sizeof(bot_goal_t)); - //go through the items in the level - for (li = levelitems; li; li = li->next) - { + // go through the items in the level + for (li = levelitems; li; li = li->next) { if (g_gametype == GT_SINGLE_PLAYER) { if (li->flags & IFL_NOTSINGLE) continue; - } - else if (g_gametype >= GT_TEAM) { + } else if (g_gametype >= GT_TEAM) { if (li->flags & IFL_NOTTEAM) continue; - } - else { + } else { if (li->flags & IFL_NOTFREE) continue; } if (li->flags & IFL_NOTBOT) continue; - //if the item is in a possible goal area + // if the item is in a possible goal area if (!li->goalareanum) continue; - //FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) + // FIXME: is this a good thing? added this for items that never spawned into the game (f.i. CTF flags in obelisk) if (!li->entitynum && !(li->flags & IFL_ROAM)) continue; - //get the fuzzy weight function for this item + // get the fuzzy weight function for this item iteminfo = &ic->iteminfo[li->iteminfo]; weightnum = gs->itemweightindex[iteminfo->number]; if (weightnum < 0) continue; - // + // #ifdef UNDECIDEDFUZZY weight = FuzzyWeightUndecided(inventory, gs->itemweightconfig, weightnum); #else weight = FuzzyWeight(inventory, gs->itemweightconfig, weightnum); -#endif //UNDECIDEDFUZZY +#endif // UNDECIDEDFUZZY #ifdef DROPPEDWEIGHT - //HACK: to make dropped items more attractive + // HACK: to make dropped items more attractive if (li->timeout) weight += droppedweight->value; -#endif //DROPPEDWEIGHT - //use weight scale for item_botroam - if (li->flags & IFL_ROAM) weight *= li->weight; +#endif // DROPPEDWEIGHT + // use weight scale for item_botroam + if (li->flags & IFL_ROAM) + weight *= li->weight; // - if (weight > 0) - { - //get the travel time towards the goal area + if (weight > 0) { + // get the travel time towards the goal area t = AAS_AreaTravelTimeToGoalArea(areanum, origin, li->goalareanum, travelflags); - //if the goal is reachable - if (t > 0 && t < maxtime) - { - //if this item won't respawn before we get there + // if the goal is reachable + if (t > 0 && t < maxtime) { + // if this item won't respawn before we get there avoidtime = BotAvoidGoalTime(goalstate, li->number); if (avoidtime - t * 0.009 > 0) continue; // - weight /= (float) t * TRAVELTIME_SCALE; + weight /= (float)t * TRAVELTIME_SCALE; // - if (weight > bestweight) - { + if (weight > bestweight) { t = 0; - if (ltg && !li->timeout) - { - //get the travel time from the goal to the long term goal + if (ltg && !li->timeout) { + // get the travel time from the goal to the long term goal t = AAS_AreaTravelTimeToGoalArea(li->goalareanum, li->goalorigin, ltg->areanum, travelflags); - } //end if - //if the travel back is possible and doesn't take too long - if (t <= ltg_time) - { + } // end if + // if the travel back is possible and doesn't take too long + if (t <= ltg_time) { bestweight = weight; bestitem = li; - } //end if - } //end if - } //end if - } //end if - } //end for - //if no goal item found + } // end if + } // end if + } // end if + } // end if + } // end for + // if no goal item found if (!bestitem) return qfalse; - //create a bot goal for this item + // create a bot goal for this item iteminfo = &ic->iteminfo[bestitem->iteminfo]; VectorCopy(bestitem->goalorigin, goal.origin); VectorCopy(iteminfo->mins, goal.mins); @@ -1584,34 +1469,31 @@ int BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelfla if (bestitem->flags & IFL_ROAM) goal.flags |= GFL_ROAM; goal.iteminfo = bestitem->iteminfo; - //if it's a dropped item - if (bestitem->timeout) - { + // if it's a dropped item + if (bestitem->timeout) { avoidtime = AVOID_DROPPED_TIME; - } //end if - else - { + } // end if + else { avoidtime = iteminfo->respawntime; if (!avoidtime) avoidtime = AVOID_DEFAULT_TIME; if (avoidtime < AVOID_MINIMUM_TIME) avoidtime = AVOID_MINIMUM_TIME; - } //end else - //add the chosen goal to the goals to avoid for a while + } // end else + // add the chosen goal to the goals to avoid for a while BotAddToAvoidGoals(gs, bestitem->number, avoidtime); - //push the goal on the stack + // push the goal on the stack BotPushGoal(goalstate, &goal); // return qtrue; -} //end of the function BotChooseNBGItem +} // end of the function BotChooseNBGItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotTouchingGoal(vec3_t origin, bot_goal_t *goal) -{ +int BotTouchingGoal(vec3_t origin, bot_goal_t *goal) { int i; vec3_t boxmins, boxmaxs; vec3_t absmins, absmaxs; @@ -1623,192 +1505,186 @@ int BotTouchingGoal(vec3_t origin, bot_goal_t *goal) VectorSubtract(goal->maxs, boxmins, absmaxs); VectorAdd(absmins, goal->origin, absmins); VectorAdd(absmaxs, goal->origin, absmaxs); - //make the box a little smaller for safety + // make the box a little smaller for safety VectorSubtract(absmaxs, safety_maxs, absmaxs); VectorSubtract(absmins, safety_mins, absmins); - for (i = 0; i < 3; i++) - { - if (origin[i] < absmins[i] || origin[i] > absmaxs[i]) return qfalse; - } //end for + for (i = 0; i < 3; i++) { + if (origin[i] < absmins[i] || origin[i] > absmaxs[i]) + return qfalse; + } // end for return qtrue; -} //end of the function BotTouchingGoal +} // end of the function BotTouchingGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal) -{ +int BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, bot_goal_t *goal) { aas_entityinfo_t entinfo; bsp_trace_t trace; vec3_t middle; - if (!(goal->flags & GFL_ITEM)) return qfalse; + if (!(goal->flags & GFL_ITEM)) + return qfalse; // VectorAdd(goal->mins, goal->mins, middle); VectorScale(middle, 0.5, middle); VectorAdd(goal->origin, middle, middle); // trace = AAS_Trace(eye, NULL, NULL, middle, viewer, CONTENTS_SOLID); - //if the goal middle point is visible - if (trace.fraction >= 1) - { - //the goal entity number doesn't have to be valid - //just assume it's valid + // if the goal middle point is visible + if (trace.fraction >= 1) { + // the goal entity number doesn't have to be valid + // just assume it's valid if (goal->entitynum <= 0) return qfalse; // - //if the entity data isn't valid + // if the entity data isn't valid AAS_EntityInfo(goal->entitynum, &entinfo); - //NOTE: for some wacko reason entities are sometimes - // not updated - //if (!entinfo.valid) return qtrue; + // NOTE: for some wacko reason entities are sometimes + // not updated + // if (!entinfo.valid) return qtrue; if (entinfo.ltime < AAS_Time() - 0.5) return qtrue; - } //end if + } // end if return qfalse; -} //end of the function BotItemGoalInVisButNotVisible +} // end of the function BotItemGoalInVisButNotVisible //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetGoalState(int goalstate) -{ +void BotResetGoalState(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; + if (!gs) + return; Com_Memset(gs->goalstack, 0, MAX_GOALSTACK * sizeof(bot_goal_t)); gs->goalstacktop = 0; BotResetAvoidGoals(goalstate); -} //end of the function BotResetGoalState +} // end of the function BotResetGoalState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadItemWeights(int goalstate, char *filename) -{ +int BotLoadItemWeights(int goalstate, char *filename) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return BLERR_CANNOTLOADITEMWEIGHTS; - //load the weight configuration + if (!gs) + return BLERR_CANNOTLOADITEMWEIGHTS; + // load the weight configuration gs->itemweightconfig = ReadWeightConfig(filename); - if (!gs->itemweightconfig) - { + if (!gs->itemweightconfig) { botimport.Print(PRT_FATAL, "couldn't load weights\n"); return BLERR_CANNOTLOADITEMWEIGHTS; - } //end if - //if there's no item configuration - if (!itemconfig) return BLERR_CANNOTLOADITEMWEIGHTS; - //create the item weight index + } // end if + // if there's no item configuration + if (!itemconfig) + return BLERR_CANNOTLOADITEMWEIGHTS; + // create the item weight index gs->itemweightindex = ItemWeightIndex(gs->itemweightconfig, itemconfig); - //everything went ok + // everything went ok return BLERR_NOERROR; -} //end of the function BotLoadItemWeights +} // end of the function BotLoadItemWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeItemWeights(int goalstate) -{ +void BotFreeItemWeights(int goalstate) { bot_goalstate_t *gs; gs = BotGoalStateFromHandle(goalstate); - if (!gs) return; - if (gs->itemweightconfig) FreeWeightConfig(gs->itemweightconfig); - if (gs->itemweightindex) FreeMemory(gs->itemweightindex); -} //end of the function BotFreeItemWeights + if (!gs) + return; + if (gs->itemweightconfig) + FreeWeightConfig(gs->itemweightconfig); + if (gs->itemweightindex) + FreeMemory(gs->itemweightindex); +} // end of the function BotFreeItemWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotAllocGoalState(int client) -{ +int BotAllocGoalState(int client) { int i; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (!botgoalstates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (!botgoalstates[i]) { botgoalstates[i] = (struct bot_goalstate_s *)GetClearedMemory(sizeof(bot_goalstate_t)); botgoalstates[i]->client = client; return i; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotAllocGoalState +} // end of the function BotAllocGoalState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeGoalState(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +void BotFreeGoalState(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "goal state handle %d out of range\n", handle); return; - } //end if - if (!botgoalstates[handle]) - { + } // end if + if (!botgoalstates[handle]) { botimport.Print(PRT_FATAL, "invalid goal state handle %d\n", handle); return; - } //end if + } // end if BotFreeItemWeights(handle); FreeMemory(botgoalstates[handle]); botgoalstates[handle] = NULL; -} //end of the function BotFreeGoalState +} // end of the function BotFreeGoalState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotSetupGoalAI(void) -{ +int BotSetupGoalAI(void) { char *filename; - //check if teamplay is on + // check if teamplay is on g_gametype = LibVarValue("g_gametype", "0"); - //item configuration file + // item configuration file filename = LibVarString("itemconfig", "items.c"); - //load the item configuration + // load the item configuration itemconfig = LoadItemConfig(filename); - if (!itemconfig) - { + if (!itemconfig) { botimport.Print(PRT_FATAL, "couldn't load item config\n"); return BLERR_CANNOTLOADITEMCONFIG; - } //end if + } // end if // droppedweight = LibVar("droppedweight", "1000"); - //everything went ok + // everything went ok return BLERR_NOERROR; -} //end of the function BotSetupGoalAI +} // end of the function BotSetupGoalAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownGoalAI(void) -{ +void BotShutdownGoalAI(void) { int i; - if (itemconfig) FreeMemory(itemconfig); + if (itemconfig) + FreeMemory(itemconfig); itemconfig = NULL; - if (levelitemheap) FreeMemory(levelitemheap); + if (levelitemheap) + FreeMemory(levelitemheap); levelitemheap = NULL; freelevelitems = NULL; levelitems = NULL; @@ -1816,11 +1692,9 @@ void BotShutdownGoalAI(void) BotFreeInfoEntities(); - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (botgoalstates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (botgoalstates[i]) { BotFreeGoalState(i); - } //end if - } //end for -} //end of the function BotShutdownGoalAI + } // end if + } // end for +} // end of the function BotShutdownGoalAI diff --git a/codemp/botlib/be_ai_move.cpp b/codemp/botlib/be_ai_move.cpp index 8f24960cf9..2fd356f8ac 100644 --- a/codemp/botlib/be_ai_move.cpp +++ b/codemp/botlib/be_ai_move.cpp @@ -51,62 +51,60 @@ along with this program; if not, see . #include "be_ai_goal.h" #include "be_ai_move.h" - //#define DEBUG_AI_MOVE //#define DEBUG_ELEVATOR //#define DEBUG_GRAPPLE // bk001204 - redundant bot_avoidspot_t, see ../game/be_ai_move.h -//movement state -//NOTE: the moveflags MFL_ONGROUND, MFL_TELEPORTED, MFL_WATERJUMP and +// movement state +// NOTE: the moveflags MFL_ONGROUND, MFL_TELEPORTED, MFL_WATERJUMP and // MFL_GRAPPLEPULL must be set outside the movement code -typedef struct bot_movestate_s -{ - //input vars (all set outside the movement code) - vec3_t origin; //origin of the bot - vec3_t velocity; //velocity of the bot - vec3_t viewoffset; //view offset - int entitynum; //entity number of the bot - int client; //client number of the bot - float thinktime; //time the bot thinks - int presencetype; //presencetype of the bot - vec3_t viewangles; //view angles of the bot - //state vars - int areanum; //area the bot is in - int lastareanum; //last area the bot was in - int lastgoalareanum; //last goal area number - int lastreachnum; //last reachability number - vec3_t lastorigin; //origin previous cycle - int reachareanum; //area number of the reachabilty - int moveflags; //movement flags - int jumpreach; //set when jumped - float grapplevisible_time; //last time the grapple was visible - float lastgrappledist; //last distance to the grapple end - float reachability_time; //time to use current reachability - int avoidreach[MAX_AVOIDREACH]; //reachabilities to avoid - float avoidreachtimes[MAX_AVOIDREACH]; //times to avoid the reachabilities - int avoidreachtries[MAX_AVOIDREACH]; //number of tries before avoiding - // - bot_avoidspot_t avoidspots[MAX_AVOIDSPOTS]; //spots to avoid +typedef struct bot_movestate_s { + // input vars (all set outside the movement code) + vec3_t origin; // origin of the bot + vec3_t velocity; // velocity of the bot + vec3_t viewoffset; // view offset + int entitynum; // entity number of the bot + int client; // client number of the bot + float thinktime; // time the bot thinks + int presencetype; // presencetype of the bot + vec3_t viewangles; // view angles of the bot + // state vars + int areanum; // area the bot is in + int lastareanum; // last area the bot was in + int lastgoalareanum; // last goal area number + int lastreachnum; // last reachability number + vec3_t lastorigin; // origin previous cycle + int reachareanum; // area number of the reachabilty + int moveflags; // movement flags + int jumpreach; // set when jumped + float grapplevisible_time; // last time the grapple was visible + float lastgrappledist; // last distance to the grapple end + float reachability_time; // time to use current reachability + int avoidreach[MAX_AVOIDREACH]; // reachabilities to avoid + float avoidreachtimes[MAX_AVOIDREACH]; // times to avoid the reachabilities + int avoidreachtries[MAX_AVOIDREACH]; // number of tries before avoiding + // + bot_avoidspot_t avoidspots[MAX_AVOIDSPOTS]; // spots to avoid int numavoidspots; } bot_movestate_t; -//used to avoid reachability links for some time after being used +// used to avoid reachability links for some time after being used #define AVOIDREACH -#define AVOIDREACH_TIME 6 //avoid links for 6 seconds after use -#define AVOIDREACH_TRIES 4 -//prediction times -#define PREDICTIONTIME_JUMP 3 //in seconds -#define PREDICTIONTIME_MOVE 2 //in seconds -//weapon indexes for weapon jumping -#define WEAPONINDEX_ROCKET_LAUNCHER 5 -#define WEAPONINDEX_BFG 9 - -#define MODELTYPE_FUNC_PLAT 1 -#define MODELTYPE_FUNC_BOB 2 -#define MODELTYPE_FUNC_DOOR 3 -#define MODELTYPE_FUNC_STATIC 4 +#define AVOIDREACH_TIME 6 // avoid links for 6 seconds after use +#define AVOIDREACH_TRIES 4 +// prediction times +#define PREDICTIONTIME_JUMP 3 // in seconds +#define PREDICTIONTIME_MOVE 2 // in seconds +// weapon indexes for weapon jumping +#define WEAPONINDEX_ROCKET_LAUNCHER 5 +#define WEAPONINDEX_BFG 9 + +#define MODELTYPE_FUNC_PLAT 1 +#define MODELTYPE_FUNC_BOB 2 +#define MODELTYPE_FUNC_DOOR 3 +#define MODELTYPE_FUNC_STATIC 4 libvar_t *sv_maxstep; libvar_t *sv_maxbarrier; @@ -118,10 +116,10 @@ libvar_t *entitytypemissile; libvar_t *offhandgrapple; libvar_t *cmd_grappleoff; libvar_t *cmd_grappleon; -//type of model, func_plat or func_bobbing +// type of model, func_plat or func_bobbing int modeltypes[MAX_MODELS]; -bot_movestate_t *botmovestates[MAX_CLIENTS+1]; +bot_movestate_t *botmovestates[MAX_CLIENTS + 1]; //======================================================================== // @@ -129,73 +127,64 @@ bot_movestate_t *botmovestates[MAX_CLIENTS+1]; // Returns: - // Changes Globals: - //======================================================================== -int BotAllocMoveState(void) -{ +int BotAllocMoveState(void) { int i; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (!botmovestates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (!botmovestates[i]) { botmovestates[i] = (struct bot_movestate_s *)GetClearedMemory(sizeof(bot_movestate_t)); return i; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotAllocMoveState +} // end of the function BotAllocMoveState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeMoveState(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +void BotFreeMoveState(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle); return; - } //end if - if (!botmovestates[handle]) - { + } // end if + if (!botmovestates[handle]) { botimport.Print(PRT_FATAL, "invalid move state %d\n", handle); return; - } //end if + } // end if FreeMemory(botmovestates[handle]); botmovestates[handle] = NULL; -} //end of the function BotFreeMoveState +} // end of the function BotFreeMoveState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -bot_movestate_t *BotMoveStateFromHandle(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +bot_movestate_t *BotMoveStateFromHandle(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle); return NULL; - } //end if - if (!botmovestates[handle]) - { + } // end if + if (!botmovestates[handle]) { botimport.Print(PRT_FATAL, "invalid move state %d\n", handle); return NULL; - } //end if + } // end if return botmovestates[handle]; -} //end of the function BotMoveStateFromHandle +} // end of the function BotMoveStateFromHandle //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotInitMoveState(int handle, bot_initmove_t *initmove) -{ +void BotInitMoveState(int handle, bot_initmove_t *initmove) { bot_movestate_t *ms; ms = BotMoveStateFromHandle(handle); - if (!ms) return; + if (!ms) + return; VectorCopy(initmove->origin, ms->origin); VectorCopy(initmove->velocity, ms->velocity); VectorCopy(initmove->viewoffset, ms->viewoffset); @@ -206,45 +195,48 @@ void BotInitMoveState(int handle, bot_initmove_t *initmove) VectorCopy(initmove->viewangles, ms->viewangles); // ms->moveflags &= ~MFL_ONGROUND; - if (initmove->or_moveflags & MFL_ONGROUND) ms->moveflags |= MFL_ONGROUND; + if (initmove->or_moveflags & MFL_ONGROUND) + ms->moveflags |= MFL_ONGROUND; ms->moveflags &= ~MFL_TELEPORTED; - if (initmove->or_moveflags & MFL_TELEPORTED) ms->moveflags |= MFL_TELEPORTED; + if (initmove->or_moveflags & MFL_TELEPORTED) + ms->moveflags |= MFL_TELEPORTED; ms->moveflags &= ~MFL_WATERJUMP; - if (initmove->or_moveflags & MFL_WATERJUMP) ms->moveflags |= MFL_WATERJUMP; + if (initmove->or_moveflags & MFL_WATERJUMP) + ms->moveflags |= MFL_WATERJUMP; ms->moveflags &= ~MFL_WALK; - if (initmove->or_moveflags & MFL_WALK) ms->moveflags |= MFL_WALK; + if (initmove->or_moveflags & MFL_WALK) + ms->moveflags |= MFL_WALK; ms->moveflags &= ~MFL_GRAPPLEPULL; - if (initmove->or_moveflags & MFL_GRAPPLEPULL) ms->moveflags |= MFL_GRAPPLEPULL; -} //end of the function BotInitMoveState + if (initmove->or_moveflags & MFL_GRAPPLEPULL) + ms->moveflags |= MFL_GRAPPLEPULL; +} // end of the function BotInitMoveState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -float AngleDiff(float ang1, float ang2) -{ +float AngleDiff(float ang1, float ang2) { float diff; diff = ang1 - ang2; - if (ang1 > ang2) - { - if (diff > 180.0) diff -= 360.0; - } //end if - else - { - if (diff < -180.0) diff += 360.0; - } //end else + if (ang1 > ang2) { + if (diff > 180.0) + diff -= 360.0; + } // end if + else { + if (diff < -180.0) + diff += 360.0; + } // end else return diff; -} //end of the function AngleDiff +} // end of the function AngleDiff //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotFuzzyPointReachabilityArea(vec3_t origin) -{ +int BotFuzzyPointReachabilityArea(vec3_t origin) { int firstareanum, j, x, y, z; int areas[10], numareas, areanum, bestareanum; float dist, bestdist; @@ -252,116 +244,106 @@ int BotFuzzyPointReachabilityArea(vec3_t origin) firstareanum = 0; areanum = AAS_PointAreaNum(origin); - if (areanum) - { + if (areanum) { firstareanum = areanum; - if (AAS_AreaReachability(areanum)) return areanum; - } //end if + if (AAS_AreaReachability(areanum)) + return areanum; + } // end if VectorCopy(origin, end); end[2] += 4; numareas = AAS_TraceAreas(origin, end, areas, points, 10); - for (j = 0; j < numareas; j++) - { - if (AAS_AreaReachability(areas[j])) return areas[j]; - } //end for + for (j = 0; j < numareas; j++) { + if (AAS_AreaReachability(areas[j])) + return areas[j]; + } // end for bestdist = 999999; bestareanum = 0; - for (z = 1; z >= -1; z -= 1) - { - for (x = 1; x >= -1; x -= 1) - { - for (y = 1; y >= -1; y -= 1) - { + for (z = 1; z >= -1; z -= 1) { + for (x = 1; x >= -1; x -= 1) { + for (y = 1; y >= -1; y -= 1) { VectorCopy(origin, end); end[0] += x * 8; end[1] += y * 8; end[2] += z * 12; numareas = AAS_TraceAreas(origin, end, areas, points, 10); - for (j = 0; j < numareas; j++) - { - if (AAS_AreaReachability(areas[j])) - { + for (j = 0; j < numareas; j++) { + if (AAS_AreaReachability(areas[j])) { VectorSubtract(points[j], origin, v); dist = VectorLength(v); - if (dist < bestdist) - { + if (dist < bestdist) { bestareanum = areas[j]; bestdist = dist; - } //end if - } //end if - if (!firstareanum) firstareanum = areas[j]; - } //end for - } //end for - } //end for - if (bestareanum) return bestareanum; - } //end for + } // end if + } // end if + if (!firstareanum) + firstareanum = areas[j]; + } // end for + } // end for + } // end for + if (bestareanum) + return bestareanum; + } // end for return firstareanum; -} //end of the function BotFuzzyPointReachabilityArea +} // end of the function BotFuzzyPointReachabilityArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotReachabilityArea(vec3_t origin, int client) -{ +int BotReachabilityArea(vec3_t origin, int client) { int modelnum, modeltype, reachnum, areanum; aas_reachability_t reach; vec3_t org, end, mins, maxs, up = {0, 0, 1}; bsp_trace_t bsptrace; aas_trace_t trace; - //check if the bot is standing on something + // check if the bot is standing on something AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, mins, maxs); VectorMA(origin, -3, up, end); - bsptrace = AAS_Trace(origin, mins, maxs, end, client, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - if (!bsptrace.startsolid && bsptrace.fraction < 1 && bsptrace.ent != ENTITYNUM_NONE) - { - //if standing on the world the bot should be in a valid area - if (bsptrace.ent == ENTITYNUM_WORLD) - { + bsptrace = AAS_Trace(origin, mins, maxs, end, client, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + if (!bsptrace.startsolid && bsptrace.fraction < 1 && bsptrace.ent != ENTITYNUM_NONE) { + // if standing on the world the bot should be in a valid area + if (bsptrace.ent == ENTITYNUM_WORLD) { return BotFuzzyPointReachabilityArea(origin); - } //end if + } // end if modelnum = AAS_EntityModelindex(bsptrace.ent); modeltype = modeltypes[modelnum]; - //if standing on a func_plat or func_bobbing then the bot is assumed to be - //in the area the reachability points to - if (modeltype == MODELTYPE_FUNC_PLAT || modeltype == MODELTYPE_FUNC_BOB) - { + // if standing on a func_plat or func_bobbing then the bot is assumed to be + // in the area the reachability points to + if (modeltype == MODELTYPE_FUNC_PLAT || modeltype == MODELTYPE_FUNC_BOB) { reachnum = AAS_NextModelReachability(0, modelnum); - if (reachnum) - { + if (reachnum) { AAS_ReachabilityFromNum(reachnum, &reach); return reach.areanum; - } //end if - } //end else if + } // end if + } // end else if - //if the bot is swimming the bot should be in a valid area - if (AAS_Swimming(origin)) - { + // if the bot is swimming the bot should be in a valid area + if (AAS_Swimming(origin)) { return BotFuzzyPointReachabilityArea(origin); - } //end if + } // end if // areanum = BotFuzzyPointReachabilityArea(origin); - //if the bot is in an area with reachabilities - if (areanum && AAS_AreaReachability(areanum)) return areanum; - //trace down till the ground is hit because the bot is standing on some other entity + // if the bot is in an area with reachabilities + if (areanum && AAS_AreaReachability(areanum)) + return areanum; + // trace down till the ground is hit because the bot is standing on some other entity VectorCopy(origin, org); VectorCopy(org, end); end[2] -= 800; trace = AAS_TraceClientBBox(org, end, PRESENCE_CROUCH, -1); - if (!trace.startsolid) - { + if (!trace.startsolid) { VectorCopy(trace.endpos, org); - } //end if + } // end if // return BotFuzzyPointReachabilityArea(org); - } //end if + } // end if // return BotFuzzyPointReachabilityArea(origin); -} //end of the function BotReachabilityArea +} // end of the function BotReachabilityArea //=========================================================================== // returns the reachability area the bot is in // @@ -444,8 +426,7 @@ int BotReachabilityArea(vec3_t origin, int testground) // Returns: - // Changes Globals: - //=========================================================================== -int BotOnMover(vec3_t origin, int entnum, aas_reachability_t *reach) -{ +int BotOnMover(vec3_t origin, int entnum, aas_reachability_t *reach) { int i, modelnum; vec3_t mins, maxs, modelorigin, org, end; vec3_t angles = {0, 0, 0}; @@ -453,87 +434,85 @@ int BotOnMover(vec3_t origin, int entnum, aas_reachability_t *reach) bsp_trace_t trace; modelnum = reach->facenum & 0x0000FFFF; - //get some bsp model info + // get some bsp model info AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL); // - if (!AAS_OriginOfMoverWithModelNum(modelnum, modelorigin)) - { + if (!AAS_OriginOfMoverWithModelNum(modelnum, modelorigin)) { botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum); return qfalse; - } //end if + } // end if // - for (i = 0; i < 2; i++) - { - if (origin[i] > modelorigin[i] + maxs[i] + 16) return qfalse; - if (origin[i] < modelorigin[i] + mins[i] - 16) return qfalse; - } //end for + for (i = 0; i < 2; i++) { + if (origin[i] > modelorigin[i] + maxs[i] + 16) + return qfalse; + if (origin[i] < modelorigin[i] + mins[i] - 16) + return qfalse; + } // end for // VectorCopy(origin, org); org[2] += 24; VectorCopy(origin, end); end[2] -= 48; // - trace = AAS_Trace(org, boxmins, boxmaxs, end, entnum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - if (!trace.startsolid && !trace.allsolid) - { - //NOTE: the reachability face number is the model number of the elevator - if (trace.ent != ENTITYNUM_NONE && AAS_EntityModelNum(trace.ent) == modelnum) - { + trace = AAS_Trace(org, boxmins, boxmaxs, end, entnum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + if (!trace.startsolid && !trace.allsolid) { + // NOTE: the reachability face number is the model number of the elevator + if (trace.ent != ENTITYNUM_NONE && AAS_EntityModelNum(trace.ent) == modelnum) { return qtrue; - } //end if - } //end if + } // end if + } // end if return qfalse; -} //end of the function BotOnMover +} // end of the function BotOnMover //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int MoverDown(aas_reachability_t *reach) -{ +int MoverDown(aas_reachability_t *reach) { int modelnum; vec3_t mins, maxs, origin; vec3_t angles = {0, 0, 0}; modelnum = reach->facenum & 0x0000FFFF; - //get some bsp model info + // get some bsp model info AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin); // - if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) - { + if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) { botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum); return qfalse; - } //end if - //if the top of the plat is below the reachability start point - if (origin[2] + maxs[2] < reach->start[2]) return qtrue; + } // end if + // if the top of the plat is below the reachability start point + if (origin[2] + maxs[2] < reach->start[2]) + return qtrue; return qfalse; -} //end of the function MoverDown +} // end of the function MoverDown //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotSetBrushModelTypes(void) -{ +void BotSetBrushModelTypes(void) { int ent, modelnum; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; Com_Memset(modeltypes, 0, MAX_MODELS * sizeof(int)); // - for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) - { - if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue; - if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) continue; - if (model[0]) modelnum = atoi(model+1); - else modelnum = 0; + for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent)) { + if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) + continue; + if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) + continue; + if (model[0]) + modelnum = atoi(model + 1); + else + modelnum = 0; - if (modelnum < 0 || modelnum >= MAX_MODELS) - { + if (modelnum < 0 || modelnum >= MAX_MODELS) { botimport.Print(PRT_MESSAGE, "entity %s model number out of range\n", classname); continue; - } //end if + } // end if if (!Q_stricmp(classname, "func_bobbing")) modeltypes[modelnum] = MODELTYPE_FUNC_BOB; @@ -543,89 +522,83 @@ void BotSetBrushModelTypes(void) modeltypes[modelnum] = MODELTYPE_FUNC_DOOR; else if (!Q_stricmp(classname, "func_static")) modeltypes[modelnum] = MODELTYPE_FUNC_STATIC; - } //end for -} //end of the function BotSetBrushModelTypes + } // end for +} // end of the function BotSetBrushModelTypes //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotOnTopOfEntity(bot_movestate_t *ms) -{ +int BotOnTopOfEntity(bot_movestate_t *ms) { vec3_t mins, maxs, end, up = {0, 0, 1}; bsp_trace_t trace; AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs); VectorMA(ms->origin, -3, up, end); - trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) ) - { + trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE)) { return trace.ent; - } //end if + } // end if return -1; -} //end of the function BotOnTopOfEntity +} // end of the function BotOnTopOfEntity //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotValidTravel(vec3_t origin, aas_reachability_t *reach, int travelflags) -{ - //if the reachability uses an unwanted travel type - if (AAS_TravelFlagForType(reach->traveltype) & ~travelflags) return qfalse; - //don't go into areas with bad travel types - if (AAS_AreaContentsTravelFlags(reach->areanum) & ~travelflags) return qfalse; +int BotValidTravel(vec3_t origin, aas_reachability_t *reach, int travelflags) { + // if the reachability uses an unwanted travel type + if (AAS_TravelFlagForType(reach->traveltype) & ~travelflags) + return qfalse; + // don't go into areas with bad travel types + if (AAS_AreaContentsTravelFlags(reach->areanum) & ~travelflags) + return qfalse; return qtrue; -} //end of the function BotValidTravel +} // end of the function BotValidTravel //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotAddToAvoidReach(bot_movestate_t *ms, int number, float avoidtime) -{ +void BotAddToAvoidReach(bot_movestate_t *ms, int number, float avoidtime) { int i; - for (i = 0; i < MAX_AVOIDREACH; i++) - { - if (ms->avoidreach[i] == number) - { - if (ms->avoidreachtimes[i] > AAS_Time()) ms->avoidreachtries[i]++; - else ms->avoidreachtries[i] = 1; + for (i = 0; i < MAX_AVOIDREACH; i++) { + if (ms->avoidreach[i] == number) { + if (ms->avoidreachtimes[i] > AAS_Time()) + ms->avoidreachtries[i]++; + else + ms->avoidreachtries[i] = 1; ms->avoidreachtimes[i] = AAS_Time() + avoidtime; return; - } //end if - } //end for - //add the reachability to the reachabilities to avoid for a while - for (i = 0; i < MAX_AVOIDREACH; i++) - { - if (ms->avoidreachtimes[i] < AAS_Time()) - { + } // end if + } // end for + // add the reachability to the reachabilities to avoid for a while + for (i = 0; i < MAX_AVOIDREACH; i++) { + if (ms->avoidreachtimes[i] < AAS_Time()) { ms->avoidreach[i] = number; ms->avoidreachtimes[i] = AAS_Time() + avoidtime; ms->avoidreachtries[i] = 1; return; - } //end if - } //end for -} //end of the function BotAddToAvoidReach + } // end if + } // end for +} // end of the function BotAddToAvoidReach //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2) -{ +float DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2) { vec3_t proj, dir; int j; AAS_ProjectPointOntoVector(p, lp1, lp2, proj); for (j = 0; j < 3; j++) - if ((proj[j] > lp1[j] && proj[j] > lp2[j]) || - (proj[j] < lp1[j] && proj[j] < lp2[j])) + if ((proj[j] > lp1[j] && proj[j] > lp2[j]) || (proj[j] < lp1[j] && proj[j] < lp2[j])) break; if (j < 3) { if (fabs(proj[j] - lp1[j]) < fabs(proj[j] - lp2[j])) @@ -636,102 +609,122 @@ float DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2) } VectorSubtract(p, proj, dir); return VectorLengthSquared(dir); -} //end of the function DistanceFromLineSquared +} // end of the function DistanceFromLineSquared //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float VectorDistanceSquared(vec3_t p1, vec3_t p2) -{ +float VectorDistanceSquared(vec3_t p1, vec3_t p2) { vec3_t dir; VectorSubtract(p2, p1, dir); return VectorLengthSquared(dir); -} //end of the function VectorDistanceSquared +} // end of the function VectorDistanceSquared //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotAvoidSpots(vec3_t origin, aas_reachability_t *reach, bot_avoidspot_t *avoidspots, int numavoidspots) -{ +int BotAvoidSpots(vec3_t origin, aas_reachability_t *reach, bot_avoidspot_t *avoidspots, int numavoidspots) { int checkbetween, i, type; float squareddist, squaredradius; - switch(reach->traveltype & TRAVELTYPE_MASK) - { - case TRAVEL_WALK: checkbetween = qtrue; break; - case TRAVEL_CROUCH: checkbetween = qtrue; break; - case TRAVEL_BARRIERJUMP: checkbetween = qtrue; break; - case TRAVEL_LADDER: checkbetween = qtrue; break; - case TRAVEL_WALKOFFLEDGE: checkbetween = qfalse; break; - case TRAVEL_JUMP: checkbetween = qfalse; break; - case TRAVEL_SWIM: checkbetween = qtrue; break; - case TRAVEL_WATERJUMP: checkbetween = qtrue; break; - case TRAVEL_TELEPORT: checkbetween = qfalse; break; - case TRAVEL_ELEVATOR: checkbetween = qfalse; break; - case TRAVEL_GRAPPLEHOOK: checkbetween = qfalse; break; - case TRAVEL_ROCKETJUMP: checkbetween = qfalse; break; - case TRAVEL_BFGJUMP: checkbetween = qfalse; break; - case TRAVEL_JUMPPAD: checkbetween = qfalse; break; - case TRAVEL_FUNCBOB: checkbetween = qfalse; break; - default: checkbetween = qtrue; break; - } //end switch + switch (reach->traveltype & TRAVELTYPE_MASK) { + case TRAVEL_WALK: + checkbetween = qtrue; + break; + case TRAVEL_CROUCH: + checkbetween = qtrue; + break; + case TRAVEL_BARRIERJUMP: + checkbetween = qtrue; + break; + case TRAVEL_LADDER: + checkbetween = qtrue; + break; + case TRAVEL_WALKOFFLEDGE: + checkbetween = qfalse; + break; + case TRAVEL_JUMP: + checkbetween = qfalse; + break; + case TRAVEL_SWIM: + checkbetween = qtrue; + break; + case TRAVEL_WATERJUMP: + checkbetween = qtrue; + break; + case TRAVEL_TELEPORT: + checkbetween = qfalse; + break; + case TRAVEL_ELEVATOR: + checkbetween = qfalse; + break; + case TRAVEL_GRAPPLEHOOK: + checkbetween = qfalse; + break; + case TRAVEL_ROCKETJUMP: + checkbetween = qfalse; + break; + case TRAVEL_BFGJUMP: + checkbetween = qfalse; + break; + case TRAVEL_JUMPPAD: + checkbetween = qfalse; + break; + case TRAVEL_FUNCBOB: + checkbetween = qfalse; + break; + default: + checkbetween = qtrue; + break; + } // end switch type = AVOID_CLEAR; - for (i = 0; i < numavoidspots; i++) - { + for (i = 0; i < numavoidspots; i++) { squaredradius = Square(avoidspots[i].radius); squareddist = DistanceFromLineSquared(avoidspots[i].origin, origin, reach->start); // if moving towards the avoid spot - if (squareddist < squaredradius && - VectorDistanceSquared(avoidspots[i].origin, origin) > squareddist) - { + if (squareddist < squaredradius && VectorDistanceSquared(avoidspots[i].origin, origin) > squareddist) { type = avoidspots[i].type; - } //end if + } // end if else if (checkbetween) { squareddist = DistanceFromLineSquared(avoidspots[i].origin, reach->start, reach->end); // if moving towards the avoid spot - if (squareddist < squaredradius && - VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist) - { + if (squareddist < squaredradius && VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist) { type = avoidspots[i].type; - } //end if - } //end if - else - { + } // end if + } // end if + else { VectorDistanceSquared(avoidspots[i].origin, reach->end); // if the reachability leads closer to the avoid spot - if (squareddist < squaredradius && - VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist) - { + if (squareddist < squaredradius && VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist) { type = avoidspots[i].type; - } //end if - } //end else + } // end if + } // end else if (type == AVOID_ALWAYS) return type; - } //end for + } // end for return type; -} //end of the function BotAvoidSpots +} // end of the function BotAvoidSpots //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) -{ +void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) { bot_movestate_t *ms; ms = BotMoveStateFromHandle(movestate); - if (!ms) return; - if (type == AVOID_CLEAR) - { + if (!ms) + return; + if (type == AVOID_CLEAR) { ms->numavoidspots = 0; return; - } //end if + } // end if if (ms->numavoidspots >= MAX_AVOIDSPOTS) return; @@ -739,113 +732,103 @@ void BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) ms->avoidspots[ms->numavoidspots].radius = radius; ms->avoidspots[ms->numavoidspots].type = type; ms->numavoidspots++; -} //end of the function BotAddAvoidSpot +} // end of the function BotAddAvoidSpot //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotGetReachabilityToGoal(vec3_t origin, int areanum, - int lastgoalareanum, int lastareanum, - int *avoidreach, float *avoidreachtimes, int *avoidreachtries, - bot_goal_t *goal, int travelflags, - struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags) -{ +int BotGetReachabilityToGoal(vec3_t origin, int areanum, int lastgoalareanum, int lastareanum, int *avoidreach, float *avoidreachtimes, int *avoidreachtries, + bot_goal_t *goal, int travelflags, struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags) { int i, t, besttime, bestreachnum, reachnum; aas_reachability_t reach; - //if not in a valid area - if (!areanum) return 0; + // if not in a valid area + if (!areanum) + return 0; // - if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goal->areanum)) - { + if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goal->areanum)) { travelflags |= TFL_DONOTENTER; - } //end if - //use the routing to find the next area to go to + } // end if + // use the routing to find the next area to go to besttime = 0; bestreachnum = 0; // - for (reachnum = AAS_NextAreaReachability(areanum, 0); reachnum; - reachnum = AAS_NextAreaReachability(areanum, reachnum)) - { + for (reachnum = AAS_NextAreaReachability(areanum, 0); reachnum; reachnum = AAS_NextAreaReachability(areanum, reachnum)) { #ifdef AVOIDREACH - //check if it isn't a reachability to avoid - for (i = 0; i < MAX_AVOIDREACH; i++) - { - if (avoidreach[i] == reachnum && avoidreachtimes[i] >= AAS_Time()) break; - } //end for - if (i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES) - { + // check if it isn't a reachability to avoid + for (i = 0; i < MAX_AVOIDREACH; i++) { + if (avoidreach[i] == reachnum && avoidreachtimes[i] >= AAS_Time()) + break; + } // end for + if (i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES) { #ifdef DEBUG - if (botDeveloper) - { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "avoiding reachability %d\n", avoidreach[i]); - } //end if -#endif //DEBUG + } // end if +#endif // DEBUG continue; - } //end if -#endif //AVOIDREACH - //get the reachability from the number + } // end if +#endif // AVOIDREACH + // get the reachability from the number AAS_ReachabilityFromNum(reachnum, &reach); - //NOTE: do not go back to the previous area if the goal didn't change - //NOTE: is this actually avoidance of local routing minima between two areas??? - if (lastgoalareanum == goal->areanum && reach.areanum == lastareanum) continue; - //if (AAS_AreaContentsTravelFlags(reach.areanum) & ~travelflags) continue; - //if the travel isn't valid - if (!BotValidTravel(origin, &reach, travelflags)) continue; - //get the travel time + // NOTE: do not go back to the previous area if the goal didn't change + // NOTE: is this actually avoidance of local routing minima between two areas??? + if (lastgoalareanum == goal->areanum && reach.areanum == lastareanum) + continue; + // if (AAS_AreaContentsTravelFlags(reach.areanum) & ~travelflags) continue; + // if the travel isn't valid + if (!BotValidTravel(origin, &reach, travelflags)) + continue; + // get the travel time t = AAS_AreaTravelTimeToGoalArea(reach.areanum, reach.end, goal->areanum, travelflags); - //if the goal area isn't reachable from the reachable area - if (!t) continue; - //if the bot should not use this reachability to avoid bad spots + // if the goal area isn't reachable from the reachable area + if (!t) + continue; + // if the bot should not use this reachability to avoid bad spots if (BotAvoidSpots(origin, &reach, avoidspots, numavoidspots)) { if (flags) { *flags |= MOVERESULT_BLOCKEDBYAVOIDSPOT; } continue; } - //add the travel time towards the area - t += reach.traveltime;// + AAS_AreaTravelTime(areanum, origin, reach.start); - //if the travel time is better than the ones already found - if (!besttime || t < besttime) - { + // add the travel time towards the area + t += reach.traveltime; // + AAS_AreaTravelTime(areanum, origin, reach.start); + // if the travel time is better than the ones already found + if (!besttime || t < besttime) { besttime = t; bestreachnum = reachnum; - } //end if - } //end for + } // end if + } // end for // return bestreachnum; -} //end of the function BotGetReachabilityToGoal +} // end of the function BotGetReachabilityToGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotAddToTarget(vec3_t start, vec3_t end, float maxdist, float *dist, vec3_t target) -{ +int BotAddToTarget(vec3_t start, vec3_t end, float maxdist, float *dist, vec3_t target) { vec3_t dir; float curdist; VectorSubtract(end, start, dir); curdist = VectorNormalize(dir); - if (*dist + curdist < maxdist) - { + if (*dist + curdist < maxdist) { VectorCopy(end, target); *dist += curdist; return qfalse; - } //end if - else - { + } // end if + else { VectorMA(start, maxdist - *dist, dir, target); *dist = maxdist; return qtrue; - } //end else -} //end of the function BotAddToTarget + } // end else +} // end of the function BotAddToTarget -int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target) -{ +int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, float lookahead, vec3_t target) { aas_reachability_t reach; int reachnum, lastareanum; bot_movestate_t *ms; @@ -853,67 +836,67 @@ int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, floa float dist; ms = BotMoveStateFromHandle(movestate); - if (!ms) return qfalse; - //if the bot has no goal or no last reachability - if (!ms->lastreachnum || !goal) return qfalse; + if (!ms) + return qfalse; + // if the bot has no goal or no last reachability + if (!ms->lastreachnum || !goal) + return qfalse; reachnum = ms->lastreachnum; VectorCopy(ms->origin, end); lastareanum = ms->lastareanum; dist = 0; - while(reachnum && dist < lookahead) - { + while (reachnum && dist < lookahead) { AAS_ReachabilityFromNum(reachnum, &reach); - if (BotAddToTarget(end, reach.start, lookahead, &dist, target)) return qtrue; - //never look beyond teleporters - if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_TELEPORT) return qtrue; - //never look beyond the weapon jump point - if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) return qtrue; - if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_BFGJUMP) return qtrue; - //don't add jump pad distances - if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_JUMPPAD && - (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR && - (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB) - { - if (BotAddToTarget(reach.start, reach.end, lookahead, &dist, target)) return qtrue; - } //end if - reachnum = BotGetReachabilityToGoal(reach.end, reach.areanum, - ms->lastgoalareanum, lastareanum, - ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries, - goal, travelflags, NULL, 0, NULL); + if (BotAddToTarget(end, reach.start, lookahead, &dist, target)) + return qtrue; + // never look beyond teleporters + if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_TELEPORT) + return qtrue; + // never look beyond the weapon jump point + if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) + return qtrue; + if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_BFGJUMP) + return qtrue; + // don't add jump pad distances + if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_JUMPPAD && (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR && + (reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB) { + if (BotAddToTarget(reach.start, reach.end, lookahead, &dist, target)) + return qtrue; + } // end if + reachnum = BotGetReachabilityToGoal(reach.end, reach.areanum, ms->lastgoalareanum, lastareanum, ms->avoidreach, ms->avoidreachtimes, + ms->avoidreachtries, goal, travelflags, NULL, 0, NULL); VectorCopy(reach.end, end); lastareanum = reach.areanum; - if (lastareanum == goal->areanum) - { + if (lastareanum == goal->areanum) { BotAddToTarget(reach.end, goal->origin, lookahead, &dist, target); return qtrue; - } //end if - } //end while + } // end if + } // end while // return qfalse; -} //end of the function BotMovementViewTarget +} // end of the function BotMovementViewTarget //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotVisible(int ent, vec3_t eye, vec3_t target) -{ +int BotVisible(int ent, vec3_t eye, vec3_t target) { bsp_trace_t trace; - trace = AAS_Trace(eye, NULL, NULL, target, ent, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - if (trace.fraction >= 1) return qtrue; + trace = AAS_Trace(eye, NULL, NULL, target, ent, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + if (trace.fraction >= 1) + return qtrue; return qfalse; -} //end of the function BotVisible +} // end of the function BotVisible //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target) -{ +int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int travelflags, vec3_t target) { aas_reachability_t reach; int reachnum, lastgoalareanum, lastareanum, i; int avoidreach[MAX_AVOIDREACH]; @@ -921,148 +904,143 @@ int BotPredictVisiblePosition(vec3_t origin, int areanum, bot_goal_t *goal, int int avoidreachtries[MAX_AVOIDREACH]; vec3_t end; - //if the bot has no goal or no last reachability - if (!goal) return qfalse; - //if the areanum is not valid - if (!areanum) return qfalse; - //if the goal areanum is not valid - if (!goal->areanum) return qfalse; + // if the bot has no goal or no last reachability + if (!goal) + return qfalse; + // if the areanum is not valid + if (!areanum) + return qfalse; + // if the goal areanum is not valid + if (!goal->areanum) + return qfalse; Com_Memset(avoidreach, 0, MAX_AVOIDREACH * sizeof(int)); lastgoalareanum = goal->areanum; lastareanum = areanum; VectorCopy(origin, end); - //only do 20 hops - for (i = 0; i < 20 && (areanum != goal->areanum); i++) - { + // only do 20 hops + for (i = 0; i < 20 && (areanum != goal->areanum); i++) { // - reachnum = BotGetReachabilityToGoal(end, areanum, - lastgoalareanum, lastareanum, - avoidreach, avoidreachtimes, avoidreachtries, - goal, travelflags, NULL, 0, NULL); - if (!reachnum) return qfalse; + reachnum = BotGetReachabilityToGoal(end, areanum, lastgoalareanum, lastareanum, avoidreach, avoidreachtimes, avoidreachtries, goal, travelflags, NULL, + 0, NULL); + if (!reachnum) + return qfalse; AAS_ReachabilityFromNum(reachnum, &reach); // - if (BotVisible(goal->entitynum, goal->origin, reach.start)) - { + if (BotVisible(goal->entitynum, goal->origin, reach.start)) { VectorCopy(reach.start, target); return qtrue; - } //end if + } // end if // - if (BotVisible(goal->entitynum, goal->origin, reach.end)) - { + if (BotVisible(goal->entitynum, goal->origin, reach.end)) { VectorCopy(reach.end, target); return qtrue; - } //end if + } // end if // - if (reach.areanum == goal->areanum) - { + if (reach.areanum == goal->areanum) { VectorCopy(reach.end, target); return qtrue; - } //end if + } // end if // lastareanum = areanum; areanum = reach.areanum; VectorCopy(reach.end, end); // - } //end while + } // end while // return qfalse; -} //end of the function BotPredictVisiblePosition +} // end of the function BotPredictVisiblePosition //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void MoverBottomCenter(aas_reachability_t *reach, vec3_t bottomcenter) -{ +void MoverBottomCenter(aas_reachability_t *reach, vec3_t bottomcenter) { int modelnum; vec3_t mins, maxs, origin, mids; vec3_t angles = {0, 0, 0}; modelnum = reach->facenum & 0x0000FFFF; - //get some bsp model info + // get some bsp model info AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin); // - if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) - { + if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) { botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum); - } //end if - //get a point just above the plat in the bottom position + } // end if + // get a point just above the plat in the bottom position VectorAdd(mins, maxs, mids); VectorMA(origin, 0.5, mids, bottomcenter); bottomcenter[2] = reach->start[2]; -} //end of the function MoverBottomCenter +} // end of the function MoverBottomCenter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float BotGapDistance(vec3_t origin, vec3_t hordir, int entnum) -{ +float BotGapDistance(vec3_t origin, vec3_t hordir, int entnum) { int dist; float startz; vec3_t start, end; aas_trace_t trace; - //do gap checking - //startz = origin[2]; - //this enables walking down stairs more fluidly + // do gap checking + // startz = origin[2]; + // this enables walking down stairs more fluidly { VectorCopy(origin, start); VectorCopy(origin, end); end[2] -= 60; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum); - if (trace.fraction >= 1) return 1; + if (trace.fraction >= 1) + return 1; startz = trace.endpos[2] + 1; } // - for (dist = 8; dist <= 100; dist += 8) - { + for (dist = 8; dist <= 100; dist += 8) { VectorMA(origin, dist, hordir, start); start[2] = startz + 24; VectorCopy(start, end); end[2] -= 48 + sv_maxbarrier->value; trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum); - //if solid is found the bot can't walk any further and fall into a gap - if (!trace.startsolid) - { - //if it is a gap - if (trace.endpos[2] < startz - sv_maxstep->value - 8) - { + // if solid is found the bot can't walk any further and fall into a gap + if (!trace.startsolid) { + // if it is a gap + if (trace.endpos[2] < startz - sv_maxstep->value - 8) { VectorCopy(trace.endpos, end); end[2] -= 20; - if (AAS_PointContents(end) & CONTENTS_WATER) break; - //if a gap is found slow down - //botimport.Print(PRT_MESSAGE, "gap at %i\n", dist); + if (AAS_PointContents(end) & CONTENTS_WATER) + break; + // if a gap is found slow down + // botimport.Print(PRT_MESSAGE, "gap at %i\n", dist); return dist; - } //end if + } // end if startz = trace.endpos[2]; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotGapDistance +} // end of the function BotGapDistance //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotCheckBarrierJump(bot_movestate_t *ms, vec3_t dir, float speed) -{ +int BotCheckBarrierJump(bot_movestate_t *ms, vec3_t dir, float speed) { vec3_t start, hordir, end; aas_trace_t trace; VectorCopy(ms->origin, end); end[2] += sv_maxbarrier->value; - //trace right up + // trace right up trace = AAS_TraceClientBBox(ms->origin, end, PRESENCE_NORMAL, ms->entitynum); - //this shouldn't happen... but we check anyway - if (trace.startsolid) return qfalse; - //if very low ceiling it isn't possible to jump up to a barrier - if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) return qfalse; + // this shouldn't happen... but we check anyway + if (trace.startsolid) + return qfalse; + // if very low ceiling it isn't possible to jump up to a barrier + if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) + return qfalse; // hordir[0] = dir[0]; hordir[1] = dir[1]; @@ -1071,273 +1049,261 @@ int BotCheckBarrierJump(bot_movestate_t *ms, vec3_t dir, float speed) VectorMA(ms->origin, ms->thinktime * speed * 0.5, hordir, end); VectorCopy(trace.endpos, start); end[2] = trace.endpos[2]; - //trace from previous trace end pos horizontally in the move direction + // trace from previous trace end pos horizontally in the move direction trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum); - //again this shouldn't happen - if (trace.startsolid) return qfalse; + // again this shouldn't happen + if (trace.startsolid) + return qfalse; // VectorCopy(trace.endpos, start); VectorCopy(trace.endpos, end); end[2] = ms->origin[2]; - //trace down from the previous trace end pos + // trace down from the previous trace end pos trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum); - //if solid - if (trace.startsolid) return qfalse; - //if no obstacle at all - if (trace.fraction >= 1.0) return qfalse; - //if less than the maximum step height - if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) return qfalse; + // if solid + if (trace.startsolid) + return qfalse; + // if no obstacle at all + if (trace.fraction >= 1.0) + return qfalse; + // if less than the maximum step height + if (trace.endpos[2] - ms->origin[2] < sv_maxstep->value) + return qfalse; // EA_Jump(ms->client); EA_Move(ms->client, hordir, speed); ms->moveflags |= MFL_BARRIERJUMP; - //there is a barrier + // there is a barrier return qtrue; -} //end of the function BotCheckBarrierJump +} // end of the function BotCheckBarrierJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotSwimInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type) -{ +int BotSwimInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type) { vec3_t normdir; VectorCopy(dir, normdir); VectorNormalize(normdir); EA_Move(ms->client, normdir, speed); return qtrue; -} //end of the function BotSwimInDirection +} // end of the function BotSwimInDirection //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotWalkInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type) -{ +int BotWalkInDirection(bot_movestate_t *ms, vec3_t dir, float speed, int type) { vec3_t hordir, cmdmove, velocity, tmpdir, origin; int presencetype, maxframes, cmdframes, stopevent; aas_clientmove_t move; float dist; - if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND; - //if the bot is on the ground - if (ms->moveflags & MFL_ONGROUND) - { - //if there is a barrier the bot can jump on - if (BotCheckBarrierJump(ms, dir, speed)) return qtrue; - //remove barrier jump flag + if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) + ms->moveflags |= MFL_ONGROUND; + // if the bot is on the ground + if (ms->moveflags & MFL_ONGROUND) { + // if there is a barrier the bot can jump on + if (BotCheckBarrierJump(ms, dir, speed)) + return qtrue; + // remove barrier jump flag ms->moveflags &= ~MFL_BARRIERJUMP; - //get the presence type for the movement - if ((type & MOVE_CROUCH) && !(type & MOVE_JUMP)) presencetype = PRESENCE_CROUCH; - else presencetype = PRESENCE_NORMAL; - //horizontal direction + // get the presence type for the movement + if ((type & MOVE_CROUCH) && !(type & MOVE_JUMP)) + presencetype = PRESENCE_CROUCH; + else + presencetype = PRESENCE_NORMAL; + // horizontal direction hordir[0] = dir[0]; hordir[1] = dir[1]; hordir[2] = 0; VectorNormalize(hordir); - //if the bot is not supposed to jump - if (!(type & MOVE_JUMP)) - { - //if there is a gap, try to jump over it - if (BotGapDistance(ms->origin, hordir, ms->entitynum) > 0) type |= MOVE_JUMP; - } //end if - //get command movement + // if the bot is not supposed to jump + if (!(type & MOVE_JUMP)) { + // if there is a gap, try to jump over it + if (BotGapDistance(ms->origin, hordir, ms->entitynum) > 0) + type |= MOVE_JUMP; + } // end if + // get command movement VectorScale(hordir, speed, cmdmove); VectorCopy(ms->velocity, velocity); // - if (type & MOVE_JUMP) - { - //botimport.Print(PRT_MESSAGE, "trying jump\n"); + if (type & MOVE_JUMP) { + // botimport.Print(PRT_MESSAGE, "trying jump\n"); cmdmove[2] = 400; maxframes = PREDICTIONTIME_JUMP / 0.1; cmdframes = 1; - stopevent = SE_HITGROUND|SE_HITGROUNDDAMAGE| - SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA; - } //end if - else - { + stopevent = SE_HITGROUND | SE_HITGROUNDDAMAGE | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA; + } // end if + else { maxframes = 2; cmdframes = 2; - stopevent = SE_HITGROUNDDAMAGE| - SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA; - } //end else - //AAS_ClearShownDebugLines(); + stopevent = SE_HITGROUNDDAMAGE | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA; + } // end else + // AAS_ClearShownDebugLines(); // VectorCopy(ms->origin, origin); origin[2] += 0.5; - AAS_PredictClientMovement(&move, ms->entitynum, origin, presencetype, qtrue, - velocity, cmdmove, cmdframes, maxframes, 0.1f, - stopevent, 0, qfalse);//qtrue); - //if prediction time wasn't enough to fully predict the movement - if (move.frames >= maxframes && (type & MOVE_JUMP)) - { - //botimport.Print(PRT_MESSAGE, "client %d: max prediction frames\n", ms->client); + AAS_PredictClientMovement(&move, ms->entitynum, origin, presencetype, qtrue, velocity, cmdmove, cmdframes, maxframes, 0.1f, stopevent, 0, + qfalse); // qtrue); + // if prediction time wasn't enough to fully predict the movement + if (move.frames >= maxframes && (type & MOVE_JUMP)) { + // botimport.Print(PRT_MESSAGE, "client %d: max prediction frames\n", ms->client); return qfalse; - } //end if - //don't enter slime or lava and don't fall from too high - if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE)) - { - //botimport.Print(PRT_MESSAGE, "client %d: would be hurt ", ms->client); - //if (move.stopevent & SE_ENTERSLIME) botimport.Print(PRT_MESSAGE, "slime\n"); - //if (move.stopevent & SE_ENTERLAVA) botimport.Print(PRT_MESSAGE, "lava\n"); - //if (move.stopevent & SE_HITGROUNDDAMAGE) botimport.Print(PRT_MESSAGE, "hitground\n"); + } // end if + // don't enter slime or lava and don't fall from too high + if (move.stopevent & (SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE)) { + // botimport.Print(PRT_MESSAGE, "client %d: would be hurt ", ms->client); + // if (move.stopevent & SE_ENTERSLIME) botimport.Print(PRT_MESSAGE, "slime\n"); + // if (move.stopevent & SE_ENTERLAVA) botimport.Print(PRT_MESSAGE, "lava\n"); + // if (move.stopevent & SE_HITGROUNDDAMAGE) botimport.Print(PRT_MESSAGE, "hitground\n"); return qfalse; - } //end if - //if ground was hit - if (move.stopevent & SE_HITGROUND) - { - //check for nearby gap + } // end if + // if ground was hit + if (move.stopevent & SE_HITGROUND) { + // check for nearby gap VectorNormalize2(move.velocity, tmpdir); dist = BotGapDistance(move.endpos, tmpdir, ms->entitynum); - if (dist > 0) return qfalse; + if (dist > 0) + return qfalse; // dist = BotGapDistance(move.endpos, hordir, ms->entitynum); - if (dist > 0) return qfalse; - } //end if - //get horizontal movement + if (dist > 0) + return qfalse; + } // end if + // get horizontal movement tmpdir[0] = move.endpos[0] - ms->origin[0]; tmpdir[1] = move.endpos[1] - ms->origin[1]; tmpdir[2] = 0; // - //AAS_DrawCross(move.endpos, 4, LINECOLOR_BLUE); - //the bot is blocked by something - if (VectorLength(tmpdir) < speed * ms->thinktime * 0.5) return qfalse; - //perform the movement - if (type & MOVE_JUMP) EA_Jump(ms->client); - if (type & MOVE_CROUCH) EA_Crouch(ms->client); + // AAS_DrawCross(move.endpos, 4, LINECOLOR_BLUE); + // the bot is blocked by something + if (VectorLength(tmpdir) < speed * ms->thinktime * 0.5) + return qfalse; + // perform the movement + if (type & MOVE_JUMP) + EA_Jump(ms->client); + if (type & MOVE_CROUCH) + EA_Crouch(ms->client); EA_Move(ms->client, hordir, speed); - //movement was succesfull + // movement was succesfull return qtrue; - } //end if - else - { - if (ms->moveflags & MFL_BARRIERJUMP) - { - //if near the top or going down - if (ms->velocity[2] < 50) - { + } // end if + else { + if (ms->moveflags & MFL_BARRIERJUMP) { + // if near the top or going down + if (ms->velocity[2] < 50) { EA_Move(ms->client, dir, speed); - } //end if - } //end if - //FIXME: do air control to avoid hazards + } // end if + } // end if + // FIXME: do air control to avoid hazards return qtrue; - } //end else -} //end of the function BotWalkInDirection + } // end else +} // end of the function BotWalkInDirection //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) -{ +int BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) { bot_movestate_t *ms; ms = BotMoveStateFromHandle(movestate); - if (!ms) return qfalse; - //if swimming - if (AAS_Swimming(ms->origin)) - { + if (!ms) + return qfalse; + // if swimming + if (AAS_Swimming(ms->origin)) { return BotSwimInDirection(ms, dir, speed, type); - } //end if - else - { + } // end if + else { return BotWalkInDirection(ms, dir, speed, type); - } //end else -} //end of the function BotMoveInDirection + } // end else +} // end of the function BotMoveInDirection //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Intersection(vec2_t p1, vec2_t p2, vec2_t p3, vec2_t p4, vec2_t out) -{ - float x1, dx1, dy1, x2, dx2, dy2, d; - - dx1 = p2[0] - p1[0]; - dy1 = p2[1] - p1[1]; - dx2 = p4[0] - p3[0]; - dy2 = p4[1] - p3[1]; - - d = dy1 * dx2 - dx1 * dy2; - if (d != 0) - { - x1 = p1[1] * dx1 - p1[0] * dy1; - x2 = p3[1] * dx2 - p3[0] * dy2; - out[0] = (int) ((dx1 * x2 - dx2 * x1) / d); - out[1] = (int) ((dy1 * x2 - dy2 * x1) / d); +int Intersection(vec2_t p1, vec2_t p2, vec2_t p3, vec2_t p4, vec2_t out) { + float x1, dx1, dy1, x2, dx2, dy2, d; + + dx1 = p2[0] - p1[0]; + dy1 = p2[1] - p1[1]; + dx2 = p4[0] - p3[0]; + dy2 = p4[1] - p3[1]; + + d = dy1 * dx2 - dx1 * dy2; + if (d != 0) { + x1 = p1[1] * dx1 - p1[0] * dy1; + x2 = p3[1] * dx2 - p3[0] * dy2; + out[0] = (int)((dx1 * x2 - dx2 * x1) / d); + out[1] = (int)((dy1 * x2 - dy2 * x1) / d); return qtrue; - } //end if - else - { - return qfalse; - } //end else -} //end of the function Intersection + } // end if + else { + return qfalse; + } // end else +} // end of the function Intersection //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotCheckBlocked(bot_movestate_t *ms, vec3_t dir, int checkbottom, bot_moveresult_t *result) -{ +void BotCheckBlocked(bot_movestate_t *ms, vec3_t dir, int checkbottom, bot_moveresult_t *result) { vec3_t mins, maxs, end, up = {0, 0, 1}; bsp_trace_t trace; - //test for entities obstructing the bot's path + // test for entities obstructing the bot's path AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs); // - if (fabs(DotProduct(dir, up)) < 0.7) - { - mins[2] += sv_maxstep->value; //if the bot can step on - maxs[2] -= 10; //a little lower to avoid low ceiling - } //end if + if (fabs(DotProduct(dir, up)) < 0.7) { + mins[2] += sv_maxstep->value; // if the bot can step on + maxs[2] -= 10; // a little lower to avoid low ceiling + } // end if VectorMA(ms->origin, 3, dir, end); - trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY); - //if not started in solid and not hitting the world entity - if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) ) - { + trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_BODY); + // if not started in solid and not hitting the world entity + if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE)) { result->blocked = qtrue; result->blockentity = trace.ent; #ifdef DEBUG - //botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client); -#endif //DEBUG - } //end if - //if not in an area with reachability - else if (checkbottom && !AAS_AreaReachability(ms->areanum)) - { - //check if the bot is standing on something + // botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client); +#endif // DEBUG + } // end if + // if not in an area with reachability + else if (checkbottom && !AAS_AreaReachability(ms->areanum)) { + // check if the bot is standing on something AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs); VectorMA(ms->origin, -3, up, end); - trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP); - if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) ) - { + trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP); + if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE)) { result->blocked = qtrue; result->blockentity = trace.ent; result->flags |= MOVERESULT_ONTOPOFOBSTACLE; #ifdef DEBUG - //botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client); -#endif //DEBUG - } //end if - } //end else -} //end of the function BotCheckBlocked + // botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client); +#endif // DEBUG + } // end if + } // end else +} // end of the function BotCheckBlocked //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach) { float dist, speed; vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //first walk straight to the reachability start + // first walk straight to the reachability start hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; hordir[2] = 0; @@ -1345,52 +1311,52 @@ bot_moveresult_t BotTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach) // BotCheckBlocked(ms, hordir, qtrue, &result); // - if (dist < 10) - { - //walk straight to the reachability end + if (dist < 10) { + // walk straight to the reachability end hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; dist = VectorNormalize(hordir); - } //end if - //if going towards a crouch area - if (!(AAS_AreaPresenceType(reach->areanum) & PRESENCE_NORMAL)) - { - //if pretty close to the reachable area - if (dist < 20) EA_Crouch(ms->client); - } //end if + } // end if + // if going towards a crouch area + if (!(AAS_AreaPresenceType(reach->areanum) & PRESENCE_NORMAL)) { + // if pretty close to the reachable area + if (dist < 20) + EA_Crouch(ms->client); + } // end if // dist = BotGapDistance(ms->origin, hordir, ms->entitynum); // - if (ms->moveflags & MFL_WALK) - { - if (dist > 0) speed = 200 - (180 - 1 * dist); - else speed = 200; + if (ms->moveflags & MFL_WALK) { + if (dist > 0) + speed = 200 - (180 - 1 * dist); + else + speed = 200; EA_Walk(ms->client); - } //end if - else - { - if (dist > 0) speed = 400 - (360 - 2 * dist); - else speed = 400; - } //end else - //elemantary action move in direction + } // end if + else { + if (dist > 0) + speed = 400 - (360 - 2 * dist); + else + speed = 400; + } // end else + // elemantary action move in direction EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_Walk +} // end of the function BotTravel_Walk //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; float dist, speed; - bot_moveresult_t_cleared( result ); - //if not on the ground and changed areas... don't walk back!! + bot_moveresult_t_cleared(result); + // if not on the ground and changed areas... don't walk back!! //(doesn't seem to help) /* ms->areanum = BotFuzzyPointReachabilityArea(ms->origin); @@ -1401,97 +1367,93 @@ bot_moveresult_t BotFinishTravel_Walk(bot_movestate_t *ms, aas_reachability_t *r #endif //DEBUG return result; } //end if*/ - //go straight to the reachability end + // go straight to the reachability end hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; dist = VectorNormalize(hordir); // - if (dist > 100) dist = 100; + if (dist > 100) + dist = 100; speed = 400 - (400 - 3 * dist); // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotFinishTravel_Walk +} // end of the function BotFinishTravel_Walk //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Crouch(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Crouch(bot_movestate_t *ms, aas_reachability_t *reach) { float speed; vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); // speed = 400; - //walk straight to reachability end + // walk straight to reachability end hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); // BotCheckBlocked(ms, hordir, qtrue, &result); - //elemantary actions + // elemantary actions EA_Crouch(ms->client); EA_Move(ms->client, hordir, speed); // VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_Crouch +} // end of the function BotTravel_Crouch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach) { float dist, speed; vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //walk straight to reachability start + // walk straight to reachability start hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; hordir[2] = 0; dist = VectorNormalize(hordir); // BotCheckBlocked(ms, hordir, qtrue, &result); - //if pretty close to the barrier - if (dist < 9) - { + // if pretty close to the barrier + if (dist < 9) { EA_Jump(ms->client); - } //end if - else - { - if (dist > 60) dist = 60; + } // end if + else { + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); EA_Move(ms->client, hordir, speed); - } //end else + } // end else VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_BarrierJump +} // end of the function BotTravel_BarrierJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //if near the top or going down - if (ms->velocity[2] < 250) - { + // if near the top or going down + if (ms->velocity[2] < 250) { hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; @@ -1500,27 +1462,26 @@ bot_moveresult_t BotFinishTravel_BarrierJump(bot_movestate_t *ms, aas_reachabili // EA_Move(ms->client, hordir, 400); VectorCopy(hordir, result.movedir); - } //end if + } // end if // return result; -} //end of the function BotFinishTravel_BarrierJump +} // end of the function BotFinishTravel_BarrierJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Swim(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Swim(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //swim straight to reachability end + // swim straight to reachability end VectorSubtract(reach->start, ms->origin, dir); VectorNormalize(dir); // BotCheckBlocked(ms, dir, qtrue, &result); - //elemantary actions + // elemantary actions EA_Move(ms->client, dir, 400); // VectorCopy(dir, result.movedir); @@ -1528,184 +1489,175 @@ bot_moveresult_t BotTravel_Swim(bot_movestate_t *ms, aas_reachability_t *reach) result.flags |= MOVERESULT_SWIMVIEW; // return result; -} //end of the function BotTravel_Swim +} // end of the function BotTravel_Swim //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir, hordir; float dist; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //swim straight to reachability end + // swim straight to reachability end VectorSubtract(reach->end, ms->origin, dir); VectorCopy(dir, hordir); hordir[2] = 0; dir[2] += 15 + Q_flrand(-1.0f, 1.0f) * 40; - //botimport.Print(PRT_MESSAGE, "BotTravel_WaterJump: dir[2] = %f\n", dir[2]); + // botimport.Print(PRT_MESSAGE, "BotTravel_WaterJump: dir[2] = %f\n", dir[2]); VectorNormalize(dir); dist = VectorNormalize(hordir); - //elemantary actions - //EA_Move(ms->client, dir, 400); + // elemantary actions + // EA_Move(ms->client, dir, 400); EA_MoveForward(ms->client); - //move up if close to the actual out of water jump spot - if (dist < 40) EA_MoveUp(ms->client); - //set the ideal view angles + // move up if close to the actual out of water jump spot + if (dist < 40) + EA_MoveUp(ms->client); + // set the ideal view angles Vector2Angles(dir, result.ideal_viewangles); result.flags |= MOVERESULT_MOVEMENTVIEW; // VectorCopy(dir, result.movedir); // return result; -} //end of the function BotTravel_WaterJump +} // end of the function BotTravel_WaterJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir, pnt; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //botimport.Print(PRT_MESSAGE, "BotFinishTravel_WaterJump\n"); - //if waterjumping there's nothing to do - if (ms->moveflags & MFL_WATERJUMP) return result; - //if not touching any water anymore don't do anything - //otherwise the bot sometimes keeps jumping? + // botimport.Print(PRT_MESSAGE, "BotFinishTravel_WaterJump\n"); + // if waterjumping there's nothing to do + if (ms->moveflags & MFL_WATERJUMP) + return result; + // if not touching any water anymore don't do anything + // otherwise the bot sometimes keeps jumping? VectorCopy(ms->origin, pnt); - pnt[2] -= 32; //extra for q2dm4 near red armor/mega health - if (!(AAS_PointContents(pnt) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) return result; - //swim straight to reachability end + pnt[2] -= 32; // extra for q2dm4 near red armor/mega health + if (!(AAS_PointContents(pnt) & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER))) + return result; + // swim straight to reachability end VectorSubtract(reach->end, ms->origin, dir); dir[0] += Q_flrand(-1.0f, 1.0f) * 10; dir[1] += Q_flrand(-1.0f, 1.0f) * 10; dir[2] += 70 + Q_flrand(-1.0f, 1.0f) * 10; - //elemantary actions + // elemantary actions EA_Move(ms->client, dir, 400); - //set the ideal view angles + // set the ideal view angles Vector2Angles(dir, result.ideal_viewangles); result.flags |= MOVERESULT_MOVEMENTVIEW; // VectorCopy(dir, result.movedir); // return result; -} //end of the function BotFinishTravel_WaterJump +} // end of the function BotFinishTravel_WaterJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir, dir; float dist, speed, reachhordist; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //check if the bot is blocked by anything + // check if the bot is blocked by anything VectorSubtract(reach->start, ms->origin, dir); VectorNormalize(dir); BotCheckBlocked(ms, dir, qtrue, &result); - //if the reachability start and end are practially above each other + // if the reachability start and end are practially above each other VectorSubtract(reach->end, reach->start, dir); dir[2] = 0; reachhordist = VectorLength(dir); - //walk straight to the reachability start + // walk straight to the reachability start hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; hordir[2] = 0; dist = VectorNormalize(hordir); - //if pretty close to the start focus on the reachability end - if (dist < 48) - { + // if pretty close to the start focus on the reachability end + if (dist < 48) { hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); // - if (reachhordist < 20) - { + if (reachhordist < 20) { speed = 100; - } //end if - else if (!AAS_HorizontalVelocityForJump(0, reach->start, reach->end, &speed)) - { + } // end if + else if (!AAS_HorizontalVelocityForJump(0, reach->start, reach->end, &speed)) { speed = 400; - } //end if - } //end if - else - { - if (reachhordist < 20) - { - if (dist > 64) dist = 64; + } // end if + } // end if + else { + if (reachhordist < 20) { + if (dist > 64) + dist = 64; speed = 400 - (256 - 4 * dist); - } //end if - else - { + } // end if + else { speed = 400; - } //end else - } //end else + } // end else + } // end else // BotCheckBlocked(ms, hordir, qtrue, &result); - //elemantary action + // elemantary action EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_WalkOffLedge +} // end of the function BotTravel_WalkOffLedge //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotAirControl(vec3_t origin, vec3_t velocity, vec3_t goal, vec3_t dir, float *speed) -{ +int BotAirControl(vec3_t origin, vec3_t velocity, vec3_t goal, vec3_t dir, float *speed) { vec3_t org, vel; float dist; int i; VectorCopy(origin, org); VectorScale(velocity, 0.1, vel); - for (i = 0; i < 50; i++) - { + for (i = 0; i < 50; i++) { vel[2] -= sv_gravity->value * 0.01; - //if going down and next position would be below the goal - if (vel[2] < 0 && org[2] + vel[2] < goal[2]) - { + // if going down and next position would be below the goal + if (vel[2] < 0 && org[2] + vel[2] < goal[2]) { VectorScale(vel, (goal[2] - org[2]) / vel[2], vel); VectorAdd(org, vel, org); VectorSubtract(goal, org, dir); dist = VectorNormalize(dir); - if (dist > 32) dist = 32; + if (dist > 32) + dist = 32; *speed = 400 - (400 - 13 * dist); return qtrue; - } //end if - else - { + } // end if + else { VectorAdd(org, vel, org); - } //end else - } //end for + } // end else + } // end for VectorSet(dir, 0, 0, 0); *speed = 400; return qfalse; -} //end of the function BotAirControl +} // end of the function BotAirControl //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir, hordir, end, v; float dist, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); // VectorSubtract(reach->end, ms->origin, dir); @@ -1714,23 +1666,24 @@ bot_moveresult_t BotFinishTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachabil VectorSubtract(reach->end, ms->origin, v); v[2] = 0; dist = VectorNormalize(v); - if (dist > 16) VectorMA(reach->end, 16, v, end); - else VectorCopy(reach->end, end); + if (dist > 16) + VectorMA(reach->end, 16, v, end); + else + VectorCopy(reach->end, end); // - if (!BotAirControl(ms->origin, ms->velocity, end, hordir, &speed)) - { - //go straight to the reachability end + if (!BotAirControl(ms->origin, ms->velocity, end, hordir, &speed)) { + // go straight to the reachability end VectorCopy(dir, hordir); hordir[2] = 0; // speed = 400; - } //end if + } // end if // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotFinishTravel_WalkOffLedge +} // end of the function BotFinishTravel_WalkOffLedge //=========================================================================== // // Parameter: - @@ -1858,13 +1811,12 @@ bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) return result; } //end of the function BotTravel_Jump*/ //* -bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir, dir1, dir2, start, end, runstart; -// vec3_t runstart, dir1, dir2, hordir; + // vec3_t runstart, dir1, dir2, hordir; int gapdist; float dist1, dist2, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); // AAS_JumpReachRunStart(reach, runstart); @@ -1877,14 +1829,15 @@ bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) VectorCopy(reach->start, start); start[2] += 1; VectorMA(reach->start, 80, hordir, runstart); - //check for a gap - for (gapdist = 0; gapdist < 80; gapdist += 10) - { - VectorMA(start, gapdist+10, hordir, end); + // check for a gap + for (gapdist = 0; gapdist < 80; gapdist += 10) { + VectorMA(start, gapdist + 10, hordir, end); end[2] += 1; - if (AAS_PointAreaNum(end) != ms->reachareanum) break; - } //end for - if (gapdist < 80) VectorMA(reach->start, gapdist, hordir, runstart); + if (AAS_PointAreaNum(end) != ms->reachareanum) + break; + } // end for + if (gapdist < 80) + VectorMA(reach->start, gapdist, hordir, runstart); // VectorSubtract(ms->origin, reach->start, dir1); dir1[2] = 0; @@ -1892,52 +1845,53 @@ bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) VectorSubtract(ms->origin, runstart, dir2); dir2[2] = 0; dist2 = VectorNormalize(dir2); - //if just before the reachability start - if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5) - { -// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); + // if just before the reachability start + if (DotProduct(dir1, dir2) < -0.8 || dist2 < 5) { + // botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); - //elemantary action jump - if (dist1 < 24) EA_Jump(ms->client); - else if (dist1 < 32) EA_DelayedJump(ms->client); + // elemantary action jump + if (dist1 < 24) + EA_Jump(ms->client); + else if (dist1 < 32) + EA_DelayedJump(ms->client); EA_Move(ms->client, hordir, 600); // ms->jumpreach = ms->lastreachnum; - } //end if - else - { -// botimport.Print(PRT_MESSAGE, "going towards run start point\n"); + } // end if + else { + // botimport.Print(PRT_MESSAGE, "going towards run start point\n"); hordir[0] = runstart[0] - ms->origin[0]; hordir[1] = runstart[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); // - if (dist2 > 80) dist2 = 80; + if (dist2 > 80) + dist2 = 80; speed = 400 - (400 - 5 * dist2); EA_Move(ms->client, hordir, speed); - } //end else + } // end else VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_Jump*/ +} // end of the function BotTravel_Jump*/ //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir, hordir2; float speed, dist; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //if not jumped yet - if (!ms->jumpreach) return result; - //go straight to the reachability end + // if not jumped yet + if (!ms->jumpreach) + return result; + // go straight to the reachability end hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; @@ -1948,260 +1902,261 @@ bot_moveresult_t BotFinishTravel_Jump(bot_movestate_t *ms, aas_reachability_t *r hordir2[2] = 0; VectorNormalize(hordir2); // - if (DotProduct(hordir, hordir2) < -0.5 && dist < 24) return result; - //always use max speed when traveling through the air + if (DotProduct(hordir, hordir2) < -0.5 && dist < 24) + return result; + // always use max speed when traveling through the air speed = 800; // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotFinishTravel_Jump +} // end of the function BotFinishTravel_Jump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Ladder(bot_movestate_t *ms, aas_reachability_t *reach) -{ - //float dist, speed; - vec3_t dir, viewdir;//, hordir; +bot_moveresult_t BotTravel_Ladder(bot_movestate_t *ms, aas_reachability_t *reach) { + // float dist, speed; + vec3_t dir, viewdir; //, hordir; vec3_t origin = {0, 0, 0}; -// vec3_t up = {0, 0, 1}; - bot_moveresult_t_cleared( result ); + // vec3_t up = {0, 0, 1}; + bot_moveresult_t_cleared(result); // -// if ((ms->moveflags & MFL_AGAINSTLADDER)) - //NOTE: not a good idea for ladders starting in water - // || !(ms->moveflags & MFL_ONGROUND)) + // if ((ms->moveflags & MFL_AGAINSTLADDER)) + // NOTE: not a good idea for ladders starting in water + // || !(ms->moveflags & MFL_ONGROUND)) { - //botimport.Print(PRT_MESSAGE, "against ladder or not on ground\n"); + // botimport.Print(PRT_MESSAGE, "against ladder or not on ground\n"); VectorSubtract(reach->end, ms->origin, dir); VectorNormalize(dir); - //set the ideal view angles, facing the ladder up or down + // set the ideal view angles, facing the ladder up or down viewdir[0] = dir[0]; viewdir[1] = dir[1]; viewdir[2] = 3 * dir[2]; Vector2Angles(viewdir, result.ideal_viewangles); - //elemantary action + // elemantary action EA_Move(ms->client, origin, 0); EA_MoveForward(ms->client); - //set movement view flag so the AI can see the view is focussed + // set movement view flag so the AI can see the view is focussed result.flags |= MOVERESULT_MOVEMENTVIEW; - } //end if -/* else - { - //botimport.Print(PRT_MESSAGE, "moving towards ladder\n"); - VectorSubtract(reach->end, ms->origin, dir); - //make sure the horizontal movement is large enough - VectorCopy(dir, hordir); - hordir[2] = 0; - dist = VectorNormalize(hordir); - // - dir[0] = hordir[0]; - dir[1] = hordir[1]; - if (dir[2] > 0) dir[2] = 1; - else dir[2] = -1; - if (dist > 50) dist = 50; - speed = 400 - (200 - 4 * dist); - EA_Move(ms->client, dir, speed); - } //end else*/ - //save the movement direction + } // end if + /* else + { + //botimport.Print(PRT_MESSAGE, "moving towards ladder\n"); + VectorSubtract(reach->end, ms->origin, dir); + //make sure the horizontal movement is large enough + VectorCopy(dir, hordir); + hordir[2] = 0; + dist = VectorNormalize(hordir); + // + dir[0] = hordir[0]; + dir[1] = hordir[1]; + if (dir[2] > 0) dir[2] = 1; + else dir[2] = -1; + if (dist > 50) dist = 50; + speed = 400 - (200 - 4 * dist); + EA_Move(ms->client, dir, speed); + } //end else*/ + // save the movement direction VectorCopy(dir, result.movedir); // return result; -} //end of the function BotTravel_Ladder +} // end of the function BotTravel_Ladder //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Teleport(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Teleport(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; float dist; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //if the bot is being teleported - if (ms->moveflags & MFL_TELEPORTED) return result; + // if the bot is being teleported + if (ms->moveflags & MFL_TELEPORTED) + return result; - //walk straight to center of the teleporter + // walk straight to center of the teleporter VectorSubtract(reach->start, ms->origin, hordir); - if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + hordir[2] = 0; dist = VectorNormalize(hordir); // BotCheckBlocked(ms, hordir, qtrue, &result); - if (dist < 30) EA_Move(ms->client, hordir, 200); - else EA_Move(ms->client, hordir, 400); + if (dist < 30) + EA_Move(ms->client, hordir, 200); + else + EA_Move(ms->client, hordir, 400); - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; VectorCopy(hordir, result.movedir); return result; -} //end of the function BotTravel_Teleport +} // end of the function BotTravel_Teleport //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir, dir1, dir2, hordir, bottomcenter; float dist, dist1, dist2, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //if standing on the plat - if (BotOnMover(ms->origin, ms->entitynum, reach)) - { + // if standing on the plat + if (BotOnMover(ms->origin, ms->entitynum, reach)) { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot on elevator\n"); -#endif //DEBUG_ELEVATOR - //if vertically not too far from the end point - if (fabs(ms->origin[2] - reach->end[2]) < sv_maxbarrier->value) - { +#endif // DEBUG_ELEVATOR + // if vertically not too far from the end point + if (fabs(ms->origin[2] - reach->end[2]) < sv_maxbarrier->value) { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot moving to end\n"); -#endif //DEBUG_ELEVATOR - //move to the end point +#endif // DEBUG_ELEVATOR + // move to the end point VectorSubtract(reach->end, ms->origin, hordir); hordir[2] = 0; VectorNormalize(hordir); - if (!BotCheckBarrierJump(ms, hordir, 100)) - { + if (!BotCheckBarrierJump(ms, hordir, 100)) { EA_Move(ms->client, hordir, 400); - } //end if + } // end if VectorCopy(hordir, result.movedir); - } //end else - //if not really close to the center of the elevator - else - { + } // end else + // if not really close to the center of the elevator + else { MoverBottomCenter(reach, bottomcenter); VectorSubtract(bottomcenter, ms->origin, hordir); hordir[2] = 0; dist = VectorNormalize(hordir); // - if (dist > 10) - { + if (dist > 10) { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot moving to center\n"); -#endif //DEBUG_ELEVATOR - //move to the center of the plat - if (dist > 100) dist = 100; +#endif // DEBUG_ELEVATOR + // move to the center of the plat + if (dist > 100) + dist = 100; speed = 400 - (400 - 4 * dist); // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); - } //end if - } //end else - } //end if - else - { + } // end if + } // end else + } // end if + else { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot not on elevator\n"); -#endif //DEBUG_ELEVATOR - //if very near the reachability end +#endif // DEBUG_ELEVATOR + // if very near the reachability end VectorSubtract(reach->end, ms->origin, dir); dist = VectorLength(dir); - if (dist < 64) - { - if (dist > 60) dist = 60; + if (dist < 64) { + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); // - if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50)) - { - if (speed > 5) EA_Move(ms->client, dir, speed); - } //end if + if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50)) { + if (speed > 5) + EA_Move(ms->client, dir, speed); + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - //stop using this reachability + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + // stop using this reachability ms->reachability_time = 0; return result; - } //end if - //get direction and distance to reachability start + } // end if + // get direction and distance to reachability start VectorSubtract(reach->start, ms->origin, dir1); - if (!(ms->moveflags & MFL_SWIMMING)) dir1[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + dir1[2] = 0; dist1 = VectorNormalize(dir1); - //if the elevator isn't down - if (!MoverDown(reach)) - { + // if the elevator isn't down + if (!MoverDown(reach)) { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "elevator not down\n"); -#endif //DEBUG_ELEVATOR +#endif // DEBUG_ELEVATOR dist = dist1; VectorCopy(dir1, dir); // BotCheckBlocked(ms, dir, qfalse, &result); // - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); // - if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) - { - if (speed > 5) EA_Move(ms->client, dir, speed); - } //end if + if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) { + if (speed > 5) + EA_Move(ms->client, dir, speed); + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - //this isn't a failure... just wait till the elevator comes down + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + // this isn't a failure... just wait till the elevator comes down result.type = RESULTTYPE_ELEVATORUP; result.flags |= MOVERESULT_WAITING; return result; - } //end if - //get direction and distance to elevator bottom center + } // end if + // get direction and distance to elevator bottom center MoverBottomCenter(reach, bottomcenter); VectorSubtract(bottomcenter, ms->origin, dir2); - if (!(ms->moveflags & MFL_SWIMMING)) dir2[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + dir2[2] = 0; dist2 = VectorNormalize(dir2); - //if very close to the reachability start or - //closer to the elevator center or - //between reachability start and elevator center - if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0) - { + // if very close to the reachability start or + // closer to the elevator center or + // between reachability start and elevator center + if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0) { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot moving to center\n"); -#endif //DEBUG_ELEVATOR +#endif // DEBUG_ELEVATOR dist = dist2; VectorCopy(dir2, dir); - } //end if - else //closer to the reachability start + } // end if + else // closer to the reachability start { #ifdef DEBUG_ELEVATOR botimport.Print(PRT_MESSAGE, "bot moving to start\n"); -#endif //DEBUG_ELEVATOR +#endif // DEBUG_ELEVATOR dist = dist1; VectorCopy(dir1, dir); - } //end else + } // end else // BotCheckBlocked(ms, dir, qfalse, &result); // - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 400 - (400 - 6 * dist); // - if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) - { + if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) { EA_Move(ms->client, dir, speed); - } //end if + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - } //end else + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + } // end else return result; -} //end of the function BotTravel_Elevator +} // end of the function BotTravel_Elevator //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t bottomcenter, bottomdir, topdir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); // MoverBottomCenter(reach, bottomcenter); @@ -2209,38 +2164,34 @@ bot_moveresult_t BotFinishTravel_Elevator(bot_movestate_t *ms, aas_reachability_ // VectorSubtract(reach->end, ms->origin, topdir); // - if (fabs(bottomdir[2]) < fabs(topdir[2])) - { + if (fabs(bottomdir[2]) < fabs(topdir[2])) { VectorNormalize(bottomdir); EA_Move(ms->client, bottomdir, 300); - } //end if - else - { + } // end if + else { VectorNormalize(topdir); EA_Move(ms->client, topdir, 300); - } //end else + } // end else return result; -} //end of the function BotFinishTravel_Elevator +} // end of the function BotFinishTravel_Elevator //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFuncBobStartEnd(aas_reachability_t *reach, vec3_t start, vec3_t end, vec3_t origin) -{ +void BotFuncBobStartEnd(aas_reachability_t *reach, vec3_t start, vec3_t end, vec3_t origin) { int spawnflags, modelnum; vec3_t mins, maxs, mid, angles = {0, 0, 0}; int num0, num1; modelnum = reach->facenum & 0x0000FFFF; - if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) - { + if (!AAS_OriginOfMoverWithModelNum(modelnum, origin)) { botimport.Print(PRT_MESSAGE, "BotFuncBobStartEnd: no entity with model %d\n", modelnum); VectorSet(start, 0, 0, 0); VectorSet(end, 0, 0, 0); return; - } //end if + } // end if AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL); VectorAdd(mins, maxs, mid); VectorScale(mid, 0.5, mid); @@ -2248,131 +2199,125 @@ void BotFuncBobStartEnd(aas_reachability_t *reach, vec3_t start, vec3_t end, vec VectorCopy(mid, end); spawnflags = reach->facenum >> 16; num0 = reach->edgenum >> 16; - if (num0 > 0x00007FFF) num0 |= 0xFFFF0000; + if (num0 > 0x00007FFF) + num0 |= 0xFFFF0000; num1 = reach->edgenum & 0x0000FFFF; - if (num1 > 0x00007FFF) num1 |= 0xFFFF0000; - if (spawnflags & 1) - { + if (num1 > 0x00007FFF) + num1 |= 0xFFFF0000; + if (spawnflags & 1) { start[0] = num0; end[0] = num1; // origin[0] += mid[0]; origin[1] = mid[1]; origin[2] = mid[2]; - } //end if - else if (spawnflags & 2) - { + } // end if + else if (spawnflags & 2) { start[1] = num0; end[1] = num1; // origin[0] = mid[0]; origin[1] += mid[1]; origin[2] = mid[2]; - } //end else if - else - { + } // end else if + else { start[2] = num0; end[2] = num1; // origin[0] = mid[0]; origin[1] = mid[1]; origin[2] += mid[2]; - } //end else -} //end of the function BotFuncBobStartEnd + } // end else +} // end of the function BotFuncBobStartEnd //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t dir, dir1, dir2, hordir, bottomcenter, bob_start, bob_end, bob_origin; float dist, dist1, dist2, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); // BotFuncBobStartEnd(reach, bob_start, bob_end, bob_origin); - //if standing ontop of the func_bobbing - if (BotOnMover(ms->origin, ms->entitynum, reach)) - { + // if standing ontop of the func_bobbing + if (BotOnMover(ms->origin, ms->entitynum, reach)) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot on func_bobbing\n"); #endif - //if near end point of reachability + // if near end point of reachability VectorSubtract(bob_origin, bob_end, dir); - if (VectorLength(dir) < 24) - { + if (VectorLength(dir) < 24) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot moving to reachability end\n"); #endif - //move to the end point + // move to the end point VectorSubtract(reach->end, ms->origin, hordir); hordir[2] = 0; VectorNormalize(hordir); - if (!BotCheckBarrierJump(ms, hordir, 100)) - { + if (!BotCheckBarrierJump(ms, hordir, 100)) { EA_Move(ms->client, hordir, 400); - } //end if + } // end if VectorCopy(hordir, result.movedir); - } //end else - //if not really close to the center of the elevator - else - { + } // end else + // if not really close to the center of the elevator + else { MoverBottomCenter(reach, bottomcenter); VectorSubtract(bottomcenter, ms->origin, hordir); hordir[2] = 0; dist = VectorNormalize(hordir); // - if (dist > 10) - { + if (dist > 10) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n"); #endif - //move to the center of the plat - if (dist > 100) dist = 100; + // move to the center of the plat + if (dist > 100) + dist = 100; speed = 400 - (400 - 4 * dist); // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); - } //end if - } //end else - } //end if - else - { + } // end if + } // end else + } // end if + else { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot not ontop of func_bobbing\n"); #endif - //if very near the reachability end + // if very near the reachability end VectorSubtract(reach->end, ms->origin, dir); dist = VectorLength(dir); - if (dist < 64) - { + if (dist < 64) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot moving to end\n"); #endif - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); - //if swimming or no barrier jump - if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50)) - { - if (speed > 5) EA_Move(ms->client, dir, speed); - } //end if + // if swimming or no barrier jump + if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, 50)) { + if (speed > 5) + EA_Move(ms->client, dir, speed); + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - //stop using this reachability + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + // stop using this reachability ms->reachability_time = 0; return result; - } //end if - //get direction and distance to reachability start + } // end if + // get direction and distance to reachability start VectorSubtract(reach->start, ms->origin, dir1); - if (!(ms->moveflags & MFL_SWIMMING)) dir1[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + dir1[2] = 0; dist1 = VectorNormalize(dir1); - //if func_bobbing is Not its start position + // if func_bobbing is Not its start position VectorSubtract(bob_origin, bob_start, dir); - if (VectorLength(dir) > 16) - { + if (VectorLength(dir) > 16) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "func_bobbing not at start\n"); #endif @@ -2381,71 +2326,73 @@ bot_moveresult_t BotTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t * // BotCheckBlocked(ms, dir, qfalse, &result); // - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); // - if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) - { - if (speed > 5) EA_Move(ms->client, dir, speed); - } //end if + if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) { + if (speed > 5) + EA_Move(ms->client, dir, speed); + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - //this isn't a failure... just wait till the func_bobbing arrives + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + // this isn't a failure... just wait till the func_bobbing arrives result.type = RESULTTYPE_WAITFORFUNCBOBBING; result.flags |= MOVERESULT_WAITING; return result; - } //end if - //get direction and distance to func_bob bottom center + } // end if + // get direction and distance to func_bob bottom center MoverBottomCenter(reach, bottomcenter); VectorSubtract(bottomcenter, ms->origin, dir2); - if (!(ms->moveflags & MFL_SWIMMING)) dir2[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + dir2[2] = 0; dist2 = VectorNormalize(dir2); - //if very close to the reachability start or - //closer to the elevator center or - //between reachability start and func_bobbing center - if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0) - { + // if very close to the reachability start or + // closer to the elevator center or + // between reachability start and func_bobbing center + if (dist1 < 20 || dist2 < dist1 || DotProduct(dir1, dir2) < 0) { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n"); #endif dist = dist2; VectorCopy(dir2, dir); - } //end if - else //closer to the reachability start + } // end if + else // closer to the reachability start { #ifdef DEBUG_FUNCBOB botimport.Print(PRT_MESSAGE, "bot moving to reachability start\n"); #endif dist = dist1; VectorCopy(dir1, dir); - } //end else + } // end else // BotCheckBlocked(ms, dir, qfalse, &result); // - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 400 - (400 - 6 * dist); // - if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) - { + if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, 50)) { EA_Move(ms->client, dir, speed); - } //end if + } // end if VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - } //end else + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + } // end else return result; -} //end of the function BotTravel_FuncBobbing +} // end of the function BotTravel_FuncBobbing //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t bob_origin, bob_start, bob_end, dir, hordir, bottomcenter; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); float dist, speed; // @@ -2453,40 +2400,43 @@ bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachabili // VectorSubtract(bob_origin, bob_end, dir); dist = VectorLength(dir); - //if the func_bobbing is near the end - if (dist < 16) - { + // if the func_bobbing is near the end + if (dist < 16) { VectorSubtract(reach->end, ms->origin, hordir); - if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + hordir[2] = 0; dist = VectorNormalize(hordir); // - if (dist > 60) dist = 60; + if (dist > 60) + dist = 60; speed = 360 - (360 - 6 * dist); // - if (speed > 5) EA_Move(ms->client, dir, speed); + if (speed > 5) + EA_Move(ms->client, dir, speed); VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW; - } //end if - else - { + if (ms->moveflags & MFL_SWIMMING) + result.flags |= MOVERESULT_SWIMVIEW; + } // end if + else { MoverBottomCenter(reach, bottomcenter); VectorSubtract(bottomcenter, ms->origin, hordir); - if (!(ms->moveflags & MFL_SWIMMING)) hordir[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + hordir[2] = 0; dist = VectorNormalize(hordir); // - if (dist > 5) - { - //move to the center of the plat - if (dist > 100) dist = 100; + if (dist > 5) { + // move to the center of the plat + if (dist > 100) + dist = 100; speed = 400 - (400 - 4 * dist); // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); - } //end if - } //end else + } // end if + } // end else return result; -} //end of the function BotFinishTravel_FuncBobbing +} // end of the function BotFinishTravel_FuncBobbing //=========================================================================== // 0 no valid grapple hook visible // 1 the grapple hook is still flying @@ -2496,65 +2446,57 @@ bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachabili // Returns: - // Changes Globals: - //=========================================================================== -int GrappleState(bot_movestate_t *ms, aas_reachability_t *reach) -{ +int GrappleState(bot_movestate_t *ms, aas_reachability_t *reach) { int i; aas_entityinfo_t entinfo; - //if the grapple hook is pulling + // if the grapple hook is pulling if (ms->moveflags & MFL_GRAPPLEPULL) return 2; - //check for a visible grapple missile entity - //or visible grapple entity - for (i = AAS_NextEntity(0); i; i = AAS_NextEntity(i)) - { - if (AAS_EntityType(i) == (int) entitytypemissile->value) - { + // check for a visible grapple missile entity + // or visible grapple entity + for (i = AAS_NextEntity(0); i; i = AAS_NextEntity(i)) { + if (AAS_EntityType(i) == (int)entitytypemissile->value) { AAS_EntityInfo(i, &entinfo); - if (entinfo.weapon == (int) weapindex_grapple->value) - { + if (entinfo.weapon == (int)weapindex_grapple->value) { return 1; - } //end if - } //end if - } //end for - //no valid grapple at all + } // end if + } // end if + } // end for + // no valid grapple at all return 0; -} //end of the function GrappleState +} // end of the function GrappleState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetGrapple(bot_movestate_t *ms) -{ +void BotResetGrapple(bot_movestate_t *ms) { aas_reachability_t reach; AAS_ReachabilityFromNum(ms->lastreachnum, &reach); - //if not using the grapple hook reachability anymore - if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_GRAPPLEHOOK) - { - if ((ms->moveflags & MFL_ACTIVEGRAPPLE) || ms->grapplevisible_time) - { + // if not using the grapple hook reachability anymore + if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_GRAPPLEHOOK) { + if ((ms->moveflags & MFL_ACTIVEGRAPPLE) || ms->grapplevisible_time) { if (offhandgrapple->value) EA_Command(ms->client, cmd_grappleoff->string); ms->moveflags &= ~MFL_ACTIVEGRAPPLE; ms->grapplevisible_time = 0; #ifdef DEBUG_GRAPPLE botimport.Print(PRT_MESSAGE, "reset grapple\n"); -#endif //DEBUG_GRAPPLE - } //end if - } //end if -} //end of the function BotResetGrapple +#endif // DEBUG_GRAPPLE + } // end if + } // end if +} // end of the function BotResetGrapple //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reach) -{ - bot_moveresult_t_cleared( result ); +bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reach) { + bot_moveresult_t_cleared(result); float dist, speed; vec3_t dir, viewdir, org; int state, areanum; @@ -2562,92 +2504,84 @@ bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reac #ifdef DEBUG_GRAPPLE static int debugline; - if (!debugline) debugline = botimport.DebugLineCreate(); + if (!debugline) + debugline = botimport.DebugLineCreate(); botimport.DebugLineShow(debugline, reach->start, reach->end, LINECOLOR_BLUE); -#endif //DEBUG_GRAPPLE +#endif // DEBUG_GRAPPLE // - if (ms->moveflags & MFL_GRAPPLERESET) - { + if (ms->moveflags & MFL_GRAPPLERESET) { if (offhandgrapple->value) EA_Command(ms->client, cmd_grappleoff->string); ms->moveflags &= ~MFL_ACTIVEGRAPPLE; return result; - } //end if + } // end if // - if (!(int) offhandgrapple->value) - { + if (!(int)offhandgrapple->value) { result.weapon = weapindex_grapple->value; result.flags |= MOVERESULT_MOVEMENTWEAPON; - } //end if + } // end if // - if (ms->moveflags & MFL_ACTIVEGRAPPLE) - { + if (ms->moveflags & MFL_ACTIVEGRAPPLE) { #ifdef DEBUG_GRAPPLE botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: active grapple\n"); -#endif //DEBUG_GRAPPLE - // +#endif // DEBUG_GRAPPLE + // state = GrappleState(ms, reach); // VectorSubtract(reach->end, ms->origin, dir); dir[2] = 0; dist = VectorLength(dir); - //if very close to the grapple end or the grappled is hooked and - //the bot doesn't get any closer - if (state && dist < 48) - { - if (ms->lastgrappledist - dist < 1) - { + // if very close to the grapple end or the grappled is hooked and + // the bot doesn't get any closer + if (state && dist < 48) { + if (ms->lastgrappledist - dist < 1) { #ifdef DEBUG_GRAPPLE botimport.Print(PRT_ERROR, "grapple normal end\n"); -#endif //DEBUG_GRAPPLE +#endif // DEBUG_GRAPPLE if (offhandgrapple->value) EA_Command(ms->client, cmd_grappleoff->string); ms->moveflags &= ~MFL_ACTIVEGRAPPLE; ms->moveflags |= MFL_GRAPPLERESET; - ms->reachability_time = 0; //end the reachability + ms->reachability_time = 0; // end the reachability return result; - } //end if - } //end if - //if no valid grapple at all, or the grapple hooked and the bot - //isn't moving anymore - else if (!state || (state == 2 && dist > ms->lastgrappledist - 2)) - { - if (ms->grapplevisible_time < AAS_Time() - 0.4) - { + } // end if + } // end if + // if no valid grapple at all, or the grapple hooked and the bot + // isn't moving anymore + else if (!state || (state == 2 && dist > ms->lastgrappledist - 2)) { + if (ms->grapplevisible_time < AAS_Time() - 0.4) { #ifdef DEBUG_GRAPPLE botimport.Print(PRT_ERROR, "grapple not visible\n"); -#endif //DEBUG_GRAPPLE +#endif // DEBUG_GRAPPLE if (offhandgrapple->value) EA_Command(ms->client, cmd_grappleoff->string); ms->moveflags &= ~MFL_ACTIVEGRAPPLE; ms->moveflags |= MFL_GRAPPLERESET; - ms->reachability_time = 0; //end the reachability + ms->reachability_time = 0; // end the reachability return result; - } //end if - } //end if - else - { + } // end if + } // end if + else { ms->grapplevisible_time = AAS_Time(); - } //end else + } // end else // - if (!(int) offhandgrapple->value) - { + if (!(int)offhandgrapple->value) { EA_Attack(ms->client); - } //end if - //remember the current grapple distance + } // end if + // remember the current grapple distance ms->lastgrappledist = dist; - } //end if - else - { + } // end if + else { #ifdef DEBUG_GRAPPLE botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: inactive grapple\n"); -#endif //DEBUG_GRAPPLE - // +#endif // DEBUG_GRAPPLE + // ms->grapplevisible_time = AAS_Time(); // VectorSubtract(reach->start, ms->origin, dir); - if (!(ms->moveflags & MFL_SWIMMING)) dir[2] = 0; + if (!(ms->moveflags & MFL_SWIMMING)) + dir[2] = 0; VectorAdd(ms->origin, ms->viewoffset, org); VectorSubtract(reach->end, org, viewdir); // @@ -2655,127 +2589,119 @@ bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reac Vector2Angles(viewdir, result.ideal_viewangles); result.flags |= MOVERESULT_MOVEMENTVIEW; // - if (dist < 5 && - fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 2 && - fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 2) - { + if (dist < 5 && fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 2 && + fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 2) { #ifdef DEBUG_GRAPPLE botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: activating grapple\n"); -#endif //DEBUG_GRAPPLE - //check if the grapple missile path is clear +#endif // DEBUG_GRAPPLE + // check if the grapple missile path is clear VectorAdd(ms->origin, ms->viewoffset, org); trace = AAS_Trace(org, NULL, NULL, reach->end, ms->entitynum, CONTENTS_SOLID); VectorSubtract(reach->end, trace.endpos, dir); - if (VectorLength(dir) > 16) - { + if (VectorLength(dir) > 16) { result.failure = qtrue; return result; - } //end if - //activate the grapple - if (offhandgrapple->value) - { + } // end if + // activate the grapple + if (offhandgrapple->value) { EA_Command(ms->client, cmd_grappleon->string); - } //end if - else - { + } // end if + else { EA_Attack(ms->client); - } //end else + } // end else ms->moveflags |= MFL_ACTIVEGRAPPLE; ms->lastgrappledist = 999999; - } //end if - else - { - if (dist < 70) speed = 300 - (300 - 4 * dist); - else speed = 400; + } // end if + else { + if (dist < 70) + speed = 300 - (300 - 4 * dist); + else + speed = 400; // BotCheckBlocked(ms, dir, qtrue, &result); - //elemantary action move in direction + // elemantary action move in direction EA_Move(ms->client, dir, speed); VectorCopy(dir, result.movedir); - } //end else - //if in another area before actually grappling + } // end else + // if in another area before actually grappling areanum = AAS_PointAreaNum(ms->origin); - if (areanum && areanum != ms->reachareanum) ms->reachability_time = 0; - } //end else + if (areanum && areanum != ms->reachareanum) + ms->reachability_time = 0; + } // end else return result; -} //end of the function BotTravel_Grapple +} // end of the function BotTravel_Grapple //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_RocketJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_RocketJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; float dist, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n"); + // botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n"); // hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; hordir[2] = 0; // dist = VectorNormalize(hordir); - //look in the movement direction + // look in the movement direction Vector2Angles(hordir, result.ideal_viewangles); - //look straight down + // look straight down result.ideal_viewangles[PITCH] = 90; // - if (dist < 5 && - fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 && - fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5) - { - //botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); + if (dist < 5 && fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 && fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5) { + // botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); - //elemantary action jump + // elemantary action jump EA_Jump(ms->client); EA_Attack(ms->client); EA_Move(ms->client, hordir, 800); // ms->jumpreach = ms->lastreachnum; - } //end if - else - { - if (dist > 80) dist = 80; + } // end if + else { + if (dist > 80) + dist = 80; speed = 400 - (400 - 5 * dist); EA_Move(ms->client, hordir, speed); - } //end else - //look in the movement direction + } // end else + // look in the movement direction Vector2Angles(hordir, result.ideal_viewangles); - //look straight down + // look straight down result.ideal_viewangles[PITCH] = 90; - //set the view angles directly + // set the view angles directly EA_View(ms->client, result.ideal_viewangles); - //view is important for the movment + // view is important for the movment result.flags |= MOVERESULT_MOVEMENTVIEWSET; - //select the rocket launcher - EA_SelectWeapon(ms->client, (int) weapindex_rocketlauncher->value); - //weapon is used for movement - result.weapon = (int) weapindex_rocketlauncher->value; + // select the rocket launcher + EA_SelectWeapon(ms->client, (int)weapindex_rocketlauncher->value); + // weapon is used for movement + result.weapon = (int)weapindex_rocketlauncher->value; result.flags |= MOVERESULT_MOVEMENTWEAPON; // VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_RocketJump +} // end of the function BotTravel_RocketJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_BFGJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_BFGJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; float dist, speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //botimport.Print(PRT_MESSAGE, "BotTravel_BFGJump: bah\n"); + // botimport.Print(PRT_MESSAGE, "BotTravel_BFGJump: bah\n"); // hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; @@ -2783,60 +2709,57 @@ bot_moveresult_t BotTravel_BFGJump(bot_movestate_t *ms, aas_reachability_t *reac // dist = VectorNormalize(hordir); // - if (dist < 5 && - fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 && - fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5) - { - //botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); + if (dist < 5 && fabs(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < 5 && fabs(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < 5) { + // botimport.Print(PRT_MESSAGE, "between jump start and run start point\n"); hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); - //elemantary action jump + // elemantary action jump EA_Jump(ms->client); EA_Attack(ms->client); EA_Move(ms->client, hordir, 800); // ms->jumpreach = ms->lastreachnum; - } //end if - else - { - if (dist > 80) dist = 80; + } // end if + else { + if (dist > 80) + dist = 80; speed = 400 - (400 - 5 * dist); EA_Move(ms->client, hordir, speed); - } //end else - //look in the movement direction + } // end else + // look in the movement direction Vector2Angles(hordir, result.ideal_viewangles); - //look straight down + // look straight down result.ideal_viewangles[PITCH] = 90; - //set the view angles directly + // set the view angles directly EA_View(ms->client, result.ideal_viewangles); - //view is important for the movment + // view is important for the movment result.flags |= MOVERESULT_MOVEMENTVIEWSET; - //select the rocket launcher - EA_SelectWeapon(ms->client, (int) weapindex_bfg10k->value); - //weapon is used for movement - result.weapon = (int) weapindex_bfg10k->value; + // select the rocket launcher + EA_SelectWeapon(ms->client, (int)weapindex_bfg10k->value); + // weapon is used for movement + result.weapon = (int)weapindex_bfg10k->value; result.flags |= MOVERESULT_MOVEMENTWEAPON; // VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_BFGJump +} // end of the function BotTravel_BFGJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_WeaponJump(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_WeaponJump(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; float speed; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //if not jumped yet - if (!ms->jumpreach) return result; + // if not jumped yet + if (!ms->jumpreach) + return result; /* //go straight to the reachability end hordir[0] = reach->end[0] - ms->origin[0]; @@ -2848,70 +2771,66 @@ bot_moveresult_t BotFinishTravel_WeaponJump(bot_movestate_t *ms, aas_reachabilit VectorCopy(hordir, result.movedir); */ // - if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed)) - { - //go straight to the reachability end + if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed)) { + // go straight to the reachability end VectorSubtract(reach->end, ms->origin, hordir); hordir[2] = 0; VectorNormalize(hordir); speed = 400; - } //end if + } // end if // EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotFinishTravel_WeaponJump +} // end of the function BotFinishTravel_WeaponJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach) { vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - //first walk straight to the reachability start + // first walk straight to the reachability start hordir[0] = reach->start[0] - ms->origin[0]; hordir[1] = reach->start[1] - ms->origin[1]; hordir[2] = 0; // BotCheckBlocked(ms, hordir, qtrue, &result); - //elemantary action move in direction + // elemantary action move in direction EA_Move(ms->client, hordir, 400); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotTravel_JumpPad +} // end of the function BotTravel_JumpPad //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotFinishTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach) -{ +bot_moveresult_t BotFinishTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach) { float speed; vec3_t hordir; - bot_moveresult_t_cleared( result ); + bot_moveresult_t_cleared(result); - if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed)) - { + if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed)) { hordir[0] = reach->end[0] - ms->origin[0]; hordir[1] = reach->end[1] - ms->origin[1]; hordir[2] = 0; VectorNormalize(hordir); speed = 400; - } //end if + } // end if BotCheckBlocked(ms, hordir, qtrue, &result); - //elemantary action move in direction + // elemantary action move in direction EA_Move(ms->client, hordir, speed); VectorCopy(hordir, result.movedir); // return result; -} //end of the function BotFinishTravel_JumpPad +} // end of the function BotFinishTravel_JumpPad //=========================================================================== // time before the reachability times out // @@ -2919,80 +2838,90 @@ bot_moveresult_t BotFinishTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t // Returns: - // Changes Globals: - //=========================================================================== -int BotReachabilityTime(aas_reachability_t *reach) -{ - switch(reach->traveltype & TRAVELTYPE_MASK) - { - case TRAVEL_WALK: return 5; - case TRAVEL_CROUCH: return 5; - case TRAVEL_BARRIERJUMP: return 5; - case TRAVEL_LADDER: return 6; - case TRAVEL_WALKOFFLEDGE: return 5; - case TRAVEL_JUMP: return 5; - case TRAVEL_SWIM: return 5; - case TRAVEL_WATERJUMP: return 5; - case TRAVEL_TELEPORT: return 5; - case TRAVEL_ELEVATOR: return 10; - case TRAVEL_GRAPPLEHOOK: return 8; - case TRAVEL_ROCKETJUMP: return 6; - case TRAVEL_BFGJUMP: return 6; - case TRAVEL_JUMPPAD: return 10; - case TRAVEL_FUNCBOB: return 10; - default: - { - botimport.Print(PRT_ERROR, "travel type %d not implemented yet\n", reach->traveltype); - return 8; - } //end case - } //end switch -} //end of the function BotReachabilityTime +int BotReachabilityTime(aas_reachability_t *reach) { + switch (reach->traveltype & TRAVELTYPE_MASK) { + case TRAVEL_WALK: + return 5; + case TRAVEL_CROUCH: + return 5; + case TRAVEL_BARRIERJUMP: + return 5; + case TRAVEL_LADDER: + return 6; + case TRAVEL_WALKOFFLEDGE: + return 5; + case TRAVEL_JUMP: + return 5; + case TRAVEL_SWIM: + return 5; + case TRAVEL_WATERJUMP: + return 5; + case TRAVEL_TELEPORT: + return 5; + case TRAVEL_ELEVATOR: + return 10; + case TRAVEL_GRAPPLEHOOK: + return 8; + case TRAVEL_ROCKETJUMP: + return 6; + case TRAVEL_BFGJUMP: + return 6; + case TRAVEL_JUMPPAD: + return 10; + case TRAVEL_FUNCBOB: + return 10; + default: { + botimport.Print(PRT_ERROR, "travel type %d not implemented yet\n", reach->traveltype); + return 8; + } // end case + } // end switch +} // end of the function BotReachabilityTime //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -bot_moveresult_t BotMoveInGoalArea(bot_movestate_t *ms, bot_goal_t *goal) -{ - bot_moveresult_t_cleared( result ); +bot_moveresult_t BotMoveInGoalArea(bot_movestate_t *ms, bot_goal_t *goal) { + bot_moveresult_t_cleared(result); vec3_t dir; float dist, speed; #ifdef DEBUG - //botimport.Print(PRT_MESSAGE, "%s: moving straight to goal\n", ClientName(ms->entitynum-1)); - //AAS_ClearShownDebugLines(); - //AAS_DebugLine(ms->origin, goal->origin, LINECOLOR_RED); -#endif //DEBUG - //walk straight to the goal origin + // botimport.Print(PRT_MESSAGE, "%s: moving straight to goal\n", ClientName(ms->entitynum-1)); + // AAS_ClearShownDebugLines(); + // AAS_DebugLine(ms->origin, goal->origin, LINECOLOR_RED); +#endif // DEBUG + // walk straight to the goal origin dir[0] = goal->origin[0] - ms->origin[0]; dir[1] = goal->origin[1] - ms->origin[1]; - if (ms->moveflags & MFL_SWIMMING) - { + if (ms->moveflags & MFL_SWIMMING) { dir[2] = goal->origin[2] - ms->origin[2]; result.traveltype = TRAVEL_SWIM; - } //end if - else - { + } // end if + else { dir[2] = 0; result.traveltype = TRAVEL_WALK; - } //endif + } // endif // dist = VectorNormalize(dir); - if (dist > 100) dist = 100; + if (dist > 100) + dist = 100; speed = 400 - (400 - 4 * dist); - if (speed < 10) speed = 0; + if (speed < 10) + speed = 0; // BotCheckBlocked(ms, dir, qtrue, &result); - //elemantary action move in direction + // elemantary action move in direction EA_Move(ms->client, dir, speed); VectorCopy(dir, result.movedir); // - if (ms->moveflags & MFL_SWIMMING) - { + if (ms->moveflags & MFL_SWIMMING) { Vector2Angles(dir, result.ideal_viewangles); result.flags |= MOVERESULT_SWIMVIEW; - } //end if - //if (!debugline) debugline = botimport.DebugLineCreate(); - //botimport.DebugLineShow(debugline, ms->origin, goal->origin, LINECOLOR_BLUE); + } // end if + // if (!debugline) debugline = botimport.DebugLineCreate(); + // botimport.DebugLineShow(debugline, ms->origin, goal->origin, LINECOLOR_BLUE); // ms->lastreachnum = 0; ms->lastareanum = 0; @@ -3000,21 +2929,20 @@ bot_moveresult_t BotMoveInGoalArea(bot_movestate_t *ms, bot_goal_t *goal) VectorCopy(ms->origin, ms->lastorigin); // return result; -} //end of the function BotMoveInGoalArea +} // end of the function BotMoveInGoalArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags) -{ +void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags) { int reachnum, lastreachnum, foundjumppad, ent, resultflags; aas_reachability_t reach, lastreach; bot_movestate_t *ms; - //vec3_t mins, maxs, up = {0, 0, 1}; - //bsp_trace_t trace; - //static int debugline; + // vec3_t mins, maxs, up = {0, 0, 1}; + // bsp_trace_t trace; + // static int debugline; result->failure = qfalse; result->type = 0; @@ -3025,280 +2953,235 @@ void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, in // ms = BotMoveStateFromHandle(movestate); - if (!ms) return; - //reset the grapple before testing if the bot has a valid goal - //because the bot could lose all its goals when stuck to a wall + if (!ms) + return; + // reset the grapple before testing if the bot has a valid goal + // because the bot could lose all its goals when stuck to a wall BotResetGrapple(ms); // - if (!goal) - { + if (!goal) { #ifdef DEBUG botimport.Print(PRT_MESSAGE, "client %d: movetogoal -> no goal\n", ms->client); -#endif //DEBUG +#endif // DEBUG result->failure = qtrue; return; - } //end if - //botimport.Print(PRT_MESSAGE, "numavoidreach = %d\n", ms->numavoidreach); - //remove some of the move flags - ms->moveflags &= ~(MFL_SWIMMING|MFL_AGAINSTLADDER); - //set some of the move flags - //NOTE: the MFL_ONGROUND flag is also set in the higher AI - if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND; - // - if (ms->moveflags & MFL_ONGROUND) - { + } // end if + // botimport.Print(PRT_MESSAGE, "numavoidreach = %d\n", ms->numavoidreach); + // remove some of the move flags + ms->moveflags &= ~(MFL_SWIMMING | MFL_AGAINSTLADDER); + // set some of the move flags + // NOTE: the MFL_ONGROUND flag is also set in the higher AI + if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) + ms->moveflags |= MFL_ONGROUND; + // + if (ms->moveflags & MFL_ONGROUND) { int modeltype, modelnum; ent = BotOnTopOfEntity(ms); - if (ent != -1) - { + if (ent != -1) { modelnum = AAS_EntityModelindex(ent); - if (modelnum >= 0 && modelnum < MAX_MODELS) - { + if (modelnum >= 0 && modelnum < MAX_MODELS) { modeltype = modeltypes[modelnum]; - if (modeltype == MODELTYPE_FUNC_PLAT) - { + if (modeltype == MODELTYPE_FUNC_PLAT) { AAS_ReachabilityFromNum(ms->lastreachnum, &reach); - //if the bot is Not using the elevator + // if the bot is Not using the elevator if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR || - //NOTE: the face number is the plat model number - (reach.facenum & 0x0000FFFF) != modelnum) - { + // NOTE: the face number is the plat model number + (reach.facenum & 0x0000FFFF) != modelnum) { reachnum = AAS_NextModelReachability(0, modelnum); - if (reachnum) - { - //botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_plat\n", ms->client); + if (reachnum) { + // botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_plat\n", ms->client); AAS_ReachabilityFromNum(reachnum, &reach); ms->lastreachnum = reachnum; ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach); - } //end if - else - { - if (botDeveloper) - { + } // end if + else { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "client %d: on func_plat without reachability\n", ms->client); - } //end if + } // end if result->blocked = qtrue; result->blockentity = ent; result->flags |= MOVERESULT_ONTOPOFOBSTACLE; return; - } //end else - } //end if + } // end else + } // end if result->flags |= MOVERESULT_ONTOPOF_ELEVATOR; - } //end if - else if (modeltype == MODELTYPE_FUNC_BOB) - { + } // end if + else if (modeltype == MODELTYPE_FUNC_BOB) { AAS_ReachabilityFromNum(ms->lastreachnum, &reach); - //if the bot is Not using the func bobbing + // if the bot is Not using the func bobbing if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB || - //NOTE: the face number is the func_bobbing model number - (reach.facenum & 0x0000FFFF) != modelnum) - { + // NOTE: the face number is the func_bobbing model number + (reach.facenum & 0x0000FFFF) != modelnum) { reachnum = AAS_NextModelReachability(0, modelnum); - if (reachnum) - { - //botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_bobbing\n", ms->client); + if (reachnum) { + // botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_bobbing\n", ms->client); AAS_ReachabilityFromNum(reachnum, &reach); ms->lastreachnum = reachnum; ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach); - } //end if - else - { - if (botDeveloper) - { + } // end if + else { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "client %d: on func_bobbing without reachability\n", ms->client); - } //end if + } // end if result->blocked = qtrue; result->blockentity = ent; result->flags |= MOVERESULT_ONTOPOFOBSTACLE; return; - } //end else - } //end if + } // end else + } // end if result->flags |= MOVERESULT_ONTOPOF_FUNCBOB; - } //end if - else if (modeltype == MODELTYPE_FUNC_STATIC || modeltype == MODELTYPE_FUNC_DOOR) - { + } // end if + else if (modeltype == MODELTYPE_FUNC_STATIC || modeltype == MODELTYPE_FUNC_DOOR) { // check if ontop of a door bridge ? ms->areanum = BotFuzzyPointReachabilityArea(ms->origin); // if not in a reachability area - if (!AAS_AreaReachability(ms->areanum)) - { + if (!AAS_AreaReachability(ms->areanum)) { result->blocked = qtrue; result->blockentity = ent; result->flags |= MOVERESULT_ONTOPOFOBSTACLE; return; - } //end if - } //end else if - else - { + } // end if + } // end else if + else { result->blocked = qtrue; result->blockentity = ent; result->flags |= MOVERESULT_ONTOPOFOBSTACLE; return; - } //end else - } //end if - } //end if - } //end if - //if swimming - if (AAS_Swimming(ms->origin)) ms->moveflags |= MFL_SWIMMING; - //if against a ladder - if (AAS_AgainstLadder(ms->origin)) ms->moveflags |= MFL_AGAINSTLADDER; - //if the bot is on the ground, swimming or against a ladder - if (ms->moveflags & (MFL_ONGROUND|MFL_SWIMMING|MFL_AGAINSTLADDER)) - { - //botimport.Print(PRT_MESSAGE, "%s: onground, swimming or against ladder\n", ClientName(ms->entitynum-1)); + } // end else + } // end if + } // end if + } // end if + // if swimming + if (AAS_Swimming(ms->origin)) + ms->moveflags |= MFL_SWIMMING; + // if against a ladder + if (AAS_AgainstLadder(ms->origin)) + ms->moveflags |= MFL_AGAINSTLADDER; + // if the bot is on the ground, swimming or against a ladder + if (ms->moveflags & (MFL_ONGROUND | MFL_SWIMMING | MFL_AGAINSTLADDER)) { + // botimport.Print(PRT_MESSAGE, "%s: onground, swimming or against ladder\n", ClientName(ms->entitynum-1)); // AAS_ReachabilityFromNum(ms->lastreachnum, &lastreach); - //reachability area the bot is in - //ms->areanum = BotReachabilityArea(ms->origin, ((lastreach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR)); + // reachability area the bot is in + // ms->areanum = BotReachabilityArea(ms->origin, ((lastreach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR)); ms->areanum = BotFuzzyPointReachabilityArea(ms->origin); // - if ( !ms->areanum ) - { + if (!ms->areanum) { result->failure = qtrue; result->blocked = qtrue; result->blockentity = 0; result->type = RESULTTYPE_INSOLIDAREA; return; - } //end if - //if the bot is in the goal area - if (ms->areanum == goal->areanum) - { + } // end if + // if the bot is in the goal area + if (ms->areanum == goal->areanum) { *result = BotMoveInGoalArea(ms, goal); return; - } //end if - //assume we can use the reachability from the last frame + } // end if + // assume we can use the reachability from the last frame reachnum = ms->lastreachnum; - //if there is a last reachability - if (reachnum) - { + // if there is a last reachability + if (reachnum) { AAS_ReachabilityFromNum(reachnum, &reach); - //check if the reachability is still valid - if (!(AAS_TravelFlagForType(reach.traveltype) & travelflags)) - { + // check if the reachability is still valid + if (!(AAS_TravelFlagForType(reach.traveltype) & travelflags)) { reachnum = 0; - } //end if - //special grapple hook case - else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_GRAPPLEHOOK) - { - if (ms->reachability_time < AAS_Time() || - (ms->moveflags & MFL_GRAPPLERESET)) - { + } // end if + // special grapple hook case + else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_GRAPPLEHOOK) { + if (ms->reachability_time < AAS_Time() || (ms->moveflags & MFL_GRAPPLERESET)) { reachnum = 0; - } //end if - } //end if - //special elevator case - else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR || - (reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) - { - if ((result->flags & MOVERESULT_ONTOPOF_ELEVATOR) || - (result->flags & MOVERESULT_ONTOPOF_FUNCBOB)) - { + } // end if + } // end if + // special elevator case + else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR || (reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB) { + if ((result->flags & MOVERESULT_ONTOPOF_ELEVATOR) || (result->flags & MOVERESULT_ONTOPOF_FUNCBOB)) { ms->reachability_time = AAS_Time() + 5; - } //end if - //if the bot was going for an elevator and reached the reachability area - if (ms->areanum == reach.areanum || - ms->reachability_time < AAS_Time()) - { + } // end if + // if the bot was going for an elevator and reached the reachability area + if (ms->areanum == reach.areanum || ms->reachability_time < AAS_Time()) { reachnum = 0; - } //end if - } //end if - else - { + } // end if + } // end if + else { #ifdef DEBUG - if (botDeveloper) - { - if (ms->reachability_time < AAS_Time()) - { + if (botDeveloper) { + if (ms->reachability_time < AAS_Time()) { botimport.Print(PRT_MESSAGE, "client %d: reachability timeout in ", ms->client); AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); botimport.Print(PRT_MESSAGE, "\n"); - } //end if + } // end if /* if (ms->lastareanum != ms->areanum) { botimport.Print(PRT_MESSAGE, "changed from area %d to %d\n", ms->lastareanum, ms->areanum); } //end if*/ - } //end if -#endif //DEBUG - //if the goal area changed or the reachability timed out - //or the area changed - if (ms->lastgoalareanum != goal->areanum || - ms->reachability_time < AAS_Time() || - ms->lastareanum != ms->areanum) - { + } // end if +#endif // DEBUG + // if the goal area changed or the reachability timed out + // or the area changed + if (ms->lastgoalareanum != goal->areanum || ms->reachability_time < AAS_Time() || ms->lastareanum != ms->areanum) { reachnum = 0; - //botimport.Print(PRT_MESSAGE, "area change or timeout\n"); - } //end else if - } //end else - } //end if + // botimport.Print(PRT_MESSAGE, "area change or timeout\n"); + } // end else if + } // end else + } // end if resultflags = 0; - //if the bot needs a new reachability - if (!reachnum) - { - //if the area has no reachability links - if (!AAS_AreaReachability(ms->areanum)) - { + // if the bot needs a new reachability + if (!reachnum) { + // if the area has no reachability links + if (!AAS_AreaReachability(ms->areanum)) { #ifdef DEBUG - if (botDeveloper) - { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "area %d no reachability\n", ms->areanum); - } //end if -#endif //DEBUG - } //end if - //get a new reachability leading towards the goal - reachnum = BotGetReachabilityToGoal(ms->origin, ms->areanum, - ms->lastgoalareanum, ms->lastareanum, - ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries, - goal, travelflags, - ms->avoidspots, ms->numavoidspots, &resultflags); - //the area number the reachability starts in + } // end if +#endif // DEBUG + } // end if + // get a new reachability leading towards the goal + reachnum = BotGetReachabilityToGoal(ms->origin, ms->areanum, ms->lastgoalareanum, ms->lastareanum, ms->avoidreach, ms->avoidreachtimes, + ms->avoidreachtries, goal, travelflags, ms->avoidspots, ms->numavoidspots, &resultflags); + // the area number the reachability starts in ms->reachareanum = ms->areanum; - //reset some state variables - ms->jumpreach = 0; //for TRAVEL_JUMP - ms->moveflags &= ~MFL_GRAPPLERESET; //for TRAVEL_GRAPPLEHOOK - //if there is a reachability to the goal - if (reachnum) - { + // reset some state variables + ms->jumpreach = 0; // for TRAVEL_JUMP + ms->moveflags &= ~MFL_GRAPPLERESET; // for TRAVEL_GRAPPLEHOOK + // if there is a reachability to the goal + if (reachnum) { AAS_ReachabilityFromNum(reachnum, &reach); - //set a timeout for this reachability + // set a timeout for this reachability ms->reachability_time = AAS_Time() + BotReachabilityTime(&reach); // #ifdef AVOIDREACH - //add the reachability to the reachabilities to avoid for a while + // add the reachability to the reachabilities to avoid for a while BotAddToAvoidReach(ms, reachnum, AVOIDREACH_TIME); -#endif //AVOIDREACH - } //end if +#endif // AVOIDREACH + } // end if #ifdef DEBUG - else if (botDeveloper) - { + else if (botDeveloper) { botimport.Print(PRT_MESSAGE, "goal not reachable\n"); - Com_Memset(&reach, 0, sizeof(aas_reachability_t)); //make compiler happy - } //end else - if (botDeveloper) - { - //if still going for the same goal - if (ms->lastgoalareanum == goal->areanum) - { - if (ms->lastareanum == reach.areanum) - { + Com_Memset(&reach, 0, sizeof(aas_reachability_t)); // make compiler happy + } // end else + if (botDeveloper) { + // if still going for the same goal + if (ms->lastgoalareanum == goal->areanum) { + if (ms->lastareanum == reach.areanum) { botimport.Print(PRT_MESSAGE, "same goal, going back to previous area\n"); - } //end if - } //end if - } //end if -#endif //DEBUG - } //end else + } // end if + } // end if + } // end if +#endif // DEBUG + } // end else // ms->lastreachnum = reachnum; ms->lastgoalareanum = goal->areanum; ms->lastareanum = ms->areanum; - //if the bot has a reachability - if (reachnum) - { - //get the reachability from the number + // if the bot has a reachability + if (reachnum) { + // get the reachability from the number AAS_ReachabilityFromNum(reachnum, &reach); result->traveltype = reach.traveltype; // @@ -3306,233 +3189,266 @@ void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, in AAS_ClearShownDebugLines(); AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); AAS_ShowReachability(&reach); -#endif //DEBUG_AI_MOVE - // +#endif // DEBUG_AI_MOVE + // #ifdef DEBUG - //botimport.Print(PRT_MESSAGE, "client %d: ", ms->client); - //AAS_PrintTravelType(reach.traveltype); - //botimport.Print(PRT_MESSAGE, "\n"); -#endif //DEBUG - switch(reach.traveltype & TRAVELTYPE_MASK) - { - case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break; - case TRAVEL_CROUCH: *result = BotTravel_Crouch(ms, &reach); break; - case TRAVEL_BARRIERJUMP: *result = BotTravel_BarrierJump(ms, &reach); break; - case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break; - case TRAVEL_WALKOFFLEDGE: *result = BotTravel_WalkOffLedge(ms, &reach); break; - case TRAVEL_JUMP: *result = BotTravel_Jump(ms, &reach); break; - case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break; - case TRAVEL_WATERJUMP: *result = BotTravel_WaterJump(ms, &reach); break; - case TRAVEL_TELEPORT: *result = BotTravel_Teleport(ms, &reach); break; - case TRAVEL_ELEVATOR: *result = BotTravel_Elevator(ms, &reach); break; - case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break; - case TRAVEL_ROCKETJUMP: *result = BotTravel_RocketJump(ms, &reach); break; - case TRAVEL_BFGJUMP: *result = BotTravel_BFGJump(ms, &reach); break; - case TRAVEL_JUMPPAD: *result = BotTravel_JumpPad(ms, &reach); break; - case TRAVEL_FUNCBOB: *result = BotTravel_FuncBobbing(ms, &reach); break; - default: - { - botimport.Print(PRT_FATAL, "travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK)); - break; - } //end case - } //end switch + // botimport.Print(PRT_MESSAGE, "client %d: ", ms->client); + // AAS_PrintTravelType(reach.traveltype); + // botimport.Print(PRT_MESSAGE, "\n"); +#endif // DEBUG + switch (reach.traveltype & TRAVELTYPE_MASK) { + case TRAVEL_WALK: + *result = BotTravel_Walk(ms, &reach); + break; + case TRAVEL_CROUCH: + *result = BotTravel_Crouch(ms, &reach); + break; + case TRAVEL_BARRIERJUMP: + *result = BotTravel_BarrierJump(ms, &reach); + break; + case TRAVEL_LADDER: + *result = BotTravel_Ladder(ms, &reach); + break; + case TRAVEL_WALKOFFLEDGE: + *result = BotTravel_WalkOffLedge(ms, &reach); + break; + case TRAVEL_JUMP: + *result = BotTravel_Jump(ms, &reach); + break; + case TRAVEL_SWIM: + *result = BotTravel_Swim(ms, &reach); + break; + case TRAVEL_WATERJUMP: + *result = BotTravel_WaterJump(ms, &reach); + break; + case TRAVEL_TELEPORT: + *result = BotTravel_Teleport(ms, &reach); + break; + case TRAVEL_ELEVATOR: + *result = BotTravel_Elevator(ms, &reach); + break; + case TRAVEL_GRAPPLEHOOK: + *result = BotTravel_Grapple(ms, &reach); + break; + case TRAVEL_ROCKETJUMP: + *result = BotTravel_RocketJump(ms, &reach); + break; + case TRAVEL_BFGJUMP: + *result = BotTravel_BFGJump(ms, &reach); + break; + case TRAVEL_JUMPPAD: + *result = BotTravel_JumpPad(ms, &reach); + break; + case TRAVEL_FUNCBOB: + *result = BotTravel_FuncBobbing(ms, &reach); + break; + default: { + botimport.Print(PRT_FATAL, "travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK)); + break; + } // end case + } // end switch result->traveltype = reach.traveltype; result->flags |= resultflags; - } //end if - else - { + } // end if + else { result->failure = qtrue; result->flags |= resultflags; Com_Memset(&reach, 0, sizeof(aas_reachability_t)); - } //end else + } // end else #ifdef DEBUG - if (botDeveloper) - { - if (result->failure) - { + if (botDeveloper) { + if (result->failure) { botimport.Print(PRT_MESSAGE, "client %d: movement failure in ", ms->client); AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); botimport.Print(PRT_MESSAGE, "\n"); - } //end if - } //end if -#endif //DEBUG - } //end if - else - { + } // end if + } // end if +#endif // DEBUG + } // end if + else { int i, numareas, areas[16]; vec3_t end; - //special handling of jump pads when the bot uses a jump pad without knowing it + // special handling of jump pads when the bot uses a jump pad without knowing it foundjumppad = qfalse; VectorMA(ms->origin, -2 * ms->thinktime, ms->velocity, end); numareas = AAS_TraceAreas(ms->origin, end, areas, NULL, 16); - for (i = numareas-1; i >= 0; i--) - { - if (AAS_AreaJumpPad(areas[i])) - { - //botimport.Print(PRT_MESSAGE, "client %d used a jumppad without knowing, area %d\n", ms->client, areas[i]); + for (i = numareas - 1; i >= 0; i--) { + if (AAS_AreaJumpPad(areas[i])) { + // botimport.Print(PRT_MESSAGE, "client %d used a jumppad without knowing, area %d\n", ms->client, areas[i]); foundjumppad = qtrue; - lastreachnum = BotGetReachabilityToGoal(end, areas[i], - ms->lastgoalareanum, ms->lastareanum, - ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries, - goal, TFL_JUMPPAD, ms->avoidspots, ms->numavoidspots, NULL); - if (lastreachnum) - { + lastreachnum = BotGetReachabilityToGoal(end, areas[i], ms->lastgoalareanum, ms->lastareanum, ms->avoidreach, ms->avoidreachtimes, + ms->avoidreachtries, goal, TFL_JUMPPAD, ms->avoidspots, ms->numavoidspots, NULL); + if (lastreachnum) { ms->lastreachnum = lastreachnum; ms->lastareanum = areas[i]; - //botimport.Print(PRT_MESSAGE, "found jumppad reachability\n"); + // botimport.Print(PRT_MESSAGE, "found jumppad reachability\n"); break; - } //end if - else - { - for (lastreachnum = AAS_NextAreaReachability(areas[i], 0); lastreachnum; - lastreachnum = AAS_NextAreaReachability(areas[i], lastreachnum)) - { - //get the reachability from the number + } // end if + else { + for (lastreachnum = AAS_NextAreaReachability(areas[i], 0); lastreachnum; lastreachnum = AAS_NextAreaReachability(areas[i], lastreachnum)) { + // get the reachability from the number AAS_ReachabilityFromNum(lastreachnum, &reach); - if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) - { + if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD) { ms->lastreachnum = lastreachnum; ms->lastareanum = areas[i]; - //botimport.Print(PRT_MESSAGE, "found jumppad reachability hard!!\n"); - } //end if - } //end for - if (lastreachnum) break; - } //end else - } //end if - } //end for - if (botDeveloper) - { - //if a jumppad is found with the trace but no reachability is found - if (foundjumppad && !ms->lastreachnum) - { + // botimport.Print(PRT_MESSAGE, "found jumppad reachability hard!!\n"); + } // end if + } // end for + if (lastreachnum) + break; + } // end else + } // end if + } // end for + if (botDeveloper) { + // if a jumppad is found with the trace but no reachability is found + if (foundjumppad && !ms->lastreachnum) { botimport.Print(PRT_MESSAGE, "client %d didn't find jumppad reachability\n", ms->client); - } //end if - } //end if + } // end if + } // end if // - if (ms->lastreachnum) - { - //botimport.Print(PRT_MESSAGE, "%s: NOT onground, swimming or against ladder\n", ClientName(ms->entitynum-1)); + if (ms->lastreachnum) { + // botimport.Print(PRT_MESSAGE, "%s: NOT onground, swimming or against ladder\n", ClientName(ms->entitynum-1)); AAS_ReachabilityFromNum(ms->lastreachnum, &reach); result->traveltype = reach.traveltype; #ifdef DEBUG - //botimport.Print(PRT_MESSAGE, "client %d finish: ", ms->client); - //AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); - //botimport.Print(PRT_MESSAGE, "\n"); -#endif //DEBUG - // - switch(reach.traveltype & TRAVELTYPE_MASK) - { - case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break;//BotFinishTravel_Walk(ms, &reach); break; - case TRAVEL_CROUCH: /*do nothing*/ break; - case TRAVEL_BARRIERJUMP: *result = BotFinishTravel_BarrierJump(ms, &reach); break; - case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break; - case TRAVEL_WALKOFFLEDGE: *result = BotFinishTravel_WalkOffLedge(ms, &reach); break; - case TRAVEL_JUMP: *result = BotFinishTravel_Jump(ms, &reach); break; - case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break; - case TRAVEL_WATERJUMP: *result = BotFinishTravel_WaterJump(ms, &reach); break; - case TRAVEL_TELEPORT: /*do nothing*/ break; - case TRAVEL_ELEVATOR: *result = BotFinishTravel_Elevator(ms, &reach); break; - case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break; - case TRAVEL_ROCKETJUMP: - case TRAVEL_BFGJUMP: *result = BotFinishTravel_WeaponJump(ms, &reach); break; - case TRAVEL_JUMPPAD: *result = BotFinishTravel_JumpPad(ms, &reach); break; - case TRAVEL_FUNCBOB: *result = BotFinishTravel_FuncBobbing(ms, &reach); break; - default: - { - botimport.Print(PRT_FATAL, "(last) travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK)); - break; - } //end case - } //end switch + // botimport.Print(PRT_MESSAGE, "client %d finish: ", ms->client); + // AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); + // botimport.Print(PRT_MESSAGE, "\n"); +#endif // DEBUG + // + switch (reach.traveltype & TRAVELTYPE_MASK) { + case TRAVEL_WALK: + *result = BotTravel_Walk(ms, &reach); + break; // BotFinishTravel_Walk(ms, &reach); break; + case TRAVEL_CROUCH: /*do nothing*/ + break; + case TRAVEL_BARRIERJUMP: + *result = BotFinishTravel_BarrierJump(ms, &reach); + break; + case TRAVEL_LADDER: + *result = BotTravel_Ladder(ms, &reach); + break; + case TRAVEL_WALKOFFLEDGE: + *result = BotFinishTravel_WalkOffLedge(ms, &reach); + break; + case TRAVEL_JUMP: + *result = BotFinishTravel_Jump(ms, &reach); + break; + case TRAVEL_SWIM: + *result = BotTravel_Swim(ms, &reach); + break; + case TRAVEL_WATERJUMP: + *result = BotFinishTravel_WaterJump(ms, &reach); + break; + case TRAVEL_TELEPORT: /*do nothing*/ + break; + case TRAVEL_ELEVATOR: + *result = BotFinishTravel_Elevator(ms, &reach); + break; + case TRAVEL_GRAPPLEHOOK: + *result = BotTravel_Grapple(ms, &reach); + break; + case TRAVEL_ROCKETJUMP: + case TRAVEL_BFGJUMP: + *result = BotFinishTravel_WeaponJump(ms, &reach); + break; + case TRAVEL_JUMPPAD: + *result = BotFinishTravel_JumpPad(ms, &reach); + break; + case TRAVEL_FUNCBOB: + *result = BotFinishTravel_FuncBobbing(ms, &reach); + break; + default: { + botimport.Print(PRT_FATAL, "(last) travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK)); + break; + } // end case + } // end switch result->traveltype = reach.traveltype; #ifdef DEBUG - if (botDeveloper) - { - if (result->failure) - { + if (botDeveloper) { + if (result->failure) { botimport.Print(PRT_MESSAGE, "client %d: movement failure in finish ", ms->client); AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK); botimport.Print(PRT_MESSAGE, "\n"); - } //end if - } //end if -#endif //DEBUG - } //end if - } //end else - //FIXME: is it right to do this here? - if (result->blocked) ms->reachability_time -= 10 * ms->thinktime; - //copy the last origin + } // end if + } // end if +#endif // DEBUG + } // end if + } // end else + // FIXME: is it right to do this here? + if (result->blocked) + ms->reachability_time -= 10 * ms->thinktime; + // copy the last origin VectorCopy(ms->origin, ms->lastorigin); - //return the movement result + // return the movement result return; -} //end of the function BotMoveToGoal +} // end of the function BotMoveToGoal //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetAvoidReach(int movestate) -{ +void BotResetAvoidReach(int movestate) { bot_movestate_t *ms; ms = BotMoveStateFromHandle(movestate); - if (!ms) return; + if (!ms) + return; Com_Memset(ms->avoidreach, 0, MAX_AVOIDREACH * sizeof(int)); Com_Memset(ms->avoidreachtimes, 0, MAX_AVOIDREACH * sizeof(float)); Com_Memset(ms->avoidreachtries, 0, MAX_AVOIDREACH * sizeof(int)); -} //end of the function BotResetAvoidReach +} // end of the function BotResetAvoidReach //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetLastAvoidReach(int movestate) -{ +void BotResetLastAvoidReach(int movestate) { int i, latest; float latesttime; bot_movestate_t *ms; ms = BotMoveStateFromHandle(movestate); - if (!ms) return; + if (!ms) + return; latesttime = 0; latest = 0; - for (i = 0; i < MAX_AVOIDREACH; i++) - { - if (ms->avoidreachtimes[i] > latesttime) - { + for (i = 0; i < MAX_AVOIDREACH; i++) { + if (ms->avoidreachtimes[i] > latesttime) { latesttime = ms->avoidreachtimes[i]; latest = i; - } //end if - } //end for - if (latesttime) - { + } // end if + } // end for + if (latesttime) { ms->avoidreachtimes[latest] = 0; - if (ms->avoidreachtries[latest] > 0) ms->avoidreachtries[latest]--; - } //end if -} //end of the function BotResetLastAvoidReach + if (ms->avoidreachtries[latest] > 0) + ms->avoidreachtries[latest]--; + } // end if +} // end of the function BotResetLastAvoidReach //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetMoveState(int movestate) -{ +void BotResetMoveState(int movestate) { bot_movestate_t *ms; ms = BotMoveStateFromHandle(movestate); - if (!ms) return; + if (!ms) + return; Com_Memset(ms, 0, sizeof(bot_movestate_t)); -} //end of the function BotResetMoveState +} // end of the function BotResetMoveState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotSetupMoveAI(void) -{ +int BotSetupMoveAI(void) { BotSetBrushModelTypes(); sv_maxstep = LibVar("sv_step", "18"); sv_maxbarrier = LibVar("sv_maxbarrier", "32"); @@ -3545,25 +3461,20 @@ int BotSetupMoveAI(void) cmd_grappleon = LibVar("cmd_grappleon", "grappleon"); cmd_grappleoff = LibVar("cmd_grappleoff", "grappleoff"); return BLERR_NOERROR; -} //end of the function BotSetupMoveAI +} // end of the function BotSetupMoveAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownMoveAI(void) -{ +void BotShutdownMoveAI(void) { int i; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (botmovestates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (botmovestates[i]) { FreeMemory(botmovestates[i]); botmovestates[i] = NULL; - } //end if - } //end for -} //end of the function BotShutdownMoveAI - - + } // end if + } // end for +} // end of the function BotShutdownMoveAI diff --git a/codemp/botlib/be_ai_weap.cpp b/codemp/botlib/be_ai_weap.cpp index 231f722a55..d4a254e1d1 100644 --- a/codemp/botlib/be_ai_weap.cpp +++ b/codemp/botlib/be_ai_weap.cpp @@ -47,90 +47,77 @@ along with this program; if not, see . #include "be_aas.h" #include "be_aas_funcs.h" #include "be_interface.h" -#include "be_ai_weight.h" //fuzzy weights +#include "be_ai_weight.h" //fuzzy weights #include "be_ai_weap.h" //#define DEBUG_AI_WEAP -//structure field offsets +// structure field offsets #define WEAPON_OFS(x) offsetof(weaponinfo_t, x) #define PROJECTILE_OFS(x) offsetof(projectileinfo_t, x) -//weapon definition // bk001212 - static -static fielddef_t weaponinfo_fields[] = -{ -{"number", WEAPON_OFS(number), FT_INT}, //weapon number -{"name", WEAPON_OFS(name), FT_STRING}, //name of the weapon -{"level", WEAPON_OFS(level), FT_INT}, -{"model", WEAPON_OFS(model), FT_STRING}, //model of the weapon -{"weaponindex", WEAPON_OFS(weaponindex), FT_INT}, //index of weapon in inventory -{"flags", WEAPON_OFS(flags), FT_INT}, //special flags -{"projectile", WEAPON_OFS(projectile), FT_STRING}, //projectile used by the weapon -{"numprojectiles", WEAPON_OFS(numprojectiles), FT_INT}, //number of projectiles -{"hspread", WEAPON_OFS(hspread), FT_FLOAT}, //horizontal spread of projectiles (degrees from middle) -{"vspread", WEAPON_OFS(vspread), FT_FLOAT}, //vertical spread of projectiles (degrees from middle) -{"speed", WEAPON_OFS(speed), FT_FLOAT}, //speed of the projectile (0 = instant hit) -{"acceleration", WEAPON_OFS(acceleration), FT_FLOAT}, //"acceleration" * time (in seconds) + "speed" = projectile speed -{"recoil", WEAPON_OFS(recoil), FT_FLOAT|FT_ARRAY, 3}, //amount of recoil the player gets from the weapon -{"offset", WEAPON_OFS(offset), FT_FLOAT|FT_ARRAY, 3}, //projectile start offset relative to eye and view angles -{"angleoffset", WEAPON_OFS(angleoffset), FT_FLOAT|FT_ARRAY, 3},//offset of the shoot angles relative to the view angles -{"extrazvelocity", WEAPON_OFS(extrazvelocity), FT_FLOAT},//extra z velocity the projectile gets -{"ammoamount", WEAPON_OFS(ammoamount), FT_INT}, //ammo amount used per shot -{"ammoindex", WEAPON_OFS(ammoindex), FT_INT}, //index of ammo in inventory -{"activate", WEAPON_OFS(activate), FT_FLOAT}, //time it takes to select the weapon -{"reload", WEAPON_OFS(reload), FT_FLOAT}, //time it takes to reload the weapon -{"spinup", WEAPON_OFS(spinup), FT_FLOAT}, //time it takes before first shot -{"spindown", WEAPON_OFS(spindown), FT_FLOAT}, //time it takes before weapon stops firing -{NULL, 0, 0, 0} -}; - -//projectile definition -static fielddef_t projectileinfo_fields[] = -{ -{"name", PROJECTILE_OFS(name), FT_STRING}, //name of the projectile -{"model", PROJECTILE_OFS(model), FT_STRING}, //model of the projectile -{"flags", PROJECTILE_OFS(flags), FT_INT}, //special flags -{"gravity", PROJECTILE_OFS(gravity), FT_FLOAT}, //amount of gravity applied to the projectile [0,1] -{"damage", PROJECTILE_OFS(damage), FT_INT}, //damage of the projectile -{"radius", PROJECTILE_OFS(radius), FT_FLOAT}, //radius of damage -{"visdamage", PROJECTILE_OFS(visdamage), FT_INT}, //damage of the projectile to visible entities -{"damagetype", PROJECTILE_OFS(damagetype), FT_INT}, //type of damage (combination of the DAMAGETYPE_? flags) -{"healthinc", PROJECTILE_OFS(healthinc), FT_INT}, //health increase the owner gets -{"push", PROJECTILE_OFS(push), FT_FLOAT}, //amount a player is pushed away from the projectile impact -{"detonation", PROJECTILE_OFS(detonation), FT_FLOAT}, //time before projectile explodes after fire pressed -{"bounce", PROJECTILE_OFS(bounce), FT_FLOAT}, //amount the projectile bounces -{"bouncefric", PROJECTILE_OFS(bouncefric), FT_FLOAT}, //amount the bounce decreases per bounce -{"bouncestop", PROJECTILE_OFS(bouncestop), FT_FLOAT}, //minimum bounce value before bouncing stops -//recurive projectile definition?? -{NULL, 0, 0, 0} -}; - -static structdef_t weaponinfo_struct = -{ - sizeof(weaponinfo_t), weaponinfo_fields -}; -static structdef_t projectileinfo_struct = -{ - sizeof(projectileinfo_t), projectileinfo_fields -}; - -//weapon configuration: set of weapons with projectiles -typedef struct weaponconfig_s -{ +// weapon definition // bk001212 - static +static fielddef_t weaponinfo_fields[] = { + {"number", WEAPON_OFS(number), FT_INT}, // weapon number + {"name", WEAPON_OFS(name), FT_STRING}, // name of the weapon + {"level", WEAPON_OFS(level), FT_INT}, + {"model", WEAPON_OFS(model), FT_STRING}, // model of the weapon + {"weaponindex", WEAPON_OFS(weaponindex), FT_INT}, // index of weapon in inventory + {"flags", WEAPON_OFS(flags), FT_INT}, // special flags + {"projectile", WEAPON_OFS(projectile), FT_STRING}, // projectile used by the weapon + {"numprojectiles", WEAPON_OFS(numprojectiles), FT_INT}, // number of projectiles + {"hspread", WEAPON_OFS(hspread), FT_FLOAT}, // horizontal spread of projectiles (degrees from middle) + {"vspread", WEAPON_OFS(vspread), FT_FLOAT}, // vertical spread of projectiles (degrees from middle) + {"speed", WEAPON_OFS(speed), FT_FLOAT}, // speed of the projectile (0 = instant hit) + {"acceleration", WEAPON_OFS(acceleration), FT_FLOAT}, //"acceleration" * time (in seconds) + "speed" = projectile speed + {"recoil", WEAPON_OFS(recoil), FT_FLOAT | FT_ARRAY, 3}, // amount of recoil the player gets from the weapon + {"offset", WEAPON_OFS(offset), FT_FLOAT | FT_ARRAY, 3}, // projectile start offset relative to eye and view angles + {"angleoffset", WEAPON_OFS(angleoffset), FT_FLOAT | FT_ARRAY, 3}, // offset of the shoot angles relative to the view angles + {"extrazvelocity", WEAPON_OFS(extrazvelocity), FT_FLOAT}, // extra z velocity the projectile gets + {"ammoamount", WEAPON_OFS(ammoamount), FT_INT}, // ammo amount used per shot + {"ammoindex", WEAPON_OFS(ammoindex), FT_INT}, // index of ammo in inventory + {"activate", WEAPON_OFS(activate), FT_FLOAT}, // time it takes to select the weapon + {"reload", WEAPON_OFS(reload), FT_FLOAT}, // time it takes to reload the weapon + {"spinup", WEAPON_OFS(spinup), FT_FLOAT}, // time it takes before first shot + {"spindown", WEAPON_OFS(spindown), FT_FLOAT}, // time it takes before weapon stops firing + {NULL, 0, 0, 0}}; + +// projectile definition +static fielddef_t projectileinfo_fields[] = {{"name", PROJECTILE_OFS(name), FT_STRING}, // name of the projectile + {"model", PROJECTILE_OFS(model), FT_STRING}, // model of the projectile + {"flags", PROJECTILE_OFS(flags), FT_INT}, // special flags + {"gravity", PROJECTILE_OFS(gravity), FT_FLOAT}, // amount of gravity applied to the projectile [0,1] + {"damage", PROJECTILE_OFS(damage), FT_INT}, // damage of the projectile + {"radius", PROJECTILE_OFS(radius), FT_FLOAT}, // radius of damage + {"visdamage", PROJECTILE_OFS(visdamage), FT_INT}, // damage of the projectile to visible entities + {"damagetype", PROJECTILE_OFS(damagetype), FT_INT}, // type of damage (combination of the DAMAGETYPE_? flags) + {"healthinc", PROJECTILE_OFS(healthinc), FT_INT}, // health increase the owner gets + {"push", PROJECTILE_OFS(push), FT_FLOAT}, // amount a player is pushed away from the projectile impact + {"detonation", PROJECTILE_OFS(detonation), FT_FLOAT}, // time before projectile explodes after fire pressed + {"bounce", PROJECTILE_OFS(bounce), FT_FLOAT}, // amount the projectile bounces + {"bouncefric", PROJECTILE_OFS(bouncefric), FT_FLOAT}, // amount the bounce decreases per bounce + {"bouncestop", PROJECTILE_OFS(bouncestop), FT_FLOAT}, // minimum bounce value before bouncing stops + // recurive projectile definition?? + {NULL, 0, 0, 0}}; + +static structdef_t weaponinfo_struct = {sizeof(weaponinfo_t), weaponinfo_fields}; +static structdef_t projectileinfo_struct = {sizeof(projectileinfo_t), projectileinfo_fields}; + +// weapon configuration: set of weapons with projectiles +typedef struct weaponconfig_s { int numweapons; int numprojectiles; projectileinfo_t *projectileinfo; weaponinfo_t *weaponinfo; } weaponconfig_t; -//the bot weapon state -typedef struct bot_weaponstate_s -{ - struct weightconfig_s *weaponweightconfig; //weapon weight configuration - int *weaponweightindex; //weapon weight index +// the bot weapon state +typedef struct bot_weaponstate_s { + struct weightconfig_s *weaponweightconfig; // weapon weight configuration + int *weaponweightindex; // weapon weight index } bot_weaponstate_t; -static bot_weaponstate_t *botweaponstates[MAX_CLIENTS+1]; +static bot_weaponstate_t *botweaponstates[MAX_CLIENTS + 1]; static weaponconfig_t *weaponconfig; //======================================================================== @@ -139,35 +126,30 @@ static weaponconfig_t *weaponconfig; // Returns: - // Changes Globals: - //======================================================================== -int BotValidWeaponNumber(int weaponnum) -{ - if (weaponnum <= 0 || weaponnum > weaponconfig->numweapons) - { +int BotValidWeaponNumber(int weaponnum) { + if (weaponnum <= 0 || weaponnum > weaponconfig->numweapons) { botimport.Print(PRT_ERROR, "weapon number out of range\n"); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function BotValidWeaponNumber +} // end of the function BotValidWeaponNumber //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -bot_weaponstate_t *BotWeaponStateFromHandle(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +bot_weaponstate_t *BotWeaponStateFromHandle(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "weapon state handle %d out of range\n", handle); return NULL; - } //end if - if (!botweaponstates[handle]) - { + } // end if + if (!botweaponstates[handle]) { botimport.Print(PRT_FATAL, "invalid weapon state %d\n", handle); return NULL; - } //end if + } // end if return botweaponstates[handle]; -} //end of the function BotWeaponStateFromHandle +} // end of the function BotWeaponStateFromHandle //=========================================================================== // // Parameter: - @@ -175,33 +157,30 @@ bot_weaponstate_t *BotWeaponStateFromHandle(int handle) // Changes Globals: - //=========================================================================== #ifdef DEBUG_AI_WEAP -void DumpWeaponConfig(weaponconfig_t *wc) -{ +void DumpWeaponConfig(weaponconfig_t *wc) { FILE *fp; int i; fp = Log_FileStruct(); - if (!fp) return; - for (i = 0; i < wc->numprojectiles; i++) - { - WriteStructure(fp, &projectileinfo_struct, (char *) &wc->projectileinfo[i]); + if (!fp) + return; + for (i = 0; i < wc->numprojectiles; i++) { + WriteStructure(fp, &projectileinfo_struct, (char *)&wc->projectileinfo[i]); Log_Flush(); - } //end for - for (i = 0; i < wc->numweapons; i++) - { - WriteStructure(fp, &weaponinfo_struct, (char *) &wc->weaponinfo[i]); + } // end for + for (i = 0; i < wc->numweapons; i++) { + WriteStructure(fp, &weaponinfo_struct, (char *)&wc->weaponinfo[i]); Log_Flush(); - } //end for -} //end of the function DumpWeaponConfig -#endif //DEBUG_AI_WEAP + } // end for +} // end of the function DumpWeaponConfig +#endif // DEBUG_AI_WEAP //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -weaponconfig_t *LoadWeaponConfig(char *filename) -{ +weaponconfig_t *LoadWeaponConfig(char *filename) { int max_weaponinfo, max_projectileinfo; token_t token; char path[MAX_PATH]; @@ -210,339 +189,314 @@ weaponconfig_t *LoadWeaponConfig(char *filename) weaponconfig_t *wc; weaponinfo_t weaponinfo; - max_weaponinfo = (int) LibVarValue("max_weaponinfo", "32"); - if (max_weaponinfo < 0) - { + max_weaponinfo = (int)LibVarValue("max_weaponinfo", "32"); + if (max_weaponinfo < 0) { botimport.Print(PRT_ERROR, "max_weaponinfo = %d\n", max_weaponinfo); max_weaponinfo = 32; LibVarSet("max_weaponinfo", "32"); - } //end if - max_projectileinfo = (int) LibVarValue("max_projectileinfo", "32"); - if (max_projectileinfo < 0) - { + } // end if + max_projectileinfo = (int)LibVarValue("max_projectileinfo", "32"); + if (max_projectileinfo < 0) { botimport.Print(PRT_ERROR, "max_projectileinfo = %d\n", max_projectileinfo); max_projectileinfo = 32; LibVarSet("max_projectileinfo", "32"); - } //end if + } // end if strncpy(path, filename, MAX_PATH); PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(path); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", path); return NULL; - } //end if - //initialize weapon config - wc = (weaponconfig_t *) GetClearedHunkMemory(sizeof(weaponconfig_t) + - max_weaponinfo * sizeof(weaponinfo_t) + - max_projectileinfo * sizeof(projectileinfo_t)); - wc->weaponinfo = (weaponinfo_t *) ((char *) wc + sizeof(weaponconfig_t)); - wc->projectileinfo = (projectileinfo_t *) ((char *) wc->weaponinfo + - max_weaponinfo * sizeof(weaponinfo_t)); + } // end if + // initialize weapon config + wc = (weaponconfig_t *)GetClearedHunkMemory(sizeof(weaponconfig_t) + max_weaponinfo * sizeof(weaponinfo_t) + max_projectileinfo * sizeof(projectileinfo_t)); + wc->weaponinfo = (weaponinfo_t *)((char *)wc + sizeof(weaponconfig_t)); + wc->projectileinfo = (projectileinfo_t *)((char *)wc->weaponinfo + max_weaponinfo * sizeof(weaponinfo_t)); wc->numweapons = max_weaponinfo; wc->numprojectiles = 0; - //parse the source file - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "weaponinfo")) - { + // parse the source file + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "weaponinfo")) { Com_Memset(&weaponinfo, 0, sizeof(weaponinfo_t)); - if (!ReadStructure(source, &weaponinfo_struct, (char *) &weaponinfo)) - { + if (!ReadStructure(source, &weaponinfo_struct, (char *)&weaponinfo)) { FreeMemory(wc); FreeSource(source); return NULL; - } //end if - if (weaponinfo.number < 0 || weaponinfo.number >= max_weaponinfo) - { + } // end if + if (weaponinfo.number < 0 || weaponinfo.number >= max_weaponinfo) { botimport.Print(PRT_ERROR, "weapon info number %d out of range in %s\n", weaponinfo.number, path); FreeMemory(wc); FreeSource(source); return NULL; - } //end if + } // end if Com_Memcpy(&wc->weaponinfo[weaponinfo.number], &weaponinfo, sizeof(weaponinfo_t)); wc->weaponinfo[weaponinfo.number].valid = qtrue; - } //end if - else if (!strcmp(token.string, "projectileinfo")) - { - if (wc->numprojectiles >= max_projectileinfo) - { + } // end if + else if (!strcmp(token.string, "projectileinfo")) { + if (wc->numprojectiles >= max_projectileinfo) { botimport.Print(PRT_ERROR, "more than %d projectiles defined in %s\n", max_projectileinfo, path); FreeMemory(wc); FreeSource(source); return NULL; - } //end if + } // end if Com_Memset(&wc->projectileinfo[wc->numprojectiles], 0, sizeof(projectileinfo_t)); - if (!ReadStructure(source, &projectileinfo_struct, (char *) &wc->projectileinfo[wc->numprojectiles])) - { + if (!ReadStructure(source, &projectileinfo_struct, (char *)&wc->projectileinfo[wc->numprojectiles])) { FreeMemory(wc); FreeSource(source); return NULL; - } //end if + } // end if wc->numprojectiles++; - } //end if - else - { + } // end if + else { botimport.Print(PRT_ERROR, "unknown definition %s in %s\n", token.string, path); FreeMemory(wc); FreeSource(source); return NULL; - } //end else - } //end while + } // end else + } // end while FreeSource(source); - //fix up weapons - for (i = 0; i < wc->numweapons; i++) - { - if (!wc->weaponinfo[i].valid) continue; - if (!wc->weaponinfo[i].name[0]) - { + // fix up weapons + for (i = 0; i < wc->numweapons; i++) { + if (!wc->weaponinfo[i].valid) + continue; + if (!wc->weaponinfo[i].name[0]) { botimport.Print(PRT_ERROR, "weapon %d has no name in %s\n", i, path); FreeMemory(wc); return NULL; - } //end if - if (!wc->weaponinfo[i].projectile[0]) - { + } // end if + if (!wc->weaponinfo[i].projectile[0]) { botimport.Print(PRT_ERROR, "weapon %s has no projectile in %s\n", wc->weaponinfo[i].name, path); FreeMemory(wc); return NULL; - } //end if - //find the projectile info and copy it to the weapon info - for (j = 0; j < wc->numprojectiles; j++) - { - if (!strcmp(wc->projectileinfo[j].name, wc->weaponinfo[i].projectile)) - { + } // end if + // find the projectile info and copy it to the weapon info + for (j = 0; j < wc->numprojectiles; j++) { + if (!strcmp(wc->projectileinfo[j].name, wc->weaponinfo[i].projectile)) { Com_Memcpy(&wc->weaponinfo[i].proj, &wc->projectileinfo[j], sizeof(projectileinfo_t)); break; - } //end if - } //end for - if (j == wc->numprojectiles) - { + } // end if + } // end for + if (j == wc->numprojectiles) { botimport.Print(PRT_ERROR, "weapon %s uses undefined projectile in %s\n", wc->weaponinfo[i].name, path); FreeMemory(wc); return NULL; - } //end if - } //end for - if (!wc->numweapons) botimport.Print(PRT_WARNING, "no weapon info loaded\n"); + } // end if + } // end for + if (!wc->numweapons) + botimport.Print(PRT_WARNING, "no weapon info loaded\n"); botimport.Print(PRT_MESSAGE, "loaded %s\n", path); return wc; -} //end of the function LoadWeaponConfig +} // end of the function LoadWeaponConfig //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int *WeaponWeightIndex(weightconfig_t *wwc, weaponconfig_t *wc) -{ +int *WeaponWeightIndex(weightconfig_t *wwc, weaponconfig_t *wc) { int *index, i; - //initialize item weight index - index = (int *) GetClearedMemory(sizeof(int) * wc->numweapons); + // initialize item weight index + index = (int *)GetClearedMemory(sizeof(int) * wc->numweapons); - for (i = 0; i < wc->numweapons; i++) - { + for (i = 0; i < wc->numweapons; i++) { index[i] = FindFuzzyWeight(wwc, wc->weaponinfo[i].name); - } //end for + } // end for return index; -} //end of the function WeaponWeightIndex +} // end of the function WeaponWeightIndex //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotFreeWeaponWeights(int weaponstate) -{ +void BotFreeWeaponWeights(int weaponstate) { bot_weaponstate_t *ws; ws = BotWeaponStateFromHandle(weaponstate); - if (!ws) return; - if (ws->weaponweightconfig) FreeWeightConfig(ws->weaponweightconfig); - if (ws->weaponweightindex) FreeMemory(ws->weaponweightindex); -} //end of the function BotFreeWeaponWeights + if (!ws) + return; + if (ws->weaponweightconfig) + FreeWeightConfig(ws->weaponweightconfig); + if (ws->weaponweightindex) + FreeMemory(ws->weaponweightindex); +} // end of the function BotFreeWeaponWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotLoadWeaponWeights(int weaponstate, char *filename) -{ +int BotLoadWeaponWeights(int weaponstate, char *filename) { bot_weaponstate_t *ws; ws = BotWeaponStateFromHandle(weaponstate); - if (!ws) return BLERR_CANNOTLOADWEAPONWEIGHTS; + if (!ws) + return BLERR_CANNOTLOADWEAPONWEIGHTS; BotFreeWeaponWeights(weaponstate); // ws->weaponweightconfig = ReadWeightConfig(filename); - if (!ws->weaponweightconfig) - { + if (!ws->weaponweightconfig) { botimport.Print(PRT_FATAL, "couldn't load weapon config %s\n", filename); return BLERR_CANNOTLOADWEAPONWEIGHTS; - } //end if - if (!weaponconfig) return BLERR_CANNOTLOADWEAPONCONFIG; + } // end if + if (!weaponconfig) + return BLERR_CANNOTLOADWEAPONCONFIG; ws->weaponweightindex = WeaponWeightIndex(ws->weaponweightconfig, weaponconfig); return BLERR_NOERROR; -} //end of the function BotLoadWeaponWeights +} // end of the function BotLoadWeaponWeights //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotGetWeaponInfo(int weaponstate, int weapon, weaponinfo_t *weaponinfo) -{ +void BotGetWeaponInfo(int weaponstate, int weapon, weaponinfo_t *weaponinfo) { bot_weaponstate_t *ws; - if (!BotValidWeaponNumber(weapon)) return; + if (!BotValidWeaponNumber(weapon)) + return; ws = BotWeaponStateFromHandle(weaponstate); - if (!ws) return; - if (!weaponconfig) return; + if (!ws) + return; + if (!weaponconfig) + return; Com_Memcpy(weaponinfo, &weaponconfig->weaponinfo[weapon], sizeof(weaponinfo_t)); -} //end of the function BotGetWeaponInfo +} // end of the function BotGetWeaponInfo //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotChooseBestFightWeapon(int weaponstate, int *inventory) -{ +int BotChooseBestFightWeapon(int weaponstate, int *inventory) { int i, index, bestweapon; float weight, bestweight; weaponconfig_t *wc; bot_weaponstate_t *ws; ws = BotWeaponStateFromHandle(weaponstate); - if (!ws) return 0; + if (!ws) + return 0; wc = weaponconfig; - if (!weaponconfig) return 0; + if (!weaponconfig) + return 0; - //if the bot has no weapon weight configuration - if (!ws->weaponweightconfig) return 0; + // if the bot has no weapon weight configuration + if (!ws->weaponweightconfig) + return 0; bestweight = 0; bestweapon = 0; - for (i = 0; i < wc->numweapons; i++) - { - if (!wc->weaponinfo[i].valid) continue; + for (i = 0; i < wc->numweapons; i++) { + if (!wc->weaponinfo[i].valid) + continue; index = ws->weaponweightindex[i]; - if (index < 0) continue; + if (index < 0) + continue; weight = FuzzyWeight(inventory, ws->weaponweightconfig, index); - if (weight > bestweight) - { + if (weight > bestweight) { bestweight = weight; bestweapon = i; - } //end if - } //end for + } // end if + } // end for return bestweapon; -} //end of the function BotChooseBestFightWeapon +} // end of the function BotChooseBestFightWeapon //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotResetWeaponState(int weaponstate) -{ +void BotResetWeaponState(int weaponstate) { struct weightconfig_s *weaponweightconfig; int *weaponweightindex; bot_weaponstate_t *ws; ws = BotWeaponStateFromHandle(weaponstate); - if (!ws) return; + if (!ws) + return; weaponweightconfig = ws->weaponweightconfig; weaponweightindex = ws->weaponweightindex; - //Com_Memset(ws, 0, sizeof(bot_weaponstate_t)); + // Com_Memset(ws, 0, sizeof(bot_weaponstate_t)); ws->weaponweightconfig = weaponweightconfig; ws->weaponweightindex = weaponweightindex; -} //end of the function BotResetWeaponState +} // end of the function BotResetWeaponState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -int BotAllocWeaponState(void) -{ +int BotAllocWeaponState(void) { int i; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (!botweaponstates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (!botweaponstates[i]) { botweaponstates[i] = (struct bot_weaponstate_s *)GetClearedMemory(sizeof(bot_weaponstate_t)); return i; - } //end if - } //end for + } // end if + } // end for return 0; -} //end of the function BotAllocWeaponState +} // end of the function BotAllocWeaponState //======================================================================== // // Parameter: - // Returns: - // Changes Globals: - //======================================================================== -void BotFreeWeaponState(int handle) -{ - if (handle <= 0 || handle > MAX_CLIENTS) - { +void BotFreeWeaponState(int handle) { + if (handle <= 0 || handle > MAX_CLIENTS) { botimport.Print(PRT_FATAL, "weapon state handle %d out of range\n", handle); return; - } //end if - if (!botweaponstates[handle]) - { + } // end if + if (!botweaponstates[handle]) { botimport.Print(PRT_FATAL, "invalid weapon state %d\n", handle); return; - } //end if + } // end if BotFreeWeaponWeights(handle); FreeMemory(botweaponstates[handle]); botweaponstates[handle] = NULL; -} //end of the function BotFreeWeaponState +} // end of the function BotFreeWeaponState //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int BotSetupWeaponAI(void) -{ +int BotSetupWeaponAI(void) { char *file; file = LibVarString("weaponconfig", "weapons.c"); weaponconfig = LoadWeaponConfig(file); - if (!weaponconfig) - { + if (!weaponconfig) { botimport.Print(PRT_FATAL, "couldn't load the weapon config\n"); return BLERR_CANNOTLOADWEAPONCONFIG; - } //end if + } // end if #ifdef DEBUG_AI_WEAP DumpWeaponConfig(weaponconfig); -#endif //DEBUG_AI_WEAP +#endif // DEBUG_AI_WEAP // return BLERR_NOERROR; -} //end of the function BotSetupWeaponAI +} // end of the function BotSetupWeaponAI //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownWeaponAI(void) -{ +void BotShutdownWeaponAI(void) { int i; - if (weaponconfig) FreeMemory(weaponconfig); + if (weaponconfig) + FreeMemory(weaponconfig); weaponconfig = NULL; - for (i = 1; i <= MAX_CLIENTS; i++) - { - if (botweaponstates[i]) - { + for (i = 1; i <= MAX_CLIENTS; i++) { + if (botweaponstates[i]) { BotFreeWeaponState(i); - } //end if - } //end for -} //end of the function BotShutdownWeaponAI - + } // end if + } // end for +} // end of the function BotShutdownWeaponAI diff --git a/codemp/botlib/be_ai_weight.cpp b/codemp/botlib/be_ai_weight.cpp index 6f5d74d235..e8c1fe127e 100644 --- a/codemp/botlib/be_ai_weight.cpp +++ b/codemp/botlib/be_ai_weight.cpp @@ -49,11 +49,11 @@ along with this program; if not, see . #include "be_interface.h" #include "be_ai_weight.h" -#define MAX_INVENTORYVALUE 999999 +#define MAX_INVENTORYVALUE 999999 #define EVALUATERECURSIVELY -#define MAX_WEIGHT_FILES 128 -weightconfig_t *weightFileList[MAX_WEIGHT_FILES]; +#define MAX_WEIGHT_FILES 128 +weightconfig_t *weightFileList[MAX_WEIGHT_FILES]; //=========================================================================== // @@ -61,109 +61,112 @@ weightconfig_t *weightFileList[MAX_WEIGHT_FILES]; // Returns: - // Changes Globals: - //=========================================================================== -int ReadValue(source_t *source, float *value) -{ +int ReadValue(source_t *source, float *value) { token_t token; - if (!PC_ExpectAnyToken(source, &token)) return qfalse; - if (!strcmp(token.string, "-")) - { + if (!PC_ExpectAnyToken(source, &token)) + return qfalse; + if (!strcmp(token.string, "-")) { SourceWarning(source, "negative value set to zero"); - if(!PC_ExpectAnyToken(source, &token)) - { + if (!PC_ExpectAnyToken(source, &token)) { SourceError(source, "Missing return value"); return qfalse; } } - if (token.type != TT_NUMBER) - { + if (token.type != TT_NUMBER) { SourceError(source, "invalid return value %s", token.string); return qfalse; } *value = token.floatvalue; return qtrue; -} //end of the function ReadValue +} // end of the function ReadValue //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int ReadFuzzyWeight(source_t *source, fuzzyseperator_t *fs) -{ - if (PC_CheckTokenString(source, "balance")) - { +int ReadFuzzyWeight(source_t *source, fuzzyseperator_t *fs) { + if (PC_CheckTokenString(source, "balance")) { fs->type = WT_BALANCE; - if (!PC_ExpectTokenString(source, "(")) return qfalse; - if (!ReadValue(source, &fs->weight)) return qfalse; - if (!PC_ExpectTokenString(source, ",")) return qfalse; - if (!ReadValue(source, &fs->minweight)) return qfalse; - if (!PC_ExpectTokenString(source, ",")) return qfalse; - if (!ReadValue(source, &fs->maxweight)) return qfalse; - if (!PC_ExpectTokenString(source, ")")) return qfalse; - } //end if - else - { + if (!PC_ExpectTokenString(source, "(")) + return qfalse; + if (!ReadValue(source, &fs->weight)) + return qfalse; + if (!PC_ExpectTokenString(source, ",")) + return qfalse; + if (!ReadValue(source, &fs->minweight)) + return qfalse; + if (!PC_ExpectTokenString(source, ",")) + return qfalse; + if (!ReadValue(source, &fs->maxweight)) + return qfalse; + if (!PC_ExpectTokenString(source, ")")) + return qfalse; + } // end if + else { fs->type = 0; - if (!ReadValue(source, &fs->weight)) return qfalse; + if (!ReadValue(source, &fs->weight)) + return qfalse; fs->minweight = fs->weight; fs->maxweight = fs->weight; - } //end if - if (!PC_ExpectTokenString(source, ";")) return qfalse; + } // end if + if (!PC_ExpectTokenString(source, ";")) + return qfalse; return qtrue; -} //end of the function ReadFuzzyWeight +} // end of the function ReadFuzzyWeight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeFuzzySeperators_r(fuzzyseperator_t *fs) -{ - if (!fs) return; - if (fs->child) FreeFuzzySeperators_r(fs->child); - if (fs->next) FreeFuzzySeperators_r(fs->next); +void FreeFuzzySeperators_r(fuzzyseperator_t *fs) { + if (!fs) + return; + if (fs->child) + FreeFuzzySeperators_r(fs->child); + if (fs->next) + FreeFuzzySeperators_r(fs->next); FreeMemory(fs); -} //end of the function FreeFuzzySeperators +} // end of the function FreeFuzzySeperators //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeWeightConfig2(weightconfig_t *config) -{ +void FreeWeightConfig2(weightconfig_t *config) { int i; - for (i = 0; i < config->numweights; i++) - { + for (i = 0; i < config->numweights; i++) { FreeFuzzySeperators_r(config->weights[i].firstseperator); - if (config->weights[i].name) FreeMemory(config->weights[i].name); - } //end for + if (config->weights[i].name) + FreeMemory(config->weights[i].name); + } // end for FreeMemory(config); -} //end of the function FreeWeightConfig2 +} // end of the function FreeWeightConfig2 //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeWeightConfig(weightconfig_t *config) -{ - if (!LibVarGetValue("bot_reloadcharacters")) return; +void FreeWeightConfig(weightconfig_t *config) { + if (!LibVarGetValue("bot_reloadcharacters")) + return; FreeWeightConfig2(config); -} //end of the function FreeWeightConfig +} // end of the function FreeWeightConfig //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -fuzzyseperator_t *ReadFuzzySeperators_r(source_t *source) -{ +fuzzyseperator_t *ReadFuzzySeperators_r(source_t *source) { int newindent, index, def, founddefault; token_t token; fuzzyseperator_t *fs, *lastfs, *firstfs; @@ -171,125 +174,114 @@ fuzzyseperator_t *ReadFuzzySeperators_r(source_t *source) founddefault = qfalse; firstfs = NULL; lastfs = NULL; - if (!PC_ExpectTokenString(source, "(")) return NULL; - if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) return NULL; + if (!PC_ExpectTokenString(source, "(")) + return NULL; + if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) + return NULL; index = token.intvalue; - if (!PC_ExpectTokenString(source, ")")) return NULL; - if (!PC_ExpectTokenString(source, "{")) return NULL; - if (!PC_ExpectAnyToken(source, &token)) return NULL; - do - { + if (!PC_ExpectTokenString(source, ")")) + return NULL; + if (!PC_ExpectTokenString(source, "{")) + return NULL; + if (!PC_ExpectAnyToken(source, &token)) + return NULL; + do { def = !strcmp(token.string, "default"); - if (def || !strcmp(token.string, "case")) - { - fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t)); + if (def || !strcmp(token.string, "case")) { + fs = (fuzzyseperator_t *)GetClearedMemory(sizeof(fuzzyseperator_t)); fs->index = index; - if (lastfs) lastfs->next = fs; - else firstfs = fs; + if (lastfs) + lastfs->next = fs; + else + firstfs = fs; lastfs = fs; - if (def) - { - if (founddefault) - { + if (def) { + if (founddefault) { SourceError(source, "switch already has a default"); FreeFuzzySeperators_r(firstfs); return NULL; - } //end if + } // end if fs->value = MAX_INVENTORYVALUE; founddefault = qtrue; - } //end if - else - { - if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) - { + } // end if + else { + if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if + } // end if fs->value = token.intvalue; - } //end else - if (!PC_ExpectTokenString(source, ":") || !PC_ExpectAnyToken(source, &token)) - { + } // end else + if (!PC_ExpectTokenString(source, ":") || !PC_ExpectAnyToken(source, &token)) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if + } // end if newindent = qfalse; - if (!strcmp(token.string, "{")) - { + if (!strcmp(token.string, "{")) { newindent = qtrue; - if (!PC_ExpectAnyToken(source, &token)) - { + if (!PC_ExpectAnyToken(source, &token)) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if - } //end if - if (!strcmp(token.string, "return")) - { - if (!ReadFuzzyWeight(source, fs)) - { + } // end if + } // end if + if (!strcmp(token.string, "return")) { + if (!ReadFuzzyWeight(source, fs)) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if - } //end if - else if (!strcmp(token.string, "switch")) - { + } // end if + } // end if + else if (!strcmp(token.string, "switch")) { fs->child = ReadFuzzySeperators_r(source); - if (!fs->child) - { + if (!fs->child) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if - } //end else if - else - { + } // end if + } // end else if + else { SourceError(source, "invalid name %s", token.string); return NULL; - } //end else - if (newindent) - { - if (!PC_ExpectTokenString(source, "}")) - { + } // end else + if (newindent) { + if (!PC_ExpectTokenString(source, "}")) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if - } //end if - } //end if - else - { + } // end if + } // end if + } // end if + else { FreeFuzzySeperators_r(firstfs); SourceError(source, "invalid name %s", token.string); return NULL; - } //end else - if (!PC_ExpectAnyToken(source, &token)) - { + } // end else + if (!PC_ExpectAnyToken(source, &token)) { FreeFuzzySeperators_r(firstfs); return NULL; - } //end if - } while(strcmp(token.string, "}")); + } // end if + } while (strcmp(token.string, "}")); // - if (!founddefault) - { + if (!founddefault) { SourceWarning(source, "switch without default"); - fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t)); + fs = (fuzzyseperator_t *)GetClearedMemory(sizeof(fuzzyseperator_t)); fs->index = index; fs->value = MAX_INVENTORYVALUE; fs->weight = 0; fs->next = NULL; fs->child = NULL; - if (lastfs) lastfs->next = fs; - else firstfs = fs; + if (lastfs) + lastfs->next = fs; + else + firstfs = fs; lastfs = fs; - } //end if + } // end if // return firstfs; -} //end of the function ReadFuzzySeperators_r +} // end of the function ReadFuzzySeperators_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -weightconfig_t *ReadWeightConfig(char *filename) -{ +weightconfig_t *ReadWeightConfig(char *filename) { int newindent, avail = 0, n; token_t token; source_t *source; @@ -299,154 +291,130 @@ weightconfig_t *ReadWeightConfig(char *filename) int starttime; starttime = Sys_MilliSeconds(); -#endif //DEBUG +#endif // DEBUG - if (!LibVarGetValue("bot_reloadcharacters")) - { + if (!LibVarGetValue("bot_reloadcharacters")) { avail = -1; - for( n = 0; n < MAX_WEIGHT_FILES; n++ ) - { + for (n = 0; n < MAX_WEIGHT_FILES; n++) { config = weightFileList[n]; - if( !config ) - { - if( avail == -1 ) - { + if (!config) { + if (avail == -1) { avail = n; - } //end if + } // end if continue; - } //end if - if( strcmp( filename, config->filename ) == 0 ) - { - //botimport.Print( PRT_MESSAGE, "retained %s\n", filename ); + } // end if + if (strcmp(filename, config->filename) == 0) { + // botimport.Print( PRT_MESSAGE, "retained %s\n", filename ); return config; - } //end if - } //end for + } // end if + } // end for - if( avail == -1 ) - { - botimport.Print( PRT_ERROR, "weightFileList was full trying to load %s\n", filename ); + if (avail == -1) { + botimport.Print(PRT_ERROR, "weightFileList was full trying to load %s\n", filename); return NULL; - } //end if - } //end if + } // end if + } // end if PC_SetBaseFolder(BOTFILESBASEFOLDER); source = LoadSourceFile(filename); - if (!source) - { + if (!source) { botimport.Print(PRT_ERROR, "counldn't load %s\n", filename); return NULL; - } //end if + } // end if // - config = (weightconfig_t *) GetClearedMemory(sizeof(weightconfig_t)); + config = (weightconfig_t *)GetClearedMemory(sizeof(weightconfig_t)); config->numweights = 0; - Q_strncpyz( config->filename, filename, sizeof(config->filename) ); - //parse the item config file - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, "weight")) - { - if (config->numweights >= MAX_WEIGHTS) - { + Q_strncpyz(config->filename, filename, sizeof(config->filename)); + // parse the item config file + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, "weight")) { + if (config->numweights >= MAX_WEIGHTS) { SourceWarning(source, "too many fuzzy weights"); break; - } //end if - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) - { + } // end if + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) { FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if + } // end if StripDoubleQuotes(token.string); - config->weights[config->numweights].name = (char *) GetClearedMemory(strlen(token.string) + 1); + config->weights[config->numweights].name = (char *)GetClearedMemory(strlen(token.string) + 1); strcpy(config->weights[config->numweights].name, token.string); - if (!PC_ExpectAnyToken(source, &token)) - { + if (!PC_ExpectAnyToken(source, &token)) { FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if + } // end if newindent = qfalse; - if (!strcmp(token.string, "{")) - { + if (!strcmp(token.string, "{")) { newindent = qtrue; - if (!PC_ExpectAnyToken(source, &token)) - { + if (!PC_ExpectAnyToken(source, &token)) { FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if - } //end if - if (!strcmp(token.string, "switch")) - { + } // end if + } // end if + if (!strcmp(token.string, "switch")) { fs = ReadFuzzySeperators_r(source); - if (!fs) - { + if (!fs) { FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if + } // end if config->weights[config->numweights].firstseperator = fs; - } //end if - else if (!strcmp(token.string, "return")) - { - fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t)); + } // end if + else if (!strcmp(token.string, "return")) { + fs = (fuzzyseperator_t *)GetClearedMemory(sizeof(fuzzyseperator_t)); fs->index = 0; fs->value = MAX_INVENTORYVALUE; fs->next = NULL; fs->child = NULL; - if (!ReadFuzzyWeight(source, fs)) - { + if (!ReadFuzzyWeight(source, fs)) { FreeMemory(fs); FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if + } // end if config->weights[config->numweights].firstseperator = fs; - } //end else if - else - { + } // end else if + else { SourceError(source, "invalid name %s", token.string); FreeWeightConfig(config); FreeSource(source); return NULL; - } //end else - if (newindent) - { - if (!PC_ExpectTokenString(source, "}")) - { + } // end else + if (newindent) { + if (!PC_ExpectTokenString(source, "}")) { FreeWeightConfig(config); FreeSource(source); return NULL; - } //end if - } //end if + } // end if + } // end if config->numweights++; - } //end if - else - { + } // end if + else { SourceError(source, "invalid name %s", token.string); FreeWeightConfig(config); FreeSource(source); return NULL; - } //end else - } //end while - //free the source at the end of a pass + } // end else + } // end while + // free the source at the end of a pass FreeSource(source); - //if the file was located in a pak file + // if the file was located in a pak file botimport.Print(PRT_MESSAGE, "loaded %s\n", filename); #ifdef DEBUG - if (botDeveloper) - { + if (botDeveloper) { botimport.Print(PRT_MESSAGE, "weights loaded in %d msec\n", Sys_MilliSeconds() - starttime); - } //end if -#endif //DEBUG + } // end if +#endif // DEBUG // - if (!LibVarGetValue("bot_reloadcharacters")) - { + if (!LibVarGetValue("bot_reloadcharacters")) { weightFileList[avail] = config; - } //end if + } // end if // return config; -} //end of the function ReadWeightConfig +} // end of the function ReadWeightConfig #if 0 //=========================================================================== // @@ -566,324 +534,315 @@ qboolean WriteWeightConfig(char *filename, weightconfig_t *config) // Returns: - // Changes Globals: - //=========================================================================== -int FindFuzzyWeight(weightconfig_t *wc, char *name) -{ +int FindFuzzyWeight(weightconfig_t *wc, char *name) { int i; - for (i = 0; i < wc->numweights; i++) - { - if (!strcmp(wc->weights[i].name, name)) - { + for (i = 0; i < wc->numweights; i++) { + if (!strcmp(wc->weights[i].name, name)) { return i; - } //end if - } //end if + } // end if + } // end if return -1; -} //end of the function FindFuzzyWeight +} // end of the function FindFuzzyWeight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float FuzzyWeight_r(int *inventory, fuzzyseperator_t *fs) -{ +float FuzzyWeight_r(int *inventory, fuzzyseperator_t *fs) { float scale, w1, w2; - if (inventory[fs->index] < fs->value) - { - if (fs->child) return FuzzyWeight_r(inventory, fs->child); - else return fs->weight; - } //end if - else if (fs->next) - { - if (inventory[fs->index] < fs->next->value) - { - //first weight - if (fs->child) w1 = FuzzyWeight_r(inventory, fs->child); - else w1 = fs->weight; - //second weight - if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child); - else w2 = fs->next->weight; - //the scale factor - if(fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case? - return w2; // can't interpolate, return default weight + if (inventory[fs->index] < fs->value) { + if (fs->child) + return FuzzyWeight_r(inventory, fs->child); + else + return fs->weight; + } // end if + else if (fs->next) { + if (inventory[fs->index] < fs->next->value) { + // first weight + if (fs->child) + w1 = FuzzyWeight_r(inventory, fs->child); else - scale = (float) (inventory[fs->index] - fs->value) / (fs->next->value - fs->value); - //scale between the two weights + w1 = fs->weight; + // second weight + if (fs->next->child) + w2 = FuzzyWeight_r(inventory, fs->next->child); + else + w2 = fs->next->weight; + // the scale factor + if (fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case? + return w2; // can't interpolate, return default weight + else + scale = (float)(inventory[fs->index] - fs->value) / (fs->next->value - fs->value); + // scale between the two weights return (1 - scale) * w1 + scale * w2; - } //end if + } // end if return FuzzyWeight_r(inventory, fs->next); - } //end else if + } // end else if return fs->weight; -} //end of the function FuzzyWeight_r +} // end of the function FuzzyWeight_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float FuzzyWeightUndecided_r(int *inventory, fuzzyseperator_t *fs) -{ +float FuzzyWeightUndecided_r(int *inventory, fuzzyseperator_t *fs) { float scale, w1, w2; - if (inventory[fs->index] < fs->value) - { - if (fs->child) return FuzzyWeightUndecided_r(inventory, fs->child); - else return fs->minweight + Q_flrand(0.0f, 1.0f) * (fs->maxweight - fs->minweight); - } //end if - else if (fs->next) - { - if (inventory[fs->index] < fs->next->value) - { - //first weight - if (fs->child) w1 = FuzzyWeightUndecided_r(inventory, fs->child); - else w1 = fs->minweight + Q_flrand(0.0f, 1.0f) * (fs->maxweight - fs->minweight); - //second weight - if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child); - else w2 = fs->next->minweight + Q_flrand(0.0f, 1.0f) * (fs->next->maxweight - fs->next->minweight); - //the scale factor - if(fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case? - return w2; // can't interpolate, return default weight + if (inventory[fs->index] < fs->value) { + if (fs->child) + return FuzzyWeightUndecided_r(inventory, fs->child); + else + return fs->minweight + Q_flrand(0.0f, 1.0f) * (fs->maxweight - fs->minweight); + } // end if + else if (fs->next) { + if (inventory[fs->index] < fs->next->value) { + // first weight + if (fs->child) + w1 = FuzzyWeightUndecided_r(inventory, fs->child); else - scale = (float) (inventory[fs->index] - fs->value) / (fs->next->value - fs->value); - //scale between the two weights + w1 = fs->minweight + Q_flrand(0.0f, 1.0f) * (fs->maxweight - fs->minweight); + // second weight + if (fs->next->child) + w2 = FuzzyWeight_r(inventory, fs->next->child); + else + w2 = fs->next->minweight + Q_flrand(0.0f, 1.0f) * (fs->next->maxweight - fs->next->minweight); + // the scale factor + if (fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case? + return w2; // can't interpolate, return default weight + else + scale = (float)(inventory[fs->index] - fs->value) / (fs->next->value - fs->value); + // scale between the two weights return (1 - scale) * w1 + scale * w2; - } //end if + } // end if return FuzzyWeightUndecided_r(inventory, fs->next); - } //end else if + } // end else if return fs->weight; -} //end of the function FuzzyWeightUndecided_r +} // end of the function FuzzyWeightUndecided_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum) -{ +float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum) { #ifdef EVALUATERECURSIVELY return FuzzyWeight_r(inventory, wc->weights[weightnum].firstseperator); #else fuzzyseperator_t *s; s = wc->weights[weightnum].firstseperator; - if (!s) return 0; - while(1) - { - if (inventory[s->index] < s->value) - { - if (s->child) s = s->child; - else return s->weight; - } //end if - else - { - if (s->next) s = s->next; - else return s->weight; - } //end else - } //end if + if (!s) + return 0; + while (1) { + if (inventory[s->index] < s->value) { + if (s->child) + s = s->child; + else + return s->weight; + } // end if + else { + if (s->next) + s = s->next; + else + return s->weight; + } // end else + } // end if return 0; #endif -} //end of the function FuzzyWeight +} // end of the function FuzzyWeight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum) -{ +float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum) { #ifdef EVALUATERECURSIVELY return FuzzyWeightUndecided_r(inventory, wc->weights[weightnum].firstseperator); #else fuzzyseperator_t *s; s = wc->weights[weightnum].firstseperator; - if (!s) return 0; - while(1) - { - if (inventory[s->index] < s->value) - { - if (s->child) s = s->child; - else return s->minweight + Q_flrand(0.0f, 1.0f) * (s->maxweight - s->minweight); - } //end if - else - { - if (s->next) s = s->next; - else return s->minweight + Q_flrand(0.0f, 1.0f) * (s->maxweight - s->minweight); - } //end else - } //end if + if (!s) + return 0; + while (1) { + if (inventory[s->index] < s->value) { + if (s->child) + s = s->child; + else + return s->minweight + Q_flrand(0.0f, 1.0f) * (s->maxweight - s->minweight); + } // end if + else { + if (s->next) + s = s->next; + else + return s->minweight + Q_flrand(0.0f, 1.0f) * (s->maxweight - s->minweight); + } // end else + } // end if return 0; #endif -} //end of the function FuzzyWeightUndecided +} // end of the function FuzzyWeightUndecided //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EvolveFuzzySeperator_r(fuzzyseperator_t *fs) -{ - if (fs->child) - { +void EvolveFuzzySeperator_r(fuzzyseperator_t *fs) { + if (fs->child) { EvolveFuzzySeperator_r(fs->child); - } //end if - else if (fs->type == WT_BALANCE) - { - //every once in a while an evolution leap occurs, mutation - if (Q_flrand(0.0f, 1.0f) < 0.01) fs->weight += Q_flrand(-1.0f, 1.0f) * (fs->maxweight - fs->minweight); - else fs->weight += Q_flrand(-1.0f, 1.0f) * (fs->maxweight - fs->minweight) * 0.5; - //modify bounds if necesary because of mutation - if (fs->weight < fs->minweight) fs->minweight = fs->weight; - else if (fs->weight > fs->maxweight) fs->maxweight = fs->weight; - } //end else if - if (fs->next) EvolveFuzzySeperator_r(fs->next); -} //end of the function EvolveFuzzySeperator_r + } // end if + else if (fs->type == WT_BALANCE) { + // every once in a while an evolution leap occurs, mutation + if (Q_flrand(0.0f, 1.0f) < 0.01) + fs->weight += Q_flrand(-1.0f, 1.0f) * (fs->maxweight - fs->minweight); + else + fs->weight += Q_flrand(-1.0f, 1.0f) * (fs->maxweight - fs->minweight) * 0.5; + // modify bounds if necesary because of mutation + if (fs->weight < fs->minweight) + fs->minweight = fs->weight; + else if (fs->weight > fs->maxweight) + fs->maxweight = fs->weight; + } // end else if + if (fs->next) + EvolveFuzzySeperator_r(fs->next); +} // end of the function EvolveFuzzySeperator_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EvolveWeightConfig(weightconfig_t *config) -{ +void EvolveWeightConfig(weightconfig_t *config) { int i; - for (i = 0; i < config->numweights; i++) - { + for (i = 0; i < config->numweights; i++) { EvolveFuzzySeperator_r(config->weights[i].firstseperator); - } //end for -} //end of the function EvolveWeightConfig + } // end for +} // end of the function EvolveWeightConfig //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void ScaleFuzzySeperator_r(fuzzyseperator_t *fs, float scale) -{ - if (fs->child) - { +void ScaleFuzzySeperator_r(fuzzyseperator_t *fs, float scale) { + if (fs->child) { ScaleFuzzySeperator_r(fs->child, scale); - } //end if - else if (fs->type == WT_BALANCE) - { + } // end if + else if (fs->type == WT_BALANCE) { // - fs->weight = (float) (fs->maxweight + fs->minweight) * scale; - //get the weight between bounds - if (fs->weight < fs->minweight) fs->weight = fs->minweight; - else if (fs->weight > fs->maxweight) fs->weight = fs->maxweight; - } //end else if - if (fs->next) ScaleFuzzySeperator_r(fs->next, scale); -} //end of the function ScaleFuzzySeperator_r + fs->weight = (float)(fs->maxweight + fs->minweight) * scale; + // get the weight between bounds + if (fs->weight < fs->minweight) + fs->weight = fs->minweight; + else if (fs->weight > fs->maxweight) + fs->weight = fs->maxweight; + } // end else if + if (fs->next) + ScaleFuzzySeperator_r(fs->next, scale); +} // end of the function ScaleFuzzySeperator_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void ScaleWeight(weightconfig_t *config, char *name, float scale) -{ +void ScaleWeight(weightconfig_t *config, char *name, float scale) { int i; - if (scale < 0) scale = 0; - else if (scale > 1) scale = 1; - for (i = 0; i < config->numweights; i++) - { - if (!strcmp(name, config->weights[i].name)) - { + if (scale < 0) + scale = 0; + else if (scale > 1) + scale = 1; + for (i = 0; i < config->numweights; i++) { + if (!strcmp(name, config->weights[i].name)) { ScaleFuzzySeperator_r(config->weights[i].firstseperator, scale); break; - } //end if - } //end for -} //end of the function ScaleWeight + } // end if + } // end for +} // end of the function ScaleWeight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void ScaleFuzzySeperatorBalanceRange_r(fuzzyseperator_t *fs, float scale) -{ - if (fs->child) - { +void ScaleFuzzySeperatorBalanceRange_r(fuzzyseperator_t *fs, float scale) { + if (fs->child) { ScaleFuzzySeperatorBalanceRange_r(fs->child, scale); - } //end if - else if (fs->type == WT_BALANCE) - { + } // end if + else if (fs->type == WT_BALANCE) { float mid = (fs->minweight + fs->maxweight) * 0.5; - //get the weight between bounds + // get the weight between bounds fs->maxweight = mid + (fs->maxweight - mid) * scale; fs->minweight = mid + (fs->minweight - mid) * scale; - if (fs->maxweight < fs->minweight) - { + if (fs->maxweight < fs->minweight) { fs->maxweight = fs->minweight; - } //end if - } //end else if - if (fs->next) ScaleFuzzySeperatorBalanceRange_r(fs->next, scale); -} //end of the function ScaleFuzzySeperatorBalanceRange_r + } // end if + } // end else if + if (fs->next) + ScaleFuzzySeperatorBalanceRange_r(fs->next, scale); +} // end of the function ScaleFuzzySeperatorBalanceRange_r //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void ScaleFuzzyBalanceRange(weightconfig_t *config, float scale) -{ +void ScaleFuzzyBalanceRange(weightconfig_t *config, float scale) { int i; - if (scale < 0) scale = 0; - else if (scale > 100) scale = 100; - for (i = 0; i < config->numweights; i++) - { + if (scale < 0) + scale = 0; + else if (scale > 100) + scale = 100; + for (i = 0; i < config->numweights; i++) { ScaleFuzzySeperatorBalanceRange_r(config->weights[i].firstseperator, scale); - } //end for -} //end of the function ScaleFuzzyBalanceRange + } // end for +} // end of the function ScaleFuzzyBalanceRange //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int InterbreedFuzzySeperator_r(fuzzyseperator_t *fs1, fuzzyseperator_t *fs2, - fuzzyseperator_t *fsout) -{ - if (fs1->child) - { - if (!fs2->child || !fsout->child) - { +int InterbreedFuzzySeperator_r(fuzzyseperator_t *fs1, fuzzyseperator_t *fs2, fuzzyseperator_t *fsout) { + if (fs1->child) { + if (!fs2->child || !fsout->child) { botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal child\n"); return qfalse; - } //end if - if (!InterbreedFuzzySeperator_r(fs2->child, fs2->child, fsout->child)) - { + } // end if + if (!InterbreedFuzzySeperator_r(fs2->child, fs2->child, fsout->child)) { return qfalse; - } //end if - } //end if - else if (fs1->type == WT_BALANCE) - { - if (fs2->type != WT_BALANCE || fsout->type != WT_BALANCE) - { + } // end if + } // end if + else if (fs1->type == WT_BALANCE) { + if (fs2->type != WT_BALANCE || fsout->type != WT_BALANCE) { botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal balance\n"); return qfalse; - } //end if + } // end if fsout->weight = (fs1->weight + fs2->weight) / 2; - if (fsout->weight > fsout->maxweight) fsout->maxweight = fsout->weight; - if (fsout->weight > fsout->minweight) fsout->minweight = fsout->weight; - } //end else if - if (fs1->next) - { - if (!fs2->next || !fsout->next) - { + if (fsout->weight > fsout->maxweight) + fsout->maxweight = fsout->weight; + if (fsout->weight > fsout->minweight) + fsout->minweight = fsout->weight; + } // end else if + if (fs1->next) { + if (!fs2->next || !fsout->next) { botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal next\n"); return qfalse; - } //end if - if (!InterbreedFuzzySeperator_r(fs1->next, fs2->next, fsout->next)) - { + } // end if + if (!InterbreedFuzzySeperator_r(fs1->next, fs2->next, fsout->next)) { return qfalse; - } //end if - } //end if + } // end if + } // end if return qtrue; -} //end of the function InterbreedFuzzySeperator_r +} // end of the function InterbreedFuzzySeperator_r //=========================================================================== // config1 and config2 are interbreeded and stored in configout // @@ -891,40 +850,30 @@ int InterbreedFuzzySeperator_r(fuzzyseperator_t *fs1, fuzzyseperator_t *fs2, // Returns: - // Changes Globals: - //=========================================================================== -void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2, - weightconfig_t *configout) -{ +void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2, weightconfig_t *configout) { int i; - if (config1->numweights != config2->numweights || - config1->numweights != configout->numweights) - { + if (config1->numweights != config2->numweights || config1->numweights != configout->numweights) { botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal numweights\n"); return; - } //end if - for (i = 0; i < config1->numweights; i++) - { - InterbreedFuzzySeperator_r(config1->weights[i].firstseperator, - config2->weights[i].firstseperator, - configout->weights[i].firstseperator); - } //end for -} //end of the function InterbreedWeightConfigs + } // end if + for (i = 0; i < config1->numweights; i++) { + InterbreedFuzzySeperator_r(config1->weights[i].firstseperator, config2->weights[i].firstseperator, configout->weights[i].firstseperator); + } // end for +} // end of the function InterbreedWeightConfigs //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void BotShutdownWeights(void) -{ +void BotShutdownWeights(void) { int i; - for( i = 0; i < MAX_WEIGHT_FILES; i++ ) - { - if (weightFileList[i]) - { + for (i = 0; i < MAX_WEIGHT_FILES; i++) { + if (weightFileList[i]) { FreeWeightConfig2(weightFileList[i]); weightFileList[i] = NULL; - } //end if - } //end for -} //end of the function BotShutdownWeights + } // end if + } // end for +} // end of the function BotShutdownWeights diff --git a/codemp/botlib/be_ea.cpp b/codemp/botlib/be_ea.cpp index 24ea43b707..9c4c0d7fa2 100644 --- a/codemp/botlib/be_ea.cpp +++ b/codemp/botlib/be_ea.cpp @@ -43,9 +43,9 @@ along with this program; if not, see . #include "be_interface.h" #include "be_ea.h" -#define MAX_USERMOVE 400 -#define MAX_COMMANDARGUMENTS 10 -#define ACTION_JUMPEDLASTFRAME 0x0800000//128 +#define MAX_USERMOVE 400 +#define MAX_COMMANDARGUMENTS 10 +#define ACTION_JUMPEDLASTFRAME 0x0800000 // 128 bot_input_t *botinputs; @@ -55,423 +55,372 @@ bot_input_t *botinputs; // Returns: - // Changes Globals: - //=========================================================================== -void EA_Say(int client, char *str) -{ - botimport.BotClientCommand(client, va("say %s", str) ); -} //end of the function EA_Say +void EA_Say(int client, char *str) { botimport.BotClientCommand(client, va("say %s", str)); } // end of the function EA_Say //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_SayTeam(int client, char *str) -{ - botimport.BotClientCommand(client, va("say_team %s", str)); -} //end of the function EA_SayTeam +void EA_SayTeam(int client, char *str) { botimport.BotClientCommand(client, va("say_team %s", str)); } // end of the function EA_SayTeam //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Tell(int client, int clientto, char *str) -{ - botimport.BotClientCommand(client, va("tell %d, %s", clientto, str)); -} //end of the function EA_SayTeam +void EA_Tell(int client, int clientto, char *str) { botimport.BotClientCommand(client, va("tell %d, %s", clientto, str)); } // end of the function EA_SayTeam //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_UseItem(int client, char *it) -{ - botimport.BotClientCommand(client, va("use %s", it)); -} //end of the function EA_UseItem +void EA_UseItem(int client, char *it) { botimport.BotClientCommand(client, va("use %s", it)); } // end of the function EA_UseItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_DropItem(int client, char *it) -{ - botimport.BotClientCommand(client, va("drop %s", it)); -} //end of the function EA_DropItem +void EA_DropItem(int client, char *it) { botimport.BotClientCommand(client, va("drop %s", it)); } // end of the function EA_DropItem //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_UseInv(int client, char *inv) -{ - botimport.BotClientCommand(client, va("invuse %s", inv)); -} //end of the function EA_UseInv +void EA_UseInv(int client, char *inv) { botimport.BotClientCommand(client, va("invuse %s", inv)); } // end of the function EA_UseInv //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_DropInv(int client, char *inv) -{ - botimport.BotClientCommand(client, va("invdrop %s", inv)); -} //end of the function EA_DropInv +void EA_DropInv(int client, char *inv) { botimport.BotClientCommand(client, va("invdrop %s", inv)); } // end of the function EA_DropInv //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Gesture(int client) -{ +void EA_Gesture(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_GESTURE; -} //end of the function EA_Gesture +} // end of the function EA_Gesture //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Command(int client, char *command) -{ - botimport.BotClientCommand(client, command); -} //end of the function EA_Command +void EA_Command(int client, char *command) { botimport.BotClientCommand(client, command); } // end of the function EA_Command //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_SelectWeapon(int client, int weapon) -{ +void EA_SelectWeapon(int client, int weapon) { bot_input_t *bi; bi = &botinputs[client]; bi->weapon = weapon; -} //end of the function EA_SelectWeapon +} // end of the function EA_SelectWeapon //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Attack(int client) -{ +void EA_Attack(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_ATTACK; -} //end of the function EA_Attack +} // end of the function EA_Attack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Alt_Attack(int client) -{ +void EA_Alt_Attack(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_ALT_ATTACK; -} //end of the function EA_Alt_Attack +} // end of the function EA_Alt_Attack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_ForcePower(int client) -{ +void EA_ForcePower(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_FORCEPOWER; -} //end of the function EA_ForcePower +} // end of the function EA_ForcePower //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Talk(int client) -{ +void EA_Talk(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_TALK; -} //end of the function EA_Talk +} // end of the function EA_Talk //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Use(int client) -{ +void EA_Use(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_USE; -} //end of the function EA_Use +} // end of the function EA_Use //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Respawn(int client) -{ +void EA_Respawn(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_RESPAWN; -} //end of the function EA_Respawn +} // end of the function EA_Respawn //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Jump(int client) -{ +void EA_Jump(int client) { bot_input_t *bi; bi = &botinputs[client]; - if (bi->actionflags & ACTION_JUMPEDLASTFRAME) - { + if (bi->actionflags & ACTION_JUMPEDLASTFRAME) { bi->actionflags &= ~ACTION_JUMP; - } //end if - else - { + } // end if + else { bi->actionflags |= ACTION_JUMP; - } //end if -} //end of the function EA_Jump + } // end if +} // end of the function EA_Jump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_DelayedJump(int client) -{ +void EA_DelayedJump(int client) { bot_input_t *bi; bi = &botinputs[client]; - if (bi->actionflags & ACTION_JUMPEDLASTFRAME) - { + if (bi->actionflags & ACTION_JUMPEDLASTFRAME) { bi->actionflags &= ~ACTION_DELAYEDJUMP; - } //end if - else - { + } // end if + else { bi->actionflags |= ACTION_DELAYEDJUMP; - } //end if -} //end of the function EA_DelayedJump + } // end if +} // end of the function EA_DelayedJump //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Crouch(int client) -{ +void EA_Crouch(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_CROUCH; -} //end of the function EA_Crouch +} // end of the function EA_Crouch //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Walk(int client) -{ +void EA_Walk(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_WALK; -} //end of the function EA_Walk +} // end of the function EA_Walk //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Action(int client, int action) -{ +void EA_Action(int client, int action) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= action; -} //end of function EA_Action +} // end of function EA_Action //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveUp(int client) -{ +void EA_MoveUp(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVEUP; -} //end of the function EA_MoveUp +} // end of the function EA_MoveUp //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveDown(int client) -{ +void EA_MoveDown(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVEDOWN; -} //end of the function EA_MoveDown +} // end of the function EA_MoveDown //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveForward(int client) -{ +void EA_MoveForward(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVEFORWARD; -} //end of the function EA_MoveForward +} // end of the function EA_MoveForward //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveBack(int client) -{ +void EA_MoveBack(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVEBACK; -} //end of the function EA_MoveBack +} // end of the function EA_MoveBack //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveLeft(int client) -{ +void EA_MoveLeft(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVELEFT; -} //end of the function EA_MoveLeft +} // end of the function EA_MoveLeft //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_MoveRight(int client) -{ +void EA_MoveRight(int client) { bot_input_t *bi; bi = &botinputs[client]; bi->actionflags |= ACTION_MOVERIGHT; -} //end of the function EA_MoveRight +} // end of the function EA_MoveRight //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Move(int client, vec3_t dir, float speed) -{ +void EA_Move(int client, vec3_t dir, float speed) { bot_input_t *bi; bi = &botinputs[client]; VectorCopy(dir, bi->dir); - //cap speed - if (speed > MAX_USERMOVE) speed = MAX_USERMOVE; - else if (speed < -MAX_USERMOVE) speed = -MAX_USERMOVE; + // cap speed + if (speed > MAX_USERMOVE) + speed = MAX_USERMOVE; + else if (speed < -MAX_USERMOVE) + speed = -MAX_USERMOVE; bi->speed = speed; -} //end of the function EA_Move +} // end of the function EA_Move //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_View(int client, vec3_t viewangles) -{ +void EA_View(int client, vec3_t viewangles) { bot_input_t *bi; bi = &botinputs[client]; VectorCopy(viewangles, bi->viewangles); -} //end of the function EA_View +} // end of the function EA_View //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_EndRegular(int client, float thinktime) -{ -} //end of the function EA_EndRegular +void EA_EndRegular(int client, float thinktime) {} // end of the function EA_EndRegular //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_GetInput(int client, float thinktime, bot_input_t *input) -{ +void EA_GetInput(int client, float thinktime, bot_input_t *input) { bot_input_t *bi; bi = &botinputs[client]; bi->thinktime = thinktime; Com_Memcpy(input, bi, sizeof(bot_input_t)); -} //end of the function EA_GetInput +} // end of the function EA_GetInput //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_ResetInput(int client) -{ +void EA_ResetInput(int client) { bot_input_t *bi; int jumped = qfalse; @@ -483,29 +432,27 @@ void EA_ResetInput(int client) bi->speed = 0; jumped = bi->actionflags & ACTION_JUMP; bi->actionflags = 0; - if (jumped) bi->actionflags |= ACTION_JUMPEDLASTFRAME; -} //end of the function EA_ResetInput + if (jumped) + bi->actionflags |= ACTION_JUMPEDLASTFRAME; +} // end of the function EA_ResetInput //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int EA_Setup(void) -{ - //initialize the bot inputs - botinputs = (bot_input_t *) GetClearedHunkMemory( - botlibglobals.maxclients * sizeof(bot_input_t)); +int EA_Setup(void) { + // initialize the bot inputs + botinputs = (bot_input_t *)GetClearedHunkMemory(botlibglobals.maxclients * sizeof(bot_input_t)); return BLERR_NOERROR; -} //end of the function EA_Setup +} // end of the function EA_Setup //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void EA_Shutdown(void) -{ +void EA_Shutdown(void) { FreeMemory(botinputs); botinputs = NULL; -} //end of the function EA_Shutdown +} // end of the function EA_Shutdown diff --git a/codemp/botlib/be_interface.cpp b/codemp/botlib/be_interface.cpp index 6d61da92a3..4758f5a874 100644 --- a/codemp/botlib/be_interface.cpp +++ b/codemp/botlib/be_interface.cpp @@ -57,14 +57,14 @@ along with this program; if not, see . #include "be_ai_char.h" #include "be_ai_gen.h" -//library globals in a structure +// library globals in a structure botlib_globals_t botlibglobals; botlib_export_t be_botlib_export; botlib_import_t botimport; // int botDeveloper; -//true if the library is setup +// true if the library is setup int botlibsetup = qfalse; //=========================================================================== @@ -79,58 +79,47 @@ int botlibsetup = qfalse; // Returns: - // Changes Globals: - //=========================================================================== -int Sys_MilliSeconds(void) -{ - return clock() * 1000 / CLOCKS_PER_SEC; -} //end of the function Sys_MilliSeconds +int Sys_MilliSeconds(void) { return clock() * 1000 / CLOCKS_PER_SEC; } // end of the function Sys_MilliSeconds //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean ValidClientNumber(int num, char *str) -{ - if (num < 0 || num > botlibglobals.maxclients) - { - //weird: the disabled stuff results in a crash - botimport.Print(PRT_ERROR, "%s: invalid client number %d, [0, %d]\n", - str, num, botlibglobals.maxclients); +qboolean ValidClientNumber(int num, char *str) { + if (num < 0 || num > botlibglobals.maxclients) { + // weird: the disabled stuff results in a crash + botimport.Print(PRT_ERROR, "%s: invalid client number %d, [0, %d]\n", str, num, botlibglobals.maxclients); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function BotValidateClientNumber +} // end of the function BotValidateClientNumber //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean ValidEntityNumber(int num, char *str) -{ - if (num < 0 || num > botlibglobals.maxentities) - { - botimport.Print(PRT_ERROR, "%s: invalid entity number %d, [0, %d]\n", - str, num, botlibglobals.maxentities); +qboolean ValidEntityNumber(int num, char *str) { + if (num < 0 || num > botlibglobals.maxentities) { + botimport.Print(PRT_ERROR, "%s: invalid entity number %d, [0, %d]\n", str, num, botlibglobals.maxentities); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function BotValidateClientNumber +} // end of the function BotValidateClientNumber //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean BotLibSetup(char *str) -{ - if (!botlibglobals.botlibsetup) - { +qboolean BotLibSetup(char *str) { + if (!botlibglobals.botlibsetup) { botimport.Print(PRT_ERROR, "%s: bot library used before being setup\n", str); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function BotLibSetup +} // end of the function BotLibSetup //=========================================================================== // @@ -138,17 +127,15 @@ qboolean BotLibSetup(char *str) // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibSetup(void) -{ - int errnum; +int Export_BotLibSetup(void) { + int errnum; botDeveloper = LibVarGetValue("bot_developer"); - memset( &botlibglobals, 0, sizeof(botlibglobals) ); // bk001207 - init - //initialize byte swapping (litte endian etc.) -// Swap_Init(); + memset(&botlibglobals, 0, sizeof(botlibglobals)); // bk001207 - init + // initialize byte swapping (litte endian etc.) + // Swap_Init(); - if(botDeveloper) - { + if (botDeveloper) { char *homedir, *gamedir, *basedir; char logfilename[MAX_OSPATH]; @@ -156,30 +143,34 @@ int Export_BotLibSetup(void) gamedir = LibVarGetString("gamedir"); basedir = LibVarGetString("com_basegame"); - if (*homedir) - { - if(*gamedir) + if (*homedir) { + if (*gamedir) Com_sprintf(logfilename, sizeof(logfilename), "%s%c%s%cbotlib.log", homedir, PATH_SEP, gamedir, PATH_SEP); - else if(*basedir) + else if (*basedir) Com_sprintf(logfilename, sizeof(logfilename), "%s%c%s%cbotlib.log", homedir, PATH_SEP, basedir, PATH_SEP); else - Com_sprintf(logfilename, sizeof(logfilename), "%s%c" "base" "%cbotlib.log", homedir, PATH_SEP, PATH_SEP); //fixme use BASEGAME define - } - else + Com_sprintf(logfilename, sizeof(logfilename), + "%s%c" + "base" + "%cbotlib.log", + homedir, PATH_SEP, PATH_SEP); // fixme use BASEGAME define + } else Com_sprintf(logfilename, sizeof(logfilename), "botlib.log"); Log_Open(logfilename); } // -// botimport.Print(PRT_MESSAGE, "------- BotLib Initialization -------\n"); + // botimport.Print(PRT_MESSAGE, "------- BotLib Initialization -------\n"); // - botlibglobals.maxclients = (int) LibVarValue("maxclients", "128"); - botlibglobals.maxentities = (int) LibVarValue("maxentities", "1024"); - - errnum = AAS_Setup(); //be_aas_main.c - if (errnum != BLERR_NOERROR) return errnum; - errnum = EA_Setup(); //be_ea.c - if (errnum != BLERR_NOERROR) return errnum; + botlibglobals.maxclients = (int)LibVarValue("maxclients", "128"); + botlibglobals.maxentities = (int)LibVarValue("maxentities", "1024"); + + errnum = AAS_Setup(); // be_aas_main.c + if (errnum != BLERR_NOERROR) + return errnum; + errnum = EA_Setup(); // be_ea.c + if (errnum != BLERR_NOERROR) + return errnum; /* errnum = BotSetupWeaponAI(); //be_ai_weap.c if (errnum != BLERR_NOERROR)return errnum; @@ -194,41 +185,41 @@ int Export_BotLibSetup(void) botlibglobals.botlibsetup = qtrue; return BLERR_NOERROR; -} //end of the function Export_BotLibSetup +} // end of the function Export_BotLibSetup //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibShutdown(void) -{ - if (!BotLibSetup("BotLibShutdown")) return BLERR_LIBRARYNOTSETUP; +int Export_BotLibShutdown(void) { + if (!BotLibSetup("BotLibShutdown")) + return BLERR_LIBRARYNOTSETUP; #ifndef DEMO - //DumpFileCRCs(); -#endif //DEMO + // DumpFileCRCs(); +#endif // DEMO // - BotShutdownChatAI(); //be_ai_chat.c - BotShutdownMoveAI(); //be_ai_move.c - BotShutdownGoalAI(); //be_ai_goal.c - BotShutdownWeaponAI(); //be_ai_weap.c - BotShutdownWeights(); //be_ai_weight.c - BotShutdownCharacters(); //be_ai_char.c - //shud down aas + BotShutdownChatAI(); // be_ai_chat.c + BotShutdownMoveAI(); // be_ai_move.c + BotShutdownGoalAI(); // be_ai_goal.c + BotShutdownWeaponAI(); // be_ai_weap.c + BotShutdownWeights(); // be_ai_weight.c + BotShutdownCharacters(); // be_ai_char.c + // shud down aas AAS_Shutdown(); - //shut down bot elemantary actions + // shut down bot elemantary actions EA_Shutdown(); - //free all libvars + // free all libvars LibVarDeAllocAll(); - //remove all global defines from the pre compiler + // remove all global defines from the pre compiler PC_RemoveAllGlobalDefines(); - //dump all allocated memory + // dump all allocated memory // DumpMemory(); #ifdef DEBUG PrintMemoryLabels(); #endif - //shut down library log file + // shut down library log file Log_Shutdown(); // botlibsetup = qfalse; @@ -237,66 +228,65 @@ int Export_BotLibShutdown(void) PC_CheckOpenSourceHandles(); // return BLERR_NOERROR; -} //end of the function Export_BotLibShutdown +} // end of the function Export_BotLibShutdown //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibVarSet(char *var_name, char *value) -{ +int Export_BotLibVarSet(char *var_name, char *value) { LibVarSet(var_name, value); return BLERR_NOERROR; -} //end of the function Export_BotLibVarSet +} // end of the function Export_BotLibVarSet //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibVarGet(char *var_name, char *value, int size) -{ +int Export_BotLibVarGet(char *var_name, char *value, int size) { char *varvalue; varvalue = LibVarGetString(var_name); - strncpy(value, varvalue, size-1); - value[size-1] = '\0'; + strncpy(value, varvalue, size - 1); + value[size - 1] = '\0'; return BLERR_NOERROR; -} //end of the function Export_BotLibVarGet +} // end of the function Export_BotLibVarGet //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibStartFrame(float time) -{ - if (!BotLibSetup("BotStartFrame")) return BLERR_LIBRARYNOTSETUP; +int Export_BotLibStartFrame(float time) { + if (!BotLibSetup("BotStartFrame")) + return BLERR_LIBRARYNOTSETUP; return AAS_StartFrame(time); -} //end of the function Export_BotLibStartFrame +} // end of the function Export_BotLibStartFrame //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibLoadMap(const char *mapname) -{ +int Export_BotLibLoadMap(const char *mapname) { #ifdef DEBUG int starttime = Sys_MilliSeconds(); #endif int errnum; - if (!BotLibSetup("BotLoadMap")) return BLERR_LIBRARYNOTSETUP; + if (!BotLibSetup("BotLoadMap")) + return BLERR_LIBRARYNOTSETUP; // botimport.Print(PRT_MESSAGE, "------------ Map Loading ------------\n"); - //startup AAS for the current map, model and sound index + // startup AAS for the current map, model and sound index errnum = AAS_LoadMap(mapname); - if (errnum != BLERR_NOERROR) return errnum; - //initialize the items in the level - BotInitLevelItems(); //be_ai_goal.h - BotSetBrushModelTypes(); //be_ai_move.h + if (errnum != BLERR_NOERROR) + return errnum; + // initialize the items in the level + BotInitLevelItems(); // be_ai_goal.h + BotSetBrushModelTypes(); // be_ai_move.h // botimport.Print(PRT_MESSAGE, "-------------------------------------\n"); #ifdef DEBUG @@ -304,20 +294,21 @@ int Export_BotLibLoadMap(const char *mapname) #endif // return BLERR_NOERROR; -} //end of the function Export_BotLibLoadMap +} // end of the function Export_BotLibLoadMap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int Export_BotLibUpdateEntity(int ent, bot_entitystate_t *state) -{ - if (!BotLibSetup("BotUpdateEntity")) return BLERR_LIBRARYNOTSETUP; - if (!ValidEntityNumber(ent, "BotUpdateEntity")) return BLERR_INVALIDENTITYNUMBER; +int Export_BotLibUpdateEntity(int ent, bot_entitystate_t *state) { + if (!BotLibSetup("BotUpdateEntity")) + return BLERR_LIBRARYNOTSETUP; + if (!ValidEntityNumber(ent, "BotUpdateEntity")) + return BLERR_INVALIDENTITYNUMBER; return AAS_UpdateEntity(ent, state); -} //end of the function Export_BotLibUpdateEntity +} // end of the function Export_BotLibUpdateEntity //=========================================================================== // // Parameter: - @@ -326,11 +317,8 @@ int Export_BotLibUpdateEntity(int ent, bot_entitystate_t *state) //=========================================================================== void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir); void ElevatorBottomCenter(aas_reachability_t *reach, vec3_t bottomcenter); -int BotGetReachabilityToGoal(vec3_t origin, int areanum, - int lastgoalareanum, int lastareanum, - int *avoidreach, float *avoidreachtimes, int *avoidreachtries, - bot_goal_t *goal, int travelflags, - struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags); +int BotGetReachabilityToGoal(vec3_t origin, int areanum, int lastgoalareanum, int lastareanum, int *avoidreach, float *avoidreachtimes, int *avoidreachtries, + bot_goal_t *goal, int travelflags, struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags); int AAS_PointLight(vec3_t origin, int *red, int *green, int *blue); @@ -344,35 +332,34 @@ float BotGapDistance(vec3_t origin, vec3_t hordir, int entnum); void AAS_FloodAreas(vec3_t origin); -int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) -{ +int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) { -// return AAS_PointLight(parm2, NULL, NULL, NULL); + // return AAS_PointLight(parm2, NULL, NULL, NULL); #ifdef DEBUG static int area = -1; static int line[2]; int newarea, i, highlightarea, flood; -// int reachnum; + // int reachnum; vec3_t eye, forward, right, end, origin; -// vec3_t bottomcenter; -// aas_trace_t trace; -// aas_face_t *face; -// aas_entity_t *ent; -// bsp_trace_t bsptrace; -// aas_reachability_t reach; -// bot_goal_t goal; + // vec3_t bottomcenter; + // aas_trace_t trace; + // aas_face_t *face; + // aas_entity_t *ent; + // bsp_trace_t bsptrace; + // aas_reachability_t reach; + // bot_goal_t goal; // clock_t start_time, end_time; vec3_t mins = {-16, -16, -24}; vec3_t maxs = {16, 16, 32}; -// int areas[10], numareas; + // int areas[10], numareas; + // return 0; - //return 0; - - if (!aasworld.loaded) return 0; + if (!aasworld.loaded) + return 0; /* if (parm0 & 1) @@ -382,76 +369,65 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) } //end if return 0; */ - for (i = 0; i < 2; i++) if (!line[i]) line[i] = botimport.DebugLineCreate(); + for (i = 0; i < 2; i++) + if (!line[i]) + line[i] = botimport.DebugLineCreate(); -// AAS_ClearShownDebugLines(); + // AAS_ClearShownDebugLines(); - //if (AAS_AgainstLadder(parm2)) botimport.Print(PRT_MESSAGE, "against ladder\n"); - //BotOnGround(parm2, PRESENCE_NORMAL, 1, &newarea, &newarea); - //botimport.Print(PRT_MESSAGE, "%f %f %f\n", parm2[0], parm2[1], parm2[2]); + // if (AAS_AgainstLadder(parm2)) botimport.Print(PRT_MESSAGE, "against ladder\n"); + // BotOnGround(parm2, PRESENCE_NORMAL, 1, &newarea, &newarea); + // botimport.Print(PRT_MESSAGE, "%f %f %f\n", parm2[0], parm2[1], parm2[2]); //* highlightarea = LibVarGetValue("bot_highlightarea"); - if (highlightarea > 0) - { + if (highlightarea > 0) { newarea = highlightarea; - } //end if - else - { + } // end if + else { VectorCopy(parm2, origin); origin[2] += 0.5; - //newarea = AAS_PointAreaNum(origin); + // newarea = AAS_PointAreaNum(origin); newarea = BotFuzzyPointReachabilityArea(origin); - } //end else + } // end else botimport.Print(PRT_MESSAGE, "\rtravel time to goal (%d) = %d ", botlibglobals.goalareanum, - AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT)); - //newarea = BotReachabilityArea(origin, qtrue); - if (newarea != area) - { + AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT)); + // newarea = BotReachabilityArea(origin, qtrue); + if (newarea != area) { botimport.Print(PRT_MESSAGE, "origin = %f, %f, %f\n", origin[0], origin[1], origin[2]); area = newarea; - botimport.Print(PRT_MESSAGE, "new area %d, cluster %d, presence type %d\n", - area, AAS_AreaCluster(area), AAS_PointPresenceType(origin)); + botimport.Print(PRT_MESSAGE, "new area %d, cluster %d, presence type %d\n", area, AAS_AreaCluster(area), AAS_PointPresenceType(origin)); botimport.Print(PRT_MESSAGE, "area contents: "); - if (aasworld.areasettings[area].contents & AREACONTENTS_WATER) - { + if (aasworld.areasettings[area].contents & AREACONTENTS_WATER) { botimport.Print(PRT_MESSAGE, "water &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_LAVA) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_LAVA) { botimport.Print(PRT_MESSAGE, "lava &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_SLIME) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_SLIME) { botimport.Print(PRT_MESSAGE, "slime &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_JUMPPAD) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_JUMPPAD) { botimport.Print(PRT_MESSAGE, "jump pad &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_CLUSTERPORTAL) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_CLUSTERPORTAL) { botimport.Print(PRT_MESSAGE, "cluster portal &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_VIEWPORTAL) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_VIEWPORTAL) { botimport.Print(PRT_MESSAGE, "view portal &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_DONOTENTER) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_DONOTENTER) { botimport.Print(PRT_MESSAGE, "do not enter &"); - } //end if - if (aasworld.areasettings[area].contents & AREACONTENTS_MOVER) - { + } // end if + if (aasworld.areasettings[area].contents & AREACONTENTS_MOVER) { botimport.Print(PRT_MESSAGE, "mover &"); - } //end if - if (!aasworld.areasettings[area].contents) - { + } // end if + if (!aasworld.areasettings[area].contents) { botimport.Print(PRT_MESSAGE, "empty"); - } //end if + } // end if botimport.Print(PRT_MESSAGE, "\n"); botimport.Print(PRT_MESSAGE, "travel time to goal (%d) = %d\n", botlibglobals.goalareanum, - AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT|TFL_ROCKETJUMP)); + AAS_AreaTravelTimeToGoalArea(newarea, origin, botlibglobals.goalareanum, TFL_DEFAULT | TFL_ROCKETJUMP)); /* VectorCopy(origin, end); end[2] += 5; @@ -465,68 +441,63 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) botimport.Print(PRT_MESSAGE, "new goal %2.1f %2.1f %2.1f area %d\n", origin[0], origin[1], origin[2], newarea); */ - } //end if + } // end if //* flood = LibVarGetValue("bot_flood"); - if (parm0 & 1) - { - if (flood) - { + if (parm0 & 1) { + if (flood) { AAS_ClearShownPolygons(); AAS_ClearShownDebugLines(); AAS_FloodAreas(parm2); - } - else - { + } else { botlibglobals.goalareanum = newarea; VectorCopy(parm2, botlibglobals.goalorigin); - botimport.Print(PRT_MESSAGE, "new goal %2.1f %2.1f %2.1f area %d\n", - origin[0], origin[1], origin[2], newarea); + botimport.Print(PRT_MESSAGE, "new goal %2.1f %2.1f %2.1f area %d\n", origin[0], origin[1], origin[2], newarea); } - } //end if*/ + } // end if*/ if (flood) return 0; -// if (parm0 & BUTTON_USE) -// { -// botlibglobals.runai = !botlibglobals.runai; -// if (botlibglobals.runai) botimport.Print(PRT_MESSAGE, "started AI\n"); -// else botimport.Print(PRT_MESSAGE, "stopped AI\n"); - //* / - /* - goal.areanum = botlibglobals.goalareanum; - reachnum = BotGetReachabilityToGoal(parm2, newarea, 1, - ms.avoidreach, ms.avoidreachtimes, - &goal, TFL_DEFAULT); - if (!reachnum) + // if (parm0 & BUTTON_USE) + // { + // botlibglobals.runai = !botlibglobals.runai; + // if (botlibglobals.runai) botimport.Print(PRT_MESSAGE, "started AI\n"); + // else botimport.Print(PRT_MESSAGE, "stopped AI\n"); + //* / + /* + goal.areanum = botlibglobals.goalareanum; + reachnum = BotGetReachabilityToGoal(parm2, newarea, 1, + ms.avoidreach, ms.avoidreachtimes, + &goal, TFL_DEFAULT); + if (!reachnum) + { + botimport.Print(PRT_MESSAGE, "goal not reachable\n"); + } //end if + else + { + AAS_ReachabilityFromNum(reachnum, &reach); + AAS_ClearShownDebugLines(); + AAS_ShowArea(area, qtrue); + AAS_ShowArea(reach.areanum, qtrue); + AAS_DrawCross(reach.start, 6, LINECOLOR_BLUE); + AAS_DrawCross(reach.end, 6, LINECOLOR_RED); + // + if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) { - botimport.Print(PRT_MESSAGE, "goal not reachable\n"); + ElevatorBottomCenter(&reach, bottomcenter); + AAS_DrawCross(bottomcenter, 10, LINECOLOR_GREEN); } //end if - else + } //end else*/ + // botimport.Print(PRT_MESSAGE, "travel time to goal = %d\n", + // AAS_AreaTravelTimeToGoalArea(area, origin, botlibglobals.goalareanum, TFL_DEFAULT)); + // botimport.Print(PRT_MESSAGE, "test rj from 703 to 716\n"); + // AAS_Reachability_WeaponJump(703, 716); + // } //end if*/ + + /* face = AAS_AreaGroundFace(newarea, parm2); + if (face) { - AAS_ReachabilityFromNum(reachnum, &reach); - AAS_ClearShownDebugLines(); - AAS_ShowArea(area, qtrue); - AAS_ShowArea(reach.areanum, qtrue); - AAS_DrawCross(reach.start, 6, LINECOLOR_BLUE); - AAS_DrawCross(reach.end, 6, LINECOLOR_RED); - // - if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR) - { - ElevatorBottomCenter(&reach, bottomcenter); - AAS_DrawCross(bottomcenter, 10, LINECOLOR_GREEN); - } //end if - } //end else*/ -// botimport.Print(PRT_MESSAGE, "travel time to goal = %d\n", -// AAS_AreaTravelTimeToGoalArea(area, origin, botlibglobals.goalareanum, TFL_DEFAULT)); -// botimport.Print(PRT_MESSAGE, "test rj from 703 to 716\n"); -// AAS_Reachability_WeaponJump(703, 716); -// } //end if*/ - -/* face = AAS_AreaGroundFace(newarea, parm2); - if (face) - { - AAS_ShowFace(face - aasworld.faces); - } //end if*/ + AAS_ShowFace(face - aasworld.faces); + } //end if*/ /* AAS_ClearShownDebugLines(); AAS_ShowArea(newarea, parm0 & BUTTON_USE); @@ -535,9 +506,9 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) AAS_ClearShownPolygons(); AAS_ClearShownDebugLines(); AAS_ShowAreaPolygons(newarea, 1, parm0 & 4); - if (parm0 & 2) AAS_ShowReachableAreas(area); - else - { + if (parm0 & 2) + AAS_ShowReachableAreas(area); + else { static int lastgoalareanum, lastareanum; static int avoidreach[MAX_AVOIDREACH]; static float avoidreachtimes[MAX_AVOIDREACH]; @@ -564,24 +535,21 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) VectorCopy(botlibglobals.goalorigin, goal.origin); VectorCopy(origin, curorigin); curarea = newarea; - for ( i = 0; i < 100; i++ ) { - if ( curarea == goal.areanum ) { + for (i = 0; i < 100; i++) { + if (curarea == goal.areanum) { break; } - reachnum = BotGetReachabilityToGoal(curorigin, curarea, - lastgoalareanum, lastareanum, - avoidreach, avoidreachtimes, avoidreachtries, - &goal, TFL_DEFAULT|TFL_FUNCBOB|TFL_ROCKETJUMP, - NULL, 0, &resultFlags); + reachnum = BotGetReachabilityToGoal(curorigin, curarea, lastgoalareanum, lastareanum, avoidreach, avoidreachtimes, avoidreachtries, &goal, + TFL_DEFAULT | TFL_FUNCBOB | TFL_ROCKETJUMP, NULL, 0, &resultFlags); AAS_ReachabilityFromNum(reachnum, &reach); AAS_ShowReachability(&reach); VectorCopy(reach.end, origin); lastareanum = curarea; curarea = reach.areanum; } - } //end else + } // end else VectorClear(forward); - //BotGapDistance(origin, forward, 0); + // BotGapDistance(origin, forward, 0); /* if (parm0 & BUTTON_USE) { @@ -590,47 +558,47 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) } //end if*/ AngleVectors(parm3, forward, right, NULL); - //get the eye 16 units to the right of the origin + // get the eye 16 units to the right of the origin VectorMA(parm2, 8, right, eye); - //get the eye 24 units up + // get the eye 24 units up eye[2] += 24; - //get the end point for the line to be traced + // get the end point for the line to be traced VectorMA(eye, 800, forward, end); -// AAS_TestMovementPrediction(1, parm2, forward); -/* - //trace the line to find the hit point - trace = AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1); - if (!line[0]) line[0] = botimport.DebugLineCreate(); - botimport.DebugLineShow(line[0], eye, trace.endpos, LINECOLOR_BLUE); - // - AAS_ClearShownDebugLines(); - if (trace.ent) - { - ent = &aasworld.entities[trace.ent]; - AAS_ShowBoundingBox(ent->origin, ent->mins, ent->maxs); - } //end if -*/ + // AAS_TestMovementPrediction(1, parm2, forward); + /* + //trace the line to find the hit point + trace = AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1); + if (!line[0]) line[0] = botimport.DebugLineCreate(); + botimport.DebugLineShow(line[0], eye, trace.endpos, LINECOLOR_BLUE); + // + AAS_ClearShownDebugLines(); + if (trace.ent) + { + ent = &aasworld.entities[trace.ent]; + AAS_ShowBoundingBox(ent->origin, ent->mins, ent->maxs); + } //end if + */ -/* - start_time = clock(); - for (i = 0; i < 2000; i++) - { - AAS_Trace2(eye, mins, maxs, end, 1, MASK_PLAYERSOLID); -// AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1); - } //end for - end_time = clock(); - botimport.Print(PRT_MESSAGE, "me %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC); - start_time = clock(); - for (i = 0; i < 2000; i++) - { - AAS_Trace(eye, mins, maxs, end, 1, MASK_PLAYERSOLID); - } //end for - end_time = clock(); - botimport.Print(PRT_MESSAGE, "id %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC); -*/ + /* + start_time = clock(); + for (i = 0; i < 2000; i++) + { + AAS_Trace2(eye, mins, maxs, end, 1, MASK_PLAYERSOLID); + // AAS_TraceClientBBox(eye, end, PRESENCE_NORMAL, 1); + } //end for + end_time = clock(); + botimport.Print(PRT_MESSAGE, "me %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC); + start_time = clock(); + for (i = 0; i < 2000; i++) + { + AAS_Trace(eye, mins, maxs, end, 1, MASK_PLAYERSOLID); + } //end for + end_time = clock(); + botimport.Print(PRT_MESSAGE, "id %lu clocks, %lu CLOCKS_PER_SEC\n", end_time - start_time, CLOCKS_PER_SEC); + */ - // TTimo: nested comments are BAD for gcc -Werror, use #if 0 instead.. + // TTimo: nested comments are BAD for gcc -Werror, use #if 0 instead.. #if 0 AAS_ClearShownDebugLines(); //bsptrace = AAS_Trace(eye, NULL, NULL, end, 1, MASK_PLAYERSOLID); @@ -673,15 +641,14 @@ int BotExportTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) #endif #endif return 0; -} //end of the function BotExportTest - +} // end of the function BotExportTest /* ============ Init_AAS_Export ============ */ -static void Init_AAS_Export( aas_export_t *aas ) { +static void Init_AAS_Export(aas_export_t *aas) { //-------------------------------------------- // be_aas_entity.c //-------------------------------------------- @@ -730,14 +697,13 @@ static void Init_AAS_Export( aas_export_t *aas ) { aas->AAS_PredictClientMovement = AAS_PredictClientMovement; } - /* ============ Init_EA_Export ============ */ -static void Init_EA_Export( ea_export_t *ea ) { - //ClientCommand elementary actions +static void Init_EA_Export(ea_export_t *ea) { + // ClientCommand elementary actions ea->EA_Command = EA_Command; ea->EA_Say = EA_Say; ea->EA_SayTeam = EA_SayTeam; @@ -768,13 +734,12 @@ static void Init_EA_Export( ea_export_t *ea ) { ea->EA_ResetInput = EA_ResetInput; } - /* ============ Init_AI_Export ============ */ -static void Init_AI_Export( ai_export_t *ai ) { +static void Init_AI_Export(ai_export_t *ai) { //----------------------------------- // be_ai_char.h //----------------------------------- @@ -870,21 +835,20 @@ static void Init_AI_Export( ai_export_t *ai ) { ai->GeneticParentsAndChildSelection = GeneticParentsAndChildSelection; } - /* ============ GetBotLibAPI ============ */ botlib_export_t *GetBotLibAPI(int apiVersion, botlib_import_t *import) { - assert(import); // bk001129 - this wasn't set for base/ - botimport = *import; - assert(botimport.Print); // bk001129 - pars pro toto + assert(import); // bk001129 - this wasn't set for base/ + botimport = *import; + assert(botimport.Print); // bk001129 - pars pro toto - Com_Memset( &be_botlib_export, 0, sizeof( be_botlib_export ) ); + Com_Memset(&be_botlib_export, 0, sizeof(be_botlib_export)); - if ( apiVersion != BOTLIB_API_VERSION ) { - botimport.Print( PRT_ERROR, "Mismatched BOTLIB_API_VERSION: expected %i, got %i\n", BOTLIB_API_VERSION, apiVersion ); + if (apiVersion != BOTLIB_API_VERSION) { + botimport.Print(PRT_ERROR, "Mismatched BOTLIB_API_VERSION: expected %i, got %i\n", BOTLIB_API_VERSION, apiVersion); return NULL; } diff --git a/codemp/botlib/l_crc.cpp b/codemp/botlib/l_crc.cpp index d542eea4dc..6e7c8ea82c 100644 --- a/codemp/botlib/l_crc.cpp +++ b/codemp/botlib/l_crc.cpp @@ -40,54 +40,33 @@ along with this program; if not, see . #include "qcommon/q_shared.h" #include "botlib.h" -#include "be_interface.h" //for botimport.Print +#include "be_interface.h" //for botimport.Print #include "l_crc.h" - // FIXME: byte swap? // this is a 16 bit, non-reflected CRC using the polynomial 0x1021 // and the initial and final xor values shown below... in other words, the // CCITT standard CRC used by XMODEM -#define CRC_INIT_VALUE 0xffff -#define CRC_XOR_VALUE 0x0000 - -unsigned short crctable[257] = -{ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -}; +#define CRC_INIT_VALUE 0xffff +#define CRC_XOR_VALUE 0x0000 + +unsigned short crctable[257] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, + 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, + 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, + 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, + 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, + 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, + 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, + 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, + 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, + 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, + 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, + 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, + 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0}; //=========================================================================== // @@ -95,63 +74,53 @@ unsigned short crctable[257] = // Returns: - // Changes Globals: - //=========================================================================== -void CRC_Init(unsigned short *crcvalue) -{ - *crcvalue = CRC_INIT_VALUE; -} //end of the function CRC_Init +void CRC_Init(unsigned short *crcvalue) { *crcvalue = CRC_INIT_VALUE; } // end of the function CRC_Init //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void CRC_ProcessByte(unsigned short *crcvalue, byte data) -{ +void CRC_ProcessByte(unsigned short *crcvalue, byte data) { *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data]; -} //end of the function CRC_ProcessByte +} // end of the function CRC_ProcessByte //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -unsigned short CRC_Value(unsigned short crcvalue) -{ - return crcvalue ^ CRC_XOR_VALUE; -} //end of the function CRC_Value +unsigned short CRC_Value(unsigned short crcvalue) { return crcvalue ^ CRC_XOR_VALUE; } // end of the function CRC_Value //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -unsigned short CRC_ProcessString(unsigned char *data, int length) -{ +unsigned short CRC_ProcessString(unsigned char *data, int length) { unsigned short crcvalue; int i, ind; CRC_Init(&crcvalue); - for (i = 0; i < length; i++) - { + for (i = 0; i < length; i++) { ind = (crcvalue >> 8) ^ data[i]; - if (ind < 0 || ind > 256) ind = 0; + if (ind < 0 || ind > 256) + ind = 0; crcvalue = (crcvalue << 8) ^ crctable[ind]; - } //end for + } // end for return CRC_Value(crcvalue); -} //end of the function CRC_ProcessString +} // end of the function CRC_ProcessString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void CRC_ContinueProcessString(unsigned short *crc, char *data, int length) -{ +void CRC_ContinueProcessString(unsigned short *crc, char *data, int length) { int i; - for (i = 0; i < length; i++) - { + for (i = 0; i < length; i++) { *crc = (*crc << 8) ^ crctable[(*crc >> 8) ^ data[i]]; - } //end for -} //end of the function CRC_ProcessString + } // end for +} // end of the function CRC_ProcessString diff --git a/codemp/botlib/l_libvar.cpp b/codemp/botlib/l_libvar.cpp index a27e93a762..fc401eaccd 100644 --- a/codemp/botlib/l_libvar.cpp +++ b/codemp/botlib/l_libvar.cpp @@ -38,7 +38,7 @@ along with this program; if not, see . #include "l_memory.h" #include "l_libvar.h" -//list with library variables +// list with library variables libvar_t *libvarlist = NULL; //=========================================================================== @@ -47,254 +47,225 @@ libvar_t *libvarlist = NULL; // Returns: - // Changes Globals: - //=========================================================================== -float LibVarStringValue(char *string) -{ +float LibVarStringValue(char *string) { int dotfound = 0; float value = 0; - while(*string) - { - if (*string < '0' || *string > '9') - { - if (dotfound || *string != '.') - { + while (*string) { + if (*string < '0' || *string > '9') { + if (dotfound || *string != '.') { return 0; - } //end if - else - { + } // end if + else { dotfound = 10; string++; - } //end if - } //end if - if (dotfound) - { - value = value + (float) (*string - '0') / (float) dotfound; + } // end if + } // end if + if (dotfound) { + value = value + (float)(*string - '0') / (float)dotfound; dotfound *= 10; - } //end if - else - { - value = value * 10.0 + (float) (*string - '0'); - } //end else + } // end if + else { + value = value * 10.0 + (float)(*string - '0'); + } // end else string++; - } //end while + } // end while return value; -} //end of the function LibVarStringValue +} // end of the function LibVarStringValue //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -libvar_t *LibVarAlloc(char *var_name) -{ +libvar_t *LibVarAlloc(char *var_name) { libvar_t *v; - v = (libvar_t *) GetMemory(sizeof(libvar_t)); + v = (libvar_t *)GetMemory(sizeof(libvar_t)); Com_Memset(v, 0, sizeof(libvar_t)); - v->name = (char *) GetMemory(strlen(var_name)+1); + v->name = (char *)GetMemory(strlen(var_name) + 1); strcpy(v->name, var_name); - //add the variable in the list + // add the variable in the list v->next = libvarlist; libvarlist = v; return v; -} //end of the function LibVarAlloc +} // end of the function LibVarAlloc //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void LibVarDeAlloc(libvar_t *v) -{ - if (v->string) FreeMemory(v->string); +void LibVarDeAlloc(libvar_t *v) { + if (v->string) + FreeMemory(v->string); FreeMemory(v->name); FreeMemory(v); -} //end of the function LibVarDeAlloc +} // end of the function LibVarDeAlloc //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void LibVarDeAllocAll(void) -{ +void LibVarDeAllocAll(void) { libvar_t *v; - for (v = libvarlist; v; v = libvarlist) - { + for (v = libvarlist; v; v = libvarlist) { libvarlist = libvarlist->next; LibVarDeAlloc(v); - } //end for + } // end for libvarlist = NULL; -} //end of the function LibVarDeAllocAll +} // end of the function LibVarDeAllocAll //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -libvar_t *LibVarGet(char *var_name) -{ +libvar_t *LibVarGet(char *var_name) { libvar_t *v; - for (v = libvarlist; v; v = v->next) - { - if (!Q_stricmp(v->name, var_name)) - { + for (v = libvarlist; v; v = v->next) { + if (!Q_stricmp(v->name, var_name)) { return v; - } //end if - } //end for + } // end if + } // end for return NULL; -} //end of the function LibVarGet +} // end of the function LibVarGet //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -char *LibVarGetString(char *var_name) -{ +char *LibVarGetString(char *var_name) { libvar_t *v; v = LibVarGet(var_name); - if (v) - { + if (v) { return v->string; - } //end if - else - { + } // end if + else { return ""; - } //end else -} //end of the function LibVarGetString + } // end else +} // end of the function LibVarGetString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float LibVarGetValue(char *var_name) -{ +float LibVarGetValue(char *var_name) { libvar_t *v; v = LibVarGet(var_name); - if (v) - { + if (v) { return v->value; - } //end if - else - { + } // end if + else { return 0; - } //end else -} //end of the function LibVarGetValue + } // end else +} // end of the function LibVarGetValue //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -libvar_t *LibVar(char *var_name, char *value) -{ +libvar_t *LibVar(char *var_name, char *value) { libvar_t *v; v = LibVarGet(var_name); - if (v) return v; - //create new variable + if (v) + return v; + // create new variable v = LibVarAlloc(var_name); - //variable string - v->string = (char *) GetMemory(strlen(value) + 1); + // variable string + v->string = (char *)GetMemory(strlen(value) + 1); strcpy(v->string, value); - //the value + // the value v->value = LibVarStringValue(v->string); - //variable is modified + // variable is modified v->modified = qtrue; // return v; -} //end of the function LibVar +} // end of the function LibVar //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -char *LibVarString(char *var_name, char *value) -{ +char *LibVarString(char *var_name, char *value) { libvar_t *v; v = LibVar(var_name, value); return v->string; -} //end of the function LibVarString +} // end of the function LibVarString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -float LibVarValue(char *var_name, char *value) -{ +float LibVarValue(char *var_name, char *value) { libvar_t *v; v = LibVar(var_name, value); return v->value; -} //end of the function LibVarValue +} // end of the function LibVarValue //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void LibVarSet(char *var_name, char *value) -{ +void LibVarSet(char *var_name, char *value) { libvar_t *v; v = LibVarGet(var_name); - if (v) - { + if (v) { FreeMemory(v->string); - } //end if - else - { + } // end if + else { v = LibVarAlloc(var_name); - } //end else - //variable string - v->string = (char *) GetMemory(strlen(value) + 1); + } // end else + // variable string + v->string = (char *)GetMemory(strlen(value) + 1); strcpy(v->string, value); - //the value + // the value v->value = LibVarStringValue(v->string); - //variable is modified + // variable is modified v->modified = qtrue; -} //end of the function LibVarSet +} // end of the function LibVarSet //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean LibVarChanged(char *var_name) -{ +qboolean LibVarChanged(char *var_name) { libvar_t *v; v = LibVarGet(var_name); - if (v) - { + if (v) { return v->modified; - } //end if - else - { + } // end if + else { return qfalse; - } //end else -} //end of the function LibVarChanged + } // end else +} // end of the function LibVarChanged //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void LibVarSetNotModified(char *var_name) -{ +void LibVarSetNotModified(char *var_name) { libvar_t *v; v = LibVarGet(var_name); - if (v) - { + if (v) { v->modified = qfalse; - } //end if -} //end of the function LibVarSetNotModified + } // end if +} // end of the function LibVarSetNotModified diff --git a/codemp/botlib/l_log.cpp b/codemp/botlib/l_log.cpp index 0a977ee6bb..338e58feb4 100644 --- a/codemp/botlib/l_log.cpp +++ b/codemp/botlib/l_log.cpp @@ -40,14 +40,13 @@ along with this program; if not, see . #include "qcommon/q_shared.h" #include "botlib.h" -#include "be_interface.h" //for botimport.Print +#include "be_interface.h" //for botimport.Print #include "l_libvar.h" #include "l_log.h" -#define MAX_LOGFILENAMESIZE 1024 +#define MAX_LOGFILENAMESIZE 1024 -typedef struct logfile_s -{ +typedef struct logfile_s { char filename[MAX_LOGFILENAMESIZE]; FILE *fp; int numwrites; @@ -61,115 +60,102 @@ static logfile_t logfile; // Returns: - // Changes Globals: - //=========================================================================== -void Log_Open(char *filename) -{ - if (!LibVarValue("log", "0")) return; - if (!filename || !strlen(filename)) - { +void Log_Open(char *filename) { + if (!LibVarValue("log", "0")) + return; + if (!filename || !strlen(filename)) { botimport.Print(PRT_MESSAGE, "openlog \n"); return; - } //end if - if (logfile.fp) - { + } // end if + if (logfile.fp) { botimport.Print(PRT_ERROR, "log file %s is already opened\n", logfile.filename); return; - } //end if + } // end if logfile.fp = fopen(filename, "wb"); - if (!logfile.fp) - { + if (!logfile.fp) { botimport.Print(PRT_ERROR, "can't open the log file %s\n", filename); return; - } //end if + } // end if strncpy(logfile.filename, filename, MAX_LOGFILENAMESIZE); botimport.Print(PRT_MESSAGE, "Opened log %s\n", logfile.filename); -} //end of the function Log_Create +} // end of the function Log_Create //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void Log_Close(void) -{ - if (!logfile.fp) return; - if (fclose(logfile.fp)) - { +void Log_Close(void) { + if (!logfile.fp) + return; + if (fclose(logfile.fp)) { botimport.Print(PRT_ERROR, "can't close log file %s\n", logfile.filename); return; - } //end if + } // end if logfile.fp = NULL; botimport.Print(PRT_MESSAGE, "Closed log %s\n", logfile.filename); -} //end of the function Log_Close +} // end of the function Log_Close //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void Log_Shutdown(void) -{ - if (logfile.fp) Log_Close(); -} //end of the function Log_Shutdown +void Log_Shutdown(void) { + if (logfile.fp) + Log_Close(); +} // end of the function Log_Shutdown //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void QDECL Log_Write(char *fmt, ...) -{ +void QDECL Log_Write(char *fmt, ...) { va_list ap; - if (!logfile.fp) return; + if (!logfile.fp) + return; va_start(ap, fmt); vfprintf(logfile.fp, fmt, ap); va_end(ap); - //fprintf(logfile.fp, "\r\n"); + // fprintf(logfile.fp, "\r\n"); fflush(logfile.fp); -} //end of the function Log_Write +} // end of the function Log_Write //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void QDECL Log_WriteTimeStamped(char *fmt, ...) -{ +void QDECL Log_WriteTimeStamped(char *fmt, ...) { va_list ap; - if (!logfile.fp) return; - fprintf(logfile.fp, "%d %02d:%02d:%02d:%02d ", - logfile.numwrites, - (int) (botlibglobals.time / 60 / 60), - (int) (botlibglobals.time / 60), - (int) (botlibglobals.time), - (int) ((int) (botlibglobals.time * 100)) - - ((int) botlibglobals.time) * 100); + if (!logfile.fp) + return; + fprintf(logfile.fp, "%d %02d:%02d:%02d:%02d ", logfile.numwrites, (int)(botlibglobals.time / 60 / 60), (int)(botlibglobals.time / 60), + (int)(botlibglobals.time), (int)((int)(botlibglobals.time * 100)) - ((int)botlibglobals.time) * 100); va_start(ap, fmt); vfprintf(logfile.fp, fmt, ap); va_end(ap); fprintf(logfile.fp, "\r\n"); logfile.numwrites++; fflush(logfile.fp); -} //end of the function Log_Write +} // end of the function Log_Write //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -FILE *Log_FilePointer(void) -{ - return logfile.fp; -} //end of the function Log_FilePointer +FILE *Log_FilePointer(void) { return logfile.fp; } // end of the function Log_FilePointer //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void Log_Flush(void) -{ - if (logfile.fp) fflush(logfile.fp); -} //end of the function Log_Flush - +void Log_Flush(void) { + if (logfile.fp) + fflush(logfile.fp); +} // end of the function Log_Flush diff --git a/codemp/botlib/l_memory.cpp b/codemp/botlib/l_memory.cpp index 569d398491..3cfe61e56e 100644 --- a/codemp/botlib/l_memory.cpp +++ b/codemp/botlib/l_memory.cpp @@ -44,8 +44,8 @@ along with this program; if not, see . //#define MEMDEBUG //#define MEMORYMANEGER -#define MEM_ID 0x12345678l -#define HUNK_ID 0x87654321l +#define MEM_ID 0x12345678l +#define HUNK_ID 0x87654321l int allocatedmemory; int totalmemorysize; @@ -53,8 +53,7 @@ int numblocks; #ifdef MEMORYMANEGER -typedef struct memoryblock_s -{ +typedef struct memoryblock_s { unsigned long int id; void *ptr; int size; @@ -62,7 +61,7 @@ typedef struct memoryblock_s char *label; char *file; int line; -#endif //MEMDEBUG +#endif // MEMDEBUG struct memoryblock_s *prev, *next; } memoryblock_t; @@ -74,25 +73,27 @@ memoryblock_t *memory; // Returns: - // Changes Globals: - //=========================================================================== -void LinkMemoryBlock(memoryblock_t *block) -{ +void LinkMemoryBlock(memoryblock_t *block) { block->prev = NULL; block->next = memory; - if (memory) memory->prev = block; + if (memory) + memory->prev = block; memory = block; -} //end of the function LinkMemoryBlock +} // end of the function LinkMemoryBlock //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void UnlinkMemoryBlock(memoryblock_t *block) -{ - if (block->prev) block->prev->next = block->next; - else memory = block->next; - if (block->next) block->next->prev = block->prev; -} //end of the function UnlinkMemoryBlock +void UnlinkMemoryBlock(memoryblock_t *block) { + if (block->prev) + block->prev->next = block->next; + else + memory = block->next; + if (block->next) + block->next->prev = block->prev; +} // end of the function UnlinkMemoryBlock //=========================================================================== // // Parameter: - @@ -103,27 +104,27 @@ void UnlinkMemoryBlock(memoryblock_t *block) void *GetMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; memoryblock_t *block; - assert(botimport.GetMemory); // bk001129 - was NULL'ed + assert(botimport.GetMemory); // bk001129 - was NULL'ed ptr = botimport.GetMemory(size + sizeof(memoryblock_t)); - block = (memoryblock_t *) ptr; + block = (memoryblock_t *)ptr; block->id = MEM_ID; - block->ptr = (char *) ptr + sizeof(memoryblock_t); + block->ptr = (char *)ptr + sizeof(memoryblock_t); block->size = size + sizeof(memoryblock_t); #ifdef MEMDEBUG block->label = label; block->file = file; block->line = line; -#endif //MEMDEBUG +#endif // MEMDEBUG LinkMemoryBlock(block); allocatedmemory += block->size; totalmemorysize += block->size + sizeof(memoryblock_t); numblocks++; return block->ptr; -} //end of the function GetMemoryDebug +} // end of the function GetMemoryDebug //=========================================================================== // // Parameter: - @@ -134,17 +135,17 @@ void *GetMemory(unsigned long size) void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetClearedMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; #ifdef MEMDEBUG ptr = GetMemoryDebug(size, label, file, line); #else ptr = GetMemory(size); -#endif //MEMDEBUG +#endif // MEMDEBUG Com_Memset(ptr, 0, size); return ptr; -} //end of the function GetClearedMemory +} // end of the function GetClearedMemory //=========================================================================== // // Parameter: - @@ -155,27 +156,27 @@ void *GetClearedMemory(unsigned long size) void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetHunkMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; memoryblock_t *block; ptr = botimport.HunkAlloc(size + sizeof(memoryblock_t)); - block = (memoryblock_t *) ptr; + block = (memoryblock_t *)ptr; block->id = HUNK_ID; - block->ptr = (char *) ptr + sizeof(memoryblock_t); + block->ptr = (char *)ptr + sizeof(memoryblock_t); block->size = size + sizeof(memoryblock_t); #ifdef MEMDEBUG block->label = label; block->file = file; block->line = line; -#endif //MEMDEBUG +#endif // MEMDEBUG LinkMemoryBlock(block); allocatedmemory += block->size; totalmemorysize += block->size + sizeof(memoryblock_t); numblocks++; return block->ptr; -} //end of the function GetHunkMemoryDebug +} // end of the function GetHunkMemoryDebug //=========================================================================== // // Parameter: - @@ -186,115 +187,105 @@ void *GetHunkMemory(unsigned long size) void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetClearedHunkMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; #ifdef MEMDEBUG ptr = GetHunkMemoryDebug(size, label, file, line); #else ptr = GetHunkMemory(size); -#endif //MEMDEBUG +#endif // MEMDEBUG Com_Memset(ptr, 0, size); return ptr; -} //end of the function GetClearedHunkMemory +} // end of the function GetClearedHunkMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -memoryblock_t *BlockFromPointer(void *ptr, char *str) -{ +memoryblock_t *BlockFromPointer(void *ptr, char *str) { memoryblock_t *block; - if (!ptr) - { + if (!ptr) { #ifdef MEMDEBUG - //char *crash = (char *) NULL; - //crash[0] = 1; + // char *crash = (char *) NULL; + // crash[0] = 1; botimport.Print(PRT_FATAL, "%s: NULL pointer\n", str); #endif // MEMDEBUG return NULL; - } //end if - block = (memoryblock_t *) ((char *) ptr - sizeof(memoryblock_t)); - if (block->id != MEM_ID && block->id != HUNK_ID) - { + } // end if + block = (memoryblock_t *)((char *)ptr - sizeof(memoryblock_t)); + if (block->id != MEM_ID && block->id != HUNK_ID) { botimport.Print(PRT_FATAL, "%s: invalid memory block\n", str); return NULL; - } //end if - if (block->ptr != ptr) - { + } // end if + if (block->ptr != ptr) { botimport.Print(PRT_FATAL, "%s: memory block pointer invalid\n", str); return NULL; - } //end if + } // end if return block; -} //end of the function BlockFromPointer +} // end of the function BlockFromPointer //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeMemory(void *ptr) -{ +void FreeMemory(void *ptr) { memoryblock_t *block; block = BlockFromPointer(ptr, "FreeMemory"); - if (!block) return; + if (!block) + return; UnlinkMemoryBlock(block); allocatedmemory -= block->size; totalmemorysize -= block->size + sizeof(memoryblock_t); numblocks--; // - if (block->id == MEM_ID) - { + if (block->id == MEM_ID) { botimport.FreeMemory(block); - } //end if -} //end of the function FreeMemory + } // end if +} // end of the function FreeMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AvailableMemory(void) -{ - return botimport.AvailableMemory(); -} //end of the function AvailableMemory +int AvailableMemory(void) { return botimport.AvailableMemory(); } // end of the function AvailableMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int MemoryByteSize(void *ptr) -{ +int MemoryByteSize(void *ptr) { memoryblock_t *block; block = BlockFromPointer(ptr, "MemoryByteSize"); - if (!block) return 0; + if (!block) + return 0; return block->size; -} //end of the function MemoryByteSize +} // end of the function MemoryByteSize //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void PrintUsedMemorySize(void) -{ +void PrintUsedMemorySize(void) { botimport.Print(PRT_MESSAGE, "total allocated memory: %d KB\n", allocatedmemory >> 10); botimport.Print(PRT_MESSAGE, "total botlib memory: %d KB\n", totalmemorysize >> 10); botimport.Print(PRT_MESSAGE, "total memory blocks: %d\n", numblocks); -} //end of the function PrintUsedMemorySize +} // end of the function PrintUsedMemorySize //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void PrintMemoryLabels(void) -{ +void PrintMemoryLabels(void) { memoryblock_t *block; int i; @@ -302,38 +293,33 @@ void PrintMemoryLabels(void) i = 0; Log_Write("============= Botlib memory log ==============\r\n"); Log_Write("\r\n"); - for (block = memory; block; block = block->next) - { + for (block = memory; block; block = block->next) { #ifdef MEMDEBUG - if (block->id == HUNK_ID) - { + if (block->id == HUNK_ID) { Log_Write("%6d, hunk %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label); - } //end if - else - { + } // end if + else { Log_Write("%6d, %p, %8d: %24s line %6d: %s\r\n", i, block->ptr, block->size, block->file, block->line, block->label); - } //end else -#endif //MEMDEBUG + } // end else +#endif // MEMDEBUG i++; - } //end for -} //end of the function PrintMemoryLabels + } // end for +} // end of the function PrintMemoryLabels //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void DumpMemory(void) -{ +void DumpMemory(void) { memoryblock_t *block; - for (block = memory; block; block = memory) - { + for (block = memory; block; block = memory) { FreeMemory(block->ptr); - } //end for + } // end for totalmemorysize = 0; allocatedmemory = 0; -} //end of the function DumpMemory +} // end of the function DumpMemory #else @@ -347,17 +333,18 @@ void DumpMemory(void) void *GetMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; unsigned long int *memid; ptr = botimport.GetMemory(size + sizeof(qmax_align_t)); - if (!ptr) return NULL; - memid = (unsigned long int *) ptr; + if (!ptr) + return NULL; + memid = (unsigned long int *)ptr; *memid = MEM_ID; - return (unsigned long int *) ((char *) ptr + sizeof(qmax_align_t)); -} //end of the function GetMemory + return (unsigned long int *)((char *)ptr + sizeof(qmax_align_t)); +} // end of the function GetMemory //=========================================================================== // // Parameter: - @@ -368,17 +355,17 @@ void *GetMemory(unsigned long size) void *GetClearedMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetClearedMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; #ifdef MEMDEBUG ptr = GetMemoryDebug(size, label, file, line); #else ptr = GetMemory(size); -#endif //MEMDEBUG +#endif // MEMDEBUG Com_Memset(ptr, 0, size); return ptr; -} //end of the function GetClearedMemory +} // end of the function GetClearedMemory //=========================================================================== // // Parameter: - @@ -389,17 +376,18 @@ void *GetClearedMemory(unsigned long size) void *GetHunkMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetHunkMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; unsigned long int *memid; ptr = botimport.HunkAlloc(size + sizeof(qmax_align_t)); - if (!ptr) return NULL; - memid = (unsigned long int *) ptr; + if (!ptr) + return NULL; + memid = (unsigned long int *)ptr; *memid = HUNK_ID; - return (unsigned long int *) ((char *) ptr + sizeof(qmax_align_t)); -} //end of the function GetHunkMemory + return (unsigned long int *)((char *)ptr + sizeof(qmax_align_t)); +} // end of the function GetHunkMemory //=========================================================================== // // Parameter: - @@ -410,61 +398,52 @@ void *GetHunkMemory(unsigned long size) void *GetClearedHunkMemoryDebug(unsigned long size, char *label, char *file, int line) #else void *GetClearedHunkMemory(unsigned long size) -#endif //MEMDEBUG +#endif // MEMDEBUG { void *ptr; #ifdef MEMDEBUG ptr = GetHunkMemoryDebug(size, label, file, line); #else ptr = GetHunkMemory(size); -#endif //MEMDEBUG +#endif // MEMDEBUG Com_Memset(ptr, 0, size); return ptr; -} //end of the function GetClearedHunkMemory +} // end of the function GetClearedHunkMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void FreeMemory(void *ptr) -{ +void FreeMemory(void *ptr) { unsigned long int *memid; - memid = (unsigned long int *) ((char *) ptr - sizeof(qmax_align_t)); + memid = (unsigned long int *)((char *)ptr - sizeof(qmax_align_t)); - if (*memid == MEM_ID) - { + if (*memid == MEM_ID) { botimport.FreeMemory(memid); - } //end if -} //end of the function FreeMemory + } // end if +} // end of the function FreeMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int AvailableMemory(void) -{ - return botimport.AvailableMemory(); -} //end of the function AvailableMemory +int AvailableMemory(void) { return botimport.AvailableMemory(); } // end of the function AvailableMemory //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void PrintUsedMemorySize(void) -{ -} //end of the function PrintUsedMemorySize +void PrintUsedMemorySize(void) {} // end of the function PrintUsedMemorySize //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void PrintMemoryLabels(void) -{ -} //end of the function PrintMemoryLabels +void PrintMemoryLabels(void) {} // end of the function PrintMemoryLabels #endif diff --git a/codemp/botlib/l_precomp.cpp b/codemp/botlib/l_precomp.cpp index 8089a56c0a..362473a717 100644 --- a/codemp/botlib/l_precomp.cpp +++ b/codemp/botlib/l_precomp.cpp @@ -34,7 +34,7 @@ along with this program; if not, see . * *****************************************************************************/ -//Notes: fix: PC_StringizeTokens +// Notes: fix: PC_StringizeTokens //#define SCREWUP //#define BOTLIB @@ -53,8 +53,8 @@ along with this program; if not, see . #include "l_script.h" #include "l_precomp.h" -typedef enum {qfalse, qtrue} qboolean; -#endif //SCREWUP +typedef enum { qfalse, qtrue } qboolean; +#endif // SCREWUP #ifdef BOTLIB #include "qcommon/q_shared.h" @@ -64,54 +64,53 @@ typedef enum {qfalse, qtrue} qboolean; #include "l_script.h" #include "l_precomp.h" #include "l_log.h" -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC #include "qcc.h" -#include "time.h" //time & ctime -#include "math.h" //fabs +#include "time.h" //time & ctime +#include "math.h" //fabs #include "l_memory.h" #include "l_script.h" #include "l_precomp.h" #include "l_log.h" -#define qtrue true -#define qfalse false -#endif //MEQCC +#define qtrue true +#define qfalse false +#endif // MEQCC #ifdef BSPC -//include files for usage in the BSP Converter +// include files for usage in the BSP Converter #include "../bspc/qbsp.h" #include "../bspc/l_log.h" #include "../bspc/l_mem.h" #include "l_precomp.h" -#define qtrue true -#define qfalse false -#define Q_stricmp stricmp +#define qtrue true +#define qfalse false +#define Q_stricmp stricmp -#endif //BSPC +#endif // BSPC #if defined(QUAKE) && !defined(BSPC) #include "l_utils.h" -#endif //QUAKE +#endif // QUAKE //#define DEBUG_EVAL -#define MAX_DEFINEPARMS 128 +#define MAX_DEFINEPARMS 128 -#define DEFINEHASHING 1 +#define DEFINEHASHING 1 -//directive name with parse function -typedef struct directive_s -{ +// directive name with parse function +typedef struct directive_s { char *name; int (*func)(source_t *source); } directive_t; -#define DEFINEHASHSIZE 1024 +#define DEFINEHASHSIZE 1024 -#define TOKEN_HEAP_SIZE 4096 +#define TOKEN_HEAP_SIZE 4096 int numtokens; /* @@ -120,13 +119,13 @@ token_t token_heap[TOKEN_HEAP_SIZE]; //heap with tokens token_t *freetokens; //free tokens from the heap */ -//list with global defines added to every source loaded +// list with global defines added to every source loaded #if DEFINEHASHING -define_t **globaldefines = NULL; +define_t **globaldefines = NULL; #else -define_t *globaldefines = NULL; +define_t *globaldefines = NULL; #endif -qboolean addGlobalDefine = qfalse; +qboolean addGlobalDefine = qfalse; //============================================================================ // @@ -134,8 +133,7 @@ qboolean addGlobalDefine = qfalse; // Returns: - // Changes Globals: - //============================================================================ -void QDECL SourceError(source_t *source, char *str, ...) -{ +void QDECL SourceError(source_t *source, char *str, ...) { char text[1024]; va_list ap; @@ -144,22 +142,21 @@ void QDECL SourceError(source_t *source, char *str, ...) va_end(ap); #ifdef BOTLIB botimport.Print(PRT_ERROR, "file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC printf("error: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //MEQCC +#endif // MEQCC #ifdef BSPC Log_Print("error: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //BSPC -} //end of the function SourceError +#endif // BSPC +} // end of the function SourceError //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void QDECL SourceWarning(source_t *source, char *str, ...) -{ +void QDECL SourceWarning(source_t *source, char *str, ...) { char text[1024]; va_list ap; @@ -168,87 +165,83 @@ void QDECL SourceWarning(source_t *source, char *str, ...) va_end(ap); #ifdef BOTLIB botimport.Print(PRT_WARNING, "file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC printf("warning: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //MEQCC +#endif // MEQCC #ifdef BSPC Log_Print("warning: file %s, line %d: %s\n", source->scriptstack->filename, source->scriptstack->line, text); -#endif //BSPC -} //end of the function ScriptWarning +#endif // BSPC +} // end of the function ScriptWarning //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_PushIndent(source_t *source, int type, int skip) -{ +void PC_PushIndent(source_t *source, int type, int skip) { indent_t *indent; - indent = (indent_t *) GetMemory(sizeof(indent_t)); + indent = (indent_t *)GetMemory(sizeof(indent_t)); indent->type = type; indent->script = source->scriptstack; indent->skip = (skip != 0); source->skip += indent->skip; indent->next = source->indentstack; source->indentstack = indent; -} //end of the function PC_PushIndent +} // end of the function PC_PushIndent //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_PopIndent(source_t *source, int *type, int *skip) -{ +void PC_PopIndent(source_t *source, int *type, int *skip) { indent_t *indent; *type = 0; *skip = 0; indent = source->indentstack; - if (!indent) return; + if (!indent) + return; - //must be an indent from the current script - if (source->indentstack->script != source->scriptstack) return; + // must be an indent from the current script + if (source->indentstack->script != source->scriptstack) + return; *type = indent->type; *skip = indent->skip; source->indentstack = source->indentstack->next; source->skip -= indent->skip; FreeMemory(indent); -} //end of the function PC_PopIndent +} // end of the function PC_PopIndent //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_PushScript(source_t *source, script_t *script) -{ +void PC_PushScript(source_t *source, script_t *script) { script_t *s; - for (s = source->scriptstack; s; s = s->next) - { - if (!Q_stricmp(s->filename, script->filename)) - { + for (s = source->scriptstack; s; s = s->next) { + if (!Q_stricmp(s->filename, script->filename)) { SourceError(source, "%s recursively included", script->filename); return; - } //end if - } //end for - //push the script on the script stack + } // end if + } // end for + // push the script on the script stack script->next = source->scriptstack; source->scriptstack = script; -} //end of the function PC_PushScript +} // end of the function PC_PushScript //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_InitTokenHeap(void) -{ +void PC_InitTokenHeap(void) { /* int i; @@ -261,214 +254,194 @@ void PC_InitTokenHeap(void) } //end for tokenheapinitialized = qtrue; */ -} //end of the function PC_InitTokenHeap +} // end of the function PC_InitTokenHeap //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -token_t *PC_CopyToken(token_t *token) -{ +token_t *PC_CopyToken(token_t *token) { token_t *t; -// t = (token_t *) malloc(sizeof(token_t)); - t = (token_t *) GetMemory(sizeof(token_t)); -// t = freetokens; - if (!t) - { + // t = (token_t *) malloc(sizeof(token_t)); + t = (token_t *)GetMemory(sizeof(token_t)); + // t = freetokens; + if (!t) { #ifdef BSPC Error("out of token space"); #else Com_Error(ERR_FATAL, "out of token space"); #endif return NULL; - } //end if -// freetokens = freetokens->next; + } // end if + // freetokens = freetokens->next; Com_Memcpy(t, token, sizeof(token_t)); t->next = NULL; numtokens++; return t; -} //end of the function PC_CopyToken +} // end of the function PC_CopyToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_FreeToken(token_t *token) -{ - //free(token); +void PC_FreeToken(token_t *token) { + // free(token); FreeMemory(token); -// token->next = freetokens; -// freetokens = token; + // token->next = freetokens; + // freetokens = token; numtokens--; -} //end of the function PC_FreeToken +} // end of the function PC_FreeToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ReadSourceToken(source_t *source, token_t *token) -{ +int PC_ReadSourceToken(source_t *source, token_t *token) { token_t *t; script_t *script; int type, skip; - //if there's no token already available - while(!source->tokens) - { - //if there's a token to read from the script - if (PS_ReadToken(source->scriptstack, token)) return qtrue; - //if at the end of the script - if (EndOfScript(source->scriptstack)) - { - //remove all indents of the script - while(source->indentstack && - source->indentstack->script == source->scriptstack) - { + // if there's no token already available + while (!source->tokens) { + // if there's a token to read from the script + if (PS_ReadToken(source->scriptstack, token)) + return qtrue; + // if at the end of the script + if (EndOfScript(source->scriptstack)) { + // remove all indents of the script + while (source->indentstack && source->indentstack->script == source->scriptstack) { SourceWarning(source, "missing #endif"); PC_PopIndent(source, &type, &skip); - } //end if - } //end if - //if this was the initial script - if (!source->scriptstack->next) return qfalse; - //remove the script and return to the last one + } // end if + } // end if + // if this was the initial script + if (!source->scriptstack->next) + return qfalse; + // remove the script and return to the last one script = source->scriptstack; source->scriptstack = source->scriptstack->next; FreeScript(script); - } //end while - //copy the already available token + } // end while + // copy the already available token Com_Memcpy(token, source->tokens, sizeof(token_t)); - //free the read token + // free the read token t = source->tokens; source->tokens = source->tokens->next; PC_FreeToken(t); return qtrue; -} //end of the function PC_ReadSourceToken +} // end of the function PC_ReadSourceToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_UnreadSourceToken(source_t *source, token_t *token) -{ +int PC_UnreadSourceToken(source_t *source, token_t *token) { token_t *t; t = PC_CopyToken(token); t->next = source->tokens; source->tokens = t; return qtrue; -} //end of the function PC_UnreadSourceToken +} // end of the function PC_UnreadSourceToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ReadDefineParms(source_t *source, define_t *define, token_t **parms, int maxparms) -{ +int PC_ReadDefineParms(source_t *source, define_t *define, token_t **parms, int maxparms) { token_t token, *t, *last; int i, done, lastcomma, numparms, indent; - if (!PC_ReadSourceToken(source, &token)) - { + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "define %s missing parms", define->name); return qfalse; - } //end if + } // end if // - if (define->numparms > maxparms) - { + if (define->numparms > maxparms) { SourceError(source, "define with more than %d parameters", maxparms); return qfalse; - } //end if + } // end if // - for (i = 0; i < define->numparms; i++) parms[i] = NULL; - //if no leading "(" - if (strcmp(token.string, "(")) - { + for (i = 0; i < define->numparms; i++) + parms[i] = NULL; + // if no leading "(" + if (strcmp(token.string, "(")) { PC_UnreadSourceToken(source, &token); SourceError(source, "define %s missing parms", define->name); return qfalse; - } //end if - //read the define parameters - for (done = 0, numparms = 0, indent = 0; !done;) - { - if (numparms >= maxparms) - { + } // end if + // read the define parameters + for (done = 0, numparms = 0, indent = 0; !done;) { + if (numparms >= maxparms) { SourceError(source, "define %s with too many parms", define->name); return qfalse; - } //end if - if (numparms >= define->numparms) - { + } // end if + if (numparms >= define->numparms) { SourceWarning(source, "define %s has too many parms", define->name); return qfalse; - } //end if + } // end if parms[numparms] = NULL; lastcomma = 1; last = NULL; - while(!done) - { + while (!done) { // - if (!PC_ReadSourceToken(source, &token)) - { + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "define %s incomplete", define->name); return qfalse; - } //end if + } // end if // - if (!strcmp(token.string, ",")) - { - if (indent <= 0) - { - if (lastcomma) SourceWarning(source, "too many comma's"); + if (!strcmp(token.string, ",")) { + if (indent <= 0) { + if (lastcomma) + SourceWarning(source, "too many comma's"); lastcomma = 1; break; - } //end if - } //end if + } // end if + } // end if lastcomma = 0; // - if (!strcmp(token.string, "(")) - { + if (!strcmp(token.string, "(")) { indent++; continue; - } //end if - else if (!strcmp(token.string, ")")) - { - if (--indent <= 0) - { - if (!parms[define->numparms-1]) - { + } // end if + else if (!strcmp(token.string, ")")) { + if (--indent <= 0) { + if (!parms[define->numparms - 1]) { SourceWarning(source, "too few define parms"); - } //end if + } // end if done = 1; break; - } //end if - } //end if + } // end if + } // end if // - if (numparms < define->numparms) - { + if (numparms < define->numparms) { // t = PC_CopyToken(&token); t->next = NULL; - if (last) last->next = t; - else parms[numparms] = t; + if (last) + last->next = t; + else + parms[numparms] = t; last = t; - } //end if - } //end while + } // end if + } // end while numparms++; - } //end for + } // end for return qtrue; -} //end of the function PC_ReadDefineParms +} // end of the function PC_ReadDefineParms //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_StringizeTokens(token_t *tokens, token_t *token) -{ +int PC_StringizeTokens(token_t *tokens, token_t *token) { token_t *t; token->type = TT_STRING; @@ -476,39 +449,35 @@ int PC_StringizeTokens(token_t *tokens, token_t *token) token->endwhitespace_p = NULL; token->string[0] = '\0'; strcat(token->string, "\""); - for (t = tokens; t; t = t->next) - { + for (t = tokens; t; t = t->next) { strncat(token->string, t->string, MAX_TOKEN - strlen(token->string) - 1); - } //end for + } // end for strncat(token->string, "\"", MAX_TOKEN - strlen(token->string) - 1); return qtrue; -} //end of the function PC_StringizeTokens +} // end of the function PC_StringizeTokens //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_MergeTokens(token_t *t1, token_t *t2) -{ - //merging of a name with a name or number - if (t1->type == TT_NAME && (t2->type == TT_NAME || t2->type == TT_NUMBER)) - { +int PC_MergeTokens(token_t *t1, token_t *t2) { + // merging of a name with a name or number + if (t1->type == TT_NAME && (t2->type == TT_NAME || t2->type == TT_NUMBER)) { strcat(t1->string, t2->string); return qtrue; - } //end if - //merging of two strings - if (t1->type == TT_STRING && t2->type == TT_STRING) - { - //remove trailing double quote - t1->string[strlen(t1->string)-1] = '\0'; - //concat without leading double quote + } // end if + // merging of two strings + if (t1->type == TT_STRING && t2->type == TT_STRING) { + // remove trailing double quote + t1->string[strlen(t1->string) - 1] = '\0'; + // concat without leading double quote strcat(t1->string, &t2->string[1]); return qtrue; - } //end if - //FIXME: merging of two number of the same sub type + } // end if + // FIXME: merging of two number of the same sub type return qfalse; -} //end of the function PC_MergeTokens +} // end of the function PC_MergeTokens //============================================================================ // // Parameter: - @@ -533,56 +502,48 @@ void PC_PrintDefine(define_t *define) // Returns: - // Changes Globals: - //============================================================================ -void PC_PrintDefineHashTable(define_t **definehash) -{ +void PC_PrintDefineHashTable(define_t **definehash) { int i; define_t *d; - for (i = 0; i < DEFINEHASHSIZE; i++) - { + for (i = 0; i < DEFINEHASHSIZE; i++) { Log_Write("%4d:", i); - for (d = definehash[i]; d; d = d->hashnext) - { + for (d = definehash[i]; d; d = d->hashnext) { Log_Write(" %s", d->name); - } //end for + } // end for Log_Write("\n"); - } //end for -} //end of the function PC_PrintDefineHashTable + } // end for +} // end of the function PC_PrintDefineHashTable //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -//char primes[16] = {1, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 41, 43, 47}; +// char primes[16] = {1, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 41, 43, 47}; -int PC_NameHash(char *name) -{ +int PC_NameHash(char *name) { int hash, i; hash = 0; - for (i = 0; name[i] != '\0'; i++) - { + for (i = 0; name[i] != '\0'; i++) { hash += name[i] * (119 + i); - //hash += (name[i] << 7) + i; - //hash += (name[i] << (i&15)); - } //end while - hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (DEFINEHASHSIZE-1); + // hash += (name[i] << 7) + i; + // hash += (name[i] << (i&15)); + } // end while + hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (DEFINEHASHSIZE - 1); return hash; -} //end of the function PC_NameHash +} // end of the function PC_NameHash //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_AddDefineToHash(define_t *define, define_t **definehash) -{ +void PC_AddDefineToHash(define_t *define, define_t **definehash) { int hash; - - if ( addGlobalDefine ) - { + if (addGlobalDefine) { definehash = globaldefines; define->flags |= DEFINE_GLOBAL; } @@ -591,46 +552,43 @@ void PC_AddDefineToHash(define_t *define, define_t **definehash) define->hashnext = definehash[hash]; definehash[hash] = define; - if ( addGlobalDefine ) - { + if (addGlobalDefine) { define->globalnext = define->hashnext; } -} //end of the function PC_AddDefineToHash +} // end of the function PC_AddDefineToHash //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -define_t *PC_FindHashedDefine(define_t **definehash, char *name) -{ +define_t *PC_FindHashedDefine(define_t **definehash, char *name) { define_t *d; int hash; hash = PC_NameHash(name); - for (d = definehash[hash]; d; d = d->hashnext) - { - if (!strcmp(d->name, name)) return d; - } //end for + for (d = definehash[hash]; d; d = d->hashnext) { + if (!strcmp(d->name, name)) + return d; + } // end for return NULL; -} //end of the function PC_FindHashedDefine -#endif //DEFINEHASHING +} // end of the function PC_FindHashedDefine +#endif // DEFINEHASHING //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -define_t *PC_FindDefine(define_t *defines, char *name) -{ +define_t *PC_FindDefine(define_t *defines, char *name) { define_t *d; - for (d = defines; d; d = d->next) - { - if (!strcmp(d->name, name)) return d; - } //end for + for (d = defines; d; d = d->next) { + if (!strcmp(d->name, name)) + return d; + } // end for return NULL; -} //end of the function PC_FindDefine +} // end of the function PC_FindDefine //============================================================================ // // Parameter: - @@ -638,440 +596,393 @@ define_t *PC_FindDefine(define_t *defines, char *name) // if no parm found with the given name -1 is returned // Changes Globals: - //============================================================================ -int PC_FindDefineParm(define_t *define, char *name) -{ +int PC_FindDefineParm(define_t *define, char *name) { token_t *p; int i; i = 0; - for (p = define->parms; p; p = p->next) - { - if (!strcmp(p->string, name)) return i; + for (p = define->parms; p; p = p->next) { + if (!strcmp(p->string, name)) + return i; i++; - } //end for + } // end for return -1; -} //end of the function PC_FindDefineParm +} // end of the function PC_FindDefineParm //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_FreeDefine(define_t *define) -{ +void PC_FreeDefine(define_t *define) { token_t *t, *next; - //free the define parameters - for (t = define->parms; t; t = next) - { + // free the define parameters + for (t = define->parms; t; t = next) { next = t->next; PC_FreeToken(t); - } //end for - //free the define tokens - for (t = define->tokens; t; t = next) - { + } // end for + // free the define tokens + for (t = define->tokens; t; t = next) { next = t->next; PC_FreeToken(t); - } //end for - //free the define + } // end for + // free the define FreeMemory(define->name); FreeMemory(define); -} //end of the function PC_FreeDefine +} // end of the function PC_FreeDefine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_AddBuiltinDefines(source_t *source) -{ +void PC_AddBuiltinDefines(source_t *source) { int i; define_t *define; - struct builtin - { + struct builtin { char *string; int mBuiltin; - } builtin[] = { // bk001204 - brackets - { "__LINE__", BUILTIN_LINE }, - { "__FILE__", BUILTIN_FILE }, - { "__DATE__", BUILTIN_DATE }, - { "__TIME__", BUILTIN_TIME }, -// { "__STDC__", BUILTIN_STDC }, - { NULL, 0 } - }; - - for (i = 0; builtin[i].string; i++) - { - define = (define_t *) GetMemory(sizeof(define_t)); + } builtin[] = {// bk001204 - brackets + {"__LINE__", BUILTIN_LINE}, + {"__FILE__", BUILTIN_FILE}, + {"__DATE__", BUILTIN_DATE}, + {"__TIME__", BUILTIN_TIME}, + // { "__STDC__", BUILTIN_STDC }, + {NULL, 0}}; + + for (i = 0; builtin[i].string; i++) { + define = (define_t *)GetMemory(sizeof(define_t)); Com_Memset(define, 0, sizeof(define_t)); - define->name = (char *) GetMemory(strlen(builtin[i].string) + 1); + define->name = (char *)GetMemory(strlen(builtin[i].string) + 1); strcpy(define->name, builtin[i].string); define->flags |= DEFINE_FIXED; define->builtin = builtin[i].mBuiltin; - //add the define to the source + // add the define to the source #if DEFINEHASHING PC_AddDefineToHash(define, source->definehash); #else define->next = source->defines; source->defines = define; -#endif //DEFINEHASHING - } //end for -} //end of the function PC_AddBuiltinDefines +#endif // DEFINEHASHING + } // end for +} // end of the function PC_AddBuiltinDefines //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpandBuiltinDefine(source_t *source, token_t *deftoken, define_t *define, - token_t **firsttoken, token_t **lasttoken) -{ +int PC_ExpandBuiltinDefine(source_t *source, token_t *deftoken, define_t *define, token_t **firsttoken, token_t **lasttoken) { token_t *token; time_t t; char *curtime; token = PC_CopyToken(deftoken); - switch(define->builtin) - { - case BUILTIN_LINE: - { - sprintf(token->string, "%d", deftoken->line); + switch (define->builtin) { + case BUILTIN_LINE: { + sprintf(token->string, "%d", deftoken->line); #ifdef NUMBERVALUE - token->intvalue = deftoken->line; - token->floatvalue = deftoken->line; -#endif //NUMBERVALUE - token->type = TT_NUMBER; - token->subtype = TT_DECIMAL | TT_INTEGER; - *firsttoken = token; - *lasttoken = token; - break; - } //end case - case BUILTIN_FILE: - { - strcpy(token->string, source->scriptstack->filename); - token->type = TT_NAME; - token->subtype = strlen(token->string); - *firsttoken = token; - *lasttoken = token; - break; - } //end case - case BUILTIN_DATE: - { - t = time(NULL); - curtime = ctime(&t); - strcpy(token->string, "\""); - strncat(token->string, curtime+4, 7); - strncat(token->string+7, curtime+20, 4); - strcat(token->string, "\""); - free(curtime); - token->type = TT_NAME; - token->subtype = strlen(token->string); - *firsttoken = token; - *lasttoken = token; - break; - } //end case - case BUILTIN_TIME: - { - t = time(NULL); - curtime = ctime(&t); - strcpy(token->string, "\""); - strncat(token->string, curtime+11, 8); - strcat(token->string, "\""); - free(curtime); - token->type = TT_NAME; - token->subtype = strlen(token->string); - *firsttoken = token; - *lasttoken = token; - break; - } //end case - case BUILTIN_STDC: - default: - { - *firsttoken = NULL; - *lasttoken = NULL; - break; - } //end case - } //end switch + token->intvalue = deftoken->line; + token->floatvalue = deftoken->line; +#endif // NUMBERVALUE + token->type = TT_NUMBER; + token->subtype = TT_DECIMAL | TT_INTEGER; + *firsttoken = token; + *lasttoken = token; + break; + } // end case + case BUILTIN_FILE: { + strcpy(token->string, source->scriptstack->filename); + token->type = TT_NAME; + token->subtype = strlen(token->string); + *firsttoken = token; + *lasttoken = token; + break; + } // end case + case BUILTIN_DATE: { + t = time(NULL); + curtime = ctime(&t); + strcpy(token->string, "\""); + strncat(token->string, curtime + 4, 7); + strncat(token->string + 7, curtime + 20, 4); + strcat(token->string, "\""); + free(curtime); + token->type = TT_NAME; + token->subtype = strlen(token->string); + *firsttoken = token; + *lasttoken = token; + break; + } // end case + case BUILTIN_TIME: { + t = time(NULL); + curtime = ctime(&t); + strcpy(token->string, "\""); + strncat(token->string, curtime + 11, 8); + strcat(token->string, "\""); + free(curtime); + token->type = TT_NAME; + token->subtype = strlen(token->string); + *firsttoken = token; + *lasttoken = token; + break; + } // end case + case BUILTIN_STDC: + default: { + *firsttoken = NULL; + *lasttoken = NULL; + break; + } // end case + } // end switch return qtrue; -} //end of the function PC_ExpandBuiltinDefine +} // end of the function PC_ExpandBuiltinDefine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpandDefine(source_t *source, token_t *deftoken, define_t *define, - token_t **firsttoken, token_t **lasttoken) -{ +int PC_ExpandDefine(source_t *source, token_t *deftoken, define_t *define, token_t **firsttoken, token_t **lasttoken) { token_t *parms[MAX_DEFINEPARMS], *dt, *pt, *t; token_t *t1, *t2, *first, *last, *nextpt, token; int parmnum, i; - //if it is a builtin define - if (define->builtin) - { + // if it is a builtin define + if (define->builtin) { return PC_ExpandBuiltinDefine(source, deftoken, define, firsttoken, lasttoken); - } //end if - //if the define has parameters - if (define->numparms) - { - if (!PC_ReadDefineParms(source, define, parms, MAX_DEFINEPARMS)) return qfalse; + } // end if + // if the define has parameters + if (define->numparms) { + if (!PC_ReadDefineParms(source, define, parms, MAX_DEFINEPARMS)) + return qfalse; #ifdef DEBUG_EVAL - for (i = 0; i < define->numparms; i++) - { + for (i = 0; i < define->numparms; i++) { Log_Write("define parms %d:", i); - for (pt = parms[i]; pt; pt = pt->next) - { + for (pt = parms[i]; pt; pt = pt->next) { Log_Write("%s", pt->string); - } //end for - } //end for -#endif //DEBUG_EVAL - } //end if - //empty list at first + } // end for + } // end for +#endif // DEBUG_EVAL + } // end if + // empty list at first first = NULL; last = NULL; - //create a list with tokens of the expanded define - for (dt = define->tokens; dt; dt = dt->next) - { + // create a list with tokens of the expanded define + for (dt = define->tokens; dt; dt = dt->next) { parmnum = -1; - //if the token is a name, it could be a define parameter - if (dt->type == TT_NAME) - { + // if the token is a name, it could be a define parameter + if (dt->type == TT_NAME) { parmnum = PC_FindDefineParm(define, dt->string); - } //end if - //if it is a define parameter - if (parmnum >= 0) - { - for (pt = parms[parmnum]; pt; pt = pt->next) - { + } // end if + // if it is a define parameter + if (parmnum >= 0) { + for (pt = parms[parmnum]; pt; pt = pt->next) { t = PC_CopyToken(pt); - //add the token to the list + // add the token to the list t->next = NULL; - if (last) last->next = t; - else first = t; + if (last) + last->next = t; + else + first = t; last = t; - } //end for - } //end if - else - { - //if stringizing operator - if (dt->string[0] == '#' && dt->string[1] == '\0') - { - //the stringizing operator must be followed by a define parameter - if (dt->next) parmnum = PC_FindDefineParm(define, dt->next->string); - else parmnum = -1; + } // end for + } // end if + else { + // if stringizing operator + if (dt->string[0] == '#' && dt->string[1] == '\0') { + // the stringizing operator must be followed by a define parameter + if (dt->next) + parmnum = PC_FindDefineParm(define, dt->next->string); + else + parmnum = -1; // - if (parmnum >= 0) - { - //step over the stringizing operator + if (parmnum >= 0) { + // step over the stringizing operator dt = dt->next; - //stringize the define parameter tokens - if (!PC_StringizeTokens(parms[parmnum], &token)) - { + // stringize the define parameter tokens + if (!PC_StringizeTokens(parms[parmnum], &token)) { SourceError(source, "can't stringize tokens"); return qfalse; - } //end if + } // end if t = PC_CopyToken(&token); - } //end if - else - { + } // end if + else { SourceWarning(source, "stringizing operator without define parameter"); continue; - } //end if - } //end if - else - { + } // end if + } // end if + else { t = PC_CopyToken(dt); - } //end else - //add the token to the list + } // end else + // add the token to the list t->next = NULL; - if (last) last->next = t; - else first = t; + if (last) + last->next = t; + else + first = t; last = t; - } //end else - } //end for - //check for the merging operator - for (t = first; t; ) - { - if (t->next) - { - //if the merging operator - if (t->next->string[0] == '#' && t->next->string[1] == '#') - { + } // end else + } // end for + // check for the merging operator + for (t = first; t;) { + if (t->next) { + // if the merging operator + if (t->next->string[0] == '#' && t->next->string[1] == '#') { t1 = t; t2 = t->next->next; - if (t2) - { - if (!PC_MergeTokens(t1, t2)) - { + if (t2) { + if (!PC_MergeTokens(t1, t2)) { SourceError(source, "can't merge %s with %s", t1->string, t2->string); return qfalse; - } //end if + } // end if PC_FreeToken(t1->next); t1->next = t2->next; - if (t2 == last) last = t1; + if (t2 == last) + last = t1; PC_FreeToken(t2); continue; - } //end if - } //end if - } //end if + } // end if + } // end if + } // end if t = t->next; - } //end for - //store the first and last token of the list + } // end for + // store the first and last token of the list *firsttoken = first; *lasttoken = last; - //free all the parameter tokens - for (i = 0; i < define->numparms; i++) - { - for (pt = parms[i]; pt; pt = nextpt) - { + // free all the parameter tokens + for (i = 0; i < define->numparms; i++) { + for (pt = parms[i]; pt; pt = nextpt) { nextpt = pt->next; PC_FreeToken(pt); - } //end for - } //end for + } // end for + } // end for // return qtrue; -} //end of the function PC_ExpandDefine +} // end of the function PC_ExpandDefine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpandDefineIntoSource(source_t *source, token_t *deftoken, define_t *define) -{ +int PC_ExpandDefineIntoSource(source_t *source, token_t *deftoken, define_t *define) { token_t *firsttoken, *lasttoken; - if (!PC_ExpandDefine(source, deftoken, define, &firsttoken, &lasttoken)) return qfalse; + if (!PC_ExpandDefine(source, deftoken, define, &firsttoken, &lasttoken)) + return qfalse; - if (firsttoken && lasttoken) - { + if (firsttoken && lasttoken) { lasttoken->next = source->tokens; source->tokens = firsttoken; return qtrue; - } //end if + } // end if return qfalse; -} //end of the function PC_ExpandDefineIntoSource +} // end of the function PC_ExpandDefineIntoSource //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_ConvertPath(char *path) -{ +void PC_ConvertPath(char *path) { char *ptr; - //remove double path seperators - for (ptr = path; *ptr;) - { - if ((*ptr == '\\' || *ptr == '/') && - (*(ptr+1) == '\\' || *(ptr+1) == '/')) - { - memmove(ptr, ptr+1, strlen(ptr)); - } //end if - else - { + // remove double path seperators + for (ptr = path; *ptr;) { + if ((*ptr == '\\' || *ptr == '/') && (*(ptr + 1) == '\\' || *(ptr + 1) == '/')) { + memmove(ptr, ptr + 1, strlen(ptr)); + } // end if + else { ptr++; - } //end else - } //end while - //set OS dependent path seperators - for (ptr = path; *ptr;) - { - if (*ptr == '/' || *ptr == '\\') *ptr = PATHSEPERATOR_CHAR; + } // end else + } // end while + // set OS dependent path seperators + for (ptr = path; *ptr;) { + if (*ptr == '/' || *ptr == '\\') + *ptr = PATHSEPERATOR_CHAR; ptr++; - } //end while -} //end of the function PC_ConvertPath + } // end while +} // end of the function PC_ConvertPath //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_include(source_t *source) -{ +int PC_Directive_include(source_t *source) { script_t *script; token_t token; char path[MAX_PATH]; #ifdef QUAKE foundfile_t file; -#endif //QUAKE +#endif // QUAKE - if (source->skip > 0) return qtrue; + if (source->skip > 0) + return qtrue; // - if (!PC_ReadSourceToken(source, &token)) - { + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "#include without file name"); return qfalse; - } //end if - if (token.linescrossed > 0) - { + } // end if + if (token.linescrossed > 0) { SourceError(source, "#include without file name"); return qfalse; - } //end if - if (token.type == TT_STRING) - { + } // end if + if (token.type == TT_STRING) { StripDoubleQuotes(token.string); PC_ConvertPath(token.string); script = LoadScriptFile(token.string); - if (!script) - { + if (!script) { Q_strncpyz(path, source->includepath, sizeof(path)); Q_strcat(path, sizeof(path), token.string); script = LoadScriptFile(path); - } //end if - } //end if - else if (token.type == TT_PUNCTUATION && *token.string == '<') - { + } // end if + } // end if + else if (token.type == TT_PUNCTUATION && *token.string == '<') { Q_strncpyz(path, source->includepath, sizeof(path)); - while(PC_ReadSourceToken(source, &token)) - { - if (token.linescrossed > 0) - { + while (PC_ReadSourceToken(source, &token)) { + if (token.linescrossed > 0) { PC_UnreadSourceToken(source, &token); break; - } //end if - if (token.type == TT_PUNCTUATION && *token.string == '>') break; + } // end if + if (token.type == TT_PUNCTUATION && *token.string == '>') + break; Q_strcat(path, sizeof(path), token.string); - } //end while - if (*token.string != '>') - { + } // end while + if (*token.string != '>') { SourceWarning(source, "#include missing trailing >"); - } //end if - if (!strlen(path)) - { + } // end if + if (!strlen(path)) { SourceError(source, "#include without file name between < >"); return qfalse; - } //end if + } // end if PC_ConvertPath(path); script = LoadScriptFile(path); - } //end if - else - { + } // end if + else { SourceError(source, "#include without file name"); return qfalse; - } //end else + } // end else #ifdef QUAKE - if (!script) - { + if (!script) { Com_Memset(&file, 0, sizeof(foundfile_t)); script = LoadScriptFile(path); - if (script) strncpy(script->filename, path, MAX_PATH); - } //end if -#endif //QUAKE - if (!script) - { + if (script) + strncpy(script->filename, path, MAX_PATH); + } // end if +#endif // QUAKE + if (!script) { #ifdef SCREWUP SourceWarning(source, "file %s not found", path); return qtrue; #else SourceError(source, "file %s not found", path); return qfalse; -#endif //SCREWUP - } //end if +#endif // SCREWUP + } // end if PC_PushScript(source, script); return qtrue; -} //end of the function PC_Directive_include +} // end of the function PC_Directive_include //============================================================================ // reads a token from the current line, continues reading on the next // line only if a backslash '\' is encountered. @@ -1080,269 +991,246 @@ int PC_Directive_include(source_t *source) // Returns: - // Changes Globals: - //============================================================================ -int PC_ReadLine(source_t *source, token_t *token) -{ +int PC_ReadLine(source_t *source, token_t *token) { int crossline; crossline = 0; - do - { - if (!PC_ReadSourceToken(source, token)) return qfalse; + do { + if (!PC_ReadSourceToken(source, token)) + return qfalse; - if (token->linescrossed > crossline) - { + if (token->linescrossed > crossline) { PC_UnreadSourceToken(source, token); return qfalse; - } //end if + } // end if crossline = 1; - } while(!strcmp(token->string, "\\")); + } while (!strcmp(token->string, "\\")); return qtrue; -} //end of the function PC_ReadLine +} // end of the function PC_ReadLine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_WhiteSpaceBeforeToken(token_t *token) -{ - return token->endwhitespace_p - token->whitespace_p > 0; -} //end of the function PC_WhiteSpaceBeforeToken +int PC_WhiteSpaceBeforeToken(token_t *token) { return token->endwhitespace_p - token->whitespace_p > 0; } // end of the function PC_WhiteSpaceBeforeToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_ClearTokenWhiteSpace(token_t *token) -{ +void PC_ClearTokenWhiteSpace(token_t *token) { token->whitespace_p = NULL; token->endwhitespace_p = NULL; token->linescrossed = 0; -} //end of the function PC_ClearTokenWhiteSpace +} // end of the function PC_ClearTokenWhiteSpace //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_undef(source_t *source) -{ +int PC_Directive_undef(source_t *source) { token_t token; define_t *define, *lastdefine; int hash; - if (source->skip > 0) return qtrue; + if (source->skip > 0) + return qtrue; // - if (!PC_ReadLine(source, &token)) - { + if (!PC_ReadLine(source, &token)) { SourceError(source, "undef without name"); return qfalse; - } //end if - if (token.type != TT_NAME) - { + } // end if + if (token.type != TT_NAME) { PC_UnreadSourceToken(source, &token); SourceError(source, "expected name, found %s", token.string); return qfalse; - } //end if + } // end if #if DEFINEHASHING hash = PC_NameHash(token.string); - for (lastdefine = NULL, define = source->definehash[hash]; define; define = define->hashnext) - { - if (!strcmp(define->name, token.string)) - { - if (define->flags & DEFINE_FIXED) - { + for (lastdefine = NULL, define = source->definehash[hash]; define; define = define->hashnext) { + if (!strcmp(define->name, token.string)) { + if (define->flags & DEFINE_FIXED) { SourceWarning(source, "can't undef %s", token.string); - } //end if - else - { - if (lastdefine) lastdefine->hashnext = define->hashnext; - else source->definehash[hash] = define->hashnext; + } // end if + else { + if (lastdefine) + lastdefine->hashnext = define->hashnext; + else + source->definehash[hash] = define->hashnext; - if ( !(define->flags & DEFINE_GLOBAL ) ) - { + if (!(define->flags & DEFINE_GLOBAL)) { PC_FreeDefine(define); } - } //end else + } // end else break; - } //end if + } // end if lastdefine = define; - } //end for -#else //DEFINEHASHING - for (lastdefine = NULL, define = source->defines; define; define = define->next) - { - if (!strcmp(define->name, token.string)) - { - if (define->flags & DEFINE_FIXED) - { + } // end for +#else // DEFINEHASHING + for (lastdefine = NULL, define = source->defines; define; define = define->next) { + if (!strcmp(define->name, token.string)) { + if (define->flags & DEFINE_FIXED) { SourceWarning(source, "can't undef %s", token.string); - } //end if - else - { - if (lastdefine) lastdefine->next = define->next; - else source->defines = define->next; + } // end if + else { + if (lastdefine) + lastdefine->next = define->next; + else + source->defines = define->next; PC_FreeDefine(define); - } //end else + } // end else break; - } //end if + } // end if lastdefine = define; - } //end for -#endif //DEFINEHASHING + } // end for +#endif // DEFINEHASHING return qtrue; -} //end of the function PC_Directive_undef +} // end of the function PC_Directive_undef //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_define(source_t *source) -{ +int PC_Directive_define(source_t *source) { token_t token, *t, *last; define_t *define; - if (source->skip > 0) return qtrue; + if (source->skip > 0) + return qtrue; // - if (!PC_ReadLine(source, &token)) - { + if (!PC_ReadLine(source, &token)) { SourceError(source, "#define without name"); return qfalse; - } //end if - if (token.type != TT_NAME) - { + } // end if + if (token.type != TT_NAME) { PC_UnreadSourceToken(source, &token); SourceError(source, "expected name after #define, found %s", token.string); return qfalse; - } //end if - //check if the define already exists + } // end if + // check if the define already exists #if DEFINEHASHING define = PC_FindHashedDefine(source->definehash, token.string); #else define = PC_FindDefine(source->defines, token.string); -#endif //DEFINEHASHING - if (define) - { - if (define->flags & DEFINE_FIXED) - { +#endif // DEFINEHASHING + if (define) { + if (define->flags & DEFINE_FIXED) { SourceError(source, "can't redefine %s", token.string); return qfalse; - } //end if + } // end if SourceWarning(source, "redefinition of %s", token.string); - //unread the define name before executing the #undef directive + // unread the define name before executing the #undef directive PC_UnreadSourceToken(source, &token); - if (!PC_Directive_undef(source)) return qfalse; - //if the define was not removed (define->flags & DEFINE_FIXED) + if (!PC_Directive_undef(source)) + return qfalse; + // if the define was not removed (define->flags & DEFINE_FIXED) #if DEFINEHASHING define = PC_FindHashedDefine(source->definehash, token.string); #else define = PC_FindDefine(source->defines, token.string); -#endif //DEFINEHASHING - } //end if - //allocate define - define = (define_t *) GetMemory(sizeof(define_t)); +#endif // DEFINEHASHING + } // end if + // allocate define + define = (define_t *)GetMemory(sizeof(define_t)); Com_Memset(define, 0, sizeof(define_t)); - define->name = (char *) GetMemory(strlen(token.string) + 1); + define->name = (char *)GetMemory(strlen(token.string) + 1); strcpy(define->name, token.string); - //add the define to the source + // add the define to the source #if DEFINEHASHING PC_AddDefineToHash(define, source->definehash); -#else //DEFINEHASHING +#else // DEFINEHASHING define->next = source->defines; source->defines = define; -#endif //DEFINEHASHING - //if nothing is defined, just return - if (!PC_ReadLine(source, &token)) return qtrue; - //if it is a define with parameters - if (!PC_WhiteSpaceBeforeToken(&token) && !strcmp(token.string, "(")) - { - //read the define parameters +#endif // DEFINEHASHING + // if nothing is defined, just return + if (!PC_ReadLine(source, &token)) + return qtrue; + // if it is a define with parameters + if (!PC_WhiteSpaceBeforeToken(&token) && !strcmp(token.string, "(")) { + // read the define parameters last = NULL; - if (!PC_CheckTokenString(source, ")")) - { - while(1) - { - if (!PC_ReadLine(source, &token)) - { + if (!PC_CheckTokenString(source, ")")) { + while (1) { + if (!PC_ReadLine(source, &token)) { SourceError(source, "expected define parameter"); return qfalse; - } //end if - //if it isn't a name - if (token.type != TT_NAME) - { + } // end if + // if it isn't a name + if (token.type != TT_NAME) { SourceError(source, "invalid define parameter"); return qfalse; - } //end if + } // end if // - if (PC_FindDefineParm(define, token.string) >= 0) - { + if (PC_FindDefineParm(define, token.string) >= 0) { SourceError(source, "two the same define parameters"); return qfalse; - } //end if - //add the define parm + } // end if + // add the define parm t = PC_CopyToken(&token); PC_ClearTokenWhiteSpace(t); t->next = NULL; - if (last) last->next = t; - else define->parms = t; + if (last) + last->next = t; + else + define->parms = t; last = t; define->numparms++; - //read next token - if (!PC_ReadLine(source, &token)) - { + // read next token + if (!PC_ReadLine(source, &token)) { SourceError(source, "define parameters not terminated"); return qfalse; - } //end if + } // end if // - if (!strcmp(token.string, ")")) break; - //then it must be a comma - if (strcmp(token.string, ",")) - { + if (!strcmp(token.string, ")")) + break; + // then it must be a comma + if (strcmp(token.string, ",")) { SourceError(source, "define not terminated"); return qfalse; - } //end if - } //end while - } //end if - if (!PC_ReadLine(source, &token)) return qtrue; - } //end if - //read the defined stuff + } // end if + } // end while + } // end if + if (!PC_ReadLine(source, &token)) + return qtrue; + } // end if + // read the defined stuff last = NULL; - do - { + do { t = PC_CopyToken(&token); - if (t->type == TT_NAME && !strcmp(t->string, define->name)) - { + if (t->type == TT_NAME && !strcmp(t->string, define->name)) { SourceError(source, "recursive define (removed recursion)"); continue; - } //end if + } // end if PC_ClearTokenWhiteSpace(t); t->next = NULL; - if (last) last->next = t; - else define->tokens = t; + if (last) + last->next = t; + else + define->tokens = t; last = t; - } while(PC_ReadLine(source, &token)); + } while (PC_ReadLine(source, &token)); // - if (last) - { - //check for merge operators at the beginning or end - if (!strcmp(define->tokens->string, "##") || - !strcmp(last->string, "##")) - { + if (last) { + // check for merge operators at the beginning or end + if (!strcmp(define->tokens->string, "##") || !strcmp(last->string, "##")) { SourceError(source, "define with misplaced ##"); return qfalse; - } //end if - } //end if + } // end if + } // end if return qtrue; -} //end of the function PC_Directive_define +} // end of the function PC_Directive_define //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -define_t *PC_DefineFromString(char *string) -{ +define_t *PC_DefineFromString(char *string) { script_t *script; source_t src; token_t *t; @@ -1352,72 +1240,70 @@ define_t *PC_DefineFromString(char *string) PC_InitTokenHeap(); script = LoadScriptMemory(string, strlen(string), "*extern"); - //create a new source + // create a new source Com_Memset(&src, 0, sizeof(source_t)); strncpy(src.filename, "*extern", MAX_PATH); src.scriptstack = script; #if DEFINEHASHING src.definehash = (struct define_s **)GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *)); -#endif //DEFINEHASHING - //create a define from the source +#endif // DEFINEHASHING + // create a define from the source res = PC_Directive_define(&src); - //free any tokens if left - for (t = src.tokens; t; t = src.tokens) - { + // free any tokens if left + for (t = src.tokens; t; t = src.tokens) { src.tokens = src.tokens->next; PC_FreeToken(t); - } //end for + } // end for #ifdef DEFINEHASHING def = NULL; - for (i = 0; i < DEFINEHASHSIZE; i++) - { - if (src.definehash[i]) - { + for (i = 0; i < DEFINEHASHSIZE; i++) { + if (src.definehash[i]) { def = src.definehash[i]; break; - } //end if - } //end for + } // end if + } // end for #else def = src.defines; -#endif //DEFINEHASHING +#endif // DEFINEHASHING // #if DEFINEHASHING FreeMemory(src.definehash); -#endif //DEFINEHASHING +#endif // DEFINEHASHING // FreeScript(script); - //if the define was created successfully - if (res > 0) return def; - //free the define is created - if (src.defines) PC_FreeDefine(def); + // if the define was created successfully + if (res > 0) + return def; + // free the define is created + if (src.defines) + PC_FreeDefine(def); // return NULL; -} //end of the function PC_DefineFromString +} // end of the function PC_DefineFromString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_AddDefine(source_t *source, char *string) -{ +int PC_AddDefine(source_t *source, char *string) { define_t *define; - if ( addGlobalDefine ) - { - return PC_AddGlobalDefine ( string ); + if (addGlobalDefine) { + return PC_AddGlobalDefine(string); } define = PC_DefineFromString(string); - if (!define) return qfalse; + if (!define) + return qfalse; #if DEFINEHASHING PC_AddDefineToHash(define, source->definehash); -#else //DEFINEHASHING +#else // DEFINEHASHING define->next = source->defines; source->defines = define; -#endif //DEFINEHASHING +#endif // DEFINEHASHING return qtrue; -} //end of the function PC_AddDefine +} // end of the function PC_AddDefine //============================================================================ // add a globals define that will be added to all opened sources // @@ -1425,18 +1311,18 @@ int PC_AddDefine(source_t *source, char *string) // Returns: - // Changes Globals: - //============================================================================ -int PC_AddGlobalDefine(char *string) -{ +int PC_AddGlobalDefine(char *string) { #if !DEFINEHASHING define_t *define; define = PC_DefineFromString(string); - if (!define) return qfalse; + if (!define) + return qfalse; define->next = globaldefines; globaldefines = define; #endif return qtrue; -} //end of the function PC_AddGlobalDefine +} // end of the function PC_AddGlobalDefine //============================================================================ // remove the given global define // @@ -1444,20 +1330,18 @@ int PC_AddGlobalDefine(char *string) // Returns: - // Changes Globals: - //============================================================================ -int PC_RemoveGlobalDefine(char *name) -{ +int PC_RemoveGlobalDefine(char *name) { #if !DEFINEHASHING define_t *define; define = PC_FindDefine(globaldefines, name); - if (define) - { + if (define) { PC_FreeDefine(define); return qtrue; - } //end if + } // end if #endif return qfalse; -} //end of the function PC_RemoveGlobalDefine +} // end of the function PC_RemoveGlobalDefine //============================================================================ // remove all globals defines // @@ -1465,287 +1349,277 @@ int PC_RemoveGlobalDefine(char *name) // Returns: - // Changes Globals: - //============================================================================ -void PC_RemoveAllGlobalDefines(void) -{ +void PC_RemoveAllGlobalDefines(void) { define_t *define; #if DEFINEHASHING int i; - if ( globaldefines ) - { - for (i = 0; i < DEFINEHASHSIZE; i++) - { - while(globaldefines[i]) - { + if (globaldefines) { + for (i = 0; i < DEFINEHASHSIZE; i++) { + while (globaldefines[i]) { define = globaldefines[i]; globaldefines[i] = globaldefines[i]->globalnext; PC_FreeDefine(define); } } } -#else //DEFINEHASHING - for (define = globaldefines; define; define = globaldefines) - { +#else // DEFINEHASHING + for (define = globaldefines; define; define = globaldefines) { globaldefines = globaldefines->next; PC_FreeDefine(define); - } //end for + } // end for #endif -} //end of the function PC_RemoveAllGlobalDefines +} // end of the function PC_RemoveAllGlobalDefines //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -define_t *PC_CopyDefine(source_t *source, define_t *define) -{ +define_t *PC_CopyDefine(source_t *source, define_t *define) { define_t *newdefine; token_t *token, *newtoken, *lasttoken; - newdefine = (define_t *) GetMemory(sizeof(define_t)); - //copy the define name - newdefine->name = (char *) GetMemory(strlen(define->name) + 1); + newdefine = (define_t *)GetMemory(sizeof(define_t)); + // copy the define name + newdefine->name = (char *)GetMemory(strlen(define->name) + 1); strcpy(newdefine->name, define->name); newdefine->flags = define->flags; newdefine->builtin = define->builtin; newdefine->numparms = define->numparms; - //the define is not linked + // the define is not linked newdefine->next = NULL; newdefine->hashnext = NULL; - //copy the define tokens + // copy the define tokens newdefine->tokens = NULL; - for (lasttoken = NULL, token = define->tokens; token; token = token->next) - { + for (lasttoken = NULL, token = define->tokens; token; token = token->next) { newtoken = PC_CopyToken(token); newtoken->next = NULL; - if (lasttoken) lasttoken->next = newtoken; - else newdefine->tokens = newtoken; + if (lasttoken) + lasttoken->next = newtoken; + else + newdefine->tokens = newtoken; lasttoken = newtoken; - } //end for - //copy the define parameters + } // end for + // copy the define parameters newdefine->parms = NULL; - for (lasttoken = NULL, token = define->parms; token; token = token->next) - { + for (lasttoken = NULL, token = define->parms; token; token = token->next) { newtoken = PC_CopyToken(token); newtoken->next = NULL; - if (lasttoken) lasttoken->next = newtoken; - else newdefine->parms = newtoken; + if (lasttoken) + lasttoken->next = newtoken; + else + newdefine->parms = newtoken; lasttoken = newtoken; - } //end for + } // end for return newdefine; -} //end of the function PC_CopyDefine +} // end of the function PC_CopyDefine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_AddGlobalDefinesToSource(source_t *source) -{ +void PC_AddGlobalDefinesToSource(source_t *source) { define_t *define; #if DEFINEHASHING int i; - for (i = 0; i < DEFINEHASHSIZE; i++) - { + for (i = 0; i < DEFINEHASHSIZE; i++) { define = globaldefines[i]; - while(define) - { + while (define) { define->hashnext = NULL; PC_AddDefineToHash(define, source->definehash); define = define->globalnext; } } -#else //DEFINEHASHING - define_t* newdefine; - for (define = globaldefines; define; define = define->next) - { +#else // DEFINEHASHING + define_t *newdefine; + for (define = globaldefines; define; define = define->next) { newdefine = PC_CopyDefine(source, define); - - newdefine->next = source->defines; source->defines = newdefine; } #endif -} //end of the function PC_AddGlobalDefinesToSource +} // end of the function PC_AddGlobalDefinesToSource //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_if_def(source_t *source, int type) -{ +int PC_Directive_if_def(source_t *source, int type) { token_t token; define_t *d; int skip; - if (!PC_ReadLine(source, &token)) - { + if (!PC_ReadLine(source, &token)) { SourceError(source, "#ifdef without name"); return qfalse; - } //end if - if (token.type != TT_NAME) - { + } // end if + if (token.type != TT_NAME) { PC_UnreadSourceToken(source, &token); SourceError(source, "expected name after #ifdef, found %s", token.string); return qfalse; - } //end if + } // end if #if DEFINEHASHING d = PC_FindHashedDefine(source->definehash, token.string); #else d = PC_FindDefine(source->defines, token.string); -#endif //DEFINEHASHING +#endif // DEFINEHASHING skip = (type == INDENT_IFDEF) == (d == NULL); PC_PushIndent(source, type, skip); return qtrue; -} //end of the function PC_Directiveif_def +} // end of the function PC_Directiveif_def //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_ifdef(source_t *source) -{ - return PC_Directive_if_def(source, INDENT_IFDEF); -} //end of the function PC_Directive_ifdef +int PC_Directive_ifdef(source_t *source) { return PC_Directive_if_def(source, INDENT_IFDEF); } // end of the function PC_Directive_ifdef //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_ifndef(source_t *source) -{ - return PC_Directive_if_def(source, INDENT_IFNDEF); -} //end of the function PC_Directive_ifndef +int PC_Directive_ifndef(source_t *source) { return PC_Directive_if_def(source, INDENT_IFNDEF); } // end of the function PC_Directive_ifndef //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_else(source_t *source) -{ +int PC_Directive_else(source_t *source) { int type, skip; PC_PopIndent(source, &type, &skip); - if (!type) - { + if (!type) { SourceError(source, "misplaced #else"); return qfalse; - } //end if - if (type == INDENT_ELSE) - { + } // end if + if (type == INDENT_ELSE) { SourceError(source, "#else after #else"); return qfalse; - } //end if + } // end if PC_PushIndent(source, INDENT_ELSE, !skip); return qtrue; -} //end of the function PC_Directive_else +} // end of the function PC_Directive_else //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_endif(source_t *source) -{ +int PC_Directive_endif(source_t *source) { int type, skip; PC_PopIndent(source, &type, &skip); - if (!type) - { + if (!type) { SourceError(source, "misplaced #endif"); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function PC_Directive_endif +} // end of the function PC_Directive_endif //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -typedef struct operator_s -{ +typedef struct operator_s { int mOperator; int priority; int parentheses; struct operator_s *prev, *next; } operator_t; -typedef struct value_s -{ +typedef struct value_s { signed long int intvalue; double floatvalue; int parentheses; struct value_s *prev, *next; } value_t; -int PC_OperatorPriority(int op) -{ - switch(op) - { - case P_MUL: return 15; - case P_DIV: return 15; - case P_MOD: return 15; - case P_ADD: return 14; - case P_SUB: return 14; - - case P_LOGIC_AND: return 7; - case P_LOGIC_OR: return 6; - case P_LOGIC_GEQ: return 12; - case P_LOGIC_LEQ: return 12; - case P_LOGIC_EQ: return 11; - case P_LOGIC_UNEQ: return 11; - - case P_LOGIC_NOT: return 16; - case P_LOGIC_GREATER: return 12; - case P_LOGIC_LESS: return 12; - - case P_RSHIFT: return 13; - case P_LSHIFT: return 13; - - case P_BIN_AND: return 10; - case P_BIN_OR: return 8; - case P_BIN_XOR: return 9; - case P_BIN_NOT: return 16; - - case P_COLON: return 5; - case P_QUESTIONMARK: return 5; - } //end switch +int PC_OperatorPriority(int op) { + switch (op) { + case P_MUL: + return 15; + case P_DIV: + return 15; + case P_MOD: + return 15; + case P_ADD: + return 14; + case P_SUB: + return 14; + + case P_LOGIC_AND: + return 7; + case P_LOGIC_OR: + return 6; + case P_LOGIC_GEQ: + return 12; + case P_LOGIC_LEQ: + return 12; + case P_LOGIC_EQ: + return 11; + case P_LOGIC_UNEQ: + return 11; + + case P_LOGIC_NOT: + return 16; + case P_LOGIC_GREATER: + return 12; + case P_LOGIC_LESS: + return 12; + + case P_RSHIFT: + return 13; + case P_LSHIFT: + return 13; + + case P_BIN_AND: + return 10; + case P_BIN_OR: + return 8; + case P_BIN_XOR: + return 9; + case P_BIN_NOT: + return 16; + + case P_COLON: + return 5; + case P_QUESTIONMARK: + return 5; + } // end switch return qfalse; -} //end of the function PC_OperatorPriority - -#define MAX_VALUES 64 -#define MAX_OPERATORS 64 -#define AllocValue(val) \ - if (numvalues >= MAX_VALUES) { \ - SourceError(source, "out of value space"); \ - error = 1; \ - break; \ - } \ - else \ +} // end of the function PC_OperatorPriority + +#define MAX_VALUES 64 +#define MAX_OPERATORS 64 +#define AllocValue(val) \ + if (numvalues >= MAX_VALUES) { \ + SourceError(source, "out of value space"); \ + error = 1; \ + break; \ + } else \ val = &value_heap[numvalues++]; #define FreeValue(val) // -#define AllocOperator(op) \ - if (numoperators >= MAX_OPERATORS) { \ - SourceError(source, "out of operator space"); \ - error = 1; \ - break; \ - } \ - else \ +#define AllocOperator(op) \ + if (numoperators >= MAX_OPERATORS) { \ + SourceError(source, "out of operator space"); \ + error = 1; \ + break; \ + } else \ op = &operator_heap[numoperators++]; #define FreeOperator(op) -int PC_EvaluateTokens(source_t *source, token_t *tokens, signed long int *intvalue, - double *floatvalue, int integer) -{ +int PC_EvaluateTokens(source_t *source, token_t *tokens, signed long int *intvalue, double *floatvalue, int integer) { operator_t *o, *firstoperator, *lastoperator; value_t *v, *firstvalue, *lastvalue, *v1, *v2; token_t *t; @@ -1765,723 +1639,733 @@ int PC_EvaluateTokens(source_t *source, token_t *tokens, signed long int *intval firstoperator = lastoperator = NULL; firstvalue = lastvalue = NULL; - if (intvalue) *intvalue = 0; - if (floatvalue) *floatvalue = 0; - for (t = tokens; t; t = t->next) - { - switch(t->type) - { - case TT_NAME: - { - if (lastwasvalue || negativevalue) - { - SourceError(source, "syntax error in #if/#elif"); - error = 1; - break; - } //end if - if (strcmp(t->string, "defined")) - { - SourceError(source, "undefined name %s in #if/#elif", t->string); - error = 1; - break; - } //end if + if (intvalue) + *intvalue = 0; + if (floatvalue) + *floatvalue = 0; + for (t = tokens; t; t = t->next) { + switch (t->type) { + case TT_NAME: { + if (lastwasvalue || negativevalue) { + SourceError(source, "syntax error in #if/#elif"); + error = 1; + break; + } // end if + if (strcmp(t->string, "defined")) { + SourceError(source, "undefined name %s in #if/#elif", t->string); + error = 1; + break; + } // end if + t = t->next; + if (!strcmp(t->string, "(")) { + brace = qtrue; t = t->next; - if (!strcmp(t->string, "(")) - { - brace = qtrue; - t = t->next; - } //end if - if (!t || t->type != TT_NAME) - { - SourceError(source, "defined without name in #if/#elif"); - error = 1; - break; - } //end if - //v = (value_t *) GetClearedMemory(sizeof(value_t)); - AllocValue(v); + } // end if + if (!t || t->type != TT_NAME) { + SourceError(source, "defined without name in #if/#elif"); + error = 1; + break; + } // end if + // v = (value_t *) GetClearedMemory(sizeof(value_t)); + AllocValue(v); #if DEFINEHASHING - if (PC_FindHashedDefine(source->definehash, t->string)) + if (PC_FindHashedDefine(source->definehash, t->string)) #else - if (PC_FindDefine(source->defines, t->string)) -#endif //DEFINEHASHING - { - v->intvalue = 1; - v->floatvalue = 1; - } //end if - else - { - v->intvalue = 0; - v->floatvalue = 0; - } //end else - v->parentheses = parentheses; - v->next = NULL; - v->prev = lastvalue; - if (lastvalue) lastvalue->next = v; - else firstvalue = v; - lastvalue = v; - if (brace) - { - t = t->next; - if (!t || strcmp(t->string, ")")) - { - SourceError(source, "defined without ) in #if/#elif"); - error = 1; - break; - } //end if - } //end if - brace = qfalse; - // defined() creates a value - lastwasvalue = 1; - break; - } //end case - case TT_NUMBER: + if (PC_FindDefine(source->defines, t->string)) +#endif // DEFINEHASHING { - if (lastwasvalue) - { - SourceError(source, "syntax error in #if/#elif"); + v->intvalue = 1; + v->floatvalue = 1; + } // end if + else { + v->intvalue = 0; + v->floatvalue = 0; + } // end else + v->parentheses = parentheses; + v->next = NULL; + v->prev = lastvalue; + if (lastvalue) + lastvalue->next = v; + else + firstvalue = v; + lastvalue = v; + if (brace) { + t = t->next; + if (!t || strcmp(t->string, ")")) { + SourceError(source, "defined without ) in #if/#elif"); error = 1; break; - } //end if - //v = (value_t *) GetClearedMemory(sizeof(value_t)); - AllocValue(v); - if (negativevalue) - { - v->intvalue = - (signed int) t->intvalue; - v->floatvalue = - t->floatvalue; - } //end if - else - { - v->intvalue = t->intvalue; - v->floatvalue = t->floatvalue; - } //end else - v->parentheses = parentheses; - v->next = NULL; - v->prev = lastvalue; - if (lastvalue) lastvalue->next = v; - else firstvalue = v; - lastvalue = v; - //last token was a value - lastwasvalue = 1; - // - negativevalue = 0; - break; - } //end case - case TT_PUNCTUATION: - { - if (negativevalue) - { - SourceError(source, "misplaced minus sign in #if/#elif"); + } // end if + } // end if + brace = qfalse; + // defined() creates a value + lastwasvalue = 1; + break; + } // end case + case TT_NUMBER: { + if (lastwasvalue) { + SourceError(source, "syntax error in #if/#elif"); + error = 1; + break; + } // end if + // v = (value_t *) GetClearedMemory(sizeof(value_t)); + AllocValue(v); + if (negativevalue) { + v->intvalue = -(signed int)t->intvalue; + v->floatvalue = -t->floatvalue; + } // end if + else { + v->intvalue = t->intvalue; + v->floatvalue = t->floatvalue; + } // end else + v->parentheses = parentheses; + v->next = NULL; + v->prev = lastvalue; + if (lastvalue) + lastvalue->next = v; + else + firstvalue = v; + lastvalue = v; + // last token was a value + lastwasvalue = 1; + // + negativevalue = 0; + break; + } // end case + case TT_PUNCTUATION: { + if (negativevalue) { + SourceError(source, "misplaced minus sign in #if/#elif"); + error = 1; + break; + } // end if + if (t->subtype == P_PARENTHESESOPEN) { + parentheses++; + break; + } // end if + else if (t->subtype == P_PARENTHESESCLOSE) { + parentheses--; + if (parentheses < 0) { + SourceError(source, "too many ) in #if/#elsif"); + error = 1; + } // end if + break; + } // end else if + // check for invalid operators on floating point values + if (!integer) { + if (t->subtype == P_BIN_NOT || t->subtype == P_MOD || t->subtype == P_RSHIFT || t->subtype == P_LSHIFT || t->subtype == P_BIN_AND || + t->subtype == P_BIN_OR || t->subtype == P_BIN_XOR) { + SourceError(source, "illigal operator %s on floating point operands", t->string); + error = 1; + break; + } // end if + } // end if + switch (t->subtype) { + case P_LOGIC_NOT: + case P_BIN_NOT: { + if (lastwasvalue) { + SourceError(source, "! or ~ after value in #if/#elif"); error = 1; break; - } //end if - if (t->subtype == P_PARENTHESESOPEN) - { - parentheses++; + } // end if + break; + } // end case + case P_INC: + case P_DEC: { + SourceError(source, "++ or -- used in #if/#elif"); + break; + } // end case + case P_SUB: { + if (!lastwasvalue) { + negativevalue = 1; break; - } //end if - else if (t->subtype == P_PARENTHESESCLOSE) - { - parentheses--; - if (parentheses < 0) - { - SourceError(source, "too many ) in #if/#elsif"); - error = 1; - } //end if + } // end if + } // end case + + case P_MUL: + case P_DIV: + case P_MOD: + case P_ADD: + + case P_LOGIC_AND: + case P_LOGIC_OR: + case P_LOGIC_GEQ: + case P_LOGIC_LEQ: + case P_LOGIC_EQ: + case P_LOGIC_UNEQ: + + case P_LOGIC_GREATER: + case P_LOGIC_LESS: + + case P_RSHIFT: + case P_LSHIFT: + + case P_BIN_AND: + case P_BIN_OR: + case P_BIN_XOR: + + case P_COLON: + case P_QUESTIONMARK: { + if (!lastwasvalue) { + SourceError(source, "operator %s after operator in #if/#elif", t->string); + error = 1; break; - } //end else if - //check for invalid operators on floating point values - if (!integer) - { - if (t->subtype == P_BIN_NOT || t->subtype == P_MOD || - t->subtype == P_RSHIFT || t->subtype == P_LSHIFT || - t->subtype == P_BIN_AND || t->subtype == P_BIN_OR || - t->subtype == P_BIN_XOR) - { - SourceError(source, "illigal operator %s on floating point operands", t->string); - error = 1; - break; - } //end if - } //end if - switch(t->subtype) - { - case P_LOGIC_NOT: - case P_BIN_NOT: - { - if (lastwasvalue) - { - SourceError(source, "! or ~ after value in #if/#elif"); - error = 1; - break; - } //end if - break; - } //end case - case P_INC: - case P_DEC: - { - SourceError(source, "++ or -- used in #if/#elif"); - break; - } //end case - case P_SUB: - { - if (!lastwasvalue) - { - negativevalue = 1; - break; - } //end if - } //end case - - case P_MUL: - case P_DIV: - case P_MOD: - case P_ADD: - - case P_LOGIC_AND: - case P_LOGIC_OR: - case P_LOGIC_GEQ: - case P_LOGIC_LEQ: - case P_LOGIC_EQ: - case P_LOGIC_UNEQ: - - case P_LOGIC_GREATER: - case P_LOGIC_LESS: - - case P_RSHIFT: - case P_LSHIFT: - - case P_BIN_AND: - case P_BIN_OR: - case P_BIN_XOR: - - case P_COLON: - case P_QUESTIONMARK: - { - if (!lastwasvalue) - { - SourceError(source, "operator %s after operator in #if/#elif", t->string); - error = 1; - break; - } //end if - break; - } //end case - default: - { - SourceError(source, "invalid operator %s in #if/#elif", t->string); - error = 1; - break; - } //end default - } //end switch - if (!error && !negativevalue) - { - //o = (operator_t *) GetClearedMemory(sizeof(operator_t)); - AllocOperator(o); - o->mOperator = t->subtype; - o->priority = PC_OperatorPriority(t->subtype); - o->parentheses = parentheses; - o->next = NULL; - o->prev = lastoperator; - if (lastoperator) lastoperator->next = o; - else firstoperator = o; - lastoperator = o; - lastwasvalue = 0; - } //end if + } // end if break; - } //end case - default: - { - SourceError(source, "unknown %s in #if/#elif", t->string); + } // end case + default: { + SourceError(source, "invalid operator %s in #if/#elif", t->string); error = 1; break; - } //end default - } //end switch - if (error) break; - } //end for - if (!error) - { - if (!lastwasvalue) - { + } // end default + } // end switch + if (!error && !negativevalue) { + // o = (operator_t *) GetClearedMemory(sizeof(operator_t)); + AllocOperator(o); + o->mOperator = t->subtype; + o->priority = PC_OperatorPriority(t->subtype); + o->parentheses = parentheses; + o->next = NULL; + o->prev = lastoperator; + if (lastoperator) + lastoperator->next = o; + else + firstoperator = o; + lastoperator = o; + lastwasvalue = 0; + } // end if + break; + } // end case + default: { + SourceError(source, "unknown %s in #if/#elif", t->string); + error = 1; + break; + } // end default + } // end switch + if (error) + break; + } // end for + if (!error) { + if (!lastwasvalue) { SourceError(source, "trailing operator in #if/#elif"); error = 1; - } //end if - else if (parentheses) - { + } // end if + else if (parentheses) { SourceError(source, "too many ( in #if/#elif"); error = 1; - } //end else if - } //end if + } // end else if + } // end if // gotquestmarkvalue = qfalse; questmarkintvalue = 0; questmarkfloatvalue = 0; - //while there are operators - while(!error && firstoperator) - { + // while there are operators + while (!error && firstoperator) { v = firstvalue; - for (o = firstoperator; o->next; o = o->next) - { - //if the current operator is nested deeper in parentheses - //than the next operator - if (o->parentheses > o->next->parentheses) break; - //if the current and next operator are nested equally deep in parentheses - if (o->parentheses == o->next->parentheses) - { - //if the priority of the current operator is equal or higher - //than the priority of the next operator - if (o->priority >= o->next->priority) break; - } //end if - //if the arity of the operator isn't equal to 1 - if (o->mOperator != P_LOGIC_NOT - && o->mOperator != P_BIN_NOT) v = v->next; - //if there's no value or no next value - if (!v) - { + for (o = firstoperator; o->next; o = o->next) { + // if the current operator is nested deeper in parentheses + // than the next operator + if (o->parentheses > o->next->parentheses) + break; + // if the current and next operator are nested equally deep in parentheses + if (o->parentheses == o->next->parentheses) { + // if the priority of the current operator is equal or higher + // than the priority of the next operator + if (o->priority >= o->next->priority) + break; + } // end if + // if the arity of the operator isn't equal to 1 + if (o->mOperator != P_LOGIC_NOT && o->mOperator != P_BIN_NOT) + v = v->next; + // if there's no value or no next value + if (!v) { SourceError(source, "mising values in #if/#elif"); error = 1; break; - } //end if - } //end for - if (error) break; + } // end if + } // end for + if (error) + break; v1 = v; v2 = v->next; #ifdef DEBUG_EVAL - if (integer) - { + if (integer) { Log_Write("operator %s, value1 = %d", PunctuationFromNum(source->scriptstack, o->mOperator), v1->intvalue); - if (v2) Log_Write("value2 = %d", v2->intvalue); - } //end if - else - { + if (v2) + Log_Write("value2 = %d", v2->intvalue); + } // end if + else { Log_Write("operator %s, value1 = %f", PunctuationFromNum(source->scriptstack, o->mOperator), v1->floatvalue); - if (v2) Log_Write("value2 = %f", v2->floatvalue); - } //end else -#endif //DEBUG_EVAL - switch(o->mOperator) - { - case P_LOGIC_NOT: v1->intvalue = !v1->intvalue; - v1->floatvalue = !v1->floatvalue; break; - case P_BIN_NOT: v1->intvalue = ~v1->intvalue; - break; - case P_MUL: v1->intvalue *= v2->intvalue; - v1->floatvalue *= v2->floatvalue; break; - case P_DIV: if (!v2->intvalue || !v2->floatvalue) - { - SourceError(source, "divide by zero in #if/#elif"); - error = 1; - break; - } - v1->intvalue /= v2->intvalue; - v1->floatvalue /= v2->floatvalue; break; - case P_MOD: if (!v2->intvalue) - { - SourceError(source, "divide by zero in #if/#elif"); - error = 1; - break; - } - v1->intvalue %= v2->intvalue; break; - case P_ADD: v1->intvalue += v2->intvalue; - v1->floatvalue += v2->floatvalue; break; - case P_SUB: v1->intvalue -= v2->intvalue; - v1->floatvalue -= v2->floatvalue; break; - case P_LOGIC_AND: v1->intvalue = v1->intvalue && v2->intvalue; - v1->floatvalue = v1->floatvalue && v2->floatvalue; break; - case P_LOGIC_OR: v1->intvalue = v1->intvalue || v2->intvalue; - v1->floatvalue = v1->floatvalue || v2->floatvalue; break; - case P_LOGIC_GEQ: v1->intvalue = v1->intvalue >= v2->intvalue; - v1->floatvalue = v1->floatvalue >= v2->floatvalue; break; - case P_LOGIC_LEQ: v1->intvalue = v1->intvalue <= v2->intvalue; - v1->floatvalue = v1->floatvalue <= v2->floatvalue; break; - case P_LOGIC_EQ: v1->intvalue = v1->intvalue == v2->intvalue; - v1->floatvalue = v1->floatvalue == v2->floatvalue; break; - case P_LOGIC_UNEQ: v1->intvalue = v1->intvalue != v2->intvalue; - v1->floatvalue = v1->floatvalue != v2->floatvalue; break; - case P_LOGIC_GREATER: v1->intvalue = v1->intvalue > v2->intvalue; - v1->floatvalue = v1->floatvalue > v2->floatvalue; break; - case P_LOGIC_LESS: v1->intvalue = v1->intvalue < v2->intvalue; - v1->floatvalue = v1->floatvalue < v2->floatvalue; break; - case P_RSHIFT: v1->intvalue >>= v2->intvalue; - break; - case P_LSHIFT: v1->intvalue <<= v2->intvalue; - break; - case P_BIN_AND: v1->intvalue &= v2->intvalue; - break; - case P_BIN_OR: v1->intvalue |= v2->intvalue; - break; - case P_BIN_XOR: v1->intvalue ^= v2->intvalue; - break; - case P_COLON: - { - if (!gotquestmarkvalue) - { - SourceError(source, ": without ? in #if/#elif"); - error = 1; - break; - } //end if - if (integer) - { - if (!questmarkintvalue) v1->intvalue = v2->intvalue; - } //end if - else - { - if (!questmarkfloatvalue) v1->floatvalue = v2->floatvalue; - } //end else - gotquestmarkvalue = qfalse; + if (v2) + Log_Write("value2 = %f", v2->floatvalue); + } // end else +#endif // DEBUG_EVAL + switch (o->mOperator) { + case P_LOGIC_NOT: + v1->intvalue = !v1->intvalue; + v1->floatvalue = !v1->floatvalue; + break; + case P_BIN_NOT: + v1->intvalue = ~v1->intvalue; + break; + case P_MUL: + v1->intvalue *= v2->intvalue; + v1->floatvalue *= v2->floatvalue; + break; + case P_DIV: + if (!v2->intvalue || !v2->floatvalue) { + SourceError(source, "divide by zero in #if/#elif"); + error = 1; break; - } //end case - case P_QUESTIONMARK: - { - if (gotquestmarkvalue) - { - SourceError(source, "? after ? in #if/#elif"); - error = 1; - break; - } //end if - questmarkintvalue = v1->intvalue; - questmarkfloatvalue = v1->floatvalue; - gotquestmarkvalue = qtrue; + } + v1->intvalue /= v2->intvalue; + v1->floatvalue /= v2->floatvalue; + break; + case P_MOD: + if (!v2->intvalue) { + SourceError(source, "divide by zero in #if/#elif"); + error = 1; break; - } //end if - } //end switch + } + v1->intvalue %= v2->intvalue; + break; + case P_ADD: + v1->intvalue += v2->intvalue; + v1->floatvalue += v2->floatvalue; + break; + case P_SUB: + v1->intvalue -= v2->intvalue; + v1->floatvalue -= v2->floatvalue; + break; + case P_LOGIC_AND: + v1->intvalue = v1->intvalue && v2->intvalue; + v1->floatvalue = v1->floatvalue && v2->floatvalue; + break; + case P_LOGIC_OR: + v1->intvalue = v1->intvalue || v2->intvalue; + v1->floatvalue = v1->floatvalue || v2->floatvalue; + break; + case P_LOGIC_GEQ: + v1->intvalue = v1->intvalue >= v2->intvalue; + v1->floatvalue = v1->floatvalue >= v2->floatvalue; + break; + case P_LOGIC_LEQ: + v1->intvalue = v1->intvalue <= v2->intvalue; + v1->floatvalue = v1->floatvalue <= v2->floatvalue; + break; + case P_LOGIC_EQ: + v1->intvalue = v1->intvalue == v2->intvalue; + v1->floatvalue = v1->floatvalue == v2->floatvalue; + break; + case P_LOGIC_UNEQ: + v1->intvalue = v1->intvalue != v2->intvalue; + v1->floatvalue = v1->floatvalue != v2->floatvalue; + break; + case P_LOGIC_GREATER: + v1->intvalue = v1->intvalue > v2->intvalue; + v1->floatvalue = v1->floatvalue > v2->floatvalue; + break; + case P_LOGIC_LESS: + v1->intvalue = v1->intvalue < v2->intvalue; + v1->floatvalue = v1->floatvalue < v2->floatvalue; + break; + case P_RSHIFT: + v1->intvalue >>= v2->intvalue; + break; + case P_LSHIFT: + v1->intvalue <<= v2->intvalue; + break; + case P_BIN_AND: + v1->intvalue &= v2->intvalue; + break; + case P_BIN_OR: + v1->intvalue |= v2->intvalue; + break; + case P_BIN_XOR: + v1->intvalue ^= v2->intvalue; + break; + case P_COLON: { + if (!gotquestmarkvalue) { + SourceError(source, ": without ? in #if/#elif"); + error = 1; + break; + } // end if + if (integer) { + if (!questmarkintvalue) + v1->intvalue = v2->intvalue; + } // end if + else { + if (!questmarkfloatvalue) + v1->floatvalue = v2->floatvalue; + } // end else + gotquestmarkvalue = qfalse; + break; + } // end case + case P_QUESTIONMARK: { + if (gotquestmarkvalue) { + SourceError(source, "? after ? in #if/#elif"); + error = 1; + break; + } // end if + questmarkintvalue = v1->intvalue; + questmarkfloatvalue = v1->floatvalue; + gotquestmarkvalue = qtrue; + break; + } // end if + } // end switch #ifdef DEBUG_EVAL - if (integer) Log_Write("result value = %d", v1->intvalue); - else Log_Write("result value = %f", v1->floatvalue); -#endif //DEBUG_EVAL - if (error) break; - //if not an operator with arity 1 - if (o->mOperator != P_LOGIC_NOT - && o->mOperator != P_BIN_NOT) - { - //remove the second value if not question mark operator - if (o->mOperator != P_QUESTIONMARK) v = v->next; + if (integer) + Log_Write("result value = %d", v1->intvalue); + else + Log_Write("result value = %f", v1->floatvalue); +#endif // DEBUG_EVAL + if (error) + break; + // if not an operator with arity 1 + if (o->mOperator != P_LOGIC_NOT && o->mOperator != P_BIN_NOT) { + // remove the second value if not question mark operator + if (o->mOperator != P_QUESTIONMARK) + v = v->next; // - if (v->prev) v->prev->next = v->next; - else firstvalue = v->next; - if (v->next) v->next->prev = v->prev; - else lastvalue = v->prev; - //FreeMemory(v); + if (v->prev) + v->prev->next = v->next; + else + firstvalue = v->next; + if (v->next) + v->next->prev = v->prev; + else + lastvalue = v->prev; + // FreeMemory(v); FreeValue(v); - } //end if - //remove the operator - if (o->prev) o->prev->next = o->next; - else firstoperator = o->next; - if (o->next) o->next->prev = o->prev; - else lastoperator = o->prev; - //FreeMemory(o); + } // end if + // remove the operator + if (o->prev) + o->prev->next = o->next; + else + firstoperator = o->next; + if (o->next) + o->next->prev = o->prev; + else + lastoperator = o->prev; + // FreeMemory(o); FreeOperator(o); - } //end while - if (firstvalue) - { - if (intvalue) *intvalue = firstvalue->intvalue; - if (floatvalue) *floatvalue = firstvalue->floatvalue; - } //end if - for (o = firstoperator; o; o = lastoperator) - { + } // end while + if (firstvalue) { + if (intvalue) + *intvalue = firstvalue->intvalue; + if (floatvalue) + *floatvalue = firstvalue->floatvalue; + } // end if + for (o = firstoperator; o; o = lastoperator) { lastoperator = o->next; - //FreeMemory(o); + // FreeMemory(o); FreeOperator(o); - } //end for - for (v = firstvalue; v; v = lastvalue) - { + } // end for + for (v = firstvalue; v; v = lastvalue) { lastvalue = v->next; - //FreeMemory(v); + // FreeMemory(v); FreeValue(v); - } //end for - if (!error) return qtrue; - if (intvalue) *intvalue = 0; - if (floatvalue) *floatvalue = 0; + } // end for + if (!error) + return qtrue; + if (intvalue) + *intvalue = 0; + if (floatvalue) + *floatvalue = 0; return qfalse; -} //end of the function PC_EvaluateTokens +} // end of the function PC_EvaluateTokens //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Evaluate(source_t *source, signed long int *intvalue, - double *floatvalue, int integer) -{ +int PC_Evaluate(source_t *source, signed long int *intvalue, double *floatvalue, int integer) { token_t token, *firsttoken, *lasttoken; token_t *t, *nexttoken; define_t *define; int defined = qfalse; - if (intvalue) *intvalue = 0; - if (floatvalue) *floatvalue = 0; + if (intvalue) + *intvalue = 0; + if (floatvalue) + *floatvalue = 0; // - if (!PC_ReadLine(source, &token)) - { + if (!PC_ReadLine(source, &token)) { SourceError(source, "no value after #if/#elif"); return qfalse; - } //end if + } // end if firsttoken = NULL; lasttoken = NULL; - do - { - //if the token is a name - if (token.type == TT_NAME) - { - if (defined) - { + do { + // if the token is a name + if (token.type == TT_NAME) { + if (defined) { defined = qfalse; t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end if - else if (!strcmp(token.string, "defined")) - { + } // end if + else if (!strcmp(token.string, "defined")) { defined = qtrue; t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end if - else - { - //then it must be a define + } // end if + else { + // then it must be a define #if DEFINEHASHING define = PC_FindHashedDefine(source->definehash, token.string); #else define = PC_FindDefine(source->defines, token.string); -#endif //DEFINEHASHING - if (!define) - { +#endif // DEFINEHASHING + if (!define) { SourceError(source, "can't evaluate %s, not defined", token.string); return qfalse; - } //end if - if (!PC_ExpandDefineIntoSource(source, &token, define)) return qfalse; - } //end else - } //end if - //if the token is a number or a punctuation - else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION) - { + } // end if + if (!PC_ExpandDefineIntoSource(source, &token, define)) + return qfalse; + } // end else + } // end if + // if the token is a number or a punctuation + else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION) { t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end else - else //can't evaluate the token + } // end else + else // can't evaluate the token { SourceError(source, "can't evaluate %s", token.string); return qfalse; - } //end else - } while(PC_ReadLine(source, &token)); - // - if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) return qfalse; + } // end else + } while (PC_ReadLine(source, &token)); // + if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) + return qfalse; + // #ifdef DEBUG_EVAL Log_Write("eval:"); -#endif //DEBUG_EVAL - for (t = firsttoken; t; t = nexttoken) - { +#endif // DEBUG_EVAL + for (t = firsttoken; t; t = nexttoken) { #ifdef DEBUG_EVAL Log_Write(" %s", t->string); -#endif //DEBUG_EVAL +#endif // DEBUG_EVAL nexttoken = t->next; PC_FreeToken(t); - } //end for + } // end for #ifdef DEBUG_EVAL - if (integer) Log_Write("eval result: %d", *intvalue); - else Log_Write("eval result: %f", *floatvalue); -#endif //DEBUG_EVAL + if (integer) + Log_Write("eval result: %d", *intvalue); + else + Log_Write("eval result: %f", *floatvalue); +#endif // DEBUG_EVAL // return qtrue; -} //end of the function PC_Evaluate +} // end of the function PC_Evaluate //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_DollarEvaluate(source_t *source, signed long int *intvalue, - double *floatvalue, int integer) -{ +int PC_DollarEvaluate(source_t *source, signed long int *intvalue, double *floatvalue, int integer) { int indent, defined = qfalse; token_t token, *firsttoken, *lasttoken; token_t *t, *nexttoken; define_t *define; - if (intvalue) *intvalue = 0; - if (floatvalue) *floatvalue = 0; + if (intvalue) + *intvalue = 0; + if (floatvalue) + *floatvalue = 0; // - if (!PC_ReadSourceToken(source, &token)) - { + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "no leading ( after $evalint/$evalfloat"); return qfalse; - } //end if - if (!PC_ReadSourceToken(source, &token)) - { + } // end if + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "nothing to evaluate"); return qfalse; - } //end if + } // end if indent = 1; firsttoken = NULL; lasttoken = NULL; - do - { - //if the token is a name - if (token.type == TT_NAME) - { - if (defined) - { + do { + // if the token is a name + if (token.type == TT_NAME) { + if (defined) { defined = qfalse; t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end if - else if (!strcmp(token.string, "defined")) - { + } // end if + else if (!strcmp(token.string, "defined")) { defined = qtrue; t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end if - else - { - //then it must be a define + } // end if + else { + // then it must be a define #if DEFINEHASHING define = PC_FindHashedDefine(source->definehash, token.string); #else define = PC_FindDefine(source->defines, token.string); -#endif //DEFINEHASHING - if (!define) - { +#endif // DEFINEHASHING + if (!define) { SourceError(source, "can't evaluate %s, not defined", token.string); return qfalse; - } //end if - if (!PC_ExpandDefineIntoSource(source, &token, define)) return qfalse; - } //end else - } //end if - //if the token is a number or a punctuation - else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION) - { - if (*token.string == '(') indent++; - else if (*token.string == ')') indent--; - if (indent <= 0) break; + } // end if + if (!PC_ExpandDefineIntoSource(source, &token, define)) + return qfalse; + } // end else + } // end if + // if the token is a number or a punctuation + else if (token.type == TT_NUMBER || token.type == TT_PUNCTUATION) { + if (*token.string == '(') + indent++; + else if (*token.string == ')') + indent--; + if (indent <= 0) + break; t = PC_CopyToken(&token); t->next = NULL; - if (lasttoken) lasttoken->next = t; - else firsttoken = t; + if (lasttoken) + lasttoken->next = t; + else + firsttoken = t; lasttoken = t; - } //end else - else //can't evaluate the token + } // end else + else // can't evaluate the token { SourceError(source, "can't evaluate %s", token.string); return qfalse; - } //end else - } while(PC_ReadSourceToken(source, &token)); - // - if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) return qfalse; + } // end else + } while (PC_ReadSourceToken(source, &token)); // + if (!PC_EvaluateTokens(source, firsttoken, intvalue, floatvalue, integer)) + return qfalse; + // #ifdef DEBUG_EVAL Log_Write("$eval:"); -#endif //DEBUG_EVAL - for (t = firsttoken; t; t = nexttoken) - { +#endif // DEBUG_EVAL + for (t = firsttoken; t; t = nexttoken) { #ifdef DEBUG_EVAL Log_Write(" %s", t->string); -#endif //DEBUG_EVAL +#endif // DEBUG_EVAL nexttoken = t->next; PC_FreeToken(t); - } //end for + } // end for #ifdef DEBUG_EVAL - if (integer) Log_Write("$eval result: %d", *intvalue); - else Log_Write("$eval result: %f", *floatvalue); -#endif //DEBUG_EVAL + if (integer) + Log_Write("$eval result: %d", *intvalue); + else + Log_Write("$eval result: %f", *floatvalue); +#endif // DEBUG_EVAL // return qtrue; -} //end of the function PC_DollarEvaluate +} // end of the function PC_DollarEvaluate //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_elif(source_t *source) -{ +int PC_Directive_elif(source_t *source) { signed long int value; int type, skip; PC_PopIndent(source, &type, &skip); - if (!type || type == INDENT_ELSE) - { + if (!type || type == INDENT_ELSE) { SourceError(source, "misplaced #elif"); return qfalse; - } //end if - if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse; + } // end if + if (!PC_Evaluate(source, &value, NULL, qtrue)) + return qfalse; skip = (value == 0); PC_PushIndent(source, INDENT_ELIF, skip); return qtrue; -} //end of the function PC_Directive_elif +} // end of the function PC_Directive_elif //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_if(source_t *source) -{ +int PC_Directive_if(source_t *source) { signed long int value; int skip; - if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse; + if (!PC_Evaluate(source, &value, NULL, qtrue)) + return qfalse; skip = (value == 0); PC_PushIndent(source, INDENT_IF, skip); return qtrue; -} //end of the function PC_Directive +} // end of the function PC_Directive //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_line(source_t *source) -{ +int PC_Directive_line(source_t *source) { SourceError(source, "#line directive not supported"); return qfalse; -} //end of the function PC_Directive_line +} // end of the function PC_Directive_line //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_error(source_t *source) -{ +int PC_Directive_error(source_t *source) { token_t token; strcpy(token.string, ""); PC_ReadSourceToken(source, &token); SourceError(source, "#error directive: %s", token.string); return qfalse; -} //end of the function PC_Directive_error +} // end of the function PC_Directive_error //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_pragma(source_t *source) -{ +int PC_Directive_pragma(source_t *source) { token_t token; SourceWarning(source, "#pragma directive not supported"); - while(PC_ReadLine(source, &token)) ; + while (PC_ReadLine(source, &token)) + ; return qtrue; -} //end of the function PC_Directive_pragma +} // end of the function PC_Directive_pragma //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void UnreadSignToken(source_t *source) -{ +void UnreadSignToken(source_t *source) { token_t token; token.line = source->scriptstack->line; @@ -2492,19 +2376,19 @@ void UnreadSignToken(source_t *source) token.type = TT_PUNCTUATION; token.subtype = P_SUB; PC_UnreadSourceToken(source, &token); -} //end of the function UnreadSignToken +} // end of the function UnreadSignToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_eval(source_t *source) -{ +int PC_Directive_eval(source_t *source) { signed long int value; token_t token; - if (!PC_Evaluate(source, &value, NULL, qtrue)) return qfalse; + if (!PC_Evaluate(source, &value, NULL, qtrue)) + return qfalse; // token.line = source->scriptstack->line; token.whitespace_p = source->scriptstack->script_p; @@ -2512,104 +2396,87 @@ int PC_Directive_eval(source_t *source) token.linescrossed = 0; sprintf(token.string, "%ld", labs(value)); token.type = TT_NUMBER; - token.subtype = TT_INTEGER|TT_LONG|TT_DECIMAL; + token.subtype = TT_INTEGER | TT_LONG | TT_DECIMAL; PC_UnreadSourceToken(source, &token); - if (value < 0) UnreadSignToken(source); + if (value < 0) + UnreadSignToken(source); return qtrue; -} //end of the function PC_Directive_eval +} // end of the function PC_Directive_eval //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_Directive_evalfloat(source_t *source) -{ +int PC_Directive_evalfloat(source_t *source) { double value; token_t token; - if (!PC_Evaluate(source, NULL, &value, qfalse)) return qfalse; + if (!PC_Evaluate(source, NULL, &value, qfalse)) + return qfalse; token.line = source->scriptstack->line; token.whitespace_p = source->scriptstack->script_p; token.endwhitespace_p = source->scriptstack->script_p; token.linescrossed = 0; sprintf(token.string, "%1.2f", fabs(value)); token.type = TT_NUMBER; - token.subtype = TT_FLOAT|TT_LONG|TT_DECIMAL; + token.subtype = TT_FLOAT | TT_LONG | TT_DECIMAL; PC_UnreadSourceToken(source, &token); - if (value < 0) UnreadSignToken(source); + if (value < 0) + UnreadSignToken(source); return qtrue; -} //end of the function PC_Directive_evalfloat +} // end of the function PC_Directive_evalfloat //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -directive_t directives[20] = -{ - {"if", PC_Directive_if}, - {"ifdef", PC_Directive_ifdef}, - {"ifndef", PC_Directive_ifndef}, - {"elif", PC_Directive_elif}, - {"else", PC_Directive_else}, - {"endif", PC_Directive_endif}, - {"include", PC_Directive_include}, - {"define", PC_Directive_define}, - {"undef", PC_Directive_undef}, - {"line", PC_Directive_line}, - {"error", PC_Directive_error}, - {"pragma", PC_Directive_pragma}, - {"eval", PC_Directive_eval}, - {"evalfloat", PC_Directive_evalfloat}, - {NULL, NULL} -}; - -int PC_ReadDirective(source_t *source) -{ +directive_t directives[20] = {{"if", PC_Directive_if}, {"ifdef", PC_Directive_ifdef}, {"ifndef", PC_Directive_ifndef}, + {"elif", PC_Directive_elif}, {"else", PC_Directive_else}, {"endif", PC_Directive_endif}, + {"include", PC_Directive_include}, {"define", PC_Directive_define}, {"undef", PC_Directive_undef}, + {"line", PC_Directive_line}, {"error", PC_Directive_error}, {"pragma", PC_Directive_pragma}, + {"eval", PC_Directive_eval}, {"evalfloat", PC_Directive_evalfloat}, {NULL, NULL}}; + +int PC_ReadDirective(source_t *source) { token_t token; int i; - //read the directive name - if (!PC_ReadSourceToken(source, &token)) - { + // read the directive name + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "found # without name"); return qfalse; - } //end if - //directive name must be on the same line - if (token.linescrossed > 0) - { + } // end if + // directive name must be on the same line + if (token.linescrossed > 0) { PC_UnreadSourceToken(source, &token); SourceError(source, "found # at end of line"); return qfalse; - } //end if - //if if is a name - if (token.type == TT_NAME) - { - //find the precompiler directive - for (i = 0; directives[i].name; i++) - { - if (!strcmp(directives[i].name, token.string)) - { + } // end if + // if if is a name + if (token.type == TT_NAME) { + // find the precompiler directive + for (i = 0; directives[i].name; i++) { + if (!strcmp(directives[i].name, token.string)) { return directives[i].func(source); - } //end if - } //end for - } //end if + } // end if + } // end for + } // end if SourceError(source, "unknown precompiler directive %s", token.string); return qfalse; -} //end of the function PC_ReadDirective +} // end of the function PC_ReadDirective //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_DollarDirective_evalint(source_t *source) -{ +int PC_DollarDirective_evalint(source_t *source) { signed long int value; token_t token; - if (!PC_DollarEvaluate(source, &value, NULL, qtrue)) return qfalse; + if (!PC_DollarEvaluate(source, &value, NULL, qtrue)) + return qfalse; // token.line = source->scriptstack->line; token.whitespace_p = source->scriptstack->script_p; @@ -2617,97 +2484,86 @@ int PC_DollarDirective_evalint(source_t *source) token.linescrossed = 0; sprintf(token.string, "%ld", labs(value)); token.type = TT_NUMBER; - token.subtype = TT_INTEGER|TT_LONG|TT_DECIMAL; + token.subtype = TT_INTEGER | TT_LONG | TT_DECIMAL; #ifdef NUMBERVALUE token.intvalue = labs(value); token.floatvalue = token.intvalue; -#endif //NUMBERVALUE +#endif // NUMBERVALUE PC_UnreadSourceToken(source, &token); if (value < 0) UnreadSignToken(source); return qtrue; -} //end of the function PC_DollarDirective_evalint +} // end of the function PC_DollarDirective_evalint //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_DollarDirective_evalfloat(source_t *source) -{ +int PC_DollarDirective_evalfloat(source_t *source) { double value; token_t token; - if (!PC_DollarEvaluate(source, NULL, &value, qfalse)) return qfalse; + if (!PC_DollarEvaluate(source, NULL, &value, qfalse)) + return qfalse; token.line = source->scriptstack->line; token.whitespace_p = source->scriptstack->script_p; token.endwhitespace_p = source->scriptstack->script_p; token.linescrossed = 0; sprintf(token.string, "%1.2f", fabs(value)); token.type = TT_NUMBER; - token.subtype = TT_FLOAT|TT_LONG|TT_DECIMAL; + token.subtype = TT_FLOAT | TT_LONG | TT_DECIMAL; #ifdef NUMBERVALUE token.floatvalue = fabs(value); - token.intvalue = (unsigned long) token.floatvalue; -#endif //NUMBERVALUE + token.intvalue = (unsigned long)token.floatvalue; +#endif // NUMBERVALUE PC_UnreadSourceToken(source, &token); if (value < 0) UnreadSignToken(source); return qtrue; -} //end of the function PC_DollarDirective_evalfloat +} // end of the function PC_DollarDirective_evalfloat //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -directive_t dollardirectives[20] = -{ - {"evalint", PC_DollarDirective_evalint}, - {"evalfloat", PC_DollarDirective_evalfloat}, - {NULL, NULL} -}; +directive_t dollardirectives[20] = {{"evalint", PC_DollarDirective_evalint}, {"evalfloat", PC_DollarDirective_evalfloat}, {NULL, NULL}}; -int PC_ReadDollarDirective(source_t *source) -{ +int PC_ReadDollarDirective(source_t *source) { token_t token; int i; - //read the directive name - if (!PC_ReadSourceToken(source, &token)) - { + // read the directive name + if (!PC_ReadSourceToken(source, &token)) { SourceError(source, "found $ without name"); return qfalse; - } //end if - //directive name must be on the same line - if (token.linescrossed > 0) - { + } // end if + // directive name must be on the same line + if (token.linescrossed > 0) { PC_UnreadSourceToken(source, &token); SourceError(source, "found $ at end of line"); return qfalse; - } //end if - //if if is a name - if (token.type == TT_NAME) - { - //find the precompiler directive - for (i = 0; dollardirectives[i].name; i++) - { - if (!strcmp(dollardirectives[i].name, token.string)) - { + } // end if + // if if is a name + if (token.type == TT_NAME) { + // find the precompiler directive + for (i = 0; dollardirectives[i].name; i++) { + if (!strcmp(dollardirectives[i].name, token.string)) { return dollardirectives[i].func(source); - } //end if - } //end for - } //end if + } // end if + } // end for + } // end if PC_UnreadSourceToken(source, &token); SourceError(source, "unknown precompiler directive %s", token.string); return qfalse; -} //end of the function PC_ReadDirective +} // end of the function PC_ReadDirective #ifdef QUAKEC //============================================================================ @@ -2716,373 +2572,346 @@ int PC_ReadDollarDirective(source_t *source) // Returns: - // Changes Globals: - //============================================================================ -int BuiltinFunction(source_t *source) -{ +int BuiltinFunction(source_t *source) { token_t token; - if (!PC_ReadSourceToken(source, &token)) return qfalse; - if (token.type == TT_NUMBER) - { + if (!PC_ReadSourceToken(source, &token)) + return qfalse; + if (token.type == TT_NUMBER) { PC_UnreadSourceToken(source, &token); return qtrue; - } //end if - else - { + } // end if + else { PC_UnreadSourceToken(source, &token); return qfalse; - } //end else -} //end of the function BuiltinFunction + } // end else +} // end of the function BuiltinFunction //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int QuakeCMacro(source_t *source) -{ +int QuakeCMacro(source_t *source) { int i; token_t token; - if (!PC_ReadSourceToken(source, &token)) return qtrue; - if (token.type != TT_NAME) - { + if (!PC_ReadSourceToken(source, &token)) + return qtrue; + if (token.type != TT_NAME) { PC_UnreadSourceToken(source, &token); return qtrue; - } //end if - //find the precompiler directive - for (i = 0; dollardirectives[i].name; i++) - { - if (!strcmp(dollardirectives[i].name, token.string)) - { + } // end if + // find the precompiler directive + for (i = 0; dollardirectives[i].name; i++) { + if (!strcmp(dollardirectives[i].name, token.string)) { PC_UnreadSourceToken(source, &token); return qfalse; - } //end if - } //end for + } // end if + } // end for PC_UnreadSourceToken(source, &token); return qtrue; -} //end of the function QuakeCMacro -#endif //QUAKEC +} // end of the function QuakeCMacro +#endif // QUAKEC //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ReadToken(source_t *source, token_t *token) -{ +int PC_ReadToken(source_t *source, token_t *token) { define_t *define; - while(1) - { - if (!PC_ReadSourceToken(source, token)) return qfalse; - //check for precompiler directives - if (token->type == TT_PUNCTUATION && *token->string == '@') // It is a StringEd key + while (1) { + if (!PC_ReadSourceToken(source, token)) + return qfalse; + // check for precompiler directives + if (token->type == TT_PUNCTUATION && *token->string == '@') // It is a StringEd key { - char *holdString,holdString2[MAX_TOKEN]; + char *holdString, holdString2[MAX_TOKEN]; PC_ReadSourceToken(source, token); holdString = &token->string[1]; - Com_Memcpy( holdString2, token->string, sizeof(token->string)); - Com_Memcpy( holdString, holdString2, sizeof(token->string)); + Com_Memcpy(holdString2, token->string, sizeof(token->string)); + Com_Memcpy(holdString, holdString2, sizeof(token->string)); token->string[0] = '@'; return qtrue; } - if (token->type == TT_PUNCTUATION && *token->string == '#') - { + if (token->type == TT_PUNCTUATION && *token->string == '#') { #ifdef QUAKEC if (!BuiltinFunction(source)) -#endif //QUAKC +#endif // QUAKC { - //read the precompiler directive - if (!PC_ReadDirective(source)) return qfalse; + // read the precompiler directive + if (!PC_ReadDirective(source)) + return qfalse; continue; - } //end if - } //end if - if (token->type == TT_PUNCTUATION && *token->string == '$') - { + } // end if + } // end if + if (token->type == TT_PUNCTUATION && *token->string == '$') { #ifdef QUAKEC if (!QuakeCMacro(source)) -#endif //QUAKEC +#endif // QUAKEC { - //read the precompiler directive - if (!PC_ReadDollarDirective(source)) return qfalse; + // read the precompiler directive + if (!PC_ReadDollarDirective(source)) + return qfalse; continue; - } //end if - } //end if + } // end if + } // end if // recursively concatenate strings that are behind each other still resolving defines - if (token->type == TT_STRING) - { + if (token->type == TT_STRING) { token_t newtoken; - if (PC_ReadToken(source, &newtoken)) - { - if (newtoken.type == TT_STRING) - { - token->string[strlen(token->string)-1] = '\0'; - if (strlen(token->string) + strlen(newtoken.string+1) + 1 >= MAX_TOKEN) - { + if (PC_ReadToken(source, &newtoken)) { + if (newtoken.type == TT_STRING) { + token->string[strlen(token->string) - 1] = '\0'; + if (strlen(token->string) + strlen(newtoken.string + 1) + 1 >= MAX_TOKEN) { SourceError(source, "string longer than MAX_TOKEN %d", MAX_TOKEN); return qfalse; } - strcat(token->string, newtoken.string+1); - } - else - { + strcat(token->string, newtoken.string + 1); + } else { PC_UnreadToken(source, &newtoken); } } - } //end if - //if skipping source because of conditional compilation - if (source->skip) continue; - //if the token is a name - if (token->type == TT_NAME) - { - //check if the name is a define macro + } // end if + // if skipping source because of conditional compilation + if (source->skip) + continue; + // if the token is a name + if (token->type == TT_NAME) { + // check if the name is a define macro #if DEFINEHASHING define = PC_FindHashedDefine(source->definehash, token->string); #else define = PC_FindDefine(source->defines, token->string); -#endif //DEFINEHASHING - //if it is a define macro - if (define) - { - //expand the defined macro - if (!PC_ExpandDefineIntoSource(source, token, define)) return qfalse; +#endif // DEFINEHASHING + // if it is a define macro + if (define) { + // expand the defined macro + if (!PC_ExpandDefineIntoSource(source, token, define)) + return qfalse; continue; - } //end if - } //end if - //copy token for unreading + } // end if + } // end if + // copy token for unreading Com_Memcpy(&source->token, token, sizeof(token_t)); - //found a token + // found a token return qtrue; - } //end while -} //end of the function PC_ReadToken + } // end while +} // end of the function PC_ReadToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpectTokenString(source_t *source, char *string) -{ +int PC_ExpectTokenString(source_t *source, char *string) { token_t token; - if (!PC_ReadToken(source, &token)) - { + if (!PC_ReadToken(source, &token)) { SourceError(source, "couldn't find expected %s", string); return qfalse; - } //end if + } // end if - if (strcmp(token.string, string)) - { + if (strcmp(token.string, string)) { SourceError(source, "expected %s, found %s", string, token.string); return qfalse; - } //end if + } // end if return qtrue; -} //end of the function PC_ExpectTokenString +} // end of the function PC_ExpectTokenString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token) -{ +int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token) { char str[MAX_TOKEN]; - if (!PC_ReadToken(source, token)) - { + if (!PC_ReadToken(source, token)) { SourceError(source, "couldn't read expected token"); return qfalse; - } //end if + } // end if - if (token->type != type) - { + if (token->type != type) { strcpy(str, ""); - if (type == TT_STRING) strcpy(str, "string"); - if (type == TT_LITERAL) strcpy(str, "literal"); - if (type == TT_NUMBER) strcpy(str, "number"); - if (type == TT_NAME) strcpy(str, "name"); - if (type == TT_PUNCTUATION) strcpy(str, "punctuation"); + if (type == TT_STRING) + strcpy(str, "string"); + if (type == TT_LITERAL) + strcpy(str, "literal"); + if (type == TT_NUMBER) + strcpy(str, "number"); + if (type == TT_NAME) + strcpy(str, "name"); + if (type == TT_PUNCTUATION) + strcpy(str, "punctuation"); SourceError(source, "expected a %s, found %s", str, token->string); return qfalse; - } //end if - if (token->type == TT_NUMBER) - { - if ((token->subtype & subtype) != subtype) - { + } // end if + if (token->type == TT_NUMBER) { + if ((token->subtype & subtype) != subtype) { strcpy(str, ""); - if (subtype & TT_DECIMAL) strcpy(str, "decimal"); - if (subtype & TT_HEX) strcpy(str, "hex"); - if (subtype & TT_OCTAL) strcpy(str, "octal"); - if (subtype & TT_BINARY) strcpy(str, "binary"); - if (subtype & TT_LONG) strcat(str, " long"); - if (subtype & TT_UNSIGNED) strcat(str, " unsigned"); - if (subtype & TT_FLOAT) strcat(str, " float"); - if (subtype & TT_INTEGER) strcat(str, " integer"); + if (subtype & TT_DECIMAL) + strcpy(str, "decimal"); + if (subtype & TT_HEX) + strcpy(str, "hex"); + if (subtype & TT_OCTAL) + strcpy(str, "octal"); + if (subtype & TT_BINARY) + strcpy(str, "binary"); + if (subtype & TT_LONG) + strcat(str, " long"); + if (subtype & TT_UNSIGNED) + strcat(str, " unsigned"); + if (subtype & TT_FLOAT) + strcat(str, " float"); + if (subtype & TT_INTEGER) + strcat(str, " integer"); SourceError(source, "expected %s, found %s", str, token->string); return qfalse; - } //end if - } //end if - else if (token->type == TT_PUNCTUATION) - { - if (token->subtype != subtype) - { + } // end if + } // end if + else if (token->type == TT_PUNCTUATION) { + if (token->subtype != subtype) { SourceError(source, "found %s", token->string); return qfalse; - } //end if - } //end else if + } // end if + } // end else if return qtrue; -} //end of the function PC_ExpectTokenType +} // end of the function PC_ExpectTokenType //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_ExpectAnyToken(source_t *source, token_t *token) -{ - if (!PC_ReadToken(source, token)) - { +int PC_ExpectAnyToken(source_t *source, token_t *token) { + if (!PC_ReadToken(source, token)) { SourceError(source, "couldn't read expected token"); return qfalse; - } //end if - else - { + } // end if + else { return qtrue; - } //end else -} //end of the function PC_ExpectAnyToken + } // end else +} // end of the function PC_ExpectAnyToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_CheckTokenString(source_t *source, char *string) -{ +int PC_CheckTokenString(source_t *source, char *string) { token_t tok; - if (!PC_ReadToken(source, &tok)) return qfalse; - //if the token is available - if (!strcmp(tok.string, string)) return qtrue; + if (!PC_ReadToken(source, &tok)) + return qfalse; + // if the token is available + if (!strcmp(tok.string, string)) + return qtrue; // PC_UnreadSourceToken(source, &tok); return qfalse; -} //end of the function PC_CheckTokenString +} // end of the function PC_CheckTokenString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token) -{ +int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token) { token_t tok; - if (!PC_ReadToken(source, &tok)) return qfalse; - //if the type matches - if (tok.type == type && - (tok.subtype & subtype) == subtype) - { + if (!PC_ReadToken(source, &tok)) + return qfalse; + // if the type matches + if (tok.type == type && (tok.subtype & subtype) == subtype) { Com_Memcpy(token, &tok, sizeof(token_t)); return qtrue; - } //end if + } // end if // PC_UnreadSourceToken(source, &tok); return qfalse; -} //end of the function PC_CheckTokenType +} // end of the function PC_CheckTokenType //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_SkipUntilString(source_t *source, char *string) -{ +int PC_SkipUntilString(source_t *source, char *string) { token_t token; - while(PC_ReadToken(source, &token)) - { - if (!strcmp(token.string, string)) return qtrue; - } //end while + while (PC_ReadToken(source, &token)) { + if (!strcmp(token.string, string)) + return qtrue; + } // end while return qfalse; -} //end of the function PC_SkipUntilString +} // end of the function PC_SkipUntilString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_UnreadLastToken(source_t *source) -{ - PC_UnreadSourceToken(source, &source->token); -} //end of the function PC_UnreadLastToken +void PC_UnreadLastToken(source_t *source) { PC_UnreadSourceToken(source, &source->token); } // end of the function PC_UnreadLastToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_UnreadToken(source_t *source, token_t *token) -{ - PC_UnreadSourceToken(source, token); -} //end of the function PC_UnreadToken +void PC_UnreadToken(source_t *source, token_t *token) { PC_UnreadSourceToken(source, token); } // end of the function PC_UnreadToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_SetIncludePath(source_t *source, char *path) -{ +void PC_SetIncludePath(source_t *source, char *path) { size_t len; - Q_strncpyz(source->includepath, path, MAX_PATH-1); + Q_strncpyz(source->includepath, path, MAX_PATH - 1); len = strlen(source->includepath); - //add trailing path seperator - if (len > 0 && source->includepath[len-1] != '\\' && - source->includepath[len-1] != '/') - { + // add trailing path seperator + if (len > 0 && source->includepath[len - 1] != '\\' && source->includepath[len - 1] != '/') { strcat(source->includepath, PATHSEPERATOR_STR); - } //end if -} //end of the function PC_SetIncludePath + } // end if +} // end of the function PC_SetIncludePath //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_SetPunctuations(source_t *source, punctuation_t *p) -{ - source->punctuations = p; -} //end of the function PC_SetPunctuations +void PC_SetPunctuations(source_t *source, punctuation_t *p) { source->punctuations = p; } // end of the function PC_SetPunctuations //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -source_t *LoadSourceFile(const char *filename) -{ +source_t *LoadSourceFile(const char *filename) { source_t *source; script_t *script; PC_InitTokenHeap(); #if DEFINEHASHING - if ( !globaldefines ) - { + if (!globaldefines) { globaldefines = (struct define_s **)GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *)); } #endif script = LoadScriptFile(filename); - if (!script) return NULL; + if (!script) + return NULL; script->next = NULL; - source = (source_t *) GetMemory(sizeof(source_t)); + source = (source_t *)GetMemory(sizeof(source_t)); Com_Memset(source, 0, sizeof(source_t)); strncpy(source->filename, filename, MAX_PATH); @@ -3094,28 +2923,28 @@ source_t *LoadSourceFile(const char *filename) #if DEFINEHASHING source->definehash = (struct define_s **)GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *)); -#endif //DEFINEHASHING +#endif // DEFINEHASHING PC_AddGlobalDefinesToSource(source); return source; -} //end of the function LoadSourceFile +} // end of the function LoadSourceFile //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -source_t *LoadSourceMemory(char *ptr, int length, char *name) -{ +source_t *LoadSourceMemory(char *ptr, int length, char *name) { source_t *source; script_t *script; PC_InitTokenHeap(); script = LoadScriptMemory(ptr, length, name); - if (!script) return NULL; + if (!script) + return NULL; script->next = NULL; - source = (source_t *) GetMemory(sizeof(source_t)); + source = (source_t *)GetMemory(sizeof(source_t)); Com_Memset(source, 0, sizeof(source_t)); strncpy(source->filename, name, MAX_PATH); @@ -3127,18 +2956,17 @@ source_t *LoadSourceMemory(char *ptr, int length, char *name) #if DEFINEHASHING source->definehash = (struct define_s **)GetClearedMemory(DEFINEHASHSIZE * sizeof(define_t *)); -#endif //DEFINEHASHING +#endif // DEFINEHASHING PC_AddGlobalDefinesToSource(source); return source; -} //end of the function LoadSourceMemory +} // end of the function LoadSourceMemory //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void FreeSource(source_t *source) -{ +void FreeSource(source_t *source) { script_t *script; token_t *token; define_t *define; @@ -3146,62 +2974,56 @@ void FreeSource(source_t *source) define_t *nextdefine; int i; - //PC_PrintDefineHashTable(source->definehash); - //free all the scripts - while(source->scriptstack) - { + // PC_PrintDefineHashTable(source->definehash); + // free all the scripts + while (source->scriptstack) { script = source->scriptstack; source->scriptstack = source->scriptstack->next; FreeScript(script); - } //end for - //free all the tokens - while(source->tokens) - { + } // end for + // free all the tokens + while (source->tokens) { token = source->tokens; source->tokens = source->tokens->next; PC_FreeToken(token); - } //end for + } // end for #if DEFINEHASHING - for (i = 0; i < DEFINEHASHSIZE; i++) - { + for (i = 0; i < DEFINEHASHSIZE; i++) { define = source->definehash[i]; - while(define) - { + while (define) { nextdefine = define->hashnext; - if ( !(define->flags & DEFINE_GLOBAL) ) - { + if (!(define->flags & DEFINE_GLOBAL)) { PC_FreeDefine(define); } define = nextdefine; - } //end while + } // end while source->definehash[i] = NULL; - } //end for -#else //DEFINEHASHING - //free all defines - while(source->defines) - { + } // end for +#else // DEFINEHASHING + // free all defines + while (source->defines) { define = source->defines; source->defines = source->defines->next; PC_FreeDefine(define); - } //end for -#endif //DEFINEHASHING - //free all indents - while(source->indentstack) - { + } // end for +#endif // DEFINEHASHING + // free all indents + while (source->indentstack) { indent = source->indentstack; source->indentstack = source->indentstack->next; FreeMemory(indent); - } //end for + } // end for #if DEFINEHASHING // - if (source->definehash) FreeMemory(source->definehash); -#endif //DEFINEHASHING - //free the source itself + if (source->definehash) + FreeMemory(source->definehash); +#endif // DEFINEHASHING + // free the source itself FreeMemory(source); -} //end of the function FreeSource +} // end of the function FreeSource //============================================================================ // // Parameter: - @@ -3209,20 +3031,18 @@ void FreeSource(source_t *source) // Changes Globals: - //============================================================================ -#define MAX_SOURCEFILES 64 +#define MAX_SOURCEFILES 64 source_t *sourceFiles[MAX_SOURCEFILES]; -int PC_LoadSourceHandle(const char *filename) -{ +int PC_LoadSourceHandle(const char *filename) { source_t *source; int i; - for (i = 1; i < MAX_SOURCEFILES; i++) - { + for (i = 1; i < MAX_SOURCEFILES; i++) { if (!sourceFiles[i]) break; - } //end for + } // end for if (i >= MAX_SOURCEFILES) return 0; PS_SetBaseFolder(""); @@ -3231,15 +3051,14 @@ int PC_LoadSourceHandle(const char *filename) return 0; sourceFiles[i] = source; return i; -} //end of the function PC_LoadSourceHandle +} // end of the function PC_LoadSourceHandle //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_FreeSourceHandle(int handle) -{ +int PC_FreeSourceHandle(int handle) { if (handle < 1 || handle >= MAX_SOURCEFILES) return qfalse; if (!sourceFiles[handle]) @@ -3248,25 +3067,25 @@ int PC_FreeSourceHandle(int handle) FreeSource(sourceFiles[handle]); sourceFiles[handle] = NULL; return qtrue; -} //end of the function PC_FreeSourceHandle +} // end of the function PC_FreeSourceHandle -int PC_LoadGlobalDefines ( const char* filename ) -{ - int handle; +int PC_LoadGlobalDefines(const char *filename) { + int handle; token_t token; - handle = PC_LoadSourceHandle ( filename ); - if ( handle < 1 ) + handle = PC_LoadSourceHandle(filename); + if (handle < 1) return qfalse; addGlobalDefine = qtrue; // Read all the token files which will add the defines globally - while ( PC_ReadToken(sourceFiles[handle], &token) ); + while (PC_ReadToken(sourceFiles[handle], &token)) + ; addGlobalDefine = qfalse; - PC_FreeSourceHandle ( handle ); + PC_FreeSourceHandle(handle); return qtrue; } @@ -3277,8 +3096,7 @@ int PC_LoadGlobalDefines ( const char* filename ) // Returns: - // Changes Globals: - //============================================================================ -int PC_ReadTokenHandle(int handle, pc_token_t *pc_token) -{ +int PC_ReadTokenHandle(int handle, pc_token_t *pc_token) { token_t token; int ret; @@ -3293,19 +3111,18 @@ int PC_ReadTokenHandle(int handle, pc_token_t *pc_token) pc_token->subtype = token.subtype; pc_token->intvalue = token.intvalue; pc_token->floatvalue = token.floatvalue; - if ((pc_token->type == TT_STRING) && (pc_token->string[0]!='@')) + if ((pc_token->type == TT_STRING) && (pc_token->string[0] != '@')) StripDoubleQuotes(pc_token->string); return ret; -} //end of the function PC_ReadTokenHandle +} // end of the function PC_ReadTokenHandle //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PC_SourceFileAndLine(int handle, char *filename, int *line) -{ +int PC_SourceFileAndLine(int handle, char *filename, int *line) { if (handle < 1 || handle >= MAX_SOURCEFILES) return qfalse; if (!sourceFiles[handle]) @@ -3317,35 +3134,28 @@ int PC_SourceFileAndLine(int handle, char *filename, int *line) else *line = 0; return qtrue; -} //end of the function PC_SourceFileAndLine +} // end of the function PC_SourceFileAndLine //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_SetBaseFolder(char *path) -{ - PS_SetBaseFolder(path); -} //end of the function PC_SetBaseFolder +void PC_SetBaseFolder(char *path) { PS_SetBaseFolder(path); } // end of the function PC_SetBaseFolder //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PC_CheckOpenSourceHandles(void) -{ +void PC_CheckOpenSourceHandles(void) { int i; - for (i = 1; i < MAX_SOURCEFILES; i++) - { - if (sourceFiles[i]) - { + for (i = 1; i < MAX_SOURCEFILES; i++) { + if (sourceFiles[i]) { #ifdef BOTLIB botimport.Print(PRT_ERROR, "file %s still open in precompiler\n", sourceFiles[i]->scriptstack->filename); -#endif //BOTLIB - } //end if - } //end for -} //end of the function PC_CheckOpenSourceHandles - +#endif // BOTLIB + } // end if + } // end for +} // end of the function PC_CheckOpenSourceHandles diff --git a/codemp/botlib/l_script.cpp b/codemp/botlib/l_script.cpp index ab49c8c62b..e7a529c228 100644 --- a/codemp/botlib/l_script.cpp +++ b/codemp/botlib/l_script.cpp @@ -48,12 +48,12 @@ along with this program; if not, see . #include "l_memory.h" #include "l_script.h" -typedef enum {qfalse, qtrue} qboolean; +typedef enum { qfalse, qtrue } qboolean; -#endif //SCREWUP +#endif // SCREWUP #ifdef BOTLIB -//include files for usage in the bot library +// include files for usage in the bot library #include "qcommon/q_shared.h" #include "botlib.h" #include "be_interface.h" @@ -61,111 +61,108 @@ typedef enum {qfalse, qtrue} qboolean; #include "l_memory.h" #include "l_log.h" #include "l_libvar.h" -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC -//include files for usage in MrElusive's QuakeC Compiler +// include files for usage in MrElusive's QuakeC Compiler #include "qcc.h" #include "l_script.h" #include "l_memory.h" #include "l_log.h" -#define qtrue true -#define qfalse false -#endif //MEQCC +#define qtrue true +#define qfalse false +#endif // MEQCC #ifdef BSPC -//include files for usage in the BSP Converter +// include files for usage in the BSP Converter #include "../bspc/qbsp.h" #include "../bspc/l_log.h" #include "../bspc/l_mem.h" -#define qtrue true -#define qfalse false -#endif //BSPC - +#define qtrue true +#define qfalse false +#endif // BSPC #define PUNCTABLE -//longer punctuations first -punctuation_t default_punctuations[] = -{ - //binary operators - {">>=",P_RSHIFT_ASSIGN, NULL}, - {"<<=",P_LSHIFT_ASSIGN, NULL}, +// longer punctuations first +punctuation_t default_punctuations[] = { + // binary operators + {">>=", P_RSHIFT_ASSIGN, NULL}, + {"<<=", P_LSHIFT_ASSIGN, NULL}, // - {"...",P_PARMS, NULL}, - //define merge operator - {"##",P_PRECOMPMERGE, NULL}, - //logic operators - {"&&",P_LOGIC_AND, NULL}, - {"||",P_LOGIC_OR, NULL}, - {">=",P_LOGIC_GEQ, NULL}, - {"<=",P_LOGIC_LEQ, NULL}, - {"==",P_LOGIC_EQ, NULL}, - {"!=",P_LOGIC_UNEQ, NULL}, - //arithmatic operators - {"*=",P_MUL_ASSIGN, NULL}, - {"/=",P_DIV_ASSIGN, NULL}, - {"%=",P_MOD_ASSIGN, NULL}, - {"+=",P_ADD_ASSIGN, NULL}, - {"-=",P_SUB_ASSIGN, NULL}, - {"++",P_INC, NULL}, - {"--",P_DEC, NULL}, - //binary operators - {"&=",P_BIN_AND_ASSIGN, NULL}, - {"|=",P_BIN_OR_ASSIGN, NULL}, - {"^=",P_BIN_XOR_ASSIGN, NULL}, - {">>",P_RSHIFT, NULL}, - {"<<",P_LSHIFT, NULL}, - //reference operators - {"->",P_POINTERREF, NULL}, - //C++ - {"::",P_CPP1, NULL}, - {".*",P_CPP2, NULL}, - //arithmatic operators - {"*",P_MUL, NULL}, - {"/",P_DIV, NULL}, - {"%",P_MOD, NULL}, - {"+",P_ADD, NULL}, - {"-",P_SUB, NULL}, - {"=",P_ASSIGN, NULL}, - //binary operators - {"&",P_BIN_AND, NULL}, - {"|",P_BIN_OR, NULL}, - {"^",P_BIN_XOR, NULL}, - {"~",P_BIN_NOT, NULL}, - //logic operators - {"!",P_LOGIC_NOT, NULL}, - {">",P_LOGIC_GREATER, NULL}, - {"<",P_LOGIC_LESS, NULL}, - //reference operator - {".",P_REF, NULL}, - //seperators - {",",P_COMMA, NULL}, - {";",P_SEMICOLON, NULL}, - //label indication - {":",P_COLON, NULL}, - //if statement - {"?",P_QUESTIONMARK, NULL}, - //embracements - {"(",P_PARENTHESESOPEN, NULL}, - {")",P_PARENTHESESCLOSE, NULL}, - {"{",P_BRACEOPEN, NULL}, - {"}",P_BRACECLOSE, NULL}, - {"[",P_SQBRACKETOPEN, NULL}, - {"]",P_SQBRACKETCLOSE, NULL}, + {"...", P_PARMS, NULL}, + // define merge operator + {"##", P_PRECOMPMERGE, NULL}, + // logic operators + {"&&", P_LOGIC_AND, NULL}, + {"||", P_LOGIC_OR, NULL}, + {">=", P_LOGIC_GEQ, NULL}, + {"<=", P_LOGIC_LEQ, NULL}, + {"==", P_LOGIC_EQ, NULL}, + {"!=", P_LOGIC_UNEQ, NULL}, + // arithmatic operators + {"*=", P_MUL_ASSIGN, NULL}, + {"/=", P_DIV_ASSIGN, NULL}, + {"%=", P_MOD_ASSIGN, NULL}, + {"+=", P_ADD_ASSIGN, NULL}, + {"-=", P_SUB_ASSIGN, NULL}, + {"++", P_INC, NULL}, + {"--", P_DEC, NULL}, + // binary operators + {"&=", P_BIN_AND_ASSIGN, NULL}, + {"|=", P_BIN_OR_ASSIGN, NULL}, + {"^=", P_BIN_XOR_ASSIGN, NULL}, + {">>", P_RSHIFT, NULL}, + {"<<", P_LSHIFT, NULL}, + // reference operators + {"->", P_POINTERREF, NULL}, + // C++ + {"::", P_CPP1, NULL}, + {".*", P_CPP2, NULL}, + // arithmatic operators + {"*", P_MUL, NULL}, + {"/", P_DIV, NULL}, + {"%", P_MOD, NULL}, + {"+", P_ADD, NULL}, + {"-", P_SUB, NULL}, + {"=", P_ASSIGN, NULL}, + // binary operators + {"&", P_BIN_AND, NULL}, + {"|", P_BIN_OR, NULL}, + {"^", P_BIN_XOR, NULL}, + {"~", P_BIN_NOT, NULL}, + // logic operators + {"!", P_LOGIC_NOT, NULL}, + {">", P_LOGIC_GREATER, NULL}, + {"<", P_LOGIC_LESS, NULL}, + // reference operator + {".", P_REF, NULL}, + // seperators + {",", P_COMMA, NULL}, + {";", P_SEMICOLON, NULL}, + // label indication + {":", P_COLON, NULL}, + // if statement + {"?", P_QUESTIONMARK, NULL}, + // embracements + {"(", P_PARENTHESESOPEN, NULL}, + {")", P_PARENTHESESCLOSE, NULL}, + {"{", P_BRACEOPEN, NULL}, + {"}", P_BRACECLOSE, NULL}, + {"[", P_SQBRACKETOPEN, NULL}, + {"]", P_SQBRACKETCLOSE, NULL}, // - {"\\",P_BACKSLASH, NULL}, - //precompiler operator - {"#",P_PRECOMP, NULL}, + {"\\", P_BACKSLASH, NULL}, + // precompiler operator + {"#", P_PRECOMP, NULL}, #ifdef DOLLAR - {"$",P_DOLLAR, NULL}, -#endif //DOLLAR + {"$", P_DOLLAR, NULL}, +#endif // DOLLAR // StringEd key - {"@",P_ATSIGN, NULL}, - {NULL, 0} -}; + {"@", P_ATSIGN, NULL}, + {NULL, 0}}; #ifdef BSPC char basefolder[MAX_PATH]; @@ -179,123 +176,124 @@ char basefolder[MAX_QPATH]; // Returns: - // Changes Globals: - //=========================================================================== -void PS_CreatePunctuationTable(script_t *script, punctuation_t *punctuations) -{ +void PS_CreatePunctuationTable(script_t *script, punctuation_t *punctuations) { int i; punctuation_t *p, *lastp, *newp; - //get memory for the table - if (!script->punctuationtable) script->punctuationtable = (punctuation_t **) - GetMemory(256 * sizeof(punctuation_t *)); + // get memory for the table + if (!script->punctuationtable) + script->punctuationtable = (punctuation_t **)GetMemory(256 * sizeof(punctuation_t *)); Com_Memset(script->punctuationtable, 0, 256 * sizeof(punctuation_t *)); - //add the punctuations in the list to the punctuation table - for (i = 0; punctuations[i].p; i++) - { + // add the punctuations in the list to the punctuation table + for (i = 0; punctuations[i].p; i++) { newp = &punctuations[i]; lastp = NULL; - //sort the punctuations in this table entry on length (longer punctuations first) - for (p = script->punctuationtable[(unsigned int) newp->p[0]]; p; p = p->next) - { - if (strlen(p->p) < strlen(newp->p)) - { + // sort the punctuations in this table entry on length (longer punctuations first) + for (p = script->punctuationtable[(unsigned int)newp->p[0]]; p; p = p->next) { + if (strlen(p->p) < strlen(newp->p)) { newp->next = p; - if (lastp) lastp->next = newp; - else script->punctuationtable[(unsigned int) newp->p[0]] = newp; + if (lastp) + lastp->next = newp; + else + script->punctuationtable[(unsigned int)newp->p[0]] = newp; break; - } //end if + } // end if lastp = p; - } //end for - if (!p) - { + } // end for + if (!p) { newp->next = NULL; - if (lastp) lastp->next = newp; - else script->punctuationtable[(unsigned int) newp->p[0]] = newp; - } //end if - } //end for -} //end of the function PS_CreatePunctuationTable + if (lastp) + lastp->next = newp; + else + script->punctuationtable[(unsigned int)newp->p[0]] = newp; + } // end if + } // end for +} // end of the function PS_CreatePunctuationTable //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -const char *PunctuationFromNum(script_t *script, int num) -{ +const char *PunctuationFromNum(script_t *script, int num) { int i; - for (i = 0; script->punctuations[i].p; i++) - { - if (script->punctuations[i].n == num) return script->punctuations[i].p; - } //end for + for (i = 0; script->punctuations[i].p; i++) { + if (script->punctuations[i].n == num) + return script->punctuations[i].p; + } // end for return "unkown punctuation"; -} //end of the function PunctuationFromNum +} // end of the function PunctuationFromNum //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void QDECL ScriptError(script_t *script, char *str, ...) -{ +void QDECL ScriptError(script_t *script, char *str, ...) { char text[1024]; va_list ap; - if (script->flags & SCFL_NOERRORS) return; + if (script->flags & SCFL_NOERRORS) + return; va_start(ap, str); Q_vsnprintf(text, sizeof(text), str, ap); va_end(ap); #ifdef BOTLIB botimport.Print(PRT_ERROR, "file %s, line %d: %s\n", script->filename, script->line, text); -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC printf("error: file %s, line %d: %s\n", script->filename, script->line, text); -#endif //MEQCC +#endif // MEQCC #ifdef BSPC Log_Print("error: file %s, line %d: %s\n", script->filename, script->line, text); -#endif //BSPC -} //end of the function ScriptError +#endif // BSPC +} // end of the function ScriptError //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void QDECL ScriptWarning(script_t *script, char *str, ...) -{ +void QDECL ScriptWarning(script_t *script, char *str, ...) { char text[1024]; va_list ap; - if (script->flags & SCFL_NOWARNINGS) return; + if (script->flags & SCFL_NOWARNINGS) + return; va_start(ap, str); Q_vsnprintf(text, sizeof(text), str, ap); va_end(ap); #ifdef BOTLIB botimport.Print(PRT_WARNING, "file %s, line %d: %s\n", script->filename, script->line, text); -#endif //BOTLIB +#endif // BOTLIB #ifdef MEQCC printf("warning: file %s, line %d: %s\n", script->filename, script->line, text); -#endif //MEQCC +#endif // MEQCC #ifdef BSPC Log_Print("warning: file %s, line %d: %s\n", script->filename, script->line, text); -#endif //BSPC -} //end of the function ScriptWarning +#endif // BSPC +} // end of the function ScriptWarning //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -void SetScriptPunctuations(script_t *script, punctuation_t *p) -{ +void SetScriptPunctuations(script_t *script, punctuation_t *p) { #ifdef PUNCTABLE - if (p) PS_CreatePunctuationTable(script, p); - else PS_CreatePunctuationTable(script, default_punctuations); -#endif //PUNCTABLE - if (p) script->punctuations = p; - else script->punctuations = default_punctuations; -} //end of the function SetScriptPunctuations + if (p) + PS_CreatePunctuationTable(script, p); + else + PS_CreatePunctuationTable(script, default_punctuations); +#endif // PUNCTABLE + if (p) + script->punctuations = p; + else + script->punctuations = default_punctuations; +} // end of the function SetScriptPunctuations //============================================================================ // Reads spaces, tabs, C-like comments etc. // When a newline character is found the scripts line counter is increased. @@ -304,57 +302,57 @@ void SetScriptPunctuations(script_t *script, punctuation_t *p) // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadWhiteSpace(script_t *script) -{ - while(1) - { - //skip white space - while(*script->script_p <= ' ') - { - if (!*script->script_p) return 0; - if (*script->script_p == '\n') script->line++; +int PS_ReadWhiteSpace(script_t *script) { + while (1) { + // skip white space + while (*script->script_p <= ' ') { + if (!*script->script_p) + return 0; + if (*script->script_p == '\n') + script->line++; script->script_p++; - } //end while - //skip comments - if (*script->script_p == '/') - { - //comments // - if (*(script->script_p+1) == '/') - { + } // end while + // skip comments + if (*script->script_p == '/') { + // comments // + if (*(script->script_p + 1) == '/') { script->script_p++; - do - { + do { script->script_p++; - if (!*script->script_p) return 0; - } //end do - while(*script->script_p != '\n'); + if (!*script->script_p) + return 0; + } // end do + while (*script->script_p != '\n'); script->line++; script->script_p++; - if (!*script->script_p) return 0; + if (!*script->script_p) + return 0; continue; - } //end if - //comments /* */ - else if (*(script->script_p+1) == '*') - { + } // end if + // comments /* */ + else if (*(script->script_p + 1) == '*') { script->script_p++; - do - { + do { script->script_p++; - if (!*script->script_p) return 0; - if (*script->script_p == '\n') script->line++; - } //end do - while(!(*script->script_p == '*' && *(script->script_p+1) == '/')); + if (!*script->script_p) + return 0; + if (*script->script_p == '\n') + script->line++; + } // end do + while (!(*script->script_p == '*' && *(script->script_p + 1) == '/')); script->script_p++; - if (!*script->script_p) return 0; + if (!*script->script_p) + return 0; script->script_p++; - if (!*script->script_p) return 0; + if (!*script->script_p) + return 0; continue; - } //end if - } //end if + } // end if + } // end if break; - } //end while + } // end while return 1; -} //end of the function PS_ReadWhiteSpace +} // end of the function PS_ReadWhiteSpace //============================================================================ // Reads an escape character. // @@ -363,74 +361,96 @@ int PS_ReadWhiteSpace(script_t *script) // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadEscapeCharacter(script_t *script, char *ch) -{ +int PS_ReadEscapeCharacter(script_t *script, char *ch) { int c, val, i; - //step over the leading '\\' + // step over the leading '\\' script->script_p++; - //determine the escape character - switch(*script->script_p) + // determine the escape character + switch (*script->script_p) { + case '\\': + c = '\\'; + break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'v': + c = '\v'; + break; + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'a': + c = '\a'; + break; + case '\'': + c = '\''; + break; + case '\"': + c = '\"'; + break; + case '\?': + c = '\?'; + break; + case 'x': { + script->script_p++; + for (i = 0, val = 0;; i++, script->script_p++) { + c = *script->script_p; + if (c >= '0' && c <= '9') + c = c - '0'; + else if (c >= 'A' && c <= 'Z') + c = c - 'A' + 10; + else if (c >= 'a' && c <= 'z') + c = c - 'a' + 10; + else + break; + val = (val << 4) + c; + } // end for + script->script_p--; + if (val > 0xFF) { + ScriptWarning(script, "too large value in escape character"); + val = 0xFF; + } // end if + c = val; + break; + } // end case + default: // NOTE: decimal ASCII code, NOT octal { - case '\\': c = '\\'; break; - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'v': c = '\v'; break; - case 'b': c = '\b'; break; - case 'f': c = '\f'; break; - case 'a': c = '\a'; break; - case '\'': c = '\''; break; - case '\"': c = '\"'; break; - case '\?': c = '\?'; break; - case 'x': - { - script->script_p++; - for (i = 0, val = 0; ; i++, script->script_p++) - { - c = *script->script_p; - if (c >= '0' && c <= '9') c = c - '0'; - else if (c >= 'A' && c <= 'Z') c = c - 'A' + 10; - else if (c >= 'a' && c <= 'z') c = c - 'a' + 10; - else break; - val = (val << 4) + c; - } //end for - script->script_p--; - if (val > 0xFF) - { - ScriptWarning(script, "too large value in escape character"); - val = 0xFF; - } //end if - c = val; - break; - } //end case - default: //NOTE: decimal ASCII code, NOT octal - { - if (*script->script_p < '0' || *script->script_p > '9') ScriptError(script, "unknown escape char"); - for (i = 0, val = 0; ; i++, script->script_p++) - { - c = *script->script_p; - if (c >= '0' && c <= '9') c = c - '0'; - else break; - val = val * 10 + c; - } //end for - script->script_p--; - if (val > 0xFF) - { - ScriptWarning(script, "too large value in escape character"); - val = 0xFF; - } //end if - c = val; - break; - } //end default - } //end switch - //step over the escape character or the last digit of the number + if (*script->script_p < '0' || *script->script_p > '9') + ScriptError(script, "unknown escape char"); + for (i = 0, val = 0;; i++, script->script_p++) { + c = *script->script_p; + if (c >= '0' && c <= '9') + c = c - '0'; + else + break; + val = val * 10 + c; + } // end for + script->script_p--; + if (val > 0xFF) { + ScriptWarning(script, "too large value in escape character"); + val = 0xFF; + } // end if + c = val; + break; + } // end default + } // end switch + // step over the escape character or the last digit of the number script->script_p++; - //store the escape character + // store the escape character *ch = c; - //successfully read escape character + // successfully read escape character return 1; -} //end of the function PS_ReadEscapeCharacter +} // end of the function PS_ReadEscapeCharacter //============================================================================ // Reads C-like string. Escape characters are interpretted. // Quotes are included with the string. @@ -441,664 +461,607 @@ int PS_ReadEscapeCharacter(script_t *script, char *ch) // Returns: qtrue when a string was read succesfully // Changes Globals: - //============================================================================ -int PS_ReadString(script_t *script, token_t *token, int quote) -{ +int PS_ReadString(script_t *script, token_t *token, int quote) { int len, tmpline; char *tmpscript_p; - if (quote == '\"') token->type = TT_STRING; - else token->type = TT_LITERAL; + if (quote == '\"') + token->type = TT_STRING; + else + token->type = TT_LITERAL; len = 0; - //leading quote + // leading quote token->string[len++] = *script->script_p++; // - while(1) - { - //minus 2 because trailing double quote and zero have to be appended - if (len >= MAX_TOKEN - 2) - { + while (1) { + // minus 2 because trailing double quote and zero have to be appended + if (len >= MAX_TOKEN - 2) { ScriptError(script, "string longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if - //if there is an escape character and - //if escape characters inside a string are allowed - if (*script->script_p == '\\' && !(script->flags & SCFL_NOSTRINGESCAPECHARS)) - { - if (!PS_ReadEscapeCharacter(script, &token->string[len])) - { + } // end if + // if there is an escape character and + // if escape characters inside a string are allowed + if (*script->script_p == '\\' && !(script->flags & SCFL_NOSTRINGESCAPECHARS)) { + if (!PS_ReadEscapeCharacter(script, &token->string[len])) { token->string[len] = 0; return 0; - } //end if + } // end if len++; - } //end if - //if a trailing quote - else if (*script->script_p == quote) - { - //step over the double quote + } // end if + // if a trailing quote + else if (*script->script_p == quote) { + // step over the double quote script->script_p++; - //if white spaces in a string are not allowed - if (script->flags & SCFL_NOSTRINGWHITESPACES) break; + // if white spaces in a string are not allowed + if (script->flags & SCFL_NOSTRINGWHITESPACES) + break; // tmpscript_p = script->script_p; tmpline = script->line; - //read unusefull stuff between possible two following strings - if (!PS_ReadWhiteSpace(script)) - { + // read unusefull stuff between possible two following strings + if (!PS_ReadWhiteSpace(script)) { script->script_p = tmpscript_p; script->line = tmpline; break; - } //end if - //if there's no leading double qoute - if (*script->script_p != quote) - { + } // end if + // if there's no leading double qoute + if (*script->script_p != quote) { script->script_p = tmpscript_p; script->line = tmpline; break; - } //end if - //step over the new leading double quote + } // end if + // step over the new leading double quote script->script_p++; - } //end if - else - { - if (*script->script_p == '\0') - { + } // end if + else { + if (*script->script_p == '\0') { token->string[len] = 0; ScriptError(script, "missing trailing quote"); return 0; - } //end if - if (*script->script_p == '\n') - { + } // end if + if (*script->script_p == '\n') { token->string[len] = 0; ScriptError(script, "newline inside string %s", token->string); return 0; - } //end if + } // end if token->string[len++] = *script->script_p++; - } //end else - } //end while - //trailing quote + } // end else + } // end while + // trailing quote token->string[len++] = quote; - //end string with a zero + // end string with a zero token->string[len] = '\0'; - //the sub type is the length of the string + // the sub type is the length of the string token->subtype = len; return 1; -} //end of the function PS_ReadString +} // end of the function PS_ReadString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadName(script_t *script, token_t *token) -{ +int PS_ReadName(script_t *script, token_t *token) { int len = 0; char c; token->type = TT_NAME; - do - { + do { token->string[len++] = *script->script_p++; - if (len >= MAX_TOKEN) - { + if (len >= MAX_TOKEN) { ScriptError(script, "name longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if + } // end if c = *script->script_p; - } while ((c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || - c == '_'); + } while ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'); token->string[len] = '\0'; - //the sub type is the length of the name + // the sub type is the length of the name token->subtype = len; return 1; -} //end of the function PS_ReadName +} // end of the function PS_ReadName //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void NumberValue(char *string, int subtype, unsigned long int *intvalue, - long double *floatvalue) -{ +void NumberValue(char *string, int subtype, unsigned long int *intvalue, long double *floatvalue) { unsigned long int dotfound = 0; *intvalue = 0; *floatvalue = 0; - //floating point number - if (subtype & TT_FLOAT) - { - while(*string) - { - if (*string == '.') - { - if (dotfound) return; + // floating point number + if (subtype & TT_FLOAT) { + while (*string) { + if (*string == '.') { + if (dotfound) + return; dotfound = 10; string++; - } //end if - if (dotfound) - { - *floatvalue = *floatvalue + (long double) (*string - '0') / - (long double) dotfound; + } // end if + if (dotfound) { + *floatvalue = *floatvalue + (long double)(*string - '0') / (long double)dotfound; dotfound *= 10; - } //end if - else - { - *floatvalue = *floatvalue * 10.0 + (long double) (*string - '0'); - } //end else + } // end if + else { + *floatvalue = *floatvalue * 10.0 + (long double)(*string - '0'); + } // end else string++; - } //end while - *intvalue = (unsigned long) *floatvalue; - } //end if - else if (subtype & TT_DECIMAL) - { - while(*string) *intvalue = *intvalue * 10 + (*string++ - '0'); + } // end while + *intvalue = (unsigned long)*floatvalue; + } // end if + else if (subtype & TT_DECIMAL) { + while (*string) + *intvalue = *intvalue * 10 + (*string++ - '0'); *floatvalue = *intvalue; - } //end else if - else if (subtype & TT_HEX) - { - //step over the leading 0x or 0X + } // end else if + else if (subtype & TT_HEX) { + // step over the leading 0x or 0X string += 2; - while(*string) - { + while (*string) { *intvalue <<= 4; - if (*string >= 'a' && *string <= 'f') *intvalue += *string - 'a' + 10; - else if (*string >= 'A' && *string <= 'F') *intvalue += *string - 'A' + 10; - else *intvalue += *string - '0'; + if (*string >= 'a' && *string <= 'f') + *intvalue += *string - 'a' + 10; + else if (*string >= 'A' && *string <= 'F') + *intvalue += *string - 'A' + 10; + else + *intvalue += *string - '0'; string++; - } //end while + } // end while *floatvalue = *intvalue; - } //end else if - else if (subtype & TT_OCTAL) - { - //step over the first zero + } // end else if + else if (subtype & TT_OCTAL) { + // step over the first zero string += 1; - while(*string) *intvalue = (*intvalue << 3) + (*string++ - '0'); + while (*string) + *intvalue = (*intvalue << 3) + (*string++ - '0'); *floatvalue = *intvalue; - } //end else if - else if (subtype & TT_BINARY) - { - //step over the leading 0b or 0B + } // end else if + else if (subtype & TT_BINARY) { + // step over the leading 0b or 0B string += 2; - while(*string) *intvalue = (*intvalue << 1) + (*string++ - '0'); + while (*string) + *intvalue = (*intvalue << 1) + (*string++ - '0'); *floatvalue = *intvalue; - } //end else if -} //end of the function NumberValue + } // end else if +} // end of the function NumberValue //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadNumber(script_t *script, token_t *token) -{ +int PS_ReadNumber(script_t *script, token_t *token) { int len = 0, i; int octal, dot; char c; -// unsigned long int intvalue = 0; -// long double floatvalue = 0; + // unsigned long int intvalue = 0; + // long double floatvalue = 0; token->type = TT_NUMBER; - //check for a hexadecimal number - if (*script->script_p == '0' && - (*(script->script_p + 1) == 'x' || - *(script->script_p + 1) == 'X')) - { + // check for a hexadecimal number + if (*script->script_p == '0' && (*(script->script_p + 1) == 'x' || *(script->script_p + 1) == 'X')) { token->string[len++] = *script->script_p++; token->string[len++] = *script->script_p++; c = *script->script_p; - //hexadecimal - while((c >= '0' && c <= '9') || - (c >= 'a' && c <= 'f') || - (c >= 'A' && c <= 'F')) - { + // hexadecimal + while ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { token->string[len++] = *script->script_p++; - if (len >= MAX_TOKEN) - { + if (len >= MAX_TOKEN) { ScriptError(script, "hexadecimal number longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if + } // end if c = *script->script_p; - } //end while + } // end while token->subtype |= TT_HEX; - } //end if + } // end if #ifdef BINARYNUMBERS - //check for a binary number - else if (*script->script_p == '0' && - (*(script->script_p + 1) == 'b' || - *(script->script_p + 1) == 'B')) - { + // check for a binary number + else if (*script->script_p == '0' && (*(script->script_p + 1) == 'b' || *(script->script_p + 1) == 'B')) { token->string[len++] = *script->script_p++; token->string[len++] = *script->script_p++; c = *script->script_p; - //binary - while(c == '0' || c == '1') - { + // binary + while (c == '0' || c == '1') { token->string[len++] = *script->script_p++; - if (len >= MAX_TOKEN) - { + if (len >= MAX_TOKEN) { ScriptError(script, "binary number longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if + } // end if c = *script->script_p; - } //end while + } // end while token->subtype |= TT_BINARY; - } //end if -#endif //BINARYNUMBERS - else //decimal or octal integer or floating point number + } // end if +#endif // BINARYNUMBERS + else // decimal or octal integer or floating point number { octal = qfalse; dot = qfalse; - if (*script->script_p == '0') octal = qtrue; - while(1) - { + if (*script->script_p == '0') + octal = qtrue; + while (1) { c = *script->script_p; - if (c == '.') dot = qtrue; - else if (c == '8' || c == '9') octal = qfalse; - else if (c < '0' || c > '9') break; + if (c == '.') + dot = qtrue; + else if (c == '8' || c == '9') + octal = qfalse; + else if (c < '0' || c > '9') + break; token->string[len++] = *script->script_p++; - if (len >= MAX_TOKEN - 1) - { + if (len >= MAX_TOKEN - 1) { ScriptError(script, "number longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if - } //end while - if (octal) token->subtype |= TT_OCTAL; - else token->subtype |= TT_DECIMAL; - if (dot) token->subtype |= TT_FLOAT; - } //end else - for (i = 0; i < 2; i++) - { + } // end if + } // end while + if (octal) + token->subtype |= TT_OCTAL; + else + token->subtype |= TT_DECIMAL; + if (dot) + token->subtype |= TT_FLOAT; + } // end else + for (i = 0; i < 2; i++) { c = *script->script_p; - //check for a LONG number - if ( (c == 'l' || c == 'L') // bk001204 - brackets - && !(token->subtype & TT_LONG)) - { + // check for a LONG number + if ((c == 'l' || c == 'L') // bk001204 - brackets + && !(token->subtype & TT_LONG)) { script->script_p++; token->subtype |= TT_LONG; - } //end if - //check for an UNSIGNED number - else if ( (c == 'u' || c == 'U') // bk001204 - brackets - && !(token->subtype & (TT_UNSIGNED | TT_FLOAT))) - { + } // end if + // check for an UNSIGNED number + else if ((c == 'u' || c == 'U') // bk001204 - brackets + && !(token->subtype & (TT_UNSIGNED | TT_FLOAT))) { script->script_p++; token->subtype |= TT_UNSIGNED; - } //end if - } //end for + } // end if + } // end for token->string[len] = '\0'; #ifdef NUMBERVALUE NumberValue(token->string, token->subtype, &token->intvalue, &token->floatvalue); -#endif //NUMBERVALUE - if (!(token->subtype & TT_FLOAT)) token->subtype |= TT_INTEGER; +#endif // NUMBERVALUE + if (!(token->subtype & TT_FLOAT)) + token->subtype |= TT_INTEGER; return 1; -} //end of the function PS_ReadNumber +} // end of the function PS_ReadNumber //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadLiteral(script_t *script, token_t *token) -{ +int PS_ReadLiteral(script_t *script, token_t *token) { token->type = TT_LITERAL; - //first quote + // first quote token->string[0] = *script->script_p++; - //check for end of file - if (!*script->script_p) - { + // check for end of file + if (!*script->script_p) { ScriptError(script, "end of file before trailing \'"); return 0; - } //end if - //if it is an escape character - if (*script->script_p == '\\') - { - if (!PS_ReadEscapeCharacter(script, &token->string[1])) return 0; - } //end if - else - { + } // end if + // if it is an escape character + if (*script->script_p == '\\') { + if (!PS_ReadEscapeCharacter(script, &token->string[1])) + return 0; + } // end if + else { token->string[1] = *script->script_p++; - } //end else - //check for trailing quote - if (*script->script_p != '\'') - { + } // end else + // check for trailing quote + if (*script->script_p != '\'') { ScriptWarning(script, "too many characters in literal, ignored"); - while(*script->script_p && - *script->script_p != '\'' && - *script->script_p != '\n') - { + while (*script->script_p && *script->script_p != '\'' && *script->script_p != '\n') { script->script_p++; - } //end while - if (*script->script_p == '\'') script->script_p++; - } //end if - //store the trailing quote + } // end while + if (*script->script_p == '\'') + script->script_p++; + } // end if + // store the trailing quote token->string[2] = *script->script_p++; - //store trailing zero to end the string + // store trailing zero to end the string token->string[3] = '\0'; - //the sub type is the integer literal value + // the sub type is the integer literal value token->subtype = token->string[1]; // return 1; -} //end of the function PS_ReadLiteral +} // end of the function PS_ReadLiteral //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadPunctuation(script_t *script, token_t *token) -{ +int PS_ReadPunctuation(script_t *script, token_t *token) { int len; const char *p; punctuation_t *punc; #ifdef PUNCTABLE - for (punc = script->punctuationtable[(unsigned int)*script->script_p]; punc; punc = punc->next) - { + for (punc = script->punctuationtable[(unsigned int)*script->script_p]; punc; punc = punc->next) { #else int i; - for (i = 0; script->punctuations[i].p; i++) - { + for (i = 0; script->punctuations[i].p; i++) { punc = &script->punctuations[i]; -#endif //PUNCTABLE +#endif // PUNCTABLE p = punc->p; len = strlen(p); - //if the script contains at least as much characters as the punctuation - if (script->script_p + len <= script->end_p) - { - //if the script contains the punctuation - if (!Q_strncmp(script->script_p, p, len)) - { + // if the script contains at least as much characters as the punctuation + if (script->script_p + len <= script->end_p) { + // if the script contains the punctuation + if (!Q_strncmp(script->script_p, p, len)) { strncpy(token->string, p, MAX_TOKEN); script->script_p += len; token->type = TT_PUNCTUATION; - //sub type is the number of the punctuation + // sub type is the number of the punctuation token->subtype = punc->n; return 1; - } //end if - } //end if - } //end for + } // end if + } // end if + } // end for return 0; -} //end of the function PS_ReadPunctuation +} // end of the function PS_ReadPunctuation //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadPrimitive(script_t *script, token_t *token) -{ +int PS_ReadPrimitive(script_t *script, token_t *token) { int len; len = 0; - while(*script->script_p > ' ' && *script->script_p != ';') - { - if (len >= MAX_TOKEN - 1) - { + while (*script->script_p > ' ' && *script->script_p != ';') { + if (len >= MAX_TOKEN - 1) { ScriptError(script, "primitive token longer than MAX_TOKEN = %d", MAX_TOKEN); return 0; - } //end if + } // end if token->string[len++] = *script->script_p++; - } //end while + } // end while token->string[len] = 0; - //copy the token into the script structure + // copy the token into the script structure Com_Memcpy(&script->token, token, sizeof(token_t)); - //primitive reading successfull + // primitive reading successfull return 1; -} //end of the function PS_ReadPrimitive +} // end of the function PS_ReadPrimitive //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ReadToken(script_t *script, token_t *token) -{ - //if there is a token available (from UnreadToken) - if (script->tokenavailable) - { +int PS_ReadToken(script_t *script, token_t *token) { + // if there is a token available (from UnreadToken) + if (script->tokenavailable) { script->tokenavailable = 0; Com_Memcpy(token, &script->token, sizeof(token_t)); return 1; - } //end if - //save script pointer + } // end if + // save script pointer script->lastscript_p = script->script_p; - //save line counter + // save line counter script->lastline = script->line; - //clear the token stuff + // clear the token stuff Com_Memset(token, 0, sizeof(token_t)); - //start of the white space + // start of the white space script->whitespace_p = script->script_p; token->whitespace_p = script->script_p; - //read unusefull stuff - if (!PS_ReadWhiteSpace(script)) return 0; - //end of the white space + // read unusefull stuff + if (!PS_ReadWhiteSpace(script)) + return 0; + // end of the white space script->endwhitespace_p = script->script_p; token->endwhitespace_p = script->script_p; - //line the token is on + // line the token is on token->line = script->line; - //number of lines crossed before token + // number of lines crossed before token token->linescrossed = script->line - script->lastline; - //if there is a leading double quote - if (*script->script_p == '\"') - { - if (!PS_ReadString(script, token, '\"')) return 0; - } //end if - //if an literal - else if (*script->script_p == '\'') - { - //if (!PS_ReadLiteral(script, token)) return 0; - if (!PS_ReadString(script, token, '\'')) return 0; - } //end if - //if there is a number + // if there is a leading double quote + if (*script->script_p == '\"') { + if (!PS_ReadString(script, token, '\"')) + return 0; + } // end if + // if an literal + else if (*script->script_p == '\'') { + // if (!PS_ReadLiteral(script, token)) return 0; + if (!PS_ReadString(script, token, '\'')) + return 0; + } // end if + // if there is a number else if ((*script->script_p >= '0' && *script->script_p <= '9') || - (*script->script_p == '.' && - (*(script->script_p + 1) >= '0' && *(script->script_p + 1) <= '9'))) - { - if (!PS_ReadNumber(script, token)) return 0; - } //end if - //if this is a primitive script - else if (script->flags & SCFL_PRIMITIVE) - { + (*script->script_p == '.' && (*(script->script_p + 1) >= '0' && *(script->script_p + 1) <= '9'))) { + if (!PS_ReadNumber(script, token)) + return 0; + } // end if + // if this is a primitive script + else if (script->flags & SCFL_PRIMITIVE) { return PS_ReadPrimitive(script, token); - } //end else if - //if there is a name - else if ((*script->script_p >= 'a' && *script->script_p <= 'z') || - (*script->script_p >= 'A' && *script->script_p <= 'Z') || - *script->script_p == '_' || *script->script_p == '@') - { - if (!PS_ReadName(script, token)) return 0; - } //end if - //check for punctuations - else if (!PS_ReadPunctuation(script, token)) - { + } // end else if + // if there is a name + else if ((*script->script_p >= 'a' && *script->script_p <= 'z') || (*script->script_p >= 'A' && *script->script_p <= 'Z') || *script->script_p == '_' || + *script->script_p == '@') { + if (!PS_ReadName(script, token)) + return 0; + } // end if + // check for punctuations + else if (!PS_ReadPunctuation(script, token)) { ScriptError(script, "can't read token"); return 0; - } //end if - //copy the token into the script structure + } // end if + // copy the token into the script structure Com_Memcpy(&script->token, token, sizeof(token_t)); - //successfully read a token + // successfully read a token return 1; -} //end of the function PS_ReadToken +} // end of the function PS_ReadToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ExpectTokenString(script_t *script, char *string) -{ +int PS_ExpectTokenString(script_t *script, char *string) { token_t token; - if (!PS_ReadToken(script, &token)) - { + if (!PS_ReadToken(script, &token)) { ScriptError(script, "couldn't find expected %s", string); return 0; - } //end if + } // end if - if (strcmp(token.string, string)) - { + if (strcmp(token.string, string)) { ScriptError(script, "expected %s, found %s", string, token.string); return 0; - } //end if + } // end if return 1; -} //end of the function PS_ExpectToken +} // end of the function PS_ExpectToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ExpectTokenType(script_t *script, int type, int subtype, token_t *token) -{ +int PS_ExpectTokenType(script_t *script, int type, int subtype, token_t *token) { char str[MAX_TOKEN]; - if (!PS_ReadToken(script, token)) - { + if (!PS_ReadToken(script, token)) { ScriptError(script, "couldn't read expected token"); return 0; - } //end if + } // end if - if (token->type != type) - { + if (token->type != type) { strcpy(str, ""); - if (type == TT_STRING) strcpy(str, "string"); - if (type == TT_LITERAL) strcpy(str, "literal"); - if (type == TT_NUMBER) strcpy(str, "number"); - if (type == TT_NAME) strcpy(str, "name"); - if (type == TT_PUNCTUATION) strcpy(str, "punctuation"); + if (type == TT_STRING) + strcpy(str, "string"); + if (type == TT_LITERAL) + strcpy(str, "literal"); + if (type == TT_NUMBER) + strcpy(str, "number"); + if (type == TT_NAME) + strcpy(str, "name"); + if (type == TT_PUNCTUATION) + strcpy(str, "punctuation"); ScriptError(script, "expected a %s, found %s", str, token->string); return 0; - } //end if - if (token->type == TT_NUMBER) - { - if ((token->subtype & subtype) != subtype) - { + } // end if + if (token->type == TT_NUMBER) { + if ((token->subtype & subtype) != subtype) { strcpy(str, ""); - if (subtype & TT_DECIMAL) strcpy(str, "decimal"); - if (subtype & TT_HEX) strcpy(str, "hex"); - if (subtype & TT_OCTAL) strcpy(str, "octal"); - if (subtype & TT_BINARY) strcpy(str, "binary"); - if (subtype & TT_LONG) strcat(str, " long"); - if (subtype & TT_UNSIGNED) strcat(str, " unsigned"); - if (subtype & TT_FLOAT) strcat(str, " float"); - if (subtype & TT_INTEGER) strcat(str, " integer"); + if (subtype & TT_DECIMAL) + strcpy(str, "decimal"); + if (subtype & TT_HEX) + strcpy(str, "hex"); + if (subtype & TT_OCTAL) + strcpy(str, "octal"); + if (subtype & TT_BINARY) + strcpy(str, "binary"); + if (subtype & TT_LONG) + strcat(str, " long"); + if (subtype & TT_UNSIGNED) + strcat(str, " unsigned"); + if (subtype & TT_FLOAT) + strcat(str, " float"); + if (subtype & TT_INTEGER) + strcat(str, " integer"); ScriptError(script, "expected %s, found %s", str, token->string); return 0; - } //end if - } //end if - else if (token->type == TT_PUNCTUATION) - { - if (subtype < 0) - { + } // end if + } // end if + else if (token->type == TT_PUNCTUATION) { + if (subtype < 0) { ScriptError(script, "BUG: wrong punctuation subtype"); return 0; - } //end if - if (token->subtype != subtype) - { - ScriptError(script, "expected %s, found %s", - script->punctuations[subtype].p, token->string); + } // end if + if (token->subtype != subtype) { + ScriptError(script, "expected %s, found %s", script->punctuations[subtype].p, token->string); return 0; - } //end if - } //end else if + } // end if + } // end else if return 1; -} //end of the function PS_ExpectTokenType +} // end of the function PS_ExpectTokenType //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_ExpectAnyToken(script_t *script, token_t *token) -{ - if (!PS_ReadToken(script, token)) - { +int PS_ExpectAnyToken(script_t *script, token_t *token) { + if (!PS_ReadToken(script, token)) { ScriptError(script, "couldn't read expected token"); return 0; - } //end if - else - { + } // end if + else { return 1; - } //end else -} //end of the function PS_ExpectAnyToken + } // end else +} // end of the function PS_ExpectAnyToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_CheckTokenString(script_t *script, char *string) -{ +int PS_CheckTokenString(script_t *script, char *string) { token_t tok; - if (!PS_ReadToken(script, &tok)) return 0; - //if the token is available - if (!strcmp(tok.string, string)) return 1; - //token not available + if (!PS_ReadToken(script, &tok)) + return 0; + // if the token is available + if (!strcmp(tok.string, string)) + return 1; + // token not available script->script_p = script->lastscript_p; return 0; -} //end of the function PS_CheckTokenString +} // end of the function PS_CheckTokenString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_CheckTokenType(script_t *script, int type, int subtype, token_t *token) -{ +int PS_CheckTokenType(script_t *script, int type, int subtype, token_t *token) { token_t tok; - if (!PS_ReadToken(script, &tok)) return 0; - //if the type matches - if (tok.type == type && - (tok.subtype & subtype) == subtype) - { + if (!PS_ReadToken(script, &tok)) + return 0; + // if the type matches + if (tok.type == type && (tok.subtype & subtype) == subtype) { Com_Memcpy(token, &tok, sizeof(token_t)); return 1; - } //end if - //token is not available + } // end if + // token is not available script->script_p = script->lastscript_p; return 0; -} //end of the function PS_CheckTokenType +} // end of the function PS_CheckTokenType //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int PS_SkipUntilString(script_t *script, char *string) -{ +int PS_SkipUntilString(script_t *script, char *string) { token_t token; - while(PS_ReadToken(script, &token)) - { - if (!strcmp(token.string, string)) return 1; - } //end while + while (PS_ReadToken(script, &token)) { + if (!strcmp(token.string, string)) + return 1; + } // end while return 0; -} //end of the function PS_SkipUntilString +} // end of the function PS_SkipUntilString //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PS_UnreadLastToken(script_t *script) -{ - script->tokenavailable = 1; -} //end of the function UnreadLastToken +void PS_UnreadLastToken(script_t *script) { script->tokenavailable = 1; } // end of the function UnreadLastToken //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PS_UnreadToken(script_t *script, token_t *token) -{ +void PS_UnreadToken(script_t *script, token_t *token) { Com_Memcpy(&script->token, token, sizeof(token_t)); script->tokenavailable = 1; -} //end of the function UnreadToken +} // end of the function UnreadToken //============================================================================ // returns the next character of the read white space, returns NULL if none // @@ -1106,67 +1069,55 @@ void PS_UnreadToken(script_t *script, token_t *token) // Returns: - // Changes Globals: - //============================================================================ -char PS_NextWhiteSpaceChar(script_t *script) -{ - if (script->whitespace_p != script->endwhitespace_p) - { +char PS_NextWhiteSpaceChar(script_t *script) { + if (script->whitespace_p != script->endwhitespace_p) { return *script->whitespace_p++; - } //end if - else - { + } // end if + else { return 0; - } //end else -} //end of the function PS_NextWhiteSpaceChar + } // end else +} // end of the function PS_NextWhiteSpaceChar //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void StripDoubleQuotes(char *string) -{ - if (*string == '\"') - { - memmove(string, string+1, strlen(string)); - } //end if - if (string[strlen(string)-1] == '\"') - { - string[strlen(string)-1] = '\0'; - } //end if -} //end of the function StripDoubleQuotes +void StripDoubleQuotes(char *string) { + if (*string == '\"') { + memmove(string, string + 1, strlen(string)); + } // end if + if (string[strlen(string) - 1] == '\"') { + string[strlen(string) - 1] = '\0'; + } // end if +} // end of the function StripDoubleQuotes //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void StripSingleQuotes(char *string) -{ - if (*string == '\'') - { - memmove(string, string+1, strlen(string)); - } //end if - if (string[strlen(string)-1] == '\'') - { - string[strlen(string)-1] = '\0'; - } //end if -} //end of the function StripSingleQuotes +void StripSingleQuotes(char *string) { + if (*string == '\'') { + memmove(string, string + 1, strlen(string)); + } // end if + if (string[strlen(string) - 1] == '\'') { + string[strlen(string) - 1] = '\0'; + } // end if +} // end of the function StripSingleQuotes //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -long double ReadSignedFloat(script_t *script) -{ +long double ReadSignedFloat(script_t *script) { token_t token; long double sign = 1; PS_ExpectAnyToken(script, &token); - if (!strcmp(token.string, "-")) - { - if(!PS_ExpectAnyToken(script, &token)) - { + if (!strcmp(token.string, "-")) { + if (!PS_ExpectAnyToken(script, &token)) { ScriptError(script, "Missing float value"); return 0; } @@ -1174,30 +1125,26 @@ long double ReadSignedFloat(script_t *script) sign = -1; } - if (token.type != TT_NUMBER) - { + if (token.type != TT_NUMBER) { ScriptError(script, "expected float value, found %s", token.string); return 0; } return sign * token.floatvalue; -} //end of the function ReadSignedFloat +} // end of the function ReadSignedFloat //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -signed long int ReadSignedInt(script_t *script) -{ +signed long int ReadSignedInt(script_t *script) { token_t token; signed long int sign = 1; PS_ExpectAnyToken(script, &token); - if (!strcmp(token.string, "-")) - { - if(!PS_ExpectAnyToken(script, &token)) - { + if (!strcmp(token.string, "-")) { + if (!PS_ExpectAnyToken(script, &token)) { ScriptError(script, "Missing integer value"); return 0; } @@ -1205,58 +1152,50 @@ signed long int ReadSignedInt(script_t *script) sign = -1; } - if (token.type != TT_NUMBER || token.subtype == TT_FLOAT) - { + if (token.type != TT_NUMBER || token.subtype == TT_FLOAT) { ScriptError(script, "expected integer value, found %s", token.string); return 0; } return sign * token.intvalue; -} //end of the function ReadSignedInt +} // end of the function ReadSignedInt //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void SetScriptFlags(script_t *script, int flags) -{ - script->flags = flags; -} //end of the function SetScriptFlags +void SetScriptFlags(script_t *script, int flags) { script->flags = flags; } // end of the function SetScriptFlags //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int GetScriptFlags(script_t *script) -{ - return script->flags; -} //end of the function GetScriptFlags +int GetScriptFlags(script_t *script) { return script->flags; } // end of the function GetScriptFlags //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void ResetScript(script_t *script) -{ - //pointer in script buffer +void ResetScript(script_t *script) { + // pointer in script buffer script->script_p = script->buffer; - //pointer in script buffer before reading token + // pointer in script buffer before reading token script->lastscript_p = script->buffer; - //begin of white space + // begin of white space script->whitespace_p = NULL; - //end of white space + // end of white space script->endwhitespace_p = NULL; - //set if there's a token available in script->token + // set if there's a token available in script->token script->tokenavailable = 0; // script->line = 1; script->lastline = 1; - //clear the saved token + // clear the saved token Com_Memset(&script->token, 0, sizeof(token_t)); -} //end of the function ResetScript +} // end of the function ResetScript //============================================================================ // returns true if at the end of the script // @@ -1264,46 +1203,37 @@ void ResetScript(script_t *script) // Returns: - // Changes Globals: - //============================================================================ -int EndOfScript(script_t *script) -{ - return script->script_p >= script->end_p; -} //end of the function EndOfScript +int EndOfScript(script_t *script) { return script->script_p >= script->end_p; } // end of the function EndOfScript //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int NumLinesCrossed(script_t *script) -{ - return script->line - script->lastline; -} //end of the function NumLinesCrossed +int NumLinesCrossed(script_t *script) { return script->line - script->lastline; } // end of the function NumLinesCrossed //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -int ScriptSkipTo(script_t *script, char *value) -{ +int ScriptSkipTo(script_t *script, char *value) { int len; char firstchar; firstchar = *value; len = strlen(value); - do - { - if (!PS_ReadWhiteSpace(script)) return 0; - if (*script->script_p == firstchar) - { - if (!Q_strncmp(script->script_p, value, len)) - { + do { + if (!PS_ReadWhiteSpace(script)) + return 0; + if (*script->script_p == firstchar) { + if (!Q_strncmp(script->script_p, value, len)) { return 1; - } //end if - } //end if + } // end if + } // end if script->script_p++; - } while(1); -} //end of the function ScriptSkipTo + } while (1); +} // end of the function ScriptSkipTo #ifndef BOTLIB //============================================================================ // @@ -1311,8 +1241,7 @@ int ScriptSkipTo(script_t *script, char *value) // Returns: - // Changes Globals: - //============================================================================ -int FileLength(FILE *fp) -{ +int FileLength(FILE *fp) { int pos; int end; @@ -1322,7 +1251,7 @@ int FileLength(FILE *fp) fseek(fp, pos, SEEK_SET); return end; -} //end of the function FileLength +} // end of the function FileLength #endif //============================================================================ // @@ -1330,8 +1259,7 @@ int FileLength(FILE *fp) // Returns: - // Changes Globals: - //============================================================================ -script_t *LoadScriptFile(const char *filename) -{ +script_t *LoadScriptFile(const char *filename) { #ifdef BOTLIB fileHandle_t fp; char pathname[MAX_QPATH]; @@ -1347,29 +1275,31 @@ script_t *LoadScriptFile(const char *filename) Com_sprintf(pathname, sizeof(pathname), "%s/%s", basefolder, filename); else Com_sprintf(pathname, sizeof(pathname), "%s", filename); - length = botimport.FS_FOpenFile( pathname, &fp, FS_READ ); - if (!fp) return NULL; + length = botimport.FS_FOpenFile(pathname, &fp, FS_READ); + if (!fp) + return NULL; #else fp = fopen(filename, "rb"); - if (!fp) return NULL; + if (!fp) + return NULL; length = FileLength(fp); #endif buffer = GetClearedMemory(sizeof(script_t) + length + 1); - script = (script_t *) buffer; + script = (script_t *)buffer; Com_Memset(script, 0, sizeof(script_t)); Q_strncpyz(script->filename, filename, sizeof(script->filename)); - script->buffer = (char *) buffer + sizeof(script_t); + script->buffer = (char *)buffer + sizeof(script_t); script->buffer[length] = 0; script->length = length; - //pointer in script buffer + // pointer in script buffer script->script_p = script->buffer; - //pointer in script buffer before reading token + // pointer in script buffer before reading token script->lastscript_p = script->buffer; - //pointer to end of script buffer + // pointer to end of script buffer script->end_p = &script->buffer[length]; - //set if there's a token available in script->token + // set if there's a token available in script->token script->tokenavailable = 0; // script->line = 1; @@ -1381,43 +1311,41 @@ script_t *LoadScriptFile(const char *filename) botimport.FS_Read(script->buffer, length, fp); botimport.FS_FCloseFile(fp); #else - if (fread(script->buffer, length, 1, fp) != 1) - { + if (fread(script->buffer, length, 1, fp) != 1) { FreeMemory(buffer); script = NULL; - } //end if + } // end if fclose(fp); #endif // script->length = COM_Compress(script->buffer); return script; -} //end of the function LoadScriptFile +} // end of the function LoadScriptFile //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -script_t *LoadScriptMemory(char *ptr, int length, char *name) -{ +script_t *LoadScriptMemory(char *ptr, int length, char *name) { void *buffer; script_t *script; buffer = GetClearedMemory(sizeof(script_t) + length + 1); - script = (script_t *) buffer; + script = (script_t *)buffer; Com_Memset(script, 0, sizeof(script_t)); Q_strncpyz(script->filename, name, sizeof(script->filename)); - script->buffer = (char *) buffer + sizeof(script_t); + script->buffer = (char *)buffer + sizeof(script_t); script->buffer[length] = 0; script->length = length; - //pointer in script buffer + // pointer in script buffer script->script_p = script->buffer; - //pointer in script buffer before reading token + // pointer in script buffer before reading token script->lastscript_p = script->buffer; - //pointer to end of script buffer + // pointer to end of script buffer script->end_p = &script->buffer[length]; - //set if there's a token available in script->token + // set if there's a token available in script->token script->tokenavailable = 0; // script->line = 1; @@ -1428,31 +1356,30 @@ script_t *LoadScriptMemory(char *ptr, int length, char *name) Com_Memcpy(script->buffer, ptr, length); // return script; -} //end of the function LoadScriptMemory +} // end of the function LoadScriptMemory //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void FreeScript(script_t *script) -{ +void FreeScript(script_t *script) { #ifdef PUNCTABLE - if (script->punctuationtable) FreeMemory(script->punctuationtable); -#endif //PUNCTABLE + if (script->punctuationtable) + FreeMemory(script->punctuationtable); +#endif // PUNCTABLE FreeMemory(script); -} //end of the function FreeScript +} // end of the function FreeScript //============================================================================ // // Parameter: - // Returns: - // Changes Globals: - //============================================================================ -void PS_SetBaseFolder(char *path) -{ +void PS_SetBaseFolder(char *path) { #ifdef BSPC sprintf(basefolder, path); #else Com_sprintf(basefolder, sizeof(basefolder), "%s", path); #endif -} //end of the function PS_SetBaseFolder +} // end of the function PS_SetBaseFolder diff --git a/codemp/botlib/l_struct.cpp b/codemp/botlib/l_struct.cpp index bd8e0bfcce..8f23f18b6f 100644 --- a/codemp/botlib/l_struct.cpp +++ b/codemp/botlib/l_struct.cpp @@ -36,25 +36,25 @@ along with this program; if not, see . #ifdef BOTLIB #include "qcommon/q_shared.h" -#include "botlib.h" //for the include of be_interface.h +#include "botlib.h" //for the include of be_interface.h #include "l_script.h" #include "l_precomp.h" #include "l_struct.h" #include "l_utils.h" #include "be_interface.h" -#endif //BOTLIB +#endif // BOTLIB #ifdef BSPC -//include files for usage in the BSP Converter +// include files for usage in the BSP Converter #include "../bspc/qbsp.h" #include "../bspc/l_log.h" #include "../bspc/l_mem.h" #include "l_precomp.h" #include "l_struct.h" -#define qtrue true -#define qfalse false -#endif //BSPC +#define qtrue true +#define qfalse false +#endif // BSPC //=========================================================================== // @@ -62,406 +62,392 @@ along with this program; if not, see . // Returns: - // Changes Globals: - //=========================================================================== -fielddef_t *FindField(fielddef_t *defs, char *name) -{ +fielddef_t *FindField(fielddef_t *defs, char *name) { int i; - for (i = 0; defs[i].name; i++) - { - if (!strcmp(defs[i].name, name)) return &defs[i]; - } //end for + for (i = 0; defs[i].name; i++) { + if (!strcmp(defs[i].name, name)) + return &defs[i]; + } // end for return NULL; -} //end of the function FindField +} // end of the function FindField //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean ReadNumber(source_t *source, fielddef_t *fd, void *p) -{ +qboolean ReadNumber(source_t *source, fielddef_t *fd, void *p) { token_t token; int negative = qfalse; long int intval, intmin = 0, intmax = 0; double floatval; - if (!PC_ExpectAnyToken(source, &token)) return (qboolean)0; + if (!PC_ExpectAnyToken(source, &token)) + return (qboolean)0; - //check for minus sign - if (token.type == TT_PUNCTUATION) - { - if (fd->type & FT_UNSIGNED) - { + // check for minus sign + if (token.type == TT_PUNCTUATION) { + if (fd->type & FT_UNSIGNED) { SourceError(source, "expected unsigned value, found %s", token.string); return (qboolean)0; - } //end if - //if not a minus sign - if (strcmp(token.string, "-")) - { + } // end if + // if not a minus sign + if (strcmp(token.string, "-")) { SourceError(source, "unexpected punctuation %s", token.string); return (qboolean)0; - } //end if + } // end if negative = qtrue; - //read the number - if (!PC_ExpectAnyToken(source, &token)) return (qboolean)0; - } //end if - //check if it is a number - if (token.type != TT_NUMBER) - { + // read the number + if (!PC_ExpectAnyToken(source, &token)) + return (qboolean)0; + } // end if + // check if it is a number + if (token.type != TT_NUMBER) { SourceError(source, "expected number, found %s", token.string); return (qboolean)0; - } //end if - //check for a float value - if (token.subtype & TT_FLOAT) - { - if ((fd->type & FT_TYPE) != FT_FLOAT) - { + } // end if + // check for a float value + if (token.subtype & TT_FLOAT) { + if ((fd->type & FT_TYPE) != FT_FLOAT) { SourceError(source, "unexpected float"); return (qboolean)0; - } //end if + } // end if floatval = token.floatvalue; - if (negative) floatval = -floatval; - if (fd->type & FT_BOUNDED) - { - if (floatval < fd->floatmin || floatval > fd->floatmax) - { + if (negative) + floatval = -floatval; + if (fd->type & FT_BOUNDED) { + if (floatval < fd->floatmin || floatval > fd->floatmax) { SourceError(source, "float out of range [%f, %f]", fd->floatmin, fd->floatmax); return (qboolean)0; - } //end if - } //end if - *(float *) p = (float) floatval; + } // end if + } // end if + *(float *)p = (float)floatval; return (qboolean)1; - } //end if + } // end if // intval = token.intvalue; - if (negative) intval = -intval; - //check bounds - if ((fd->type & FT_TYPE) == FT_CHAR) - { - if (fd->type & FT_UNSIGNED) {intmin = 0; intmax = 255;} - else {intmin = -128; intmax = 127;} - } //end if - if ((fd->type & FT_TYPE) == FT_INT) - { - if (fd->type & FT_UNSIGNED) {intmin = 0; intmax = 65535;} - else {intmin = -32768; intmax = 32767;} - } //end else if - if ((fd->type & FT_TYPE) == FT_CHAR || (fd->type & FT_TYPE) == FT_INT) - { - if (fd->type & FT_BOUNDED) - { + if (negative) + intval = -intval; + // check bounds + if ((fd->type & FT_TYPE) == FT_CHAR) { + if (fd->type & FT_UNSIGNED) { + intmin = 0; + intmax = 255; + } else { + intmin = -128; + intmax = 127; + } + } // end if + if ((fd->type & FT_TYPE) == FT_INT) { + if (fd->type & FT_UNSIGNED) { + intmin = 0; + intmax = 65535; + } else { + intmin = -32768; + intmax = 32767; + } + } // end else if + if ((fd->type & FT_TYPE) == FT_CHAR || (fd->type & FT_TYPE) == FT_INT) { + if (fd->type & FT_BOUNDED) { intmin = Maximum(intmin, fd->floatmin); intmax = Minimum(intmax, fd->floatmax); - } //end if - if (intval < intmin || intval > intmax) - { + } // end if + if (intval < intmin || intval > intmax) { SourceError(source, "value %ld out of range [%ld, %ld]", intval, intmin, intmax); return (qboolean)0; - } //end if - } //end if - else if ((fd->type & FT_TYPE) == FT_FLOAT) - { - if (fd->type & FT_BOUNDED) - { - if (intval < fd->floatmin || intval > fd->floatmax) - { + } // end if + } // end if + else if ((fd->type & FT_TYPE) == FT_FLOAT) { + if (fd->type & FT_BOUNDED) { + if (intval < fd->floatmin || intval > fd->floatmax) { SourceError(source, "value %ld out of range [%f, %f]", intval, fd->floatmin, fd->floatmax); return (qboolean)0; - } //end if - } //end if - } //end else if - //store the value - if ((fd->type & FT_TYPE) == FT_CHAR) - { - if (fd->type & FT_UNSIGNED) *(unsigned char *) p = (unsigned char) intval; - else *(char *) p = (char) intval; - } //end if - else if ((fd->type & FT_TYPE) == FT_INT) - { - if (fd->type & FT_UNSIGNED) *(unsigned int *) p = (unsigned int) intval; - else *(int *) p = (int) intval; - } //end else - else if ((fd->type & FT_TYPE) == FT_FLOAT) - { - *(float *) p = (float) intval; - } //end else + } // end if + } // end if + } // end else if + // store the value + if ((fd->type & FT_TYPE) == FT_CHAR) { + if (fd->type & FT_UNSIGNED) + *(unsigned char *)p = (unsigned char)intval; + else + *(char *)p = (char)intval; + } // end if + else if ((fd->type & FT_TYPE) == FT_INT) { + if (fd->type & FT_UNSIGNED) + *(unsigned int *)p = (unsigned int)intval; + else + *(int *)p = (int)intval; + } // end else + else if ((fd->type & FT_TYPE) == FT_FLOAT) { + *(float *)p = (float)intval; + } // end else return (qboolean)1; -} //end of the function ReadNumber +} // end of the function ReadNumber //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -qboolean ReadChar(source_t *source, fielddef_t *fd, void *p) -{ +qboolean ReadChar(source_t *source, fielddef_t *fd, void *p) { token_t token; - if (!PC_ExpectAnyToken(source, &token)) return (qboolean)0; + if (!PC_ExpectAnyToken(source, &token)) + return (qboolean)0; - //take literals into account - if (token.type == TT_LITERAL) - { + // take literals into account + if (token.type == TT_LITERAL) { StripSingleQuotes(token.string); - *(char *) p = token.string[0]; - } //end if - else - { + *(char *)p = token.string[0]; + } // end if + else { PC_UnreadLastToken(source); - if (!ReadNumber(source, fd, p)) return (qboolean)0; - } //end if + if (!ReadNumber(source, fd, p)) + return (qboolean)0; + } // end if return (qboolean)1; -} //end of the function ReadChar +} // end of the function ReadChar //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int ReadString(source_t *source, fielddef_t *fd, void *p) -{ +int ReadString(source_t *source, fielddef_t *fd, void *p) { token_t token; - if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) return 0; - //remove the double quotes + if (!PC_ExpectTokenType(source, TT_STRING, 0, &token)) + return 0; + // remove the double quotes StripDoubleQuotes(token.string); - //copy the string - strncpy((char *) p, token.string, MAX_STRINGFIELD); - //make sure the string is closed with a zero - ((char *)p)[MAX_STRINGFIELD-1] = '\0'; + // copy the string + strncpy((char *)p, token.string, MAX_STRINGFIELD); + // make sure the string is closed with a zero + ((char *)p)[MAX_STRINGFIELD - 1] = '\0'; // return 1; -} //end of the function ReadString +} // end of the function ReadString //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int ReadStructure(source_t *source, structdef_t *def, char *structure) -{ +int ReadStructure(source_t *source, structdef_t *def, char *structure) { token_t token; fielddef_t *fd; void *p; int num; - if (!PC_ExpectTokenString(source, "{")) return 0; - while(1) - { - if (!PC_ExpectAnyToken(source, &token)) return qfalse; - //if end of structure - if (!strcmp(token.string, "}")) break; - //find the field with the name + if (!PC_ExpectTokenString(source, "{")) + return 0; + while (1) { + if (!PC_ExpectAnyToken(source, &token)) + return qfalse; + // if end of structure + if (!strcmp(token.string, "}")) + break; + // find the field with the name fd = FindField(def->fields, token.string); - if (!fd) - { + if (!fd) { SourceError(source, "unknown structure field %s", token.string); return qfalse; - } //end if - if (fd->type & FT_ARRAY) - { + } // end if + if (fd->type & FT_ARRAY) { num = fd->maxarray; - if (!PC_ExpectTokenString(source, "{")) return qfalse; - } //end if - else - { + if (!PC_ExpectTokenString(source, "{")) + return qfalse; + } // end if + else { num = 1; - } //end else + } // end else p = (void *)(structure + fd->offset); - while (num-- > 0) - { - if (fd->type & FT_ARRAY) - { - if (PC_CheckTokenString(source, "}")) break; - } //end if - switch(fd->type & FT_TYPE) - { - case FT_CHAR: - { - if (!ReadChar(source, fd, p)) return qfalse; - p = (char *) p + sizeof(char); - break; - } //end case - case FT_INT: - { - if (!ReadNumber(source, fd, p)) return qfalse; - p = (char *) p + sizeof(int); - break; - } //end case - case FT_FLOAT: - { - if (!ReadNumber(source, fd, p)) return qfalse; - p = (char *) p + sizeof(float); + while (num-- > 0) { + if (fd->type & FT_ARRAY) { + if (PC_CheckTokenString(source, "}")) break; - } //end case - case FT_STRING: - { - if (!ReadString(source, fd, p)) return qfalse; - p = (char *) p + MAX_STRINGFIELD; - break; - } //end case - case FT_STRUCT: - { - if (!fd->substruct) - { - SourceError(source, "BUG: no sub structure defined"); - return qfalse; - } //end if - ReadStructure(source, fd->substruct, (char *) p); - p = (char *) p + fd->substruct->size; + } // end if + switch (fd->type & FT_TYPE) { + case FT_CHAR: { + if (!ReadChar(source, fd, p)) + return qfalse; + p = (char *)p + sizeof(char); + break; + } // end case + case FT_INT: { + if (!ReadNumber(source, fd, p)) + return qfalse; + p = (char *)p + sizeof(int); + break; + } // end case + case FT_FLOAT: { + if (!ReadNumber(source, fd, p)) + return qfalse; + p = (char *)p + sizeof(float); + break; + } // end case + case FT_STRING: { + if (!ReadString(source, fd, p)) + return qfalse; + p = (char *)p + MAX_STRINGFIELD; + break; + } // end case + case FT_STRUCT: { + if (!fd->substruct) { + SourceError(source, "BUG: no sub structure defined"); + return qfalse; + } // end if + ReadStructure(source, fd->substruct, (char *)p); + p = (char *)p + fd->substruct->size; + break; + } // end case + } // end switch + if (fd->type & FT_ARRAY) { + if (!PC_ExpectAnyToken(source, &token)) + return qfalse; + if (!strcmp(token.string, "}")) break; - } //end case - } //end switch - if (fd->type & FT_ARRAY) - { - if (!PC_ExpectAnyToken(source, &token)) return qfalse; - if (!strcmp(token.string, "}")) break; - if (strcmp(token.string, ",")) - { + if (strcmp(token.string, ",")) { SourceError(source, "expected a comma, found %s", token.string); return qfalse; - } //end if - } //end if - } //end while - } //end while + } // end if + } // end if + } // end while + } // end while return qtrue; -} //end of the function ReadStructure +} // end of the function ReadStructure //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WriteIndent(FILE *fp, int indent) -{ - while(indent-- > 0) - { - if (fprintf(fp, "\t") < 0) return qfalse; - } //end while +int WriteIndent(FILE *fp, int indent) { + while (indent-- > 0) { + if (fprintf(fp, "\t") < 0) + return qfalse; + } // end while return qtrue; -} //end of the function WriteIndent +} // end of the function WriteIndent //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WriteFloat(FILE *fp, float value) -{ +int WriteFloat(FILE *fp, float value) { char buf[128]; int l; Com_sprintf(buf, sizeof(buf), "%f", value); l = strlen(buf); - //strip any trailing zeros - while(l-- > 1) - { - if (buf[l] != '0' && buf[l] != '.') break; - if (buf[l] == '.') - { + // strip any trailing zeros + while (l-- > 1) { + if (buf[l] != '0' && buf[l] != '.') + break; + if (buf[l] == '.') { buf[l] = 0; break; - } //end if + } // end if buf[l] = 0; - } //end while - //write the float to file - if (fprintf(fp, "%s", buf) < 0) return 0; + } // end while + // write the float to file + if (fprintf(fp, "%s", buf) < 0) + return 0; return 1; -} //end of the function WriteFloat +} // end of the function WriteFloat //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WriteStructWithIndent(FILE *fp, structdef_t *def, char *structure, int indent) -{ +int WriteStructWithIndent(FILE *fp, structdef_t *def, char *structure, int indent) { int i, num; void *p; fielddef_t *fd; - if (!WriteIndent(fp, indent)) return qfalse; - if (fprintf(fp, "{\r\n") < 0) return qfalse; + if (!WriteIndent(fp, indent)) + return qfalse; + if (fprintf(fp, "{\r\n") < 0) + return qfalse; indent++; - for (i = 0; def->fields[i].name; i++) - { + for (i = 0; def->fields[i].name; i++) { fd = &def->fields[i]; - if (!WriteIndent(fp, indent)) return qfalse; - if (fprintf(fp, "%s\t", fd->name) < 0) return qfalse; + if (!WriteIndent(fp, indent)) + return qfalse; + if (fprintf(fp, "%s\t", fd->name) < 0) + return qfalse; p = (void *)(structure + fd->offset); - if (fd->type & FT_ARRAY) - { + if (fd->type & FT_ARRAY) { num = fd->maxarray; - if (fprintf(fp, "{") < 0) return qfalse; - } //end if - else - { + if (fprintf(fp, "{") < 0) + return qfalse; + } // end if + else { num = 1; - } //end else - while(num-- > 0) - { - switch(fd->type & FT_TYPE) - { - case FT_CHAR: - { - if (fprintf(fp, "%d", *(char *) p) < 0) return qfalse; - p = (char *) p + sizeof(char); - break; - } //end case - case FT_INT: - { - if (fprintf(fp, "%d", *(int *) p) < 0) return qfalse; - p = (char *) p + sizeof(int); - break; - } //end case - case FT_FLOAT: - { - if (!WriteFloat(fp, *(float *)p)) return qfalse; - p = (char *) p + sizeof(float); - break; - } //end case - case FT_STRING: - { - if (fprintf(fp, "\"%s\"", (char *) p) < 0) return qfalse; - p = (char *) p + MAX_STRINGFIELD; - break; - } //end case - case FT_STRUCT: - { - if (!WriteStructWithIndent(fp, fd->substruct, structure, indent)) return qfalse; - p = (char *) p + fd->substruct->size; - break; - } //end case - } //end switch - if (fd->type & FT_ARRAY) - { - if (num > 0) - { - if (fprintf(fp, ",") < 0) return qfalse; - } //end if - else - { - if (fprintf(fp, "}") < 0) return qfalse; - } //end else - } //end if - } //end while - if (fprintf(fp, "\r\n") < 0) return qfalse; - } //end for + } // end else + while (num-- > 0) { + switch (fd->type & FT_TYPE) { + case FT_CHAR: { + if (fprintf(fp, "%d", *(char *)p) < 0) + return qfalse; + p = (char *)p + sizeof(char); + break; + } // end case + case FT_INT: { + if (fprintf(fp, "%d", *(int *)p) < 0) + return qfalse; + p = (char *)p + sizeof(int); + break; + } // end case + case FT_FLOAT: { + if (!WriteFloat(fp, *(float *)p)) + return qfalse; + p = (char *)p + sizeof(float); + break; + } // end case + case FT_STRING: { + if (fprintf(fp, "\"%s\"", (char *)p) < 0) + return qfalse; + p = (char *)p + MAX_STRINGFIELD; + break; + } // end case + case FT_STRUCT: { + if (!WriteStructWithIndent(fp, fd->substruct, structure, indent)) + return qfalse; + p = (char *)p + fd->substruct->size; + break; + } // end case + } // end switch + if (fd->type & FT_ARRAY) { + if (num > 0) { + if (fprintf(fp, ",") < 0) + return qfalse; + } // end if + else { + if (fprintf(fp, "}") < 0) + return qfalse; + } // end else + } // end if + } // end while + if (fprintf(fp, "\r\n") < 0) + return qfalse; + } // end for indent--; - if (!WriteIndent(fp, indent)) return qfalse; - if (fprintf(fp, "}\r\n") < 0) return qfalse; + if (!WriteIndent(fp, indent)) + return qfalse; + if (fprintf(fp, "}\r\n") < 0) + return qfalse; return qtrue; -} //end of the function WriteStructWithIndent +} // end of the function WriteStructWithIndent //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== -int WriteStructure(FILE *fp, structdef_t *def, char *structure) -{ - return WriteStructWithIndent(fp, def, structure, 0); -} //end of the function WriteStructure - +int WriteStructure(FILE *fp, structdef_t *def, char *structure) { return WriteStructWithIndent(fp, def, structure, 0); } // end of the function WriteStructure diff --git a/codemp/cgame/cg_consolecmds.c b/codemp/cgame/cg_consolecmds.c index 564da918a9..41a186a95c 100644 --- a/codemp/cgame/cg_consolecmds.c +++ b/codemp/cgame/cg_consolecmds.c @@ -35,17 +35,17 @@ CG_TargetCommand_f ================= */ -void CG_TargetCommand_f( void ) { - int targetNum; - char test[4]; +void CG_TargetCommand_f(void) { + int targetNum; + char test[4]; targetNum = CG_CrosshairPlayer(); - if ( targetNum == -1 ) { + if (targetNum == -1) { return; } - trap->Cmd_Argv( 1, test, 4 ); - trap->SendClientCommand( va( "gc %i %i", targetNum, atoi( test ) ) ); + trap->Cmd_Argv(1, test, 4); + trap->SendClientCommand(va("gc %i %i", targetNum, atoi(test))); } /* @@ -55,9 +55,7 @@ CG_SizeUp_f Keybinding command ================= */ -static void CG_SizeUp_f (void) { - trap->Cvar_Set( "cg_viewsize", va( "%i", Q_min( cg_viewsize.integer + 10, 100 ) ) ); -} +static void CG_SizeUp_f(void) { trap->Cvar_Set("cg_viewsize", va("%i", Q_min(cg_viewsize.integer + 10, 100))); } /* ================= @@ -66,9 +64,7 @@ CG_SizeDown_f Keybinding command ================= */ -static void CG_SizeDown_f (void) { - trap->Cvar_Set( "cg_viewsize", va( "%i", Q_max( cg_viewsize.integer - 10, 30 ) ) ); -} +static void CG_SizeDown_f(void) { trap->Cvar_Set("cg_viewsize", va("%i", Q_max(cg_viewsize.integer - 10, 30))); } /* ============= @@ -77,10 +73,9 @@ CG_Viewpos_f Debugging command to print the current position ============= */ -static void CG_Viewpos_f (void) { - trap->Print ("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], - (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], - (int)cg.refdef.viewangles[YAW]); +static void CG_Viewpos_f(void) { + trap->Print("%s (%i %i %i) : %i\n", cgs.mapname, (int)cg.refdef.vieworg[0], (int)cg.refdef.vieworg[1], (int)cg.refdef.vieworg[2], + (int)cg.refdef.viewangles[YAW]); } /* @@ -89,18 +84,18 @@ CG_ScoresDown_f ================= */ -static void CG_ScoresDown_f( void ) { +static void CG_ScoresDown_f(void) { CG_BuildSpectatorString(); - if ( cg.scoresRequestTime + 2000 < cg.time ) { + if (cg.scoresRequestTime + 2000 < cg.time) { // the scores are more than two seconds out of data, // so request new ones cg.scoresRequestTime = cg.time; - trap->SendClientCommand( "score" ); + trap->SendClientCommand("score"); // leave the current scores up if they were already // displayed, but if this is the first hit, clear them out - if ( !cg.showScores ) { + if (!cg.showScores) { cg.showScores = qtrue; cg.numScores = 0; } @@ -117,82 +112,76 @@ CG_ScoresUp_f ================= */ -static void CG_ScoresUp_f( void ) { - if ( cg.showScores ) { +static void CG_ScoresUp_f(void) { + if (cg.showScores) { cg.showScores = qfalse; cg.scoreFadeTime = cg.time; } } -void CG_ClientList_f( void ) -{ +void CG_ClientList_f(void) { clientInfo_t *ci; int i; int count = 0; - for( i = 0; i < MAX_CLIENTS; i++ ) - { - ci = &cgs.clientinfo[ i ]; - if( !ci->infoValid ) + for (i = 0; i < MAX_CLIENTS; i++) { + ci = &cgs.clientinfo[i]; + if (!ci->infoValid) continue; - switch( ci->team ) - { + switch (ci->team) { case TEAM_FREE: - Com_Printf( "%2d " S_COLOR_YELLOW "F " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : "" ); + Com_Printf("%2d " S_COLOR_YELLOW "F " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : ""); break; case TEAM_RED: - Com_Printf( "%2d " S_COLOR_RED "R " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, - ci->name, (ci->botSkill != -1) ? " (bot)" : "" ); + Com_Printf("%2d " S_COLOR_RED "R " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : ""); break; case TEAM_BLUE: - Com_Printf( "%2d " S_COLOR_BLUE "B " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, - ci->name, (ci->botSkill != -1) ? " (bot)" : "" ); + Com_Printf("%2d " S_COLOR_BLUE "B " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : ""); break; default: case TEAM_SPECTATOR: - Com_Printf( "%2d " S_COLOR_YELLOW "S " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : "" ); + Com_Printf("%2d " S_COLOR_YELLOW "S " S_COLOR_WHITE "%s" S_COLOR_WHITE "%s\n", i, ci->name, (ci->botSkill != -1) ? " (bot)" : ""); break; } count++; } - Com_Printf( "Listed %2d clients\n", count ); + Com_Printf("Listed %2d clients\n", count); } - -static void CG_TellTarget_f( void ) { - int clientNum; - char command[MAX_SAY_TEXT+10]; - char message[MAX_SAY_TEXT]; +static void CG_TellTarget_f(void) { + int clientNum; + char command[MAX_SAY_TEXT + 10]; + char message[MAX_SAY_TEXT]; clientNum = CG_CrosshairPlayer(); - if ( clientNum == -1 ) { + if (clientNum == -1) { return; } - trap->Cmd_Args( message, sizeof(message) ); - Com_sprintf( command, sizeof(command), "tell %i %s", clientNum, message ); - trap->SendClientCommand( command ); + trap->Cmd_Args(message, sizeof(message)); + Com_sprintf(command, sizeof(command), "tell %i %s", clientNum, message); + trap->SendClientCommand(command); } -static void CG_TellAttacker_f( void ) { - int clientNum; - char command[MAX_SAY_TEXT + 10]; - char message[MAX_SAY_TEXT]; +static void CG_TellAttacker_f(void) { + int clientNum; + char command[MAX_SAY_TEXT + 10]; + char message[MAX_SAY_TEXT]; clientNum = CG_LastAttacker(); - if ( clientNum == -1 ) { + if (clientNum == -1) { return; } - trap->Cmd_Args( message, sizeof(message) ); - Com_sprintf( command, sizeof(command), "tell %i %s", clientNum, message ); - trap->SendClientCommand( command ); + trap->Cmd_Args(message, sizeof(message)); + Com_sprintf(command, sizeof(command), "tell %i %s", clientNum, message); + trap->SendClientCommand(command); } /* @@ -201,15 +190,15 @@ CG_StartOrbit_f ================== */ -static void CG_StartOrbit_f( void ) { +static void CG_StartOrbit_f(void) { char var[MAX_TOKEN_CHARS]; - trap->Cvar_VariableStringBuffer( "developer", var, sizeof( var ) ); - if ( !atoi(var) ) { + trap->Cvar_VariableStringBuffer("developer", var, sizeof(var)); + if (!atoi(var)) { return; } if (cg_cameraOrbit.value != 0) { - trap->Cvar_Set ("cg_cameraOrbit", "0"); + trap->Cvar_Set("cg_cameraOrbit", "0"); trap->Cvar_Set("cg_thirdPerson", "0"); } else { trap->Cvar_Set("cg_cameraOrbit", "5"); @@ -220,50 +209,40 @@ static void CG_StartOrbit_f( void ) { } void CG_SiegeBriefingDisplay(int team, int dontshow); -static void CG_SiegeBriefing_f(void) -{ +static void CG_SiegeBriefing_f(void) { int team; - if (cgs.gametype != GT_SIEGE) - { //Cannot be displayed unless in this gametype + if (cgs.gametype != GT_SIEGE) { // Cannot be displayed unless in this gametype return; } team = cg.predictedPlayerState.persistant[PERS_TEAM]; - if (team != SIEGETEAM_TEAM1 && - team != SIEGETEAM_TEAM2) - { //cannot be displayed if not on a valid team + if (team != SIEGETEAM_TEAM1 && team != SIEGETEAM_TEAM2) { // cannot be displayed if not on a valid team return; } CG_SiegeBriefingDisplay(team, 0); } -static void CG_SiegeCvarUpdate_f(void) -{ +static void CG_SiegeCvarUpdate_f(void) { int team; - if (cgs.gametype != GT_SIEGE) - { //Cannot be displayed unless in this gametype + if (cgs.gametype != GT_SIEGE) { // Cannot be displayed unless in this gametype return; } team = cg.predictedPlayerState.persistant[PERS_TEAM]; - if (team != SIEGETEAM_TEAM1 && - team != SIEGETEAM_TEAM2) - { //cannot be displayed if not on a valid team + if (team != SIEGETEAM_TEAM1 && team != SIEGETEAM_TEAM2) { // cannot be displayed if not on a valid team return; } CG_SiegeBriefingDisplay(team, 1); } -static void CG_SiegeCompleteCvarUpdate_f(void) -{ - if (cgs.gametype != GT_SIEGE) - { //Cannot be displayed unless in this gametype +static void CG_SiegeCompleteCvarUpdate_f(void) { + if (cgs.gametype != GT_SIEGE) { // Cannot be displayed unless in this gametype return; } @@ -272,59 +251,57 @@ static void CG_SiegeCompleteCvarUpdate_f(void) CG_SiegeBriefingDisplay(SIEGETEAM_TEAM2, 1); } -static void CG_LoadHud_f( void ) { +static void CG_LoadHud_f(void) { const char *hudSet = cg_hudFiles.string; - if ( hudSet[0] == '\0' ) { + if (hudSet[0] == '\0') { hudSet = "ui/jahud.txt"; } String_Init(); Menu_Reset(); - CG_LoadMenus( hudSet ); + CG_LoadMenus(hudSet); } typedef struct consoleCommand_s { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } consoleCommand_t; -int cmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((consoleCommand_t*)b)->cmd ); -} - -static consoleCommand_t commands[] = { - { "+scores", CG_ScoresDown_f }, - { "-scores", CG_ScoresUp_f }, - { "briefing", CG_SiegeBriefing_f }, - { "clientlist", CG_ClientList_f }, - { "forcenext", CG_NextForcePower_f }, - { "forceprev", CG_PrevForcePower_f }, - { "invnext", CG_NextInventory_f }, - { "invprev", CG_PrevInventory_f }, - { "loaddeferred", CG_LoadDeferredPlayers }, - { "loadhud", CG_LoadHud_f }, - { "nextframe", CG_TestModelNextFrame_f }, - { "nextskin", CG_TestModelNextSkin_f }, - { "prevframe", CG_TestModelPrevFrame_f }, - { "prevskin", CG_TestModelPrevSkin_f }, - { "siegeCompleteCvarUpdate", CG_SiegeCompleteCvarUpdate_f }, - { "siegeCvarUpdate", CG_SiegeCvarUpdate_f }, - { "sizedown", CG_SizeDown_f }, - { "sizeup", CG_SizeUp_f }, - { "startOrbit", CG_StartOrbit_f }, - { "tcmd", CG_TargetCommand_f }, - { "tell_attacker", CG_TellAttacker_f }, - { "tell_target", CG_TellTarget_f }, - { "testgun", CG_TestGun_f }, - { "testmodel", CG_TestModel_f }, - { "viewpos", CG_Viewpos_f }, - { "weapnext", CG_NextWeapon_f }, - { "weapon", CG_Weapon_f }, - { "weaponclean", CG_WeaponClean_f }, - { "weapprev", CG_PrevWeapon_f }, +int cmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((consoleCommand_t *)b)->cmd); } + +static consoleCommand_t commands[] = { + {"+scores", CG_ScoresDown_f}, + {"-scores", CG_ScoresUp_f}, + {"briefing", CG_SiegeBriefing_f}, + {"clientlist", CG_ClientList_f}, + {"forcenext", CG_NextForcePower_f}, + {"forceprev", CG_PrevForcePower_f}, + {"invnext", CG_NextInventory_f}, + {"invprev", CG_PrevInventory_f}, + {"loaddeferred", CG_LoadDeferredPlayers}, + {"loadhud", CG_LoadHud_f}, + {"nextframe", CG_TestModelNextFrame_f}, + {"nextskin", CG_TestModelNextSkin_f}, + {"prevframe", CG_TestModelPrevFrame_f}, + {"prevskin", CG_TestModelPrevSkin_f}, + {"siegeCompleteCvarUpdate", CG_SiegeCompleteCvarUpdate_f}, + {"siegeCvarUpdate", CG_SiegeCvarUpdate_f}, + {"sizedown", CG_SizeDown_f}, + {"sizeup", CG_SizeUp_f}, + {"startOrbit", CG_StartOrbit_f}, + {"tcmd", CG_TargetCommand_f}, + {"tell_attacker", CG_TellAttacker_f}, + {"tell_target", CG_TellTarget_f}, + {"testgun", CG_TestGun_f}, + {"testmodel", CG_TestModel_f}, + {"viewpos", CG_Viewpos_f}, + {"weapnext", CG_NextWeapon_f}, + {"weapon", CG_Weapon_f}, + {"weaponclean", CG_WeaponClean_f}, + {"weapprev", CG_PrevWeapon_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -334,51 +311,23 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -qboolean CG_ConsoleCommand( void ) { - consoleCommand_t *command = NULL; +qboolean CG_ConsoleCommand(void) { + consoleCommand_t *command = NULL; - command = (consoleCommand_t *)Q_LinearSearch( CG_Argv( 0 ), commands, numCommands, sizeof( commands[0] ), cmdcmp ); + command = (consoleCommand_t *)Q_LinearSearch(CG_Argv(0), commands, numCommands, sizeof(commands[0]), cmdcmp); - if ( !command || !command->func ) + if (!command || !command->func) return qfalse; command->func(); return qtrue; } -static const char *gcmds[] = { - "addbot", - "callteamvote", - "callvote", - "duelteam", - "follow", - "follownext", - "followprev", - "forcechanged", - "give", - "god", - "kill", - "levelshot", - "loaddefered", - "noclip", - "notarget", - "NPC", - "say", - "say_team", - "setviewpos", - "siegeclass", - "stats", - //"stopfollow", - "team", - "teamtask", - "teamvote", - "tell", - "voice_cmd", - "vote", - "where", - "zoom" -}; -static const size_t numgcmds = ARRAY_LEN( gcmds ); +static const char *gcmds[] = {"addbot", "callteamvote", "callvote", "duelteam", "follow", "follownext", "followprev", "forcechanged", "give", "god", "kill", + "levelshot", "loaddefered", "noclip", "notarget", "NPC", "say", "say_team", "setviewpos", "siegeclass", "stats", + //"stopfollow", + "team", "teamtask", "teamvote", "tell", "voice_cmd", "vote", "where", "zoom"}; +static const size_t numgcmds = ARRAY_LEN(gcmds); /* ================= @@ -388,16 +337,16 @@ Let the client system know about all of our commands so it can perform tab completion ================= */ -void CG_InitConsoleCommands( void ) { +void CG_InitConsoleCommands(void) { size_t i; - for ( i = 0; i < numCommands; i++ ) - trap->AddCommand( commands[i].cmd ); + for (i = 0; i < numCommands; i++) + trap->AddCommand(commands[i].cmd); // // the game server will interpret these commands, which will be automatically // forwarded to the server after they are not recognized locally // - for( i = 0; i < numgcmds; i++ ) - trap->AddCommand( gcmds[i] ); + for (i = 0; i < numgcmds; i++) + trap->AddCommand(gcmds[i]); } diff --git a/codemp/cgame/cg_cvar.c b/codemp/cgame/cg_cvar.c index 4666010135..d9b58fcea7 100644 --- a/codemp/cgame/cg_cvar.c +++ b/codemp/cgame/cg_cvar.c @@ -27,77 +27,74 @@ along with this program; if not, see . // Cvar callbacks // -static void CG_SVRunningChange( void ) { - cgs.localServer = sv_running.integer; -} +static void CG_SVRunningChange(void) { cgs.localServer = sv_running.integer; } -static void CG_ForceModelChange( void ) { +static void CG_ForceModelChange(void) { int i; - for ( i=0; i 0 && cgs.gametype >= GT_SINGLE_PLAYER) - trap->Cvar_Set( "teamoverlay", "1" ); + if (cg_drawTeamOverlay.integer > 0 && cgs.gametype >= GT_SINGLE_PLAYER) + trap->Cvar_Set("teamoverlay", "1"); else - trap->Cvar_Set( "teamoverlay", "0" ); + trap->Cvar_Set("teamoverlay", "0"); } - // // Cvar table // typedef struct cvarTable_s { - vmCvar_t *vmCvar; - char *cvarName; - char *defaultString; - void (*update)( void ); - uint32_t cvarFlags; + vmCvar_t *vmCvar; + char *cvarName; + char *defaultString; + void (*update)(void); + uint32_t cvarFlags; } cvarTable_t; #define XCVAR_DECL - #include "cg_xcvar.h" +#include "cg_xcvar.h" #undef XCVAR_DECL static const cvarTable_t cvarTable[] = { - #define XCVAR_LIST - #include "cg_xcvar.h" - #undef XCVAR_LIST +#define XCVAR_LIST +#include "cg_xcvar.h" +#undef XCVAR_LIST }; -static const size_t cvarTableSize = ARRAY_LEN( cvarTable ); +static const size_t cvarTableSize = ARRAY_LEN(cvarTable); -void CG_RegisterCvars( void ) { +void CG_RegisterCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=cvarTable; iCvar_Register( cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); - if ( cv->update ) + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + trap->Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); + if (cv->update) cv->update(); } } -void CG_UpdateCvars( void ) { +void CG_UpdateCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=cvarTable; ivmCvar ) { + for (i = 0, cv = cvarTable; i < cvarTableSize; i++, cv++) { + if (cv->vmCvar) { int modCount = cv->vmCvar->modificationCount; - trap->Cvar_Update( cv->vmCvar ); - if ( cv->vmCvar->modificationCount != modCount ) { - if ( cv->update ) + trap->Cvar_Update(cv->vmCvar); + if (cv->vmCvar->modificationCount != modCount) { + if (cv->update) cv->update(); } } diff --git a/codemp/cgame/cg_draw.c b/codemp/cgame/cg_draw.c index 8b793c1593..316b342161 100644 --- a/codemp/cgame/cg_draw.c +++ b/codemp/cgame/cg_draw.c @@ -31,23 +31,23 @@ along with this program; if not, see . #include "ui/ui_shared.h" #include "ui/ui_public.h" -extern float CG_RadiusForCent( centity_t *cent ); +extern float CG_RadiusForCent(centity_t *cent); qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y); -qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ); +qboolean CG_CalcMuzzlePoint(int entityNum, vec3_t muzzle); static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam); -static void CG_DrawSiegeDeathTimer( int timeRemaining ); +static void CG_DrawSiegeDeathTimer(int timeRemaining); // nmckenzie: DUEL_HEALTH -void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist ); +void CG_DrawDuelistHealth(float x, float y, float w, float h, int duelist); // used for scoreboard extern displayContextDef_t cgDC; int sortedTeamPlayers[TEAM_MAXOVERLAY]; -int numSortedTeamPlayers; +int numSortedTeamPlayers; int lastvalidlockdif; -extern float zoomFov; //this has to be global client-side +extern float zoomFov; // this has to be global client-side char systemChat[256]; char teamChat1[256]; @@ -57,123 +57,123 @@ char teamChat2[256]; int cg_siegeDeathTime = 0; #define MAX_HUD_TICS 4 -const char *armorTicName[MAX_HUD_TICS] = -{ -"armor_tic1", -"armor_tic2", -"armor_tic3", -"armor_tic4", -}; - -const char *healthTicName[MAX_HUD_TICS] = -{ -"health_tic1", -"health_tic2", -"health_tic3", -"health_tic4", +const char *armorTicName[MAX_HUD_TICS] = { + "armor_tic1", + "armor_tic2", + "armor_tic3", + "armor_tic4", }; -const char *forceTicName[MAX_HUD_TICS] = -{ -"force_tic1", -"force_tic2", -"force_tic3", -"force_tic4", +const char *healthTicName[MAX_HUD_TICS] = { + "health_tic1", + "health_tic2", + "health_tic3", + "health_tic4", }; -const char *ammoTicName[MAX_HUD_TICS] = -{ -"ammo_tic1", -"ammo_tic2", -"ammo_tic3", -"ammo_tic4", +const char *forceTicName[MAX_HUD_TICS] = { + "force_tic1", + "force_tic2", + "force_tic3", + "force_tic4", }; -char *showPowersName[] = -{ - "HEAL2",//FP_HEAL - "JUMP2",//FP_LEVITATION - "SPEED2",//FP_SPEED - "PUSH2",//FP_PUSH - "PULL2",//FP_PULL - "MINDTRICK2",//FP_TELEPTAHY - "GRIP2",//FP_GRIP - "LIGHTNING2",//FP_LIGHTNING - "DARK_RAGE2",//FP_RAGE - "PROTECT2",//FP_PROTECT - "ABSORB2",//FP_ABSORB - "TEAM_HEAL2",//FP_TEAM_HEAL - "TEAM_REPLENISH2",//FP_TEAM_FORCE - "DRAIN2",//FP_DRAIN - "SEEING2",//FP_SEE - "SABER_OFFENSE2",//FP_SABER_OFFENSE - "SABER_DEFENSE2",//FP_SABER_DEFENSE - "SABER_THROW2",//FP_SABERTHROW - NULL +const char *ammoTicName[MAX_HUD_TICS] = { + "ammo_tic1", + "ammo_tic2", + "ammo_tic3", + "ammo_tic4", }; -//Called from UI shared code. For now we'll just redirect to the normal anim load function. - - -int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) -{ - return BG_ParseAnimationFile(filename, animset, isHumanoid); -} - -int MenuFontToHandle(int iMenuFont) -{ - switch (iMenuFont) - { - case FONT_SMALL: return cgDC.Assets.qhSmallFont; - case FONT_SMALL2: return cgDC.Assets.qhSmall2Font; - case FONT_MEDIUM: return cgDC.Assets.qhMediumFont; - case FONT_LARGE: return cgDC.Assets.qhMediumFont;//cgDC.Assets.qhBigFont; - //fixme? Big fonr isn't registered...? +char *showPowersName[] = {"HEAL2", // FP_HEAL + "JUMP2", // FP_LEVITATION + "SPEED2", // FP_SPEED + "PUSH2", // FP_PUSH + "PULL2", // FP_PULL + "MINDTRICK2", // FP_TELEPTAHY + "GRIP2", // FP_GRIP + "LIGHTNING2", // FP_LIGHTNING + "DARK_RAGE2", // FP_RAGE + "PROTECT2", // FP_PROTECT + "ABSORB2", // FP_ABSORB + "TEAM_HEAL2", // FP_TEAM_HEAL + "TEAM_REPLENISH2", // FP_TEAM_FORCE + "DRAIN2", // FP_DRAIN + "SEEING2", // FP_SEE + "SABER_OFFENSE2", // FP_SABER_OFFENSE + "SABER_DEFENSE2", // FP_SABER_DEFENSE + "SABER_THROW2", // FP_SABERTHROW + NULL}; + +// Called from UI shared code. For now we'll just redirect to the normal anim load function. + +int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) { return BG_ParseAnimationFile(filename, animset, isHumanoid); } + +int MenuFontToHandle(int iMenuFont) { + switch (iMenuFont) { + case FONT_SMALL: + return cgDC.Assets.qhSmallFont; + case FONT_SMALL2: + return cgDC.Assets.qhSmall2Font; + case FONT_MEDIUM: + return cgDC.Assets.qhMediumFont; + case FONT_LARGE: + return cgDC.Assets.qhMediumFont; // cgDC.Assets.qhBigFont; + // fixme? Big fonr isn't registered...? } return cgDC.Assets.qhMediumFont; } - -int CG_Text_Width(const char *text, float scale, int iMenuFont) -{ +int CG_Text_Width(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap->R_Font_StrLenPixels(text, iFontIndex, scale); } -int CG_Text_Height(const char *text, float scale, int iMenuFont) -{ +int CG_Text_Height(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap->R_Font_HeightPixels(iFontIndex, scale); } -#include "qcommon/qfiles.h" // for STYLE_BLINK etc -void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont) -{ +#include "qcommon/qfiles.h" // for STYLE_BLINK etc +void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont) { int iStyleOR = 0; int iFontIndex = MenuFontToHandle(iMenuFont); - switch (style) - { - case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text - case ITEM_TEXTSTYLE_BLINK: iStyleOR = STYLE_BLINK;break; // JK2 fast blinking - case ITEM_TEXTSTYLE_PULSE: iStyleOR = STYLE_BLINK;break; // JK2 slow pulsing - case ITEM_TEXTSTYLE_SHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_OUTLINED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_OUTLINESHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - case ITEM_TEXTSTYLE_SHADOWEDMORE: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this ) - } - - trap->R_Font_DrawString( x, // int ox - y, // int oy - text, // const char *text - color, // paletteRGBA_c c - iStyleOR | iFontIndex, // const int iFontHandle - !limit?-1:limit, // iCharLimit (-1 = none) - scale // const float scale = 1.0f - ); + switch (style) { + case ITEM_TEXTSTYLE_NORMAL: + iStyleOR = 0; + break; // JK2 normal text + case ITEM_TEXTSTYLE_BLINK: + iStyleOR = STYLE_BLINK; + break; // JK2 fast blinking + case ITEM_TEXTSTYLE_PULSE: + iStyleOR = STYLE_BLINK; + break; // JK2 slow pulsing + case ITEM_TEXTSTYLE_SHADOWED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_OUTLINED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_OUTLINESHADOWED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + case ITEM_TEXTSTYLE_SHADOWEDMORE: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow ( need a color for this ) + } + + trap->R_Font_DrawString(x, // int ox + y, // int oy + text, // const char *text + color, // paletteRGBA_c c + iStyleOR | iFontIndex, // const int iFontHandle + !limit ? -1 : limit, // iCharLimit (-1 = none) + scale // const float scale = 1.0f + ); } /* @@ -182,20 +182,18 @@ CG_DrawZoomMask ================ */ -static void CG_DrawZoomMask( void ) -{ - vec4_t color1; - float level; - static qboolean flip = qtrue; +static void CG_DrawZoomMask(void) { + vec4_t color1; + float level; + static qboolean flip = qtrue; -// int ammo = cg_entities[0].gent->client->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; + // int ammo = cg_entities[0].gent->client->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]; float cx, cy; -// int val[5]; + // int val[5]; float max, fi; // Check for Binocular specific zooming since we'll want to render different bits in each case - if ( cg.predictedPlayerState.zoomMode == 2 ) - { + if (cg.predictedPlayerState.zoomMode == 2) { int val, i; float off; @@ -203,12 +201,9 @@ static void CG_DrawZoomMask( void ) level = (float)(80.0f - cg.predictedPlayerState.zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } @@ -216,94 +211,82 @@ static void CG_DrawZoomMask( void ) level *= 162.0f; // draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic ); + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(34, 48, 570, 362, cgs.media.binocularStatic); // Black out the area behind the numbers - trap->R_SetColor( colorTable[CT_BLACK]); - CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader ); + trap->R_SetColor(colorTable[CT_BLACK]); + CG_DrawPic(212, 367, 200, 40, cgs.media.whiteShader); // Numbers should be kind of greenish color1[0] = 0.2f; color1[1] = 0.4f; color1[2] = 0.2f; color1[3] = 0.3f; - trap->R_SetColor( color1 ); + trap->R_SetColor(color1); // Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked // up with a bunch of magic numbers..... val = ((int)((cg.refdef.viewangles[YAW] + 180) / 10)) * 10; off = (cg.refdef.viewangles[YAW] + 180) - val; - for ( i = -10; i < 30; i += 10 ) - { + for (i = -10; i < 30; i += 10) { val -= 10; - if ( val < 0 ) - { + if (val < 0) { val += 360; } // we only want to draw the very far left one some of the time, if it's too far to the left it will // poke outside the mask. - if (( off > 3.0f && i == -10 ) || i > -10 ) - { + if ((off > 3.0f && i == -10) || i > -10) { // draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like - CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue ); - CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader ); + CG_DrawNumField(155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue); + CG_DrawPic(245 + (i - 1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader); } } - CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay ); + CG_DrawPic(212, 367, 200, 28, cgs.media.binocularOverlay); - color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f; + color1[0] = sin(cg.time * 0.01f) * 0.5f + 0.5f; color1[0] = color1[0] * color1[0]; color1[1] = color1[0]; color1[2] = color1[0]; color1[3] = 1.0f; - trap->R_SetColor( color1 ); + trap->R_SetColor(color1); - CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle ); + CG_DrawPic(82, 94, 16, 16, cgs.media.binocularCircle); // Flickery color color1[0] = 0.7f + Q_flrand(-0.1f, 0.1f); color1[1] = 0.8f + Q_flrand(-0.1f, 0.1f); color1[2] = 0.7f + Q_flrand(-0.1f, 0.1f); color1[3] = 1.0f; - trap->R_SetColor( color1 ); + trap->R_SetColor(color1); - CG_DrawPic( 0, 0, 640, 480, cgs.media.binocularMask ); + CG_DrawPic(0, 0, 640, 480, cgs.media.binocularMask); - CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow ); + CG_DrawPic(4, 282 - level, 16, 16, cgs.media.binocularArrow); // The top triangle bit randomly flips - if ( flip ) - { - CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri ); - } - else - { - CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri ); + if (flip) { + CG_DrawPic(330, 60, -26, -30, cgs.media.binocularTri); + } else { + CG_DrawPic(307, 40, 26, 30, cgs.media.binocularTri); } - if ( Q_flrand(0.0f, 1.0f) > 0.98f && ( cg.time & 1024 )) - { + if (Q_flrand(0.0f, 1.0f) > 0.98f && (cg.time & 1024)) { flip = !flip; } - } - else if ( cg.predictedPlayerState.zoomMode) - { + } else if (cg.predictedPlayerState.zoomMode) { // disruptor zoom mode - level = (float)(50.0f - zoomFov) / 50.0f;//(float)(80.0f - zoomFov) / 80.0f; + level = (float)(50.0f - zoomFov) / 50.0f; //(float)(80.0f - zoomFov) / 80.0f; // ...so we'll clamp it - if ( level < 0.0f ) - { + if (level < 0.0f) { level = 0.0f; - } - else if ( level > 1.0f ) - { + } else if (level > 1.0f) { level = 1.0f; } @@ -311,61 +294,55 @@ static void CG_DrawZoomMask( void ) level *= 103.0f; // Draw target mask - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(0, 0, 640, 480, cgs.media.disruptorMask); // apparently 99.0f is the full zoom level - if ( level >= 99 ) - { + if (level >= 99) { // Fully zoomed, so make the rotating insert pulse color1[0] = 1.0f; color1[1] = 1.0f; color1[2] = 1.0f; - color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f; + color1[3] = 0.7f + sin(cg.time * 0.01f) * 0.3f; - trap->R_SetColor( color1 ); + trap->R_SetColor(color1); } // Draw rotating insert - CG_DrawRotatePic2( 320, 240, 640, 480, -level, cgs.media.disruptorInsert ); + CG_DrawRotatePic2(320, 240, 640, 480, -level, cgs.media.disruptorInsert); // Increase the light levels under the center of the target -// CG_DrawPic( 198, 118, 246, 246, cgs.media.disruptorLight ); + // CG_DrawPic( 198, 118, 246, 246, cgs.media.disruptorLight ); // weirdness.....converting ammo to a base five number scale just to be geeky. -/* val[0] = ammo % 5; - val[1] = (ammo / 5) % 5; - val[2] = (ammo / 25) % 5; - val[3] = (ammo / 125) % 5; - val[4] = (ammo / 625) % 5; - - color1[0] = 0.2f; - color1[1] = 0.55f + Q_flrand(-1.0f, 1.0f) * 0.1f; - color1[2] = 0.5f + Q_flrand(-1.0f, 1.0f) * 0.1f; - color1[3] = 1.0f; - trap->R_SetColor( color1 ); - - for ( int t = 0; t < 5; t++ ) - { - cx = 320 + sin( (t*10+45)/57.296f ) * 192; - cy = 240 + cos( (t*10+45)/57.296f ) * 192; - - CG_DrawRotatePic2( cx, cy, 24, 38, 45 - t * 10, trap->R_RegisterShader( va("gfx/2d/char%d",val[4-t] ))); - } -*/ - //max = ( cg_entities[0].gent->health / 100.0f ); + /* val[0] = ammo % 5; + val[1] = (ammo / 5) % 5; + val[2] = (ammo / 25) % 5; + val[3] = (ammo / 125) % 5; + val[4] = (ammo / 625) % 5; + + color1[0] = 0.2f; + color1[1] = 0.55f + Q_flrand(-1.0f, 1.0f) * 0.1f; + color1[2] = 0.5f + Q_flrand(-1.0f, 1.0f) * 0.1f; + color1[3] = 1.0f; + trap->R_SetColor( color1 ); + + for ( int t = 0; t < 5; t++ ) + { + cx = 320 + sin( (t*10+45)/57.296f ) * 192; + cy = 240 + cos( (t*10+45)/57.296f ) * 192; + CG_DrawRotatePic2( cx, cy, 24, 38, 45 - t * 10, trap->R_RegisterShader( va("gfx/2d/char%d",val[4-t] ))); + } + */ + // max = ( cg_entities[0].gent->health / 100.0f ); - if ( (cg.snap->ps.eFlags & EF_DOUBLE_AMMO) ) - { - max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / ((float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max*2.0f); - } - else - { + if ((cg.snap->ps.eFlags & EF_DOUBLE_AMMO)) { + max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / ((float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max * 2.0f); + } else { max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max; } - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } @@ -375,82 +352,76 @@ static void CG_DrawZoomMask( void ) color1[3] = 1.0f; // If we are low on health, make us flash - if ( max < 0.15f && ( cg.time & 512 )) - { - VectorClear( color1 ); + if (max < 0.15f && (cg.time & 512)) { + VectorClear(color1); } - if ( color1[0] > 1.0f ) - { + if (color1[0] > 1.0f) { color1[0] = 1.0f; } - if ( color1[1] > 1.0f ) - { + if (color1[1] > 1.0f) { color1[1] = 1.0f; } - trap->R_SetColor( color1 ); + trap->R_SetColor(color1); max *= 58.0f; - for (fi = 18.5f; fi <= 18.5f + max; fi+= 3 ) // going from 15 to 45 degrees, with 5 degree increments + for (fi = 18.5f; fi <= 18.5f + max; fi += 3) // going from 15 to 45 degrees, with 5 degree increments { - cx = 320 + sin( (fi+90.0f)/57.296f ) * 190; - cy = 240 + cos( (fi+90.0f)/57.296f ) * 190; + cx = 320 + sin((fi + 90.0f) / 57.296f) * 190; + cy = 240 + cos((fi + 90.0f) / 57.296f) * 190; - CG_DrawRotatePic2( cx, cy, 12, 24, 90 - fi, cgs.media.disruptorInsertTick ); + CG_DrawRotatePic2(cx, cy, 12, 24, 90 - fi, cgs.media.disruptorInsertTick); } - if ( cg.predictedPlayerState.weaponstate == WEAPON_CHARGING_ALT ) - { - trap->R_SetColor( colorTable[CT_WHITE] ); + if (cg.predictedPlayerState.weaponstate == WEAPON_CHARGING_ALT) { + trap->R_SetColor(colorTable[CT_WHITE]); // draw the charge level - max = ( cg.time - cg.predictedPlayerState.weaponChargeTime ) / ( 50.0f * 30.0f ); // bad hardcodedness 50 is disruptor charge unit and 30 is max charge units allowed. + max = (cg.time - cg.predictedPlayerState.weaponChargeTime) / + (50.0f * 30.0f); // bad hardcodedness 50 is disruptor charge unit and 30 is max charge units allowed. - if ( max > 1.0f ) - { + if (max > 1.0f) { max = 1.0f; } - trap->R_DrawStretchPic(257, 435, 134*max, 34, 0, 0, max, 1, cgs.media.disruptorChargeShader); + trap->R_DrawStretchPic(257, 435, 134 * max, 34, 0, 0, max, 1, cgs.media.disruptorChargeShader); } -// trap->R_SetColor( colorTable[CT_WHITE] ); -// CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); - + // trap->R_SetColor( colorTable[CT_WHITE] ); + // CG_DrawPic( 0, 0, 640, 480, cgs.media.disruptorMask ); } } - /* ================ CG_Draw3DModel ================ */ -void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, void *ghoul2, int g2radius, qhandle_t skin, vec3_t origin, vec3_t angles ) { - refdef_t refdef; - refEntity_t ent; +void CG_Draw3DModel(float x, float y, float w, float h, qhandle_t model, void *ghoul2, int g2radius, qhandle_t skin, vec3_t origin, vec3_t angles) { + refdef_t refdef; + refEntity_t ent; - if ( !cg_draw3DIcons.integer || !cg_drawIcons.integer ) { + if (!cg_draw3DIcons.integer || !cg_drawIcons.integer) { return; } - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); - memset( &ent, 0, sizeof( ent ) ); - AnglesToAxis( angles, ent.axis ); - VectorCopy( origin, ent.origin ); + memset(&ent, 0, sizeof(ent)); + AnglesToAxis(angles, ent.axis); + VectorCopy(origin, ent.origin); ent.hModel = model; ent.ghoul2 = ghoul2; ent.radius = g2radius; ent.customSkin = skin; - ent.renderfx = RF_NOSHADOW; // no stencil shadows + ent.renderfx = RF_NOSHADOW; // no stencil shadows refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); + AxisClear(refdef.viewaxis); refdef.fov_x = 30; refdef.fov_y = 30; @@ -463,8 +434,8 @@ void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, void * refdef.time = cg.time; trap->R_ClearScene(); - trap->R_AddRefEntityToScene( &ent ); - trap->R_RenderScene( &refdef ); + trap->R_AddRefEntityToScene(&ent); + trap->R_RenderScene(&refdef); } /* @@ -474,23 +445,20 @@ CG_DrawHead Used for both the status bar and the scoreboard ================ */ -void CG_DrawHead( float x, float y, float w, float h, int clientNum, vec3_t headAngles ) -{ - clientInfo_t *ci; +void CG_DrawHead(float x, float y, float w, float h, int clientNum, vec3_t headAngles) { + clientInfo_t *ci; - if (clientNum >= MAX_CLIENTS) - { //npc? + if (clientNum >= MAX_CLIENTS) { // npc? return; } - ci = &cgs.clientinfo[ clientNum ]; + ci = &cgs.clientinfo[clientNum]; - CG_DrawPic( x, y, w, h, ci->modelIcon ); + CG_DrawPic(x, y, w, h, ci->modelIcon); // if they are deferred, draw a cross out - if ( ci->deferred ) - { - CG_DrawPic( x, y, w, h, cgs.media.deferShader ); + if (ci->deferred) { + CG_DrawPic(x, y, w, h, cgs.media.deferShader); } } @@ -501,60 +469,61 @@ CG_DrawFlagModel Used for both the status bar and the scoreboard ================ */ -void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean force2D ) { - qhandle_t cm; - float len; - vec3_t origin, angles; - vec3_t mins, maxs; - qhandle_t handle; - - if ( !force2D && cg_draw3DIcons.integer ) { +void CG_DrawFlagModel(float x, float y, float w, float h, int team, qboolean force2D) { + qhandle_t cm; + float len; + vec3_t origin, angles; + vec3_t mins, maxs; + qhandle_t handle; + + if (!force2D && cg_draw3DIcons.integer) { x *= cgs.screenXScale; y *= cgs.screenYScale; w *= cgs.screenXScale; h *= cgs.screenYScale; - VectorClear( angles ); + VectorClear(angles); cm = cgs.media.redFlagModel; // offset the origin y and z to center the flag - trap->R_ModelBounds( cm, mins, maxs ); + trap->R_ModelBounds(cm, mins, maxs); - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); // calculate distance so the flag nearly fills the box // assume heads are taller than wide - len = 0.5 * ( maxs[2] - mins[2] ); - origin[0] = len / 0.268; // len / tan( fov/2 ) + len = 0.5 * (maxs[2] - mins[2]); + origin[0] = len / 0.268; // len / tan( fov/2 ) - angles[YAW] = 60 * sin( cg.time / 2000.0 );; + angles[YAW] = 60 * sin(cg.time / 2000.0); + ; - if( team == TEAM_RED ) { + if (team == TEAM_RED) { handle = cgs.media.redFlagModel; - } else if( team == TEAM_BLUE ) { + } else if (team == TEAM_BLUE) { handle = cgs.media.blueFlagModel; - } else if( team == TEAM_FREE ) { - handle = 0;//cgs.media.neutralFlagModel; + } else if (team == TEAM_FREE) { + handle = 0; // cgs.media.neutralFlagModel; } else { return; } - CG_Draw3DModel( x, y, w, h, handle, NULL, 0, 0, origin, angles ); - } else if ( cg_drawIcons.integer ) { + CG_Draw3DModel(x, y, w, h, handle, NULL, 0, 0, origin, angles); + } else if (cg_drawIcons.integer) { gitem_t *item; - if( team == TEAM_RED ) { - item = BG_FindItemForPowerup( PW_REDFLAG ); - } else if( team == TEAM_BLUE ) { - item = BG_FindItemForPowerup( PW_BLUEFLAG ); - } else if( team == TEAM_FREE ) { - item = BG_FindItemForPowerup( PW_NEUTRALFLAG ); + if (team == TEAM_RED) { + item = BG_FindItemForPowerup(PW_REDFLAG); + } else if (team == TEAM_BLUE) { + item = BG_FindItemForPowerup(PW_BLUEFLAG); + } else if (team == TEAM_FREE) { + item = BG_FindItemForPowerup(PW_NEUTRALFLAG); } else { return; } if (item) { - CG_DrawPic( x, y, w, h, cg_items[ ITEM_INDEX(item) ].icon ); + CG_DrawPic(x, y, w, h, cg_items[ITEM_INDEX(item)].icon); } } } @@ -564,18 +533,16 @@ void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean fo CG_DrawHealth ================ */ -void CG_DrawHealth( menuDef_t *menuHUD ) -{ - vec4_t calcColor; - playerState_t *ps; - int healthAmt; - int i,currValue,inc; - itemDef_t *focusItem; +void CG_DrawHealth(menuDef_t *menuHUD) { + vec4_t calcColor; + playerState_t *ps; + int healthAmt; + int i, currValue, inc; + itemDef_t *focusItem; float percent; // Can we find the menu? - if (!menuHUD) - { + if (!menuHUD) { return; } @@ -583,68 +550,49 @@ void CG_DrawHealth( menuDef_t *menuHUD ) // What's the health? healthAmt = ps->stats[STAT_HEALTH]; - if (healthAmt > ps->stats[STAT_MAX_HEALTH]) - { + if (healthAmt > ps->stats[STAT_MAX_HEALTH]) { healthAmt = ps->stats[STAT_MAX_HEALTH]; } - - inc = (float) ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; + inc = (float)ps->stats[STAT_MAX_HEALTH] / MAX_HUD_TICS; currValue = healthAmt; // Print the health tics, fading out the one which is partial health - for (i=(MAX_HUD_TICS-1);i>=0;i--) - { + for (i = (MAX_HUD_TICS - 1); i >= 0; i--) { focusItem = Menu_FindItemByName(menuHUD, healthTicName[i]); - if (!focusItem) // This is bad + if (!focusItem) // This is bad { continue; } memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { - percent = (float) currValue / inc; - calcColor[3] *= percent; // Fade it out + percent = (float)currValue / inc; + calcColor[3] *= percent; // Fade it out } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); currValue -= inc; } // Print the mueric amount focusItem = Menu_FindItemByName(menuHUD, "healthamount"); - if (focusItem) - { + if (focusItem) { // Print health amount - trap->R_SetColor( focusItem->window.foreColor ); + trap->R_SetColor(focusItem->window.foreColor); - CG_DrawNumField ( - focusItem->window.rect.x, - focusItem->window.rect.y, - 3, - ps->stats[STAT_HEALTH], - focusItem->window.rect.w, - focusItem->window.rect.h, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(focusItem->window.rect.x, focusItem->window.rect.y, 3, ps->stats[STAT_HEALTH], focusItem->window.rect.w, focusItem->window.rect.h, + NUM_FONT_SMALL, qfalse); } - } /* @@ -652,75 +600,56 @@ void CG_DrawHealth( menuDef_t *menuHUD ) CG_DrawArmor ================ */ -void CG_DrawArmor( menuDef_t *menuHUD ) -{ - vec4_t calcColor; - playerState_t *ps; - int maxArmor; - itemDef_t *focusItem; - float percent,quarterArmor; - int i,currValue,inc; - - //ps = &cg.snap->ps; +void CG_DrawArmor(menuDef_t *menuHUD) { + vec4_t calcColor; + playerState_t *ps; + int maxArmor; + itemDef_t *focusItem; + float percent, quarterArmor; + int i, currValue, inc; + + // ps = &cg.snap->ps; ps = &cg.predictedPlayerState; // Can we find the menu? - if (!menuHUD) - { + if (!menuHUD) { return; } maxArmor = ps->stats[STAT_MAX_HEALTH]; currValue = ps->stats[STAT_ARMOR]; - inc = (float) maxArmor / MAX_HUD_TICS; + inc = (float)maxArmor / MAX_HUD_TICS; memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - for (i=(MAX_HUD_TICS-1);i>=0;i--) - { + for (i = (MAX_HUD_TICS - 1); i >= 0; i--) { focusItem = Menu_FindItemByName(menuHUD, armorTicName[i]); - if (!focusItem) // This is bad + if (!focusItem) // This is bad { continue; } memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { - percent = (float) currValue / inc; + percent = (float)currValue / inc; calcColor[3] *= percent; } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - if ((i==(MAX_HUD_TICS-1)) && (currValue < inc)) - { - if (cg.HUDArmorFlag) - { - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + if ((i == (MAX_HUD_TICS - 1)) && (currValue < inc)) { + if (cg.HUDArmorFlag) { + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, + focusItem->window.background); } - } - else - { - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + } else { + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); } currValue -= inc; @@ -728,53 +657,38 @@ void CG_DrawArmor( menuDef_t *menuHUD ) focusItem = Menu_FindItemByName(menuHUD, "armoramount"); - if (focusItem) - { + if (focusItem) { // Print armor amount - trap->R_SetColor( focusItem->window.foreColor ); + trap->R_SetColor(focusItem->window.foreColor); - CG_DrawNumField ( - focusItem->window.rect.x, - focusItem->window.rect.y, - 3, - ps->stats[STAT_ARMOR], - focusItem->window.rect.w, - focusItem->window.rect.h, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(focusItem->window.rect.x, focusItem->window.rect.y, 3, ps->stats[STAT_ARMOR], focusItem->window.rect.w, focusItem->window.rect.h, + NUM_FONT_SMALL, qfalse); } // If armor is low, flash a graphic to warn the player - if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC + if (ps->stats[STAT_ARMOR]) // Is there armor? Draw the HUD Armor TIC { - quarterArmor = (float) (ps->stats[STAT_MAX_HEALTH] / 4.0f); + quarterArmor = (float)(ps->stats[STAT_MAX_HEALTH] / 4.0f); // Make tic flash if armor is at 25% of full armor - if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says + if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says { - if (cg.HUDTickFlashTime < cg.time) // Flip at the same time + if (cg.HUDTickFlashTime < cg.time) // Flip at the same time { cg.HUDTickFlashTime = cg.time + 400; - if (cg.HUDArmorFlag) - { + if (cg.HUDArmorFlag) { cg.HUDArmorFlag = qfalse; - } - else - { + } else { cg.HUDArmorFlag = qtrue; } } + } else { + cg.HUDArmorFlag = qtrue; } - else - { - cg.HUDArmorFlag=qtrue; - } - } - else // No armor? Don't show it. + } else // No armor? Don't show it. { - cg.HUDArmorFlag=qfalse; + cg.HUDArmorFlag = qfalse; } - } /* @@ -785,86 +699,59 @@ If the weapon is a light saber (which needs no ammo) then draw a graphic showing the saber style (fast, medium, strong) ================ */ -static void CG_DrawSaberStyle( centity_t *cent, menuDef_t *menuHUD) -{ - itemDef_t *focusItem; +static void CG_DrawSaberStyle(centity_t *cent, menuDef_t *menuHUD) { + itemDef_t *focusItem; - if (!cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon != WP_SABER ) - { + if (cent->currentState.weapon != WP_SABER) { return; } // Can we find the menu? - if (!menuHUD) - { + if (!menuHUD) { return; } - // draw the current saber style in this window - switch ( cg.predictedPlayerState.fd.saberDrawAnimLevel ) - { - case 1://FORCE_LEVEL_1: - case 5://FORCE_LEVEL_5://Tavion + switch (cg.predictedPlayerState.fd.saberDrawAnimLevel) { + case 1: // FORCE_LEVEL_1: + case 5: // FORCE_LEVEL_5://Tavion focusItem = Menu_FindItemByName(menuHUD, "saberstyle_fast"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); } break; - case 2://FORCE_LEVEL_2: - case 6://SS_DUAL - case 7://SS_STAFF + case 2: // FORCE_LEVEL_2: + case 6: // SS_DUAL + case 7: // SS_STAFF focusItem = Menu_FindItemByName(menuHUD, "saberstyle_medium"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); } break; - case 3://FORCE_LEVEL_3: - case 4://FORCE_LEVEL_4://Desann + case 3: // FORCE_LEVEL_3: + case 4: // FORCE_LEVEL_4://Desann focusItem = Menu_FindItemByName(menuHUD, "saberstyle_strong"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); } break; } - } /* @@ -872,29 +759,27 @@ static void CG_DrawSaberStyle( centity_t *cent, menuDef_t *menuHUD) CG_DrawAmmo ================ */ -static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD) -{ - playerState_t *ps; - int i; - vec4_t calcColor; - float value=0.0f,inc = 0.0f,percent; - itemDef_t *focusItem; +static void CG_DrawAmmo(centity_t *cent, menuDef_t *menuHUD) { + playerState_t *ps; + int i; + vec4_t calcColor; + float value = 0.0f, inc = 0.0f, percent; + itemDef_t *focusItem; ps = &cg.snap->ps; // Can we find the menu? - if (!menuHUD) - { + if (!menuHUD) { return; } - if (!cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; - if (value < 0) // No ammo + if (value < 0) // No ammo { return; } @@ -902,8 +787,7 @@ static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD) // // ammo // - if (cg.oldammo < value) - { + if (cg.oldammo < value) { cg.oldAmmoTime = cg.time + 200; } @@ -911,112 +795,75 @@ static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD) focusItem = Menu_FindItemByName(menuHUD, "ammoamount"); - if (weaponData[cent->currentState.weapon].energyPerShot == 0 && - weaponData[cent->currentState.weapon].altEnergyPerShot == 0) - { //just draw "infinite" + if (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0) { // just draw "infinite" inc = 8 / MAX_HUD_TICS; value = 8; focusItem = Menu_FindItemByName(menuHUD, "ammoinfinite"); - trap->R_SetColor( colorTable[CT_YELLOW] ); - if (focusItem) - { + trap->R_SetColor(colorTable[CT_YELLOW]); + if (focusItem) { CG_DrawProportionalString(focusItem->window.rect.x, focusItem->window.rect.y, "--", NUM_FONT_SMALL, focusItem->window.foreColor); } - } - else - { + } else { focusItem = Menu_FindItemByName(menuHUD, "ammoamount"); // Firing or reloading? - if (( cg.predictedPlayerState.weaponstate == WEAPON_FIRING - && cg.predictedPlayerState.weaponTime > 100 )) - { + if ((cg.predictedPlayerState.weaponstate == WEAPON_FIRING && cg.predictedPlayerState.weaponTime > 100)) { memcpy(calcColor, colorTable[CT_LTGREY], sizeof(vec4_t)); - } - else - { - if ( value > 0 ) - { - if (cg.oldAmmoTime > cg.time) - { + } else { + if (value > 0) { + if (cg.oldAmmoTime > cg.time) { memcpy(calcColor, colorTable[CT_YELLOW], sizeof(vec4_t)); - } - else - { + } else { memcpy(calcColor, focusItem->window.foreColor, sizeof(vec4_t)); } - } - else - { + } else { memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); } } + trap->R_SetColor(calcColor); + if (focusItem) { - trap->R_SetColor( calcColor ); - if (focusItem) - { - - if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) ) - { - inc = (float) (ammoData[weaponData[cent->currentState.weapon].ammoIndex].max*2.0f) / MAX_HUD_TICS; - } - else - { - inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; + if ((cent->currentState.eFlags & EF_DOUBLE_AMMO)) { + inc = (float)(ammoData[weaponData[cent->currentState.weapon].ammoIndex].max * 2.0f) / MAX_HUD_TICS; + } else { + inc = (float)ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS; } - value =ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; + value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; - CG_DrawNumField ( - focusItem->window.rect.x, - focusItem->window.rect.y, - 3, - value, - focusItem->window.rect.w, - focusItem->window.rect.h, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(focusItem->window.rect.x, focusItem->window.rect.y, 3, value, focusItem->window.rect.w, focusItem->window.rect.h, NUM_FONT_SMALL, + qfalse); } } - trap->R_SetColor( colorTable[CT_WHITE] ); + trap->R_SetColor(colorTable[CT_WHITE]); // Draw tics - for (i=MAX_HUD_TICS-1;i>=0;i--) - { + for (i = MAX_HUD_TICS - 1; i >= 0; i--) { focusItem = Menu_FindItemByName(menuHUD, ammoTicName[i]); - if (!focusItem) - { + if (!focusItem) { continue; } memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - if ( value <= 0 ) // done + if (value <= 0) // done { break; - } - else if (value < inc) // partial tic + } else if (value < inc) // partial tic { percent = value / inc; calcColor[3] = percent; } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); value -= inc; } - } /* @@ -1024,196 +871,155 @@ static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD) CG_DrawForcePower ================ */ -void CG_DrawForcePower( menuDef_t *menuHUD ) -{ - int i; - vec4_t calcColor; - float value,inc,percent; - itemDef_t *focusItem; - const int maxForcePower = 100; - qboolean flash=qfalse; +void CG_DrawForcePower(menuDef_t *menuHUD) { + int i; + vec4_t calcColor; + float value, inc, percent; + itemDef_t *focusItem; + const int maxForcePower = 100; + qboolean flash = qfalse; // Can we find the menu? - if (!menuHUD) - { + if (!menuHUD) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time - if (cg.forceHUDTotalFlashTime > cg.time ) - { + if (cg.forceHUDTotalFlashTime > cg.time) { flash = qtrue; - if (cg.forceHUDNextFlashTime < cg.time) - { + if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; - trap->S_StartSound (NULL, 0, CHAN_LOCAL, cgs.media.noforceSound ); + trap->S_StartSound(NULL, 0, CHAN_LOCAL, cgs.media.noforceSound); - if (cg.forceHUDActive) - { + if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; - } - else - { + } else { cg.forceHUDActive = qtrue; } - } - } - else // turn HUD back on if it had just finished flashing time. + } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; } -// if (!cg.forceHUDActive) -// { -// return; -// } + // if (!cg.forceHUDActive) + // { + // return; + // } - inc = (float) maxForcePower / MAX_HUD_TICS; + inc = (float)maxForcePower / MAX_HUD_TICS; value = cg.snap->ps.fd.forcePower; - for (i=MAX_HUD_TICS-1;i>=0;i--) - { + for (i = MAX_HUD_TICS - 1; i >= 0; i--) { focusItem = Menu_FindItemByName(menuHUD, forceTicName[i]); - if (!focusItem) - { + if (!focusItem) { continue; } -// memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + // memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); - if ( value <= 0 ) // done + if (value <= 0) // done { break; - } - else if (value < inc) // partial tic + } else if (value < inc) // partial tic { - if (flash) - { - memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); - } - else - { - memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + if (flash) { + memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); + } else { + memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } percent = value / inc; calcColor[3] = percent; - } - else - { - if (flash) - { - memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); - } - else - { - memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + } else { + if (flash) { + memcpy(calcColor, colorTable[CT_RED], sizeof(vec4_t)); + } else { + memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); } } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, focusItem->window.background); value -= inc; } focusItem = Menu_FindItemByName(menuHUD, "forceamount"); - if (focusItem) - { + if (focusItem) { // Print force amount - if ( flash ) - { - trap->R_SetColor( colorTable[CT_RED] ); - } - else - { - trap->R_SetColor( focusItem->window.foreColor ); + if (flash) { + trap->R_SetColor(colorTable[CT_RED]); + } else { + trap->R_SetColor(focusItem->window.foreColor); } - CG_DrawNumField ( - focusItem->window.rect.x, - focusItem->window.rect.y, - 3, - cg.snap->ps.fd.forcePower, - focusItem->window.rect.w, - focusItem->window.rect.h, - NUM_FONT_SMALL, - qfalse); + CG_DrawNumField(focusItem->window.rect.x, focusItem->window.rect.y, 3, cg.snap->ps.fd.forcePower, focusItem->window.rect.w, focusItem->window.rect.h, + NUM_FONT_SMALL, qfalse); } } -static void CG_DrawSimpleSaberStyle( const centity_t *cent ) -{ - uint32_t calcColor; - char num[7] = { 0 }; - int weapX = 16; +static void CG_DrawSimpleSaberStyle(const centity_t *cent) { + uint32_t calcColor; + char num[7] = {0}; + int weapX = 16; - if ( !cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } - if ( cent->currentState.weapon != WP_SABER ) - { + if (cent->currentState.weapon != WP_SABER) { return; } - switch ( cg.predictedPlayerState.fd.saberDrawAnimLevel ) - { + switch (cg.predictedPlayerState.fd.saberDrawAnimLevel) { default: case SS_FAST: - Com_sprintf( num, sizeof( num ), "FAST" ); + Com_sprintf(num, sizeof(num), "FAST"); calcColor = CT_ICON_BLUE; weapX = 0; break; case SS_MEDIUM: - Com_sprintf( num, sizeof( num ), "MEDIUM" ); + Com_sprintf(num, sizeof(num), "MEDIUM"); calcColor = CT_YELLOW; break; case SS_STRONG: - Com_sprintf( num, sizeof( num ), "STRONG" ); + Com_sprintf(num, sizeof(num), "STRONG"); calcColor = CT_HUD_RED; break; case SS_DESANN: - Com_sprintf( num, sizeof( num ), "DESANN" ); + Com_sprintf(num, sizeof(num), "DESANN"); calcColor = CT_HUD_RED; break; case SS_TAVION: - Com_sprintf( num, sizeof( num ), "TAVION" ); + Com_sprintf(num, sizeof(num), "TAVION"); calcColor = CT_ICON_BLUE; break; case SS_DUAL: - Com_sprintf( num, sizeof( num ), "AKIMBO" ); + Com_sprintf(num, sizeof(num), "AKIMBO"); calcColor = CT_HUD_ORANGE; break; case SS_STAFF: - Com_sprintf( num, sizeof( num ), "STAFF" ); + Com_sprintf(num, sizeof(num), "STAFF"); calcColor = CT_HUD_ORANGE; break; } - CG_DrawProportionalString( SCREEN_WIDTH - (weapX + 16 + 32), (SCREEN_HEIGHT - 80) + 40, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor] ); + CG_DrawProportionalString(SCREEN_WIDTH - (weapX + 16 + 32), (SCREEN_HEIGHT - 80) + 40, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor]); } -static void CG_DrawSimpleAmmo( const centity_t *cent ) -{ - playerState_t *ps; - uint32_t calcColor; - int currValue = 0; - char num[16] = { 0 }; +static void CG_DrawSimpleAmmo(const centity_t *cent) { + playerState_t *ps; + uint32_t calcColor; + int currValue = 0; + char num[16] = {0}; - if ( !cent->currentState.weapon ) // We don't have a weapon right now + if (!cent->currentState.weapon) // We don't have a weapon right now { return; } @@ -1223,17 +1029,15 @@ static void CG_DrawSimpleAmmo( const centity_t *cent ) currValue = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; // No ammo - if ( currValue < 0 || (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0) ) - { - CG_DrawProportionalString( SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, "--", UI_SMALLFONT | UI_DROPSHADOW, colorTable[CT_HUD_ORANGE] ); + if (currValue < 0 || (weaponData[cent->currentState.weapon].energyPerShot == 0 && weaponData[cent->currentState.weapon].altEnergyPerShot == 0)) { + CG_DrawProportionalString(SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, "--", UI_SMALLFONT | UI_DROPSHADOW, colorTable[CT_HUD_ORANGE]); return; } // // ammo // - if ( cg.oldammo < currValue ) - { + if (cg.oldammo < currValue) { cg.oldAmmoTime = cg.time + 200; } @@ -1242,66 +1046,47 @@ static void CG_DrawSimpleAmmo( const centity_t *cent ) // Determine the color of the numeric field // Firing or reloading? - if ( (cg.predictedPlayerState.weaponstate == WEAPON_FIRING - && cg.predictedPlayerState.weaponTime > 100) ) - { + if ((cg.predictedPlayerState.weaponstate == WEAPON_FIRING && cg.predictedPlayerState.weaponTime > 100)) { calcColor = CT_LTGREY; - } - else - { - if ( currValue > 0 ) - { - if ( cg.oldAmmoTime > cg.time ) - { + } else { + if (currValue > 0) { + if (cg.oldAmmoTime > cg.time) { calcColor = CT_YELLOW; - } - else - { + } else { calcColor = CT_HUD_ORANGE; } - } - else - { + } else { calcColor = CT_RED; } } - Com_sprintf( num, sizeof( num ), "%i", currValue ); + Com_sprintf(num, sizeof(num), "%i", currValue); - CG_DrawProportionalString( SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor] ); + CG_DrawProportionalString(SCREEN_WIDTH - (16 + 32), (SCREEN_HEIGHT - 80) + 40, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor]); } -static void CG_DrawSimpleForcePower( const centity_t *cent ) -{ - uint32_t calcColor; - char num[16] = { 0 }; - qboolean flash = qfalse; +static void CG_DrawSimpleForcePower(const centity_t *cent) { + uint32_t calcColor; + char num[16] = {0}; + qboolean flash = qfalse; - if ( !cg.snap->ps.fd.forcePowersKnown ) - { + if (!cg.snap->ps.fd.forcePowersKnown) { return; } // Make the hud flash by setting forceHUDTotalFlashTime above cg.time - if ( cg.forceHUDTotalFlashTime > cg.time ) - { + if (cg.forceHUDTotalFlashTime > cg.time) { flash = qtrue; - if ( cg.forceHUDNextFlashTime < cg.time ) - { + if (cg.forceHUDNextFlashTime < cg.time) { cg.forceHUDNextFlashTime = cg.time + 400; - trap->S_StartSound( NULL, 0, CHAN_LOCAL, cgs.media.noforceSound ); - if ( cg.forceHUDActive ) - { + trap->S_StartSound(NULL, 0, CHAN_LOCAL, cgs.media.noforceSound); + if (cg.forceHUDActive) { cg.forceHUDActive = qfalse; - } - else - { + } else { cg.forceHUDActive = qtrue; } - } - } - else // turn HUD back on if it had just finished flashing time. + } else // turn HUD back on if it had just finished flashing time. { cg.forceHUDNextFlashTime = 0; cg.forceHUDActive = qtrue; @@ -1310,9 +1095,9 @@ static void CG_DrawSimpleForcePower( const centity_t *cent ) // Determine the color of the numeric field calcColor = flash ? CT_RED : CT_ICON_BLUE; - Com_sprintf( num, sizeof( num ), "%i", cg.snap->ps.fd.forcePower ); + Com_sprintf(num, sizeof(num), "%i", cg.snap->ps.fd.forcePower); - CG_DrawProportionalString( SCREEN_WIDTH - (18 + 14 + 32), (SCREEN_HEIGHT - 80) + 40 + 14, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor] ); + CG_DrawProportionalString(SCREEN_WIDTH - (18 + 14 + 32), (SCREEN_HEIGHT - 80) + 40 + 14, num, UI_SMALLFONT | UI_DROPSHADOW, colorTable[calcColor]); } /* @@ -1320,203 +1105,141 @@ static void CG_DrawSimpleForcePower( const centity_t *cent ) CG_DrawHUD ================ */ -void CG_DrawHUD(centity_t *cent) -{ - menuDef_t *menuHUD = NULL; - itemDef_t *focusItem = NULL; +void CG_DrawHUD(centity_t *cent) { + menuDef_t *menuHUD = NULL; + itemDef_t *focusItem = NULL; const char *scoreStr = NULL; - int scoreBias; + int scoreBias; char scoreBiasStr[16]; - if (cg_hudFiles.integer) - { + if (cg_hudFiles.integer) { int x = 0; - int y = SCREEN_HEIGHT-80; + int y = SCREEN_HEIGHT - 80; - if (cg.predictedPlayerState.pm_type != PM_SPECTATOR) - { - CG_DrawProportionalString( x+16, y+40, va( "%i", cg.snap->ps.stats[STAT_HEALTH] ), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_RED] ); + if (cg.predictedPlayerState.pm_type != PM_SPECTATOR) { + CG_DrawProportionalString(x + 16, y + 40, va("%i", cg.snap->ps.stats[STAT_HEALTH]), UI_SMALLFONT | UI_DROPSHADOW, colorTable[CT_HUD_RED]); - CG_DrawProportionalString( x+18+14, y+40+14, va( "%i", cg.snap->ps.stats[STAT_ARMOR] ), UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_GREEN] ); + CG_DrawProportionalString(x + 18 + 14, y + 40 + 14, va("%i", cg.snap->ps.stats[STAT_ARMOR]), UI_SMALLFONT | UI_DROPSHADOW, + colorTable[CT_HUD_GREEN]); - CG_DrawSimpleForcePower( cent ); + CG_DrawSimpleForcePower(cent); - if ( cent->currentState.weapon == WP_SABER ) - CG_DrawSimpleSaberStyle( cent ); + if (cent->currentState.weapon == WP_SABER) + CG_DrawSimpleSaberStyle(cent); else - CG_DrawSimpleAmmo( cent ); + CG_DrawSimpleAmmo(cent); - //TODO Add score line + // TODO Add score line } return; } - if (cg.predictedPlayerState.pm_type != PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type != PM_SPECTATOR) { // Draw the left HUD menuHUD = Menus_FindByName("lefthud"); - Menu_Paint( menuHUD, qtrue ); + Menu_Paint(menuHUD, qtrue); - if (menuHUD) - { + if (menuHUD) { itemDef_t *focusItem; // Print scanline focusItem = Menu_FindItemByName(menuHUD, "scanline"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, + focusItem->window.background); } // Print frame focusItem = Menu_FindItemByName(menuHUD, "frame"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, + focusItem->window.background); } CG_DrawArmor(menuHUD); CG_DrawHealth(menuHUD); - } - else - { - //trap->Error( ERR_DROP, "CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); + } else { + // trap->Error( ERR_DROP, "CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); } - //scoreStr = va("Score: %i", cgs.clientinfo[cg.snap->ps.clientNum].score); - if ( cgs.gametype == GT_DUEL ) - {//A duel that requires more than one kill to knock the current enemy back to the queue - //show current kills out of how many needed + // scoreStr = va("Score: %i", cgs.clientinfo[cg.snap->ps.clientNum].score); + if (cgs.gametype == GT_DUEL) { // A duel that requires more than one kill to knock the current enemy back to the queue + // show current kills out of how many needed scoreStr = va("%s: %i/%i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], cgs.fraglimit); - } - else if (0 && cgs.gametype < GT_TEAM ) - { // This is a teamless mode, draw the score bias. + } else if (0 && cgs.gametype < GT_TEAM) { // This is a teamless mode, draw the score bias. scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores1; - if (scoreBias == 0) - { // We are the leader! - if (cgs.scores2 <= 0) - { // Nobody to be ahead of yet. + if (scoreBias == 0) { // We are the leader! + if (cgs.scores2 <= 0) { // Nobody to be ahead of yet. Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), ""); - } - else - { + } else { scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores2; - if (scoreBias == 0) - { + if (scoreBias == 0) { Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (Tie)"); - } - else - { + } else { Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (+%d)", scoreBias); } } - } - else // if (scoreBias < 0) - { // We are behind! + } else // if (scoreBias < 0) + { // We are behind! Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (%d)", scoreBias); } scoreStr = va("%s: %i%s", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], scoreBiasStr); - } - else - { // Don't draw a bias. + } else { // Don't draw a bias. scoreStr = va("%s: %i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE]); } menuHUD = Menus_FindByName("righthud"); - Menu_Paint( menuHUD, qtrue ); + Menu_Paint(menuHUD, qtrue); - if (menuHUD) - { - if (cgs.gametype != GT_POWERDUEL) - { + if (menuHUD) { + if (cgs.gametype != GT_POWERDUEL) { focusItem = Menu_FindItemByName(menuHUD, "score_line"); - if (focusItem) - { - CG_DrawScaledProportionalString( - focusItem->window.rect.x, - focusItem->window.rect.y, - scoreStr, - UI_RIGHT|UI_DROPSHADOW, - focusItem->window.foreColor, - 0.7f); + if (focusItem) { + CG_DrawScaledProportionalString(focusItem->window.rect.x, focusItem->window.rect.y, scoreStr, UI_RIGHT | UI_DROPSHADOW, + focusItem->window.foreColor, 0.7f); } } // Print scanline focusItem = Menu_FindItemByName(menuHUD, "scanline"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, + focusItem->window.background); } focusItem = Menu_FindItemByName(menuHUD, "frame"); - if (focusItem) - { - trap->R_SetColor( colorTable[CT_WHITE] ); - CG_DrawPic( - focusItem->window.rect.x, - focusItem->window.rect.y, - focusItem->window.rect.w, - focusItem->window.rect.h, - focusItem->window.background - ); + if (focusItem) { + trap->R_SetColor(colorTable[CT_WHITE]); + CG_DrawPic(focusItem->window.rect.x, focusItem->window.rect.y, focusItem->window.rect.w, focusItem->window.rect.h, + focusItem->window.background); } CG_DrawForcePower(menuHUD); // Draw ammo tics or saber style - if ( cent->currentState.weapon == WP_SABER ) - { - CG_DrawSaberStyle(cent,menuHUD); - } - else - { - CG_DrawAmmo(cent,menuHUD); + if (cent->currentState.weapon == WP_SABER) { + CG_DrawSaberStyle(cent, menuHUD); + } else { + CG_DrawAmmo(cent, menuHUD); } - } - else - { - //trap->Error( ERR_DROP, "CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); + } else { + // trap->Error( ERR_DROP, "CG_ChatBox_ArrayInsert: unable to locate HUD menu file "); } } } #define MAX_SHOWPOWERS NUM_FORCE_POWERS -qboolean ForcePower_Valid(int i) -{ - if (i == FP_LEVITATION || - i == FP_SABER_OFFENSE || - i == FP_SABER_DEFENSE || - i == FP_SABERTHROW) - { +qboolean ForcePower_Valid(int i) { + if (i == FP_LEVITATION || i == FP_SABER_OFFENSE || i == FP_SABER_DEFENSE || i == FP_SABERTHROW) { return qfalse; } - if (cg.snap->ps.fd.forcePowersKnown & (1 << i)) - { + if (cg.snap->ps.fd.forcePowersKnown & (1 << i)) { return qtrue; } @@ -1528,66 +1251,59 @@ qboolean ForcePower_Valid(int i) CG_DrawForceSelect =================== */ -void CG_DrawForceSelect( void ) -{ - int i; - int count; - int smallIconSize,bigIconSize; - int holdX, x, y, pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; - int yOffset = 0; +void CG_DrawForceSelect(void) { + int i; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + int yOffset = 0; // don't display if dead - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { return; } - if ((cg.forceSelectTime+WEAPON_SELECT_TIME)ps.fd.forcePowerSelected; return; } - if (!cg.snap->ps.fd.forcePowersKnown) - { + if (!cg.snap->ps.fd.forcePowersKnown) { return; } // count the number of powers owned count = 0; - for (i=0;i < NUM_FORCE_POWERS;++i) - { - if (ForcePower_Valid(i)) - { + for (i = 0; i < NUM_FORCE_POWERS; ++i) { + if (ForcePower_Valid(i)) { count++; } } - if (count == 0) // If no force powers, don't display + if (count == 0) // If no force powers, don't display { return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } @@ -1599,76 +1315,67 @@ void CG_DrawForceSelect( void ) y = 425; i = BG_ProperForceIndex(cg.forceSelect) - 1; - if (i < 0) - { + if (i < 0) { i = MAX_SHOWPOWERS - 1; } trap->R_SetColor(NULL); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if (i < 0) - { + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i < 0) { i = MAX_SHOWPOWERS - 1; } - if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? + if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) - { - CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] ); - holdX -= (smallIconSize+pad); + if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) { + CG_DrawPic(holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]]); + holdX -= (smallIconSize + pad); } } - if (ForcePower_Valid(cg.forceSelect)) - { + if (ForcePower_Valid(cg.forceSelect)) { // Current Center Icon - if (cgs.media.forcePowerIcons[cg.forceSelect]) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)) + yOffset, bigIconSize, bigIconSize, cgs.media.forcePowerIcons[cg.forceSelect] ); //only cache the icon for display + if (cgs.media.forcePowerIcons[cg.forceSelect]) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + yOffset, bigIconSize, bigIconSize, + cgs.media.forcePowerIcons[cg.forceSelect]); // only cache the icon for display } } i = BG_ProperForceIndex(cg.forceSelect) + 1; - if (i>=MAX_SHOWPOWERS) - { + if (i >= MAX_SHOWPOWERS) { i = 0; } // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if (i>=MAX_SHOWPOWERS) - { + holdX = x + (bigIconSize / 2) + pad; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i >= MAX_SHOWPOWERS) { i = 0; } - if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? + if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power? { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) - { - CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] ); //only cache the icon for display - holdX += (smallIconSize+pad); + if (cgs.media.forcePowerIcons[forcePowerSorted[i]]) { + CG_DrawPic(holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]]); // only cache the icon for display + holdX += (smallIconSize + pad); } } - if ( showPowersName[cg.forceSelect] ) - { - CG_DrawProportionalString(320, y + 30 + yOffset, CG_GetStringEdString("SP_INGAME", showPowersName[cg.forceSelect]), UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]); + if (showPowersName[cg.forceSelect]) { + CG_DrawProportionalString(320, y + 30 + yOffset, CG_GetStringEdString("SP_INGAME", showPowersName[cg.forceSelect]), UI_CENTER | UI_SMALLFONT, + colorTable[CT_ICON_BLUE]); } } @@ -1677,81 +1384,71 @@ void CG_DrawForceSelect( void ) CG_DrawInventorySelect =================== */ -void CG_DrawInvenSelect( void ) -{ - int i; - int sideMax,holdCount,iconCnt; - int smallIconSize,bigIconSize; - int sideLeftIconCnt,sideRightIconCnt; - int count; - int holdX, x, y, y2, pad; -// float addX; +void CG_DrawInvenSelect(void) { + int i; + int sideMax, holdCount, iconCnt; + int smallIconSize, bigIconSize; + int sideLeftIconCnt, sideRightIconCnt; + int count; + int holdX, x, y, y2, pad; + // float addX; // don't display if dead - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { return; } - if ((cg.invenSelectTime+WEAPON_SELECT_TIME)ps.stats[STAT_HOLDABLE_ITEM] || !cg.snap->ps.stats[STAT_HOLDABLE_ITEMS]) - { + if (!cg.snap->ps.stats[STAT_HOLDABLE_ITEM] || !cg.snap->ps.stats[STAT_HOLDABLE_ITEMS]) { return; } - if (cg.itemSelect == -1) - { + if (cg.itemSelect == -1) { cg.itemSelect = bg_itemlist[cg.snap->ps.stats[STAT_HOLDABLE_ITEM]].giTag; } -//const int bits = cg.snap->ps.stats[ STAT_ITEMS ]; + // const int bits = cg.snap->ps.stats[ STAT_ITEMS ]; // count the number of items owned count = 0; - for ( i = 0 ; i < HI_NUM_HOLDABLE ; i++ ) - { + for (i = 0; i < HI_NUM_HOLDABLE; i++) { if (/*CG_InventorySelectable(i) && inv_icons[i]*/ - (cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) ) - { + (cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i))) { count++; } } - if (!count) - { - y2 = 0; //err? + if (!count) { + y2 = 0; // err? CG_DrawProportionalString(320, y2 + 22, "EMPTY INVENTORY", UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]); return; } - sideMax = 3; // Max number of icons on the side + sideMax = 3; // Max number of icons on the side // Calculate how many icons will appear to either side of the center one - holdCount = count - 1; // -1 for the center icon - if (holdCount == 0) // No icons to either side + holdCount = count - 1; // -1 for the center icon + if (holdCount == 0) // No icons to either side { sideLeftIconCnt = 0; sideRightIconCnt = 0; - } - else if (count > (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } i = cg.itemSelect - 1; - if (i<0) - { - i = HI_NUM_HOLDABLE-1; + if (i < 0) { + i = HI_NUM_HOLDABLE - 1; } smallIconSize = 40; @@ -1763,186 +1460,151 @@ void CG_DrawInvenSelect( void ) // Left side ICONS // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); -// addX = (float) smallIconSize * .75; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCntps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect ) - { + if (!(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) - { + if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) { continue; } - if (cgs.media.invenIcons[i]) - { + if (cgs.media.invenIcons[i]) { trap->R_SetColor(NULL); - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] ); + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, cgs.media.invenIcons[i]); trap->R_SetColor(colorTable[CT_ICON_BLUE]); /*CG_DrawNumField (holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL,qfalse); */ - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } } // Current Center Icon - if (cgs.media.invenIcons[cg.itemSelect] && BG_IsItemSelectable(&cg.predictedPlayerState, cg.itemSelect)) - { + if (cgs.media.invenIcons[cg.itemSelect] && BG_IsItemSelectable(&cg.predictedPlayerState, cg.itemSelect)) { int itemNdex; trap->R_SetColor(NULL); - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, cgs.media.invenIcons[cg.itemSelect] ); - // addX = (float) bigIconSize * .75; + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10, bigIconSize, bigIconSize, cgs.media.invenIcons[cg.itemSelect]); + // addX = (float) bigIconSize * .75; trap->R_SetColor(colorTable[CT_ICON_BLUE]); /*CG_DrawNumField ((x-(bigIconSize/2)) + addX, y, 2, cg.snap->ps.inventory[cg.inventorySelect], 6, 12, NUM_FONT_SMALL,qfalse);*/ itemNdex = BG_GetItemIndexByTag(cg.itemSelect, IT_HOLDABLE); - if (bg_itemlist[itemNdex].classname) - { - vec4_t textColor = { .312f, .75f, .621f, 1.0f }; - char text[1024]; - char upperKey[1024]; + if (bg_itemlist[itemNdex].classname) { + vec4_t textColor = {.312f, .75f, .621f, 1.0f}; + char text[1024]; + char upperKey[1024]; strcpy(upperKey, bg_itemlist[itemNdex].classname); - if ( trap->SE_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text ))) - { - CG_DrawProportionalString(320, y+45, text, UI_CENTER | UI_SMALLFONT, textColor); - } - else - { - CG_DrawProportionalString(320, y+45, bg_itemlist[itemNdex].classname, UI_CENTER | UI_SMALLFONT, textColor); + if (trap->SE_GetStringTextString(va("SP_INGAME_%s", Q_strupr(upperKey)), text, sizeof(text))) { + CG_DrawProportionalString(320, y + 45, text, UI_CENTER | UI_SMALLFONT, textColor); + } else { + CG_DrawProportionalString(320, y + 45, bg_itemlist[itemNdex].classname, UI_CENTER | UI_SMALLFONT, textColor); } } } i = cg.itemSelect + 1; - if (i> HI_NUM_HOLDABLE-1) - { + if (i > HI_NUM_HOLDABLE - 1) { i = 0; } // Right side ICONS // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; -// addX = (float) smallIconSize * .75; - for (iconCnt=0;iconCnt HI_NUM_HOLDABLE-1) - { + holdX = x + (bigIconSize / 2) + pad; + // addX = (float) smallIconSize * .75; + for (iconCnt = 0; iconCnt < sideRightIconCnt; i++) { + if (i > HI_NUM_HOLDABLE - 1) { i = 0; } - if ( !(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect ) - { + if (!(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect) { continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) - { + if (!BG_IsItemSelectable(&cg.predictedPlayerState, i)) { continue; } - if (cgs.media.invenIcons[i]) - { + if (cgs.media.invenIcons[i]) { trap->R_SetColor(NULL); - CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] ); + CG_DrawPic(holdX, y + 10, smallIconSize, smallIconSize, cgs.media.invenIcons[i]); trap->R_SetColor(colorTable[CT_ICON_BLUE]); /*CG_DrawNumField (holdX + addX, y + smallIconSize, 2, cg.snap->ps.inventory[i], 6, 12, NUM_FONT_SMALL,qfalse);*/ - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } } } int cg_targVeh = ENTITYNUM_NONE; int cg_targVehLastTime = 0; -qboolean CG_CheckTargetVehicle( centity_t **pTargetVeh, float *alpha ) -{ +qboolean CG_CheckTargetVehicle(centity_t **pTargetVeh, float *alpha) { int targetNum = ENTITYNUM_NONE; - centity_t *targetVeh = NULL; + centity_t *targetVeh = NULL; - if ( !pTargetVeh || !alpha ) - {//hey, where are my pointers? + if (!pTargetVeh || !alpha) { // hey, where are my pointers? return qfalse; } *alpha = 1.0f; - //FIXME: need to clear all of these when you die? - if ( cg.predictedPlayerState.rocketLockIndex < ENTITYNUM_WORLD ) - { + // FIXME: need to clear all of these when you die? + if (cg.predictedPlayerState.rocketLockIndex < ENTITYNUM_WORLD) { targetNum = cg.predictedPlayerState.rocketLockIndex; - } - else if ( cg.crosshairVehNum < ENTITYNUM_WORLD - && cg.time - cg.crosshairVehTime < 3000 ) - {//crosshair was on a vehicle in the last 3 seconds + } else if (cg.crosshairVehNum < ENTITYNUM_WORLD && cg.time - cg.crosshairVehTime < 3000) { // crosshair was on a vehicle in the last 3 seconds targetNum = cg.crosshairVehNum; - } - else if ( cg.crosshairClientNum < ENTITYNUM_WORLD ) - { + } else if (cg.crosshairClientNum < ENTITYNUM_WORLD) { targetNum = cg.crosshairClientNum; } - if ( targetNum < MAX_CLIENTS ) - {//real client - if ( cg_entities[targetNum].currentState.m_iVehicleNum >= MAX_CLIENTS ) - {//in a vehicle + if (targetNum < MAX_CLIENTS) { // real client + if (cg_entities[targetNum].currentState.m_iVehicleNum >= MAX_CLIENTS) { // in a vehicle targetNum = cg_entities[targetNum].currentState.m_iVehicleNum; } } - if ( targetNum < ENTITYNUM_WORLD - && targetNum >= MAX_CLIENTS ) - { - //centity_t *targetVeh = &cg_entities[targetNum]; + if (targetNum < ENTITYNUM_WORLD && targetNum >= MAX_CLIENTS) { + // centity_t *targetVeh = &cg_entities[targetNum]; targetVeh = &cg_entities[targetNum]; - if ( targetVeh->currentState.NPC_class == CLASS_VEHICLE - && targetVeh->m_pVehicle - && targetVeh->m_pVehicle->m_pVehicleInfo - && targetVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//it's a vehicle + if (targetVeh->currentState.NPC_class == CLASS_VEHICLE && targetVeh->m_pVehicle && targetVeh->m_pVehicle->m_pVehicleInfo && + targetVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // it's a vehicle cg_targVeh = targetNum; cg_targVehLastTime = cg.time; *alpha = 1.0f; - } - else - { + } else { targetVeh = NULL; } } - if ( targetVeh ) - { + if (targetVeh) { *pTargetVeh = targetVeh; return qtrue; } - if ( cg_targVehLastTime && cg.time - cg_targVehLastTime < 3000 ) - { + if (cg_targVehLastTime && cg.time - cg_targVehLastTime < 3000) { targetVeh = &cg_entities[cg_targVeh]; - //stay at full alpha for 1 sec after lose them from crosshair - if ( cg.time-cg_targVehLastTime < 1000 ) + // stay at full alpha for 1 sec after lose them from crosshair + if (cg.time - cg_targVehLastTime < 1000) *alpha = 1.0f; - else //fade out over 2 secs - *alpha = 1.0f-((cg.time-cg_targVehLastTime-1000)/2000.0f); + else // fade out over 2 secs + *alpha = 1.0f - ((cg.time - cg_targVehLastTime - 1000) / 2000.0f); } return qfalse; } @@ -1952,66 +1614,51 @@ qboolean CG_CheckTargetVehicle( centity_t **pTargetVeh, float *alpha ) #define MAX_VHUD_ARMOR_TICS 5 #define MAX_VHUD_AMMO_TICS 5 -float CG_DrawVehicleShields( const menuDef_t *menuHUD, const centity_t *veh ) -{ - int i; - char itemName[64]; - float inc, currValue,maxShields; - vec4_t calcColor; - itemDef_t *item; - float percShields; +float CG_DrawVehicleShields(const menuDef_t *menuHUD, const centity_t *veh) { + int i; + char itemName[64]; + float inc, currValue, maxShields; + vec4_t calcColor; + itemDef_t *item; + float percShields; - item = Menu_FindItemByName((menuDef_t *) menuHUD, "armorbackground"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "armorbackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } maxShields = veh->m_pVehicle->m_pVehicleInfo->shields; currValue = cg.predictedVehicleState.stats[STAT_ARMOR]; - percShields = (float)currValue/(float)maxShields; + percShields = (float)currValue / (float)maxShields; // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxShields / MAX_VHUD_ARMOR_TICS; - for (i=1;i<=MAX_VHUD_ARMOR_TICS;i++) - { - sprintf( itemName, "armor_tic%d", i ); + inc = (float)maxShields / MAX_VHUD_ARMOR_TICS; + for (i = 1; i <= MAX_VHUD_ARMOR_TICS; i++) { + sprintf(itemName, "armor_tic%d", i); - item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName); + item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); - if (!item) - { + if (!item) { continue; } memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } @@ -2021,755 +1668,558 @@ float CG_DrawVehicleShields( const menuDef_t *menuHUD, const centity_t *veh ) int cg_vehicleAmmoWarning = 0; int cg_vehicleAmmoWarningTime = 0; -void CG_DrawVehicleAmmo( const menuDef_t *menuHUD, const centity_t *veh ) -{ +void CG_DrawVehicleAmmo(const menuDef_t *menuHUD, const centity_t *veh) { int i; char itemName[64]; - float inc, currValue,maxAmmo; - vec4_t calcColor; - itemDef_t *item; + float inc, currValue, maxAmmo; + vec4_t calcColor; + itemDef_t *item; - item = Menu_FindItemByName((menuDef_t *) menuHUD, "ammobackground"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammobackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax; currValue = cg.predictedVehicleState.ammo[0]; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;i<=MAX_VHUD_AMMO_TICS;i++) - { - sprintf( itemName, "ammo_tic%d", i ); + inc = (float)maxAmmo / MAX_VHUD_AMMO_TICS; + for (i = 1; i <= MAX_VHUD_AMMO_TICS; i++) { + sprintf(itemName, "ammo_tic%d", i); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); - if (!item) - { + if (!item) { continue; } - if ( cg_vehicleAmmoWarningTime > cg.time - && cg_vehicleAmmoWarning == 0 ) - { + if (cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 0) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); - calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; - } - else - { + calcColor[3] = sin(cg.time * 0.005) * 0.5f + 0.5f; + } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } } - -void CG_DrawVehicleAmmoUpper( const menuDef_t *menuHUD, const centity_t *veh ) -{ - int i; - char itemName[64]; - float inc, currValue,maxAmmo; - vec4_t calcColor; - itemDef_t *item; +void CG_DrawVehicleAmmoUpper(const menuDef_t *menuHUD, const centity_t *veh) { + int i; + char itemName[64]; + float inc, currValue, maxAmmo; + vec4_t calcColor; + itemDef_t *item; item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammoupperbackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax; currValue = cg.predictedVehicleState.ammo[0]; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;i cg.time - && cg_vehicleAmmoWarning == 0 ) - { + if (cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 0) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); - calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; - } - else - { + calcColor[3] = sin(cg.time * 0.005) * 0.5f + 0.5f; + } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } } - -void CG_DrawVehicleAmmoLower( const menuDef_t *menuHUD, const centity_t *veh ) -{ - int i; - char itemName[64]; - float inc, currValue,maxAmmo; - vec4_t calcColor; - itemDef_t *item; - +void CG_DrawVehicleAmmoLower(const menuDef_t *menuHUD, const centity_t *veh) { + int i; + char itemName[64]; + float inc, currValue, maxAmmo; + vec4_t calcColor; + itemDef_t *item; item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammolowerbackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[1].ammoMax; currValue = cg.predictedVehicleState.ammo[1]; - inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS; - for (i=1;i cg.time - && cg_vehicleAmmoWarning == 1 ) - { + if (cg_vehicleAmmoWarningTime > cg.time && cg_vehicleAmmoWarning == 1) { memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t)); - calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f; - } - else - { + calcColor[3] = sin(cg.time * 0.005) * 0.5f + 0.5f; + } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } } // The HUD.menu file has the graphic print with a negative height, so it will print from the bottom up. -void CG_DrawVehicleTurboRecharge( const menuDef_t *menuHUD, const centity_t *veh ) -{ - itemDef_t *item; - int height; +void CG_DrawVehicleTurboRecharge(const menuDef_t *menuHUD, const centity_t *veh) { + itemDef_t *item; + int height; - item = Menu_FindItemByName( (menuDef_t *) menuHUD, "turborecharge"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "turborecharge"); - if (item) - { - float percent=0.0f; - int diff = ( cg.time - veh->m_pVehicle->m_iTurboTime ); + if (item) { + float percent = 0.0f; + int diff = (cg.time - veh->m_pVehicle->m_iTurboTime); height = item->window.rect.h; - if (diff > veh->m_pVehicle->m_pVehicleInfo->turboRecharge) - { + if (diff > veh->m_pVehicle->m_pVehicleInfo->turboRecharge) { percent = 1.0f; - trap->R_SetColor( colorTable[CT_GREEN] ); - } - else - { - percent = (float) diff / veh->m_pVehicle->m_pVehicleInfo->turboRecharge; - if (percent < 0.0f) - { + trap->R_SetColor(colorTable[CT_GREEN]); + } else { + percent = (float)diff / veh->m_pVehicle->m_pVehicleInfo->turboRecharge; + if (percent < 0.0f) { percent = 0.0f; } - trap->R_SetColor( colorTable[CT_RED] ); + trap->R_SetColor(colorTable[CT_RED]); } height *= percent; - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - height, - cgs.media.whiteShader); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, height, cgs.media.whiteShader); } } qboolean cg_drawLink = qfalse; -void CG_DrawVehicleWeaponsLinked( const menuDef_t *menuHUD, const centity_t *veh ) -{ +void CG_DrawVehicleWeaponsLinked(const menuDef_t *menuHUD, const centity_t *veh) { qboolean drawLink = qfalse; - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pVehicleInfo - && (veh->m_pVehicle->m_pVehicleInfo->weapon[0].linkable == 2|| veh->m_pVehicle->m_pVehicleInfo->weapon[1].linkable == 2) ) - {//weapon is always linked + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && + (veh->m_pVehicle->m_pVehicleInfo->weapon[0].linkable == 2 || veh->m_pVehicle->m_pVehicleInfo->weapon[1].linkable == 2)) { // weapon is always linked drawLink = qtrue; - } - else - { -//MP way: - //must get sent over network - if ( cg.predictedVehicleState.vehWeaponsLinked ) - { - drawLink = qtrue; - } -//NOTE: below is SP way -/* - //just cheat it - if ( veh->gent->m_pVehicle->weaponStatus[0].linked - || veh->gent->m_pVehicle->weaponStatus[1].linked ) - { + } else { + // MP way: + // must get sent over network + if (cg.predictedVehicleState.vehWeaponsLinked) { drawLink = qtrue; } -*/ + // NOTE: below is SP way + /* + //just cheat it + if ( veh->gent->m_pVehicle->weaponStatus[0].linked + || veh->gent->m_pVehicle->weaponStatus[1].linked ) + { + drawLink = qtrue; + } + */ } - if ( cg_drawLink != drawLink ) - {//state changed, play sound + if (cg_drawLink != drawLink) { // state changed, play sound cg_drawLink = drawLink; - trap->S_StartSound (NULL, cg.predictedPlayerState.clientNum, CHAN_LOCAL, trap->S_RegisterSound( "sound/vehicles/common/linkweaps.wav" ) ); + trap->S_StartSound(NULL, cg.predictedPlayerState.clientNum, CHAN_LOCAL, trap->S_RegisterSound("sound/vehicles/common/linkweaps.wav")); } - if ( drawLink ) - { - itemDef_t *item; + if (drawLink) { + itemDef_t *item; - item = Menu_FindItemByName( (menuDef_t *) menuHUD, "weaponslinked"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "weaponslinked"); - if (item) - { - trap->R_SetColor( colorTable[CT_CYAN] ); + if (item) { + trap->R_SetColor(colorTable[CT_CYAN]); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - cgs.media.whiteShader); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, cgs.media.whiteShader); } } } -void CG_DrawVehicleSpeed( const menuDef_t *menuHUD, const centity_t *veh ) -{ +void CG_DrawVehicleSpeed(const menuDef_t *menuHUD, const centity_t *veh) { int i; char itemName[64]; - float inc, currValue,maxSpeed; - vec4_t calcColor; - itemDef_t *item; + float inc, currValue, maxSpeed; + vec4_t calcColor; + itemDef_t *item; - item = Menu_FindItemByName((menuDef_t *) menuHUD, "speedbackground"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "speedbackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } maxSpeed = veh->m_pVehicle->m_pVehicleInfo->speedMax; currValue = cg.predictedVehicleState.speed; - // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxSpeed / MAX_VHUD_SPEED_TICS; - for (i=1;i<=MAX_VHUD_SPEED_TICS;i++) - { - sprintf( itemName, "speed_tic%d", i ); + inc = (float)maxSpeed / MAX_VHUD_SPEED_TICS; + for (i = 1; i <= MAX_VHUD_SPEED_TICS; i++) { + sprintf(itemName, "speed_tic%d", i); item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); - if (!item) - { + if (!item) { continue; } - if ( cg.time > veh->m_pVehicle->m_iTurboTime ) - { + if (cg.time > veh->m_pVehicle->m_iTurboTime) { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - } - else // In turbo mode + } else // In turbo mode { - if (cg.VHUDFlashTime < cg.time) - { + if (cg.VHUDFlashTime < cg.time) { cg.VHUDFlashTime = cg.time + 200; - if (cg.VHUDTurboFlag) - { + if (cg.VHUDTurboFlag) { cg.VHUDTurboFlag = qfalse; - } - else - { + } else { cg.VHUDTurboFlag = qtrue; } } - if (cg.VHUDTurboFlag) - { + if (cg.VHUDTurboFlag) { memcpy(calcColor, colorTable[CT_LTRED1], sizeof(vec4_t)); - } - else - { + } else { memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); } } - - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } } -void CG_DrawVehicleArmor( const menuDef_t *menuHUD, const centity_t *veh ) -{ - int i; - vec4_t calcColor; - char itemName[64]; - float inc, currValue,maxArmor; - itemDef_t *item; +void CG_DrawVehicleArmor(const menuDef_t *menuHUD, const centity_t *veh) { + int i; + vec4_t calcColor; + char itemName[64]; + float inc, currValue, maxArmor; + itemDef_t *item; maxArmor = veh->m_pVehicle->m_pVehicleInfo->armor; currValue = cg.predictedVehicleState.stats[STAT_HEALTH]; - item = Menu_FindItemByName( (menuDef_t *) menuHUD, "shieldbackground"); + item = Menu_FindItemByName((menuDef_t *)menuHUD, "shieldbackground"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } - // Print all the tics of the shield graphic // Look at the amount of health left and show only as much of the graphic as there is health. // Use alpha to fade out partial section of health - inc = (float) maxArmor / MAX_VHUD_SHIELD_TICS; - for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++) - { - sprintf( itemName, "shield_tic%d", i ); + inc = (float)maxArmor / MAX_VHUD_SHIELD_TICS; + for (i = 1; i <= MAX_VHUD_SHIELD_TICS; i++) { + sprintf(itemName, "shield_tic%d", i); - item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName); + item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName); - if (!item) - { + if (!item) { continue; } - memcpy(calcColor, item->window.foreColor, sizeof(vec4_t)); - if (currValue <= 0) // don't show tic + if (currValue <= 0) // don't show tic { break; - } - else if (currValue < inc) // partial tic (alpha it out) + } else if (currValue < inc) // partial tic (alpha it out) { float percent = currValue / inc; - calcColor[3] *= percent; // Fade it out + calcColor[3] *= percent; // Fade it out } - trap->R_SetColor( calcColor); + trap->R_SetColor(calcColor); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); currValue -= inc; } } -enum -{ - VEH_DAMAGE_FRONT=0, +enum { + VEH_DAMAGE_FRONT = 0, VEH_DAMAGE_BACK, VEH_DAMAGE_LEFT, VEH_DAMAGE_RIGHT, }; -typedef struct -{ - const char *itemName; - short heavyDamage; - short lightDamage; +typedef struct { + const char *itemName; + short heavyDamage; + short lightDamage; } veh_damage_t; -veh_damage_t vehDamageData[4] = -{ - { "vehicle_front",SHIPSURF_DAMAGE_FRONT_HEAVY,SHIPSURF_DAMAGE_FRONT_LIGHT }, - { "vehicle_back",SHIPSURF_DAMAGE_BACK_HEAVY,SHIPSURF_DAMAGE_BACK_LIGHT }, - { "vehicle_left",SHIPSURF_DAMAGE_LEFT_HEAVY,SHIPSURF_DAMAGE_LEFT_LIGHT }, - { "vehicle_right",SHIPSURF_DAMAGE_RIGHT_HEAVY,SHIPSURF_DAMAGE_RIGHT_LIGHT }, +veh_damage_t vehDamageData[4] = { + {"vehicle_front", SHIPSURF_DAMAGE_FRONT_HEAVY, SHIPSURF_DAMAGE_FRONT_LIGHT}, + {"vehicle_back", SHIPSURF_DAMAGE_BACK_HEAVY, SHIPSURF_DAMAGE_BACK_LIGHT}, + {"vehicle_left", SHIPSURF_DAMAGE_LEFT_HEAVY, SHIPSURF_DAMAGE_LEFT_LIGHT}, + {"vehicle_right", SHIPSURF_DAMAGE_RIGHT_HEAVY, SHIPSURF_DAMAGE_RIGHT_LIGHT}, }; // Draw health graphic for given part of vehicle -void CG_DrawVehicleDamage(const centity_t *veh,int brokenLimbs,const menuDef_t *menuHUD,float alpha,int index) -{ - itemDef_t *item; - int colorI; - vec4_t color; - int graphicHandle=0; +void CG_DrawVehicleDamage(const centity_t *veh, int brokenLimbs, const menuDef_t *menuHUD, float alpha, int index) { + itemDef_t *item; + int colorI; + vec4_t color; + int graphicHandle = 0; item = Menu_FindItemByName((menuDef_t *)menuHUD, vehDamageData[index].itemName); - if (item) - { - if (brokenLimbs & (1<R_SetColor( color ); + trap->R_SetColor(color); - switch ( index ) - { - case VEH_DAMAGE_FRONT : - graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconFrontHandle; - break; - case VEH_DAMAGE_BACK : - graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconBackHandle; - break; - case VEH_DAMAGE_LEFT : - graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconLeftHandle; - break; - case VEH_DAMAGE_RIGHT : - graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconRightHandle; - break; + switch (index) { + case VEH_DAMAGE_FRONT: + graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconFrontHandle; + break; + case VEH_DAMAGE_BACK: + graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconBackHandle; + break; + case VEH_DAMAGE_LEFT: + graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconLeftHandle; + break; + case VEH_DAMAGE_RIGHT: + graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconRightHandle; + break; } - if (graphicHandle) - { - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - graphicHandle ); + if (graphicHandle) { + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, graphicHandle); } } } - // Used on both damage indicators : player vehicle and the vehicle the player is locked on -void CG_DrawVehicleDamageHUD(const centity_t *veh,int brokenLimbs,float percShields,char *menuName, float alpha) -{ - menuDef_t *menuHUD; - itemDef_t *item; - vec4_t color; +void CG_DrawVehicleDamageHUD(const centity_t *veh, int brokenLimbs, float percShields, char *menuName, float alpha) { + menuDef_t *menuHUD; + itemDef_t *item; + vec4_t color; menuHUD = Menus_FindByName(menuName); - if ( !menuHUD ) - { + if (!menuHUD) { return; } item = Menu_FindItemByName(menuHUD, "background"); - if (item) - { - if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle) - { - if ( veh->damageTime > cg.time ) - {//ship shields currently taking damage - //NOTE: cent->damageAngle can be accessed to get the direction from the ship origin to the impact point (in 3-D space) - float perc = 1.0f - ((veh->damageTime - cg.time) / 2000.0f/*MIN_SHIELD_TIME*/); - if ( perc < 0.0f ) - { + if (item) { + if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle) { + if (veh->damageTime > cg.time) { // ship shields currently taking damage + // NOTE: cent->damageAngle can be accessed to get the direction from the ship origin to the impact point (in 3-D space) + float perc = 1.0f - ((veh->damageTime - cg.time) / 2000.0f /*MIN_SHIELD_TIME*/); + if (perc < 0.0f) { perc = 0.0f; - } - else if ( perc > 1.0f ) - { + } else if (perc > 1.0f) { perc = 1.0f; } - color[0] = item->window.foreColor[0];//flash red - color[1] = item->window.foreColor[1]*perc;//fade other colors back in over time - color[2] = item->window.foreColor[2]*perc;//fade other colors back in over time - color[3] = item->window.foreColor[3];//always normal alpha - trap->R_SetColor( color ); - } - else - { - trap->R_SetColor( item->window.foreColor ); + color[0] = item->window.foreColor[0]; // flash red + color[1] = item->window.foreColor[1] * perc; // fade other colors back in over time + color[2] = item->window.foreColor[2] * perc; // fade other colors back in over time + color[3] = item->window.foreColor[3]; // always normal alpha + trap->R_SetColor(color); + } else { + trap->R_SetColor(item->window.foreColor); } - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle ); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, + veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle); } } item = Menu_FindItemByName(menuHUD, "outer_frame"); - if (item) - { - if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle ); + if (item) { + if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, + veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle); } } item = Menu_FindItemByName(menuHUD, "shields"); - if (item) - { - if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle) - { - VectorCopy4 ( colorTable[CT_HUD_GREEN], color ); + if (item) { + if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle) { + VectorCopy4(colorTable[CT_HUD_GREEN], color); color[3] = percShields; - trap->R_SetColor( color ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle ); - } - } - - //TODO: if we check nextState.brokenLimbs & prevState.brokenLimbs, we can tell when a damage flag has been added and flash that part of the ship - //FIXME: when ship explodes, either stop drawing ship or draw all parts black - CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_FRONT); - CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_BACK); - CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_LEFT); - CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_RIGHT); + trap->R_SetColor(color); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, + veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle); + } + } + + // TODO: if we check nextState.brokenLimbs & prevState.brokenLimbs, we can tell when a damage flag has been added and flash that part of the ship + // FIXME: when ship explodes, either stop drawing ship or draw all parts black + CG_DrawVehicleDamage(veh, brokenLimbs, menuHUD, alpha, VEH_DAMAGE_FRONT); + CG_DrawVehicleDamage(veh, brokenLimbs, menuHUD, alpha, VEH_DAMAGE_BACK); + CG_DrawVehicleDamage(veh, brokenLimbs, menuHUD, alpha, VEH_DAMAGE_LEFT); + CG_DrawVehicleDamage(veh, brokenLimbs, menuHUD, alpha, VEH_DAMAGE_RIGHT); } -qboolean CG_DrawVehicleHud( const centity_t *cent ) -{ - itemDef_t *item; - menuDef_t *menuHUD; - playerState_t *ps; - centity_t *veh; - float shieldPerc,alpha; +qboolean CG_DrawVehicleHud(const centity_t *cent) { + itemDef_t *item; + menuDef_t *menuHUD; + playerState_t *ps; + centity_t *veh; + float shieldPerc, alpha; menuHUD = Menus_FindByName("swoopvehiclehud"); - if (!menuHUD) - { - return qtrue; // Draw player HUD + if (!menuHUD) { + return qtrue; // Draw player HUD } ps = &cg.predictedPlayerState; - if (!ps || !(ps->m_iVehicleNum)) - { - return qtrue; // Draw player HUD + if (!ps || !(ps->m_iVehicleNum)) { + return qtrue; // Draw player HUD } veh = &cg_entities[ps->m_iVehicleNum]; - if ( !veh || !veh->m_pVehicle ) - { - return qtrue; // Draw player HUD + if (!veh || !veh->m_pVehicle) { + return qtrue; // Draw player HUD } - CG_DrawVehicleTurboRecharge( menuHUD, veh ); - CG_DrawVehicleWeaponsLinked( menuHUD, veh ); + CG_DrawVehicleTurboRecharge(menuHUD, veh); + CG_DrawVehicleWeaponsLinked(menuHUD, veh); item = Menu_FindItemByName(menuHUD, "leftframe"); // Draw frame - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } item = Menu_FindItemByName(menuHUD, "rightframe"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } - - CG_DrawVehicleArmor( menuHUD, veh ); + CG_DrawVehicleArmor(menuHUD, veh); // Get animal hud for speed -// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) -// { -// menuHUD = Menus_FindByName("tauntaunhud"); -// } - + // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) + // { + // menuHUD = Menus_FindByName("tauntaunhud"); + // } - CG_DrawVehicleSpeed( menuHUD, veh ); + CG_DrawVehicleSpeed(menuHUD, veh); // Revert to swoophud -// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) -// { -// menuHUD = Menus_FindByName("swoopvehiclehud"); -// } + // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) + // { + // menuHUD = Menus_FindByName("swoopvehiclehud"); + // } -// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) -// { - shieldPerc = CG_DrawVehicleShields( menuHUD, veh ); -// } + // if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) + // { + shieldPerc = CG_DrawVehicleShields(menuHUD, veh); + // } - if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && !veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) - { - CG_DrawVehicleAmmo( menuHUD, veh ); - } - else if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) - { - CG_DrawVehicleAmmoUpper( menuHUD, veh ); - CG_DrawVehicleAmmoLower( menuHUD, veh ); + if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && !veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) { + CG_DrawVehicleAmmo(menuHUD, veh); + } else if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID) { + CG_DrawVehicleAmmoUpper(menuHUD, veh); + CG_DrawVehicleAmmoLower(menuHUD, veh); } // If he's hidden, he must be in a vehicle - if (veh->m_pVehicle->m_pVehicleInfo->hideRider) - { - CG_DrawVehicleDamageHUD(veh,cg.predictedVehicleState.brokenLimbs,shieldPerc,"vehicledamagehud",1.0f); + if (veh->m_pVehicle->m_pVehicleInfo->hideRider) { + CG_DrawVehicleDamageHUD(veh, cg.predictedVehicleState.brokenLimbs, shieldPerc, "vehicledamagehud", 1.0f); // Has he targeted an enemy? - if (CG_CheckTargetVehicle( &veh, &alpha )) - { - CG_DrawVehicleDamageHUD(veh,veh->currentState.brokenLimbs,((float)veh->currentState.activeForcePass/10.0f),"enemyvehicledamagehud",alpha); + if (CG_CheckTargetVehicle(&veh, &alpha)) { + CG_DrawVehicleDamageHUD(veh, veh->currentState.brokenLimbs, ((float)veh->currentState.activeForcePass / 10.0f), "enemyvehicledamagehud", alpha); } - return qfalse; // Don't draw player HUD + return qfalse; // Don't draw player HUD } - return qtrue; // Draw player HUD - + return qtrue; // Draw player HUD } /* @@ -2778,44 +2228,41 @@ CG_DrawStats ================ */ -static void CG_DrawStats( void ) -{ - centity_t *cent; - playerState_t *ps; - qboolean drawHUD = qtrue; -/* playerState_t *ps; - vec3_t angles; -// vec3_t origin; - - if ( cg_drawStatus.integer == 0 ) { - return; - } -*/ +static void CG_DrawStats(void) { + centity_t *cent; + playerState_t *ps; + qboolean drawHUD = qtrue; + /* playerState_t *ps; + vec3_t angles; + // vec3_t origin; + + if ( cg_drawStatus.integer == 0 ) { + return; + } + */ cent = &cg_entities[cg.snap->ps.clientNum]; -/* ps = &cg.snap->ps; + /* ps = &cg.snap->ps; - VectorClear( angles ); + VectorClear( angles ); - // Do start - if (!cg.interfaceStartupDone) - { - CG_InterfaceStartup(); - } + // Do start + if (!cg.interfaceStartupDone) + { + CG_InterfaceStartup(); + } - cgi_UI_MenuPaintAll();*/ + cgi_UI_MenuPaintAll();*/ - if ( cent ) - { + if (cent) { ps = &cg.predictedPlayerState; - if ( (ps->m_iVehicleNum ) ) // In a vehicle??? + if ((ps->m_iVehicleNum)) // In a vehicle??? { - drawHUD = CG_DrawVehicleHud( cent ); + drawHUD = CG_DrawVehicleHud(cent); } } - if (drawHUD) - { + if (drawHUD) { CG_DrawHUD(cent); } @@ -2831,20 +2278,18 @@ static void CG_DrawStats( void ) CG_DrawPickupItem =================== */ -static void CG_DrawPickupItem( void ) { - int value; - float *fadeColor; +static void CG_DrawPickupItem(void) { + int value; + float *fadeColor; value = cg.itemPickup; - if ( value && cg_items[ value ].icon != -1 ) - { - fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 ); - if ( fadeColor ) - { - CG_RegisterItemVisuals( value ); - trap->R_SetColor( fadeColor ); - CG_DrawPic( 573, 320, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon ); - trap->R_SetColor( NULL ); + if (value && cg_items[value].icon != -1) { + fadeColor = CG_FadeColor(cg.itemPickupTime, 3000); + if (fadeColor) { + CG_RegisterItemVisuals(value); + trap->R_SetColor(fadeColor); + CG_DrawPic(573, 320, ICON_SIZE, ICON_SIZE, cg_items[value].icon); + trap->R_SetColor(NULL); } } } @@ -2855,30 +2300,28 @@ CG_DrawTeamBackground ================ */ -void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team ) -{ - vec4_t hcolor; +void CG_DrawTeamBackground(int x, int y, int w, int h, float alpha, int team) { + vec4_t hcolor; hcolor[3] = alpha; - if ( team == TEAM_RED ) { + if (team == TEAM_RED) { hcolor[0] = 1; hcolor[1] = .2f; hcolor[2] = .2f; - } else if ( team == TEAM_BLUE ) { + } else if (team == TEAM_BLUE) { hcolor[0] = .2f; hcolor[1] = .2f; hcolor[2] = 1; } else { return; } -// trap->R_SetColor( hcolor ); + // trap->R_SetColor( hcolor ); - CG_FillRect ( x, y, w, h, hcolor ); -// CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar ); - trap->R_SetColor( NULL ); + CG_FillRect(x, y, w, h, hcolor); + // CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar ); + trap->R_SetColor(NULL); } - /* =========================================================================================== @@ -2892,33 +2335,27 @@ void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team ) CG_DrawMiniScoreboard ================ */ -static float CG_DrawMiniScoreboard ( float y ) -{ +static float CG_DrawMiniScoreboard(float y) { char temp[MAX_QPATH]; int xOffset = 0; - if ( !cg_drawScores.integer ) - { + if (!cg_drawScores.integer) { return y; } - if (cgs.gametype == GT_SIEGE) - { //don't bother with this in siege + if (cgs.gametype == GT_SIEGE) { // don't bother with this in siege return y; } - if ( cgs.gametype >= GT_TEAM ) - { - Q_strncpyz( temp, va( "%s: ", CG_GetStringEdString( "MP_INGAME", "RED" ) ), sizeof( temp ) ); - Q_strcat( temp, sizeof( temp ), cgs.scores1 == SCORE_NOT_PRESENT ? "-" : (va( "%i", cgs.scores1 )) ); - Q_strcat( temp, sizeof( temp ), va( " %s: ", CG_GetStringEdString( "MP_INGAME", "BLUE" ) ) ); - Q_strcat( temp, sizeof( temp ), cgs.scores2 == SCORE_NOT_PRESENT ? "-" : (va( "%i", cgs.scores2 )) ); + if (cgs.gametype >= GT_TEAM) { + Q_strncpyz(temp, va("%s: ", CG_GetStringEdString("MP_INGAME", "RED")), sizeof(temp)); + Q_strcat(temp, sizeof(temp), cgs.scores1 == SCORE_NOT_PRESENT ? "-" : (va("%i", cgs.scores1))); + Q_strcat(temp, sizeof(temp), va(" %s: ", CG_GetStringEdString("MP_INGAME", "BLUE"))); + Q_strcat(temp, sizeof(temp), cgs.scores2 == SCORE_NOT_PRESENT ? "-" : (va("%i", cgs.scores2))); - CG_Text_Paint( 630 - CG_Text_Width ( temp, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, temp, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM ); + CG_Text_Paint(630 - CG_Text_Width(temp, 0.7f, FONT_MEDIUM) + xOffset, y, 0.7f, colorWhite, temp, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); y += 15; - } - else - { + } else { /* strcpy ( temp, "1st: " ); Q_strcat ( temp, MAX_QPATH, cgs.scores1==SCORE_NOT_PRESENT?"-":(va("%i",cgs.scores1)) ); @@ -2929,10 +2366,9 @@ static float CG_DrawMiniScoreboard ( float y ) CG_Text_Paint( 630 - CG_Text_Width ( temp, 0.7f, FONT_SMALL ), y, 0.7f, colorWhite, temp, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM ); y += 15; */ - //rww - no longer doing this. Since the attacker now shows who is first, we print the score there. + // rww - no longer doing this. Since the attacker now shows who is first, we print the score there. } - return y; } @@ -2941,51 +2377,43 @@ static float CG_DrawMiniScoreboard ( float y ) CG_DrawEnemyInfo ================ */ -static float CG_DrawEnemyInfo ( float y ) -{ - float size; - int clientNum; - const char *title; - clientInfo_t *ci; +static float CG_DrawEnemyInfo(float y) { + float size; + int clientNum; + const char *title; + clientInfo_t *ci; int xOffset = 0; - if (!cg.snap) - { + if (!cg.snap) { return y; } - if ( !cg_drawEnemyInfo.integer ) - { + if (!cg_drawEnemyInfo.integer) { return y; } - if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) - { + if (cg.predictedPlayerState.stats[STAT_HEALTH] <= 0) { return y; } - if (cgs.gametype == GT_POWERDUEL) - { //just get out of here then + if (cgs.gametype == GT_POWERDUEL) { // just get out of here then return y; } - if ( cgs.gametype == GT_JEDIMASTER ) - { - //title = "Jedi Master"; + if (cgs.gametype == GT_JEDIMASTER) { + // title = "Jedi Master"; title = CG_GetStringEdString("MP_INGAME", "MASTERY7"); clientNum = cgs.jediMaster; - if ( clientNum < 0 ) - { - //return y; -// title = "Get Saber!"; + if (clientNum < 0) { + // return y; + // title = "Get Saber!"; title = CG_GetStringEdString("MP_INGAME", "GET_SABER"); - size = ICON_SIZE * 1.25; y += 5; - CG_DrawPic( 640 - size - 12 + xOffset, y, size, size, cgs.media.weaponIcons[WP_SABER] ); + CG_DrawPic(640 - size - 12 + xOffset, y, size, size, cgs.media.weaponIcons[WP_SABER]); y += size; @@ -2994,39 +2422,26 @@ static float CG_DrawEnemyInfo ( float y ) y += 15; */ - CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM ); + CG_Text_Paint(630 - CG_Text_Width(title, 0.7f, FONT_MEDIUM) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM); return y + BIGCHAR_HEIGHT + 2; } - } - else if ( cg.snap->ps.duelInProgress ) - { -// title = "Dueling"; + } else if (cg.snap->ps.duelInProgress) { + // title = "Dueling"; title = CG_GetStringEdString("MP_INGAME", "DUELING"); clientNum = cg.snap->ps.duelIndex; - } - else if ( cgs.gametype == GT_DUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) - { + } else if (cgs.gametype == GT_DUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) { title = CG_GetStringEdString("MP_INGAME", "DUELING"); - if (cg.snap->ps.clientNum == cgs.duelist1) - { - clientNum = cgs.duelist2; //if power duel, should actually draw both duelists 2 and 3 I guess - } - else if (cg.snap->ps.clientNum == cgs.duelist2) - { + if (cg.snap->ps.clientNum == cgs.duelist1) { + clientNum = cgs.duelist2; // if power duel, should actually draw both duelists 2 and 3 I guess + } else if (cg.snap->ps.clientNum == cgs.duelist2) { clientNum = cgs.duelist1; - } - else if (cg.snap->ps.clientNum == cgs.duelist3) - { + } else if (cg.snap->ps.clientNum == cgs.duelist3) { clientNum = cgs.duelist1; - } - else - { + } else { return y; } - } - else - { + } else { /* title = "Attacker"; clientNum = cg.predictedPlayerState.persistant[PERS_ATTACKER]; @@ -3042,14 +2457,12 @@ static float CG_DrawEnemyInfo ( float y ) return y; } */ - //As of current, we don't want to draw the attacker. Instead, draw whoever is in first place. - if (cgs.duelWinner < 0 || cgs.duelWinner >= MAX_CLIENTS) - { + // As of current, we don't want to draw the attacker. Instead, draw whoever is in first place. + if (cgs.duelWinner < 0 || cgs.duelWinner >= MAX_CLIENTS) { return y; } - - title = va("%s: %i",CG_GetStringEdString("MP_INGAME", "LEADER"), cgs.scores1); + title = va("%s: %i", CG_GetStringEdString("MP_INGAME", "LEADER"), cgs.scores1); /* if (cgs.scores1 == 1) @@ -3064,49 +2477,42 @@ static float CG_DrawEnemyInfo ( float y ) clientNum = cgs.duelWinner; } - if ( clientNum >= MAX_CLIENTS || !(&cgs.clientinfo[ clientNum ]) ) - { + if (clientNum >= MAX_CLIENTS || !(&cgs.clientinfo[clientNum])) { return y; } - ci = &cgs.clientinfo[ clientNum ]; + ci = &cgs.clientinfo[clientNum]; size = ICON_SIZE * 1.25; y += 5; - if ( ci->modelIcon ) - { - CG_DrawPic( 640 - size - 5 + xOffset, y, size, size, ci->modelIcon ); + if (ci->modelIcon) { + CG_DrawPic(640 - size - 5 + xOffset, y, size, size, ci->modelIcon); } y += size; -// CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, ci->name, 0, 0, 0, FONT_MEDIUM ); - CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, ci->name, 0, 0, 0, FONT_SMALL2 ); + // CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, ci->name, 0, 0, 0, FONT_MEDIUM ); + CG_Text_Paint(630 - CG_Text_Width(ci->name, 1.0f, FONT_SMALL2) + xOffset, y, 1.0f, colorWhite, ci->name, 0, 0, 0, FONT_SMALL2); y += 15; -// CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM ); - CG_Text_Paint( 630 - CG_Text_Width ( title, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, title, 0, 0, 0, FONT_SMALL2 ); + // CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM ); + CG_Text_Paint(630 - CG_Text_Width(title, 1.0f, FONT_SMALL2) + xOffset, y, 1.0f, colorWhite, title, 0, 0, 0, FONT_SMALL2); - if ( (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) - {//also print their score + if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) { // also print their score char text[1024]; y += 15; - Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[clientNum].score, cgs.fraglimit ); - CG_Text_Paint( 630 - CG_Text_Width ( text, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, text, 0, 0, 0, FONT_MEDIUM ); + Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[clientNum].score, cgs.fraglimit); + CG_Text_Paint(630 - CG_Text_Width(text, 0.7f, FONT_MEDIUM) + xOffset, y, 0.7f, colorWhite, text, 0, 0, 0, FONT_MEDIUM); } -// nmckenzie: DUEL_HEALTH - fixme - need checks and such here. And this is coded to duelist 1 right now, which is wrongly. - if ( cgs.showDuelHealths >= 2) - { + // nmckenzie: DUEL_HEALTH - fixme - need checks and such here. And this is coded to duelist 1 right now, which is wrongly. + if (cgs.showDuelHealths >= 2) { y += 15; - if ( cgs.duelist1 == clientNum ) - { - CG_DrawDuelistHealth ( 640 - size - 5 + xOffset, y, 64, 8, 1 ); - } - else if ( cgs.duelist2 == clientNum ) - { - CG_DrawDuelistHealth ( 640 - size - 5 + xOffset, y, 64, 8, 2 ); + if (cgs.duelist1 == clientNum) { + CG_DrawDuelistHealth(640 - size - 5 + xOffset, y, 64, 8, 1); + } else if (cgs.duelist2 == clientNum) { + CG_DrawDuelistHealth(640 - size - 5 + xOffset, y, 64, 8, 2); } } @@ -3118,16 +2524,15 @@ static float CG_DrawEnemyInfo ( float y ) CG_DrawSnapshot ================== */ -static float CG_DrawSnapshot( float y ) { - char *s; - int w; - int xOffset = 0; +static float CG_DrawSnapshot(float y) { + char *s; + int w; + int xOffset = 0; - s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime, - cg.latestSnapshotNum, cgs.serverCommandSequence ); - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; + s = va("time:%i snap:%i cmd:%i", cg.snap->serverTime, cg.latestSnapshotNum, cgs.serverCommandSequence); + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; - CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); + CG_DrawBigString(635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } @@ -3137,24 +2542,23 @@ static float CG_DrawSnapshot( float y ) { CG_DrawFPS ================== */ -#define FPS_FRAMES 16 -static float CG_DrawFPS( float y ) { - char *s; - int w; +#define FPS_FRAMES 16 +static float CG_DrawFPS(float y) { + char *s; + int w; static unsigned short previousTimes[FPS_FRAMES]; static unsigned short index; - static int previous, lastupdate; - int t, i, fps, total; + static int previous, lastupdate; + int t, i, fps, total; unsigned short frameTime; - const int xOffset = 0; - + const int xOffset = 0; // don't use serverTime, because that will be drifting to // correct for internet lag changes, timescales, timedemos, etc t = trap->Milliseconds(); frameTime = t - previous; previous = t; - if (t - lastupdate > 50) //don't sample faster than this + if (t - lastupdate > 50) // don't sample faster than this { lastupdate = t; previousTimes[index % FPS_FRAMES] = frameTime; @@ -3162,26 +2566,25 @@ static float CG_DrawFPS( float y ) { } // average multiple frames together to smooth changes out a bit total = 0; - for ( i = 0 ; i < FPS_FRAMES ; i++ ) { + for (i = 0; i < FPS_FRAMES; i++) { total += previousTimes[i]; } - if ( !total ) { + if (!total) { total = 1; } fps = 1000 * FPS_FRAMES / total; - s = va( "%ifps", fps ); - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; + s = va("%ifps", fps); + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; - CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); + CG_DrawBigString(635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } // nmckenzie: DUEL_HEALTH -#define MAX_HEALTH_FOR_IFACE 100 -void CG_DrawHealthBarRough (float x, float y, int width, int height, float ratio, const float *color1, const float *color2) -{ +#define MAX_HEALTH_FOR_IFACE 100 +void CG_DrawHealthBarRough(float x, float y, int width, int height, float ratio, const float *color1, const float *color2) { float midpoint, remainder; float color3[4] = {1, 0, 0, .7f}; @@ -3189,39 +2592,33 @@ void CG_DrawHealthBarRough (float x, float y, int width, int height, float ratio remainder = width - midpoint; color3[0] = color1[0] * 0.5f; - assert(!(height%4));//this won't line up otherwise. - CG_DrawRect(x + 1, y + height/2-1, midpoint, 1, height/4+1, color1); // creme-y filling. - CG_DrawRect(x + midpoint, y + height/2-1, remainder, 1, height/4+1, color3); // used-up-ness. - CG_DrawRect(x, y, width, height, 1, color2); // hard crispy shell + assert(!(height % 4)); // this won't line up otherwise. + CG_DrawRect(x + 1, y + height / 2 - 1, midpoint, 1, height / 4 + 1, color1); // creme-y filling. + CG_DrawRect(x + midpoint, y + height / 2 - 1, remainder, 1, height / 4 + 1, color3); // used-up-ness. + CG_DrawRect(x, y, width, height, 1, color2); // hard crispy shell } -void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist ) -{ - float duelHealthColor[4] = {1, 0, 0, 0.7f}; - float healthSrc = 0.0f; - float ratio; +void CG_DrawDuelistHealth(float x, float y, float w, float h, int duelist) { + float duelHealthColor[4] = {1, 0, 0, 0.7f}; + float healthSrc = 0.0f; + float ratio; - if ( duelist == 1 ) - { + if (duelist == 1) { healthSrc = cgs.duelist1health; - } - else if (duelist == 2 ) - { + } else if (duelist == 2) { healthSrc = cgs.duelist2health; } ratio = healthSrc / MAX_HEALTH_FOR_IFACE; - if ( ratio > 1.0f ) - { + if (ratio > 1.0f) { ratio = 1.0f; } - if ( ratio < 0.0f ) - { + if (ratio < 0.0f) { ratio = 0.0f; } duelHealthColor[0] = (ratio * 0.2f) + 0.5f; - CG_DrawHealthBarRough (x, y, w, h, ratio, duelHealthColor, colorTable[CT_WHITE]); // new art for this? I'm not crazy about how this looks. + CG_DrawHealthBarRough(x, y, w, h, ratio, duelHealthColor, colorTable[CT_WHITE]); // new art for this? I'm not crazy about how this looks. } /* @@ -3229,463 +2626,215 @@ void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist ) CG_DrawRadar ===================== */ -float cg_radarRange = 2500.0f; +float cg_radarRange = 2500.0f; -#define RADAR_RADIUS 60 -#define RADAR_X (580 - RADAR_RADIUS) -#define RADAR_CHAT_DURATION 6000 +#define RADAR_RADIUS 60 +#define RADAR_X (580 - RADAR_RADIUS) +#define RADAR_CHAT_DURATION 6000 static int radarLockSoundDebounceTime = 0; static int impactSoundDebounceTime = 0; -#define RADAR_MISSILE_RANGE 3000.0f -#define RADAR_ASTEROID_RANGE 10000.0f -#define RADAR_MIN_ASTEROID_SURF_WARN_DIST 1200.0f +#define RADAR_MISSILE_RANGE 3000.0f +#define RADAR_ASTEROID_RANGE 10000.0f +#define RADAR_MIN_ASTEROID_SURF_WARN_DIST 1200.0f -float CG_DrawRadar ( float y ) -{ - vec4_t color; - vec4_t teamColor; - float arrow_w; - float arrow_h; - clientInfo_t *cl; - clientInfo_t *local; - int i; - float arrowBaseScale; - float zScale; - int xOffset = 0; +float CG_DrawRadar(float y) { + vec4_t color; + vec4_t teamColor; + float arrow_w; + float arrow_h; + clientInfo_t *cl; + clientInfo_t *local; + int i; + float arrowBaseScale; + float zScale; + int xOffset = 0; - if (!cg.snap) - { + if (!cg.snap) { return y; } // Make sure the radar should be showing - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { return y; } - if ( (cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR ) - { + if ((cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR) { return y; } - local = &cgs.clientinfo[ cg.snap->ps.clientNum ]; - if ( !local->infoValid ) - { + local = &cgs.clientinfo[cg.snap->ps.clientNum]; + if (!local->infoValid) { return y; } // Draw the radar background image color[0] = color[1] = color[2] = 1.0f; color[3] = 0.6f; - trap->R_SetColor ( color ); - CG_DrawPic( RADAR_X + xOffset, y, RADAR_RADIUS*2, RADAR_RADIUS*2, cgs.media.radarShader ); + trap->R_SetColor(color); + CG_DrawPic(RADAR_X + xOffset, y, RADAR_RADIUS * 2, RADAR_RADIUS * 2, cgs.media.radarShader); - //Always green for your own team. - VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], teamColor ); + // Always green for your own team. + VectorCopy(g_color_table[ColorIndex(COLOR_GREEN)], teamColor); teamColor[3] = 1.0f; // Draw all of the radar entities. Draw them backwards so players are drawn last - for ( i = cg.radarEntityCount -1 ; i >= 0 ; i-- ) - { - vec3_t dirLook; - vec3_t dirPlayer; - float angleLook; - float anglePlayer; - float angle; - float distance, actualDist; - centity_t* cent; + for (i = cg.radarEntityCount - 1; i >= 0; i--) { + vec3_t dirLook; + vec3_t dirPlayer; + float angleLook; + float anglePlayer; + float angle; + float distance, actualDist; + centity_t *cent; cent = &cg_entities[cg.radarEntities[i]]; // Get the distances first - VectorSubtract ( cg.predictedPlayerState.origin, cent->lerpOrigin, dirPlayer ); + VectorSubtract(cg.predictedPlayerState.origin, cent->lerpOrigin, dirPlayer); dirPlayer[2] = 0; - actualDist = distance = VectorNormalize ( dirPlayer ); + actualDist = distance = VectorNormalize(dirPlayer); - if ( distance > cg_radarRange * 0.8f) - { - if ( (cent->currentState.eFlags & EF_RADAROBJECT)//still want to draw the direction - || ( cent->currentState.eType==ET_NPC//FIXME: draw last, with players... - && cent->currentState.NPC_class == CLASS_VEHICLE - && cent->currentState.speed > 0 ) )//always draw vehicles - { - distance = cg_radarRange*0.8f; - } - else + if (distance > cg_radarRange * 0.8f) { + if ((cent->currentState.eFlags & EF_RADAROBJECT) // still want to draw the direction + || (cent->currentState.eType == ET_NPC // FIXME: draw last, with players... + && cent->currentState.NPC_class == CLASS_VEHICLE && cent->currentState.speed > 0)) // always draw vehicles { + distance = cg_radarRange * 0.8f; + } else { continue; } } - distance = distance / cg_radarRange; + distance = distance / cg_radarRange; distance *= RADAR_RADIUS; - AngleVectors ( cg.predictedPlayerState.viewangles, dirLook, NULL, NULL ); + AngleVectors(cg.predictedPlayerState.viewangles, dirLook, NULL, NULL); dirLook[2] = 0; - anglePlayer = atan2(dirPlayer[0],dirPlayer[1]); - VectorNormalize ( dirLook ); - angleLook = atan2(dirLook[0],dirLook[1]); + anglePlayer = atan2(dirPlayer[0], dirPlayer[1]); + VectorNormalize(dirLook); + angleLook = atan2(dirLook[0], dirLook[1]); angle = angleLook - anglePlayer; - switch ( cent->currentState.eType ) - { - default: - { - float x; - float ly; - qhandle_t shader; - vec4_t color; + switch (cent->currentState.eType) { + default: { + float x; + float ly; + qhandle_t shader; + vec4_t color; - x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; - ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; - - arrowBaseScale = 9.0f; - shader = 0; - zScale = 1.0f; + x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin(angle) * distance; + ly = y + (float)RADAR_RADIUS + (float)cos(angle) * distance; - //we want to scale the thing up/down based on the relative Z (up/down) positioning - if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) - { //higher, scale up (between 16 and 24) - float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); - - //max out to 1.5x scale at 512 units above local player's height - dif /= 1024.0f; - if (dif > 0.5f) - { - dif = 0.5f; - } - zScale += dif; - } - else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) - { //lower, scale down (between 16 and 8) - float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); + arrowBaseScale = 9.0f; + shader = 0; + zScale = 1.0f; - //half scale at 512 units below local player's height - dif /= 1024.0f; - if (dif > 0.5f) - { - dif = 0.5f; - } - zScale -= dif; - } + // we want to scale the thing up/down based on the relative Z (up/down) positioning + if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { // higher, scale up (between 16 and 24) + float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); - arrowBaseScale *= zScale; + // max out to 1.5x scale at 512 units above local player's height + dif /= 1024.0f; + if (dif > 0.5f) { + dif = 0.5f; + } + zScale += dif; + } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { // lower, scale down (between 16 and 8) + float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); + + // half scale at 512 units below local player's height + dif /= 1024.0f; + if (dif > 0.5f) { + dif = 0.5f; + } + zScale -= dif; + } - if (cent->currentState.brokenLimbs) - { //slightly misleading to use this value, but don't want to add more to entstate. - //any ent with brokenLimbs non-0 and on radar is an objective ent. - //brokenLimbs is literal team value. - char objState[1024]; - int complete; + arrowBaseScale *= zScale; - //we only want to draw it if the objective for it is not complete. - //frame represents objective num. - trap->Cvar_VariableStringBuffer(va("team%i_objective%i", cent->currentState.brokenLimbs, cent->currentState.frame), objState, 1024); + if (cent->currentState.brokenLimbs) { // slightly misleading to use this value, but don't want to add more to entstate. + // any ent with brokenLimbs non-0 and on radar is an objective ent. + // brokenLimbs is literal team value. + char objState[1024]; + int complete; - complete = atoi(objState); + // we only want to draw it if the objective for it is not complete. + // frame represents objective num. + trap->Cvar_VariableStringBuffer(va("team%i_objective%i", cent->currentState.brokenLimbs, cent->currentState.frame), objState, 1024); - if (!complete) - { + complete = atoi(objState); - // generic enemy index specifies a shader to use for the radar entity. - if ( cent->currentState.genericenemyindex && cent->currentState.genericenemyindex < MAX_ICONS ) - { - color[0] = color[1] = color[2] = color[3] = 1.0f; - shader = cgs.gameIcons[cent->currentState.genericenemyindex]; - } - else - { - if (cg.snap && - cent->currentState.brokenLimbs == cg.snap->ps.persistant[PERS_TEAM]) - { - VectorCopy ( g_color_table[ColorIndex(COLOR_RED)], color ); - } - else - { - VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], color ); - } + if (!complete) { - shader = cgs.media.siegeItemShader; - } - } - } - else - { + // generic enemy index specifies a shader to use for the radar entity. + if (cent->currentState.genericenemyindex && cent->currentState.genericenemyindex < MAX_ICONS) { color[0] = color[1] = color[2] = color[3] = 1.0f; - - // generic enemy index specifies a shader to use for the radar entity. - if ( cent->currentState.genericenemyindex ) - { - shader = cgs.gameIcons[cent->currentState.genericenemyindex]; - } - else - { - shader = cgs.media.siegeItemShader; - } - - } - - if ( shader ) - { - // Pulse the alpha if time2 is set. time2 gets set when the entity takes pain - if ( (cent->currentState.time2 && cg.time - cent->currentState.time2 < 5000) || - (cent->currentState.time2 == 0xFFFFFFFF) ) - { - if ( (cg.time / 200) & 1 ) - { - color[3] = 0.1f + 0.9f * (float) (cg.time % 200) / 200.0f; - } - else - { - color[3] = 1.0f - 0.9f * (float) (cg.time % 200) / 200.0f; - } + shader = cgs.gameIcons[cent->currentState.genericenemyindex]; + } else { + if (cg.snap && cent->currentState.brokenLimbs == cg.snap->ps.persistant[PERS_TEAM]) { + VectorCopy(g_color_table[ColorIndex(COLOR_RED)], color); + } else { + VectorCopy(g_color_table[ColorIndex(COLOR_GREEN)], color); } - trap->R_SetColor ( color ); - CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, shader ); + shader = cgs.media.siegeItemShader; } } - break; - - case ET_NPC://FIXME: draw last, with players... - if ( cent->currentState.NPC_class == CLASS_VEHICLE - && cent->currentState.speed > 0 ) - { - if ( cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->radarIconHandle ) - { - float x; - float ly; - - x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; - ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; - - arrowBaseScale = 9.0f; - zScale = 1.0f; - - //we want to scale the thing up/down based on the relative Z (up/down) positioning - if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) - { //higher, scale up (between 16 and 24) - float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); - - //max out to 1.5x scale at 512 units above local player's height - dif /= 4096.0f; - if (dif > 0.5f) - { - dif = 0.5f; - } - zScale += dif; - } - else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) - { //lower, scale down (between 16 and 8) - float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); - - //half scale at 512 units below local player's height - dif /= 4096.0f; - if (dif > 0.5f) - { - dif = 0.5f; - } - zScale -= dif; - } + } else { + color[0] = color[1] = color[2] = color[3] = 1.0f; - arrowBaseScale *= zScale; + // generic enemy index specifies a shader to use for the radar entity. + if (cent->currentState.genericenemyindex) { + shader = cgs.gameIcons[cent->currentState.genericenemyindex]; + } else { + shader = cgs.media.siegeItemShader; + } + } - if ( cent->currentState.m_iVehicleNum //vehicle has a driver - && cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid ) - { - if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team ) - { - trap->R_SetColor ( teamColor ); - } - else - { - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); - } - } - else - { - trap->R_SetColor ( NULL ); - } - CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cent->m_pVehicle->m_pVehicleInfo->radarIconHandle ); + if (shader) { + // Pulse the alpha if time2 is set. time2 gets set when the entity takes pain + if ((cent->currentState.time2 && cg.time - cent->currentState.time2 < 5000) || (cent->currentState.time2 == 0xFFFFFFFF)) { + if ((cg.time / 200) & 1) { + color[3] = 0.1f + 0.9f * (float)(cg.time % 200) / 200.0f; + } else { + color[3] = 1.0f - 0.9f * (float)(cg.time % 200) / 200.0f; } } - break; //maybe do something? - - case ET_MOVER: - if ( cent->currentState.speed//the mover's size, actually - && actualDist < (cent->currentState.speed+RADAR_ASTEROID_RANGE) - && cg.predictedPlayerState.m_iVehicleNum ) - {//a mover that's close to me and I'm in a vehicle - qboolean mayImpact = qfalse; - float surfaceDist = (actualDist-cent->currentState.speed); - if ( surfaceDist < 0.0f ) - { - surfaceDist = 0.0f; - } - if ( surfaceDist < RADAR_MIN_ASTEROID_SURF_WARN_DIST ) - {//always warn! - mayImpact = qtrue; - } - else - {//not close enough to always warn, yet, so check its direction - vec3_t asteroidPos, myPos, moveDir; - int predictTime, timeStep = 500; - float newDist; - for ( predictTime = timeStep; predictTime < 5000; predictTime+=timeStep ) - { - //asteroid dir, speed, size, + my dir & speed... - BG_EvaluateTrajectory( ¢->currentState.pos, cg.time+predictTime, asteroidPos ); - //FIXME: I don't think it's calcing "myPos" correctly - AngleVectors( cg.predictedVehicleState.viewangles, moveDir, NULL, NULL ); - VectorMA( cg.predictedVehicleState.origin, cg.predictedVehicleState.speed*predictTime/1000.0f, moveDir, myPos ); - newDist = Distance( myPos, asteroidPos ); - if ( (newDist-cent->currentState.speed) <= RADAR_MIN_ASTEROID_SURF_WARN_DIST )//200.0f ) - {//heading for an impact within the next 5 seconds - mayImpact = qtrue; - break; - } - } - } - if ( mayImpact ) - {//possible collision - vec4_t asteroidColor = {0.5f,0.5f,0.5f,1.0f}; - float x; - float ly; - float asteroidScale = (cent->currentState.speed/2000.0f);//average asteroid radius? - if ( actualDist > RADAR_ASTEROID_RANGE ) - { - actualDist = RADAR_ASTEROID_RANGE; - } - distance = (actualDist/RADAR_ASTEROID_RANGE)*RADAR_RADIUS; - x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; - ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; + trap->R_SetColor(color); + CG_DrawPic(x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, shader); + } + } break; - if ( asteroidScale > 3.0f ) - { - asteroidScale = 3.0f; - } - else if ( asteroidScale < 0.2f ) - { - asteroidScale = 0.2f; - } - arrowBaseScale = (9.0f*asteroidScale); - if ( impactSoundDebounceTime < cg.time ) - { - vec3_t soundOrg; - if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f ) - { - impactSoundDebounceTime = cg.time + 1000; - } - else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f ) - { - impactSoundDebounceTime = cg.time + 400; - } - else - { - impactSoundDebounceTime = cg.time + 100; - } - VectorMA( cg.refdef.vieworg, -500.0f*(surfaceDist/RADAR_ASTEROID_RANGE), dirPlayer, soundOrg ); - trap->S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, trap->S_RegisterSound( "sound/vehicles/common/impactalarm.wav" ) ); - } - //brighten it the closer it is - if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f ) - { - asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.7f; - } - else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f ) - { - asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.85f; - } - else - { - asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 1.0f; - } - //alpha out the longer it's been since it was considered dangerous - if ( (cg.time-impactSoundDebounceTime) > 100 ) - { - asteroidColor[3] = (float)((cg.time-impactSoundDebounceTime)-100)/900.0f; - } + case ET_NPC: // FIXME: draw last, with players... + if (cent->currentState.NPC_class == CLASS_VEHICLE && cent->currentState.speed > 0) { + if (cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->radarIconHandle) { + float x; + float ly; - trap->R_SetColor ( asteroidColor ); - CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, trap->R_RegisterShaderNoMip( "gfx/menus/radar/asteroid" ) ); - } - } - break; + x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin(angle) * distance; + ly = y + (float)RADAR_RADIUS + (float)cos(angle) * distance; - case ET_MISSILE: - if ( //cent->currentState.weapon == WP_ROCKET_LAUNCHER &&//a rocket - cent->currentState.owner > MAX_CLIENTS //belongs to an NPC - && cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE ) - {//a rocket belonging to an NPC, FIXME: only tracking rockets! - float x; - float ly; - - x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance; - ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance; - - arrowBaseScale = 3.0f; - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//I'm in a vehicle - //if it's targetting me, then play an alarm sound if I'm in a vehicle - if ( cent->currentState.otherEntityNum == cg.predictedPlayerState.clientNum || cent->currentState.otherEntityNum == cg.predictedPlayerState.m_iVehicleNum ) - { - if ( radarLockSoundDebounceTime < cg.time ) - { - vec3_t soundOrg; - int alarmSound; - if ( actualDist > RADAR_MISSILE_RANGE * 0.66f ) - { - radarLockSoundDebounceTime = cg.time + 1000; - arrowBaseScale = 3.0f; - alarmSound = trap->S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" ); - } - else if ( actualDist > RADAR_MISSILE_RANGE/3.0f ) - { - radarLockSoundDebounceTime = cg.time + 500; - arrowBaseScale = 6.0f; - alarmSound = trap->S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" ); - } - else - { - radarLockSoundDebounceTime = cg.time + 250; - arrowBaseScale = 9.0f; - alarmSound = trap->S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" ); - } - if ( actualDist > RADAR_MISSILE_RANGE ) - { - actualDist = RADAR_MISSILE_RANGE; - } - VectorMA( cg.refdef.vieworg, -500.0f*(actualDist/RADAR_MISSILE_RANGE), dirPlayer, soundOrg ); - trap->S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, alarmSound ); - } - } - } + arrowBaseScale = 9.0f; zScale = 1.0f; - //we want to scale the thing up/down based on the relative Z (up/down) positioning - if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) - { //higher, scale up (between 16 and 24) + // we want to scale the thing up/down based on the relative Z (up/down) positioning + if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { // higher, scale up (between 16 and 24) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); - //max out to 1.5x scale at 512 units above local player's height - dif /= 1024.0f; - if (dif > 0.5f) - { + // max out to 1.5x scale at 512 units above local player's height + dif /= 4096.0f; + if (dif > 0.5f) { dif = 0.5f; } zScale += dif; - } - else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) - { //lower, scale down (between 16 and 8) + } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { // lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); - //half scale at 512 units below local player's height - dif /= 1024.0f; - if (dif > 0.5f) - { + // half scale at 512 units below local player's height + dif /= 4096.0f; + if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; @@ -3693,79 +2842,158 @@ float CG_DrawRadar ( float y ) arrowBaseScale *= zScale; - if ( cent->currentState.owner >= MAX_CLIENTS//missile owned by an NPC - && cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE//NPC is a vehicle - && cg_entities[cent->currentState.owner].currentState.m_iVehicleNum <= MAX_CLIENTS//Vehicle has a player driver - && cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1].infoValid ) //player driver is valid - { - cl = &cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1]; - if ( cl->team == local->team ) - { - trap->R_SetColor ( teamColor ); - } - else - { - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); + if (cent->currentState.m_iVehicleNum // vehicle has a driver + && cgs.clientinfo[cent->currentState.m_iVehicleNum - 1].infoValid) { + if (cgs.clientinfo[cent->currentState.m_iVehicleNum - 1].team == local->team) { + trap->R_SetColor(teamColor); + } else { + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); } + } else { + trap->R_SetColor(NULL); } - else - { - trap->R_SetColor ( NULL ); - } - CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cgs.media.mAutomapRocketIcon ); + CG_DrawPic(x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cent->m_pVehicle->m_pVehicleInfo->radarIconHandle); } - break; - - case ET_PLAYER: - { - vec4_t color; - - cl = &cgs.clientinfo[ cent->currentState.number ]; + } + break; // maybe do something? - // not valid then dont draw it - if ( !cl->infoValid ) - { - continue; + case ET_MOVER: + if (cent->currentState.speed // the mover's size, actually + && actualDist < (cent->currentState.speed + RADAR_ASTEROID_RANGE) && + cg.predictedPlayerState.m_iVehicleNum) { // a mover that's close to me and I'm in a vehicle + qboolean mayImpact = qfalse; + float surfaceDist = (actualDist - cent->currentState.speed); + if (surfaceDist < 0.0f) { + surfaceDist = 0.0f; + } + if (surfaceDist < RADAR_MIN_ASTEROID_SURF_WARN_DIST) { // always warn! + mayImpact = qtrue; + } else { // not close enough to always warn, yet, so check its direction + vec3_t asteroidPos, myPos, moveDir; + int predictTime, timeStep = 500; + float newDist; + for (predictTime = timeStep; predictTime < 5000; predictTime += timeStep) { + // asteroid dir, speed, size, + my dir & speed... + BG_EvaluateTrajectory(¢->currentState.pos, cg.time + predictTime, asteroidPos); + // FIXME: I don't think it's calcing "myPos" correctly + AngleVectors(cg.predictedVehicleState.viewangles, moveDir, NULL, NULL); + VectorMA(cg.predictedVehicleState.origin, cg.predictedVehicleState.speed * predictTime / 1000.0f, moveDir, myPos); + newDist = Distance(myPos, asteroidPos); + if ((newDist - cent->currentState.speed) <= RADAR_MIN_ASTEROID_SURF_WARN_DIST) // 200.0f ) + { // heading for an impact within the next 5 seconds + mayImpact = qtrue; + break; + } + } } + if (mayImpact) { // possible collision + vec4_t asteroidColor = {0.5f, 0.5f, 0.5f, 1.0f}; + float x; + float ly; + float asteroidScale = (cent->currentState.speed / 2000.0f); // average asteroid radius? + if (actualDist > RADAR_ASTEROID_RANGE) { + actualDist = RADAR_ASTEROID_RANGE; + } + distance = (actualDist / RADAR_ASTEROID_RANGE) * RADAR_RADIUS; - VectorCopy4 ( teamColor, color ); + x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin(angle) * distance; + ly = y + (float)RADAR_RADIUS + (float)cos(angle) * distance; - arrowBaseScale = 16.0f; - zScale = 1.0f; + if (asteroidScale > 3.0f) { + asteroidScale = 3.0f; + } else if (asteroidScale < 0.2f) { + asteroidScale = 0.2f; + } + arrowBaseScale = (9.0f * asteroidScale); + if (impactSoundDebounceTime < cg.time) { + vec3_t soundOrg; + if (surfaceDist > RADAR_ASTEROID_RANGE * 0.66f) { + impactSoundDebounceTime = cg.time + 1000; + } else if (surfaceDist > RADAR_ASTEROID_RANGE / 3.0f) { + impactSoundDebounceTime = cg.time + 400; + } else { + impactSoundDebounceTime = cg.time + 100; + } + VectorMA(cg.refdef.vieworg, -500.0f * (surfaceDist / RADAR_ASTEROID_RANGE), dirPlayer, soundOrg); + trap->S_StartSound(soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, trap->S_RegisterSound("sound/vehicles/common/impactalarm.wav")); + } + // brighten it the closer it is + if (surfaceDist > RADAR_ASTEROID_RANGE * 0.66f) { + asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.7f; + } else if (surfaceDist > RADAR_ASTEROID_RANGE / 3.0f) { + asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.85f; + } else { + asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 1.0f; + } + // alpha out the longer it's been since it was considered dangerous + if ((cg.time - impactSoundDebounceTime) > 100) { + asteroidColor[3] = (float)((cg.time - impactSoundDebounceTime) - 100) / 900.0f; + } - // Pulse the radar icon after a voice message - if ( cent->vChatTime + 2000 > cg.time ) - { - float f = (cent->vChatTime + 2000 - cg.time) / 3000.0f; - arrowBaseScale = 16.0f + 4.0f * f; - color[0] = teamColor[0] + (1.0f - teamColor[0]) * f; - color[1] = teamColor[1] + (1.0f - teamColor[1]) * f; - color[2] = teamColor[2] + (1.0f - teamColor[2]) * f; + trap->R_SetColor(asteroidColor); + CG_DrawPic(x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, trap->R_RegisterShaderNoMip("gfx/menus/radar/asteroid")); } + } + break; - trap->R_SetColor ( color ); + case ET_MISSILE: + if ( // cent->currentState.weapon == WP_ROCKET_LAUNCHER &&//a rocket + cent->currentState.owner > MAX_CLIENTS // belongs to an NPC + && + cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE) { // a rocket belonging to an NPC, FIXME: only tracking rockets! + float x; + float ly; + + x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin(angle) * distance; + ly = y + (float)RADAR_RADIUS + (float)cos(angle) * distance; + + arrowBaseScale = 3.0f; + if (cg.predictedPlayerState.m_iVehicleNum) { // I'm in a vehicle + // if it's targetting me, then play an alarm sound if I'm in a vehicle + if (cent->currentState.otherEntityNum == cg.predictedPlayerState.clientNum || + cent->currentState.otherEntityNum == cg.predictedPlayerState.m_iVehicleNum) { + if (radarLockSoundDebounceTime < cg.time) { + vec3_t soundOrg; + int alarmSound; + if (actualDist > RADAR_MISSILE_RANGE * 0.66f) { + radarLockSoundDebounceTime = cg.time + 1000; + arrowBaseScale = 3.0f; + alarmSound = trap->S_RegisterSound("sound/vehicles/common/lockalarm1.wav"); + } else if (actualDist > RADAR_MISSILE_RANGE / 3.0f) { + radarLockSoundDebounceTime = cg.time + 500; + arrowBaseScale = 6.0f; + alarmSound = trap->S_RegisterSound("sound/vehicles/common/lockalarm2.wav"); + } else { + radarLockSoundDebounceTime = cg.time + 250; + arrowBaseScale = 9.0f; + alarmSound = trap->S_RegisterSound("sound/vehicles/common/lockalarm3.wav"); + } + if (actualDist > RADAR_MISSILE_RANGE) { + actualDist = RADAR_MISSILE_RANGE; + } + VectorMA(cg.refdef.vieworg, -500.0f * (actualDist / RADAR_MISSILE_RANGE), dirPlayer, soundOrg); + trap->S_StartSound(soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, alarmSound); + } + } + } + zScale = 1.0f; - //we want to scale the thing up/down based on the relative Z (up/down) positioning - if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) - { //higher, scale up (between 16 and 32) + // we want to scale the thing up/down based on the relative Z (up/down) positioning + if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { // higher, scale up (between 16 and 24) float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); - //max out to 2x scale at 1024 units above local player's height + // max out to 1.5x scale at 512 units above local player's height dif /= 1024.0f; - if (dif > 1.0f) - { - dif = 1.0f; + if (dif > 0.5f) { + dif = 0.5f; } zScale += dif; - } - else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) - { //lower, scale down (between 16 and 8) + } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { // lower, scale down (between 16 and 8) float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); - //half scale at 512 units below local player's height + // half scale at 512 units below local player's height dif /= 1024.0f; - if (dif > 0.5f) - { + if (dif > 0.5f) { dif = 0.5f; } zScale -= dif; @@ -3773,15 +3001,80 @@ float CG_DrawRadar ( float y ) arrowBaseScale *= zScale; - arrow_w = arrowBaseScale * RADAR_RADIUS / 128; - arrow_h = arrowBaseScale * RADAR_RADIUS / 128; + if (cent->currentState.owner >= MAX_CLIENTS // missile owned by an NPC + && cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE // NPC is a vehicle + && cg_entities[cent->currentState.owner].currentState.m_iVehicleNum <= MAX_CLIENTS // Vehicle has a player driver + && cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum - 1].infoValid) // player driver is valid + { + cl = &cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum - 1]; + if (cl->team == local->team) { + trap->R_SetColor(teamColor); + } else { + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); + } + } else { + trap->R_SetColor(NULL); + } + CG_DrawPic(x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cgs.media.mAutomapRocketIcon); + } + break; + + case ET_PLAYER: { + vec4_t color; - CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + sin (angle) * distance + xOffset, - y + RADAR_RADIUS + cos (angle) * distance, - arrow_w, arrow_h, - (360 - cent->lerpAngles[YAW]) + cg.predictedPlayerState.viewangles[YAW], cgs.media.mAutomapPlayerIcon ); - break; + cl = &cgs.clientinfo[cent->currentState.number]; + + // not valid then dont draw it + if (!cl->infoValid) { + continue; + } + + VectorCopy4(teamColor, color); + + arrowBaseScale = 16.0f; + zScale = 1.0f; + + // Pulse the radar icon after a voice message + if (cent->vChatTime + 2000 > cg.time) { + float f = (cent->vChatTime + 2000 - cg.time) / 3000.0f; + arrowBaseScale = 16.0f + 4.0f * f; + color[0] = teamColor[0] + (1.0f - teamColor[0]) * f; + color[1] = teamColor[1] + (1.0f - teamColor[1]) * f; + color[2] = teamColor[2] + (1.0f - teamColor[2]) * f; + } + + trap->R_SetColor(color); + + // we want to scale the thing up/down based on the relative Z (up/down) positioning + if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2]) { // higher, scale up (between 16 and 32) + float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]); + + // max out to 2x scale at 1024 units above local player's height + dif /= 1024.0f; + if (dif > 1.0f) { + dif = 1.0f; + } + zScale += dif; + } else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2]) { // lower, scale down (between 16 and 8) + float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]); + + // half scale at 512 units below local player's height + dif /= 1024.0f; + if (dif > 0.5f) { + dif = 0.5f; + } + zScale -= dif; } + + arrowBaseScale *= zScale; + + arrow_w = arrowBaseScale * RADAR_RADIUS / 128; + arrow_h = arrowBaseScale * RADAR_RADIUS / 128; + + CG_DrawRotatePic2(RADAR_X + RADAR_RADIUS + sin(angle) * distance + xOffset, y + RADAR_RADIUS + cos(angle) * distance, arrow_w, arrow_h, + (360 - cent->lerpAngles[YAW]) + cg.predictedPlayerState.viewangles[YAW], cgs.media.mAutomapPlayerIcon); + break; + } } } @@ -3790,11 +3083,10 @@ float CG_DrawRadar ( float y ) arrow_w = arrowBaseScale * RADAR_RADIUS / 128; arrow_h = arrowBaseScale * RADAR_RADIUS / 128; - trap->R_SetColor ( colorWhite ); - CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + xOffset, y + RADAR_RADIUS, arrow_w, arrow_h, - 0, cgs.media.mAutomapPlayerIcon ); + trap->R_SetColor(colorWhite); + CG_DrawRotatePic2(RADAR_X + RADAR_RADIUS + xOffset, y + RADAR_RADIUS, arrow_w, arrow_h, 0, cgs.media.mAutomapPlayerIcon); - return y+(RADAR_RADIUS*2); + return y + (RADAR_RADIUS * 2); } /* @@ -3802,12 +3094,12 @@ float CG_DrawRadar ( float y ) CG_DrawTimer ================= */ -static float CG_DrawTimer( float y ) { - char *s; - int w; - int mins, seconds, tens; - int msec; - int xOffset = 0; +static float CG_DrawTimer(float y) { + char *s; + int w; + int mins, seconds, tens; + int msec; + int xOffset = 0; msec = cg.time - cgs.levelStartTime; @@ -3817,45 +3109,44 @@ static float CG_DrawTimer( float y ) { tens = seconds / 10; seconds -= tens * 10; - s = va( "%i:%i%i", mins, tens, seconds ); - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; + s = va("%i:%i%i", mins, tens, seconds); + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; - CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F); + CG_DrawBigString(635 - w + xOffset, y + 2, s, 1.0F); return y + BIGCHAR_HEIGHT + 4; } - /* ================= CG_DrawTeamOverlay ================= */ -extern const char *CG_GetLocationString(const char *loc); //cg_main.c -static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { +extern const char *CG_GetLocationString(const char *loc); // cg_main.c +static float CG_DrawTeamOverlay(float y, qboolean right, qboolean upper) { int x, w, h, xx; int i, j, len; const char *p; - vec4_t hcolor; + vec4_t hcolor; int pwidth, lwidth; int plyrs; char st[16]; clientInfo_t *ci; - gitem_t *item; + gitem_t *item; int ret_y, count; int xOffset = 0; - if ( !cg_drawTeamOverlay.integer ) { + if (!cg_drawTeamOverlay.integer) { return y; } - if ( cg.snap->ps.persistant[PERS_TEAM] != TEAM_RED && cg.snap->ps.persistant[PERS_TEAM] != TEAM_BLUE ) { + if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_RED && cg.snap->ps.persistant[PERS_TEAM] != TEAM_BLUE) { return y; // Not on any team } plyrs = 0; - //TODO: On basejka servers, we won't have valid teaminfo if we're spectating someone. + // TODO: On basejka servers, we won't have valid teaminfo if we're spectating someone. // Find a way to detect invalid info and return early? // max player name width @@ -3863,7 +3154,7 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers; for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; - if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { + if (ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { plyrs++; len = CG_DrawStrlen(ci->name); if (len > pwidth) @@ -3880,7 +3171,7 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { // max location name width lwidth = 0; for (i = 1; i < MAX_LOCATIONS; i++) { - p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+i)); + p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS + i)); if (p && *p) { len = CG_DrawStrlen(p); if (len > lwidth) @@ -3893,21 +3184,21 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { w = (pwidth + lwidth + 4 + 7) * TINYCHAR_WIDTH; - if ( right ) + if (right) x = 640 - w; else x = 0; h = plyrs * TINYCHAR_HEIGHT; - if ( upper ) { + if (upper) { ret_y = y + h; } else { y -= h; ret_y = y; } - if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) { + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED) { hcolor[0] = 1.0f; hcolor[1] = 0.0f; hcolor[2] = 0.0f; @@ -3918,58 +3209,49 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { hcolor[2] = 1.0f; hcolor[3] = 0.33f; } - trap->R_SetColor( hcolor ); - CG_DrawPic( x + xOffset, y, w, h, cgs.media.teamStatusBar ); - trap->R_SetColor( NULL ); + trap->R_SetColor(hcolor); + CG_DrawPic(x + xOffset, y, w, h, cgs.media.teamStatusBar); + trap->R_SetColor(NULL); for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; - if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { + if (ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { hcolor[0] = hcolor[1] = hcolor[2] = hcolor[3] = 1.0; xx = x + TINYCHAR_WIDTH; - CG_DrawStringExt( xx + xOffset, y, - ci->name, hcolor, qfalse, qfalse, - TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXNAME_WIDTH); + CG_DrawStringExt(xx + xOffset, y, ci->name, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXNAME_WIDTH); if (lwidth) { - p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+ci->location)); + p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS + ci->location)); if (!p || !*p) p = "unknown"; len = CG_DrawStrlen(p); if (len > lwidth) len = lwidth; -// xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth + -// ((lwidth/2 - len/2) * TINYCHAR_WIDTH); + // xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth + + // ((lwidth/2 - len/2) * TINYCHAR_WIDTH); xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth; - CG_DrawStringExt( xx + xOffset, y, - p, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, - TEAM_OVERLAY_MAXLOCATION_WIDTH); + CG_DrawStringExt(xx + xOffset, y, p, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXLOCATION_WIDTH); } - CG_GetColorForHealth( ci->health, ci->armor, hcolor ); + CG_GetColorForHealth(ci->health, ci->armor, hcolor); - Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor); + Com_sprintf(st, sizeof(st), "%3i %3i", ci->health, ci->armor); - xx = x + TINYCHAR_WIDTH * 3 + - TINYCHAR_WIDTH * pwidth + TINYCHAR_WIDTH * lwidth; + xx = x + TINYCHAR_WIDTH * 3 + TINYCHAR_WIDTH * pwidth + TINYCHAR_WIDTH * lwidth; - CG_DrawStringExt( xx + xOffset, y, - st, hcolor, qfalse, qfalse, - TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0 ); + CG_DrawStringExt(xx + xOffset, y, st, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0); // draw weapon icon xx += TINYCHAR_WIDTH * 3; - if ( cg_weapons[ci->curWeapon].weaponIcon ) { - CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, - cg_weapons[ci->curWeapon].weaponIcon ); + if (cg_weapons[ci->curWeapon].weaponIcon) { + CG_DrawPic(xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, cg_weapons[ci->curWeapon].weaponIcon); } else { - CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, - cgs.media.deferShader ); + CG_DrawPic(xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, cgs.media.deferShader); } // Draw powerup icons @@ -3981,11 +3263,10 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { for (j = 0; j <= PW_NUM_POWERUPS; j++) { if (ci->powerups & (1 << j)) { - item = BG_FindItemForPowerup( j ); + item = BG_FindItemForPowerup(j); if (item) { - CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, - trap->R_RegisterShader( item->icon ) ); + CG_DrawPic(xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT, trap->R_RegisterShader(item->icon)); if (right) { xx -= TINYCHAR_WIDTH; } else { @@ -4000,104 +3281,90 @@ static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) { } return ret_y; -//#endif + //#endif } - -static void CG_DrawPowerupIcons(int y) -{ +static void CG_DrawPowerupIcons(int y) { int j; int ico_size = 64; - //int y = ico_size/2; + // int y = ico_size/2; int xOffset = 0; - gitem_t *item; + gitem_t *item; - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); - if (!cg.snap) - { + if (!cg.snap) { return; } y += 16; - for (j = 0; j < PW_NUM_POWERUPS; j++) - { - if (cg.snap->ps.powerups[j] > cg.time) - { - int secondsleft = (cg.snap->ps.powerups[j] - cg.time)/1000; + for (j = 0; j < PW_NUM_POWERUPS; j++) { + if (cg.snap->ps.powerups[j] > cg.time) { + int secondsleft = (cg.snap->ps.powerups[j] - cg.time) / 1000; - item = BG_FindItemForPowerup( j ); + item = BG_FindItemForPowerup(j); - if (item) - { + if (item) { int icoShader = 0; - if (cgs.gametype == GT_CTY && (j == PW_REDFLAG || j == PW_BLUEFLAG)) - { - if (j == PW_REDFLAG) - { - icoShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" ); - } - else - { - icoShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" ); + if (cgs.gametype == GT_CTY && (j == PW_REDFLAG || j == PW_BLUEFLAG)) { + if (j == PW_REDFLAG) { + icoShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_ys"); + } else { + icoShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_ys"); } - } - else - { - icoShader = trap->R_RegisterShader( item->icon ); + } else { + icoShader = trap->R_RegisterShader(item->icon); } - CG_DrawPic( (640-(ico_size*1.1)) + xOffset, y, ico_size, ico_size, icoShader ); + CG_DrawPic((640 - (ico_size * 1.1)) + xOffset, y, ico_size, ico_size, icoShader); y += ico_size; - if (j != PW_REDFLAG && j != PW_BLUEFLAG && secondsleft < 999) - { - CG_DrawProportionalString((640-(ico_size*1.1))+(ico_size/2) + xOffset, y-8, va("%i", secondsleft), UI_CENTER | UI_BIGFONT | UI_DROPSHADOW, colorTable[CT_WHITE]); + if (j != PW_REDFLAG && j != PW_BLUEFLAG && secondsleft < 999) { + CG_DrawProportionalString((640 - (ico_size * 1.1)) + (ico_size / 2) + xOffset, y - 8, va("%i", secondsleft), + UI_CENTER | UI_BIGFONT | UI_DROPSHADOW, colorTable[CT_WHITE]); } - y += (ico_size/3); + y += (ico_size / 3); } } } } - /* ===================== CG_DrawUpperRight ===================== */ -static void CG_DrawUpperRight( void ) { - float y = 0; +static void CG_DrawUpperRight(void) { + float y = 0; - trap->R_SetColor( colorTable[CT_WHITE] ); + trap->R_SetColor(colorTable[CT_WHITE]); - if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 1 ) { - y = CG_DrawTeamOverlay( y, qtrue, qtrue ); + if (cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 1) { + y = CG_DrawTeamOverlay(y, qtrue, qtrue); } - if ( cg_drawSnapshot.integer ) { - y = CG_DrawSnapshot( y ); + if (cg_drawSnapshot.integer) { + y = CG_DrawSnapshot(y); } - if ( cg_drawFPS.integer ) { - y = CG_DrawFPS( y ); + if (cg_drawFPS.integer) { + y = CG_DrawFPS(y); } - if ( cg_drawTimer.integer ) { - y = CG_DrawTimer( y ); + if (cg_drawTimer.integer) { + y = CG_DrawTimer(y); } - if ( ( cgs.gametype >= GT_TEAM || cg.predictedPlayerState.m_iVehicleNum ) - && cg_drawRadar.integer ) - {//draw Radar in Siege mode or when in a vehicle of any kind - y = CG_DrawRadar ( y ); + if ((cgs.gametype >= GT_TEAM || cg.predictedPlayerState.m_iVehicleNum) && + cg_drawRadar.integer) { // draw Radar in Siege mode or when in a vehicle of any kind + y = CG_DrawRadar(y); } - y = CG_DrawEnemyInfo ( y ); + y = CG_DrawEnemyInfo(y); - y = CG_DrawMiniScoreboard ( y ); + y = CG_DrawMiniScoreboard(y); CG_DrawPowerupIcons(y); } @@ -4108,34 +3375,34 @@ CG_DrawReward =================== */ #ifdef JK2AWARDS -static void CG_DrawReward( void ) { - float *color; - int i, count; - float x, y; - char buf[32]; +static void CG_DrawReward(void) { + float *color; + int i, count; + float x, y; + char buf[32]; - if ( !cg_drawRewards.integer ) { + if (!cg_drawRewards.integer) { return; } - color = CG_FadeColor( cg.rewardTime, REWARD_TIME ); - if ( !color ) { + color = CG_FadeColor(cg.rewardTime, REWARD_TIME); + if (!color) { if (cg.rewardStack > 0) { - for(i = 0; i < cg.rewardStack; i++) { - cg.rewardSound[i] = cg.rewardSound[i+1]; - cg.rewardShader[i] = cg.rewardShader[i+1]; - cg.rewardCount[i] = cg.rewardCount[i+1]; + for (i = 0; i < cg.rewardStack; i++) { + cg.rewardSound[i] = cg.rewardSound[i + 1]; + cg.rewardShader[i] = cg.rewardShader[i + 1]; + cg.rewardCount[i] = cg.rewardCount[i + 1]; } cg.rewardTime = cg.time; cg.rewardStack--; - color = CG_FadeColor( cg.rewardTime, REWARD_TIME ); + color = CG_FadeColor(cg.rewardTime, REWARD_TIME); trap->S_StartLocalSound(cg.rewardSound[0], CHAN_ANNOUNCER); } else { return; } } - trap->R_SetColor( color ); + trap->R_SetColor(color); /* count = cg.rewardCount[0]/10; // number of big rewards to draw @@ -4152,31 +3419,28 @@ static void CG_DrawReward( void ) { count = cg.rewardCount[0] - count*10; // number of small rewards to draw */ - if ( cg.rewardCount[0] >= 10 ) { + if (cg.rewardCount[0] >= 10) { y = 56; - x = 320 - ICON_SIZE/2; - CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] ); + x = 320 - ICON_SIZE / 2; + CG_DrawPic(x, y, ICON_SIZE - 4, ICON_SIZE - 4, cg.rewardShader[0]); Com_sprintf(buf, sizeof(buf), "%d", cg.rewardCount[0]); - x = ( SCREEN_WIDTH - SMALLCHAR_WIDTH * CG_DrawStrlen( buf ) ) / 2; - CG_DrawStringExt( x, y+ICON_SIZE, buf, color, qfalse, qtrue, - SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); - } - else { + x = (SCREEN_WIDTH - SMALLCHAR_WIDTH * CG_DrawStrlen(buf)) / 2; + CG_DrawStringExt(x, y + ICON_SIZE, buf, color, qfalse, qtrue, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0); + } else { count = cg.rewardCount[0]; y = 56; - x = 320 - count * ICON_SIZE/2; - for ( i = 0 ; i < count ; i++ ) { - CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] ); + x = 320 - count * ICON_SIZE / 2; + for (i = 0; i < count; i++) { + CG_DrawPic(x, y, ICON_SIZE - 4, ICON_SIZE - 4, cg.rewardShader[0]); x += ICON_SIZE; } } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } #endif - /* =============================================================================== @@ -4185,15 +3449,14 @@ LAGOMETER =============================================================================== */ -#define LAG_SAMPLES 128 - +#define LAG_SAMPLES 128 struct lagometer_s { - int frameSamples[LAG_SAMPLES]; - int frameCount; - int snapshotFlags[LAG_SAMPLES]; - int snapshotSamples[LAG_SAMPLES]; - int snapshotCount; + int frameSamples[LAG_SAMPLES]; + int frameCount; + int snapshotFlags[LAG_SAMPLES]; + int snapshotSamples[LAG_SAMPLES]; + int snapshotCount; } lagometer; /* @@ -4203,11 +3466,11 @@ CG_AddLagometerFrameInfo Adds the current interpolate / extrapolate bar for this frame ============== */ -void CG_AddLagometerFrameInfo( void ) { - int offset; +void CG_AddLagometerFrameInfo(void) { + int offset; offset = cg.time - cg.latestSnapshotTime; - lagometer.frameSamples[ lagometer.frameCount & ( LAG_SAMPLES - 1) ] = offset; + lagometer.frameSamples[lagometer.frameCount & (LAG_SAMPLES - 1)] = offset; lagometer.frameCount++; } @@ -4221,17 +3484,17 @@ the number of snapshots that were dropped before it. Pass NULL for a dropped packet. ============== */ -void CG_AddLagometerSnapshotInfo( snapshot_t *snap ) { +void CG_AddLagometerSnapshotInfo(snapshot_t *snap) { // dropped packet - if ( !snap ) { - lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = -1; + if (!snap) { + lagometer.snapshotSamples[lagometer.snapshotCount & (LAG_SAMPLES - 1)] = -1; lagometer.snapshotCount++; return; } // add this snapshot's info - lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->ping; - lagometer.snapshotFlags[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->snapFlags; + lagometer.snapshotSamples[lagometer.snapshotCount & (LAG_SAMPLES - 1)] = snap->ping; + lagometer.snapshotFlags[lagometer.snapshotCount & (LAG_SAMPLES - 1)] = snap->snapFlags; lagometer.snapshotCount++; } @@ -4242,66 +3505,63 @@ CG_DrawDisconnect Should we draw something different for long lag vs no packets? ============== */ -static void CG_DrawDisconnect( void ) { - float x, y; - int cmdNum; - usercmd_t cmd; - const char *s; - int w; // bk010215 - FIXME char message[1024]; - - if (cg.mMapChange) - { - s = CG_GetStringEdString("MP_INGAME", "SERVER_CHANGING_MAPS"); // s = "Server Changing Maps"; - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; - CG_DrawBigString( 320 - w/2, 100, s, 1.0F); - - s = CG_GetStringEdString("MP_INGAME", "PLEASE_WAIT"); // s = "Please wait..."; - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; - CG_DrawBigString( 320 - w/2, 200, s, 1.0F); +static void CG_DrawDisconnect(void) { + float x, y; + int cmdNum; + usercmd_t cmd; + const char *s; + int w; // bk010215 - FIXME char message[1024]; + + if (cg.mMapChange) { + s = CG_GetStringEdString("MP_INGAME", "SERVER_CHANGING_MAPS"); // s = "Server Changing Maps"; + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; + CG_DrawBigString(320 - w / 2, 100, s, 1.0F); + + s = CG_GetStringEdString("MP_INGAME", "PLEASE_WAIT"); // s = "Please wait..."; + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; + CG_DrawBigString(320 - w / 2, 200, s, 1.0F); return; } // draw the phone jack if we are completely past our buffers cmdNum = trap->GetCurrentCmdNumber() - CMD_BACKUP + 1; - trap->GetUserCmd( cmdNum, &cmd ); - if ( cmd.serverTime <= cg.snap->ps.commandTime - || cmd.serverTime > cg.time ) { // special check for map_restart // bk 0102165 - FIXME + trap->GetUserCmd(cmdNum, &cmd); + if (cmd.serverTime <= cg.snap->ps.commandTime || cmd.serverTime > cg.time) { // special check for map_restart // bk 0102165 - FIXME return; } // also add text in center of screen s = CG_GetStringEdString("MP_INGAME", "CONNECTION_INTERRUPTED"); // s = "Connection Interrupted"; // bk 010215 - FIXME - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; - CG_DrawBigString( 320 - w/2, 100, s, 1.0F); + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; + CG_DrawBigString(320 - w / 2, 100, s, 1.0F); // blink the icon - if ( ( cg.time >> 9 ) & 1 ) { + if ((cg.time >> 9) & 1) { return; } x = 640 - 48; y = 480 - 48; - CG_DrawPic( x, y, 48, 48, trap->R_RegisterShader("gfx/2d/net.tga" ) ); + CG_DrawPic(x, y, 48, 48, trap->R_RegisterShader("gfx/2d/net.tga")); } - -#define MAX_LAGOMETER_PING 900 -#define MAX_LAGOMETER_RANGE 300 +#define MAX_LAGOMETER_PING 900 +#define MAX_LAGOMETER_RANGE 300 /* ============== CG_DrawLagometer ============== */ -static void CG_DrawLagometer( void ) { - int a, x, y, i; - float v; - float ax, ay, aw, ah, mid, range; - int color; - float vscale; - - if ( !cg_lagometer.integer || cgs.localServer ) { +static void CG_DrawLagometer(void) { + int a, x, y, i; + float v; + float ax, ay, aw, ah, mid, range; + int color; + float vscale; + + if (!cg_lagometer.integer || cgs.localServer) { CG_DrawDisconnect(); return; } @@ -4312,8 +3572,8 @@ static void CG_DrawLagometer( void ) { x = 640 - 48; y = 480 - 144; - trap->R_SetColor( NULL ); - CG_DrawPic( x, y, 48, 48, cgs.media.lagometerShader ); + trap->R_SetColor(NULL); + CG_DrawPic(x, y, 48, 48, cgs.media.lagometerShader); ax = x; ay = y; @@ -4327,29 +3587,29 @@ static void CG_DrawLagometer( void ) { vscale = range / MAX_LAGOMETER_RANGE; // draw the frame interpoalte / extrapolate graph - for ( a = 0 ; a < aw ; a++ ) { - i = ( lagometer.frameCount - 1 - a ) & (LAG_SAMPLES - 1); + for (a = 0; a < aw; a++) { + i = (lagometer.frameCount - 1 - a) & (LAG_SAMPLES - 1); v = lagometer.frameSamples[i]; v *= vscale; - if ( v > 0 ) { - if ( color != 1 ) { + if (v > 0) { + if (color != 1) { color = 1; - trap->R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] ); + trap->R_SetColor(g_color_table[ColorIndex(COLOR_YELLOW)]); } - if ( v > range ) { + if (v > range) { v = range; } - trap->R_DrawStretchPic ( ax + aw - a, mid - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); - } else if ( v < 0 ) { - if ( color != 2 ) { + trap->R_DrawStretchPic(ax + aw - a, mid - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader); + } else if (v < 0) { + if (color != 2) { color = 2; - trap->R_SetColor( g_color_table[ColorIndex(COLOR_BLUE)] ); + trap->R_SetColor(g_color_table[ColorIndex(COLOR_BLUE)]); } v = -v; - if ( v > range ) { + if (v > range) { v = range; } - trap->R_DrawStretchPic( ax + aw - a, mid, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); + trap->R_DrawStretchPic(ax + aw - a, mid, 1, v, 0, 0, 0, 0, cgs.media.whiteShader); } } @@ -4357,67 +3617,61 @@ static void CG_DrawLagometer( void ) { range = ah / 2; vscale = range / MAX_LAGOMETER_PING; - for ( a = 0 ; a < aw ; a++ ) { - i = ( lagometer.snapshotCount - 1 - a ) & (LAG_SAMPLES - 1); + for (a = 0; a < aw; a++) { + i = (lagometer.snapshotCount - 1 - a) & (LAG_SAMPLES - 1); v = lagometer.snapshotSamples[i]; - if ( v > 0 ) { - if ( lagometer.snapshotFlags[i] & SNAPFLAG_RATE_DELAYED ) { - if ( color != 5 ) { - color = 5; // YELLOW for rate delay - trap->R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] ); + if (v > 0) { + if (lagometer.snapshotFlags[i] & SNAPFLAG_RATE_DELAYED) { + if (color != 5) { + color = 5; // YELLOW for rate delay + trap->R_SetColor(g_color_table[ColorIndex(COLOR_YELLOW)]); } } else { - if ( color != 3 ) { + if (color != 3) { color = 3; - trap->R_SetColor( g_color_table[ColorIndex(COLOR_GREEN)] ); + trap->R_SetColor(g_color_table[ColorIndex(COLOR_GREEN)]); } } v = v * vscale; - if ( v > range ) { + if (v > range) { v = range; } - trap->R_DrawStretchPic( ax + aw - a, ay + ah - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader ); - } else if ( v < 0 ) { - if ( color != 4 ) { - color = 4; // RED for dropped snapshots - trap->R_SetColor( g_color_table[ColorIndex(COLOR_RED)] ); + trap->R_DrawStretchPic(ax + aw - a, ay + ah - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader); + } else if (v < 0) { + if (color != 4) { + color = 4; // RED for dropped snapshots + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); } - trap->R_DrawStretchPic( ax + aw - a, ay + ah - range, 1, range, 0, 0, 0, 0, cgs.media.whiteShader ); + trap->R_DrawStretchPic(ax + aw - a, ay + ah - range, 1, range, 0, 0, 0, 0, cgs.media.whiteShader); } } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); - if ( cg_noPredict.integer || g_synchronousClients.integer ) { - CG_DrawBigString( ax, ay, "snc", 1.0 ); + if (cg_noPredict.integer || g_synchronousClients.integer) { + CG_DrawBigString(ax, ay, "snc", 1.0); } CG_DrawDisconnect(); } -void CG_DrawSiegeMessage( const char *str, int objectiveScreen ) -{ -// if (!( trap->Key_GetCatcher() & KEYCATCH_UI )) +void CG_DrawSiegeMessage(const char *str, int objectiveScreen) { + // if (!( trap->Key_GetCatcher() & KEYCATCH_UI )) { trap->OpenUIMenu(UIMENU_CLOSEALL); trap->Cvar_Set("cg_siegeMessage", str); - if (objectiveScreen) - { + if (objectiveScreen) { trap->OpenUIMenu(UIMENU_SIEGEOBJECTIVES); - } - else - { + } else { trap->OpenUIMenu(UIMENU_SIEGEMESSAGE); } } } -void CG_DrawSiegeMessageNonMenu( const char *str ) -{ - char text[1024]; - if (str[0]=='@') - { - trap->SE_GetStringTextString(str+1, text, sizeof(text)); +void CG_DrawSiegeMessageNonMenu(const char *str) { + char text[1024]; + if (str[0] == '@') { + trap->SE_GetStringTextString(str + 1, text, sizeof(text)); str = text; } CG_CenterPrint(str, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); @@ -4431,7 +3685,6 @@ CENTER PRINTING =============================================================================== */ - /* ============== CG_CenterPrint @@ -4440,13 +3693,13 @@ Called for important messages that should stay in the center of the screen for a few moments ============== */ -void CG_CenterPrint( const char *str, int y, int charWidth ) { - char *s; +void CG_CenterPrint(const char *str, int y, int charWidth) { + char *s; //[BugFix19] - int i = 0; + int i = 0; //[/BugFix19] - Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) ); + Q_strncpyz(cg.centerPrint, str, sizeof(cg.centerPrint)); cg.centerPrintTime = cg.time; cg.centerPrintY = y; @@ -4455,64 +3708,59 @@ void CG_CenterPrint( const char *str, int y, int charWidth ) { // count the number of lines for centering cg.centerPrintLines = 1; s = cg.centerPrint; - while( *s ) - { + while (*s) { //[BugFix19] i++; - if(i >= 50) - {//maxed out a line of text, this will make the line spill over onto another line. + if (i >= 50) { // maxed out a line of text, this will make the line spill over onto another line. i = 0; cg.centerPrintLines++; - } - else if (*s == '\n') - //if (*s == '\n') - //[/BugFix19] + } else if (*s == '\n') + // if (*s == '\n') + //[/BugFix19] cg.centerPrintLines++; s++; } } - /* =================== CG_DrawCenterString =================== */ -qboolean BG_IsWhiteSpace( char c ) -{//this function simply checks to see if the given character is whitespace. - if ( c == ' ' || c == '\n' || c == '\0' ) +qboolean BG_IsWhiteSpace(char c) { // this function simply checks to see if the given character is whitespace. + if (c == ' ' || c == '\n' || c == '\0') return qtrue; return qfalse; } -static void CG_DrawCenterString( void ) { - char *start; - int l; - int x, y, w; +static void CG_DrawCenterString(void) { + char *start; + int l; + int x, y, w; int h; - float *color; - const float scale = 1.0; //0.5 + float *color; + const float scale = 1.0; // 0.5 - if ( !cg.centerPrintTime ) { + if (!cg.centerPrintTime) { return; } - color = CG_FadeColor( cg.centerPrintTime, 1000 * cg_centerTime.value ); - if ( !color ) { + color = CG_FadeColor(cg.centerPrintTime, 1000 * cg_centerTime.value); + if (!color) { return; } - trap->R_SetColor( color ); + trap->R_SetColor(color); start = cg.centerPrint; y = cg.centerPrintY - cg.centerPrintLines * BIGCHAR_HEIGHT / 2; - while ( 1 ) { + while (1) { char linebuffer[1024]; - for ( l = 0; l < 50; l++ ) { - if ( !start[l] || start[l] == '\n' ) { + for (l = 0; l < 50; l++) { + if (!start[l] || start[l] == '\n') { break; } linebuffer[l] = start[l]; @@ -4520,22 +3768,19 @@ static void CG_DrawCenterString( void ) { linebuffer[l] = 0; //[BugFix19] - if(!BG_IsWhiteSpace(start[l]) && !BG_IsWhiteSpace(linebuffer[l-1]) ) - {//we might have cut a word off, attempt to find a spot where we won't cut words off at. + if (!BG_IsWhiteSpace(start[l]) && + !BG_IsWhiteSpace(linebuffer[l - 1])) { // we might have cut a word off, attempt to find a spot where we won't cut words off at. int savedL = l; - int counter = l-2; + int counter = l - 2; - for(; counter >= 0; counter--) - { - if(BG_IsWhiteSpace(start[counter])) - {//this location is whitespace, line break from this position + for (; counter >= 0; counter--) { + if (BG_IsWhiteSpace(start[counter])) { // this location is whitespace, line break from this position linebuffer[counter] = 0; l = counter + 1; break; } } - if(counter < 0) - {//couldn't find a break in the text, just go ahead and cut off the word mid-word. + if (counter < 0) { // couldn't find a break in the text, just go ahead and cut off the word mid-word. l = savedL; } } @@ -4548,28 +3793,24 @@ static void CG_DrawCenterString( void ) { y += h + 6; //[BugFix19] - //this method of advancing to new line from the start of the array was causing long lines without - //new lines to be totally truncated. - if(start[l] && start[l] == '\n') - {//next char is a newline, advance past + // this method of advancing to new line from the start of the array was causing long lines without + // new lines to be totally truncated. + if (start[l] && start[l] == '\n') { // next char is a newline, advance past l++; } - if ( !start[l] ) - {//end of string, we're done. + if (!start[l]) { // end of string, we're done. break; } - //advance pointer to the last character that we didn't read in. + // advance pointer to the last character that we didn't read in. start = &start[l]; //[/BugFix19] } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } - - /* ================================================================================ @@ -4578,12 +3819,11 @@ CROSSHAIR ================================================================================ */ -#define HEALTH_WIDTH 50.0f -#define HEALTH_HEIGHT 5.0f +#define HEALTH_WIDTH 50.0f +#define HEALTH_HEIGHT 5.0f -//see if we can draw some extra info on this guy based on our class -void CG_DrawSiegeInfo(centity_t *cent, float chX, float chY, float chW, float chH) -{ +// see if we can draw some extra info on this guy based on our class +void CG_DrawSiegeInfo(centity_t *cent, float chX, float chY, float chW, float chH) { siegeExtended_t *se = &cg_siegeExtendedData[cent->currentState.number]; clientInfo_t *ci; const char *configstring, *v; @@ -4597,258 +3837,232 @@ void CG_DrawSiegeInfo(centity_t *cent, float chX, float chY, float chW, float ch assert(cent->currentState.number < MAX_CLIENTS); - if (se->lastUpdated > cg.time) - { //strange, shouldn't happen + if (se->lastUpdated > cg.time) { // strange, shouldn't happen return; } - if ((cg.time - se->lastUpdated) > 10000) - { //if you haven't received a status update on this guy in 10 seconds, forget about it + if ((cg.time - se->lastUpdated) > 10000) { // if you haven't received a status update on this guy in 10 seconds, forget about it return; } - if (cent->currentState.eFlags & EF_DEAD) - { //he's dead, don't display info on him + if (cent->currentState.eFlags & EF_DEAD) { // he's dead, don't display info on him return; } - if (cent->currentState.weapon != se->weapon) - { //data is invalidated until it syncs back again + if (cent->currentState.weapon != se->weapon) { // data is invalidated until it syncs back again return; } ci = &cgs.clientinfo[cent->currentState.number]; - if (ci->team != cg.predictedPlayerState.persistant[PERS_TEAM]) - { //not on the same team + if (ci->team != cg.predictedPlayerState.persistant[PERS_TEAM]) { // not on the same team return; } - configstring = CG_ConfigString( cg.predictedPlayerState.clientNum + CS_PLAYERS ); - v = Info_ValueForKey( configstring, "siegeclass" ); + configstring = CG_ConfigString(cg.predictedPlayerState.clientNum + CS_PLAYERS); + v = Info_ValueForKey(configstring, "siegeclass"); - if (!v || !v[0]) - { //don't have siege class in info? + if (!v || !v[0]) { // don't have siege class in info? return; } siegeClass = BG_SiegeFindClassByName(v); - if (!siegeClass) - { //invalid + if (!siegeClass) { // invalid return; } - if (!(siegeClass->classflags & (1<classflags & (1 << CFL_STATVIEWER))) { // doesn't really have the ability to see others' stats return; } - x = chX+((chW/2)-(HEALTH_WIDTH/2)); - y = (chY+chH) + 8.0f; - percent = ((float)se->health/(float)se->maxhealth)*HEALTH_WIDTH; + x = chX + ((chW / 2) - (HEALTH_WIDTH / 2)); + y = (chY + chH) + 8.0f; + percent = ((float)se->health / (float)se->maxhealth) * HEALTH_WIDTH; - //color of the bar + // color of the bar aColor[0] = 0.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - //color of greyed out "missing health" + // color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); - - //then draw the other part greyed out - CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f, percent - 1.0f, HEALTH_HEIGHT - 1.0f, aColor); + // then draw the other part greyed out + CG_FillRect(x + percent, y + 1.0f, HEALTH_WIDTH - percent - 1.0f, HEALTH_HEIGHT - 1.0f, cColor); - //now draw his ammo + // now draw his ammo ammoMax = ammoData[weaponData[cent->currentState.weapon].ammoIndex].max; - if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) ) - { + if ((cent->currentState.eFlags & EF_DOUBLE_AMMO)) { ammoMax *= 2; } - x = chX+((chW/2)-(HEALTH_WIDTH/2)); - y = (chY+chH) + HEALTH_HEIGHT + 10.0f; + x = chX + ((chW / 2) - (HEALTH_WIDTH / 2)); + y = (chY + chH) + HEALTH_HEIGHT + 10.0f; if (!weaponData[cent->currentState.weapon].energyPerShot && - !weaponData[cent->currentState.weapon].altEnergyPerShot) - { //a weapon that takes no ammo, so show full + !weaponData[cent->currentState.weapon].altEnergyPerShot) { // a weapon that takes no ammo, so show full percent = HEALTH_WIDTH; - } - else - { - percent = ((float)se->ammo/(float)ammoMax)*HEALTH_WIDTH; + } else { + percent = ((float)se->ammo / (float)ammoMax) * HEALTH_WIDTH; } - //color of the bar + // color of the bar aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - //color of greyed out "missing health" + // color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f, percent - 1.0f, HEALTH_HEIGHT - 1.0f, aColor); - //then draw the other part greyed out - CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); + // then draw the other part greyed out + CG_FillRect(x + percent, y + 1.0f, HEALTH_WIDTH - percent - 1.0f, HEALTH_HEIGHT - 1.0f, cColor); } -//draw the health bar based on current "health" and maxhealth -void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) -{ +// draw the health bar based on current "health" and maxhealth +void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t cColor; - float x = chX+((chW/2)-(HEALTH_WIDTH/2)); - float y = (chY+chH) + 8.0f; - float percent = ((float)cent->currentState.health/(float)cent->currentState.maxhealth)*HEALTH_WIDTH; - if (percent <= 0) - { + float x = chX + ((chW / 2) - (HEALTH_WIDTH / 2)); + float y = (chY + chH) + 8.0f; + float percent = ((float)cent->currentState.health / (float)cent->currentState.maxhealth) * HEALTH_WIDTH; + if (percent <= 0) { return; } - //color of the bar - if (!cent->currentState.teamowner || cgs.gametype < GT_TEAM) - { //not owned by a team or teamplay + // color of the bar + if (!cent->currentState.teamowner || cgs.gametype < GT_TEAM) { // not owned by a team or teamplay aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - } - else if (cent->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) - { //owned by my team + } else if (cent->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) { // owned by my team aColor[0] = 0.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - } - else - { //hostile + } else { // hostile aColor[0] = 1.0f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; } - //color of greyed out "missing health" + // color of greyed out "missing health" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.4f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f, percent - 1.0f, HEALTH_HEIGHT - 1.0f, aColor); - //then draw the other part greyed out - CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); + // then draw the other part greyed out + CG_FillRect(x + percent, y + 1.0f, HEALTH_WIDTH - percent - 1.0f, HEALTH_HEIGHT - 1.0f, cColor); } -//same routine (at least for now), draw progress of a "hack" or whatever -void CG_DrawHaqrBar(float chX, float chY, float chW, float chH) -{ +// same routine (at least for now), draw progress of a "hack" or whatever +void CG_DrawHaqrBar(float chX, float chY, float chW, float chH) { vec4_t aColor; vec4_t cColor; - float x = chX+((chW/2)-(HEALTH_WIDTH/2)); - float y = (chY+chH) + 8.0f; - float percent = (((float)cg.predictedPlayerState.hackingTime-(float)cg.time)/(float)cg.predictedPlayerState.hackingBaseTime)*HEALTH_WIDTH; + float x = chX + ((chW / 2) - (HEALTH_WIDTH / 2)); + float y = (chY + chH) + 8.0f; + float percent = (((float)cg.predictedPlayerState.hackingTime - (float)cg.time) / (float)cg.predictedPlayerState.hackingBaseTime) * HEALTH_WIDTH; - if (percent > HEALTH_WIDTH || - percent < 1.0f) - { + if (percent > HEALTH_WIDTH || percent < 1.0f) { return; } - //color of the bar + // color of the bar aColor[0] = 1.0f; aColor[1] = 1.0f; aColor[2] = 0.0f; aColor[3] = 0.4f; - //color of greyed out done area + // color of greyed out done area cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f, percent - 1.0f, HEALTH_HEIGHT - 1.0f, aColor); - //then draw the other part greyed out - CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor); + // then draw the other part greyed out + CG_FillRect(x + percent, y + 1.0f, HEALTH_WIDTH - percent - 1.0f, HEALTH_HEIGHT - 1.0f, cColor); - //draw the hacker icon - CG_DrawPic(x, y-HEALTH_WIDTH, HEALTH_WIDTH, HEALTH_WIDTH, cgs.media.hackerIconShader); + // draw the hacker icon + CG_DrawPic(x, y - HEALTH_WIDTH, HEALTH_WIDTH, HEALTH_WIDTH, cgs.media.hackerIconShader); } -//generic timing bar +// generic timing bar int cg_genericTimerBar = 0; int cg_genericTimerDur = 0; vec4_t cg_genericTimerColor; -#define CGTIMERBAR_H 50.0f -#define CGTIMERBAR_W 10.0f -#define CGTIMERBAR_X (SCREEN_WIDTH-CGTIMERBAR_W-120.0f) -#define CGTIMERBAR_Y (SCREEN_HEIGHT-CGTIMERBAR_H-20.0f) -void CG_DrawGenericTimerBar(void) -{ +#define CGTIMERBAR_H 50.0f +#define CGTIMERBAR_W 10.0f +#define CGTIMERBAR_X (SCREEN_WIDTH - CGTIMERBAR_W - 120.0f) +#define CGTIMERBAR_Y (SCREEN_HEIGHT - CGTIMERBAR_H - 20.0f) +void CG_DrawGenericTimerBar(void) { vec4_t aColor; vec4_t cColor; float x = CGTIMERBAR_X; float y = CGTIMERBAR_Y; - float percent = ((float)(cg_genericTimerBar-cg.time)/(float)cg_genericTimerDur)*CGTIMERBAR_H; + float percent = ((float)(cg_genericTimerBar - cg.time) / (float)cg_genericTimerDur) * CGTIMERBAR_H; - if (percent > CGTIMERBAR_H) - { + if (percent > CGTIMERBAR_H) { return; } - if (percent < 0.1f) - { + if (percent < 0.1f) { percent = 0.1f; } - //color of the bar + // color of the bar aColor[0] = cg_genericTimerColor[0]; aColor[1] = cg_genericTimerColor[1]; aColor[2] = cg_genericTimerColor[2]; aColor[3] = cg_genericTimerColor[3]; - //color of greyed out "missing fuel" + // color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, CGTIMERBAR_W, CGTIMERBAR_H, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f+(CGTIMERBAR_H-percent), CGTIMERBAR_W-2.0f, CGTIMERBAR_H-1.0f-(CGTIMERBAR_H-percent), aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f + (CGTIMERBAR_H - percent), CGTIMERBAR_W - 2.0f, CGTIMERBAR_H - 1.0f - (CGTIMERBAR_H - percent), aColor); - //then draw the other part greyed out - CG_FillRect(x+1.0f, y+1.0f, CGTIMERBAR_W-2.0f, CGTIMERBAR_H-percent, cColor); + // then draw the other part greyed out + CG_FillRect(x + 1.0f, y + 1.0f, CGTIMERBAR_W - 2.0f, CGTIMERBAR_H - percent, cColor); } /* @@ -4859,315 +4073,232 @@ CG_DrawCrosshair float cg_crosshairPrevPosX = 0; float cg_crosshairPrevPosY = 0; -#define CRAZY_CROSSHAIR_MAX_ERROR_X (100.0f*640.0f/480.0f) -#define CRAZY_CROSSHAIR_MAX_ERROR_Y (100.0f) -void CG_LerpCrosshairPos( float *x, float *y ) -{ - if ( cg_crosshairPrevPosX ) - {//blend from old pos - float maxMove = 30.0f * ((float)cg.frametime/500.0f) * 640.0f/480.0f; +#define CRAZY_CROSSHAIR_MAX_ERROR_X (100.0f * 640.0f / 480.0f) +#define CRAZY_CROSSHAIR_MAX_ERROR_Y (100.0f) +void CG_LerpCrosshairPos(float *x, float *y) { + if (cg_crosshairPrevPosX) { // blend from old pos + float maxMove = 30.0f * ((float)cg.frametime / 500.0f) * 640.0f / 480.0f; float xDiff = (*x - cg_crosshairPrevPosX); - if ( fabs(xDiff) > CRAZY_CROSSHAIR_MAX_ERROR_X ) - { + if (fabs(xDiff) > CRAZY_CROSSHAIR_MAX_ERROR_X) { maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X; } - if ( xDiff > maxMove ) - { + if (xDiff > maxMove) { *x = cg_crosshairPrevPosX + maxMove; - } - else if ( xDiff < -maxMove ) - { + } else if (xDiff < -maxMove) { *x = cg_crosshairPrevPosX - maxMove; } } cg_crosshairPrevPosX = *x; - if ( cg_crosshairPrevPosY ) - {//blend from old pos - float maxMove = 30.0f * ((float)cg.frametime/500.0f); + if (cg_crosshairPrevPosY) { // blend from old pos + float maxMove = 30.0f * ((float)cg.frametime / 500.0f); float yDiff = (*y - cg_crosshairPrevPosY); - if ( fabs(yDiff) > CRAZY_CROSSHAIR_MAX_ERROR_Y ) - { + if (fabs(yDiff) > CRAZY_CROSSHAIR_MAX_ERROR_Y) { maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X; } - if ( yDiff > maxMove ) - { + if (yDiff > maxMove) { *y = cg_crosshairPrevPosY + maxMove; - } - else if ( yDiff < -maxMove ) - { + } else if (yDiff < -maxMove) { *y = cg_crosshairPrevPosY - maxMove; } } cg_crosshairPrevPosY = *y; } -vec3_t cg_crosshairPos={0,0,0}; -static void CG_DrawCrosshair( vec3_t worldPoint, int chEntValid ) { - float w, h; - qhandle_t hShader = 0; - float f; - float x, y; - qboolean corona = qfalse; - vec4_t ecolor = {0,0,0,0}; - centity_t *crossEnt = NULL; - float chX, chY; - - if ( worldPoint ) - { - VectorCopy( worldPoint, cg_crosshairPos ); +vec3_t cg_crosshairPos = {0, 0, 0}; +static void CG_DrawCrosshair(vec3_t worldPoint, int chEntValid) { + float w, h; + qhandle_t hShader = 0; + float f; + float x, y; + qboolean corona = qfalse; + vec4_t ecolor = {0, 0, 0, 0}; + centity_t *crossEnt = NULL; + float chX, chY; + + if (worldPoint) { + VectorCopy(worldPoint, cg_crosshairPos); } - if ( !cg_drawCrosshair.integer ) - { + if (!cg_drawCrosshair.integer) { return; } - if (cg.snap->ps.fallingToDeath) - { + if (cg.snap->ps.fallingToDeath) { return; } - if ( cg.predictedPlayerState.zoomMode != 0 ) - {//not while scoped + if (cg.predictedPlayerState.zoomMode != 0) { // not while scoped return; } - if ( cg_crosshairHealth.integer ) - { - vec4_t hcolor; + if (cg_crosshairHealth.integer) { + vec4_t hcolor; - CG_ColorForHealth( hcolor ); - trap->R_SetColor( hcolor ); - } - else - { - //set color based on what kind of ent is under crosshair - if ( cg.crosshairClientNum >= ENTITYNUM_WORLD ) - { - trap->R_SetColor( NULL ); + CG_ColorForHealth(hcolor); + trap->R_SetColor(hcolor); + } else { + // set color based on what kind of ent is under crosshair + if (cg.crosshairClientNum >= ENTITYNUM_WORLD) { + trap->R_SetColor(NULL); } - //rwwFIXMEFIXME: Write this a different way, it's getting a bit too sloppy looking + // rwwFIXMEFIXME: Write this a different way, it's getting a bit too sloppy looking else if (chEntValid && - (cg_entities[cg.crosshairClientNum].currentState.number < MAX_CLIENTS || - cg_entities[cg.crosshairClientNum].currentState.eType == ET_NPC || - cg_entities[cg.crosshairClientNum].currentState.shouldtarget || - cg_entities[cg.crosshairClientNum].currentState.health || //always show ents with health data under crosshair - (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER) || - (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.teamowner))) - { + (cg_entities[cg.crosshairClientNum].currentState.number < MAX_CLIENTS || cg_entities[cg.crosshairClientNum].currentState.eType == ET_NPC || + cg_entities[cg.crosshairClientNum].currentState.shouldtarget || + cg_entities[cg.crosshairClientNum].currentState.health || // always show ents with health data under crosshair + (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.bolt1 && + cg.predictedPlayerState.weapon == WP_SABER) || + (cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.teamowner))) { crossEnt = &cg_entities[cg.crosshairClientNum]; - if ( crossEnt->currentState.powerups & (1 <currentState.number < MAX_CLIENTS ) - { - if (cgs.gametype >= GT_TEAM && - cgs.clientinfo[crossEnt->currentState.number].team == cgs.clientinfo[cg.snap->ps.clientNum].team ) - { - //Allies are green - ecolor[0] = 0.0;//R - ecolor[1] = 1.0;//G - ecolor[2] = 0.0;//B - } - else - { + if (crossEnt->currentState.powerups & (1 << PW_CLOAKED)) { // don't show up for cloaked guys + ecolor[0] = 1.0; // R + ecolor[1] = 1.0; // G + ecolor[2] = 1.0; // B + } else if (crossEnt->currentState.number < MAX_CLIENTS) { + if (cgs.gametype >= GT_TEAM && cgs.clientinfo[crossEnt->currentState.number].team == cgs.clientinfo[cg.snap->ps.clientNum].team) { + // Allies are green + ecolor[0] = 0.0; // R + ecolor[1] = 1.0; // G + ecolor[2] = 0.0; // B + } else { if (cgs.gametype == GT_POWERDUEL && - cgs.clientinfo[crossEnt->currentState.number].duelTeam == cgs.clientinfo[cg.snap->ps.clientNum].duelTeam) - { //on the same duel team in powerduel, so he's a friend - ecolor[0] = 0.0;//R - ecolor[1] = 1.0;//G - ecolor[2] = 0.0;//B - } - else - { //Enemies are red - ecolor[0] = 1.0;//R - ecolor[1] = 0.0;//G - ecolor[2] = 0.0;//B + cgs.clientinfo[crossEnt->currentState.number].duelTeam == + cgs.clientinfo[cg.snap->ps.clientNum].duelTeam) { // on the same duel team in powerduel, so he's a friend + ecolor[0] = 0.0; // R + ecolor[1] = 1.0; // G + ecolor[2] = 0.0; // B + } else { // Enemies are red + ecolor[0] = 1.0; // R + ecolor[1] = 0.0; // G + ecolor[2] = 0.0; // B } } - if (cg.snap->ps.duelInProgress) - { - if (crossEnt->currentState.number != cg.snap->ps.duelIndex) - { //grey out crosshair for everyone but your foe if you're in a duel + if (cg.snap->ps.duelInProgress) { + if (crossEnt->currentState.number != cg.snap->ps.duelIndex) { // grey out crosshair for everyone but your foe if you're in a duel ecolor[0] = 0.4f; ecolor[1] = 0.4f; ecolor[2] = 0.4f; } - } - else if (crossEnt->currentState.bolt1) - { //this fellow is in a duel. We just checked if we were in a duel above, so - //this means we aren't and he is. Which of course means our crosshair greys out over him. + } else if (crossEnt->currentState.bolt1) { // this fellow is in a duel. We just checked if we were in a duel above, so + // this means we aren't and he is. Which of course means our crosshair greys out over him. ecolor[0] = 0.4f; ecolor[1] = 0.4f; ecolor[2] = 0.4f; } - } - else if (crossEnt->currentState.shouldtarget || crossEnt->currentState.eType == ET_NPC) - { - //VectorCopy( crossEnt->startRGBA, ecolor ); - if ( !ecolor[0] && !ecolor[1] && !ecolor[2] ) - { + } else if (crossEnt->currentState.shouldtarget || crossEnt->currentState.eType == ET_NPC) { + // VectorCopy( crossEnt->startRGBA, ecolor ); + if (!ecolor[0] && !ecolor[1] && !ecolor[2]) { // We really don't want black, so set it to yellow - ecolor[0] = 1.0f;//R - ecolor[1] = 0.8f;//G - ecolor[2] = 0.3f;//B + ecolor[0] = 1.0f; // R + ecolor[1] = 0.8f; // G + ecolor[2] = 0.3f; // B } - if (crossEnt->currentState.eType == ET_NPC) - { + if (crossEnt->currentState.eType == ET_NPC) { int plTeam; - if (cgs.gametype == GT_SIEGE) - { + if (cgs.gametype == GT_SIEGE) { plTeam = cg.predictedPlayerState.persistant[PERS_TEAM]; - } - else - { + } else { plTeam = NPCTEAM_PLAYER; } - if ( crossEnt->currentState.powerups & (1 <currentState.teamowner ) - { //not on a team - if (!crossEnt->currentState.teamowner || - crossEnt->currentState.NPC_class == CLASS_VEHICLE) - { //neutral - if (crossEnt->currentState.owner < MAX_CLIENTS) - { //base color on who is pilotting this thing + if (crossEnt->currentState.powerups & (1 << PW_CLOAKED)) { + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 1.0f; // B + } else if (!crossEnt->currentState.teamowner) { // not on a team + if (!crossEnt->currentState.teamowner || crossEnt->currentState.NPC_class == CLASS_VEHICLE) { // neutral + if (crossEnt->currentState.owner < MAX_CLIENTS) { // base color on who is pilotting this thing clientInfo_t *ci = &cgs.clientinfo[crossEnt->currentState.owner]; - if (cgs.gametype >= GT_TEAM && ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) - { //friendly - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else - { //hostile - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B + if (cgs.gametype >= GT_TEAM && ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) { // friendly + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else { // hostile + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B } + } else { // unmanned + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B } - else - { //unmanned - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - } - else - { - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B + } else { + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B } + } else if (crossEnt->currentState.teamowner != plTeam) { // on enemy team + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B + } else { // a friend + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B } - else if ( crossEnt->currentState.teamowner != plTeam ) - {// on enemy team - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B - } - else - { //a friend - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - } - else if ( crossEnt->currentState.teamowner == TEAM_RED - || crossEnt->currentState.teamowner == TEAM_BLUE ) - { - if (cgs.gametype < GT_TEAM) - { //not teamplay, just neutral then - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else if ( crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team ) - { //on the enemy team - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B - } - else - { //on my team - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B + } else if (crossEnt->currentState.teamowner == TEAM_RED || crossEnt->currentState.teamowner == TEAM_BLUE) { + if (cgs.gametype < GT_TEAM) { // not teamplay, just neutral then + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else if (crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team) { // on the enemy team + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B + } else { // on my team + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B } + } else if (crossEnt->currentState.owner == cg.snap->ps.clientNum || + (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner == cgs.clientinfo[cg.snap->ps.clientNum].team)) { + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else if (crossEnt->currentState.teamowner == 16 || (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner && + crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team)) { + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B } - else if (crossEnt->currentState.owner == cg.snap->ps.clientNum || - (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner == cgs.clientinfo[cg.snap->ps.clientNum].team)) - { - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else if (crossEnt->currentState.teamowner == 16 || - (cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner && crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team)) - { - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B - } - } - else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER) - { //can push/pull this mover. Only show it if we're using the saber. + } else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.bolt1 && + cg.predictedPlayerState.weapon == WP_SABER) { // can push/pull this mover. Only show it if we're using the saber. ecolor[0] = 0.2f; ecolor[1] = 0.5f; ecolor[2] = 1.0f; corona = qtrue; - } - else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.teamowner) - { //a team owns this - if it's my team green, if not red, if not teamplay then yellow - if (cgs.gametype < GT_TEAM) - { - ecolor[0] = 1.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - else if (cg.predictedPlayerState.persistant[PERS_TEAM] != crossEnt->currentState.teamowner) - { //not my team - ecolor[0] = 1.0f;//R - ecolor[1] = 0.0f;//G - ecolor[2] = 0.0f;//B + } else if (crossEnt->currentState.eType == ET_MOVER && + crossEnt->currentState.teamowner) { // a team owns this - if it's my team green, if not red, if not teamplay then yellow + if (cgs.gametype < GT_TEAM) { + ecolor[0] = 1.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B + } else if (cg.predictedPlayerState.persistant[PERS_TEAM] != crossEnt->currentState.teamowner) { // not my team + ecolor[0] = 1.0f; // R + ecolor[1] = 0.0f; // G + ecolor[2] = 0.0f; // B + } else { // my team + ecolor[0] = 0.0f; // R + ecolor[1] = 1.0f; // G + ecolor[2] = 0.0f; // B } - else - { //my team - ecolor[0] = 0.0f;//R - ecolor[1] = 1.0f;//G - ecolor[2] = 0.0f;//B - } - } - else if (crossEnt->currentState.health) - { - if (!crossEnt->currentState.teamowner || cgs.gametype < GT_TEAM) - { //not owned by a team or teamplay + } else if (crossEnt->currentState.health) { + if (!crossEnt->currentState.teamowner || cgs.gametype < GT_TEAM) { // not owned by a team or teamplay ecolor[0] = 1.0f; ecolor[1] = 1.0f; ecolor[2] = 0.0f; - } - else if (crossEnt->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) - { //owned by my team + } else if (crossEnt->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM]) { // owned by my team ecolor[0] = 0.0f; ecolor[1] = 1.0f; ecolor[2] = 0.0f; - } - else - { //hostile + } else { // hostile ecolor[0] = 1.0f; ecolor[1] = 0.0f; ecolor[2] = 0.0f; @@ -5176,151 +4307,125 @@ static void CG_DrawCrosshair( vec3_t worldPoint, int chEntValid ) { ecolor[3] = 1.0f; - trap->R_SetColor( ecolor ); + trap->R_SetColor(ecolor); } } - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//I'm in a vehicle + if (cg.predictedPlayerState.m_iVehicleNum) { // I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( vehCent - && vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo - && vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle ) - { + if (vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle) { hShader = vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle; } - //bigger by default - w = cg_crosshairSize.value*2.0f; + // bigger by default + w = cg_crosshairSize.value * 2.0f; h = w; - } - else - { + } else { w = h = cg_crosshairSize.value; } // pulse the size of the crosshair when picking up items f = cg.time - cg.itemPickupBlendTime; - if ( f > 0 && f < ITEM_BLOB_TIME ) { + if (f > 0 && f < ITEM_BLOB_TIME) { f /= ITEM_BLOB_TIME; - w *= ( 1 + f ); - h *= ( 1 + f ); + w *= (1 + f); + h *= (1 + f); } - if ( worldPoint && VectorLength( worldPoint ) ) - { - if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) ) - {//off screen, don't draw it + if (worldPoint && VectorLength(worldPoint)) { + if (!CG_WorldCoordToScreenCoordFloat(worldPoint, &x, &y)) { // off screen, don't draw it return; } - //CG_LerpCrosshairPos( &x, &y ); - x -= 320; - y -= 240; - } - else - { + // CG_LerpCrosshairPos( &x, &y ); + x -= 320; + y -= 240; + } else { x = cg_crosshairX.integer; y = cg_crosshairY.integer; } - if ( !hShader ) - { - hShader = cgs.media.crosshairShader[Com_Clampi( 1, NUM_CROSSHAIRS, cg_drawCrosshair.integer ) - 1]; + if (!hShader) { + hShader = cgs.media.crosshairShader[Com_Clampi(1, NUM_CROSSHAIRS, cg_drawCrosshair.integer) - 1]; } chX = x + cg.refdef.x + 0.5 * (640 - w); chY = y + cg.refdef.y + 0.5 * (480 - h); - trap->R_DrawStretchPic( chX, chY, w, h, 0, 0, 1, 1, hShader ); + trap->R_DrawStretchPic(chX, chY, w, h, 0, 0, 1, 1, hShader); - //draw a health bar directly under the crosshair if we're looking at something - //that takes damage - if (crossEnt && - crossEnt->currentState.maxhealth) - { + // draw a health bar directly under the crosshair if we're looking at something + // that takes damage + if (crossEnt && crossEnt->currentState.maxhealth) { CG_DrawHealthBar(crossEnt, chX, chY, w, h); - chY += HEALTH_HEIGHT*2; - } - else if (crossEnt && crossEnt->currentState.number < MAX_CLIENTS) - { - if (cgs.gametype == GT_SIEGE) - { + chY += HEALTH_HEIGHT * 2; + } else if (crossEnt && crossEnt->currentState.number < MAX_CLIENTS) { + if (cgs.gametype == GT_SIEGE) { CG_DrawSiegeInfo(crossEnt, chX, chY, w, h); - chY += HEALTH_HEIGHT*4; + chY += HEALTH_HEIGHT * 4; } - if (cg.crosshairVehNum && cg.time == cg.crosshairVehTime) - { //it was in the crosshair this frame + if (cg.crosshairVehNum && cg.time == cg.crosshairVehTime) { // it was in the crosshair this frame centity_t *hisVeh = &cg_entities[cg.crosshairVehNum]; - if (hisVeh->currentState.eType == ET_NPC && - hisVeh->currentState.NPC_class == CLASS_VEHICLE && - hisVeh->currentState.maxhealth && - hisVeh->m_pVehicle) - { //draw the health for this vehicle + if (hisVeh->currentState.eType == ET_NPC && hisVeh->currentState.NPC_class == CLASS_VEHICLE && hisVeh->currentState.maxhealth && + hisVeh->m_pVehicle) { // draw the health for this vehicle CG_DrawHealthBar(hisVeh, chX, chY, w, h); - chY += HEALTH_HEIGHT*2; + chY += HEALTH_HEIGHT * 2; } } } - if (cg.predictedPlayerState.hackingTime) - { //hacking something + if (cg.predictedPlayerState.hackingTime) { // hacking something CG_DrawHaqrBar(chX, chY, w, h); } - if (cg_genericTimerBar > cg.time) - { //draw generic timing bar, can be used for whatever + if (cg_genericTimerBar > cg.time) { // draw generic timing bar, can be used for whatever CG_DrawGenericTimerBar(); } - if ( corona ) // drawing extra bits + if (corona) // drawing extra bits { ecolor[3] = 0.5f; - ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color + ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * (sin(cg.time * 0.001f) * 0.08f + 0.35f); // don't draw full color ecolor[3] = 1.0f; - trap->R_SetColor( ecolor ); + trap->R_SetColor(ecolor); w *= 2.0f; h *= 2.0f; - trap->R_DrawStretchPic( x + cg.refdef.x + 0.5 * (640 - w), - y + cg.refdef.y + 0.5 * (480 - h), - w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader ); + trap->R_DrawStretchPic(x + cg.refdef.x + 0.5 * (640 - w), y + cg.refdef.y + 0.5 * (480 - h), w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader); } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } -qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) -{ - vec3_t trans; - float xc, yc; - float px, py; - float z; +qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { + vec3_t trans; + float xc, yc; + float px, py; + float z; - px = tan(cg.refdef.fov_x * (M_PI / 360) ); - py = tan(cg.refdef.fov_y * (M_PI / 360) ); + px = tan(cg.refdef.fov_x * (M_PI / 360)); + py = tan(cg.refdef.fov_y * (M_PI / 360)); - VectorSubtract(worldCoord, cg.refdef.vieworg, trans); + VectorSubtract(worldCoord, cg.refdef.vieworg, trans); - xc = 640 / 2.0; - yc = 480 / 2.0; + xc = 640 / 2.0; + yc = 480 / 2.0; // z = how far is the object in our forward direction - z = DotProduct(trans, cg.refdef.viewaxis[0]); - if (z <= 0.001) - return qfalse; + z = DotProduct(trans, cg.refdef.viewaxis[0]); + if (z <= 0.001) + return qfalse; - *x = xc - DotProduct(trans, cg.refdef.viewaxis[1])*xc/(z*px); - *y = yc - DotProduct(trans, cg.refdef.viewaxis[2])*yc/(z*py); + *x = xc - DotProduct(trans, cg.refdef.viewaxis[1]) * xc / (z * px); + *y = yc - DotProduct(trans, cg.refdef.viewaxis[2]) * yc / (z * py); - return qtrue; + return qtrue; } -qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) { +qboolean CG_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) { float xF, yF; - if ( CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ) ) { + if (CG_WorldCoordToScreenCoordFloat(worldCoord, &xF, &yF)) { *x = (int)xF; *y = (int)yF; return qtrue; @@ -5336,38 +4441,34 @@ CG_SaberClashFlare */ int cg_saberFlashTime = 0; vec3_t cg_saberFlashPos = {0, 0, 0}; -void CG_SaberClashFlare( void ) -{ - int t, maxTime = 150; +void CG_SaberClashFlare(void) { + int t, maxTime = 150; vec3_t dif; vec4_t color; - int x,y; + int x, y; float v, len; trace_t tr; t = cg.time - cg_saberFlashTime; - if ( t <= 0 || t >= maxTime ) - { + if (t <= 0 || t >= maxTime) { return; } // Don't do clashes for things that are behind us - VectorSubtract( cg_saberFlashPos, cg.refdef.vieworg, dif ); + VectorSubtract(cg_saberFlashPos, cg.refdef.vieworg, dif); - if ( DotProduct( dif, cg.refdef.viewaxis[0] ) < 0.2 ) - { + if (DotProduct(dif, cg.refdef.viewaxis[0]) < 0.2) { return; } - CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cg_saberFlashPos, -1, CONTENTS_SOLID ); + CG_Trace(&tr, cg.refdef.vieworg, NULL, NULL, cg_saberFlashPos, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f ) - { + if (tr.fraction < 1.0f) { return; } - len = VectorNormalize( dif ); + len = VectorNormalize(dif); // clamp to a known range /* @@ -5376,235 +4477,197 @@ void CG_SaberClashFlare( void ) len = 800; } */ - if ( len > 1200 ) - { + if (len > 1200) { return; } - v = ( 1.0f - ((float)t / maxTime )) * ((1.0f - ( len / 800.0f )) * 2.0f + 0.35f); - if (v < 0.001f) - { + v = (1.0f - ((float)t / maxTime)) * ((1.0f - (len / 800.0f)) * 2.0f + 0.35f); + if (v < 0.001f) { v = 0.001f; } - if ( !CG_WorldCoordToScreenCoord( cg_saberFlashPos, &x, &y ) ) { + if (!CG_WorldCoordToScreenCoord(cg_saberFlashPos, &x, &y)) { return; } - VectorSet4( color, 0.8f, 0.8f, 0.8f, 1.0f ); - trap->R_SetColor( color ); + VectorSet4(color, 0.8f, 0.8f, 0.8f, 1.0f); + trap->R_SetColor(color); - CG_DrawPic( x - ( v * 300 ), y - ( v * 300 ), - v * 600, v * 600, - trap->R_RegisterShader( "gfx/effects/saberFlare" )); + CG_DrawPic(x - (v * 300), y - (v * 300), v * 600, v * 600, trap->R_RegisterShader("gfx/effects/saberFlare")); } -void CG_DottedLine( float x1, float y1, float x2, float y2, float dotSize, int numDots, vec4_t color, float alpha ) -{ +void CG_DottedLine(float x1, float y1, float x2, float y2, float dotSize, int numDots, vec4_t color, float alpha) { float x, y, xDiff, yDiff, xStep, yStep; vec4_t colorRGBA; int dotNum = 0; - VectorCopy4( color, colorRGBA ); + VectorCopy4(color, colorRGBA); colorRGBA[3] = alpha; - trap->R_SetColor( colorRGBA ); + trap->R_SetColor(colorRGBA); - xDiff = x2-x1; - yDiff = y2-y1; - xStep = xDiff/(float)numDots; - yStep = yDiff/(float)numDots; + xDiff = x2 - x1; + yDiff = y2 - y1; + xStep = xDiff / (float)numDots; + yStep = yDiff / (float)numDots; - for ( dotNum = 0; dotNum < numDots; dotNum++ ) - { - x = x1 + (xStep*dotNum) - (dotSize*0.5f); - y = y1 + (yStep*dotNum) - (dotSize*0.5f); + for (dotNum = 0; dotNum < numDots; dotNum++) { + x = x1 + (xStep * dotNum) - (dotSize * 0.5f); + y = y1 + (yStep * dotNum) - (dotSize * 0.5f); - CG_DrawPic( x, y, dotSize, dotSize, cgs.media.whiteShader ); + CG_DrawPic(x, y, dotSize, dotSize, cgs.media.whiteShader); } } -void CG_BracketEntity( centity_t *cent, float radius ) -{ +void CG_BracketEntity(centity_t *cent, float radius) { trace_t tr; vec3_t dif; - float len, size, lineLength, lineWidth; - float x, y; + float len, size, lineLength, lineWidth; + float x, y; clientInfo_t *local; qboolean isEnemy = qfalse; - VectorSubtract( cent->lerpOrigin, cg.refdef.vieworg, dif ); - len = VectorNormalize( dif ); + VectorSubtract(cent->lerpOrigin, cg.refdef.vieworg, dif); + len = VectorNormalize(dif); - if ( cg.crosshairClientNum != cent->currentState.clientNum - && (!cg.snap||cg.snap->ps.rocketLockIndex!= cent->currentState.clientNum) ) - {//if they're the entity you're locking onto or under your crosshair, always draw bracket - //Hmm... for now, if they're closer than 2000, don't bracket? - if ( len < 2000.0f ) - { + if (cg.crosshairClientNum != cent->currentState.clientNum && + (!cg.snap || cg.snap->ps.rocketLockIndex != + cent->currentState.clientNum)) { // if they're the entity you're locking onto or under your crosshair, always draw bracket + // Hmm... for now, if they're closer than 2000, don't bracket? + if (len < 2000.0f) { return; } - CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cent->lerpOrigin, -1, CONTENTS_OPAQUE ); + CG_Trace(&tr, cg.refdef.vieworg, NULL, NULL, cent->lerpOrigin, -1, CONTENTS_OPAQUE); - //don't bracket if can't see them - if ( tr.fraction < 1.0f ) - { + // don't bracket if can't see them + if (tr.fraction < 1.0f) { return; } } - if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) ) - {//off-screen, don't draw it + if (!CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y)) { // off-screen, don't draw it return; } - //just to see if it's centered - //CG_DrawPic( x-2, y-2, 4, 4, cgs.media.whiteShader ); + // just to see if it's centered + // CG_DrawPic( x-2, y-2, 4, 4, cgs.media.whiteShader ); local = &cgs.clientinfo[cg.snap->ps.clientNum]; - if ( cent->currentState.m_iVehicleNum //vehicle has a driver - && (cent->currentState.m_iVehicleNum-1) < MAX_CLIENTS - && cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid ) - { - if ( cgs.gametype < GT_TEAM ) - {//ffa? + if (cent->currentState.m_iVehicleNum // vehicle has a driver + && (cent->currentState.m_iVehicleNum - 1) < MAX_CLIENTS && cgs.clientinfo[cent->currentState.m_iVehicleNum - 1].infoValid) { + if (cgs.gametype < GT_TEAM) { // ffa? isEnemy = qtrue; - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); - } - else if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team ) - { - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] ); - } - else - { + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); + } else if (cgs.clientinfo[cent->currentState.m_iVehicleNum - 1].team == local->team) { + trap->R_SetColor(g_color_table[ColorIndex(COLOR_GREEN)]); + } else { isEnemy = qtrue; - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); } - } - else if ( cent->currentState.teamowner ) - { - if ( cgs.gametype < GT_TEAM ) - {//ffa? + } else if (cent->currentState.teamowner) { + if (cgs.gametype < GT_TEAM) { // ffa? isEnemy = qtrue; - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); - } - else if ( cent->currentState.teamowner != cg.predictedPlayerState.persistant[PERS_TEAM] ) - {// on enemy team + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); + } else if (cent->currentState.teamowner != cg.predictedPlayerState.persistant[PERS_TEAM]) { // on enemy team isEnemy = qtrue; - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); - } - else - { //a friend - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] ); + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); + } else { // a friend + trap->R_SetColor(g_color_table[ColorIndex(COLOR_GREEN)]); } - } - else - {//FIXME: if we want to ever bracket anything besides vehicles (like siege objectives we want to blow up), we should handle the coloring here - trap->R_SetColor ( NULL ); + } else { // FIXME: if we want to ever bracket anything besides vehicles (like siege objectives we want to blow up), we should handle the coloring here + trap->R_SetColor(NULL); } - if ( len <= 1.0f ) - {//super-close, max out at 400 times radius (which is HUGE) - size = radius*400.0f; - } - else - {//scale by dist - size = radius*(400.0f/len); + if (len <= 1.0f) { // super-close, max out at 400 times radius (which is HUGE) + size = radius * 400.0f; + } else { // scale by dist + size = radius * (400.0f / len); } - if ( size < 1.0f ) - { + if (size < 1.0f) { size = 1.0f; } - //length scales with dist - lineLength = (size*0.1f); - if ( lineLength < 0.5f ) - {//always visible + // length scales with dist + lineLength = (size * 0.1f); + if (lineLength < 0.5f) { // always visible lineLength = 0.5f; } - //always visible width + // always visible width lineWidth = 1.0f; - x -= (size*0.5f); - y -= (size*0.5f); + x -= (size * 0.5f); + y -= (size * 0.5f); /* if ( x >= 0 && x <= 640 && y >= 0 && y <= 480 ) */ - {//brackets would be drawn on the screen, so draw them - //upper left corner - //horz - CG_DrawPic( x, y, lineLength, lineWidth, cgs.media.whiteShader ); - //vert - CG_DrawPic( x, y, lineWidth, lineLength, cgs.media.whiteShader ); - //upper right corner - //horz - CG_DrawPic( x+size-lineLength, y, lineLength, lineWidth, cgs.media.whiteShader ); - //vert - CG_DrawPic( x+size-lineWidth, y, lineWidth, lineLength, cgs.media.whiteShader ); - //lower left corner - //horz - CG_DrawPic( x, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader ); - //vert - CG_DrawPic( x, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader ); - //lower right corner - //horz - CG_DrawPic( x+size-lineLength, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader ); - //vert - CG_DrawPic( x+size-lineWidth, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader ); - } - //Lead Indicator... - if ( cg_drawVehLeadIndicator.integer ) - {//draw the lead indicator - if ( isEnemy ) - {//an enemy object - if ( cent->currentState.NPC_class == CLASS_VEHICLE ) - {//enemy vehicle - if ( !VectorCompare( cent->currentState.pos.trDelta, vec3_origin ) ) - {//enemy vehicle is moving - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//I'm in a vehicle - centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( veh //vehicle cent - && veh->m_pVehicle//vehicle - && veh->m_pVehicle->m_pVehicleInfo//vehicle stats - && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE )//valid vehicle weapon + { // brackets would be drawn on the screen, so draw them + // upper left corner + // horz + CG_DrawPic(x, y, lineLength, lineWidth, cgs.media.whiteShader); + // vert + CG_DrawPic(x, y, lineWidth, lineLength, cgs.media.whiteShader); + // upper right corner + // horz + CG_DrawPic(x + size - lineLength, y, lineLength, lineWidth, cgs.media.whiteShader); + // vert + CG_DrawPic(x + size - lineWidth, y, lineWidth, lineLength, cgs.media.whiteShader); + // lower left corner + // horz + CG_DrawPic(x, y + size - lineWidth, lineLength, lineWidth, cgs.media.whiteShader); + // vert + CG_DrawPic(x, y + size - lineLength, lineWidth, lineLength, cgs.media.whiteShader); + // lower right corner + // horz + CG_DrawPic(x + size - lineLength, y + size - lineWidth, lineLength, lineWidth, cgs.media.whiteShader); + // vert + CG_DrawPic(x + size - lineWidth, y + size - lineLength, lineWidth, lineLength, cgs.media.whiteShader); + } + // Lead Indicator... + if (cg_drawVehLeadIndicator.integer) { // draw the lead indicator + if (isEnemy) { // an enemy object + if (cent->currentState.NPC_class == CLASS_VEHICLE) { // enemy vehicle + if (!VectorCompare(cent->currentState.pos.trDelta, vec3_origin)) { // enemy vehicle is moving + if (cg.predictedPlayerState.m_iVehicleNum) { // I'm in a vehicle + centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; + if (veh // vehicle cent + && veh->m_pVehicle // vehicle + && veh->m_pVehicle->m_pVehicleInfo // vehicle stats + && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE) // valid vehicle weapon { vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID]; - if ( vehWeapon - && vehWeapon->bIsProjectile//primary weapon's shot is a projectile - && !vehWeapon->bHasGravity//primary weapon's shot is not affected by gravity - && !vehWeapon->fHoming//primary weapon's shot is not homing - && vehWeapon->fSpeed )//primary weapon's shot has speed - {//our primary weapon's projectile has a speed + if (vehWeapon && vehWeapon->bIsProjectile // primary weapon's shot is a projectile + && !vehWeapon->bHasGravity // primary weapon's shot is not affected by gravity + && !vehWeapon->fHoming // primary weapon's shot is not homing + && vehWeapon->fSpeed) // primary weapon's shot has speed + { // our primary weapon's projectile has a speed vec3_t vehDiff, vehLeadPos; float vehDist, eta; float leadX, leadY; - VectorSubtract( cent->lerpOrigin, cg.predictedVehicleState.origin, vehDiff ); - vehDist = VectorNormalize( vehDiff ); - eta = (vehDist/vehWeapon->fSpeed);//how many seconds it would take for my primary weapon's projectile to get from my ship to theirs - //now extrapolate their position that number of seconds into the future based on their velocity - VectorMA( cent->lerpOrigin, eta, cent->currentState.pos.trDelta, vehLeadPos ); - //now we have where we should be aiming at, project that onto the screen at a 2D co-ord - if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) ) - {//off-screen, don't draw it + VectorSubtract(cent->lerpOrigin, cg.predictedVehicleState.origin, vehDiff); + vehDist = VectorNormalize(vehDiff); + eta = (vehDist / + vehWeapon->fSpeed); // how many seconds it would take for my primary weapon's projectile to get from my ship to theirs + // now extrapolate their position that number of seconds into the future based on their velocity + VectorMA(cent->lerpOrigin, eta, cent->currentState.pos.trDelta, vehLeadPos); + // now we have where we should be aiming at, project that onto the screen at a 2D co-ord + if (!CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y)) { // off-screen, don't draw it return; } - if ( !CG_WorldCoordToScreenCoordFloat(vehLeadPos, &leadX, &leadY) ) - {//off-screen, don't draw it - //just draw the line - CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f ); + if (!CG_WorldCoordToScreenCoordFloat(vehLeadPos, &leadX, &leadY)) { // off-screen, don't draw it + // just draw the line + CG_DottedLine(x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f); return; } - //draw a line from the ship's cur pos to the lead pos - CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f ); - //now draw the lead indicator - trap->R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] ); - CG_DrawPic( leadX-8, leadY-8, 16, 16, trap->R_RegisterShader( "gfx/menus/radar/lead" ) ); + // draw a line from the ship's cur pos to the lead pos + CG_DottedLine(x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f); + // now draw the lead indicator + trap->R_SetColor(g_color_table[ColorIndex(COLOR_RED)]); + CG_DrawPic(leadX - 8, leadY - 8, 16, 16, trap->R_RegisterShader("gfx/menus/radar/lead")); } } } @@ -5614,45 +4677,32 @@ void CG_BracketEntity( centity_t *cent, float radius ) } } -qboolean CG_InFighter( void ) -{ - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//I'm in a vehicle +qboolean CG_InFighter(void) { + if (cg.predictedPlayerState.m_iVehicleNum) { // I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( vehCent - && vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo - && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//I'm in a fighter + if (vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && + vehCent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // I'm in a fighter return qtrue; } } return qfalse; } -qboolean CG_InATST( void ) -{ - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//I'm in a vehicle +qboolean CG_InATST(void) { + if (cg.predictedPlayerState.m_iVehicleNum) { // I'm in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( vehCent - && vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo - && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - {//I'm in an atst + if (vehCent && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // I'm in an atst return qtrue; } } return qfalse; } -void CG_DrawBracketedEntities( void ) -{ +void CG_DrawBracketedEntities(void) { int i; - for ( i = 0; i < cg.bracketedEntityCount; i++ ) - { + for (i = 0; i < cg.bracketedEntityCount; i++) { centity_t *cent = &cg_entities[cg.bracketedEntities[i]]; - CG_BracketEntity( cent, CG_RadiusForCent( cent ) ); + CG_BracketEntity(cent, CG_RadiusForCent(cent)); } } @@ -5663,31 +4713,26 @@ static void CG_DrawHolocronIcons(void) int icon_size = 40; int i = 0; int startx = 10; - int starty = 10;//SCREEN_HEIGHT - icon_size*3; + int starty = 10; // SCREEN_HEIGHT - icon_size*3; int endx = icon_size; int endy = icon_size; - if (cg.snap->ps.zoomMode) - { //don't display over zoom mask + if (cg.snap->ps.zoomMode) { // don't display over zoom mask return; } - if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) - { + if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } - while (i < NUM_FORCE_POWERS) - { - if (cg.snap->ps.holocronBits & (1 << forcePowerSorted[i])) - { - CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); - starty += (icon_size+2); //+2 for spacing - if ((starty+icon_size) >= SCREEN_HEIGHT-80) - { - starty = 10;//SCREEN_HEIGHT - icon_size*3; - startx += (icon_size+2); + while (i < NUM_FORCE_POWERS) { + if (cg.snap->ps.holocronBits & (1 << forcePowerSorted[i])) { + CG_DrawPic(startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); + starty += (icon_size + 2); //+2 for spacing + if ((starty + icon_size) >= SCREEN_HEIGHT - 80) { + starty = 10; // SCREEN_HEIGHT - icon_size*3; + startx += (icon_size + 2); } } @@ -5695,16 +4740,8 @@ static void CG_DrawHolocronIcons(void) } } -static qboolean CG_IsDurationPower(int power) -{ - if (power == FP_HEAL || - power == FP_SPEED || - power == FP_TELEPATHY || - power == FP_RAGE || - power == FP_PROTECT || - power == FP_ABSORB || - power == FP_SEE) - { +static qboolean CG_IsDurationPower(int power) { + if (power == FP_HEAL || power == FP_SPEED || power == FP_TELEPATHY || power == FP_RAGE || power == FP_PROTECT || power == FP_ABSORB || power == FP_SEE) { return qtrue; } @@ -5717,150 +4754,112 @@ static void CG_DrawActivePowers(void) { int icon_size = 40; int i = 0; - int startx = icon_size*2+16; - int starty = SCREEN_HEIGHT - icon_size*2; + int startx = icon_size * 2 + 16; + int starty = SCREEN_HEIGHT - icon_size * 2; int endx = icon_size; int endy = icon_size; - if (cg.snap->ps.zoomMode) - { //don't display over zoom mask + if (cg.snap->ps.zoomMode) { // don't display over zoom mask return; } - if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) - { + if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); - while (i < NUM_FORCE_POWERS) - { - if ((cg.snap->ps.fd.forcePowersActive & (1 << forcePowerSorted[i])) && - CG_IsDurationPower(forcePowerSorted[i])) - { - CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); - startx += (icon_size+2); //+2 for spacing - if ((startx+icon_size) >= SCREEN_WIDTH-80) - { - startx = icon_size*2+16; - starty += (icon_size+2); + while (i < NUM_FORCE_POWERS) { + if ((cg.snap->ps.fd.forcePowersActive & (1 << forcePowerSorted[i])) && CG_IsDurationPower(forcePowerSorted[i])) { + CG_DrawPic(startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]); + startx += (icon_size + 2); //+2 for spacing + if ((startx + icon_size) >= SCREEN_WIDTH - 80) { + startx = icon_size * 2 + 16; + starty += (icon_size + 2); } } i++; } - //additionally, draw an icon force force rage recovery - if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) - { - CG_DrawPic( startx, starty, endx, endy, cgs.media.rageRecShader); + // additionally, draw an icon force force rage recovery + if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { + CG_DrawPic(startx, starty, endx, endy, cgs.media.rageRecShader); } } //-------------------------------------------------------------- -static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) +static void CG_DrawRocketLocking(int lockEntNum, int lockTime) //-------------------------------------------------------------- { - int cx, cy; - vec3_t org; - static int oldDif = 0; + int cx, cy; + vec3_t org; + static int oldDif = 0; centity_t *cent = &cg_entities[lockEntNum]; - vec4_t color={0.0f,0.0f,0.0f,0.0f}; - float lockTimeInterval = ((cgs.gametype==GT_SIEGE)?2400.0f:1200.0f)/16.0f; - //FIXME: if in a vehicle, use the vehicle's lockOnTime... - int dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval; + vec4_t color = {0.0f, 0.0f, 0.0f, 0.0f}; + float lockTimeInterval = ((cgs.gametype == GT_SIEGE) ? 2400.0f : 1200.0f) / 16.0f; + // FIXME: if in a vehicle, use the vehicle's lockOnTime... + int dif = (cg.time - cg.snap->ps.rocketLockTime) / lockTimeInterval; int i; - if (!cg.snap->ps.rocketLockTime) - { + if (!cg.snap->ps.rocketLockTime) { return; } - if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) - { + if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { return; } - if ( cg.snap->ps.m_iVehicleNum ) - {//driving a vehicle + if (cg.snap->ps.m_iVehicleNum) { // driving a vehicle centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; - if ( veh->m_pVehicle ) - { + if (veh->m_pVehicle) { vehWeaponInfo_t *vehWeapon = NULL; - if ( cg.predictedVehicleState.weaponstate == WEAPON_CHARGING_ALT ) - { - if ( veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID > VEH_WEAPON_BASE - && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID < MAX_VEH_WEAPONS ) - { + if (cg.predictedVehicleState.weaponstate == WEAPON_CHARGING_ALT) { + if (veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID > VEH_WEAPON_BASE && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID < MAX_VEH_WEAPONS) { vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID]; } - } - else - { - if ( veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE - && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID < MAX_VEH_WEAPONS ) - { + } else { + if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE && veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID < MAX_VEH_WEAPONS) { vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID]; } } - if ( vehWeapon != NULL ) - {//we are trying to lock on with a valid vehicle weapon, so use *its* locktime, not the hard-coded one - if ( !vehWeapon->iLockOnTime ) - {//instant lock-on + if (vehWeapon != NULL) { // we are trying to lock on with a valid vehicle weapon, so use *its* locktime, not the hard-coded one + if (!vehWeapon->iLockOnTime) { // instant lock-on dif = 10.0f; - } - else - {//use the custom vehicle lockOnTime - lockTimeInterval = (vehWeapon->iLockOnTime/16.0f); - dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval; + } else { // use the custom vehicle lockOnTime + lockTimeInterval = (vehWeapon->iLockOnTime / 16.0f); + dif = (cg.time - cg.snap->ps.rocketLockTime) / lockTimeInterval; } } } } - //We can't check to see in pmove if players are on the same team, so we resort - //to just not drawing the lock if a teammate is the locked on ent - if (cg.snap->ps.rocketLockIndex >= 0 && - cg.snap->ps.rocketLockIndex < ENTITYNUM_NONE) - { + // We can't check to see in pmove if players are on the same team, so we resort + // to just not drawing the lock if a teammate is the locked on ent + if (cg.snap->ps.rocketLockIndex >= 0 && cg.snap->ps.rocketLockIndex < ENTITYNUM_NONE) { clientInfo_t *ci = NULL; - if (cg.snap->ps.rocketLockIndex < MAX_CLIENTS) - { + if (cg.snap->ps.rocketLockIndex < MAX_CLIENTS) { ci = &cgs.clientinfo[cg.snap->ps.rocketLockIndex]; - } - else - { + } else { ci = cg_entities[cg.snap->ps.rocketLockIndex].npcClient; } - if (ci) - { - if (ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) - { - if (cgs.gametype >= GT_TEAM) - { + if (ci) { + if (ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) { + if (cgs.gametype >= GT_TEAM) { return; } - } - else if (cgs.gametype >= GT_TEAM) - { + } else if (cgs.gametype >= GT_TEAM) { centity_t *hitEnt = &cg_entities[cg.snap->ps.rocketLockIndex]; - if (hitEnt->currentState.eType == ET_NPC && - hitEnt->currentState.NPC_class == CLASS_VEHICLE && - hitEnt->currentState.owner < ENTITYNUM_WORLD) - { //this is a vehicle, if it has a pilot and that pilot is on my team, then... - if (hitEnt->currentState.owner < MAX_CLIENTS) - { + if (hitEnt->currentState.eType == ET_NPC && hitEnt->currentState.NPC_class == CLASS_VEHICLE && + hitEnt->currentState.owner < ENTITYNUM_WORLD) { // this is a vehicle, if it has a pilot and that pilot is on my team, then... + if (hitEnt->currentState.owner < MAX_CLIENTS) { ci = &cgs.clientinfo[hitEnt->currentState.owner]; - } - else - { + } else { ci = cg_entities[hitEnt->currentState.owner].npcClient; } - if (ci && ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) - { + if (ci && ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team) { return; } } @@ -5868,33 +4867,25 @@ static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) } } - if (cg.snap->ps.rocketLockTime != -1) - { + if (cg.snap->ps.rocketLockTime != -1) { lastvalidlockdif = dif; - } - else - { + } else { dif = lastvalidlockdif; } - if ( !cent ) - { + if (!cent) { return; } - VectorCopy( cent->lerpOrigin, org ); + VectorCopy(cent->lerpOrigin, org); - if ( CG_WorldCoordToScreenCoord( org, &cx, &cy )) - { + if (CG_WorldCoordToScreenCoord(org, &cx, &cy)) { // we care about distance from enemy to eye, so this is good enough - float sz = Distance( cent->lerpOrigin, cg.refdef.vieworg ) / 1024.0f; + float sz = Distance(cent->lerpOrigin, cg.refdef.vieworg) / 1024.0f; - if ( sz > 1.0f ) - { + if (sz > 1.0f) { sz = 1.0f; - } - else if ( sz < 0.0f ) - { + } else if (sz < 0.0f) { sz = 0.0f; } @@ -5902,80 +4893,63 @@ static void CG_DrawRocketLocking( int lockEntNum, int lockTime ) cy += sz * 0.5f; - if ( dif < 0 ) - { + if (dif < 0) { oldDif = 0; return; - } - else if ( dif > 8 ) - { + } else if (dif > 8) { dif = 8; } // do sounds - if ( oldDif != dif ) - { - if ( dif == 8 ) - { - if ( cg.snap->ps.m_iVehicleNum ) - { - trap->S_StartSound( org, 0, CHAN_AUTO, trap->S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" )); - } - else - { - trap->S_StartSound( org, 0, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/rocket/lock.wav" )); - } - } - else - { - if ( cg.snap->ps.m_iVehicleNum ) - { - trap->S_StartSound( org, 0, CHAN_AUTO, trap->S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" )); + if (oldDif != dif) { + if (dif == 8) { + if (cg.snap->ps.m_iVehicleNum) { + trap->S_StartSound(org, 0, CHAN_AUTO, trap->S_RegisterSound("sound/vehicles/weapons/common/lock.wav")); + } else { + trap->S_StartSound(org, 0, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/rocket/lock.wav")); } - else - { - trap->S_StartSound( org, 0, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/rocket/tick.wav" )); + } else { + if (cg.snap->ps.m_iVehicleNum) { + trap->S_StartSound(org, 0, CHAN_AUTO, trap->S_RegisterSound("sound/vehicles/weapons/common/tick.wav")); + } else { + trap->S_StartSound(org, 0, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/rocket/tick.wav")); } } } oldDif = dif; - for ( i = 0; i < dif; i++ ) - { + for (i = 0; i < dif; i++) { color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; color[3] = 0.1f * i + 0.2f; - trap->R_SetColor( color ); + trap->R_SetColor(color); // our slices are offset by about 45 degrees. - CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, trap->R_RegisterShaderNoMip( "gfx/2d/wedge" )); + CG_DrawRotatePic(cx - sz, cy - sz, sz, sz, i * 45.0f, trap->R_RegisterShaderNoMip("gfx/2d/wedge")); } // we are locked and loaded baby - if ( dif == 8 ) - { - color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f; + if (dif == 8) { + color[0] = color[1] = color[2] = sin(cg.time * 0.05f) * 0.5f + 0.5f; color[3] = 1.0f; // this art is additive, so the alpha value does nothing - trap->R_SetColor( color ); + trap->R_SetColor(color); - CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, trap->R_RegisterShaderNoMip( "gfx/2d/lock" )); + CG_DrawPic(cx - sz, cy - sz * 2, sz * 2, sz * 2, trap->R_RegisterShaderNoMip("gfx/2d/lock")); } } } extern void CG_CalcVehMuzzle(Vehicle_t *pVeh, centity_t *ent, int muzzleNum); -qboolean CG_CalcVehicleMuzzlePoint( int entityNum, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) -{ +qboolean CG_CalcVehicleMuzzlePoint(int entityNum, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) { centity_t *vehCent = &cg_entities[entityNum]; - if ( vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - {//draw from barrels - VectorCopy( vehCent->lerpOrigin, start ); - start[2] += vehCent->m_pVehicle->m_pVehicleInfo->height-DEFAULT_MINS_2-48; - AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up ); + if (vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // draw from barrels + VectorCopy(vehCent->lerpOrigin, start); + start[2] += vehCent->m_pVehicle->m_pVehicleInfo->height - DEFAULT_MINS_2 - 48; + AngleVectors(vehCent->lerpAngles, d_f, d_rt, d_up); /* mdxaBone_t boltMatrix; int bolt; @@ -5994,45 +4968,35 @@ qboolean CG_CalcVehicleMuzzlePoint( int entityNum, vec3_t start, vec3_t d_f, vec VectorClear( d_rt );//don't really need this, do we? VectorClear( d_up );//don't really need this, do we? */ - } - else - { - //check to see if we're a turret gunner on this vehicle - if ( cg.predictedPlayerState.generic1 )//as a passenger - {//passenger in a vehicle - if ( vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo - && vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers ) - {//a vehicle capable of carrying passengers + } else { + // check to see if we're a turret gunner on this vehicle + if (cg.predictedPlayerState.generic1) // as a passenger + { // passenger in a vehicle + if (vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && + vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers) { // a vehicle capable of carrying passengers int turretNum; - for ( turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++ ) - { - if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax ) - {// valid turret - if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1 ) - {//I control this turret - //Go through all muzzles, average their positions and directions and use the result for crosshair trace + for (turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++) { + if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax) { // valid turret + if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1) { // I control this turret + // Go through all muzzles, average their positions and directions and use the result for crosshair trace int vehMuzzle, numMuzzles = 0; - vec3_t muzzlesAvgPos={0},muzzlesAvgDir={0}; - int i; + vec3_t muzzlesAvgPos = {0}, muzzlesAvgDir = {0}; + int i; - for ( i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++ ) - { + for (i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++) { vehMuzzle = vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iMuzzle[i]; - if ( vehMuzzle ) - { + if (vehMuzzle) { vehMuzzle -= 1; - CG_CalcVehMuzzle( vehCent->m_pVehicle, vehCent, vehMuzzle ); - VectorAdd( muzzlesAvgPos, vehCent->m_pVehicle->m_vMuzzlePos[vehMuzzle], muzzlesAvgPos ); - VectorAdd( muzzlesAvgDir, vehCent->m_pVehicle->m_vMuzzleDir[vehMuzzle], muzzlesAvgDir ); + CG_CalcVehMuzzle(vehCent->m_pVehicle, vehCent, vehMuzzle); + VectorAdd(muzzlesAvgPos, vehCent->m_pVehicle->m_vMuzzlePos[vehMuzzle], muzzlesAvgPos); + VectorAdd(muzzlesAvgDir, vehCent->m_pVehicle->m_vMuzzleDir[vehMuzzle], muzzlesAvgDir); numMuzzles++; } - if ( numMuzzles ) - { - VectorScale( muzzlesAvgPos, 1.0f/(float)numMuzzles, start ); - VectorScale( muzzlesAvgDir, 1.0f/(float)numMuzzles, d_f ); - VectorClear( d_rt ); - VectorClear( d_up ); + if (numMuzzles) { + VectorScale(muzzlesAvgPos, 1.0f / (float)numMuzzles, start); + VectorScale(muzzlesAvgDir, 1.0f / (float)numMuzzles, d_f); + VectorClear(d_rt); + VectorClear(d_up); return qtrue; } } @@ -6041,33 +5005,31 @@ qboolean CG_CalcVehicleMuzzlePoint( int entityNum, vec3_t start, vec3_t d_f, vec } } } - VectorCopy( vehCent->lerpOrigin, start ); - AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up ); + VectorCopy(vehCent->lerpOrigin, start); + AngleVectors(vehCent->lerpAngles, d_f, d_rt, d_up); } return qfalse; } -//calc the muzzle point from the e-web itself -void CG_CalcEWebMuzzlePoint(centity_t *cent, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) -{ +// calc the muzzle point from the e-web itself +void CG_CalcEWebMuzzlePoint(centity_t *cent, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up) { int bolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*cannonflash"); assert(bolt != -1); - if (bolt != -1) - { + if (bolt != -1) { mdxaBone_t boltMatrix; trap->G2API_GetBoltMatrix_NoRecNoRot(cent->ghoul2, 0, bolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, NULL, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, start); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, d_f); - //these things start the shot a little inside the bbox to assure not starting in something solid + // these things start the shot a little inside the bbox to assure not starting in something solid VectorMA(start, -16.0f, d_f, start); - //I guess - VectorClear( d_rt );//don't really need this, do we? - VectorClear( d_up );//don't really need this, do we? + // I guess + VectorClear(d_rt); // don't really need this, do we? + VectorClear(d_up); // don't really need this, do we? } } @@ -6076,18 +5038,17 @@ void CG_CalcEWebMuzzlePoint(centity_t *cent, vec3_t start, vec3_t d_f, vec3_t d_ CG_`Entity ================= */ -#define MAX_XHAIR_DIST_ACCURACY 20000.0f -static void CG_ScanForCrosshairEntity( void ) { - trace_t trace; - vec3_t start, end; - int content; - int ignore; - qboolean bVehCheckTraceFromCamPos = qfalse; +#define MAX_XHAIR_DIST_ACCURACY 20000.0f +static void CG_ScanForCrosshairEntity(void) { + trace_t trace; + vec3_t start, end; + int content; + int ignore; + qboolean bVehCheckTraceFromCamPos = qfalse; ignore = cg.predictedPlayerState.clientNum; - if ( cg_dynamicCrosshair.integer ) - { + if (cg_dynamicCrosshair.integer) { vec3_t d_f, d_rt, d_up; /* if ( cg.snap->ps.weapon == WP_NONE || @@ -6099,16 +5060,15 @@ static void CG_ScanForCrosshairEntity( void ) { } else */ - //For now we still want to draw the crosshair in relation to the player's world coordinates - //even if we have a melee weapon/no weapon. - if ( cg.predictedPlayerState.m_iVehicleNum && (cg.predictedPlayerState.eFlags&EF_NODRAW) ) - {//we're *inside* a vehicle - //do the vehicle's crosshair instead + // For now we still want to draw the crosshair in relation to the player's world coordinates + // even if we have a melee weapon/no weapon. + if (cg.predictedPlayerState.m_iVehicleNum && (cg.predictedPlayerState.eFlags & EF_NODRAW)) { // we're *inside* a vehicle + // do the vehicle's crosshair instead centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; qboolean gunner = qfalse; - //if (veh->currentState.owner == cg.predictedPlayerState.clientNum) - { //the pilot + // if (veh->currentState.owner == cg.predictedPlayerState.clientNum) + { // the pilot ignore = cg.predictedPlayerState.m_iVehicleNum; gunner = CG_CalcVehicleMuzzlePoint(cg.predictedPlayerState.m_iVehicleNum, start, d_f, d_rt, d_up); } @@ -6121,166 +5081,125 @@ static void CG_ScanForCrosshairEntity( void ) { VectorMA(start, 32.0f, d_f, start); //super hack } */ - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pVehicleInfo - && veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER - && cg.distanceCull > MAX_XHAIR_DIST_ACCURACY - && !gunner ) - { - //NOTE: on huge maps, the crosshair gets inaccurate at close range, + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && + cg.distanceCull > MAX_XHAIR_DIST_ACCURACY && !gunner) { + // NOTE: on huge maps, the crosshair gets inaccurate at close range, // so we'll do an extra G2 trace from the cg.refdef.vieworg // to see if we hit anything closer and auto-aim at it if so bVehCheckTraceFromCamPos = qtrue; } - } - else if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex && - cg_entities[cg.snap->ps.emplacedIndex].ghoul2 && cg_entities[cg.snap->ps.emplacedIndex].currentState.weapon == WP_NONE) - { //locked into our e-web, calc the muzzle from it + } else if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex && cg_entities[cg.snap->ps.emplacedIndex].ghoul2 && + cg_entities[cg.snap->ps.emplacedIndex].currentState.weapon == WP_NONE) { // locked into our e-web, calc the muzzle from it CG_CalcEWebMuzzlePoint(&cg_entities[cg.snap->ps.emplacedIndex], start, d_f, d_rt, d_up); - } - else - { - if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) - { + } else { + if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) { vec3_t pitchConstraint; ignore = cg.snap->ps.emplacedIndex; VectorCopy(cg.refdef.viewangles, pitchConstraint); - if (cg.renderingThirdPerson) - { + if (cg.renderingThirdPerson) { VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint); - } - else - { + } else { VectorCopy(cg.refdef.viewangles, pitchConstraint); } - if (pitchConstraint[PITCH] > 40) - { + if (pitchConstraint[PITCH] > 40) { pitchConstraint[PITCH] = 40; } - AngleVectors( pitchConstraint, d_f, d_rt, d_up ); - } - else - { + AngleVectors(pitchConstraint, d_f, d_rt, d_up); + } else { vec3_t pitchConstraint; - if (cg.renderingThirdPerson) - { + if (cg.renderingThirdPerson) { VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint); - } - else - { + } else { VectorCopy(cg.refdef.viewangles, pitchConstraint); } - AngleVectors( pitchConstraint, d_f, d_rt, d_up ); + AngleVectors(pitchConstraint, d_f, d_rt, d_up); } CG_CalcMuzzlePoint(cg.snap->ps.clientNum, start); } - VectorMA( start, cg.distanceCull, d_f, end ); - } - else - { - VectorCopy( cg.refdef.vieworg, start ); - VectorMA( start, 131072, cg.refdef.viewaxis[0], end ); + VectorMA(start, cg.distanceCull, d_f, end); + } else { + VectorCopy(cg.refdef.vieworg, start); + VectorMA(start, 131072, cg.refdef.viewaxis[0], end); } - if ( cg_dynamicCrosshair.integer && cg_dynamicCrosshairPrecision.integer ) - { //then do a trace with ghoul2 models in mind - CG_G2Trace( &trace, start, vec3_origin, vec3_origin, end, - ignore, CONTENTS_SOLID|CONTENTS_BODY ); - if ( bVehCheckTraceFromCamPos ) - { - //NOTE: this MUST stay up to date with the method used in WP_VehCheckTraceFromCamPos + if (cg_dynamicCrosshair.integer && cg_dynamicCrosshairPrecision.integer) { // then do a trace with ghoul2 models in mind + CG_G2Trace(&trace, start, vec3_origin, vec3_origin, end, ignore, CONTENTS_SOLID | CONTENTS_BODY); + if (bVehCheckTraceFromCamPos) { + // NOTE: this MUST stay up to date with the method used in WP_VehCheckTraceFromCamPos centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - trace_t extraTrace; - vec3_t viewDir2End, extraEnd; - float minAutoAimDist = Distance( veh->lerpOrigin, cg.refdef.vieworg ) + (veh->m_pVehicle->m_pVehicleInfo->length/2.0f) + 200.0f; - - VectorSubtract( end, cg.refdef.vieworg, viewDir2End ); - VectorNormalize( viewDir2End ); - VectorMA( cg.refdef.vieworg, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd ); - CG_G2Trace( &extraTrace, cg.refdef.vieworg, vec3_origin, vec3_origin, extraEnd, - ignore, CONTENTS_SOLID|CONTENTS_BODY ); - if ( !extraTrace.allsolid - && !extraTrace.startsolid ) - { - if ( extraTrace.fraction < 1.0f ) - { - if ( (extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist ) - { - if ( ((extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY)-Distance( veh->lerpOrigin, cg.refdef.vieworg )) < (trace.fraction*cg.distanceCull) ) - {//this trace hit *something* that's closer than the thing the main trace hit, so use this result instead - memcpy( &trace, &extraTrace, sizeof( trace_t ) ); + trace_t extraTrace; + vec3_t viewDir2End, extraEnd; + float minAutoAimDist = Distance(veh->lerpOrigin, cg.refdef.vieworg) + (veh->m_pVehicle->m_pVehicleInfo->length / 2.0f) + 200.0f; + + VectorSubtract(end, cg.refdef.vieworg, viewDir2End); + VectorNormalize(viewDir2End); + VectorMA(cg.refdef.vieworg, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd); + CG_G2Trace(&extraTrace, cg.refdef.vieworg, vec3_origin, vec3_origin, extraEnd, ignore, CONTENTS_SOLID | CONTENTS_BODY); + if (!extraTrace.allsolid && !extraTrace.startsolid) { + if (extraTrace.fraction < 1.0f) { + if ((extraTrace.fraction * MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist) { + if (((extraTrace.fraction * MAX_XHAIR_DIST_ACCURACY) - Distance(veh->lerpOrigin, cg.refdef.vieworg)) < + (trace.fraction * + cg.distanceCull)) { // this trace hit *something* that's closer than the thing the main trace hit, so use this result instead + memcpy(&trace, &extraTrace, sizeof(trace_t)); } } } } } - } - else - { - CG_Trace( &trace, start, vec3_origin, vec3_origin, end, - ignore, CONTENTS_SOLID|CONTENTS_BODY ); + } else { + CG_Trace(&trace, start, vec3_origin, vec3_origin, end, ignore, CONTENTS_SOLID | CONTENTS_BODY); } - if (trace.entityNum < MAX_CLIENTS) - { - if (CG_IsMindTricked(cg_entities[trace.entityNum].currentState.trickedentindex, - cg_entities[trace.entityNum].currentState.trickedentindex2, - cg_entities[trace.entityNum].currentState.trickedentindex3, - cg_entities[trace.entityNum].currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - if (cg.crosshairClientNum == trace.entityNum) - { + if (trace.entityNum < MAX_CLIENTS) { + if (CG_IsMindTricked(cg_entities[trace.entityNum].currentState.trickedentindex, cg_entities[trace.entityNum].currentState.trickedentindex2, + cg_entities[trace.entityNum].currentState.trickedentindex3, cg_entities[trace.entityNum].currentState.trickedentindex4, + cg.snap->ps.clientNum)) { + if (cg.crosshairClientNum == trace.entityNum) { cg.crosshairClientNum = ENTITYNUM_NONE; cg.crosshairClientTime = 0; } CG_DrawCrosshair(trace.endpos, 0); - return; //this entity is mind-tricking the current client, so don't render it + return; // this entity is mind-tricking the current client, so don't render it } } - if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) - { - if (trace.entityNum < /*MAX_CLIENTS*/ENTITYNUM_WORLD) - { + if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) { + if (trace.entityNum < /*MAX_CLIENTS*/ ENTITYNUM_WORLD) { centity_t *veh = &cg_entities[trace.entityNum]; cg.crosshairClientNum = trace.entityNum; cg.crosshairClientTime = cg.time; - if (veh->currentState.eType == ET_NPC && - veh->currentState.NPC_class == CLASS_VEHICLE && - veh->currentState.owner < MAX_CLIENTS) - { //draw the name of the pilot then + if (veh->currentState.eType == ET_NPC && veh->currentState.NPC_class == CLASS_VEHICLE && + veh->currentState.owner < MAX_CLIENTS) { // draw the name of the pilot then cg.crosshairClientNum = veh->currentState.owner; cg.crosshairVehNum = veh->currentState.number; cg.crosshairVehTime = cg.time; } CG_DrawCrosshair(trace.endpos, 1); - } - else - { + } else { CG_DrawCrosshair(trace.endpos, 0); } } - if ( trace.entityNum >= MAX_CLIENTS ) { + if (trace.entityNum >= MAX_CLIENTS) { return; } // if the player is in fog, don't show it - content = CG_PointContents( trace.endpos, 0 ); - if ( content & CONTENTS_FOG ) { + content = CG_PointContents(trace.endpos, 0); + if (content & CONTENTS_FOG) { return; } @@ -6294,133 +5213,106 @@ static void CG_ScanForCrosshairEntity( void ) { CG_DrawCrosshairNames ===================== */ -static void CG_DrawCrosshairNames( void ) { - float *color; - vec4_t tcolor; - char *name; - int baseColor; - qboolean isVeh = qfalse; - - if ( !cg_drawCrosshair.integer ) { +static void CG_DrawCrosshairNames(void) { + float *color; + vec4_t tcolor; + char *name; + int baseColor; + qboolean isVeh = qfalse; + + if (!cg_drawCrosshair.integer) { return; } // scan the known entities to see if the crosshair is sighted on one CG_ScanForCrosshairEntity(); - if ( !cg_drawCrosshairNames.integer ) { + if (!cg_drawCrosshairNames.integer) { return; } - //rww - still do the trace, our dynamic crosshair depends on it + // rww - still do the trace, our dynamic crosshair depends on it - if (cg.crosshairClientNum < ENTITYNUM_WORLD) - { + if (cg.crosshairClientNum < ENTITYNUM_WORLD) { centity_t *veh = &cg_entities[cg.crosshairClientNum]; - if (veh->currentState.eType == ET_NPC && - veh->currentState.NPC_class == CLASS_VEHICLE && - veh->currentState.owner < MAX_CLIENTS) - { //draw the name of the pilot then + if (veh->currentState.eType == ET_NPC && veh->currentState.NPC_class == CLASS_VEHICLE && + veh->currentState.owner < MAX_CLIENTS) { // draw the name of the pilot then cg.crosshairClientNum = veh->currentState.owner; cg.crosshairVehNum = veh->currentState.number; cg.crosshairVehTime = cg.time; - isVeh = qtrue; //so we know we're drawing the pilot's name + isVeh = qtrue; // so we know we're drawing the pilot's name } } - if (cg.crosshairClientNum >= MAX_CLIENTS) - { + if (cg.crosshairClientNum >= MAX_CLIENTS) { return; } - if (cg_entities[cg.crosshairClientNum].currentState.powerups & (1 << PW_CLOAKED)) - { + if (cg_entities[cg.crosshairClientNum].currentState.powerups & (1 << PW_CLOAKED)) { return; } // draw the name of the player being looked at - color = CG_FadeColor( cg.crosshairClientTime, 1000 ); - if ( !color ) { - trap->R_SetColor( NULL ); + color = CG_FadeColor(cg.crosshairClientTime, 1000); + if (!color) { + trap->R_SetColor(NULL); return; } - name = cgs.clientinfo[ cg.crosshairClientNum ].cleanname; + name = cgs.clientinfo[cg.crosshairClientNum].cleanname; - if (cgs.gametype >= GT_TEAM) - { - //if (cgs.gametype == GT_SIEGE) - if (1) - { //instead of team-based we'll make it oriented based on which team we're on - if (cgs.clientinfo[cg.crosshairClientNum].team == cg.predictedPlayerState.persistant[PERS_TEAM]) - { + if (cgs.gametype >= GT_TEAM) { + // if (cgs.gametype == GT_SIEGE) + if (1) { // instead of team-based we'll make it oriented based on which team we're on + if (cgs.clientinfo[cg.crosshairClientNum].team == cg.predictedPlayerState.persistant[PERS_TEAM]) { baseColor = CT_GREEN; - } - else - { + } else { baseColor = CT_RED; } - } - else - { - if (cgs.clientinfo[cg.crosshairClientNum].team == TEAM_RED) - { + } else { + if (cgs.clientinfo[cg.crosshairClientNum].team == TEAM_RED) { baseColor = CT_RED; - } - else - { + } else { baseColor = CT_BLUE; } } - } - else - { - //baseColor = CT_WHITE; - if (cgs.gametype == GT_POWERDUEL && - cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR && - cgs.clientinfo[cg.crosshairClientNum].duelTeam == cgs.clientinfo[cg.predictedPlayerState.clientNum].duelTeam) - { //on the same duel team in powerduel, so he's a friend + } else { + // baseColor = CT_WHITE; + if (cgs.gametype == GT_POWERDUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR && + cgs.clientinfo[cg.crosshairClientNum].duelTeam == + cgs.clientinfo[cg.predictedPlayerState.clientNum].duelTeam) { // on the same duel team in powerduel, so he's a friend baseColor = CT_GREEN; - } - else - { - baseColor = CT_RED; //just make it red in nonteam modes since everyone is hostile and crosshair will be red on them too + } else { + baseColor = CT_RED; // just make it red in nonteam modes since everyone is hostile and crosshair will be red on them too } } - if (cg.snap->ps.duelInProgress) - { - if (cg.crosshairClientNum != cg.snap->ps.duelIndex) - { //grey out crosshair for everyone but your foe if you're in a duel + if (cg.snap->ps.duelInProgress) { + if (cg.crosshairClientNum != cg.snap->ps.duelIndex) { // grey out crosshair for everyone but your foe if you're in a duel baseColor = CT_BLACK; } - } - else if (cg_entities[cg.crosshairClientNum].currentState.bolt1) - { //this fellow is in a duel. We just checked if we were in a duel above, so - //this means we aren't and he is. Which of course means our crosshair greys out over him. + } else if (cg_entities[cg.crosshairClientNum] + .currentState.bolt1) { // this fellow is in a duel. We just checked if we were in a duel above, so + // this means we aren't and he is. Which of course means our crosshair greys out over him. baseColor = CT_BLACK; } tcolor[0] = colorTable[baseColor][0]; tcolor[1] = colorTable[baseColor][1]; tcolor[2] = colorTable[baseColor][2]; - tcolor[3] = color[3]*0.5f; + tcolor[3] = color[3] * 0.5f; - if (isVeh) - { + if (isVeh) { char str[MAX_STRING_CHARS]; Com_sprintf(str, MAX_STRING_CHARS, "%s (pilot)", name); CG_DrawProportionalString(320, 170, str, UI_CENTER, tcolor); - } - else - { + } else { CG_DrawProportionalString(320, 170, name, UI_CENTER, tcolor); } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } - //============================================================================== /* @@ -6428,80 +5320,64 @@ static void CG_DrawCrosshairNames( void ) { CG_DrawSpectator ================= */ -static void CG_DrawSpectator(void) -{ - const char* s; +static void CG_DrawSpectator(void) { + const char *s; s = CG_GetStringEdString("MP_INGAME", "SPECTATOR"); - if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && - cgs.duelist1 != -1 && - cgs.duelist2 != -1) - { + if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelist1 != -1 && cgs.duelist2 != -1) { char text[1024]; int size = 64; - if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) - { - Com_sprintf(text, sizeof(text), "%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name); - } - else - { - Com_sprintf(text, sizeof(text), "%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name); + if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) { + Com_sprintf(text, sizeof(text), "%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), + cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name); + } else { + Com_sprintf(text, sizeof(text), "%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), + cgs.clientinfo[cgs.duelist2].name); } - CG_Text_Paint ( 320 - CG_Text_Width ( text, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, text, 0, 0, 0, 3 ); + CG_Text_Paint(320 - CG_Text_Width(text, 1.0f, 3) / 2, 420, 1.0f, colorWhite, text, 0, 0, 0, 3); - trap->R_SetColor( colorTable[CT_WHITE] ); - if ( cgs.clientinfo[cgs.duelist1].modelIcon ) - { - CG_DrawPic( 10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist1].modelIcon ); + trap->R_SetColor(colorTable[CT_WHITE]); + if (cgs.clientinfo[cgs.duelist1].modelIcon) { + CG_DrawPic(10, SCREEN_HEIGHT - (size * 1.5), size, size, cgs.clientinfo[cgs.duelist1].modelIcon); } - if ( cgs.clientinfo[cgs.duelist2].modelIcon ) - { - CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist2].modelIcon ); + if (cgs.clientinfo[cgs.duelist2].modelIcon) { + CG_DrawPic(SCREEN_WIDTH - size - 10, SCREEN_HEIGHT - (size * 1.5), size, size, cgs.clientinfo[cgs.duelist2].modelIcon); } -// nmckenzie: DUEL_HEALTH - if (cgs.gametype == GT_DUEL) - { - if ( cgs.showDuelHealths >= 1) - { // draw the healths on the two guys - how does this interact with power duel, though? - CG_DrawDuelistHealth ( 10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 1 ); - CG_DrawDuelistHealth ( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 2 ); + // nmckenzie: DUEL_HEALTH + if (cgs.gametype == GT_DUEL) { + if (cgs.showDuelHealths >= 1) { // draw the healths on the two guys - how does this interact with power duel, though? + CG_DrawDuelistHealth(10, SCREEN_HEIGHT - (size * 1.5) - 12, 64, 8, 1); + CG_DrawDuelistHealth(SCREEN_WIDTH - size - 10, SCREEN_HEIGHT - (size * 1.5) - 12, 64, 8, 2); } } - if (cgs.gametype != GT_POWERDUEL) - { - Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist1].score, cgs.fraglimit ); - CG_Text_Paint( 42 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 ); + if (cgs.gametype != GT_POWERDUEL) { + Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist1].score, cgs.fraglimit); + CG_Text_Paint(42 - CG_Text_Width(text, 1.0f, 2) / 2, SCREEN_HEIGHT - (size * 1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2); - Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist2].score, cgs.fraglimit ); - CG_Text_Paint( SCREEN_WIDTH-size+22 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 ); + Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist2].score, cgs.fraglimit); + CG_Text_Paint(SCREEN_WIDTH - size + 22 - CG_Text_Width(text, 1.0f, 2) / 2, SCREEN_HEIGHT - (size * 1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2); } - if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) - { - if ( cgs.clientinfo[cgs.duelist3].modelIcon ) - { - CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*2.8), size, size, cgs.clientinfo[cgs.duelist3].modelIcon ); + if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) { + if (cgs.clientinfo[cgs.duelist3].modelIcon) { + CG_DrawPic(SCREEN_WIDTH - size - 10, SCREEN_HEIGHT - (size * 2.8), size, size, cgs.clientinfo[cgs.duelist3].modelIcon); } } - } - else - { - CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, s, 0, 0, 0, 3 ); + } else { + CG_Text_Paint(320 - CG_Text_Width(s, 1.0f, 3) / 2, 420, 1.0f, colorWhite, s, 0, 0, 0, 3); } - if ( cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL ) - { - s = CG_GetStringEdString("MP_INGAME", "WAITING_TO_PLAY"); // "waiting to play"; - CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 ); - } - else //if ( cgs.gametype >= GT_TEAM ) + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + s = CG_GetStringEdString("MP_INGAME", "WAITING_TO_PLAY"); // "waiting to play"; + CG_Text_Paint(320 - CG_Text_Width(s, 1.0f, 3) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3); + } else // if ( cgs.gametype >= GT_TEAM ) { - //s = "press ESC and use the JOIN menu to play"; + // s = "press ESC and use the JOIN menu to play"; s = CG_GetStringEdString("MP_INGAME", "SPEC_CHOOSEJOIN"); - CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 ); + CG_Text_Paint(320 - CG_Text_Width(s, 1.0f, 3) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3); } } @@ -6515,65 +5391,67 @@ static void CG_DrawVote(void) { int sec; char sYes[20] = {0}, sNo[20] = {0}, sVote[20] = {0}, sCmd[100] = {0}; - if ( !cgs.voteTime ) + if (!cgs.voteTime) return; // play a talk beep whenever it is modified - if ( cgs.voteModified ) { + if (cgs.voteModified) { cgs.voteModified = qfalse; - trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); + trap->S_StartLocalSound(cgs.media.talkSound, CHAN_LOCAL_SOUND); } - sec = ( VOTE_TIME - ( cg.time - cgs.voteTime ) ) / 1000; - if ( sec < 0 ) { + sec = (VOTE_TIME - (cg.time - cgs.voteTime)) / 1000; + if (sec < 0) { sec = 0; } - if ( !Q_strncmp( cgs.voteString, "map_restart", 11 ) ) - trap->SE_GetStringTextString( "MENUS_RESTART_MAP", sCmd, sizeof( sCmd ) ); - else if ( !Q_strncmp( cgs.voteString, "vstr nextmap", 12 ) ) - trap->SE_GetStringTextString( "MENUS_NEXT_MAP", sCmd, sizeof( sCmd ) ); - else if ( !Q_strncmp( cgs.voteString, "g_doWarmup", 10 ) ) - trap->SE_GetStringTextString( "MENUS_WARMUP", sCmd, sizeof( sCmd ) ); - else if ( !Q_strncmp( cgs.voteString, "g_gametype", 10 ) ) { - trap->SE_GetStringTextString( "MENUS_GAME_TYPE", sCmd, sizeof( sCmd ) ); - - if ( !Q_stricmp( "Free For All", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "FREE_FOR_ALL" ); - else if ( !Q_stricmp( "Duel", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "DUEL" ); - else if ( !Q_stricmp( "Holocron FFA", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "HOLOCRON_FFA" ); - else if ( !Q_stricmp( "Power Duel", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "POWERDUEL" ); - else if ( !Q_stricmp( "Team FFA", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "TEAM_FFA" ); - else if ( !Q_stricmp( "Siege", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "SIEGE" ); - else if ( !Q_stricmp( "Capture the Flag", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "CAPTURE_THE_FLAG" ); - else if ( !Q_stricmp( "Capture the Ysalamiri", cgs.voteString+11 ) ) sParm = CG_GetStringEdString( "MENUS", "CAPTURE_THE_YSALIMARI" ); - } - else if ( !Q_strncmp( cgs.voteString, "map", 3 ) ) { - trap->SE_GetStringTextString( "MENUS_NEW_MAP", sCmd, sizeof( sCmd ) ); - sParm = cgs.voteString+4; - } - else if ( !Q_strncmp( cgs.voteString, "kick", 4 ) ) { - trap->SE_GetStringTextString( "MENUS_KICK_PLAYER", sCmd, sizeof( sCmd ) ); - sParm = cgs.voteString+5; - } - else - {// custom votes like ampoll, cointoss, etc + if (!Q_strncmp(cgs.voteString, "map_restart", 11)) + trap->SE_GetStringTextString("MENUS_RESTART_MAP", sCmd, sizeof(sCmd)); + else if (!Q_strncmp(cgs.voteString, "vstr nextmap", 12)) + trap->SE_GetStringTextString("MENUS_NEXT_MAP", sCmd, sizeof(sCmd)); + else if (!Q_strncmp(cgs.voteString, "g_doWarmup", 10)) + trap->SE_GetStringTextString("MENUS_WARMUP", sCmd, sizeof(sCmd)); + else if (!Q_strncmp(cgs.voteString, "g_gametype", 10)) { + trap->SE_GetStringTextString("MENUS_GAME_TYPE", sCmd, sizeof(sCmd)); + + if (!Q_stricmp("Free For All", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "FREE_FOR_ALL"); + else if (!Q_stricmp("Duel", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "DUEL"); + else if (!Q_stricmp("Holocron FFA", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "HOLOCRON_FFA"); + else if (!Q_stricmp("Power Duel", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "POWERDUEL"); + else if (!Q_stricmp("Team FFA", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "TEAM_FFA"); + else if (!Q_stricmp("Siege", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "SIEGE"); + else if (!Q_stricmp("Capture the Flag", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"); + else if (!Q_stricmp("Capture the Ysalamiri", cgs.voteString + 11)) + sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"); + } else if (!Q_strncmp(cgs.voteString, "map", 3)) { + trap->SE_GetStringTextString("MENUS_NEW_MAP", sCmd, sizeof(sCmd)); + sParm = cgs.voteString + 4; + } else if (!Q_strncmp(cgs.voteString, "kick", 4)) { + trap->SE_GetStringTextString("MENUS_KICK_PLAYER", sCmd, sizeof(sCmd)); + sParm = cgs.voteString + 5; + } else { // custom votes like ampoll, cointoss, etc sParm = cgs.voteString; } - - - trap->SE_GetStringTextString( "MENUS_VOTE", sVote, sizeof( sVote ) ); - trap->SE_GetStringTextString( "MENUS_YES", sYes, sizeof( sYes ) ); - trap->SE_GetStringTextString( "MENUS_NO", sNo, sizeof( sNo ) ); + trap->SE_GetStringTextString("MENUS_VOTE", sVote, sizeof(sVote)); + trap->SE_GetStringTextString("MENUS_YES", sYes, sizeof(sYes)); + trap->SE_GetStringTextString("MENUS_NO", sNo, sizeof(sNo)); if (sParm && sParm[0]) - s = va( "%s(%i):<%s %s> %s:%i %s:%i", sVote, sec, sCmd, sParm, sYes, cgs.voteYes, sNo, cgs.voteNo); + s = va("%s(%i):<%s %s> %s:%i %s:%i", sVote, sec, sCmd, sParm, sYes, cgs.voteYes, sNo, cgs.voteNo); else - s = va( "%s(%i):<%s> %s:%i %s:%i", sVote, sec, sCmd, sYes, cgs.voteYes, sNo, cgs.voteNo); - CG_DrawSmallString( 4, 58, s, 1.0F ); - if ( cgs.clientinfo[cg.clientNum].team != TEAM_SPECTATOR ) { - s = CG_GetStringEdString( "MP_INGAME", "OR_PRESS_ESC_THEN_CLICK_VOTE" ); // s = "or press ESC then click Vote"; - CG_DrawSmallString( 4, 58 + SMALLCHAR_HEIGHT + 2, s, 1.0F ); + s = va("%s(%i):<%s> %s:%i %s:%i", sVote, sec, sCmd, sYes, cgs.voteYes, sNo, cgs.voteNo); + CG_DrawSmallString(4, 58, s, 1.0F); + if (cgs.clientinfo[cg.clientNum].team != TEAM_SPECTATOR) { + s = CG_GetStringEdString("MP_INGAME", "OR_PRESS_ESC_THEN_CLICK_VOTE"); // s = "or press ESC then click Vote"; + CG_DrawSmallString(4, 58 + SMALLCHAR_HEIGHT + 2, s, 1.0F); } } @@ -6583,48 +5461,44 @@ CG_DrawTeamVote ================= */ static void CG_DrawTeamVote(void) { - char *s; - int sec, cs_offset; + char *s; + int sec, cs_offset; - if ( cgs.clientinfo[cg.clientNum].team == TEAM_RED ) + if (cgs.clientinfo[cg.clientNum].team == TEAM_RED) cs_offset = 0; - else if ( cgs.clientinfo[cg.clientNum].team == TEAM_BLUE ) + else if (cgs.clientinfo[cg.clientNum].team == TEAM_BLUE) cs_offset = 1; else return; - if ( !cgs.teamVoteTime[cs_offset] ) { + if (!cgs.teamVoteTime[cs_offset]) { return; } // play a talk beep whenever it is modified - if ( cgs.teamVoteModified[cs_offset] ) { + if (cgs.teamVoteModified[cs_offset]) { cgs.teamVoteModified[cs_offset] = qfalse; -// trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); + // trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); } - sec = ( VOTE_TIME - ( cg.time - cgs.teamVoteTime[cs_offset] ) ) / 1000; - if ( sec < 0 ) { + sec = (VOTE_TIME - (cg.time - cgs.teamVoteTime[cs_offset])) / 1000; + if (sec < 0) { sec = 0; } - if (strstr(cgs.teamVoteString[cs_offset], "leader")) - { + if (strstr(cgs.teamVoteString[cs_offset], "leader")) { int i = 0; - while (cgs.teamVoteString[cs_offset][i] && cgs.teamVoteString[cs_offset][i] != ' ') - { + while (cgs.teamVoteString[cs_offset][i] && cgs.teamVoteString[cs_offset][i] != ' ') { i++; } - if (cgs.teamVoteString[cs_offset][i] == ' ') - { + if (cgs.teamVoteString[cs_offset][i] == ' ') { int voteIndex = 0; char voteIndexStr[256]; i++; - while (cgs.teamVoteString[cs_offset][i]) - { + while (cgs.teamVoteString[cs_offset][i]) { voteIndexStr[voteIndex] = cgs.teamVoteString[cs_offset][i]; voteIndex++; i++; @@ -6633,35 +5507,27 @@ static void CG_DrawTeamVote(void) { voteIndex = atoi(voteIndexStr); - s = va("TEAMVOTE(%i):(Make %s the new team leader) yes:%i no:%i", sec, cgs.clientinfo[voteIndex].name, - cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); - } - else - { - s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], - cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); + s = va("TEAMVOTE(%i):(Make %s the new team leader) yes:%i no:%i", sec, cgs.clientinfo[voteIndex].name, cgs.teamVoteYes[cs_offset], + cgs.teamVoteNo[cs_offset]); + } else { + s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset]); } + } else { + s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset]); } - else - { - s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset], - cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] ); - } - CG_DrawSmallString( 4, 90, s, 1.0F ); + CG_DrawSmallString(4, 90, s, 1.0F); } -static qboolean CG_DrawScoreboard() { - return CG_DrawOldScoreboard(); -} +static qboolean CG_DrawScoreboard() { return CG_DrawOldScoreboard(); } /* ================= CG_DrawIntermission ================= */ -static void CG_DrawIntermission( void ) { -// int key; - //if (cg_singlePlayer.integer) { +static void CG_DrawIntermission(void) { + // int key; + // if (cg_singlePlayer.integer) { // CG_DrawCenterString(); // return; //} @@ -6674,42 +5540,32 @@ static void CG_DrawIntermission( void ) { CG_DrawFollow ================= */ -static qboolean CG_DrawFollow( void ) -{ - const char *s; +static qboolean CG_DrawFollow(void) { + const char *s; - if ( !(cg.snap->ps.pm_flags & PMF_FOLLOW) ) - { + if (!(cg.snap->ps.pm_flags & PMF_FOLLOW)) { return qfalse; } -// s = "following"; - if (cgs.gametype == GT_POWERDUEL) - { - clientInfo_t *ci = &cgs.clientinfo[ cg.snap->ps.clientNum ]; + // s = "following"; + if (cgs.gametype == GT_POWERDUEL) { + clientInfo_t *ci = &cgs.clientinfo[cg.snap->ps.clientNum]; - if (ci->duelTeam == DUELTEAM_LONE) - { + if (ci->duelTeam == DUELTEAM_LONE) { s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGLONE"); - } - else if (ci->duelTeam == DUELTEAM_DOUBLE) - { + } else if (ci->duelTeam == DUELTEAM_DOUBLE) { s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGDOUBLE"); - } - else - { + } else { s = CG_GetStringEdString("MP_INGAME", "FOLLOWING"); } - } - else - { + } else { s = CG_GetStringEdString("MP_INGAME", "FOLLOWING"); } - CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, 60, 1.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM ); + CG_Text_Paint(320 - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, 60, 1.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM); - s = cgs.clientinfo[ cg.snap->ps.clientNum ].name; - CG_Text_Paint ( 320 - CG_Text_Width ( s, 2.0f, FONT_MEDIUM ) / 2, 80, 2.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM ); + s = cgs.clientinfo[cg.snap->ps.clientNum].name; + CG_Text_Paint(320 - CG_Text_Width(s, 2.0f, FONT_MEDIUM) / 2, 80, 2.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM); return qtrue; } @@ -6747,7 +5603,7 @@ static void CG_DrawTemporaryStats() CG_DrawAmmoWarning ================= */ -static void CG_DrawAmmoWarning( void ) { +static void CG_DrawAmmoWarning(void) { #if 0 const char *s; int w; @@ -6775,61 +5631,52 @@ static void CG_DrawAmmoWarning( void ) { #endif } - - /* ================= CG_DrawWarmup ================= */ -static void CG_DrawWarmup( void ) { - int w, sec, i; - float scale; - const char *s; +static void CG_DrawWarmup(void) { + int w, sec, i; + float scale; + const char *s; sec = cg.warmup; - if ( !sec ) { + if (!sec) { return; } - if ( sec < 0 ) { -// s = "Waiting for players"; + if (sec < 0) { + // s = "Waiting for players"; s = CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS"); - w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; + w = CG_DrawStrlen(s) * BIGCHAR_WIDTH; CG_DrawBigString(320 - w / 2, 24, s, 1.0F); cg.warmupCount = 0; return; } - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) - { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { // find the two active players - clientInfo_t *ci1, *ci2, *ci3; + clientInfo_t *ci1, *ci2, *ci3; ci1 = NULL; ci2 = NULL; ci3 = NULL; - if (cgs.gametype == GT_POWERDUEL) - { - if (cgs.duelist1 != -1) - { + if (cgs.gametype == GT_POWERDUEL) { + if (cgs.duelist1 != -1) { ci1 = &cgs.clientinfo[cgs.duelist1]; } - if (cgs.duelist2 != -1) - { + if (cgs.duelist2 != -1) { ci2 = &cgs.clientinfo[cgs.duelist2]; } - if (cgs.duelist3 != -1) - { + if (cgs.duelist3 != -1) { ci3 = &cgs.clientinfo[cgs.duelist3]; } - } - else - { - for ( i = 0 ; i < cgs.maxclients ; i++ ) { - if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_FREE ) { - if ( !ci1 ) { + } else { + for (i = 0; i < cgs.maxclients; i++) { + if (cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_FREE) { + if (!ci1) { ci1 = &cgs.clientinfo[i]; } else { ci2 = &cgs.clientinfo[i]; @@ -6837,54 +5684,58 @@ static void CG_DrawWarmup( void ) { } } } - if ( ci1 && ci2 ) - { - if (ci3) - { - s = va( "%s vs %s and %s", ci1->name, ci2->name, ci3->name ); - } - else - { - s = va( "%s vs %s", ci1->name, ci2->name ); + if (ci1 && ci2) { + if (ci3) { + s = va("%s vs %s and %s", ci1->name, ci2->name, ci3->name); + } else { + s = va("%s vs %s", ci1->name, ci2->name); } w = CG_Text_Width(s, 0.6f, FONT_MEDIUM); - CG_Text_Paint(320 - w / 2, 60, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM); + CG_Text_Paint(320 - w / 2, 60, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); } } else { - if ( cgs.gametype == GT_FFA ) s = CG_GetStringEdString("MENUS", "FREE_FOR_ALL");//"Free For All"; - else if ( cgs.gametype == GT_HOLOCRON ) s = CG_GetStringEdString("MENUS", "HOLOCRON_FFA");//"Holocron FFA"; - else if ( cgs.gametype == GT_JEDIMASTER ) s = "Jedi Master"; - else if ( cgs.gametype == GT_TEAM ) s = CG_GetStringEdString("MENUS", "TEAM_FFA");//"Team FFA"; - else if ( cgs.gametype == GT_SIEGE ) s = CG_GetStringEdString("MENUS", "SIEGE");//"Siege"; - else if ( cgs.gametype == GT_CTF ) s = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG");//"Capture the Flag"; - else if ( cgs.gametype == GT_CTY ) s = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI");//"Capture the Ysalamiri"; - else if ( cgs.gametype == GT_SINGLE_PLAYER ) s = "Cooperative"; - else s = ""; + if (cgs.gametype == GT_FFA) + s = CG_GetStringEdString("MENUS", "FREE_FOR_ALL"); //"Free For All"; + else if (cgs.gametype == GT_HOLOCRON) + s = CG_GetStringEdString("MENUS", "HOLOCRON_FFA"); //"Holocron FFA"; + else if (cgs.gametype == GT_JEDIMASTER) + s = "Jedi Master"; + else if (cgs.gametype == GT_TEAM) + s = CG_GetStringEdString("MENUS", "TEAM_FFA"); //"Team FFA"; + else if (cgs.gametype == GT_SIEGE) + s = CG_GetStringEdString("MENUS", "SIEGE"); //"Siege"; + else if (cgs.gametype == GT_CTF) + s = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"); //"Capture the Flag"; + else if (cgs.gametype == GT_CTY) + s = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"); //"Capture the Ysalamiri"; + else if (cgs.gametype == GT_SINGLE_PLAYER) + s = "Cooperative"; + else + s = ""; w = CG_Text_Width(s, 1.5f, FONT_MEDIUM); - CG_Text_Paint(320 - w / 2, 90, 1.5f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM); + CG_Text_Paint(320 - w / 2, 90, 1.5f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); } - sec = ( sec - cg.time ) / 1000; - if ( sec < 0 ) { + sec = (sec - cg.time) / 1000; + if (sec < 0) { cg.warmup = 0; sec = 0; } -// s = va( "Starts in: %i", sec + 1 ); - s = va( "%s: %i",CG_GetStringEdString("MP_INGAME", "STARTS_IN"), sec + 1 ); - if ( sec != cg.warmupCount ) { + // s = va( "Starts in: %i", sec + 1 ); + s = va("%s: %i", CG_GetStringEdString("MP_INGAME", "STARTS_IN"), sec + 1); + if (sec != cg.warmupCount) { cg.warmupCount = sec; - if (cgs.gametype != GT_SIEGE) - { - switch ( sec ) { + if (cgs.gametype != GT_SIEGE) { + switch (sec) { case 0: - trap->S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count1Sound, CHAN_ANNOUNCER); break; case 1: - trap->S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count2Sound, CHAN_ANNOUNCER); break; case 2: - trap->S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count3Sound, CHAN_ANNOUNCER); break; default: break; @@ -6892,7 +5743,7 @@ static void CG_DrawWarmup( void ) { } } scale = 0.45f; - switch ( cg.warmupCount ) { + switch (cg.warmupCount) { case 0: scale = 1.25f; break; @@ -6920,7 +5771,7 @@ CG_DrawTimedMenus void CG_DrawTimedMenus() { if (cg.voiceTime) { int t = cg.time - cg.voiceTime; - if ( t > 2500 ) { + if (t > 2500) { Menus_CloseByName("voiceMenu"); trap->Cvar_Set("cl_conXOffset", "0"); cg.voiceTime = 0; @@ -6928,219 +5779,193 @@ void CG_DrawTimedMenus() { } } -void CG_DrawFlagStatus() -{ +void CG_DrawFlagStatus() { int myFlagTakenShader = 0; int theirFlagShader = 0; int team = 0; int startDrawPos = 2; int ico_size = 32; - //Raz: was missing this - trap->R_SetColor( NULL ); + // Raz: was missing this + trap->R_SetColor(NULL); - if (!cg.snap) - { + if (!cg.snap) { return; } - if (cgs.gametype != GT_CTF && cgs.gametype != GT_CTY) - { + if (cgs.gametype != GT_CTF && cgs.gametype != GT_CTY) { return; } team = cg.snap->ps.persistant[PERS_TEAM]; - if (cgs.gametype == GT_CTY) - { - if (team == TEAM_RED) - { - myFlagTakenShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" ); - theirFlagShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" ); - } - else - { - myFlagTakenShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" ); - theirFlagShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" ); - } - } - else - { - if (team == TEAM_RED) - { - myFlagTakenShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" ); - theirFlagShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag" ); + if (cgs.gametype == GT_CTY) { + if (team == TEAM_RED) { + myFlagTakenShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_x"); + theirFlagShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_ys"); + } else { + myFlagTakenShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_x"); + theirFlagShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_ys"); } - else - { - myFlagTakenShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" ); - theirFlagShader = trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag" ); + } else { + if (team == TEAM_RED) { + myFlagTakenShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_x"); + theirFlagShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag"); + } else { + myFlagTakenShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_x"); + theirFlagShader = trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag"); } } - if (CG_YourTeamHasFlag()) - { - //CG_DrawPic( startDrawPos, 330, ico_size, ico_size, theirFlagShader ); - CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, theirFlagShader ); - startDrawPos += ico_size+2; + if (CG_YourTeamHasFlag()) { + // CG_DrawPic( startDrawPos, 330, ico_size, ico_size, theirFlagShader ); + CG_DrawPic(2, 330 - startDrawPos, ico_size, ico_size, theirFlagShader); + startDrawPos += ico_size + 2; } - if (CG_OtherTeamHasFlag()) - { - //CG_DrawPic( startDrawPos, 330, ico_size, ico_size, myFlagTakenShader ); - CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, myFlagTakenShader ); + if (CG_OtherTeamHasFlag()) { + // CG_DrawPic( startDrawPos, 330, ico_size, ico_size, myFlagTakenShader ); + CG_DrawPic(2, 330 - startDrawPos, ico_size, ico_size, myFlagTakenShader); } } -//draw meter showing jetpack fuel when it's not full -#define JPFUELBAR_H 100.0f -#define JPFUELBAR_W 20.0f -#define JPFUELBAR_X (SCREEN_WIDTH-JPFUELBAR_W-8.0f) -#define JPFUELBAR_Y 260.0f -void CG_DrawJetpackFuel(void) -{ +// draw meter showing jetpack fuel when it's not full +#define JPFUELBAR_H 100.0f +#define JPFUELBAR_W 20.0f +#define JPFUELBAR_X (SCREEN_WIDTH - JPFUELBAR_W - 8.0f) +#define JPFUELBAR_Y 260.0f +void CG_DrawJetpackFuel(void) { vec4_t aColor; vec4_t cColor; float x = JPFUELBAR_X; float y = JPFUELBAR_Y; - float percent = ((float)cg.snap->ps.jetpackFuel/100.0f)*JPFUELBAR_H; + float percent = ((float)cg.snap->ps.jetpackFuel / 100.0f) * JPFUELBAR_H; - if (percent > JPFUELBAR_H) - { + if (percent > JPFUELBAR_H) { return; } - if (percent < 0.1f) - { + if (percent < 0.1f) { percent = 0.1f; } - //color of the bar + // color of the bar aColor[0] = 0.5f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.8f; - //color of greyed out "missing fuel" + // color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, JPFUELBAR_W, JPFUELBAR_H, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f+(JPFUELBAR_H-percent), JPFUELBAR_W-1.0f, JPFUELBAR_H-1.0f-(JPFUELBAR_H-percent), aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f + (JPFUELBAR_H - percent), JPFUELBAR_W - 1.0f, JPFUELBAR_H - 1.0f - (JPFUELBAR_H - percent), aColor); - //then draw the other part greyed out - CG_FillRect(x+1.0f, y+1.0f, JPFUELBAR_W-1.0f, JPFUELBAR_H-percent, cColor); + // then draw the other part greyed out + CG_FillRect(x + 1.0f, y + 1.0f, JPFUELBAR_W - 1.0f, JPFUELBAR_H - percent, cColor); } -//draw meter showing e-web health when it is in use -#define EWEBHEALTH_H 100.0f -#define EWEBHEALTH_W 20.0f -#define EWEBHEALTH_X (SCREEN_WIDTH-EWEBHEALTH_W-8.0f) -#define EWEBHEALTH_Y 290.0f -void CG_DrawEWebHealth(void) -{ +// draw meter showing e-web health when it is in use +#define EWEBHEALTH_H 100.0f +#define EWEBHEALTH_W 20.0f +#define EWEBHEALTH_X (SCREEN_WIDTH - EWEBHEALTH_W - 8.0f) +#define EWEBHEALTH_Y 290.0f +void CG_DrawEWebHealth(void) { vec4_t aColor; vec4_t cColor; float x = EWEBHEALTH_X; float y = EWEBHEALTH_Y; centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex]; - float percent = ((float)eweb->currentState.health/eweb->currentState.maxhealth)*EWEBHEALTH_H; + float percent = ((float)eweb->currentState.health / eweb->currentState.maxhealth) * EWEBHEALTH_H; - if (percent > EWEBHEALTH_H) - { + if (percent > EWEBHEALTH_H) { return; } - if (percent < 0.1f) - { + if (percent < 0.1f) { percent = 0.1f; } - //kind of hacky, need to pass a coordinate in here - if (cg.snap->ps.jetpackFuel < 100) - { - x -= (JPFUELBAR_W+8.0f); + // kind of hacky, need to pass a coordinate in here + if (cg.snap->ps.jetpackFuel < 100) { + x -= (JPFUELBAR_W + 8.0f); } - if (cg.snap->ps.cloakFuel < 100) - { - x -= (JPFUELBAR_W+8.0f); + if (cg.snap->ps.cloakFuel < 100) { + x -= (JPFUELBAR_W + 8.0f); } - //color of the bar + // color of the bar aColor[0] = 0.5f; aColor[1] = 0.0f; aColor[2] = 0.0f; aColor[3] = 0.8f; - //color of greyed out "missing fuel" + // color of greyed out "missing fuel" cColor[0] = 0.5f; cColor[1] = 0.5f; cColor[2] = 0.5f; cColor[3] = 0.1f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, EWEBHEALTH_W, EWEBHEALTH_H, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much health there is in the color specified - CG_FillRect(x+1.0f, y+1.0f+(EWEBHEALTH_H-percent), EWEBHEALTH_W-1.0f, EWEBHEALTH_H-1.0f-(EWEBHEALTH_H-percent), aColor); + // now draw the part to show how much health there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f + (EWEBHEALTH_H - percent), EWEBHEALTH_W - 1.0f, EWEBHEALTH_H - 1.0f - (EWEBHEALTH_H - percent), aColor); - //then draw the other part greyed out - CG_FillRect(x+1.0f, y+1.0f, EWEBHEALTH_W-1.0f, EWEBHEALTH_H-percent, cColor); + // then draw the other part greyed out + CG_FillRect(x + 1.0f, y + 1.0f, EWEBHEALTH_W - 1.0f, EWEBHEALTH_H - percent, cColor); } -//draw meter showing cloak fuel when it's not full -#define CLFUELBAR_H 100.0f -#define CLFUELBAR_W 20.0f -#define CLFUELBAR_X (SCREEN_WIDTH-CLFUELBAR_W-8.0f) -#define CLFUELBAR_Y 260.0f -void CG_DrawCloakFuel(void) -{ +// draw meter showing cloak fuel when it's not full +#define CLFUELBAR_H 100.0f +#define CLFUELBAR_W 20.0f +#define CLFUELBAR_X (SCREEN_WIDTH - CLFUELBAR_W - 8.0f) +#define CLFUELBAR_Y 260.0f +void CG_DrawCloakFuel(void) { vec4_t aColor; vec4_t cColor; float x = CLFUELBAR_X; float y = CLFUELBAR_Y; - float percent = ((float)cg.snap->ps.cloakFuel/100.0f)*CLFUELBAR_H; + float percent = ((float)cg.snap->ps.cloakFuel / 100.0f) * CLFUELBAR_H; - if (percent > CLFUELBAR_H) - { + if (percent > CLFUELBAR_H) { return; } - if ( cg.snap->ps.jetpackFuel < 100 ) - {//if drawing jetpack fuel bar too, then move this over...? - x -= (JPFUELBAR_W+8.0f); + if (cg.snap->ps.jetpackFuel < 100) { // if drawing jetpack fuel bar too, then move this over...? + x -= (JPFUELBAR_W + 8.0f); } - if (percent < 0.1f) - { + if (percent < 0.1f) { percent = 0.1f; } - //color of the bar + // color of the bar aColor[0] = 0.0f; aColor[1] = 0.0f; aColor[2] = 0.6f; aColor[3] = 0.8f; - //color of greyed out "missing fuel" + // color of greyed out "missing fuel" cColor[0] = 0.1f; cColor[1] = 0.1f; cColor[2] = 0.3f; cColor[3] = 0.1f; - //draw the background (black) + // draw the background (black) CG_DrawRect(x, y, CLFUELBAR_W, CLFUELBAR_H, 1.0f, colorTable[CT_BLACK]); - //now draw the part to show how much fuel there is in the color specified - CG_FillRect(x+1.0f, y+1.0f+(CLFUELBAR_H-percent), CLFUELBAR_W-1.0f, CLFUELBAR_H-1.0f-(CLFUELBAR_H-percent), aColor); + // now draw the part to show how much fuel there is in the color specified + CG_FillRect(x + 1.0f, y + 1.0f + (CLFUELBAR_H - percent), CLFUELBAR_W - 1.0f, CLFUELBAR_H - 1.0f - (CLFUELBAR_H - percent), aColor); - //then draw the other part greyed out - CG_FillRect(x+1.0f, y+1.0f, CLFUELBAR_W-1.0f, CLFUELBAR_H-percent, cColor); + // then draw the other part greyed out + CG_FillRect(x + 1.0f, y + 1.0f, CLFUELBAR_W - 1.0f, CLFUELBAR_H - percent, cColor); } int cgRageTime = 0; @@ -7182,134 +6007,95 @@ int cg_beatingSiegeTime = 0; int cgSiegeRoundBeganTime = 0; int cgSiegeRoundCountTime = 0; -static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam) -{ //rwwFIXMEFIXME: Make someone make assets and use them. - //this function is pretty much totally placeholder. -// int x = 0; -// int y = SCREEN_HEIGHT-160; +static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam) { // rwwFIXMEFIXME: Make someone make assets and use them. + // this function is pretty much totally placeholder. + // int x = 0; + // int y = SCREEN_HEIGHT-160; int fColor = 0; int minutes = 0; int seconds = 0; char timeStr[1024]; - menuDef_t *menuHUD = NULL; - itemDef_t *item = NULL; + menuDef_t *menuHUD = NULL; + itemDef_t *item = NULL; menuHUD = Menus_FindByName("mp_timer"); - if (!menuHUD) - { + if (!menuHUD) { return; } item = Menu_FindItemByName(menuHUD, "frame"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } seconds = timeRemaining; - while (seconds >= 60) - { + while (seconds >= 60) { minutes++; seconds -= 60; } - strcpy(timeStr, va( "%i:%02i", minutes, seconds )); + strcpy(timeStr, va("%i:%02i", minutes, seconds)); - if (isMyTeam) - { + if (isMyTeam) { fColor = CT_HUD_RED; - } - else - { + } else { fColor = CT_HUD_GREEN; } -// trap->Cvar_Set("ui_siegeTimer", timeStr); + // trap->Cvar_Set("ui_siegeTimer", timeStr); -// CG_DrawProportionalString( x+16, y+40, timeStr, UI_SMALLFONT|UI_DROPSHADOW, colorTable[fColor] ); + // CG_DrawProportionalString( x+16, y+40, timeStr, UI_SMALLFONT|UI_DROPSHADOW, colorTable[fColor] ); item = Menu_FindItemByName(menuHUD, "timer"); - if (item) - { - CG_DrawProportionalString( - item->window.rect.x, - item->window.rect.y, - timeStr, - UI_SMALLFONT|UI_DROPSHADOW, - colorTable[fColor] ); + if (item) { + CG_DrawProportionalString(item->window.rect.x, item->window.rect.y, timeStr, UI_SMALLFONT | UI_DROPSHADOW, colorTable[fColor]); } - } -static void CG_DrawSiegeDeathTimer( int timeRemaining ) -{ +static void CG_DrawSiegeDeathTimer(int timeRemaining) { int minutes = 0; int seconds = 0; char timeStr[1024]; - menuDef_t *menuHUD = NULL; - itemDef_t *item = NULL; + menuDef_t *menuHUD = NULL; + itemDef_t *item = NULL; menuHUD = Menus_FindByName("mp_timer"); - if (!menuHUD) - { + if (!menuHUD) { return; } item = Menu_FindItemByName(menuHUD, "frame"); - if (item) - { - trap->R_SetColor( item->window.foreColor ); - CG_DrawPic( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - item->window.background ); + if (item) { + trap->R_SetColor(item->window.foreColor); + CG_DrawPic(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->window.background); } seconds = timeRemaining; - while (seconds >= 60) - { + while (seconds >= 60) { minutes++; seconds -= 60; } - if (seconds < 10) - { - strcpy(timeStr, va( "%i:0%i", minutes, seconds )); - } - else - { - strcpy(timeStr, va( "%i:%i", minutes, seconds )); + if (seconds < 10) { + strcpy(timeStr, va("%i:0%i", minutes, seconds)); + } else { + strcpy(timeStr, va("%i:%i", minutes, seconds)); } item = Menu_FindItemByName(menuHUD, "deathtimer"); - if (item) - { - CG_DrawProportionalString( - item->window.rect.x, - item->window.rect.y, - timeStr, - UI_SMALLFONT|UI_DROPSHADOW, - item->window.foreColor ); + if (item) { + CG_DrawProportionalString(item->window.rect.x, item->window.rect.y, timeStr, UI_SMALLFONT | UI_DROPSHADOW, item->window.foreColor); } - } int cgSiegeEntityRender = 0; -static void CG_DrawSiegeHUDItem(void) -{ +static void CG_DrawSiegeHUDItem(void) { void *g2; qhandle_t handle; vec3_t origin, angles; @@ -7317,86 +6103,74 @@ static void CG_DrawSiegeHUDItem(void) float len; centity_t *cent = &cg_entities[cgSiegeEntityRender]; - if (cent->ghoul2) - { + if (cent->ghoul2) { g2 = cent->ghoul2; handle = 0; - } - else - { + } else { handle = cgs.gameModels[cent->currentState.modelindex]; g2 = NULL; } - if (handle) - { - trap->R_ModelBounds( handle, mins, maxs ); - } - else - { + if (handle) { + trap->R_ModelBounds(handle, mins, maxs); + } else { VectorSet(mins, -16, -16, -20); VectorSet(maxs, 16, 16, 32); } - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); - len = 0.5 * ( maxs[2] - mins[2] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); + len = 0.5 * (maxs[2] - mins[2]); origin[0] = len / 0.268; VectorClear(angles); angles[YAW] = cg.autoAngles[YAW]; - CG_Draw3DModel( 8, 8, 64, 64, handle, g2, cent->currentState.g2radius, 0, origin, angles ); + CG_Draw3DModel(8, 8, 64, 64, handle, g2, cent->currentState.g2radius, 0, origin, angles); - cgSiegeEntityRender = 0; //reset for next frame + cgSiegeEntityRender = 0; // reset for next frame } /*==================================== chatbox functionality -rww ====================================*/ -#define CHATBOX_CUTOFF_LEN 550 -#define CHATBOX_FONT_HEIGHT 20 +#define CHATBOX_CUTOFF_LEN 550 +#define CHATBOX_FONT_HEIGHT 20 -//utility func, insert a string into a string at the specified -//place (assuming this will not overflow the buffer) -void CG_ChatBox_StrInsert(char *buffer, int place, char *str) -{ +// utility func, insert a string into a string at the specified +// place (assuming this will not overflow the buffer) +void CG_ChatBox_StrInsert(char *buffer, int place, char *str) { int insLen = strlen(str); int i = strlen(buffer); int k = 0; - buffer[i+insLen+1] = 0; //terminate the string at its new length - while (i >= place) - { - buffer[i+insLen] = buffer[i]; + buffer[i + insLen + 1] = 0; // terminate the string at its new length + while (i >= place) { + buffer[i + insLen] = buffer[i]; i--; } i++; - while (k < insLen) - { + while (k < insLen) { buffer[i] = str[k]; i++; k++; } } -//add chatbox string -void CG_ChatBox_AddString(char *chatStr) -{ +// add chatbox string +void CG_ChatBox_AddString(char *chatStr) { chatBoxItem_t *chat = &cg.chatItems[cg.chatItemActive]; float chatLen; - if (cg_chatBox.integer<=0) - { //don't bother then. + if (cg_chatBox.integer <= 0) { // don't bother then. return; } memset(chat, 0, sizeof(chatBoxItem_t)); - if (strlen(chatStr) > sizeof(chat->string)) - { //too long, terminate at proper len. - chatStr[sizeof(chat->string)-1] = 0; + if (strlen(chatStr) > sizeof(chat->string)) { // too long, terminate at proper len. + chatStr[sizeof(chat->string) - 1] = 0; } strcpy(chat->string, chatStr); @@ -7405,71 +6179,60 @@ void CG_ChatBox_AddString(char *chatStr) chat->lines = 1; chatLen = CG_Text_Width(chat->string, 1.0f, FONT_SMALL); - if (chatLen > CHATBOX_CUTOFF_LEN) - { //we have to break it into segments... - int i = 0; + if (chatLen > CHATBOX_CUTOFF_LEN) { // we have to break it into segments... + int i = 0; int lastLinePt = 0; char s[2]; chatLen = 0; - while (chat->string[i]) - { + while (chat->string[i]) { s[0] = chat->string[i]; s[1] = 0; chatLen += CG_Text_Width(s, 0.65f, FONT_SMALL); - if (chatLen >= CHATBOX_CUTOFF_LEN) - { + if (chatLen >= CHATBOX_CUTOFF_LEN) { int j = i; - while (j > 0 && j > lastLinePt) - { - if (chat->string[j] == ' ') - { + while (j > 0 && j > lastLinePt) { + if (chat->string[j] == ' ') { break; } j--; } - if (chat->string[j] == ' ') - { + if (chat->string[j] == ' ') { i = j; } - chat->lines++; + chat->lines++; CG_ChatBox_StrInsert(chat->string, i, "\n"); i++; chatLen = 0; - lastLinePt = i+1; + lastLinePt = i + 1; } i++; } } cg.chatItemActive++; - if (cg.chatItemActive >= MAX_CHATBOX_ITEMS) - { + if (cg.chatItemActive >= MAX_CHATBOX_ITEMS) { cg.chatItemActive = 0; } } -//insert item into array (rearranging the array if necessary) -void CG_ChatBox_ArrayInsert(chatBoxItem_t **array, int insPoint, int maxNum, chatBoxItem_t *item) -{ - if (array[insPoint]) - { //recursively call, to move everything up to the top - if (insPoint+1 >= maxNum) - { - trap->Error( ERR_DROP, "CG_ChatBox_ArrayInsert: Exceeded array size"); +// insert item into array (rearranging the array if necessary) +void CG_ChatBox_ArrayInsert(chatBoxItem_t **array, int insPoint, int maxNum, chatBoxItem_t *item) { + if (array[insPoint]) { // recursively call, to move everything up to the top + if (insPoint + 1 >= maxNum) { + trap->Error(ERR_DROP, "CG_ChatBox_ArrayInsert: Exceeded array size"); } - CG_ChatBox_ArrayInsert(array, insPoint+1, maxNum, array[insPoint]); + CG_ChatBox_ArrayInsert(array, insPoint + 1, maxNum, array[insPoint]); } - //now that we have moved anything that would be in this slot up, insert what we want into the slot + // now that we have moved anything that would be in this slot up, insert what we want into the slot array[insPoint] = item; } -//go through all the chat strings and draw them if they are not yet expired -static QINLINE void CG_ChatBox_DrawStrings(void) -{ +// go through all the chat strings and draw them if they are not yet expired +static QINLINE void CG_ChatBox_DrawStrings(void) { chatBoxItem_t *drawThese[MAX_CHATBOX_ITEMS]; int numToDraw = 0; int linesToDraw = 0; @@ -7478,25 +6241,19 @@ static QINLINE void CG_ChatBox_DrawStrings(void) float y = cg.scoreBoardShowing ? 475 : cg_chatBoxHeight.integer; float fontScale = 0.65f; - if (!cg_chatBox.integer) - { + if (!cg_chatBox.integer) { return; } memset(drawThese, 0, sizeof(drawThese)); - while (i < MAX_CHATBOX_ITEMS) - { - if (cg.chatItems[i].time >= cg.time) - { + while (i < MAX_CHATBOX_ITEMS) { + if (cg.chatItems[i].time >= cg.time) { int check = numToDraw; int insertionPoint = numToDraw; - while (check >= 0) - { - if (drawThese[check] && - cg.chatItems[i].time < drawThese[check]->time) - { //insert here + while (check >= 0) { + if (drawThese[check] && cg.chatItems[i].time < drawThese[check]->time) { // insert here insertionPoint = check; } check--; @@ -7508,34 +6265,28 @@ static QINLINE void CG_ChatBox_DrawStrings(void) i++; } - if (!numToDraw) - { //nothing, then, just get out of here now. + if (!numToDraw) { // nothing, then, just get out of here now. return; } - //move initial point up so we draw bottom-up (visually) - y -= (CHATBOX_FONT_HEIGHT*fontScale)*linesToDraw; + // move initial point up so we draw bottom-up (visually) + y -= (CHATBOX_FONT_HEIGHT * fontScale) * linesToDraw; - //we have the items we want to draw, just quickly loop through them now + // we have the items we want to draw, just quickly loop through them now i = 0; - while (i < numToDraw) - { - CG_Text_Paint(x, y, fontScale, colorWhite, drawThese[i]->string, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - y += ((CHATBOX_FONT_HEIGHT*fontScale)*drawThese[i]->lines); + while (i < numToDraw) { + CG_Text_Paint(x, y, fontScale, colorWhite, drawThese[i]->string, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + y += ((CHATBOX_FONT_HEIGHT * fontScale) * drawThese[i]->lines); i++; } } -static void CG_Draw2DScreenTints( void ) -{ - float rageTime, rageRecTime, absorbTime, protectTime, ysalTime; - vec4_t hcolor; - if (cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) - { - if (cg.snap->ps.fd.forcePowersActive & (1 << FP_RAGE)) - { - if (!cgRageTime) - { +static void CG_Draw2DScreenTints(void) { + float rageTime, rageRecTime, absorbTime, protectTime, ysalTime; + vec4_t hcolor; + if (cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR) { + if (cg.snap->ps.fd.forcePowersActive & (1 << FP_RAGE)) { + if (!cgRageTime) { cgRageTime = cg.time; } @@ -7543,12 +6294,10 @@ static void CG_Draw2DScreenTints( void ) rageTime /= 9000; - if (rageTime < 0) - { + if (rageTime < 0) { rageTime = 0; } - if (rageTime > 0.15) - { + if (rageTime > 0.15) { rageTime = 0.15f; } @@ -7557,82 +6306,64 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0; hcolor[2] = 0; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageFadeTime = 0; cgRageFadeVal = 0; - } - else if (cgRageTime) - { - if (!cgRageFadeTime) - { + } else if (cgRageTime) { + if (!cgRageFadeTime) { cgRageFadeTime = cg.time; cgRageFadeVal = 0.15f; } rageTime = cgRageFadeVal; - cgRageFadeVal -= (cg.time - cgRageFadeTime)*0.000005; + cgRageFadeVal -= (cg.time - cgRageFadeTime) * 0.000005; - if (rageTime < 0) - { + if (rageTime < 0) { rageTime = 0; } - if (rageTime > 0.15f) - { + if (rageTime > 0.15f) { rageTime = 0.15f; } - if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) - { + if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { float checkRageRecTime = rageTime; - if (checkRageRecTime < 0.15f) - { + if (checkRageRecTime < 0.15f) { checkRageRecTime = 0.15f; } hcolor[3] = checkRageRecTime; - hcolor[0] = rageTime*4; - if (hcolor[0] < 0.2f) - { + hcolor[0] = rageTime * 4; + if (hcolor[0] < 0.2f) { hcolor[0] = 0.2f; } hcolor[1] = 0.2f; hcolor[2] = 0.2f; - } - else - { + } else { hcolor[3] = rageTime; hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; } - if (!cg.renderingThirdPerson && rageTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { - if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) - { + if (!cg.renderingThirdPerson && rageTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { + if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { hcolor[3] = 0.15f; hcolor[0] = 0.2f; hcolor[1] = 0.2f; hcolor[2] = 0.2f; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageTime = 0; } - } - else if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) - { - if (!cgRageRecTime) - { + } else if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { + if (!cgRageRecTime) { cgRageRecTime = cg.time; } @@ -7640,12 +6371,11 @@ static void CG_Draw2DScreenTints( void ) rageRecTime /= 9000; - if (rageRecTime < 0.15f)//0) + if (rageRecTime < 0.15f) // 0) { - rageRecTime = 0.15f;//0; + rageRecTime = 0.15f; // 0; } - if (rageRecTime > 0.15f) - { + if (rageRecTime > 0.15f) { rageRecTime = 0.15f; } @@ -7654,32 +6384,26 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0.2f; hcolor[2] = 0.2f; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgRageRecFadeTime = 0; cgRageRecFadeVal = 0; - } - else if (cgRageRecTime) - { - if (!cgRageRecFadeTime) - { + } else if (cgRageRecTime) { + if (!cgRageRecFadeTime) { cgRageRecFadeTime = cg.time; cgRageRecFadeVal = 0.15f; } rageRecTime = cgRageRecFadeVal; - cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime)*0.000005; + cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime) * 0.000005; - if (rageRecTime < 0) - { + if (rageRecTime < 0) { rageRecTime = 0; } - if (rageRecTime > 0.15f) - { + if (rageRecTime > 0.15f) { rageRecTime = 0.15f; } @@ -7688,20 +6412,15 @@ static void CG_Draw2DScreenTints( void ) hcolor[1] = 0.2f; hcolor[2] = 0.2f; - if (!cg.renderingThirdPerson && rageRecTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && rageRecTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgRageRecTime = 0; } } - if (cg.snap->ps.fd.forcePowersActive & (1 << FP_ABSORB)) - { - if (!cgAbsorbTime) - { + if (cg.snap->ps.fd.forcePowersActive & (1 << FP_ABSORB)) { + if (!cgAbsorbTime) { cgAbsorbTime = cg.time; } @@ -7709,68 +6428,55 @@ static void CG_Draw2DScreenTints( void ) absorbTime /= 9000; - if (absorbTime < 0) - { + if (absorbTime < 0) { absorbTime = 0; } - if (absorbTime > 0.15f) - { + if (absorbTime > 0.15f) { absorbTime = 0.15f; } - hcolor[3] = absorbTime/2; + hcolor[3] = absorbTime / 2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgAbsorbFadeTime = 0; cgAbsorbFadeVal = 0; - } - else if (cgAbsorbTime) - { - if (!cgAbsorbFadeTime) - { + } else if (cgAbsorbTime) { + if (!cgAbsorbFadeTime) { cgAbsorbFadeTime = cg.time; cgAbsorbFadeVal = 0.15f; } absorbTime = cgAbsorbFadeVal; - cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime)*0.000005f; + cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime) * 0.000005f; - if (absorbTime < 0) - { + if (absorbTime < 0) { absorbTime = 0; } - if (absorbTime > 0.15f) - { + if (absorbTime > 0.15f) { absorbTime = 0.15f; } - hcolor[3] = absorbTime/2; + hcolor[3] = absorbTime / 2; hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; - if (!cg.renderingThirdPerson && absorbTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && absorbTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgAbsorbTime = 0; } } - if (cg.snap->ps.fd.forcePowersActive & (1 << FP_PROTECT)) - { - if (!cgProtectTime) - { + if (cg.snap->ps.fd.forcePowersActive & (1 << FP_PROTECT)) { + if (!cgProtectTime) { cgProtectTime = cg.time; } @@ -7778,73 +6484,59 @@ static void CG_Draw2DScreenTints( void ) protectTime /= 9000; - if (protectTime < 0) - { + if (protectTime < 0) { protectTime = 0; } - if (protectTime > 0.15f) - { + if (protectTime > 0.15f) { protectTime = 0.15f; } - hcolor[3] = protectTime/2; + hcolor[3] = protectTime / 2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgProtectFadeTime = 0; cgProtectFadeVal = 0; - } - else if (cgProtectTime) - { - if (!cgProtectFadeTime) - { + } else if (cgProtectTime) { + if (!cgProtectFadeTime) { cgProtectFadeTime = cg.time; cgProtectFadeVal = 0.15f; } protectTime = cgProtectFadeVal; - cgProtectFadeVal -= (cg.time - cgProtectFadeTime)*0.000005; + cgProtectFadeVal -= (cg.time - cgProtectFadeTime) * 0.000005; - if (protectTime < 0) - { + if (protectTime < 0) { protectTime = 0; } - if (protectTime > 0.15f) - { + if (protectTime > 0.15f) { protectTime = 0.15f; } - hcolor[3] = protectTime/2; + hcolor[3] = protectTime / 2; hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - if (!cg.renderingThirdPerson && protectTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && protectTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgProtectTime = 0; } } - if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) - { - CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime ); + if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) { + CG_DrawRocketLocking(cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime); } - if (BG_HasYsalamiri(cgs.gametype, &cg.snap->ps)) - { - if (!cgYsalTime) - { + if (BG_HasYsalamiri(cgs.gametype, &cg.snap->ps)) { + if (!cgYsalTime) { cgYsalTime = cg.time; } @@ -7852,111 +6544,95 @@ static void CG_Draw2DScreenTints( void ) ysalTime /= 9000; - if (ysalTime < 0) - { + if (ysalTime < 0) { ysalTime = 0; } - if (ysalTime > 0.15f) - { + if (ysalTime > 0.15f) { ysalTime = 0.15f; } - hcolor[3] = ysalTime/2; + hcolor[3] = ysalTime / 2; hcolor[0] = 0.7f; hcolor[1] = 0.7f; hcolor[2] = 0; - if (!cg.renderingThirdPerson) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + if (!cg.renderingThirdPerson) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } cgYsalFadeTime = 0; cgYsalFadeVal = 0; - } - else if (cgYsalTime) - { - if (!cgYsalFadeTime) - { + } else if (cgYsalTime) { + if (!cgYsalFadeTime) { cgYsalFadeTime = cg.time; cgYsalFadeVal = 0.15f; } ysalTime = cgYsalFadeVal; - cgYsalFadeVal -= (cg.time - cgYsalFadeTime)*0.000005f; + cgYsalFadeVal -= (cg.time - cgYsalFadeTime) * 0.000005f; - if (ysalTime < 0) - { + if (ysalTime < 0) { ysalTime = 0; } - if (ysalTime > 0.15f) - { + if (ysalTime > 0.15f) { ysalTime = 0.15f; } - hcolor[3] = ysalTime/2; + hcolor[3] = ysalTime / 2; hcolor[0] = 0.7f; hcolor[1] = 0.7f; hcolor[2] = 0; - if (!cg.renderingThirdPerson && ysalTime) - { - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else - { + if (!cg.renderingThirdPerson && ysalTime) { + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else { cgYsalTime = 0; } } } - if ( (cg.refdef.viewContents&CONTENTS_LAVA) ) - {//tint screen red + if ((cg.refdef.viewContents & CONTENTS_LAVA)) { // tint screen red float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.5 + (0.15f*sin( phase )); + hcolor[3] = 0.5 + (0.15f * sin(phase)); hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else if ( (cg.refdef.viewContents&CONTENTS_SLIME) ) - {//tint screen green + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else if ((cg.refdef.viewContents & CONTENTS_SLIME)) { // tint screen green float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.4 + (0.1f*sin( phase )); + hcolor[3] = 0.4 + (0.1f * sin(phase)); hcolor[0] = 0; hcolor[1] = 0.7f; hcolor[2] = 0; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); - } - else if ( (cg.refdef.viewContents&CONTENTS_WATER) ) - {//tint screen light blue -- FIXME: don't do this if CONTENTS_FOG? (in case someone *does* make a water shader with fog in it?) + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); + } else if ((cg.refdef.viewContents & CONTENTS_WATER)) { // tint screen light blue -- FIXME: don't do this if CONTENTS_FOG? (in case someone *does* make a + // water shader with fog in it?) float phase = cg.time / 1000.0f * WAVE_FREQUENCY * M_PI * 2; - hcolor[3] = 0.3f + (0.05f*sinf( phase )); + hcolor[3] = 0.3f + (0.05f * sinf(phase)); hcolor[0] = 0; hcolor[1] = 0.2f; hcolor[2] = 0.8f; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); } } -static void CG_Draw2D( void ) { - float inTime = cg.invenSelectTime+WEAPON_SELECT_TIME; - float wpTime = cg.weaponSelectTime+WEAPON_SELECT_TIME; - float fallTime; - float bestTime; - int drawSelect = 0; +static void CG_Draw2D(void) { + float inTime = cg.invenSelectTime + WEAPON_SELECT_TIME; + float wpTime = cg.weaponSelectTime + WEAPON_SELECT_TIME; + float fallTime; + float bestTime; + int drawSelect = 0; // if we are taking a levelshot for the menu, don't draw anything - if ( cg.levelShot ) { + if (cg.levelShot) { return; } - if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) - { + if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR) { cgRageTime = 0; cgRageFadeTime = 0; cgRageFadeVal = 0; @@ -7978,13 +6654,13 @@ static void CG_Draw2D( void ) { cgYsalFadeVal = 0; } - if ( !cg_draw2D.integer ) { + if (!cg_draw2D.integer) { gCGHasFallVector = qfalse; - VectorClear( gCGFallVector ); + VectorClear(gCGFallVector); return; } - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { + if (cg.snap->ps.pm_type == PM_INTERMISSION) { CG_DrawIntermission(); CG_ChatBox_DrawStrings(); return; @@ -7992,34 +6668,27 @@ static void CG_Draw2D( void ) { CG_Draw2DScreenTints(); - if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) - { - CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime ); + if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0) { + CG_DrawRocketLocking(cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime); } - if (cg.snap->ps.holocronBits) - { + if (cg.snap->ps.holocronBits) { CG_DrawHolocronIcons(); } - if (cg.snap->ps.fd.forcePowersActive || cg.snap->ps.fd.forceRageRecoveryTime > cg.time) - { + if (cg.snap->ps.fd.forcePowersActive || cg.snap->ps.fd.forceRageRecoveryTime > cg.time) { CG_DrawActivePowers(); } - if (cg.snap->ps.jetpackFuel < 100) - { //draw it as long as it isn't full - CG_DrawJetpackFuel(); + if (cg.snap->ps.jetpackFuel < 100) { // draw it as long as it isn't full + CG_DrawJetpackFuel(); } - if (cg.snap->ps.cloakFuel < 100) - { //draw it as long as it isn't full + if (cg.snap->ps.cloakFuel < 100) { // draw it as long as it isn't full CG_DrawCloakFuel(); } - if (cg.predictedPlayerState.emplacedIndex > 0) - { + if (cg.predictedPlayerState.emplacedIndex > 0) { centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex]; - if (eweb->currentState.weapon == WP_NONE) - { //using an e-web, draw its health + if (eweb->currentState.weapon == WP_NONE) { // using an e-web, draw its health CG_DrawEWebHealth(); } } @@ -8027,55 +6696,50 @@ static void CG_Draw2D( void ) { // Draw this before the text so that any text won't get clipped off CG_DrawZoomMask(); -/* - if (cg.cameraMode) { - return; - } -*/ - if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) { + /* + if (cg.cameraMode) { + return; + } + */ + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR) { CG_DrawSpectator(); CG_DrawCrosshair(NULL, 0); CG_DrawCrosshairNames(); CG_SaberClashFlare(); } else { // don't draw any status if dead or the scoreboard is being explicitly shown - if ( !cg.showScores && cg.snap->ps.stats[STAT_HEALTH] > 0 ) { + if (!cg.showScores && cg.snap->ps.stats[STAT_HEALTH] > 0) { - if ( /*cg_drawStatus.integer*/0 ) { - //Reenable if stats are drawn with menu system again + if (/*cg_drawStatus.integer*/ 0) { + // Reenable if stats are drawn with menu system again Menu_PaintAll(); CG_DrawTimedMenus(); } - //CG_DrawTemporaryStats(); + // CG_DrawTemporaryStats(); CG_DrawAmmoWarning(); CG_DrawCrosshairNames(); - if (cg_drawStatus.integer) - { + if (cg_drawStatus.integer) { CG_DrawIconBackground(); } - if (inTime > wpTime) - { + if (inTime > wpTime) { drawSelect = 1; bestTime = cg.invenSelectTime; - } - else //only draw the most recent since they're drawn in the same place + } else // only draw the most recent since they're drawn in the same place { drawSelect = 2; bestTime = cg.weaponSelectTime; } - if (cg.forceSelectTime > bestTime) - { + if (cg.forceSelectTime > bestTime) { drawSelect = 3; } - switch(drawSelect) - { + switch (drawSelect) { case 1: CG_DrawInvenSelect(); break; @@ -8089,42 +6753,36 @@ static void CG_Draw2D( void ) { break; } - if (cg_drawStatus.integer) - { - //Powerups now done with upperright stuff - //CG_DrawPowerupIcons(); + if (cg_drawStatus.integer) { + // Powerups now done with upperright stuff + // CG_DrawPowerupIcons(); CG_DrawFlagStatus(); } CG_SaberClashFlare(); - if (cg_drawStatus.integer) - { + if (cg_drawStatus.integer) { CG_DrawStats(); } CG_DrawPickupItem(); - //Do we want to use this system again at some point? - //CG_DrawReward(); + // Do we want to use this system again at some point? + // CG_DrawReward(); } - } - if (cg.snap->ps.fallingToDeath) - { - vec4_t hcolor; + if (cg.snap->ps.fallingToDeath) { + vec4_t hcolor; fallTime = (float)(cg.time - cg.snap->ps.fallingToDeath); - fallTime /= (FALL_FADE_TIME/2); + fallTime /= (FALL_FADE_TIME / 2); - if (fallTime < 0) - { + if (fallTime < 0) { fallTime = 0; } - if (fallTime > 1) - { + if (fallTime > 1) { fallTime = 1; } @@ -8133,18 +6791,14 @@ static void CG_Draw2D( void ) { hcolor[1] = 0; hcolor[2] = 0; - CG_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor ); + CG_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, hcolor); - if (!gCGHasFallVector) - { + if (!gCGHasFallVector) { VectorCopy(cg.snap->ps.origin, gCGFallVector); gCGHasFallVector = qtrue; } - } - else - { - if (gCGHasFallVector) - { + } else { + if (gCGHasFallVector) { gCGHasFallVector = qfalse; VectorClear(gCGFallVector); } @@ -8155,37 +6809,32 @@ static void CG_Draw2D( void ) { CG_DrawLagometer(); - if (!cl_paused.integer) { CG_DrawBracketedEntities(); CG_DrawUpperRight(); } - if ( !CG_DrawFollow() ) { + if (!CG_DrawFollow()) { CG_DrawWarmup(); } - if (cgSiegeRoundState) - { + if (cgSiegeRoundState) { char pStr[1024]; int rTime = 0; - //cgSiegeRoundBeganTime = 0; + // cgSiegeRoundBeganTime = 0; - switch (cgSiegeRoundState) - { + switch (cgSiegeRoundState) { case 1: CG_CenterPrint(CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS"), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); break; case 2: rTime = (SIEGE_ROUND_BEGIN_TIME - (cg.time - cgSiegeRoundTime)); - if (rTime < 0) - { + if (rTime < 0) { rTime = 0; } - if (rTime > SIEGE_ROUND_BEGIN_TIME) - { + if (rTime > SIEGE_ROUND_BEGIN_TIME) { rTime = SIEGE_ROUND_BEGIN_TIME; } @@ -8193,25 +6842,22 @@ static void CG_Draw2D( void ) { rTime += 1; - if (rTime < 1) - { + if (rTime < 1) { rTime = 1; } - if (rTime <= 3 && rTime != cgSiegeRoundCountTime) - { + if (rTime <= 3 && rTime != cgSiegeRoundCountTime) { cgSiegeRoundCountTime = rTime; - switch (rTime) - { + switch (rTime) { case 1: - trap->S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count1Sound, CHAN_ANNOUNCER); break; case 2: - trap->S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count2Sound, CHAN_ANNOUNCER); break; case 3: - trap->S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.count3Sound, CHAN_ANNOUNCER); break; default: break; @@ -8220,123 +6866,94 @@ static void CG_Draw2D( void ) { Q_strncpyz(pStr, va("%s %i...", CG_GetStringEdString("MP_INGAME", "ROUNDBEGINSIN"), rTime), sizeof(pStr)); CG_CenterPrint(pStr, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); - //same + // same break; default: break; } cgSiegeEntityRender = 0; - } - else if (cgSiegeRoundTime) - { + } else if (cgSiegeRoundTime) { CG_CenterPrint("", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); cgSiegeRoundTime = 0; - //cgSiegeRoundBeganTime = cg.time; + // cgSiegeRoundBeganTime = cg.time; cgSiegeEntityRender = 0; - } - else if (cgSiegeRoundBeganTime) - { //Draw how much time is left in the round based on local info. + } else if (cgSiegeRoundBeganTime) { // Draw how much time is left in the round based on local info. int timedTeam = TEAM_FREE; int timedValue = 0; - if (cgSiegeEntityRender) - { //render the objective item model since this client has it + if (cgSiegeEntityRender) { // render the objective item model since this client has it CG_DrawSiegeHUDItem(); } - if (team1Timed) - { - timedTeam = TEAM_RED; //team 1 - if (cg_beatingSiegeTime) - { + if (team1Timed) { + timedTeam = TEAM_RED; // team 1 + if (cg_beatingSiegeTime) { timedValue = cg_beatingSiegeTime; - } - else - { + } else { timedValue = team1Timed; } - } - else if (team2Timed) - { - timedTeam = TEAM_BLUE; //team 2 - if (cg_beatingSiegeTime) - { + } else if (team2Timed) { + timedTeam = TEAM_BLUE; // team 2 + if (cg_beatingSiegeTime) { timedValue = cg_beatingSiegeTime; - } - else - { + } else { timedValue = team2Timed; } } - if (timedTeam != TEAM_FREE) - { //one of the teams has a timer + if (timedTeam != TEAM_FREE) { // one of the teams has a timer int timeRemaining; qboolean isMyTeam = qfalse; - if (cgs.siegeTeamSwitch && !cg_beatingSiegeTime) - { //in switchy mode but not beating a time, so count up. - timeRemaining = (cg.time-cgSiegeRoundBeganTime); - if (timeRemaining < 0) - { + if (cgs.siegeTeamSwitch && !cg_beatingSiegeTime) { // in switchy mode but not beating a time, so count up. + timeRemaining = (cg.time - cgSiegeRoundBeganTime); + if (timeRemaining < 0) { timeRemaining = 0; } - } - else - { - timeRemaining = (((cgSiegeRoundBeganTime)+timedValue) - cg.time); + } else { + timeRemaining = (((cgSiegeRoundBeganTime) + timedValue) - cg.time); } - if (timeRemaining > timedValue) - { + if (timeRemaining > timedValue) { timeRemaining = timedValue; - } - else if (timeRemaining < 0) - { + } else if (timeRemaining < 0) { timeRemaining = 0; } - if (timeRemaining) - { + if (timeRemaining) { timeRemaining /= 1000; } - if (cg.predictedPlayerState.persistant[PERS_TEAM] == timedTeam) - { //the team that's timed is the one this client is on + if (cg.predictedPlayerState.persistant[PERS_TEAM] == timedTeam) { // the team that's timed is the one this client is on isMyTeam = qtrue; } CG_DrawSiegeTimer(timeRemaining, isMyTeam); } - } - else - { + } else { cgSiegeEntityRender = 0; } - if ( cg_siegeDeathTime ) - { - int timeRemaining = ( cg_siegeDeathTime - cg.time ); + if (cg_siegeDeathTime) { + int timeRemaining = (cg_siegeDeathTime - cg.time); - if ( timeRemaining < 0 ) - { + if (timeRemaining < 0) { timeRemaining = 0; cg_siegeDeathTime = 0; } - if ( timeRemaining ) - { + if (timeRemaining) { timeRemaining /= 1000; } - CG_DrawSiegeDeathTimer( timeRemaining ); + CG_DrawSiegeDeathTimer(timeRemaining); } // don't draw center string if scoreboard is up cg.scoreBoardShowing = CG_DrawScoreboard(); - if ( !cg.scoreBoardShowing) { + if (!cg.scoreBoardShowing) { CG_DrawCenterString(); } @@ -8344,14 +6961,14 @@ static void CG_Draw2D( void ) { CG_ChatBox_DrawStrings(); } -qboolean CG_CullPointAndRadius( const vec3_t pt, float radius); -void CG_DrawMiscStaticModels( void ) { +qboolean CG_CullPointAndRadius(const vec3_t pt, float radius); +void CG_DrawMiscStaticModels(void) { int i, j; refEntity_t ent; vec3_t cullorg; vec3_t diff; - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); ent.reType = RT_MODEL; ent.frame = 0; @@ -8360,41 +6977,40 @@ void CG_DrawMiscStaticModels( void ) { // static models don't project shadows ent.renderfx = RF_NOSHADOW; - for( i = 0; i < cgs.numMiscStaticModels; i++ ) { + for (i = 0; i < cgs.numMiscStaticModels; i++) { VectorCopy(cgs.miscStaticModels[i].org, cullorg); cullorg[2] += 1.0f; - if ( cgs.miscStaticModels[i].zoffset ) { + if (cgs.miscStaticModels[i].zoffset) { cullorg[2] += cgs.miscStaticModels[i].zoffset; } - if( cgs.miscStaticModels[i].radius ) { - if( CG_CullPointAndRadius( cullorg, cgs.miscStaticModels[i].radius ) ) { - continue; + if (cgs.miscStaticModels[i].radius) { + if (CG_CullPointAndRadius(cullorg, cgs.miscStaticModels[i].radius)) { + continue; } } - if( !trap->R_InPVS( cg.refdef.vieworg, cullorg, cg.refdef.areamask ) ) { + if (!trap->R_InPVS(cg.refdef.vieworg, cullorg, cg.refdef.areamask)) { continue; } - VectorCopy( cgs.miscStaticModels[i].org, ent.origin ); - VectorCopy( cgs.miscStaticModels[i].org, ent.oldorigin ); - VectorCopy( cgs.miscStaticModels[i].org, ent.lightingOrigin ); + VectorCopy(cgs.miscStaticModels[i].org, ent.origin); + VectorCopy(cgs.miscStaticModels[i].org, ent.oldorigin); + VectorCopy(cgs.miscStaticModels[i].org, ent.lightingOrigin); - for( j = 0; j < 3; j++ ) { - VectorCopy( cgs.miscStaticModels[i].axes[j], ent.axis[j] ); + for (j = 0; j < 3; j++) { + VectorCopy(cgs.miscStaticModels[i].axes[j], ent.axis[j]); } ent.hModel = cgs.miscStaticModels[i].model; VectorSubtract(ent.origin, cg.refdef.vieworg, diff); - if (VectorLength(diff)-(cgs.miscStaticModels[i].radius) <= cg.distanceCull) { - trap->R_AddRefEntityToScene( &ent ); + if (VectorLength(diff) - (cgs.miscStaticModels[i].radius) <= cg.distanceCull) { + trap->R_AddRefEntityToScene(&ent); } } } -static void CG_DrawTourneyScoreboard() { -} +static void CG_DrawTourneyScoreboard() {} /* ===================== @@ -8403,24 +7019,23 @@ CG_DrawActive Perform all drawing needed to completely fill the screen ===================== */ -void CG_DrawActive( stereoFrame_t stereoView ) { - float separation; - vec3_t baseOrg; +void CG_DrawActive(stereoFrame_t stereoView) { + float separation; + vec3_t baseOrg; // optionally draw the info screen instead - if ( !cg.snap ) { + if (!cg.snap) { CG_DrawInformation(); return; } // optionally draw the tournament scoreboard instead - if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR && - ( cg.snap->ps.pm_flags & PMF_SCOREBOARD ) ) { + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR && (cg.snap->ps.pm_flags & PMF_SCOREBOARD)) { CG_DrawTourneyScoreboard(); return; } - switch ( stereoView ) { + switch (stereoView) { case STEREO_CENTER: separation = 0; break; @@ -8432,20 +7047,19 @@ void CG_DrawActive( stereoFrame_t stereoView ) { break; default: separation = 0; - trap->Error( ERR_DROP, "CG_DrawActive: Undefined stereoView" ); + trap->Error(ERR_DROP, "CG_DrawActive: Undefined stereoView"); } - // clear around the rendered view if sized down CG_TileClear(); // offset vieworg appropriately if we're doing stereo separation - VectorCopy( cg.refdef.vieworg, baseOrg ); - if ( separation != 0 ) { - VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg ); + VectorCopy(cg.refdef.vieworg, baseOrg); + if (separation != 0) { + VectorMA(cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg); } - if ( cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE) ) + if (cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) cg.refdef.rdflags |= RDF_ForceSightOn; cg.refdef.rdflags |= RDF_DRAWSKYBOX; @@ -8453,16 +7067,13 @@ void CG_DrawActive( stereoFrame_t stereoView ) { CG_DrawMiscStaticModels(); // draw 3D view - trap->R_RenderScene( &cg.refdef ); + trap->R_RenderScene(&cg.refdef); // restore original viewpoint if running stereo - if ( separation != 0 ) { - VectorCopy( baseOrg, cg.refdef.vieworg ); + if (separation != 0) { + VectorCopy(baseOrg, cg.refdef.vieworg); } // draw status bar and other floating elements - CG_Draw2D(); + CG_Draw2D(); } - - - diff --git a/codemp/cgame/cg_drawtools.c b/codemp/cgame/cg_drawtools.c index 8e6b9a2b91..1ab7e57193 100644 --- a/codemp/cgame/cg_drawtools.c +++ b/codemp/cgame/cg_drawtools.c @@ -25,7 +25,6 @@ along with this program; if not, see . #include "cg_local.h" #include "qcommon/q_shared.h" - /* ================ CG_DrawRect @@ -33,36 +32,34 @@ CG_DrawRect Coordinates are 640*480 virtual values ================= */ -void CG_DrawRect( float x, float y, float width, float height, float size, const float *color ) { - trap->R_SetColor( color ); +void CG_DrawRect(float x, float y, float width, float height, float size, const float *color) { + trap->R_SetColor(color); CG_DrawTopBottom(x, y, width, height, size); CG_DrawSides(x, y, width, height, size); - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } - - /* ================= CG_GetColorForHealth ================= */ -void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) { - int count; - int max; +void CG_GetColorForHealth(int health, int armor, vec4_t hcolor) { + int count; + int max; // calculate the total points of damage that can // be sustained at the current health / armor level - if ( health <= 0 ) { - VectorClear( hcolor ); // black + if (health <= 0) { + VectorClear(hcolor); // black hcolor[3] = 1; return; } count = armor; - max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); - if ( max < count ) { + max = health * ARMOR_PROTECTION / (1.0 - ARMOR_PROTECTION); + if (max < count) { count = max; } health += count; @@ -70,20 +67,20 @@ void CG_GetColorForHealth( int health, int armor, vec4_t hcolor ) { // set the color based on health hcolor[0] = 1.0; hcolor[3] = 1.0; - if ( health >= 100 ) { + if (health >= 100) { hcolor[2] = 1.0; - } else if ( health < 66 ) { + } else if (health < 66) { hcolor[2] = 0; } else { - hcolor[2] = ( health - 66 ) / 33.0; + hcolor[2] = (health - 66) / 33.0; } - if ( health > 60 ) { + if (health > 60) { hcolor[1] = 1.0; - } else if ( health < 30 ) { + } else if (health < 30) { hcolor[1] = 0; } else { - hcolor[1] = ( health - 30 ) / 30.0; + hcolor[1] = (health - 30) / 30.0; } } @@ -96,14 +93,14 @@ Coords are virtual 640x480 */ void CG_DrawSides(float x, float y, float w, float h, float size) { size *= cgs.screenXScale; - trap->R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); - trap->R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader ); + trap->R_DrawStretchPic(x, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader); + trap->R_DrawStretchPic(x + w - size, y, size, h, 0, 0, 0, 0, cgs.media.whiteShader); } void CG_DrawTopBottom(float x, float y, float w, float h, float size) { size *= cgs.screenYScale; - trap->R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); - trap->R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader ); + trap->R_DrawStretchPic(x, y, w, size, 0, 0, 0, 0, cgs.media.whiteShader); + trap->R_DrawStretchPic(x, y + h - size, w, size, 0, 0, 0, 0, cgs.media.whiteShader); } /* @@ -112,10 +109,10 @@ CGC_FillRect2 real coords ------------------------- */ -void CG_FillRect2( float x, float y, float width, float height, const float *color ) { - trap->R_SetColor( color ); - trap->R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); - trap->R_SetColor( NULL ); +void CG_FillRect2(float x, float y, float width, float height, const float *color) { + trap->R_SetColor(color); + trap->R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); + trap->R_SetColor(NULL); } /* @@ -125,13 +122,12 @@ CG_FillRect Coordinates are 640*480 virtual values ================= */ -void CG_FillRect( float x, float y, float width, float height, const float *color ) { - trap->R_SetColor( color ); - trap->R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); - trap->R_SetColor( NULL ); +void CG_FillRect(float x, float y, float width, float height, const float *color) { + trap->R_SetColor(color); + trap->R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cgs.media.whiteShader); + trap->R_SetColor(NULL); } - /* ================ CG_DrawPic @@ -140,9 +136,7 @@ Coordinates are 640*480 virtual values A width of 0 will draw with the original image width ================= */ -void CG_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { - trap->R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); -} +void CG_DrawPic(float x, float y, float width, float height, qhandle_t hShader) { trap->R_DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } /* ================ @@ -153,8 +147,8 @@ A width of 0 will draw with the original image width rotates around the upper right corner of the passed in point ================= */ -void CG_DrawRotatePic( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - trap->R_DrawRotatePic( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic(float x, float y, float width, float height, float angle, qhandle_t hShader) { + trap->R_DrawRotatePic(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -166,8 +160,8 @@ A width of 0 will draw with the original image width Actually rotates around the center point of the passed in coordinates ================= */ -void CG_DrawRotatePic2( float x, float y, float width, float height,float angle, qhandle_t hShader ) { - trap->R_DrawRotatePic2( x, y, width, height, 0, 0, 1, 1, angle, hShader ); +void CG_DrawRotatePic2(float x, float y, float width, float height, float angle, qhandle_t hShader) { + trap->R_DrawRotatePic2(x, y, width, height, 0, 0, 1, 1, angle, hShader); } /* @@ -177,16 +171,16 @@ CG_DrawChar Coordinates and size in 640*480 virtual screen size =============== */ -void CG_DrawChar( int x, int y, int width, int height, int ch ) { +void CG_DrawChar(int x, int y, int width, int height, int ch) { int row, col; float frow, fcol; float size; - float ax, ay, aw, ah; + float ax, ay, aw, ah; float size2; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } @@ -195,16 +189,15 @@ void CG_DrawChar( int x, int y, int width, int height, int ch ) { aw = width; ah = height; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - trap->R_DrawStretchPic( ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader ); - + trap->R_DrawStretchPic(ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cgs.media.charsetShader); } /* @@ -217,43 +210,40 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -#include "ui/menudef.h" // for "ITEM_TEXTSTYLE_SHADOWED" -void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight, int maxChars ) -{ - if (trap->R_Language_IsAsian()) - { +#include "ui/menudef.h" // for "ITEM_TEXTSTYLE_SHADOWED" +void CG_DrawStringExt(int x, int y, const char *string, const float *setColor, qboolean forceColor, qboolean shadow, int charWidth, int charHeight, + int maxChars) { + if (trap->R_Language_IsAsian()) { // hack-a-doodle-do (post-release quick fix code)... // vec4_t color; - memcpy(color,setColor, sizeof(color)); // de-const it - CG_Text_Paint(x, y, 1.0f, // float scale, - color, // vec4_t color, - string, // const char *text, - 0.0f, // float adjust, - 0, // int limit, - shadow ? ITEM_TEXTSTYLE_SHADOWED : 0, // int style, - FONT_MEDIUM // iMenuFont - ) ; - } - else - { - vec4_t color; - const char *s; - int xx; + memcpy(color, setColor, sizeof(color)); // de-const it + CG_Text_Paint(x, y, 1.0f, // float scale, + color, // vec4_t color, + string, // const char *text, + 0.0f, // float adjust, + 0, // int limit, + shadow ? ITEM_TEXTSTYLE_SHADOWED : 0, // int style, + FONT_MEDIUM // iMenuFont + ); + } else { + vec4_t color; + const char *s; + int xx; // draw the drop shadow if (shadow) { color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; - trap->R_SetColor( color ); + trap->R_SetColor(color); s = string; xx = x; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; continue; } - CG_DrawChar( xx + 2, y + 2, charWidth, charHeight, *s ); + CG_DrawChar(xx + 2, y + 2, charWidth, charHeight, *s); xx += charWidth; s++; } @@ -262,47 +252,45 @@ void CG_DrawStringExt( int x, int y, const char *string, const float *setColor, // draw the colored text s = string; xx = x; - trap->R_SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + trap->R_SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - trap->R_SetColor( color ); + trap->R_SetColor(color); } s += 2; continue; } - CG_DrawChar( xx, y, charWidth, charHeight, *s ); + CG_DrawChar(xx, y, charWidth, charHeight, *s); xx += charWidth; s++; } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } } -void CG_DrawBigString( int x, int y, const char *s, float alpha ) { - float color[4]; +void CG_DrawBigString(int x, int y, const char *s, float alpha) { + float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; - CG_DrawStringExt( x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); + CG_DrawStringExt(x, y, s, color, qfalse, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0); } -void CG_DrawBigStringColor( int x, int y, const char *s, vec4_t color ) { - CG_DrawStringExt( x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0 ); -} +void CG_DrawBigStringColor(int x, int y, const char *s, vec4_t color) { CG_DrawStringExt(x, y, s, color, qtrue, qtrue, BIGCHAR_WIDTH, BIGCHAR_HEIGHT, 0); } -void CG_DrawSmallString( int x, int y, const char *s, float alpha ) { - float color[4]; +void CG_DrawSmallString(int x, int y, const char *s, float alpha) { + float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; - CG_DrawStringExt( x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); + CG_DrawStringExt(x, y, s, color, qfalse, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0); } -void CG_DrawSmallStringColor( int x, int y, const char *s, vec4_t color ) { - CG_DrawStringExt( x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 ); +void CG_DrawSmallStringColor(int x, int y, const char *s, vec4_t color) { + CG_DrawStringExt(x, y, s, color, qtrue, qfalse, SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0); } /* @@ -312,12 +300,12 @@ CG_DrawStrlen Returns character count, skiping color escape codes ================= */ -int CG_DrawStrlen( const char *str ) { +int CG_DrawStrlen(const char *str) { const char *s = str; int count = 0; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; } else { count++; @@ -336,18 +324,16 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -static void CG_TileClearBox( int x, int y, int w, int h, qhandle_t hShader ) { - float s1, t1, s2, t2; - - s1 = x/64.0; - t1 = y/64.0; - s2 = (x+w)/64.0; - t2 = (y+h)/64.0; - trap->R_DrawStretchPic( x, y, w, h, s1, t1, s2, t2, hShader ); +static void CG_TileClearBox(int x, int y, int w, int h, qhandle_t hShader) { + float s1, t1, s2, t2; + + s1 = x / 64.0; + t1 = y / 64.0; + s2 = (x + w) / 64.0; + t2 = (y + h) / 64.0; + trap->R_DrawStretchPic(x, y, w, h, s1, t1, s2, t2, hShader); } - - /* ============== CG_TileClear @@ -355,65 +341,62 @@ CG_TileClear Clear around a sized down screen ============== */ -void CG_TileClear( void ) { - int top, bottom, left, right; - int w, h; +void CG_TileClear(void) { + int top, bottom, left, right; + int w, h; w = cgs.glconfig.vidWidth; h = cgs.glconfig.vidHeight; - if ( cg.refdef.x == 0 && cg.refdef.y == 0 && - cg.refdef.width == w && cg.refdef.height == h ) { - return; // full screen rendering + if (cg.refdef.x == 0 && cg.refdef.y == 0 && cg.refdef.width == w && cg.refdef.height == h) { + return; // full screen rendering } top = cg.refdef.y; - bottom = top + cg.refdef.height-1; + bottom = top + cg.refdef.height - 1; left = cg.refdef.x; - right = left + cg.refdef.width-1; + right = left + cg.refdef.width - 1; // clear above view screen - CG_TileClearBox( 0, 0, w, top, cgs.media.backTileShader ); + CG_TileClearBox(0, 0, w, top, cgs.media.backTileShader); // clear below view screen - CG_TileClearBox( 0, bottom, w, h - bottom, cgs.media.backTileShader ); + CG_TileClearBox(0, bottom, w, h - bottom, cgs.media.backTileShader); // clear left of view screen - CG_TileClearBox( 0, top, left, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(0, top, left, bottom - top + 1, cgs.media.backTileShader); // clear right of view screen - CG_TileClearBox( right, top, w - right, bottom - top + 1, cgs.media.backTileShader ); + CG_TileClearBox(right, top, w - right, bottom - top + 1, cgs.media.backTileShader); } - - /* ================ CG_FadeColor ================ */ -float *CG_FadeColor( int startMsec, int totalMsec ) { - static vec4_t color; - int t; +float *CG_FadeColor(int startMsec, int totalMsec) { + static vec4_t color; + int t; - if ( startMsec == 0 ) { + if (startMsec == 0) { return NULL; } t = cg.time - startMsec; - if ( t >= totalMsec ) { + if (t >= totalMsec) { return NULL; } // this color shouldn't be visible yet - if (t < 0){ + if (t < 0) { return NULL; } // fade out - if ( totalMsec - t < FADE_TIME ) { - color[3] = ( totalMsec - t ) * 1.0/FADE_TIME; + if (totalMsec - t < FADE_TIME) { + color[3] = (totalMsec - t) * 1.0 / FADE_TIME; } else { color[3] = 1.0; } @@ -422,40 +405,28 @@ float *CG_FadeColor( int startMsec, int totalMsec ) { return color; } - /* ================= CG_ColorForHealth ================= */ -void CG_ColorForGivenHealth( vec4_t hcolor, int health ) -{ +void CG_ColorForGivenHealth(vec4_t hcolor, int health) { // set the color based on health hcolor[0] = 1.0; - if ( health >= 100 ) - { + if (health >= 100) { hcolor[2] = 1.0; - } - else if ( health < 66 ) - { + } else if (health < 66) { hcolor[2] = 0; - } - else - { - hcolor[2] = ( health - 66 ) / 33.0; + } else { + hcolor[2] = (health - 66) / 33.0; } - if ( health > 60 ) - { + if (health > 60) { hcolor[1] = 1.0; - } - else if ( health < 30 ) - { + } else if (health < 30) { hcolor[1] = 0; - } - else - { - hcolor[1] = ( health - 30 ) / 30.0; + } else { + hcolor[1] = (health - 30) / 30.0; } } @@ -464,33 +435,30 @@ void CG_ColorForGivenHealth( vec4_t hcolor, int health ) CG_ColorForHealth ================= */ -void CG_ColorForHealth( vec4_t hcolor ) -{ - int health; - int count; - int max; +void CG_ColorForHealth(vec4_t hcolor) { + int health; + int count; + int max; // calculate the total points of damage that can // be sustained at the current health / armor level health = cg.snap->ps.stats[STAT_HEALTH]; - if ( health <= 0 ) - { - VectorClear( hcolor ); // black + if (health <= 0) { + VectorClear(hcolor); // black hcolor[3] = 1; return; } count = cg.snap->ps.stats[STAT_ARMOR]; - max = health * ARMOR_PROTECTION / ( 1.0 - ARMOR_PROTECTION ); - if ( max < count ) - { + max = health * ARMOR_PROTECTION / (1.0 - ARMOR_PROTECTION); + if (max < count) { count = max; } health += count; hcolor[3] = 1.0; - CG_ColorForGivenHealth( hcolor, health ); + CG_ColorForGivenHealth(hcolor, health); } /* @@ -501,13 +469,12 @@ Take x,y positions as if 640 x 480 and scales them to the proper resolution ============== */ -void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charHeight,int style,qboolean zeroFill) -{ - char num[16], *ptr; - int l; - int frame; - int xWidth; - int i = 0; +void CG_DrawNumField(int x, int y, int width, int value, int charWidth, int charHeight, int style, qboolean zeroFill) { + char num[16], *ptr; + int l; + int frame; + int xWidth; + int i = 0; if (width < 1) { return; @@ -518,7 +485,7 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH width = 5; } - switch ( width ) { + switch (width) { case 1: value = value > 9 ? 9 : value; value = value < 0 ? 0 : value; @@ -537,71 +504,63 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH break; } - Com_sprintf (num, sizeof(num), "%i", value); + Com_sprintf(num, sizeof(num), "%i", value); l = strlen(num); if (l > width) l = width; // FIXME: Might need to do something different for the chunky font?? - switch(style) - { + switch (style) { case NUM_FONT_SMALL: xWidth = charWidth; break; case NUM_FONT_CHUNKY: - xWidth = (charWidth/1.2f) + 2; + xWidth = (charWidth / 1.2f) + 2; break; default: case NUM_FONT_BIG: - xWidth = (charWidth/2) + 7;//(charWidth/6); + xWidth = (charWidth / 2) + 7; //(charWidth/6); break; } - if ( zeroFill ) - { - for (i = 0; i < (width - l); i++ ) - { - switch(style) - { + if (zeroFill) { + for (i = 0; i < (width - l); i++) { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[0]); break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[0]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[0] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[0]); break; } x += 2 + (xWidth); } - } - else - { - x += 2 + (xWidth)*(width - l); + } else { + x += 2 + (xWidth) * (width - l); } ptr = num; - while (*ptr && l) - { + while (*ptr && l) { if (*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - switch(style) - { + switch (style) { case NUM_FONT_SMALL: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.smallnumberShaders[frame] ); - x++; // For a one line gap + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.smallnumberShaders[frame]); + x++; // For a one line gap break; case NUM_FONT_CHUNKY: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.chunkyNumberShaders[frame]); break; default: case NUM_FONT_BIG: - CG_DrawPic( x,y, charWidth, charHeight, cgs.media.numberShaders[frame] ); + CG_DrawPic(x, y, charWidth, charHeight, cgs.media.numberShaders[frame]); break; } @@ -609,89 +568,64 @@ void CG_DrawNumField (int x, int y, int width, int value,int charWidth,int charH ptr++; l--; } - } -#include "ui/ui_shared.h" // for some text style junk -void CG_DrawProportionalString( int x, int y, const char* str, int style, vec4_t color ) -{ +#include "ui/ui_shared.h" // for some text style junk +void CG_DrawProportionalString(int x, int y, const char *str, int style, vec4_t color) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; int iMenuFont = (style & UI_SMALLFONT) ? FONT_SMALL : FONT_MEDIUM; - switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) - { - default: - case UI_LEFT: - { - // nada... - } - break; + switch (style & (UI_LEFT | UI_CENTER | UI_RIGHT)) { + default: + case UI_LEFT: { + // nada... + } break; - case UI_CENTER: - { - x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; - } - break; + case UI_CENTER: { + x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; + } break; - case UI_RIGHT: - { - x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; - } - break; + case UI_RIGHT: { + x -= CG_Text_Width(str, 1.0, iMenuFont) / 2; + } break; } - if (style & UI_DROPSHADOW) - { + if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; - } - else - if ( style & (UI_BLINK|UI_PULSE) ) - { + } else if (style & (UI_BLINK | UI_PULSE)) { iStyle = ITEM_TEXTSTYLE_BLINK; } CG_Text_Paint(x, y, 1.0, color, str, 0, 0, iStyle, iMenuFont); } -void CG_DrawScaledProportionalString( int x, int y, const char* str, int style, vec4_t color, float scale) -{ +void CG_DrawScaledProportionalString(int x, int y, const char *str, int style, vec4_t color, float scale) { // having all these different style defines (1 for UI, one for CG, and now one for the re->font stuff) // is dumb, but for now... // int iStyle = 0; - switch (style & (UI_LEFT|UI_CENTER|UI_RIGHT)) - { - default: - case UI_LEFT: - { - // nada... - } - break; + switch (style & (UI_LEFT | UI_CENTER | UI_RIGHT)) { + default: + case UI_LEFT: { + // nada... + } break; - case UI_CENTER: - { - x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; - } - break; + case UI_CENTER: { + x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; + } break; - case UI_RIGHT: - { - x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; - } - break; + case UI_RIGHT: { + x -= CG_Text_Width(str, scale, FONT_MEDIUM) / 2; + } break; } - if (style & UI_DROPSHADOW) - { + if (style & UI_DROPSHADOW) { iStyle = ITEM_TEXTSTYLE_SHADOWED; - } - else - if ( style & (UI_BLINK|UI_PULSE) ) - { + } else if (style & (UI_BLINK | UI_PULSE)) { iStyle = ITEM_TEXTSTYLE_BLINK; } diff --git a/codemp/cgame/cg_effects.c b/codemp/cgame/cg_effects.c index 3a1cee61b8..682ae4ed94 100644 --- a/codemp/cgame/cg_effects.c +++ b/codemp/cgame/cg_effects.c @@ -33,36 +33,36 @@ CG_BubbleTrail Bullets shot underwater ================== */ -void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing ) { - vec3_t move; - vec3_t vec; - float len; - int i; +void CG_BubbleTrail(vec3_t start, vec3_t end, float spacing) { + vec3_t move; + vec3_t vec; + float len; + int i; - if ( cg_noProjectileTrail.integer ) { + if (cg_noProjectileTrail.integer) { return; } - VectorCopy (start, move); - VectorSubtract (end, start, vec); - len = VectorNormalize (vec); + VectorCopy(start, move); + VectorSubtract(end, start, vec); + len = VectorNormalize(vec); // advance a random amount first i = rand() % (int)spacing; - VectorMA( move, i, vec, move ); + VectorMA(move, i, vec, move); - VectorScale (vec, spacing, vec); + VectorScale(vec, spacing, vec); - for ( ; i < len; i += spacing ) { - localEntity_t *le; - refEntity_t *re; + for (; i < len; i += spacing) { + localEntity_t *le; + refEntity_t *re; le = CG_AllocLocalEntity(); le->leFlags = LEF_PUFF_DONT_SCALE; le->leType = LE_MOVE_SCALE_FADE; le->startTime = cg.time; le->endTime = cg.time + 1000 + Q_flrand(-250.0f, 250.0f); - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + le->lifeRate = 1.0 / (le->endTime - le->startTime); re = &le->refEntity; re->shaderTime = cg.time / 1000.0f; @@ -70,7 +70,7 @@ void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing ) { re->reType = RT_SPRITE; re->rotation = 0; re->radius = 3; - re->customShader = 0;//cgs.media.waterBubbleShader; + re->customShader = 0; // cgs.media.waterBubbleShader; re->shaderRGBA[0] = 0xff; re->shaderRGBA[1] = 0xff; re->shaderRGBA[2] = 0xff; @@ -80,12 +80,12 @@ void CG_BubbleTrail( vec3_t start, vec3_t end, float spacing ) { le->pos.trType = TR_LINEAR; le->pos.trTime = cg.time; - VectorCopy( move, le->pos.trBase ); + VectorCopy(move, le->pos.trBase); le->pos.trDelta[0] = Q_flrand(-5.0f, 5.0f); le->pos.trDelta[1] = Q_flrand(-5.0f, 5.0f); le->pos.trDelta[2] = Q_flrand(-5.0f, 5.0f) + 6; - VectorAdd (move, vec, move); + VectorAdd(move, vec, move); } } @@ -96,25 +96,19 @@ CG_SmokePuff Adds a smoke puff or blood trail localEntity. ===================== */ -localEntity_t *CG_SmokePuff( const vec3_t p, const vec3_t vel, - float radius, - float r, float g, float b, float a, - float duration, - int startTime, - int fadeInTime, - int leFlags, - qhandle_t hShader ) { - static int seed = 0x92; - localEntity_t *le; - refEntity_t *re; -// int fadeInTime = startTime + duration / 2; +localEntity_t *CG_SmokePuff(const vec3_t p, const vec3_t vel, float radius, float r, float g, float b, float a, float duration, int startTime, int fadeInTime, + int leFlags, qhandle_t hShader) { + static int seed = 0x92; + localEntity_t *le; + refEntity_t *re; + // int fadeInTime = startTime + duration / 2; le = CG_AllocLocalEntity(); le->leFlags = leFlags; le->radius = radius; re = &le->refEntity; - re->rotation = Q_random( &seed ) * 360; + re->rotation = Q_random(&seed) * 360; re->radius = radius; re->shaderTime = startTime / 1000.0f; @@ -122,24 +116,22 @@ localEntity_t *CG_SmokePuff( const vec3_t p, const vec3_t vel, le->startTime = startTime; le->fadeInTime = fadeInTime; le->endTime = startTime + duration; - if ( fadeInTime > startTime ) { - le->lifeRate = 1.0 / ( le->endTime - le->fadeInTime ); - } - else { - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + if (fadeInTime > startTime) { + le->lifeRate = 1.0 / (le->endTime - le->fadeInTime); + } else { + le->lifeRate = 1.0 / (le->endTime - le->startTime); } le->color[0] = r; le->color[1] = g; le->color[2] = b; le->color[3] = a; - le->pos.trType = TR_LINEAR; le->pos.trTime = startTime; - VectorCopy( vel, le->pos.trDelta ); - VectorCopy( p, le->pos.trBase ); + VectorCopy(vel, le->pos.trDelta); + VectorCopy(p, le->pos.trBase); - VectorCopy( p, re->origin ); + VectorCopy(p, re->origin); re->customShader = hShader; re->shaderRGBA[0] = le->color[0] * 0xff; @@ -153,75 +145,70 @@ localEntity_t *CG_SmokePuff( const vec3_t p, const vec3_t vel, return le; } -int CGDEBUG_SaberColor( int saberColor ) -{ - switch( (int)(saberColor) ) - { - case SABER_RED: - return 0x000000ff; - break; - case SABER_ORANGE: - return 0x000088ff; - break; - case SABER_YELLOW: - return 0x0000ffff; - break; - case SABER_GREEN: - return 0x0000ff00; - break; - case SABER_BLUE: - return 0x00ff0000; - break; - case SABER_PURPLE: - return 0x00ff00ff; - break; - default: - return saberColor; - break; +int CGDEBUG_SaberColor(int saberColor) { + switch ((int)(saberColor)) { + case SABER_RED: + return 0x000000ff; + break; + case SABER_ORANGE: + return 0x000088ff; + break; + case SABER_YELLOW: + return 0x0000ffff; + break; + case SABER_GREEN: + return 0x0000ff00; + break; + case SABER_BLUE: + return 0x00ff0000; + break; + case SABER_PURPLE: + return 0x00ff00ff; + break; + default: + return saberColor; + break; } } -void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int radius) { - localEntity_t *le; - refEntity_t *re; +void CG_TestLine(vec3_t start, vec3_t end, int time, unsigned int color, int radius) { + localEntity_t *le; + refEntity_t *re; le = CG_AllocLocalEntity(); le->leType = LE_LINE; le->startTime = cg.time; le->endTime = cg.time + time; - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + le->lifeRate = 1.0 / (le->endTime - le->startTime); re = &le->refEntity; - VectorCopy( start, re->origin ); - VectorCopy( end, re->oldorigin); + VectorCopy(start, re->origin); + VectorCopy(end, re->oldorigin); re->shaderTime = cg.time / 1000.0f; re->reType = RT_LINE; - re->radius = 0.5*radius; - re->customShader = cgs.media.whiteShader; //trap->R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); + re->radius = 0.5 * radius; + re->customShader = cgs.media.whiteShader; // trap->R_RegisterShaderNoMip("textures/colombia/canvas_doublesided"); re->shaderTexCoord[0] = re->shaderTexCoord[1] = 1.0f; - if (color==0) - { + if (color == 0) { re->shaderRGBA[0] = re->shaderRGBA[1] = re->shaderRGBA[2] = re->shaderRGBA[3] = 0xff; - } - else - { - color = CGDEBUG_SaberColor( color ); + } else { + color = CGDEBUG_SaberColor(color); re->shaderRGBA[0] = color & 0xff; color >>= 8; re->shaderRGBA[1] = color & 0xff; color >>= 8; re->shaderRGBA[2] = color & 0xff; -// color >>= 8; -// re->shaderRGBA[3] = color & 0xff; + // color >>= 8; + // re->shaderRGBA[3] = color & 0xff; re->shaderRGBA[3] = 0xff; } le->color[3] = 1.0; - //re->renderfx |= RF_DEPTHHACK; + // re->renderfx |= RF_DEPTHHACK; } //---------------------------- @@ -233,44 +220,41 @@ void CG_TestLine( vec3_t start, vec3_t end, int time, unsigned int color, int ra // Since we have shared verts when we tesselate the glass sheet, it helps to have a // random offset table set up up front. -static float offX[20][20], - offZ[20][20]; +static float offX[20][20], offZ[20][20]; -#define FX_ALPHA_NONLINEAR 0x00000004 -#define FX_APPLY_PHYSICS 0x02000000 -#define FX_USE_ALPHA 0x08000000 +#define FX_ALPHA_NONLINEAR 0x00000004 +#define FX_APPLY_PHYSICS 0x02000000 +#define FX_USE_ALPHA 0x08000000 -static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], qboolean stick, int time, vec3_t dmgDir ) -{ - float bounce; - vec3_t rotDelta; - vec3_t vel, accel; - vec3_t rgb1; +static void CG_DoGlassQuad(vec3_t p[4], vec2_t uv[4], qboolean stick, int time, vec3_t dmgDir) { + float bounce; + vec3_t rotDelta; + vec3_t vel, accel; + vec3_t rgb1; addpolyArgStruct_t apArgs; - int i, i_2; + int i, i_2; - VectorSet( vel, Q_flrand(-12.0f, 12.0f), Q_flrand(-12.0f, 12.0f), -1 ); + VectorSet(vel, Q_flrand(-12.0f, 12.0f), Q_flrand(-12.0f, 12.0f), -1); - if ( !stick ) - { + if (!stick) { // We aren't a motion delayed chunk, so let us move quickly - VectorMA( vel, 0.3f, dmgDir, vel ); + VectorMA(vel, 0.3f, dmgDir, vel); } // Set up acceleration due to gravity, 800 is standard QuakeIII gravity, so let's use something close - VectorSet( accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f ) ); + VectorSet(accel, 0.0f, 0.0f, -(600.0f + Q_flrand(0.0f, 1.0f) * 100.0f)); // We are using an additive shader, so let's set the RGB low so we look more like transparent glass -// VectorSet( rgb1, 0.1f, 0.1f, 0.1f ); - VectorSet( rgb1, 1.0f, 1.0f, 1.0f ); + // VectorSet( rgb1, 0.1f, 0.1f, 0.1f ); + VectorSet(rgb1, 1.0f, 1.0f, 1.0f); // Being glass, we don't want to bounce much bounce = Q_flrand(0.0f, 1.0f) * 0.2f + 0.15f; // Set up our random rotate, we only do PITCH and YAW, not ROLL. This is something like degrees per second - VectorSet( rotDelta, Q_flrand(-40.0f, 40.0f), Q_flrand(-40.0f, 40.0f), 0.0f ); + VectorSet(rotDelta, Q_flrand(-40.0f, 40.0f), Q_flrand(-40.0f, 40.0f), 0.0f); - //In an ideal world, this might actually work. + // In an ideal world, this might actually work. /* CPoly *pol = FX_AddPoly(p, uv, 4, // verts, ST, vertCount vel, accel, // motion @@ -288,15 +272,13 @@ static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], qboolean stick, int time, } */ - //rww - this is dirty. + // rww - this is dirty. i = 0; i_2 = 0; - while (i < 4) - { - while (i_2 < 3) - { + while (i < 4) { + while (i_2 < 3) { apArgs.p[i][i_2] = p[i][i_2]; i_2++; @@ -309,10 +291,8 @@ static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], qboolean stick, int time, i = 0; i_2 = 0; - while (i < 4) - { - while (i_2 < 2) - { + while (i < 4) { + while (i_2 < 2) { apArgs.ev[i][i_2] = uv[i][i_2]; i_2++; @@ -346,127 +326,115 @@ static void CG_DoGlassQuad( vec3_t p[4], vec2_t uv[4], qboolean stick, int time, trap->FX_AddPoly(&apArgs); } -static void CG_CalcBiLerp( vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4] ) -{ - vec3_t temp; +static void CG_CalcBiLerp(vec3_t verts[4], vec3_t subVerts[4], vec2_t uv[4]) { + vec3_t temp; // Nasty crap - VectorScale( verts[0], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[1], subVerts[0] ); - VectorScale( subVerts[0], 1.0f - uv[0][1], temp ); - VectorScale( verts[3], 1.0f - uv[0][0], subVerts[0] ); - VectorMA( subVerts[0], uv[0][0], verts[2], subVerts[0] ); - VectorMA( temp, uv[0][1], subVerts[0], subVerts[0] ); - - VectorScale( verts[0], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[1], subVerts[1] ); - VectorScale( subVerts[1], 1.0f - uv[1][1], temp ); - VectorScale( verts[3], 1.0f - uv[1][0], subVerts[1] ); - VectorMA( subVerts[1], uv[1][0], verts[2], subVerts[1] ); - VectorMA( temp, uv[1][1], subVerts[1], subVerts[1] ); - - VectorScale( verts[0], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[1], subVerts[2] ); - VectorScale( subVerts[2], 1.0f - uv[2][1], temp ); - VectorScale( verts[3], 1.0f - uv[2][0], subVerts[2] ); - VectorMA( subVerts[2], uv[2][0], verts[2], subVerts[2] ); - VectorMA( temp, uv[2][1], subVerts[2], subVerts[2] ); - - VectorScale( verts[0], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[1], subVerts[3] ); - VectorScale( subVerts[3], 1.0f - uv[3][1], temp ); - VectorScale( verts[3], 1.0f - uv[3][0], subVerts[3] ); - VectorMA( subVerts[3], uv[3][0], verts[2], subVerts[3] ); - VectorMA( temp, uv[3][1], subVerts[3], subVerts[3] ); + VectorScale(verts[0], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[1], subVerts[0]); + VectorScale(subVerts[0], 1.0f - uv[0][1], temp); + VectorScale(verts[3], 1.0f - uv[0][0], subVerts[0]); + VectorMA(subVerts[0], uv[0][0], verts[2], subVerts[0]); + VectorMA(temp, uv[0][1], subVerts[0], subVerts[0]); + + VectorScale(verts[0], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[1], subVerts[1]); + VectorScale(subVerts[1], 1.0f - uv[1][1], temp); + VectorScale(verts[3], 1.0f - uv[1][0], subVerts[1]); + VectorMA(subVerts[1], uv[1][0], verts[2], subVerts[1]); + VectorMA(temp, uv[1][1], subVerts[1], subVerts[1]); + + VectorScale(verts[0], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[1], subVerts[2]); + VectorScale(subVerts[2], 1.0f - uv[2][1], temp); + VectorScale(verts[3], 1.0f - uv[2][0], subVerts[2]); + VectorMA(subVerts[2], uv[2][0], verts[2], subVerts[2]); + VectorMA(temp, uv[2][1], subVerts[2], subVerts[2]); + + VectorScale(verts[0], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[1], subVerts[3]); + VectorScale(subVerts[3], 1.0f - uv[3][1], temp); + VectorScale(verts[3], 1.0f - uv[3][0], subVerts[3]); + VectorMA(subVerts[3], uv[3][0], verts[2], subVerts[3]); + VectorMA(temp, uv[3][1], subVerts[3], subVerts[3]); } // bilinear -//f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. - - -static void CG_CalcHeightWidth( vec3_t verts[4], float *height, float *width ) -{ - vec3_t dir1, dir2, cross; - - VectorSubtract( verts[3], verts[0], dir1 ); // v - VectorSubtract( verts[1], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *width += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v +// f(p',q') = (1 - y) × {[(1 - x) × f(p,q)] + [x × f(p,q+1)]} + y × {[(1 - x) × f(p+1,q)] + [x × f(p+1,q+1)]}. + +static void CG_CalcHeightWidth(vec3_t verts[4], float *height, float *width) { + vec3_t dir1, dir2, cross; + + VectorSubtract(verts[3], verts[0], dir1); // v + VectorSubtract(verts[1], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *width += VectorNormalize(cross) / VectorNormalize(dir1); // v *width *= 0.5f; - VectorSubtract( verts[1], verts[0], dir1 ); // v - VectorSubtract( verts[2], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height = VectorNormalize( cross ) / VectorNormalize( dir1 ); // v - VectorSubtract( verts[3], verts[0], dir2 ); // p-a - CrossProduct( dir1, dir2, cross ); - *height += VectorNormalize( cross ) / VectorNormalize( dir1 ); // v + VectorSubtract(verts[1], verts[0], dir1); // v + VectorSubtract(verts[2], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height = VectorNormalize(cross) / VectorNormalize(dir1); // v + VectorSubtract(verts[3], verts[0], dir2); // p-a + CrossProduct(dir1, dir2, cross); + *height += VectorNormalize(cross) / VectorNormalize(dir1); // v *height *= 0.5f; } -//Consider a line in 3D with position vector "a" and direction vector "v" and -// let "p" be the position vector of an arbitrary point in 3D -//dist = len( crossprod(p-a,v) ) / len(v); +// Consider a line in 3D with position vector "a" and direction vector "v" and +// let "p" be the position vector of an arbitrary point in 3D +// dist = len( crossprod(p-a,v) ) / len(v); -void CG_InitGlass( void ) -{ +void CG_InitGlass(void) { int i, t; // Build a table first, so that we can do a more unpredictable crack scheme // do it once, up front to save a bit of time. - for ( i = 0; i < 20; i++ ) - { - for ( t = 0; t < 20; t++ ) - { + for (i = 0; i < 20; i++) { + for (t = 0; t < 20; t++) { offX[t][i] = Q_flrand(-1.0f, 1.0f) * 0.03f; offZ[i][t] = Q_flrand(-1.0f, 1.0f) * 0.03f; } } } -#define TIME_DECAY_SLOW 0.1f -#define TIME_DECAY_MED 0.04f -#define TIME_DECAY_FAST 0.009f - -void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius, int maxShards ) -{ - int i, t; - int mxHeight, mxWidth; - float height, width; - float stepWidth, stepHeight; - float timeDecay; - float x, z; - float xx, zz; - float dif; - int time = 0; - int glassShards = 0; - qboolean stick = qtrue; - vec3_t subVerts[4]; - vec2_t biPoints[4]; +#define TIME_DECAY_SLOW 0.1f +#define TIME_DECAY_MED 0.04f +#define TIME_DECAY_FAST 0.009f + +void CG_DoGlass(vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius, int maxShards) { + int i, t; + int mxHeight, mxWidth; + float height, width; + float stepWidth, stepHeight; + float timeDecay; + float x, z; + float xx, zz; + float dif; + int time = 0; + int glassShards = 0; + qboolean stick = qtrue; + vec3_t subVerts[4]; + vec2_t biPoints[4]; // To do a smarter tesselation, we should figure out the relative height and width of the brush face, // then use this to pick a lod value from 1-3 in each axis. This will give us 1-9 lod levels, which will // hopefully be sufficient. - CG_CalcHeightWidth( verts, &height, &width ); + CG_CalcHeightWidth(verts, &height, &width); - trap->S_StartSound( dmgPt, -1, CHAN_AUTO, trap->S_RegisterSound("sound/effects/glassbreak1.wav")); + trap->S_StartSound(dmgPt, -1, CHAN_AUTO, trap->S_RegisterSound("sound/effects/glassbreak1.wav")); // Pick "LOD" for height - if ( height < 100 ) - { + if (height < 100) { stepHeight = 0.2f; mxHeight = 5; timeDecay = TIME_DECAY_SLOW; - } - else if ( height > 220 ) - { + } else if (height > 220) { stepHeight = 0.05f; mxHeight = 20; timeDecay = TIME_DECAY_FAST; - } - else - { + } else { stepHeight = 0.1f; mxHeight = 10; timeDecay = TIME_DECAY_MED; @@ -494,129 +462,97 @@ void CG_DoGlass( vec3_t verts[4], vec3_t normal, vec3_t dmgPt, vec3_t dmgDir, fl } */ - //Attempt to scale the glass directly to the size of the window + // Attempt to scale the glass directly to the size of the window - stepWidth = (0.25f - (width*0.0002)); //(width*0.0005)); - mxWidth = width*0.2; - timeDecay = ( timeDecay + TIME_DECAY_FAST ) * 0.5f; + stepWidth = (0.25f - (width * 0.0002)); //(width*0.0005)); + mxWidth = width * 0.2; + timeDecay = (timeDecay + TIME_DECAY_FAST) * 0.5f; - if (stepWidth < 0.01f) - { + if (stepWidth < 0.01f) { stepWidth = 0.01f; } - if (mxWidth < 5) - { + if (mxWidth < 5) { mxWidth = 5; } - for ( z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++ ) - { - for ( x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++ ) - { + for (z = 0.0f, i = 0; z < 1.0f; z += stepHeight, i++) { + for (x = 0.0f, t = 0; x < 1.0f; x += stepWidth, t++) { // This is nasty.. - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i][t]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[0], xx, zz ); + VectorSet2(biPoints[0], xx, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i][t + 1]; - } - else - { + } else { xx = x; } - if ( i > 0 && i < mxHeight ) - { + if (i > 0 && i < mxHeight) { zz = z - offZ[t + 1][i]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[1], xx + stepWidth, zz ); + VectorSet2(biPoints[1], xx + stepWidth, zz); - if ( t + 1 > 0 && t + 1 < mxWidth ) - { + if (t + 1 > 0 && t + 1 < mxWidth) { xx = x - offX[i + 1][t + 1]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t + 1][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[2], xx + stepWidth, zz + stepHeight); + VectorSet2(biPoints[2], xx + stepWidth, zz + stepHeight); - if ( t > 0 && t < mxWidth ) - { + if (t > 0 && t < mxWidth) { xx = x - offX[i + 1][t]; - } - else - { + } else { xx = x; } - if ( i + 1 > 0 && i + 1 < mxHeight ) - { + if (i + 1 > 0 && i + 1 < mxHeight) { zz = z - offZ[t][i + 1]; - } - else - { + } else { zz = z; } - VectorSet2( biPoints[3], xx, zz + stepHeight ); + VectorSet2(biPoints[3], xx, zz + stepHeight); - CG_CalcBiLerp( verts, subVerts, biPoints ); + CG_CalcBiLerp(verts, subVerts, biPoints); - dif = DistanceSquared( subVerts[0], dmgPt ) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; + dif = DistanceSquared(subVerts[0], dmgPt) * timeDecay - Q_flrand(0.0f, 1.0f) * 32; // If we decrease dif, we are increasing the impact area, making it more likely to blow out large holes dif -= dmgRadius * dmgRadius; - if ( dif > 1 ) - { + if (dif > 1) { stick = qtrue; time = dif + Q_flrand(0.0f, 1.0f) * 200; - } - else - { + } else { stick = qfalse; time = 0; } - CG_DoGlassQuad( subVerts, biPoints, stick, time, dmgDir ); + CG_DoGlassQuad(subVerts, biPoints, stick, time, dmgDir); glassShards++; - if (maxShards && glassShards >= maxShards) - { + if (maxShards && glassShards >= maxShards) { return; } } @@ -629,20 +565,18 @@ CG_GlassShatter Break glass with fancy method ================== */ -void CG_GlassShatter(int entnum, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius, int maxShards) -{ - vec3_t verts[4], normal; +void CG_GlassShatter(int entnum, vec3_t dmgPt, vec3_t dmgDir, float dmgRadius, int maxShards) { + vec3_t verts[4], normal; - if (cgs.inlineDrawModel[cg_entities[entnum].currentState.modelindex]) - { + if (cgs.inlineDrawModel[cg_entities[entnum].currentState.modelindex]) { trap->R_GetBModelVerts(cgs.inlineDrawModel[cg_entities[entnum].currentState.modelindex], verts, normal); CG_DoGlass(verts, normal, dmgPt, dmgDir, dmgRadius, maxShards); } - //otherwise something awful has happened. + // otherwise something awful has happened. } //========================================================== -//SP-style chunks +// SP-style chunks //========================================================== /* @@ -654,26 +588,25 @@ intensity ranges from 1 (minor tremble) to 16 (major quake) ------------------------- */ -void CG_ExplosionEffects( vec3_t origin, float intensity, int radius, int time ) -{ - //FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s +void CG_ExplosionEffects(vec3_t origin, float intensity, int radius, int time) { + // FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s - vec3_t dir; - float dist, intensityScale; - float realIntensity; + vec3_t dir; + float dist, intensityScale; + float realIntensity; - VectorSubtract( cg.refdef.vieworg, origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(cg.refdef.vieworg, origin, dir); + dist = VectorNormalize(dir); - //Use the dir to add kick to the explosion + // Use the dir to add kick to the explosion - if ( dist > radius ) + if (dist > radius) return; - intensityScale = 1 - ( dist / (float) radius ); + intensityScale = 1 - (dist / (float)radius); realIntensity = intensity * intensityScale; - CGCam_Shake( realIntensity, time ); + CGCam_Shake(realIntensity, time); } /* @@ -684,20 +617,18 @@ Adds an explosion to a misc model breakables ------------------------- */ -void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ) -{ - int ct = 13; - float r; - vec3_t org, mid, dir; - char *effect = NULL, *effect2 = NULL; - int eID1, eID2 = 0; - int i; +void CG_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType) { + int ct = 13; + float r; + vec3_t org, mid, dir; + char *effect = NULL, *effect2 = NULL; + int eID1, eID2 = 0; + int i; - VectorAdd( mins, maxs, mid ); - VectorScale( mid, 0.5f, mid ); + VectorAdd(mins, maxs, mid); + VectorScale(mid, 0.5f, mid); - switch( chunkType ) - { + switch (chunkType) { default: break; case MAT_GLASS: @@ -730,13 +661,12 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk ct = 20; effect = "chunks/ropebreak"; break; - case MAT_WHITE_METAL: //not sure what this crap is really supposed to be.. + case MAT_WHITE_METAL: // not sure what this crap is really supposed to be.. case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: case MAT_SNOWY_ROCK: - switch( size ) - { + switch (size) { case 2: effect = "chunks/rockbreaklg"; break; @@ -747,45 +677,38 @@ void CG_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunk } } - if ( !effect ) - { + if (!effect) { return; } ct += 7 * size; // FIXME: real precache .. VERify that these need to be here...don't think they would because the effects should be registered in g_breakable - //rww - No they don't.. indexed effects gameside get precached on load clientside, as server objects are setup before client asset load time. - //However, we need to index them, so.. - eID1 = trap->FX_RegisterEffect( effect ); + // rww - No they don't.. indexed effects gameside get precached on load clientside, as server objects are setup before client asset load time. + // However, we need to index them, so.. + eID1 = trap->FX_RegisterEffect(effect); - if ( effect2 && effect2[0] ) - { + if (effect2 && effect2[0]) { // FIXME: real precache - eID2 = trap->FX_RegisterEffect( effect2 ); + eID2 = trap->FX_RegisterEffect(effect2); } // spawn chunk roughly in the bbox of the thing.. - for ( i = 0; i < ct; i++ ) - { + for (i = 0; i < ct; i++) { int j; - for( j = 0; j < 3; j++ ) - { + for (j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - org[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + org[j] = (r * mins[j] + (1 - r) * maxs[j]); } // shoot effect away from center - VectorSubtract( org, mid, dir ); - VectorNormalize( dir ); + VectorSubtract(org, mid, dir); + VectorNormalize(dir); - if ( effect2 && effect2[0] && ( rand() & 1 )) - { - trap->FX_PlayEffectID( eID2, org, dir, -1, -1, qfalse ); - } - else - { - trap->FX_PlayEffectID( eID1, org, dir, -1, -1, qfalse ); + if (effect2 && effect2[0] && (rand() & 1)) { + trap->FX_PlayEffectID(eID2, org, dir, -1, -1, qfalse); + } else { + trap->FX_PlayEffectID(eID1, org, dir, -1, -1, qfalse); } } } @@ -798,140 +721,126 @@ Fun chunk spewer ------------------------- */ -void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale ) -{ - localEntity_t *le; - refEntity_t *re; - vec3_t dir; - int i, j, k; - int chunkModel = 0; - leBounceSoundType_t bounce = LEBS_NONE; - float r, speedMod = 1.0f; - qboolean chunk = qfalse; - - if ( chunkType == MAT_NONE ) - { +void CG_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale) { + localEntity_t *le; + refEntity_t *re; + vec3_t dir; + int i, j, k; + int chunkModel = 0; + leBounceSoundType_t bounce = LEBS_NONE; + float r, speedMod = 1.0f; + qboolean chunk = qfalse; + + if (chunkType == MAT_NONE) { // Well, we should do nothing return; } - // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with effects instead of models - switch( chunkType ) - { + // Set up our chunk sound info...breaking sounds are done here so they are done once on breaking..some return instantly because the chunks are done with + // effects instead of models + switch (chunkType) { default: break; case MAT_GLASS: - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); return; break; case MAT_GRATE1: - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.grateSound ); + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.grateSound); return; break; - case MAT_ELECTRICAL:// (sparks) - trap->S_StartSound( NULL, owner, CHAN_BODY, trap->S_RegisterSound (va("sound/ambience/spark%d.wav", Q_irand(1, 6))) ); + case MAT_ELECTRICAL: // (sparks) + trap->S_StartSound(NULL, owner, CHAN_BODY, trap->S_RegisterSound(va("sound/ambience/spark%d.wav", Q_irand(1, 6)))); return; break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: - case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu + case MAT_WHITE_METAL: // not quite sure what this stuff is supposed to be...it's for Stu case MAT_SNOWY_ROCK: - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.rockBreakSound ); + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.rockBreakSound); bounce = LEBS_ROCK; speedMod = 0.5f; // rock blows up less break; case MAT_GLASS_METAL: - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.glassChunkSound ); // FIXME: should probably have a custom sound + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.glassChunkSound); // FIXME: should probably have a custom sound bounce = LEBS_METAL; break; case MAT_CRATE1: case MAT_CRATE2: - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0,1)] ); + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.crateBreakSound[Q_irand(0, 1)]); break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: - case MAT_ELEC_METAL:// FIXME: maybe have its own sound? - trap->S_StartSound( NULL, owner, CHAN_BODY, cgs.media.chunkSound ); + case MAT_ELEC_METAL: // FIXME: maybe have its own sound? + trap->S_StartSound(NULL, owner, CHAN_BODY, cgs.media.chunkSound); bounce = LEBS_METAL; speedMod = 0.8f; // metal blows up a bit more break; case MAT_ROPE: -// trap->S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound( "" )); FIXME: needs a sound + // trap->S_StartSound( NULL, owner, CHAN_BODY, cgi_S_RegisterSound( "" )); FIXME: needs a sound return; break; } - if ( baseScale <= 0.0f ) - { + if (baseScale <= 0.0f) { baseScale = 1.0f; } // Chunks - for( i = 0; i < numChunks; i++ ) - { - if ( customChunk > 0 ) - { + for (i = 0; i < numChunks; i++) { + if (customChunk > 0) { // Try to use a custom chunk. - if ( cgs.gameModels[customChunk] ) - { + if (cgs.gameModels[customChunk]) { chunk = qtrue; chunkModel = cgs.gameModels[customChunk]; } } - if ( !chunk ) - { + if (!chunk) { // No custom chunk. Pick a random chunk type at run-time so we don't get the same chunks - switch( chunkType ) - { + switch (chunkType) { default: break; - case MAT_METAL2: //bluegrey + case MAT_METAL2: // bluegrey chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; break; - case MAT_GREY_STONE://gray + case MAT_GREY_STONE: // gray chunkModel = cgs.media.chunkModels[CHUNK_ROCK1][Q_irand(0, 3)]; break; - case MAT_LT_STONE: //tan + case MAT_LT_STONE: // tan chunkModel = cgs.media.chunkModels[CHUNK_ROCK2][Q_irand(0, 3)]; break; - case MAT_DRK_STONE://brown + case MAT_DRK_STONE: // brown chunkModel = cgs.media.chunkModels[CHUNK_ROCK3][Q_irand(0, 3)]; break; - case MAT_SNOWY_ROCK://gray & brown - if ( Q_irand( 0, 1 ) ) - { + case MAT_SNOWY_ROCK: // gray & brown + if (Q_irand(0, 1)) { chunkModel = cgs.media.chunkModels[CHUNK_ROCK1][Q_irand(0, 3)]; - } - else - { + } else { chunkModel = cgs.media.chunkModels[CHUNK_ROCK3][Q_irand(0, 3)]; } break; case MAT_WHITE_METAL: chunkModel = cgs.media.chunkModels[CHUNK_WHITE_METAL][Q_irand(0, 3)]; break; - case MAT_CRATE1://yellow multi-colored crate chunks + case MAT_CRATE1: // yellow multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE1][Q_irand(0, 3)]; break; - case MAT_CRATE2://red multi-colored crate chunks + case MAT_CRATE2: // red multi-colored crate chunks chunkModel = cgs.media.chunkModels[CHUNK_CRATE2][Q_irand(0, 3)]; break; case MAT_ELEC_METAL: case MAT_GLASS_METAL: - case MAT_METAL://grey + case MAT_METAL: // grey chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; break; case MAT_METAL3: - if ( rand() & 1 ) - { + if (rand() & 1) { chunkModel = cgs.media.chunkModels[CHUNK_METAL1][Q_irand(0, 3)]; - } - else - { + } else { chunkModel = cgs.media.chunkModels[CHUNK_METAL2][Q_irand(0, 3)]; } break; @@ -939,8 +848,7 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins } // It wouldn't look good to throw a bunch of RGB axis models...so make sure we have something to work with. - if ( chunkModel ) - { + if (chunkModel) { le = CG_AllocLocalEntity(); re = &le->refEntity; @@ -949,41 +857,39 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins le->endTime = cg.time + 1300 + Q_flrand(0.0f, 1.0f) * 900; // spawn chunk roughly in the bbox of the thing...bias towards center in case thing blowing up doesn't complete fill its bbox. - for( j = 0; j < 3; j++ ) - { + for (j = 0; j < 3; j++) { r = Q_flrand(0.0f, 1.0f) * 0.8f + 0.1f; - re->origin[j] = ( r * mins[j] + ( 1 - r ) * maxs[j] ); + re->origin[j] = (r * mins[j] + (1 - r) * maxs[j]); } - VectorCopy( re->origin, le->pos.trBase ); + VectorCopy(re->origin, le->pos.trBase); // Move out from center of thing, otherwise you can end up things moving across the brush in an undesirable direction. Visually looks wrong - VectorSubtract( re->origin, origin, dir ); - VectorNormalize( dir ); - VectorScale( dir, flrand( speed * 0.5f, speed * 1.25f ) * speedMod, le->pos.trDelta ); + VectorSubtract(re->origin, origin, dir); + VectorNormalize(dir); + VectorScale(dir, flrand(speed * 0.5f, speed * 1.25f) * speedMod, le->pos.trDelta); // Angular Velocity - VectorSet( le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360 ); + VectorSet(le->angles.trBase, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360, Q_flrand(0.0f, 1.0f) * 360); le->angles.trDelta[0] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[1] = Q_flrand(-1.0f, 1.0f); le->angles.trDelta[2] = 0; // don't do roll - VectorScale( le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta ); + VectorScale(le->angles.trDelta, Q_flrand(0.0f, 1.0f) * 600.0f + 200.0f, le->angles.trDelta); le->pos.trType = TR_GRAVITY; le->angles.trType = TR_LINEAR; le->pos.trTime = le->angles.trTime = cg.time; le->bounceFactor = 0.2f + Q_flrand(0.0f, 1.0f) * 0.2f; le->leFlags |= LEF_TUMBLE; - //le->ownerGentNum = owner; + // le->ownerGentNum = owner; le->leBounceSoundType = bounce; // Make sure that we have the desired start size set - le->radius = flrand( baseScale * 0.75f, baseScale * 1.25f ); + le->radius = flrand(baseScale * 0.75f, baseScale * 1.25f); re->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, re->axis ); // could do an angles to axis, but this is cheaper and works ok - for( k = 0; k < 3; k++ ) - { + AxisCopy(axisDefault, re->axis); // could do an angles to axis, but this is cheaper and works ok + for (k = 0; k < 3; k++) { re->modelScale[k] = le->radius; } ScaleModelAxis(re); @@ -1002,10 +908,10 @@ void CG_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins CG_ScorePlum ================== */ -void CG_ScorePlum( int client, vec3_t org, int score ) { - localEntity_t *le; - refEntity_t *re; - vec3_t angles; +void CG_ScorePlum(int client, vec3_t org, int score) { + localEntity_t *le; + refEntity_t *re; + vec3_t angles; static vec3_t lastPos; // only visualize for the client that scored @@ -1018,28 +924,26 @@ void CG_ScorePlum( int client, vec3_t org, int score ) { le->leType = LE_SCOREPLUM; le->startTime = cg.time; le->endTime = cg.time + 4000; - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); - + le->lifeRate = 1.0 / (le->endTime - le->startTime); le->color[0] = le->color[1] = le->color[2] = le->color[3] = 1.0; le->radius = score; - VectorCopy( org, le->pos.trBase ); + VectorCopy(org, le->pos.trBase); if (org[2] >= lastPos[2] - 20 && org[2] <= lastPos[2] + 20) { le->pos.trBase[2] -= 20; } - //trap->Print( "Plum origin %i %i %i -- %i\n", (int)org[0], (int)org[1], (int)org[2], (int)Distance(org, lastPos)); + // trap->Print( "Plum origin %i %i %i -- %i\n", (int)org[0], (int)org[1], (int)org[2], (int)Distance(org, lastPos)); VectorCopy(org, lastPos); - re = &le->refEntity; re->reType = RT_SPRITE; re->radius = 16; VectorClear(angles); - AnglesToAxis( angles, re->axis ); + AnglesToAxis(angles, re->axis); } /* @@ -1047,44 +951,39 @@ void CG_ScorePlum( int client, vec3_t org, int score ) { CG_MakeExplosion ==================== */ -localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, - qhandle_t hModel, int numFrames, qhandle_t shader, - int msec, qboolean isSprite, float scale, int flags ) -{ - float ang = 0; - localEntity_t *ex; - int offset; - vec3_t tmpVec, newOrigin; - - if ( msec <= 0 ) { - trap->Error( ERR_DROP, "CG_MakeExplosion: msec = %i", msec ); +localEntity_t *CG_MakeExplosion(vec3_t origin, vec3_t dir, qhandle_t hModel, int numFrames, qhandle_t shader, int msec, qboolean isSprite, float scale, + int flags) { + float ang = 0; + localEntity_t *ex; + int offset; + vec3_t tmpVec, newOrigin; + + if (msec <= 0) { + trap->Error(ERR_DROP, "CG_MakeExplosion: msec = %i", msec); } // skew the time a bit so they aren't all in sync offset = rand() & 63; ex = CG_AllocLocalEntity(); - if ( isSprite ) { + if (isSprite) { ex->leType = LE_SPRITE_EXPLOSION; ex->refEntity.rotation = rand() % 360; ex->radius = scale; - VectorScale( dir, 16, tmpVec ); - VectorAdd( tmpVec, origin, newOrigin ); + VectorScale(dir, 16, tmpVec); + VectorAdd(tmpVec, origin, newOrigin); } else { ex->leType = LE_EXPLOSION; - VectorCopy( origin, newOrigin ); + VectorCopy(origin, newOrigin); // set axis with random rotate when necessary - if ( !dir ) - { - AxisClear( ex->refEntity.axis ); - } - else - { - if ( !(flags & LEF_NO_RANDOM_ROTATE) ) + if (!dir) { + AxisClear(ex->refEntity.axis); + } else { + if (!(flags & LEF_NO_RANDOM_ROTATE)) ang = rand() % 360; - VectorCopy( dir, ex->refEntity.axis[0] ); - RotateAroundDirection( ex->refEntity.axis, ang ); + VectorCopy(dir, ex->refEntity.axis[0]); + RotateAroundDirection(ex->refEntity.axis, ang); } } @@ -1099,24 +998,23 @@ localEntity_t *CG_MakeExplosion( vec3_t origin, vec3_t dir, ex->lifeRate = (float)numFrames / msec; ex->leFlags = flags; - //Scale the explosion + // Scale the explosion if (scale != 1) { ex->refEntity.nonNormalizedAxes = qtrue; - VectorScale( ex->refEntity.axis[0], scale, ex->refEntity.axis[0] ); - VectorScale( ex->refEntity.axis[1], scale, ex->refEntity.axis[1] ); - VectorScale( ex->refEntity.axis[2], scale, ex->refEntity.axis[2] ); + VectorScale(ex->refEntity.axis[0], scale, ex->refEntity.axis[0]); + VectorScale(ex->refEntity.axis[1], scale, ex->refEntity.axis[1]); + VectorScale(ex->refEntity.axis[2], scale, ex->refEntity.axis[2]); } // set origin - VectorCopy ( newOrigin, ex->refEntity.origin); - VectorCopy ( newOrigin, ex->refEntity.oldorigin ); + VectorCopy(newOrigin, ex->refEntity.origin); + VectorCopy(newOrigin, ex->refEntity.oldorigin); ex->color[0] = ex->color[1] = ex->color[2] = 1.0; return ex; } - /* ------------------------- CG_SurfaceExplosion @@ -1125,100 +1023,101 @@ Adds an explosion to a surface ------------------------- */ -#define NUM_SPARKS 12 -#define NUM_PUFFS 1 -#define NUM_EXPLOSIONS 4 - -void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ) -{ - localEntity_t *le; - //FXTrail *particle; - vec3_t direction, new_org; - vec3_t velocity = { 0, 0, 0 }; - vec3_t temp_org, temp_vel; -// float scale; - int i, numSparks; - - //Sparks +#define NUM_SPARKS 12 +#define NUM_PUFFS 1 +#define NUM_EXPLOSIONS 4 + +void CG_SurfaceExplosion(vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke) { + localEntity_t *le; + // FXTrail *particle; + vec3_t direction, new_org; + vec3_t velocity = {0, 0, 0}; + vec3_t temp_org, temp_vel; + // float scale; + int i, numSparks; + + // Sparks numSparks = 16 + (Q_flrand(0.0f, 1.0f) * 16.0f); - for ( i = 0; i < numSparks; i++ ) - { - // scale = 0.25f + (Q_flrand(0.0f, 1.0f) * 2.0f); + for (i = 0; i < numSparks; i++) { + // scale = 0.25f + (Q_flrand(0.0f, 1.0f) * 2.0f); + + /* particle = FX_AddTrail( origin, + NULL, + NULL, + 32.0f, + -64.0f, + scale, + -scale, + 1.0f, + 0.0f, + 0.25f, + 4000.0f, + cgs.media.sparkShader, + rand() & FXF_BOUNCE); + if ( particle == NULL ) + return; + + FXE_Spray( normal, 500, 150, 1.0f, 768 + (rand() & 255), (FXPrimitive *) particle );*/ + } -/* particle = FX_AddTrail( origin, - NULL, + // Smoke + // Move this out a little from the impact surface + VectorMA(origin, 4, normal, new_org); + VectorSet(velocity, 0.0f, 0.0f, 16.0f); + + for (i = 0; i < 4; i++) { + VectorSet(temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), + new_org[2] + (Q_flrand(0.0f, 1.0f) * 4.0f)); + VectorSet(temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), + velocity[2] + (Q_flrand(-1.0f, 1.0f) * 8.0f)); + + /* FX_AddSprite( temp_org, + temp_vel, NULL, - 32.0f, - -64.0f, - scale, - -scale, + 64.0f + (Q_flrand(0.0f, 1.0f) * 32.0f), + 16.0f, 1.0f, 0.0f, - 0.25f, - 4000.0f, - cgs.media.sparkShader, - rand() & FXF_BOUNCE); - if ( particle == NULL ) - return; - - FXE_Spray( normal, 500, 150, 1.0f, 768 + (rand() & 255), (FXPrimitive *) particle );*/ + 20.0f + (Q_flrand(-1.0f, 1.0f) * 90.0f), + 0.5f, + 1500.0f, + cgs.media.smokeShader, FXF_USE_ALPHA_CHAN );*/ } - //Smoke - //Move this out a little from the impact surface - VectorMA( origin, 4, normal, new_org ); - VectorSet( velocity, 0.0f, 0.0f, 16.0f ); + // Core of the explosion - for ( i = 0; i < 4; i++ ) - { - VectorSet( temp_org, new_org[0] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[1] + (Q_flrand(-1.0f, 1.0f) * 16.0f), new_org[2] + (Q_flrand(0.0f, 1.0f) * 4.0f) ); - VectorSet( temp_vel, velocity[0] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[1] + (Q_flrand(-1.0f, 1.0f) * 8.0f), velocity[2] + (Q_flrand(-1.0f, 1.0f) * 8.0f) ); - -/* FX_AddSprite( temp_org, - temp_vel, - NULL, - 64.0f + (Q_flrand(0.0f, 1.0f) * 32.0f), - 16.0f, - 1.0f, - 0.0f, - 20.0f + (Q_flrand(-1.0f, 1.0f) * 90.0f), - 0.5f, - 1500.0f, - cgs.media.smokeShader, FXF_USE_ALPHA_CHAN );*/ - } - - //Core of the explosion - - //Orient the explosions to face the camera - VectorSubtract( cg.refdef.vieworg, origin, direction ); - VectorNormalize( direction ); + // Orient the explosions to face the camera + VectorSubtract(cg.refdef.vieworg, origin, direction); + VectorNormalize(direction); - //Tag the last one with a light - le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, radius * 0.02f + (Q_flrand(0.0f, 1.0f) * 0.3f), 0); + // Tag the last one with a light + le = CG_MakeExplosion(origin, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 500, qfalse, + radius * 0.02f + (Q_flrand(0.0f, 1.0f) * 0.3f), 0); le->light = 150; - VectorSet( le->lightColor, 0.9f, 0.8f, 0.5f ); - - for ( i = 0; i < NUM_EXPLOSIONS-1; i ++) - { - VectorSet( new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)), (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8))*Q_flrand(-1.0f, 1.0f)) ); - le = CG_MakeExplosion( new_org, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, radius * 0.05f + (Q_flrand(-1.0f, 1.0f) *0.3f), 0); + VectorSet(le->lightColor, 0.9f, 0.8f, 0.5f); + + for (i = 0; i < NUM_EXPLOSIONS - 1; i++) { + VectorSet(new_org, (origin[0] + (16 + (Q_flrand(-1.0f, 1.0f) * 8)) * Q_flrand(-1.0f, 1.0f)), + (origin[1] + (16 + (Q_flrand(-1.0f, 1.0f) * 8)) * Q_flrand(-1.0f, 1.0f)), + (origin[2] + (16 + (Q_flrand(-1.0f, 1.0f) * 8)) * Q_flrand(-1.0f, 1.0f))); + le = CG_MakeExplosion(new_org, direction, cgs.media.explosionModel, 6, cgs.media.surfaceExplosionShader, 300 + (rand() & 99), qfalse, + radius * 0.05f + (Q_flrand(-1.0f, 1.0f) * 0.3f), 0); } - //Shake the camera - CG_ExplosionEffects( origin, shake_speed, 350, 750 ); + // Shake the camera + CG_ExplosionEffects(origin, shake_speed, 350, 750); // The level designers wanted to be able to turn the smoke spawners off. The rationale is that they // want to blow up catwalks and such that fall down...when that happens, it shouldn't really leave a mark // and a smoke spewer at the explosion point... - if ( smoke ) - { - VectorMA( origin, -8, normal, temp_org ); -// FX_AddSpawner( temp_org, normal, NULL, NULL, 100, Q_flrand(0.0f, 1.0f)*25.0f, 5000.0f, (void *) CG_SmokeSpawn ); + if (smoke) { + VectorMA(origin, -8, normal, temp_org); + // FX_AddSpawner( temp_org, normal, NULL, NULL, 100, Q_flrand(0.0f, 1.0f)*25.0f, 5000.0f, (void *) CG_SmokeSpawn ); - //Impact mark - //FIXME: Replace mark - //CG_ImpactMark( cgs.media.burnMarkShader, origin, normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qfalse, 8, qfalse ); + // Impact mark + // FIXME: Replace mark + // CG_ImpactMark( cgs.media.burnMarkShader, origin, normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qfalse, 8, qfalse ); } } @@ -1227,9 +1126,9 @@ void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shak CG_LaunchGib ================== */ -void CG_LaunchGib( vec3_t origin, vec3_t velocity, qhandle_t hModel ) { - localEntity_t *le; - refEntity_t *re; +void CG_LaunchGib(vec3_t origin, vec3_t velocity, qhandle_t hModel) { + localEntity_t *le; + refEntity_t *re; le = CG_AllocLocalEntity(); re = &le->refEntity; @@ -1238,13 +1137,13 @@ void CG_LaunchGib( vec3_t origin, vec3_t velocity, qhandle_t hModel ) { le->startTime = cg.time; le->endTime = le->startTime + 5000 + Q_flrand(0.0f, 1.0f) * 3000; - VectorCopy( origin, re->origin ); - AxisCopy( axisDefault, re->axis ); + VectorCopy(origin, re->origin); + AxisCopy(axisDefault, re->axis); re->hModel = hModel; le->pos.trType = TR_GRAVITY; - VectorCopy( origin, le->pos.trBase ); - VectorCopy( velocity, le->pos.trDelta ); + VectorCopy(origin, le->pos.trBase); + VectorCopy(velocity, le->pos.trDelta); le->pos.trTime = cg.time; le->bounceFactor = 0.6f; diff --git a/codemp/cgame/cg_ents.c b/codemp/cgame/cg_ents.c index 531dd40038..5c264ed81f 100644 --- a/codemp/cgame/cg_ents.c +++ b/codemp/cgame/cg_ents.c @@ -34,8 +34,8 @@ Ghoul2 Insert Start Ghoul2 Insert end */ -extern qboolean CG_InFighter( void ); -static void CG_Missile( centity_t *cent ); +extern qboolean CG_InFighter(void); +static void CG_Missile(centity_t *cent); /* ====================== @@ -45,27 +45,24 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName ) { - int i; - orientation_t lerped; +void CG_PositionEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName) { + int i; + orientation_t lerped; // lerp the tag - trap->R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0 - parent->backlerp, tagName ); + trap->R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0 - parent->backlerp, tagName); // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } // had to cast away the const to avoid compiler problems... - MatrixMultiply( lerped.axis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(lerped.axis, ((refEntity_t *)parent)->axis, entity->axis); entity->backlerp = parent->backlerp; } - /* ====================== CG_PositionRotatedEntityOnTag @@ -74,30 +71,26 @@ Modifies the entities position and axis by the given tag location ====================== */ -void CG_PositionRotatedEntityOnTag( refEntity_t *entity, const refEntity_t *parent, - qhandle_t parentModel, char *tagName ) { - int i; - orientation_t lerped; - matrix3_t tempAxis; +void CG_PositionRotatedEntityOnTag(refEntity_t *entity, const refEntity_t *parent, qhandle_t parentModel, char *tagName) { + int i; + orientation_t lerped; + matrix3_t tempAxis; -//AxisClear( entity->axis ); - // lerp the tag - trap->R_LerpTag( &lerped, parentModel, parent->oldframe, parent->frame, - 1.0 - parent->backlerp, tagName ); + // AxisClear( entity->axis ); + // lerp the tag + trap->R_LerpTag(&lerped, parentModel, parent->oldframe, parent->frame, 1.0 - parent->backlerp, tagName); // FIXME: allow origin offsets along tag? - VectorCopy( parent->origin, entity->origin ); - for ( i = 0 ; i < 3 ; i++ ) { - VectorMA( entity->origin, lerped.origin[i], parent->axis[i], entity->origin ); + VectorCopy(parent->origin, entity->origin); + for (i = 0; i < 3; i++) { + VectorMA(entity->origin, lerped.origin[i], parent->axis[i], entity->origin); } // had to cast away the const to avoid compiler problems... - MatrixMultiply( entity->axis, lerped.axis, tempAxis ); - MatrixMultiply( tempAxis, ((refEntity_t *)parent)->axis, entity->axis ); + MatrixMultiply(entity->axis, lerped.axis, tempAxis); + MatrixMultiply(tempAxis, ((refEntity_t *)parent)->axis, entity->axis); } - - /* ========================================================================== @@ -106,8 +99,8 @@ FUNCTIONS CALLED EACH FRAME ========================================================================== */ -//only need to use the CG_S_ system when you want a looping sound that isn't going to add itself -//via trap each frame. Such as ones generated by events. +// only need to use the CG_S_ system when you want a looping sound that isn't going to add itself +// via trap each frame. Such as ones generated by events. /* ====================== CG_SetEntitySoundPosition @@ -115,19 +108,16 @@ CG_SetEntitySoundPosition Also called by event processing code ====================== */ -void CG_SetEntitySoundPosition( centity_t *cent ) { - if ( cent->currentState.solid == SOLID_BMODEL ) - { - vec3_t origin; - float *v; - - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, origin ); - trap->S_UpdateEntityPosition( cent->currentState.number, origin ); - } - else - { - trap->S_UpdateEntityPosition( cent->currentState.number, cent->lerpOrigin ); +void CG_SetEntitySoundPosition(centity_t *cent) { + if (cent->currentState.solid == SOLID_BMODEL) { + vec3_t origin; + float *v; + + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, origin); + trap->S_UpdateEntityPosition(cent->currentState.number, origin); + } else { + trap->S_UpdateEntityPosition(cent->currentState.number, cent->lerpOrigin); } } @@ -138,20 +128,17 @@ CG_S_AddLoopingSound Set the current looping sounds on the entity. ================== */ -void CG_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) -{ +void CG_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) { centity_t *cent = &cg_entities[entityNum]; cgLoopSound_t *cSound = NULL; int i = 0; qboolean alreadyPlaying = qfalse; - //first see if we're already looping this sound handle. - while (i < cent->numLoopingSounds) - { + // first see if we're already looping this sound handle. + while (i < cent->numLoopingSounds) { cSound = ¢->loopingSound[i]; - if (cSound->sfx == sfx) - { + if (cSound->sfx == sfx) { alreadyPlaying = qtrue; break; } @@ -159,17 +146,14 @@ void CG_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t veloc i++; } - if (alreadyPlaying && cSound) - { //if this is the case, just update the properties of the looping sound and return. + if (alreadyPlaying && cSound) { // if this is the case, just update the properties of the looping sound and return. VectorCopy(origin, cSound->origin); VectorCopy(velocity, cSound->velocity); - } - else if (cent->numLoopingSounds >= MAX_CG_LOOPSOUNDS) - { //Just don't add it then I suppose. + } else if (cent->numLoopingSounds >= MAX_CG_LOOPSOUNDS) { // Just don't add it then I suppose. return; } - //Add a new looping sound. + // Add a new looping sound. cSound = ¢->loopingSound[cent->numLoopingSounds]; cSound->entityNum = entityNum; @@ -187,8 +171,7 @@ CG_S_AddLoopingSound For now just redirect, might eventually do something different. ================== */ -void CG_S_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) -{ +void CG_S_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) { CG_S_AddLoopingSound(entityNum, origin, velocity, sfx); } @@ -199,30 +182,23 @@ CG_S_AddLoopingSound Clear looping sounds. ================== */ -void CG_S_StopLoopingSound(int entityNum, sfxHandle_t sfx) -{ +void CG_S_StopLoopingSound(int entityNum, sfxHandle_t sfx) { centity_t *cent = &cg_entities[entityNum]; cgLoopSound_t *cSound; - if (sfx == -1) - { //clear all the looping sounds on the entity + if (sfx == -1) { // clear all the looping sounds on the entity cent->numLoopingSounds = 0; - } - else - { //otherwise, clear only the specified looping sound + } else { // otherwise, clear only the specified looping sound int i = 0; - while (i < cent->numLoopingSounds) - { + while (i < cent->numLoopingSounds) { cSound = ¢->loopingSound[i]; - if (cSound->sfx == sfx) - { //remove it then - int x = i+1; + if (cSound->sfx == sfx) { // remove it then + int x = i + 1; - while (x < cent->numLoopingSounds) - { - memcpy(¢->loopingSound[x-1], ¢->loopingSound[x], sizeof(cent->loopingSound[x])); + while (x < cent->numLoopingSounds) { + memcpy(¢->loopingSound[x - 1], ¢->loopingSound[x], sizeof(cent->loopingSound[x])); x++; } cent->numLoopingSounds--; @@ -231,7 +207,7 @@ void CG_S_StopLoopingSound(int entityNum, sfxHandle_t sfx) i++; } } - //trap->S_StopLoopingSound(entityNum); + // trap->S_StopLoopingSound(entityNum); } /* @@ -241,45 +217,39 @@ CG_S_UpdateLoopingSounds Update any existing looping sounds on the entity. ================== */ -void CG_S_UpdateLoopingSounds(int entityNum) -{ +void CG_S_UpdateLoopingSounds(int entityNum) { centity_t *cent = &cg_entities[entityNum]; cgLoopSound_t *cSound; vec3_t lerpOrg; float *v; int i = 0; - if (!cent->numLoopingSounds) - { + if (!cent->numLoopingSounds) { return; } - if (cent->currentState.eType == ET_MOVER) - { - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, lerpOrg ); - } - else - { + if (cent->currentState.eType == ET_MOVER) { + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, lerpOrg); + } else { VectorCopy(cent->lerpOrigin, lerpOrg); } - if ( (cent->currentState.eFlags & EF_SOUNDTRACKER) - && (!cg.snap || cent->currentState.trickedentindex != cg.snap->ps.clientNum) ) - {//keep sound for this entity updated in accordance with its attached entity at all times - //entity out of range - if ( !cg_entities[cent->currentState.trickedentindex].currentValid ) + if ((cent->currentState.eFlags & EF_SOUNDTRACKER) && + (!cg.snap || cent->currentState.trickedentindex != + cg.snap->ps.clientNum)) { // keep sound for this entity updated in accordance with its attached entity at all times + // entity out of range + if (!cg_entities[cent->currentState.trickedentindex].currentValid) return; - VectorCopy( cg_entities[cent->currentState.trickedentindex].lerpOrigin, lerpOrg ); + VectorCopy(cg_entities[cent->currentState.trickedentindex].lerpOrigin, lerpOrg); } - while (i < cent->numLoopingSounds) - { + while (i < cent->numLoopingSounds) { cSound = ¢->loopingSound[i]; - //trap->S_AddLoopingSound(entityNum, cSound->origin, cSound->velocity, cSound->sfx); - //I guess just keep using lerpOrigin for now, + // trap->S_AddLoopingSound(entityNum, cSound->origin, cSound->velocity, cSound->sfx); + // I guess just keep using lerpOrigin for now, trap->S_AddLoopingSound(entityNum, lerpOrg, cSound->velocity, cSound->sfx); i++; } @@ -292,81 +262,73 @@ CG_EntityEffects Add continuous entity effects, like local entity emission and lighting ================== */ -static void CG_EntityEffects( centity_t *cent ) { +static void CG_EntityEffects(centity_t *cent) { - if( !cent ) return; + if (!cent) + return; // update sound origins - CG_SetEntitySoundPosition( cent ); + CG_SetEntitySoundPosition(cent); // add loop sound - if ( cent->currentState.loopSound || ((cent->currentState.loopIsSoundset && cent->currentState.number >= MAX_CLIENTS) - && cent->currentState.loopSound < MAX_SOUNDS)) { + if (cent->currentState.loopSound || + ((cent->currentState.loopIsSoundset && cent->currentState.number >= MAX_CLIENTS) && cent->currentState.loopSound < MAX_SOUNDS)) { sfxHandle_t realSoundIndex = -1; - if (cent->currentState.loopIsSoundset && cent->currentState.number >= MAX_CLIENTS) - { //If this is so, then first get our soundset from the index, and loopSound actually contains which part of the set to - //use rather than a sound index (BMS_START [0], BMS_MID [1], or BMS_END [2]). Typically loop sounds will be BMS_MID. + if (cent->currentState.loopIsSoundset && + cent->currentState.number >= + MAX_CLIENTS) { // If this is so, then first get our soundset from the index, and loopSound actually contains which part of the set to + // use rather than a sound index (BMS_START [0], BMS_MID [1], or BMS_END [2]). Typically loop sounds will be BMS_MID. const char *soundSet; - soundSet = CG_ConfigString( CS_AMBIENT_SET + cent->currentState.soundSetIndex ); + soundSet = CG_ConfigString(CS_AMBIENT_SET + cent->currentState.soundSetIndex); - if (soundSet && soundSet[0]) - { + if (soundSet && soundSet[0]) { realSoundIndex = trap->AS_GetBModelSound(soundSet, cent->currentState.loopSound); } - } - else - { - realSoundIndex = cgs.gameSounds[ cent->currentState.loopSound ]; + } else { + realSoundIndex = cgs.gameSounds[cent->currentState.loopSound]; } - //rww - doors and things with looping sounds have a crazy origin (being brush models and all) - if (realSoundIndex != -1) - { - if ( cent->currentState.solid == SOLID_BMODEL ) - { - vec3_t origin; - float *v; + // rww - doors and things with looping sounds have a crazy origin (being brush models and all) + if (realSoundIndex != -1) { + if (cent->currentState.solid == SOLID_BMODEL) { + vec3_t origin; + float *v; - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, origin ); - trap->S_AddLoopingSound( cent->currentState.number, origin, vec3_origin, - realSoundIndex ); - } - else if (cent->currentState.eType != ET_SPEAKER) { - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex ); + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, origin); + trap->S_AddLoopingSound(cent->currentState.number, origin, vec3_origin, realSoundIndex); + } else if (cent->currentState.eType != ET_SPEAKER) { + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex); } else { - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex ); - // trap->S_AddRealLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex ); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex); + // trap->S_AddRealLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, realSoundIndex ); } } } - // constant light glow - if ( cent->currentState.constantLight && cent->currentState.eType != ET_PLAYER && cent->currentState.eType != ET_BODY && cent->currentState.eType != ET_NPC && cent->currentState.eType != ET_INVISIBLE ) { - int cl; - float i, r, g, b; + if (cent->currentState.constantLight && cent->currentState.eType != ET_PLAYER && cent->currentState.eType != ET_BODY && + cent->currentState.eType != ET_NPC && cent->currentState.eType != ET_INVISIBLE) { + int cl; + float i, r, g, b; cl = cent->currentState.constantLight; - r = (float) (cl & 0xFF) / 255.0; - g = (float) ((cl >> 8) & 0xFF) / 255.0; - b = (float) ((cl >> 16) & 0xFF) / 255.0; - i = (float) ((cl >> 24) & 0xFF) * 4.0; - trap->R_AddLightToScene( cent->lerpOrigin, i, r, g, b ); + r = (float)(cl & 0xFF) / 255.0; + g = (float)((cl >> 8) & 0xFF) / 255.0; + b = (float)((cl >> 16) & 0xFF) / 255.0; + i = (float)((cl >> 24) & 0xFF) * 4.0; + trap->R_AddLightToScene(cent->lerpOrigin, i, r, g, b); } - } -localEntity_t *FX_AddOrientedLine(vec3_t start, vec3_t end, vec3_t normal, float stScale, float scale, - float dscale, float startalpha, float endalpha, float killTime, qhandle_t shader) -{ - localEntity_t *le; +localEntity_t *FX_AddOrientedLine(vec3_t start, vec3_t end, vec3_t normal, float stScale, float scale, float dscale, float startalpha, float endalpha, + float killTime, qhandle_t shader) { + localEntity_t *le; #ifdef _DEBUG - if (!shader) - { + if (!shader) { Com_Printf("FX_AddLine: NULL shader\n"); } #endif @@ -388,12 +350,12 @@ localEntity_t *FX_AddOrientedLine(vec3_t start, vec3_t end, vec3_t normal, float le->refEntity.customShader = shader; // set origin - VectorCopy ( start, le->refEntity.origin); - VectorCopy ( end, le->refEntity.oldorigin ); + VectorCopy(start, le->refEntity.origin); + VectorCopy(end, le->refEntity.oldorigin); AxisClear(le->refEntity.axis); - VectorCopy( normal, le->refEntity.axis[0] ); - RotateAroundDirection( le->refEntity.axis, 0); // le->refEntity.data.sprite.rotation ); This is roll in quad land + VectorCopy(normal, le->refEntity.axis[0]); + RotateAroundDirection(le->refEntity.axis, 0); // le->refEntity.data.sprite.rotation ); This is roll in quad land le->refEntity.shaderRGBA[0] = 0xff; le->refEntity.shaderRGBA[1] = 0xff; @@ -404,27 +366,24 @@ localEntity_t *FX_AddOrientedLine(vec3_t start, vec3_t end, vec3_t normal, float le->color[1] = 1.0; le->color[2] = 1.0; le->color[3] = 1.0; - le->lifeRate = 1.0 / ( le->endTime - le->startTime ); + le->lifeRate = 1.0 / (le->endTime - le->startTime); - return(le); + return (le); } -void FX_DrawPortableShield(centity_t *cent) -{ - //rww - this code differs a bit from the draw code in EF, I don't know why I had to do - //it this way yet it worked in EF the other way. +void FX_DrawPortableShield(centity_t *cent) { + // rww - this code differs a bit from the draw code in EF, I don't know why I had to do + // it this way yet it worked in EF the other way. - int xaxis, height, posWidth, negWidth, team; - vec3_t start, end, normal; - qhandle_t shader; + int xaxis, height, posWidth, negWidth, team; + vec3_t start, end, normal; + qhandle_t shader; - if ( cl_paused.integer ) - { //rww - fix to keep from rendering repeatedly while HUD menu is up + if (cl_paused.integer) { // rww - fix to keep from rendering repeatedly while HUD menu is up return; } - if (cent->currentState.eFlags & EF_NODRAW) - { + if (cent->currentState.eFlags & EF_NODRAW) { return; } @@ -445,9 +404,7 @@ void FX_DrawPortableShield(centity_t *cent) { start[0] -= negWidth; end[0] += posWidth; - } - else - { + } else { start[1] -= negWidth; end[1] += posWidth; } @@ -455,29 +412,20 @@ void FX_DrawPortableShield(centity_t *cent) normal[0] = 1; normal[1] = 1; - start[2] += height/2; - end[2] += height/2; + start[2] += height / 2; + end[2] += height / 2; - if (team == TEAM_RED) - { - if (cent->currentState.trickedentindex) - { - shader = trap->R_RegisterShader( "gfx/misc/red_dmgshield" ); - } - else - { - shader = trap->R_RegisterShader( "gfx/misc/red_portashield" ); - } - } - else - { - if (cent->currentState.trickedentindex) - { - shader = trap->R_RegisterShader( "gfx/misc/blue_dmgshield" ); + if (team == TEAM_RED) { + if (cent->currentState.trickedentindex) { + shader = trap->R_RegisterShader("gfx/misc/red_dmgshield"); + } else { + shader = trap->R_RegisterShader("gfx/misc/red_portashield"); } - else - { - shader = trap->R_RegisterShader( "gfx/misc/blue_portashield" ); + } else { + if (cent->currentState.trickedentindex) { + shader = trap->R_RegisterShader("gfx/misc/blue_dmgshield"); + } else { + shader = trap->R_RegisterShader("gfx/misc/blue_portashield"); } } @@ -489,13 +437,12 @@ void FX_DrawPortableShield(centity_t *cent) CG_Special ================== */ -void CG_Special( centity_t *cent ) { - entityState_t *s1; +void CG_Special(centity_t *cent) { + entityState_t *s1; s1 = ¢->currentState; - if (!s1) - { + if (!s1) { return; } @@ -504,8 +451,7 @@ void CG_Special( centity_t *cent ) { return; } - if (s1->modelindex == HI_SHIELD) - { // The portable shield should go through a different rendering function. + if (s1->modelindex == HI_SHIELD) { // The portable shield should go through a different rendering function. FX_DrawPortableShield(cent); return; } @@ -516,245 +462,228 @@ Ghoul2 Insert Start */ // Copy the ghoul2 data into the ref ent correctly -void CG_SetGhoul2Info( refEntity_t *ent, centity_t *cent) -{ +void CG_SetGhoul2Info(refEntity_t *ent, centity_t *cent) { ent->ghoul2 = cent->ghoul2; - VectorCopy( cent->modelScale, ent->modelScale); + VectorCopy(cent->modelScale, ent->modelScale); ent->radius = cent->radius; - VectorCopy (cent->lerpAngles, ent->angles); + VectorCopy(cent->lerpAngles, ent->angles); } - - // create 8 new points on screen around a model so we can see it's bounding box -void CG_CreateBBRefEnts(entityState_t *s1, vec3_t origin ) -{ -/* -//g2r -#if _DEBUG - refEntity_t point[8]; - int i; - vec3_t angles = {0,0,0}; - - for (i=0; i<8; i++) - { - memset (&point[i], 0, sizeof(refEntity_t)); - point[i].reType = RT_SPRITE; - point[i].radius = 1; - point[i].customShader = trap->R_RegisterShader("textures/tests/circle"); - point[i].shaderRGBA[0] = 255; - point[i].shaderRGBA[1] = 255; - point[i].shaderRGBA[2] = 255; - point[i].shaderRGBA[3] = 255; - - AnglesToAxis( angles, point[i].axis ); - - // now, we need to put the correct origins into each origin from the mins and max's - switch(i) - { - case 0: - VectorCopy(s1->mins, point[i].origin); - break; - case 1: - VectorCopy(s1->mins, point[i].origin); - point[i].origin[0] = s1->maxs[0]; - break; - case 2: - VectorCopy(s1->mins, point[i].origin); - point[i].origin[1] = s1->maxs[1]; - break; - case 3: - VectorCopy(s1->mins, point[i].origin); - point[i].origin[0] = s1->maxs[0]; - point[i].origin[1] = s1->maxs[1]; - break; - case 4: - VectorCopy(s1->maxs, point[i].origin); - break; - case 5: - VectorCopy(s1->maxs, point[i].origin); - point[i].origin[0] = s1->mins[0]; - break; - case 6: - VectorCopy(s1->maxs, point[i].origin); - point[i].origin[1] = s1->mins[1]; - break; - case 7: - VectorCopy(s1->maxs, point[i].origin); - point[i].origin[0] = s1->mins[0]; - point[i].origin[1] = s1->mins[1]; - break; - } - - // add the original origin to each point and then stuff them out there - VectorAdd(point[i].origin, origin, point[i].origin); - - trap->R_AddRefEntityToScene (&point[i]); - } -#endif - */ +void CG_CreateBBRefEnts(entityState_t *s1, vec3_t origin) { + /* + //g2r + #if _DEBUG + refEntity_t point[8]; + int i; + vec3_t angles = {0,0,0}; + + for (i=0; i<8; i++) + { + memset (&point[i], 0, sizeof(refEntity_t)); + point[i].reType = RT_SPRITE; + point[i].radius = 1; + point[i].customShader = trap->R_RegisterShader("textures/tests/circle"); + point[i].shaderRGBA[0] = 255; + point[i].shaderRGBA[1] = 255; + point[i].shaderRGBA[2] = 255; + point[i].shaderRGBA[3] = 255; + + AnglesToAxis( angles, point[i].axis ); + + // now, we need to put the correct origins into each origin from the mins and max's + switch(i) + { + case 0: + VectorCopy(s1->mins, point[i].origin); + break; + case 1: + VectorCopy(s1->mins, point[i].origin); + point[i].origin[0] = s1->maxs[0]; + break; + case 2: + VectorCopy(s1->mins, point[i].origin); + point[i].origin[1] = s1->maxs[1]; + break; + case 3: + VectorCopy(s1->mins, point[i].origin); + point[i].origin[0] = s1->maxs[0]; + point[i].origin[1] = s1->maxs[1]; + break; + case 4: + VectorCopy(s1->maxs, point[i].origin); + break; + case 5: + VectorCopy(s1->maxs, point[i].origin); + point[i].origin[0] = s1->mins[0]; + break; + case 6: + VectorCopy(s1->maxs, point[i].origin); + point[i].origin[1] = s1->mins[1]; + break; + case 7: + VectorCopy(s1->maxs, point[i].origin); + point[i].origin[0] = s1->mins[0]; + point[i].origin[1] = s1->mins[1]; + break; + } + + // add the original origin to each point and then stuff them out there + VectorAdd(point[i].origin, origin, point[i].origin); + + trap->R_AddRefEntityToScene (&point[i]); + } + #endif + */ } // write in the axis and stuff -void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) -{ - // extract the wraith ID from the bolt info +void G2_BoltToGhoul2Model(centity_t *cent, refEntity_t *ent) { + // extract the wraith ID from the bolt info int modelNum = cent->boltInfo >> MODEL_SHIFT; - int boltNum = cent->boltInfo >> BOLT_SHIFT; - int entNum = cent->boltInfo >> ENTITY_SHIFT; - mdxaBone_t boltMatrix; + int boltNum = cent->boltInfo >> BOLT_SHIFT; + int entNum = cent->boltInfo >> ENTITY_SHIFT; + mdxaBone_t boltMatrix; modelNum &= MODEL_AND; boltNum &= BOLT_AND; entNum &= ENTITY_AND; - - //NOTENOTE I put this here because the cgs.gamemodels array no longer gets initialized. + // NOTENOTE I put this here because the cgs.gamemodels array no longer gets initialized. assert(0); - - // go away and get me the bolt position for this frame please - trap->G2API_GetBoltMatrix(cent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, cg.time, cgs.gameModels, cent->modelScale); + // go away and get me the bolt position for this frame please + trap->G2API_GetBoltMatrix(cent->ghoul2, modelNum, boltNum, &boltMatrix, cg_entities[entNum].currentState.angles, cg_entities[entNum].currentState.origin, + cg.time, cgs.gameModels, cent->modelScale); // set up the axis and origin we need for the actual effect spawning - ent->origin[0] = boltMatrix.matrix[0][3]; - ent->origin[1] = boltMatrix.matrix[1][3]; - ent->origin[2] = boltMatrix.matrix[2][3]; + ent->origin[0] = boltMatrix.matrix[0][3]; + ent->origin[1] = boltMatrix.matrix[1][3]; + ent->origin[2] = boltMatrix.matrix[2][3]; - ent->axis[0][0] = boltMatrix.matrix[0][0]; - ent->axis[0][1] = boltMatrix.matrix[1][0]; - ent->axis[0][2] = boltMatrix.matrix[2][0]; + ent->axis[0][0] = boltMatrix.matrix[0][0]; + ent->axis[0][1] = boltMatrix.matrix[1][0]; + ent->axis[0][2] = boltMatrix.matrix[2][0]; - ent->axis[1][0] = boltMatrix.matrix[0][1]; - ent->axis[1][1] = boltMatrix.matrix[1][1]; - ent->axis[1][2] = boltMatrix.matrix[2][1]; + ent->axis[1][0] = boltMatrix.matrix[0][1]; + ent->axis[1][1] = boltMatrix.matrix[1][1]; + ent->axis[1][2] = boltMatrix.matrix[2][1]; - ent->axis[2][0] = boltMatrix.matrix[0][2]; - ent->axis[2][1] = boltMatrix.matrix[1][2]; - ent->axis[2][2] = boltMatrix.matrix[2][2]; + ent->axis[2][0] = boltMatrix.matrix[0][2]; + ent->axis[2][1] = boltMatrix.matrix[1][2]; + ent->axis[2][2] = boltMatrix.matrix[2][2]; } -void ScaleModelAxis(refEntity_t *ent) +void ScaleModelAxis(refEntity_t *ent) -{ // scale the model should we need to - if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) - { - VectorScale( ent->axis[0], ent->modelScale[0] , ent->axis[0] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) - { - VectorScale( ent->axis[1], ent->modelScale[1] , ent->axis[1] ); - ent->nonNormalizedAxes = qtrue; - } - if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) - { - VectorScale( ent->axis[2], ent->modelScale[2] , ent->axis[2] ); - ent->nonNormalizedAxes = qtrue; - } +{ // scale the model should we need to + if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) { + VectorScale(ent->axis[0], ent->modelScale[0], ent->axis[0]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) { + VectorScale(ent->axis[1], ent->modelScale[1], ent->axis[1]); + ent->nonNormalizedAxes = qtrue; + } + if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) { + VectorScale(ent->axis[2], ent->modelScale[2], ent->axis[2]); + ent->nonNormalizedAxes = qtrue; + } } /* Ghoul2 Insert End */ char *forceHolocronModels[NUM_FORCE_POWERS] = { - "models/map_objects/mp/lt_heal.md3", //FP_HEAL, - "models/map_objects/mp/force_jump.md3", //FP_LEVITATION, - "models/map_objects/mp/force_speed.md3", //FP_SPEED, - "models/map_objects/mp/force_push.md3", //FP_PUSH, - "models/map_objects/mp/force_pull.md3", //FP_PULL, - "models/map_objects/mp/lt_telepathy.md3", //FP_TELEPATHY, - "models/map_objects/mp/dk_grip.md3", //FP_GRIP, - "models/map_objects/mp/dk_lightning.md3", //FP_LIGHTNING, - "models/map_objects/mp/dk_rage.md3", //FP_RAGE, - "models/map_objects/mp/lt_protect.md3", //FP_PROTECT, - "models/map_objects/mp/lt_absorb.md3", //FP_ABSORB, - "models/map_objects/mp/lt_healother.md3", //FP_TEAM_HEAL, - "models/map_objects/mp/dk_powerother.md3", //FP_TEAM_FORCE, - "models/map_objects/mp/dk_drain.md3", //FP_DRAIN, - "models/map_objects/mp/force_sight.md3", //FP_SEE, - "models/map_objects/mp/saber_attack.md3", //FP_SABER_OFFENSE, - "models/map_objects/mp/saber_defend.md3", //FP_SABER_DEFENSE, - "models/map_objects/mp/saber_throw.md3" //FP_SABERTHROW + "models/map_objects/mp/lt_heal.md3", // FP_HEAL, + "models/map_objects/mp/force_jump.md3", // FP_LEVITATION, + "models/map_objects/mp/force_speed.md3", // FP_SPEED, + "models/map_objects/mp/force_push.md3", // FP_PUSH, + "models/map_objects/mp/force_pull.md3", // FP_PULL, + "models/map_objects/mp/lt_telepathy.md3", // FP_TELEPATHY, + "models/map_objects/mp/dk_grip.md3", // FP_GRIP, + "models/map_objects/mp/dk_lightning.md3", // FP_LIGHTNING, + "models/map_objects/mp/dk_rage.md3", // FP_RAGE, + "models/map_objects/mp/lt_protect.md3", // FP_PROTECT, + "models/map_objects/mp/lt_absorb.md3", // FP_ABSORB, + "models/map_objects/mp/lt_healother.md3", // FP_TEAM_HEAL, + "models/map_objects/mp/dk_powerother.md3", // FP_TEAM_FORCE, + "models/map_objects/mp/dk_drain.md3", // FP_DRAIN, + "models/map_objects/mp/force_sight.md3", // FP_SEE, + "models/map_objects/mp/saber_attack.md3", // FP_SABER_OFFENSE, + "models/map_objects/mp/saber_defend.md3", // FP_SABER_DEFENSE, + "models/map_objects/mp/saber_throw.md3" // FP_SABERTHROW }; -void CG_Disintegration(centity_t *cent, refEntity_t *ent) -{ +void CG_Disintegration(centity_t *cent, refEntity_t *ent) { vec3_t tempAng, hitLoc; float tempLength; VectorCopy(cent->currentState.origin2, hitLoc); - VectorSubtract( hitLoc, ent->origin, ent->oldorigin ); + VectorSubtract(hitLoc, ent->origin, ent->oldorigin); - tempLength = VectorNormalize( ent->oldorigin ); - vectoangles( ent->oldorigin, tempAng ); + tempLength = VectorNormalize(ent->oldorigin); + vectoangles(ent->oldorigin, tempAng); tempAng[YAW] -= cent->lerpAngles[YAW]; - AngleVectors( tempAng, ent->oldorigin, NULL, NULL ); - VectorScale( ent->oldorigin, tempLength, ent->oldorigin ); + AngleVectors(tempAng, ent->oldorigin, NULL, NULL); + VectorScale(ent->oldorigin, tempLength, ent->oldorigin); ent->endTime = cent->dustTrailTime; ent->renderfx |= RF_DISINTEGRATE2; ent->customShader = cgs.media.disruptorShader; - trap->R_AddRefEntityToScene( ent ); + trap->R_AddRefEntityToScene(ent); ent->renderfx &= ~(RF_DISINTEGRATE2); ent->renderfx |= (RF_DISINTEGRATE1); ent->customShader = 0; - trap->R_AddRefEntityToScene( ent ); + trap->R_AddRefEntityToScene(ent); - if ( cg.time - ent->endTime < 1000 && (timescale.value * timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f ) - { + if (cg.time - ent->endTime < 1000 && (timescale.value * timescale.value * Q_flrand(0.0f, 1.0f)) > 0.05f) { vec3_t fxOrg, fxDir; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; int torsoBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "lower_lumbar"); VectorSet(fxDir, 0, 1, 0); - trap->G2API_GetBoltMatrix( cent->ghoul2, 0, torsoBolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, - cgs.gameModels, cent->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, fxOrg ); + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, torsoBolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, fxOrg); - VectorMA( fxOrg, -18, cg.refdef.viewaxis[0], fxOrg ); + VectorMA(fxOrg, -18, cg.refdef.viewaxis[0], fxOrg); fxOrg[2] += Q_flrand(-1.0f, 1.0f) * 20; - trap->FX_PlayEffectID( cgs.effects.mDisruptorDeathSmoke, fxOrg, fxDir, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.mDisruptorDeathSmoke, fxOrg, fxDir, -1, -1, qfalse); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - trap->FX_PlayEffectID( cgs.effects.mDisruptorDeathSmoke, fxOrg, fxDir, -1, -1, qfalse ); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + trap->FX_PlayEffectID(cgs.effects.mDisruptorDeathSmoke, fxOrg, fxDir, -1, -1, qfalse); } } } extern int cgSiegeEntityRender; -static qboolean CG_RenderTimeEntBolt(centity_t *cent) -{ - int clientNum = cent->currentState.boltToPlayer-1; +static qboolean CG_RenderTimeEntBolt(centity_t *cent) { + int clientNum = cent->currentState.boltToPlayer - 1; centity_t *cl; mdxaBone_t matrix; vec3_t boltOrg, boltAng; int getBolt = -1; - if (clientNum >= MAX_CLIENTS || clientNum < 0) - { + if (clientNum >= MAX_CLIENTS || clientNum < 0) { assert(0); return qfalse; } cl = &cg_entities[clientNum]; - if (!cl->ghoul2) - { + if (!cl->ghoul2) { assert(0); return qfalse; } if (clientNum == cg.predictedPlayerState.clientNum && - !cg.renderingThirdPerson) - { //If in first person and you have it then render the thing spinning around on your hud. - cgSiegeEntityRender = cent->currentState.number; //set it to render at the end of the frame. + !cg.renderingThirdPerson) { // If in first person and you have it then render the thing spinning around on your hud. + cgSiegeEntityRender = cent->currentState.number; // set it to render at the end of the frame. return qfalse; } @@ -825,11 +754,9 @@ static void CG_SiegeEntRenderAboveHead(centity_t *cent) } */ -void CG_AddRadarEnt(centity_t *cent) -{ - static const size_t numRadarEnts = ARRAY_LEN( cg.radarEntities ); - if (cg.radarEntityCount >= numRadarEnts) - { +void CG_AddRadarEnt(centity_t *cent) { + static const size_t numRadarEnts = ARRAY_LEN(cg.radarEntities); + if (cg.radarEntityCount >= numRadarEnts) { #ifdef _DEBUG Com_Printf("^3Warning: CG_AddRadarEnt full. (%d max)\n", numRadarEnts); #endif @@ -838,11 +765,9 @@ void CG_AddRadarEnt(centity_t *cent) cg.radarEntities[cg.radarEntityCount++] = cent->currentState.number; } -void CG_AddBracketedEnt(centity_t *cent) -{ - static const size_t numBracketEnts = ARRAY_LEN( cg.bracketedEntities ); - if (cg.bracketedEntityCount >= numBracketEnts) - { +void CG_AddBracketedEnt(centity_t *cent) { + static const size_t numBracketEnts = ARRAY_LEN(cg.bracketedEntities); + if (cg.bracketedEntityCount >= numBracketEnts) { #ifdef _DEBUG Com_Printf("^3Warning: CG_AddBracketedEnt full. (%d max)\n", numBracketEnts); #endif @@ -857,117 +782,92 @@ CG_General */ void CG_G2ServerBoneAngles(centity_t *cent); -extern qboolean BG_GetRootSurfNameWithVariant( void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize ); +extern qboolean BG_GetRootSurfNameWithVariant(void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize); -static void CG_General( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; - float val; - int beamID; - vec3_t beamOrg; - mdxaBone_t matrix; - qboolean doNotSetModel = qfalse; +static void CG_General(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; + float val; + int beamID; + vec3_t beamOrg; + mdxaBone_t matrix; + qboolean doNotSetModel = qfalse; - if (cent->currentState.modelGhoul2 == 127) - { //not ready to be drawn or initialized.. + if (cent->currentState.modelGhoul2 == 127) { // not ready to be drawn or initialized.. return; } if (cent->ghoul2 && !cent->currentState.modelGhoul2 && cent->currentState.eType != ET_BODY && - cent->currentState.number >= MAX_CLIENTS) - { //this is a bad thing - if (trap->G2_HaveWeGhoul2Models(cent->ghoul2)) - { + cent->currentState.number >= MAX_CLIENTS) { // this is a bad thing + if (trap->G2_HaveWeGhoul2Models(cent->ghoul2)) { trap->G2API_CleanGhoul2Models(&(cent->ghoul2)); } } - if (cent->currentState.eFlags & EF_RADAROBJECT) - { + if (cent->currentState.eFlags & EF_RADAROBJECT) { CG_AddRadarEnt(cent); } - if (cent->currentState.eFlags2 & EF2_BRACKET_ENTITY) - { - if ( CG_InFighter() ) - {//only bracken when in a fighter + if (cent->currentState.eFlags2 & EF2_BRACKET_ENTITY) { + if (CG_InFighter()) { // only bracken when in a fighter CG_AddBracketedEnt(cent); } } - if (cent->currentState.boltToPlayer) - { //Shove it into the player's left hand then. - centity_t *pl = &cg_entities[cent->currentState.boltToPlayer-1]; - if (CG_IsMindTricked(pl->currentState.trickedentindex, - pl->currentState.trickedentindex2, - pl->currentState.trickedentindex3, - pl->currentState.trickedentindex4, - cg.predictedPlayerState.clientNum)) - { //don't show if this guy is mindtricking - return; + if (cent->currentState.boltToPlayer) { // Shove it into the player's left hand then. + centity_t *pl = &cg_entities[cent->currentState.boltToPlayer - 1]; + if (CG_IsMindTricked(pl->currentState.trickedentindex, pl->currentState.trickedentindex2, pl->currentState.trickedentindex3, + pl->currentState.trickedentindex4, + cg.predictedPlayerState.clientNum)) { // don't show if this guy is mindtricking + return; } - if (!CG_RenderTimeEntBolt(cent)) - { //If this function returns qfalse we shouldn't render this ent at all. - if (cent->currentState.boltToPlayer > 0 && - cent->currentState.boltToPlayer <= MAX_CLIENTS) - { + if (!CG_RenderTimeEntBolt(cent)) { // If this function returns qfalse we shouldn't render this ent at all. + if (cent->currentState.boltToPlayer > 0 && cent->currentState.boltToPlayer <= MAX_CLIENTS) { VectorCopy(pl->lerpOrigin, cent->lerpOrigin); - if (cent->currentState.eFlags & EF_CLIENTSMOOTH) - { //if it's set to smooth keep the smoothed lerp origin updated, as we don't want to smooth while bolted. + if (cent->currentState.eFlags & + EF_CLIENTSMOOTH) { // if it's set to smooth keep the smoothed lerp origin updated, as we don't want to smooth while bolted. VectorCopy(cent->lerpOrigin, cent->turAngles); } } return; } - if (cent->currentState.eFlags & EF_CLIENTSMOOTH) - { //if it's set to smooth keep the smoothed lerp origin updated, as we don't want to smooth while bolted. + if (cent->currentState.eFlags & + EF_CLIENTSMOOTH) { // if it's set to smooth keep the smoothed lerp origin updated, as we don't want to smooth while bolted. VectorCopy(cent->lerpOrigin, cent->turAngles); } -/* disabled for now - if (pl->currentState.number != cg.predictedPlayerState.clientNum) - { //don't render thing above head to self - CG_SiegeEntRenderAboveHead(cent); - } -*/ - } - else if (cent->currentState.eFlags & EF_CLIENTSMOOTH) - { - if (cent->currentState.groundEntityNum >= ENTITYNUM_WORLD) - { - float smoothFactor = 0.5f*timescale.value; + /* disabled for now + if (pl->currentState.number != cg.predictedPlayerState.clientNum) + { //don't render thing above head to self + CG_SiegeEntRenderAboveHead(cent); + } + */ + } else if (cent->currentState.eFlags & EF_CLIENTSMOOTH) { + if (cent->currentState.groundEntityNum >= ENTITYNUM_WORLD) { + float smoothFactor = 0.5f * timescale.value; int k = 0; vec3_t posDif; - //Use origin smoothing since dismembered limbs use ExPhys - if (DistanceSquared(cent->turAngles,cent->lerpOrigin)>18000.0f) - { + // Use origin smoothing since dismembered limbs use ExPhys + if (DistanceSquared(cent->turAngles, cent->lerpOrigin) > 18000.0f) { VectorCopy(cent->lerpOrigin, cent->turAngles); } VectorSubtract(cent->lerpOrigin, cent->turAngles, posDif); - for (k=0;k<3;k++) - { - cent->turAngles[k]=(cent->turAngles[k]+posDif[k]*smoothFactor); - cent->lerpOrigin[k]=cent->turAngles[k]; + for (k = 0; k < 3; k++) { + cent->turAngles[k] = (cent->turAngles[k] + posDif[k] * smoothFactor); + cent->lerpOrigin[k] = cent->turAngles[k]; } - } - else - { //if we're sitting on an entity like a moving plat then we don't want to smooth either + } else { // if we're sitting on an entity like a moving plat then we don't want to smooth either VectorCopy(cent->lerpOrigin, cent->turAngles); } } - //rww - now do ragdoll stuff - if (cent->ghoul2 && - (cent->currentState.eType == ET_BODY || (cent->currentState.eFlags & EF_RAG))) - { - if (!(cent->currentState.eFlags & EF_NODRAW) && - !(cent->currentState.eFlags & EF_DISINTEGRATION) && - cent->bodyFadeTime <= cg.time) - { + // rww - now do ragdoll stuff + if (cent->ghoul2 && (cent->currentState.eType == ET_BODY || (cent->currentState.eFlags & EF_RAG))) { + if (!(cent->currentState.eFlags & EF_NODRAW) && !(cent->currentState.eFlags & EF_DISINTEGRATION) && cent->bodyFadeTime <= cg.time) { vec3_t forcedAngles; VectorClear(forcedAngles); @@ -975,33 +875,27 @@ static void CG_General( centity_t *cent ) { CG_RagDoll(cent, forcedAngles); } - } - else if (cent->isRagging) - { + } else if (cent->isRagging) { cent->isRagging = qfalse; - if (cent->ghoul2 && trap->G2_HaveWeGhoul2Models(cent->ghoul2)) - { //May not be valid, in the case of a ragged entity being removed and a non-g2 ent filling its slot. - trap->G2API_SetRagDoll(cent->ghoul2, NULL); //calling with null parms resets to no ragdoll. + if (cent->ghoul2 && + trap->G2_HaveWeGhoul2Models(cent->ghoul2)) { // May not be valid, in the case of a ragged entity being removed and a non-g2 ent filling its slot. + trap->G2API_SetRagDoll(cent->ghoul2, NULL); // calling with null parms resets to no ragdoll. } } - if (cent->currentState.boneOrient && cent->ghoul2) - { //server sent us some bone angles to use + if (cent->currentState.boneOrient && cent->ghoul2) { // server sent us some bone angles to use CG_G2ServerBoneAngles(cent); } - if ((cent->currentState.eFlags & EF_G2ANIMATING) && cent->ghoul2) - { //mini-animation routine for general objects that want to play quick ghoul2 anims - //obviously lacks much of the functionality contained in player/npc animation. - //we actually use torsoAnim as the start frame and legsAnim as the end frame and - //always play the anim on the root bone. - if (cent->currentState.torsoAnim != cent->pe.torso.animationNumber || - cent->currentState.legsAnim != cent->pe.legs.animationNumber || - cent->currentState.torsoFlip != cent->pe.torso.lastFlip) - { - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", cent->currentState.torsoAnim, - cent->currentState.legsAnim, (BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND), 1.0f, cg.time, -1, 100); + if ((cent->currentState.eFlags & EF_G2ANIMATING) && cent->ghoul2) { // mini-animation routine for general objects that want to play quick ghoul2 anims + // obviously lacks much of the functionality contained in player/npc animation. + // we actually use torsoAnim as the start frame and legsAnim as the end frame and + // always play the anim on the root bone. + if (cent->currentState.torsoAnim != cent->pe.torso.animationNumber || cent->currentState.legsAnim != cent->pe.legs.animationNumber || + cent->currentState.torsoFlip != cent->pe.torso.lastFlip) { + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", cent->currentState.torsoAnim, cent->currentState.legsAnim, + (BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND), 1.0f, cg.time, -1, 100); cent->pe.torso.animationNumber = cent->currentState.torsoAnim; cent->pe.legs.animationNumber = cent->currentState.legsAnim; @@ -1009,72 +903,63 @@ static void CG_General( centity_t *cent ) { } } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); ent.shaderRGBA[0] = cent->currentState.customRGBA[0]; ent.shaderRGBA[1] = cent->currentState.customRGBA[1]; ent.shaderRGBA[2] = cent->currentState.customRGBA[2]; ent.shaderRGBA[3] = cent->currentState.customRGBA[3]; - if (cent->currentState.modelGhoul2 >= G2_MODELPART_HEAD && - cent->currentState.modelGhoul2 <= G2_MODELPART_RLEG && + if (cent->currentState.modelGhoul2 >= G2_MODELPART_HEAD && cent->currentState.modelGhoul2 <= G2_MODELPART_RLEG && /*cent->currentState.modelindex < MAX_CLIENTS &&*/ - cent->currentState.weapon == G2_MODEL_PART) - { //special case for client limbs + cent->currentState.weapon == G2_MODEL_PART) { // special case for client limbs centity_t *clEnt; int dismember_settings = cg_dismember.integer; - float smoothFactor = 0.5f*timescale.value; + float smoothFactor = 0.5f * timescale.value; int k = 0; vec3_t posDif; doNotSetModel = qtrue; - if (cent->currentState.modelindex >= 0) - { + if (cent->currentState.modelindex >= 0) { clEnt = &cg_entities[cent->currentState.modelindex]; - } - else - { + } else { clEnt = &cg_entities[cent->currentState.otherEntityNum2]; } - if (!dismember_settings) - { //This client does not wish to see dismemberment. + if (!dismember_settings) { // This client does not wish to see dismemberment. return; } - if (dismember_settings < 2 && (cent->currentState.modelGhoul2 == G2_MODELPART_HEAD || cent->currentState.modelGhoul2 == G2_MODELPART_WAIST)) - { //dismember settings are not high enough to display decaps and torso slashes + if (dismember_settings < 2 && + (cent->currentState.modelGhoul2 == G2_MODELPART_HEAD || + cent->currentState.modelGhoul2 == G2_MODELPART_WAIST)) { // dismember settings are not high enough to display decaps and torso slashes return; } - if (!cent->ghoul2) - { + if (!cent->ghoul2) { const char *rotateBone; - char limbName[MAX_QPATH]; - char stubName[MAX_QPATH]; - char limbCapName[MAX_QPATH]; - char stubCapName[MAX_QPATH]; + char limbName[MAX_QPATH]; + char stubName[MAX_QPATH]; + char limbCapName[MAX_QPATH]; + char stubCapName[MAX_QPATH]; char *limbTagName; char *stubTagName; int newBolt; - int limbBit = (1 << (cent->currentState.modelGhoul2-10)); + int limbBit = (1 << (cent->currentState.modelGhoul2 - 10)); - if (clEnt && (clEnt->torsoBolt & limbBit)) - { //already have this limb missing! + if (clEnt && (clEnt->torsoBolt & limbBit)) { // already have this limb missing! return; } - - if (clEnt && !(clEnt->currentState.eFlags & EF_DEAD)) - { //death flag hasn't made it through yet for the limb owner, we cannot create the limb until he's flagged as dead + if (clEnt && !(clEnt->currentState.eFlags & + EF_DEAD)) { // death flag hasn't made it through yet for the limb owner, we cannot create the limb until he's flagged as dead return; } - if (clEnt && (!BG_InDeathAnim(clEnt->currentState.torsoAnim) || !BG_InDeathAnim(clEnt->pe.torso.animationNumber))) - { //don't make it unless we're in an actual death anim already - if (clEnt->currentState.torsoAnim != BOTH_RIGHTHANDCHOPPEDOFF) - { //exception + if (clEnt && (!BG_InDeathAnim(clEnt->currentState.torsoAnim) || + !BG_InDeathAnim(clEnt->pe.torso.animationNumber))) { // don't make it unless we're in an actual death anim already + if (clEnt->currentState.torsoAnim != BOTH_RIGHTHANDCHOPPEDOFF) { // exception return; } } @@ -1082,133 +967,118 @@ static void CG_General( centity_t *cent ) { cent->bolt4 = -1; cent->trailTime = 0; - if (cent->currentState.modelGhoul2 == G2_MODELPART_HEAD) - { + if (cent->currentState.modelGhoul2 == G2_MODELPART_HEAD) { rotateBone = "cranium"; - Q_strncpyz( limbName , "head", sizeof( limbName ) ); - Q_strncpyz( limbCapName, "head_cap_torso", sizeof( limbCapName ) ); - Q_strncpyz( stubCapName, "torso_cap_head", sizeof( stubCapName ) ); + Q_strncpyz(limbName, "head", sizeof(limbName)); + Q_strncpyz(limbCapName, "head_cap_torso", sizeof(limbCapName)); + Q_strncpyz(stubCapName, "torso_cap_head", sizeof(stubCapName)); limbTagName = "*head_cap_torso"; stubTagName = "*torso_cap_head"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_WAIST) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_WAIST) { - if (clEnt->localAnimIndex <= 1) - { //humanoid/rtrooper + if (clEnt->localAnimIndex <= 1) { // humanoid/rtrooper rotateBone = "thoracic"; - } - else - { + } else { rotateBone = "pelvis"; } - Q_strncpyz( limbName, "torso", sizeof( limbName ) ); - Q_strncpyz( limbCapName, "torso_cap_hips", sizeof( limbCapName ) ); - Q_strncpyz( stubCapName, "hips_cap_torso", sizeof( stubCapName ) ); + Q_strncpyz(limbName, "torso", sizeof(limbName)); + Q_strncpyz(limbCapName, "torso_cap_hips", sizeof(limbCapName)); + Q_strncpyz(stubCapName, "hips_cap_torso", sizeof(stubCapName)); limbTagName = "*torso_cap_hips"; stubTagName = "*hips_cap_torso"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_LARM) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_LARM) { rotateBone = "lradius"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "l_arm", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "torso", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_torso", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_arm", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "l_arm", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "torso", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_torso", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_arm", stubName); limbTagName = "*l_arm_cap_torso"; stubTagName = "*torso_cap_l_arm"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_RARM) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_RARM) { rotateBone = "rradius"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "r_arm", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "torso", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_torso", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_arm", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "r_arm", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "torso", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_torso", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_arm", stubName); limbTagName = "*r_arm_cap_torso"; stubTagName = "*torso_cap_r_arm"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_RHAND) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_RHAND) { rotateBone = "rhand"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "r_hand", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "r_arm", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_r_arm", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_hand", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "r_hand", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "r_arm", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_r_arm", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_hand", stubName); limbTagName = "*r_hand_cap_r_arm"; stubTagName = "*r_arm_cap_r_hand"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_LLEG) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_LLEG) { rotateBone = "ltibia"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "l_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_hips", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_leg", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "l_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_hips", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_leg", stubName); limbTagName = "*l_leg_cap_hips"; stubTagName = "*hips_cap_l_leg"; - } - else if (cent->currentState.modelGhoul2 == G2_MODELPART_RLEG) - { + } else if (cent->currentState.modelGhoul2 == G2_MODELPART_RLEG) { rotateBone = "rtibia"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "r_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_hips", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_leg", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "r_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_hips", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_leg", stubName); limbTagName = "*r_leg_cap_hips"; stubTagName = "*hips_cap_r_leg"; - } - else - {//umm... just default to the right leg, I guess (same as on server) + } else { // umm... just default to the right leg, I guess (same as on server) rotateBone = "rtibia"; - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "r_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( clEnt->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( limbCapName, sizeof( limbCapName ), "%s_cap_hips", limbName ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_leg", stubName ); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "r_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(clEnt->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(limbCapName, sizeof(limbCapName), "%s_cap_hips", limbName); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_leg", stubName); limbTagName = "*r_leg_cap_hips"; stubTagName = "*hips_cap_r_leg"; } - if (clEnt && clEnt->ghoul2) - { - if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), 2)) - { //don't want to bother dealing with a second saber on limbs and stuff, just remove the thing + if (clEnt && clEnt->ghoul2) { + if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), + 2)) { // don't want to bother dealing with a second saber on limbs and stuff, just remove the thing trap->G2API_RemoveGhoul2Model(&(clEnt->ghoul2), 2); } - if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), 3)) - { //turn off jetpack also I suppose + if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), 3)) { // turn off jetpack also I suppose trap->G2API_RemoveGhoul2Model(&(clEnt->ghoul2), 3); } - if (clEnt->localAnimIndex <= 0) - { //humanoid - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "model_root", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, cgs.gameModels, 100, cg.time); - } - else - { - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "model_root", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); + if (clEnt->localAnimIndex <= 0) { // humanoid + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "model_root", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, + 0, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 0, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, + cgs.gameModels, 100, cg.time); + } else { + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "model_root", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, + 0, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); + trap->G2API_SetBoneAngles(clEnt->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + cgs.gameModels, 100, cg.time); } trap->G2API_DuplicateGhoul2Instance(clEnt->ghoul2, ¢->ghoul2); } - if (!cent->ghoul2) - { + if (!cent->ghoul2) { return; } - newBolt = trap->G2API_AddBolt( cent->ghoul2, 0, limbTagName ); - if ( newBolt != -1 ) - { + newBolt = trap->G2API_AddBolt(cent->ghoul2, 0, limbTagName); + if (newBolt != -1) { vec3_t boltOrg, boltAng; trap->G2API_GetBoltMatrix(cent->ghoul2, 0, newBolt, &matrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); @@ -1230,9 +1100,8 @@ static void CG_General( centity_t *cent ) { trap->G2API_SetSurfaceOnOff(clEnt->ghoul2, limbName, 0x00000100); trap->G2API_SetSurfaceOnOff(clEnt->ghoul2, stubCapName, 0); - newBolt = trap->G2API_AddBolt( clEnt->ghoul2, 0, stubTagName ); - if ( newBolt != -1 ) - { + newBolt = trap->G2API_AddBolt(clEnt->ghoul2, 0, stubTagName); + if (newBolt != -1) { vec3_t boltOrg, boltAng; trap->G2API_GetBoltMatrix(clEnt->ghoul2, 0, newBolt, &matrix, clEnt->lerpAngles, clEnt->lerpOrigin, cg.time, cgs.gameModels, clEnt->modelScale); @@ -1243,16 +1112,15 @@ static void CG_General( centity_t *cent ) { trap->FX_PlayEffectID(cgs.effects.mBlasterSmoke, boltOrg, boltAng, -1, -1, qfalse); } - if (cent->currentState.modelGhoul2 == G2_MODELPART_RARM || cent->currentState.modelGhoul2 == G2_MODELPART_RHAND || cent->currentState.modelGhoul2 == G2_MODELPART_WAIST) - { //Cut his weapon holding arm off, so remove the weapon - if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), 1)) - { + if (cent->currentState.modelGhoul2 == G2_MODELPART_RARM || cent->currentState.modelGhoul2 == G2_MODELPART_RHAND || + cent->currentState.modelGhoul2 == G2_MODELPART_WAIST) { // Cut his weapon holding arm off, so remove the weapon + if (trap->G2API_HasGhoul2ModelOnIndex(&(clEnt->ghoul2), 1)) { trap->G2API_RemoveGhoul2Model(&(clEnt->ghoul2), 1); } } - clEnt->torsoBolt |= limbBit; //reinit model after copying limbless one to queue - //This causes issues after respawning.. just keep track of limbs cut/made on server or something. + clEnt->torsoBolt |= limbBit; // reinit model after copying limbless one to queue + // This causes issues after respawning.. just keep track of limbs cut/made on server or something. /* if (cent->currentState.modelGhoul2 == G2_MODELPART_WAIST) { @@ -1268,28 +1136,23 @@ static void CG_General( centity_t *cent ) { */ VectorCopy(cent->lerpOrigin, cent->turAngles); - // return; + // return; } - //Use origin smoothing since dismembered limbs use ExPhys - if (DistanceSquared(cent->turAngles,cent->lerpOrigin)>18000.0f) - { + // Use origin smoothing since dismembered limbs use ExPhys + if (DistanceSquared(cent->turAngles, cent->lerpOrigin) > 18000.0f) { VectorCopy(cent->lerpOrigin, cent->turAngles); } VectorSubtract(cent->lerpOrigin, cent->turAngles, posDif); - for (k=0;k<3;k++) - { - cent->turAngles[k]=(cent->turAngles[k]+posDif[k]*smoothFactor); - cent->lerpOrigin[k]=cent->turAngles[k]; + for (k = 0; k < 3; k++) { + cent->turAngles[k] = (cent->turAngles[k] + posDif[k] * smoothFactor); + cent->lerpOrigin[k] = cent->turAngles[k]; } - if (cent->ghoul2 && cent->bolt4 != -1 && cent->trailTime < cg.time) - { - if ( cent->bolt4 != -1 && - (cent->currentState.pos.trDelta[0] || cent->currentState.pos.trDelta[1] || cent->currentState.pos.trDelta[2]) ) - { + if (cent->ghoul2 && cent->bolt4 != -1 && cent->trailTime < cg.time) { + if (cent->bolt4 != -1 && (cent->currentState.pos.trDelta[0] || cent->currentState.pos.trDelta[1] || cent->currentState.pos.trDelta[2])) { vec3_t boltOrg, boltAng; trap->G2API_GetBoltMatrix(cent->ghoul2, 0, cent->bolt4, &matrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); @@ -1297,8 +1160,7 @@ static void CG_General( centity_t *cent ) { BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, boltOrg); BG_GiveMeVectorFromMatrix(&matrix, NEGATIVE_Y, boltAng); - if (!boltAng[0] && !boltAng[1] && !boltAng[2]) - { + if (!boltAng[0] && !boltAng[1] && !boltAng[2]) { boltAng[1] = 1; } trap->FX_PlayEffectID(cgs.effects.mBlasterSmoke, boltOrg, boltAng, -1, -1, qfalse); @@ -1311,92 +1173,75 @@ static void CG_General( centity_t *cent ) { ent.hModel = 0; } - if (cent->currentState.number >= MAX_CLIENTS && - cent->currentState.activeForcePass == NUM_FORCE_POWERS+1&& - cent->currentState.NPC_class != CLASS_VEHICLE ) - { - vec3_t empAngles; - centity_t *empOwn; + if (cent->currentState.number >= MAX_CLIENTS && cent->currentState.activeForcePass == NUM_FORCE_POWERS + 1 && + cent->currentState.NPC_class != CLASS_VEHICLE) { + vec3_t empAngles; + centity_t *empOwn; empOwn = &cg_entities[cent->currentState.emplacedOwner]; - if (cg.snap->ps.clientNum == empOwn->currentState.number && - !cg.renderingThirdPerson) - { + if (cg.snap->ps.clientNum == empOwn->currentState.number && !cg.renderingThirdPerson) { VectorCopy(cg.refdef.viewangles, empAngles); - } - else - { + } else { VectorCopy(empOwn->lerpAngles, empAngles); } - if (empAngles[PITCH] > 40) - { + if (empAngles[PITCH] > 40) { empAngles[PITCH] = 40; } empAngles[YAW] -= cent->currentState.angles[YAW]; - trap->G2API_SetBoneAngles( cent->ghoul2, 0, "Bone02", empAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_X, POSITIVE_Z, NULL, 0, cg.time); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "Bone02", empAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_X, POSITIVE_Z, NULL, 0, cg.time); } s1 = ¢->currentState; // if set to invisible, skip - if ((!s1->modelindex) && !(trap->G2_HaveWeGhoul2Models(cent->ghoul2))) - { + if ((!s1->modelindex) && !(trap->G2_HaveWeGhoul2Models(cent->ghoul2))) { return; } - if ( ( s1->eFlags & EF_NODRAW ) ) - { + if ((s1->eFlags & EF_NODRAW)) { return; } // set frame - if ( s1->eFlags & EF_SHADER_ANIM ) - { + if (s1->eFlags & EF_SHADER_ANIM) { // Deliberately setting it up so that shader anim will completely override any kind of model animation frame setting. - ent.renderfx|=RF_SETANIMINDEX; + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - } - else - { + } else { ent.frame = s1->frame; } ent.oldframe = ent.frame; ent.backlerp = 0; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + /* + Ghoul2 Insert End + */ + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); - if (cent->currentState.modelGhoul2) - { //If the game says this guy uses a ghoul2 model and the g2 instance handle is null, then initialize it - if (!cent->ghoul2 && !cent->currentState.bolt1) - { + if (cent->currentState.modelGhoul2) { // If the game says this guy uses a ghoul2 model and the g2 instance handle is null, then initialize it + if (!cent->ghoul2 && !cent->currentState.bolt1) { char skinName[MAX_QPATH]; - const char *modelName = CG_ConfigString( CS_MODELS+cent->currentState.modelindex ); + const char *modelName = CG_ConfigString(CS_MODELS + cent->currentState.modelindex); int l; int skin = 0; trap->G2API_InitGhoul2Model(¢->ghoul2, modelName, 0, 0, 0, 0, 0); - if (cent->ghoul2 && trap->G2API_SkinlessModel(cent->ghoul2, 0)) - { //well, you'd never want a skinless model, so try to get his skin... + if (cent->ghoul2 && trap->G2API_SkinlessModel(cent->ghoul2, 0)) { // well, you'd never want a skinless model, so try to get his skin... Q_strncpyz(skinName, modelName, MAX_QPATH); l = strlen(skinName); - while (l > 0 && skinName[l] != '/') - { //parse back to first / + while (l > 0 && skinName[l] != '/') { // parse back to first / l--; } - if (skinName[l] == '/') - { //got it + if (skinName[l] == '/') { // got it l++; skinName[l] = 0; Q_strcat(skinName, MAX_QPATH, "model_default.skin"); @@ -1405,105 +1250,91 @@ Ghoul2 Insert End } trap->G2API_SetSkin(cent->ghoul2, 0, skin, skin); } - } - else if (cent->currentState.bolt1) - { + } else if (cent->currentState.bolt1) { TurretClientRun(cent); } - if (cent->ghoul2) - { //give us a proper radius + if (cent->ghoul2) { // give us a proper radius ent.radius = cent->currentState.g2radius; } } - if (s1->eType == ET_BODY) - { //bodies should have a radius as well + if (s1->eType == ET_BODY) { // bodies should have a radius as well ent.radius = cent->currentState.g2radius; - if (cent->ghoul2) - { //all bodies should already have a ghoul2 instance. Use it to set the torso/head angles to 0. + if (cent->ghoul2) { // all bodies should already have a ghoul2 instance. Use it to set the torso/head angles to 0. cent->lerpAngles[PITCH] = 0; cent->lerpAngles[ROLL] = 0; - trap->G2API_SetBoneAngles(cent->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, cg.time); - trap->G2API_SetBoneAngles(cent->ghoul2, 0, "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, cg.time); - trap->G2API_SetBoneAngles(cent->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(cent->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 100, cg.time); - trap->G2API_SetBoneAngles(cent->ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, cgs.gameModels, 100, cg.time); - } - } - - if (s1->eType == ET_HOLOCRON && s1->modelindex < -100) - { //special render, it's a holocron - //Using actual models now: - ent.hModel = trap->R_RegisterModel(forceHolocronModels[s1->modelindex+128]); - - //Rotate them - VectorCopy( cg.autoAngles, cent->lerpAngles ); - AxisCopy( cg.autoAxis, ent.axis ); - } - else if (!doNotSetModel) - { + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "pelvis", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, + cg.time); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "thoracic", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, 0, + cg.time); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, + 100, cg.time); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.gameModels, + 100, cg.time); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, cgs.gameModels, 100, + cg.time); + } + } + + if (s1->eType == ET_HOLOCRON && s1->modelindex < -100) { // special render, it's a holocron + // Using actual models now: + ent.hModel = trap->R_RegisterModel(forceHolocronModels[s1->modelindex + 128]); + + // Rotate them + VectorCopy(cg.autoAngles, cent->lerpAngles); + AxisCopy(cg.autoAxis, ent.axis); + } else if (!doNotSetModel) { ent.hModel = cgs.gameModels[s1->modelindex]; } // player model if (s1->number == cg.snap->ps.clientNum) { - ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors + ent.renderfx |= RF_THIRD_PERSON; // only draw from mirrors } // convert angles to axis - AnglesToAxis( cent->lerpAngles, ent.axis ); + AnglesToAxis(cent->lerpAngles, ent.axis); - if (cent->currentState.iModelScale) - { //if the server says we have a custom scale then set it now. - cent->modelScale[0] = cent->modelScale[1] = cent->modelScale[2] = cent->currentState.iModelScale/100.0f; + if (cent->currentState.iModelScale) { // if the server says we have a custom scale then set it now. + cent->modelScale[0] = cent->modelScale[1] = cent->modelScale[2] = cent->currentState.iModelScale / 100.0f; VectorCopy(cent->modelScale, ent.modelScale); ScaleModelAxis(&ent); - } - else - { + } else { VectorClear(cent->modelScale); } - if ( cent->currentState.time > cg.time && cent->currentState.weapon == WP_EMPLACED_GUN ) - { + if (cent->currentState.time > cg.time && cent->currentState.weapon == WP_EMPLACED_GUN) { // make the gun pulse red to warn about it exploding - val = (1.0f - (float)(cent->currentState.time - cg.time) / 3200.0f ) * 0.3f; + val = (1.0f - (float)(cent->currentState.time - cg.time) / 3200.0f) * 0.3f; - ent.customShader = trap->R_RegisterShader( "gfx/effects/turretflashdie" ); - ent.shaderRGBA[0] = (sin( cg.time * 0.04f ) * val * 0.4f + val) * 255; + ent.customShader = trap->R_RegisterShader("gfx/effects/turretflashdie"); + ent.shaderRGBA[0] = (sin(cg.time * 0.04f) * val * 0.4f + val) * 255; ent.shaderRGBA[1] = ent.shaderRGBA[2] = 0; ent.shaderRGBA[3] = 100; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); ent.customShader = 0; - } - else if ( cent->currentState.time == -1 && cent->currentState.weapon == WP_EMPLACED_GUN) - { - ent.customShader = trap->R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg.tga" ); - //trap->R_AddRefEntityToScene( &ent ); + } else if (cent->currentState.time == -1 && cent->currentState.weapon == WP_EMPLACED_GUN) { + ent.customShader = trap->R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg.tga"); + // trap->R_AddRefEntityToScene( &ent ); } - if ((cent->currentState.eFlags & EF_DISINTEGRATION) && cent->currentState.eType == ET_BODY) - { - if (!cent->dustTrailTime) - { + if ((cent->currentState.eFlags & EF_DISINTEGRATION) && cent->currentState.eType == ET_BODY) { + if (!cent->dustTrailTime) { cent->dustTrailTime = cg.time; } CG_Disintegration(cent, &ent); return; - } - else if (cent->currentState.eType == ET_BODY) - { - if (cent->bodyFadeTime > cg.time) - { + } else if (cent->currentState.eType == ET_BODY) { + if (cent->bodyFadeTime > cg.time) { qboolean lightSide = (cent->teamPowerType != 0) ? qtrue : qfalse; vec3_t hitLoc, tempAng; float tempLength; int curTimeDif = ((cg.time + 60000) - cent->bodyFadeTime); - int tMult = curTimeDif*0.08; + int tMult = curTimeDif * 0.08; ent.renderfx |= RF_FORCE_ENT_ALPHA; @@ -1514,149 +1345,118 @@ Ghoul2 Insert End } */ - if (curTimeDif*0.1 > 254) - { + if (curTimeDif * 0.1 > 254) { ent.shaderRGBA[3] = 0; - } - else - { + } else { ent.shaderRGBA[3] = (254 - tMult); } - if (ent.shaderRGBA[3] >= 1) - { //add the transparent body section - trap->R_AddRefEntityToScene (&ent); + if (ent.shaderRGBA[3] >= 1) { // add the transparent body section + trap->R_AddRefEntityToScene(&ent); } ent.renderfx &= ~RF_FORCE_ENT_ALPHA; ent.renderfx |= RF_RGB_TINT; - if (tMult > 200) - { //begin the disintegration effect + if (tMult > 200) { // begin the disintegration effect ent.shaderRGBA[3] = 200; - if (!cent->dustTrailTime) - { + if (!cent->dustTrailTime) { cent->dustTrailTime = cg.time; - if (lightSide) - { - trap->S_StartSound ( NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/force/see.wav") ); - } - else - { - trap->S_StartSound ( NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/force/lightning") ); + if (lightSide) { + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/force/see.wav")); + } else { + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/force/lightning")); } } ent.endTime = cent->dustTrailTime; ent.renderfx |= RF_DISINTEGRATE2; - } - else - { //set the alpha on the to-be-disintegrated layer + } else { // set the alpha on the to-be-disintegrated layer ent.shaderRGBA[3] = tMult; - if (ent.shaderRGBA[3] < 1) - { + if (ent.shaderRGBA[3] < 1) { ent.shaderRGBA[3] = 1; } } - //Set everything up on the disint ref + // Set everything up on the disint ref ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = ent.shaderRGBA[3]; VectorCopy(cent->lerpOrigin, hitLoc); - VectorSubtract( hitLoc, ent.origin, ent.oldorigin ); + VectorSubtract(hitLoc, ent.origin, ent.oldorigin); - tempLength = VectorNormalize( ent.oldorigin ); - vectoangles( ent.oldorigin, tempAng ); + tempLength = VectorNormalize(ent.oldorigin); + vectoangles(ent.oldorigin, tempAng); tempAng[YAW] -= cent->lerpAngles[YAW]; - AngleVectors( tempAng, ent.oldorigin, NULL, NULL ); - VectorScale( ent.oldorigin, tempLength, ent.oldorigin ); + AngleVectors(tempAng, ent.oldorigin, NULL, NULL); + VectorScale(ent.oldorigin, tempLength, ent.oldorigin); - if (lightSide) - { //might be temporary, dunno. + if (lightSide) { // might be temporary, dunno. ent.customShader = cgs.media.playerShieldDamage; - } - else - { + } else { ent.customShader = cgs.media.redSaberGlowShader; } - //slowly move the glowing part upward, out of the fading body + // slowly move the glowing part upward, out of the fading body /* cent->bodyHeight += 0.4f; ent.origin[2] = cent->bodyHeight; */ - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); ent.renderfx &= ~RF_DISINTEGRATE2; ent.customShader = 0; - if (curTimeDif < 3400) - { - if (lightSide) - { - if (curTimeDif < 2200) - { //probably temporary - trap->S_StartSound ( NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ) ); + if (curTimeDif < 3400) { + if (lightSide) { + if (curTimeDif < 2200) { // probably temporary + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/saber/saberhum1.wav")); } - } - else - { //probably temporary as well + } else { // probably temporary as well ent.renderfx |= RF_RGB_TINT; ent.shaderRGBA[0] = 255; ent.shaderRGBA[1] = ent.shaderRGBA[2] = 0; ent.shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { ent.customShader = cgs.media.electricBodyShader; - } - else - { + } else { ent.customShader = cgs.media.electricBody2Shader; } - if ( Q_flrand(0.0f, 1.0f) > 0.9f ) - { - trap->S_StartSound ( NULL, cent->currentState.number, CHAN_AUTO, cgs.media.crackleSound ); + if (Q_flrand(0.0f, 1.0f) > 0.9f) { + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, cgs.media.crackleSound); } - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } } return; - } - else - { + } else { cent->dustTrailTime = 0; } } - if (cent->currentState.modelGhoul2 && - !ent.ghoul2 && - !ent.hModel) - { + if (cent->currentState.modelGhoul2 && !ent.ghoul2 && !ent.hModel) { return; } // add to refresh list - trap->R_AddRefEntityToScene (&ent); + trap->R_AddRefEntityToScene(&ent); - if (cent->bolt3 == 999) - { //this is an in-flight saber being rendered manually + if (cent->bolt3 == 999) { // this is an in-flight saber being rendered manually vec3_t org; float wv; int i; addspriteArgStruct_t fxSArgs; - //refEntity_t sRef; - //memcpy( &sRef, &ent, sizeof( sRef ) ); + // refEntity_t sRef; + // memcpy( &sRef, &ent, sizeof( sRef ) ); ent.customShader = cgs.media.solidWhite; ent.renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.003f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.003f) * 0.08f + 0.1f; ent.shaderRGBA[0] = wv * 255; ent.shaderRGBA[1] = wv * 255; ent.shaderRGBA[2] = wv * 0; - trap->R_AddRefEntityToScene (&ent); + trap->R_AddRefEntityToScene(&ent); - for ( i = -4; i < 10; i += 1 ) - { - VectorMA( ent.origin, -i, ent.axis[2], org ); + for (i = -4; i < 10; i += 1) { + VectorMA(ent.origin, -i, ent.axis[2], org); VectorCopy(org, fxSArgs.origin); VectorClear(fxSArgs.vel); @@ -1671,49 +1471,38 @@ Ghoul2 Insert End fxSArgs.shader = cgs.media.yellowDroppedSaberShader; fxSArgs.flags = 0x08000000; - //trap->FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); + // trap->FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); trap->FX_AddSprite(&fxSArgs); } - } - else if (cent->currentState.trickedentindex3) - { //holocron special effects + } else if (cent->currentState.trickedentindex3) { // holocron special effects vec3_t org; float wv; addspriteArgStruct_t fxSArgs; - //refEntity_t sRef; - //memcpy( &sRef, &ent, sizeof( sRef ) ); + // refEntity_t sRef; + // memcpy( &sRef, &ent, sizeof( sRef ) ); ent.customShader = cgs.media.solidWhite; ent.renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.005f ) * 0.08f + 0.1f; //* 0.08f + 0.1f; + wv = sin(cg.time * 0.005f) * 0.08f + 0.1f; //* 0.08f + 0.1f; - if (cent->currentState.trickedentindex3 == 1) - { //dark - ent.shaderRGBA[0] = wv*255; + if (cent->currentState.trickedentindex3 == 1) { // dark + ent.shaderRGBA[0] = wv * 255; ent.shaderRGBA[1] = 0; ent.shaderRGBA[2] = 0; - } - else if (cent->currentState.trickedentindex3 == 2) - { //light - ent.shaderRGBA[0] = wv*255; - ent.shaderRGBA[1] = wv*255; - ent.shaderRGBA[2] = wv*255; - } - else - { //neutral - if ((s1->modelindex+128) == FP_SABER_OFFENSE || - (s1->modelindex+128) == FP_SABER_DEFENSE || - (s1->modelindex+128) == FP_SABERTHROW) - { //saber power + } else if (cent->currentState.trickedentindex3 == 2) { // light + ent.shaderRGBA[0] = wv * 255; + ent.shaderRGBA[1] = wv * 255; + ent.shaderRGBA[2] = wv * 255; + } else { // neutral + if ((s1->modelindex + 128) == FP_SABER_OFFENSE || (s1->modelindex + 128) == FP_SABER_DEFENSE || + (s1->modelindex + 128) == FP_SABERTHROW) { // saber power ent.shaderRGBA[0] = 0; - ent.shaderRGBA[1] = wv*255; + ent.shaderRGBA[1] = wv * 255; ent.shaderRGBA[2] = 0; - } - else - { + } else { ent.shaderRGBA[0] = 0; - ent.shaderRGBA[1] = wv*255; - ent.shaderRGBA[2] = wv*255; + ent.shaderRGBA[1] = wv * 255; + ent.shaderRGBA[2] = wv * 255; } } @@ -1724,36 +1513,33 @@ Ghoul2 Insert End ent.origin[2] -= 2; ScaleModelAxis(&ent); - trap->R_AddRefEntityToScene (&ent); + trap->R_AddRefEntityToScene(&ent); - VectorMA( ent.origin, 1, ent.axis[2], org ); + VectorMA(ent.origin, 1, ent.axis[2], org); org[2] += 18; - wv = sin( cg.time * 0.002f ) * 0.08f + 0.1f; //* 0.08f + 0.1f; + wv = sin(cg.time * 0.002f) * 0.08f + 0.1f; //* 0.08f + 0.1f; VectorCopy(org, fxSArgs.origin); VectorClear(fxSArgs.vel); VectorClear(fxSArgs.accel); - fxSArgs.scale = wv*120;//16.0f; - fxSArgs.dscale = wv*120;//16.0f; - fxSArgs.sAlpha = wv*12; - fxSArgs.eAlpha = wv*12; + fxSArgs.scale = wv * 120; // 16.0f; + fxSArgs.dscale = wv * 120; // 16.0f; + fxSArgs.sAlpha = wv * 12; + fxSArgs.eAlpha = wv * 12; fxSArgs.rotation = 0.0f; fxSArgs.bounce = 0.0f; fxSArgs.life = 1.0f; - fxSArgs.flags = 0x08000000|0x00000001; + fxSArgs.flags = 0x08000000 | 0x00000001; - if (cent->currentState.trickedentindex3 == 1) - { //dark + if (cent->currentState.trickedentindex3 == 1) { // dark fxSArgs.sAlpha *= 3; fxSArgs.eAlpha *= 3; fxSArgs.shader = cgs.media.redSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else if (cent->currentState.trickedentindex3 == 2) - { //light + } else if (cent->currentState.trickedentindex3 == 2) { // light fxSArgs.sAlpha *= 1.5; fxSArgs.eAlpha *= 1.5; fxSArgs.shader = cgs.media.redSaberGlowShader; @@ -1762,20 +1548,14 @@ Ghoul2 Insert End trap->FX_AddSprite(&fxSArgs); fxSArgs.shader = cgs.media.blueSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else - { //neutral - if ((s1->modelindex+128) == FP_SABER_OFFENSE || - (s1->modelindex+128) == FP_SABER_DEFENSE || - (s1->modelindex+128) == FP_SABERTHROW) - { //saber power + } else { // neutral + if ((s1->modelindex + 128) == FP_SABER_OFFENSE || (s1->modelindex + 128) == FP_SABER_DEFENSE || + (s1->modelindex + 128) == FP_SABERTHROW) { // saber power fxSArgs.sAlpha *= 1.5; fxSArgs.eAlpha *= 1.5; fxSArgs.shader = cgs.media.greenSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else - { + } else { fxSArgs.sAlpha *= 0.5; fxSArgs.eAlpha *= 0.5; fxSArgs.shader = cgs.media.greenSaberGlowShader; @@ -1786,47 +1566,42 @@ Ghoul2 Insert End } } - if ( cent->currentState.time == -1 && cent->currentState.weapon == WP_TRIP_MINE && (cent->currentState.eFlags & EF_FIRING) ) - { //if force sight is active, render the laser multiple times up to the force sight level to increase visibility - if (cent->currentState.bolt2 == 1) - { - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward + if (cent->currentState.time == -1 && cent->currentState.weapon == WP_TRIP_MINE && + (cent->currentState.eFlags & + EF_FIRING)) { // if force sight is active, render the laser multiple times up to the force sight level to increase visibility + if (cent->currentState.bolt2 == 1) { + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward beamID = cgs.effects.tripmineGlowFX; - trap->FX_PlayEffectID( beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse ); - } - else - { + trap->FX_PlayEffectID(beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse); + } else { int i = 0; - VectorMA( ent.origin, 6.6f, ent.axis[0], beamOrg );// forward + VectorMA(ent.origin, 6.6f, ent.axis[0], beamOrg); // forward beamID = cgs.effects.tripmineLaserFX; - if (cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) - { + if (cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) { i = cg.snap->ps.fd.forcePowerLevel[FP_SEE]; - while (i > 0) - { - trap->FX_PlayEffectID( beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse ); - trap->FX_PlayEffectID( beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse ); + while (i > 0) { + trap->FX_PlayEffectID(beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse); + trap->FX_PlayEffectID(beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse); i--; } } - trap->FX_PlayEffectID( beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse ); + trap->FX_PlayEffectID(beamID, beamOrg, cent->currentState.pos.trDelta, -1, -1, qfalse); } } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - if (debugBB.integer) - { + if (debugBB.integer) { CG_CreateBBRefEnts(s1, cent->lerpOrigin); } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ } /* @@ -1836,43 +1611,34 @@ CG_Speaker Speaker entities can automatically play sounds ================== */ -static void CG_Speaker( centity_t *cent ) { - if (cent->currentState.trickedentindex) - { +static void CG_Speaker(centity_t *cent) { + if (cent->currentState.trickedentindex) { CG_S_StopLoopingSound(cent->currentState.number, -1); } - if ( ! cent->currentState.clientNum ) { // FIXME: use something other than clientNum... - return; // not auto triggering + if (!cent->currentState.clientNum) { // FIXME: use something other than clientNum... + return; // not auto triggering } - if ( cg.time < cent->miscTime ) { + if (cg.time < cent->miscTime) { return; } - trap->S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.gameSounds[cent->currentState.eventParm] ); + trap->S_StartSound(NULL, cent->currentState.number, CHAN_ITEM, cgs.gameSounds[cent->currentState.eventParm]); // ent->s.frame = ent->wait * 10; // ent->s.clientNum = ent->random * 10; cent->miscTime = cg.time + cent->currentState.frame * 100 + cent->currentState.clientNum * 100 * Q_flrand(-1.0f, 1.0f); } -qboolean CG_GreyItem(int type, int tag, int plSide) -{ - if (type == IT_POWERUP && - (tag == PW_FORCE_ENLIGHTENED_LIGHT || tag == PW_FORCE_ENLIGHTENED_DARK)) - { - if (plSide == FORCE_LIGHTSIDE) - { - if (tag == PW_FORCE_ENLIGHTENED_DARK) - { +qboolean CG_GreyItem(int type, int tag, int plSide) { + if (type == IT_POWERUP && (tag == PW_FORCE_ENLIGHTENED_LIGHT || tag == PW_FORCE_ENLIGHTENED_DARK)) { + if (plSide == FORCE_LIGHTSIDE) { + if (tag == PW_FORCE_ENLIGHTENED_DARK) { return qtrue; } - } - else if (plSide == FORCE_DARKSIDE) - { - if (tag == PW_FORCE_ENLIGHTENED_LIGHT) - { + } else if (plSide == FORCE_DARKSIDE) { + if (tag == PW_FORCE_ENLIGHTENED_LIGHT) { return qtrue; } } @@ -1886,39 +1652,34 @@ qboolean CG_GreyItem(int type, int tag, int plSide) CG_Item ================== */ -static void CG_Item( centity_t *cent ) { - refEntity_t ent; - entityState_t *es; - gitem_t *item; - int msec; - float scale; - weaponInfo_t *wi; +static void CG_Item(centity_t *cent) { + refEntity_t ent; + entityState_t *es; + gitem_t *item; + int msec; + float scale; + weaponInfo_t *wi; es = ¢->currentState; - if ( es->modelindex >= bg_numItems ) { - trap->Error( ERR_DROP, "Bad item index %i on entity", es->modelindex ); + if (es->modelindex >= bg_numItems) { + trap->Error(ERR_DROP, "Bad item index %i on entity", es->modelindex); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - if ((es->eFlags & EF_NODRAW) && (es->eFlags & EF_ITEMPLACEHOLDER)) - { + if ((es->eFlags & EF_NODRAW) && (es->eFlags & EF_ITEMPLACEHOLDER)) { es->eFlags &= ~EF_NODRAW; } - if ( !es->modelindex ) - { + if (!es->modelindex) { return; } - item = &bg_itemlist[ es->modelindex ]; + item = &bg_itemlist[es->modelindex]; - if ((item->giType == IT_WEAPON || item->giType == IT_POWERUP) && - !(cent->currentState.eFlags & EF_DROPPEDWEAPON) && - !cg_simpleItems.integer) - { + if ((item->giType == IT_WEAPON || item->giType == IT_POWERUP) && !(cent->currentState.eFlags & EF_DROPPEDWEAPON) && !cg_simpleItems.integer) { vec3_t uNorm; qboolean doGrey; @@ -1926,18 +1687,17 @@ Ghoul2 Insert Start uNorm[2] = 1; - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); ent.customShader = 0; VectorCopy(cent->lerpOrigin, ent.origin); - VectorCopy( cent->currentState.angles, cent->lerpAngles ); + VectorCopy(cent->currentState.angles, cent->lerpAngles); AnglesToAxis(cent->lerpAngles, ent.axis); ent.hModel = cgs.media.itemHoloModel; doGrey = CG_GreyItem(item->giType, item->giTag, cg.snap->ps.fd.forceSide); - if (doGrey) - { + if (doGrey) { ent.renderfx |= RF_RGB_TINT; ent.shaderRGBA[0] = 150; @@ -1947,25 +1707,23 @@ Ghoul2 Insert Start trap->R_AddRefEntityToScene(&ent); - if (!doGrey) - { + if (!doGrey) { trap->FX_PlayEffectID(cgs.effects.itemCone, ent.origin, uNorm, -1, -1, qfalse); } } // if set to invisible, skip - if ( ( es->eFlags & EF_NODRAW ) ) - { + if ((es->eFlags & EF_NODRAW)) { return; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - if ( cg_simpleItems.integer && item->giType != IT_TEAM ) { - memset( &ent, 0, sizeof( ent ) ); + if (cg_simpleItems.integer && item->giType != IT_TEAM) { + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); ent.radius = 14; ent.customShader = cg_items[es->modelindex].icon; ent.shaderRGBA[0] = 255; @@ -1974,41 +1732,32 @@ Ghoul2 Insert End ent.origin[2] += 16; - if (item->giType != IT_POWERUP || item->giTag != PW_FORCE_BOON) - { + if (item->giType != IT_POWERUP || item->giTag != PW_FORCE_BOON) { ent.renderfx |= RF_FORCE_ENT_ALPHA; } - if ( es->eFlags & EF_ITEMPLACEHOLDER ) - { - if (item->giType == IT_POWERUP && item->giTag == PW_FORCE_BOON) - { + if (es->eFlags & EF_ITEMPLACEHOLDER) { + if (item->giType == IT_POWERUP && item->giTag == PW_FORCE_BOON) { return; } ent.shaderRGBA[0] = 200; ent.shaderRGBA[1] = 200; ent.shaderRGBA[2] = 200; - ent.shaderRGBA[3] = 150 + sin(cg.time*0.01)*30; - } - else - { + ent.shaderRGBA[3] = 150 + sin(cg.time * 0.01) * 30; + } else { ent.shaderRGBA[3] = 255; } - if (CG_GreyItem(item->giType, item->giTag, cg.snap->ps.fd.forceSide)) - { + if (CG_GreyItem(item->giType, item->giTag, cg.snap->ps.fd.forceSide)) { ent.shaderRGBA[0] = 100; ent.shaderRGBA[1] = 100; ent.shaderRGBA[2] = 100; ent.shaderRGBA[3] = 200; - if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) - { + if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) { ent.customShader = trap->R_RegisterShader("gfx/misc/mp_light_enlight_disable"); - } - else - { + } else { ent.customShader = trap->R_RegisterShader("gfx/misc/mp_dark_enlight_disable"); } } @@ -2016,61 +1765,45 @@ Ghoul2 Insert End return; } - if ((item->giType == IT_WEAPON || item->giType == IT_POWERUP) && - !(cent->currentState.eFlags & EF_DROPPEDWEAPON)) - { + if ((item->giType == IT_WEAPON || item->giType == IT_POWERUP) && !(cent->currentState.eFlags & EF_DROPPEDWEAPON)) { cent->lerpOrigin[2] += 16; } - if ((!(cent->currentState.eFlags & EF_DROPPEDWEAPON) || item->giType == IT_POWERUP) && - (item->giType == IT_WEAPON || item->giType == IT_POWERUP)) - { + if ((!(cent->currentState.eFlags & EF_DROPPEDWEAPON) || item->giType == IT_POWERUP) && (item->giType == IT_WEAPON || item->giType == IT_POWERUP)) { // items bob up and down continuously scale = 0.005 + cent->currentState.number * 0.00001; - cent->lerpOrigin[2] += 4 + cos( ( cg.time + 1000 ) * scale ) * 4; - } - else - { - if (item->giType == IT_HOLDABLE) - { - if (item->giTag == HI_SEEKER) - { + cent->lerpOrigin[2] += 4 + cos((cg.time + 1000) * scale) * 4; + } else { + if (item->giType == IT_HOLDABLE) { + if (item->giTag == HI_SEEKER) { cent->lerpOrigin[2] += 5; } - if (item->giTag == HI_SHIELD) - { + if (item->giTag == HI_SHIELD) { cent->lerpOrigin[2] += 2; } - if (item->giTag == HI_BINOCULARS) - { + if (item->giTag == HI_BINOCULARS) { cent->lerpOrigin[2] += 2; } } - if (item->giType == IT_HEALTH) - { + if (item->giType == IT_HEALTH) { cent->lerpOrigin[2] += 2; } - if (item->giType == IT_ARMOR) - { - if (item->quantity == 100) - { + if (item->giType == IT_ARMOR) { + if (item->quantity == 100) { cent->lerpOrigin[2] += 7; } } } - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); - if ( (!(cent->currentState.eFlags & EF_DROPPEDWEAPON) || item->giType == IT_POWERUP) && - (item->giType == IT_WEAPON || item->giType == IT_POWERUP) ) - { //only weapons and powerups rotate now + if ((!(cent->currentState.eFlags & EF_DROPPEDWEAPON) || item->giType == IT_POWERUP) && + (item->giType == IT_WEAPON || item->giType == IT_POWERUP)) { // only weapons and powerups rotate now // autorotate at one of two speeds - VectorCopy( cg.autoAngles, cent->lerpAngles ); - AxisCopy( cg.autoAxis, ent.axis ); - } - else - { - VectorCopy( cent->currentState.angles, cent->lerpAngles ); + VectorCopy(cg.autoAngles, cent->lerpAngles); + AxisCopy(cg.autoAxis, ent.axis); + } else { + VectorCopy(cent->currentState.angles, cent->lerpAngles); AnglesToAxis(cent->lerpAngles, ent.axis); } @@ -2078,32 +1811,19 @@ Ghoul2 Insert End // the weapons have their origin where they attatch to player // models, so we need to offset them or they will rotate // eccentricly - if (!(cent->currentState.eFlags & EF_DROPPEDWEAPON)) - { - if ( item->giType == IT_WEAPON ) { + if (!(cent->currentState.eFlags & EF_DROPPEDWEAPON)) { + if (item->giType == IT_WEAPON) { wi = &cg_weapons[item->giTag]; - cent->lerpOrigin[0] -= - wi->weaponMidpoint[0] * ent.axis[0][0] + - wi->weaponMidpoint[1] * ent.axis[1][0] + - wi->weaponMidpoint[2] * ent.axis[2][0]; - cent->lerpOrigin[1] -= - wi->weaponMidpoint[0] * ent.axis[0][1] + - wi->weaponMidpoint[1] * ent.axis[1][1] + - wi->weaponMidpoint[2] * ent.axis[2][1]; - cent->lerpOrigin[2] -= - wi->weaponMidpoint[0] * ent.axis[0][2] + - wi->weaponMidpoint[1] * ent.axis[1][2] + - wi->weaponMidpoint[2] * ent.axis[2][2]; - - cent->lerpOrigin[2] += 8; // an extra height boost + cent->lerpOrigin[0] -= wi->weaponMidpoint[0] * ent.axis[0][0] + wi->weaponMidpoint[1] * ent.axis[1][0] + wi->weaponMidpoint[2] * ent.axis[2][0]; + cent->lerpOrigin[1] -= wi->weaponMidpoint[0] * ent.axis[0][1] + wi->weaponMidpoint[1] * ent.axis[1][1] + wi->weaponMidpoint[2] * ent.axis[2][1]; + cent->lerpOrigin[2] -= wi->weaponMidpoint[0] * ent.axis[0][2] + wi->weaponMidpoint[1] * ent.axis[1][2] + wi->weaponMidpoint[2] * ent.axis[2][2]; + + cent->lerpOrigin[2] += 8; // an extra height boost } - } - else - { + } else { wi = &cg_weapons[item->giTag]; - switch(item->giTag) - { + switch (item->giTag) { case WP_BLASTER: cent->lerpOrigin[2] -= 12; break; @@ -2141,17 +1861,17 @@ Ghoul2 Insert End } ent.hModel = cg_items[es->modelindex].models[0]; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ ent.ghoul2 = cg_items[es->modelindex].g2Models[0]; ent.radius = cg_items[es->modelindex].radius[0]; - VectorCopy (cent->lerpAngles, ent.angles); -/* -Ghoul2 Insert End -*/ - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); + VectorCopy(cent->lerpAngles, ent.angles); + /* + Ghoul2 Insert End + */ + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); ent.nonNormalizedAxes = qfalse; @@ -2159,8 +1879,7 @@ Ghoul2 Insert End msec = cg.time - cent->miscTime; - if (CG_GreyItem(item->giType, item->giTag, cg.snap->ps.fd.forceSide)) - { + if (CG_GreyItem(item->giType, item->giTag, cg.snap->ps.fd.forceSide)) { ent.renderfx |= RF_RGB_TINT; ent.shaderRGBA[0] = 150; @@ -2171,22 +1890,19 @@ Ghoul2 Insert End ent.shaderRGBA[3] = 200; - if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) - { + if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) { ent.customShader = trap->R_RegisterShader("gfx/misc/mp_light_enlight_disable"); - } - else - { + } else { ent.customShader = trap->R_RegisterShader("gfx/misc/mp_dark_enlight_disable"); } - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); return; } - if ( es->eFlags & EF_ITEMPLACEHOLDER ) // item has been picked up + if (es->eFlags & EF_ITEMPLACEHOLDER) // item has been picked up { - if ( es->eFlags & EF_DEAD ) // if item had been droped, don't show at all + if (es->eFlags & EF_DEAD) // if item had been droped, don't show at all return; ent.renderfx |= RF_RGB_TINT; @@ -2197,33 +1913,31 @@ Ghoul2 Insert End } // increase the size of the weapons when they are presented as items - if ( item->giType == IT_WEAPON ) { - VectorScale( ent.axis[0], 1.5, ent.axis[0] ); - VectorScale( ent.axis[1], 1.5, ent.axis[1] ); - VectorScale( ent.axis[2], 1.5, ent.axis[2] ); + if (item->giType == IT_WEAPON) { + VectorScale(ent.axis[0], 1.5, ent.axis[0]); + VectorScale(ent.axis[1], 1.5, ent.axis[1]); + VectorScale(ent.axis[2], 1.5, ent.axis[2]); ent.nonNormalizedAxes = qtrue; - //trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, cgs.media.weaponHoverSound ); + // trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, cgs.media.weaponHoverSound ); } - if (!(cent->currentState.eFlags & EF_DROPPEDWEAPON) && - (item->giType == IT_WEAPON || item->giType == IT_POWERUP)) - { + if (!(cent->currentState.eFlags & EF_DROPPEDWEAPON) && (item->giType == IT_WEAPON || item->giType == IT_POWERUP)) { ent.renderfx |= RF_MINLIGHT; } - if (item->giType != IT_TEAM && msec >= 0 && msec < ITEM_SCALEUP_TIME && !(es->eFlags & EF_ITEMPLACEHOLDER) && !(es->eFlags & EF_DROPPEDWEAPON)) - { // if just respawned, fade in, but don't do this for flags. + if (item->giType != IT_TEAM && msec >= 0 && msec < ITEM_SCALEUP_TIME && !(es->eFlags & EF_ITEMPLACEHOLDER) && + !(es->eFlags & EF_DROPPEDWEAPON)) { // if just respawned, fade in, but don't do this for flags. float alpha; int a; alpha = (float)msec / ITEM_SCALEUP_TIME; a = alpha * 255.0; if (a <= 0) - a=1; + a = 1; ent.shaderRGBA[3] = a; - if (item->giType != IT_POWERUP || item->giTag != PW_FORCE_BOON) - { //boon model uses a different blending mode for the sprite inside and doesn't look proper with this method + if (item->giType != IT_POWERUP || + item->giTag != PW_FORCE_BOON) { // boon model uses a different blending mode for the sprite inside and doesn't look proper with this method ent.renderfx |= RF_FORCE_ENT_ALPHA; } trap->R_AddRefEntityToScene(&ent); @@ -2233,15 +1947,15 @@ Ghoul2 Insert End // Now draw the static shader over it. // Alpha in over half the time, out over half. - //alpha = sin(M_PI*alpha); + // alpha = sin(M_PI*alpha); a = alpha * 255.0; a = 255 - a; if (a <= 0) - a=1; + a = 1; if (a > 255) - a=255; + a = 255; ent.customShader = cgs.media.itemRespawningRezOut; @@ -2267,13 +1981,9 @@ Ghoul2 Insert End ent.shaderRGBA[1] = 200; ent.shaderRGBA[2] = 85; - trap->R_AddRefEntityToScene( &ent ); - } - else - { // add to refresh list -- normal item - if (item->giType == IT_TEAM && - (item->giTag == PW_REDFLAG || item->giTag == PW_BLUEFLAG)) - { + trap->R_AddRefEntityToScene(&ent); + } else { // add to refresh list -- normal item + if (item->giType == IT_TEAM && (item->giTag == PW_REDFLAG || item->giTag == PW_BLUEFLAG)) { ent.modelScale[0] = 0.7f; ent.modelScale[1] = 0.7f; ent.modelScale[2] = 0.7f; @@ -2282,7 +1992,7 @@ Ghoul2 Insert End trap->R_AddRefEntityToScene(&ent); } - //rww - As far as I can see, this is useless. + // rww - As far as I can see, this is useless. /* if ( item->giType == IT_WEAPON && wi->barrelModel ) { refEntity_t barrel; @@ -2307,24 +2017,20 @@ Ghoul2 Insert End */ // accompanying rings / spheres for powerups - if ( !cg_simpleItems.integer ) - { + if (!cg_simpleItems.integer) { vec3_t spinAngles; - VectorClear( spinAngles ); + VectorClear(spinAngles); - if ( item->giType == IT_HEALTH || item->giType == IT_POWERUP ) - { - if ( ( ent.hModel = cg_items[es->modelindex].models[1] ) != 0 ) - { - if ( item->giType == IT_POWERUP ) - { + if (item->giType == IT_HEALTH || item->giType == IT_POWERUP) { + if ((ent.hModel = cg_items[es->modelindex].models[1]) != 0) { + if (item->giType == IT_POWERUP) { ent.origin[2] += 12; - spinAngles[1] = ( cg.time & 1023 ) * 360 / -1024.0f; + spinAngles[1] = (cg.time & 1023) * 360 / -1024.0f; } - AnglesToAxis( spinAngles, ent.axis ); + AnglesToAxis(spinAngles, ent.axis); - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } } } @@ -2332,24 +2038,21 @@ Ghoul2 Insert End //============================================================================ -void CG_CreateDistortionTrailPart(centity_t *cent, float scale, vec3_t pos) -{ +void CG_CreateDistortionTrailPart(centity_t *cent, float scale, vec3_t pos) { refEntity_t ent; vec3_t ang; float vLen; - if (!cg_renderToTextureFX.integer) - { + if (!cg_renderToTextureFX.integer) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); - VectorCopy( pos, ent.origin ); + VectorCopy(pos, ent.origin); VectorSubtract(ent.origin, cg.refdef.vieworg, ent.axis[0]); vLen = VectorLength(ent.axis[0]); - if (VectorNormalize(ent.axis[0]) <= 0.1f) - { // Entity is right on vieworg. quit. + if (VectorNormalize(ent.axis[0]) <= 0.1f) { // Entity is right on vieworg. quit. return; } @@ -2357,46 +2060,39 @@ void CG_CreateDistortionTrailPart(centity_t *cent, float scale, vec3_t pos) ang[PITCH] += 90.0f; AnglesToAxis(ang, ent.axis); - //radius must be a power of 2, and is the actual captured texture size - if (vLen < 512) - { + // radius must be a power of 2, and is the actual captured texture size + if (vLen < 512) { ent.radius = 256; - } - else if (vLen < 1024) - { + } else if (vLen < 1024) { ent.radius = 128; - } - else if (vLen < 2048) - { + } else if (vLen < 2048) { ent.radius = 64; - } - else - { + } else { ent.radius = 32; } ent.modelScale[0] = scale; ent.modelScale[1] = scale; - ent.modelScale[2] = scale*16.0f; + ent.modelScale[2] = scale * 16.0f; ScaleModelAxis(&ent); ent.hModel = trap->R_RegisterModel("models/weapons2/merr_sonn/trailmodel.md3"); - ent.customShader = cgs.media.itemRespawningRezOut;//cgs.media.cloakedShader;//cgs.media.halfShieldShader; + ent.customShader = cgs.media.itemRespawningRezOut; // cgs.media.cloakedShader;//cgs.media.halfShieldShader; #if 1 - ent.renderfx = (RF_DISTORTION|RF_FORCE_ENT_ALPHA); + ent.renderfx = (RF_DISTORTION | RF_FORCE_ENT_ALPHA); ent.shaderRGBA[0] = 255.0f; ent.shaderRGBA[1] = 255.0f; ent.shaderRGBA[2] = 255.0f; ent.shaderRGBA[3] = 100.0f; -#else //no alpha +#else // no alpha ent.renderfx = RF_DISTORTION; #endif - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } -//distortion trail effect for rockets -rww +// distortion trail effect for rockets -rww /* static void CG_DistortionTrail( centity_t *cent ) { @@ -2427,276 +2123,223 @@ static void CG_DistortionTrail( centity_t *cent ) CG_Missile =============== */ -static void CG_Missile( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; - const weaponInfo_t *weapon; -// int col; +static void CG_Missile(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; + const weaponInfo_t *weapon; + // int col; s1 = ¢->currentState; - if ( s1->weapon > WP_NUM_WEAPONS && s1->weapon != G2_MODEL_PART ) { + if (s1->weapon > WP_NUM_WEAPONS && s1->weapon != G2_MODEL_PART) { s1->weapon = 0; } - if (cent->ghoul2 && s1->weapon == G2_MODEL_PART) - { + if (cent->ghoul2 && s1->weapon == G2_MODEL_PART) { weapon = &cg_weapons[WP_SABER]; - } - else - { + } else { weapon = &cg_weapons[s1->weapon]; } - if (cent->currentState.eFlags & EF_RADAROBJECT) - { + if (cent->currentState.eFlags & EF_RADAROBJECT) { CG_AddRadarEnt(cent); } - if (s1->weapon == WP_SABER) - { - if ((cent->currentState.modelindex != cent->serverSaberHitIndex || !cent->ghoul2) && !(s1->eFlags & EF_NODRAW)) - { //no g2, or server changed the model we are using - const char *saberModel = CG_ConfigString( CS_MODELS+cent->currentState.modelindex ); + if (s1->weapon == WP_SABER) { + if ((cent->currentState.modelindex != cent->serverSaberHitIndex || !cent->ghoul2) && + !(s1->eFlags & EF_NODRAW)) { // no g2, or server changed the model we are using + const char *saberModel = CG_ConfigString(CS_MODELS + cent->currentState.modelindex); cent->serverSaberHitIndex = cent->currentState.modelindex; - if (cent->ghoul2) - { //clean if we already have one (because server changed model string index) + if (cent->ghoul2) { // clean if we already have one (because server changed model string index) trap->G2API_CleanGhoul2Models(&(cent->ghoul2)); cent->ghoul2 = 0; } - if (saberModel && saberModel[0]) - { + if (saberModel && saberModel[0]) { trap->G2API_InitGhoul2Model(¢->ghoul2, saberModel, 0, 0, 0, 0, 0); - } - else - { + } else { trap->G2API_InitGhoul2Model(¢->ghoul2, DEFAULT_SABER_MODEL, 0, 0, 0, 0, 0); } return; - } - else if (s1->eFlags & EF_NODRAW) - { + } else if (s1->eFlags & EF_NODRAW) { return; } } - if (cent->ghoul2) - { //give us a proper radius + if (cent->ghoul2) { // give us a proper radius ent.radius = cent->currentState.g2radius; } // calculate the axis - VectorCopy( s1->angles, cent->lerpAngles); + VectorCopy(s1->angles, cent->lerpAngles); - if ( s1->otherEntityNum2 && s1->weapon != WP_SABER ) - {//using an over-ridden trail effect! + if (s1->otherEntityNum2 && s1->weapon != WP_SABER) { // using an over-ridden trail effect! vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - if ((s1->eFlags&EF_JETPACK_ACTIVE)//hack so we know we're a vehicle Weapon shot - && (g_vehWeaponInfo[s1->otherEntityNum2].iShotFX - || g_vehWeaponInfo[s1->otherEntityNum2].iModel != NULL_HANDLE) ) - { //a vehicle with an override for the weapon trail fx or model - trap->FX_PlayEffectID( g_vehWeaponInfo[s1->otherEntityNum2].iShotFX, cent->lerpOrigin, forward, -1, -1, qfalse ); - if ( g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound ) - { - vec3_t velocity; - BG_EvaluateTrajectoryDelta( ¢->currentState.pos, cg.time, velocity ); - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound ); - } - //add custom model - if ( g_vehWeaponInfo[s1->otherEntityNum2].iModel == NULL_HANDLE ) - { + if ((s1->eFlags & EF_JETPACK_ACTIVE) // hack so we know we're a vehicle Weapon shot + && (g_vehWeaponInfo[s1->otherEntityNum2].iShotFX || + g_vehWeaponInfo[s1->otherEntityNum2].iModel != NULL_HANDLE)) { // a vehicle with an override for the weapon trail fx or model + trap->FX_PlayEffectID(g_vehWeaponInfo[s1->otherEntityNum2].iShotFX, cent->lerpOrigin, forward, -1, -1, qfalse); + if (g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound) { + vec3_t velocity; + BG_EvaluateTrajectoryDelta(¢->currentState.pos, cg.time, velocity); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, velocity, g_vehWeaponInfo[s1->otherEntityNum2].iLoopSound); + } + // add custom model + if (g_vehWeaponInfo[s1->otherEntityNum2].iModel == NULL_HANDLE) { return; } - } - else - {//a regular missile - trap->FX_PlayEffectID( cgs.gameEffects[s1->otherEntityNum2], cent->lerpOrigin, forward, -1, -1, qfalse ); - if ( s1->loopSound ) - { - vec3_t velocity; - BG_EvaluateTrajectoryDelta( ¢->currentState.pos, cg.time, velocity ); - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, s1->loopSound ); + } else { // a regular missile + trap->FX_PlayEffectID(cgs.gameEffects[s1->otherEntityNum2], cent->lerpOrigin, forward, -1, -1, qfalse); + if (s1->loopSound) { + vec3_t velocity; + BG_EvaluateTrajectoryDelta(¢->currentState.pos, cg.time, velocity); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, velocity, s1->loopSound); } - //FIXME: if has a custom model, too, then set it and do rest of code below? + // FIXME: if has a custom model, too, then set it and do rest of code below? return; } - } - else if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { + } else if (cent->currentState.eFlags & EF_ALT_FIRING) { // add trails - if ( weapon->altMissileTrailFunc ) - { - weapon->altMissileTrailFunc( cent, weapon ); + if (weapon->altMissileTrailFunc) { + weapon->altMissileTrailFunc(cent, weapon); } // add dynamic light - if ( weapon->altMissileDlight ) - { - trap->R_AddLightToScene(cent->lerpOrigin, weapon->altMissileDlight, - weapon->altMissileDlightColor[0], weapon->altMissileDlightColor[1], weapon->altMissileDlightColor[2] ); + if (weapon->altMissileDlight) { + trap->R_AddLightToScene(cent->lerpOrigin, weapon->altMissileDlight, weapon->altMissileDlightColor[0], weapon->altMissileDlightColor[1], + weapon->altMissileDlightColor[2]); } // add missile sound - if ( weapon->altMissileSound ) { - vec3_t velocity; + if (weapon->altMissileSound) { + vec3_t velocity; - BG_EvaluateTrajectoryDelta( ¢->currentState.pos, cg.time, velocity ); + BG_EvaluateTrajectoryDelta(¢->currentState.pos, cg.time, velocity); - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, weapon->altMissileSound ); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, velocity, weapon->altMissileSound); } - //Don't draw something without a model - if ( weapon->altMissileModel == NULL_HANDLE ) + // Don't draw something without a model + if (weapon->altMissileModel == NULL_HANDLE) return; - } - else - { + } else { // add trails - if ( weapon->missileTrailFunc ) - { - weapon->missileTrailFunc( cent, weapon ); + if (weapon->missileTrailFunc) { + weapon->missileTrailFunc(cent, weapon); } // add dynamic light - if ( weapon->missileDlight ) - { - trap->R_AddLightToScene(cent->lerpOrigin, weapon->missileDlight, - weapon->missileDlightColor[0], weapon->missileDlightColor[1], weapon->missileDlightColor[2] ); + if (weapon->missileDlight) { + trap->R_AddLightToScene(cent->lerpOrigin, weapon->missileDlight, weapon->missileDlightColor[0], weapon->missileDlightColor[1], + weapon->missileDlightColor[2]); } // add missile sound - if ( weapon->missileSound ) - { - vec3_t velocity; + if (weapon->missileSound) { + vec3_t velocity; - BG_EvaluateTrajectoryDelta( ¢->currentState.pos, cg.time, velocity ); + BG_EvaluateTrajectoryDelta(¢->currentState.pos, cg.time, velocity); - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, velocity, weapon->missileSound ); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, velocity, weapon->missileSound); } - //Don't draw something without a model - if ( weapon->missileModel == NULL_HANDLE && s1->weapon != WP_SABER && s1->weapon != G2_MODEL_PART ) //saber uses ghoul2 model, doesn't matter + // Don't draw something without a model + if (weapon->missileModel == NULL_HANDLE && s1->weapon != WP_SABER && s1->weapon != G2_MODEL_PART) // saber uses ghoul2 model, doesn't matter return; } // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); -/* -Ghoul2 Insert Start -*/ + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // flicker between two skins ent.skinNum = cg.clientFrame & 1; - ent.renderfx = /*weapon->missileRenderfx | */RF_NOSHADOW; + ent.renderfx = /*weapon->missileRenderfx | */ RF_NOSHADOW; - if ( !(s1->eFlags&EF_JETPACK_ACTIVE) ) - { - if (s1->weapon != WP_SABER && s1->weapon != G2_MODEL_PART) - { - //if ( cent->currentState.eFlags | EF_ALT_FIRING ) - //rww - why was this like this? - if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { + if (!(s1->eFlags & EF_JETPACK_ACTIVE)) { + if (s1->weapon != WP_SABER && s1->weapon != G2_MODEL_PART) { + // if ( cent->currentState.eFlags | EF_ALT_FIRING ) + // rww - why was this like this? + if (cent->currentState.eFlags & EF_ALT_FIRING) { ent.hModel = weapon->altMissileModel; - } - else - { + } else { ent.hModel = weapon->missileModel; } } } - //add custom model - else - { - if ( g_vehWeaponInfo[s1->otherEntityNum2].iModel != NULL_HANDLE ) - { + // add custom model + else { + if (g_vehWeaponInfo[s1->otherEntityNum2].iModel != NULL_HANDLE) { ent.hModel = g_vehWeaponInfo[s1->otherEntityNum2].iModel; - } - else - {//wtf? how did we get here? + } else { // wtf? how did we get here? return; } } // spin as it moves - if ( s1->apos.trType != TR_INTERPOLATE ) - { + if (s1->apos.trType != TR_INTERPOLATE) { // convert direction of travel into axis - if ( VectorNormalize2( s1->pos.trDelta, ent.axis[0] ) == 0 ) { + if (VectorNormalize2(s1->pos.trDelta, ent.axis[0]) == 0) { ent.axis[0][2] = 1; } // spin as it moves - if ( s1->pos.trType != TR_STATIONARY ) - { - if ( s1->eFlags & EF_MISSILE_STICK ) - { - RotateAroundDirection( ent.axis, cg.time * 0.5f );//Did this so regular missiles don't get broken - } - else - { - RotateAroundDirection( ent.axis, cg.time * 0.25f );//JFM:FLOAT FIX - } - } - else - { - if ( s1->eFlags & EF_MISSILE_STICK ) - { - RotateAroundDirection( ent.axis, (float)s1->pos.trTime * 0.5f ); + if (s1->pos.trType != TR_STATIONARY) { + if (s1->eFlags & EF_MISSILE_STICK) { + RotateAroundDirection(ent.axis, cg.time * 0.5f); // Did this so regular missiles don't get broken + } else { + RotateAroundDirection(ent.axis, cg.time * 0.25f); // JFM:FLOAT FIX } - else - { - RotateAroundDirection( ent.axis, (float)s1->time ); + } else { + if (s1->eFlags & EF_MISSILE_STICK) { + RotateAroundDirection(ent.axis, (float)s1->pos.trTime * 0.5f); + } else { + RotateAroundDirection(ent.axis, (float)s1->time); } } - } - else - { - AnglesToAxis( cent->lerpAngles, ent.axis ); + } else { + AnglesToAxis(cent->lerpAngles, ent.axis); } - if (s1->weapon == WP_SABER) - { + if (s1->weapon == WP_SABER) { ent.radius = s1->g2radius; } // add to refresh list, possibly with quad glow - CG_AddRefEntityWithPowerups( &ent, s1, TEAM_FREE ); + CG_AddRefEntityWithPowerups(&ent, s1, TEAM_FREE); - if (s1->weapon == WP_SABER && cgs.gametype == GT_JEDIMASTER) - { //in jedimaster always make the saber glow when on the ground + if (s1->weapon == WP_SABER && cgs.gametype == GT_JEDIMASTER) { // in jedimaster always make the saber glow when on the ground vec3_t org; float wv; int i; addspriteArgStruct_t fxSArgs; - //refEntity_t sRef; - //memcpy( &sRef, &ent, sizeof( sRef ) ); + // refEntity_t sRef; + // memcpy( &sRef, &ent, sizeof( sRef ) ); ent.customShader = cgs.media.solidWhite; ent.renderfx = RF_RGB_TINT; - wv = sin( cg.time * 0.003f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.003f) * 0.08f + 0.1f; ent.shaderRGBA[0] = wv * 255; ent.shaderRGBA[1] = wv * 255; ent.shaderRGBA[2] = wv * 0; - trap->R_AddRefEntityToScene (&ent); + trap->R_AddRefEntityToScene(&ent); - for ( i = -4; i < 10; i += 1 ) - { - VectorMA( ent.origin, -i, ent.axis[2], org ); + for (i = -4; i < 10; i += 1) { + VectorMA(ent.origin, -i, ent.axis[2], org); VectorCopy(org, fxSArgs.origin); VectorClear(fxSArgs.vel); @@ -2711,12 +2354,11 @@ Ghoul2 Insert End fxSArgs.shader = cgs.media.yellowDroppedSaberShader; fxSArgs.flags = 0x08000000; - //trap->FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); + // trap->FX_AddSprite( org, NULL, NULL, 5.5f, 5.5f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); trap->FX_AddSprite(&fxSArgs); } - if (cgs.gametype == GT_JEDIMASTER) - { + if (cgs.gametype == GT_JEDIMASTER) { ent.shaderRGBA[0] = 255; ent.shaderRGBA[1] = 255; ent.shaderRGBA[2] = 0; @@ -2724,22 +2366,21 @@ Ghoul2 Insert End ent.renderfx |= RF_DEPTHHACK; ent.customShader = cgs.media.forceSightBubble; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } } - if ( s1->eFlags & EF_FIRING ) - {//special code for adding the beam to the attached tripwire mine - vec3_t beamOrg; + if (s1->eFlags & EF_FIRING) { // special code for adding the beam to the attached tripwire mine + vec3_t beamOrg; - VectorMA( ent.origin, 8, ent.axis[0], beamOrg );// forward - trap->FX_PlayEffectID( cgs.effects.mTripMineLaser, beamOrg, ent.axis[0], -1, -1, qfalse ); + VectorMA(ent.origin, 8, ent.axis[0], beamOrg); // forward + trap->FX_PlayEffectID(cgs.effects.mTripMineLaser, beamOrg, ent.axis[0], -1, -1, qfalse); } } -int CG_BMS_START = 0; -int CG_BMS_MID = 1; -int CG_BMS_END = 2; +int CG_BMS_START = 0; +int CG_BMS_MID = 1; +int CG_BMS_END = 2; /* ------------------------- @@ -2747,43 +2388,37 @@ CG_PlayDoorLoopSound ------------------------- */ -void CG_PlayDoorLoopSound( centity_t *cent ) -{ - sfxHandle_t sfx; +void CG_PlayDoorLoopSound(centity_t *cent) { + sfxHandle_t sfx; const char *soundSet; - vec3_t origin; - float *v; + vec3_t origin; + float *v; - if ( !cent->currentState.soundSetIndex ) - { + if (!cent->currentState.soundSetIndex) { return; } - soundSet = CG_ConfigString( CS_AMBIENT_SET + cent->currentState.soundSetIndex ); + soundSet = CG_ConfigString(CS_AMBIENT_SET + cent->currentState.soundSetIndex); - if (!soundSet || !soundSet[0]) - { + if (!soundSet || !soundSet[0]) { return; } - sfx = trap->AS_GetBModelSound( soundSet, CG_BMS_MID ); + sfx = trap->AS_GetBModelSound(soundSet, CG_BMS_MID); - if ( sfx == -1 ) - { + if (sfx == -1) { return; } - if (cent->currentState.eType == ET_MOVER) //shouldn't be in here otherwise, but just in case. - { - v = cgs.inlineModelMidpoints[ cent->currentState.modelindex ]; - VectorAdd( cent->lerpOrigin, v, origin ); - } - else + if (cent->currentState.eType == ET_MOVER) // shouldn't be in here otherwise, but just in case. { + v = cgs.inlineModelMidpoints[cent->currentState.modelindex]; + VectorAdd(cent->lerpOrigin, v, origin); + } else { VectorCopy(cent->lerpOrigin, origin); } - //ent->s.loopSound = sfx; + // ent->s.loopSound = sfx; CG_S_AddRealLoopingSound(cent->currentState.number, origin, vec3_origin, sfx); } @@ -2793,31 +2428,27 @@ CG_PlayDoorSound ------------------------- */ -void CG_PlayDoorSound( centity_t *cent, int type ) -{ - sfxHandle_t sfx; +void CG_PlayDoorSound(centity_t *cent, int type) { + sfxHandle_t sfx; const char *soundSet; - if ( !cent->currentState.soundSetIndex ) - { + if (!cent->currentState.soundSetIndex) { return; } - soundSet = CG_ConfigString( CS_AMBIENT_SET + cent->currentState.soundSetIndex ); + soundSet = CG_ConfigString(CS_AMBIENT_SET + cent->currentState.soundSetIndex); - if (!soundSet || !soundSet[0]) - { + if (!soundSet || !soundSet[0]) { return; } - sfx = trap->AS_GetBModelSound( soundSet, type ); + sfx = trap->AS_GetBModelSound(soundSet, type); - if ( sfx == -1 ) - { + if (sfx == -1) { return; } - trap->S_StartSound( NULL, cent->currentState.number, CHAN_AUTO, sfx ); + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, sfx); } /* @@ -2825,101 +2456,83 @@ void CG_PlayDoorSound( centity_t *cent, int type ) CG_Mover =============== */ -static void CG_Mover( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Mover(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); + memset(&ent, 0, sizeof(ent)); - if ( (cent->currentState.eFlags2&EF2_HYPERSPACE) ) - {//I'm the hyperspace brush + if ((cent->currentState.eFlags2 & EF2_HYPERSPACE)) { // I'm the hyperspace brush qboolean drawMe = qfalse; - if ( cg.predictedPlayerState.m_iVehicleNum - && cg.predictedVehicleState.hyperSpaceTime - && (cg.time-cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME - && (cg.time-cg.predictedVehicleState.hyperSpaceTime) > 1000 ) - { - if ( cg.snap - && cg.snap->ps.pm_type == PM_INTERMISSION ) - {//in the intermission, stop drawing hyperspace ent - } - else if ( (cg.predictedVehicleState.eFlags2&EF2_HYPERSPACE) ) - {//actually hyperspacing now - float timeFrac = ((float)(cg.time-cg.predictedVehicleState.hyperSpaceTime-1000))/(HYPERSPACE_TIME-1000); - if ( timeFrac < (HYPERSPACE_TELEPORT_FRAC+0.1f) ) - {//still in hyperspace or just popped out - const float alpha = timeFrac<0.5f?timeFrac/0.5f:1.0f; + if (cg.predictedPlayerState.m_iVehicleNum && cg.predictedVehicleState.hyperSpaceTime && + (cg.time - cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME && (cg.time - cg.predictedVehicleState.hyperSpaceTime) > 1000) { + if (cg.snap && cg.snap->ps.pm_type == PM_INTERMISSION) { // in the intermission, stop drawing hyperspace ent + } else if ((cg.predictedVehicleState.eFlags2 & EF2_HYPERSPACE)) { // actually hyperspacing now + float timeFrac = ((float)(cg.time - cg.predictedVehicleState.hyperSpaceTime - 1000)) / (HYPERSPACE_TIME - 1000); + if (timeFrac < (HYPERSPACE_TELEPORT_FRAC + 0.1f)) { // still in hyperspace or just popped out + const float alpha = timeFrac < 0.5f ? timeFrac / 0.5f : 1.0f; drawMe = qtrue; - VectorMA( cg.refdef.vieworg, 1000.0f+((1.0f-timeFrac)*1000.0f), cg.refdef.viewaxis[0], cent->lerpOrigin ); - VectorSet( cent->lerpAngles, cg.refdef.viewangles[PITCH], cg.refdef.viewangles[YAW]-90.0f, 0 );//cos( ( cg.time + 1000 ) * scale ) * 4 ); + VectorMA(cg.refdef.vieworg, 1000.0f + ((1.0f - timeFrac) * 1000.0f), cg.refdef.viewaxis[0], cent->lerpOrigin); + VectorSet(cent->lerpAngles, cg.refdef.viewangles[PITCH], cg.refdef.viewangles[YAW] - 90.0f, 0); // cos( ( cg.time + 1000 ) * scale ) * 4 ); ent.shaderRGBA[0] = ent.shaderRGBA[1] = ent.shaderRGBA[2] = 255; - ent.shaderRGBA[3] = alpha*255; + ent.shaderRGBA[3] = alpha * 255; } } } - if ( !drawMe ) - {//else, never draw + if (!drawMe) { // else, never draw return; } } - if (cent->currentState.eFlags & EF_RADAROBJECT) - { + if (cent->currentState.eFlags & EF_RADAROBJECT) { CG_AddRadarEnt(cent); } - VectorCopy( cent->lerpOrigin, ent.origin); - VectorCopy( cent->lerpOrigin, ent.oldorigin); - AnglesToAxis( cent->lerpAngles, ent.axis ); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(cent->lerpOrigin, ent.oldorigin); + AnglesToAxis(cent->lerpAngles, ent.axis); ent.renderfx = RF_NOSHADOW; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // flicker between two skins (FIXME?) - ent.skinNum = ( cg.time >> 6 ) & 1; + ent.skinNum = (cg.time >> 6) & 1; // get the model, either as a bmodel or a modelindex - if ( s1->solid == SOLID_BMODEL ) - { + if (s1->solid == SOLID_BMODEL) { ent.hModel = cgs.inlineDrawModel[s1->modelindex]; - } - else - { + } else { ent.hModel = cgs.gameModels[s1->modelindex]; } - if ( s1->eFlags & EF_SHADER_ANIM ) - { - ent.renderfx|=RF_SETANIMINDEX; + if (s1->eFlags & EF_SHADER_ANIM) { + ent.renderfx |= RF_SETANIMINDEX; ent.skinNum = s1->frame; - //ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames + // ent.shaderTime = cg.time*0.001f - s1->frame/s1->time;//NOTE: s1->time is number of frames } // add to refresh list trap->R_AddRefEntityToScene(&ent); // add the secondary model - if ( s1->modelindex2 && s1->modelindex2 < MAX_MODELS ) - { + if (s1->modelindex2 && s1->modelindex2 < MAX_MODELS) { ent.skinNum = 0; ent.hModel = cgs.gameModels[s1->modelindex2]; - if (s1->iModelScale) - { //custom model2 scale - ent.modelScale[0] = ent.modelScale[1] = ent.modelScale[2] = s1->iModelScale/100.0f; + if (s1->iModelScale) { // custom model2 scale + ent.modelScale[0] = ent.modelScale[1] = ent.modelScale[2] = s1->iModelScale / 100.0f; ScaleModelAxis(&ent); } trap->R_AddRefEntityToScene(&ent); } - } /* @@ -2929,72 +2542,70 @@ CG_Beam Also called as an event =============== */ -void CG_Beam( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +void CG_Beam(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( s1->pos.trBase, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - AxisClear( ent.axis ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(s1->pos.trBase, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + AxisClear(ent.axis); ent.reType = RT_BEAM; ent.renderfx = RF_NOSHADOW; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // add to refresh list trap->R_AddRefEntityToScene(&ent); } - /* =============== CG_Portal =============== */ -static void CG_Portal( centity_t *cent ) { - refEntity_t ent; - entityState_t *s1; +static void CG_Portal(centity_t *cent) { + refEntity_t ent; + entityState_t *s1; s1 = ¢->currentState; // create the render entity - memset (&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); - VectorCopy( s1->origin2, ent.oldorigin ); - ByteToDir( s1->eventParm, ent.axis[0] ); - PerpendicularVector( ent.axis[1], ent.axis[0] ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); + VectorCopy(s1->origin2, ent.oldorigin); + ByteToDir(s1->eventParm, ent.axis[0]); + PerpendicularVector(ent.axis[1], ent.axis[0]); // negating this tends to get the directions like they want // we really should have a camera roll value - VectorSubtract( vec3_origin, ent.axis[1], ent.axis[1] ); + VectorSubtract(vec3_origin, ent.axis[1], ent.axis[1]); - CrossProduct( ent.axis[0], ent.axis[1], ent.axis[2] ); + CrossProduct(ent.axis[0], ent.axis[1], ent.axis[2]); ent.reType = RT_PORTALSURFACE; ent.oldframe = s1->powerups; - ent.frame = s1->frame; // rotation speed - ent.skinNum = s1->clientNum/256.0 * 360; // roll offset -/* -Ghoul2 Insert Start -*/ + ent.frame = s1->frame; // rotation speed + ent.skinNum = s1->clientNum / 256.0 * 360; // roll offset + /* + Ghoul2 Insert Start + */ CG_SetGhoul2Info(&ent, cent); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // add to refresh list trap->R_AddRefEntityToScene(&ent); } - /* ========================= CG_AdjustPositionForMover @@ -3002,38 +2613,37 @@ CG_AdjustPositionForMover Also called by client movement prediction code ========================= */ -void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int fromTime, int toTime, vec3_t out ) { - centity_t *cent; - vec3_t oldOrigin, origin, deltaOrigin; - vec3_t oldAngles, angles, deltaAngles; +void CG_AdjustPositionForMover(const vec3_t in, int moverNum, int fromTime, int toTime, vec3_t out) { + centity_t *cent; + vec3_t oldOrigin, origin, deltaOrigin; + vec3_t oldAngles, angles, deltaAngles; - if ( cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR ) - { - VectorCopy( in, out ); + if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR) { + VectorCopy(in, out); return; } - if ( moverNum <= 0 || moverNum >= ENTITYNUM_MAX_NORMAL ) { - VectorCopy( in, out ); + if (moverNum <= 0 || moverNum >= ENTITYNUM_MAX_NORMAL) { + VectorCopy(in, out); return; } - cent = &cg_entities[ moverNum ]; - if ( cent->currentState.eType != ET_MOVER ) { - VectorCopy( in, out ); + cent = &cg_entities[moverNum]; + if (cent->currentState.eType != ET_MOVER) { + VectorCopy(in, out); return; } - BG_EvaluateTrajectory( ¢->currentState.pos, fromTime, oldOrigin ); - BG_EvaluateTrajectory( ¢->currentState.apos, fromTime, oldAngles ); + BG_EvaluateTrajectory(¢->currentState.pos, fromTime, oldOrigin); + BG_EvaluateTrajectory(¢->currentState.apos, fromTime, oldAngles); - BG_EvaluateTrajectory( ¢->currentState.pos, toTime, origin ); - BG_EvaluateTrajectory( ¢->currentState.apos, toTime, angles ); + BG_EvaluateTrajectory(¢->currentState.pos, toTime, origin); + BG_EvaluateTrajectory(¢->currentState.apos, toTime, angles); - VectorSubtract( origin, oldOrigin, deltaOrigin ); - VectorSubtract( angles, oldAngles, deltaAngles ); + VectorSubtract(origin, oldOrigin, deltaOrigin); + VectorSubtract(angles, oldAngles, deltaAngles); - VectorAdd( in, deltaOrigin, out ); + VectorAdd(in, deltaOrigin, out); // FIXME: origin change when on a rotating object } @@ -3043,14 +2653,14 @@ void CG_AdjustPositionForMover( const vec3_t in, int moverNum, int fromTime, int CG_InterpolateEntityPosition ============================= */ -static void CG_InterpolateEntityPosition( centity_t *cent ) { - vec3_t current, next; - float f; +static void CG_InterpolateEntityPosition(centity_t *cent) { + vec3_t current, next; + float f; // it would be an internal error to find an entity that interpolates without // a snapshot ahead of the current one - if ( cg.nextSnap == NULL ) { - trap->Error( ERR_DROP, "CG_InterpoateEntityPosition: cg.nextSnap == NULL" ); + if (cg.nextSnap == NULL) { + trap->Error(ERR_DROP, "CG_InterpoateEntityPosition: cg.nextSnap == NULL"); return; } @@ -3058,19 +2668,19 @@ static void CG_InterpolateEntityPosition( centity_t *cent ) { // this will linearize a sine or parabolic curve, but it is important // to not extrapolate player positions if more recent data is available - BG_EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, current ); - BG_EvaluateTrajectory( ¢->nextState.pos, cg.nextSnap->serverTime, next ); + BG_EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, current); + BG_EvaluateTrajectory(¢->nextState.pos, cg.nextSnap->serverTime, next); - cent->lerpOrigin[0] = current[0] + f * ( next[0] - current[0] ); - cent->lerpOrigin[1] = current[1] + f * ( next[1] - current[1] ); - cent->lerpOrigin[2] = current[2] + f * ( next[2] - current[2] ); + cent->lerpOrigin[0] = current[0] + f * (next[0] - current[0]); + cent->lerpOrigin[1] = current[1] + f * (next[1] - current[1]); + cent->lerpOrigin[2] = current[2] + f * (next[2] - current[2]); - BG_EvaluateTrajectory( ¢->currentState.apos, cg.snap->serverTime, current ); - BG_EvaluateTrajectory( ¢->nextState.apos, cg.nextSnap->serverTime, next ); + BG_EvaluateTrajectory(¢->currentState.apos, cg.snap->serverTime, current); + BG_EvaluateTrajectory(¢->nextState.apos, cg.nextSnap->serverTime, next); - cent->lerpAngles[0] = LerpAngle( current[0], next[0], f ); - cent->lerpAngles[1] = LerpAngle( current[1], next[1], f ); - cent->lerpAngles[2] = LerpAngle( current[2], next[2], f ); + cent->lerpAngles[0] = LerpAngle(current[0], next[0], f); + cent->lerpAngles[1] = LerpAngle(current[1], next[1], f); + cent->lerpAngles[2] = LerpAngle(current[2], next[2], f); } /* @@ -3079,55 +2689,47 @@ CG_CalcEntityLerpPositions =============== */ -void CG_CalcEntityLerpPositions( centity_t *cent ) { +void CG_CalcEntityLerpPositions(centity_t *cent) { qboolean goAway = qfalse; // if this player does not want to see extrapolated players - if ( !cg_smoothClients.integer ) { + if (!cg_smoothClients.integer) { // make sure the clients use TR_INTERPOLATE - if ( (cent->currentState.number != cg.clientNum && cent->currentState.number < MAX_CLIENTS) || cent->currentState.eType == ET_NPC ) { + if ((cent->currentState.number != cg.clientNum && cent->currentState.number < MAX_CLIENTS) || cent->currentState.eType == ET_NPC) { cent->currentState.pos.trType = TR_INTERPOLATE; cent->nextState.pos.trType = TR_INTERPOLATE; } } - if (cg.predictedPlayerState.m_iVehicleNum && - cg.predictedPlayerState.m_iVehicleNum == cent->currentState.number && - cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE) - { //special case for vehicle we are riding + if (cg.predictedPlayerState.m_iVehicleNum && cg.predictedPlayerState.m_iVehicleNum == cent->currentState.number && cent->currentState.eType == ET_NPC && + cent->currentState.NPC_class == CLASS_VEHICLE) { // special case for vehicle we are riding centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if (veh->currentState.owner == cg.predictedPlayerState.clientNum) - { //only do this if the vehicle is pilotted by this client and predicting properly - BG_EvaluateTrajectory( ¢->currentState.pos, cg.time, cent->lerpOrigin ); - BG_EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + if (veh->currentState.owner == cg.predictedPlayerState.clientNum) { // only do this if the vehicle is pilotted by this client and predicting properly + BG_EvaluateTrajectory(¢->currentState.pos, cg.time, cent->lerpOrigin); + BG_EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); return; } } - if ( cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE ) { - CG_InterpolateEntityPosition( cent ); + if (cent->interpolate && cent->currentState.pos.trType == TR_INTERPOLATE) { + CG_InterpolateEntityPosition(cent); return; } // first see if we can interpolate between two snaps for // linear extrapolated clients - if ( cent->interpolate && cent->currentState.pos.trType == TR_LINEAR_STOP - && ((cent->currentState.number != cg.clientNum && cent->currentState.number < MAX_CLIENTS) || cent->currentState.eType == ET_NPC) ) { - CG_InterpolateEntityPosition( cent ); + if (cent->interpolate && cent->currentState.pos.trType == TR_LINEAR_STOP && + ((cent->currentState.number != cg.clientNum && cent->currentState.number < MAX_CLIENTS) || cent->currentState.eType == ET_NPC)) { + CG_InterpolateEntityPosition(cent); goAway = qtrue; - } - else if (cent->interpolate && - cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE) - { - CG_InterpolateEntityPosition( cent ); + } else if (cent->interpolate && cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE) { + CG_InterpolateEntityPosition(cent); goAway = qtrue; - } - else - { + } else { // just use the current frame and evaluate as best we can - BG_EvaluateTrajectory( ¢->currentState.pos, cg.time, cent->lerpOrigin ); - BG_EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + BG_EvaluateTrajectory(¢->currentState.pos, cg.time, cent->lerpOrigin); + BG_EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); } #if 0 @@ -3190,49 +2792,41 @@ void CG_CalcEntityLerpPositions( centity_t *cent ) { } #endif - if (goAway) - { + if (goAway) { return; } // adjust for riding a mover if it wasn't rolled into the predicted // player state - if ( cent->currentState.number != cg.clientNum ) { - CG_AdjustPositionForMover( cent->lerpOrigin, cent->currentState.groundEntityNum, - cg.snap->serverTime, cg.time, cent->lerpOrigin ); + if (cent->currentState.number != cg.clientNum) { + CG_AdjustPositionForMover(cent->lerpOrigin, cent->currentState.groundEntityNum, cg.snap->serverTime, cg.time, cent->lerpOrigin); } } -void CG_G2Animated( centity_t *cent ); +void CG_G2Animated(centity_t *cent); -static void CG_FX( centity_t *cent ) -{ - vec3_t fxDir; - int efxIndex = 0; - entityState_t *s1; - const char *s; +static void CG_FX(centity_t *cent) { + vec3_t fxDir; + int efxIndex = 0; + entityState_t *s1; + const char *s; - if (cent->miscTime > cg.time) - { + if (cent->miscTime > cg.time) { return; } s1 = ¢->currentState; - if (!s1) - { + if (!s1) { return; } - if (s1->modelindex2 == FX_STATE_OFF) - { // fx not active + if (s1->modelindex2 == FX_STATE_OFF) { // fx not active return; } - if (s1->modelindex2 < FX_STATE_ONE_SHOT_LIMIT) - { // fx is single shot - if (cent->muzzleFlashTime == s1->modelindex2) - { + if (s1->modelindex2 < FX_STATE_ONE_SHOT_LIMIT) { // fx is single shot + if (cent->muzzleFlashTime == s1->modelindex2) { return; } @@ -3243,104 +2837,83 @@ static void CG_FX( centity_t *cent ) AngleVectors(s1->angles, fxDir, 0, 0); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - if ( cgs.gameEffects[ s1->modelindex ] ) - { + if (cgs.gameEffects[s1->modelindex]) { efxIndex = cgs.gameEffects[s1->modelindex]; - } - else - { - s = CG_ConfigString( CS_EFFECTS + s1->modelindex ); - if (s && s[0]) - { + } else { + s = CG_ConfigString(CS_EFFECTS + s1->modelindex); + if (s && s[0]) { efxIndex = trap->FX_RegisterEffect(s); cgs.gameEffects[s1->modelindex] = efxIndex; } } - if (efxIndex) - { - if (s1->isPortalEnt) - { - trap->FX_PlayEffectID(efxIndex, cent->lerpOrigin, fxDir, -1, -1, qtrue ); - } - else - { - trap->FX_PlayEffectID(efxIndex, cent->lerpOrigin, fxDir, -1, -1, qfalse ); + if (efxIndex) { + if (s1->isPortalEnt) { + trap->FX_PlayEffectID(efxIndex, cent->lerpOrigin, fxDir, -1, -1, qtrue); + } else { + trap->FX_PlayEffectID(efxIndex, cent->lerpOrigin, fxDir, -1, -1, qfalse); } } - - } - /* =============== CG_AddCEntity =============== */ -static void CG_AddCEntity( centity_t *cent ) { +static void CG_AddCEntity(centity_t *cent) { // event-only entities will have been dealt with already - if ( cent->currentState.eType >= ET_EVENTS ) { + if (cent->currentState.eType >= ET_EVENTS) { return; } - if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) - { //don't render anything then - if (cent->currentState.eType == ET_GENERAL || - cent->currentState.eType == ET_PLAYER || - cent->currentState.eType == ET_INVISIBLE) - { + if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) { // don't render anything then + if (cent->currentState.eType == ET_GENERAL || cent->currentState.eType == ET_PLAYER || cent->currentState.eType == ET_INVISIBLE) { return; } - if ( cent->currentState.eType == ET_NPC ) - {//NPC in intermission - if ( cent->currentState.NPC_class == CLASS_VEHICLE ) - {//don't render vehicles in intermissions, allow other NPCs for scripts + if (cent->currentState.eType == ET_NPC) { // NPC in intermission + if (cent->currentState.NPC_class == CLASS_VEHICLE) { // don't render vehicles in intermissions, allow other NPCs for scripts return; } } } // don't render when we are in spec, happens occasionally on map_restart and such - if ( cg.predictedPlayerState.clientNum == cent->currentState.number && cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR ) + if (cg.predictedPlayerState.clientNum == cent->currentState.number && cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR) return; - // calculate the current origin - CG_CalcEntityLerpPositions( cent ); + CG_CalcEntityLerpPositions(cent); // add automatic effects - CG_EntityEffects( cent ); -/* -Ghoul2 Insert Start -*/ + CG_EntityEffects(cent); + /* + Ghoul2 Insert Start + */ // add local sound set if any - if ( cent->currentState.soundSetIndex && cent->currentState.eType != ET_MOVER ) - { - const char *soundSet = CG_ConfigString( CS_AMBIENT_SET + cent->currentState.soundSetIndex ); + if (cent->currentState.soundSetIndex && cent->currentState.eType != ET_MOVER) { + const char *soundSet = CG_ConfigString(CS_AMBIENT_SET + cent->currentState.soundSetIndex); - if (soundSet && soundSet[0]) - { + if (soundSet && soundSet[0]) { trap->S_AddLocalSet(soundSet, cg.refdef.vieworg, cent->lerpOrigin, cent->currentState.number, cg.time); } } -/* -Ghoul2 Insert End -*/ - switch ( cent->currentState.eType ) { + /* + Ghoul2 Insert End + */ + switch (cent->currentState.eType) { default: - trap->Error( ERR_DROP, "Bad entity type: %i\n", cent->currentState.eType ); + trap->Error(ERR_DROP, "Bad entity type: %i\n", cent->currentState.eType); break; case ET_FX: - CG_FX( cent ); + CG_FX(cent); break; case ET_INVISIBLE: @@ -3349,50 +2922,47 @@ Ghoul2 Insert End case ET_TERRAIN: break; case ET_GENERAL: - CG_General( cent ); + CG_General(cent); break; case ET_PLAYER: - CG_Player( cent ); + CG_Player(cent); break; case ET_ITEM: - CG_Item( cent ); + CG_Item(cent); break; case ET_MISSILE: - CG_Missile( cent ); + CG_Missile(cent); break; case ET_SPECIAL: - CG_Special( cent ); + CG_Special(cent); break; case ET_HOLOCRON: - CG_General( cent ); + CG_General(cent); break; case ET_MOVER: - CG_Mover( cent ); + CG_Mover(cent); break; case ET_BEAM: - CG_Beam( cent ); + CG_Beam(cent); break; case ET_PORTAL: - CG_Portal( cent ); + CG_Portal(cent); break; case ET_SPEAKER: - CG_Speaker( cent ); + CG_Speaker(cent); break; - case ET_NPC: //An entity that wants to be able to use ghoul2 humanoid (and other) anims. Like a player, but not. - CG_G2Animated( cent ); + case ET_NPC: // An entity that wants to be able to use ghoul2 humanoid (and other) anims. Like a player, but not. + CG_G2Animated(cent); break; case ET_TEAM: break; case ET_BODY: - CG_General( cent ); + CG_General(cent); break; } } -void CG_ManualEntityRender(centity_t *cent) -{ - CG_AddCEntity(cent); -} +void CG_ManualEntityRender(centity_t *cent) { CG_AddCEntity(cent); } /* =============== @@ -3400,51 +2970,48 @@ CG_AddPacketEntities =============== */ -void CG_AddPacketEntities( qboolean isPortal ) { - int num; - centity_t *cent; - playerState_t *ps; +void CG_AddPacketEntities(qboolean isPortal) { + int num; + centity_t *cent; + playerState_t *ps; - if (isPortal) - { - for ( num = 0 ; num < cg.snap->numEntities ; num++ ) - { - cent = &cg_entities[ cg.snap->entities[ num ].number ]; + if (isPortal) { + for (num = 0; num < cg.snap->numEntities; num++) { + cent = &cg_entities[cg.snap->entities[num].number]; - if (cent->currentState.isPortalEnt) - { - CG_AddCEntity( cent ); + if (cent->currentState.isPortalEnt) { + CG_AddCEntity(cent); } } return; } // set cg.frameInterpolation - if ( cg.nextSnap ) { - int delta; + if (cg.nextSnap) { + int delta; delta = (cg.nextSnap->serverTime - cg.snap->serverTime); - if ( delta == 0 ) { + if (delta == 0) { cg.frameInterpolation = 0; } else { - cg.frameInterpolation = (float)( cg.time - cg.snap->serverTime ) / delta; + cg.frameInterpolation = (float)(cg.time - cg.snap->serverTime) / delta; } } else { - cg.frameInterpolation = 0; // actually, it should never be used, because - // no entities should be marked as interpolating + cg.frameInterpolation = 0; // actually, it should never be used, because + // no entities should be marked as interpolating } // the auto-rotating items will all have the same axis cg.autoAngles[0] = 0; - cg.autoAngles[1] = ( cg.time & 2047 ) * 360 / 2048.0; + cg.autoAngles[1] = (cg.time & 2047) * 360 / 2048.0; cg.autoAngles[2] = 0; cg.autoAnglesFast[0] = 0; - cg.autoAnglesFast[1] = ( cg.time & 1023 ) * 360 / 1024.0f; + cg.autoAnglesFast[1] = (cg.time & 1023) * 360 / 1024.0f; cg.autoAnglesFast[2] = 0; - AnglesToAxis( cg.autoAngles, cg.autoAxis ); - AnglesToAxis( cg.autoAnglesFast, cg.autoAxisFast ); + AnglesToAxis(cg.autoAngles, cg.autoAxis); + AnglesToAxis(cg.autoAnglesFast, cg.autoAxisFast); // Reset radar entities cg.radarEntityCount = 0; @@ -3454,81 +3021,68 @@ void CG_AddPacketEntities( qboolean isPortal ) { ps = &cg.predictedPlayerState; CG_CheckPlayerG2Weapons(ps, &cg_entities[cg.predictedPlayerState.clientNum]); - BG_PlayerStateToEntityState( ps, &cg_entities[cg.predictedPlayerState.clientNum].currentState, qfalse ); + BG_PlayerStateToEntityState(ps, &cg_entities[cg.predictedPlayerState.clientNum].currentState, qfalse); - if (cg.predictedPlayerState.m_iVehicleNum) - { //add the vehicle I'm riding first - //BG_PlayerStateToEntityState( &cg.predictedVehicleState, &cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState, qfalse ); - //cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState.eType = ET_NPC; + if (cg.predictedPlayerState.m_iVehicleNum) { // add the vehicle I'm riding first + // BG_PlayerStateToEntityState( &cg.predictedVehicleState, &cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState, qfalse ); + // cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState.eType = ET_NPC; centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if (veh->currentState.owner == cg.predictedPlayerState.clientNum) - { - BG_PlayerStateToEntityState( &cg.predictedVehicleState, &veh->currentState, qfalse ); + if (veh->currentState.owner == cg.predictedPlayerState.clientNum) { + BG_PlayerStateToEntityState(&cg.predictedVehicleState, &veh->currentState, qfalse); veh->currentState.eType = ET_NPC; veh->currentState.pos.trType = TR_INTERPOLATE; } - CG_AddCEntity(veh); - veh->bodyHeight = cg.time; //indicate we have already been added + CG_AddCEntity(veh); + veh->bodyHeight = cg.time; // indicate we have already been added } - CG_AddCEntity( &cg_entities[cg.predictedPlayerState.clientNum] ); + CG_AddCEntity(&cg_entities[cg.predictedPlayerState.clientNum]); /* // lerp the non-predicted value for lightning gun origins CG_CalcEntityLerpPositions( &cg_entities[ cg.snap->ps.clientNum ] ); */ - //No longer have to do this. + // No longer have to do this. // add each entity sent over by the server - for ( num = 0 ; num < cg.snap->numEntities ; num++ ) { + for (num = 0; num < cg.snap->numEntities; num++) { // Don't re-add ents that have been predicted. - if (cg.snap->entities[ num ].number != cg.snap->ps.clientNum) - { - cent = &cg_entities[ cg.snap->entities[ num ].number ]; - if (cent->currentState.eType == ET_PLAYER && - cent->currentState.m_iVehicleNum) - { //add his veh first + if (cg.snap->entities[num].number != cg.snap->ps.clientNum) { + cent = &cg_entities[cg.snap->entities[num].number]; + if (cent->currentState.eType == ET_PLAYER && cent->currentState.m_iVehicleNum) { // add his veh first int j = 0; - while (j < cg.snap->numEntities) - { - if (cg.snap->entities[j].number == cent->currentState.m_iVehicleNum) - { + while (j < cg.snap->numEntities) { + if (cg.snap->entities[j].number == cent->currentState.m_iVehicleNum) { centity_t *veh = &cg_entities[cg.snap->entities[j].number]; CG_AddCEntity(veh); - veh->bodyHeight = cg.time; //indicate we have already been added + veh->bodyHeight = cg.time; // indicate we have already been added break; } j++; } - } - else if (cent->currentState.eType == ET_NPC && - cent->currentState.m_iVehicleNum && - cent->bodyHeight == cg.time) - { //never add a vehicle with a pilot, his pilot entity will get him added first. - //if we were to add the vehicle after the pilot, the pilot's bolt would lag a frame behind. + } else if (cent->currentState.eType == ET_NPC && cent->currentState.m_iVehicleNum && + cent->bodyHeight == cg.time) { // never add a vehicle with a pilot, his pilot entity will get him added first. + // if we were to add the vehicle after the pilot, the pilot's bolt would lag a frame behind. continue; } - CG_AddCEntity( cent ); + CG_AddCEntity(cent); } } - for(num=0;numcurrentValid) - { - CG_AddCEntity( cent ); + if (cent->currentValid) { + CG_AddCEntity(cent); } } } -void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) -{ +void CG_ROFF_NotetrackCallback(centity_t *cent, const char *notetrack) { int i = 0, r = 0, objectID = 0, anglesGathered = 0, posoffsetGathered = 0; char type[256]; char argument[512]; @@ -3538,49 +3092,42 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) int addlArgs = 0; vec3_t parsedAngles, parsedOffset, useAngles, useOrigin, forward, right, up; - if (!cent || !notetrack) - { + if (!cent || !notetrack) { return; } - //notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; + // notetrack = "effect effects/explosion1.efx 0+0+64 0-0-1"; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (notetrack[i] != ' ') - { //didn't pass in a valid notetrack type, or forgot the argument for it + if (notetrack[i] != ' ') { // didn't pass in a valid notetrack type, or forgot the argument for it return; } i++; - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { argument[r] = notetrack[i]; r++; i++; } argument[r] = '\0'; - if (!r) - { + if (!r) { return; } - if (notetrack[i] == ' ') - { //additional arguments... + if (notetrack[i] == ' ') { // additional arguments... addlArgs = 1; i++; r = 0; - while (notetrack[i]) - { + while (notetrack[i]) { addlArg[r] = notetrack[i]; r++; i++; @@ -3588,33 +3135,28 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) addlArg[r] = '\0'; } - if (strcmp(type, "effect") == 0) - { - if (!addlArgs) - { - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (strcmp(type, "effect") == 0) { + if (!addlArgs) { + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); goto defaultoffsetposition; } i = 0; - while (posoffsetGathered < 3) - { + while (posoffsetGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') - { + while (addlArg[i] && addlArg[i] != '+' && addlArg[i] != ' ') { t[r] = addlArg[i]; r++; i++; } t[r] = '\0'; i++; - if (!r) - { //failure.. - //sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); - //goto functionend; + if (!r) { // failure.. + // sprintf(errMsg, "Offset position argument for 'effect' type is invalid."); + // goto functionend; VectorClear(parsedOffset); i = 0; goto defaultoffsetposition; @@ -3623,33 +3165,27 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) posoffsetGathered++; } - if (posoffsetGathered < 3) - { + if (posoffsetGathered < 3) { Com_sprintf(errMsg, sizeof(errMsg), "Offset position argument for 'effect' type is invalid."); goto functionend; } i--; - if (addlArg[i] != ' ') - { + if (addlArg[i] != ' ') { addlArgs = 0; } -defaultoffsetposition: + defaultoffsetposition: objectID = trap->FX_RegisterEffect(argument); - if (objectID) - { - if (addlArgs) - { //if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE + if (objectID) { + if (addlArgs) { // if there is an additional argument for an effect it is expected to be XANGLE-YANGLE-ZANGLE i++; - while (anglesGathered < 3) - { + while (anglesGathered < 3) { r = 0; - while (addlArg[i] && addlArg[i] != '-') - { + while (addlArg[i] && addlArg[i] != '-') { t[r] = addlArg[i]; r++; i++; @@ -3657,8 +3193,7 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) t[r] = '\0'; i++; - if (!r) - { //failed to get a new part of the vector + if (!r) { // failed to get a new part of the vector anglesGathered = 0; break; } @@ -3667,17 +3202,12 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) anglesGathered++; } - if (anglesGathered) - { + if (anglesGathered) { VectorCopy(parsedAngles, useAngles); - } - else - { //failed to parse angles from the extra argument provided.. + } else { // failed to parse angles from the extra argument provided.. VectorCopy(cent->lerpAngles, useAngles); } - } - else - { //if no constant angles, play in direction entity is facing + } else { // if no constant angles, play in direction entity is facing VectorCopy(cent->lerpAngles, useAngles); } @@ -3685,42 +3215,34 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) VectorCopy(cent->lerpOrigin, useOrigin); - //forward - useOrigin[0] += forward[0]*parsedOffset[0]; - useOrigin[1] += forward[1]*parsedOffset[0]; - useOrigin[2] += forward[2]*parsedOffset[0]; + // forward + useOrigin[0] += forward[0] * parsedOffset[0]; + useOrigin[1] += forward[1] * parsedOffset[0]; + useOrigin[2] += forward[2] * parsedOffset[0]; - //right - useOrigin[0] += right[0]*parsedOffset[1]; - useOrigin[1] += right[1]*parsedOffset[1]; - useOrigin[2] += right[2]*parsedOffset[1]; + // right + useOrigin[0] += right[0] * parsedOffset[1]; + useOrigin[1] += right[1] * parsedOffset[1]; + useOrigin[2] += right[2] * parsedOffset[1]; - //up - useOrigin[0] += up[0]*parsedOffset[2]; - useOrigin[1] += up[1]*parsedOffset[2]; - useOrigin[2] += up[2]*parsedOffset[2]; + // up + useOrigin[0] += up[0] * parsedOffset[2]; + useOrigin[1] += up[1] * parsedOffset[2]; + useOrigin[2] += up[2] * parsedOffset[2]; trap->FX_PlayEffectID(objectID, useOrigin, useAngles, -1, -1, qfalse); } - } - else if (strcmp(type, "sound") == 0) - { + } else if (strcmp(type, "sound") == 0) { objectID = trap->S_RegisterSound(argument); trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_BODY, objectID); - } - else if (strcmp(type, "loop") == 0) - { //handled server-side + } else if (strcmp(type, "loop") == 0) { // handled server-side return; } - //else if ... - else - { - if (type[0]) - { + // else if ... + else { + if (type[0]) { Com_Printf("^3Warning: \"%s\" is an invalid ROFF notetrack function\n", type); - } - else - { + } else { Com_Printf("^3Warning: Notetrack is missing function and/or arguments\n"); } } @@ -3732,21 +3254,17 @@ void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack) return; } -void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) -{ - vec3_t rot={0,0,0}; - int vec[3]; - int axis, i; +void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha) { + vec3_t rot = {0, 0, 0}; + int vec[3]; + int axis, i; addpolyArgStruct_t apArgs; - memset (&apArgs, 0, sizeof(apArgs)); + memset(&apArgs, 0, sizeof(apArgs)); - for ( axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++ ) - { - for ( i = 0; i < 3; i++ ) - { - if ( vec[i] > 2 ) - { + for (axis = 0, vec[0] = 0, vec[1] = 1, vec[2] = 2; axis < 3; axis++, vec[0]++, vec[1]++, vec[2]++) { + for (i = 0; i < 3; i++) { + if (vec[i] > 2) { vec[i] = 0; } } @@ -3768,17 +3286,17 @@ void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) apArgs.numVerts = 4; apArgs.alpha1 = apArgs.alpha2 = alpha; - VectorCopy( color, apArgs.rgb1 ); - VectorCopy( color, apArgs.rgb2 ); - VectorCopy( rot, apArgs.rotationDelta ); + VectorCopy(color, apArgs.rgb1); + VectorCopy(color, apArgs.rgb2); + VectorCopy(rot, apArgs.rotationDelta); apArgs.killTime = cg.frametime; apArgs.shader = cgs.media.solidWhite; - trap->FX_AddPoly( &apArgs ); + trap->FX_AddPoly(&apArgs); //+ face apArgs.p[0][vec[0]] = apArgs.p[1][vec[0]] = apArgs.p[2][vec[0]] = apArgs.p[3][vec[0]] = maxs[vec[0]]; - trap->FX_AddPoly( &apArgs ); + trap->FX_AddPoly(&apArgs); } } diff --git a/codemp/cgame/cg_event.c b/codemp/cgame/cg_event.c index 98d3992a7c..0f1db36563 100644 --- a/codemp/cgame/cg_event.c +++ b/codemp/cgame/cg_event.c @@ -34,10 +34,10 @@ along with this program; if not, see . #include "ghoul2/G2.h" //========================================================================== -extern qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); -extern qboolean CG_VehicleWeaponImpact( centity_t *cent ); -extern qboolean CG_InFighter( void ); -extern qboolean CG_InATST( void ); +extern qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); +extern qboolean CG_VehicleWeaponImpact(centity_t *cent); +extern qboolean CG_InFighter(void); +extern qboolean CG_InATST(void); extern int cg_saberFlashTime; extern vec3_t cg_saberFlashPos; extern char *showPowersName[]; @@ -47,15 +47,8 @@ extern int cg_siegeDeathDelay; extern int cg_vehicleAmmoWarning; extern int cg_vehicleAmmoWarningTime; -//I know, not siege, but... -typedef enum -{ - TAUNT_TAUNT = 0, - TAUNT_BOW, - TAUNT_MEDITATE, - TAUNT_FLOURISH, - TAUNT_GLOAT -} tauntTypes_t ; +// I know, not siege, but... +typedef enum { TAUNT_TAUNT = 0, TAUNT_BOW, TAUNT_MEDITATE, TAUNT_FLOURISH, TAUNT_GLOAT } tauntTypes_t; /* =================== CG_PlaceString @@ -63,54 +56,54 @@ CG_PlaceString Also called by scoreboard drawing =================== */ -const char *CG_PlaceString( int rank ) { - static char str[64]; - char *s, *t; +const char *CG_PlaceString(int rank) { + static char str[64]; + char *s, *t; // number extenstions, eg 1st, 2nd, 3rd, 4th etc. // note that the rules are different for french, but by changing the required strip strings they seem to work char sST[10]; char sND[10]; char sRD[10]; char sTH[10]; - char sTiedFor[64]; // german is much longer, super safe... + char sTiedFor[64]; // german is much longer, super safe... - trap->SE_GetStringTextString("MP_INGAME_NUMBER_ST",sST, sizeof(sST) ); - trap->SE_GetStringTextString("MP_INGAME_NUMBER_ND",sND, sizeof(sND) ); - trap->SE_GetStringTextString("MP_INGAME_NUMBER_RD",sRD, sizeof(sRD) ); - trap->SE_GetStringTextString("MP_INGAME_NUMBER_TH",sTH, sizeof(sTH) ); - trap->SE_GetStringTextString("MP_INGAME_TIED_FOR" ,sTiedFor,sizeof(sTiedFor) ); - strcat(sTiedFor," "); // save worrying about translators adding spaces or not + trap->SE_GetStringTextString("MP_INGAME_NUMBER_ST", sST, sizeof(sST)); + trap->SE_GetStringTextString("MP_INGAME_NUMBER_ND", sND, sizeof(sND)); + trap->SE_GetStringTextString("MP_INGAME_NUMBER_RD", sRD, sizeof(sRD)); + trap->SE_GetStringTextString("MP_INGAME_NUMBER_TH", sTH, sizeof(sTH)); + trap->SE_GetStringTextString("MP_INGAME_TIED_FOR", sTiedFor, sizeof(sTiedFor)); + strcat(sTiedFor, " "); // save worrying about translators adding spaces or not - if ( rank & RANK_TIED_FLAG ) { + if (rank & RANK_TIED_FLAG) { rank &= ~RANK_TIED_FLAG; - t = sTiedFor;//"Tied for "; + t = sTiedFor; //"Tied for "; } else { t = ""; } - if ( rank == 1 ) { - s = va("1%s",sST);//S_COLOR_BLUE "1st" S_COLOR_WHITE; // draw in blue - } else if ( rank == 2 ) { - s = va("2%s",sND);//S_COLOR_RED "2nd" S_COLOR_WHITE; // draw in red - } else if ( rank == 3 ) { - s = va("3%s",sRD);//S_COLOR_YELLOW "3rd" S_COLOR_WHITE; // draw in yellow - } else if ( rank == 11 ) { - s = va("11%s",sTH); - } else if ( rank == 12 ) { - s = va("12%s",sTH); - } else if ( rank == 13 ) { - s = va("13%s",sTH); - } else if ( rank % 10 == 1 ) { - s = va("%i%s", rank,sST); - } else if ( rank % 10 == 2 ) { - s = va("%i%s", rank,sND); - } else if ( rank % 10 == 3 ) { - s = va("%i%s", rank,sRD); + if (rank == 1) { + s = va("1%s", sST); // S_COLOR_BLUE "1st" S_COLOR_WHITE; // draw in blue + } else if (rank == 2) { + s = va("2%s", sND); // S_COLOR_RED "2nd" S_COLOR_WHITE; // draw in red + } else if (rank == 3) { + s = va("3%s", sRD); // S_COLOR_YELLOW "3rd" S_COLOR_WHITE; // draw in yellow + } else if (rank == 11) { + s = va("11%s", sTH); + } else if (rank == 12) { + s = va("12%s", sTH); + } else if (rank == 13) { + s = va("13%s", sTH); + } else if (rank % 10 == 1) { + s = va("%i%s", rank, sST); + } else if (rank % 10 == 2) { + s = va("%i%s", rank, sND); + } else if (rank % 10 == 3) { + s = va("%i%s", rank, sRD); } else { - s = va("%i%s", rank,sTH); + s = va("%i%s", rank, sTH); } - Com_sprintf( str, sizeof( str ), "%s%s", t, s ); + Com_sprintf(str, sizeof(str), "%s%s", t, s); return str; } @@ -121,44 +114,43 @@ qboolean CG_ThereIsAMaster(void); CG_Obituary ============= */ -static void CG_Obituary( entityState_t *ent ) { - int mod; - int target, attacker; - char *message; - const char *targetInfo; - const char *attackerInfo; - char targetName[32]; - char attackerName[32]; - gender_t gender; - clientInfo_t *ci; - +static void CG_Obituary(entityState_t *ent) { + int mod; + int target, attacker; + char *message; + const char *targetInfo; + const char *attackerInfo; + char targetName[32]; + char attackerName[32]; + gender_t gender; + clientInfo_t *ci; target = ent->otherEntityNum; attacker = ent->otherEntityNum2; mod = ent->eventParm; - if ( target < 0 || target >= MAX_CLIENTS ) { - trap->Error( ERR_DROP, "CG_Obituary: target out of range" ); + if (target < 0 || target >= MAX_CLIENTS) { + trap->Error(ERR_DROP, "CG_Obituary: target out of range"); } ci = &cgs.clientinfo[target]; - if ( attacker < 0 || attacker >= MAX_CLIENTS ) { + if (attacker < 0 || attacker >= MAX_CLIENTS) { attacker = ENTITYNUM_WORLD; attackerInfo = NULL; } else { - attackerInfo = CG_ConfigString( CS_PLAYERS + attacker ); + attackerInfo = CG_ConfigString(CS_PLAYERS + attacker); } - targetInfo = CG_ConfigString( CS_PLAYERS + target ); - if ( !targetInfo ) { + targetInfo = CG_ConfigString(CS_PLAYERS + target); + if (!targetInfo) { return; } - Q_strncpyz( targetName, Info_ValueForKey( targetInfo, "n" ), sizeof(targetName) - 2); - strcat( targetName, S_COLOR_WHITE ); + Q_strncpyz(targetName, Info_ValueForKey(targetInfo, "n"), sizeof(targetName) - 2); + strcat(targetName, S_COLOR_WHITE); // check for single client messages - switch( mod ) { + switch (mod) { case MOD_SUICIDE: case MOD_FALLING: case MOD_CRUSH: @@ -191,9 +183,9 @@ static void CG_Obituary( entityState_t *ent ) { case MOD_REPEATER: case MOD_REPEATER_ALT: case MOD_FLECHETTE: - if ( gender == GENDER_FEMALE ) + if (gender == GENDER_FEMALE) message = "SUICIDE_SHOT_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_SHOT_GENDERLESS"; else message = "SUICIDE_SHOT_MALE"; @@ -212,33 +204,33 @@ static void CG_Obituary( entityState_t *ent ) { case MOD_VEHICLE: case MOD_CONC: case MOD_CONC_ALT: - if ( gender == GENDER_FEMALE ) + if (gender == GENDER_FEMALE) message = "SUICIDE_EXPLOSIVES_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_EXPLOSIVES_GENDERLESS"; else message = "SUICIDE_EXPLOSIVES_MALE"; break; case MOD_DEMP2: - if ( gender == GENDER_FEMALE ) + if (gender == GENDER_FEMALE) message = "SUICIDE_ELECTROCUTED_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_ELECTROCUTED_GENDERLESS"; else message = "SUICIDE_ELECTROCUTED_MALE"; break; case MOD_FALLING: - if ( gender == GENDER_FEMALE ) + if (gender == GENDER_FEMALE) message = "SUICIDE_FALLDEATH_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_FALLDEATH_GENDERLESS"; else message = "SUICIDE_FALLDEATH_MALE"; break; default: - if ( gender == GENDER_FEMALE ) + if (gender == GENDER_FEMALE) message = "SUICIDE_GENERICDEATH_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_GENERICDEATH_GENDERLESS"; else message = "SUICIDE_GENERICDEATH_MALE"; @@ -246,53 +238,41 @@ static void CG_Obituary( entityState_t *ent ) { } } - if (target != attacker && target < MAX_CLIENTS && attacker < MAX_CLIENTS) - { + if (target != attacker && target < MAX_CLIENTS && attacker < MAX_CLIENTS) { goto clientkilled; } if (message) { gender = ci->gender; - if (!message[0]) - { - if ( gender == GENDER_FEMALE ) + if (!message[0]) { + if (gender == GENDER_FEMALE) message = "SUICIDE_GENERICDEATH_FEMALE"; - else if ( gender == GENDER_NEUTER ) + else if (gender == GENDER_NEUTER) message = "SUICIDE_GENERICDEATH_GENDERLESS"; else message = "SUICIDE_GENERICDEATH_MALE"; } message = (char *)CG_GetStringEdString("MP_INGAME", message); - trap->Print( "%s %s\n", targetName, message); + trap->Print("%s %s\n", targetName, message); return; } clientkilled: // check for kill messages from the current clientNum - if ( attacker == cg.snap->ps.clientNum ) { - char *s; - - if ( cgs.gametype < GT_TEAM && cgs.gametype != GT_DUEL && cgs.gametype != GT_POWERDUEL ) { - if (cgs.gametype == GT_JEDIMASTER && - attacker < MAX_CLIENTS && - !ent->isJediMaster && - !cg.snap->ps.isJediMaster && - CG_ThereIsAMaster()) - { + if (attacker == cg.snap->ps.clientNum) { + char *s; + + if (cgs.gametype < GT_TEAM && cgs.gametype != GT_DUEL && cgs.gametype != GT_POWERDUEL) { + if (cgs.gametype == GT_JEDIMASTER && attacker < MAX_CLIENTS && !ent->isJediMaster && !cg.snap->ps.isJediMaster && CG_ThereIsAMaster()) { char part1[512]; char part2[512]; trap->SE_GetStringTextString("MP_INGAME_KILLED_MESSAGE", part1, sizeof(part1)); trap->SE_GetStringTextString("MP_INGAME_JMKILLED_NOTJM", part2, sizeof(part2)); s = va("%s %s\n%s\n", part1, targetName, part2); - } - else if (cgs.gametype == GT_JEDIMASTER && - attacker < MAX_CLIENTS && - !ent->isJediMaster && - !cg.snap->ps.isJediMaster) - { //no JM, saber must be out + } else if (cgs.gametype == GT_JEDIMASTER && attacker < MAX_CLIENTS && !ent->isJediMaster && !cg.snap->ps.isJediMaster) { // no JM, saber must be out char part1[512]; trap->SE_GetStringTextString("MP_INGAME_KILLED_MESSAGE", part1, sizeof(part1)); /* @@ -302,48 +282,42 @@ static void CG_Obituary( entityState_t *ent ) { s = va("%s %s %s\n", part1, targetName, part2); */ s = va("%s %s\n", part1, targetName); - } - else if (cgs.gametype == GT_POWERDUEL) - { + } else if (cgs.gametype == GT_POWERDUEL) { s = ""; - } - else - { + } else { char sPlaceWith[256]; char sKilledStr[256]; - trap->SE_GetStringTextString("MP_INGAME_PLACE_WITH", sPlaceWith, sizeof(sPlaceWith)); + trap->SE_GetStringTextString("MP_INGAME_PLACE_WITH", sPlaceWith, sizeof(sPlaceWith)); trap->SE_GetStringTextString("MP_INGAME_KILLED_MESSAGE", sKilledStr, sizeof(sKilledStr)); - s = va("%s %s.\n%s %s %i.", sKilledStr, targetName, - CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ), - sPlaceWith, - cg.snap->ps.persistant[PERS_SCORE] ); + s = va("%s %s.\n%s %s %i.", sKilledStr, targetName, CG_PlaceString(cg.snap->ps.persistant[PERS_RANK] + 1), sPlaceWith, + cg.snap->ps.persistant[PERS_SCORE]); } } else { char sKilledStr[256]; trap->SE_GetStringTextString("MP_INGAME_KILLED_MESSAGE", sKilledStr, sizeof(sKilledStr)); - s = va("%s %s", sKilledStr, targetName ); + s = va("%s %s", sKilledStr, targetName); } - //if (!(cg_singlePlayerActive.integer && cg_cameraOrbit.integer)) { - CG_CenterPrint( s, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + // if (!(cg_singlePlayerActive.integer && cg_cameraOrbit.integer)) { + CG_CenterPrint(s, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); //} // print the text message as well } // check for double client messages - if ( !attackerInfo ) { + if (!attackerInfo) { attacker = ENTITYNUM_WORLD; - strcpy( attackerName, "noname" ); + strcpy(attackerName, "noname"); } else { - Q_strncpyz( attackerName, Info_ValueForKey( attackerInfo, "n" ), sizeof(attackerName) - 2); - strcat( attackerName, S_COLOR_WHITE ); + Q_strncpyz(attackerName, Info_ValueForKey(attackerInfo, "n"), sizeof(attackerName) - 2); + strcat(attackerName, S_COLOR_WHITE); // check for kill messages about the current clientNum - if ( target == cg.snap->ps.clientNum ) { - Q_strncpyz( cg.killerName, attackerName, sizeof( cg.killerName ) ); + if (target == cg.snap->ps.clientNum) { + Q_strncpyz(cg.killerName, attackerName, sizeof(cg.killerName)); } } - if ( attacker != ENTITYNUM_WORLD ) { + if (attacker != ENTITYNUM_WORLD) { switch (mod) { case MOD_STUN_BATON: message = "KILLED_STUN"; @@ -427,13 +401,13 @@ static void CG_Obituary( entityState_t *ent ) { message = "KILLED_TELEFRAG"; break; case MOD_CRUSH: - message = "KILLED_GENERIC";//"KILLED_FORCETOSS"; + message = "KILLED_GENERIC"; //"KILLED_FORCETOSS"; break; case MOD_FALLING: message = "KILLED_FORCETOSS"; break; case MOD_TRIGGER_HURT: - message = "KILLED_GENERIC";//"KILLED_FORCETOSS"; + message = "KILLED_GENERIC"; //"KILLED_FORCETOSS"; break; default: message = "KILLED_GENERIC"; @@ -443,27 +417,23 @@ static void CG_Obituary( entityState_t *ent ) { if (message) { message = (char *)CG_GetStringEdString("MP_INGAME", message); - trap->Print( "%s %s %s\n", - targetName, message, attackerName); + trap->Print("%s %s %s\n", targetName, message, attackerName); return; } } // we don't know what it was - trap->Print( "%s %s\n", targetName, (char *)CG_GetStringEdString("MP_INGAME", "DIED_GENERIC") ); + trap->Print("%s %s\n", targetName, (char *)CG_GetStringEdString("MP_INGAME", "DIED_GENERIC")); } //========================================================================== -void CG_ToggleBinoculars(centity_t *cent, int forceZoom) -{ - if (cent->currentState.number != cg.snap->ps.clientNum) - { +void CG_ToggleBinoculars(centity_t *cent, int forceZoom) { + if (cent->currentState.number != cg.snap->ps.clientNum) { return; } - if (cg.snap->ps.weaponstate != WEAPON_READY) - { //So we can't fool it and reactivate while switching to the saber or something. + if (cg.snap->ps.weaponstate != WEAPON_READY) { // So we can't fool it and reactivate while switching to the saber or something. return; } @@ -474,35 +444,27 @@ void CG_ToggleBinoculars(centity_t *cent, int forceZoom) } */ - if (forceZoom) - { - if (forceZoom == 2) - { + if (forceZoom) { + if (forceZoom == 2) { cg.snap->ps.zoomMode = 0; - } - else if (forceZoom == 1) - { + } else if (forceZoom == 1) { cg.snap->ps.zoomMode = 2; } } - if (cg.snap->ps.zoomMode == 0) - { - trap->S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart ); - } - else if (cg.snap->ps.zoomMode == 2) - { - trap->S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd ); + if (cg.snap->ps.zoomMode == 0) { + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomStart); + } else if (cg.snap->ps.zoomMode == 2) { + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.zoomEnd); } } -//set the local timing bar +// set the local timing bar extern int cg_genericTimerBar; extern int cg_genericTimerDur; extern vec4_t cg_genericTimerColor; -void CG_LocalTimingBar(int startTime, int duration) -{ - cg_genericTimerBar = startTime + duration; +void CG_LocalTimingBar(int startTime, int duration) { + cg_genericTimerBar = startTime + duration; cg_genericTimerDur = duration; cg_genericTimerColor[0] = 1.0f; @@ -516,29 +478,29 @@ void CG_LocalTimingBar(int startTime, int duration) CG_UseItem =============== */ -static void CG_UseItem( centity_t *cent ) { +static void CG_UseItem(centity_t *cent) { clientInfo_t *ci; - int itemNum, clientNum; + int itemNum, clientNum; entityState_t *es; es = ¢->currentState; itemNum = (es->event & ~EV_EVENT_BITS) - EV_USE_ITEM0; - if ( itemNum < 0 || itemNum > HI_NUM_HOLDABLE ) { + if (itemNum < 0 || itemNum > HI_NUM_HOLDABLE) { itemNum = 0; } // print a message if the local player - if ( es->number == cg.snap->ps.clientNum ) { - if ( !itemNum ) { - //CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + if (es->number == cg.snap->ps.clientNum) { + if (!itemNum) { + // CG_CenterPrint( "No item to use", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); } } - switch ( itemNum ) { + switch (itemNum) { default: case HI_NONE: - //trap->S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.useNothingSound ); + // trap->S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.useNothingSound ); break; case HI_BINOCULARS: @@ -546,47 +508,46 @@ static void CG_UseItem( centity_t *cent ) { break; case HI_SEEKER: - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.deploySeeker ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.deploySeeker); break; case HI_SHIELD: case HI_SENTRY_GUN: break; -// case HI_MEDKIT: + // case HI_MEDKIT: case HI_MEDPAC: case HI_MEDPAC_BIG: clientNum = cent->currentState.clientNum; - if ( clientNum >= 0 && clientNum < MAX_CLIENTS ) { - ci = &cgs.clientinfo[ clientNum ]; + if (clientNum >= 0 && clientNum < MAX_CLIENTS) { + ci = &cgs.clientinfo[clientNum]; ci->medkitUsageTime = cg.time; } - //Different sound for big bacta? - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.medkitSound ); + // Different sound for big bacta? + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.medkitSound); break; case HI_JETPACK: - break; //Do something? + break; // Do something? case HI_HEALTHDISP: - //CG_LocalTimingBar(cg.time, TOSS_DEBOUNCE_TIME); + // CG_LocalTimingBar(cg.time, TOSS_DEBOUNCE_TIME); break; case HI_AMMODISP: - //CG_LocalTimingBar(cg.time, TOSS_DEBOUNCE_TIME); + // CG_LocalTimingBar(cg.time, TOSS_DEBOUNCE_TIME); break; case HI_EWEB: break; case HI_CLOAK: - break; //Do something? + break; // Do something? } - if (cg.snap && cg.snap->ps.clientNum == cent->currentState.number && itemNum != HI_BINOCULARS && - itemNum != HI_JETPACK && itemNum != HI_HEALTHDISP && itemNum != HI_AMMODISP && itemNum != HI_CLOAK && itemNum != HI_EWEB) - { //if not using binoculars/jetpack/dispensers/cloak, we just used that item up, so switch + if (cg.snap && cg.snap->ps.clientNum == cent->currentState.number && itemNum != HI_BINOCULARS && itemNum != HI_JETPACK && itemNum != HI_HEALTHDISP && + itemNum != HI_AMMODISP && itemNum != HI_CLOAK && + itemNum != HI_EWEB) { // if not using binoculars/jetpack/dispensers/cloak, we just used that item up, so switch BG_CycleInven(&cg.snap->ps, 1); - cg.itemSelect = -1; //update the client-side selection display + cg.itemSelect = -1; // update the client-side selection display } } - /* ================ CG_ItemPickup @@ -594,45 +555,31 @@ CG_ItemPickup A new item was picked up this frame ================ */ -static void CG_ItemPickup( int itemNum ) { +static void CG_ItemPickup(int itemNum) { cg.itemPickup = itemNum; cg.itemPickupTime = cg.time; cg.itemPickupBlendTime = cg.time; // see if it should be the grabbed weapon - if ( cg.snap && bg_itemlist[itemNum].giType == IT_WEAPON ) { + if (cg.snap && bg_itemlist[itemNum].giType == IT_WEAPON) { // 0 == no switching // 1 == automatically switch to best SAFE weapon // 2 == automatically switch to best weapon, safe or otherwise // 3 == if not saber, automatically switch to best weapon, safe or otherwise - if (0 == cg_autoSwitch.integer) - { + if (0 == cg_autoSwitch.integer) { // don't switch - } - else if ( cg_autoSwitch.integer == 1) - { //only autoselect if not explosive ("safe") - if (bg_itemlist[itemNum].giTag != WP_TRIP_MINE && - bg_itemlist[itemNum].giTag != WP_DET_PACK && - bg_itemlist[itemNum].giTag != WP_THERMAL && - bg_itemlist[itemNum].giTag != WP_ROCKET_LAUNCHER && - bg_itemlist[itemNum].giTag > cg.snap->ps.weapon && - cg.snap->ps.weapon != WP_SABER) - { - if (!cg.snap->ps.emplacedIndex) - { + } else if (cg_autoSwitch.integer == 1) { // only autoselect if not explosive ("safe") + if (bg_itemlist[itemNum].giTag != WP_TRIP_MINE && bg_itemlist[itemNum].giTag != WP_DET_PACK && bg_itemlist[itemNum].giTag != WP_THERMAL && + bg_itemlist[itemNum].giTag != WP_ROCKET_LAUNCHER && bg_itemlist[itemNum].giTag > cg.snap->ps.weapon && cg.snap->ps.weapon != WP_SABER) { + if (!cg.snap->ps.emplacedIndex) { cg.weaponSelectTime = cg.time; } cg.weaponSelect = bg_itemlist[itemNum].giTag; } - } - else if ( cg_autoSwitch.integer == 2) - { //autoselect if better - if (bg_itemlist[itemNum].giTag > cg.snap->ps.weapon && - cg.snap->ps.weapon != WP_SABER) - { - if (!cg.snap->ps.emplacedIndex) - { + } else if (cg_autoSwitch.integer == 2) { // autoselect if better + if (bg_itemlist[itemNum].giTag > cg.snap->ps.weapon && cg.snap->ps.weapon != WP_SABER) { + if (!cg.snap->ps.emplacedIndex) { cg.weaponSelectTime = cg.time; } cg.weaponSelect = bg_itemlist[itemNum].giTag; @@ -652,30 +599,27 @@ static void CG_ItemPickup( int itemNum ) { } } */ - //No longer required - just not switching ever if using saber + // No longer required - just not switching ever if using saber } - //rww - print pickup messages + // rww - print pickup messages if (bg_itemlist[itemNum].classname && bg_itemlist[itemNum].classname[0] && - (bg_itemlist[itemNum].giType != IT_TEAM || (bg_itemlist[itemNum].giTag != PW_REDFLAG && bg_itemlist[itemNum].giTag != PW_BLUEFLAG)) ) - { //don't print messages for flags, they have their own pickup event broadcasts - char text[1024]; - char upperKey[1024]; + (bg_itemlist[itemNum].giType != IT_TEAM || + (bg_itemlist[itemNum].giTag != PW_REDFLAG && + bg_itemlist[itemNum].giTag != PW_BLUEFLAG))) { // don't print messages for flags, they have their own pickup event broadcasts + char text[1024]; + char upperKey[1024]; strcpy(upperKey, bg_itemlist[itemNum].classname); - if ( trap->SE_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text ))) - { + if (trap->SE_GetStringTextString(va("SP_INGAME_%s", Q_strupr(upperKey)), text, sizeof(text))) { Com_Printf("%s %s\n", CG_GetStringEdString("MP_INGAME", "PICKUPLINE"), text); - } - else - { + } else { Com_Printf("%s %s\n", CG_GetStringEdString("MP_INGAME", "PICKUPLINE"), bg_itemlist[itemNum].classname); } } } - /* ================ CG_PainEvent @@ -683,49 +627,42 @@ CG_PainEvent Also called by playerstate transition ================ */ -void CG_PainEvent( centity_t *cent, int health ) { - char *snd; +void CG_PainEvent(centity_t *cent, int health) { + char *snd; // don't do more than two pain sounds a second - if ( cg.time - cent->pe.painTime < 500 ) { + if (cg.time - cent->pe.painTime < 500) { return; } - if ( health < 25 ) { + if (health < 25) { snd = "*pain25.wav"; - } else if ( health < 50 ) { + } else if (health < 50) { snd = "*pain50.wav"; - } else if ( health < 75 ) { + } else if (health < 75) { snd = "*pain75.wav"; } else { snd = "*pain100.wav"; } - trap->S_StartSound( NULL, cent->currentState.number, CHAN_VOICE, - CG_CustomSound( cent->currentState.number, snd ) ); + trap->S_StartSound(NULL, cent->currentState.number, CHAN_VOICE, CG_CustomSound(cent->currentState.number, snd)); // save pain time for programitic twitch animation cent->pe.painTime = cg.time; - cent->pe.painDirection ^= 1; + cent->pe.painDirection ^= 1; } -extern qboolean BG_GetRootSurfNameWithVariant( void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize ); -void CG_ReattachLimb(centity_t *source) -{ +extern qboolean BG_GetRootSurfNameWithVariant(void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize); +void CG_ReattachLimb(centity_t *source) { clientInfo_t *ci = NULL; - if ( source->currentState.number >= MAX_CLIENTS ) - { + if (source->currentState.number >= MAX_CLIENTS) { ci = source->npcClient; - } - else - { + } else { ci = &cgs.clientinfo[source->currentState.number]; } - if ( ci ) - {//re-apply the skin - if ( ci->torsoSkin > 0 ) - { - trap->G2API_SetSkin(source->ghoul2,0,ci->torsoSkin,ci->torsoSkin); + if (ci) { // re-apply the skin + if (ci->torsoSkin > 0) { + trap->G2API_SetSkin(source->ghoul2, 0, ci->torsoSkin, ci->torsoSkin); } } @@ -786,25 +723,22 @@ void CG_ReattachLimb(centity_t *source) source->ghoul2weapon = NULL; } -const char *CG_TeamName(int team) -{ - if (team==TEAM_RED) +const char *CG_TeamName(int team) { + if (team == TEAM_RED) return "RED"; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return "BLUE"; - else if (team==TEAM_SPECTATOR) + else if (team == TEAM_SPECTATOR) return "SPECTATOR"; return "FREE"; } -void CG_PrintCTFMessage(clientInfo_t *ci, const char *teamName, int ctfMessage) -{ +void CG_PrintCTFMessage(clientInfo_t *ci, const char *teamName, int ctfMessage) { char printMsg[1024]; char *refName = NULL; const char *psStringEDString = NULL; - switch (ctfMessage) - { + switch (ctfMessage) { case CTFMESSAGE_FRAGGED_FLAG_CARRIER: refName = "FRAGGED_FLAG_CARRIER"; break; @@ -826,39 +760,30 @@ void CG_PrintCTFMessage(clientInfo_t *ci, const char *teamName, int ctfMessage) psStringEDString = CG_GetStringEdString("MP_INGAME", refName); - if (!psStringEDString || !psStringEDString[0]) - { + if (!psStringEDString || !psStringEDString[0]) { return; } - if (teamName && teamName[0]) - { + if (teamName && teamName[0]) { const char *f = strstr(psStringEDString, "%s"); - if (f) - { + if (f) { int strLen = 0; int i = 0; - if (ci) - { + if (ci) { Com_sprintf(printMsg, sizeof(printMsg), "%s^7 ", ci->name); strLen = strlen(printMsg); } - while (psStringEDString[i] && i < 512) - { - if (psStringEDString[i] == '%' && - psStringEDString[i+1] == 's') - { + while (psStringEDString[i] && i < 512) { + if (psStringEDString[i] == '%' && psStringEDString[i + 1] == 's') { printMsg[strLen] = '\0'; Q_strcat(printMsg, sizeof(printMsg), teamName); strLen = strlen(printMsg); i++; - } - else - { + } else { printMsg[strLen] = psStringEDString[i]; strLen++; } @@ -872,12 +797,9 @@ void CG_PrintCTFMessage(clientInfo_t *ci, const char *teamName, int ctfMessage) } } - if (ci) - { + if (ci) { Com_sprintf(printMsg, sizeof(printMsg), "%s^7 %s", ci->name, psStringEDString); - } - else - { + } else { Com_sprintf(printMsg, sizeof(printMsg), "%s", psStringEDString); } @@ -885,178 +807,136 @@ void CG_PrintCTFMessage(clientInfo_t *ci, const char *teamName, int ctfMessage) Com_Printf("%s\n", printMsg); } -void CG_GetCTFMessageEvent(entityState_t *es) -{ +void CG_GetCTFMessageEvent(entityState_t *es) { int clIndex = es->trickedentindex; int teamIndex = es->trickedentindex2; clientInfo_t *ci = NULL; const char *teamName = NULL; - if (clIndex < MAX_CLIENTS) - { + if (clIndex < MAX_CLIENTS) { ci = &cgs.clientinfo[clIndex]; } - if (teamIndex < 50) - { + if (teamIndex < 50) { teamName = CG_TeamName(teamIndex); } - if (!ci) - { + if (!ci) { return; } CG_PrintCTFMessage(ci, teamName, es->eventParm); } -qboolean BG_InKnockDownOnly( int anim ); +qboolean BG_InKnockDownOnly(int anim); -void DoFall(centity_t *cent, entityState_t *es, int clientNum) -{ +void DoFall(centity_t *cent, entityState_t *es, int clientNum) { int delta = es->eventParm; - if (cent->currentState.eFlags & EF_DEAD) - { //corpses crack into the ground ^_^ - if (delta > 25) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.fallSound ); - } - else - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, trap->S_RegisterSound( "sound/movers/objects/objectHit.wav" ) ); - } - } - else if (BG_InKnockDownOnly(es->legsAnim)) - { - if (delta > 14) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.fallSound ); - } - else - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, trap->S_RegisterSound( "sound/movers/objects/objectHit.wav" ) ); + if (cent->currentState.eFlags & EF_DEAD) { // corpses crack into the ground ^_^ + if (delta > 25) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.fallSound); + } else { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, trap->S_RegisterSound("sound/movers/objects/objectHit.wav")); } - } - else if (delta > 50) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.fallSound ); - trap->S_StartSound( NULL, cent->currentState.number, CHAN_VOICE, - CG_CustomSound( cent->currentState.number, "*land1.wav" ) ); - cent->pe.painTime = cg.time; // don't play a pain sound right after this - } - else if (delta > 44) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.fallSound ); - trap->S_StartSound( NULL, cent->currentState.number, CHAN_VOICE, - CG_CustomSound( cent->currentState.number, "*land1.wav" ) ); - cent->pe.painTime = cg.time; // don't play a pain sound right after this - } - else - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.landSound ); + } else if (BG_InKnockDownOnly(es->legsAnim)) { + if (delta > 14) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.fallSound); + } else { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, trap->S_RegisterSound("sound/movers/objects/objectHit.wav")); + } + } else if (delta > 50) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.fallSound); + trap->S_StartSound(NULL, cent->currentState.number, CHAN_VOICE, CG_CustomSound(cent->currentState.number, "*land1.wav")); + cent->pe.painTime = cg.time; // don't play a pain sound right after this + } else if (delta > 44) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.fallSound); + trap->S_StartSound(NULL, cent->currentState.number, CHAN_VOICE, CG_CustomSound(cent->currentState.number, "*land1.wav")); + cent->pe.painTime = cg.time; // don't play a pain sound right after this + } else { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.landSound); } - if ( clientNum == cg.predictedPlayerState.clientNum ) - { + if (clientNum == cg.predictedPlayerState.clientNum) { // smooth landing z changes cg.landChange = -delta; - if (cg.landChange > 32) - { + if (cg.landChange > 32) { cg.landChange = 32; } - if (cg.landChange < -32) - { + if (cg.landChange < -32) { cg.landChange = -32; } cg.landTime = cg.time; } } -int CG_InClientBitflags(entityState_t *ent, int client) -{ +int CG_InClientBitflags(entityState_t *ent, int client) { int checkIn; int sub = 0; - if (client > 47) - { + if (client > 47) { checkIn = ent->trickedentindex4; sub = 48; - } - else if (client > 31) - { + } else if (client > 31) { checkIn = ent->trickedentindex3; sub = 32; - } - else if (client > 15) - { + } else if (client > 15) { checkIn = ent->trickedentindex2; sub = 16; - } - else - { + } else { checkIn = ent->trickedentindex; } - if (checkIn & (1 << (client-sub))) - { + if (checkIn & (1 << (client - sub))) { return 1; } return 0; } -void CG_PlayDoorLoopSound( centity_t *cent ); -void CG_PlayDoorSound( centity_t *cent, int type ); +void CG_PlayDoorLoopSound(centity_t *cent); +void CG_PlayDoorSound(centity_t *cent, int type); -void CG_TryPlayCustomSound( vec3_t origin, int entityNum, int channel, const char *soundName ) -{ +void CG_TryPlayCustomSound(vec3_t origin, int entityNum, int channel, const char *soundName) { sfxHandle_t cSound = CG_CustomSound(entityNum, soundName); - if (cSound <= 0) - { + if (cSound <= 0) { return; } trap->S_StartSound(origin, entityNum, channel, cSound); } -void CG_G2MarkEvent(entityState_t *es) -{ - //es->origin should be the hit location of the projectile, - //whereas es->origin2 is the predicted position of the - //projectile. (based on the trajectory upon impact) -rww +void CG_G2MarkEvent(entityState_t *es) { + // es->origin should be the hit location of the projectile, + // whereas es->origin2 is the predicted position of the + // projectile. (based on the trajectory upon impact) -rww centity_t *pOwner = &cg_entities[es->otherEntityNum]; vec3_t startPoint; - float size = 0.0f; + float size = 0.0f; qhandle_t shader = 0; - if (!pOwner->ghoul2) - { //can't do anything then... + if (!pOwner->ghoul2) { // can't do anything then... return; } - //es->eventParm being non-0 means to do a special trace check - //first. This will give us an impact right at the surface to - //project the mark on. Typically this is used for radius - //explosions and such, where the source position could be - //way outside of model space. - if (es->eventParm) - { + // es->eventParm being non-0 means to do a special trace check + // first. This will give us an impact right at the surface to + // project the mark on. Typically this is used for radius + // explosions and such, where the source position could be + // way outside of model space. + if (es->eventParm) { trace_t tr; int ignore = ENTITYNUM_NONE; CG_G2Trace(&tr, es->origin, NULL, NULL, es->origin2, ignore, MASK_PLAYERSOLID); - if (tr.entityNum != es->otherEntityNum) - { //try again if we hit an ent but not the one we wanted. - //CG_TestLine(es->origin, es->origin2, 2000, 0x0000ff, 1); - if (tr.entityNum < ENTITYNUM_WORLD) - { + if (tr.entityNum != es->otherEntityNum) { // try again if we hit an ent but not the one we wanted. + // CG_TestLine(es->origin, es->origin2, 2000, 0x0000ff, 1); + if (tr.entityNum < ENTITYNUM_WORLD) { ignore = tr.entityNum; CG_G2Trace(&tr, es->origin, NULL, NULL, es->origin2, ignore, MASK_PLAYERSOLID); - if (tr.entityNum != es->otherEntityNum) - { //try extending the trace a bit.. or not + if (tr.entityNum != es->otherEntityNum) { // try extending the trace a bit.. or not /* vec3_t v; @@ -1070,39 +950,31 @@ void CG_G2MarkEvent(entityState_t *es) return; } */ - //didn't manage to collide with the desired person. No mark will be placed then. + // didn't manage to collide with the desired person. No mark will be placed then. return; } } } - //otherwise we now have a valid starting point. + // otherwise we now have a valid starting point. VectorCopy(tr.endpos, startPoint); - } - else - { + } else { VectorCopy(es->origin, startPoint); } - if ( (es->eFlags&EF_JETPACK_ACTIVE) ) - {// a vehicle weapon, make it a larger size mark - //OR base this on the size of the thing you hit? - if ( g_vehWeaponInfo[es->otherEntityNum2].fG2MarkSize ) - { - size = flrand( 0.6f, 1.4f )*g_vehWeaponInfo[es->otherEntityNum2].fG2MarkSize; - } - else - { - size = flrand( 32.0f, 72.0f ); + if ((es->eFlags & EF_JETPACK_ACTIVE)) { // a vehicle weapon, make it a larger size mark + // OR base this on the size of the thing you hit? + if (g_vehWeaponInfo[es->otherEntityNum2].fG2MarkSize) { + size = flrand(0.6f, 1.4f) * g_vehWeaponInfo[es->otherEntityNum2].fG2MarkSize; + } else { + size = flrand(32.0f, 72.0f); } - //specify mark shader in vehWeapon file - if ( g_vehWeaponInfo[es->otherEntityNum2].iG2MarkShaderHandle ) - {//have one we want to use instead of defaults + // specify mark shader in vehWeapon file + if (g_vehWeaponInfo[es->otherEntityNum2].iG2MarkShaderHandle) { // have one we want to use instead of defaults shader = g_vehWeaponInfo[es->otherEntityNum2].iG2MarkShaderHandle; } } - switch(es->weapon) - { + switch (es->weapon) { case WP_BRYAR_PISTOL: case WP_CONCUSSION: case WP_BRYAR_OLD: @@ -1111,33 +983,25 @@ void CG_G2MarkEvent(entityState_t *es) case WP_BOWCASTER: case WP_REPEATER: case WP_TURRET: - if ( !size ) - { + if (!size) { size = 4.0f; } - if ( !shader ) - { + if (!shader) { shader = cgs.media.bdecal_bodyburn1; } - CG_AddGhoul2Mark(shader, size, - startPoint, es->origin2, es->owner, pOwner->lerpOrigin, - pOwner->lerpAngles[YAW], pOwner->ghoul2, - pOwner->modelScale, Q_irand(10000, 20000)); + CG_AddGhoul2Mark(shader, size, startPoint, es->origin2, es->owner, pOwner->lerpOrigin, pOwner->lerpAngles[YAW], pOwner->ghoul2, pOwner->modelScale, + Q_irand(10000, 20000)); break; case WP_ROCKET_LAUNCHER: case WP_THERMAL: - if ( !size ) - { + if (!size) { size = 24.0f; } - if ( !shader ) - { + if (!shader) { shader = cgs.media.bdecal_burn1; } - CG_AddGhoul2Mark(shader, size, - startPoint, es->origin2, es->owner, pOwner->lerpOrigin, - pOwner->lerpAngles[YAW], pOwner->ghoul2, - pOwner->modelScale, Q_irand(10000, 20000)); + CG_AddGhoul2Mark(shader, size, startPoint, es->origin2, es->owner, pOwner->lerpOrigin, pOwner->lerpAngles[YAW], pOwner->ghoul2, pOwner->modelScale, + Q_irand(10000, 20000)); break; /* case WP_FLECHETTE: @@ -1147,134 +1011,110 @@ void CG_G2MarkEvent(entityState_t *es) pOwner->modelScale); break; */ - //Issues with small scale? + // Issues with small scale? default: break; } } -void CG_CalcVehMuzzle(Vehicle_t *pVeh, centity_t *ent, int muzzleNum) -{ +void CG_CalcVehMuzzle(Vehicle_t *pVeh, centity_t *ent, int muzzleNum) { mdxaBone_t boltMatrix; - vec3_t vehAngles; + vec3_t vehAngles; assert(pVeh); - if (pVeh->m_iMuzzleTime[muzzleNum] == cg.time) - { //already done for this frame, don't need to do it again + if (pVeh->m_iMuzzleTime[muzzleNum] == cg.time) { // already done for this frame, don't need to do it again return; } - //Uh... how about we set this, hunh...? :) + // Uh... how about we set this, hunh...? :) pVeh->m_iMuzzleTime[muzzleNum] = cg.time; - VectorCopy( ent->lerpAngles, vehAngles ); - if ( pVeh->m_pVehicleInfo ) - { - if (pVeh->m_pVehicleInfo->type == VH_ANIMAL - ||pVeh->m_pVehicleInfo->type == VH_WALKER) - { + VectorCopy(ent->lerpAngles, vehAngles); + if (pVeh->m_pVehicleInfo) { + if (pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_WALKER) { vehAngles[PITCH] = vehAngles[ROLL] = 0.0f; - } - else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) - { + } else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { vehAngles[PITCH] = 0.0f; } } - trap->G2API_GetBoltMatrix_NoRecNoRot(ent->ghoul2, 0, pVeh->m_iMuzzleTag[muzzleNum], &boltMatrix, vehAngles, - ent->lerpOrigin, cg.time, NULL, ent->modelScale); + trap->G2API_GetBoltMatrix_NoRecNoRot(ent->ghoul2, 0, pVeh->m_iMuzzleTag[muzzleNum], &boltMatrix, vehAngles, ent->lerpOrigin, cg.time, NULL, + ent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pVeh->m_vMuzzlePos[muzzleNum]); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, pVeh->m_vMuzzleDir[muzzleNum]); } -//corresponds to G_VehMuzzleFireFX -rww -void CG_VehMuzzleFireFX(centity_t *veh, entityState_t *broadcaster) -{ +// corresponds to G_VehMuzzleFireFX -rww +void CG_VehMuzzleFireFX(centity_t *veh, entityState_t *broadcaster) { Vehicle_t *pVeh = veh->m_pVehicle; int curMuz = 0, muzFX = 0; - if (!pVeh || !veh->ghoul2) - { + if (!pVeh || !veh->ghoul2) { return; } - for ( curMuz = 0; curMuz < MAX_VEHICLE_MUZZLES; curMuz++ ) - {//go through all muzzles and - if ( pVeh->m_iMuzzleTag[curMuz] != -1//valid muzzle bolt - && (broadcaster->trickedentindex&(1<m_iMuzzleTag[curMuz] != -1 // valid muzzle bolt + && (broadcaster->trickedentindex & (1 << curMuz))) // fired + { // this muzzle fired muzFX = 0; - if ( pVeh->m_pVehicleInfo->weapMuzzle[curMuz] == 0 ) - {//no weaopon for this muzzle? check turrets + if (pVeh->m_pVehicleInfo->weapMuzzle[curMuz] == 0) { // no weaopon for this muzzle? check turrets int i, j; - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - for ( j = 0; j < MAX_VEHICLE_TURRETS; j++ ) - { - if ( pVeh->m_pVehicleInfo->turret[i].iMuzzle[j]-1 == curMuz ) - {//this muzzle belongs to this turret + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + for (j = 0; j < MAX_VEHICLE_TURRETS; j++) { + if (pVeh->m_pVehicleInfo->turret[i].iMuzzle[j] - 1 == curMuz) { // this muzzle belongs to this turret muzFX = g_vehWeaponInfo[pVeh->m_pVehicleInfo->turret[i].iWeapon].iMuzzleFX; break; } } } - } - else - { + } else { muzFX = g_vehWeaponInfo[pVeh->m_pVehicleInfo->weapMuzzle[curMuz]].iMuzzleFX; } - if ( muzFX ) - { - //CG_CalcVehMuzzle(pVeh, veh, curMuz); - //trap->FX_PlayEffectID(muzFX, pVeh->m_vMuzzlePos[curMuz], pVeh->m_vMuzzleDir[curMuz], -1, -1, qfalse); + if (muzFX) { + // CG_CalcVehMuzzle(pVeh, veh, curMuz); + // trap->FX_PlayEffectID(muzFX, pVeh->m_vMuzzlePos[curMuz], pVeh->m_vMuzzleDir[curMuz], -1, -1, qfalse); trap->FX_PlayBoltedEffectID(muzFX, veh->currentState.origin, veh->ghoul2, pVeh->m_iMuzzleTag[curMuz], veh->currentState.number, 0, 0, qtrue); } } } } -const char *cg_stringEdVoiceChatTable[MAX_CUSTOM_SIEGE_SOUNDS] = -{ - "VC_ATT",//"*att_attack", - "VC_ATT_PRIMARY",//"*att_primary", - "VC_ATT_SECONDARY",//"*att_second", - "VC_DEF_GUNS",//"*def_guns", - "VC_DEF_POSITION",//"*def_position", - "VC_DEF_PRIMARY",//"*def_primary", - "VC_DEF_SECONDARY",//"*def_second", - "VC_REPLY_COMING",//"*reply_coming", - "VC_REPLY_GO",//"*reply_go", - "VC_REPLY_NO",//"*reply_no", - "VC_REPLY_STAY",//"*reply_stay", - "VC_REPLY_YES",//"*reply_yes", - "VC_REQ_ASSIST",//"*req_assist", - "VC_REQ_DEMO",//"*req_demo", - "VC_REQ_HVY",//"*req_hvy", - "VC_REQ_MEDIC",//"*req_medic", - "VC_REQ_SUPPLY",//"*req_sup", - "VC_REQ_TECH",//"*req_tech", - "VC_SPOT_AIR",//"*spot_air", - "VC_SPOT_DEF",//"*spot_defenses", - "VC_SPOT_EMPLACED",//"*spot_emplaced", - "VC_SPOT_SNIPER",//"*spot_sniper", - "VC_SPOT_TROOP",//"*spot_troops", - "VC_TAC_COVER",//"*tac_cover", - "VC_TAC_FALLBACK",//"*tac_fallback", - "VC_TAC_FOLLOW",//"*tac_follow", - "VC_TAC_HOLD",//"*tac_hold", - "VC_TAC_SPLIT",//"*tac_split", - "VC_TAC_TOGETHER",//"*tac_together", - NULL -}; - -//stupid way of figuring out what string to use for voice chats -const char *CG_GetStringForVoiceSound(const char *s) -{ +const char *cg_stringEdVoiceChatTable[MAX_CUSTOM_SIEGE_SOUNDS] = {"VC_ATT", //"*att_attack", + "VC_ATT_PRIMARY", //"*att_primary", + "VC_ATT_SECONDARY", //"*att_second", + "VC_DEF_GUNS", //"*def_guns", + "VC_DEF_POSITION", //"*def_position", + "VC_DEF_PRIMARY", //"*def_primary", + "VC_DEF_SECONDARY", //"*def_second", + "VC_REPLY_COMING", //"*reply_coming", + "VC_REPLY_GO", //"*reply_go", + "VC_REPLY_NO", //"*reply_no", + "VC_REPLY_STAY", //"*reply_stay", + "VC_REPLY_YES", //"*reply_yes", + "VC_REQ_ASSIST", //"*req_assist", + "VC_REQ_DEMO", //"*req_demo", + "VC_REQ_HVY", //"*req_hvy", + "VC_REQ_MEDIC", //"*req_medic", + "VC_REQ_SUPPLY", //"*req_sup", + "VC_REQ_TECH", //"*req_tech", + "VC_SPOT_AIR", //"*spot_air", + "VC_SPOT_DEF", //"*spot_defenses", + "VC_SPOT_EMPLACED", //"*spot_emplaced", + "VC_SPOT_SNIPER", //"*spot_sniper", + "VC_SPOT_TROOP", //"*spot_troops", + "VC_TAC_COVER", //"*tac_cover", + "VC_TAC_FALLBACK", //"*tac_fallback", + "VC_TAC_FOLLOW", //"*tac_follow", + "VC_TAC_HOLD", //"*tac_hold", + "VC_TAC_SPLIT", //"*tac_split", + "VC_TAC_TOGETHER", //"*tac_together", + NULL}; + +// stupid way of figuring out what string to use for voice chats +const char *CG_GetStringForVoiceSound(const char *s) { int i = 0; - while (i < MAX_CUSTOM_SIEGE_SOUNDS) - { - if (bg_customSiegeSoundNames[i] && - !Q_stricmp(bg_customSiegeSoundNames[i], s)) - { //get the matching reference name + while (i < MAX_CUSTOM_SIEGE_SOUNDS) { + if (bg_customSiegeSoundNames[i] && !Q_stricmp(bg_customSiegeSoundNames[i], s)) { // get the matching reference name assert(cg_stringEdVoiceChatTable[i]); return CG_GetStringEdString("MENUS", (char *)cg_stringEdVoiceChatTable[i]); } @@ -1292,45 +1132,45 @@ An entity has an event value also called by CG_CheckPlayerstateEvents ============== */ -#define DEBUGNAME(x) if(cg_debugEvents.integer){trap->Print(x"\n");} -extern void CG_ChatBox_AddString(char *chatStr); //cg_draw.c -void CG_EntityEvent( centity_t *cent, vec3_t position ) { - entityState_t *es; - int event; - vec3_t dir; - const char *s; - int clientNum; - int eID = 0; - int isnd = 0; - centity_t *cl_ent; +#define DEBUGNAME(x) \ + if (cg_debugEvents.integer) { \ + trap->Print(x "\n"); \ + } +extern void CG_ChatBox_AddString(char *chatStr); // cg_draw.c +void CG_EntityEvent(centity_t *cent, vec3_t position) { + entityState_t *es; + int event; + vec3_t dir; + const char *s; + int clientNum; + int eID = 0; + int isnd = 0; + centity_t *cl_ent; es = ¢->currentState; event = es->event & ~EV_EVENT_BITS; - if ( cg_debugEvents.integer ) { - trap->Print( "ent:%3i event:%3i ", es->number, event ); + if (cg_debugEvents.integer) { + trap->Print("ent:%3i event:%3i ", es->number, event); } - if ( !event ) { + if (!event) { DEBUGNAME("ZEROEVENT"); return; } clientNum = es->clientNum; - if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) { + if (clientNum < 0 || clientNum >= MAX_CLIENTS) { clientNum = 0; } - if (es->eType == ET_NPC) - { + if (es->eType == ET_NPC) { clientNum = es->number; - if (!cent->npcClient) - { - CG_CreateNPCClient(¢->npcClient); //allocate memory for it + if (!cent->npcClient) { + CG_CreateNPCClient(¢->npcClient); // allocate memory for it - if (!cent->npcClient) - { + if (!cent->npcClient) { assert(0); return; } @@ -1339,28 +1179,27 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { cent->npcClient->ghoul2Model = NULL; } - assert( cent->npcClient ); + assert(cent->npcClient); } - switch ( event ) { + switch (event) { // // movement generated events // case EV_CLIENTJOIN: DEBUGNAME("EV_CLIENTJOIN"); - //Slight hack to force a local reinit of client entity on join. + // Slight hack to force a local reinit of client entity on join. cl_ent = &cg_entities[es->eventParm]; - if (cl_ent) - { - //cl_ent->torsoBolt = 0; + if (cl_ent) { + // cl_ent->torsoBolt = 0; cl_ent->bolt1 = 0; cl_ent->bolt2 = 0; cl_ent->bolt3 = 0; cl_ent->bolt4 = 0; - cl_ent->bodyHeight = 0;//SABER_LENGTH_MAX; - //cl_ent->saberExtendTime = 0; + cl_ent->bodyHeight = 0; // SABER_LENGTH_MAX; + // cl_ent->saberExtendTime = 0; cl_ent->boltInfo = 0; cl_ent->frame_minus1_refreshed = 0; cl_ent->frame_minus2_refreshed = 0; @@ -1373,16 +1212,15 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { cl_ent->teamPowerEffectTime = 0; cl_ent->teamPowerType = 0; cl_ent->numLoopingSounds = 0; - //cl_ent->localAnimIndex = 0; + // cl_ent->localAnimIndex = 0; } break; case EV_FOOTSTEP: DEBUGNAME("EV_FOOTSTEP"); if (cg_footsteps.integer) { - footstep_t soundType; - switch( es->eventParm ) - { + footstep_t soundType; + switch (es->eventParm) { case MATERIAL_MUD: soundType = FOOTSTEP_MUDWALK; break; @@ -1425,43 +1263,37 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; } - trap->S_StartSound (NULL, es->number, CHAN_BODY, cgs.media.footsteps[ soundType ][rand()&3] ); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[soundType][rand() & 3]); } break; case EV_FOOTSTEP_METAL: DEBUGNAME("EV_FOOTSTEP_METAL"); if (cg_footsteps.integer) { - trap->S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_METALWALK ][rand()&3] ); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_METALWALK][rand() & 3]); } break; case EV_FOOTSPLASH: DEBUGNAME("EV_FOOTSPLASH"); if (cg_footsteps.integer) { - trap->S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] ); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SPLASH][rand() & 3]); } break; case EV_FOOTWADE: DEBUGNAME("EV_FOOTWADE"); if (cg_footsteps.integer) { - trap->S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] ); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SPLASH][rand() & 3]); } break; case EV_SWIM: DEBUGNAME("EV_SWIM"); if (cg_footsteps.integer) { - trap->S_StartSound (NULL, es->number, CHAN_BODY, - cgs.media.footsteps[ FOOTSTEP_SPLASH ][rand()&3] ); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.footsteps[FOOTSTEP_SPLASH][rand() & 3]); } break; - case EV_FALL: DEBUGNAME("EV_FALL"); - if (es->number == cg.snap->ps.clientNum && cg.snap->ps.fallingToDeath) - { + if (es->number == cg.snap->ps.clientNum && cg.snap->ps.fallingToDeath) { break; } DoFall(cent, es, clientNum); @@ -1469,38 +1301,37 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_STEP_4: case EV_STEP_8: case EV_STEP_12: - case EV_STEP_16: // smooth out step up transitions + case EV_STEP_16: // smooth out step up transitions DEBUGNAME("EV_STEP"); - { - float oldStep; - int delta; - int step; + { + float oldStep; + int delta; + int step; - if ( clientNum != cg.predictedPlayerState.clientNum ) { - break; - } - // if we are interpolating, we don't need to smooth steps - if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) || - cg_noPredict.integer || g_synchronousClients.integer ) { - break; - } - // check for stepping up before a previous step is completed - delta = cg.time - cg.stepTime; - if (delta < STEP_TIME) { - oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; - } else { - oldStep = 0; - } + if (clientNum != cg.predictedPlayerState.clientNum) { + break; + } + // if we are interpolating, we don't need to smooth steps + if (cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) || cg_noPredict.integer || g_synchronousClients.integer) { + break; + } + // check for stepping up before a previous step is completed + delta = cg.time - cg.stepTime; + if (delta < STEP_TIME) { + oldStep = cg.stepChange * (STEP_TIME - delta) / STEP_TIME; + } else { + oldStep = 0; + } - // add this amount - step = 4 * (event - EV_STEP_4 + 1 ); - cg.stepChange = oldStep + step; - if ( cg.stepChange > MAX_STEP_CHANGE ) { - cg.stepChange = MAX_STEP_CHANGE; + // add this amount + step = 4 * (event - EV_STEP_4 + 1); + cg.stepChange = oldStep + step; + if (cg.stepChange > MAX_STEP_CHANGE) { + cg.stepChange = MAX_STEP_CHANGE; + } + cg.stepTime = cg.time; + break; } - cg.stepTime = cg.time; - break; - } case EV_JUMP_PAD: DEBUGNAME("EV_JUMP_PAD"); @@ -1509,73 +1340,60 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_GHOUL2_MARK: DEBUGNAME("EV_GHOUL2_MARK"); - if (cg_ghoul2Marks.integer) - { //Can we put a burn mark on him? + if (cg_ghoul2Marks.integer) { // Can we put a burn mark on him? CG_G2MarkEvent(es); } break; case EV_GLOBAL_DUEL: DEBUGNAME("EV_GLOBAL_DUEL"); - //used for beginning of power duels - //if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR) - if (es->otherEntityNum == cg.predictedPlayerState.clientNum || - es->otherEntityNum2 == cg.predictedPlayerState.clientNum || - es->groundEntityNum == cg.predictedPlayerState.clientNum) - { - CG_CenterPrint( CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH*2 ); - trap->S_StartLocalSound( cgs.media.countFightSound, CHAN_ANNOUNCER ); + // used for beginning of power duels + // if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR) + if (es->otherEntityNum == cg.predictedPlayerState.clientNum || es->otherEntityNum2 == cg.predictedPlayerState.clientNum || + es->groundEntityNum == cg.predictedPlayerState.clientNum) { + CG_CenterPrint(CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH * 2); + trap->S_StartLocalSound(cgs.media.countFightSound, CHAN_ANNOUNCER); } break; case EV_PRIVATE_DUEL: DEBUGNAME("EV_PRIVATE_DUEL"); - if (cg.snap->ps.clientNum != es->number) - { + if (cg.snap->ps.clientNum != es->number) { break; } - if (es->eventParm) - { //starting the duel - if (es->eventParm == 2) - { - CG_CenterPrint( CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH*2 ); - trap->S_StartLocalSound( cgs.media.countFightSound, CHAN_ANNOUNCER ); - } - else - { - trap->S_StartBackgroundTrack( "music/mp/duel.mp3", "music/mp/duel.mp3", qfalse ); + if (es->eventParm) { // starting the duel + if (es->eventParm == 2) { + CG_CenterPrint(CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH * 2); + trap->S_StartLocalSound(cgs.media.countFightSound, CHAN_ANNOUNCER); + } else { + trap->S_StartBackgroundTrack("music/mp/duel.mp3", "music/mp/duel.mp3", qfalse); } - } - else - { //ending the duel + } else { // ending the duel CG_StartMusic(qtrue); } break; case EV_JUMP: DEBUGNAME("EV_JUMP"); - if (cg_jumpSounds.integer) - { - trap->S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*jump1.wav" ) ); + if (cg_jumpSounds.integer) { + trap->S_StartSound(NULL, es->number, CHAN_VOICE, CG_CustomSound(es->number, "*jump1.wav")); } break; case EV_ROLL: DEBUGNAME("EV_ROLL"); - if (es->number == cg.snap->ps.clientNum && cg.snap->ps.fallingToDeath) - { + if (es->number == cg.snap->ps.clientNum && cg.snap->ps.fallingToDeath) { break; } - if (es->eventParm) - { //fall-roll-in-one event + if (es->eventParm) { // fall-roll-in-one event DoFall(cent, es, clientNum); } - trap->S_StartSound (NULL, es->number, CHAN_VOICE, CG_CustomSound( es->number, "*jump1.wav" ) ); - trap->S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.rollSound ); + trap->S_StartSound(NULL, es->number, CHAN_VOICE, CG_CustomSound(es->number, "*jump1.wav")); + trap->S_StartSound(NULL, es->number, CHAN_BODY, cgs.media.rollSound); - //FIXME: need some sort of body impact on ground sound and maybe kick up some dust? + // FIXME: need some sort of body impact on ground sound and maybe kick up some dust? break; case EV_TAUNT: @@ -1583,134 +1401,115 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { int soundIndex = 0; - if ( cg_noTaunt.integer ) + if (cg_noTaunt.integer) break; - if ( cgs.gametype != GT_DUEL - && cgs.gametype != GT_POWERDUEL - && es->eventParm == TAUNT_TAUNT ) - {//normal taunt - soundIndex = CG_CustomSound( es->number, "*taunt.wav" ); - } - else - { - switch ( es->eventParm ) - { + if (cgs.gametype != GT_DUEL && cgs.gametype != GT_POWERDUEL && es->eventParm == TAUNT_TAUNT) { // normal taunt + soundIndex = CG_CustomSound(es->number, "*taunt.wav"); + } else { + switch (es->eventParm) { case TAUNT_TAUNT: default: - if ( Q_irand( 0, 1 ) ) - { - soundIndex = CG_CustomSound( es->number, va("*anger%d.wav", Q_irand(1,3)) ); - } - else - { - soundIndex = CG_CustomSound( es->number, va("*taunt%d.wav", Q_irand(1,3)) ); - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, va("*anger%d.wav", Q_irand(1,3)) ); + if (Q_irand(0, 1)) { + soundIndex = CG_CustomSound(es->number, va("*anger%d.wav", Q_irand(1, 3))); + } else { + soundIndex = CG_CustomSound(es->number, va("*taunt%d.wav", Q_irand(1, 3))); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, va("*anger%d.wav", Q_irand(1, 3))); } } break; case TAUNT_BOW: - //soundIndex = CG_CustomSound( es->number, va("*respect%d.wav", Q_irand(1,3)) ); + // soundIndex = CG_CustomSound( es->number, va("*respect%d.wav", Q_irand(1,3)) ); break; case TAUNT_MEDITATE: - //soundIndex = CG_CustomSound( es->number, va("*meditate%d.wav", Q_irand(1,3)) ); + // soundIndex = CG_CustomSound( es->number, va("*meditate%d.wav", Q_irand(1,3)) ); break; case TAUNT_FLOURISH: - if ( Q_irand( 0, 1 ) ) - { - soundIndex = CG_CustomSound( es->number, va("*deflect%d.wav", Q_irand(1,3)) ); - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, va("*gloat%d.wav", Q_irand(1,3)) ); - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, va("*anger%d.wav", Q_irand(1,3)) ); + if (Q_irand(0, 1)) { + soundIndex = CG_CustomSound(es->number, va("*deflect%d.wav", Q_irand(1, 3))); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, va("*gloat%d.wav", Q_irand(1, 3))); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, va("*anger%d.wav", Q_irand(1, 3))); } } - } - else - { - soundIndex = CG_CustomSound( es->number, va("*gloat%d.wav", Q_irand(1,3)) ); - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, va("*deflect%d.wav", Q_irand(1,3)) ); - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, va("*anger%d.wav", Q_irand(1,3)) ); + } else { + soundIndex = CG_CustomSound(es->number, va("*gloat%d.wav", Q_irand(1, 3))); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, va("*deflect%d.wav", Q_irand(1, 3))); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, va("*anger%d.wav", Q_irand(1, 3))); } } } break; case TAUNT_GLOAT: - soundIndex = CG_CustomSound( es->number, va("*victory%d.wav", Q_irand(1,3)) ); + soundIndex = CG_CustomSound(es->number, va("*victory%d.wav", Q_irand(1, 3))); break; } } - if ( !soundIndex ) - { - soundIndex = CG_CustomSound( es->number, "*taunt.wav" ); + if (!soundIndex) { + soundIndex = CG_CustomSound(es->number, "*taunt.wav"); } - if ( soundIndex ) - { - trap->S_StartSound (NULL, es->number, CHAN_VOICE, soundIndex ); + if (soundIndex) { + trap->S_StartSound(NULL, es->number, CHAN_VOICE, soundIndex); } } break; - //Begin NPC sounds - case EV_ANGER1: //Say when acquire an enemy when didn't have one before + // Begin NPC sounds + case EV_ANGER1: // Say when acquire an enemy when didn't have one before case EV_ANGER2: case EV_ANGER3: DEBUGNAME("EV_ANGERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*anger%i.wav", event - EV_ANGER1 + 1)); break; - case EV_VICTORY1: //Say when killed an enemy + case EV_VICTORY1: // Say when killed an enemy case EV_VICTORY2: case EV_VICTORY3: DEBUGNAME("EV_VICTORYx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*victory%i.wav", event - EV_VICTORY1 + 1)); break; - case EV_CONFUSE1: //Say when confused + case EV_CONFUSE1: // Say when confused case EV_CONFUSE2: case EV_CONFUSE3: DEBUGNAME("EV_CONFUSEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*confuse%i.wav", event - EV_CONFUSE1 + 1)); break; - case EV_PUSHED1: //Say when pushed + case EV_PUSHED1: // Say when pushed case EV_PUSHED2: case EV_PUSHED3: DEBUGNAME("EV_PUSHEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*pushed%i.wav", event - EV_PUSHED1 + 1)); break; - case EV_CHOKE1: //Say when choking + case EV_CHOKE1: // Say when choking case EV_CHOKE2: case EV_CHOKE3: DEBUGNAME("EV_CHOKEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*choke%i.wav", event - EV_CHOKE1 + 1)); break; - case EV_FFWARN: //Warn ally to stop shooting you + case EV_FFWARN: // Warn ally to stop shooting you DEBUGNAME("EV_FFWARN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffwarn.wav" ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffwarn.wav"); break; - case EV_FFTURN: //Turn on ally after being shot by them + case EV_FFTURN: // Turn on ally after being shot by them DEBUGNAME("EV_FFTURN"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*ffturn.wav" ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*ffturn.wav"); break; - //extra sounds for ST + // extra sounds for ST case EV_CHASE1: case EV_CHASE2: case EV_CHASE3: DEBUGNAME("EV_CHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*chase%i.wav", event - EV_CHASE1 + 1)); break; case EV_COVER1: case EV_COVER2: @@ -1718,7 +1517,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_COVER4: case EV_COVER5: DEBUGNAME("EV_COVERx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*cover%i.wav", event - EV_COVER1 + 1)); break; case EV_DETECTED1: case EV_DETECTED2: @@ -1726,46 +1525,46 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DETECTED4: case EV_DETECTED5: DEBUGNAME("EV_DETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*detected%i.wav", event - EV_DETECTED1 + 1)); break; case EV_GIVEUP1: case EV_GIVEUP2: case EV_GIVEUP3: case EV_GIVEUP4: DEBUGNAME("EV_GIVEUPx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*giveup%i.wav", event - EV_GIVEUP1 + 1)); break; case EV_LOOK1: case EV_LOOK2: DEBUGNAME("EV_LOOKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*look%i.wav", event - EV_LOOK1 + 1)); break; case EV_LOST1: DEBUGNAME("EV_LOST1"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*lost1.wav" ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*lost1.wav"); break; case EV_OUTFLANK1: case EV_OUTFLANK2: DEBUGNAME("EV_OUTFLANKx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*outflank%i.wav", event - EV_OUTFLANK1 + 1)); break; case EV_ESCAPING1: case EV_ESCAPING2: case EV_ESCAPING3: DEBUGNAME("EV_ESCAPINGx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*escaping%i.wav", event - EV_ESCAPING1 + 1)); break; case EV_SIGHT1: case EV_SIGHT2: case EV_SIGHT3: DEBUGNAME("EV_SIGHTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sight%i.wav", event - EV_SIGHT1 + 1)); break; case EV_SOUND1: case EV_SOUND2: case EV_SOUND3: DEBUGNAME("EV_SOUNDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*sound%i.wav", event - EV_SOUND1 + 1)); break; case EV_SUSPICIOUS1: case EV_SUSPICIOUS2: @@ -1773,61 +1572,60 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SUSPICIOUS4: case EV_SUSPICIOUS5: DEBUGNAME("EV_SUSPICIOUSx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*suspicious%i.wav", event - EV_SUSPICIOUS1 + 1)); break; - //extra sounds for Jedi + // extra sounds for Jedi case EV_COMBAT1: case EV_COMBAT2: case EV_COMBAT3: DEBUGNAME("EV_COMBATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*combat%i.wav", event - EV_COMBAT1 + 1)); break; case EV_JDETECTED1: case EV_JDETECTED2: case EV_JDETECTED3: DEBUGNAME("EV_JDETECTEDx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jdetected%i.wav", event - EV_JDETECTED1 + 1)); break; case EV_TAUNT1: case EV_TAUNT2: case EV_TAUNT3: DEBUGNAME("EV_TAUNTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*taunt%i.wav", event - EV_TAUNT1 + 1)); break; case EV_JCHASE1: case EV_JCHASE2: case EV_JCHASE3: DEBUGNAME("EV_JCHASEx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jchase%i.wav", event - EV_JCHASE1 + 1)); break; case EV_JLOST1: case EV_JLOST2: case EV_JLOST3: DEBUGNAME("EV_JLOSTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*jlost%i.wav", event - EV_JLOST1 + 1)); break; case EV_DEFLECT1: case EV_DEFLECT2: case EV_DEFLECT3: DEBUGNAME("EV_DEFLECTx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*deflect%i.wav", event - EV_DEFLECT1 + 1)); break; case EV_GLOAT1: case EV_GLOAT2: case EV_GLOAT3: DEBUGNAME("EV_GLOATx"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1) ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, va("*gloat%i.wav", event - EV_GLOAT1 + 1)); break; case EV_PUSHFAIL: DEBUGNAME("EV_PUSHFAIL"); - CG_TryPlayCustomSound( NULL, es->number, CHAN_VOICE, "*pushfail.wav" ); + CG_TryPlayCustomSound(NULL, es->number, CHAN_VOICE, "*pushfail.wav"); break; - //End NPC sounds + // End NPC sounds case EV_SIEGESPEC: DEBUGNAME("EV_SIEGESPEC"); - if ( es->owner == cg.predictedPlayerState.clientNum ) - { + if (es->owner == cg.predictedPlayerState.clientNum) { cg_siegeDeathTime = es->time; } @@ -1835,60 +1633,53 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_WATER_TOUCH: DEBUGNAME("EV_WATER_TOUCH"); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrInSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrInSound); break; case EV_WATER_LEAVE: DEBUGNAME("EV_WATER_LEAVE"); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrOutSound); break; case EV_WATER_UNDER: DEBUGNAME("EV_WATER_UNDER"); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.watrUnSound); break; case EV_WATER_CLEAR: DEBUGNAME("EV_WATER_CLEAR"); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, CG_CustomSound( es->number, "*gasp.wav" ) ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, CG_CustomSound(es->number, "*gasp.wav")); break; case EV_ITEM_PICKUP: DEBUGNAME("EV_ITEM_PICKUP"); { - gitem_t *item; - int index; - qboolean newindex = qfalse; + gitem_t *item; + int index; + qboolean newindex = qfalse; - index = cg_entities[es->eventParm].currentState.modelindex; // player predicted + index = cg_entities[es->eventParm].currentState.modelindex; // player predicted - if (index < 1 && cg_entities[es->eventParm].currentState.isJediMaster) - { //a holocron most likely + if (index < 1 && cg_entities[es->eventParm].currentState.isJediMaster) { // a holocron most likely index = cg_entities[es->eventParm].currentState.trickedentindex4; - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.holocronPickup ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.holocronPickup); - if (es->number == cg.snap->ps.clientNum && showPowersName[index]) - { + if (es->number == cg.snap->ps.clientNum && showPowersName[index]) { const char *strText = CG_GetStringEdString("MP_INGAME", "PICKUPLINE"); - //Com_Printf("%s %s\n", strText, showPowersName[index]); - CG_CenterPrint( va("%s %s\n", strText, CG_GetStringEdString("SP_INGAME",showPowersName[index])), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + // Com_Printf("%s %s\n", strText, showPowersName[index]); + CG_CenterPrint(va("%s %s\n", strText, CG_GetStringEdString("SP_INGAME", showPowersName[index])), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); } - //Show the player their force selection bar in case picking the holocron up changed the current selection - if (index != FP_SABER_OFFENSE && index != FP_SABER_DEFENSE && index != FP_SABERTHROW && - index != FP_LEVITATION && + // Show the player their force selection bar in case picking the holocron up changed the current selection + if (index != FP_SABER_OFFENSE && index != FP_SABER_DEFENSE && index != FP_SABERTHROW && index != FP_LEVITATION && es->number == cg.snap->ps.clientNum && - (index == cg.snap->ps.fd.forcePowerSelected || !(cg.snap->ps.fd.forcePowersActive & (1 << cg.snap->ps.fd.forcePowerSelected)))) - { - if (cg.forceSelect != index) - { + (index == cg.snap->ps.fd.forcePowerSelected || !(cg.snap->ps.fd.forcePowersActive & (1 << cg.snap->ps.fd.forcePowerSelected)))) { + if (cg.forceSelect != index) { cg.forceSelect = index; newindex = qtrue; } } - if (es->number == cg.snap->ps.clientNum && newindex) - { - if (cg.forceSelectTime < cg.time) - { + if (es->number == cg.snap->ps.clientNum && newindex) { + if (cg.forceSelectTime < cg.time) { cg.forceSelectTime = cg.time; } } @@ -1896,32 +1687,30 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; } - if (cg_entities[es->eventParm].weapon >= cg.time) - { //rww - an unfortunately necessary hack to prevent double item pickups + if (cg_entities[es->eventParm].weapon >= cg.time) { // rww - an unfortunately necessary hack to prevent double item pickups break; } - //Hopefully even if this entity is somehow removed and replaced with, say, another - //item, this time will have expired by the time that item needs to be picked up. - //Of course, it's quite possible this will fail miserably, so if you've got a better - //solution then please do use it. - cg_entities[es->eventParm].weapon = cg.time+500; + // Hopefully even if this entity is somehow removed and replaced with, say, another + // item, this time will have expired by the time that item needs to be picked up. + // Of course, it's quite possible this will fail miserably, so if you've got a better + // solution then please do use it. + cg_entities[es->eventParm].weapon = cg.time + 500; - if ( index < 1 || index >= bg_numItems ) { + if (index < 1 || index >= bg_numItems) { break; } - item = &bg_itemlist[ index ]; + item = &bg_itemlist[index]; - if ( /*item->giType != IT_POWERUP && */item->giType != IT_TEAM) { - if (item->pickup_sound && item->pickup_sound[0]) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, trap->S_RegisterSound( item->pickup_sound ) ); + if (/*item->giType != IT_POWERUP && */ item->giType != IT_TEAM) { + if (item->pickup_sound && item->pickup_sound[0]) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, trap->S_RegisterSound(item->pickup_sound)); } } // show icon and name on status bar - if ( es->number == cg.snap->ps.clientNum ) { - CG_ItemPickup( index ); + if (es->number == cg.snap->ps.clientNum) { + CG_ItemPickup(index); } } break; @@ -1929,23 +1718,23 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_GLOBAL_ITEM_PICKUP: DEBUGNAME("EV_GLOBAL_ITEM_PICKUP"); { - gitem_t *item; - int index; + gitem_t *item; + int index; - index = es->eventParm; // player predicted + index = es->eventParm; // player predicted - if ( index < 1 || index >= bg_numItems ) { + if (index < 1 || index >= bg_numItems) { break; } - item = &bg_itemlist[ index ]; + item = &bg_itemlist[index]; // powerup pickups are global - if( item->pickup_sound && item->pickup_sound[0] ) { - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, trap->S_RegisterSound( item->pickup_sound) ); + if (item->pickup_sound && item->pickup_sound[0]) { + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, trap->S_RegisterSound(item->pickup_sound)); } // show icon and name on status bar - if ( es->number == cg.snap->ps.clientNum ) { - CG_ItemPickup( index ); + if (es->number == cg.snap->ps.clientNum) { + CG_ItemPickup(index); } } break; @@ -1963,47 +1752,34 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // case EV_NOAMMO: DEBUGNAME("EV_NOAMMO"); -// trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); - if ( es->number == cg.snap->ps.clientNum ) - { - if ( CG_InFighter() || CG_InATST() || cg.snap->ps.weapon == WP_NONE ) - {//just letting us know our vehicle is out of ammo - //FIXME: flash something on HUD or give some message so we know we have no ammo + // trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.noAmmoSound ); + if (es->number == cg.snap->ps.clientNum) { + if (CG_InFighter() || CG_InATST() || cg.snap->ps.weapon == WP_NONE) { // just letting us know our vehicle is out of ammo + // FIXME: flash something on HUD or give some message so we know we have no ammo centity_t *localCent = &cg_entities[cg.snap->ps.clientNum]; - if ( localCent->m_pVehicle - && localCent->m_pVehicle->m_pVehicleInfo - && localCent->m_pVehicle->m_pVehicleInfo->weapon[es->eventParm].soundNoAmmo ) - {//play the "no Ammo" sound for this weapon - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, localCent->m_pVehicle->m_pVehicleInfo->weapon[es->eventParm].soundNoAmmo ); + if (localCent->m_pVehicle && localCent->m_pVehicle->m_pVehicleInfo && + localCent->m_pVehicle->m_pVehicleInfo->weapon[es->eventParm].soundNoAmmo) { // play the "no Ammo" sound for this weapon + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, localCent->m_pVehicle->m_pVehicleInfo->weapon[es->eventParm].soundNoAmmo); + } else { // play the default "no ammo" sound + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.noAmmoSound); } - else - {//play the default "no ammo" sound - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_AUTO, cgs.media.noAmmoSound ); - } - //flash the HUD so they associate the sound with the visual indicator that they don't have enough ammo - if ( cg_vehicleAmmoWarningTime < cg.time - || cg_vehicleAmmoWarning != es->eventParm ) - {//if there's already one going, don't interrupt it (unless they tried to fire another weapon that's out of ammo) + // flash the HUD so they associate the sound with the visual indicator that they don't have enough ammo + if (cg_vehicleAmmoWarningTime < cg.time || + cg_vehicleAmmoWarning != + es->eventParm) { // if there's already one going, don't interrupt it (unless they tried to fire another weapon that's out of ammo) cg_vehicleAmmoWarning = es->eventParm; - cg_vehicleAmmoWarningTime = cg.time+500; + cg_vehicleAmmoWarningTime = cg.time + 500; } - } - else if ( cg.snap->ps.weapon == WP_SABER ) - { + } else if (cg.snap->ps.weapon == WP_SABER) { cg.forceHUDTotalFlashTime = cg.time + 1000; - } - else - { + } else { int weap = 0; - if (es->eventParm && es->eventParm < WP_NUM_WEAPONS) - { + if (es->eventParm && es->eventParm < WP_NUM_WEAPONS) { cg.snap->ps.stats[STAT_WEAPONS] &= ~(1 << es->eventParm); weap = cg.snap->ps.weapon; - } - else if (es->eventParm) - { - weap = (es->eventParm-WP_NUM_WEAPONS); + } else if (es->eventParm) { + weap = (es->eventParm - WP_NUM_WEAPONS); } CG_OutOfAmmoChange(weap); } @@ -2021,55 +1797,43 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { assert(weaponInfo); - if (weaponInfo->selectSound) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, weaponInfo->selectSound ); - } - else if (weapon != WP_SABER) - { //not sure what SP is doing for this but I don't want a select sound for saber (it has the saber-turn-on) - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.selectSound ); + if (weaponInfo->selectSound) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, weaponInfo->selectSound); + } else if (weapon != WP_SABER) { // not sure what SP is doing for this but I don't want a select sound for saber (it has the saber-turn-on) + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.selectSound); } } break; case EV_FIRE_WEAPON: DEBUGNAME("EV_FIRE_WEAPON"); - if (cent->currentState.number >= MAX_CLIENTS && cent->currentState.eType != ET_NPC) - { //special case for turret firing + if (cent->currentState.number >= MAX_CLIENTS && cent->currentState.eType != ET_NPC) { // special case for turret firing vec3_t gunpoint, gunangle; mdxaBone_t matrix; weaponInfo_t *weaponInfo = &cg_weapons[WP_TURRET]; - if ( !weaponInfo->registered ) - { + if (!weaponInfo->registered) { CG_RegisterWeapon(WP_TURRET); } - if (cent->ghoul2) - { - if (!cent->bolt1) - { + if (cent->ghoul2) { + if (!cent->bolt1) { cent->bolt1 = trap->G2API_AddBolt(cent->ghoul2, 0, "*flash01"); } - if (!cent->bolt2) - { + if (!cent->bolt2) { cent->bolt2 = trap->G2API_AddBolt(cent->ghoul2, 0, "*flash02"); } - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Bone02", 1, 4, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f, cg.time, -1, 300); - } - else - { + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Bone02", 1, 4, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, cg.time, -1, 300); + } else { break; } - if (cent->currentState.eventParm) - { - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, cent->bolt2, &matrix, cent->currentState.angles, cent->currentState.origin, cg.time, cgs.gameModels, cent->modelScale); - } - else - { - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, cent->bolt1, &matrix, cent->currentState.angles, cent->currentState.origin, cg.time, cgs.gameModels, cent->modelScale); + if (cent->currentState.eventParm) { + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, cent->bolt2, &matrix, cent->currentState.angles, cent->currentState.origin, cg.time, cgs.gameModels, + cent->modelScale); + } else { + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, cent->bolt1, &matrix, cent->currentState.angles, cent->currentState.origin, cg.time, cgs.gameModels, + cent->modelScale); } gunpoint[0] = matrix.matrix[0][3]; @@ -2081,42 +1845,32 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { gunangle[2] = -matrix.matrix[2][0]; trap->FX_PlayEffectID(cgs.effects.mEmplacedMuzzleFlash, gunpoint, gunangle, -1, -1, qfalse); - } - else if (cent->currentState.weapon != WP_EMPLACED_GUN || cent->currentState.eType == ET_NPC) - { - if (cent->currentState.eType == ET_NPC && - cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle) - { //vehicles do nothing for clientside weapon fire events.. at least for now. + } else if (cent->currentState.weapon != WP_EMPLACED_GUN || cent->currentState.eType == ET_NPC) { + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && + cent->m_pVehicle) { // vehicles do nothing for clientside weapon fire events.. at least for now. break; } - CG_FireWeapon( cent, qfalse ); + CG_FireWeapon(cent, qfalse); } break; case EV_ALT_FIRE: DEBUGNAME("EV_ALT_FIRE"); - if (cent->currentState.weapon == WP_EMPLACED_GUN) - { //don't do anything for emplaced stuff + if (cent->currentState.weapon == WP_EMPLACED_GUN) { // don't do anything for emplaced stuff break; } - if (cent->currentState.eType == ET_NPC && - cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle) - { //vehicles do nothing for clientside weapon fire events.. at least for now. + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && + cent->m_pVehicle) { // vehicles do nothing for clientside weapon fire events.. at least for now. break; } - CG_FireWeapon( cent, qtrue ); + CG_FireWeapon(cent, qtrue); - //if you just exploded your detpacks and you have no ammo left for them, autoswitch - if ( cg.snap->ps.clientNum == cent->currentState.number && - cg.snap->ps.weapon == WP_DET_PACK ) - { - if (cg.snap->ps.ammo[weaponData[WP_DET_PACK].ammoIndex] == 0) - { + // if you just exploded your detpacks and you have no ammo left for them, autoswitch + if (cg.snap->ps.clientNum == cent->currentState.number && cg.snap->ps.weapon == WP_DET_PACK) { + if (cg.snap->ps.ammo[weaponData[WP_DET_PACK].ammoIndex] == 0) { CG_OutOfAmmoChange(WP_DET_PACK); } } @@ -2128,19 +1882,15 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { qhandle_t swingSound = trap->S_RegisterSound(va("sound/weapons/saber/saberhup%i.wav", Q_irand(1, 8))); clientInfo_t *client = NULL; - if ( cg_entities[es->number].currentState.eType == ET_NPC ) - { + if (cg_entities[es->number].currentState.eType == ET_NPC) { client = cg_entities[es->number].npcClient; - } - else if ( es->number < MAX_CLIENTS ) - { + } else if (es->number < MAX_CLIENTS) { client = &cgs.clientinfo[es->number]; } - if ( client && client->infoValid && client->saber[0].swingSound[0] ) - {//custom swing sound - swingSound = client->saber[0].swingSound[Q_irand(0,2)]; + if (client && client->infoValid && client->saber[0].swingSound[0]) { // custom swing sound + swingSound = client->saber[0].swingSound[Q_irand(0, 2)]; } - trap->S_StartSound(es->pos.trBase, es->number, CHAN_WEAPON, swingSound ); + trap->S_StartSound(es->pos.trBase, es->number, CHAN_WEAPON, swingSound); } break; @@ -2153,118 +1903,91 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { int hitOtherFxID = cgs.effects.mSaberCut; int hitSound = trap->S_RegisterSound(va("sound/weapons/saber/saberhit%i.wav", Q_irand(1, 3))); - if ( es->otherEntityNum2 >= 0 - && es->otherEntityNum2 < ENTITYNUM_NONE ) - {//we have a specific person who is causing this effect, see if we should override it with any custom saber effects/sounds + if (es->otherEntityNum2 >= 0 && + es->otherEntityNum2 < + ENTITYNUM_NONE) { // we have a specific person who is causing this effect, see if we should override it with any custom saber effects/sounds clientInfo_t *client = NULL; - if ( cg_entities[es->otherEntityNum2].currentState.eType == ET_NPC ) - { + if (cg_entities[es->otherEntityNum2].currentState.eType == ET_NPC) { client = cg_entities[es->otherEntityNum2].npcClient; - } - else if ( es->otherEntityNum2 < MAX_CLIENTS ) - { + } else if (es->otherEntityNum2 < MAX_CLIENTS) { client = &cgs.clientinfo[es->otherEntityNum2]; } - if ( client && client->infoValid ) - { + if (client && client->infoValid) { int saberNum = es->weapon; int bladeNum = es->legsAnim; - if ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) ) - {//use second blade style values - if ( client->saber[saberNum].hitPersonEffect2 ) - {//custom hit person effect + if (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum)) { // use second blade style values + if (client->saber[saberNum].hitPersonEffect2) { // custom hit person effect hitPersonFxID = hitPersonSmallFxID = hitPersonMidFxID = client->saber[saberNum].hitPersonEffect2; } - if ( client->saber[saberNum].hitOtherEffect2 ) - {//custom hit other effect + if (client->saber[saberNum].hitOtherEffect2) { // custom hit other effect hitOtherFxID = client->saber[saberNum].hitOtherEffect2; } - if ( client->saber[saberNum].hit2Sound[0] ) - {//custom hit sound - hitSound = client->saber[saberNum].hit2Sound[Q_irand(0,2)]; + if (client->saber[saberNum].hit2Sound[0]) { // custom hit sound + hitSound = client->saber[saberNum].hit2Sound[Q_irand(0, 2)]; } - } - else - {//use first blade style values - if ( client->saber[saberNum].hitPersonEffect ) - {//custom hit person effect + } else { // use first blade style values + if (client->saber[saberNum].hitPersonEffect) { // custom hit person effect hitPersonFxID = hitPersonSmallFxID = hitPersonMidFxID = client->saber[saberNum].hitPersonEffect; } - if ( client->saber[saberNum].hitOtherEffect ) - {//custom hit other effect + if (client->saber[saberNum].hitOtherEffect) { // custom hit other effect hitOtherFxID = client->saber[0].hitOtherEffect; } - if ( client->saber[saberNum].hitSound[0] ) - {//custom hit sound - hitSound = client->saber[saberNum].hitSound[Q_irand(0,2)]; + if (client->saber[saberNum].hitSound[0]) { // custom hit sound + hitSound = client->saber[saberNum].hitSound[Q_irand(0, 2)]; } } } } - if (es->eventParm == 16) - { //Make lots of sparks, something special happened + if (es->eventParm == 16) { // Make lots of sparks, something special happened vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - trap->S_StartSound(es->origin, es->number, CHAN_AUTO, hitSound ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - } - else if (es->eventParm) - { //hit a person + trap->S_StartSound(es->origin, es->number, CHAN_AUTO, hitSound); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + } else if (es->eventParm) { // hit a person vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - trap->S_StartSound(es->origin, es->number, CHAN_AUTO, hitSound ); - if ( es->eventParm == 3 ) - { // moderate or big hits. - trap->FX_PlayEffectID( hitPersonSmallFxID, es->origin, fxDir, -1, -1, qfalse ); - } - else if ( es->eventParm == 2 ) - { // this is for really big hits. - trap->FX_PlayEffectID( hitPersonMidFxID, es->origin, fxDir, -1, -1, qfalse ); + trap->S_StartSound(es->origin, es->number, CHAN_AUTO, hitSound); + if (es->eventParm == 3) { // moderate or big hits. + trap->FX_PlayEffectID(hitPersonSmallFxID, es->origin, fxDir, -1, -1, qfalse); + } else if (es->eventParm == 2) { // this is for really big hits. + trap->FX_PlayEffectID(hitPersonMidFxID, es->origin, fxDir, -1, -1, qfalse); + } else { // this should really just be done in the effect itself, no? + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); + trap->FX_PlayEffectID(hitPersonFxID, es->origin, fxDir, -1, -1, qfalse); } - else - { // this should really just be done in the effect itself, no? - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - trap->FX_PlayEffectID( hitPersonFxID, es->origin, fxDir, -1, -1, qfalse ); - } - } - else - { //hit something else + } else { // hit something else vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - //old jk2mp method + // old jk2mp method /* trap->S_StartSound(es->origin, es->number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/saber/saberhit.wav")); trap->FX_PlayEffectID( trap->FX_RegisterEffect("saber/spark.efx"), es->origin, fxDir, -1, -1, qfalse ); */ - trap->FX_PlayEffectID( hitOtherFxID, es->origin, fxDir, -1, -1, qfalse ); + trap->FX_PlayEffectID(hitOtherFxID, es->origin, fxDir, -1, -1, qfalse); } - //rww - this means we have the number of the ent being hit and the ent that owns the saber doing - //the hit. This being the case, we can store these indecies and the current time in order to do - //some visual tricks on the client between frames to make it look like we're actually continuing - //to hit between server frames. - if (es->otherEntityNum != ENTITYNUM_NONE && es->otherEntityNum2 != ENTITYNUM_NONE) - { + // rww - this means we have the number of the ent being hit and the ent that owns the saber doing + // the hit. This being the case, we can store these indecies and the current time in order to do + // some visual tricks on the client between frames to make it look like we're actually continuing + // to hit between server frames. + if (es->otherEntityNum != ENTITYNUM_NONE && es->otherEntityNum2 != ENTITYNUM_NONE) { centity_t *saberOwner; saberOwner = &cg_entities[es->otherEntityNum2]; @@ -2272,12 +1995,9 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { saberOwner->serverSaberHitIndex = es->otherEntityNum; saberOwner->serverSaberHitTime = cg.time; - if (es->eventParm) - { + if (es->eventParm) { saberOwner->serverSaberFleshImpact = qtrue; - } - else - { + } else { saberOwner->serverSaberFleshImpact = qfalse; } } @@ -2287,52 +2007,38 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SABER_BLOCK: DEBUGNAME("EV_SABER_BLOCK"); { - if (es->eventParm) - { //saber block - int blockFXID = cgs.effects.mSaberBlock; - qhandle_t blockSound = trap->S_RegisterSound(va( "sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9) )); - qboolean noFlare = qfalse; - - if ( es->otherEntityNum2 >= 0 - && es->otherEntityNum2 < ENTITYNUM_NONE ) - {//we have a specific person who is causing this effect, see if we should override it with any custom saber effects/sounds + if (es->eventParm) { // saber block + int blockFXID = cgs.effects.mSaberBlock; + qhandle_t blockSound = trap->S_RegisterSound(va("sound/weapons/saber/saberblock%d.wav", Q_irand(1, 9))); + qboolean noFlare = qfalse; + + if (es->otherEntityNum2 >= 0 && es->otherEntityNum2 < ENTITYNUM_NONE) { // we have a specific person who is causing this effect, see if we + // should override it with any custom saber effects/sounds clientInfo_t *client = NULL; - if ( cg_entities[es->otherEntityNum2].currentState.eType == ET_NPC ) - { + if (cg_entities[es->otherEntityNum2].currentState.eType == ET_NPC) { client = cg_entities[es->otherEntityNum2].npcClient; - } - else if ( es->otherEntityNum2 < MAX_CLIENTS ) - { + } else if (es->otherEntityNum2 < MAX_CLIENTS) { client = &cgs.clientinfo[es->otherEntityNum2]; } - if ( client && client->infoValid ) - { + if (client && client->infoValid) { int saberNum = es->weapon; int bladeNum = es->legsAnim; - if ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) ) - {//use second blade style values - if ( client->saber[saberNum].blockEffect2 ) - {//custom saber block effect + if (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum)) { // use second blade style values + if (client->saber[saberNum].blockEffect2) { // custom saber block effect blockFXID = client->saber[saberNum].blockEffect2; } - if ( client->saber[saberNum].block2Sound[0] ) - {//custom hit sound - blockSound = client->saber[saberNum].block2Sound[Q_irand(0,2)]; + if (client->saber[saberNum].block2Sound[0]) { // custom hit sound + blockSound = client->saber[saberNum].block2Sound[Q_irand(0, 2)]; } - } - else - { - if ( client->saber[saberNum].blockEffect ) - {//custom saber block effect + } else { + if (client->saber[saberNum].blockEffect) { // custom saber block effect blockFXID = client->saber[saberNum].blockEffect; } - if ( client->saber[saberNum].blockSound[0] ) - {//custom hit sound - blockSound = client->saber[saberNum].blockSound[Q_irand(0,2)]; + if (client->saber[saberNum].blockSound[0]) { // custom hit sound + blockSound = client->saber[saberNum].blockSound[Q_irand(0, 2)]; } } - if ( (client->saber[saberNum].saberFlags2&SFL2_NO_CLASH_FLARE) ) - { + if ((client->saber[saberNum].saberFlags2 & SFL2_NO_CLASH_FLARE)) { noFlare = qtrue; } } @@ -2342,26 +2048,21 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - trap->S_StartSound(es->origin, es->number, CHAN_AUTO, blockSound ); - trap->FX_PlayEffectID( blockFXID, es->origin, fxDir, -1, -1, qfalse ); + trap->S_StartSound(es->origin, es->number, CHAN_AUTO, blockSound); + trap->FX_PlayEffectID(blockFXID, es->origin, fxDir, -1, -1, qfalse); - if ( !noFlare ) - { - cg_saberFlashTime = cg.time-50; - VectorCopy( es->origin, cg_saberFlashPos ); + if (!noFlare) { + cg_saberFlashTime = cg.time - 50; + VectorCopy(es->origin, cg_saberFlashPos); } } - } - else - { //projectile block + } else { // projectile block vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } trap->FX_PlayEffectID(cgs.effects.mBlasterDeflect, es->origin, fxDir, -1, -1, qfalse); @@ -2372,9 +2073,9 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SABER_CLASHFLARE: DEBUGNAME("EV_SABER_CLASHFLARE"); { - cg_saberFlashTime = cg.time-50; - VectorCopy( es->origin, cg_saberFlashPos ); - trap->S_StartSound ( es->origin, -1, CHAN_WEAPON, trap->S_RegisterSound( va("sound/weapons/saber/saberhitwall%i", Q_irand(1, 3)) ) ); + cg_saberFlashTime = cg.time - 50; + VectorCopy(es->origin, cg_saberFlashPos); + trap->S_StartSound(es->origin, -1, CHAN_WEAPON, trap->S_RegisterSound(va("sound/weapons/saber/saberhitwall%i", Q_irand(1, 3)))); } break; @@ -2383,24 +2084,18 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { clientInfo_t *ci = NULL; - if (es->eType == ET_NPC) - { + if (es->eType == ET_NPC) { ci = cg_entities[es->number].npcClient; - } - else if (es->number < MAX_CLIENTS) - { + } else if (es->number < MAX_CLIENTS) { ci = &cgs.clientinfo[es->number]; } - if (ci) - { - if (ci->saber[0].soundOn) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, ci->saber[0].soundOn ); + if (ci) { + if (ci->saber[0].soundOn) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, ci->saber[0].soundOn); } - if (ci->saber[1].soundOn) - { - trap->S_StartSound (NULL, es->number, CHAN_AUTO, ci->saber[1].soundOn ); + if (ci->saber[1].soundOn) { + trap->S_StartSound(NULL, es->number, CHAN_AUTO, ci->saber[1].soundOn); } } } @@ -2410,7 +2105,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { DEBUGNAME("EV_SABER_UNHOLSTER"); { trace_t tr; - vec3_t playerMins = {-15, -15, DEFAULT_MINS_2+8}; + vec3_t playerMins = {-15, -15, DEFAULT_MINS_2 + 8}; vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; vec3_t ang, pos, dpos; @@ -2423,16 +2118,14 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { CG_Trace(&tr, position, playerMins, playerMaxs, dpos, es->number, MASK_SOLID); VectorCopy(tr.endpos, pos); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { break; } trap->FX_PlayEffectID(cgs.effects.mJediSpawn, pos, ang, -1, -1, qfalse); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" ) ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/saber/saberon.wav")); - if (cg.snap->ps.clientNum == es->number) - { + if (cg.snap->ps.clientNum == es->number) { trap->S_StartLocalSound(cgs.media.happyMusic, CHAN_LOCAL); CGCam_SetMusicMult(0.3f, 5000); } @@ -2441,74 +2134,56 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DISRUPTOR_MAIN_SHOT: DEBUGNAME("EV_DISRUPTOR_MAIN_SHOT"); - if (cent->currentState.eventParm != cg.snap->ps.clientNum || - cg.renderingThirdPerson) - { //h4q3ry + if (cent->currentState.eventParm != cg.snap->ps.clientNum || cg.renderingThirdPerson) { // h4q3ry CG_GetClientWeaponMuzzleBoltPoint(cent->currentState.eventParm, cent->currentState.origin2); - } - else - { - if (cg.lastFPFlashPoint[0] ||cg.lastFPFlashPoint[1] || cg.lastFPFlashPoint[2]) - { //get the position of the muzzle flash for the first person weapon model from the last frame + } else { + if (cg.lastFPFlashPoint[0] || cg.lastFPFlashPoint[1] || + cg.lastFPFlashPoint[2]) { // get the position of the muzzle flash for the first person weapon model from the last frame VectorCopy(cg.lastFPFlashPoint, cent->currentState.origin2); } } - FX_DisruptorMainShot( cent->currentState.origin2, cent->lerpOrigin ); + FX_DisruptorMainShot(cent->currentState.origin2, cent->lerpOrigin); break; case EV_DISRUPTOR_SNIPER_SHOT: DEBUGNAME("EV_DISRUPTOR_SNIPER_SHOT"); - if (cent->currentState.eventParm != cg.snap->ps.clientNum || - cg.renderingThirdPerson) - { //h4q3ry + if (cent->currentState.eventParm != cg.snap->ps.clientNum || cg.renderingThirdPerson) { // h4q3ry CG_GetClientWeaponMuzzleBoltPoint(cent->currentState.eventParm, cent->currentState.origin2); - } - else - { - if (cg.lastFPFlashPoint[0] ||cg.lastFPFlashPoint[1] || cg.lastFPFlashPoint[2]) - { //get the position of the muzzle flash for the first person weapon model from the last frame + } else { + if (cg.lastFPFlashPoint[0] || cg.lastFPFlashPoint[1] || + cg.lastFPFlashPoint[2]) { // get the position of the muzzle flash for the first person weapon model from the last frame VectorCopy(cg.lastFPFlashPoint, cent->currentState.origin2); } } - FX_DisruptorAltShot( cent->currentState.origin2, cent->lerpOrigin, cent->currentState.shouldtarget ); + FX_DisruptorAltShot(cent->currentState.origin2, cent->lerpOrigin, cent->currentState.shouldtarget); break; case EV_DISRUPTOR_SNIPER_MISS: DEBUGNAME("EV_DISRUPTOR_SNIPER_MISS"); - ByteToDir( es->eventParm, dir ); - if (es->weapon) - { //primary - FX_DisruptorHitWall( cent->lerpOrigin, dir ); - } - else - { //secondary - FX_DisruptorAltMiss( cent->lerpOrigin, dir ); + ByteToDir(es->eventParm, dir); + if (es->weapon) { // primary + FX_DisruptorHitWall(cent->lerpOrigin, dir); + } else { // secondary + FX_DisruptorAltMiss(cent->lerpOrigin, dir); } break; case EV_DISRUPTOR_HIT: DEBUGNAME("EV_DISRUPTOR_HIT"); - ByteToDir( es->eventParm, dir ); - if (es->weapon) - { //client - FX_DisruptorHitPlayer( cent->lerpOrigin, dir, qtrue ); - } - else - { //non-client - FX_DisruptorHitWall( cent->lerpOrigin, dir ); + ByteToDir(es->eventParm, dir); + if (es->weapon) { // client + FX_DisruptorHitPlayer(cent->lerpOrigin, dir, qtrue); + } else { // non-client + FX_DisruptorHitWall(cent->lerpOrigin, dir); } break; case EV_DISRUPTOR_ZOOMSOUND: DEBUGNAME("EV_DISRUPTOR_ZOOMSOUND"); - if (es->number == cg.snap->ps.clientNum) - { - if (cg.snap->ps.zoomMode) - { + if (es->number == cg.snap->ps.clientNum) { + if (cg.snap->ps.zoomMode) { trap->S_StartLocalSound(trap->S_RegisterSound("sound/weapons/disruptor/zoomstart.wav"), CHAN_AUTO); - } - else - { + } else { trap->S_StartLocalSound(trap->S_RegisterSound("sound/weapons/disruptor/zoomend.wav"), CHAN_AUTO); } } @@ -2518,8 +2193,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { int sID = -1; - switch (es->eventParm) - { + switch (es->eventParm) { case PDSOUND_PROTECTHIT: sID = trap->S_RegisterSound("sound/weapons/force/protecthit.mp3"); break; @@ -2528,8 +2202,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; case PDSOUND_ABSORBHIT: sID = trap->S_RegisterSound("sound/weapons/force/absorbhit.mp3"); - if (es->trickedentindex >= 0 && es->trickedentindex < MAX_CLIENTS) - { + if (es->trickedentindex >= 0 && es->trickedentindex < MAX_CLIENTS) { int clnum = es->trickedentindex; cg_entities[clnum].teamPowerEffectTime = cg.time + 1000; @@ -2549,8 +2222,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; } - if (sID != 1) - { + if (sID != 1) { trap->S_StartSound(es->origin, es->number, CHAN_AUTO, sID); } } @@ -2561,19 +2233,14 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { { int clnum = 0; - while (clnum < MAX_CLIENTS) - { - if (CG_InClientBitflags(es, clnum)) - { - if (es->eventParm == 1) - { //eventParm 1 is heal - trap->S_StartSound (NULL, clnum, CHAN_AUTO, cgs.media.teamHealSound ); + while (clnum < MAX_CLIENTS) { + if (CG_InClientBitflags(es, clnum)) { + if (es->eventParm == 1) { // eventParm 1 is heal + trap->S_StartSound(NULL, clnum, CHAN_AUTO, cgs.media.teamHealSound); cg_entities[clnum].teamPowerEffectTime = cg.time + 1000; cg_entities[clnum].teamPowerType = 1; - } - else - { //eventParm 2 is force regen - trap->S_StartSound (NULL, clnum, CHAN_AUTO, cgs.media.teamRegenSound ); + } else { // eventParm 2 is force regen + trap->S_StartSound(NULL, clnum, CHAN_AUTO, cgs.media.teamRegenSound); cg_entities[clnum].teamPowerEffectTime = cg.time + 1000; cg_entities[clnum].teamPowerType = 0; } @@ -2585,87 +2252,83 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_SCREENSHAKE: DEBUGNAME("EV_SCREENSHAKE"); - if (!es->modelindex || cg.predictedPlayerState.clientNum == es->modelindex-1) - { + if (!es->modelindex || cg.predictedPlayerState.clientNum == es->modelindex - 1) { CGCam_Shake(es->angles[0], es->time); } break; case EV_LOCALTIMER: DEBUGNAME("EV_LOCALTIMER"); - if (es->owner == cg.predictedPlayerState.clientNum) - { + if (es->owner == cg.predictedPlayerState.clientNum) { CG_LocalTimingBar(es->time, es->time2); } break; case EV_USE_ITEM0: DEBUGNAME("EV_USE_ITEM0"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM1: DEBUGNAME("EV_USE_ITEM1"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM2: DEBUGNAME("EV_USE_ITEM2"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM3: DEBUGNAME("EV_USE_ITEM3"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM4: DEBUGNAME("EV_USE_ITEM4"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM5: DEBUGNAME("EV_USE_ITEM5"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM6: DEBUGNAME("EV_USE_ITEM6"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM7: DEBUGNAME("EV_USE_ITEM7"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM8: DEBUGNAME("EV_USE_ITEM8"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM9: DEBUGNAME("EV_USE_ITEM9"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM10: DEBUGNAME("EV_USE_ITEM10"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM11: DEBUGNAME("EV_USE_ITEM11"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM12: DEBUGNAME("EV_USE_ITEM12"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM13: DEBUGNAME("EV_USE_ITEM13"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_USE_ITEM14: DEBUGNAME("EV_USE_ITEM14"); - CG_UseItem( cent ); + CG_UseItem(cent); break; case EV_ITEMUSEFAIL: DEBUGNAME("EV_ITEMUSEFAIL"); - if (cg.snap->ps.clientNum == es->number) - { + if (cg.snap->ps.clientNum == es->number) { char *psStringEDRef = NULL; - switch(es->eventParm) - { + switch (es->eventParm) { case SENTRY_NOROOM: psStringEDRef = (char *)CG_GetStringEdString("MP_INGAME", "SENTRY_NOROOM"); break; @@ -2682,8 +2345,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; } - if (!psStringEDRef) - { + if (!psStringEDRef) { break; } @@ -2700,7 +2362,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { DEBUGNAME("EV_PLAYER_TELEPORT_IN"); { trace_t tr; - vec3_t playerMins = {-15, -15, DEFAULT_MINS_2+8}; + vec3_t playerMins = {-15, -15, DEFAULT_MINS_2 + 8}; vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; vec3_t ang, pos, dpos; @@ -2713,10 +2375,9 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { CG_Trace(&tr, position, playerMins, playerMaxs, dpos, es->number, MASK_SOLID); VectorCopy(tr.endpos, pos); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.teleInSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.teleInSound); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { break; } trap->FX_PlayEffectID(cgs.effects.mSpawn, pos, ang, -1, -1, qfalse); @@ -2727,7 +2388,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { DEBUGNAME("EV_PLAYER_TELEPORT_OUT"); { trace_t tr; - vec3_t playerMins = {-15, -15, DEFAULT_MINS_2+8}; + vec3_t playerMins = {-15, -15, DEFAULT_MINS_2 + 8}; vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; vec3_t ang, pos, dpos; @@ -2740,10 +2401,9 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { CG_Trace(&tr, position, playerMins, playerMaxs, dpos, es->number, MASK_SOLID); VectorCopy(tr.endpos, pos); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.teleOutSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.teleOutSound); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { break; } trap->FX_PlayEffectID(cgs.effects.mSpawn, pos, ang, -1, -1, qfalse); @@ -2752,22 +2412,22 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_ITEM_POP: DEBUGNAME("EV_ITEM_POP"); - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.respawnSound ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.respawnSound); break; case EV_ITEM_RESPAWN: DEBUGNAME("EV_ITEM_RESPAWN"); - cent->miscTime = cg.time; // scale up from this - trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.respawnSound ); + cent->miscTime = cg.time; // scale up from this + trap->S_StartSound(NULL, es->number, CHAN_AUTO, cgs.media.respawnSound); break; case EV_GRENADE_BOUNCE: DEBUGNAME("EV_GRENADE_BOUNCE"); - //Do something here? + // Do something here? break; case EV_SCOREPLUM: DEBUGNAME("EV_SCOREPLUM"); - CG_ScorePlum( cent->currentState.otherEntityNum, cent->lerpOrigin, cent->currentState.time ); + CG_ScorePlum(cent->currentState.otherEntityNum, cent->lerpOrigin, cent->currentState.time); break; case EV_CTFMESSAGE: @@ -2776,16 +2436,14 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; case EV_BODYFADE: - if (es->eType != ET_BODY) - { + if (es->eType != ET_BODY) { assert(!"EV_BODYFADE event from a non-corpse"); break; } - if (cent->ghoul2 && trap->G2_HaveWeGhoul2Models(cent->ghoul2)) - { - //turn the inside of the face off, to avoid showing the mouth when we start alpha fading the corpse - trap->G2API_SetSurfaceOnOff( cent->ghoul2, "head_eyes_mouth", 0x00000002/*G2SURFACEFLAG_OFF*/ ); + if (cent->ghoul2 && trap->G2_HaveWeGhoul2Models(cent->ghoul2)) { + // turn the inside of the face off, to avoid showing the mouth when we start alpha fading the corpse + trap->G2API_SetSurfaceOnOff(cent->ghoul2, "head_eyes_mouth", 0x00000002 /*G2SURFACEFLAG_OFF*/); } cent->bodyFadeTime = cg.time + 60000; @@ -2805,10 +2463,8 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DESTROY_GHOUL2_INSTANCE: DEBUGNAME("EV_DESTROY_GHOUL2_INSTANCE"); - if (cg_entities[es->eventParm].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[es->eventParm].ghoul2)) - { - if (es->eventParm < MAX_CLIENTS) - { //You try to do very bad thing! + if (cg_entities[es->eventParm].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[es->eventParm].ghoul2)) { + if (es->eventParm < MAX_CLIENTS) { // You try to do very bad thing! #ifdef _DEBUG Com_Printf("WARNING: Tried to kill a client ghoul2 instance with a server event!\n"); #endif @@ -2821,22 +2477,19 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DESTROY_WEAPON_MODEL: DEBUGNAME("EV_DESTROY_WEAPON_MODEL"); if (cg_entities[es->eventParm].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[es->eventParm].ghoul2) && - trap->G2API_HasGhoul2ModelOnIndex(&(cg_entities[es->eventParm].ghoul2), 1)) - { + trap->G2API_HasGhoul2ModelOnIndex(&(cg_entities[es->eventParm].ghoul2), 1)) { trap->G2API_RemoveGhoul2Model(&(cg_entities[es->eventParm].ghoul2), 1); } break; case EV_GIVE_NEW_RANK: DEBUGNAME("EV_GIVE_NEW_RANK"); - if (es->trickedentindex == cg.snap->ps.clientNum) - { + if (es->trickedentindex == cg.snap->ps.clientNum) { trap->Cvar_Set("ui_rankChange", va("%i", es->eventParm)); trap->Cvar_Set("ui_myteam", va("%i", es->bolt2)); - if (!( trap->Key_GetCatcher() & KEYCATCH_UI ) && !es->bolt1) - { + if (!(trap->Key_GetCatcher() & KEYCATCH_UI) && !es->bolt1) { trap->OpenUIMenu(UIMENU_PLAYERCONFIG); } } @@ -2864,103 +2517,76 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { float shotDist = VectorNormalize(es->angles); vec3_t spot; - for (dist = 0.0f; dist < shotDist; dist += 64.0f) - { //one effect would be.. a whole lot better - VectorMA( es->origin2, dist, es->angles, spot ); - trap->FX_PlayEffectID(cgs.effects.mConcussionAltRing, spot, es->angles2, -1, -1, qfalse); + for (dist = 0.0f; dist < shotDist; dist += 64.0f) { // one effect would be.. a whole lot better + VectorMA(es->origin2, dist, es->angles, spot); + trap->FX_PlayEffectID(cgs.effects.mConcussionAltRing, spot, es->angles2, -1, -1, qfalse); } - ByteToDir( es->eventParm, dir ); + ByteToDir(es->eventParm, dir); CG_MissileHitWall(WP_CONCUSSION, es->owner, position, dir, IMPACTSOUND_DEFAULT, qtrue, 0); FX_ConcAltShot(es->origin2, spot); - //steal the bezier effect from the disruptor + // steal the bezier effect from the disruptor FX_DisruptorAltMiss(position, dir); } break; case EV_MISSILE_STICK: DEBUGNAME("EV_MISSILE_STICK"); -// trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.missileStick ); + // trap->S_StartSound (NULL, es->number, CHAN_AUTO, cgs.media.missileStick ); break; case EV_MISSILE_HIT: DEBUGNAME("EV_MISSILE_HIT"); - ByteToDir( es->eventParm, dir ); - if ( es->emplacedOwner ) - {//hack: this is an index to a custom effect to use + ByteToDir(es->eventParm, dir); + if (es->emplacedOwner) { // hack: this is an index to a custom effect to use trap->FX_PlayEffectID(cgs.gameEffects[es->emplacedOwner], position, dir, -1, -1, qfalse); - } - else if ( CG_VehicleWeaponImpact( cent ) ) - {//a vehicle missile that uses an overridden impact effect... - } - else if (cent->currentState.eFlags & EF_ALT_FIRING) - { - CG_MissileHitPlayer( es->weapon, position, dir, es->otherEntityNum, qtrue); - } - else - { - CG_MissileHitPlayer( es->weapon, position, dir, es->otherEntityNum, qfalse); + } else if (CG_VehicleWeaponImpact(cent)) { // a vehicle missile that uses an overridden impact effect... + } else if (cent->currentState.eFlags & EF_ALT_FIRING) { + CG_MissileHitPlayer(es->weapon, position, dir, es->otherEntityNum, qtrue); + } else { + CG_MissileHitPlayer(es->weapon, position, dir, es->otherEntityNum, qfalse); } - if (cg_ghoul2Marks.integer && - es->trickedentindex) - { //flag to place a ghoul2 mark + if (cg_ghoul2Marks.integer && es->trickedentindex) { // flag to place a ghoul2 mark CG_G2MarkEvent(es); } break; case EV_MISSILE_MISS: DEBUGNAME("EV_MISSILE_MISS"); - ByteToDir( es->eventParm, dir ); - if ( es->emplacedOwner ) - {//hack: this is an index to a custom effect to use + ByteToDir(es->eventParm, dir); + if (es->emplacedOwner) { // hack: this is an index to a custom effect to use trap->FX_PlayEffectID(cgs.gameEffects[es->emplacedOwner], position, dir, -1, -1, qfalse); - } - else if ( CG_VehicleWeaponImpact( cent ) ) - {//a vehicle missile that used an overridden impact effect... - } - else if (cent->currentState.eFlags & EF_ALT_FIRING) - { + } else if (CG_VehicleWeaponImpact(cent)) { // a vehicle missile that used an overridden impact effect... + } else if (cent->currentState.eFlags & EF_ALT_FIRING) { CG_MissileHitWall(es->weapon, 0, position, dir, IMPACTSOUND_DEFAULT, qtrue, es->generic1); - } - else - { + } else { CG_MissileHitWall(es->weapon, 0, position, dir, IMPACTSOUND_DEFAULT, qfalse, 0); } - if (cg_ghoul2Marks.integer && - es->trickedentindex) - { //flag to place a ghoul2 mark + if (cg_ghoul2Marks.integer && es->trickedentindex) { // flag to place a ghoul2 mark CG_G2MarkEvent(es); } break; case EV_MISSILE_MISS_METAL: DEBUGNAME("EV_MISSILE_MISS_METAL"); - ByteToDir( es->eventParm, dir ); - if ( es->emplacedOwner ) - {//hack: this is an index to a custom effect to use + ByteToDir(es->eventParm, dir); + if (es->emplacedOwner) { // hack: this is an index to a custom effect to use trap->FX_PlayEffectID(cgs.gameEffects[es->emplacedOwner], position, dir, -1, -1, qfalse); - } - else if ( CG_VehicleWeaponImpact( cent ) ) - {//a vehicle missile that used an overridden impact effect... - } - else if (cent->currentState.eFlags & EF_ALT_FIRING) - { + } else if (CG_VehicleWeaponImpact(cent)) { // a vehicle missile that used an overridden impact effect... + } else if (cent->currentState.eFlags & EF_ALT_FIRING) { CG_MissileHitWall(es->weapon, 0, position, dir, IMPACTSOUND_METAL, qtrue, es->generic1); - } - else - { + } else { CG_MissileHitWall(es->weapon, 0, position, dir, IMPACTSOUND_METAL, qfalse, 0); } break; case EV_PLAY_EFFECT: DEBUGNAME("EV_PLAY_EFFECT"); - switch(es->eventParm) - { //it isn't a hack, it's ingenuity! + switch (es->eventParm) { // it isn't a hack, it's ingenuity! case EFFECT_SMOKE: eID = cgs.effects.mEmplacedDeadSmoke; break; @@ -2986,7 +2612,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { eID = cgs.effects.mStunBatonFleshImpact; break; case EFFECT_EXPLOSION_DEMP2ALT: - FX_DEMP2_AltDetonate( cent->lerpOrigin, es->weapon ); + FX_DEMP2_AltDetonate(cent->lerpOrigin, es->weapon); eID = cgs.effects.mAltDetonate; break; case EFFECT_EXPLOSION_TURRET: @@ -3024,14 +2650,12 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { break; } - if (eID != -1) - { + if (eID != -1) { vec3_t fxDir; VectorCopy(es->angles, fxDir); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } @@ -3047,40 +2671,30 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { qboolean portalEffect = qfalse; int efxIndex = 0; - if (event == EV_PLAY_PORTAL_EFFECT_ID) - { //This effect should only be played inside sky portals. + if (event == EV_PLAY_PORTAL_EFFECT_ID) { // This effect should only be played inside sky portals. portalEffect = qtrue; } AngleVectors(es->angles, fxDir, 0, 0); - if (!fxDir[0] && !fxDir[1] && !fxDir[2]) - { + if (!fxDir[0] && !fxDir[1] && !fxDir[2]) { fxDir[1] = 1; } - if ( cgs.gameEffects[ es->eventParm ] ) - { + if (cgs.gameEffects[es->eventParm]) { efxIndex = cgs.gameEffects[es->eventParm]; - } - else - { - s = CG_ConfigString( CS_EFFECTS + es->eventParm ); - if (s && s[0]) - { + } else { + s = CG_ConfigString(CS_EFFECTS + es->eventParm); + if (s && s[0]) { efxIndex = trap->FX_RegisterEffect(s); } } - if (efxIndex) - { - if (portalEffect) - { - trap->FX_PlayEffectID(efxIndex, position, fxDir, -1, -1, qtrue ); - } - else - { - trap->FX_PlayEffectID(efxIndex, position, fxDir, -1, -1, qfalse ); + if (efxIndex) { + if (portalEffect) { + trap->FX_PlayEffectID(efxIndex, position, fxDir, -1, -1, qtrue); + } else { + trap->FX_PlayEffectID(efxIndex, position, fxDir, -1, -1, qfalse); } } } @@ -3098,29 +2712,25 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { sfxHandle_t sfx; const char *soundSet; - soundSet = CG_ConfigString( CS_AMBIENT_SET + es->soundSetIndex ); + soundSet = CG_ConfigString(CS_AMBIENT_SET + es->soundSetIndex); - if (!soundSet || !soundSet[0]) - { + if (!soundSet || !soundSet[0]) { break; } sfx = trap->AS_GetBModelSound(soundSet, es->eventParm); - if (sfx == -1) - { + if (sfx == -1) { break; } - trap->S_StartSound( NULL, es->number, CHAN_AUTO, sfx ); + trap->S_StartSound(NULL, es->number, CHAN_AUTO, sfx); } break; - case EV_MUTE_SOUND: DEBUGNAME("EV_MUTE_SOUND"); - if (cg_entities[es->trickedentindex2].currentState.eFlags & EF_SOUNDTRACKER) - { + if (cg_entities[es->trickedentindex2].currentState.eFlags & EF_SOUNDTRACKER) { cg_entities[es->trickedentindex2].currentState.eFlags &= ~EF_SOUNDTRACKER; } trap->S_MuteSound(es->trickedentindex2, es->trickedentindex); @@ -3129,43 +2739,37 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_VOICECMD_SOUND: DEBUGNAME("EV_VOICECMD_SOUND"); - if (es->groundEntityNum < MAX_CLIENTS && es->groundEntityNum >= 0) - { + if (es->groundEntityNum < MAX_CLIENTS && es->groundEntityNum >= 0) { int clientNum = es->groundEntityNum; - sfxHandle_t sfx = cgs.gameSounds[ es->eventParm ]; + sfxHandle_t sfx = cgs.gameSounds[es->eventParm]; clientInfo_t *ci = &cgs.clientinfo[clientNum]; centity_t *vChatEnt = &cg_entities[clientNum]; char descr[1024] = {0}; - Q_strncpyz(descr, CG_GetStringForVoiceSound(CG_ConfigString( CS_SOUNDS + es->eventParm )), sizeof( descr ) ); + Q_strncpyz(descr, CG_GetStringForVoiceSound(CG_ConfigString(CS_SOUNDS + es->eventParm)), sizeof(descr)); - if (!sfx) - { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - sfx = CG_CustomSound( clientNum, s ); + if (!sfx) { + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + sfx = CG_CustomSound(clientNum, s); } - if (sfx) - { - if (clientNum != cg.predictedPlayerState.clientNum) - { //play on the head as well to simulate hearing in radio and in world - if (ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) - { //don't hear it if this person is on the other team, but they can still - //hear it in the world spot. - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_MENU1, sfx); + if (sfx) { + if (clientNum != cg.predictedPlayerState.clientNum) { // play on the head as well to simulate hearing in radio and in world + if (ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) { // don't hear it if this person is on the other team, but they can still + // hear it in the world spot. + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_MENU1, sfx); } } - if (ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) - { //add to the chat box - //hear it in the world spot. + if (ci->team == cg.predictedPlayerState.persistant[PERS_TEAM]) { // add to the chat box + // hear it in the world spot. char vchatstr[1024] = {0}; - Q_strncpyz(vchatstr, va("<%s^7: %s>\n", ci->name, descr), sizeof( vchatstr ) ); + Q_strncpyz(vchatstr, va("<%s^7: %s>\n", ci->name, descr), sizeof(vchatstr)); CG_ChatBox_AddString(vchatstr); trap->Print("*%s", vchatstr); } - //and play in world for everyone - trap->S_StartSound (NULL, clientNum, CHAN_VOICE, sfx); + // and play in world for everyone + trap->S_StartSound(NULL, clientNum, CHAN_VOICE, sfx); vChatEnt->vChatTime = cg.time + 1000; } } @@ -3174,116 +2778,100 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_GENERAL_SOUND: DEBUGNAME("EV_GENERAL_SOUND"); if (es->saberEntityNum == TRACK_CHANNEL_2 || es->saberEntityNum == TRACK_CHANNEL_3 || - es->saberEntityNum == TRACK_CHANNEL_5) - { //channels 2 and 3 are for speed and rage, 5 for sight - if ( cgs.gameSounds[ es->eventParm ] ) - { - CG_S_AddRealLoopingSound(es->number, es->pos.trBase, vec3_origin, cgs.gameSounds[ es->eventParm ] ); + es->saberEntityNum == TRACK_CHANNEL_5) { // channels 2 and 3 are for speed and rage, 5 for sight + if (cgs.gameSounds[es->eventParm]) { + CG_S_AddRealLoopingSound(es->number, es->pos.trBase, vec3_origin, cgs.gameSounds[es->eventParm]); } - } - else - { - if ( cgs.gameSounds[ es->eventParm ] ) { - trap->S_StartSound (NULL, es->number, es->saberEntityNum, cgs.gameSounds[ es->eventParm ] ); + } else { + if (cgs.gameSounds[es->eventParm]) { + trap->S_StartSound(NULL, es->number, es->saberEntityNum, cgs.gameSounds[es->eventParm]); } else { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - trap->S_StartSound (NULL, es->number, es->saberEntityNum, CG_CustomSound( es->number, s ) ); + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + trap->S_StartSound(NULL, es->number, es->saberEntityNum, CG_CustomSound(es->number, s)); } } break; - case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes + case EV_GLOBAL_SOUND: // play from the player's head so it never diminishes DEBUGNAME("EV_GLOBAL_SOUND"); - if ( cgs.gameSounds[ es->eventParm ] ) { - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_MENU1, cgs.gameSounds[ es->eventParm ] ); + if (cgs.gameSounds[es->eventParm]) { + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_MENU1, cgs.gameSounds[es->eventParm]); } else { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - trap->S_StartSound (NULL, cg.snap->ps.clientNum, CHAN_MENU1, CG_CustomSound( es->number, s ) ); + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + trap->S_StartSound(NULL, cg.snap->ps.clientNum, CHAN_MENU1, CG_CustomSound(es->number, s)); } break; - case EV_GLOBAL_TEAM_SOUND: // play from the player's head so it never diminishes - { - DEBUGNAME("EV_GLOBAL_TEAM_SOUND"); - switch( es->eventParm ) { - case GTS_RED_CAPTURE: // CTF: red team captured the blue flag, 1FCTF: red team captured the neutral flag - //CG_AddBufferedSound( cgs.media.redScoredSound ); - break; - case GTS_BLUE_CAPTURE: // CTF: blue team captured the red flag, 1FCTF: blue team captured the neutral flag - //CG_AddBufferedSound( cgs.media.blueScoredSound ); - break; - case GTS_RED_RETURN: // CTF: blue flag returned, 1FCTF: never used - if (cgs.gametype == GT_CTY) - { - CG_AddBufferedSound( cgs.media.blueYsalReturnedSound ); - } - else - { - CG_AddBufferedSound( cgs.media.blueFlagReturnedSound ); - } - break; - case GTS_BLUE_RETURN: // CTF red flag returned, 1FCTF: neutral flag returned - if (cgs.gametype == GT_CTY) - { - CG_AddBufferedSound( cgs.media.redYsalReturnedSound ); - } - else - { - CG_AddBufferedSound( cgs.media.redFlagReturnedSound ); - } - break; + case EV_GLOBAL_TEAM_SOUND: // play from the player's head so it never diminishes + { + DEBUGNAME("EV_GLOBAL_TEAM_SOUND"); + switch (es->eventParm) { + case GTS_RED_CAPTURE: // CTF: red team captured the blue flag, 1FCTF: red team captured the neutral flag + // CG_AddBufferedSound( cgs.media.redScoredSound ); + break; + case GTS_BLUE_CAPTURE: // CTF: blue team captured the red flag, 1FCTF: blue team captured the neutral flag + // CG_AddBufferedSound( cgs.media.blueScoredSound ); + break; + case GTS_RED_RETURN: // CTF: blue flag returned, 1FCTF: never used + if (cgs.gametype == GT_CTY) { + CG_AddBufferedSound(cgs.media.blueYsalReturnedSound); + } else { + CG_AddBufferedSound(cgs.media.blueFlagReturnedSound); + } + break; + case GTS_BLUE_RETURN: // CTF red flag returned, 1FCTF: neutral flag returned + if (cgs.gametype == GT_CTY) { + CG_AddBufferedSound(cgs.media.redYsalReturnedSound); + } else { + CG_AddBufferedSound(cgs.media.redFlagReturnedSound); + } + break; - case GTS_RED_TAKEN: // CTF: red team took blue flag, 1FCTF: blue team took the neutral flag - // if this player picked up the flag then a sound is played in CG_CheckLocalSounds - if (cgs.gametype == GT_CTY) - { - CG_AddBufferedSound( cgs.media.redTookYsalSound ); - } - else - { - CG_AddBufferedSound( cgs.media.redTookFlagSound ); - } - break; - case GTS_BLUE_TAKEN: // CTF: blue team took the red flag, 1FCTF red team took the neutral flag - // if this player picked up the flag then a sound is played in CG_CheckLocalSounds - if (cgs.gametype == GT_CTY) - { - CG_AddBufferedSound( cgs.media.blueTookYsalSound ); - } - else - { - CG_AddBufferedSound( cgs.media.blueTookFlagSound ); - } - break; - case GTS_REDTEAM_SCORED: - CG_AddBufferedSound(cgs.media.redScoredSound); - break; - case GTS_BLUETEAM_SCORED: - CG_AddBufferedSound(cgs.media.blueScoredSound); - break; - case GTS_REDTEAM_TOOK_LEAD: - CG_AddBufferedSound(cgs.media.redLeadsSound); - break; - case GTS_BLUETEAM_TOOK_LEAD: - CG_AddBufferedSound(cgs.media.blueLeadsSound); - break; - case GTS_TEAMS_ARE_TIED: - CG_AddBufferedSound( cgs.media.teamsTiedSound ); - break; - default: - break; + case GTS_RED_TAKEN: // CTF: red team took blue flag, 1FCTF: blue team took the neutral flag + // if this player picked up the flag then a sound is played in CG_CheckLocalSounds + if (cgs.gametype == GT_CTY) { + CG_AddBufferedSound(cgs.media.redTookYsalSound); + } else { + CG_AddBufferedSound(cgs.media.redTookFlagSound); + } + break; + case GTS_BLUE_TAKEN: // CTF: blue team took the red flag, 1FCTF red team took the neutral flag + // if this player picked up the flag then a sound is played in CG_CheckLocalSounds + if (cgs.gametype == GT_CTY) { + CG_AddBufferedSound(cgs.media.blueTookYsalSound); + } else { + CG_AddBufferedSound(cgs.media.blueTookFlagSound); } break; + case GTS_REDTEAM_SCORED: + CG_AddBufferedSound(cgs.media.redScoredSound); + break; + case GTS_BLUETEAM_SCORED: + CG_AddBufferedSound(cgs.media.blueScoredSound); + break; + case GTS_REDTEAM_TOOK_LEAD: + CG_AddBufferedSound(cgs.media.redLeadsSound); + break; + case GTS_BLUETEAM_TOOK_LEAD: + CG_AddBufferedSound(cgs.media.blueLeadsSound); + break; + case GTS_TEAMS_ARE_TIED: + CG_AddBufferedSound(cgs.media.teamsTiedSound); + break; + default: + break; } + break; + } case EV_ENTITY_SOUND: DEBUGNAME("EV_ENTITY_SOUND"); - //somewhat of a hack - weapon is the caller entity's index, trickedentindex is the proper sound channel - if ( cgs.gameSounds[ es->eventParm ] ) { - trap->S_StartSound (NULL, es->clientNum, es->trickedentindex, cgs.gameSounds[ es->eventParm ] ); + // somewhat of a hack - weapon is the caller entity's index, trickedentindex is the proper sound channel + if (cgs.gameSounds[es->eventParm]) { + trap->S_StartSound(NULL, es->clientNum, es->trickedentindex, cgs.gameSounds[es->eventParm]); } else { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); - trap->S_StartSound (NULL, es->clientNum, es->trickedentindex, CG_CustomSound( es->clientNum, s ) ); + s = CG_ConfigString(CS_SOUNDS + es->eventParm); + trap->S_StartSound(NULL, es->clientNum, es->trickedentindex, CG_CustomSound(es->clientNum, s)); } break; @@ -3299,8 +2887,8 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DEBRIS: DEBUGNAME("EV_DEBRIS"); - CG_Chunks(es->owner, es->origin, es->angles, es->origin2, es->angles2, es->speed, - es->eventParm, es->trickedentindex, es->modelindex, es->apos.trBase[0]); + CG_Chunks(es->owner, es->origin, es->angles, es->origin2, es->angles2, es->speed, es->eventParm, es->trickedentindex, es->modelindex, + es->apos.trBase[0]); break; case EV_MISC_MODEL_EXP: @@ -3313,9 +2901,8 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { // so ignore events on the player DEBUGNAME("EV_PAIN"); - if ( !cg_oldPainSounds.integer || (cent->currentState.number != cg.snap->ps.clientNum) ) - { - CG_PainEvent( cent, es->eventParm ); + if (!cg_oldPainSounds.integer || (cent->currentState.number != cg.snap->ps.clientNum)) { + CG_PainEvent(cent, es->eventParm); } break; @@ -3323,89 +2910,80 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DEATH2: case EV_DEATH3: DEBUGNAME("EV_DEATHx"); - trap->S_StartSound( NULL, es->number, CHAN_VOICE, - CG_CustomSound( es->number, va("*death%i.wav", event - EV_DEATH1 + 1) ) ); - if (es->eventParm && es->number == cg.snap->ps.clientNum) - { + trap->S_StartSound(NULL, es->number, CHAN_VOICE, CG_CustomSound(es->number, va("*death%i.wav", event - EV_DEATH1 + 1))); + if (es->eventParm && es->number == cg.snap->ps.clientNum) { trap->S_StartLocalSound(cgs.media.dramaticFailure, CHAN_LOCAL); CGCam_SetMusicMult(0.3f, 5000); } break; - case EV_OBITUARY: DEBUGNAME("EV_OBITUARY"); - CG_Obituary( es ); + CG_Obituary(es); break; - // - // powerup events - // + // + // powerup events + // #ifdef BASE_COMPAT case EV_POWERUP_QUAD: DEBUGNAME("EV_POWERUP_QUAD"); - if ( es->number == cg.snap->ps.clientNum ) { + if (es->number == cg.snap->ps.clientNum) { cg.powerupActive = PW_QUAD; cg.powerupTime = cg.time; } - //trap->S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.quadSound ); + // trap->S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.quadSound ); break; case EV_POWERUP_BATTLESUIT: DEBUGNAME("EV_POWERUP_BATTLESUIT"); - if ( es->number == cg.snap->ps.clientNum ) { + if (es->number == cg.snap->ps.clientNum) { cg.powerupActive = PW_BATTLESUIT; cg.powerupTime = cg.time; } - //trap->S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.protectSound ); + // trap->S_StartSound (NULL, es->number, CHAN_ITEM, cgs.media.protectSound ); break; #endif // BASE_COMPAT case EV_FORCE_DRAINED: DEBUGNAME("EV_FORCE_DRAINED"); - ByteToDir( es->eventParm, dir ); - //FX_ForceDrained(position, dir); - trap->S_StartSound (NULL, es->owner, CHAN_AUTO, cgs.media.drainSound ); + ByteToDir(es->eventParm, dir); + // FX_ForceDrained(position, dir); + trap->S_StartSound(NULL, es->owner, CHAN_AUTO, cgs.media.drainSound); cg_entities[es->owner].teamPowerEffectTime = cg.time + 1000; cg_entities[es->owner].teamPowerType = 2; break; case EV_GIB_PLAYER: DEBUGNAME("EV_GIB_PLAYER"); - //trap->S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.gibSound ); - //CG_GibPlayer( cent->lerpOrigin ); + // trap->S_StartSound( NULL, es->number, CHAN_BODY, cgs.media.gibSound ); + // CG_GibPlayer( cent->lerpOrigin ); break; case EV_STARTLOOPINGSOUND: DEBUGNAME("EV_STARTLOOPINGSOUND"); - if ( cgs.gameSounds[ es->eventParm ] ) - { + if (cgs.gameSounds[es->eventParm]) { isnd = cgs.gameSounds[es->eventParm]; - } - else - { - s = CG_ConfigString( CS_SOUNDS + es->eventParm ); + } else { + s = CG_ConfigString(CS_SOUNDS + es->eventParm); isnd = CG_CustomSound(es->number, s); } - CG_S_AddRealLoopingSound( es->number, es->pos.trBase, vec3_origin, isnd ); + CG_S_AddRealLoopingSound(es->number, es->pos.trBase, vec3_origin, isnd); es->loopSound = isnd; break; case EV_STOPLOOPINGSOUND: DEBUGNAME("EV_STOPLOOPINGSOUND"); - CG_S_StopLoopingSound( es->number, -1 ); + CG_S_StopLoopingSound(es->number, -1); es->loopSound = 0; break; case EV_WEAPON_CHARGE: DEBUGNAME("EV_WEAPON_CHARGE"); assert(es->eventParm > WP_NONE && es->eventParm < WP_NUM_WEAPONS); - if (cg_weapons[es->eventParm].chargeSound) - { + if (cg_weapons[es->eventParm].chargeSound) { trap->S_StartSound(NULL, es->number, CHAN_WEAPON, cg_weapons[es->eventParm].chargeSound); - } - else if (es->eventParm == WP_DISRUPTOR) - { + } else if (es->eventParm == WP_DISRUPTOR) { trap->S_StartSound(NULL, es->number, CHAN_WEAPON, cgs.media.disruptorZoomLoop); } break; @@ -3413,8 +2991,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_WEAPON_CHARGE_ALT: DEBUGNAME("EV_WEAPON_CHARGE_ALT"); assert(es->eventParm > WP_NONE && es->eventParm < WP_NUM_WEAPONS); - if (cg_weapons[es->eventParm].altChargeSound) - { + if (cg_weapons[es->eventParm].altChargeSound) { trap->S_StartSound(NULL, es->number, CHAN_WEAPON, cg_weapons[es->eventParm].altChargeSound); } break; @@ -3427,7 +3004,7 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { case EV_DEBUG_LINE: DEBUGNAME("EV_DEBUG_LINE"); - CG_Beam( cent ); + CG_Beam(cent); break; case EV_TESTLINE: @@ -3437,27 +3014,25 @@ void CG_EntityEvent( centity_t *cent, vec3_t position ) { default: DEBUGNAME("UNKNOWN"); - trap->Error( ERR_DROP, "Unknown event: %i", event ); + trap->Error(ERR_DROP, "Unknown event: %i", event); break; } - } - /* ============== CG_CheckEvents ============== */ -void CG_CheckEvents( centity_t *cent ) { +void CG_CheckEvents(centity_t *cent) { // check for event-only entities - if ( cent->currentState.eType > ET_EVENTS ) { - if ( cent->previousEvent ) { - return; // already fired + if (cent->currentState.eType > ET_EVENTS) { + if (cent->previousEvent) { + return; // already fired } // if this is a player event set the entity number of the client entity number - if ( cent->currentState.eFlags & EF_PLAYER_EVENT ) { + if (cent->currentState.eFlags & EF_PLAYER_EVENT) { cent->currentState.number = cent->currentState.otherEntityNum; } @@ -3466,19 +3041,18 @@ void CG_CheckEvents( centity_t *cent ) { cent->currentState.event = cent->currentState.eType - ET_EVENTS; } else { // check for events riding with another entity - if ( cent->currentState.event == cent->previousEvent ) { + if (cent->currentState.event == cent->previousEvent) { return; } cent->previousEvent = cent->currentState.event; - if ( ( cent->currentState.event & ~EV_EVENT_BITS ) == 0 ) { + if ((cent->currentState.event & ~EV_EVENT_BITS) == 0) { return; } } // calculate the position at exactly the frame time - BG_EvaluateTrajectory( ¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin ); - CG_SetEntitySoundPosition( cent ); + BG_EvaluateTrajectory(¢->currentState.pos, cg.snap->serverTime, cent->lerpOrigin); + CG_SetEntitySoundPosition(cent); - CG_EntityEvent( cent, cent->lerpOrigin ); + CG_EntityEvent(cent, cent->lerpOrigin); } - diff --git a/codemp/cgame/cg_info.c b/codemp/cgame/cg_info.c index 75342288de..f5ba7e14cb 100644 --- a/codemp/cgame/cg_info.c +++ b/codemp/cgame/cg_info.c @@ -25,11 +25,11 @@ along with this program; if not, see . #include "cg_local.h" -#define MAX_LOADING_PLAYER_ICONS 16 -#define MAX_LOADING_ITEM_ICONS 26 +#define MAX_LOADING_PLAYER_ICONS 16 +#define MAX_LOADING_ITEM_ICONS 26 -//static int loadingPlayerIconCount; -//static qhandle_t loadingPlayerIcons[MAX_LOADING_PLAYER_ICONS]; +// static int loadingPlayerIconCount; +// static qhandle_t loadingPlayerIcons[MAX_LOADING_PLAYER_ICONS]; void CG_LoadBar(void); @@ -39,8 +39,8 @@ CG_LoadingString ====================== */ -void CG_LoadingString( const char *s ) { - Q_strncpyz( cg.infoScreenText, s, sizeof( cg.infoScreenText ) ); +void CG_LoadingString(const char *s) { + Q_strncpyz(cg.infoScreenText, s, sizeof(cg.infoScreenText)); trap->UpdateScreen(); } @@ -50,20 +50,19 @@ void CG_LoadingString( const char *s ) { CG_LoadingItem =================== */ -void CG_LoadingItem( int itemNum ) { - gitem_t *item; - char upperKey[1024]; +void CG_LoadingItem(int itemNum) { + gitem_t *item; + char upperKey[1024]; item = &bg_itemlist[itemNum]; - if (!item->classname || !item->classname[0]) - { - // CG_LoadingString( "Unknown item" ); + if (!item->classname || !item->classname[0]) { + // CG_LoadingString( "Unknown item" ); return; } strcpy(upperKey, item->classname); - CG_LoadingString( CG_GetStringEdString("SP_INGAME",Q_strupr(upperKey)) ); + CG_LoadingString(CG_GetStringEdString("SP_INGAME", Q_strupr(upperKey))); } /* @@ -71,43 +70,43 @@ void CG_LoadingItem( int itemNum ) { CG_LoadingClient =================== */ -void CG_LoadingClient( int clientNum ) { - const char *info; - char personality[MAX_QPATH]; +void CG_LoadingClient(int clientNum) { + const char *info; + char personality[MAX_QPATH]; - info = CG_ConfigString( CS_PLAYERS + clientNum ); + info = CG_ConfigString(CS_PLAYERS + clientNum); -/* - char model[MAX_QPATH]; - char iconName[MAX_QPATH]; - char *skin; - if ( loadingPlayerIconCount < MAX_LOADING_PLAYER_ICONS ) { - Q_strncpyz( model, Info_ValueForKey( info, "model" ), sizeof( model ) ); - skin = Q_strrchr( model, '/' ); - if ( skin ) { - *skin++ = '\0'; - } else { - skin = "default"; - } + /* + char model[MAX_QPATH]; + char iconName[MAX_QPATH]; + char *skin; + if ( loadingPlayerIconCount < MAX_LOADING_PLAYER_ICONS ) { + Q_strncpyz( model, Info_ValueForKey( info, "model" ), sizeof( model ) ); + skin = Q_strrchr( model, '/' ); + if ( skin ) { + *skin++ = '\0'; + } else { + skin = "default"; + } - Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", model, skin ); + Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", model, skin ); - loadingPlayerIcons[loadingPlayerIconCount] = trap->R_RegisterShaderNoMip( iconName ); - if ( !loadingPlayerIcons[loadingPlayerIconCount] ) { - Com_sprintf( iconName, MAX_QPATH, "models/players/characters/%s/icon_%s.tga", model, skin ); loadingPlayerIcons[loadingPlayerIconCount] = trap->R_RegisterShaderNoMip( iconName ); + if ( !loadingPlayerIcons[loadingPlayerIconCount] ) { + Com_sprintf( iconName, MAX_QPATH, "models/players/characters/%s/icon_%s.tga", model, skin ); + loadingPlayerIcons[loadingPlayerIconCount] = trap->R_RegisterShaderNoMip( iconName ); + } + if ( !loadingPlayerIcons[loadingPlayerIconCount] ) { + Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", DEFAULT_MODEL, "default" ); + loadingPlayerIcons[loadingPlayerIconCount] = trap->R_RegisterShaderNoMip( iconName ); + } + if ( loadingPlayerIcons[loadingPlayerIconCount] ) { + loadingPlayerIconCount++; + } } - if ( !loadingPlayerIcons[loadingPlayerIconCount] ) { - Com_sprintf( iconName, MAX_QPATH, "models/players/%s/icon_%s.tga", DEFAULT_MODEL, "default" ); - loadingPlayerIcons[loadingPlayerIconCount] = trap->R_RegisterShaderNoMip( iconName ); - } - if ( loadingPlayerIcons[loadingPlayerIconCount] ) { - loadingPlayerIconCount++; - } - } -*/ - Q_strncpyz( personality, Info_ValueForKey( info, "n" ), sizeof(personality) ); -// Q_CleanStr( personality ); + */ + Q_strncpyz(personality, Info_ValueForKey(info, "n"), sizeof(personality)); + // Q_CleanStr( personality ); /* if( cgs.gametype == GT_SINGLE_PLAYER ) { @@ -115,10 +114,9 @@ void CG_LoadingClient( int clientNum ) { } */ - CG_LoadingString( personality ); + CG_LoadingString(personality); } - /* ==================== CG_DrawInformation @@ -128,77 +126,76 @@ Draw all the status / pacifier stuff during level loading overlays UI_DrawConnectScreen */ #define UI_INFOFONT (UI_BIGFONT) -void CG_DrawInformation( void ) { - const char *s; - const char *info; - const char *sysInfo; - int y; - int value, valueNOFP; - qhandle_t levelshot; - char buf[1024]; - int iPropHeight = 18; // I know, this is total crap, but as a post release asian-hack.... -Ste - - info = CG_ConfigString( CS_SERVERINFO ); - sysInfo = CG_ConfigString( CS_SYSTEMINFO ); - - s = Info_ValueForKey( info, "mapname" ); - levelshot = trap->R_RegisterShaderNoMip( va( "levelshots/%s", s ) ); - if ( !levelshot ) { - levelshot = trap->R_RegisterShaderNoMip( "menu/art/unknownmap_mp" ); +void CG_DrawInformation(void) { + const char *s; + const char *info; + const char *sysInfo; + int y; + int value, valueNOFP; + qhandle_t levelshot; + char buf[1024]; + int iPropHeight = 18; // I know, this is total crap, but as a post release asian-hack.... -Ste + + info = CG_ConfigString(CS_SERVERINFO); + sysInfo = CG_ConfigString(CS_SYSTEMINFO); + + s = Info_ValueForKey(info, "mapname"); + levelshot = trap->R_RegisterShaderNoMip(va("levelshots/%s", s)); + if (!levelshot) { + levelshot = trap->R_RegisterShaderNoMip("menu/art/unknownmap_mp"); } - trap->R_SetColor( NULL ); - CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot ); + trap->R_SetColor(NULL); + CG_DrawPic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, levelshot); CG_LoadBar(); // draw the icons of things as they are loaded -// CG_DrawLoadingIcons(); + // CG_DrawLoadingIcons(); // the first 150 rows are reserved for the client connection // screen to write into - if ( cg.infoScreenText[0] ) { + if (cg.infoScreenText[0]) { const char *psLoading = CG_GetStringEdString("MENUS", "LOADING_MAPNAME"); - CG_DrawProportionalString( 320, 128-32, va(/*"Loading... %s"*/ psLoading, cg.infoScreenText), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, 128 - 32, va(/*"Loading... %s"*/ psLoading, cg.infoScreenText), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); } else { const char *psAwaitingSnapshot = CG_GetStringEdString("MENUS", "AWAITING_SNAPSHOT"); - CG_DrawProportionalString( 320, 128-32, /*"Awaiting snapshot..."*/psAwaitingSnapshot, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, 128 - 32, /*"Awaiting snapshot..."*/ psAwaitingSnapshot, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); } // draw info string information - y = 180-32; + y = 180 - 32; // don't print server lines if playing a local game - trap->Cvar_VariableStringBuffer( "sv_running", buf, sizeof( buf ) ); - if ( !atoi( buf ) ) { + trap->Cvar_VariableStringBuffer("sv_running", buf, sizeof(buf)); + if (!atoi(buf)) { // server hostname - Q_strncpyz(buf, Info_ValueForKey( info, "sv_hostname" ), sizeof( buf ) ); + Q_strncpyz(buf, Info_ValueForKey(info, "sv_hostname"), sizeof(buf)); Q_CleanStr(buf); - CG_DrawProportionalString( 320, y, buf, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, buf, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; // pure server - s = Info_ValueForKey( sysInfo, "sv_pure" ); - if ( s[0] == '1' ) { + s = Info_ValueForKey(sysInfo, "sv_pure"); + if (s[0] == '1') { const char *psPure = CG_GetStringEdString("MP_INGAME", "PURE_SERVER"); - CG_DrawProportionalString( 320, y, psPure, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, psPure, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } // server-specific message of the day - s = CG_ConfigString( CS_MOTD ); - if ( s[0] ) { - CG_DrawProportionalString( 320, y, s, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + s = CG_ConfigString(CS_MOTD); + if (s[0]) { + CG_DrawProportionalString(320, y, s, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } - { // display global MOTD at bottom (mirrors ui_main UI_DrawConnectScreen + { // display global MOTD at bottom (mirrors ui_main UI_DrawConnectScreen char motdString[1024]; - trap->Cvar_VariableStringBuffer( "cl_motdString", motdString, sizeof( motdString ) ); + trap->Cvar_VariableStringBuffer("cl_motdString", motdString, sizeof(motdString)); - if (motdString[0]) - { - CG_DrawProportionalString( 320, 425, motdString, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (motdString[0]) { + CG_DrawProportionalString(320, 425, motdString, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); } } @@ -207,44 +204,45 @@ void CG_DrawInformation( void ) { } // map-specific message (long map name) - s = CG_ConfigString( CS_MESSAGE ); - if ( s[0] ) { - CG_DrawProportionalString( 320, y, s, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + s = CG_ConfigString(CS_MESSAGE); + if (s[0]) { + CG_DrawProportionalString(320, y, s, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } // cheats warning - s = Info_ValueForKey( sysInfo, "sv_cheats" ); - if ( s[0] == '1' ) { - CG_DrawProportionalString( 320, y, CG_GetStringEdString("MP_INGAME", "CHEATSAREENABLED"), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + s = Info_ValueForKey(sysInfo, "sv_cheats"); + if (s[0] == '1') { + CG_DrawProportionalString(320, y, CG_GetStringEdString("MP_INGAME", "CHEATSAREENABLED"), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } // game type - s = BG_GetGametypeString( cgs.gametype ); - CG_DrawProportionalString( 320, y, s, UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + s = BG_GetGametypeString(cgs.gametype); + CG_DrawProportionalString(320, y, s, UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; - if (cgs.gametype != GT_SIEGE) - { - value = atoi( Info_ValueForKey( info, "timelimit" ) ); - if ( value ) { - CG_DrawProportionalString( 320, y, va( "%s %i", CG_GetStringEdString("MP_INGAME", "TIMELIMIT"), value ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (cgs.gametype != GT_SIEGE) { + value = atoi(Info_ValueForKey(info, "timelimit")); + if (value) { + CG_DrawProportionalString(320, y, va("%s %i", CG_GetStringEdString("MP_INGAME", "TIMELIMIT"), value), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; } - if (cgs.gametype < GT_CTF ) { - value = atoi( Info_ValueForKey( info, "fraglimit" ) ); - if ( value ) { - CG_DrawProportionalString( 320, y, va( "%s %i", CG_GetStringEdString("MP_INGAME", "FRAGLIMIT"), value ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (cgs.gametype < GT_CTF) { + value = atoi(Info_ValueForKey(info, "fraglimit")); + if (value) { + CG_DrawProportionalString(320, y, va("%s %i", CG_GetStringEdString("MP_INGAME", "FRAGLIMIT"), value), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; } - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) - { - value = atoi( Info_ValueForKey( info, "duel_fraglimit" ) ); - if ( value ) { - CG_DrawProportionalString( 320, y, va( "%s %i", CG_GetStringEdString("MP_INGAME", "WINLIMIT"), value ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + value = atoi(Info_ValueForKey(info, "duel_fraglimit")); + if (value) { + CG_DrawProportionalString(320, y, va("%s %i", CG_GetStringEdString("MP_INGAME", "WINLIMIT"), value), + UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } } @@ -252,114 +250,127 @@ void CG_DrawInformation( void ) { } if (cgs.gametype >= GT_CTF) { - value = atoi( Info_ValueForKey( info, "capturelimit" ) ); - if ( value ) { - CG_DrawProportionalString( 320, y, va( "%s %i", CG_GetStringEdString("MP_INGAME", "CAPTURELIMIT"), value ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + value = atoi(Info_ValueForKey(info, "capturelimit")); + if (value) { + CG_DrawProportionalString(320, y, va("%s %i", CG_GetStringEdString("MP_INGAME", "CAPTURELIMIT"), value), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; } } - if (cgs.gametype >= GT_TEAM) - { - value = atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) ); - if ( value ) { - CG_DrawProportionalString( 320, y, CG_GetStringEdString("MP_INGAME", "FORCEBASEDTEAMS"), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (cgs.gametype >= GT_TEAM) { + value = atoi(Info_ValueForKey(info, "g_forceBasedTeams")); + if (value) { + CG_DrawProportionalString(320, y, CG_GetStringEdString("MP_INGAME", "FORCEBASEDTEAMS"), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } } - if (cgs.gametype != GT_SIEGE) - { - valueNOFP = atoi( Info_ValueForKey( info, "g_forcePowerDisable" ) ); + if (cgs.gametype != GT_SIEGE) { + valueNOFP = atoi(Info_ValueForKey(info, "g_forcePowerDisable")); - value = atoi( Info_ValueForKey( info, "g_maxForceRank" ) ); - if ( value && !valueNOFP && (value < NUM_FORCE_MASTERY_LEVELS) ) { + value = atoi(Info_ValueForKey(info, "g_maxForceRank")); + if (value && !valueNOFP && (value < NUM_FORCE_MASTERY_LEVELS)) { char fmStr[1024]; - trap->SE_GetStringTextString("MP_INGAME_MAXFORCERANK",fmStr, sizeof(fmStr)); + trap->SE_GetStringTextString("MP_INGAME_MAXFORCERANK", fmStr, sizeof(fmStr)); - CG_DrawProportionalString( 320, y, va( "%s %s", fmStr, CG_GetStringEdString("MP_INGAME", forceMasteryLevels[value]) ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s %s", fmStr, CG_GetStringEdString("MP_INGAME", forceMasteryLevels[value])), + UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; - } - else if (!valueNOFP) - { + } else if (!valueNOFP) { char fmStr[1024]; - trap->SE_GetStringTextString("MP_INGAME_MAXFORCERANK",fmStr, sizeof(fmStr)); + trap->SE_GetStringTextString("MP_INGAME_MAXFORCERANK", fmStr, sizeof(fmStr)); - CG_DrawProportionalString( 320, y, va( "%s %s", fmStr, (char *)CG_GetStringEdString("MP_INGAME", forceMasteryLevels[7]) ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s %s", fmStr, (char *)CG_GetStringEdString("MP_INGAME", forceMasteryLevels[7])), + UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, colorWhite); y += iPropHeight; } - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) - { - value = atoi( Info_ValueForKey( info, "g_duelWeaponDisable" ) ); - } - else - { - value = atoi( Info_ValueForKey( info, "g_weaponDisable" ) ); + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + value = atoi(Info_ValueForKey(info, "g_duelWeaponDisable")); + } else { + value = atoi(Info_ValueForKey(info, "g_weaponDisable")); } - if ( cgs.gametype != GT_JEDIMASTER && value ) { - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "SABERONLYSET") ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (cgs.gametype != GT_JEDIMASTER && value) { + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "SABERONLYSET")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; } - if ( valueNOFP ) { - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "NOFPSET") ), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + if (valueNOFP) { + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "NOFPSET")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; } } // Display the rules based on type - y += iPropHeight; - switch ( cgs.gametype ) { + y += iPropHeight; + switch (cgs.gametype) { case GT_FFA: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_FFA_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_FFA_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_HOLOCRON: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_HOLO_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_HOLO_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_HOLO_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_HOLO_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_JEDIMASTER: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_JEDI_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_JEDI_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_JEDI_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_JEDI_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_SINGLE_PLAYER: break; case GT_DUEL: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_DUEL_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_DUEL_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_DUEL_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_DUEL_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_POWERDUEL: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_POWERDUEL_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_POWERDUEL_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_POWERDUEL_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_POWERDUEL_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_TEAM: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_TEAM_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_TEAM_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_TEAM_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_TEAM_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_SIEGE: break; case GT_CTF: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTF_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTF_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTF_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTF_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; case GT_CTY: - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTY_1")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTY_1")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; - CG_DrawProportionalString( 320, y, va( "%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTY_2")), UI_CENTER|UI_INFOFONT|UI_DROPSHADOW, colorWhite ); + CG_DrawProportionalString(320, y, va("%s", (char *)CG_GetStringEdString("MP_INGAME", "RULES_CTY_2")), UI_CENTER | UI_INFOFONT | UI_DROPSHADOW, + colorWhite); y += iPropHeight; break; default: @@ -372,16 +383,15 @@ void CG_DrawInformation( void ) { CG_LoadBar =================== */ -void CG_LoadBar(void) -{ +void CG_LoadBar(void) { const int numticks = 9, tickwidth = 40, tickheight = 8; const int tickpadx = 20, tickpady = 12; const int capwidth = 8; - const int barwidth = numticks*tickwidth+tickpadx*2+capwidth*2, barleft = ((640-barwidth)/2); - const int barheight = tickheight + tickpady*2, bartop = 480-barheight; - const int capleft = barleft+tickpadx, tickleft = capleft+capwidth, ticktop = bartop+tickpady; + const int barwidth = numticks * tickwidth + tickpadx * 2 + capwidth * 2, barleft = ((640 - barwidth) / 2); + const int barheight = tickheight + tickpady * 2, bartop = 480 - barheight; + const int capleft = barleft + tickpadx, tickleft = capleft + capwidth, ticktop = bartop + tickpady; - trap->R_SetColor( colorWhite ); + trap->R_SetColor(colorWhite); // Draw background CG_DrawPic(barleft, bartop, barwidth, barheight, cgs.media.loadBarLEDSurround); @@ -389,9 +399,8 @@ void CG_LoadBar(void) CG_DrawPic(tickleft, ticktop, -capwidth, tickheight, cgs.media.loadBarLEDCap); // Draw bar - CG_DrawPic(tickleft, ticktop, tickwidth*cg.loadLCARSStage, tickheight, cgs.media.loadBarLED); + CG_DrawPic(tickleft, ticktop, tickwidth * cg.loadLCARSStage, tickheight, cgs.media.loadBarLED); // Draw right cap - CG_DrawPic(tickleft+tickwidth*cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadBarLEDCap); + CG_DrawPic(tickleft + tickwidth * cg.loadLCARSStage, ticktop, capwidth, tickheight, cgs.media.loadBarLEDCap); } - diff --git a/codemp/cgame/cg_light.c b/codemp/cgame/cg_light.c index 976ae03918..90ac46b273 100644 --- a/codemp/cgame/cg_light.c +++ b/codemp/cgame/cg_light.c @@ -23,28 +23,27 @@ along with this program; if not, see . #include "cg_local.h" typedef struct clightstyle_s { - int length; - color4ub_t value; - color4ub_t map[MAX_QPATH]; + int length; + color4ub_t value; + color4ub_t map[MAX_QPATH]; } clightstyle_t; -static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; -static int lastofs; +static clightstyle_t cl_lightstyle[MAX_LIGHT_STYLES]; +static int lastofs; /* ================ CG_ClearLightStyles ================ */ -void CG_ClearLightStyles (void) -{ - int i; +void CG_ClearLightStyles(void) { + int i; - memset( cl_lightstyle, 0, sizeof( cl_lightstyle ) ); + memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); lastofs = -1; - for ( i=0; ivalue; ls->value[3] = 255; - if ( !ls->length ) { + if (!ls->length) { ls->value[0] = ls->value[1] = ls->value[2] = 255; - } - else if ( ls->length == 1 ) { + } else if (ls->length == 1) { ls->value[0] = ls->map[0][0]; ls->value[1] = ls->map[0][1]; ls->value[2] = ls->map[0][2]; - // ls->value[3] = ls->map[0][3]; - } - else { - ls->value[0] = ls->map[ofs%ls->length][0]; - ls->value[1] = ls->map[ofs%ls->length][1]; - ls->value[2] = ls->map[ofs%ls->length][2]; - // ls->value[3] = ls->map[ofs%ls->length][3]; + // ls->value[3] = ls->map[0][3]; + } else { + ls->value[0] = ls->map[ofs % ls->length][0]; + ls->value[1] = ls->map[ofs % ls->length][1]; + ls->value[2] = ls->map[ofs % ls->length][2]; + // ls->value[3] = ls->map[ofs%ls->length][3]; } - trap->R_SetLightStyle( i, ba->i ); + trap->R_SetLightStyle(i, ba->i); } } -void CG_SetLightstyle (int i) -{ - const char *s; - int j, k; +void CG_SetLightstyle(int i) { + const char *s; + int j, k; - s = CG_ConfigString( i+CS_LIGHT_STYLES ); - j = strlen (s); - if (j >= MAX_QPATH) - { - Com_Error (ERR_DROP, "svc_lightstyle length=%i", j); + s = CG_ConfigString(i + CS_LIGHT_STYLES); + j = strlen(s); + if (j >= MAX_QPATH) { + Com_Error(ERR_DROP, "svc_lightstyle length=%i", j); } - cl_lightstyle[(i/3)].length = j; - for (k=0 ; k. #include "cg_local.h" -#define MAX_LOCAL_ENTITIES 2048 // 512 -localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; -localEntity_t cg_activeLocalEntities; // double linked list -localEntity_t *cg_freeLocalEntities; // single linked list +#define MAX_LOCAL_ENTITIES 2048 // 512 +localEntity_t cg_localEntities[MAX_LOCAL_ENTITIES]; +localEntity_t cg_activeLocalEntities; // double linked list +localEntity_t *cg_freeLocalEntities; // single linked list /* =================== @@ -38,27 +38,26 @@ CG_InitLocalEntities This is called at startup and for tournament restarts =================== */ -void CG_InitLocalEntities( void ) { - int i; +void CG_InitLocalEntities(void) { + int i; - memset( cg_localEntities, 0, sizeof( cg_localEntities ) ); + memset(cg_localEntities, 0, sizeof(cg_localEntities)); cg_activeLocalEntities.next = &cg_activeLocalEntities; cg_activeLocalEntities.prev = &cg_activeLocalEntities; cg_freeLocalEntities = cg_localEntities; - for ( i = 0 ; i < MAX_LOCAL_ENTITIES - 1 ; i++ ) { - cg_localEntities[i].next = &cg_localEntities[i+1]; + for (i = 0; i < MAX_LOCAL_ENTITIES - 1; i++) { + cg_localEntities[i].next = &cg_localEntities[i + 1]; } } - /* ================== CG_FreeLocalEntity ================== */ -void CG_FreeLocalEntity( localEntity_t *le ) { - if ( !le->prev ) { - trap->Error( ERR_DROP, "CG_FreeLocalEntity: not active" ); +void CG_FreeLocalEntity(localEntity_t *le) { + if (!le->prev) { + trap->Error(ERR_DROP, "CG_FreeLocalEntity: not active"); return; } @@ -78,19 +77,19 @@ CG_AllocLocalEntity Will allways succeed, even if it requires freeing an old active entity =================== */ -localEntity_t *CG_AllocLocalEntity( void ) { - localEntity_t *le; +localEntity_t *CG_AllocLocalEntity(void) { + localEntity_t *le; - if ( !cg_freeLocalEntities ) { + if (!cg_freeLocalEntities) { // no free entities, so free the one at the end of the chain // remove the oldest active entity - CG_FreeLocalEntity( cg_activeLocalEntities.prev ); + CG_FreeLocalEntity(cg_activeLocalEntities.prev); } le = cg_freeLocalEntities; cg_freeLocalEntities = cg_freeLocalEntities->next; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->next = cg_activeLocalEntities.next; @@ -100,7 +99,6 @@ localEntity_t *CG_AllocLocalEntity( void ) { return le; } - /* ==================================================================================== @@ -119,28 +117,28 @@ CG_BloodTrail Leave expanding blood puffs behind gibs ================ */ -void CG_BloodTrail( localEntity_t *le ) { - int t; - int t2; - int step; - vec3_t newOrigin; - localEntity_t *blood; +void CG_BloodTrail(localEntity_t *le) { + int t; + int t2; + int step; + vec3_t newOrigin; + localEntity_t *blood; step = 150; - t = step * ( (cg.time - cg.frametime + step ) / step ); - t2 = step * ( cg.time / step ); - - for ( ; t <= t2; t += step ) { - BG_EvaluateTrajectory( &le->pos, t, newOrigin ); - - blood = CG_SmokePuff( newOrigin, vec3_origin, - 20, // radius - 1, 1, 1, 1, // color - 2000, // trailTime - t, // startTime - 0, // fadeInTime - 0, // flags - /*cgs.media.bloodTrailShader*/0 ); + t = step * ((cg.time - cg.frametime + step) / step); + t2 = step * (cg.time / step); + + for (; t <= t2; t += step) { + BG_EvaluateTrajectory(&le->pos, t, newOrigin); + + blood = CG_SmokePuff(newOrigin, vec3_origin, + 20, // radius + 1, 1, 1, 1, // color + 2000, // trailTime + t, // startTime + 0, // fadeInTime + 0, // flags + /*cgs.media.bloodTrailShader*/ 0); // use the optimized version blood->leType = LE_FALL_SCALE_FADE; // drop a total of 40 units over its lifetime @@ -148,21 +146,20 @@ void CG_BloodTrail( localEntity_t *le ) { } } - /* ================ CG_FragmentBounceMark ================ */ -void CG_FragmentBounceMark( localEntity_t *le, trace_t *trace ) { -// int radius; - - if ( le->leMarkType == LEMT_BLOOD ) { - // radius = 16 + (rand()&31); - // CG_ImpactMark( cgs.media.bloodMarkShader, trace->endpos, trace->plane.normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qtrue, radius, qfalse ); - } else if ( le->leMarkType == LEMT_BURN ) { - // radius = 8 + (rand()&15); - // CG_ImpactMark( cgs.media.burnMarkShader, trace->endpos, trace->plane.normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qtrue, radius, qfalse ); +void CG_FragmentBounceMark(localEntity_t *le, trace_t *trace) { + // int radius; + + if (le->leMarkType == LEMT_BLOOD) { + // radius = 16 + (rand()&31); + // CG_ImpactMark( cgs.media.bloodMarkShader, trace->endpos, trace->plane.normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qtrue, radius, qfalse ); + } else if (le->leMarkType == LEMT_BURN) { + // radius = 8 + (rand()&15); + // CG_ImpactMark( cgs.media.burnMarkShader, trace->endpos, trace->plane.normal, Q_flrand(0.0f, 1.0f)*360, 1,1,1,1, qtrue, radius, qfalse ); } // don't allow a fragment to make multiple marks, or they pile up while settling @@ -174,70 +171,61 @@ void CG_FragmentBounceMark( localEntity_t *le, trace_t *trace ) { CG_FragmentBounceSound ================ */ -void CG_FragmentBounceSound( localEntity_t *le, trace_t *trace ) { +void CG_FragmentBounceSound(localEntity_t *le, trace_t *trace) { // half the fragments will make a bounce sounds - if ( rand() & 1 ) - { - sfxHandle_t s = 0; + if (rand() & 1) { + sfxHandle_t s = 0; - switch( le->leBounceSoundType ) - { + switch (le->leBounceSoundType) { case LEBS_ROCK: - s = cgs.media.rockBounceSound[Q_irand(0,1)]; + s = cgs.media.rockBounceSound[Q_irand(0, 1)]; break; case LEBS_METAL: - s = cgs.media.metalBounceSound[Q_irand(0,1)];// FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... + s = cgs.media.metalBounceSound[Q_irand(0, 1)]; // FIXME: make sure that this sound is registered properly...might still be rock bounce sound.... break; default: return; } - if ( s ) - { - trap->S_StartSound( trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s ); + if (s) { + trap->S_StartSound(trace->endpos, ENTITYNUM_WORLD, CHAN_AUTO, s); } // bouncers only make the sound once... // FIXME: arbitrary...change if it bugs you le->leBounceSoundType = LEBS_NONE; - } - else if ( rand() & 1 ) - { + } else if (rand() & 1) { // we may end up bouncing again, but each bounce reduces the chance of playing the sound again or they may make a lot of noise when they settle // FIXME: maybe just always do this?? le->leBounceSoundType = LEBS_NONE; } } - /* ================ CG_ReflectVelocity ================ */ -void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void CG_ReflectVelocity(localEntity_t *le, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane hitTime = cg.time - cg.frametime + cg.frametime * trace->fraction; - BG_EvaluateTrajectoryDelta( &le->pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, le->pos.trDelta ); + BG_EvaluateTrajectoryDelta(&le->pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, le->pos.trDelta); - VectorScale( le->pos.trDelta, le->bounceFactor, le->pos.trDelta ); + VectorScale(le->pos.trDelta, le->bounceFactor, le->pos.trDelta); - VectorCopy( trace->endpos, le->pos.trBase ); + VectorCopy(trace->endpos, le->pos.trBase); le->pos.trTime = cg.time; // check for stop, making sure that even on low FPS systems it doesn't bobble - if ( trace->allsolid || - ( trace->plane.normal[2] > 0 && - ( le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2] ) ) ) { + if (trace->allsolid || (trace->plane.normal[2] > 0 && (le->pos.trDelta[2] < 40 || le->pos.trDelta[2] < -cg.frametime * le->pos.trDelta[2]))) { le->pos.trType = TR_STATIONARY; } else { - } } @@ -246,73 +234,69 @@ void CG_ReflectVelocity( localEntity_t *le, trace_t *trace ) { CG_AddFragment ================ */ -void CG_AddFragment( localEntity_t *le ) { - vec3_t newOrigin; - trace_t trace; +void CG_AddFragment(localEntity_t *le) { + vec3_t newOrigin; + trace_t trace; - if (le->forceAlpha) - { + if (le->forceAlpha) { le->refEntity.renderfx |= RF_FORCE_ENT_ALPHA; le->refEntity.shaderRGBA[3] = le->forceAlpha; } - if ( le->pos.trType == TR_STATIONARY ) { + if (le->pos.trType == TR_STATIONARY) { // sink into the ground if near the removal time - int t; - float t_e; + int t; + float t_e; t = le->endTime - cg.time; - if ( t < (SINK_TIME*2) ) { + if (t < (SINK_TIME * 2)) { le->refEntity.renderfx |= RF_FORCE_ENT_ALPHA; - t_e = (float)((float)(le->endTime - cg.time)/(SINK_TIME*2)); + t_e = (float)((float)(le->endTime - cg.time) / (SINK_TIME * 2)); t_e = (int)((t_e)*255); - if (t_e > 255) - { + if (t_e > 255) { t_e = 255; } - if (t_e < 1) - { + if (t_e < 1) { t_e = 1; } - if (le->refEntity.shaderRGBA[3] && t_e > le->refEntity.shaderRGBA[3]) - { + if (le->refEntity.shaderRGBA[3] && t_e > le->refEntity.shaderRGBA[3]) { t_e = le->refEntity.shaderRGBA[3]; } le->refEntity.shaderRGBA[3] = t_e; - trap->R_AddRefEntityToScene( &le->refEntity ); + trap->R_AddRefEntityToScene(&le->refEntity); } else { - trap->R_AddRefEntityToScene( &le->refEntity ); + trap->R_AddRefEntityToScene(&le->refEntity); } return; } // calculate new position - BG_EvaluateTrajectory( &le->pos, cg.time, newOrigin ); + BG_EvaluateTrajectory(&le->pos, cg.time, newOrigin); // trace a line from previous position to new position - CG_Trace( &trace, le->refEntity.origin, NULL, NULL, newOrigin, -1, CONTENTS_SOLID ); - if ( trace.fraction == 1.0 ) { + CG_Trace(&trace, le->refEntity.origin, NULL, NULL, newOrigin, -1, CONTENTS_SOLID); + if (trace.fraction == 1.0) { // still in free fall - VectorCopy( newOrigin, le->refEntity.origin ); + VectorCopy(newOrigin, le->refEntity.origin); - if ( le->leFlags & LEF_TUMBLE ) { + if (le->leFlags & LEF_TUMBLE) { vec3_t angles; - BG_EvaluateTrajectory( &le->angles, cg.time, angles ); - AnglesToAxis( angles, le->refEntity.axis ); + BG_EvaluateTrajectory(&le->angles, cg.time, angles); + AnglesToAxis(angles, le->refEntity.axis); ScaleModelAxis(&le->refEntity); } - trap->R_AddRefEntityToScene( &le->refEntity ); + trap->R_AddRefEntityToScene(&le->refEntity); // add a blood trail - if ( le->leBounceSoundType == LEBS_BLOOD ) { - CG_BloodTrail( le ); + if (le->leBounceSoundType == LEBS_BLOOD) { + CG_BloodTrail(le); } return; @@ -321,28 +305,26 @@ void CG_AddFragment( localEntity_t *le ) { // if it is in a nodrop zone, remove it // this keeps gibs from waiting at the bottom of pits of death // and floating levels - if ( CG_PointContents( trace.endpos, 0 ) & CONTENTS_NODROP ) { - CG_FreeLocalEntity( le ); + if (CG_PointContents(trace.endpos, 0) & CONTENTS_NODROP) { + CG_FreeLocalEntity(le); return; } - if (!trace.startsolid) - { + if (!trace.startsolid) { // leave a mark - CG_FragmentBounceMark( le, &trace ); + CG_FragmentBounceMark(le, &trace); // do a bouncy sound - CG_FragmentBounceSound( le, &trace ); + CG_FragmentBounceSound(le, &trace); - if (le->bounceSound) - { //specified bounce sound (debris) + if (le->bounceSound) { // specified bounce sound (debris) trap->S_StartSound(le->pos.trBase, ENTITYNUM_WORLD, CHAN_AUTO, le->bounceSound); } // reflect the velocity on the trace plane - CG_ReflectVelocity( le, &trace ); + CG_ReflectVelocity(le, &trace); - trap->R_AddRefEntityToScene( &le->refEntity ); + trap->R_AddRefEntityToScene(&le->refEntity); } } @@ -360,13 +342,13 @@ These only do simple scaling or modulation before passing to the renderer CG_AddFadeRGB ==================== */ -void CG_AddFadeRGB( localEntity_t *le ) { +void CG_AddFadeRGB(localEntity_t *le) { refEntity_t *re; float c; re = &le->refEntity; - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; c *= 0xff; re->shaderRGBA[0] = le->color[0] * c; @@ -374,24 +356,23 @@ void CG_AddFadeRGB( localEntity_t *le ) { re->shaderRGBA[2] = le->color[2] * c; re->shaderRGBA[3] = le->color[3] * c; - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } -static void CG_AddFadeScaleModel( localEntity_t *le ) -{ - refEntity_t *ent = &le->refEntity; +static void CG_AddFadeScaleModel(localEntity_t *le) { + refEntity_t *ent = &le->refEntity; - float frac = ( cg.time - le->startTime )/((float)( le->endTime - le->startTime )); + float frac = (cg.time - le->startTime) / ((float)(le->endTime - le->startTime)); frac *= frac * frac; // yes, this is completely ridiculous...but it causes the shell to grow slowly then "explode" at the end ent->nonNormalizedAxes = qtrue; - AxisCopy( axisDefault, ent->axis ); + AxisCopy(axisDefault, ent->axis); - VectorScale( ent->axis[0], le->radius * frac, ent->axis[0] ); - VectorScale( ent->axis[1], le->radius * frac, ent->axis[1] ); - VectorScale( ent->axis[2], le->radius * 0.5f * frac, ent->axis[2] ); + VectorScale(ent->axis[0], le->radius * frac, ent->axis[0]); + VectorScale(ent->axis[1], le->radius * frac, ent->axis[1]); + VectorScale(ent->axis[2], le->radius * 0.5f * frac, ent->axis[2]); frac = 1.0f - frac; @@ -401,7 +382,7 @@ static void CG_AddFadeScaleModel( localEntity_t *le ) ent->shaderRGBA[3] = le->color[3] * frac; // add the entity - trap->R_AddRefEntityToScene( ent ); + trap->R_AddRefEntityToScene(ent); } /* @@ -409,41 +390,40 @@ static void CG_AddFadeScaleModel( localEntity_t *le ) CG_AddMoveScaleFade ================== */ -static void CG_AddMoveScaleFade( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddMoveScaleFade(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; - if ( le->fadeInTime > le->startTime && cg.time < le->fadeInTime ) { + if (le->fadeInTime > le->startTime && cg.time < le->fadeInTime) { // fade / grow time - c = 1.0 - (float) ( le->fadeInTime - cg.time ) / ( le->fadeInTime - le->startTime ); - } - else { + c = 1.0 - (float)(le->fadeInTime - cg.time) / (le->fadeInTime - le->startTime); + } else { // fade / grow time - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; } re->shaderRGBA[3] = 0xff * c * le->color[3]; - if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) { - re->radius = le->radius * ( 1.0 - c ) + 8; + if (!(le->leFlags & LEF_PUFF_DONT_SCALE)) { + re->radius = le->radius * (1.0 - c) + 8; } - BG_EvaluateTrajectory( &le->pos, cg.time, re->origin ); + BG_EvaluateTrajectory(&le->pos, cg.time, re->origin); // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } /* @@ -451,37 +431,37 @@ static void CG_AddMoveScaleFade( localEntity_t *le ) { CG_AddPuff ================== */ -static void CG_AddPuff( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddPuff(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; // fade / grow time - c = ( le->endTime - cg.time ) / (float)( le->endTime - le->startTime ); + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); re->shaderRGBA[0] = le->color[0] * c; re->shaderRGBA[1] = le->color[1] * c; re->shaderRGBA[2] = le->color[2] * c; - if ( !( le->leFlags & LEF_PUFF_DONT_SCALE ) ) { - re->radius = le->radius * ( 1.0 - c ) + 8; + if (!(le->leFlags & LEF_PUFF_DONT_SCALE)) { + re->radius = le->radius * (1.0 - c) + 8; } - BG_EvaluateTrajectory( &le->pos, cg.time, re->origin ); + BG_EvaluateTrajectory(&le->pos, cg.time, re->origin); // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } /* @@ -493,33 +473,32 @@ removed if the view passes through them. There are often many of these, so it needs to be simple. =================== */ -static void CG_AddScaleFade( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddScaleFade(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; // fade / grow time - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; re->shaderRGBA[3] = 0xff * c * le->color[3]; - re->radius = le->radius * ( 1.0 - c ) + 8; + re->radius = le->radius * (1.0 - c) + 8; // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } - /* ================= CG_AddFallScaleFade @@ -530,44 +509,42 @@ removed if the view passes through them. There are often 100+ of these, so it needs to be simple. ================= */ -static void CG_AddFallScaleFade( localEntity_t *le ) { - refEntity_t *re; - float c; - vec3_t delta; - float len; +static void CG_AddFallScaleFade(localEntity_t *le) { + refEntity_t *re; + float c; + vec3_t delta; + float len; re = &le->refEntity; // fade time - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; re->shaderRGBA[3] = 0xff * c * le->color[3]; - re->origin[2] = le->pos.trBase[2] - ( 1.0 - c ) * le->pos.trDelta[2]; + re->origin[2] = le->pos.trBase[2] - (1.0 - c) * le->pos.trDelta[2]; - re->radius = le->radius * ( 1.0 - c ) + 16; + re->radius = le->radius * (1.0 - c) + 16; // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( re->origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < le->radius ) { - CG_FreeLocalEntity( le ); + VectorSubtract(re->origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < le->radius) { + CG_FreeLocalEntity(le); return; } - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } - - /* ================ CG_AddExplosion ================ */ -static void CG_AddExplosion( localEntity_t *ex ) { - refEntity_t *ent; +static void CG_AddExplosion(localEntity_t *ex) { + refEntity_t *ent; ent = &ex->refEntity; @@ -575,17 +552,17 @@ static void CG_AddExplosion( localEntity_t *ex ) { trap->R_AddRefEntityToScene(ent); // add the dlight - if ( ex->light ) { - float light; + if (ex->light) { + float light; - light = (float)( cg.time - ex->startTime ) / ( ex->endTime - ex->startTime ); - if ( light < 0.5 ) { + light = (float)(cg.time - ex->startTime) / (ex->endTime - ex->startTime); + if (light < 0.5) { light = 1.0; } else { - light = 1.0 - ( light - 0.5 ) * 2; + light = 1.0 - (light - 0.5) * 2; } light = ex->light * light; - trap->R_AddLightToScene(ent->origin, light, ex->lightColor[0], ex->lightColor[1], ex->lightColor[2] ); + trap->R_AddLightToScene(ent->origin, light, ex->lightColor[0], ex->lightColor[1], ex->lightColor[2]); } } @@ -594,15 +571,15 @@ static void CG_AddExplosion( localEntity_t *ex ) { CG_AddSpriteExplosion ================ */ -static void CG_AddSpriteExplosion( localEntity_t *le ) { - refEntity_t re; +static void CG_AddSpriteExplosion(localEntity_t *le) { + refEntity_t re; float c; re = le->refEntity; - c = ( le->endTime - cg.time ) / ( float ) ( le->endTime - le->startTime ); - if ( c > 1 ) { - c = 1.0; // can happen during connection problems + c = (le->endTime - cg.time) / (float)(le->endTime - le->startTime); + if (c > 1) { + c = 1.0; // can happen during connection problems } re.shaderRGBA[0] = 0xff; @@ -611,37 +588,36 @@ static void CG_AddSpriteExplosion( localEntity_t *le ) { re.shaderRGBA[3] = 0xff * c * 0.33; re.reType = RT_SPRITE; - re.radius = 42 * ( 1.0 - c ) + 30; + re.radius = 42 * (1.0 - c) + 30; - trap->R_AddRefEntityToScene( &re ); + trap->R_AddRefEntityToScene(&re); // add the dlight - if ( le->light ) { - float light; + if (le->light) { + float light; - light = (float)( cg.time - le->startTime ) / ( le->endTime - le->startTime ); - if ( light < 0.5 ) { + light = (float)(cg.time - le->startTime) / (le->endTime - le->startTime); + if (light < 0.5) { light = 1.0; } else { - light = 1.0 - ( light - 0.5 ) * 2; + light = 1.0 - (light - 0.5) * 2; } light = le->light * light; - trap->R_AddLightToScene(re.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2] ); + trap->R_AddLightToScene(re.origin, light, le->lightColor[0], le->lightColor[1], le->lightColor[2]); } } - /* =================== CG_AddRefEntity =================== */ -void CG_AddRefEntity( localEntity_t *le ) { +void CG_AddRefEntity(localEntity_t *le) { if (le->endTime < cg.time) { - CG_FreeLocalEntity( le ); + CG_FreeLocalEntity(le); return; } - trap->R_AddRefEntityToScene( &le->refEntity ); + trap->R_AddRefEntityToScene(&le->refEntity); } /* @@ -649,25 +625,24 @@ void CG_AddRefEntity( localEntity_t *le ) { CG_AddScorePlum =================== */ -#define NUMBER_SIZE 8 +#define NUMBER_SIZE 8 -void CG_AddScorePlum( localEntity_t *le ) { - refEntity_t *re; - vec3_t origin, delta, dir, vec, up = {0, 0, 1}; - float c, len; - int i, score, digits[10], numdigits, negative; +void CG_AddScorePlum(localEntity_t *le) { + refEntity_t *re; + vec3_t origin, delta, dir, vec, up = {0, 0, 1}; + float c, len; + int i, score, digits[10], numdigits, negative; re = &le->refEntity; - c = ( le->endTime - cg.time ) * le->lifeRate; + c = (le->endTime - cg.time) * le->lifeRate; score = le->radius; if (score < 0) { re->shaderRGBA[0] = 0xff; re->shaderRGBA[1] = 0x11; re->shaderRGBA[2] = 0x11; - } - else { + } else { re->shaderRGBA[0] = 0xff; re->shaderRGBA[1] = 0xff; re->shaderRGBA[2] = 0xff; @@ -680,7 +655,6 @@ void CG_AddScorePlum( localEntity_t *le ) { } else if (score >= 2) { re->shaderRGBA[0] = re->shaderRGBA[2] = 0; } - } if (c < 0.25) re->shaderRGBA[3] = 0xff * 4 * c; @@ -700,10 +674,10 @@ void CG_AddScorePlum( localEntity_t *le ) { // if the view would be "inside" the sprite, kill the sprite // so it doesn't add too much overdraw - VectorSubtract( origin, cg.refdef.vieworg, delta ); - len = VectorLength( delta ); - if ( len < 20 ) { - CG_FreeLocalEntity( le ); + VectorSubtract(origin, cg.refdef.vieworg, delta); + len = VectorLength(delta); + if (len < 20) { + CG_FreeLocalEntity(le); return; } @@ -724,9 +698,9 @@ void CG_AddScorePlum( localEntity_t *le ) { } for (i = 0; i < numdigits; i++) { - VectorMA(origin, (float) (((float) numdigits / 2) - i) * NUMBER_SIZE, vec, re->origin); - re->customShader = cgs.media.numberShaders[digits[numdigits-1-i]]; - trap->R_AddRefEntityToScene( re ); + VectorMA(origin, (float)(((float)numdigits / 2) - i) * NUMBER_SIZE, vec, re->origin); + re->customShader = cgs.media.numberShaders[digits[numdigits - 1 - i]]; + trap->R_AddRefEntityToScene(re); } } @@ -737,24 +711,22 @@ CG_AddOLine For forcefields/other rectangular things =================== */ -void CG_AddOLine( localEntity_t *le ) -{ - refEntity_t *re; - float frac, alpha; +void CG_AddOLine(localEntity_t *le) { + refEntity_t *re; + float frac, alpha; re = &le->refEntity; - frac = (cg.time - le->startTime) / ( float ) ( le->endTime - le->startTime ); - if ( frac > 1 ) - frac = 1.0; // can happen during connection problems + frac = (cg.time - le->startTime) / (float)(le->endTime - le->startTime); + if (frac > 1) + frac = 1.0; // can happen during connection problems else if (frac < 0) frac = 0.0; // Use the liferate to set the scale over time. re->data.line.width = le->data.line.width + (le->data.line.dwidth * frac); - if (re->data.line.width <= 0) - { - CG_FreeLocalEntity( le ); + if (re->data.line.width <= 0) { + CG_FreeLocalEntity(le); return; } @@ -763,7 +735,7 @@ void CG_AddOLine( localEntity_t *le ) re->shaderRGBA[0] = 0xff * alpha; re->shaderRGBA[1] = 0xff * alpha; re->shaderRGBA[2] = 0xff * alpha; - re->shaderRGBA[3] = 0xff * alpha; // Yes, we could apply c to this too, but fading the color is better for lines. + re->shaderRGBA[3] = 0xff * alpha; // Yes, we could apply c to this too, but fading the color is better for lines. re->shaderTexCoord[0] = 1; re->shaderTexCoord[1] = 1; @@ -772,7 +744,7 @@ void CG_AddOLine( localEntity_t *le ) re->reType = RT_ORIENTEDLINE; - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } /* @@ -782,15 +754,14 @@ CG_AddLine for beams and the like. =================== */ -void CG_AddLine( localEntity_t *le ) -{ - refEntity_t *re; +void CG_AddLine(localEntity_t *le) { + refEntity_t *re; re = &le->refEntity; re->reType = RT_LINE; - trap->R_AddRefEntityToScene( re ); + trap->R_AddRefEntityToScene(re); } //============================================================================== @@ -801,84 +772,80 @@ CG_AddLocalEntities =================== */ -void CG_AddLocalEntities( void ) { - localEntity_t *le, *next; +void CG_AddLocalEntities(void) { + localEntity_t *le, *next; // walk the list backwards, so any new local entities generated // (trails, marks, etc) will be present this frame le = cg_activeLocalEntities.prev; - for ( ; le != &cg_activeLocalEntities ; le = next ) { + for (; le != &cg_activeLocalEntities; le = next) { // grab next now, so if the local entity is freed we // still have it next = le->prev; - if ( cg.time >= le->endTime ) { - CG_FreeLocalEntity( le ); + if (cg.time >= le->endTime) { + CG_FreeLocalEntity(le); continue; } - switch ( le->leType ) { + switch (le->leType) { default: - trap->Error( ERR_DROP, "Bad leType: %i", le->leType ); + trap->Error(ERR_DROP, "Bad leType: %i", le->leType); break; case LE_MARK: break; case LE_SPRITE_EXPLOSION: - CG_AddSpriteExplosion( le ); + CG_AddSpriteExplosion(le); break; case LE_EXPLOSION: - CG_AddExplosion( le ); + CG_AddExplosion(le); break; case LE_FADE_SCALE_MODEL: - CG_AddFadeScaleModel( le ); + CG_AddFadeScaleModel(le); break; - case LE_FRAGMENT: // gibs and brass - CG_AddFragment( le ); + case LE_FRAGMENT: // gibs and brass + CG_AddFragment(le); break; case LE_PUFF: - CG_AddPuff( le ); + CG_AddPuff(le); break; - case LE_MOVE_SCALE_FADE: // water bubbles - CG_AddMoveScaleFade( le ); + case LE_MOVE_SCALE_FADE: // water bubbles + CG_AddMoveScaleFade(le); break; - case LE_FADE_RGB: // teleporters, railtrails - CG_AddFadeRGB( le ); + case LE_FADE_RGB: // teleporters, railtrails + CG_AddFadeRGB(le); break; case LE_FALL_SCALE_FADE: // gib blood trails - CG_AddFallScaleFade( le ); + CG_AddFallScaleFade(le); break; - case LE_SCALE_FADE: // rocket trails - CG_AddScaleFade( le ); + case LE_SCALE_FADE: // rocket trails + CG_AddScaleFade(le); break; case LE_SCOREPLUM: - CG_AddScorePlum( le ); + CG_AddScorePlum(le); break; case LE_OLINE: - CG_AddOLine( le ); + CG_AddOLine(le); break; case LE_SHOWREFENTITY: - CG_AddRefEntity( le ); + CG_AddRefEntity(le); break; - case LE_LINE: // oriented lines for FX - CG_AddLine( le ); + case LE_LINE: // oriented lines for FX + CG_AddLine(le); break; } } } - - - - diff --git a/codemp/cgame/cg_main.c b/codemp/cgame/cg_main.c index b9c926d787..6312e9b777 100644 --- a/codemp/cgame/cg_main.c +++ b/codemp/cgame/cg_main.c @@ -27,8 +27,8 @@ along with this program; if not, see . #include "ui/ui_shared.h" -NORETURN_PTR void (*Com_Error)( int level, const char *error, ... ); -void (*Com_Printf)( const char *msg, ... ); +NORETURN_PTR void (*Com_Error)(int level, const char *error, ...); +void (*Com_Printf)(const char *msg, ...); // display context for new ui stuff displayContextDef_t cgDC; @@ -46,88 +46,78 @@ Ghoul2 Insert End void CG_InitJetpackGhoul2(void); void CG_CleanJetpackGhoul2(void); -void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum ); -void CG_Shutdown( void ); +void CG_Init(int serverMessageNum, int serverCommandSequence, int clientNum); +void CG_Shutdown(void); -void CG_CalcEntityLerpPositions( centity_t *cent ); -void CG_ROFF_NotetrackCallback( centity_t *cent, const char *notetrack); +void CG_CalcEntityLerpPositions(centity_t *cent); +void CG_ROFF_NotetrackCallback(centity_t *cent, const char *notetrack); void UI_CleanupGhoul2(void); -static int C_PointContents(void); +static int C_PointContents(void); static void C_GetLerpOrigin(void); static void C_GetLerpData(void); static void C_Trace(void); static void C_G2Trace(void); static void C_G2Mark(void); -static int CG_RagCallback(int callType); +static int CG_RagCallback(int callType); static void C_ImpactMark(void); -extern autoMapInput_t cg_autoMapInput; //cg_view.c +extern autoMapInput_t cg_autoMapInput; // cg_view.c extern int cg_autoMapInputTime; extern vec3_t cg_autoMapAngle; void CG_MiscEnt(void); -void CG_DoCameraShake( vec3_t origin, float intensity, int radius, int time ); +void CG_DoCameraShake(vec3_t origin, float intensity, int radius, int time); -//do we have any force powers that we would normally need to cycle to? -qboolean CG_NoUseableForce(void) -{ +// do we have any force powers that we would normally need to cycle to? +qboolean CG_NoUseableForce(void) { int i = FP_HEAL; - while (i < NUM_FORCE_POWERS) - { - if (i != FP_SABERTHROW && - i != FP_SABER_OFFENSE && - i != FP_SABER_DEFENSE && - i != FP_LEVITATION) - { //valid selectable power - if (cg.predictedPlayerState.fd.forcePowersKnown & (1 << i)) - { //we have it + while (i < NUM_FORCE_POWERS) { + if (i != FP_SABERTHROW && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE && i != FP_LEVITATION) { // valid selectable power + if (cg.predictedPlayerState.fd.forcePowersKnown & (1 << i)) { // we have it return qfalse; } } i++; } - //no useable force powers, I guess. + // no useable force powers, I guess. return qtrue; } -static int C_PointContents( void ) { +static int C_PointContents(void) { TCGPointContents *data = &cg.sharedBuffer.pointContents; - return CG_PointContents( data->mPoint, data->mPassEntityNum ); + return CG_PointContents(data->mPoint, data->mPassEntityNum); } -static void C_GetLerpOrigin( void ) { +static void C_GetLerpOrigin(void) { TCGVectorData *data = &cg.sharedBuffer.vectorData; - VectorCopy( cg_entities[data->mEntityNum].lerpOrigin, data->mPoint ); + VectorCopy(cg_entities[data->mEntityNum].lerpOrigin, data->mPoint); } // only used by FX system to pass to getboltmat -static void C_GetLerpData( void ) { +static void C_GetLerpData(void) { TCGGetBoltData *data = &cg.sharedBuffer.getBoltData; - VectorCopy( cg_entities[data->mEntityNum].lerpOrigin, data->mOrigin ); - VectorCopy( cg_entities[data->mEntityNum].modelScale, data->mScale ); - VectorCopy( cg_entities[data->mEntityNum].lerpAngles, data->mAngles ); - if ( cg_entities[data->mEntityNum].currentState.eType == ET_PLAYER ) { + VectorCopy(cg_entities[data->mEntityNum].lerpOrigin, data->mOrigin); + VectorCopy(cg_entities[data->mEntityNum].modelScale, data->mScale); + VectorCopy(cg_entities[data->mEntityNum].lerpAngles, data->mAngles); + if (cg_entities[data->mEntityNum].currentState.eType == ET_PLAYER) { // normal player data->mAngles[PITCH] = 0.0f; data->mAngles[ROLL] = 0.0f; - } - else if ( cg_entities[data->mEntityNum].currentState.eType == ET_NPC ) { + } else if (cg_entities[data->mEntityNum].currentState.eType == ET_NPC) { // an NPC Vehicle_t *pVeh = cg_entities[data->mEntityNum].m_pVehicle; - if ( !pVeh ) { + if (!pVeh) { // for vehicles, we may or may not want to 0 out pitch and roll data->mAngles[PITCH] = 0.0f; data->mAngles[ROLL] = 0.0f; - } - else if ( pVeh->m_pVehicleInfo->type == VH_SPEEDER ) { + } else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // speeder wants no pitch but a roll data->mAngles[PITCH] = 0.0f; - } - else if ( pVeh->m_pVehicleInfo->type != VH_FIGHTER ) { + } else if (pVeh->m_pVehicleInfo->type != VH_FIGHTER) { // fighters want all angles data->mAngles[PITCH] = 0.0f; data->mAngles[ROLL] = 0.0f; @@ -135,37 +125,37 @@ static void C_GetLerpData( void ) { } } -static void C_Trace( void ) { +static void C_Trace(void) { TCGTrace *td = &cg.sharedBuffer.trace; - CG_Trace( &td->mResult, td->mStart, td->mMins, td->mMaxs, td->mEnd, td->mSkipNumber, td->mMask ); + CG_Trace(&td->mResult, td->mStart, td->mMins, td->mMaxs, td->mEnd, td->mSkipNumber, td->mMask); } -static void C_G2Trace( void ) { +static void C_G2Trace(void) { TCGTrace *td = &cg.sharedBuffer.trace; - CG_G2Trace( &td->mResult, td->mStart, td->mMins, td->mMaxs, td->mEnd, td->mSkipNumber, td->mMask ); + CG_G2Trace(&td->mResult, td->mStart, td->mMins, td->mMaxs, td->mEnd, td->mSkipNumber, td->mMask); } -static void C_G2Mark( void ) { +static void C_G2Mark(void) { TCGG2Mark *td = &cg.sharedBuffer.g2Mark; trace_t tr; vec3_t end; - VectorMA( td->start, 64.0f, td->dir, end ); - CG_G2Trace( &tr, td->start, NULL, NULL, end, ENTITYNUM_NONE, MASK_PLAYERSOLID ); + VectorMA(td->start, 64.0f, td->dir, end); + CG_G2Trace(&tr, td->start, NULL, NULL, end, ENTITYNUM_NONE, MASK_PLAYERSOLID); - if ( tr.entityNum < ENTITYNUM_WORLD && cg_entities[tr.entityNum].ghoul2 ) { + if (tr.entityNum < ENTITYNUM_WORLD && cg_entities[tr.entityNum].ghoul2) { // hit someone with a ghoul2 instance, let's project the decal on them then. centity_t *cent = &cg_entities[tr.entityNum]; - // CG_TestLine( tr.endpos, end, 2000, 0x0000ff, 1 ); + // CG_TestLine( tr.endpos, end, 2000, 0x0000ff, 1 ); - CG_AddGhoul2Mark( td->shader, td->size, tr.endpos, end, tr.entityNum, cent->lerpOrigin, cent->lerpAngles[YAW], - cent->ghoul2, cent->modelScale, Q_irand( 2000, 4000 ) ); + CG_AddGhoul2Mark(td->shader, td->size, tr.endpos, end, tr.entityNum, cent->lerpOrigin, cent->lerpAngles[YAW], cent->ghoul2, cent->modelScale, + Q_irand(2000, 4000)); // I'm making fx system decals have a very short lifetime. } } -static void CG_DebugBoxLines( vec3_t mins, vec3_t maxs, int duration ) { +static void CG_DebugBoxLines(vec3_t mins, vec3_t maxs, int duration) { vec3_t start, end, vert; float x = maxs[0] - mins[0]; float y = maxs[1] - mins[1]; @@ -223,33 +213,26 @@ static void CG_DebugBoxLines( vec3_t mins, vec3_t maxs, int duration ) { CG_TestLine(start, mins, duration, 0x00000ff, 1); } -//handle ragdoll callbacks, for events and debugging -rww -static int CG_RagCallback(int callType) -{ - switch(callType) - { - case RAG_CALLBACK_DEBUGBOX: - { - ragCallbackDebugBox_t *callData = &cg.sharedBuffer.rcbDebugBox; +// handle ragdoll callbacks, for events and debugging -rww +static int CG_RagCallback(int callType) { + switch (callType) { + case RAG_CALLBACK_DEBUGBOX: { + ragCallbackDebugBox_t *callData = &cg.sharedBuffer.rcbDebugBox; - CG_DebugBoxLines(callData->mins, callData->maxs, callData->duration); - } - break; - case RAG_CALLBACK_DEBUGLINE: - { - ragCallbackDebugLine_t *callData = &cg.sharedBuffer.rcbDebugLine; + CG_DebugBoxLines(callData->mins, callData->maxs, callData->duration); + } break; + case RAG_CALLBACK_DEBUGLINE: { + ragCallbackDebugLine_t *callData = &cg.sharedBuffer.rcbDebugLine; - CG_TestLine(callData->start, callData->end, callData->time, callData->color, callData->radius); - } - break; - case RAG_CALLBACK_BONESNAP: - { - ragCallbackBoneSnap_t *callData = &cg.sharedBuffer.rcbBoneSnap; - centity_t *cent = &cg_entities[callData->entNum]; - int snapSound = trap->S_RegisterSound(va("sound/player/bodyfall_human%i.wav", Q_irand(1, 3))); + CG_TestLine(callData->start, callData->end, callData->time, callData->color, callData->radius); + } break; + case RAG_CALLBACK_BONESNAP: { + ragCallbackBoneSnap_t *callData = &cg.sharedBuffer.rcbBoneSnap; + centity_t *cent = &cg_entities[callData->entNum]; + int snapSound = trap->S_RegisterSound(va("sound/player/bodyfall_human%i.wav", Q_irand(1, 3))); - trap->S_StartSound(cent->lerpOrigin, callData->entNum, CHAN_AUTO, snapSound); - } + trap->S_StartSound(cent->lerpOrigin, callData->entNum, CHAN_AUTO, snapSound); + } case RAG_CALLBACK_BONEIMPACT: break; case RAG_CALLBACK_BONEINSOLID: @@ -270,14 +253,11 @@ static int CG_RagCallback(int callType) } #endif break; - case RAG_CALLBACK_TRACELINE: - { - ragCallbackTraceLine_t *callData = &cg.sharedBuffer.rcbTraceLine; + case RAG_CALLBACK_TRACELINE: { + ragCallbackTraceLine_t *callData = &cg.sharedBuffer.rcbTraceLine; - CG_Trace(&callData->tr, callData->start, callData->mins, callData->maxs, - callData->end, callData->ignore, callData->mask); - } - break; + CG_Trace(&callData->tr, callData->start, callData->mins, callData->maxs, callData->end, callData->ignore, callData->mask); + } break; default: Com_Error(ERR_DROP, "Invalid callType in CG_RagCallback"); break; @@ -286,50 +266,50 @@ static int CG_RagCallback(int callType) return 0; } -static void C_ImpactMark( void ) { +static void C_ImpactMark(void) { TCGImpactMark *data = &cg.sharedBuffer.impactMark; -// CG_ImpactMark( (int)arg0, (const float *)arg1, (const float *)arg2, (float)arg3, (float)arg4, (float)arg5, (float)arg6, -// (float)arg7, qtrue, (float)arg8, qfalse ); + // CG_ImpactMark( (int)arg0, (const float *)arg1, (const float *)arg2, (float)arg3, (float)arg4, (float)arg5, (float)arg6, + // (float)arg7, qtrue, (float)arg8, qfalse ); - CG_ImpactMark( data->mHandle, data->mPoint, data->mAngle, data->mRotation, data->mRed, data->mGreen, data->mBlue, - data->mAlphaStart, qtrue, data->mSizeStart, qfalse ); + CG_ImpactMark(data->mHandle, data->mPoint, data->mAngle, data->mRotation, data->mRed, data->mGreen, data->mBlue, data->mAlphaStart, qtrue, data->mSizeStart, + qfalse); } -void CG_MiscEnt( void ) { +void CG_MiscEnt(void) { int i, modelIndex; TCGMiscEnt *data = &cg.sharedBuffer.miscEnt; cg_staticmodel_t *staticmodel; - if( cgs.numMiscStaticModels >= MAX_STATIC_MODELS ) { - trap->Error( ERR_DROP, "^1MAX_STATIC_MODELS(%i) hit", MAX_STATIC_MODELS ); + if (cgs.numMiscStaticModels >= MAX_STATIC_MODELS) { + trap->Error(ERR_DROP, "^1MAX_STATIC_MODELS(%i) hit", MAX_STATIC_MODELS); } modelIndex = trap->R_RegisterModel(data->mModel); if (modelIndex == 0) { - trap->Error( ERR_DROP, "client_model failed to load model '%s'", data->mModel ); + trap->Error(ERR_DROP, "client_model failed to load model '%s'", data->mModel); return; } staticmodel = &cgs.miscStaticModels[cgs.numMiscStaticModels++]; staticmodel->model = modelIndex; - AnglesToAxis( data->mAngles, staticmodel->axes ); - for ( i = 0; i < 3; i++ ) { - VectorScale( staticmodel->axes[i], data->mScale[i], staticmodel->axes[i] ); + AnglesToAxis(data->mAngles, staticmodel->axes); + for (i = 0; i < 3; i++) { + VectorScale(staticmodel->axes[i], data->mScale[i], staticmodel->axes[i]); } - VectorCopy( data->mOrigin, staticmodel->org ); + VectorCopy(data->mOrigin, staticmodel->org); staticmodel->zoffset = 0.f; - if( staticmodel->model ) { + if (staticmodel->model) { vec3_t mins, maxs; - trap->R_ModelBounds( staticmodel->model, mins, maxs ); + trap->R_ModelBounds(staticmodel->model, mins, maxs); VectorScaleVector(mins, data->mScale, mins); VectorScaleVector(maxs, data->mScale, maxs); - staticmodel->radius = RadiusFromBounds( mins, maxs ); + staticmodel->radius = RadiusFromBounds(mins, maxs); } else { staticmodel->radius = 0; } @@ -367,28 +347,28 @@ void CG_ResizeG2TempBone(mdxaBone_v *tempBone, int newCount) /* Ghoul2 Insert End */ -cg_t cg; -cgs_t cgs; -centity_t cg_entities[MAX_GENTITIES]; +cg_t cg; +cgs_t cgs; +centity_t cg_entities[MAX_GENTITIES]; -centity_t *cg_permanents[MAX_GENTITIES]; //rwwRMG - added -int cg_numpermanents = 0; +centity_t *cg_permanents[MAX_GENTITIES]; // rwwRMG - added +int cg_numpermanents = 0; -weaponInfo_t cg_weapons[MAX_WEAPONS]; -itemInfo_t cg_items[MAX_ITEMS]; +weaponInfo_t cg_weapons[MAX_WEAPONS]; +itemInfo_t cg_items[MAX_ITEMS]; -int CG_CrosshairPlayer( void ) { - if ( cg.time > (cg.crosshairClientTime + 1000) ) +int CG_CrosshairPlayer(void) { + if (cg.time > (cg.crosshairClientTime + 1000)) return -1; - if ( cg.crosshairClientNum >= MAX_CLIENTS ) + if (cg.crosshairClientNum >= MAX_CLIENTS) return -1; return cg.crosshairClientNum; } -int CG_LastAttacker( void ) { - if ( !cg.attackerTime ) +int CG_LastAttacker(void) { + if (!cg.attackerTime) return -1; return cg.snap->ps.persistant[PERS_ATTACKER]; @@ -399,22 +379,18 @@ int CG_LastAttacker( void ) { CG_Argv ================ */ -const char *CG_Argv( int arg ) { - static char buffer[MAX_STRING_CHARS] = {0}; +const char *CG_Argv(int arg) { + static char buffer[MAX_STRING_CHARS] = {0}; - trap->Cmd_Argv( arg, buffer, sizeof( buffer ) ); + trap->Cmd_Argv(arg, buffer, sizeof(buffer)); return buffer; } - //======================================================================== -//so shared code can get the local time depending on the side it's executed on -int BG_GetTime(void) -{ - return cg.time; -} +// so shared code can get the local time depending on the side it's executed on +int BG_GetTime(void) { return cg.time; } /* ================= @@ -423,16 +399,16 @@ CG_RegisterItemSounds The server says this item is used on this level ================= */ -static void CG_RegisterItemSounds( int itemNum ) { - gitem_t *item; - char data[MAX_QPATH]; - char *s, *start; - int len; +static void CG_RegisterItemSounds(int itemNum) { + gitem_t *item; + char data[MAX_QPATH]; + char *s, *start; + int len; - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - if( item->pickup_sound ) { - trap->S_RegisterSound( item->pickup_sound ); + if (item->pickup_sound) { + trap->S_RegisterSound(item->pickup_sound); } // parse the space seperated precache string for other media @@ -446,19 +422,18 @@ static void CG_RegisterItemSounds( int itemNum ) { s++; } - len = s-start; + len = s - start; if (len >= MAX_QPATH || len < 5) { - trap->Error( ERR_DROP, "PrecacheItem: %s has bad precache string", - item->classname); + trap->Error(ERR_DROP, "PrecacheItem: %s has bad precache string", item->classname); return; } - memcpy (data, start, len); + memcpy(data, start, len); data[len] = 0; - if ( *s ) { + if (*s) { s++; } - trap->S_RegisterSound( data ); + trap->S_RegisterSound(data); } // parse the space seperated precache string for other media @@ -472,33 +447,31 @@ static void CG_RegisterItemSounds( int itemNum ) { s++; } - len = s-start; + len = s - start; if (len >= MAX_QPATH || len < 5) { - trap->Error( ERR_DROP, "PrecacheItem: %s has bad precache string", - item->classname); + trap->Error(ERR_DROP, "PrecacheItem: %s has bad precache string", item->classname); return; } - memcpy (data, start, len); + memcpy(data, start, len); data[len] = 0; - if ( *s ) { + if (*s) { s++; } - if ( !strcmp(data+len-3, "efx" )) { - trap->FX_RegisterEffect( data ); + if (!strcmp(data + len - 3, "efx")) { + trap->FX_RegisterEffect(data); } } } -static void CG_AS_Register(void) -{ +static void CG_AS_Register(void) { const char *soundName; int i; -// CG_LoadingString( "ambient sound sets" ); + // CG_LoadingString( "ambient sound sets" ); - //Load the ambient sets -#if 0 //as_preCacheMap was game-side.. that is evil. + // Load the ambient sets +#if 0 // as_preCacheMap was game-side.. that is evil. trap->AS_AddPrecacheEntry( "#clear" ); // ;-) //FIXME: Don't ask... I had to get around a really nasty MS error in the templates with this... namePrecache_m::iterator pi; @@ -507,20 +480,18 @@ static void CG_AS_Register(void) cgi_AS_AddPrecacheEntry( ((*pi).first).c_str() ); } #else - trap->AS_AddPrecacheEntry( "#clear" ); + trap->AS_AddPrecacheEntry("#clear"); - for ( i = 1 ; i < MAX_AMBIENT_SETS ; i++ ) { - soundName = CG_ConfigString( CS_AMBIENT_SET+i ); - if ( !soundName || !soundName[0] ) - { + for (i = 1; i < MAX_AMBIENT_SETS; i++) { + soundName = CG_ConfigString(CS_AMBIENT_SET + i); + if (!soundName || !soundName[0]) { break; } trap->AS_AddPrecacheEntry(soundName); } - soundName = CG_ConfigString( CS_GLOBAL_AMBIENT_SET ); - if (soundName && soundName[0] && Q_stricmp(soundName, "default")) - { //global soundset + soundName = CG_ConfigString(CS_GLOBAL_AMBIENT_SET); + if (soundName && soundName[0] && Q_stricmp(soundName, "default")) { // global soundset trap->AS_AddPrecacheEntry(soundName); } #endif @@ -528,24 +499,21 @@ static void CG_AS_Register(void) trap->AS_ParseSets(); } -//a global weather effect (rain, snow, etc) -void CG_ParseWeatherEffect(const char *str) -{ +// a global weather effect (rain, snow, etc) +void CG_ParseWeatherEffect(const char *str) { char *sptr = (char *)str; - sptr++; //pass the '*' + sptr++; // pass the '*' trap->R_WorldEffectCommand(sptr); } extern int cgSiegeRoundBeganTime; -void CG_ParseSiegeState(const char *str) -{ +void CG_ParseSiegeState(const char *str) { int i = 0; int j = 0; -// int prevState = cgSiegeRoundState; + // int prevState = cgSiegeRoundState; char b[1024]; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { b[j] = str[i]; i++; j++; @@ -553,29 +521,24 @@ void CG_ParseSiegeState(const char *str) b[j] = 0; cgSiegeRoundState = atoi(b); - if (str[i] == '|') - { + if (str[i] == '|') { j = 0; i++; - while (str[i]) - { + while (str[i]) { b[j] = str[i]; i++; j++; } b[j] = 0; -// if (cgSiegeRoundState != prevState) - { //it changed + // if (cgSiegeRoundState != prevState) + { // it changed cgSiegeRoundTime = atoi(b); - if (cgSiegeRoundState == 0 || cgSiegeRoundState == 2) - { + if (cgSiegeRoundState == 0 || cgSiegeRoundState == 2) { cgSiegeRoundBeganTime = cgSiegeRoundTime; } } - } - else - { - cgSiegeRoundTime = cg.time; + } else { + cgSiegeRoundTime = cg.time; } } @@ -590,100 +553,97 @@ void CG_PrecacheNPCSounds(const char *str); void CG_ParseSiegeObjectiveStatus(const char *str); extern int cg_beatingSiegeTime; extern int cg_siegeWinTeam; -static void CG_RegisterSounds( void ) { - int i; - char items[MAX_ITEMS+1]; - char name[MAX_QPATH]; - const char *soundName; +static void CG_RegisterSounds(void) { + int i; + char items[MAX_ITEMS + 1]; + char name[MAX_QPATH]; + const char *soundName; CG_AS_Register(); -// CG_LoadingString( "sounds" ); + // CG_LoadingString( "sounds" ); - trap->S_RegisterSound( "sound/weapons/melee/punch1.mp3" ); - trap->S_RegisterSound( "sound/weapons/melee/punch2.mp3" ); - trap->S_RegisterSound( "sound/weapons/melee/punch3.mp3" ); - trap->S_RegisterSound( "sound/weapons/melee/punch4.mp3" ); + trap->S_RegisterSound("sound/weapons/melee/punch1.mp3"); + trap->S_RegisterSound("sound/weapons/melee/punch2.mp3"); + trap->S_RegisterSound("sound/weapons/melee/punch3.mp3"); + trap->S_RegisterSound("sound/weapons/melee/punch4.mp3"); trap->S_RegisterSound("sound/movers/objects/saber_slam"); trap->S_RegisterSound("sound/player/bodyfall_human1.wav"); trap->S_RegisterSound("sound/player/bodyfall_human2.wav"); trap->S_RegisterSound("sound/player/bodyfall_human3.wav"); - //test effects + // test effects trap->FX_RegisterEffect("effects/mp/test_sparks.efx"); trap->FX_RegisterEffect("effects/mp/test_wall_impact.efx"); - cgs.media.oneMinuteSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM004" ); - cgs.media.fiveMinuteSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM005" ); - cgs.media.oneFragSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM001" ); - cgs.media.twoFragSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM002" ); - cgs.media.threeFragSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM003"); - cgs.media.count3Sound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM035" ); - cgs.media.count2Sound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM036" ); - cgs.media.count1Sound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM037" ); - cgs.media.countFightSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM038" ); + cgs.media.oneMinuteSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM004"); + cgs.media.fiveMinuteSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM005"); + cgs.media.oneFragSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM001"); + cgs.media.twoFragSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM002"); + cgs.media.threeFragSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM003"); + cgs.media.count3Sound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM035"); + cgs.media.count2Sound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM036"); + cgs.media.count1Sound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM037"); + cgs.media.countFightSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM038"); - cgs.media.hackerIconShader = trap->R_RegisterShaderNoMip("gfx/mp/c_icon_tech"); + cgs.media.hackerIconShader = trap->R_RegisterShaderNoMip("gfx/mp/c_icon_tech"); - cgs.media.redSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/red_glow" ); - cgs.media.redSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/red_line" ); - cgs.media.orangeSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/orange_glow" ); - cgs.media.orangeSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/orange_line" ); - cgs.media.yellowSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/yellow_glow" ); - cgs.media.yellowSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/yellow_line" ); - cgs.media.greenSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/green_glow" ); - cgs.media.greenSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/green_line" ); - cgs.media.blueSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/blue_glow" ); - cgs.media.blueSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/blue_line" ); - cgs.media.purpleSaberGlowShader = trap->R_RegisterShader( "gfx/effects/sabers/purple_glow" ); - cgs.media.purpleSaberCoreShader = trap->R_RegisterShader( "gfx/effects/sabers/purple_line" ); - cgs.media.saberBlurShader = trap->R_RegisterShader( "gfx/effects/sabers/saberBlur" ); - cgs.media.swordTrailShader = trap->R_RegisterShader( "gfx/effects/sabers/swordTrail" ); + cgs.media.redSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/red_glow"); + cgs.media.redSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/red_line"); + cgs.media.orangeSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/orange_glow"); + cgs.media.orangeSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/orange_line"); + cgs.media.yellowSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/yellow_glow"); + cgs.media.yellowSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/yellow_line"); + cgs.media.greenSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/green_glow"); + cgs.media.greenSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/green_line"); + cgs.media.blueSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/blue_glow"); + cgs.media.blueSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/blue_line"); + cgs.media.purpleSaberGlowShader = trap->R_RegisterShader("gfx/effects/sabers/purple_glow"); + cgs.media.purpleSaberCoreShader = trap->R_RegisterShader("gfx/effects/sabers/purple_line"); + cgs.media.saberBlurShader = trap->R_RegisterShader("gfx/effects/sabers/saberBlur"); + cgs.media.swordTrailShader = trap->R_RegisterShader("gfx/effects/sabers/swordTrail"); - cgs.media.forceCoronaShader = trap->R_RegisterShaderNoMip( "gfx/hud/force_swirl" ); + cgs.media.forceCoronaShader = trap->R_RegisterShaderNoMip("gfx/hud/force_swirl"); - cgs.media.yellowDroppedSaberShader = trap->R_RegisterShader("gfx/effects/yellow_glow"); + cgs.media.yellowDroppedSaberShader = trap->R_RegisterShader("gfx/effects/yellow_glow"); - cgs.media.rivetMarkShader = trap->R_RegisterShader( "gfx/damage/rivetmark" ); + cgs.media.rivetMarkShader = trap->R_RegisterShader("gfx/damage/rivetmark"); - trap->R_RegisterShader( "gfx/effects/saberFlare" ); + trap->R_RegisterShader("gfx/effects/saberFlare"); - trap->R_RegisterShader( "powerups/ysalimarishell" ); + trap->R_RegisterShader("powerups/ysalimarishell"); - trap->R_RegisterShader( "gfx/effects/forcePush" ); + trap->R_RegisterShader("gfx/effects/forcePush"); - trap->R_RegisterShader( "gfx/misc/red_dmgshield" ); - trap->R_RegisterShader( "gfx/misc/red_portashield" ); - trap->R_RegisterShader( "gfx/misc/blue_dmgshield" ); - trap->R_RegisterShader( "gfx/misc/blue_portashield" ); + trap->R_RegisterShader("gfx/misc/red_dmgshield"); + trap->R_RegisterShader("gfx/misc/red_portashield"); + trap->R_RegisterShader("gfx/misc/blue_dmgshield"); + trap->R_RegisterShader("gfx/misc/blue_portashield"); - trap->R_RegisterShader( "models/map_objects/imp_mine/turret_chair_dmg.tga" ); + trap->R_RegisterShader("models/map_objects/imp_mine/turret_chair_dmg.tga"); - for (i=1 ; i<9 ; i++) - { + for (i = 1; i < 9; i++) { trap->S_RegisterSound(va("sound/weapons/saber/saberhup%i.wav", i)); } - for (i=1 ; i<10 ; i++) - { + for (i = 1; i < 10; i++) { trap->S_RegisterSound(va("sound/weapons/saber/saberblock%i.wav", i)); } - for (i=1 ; i<4 ; i++) - { + for (i = 1; i < 4; i++) { trap->S_RegisterSound(va("sound/weapons/saber/bounce%i.wav", i)); } - trap->S_RegisterSound( "sound/weapons/saber/enemy_saber_on.wav" ); - trap->S_RegisterSound( "sound/weapons/saber/enemy_saber_off.wav" ); + trap->S_RegisterSound("sound/weapons/saber/enemy_saber_on.wav"); + trap->S_RegisterSound("sound/weapons/saber/enemy_saber_off.wav"); - trap->S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ); - trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" ); - trap->S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" ); - trap->S_RegisterSound( "sound/weapons/saber/saberhitwall1" ); - trap->S_RegisterSound( "sound/weapons/saber/saberhitwall2" ); - trap->S_RegisterSound( "sound/weapons/saber/saberhitwall3" ); + trap->S_RegisterSound("sound/weapons/saber/saberhum1.wav"); + trap->S_RegisterSound("sound/weapons/saber/saberon.wav"); + trap->S_RegisterSound("sound/weapons/saber/saberoffquick.wav"); + trap->S_RegisterSound("sound/weapons/saber/saberhitwall1"); + trap->S_RegisterSound("sound/weapons/saber/saberhitwall2"); + trap->S_RegisterSound("sound/weapons/saber/saberhitwall3"); trap->S_RegisterSound("sound/weapons/saber/saberhit.wav"); trap->S_RegisterSound("sound/weapons/saber/saberhit1.wav"); trap->S_RegisterSound("sound/weapons/saber/saberhit2.wav"); @@ -709,8 +669,7 @@ static void CG_RegisterSounds( void ) { trap->S_RegisterSound("sound/weapons/force/pull.wav"); trap->S_RegisterSound("sound/weapons/force/push.wav"); - for (i=1 ; i<3 ; i++) - { + for (i = 1; i < 3; i++) { trap->S_RegisterSound(va("sound/weapons/thermal/bounce%i.wav", i)); } @@ -726,41 +685,41 @@ static void CG_RegisterSounds( void ) { trap->S_RegisterSound("sound/effects/glassbreak1.wav"); - trap->S_RegisterSound( "sound/weapons/rocket/tick.wav" ); - trap->S_RegisterSound( "sound/weapons/rocket/lock.wav" ); + trap->S_RegisterSound("sound/weapons/rocket/tick.wav"); + trap->S_RegisterSound("sound/weapons/rocket/lock.wav"); trap->S_RegisterSound("sound/weapons/force/speedloop.wav"); - trap->S_RegisterSound("sound/weapons/force/protecthit.mp3"); //PDSOUND_PROTECTHIT - trap->S_RegisterSound("sound/weapons/force/protect.mp3"); //PDSOUND_PROTECT - trap->S_RegisterSound("sound/weapons/force/absorbhit.mp3"); //PDSOUND_ABSORBHIT - trap->S_RegisterSound("sound/weapons/force/absorb.mp3"); //PDSOUND_ABSORB - trap->S_RegisterSound("sound/weapons/force/jump.mp3"); //PDSOUND_FORCEJUMP - trap->S_RegisterSound("sound/weapons/force/grip.mp3"); //PDSOUND_FORCEGRIP + trap->S_RegisterSound("sound/weapons/force/protecthit.mp3"); // PDSOUND_PROTECTHIT + trap->S_RegisterSound("sound/weapons/force/protect.mp3"); // PDSOUND_PROTECT + trap->S_RegisterSound("sound/weapons/force/absorbhit.mp3"); // PDSOUND_ABSORBHIT + trap->S_RegisterSound("sound/weapons/force/absorb.mp3"); // PDSOUND_ABSORB + trap->S_RegisterSound("sound/weapons/force/jump.mp3"); // PDSOUND_FORCEJUMP + trap->S_RegisterSound("sound/weapons/force/grip.mp3"); // PDSOUND_FORCEGRIP - if ( cgs.gametype >= GT_TEAM || com_buildScript.integer ) { + if (cgs.gametype >= GT_TEAM || com_buildScript.integer) { #ifdef JK2AWARDS - cgs.media.captureAwardSound = trap->S_RegisterSound( "sound/teamplay/flagcapture_yourteam.wav" ); + cgs.media.captureAwardSound = trap->S_RegisterSound("sound/teamplay/flagcapture_yourteam.wav"); #endif - cgs.media.redLeadsSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM046"); - cgs.media.blueLeadsSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM045"); - cgs.media.teamsTiedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM032" ); + cgs.media.redLeadsSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM046"); + cgs.media.blueLeadsSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM045"); + cgs.media.teamsTiedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM032"); - cgs.media.redScoredSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM044"); - cgs.media.blueScoredSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM043" ); + cgs.media.redScoredSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM044"); + cgs.media.blueScoredSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM043"); - if ( cgs.gametype == GT_CTF || com_buildScript.integer ) { - cgs.media.redFlagReturnedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM042" ); - cgs.media.blueFlagReturnedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM041" ); - cgs.media.redTookFlagSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM040" ); - cgs.media.blueTookFlagSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM039" ); + if (cgs.gametype == GT_CTF || com_buildScript.integer) { + cgs.media.redFlagReturnedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM042"); + cgs.media.blueFlagReturnedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM041"); + cgs.media.redTookFlagSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM040"); + cgs.media.blueTookFlagSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM039"); } - if ( cgs.gametype == GT_CTY /*|| com_buildScript.integer*/ ) { - cgs.media.redYsalReturnedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM050" ); - cgs.media.blueYsalReturnedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM049" ); - cgs.media.redTookYsalSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM048" ); - cgs.media.blueTookYsalSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM047" ); + if (cgs.gametype == GT_CTY /*|| com_buildScript.integer*/) { + cgs.media.redYsalReturnedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM050"); + cgs.media.blueYsalReturnedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM049"); + cgs.media.redTookYsalSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM048"); + cgs.media.blueTookYsalSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM047"); } } @@ -769,33 +728,32 @@ static void CG_RegisterSounds( void ) { cgs.media.happyMusic = trap->S_RegisterSound("music/goodsmall.mp3"); cgs.media.dramaticFailure = trap->S_RegisterSound("music/badsmall.mp3"); - //PRECACHE ALL MUSIC HERE (don't need to precache normally because it's streamed off the disk) - if (com_buildScript.integer) - { - trap->S_StartBackgroundTrack( "music/mp/duel.mp3", "music/mp/duel.mp3", qfalse ); + // PRECACHE ALL MUSIC HERE (don't need to precache normally because it's streamed off the disk) + if (com_buildScript.integer) { + trap->S_StartBackgroundTrack("music/mp/duel.mp3", "music/mp/duel.mp3", qfalse); } cg.loadLCARSStage = 1; - cgs.media.selectSound = trap->S_RegisterSound( "sound/weapons/change.wav" ); + cgs.media.selectSound = trap->S_RegisterSound("sound/weapons/change.wav"); - cgs.media.teleInSound = trap->S_RegisterSound( "sound/player/telein.wav" ); - cgs.media.teleOutSound = trap->S_RegisterSound( "sound/player/teleout.wav" ); - cgs.media.respawnSound = trap->S_RegisterSound( "sound/items/respawn1.wav" ); + cgs.media.teleInSound = trap->S_RegisterSound("sound/player/telein.wav"); + cgs.media.teleOutSound = trap->S_RegisterSound("sound/player/teleout.wav"); + cgs.media.respawnSound = trap->S_RegisterSound("sound/items/respawn1.wav"); - trap->S_RegisterSound( "sound/movers/objects/objectHit.wav" ); + trap->S_RegisterSound("sound/movers/objects/objectHit.wav"); - cgs.media.talkSound = trap->S_RegisterSound( "sound/player/talk.wav" ); - cgs.media.landSound = trap->S_RegisterSound( "sound/player/land1.wav"); - cgs.media.fallSound = trap->S_RegisterSound( "sound/player/fallsplat.wav"); + cgs.media.talkSound = trap->S_RegisterSound("sound/player/talk.wav"); + cgs.media.landSound = trap->S_RegisterSound("sound/player/land1.wav"); + cgs.media.fallSound = trap->S_RegisterSound("sound/player/fallsplat.wav"); - cgs.media.crackleSound = trap->S_RegisterSound( "sound/effects/energy_crackle.wav" ); + cgs.media.crackleSound = trap->S_RegisterSound("sound/effects/energy_crackle.wav"); #ifdef JK2AWARDS - cgs.media.impressiveSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM025" ); - cgs.media.excellentSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM053" ); - cgs.media.deniedSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM017" ); - cgs.media.humiliationSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM019" ); - cgs.media.defendSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM024" ); + cgs.media.impressiveSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM025"); + cgs.media.excellentSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM053"); + cgs.media.deniedSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM017"); + cgs.media.humiliationSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM019"); + cgs.media.defendSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM024"); #endif /* @@ -804,196 +762,183 @@ static void CG_RegisterSounds( void ) { cgs.media.lostLeadSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM052"); */ - cgs.media.rollSound = trap->S_RegisterSound( "sound/player/roll1.wav"); + cgs.media.rollSound = trap->S_RegisterSound("sound/player/roll1.wav"); - cgs.media.noforceSound = trap->S_RegisterSound( "sound/weapons/force/noforce" ); + cgs.media.noforceSound = trap->S_RegisterSound("sound/weapons/force/noforce"); - cgs.media.watrInSound = trap->S_RegisterSound( "sound/player/watr_in.wav"); - cgs.media.watrOutSound = trap->S_RegisterSound( "sound/player/watr_out.wav"); - cgs.media.watrUnSound = trap->S_RegisterSound( "sound/player/watr_un.wav"); + cgs.media.watrInSound = trap->S_RegisterSound("sound/player/watr_in.wav"); + cgs.media.watrOutSound = trap->S_RegisterSound("sound/player/watr_out.wav"); + cgs.media.watrUnSound = trap->S_RegisterSound("sound/player/watr_un.wav"); - cgs.media.explosionModel = trap->R_RegisterModel ( "models/map_objects/mp/sphere.md3" ); - cgs.media.surfaceExplosionShader = trap->R_RegisterShader( "surfaceExplosion" ); + cgs.media.explosionModel = trap->R_RegisterModel("models/map_objects/mp/sphere.md3"); + cgs.media.surfaceExplosionShader = trap->R_RegisterShader("surfaceExplosion"); - cgs.media.disruptorShader = trap->R_RegisterShader( "gfx/effects/burn"); + cgs.media.disruptorShader = trap->R_RegisterShader("gfx/effects/burn"); - if (com_buildScript.integer) - { - trap->R_RegisterShader( "gfx/effects/turretflashdie" ); + if (com_buildScript.integer) { + trap->R_RegisterShader("gfx/effects/turretflashdie"); } - cgs.media.solidWhite = trap->R_RegisterShader( "gfx/effects/solidWhite_cull" ); + cgs.media.solidWhite = trap->R_RegisterShader("gfx/effects/solidWhite_cull"); trap->R_RegisterShader("gfx/misc/mp_light_enlight_disable"); trap->R_RegisterShader("gfx/misc/mp_dark_enlight_disable"); - trap->R_RegisterModel ( "models/map_objects/mp/sphere.md3" ); + trap->R_RegisterModel("models/map_objects/mp/sphere.md3"); trap->R_RegisterModel("models/items/remote.md3"); - cgs.media.holocronPickup = trap->S_RegisterSound( "sound/player/holocron.wav" ); + cgs.media.holocronPickup = trap->S_RegisterSound("sound/player/holocron.wav"); // Zoom - cgs.media.zoomStart = trap->S_RegisterSound( "sound/interface/zoomstart.wav" ); - cgs.media.zoomLoop = trap->S_RegisterSound( "sound/interface/zoomloop.wav" ); - cgs.media.zoomEnd = trap->S_RegisterSound( "sound/interface/zoomend.wav" ); - - for (i=0 ; i<4 ; i++) { - Com_sprintf (name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_STONEWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/stone_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_STONERUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_METALWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/metal_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_METALRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/pipe_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_PIPEWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/pipe_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_PIPERUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SPLASH][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WADE][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SWIM][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/snow_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SNOWWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/snow_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SNOWRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/sand_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SANDWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/sand_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_SANDRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/grass_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRASSWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/grass_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRASSRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/dirt_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_DIRTWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/dirt_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_DIRTRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/mud_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_MUDWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/mud_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_MUDRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/gravel_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRAVELWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/gravel_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_GRAVELRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/rug_step%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_RUGWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/rug_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_RUGRUN][i] = trap->S_RegisterSound (name); - - Com_sprintf (name, sizeof(name), "sound/player/footsteps/wood_walk%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WOODWALK][i] = trap->S_RegisterSound (name); - Com_sprintf (name, sizeof(name), "sound/player/footsteps/wood_run%i.wav", i+1); - cgs.media.footsteps[FOOTSTEP_WOODRUN][i] = trap->S_RegisterSound (name); + cgs.media.zoomStart = trap->S_RegisterSound("sound/interface/zoomstart.wav"); + cgs.media.zoomLoop = trap->S_RegisterSound("sound/interface/zoomloop.wav"); + cgs.media.zoomEnd = trap->S_RegisterSound("sound/interface/zoomend.wav"); + + for (i = 0; i < 4; i++) { + Com_sprintf(name, sizeof(name), "sound/player/footsteps/stone_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_STONEWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/stone_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_STONERUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/metal_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_METALWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/metal_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_METALRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/pipe_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_PIPEWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/pipe_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_PIPERUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SPLASH][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WADE][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/water_wade_0%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SWIM][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/snow_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SNOWWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/snow_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SNOWRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/sand_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SANDWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/sand_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_SANDRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/grass_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRASSWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/grass_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRASSRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/dirt_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_DIRTWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/dirt_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_DIRTRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/mud_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_MUDWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/mud_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_MUDRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/gravel_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRAVELWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/gravel_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_GRAVELRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/rug_step%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_RUGWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/rug_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_RUGRUN][i] = trap->S_RegisterSound(name); + + Com_sprintf(name, sizeof(name), "sound/player/footsteps/wood_walk%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WOODWALK][i] = trap->S_RegisterSound(name); + Com_sprintf(name, sizeof(name), "sound/player/footsteps/wood_run%i.wav", i + 1); + cgs.media.footsteps[FOOTSTEP_WOODRUN][i] = trap->S_RegisterSound(name); } // only register the items that the server says we need Q_strncpyz(items, CG_ConfigString(CS_ITEMS), sizeof(items)); - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( items[ i ] == '1' || com_buildScript.integer ) { - CG_RegisterItemSounds( i ); + for (i = 1; i < bg_numItems; i++) { + if (items[i] == '1' || com_buildScript.integer) { + CG_RegisterItemSounds(i); } } - for ( i = 1 ; i < MAX_SOUNDS ; i++ ) { - soundName = CG_ConfigString( CS_SOUNDS+i ); - if ( !soundName[0] ) { + for (i = 1; i < MAX_SOUNDS; i++) { + soundName = CG_ConfigString(CS_SOUNDS + i); + if (!soundName[0]) { break; } - if ( soundName[0] == '*' ) - { - if (soundName[1] == '$') - { //an NPC soundset + if (soundName[0] == '*') { + if (soundName[1] == '$') { // an NPC soundset CG_PrecacheNPCSounds(soundName); } - continue; // custom sound + continue; // custom sound } - cgs.gameSounds[i] = trap->S_RegisterSound( soundName ); + cgs.gameSounds[i] = trap->S_RegisterSound(soundName); } - for ( i = 1 ; i < MAX_FX ; i++ ) { - soundName = CG_ConfigString( CS_EFFECTS+i ); - if ( !soundName[0] ) { + for (i = 1; i < MAX_FX; i++) { + soundName = CG_ConfigString(CS_EFFECTS + i); + if (!soundName[0]) { break; } - if (soundName[0] == '*') - { //it's a special global weather effect + if (soundName[0] == '*') { // it's a special global weather effect CG_ParseWeatherEffect(soundName); cgs.gameEffects[i] = 0; - } - else - { - cgs.gameEffects[i] = trap->FX_RegisterEffect( soundName ); + } else { + cgs.gameEffects[i] = trap->FX_RegisterEffect(soundName); } } // register all the server specified icons - for ( i = 1; i < MAX_ICONS; i ++ ) - { - const char* iconName; + for (i = 1; i < MAX_ICONS; i++) { + const char *iconName; - iconName = CG_ConfigString ( CS_ICONS + i ); - if ( !iconName[0] ) - { + iconName = CG_ConfigString(CS_ICONS + i); + if (!iconName[0]) { break; } - cgs.gameIcons[i] = trap->R_RegisterShaderNoMip ( iconName ); + cgs.gameIcons[i] = trap->R_RegisterShaderNoMip(iconName); } soundName = CG_ConfigString(CS_SIEGE_STATE); - if (soundName[0]) - { + if (soundName[0]) { CG_ParseSiegeState(soundName); } soundName = CG_ConfigString(CS_SIEGE_WINTEAM); - if (soundName[0]) - { + if (soundName[0]) { cg_siegeWinTeam = atoi(soundName); } - if (cgs.gametype == GT_SIEGE) - { + if (cgs.gametype == GT_SIEGE) { CG_ParseSiegeObjectiveStatus(CG_ConfigString(CS_SIEGE_OBJECTIVES)); cg_beatingSiegeTime = atoi(CG_ConfigString(CS_SIEGE_TIMEOVERRIDE)); - if ( cg_beatingSiegeTime ) - { - CG_SetSiegeTimerCvar ( cg_beatingSiegeTime ); + if (cg_beatingSiegeTime) { + CG_SetSiegeTimerCvar(cg_beatingSiegeTime); } } cg.loadLCARSStage = 2; // FIXME: only needed with item - cgs.media.deploySeeker = trap->S_RegisterSound ("sound/chars/seeker/misc/hiss"); - cgs.media.medkitSound = trap->S_RegisterSound ("sound/items/use_bacta.wav"); + cgs.media.deploySeeker = trap->S_RegisterSound("sound/chars/seeker/misc/hiss"); + cgs.media.medkitSound = trap->S_RegisterSound("sound/items/use_bacta.wav"); - cgs.media.winnerSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM006" ); - cgs.media.loserSound = trap->S_RegisterSound( "sound/chars/protocol/misc/40MOM010" ); + cgs.media.winnerSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM006"); + cgs.media.loserSound = trap->S_RegisterSound("sound/chars/protocol/misc/40MOM010"); } - //------------------------------------- // CG_RegisterEffects // @@ -1001,8 +946,7 @@ static void CG_RegisterSounds( void ) { // and any shader, model, or sound // files an effect may use. //------------------------------------- -static void CG_RegisterEffects( void ) -{ +static void CG_RegisterEffects(void) { /* const char *effectName; int i; @@ -1019,26 +963,26 @@ static void CG_RegisterEffects( void ) trap->FX_RegisterEffect( effectName ); } */ - //the above was redundant as it's being done in CG_RegisterSounds + // the above was redundant as it's being done in CG_RegisterSounds // Set up the glass effects mini-system. CG_InitGlass(); - //footstep effects - cgs.effects.footstepMud = trap->FX_RegisterEffect( "materials/mud" ); - cgs.effects.footstepSand = trap->FX_RegisterEffect( "materials/sand" ); - cgs.effects.footstepSnow = trap->FX_RegisterEffect( "materials/snow" ); - cgs.effects.footstepGravel = trap->FX_RegisterEffect( "materials/gravel" ); - //landing effects - cgs.effects.landingMud = trap->FX_RegisterEffect( "materials/mud_large" ); - cgs.effects.landingSand = trap->FX_RegisterEffect( "materials/sand_large" ); - cgs.effects.landingDirt = trap->FX_RegisterEffect( "materials/dirt_large" ); - cgs.effects.landingSnow = trap->FX_RegisterEffect( "materials/snow_large" ); - cgs.effects.landingGravel = trap->FX_RegisterEffect( "materials/gravel_large" ); - //splashes - cgs.effects.waterSplash = trap->FX_RegisterEffect( "env/water_impact" ); - cgs.effects.lavaSplash = trap->FX_RegisterEffect( "env/lava_splash" ); - cgs.effects.acidSplash = trap->FX_RegisterEffect( "env/acid_splash" ); + // footstep effects + cgs.effects.footstepMud = trap->FX_RegisterEffect("materials/mud"); + cgs.effects.footstepSand = trap->FX_RegisterEffect("materials/sand"); + cgs.effects.footstepSnow = trap->FX_RegisterEffect("materials/snow"); + cgs.effects.footstepGravel = trap->FX_RegisterEffect("materials/gravel"); + // landing effects + cgs.effects.landingMud = trap->FX_RegisterEffect("materials/mud_large"); + cgs.effects.landingSand = trap->FX_RegisterEffect("materials/sand_large"); + cgs.effects.landingDirt = trap->FX_RegisterEffect("materials/dirt_large"); + cgs.effects.landingSnow = trap->FX_RegisterEffect("materials/snow_large"); + cgs.effects.landingGravel = trap->FX_RegisterEffect("materials/gravel_large"); + // splashes + cgs.effects.waterSplash = trap->FX_RegisterEffect("env/water_impact"); + cgs.effects.lavaSplash = trap->FX_RegisterEffect("env/lava_splash"); + cgs.effects.acidSplash = trap->FX_RegisterEffect("env/acid_splash"); } //=================================================================================== @@ -1053,104 +997,78 @@ CG_RegisterGraphics This function may execute for a couple of minutes with a slow disk. ================= */ -static void CG_RegisterGraphics( void ) { - int i; - int breakPoint; - char items[MAX_ITEMS+1]; - - static char *sb_nums[11] = { - "gfx/2d/numbers/zero", - "gfx/2d/numbers/one", - "gfx/2d/numbers/two", - "gfx/2d/numbers/three", - "gfx/2d/numbers/four", - "gfx/2d/numbers/five", - "gfx/2d/numbers/six", - "gfx/2d/numbers/seven", - "gfx/2d/numbers/eight", - "gfx/2d/numbers/nine", - "gfx/2d/numbers/minus", +static void CG_RegisterGraphics(void) { + int i; + int breakPoint; + char items[MAX_ITEMS + 1]; + + static char *sb_nums[11] = { + "gfx/2d/numbers/zero", "gfx/2d/numbers/one", "gfx/2d/numbers/two", "gfx/2d/numbers/three", "gfx/2d/numbers/four", "gfx/2d/numbers/five", + "gfx/2d/numbers/six", "gfx/2d/numbers/seven", "gfx/2d/numbers/eight", "gfx/2d/numbers/nine", "gfx/2d/numbers/minus", }; - static char *sb_t_nums[11] = { - "gfx/2d/numbers/t_zero", - "gfx/2d/numbers/t_one", - "gfx/2d/numbers/t_two", - "gfx/2d/numbers/t_three", - "gfx/2d/numbers/t_four", - "gfx/2d/numbers/t_five", - "gfx/2d/numbers/t_six", - "gfx/2d/numbers/t_seven", - "gfx/2d/numbers/t_eight", - "gfx/2d/numbers/t_nine", - "gfx/2d/numbers/t_minus", + static char *sb_t_nums[11] = { + "gfx/2d/numbers/t_zero", "gfx/2d/numbers/t_one", "gfx/2d/numbers/t_two", "gfx/2d/numbers/t_three", + "gfx/2d/numbers/t_four", "gfx/2d/numbers/t_five", "gfx/2d/numbers/t_six", "gfx/2d/numbers/t_seven", + "gfx/2d/numbers/t_eight", "gfx/2d/numbers/t_nine", "gfx/2d/numbers/t_minus", }; - static char *sb_c_nums[11] = { - "gfx/2d/numbers/c_zero", - "gfx/2d/numbers/c_one", - "gfx/2d/numbers/c_two", - "gfx/2d/numbers/c_three", - "gfx/2d/numbers/c_four", - "gfx/2d/numbers/c_five", - "gfx/2d/numbers/c_six", - "gfx/2d/numbers/c_seven", - "gfx/2d/numbers/c_eight", - "gfx/2d/numbers/c_nine", + static char *sb_c_nums[11] = { + "gfx/2d/numbers/c_zero", "gfx/2d/numbers/c_one", "gfx/2d/numbers/c_two", "gfx/2d/numbers/c_three", "gfx/2d/numbers/c_four", + "gfx/2d/numbers/c_five", "gfx/2d/numbers/c_six", "gfx/2d/numbers/c_seven", "gfx/2d/numbers/c_eight", "gfx/2d/numbers/c_nine", "gfx/2d/numbers/t_minus", //????? }; // clear any references to old media - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); trap->R_ClearScene(); - CG_LoadingString( cgs.mapname ); + CG_LoadingString(cgs.mapname); - trap->R_LoadWorld( cgs.mapname ); + trap->R_LoadWorld(cgs.mapname); // precache status bar pics -// CG_LoadingString( "game media" ); + // CG_LoadingString( "game media" ); - for ( i=0 ; i<11 ; i++) { - cgs.media.numberShaders[i] = trap->R_RegisterShader( sb_nums[i] ); + for (i = 0; i < 11; i++) { + cgs.media.numberShaders[i] = trap->R_RegisterShader(sb_nums[i]); } cg.loadLCARSStage = 3; - for ( i=0; i < 11; i++ ) - { - cgs.media.numberShaders[i] = trap->R_RegisterShaderNoMip( sb_nums[i] ); - cgs.media.smallnumberShaders[i] = trap->R_RegisterShaderNoMip( sb_t_nums[i] ); - cgs.media.chunkyNumberShaders[i] = trap->R_RegisterShaderNoMip( sb_c_nums[i] ); + for (i = 0; i < 11; i++) { + cgs.media.numberShaders[i] = trap->R_RegisterShaderNoMip(sb_nums[i]); + cgs.media.smallnumberShaders[i] = trap->R_RegisterShaderNoMip(sb_t_nums[i]); + cgs.media.chunkyNumberShaders[i] = trap->R_RegisterShaderNoMip(sb_c_nums[i]); } - trap->R_RegisterShaderNoMip ( "gfx/mp/pduel_icon_lone" ); - trap->R_RegisterShaderNoMip ( "gfx/mp/pduel_icon_double" ); + trap->R_RegisterShaderNoMip("gfx/mp/pduel_icon_lone"); + trap->R_RegisterShaderNoMip("gfx/mp/pduel_icon_double"); - cgs.media.balloonShader = trap->R_RegisterShader( "gfx/mp/chat_icon" ); - cgs.media.vchatShader = trap->R_RegisterShader( "gfx/mp/vchat_icon" ); + cgs.media.balloonShader = trap->R_RegisterShader("gfx/mp/chat_icon"); + cgs.media.vchatShader = trap->R_RegisterShader("gfx/mp/vchat_icon"); - cgs.media.deferShader = trap->R_RegisterShaderNoMip( "gfx/2d/defer.tga" ); + cgs.media.deferShader = trap->R_RegisterShaderNoMip("gfx/2d/defer.tga"); - cgs.media.radarShader = trap->R_RegisterShaderNoMip ( "gfx/menus/radar/radar.png" ); - cgs.media.siegeItemShader = trap->R_RegisterShaderNoMip ( "gfx/menus/radar/goalitem" ); - cgs.media.mAutomapPlayerIcon = trap->R_RegisterShader( "gfx/menus/radar/arrow_w" ); - cgs.media.mAutomapRocketIcon = trap->R_RegisterShader( "gfx/menus/radar/rocket" ); + cgs.media.radarShader = trap->R_RegisterShaderNoMip("gfx/menus/radar/radar.png"); + cgs.media.siegeItemShader = trap->R_RegisterShaderNoMip("gfx/menus/radar/goalitem"); + cgs.media.mAutomapPlayerIcon = trap->R_RegisterShader("gfx/menus/radar/arrow_w"); + cgs.media.mAutomapRocketIcon = trap->R_RegisterShader("gfx/menus/radar/rocket"); - cgs.media.wireframeAutomapFrame_left = trap->R_RegisterShader( "gfx/mp_automap/mpauto_frame_left" ); - cgs.media.wireframeAutomapFrame_right = trap->R_RegisterShader( "gfx/mp_automap/mpauto_frame_right" ); - cgs.media.wireframeAutomapFrame_top = trap->R_RegisterShader( "gfx/mp_automap/mpauto_frame_top" ); - cgs.media.wireframeAutomapFrame_bottom = trap->R_RegisterShader( "gfx/mp_automap/mpauto_frame_bottom" ); + cgs.media.wireframeAutomapFrame_left = trap->R_RegisterShader("gfx/mp_automap/mpauto_frame_left"); + cgs.media.wireframeAutomapFrame_right = trap->R_RegisterShader("gfx/mp_automap/mpauto_frame_right"); + cgs.media.wireframeAutomapFrame_top = trap->R_RegisterShader("gfx/mp_automap/mpauto_frame_top"); + cgs.media.wireframeAutomapFrame_bottom = trap->R_RegisterShader("gfx/mp_automap/mpauto_frame_bottom"); - cgs.media.lagometerShader = trap->R_RegisterShaderNoMip("gfx/2d/lag" ); - cgs.media.connectionShader = trap->R_RegisterShaderNoMip( "gfx/2d/net" ); + cgs.media.lagometerShader = trap->R_RegisterShaderNoMip("gfx/2d/lag"); + cgs.media.connectionShader = trap->R_RegisterShaderNoMip("gfx/2d/net"); trap->FX_InitSystem(&cg.refdef); CG_RegisterEffects(); - cgs.media.boltShader = trap->R_RegisterShader( "gfx/misc/blueLine" ); + cgs.media.boltShader = trap->R_RegisterShader("gfx/misc/blueLine"); - cgs.effects.turretShotEffect = trap->FX_RegisterEffect( "turret/shot" ); + cgs.effects.turretShotEffect = trap->FX_RegisterEffect("turret/shot"); cgs.effects.mEmplacedDeadSmoke = trap->FX_RegisterEffect("emplaced/dead_smoke.efx"); cgs.effects.mEmplacedExplode = trap->FX_RegisterEffect("emplaced/explode.efx"); cgs.effects.mTurretExplode = trap->FX_RegisterEffect("turret/explode.efx"); @@ -1162,19 +1080,18 @@ static void CG_RegisterGraphics( void ) { cgs.effects.mAltDetonate = trap->FX_RegisterEffect("demp2/altDetonate.efx"); cgs.effects.mSparksExplodeNoSound = trap->FX_RegisterEffect("sparks/spark_exp_nosnd"); cgs.effects.mTripMineLaser = trap->FX_RegisterEffect("tripMine/laser.efx"); - cgs.effects.mEmplacedMuzzleFlash = trap->FX_RegisterEffect( "effects/emplaced/muzzle_flash" ); + cgs.effects.mEmplacedMuzzleFlash = trap->FX_RegisterEffect("effects/emplaced/muzzle_flash"); cgs.effects.mConcussionAltRing = trap->FX_RegisterEffect("concussion/alt_ring"); cgs.effects.mHyperspaceStars = trap->FX_RegisterEffect("ships/hyperspace_stars"); - cgs.effects.mBlackSmoke = trap->FX_RegisterEffect( "volumetric/black_smoke" ); + cgs.effects.mBlackSmoke = trap->FX_RegisterEffect("volumetric/black_smoke"); cgs.effects.mShipDestDestroyed = trap->FX_RegisterEffect("effects/ships/dest_destroyed.efx"); cgs.effects.mShipDestBurning = trap->FX_RegisterEffect("effects/ships/dest_burning.efx"); cgs.effects.mBobaJet = trap->FX_RegisterEffect("effects/boba/jet.efx"); - cgs.effects.itemCone = trap->FX_RegisterEffect("mp/itemcone.efx"); cgs.effects.mTurretMuzzleFlash = trap->FX_RegisterEffect("effects/turret/muzzle_flash.efx"); - cgs.effects.mSparks = trap->FX_RegisterEffect("sparks/spark_nosnd.efx"); //sparks/spark.efx + cgs.effects.mSparks = trap->FX_RegisterEffect("sparks/spark_nosnd.efx"); // sparks/spark.efx cgs.effects.mSaberCut = trap->FX_RegisterEffect("saber/saber_cut.efx"); cgs.effects.mSaberBlock = trap->FX_RegisterEffect("saber/saber_block.efx"); cgs.effects.mSaberBloodSparks = trap->FX_RegisterEffect("saber/blood_sparks_mp.efx"); @@ -1186,24 +1103,24 @@ static void CG_RegisterGraphics( void ) { cgs.effects.mBlasterSmoke = trap->FX_RegisterEffect("blaster/smoke_bolton"); cgs.effects.mForceConfustionOld = trap->FX_RegisterEffect("force/confusion_old.efx"); - cgs.effects.forceLightning = trap->FX_RegisterEffect( "effects/force/lightning.efx" ); - cgs.effects.forceLightningWide = trap->FX_RegisterEffect( "effects/force/lightningwide.efx" ); - cgs.effects.forceDrain = trap->FX_RegisterEffect( "effects/mp/drain.efx" ); - cgs.effects.forceDrainWide = trap->FX_RegisterEffect( "effects/mp/drainwide.efx" ); - cgs.effects.forceDrained = trap->FX_RegisterEffect( "effects/mp/drainhit.efx"); + cgs.effects.forceLightning = trap->FX_RegisterEffect("effects/force/lightning.efx"); + cgs.effects.forceLightningWide = trap->FX_RegisterEffect("effects/force/lightningwide.efx"); + cgs.effects.forceDrain = trap->FX_RegisterEffect("effects/mp/drain.efx"); + cgs.effects.forceDrainWide = trap->FX_RegisterEffect("effects/mp/drainwide.efx"); + cgs.effects.forceDrained = trap->FX_RegisterEffect("effects/mp/drainhit.efx"); cgs.effects.mDisruptorDeathSmoke = trap->FX_RegisterEffect("disruptor/death_smoke"); - for ( i = 0 ; i < NUM_CROSSHAIRS ; i++ ) { - cgs.media.crosshairShader[i] = trap->R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a'+i) ); + for (i = 0; i < NUM_CROSSHAIRS; i++) { + cgs.media.crosshairShader[i] = trap->R_RegisterShaderNoMip(va("gfx/2d/crosshair%c", 'a' + i)); } cg.loadLCARSStage = 4; - cgs.media.backTileShader = trap->R_RegisterShader( "gfx/2d/backtile" ); + cgs.media.backTileShader = trap->R_RegisterShader("gfx/2d/backtile"); - //precache the fpls skin - //trap->R_RegisterSkin("models/players/kyle/model_fpls2.skin"); + // precache the fpls skin + // trap->R_RegisterSkin("models/players/kyle/model_fpls2.skin"); cgs.media.itemRespawningPlaceholder = trap->R_RegisterShader("powerups/placeholder"); cgs.media.itemRespawningRezOut = trap->R_RegisterShader("powerups/rezout"); @@ -1216,255 +1133,232 @@ static void CG_RegisterGraphics( void ) { cgs.media.itemHoloModel = trap->R_RegisterModel("models/map_objects/mp/holo.md3"); - if (cgs.gametype == GT_HOLOCRON || com_buildScript.integer) - { - for ( i=0; i < NUM_FORCE_POWERS; i++ ) - { - if (forceHolocronModels[i] && - forceHolocronModels[i][0]) - { + if (cgs.gametype == GT_HOLOCRON || com_buildScript.integer) { + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (forceHolocronModels[i] && forceHolocronModels[i][0]) { trap->R_RegisterModel(forceHolocronModels[i]); } } } - if ( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY || com_buildScript.integer ) { - if (com_buildScript.integer) - { - trap->R_RegisterModel( "models/flags/r_flag.md3" ); - trap->R_RegisterModel( "models/flags/b_flag.md3" ); - trap->R_RegisterModel( "models/flags/r_flag_ysal.md3" ); - trap->R_RegisterModel( "models/flags/b_flag_ysal.md3" ); + if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTY || com_buildScript.integer) { + if (com_buildScript.integer) { + trap->R_RegisterModel("models/flags/r_flag.md3"); + trap->R_RegisterModel("models/flags/b_flag.md3"); + trap->R_RegisterModel("models/flags/r_flag_ysal.md3"); + trap->R_RegisterModel("models/flags/b_flag_ysal.md3"); } - if (cgs.gametype == GT_CTF) - { - cgs.media.redFlagModel = trap->R_RegisterModel( "models/flags/r_flag.md3" ); - cgs.media.blueFlagModel = trap->R_RegisterModel( "models/flags/b_flag.md3" ); - } - else if(cgs.gametype == GT_CTY) - { - cgs.media.redFlagModel = trap->R_RegisterModel( "models/flags/r_flag_ysal.md3" ); - cgs.media.blueFlagModel = trap->R_RegisterModel( "models/flags/b_flag_ysal.md3" ); + if (cgs.gametype == GT_CTF) { + cgs.media.redFlagModel = trap->R_RegisterModel("models/flags/r_flag.md3"); + cgs.media.blueFlagModel = trap->R_RegisterModel("models/flags/b_flag.md3"); + } else if (cgs.gametype == GT_CTY) { + cgs.media.redFlagModel = trap->R_RegisterModel("models/flags/r_flag_ysal.md3"); + cgs.media.blueFlagModel = trap->R_RegisterModel("models/flags/b_flag_ysal.md3"); } - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" ); - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" ); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_x"); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_x"); - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" ); - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" ); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag_ys"); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag_ys"); - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_rflag" ); - trap->R_RegisterShaderNoMip( "gfx/hud/mpi_bflag" ); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_rflag"); + trap->R_RegisterShaderNoMip("gfx/hud/mpi_bflag"); trap->R_RegisterShaderNoMip("gfx/2d/net.tga"); } - if ( cgs.gametype >= GT_TEAM || com_buildScript.integer ) { - cgs.media.teamRedShader = trap->R_RegisterShader( "sprites/team_red" ); - cgs.media.teamBlueShader = trap->R_RegisterShader( "sprites/team_blue" ); - //cgs.media.redQuadShader = trap->R_RegisterShader("powerups/blueflag" ); - cgs.media.teamStatusBar = trap->R_RegisterShader( "gfx/2d/colorbar.tga" ); - } - else if ( cgs.gametype == GT_JEDIMASTER ) - { - cgs.media.teamRedShader = trap->R_RegisterShader( "sprites/team_red" ); + if (cgs.gametype >= GT_TEAM || com_buildScript.integer) { + cgs.media.teamRedShader = trap->R_RegisterShader("sprites/team_red"); + cgs.media.teamBlueShader = trap->R_RegisterShader("sprites/team_blue"); + // cgs.media.redQuadShader = trap->R_RegisterShader("powerups/blueflag" ); + cgs.media.teamStatusBar = trap->R_RegisterShader("gfx/2d/colorbar.tga"); + } else if (cgs.gametype == GT_JEDIMASTER) { + cgs.media.teamRedShader = trap->R_RegisterShader("sprites/team_red"); } - if (cgs.gametype == GT_POWERDUEL || com_buildScript.integer) - { - cgs.media.powerDuelAllyShader = trap->R_RegisterShader("gfx/mp/pduel_icon_double");//trap->R_RegisterShader("gfx/mp/pduel_gameicon_ally"); + if (cgs.gametype == GT_POWERDUEL || com_buildScript.integer) { + cgs.media.powerDuelAllyShader = trap->R_RegisterShader("gfx/mp/pduel_icon_double"); // trap->R_RegisterShader("gfx/mp/pduel_gameicon_ally"); } - cgs.media.heartShader = trap->R_RegisterShaderNoMip( "ui/assets/statusbar/selectedhealth.tga" ); + cgs.media.heartShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/selectedhealth.tga"); - cgs.media.ysaliredShader = trap->R_RegisterShader( "powerups/ysaliredshell"); - cgs.media.ysaliblueShader = trap->R_RegisterShader( "powerups/ysaliblueshell"); - cgs.media.ysalimariShader = trap->R_RegisterShader( "powerups/ysalimarishell"); - cgs.media.boonShader = trap->R_RegisterShader( "powerups/boonshell"); - cgs.media.endarkenmentShader = trap->R_RegisterShader( "powerups/endarkenmentshell"); - cgs.media.enlightenmentShader = trap->R_RegisterShader( "powerups/enlightenmentshell"); - cgs.media.invulnerabilityShader = trap->R_RegisterShader( "powerups/invulnerabilityshell"); + cgs.media.ysaliredShader = trap->R_RegisterShader("powerups/ysaliredshell"); + cgs.media.ysaliblueShader = trap->R_RegisterShader("powerups/ysaliblueshell"); + cgs.media.ysalimariShader = trap->R_RegisterShader("powerups/ysalimarishell"); + cgs.media.boonShader = trap->R_RegisterShader("powerups/boonshell"); + cgs.media.endarkenmentShader = trap->R_RegisterShader("powerups/endarkenmentshell"); + cgs.media.enlightenmentShader = trap->R_RegisterShader("powerups/enlightenmentshell"); + cgs.media.invulnerabilityShader = trap->R_RegisterShader("powerups/invulnerabilityshell"); #ifdef JK2AWARDS - cgs.media.medalImpressive = trap->R_RegisterShaderNoMip( "medal_impressive" ); - cgs.media.medalExcellent = trap->R_RegisterShaderNoMip( "medal_excellent" ); - cgs.media.medalGauntlet = trap->R_RegisterShaderNoMip( "medal_gauntlet" ); - cgs.media.medalDefend = trap->R_RegisterShaderNoMip( "medal_defend" ); - cgs.media.medalAssist = trap->R_RegisterShaderNoMip( "medal_assist" ); - cgs.media.medalCapture = trap->R_RegisterShaderNoMip( "medal_capture" ); + cgs.media.medalImpressive = trap->R_RegisterShaderNoMip("medal_impressive"); + cgs.media.medalExcellent = trap->R_RegisterShaderNoMip("medal_excellent"); + cgs.media.medalGauntlet = trap->R_RegisterShaderNoMip("medal_gauntlet"); + cgs.media.medalDefend = trap->R_RegisterShaderNoMip("medal_defend"); + cgs.media.medalAssist = trap->R_RegisterShaderNoMip("medal_assist"); + cgs.media.medalCapture = trap->R_RegisterShaderNoMip("medal_capture"); #endif // Binocular interface - cgs.media.binocularCircle = trap->R_RegisterShader( "gfx/2d/binCircle" ); - cgs.media.binocularMask = trap->R_RegisterShader( "gfx/2d/binMask" ); - cgs.media.binocularArrow = trap->R_RegisterShader( "gfx/2d/binSideArrow" ); - cgs.media.binocularTri = trap->R_RegisterShader( "gfx/2d/binTopTri" ); - cgs.media.binocularStatic = trap->R_RegisterShader( "gfx/2d/binocularWindow" ); - cgs.media.binocularOverlay = trap->R_RegisterShader( "gfx/2d/binocularNumOverlay" ); + cgs.media.binocularCircle = trap->R_RegisterShader("gfx/2d/binCircle"); + cgs.media.binocularMask = trap->R_RegisterShader("gfx/2d/binMask"); + cgs.media.binocularArrow = trap->R_RegisterShader("gfx/2d/binSideArrow"); + cgs.media.binocularTri = trap->R_RegisterShader("gfx/2d/binTopTri"); + cgs.media.binocularStatic = trap->R_RegisterShader("gfx/2d/binocularWindow"); + cgs.media.binocularOverlay = trap->R_RegisterShader("gfx/2d/binocularNumOverlay"); cg.loadLCARSStage = 5; // Chunk models - //FIXME: jfm:? bother to conditionally load these if an ent has this material type? - for ( i = 0; i < NUM_CHUNK_MODELS; i++ ) - { - cgs.media.chunkModels[CHUNK_METAL2][i] = trap->R_RegisterModel( va( "models/chunks/metal/metal1_%i.md3", i+1 ) ); //_ /switched\ _ - cgs.media.chunkModels[CHUNK_METAL1][i] = trap->R_RegisterModel( va( "models/chunks/metal/metal2_%i.md3", i+1 ) ); // \switched/ - cgs.media.chunkModels[CHUNK_ROCK1][i] = trap->R_RegisterModel( va( "models/chunks/rock/rock1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK2][i] = trap->R_RegisterModel( va( "models/chunks/rock/rock2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_ROCK3][i] = trap->R_RegisterModel( va( "models/chunks/rock/rock3_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE1][i] = trap->R_RegisterModel( va( "models/chunks/crate/crate1_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_CRATE2][i] = trap->R_RegisterModel( va( "models/chunks/crate/crate2_%i.md3", i+1 ) ); - cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = trap->R_RegisterModel( va( "models/chunks/metal/wmetal1_%i.md3", i+1 ) ); - } - - cgs.media.chunkSound = trap->S_RegisterSound("sound/weapons/explosions/glasslcar"); - cgs.media.grateSound = trap->S_RegisterSound( "sound/effects/grate_destroy" ); - cgs.media.rockBreakSound = trap->S_RegisterSound("sound/effects/wall_smash"); - cgs.media.rockBounceSound[0] = trap->S_RegisterSound("sound/effects/stone_bounce"); - cgs.media.rockBounceSound[1] = trap->S_RegisterSound("sound/effects/stone_bounce2"); - cgs.media.metalBounceSound[0] = trap->S_RegisterSound("sound/effects/metal_bounce"); - cgs.media.metalBounceSound[1] = trap->S_RegisterSound("sound/effects/metal_bounce2"); - cgs.media.glassChunkSound = trap->S_RegisterSound("sound/weapons/explosions/glassbreak1"); - cgs.media.crateBreakSound[0] = trap->S_RegisterSound("sound/weapons/explosions/crateBust1" ); - cgs.media.crateBreakSound[1] = trap->S_RegisterSound("sound/weapons/explosions/crateBust2" ); + // FIXME: jfm:? bother to conditionally load these if an ent has this material type? + for (i = 0; i < NUM_CHUNK_MODELS; i++) { + cgs.media.chunkModels[CHUNK_METAL2][i] = trap->R_RegisterModel(va("models/chunks/metal/metal1_%i.md3", i + 1)); //_ /switched\ _ + cgs.media.chunkModels[CHUNK_METAL1][i] = trap->R_RegisterModel(va("models/chunks/metal/metal2_%i.md3", i + 1)); // \switched/ + cgs.media.chunkModels[CHUNK_ROCK1][i] = trap->R_RegisterModel(va("models/chunks/rock/rock1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK2][i] = trap->R_RegisterModel(va("models/chunks/rock/rock2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_ROCK3][i] = trap->R_RegisterModel(va("models/chunks/rock/rock3_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE1][i] = trap->R_RegisterModel(va("models/chunks/crate/crate1_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_CRATE2][i] = trap->R_RegisterModel(va("models/chunks/crate/crate2_%i.md3", i + 1)); + cgs.media.chunkModels[CHUNK_WHITE_METAL][i] = trap->R_RegisterModel(va("models/chunks/metal/wmetal1_%i.md3", i + 1)); + } + + cgs.media.chunkSound = trap->S_RegisterSound("sound/weapons/explosions/glasslcar"); + cgs.media.grateSound = trap->S_RegisterSound("sound/effects/grate_destroy"); + cgs.media.rockBreakSound = trap->S_RegisterSound("sound/effects/wall_smash"); + cgs.media.rockBounceSound[0] = trap->S_RegisterSound("sound/effects/stone_bounce"); + cgs.media.rockBounceSound[1] = trap->S_RegisterSound("sound/effects/stone_bounce2"); + cgs.media.metalBounceSound[0] = trap->S_RegisterSound("sound/effects/metal_bounce"); + cgs.media.metalBounceSound[1] = trap->S_RegisterSound("sound/effects/metal_bounce2"); + cgs.media.glassChunkSound = trap->S_RegisterSound("sound/weapons/explosions/glassbreak1"); + cgs.media.crateBreakSound[0] = trap->S_RegisterSound("sound/weapons/explosions/crateBust1"); + cgs.media.crateBreakSound[1] = trap->S_RegisterSound("sound/weapons/explosions/crateBust2"); -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ CG_InitItems(); -/* -Ghoul2 Insert End -*/ - memset( cg_weapons, 0, sizeof( cg_weapons ) ); + /* + Ghoul2 Insert End + */ + memset(cg_weapons, 0, sizeof(cg_weapons)); // only register the items that the server says we need Q_strncpyz(items, CG_ConfigString(CS_ITEMS), sizeof(items)); - for ( i = 1 ; i < bg_numItems ; i++ ) { - if ( items[ i ] == '1' || com_buildScript.integer ) { - CG_LoadingItem( i ); - CG_RegisterItemVisuals( i ); + for (i = 1; i < bg_numItems; i++) { + if (items[i] == '1' || com_buildScript.integer) { + CG_LoadingItem(i); + CG_RegisterItemVisuals(i); } } cg.loadLCARSStage = 6; - cgs.media.glassShardShader = trap->R_RegisterShader( "gfx/misc/test_crackle" ); + cgs.media.glassShardShader = trap->R_RegisterShader("gfx/misc/test_crackle"); - // doing one shader just makes it look like a shell. By using two shaders with different bulge offsets and different texture scales, it has a much more chaotic look - cgs.media.electricBodyShader = trap->R_RegisterShader( "gfx/misc/electric" ); - cgs.media.electricBody2Shader = trap->R_RegisterShader( "gfx/misc/fullbodyelectric2" ); + // doing one shader just makes it look like a shell. By using two shaders with different bulge offsets and different texture scales, it has a much more + // chaotic look + cgs.media.electricBodyShader = trap->R_RegisterShader("gfx/misc/electric"); + cgs.media.electricBody2Shader = trap->R_RegisterShader("gfx/misc/fullbodyelectric2"); - cgs.media.fsrMarkShader = trap->R_RegisterShader( "footstep_r" ); - cgs.media.fslMarkShader = trap->R_RegisterShader( "footstep_l" ); - cgs.media.fshrMarkShader = trap->R_RegisterShader( "footstep_heavy_r" ); - cgs.media.fshlMarkShader = trap->R_RegisterShader( "footstep_heavy_l" ); + cgs.media.fsrMarkShader = trap->R_RegisterShader("footstep_r"); + cgs.media.fslMarkShader = trap->R_RegisterShader("footstep_l"); + cgs.media.fshrMarkShader = trap->R_RegisterShader("footstep_heavy_r"); + cgs.media.fshlMarkShader = trap->R_RegisterShader("footstep_heavy_l"); - cgs.media.refractionShader = trap->R_RegisterShader("effects/refraction"); + cgs.media.refractionShader = trap->R_RegisterShader("effects/refraction"); - cgs.media.cloakedShader = trap->R_RegisterShader( "gfx/effects/cloakedShader" ); + cgs.media.cloakedShader = trap->R_RegisterShader("gfx/effects/cloakedShader"); // wall marks - cgs.media.shadowMarkShader = trap->R_RegisterShader( "markShadow" ); - cgs.media.wakeMarkShader = trap->R_RegisterShader( "wake" ); + cgs.media.shadowMarkShader = trap->R_RegisterShader("markShadow"); + cgs.media.wakeMarkShader = trap->R_RegisterShader("wake"); - cgs.media.viewPainShader = trap->R_RegisterShader( "gfx/misc/borgeyeflare" ); - cgs.media.viewPainShader_Shields = trap->R_RegisterShader( "gfx/mp/dmgshader_shields" ); - cgs.media.viewPainShader_ShieldsAndHealth = trap->R_RegisterShader( "gfx/mp/dmgshader_shieldsandhealth" ); + cgs.media.viewPainShader = trap->R_RegisterShader("gfx/misc/borgeyeflare"); + cgs.media.viewPainShader_Shields = trap->R_RegisterShader("gfx/mp/dmgshader_shields"); + cgs.media.viewPainShader_ShieldsAndHealth = trap->R_RegisterShader("gfx/mp/dmgshader_shieldsandhealth"); // register the inline models breakPoint = cgs.numInlineModels = trap->CM_NumInlineModels(); - for ( i = 1 ; i < cgs.numInlineModels ; i++ ) { - char name[10]; - vec3_t mins, maxs; - int j; - - Com_sprintf( name, sizeof(name), "*%i", i ); - cgs.inlineDrawModel[i] = trap->R_RegisterModel( name ); - if (!cgs.inlineDrawModel[i]) - { + for (i = 1; i < cgs.numInlineModels; i++) { + char name[10]; + vec3_t mins, maxs; + int j; + + Com_sprintf(name, sizeof(name), "*%i", i); + cgs.inlineDrawModel[i] = trap->R_RegisterModel(name); + if (!cgs.inlineDrawModel[i]) { breakPoint = i; break; } - trap->R_ModelBounds( cgs.inlineDrawModel[i], mins, maxs ); - for ( j = 0 ; j < 3 ; j++ ) { - cgs.inlineModelMidpoints[i][j] = mins[j] + 0.5 * ( maxs[j] - mins[j] ); + trap->R_ModelBounds(cgs.inlineDrawModel[i], mins, maxs); + for (j = 0; j < 3; j++) { + cgs.inlineModelMidpoints[i][j] = mins[j] + 0.5 * (maxs[j] - mins[j]); } } cg.loadLCARSStage = 7; // register all the server specified models - for (i=1 ; iR_RegisterModel( modelName ); - } - else - {//FIXME: register here so that stuff gets precached!!! + if (modelName[0] != '$' && modelName[0] != '@') { // don't register vehicle names and saber names as models. + cgs.gameModels[i] = trap->R_RegisterModel(modelName); + } else { // FIXME: register here so that stuff gets precached!!! cgs.gameModels[i] = 0; } } cg.loadLCARSStage = 8; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ + // CG_LoadingString( "BSP instances" ); -// CG_LoadingString( "BSP instances" ); + for (i = 1; i < MAX_SUB_BSP; i++) { + const char *bspName = 0; + vec3_t mins, maxs; + int j; + int sub = 0; + char temp[MAX_QPATH]; - for(i = 1; i < MAX_SUB_BSP; i++) - { - const char *bspName = 0; - vec3_t mins, maxs; - int j; - int sub = 0; - char temp[MAX_QPATH]; - - bspName = CG_ConfigString( CS_BSP_MODELS+i ); - if ( !bspName[0] ) - { + bspName = CG_ConfigString(CS_BSP_MODELS + i); + if (!bspName[0]) { break; } - trap->CM_LoadMap( bspName, qtrue ); - cgs.inlineDrawModel[breakPoint] = trap->R_RegisterModel( bspName ); - trap->R_ModelBounds( cgs.inlineDrawModel[breakPoint], mins, maxs ); - for ( j = 0 ; j < 3 ; j++ ) - { - cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * ( maxs[j] - mins[j] ); + trap->CM_LoadMap(bspName, qtrue); + cgs.inlineDrawModel[breakPoint] = trap->R_RegisterModel(bspName); + trap->R_ModelBounds(cgs.inlineDrawModel[breakPoint], mins, maxs); + for (j = 0; j < 3; j++) { + cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * (maxs[j] - mins[j]); } breakPoint++; - for(sub=1;subR_RegisterModel( temp ); - if (!cgs.inlineDrawModel[breakPoint]) - { + cgs.inlineDrawModel[breakPoint] = trap->R_RegisterModel(temp); + if (!cgs.inlineDrawModel[breakPoint]) { break; } - trap->R_ModelBounds( cgs.inlineDrawModel[breakPoint], mins, maxs ); - for ( j = 0 ; j < 3 ; j++ ) - { - cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * ( maxs[j] - mins[j] ); + trap->R_ModelBounds(cgs.inlineDrawModel[breakPoint], mins, maxs); + for (j = 0; j < 3; j++) { + cgs.inlineModelMidpoints[breakPoint][j] = mins[j] + 0.5 * (maxs[j] - mins[j]); } breakPoint++; } @@ -1483,21 +1377,20 @@ Ghoul2 Insert Start cgs.skins[i] = trap->R_RegisterSkin( modelName ); } */ - //rww - removed and replaced with CS_G2BONES. For custom skins - //the new method is to append a * after an indexed model name and - //then append the skin name after that (note that this is only - //used for NPCs) + // rww - removed and replaced with CS_G2BONES. For custom skins + // the new method is to append a * after an indexed model name and + // then append the skin name after that (note that this is only + // used for NPCs) -// CG_LoadingString("weapons"); + // CG_LoadingString("weapons"); CG_InitG2Weapons(); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ cg.loadLCARSStage = 9; - // new stuff cgs.media.patrolShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/patrol.tga"); cgs.media.assaultShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/assault.tga"); @@ -1506,36 +1399,34 @@ Ghoul2 Insert End cgs.media.defendShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/defend.tga"); cgs.media.retrieveShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/retrieve.tga"); cgs.media.escortShader = trap->R_RegisterShaderNoMip("ui/assets/statusbar/escort.tga"); - cgs.media.cursor = trap->R_RegisterShaderNoMip( "menu/art/3_cursor2" ); - cgs.media.sizeCursor = trap->R_RegisterShaderNoMip( "ui/assets/sizecursor.tga" ); - cgs.media.selectCursor = trap->R_RegisterShaderNoMip( "ui/assets/selectcursor.tga" ); + cgs.media.cursor = trap->R_RegisterShaderNoMip("menu/art/3_cursor2"); + cgs.media.sizeCursor = trap->R_RegisterShaderNoMip("ui/assets/sizecursor.tga"); + cgs.media.selectCursor = trap->R_RegisterShaderNoMip("ui/assets/selectcursor.tga"); - cgs.media.halfShieldModel = trap->R_RegisterModel ( "models/weaphits/testboom.md3" ); - cgs.media.halfShieldShader = trap->R_RegisterShader( "halfShieldShell" ); + cgs.media.halfShieldModel = trap->R_RegisterModel("models/weaphits/testboom.md3"); + cgs.media.halfShieldShader = trap->R_RegisterShader("halfShieldShell"); trap->FX_RegisterEffect("force/force_touch"); } -const char *CG_GetStringEdString(char *refSection, char *refName) -{ - static char text[2][1024]; //just incase it's nested - static int index = 0; +const char *CG_GetStringEdString(char *refSection, char *refName) { + static char text[2][1024]; // just incase it's nested + static int index = 0; index ^= 1; trap->SE_GetStringTextString(va("%s_%s", refSection, refName), text[index], sizeof(text[0])); return text[index]; } -int CG_GetClassCount(team_t team,int siegeClass ); +int CG_GetClassCount(team_t team, int siegeClass); int CG_GetTeamNonScoreCount(team_t team); -void CG_SiegeCountCvars( void ) -{ +void CG_SiegeCountCvars(void) { int classGfx[6]; - trap->Cvar_Set( "ui_tm1_cnt",va("%d",CG_GetTeamNonScoreCount(TEAM_RED ))); - trap->Cvar_Set( "ui_tm2_cnt",va("%d",CG_GetTeamNonScoreCount(TEAM_BLUE ))); - trap->Cvar_Set( "ui_tm3_cnt",va("%d",CG_GetTeamNonScoreCount(TEAM_SPECTATOR ))); + trap->Cvar_Set("ui_tm1_cnt", va("%d", CG_GetTeamNonScoreCount(TEAM_RED))); + trap->Cvar_Set("ui_tm2_cnt", va("%d", CG_GetTeamNonScoreCount(TEAM_BLUE))); + trap->Cvar_Set("ui_tm3_cnt", va("%d", CG_GetTeamNonScoreCount(TEAM_SPECTATOR))); // This is because the only way we can match up classes is by the gfx handle. classGfx[0] = trap->R_RegisterShaderNoMip("gfx/mp/c_icon_infantry"); @@ -1545,20 +1436,19 @@ void CG_SiegeCountCvars( void ) classGfx[4] = trap->R_RegisterShaderNoMip("gfx/mp/c_icon_support"); classGfx[5] = trap->R_RegisterShaderNoMip("gfx/mp/c_icon_jedi_general"); - trap->Cvar_Set( "ui_tm1_c0_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[0]))); - trap->Cvar_Set( "ui_tm1_c1_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[1]))); - trap->Cvar_Set( "ui_tm1_c2_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[2]))); - trap->Cvar_Set( "ui_tm1_c3_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[3]))); - trap->Cvar_Set( "ui_tm1_c4_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[4]))); - trap->Cvar_Set( "ui_tm1_c5_cnt",va("%d",CG_GetClassCount(TEAM_RED,classGfx[5]))); - - trap->Cvar_Set( "ui_tm2_c0_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[0]))); - trap->Cvar_Set( "ui_tm2_c1_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[1]))); - trap->Cvar_Set( "ui_tm2_c2_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[2]))); - trap->Cvar_Set( "ui_tm2_c3_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[3]))); - trap->Cvar_Set( "ui_tm2_c4_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[4]))); - trap->Cvar_Set( "ui_tm2_c5_cnt",va("%d",CG_GetClassCount(TEAM_BLUE,classGfx[5]))); + trap->Cvar_Set("ui_tm1_c0_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[0]))); + trap->Cvar_Set("ui_tm1_c1_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[1]))); + trap->Cvar_Set("ui_tm1_c2_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[2]))); + trap->Cvar_Set("ui_tm1_c3_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[3]))); + trap->Cvar_Set("ui_tm1_c4_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[4]))); + trap->Cvar_Set("ui_tm1_c5_cnt", va("%d", CG_GetClassCount(TEAM_RED, classGfx[5]))); + trap->Cvar_Set("ui_tm2_c0_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[0]))); + trap->Cvar_Set("ui_tm2_c1_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[1]))); + trap->Cvar_Set("ui_tm2_c2_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[2]))); + trap->Cvar_Set("ui_tm2_c3_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[3]))); + trap->Cvar_Set("ui_tm2_c4_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[4]))); + trap->Cvar_Set("ui_tm2_c5_cnt", va("%d", CG_GetClassCount(TEAM_BLUE, classGfx[5]))); } /* @@ -1575,7 +1465,7 @@ void CG_BuildSpectatorString(void) { CG_SiegeCountCvars(); for (i = 0; i < MAX_CLIENTS; i++) { - if (cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_SPECTATOR ) { + if (cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_SPECTATOR) { Q_strcat(cg.spectatorList, sizeof(cg.spectatorList), va("%s ", cgs.clientinfo[i].name)); } } @@ -1586,31 +1476,30 @@ void CG_BuildSpectatorString(void) { } } - /* =================== CG_RegisterClients =================== */ -static void CG_RegisterClients( void ) { - int i; +static void CG_RegisterClients(void) { + int i; CG_LoadingClient(cg.clientNum); CG_NewClientInfo(cg.clientNum, qfalse); - for (i=0 ; i= MAX_CONFIGSTRINGS ) { - trap->Error( ERR_DROP, "CG_ConfigString: bad index: %i", index ); +const char *CG_ConfigString(int index) { + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + trap->Error(ERR_DROP, "CG_ConfigString: bad index: %i", index); } - return cgs.gameState.stringData + cgs.gameState.stringOffsets[ index ]; + return cgs.gameState.stringData + cgs.gameState.stringOffsets[index]; } //================================================================== @@ -1637,37 +1526,37 @@ CG_StartMusic ====================== */ -void CG_StartMusic( qboolean bForceStart ) { - char *s; - char parm1[MAX_QPATH], parm2[MAX_QPATH]; +void CG_StartMusic(qboolean bForceStart) { + char *s; + char parm1[MAX_QPATH], parm2[MAX_QPATH]; // start the background music - s = (char *)CG_ConfigString( CS_MUSIC ); - Q_strncpyz( parm1, COM_Parse( (const char **)&s ), sizeof( parm1 ) ); - Q_strncpyz( parm2, COM_Parse( (const char **)&s ), sizeof( parm2 ) ); + s = (char *)CG_ConfigString(CS_MUSIC); + Q_strncpyz(parm1, COM_Parse((const char **)&s), sizeof(parm1)); + Q_strncpyz(parm2, COM_Parse((const char **)&s), sizeof(parm2)); - trap->S_StartBackgroundTrack( parm1, parm2, !bForceStart ); + trap->S_StartBackgroundTrack(parm1, parm2, !bForceStart); } char *CG_GetMenuBuffer(const char *filename) { - int len; - fileHandle_t f; + int len; + fileHandle_t f; static char buf[MAX_MENUFILE]; - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "menu file not found: %s, using default\n", filename ); + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "menu file not found: %s, using default\n", filename); return NULL; } - if ( len >= MAX_MENUFILE ) { - trap->Print( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i\n", filename, len, MAX_MENUFILE ); - trap->FS_Close( f ); + if (len >= MAX_MENUFILE) { + trap->Print(S_COLOR_RED "menu file too large: %s is %i, max allowed is %i\n", filename, len, MAX_MENUFILE); + trap->FS_Close(f); return NULL; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); return buf; } @@ -1686,7 +1575,7 @@ qboolean CG_Asset_Parse(int handle) { return qfalse; } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) return qfalse; @@ -1701,7 +1590,7 @@ qboolean CG_Asset_Parse(int handle) { return qfalse; } -// cgDC.registerFont(token.string, pointSize, &cgDC.Assets.textFont); + // cgDC.registerFont(token.string, pointSize, &cgDC.Assets.textFont); cgDC.Assets.qhMediumFont = cgDC.RegisterFont(token.string); continue; } @@ -1712,7 +1601,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } -// cgDC.registerFont(token.string, pointSize, &cgDC.Assets.smallFont); + // cgDC.registerFont(token.string, pointSize, &cgDC.Assets.smallFont); cgDC.Assets.qhSmallFont = cgDC.RegisterFont(token.string); continue; } @@ -1723,7 +1612,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } -// cgDC.registerFont(token.string, pointSize, &cgDC.Assets.smallFont); + // cgDC.registerFont(token.string, pointSize, &cgDC.Assets.smallFont); cgDC.Assets.qhSmall2Font = cgDC.RegisterFont(token.string); continue; } @@ -1734,7 +1623,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } -// cgDC.registerFont(token.string, pointSize, &cgDC.Assets.bigFont); + // cgDC.registerFont(token.string, pointSize, &cgDC.Assets.bigFont); cgDC.Assets.qhBigFont = cgDC.RegisterFont(token.string); continue; } @@ -1753,7 +1642,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - cgDC.Assets.menuEnterSound = trap->S_RegisterSound( token.string ); + cgDC.Assets.menuEnterSound = trap->S_RegisterSound(token.string); continue; } @@ -1762,7 +1651,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - cgDC.Assets.menuExitSound = trap->S_RegisterSound( token.string ); + cgDC.Assets.menuExitSound = trap->S_RegisterSound(token.string); continue; } @@ -1771,7 +1660,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - cgDC.Assets.itemFocusSound = trap->S_RegisterSound( token.string ); + cgDC.Assets.itemFocusSound = trap->S_RegisterSound(token.string); continue; } @@ -1780,7 +1669,7 @@ qboolean CG_Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - cgDC.Assets.menuBuzzSound = trap->S_RegisterSound( token.string ); + cgDC.Assets.menuBuzzSound = trap->S_RegisterSound(token.string); continue; } @@ -1788,7 +1677,7 @@ qboolean CG_Asset_Parse(int handle) { if (!PC_String_Parse(handle, &cgDC.Assets.cursorStr)) { return qfalse; } - cgDC.Assets.cursor = trap->R_RegisterShaderNoMip( cgDC.Assets.cursorStr); + cgDC.Assets.cursor = trap->R_RegisterShaderNoMip(cgDC.Assets.cursorStr); continue; } @@ -1848,22 +1737,22 @@ void CG_ParseMenu(const char *menuFile) { if (!handle) return; - while ( 1 ) { - if (!trap->PC_ReadToken( handle, &token )) { + while (1) { + if (!trap->PC_ReadToken(handle, &token)) { break; } - //if ( Q_stricmp( token, "{" ) ) { + // if ( Q_stricmp( token, "{" ) ) { // Com_Printf( "Missing { in menu file\n" ); // break; - //} + // } - //if ( menuCount == MAX_MENUS ) { + // if ( menuCount == MAX_MENUS ) { // Com_Printf( "Too many menus!\n" ); // break; - //} + // } - if ( token.string[0] == '}' ) { + if (token.string[0] == '}') { break; } @@ -1875,7 +1764,6 @@ void CG_ParseMenu(const char *menuFile) { } } - if (Q_stricmp(token.string, "menudef") == 0) { // start a new menu Menu_New(handle); @@ -1884,9 +1772,7 @@ void CG_ParseMenu(const char *menuFile) { trap->PC_FreeSource(handle); } - -qboolean CG_Load_Menu(const char **p) -{ +qboolean CG_Load_Menu(const char **p) { char *token; @@ -1896,7 +1782,7 @@ qboolean CG_Load_Menu(const char **p) return qfalse; } - while ( 1 ) { + while (1) { token = COM_ParseExt((const char **)p, qtrue); @@ -1904,7 +1790,7 @@ qboolean CG_Load_Menu(const char **p) return qtrue; } - if ( !token || token[0] == 0 ) { + if (!token || token[0] == 0) { return qfalse; } @@ -1913,11 +1799,7 @@ qboolean CG_Load_Menu(const char **p) return qfalse; } - -static qboolean CG_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) { - return qfalse; -} - +static qboolean CG_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) { return qfalse; } static int CG_FeederCount(float feederID) { int i, count; @@ -1940,9 +1822,8 @@ static int CG_FeederCount(float feederID) { return count; } - void CG_SetScoreSelection(void *p) { - menuDef_t *menu = (menuDef_t*)p; + menuDef_t *menu = (menuDef_t *)p; playerState_t *ps = &cg.snap->ps; int i, red, blue; red = blue = 0; @@ -1962,7 +1843,7 @@ void CG_SetScoreSelection(void *p) { return; } - if ( cgs.gametype >= GT_TEAM ) { + if (cgs.gametype >= GT_TEAM) { int feeder = FEEDER_REDTEAM_LIST; i = red; if (cg.scores[cg.selectedScore].team == TEAM_BLUE) { @@ -1976,9 +1857,9 @@ void CG_SetScoreSelection(void *p) { } // FIXME: might need to cache this info -static clientInfo_t * CG_InfoFromScoreIndex(int index, int team, int *scoreIndex) { +static clientInfo_t *CG_InfoFromScoreIndex(int index, int team, int *scoreIndex) { int i, count; - if ( cgs.gametype >= GT_TEAM ) { + if (cgs.gametype >= GT_TEAM) { count = 0; for (i = 0; i < cg.numScores; i++) { if (cg.scores[i].team == team) { @@ -1991,11 +1872,10 @@ static clientInfo_t * CG_InfoFromScoreIndex(int index, int team, int *scoreIndex } } *scoreIndex = index; - return &cgs.clientinfo[ cg.scores[index].client ]; + return &cgs.clientinfo[cg.scores[index].client]; } -static const char *CG_FeederItemText(float feederID, int index, int column, - qhandle_t *handle1, qhandle_t *handle2, qhandle_t *handle3) { +static const char *CG_FeederItemText(float feederID, int index, int column, qhandle_t *handle1, qhandle_t *handle2, qhandle_t *handle3) { gitem_t *item; int scoreIndex = 0; clientInfo_t *info = NULL; @@ -2015,65 +1895,65 @@ static const char *CG_FeederItemText(float feederID, int index, int column, if (info && info->infoValid) { switch (column) { - case 0: - if ( info->powerups & ( 1 << PW_NEUTRALFLAG ) ) { - item = BG_FindItemForPowerup( PW_NEUTRALFLAG ); - *handle1 = cg_items[ ITEM_INDEX(item) ].icon; - } else if ( info->powerups & ( 1 << PW_REDFLAG ) ) { - item = BG_FindItemForPowerup( PW_REDFLAG ); - *handle1 = cg_items[ ITEM_INDEX(item) ].icon; - } else if ( info->powerups & ( 1 << PW_BLUEFLAG ) ) { - item = BG_FindItemForPowerup( PW_BLUEFLAG ); - *handle1 = cg_items[ ITEM_INDEX(item) ].icon; - } else { - /* - if ( info->botSkill > 0 && info->botSkill <= 5 ) { - *handle1 = cgs.media.botSkillShaders[ info->botSkill - 1 ]; - } else if ( info->handicap < 100 ) { - return va("%i", info->handicap ); - } - */ + case 0: + if (info->powerups & (1 << PW_NEUTRALFLAG)) { + item = BG_FindItemForPowerup(PW_NEUTRALFLAG); + *handle1 = cg_items[ITEM_INDEX(item)].icon; + } else if (info->powerups & (1 << PW_REDFLAG)) { + item = BG_FindItemForPowerup(PW_REDFLAG); + *handle1 = cg_items[ITEM_INDEX(item)].icon; + } else if (info->powerups & (1 << PW_BLUEFLAG)) { + item = BG_FindItemForPowerup(PW_BLUEFLAG); + *handle1 = cg_items[ITEM_INDEX(item)].icon; + } else { + /* + if ( info->botSkill > 0 && info->botSkill <= 5 ) { + *handle1 = cgs.media.botSkillShaders[ info->botSkill - 1 ]; + } else if ( info->handicap < 100 ) { + return va("%i", info->handicap ); } + */ + } break; - case 1: - if (team == -1) { - return ""; + case 1: + if (team == -1) { + return ""; + } else { + *handle1 = CG_StatusHandle(info->teamTask); + } + break; + case 2: + if (cg.snap->ps.stats[STAT_CLIENTS_READY] & (1 << sp->client)) { + return "Ready"; + } + if (team == -1) { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + return va("%i/%i", info->wins, info->losses); + } else if (info->infoValid && info->team == TEAM_SPECTATOR) { + return "Spectator"; } else { - *handle1 = CG_StatusHandle(info->teamTask); - } - break; - case 2: - if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << sp->client ) ) { - return "Ready"; + return ""; } - if (team == -1) { - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { - return va("%i/%i", info->wins, info->losses); - } else if (info->infoValid && info->team == TEAM_SPECTATOR ) { - return "Spectator"; - } else { - return ""; - } - } else { - if (info->teamLeader) { - return "Leader"; - } + } else { + if (info->teamLeader) { + return "Leader"; } + } break; - case 3: - return info->name; + case 3: + return info->name; break; - case 4: - return va("%i", info->score); + case 4: + return va("%i", info->score); break; - case 5: - return va("%4i", sp->time); + case 5: + return va("%4i", sp->time); break; - case 6: - if ( sp->ping == -1 ) { - return "connecting"; - } - return va("%4i", sp->ping); + case 6: + if (sp->ping == -1) { + return "connecting"; + } + return va("%4i", sp->ping); break; } } @@ -2081,12 +1961,10 @@ static const char *CG_FeederItemText(float feederID, int index, int column, return ""; } -static qhandle_t CG_FeederItemImage(float feederID, int index) { - return 0; -} +static qhandle_t CG_FeederItemImage(float feederID, int index) { return 0; } static qboolean CG_FeederSelection(float feederID, int index, itemDef_t *item) { - if ( cgs.gametype >= GT_TEAM ) { + if (cgs.gametype >= GT_TEAM) { int i, count; int team = (feederID == FEEDER_REDTEAM_LIST) ? TEAM_RED : TEAM_BLUE; count = 0; @@ -2118,40 +1996,34 @@ void CG_Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const static int CG_OwnerDrawWidth(int ownerDraw, float scale) { switch (ownerDraw) { - case CG_GAME_TYPE: - return CG_Text_Width(BG_GetGametypeString( cgs.gametype ), scale, FONT_MEDIUM); - case CG_GAME_STATUS: - return CG_Text_Width(CG_GetGameStatusText(), scale, FONT_MEDIUM); - break; - case CG_KILLER: - return CG_Text_Width(CG_GetKillerText(), scale, FONT_MEDIUM); - break; - case CG_RED_NAME: - return CG_Text_Width(DEFAULT_REDTEAM_NAME/*cg_redTeamName.string*/, scale, FONT_MEDIUM); - break; - case CG_BLUE_NAME: - return CG_Text_Width(DEFAULT_BLUETEAM_NAME/*cg_blueTeamName.string*/, scale, FONT_MEDIUM); - break; + case CG_GAME_TYPE: + return CG_Text_Width(BG_GetGametypeString(cgs.gametype), scale, FONT_MEDIUM); + case CG_GAME_STATUS: + return CG_Text_Width(CG_GetGameStatusText(), scale, FONT_MEDIUM); + break; + case CG_KILLER: + return CG_Text_Width(CG_GetKillerText(), scale, FONT_MEDIUM); + break; + case CG_RED_NAME: + return CG_Text_Width(DEFAULT_REDTEAM_NAME /*cg_redTeamName.string*/, scale, FONT_MEDIUM); + break; + case CG_BLUE_NAME: + return CG_Text_Width(DEFAULT_BLUETEAM_NAME /*cg_blueTeamName.string*/, scale, FONT_MEDIUM); + break; } return 0; } -static int CG_PlayCinematic(const char *name, float x, float y, float w, float h) { - return trap->CIN_PlayCinematic(name, x, y, w, h, CIN_loop); -} +static int CG_PlayCinematic(const char *name, float x, float y, float w, float h) { return trap->CIN_PlayCinematic(name, x, y, w, h, CIN_loop); } -static void CG_StopCinematic(int handle) { - trap->CIN_StopCinematic(handle); -} +static void CG_StopCinematic(int handle) { trap->CIN_StopCinematic(handle); } static void CG_DrawCinematic(int handle, float x, float y, float w, float h) { trap->CIN_SetExtents(handle, x, y, w, h); trap->CIN_DrawCinematic(handle); } -static void CG_RunCinematicFrame(int handle) { - trap->CIN_RunCinematic(handle); -} +static void CG_RunCinematicFrame(int handle) { trap->CIN_RunCinematic(handle); } /* ================= @@ -2159,70 +2031,59 @@ CG_LoadMenus(); ================= */ -void CG_LoadMenus(const char *menuFile) -{ - const char *token; - const char *p; - int len; - fileHandle_t f; +void CG_LoadMenus(const char *menuFile) { + const char *token; + const char *p; + int len; + fileHandle_t f; static char buf[MAX_MENUDEFFILE]; - len = trap->FS_Open( menuFile, &f, FS_READ ); + len = trap->FS_Open(menuFile, &f, FS_READ); - if ( !f ) - { - if( Q_isanumber( menuFile ) ) // cg_hudFiles 1 - trap->Print( S_COLOR_GREEN "hud menu file skipped, using default\n" ); + if (!f) { + if (Q_isanumber(menuFile)) // cg_hudFiles 1 + trap->Print(S_COLOR_GREEN "hud menu file skipped, using default\n"); else - trap->Print( S_COLOR_YELLOW "hud menu file not found: %s, using default\n", menuFile ); + trap->Print(S_COLOR_YELLOW "hud menu file not found: %s, using default\n", menuFile); - len = trap->FS_Open( "ui/jahud.txt", &f, FS_READ ); - if (!f) - { - trap->Error( ERR_DROP, S_COLOR_RED "default hud menu file not found: ui/jahud.txt, unable to continue!" ); + len = trap->FS_Open("ui/jahud.txt", &f, FS_READ); + if (!f) { + trap->Error(ERR_DROP, S_COLOR_RED "default hud menu file not found: ui/jahud.txt, unable to continue!"); } } - if ( len >= MAX_MENUDEFFILE ) - { - trap->FS_Close( f ); - trap->Error( ERR_DROP, S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE ); + if (len >= MAX_MENUDEFFILE) { + trap->FS_Close(f); + trap->Error(ERR_DROP, S_COLOR_RED "menu file too large: %s is %i, max allowed is %i", menuFile, len, MAX_MENUDEFFILE); } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); p = buf; - COM_BeginParseSession ("CG_LoadMenus"); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if( !token || token[0] == 0 || token[0] == '}') - { + COM_BeginParseSession("CG_LoadMenus"); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token || token[0] == 0 || token[0] == '}') { break; } - if ( Q_stricmp( token, "}" ) == 0 ) - { + if (Q_stricmp(token, "}") == 0) { break; } - if (Q_stricmp(token, "loadmenu") == 0) - { - if (CG_Load_Menu(&p)) - { + if (Q_stricmp(token, "loadmenu") == 0) { + if (CG_Load_Menu(&p)) { continue; - } - else - { + } else { break; } } } - //Com_Printf("UI menu load time = %d milli seconds\n", cgi_Milliseconds() - start); + // Com_Printf("UI menu load time = %d milli seconds\n", cgi_Milliseconds() - start); } /* @@ -2231,106 +2092,102 @@ CG_LoadHudMenu(); ================= */ -void CG_LoadHudMenu() -{ +void CG_LoadHudMenu() { const char *hudSet; - cgDC.registerShaderNoMip = trap->R_RegisterShaderNoMip; - cgDC.setColor = trap->R_SetColor; - cgDC.drawHandlePic = &CG_DrawPic; - cgDC.drawStretchPic = trap->R_DrawStretchPic; - cgDC.drawText = &CG_Text_Paint; - cgDC.textWidth = &CG_Text_Width; - cgDC.textHeight = &CG_Text_Height; - cgDC.registerModel = trap->R_RegisterModel; - cgDC.modelBounds = trap->R_ModelBounds; - cgDC.fillRect = &CG_FillRect; - cgDC.drawRect = &CG_DrawRect; - cgDC.drawSides = &CG_DrawSides; - cgDC.drawTopBottom = &CG_DrawTopBottom; - cgDC.clearScene = trap->R_ClearScene; - cgDC.addRefEntityToScene = trap->R_AddRefEntityToScene; - cgDC.renderScene = trap->R_RenderScene; - cgDC.RegisterFont = trap->R_RegisterFont; - cgDC.Font_StrLenPixels = trap->R_Font_StrLenPixels; - cgDC.Font_StrLenChars = trap->R_Font_StrLenChars; - cgDC.Font_HeightPixels = trap->R_Font_HeightPixels; - cgDC.Font_DrawString = trap->R_Font_DrawString; - cgDC.Language_IsAsian = trap->R_Language_IsAsian; - cgDC.Language_UsesSpaces = trap->R_Language_UsesSpaces; - cgDC.AnyLanguage_ReadCharFromString = trap->R_AnyLanguage_ReadCharFromString; - cgDC.ownerDrawItem = &CG_OwnerDraw; - cgDC.getValue = &CG_GetValue; - cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; - cgDC.runScript = &CG_RunMenuScript; - cgDC.deferScript = &CG_DeferMenuScript; - cgDC.getTeamColor = &CG_GetTeamColor; - cgDC.setCVar = trap->Cvar_Set; - cgDC.getCVarString = trap->Cvar_VariableStringBuffer; - cgDC.getCVarValue = CG_Cvar_Get; - cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; - //cgDC.setOverstrikeMode = &trap->Key_SetOverstrikeMode; - //cgDC.getOverstrikeMode = &trap->Key_GetOverstrikeMode; - cgDC.startLocalSound = trap->S_StartLocalSound; - cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; - cgDC.feederCount = &CG_FeederCount; - cgDC.feederItemImage = &CG_FeederItemImage; - cgDC.feederItemText = &CG_FeederItemText; - cgDC.feederSelection = &CG_FeederSelection; - //cgDC.setBinding = &trap->Key_SetBinding; - //cgDC.getBindingBuf = &trap->Key_GetBindingBuf; - //cgDC.keynumToStringBuf = &trap->Key_KeynumToStringBuf; - //cgDC.executeText = &trap->Cmd_ExecuteText; - cgDC.Error = Com_Error; - cgDC.Print = Com_Printf; - cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; - //cgDC.Pause = &CG_Pause; - cgDC.registerSound = trap->S_RegisterSound; - cgDC.startBackgroundTrack = trap->S_StartBackgroundTrack; - cgDC.stopBackgroundTrack = trap->S_StopBackgroundTrack; - cgDC.playCinematic = &CG_PlayCinematic; - cgDC.stopCinematic = &CG_StopCinematic; - cgDC.drawCinematic = &CG_DrawCinematic; - cgDC.runCinematicFrame = &CG_RunCinematicFrame; - cgDC.ext.Font_StrLenPixels = trap->ext.R_Font_StrLenPixels; - + cgDC.registerShaderNoMip = trap->R_RegisterShaderNoMip; + cgDC.setColor = trap->R_SetColor; + cgDC.drawHandlePic = &CG_DrawPic; + cgDC.drawStretchPic = trap->R_DrawStretchPic; + cgDC.drawText = &CG_Text_Paint; + cgDC.textWidth = &CG_Text_Width; + cgDC.textHeight = &CG_Text_Height; + cgDC.registerModel = trap->R_RegisterModel; + cgDC.modelBounds = trap->R_ModelBounds; + cgDC.fillRect = &CG_FillRect; + cgDC.drawRect = &CG_DrawRect; + cgDC.drawSides = &CG_DrawSides; + cgDC.drawTopBottom = &CG_DrawTopBottom; + cgDC.clearScene = trap->R_ClearScene; + cgDC.addRefEntityToScene = trap->R_AddRefEntityToScene; + cgDC.renderScene = trap->R_RenderScene; + cgDC.RegisterFont = trap->R_RegisterFont; + cgDC.Font_StrLenPixels = trap->R_Font_StrLenPixels; + cgDC.Font_StrLenChars = trap->R_Font_StrLenChars; + cgDC.Font_HeightPixels = trap->R_Font_HeightPixels; + cgDC.Font_DrawString = trap->R_Font_DrawString; + cgDC.Language_IsAsian = trap->R_Language_IsAsian; + cgDC.Language_UsesSpaces = trap->R_Language_UsesSpaces; + cgDC.AnyLanguage_ReadCharFromString = trap->R_AnyLanguage_ReadCharFromString; + cgDC.ownerDrawItem = &CG_OwnerDraw; + cgDC.getValue = &CG_GetValue; + cgDC.ownerDrawVisible = &CG_OwnerDrawVisible; + cgDC.runScript = &CG_RunMenuScript; + cgDC.deferScript = &CG_DeferMenuScript; + cgDC.getTeamColor = &CG_GetTeamColor; + cgDC.setCVar = trap->Cvar_Set; + cgDC.getCVarString = trap->Cvar_VariableStringBuffer; + cgDC.getCVarValue = CG_Cvar_Get; + cgDC.drawTextWithCursor = &CG_Text_PaintWithCursor; + // cgDC.setOverstrikeMode = &trap->Key_SetOverstrikeMode; + // cgDC.getOverstrikeMode = &trap->Key_GetOverstrikeMode; + cgDC.startLocalSound = trap->S_StartLocalSound; + cgDC.ownerDrawHandleKey = &CG_OwnerDrawHandleKey; + cgDC.feederCount = &CG_FeederCount; + cgDC.feederItemImage = &CG_FeederItemImage; + cgDC.feederItemText = &CG_FeederItemText; + cgDC.feederSelection = &CG_FeederSelection; + // cgDC.setBinding = &trap->Key_SetBinding; + // cgDC.getBindingBuf = &trap->Key_GetBindingBuf; + // cgDC.keynumToStringBuf = &trap->Key_KeynumToStringBuf; + // cgDC.executeText = &trap->Cmd_ExecuteText; + cgDC.Error = Com_Error; + cgDC.Print = Com_Printf; + cgDC.ownerDrawWidth = &CG_OwnerDrawWidth; + // cgDC.Pause = &CG_Pause; + cgDC.registerSound = trap->S_RegisterSound; + cgDC.startBackgroundTrack = trap->S_StartBackgroundTrack; + cgDC.stopBackgroundTrack = trap->S_StopBackgroundTrack; + cgDC.playCinematic = &CG_PlayCinematic; + cgDC.stopCinematic = &CG_StopCinematic; + cgDC.drawCinematic = &CG_DrawCinematic; + cgDC.runCinematicFrame = &CG_RunCinematicFrame; + cgDC.ext.Font_StrLenPixels = trap->ext.R_Font_StrLenPixels; Init_Display(&cgDC); Menu_Reset(); hudSet = cg_hudFiles.string; - if (hudSet[0] == '\0') - { + if (hudSet[0] == '\0') { hudSet = "ui/jahud.txt"; } CG_LoadMenus(hudSet); - } void CG_AssetCache() { - //if (Assets.textFont == NULL) { - // trap->R_RegisterFont("fonts/arial.ttf", 72, &Assets.textFont); - //} - //Com_Printf("Menu Size: %i bytes\n", sizeof(Menus)); - cgDC.Assets.gradientBar = trap->R_RegisterShaderNoMip( ASSET_GRADIENTBAR ); - cgDC.Assets.fxBasePic = trap->R_RegisterShaderNoMip( ART_FX_BASE ); - cgDC.Assets.fxPic[0] = trap->R_RegisterShaderNoMip( ART_FX_RED ); - cgDC.Assets.fxPic[1] = trap->R_RegisterShaderNoMip( ART_FX_YELLOW ); - cgDC.Assets.fxPic[2] = trap->R_RegisterShaderNoMip( ART_FX_GREEN ); - cgDC.Assets.fxPic[3] = trap->R_RegisterShaderNoMip( ART_FX_TEAL ); - cgDC.Assets.fxPic[4] = trap->R_RegisterShaderNoMip( ART_FX_BLUE ); - cgDC.Assets.fxPic[5] = trap->R_RegisterShaderNoMip( ART_FX_CYAN ); - cgDC.Assets.fxPic[6] = trap->R_RegisterShaderNoMip( ART_FX_WHITE ); - cgDC.Assets.scrollBar = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR ); - cgDC.Assets.scrollBarArrowDown = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWDOWN ); - cgDC.Assets.scrollBarArrowUp = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWUP ); - cgDC.Assets.scrollBarArrowLeft = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWLEFT ); - cgDC.Assets.scrollBarArrowRight = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWRIGHT ); - cgDC.Assets.scrollBarThumb = trap->R_RegisterShaderNoMip( ASSET_SCROLL_THUMB ); - cgDC.Assets.sliderBar = trap->R_RegisterShaderNoMip( ASSET_SLIDER_BAR ); - cgDC.Assets.sliderThumb = trap->R_RegisterShaderNoMip( ASSET_SLIDER_THUMB ); + // if (Assets.textFont == NULL) { + // trap->R_RegisterFont("fonts/arial.ttf", 72, &Assets.textFont); + // } + // Com_Printf("Menu Size: %i bytes\n", sizeof(Menus)); + cgDC.Assets.gradientBar = trap->R_RegisterShaderNoMip(ASSET_GRADIENTBAR); + cgDC.Assets.fxBasePic = trap->R_RegisterShaderNoMip(ART_FX_BASE); + cgDC.Assets.fxPic[0] = trap->R_RegisterShaderNoMip(ART_FX_RED); + cgDC.Assets.fxPic[1] = trap->R_RegisterShaderNoMip(ART_FX_YELLOW); + cgDC.Assets.fxPic[2] = trap->R_RegisterShaderNoMip(ART_FX_GREEN); + cgDC.Assets.fxPic[3] = trap->R_RegisterShaderNoMip(ART_FX_TEAL); + cgDC.Assets.fxPic[4] = trap->R_RegisterShaderNoMip(ART_FX_BLUE); + cgDC.Assets.fxPic[5] = trap->R_RegisterShaderNoMip(ART_FX_CYAN); + cgDC.Assets.fxPic[6] = trap->R_RegisterShaderNoMip(ART_FX_WHITE); + cgDC.Assets.scrollBar = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR); + cgDC.Assets.scrollBarArrowDown = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWDOWN); + cgDC.Assets.scrollBarArrowUp = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWUP); + cgDC.Assets.scrollBarArrowLeft = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWLEFT); + cgDC.Assets.scrollBarArrowRight = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWRIGHT); + cgDC.Assets.scrollBarThumb = trap->R_RegisterShaderNoMip(ASSET_SCROLL_THUMB); + cgDC.Assets.sliderBar = trap->R_RegisterShaderNoMip(ASSET_SLIDER_BAR); + cgDC.Assets.sliderThumb = trap->R_RegisterShaderNoMip(ASSET_SLIDER_THUMB); } /* @@ -2341,36 +2198,23 @@ Ghoul2 Insert Start */ // initialise the cg_entities structure - take into account the ghoul2 stl stuff in the active snap shots -void CG_Init_CG(void) -{ - memset( &cg, 0, sizeof(cg)); -} +void CG_Init_CG(void) { memset(&cg, 0, sizeof(cg)); } // initialise the cg_entities structure - take into account the ghoul2 stl stuff -void CG_Init_CGents(void) -{ - memset(&cg_entities, 0, sizeof(cg_entities)); -} +void CG_Init_CGents(void) { memset(&cg_entities, 0, sizeof(cg_entities)); } +void CG_InitItems(void) { memset(cg_items, 0, sizeof(cg_items)); } -void CG_InitItems(void) -{ - memset( cg_items, 0, sizeof( cg_items ) ); -} - -void CG_TransitionPermanent(void) -{ - centity_t *cent = cg_entities; - int i; +void CG_TransitionPermanent(void) { + centity_t *cent = cg_entities; + int i; cg_numpermanents = 0; - for(i=0;iGetDefaultState(i, ¢->currentState)) - { + for (i = 0; i < MAX_GENTITIES; i++, cent++) { + if (trap->GetDefaultState(i, ¢->currentState)) { cent->nextState = cent->currentState; - VectorCopy (cent->currentState.origin, cent->lerpOrigin); - VectorCopy (cent->currentState.angles, cent->lerpAngles); + VectorCopy(cent->currentState.origin, cent->lerpOrigin); + VectorCopy(cent->currentState.angles, cent->lerpAngles); cent->currentValid = qtrue; cg_permanents[cg_numpermanents++] = cent; @@ -2382,11 +2226,11 @@ void CG_TransitionPermanent(void) Ghoul2 Insert End */ -extern playerState_t *cgSendPS[MAX_GENTITIES]; //is not MAX_CLIENTS because NPCs exceed MAX_CLIENTS +extern playerState_t *cgSendPS[MAX_GENTITIES]; // is not MAX_CLIENTS because NPCs exceed MAX_CLIENTS void CG_PmoveClientPointerUpdate(); -void WP_SaberLoadParms( void ); -void BG_VehicleLoadParms( void ); +void WP_SaberLoadParms(void); +void BG_VehicleLoadParms(void); /* ================= @@ -2396,44 +2240,43 @@ Called after every level change or subsystem restart Will perform callbacks to make the loading info screen update. ================= */ -void CG_Init( int serverMessageNum, int serverCommandSequence, int clientNum ) -{ +void CG_Init(int serverMessageNum, int serverCommandSequence, int clientNum) { static gitem_t *item; char buf[64]; - const char *s; + const char *s; int i = 0; - Rand_Init( trap->Milliseconds() ); + Rand_Init(trap->Milliseconds()); - BG_InitAnimsets(); //clear it out + BG_InitAnimsets(); // clear it out - trap->RegisterSharedMemory( cg.sharedBuffer.raw ); + trap->RegisterSharedMemory(cg.sharedBuffer.raw); - //Load external vehicle data + // Load external vehicle data BG_VehicleLoadParms(); // clear everything -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ -// memset( cg_entities, 0, sizeof( cg_entities ) ); + // memset( cg_entities, 0, sizeof( cg_entities ) ); CG_Init_CGents(); -// this is a No-No now we have stl vector classes in here. -// memset( &cg, 0, sizeof( cg ) ); + // this is a No-No now we have stl vector classes in here. + // memset( &cg, 0, sizeof( cg ) ); CG_Init_CG(); CG_InitItems(); - //create the global jetpack instance + // create the global jetpack instance CG_InitJetpackGhoul2(); CG_PmoveClientPointerUpdate(); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - //Load sabers.cfg data + // Load sabers.cfg data WP_SaberLoadParms(); // this is kinda dumb as well, but I need to pre-load some fonts in order to have the text available @@ -2441,78 +2284,68 @@ Ghoul2 Insert End // defaults, then let the menu asset parser (which actually specifies the ingame fonts) load over them // if desired during parse. Dunno how legal it is to store in these cgDC things, but it causes no harm // and even if/when they get overwritten they'll be legalised by the menu asset parser :-) -// CG_LoadFonts(); - cgDC.Assets.qhSmallFont = trap->R_RegisterFont("ocr_a"); + // CG_LoadFonts(); + cgDC.Assets.qhSmallFont = trap->R_RegisterFont("ocr_a"); cgDC.Assets.qhMediumFont = trap->R_RegisterFont("ergoec"); cgDC.Assets.qhBigFont = cgDC.Assets.qhMediumFont; - memset( &cgs, 0, sizeof( cgs ) ); - memset( cg_weapons, 0, sizeof(cg_weapons) ); + memset(&cgs, 0, sizeof(cgs)); + memset(cg_weapons, 0, sizeof(cg_weapons)); cg.clientNum = clientNum; cgs.processedSnapshotNum = serverMessageNum; cgs.serverCommandSequence = serverCommandSequence; - cg.loadLCARSStage = 0; + cg.loadLCARSStage = 0; cg.itemSelect = -1; cg.forceSelect = -1; // load a few needed things before we do any screen updates - cgs.media.charsetShader = trap->R_RegisterShaderNoMip( "gfx/2d/charsgrid_med" ); - cgs.media.whiteShader = trap->R_RegisterShader( "white" ); + cgs.media.charsetShader = trap->R_RegisterShaderNoMip("gfx/2d/charsgrid_med"); + cgs.media.whiteShader = trap->R_RegisterShader("white"); - cgs.media.loadBarLED = trap->R_RegisterShaderNoMip( "gfx/hud/load_tick" ); - cgs.media.loadBarLEDCap = trap->R_RegisterShaderNoMip( "gfx/hud/load_tick_cap" ); - cgs.media.loadBarLEDSurround= trap->R_RegisterShaderNoMip( "gfx/hud/mp_levelload" ); + cgs.media.loadBarLED = trap->R_RegisterShaderNoMip("gfx/hud/load_tick"); + cgs.media.loadBarLEDCap = trap->R_RegisterShaderNoMip("gfx/hud/load_tick_cap"); + cgs.media.loadBarLEDSurround = trap->R_RegisterShaderNoMip("gfx/hud/mp_levelload"); // Force HUD set up cg.forceHUDActive = qtrue; cg.forceHUDTotalFlashTime = 0; cg.forceHUDNextFlashTime = 0; - i = WP_NONE+1; - while (i <= LAST_USEABLE_WEAPON) - { + i = WP_NONE + 1; + while (i <= LAST_USEABLE_WEAPON) { item = BG_FindItemForWeapon(i); - if (item && item->icon && item->icon[0]) - { + if (item && item->icon && item->icon[0]) { cgs.media.weaponIcons[i] = trap->R_RegisterShaderNoMip(item->icon); cgs.media.weaponIcons_NA[i] = trap->R_RegisterShaderNoMip(va("%s_na", item->icon)); - } - else - { //make sure it is zero'd (default shader) + } else { // make sure it is zero'd (default shader) cgs.media.weaponIcons[i] = 0; cgs.media.weaponIcons_NA[i] = 0; } i++; } trap->Cvar_VariableStringBuffer("com_buildscript", buf, sizeof(buf)); - if (atoi(buf)) - { + if (atoi(buf)) { trap->R_RegisterShaderNoMip("gfx/hud/w_icon_saberstaff"); trap->R_RegisterShaderNoMip("gfx/hud/w_icon_duallightsaber"); } i = 0; // HUD artwork for cycling inventory,weapons and force powers - cgs.media.weaponIconBackground = trap->R_RegisterShaderNoMip( "gfx/hud/background"); - cgs.media.forceIconBackground = trap->R_RegisterShaderNoMip( "gfx/hud/background_f"); - cgs.media.inventoryIconBackground = trap->R_RegisterShaderNoMip( "gfx/hud/background_i"); - - //rww - precache holdable item icons here - while (i < bg_numItems) - { - if (bg_itemlist[i].giType == IT_HOLDABLE) - { - if (bg_itemlist[i].icon) - { + cgs.media.weaponIconBackground = trap->R_RegisterShaderNoMip("gfx/hud/background"); + cgs.media.forceIconBackground = trap->R_RegisterShaderNoMip("gfx/hud/background_f"); + cgs.media.inventoryIconBackground = trap->R_RegisterShaderNoMip("gfx/hud/background_i"); + + // rww - precache holdable item icons here + while (i < bg_numItems) { + if (bg_itemlist[i].giType == IT_HOLDABLE) { + if (bg_itemlist[i].icon) { cgs.media.invenIcons[bg_itemlist[i].giTag] = trap->R_RegisterShaderNoMip(bg_itemlist[i].icon); - } - else - { + } else { cgs.media.invenIcons[bg_itemlist[i].giTag] = 0; } } @@ -2520,19 +2353,17 @@ Ghoul2 Insert End i++; } - //rww - precache force power icons here + // rww - precache force power icons here i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { cgs.media.forcePowerIcons[i] = trap->R_RegisterShaderNoMip(HolocronIcons[i]); i++; } cgs.media.rageRecShader = trap->R_RegisterShaderNoMip("gfx/mp/f_icon_ragerec"); - - //body decal shaders -rww + // body decal shaders -rww cgs.media.bdecal_bodyburn1 = trap->R_RegisterShader("gfx/damage/bodyburnmark1"); cgs.media.bdecal_saberglow = trap->R_RegisterShader("gfx/damage/saberglowmark"); cgs.media.bdecal_burn1 = trap->R_RegisterShader("gfx/damage/bodybigburnmark1"); @@ -2551,52 +2382,52 @@ Ghoul2 Insert End // old servers // get the rendering configuration from the client system - trap->GetGlconfig( &cgs.glconfig ); + trap->GetGlconfig(&cgs.glconfig); cgs.screenXScale = cgs.glconfig.vidWidth / 640.0; cgs.screenYScale = cgs.glconfig.vidHeight / 480.0; // get the gamestate from the client system - trap->GetGameState( &cgs.gameState ); + trap->GetGameState(&cgs.gameState); - CG_TransitionPermanent(); //rwwRMG - added + CG_TransitionPermanent(); // rwwRMG - added // check version - s = CG_ConfigString( CS_GAME_VERSION ); - if ( strcmp( s, GAME_VERSION ) ) { - trap->Error( ERR_DROP, "Client/Server game mismatch: %s/%s", GAME_VERSION, s ); + s = CG_ConfigString(CS_GAME_VERSION); + if (strcmp(s, GAME_VERSION)) { + trap->Error(ERR_DROP, "Client/Server game mismatch: %s/%s", GAME_VERSION, s); } - s = CG_ConfigString( CS_LEVEL_START_TIME ); - cgs.levelStartTime = atoi( s ); + s = CG_ConfigString(CS_LEVEL_START_TIME); + cgs.levelStartTime = atoi(s); CG_ParseServerinfo(); // load the new map -// CG_LoadingString( "collision map" ); + // CG_LoadingString( "collision map" ); - trap->CM_LoadMap( cgs.mapname, qfalse ); + trap->CM_LoadMap(cgs.mapname, qfalse); String_Init(); - cg.loading = qtrue; // force players to load instead of defer + cg.loading = qtrue; // force players to load instead of defer - //make sure saber data is loaded before this! (so we can precache the appropriate hilts) + // make sure saber data is loaded before this! (so we can precache the appropriate hilts) CG_InitSiegeMode(); CG_RegisterSounds(); -// CG_LoadingString( "graphics" ); + // CG_LoadingString( "graphics" ); CG_RegisterGraphics(); -// CG_LoadingString( "clients" ); + // CG_LoadingString( "clients" ); - CG_RegisterClients(); // if low on memory, some clients will be deferred + CG_RegisterClients(); // if low on memory, some clients will be deferred CG_AssetCache(); - CG_LoadHudMenu(); // load new hud stuff + CG_LoadHudMenu(); // load new hud stuff - cg.loading = qfalse; // future players will be deferred + cg.loading = qfalse; // future players will be deferred CG_InitLocalEntities(); @@ -2610,14 +2441,14 @@ Ghoul2 Insert End CG_StartMusic(qfalse); -// CG_LoadingString( "Clearing light styles" ); + // CG_LoadingString( "Clearing light styles" ); CG_ClearLightStyles(); -// CG_LoadingString( "Creating automap data" ); - //init automap + // CG_LoadingString( "Creating automap data" ); + // init automap trap->R_InitializeWireframeAutomap(); - CG_LoadingString( "" ); + CG_LoadingString(""); CG_ShaderStateChanged(); @@ -2628,45 +2459,38 @@ Ghoul2 Insert End CG_ParseEntitiesFromString(); } -//makes sure returned string is in localized format -const char *CG_GetLocationString(const char *loc) -{ - static char text[1024]={0}; +// makes sure returned string is in localized format +const char *CG_GetLocationString(const char *loc) { + static char text[1024] = {0}; - if (!loc || loc[0] != '@') - { //just a raw string + if (!loc || loc[0] != '@') { // just a raw string return loc; } - trap->SE_GetStringTextString(loc+1, text, sizeof(text)); + trap->SE_GetStringTextString(loc + 1, text, sizeof(text)); return text; } -//clean up all the ghoul2 allocations, the nice and non-hackly way -rww +// clean up all the ghoul2 allocations, the nice and non-hackly way -rww void CG_KillCEntityG2(int entNum); -void CG_DestroyAllGhoul2(void) -{ +void CG_DestroyAllGhoul2(void) { int i = 0; int j; -// Com_Printf("... CGameside GHOUL2 Cleanup\n"); - while (i < MAX_GENTITIES) - { //free all dynamically allocated npc client info structs and ghoul2 instances + // Com_Printf("... CGameside GHOUL2 Cleanup\n"); + while (i < MAX_GENTITIES) { // free all dynamically allocated npc client info structs and ghoul2 instances CG_KillCEntityG2(i); i++; } - //Clean the weapon instances + // Clean the weapon instances CG_ShutDownG2Weapons(); i = 0; - while (i < MAX_ITEMS) - { //and now for items + while (i < MAX_ITEMS) { // and now for items j = 0; - while (j < MAX_ITEM_MODELS) - { - if (cg_items[i].g2Models[j] && trap->G2_HaveWeGhoul2Models(cg_items[i].g2Models[j])) - { + while (j < MAX_ITEM_MODELS) { + if (cg_items[i].g2Models[j] && trap->G2_HaveWeGhoul2Models(cg_items[i].g2Models[j])) { trap->G2API_CleanGhoul2Models(&cg_items[i].g2Models[j]); cg_items[i].g2Models[j] = NULL; } @@ -2675,7 +2499,7 @@ void CG_DestroyAllGhoul2(void) i++; } - //Clean the global jetpack instance + // Clean the global jetpack instance CG_CleanJetpackGhoul2(); } @@ -2686,21 +2510,20 @@ CG_Shutdown Called before every level change or subsystem restart ================= */ -void CG_Shutdown( void ) -{ - BG_ClearAnimsets(); //free all dynamic allocations made through the engine +void CG_Shutdown(void) { + BG_ClearAnimsets(); // free all dynamic allocations made through the engine - CG_DestroyAllGhoul2(); + CG_DestroyAllGhoul2(); -// Com_Printf("... FX System Cleanup\n"); + // Com_Printf("... FX System Cleanup\n"); trap->FX_FreeSystem(); trap->ROFF_Clean(); - //reset weather + // reset weather trap->R_WorldEffectCommand("die"); UI_CleanupGhoul2(); - //If there was any ghoul2 stuff in our side of the shared ui code, then remove it now. + // If there was any ghoul2 stuff in our side of the shared ui code, then remove it now. // some mods may need to do cleanup work here, // like closing files or archiving session data @@ -2711,43 +2534,36 @@ void CG_Shutdown( void ) CG_NextForcePower_f =============== */ -void CG_NextForcePower_f( void ) -{ +void CG_NextForcePower_f(void) { int current; usercmd_t cmd; - if ( !cg.snap ) - { + if (!cg.snap) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } current = trap->GetCurrentCmdNumber(); trap->GetUserCmd(current, &cmd); - if ((cmd.buttons & BUTTON_USE) || CG_NoUseableForce()) - { + if ((cmd.buttons & BUTTON_USE) || CG_NoUseableForce()) { CG_NextInventory_f(); return; } - if (cg.snap->ps.pm_flags & PMF_FOLLOW) - { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } -// BG_CycleForce(&cg.snap->ps, 1); - if (cg.forceSelect != -1) - { + // BG_CycleForce(&cg.snap->ps, 1); + if (cg.forceSelect != -1) { cg.snap->ps.fd.forcePowerSelected = cg.forceSelect; } BG_CycleForce(&cg.snap->ps, 1); - if (cg.snap->ps.fd.forcePowersKnown & (1 << cg.snap->ps.fd.forcePowerSelected)) - { + if (cg.snap->ps.fd.forcePowersKnown & (1 << cg.snap->ps.fd.forcePowerSelected)) { cg.forceSelect = cg.snap->ps.fd.forcePowerSelected; cg.forceSelectTime = cg.time; } @@ -2758,119 +2574,100 @@ void CG_NextForcePower_f( void ) CG_PrevForcePower_f =============== */ -void CG_PrevForcePower_f( void ) -{ +void CG_PrevForcePower_f(void) { int current; usercmd_t cmd; - if ( !cg.snap ) - { + if (!cg.snap) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } current = trap->GetCurrentCmdNumber(); trap->GetUserCmd(current, &cmd); - if ((cmd.buttons & BUTTON_USE) || CG_NoUseableForce()) - { + if ((cmd.buttons & BUTTON_USE) || CG_NoUseableForce()) { CG_PrevInventory_f(); return; } - if (cg.snap->ps.pm_flags & PMF_FOLLOW) - { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } -// BG_CycleForce(&cg.snap->ps, -1); - if (cg.forceSelect != -1) - { + // BG_CycleForce(&cg.snap->ps, -1); + if (cg.forceSelect != -1) { cg.snap->ps.fd.forcePowerSelected = cg.forceSelect; } BG_CycleForce(&cg.snap->ps, -1); - if (cg.snap->ps.fd.forcePowersKnown & (1 << cg.snap->ps.fd.forcePowerSelected)) - { + if (cg.snap->ps.fd.forcePowersKnown & (1 << cg.snap->ps.fd.forcePowerSelected)) { cg.forceSelect = cg.snap->ps.fd.forcePowerSelected; cg.forceSelectTime = cg.time; } } -void CG_NextInventory_f(void) -{ - if ( !cg.snap ) - { +void CG_NextInventory_f(void) { + if (!cg.snap) { return; } - if (cg.snap->ps.pm_flags & PMF_FOLLOW) - { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } - if (cg.itemSelect != -1) - { + if (cg.itemSelect != -1) { cg.snap->ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(cg.itemSelect, IT_HOLDABLE); } BG_CycleInven(&cg.snap->ps, 1); - if (cg.snap->ps.stats[STAT_HOLDABLE_ITEM]) - { + if (cg.snap->ps.stats[STAT_HOLDABLE_ITEM]) { cg.itemSelect = bg_itemlist[cg.snap->ps.stats[STAT_HOLDABLE_ITEM]].giTag; cg.invenSelectTime = cg.time; } } -void CG_PrevInventory_f(void) -{ - if ( !cg.snap ) - { +void CG_PrevInventory_f(void) { + if (!cg.snap) { return; } - if (cg.snap->ps.pm_flags & PMF_FOLLOW) - { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } - if (cg.itemSelect != -1) - { + if (cg.itemSelect != -1) { cg.snap->ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(cg.itemSelect, IT_HOLDABLE); } BG_CycleInven(&cg.snap->ps, -1); - if (cg.snap->ps.stats[STAT_HOLDABLE_ITEM]) - { + if (cg.snap->ps.stats[STAT_HOLDABLE_ITEM]) { cg.itemSelect = bg_itemlist[cg.snap->ps.stats[STAT_HOLDABLE_ITEM]].giTag; cg.invenSelectTime = cg.time; } } -static void _CG_MouseEvent( int x, int y ) { +static void _CG_MouseEvent(int x, int y) { cgDC.cursorx = cgs.cursorX; cgDC.cursory = cgs.cursorY; - CG_MouseEvent( x, y ); + CG_MouseEvent(x, y); } -static qboolean CG_IncomingConsoleCommand( void ) { - //rww - let mod authors filter client console messages so they can cut them off if they want. - //return qtrue if the command is ok. Otherwise, you can set char 0 on the command str to 0 and return - //qfalse to not execute anything, or you can fill conCommand in with something valid and return 0 - //in order to have that string executed in place. Some example code: +static qboolean CG_IncomingConsoleCommand(void) { + // rww - let mod authors filter client console messages so they can cut them off if they want. + // return qtrue if the command is ok. Otherwise, you can set char 0 on the command str to 0 and return + // qfalse to not execute anything, or you can fill conCommand in with something valid and return 0 + // in order to have that string executed in place. Some example code: #if 0 TCGIncomingConsoleCommand *icc = &cg.sharedBuffer.icc; if ( strstr( icc->conCommand, "wait" ) ) @@ -2888,36 +2685,26 @@ static qboolean CG_IncomingConsoleCommand( void ) { return qtrue; } -static void CG_GetOrigin( int entID, vec3_t out ) { - VectorCopy( cg_entities[entID].currentState.pos.trBase, out ); -} +static void CG_GetOrigin(int entID, vec3_t out) { VectorCopy(cg_entities[entID].currentState.pos.trBase, out); } -static void CG_GetAngles( int entID, vec3_t out ) { - VectorCopy( cg_entities[entID].currentState.apos.trBase, out ); -} +static void CG_GetAngles(int entID, vec3_t out) { VectorCopy(cg_entities[entID].currentState.apos.trBase, out); } -static trajectory_t *CG_GetOriginTrajectory( int entID ) { - return &cg_entities[entID].nextState.pos; -} +static trajectory_t *CG_GetOriginTrajectory(int entID) { return &cg_entities[entID].nextState.pos; } -static trajectory_t *CG_GetAngleTrajectory( int entID ) { - return &cg_entities[entID].nextState.apos; -} +static trajectory_t *CG_GetAngleTrajectory(int entID) { return &cg_entities[entID].nextState.apos; } -static void _CG_ROFF_NotetrackCallback( int entID, const char *notetrack ) { - CG_ROFF_NotetrackCallback( &cg_entities[entID], notetrack ); -} +static void _CG_ROFF_NotetrackCallback(int entID, const char *notetrack) { CG_ROFF_NotetrackCallback(&cg_entities[entID], notetrack); } -static void CG_MapChange( void ) { +static void CG_MapChange(void) { // this may be called more than once for a given map change, as the server is going to attempt to send out // multiple broadcasts in hopes that the client will receive one of them cg.mMapChange = qtrue; } -static void CG_AutomapInput( void ) { +static void CG_AutomapInput(void) { autoMapInput_t *autoInput = &cg.sharedBuffer.autoMapInput; - memcpy( &cg_autoMapInput, autoInput, sizeof( autoMapInput_t ) ); + memcpy(&cg_autoMapInput, autoInput, sizeof(autoMapInput_t)); #if 0 if ( !arg0 ) //if this is non-0, it's actually a one-frame mouse event @@ -2925,16 +2712,18 @@ static void CG_AutomapInput( void ) { else #endif { - if ( cg_autoMapInput.yaw ) cg_autoMapAngle[YAW] += cg_autoMapInput.yaw; - if ( cg_autoMapInput.pitch ) cg_autoMapAngle[PITCH] += cg_autoMapInput.pitch; + if (cg_autoMapInput.yaw) + cg_autoMapAngle[YAW] += cg_autoMapInput.yaw; + if (cg_autoMapInput.pitch) + cg_autoMapAngle[PITCH] += cg_autoMapInput.pitch; cg_autoMapInput.yaw = 0.0f; cg_autoMapInput.pitch = 0.0f; } } -static void CG_FX_CameraShake( void ) { +static void CG_FX_CameraShake(void) { TCGCameraShake *data = &cg.sharedBuffer.cameraShake; - CG_DoCameraShake( data->mOrigin, data->mIntensity, data->mRadius, data->mTime ); + CG_DoCameraShake(data->mOrigin, data->mIntensity, data->mRadius, data->mTime); } /* @@ -2945,49 +2734,48 @@ GetModuleAPI cgameImport_t *trap = NULL; -Q_EXPORT cgameExport_t* QDECL GetModuleAPI( int apiVersion, cgameImport_t *import ) -{ +Q_EXPORT cgameExport_t *QDECL GetModuleAPI(int apiVersion, cgameImport_t *import) { static cgameExport_t cge = {0}; - assert( import ); + assert(import); trap = import; - Com_Printf = trap->Print; - Com_Error = trap->Error; + Com_Printf = trap->Print; + Com_Error = trap->Error; - memset( &cge, 0, sizeof( cge ) ); + memset(&cge, 0, sizeof(cge)); - if ( apiVersion != CGAME_API_VERSION ) { - trap->Print( "Mismatched CGAME_API_VERSION: expected %i, got %i\n", CGAME_API_VERSION, apiVersion ); + if (apiVersion != CGAME_API_VERSION) { + trap->Print("Mismatched CGAME_API_VERSION: expected %i, got %i\n", CGAME_API_VERSION, apiVersion); return NULL; } - cge.Init = CG_Init; - cge.Shutdown = CG_Shutdown; - cge.ConsoleCommand = CG_ConsoleCommand; - cge.DrawActiveFrame = CG_DrawActiveFrame; - cge.CrosshairPlayer = CG_CrosshairPlayer; - cge.LastAttacker = CG_LastAttacker; - cge.KeyEvent = CG_KeyEvent; - cge.MouseEvent = _CG_MouseEvent; - cge.EventHandling = CG_EventHandling; - cge.PointContents = C_PointContents; - cge.GetLerpOrigin = C_GetLerpOrigin; - cge.GetLerpData = C_GetLerpData; - cge.Trace = C_Trace; - cge.G2Trace = C_G2Trace; - cge.G2Mark = C_G2Mark; - cge.RagCallback = CG_RagCallback; - cge.IncomingConsoleCommand = CG_IncomingConsoleCommand; - cge.NoUseableForce = CG_NoUseableForce; - cge.GetOrigin = CG_GetOrigin; - cge.GetAngles = CG_GetAngles; - cge.GetOriginTrajectory = CG_GetOriginTrajectory; - cge.GetAngleTrajectory = CG_GetAngleTrajectory; - cge.ROFF_NotetrackCallback = _CG_ROFF_NotetrackCallback; - cge.MapChange = CG_MapChange; - cge.AutomapInput = CG_AutomapInput; - cge.MiscEnt = CG_MiscEnt; - cge.CameraShake = CG_FX_CameraShake; + cge.Init = CG_Init; + cge.Shutdown = CG_Shutdown; + cge.ConsoleCommand = CG_ConsoleCommand; + cge.DrawActiveFrame = CG_DrawActiveFrame; + cge.CrosshairPlayer = CG_CrosshairPlayer; + cge.LastAttacker = CG_LastAttacker; + cge.KeyEvent = CG_KeyEvent; + cge.MouseEvent = _CG_MouseEvent; + cge.EventHandling = CG_EventHandling; + cge.PointContents = C_PointContents; + cge.GetLerpOrigin = C_GetLerpOrigin; + cge.GetLerpData = C_GetLerpData; + cge.Trace = C_Trace; + cge.G2Trace = C_G2Trace; + cge.G2Mark = C_G2Mark; + cge.RagCallback = CG_RagCallback; + cge.IncomingConsoleCommand = CG_IncomingConsoleCommand; + cge.NoUseableForce = CG_NoUseableForce; + cge.GetOrigin = CG_GetOrigin; + cge.GetAngles = CG_GetAngles; + cge.GetOriginTrajectory = CG_GetOriginTrajectory; + cge.GetAngleTrajectory = CG_GetAngleTrajectory; + cge.ROFF_NotetrackCallback = _CG_ROFF_NotetrackCallback; + cge.MapChange = CG_MapChange; + cge.AutomapInput = CG_AutomapInput; + cge.MiscEnt = CG_MiscEnt; + cge.CameraShake = CG_FX_CameraShake; return &cge; } @@ -3000,12 +2788,11 @@ This is the only way control passes into the module. This must be the very first function compiled into the .q3vm file ================ */ -Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, - intptr_t arg5, intptr_t arg6, intptr_t arg7, intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11 ) -{ - switch ( command ) { +Q_EXPORT intptr_t vmMain(int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7, + intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11) { + switch (command) { case CG_INIT: - CG_Init( arg0, arg1, arg2 ); + CG_Init(arg0, arg1, arg2); return 0; case CG_SHUTDOWN: @@ -3016,7 +2803,7 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return CG_ConsoleCommand(); case CG_DRAW_ACTIVE_FRAME: - CG_DrawActiveFrame( arg0, arg1, arg2 ); + CG_DrawActiveFrame(arg0, arg1, arg2); return 0; case CG_CROSSHAIR_PLAYER: @@ -3026,15 +2813,15 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return CG_LastAttacker(); case CG_KEY_EVENT: - CG_KeyEvent( arg0, arg1 ); + CG_KeyEvent(arg0, arg1); return 0; case CG_MOUSE_EVENT: - _CG_MouseEvent( arg0, arg1 ); + _CG_MouseEvent(arg0, arg1); return 0; case CG_EVENT_HANDLING: - CG_EventHandling( arg0 ); + CG_EventHandling(arg0); return 0; case CG_POINT_CONTENTS: @@ -3049,15 +2836,15 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return 0; case CG_GET_GHOUL2: - return (intptr_t)cg_entities[arg0].ghoul2; //NOTE: This is used by the effect bolting which is actually not used at all. - //I'm fairly sure if you try to use it with vm's it will just give you total - //garbage. In other words, use at your own risk. + return (intptr_t)cg_entities[arg0].ghoul2; // NOTE: This is used by the effect bolting which is actually not used at all. + // I'm fairly sure if you try to use it with vm's it will just give you total + // garbage. In other words, use at your own risk. case CG_GET_MODEL_LIST: return (intptr_t)cgs.gameModels; case CG_CALC_LERP_POSITIONS: - CG_CalcEntityLerpPositions( &cg_entities[arg0] ); + CG_CalcEntityLerpPositions(&cg_entities[arg0]); return 0; case CG_TRACE: @@ -3076,7 +2863,7 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return 0; case CG_RAG_CALLBACK: - return CG_RagCallback( arg0 ); + return CG_RagCallback(arg0); case CG_INCOMING_CONSOLE_COMMAND: return CG_IncomingConsoleCommand(); @@ -3085,21 +2872,21 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return CG_NoUseableForce(); case CG_GET_ORIGIN: - CG_GetOrigin( arg0, (float *)arg1 ); + CG_GetOrigin(arg0, (float *)arg1); return 0; case CG_GET_ANGLES: - CG_GetAngles( arg0, (float *)arg1 ); + CG_GetAngles(arg0, (float *)arg1); return 0; case CG_GET_ORIGIN_TRAJECTORY: - return (intptr_t)CG_GetOriginTrajectory( arg0 ); + return (intptr_t)CG_GetOriginTrajectory(arg0); case CG_GET_ANGLE_TRAJECTORY: - return (intptr_t)CG_GetAngleTrajectory( arg0 ); + return (intptr_t)CG_GetAngleTrajectory(arg0); case CG_ROFF_NOTETRACK_CALLBACK: - _CG_ROFF_NotetrackCallback( arg0, (const char *)arg1 ); + _CG_ROFF_NotetrackCallback(arg0, (const char *)arg1); return 0; case CG_IMPACT_MARK: @@ -3123,7 +2910,7 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return 0; default: - trap->Error( ERR_DROP, "vmMain: unknown command %i", command ); + trap->Error(ERR_DROP, "vmMain: unknown command %i", command); break; } return -1; diff --git a/codemp/cgame/cg_marks.c b/codemp/cgame/cg_marks.c index 6106e9614e..e1deb5da71 100644 --- a/codemp/cgame/cg_marks.c +++ b/codemp/cgame/cg_marks.c @@ -33,11 +33,10 @@ MARK POLYS =================================================================== */ - -markPoly_t cg_activeMarkPolys; // double linked list -markPoly_t *cg_freeMarkPolys; // single linked list -markPoly_t cg_markPolys[MAX_MARK_POLYS]; -static int markTotal; +markPoly_t cg_activeMarkPolys; // double linked list +markPoly_t *cg_freeMarkPolys; // single linked list +markPoly_t cg_markPolys[MAX_MARK_POLYS]; +static int markTotal; /* =================== @@ -46,28 +45,27 @@ CG_InitMarkPolys This is called at startup and for tournament restarts =================== */ -void CG_InitMarkPolys( void ) { - int i; +void CG_InitMarkPolys(void) { + int i; - memset( cg_markPolys, 0, sizeof(cg_markPolys) ); + memset(cg_markPolys, 0, sizeof(cg_markPolys)); cg_activeMarkPolys.nextMark = &cg_activeMarkPolys; cg_activeMarkPolys.prevMark = &cg_activeMarkPolys; cg_freeMarkPolys = cg_markPolys; - for ( i = 0 ; i < MAX_MARK_POLYS - 1 ; i++ ) { - cg_markPolys[i].nextMark = &cg_markPolys[i+1]; + for (i = 0; i < MAX_MARK_POLYS - 1; i++) { + cg_markPolys[i].nextMark = &cg_markPolys[i + 1]; } } - /* ================== CG_FreeMarkPoly ================== */ -void CG_FreeMarkPoly( markPoly_t *le ) { - if ( !le->prevMark ) { - trap->Error( ERR_DROP, "CG_FreeLocalEntity: not active" ); +void CG_FreeMarkPoly(markPoly_t *le) { + if (!le->prevMark) { + trap->Error(ERR_DROP, "CG_FreeLocalEntity: not active"); } // remove from the doubly linked active list @@ -86,23 +84,23 @@ CG_AllocMark Will allways succeed, even if it requires freeing an old active mark =================== */ -markPoly_t *CG_AllocMark( void ) { - markPoly_t *le; +markPoly_t *CG_AllocMark(void) { + markPoly_t *le; int time; - if ( !cg_freeMarkPolys ) { + if (!cg_freeMarkPolys) { // no free entities, so free the one at the end of the chain // remove the oldest active entity time = cg_activeMarkPolys.prevMark->time; while (cg_activeMarkPolys.prevMark && time == cg_activeMarkPolys.prevMark->time) { - CG_FreeMarkPoly( cg_activeMarkPolys.prevMark ); + CG_FreeMarkPoly(cg_activeMarkPolys.prevMark); } } le = cg_freeMarkPolys; cg_freeMarkPolys = cg_freeMarkPolys->nextMark; - memset( le, 0, sizeof( *le ) ); + memset(le, 0, sizeof(*le)); // link into the active list le->nextMark = cg_activeMarkPolys.nextMark; @@ -112,8 +110,6 @@ markPoly_t *CG_AllocMark( void ) { return le; } - - /* ================= CG_ImpactMark @@ -125,52 +121,48 @@ temporary marks will not be stored or randomly oriented, but immediately passed to the renderer. ================= */ -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 - -void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, - float orientation, float red, float green, float blue, float alpha, - qboolean alphaFade, float radius, qboolean temporary ) { - matrix3_t axis; - float texCoordScale; - vec3_t originalPoints[4]; - byte colors[4]; - int i, j, k; - int numFragments; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - vec3_t markPoints[MAX_MARK_POINTS]; - vec3_t projection; +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 + +void CG_ImpactMark(qhandle_t markShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, + qboolean alphaFade, float radius, qboolean temporary) { + matrix3_t axis; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j, k; + int numFragments; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; + vec3_t markPoints[MAX_MARK_POINTS]; + vec3_t projection; assert(markShader); - if ( !cg_marks.integer ) { + if (!cg_marks.integer) { return; - } - else if (cg_marks.integer == 2) - { - trap->R_AddDecalToScene(markShader, origin, dir, orientation, red, green, blue, alpha, - alphaFade, radius, temporary); + } else if (cg_marks.integer == 2) { + trap->R_AddDecalToScene(markShader, origin, dir, orientation, red, green, blue, alpha, alphaFade, radius, temporary); return; } - if ( radius <= 0 ) { - trap->Error( ERR_DROP, "CG_ImpactMark called with <= 0 radius" ); + if (radius <= 0) { + trap->Error(ERR_DROP, "CG_ImpactMark called with <= 0 radius"); } - //if ( markTotal >= MAX_MARK_POLYS ) { + // if ( markTotal >= MAX_MARK_POLYS ) { // return; - //} + // } // create the texture axis - VectorNormalize2( dir, axis[0] ); - PerpendicularVector( axis[1], axis[0] ); - RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); - CrossProduct( axis[0], axis[2], axis[1] ); + VectorNormalize2(dir, axis[0]); + PerpendicularVector(axis[1], axis[0]); + RotatePointAroundVector(axis[2], axis[0], axis[1], orientation); + CrossProduct(axis[0], axis[2], axis[1]); texCoordScale = 0.5 * 1.0 / radius; // create the full polygon - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; @@ -178,39 +170,39 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, } // get the fragments - VectorScale( dir, -20, projection ); - numFragments = trap->R_MarkFragments( 4, (const vec3_t *) originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments ); + VectorScale(dir, -20, projection); + numFragments = trap->R_MarkFragments(4, (const vec3_t *)originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); colors[0] = red * 255; colors[1] = green * 255; colors[2] = blue * 255; colors[3] = alpha * 255; - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) { - polyVert_t *v; - polyVert_t verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; // we have an upper limit on the complexity of polygons // that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) { - vec3_t delta; + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { + vec3_t delta; - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); - VectorSubtract( v->xyz, origin, delta ); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale; - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale; - for ( k=0; k<4; k++ ) + VectorSubtract(v->xyz, origin, delta); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * texCoordScale; + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * texCoordScale; + for (k = 0; k < 4; k++) v->modulate[k] = colors[k]; } // if it is a temporary (shadow) mark, add it immediately and forget about it - if ( temporary ) { - trap->R_AddPolysToScene( markShader, mf->numPoints, verts, 1 ); + if (temporary) { + trap->R_AddPolysToScene(markShader, mf->numPoints, verts, 1); continue; } @@ -224,53 +216,52 @@ void CG_ImpactMark( qhandle_t markShader, const vec3_t origin, const vec3_t dir, mark->color[1] = green; mark->color[2] = blue; mark->color[3] = alpha; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); markTotal++; } } - /* =============== CG_AddMarks =============== */ -#define MARK_TOTAL_TIME 10000 -#define MARK_FADE_TIME 1000 +#define MARK_TOTAL_TIME 10000 +#define MARK_FADE_TIME 1000 -void CG_AddMarks( void ) { - int j; - markPoly_t *mp, *next; - int t; - int fade; +void CG_AddMarks(void) { + int j; + markPoly_t *mp, *next; + int t; + int fade; - if ( !cg_marks.integer ) { + if (!cg_marks.integer) { return; } mp = cg_activeMarkPolys.nextMark; - for ( ; mp != &cg_activeMarkPolys ; mp = next ) { + for (; mp != &cg_activeMarkPolys; mp = next) { // grab next now, so if the local entity is freed we // still have it next = mp->nextMark; // see if it is time to completely remove it - if ( cg.time > mp->time + MARK_TOTAL_TIME ) { - CG_FreeMarkPoly( mp ); + if (cg.time > mp->time + MARK_TOTAL_TIME) { + CG_FreeMarkPoly(mp); continue; } // fade out the energy bursts - //if ( mp->markShader == cgs.media.energyMarkShader ) { + // if ( mp->markShader == cgs.media.energyMarkShader ) { if (0) { - fade = 450 - 450 * ( (cg.time - mp->time ) / 3000.0 ); - if ( fade < 255 ) { - if ( fade < 0 ) { + fade = 450 - 450 * ((cg.time - mp->time) / 3000.0); + if (fade < 255) { + if (fade < 0) { fade = 0; } - if ( mp->verts[0].modulate[0] != 0 ) { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + if (mp->verts[0].modulate[0] != 0) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0] * fade; mp->verts[j].modulate[1] = mp->color[1] * fade; mp->verts[j].modulate[2] = mp->color[2] * fade; @@ -281,32 +272,28 @@ void CG_AddMarks( void ) { // fade all marks out with time t = mp->time + MARK_TOTAL_TIME - cg.time; - if ( t < MARK_FADE_TIME ) { + if (t < MARK_FADE_TIME) { fade = 255 * t / MARK_FADE_TIME; - if ( mp->alphaFade ) { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + if (mp->alphaFade) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[3] = fade; } - } - else - { + } else { float f = (float)t / MARK_FADE_TIME; - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0] * f; mp->verts[j].modulate[1] = mp->color[1] * f; mp->verts[j].modulate[2] = mp->color[2] * f; } } - } - else - { - for ( j = 0 ; j < mp->poly.numVerts ; j++ ) { + } else { + for (j = 0; j < mp->poly.numVerts; j++) { mp->verts[j].modulate[0] = mp->color[0]; mp->verts[j].modulate[1] = mp->color[1]; mp->verts[j].modulate[2] = mp->color[2]; } } - trap->R_AddPolysToScene( mp->markShader, mp->poly.numVerts, mp->verts, 1 ); + trap->R_AddPolysToScene(mp->markShader, mp->poly.numVerts, mp->verts, 1); } } diff --git a/codemp/cgame/cg_newDraw.c b/codemp/cgame/cg_newDraw.c index 6fb6e93848..fc06fb036e 100644 --- a/codemp/cgame/cg_newDraw.c +++ b/codemp/cgame/cg_newDraw.c @@ -26,7 +26,6 @@ along with this program; if not, see . extern displayContextDef_t cgDC; - int CG_GetSelectedPlayer() { if (cg_currentSelectedPlayer.integer < 0 || cg_currentSelectedPlayer.integer >= numSortedTeamPlayers) { cg_currentSelectedPlayer.integer = 0; @@ -37,39 +36,38 @@ int CG_GetSelectedPlayer() { qhandle_t CG_StatusHandle(int task) { qhandle_t h = cgs.media.assaultShader; switch (task) { - case TEAMTASK_OFFENSE : + case TEAMTASK_OFFENSE: h = cgs.media.assaultShader; break; - case TEAMTASK_DEFENSE : + case TEAMTASK_DEFENSE: h = cgs.media.defendShader; break; - case TEAMTASK_PATROL : + case TEAMTASK_PATROL: h = cgs.media.patrolShader; break; - case TEAMTASK_FOLLOW : + case TEAMTASK_FOLLOW: h = cgs.media.followShader; break; - case TEAMTASK_CAMP : + case TEAMTASK_CAMP: h = cgs.media.campShader; break; - case TEAMTASK_RETRIEVE : + case TEAMTASK_RETRIEVE: h = cgs.media.retrieveShader; break; - case TEAMTASK_ESCORT : + case TEAMTASK_ESCORT: h = cgs.media.escortShader; break; - default : + default: h = cgs.media.assaultShader; break; } return h; } - float CG_GetValue(int ownerDraw) { - centity_t *cent; + centity_t *cent; clientInfo_t *ci; - playerState_t *ps; + playerState_t *ps; cent = &cg_entities[cg.snap->ps.clientNum]; ps = &cg.snap->ps; @@ -87,8 +85,7 @@ float CG_GetValue(int ownerDraw) { return ps->stats[STAT_ARMOR]; break; case CG_PLAYER_AMMO_VALUE: - if ( cent->currentState.weapon ) - { + if (cent->currentState.weapon) { return ps->ammo[weaponData[cent->currentState.weapon].ammoIndex]; } break; @@ -171,19 +168,19 @@ qboolean CG_OwnerDrawVisible(int flags) { } if (flags & CG_SHOW_ANYTEAMGAME) { - if( cgs.gametype >= GT_TEAM) { + if (cgs.gametype >= GT_TEAM) { return qtrue; } } if (flags & CG_SHOW_ANYNONTEAMGAME) { - if( cgs.gametype < GT_TEAM) { + if (cgs.gametype < GT_TEAM) { return qtrue; } } if (flags & CG_SHOW_CTF) { - if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY ) { + if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTY) { return qtrue; } } @@ -201,13 +198,13 @@ qboolean CG_OwnerDrawVisible(int flags) { } if (flags & CG_SHOW_SINGLEPLAYER) { - if( cgs.gametype == GT_SINGLE_PLAYER ) { + if (cgs.gametype == GT_SINGLE_PLAYER) { return qtrue; } } if (flags & CG_SHOW_TOURNAMENT) { - if( cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL ) { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { return qtrue; } } @@ -223,40 +220,32 @@ qboolean CG_OwnerDrawVisible(int flags) { return qfalse; } - const char *CG_GetKillerText(void) { static const char *s = ""; - if ( cg.killerName[0] ) { - s = va("%s %s", CG_GetStringEdString("MP_INGAME", "KILLEDBY"), cg.killerName ); + if (cg.killerName[0]) { + s = va("%s %s", CG_GetStringEdString("MP_INGAME", "KILLEDBY"), cg.killerName); } return s; } - const char *CG_GetGameStatusText(void) { static const char *s = ""; - if (cgs.gametype == GT_POWERDUEL) - { + if (cgs.gametype == GT_POWERDUEL) { s = ""; - } - else if ( cgs.gametype < GT_TEAM) - { - if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) - { + } else if (cgs.gametype < GT_TEAM) { + if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) { char sPlaceWith[256]; trap->SE_GetStringTextString("MP_INGAME_PLACE_WITH", sPlaceWith, sizeof(sPlaceWith)); - s = va("%s %s %i",CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ), sPlaceWith, cg.snap->ps.persistant[PERS_SCORE] ); + s = va("%s %s %i", CG_PlaceString(cg.snap->ps.persistant[PERS_RANK] + 1), sPlaceWith, cg.snap->ps.persistant[PERS_SCORE]); } - } - else - { - if ( cg.teamScores[0] == cg.teamScores[1] ) { - s = va("%s %i", CG_GetStringEdString("MP_INGAME", "TIEDAT"), cg.teamScores[0] ); - } else if ( cg.teamScores[0] >= cg.teamScores[1] ) { - s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "RED_LEADS"), cg.teamScores[0], cg.teamScores[1] ); + } else { + if (cg.teamScores[0] == cg.teamScores[1]) { + s = va("%s %i", CG_GetStringEdString("MP_INGAME", "TIEDAT"), cg.teamScores[0]); + } else if (cg.teamScores[0] >= cg.teamScores[1]) { + s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "RED_LEADS"), cg.teamScores[0], cg.teamScores[1]); } else { - s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "BLUE_LEADS"), cg.teamScores[1], cg.teamScores[0] ); + s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "BLUE_LEADS"), cg.teamScores[1], cg.teamScores[0]); } } return s; @@ -266,75 +255,64 @@ extern int MenuFontToHandle(int iMenuFont); // maxX param is initially an X limit, but is also used as feedback. 0 = text was clipped to fit within, else maxX = next pos // -static void CG_Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char* text, float adjust, int limit, int iMenuFont) -{ +static void CG_Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int iMenuFont) { qboolean bIsTrailingPunctuation; // this is kinda dirty, but... // int iFontIndex = MenuFontToHandle(iMenuFont); - //float fMax = *maxX; + // float fMax = *maxX; int iPixelLen = trap->R_Font_StrLenPixels(text, iFontIndex, scale); - if (x + iPixelLen > *maxX) - { + if (x + iPixelLen > *maxX) { // whole text won't fit, so we need to print just the amount that does... // Ok, this is slow and tacky, but only called occasionally, and it works... // - char sTemp[4096]={0}; // lazy assumption + char sTemp[4096] = {0}; // lazy assumption const char *psText = text; char *psOut = &sTemp[0]; char *psOutLastGood = psOut; unsigned int uiLetter; - while (*psText && (x + trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale)<=*maxX) - && psOut < &sTemp[sizeof(sTemp)-1] // sanity - ) - { + while (*psText && (x + trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale) <= *maxX) && psOut < &sTemp[sizeof(sTemp) - 1] // sanity + ) { int iAdvanceCount; psOutLastGood = psOut; uiLetter = trap->R_AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, &bIsTrailingPunctuation); psText += iAdvanceCount; - if (uiLetter > 255) - { - *psOut++ = uiLetter>>8; - *psOut++ = uiLetter&0xFF; - } - else - { - *psOut++ = uiLetter&0xFF; + if (uiLetter > 255) { + *psOut++ = uiLetter >> 8; + *psOut++ = uiLetter & 0xFF; + } else { + *psOut++ = uiLetter & 0xFF; } } *psOutLastGood = '\0'; - *maxX = 0; // feedback + *maxX = 0; // feedback CG_Text_Paint(x, y, scale, color, sTemp, adjust, limit, ITEM_TEXTSTYLE_NORMAL, iMenuFont); - } - else - { + } else { // whole text fits fine, so print it all... // - *maxX = x + iPixelLen; // feedback the next position, as the caller expects + *maxX = x + iPixelLen; // feedback the next position, as the caller expects CG_Text_Paint(x, y, scale, color, text, adjust, limit, ITEM_TEXTSTYLE_NORMAL, iMenuFont); } } - - #define PIC_WIDTH 12 -extern const char *CG_GetLocationString(const char *loc); //cg_main.c +extern const char *CG_GetLocationString(const char *loc); // cg_main.c void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale, vec4_t color, qhandle_t shader) { int xx; float y; int i, j, len, count; const char *p; - vec4_t hcolor; + vec4_t hcolor; float pwidth, lwidth, maxx, leftOver; clientInfo_t *ci; - gitem_t *item; + gitem_t *item; qhandle_t h; // max player name width @@ -342,8 +320,8 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers; for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; - if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { - len = CG_Text_Width( ci->name, scale, 0); + if (ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { + len = CG_Text_Width(ci->name, scale, 0); if (len > pwidth) pwidth = len; } @@ -352,7 +330,7 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale // max location name width lwidth = 0; for (i = 1; i < MAX_LOCATIONS; i++) { - p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+i)); + p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS + i)); if (p && *p) { len = CG_Text_Width(p, scale, 0); if (len > lwidth) @@ -364,16 +342,16 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale for (i = 0; i < count; i++) { ci = cgs.clientinfo + sortedTeamPlayers[i]; - if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { + if (ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { xx = rect->x + 1; for (j = 0; j <= PW_NUM_POWERUPS; j++) { if (ci->powerups & (1 << j)) { - item = BG_FindItemForPowerup( j ); + item = BG_FindItemForPowerup(j); if (item) { - CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, trap->R_RegisterShader( item->icon ) ); + CG_DrawPic(xx, y, PIC_WIDTH, PIC_WIDTH, trap->R_RegisterShader(item->icon)); xx += PIC_WIDTH; } } @@ -382,12 +360,12 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale // FIXME: max of 3 powerups shown properly xx = rect->x + (PIC_WIDTH * 3) + 2; - CG_GetColorForHealth( ci->health, ci->armor, hcolor ); + CG_GetColorForHealth(ci->health, ci->armor, hcolor); trap->R_SetColor(hcolor); - CG_DrawPic( xx, y + 1, PIC_WIDTH - 2, PIC_WIDTH - 2, cgs.media.heartShader ); + CG_DrawPic(xx, y + 1, PIC_WIDTH - 2, PIC_WIDTH - 2, cgs.media.heartShader); - //Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor); - //CG_Text_Paint(xx, y + text_y, scale, hcolor, st, 0, 0); + // Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor); + // CG_Text_Paint(xx, y + text_y, scale, hcolor, st, 0, 0); // draw weapon icon xx += PIC_WIDTH + 1; @@ -405,7 +383,7 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale h = CG_StatusHandle(ci->teamTask); if (h) { - CG_DrawPic( xx, y, PIC_WIDTH, PIC_WIDTH, h); + CG_DrawPic(xx, y, PIC_WIDTH, PIC_WIDTH, h); } xx += PIC_WIDTH + 1; @@ -413,11 +391,9 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale leftOver = rect->w - xx; maxx = xx + leftOver / 3; - - CG_Text_Paint_Limit(&maxx, xx, y + text_y, scale, color, ci->name, 0, 0, FONT_MEDIUM); - p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+ci->location)); + p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS + ci->location)); if (!p || !*p) { p = "unknown"; } @@ -427,15 +403,13 @@ void CG_DrawNewTeamInfo(rectDef_t *rect, float text_x, float text_y, float scale CG_Text_Paint_Limit(&maxx, xx, y + text_y, scale, color, p, 0, 0, FONT_MEDIUM); y += text_y + 2; - if ( y + text_y + 2 > rect->y + rect->h ) { + if (y + text_y + 2 > rect->y + rect->h) { break; } - } } } - void CG_DrawTeamSpectators(rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) { if (cg.spectatorLen) { float maxX; @@ -489,12 +463,9 @@ void CG_DrawTeamSpectators(rectDef_t *rect, float scale, vec4_t color, qhandle_t } else { cg.spectatorPaintX2 = -1; } - } } - - void CG_DrawMedal(int ownerDraw, rectDef_t *rect, float scale, vec4_t color, qhandle_t shader) { score_t *score = &cg.scores[cg.selectedScore]; float value = 0; @@ -548,22 +519,21 @@ void CG_DrawMedal(int ownerDraw, rectDef_t *rect, float scale, vec4_t color, qha } trap->R_SetColor(color); - CG_DrawPic( rect->x, rect->y, rect->w, rect->h, shader ); + CG_DrawPic(rect->x, rect->y, rect->w, rect->h, shader); if (text) { color[3] = 1.0; value = CG_Text_Width(text, scale, 0); - CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h + 10 , scale, color, text, 0, 0, 0, FONT_MEDIUM); + CG_Text_Paint(rect->x + (rect->w - value) / 2, rect->y + rect->h + 10, scale, color, text, 0, 0, 0, FONT_MEDIUM); } trap->R_SetColor(NULL); - } - // -void CG_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle,int font) { +void CG_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, + vec4_t color, qhandle_t shader, int textStyle, int font) { - //Ignore all this, at least for now. May put some stat stuff back in menu files later. + // Ignore all this, at least for now. May put some stat stuff back in menu files later. #if 0 rectDef_t rect; @@ -750,13 +720,12 @@ void CG_MouseEvent(int x, int y) { int n; /* - if ( (cg.predictedPlayerState.pm_type == PM_NORMAL || cg.predictedPlayerState.pm_type == PM_JETPACK || cg.predictedPlayerState.pm_type == PM_FLOAT || cg.predictedPlayerState.pm_type == PM_SPECTATOR) && cg.showScores == qfalse) { - trap->Key_SetCatcher(0); - return; + if ( (cg.predictedPlayerState.pm_type == PM_NORMAL || cg.predictedPlayerState.pm_type == PM_JETPACK || cg.predictedPlayerState.pm_type == PM_FLOAT || + cg.predictedPlayerState.pm_type == PM_SPECTATOR) && cg.showScores == qfalse) { trap->Key_SetCatcher(0); return; } */ - cgs.cursorX+= x; + cgs.cursorX += x; if (cgs.cursorX < 0) cgs.cursorX = 0; else if (cgs.cursorX > 640) @@ -781,7 +750,6 @@ void CG_MouseEvent(int x, int y) { } else { Display_MouseMove(NULL, cgs.cursorX, cgs.cursorY); } - } /* @@ -801,12 +769,7 @@ CG_ShowTeamMenus ================== */ -void CG_ShowTeamMenu() { - Menus_OpenByName("teamMenu"); -} - - - +void CG_ShowTeamMenu() { Menus_OpenByName("teamMenu"); } /* ================== @@ -822,39 +785,35 @@ void CG_EventHandling(int type) { if (type == CGAME_EVENT_NONE) { CG_HideTeamMenu(); } else if (type == CGAME_EVENT_TEAMMENU) { - //CG_ShowTeamMenu(); + // CG_ShowTeamMenu(); } else if (type == CGAME_EVENT_SCOREBOARD) { } - } - - void CG_KeyEvent(int key, qboolean down) { if (!down) { return; } - if ( cg.predictedPlayerState.pm_type == PM_NORMAL || cg.predictedPlayerState.pm_type == PM_JETPACK || cg.predictedPlayerState.pm_type == PM_NORMAL || (cg.predictedPlayerState.pm_type == PM_SPECTATOR && cg.showScores == qfalse)) { + if (cg.predictedPlayerState.pm_type == PM_NORMAL || cg.predictedPlayerState.pm_type == PM_JETPACK || cg.predictedPlayerState.pm_type == PM_NORMAL || + (cg.predictedPlayerState.pm_type == PM_SPECTATOR && cg.showScores == qfalse)) { CG_EventHandling(CGAME_EVENT_NONE); trap->Key_SetCatcher(0); return; } - //if (key == trap->Key_GetKey("teamMenu") || !Display_CaptureItem(cgs.cursorX, cgs.cursorY)) { - // if we see this then we should always be visible - // CG_EventHandling(CGAME_EVENT_NONE); - // trap->Key_SetCatcher(0); - //} - - + // if (key == trap->Key_GetKey("teamMenu") || !Display_CaptureItem(cgs.cursorX, cgs.cursorY)) { + // if we see this then we should always be visible + // CG_EventHandling(CGAME_EVENT_NONE); + // trap->Key_SetCatcher(0); + // } Display_HandleKey(key, down, cgs.cursorX, cgs.cursorY); if (cgs.capturedItem) { cgs.capturedItem = NULL; - } else { + } else { if (key == A_MOUSE2 && down) { cgs.capturedItem = Display_CaptureItem(cgs.cursorX, cgs.cursorY); } @@ -877,13 +836,9 @@ void CG_ShowResponseHead(void) { cg.voiceTime = cg.time; } -void CG_RunMenuScript(char **args) { -} +void CG_RunMenuScript(char **args) {} -qboolean CG_DeferMenuScript (char **args) -{ - return qfalse; -} +qboolean CG_DeferMenuScript(char **args) { return qfalse; } void CG_GetTeamColor(vec4_t *color) { if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED) { diff --git a/codemp/cgame/cg_players.c b/codemp/cgame/cg_players.c index d9262deb87..13654041eb 100644 --- a/codemp/cgame/cg_players.c +++ b/codemp/cgame/cg_players.c @@ -26,159 +26,57 @@ along with this program; if not, see . #include "ghoul2/G2.h" #include "game/bg_saga.h" -extern vmCvar_t cg_thirdPersonAlpha; - -extern int cgSiegeTeam1PlShader; -extern int cgSiegeTeam2PlShader; - -extern void CG_AddRadarEnt(centity_t *cent); //cg_ents.c -extern void CG_AddBracketedEnt(centity_t *cent); //cg_ents.c -extern qboolean CG_InFighter( void ); -extern qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); - - -//for g2 surface routines -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 - -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; - -char *cg_customSoundNames[MAX_CUSTOM_SOUNDS] = { - "*death1", - "*death2", - "*death3", - "*jump1", - "*pain25", - "*pain50", - "*pain75", - "*pain100", - "*falling1", - "*choke1", - "*choke2", - "*choke3", - "*gasp", - "*land1", - "*taunt", - NULL -}; - -//NPC sounds: -//Used as a supplement to the basic set for enemies and hazard team -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = -{ - "*anger1", //Say when acquire an enemy when didn't have one before - "*anger2", - "*anger3", - "*victory1", //Say when killed an enemy - "*victory2", - "*victory3", - "*confuse1", //Say when confused - "*confuse2", - "*confuse3", - "*pushed1", //Say when force-pushed - "*pushed2", - "*pushed3", - "*choke1", - "*choke2", - "*choke3", - "*ffwarn", - "*ffturn", - NULL -}; - -//Used as a supplement to the basic set for stormtroopers -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = -{ - "*chase1", - "*chase2", - "*chase3", - "*cover1", - "*cover2", - "*cover3", - "*cover4", - "*cover5", - "*detected1", - "*detected2", - "*detected3", - "*detected4", - "*detected5", - "*lost1", - "*outflank1", - "*outflank2", - "*escaping1", - "*escaping2", - "*escaping3", - "*giveup1", - "*giveup2", - "*giveup3", - "*giveup4", - "*look1", - "*look2", - "*sight1", - "*sight2", - "*sight3", - "*sound1", - "*sound2", - "*sound3", - "*suspicious1", - "*suspicious2", - "*suspicious3", - "*suspicious4", - "*suspicious5", - NULL -}; - -//Used as a supplement to the basic set for jedi -// (keep numbers in ascending order in order for variant-capping to work) -const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = -{ - "*combat1", - "*combat2", - "*combat3", - "*jdetected1", - "*jdetected2", - "*jdetected3", - "*taunt1", - "*taunt2", - "*taunt3", - "*jchase1", - "*jchase2", - "*jchase3", - "*jlost1", - "*jlost2", - "*jlost3", - "*deflect1", - "*deflect2", - "*deflect3", - "*gloat1", - "*gloat2", - "*gloat3", - "*pushfail", - NULL -}; - -//Used for DUEL taunts -const char *cg_customDuelSoundNames[MAX_CUSTOM_DUEL_SOUNDS] = -{ - "*anger1", //Say when acquire an enemy when didn't have one before - "*anger2", - "*anger3", - "*victory1", //Say when killed an enemy - "*victory2", - "*victory3", - "*taunt1", - "*taunt2", - "*taunt3", - "*deflect1", - "*deflect2", - "*deflect3", - "*gloat1", - "*gloat2", - "*gloat3", - NULL -}; +extern vmCvar_t cg_thirdPersonAlpha; + +extern int cgSiegeTeam1PlShader; +extern int cgSiegeTeam2PlShader; + +extern void CG_AddRadarEnt(centity_t *cent); // cg_ents.c +extern void CG_AddBracketedEnt(centity_t *cent); // cg_ents.c +extern qboolean CG_InFighter(void); +extern qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); + +// for g2 surface routines +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 + +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; + +char *cg_customSoundNames[MAX_CUSTOM_SOUNDS] = {"*death1", "*death2", "*death3", "*jump1", "*pain25", "*pain50", "*pain75", "*pain100", + "*falling1", "*choke1", "*choke2", "*choke3", "*gasp", "*land1", "*taunt", NULL}; + +// NPC sounds: +// Used as a supplement to the basic set for enemies and hazard team +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customCombatSoundNames[MAX_CUSTOM_COMBAT_SOUNDS] = {"*anger1", // Say when acquire an enemy when didn't have one before + "*anger2", "*anger3", + "*victory1", // Say when killed an enemy + "*victory2", "*victory3", + "*confuse1", // Say when confused + "*confuse2", "*confuse3", + "*pushed1", // Say when force-pushed + "*pushed2", "*pushed3", "*choke1", "*choke2", "*choke3", "*ffwarn", "*ffturn", NULL}; + +// Used as a supplement to the basic set for stormtroopers +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS] = { + "*chase1", "*chase2", "*chase3", "*cover1", "*cover2", "*cover3", "*cover4", "*cover5", "*detected1", "*detected2", + "*detected3", "*detected4", "*detected5", "*lost1", "*outflank1", "*outflank2", "*escaping1", "*escaping2", "*escaping3", "*giveup1", + "*giveup2", "*giveup3", "*giveup4", "*look1", "*look2", "*sight1", "*sight2", "*sight3", "*sound1", "*sound2", + "*sound3", "*suspicious1", "*suspicious2", "*suspicious3", "*suspicious4", "*suspicious5", NULL}; + +// Used as a supplement to the basic set for jedi +// (keep numbers in ascending order in order for variant-capping to work) +const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS] = { + "*combat1", "*combat2", "*combat3", "*jdetected1", "*jdetected2", "*jdetected3", "*taunt1", "*taunt2", "*taunt3", "*jchase1", "*jchase2", "*jchase3", + "*jlost1", "*jlost2", "*jlost3", "*deflect1", "*deflect2", "*deflect3", "*gloat1", "*gloat2", "*gloat3", "*pushfail", NULL}; + +// Used for DUEL taunts +const char *cg_customDuelSoundNames[MAX_CUSTOM_DUEL_SOUNDS] = {"*anger1", // Say when acquire an enemy when didn't have one before + "*anger2", "*anger3", + "*victory1", // Say when killed an enemy + "*victory2", "*victory3", "*taunt1", "*taunt2", "*taunt3", "*deflect1", + "*deflect2", "*deflect3", "*gloat1", "*gloat2", "*gloat3", NULL}; void CG_Disintegration(centity_t *cent, refEntity_t *ent); @@ -188,138 +86,106 @@ CG_CustomSound ================ */ -sfxHandle_t CG_CustomSound( int clientNum, const char *soundName ) { +sfxHandle_t CG_CustomSound(int clientNum, const char *soundName) { clientInfo_t *ci; - int i; - int numCSounds = 0; - int numCComSounds = 0; - int numCExSounds = 0; - int numCJediSounds = 0; - int numCSiegeSounds = 0; - int numCDuelSounds = 0; - char lSoundName[MAX_QPATH]; + int i; + int numCSounds = 0; + int numCComSounds = 0; + int numCExSounds = 0; + int numCJediSounds = 0; + int numCSiegeSounds = 0; + int numCDuelSounds = 0; + char lSoundName[MAX_QPATH]; - if ( soundName[0] != '*' ) { - return trap->S_RegisterSound( soundName ); + if (soundName[0] != '*') { + return trap->S_RegisterSound(soundName); } - COM_StripExtension( soundName, lSoundName, sizeof( lSoundName ) ); + COM_StripExtension(soundName, lSoundName, sizeof(lSoundName)); - if ( clientNum < 0 ) - { + if (clientNum < 0) { clientNum = 0; } - if (clientNum >= MAX_CLIENTS) - { + if (clientNum >= MAX_CLIENTS) { ci = cg_entities[clientNum].npcClient; - } - else - { - ci = &cgs.clientinfo[ clientNum ]; + } else { + ci = &cgs.clientinfo[clientNum]; } - if (!ci) - { + if (!ci) { return 0; } - for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) - { - if (!cg_customSoundNames[i]) - { + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (!cg_customSoundNames[i]) { numCSounds = i; break; } } - if (clientNum >= MAX_CLIENTS) - { //these are only for npc's - for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) - { - if (!cg_customCombatSoundNames[i]) - { + if (clientNum >= MAX_CLIENTS) { // these are only for npc's + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (!cg_customCombatSoundNames[i]) { numCComSounds = i; break; } } - for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) - { - if (!cg_customExtraSoundNames[i]) - { + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (!cg_customExtraSoundNames[i]) { numCExSounds = i; break; } } - for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) - { - if (!cg_customJediSoundNames[i]) - { + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (!cg_customJediSoundNames[i]) { numCJediSounds = i; break; } } } - if (cgs.gametype >= GT_TEAM || com_buildScript.integer) - { //siege only - for (i = 0; i < MAX_CUSTOM_SIEGE_SOUNDS; i++) - { - if (!bg_customSiegeSoundNames[i]) - { + if (cgs.gametype >= GT_TEAM || com_buildScript.integer) { // siege only + for (i = 0; i < MAX_CUSTOM_SIEGE_SOUNDS; i++) { + if (!bg_customSiegeSoundNames[i]) { numCSiegeSounds = i; break; } } } - if (cgs.gametype == GT_DUEL - || cgs.gametype == GT_POWERDUEL - || com_buildScript.integer) - { //Duel only - for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) - { - if (!cg_customDuelSoundNames[i]) - { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL || com_buildScript.integer) { // Duel only + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (!cg_customDuelSoundNames[i]) { numCDuelSounds = i; break; } } } - for ( i = 0 ; i < MAX_CUSTOM_SOUNDS ; i++ ) - { - if ( i < numCSounds && !strcmp( lSoundName, cg_customSoundNames[i] ) ) - { + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { + if (i < numCSounds && !strcmp(lSoundName, cg_customSoundNames[i])) { return ci->sounds[i]; - } - else if ( (cgs.gametype >= GT_TEAM || com_buildScript.integer) && i < numCSiegeSounds && !strcmp( lSoundName, bg_customSiegeSoundNames[i] ) ) - { //siege only + } else if ((cgs.gametype >= GT_TEAM || com_buildScript.integer) && i < numCSiegeSounds && + !strcmp(lSoundName, bg_customSiegeSoundNames[i])) { // siege only return ci->siegeSounds[i]; - } - else if ( (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL || com_buildScript.integer) && i < numCDuelSounds && !strcmp( lSoundName, cg_customDuelSoundNames[i] ) ) - { //siege only + } else if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL || com_buildScript.integer) && i < numCDuelSounds && + !strcmp(lSoundName, cg_customDuelSoundNames[i])) { // siege only return ci->duelSounds[i]; - } - else if ( clientNum >= MAX_CLIENTS && i < numCComSounds && !strcmp( lSoundName, cg_customCombatSoundNames[i] ) ) - { //npc only + } else if (clientNum >= MAX_CLIENTS && i < numCComSounds && !strcmp(lSoundName, cg_customCombatSoundNames[i])) { // npc only return ci->combatSounds[i]; - } - else if ( clientNum >= MAX_CLIENTS && i < numCExSounds && !strcmp( lSoundName, cg_customExtraSoundNames[i] ) ) - { //npc only + } else if (clientNum >= MAX_CLIENTS && i < numCExSounds && !strcmp(lSoundName, cg_customExtraSoundNames[i])) { // npc only return ci->extraSounds[i]; - } - else if ( clientNum >= MAX_CLIENTS && i < numCJediSounds && !strcmp( lSoundName, cg_customJediSoundNames[i] ) ) - { //npc only + } else if (clientNum >= MAX_CLIENTS && i < numCJediSounds && !strcmp(lSoundName, cg_customJediSoundNames[i])) { // npc only return ci->jediSounds[i]; } } - //trap->Error( ERR_DROP, "Unknown custom sound: %s", lSoundName ); + // trap->Error( ERR_DROP, "Unknown custom sound: %s", lSoundName ); #ifndef FINAL_BUILD - Com_Printf( "Unknown custom sound: %s\n", lSoundName ); + Com_Printf("Unknown custom sound: %s\n", lSoundName); #endif return 0; } @@ -331,48 +197,42 @@ CLIENT INFO ============================================================================= */ -#define MAX_SURF_LIST_SIZE 1024 -qboolean CG_ParseSurfsFile( const char *modelName, const char *skinName, char *surfOff, char *surfOn ) -{ - const char *text_p; - int len; - const char *token; - const char *value; - char text[20000]; - char sfilename[MAX_QPATH]; - fileHandle_t f; - int i = 0; - - while (skinName && skinName[i]) - { - if (skinName[i] == '|') - { //this is a multi-part skin, said skins do not support .surf files +#define MAX_SURF_LIST_SIZE 1024 +qboolean CG_ParseSurfsFile(const char *modelName, const char *skinName, char *surfOff, char *surfOn) { + const char *text_p; + int len; + const char *token; + const char *value; + char text[20000]; + char sfilename[MAX_QPATH]; + fileHandle_t f; + int i = 0; + + while (skinName && skinName[i]) { + if (skinName[i] == '|') { // this is a multi-part skin, said skins do not support .surf files return qfalse; } i++; } - // Load and parse .surf file - Com_sprintf( sfilename, sizeof( sfilename ), "models/players/%s/model_%s.surf", modelName, skinName ); + Com_sprintf(sfilename, sizeof(sfilename), "models/players/%s/model_%s.surf", modelName, skinName); // load the file - len = trap->FS_Open( sfilename, &f, FS_READ ); - if ( len <= 0 ) - {//no file + len = trap->FS_Open(sfilename, &f, FS_READ); + if (len <= 0) { // no file return qfalse; } - if ( len >= sizeof( text ) - 1 ) - { - Com_Printf( "File %s too long\n", sfilename ); - trap->FS_Close( f ); + if (len >= sizeof(text) - 1) { + Com_Printf("File %s too long\n", sfilename); + trap->FS_Close(f); return qfalse; } - trap->FS_Read( text, len, f ); + trap->FS_Read(text, len, f); text[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); // parse the text text_p = text; @@ -380,51 +240,39 @@ qboolean CG_ParseSurfsFile( const char *modelName, const char *skinName, char *s surfOff[0] = '\0'; surfOn[0] = '\0'; - COM_BeginParseSession ("CG_ParseSurfsFile"); + COM_BeginParseSession("CG_ParseSurfsFile"); // read information for surfOff and surfOn - while ( 1 ) - { - token = COM_ParseExt( &text_p, qtrue ); - if ( !token || !token[0] ) - { + while (1) { + token = COM_ParseExt(&text_p, qtrue); + if (!token || !token[0]) { break; } // surfOff - if ( !Q_stricmp( token, "surfOff" ) ) - { - if ( COM_ParseString( &text_p, &value ) ) - { + if (!Q_stricmp(token, "surfOff")) { + if (COM_ParseString(&text_p, &value)) { continue; } - if ( surfOff && surfOff[0] ) - { - Q_strcat( surfOff, MAX_SURF_LIST_SIZE, "," ); - Q_strcat( surfOff, MAX_SURF_LIST_SIZE, value ); - } - else - { - Q_strncpyz( surfOff, value, MAX_SURF_LIST_SIZE ); + if (surfOff && surfOff[0]) { + Q_strcat(surfOff, MAX_SURF_LIST_SIZE, ","); + Q_strcat(surfOff, MAX_SURF_LIST_SIZE, value); + } else { + Q_strncpyz(surfOff, value, MAX_SURF_LIST_SIZE); } continue; } // surfOn - if ( !Q_stricmp( token, "surfOn" ) ) - { - if ( COM_ParseString( &text_p, &value ) ) - { + if (!Q_stricmp(token, "surfOn")) { + if (COM_ParseString(&text_p, &value)) { continue; } - if ( surfOn && surfOn[0] ) - { - Q_strcat( surfOn, MAX_SURF_LIST_SIZE, ","); - Q_strcat( surfOn, MAX_SURF_LIST_SIZE, value ); - } - else - { - Q_strncpyz( surfOn, value, MAX_SURF_LIST_SIZE ); + if (surfOn && surfOn[0]) { + Q_strcat(surfOn, MAX_SURF_LIST_SIZE, ","); + Q_strcat(surfOn, MAX_SURF_LIST_SIZE, value); + } else { + Q_strncpyz(surfOn, value, MAX_SURF_LIST_SIZE); } continue; } @@ -438,25 +286,23 @@ CG_RegisterClientModelname ========================== */ qboolean BG_IsValidCharacterModel(const char *modelName, const char *skinName); -qboolean BG_ValidateSkinForTeam( const char *modelName, char *skinName, int team, float *colors ); +qboolean BG_ValidateSkinForTeam(const char *modelName, char *skinName, int team, float *colors); -static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelName, const char *skinName, const char *teamName, int clientNum ) { +static qboolean CG_RegisterClientModelname(clientInfo_t *ci, const char *modelName, const char *skinName, const char *teamName, int clientNum) { int handle; - char afilename[MAX_QPATH]; - char /**GLAName,*/ *slash; - char GLAName[MAX_QPATH]; - vec3_t tempVec = {0,0,0}; + char afilename[MAX_QPATH]; + char /**GLAName,*/ *slash; + char GLAName[MAX_QPATH]; + vec3_t tempVec = {0, 0, 0}; qboolean badModel = qfalse; - char surfOff[MAX_SURF_LIST_SIZE]; - char surfOn[MAX_SURF_LIST_SIZE]; - int checkSkin; - char *useSkinName; + char surfOff[MAX_SURF_LIST_SIZE]; + char surfOn[MAX_SURF_LIST_SIZE]; + int checkSkin; + char *useSkinName; retryModel: - if (badModel) - { - if (modelName && modelName[0]) - { + if (badModel) { + if (modelName && modelName[0]) { Com_Printf("WARNING: Attempted to load an unsupported multiplayer model %s! (bad or missing bone, or missing animation sequence)\n", modelName); } @@ -467,55 +313,40 @@ static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelN } // First things first. If this is a ghoul2 model, then let's make sure we demolish this first. - if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { + if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { trap->G2API_CleanGhoul2Models(&(ci->ghoul2Model)); } - if (!BG_IsValidCharacterModel(modelName, skinName)) - { + if (!BG_IsValidCharacterModel(modelName, skinName)) { modelName = DEFAULT_MODEL; skinName = "default"; } - if ( cgs.gametype >= GT_TEAM && !cgs.jediVmerc && cgs.gametype != GT_SIEGE ) - { //We won't force colors for siege. - BG_ValidateSkinForTeam( ci->modelName, ci->skinName, ci->team, ci->colorOverride ); + if (cgs.gametype >= GT_TEAM && !cgs.jediVmerc && cgs.gametype != GT_SIEGE) { // We won't force colors for siege. + BG_ValidateSkinForTeam(ci->modelName, ci->skinName, ci->team, ci->colorOverride); skinName = ci->skinName; - } - else - { + } else { ci->colorOverride[0] = ci->colorOverride[1] = ci->colorOverride[2] = 0.0f; } // fix for transparent custom skin parts - if (strchr(skinName, '|') - && strstr(skinName,"head") - && strstr(skinName,"torso") - && strstr(skinName,"lower")) - {//three part skin + if (strchr(skinName, '|') && strstr(skinName, "head") && strstr(skinName, "torso") && strstr(skinName, "lower")) { // three part skin useSkinName = va("models/players/%s/|%s", modelName, skinName); - } - else - { + } else { useSkinName = va("models/players/%s/model_%s.skin", modelName, skinName); } checkSkin = trap->R_RegisterSkin(useSkinName); - if (checkSkin) - { + if (checkSkin) { ci->torsoSkin = checkSkin; - } - else - { //fallback to the default skin + } else { // fallback to the default skin ci->torsoSkin = trap->R_RegisterSkin(va("models/players/%s/model_default.skin", modelName, skinName)); } - Com_sprintf( afilename, sizeof( afilename ), "models/players/%s/model.glm", modelName ); + Com_sprintf(afilename, sizeof(afilename), "models/players/%s/model.glm", modelName); handle = trap->G2API_InitGhoul2Model(&ci->ghoul2Model, afilename, 0, ci->torsoSkin, 0, 0, 0); - if (handle<0) - { + if (handle < 0) { return qfalse; } @@ -525,9 +356,8 @@ static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelN GLAName[0] = 0; - trap->G2API_GetGLAName( ci->ghoul2Model, 0, GLAName); - if (GLAName[0] != 0) - { + trap->G2API_GetGLAName(ci->ghoul2Model, 0, GLAName); + if (GLAName[0] != 0) { if (!strstr(GLAName, "players/_humanoid/") /*&& (!strstr(GLAName, "players/rockettrooper/") || cgs.gametype != GT_SIEGE)*/) //only allow rockettrooper in siege { //Bad! @@ -536,154 +366,130 @@ static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelN } } - if (!BGPAFtextLoaded) - { - if (GLAName[0] == 0/*GLAName == NULL*/) - { + if (!BGPAFtextLoaded) { + if (GLAName[0] == 0 /*GLAName == NULL*/) { badModel = qtrue; goto retryModel; } - Q_strncpyz( afilename, GLAName, sizeof( afilename )); - slash = Q_strrchr( afilename, '/' ); - if ( slash ) - { + Q_strncpyz(afilename, GLAName, sizeof(afilename)); + slash = Q_strrchr(afilename, '/'); + if (slash) { strcpy(slash, "/animation.cfg"); - } // Now afilename holds just the path to the animation.cfg - else - { // Didn't find any slashes, this is a raw filename right in base (whish isn't a good thing) + } // Now afilename holds just the path to the animation.cfg + else { // Didn't find any slashes, this is a raw filename right in base (whish isn't a good thing) return qfalse; } - //rww - All player models must use humanoid, no matter what. + // rww - All player models must use humanoid, no matter what. if (Q_stricmp(afilename, "models/players/_humanoid/animation.cfg") /*&& Q_stricmp(afilename, "models/players/rockettrooper/animation.cfg")*/) { - Com_Printf( "Model does not use supported animation config.\n"); + Com_Printf("Model does not use supported animation config.\n"); return qfalse; - } - else if (BG_ParseAnimationFile("models/players/_humanoid/animation.cfg", bgHumanoidAnimations, qtrue) == -1) - { - Com_Printf( "Failed to load animation file models/players/_humanoid/animation.cfg\n" ); + } else if (BG_ParseAnimationFile("models/players/_humanoid/animation.cfg", bgHumanoidAnimations, qtrue) == -1) { + Com_Printf("Failed to load animation file models/players/_humanoid/animation.cfg\n"); return qfalse; } - BG_ParseAnimationEvtFile( "models/players/_humanoid/", 0, -1 ); //get the sounds for the humanoid anims -// if (cgs.gametype == GT_SIEGE) -// { -// BG_ParseAnimationEvtFile( "models/players/rockettrooper/", 1, 1 ); //parse rockettrooper too -// } - //For the time being, we're going to have all real players use the generic humanoid soundset and that's it. - //Only npc's will use model-specific soundsets. + BG_ParseAnimationEvtFile("models/players/_humanoid/", 0, -1); // get the sounds for the humanoid anims + // if (cgs.gametype == GT_SIEGE) + // { + // BG_ParseAnimationEvtFile( "models/players/rockettrooper/", 1, 1 ); //parse rockettrooper too + // } + // For the time being, we're going to have all real players use the generic humanoid soundset and that's it. + // Only npc's will use model-specific soundsets. - // BG_ParseAnimationSndFile(va("models/players/%s/", modelName), 0, -1); - } - else if (!bgAllEvents[0].eventsParsed) - { //make sure the player anim sounds are loaded even if the anims already are - BG_ParseAnimationEvtFile( "models/players/_humanoid/", 0, -1 ); -// if (cgs.gametype == GT_SIEGE) -// { -// BG_ParseAnimationEvtFile( "models/players/rockettrooper/", 1, 1 ); -// } + // BG_ParseAnimationSndFile(va("models/players/%s/", modelName), 0, -1); + } else if (!bgAllEvents[0].eventsParsed) { // make sure the player anim sounds are loaded even if the anims already are + BG_ParseAnimationEvtFile("models/players/_humanoid/", 0, -1); + // if (cgs.gametype == GT_SIEGE) + // { + // BG_ParseAnimationEvtFile( "models/players/rockettrooper/", 1, 1 ); + // } } - if ( CG_ParseSurfsFile( modelName, skinName, surfOff, surfOn ) ) - {//turn on/off any surfs - const char *token; - const char *p; + if (CG_ParseSurfsFile(modelName, skinName, surfOff, surfOn)) { // turn on/off any surfs + const char *token; + const char *p; - //Now turn on/off any surfaces - if ( surfOff[0] ) - { + // Now turn on/off any surfaces + if (surfOff[0]) { p = surfOff; - COM_BeginParseSession ("CG_RegisterClientModelname: surfOff"); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + COM_BeginParseSession("CG_RegisterClientModelname: surfOff"); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn off this surf - trap->G2API_SetSurfaceOnOff( ci->ghoul2Model, token, 0x00000002/*G2SURFACEFLAG_OFF*/ ); + // turn off this surf + trap->G2API_SetSurfaceOnOff(ci->ghoul2Model, token, 0x00000002 /*G2SURFACEFLAG_OFF*/); } } - if ( surfOn[0] ) - { + if (surfOn[0]) { p = surfOn; - COM_BeginParseSession ("CG_RegisterClientModelname: surfOn"); - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - {//reached end of list + COM_BeginParseSession("CG_RegisterClientModelname: surfOn"); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { // reached end of list break; } - //turn on this surf - trap->G2API_SetSurfaceOnOff( ci->ghoul2Model, token, 0 ); + // turn on this surf + trap->G2API_SetSurfaceOnOff(ci->ghoul2Model, token, 0); } } } - ci->bolt_rhand = trap->G2API_AddBolt(ci->ghoul2Model, 0, "*r_hand"); - if (!trap->G2API_SetBoneAnim(ci->ghoul2Model, 0, "model_root", 0, 12, BONE_ANIM_OVERRIDE_LOOP, 1.0f, cg.time, -1, -1)) - { + if (!trap->G2API_SetBoneAnim(ci->ghoul2Model, 0, "model_root", 0, 12, BONE_ANIM_OVERRIDE_LOOP, 1.0f, cg.time, -1, -1)) { badModel = qtrue; } - if (!trap->G2API_SetBoneAngles(ci->ghoul2Model, 0, "upper_lumbar", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, cg.time)) - { + if (!trap->G2API_SetBoneAngles(ci->ghoul2Model, 0, "upper_lumbar", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, cg.time)) { badModel = qtrue; } - if (!trap->G2API_SetBoneAngles(ci->ghoul2Model, 0, "cranium", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, NULL, 0, cg.time)) - { + if (!trap->G2API_SetBoneAngles(ci->ghoul2Model, 0, "cranium", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, NULL, 0, cg.time)) { badModel = qtrue; } ci->bolt_lhand = trap->G2API_AddBolt(ci->ghoul2Model, 0, "*l_hand"); - //rhand must always be first bolt. lhand always second. Whichever you want the - //jetpack bolted to must always be third. + // rhand must always be first bolt. lhand always second. Whichever you want the + // jetpack bolted to must always be third. trap->G2API_AddBolt(ci->ghoul2Model, 0, "*chestg"); - //claw bolts + // claw bolts trap->G2API_AddBolt(ci->ghoul2Model, 0, "*r_hand_cap_r_arm"); trap->G2API_AddBolt(ci->ghoul2Model, 0, "*l_hand_cap_l_arm"); ci->bolt_head = trap->G2API_AddBolt(ci->ghoul2Model, 0, "*head_top"); - if (ci->bolt_head == -1) - { + if (ci->bolt_head == -1) { ci->bolt_head = trap->G2API_AddBolt(ci->ghoul2Model, 0, "ceyebrow"); } ci->bolt_motion = trap->G2API_AddBolt(ci->ghoul2Model, 0, "Motion"); - //We need a lower lumbar bolt for footsteps + // We need a lower lumbar bolt for footsteps ci->bolt_llumbar = trap->G2API_AddBolt(ci->ghoul2Model, 0, "lower_lumbar"); - if (ci->bolt_rhand == -1 || ci->bolt_lhand == -1 || ci->bolt_head == -1 || ci->bolt_motion == -1 || ci->bolt_llumbar == -1) - { + if (ci->bolt_rhand == -1 || ci->bolt_lhand == -1 || ci->bolt_head == -1 || ci->bolt_motion == -1 || ci->bolt_llumbar == -1) { badModel = qtrue; } - if (badModel) - { + if (badModel) { goto retryModel; } - if (!Q_stricmp(modelName, "boba_fett")) - { //special case, turn off the jetpack surfs + if (!Q_stricmp(modelName, "boba_fett")) { // special case, turn off the jetpack surfs trap->G2API_SetSurfaceOnOff(ci->ghoul2Model, "torso_rjet", TURN_OFF); trap->G2API_SetSurfaceOnOff(ci->ghoul2Model, "torso_cjet", TURN_OFF); trap->G2API_SetSurfaceOnOff(ci->ghoul2Model, "torso_ljet", TURN_OFF); } -// ent->s.radius = 90; + // ent->s.radius = 90; - if (clientNum != -1) - { + if (clientNum != -1) { /* if (cg_entities[clientNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[clientNum].ghoul2)) { @@ -695,27 +501,24 @@ static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelN cg_entities[clientNum].ghoul2weapon = NULL; } - Q_strncpyz (ci->teamName, teamName, sizeof(ci->teamName)); + Q_strncpyz(ci->teamName, teamName, sizeof(ci->teamName)); // Model icon for drawing the portrait on screen - ci->modelIcon = trap->R_RegisterShaderNoMip ( va ( "models/players/%s/icon_%s", modelName, skinName ) ); - if (!ci->modelIcon) - { - int i = 0; + ci->modelIcon = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", modelName, skinName)); + if (!ci->modelIcon) { + int i = 0; int j; char iconName[1024]; strcpy(iconName, "icon_"); j = strlen(iconName); - while (skinName[i] && skinName[i] != '|' && j < 1024) - { - iconName[j] = skinName[i]; + while (skinName[i] && skinName[i] != '|' && j < 1024) { + iconName[j] = skinName[i]; j++; i++; } iconName[j] = 0; - if (skinName[i] == '|') - { //looks like it actually may be a custom model skin, let's try getting the icon... - ci->modelIcon = trap->R_RegisterShaderNoMip ( va ( "models/players/%s/%s", modelName, iconName ) ); + if (skinName[i] == '|') { // looks like it actually may be a custom model skin, let's try getting the icon... + ci->modelIcon = trap->R_RegisterShaderNoMip(va("models/players/%s/%s", modelName, iconName)); } } return qtrue; @@ -726,25 +529,25 @@ static qboolean CG_RegisterClientModelname( clientInfo_t *ci, const char *modelN CG_ColorFromString ==================== */ -static void CG_ColorFromString( const char *v, vec3_t color ) { +static void CG_ColorFromString(const char *v, vec3_t color) { int val; - VectorClear( color ); + VectorClear(color); - val = atoi( v ); + val = atoi(v); - if ( val < 1 || val > 7 ) { - VectorSet( color, 1, 1, 1 ); + if (val < 1 || val > 7) { + VectorSet(color, 1, 1, 1); return; } - if ( val & 1 ) { + if (val & 1) { color[2] = 1.0f; } - if ( val & 2 ) { + if (val & 2) { color[1] = 1.0f; } - if ( val & 4 ) { + if (val & 4) { color[0] = 1.0f; } } @@ -754,28 +557,27 @@ static void CG_ColorFromString( const char *v, vec3_t color ) { CG_ColorFromInt ==================== */ -static void CG_ColorFromInt( int val, vec3_t color ) { - VectorClear( color ); +static void CG_ColorFromInt(int val, vec3_t color) { + VectorClear(color); - if ( val < 1 || val > 7 ) { - VectorSet( color, 1, 1, 1 ); + if (val < 1 || val > 7) { + VectorSet(color, 1, 1, 1); return; } - if ( val & 1 ) { + if (val & 1) { color[2] = 1.0f; } - if ( val & 2 ) { + if (val & 2) { color[1] = 1.0f; } - if ( val & 4 ) { + if (val & 4) { color[0] = 1.0f; } } -//load anim info -int CG_G2SkelForModel(void *g2) -{ +// load anim info +int CG_G2SkelForModel(void *g2) { int animIndex = -1; char GLAName[MAX_QPATH]; char *slash; @@ -783,9 +585,8 @@ int CG_G2SkelForModel(void *g2) GLAName[0] = 0; trap->G2API_GetGLAName(g2, 0, GLAName); - slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { + slash = Q_strrchr(GLAName, '/'); + if (slash) { strcpy(slash, "/animation.cfg"); animIndex = BG_ParseAnimationFile(GLAName, NULL, qfalse); @@ -794,15 +595,13 @@ int CG_G2SkelForModel(void *g2) return animIndex; } -//get the appropriate anim events file index -int CG_G2EvIndexForModel(void *g2, int animIndex) -{ +// get the appropriate anim events file index +int CG_G2EvIndexForModel(void *g2, int animIndex) { int evtIndex = -1; char GLAName[MAX_QPATH]; char *slash; - if (animIndex == -1) - { + if (animIndex == -1) { assert(!"shouldn't happen, bad animIndex"); return -1; } @@ -810,9 +609,8 @@ int CG_G2EvIndexForModel(void *g2, int animIndex) GLAName[0] = 0; trap->G2API_GetGLAName(g2, 0, GLAName); - slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { + slash = Q_strrchr(GLAName, '/'); + if (slash) { slash++; *slash = 0; @@ -822,42 +620,35 @@ int CG_G2EvIndexForModel(void *g2, int animIndex) return evtIndex; } -#define DEFAULT_FEMALE_SOUNDPATH "chars/mp_generic_female/misc"//"chars/tavion/misc" -#define DEFAULT_MALE_SOUNDPATH "chars/mp_generic_male/misc"//"chars/kyle/misc" -void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded) -{ +#define DEFAULT_FEMALE_SOUNDPATH "chars/mp_generic_female/misc" //"chars/tavion/misc" +#define DEFAULT_MALE_SOUNDPATH "chars/mp_generic_male/misc" //"chars/kyle/misc" +void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded) { fileHandle_t f; - qboolean isFemale = qfalse; - int i = 0; - int fLen = 0; - const char *dir; - char soundpath[MAX_QPATH]; - char soundName[1024]; - const char *s; + qboolean isFemale = qfalse; + int i = 0; + int fLen = 0; + const char *dir; + char soundpath[MAX_QPATH]; + char soundName[1024]; + const char *s; dir = ci->modelName; - if ( !ci->skinName[0] || !Q_stricmp( "default", ci->skinName ) ) - {//try default sounds.cfg first + if (!ci->skinName[0] || !Q_stricmp("default", ci->skinName)) { // try default sounds.cfg first fLen = trap->FS_Open(va("models/players/%s/sounds.cfg", dir), &f, FS_READ); - if ( !f ) - {//no? Look for _default sounds.cfg + if (!f) { // no? Look for _default sounds.cfg fLen = trap->FS_Open(va("models/players/%s/sounds_default.cfg", dir), &f, FS_READ); } - } - else - {//use the .skin associated with this skin + } else { // use the .skin associated with this skin fLen = trap->FS_Open(va("models/players/%s/sounds_%s.cfg", dir, ci->skinName), &f, FS_READ); - if ( !f ) - {//fall back to default sounds + if (!f) { // fall back to default sounds fLen = trap->FS_Open(va("models/players/%s/sounds.cfg", dir), &f, FS_READ); } } soundpath[0] = 0; - if (f) - { + if (f) { trap->FS_Read(soundpath, fLen, f); soundpath[fLen] = 0; @@ -880,18 +671,13 @@ void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded) trap->FS_Close(f); - if (isFemale) - { + if (isFemale) { ci->gender = GENDER_FEMALE; - } - else - { + } else { ci->gender = GENDER_MALE; } - } - else - { - if ( cgs.gametype != GT_SIEGE ) + } else { + if (cgs.gametype != GT_SIEGE) isFemale = ci->gender == GENDER_FEMALE; else isFemale = qfalse; @@ -899,127 +685,94 @@ void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded) trap->S_Shutup(qtrue); - for ( i = 0 ; i < MAX_CUSTOM_SOUNDS ; i++ ) - { + for (i = 0; i < MAX_CUSTOM_SOUNDS; i++) { s = cg_customSoundNames[i]; - if ( !s ) { + if (!s) { break; } - Com_sprintf(soundName, sizeof(soundName), "%s", s+1); - COM_StripExtension(soundName, soundName, sizeof( soundName ) ); - //strip the extension because we might want .mp3's + Com_sprintf(soundName, sizeof(soundName), "%s", s + 1); + COM_StripExtension(soundName, soundName, sizeof(soundName)); + // strip the extension because we might want .mp3's ci->sounds[i] = 0; // if the model didn't load use the sounds of the default model - if (soundpath[0]) - { - ci->sounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", soundpath, soundName) ); - } - else - { - if (modelloaded) - { - ci->sounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", dir, soundName) ); + if (soundpath[0]) { + ci->sounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", soundpath, soundName)); + } else { + if (modelloaded) { + ci->sounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", dir, soundName)); } } - if (!ci->sounds[i]) - { //failed the load, try one out of the generic path - if (isFemale) - { - ci->sounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName) ); - } - else - { - ci->sounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName) ); + if (!ci->sounds[i]) { // failed the load, try one out of the generic path + if (isFemale) { + ci->sounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName)); + } else { + ci->sounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName)); } } } - if (cgs.gametype >= GT_TEAM || com_buildScript.integer) - { //load the siege sounds then - for ( i = 0 ; i < MAX_CUSTOM_SIEGE_SOUNDS; i++ ) - { + if (cgs.gametype >= GT_TEAM || com_buildScript.integer) { // load the siege sounds then + for (i = 0; i < MAX_CUSTOM_SIEGE_SOUNDS; i++) { s = bg_customSiegeSoundNames[i]; - if ( !s ) - { + if (!s) { break; } - Com_sprintf(soundName, sizeof(soundName), "%s", s+1); - COM_StripExtension(soundName, soundName, sizeof( soundName ) ); - //strip the extension because we might want .mp3's + Com_sprintf(soundName, sizeof(soundName), "%s", s + 1); + COM_StripExtension(soundName, soundName, sizeof(soundName)); + // strip the extension because we might want .mp3's ci->siegeSounds[i] = 0; // if the model didn't load use the sounds of the default model - if (soundpath[0]) - { - ci->siegeSounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", soundpath, soundName) ); - if ( !ci->siegeSounds[i] ) - ci->siegeSounds[i] = trap->S_RegisterSound( va( "sound/%s/%s", soundpath, soundName ) ); - } - else - { - if (modelloaded) - { - ci->siegeSounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", dir, soundName) ); + if (soundpath[0]) { + ci->siegeSounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", soundpath, soundName)); + if (!ci->siegeSounds[i]) + ci->siegeSounds[i] = trap->S_RegisterSound(va("sound/%s/%s", soundpath, soundName)); + } else { + if (modelloaded) { + ci->siegeSounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", dir, soundName)); } } - if (!ci->siegeSounds[i]) - { //failed the load, try one out of the generic path - if (isFemale) - { - ci->siegeSounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName) ); - } - else - { - ci->siegeSounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName) ); + if (!ci->siegeSounds[i]) { // failed the load, try one out of the generic path + if (isFemale) { + ci->siegeSounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName)); + } else { + ci->siegeSounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName)); } } } } - if (cgs.gametype == GT_DUEL - ||cgs.gametype == GT_POWERDUEL - || com_buildScript.integer) - { //load the Duel sounds then - for ( i = 0 ; i < MAX_CUSTOM_DUEL_SOUNDS; i++ ) - { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL || com_buildScript.integer) { // load the Duel sounds then + for (i = 0; i < MAX_CUSTOM_DUEL_SOUNDS; i++) { s = cg_customDuelSoundNames[i]; - if ( !s ) - { + if (!s) { break; } - Com_sprintf(soundName, sizeof(soundName), "%s", s+1); - COM_StripExtension(soundName, soundName, sizeof( soundName ) ); - //strip the extension because we might want .mp3's + Com_sprintf(soundName, sizeof(soundName), "%s", s + 1); + COM_StripExtension(soundName, soundName, sizeof(soundName)); + // strip the extension because we might want .mp3's ci->duelSounds[i] = 0; // if the model didn't load use the sounds of the default model - if (soundpath[0]) - { - ci->duelSounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", soundpath, soundName) ); - } - else - { - if (modelloaded) - { - ci->duelSounds[i] = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", dir, soundName) ); + if (soundpath[0]) { + ci->duelSounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", soundpath, soundName)); + } else { + if (modelloaded) { + ci->duelSounds[i] = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", dir, soundName)); } } - if (!ci->duelSounds[i]) - { //failed the load, try one out of the generic path - if (isFemale) - { - ci->duelSounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName) ); - } - else - { - ci->duelSounds[i] = trap->S_RegisterSound( va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName) ); + if (!ci->duelSounds[i]) { // failed the load, try one out of the generic path + if (isFemale) { + ci->duelSounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_FEMALE_SOUNDPATH, soundName)); + } else { + ci->duelSounds[i] = trap->S_RegisterSound(va("sound/%s/%s", DEFAULT_MALE_SOUNDPATH, soundName)); } } } @@ -1036,20 +789,19 @@ Load it now, taking the disk hits. This will usually be deferred to a safe time =================== */ -void CG_LoadClientInfo( clientInfo_t *ci ) { - qboolean modelloaded; - int clientNum; - int i; - char teamname[MAX_QPATH]; - char *fallbackModel = DEFAULT_MODEL; - - if ( ci->gender == GENDER_FEMALE ) +void CG_LoadClientInfo(clientInfo_t *ci) { + qboolean modelloaded; + int clientNum; + int i; + char teamname[MAX_QPATH]; + char *fallbackModel = DEFAULT_MODEL; + + if (ci->gender == GENDER_FEMALE) fallbackModel = DEFAULT_MODEL_FEMALE; clientNum = ci - cgs.clientinfo; - if (clientNum < 0 || clientNum >= MAX_CLIENTS) - { + if (clientNum < 0 || clientNum >= MAX_CLIENTS) { clientNum = -1; } @@ -1078,72 +830,63 @@ void CG_LoadClientInfo( clientInfo_t *ci ) { */ teamname[0] = 0; - if( cgs.gametype >= GT_TEAM) { - if( ci->team == TEAM_BLUE ) { - Q_strncpyz(teamname, DEFAULT_BLUETEAM_NAME/*cg_blueTeamName.string*/, sizeof(teamname) ); + if (cgs.gametype >= GT_TEAM) { + if (ci->team == TEAM_BLUE) { + Q_strncpyz(teamname, DEFAULT_BLUETEAM_NAME /*cg_blueTeamName.string*/, sizeof(teamname)); } else { - Q_strncpyz(teamname, DEFAULT_REDTEAM_NAME/*cg_redTeamName.string*/, sizeof(teamname) ); + Q_strncpyz(teamname, DEFAULT_REDTEAM_NAME /*cg_redTeamName.string*/, sizeof(teamname)); } } - if( teamname[0] ) { - strcat( teamname, "/" ); + if (teamname[0]) { + strcat(teamname, "/"); } modelloaded = qtrue; if (cgs.gametype == GT_SIEGE && - (ci->team == TEAM_SPECTATOR || ci->siegeIndex == -1)) - { //yeah.. kind of a hack I guess. Don't care until they are actually ingame with a valid class. - if ( !CG_RegisterClientModelname( ci, fallbackModel, "default", teamname, -1 ) ) - { - trap->Error( ERR_DROP, "DEFAULT_MODEL (%s) failed to register", fallbackModel ); + (ci->team == TEAM_SPECTATOR || ci->siegeIndex == -1)) { // yeah.. kind of a hack I guess. Don't care until they are actually ingame with a valid class. + if (!CG_RegisterClientModelname(ci, fallbackModel, "default", teamname, -1)) { + trap->Error(ERR_DROP, "DEFAULT_MODEL (%s) failed to register", fallbackModel); } - } - else - { - if ( !CG_RegisterClientModelname( ci, ci->modelName, ci->skinName, teamname, clientNum ) ) { - //trap->Error( ERR_DROP, "CG_RegisterClientModelname( %s, %s, %s, %s %s ) failed", ci->modelName, ci->skinName, ci->headModelName, ci->headSkinName, teamname ); - //rww - DO NOT error out here! Someone could just type in a nonsense model name and crash everyone's client. - //Give it a chance to load default model for this client instead. + } else { + if (!CG_RegisterClientModelname(ci, ci->modelName, ci->skinName, teamname, clientNum)) { + // trap->Error( ERR_DROP, "CG_RegisterClientModelname( %s, %s, %s, %s %s ) failed", ci->modelName, ci->skinName, ci->headModelName, + // ci->headSkinName, teamname ); rww - DO NOT error out here! Someone could just type in a nonsense model name and crash everyone's client. Give it + // a chance to load default model for this client instead. // fall back to default team name - if( cgs.gametype >= GT_TEAM) { + if (cgs.gametype >= GT_TEAM) { // keep skin name - if( ci->team == TEAM_BLUE ) { - Q_strncpyz(teamname, DEFAULT_BLUETEAM_NAME, sizeof(teamname) ); + if (ci->team == TEAM_BLUE) { + Q_strncpyz(teamname, DEFAULT_BLUETEAM_NAME, sizeof(teamname)); } else { - Q_strncpyz(teamname, DEFAULT_REDTEAM_NAME, sizeof(teamname) ); + Q_strncpyz(teamname, DEFAULT_REDTEAM_NAME, sizeof(teamname)); } - if ( !CG_RegisterClientModelname( ci, fallbackModel, ci->skinName, teamname, -1 ) ) { - trap->Error( ERR_DROP, "DEFAULT_MODEL / skin (%s/%s) failed to register", fallbackModel, ci->skinName ); + if (!CG_RegisterClientModelname(ci, fallbackModel, ci->skinName, teamname, -1)) { + trap->Error(ERR_DROP, "DEFAULT_MODEL / skin (%s/%s) failed to register", fallbackModel, ci->skinName); } } else { - if ( !CG_RegisterClientModelname( ci, fallbackModel, "default", teamname, -1 ) ) { - trap->Error( ERR_DROP, "DEFAULT_MODEL (%s) failed to register", fallbackModel ); + if (!CG_RegisterClientModelname(ci, fallbackModel, "default", teamname, -1)) { + trap->Error(ERR_DROP, "DEFAULT_MODEL (%s) failed to register", fallbackModel); } } modelloaded = qfalse; } } - if (clientNum != -1) - { + if (clientNum != -1) { trap->G2API_ClearAttachedInstance(clientNum); } - if (clientNum != -1 && ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { - if (cg_entities[clientNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[clientNum].ghoul2)) - { + if (clientNum != -1 && ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { + if (cg_entities[clientNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[clientNum].ghoul2)) { trap->G2API_CleanGhoul2Models(&cg_entities[clientNum].ghoul2); } trap->G2API_DuplicateGhoul2Instance(ci->ghoul2Model, &cg_entities[clientNum].ghoul2); - //Attach the instance to this entity num so we can make use of client-server - //shared operations if possible. + // Attach the instance to this entity num so we can make use of client-server + // shared operations if possible. trap->G2API_AttachInstanceToEntNum(cg_entities[clientNum].ghoul2, clientNum, qfalse); - - if (trap->G2API_AddBolt(cg_entities[clientNum].ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cg_entities[clientNum].ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cg_entities[clientNum].noFace = qtrue; } @@ -1152,21 +895,17 @@ void CG_LoadClientInfo( clientInfo_t *ci ) { } ci->newAnims = qfalse; - if ( ci->torsoModel ) { + if (ci->torsoModel) { orientation_t tag; // if the torso model has the "tag_flag" - if ( trap->R_LerpTag( &tag, ci->torsoModel, 0, 0, 1, "tag_flag" ) ) { + if (trap->R_LerpTag(&tag, ci->torsoModel, 0, 0, 1, "tag_flag")) { ci->newAnims = qtrue; } } // sounds - if (cgs.gametype == GT_SIEGE && - (ci->team == TEAM_SPECTATOR || ci->siegeIndex == -1)) - { //don't need to load sounds - } - else - { + if (cgs.gametype == GT_SIEGE && (ci->team == TEAM_SPECTATOR || ci->siegeIndex == -1)) { // don't need to load sounds + } else { CG_LoadCISounds(ci, modelloaded); } @@ -1175,60 +914,47 @@ void CG_LoadClientInfo( clientInfo_t *ci ) { // reset any existing players and bodies, because they might be in bad // frames for this new model clientNum = ci - cgs.clientinfo; - for ( i = 0 ; i < MAX_GENTITIES ; i++ ) { - if ( cg_entities[i].currentState.clientNum == clientNum - && cg_entities[i].currentState.eType == ET_PLAYER ) { - CG_ResetPlayerEntity( &cg_entities[i] ); + for (i = 0; i < MAX_GENTITIES; i++) { + if (cg_entities[i].currentState.clientNum == clientNum && cg_entities[i].currentState.eType == ET_PLAYER) { + CG_ResetPlayerEntity(&cg_entities[i]); } } } - -//Take care of initializing all the ghoul2 saber stuff based on clientinfo data. -rww -static void CG_InitG2SaberData(int saberNum, clientInfo_t *ci) -{ +// Take care of initializing all the ghoul2 saber stuff based on clientinfo data. -rww +static void CG_InitG2SaberData(int saberNum, clientInfo_t *ci) { trap->G2API_InitGhoul2Model(&ci->ghoul2Weapons[saberNum], ci->saber[saberNum].model, 0, ci->saber[saberNum].skin, 0, 0, 0); - if (ci->ghoul2Weapons[saberNum]) - { + if (ci->ghoul2Weapons[saberNum]) { int k = 0; int tagBolt; char *tagName; - if (ci->saber[saberNum].skin) - { + if (ci->saber[saberNum].skin) { trap->G2API_SetSkin(ci->ghoul2Weapons[saberNum], 0, ci->saber[saberNum].skin, ci->saber[saberNum].skin); } - if (ci->saber[saberNum].saberFlags & SFL_BOLT_TO_WRIST) - { - trap->G2API_SetBoltInfo(ci->ghoul2Weapons[saberNum], 0, 3+saberNum); - } - else - { + if (ci->saber[saberNum].saberFlags & SFL_BOLT_TO_WRIST) { + trap->G2API_SetBoltInfo(ci->ghoul2Weapons[saberNum], 0, 3 + saberNum); + } else { trap->G2API_SetBoltInfo(ci->ghoul2Weapons[saberNum], 0, saberNum); } - while (k < ci->saber[saberNum].numBlades) - { - tagName = va("*blade%i", k+1); + while (k < ci->saber[saberNum].numBlades) { + tagName = va("*blade%i", k + 1); tagBolt = trap->G2API_AddBolt(ci->ghoul2Weapons[saberNum], 0, tagName); - if (tagBolt == -1) - { - if (k == 0) - { //guess this is an 0ldsk3wl saber + if (tagBolt == -1) { + if (k == 0) { // guess this is an 0ldsk3wl saber tagBolt = trap->G2API_AddBolt(ci->ghoul2Weapons[saberNum], 0, "*flash"); - if (tagBolt == -1) - { + if (tagBolt == -1) { assert(0); } break; } - if (tagBolt == -1) - { + if (tagBolt == -1) { assert(0); break; } @@ -1239,43 +965,39 @@ static void CG_InitG2SaberData(int saberNum, clientInfo_t *ci) } } - /* ====================== CG_CopyClientInfoModel ====================== */ -static void CG_CopyClientInfoModel( clientInfo_t *from, clientInfo_t *to ) -{ - VectorCopy( from->headOffset, to->headOffset ); -// to->footsteps = from->footsteps; +static void CG_CopyClientInfoModel(clientInfo_t *from, clientInfo_t *to) { + VectorCopy(from->headOffset, to->headOffset); + // to->footsteps = from->footsteps; to->gender = from->gender; to->legsModel = from->legsModel; to->legsSkin = from->legsSkin; to->torsoModel = from->torsoModel; to->torsoSkin = from->torsoSkin; - //to->headModel = from->headModel; - //to->headSkin = from->headSkin; + // to->headModel = from->headModel; + // to->headSkin = from->headSkin; to->modelIcon = from->modelIcon; to->newAnims = from->newAnims; - //to->ghoul2Model = from->ghoul2Model; - //rww - Trying to use the same ghoul2 pointer for two seperate clients == DISASTER + // to->ghoul2Model = from->ghoul2Model; + // rww - Trying to use the same ghoul2 pointer for two seperate clients == DISASTER assert(to->ghoul2Model != from->ghoul2Model); - if (to->ghoul2Model && trap->G2_HaveWeGhoul2Models(to->ghoul2Model)) - { + if (to->ghoul2Model && trap->G2_HaveWeGhoul2Models(to->ghoul2Model)) { trap->G2API_CleanGhoul2Models(&to->ghoul2Model); } - if (from->ghoul2Model && trap->G2_HaveWeGhoul2Models(from->ghoul2Model)) - { + if (from->ghoul2Model && trap->G2_HaveWeGhoul2Models(from->ghoul2Model)) { trap->G2API_DuplicateGhoul2Instance(from->ghoul2Model, &to->ghoul2Model); } - //Don't do this, I guess. Just leave the saber info in the original, so it will be - //properly initialized. + // Don't do this, I guess. Just leave the saber info in the original, so it will be + // properly initialized. /* strcpy(to->saberName, from->saberName); strcpy(to->saber2Name, from->saber2Name); @@ -1312,9 +1034,9 @@ static void CG_CopyClientInfoModel( clientInfo_t *from, clientInfo_t *to ) to->siegeIndex = from->siegeIndex; - memcpy( to->sounds, from->sounds, sizeof( to->sounds ) ); - memcpy( to->siegeSounds, from->siegeSounds, sizeof( to->siegeSounds ) ); - memcpy( to->duelSounds, from->duelSounds, sizeof( to->duelSounds ) ); + memcpy(to->sounds, from->sounds, sizeof(to->sounds)); + memcpy(to->siegeSounds, from->siegeSounds, sizeof(to->siegeSounds)); + memcpy(to->duelSounds, from->duelSounds, sizeof(to->duelSounds)); } /* @@ -1322,50 +1044,46 @@ static void CG_CopyClientInfoModel( clientInfo_t *from, clientInfo_t *to ) CG_ScanForExistingClientInfo ====================== */ -static qboolean CG_ScanForExistingClientInfo( clientInfo_t *ci, int clientNum ) { - int i; - clientInfo_t *match; +static qboolean CG_ScanForExistingClientInfo(clientInfo_t *ci, int clientNum) { + int i; + clientInfo_t *match; - for ( i = 0 ; i < cgs.maxclients ; i++ ) { - match = &cgs.clientinfo[ i ]; - if ( !match->infoValid ) { + for (i = 0; i < cgs.maxclients; i++) { + match = &cgs.clientinfo[i]; + if (!match->infoValid) { continue; } - if ( match->deferred ) { + if (match->deferred) { continue; } - if ( !Q_stricmp( ci->modelName, match->modelName ) - && !Q_stricmp( ci->skinName, match->skinName ) - && !Q_stricmp( ci->saberName, match->saberName) - && !Q_stricmp( ci->saber2Name, match->saber2Name) -// && !Q_stricmp( ci->headModelName, match->headModelName ) -// && !Q_stricmp( ci->headSkinName, match->headSkinName ) -// && !Q_stricmp( ci->blueTeam, match->blueTeam ) -// && !Q_stricmp( ci->redTeam, match->redTeam ) - && (cgs.gametype < GT_TEAM || ci->team == match->team) - && ci->siegeIndex == match->siegeIndex - && match->ghoul2Model - && match->bolt_head) //if the bolts haven't been initialized, this "match" is useless to us + if (!Q_stricmp(ci->modelName, match->modelName) && !Q_stricmp(ci->skinName, match->skinName) && !Q_stricmp(ci->saberName, match->saberName) && + !Q_stricmp(ci->saber2Name, match->saber2Name) + // && !Q_stricmp( ci->headModelName, match->headModelName ) + // && !Q_stricmp( ci->headSkinName, match->headSkinName ) + // && !Q_stricmp( ci->blueTeam, match->blueTeam ) + // && !Q_stricmp( ci->redTeam, match->redTeam ) + && (cgs.gametype < GT_TEAM || ci->team == match->team) && ci->siegeIndex == match->siegeIndex && match->ghoul2Model && + match->bolt_head) // if the bolts haven't been initialized, this "match" is useless to us { // this clientinfo is identical, so use it's handles ci->deferred = qfalse; - //rww - Filthy hack. If this is actually the info already belonging to us, just reassign the pointer. - //Switching instances when not necessary produces small animation glitches. - //Actually, before, were we even freeing the instance attached to the old clientinfo before copying - //this new clientinfo over it? Could be a nasty leak possibility. (though this should remedy it in theory) - if (clientNum == i) - { - if (match->ghoul2Model && trap->G2_HaveWeGhoul2Models(match->ghoul2Model)) - { //The match has a valid instance (if it didn't, we'd probably already be fudged (^_^) at this state) - if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { //First kill the copy we have if we have one. (but it should be null) + // rww - Filthy hack. If this is actually the info already belonging to us, just reassign the pointer. + // Switching instances when not necessary produces small animation glitches. + // Actually, before, were we even freeing the instance attached to the old clientinfo before copying + // this new clientinfo over it? Could be a nasty leak possibility. (though this should remedy it in theory) + if (clientNum == i) { + if (match->ghoul2Model && + trap->G2_HaveWeGhoul2Models( + match->ghoul2Model)) { // The match has a valid instance (if it didn't, we'd probably already be fudged (^_^) at this state) + if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { // First kill the copy we have if we have one. (but it should be + // null) trap->G2API_CleanGhoul2Models(&ci->ghoul2Model); } - VectorCopy( match->headOffset, ci->headOffset ); -// ci->footsteps = match->footsteps; + VectorCopy(match->headOffset, ci->headOffset); + // ci->footsteps = match->footsteps; ci->gender = match->gender; ci->legsModel = match->legsModel; @@ -1383,17 +1101,17 @@ static qboolean CG_ScanForExistingClientInfo( clientInfo_t *ci, int clientNum ) ci->bolt_llumbar = match->bolt_llumbar; ci->siegeIndex = match->siegeIndex; - memcpy( ci->sounds, match->sounds, sizeof( ci->sounds ) ); - memcpy( ci->siegeSounds, match->siegeSounds, sizeof( ci->siegeSounds ) ); - memcpy( ci->duelSounds, match->duelSounds, sizeof( ci->duelSounds ) ); + memcpy(ci->sounds, match->sounds, sizeof(ci->sounds)); + memcpy(ci->siegeSounds, match->siegeSounds, sizeof(ci->siegeSounds)); + memcpy(ci->duelSounds, match->duelSounds, sizeof(ci->duelSounds)); - //We can share this pointer, because it already belongs to this client. - //The pointer itself and the ghoul2 instance is never actually changed, just passed between - //clientinfo structures. + // We can share this pointer, because it already belongs to this client. + // The pointer itself and the ghoul2 instance is never actually changed, just passed between + // clientinfo structures. ci->ghoul2Model = match->ghoul2Model; - //Don't need to do this I guess, whenever this function is called the saber stuff should - //already be taken care of in the new info. + // Don't need to do this I guess, whenever this function is called the saber stuff should + // already be taken care of in the new info. /* while (k < MAX_SABERS) { @@ -1403,16 +1121,14 @@ static qboolean CG_ScanForExistingClientInfo( clientInfo_t *ci, int clientNum ) { trap->G2API_CleanGhoul2Models(&ci->ghoul2Weapons[k]); } - ci->ghoul2Weapons[k] = match->ghoul2Weapons[k]; + ci->ghoul2Weapons[k] = match->ghoul2Weapons[k]; } k++; } */ } - } - else - { - CG_CopyClientInfoModel( match, ci ); + } else { + CG_CopyClientInfoModel(match, ci); } return qtrue; @@ -1431,48 +1147,45 @@ We aren't going to load it now, so grab some other client's info to use until we have some spare time. ====================== */ -static void CG_SetDeferredClientInfo( clientInfo_t *ci ) { - int i; - clientInfo_t *match; +static void CG_SetDeferredClientInfo(clientInfo_t *ci) { + int i; + clientInfo_t *match; // if someone else is already the same models and skins we // can just load the client info - for ( i = 0 ; i < cgs.maxclients ; i++ ) { - match = &cgs.clientinfo[ i ]; - if ( !match->infoValid || match->deferred ) { + for (i = 0; i < cgs.maxclients; i++) { + match = &cgs.clientinfo[i]; + if (!match->infoValid || match->deferred) { continue; } - if ( Q_stricmp( ci->skinName, match->skinName ) || - Q_stricmp( ci->modelName, match->modelName ) || -// Q_stricmp( ci->headModelName, match->headModelName ) || -// Q_stricmp( ci->headSkinName, match->headSkinName ) || - (cgs.gametype >= GT_TEAM && ci->team != match->team && ci->team != TEAM_SPECTATOR) ) { + if (Q_stricmp(ci->skinName, match->skinName) || Q_stricmp(ci->modelName, match->modelName) || + // Q_stricmp( ci->headModelName, match->headModelName ) || + // Q_stricmp( ci->headSkinName, match->headSkinName ) || + (cgs.gametype >= GT_TEAM && ci->team != match->team && ci->team != TEAM_SPECTATOR)) { continue; } - /* - if (Q_stricmp(ci->saberName, match->saberName) || - Q_stricmp(ci->saber2Name, match->saber2Name)) - { - continue; - } - */ + /* + if (Q_stricmp(ci->saberName, match->saberName) || + Q_stricmp(ci->saber2Name, match->saber2Name)) + { + continue; + } + */ // just load the real info cause it uses the same models and skins - CG_LoadClientInfo( ci ); + CG_LoadClientInfo(ci); return; } // if we are in teamplay, only grab a model if the skin is correct - if ( cgs.gametype >= GT_TEAM ) { - for ( i = 0 ; i < cgs.maxclients ; i++ ) { - match = &cgs.clientinfo[ i ]; - if ( !match->infoValid || match->deferred ) { + if (cgs.gametype >= GT_TEAM) { + for (i = 0; i < cgs.maxclients; i++) { + match = &cgs.clientinfo[i]; + if (!match->infoValid || match->deferred) { continue; } - if ( ci->team != TEAM_SPECTATOR && - (Q_stricmp( ci->skinName, match->skinName ) || - (cgs.gametype >= GT_TEAM && ci->team != match->team)) ) { + if (ci->team != TEAM_SPECTATOR && (Q_stricmp(ci->skinName, match->skinName) || (cgs.gametype >= GT_TEAM && ci->team != match->team))) { continue; } @@ -1485,21 +1198,21 @@ static void CG_SetDeferredClientInfo( clientInfo_t *ci ) { */ ci->deferred = qtrue; - CG_CopyClientInfoModel( match, ci ); + CG_CopyClientInfoModel(match, ci); return; } // load the full model, because we don't ever want to show // an improper team skin. This will cause a hitch for the first // player, when the second enters. Combat shouldn't be going on // yet, so it shouldn't matter - CG_LoadClientInfo( ci ); + CG_LoadClientInfo(ci); return; } // find the first valid clientinfo and grab its stuff - for ( i = 0 ; i < cgs.maxclients ; i++ ) { - match = &cgs.clientinfo[ i ]; - if ( !match->infoValid ) { + for (i = 0; i < cgs.maxclients; i++) { + match = &cgs.clientinfo[i]; + if (!match->infoValid) { continue; } @@ -1511,21 +1224,20 @@ static void CG_SetDeferredClientInfo( clientInfo_t *ci ) { } */ - if (match->deferred) - { //no deferring off of deferred info. Because I said so. + if (match->deferred) { // no deferring off of deferred info. Because I said so. continue; } ci->deferred = qtrue; - CG_CopyClientInfoModel( match, ci ); + CG_CopyClientInfoModel(match, ci); return; } // we should never get here... - //trap->Print( "CG_SetDeferredClientInfo: no valid clients!\n" ); - //Actually it is possible now because of the unique sabers. + // trap->Print( "CG_SetDeferredClientInfo: no valid clients!\n" ); + // Actually it is possible now because of the unique sabers. - CG_LoadClientInfo( ci ); + CG_LoadClientInfo(ci); } /* @@ -1533,14 +1245,14 @@ static void CG_SetDeferredClientInfo( clientInfo_t *ci ) { CG_NewClientInfo ====================== */ -void WP_SetSaber( int entNum, saberInfo_t *sabers, int saberNum, const char *saberName ); +void WP_SetSaber(int entNum, saberInfo_t *sabers, int saberNum, const char *saberName); -void CG_NewClientInfo( int clientNum, qboolean entitiesInitialized ) { +void CG_NewClientInfo(int clientNum, qboolean entitiesInitialized) { clientInfo_t *ci; clientInfo_t newInfo; - const char *configstring; - const char *v; - char *slash; + const char *configstring; + const char *v; + char *slash; void *oldGhoul2; void *oldG2Weapons[MAX_SABERS]; int i = 0; @@ -1551,190 +1263,175 @@ void CG_NewClientInfo( int clientNum, qboolean entitiesInitialized ) { oldGhoul2 = ci->ghoul2Model; - while (k < MAX_SABERS) - { + while (k < MAX_SABERS) { oldG2Weapons[k] = ci->ghoul2Weapons[k]; k++; } - configstring = CG_ConfigString( clientNum + CS_PLAYERS ); - if ( !configstring[0] ) { - if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { //clean this stuff up first + configstring = CG_ConfigString(clientNum + CS_PLAYERS); + if (!configstring[0]) { + if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { // clean this stuff up first trap->G2API_CleanGhoul2Models(&ci->ghoul2Model); } k = 0; - while (k < MAX_SABERS) - { - if (ci->ghoul2Weapons[k] && trap->G2_HaveWeGhoul2Models(ci->ghoul2Weapons[k])) - { + while (k < MAX_SABERS) { + if (ci->ghoul2Weapons[k] && trap->G2_HaveWeGhoul2Models(ci->ghoul2Weapons[k])) { trap->G2API_CleanGhoul2Models(&ci->ghoul2Weapons[k]); } k++; } - memset( ci, 0, sizeof( *ci ) ); - return; // player just left + memset(ci, 0, sizeof(*ci)); + return; // player just left } // build into a temp buffer so the defer checks can use // the old value - memset( &newInfo, 0, sizeof( newInfo ) ); + memset(&newInfo, 0, sizeof(newInfo)); // isolate the player's name v = Info_ValueForKey(configstring, "n"); - Q_strncpyz( newInfo.name, v, sizeof( newInfo.name ) ); - Q_strncpyz( newInfo.cleanname, v, sizeof( newInfo.cleanname ) ); - Q_StripColor( newInfo.cleanname ); + Q_strncpyz(newInfo.name, v, sizeof(newInfo.name)); + Q_strncpyz(newInfo.cleanname, v, sizeof(newInfo.cleanname)); + Q_StripColor(newInfo.cleanname); // colors - v = Info_ValueForKey( configstring, "c1" ); - CG_ColorFromString( v, newInfo.color1 ); + v = Info_ValueForKey(configstring, "c1"); + CG_ColorFromString(v, newInfo.color1); newInfo.icolor1 = atoi(v); - v = Info_ValueForKey( configstring, "c2" ); - CG_ColorFromString( v, newInfo.color2 ); + v = Info_ValueForKey(configstring, "c2"); + CG_ColorFromString(v, newInfo.color2); newInfo.icolor2 = atoi(v); // bot skill - v = Info_ValueForKey( configstring, "skill" ); + v = Info_ValueForKey(configstring, "skill"); // players have -1 skill so you can determine the bots from the scoreboard code - if ( v && v[0] ) - newInfo.botSkill = atoi( v ); + if (v && v[0]) + newInfo.botSkill = atoi(v); else newInfo.botSkill = -1; // handicap - v = Info_ValueForKey( configstring, "hc" ); - newInfo.handicap = atoi( v ); + v = Info_ValueForKey(configstring, "hc"); + newInfo.handicap = atoi(v); // wins - v = Info_ValueForKey( configstring, "w" ); - newInfo.wins = atoi( v ); + v = Info_ValueForKey(configstring, "w"); + newInfo.wins = atoi(v); // losses - v = Info_ValueForKey( configstring, "l" ); - newInfo.losses = atoi( v ); + v = Info_ValueForKey(configstring, "l"); + newInfo.losses = atoi(v); // team - v = Info_ValueForKey( configstring, "t" ); - newInfo.team = atoi( v ); + v = Info_ValueForKey(configstring, "t"); + newInfo.team = atoi(v); -//copy team info out to menu - if ( clientNum == cg.clientNum) //this is me + // copy team info out to menu + if (clientNum == cg.clientNum) // this is me { trap->Cvar_Set("ui_team", v); } // Gender hints - if ( (v = Info_ValueForKey( configstring, "ds" )) ) - { - if ( *v == 'f' ) + if ((v = Info_ValueForKey(configstring, "ds"))) { + if (*v == 'f') newInfo.gender = GENDER_FEMALE; else newInfo.gender = GENDER_MALE; } // team task - v = Info_ValueForKey( configstring, "tt" ); + v = Info_ValueForKey(configstring, "tt"); newInfo.teamTask = atoi(v); // team leader - v = Info_ValueForKey( configstring, "tl" ); + v = Info_ValueForKey(configstring, "tl"); newInfo.teamLeader = atoi(v); -// v = Info_ValueForKey( configstring, "g_redteam" ); -// Q_strncpyz(newInfo.redTeam, v, MAX_TEAMNAME); + // v = Info_ValueForKey( configstring, "g_redteam" ); + // Q_strncpyz(newInfo.redTeam, v, MAX_TEAMNAME); -// v = Info_ValueForKey( configstring, "g_blueteam" ); -// Q_strncpyz(newInfo.blueTeam, v, MAX_TEAMNAME); + // v = Info_ValueForKey( configstring, "g_blueteam" ); + // Q_strncpyz(newInfo.blueTeam, v, MAX_TEAMNAME); // model - v = Info_ValueForKey( configstring, "model" ); - if ( cg_forceModel.integer ) { + v = Info_ValueForKey(configstring, "model"); + if (cg_forceModel.integer) { // forcemodel makes everyone use a single model // to prevent load hitches char modelStr[MAX_QPATH]; char *skin; - trap->Cvar_VariableStringBuffer( "model", modelStr, sizeof( modelStr ) ); - if ( ( skin = strchr( modelStr, '/' ) ) == NULL) { + trap->Cvar_VariableStringBuffer("model", modelStr, sizeof(modelStr)); + if ((skin = strchr(modelStr, '/')) == NULL) { skin = "default"; } else { *skin++ = 0; } - Q_strncpyz( newInfo.skinName, skin, sizeof( newInfo.skinName ) ); - Q_strncpyz( newInfo.modelName, modelStr, sizeof( newInfo.modelName ) ); + Q_strncpyz(newInfo.skinName, skin, sizeof(newInfo.skinName)); + Q_strncpyz(newInfo.modelName, modelStr, sizeof(newInfo.modelName)); - if ( cgs.gametype >= GT_TEAM ) { + if (cgs.gametype >= GT_TEAM) { // keep skin name - slash = strchr( v, '/' ); - if ( slash ) { - Q_strncpyz( newInfo.skinName, slash + 1, sizeof( newInfo.skinName ) ); + slash = strchr(v, '/'); + if (slash) { + Q_strncpyz(newInfo.skinName, slash + 1, sizeof(newInfo.skinName)); } } } else { - Q_strncpyz( newInfo.modelName, v, sizeof( newInfo.modelName ) ); + Q_strncpyz(newInfo.modelName, v, sizeof(newInfo.modelName)); - slash = strchr( newInfo.modelName, '/' ); - if ( !slash ) { + slash = strchr(newInfo.modelName, '/'); + if (!slash) { // modelName didn not include a skin name - Q_strncpyz( newInfo.skinName, "default", sizeof( newInfo.skinName ) ); + Q_strncpyz(newInfo.skinName, "default", sizeof(newInfo.skinName)); } else { - Q_strncpyz( newInfo.skinName, slash + 1, sizeof( newInfo.skinName ) ); + Q_strncpyz(newInfo.skinName, slash + 1, sizeof(newInfo.skinName)); // truncate modelName *slash = 0; } } - if (cgs.gametype == GT_SIEGE) - { //entries only sent in siege mode - //siege desired team - v = Info_ValueForKey( configstring, "sdt" ); - if (v && v[0]) - { - newInfo.siegeDesiredTeam = atoi(v); - } - else - { + if (cgs.gametype == GT_SIEGE) { // entries only sent in siege mode + // siege desired team + v = Info_ValueForKey(configstring, "sdt"); + if (v && v[0]) { + newInfo.siegeDesiredTeam = atoi(v); + } else { newInfo.siegeDesiredTeam = 0; } - //siege classname - v = Info_ValueForKey( configstring, "siegeclass" ); + // siege classname + v = Info_ValueForKey(configstring, "siegeclass"); newInfo.siegeIndex = -1; - if (v) - { + if (v) { siegeClass_t *siegeClass = BG_SiegeFindClassByName(v); - if (siegeClass) - { //See if this class forces a model, if so, then use it. Same for skin. + if (siegeClass) { // See if this class forces a model, if so, then use it. Same for skin. newInfo.siegeIndex = BG_SiegeFindClassIndexByName(v); - if (siegeClass->forcedModel[0]) - { - Q_strncpyz( newInfo.modelName, siegeClass->forcedModel, sizeof( newInfo.modelName ) ); + if (siegeClass->forcedModel[0]) { + Q_strncpyz(newInfo.modelName, siegeClass->forcedModel, sizeof(newInfo.modelName)); } - if (siegeClass->forcedSkin[0]) - { - Q_strncpyz( newInfo.skinName, siegeClass->forcedSkin, sizeof( newInfo.skinName ) ); + if (siegeClass->forcedSkin[0]) { + Q_strncpyz(newInfo.skinName, siegeClass->forcedSkin, sizeof(newInfo.skinName)); } - if (siegeClass->hasForcedSaberColor) - { + if (siegeClass->hasForcedSaberColor) { newInfo.icolor1 = siegeClass->forcedSaberColor; - CG_ColorFromInt( newInfo.icolor1, newInfo.color1 ); + CG_ColorFromInt(newInfo.icolor1, newInfo.color1); } - if (siegeClass->hasForcedSaber2Color) - { + if (siegeClass->hasForcedSaber2Color) { newInfo.icolor2 = siegeClass->forcedSaber2Color; - CG_ColorFromInt( newInfo.icolor2, newInfo.color2 ); + CG_ColorFromInt(newInfo.icolor2, newInfo.color2); } } } @@ -1743,244 +1440,201 @@ void CG_NewClientInfo( int clientNum, qboolean entitiesInitialized ) { saberUpdate[0] = qfalse; saberUpdate[1] = qfalse; - //saber being used - v = Info_ValueForKey( configstring, "st" ); + // saber being used + v = Info_ValueForKey(configstring, "st"); - if (v && Q_stricmp(v, ci->saberName)) - { - Q_strncpyz( newInfo.saberName, v, 64 ); + if (v && Q_stricmp(v, ci->saberName)) { + Q_strncpyz(newInfo.saberName, v, 64); WP_SetSaber(clientNum, newInfo.saber, 0, newInfo.saberName); saberUpdate[0] = qtrue; - } - else - { - Q_strncpyz( newInfo.saberName, ci->saberName, 64 ); + } else { + Q_strncpyz(newInfo.saberName, ci->saberName, 64); memcpy(&newInfo.saber[0], &ci->saber[0], sizeof(newInfo.saber[0])); newInfo.ghoul2Weapons[0] = ci->ghoul2Weapons[0]; } - v = Info_ValueForKey( configstring, "st2" ); + v = Info_ValueForKey(configstring, "st2"); - if (v && Q_stricmp(v, ci->saber2Name)) - { - Q_strncpyz( newInfo.saber2Name, v, 64 ); + if (v && Q_stricmp(v, ci->saber2Name)) { + Q_strncpyz(newInfo.saber2Name, v, 64); WP_SetSaber(clientNum, newInfo.saber, 1, newInfo.saber2Name); saberUpdate[1] = qtrue; - } - else - { - Q_strncpyz( newInfo.saber2Name, ci->saber2Name, 64 ); + } else { + Q_strncpyz(newInfo.saber2Name, ci->saber2Name, 64); memcpy(&newInfo.saber[1], &ci->saber[1], sizeof(newInfo.saber[1])); newInfo.ghoul2Weapons[1] = ci->ghoul2Weapons[1]; } - if (saberUpdate[0] || saberUpdate[1]) - { + if (saberUpdate[0] || saberUpdate[1]) { int j = 0; - while (j < MAX_SABERS) - { - if (saberUpdate[j]) - { - if (newInfo.saber[j].model[0]) - { - if (oldG2Weapons[j]) - { //free the old instance(s) + while (j < MAX_SABERS) { + if (saberUpdate[j]) { + if (newInfo.saber[j].model[0]) { + if (oldG2Weapons[j]) { // free the old instance(s) trap->G2API_CleanGhoul2Models(&oldG2Weapons[j]); oldG2Weapons[j] = 0; } CG_InitG2SaberData(j, &newInfo); - } - else - { - if (oldG2Weapons[j]) - { //free the old instance(s) + } else { + if (oldG2Weapons[j]) { // free the old instance(s) trap->G2API_CleanGhoul2Models(&oldG2Weapons[j]); oldG2Weapons[j] = 0; } } cg_entities[clientNum].weapon = 0; - cg_entities[clientNum].ghoul2weapon = NULL; //force a refresh + cg_entities[clientNum].ghoul2weapon = NULL; // force a refresh } j++; } } - //Check for any sabers that didn't get set again, if they didn't, then reassign the pointers for the new ci + // Check for any sabers that didn't get set again, if they didn't, then reassign the pointers for the new ci k = 0; - while (k < MAX_SABERS) - { - if (oldG2Weapons[k]) - { + while (k < MAX_SABERS) { + if (oldG2Weapons[k]) { newInfo.ghoul2Weapons[k] = oldG2Weapons[k]; } k++; } - //duel team - v = Info_ValueForKey( configstring, "dt" ); + // duel team + v = Info_ValueForKey(configstring, "dt"); - if (v) - { + if (v) { newInfo.duelTeam = atoi(v); - } - else - { + } else { newInfo.duelTeam = 0; } // force powers - v = Info_ValueForKey( configstring, "forcepowers" ); - Q_strncpyz( newInfo.forcePowers, v, sizeof( newInfo.forcePowers ) ); + v = Info_ValueForKey(configstring, "forcepowers"); + Q_strncpyz(newInfo.forcePowers, v, sizeof(newInfo.forcePowers)); - if (cgs.gametype >= GT_TEAM && !cgs.jediVmerc && cgs.gametype != GT_SIEGE ) - { //We won't force colors for siege. - BG_ValidateSkinForTeam( newInfo.modelName, newInfo.skinName, newInfo.team, newInfo.colorOverride ); - } - else - { + if (cgs.gametype >= GT_TEAM && !cgs.jediVmerc && cgs.gametype != GT_SIEGE) { // We won't force colors for siege. + BG_ValidateSkinForTeam(newInfo.modelName, newInfo.skinName, newInfo.team, newInfo.colorOverride); + } else { newInfo.colorOverride[0] = newInfo.colorOverride[1] = newInfo.colorOverride[2] = 0.0f; } // scan for an existing clientinfo that matches this modelname // so we can avoid loading checks if possible - if ( !CG_ScanForExistingClientInfo( &newInfo, clientNum ) ) { + if (!CG_ScanForExistingClientInfo(&newInfo, clientNum)) { // if we are defering loads, just have it pick the first valid - if (cg.snap && cg.snap->ps.clientNum == clientNum) - { //rww - don't defer your own client info ever - CG_LoadClientInfo( &newInfo ); - } - else if ( cg_deferPlayers.integer && cgs.gametype != GT_SIEGE && !com_buildScript.integer && !cg.loading ) { + if (cg.snap && cg.snap->ps.clientNum == clientNum) { // rww - don't defer your own client info ever + CG_LoadClientInfo(&newInfo); + } else if (cg_deferPlayers.integer && cgs.gametype != GT_SIEGE && !com_buildScript.integer && !cg.loading) { // keep whatever they had if it won't violate team skins - CG_SetDeferredClientInfo( &newInfo ); + CG_SetDeferredClientInfo(&newInfo); } else { - CG_LoadClientInfo( &newInfo ); + CG_LoadClientInfo(&newInfo); } } // replace whatever was there with the new one newInfo.infoValid = qtrue; - if (ci->ghoul2Model && - ci->ghoul2Model != newInfo.ghoul2Model && - trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { //We must kill this instance before we remove our only pointer to it from the cgame. - //Otherwise we will end up with extra instances all over the place, I think. + if (ci->ghoul2Model && ci->ghoul2Model != newInfo.ghoul2Model && + trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { // We must kill this instance before we remove our only pointer to it from the cgame. + // Otherwise we will end up with extra instances all over the place, I think. trap->G2API_CleanGhoul2Models(&ci->ghoul2Model); } *ci = newInfo; - //force a weapon change anyway, for all clients being rendered to the current client - while (i < MAX_CLIENTS) - { + // force a weapon change anyway, for all clients being rendered to the current client + while (i < MAX_CLIENTS) { cg_entities[i].ghoul2weapon = NULL; i++; } - if (clientNum != -1) - { //don't want it using an invalid pointer to share + if (clientNum != -1) { // don't want it using an invalid pointer to share trap->G2API_ClearAttachedInstance(clientNum); } // Check if the ghoul2 model changed in any way. This is safer than assuming we have a legal cent shile loading info. - if (entitiesInitialized && ci->ghoul2Model && (oldGhoul2 != ci->ghoul2Model)) - { // Copy the new ghoul2 model to the centity. + if (entitiesInitialized && ci->ghoul2Model && (oldGhoul2 != ci->ghoul2Model)) { // Copy the new ghoul2 model to the centity. animation_t *anim; centity_t *cent = &cg_entities[clientNum]; - anim = &bgHumanoidAnimations[ (cg_entities[clientNum].currentState.legsAnim) ]; + anim = &bgHumanoidAnimations[(cg_entities[clientNum].currentState.legsAnim)]; - if (anim) - { + if (anim) { int flags = BONE_ANIM_OVERRIDE_FREEZE; int firstFrame = anim->firstFrame; int setFrame = -1; float animSpeed = 50.0f / anim->frameLerp; - if (anim->loopFrames != -1) - { + if (anim->loopFrames != -1) { flags = BONE_ANIM_OVERRIDE_LOOP; } - if (cent->pe.legs.frame >= anim->firstFrame && cent->pe.legs.frame <= (anim->firstFrame + anim->numFrames)) - { + if (cent->pe.legs.frame >= anim->firstFrame && cent->pe.legs.frame <= (anim->firstFrame + anim->numFrames)) { setFrame = cent->pe.legs.frame; } - //rww - Set the animation again because it just got reset due to the model change + // rww - Set the animation again because it just got reset due to the model change trap->G2API_SetBoneAnim(ci->ghoul2Model, 0, "model_root", firstFrame, anim->firstFrame + anim->numFrames, flags, animSpeed, cg.time, setFrame, 150); cg_entities[clientNum].currentState.legsAnim = 0; } - anim = &bgHumanoidAnimations[ (cg_entities[clientNum].currentState.torsoAnim) ]; + anim = &bgHumanoidAnimations[(cg_entities[clientNum].currentState.torsoAnim)]; - if (anim) - { + if (anim) { int flags = BONE_ANIM_OVERRIDE_FREEZE; int firstFrame = anim->firstFrame; int setFrame = -1; float animSpeed = 50.0f / anim->frameLerp; - if (anim->loopFrames != -1) - { + if (anim->loopFrames != -1) { flags = BONE_ANIM_OVERRIDE_LOOP; } - if (cent->pe.torso.frame >= anim->firstFrame && cent->pe.torso.frame <= (anim->firstFrame + anim->numFrames)) - { + if (cent->pe.torso.frame >= anim->firstFrame && cent->pe.torso.frame <= (anim->firstFrame + anim->numFrames)) { setFrame = cent->pe.torso.frame; } - //rww - Set the animation again because it just got reset due to the model change - trap->G2API_SetBoneAnim(ci->ghoul2Model, 0, "lower_lumbar", firstFrame, anim->firstFrame + anim->numFrames, flags, animSpeed, cg.time, setFrame, 150); + // rww - Set the animation again because it just got reset due to the model change + trap->G2API_SetBoneAnim(ci->ghoul2Model, 0, "lower_lumbar", firstFrame, anim->firstFrame + anim->numFrames, flags, animSpeed, cg.time, setFrame, + 150); cg_entities[clientNum].currentState.torsoAnim = 0; } - if (cg_entities[clientNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[clientNum].ghoul2)) - { + if (cg_entities[clientNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[clientNum].ghoul2)) { trap->G2API_CleanGhoul2Models(&cg_entities[clientNum].ghoul2); } trap->G2API_DuplicateGhoul2Instance(ci->ghoul2Model, &cg_entities[clientNum].ghoul2); - if (clientNum != -1) - { - //Attach the instance to this entity num so we can make use of client-server - //shared operations if possible. + if (clientNum != -1) { + // Attach the instance to this entity num so we can make use of client-server + // shared operations if possible. trap->G2API_AttachInstanceToEntNum(cg_entities[clientNum].ghoul2, clientNum, qfalse); } - if (trap->G2API_AddBolt(cg_entities[clientNum].ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cg_entities[clientNum].ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cg_entities[clientNum].noFace = qtrue; } cg_entities[clientNum].localAnimIndex = CG_G2SkelForModel(cg_entities[clientNum].ghoul2); cg_entities[clientNum].eventAnimIndex = CG_G2EvIndexForModel(cg_entities[clientNum].ghoul2, cg_entities[clientNum].localAnimIndex); - if (cg_entities[clientNum].currentState.number != cg.predictedPlayerState.clientNum && - cg_entities[clientNum].currentState.weapon == WP_SABER) - { + if (cg_entities[clientNum].currentState.number != cg.predictedPlayerState.clientNum && cg_entities[clientNum].currentState.weapon == WP_SABER) { cg_entities[clientNum].weapon = cg_entities[clientNum].currentState.weapon; - if (cg_entities[clientNum].ghoul2 && ci->ghoul2Model) - { + if (cg_entities[clientNum].ghoul2 && ci->ghoul2Model) { CG_CopyG2WeaponInstance(&cg_entities[clientNum], cg_entities[clientNum].currentState.weapon, cg_entities[clientNum].ghoul2); cg_entities[clientNum].ghoul2weapon = CG_G2WeaponInstance(&cg_entities[clientNum], cg_entities[clientNum].currentState.weapon); } - if (!cg_entities[clientNum].currentState.saberHolstered) - { //if not holstered set length and desired length for both blades to full right now. + if (!cg_entities[clientNum].currentState.saberHolstered) { // if not holstered set length and desired length for both blades to full right now. int j; BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); i = 0; - while (i < MAX_SABERS) - { + while (i < MAX_SABERS) { j = 0; - while (j < ci->saber[i].numBlades) - { + while (j < ci->saber[i].numBlades) { ci->saber[i].blade[j].length = ci->saber[i].blade[j].lengthMax; j++; } @@ -1991,7 +1645,6 @@ void CG_NewClientInfo( int clientNum, qboolean entitiesInitialized ) { } } - qboolean cgQueueLoad = qfalse; /* ====================== @@ -2000,16 +1653,15 @@ CG_ActualLoadDeferredPlayers Called at the beginning of CG_Player if cgQueueLoad is set. ====================== */ -void CG_ActualLoadDeferredPlayers( void ) -{ - int i; - clientInfo_t *ci; +void CG_ActualLoadDeferredPlayers(void) { + int i; + clientInfo_t *ci; // scan for a deferred player to load - for ( i = 0, ci = cgs.clientinfo ; i < cgs.maxclients ; i++, ci++ ) { - if ( ci->infoValid && ci->deferred ) { - CG_LoadClientInfo( ci ); -// break; + for (i = 0, ci = cgs.clientinfo; i < cgs.maxclients; i++, ci++) { + if (ci->infoValid && ci->deferred) { + CG_LoadClientInfo(ci); + // break; } } } @@ -2023,9 +1675,7 @@ and the scoreboard is up so deferred players can be loaded ====================== */ -void CG_LoadDeferredPlayers( void ) { - cgQueueLoad = qtrue; -} +void CG_LoadDeferredPlayers(void) { cgQueueLoad = qtrue; } /* ============================================================================= @@ -2035,174 +1685,163 @@ PLAYER ANIMATION ============================================================================= */ -#define FOOTSTEP_DISTANCE 32 -static void _PlayerFootStep( const vec3_t origin, - const float orientation, - const float radius, - centity_t *const cent, footstepType_t footStepType ) -{ - vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; - trace_t trace; - footstep_t soundType = FOOTSTEP_TOTAL; - qboolean bMark = qfalse; +#define FOOTSTEP_DISTANCE 32 +static void _PlayerFootStep(const vec3_t origin, const float orientation, const float radius, centity_t *const cent, footstepType_t footStepType) { + vec3_t end, mins = {-7, -7, 0}, maxs = {7, 7, 2}; + trace_t trace; + footstep_t soundType = FOOTSTEP_TOTAL; + qboolean bMark = qfalse; qhandle_t footMarkShader; - int effectID = -1; - //float alpha; + int effectID = -1; + // float alpha; // send a trace down from the player to the ground - VectorCopy( origin, end ); + VectorCopy(origin, end); end[2] -= FOOTSTEP_DISTANCE; - trap->CM_Trace( &trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0); + trap->CM_Trace(&trace, origin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0); // no shadow if too high - if ( trace.fraction >= 1.0f ) - { + if (trace.fraction >= 1.0f) { return; } - //check for foot-steppable surface flag - switch( trace.surfaceFlags & MATERIAL_MASK ) - { - case MATERIAL_MUD: - bMark = qtrue; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_MUDRUN; - } else { - soundType = FOOTSTEP_MUDWALK; - } - effectID = cgs.effects.footstepMud; - break; - case MATERIAL_DIRT: - bMark = qtrue; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_DIRTRUN; - } else { - soundType = FOOTSTEP_DIRTWALK; - } - effectID = cgs.effects.footstepSand; - break; - case MATERIAL_SAND: - bMark = qtrue; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_SANDRUN; - } else { - soundType = FOOTSTEP_SANDWALK; - } - effectID = cgs.effects.footstepSand; - break; - case MATERIAL_SNOW: - bMark = qtrue; - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_SNOWRUN; - } else { - soundType = FOOTSTEP_SNOWWALK; - } - effectID = cgs.effects.footstepSnow; - break; - case MATERIAL_SHORTGRASS: - case MATERIAL_LONGGRASS: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_GRASSRUN; - } else { - soundType = FOOTSTEP_GRASSWALK; - } - break; - case MATERIAL_SOLIDMETAL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_METALRUN; - } else { - soundType = FOOTSTEP_METALWALK; - } - break; - case MATERIAL_HOLLOWMETAL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_PIPERUN; - } else { - soundType = FOOTSTEP_PIPEWALK; - } - break; - case MATERIAL_GRAVEL: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_GRAVELRUN; - } else { - soundType = FOOTSTEP_GRAVELWALK; - } - effectID = cgs.effects.footstepGravel; - break; - case MATERIAL_CARPET: - case MATERIAL_FABRIC: - case MATERIAL_CANVAS: - case MATERIAL_RUBBER: - case MATERIAL_PLASTIC: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_RUGRUN; - } else { - soundType = FOOTSTEP_RUGWALK; - } - break; - case MATERIAL_SOLIDWOOD: - case MATERIAL_HOLLOWWOOD: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_WOODRUN; - } else { - soundType = FOOTSTEP_WOODWALK; - } - break; + // check for foot-steppable surface flag + switch (trace.surfaceFlags & MATERIAL_MASK) { + case MATERIAL_MUD: + bMark = qtrue; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_MUDRUN; + } else { + soundType = FOOTSTEP_MUDWALK; + } + effectID = cgs.effects.footstepMud; + break; + case MATERIAL_DIRT: + bMark = qtrue; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_DIRTRUN; + } else { + soundType = FOOTSTEP_DIRTWALK; + } + effectID = cgs.effects.footstepSand; + break; + case MATERIAL_SAND: + bMark = qtrue; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_SANDRUN; + } else { + soundType = FOOTSTEP_SANDWALK; + } + effectID = cgs.effects.footstepSand; + break; + case MATERIAL_SNOW: + bMark = qtrue; + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_SNOWRUN; + } else { + soundType = FOOTSTEP_SNOWWALK; + } + effectID = cgs.effects.footstepSnow; + break; + case MATERIAL_SHORTGRASS: + case MATERIAL_LONGGRASS: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_GRASSRUN; + } else { + soundType = FOOTSTEP_GRASSWALK; + } + break; + case MATERIAL_SOLIDMETAL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_METALRUN; + } else { + soundType = FOOTSTEP_METALWALK; + } + break; + case MATERIAL_HOLLOWMETAL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_PIPERUN; + } else { + soundType = FOOTSTEP_PIPEWALK; + } + break; + case MATERIAL_GRAVEL: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_GRAVELRUN; + } else { + soundType = FOOTSTEP_GRAVELWALK; + } + effectID = cgs.effects.footstepGravel; + break; + case MATERIAL_CARPET: + case MATERIAL_FABRIC: + case MATERIAL_CANVAS: + case MATERIAL_RUBBER: + case MATERIAL_PLASTIC: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_RUGRUN; + } else { + soundType = FOOTSTEP_RUGWALK; + } + break; + case MATERIAL_SOLIDWOOD: + case MATERIAL_HOLLOWWOOD: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_WOODRUN; + } else { + soundType = FOOTSTEP_WOODWALK; + } + break; - default: - //fall through - case MATERIAL_GLASS: - case MATERIAL_WATER: - case MATERIAL_FLESH: - case MATERIAL_BPGLASS: - case MATERIAL_DRYLEAVES: - case MATERIAL_GREENLEAVES: - case MATERIAL_TILES: - case MATERIAL_PLASTER: - case MATERIAL_SHATTERGLASS: - case MATERIAL_ARMOR: - case MATERIAL_COMPUTER: - - case MATERIAL_CONCRETE: - case MATERIAL_ROCK: - case MATERIAL_ICE: - case MATERIAL_MARBLE: - if ( footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { - soundType = FOOTSTEP_STONERUN; - } else { - soundType = FOOTSTEP_STONEWALK; - } - break; + default: + // fall through + case MATERIAL_GLASS: + case MATERIAL_WATER: + case MATERIAL_FLESH: + case MATERIAL_BPGLASS: + case MATERIAL_DRYLEAVES: + case MATERIAL_GREENLEAVES: + case MATERIAL_TILES: + case MATERIAL_PLASTER: + case MATERIAL_SHATTERGLASS: + case MATERIAL_ARMOR: + case MATERIAL_COMPUTER: + + case MATERIAL_CONCRETE: + case MATERIAL_ROCK: + case MATERIAL_ICE: + case MATERIAL_MARBLE: + if (footStepType == FOOTSTEP_HEAVY_R || footStepType == FOOTSTEP_HEAVY_L) { + soundType = FOOTSTEP_STONERUN; + } else { + soundType = FOOTSTEP_STONEWALK; + } + break; } - if (soundType < FOOTSTEP_TOTAL) - { - trap->S_StartSound( NULL, cent->currentState.clientNum, CHAN_BODY, cgs.media.footsteps[soundType][rand()&3] ); + if (soundType < FOOTSTEP_TOTAL) { + trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_BODY, cgs.media.footsteps[soundType][rand() & 3]); } - if ( cg_footsteps.integer < 4 ) - {//debugging - 4 always does footstep effect - if ( cg_footsteps.integer < 2 ) //1 for sounds, 2 for effects, 3 for marks + if (cg_footsteps.integer < 4) { // debugging - 4 always does footstep effect + if (cg_footsteps.integer < 2) // 1 for sounds, 2 for effects, 3 for marks { return; } } - if ( effectID != -1 ) - { - trap->FX_PlayEffectID( effectID, trace.endpos, trace.plane.normal, -1, -1, qfalse ); + if (effectID != -1) { + trap->FX_PlayEffectID(effectID, trace.endpos, trace.plane.normal, -1, -1, qfalse); } - if ( cg_footsteps.integer < 4 ) - {//debugging - 4 always does footstep effect - if ( !bMark || cg_footsteps.integer < 3 ) //1 for sounds, 2 for effects, 3 for marks + if (cg_footsteps.integer < 4) { // debugging - 4 always does footstep effect + if (!bMark || cg_footsteps.integer < 3) // 1 for sounds, 2 for effects, 3 for marks { return; } } - switch ( footStepType ) - { + switch (footStepType) { case FOOTSTEP_HEAVY_R: footMarkShader = cgs.media.fshrMarkShader; break; @@ -2219,181 +1858,141 @@ static void _PlayerFootStep( const vec3_t origin, } // fade the shadow out with height -// alpha = 1.0 - trace.fraction; + // alpha = 1.0 - trace.fraction; // add the mark as a temporary, so it goes directly to the renderer // without taking a spot in the cg_marks array - if (trace.plane.normal[0] || trace.plane.normal[1] || trace.plane.normal[2]) - { - CG_ImpactMark( footMarkShader, trace.endpos, trace.plane.normal, - orientation, 1,1,1, 1.0f, qfalse, radius, qfalse ); + if (trace.plane.normal[0] || trace.plane.normal[1] || trace.plane.normal[2]) { + CG_ImpactMark(footMarkShader, trace.endpos, trace.plane.normal, orientation, 1, 1, 1, 1.0f, qfalse, radius, qfalse); } } -static void CG_PlayerFootsteps( centity_t *cent, footstepType_t footStepType ) -{ - if ( !cg_footsteps.integer ) - { +static void CG_PlayerFootsteps(centity_t *cent, footstepType_t footStepType) { + if (!cg_footsteps.integer) { return; } - //FIXME: make this a feature of NPCs in the NPCs.cfg? Specify a footstep shader, if any? - if ( cent->currentState.NPC_class != CLASS_ATST - && cent->currentState.NPC_class != CLASS_CLAW - && cent->currentState.NPC_class != CLASS_FISH - && cent->currentState.NPC_class != CLASS_FLIER2 - && cent->currentState.NPC_class != CLASS_GLIDER - && cent->currentState.NPC_class != CLASS_INTERROGATOR - && cent->currentState.NPC_class != CLASS_MURJJ - && cent->currentState.NPC_class != CLASS_PROBE - && cent->currentState.NPC_class != CLASS_R2D2 - && cent->currentState.NPC_class != CLASS_R5D2 - && cent->currentState.NPC_class != CLASS_REMOTE - && cent->currentState.NPC_class != CLASS_SEEKER - && cent->currentState.NPC_class != CLASS_SENTRY - && cent->currentState.NPC_class != CLASS_SWAMP ) - { - mdxaBone_t boltMatrix; + // FIXME: make this a feature of NPCs in the NPCs.cfg? Specify a footstep shader, if any? + if (cent->currentState.NPC_class != CLASS_ATST && cent->currentState.NPC_class != CLASS_CLAW && cent->currentState.NPC_class != CLASS_FISH && + cent->currentState.NPC_class != CLASS_FLIER2 && cent->currentState.NPC_class != CLASS_GLIDER && cent->currentState.NPC_class != CLASS_INTERROGATOR && + cent->currentState.NPC_class != CLASS_MURJJ && cent->currentState.NPC_class != CLASS_PROBE && cent->currentState.NPC_class != CLASS_R2D2 && + cent->currentState.NPC_class != CLASS_R5D2 && cent->currentState.NPC_class != CLASS_REMOTE && cent->currentState.NPC_class != CLASS_SEEKER && + cent->currentState.NPC_class != CLASS_SENTRY && cent->currentState.NPC_class != CLASS_SWAMP) { + mdxaBone_t boltMatrix; vec3_t tempAngles, sideOrigin; int footBolt = -1; - tempAngles[PITCH] = 0; - tempAngles[YAW] = cent->pe.legs.yawAngle; - tempAngles[ROLL] = 0; + tempAngles[PITCH] = 0; + tempAngles[YAW] = cent->pe.legs.yawAngle; + tempAngles[ROLL] = 0; - switch ( footStepType ) - { + switch (footStepType) { case FOOTSTEP_R: case FOOTSTEP_HEAVY_R: - footBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_leg_foot");//cent->gent->footRBolt; + footBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_leg_foot"); // cent->gent->footRBolt; break; case FOOTSTEP_L: case FOOTSTEP_HEAVY_L: default: - footBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_leg_foot");//cent->gent->footLBolt; + footBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_leg_foot"); // cent->gent->footLBolt; break; } - - //FIXME: get yaw orientation of the foot and use on decal - trap->G2API_GetBoltMatrix( cent->ghoul2, 0, footBolt, &boltMatrix, tempAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, sideOrigin ); - sideOrigin[2] += 15; //fudge up a bit for coplanar - _PlayerFootStep( sideOrigin, cent->pe.legs.yawAngle, 6, cent, footStepType ); + // FIXME: get yaw orientation of the foot and use on decal + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, footBolt, &boltMatrix, tempAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, sideOrigin); + sideOrigin[2] += 15; // fudge up a bit for coplanar + _PlayerFootStep(sideOrigin, cent->pe.legs.yawAngle, 6, cent, footStepType); } } -void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) -{ +void CG_PlayerAnimEventDo(centity_t *cent, animevent_t *animEvent) { soundChannel_t channel = CHAN_AUTO; clientInfo_t *client = NULL; qhandle_t swingSound = 0; qhandle_t spinSound = 0; - if ( !cent || !animEvent ) - { + if (!cent || !animEvent) { return; } - switch ( animEvent->eventType ) - { + switch (animEvent->eventType) { case AEV_SOUNDCHAN: channel = (soundChannel_t)animEvent->eventData[AED_SOUNDCHANNEL]; - case AEV_SOUND: - { // are there variations on the sound? - const int holdSnd = animEvent->eventData[ AED_SOUNDINDEX_START+Q_irand( 0, animEvent->eventData[AED_SOUND_NUMRANDOMSNDS] ) ]; - if ( holdSnd > 0 ) - { - trap->S_StartSound( NULL, cent->currentState.number, channel, holdSnd ); - } + case AEV_SOUND: { // are there variations on the sound? + const int holdSnd = animEvent->eventData[AED_SOUNDINDEX_START + Q_irand(0, animEvent->eventData[AED_SOUND_NUMRANDOMSNDS])]; + if (holdSnd > 0) { + trap->S_StartSound(NULL, cent->currentState.number, channel, holdSnd); } - break; + } break; case AEV_SABER_SWING: - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { client = cent->npcClient; assert(client); - } - else - { + } else { client = &cgs.clientinfo[cent->currentState.clientNum]; } - if ( client && client->infoValid && client->saber[animEvent->eventData[AED_SABER_SWING_SABERNUM]].swingSound[0] ) - {//custom swing sound - swingSound = client->saber[0].swingSound[Q_irand(0,2)]; - } - else - { - int randomSwing = 1; - switch ( animEvent->eventData[AED_SABER_SWING_TYPE] ) - { + if (client && client->infoValid && client->saber[animEvent->eventData[AED_SABER_SWING_SABERNUM]].swingSound[0]) { // custom swing sound + swingSound = client->saber[0].swingSound[Q_irand(0, 2)]; + } else { + int randomSwing = 1; + switch (animEvent->eventData[AED_SABER_SWING_TYPE]) { default: - case 0://SWING_FAST - randomSwing = Q_irand( 1, 3 ); + case 0: // SWING_FAST + randomSwing = Q_irand(1, 3); break; - case 1://SWING_MEDIUM - randomSwing = Q_irand( 4, 6 ); + case 1: // SWING_MEDIUM + randomSwing = Q_irand(4, 6); break; - case 2://SWING_STRONG - randomSwing = Q_irand( 7, 9 ); + case 2: // SWING_STRONG + randomSwing = Q_irand(7, 9); break; } swingSound = trap->S_RegisterSound(va("sound/weapons/saber/saberhup%i.wav", randomSwing)); } - trap->S_StartSound(cent->currentState.pos.trBase, cent->currentState.number, CHAN_AUTO, swingSound ); + trap->S_StartSound(cent->currentState.pos.trBase, cent->currentState.number, CHAN_AUTO, swingSound); break; case AEV_SABER_SPIN: - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { client = cent->npcClient; assert(client); - } - else - { + } else { client = &cgs.clientinfo[cent->currentState.clientNum]; } - if ( client - && client->infoValid - && client->saber[AED_SABER_SPIN_SABERNUM].spinSound ) - {//use override + if (client && client->infoValid && client->saber[AED_SABER_SPIN_SABERNUM].spinSound) { // use override spinSound = client->saber[AED_SABER_SPIN_SABERNUM].spinSound; - } - else - { - switch ( animEvent->eventData[AED_SABER_SPIN_TYPE] ) - { - case 0://saberspinoff - spinSound = trap->S_RegisterSound( "sound/weapons/saber/saberspinoff.wav" ); + } else { + switch (animEvent->eventData[AED_SABER_SPIN_TYPE]) { + case 0: // saberspinoff + spinSound = trap->S_RegisterSound("sound/weapons/saber/saberspinoff.wav"); break; - case 1://saberspin - spinSound = trap->S_RegisterSound( "sound/weapons/saber/saberspin.wav" ); + case 1: // saberspin + spinSound = trap->S_RegisterSound("sound/weapons/saber/saberspin.wav"); break; - case 2://saberspin1 - spinSound = trap->S_RegisterSound( "sound/weapons/saber/saberspin1.wav" ); + case 2: // saberspin1 + spinSound = trap->S_RegisterSound("sound/weapons/saber/saberspin1.wav"); break; - case 3://saberspin2 - spinSound = trap->S_RegisterSound( "sound/weapons/saber/saberspin2.wav" ); + case 3: // saberspin2 + spinSound = trap->S_RegisterSound("sound/weapons/saber/saberspin2.wav"); break; - case 4://saberspin3 - spinSound = trap->S_RegisterSound( "sound/weapons/saber/saberspin3.wav" ); + case 4: // saberspin3 + spinSound = trap->S_RegisterSound("sound/weapons/saber/saberspin3.wav"); break; - default://random saberspin1-3 - spinSound = trap->S_RegisterSound( va( "sound/weapons/saber/saberspin%d.wav", Q_irand(1,3)) ); + default: // random saberspin1-3 + spinSound = trap->S_RegisterSound(va("sound/weapons/saber/saberspin%d.wav", Q_irand(1, 3))); break; } } - if ( spinSound ) - { - trap->S_StartSound( NULL, cent->currentState.clientNum, CHAN_AUTO, spinSound ); + if (spinSound) { + trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_AUTO, spinSound); } break; case AEV_FOOTSTEP: - CG_PlayerFootsteps( cent, (footstepType_t)animEvent->eventData[AED_FOOTSTEP_TYPE] ); + CG_PlayerFootsteps(cent, (footstepType_t)animEvent->eventData[AED_FOOTSTEP_TYPE]); break; case AEV_EFFECT: -#if 0 //SP method - //add bolt, play effect +#if 0 // SP method + // add bolt, play effect if ( animEvent->stringData != NULL && cent && cent->gent && cent->gent->ghoul2.size() ) {//have a bolt name we want to use animEvent->eventData[AED_BOLTINDEX] = gi.G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); @@ -2407,31 +2006,22 @@ void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) {//play at origin? FIXME: maybe allow a fwd/rt/up offset? theFxScheduler.PlayEffect( animEvent->eventData[AED_EFFECTINDEX], cent->lerpOrigin, qfalse ); } -#else //my method - if (animEvent->stringData && animEvent->stringData[0] && cent && cent->ghoul2) - { +#else // my method + if (animEvent->stringData && animEvent->stringData[0] && cent && cent->ghoul2) { animEvent->eventData[AED_MODELINDEX] = 0; - if ( ( Q_stricmpn( "*blade", animEvent->stringData, 6 ) == 0 - || Q_stricmp( "*flash", animEvent->stringData ) == 0 ) ) - {//must be a weapon, try weapon 0? - animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt( cent->ghoul2, 1, animEvent->stringData ); - if ( animEvent->eventData[AED_BOLTINDEX] != -1 ) - {//found it! + if ((Q_stricmpn("*blade", animEvent->stringData, 6) == 0 || Q_stricmp("*flash", animEvent->stringData) == 0)) { // must be a weapon, try weapon 0? + animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt(cent->ghoul2, 1, animEvent->stringData); + if (animEvent->eventData[AED_BOLTINDEX] != -1) { // found it! animEvent->eventData[AED_MODELINDEX] = 1; + } else { // hmm, just try on the player model, then? + animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt(cent->ghoul2, 0, animEvent->stringData); } - else - {//hmm, just try on the player model, then? - animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt( cent->ghoul2, 0, animEvent->stringData ); - } - } - else - { - animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt( cent->ghoul2, 0, animEvent->stringData ); + } else { + animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt(cent->ghoul2, 0, animEvent->stringData); } animEvent->stringData[0] = 0; } - if ( animEvent->eventData[AED_BOLTINDEX] != -1 ) - { + if (animEvent->eventData[AED_BOLTINDEX] != -1) { vec3_t lAngles; vec3_t bPoint, bAngle; mdxaBone_t matrix; @@ -2439,14 +2029,12 @@ void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) VectorSet(lAngles, 0, cent->lerpAngles[YAW], 0); trap->G2API_GetBoltMatrix(cent->ghoul2, animEvent->eventData[AED_MODELINDEX], animEvent->eventData[AED_BOLTINDEX], &matrix, lAngles, - cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, bPoint); VectorSet(bAngle, 0, 1, 0); trap->FX_PlayEffectID(animEvent->eventData[AED_EFFECTINDEX], bPoint, bAngle, -1, -1, qfalse); - } - else - { + } else { vec3_t bAngle; VectorSet(bAngle, 0, 1, 0); @@ -2454,7 +2042,7 @@ void CG_PlayerAnimEventDo( centity_t *cent, animevent_t *animEvent ) } #endif break; - //Would have to keep track of this on server to for these, it's not worth it. + // Would have to keep track of this on server to for these, it's not worth it. case AEV_FIRE: case AEV_MOVE: break; @@ -2508,26 +2096,20 @@ void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, play any keyframed sounds - only when start a new frame This func is called once for legs and once for torso */ -void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, int oldFrame, int frame, int entNum ) -{ - int i; - int firstFrame = 0, lastFrame = 0; - qboolean doEvent = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; +void CG_PlayerAnimEvents(int animFileIndex, int eventFileIndex, qboolean torso, int oldFrame, int frame, int entNum) { + int i; + int firstFrame = 0, lastFrame = 0; + qboolean doEvent = qfalse, inSameAnim = qfalse, loopAnim = qfalse, match = qfalse, animBackward = qfalse; animevent_t *animEvents = NULL; - if ( torso ) - { + if (torso) { animEvents = bgAllEvents[eventFileIndex].torsoAnimEvents; - } - else - { + } else { animEvents = bgAllEvents[eventFileIndex].legsAnimEvents; } - if ( fabs((float)(oldFrame-frame)) > 1 ) - {//given a range, see if keyFrame falls in that range + if (fabs((float)(oldFrame - frame)) > 1) { // given a range, see if keyFrame falls in that range int oldAnim, anim; - if ( torso ) - { + if (torso) { /* if ( cg_reliableAnimSounds.integer > 1 ) {//more precise, slower @@ -2536,13 +2118,11 @@ void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, } else */ - {//less precise, but faster + { // less precise, but faster oldAnim = cg_entities[entNum].currentState.torsoAnim; anim = cg_entities[entNum].nextState.torsoAnim; } - } - else - { + } else { /* if ( cg_reliableAnimSounds.integer > 1 ) {//more precise, slower @@ -2551,83 +2131,58 @@ void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, } else */ - {//less precise, but faster + { // less precise, but faster oldAnim = cg_entities[entNum].currentState.legsAnim; anim = cg_entities[entNum].nextState.legsAnim; } } - if ( anim != oldAnim ) - {//not in same anim + if (anim != oldAnim) { // not in same anim inSameAnim = qfalse; - //FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... - } - else - {//still in same anim, check for looping anim + // FIXME: we *could* see if the oldFrame was *just about* to play the keyframed sound... + } else { // still in same anim, check for looping anim animation_t *animation; inSameAnim = qtrue; animation = &bgAllAnims[animFileIndex].anims[anim]; - animBackward = (animation->frameLerp<0); - if ( animation->loopFrames != -1 ) - {//a looping anim! + animBackward = (animation->frameLerp < 0); + if (animation->loopFrames != -1) { // a looping anim! loopAnim = qtrue; firstFrame = animation->firstFrame; - lastFrame = animation->firstFrame+animation->numFrames; + lastFrame = animation->firstFrame + animation->numFrames; } } } // Check for anim sound - for (i=0;i 1 /*&& cg_reliableAnimSounds.integer*/ ) - {//given a range, see if keyFrame falls in that range - if ( inSameAnim ) - {//if changed anims altogether, sorry, the sound is lost - if ( fabs((float)(oldFrame-animEvents[i].keyFrame)) <= 3 - || fabs((float)(frame-animEvents[i].keyFrame)) <= 3 ) - {//must be at least close to the keyframe - if ( animBackward ) - {//animation plays backwards - if ( oldFrame > animEvents[i].keyFrame && frame < animEvents[i].keyFrame ) - {//old to new passed through keyframe + } else if (fabs((float)(oldFrame - frame)) > 1 /*&& cg_reliableAnimSounds.integer*/) { // given a range, see if keyFrame falls in that range + if (inSameAnim) { // if changed anims altogether, sorry, the sound is lost + if (fabs((float)(oldFrame - animEvents[i].keyFrame)) <= 3 || + fabs((float)(frame - animEvents[i].keyFrame)) <= 3) { // must be at least close to the keyframe + if (animBackward) { // animation plays backwards + if (oldFrame > animEvents[i].keyFrame && frame < animEvents[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame > animEvents[i].keyFrame - && frame > oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame > animEvents[i].keyFrame && frame > oldFrame) { // old to new passed through keyframe match = qtrue; } } } - } - else - {//anim plays forwards - if ( oldFrame < animEvents[i].keyFrame && frame > animEvents[i].keyFrame ) - {//old to new passed through keyframe + } else { // anim plays forwards + if (oldFrame < animEvents[i].keyFrame && frame > animEvents[i].keyFrame) { // old to new passed through keyframe match = qtrue; - } - else if ( loopAnim ) - {//hmm, didn't pass through it linearally, see if we looped - if ( animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame ) - {//keyframe is in this anim - if ( oldFrame < animEvents[i].keyFrame - && frame < oldFrame ) - {//old to new passed through keyframe + } else if (loopAnim) { // hmm, didn't pass through it linearally, see if we looped + if (animEvents[i].keyFrame >= firstFrame && animEvents[i].keyFrame < lastFrame) { // keyframe is in this anim + if (oldFrame < animEvents[i].keyFrame && frame < oldFrame) { // old to new passed through keyframe match = qtrue; } } @@ -2636,74 +2191,60 @@ void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, } } } - if ( match ) - { - switch ( animEvents[i].eventType ) - { + if (match) { + switch (animEvents[i].eventType) { case AEV_SOUND: case AEV_SOUNDCHAN: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SOUND_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SOUND_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SOUND_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SOUND_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_SABER_SWING: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SABER_SWING_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SABER_SWING_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SABER_SWING_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SABER_SWING_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_SABER_SPIN: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_SABER_SPIN_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_FOOTSTEP: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_FOOTSTEP_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_EFFECT: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_EFFECT_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_EFFECT_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_EFFECT_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_EFFECT_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; case AEV_FIRE: // Determine probability of playing sound - if (!animEvents[i].eventData[AED_FIRE_PROBABILITY]) // 100% + if (!animEvents[i].eventData[AED_FIRE_PROBABILITY]) // 100% { doEvent = qtrue; - } - else if (animEvents[i].eventData[AED_FIRE_PROBABILITY] > Q_irand(0, 99) ) - { + } else if (animEvents[i].eventData[AED_FIRE_PROBABILITY] > Q_irand(0, 99)) { doEvent = qtrue; } break; @@ -2711,67 +2252,57 @@ void CG_PlayerAnimEvents( int animFileIndex, int eventFileIndex, qboolean torso, doEvent = qtrue; break; default: - //doEvent = qfalse;//implicit + // doEvent = qfalse;//implicit break; } // do event - if ( doEvent ) - { - CG_PlayerAnimEventDo( &cg_entities[entNum], &animEvents[i] ); + if (doEvent) { + CG_PlayerAnimEventDo(&cg_entities[entNum], &animEvents[i]); } } } } -void CG_TriggerAnimSounds( centity_t *cent ) -{ //this also sets the lerp frames, so I suggest you keep calling it regardless of if you want anim sounds. - int curFrame = 0; - float currentFrame = 0; - int sFileIndex; +void CG_TriggerAnimSounds(centity_t *cent) { // this also sets the lerp frames, so I suggest you keep calling it regardless of if you want anim sounds. + int curFrame = 0; + float currentFrame = 0; + int sFileIndex; assert(cent->localAnimIndex >= 0); sFileIndex = cent->eventAnimIndex; - if (trap->G2API_GetBoneFrame(cent->ghoul2, "model_root", cg.time, ¤tFrame, cgs.gameModels, 0)) - { + if (trap->G2API_GetBoneFrame(cent->ghoul2, "model_root", cg.time, ¤tFrame, cgs.gameModels, 0)) { // the above may have failed, not sure what to do about it, current frame will be zero in that case - curFrame = floor( currentFrame ); + curFrame = floor(currentFrame); } - if ( curFrame != cent->pe.legs.frame ) - { - CG_PlayerAnimEvents( cent->localAnimIndex, sFileIndex, qfalse, cent->pe.legs.frame, curFrame, cent->currentState.number ); + if (curFrame != cent->pe.legs.frame) { + CG_PlayerAnimEvents(cent->localAnimIndex, sFileIndex, qfalse, cent->pe.legs.frame, curFrame, cent->currentState.number); } cent->pe.legs.oldFrame = cent->pe.legs.frame; cent->pe.legs.frame = curFrame; - if (cent->noLumbar) - { //probably a droid or something. + if (cent->noLumbar) { // probably a droid or something. cent->pe.torso.oldFrame = cent->pe.legs.oldFrame; cent->pe.torso.frame = cent->pe.legs.frame; return; } - if (trap->G2API_GetBoneFrame(cent->ghoul2, "lower_lumbar", cg.time, ¤tFrame, cgs.gameModels, 0)) - { - curFrame = floor( currentFrame ); + if (trap->G2API_GetBoneFrame(cent->ghoul2, "lower_lumbar", cg.time, ¤tFrame, cgs.gameModels, 0)) { + curFrame = floor(currentFrame); } - if ( curFrame != cent->pe.torso.frame ) - { - CG_PlayerAnimEvents( cent->localAnimIndex, sFileIndex, qtrue, cent->pe.torso.frame, curFrame, cent->currentState.number ); + if (curFrame != cent->pe.torso.frame) { + CG_PlayerAnimEvents(cent->localAnimIndex, sFileIndex, qtrue, cent->pe.torso.frame, curFrame, cent->currentState.number); } cent->pe.torso.oldFrame = cent->pe.torso.frame; cent->pe.torso.frame = curFrame; cent->pe.torso.backlerp = 1.0f - (currentFrame - (float)curFrame); } - static qboolean CG_FirstAnimFrame(lerpFrame_t *lf, qboolean torsoOnly, float speedScale); -qboolean CG_InRoll( centity_t *cent ) -{ - switch ( (cent->currentState.legsAnim) ) - { +qboolean CG_InRoll(centity_t *cent) { + switch ((cent->currentState.legsAnim)) { case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_BROLL_L: @@ -2784,8 +2315,7 @@ qboolean CG_InRoll( centity_t *cent ) case BOTH_ROLL_B: case BOTH_ROLL_R: case BOTH_ROLL_L: - if ( cent->pe.legs.animationTime > cg.time ) - { + if (cent->pe.legs.animationTime > cg.time) { return qtrue; } break; @@ -2793,10 +2323,8 @@ qboolean CG_InRoll( centity_t *cent ) return qfalse; } -qboolean CG_InRollAnim( centity_t *cent ) -{ - switch ( (cent->currentState.legsAnim) ) - { +qboolean CG_InRollAnim(centity_t *cent) { + switch ((cent->currentState.legsAnim)) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: @@ -2811,18 +2339,18 @@ qboolean CG_InRollAnim( centity_t *cent ) CG_SetLerpFrameAnimation =============== */ -qboolean BG_SaberStanceAnim( int anim ); -qboolean PM_RunningAnim( int anim ); -static void CG_SetLerpFrameAnimation( centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float animSpeedMult, qboolean torsoOnly, qboolean flipState) { - animation_t *anim; +qboolean BG_SaberStanceAnim(int anim); +qboolean PM_RunningAnim(int anim); +static void CG_SetLerpFrameAnimation(centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, int newAnimation, float animSpeedMult, qboolean torsoOnly, + qboolean flipState) { + animation_t *anim; float animSpeed; - int flags=BONE_ANIM_OVERRIDE_FREEZE; + int flags = BONE_ANIM_OVERRIDE_FREEZE; int oldAnim = -1; int blendTime = 100; float oldSpeed = lf->animationSpeed; - if (cent->localAnimIndex > 0) - { //rockettroopers can't have broken arms, nor can anything else but humanoids + if (cent->localAnimIndex > 0) { // rockettroopers can't have broken arms, nor can anything else but humanoids ci->brokenLimbs = cent->currentState.brokenLimbs; } @@ -2830,192 +2358,162 @@ static void CG_SetLerpFrameAnimation( centity_t *cent, clientInfo_t *ci, lerpFra lf->animationNumber = newAnimation; - if ( newAnimation < 0 || newAnimation >= MAX_TOTALANIMATIONS ) { - trap->Error( ERR_DROP, "Bad animation number: %i", newAnimation ); + if (newAnimation < 0 || newAnimation >= MAX_TOTALANIMATIONS) { + trap->Error(ERR_DROP, "Bad animation number: %i", newAnimation); } - anim = &bgAllAnims[cent->localAnimIndex].anims[ newAnimation ]; + anim = &bgAllAnims[cent->localAnimIndex].anims[newAnimation]; lf->animation = anim; lf->animationTime = lf->frameTime + abs(anim->frameLerp); - if (cent->localAnimIndex > 1 && - anim->firstFrame == 0 && - anim->numFrames == 0) - { //We'll allow this for non-humanoids. + if (cent->localAnimIndex > 1 && anim->firstFrame == 0 && anim->numFrames == 0) { // We'll allow this for non-humanoids. return; } - if ( cg_debugAnim.integer && (cg_debugAnim.integer < 0 || cg_debugAnim.integer == cent->currentState.clientNum) ) { - if (lf == ¢->pe.legs) - { - trap->Print( "%d: %d TORSO Anim: %i, '%s'\n", cg.time, cent->currentState.clientNum, newAnimation, GetStringForID(animTable, newAnimation)); - } - else - { - trap->Print( "%d: %d LEGS Anim: %i, '%s'\n", cg.time, cent->currentState.clientNum, newAnimation, GetStringForID(animTable, newAnimation)); + if (cg_debugAnim.integer && (cg_debugAnim.integer < 0 || cg_debugAnim.integer == cent->currentState.clientNum)) { + if (lf == ¢->pe.legs) { + trap->Print("%d: %d TORSO Anim: %i, '%s'\n", cg.time, cent->currentState.clientNum, newAnimation, GetStringForID(animTable, newAnimation)); + } else { + trap->Print("%d: %d LEGS Anim: %i, '%s'\n", cg.time, cent->currentState.clientNum, newAnimation, GetStringForID(animTable, newAnimation)); } } - if (cent->ghoul2) - { + if (cent->ghoul2) { qboolean resumeFrame = qfalse; int beginFrame = -1; int firstFrame; int lastFrame; -#if 0 //disabled for now +#if 0 // disabled for now float unused; #endif animSpeed = 50.0f / anim->frameLerp; - if (lf->animation->loopFrames != -1) - { + if (lf->animation->loopFrames != -1) { flags = BONE_ANIM_OVERRIDE_LOOP; } - if (animSpeed < 0) - { + if (animSpeed < 0) { lastFrame = anim->firstFrame; firstFrame = anim->firstFrame + anim->numFrames; - } - else - { + } else { firstFrame = anim->firstFrame; lastFrame = anim->firstFrame + anim->numFrames; } - if (cg_animBlend.integer) - { + if (cg_animBlend.integer) { flags |= BONE_ANIM_BLEND; } - if (BG_InDeathAnim(newAnimation)) - { + if (BG_InDeathAnim(newAnimation)) { flags &= ~BONE_ANIM_BLEND; - } - else if ( oldAnim != -1 && - BG_InDeathAnim(oldAnim)) - { + } else if (oldAnim != -1 && BG_InDeathAnim(oldAnim)) { flags &= ~BONE_ANIM_BLEND; } - if (flags & BONE_ANIM_BLEND) - { - if (BG_FlippingAnim(newAnimation)) - { + if (flags & BONE_ANIM_BLEND) { + if (BG_FlippingAnim(newAnimation)) { blendTime = 200; - } - else if ( oldAnim != -1 && - (BG_FlippingAnim(oldAnim)) ) - { + } else if (oldAnim != -1 && (BG_FlippingAnim(oldAnim))) { blendTime = 200; } } animSpeed *= animSpeedMult; - BG_SaberStartTransAnim(cent->currentState.number, cent->currentState.fireflag, cent->currentState.weapon, newAnimation, &animSpeed, cent->currentState.brokenLimbs); + BG_SaberStartTransAnim(cent->currentState.number, cent->currentState.fireflag, cent->currentState.weapon, newAnimation, &animSpeed, + cent->currentState.brokenLimbs); - if (torsoOnly) - { + if (torsoOnly) { if (lf->animationTorsoSpeed != animSpeedMult && newAnimation == oldAnim && - flipState == lf->lastFlip) - { //same animation, but changing speed, so we will want to resume off the frame we're on. + flipState == lf->lastFlip) { // same animation, but changing speed, so we will want to resume off the frame we're on. resumeFrame = qtrue; } lf->animationTorsoSpeed = animSpeedMult; - } - else - { + } else { if (lf->animationSpeed != animSpeedMult && newAnimation == oldAnim && - flipState == lf->lastFlip) - { //same animation, but changing speed, so we will want to resume off the frame we're on. + flipState == lf->lastFlip) { // same animation, but changing speed, so we will want to resume off the frame we're on. resumeFrame = qtrue; } lf->animationSpeed = animSpeedMult; } - //vehicles may have torso etc but we only want to animate the root bone - if ( cent->currentState.NPC_class == CLASS_VEHICLE ) - { - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", firstFrame, lastFrame, flags, animSpeed,cg.time, beginFrame, blendTime); + // vehicles may have torso etc but we only want to animate the root bone + if (cent->currentState.NPC_class == CLASS_VEHICLE) { + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", firstFrame, lastFrame, flags, animSpeed, cg.time, beginFrame, blendTime); return; } - if (torsoOnly && !cent->noLumbar) - { //rww - The guesswork based on the lerp frame figures is usually BS, so I've resorted to a call to get the frame of the bone directly. + if (torsoOnly && !cent->noLumbar) { // rww - The guesswork based on the lerp frame figures is usually BS, so I've resorted to a call to get the frame of + // the bone directly. float GBAcFrame = 0; - if (resumeFrame) - { //we already checked, and this is the same anim, same flip state, but different speed, so we want to resume with the new speed off of the same frame. + if (resumeFrame) { // we already checked, and this is the same anim, same flip state, but different speed, so we want to resume with the new speed + // off of the same frame. trap->G2API_GetBoneFrame(cent->ghoul2, "lower_lumbar", cg.time, &GBAcFrame, NULL, 0); beginFrame = GBAcFrame; } - //even if resuming, also be sure to check if we are running the same frame on the legs. If so, we want to use their frame no matter what. + // even if resuming, also be sure to check if we are running the same frame on the legs. If so, we want to use their frame no matter what. trap->G2API_GetBoneFrame(cent->ghoul2, "model_root", cg.time, &GBAcFrame, NULL, 0); - if ((cent->currentState.torsoAnim) == (cent->currentState.legsAnim) && GBAcFrame >= anim->firstFrame && GBAcFrame <= (anim->firstFrame + anim->numFrames)) - { //if the legs are already running this anim, pick up on the exact same frame to avoid the "wobbly spine" problem. + if ((cent->currentState.torsoAnim) == (cent->currentState.legsAnim) && GBAcFrame >= anim->firstFrame && + GBAcFrame <= + (anim->firstFrame + + anim->numFrames)) { // if the legs are already running this anim, pick up on the exact same frame to avoid the "wobbly spine" problem. beginFrame = GBAcFrame; } - if (firstFrame > lastFrame || ci->torsoAnim == newAnimation) - { //don't resume on backwards playing animations.. I guess. + if (firstFrame > lastFrame || ci->torsoAnim == newAnimation) { // don't resume on backwards playing animations.. I guess. beginFrame = -1; } - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", firstFrame, lastFrame, flags, animSpeed,cg.time, beginFrame, blendTime); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", firstFrame, lastFrame, flags, animSpeed, cg.time, beginFrame, blendTime); // Update the torso frame with the new animation cent->pe.torso.frame = firstFrame; - if (ci) - { + if (ci) { ci->torsoAnim = newAnimation; } - } - else - { - if (resumeFrame) - { //we already checked, and this is the same anim, same flip state, but different speed, so we want to resume with the new speed off of the same frame. + } else { + if (resumeFrame) { // we already checked, and this is the same anim, same flip state, but different speed, so we want to resume with the new speed + // off of the same frame. float GBAcFrame = 0; trap->G2API_GetBoneFrame(cent->ghoul2, "model_root", cg.time, &GBAcFrame, NULL, 0); beginFrame = GBAcFrame; } - if ((beginFrame < firstFrame) || (beginFrame > lastFrame)) - { //out of range, don't use it then. + if ((beginFrame < firstFrame) || (beginFrame > lastFrame)) { // out of range, don't use it then. beginFrame = -1; } if (cent->currentState.torsoAnim == cent->currentState.legsAnim && - (ci->legsAnim != newAnimation || oldSpeed != animSpeed)) - { //alright, we are starting an anim on the legs, and that same anim is already playing on the toro, so pick up the frame. + (ci->legsAnim != newAnimation || + oldSpeed != + animSpeed)) { // alright, we are starting an anim on the legs, and that same anim is already playing on the toro, so pick up the frame. float GBAcFrame = 0; int oldBeginFrame = beginFrame; trap->G2API_GetBoneFrame(cent->ghoul2, "lower_lumbar", cg.time, &GBAcFrame, NULL, 0); beginFrame = GBAcFrame; - if ((beginFrame < firstFrame) || (beginFrame > lastFrame)) - { //out of range, don't use it then. + if ((beginFrame < firstFrame) || (beginFrame > lastFrame)) { // out of range, don't use it then. beginFrame = oldBeginFrame; } } trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", firstFrame, lastFrame, flags, animSpeed, cg.time, beginFrame, blendTime); - if (ci) - { + if (ci) { ci->legsAnim = newAnimation; } } - if (cent->localAnimIndex <= 1 && (cent->currentState.torsoAnim) == newAnimation && !cent->noLumbar) - { //make sure we're humanoid before we access the motion bone + if (cent->localAnimIndex <= 1 && (cent->currentState.torsoAnim) == newAnimation && + !cent->noLumbar) { // make sure we're humanoid before we access the motion bone trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", firstFrame, lastFrame, flags, animSpeed, cg.time, beginFrame, blendTime); } -#if 0 //disabled for now +#if 0 // disabled for now if (cent->localAnimIndex <= 1 && cent->currentState.brokenLimbs && (cent->currentState.brokenLimbs & (1 << BROKENLIMB_LARM))) { //broken left arm @@ -3176,7 +2674,6 @@ static void CG_SetLerpFrameAnimation( centity_t *cent, clientInfo_t *ci, lerpFra } } - /* =============== CG_FirstAnimFrame @@ -3189,35 +2686,29 @@ the animation before it completes at normal speed, in the case of a looping animation (such as the leg running anim). =============== */ -static qboolean CG_FirstAnimFrame(lerpFrame_t *lf, qboolean torsoOnly, float speedScale) -{ - if (torsoOnly) - { - if (lf->animationTorsoSpeed == speedScale) - { +static qboolean CG_FirstAnimFrame(lerpFrame_t *lf, qboolean torsoOnly, float speedScale) { + if (torsoOnly) { + if (lf->animationTorsoSpeed == speedScale) { return qfalse; } - } - else - { - if (lf->animationSpeed == speedScale) - { + } else { + if (lf->animationSpeed == speedScale) { return qfalse; } } - //I don't care where it is in the anim now, I am going to pick up from the same bone frame. -/* - if (lf->animation->numFrames < 2) - { - return qtrue; - } + // I don't care where it is in the anim now, I am going to pick up from the same bone frame. + /* + if (lf->animation->numFrames < 2) + { + return qtrue; + } - if (lf->animation->firstFrame == lf->frame) - { - return qtrue; - } -*/ + if (lf->animation->firstFrame == lf->frame) + { + return qtrue; + } + */ return qtrue; } @@ -3230,56 +2721,53 @@ Sets cg.snap, cg.oldFrame, and cg.backlerp cg.time should be between oldFrameTime and frameTime after exit =============== */ -static void CG_RunLerpFrame( centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, qboolean flipState, int newAnimation, float speedScale, qboolean torsoOnly) -{ +static void CG_RunLerpFrame(centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, qboolean flipState, int newAnimation, float speedScale, qboolean torsoOnly) { // debugging tool to get no animations - if ( cg_animSpeed.integer == 0 ) { + if (cg_animSpeed.integer == 0) { lf->oldFrame = lf->frame = lf->backlerp = 0; return; } // see if the animation sequence is switching - if (cent->currentState.forceFrame) - { - if (lf->lastForcedFrame != cent->currentState.forceFrame) - { - int flags = BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND; + if (cent->currentState.forceFrame) { + if (lf->lastForcedFrame != cent->currentState.forceFrame) { + int flags = BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND; float animSpeed = 1.0f; - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", cent->currentState.forceFrame, cent->currentState.forceFrame+1, flags, animSpeed, cg.time, -1, 150); - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", cent->currentState.forceFrame, cent->currentState.forceFrame+1, flags, animSpeed, cg.time, -1, 150); - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", cent->currentState.forceFrame, cent->currentState.forceFrame+1, flags, animSpeed, cg.time, -1, 150); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", cent->currentState.forceFrame, cent->currentState.forceFrame + 1, flags, animSpeed, + cg.time, -1, 150); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", cent->currentState.forceFrame, cent->currentState.forceFrame + 1, flags, animSpeed, cg.time, + -1, 150); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", cent->currentState.forceFrame, cent->currentState.forceFrame + 1, flags, animSpeed, cg.time, -1, + 150); } lf->lastForcedFrame = cent->currentState.forceFrame; lf->animationNumber = 0; - } - else - { + } else { lf->lastForcedFrame = -1; - if ( (newAnimation != lf->animationNumber || cent->currentState.brokenLimbs != ci->brokenLimbs || lf->lastFlip != flipState || !lf->animation) || (CG_FirstAnimFrame(lf, torsoOnly, speedScale)) ) - { - CG_SetLerpFrameAnimation( cent, ci, lf, newAnimation, speedScale, torsoOnly, flipState); + if ((newAnimation != lf->animationNumber || cent->currentState.brokenLimbs != ci->brokenLimbs || lf->lastFlip != flipState || !lf->animation) || + (CG_FirstAnimFrame(lf, torsoOnly, speedScale))) { + CG_SetLerpFrameAnimation(cent, ci, lf, newAnimation, speedScale, torsoOnly, flipState); } } lf->lastFlip = flipState; - if ( lf->frameTime > cg.time + 200 ) { + if (lf->frameTime > cg.time + 200) { lf->frameTime = cg.time; } - if ( lf->oldFrameTime > cg.time ) { + if (lf->oldFrameTime > cg.time) { lf->oldFrameTime = cg.time; } - if ( lf->frameTime ) - {// calculate current lerp value - if ( lf->frameTime == lf->oldFrameTime ) + if (lf->frameTime) { // calculate current lerp value + if (lf->frameTime == lf->oldFrameTime) lf->backlerp = 0.0f; else - lf->backlerp = 1.0f - (float)( cg.time - lf->oldFrameTime ) / ( lf->frameTime - lf->oldFrameTime ); + lf->backlerp = 1.0f - (float)(cg.time - lf->oldFrameTime) / (lf->frameTime - lf->oldFrameTime); } } @@ -3288,77 +2776,59 @@ static void CG_RunLerpFrame( centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, CG_ClearLerpFrame =============== */ -static void CG_ClearLerpFrame( centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, int animationNumber, qboolean torsoOnly) { +static void CG_ClearLerpFrame(centity_t *cent, clientInfo_t *ci, lerpFrame_t *lf, int animationNumber, qboolean torsoOnly) { lf->frameTime = lf->oldFrameTime = cg.time; - CG_SetLerpFrameAnimation( cent, ci, lf, animationNumber, 1, torsoOnly, qfalse ); + CG_SetLerpFrameAnimation(cent, ci, lf, animationNumber, 1, torsoOnly, qfalse); - if ( lf->animation->frameLerp < 0 ) - {//Plays backwards + if (lf->animation->frameLerp < 0) { // Plays backwards lf->oldFrame = lf->frame = (lf->animation->firstFrame + lf->animation->numFrames); - } - else - { + } else { lf->oldFrame = lf->frame = lf->animation->firstFrame; } } - /* =============== CG_PlayerAnimation =============== */ -qboolean PM_WalkingAnim( int anim ); +qboolean PM_WalkingAnim(int anim); -static void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, - int *torsoOld, int *torso, float *torsoBackLerp ) { - clientInfo_t *ci; - int clientNum; - float speedScale; +static void CG_PlayerAnimation(centity_t *cent, int *legsOld, int *legs, float *legsBackLerp, int *torsoOld, int *torso, float *torsoBackLerp) { + clientInfo_t *ci; + int clientNum; + float speedScale; clientNum = cent->currentState.clientNum; - if ( cg_noPlayerAnims.integer ) { + if (cg_noPlayerAnims.integer) { *legsOld = *legs = *torsoOld = *torso = 0; return; } if (!PM_RunningAnim(cent->currentState.legsAnim) && - !PM_WalkingAnim(cent->currentState.legsAnim)) - { //if legs are not in a walking/running anim then just animate at standard speed + !PM_WalkingAnim(cent->currentState.legsAnim)) { // if legs are not in a walking/running anim then just animate at standard speed speedScale = 1.0f; - } - else if (cent->currentState.forcePowersActive & (1 << FP_RAGE)) - { + } else if (cent->currentState.forcePowersActive & (1 << FP_RAGE)) { speedScale = 1.3f; - } - else if (cent->currentState.forcePowersActive & (1 << FP_SPEED)) - { + } else if (cent->currentState.forcePowersActive & (1 << FP_SPEED)) { speedScale = 1.7f; - } - else - { + } else { speedScale = 1.0f; } - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { ci = cent->npcClient; assert(ci); - } - else - { - ci = &cgs.clientinfo[ clientNum ]; + } else { + ci = &cgs.clientinfo[clientNum]; } - CG_RunLerpFrame( cent, ci, ¢->pe.legs, cent->currentState.legsFlip, cent->currentState.legsAnim, speedScale, qfalse); + CG_RunLerpFrame(cent, ci, ¢->pe.legs, cent->currentState.legsFlip, cent->currentState.legsAnim, speedScale, qfalse); - if (!(cent->currentState.forcePowersActive & (1 << FP_RAGE))) - { //don't affect torso anim speed unless raged + if (!(cent->currentState.forcePowersActive & (1 << FP_RAGE))) { // don't affect torso anim speed unless raged speedScale = 1.0f; - } - else - { + } else { speedScale = 1.7f; } @@ -3367,9 +2837,8 @@ static void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float *legsBackLerp = cent->pe.legs.backlerp; // If this is not a vehicle, you may lerm the frame (since vehicles never have a torso anim). -AReis - if ( cent->currentState.NPC_class != CLASS_VEHICLE ) - { - CG_RunLerpFrame( cent, ci, ¢->pe.torso, cent->currentState.torsoFlip, cent->currentState.torsoAnim, speedScale, qtrue ); + if (cent->currentState.NPC_class != CLASS_VEHICLE) { + CG_RunLerpFrame(cent, ci, ¢->pe.torso, cent->currentState.torsoFlip, cent->currentState.torsoAnim, speedScale, qtrue); *torsoOld = cent->pe.torso.oldFrame; *torso = cent->pe.torso.frame; @@ -3377,9 +2846,6 @@ static void CG_PlayerAnimation( centity_t *cent, int *legsOld, int *legs, float } } - - - /* ============================================================================= @@ -3408,11 +2874,10 @@ typedef struct boneAngleParms_s { boneAngleParms_t cgBoneAnglePostSet; #endif -void CG_G2SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, - const int up, const int right, const int forward, qhandle_t *modelList, - int blendTime , int currentTime ) -{ //we want to hold off on setting the bone angles until the end of the frame, because every time we set - //them the entire skeleton has to be reconstructed. +void CG_G2SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, + int currentTime) { // we want to hold off on setting the bone angles until the end of the frame, because every time we set + // them the entire skeleton has to be reconstructed. #if 0 //This function should ONLY be called from CG_Player() or a function that is called only within CG_Player(). //At the end of the frame we will check to use this information to call SetBoneAngles @@ -3435,10 +2900,9 @@ void CG_G2SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, cons cgBoneAnglePostSet.refreshSet = qtrue; #endif - //We don't want to go with the delayed approach, we want out bolt points and everything to be updated in realtime. - //We'll just take the reconstructs and live with them. - trap->G2API_SetBoneAngles(ghoul2, modelIndex, boneName, angles, flags, up, right, forward, modelList, - blendTime, currentTime); + // We don't want to go with the delayed approach, we want out bolt points and everything to be updated in realtime. + // We'll just take the reconstructs and live with them. + trap->G2API_SetBoneAngles(ghoul2, modelIndex, boneName, angles, flags, up, right, forward, modelList, blendTime, currentTime); } /* @@ -3450,17 +2914,15 @@ trace access. Maybe correct this sometime, so bmodel col. at least works with ra But I don't want to slow it down.. ================ */ -void CG_Rag_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask ) { - trap->CM_Trace ( result, start, end, mins, maxs, 0, mask, 0); +void CG_Rag_Trace(trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask) { + trap->CM_Trace(result, start, end, mins, maxs, 0, mask, 0); result->entityNum = result->fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; } //#define _RAG_BOLT_TESTING #ifdef _RAG_BOLT_TESTING -void CG_TempTestFunction(centity_t *cent, vec3_t forcedAngles) -{ +void CG_TempTestFunction(centity_t *cent, vec3_t forcedAngles) { mdxaBone_t boltMatrix; vec3_t tAngles; vec3_t bOrg; @@ -3469,8 +2931,7 @@ void CG_TempTestFunction(centity_t *cent, vec3_t forcedAngles) VectorSet(tAngles, 0, cent->lerpAngles[YAW], 0); - trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, tAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); + trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, tAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, bOrg); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, bDir); @@ -3482,29 +2943,22 @@ void CG_TempTestFunction(centity_t *cent, vec3_t forcedAngles) } #endif -//list of valid ragdoll effectors -static const char *cg_effectorStringTable[] = -{ //commented out the ones I don't want dragging to affect -// "thoracic", -// "rhand", - "lhand", - "rtibia", - "ltibia", - "rtalus", - "ltalus", -// "rradiusX", - "lradiusX", - "rfemurX", - "lfemurX", -// "ceyebrow", - NULL //always terminate +// list of valid ragdoll effectors +static const char *cg_effectorStringTable[] = { + // commented out the ones I don't want dragging to affect + // "thoracic", + // "rhand", + "lhand", "rtibia", "ltibia", "rtalus", "ltalus", + // "rradiusX", + "lradiusX", "rfemurX", "lfemurX", + // "ceyebrow", + NULL // always terminate }; -//we want to see which way the pelvis is facing to get a relatively oriented base settling frame -//this is to avoid the arms stretching in opposite directions on the body trying to reach the base -//pose if the pelvis is flipped opposite of the base pose or something -rww -static int CG_RagAnimForPositioning(centity_t *cent) -{ +// we want to see which way the pelvis is facing to get a relatively oriented base settling frame +// this is to avoid the arms stretching in opposite directions on the body trying to reach the base +// pose if the pelvis is flipped opposite of the base pose or something -rww +static int CG_RagAnimForPositioning(centity_t *cent) { int bolt; vec3_t dir; mdxaBone_t matrix; @@ -3513,76 +2967,60 @@ static int CG_RagAnimForPositioning(centity_t *cent) bolt = trap->G2API_AddBolt(cent->ghoul2, 0, "pelvis"); assert(bolt > -1); - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, bolt, &matrix, cent->turAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, bolt, &matrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&matrix, NEGATIVE_Z, dir); - if (dir[2] > 0.0f) - { //facing up + if (dir[2] > 0.0f) { // facing up return BOTH_DEADFLOP2; - } - else - { //facing down + } else { // facing down return BOTH_DEADFLOP1; } } -//rww - cgame interface for the ragdoll stuff. -//Returns qtrue if the entity is now in a ragdoll state, otherwise qfalse. -qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) -{ +// rww - cgame interface for the ragdoll stuff. +// Returns qtrue if the entity is now in a ragdoll state, otherwise qfalse. +qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) { vec3_t usedOrg; qboolean inSomething = qfalse; - int ragAnim;//BOTH_DEAD1; //BOTH_DEATH1; + int ragAnim; // BOTH_DEAD1; //BOTH_DEATH1; - if (!broadsword.integer) - { + if (!broadsword.integer) { return qfalse; } - if (cent->localAnimIndex) - { //don't rag non-humanoids + if (cent->localAnimIndex) { // don't rag non-humanoids return qfalse; } VectorCopy(cent->lerpOrigin, usedOrg); - if (!cent->isRagging) - { //If we're not in a ragdoll state, perform the checks. - if (cent->currentState.eFlags & EF_RAG) - { //want to go into it no matter what then + if (!cent->isRagging) { // If we're not in a ragdoll state, perform the checks. + if (cent->currentState.eFlags & EF_RAG) { // want to go into it no matter what then inSomething = qtrue; - } - else if (cent->currentState.groundEntityNum == ENTITYNUM_NONE) - { + } else if (cent->currentState.groundEntityNum == ENTITYNUM_NONE) { vec3_t cVel; VectorCopy(cent->currentState.pos.trDelta, cVel); - if (VectorNormalize(cVel) > 400) - { //if he's flying through the air at a good enough speed, switch into ragdoll + if (VectorNormalize(cVel) > 400) { // if he's flying through the air at a good enough speed, switch into ragdoll inSomething = qtrue; } } - if (cent->currentState.eType == ET_BODY) - { //just rag bodies immediately if their own was ragging on respawn - if (cent->ownerRagging) - { + if (cent->currentState.eType == ET_BODY) { // just rag bodies immediately if their own was ragging on respawn + if (cent->ownerRagging) { cent->isRagging = qtrue; return qfalse; } } - if (broadsword.integer > 1) - { + if (broadsword.integer > 1) { inSomething = qtrue; } - if (!inSomething) - { + if (!inSomething) { int anim = (cent->currentState.legsAnim); - int dur = (bgAllAnims[cent->localAnimIndex].anims[anim].numFrames-1) * fabs((float)(bgAllAnims[cent->localAnimIndex].anims[anim].frameLerp)); + int dur = (bgAllAnims[cent->localAnimIndex].anims[anim].numFrames - 1) * fabs((float)(bgAllAnims[cent->localAnimIndex].anims[anim].frameLerp)); int i = 0; int boltChecks[5]; vec3_t boltPoints[5]; @@ -3592,60 +3030,51 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) trace_t tr; mdxaBone_t boltMatrix; - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); - if (cent->pe.legs.animationTime > 50 && (cg.time - cent->pe.legs.animationTime) > dur) - { //Looks like the death anim is done playing + if (cent->pe.legs.animationTime > 50 && (cg.time - cent->pe.legs.animationTime) > dur) { // Looks like the death anim is done playing deathDone = qtrue; } - if (deathDone) - { //only trace from the hands if the death anim is already done. + if (deathDone) { // only trace from the hands if the death anim is already done. boltChecks[0] = trap->G2API_AddBolt(cent->ghoul2, 0, "rhand"); boltChecks[1] = trap->G2API_AddBolt(cent->ghoul2, 0, "lhand"); - } - else - { //otherwise start the trace loop at the cranium. + } else { // otherwise start the trace loop at the cranium. i = 2; } boltChecks[2] = trap->G2API_AddBolt(cent->ghoul2, 0, "cranium"); - //boltChecks[3] = trap->G2API_AddBolt(cent->ghoul2, 0, "rtarsal"); - //boltChecks[4] = trap->G2API_AddBolt(cent->ghoul2, 0, "ltarsal"); + // boltChecks[3] = trap->G2API_AddBolt(cent->ghoul2, 0, "rtarsal"); + // boltChecks[4] = trap->G2API_AddBolt(cent->ghoul2, 0, "ltarsal"); boltChecks[3] = trap->G2API_AddBolt(cent->ghoul2, 0, "rtalus"); boltChecks[4] = trap->G2API_AddBolt(cent->ghoul2, 0, "ltalus"); - //This may seem bad, but since we have a bone cache now it should manage to not be too disgustingly slow. - //Do the head first, because the hands reference it anyway. + // This may seem bad, but since we have a bone cache now it should manage to not be too disgustingly slow. + // Do the head first, because the hands reference it anyway. trap->G2API_GetBoltMatrix(cent->ghoul2, 0, boltChecks[2], &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltPoints[2]); - while (i < 5) - { - if (i < 2) - { //when doing hands, trace to the head instead of origin + while (i < 5) { + if (i < 2) { // when doing hands, trace to the head instead of origin trap->G2API_GetBoltMatrix(cent->ghoul2, 0, boltChecks[i], &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltPoints[i]); VectorCopy(boltPoints[i], trStart); VectorCopy(boltPoints[2], trEnd); - } - else - { - if (i > 2) - { //2 is the head, which already has the bolt point. - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, boltChecks[i], &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + } else { + if (i > 2) { // 2 is the head, which already has the bolt point. + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, boltChecks[i], &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltPoints[i]); } VectorCopy(boltPoints[i], trStart); VectorCopy(cent->lerpOrigin, trEnd); } - //Now that we have all that sorted out, trace between the two points we desire. + // Now that we have all that sorted out, trace between the two points we desire. CG_Rag_Trace(&tr, trStart, NULL, NULL, trEnd, cent->currentState.number, MASK_SOLID); - if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) - { //Hit something or start in solid, so flag it and break. - //This is a slight hack, but if we aren't done with the death anim, we don't really want to - //go into ragdoll unless our body has a relatively "flat" pitch. + if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) { // Hit something or start in solid, so flag it and break. + // This is a slight hack, but if we aren't done with the death anim, we don't really + // want to go into ragdoll unless our body has a relatively "flat" pitch. #if 0 vec3_t vSub; @@ -3668,8 +3097,7 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) } } - if (inSomething) - { + if (inSomething) { cent->isRagging = qtrue; #if 0 VectorClear(cent->lerpOriginOffset); @@ -3677,21 +3105,19 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) } } - if (cent->isRagging) - { //We're in a ragdoll state, so make the call to keep our positions updated and whatnot. + if (cent->isRagging) { // We're in a ragdoll state, so make the call to keep our positions updated and whatnot. sharedRagDollParams_t tParms; sharedRagDollUpdateParams_t tuParms; ragAnim = CG_RagAnimForPositioning(cent); - if (cent->ikStatus) - { //ik must be reset before ragdoll is started, or you'll get some interesting results. + if (cent->ikStatus) { // ik must be reset before ragdoll is started, or you'll get some interesting results. trap->G2API_SetBoneIKState(cent->ghoul2, cg.time, NULL, IKS_NONE, NULL); cent->ikStatus = qfalse; } - //these will be used as "base" frames for the ragoll settling. - tParms.startFrame = bgAllAnims[cent->localAnimIndex].anims[ragAnim].firstFrame;// + bgAllAnims[cent->localAnimIndex].anims[ragAnim].numFrames; + // these will be used as "base" frames for the ragoll settling. + tParms.startFrame = bgAllAnims[cent->localAnimIndex].anims[ragAnim].firstFrame; // + bgAllAnims[cent->localAnimIndex].anims[ragAnim].numFrames; tParms.endFrame = bgAllAnims[cent->localAnimIndex].anims[ragAnim].firstFrame + bgAllAnims[cent->localAnimIndex].anims[ragAnim].numFrames; #if 0 { @@ -3716,26 +3142,25 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", tParms.startFrame, tParms.endFrame, flags, animSpeed, cg.time, -1, blendTime); trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", tParms.startFrame, tParms.endFrame, flags, animSpeed, cg.time, -1, blendTime); } -#elif 1 //with my new method of doing things I want it to continue the anim +#elif 1 // with my new method of doing things I want it to continue the anim { float currentFrame; int startFrame, endFrame; int flags; float animSpeed; - if (trap->G2API_GetBoneAnim(cent->ghoul2, "model_root", cg.time, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, cgs.gameModels, 0)) - { //lock the anim on the current frame. + if (trap->G2API_GetBoneAnim(cent->ghoul2, "model_root", cg.time, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, cgs.gameModels, + 0)) { // lock the anim on the current frame. int blendTime = 500; animation_t *curAnim = &bgAllAnims[cent->localAnimIndex].anims[cent->currentState.legsAnim]; - if (currentFrame >= (curAnim->firstFrame + curAnim->numFrames-1)) - { //this is sort of silly but it works for now. - currentFrame = (curAnim->firstFrame + curAnim->numFrames-2); + if (currentFrame >= (curAnim->firstFrame + curAnim->numFrames - 1)) { // this is sort of silly but it works for now. + currentFrame = (curAnim->firstFrame + curAnim->numFrames - 2); } - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", currentFrame, currentFrame+1, flags, animSpeed,cg.time, currentFrame, blendTime); - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", currentFrame, currentFrame+1, flags, animSpeed, cg.time, currentFrame, blendTime); - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", currentFrame, currentFrame+1, flags, animSpeed, cg.time, currentFrame, blendTime); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "lower_lumbar", currentFrame, currentFrame + 1, flags, animSpeed, cg.time, currentFrame, blendTime); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", currentFrame, currentFrame + 1, flags, animSpeed, cg.time, currentFrame, blendTime); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", currentFrame, currentFrame + 1, flags, animSpeed, cg.time, currentFrame, blendTime); } } #endif @@ -3759,41 +3184,29 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) VectorCopy(usedOrg, tuParms.position); VectorCopy(cent->modelScale, tuParms.scale); tuParms.me = cent->currentState.number; - tuParms.settleFrame = tParms.endFrame-1; + tuParms.settleFrame = tParms.endFrame - 1; - if (cent->currentState.groundEntityNum != ENTITYNUM_NONE) - { + if (cent->currentState.groundEntityNum != ENTITYNUM_NONE) { VectorClear(tuParms.velocity); - } - else - { + } else { VectorScale(cent->currentState.pos.trDelta, 2.0f, tuParms.velocity); } trap->G2API_AnimateG2Models(cent->ghoul2, cg.time, &tuParms); - //So if we try to get a bolt point it's still correct - cent->turAngles[YAW] = - cent->lerpAngles[YAW] = - cent->pe.torso.yawAngle = - cent->pe.legs.yawAngle = forcedAngles[YAW]; + // So if we try to get a bolt point it's still correct + cent->turAngles[YAW] = cent->lerpAngles[YAW] = cent->pe.torso.yawAngle = cent->pe.legs.yawAngle = forcedAngles[YAW]; - if (cent->currentState.ragAttach && - (cent->currentState.eType != ET_NPC || cent->currentState.NPC_class != CLASS_VEHICLE)) - { + if (cent->currentState.ragAttach && (cent->currentState.eType != ET_NPC || cent->currentState.NPC_class != CLASS_VEHICLE)) { centity_t *grabEnt; - if (cent->currentState.ragAttach == ENTITYNUM_NONE) - { //switch cl 0 and entitynum_none, so we can operate on the "if non-0" concept + if (cent->currentState.ragAttach == ENTITYNUM_NONE) { // switch cl 0 and entitynum_none, so we can operate on the "if non-0" concept grabEnt = &cg_entities[0]; - } - else - { + } else { grabEnt = &cg_entities[cent->currentState.ragAttach]; } - if (grabEnt->ghoul2) - { + if (grabEnt->ghoul2) { mdxaBone_t matrix; vec3_t bOrg; vec3_t thisHand; @@ -3804,45 +3217,40 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) float difLen; int thorBolt; - //Get the person who is holding our hand's hand location - trap->G2API_GetBoltMatrix(grabEnt->ghoul2, 0, 0, &matrix, grabEnt->turAngles, grabEnt->lerpOrigin, - cg.time, cgs.gameModels, grabEnt->modelScale); + // Get the person who is holding our hand's hand location + trap->G2API_GetBoltMatrix(grabEnt->ghoul2, 0, 0, &matrix, grabEnt->turAngles, grabEnt->lerpOrigin, cg.time, cgs.gameModels, + grabEnt->modelScale); BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, bOrg); - //Get our hand's location - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, 0, &matrix, cent->turAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); + // Get our hand's location + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, 0, &matrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thisHand); - //Get the position of the thoracic bone for hinting its velocity later on + // Get the position of the thoracic bone for hinting its velocity later on thorBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "thoracic"); - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, thorBolt, &matrix, cent->turAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, thorBolt, &matrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, thorPoint); VectorSubtract(bOrg, thisHand, hands); - if (VectorLength(hands) < 3.0f) - { + if (VectorLength(hands) < 3.0f) { trap->G2API_RagForceSolve(cent->ghoul2, qfalse); - } - else - { + } else { trap->G2API_RagForceSolve(cent->ghoul2, qtrue); } - //got the hand pos of him, now we want to make our hand go to it + // got the hand pos of him, now we want to make our hand go to it trap->G2API_RagEffectorGoal(cent->ghoul2, "rhand", bOrg); trap->G2API_RagEffectorGoal(cent->ghoul2, "rradius", bOrg); trap->G2API_RagEffectorGoal(cent->ghoul2, "rradiusX", bOrg); trap->G2API_RagEffectorGoal(cent->ghoul2, "rhumerusX", bOrg); trap->G2API_RagEffectorGoal(cent->ghoul2, "rhumerus", bOrg); - //Make these two solve quickly so we can update decently + // Make these two solve quickly so we can update decently trap->G2API_RagPCJGradientSpeed(cent->ghoul2, "rhumerus", 1.5f); trap->G2API_RagPCJGradientSpeed(cent->ghoul2, "rradius", 1.5f); - //Break the constraints on them I suppose + // Break the constraints on them I suppose VectorSet(pcjMin, -999, -999, -999); VectorSet(pcjMax, 999, 999, 999); trap->G2API_RagPCJConstraint(cent->ghoul2, "rhumerus", pcjMin, pcjMax); @@ -3850,7 +3258,7 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) cent->overridingBones = cg.time + 2000; - //hit the thoracic velocity to the hand point + // hit the thoracic velocity to the hand point VectorSubtract(bOrg, thorPoint, hands); VectorNormalize(hands); VectorScale(hands, 2048.0f, hands); @@ -3860,27 +3268,23 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) VectorSubtract(cent->ragLastOrigin, cent->lerpOrigin, pDif); VectorCopy(cent->lerpOrigin, cent->ragLastOrigin); - if (cent->ragLastOriginTime >= cg.time && cent->currentState.groundEntityNum != ENTITYNUM_NONE) - { //make sure it's reasonably updated + if (cent->ragLastOriginTime >= cg.time && cent->currentState.groundEntityNum != ENTITYNUM_NONE) { // make sure it's reasonably updated difLen = VectorLength(pDif); - if (difLen > 0.0f) - { //if we're being dragged, then kick all the bones around a bit + if (difLen > 0.0f) { // if we're being dragged, then kick all the bones around a bit vec3_t dVel; vec3_t rVel; int i = 0; - if (difLen < 12.0f) - { - VectorScale(pDif, 12.0f/difLen, pDif); + if (difLen < 12.0f) { + VectorScale(pDif, 12.0f / difLen, pDif); difLen = 12.0f; } - while (cg_effectorStringTable[i]) - { + while (cg_effectorStringTable[i]) { VectorCopy(pDif, dVel); dVel[2] = 0; - //Factor in a random velocity + // Factor in a random velocity VectorSet(rVel, flrand(-0.1f, 0.1f), flrand(-0.1f, 0.1f), flrand(0.1f, 0.5)); VectorScale(rVel, 8.0f, rVel); @@ -3912,13 +3316,11 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) } cent->ragLastOriginTime = cg.time + 1000; } - } - else if (cent->overridingBones) - { //reset things to their normal rag state + } else if (cent->overridingBones) { // reset things to their normal rag state vec3_t pcjMin, pcjMax; vec3_t dVel; - //got the hand pos of him, now we want to make our hand go to it + // got the hand pos of him, now we want to make our hand go to it trap->G2API_RagEffectorGoal(cent->ghoul2, "rhand", NULL); trap->G2API_RagEffectorGoal(cent->ghoul2, "rradius", NULL); trap->G2API_RagEffectorGoal(cent->ghoul2, "rradiusX", NULL); @@ -3931,21 +3333,18 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) trap->G2API_RagPCJGradientSpeed(cent->ghoul2, "rhumerus", 0.0f); trap->G2API_RagPCJGradientSpeed(cent->ghoul2, "rradius", 0.0f); - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); trap->G2API_RagPCJConstraint(cent->ghoul2, "rhumerus", pcjMin, pcjMax); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); trap->G2API_RagPCJConstraint(cent->ghoul2, "rradius", pcjMin, pcjMax); - if (cent->overridingBones < cg.time) - { + if (cent->overridingBones < cg.time) { trap->G2API_RagForceSolve(cent->ghoul2, qfalse); cent->overridingBones = 0; - } - else - { + } else { trap->G2API_RagForceSolve(cent->ghoul2, qtrue); } } @@ -3956,9 +3355,8 @@ qboolean CG_RagDoll(centity_t *cent, vec3_t forcedAngles) return qfalse; } -//set the bone angles of this client entity based on data from the server -rww -void CG_G2ServerBoneAngles(centity_t *cent) -{ +// set the bone angles of this client entity based on data from the server -rww +void CG_G2ServerBoneAngles(centity_t *cent) { int i = 0; int bone = cent->currentState.boneIndex1; int flags, up, right, forward; @@ -3966,27 +3364,23 @@ void CG_G2ServerBoneAngles(centity_t *cent) VectorCopy(cent->currentState.boneAngles1, boneAngles); - while (i < 4) - { //cycle through the 4 bone index values on the entstate - if (bone) - { //if it's non-0 then it could have something in it. - const char *boneName = CG_ConfigString(CS_G2BONES+bone); + while (i < 4) { // cycle through the 4 bone index values on the entstate + if (bone) { // if it's non-0 then it could have something in it. + const char *boneName = CG_ConfigString(CS_G2BONES + bone); - if (boneName && boneName[0]) - { //got the bone, now set the angles from the corresponding entitystate boneangles value. + if (boneName && boneName[0]) { // got the bone, now set the angles from the corresponding entitystate boneangles value. flags = BONE_ANGLES_POSTMULT; - //get the orientation out of our bit field - forward = (cent->currentState.boneOrient)&7; //3 bits from bit 0 - right = (cent->currentState.boneOrient>>3)&7; //3 bits from bit 3 - up = (cent->currentState.boneOrient>>6)&7; //3 bits from bit 6 + // get the orientation out of our bit field + forward = (cent->currentState.boneOrient) & 7; // 3 bits from bit 0 + right = (cent->currentState.boneOrient >> 3) & 7; // 3 bits from bit 3 + up = (cent->currentState.boneOrient >> 6) & 7; // 3 bits from bit 6 trap->G2API_SetBoneAngles(cent->ghoul2, 0, boneName, boneAngles, flags, up, right, forward, cgs.gameModels, 100, cg.time); } } - switch (i) - { + switch (i) { case 0: bone = cent->currentState.boneIndex2; VectorCopy(cent->currentState.boneAngles2, boneAngles); @@ -4012,42 +3406,34 @@ void CG_G2ServerBoneAngles(centity_t *cent) CG_G2SetHeadBlink ------------------------- */ -static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) -{ - vec3_t desiredAngles; +static void CG_G2SetHeadBlink(centity_t *cent, qboolean bStart) { + vec3_t desiredAngles; int blendTime = 80; qboolean bWink = qfalse; - const int hReye = trap->G2API_AddBolt( cent->ghoul2, 0, "reye" ); - const int hLeye = trap->G2API_AddBolt( cent->ghoul2, 0, "leye" ); + const int hReye = trap->G2API_AddBolt(cent->ghoul2, 0, "reye"); + const int hLeye = trap->G2API_AddBolt(cent->ghoul2, 0, "leye"); - if (hLeye == -1) - { + if (hLeye == -1) { return; } VectorClear(desiredAngles); - if (bStart) - { + if (bStart) { desiredAngles[YAW] = -50; - if ( Q_flrand(0.0f, 1.0f) > 0.95f ) - { + if (Q_flrand(0.0f, 1.0f) > 0.95f) { bWink = qtrue; - blendTime /=3; + blendTime /= 3; } } - trap->G2API_SetBoneAngles( cent->ghoul2, 0, "leye", desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "leye", desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time); - if (hReye == -1) - { + if (hReye == -1) { return; } - if (!bWink) - { - trap->G2API_SetBoneAngles( cent->ghoul2, 0, "reye", desiredAngles, - BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time ); + if (!bWink) { + trap->G2API_SetBoneAngles(cent->ghoul2, 0, "reye", desiredAngles, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, blendTime, cg.time); } } @@ -4056,167 +3442,135 @@ static void CG_G2SetHeadBlink( centity_t *cent, qboolean bStart ) CG_G2SetHeadAnims ------------------------- */ -static void CG_G2SetHeadAnim( centity_t *cent, int anim ) -{ +static void CG_G2SetHeadAnim(centity_t *cent, int anim) { const int blendTime = 50; const animation_t *animations = bgAllAnims[cent->localAnimIndex].anims; - int animFlags = BONE_ANIM_OVERRIDE ;//| BONE_ANIM_BLEND; + int animFlags = BONE_ANIM_OVERRIDE; //| BONE_ANIM_BLEND; // animSpeed is 1.0 if the frameLerp (ms/frame) is 50 (20 fps). -// float timeScaleMod = (cg_timescale.value&&gent&&gent->s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<s.clientNum==0&&!player_locked&&!MatrixMode&&gent->client->ps.forcePowersActive&(1<ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); + // int startFrame, endFrame; + // const qboolean animatingHead = gi.G2API_GetAnimRangeIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, &startFrame, &endFrame); -// if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again + // if (!animatingHead || ( animations[anim].firstFrame != startFrame ) )// only set the anim if we aren't going to do the same animation again { - // gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, - // firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); - trap->G2API_SetBoneAnim(cent->ghoul2, 0, "face", firstFrame, lastFrame, animFlags, animSpeed, - cg.time, -1, blendTime); + // gi.G2API_SetBoneAnimIndex(&gent->ghoul2[gent->playerModel], cent->gent->faceBone, + // firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); + trap->G2API_SetBoneAnim(cent->ghoul2, 0, "face", firstFrame, lastFrame, animFlags, animSpeed, cg.time, -1, blendTime); } } -qboolean CG_G2PlayerHeadAnims( centity_t *cent ) -{ +qboolean CG_G2PlayerHeadAnims(centity_t *cent) { clientInfo_t *ci = NULL; int anim = -1; int voiceVolume = 0; - if(cent->localAnimIndex > 1) - { //only do this for humanoids + if (cent->localAnimIndex > 1) { // only do this for humanoids return qfalse; } - if (cent->noFace) - { // i don't have a face + if (cent->noFace) { // i don't have a face return qfalse; } - if (cent->currentState.number < MAX_CLIENTS) - { + if (cent->currentState.number < MAX_CLIENTS) { ci = &cgs.clientinfo[cent->currentState.number]; - } - else - { + } else { ci = cent->npcClient; } - if (!ci) - { + if (!ci) { return qfalse; } - if ( cent->currentState.eFlags & EF_DEAD ) - {//Dead people close their eyes and don't make faces! + if (cent->currentState.eFlags & EF_DEAD) { // Dead people close their eyes and don't make faces! anim = FACE_DEAD; ci->facial_blink = -1; - } - else - { - if (!ci->facial_blink) - { // set the timers + } else { + if (!ci->facial_blink) { // set the timers ci->facial_blink = cg.time + flrand(4000.0, 8000.0); ci->facial_frown = cg.time + flrand(6000.0, 10000.0); ci->facial_aux = cg.time + flrand(6000.0, 10000.0); } - //are we blinking? - if (ci->facial_blink < 0) - { // yes, check if we are we done blinking ? - if (-(ci->facial_blink) < cg.time) - { // yes, so reset blink timer + // are we blinking? + if (ci->facial_blink < 0) { // yes, check if we are we done blinking ? + if (-(ci->facial_blink) < cg.time) { // yes, so reset blink timer ci->facial_blink = cg.time + flrand(4000.0, 8000.0); - CG_G2SetHeadBlink( cent, qfalse ); //stop the blink + CG_G2SetHeadBlink(cent, qfalse); // stop the blink } - } - else // no we aren't blinking + } else // no we aren't blinking { - if (ci->facial_blink < cg.time)// but should we start ? + if (ci->facial_blink < cg.time) // but should we start ? { - CG_G2SetHeadBlink( cent, qtrue ); - if (ci->facial_blink == 1) - {//requested to stay shut by SET_FACEEYESCLOSED - ci->facial_blink = -(cg.time + 99999999.0f);// set blink timer - } - else - { - ci->facial_blink = -(cg.time + 300.0f);// set blink timer + CG_G2SetHeadBlink(cent, qtrue); + if (ci->facial_blink == 1) { // requested to stay shut by SET_FACEEYESCLOSED + ci->facial_blink = -(cg.time + 99999999.0f); // set blink timer + } else { + ci->facial_blink = -(cg.time + 300.0f); // set blink timer } } } voiceVolume = trap->S_GetVoiceVolume(cent->currentState.number); - if (voiceVolume > 0) // if we aren't talking, then it will be 0, -1 for talking but paused + if (voiceVolume > 0) // if we aren't talking, then it will be 0, -1 for talking but paused { - anim = FACE_TALK1 + voiceVolume -1; - } - else if (voiceVolume == 0) //don't do aux if in a slient part of speech - {//not talking - if (ci->facial_aux < 0) // are we auxing ? - { //yes - if (-(ci->facial_aux) < cg.time)// are we done auxing ? - { // yes, reset aux timer + anim = FACE_TALK1 + voiceVolume - 1; + } else if (voiceVolume == 0) // don't do aux if in a slient part of speech + { // not talking + if (ci->facial_aux < 0) // are we auxing ? + { // yes + if (-(ci->facial_aux) < cg.time) // are we done auxing ? + { // yes, reset aux timer ci->facial_aux = cg.time + flrand(7000.0, 10000.0); - } - else - { // not yet, so choose aux + } else { // not yet, so choose aux anim = FACE_ALERT; } - } - else // no we aren't auxing - { // but should we start ? - if (ci->facial_aux < cg.time) - {//yes + } else // no we aren't auxing + { // but should we start ? + if (ci->facial_aux < cg.time) { // yes anim = FACE_ALERT; // set aux timer ci->facial_aux = -(cg.time + 2000.0); } } - if (anim != -1) //we we are auxing, see if we should override with a frown + if (anim != -1) // we we are auxing, see if we should override with a frown { - if (ci->facial_frown < 0)// are we frowning ? - { // yes, - if (-(ci->facial_frown) < cg.time)//are we done frowning ? - { // yes, reset frown timer + if (ci->facial_frown < 0) // are we frowning ? + { // yes, + if (-(ci->facial_frown) < cg.time) // are we done frowning ? + { // yes, reset frown timer ci->facial_frown = cg.time + flrand(7000.0, 10000.0); - } - else - { // not yet, so choose frown + } else { // not yet, so choose frown anim = FACE_FROWN; } - } - else// no we aren't frowning - { // but should we start ? - if (ci->facial_frown < cg.time) - { + } else // no we aren't frowning + { // but should we start ? + if (ci->facial_frown < cg.time) { anim = FACE_FROWN; // set frown timer ci->facial_frown = -(cg.time + 2000.0); @@ -4224,155 +3578,119 @@ qboolean CG_G2PlayerHeadAnims( centity_t *cent ) } } - }//talking - }//dead - if (anim != -1) - { - CG_G2SetHeadAnim( cent, anim ); + } // talking + } // dead + if (anim != -1) { + CG_G2SetHeadAnim(cent, anim); return qtrue; } return qfalse; } - -static void CG_G2PlayerAngles( centity_t *cent, matrix3_t legs, vec3_t legsAngles) -{ +static void CG_G2PlayerAngles(centity_t *cent, matrix3_t legs, vec3_t legsAngles) { clientInfo_t *ci; - //rww - now do ragdoll stuff - if ((cent->currentState.eFlags & EF_DEAD) || (cent->currentState.eFlags & EF_RAG)) - { + // rww - now do ragdoll stuff + if ((cent->currentState.eFlags & EF_DEAD) || (cent->currentState.eFlags & EF_RAG)) { vec3_t forcedAngles; VectorClear(forcedAngles); forcedAngles[YAW] = cent->lerpAngles[YAW]; - if (CG_RagDoll(cent, forcedAngles)) - { //if we managed to go into the rag state, give our ent axis the forced angles and return. - AnglesToAxis( forcedAngles, legs ); + if (CG_RagDoll(cent, forcedAngles)) { // if we managed to go into the rag state, give our ent axis the forced angles and return. + AnglesToAxis(forcedAngles, legs); VectorCopy(forcedAngles, legsAngles); return; } - } - else if (cent->isRagging) - { + } else if (cent->isRagging) { cent->isRagging = qfalse; - trap->G2API_SetRagDoll(cent->ghoul2, NULL); //calling with null parms resets to no ragdoll. + trap->G2API_SetRagDoll(cent->ghoul2, NULL); // calling with null parms resets to no ragdoll. } - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { ci = cent->npcClient; assert(ci); - } - else - { + } else { ci = &cgs.clientinfo[cent->currentState.number]; } - //rww - Quite possibly the most arguments for a function ever. - if (cent->localAnimIndex <= 1) - { //don't do these things on non-humanoids + // rww - Quite possibly the most arguments for a function ever. + if (cent->localAnimIndex <= 1) { // don't do these things on non-humanoids vec3_t lookAngles; entityState_t *emplaced = NULL; - if (cent->currentState.hasLookTarget) - { + if (cent->currentState.hasLookTarget) { VectorSubtract(cg_entities[cent->currentState.lookTarget].lerpOrigin, cent->lerpOrigin, lookAngles); vectoangles(lookAngles, lookAngles); ci->lookTime = cg.time + 1000; - } - else - { + } else { VectorCopy(cent->lerpAngles, lookAngles); } lookAngles[PITCH] = 0; - if (cent->currentState.otherEntityNum2) - { + if (cent->currentState.otherEntityNum2) { emplaced = &cg_entities[cent->currentState.otherEntityNum2].currentState; } - BG_G2PlayerAngles(cent->ghoul2, ci->bolt_motion, ¢->currentState, cg.time, - cent->lerpOrigin, cent->lerpAngles, legs, legsAngles, ¢->pe.torso.yawing, ¢->pe.torso.pitching, - ¢->pe.legs.yawing, ¢->pe.torso.yawAngle, ¢->pe.torso.pitchAngle, ¢->pe.legs.yawAngle, - cg.frametime, cent->turAngles, cent->modelScale, ci->legsAnim, ci->torsoAnim, &ci->corrTime, - lookAngles, ci->lastHeadAngles, ci->lookTime, emplaced, &ci->superSmoothTime); + BG_G2PlayerAngles(cent->ghoul2, ci->bolt_motion, ¢->currentState, cg.time, cent->lerpOrigin, cent->lerpAngles, legs, legsAngles, + ¢->pe.torso.yawing, ¢->pe.torso.pitching, ¢->pe.legs.yawing, ¢->pe.torso.yawAngle, ¢->pe.torso.pitchAngle, + ¢->pe.legs.yawAngle, cg.frametime, cent->turAngles, cent->modelScale, ci->legsAnim, ci->torsoAnim, &ci->corrTime, lookAngles, + ci->lastHeadAngles, ci->lookTime, emplaced, &ci->superSmoothTime); - if (cent->currentState.heldByClient && cent->currentState.heldByClient <= MAX_CLIENTS) - { //then put our arm in this client's hand - //is index+1 because index 0 is valid. - int heldByIndex = cent->currentState.heldByClient-1; + if (cent->currentState.heldByClient && cent->currentState.heldByClient <= MAX_CLIENTS) { // then put our arm in this client's hand + // is index+1 because index 0 is valid. + int heldByIndex = cent->currentState.heldByClient - 1; centity_t *other = &cg_entities[heldByIndex]; - if (other && other->ghoul2 && ci->bolt_lhand) - { + if (other && other->ghoul2 && ci->bolt_lhand) { mdxaBone_t boltMatrix; vec3_t boltOrg; - trap->G2API_GetBoltMatrix(other->ghoul2, 0, ci->bolt_lhand, &boltMatrix, other->turAngles, other->lerpOrigin, cg.time, cgs.gameModels, other->modelScale); + trap->G2API_GetBoltMatrix(other->ghoul2, 0, ci->bolt_lhand, &boltMatrix, other->turAngles, other->lerpOrigin, cg.time, cgs.gameModels, + other->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); - BG_IK_MoveArm(cent->ghoul2, ci->bolt_lhand, cg.time, ¢->currentState, - cent->currentState.torsoAnim/*BOTH_DEAD1*/, boltOrg, ¢->ikStatus, cent->lerpOrigin, cent->lerpAngles, cent->modelScale, 500, qfalse); + BG_IK_MoveArm(cent->ghoul2, ci->bolt_lhand, cg.time, ¢->currentState, cent->currentState.torsoAnim /*BOTH_DEAD1*/, boltOrg, ¢->ikStatus, + cent->lerpOrigin, cent->lerpAngles, cent->modelScale, 500, qfalse); } + } else if (cent->ikStatus) { // make sure we aren't IKing if we don't have anyone to hold onto us. + BG_IK_MoveArm(cent->ghoul2, ci->bolt_lhand, cg.time, ¢->currentState, cent->currentState.torsoAnim /*BOTH_DEAD1*/, vec3_origin, ¢->ikStatus, + cent->lerpOrigin, cent->lerpAngles, cent->modelScale, 500, qtrue); } - else if (cent->ikStatus) - { //make sure we aren't IKing if we don't have anyone to hold onto us. - BG_IK_MoveArm(cent->ghoul2, ci->bolt_lhand, cg.time, ¢->currentState, - cent->currentState.torsoAnim/*BOTH_DEAD1*/, vec3_origin, ¢->ikStatus, cent->lerpOrigin, cent->lerpAngles, cent->modelScale, 500, qtrue); - } - } - else if ( cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - { + } else if (cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { vec3_t lookAngles; VectorCopy(cent->lerpAngles, legsAngles); legsAngles[PITCH] = 0; - AnglesToAxis( legsAngles, legs ); + AnglesToAxis(legsAngles, legs); VectorCopy(cent->lerpAngles, lookAngles); lookAngles[YAW] = lookAngles[ROLL] = 0; - BG_G2ATSTAngles( cent->ghoul2, cg.time, lookAngles ); - } - else - { - if (cent->currentState.eType == ET_NPC && - cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle && - cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //fighters actually want to take pitch and roll into account for the axial angles + BG_G2ATSTAngles(cent->ghoul2, cg.time, lookAngles); + } else { + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle && + cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // fighters actually want to take pitch and roll into account for the axial angles VectorCopy(cent->lerpAngles, legsAngles); - AnglesToAxis( legsAngles, legs ); - } - else if (cent->currentState.eType == ET_NPC && - cent->currentState.m_iVehicleNum && - cent->currentState.NPC_class != CLASS_VEHICLE ) - { //an NPC bolted to a vehicle should use the full angles + AnglesToAxis(legsAngles, legs); + } else if (cent->currentState.eType == ET_NPC && cent->currentState.m_iVehicleNum && + cent->currentState.NPC_class != CLASS_VEHICLE) { // an NPC bolted to a vehicle should use the full angles VectorCopy(cent->lerpAngles, legsAngles); - AnglesToAxis( legsAngles, legs ); - } - else - { + AnglesToAxis(legsAngles, legs); + } else { vec3_t nhAngles; - if (cent->currentState.eType == ET_NPC && - cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle && - cent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) - { //yeah, a hack, sorry. + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle && + cent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) { // yeah, a hack, sorry. VectorSet(nhAngles, 0, cent->lerpAngles[YAW], cent->lerpAngles[ROLL]); - } - else - { + } else { VectorSet(nhAngles, 0, cent->lerpAngles[YAW], 0); } - AnglesToAxis( nhAngles, legs ); + AnglesToAxis(nhAngles, legs); } } - //See if we have any bone angles sent from the server + // See if we have any bone angles sent from the server CG_G2ServerBoneAngles(cent); } //========================================================================== @@ -4409,36 +3727,30 @@ static void CG_TrailItem( centity_t *cent, qhandle_t hModel ) { CG_PlayerFlag =============== */ -static void CG_PlayerFlag( centity_t *cent, qhandle_t hModel ) { - refEntity_t ent; - vec3_t angles; - matrix3_t axis; - vec3_t boltOrg, tAng, getAng, right; - mdxaBone_t boltMatrix; - clientInfo_t *ci; +static void CG_PlayerFlag(centity_t *cent, qhandle_t hModel) { + refEntity_t ent; + vec3_t angles; + matrix3_t axis; + vec3_t boltOrg, tAng, getAng, right; + mdxaBone_t boltMatrix; + clientInfo_t *ci; - if (cent->currentState.number == cg.snap->ps.clientNum && - !cg.renderingThirdPerson) - { + if (cent->currentState.number == cg.snap->ps.clientNum && !cg.renderingThirdPerson) { return; } - if (!cent->ghoul2) - { + if (!cent->ghoul2) { return; } - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { ci = cent->npcClient; assert(ci); - } - else - { + } else { ci = &cgs.clientinfo[cent->currentState.number]; } - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_llumbar, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); @@ -4451,20 +3763,20 @@ static void CG_PlayerFlag( centity_t *cent, qhandle_t hModel ) { boltOrg[2] -= 12; VectorSet(getAng, 0, cent->lerpAngles[1], 0); AngleVectors(getAng, 0, right, 0); - boltOrg[0] += right[0]*8; - boltOrg[1] += right[1]*8; - boltOrg[2] += right[2]*8; + boltOrg[0] += right[0] * 8; + boltOrg[1] += right[1] * 8; + boltOrg[2] += right[2] * 8; - angles[PITCH] = -cent->lerpAngles[PITCH]/2-30; - angles[YAW] = tAng[YAW]+270; + angles[PITCH] = -cent->lerpAngles[PITCH] / 2 - 30; + angles[YAW] = tAng[YAW] + 270; AnglesToAxis(angles, axis); - memset( &ent, 0, sizeof( ent ) ); - VectorMA( boltOrg, 24, axis[0], ent.origin ); + memset(&ent, 0, sizeof(ent)); + VectorMA(boltOrg, 24, axis[0], ent.origin); angles[ROLL] += 20; - AnglesToAxis( angles, ent.axis ); + AnglesToAxis(angles, ent.axis); ent.hModel = hModel; @@ -4480,49 +3792,48 @@ static void CG_PlayerFlag( centity_t *cent, qhandle_t hModel ) { ent.shaderRGBA[3] = 100; } */ - //FIXME: Not doing this at the moment because sorting totally messes up + // FIXME: Not doing this at the moment because sorting totally messes up - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } - /* =============== CG_PlayerPowerups =============== */ -static void CG_PlayerPowerups( centity_t *cent, refEntity_t *torso ) { - int powerups; +static void CG_PlayerPowerups(centity_t *cent, refEntity_t *torso) { + int powerups; powerups = cent->currentState.powerups; - if ( !powerups ) { + if (!powerups) { return; } - #ifdef BASE_COMPAT - // quad gives a dlight - if ( powerups & ( 1 << PW_QUAD ) ) - trap->R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2f, 0.2f, 1 ); - #endif // BASE_COMPAT +#ifdef BASE_COMPAT + // quad gives a dlight + if (powerups & (1 << PW_QUAD)) + trap->R_AddLightToScene(cent->lerpOrigin, 200 + (rand() & 31), 0.2f, 0.2f, 1); +#endif // BASE_COMPAT if (cent->currentState.eType == ET_NPC) assert(cent->npcClient); // redflag - if ( powerups & ( 1 << PW_REDFLAG ) ) { - CG_PlayerFlag( cent, cgs.media.redFlagModel ); - trap->R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1.0, 0.2f, 0.2f ); + if (powerups & (1 << PW_REDFLAG)) { + CG_PlayerFlag(cent, cgs.media.redFlagModel); + trap->R_AddLightToScene(cent->lerpOrigin, 200 + (rand() & 31), 1.0, 0.2f, 0.2f); } // blueflag - if ( powerups & ( 1 << PW_BLUEFLAG ) ) { - CG_PlayerFlag( cent, cgs.media.blueFlagModel ); - trap->R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 0.2f, 0.2f, 1.0 ); + if (powerups & (1 << PW_BLUEFLAG)) { + CG_PlayerFlag(cent, cgs.media.blueFlagModel); + trap->R_AddLightToScene(cent->lerpOrigin, 200 + (rand() & 31), 0.2f, 0.2f, 1.0); } // neutralflag - if ( powerups & ( 1 << PW_NEUTRALFLAG ) ) { - trap->R_AddLightToScene( cent->lerpOrigin, 200 + (rand()&31), 1.0, 1.0, 1.0 ); + if (powerups & (1 << PW_NEUTRALFLAG)) { + trap->R_AddLightToScene(cent->lerpOrigin, 200 + (rand() & 31), 1.0, 1.0, 1.0); } // haste leaves smoke trails @@ -4533,7 +3844,6 @@ static void CG_PlayerPowerups( centity_t *cent, refEntity_t *torso ) { */ } - /* =============== CG_PlayerFloatSprite @@ -4541,18 +3851,18 @@ CG_PlayerFloatSprite Float a sprite over the player's head =============== */ -static void CG_PlayerFloatSprite( centity_t *cent, qhandle_t shader ) { - int rf; - refEntity_t ent; +static void CG_PlayerFloatSprite(centity_t *cent, qhandle_t shader) { + int rf; + refEntity_t ent; - if ( cent->currentState.number == cg.snap->ps.clientNum && !cg.renderingThirdPerson ) { - rf = RF_THIRD_PERSON; // only show in mirrors + if (cent->currentState.number == cg.snap->ps.clientNum && !cg.renderingThirdPerson) { + rf = RF_THIRD_PERSON; // only show in mirrors } else { rf = 0; } - memset( &ent, 0, sizeof( ent ) ); - VectorCopy( cent->lerpOrigin, ent.origin ); + memset(&ent, 0, sizeof(ent)); + VectorCopy(cent->lerpOrigin, ent.origin); ent.origin[2] += 48; ent.reType = RT_SPRITE; ent.customShader = shader; @@ -4562,11 +3872,9 @@ static void CG_PlayerFloatSprite( centity_t *cent, qhandle_t shader ) { ent.shaderRGBA[1] = 255; ent.shaderRGBA[2] = 255; ent.shaderRGBA[3] = 255; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } - - /* =============== CG_PlayerFloatSprite @@ -4600,7 +3908,6 @@ static void CG_PlayerFloatSpriteRGBA( centity_t *cent, qhandle_t shader, vec4_t } #endif - /* =============== CG_PlayerSprites @@ -4608,32 +3915,24 @@ CG_PlayerSprites Float sprites over the player's head =============== */ -static void CG_PlayerSprites( centity_t *cent ) { -// int team; - - if (cg.snap && - CG_IsMindTricked(cent->currentState.trickedentindex, - cent->currentState.trickedentindex2, - cent->currentState.trickedentindex3, - cent->currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - return; //this entity is mind-tricking the current client, so don't render it +static void CG_PlayerSprites(centity_t *cent) { + // int team; + + if (cg.snap && CG_IsMindTricked(cent->currentState.trickedentindex, cent->currentState.trickedentindex2, cent->currentState.trickedentindex3, + cent->currentState.trickedentindex4, cg.snap->ps.clientNum)) { + return; // this entity is mind-tricking the current client, so don't render it } - if ( cent->currentState.eFlags & EF_CONNECTION ) { - CG_PlayerFloatSprite( cent, cgs.media.connectionShader ); + if (cent->currentState.eFlags & EF_CONNECTION) { + CG_PlayerFloatSprite(cent, cgs.media.connectionShader); return; } - if (cent->vChatTime > cg.time) - { - CG_PlayerFloatSprite( cent, cgs.media.vchatShader ); - } - else if ( cent->currentState.eType != ET_NPC && //don't draw talk balloons on NPCs - (cent->currentState.eFlags & EF_TALK) ) - { - CG_PlayerFloatSprite( cent, cgs.media.balloonShader ); + if (cent->vChatTime > cg.time) { + CG_PlayerFloatSprite(cent, cgs.media.vchatShader); + } else if (cent->currentState.eType != ET_NPC && // don't draw talk balloons on NPCs + (cent->currentState.eFlags & EF_TALK)) { + CG_PlayerFloatSprite(cent, cgs.media.balloonShader); return; } } @@ -4647,82 +3946,66 @@ Returns the Z component of the surface being shadowed should it return a full plane instead of a Z? =============== */ -#define SHADOW_DISTANCE 128 -static qboolean CG_PlayerShadow( centity_t *cent, float *shadowPlane ) { - vec3_t end, mins = {-15, -15, 0}, maxs = {15, 15, 2}; - trace_t trace; - float alpha; - float radius = 24.0f; +#define SHADOW_DISTANCE 128 +static qboolean CG_PlayerShadow(centity_t *cent, float *shadowPlane) { + vec3_t end, mins = {-15, -15, 0}, maxs = {15, 15, 2}; + trace_t trace; + float alpha; + float radius = 24.0f; *shadowPlane = 0; - if ( cg_shadows.integer == 0 ) { + if (cg_shadows.integer == 0) { return qfalse; } // no shadows when cloaked - if ( cent->currentState.powerups & ( 1 << PW_CLOAKED )) - { + if (cent->currentState.powerups & (1 << PW_CLOAKED)) { return qfalse; } - if (cent->currentState.eFlags & EF_DEAD) - { + if (cent->currentState.eFlags & EF_DEAD) { return qfalse; } - if (CG_IsMindTricked(cent->currentState.trickedentindex, - cent->currentState.trickedentindex2, - cent->currentState.trickedentindex3, - cent->currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - return qfalse; //this entity is mind-tricking the current client, so don't render it + if (CG_IsMindTricked(cent->currentState.trickedentindex, cent->currentState.trickedentindex2, cent->currentState.trickedentindex3, + cent->currentState.trickedentindex4, cg.snap->ps.clientNum)) { + return qfalse; // this entity is mind-tricking the current client, so don't render it } - if ( cg_shadows.integer == 1 ) - {//dropshadow - if (cent->currentState.m_iVehicleNum && - cent->currentState.NPC_class != CLASS_VEHICLE ) - {//riding a vehicle, no dropshadow + if (cg_shadows.integer == 1) { // dropshadow + if (cent->currentState.m_iVehicleNum && cent->currentState.NPC_class != CLASS_VEHICLE) { // riding a vehicle, no dropshadow return qfalse; } } // send a trace down from the player to the ground - VectorCopy( cent->lerpOrigin, end ); - if (cg_shadows.integer == 2) - { //stencil + VectorCopy(cent->lerpOrigin, end); + if (cg_shadows.integer == 2) { // stencil end[2] -= 4096.0f; - trap->CM_Trace( &trace, cent->lerpOrigin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0 ); + trap->CM_Trace(&trace, cent->lerpOrigin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0); - if ( trace.fraction == 1.0 || trace.startsolid || trace.allsolid ) - { - trace.endpos[2] = cent->lerpOrigin[2]-25.0f; + if (trace.fraction == 1.0 || trace.startsolid || trace.allsolid) { + trace.endpos[2] = cent->lerpOrigin[2] - 25.0f; } - } - else - { + } else { end[2] -= SHADOW_DISTANCE; - trap->CM_Trace( &trace, cent->lerpOrigin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0 ); + trap->CM_Trace(&trace, cent->lerpOrigin, end, mins, maxs, 0, MASK_PLAYERSOLID, 0); // no shadow if too high - if ( trace.fraction == 1.0 || trace.startsolid || trace.allsolid ) { + if (trace.fraction == 1.0 || trace.startsolid || trace.allsolid) { return qfalse; } } - if (cg_shadows.integer == 2) - { //stencil shadows need plane to be on ground + if (cg_shadows.integer == 2) { // stencil shadows need plane to be on ground *shadowPlane = trace.endpos[2]; - } - else - { + } else { *shadowPlane = trace.endpos[2] + 1; } - if ( cg_shadows.integer != 1 ) { // no mark for stencil or projection shadows + if (cg_shadows.integer != 1) { // no mark for stencil or projection shadows return qtrue; } @@ -4730,22 +4013,18 @@ static qboolean CG_PlayerShadow( centity_t *cent, float *shadowPlane ) { alpha = 1.0 - trace.fraction; // bk0101022 - hack / FPE - bogus planes? - //assert( DotProduct( trace.plane.normal, trace.plane.normal ) != 0.0f ) + // assert( DotProduct( trace.plane.normal, trace.plane.normal ) != 0.0f ) // add the mark as a temporary, so it goes directly to the renderer // without taking a spot in the cg_marks array - if ( cent->currentState.NPC_class == CLASS_REMOTE - || cent->currentState.NPC_class == CLASS_SEEKER ) - { + if (cent->currentState.NPC_class == CLASS_REMOTE || cent->currentState.NPC_class == CLASS_SEEKER) { radius = 8.0f; } - CG_ImpactMark( cgs.media.shadowMarkShader, trace.endpos, trace.plane.normal, - cent->pe.legs.yawAngle, alpha,alpha,alpha,1, qfalse, radius, qtrue ); + CG_ImpactMark(cgs.media.shadowMarkShader, trace.endpos, trace.plane.normal, cent->pe.legs.yawAngle, alpha, alpha, alpha, 1, qfalse, radius, qtrue); return qtrue; } - /* =============== CG_PlayerSplash @@ -4753,44 +4032,44 @@ CG_PlayerSplash Draw a mark at the water surface =============== */ -static void CG_PlayerSplash( centity_t *cent ) { - vec3_t start, end; - trace_t trace; - int contents; - polyVert_t verts[4]; +static void CG_PlayerSplash(centity_t *cent) { + vec3_t start, end; + trace_t trace; + int contents; + polyVert_t verts[4]; - if ( !cg_shadows.integer ) { + if (!cg_shadows.integer) { return; } - VectorCopy( cent->lerpOrigin, end ); + VectorCopy(cent->lerpOrigin, end); end[2] -= 24; // if the feet aren't in liquid, don't make a mark // this won't handle moving water brushes, but they wouldn't draw right anyway... - contents = CG_PointContents( end, 0 ); - if ( !( contents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) ) { + contents = CG_PointContents(end, 0); + if (!(contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { return; } - VectorCopy( cent->lerpOrigin, start ); + VectorCopy(cent->lerpOrigin, start); start[2] += 32; // if the head isn't out of liquid, don't make a mark - contents = CG_PointContents( start, 0 ); - if ( contents & ( CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) { + contents = CG_PointContents(start, 0); + if (contents & (CONTENTS_SOLID | CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { return; } // trace down to find the surface - trap->CM_Trace( &trace, start, end, NULL, NULL, 0, ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ), 0 ); + trap->CM_Trace(&trace, start, end, NULL, NULL, 0, (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA), 0); - if ( trace.fraction == 1.0 ) { + if (trace.fraction == 1.0) { return; } // create a mark polygon - VectorCopy( trace.endpos, verts[0].xyz ); + VectorCopy(trace.endpos, verts[0].xyz); verts[0].xyz[0] -= 32; verts[0].xyz[1] -= 32; verts[0].st[0] = 0; @@ -4800,7 +4079,7 @@ static void CG_PlayerSplash( centity_t *cent ) { verts[0].modulate[2] = 255; verts[0].modulate[3] = 255; - VectorCopy( trace.endpos, verts[1].xyz ); + VectorCopy(trace.endpos, verts[1].xyz); verts[1].xyz[0] -= 32; verts[1].xyz[1] += 32; verts[1].st[0] = 0; @@ -4810,7 +4089,7 @@ static void CG_PlayerSplash( centity_t *cent ) { verts[1].modulate[2] = 255; verts[1].modulate[3] = 255; - VectorCopy( trace.endpos, verts[2].xyz ); + VectorCopy(trace.endpos, verts[2].xyz); verts[2].xyz[0] += 32; verts[2].xyz[1] += 32; verts[2].st[0] = 1; @@ -4820,7 +4099,7 @@ static void CG_PlayerSplash( centity_t *cent ) { verts[2].modulate[2] = 255; verts[2].modulate[3] = 255; - VectorCopy( trace.endpos, verts[3].xyz ); + VectorCopy(trace.endpos, verts[3].xyz); verts[3].xyz[0] += 32; verts[3].xyz[1] -= 32; verts[3].st[0] = 1; @@ -4830,15 +4109,13 @@ static void CG_PlayerSplash( centity_t *cent ) { verts[3].modulate[2] = 255; verts[3].modulate[3] = 255; - trap->R_AddPolysToScene( cgs.media.wakeMarkShader, 4, verts, 1 ); + trap->R_AddPolysToScene(cgs.media.wakeMarkShader, 4, verts, 1); } -#define REFRACT_EFFECT_DURATION 500 -static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) -{ - if (!cent || !cg_renderToTextureFX.integer) - { - localEntity_t *ex; +#define REFRACT_EFFECT_DURATION 500 +static void CG_ForcePushBlur(vec3_t org, centity_t *cent) { + if (!cent || !cg_renderToTextureFX.integer) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -4846,15 +4123,15 @@ static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], 55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], 55, ex->pos.trDelta); ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; - ex->refEntity.customShader = trap->R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = trap->R_RegisterShader("gfx/effects/forcePush"); ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -4863,18 +4140,16 @@ static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], -55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], -55, ex->pos.trDelta); ex->color[0] = 24; ex->color[1] = 32; ex->color[2] = 40; - ex->refEntity.customShader = trap->R_RegisterShader( "gfx/effects/forcePush" ); - } - else - { //superkewl "refraction" (well sort of) effect -rww + ex->refEntity.customShader = trap->R_RegisterShader("gfx/effects/forcePush"); + } else { // superkewl "refraction" (well sort of) effect -rww refEntity_t ent; vec3_t ang; float scale; @@ -4882,61 +4157,49 @@ static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) float alpha; int tDif; - if (!cent->bodyFadeTime) - { //the duration for the expansion and fade + if (!cent->bodyFadeTime) { // the duration for the expansion and fade cent->bodyFadeTime = cg.time + REFRACT_EFFECT_DURATION; } - //closer tDif is to 0, the closer we are to - //being "done" + // closer tDif is to 0, the closer we are to + // being "done" tDif = (cent->bodyFadeTime - cg.time); - if ((REFRACT_EFFECT_DURATION-tDif) < 200) - { //stop following the hand after a little and stay in a fixed spot - //save the initial spot of the effect + if ((REFRACT_EFFECT_DURATION - tDif) < 200) { // stop following the hand after a little and stay in a fixed spot + // save the initial spot of the effect VectorCopy(org, cent->pushEffectOrigin); } - //scale from 1.0f to 0.1f then hold at 0.1 for the rest of the duration - if (cent->currentState.powerups & (1 << PW_PULL)) - { - scale = (float)(REFRACT_EFFECT_DURATION-tDif)*0.003f; - } - else - { + // scale from 1.0f to 0.1f then hold at 0.1 for the rest of the duration + if (cent->currentState.powerups & (1 << PW_PULL)) { + scale = (float)(REFRACT_EFFECT_DURATION - tDif) * 0.003f; + } else { scale = (float)(tDif)*0.003f; } - if (scale > 1.0f) - { + if (scale > 1.0f) { scale = 1.0f; - } - else if (scale < 0.2f) - { + } else if (scale < 0.2f) { scale = 0.2f; } - //start alpha at 244, fade to 10 - alpha = (float)tDif*0.488f; + // start alpha at 244, fade to 10 + alpha = (float)tDif * 0.488f; - if (alpha > 244.0f) - { + if (alpha > 244.0f) { alpha = 244.0f; - } - else if (alpha < 10.0f) - { + } else if (alpha < 10.0f) { alpha = 10.0f; } - memset( &ent, 0, sizeof( ent ) ); - ent.shaderTime = (cent->bodyFadeTime-REFRACT_EFFECT_DURATION) / 1000.0f; + memset(&ent, 0, sizeof(ent)); + ent.shaderTime = (cent->bodyFadeTime - REFRACT_EFFECT_DURATION) / 1000.0f; - VectorCopy( cent->pushEffectOrigin, ent.origin ); + VectorCopy(cent->pushEffectOrigin, ent.origin); VectorSubtract(ent.origin, cg.refdef.vieworg, ent.axis[0]); vLen = VectorLength(ent.axis[0]); - if (vLen <= 0.1f) - { // Entity is right on vieworg. quit. + if (vLen <= 0.1f) { // Entity is right on vieworg. quit. return; } @@ -4944,21 +4207,14 @@ static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) ang[ROLL] += 180.0f; AnglesToAxis(ang, ent.axis); - //radius must be a power of 2, and is the actual captured texture size - if (vLen < 128) - { + // radius must be a power of 2, and is the actual captured texture size + if (vLen < 128) { ent.radius = 256; - } - else if (vLen < 256) - { + } else if (vLen < 256) { ent.radius = 128; - } - else if (vLen < 512) - { + } else if (vLen < 512) { ent.radius = 64; - } - else - { + } else { ent.radius = 32; } @@ -4967,63 +4223,43 @@ static void CG_ForcePushBlur( vec3_t org, centity_t *cent ) VectorScale(ent.axis[2], scale, ent.axis[2]); ent.hModel = cgs.media.halfShieldModel; - ent.customShader = cgs.media.refractionShader; //cgs.media.cloakedShader; + ent.customShader = cgs.media.refractionShader; // cgs.media.cloakedShader; ent.nonNormalizedAxes = qtrue; - //make it partially transparent so it blends with the background - ent.renderfx = (RF_DISTORTION|RF_FORCE_ENT_ALPHA); + // make it partially transparent so it blends with the background + ent.renderfx = (RF_DISTORTION | RF_FORCE_ENT_ALPHA); ent.shaderRGBA[0] = 255.0f; ent.shaderRGBA[1] = 255.0f; ent.shaderRGBA[2] = 255.0f; ent.shaderRGBA[3] = alpha; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } } -static const char *cg_pushBoneNames[] = -{ - "cranium", - "lower_lumbar", - "rhand", - "lhand", - "ltibia", - "rtibia", - "lradius", - "rradius", - NULL -}; +static const char *cg_pushBoneNames[] = {"cranium", "lower_lumbar", "rhand", "lhand", "ltibia", "rtibia", "lradius", "rradius", NULL}; -static void CG_ForcePushBodyBlur( centity_t *cent ) -{ +static void CG_ForcePushBodyBlur(centity_t *cent) { vec3_t fxOrg; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; int bolt; int i; - if (cent->localAnimIndex > 1) - { //Sorry, the humanoid IS IN ANOTHER CASTLE. + if (cent->localAnimIndex > 1) { // Sorry, the humanoid IS IN ANOTHER CASTLE. return; } - if (cg.snap && - CG_IsMindTricked(cent->currentState.trickedentindex, - cent->currentState.trickedentindex2, - cent->currentState.trickedentindex3, - cent->currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - return; //this entity is mind-tricking the current client, so don't render it + if (cg.snap && CG_IsMindTricked(cent->currentState.trickedentindex, cent->currentState.trickedentindex2, cent->currentState.trickedentindex3, + cent->currentState.trickedentindex4, cg.snap->ps.clientNum)) { + return; // this entity is mind-tricking the current client, so don't render it } assert(cent->ghoul2); - for (i = 0; cg_pushBoneNames[i]; i++) - { //go through all the bones we want to put a blur effect on + for (i = 0; cg_pushBoneNames[i]; i++) { // go through all the bones we want to put a blur effect on bolt = trap->G2API_AddBolt(cent->ghoul2, 0, cg_pushBoneNames[i]); - if (bolt == -1) - { + if (bolt == -1) { assert(!"You've got an invalid bone/bolt name in cg_pushBoneNames"); continue; } @@ -5031,15 +4267,14 @@ static void CG_ForcePushBodyBlur( centity_t *cent ) trap->G2API_GetBoltMatrix(cent->ghoul2, 0, bolt, &boltMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, fxOrg); - //standard effect, don't be refractive (for now) + // standard effect, don't be refractive (for now) CG_ForcePushBlur(fxOrg, NULL); } } -static void CG_ForceGripEffect( vec3_t org ) -{ - localEntity_t *ex; - float wv = sin( cg.time * 0.004f ) * 0.08f + 0.1f; +static void CG_ForceGripEffect(vec3_t org) { + localEntity_t *ex; + float wv = sin(cg.time * 0.004f) * 0.08f + 0.1f; ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -5047,19 +4282,18 @@ static void CG_ForceGripEffect( vec3_t org ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], 55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], 55, ex->pos.trDelta); - ex->color[0] = 200+((wv*255)); - if (ex->color[0] > 255) - { + ex->color[0] = 200 + ((wv * 255)); + if (ex->color[0] > 255) { ex->color[0] = 255; } ex->color[1] = 0; ex->color[2] = 0; - ex->refEntity.customShader = trap->R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = trap->R_RegisterShader("gfx/effects/forcePush"); ex = CG_AllocLocalEntity(); ex->leType = LE_PUFF; @@ -5068,10 +4302,10 @@ static void CG_ForceGripEffect( vec3_t org ) ex->radius = 2.0f; ex->startTime = cg.time; ex->endTime = ex->startTime + 120; - VectorCopy( org, ex->pos.trBase ); + VectorCopy(org, ex->pos.trBase); ex->pos.trTime = cg.time; ex->pos.trType = TR_LINEAR; - VectorScale( cg.refdef.viewaxis[1], -55, ex->pos.trDelta ); + VectorScale(cg.refdef.viewaxis[1], -55, ex->pos.trDelta); /* ex->color[0] = 200+((wv*255)); @@ -5083,10 +4317,9 @@ static void CG_ForceGripEffect( vec3_t org ) ex->color[0] = 255; ex->color[1] = 255; ex->color[2] = 255; - ex->refEntity.customShader = cgs.media.redSaberGlowShader;//trap->R_RegisterShader( "gfx/effects/forcePush" ); + ex->refEntity.customShader = cgs.media.redSaberGlowShader; // trap->R_RegisterShader( "gfx/effects/forcePush" ); } - /* =============== CG_AddRefEntityWithPowerups @@ -5095,81 +4328,66 @@ Adds a piece with modifications or duplications for powerups Also called by CG_Missile for quad rockets, but nobody can tell... =============== */ -void CG_AddRefEntityWithPowerups( refEntity_t *ent, entityState_t *state, int team ) { +void CG_AddRefEntityWithPowerups(refEntity_t *ent, entityState_t *state, int team) { - if (CG_IsMindTricked(state->trickedentindex, - state->trickedentindex2, - state->trickedentindex3, - state->trickedentindex4, - cg.snap->ps.clientNum)) - { - return; //this entity is mind-tricking the current client, so don't render it + if (CG_IsMindTricked(state->trickedentindex, state->trickedentindex2, state->trickedentindex3, state->trickedentindex4, cg.snap->ps.clientNum)) { + return; // this entity is mind-tricking the current client, so don't render it } - trap->R_AddRefEntityToScene( ent ); + trap->R_AddRefEntityToScene(ent); } -#define MAX_SHIELD_TIME 2000.0 -#define MIN_SHIELD_TIME 2000.0 +#define MAX_SHIELD_TIME 2000.0 +#define MIN_SHIELD_TIME 2000.0 - -void CG_PlayerShieldHit(int entitynum, vec3_t dir, int amount) -{ +void CG_PlayerShieldHit(int entitynum, vec3_t dir, int amount) { centity_t *cent; - int time; + int time; - if (entitynum < 0 || entitynum >= MAX_GENTITIES) - { + if (entitynum < 0 || entitynum >= MAX_GENTITIES) { return; } cent = &cg_entities[entitynum]; - if (amount > 100) - { - time = cg.time + MAX_SHIELD_TIME; // 2 sec. - } - else - { - time = cg.time + 500 + amount*15; + if (amount > 100) { + time = cg.time + MAX_SHIELD_TIME; // 2 sec. + } else { + time = cg.time + 500 + amount * 15; } - if (time > cent->damageTime) - { + if (time > cent->damageTime) { cent->damageTime = time; VectorScale(dir, -1, dir); vectoangles(dir, cent->damageAngles); } } - -void CG_DrawPlayerShield(centity_t *cent, vec3_t origin) -{ +void CG_DrawPlayerShield(centity_t *cent, vec3_t origin) { refEntity_t ent; - int alpha; - float scale; + int alpha; + float scale; // Don't draw the shield when the player is dead. - if (cent->currentState.eFlags & EF_DEAD) - { + if (cent->currentState.eFlags & EF_DEAD) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); - VectorCopy( origin, ent.origin ); + VectorCopy(origin, ent.origin); ent.origin[2] += 10.0; - AnglesToAxis( cent->damageAngles, ent.axis ); + AnglesToAxis(cent->damageAngles, ent.axis); - alpha = 255.0 * ((cent->damageTime - cg.time) / MIN_SHIELD_TIME) + Q_flrand(0.0f, 1.0f)*16; - if (alpha>255) - alpha=255; + alpha = 255.0 * ((cent->damageTime - cg.time) / MIN_SHIELD_TIME) + Q_flrand(0.0f, 1.0f) * 16; + if (alpha > 255) + alpha = 255; // Make it bigger, but tighter if more solid - scale = 1.4 - ((float)alpha*(0.4/255.0)); // Range from 1.0 to 1.4 - VectorScale( ent.axis[0], scale, ent.axis[0] ); - VectorScale( ent.axis[1], scale, ent.axis[1] ); - VectorScale( ent.axis[2], scale, ent.axis[2] ); + scale = 1.4 - ((float)alpha * (0.4 / 255.0)); // Range from 1.0 to 1.4 + VectorScale(ent.axis[0], scale, ent.axis[0]); + VectorScale(ent.axis[1], scale, ent.axis[1]); + VectorScale(ent.axis[2], scale, ent.axis[2]); ent.hModel = cgs.media.halfShieldModel; ent.customShader = cgs.media.halfShieldShader; @@ -5177,18 +4395,13 @@ void CG_DrawPlayerShield(centity_t *cent, vec3_t origin) ent.shaderRGBA[1] = alpha; ent.shaderRGBA[2] = alpha; ent.shaderRGBA[3] = 255; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } - -void CG_PlayerHitFX(centity_t *cent) -{ +void CG_PlayerHitFX(centity_t *cent) { // only do the below fx if the cent in question is...uh...me, and it's first person. - if (cent->currentState.clientNum != cg.predictedPlayerState.clientNum || cg.renderingThirdPerson) - { - if (cent->damageTime > cg.time - && cent->currentState.NPC_class != CLASS_VEHICLE ) - { + if (cent->currentState.clientNum != cg.predictedPlayerState.clientNum || cg.renderingThirdPerson) { + if (cent->damageTime > cg.time && cent->currentState.NPC_class != CLASS_VEHICLE) { CG_DrawPlayerShield(cent, cent->lerpOrigin); } @@ -5196,46 +4409,43 @@ void CG_PlayerHitFX(centity_t *cent) } } - - /* ================= CG_LightVerts ================= */ -int CG_LightVerts( vec3_t normal, int numVerts, polyVert_t *verts ) -{ - int i, j; - float incoming; - vec3_t ambientLight; - vec3_t lightDir; - vec3_t directedLight; +int CG_LightVerts(vec3_t normal, int numVerts, polyVert_t *verts) { + int i, j; + float incoming; + vec3_t ambientLight; + vec3_t lightDir; + vec3_t directedLight; - trap->R_LightForPoint( verts[0].xyz, ambientLight, directedLight, lightDir ); + trap->R_LightForPoint(verts[0].xyz, ambientLight, directedLight, lightDir); for (i = 0; i < numVerts; i++) { - incoming = DotProduct (normal, lightDir); - if ( incoming <= 0 ) { + incoming = DotProduct(normal, lightDir); + if (incoming <= 0) { verts[i].modulate[0] = ambientLight[0]; verts[i].modulate[1] = ambientLight[1]; verts[i].modulate[2] = ambientLight[2]; verts[i].modulate[3] = 255; continue; } - j = ( ambientLight[0] + incoming * directedLight[0] ); - if ( j > 255 ) { + j = (ambientLight[0] + incoming * directedLight[0]); + if (j > 255) { j = 255; } verts[i].modulate[0] = j; - j = ( ambientLight[1] + incoming * directedLight[1] ); - if ( j > 255 ) { + j = (ambientLight[1] + incoming * directedLight[1]); + if (j > 255) { j = 255; } verts[i].modulate[1] = j; - j = ( ambientLight[2] + incoming * directedLight[2] ); - if ( j > 255 ) { + j = (ambientLight[2] + incoming * directedLight[2]); + if (j > 255) { j = 255; } verts[i].modulate[2] = j; @@ -5245,107 +4455,87 @@ int CG_LightVerts( vec3_t normal, int numVerts, polyVert_t *verts ) return qtrue; } -static void CG_RGBForSaberColor( saber_colors_t color, vec3_t rgb ) -{ - switch( color ) - { - case SABER_RED: - VectorSet( rgb, 1.0f, 0.2f, 0.2f ); - break; - case SABER_ORANGE: - VectorSet( rgb, 1.0f, 0.5f, 0.1f ); - break; - case SABER_YELLOW: - VectorSet( rgb, 1.0f, 1.0f, 0.2f ); - break; - case SABER_GREEN: - VectorSet( rgb, 0.2f, 1.0f, 0.2f ); - break; - case SABER_BLUE: - VectorSet( rgb, 0.2f, 0.4f, 1.0f ); - break; - case SABER_PURPLE: - VectorSet( rgb, 0.9f, 0.2f, 1.0f ); - break; - default: - break; +static void CG_RGBForSaberColor(saber_colors_t color, vec3_t rgb) { + switch (color) { + case SABER_RED: + VectorSet(rgb, 1.0f, 0.2f, 0.2f); + break; + case SABER_ORANGE: + VectorSet(rgb, 1.0f, 0.5f, 0.1f); + break; + case SABER_YELLOW: + VectorSet(rgb, 1.0f, 1.0f, 0.2f); + break; + case SABER_GREEN: + VectorSet(rgb, 0.2f, 1.0f, 0.2f); + break; + case SABER_BLUE: + VectorSet(rgb, 0.2f, 0.4f, 1.0f); + break; + case SABER_PURPLE: + VectorSet(rgb, 0.9f, 0.2f, 1.0f); + break; + default: + break; } } -static void CG_DoSaberLight( saberInfo_t *saber ) -{ - vec3_t positions[MAX_BLADES*2], mid={0}, rgbs[MAX_BLADES*2], rgb={0}; - float lengths[MAX_BLADES*2]={0}, totallength = 0, numpositions = 0, dist, diameter = 0; - int i, j; +static void CG_DoSaberLight(saberInfo_t *saber) { + vec3_t positions[MAX_BLADES * 2], mid = {0}, rgbs[MAX_BLADES * 2], rgb = {0}; + float lengths[MAX_BLADES * 2] = {0}, totallength = 0, numpositions = 0, dist, diameter = 0; + int i, j; - //RGB combine all the colors of the sabers you're using into one averaged color! - if ( !saber ) - { + // RGB combine all the colors of the sabers you're using into one averaged color! + if (!saber) { return; } - if ( (saber->saberFlags2&SFL2_NO_DLIGHT) ) - {//no dlight! + if ((saber->saberFlags2 & SFL2_NO_DLIGHT)) { // no dlight! return; } - for ( i = 0; i < saber->numBlades; i++ ) - { - if ( saber->blade[i].length >= 0.5f ) - { - //FIXME: make RGB sabers - CG_RGBForSaberColor( saber->blade[i].color, rgbs[i] ); + for (i = 0; i < saber->numBlades; i++) { + if (saber->blade[i].length >= 0.5f) { + // FIXME: make RGB sabers + CG_RGBForSaberColor(saber->blade[i].color, rgbs[i]); lengths[i] = saber->blade[i].length; - if ( saber->blade[i].length*2.0f > diameter ) - { - diameter = saber->blade[i].length*2.0f; + if (saber->blade[i].length * 2.0f > diameter) { + diameter = saber->blade[i].length * 2.0f; } totallength += saber->blade[i].length; - VectorMA( saber->blade[i].muzzlePoint, saber->blade[i].length, saber->blade[i].muzzleDir, positions[i] ); - if ( !numpositions ) - {//first blade, store middle of that as midpoint - VectorMA( saber->blade[i].muzzlePoint, saber->blade[i].length*0.5, saber->blade[i].muzzleDir, mid ); - VectorCopy( rgbs[i], rgb ); + VectorMA(saber->blade[i].muzzlePoint, saber->blade[i].length, saber->blade[i].muzzleDir, positions[i]); + if (!numpositions) { // first blade, store middle of that as midpoint + VectorMA(saber->blade[i].muzzlePoint, saber->blade[i].length * 0.5, saber->blade[i].muzzleDir, mid); + VectorCopy(rgbs[i], rgb); } numpositions++; } } - if ( totallength ) - {//actually have something to do - if ( numpositions == 1 ) - {//only 1 blade, midpoint is already set (halfway between the start and end of that blade), rgb is already set, so it diameter - } - else - {//multiple blades, calc averages - VectorClear( mid ); - VectorClear( rgb ); - //now go through all the data and get the average RGB and middle position and the radius - for ( i = 0; i < MAX_BLADES*2; i++ ) - { - if ( lengths[i] ) - { - VectorMA( rgb, lengths[i], rgbs[i], rgb ); - VectorAdd( mid, positions[i], mid ); + if (totallength) { // actually have something to do + if (numpositions == 1) { // only 1 blade, midpoint is already set (halfway between the start and end of that blade), rgb is already set, so it diameter + } else { // multiple blades, calc averages + VectorClear(mid); + VectorClear(rgb); + // now go through all the data and get the average RGB and middle position and the radius + for (i = 0; i < MAX_BLADES * 2; i++) { + if (lengths[i]) { + VectorMA(rgb, lengths[i], rgbs[i], rgb); + VectorAdd(mid, positions[i], mid); } } - //get middle rgb - VectorScale( rgb, 1/totallength, rgb );//get the average, normalized RGB - //get mid position - VectorScale( mid, 1/numpositions, mid ); - //find the farthest distance between the blade tips, this will be our diameter - for ( i = 0; i < MAX_BLADES*2; i++ ) - { - if ( lengths[i] ) - { - for ( j = 0; j < MAX_BLADES*2; j++ ) - { - if ( lengths[j] ) - { - dist = Distance( positions[i], positions[j] ); - if ( dist > diameter ) - { + // get middle rgb + VectorScale(rgb, 1 / totallength, rgb); // get the average, normalized RGB + // get mid position + VectorScale(mid, 1 / numpositions, mid); + // find the farthest distance between the blade tips, this will be our diameter + for (i = 0; i < MAX_BLADES * 2; i++) { + if (lengths[i]) { + for (j = 0; j < MAX_BLADES * 2; j++) { + if (lengths[j]) { + dist = Distance(positions[i], positions[j]); + if (dist > diameter) { diameter = dist; } } @@ -5354,68 +4544,64 @@ static void CG_DoSaberLight( saberInfo_t *saber ) } } - trap->R_AddLightToScene( mid, diameter + (Q_flrand(0.0f, 1.0f)*8.0f), rgb[0], rgb[1], rgb[2] ); + trap->R_AddLightToScene(mid, diameter + (Q_flrand(0.0f, 1.0f) * 8.0f), rgb[0], rgb[1], rgb[2]); } } -void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color, int rfx, qboolean doLight ) -{ - vec3_t mid; - qhandle_t blade = 0, glow = 0; +void CG_DoSaber(vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color, int rfx, qboolean doLight) { + vec3_t mid; + qhandle_t blade = 0, glow = 0; refEntity_t saber; float radiusmult; float radiusRange; float radiusStart; - if ( length < 0.5f ) - { + if (length < 0.5f) { // if the thing is so short, just forget even adding me. return; } // Find the midpoint of the saber for lighting purposes - VectorMA( origin, length * 0.5f, dir, mid ); + VectorMA(origin, length * 0.5f, dir, mid); - switch( color ) - { - case SABER_RED: - glow = cgs.media.redSaberGlowShader; - blade = cgs.media.redSaberCoreShader; - break; - case SABER_ORANGE: - glow = cgs.media.orangeSaberGlowShader; - blade = cgs.media.orangeSaberCoreShader; - break; - case SABER_YELLOW: - glow = cgs.media.yellowSaberGlowShader; - blade = cgs.media.yellowSaberCoreShader; - break; - case SABER_GREEN: - glow = cgs.media.greenSaberGlowShader; - blade = cgs.media.greenSaberCoreShader; - break; - case SABER_BLUE: - glow = cgs.media.blueSaberGlowShader; - blade = cgs.media.blueSaberCoreShader; - break; - case SABER_PURPLE: - glow = cgs.media.purpleSaberGlowShader; - blade = cgs.media.purpleSaberCoreShader; - break; - default: - glow = cgs.media.blueSaberGlowShader; - blade = cgs.media.blueSaberCoreShader; - break; + switch (color) { + case SABER_RED: + glow = cgs.media.redSaberGlowShader; + blade = cgs.media.redSaberCoreShader; + break; + case SABER_ORANGE: + glow = cgs.media.orangeSaberGlowShader; + blade = cgs.media.orangeSaberCoreShader; + break; + case SABER_YELLOW: + glow = cgs.media.yellowSaberGlowShader; + blade = cgs.media.yellowSaberCoreShader; + break; + case SABER_GREEN: + glow = cgs.media.greenSaberGlowShader; + blade = cgs.media.greenSaberCoreShader; + break; + case SABER_BLUE: + glow = cgs.media.blueSaberGlowShader; + blade = cgs.media.blueSaberCoreShader; + break; + case SABER_PURPLE: + glow = cgs.media.purpleSaberGlowShader; + blade = cgs.media.purpleSaberCoreShader; + break; + default: + glow = cgs.media.blueSaberGlowShader; + blade = cgs.media.blueSaberCoreShader; + break; } - if (doLight) - { // always add a light because sabers cast a nice glow before they slice you in half!! or something... - vec3_t rgb={1,1,1}; - CG_RGBForSaberColor( color, rgb ); - trap->R_AddLightToScene( mid, (length*1.4f) + (Q_flrand(0.0f, 1.0f)*3.0f), rgb[0], rgb[1], rgb[2] ); + if (doLight) { // always add a light because sabers cast a nice glow before they slice you in half!! or something... + vec3_t rgb = {1, 1, 1}; + CG_RGBForSaberColor(color, rgb); + trap->R_AddLightToScene(mid, (length * 1.4f) + (Q_flrand(0.0f, 1.0f) * 3.0f), rgb[0], rgb[1], rgb[2]); } - memset( &saber, 0, sizeof( refEntity_t )); + memset(&saber, 0, sizeof(refEntity_t)); // Saber glow is it's own ref type because it uses a ton of sprites, otherwise it would eat up too many // refEnts to do each glow blob individually @@ -5423,51 +4609,47 @@ void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float // Jeff, I did this because I foolishly wished to have a bright halo as the saber is unleashed. // It's not quite what I'd hoped tho. If you have any ideas, go for it! --Pat - if (length < lengthMax) - { - radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. - } - else - { + if (length < lengthMax) { + radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. + } else { radiusmult = 1.0; } - if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) - { //draw the blade as a post-render so it doesn't get in the cap... + if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && + cgs.glconfig.stencilBits >= 4) { // draw the blade as a post-render so it doesn't get in the cap... rfx |= RF_FORCEPOST; } radiusRange = radius * 0.075f; - radiusStart = radius-radiusRange; + radiusStart = radius - radiusRange; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; - //saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - VectorCopy( origin, saber.origin ); - VectorCopy( dir, saber.axis[0] ); + VectorCopy(origin, saber.origin); + VectorCopy(dir, saber.axis[0]); saber.reType = RT_SABER_GLOW; saber.customShader = glow; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; saber.renderfx = rfx; - trap->R_AddRefEntityToScene( &saber ); + trap->R_AddRefEntityToScene(&saber); // Do the hot core - VectorMA( origin, length, dir, saber.origin ); - VectorMA( origin, -1, dir, saber.oldorigin ); - + VectorMA(origin, length, dir, saber.origin); + VectorMA(origin, -1, dir, saber.oldorigin); -// CG_TestLine(saber.origin, saber.oldorigin, 50, 0x000000ff, 3); + // CG_TestLine(saber.origin, saber.oldorigin, 50, 0x000000ff, 3); saber.customShader = blade; saber.reType = RT_LINE; - radiusStart = radius/3.0f; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; -// saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + radiusStart = radius / 3.0f; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; saber.shaderTexCoord[0] = saber.shaderTexCoord[1] = 1.0f; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; - trap->R_AddRefEntityToScene( &saber ); + trap->R_AddRefEntityToScene(&saber); } //-------------------------------------------------------------- @@ -5475,107 +4657,93 @@ void CG_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float // // Can pass in NULL for the axis //-------------------------------------------------------------- -void CG_GetTagWorldPosition( refEntity_t *model, char *tag, vec3_t pos, matrix3_t axis ) -{ - orientation_t orientation; +void CG_GetTagWorldPosition(refEntity_t *model, char *tag, vec3_t pos, matrix3_t axis) { + orientation_t orientation; int i = 0; // Get the requested tag - trap->R_LerpTag( &orientation, model->hModel, model->oldframe, model->frame, - 1.0f - model->backlerp, tag ); + trap->R_LerpTag(&orientation, model->hModel, model->oldframe, model->frame, 1.0f - model->backlerp, tag); - VectorCopy( model->origin, pos ); - for ( i = 0 ; i < 3 ; i++ ) - { - VectorMA( pos, orientation.origin[i], model->axis[i], pos ); + VectorCopy(model->origin, pos); + for (i = 0; i < 3; i++) { + VectorMA(pos, orientation.origin[i], model->axis[i], pos); } - if ( axis ) - { - MatrixMultiply( orientation.axis, model->axis, axis ); + if (axis) { + MatrixMultiply(orientation.axis, model->axis, axis); } } -#define MAX_MARK_FRAGMENTS 128 -#define MAX_MARK_POINTS 384 +#define MAX_MARK_FRAGMENTS 128 +#define MAX_MARK_POINTS 384 extern markPoly_t *CG_AllocMark(); -void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) -{ -// byte colors[4]; - int i, j; - int numFragments; - matrix3_t axis; - vec3_t originalPoints[4], mid; - vec3_t markPoints[MAX_MARK_POINTS], projection; - polyVert_t *v, verts[MAX_VERTS_ON_POLY]; - markPoly_t *mark; - markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; +void CG_CreateSaberMarks(vec3_t start, vec3_t end, vec3_t normal) { + // byte colors[4]; + int i, j; + int numFragments; + matrix3_t axis; + vec3_t originalPoints[4], mid; + vec3_t markPoints[MAX_MARK_POINTS], projection; + polyVert_t *v, verts[MAX_VERTS_ON_POLY]; + markPoly_t *mark; + markFragment_t markFragments[MAX_MARK_FRAGMENTS], *mf; - float radius = 0.65f; + float radius = 0.65f; - if ( !cg_marks.integer ) - { + if (!cg_marks.integer) { return; } - VectorSubtract( end, start, axis[1] ); - VectorNormalize( axis[1] ); + VectorSubtract(end, start, axis[1]); + VectorNormalize(axis[1]); // create the texture axis - VectorCopy( normal, axis[0] ); - CrossProduct( axis[1], axis[0], axis[2] ); + VectorCopy(normal, axis[0]); + CrossProduct(axis[1], axis[0], axis[2]); // create the full polygon that we'll project - for ( i = 0 ; i < 3 ; i++ ) - { // stretch a bit more in the direction that we are traveling in... debateable as to whether this makes things better or worse + for (i = 0; i < 3; i++) { // stretch a bit more in the direction that we are traveling in... debateable as to whether this makes things better or worse originalPoints[0][i] = start[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = end[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = end[i] + radius * axis[1][i] + radius * axis[2][i]; originalPoints[3][i] = start[i] - radius * axis[1][i] + radius * axis[2][i]; } - VectorScale( normal, -1, projection ); + VectorScale(normal, -1, projection); // get the fragments - numFragments = trap->R_MarkFragments( 4, (const float (*)[3])originalPoints, - projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments ); + numFragments = trap->R_MarkFragments(4, (const float(*)[3])originalPoints, projection, MAX_MARK_POINTS, markPoints[0], MAX_MARK_FRAGMENTS, markFragments); - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) - { + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { // we have an upper limit on the complexity of polygons that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_POLY ) - { + if (mf->numPoints > MAX_VERTS_ON_POLY) { mf->numPoints = MAX_VERTS_ON_POLY; } - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) - { + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { vec3_t delta; // Set up our texture coords, this may need some work - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); - VectorAdd( end, start, mid ); - VectorScale( mid, 0.5f, mid ); - VectorSubtract( v->xyz, mid, delta ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); + VectorAdd(end, start, mid); + VectorScale(mid, 0.5f, mid); + VectorSubtract(v->xyz, mid, delta); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * (0.05f + Q_flrand(0.0f, 1.0f) * 0.03f); + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * (0.15f + Q_flrand(0.0f, 1.0f) * 0.05f); } - if (cg_saberDynamicMarks.integer) - { + if (cg_saberDynamicMarks.integer) { int i = 0; int i_2 = 0; addpolyArgStruct_t apArgs; vec3_t x; - memset (&apArgs, 0, sizeof(apArgs)); + memset(&apArgs, 0, sizeof(apArgs)); - while (i < 4) - { - while (i_2 < 3) - { + while (i < 4) { + while (i_2 < 3) { apArgs.p[i][i_2] = verts[i].xyz[i_2]; i_2++; @@ -5588,10 +4756,8 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) i = 0; i_2 = 0; - while (i < 4) - { - while (i_2 < 2) - { + while (i < 4) { + while (i_2 < 2) { apArgs.ev[i][i_2] = verts[i].st[i_2]; i_2++; @@ -5601,12 +4767,11 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) i++; } - //When using addpoly, having a situation like this tends to cause bad results. + // When using addpoly, having a situation like this tends to cause bad results. //(I assume it doesn't like trying to draw a polygon over two planes and extends - //the vertex out to some odd value) + // the vertex out to some odd value) VectorSubtract(apArgs.p[0], apArgs.p[3], x); - if (VectorLength(x) > 3.0f) - { + if (VectorLength(x) > 3.0f) { return; } @@ -5627,14 +4792,14 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) apArgs.motionDelay = 0; apArgs.killTime = cg_saberDynamicMarkTime.integer; apArgs.shader = cgs.media.rivetMarkShader; - apArgs.flags = 0x08000000|0x00000004; + apArgs.flags = 0x08000000 | 0x00000004; trap->FX_AddPoly(&apArgs); apArgs.shader = cgs.media.mSaberDamageGlow; apArgs.rgb1[0] = 215 + Q_flrand(0.0f, 1.0f) * 40.0f; apArgs.rgb1[1] = 96 + Q_flrand(0.0f, 1.0f) * 32.0f; - apArgs.rgb1[2] = apArgs.alphaParm = Q_flrand(0.0f, 1.0f)*15.0f; + apArgs.rgb1[2] = apArgs.alphaParm = Q_flrand(0.0f, 1.0f) * 15.0f; apArgs.rgb1[0] /= 255; apArgs.rgb1[1] /= 255; @@ -5644,9 +4809,7 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) apArgs.killTime = 100; trap->FX_AddPoly(&apArgs); - } - else - { + } else { // save it persistantly, do burn first mark = CG_AllocMark(); mark->time = cg.time; @@ -5654,7 +4817,7 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) mark->markShader = cgs.media.rivetMarkShader; mark->poly.numVerts = mf->numPoints; mark->color[0] = mark->color[1] = mark->color[2] = mark->color[3] = 255; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); // And now do a glow pass // by moving the start time back, we can hack it to fade out way before the burn does @@ -5665,62 +4828,50 @@ void CG_CreateSaberMarks( vec3_t start, vec3_t end, vec3_t normal ) mark->poly.numVerts = mf->numPoints; mark->color[0] = 215 + Q_flrand(0.0f, 1.0f) * 40.0f; mark->color[1] = 96 + Q_flrand(0.0f, 1.0f) * 32.0f; - mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f)*15.0f; - memcpy( mark->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + mark->color[2] = mark->color[3] = Q_flrand(0.0f, 1.0f) * 15.0f; + memcpy(mark->verts, verts, mf->numPoints * sizeof(verts[0])); } } } -qboolean CG_G2TraceCollide(trace_t *tr, vec3_t const mins, vec3_t const maxs, const vec3_t lastValidStart, const vec3_t lastValidEnd) -{ - G2Trace_t G2Trace; - centity_t *g2Hit; - vec3_t angles; - int tN = 0; - float fRadius = 0.0f; +qboolean CG_G2TraceCollide(trace_t *tr, vec3_t const mins, vec3_t const maxs, const vec3_t lastValidStart, const vec3_t lastValidEnd) { + G2Trace_t G2Trace; + centity_t *g2Hit; + vec3_t angles; + int tN = 0; + float fRadius = 0.0f; - if (mins && maxs && - (mins[0] || maxs[0])) - { - fRadius=(maxs[0]-mins[0])/2.0f; + if (mins && maxs && (mins[0] || maxs[0])) { + fRadius = (maxs[0] - mins[0]) / 2.0f; } - memset (&G2Trace, 0, sizeof(G2Trace)); + memset(&G2Trace, 0, sizeof(G2Trace)); - while (tN < MAX_G2_COLLISIONS) - { + while (tN < MAX_G2_COLLISIONS) { G2Trace[tN].mEntityNum = -1; tN++; } g2Hit = &cg_entities[tr->entityNum]; - if (g2Hit && g2Hit->ghoul2) - { + if (g2Hit && g2Hit->ghoul2) { angles[ROLL] = angles[PITCH] = 0; angles[YAW] = g2Hit->lerpAngles[YAW]; - if (com_optvehtrace.integer && - g2Hit->currentState.eType == ET_NPC && - g2Hit->currentState.NPC_class == CLASS_VEHICLE && - g2Hit->m_pVehicle) - { - trap->G2API_CollisionDetectCache ( G2Trace, g2Hit->ghoul2, angles, g2Hit->lerpOrigin, cg.time, g2Hit->currentState.number, (float *)lastValidStart, (float *)lastValidEnd, g2Hit->modelScale, 0, cg_g2TraceLod.integer, fRadius ); - } - else - { - trap->G2API_CollisionDetect ( G2Trace, g2Hit->ghoul2, angles, g2Hit->lerpOrigin, cg.time, g2Hit->currentState.number, (float *)lastValidStart, (float *)lastValidEnd, g2Hit->modelScale, 0, cg_g2TraceLod.integer, fRadius ); + if (com_optvehtrace.integer && g2Hit->currentState.eType == ET_NPC && g2Hit->currentState.NPC_class == CLASS_VEHICLE && g2Hit->m_pVehicle) { + trap->G2API_CollisionDetectCache(G2Trace, g2Hit->ghoul2, angles, g2Hit->lerpOrigin, cg.time, g2Hit->currentState.number, (float *)lastValidStart, + (float *)lastValidEnd, g2Hit->modelScale, 0, cg_g2TraceLod.integer, fRadius); + } else { + trap->G2API_CollisionDetect(G2Trace, g2Hit->ghoul2, angles, g2Hit->lerpOrigin, cg.time, g2Hit->currentState.number, (float *)lastValidStart, + (float *)lastValidEnd, g2Hit->modelScale, 0, cg_g2TraceLod.integer, fRadius); } - if (G2Trace[0].mEntityNum != g2Hit->currentState.number) - { + if (G2Trace[0].mEntityNum != g2Hit->currentState.number) { tr->fraction = 1.0f; tr->entityNum = ENTITYNUM_NONE; tr->startsolid = 0; tr->allsolid = 0; return qfalse; - } - else - { //Yay! + } else { // Yay! VectorCopy(G2Trace[0].mCollisionPosition, tr->endpos); VectorCopy(G2Trace[0].mCollisionNormal, tr->plane.normal); return qtrue; @@ -5730,72 +4881,60 @@ qboolean CG_G2TraceCollide(trace_t *tr, vec3_t const mins, vec3_t const maxs, co return qfalse; } -void CG_G2SaberEffects(vec3_t start, vec3_t end, centity_t *owner) -{ +void CG_G2SaberEffects(vec3_t start, vec3_t end, centity_t *owner) { trace_t trace; vec3_t startTr; vec3_t endTr; qboolean backWards = qfalse; qboolean doneWithTraces = qfalse; - while (!doneWithTraces) - { - if (!backWards) - { + while (!doneWithTraces) { + if (!backWards) { VectorCopy(start, startTr); VectorCopy(end, endTr); - } - else - { + } else { VectorCopy(end, startTr); VectorCopy(start, endTr); } - CG_Trace( &trace, startTr, NULL, NULL, endTr, owner->currentState.number, MASK_PLAYERSOLID ); + CG_Trace(&trace, startTr, NULL, NULL, endTr, owner->currentState.number, MASK_PLAYERSOLID); - if (trace.entityNum < MAX_CLIENTS) - { //hit a client.. + if (trace.entityNum < MAX_CLIENTS) { // hit a client.. CG_G2TraceCollide(&trace, NULL, NULL, startTr, endTr); - if (trace.entityNum != ENTITYNUM_NONE) - { //it succeeded with the ghoul2 trace - trap->FX_PlayEffectID( cgs.effects.mSaberBloodSparks, trace.endpos, trace.plane.normal, -1, -1, qfalse ); + if (trace.entityNum != ENTITYNUM_NONE) { // it succeeded with the ghoul2 trace + trap->FX_PlayEffectID(cgs.effects.mSaberBloodSparks, trace.endpos, trace.plane.normal, -1, -1, qfalse); trap->S_StartSound(trace.endpos, trace.entityNum, CHAN_AUTO, trap->S_RegisterSound(va("sound/weapons/saber/saberhit%i.wav", Q_irand(1, 3)))); } } - if (!backWards) - { + if (!backWards) { backWards = qtrue; - } - else - { + } else { doneWithTraces = qtrue; } } } -#define CG_MAX_SABER_COMP_TIME 400 //last registered saber entity hit must match within this many ms for the client effect to take place. +#define CG_MAX_SABER_COMP_TIME 400 // last registered saber entity hit must match within this many ms for the client effect to take place. -void CG_AddGhoul2Mark(int shader, float size, vec3_t start, vec3_t end, int entnum, - vec3_t entposition, float entangle, void *ghoul2, vec3_t scale, int lifeTime) -{ +void CG_AddGhoul2Mark(int shader, float size, vec3_t start, vec3_t end, int entnum, vec3_t entposition, float entangle, void *ghoul2, vec3_t scale, + int lifeTime) { SSkinGoreData goreSkin; assert(ghoul2); - memset ( &goreSkin, 0, sizeof(goreSkin) ); + memset(&goreSkin, 0, sizeof(goreSkin)); - if (trap->G2API_GetNumGoreMarks(ghoul2, 0) >= cg_ghoul2Marks.integer) - { //you've got too many marks already + if (trap->G2API_GetNumGoreMarks(ghoul2, 0) >= cg_ghoul2Marks.integer) { // you've got too many marks already return; } - goreSkin.growDuration = -1; // default expandy time + goreSkin.growDuration = -1; // default expandy time goreSkin.goreScaleStartFraction = 1.0; // default start scale goreSkin.frontFaces = qtrue; goreSkin.backFaces = qtrue; - goreSkin.lifeTime = lifeTime; //last randomly 10-20 seconds + goreSkin.lifeTime = lifeTime; // last randomly 10-20 seconds /* if (lifeTime) { @@ -5803,42 +4942,37 @@ void CG_AddGhoul2Mark(int shader, float size, vec3_t start, vec3_t end, int entn } goreSkin.fadeRGB = qtrue; //fade on RGB instead of alpha (this depends on the shader really, modify if needed) */ - //rwwFIXMEFIXME: fade has sorting issues with other non-fading decals, disabled until fixed + // rwwFIXMEFIXME: fade has sorting issues with other non-fading decals, disabled until fixed goreSkin.baseModelOnly = qfalse; goreSkin.currentTime = cg.time; - goreSkin.entNum = entnum; - goreSkin.SSize = size; - goreSkin.TSize = size; - goreSkin.theta = flrand(0.0f,6.28f); - goreSkin.shader = shader; + goreSkin.entNum = entnum; + goreSkin.SSize = size; + goreSkin.TSize = size; + goreSkin.theta = flrand(0.0f, 6.28f); + goreSkin.shader = shader; - if (!scale[0] && !scale[1] && !scale[2]) - { + if (!scale[0] && !scale[1] && !scale[2]) { VectorSet(goreSkin.scale, 1.0f, 1.0f, 1.0f); - } - else - { + } else { VectorCopy(goreSkin.scale, scale); } - VectorCopy (start, goreSkin.hitLocation); + VectorCopy(start, goreSkin.hitLocation); VectorSubtract(end, start, goreSkin.rayDirection); - if (VectorNormalize(goreSkin.rayDirection)<.1f) - { + if (VectorNormalize(goreSkin.rayDirection) < .1f) { return; } - VectorCopy ( entposition, goreSkin.position ); + VectorCopy(entposition, goreSkin.position); goreSkin.angles[YAW] = entangle; trap->G2API_AddSkinGore(ghoul2, &goreSkin); } -void CG_SaberCompWork(vec3_t start, vec3_t end, centity_t *owner, int saberNum, int bladeNum) -{ +void CG_SaberCompWork(vec3_t start, vec3_t end, centity_t *owner, int saberNum, int bladeNum) { trace_t trace; vec3_t startTr; vec3_t endTr; @@ -5847,165 +4981,119 @@ void CG_SaberCompWork(vec3_t start, vec3_t end, centity_t *owner, int saberNum, qboolean doEffect = qfalse; clientInfo_t *client = NULL; - if ((cg.time - owner->serverSaberHitTime) > CG_MAX_SABER_COMP_TIME) - { + if ((cg.time - owner->serverSaberHitTime) > CG_MAX_SABER_COMP_TIME) { return; } - if (cg.time == owner->serverSaberHitTime) - { //don't want to do it the same frame as the server hit, to avoid burst effect concentrations every x ms. + if (cg.time == owner->serverSaberHitTime) { // don't want to do it the same frame as the server hit, to avoid burst effect concentrations every x ms. return; } - while (!doneWithTraces) - { - if (!backWards) - { + while (!doneWithTraces) { + if (!backWards) { VectorCopy(start, startTr); VectorCopy(end, endTr); - } - else - { + } else { VectorCopy(end, startTr); VectorCopy(start, endTr); } - CG_Trace( &trace, startTr, NULL, NULL, endTr, owner->currentState.number, MASK_PLAYERSOLID ); + CG_Trace(&trace, startTr, NULL, NULL, endTr, owner->currentState.number, MASK_PLAYERSOLID); - if (trace.entityNum == owner->serverSaberHitIndex) - { //this is the guy the server says we last hit, so continue. - if (cg_entities[trace.entityNum].ghoul2) - { //If it has a g2 instance, do the proper ghoul2 checks + if (trace.entityNum == owner->serverSaberHitIndex) { // this is the guy the server says we last hit, so continue. + if (cg_entities[trace.entityNum].ghoul2) { // If it has a g2 instance, do the proper ghoul2 checks CG_G2TraceCollide(&trace, NULL, NULL, startTr, endTr); - if (trace.entityNum != ENTITYNUM_NONE) - { //it succeeded with the ghoul2 trace + if (trace.entityNum != ENTITYNUM_NONE) { // it succeeded with the ghoul2 trace doEffect = qtrue; - if (cg_ghoul2Marks.integer) - { + if (cg_ghoul2Marks.integer) { vec3_t ePos; centity_t *trEnt = &cg_entities[trace.entityNum]; - if (trEnt->ghoul2) - { - if (trEnt->currentState.eType != ET_NPC || - trEnt->currentState.NPC_class != CLASS_VEHICLE || - !trEnt->m_pVehicle || - trEnt->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) - { //don't do on fighters cause they have crazy full axial angles + if (trEnt->ghoul2) { + if (trEnt->currentState.eType != ET_NPC || trEnt->currentState.NPC_class != CLASS_VEHICLE || !trEnt->m_pVehicle || + trEnt->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) { // don't do on fighters cause they have crazy full axial angles int weaponMarkShader = 0, markShader = cgs.media.bdecal_saberglow; VectorSubtract(endTr, trace.endpos, ePos); VectorNormalize(ePos); VectorMA(trace.endpos, 4.0f, ePos, ePos); - if (owner->currentState.eType == ET_NPC) - { + if (owner->currentState.eType == ET_NPC) { client = owner->npcClient; - } - else - { + } else { client = &cgs.clientinfo[owner->currentState.clientNum]; } - if ( client - && client->infoValid ) - { - if ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) ) - { - if ( client->saber[saberNum].g2MarksShader2 ) - {//we have a shader to use instead of the standard mark shader + if (client && client->infoValid) { + if (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum)) { + if (client->saber[saberNum].g2MarksShader2) { // we have a shader to use instead of the standard mark shader markShader = client->saber[saberNum].g2MarksShader2; } - if ( client->saber[saberNum].g2WeaponMarkShader2 ) - {//we have a shader to use as a splashback onto the weapon model + if (client->saber[saberNum].g2WeaponMarkShader2) { // we have a shader to use as a splashback onto the weapon model weaponMarkShader = client->saber[saberNum].g2WeaponMarkShader2; } - } - else - { - if ( client->saber[saberNum].g2MarksShader ) - {//we have a shader to use instead of the standard mark shader + } else { + if (client->saber[saberNum].g2MarksShader) { // we have a shader to use instead of the standard mark shader markShader = client->saber[saberNum].g2MarksShader; } - if ( client->saber[saberNum].g2WeaponMarkShader ) - {//we have a shader to use as a splashback onto the weapon model + if (client->saber[saberNum].g2WeaponMarkShader) { // we have a shader to use as a splashback onto the weapon model weaponMarkShader = client->saber[saberNum].g2WeaponMarkShader; } } } - CG_AddGhoul2Mark(markShader, flrand(3.0f, 4.0f), - trace.endpos, ePos, trace.entityNum, trEnt->lerpOrigin, trEnt->lerpAngles[YAW], - trEnt->ghoul2, trEnt->modelScale, Q_irand(5000, 10000)); - if ( weaponMarkShader ) - { + CG_AddGhoul2Mark(markShader, flrand(3.0f, 4.0f), trace.endpos, ePos, trace.entityNum, trEnt->lerpOrigin, trEnt->lerpAngles[YAW], + trEnt->ghoul2, trEnt->modelScale, Q_irand(5000, 10000)); + if (weaponMarkShader) { vec3_t splashBackDir; - VectorScale( ePos, -1 , splashBackDir ); - CG_AddGhoul2Mark(weaponMarkShader, flrand(0.5f, 2.0f), - trace.endpos, splashBackDir, owner->currentState.clientNum, owner->lerpOrigin, owner->lerpAngles[YAW], - owner->ghoul2, owner->modelScale, Q_irand(5000, 10000)); + VectorScale(ePos, -1, splashBackDir); + CG_AddGhoul2Mark(weaponMarkShader, flrand(0.5f, 2.0f), trace.endpos, splashBackDir, owner->currentState.clientNum, + owner->lerpOrigin, owner->lerpAngles[YAW], owner->ghoul2, owner->modelScale, Q_irand(5000, 10000)); } } } } } - } - else - { //otherwise, we're all set. + } else { // otherwise, we're all set. doEffect = qtrue; } - if (doEffect) - { + if (doEffect) { int hitPersonFxID = cgs.effects.mSaberBloodSparks; int hitOtherFxID = cgs.effects.mSaberCut; - if (owner->currentState.eType == ET_NPC) - { + if (owner->currentState.eType == ET_NPC) { client = owner->npcClient; - } - else - { + } else { client = &cgs.clientinfo[owner->currentState.clientNum]; } - if ( client && client->infoValid ) - { - if ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) ) - {//use second blade style values - if ( client->saber[saberNum].hitPersonEffect2 ) - { + if (client && client->infoValid) { + if (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum)) { // use second blade style values + if (client->saber[saberNum].hitPersonEffect2) { hitPersonFxID = client->saber[saberNum].hitPersonEffect2; } - if ( client->saber[saberNum].hitOtherEffect2 ) - {//custom hit other effect + if (client->saber[saberNum].hitOtherEffect2) { // custom hit other effect hitOtherFxID = client->saber[saberNum].hitOtherEffect2; } - } - else - {//use first blade style values - if ( client->saber[saberNum].hitPersonEffect ) - { + } else { // use first blade style values + if (client->saber[saberNum].hitPersonEffect) { hitPersonFxID = client->saber[saberNum].hitPersonEffect; } - if ( client->saber[saberNum].hitOtherEffect ) - {//custom hit other effect + if (client->saber[saberNum].hitOtherEffect) { // custom hit other effect hitOtherFxID = client->saber[saberNum].hitOtherEffect; } } } - if (!trace.plane.normal[0] && !trace.plane.normal[1] && !trace.plane.normal[2]) - { //who cares, just shoot it somewhere. + if (!trace.plane.normal[0] && !trace.plane.normal[1] && !trace.plane.normal[2]) { // who cares, just shoot it somewhere. trace.plane.normal[1] = 1; } - - if (owner->serverSaberFleshImpact) - { //do standard player/live ent hit sparks - trap->FX_PlayEffectID( hitPersonFxID, trace.endpos, trace.plane.normal, -1, -1, qfalse ); - //trap->S_StartSound(trace.endpos, trace.entityNum, CHAN_AUTO, trap->S_RegisterSound(va("sound/weapons/saber/saberhit%i.wav", Q_irand(1, 3)))); - } - else - { //do the cut effect - trap->FX_PlayEffectID( hitOtherFxID, trace.endpos, trace.plane.normal, -1, -1, qfalse ); + + if (owner->serverSaberFleshImpact) { // do standard player/live ent hit sparks + trap->FX_PlayEffectID(hitPersonFxID, trace.endpos, trace.plane.normal, -1, -1, qfalse); + // trap->S_StartSound(trace.endpos, trace.entityNum, CHAN_AUTO, trap->S_RegisterSound(va("sound/weapons/saber/saberhit%i.wav", Q_irand(1, + // 3)))); + } else { // do the cut effect + trap->FX_PlayEffectID(hitOtherFxID, trace.endpos, trace.plane.normal, -1, -1, qfalse); } doEffect = qfalse; } @@ -6021,20 +5109,19 @@ void CG_SaberCompWork(vec3_t start, vec3_t end, centity_t *owner, int saberNum, doneWithTraces = qtrue; } */ - doneWithTraces = qtrue; //disabling backwards tr for now, sometimes it just makes too many effects. + doneWithTraces = qtrue; // disabling backwards tr for now, sometimes it just makes too many effects. } } -#define SABER_TRAIL_TIME 40.0f -#define FX_USE_ALPHA 0x08000000 +#define SABER_TRAIL_TIME 40.0f +#define FX_USE_ALPHA 0x08000000 -qboolean BG_SuperBreakWinAnim( int anim ); +qboolean BG_SuperBreakWinAnim(int anim); -void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, int saberNum, int bladeNum, vec3_t origin, vec3_t angles, qboolean fromSaber, qboolean dontDraw) -{ - vec3_t org_, end, v, - axis_[3] = {{0,0,0}, {0,0,0}, {0,0,0}}; // shut the compiler up - trace_t trace; +void CG_AddSaberBlade(centity_t *cent, centity_t *scent, refEntity_t *saber, int renderfx, int modelIndex, int saberNum, int bladeNum, vec3_t origin, + vec3_t angles, qboolean fromSaber, qboolean dontDraw) { + vec3_t org_, end, v, axis_[3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; // shut the compiler up + trace_t trace; int i = 0; int trailDur; float saberLen; @@ -6042,27 +5129,23 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in clientInfo_t *client; centity_t *saberEnt; saberTrail_t *saberTrail; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; vec3_t futureAngles; effectTrailArgStruct_t fx; int scolor = 0; - int useModelIndex = 0; + int useModelIndex = 0; - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { client = cent->npcClient; assert(client); - } - else - { + } else { client = &cgs.clientinfo[cent->currentState.number]; } saberEnt = &cg_entities[cent->currentState.saberEntityNum]; saberLen = client->saber[saberNum].blade[bladeNum].length; - if (saberLen <= 0 && !dontDraw) - { //don't bother then. + if (saberLen <= 0 && !dontDraw) { // don't bother then. return; } @@ -6070,210 +5153,160 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in futureAngles[PITCH] = angles[PITCH]; futureAngles[ROLL] = angles[ROLL]; - - if ( fromSaber ) - { + if (fromSaber) { useModelIndex = 0; - } - else - { - useModelIndex = saberNum+1; - } - //Assume bladeNum is equal to the bolt index because bolts should be added in order of the blades. - //if there is an effect on this blade, play it - if ( !WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) - && client->saber[saberNum].bladeEffect ) - { - trap->FX_PlayBoltedEffectID(client->saber[saberNum].bladeEffect, scent->lerpOrigin, - scent->ghoul2, bladeNum, scent->currentState.number, useModelIndex, -1, qfalse); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) - && client->saber[saberNum].bladeEffect2 ) - { - trap->FX_PlayBoltedEffectID(client->saber[saberNum].bladeEffect2, scent->lerpOrigin, - scent->ghoul2, bladeNum, scent->currentState.number, useModelIndex, -1, qfalse); - } - //get the boltMatrix + } else { + useModelIndex = saberNum + 1; + } + // Assume bladeNum is equal to the bolt index because bolts should be added in order of the blades. + // if there is an effect on this blade, play it + if (!WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && client->saber[saberNum].bladeEffect) { + trap->FX_PlayBoltedEffectID(client->saber[saberNum].bladeEffect, scent->lerpOrigin, scent->ghoul2, bladeNum, scent->currentState.number, useModelIndex, + -1, qfalse); + } else if (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && client->saber[saberNum].bladeEffect2) { + trap->FX_PlayBoltedEffectID(client->saber[saberNum].bladeEffect2, scent->lerpOrigin, scent->ghoul2, bladeNum, scent->currentState.number, useModelIndex, + -1, qfalse); + } + // get the boltMatrix trap->G2API_GetBoltMatrix(scent->ghoul2, useModelIndex, bladeNum, &boltMatrix, futureAngles, origin, cg.time, cgs.gameModels, scent->modelScale); // work the matrix axis stuff into the original axis and origins used. BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org_); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, axis_[0]); - if (!fromSaber && saberEnt && !cent->currentState.saberInFlight) - { + if (!fromSaber && saberEnt && !cent->currentState.saberInFlight) { VectorCopy(org_, saberEnt->currentState.pos.trBase); VectorCopy(axis_[0], saberEnt->currentState.apos.trBase); } - VectorMA( org_, saberLen, axis_[0], end ); + VectorMA(org_, saberLen, axis_[0], end); - VectorAdd( end, axis_[0], end ); + VectorAdd(end, axis_[0], end); - if (cent->currentState.eType == ET_NPC) - { - if (cent->currentState.boltToPlayer) - { - if (saberNum == 0) - { + if (cent->currentState.eType == ET_NPC) { + if (cent->currentState.boltToPlayer) { + if (saberNum == 0) { scolor = (cent->currentState.boltToPlayer & 0x07) - 1; - } - else - { + } else { scolor = ((cent->currentState.boltToPlayer & 0x38) >> 3) - 1; } - } - else - { + } else { scolor = client->saber[saberNum].blade[bladeNum].color; } - } - else - { - if (saberNum == 0) - { + } else { + if (saberNum == 0) { scolor = client->icolor1; - } - else - { + } else { scolor = client->icolor2; } } - if (cgs.gametype >= GT_TEAM && - cgs.gametype != GT_SIEGE && - !cgs.jediVmerc && - cent->currentState.eType != ET_NPC) - { - if (client->team == TEAM_RED) - { + if (cgs.gametype >= GT_TEAM && cgs.gametype != GT_SIEGE && !cgs.jediVmerc && cent->currentState.eType != ET_NPC) { + if (client->team == TEAM_RED) { scolor = SABER_RED; - } - else if (client->team == TEAM_BLUE) - { + } else if (client->team == TEAM_BLUE) { scolor = SABER_BLUE; } } - if (!cg_saberContact.integer) - { //if we don't have saber contact enabled, just add the blade and don't care what it's touching + if (!cg_saberContact.integer) { // if we don't have saber contact enabled, just add the blade and don't care what it's touching goto CheckTrail; } - if (!dontDraw) - { - if (cg_saberModelTraceEffect.integer) - { + if (!dontDraw) { + if (cg_saberModelTraceEffect.integer) { CG_G2SaberEffects(org_, end, cent); - } - else if (cg_saberClientVisualCompensation.integer) - { - CG_Trace( &trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID ); + } else if (cg_saberClientVisualCompensation.integer) { + CG_Trace(&trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID); - if (trace.fraction != 1) - { //nudge the endpos a very small amount from the beginning to the end, so the comp trace hits at the end. - //I'm only bothering with this because I want to do a backwards trace too in the comp trace, so if the - //blade is sticking through a player or something the standard trace doesn't it, it will make sparks - //on each side. + if (trace.fraction != 1) { // nudge the endpos a very small amount from the beginning to the end, so the comp trace hits at the end. + // I'm only bothering with this because I want to do a backwards trace too in the comp trace, so if the + // blade is sticking through a player or something the standard trace doesn't it, it will make sparks + // on each side. vec3_t seDif; VectorSubtract(trace.endpos, org_, seDif); VectorNormalize(seDif); - trace.endpos[0] += seDif[0]*0.1f; - trace.endpos[1] += seDif[1]*0.1f; - trace.endpos[2] += seDif[2]*0.1f; + trace.endpos[0] += seDif[0] * 0.1f; + trace.endpos[1] += seDif[1] * 0.1f; + trace.endpos[2] += seDif[2] * 0.1f; } - if (client->saber[saberNum].blade[bladeNum].storageTime < cg.time) - { //debounce it in case our framerate is absurdly high. Using storageTime since it's not used for anything else in the client. + if (client->saber[saberNum].blade[bladeNum].storageTime < + cg.time) { // debounce it in case our framerate is absurdly high. Using storageTime since it's not used for anything else in the client. CG_SaberCompWork(org_, trace.endpos, cent, saberNum, bladeNum); client->saber[saberNum].blade[bladeNum].storageTime = cg.time + 5; } } - for ( i = 0; i < 1; i++ )//was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad if we hit a corner, blade is still 8 longer than hit + for (i = 0; i < 1; i++) // was 2 because it would go through architecture and leave saber trails on either side of the brush - but still looks bad if we + // hit a corner, blade is still 8 longer than hit { - if ( i ) - {//tracing from end to base - CG_Trace( &trace, end, NULL, NULL, org_, ENTITYNUM_NONE, MASK_SOLID ); - } - else - {//tracing from base to end - CG_Trace( &trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID ); + if (i) { // tracing from end to base + CG_Trace(&trace, end, NULL, NULL, org_, ENTITYNUM_NONE, MASK_SOLID); + } else { // tracing from base to end + CG_Trace(&trace, org_, NULL, NULL, end, ENTITYNUM_NONE, MASK_SOLID); } - if ( trace.fraction < 1.0f ) - { + if (trace.fraction < 1.0f) { vec3_t trDir; VectorCopy(trace.plane.normal, trDir); - if (!trDir[0] && !trDir[1] && !trDir[2]) - { + if (!trDir[0] && !trDir[1] && !trDir[2]) { trDir[1] = 1; } - if ( (client->saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS) ) - {//don't actually draw the marks/impact effects - } - else - { - if (!(trace.surfaceFlags & SURF_NOIMPACT) ) // never spark on sky + if ((client->saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS)) { // don't actually draw the marks/impact effects + } else { + if (!(trace.surfaceFlags & SURF_NOIMPACT)) // never spark on sky { - trap->FX_PlayEffectID( cgs.effects.mSparks, trace.endpos, trDir, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.mSparks, trace.endpos, trDir, -1, -1, qfalse); } } - //Stop saber? (it wouldn't look right if it was stuck through a thin wall and unable to hurt players on the other side) + // Stop saber? (it wouldn't look right if it was stuck through a thin wall and unable to hurt players on the other side) VectorSubtract(org_, trace.endpos, v); saberLen = VectorLength(v); VectorCopy(trace.endpos, end); - if ( (client->saber[saberNum].saberFlags2&SFL2_NO_WALL_MARKS) ) - {//don't actually draw the marks - } - else - {//draw marks if we hit a wall + if ((client->saber[saberNum].saberFlags2 & SFL2_NO_WALL_MARKS)) { // don't actually draw the marks + } else { // draw marks if we hit a wall // All I need is a bool to mark whether I have a previous point to work with. //....come up with something better.. - if ( client->saber[saberNum].blade[bladeNum].trail.haveOldPos[i] ) - { - if ( trace.entityNum == ENTITYNUM_WORLD || cg_entities[trace.entityNum].currentState.eType == ET_TERRAIN || (cg_entities[trace.entityNum].currentState.eFlags & EF_PERMANENT) ) - {//only put marks on architecture + if (client->saber[saberNum].blade[bladeNum].trail.haveOldPos[i]) { + if (trace.entityNum == ENTITYNUM_WORLD || cg_entities[trace.entityNum].currentState.eType == ET_TERRAIN || + (cg_entities[trace.entityNum].currentState.eFlags & EF_PERMANENT)) { // only put marks on architecture // Let's do some cool burn/glowing mark bits!!! - CG_CreateSaberMarks( client->saber[saberNum].blade[bladeNum].trail.oldPos[i], trace.endpos, trace.plane.normal ); + CG_CreateSaberMarks(client->saber[saberNum].blade[bladeNum].trail.oldPos[i], trace.endpos, trace.plane.normal); - //make a sound - if ( cg.time - client->saber[saberNum].blade[bladeNum].hitWallDebounceTime >= 100 ) - {//ugh, need to have a real sound debouncer... or do this game-side + // make a sound + if (cg.time - client->saber[saberNum].blade[bladeNum].hitWallDebounceTime >= + 100) { // ugh, need to have a real sound debouncer... or do this game-side client->saber[saberNum].blade[bladeNum].hitWallDebounceTime = cg.time; - trap->S_StartSound ( trace.endpos, -1, CHAN_WEAPON, trap->S_RegisterSound( va("sound/weapons/saber/saberhitwall%i", Q_irand(1, 3)) ) ); + trap->S_StartSound(trace.endpos, -1, CHAN_WEAPON, + trap->S_RegisterSound(va("sound/weapons/saber/saberhitwall%i", Q_irand(1, 3)))); } } - } - else - { + } else { // if we impact next frame, we'll mark a slash mark client->saber[saberNum].blade[bladeNum].trail.haveOldPos[i] = qtrue; - // CG_ImpactMark( cgs.media.rivetMarkShader, client->saber[saberNum].blade[bladeNum].trail.oldPos[i], client->saber[saberNum].blade[bladeNum].trail.oldNormal[i], - // 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); + // CG_ImpactMark( cgs.media.rivetMarkShader, client->saber[saberNum].blade[bladeNum].trail.oldPos[i], + //client->saber[saberNum].blade[bladeNum].trail.oldNormal[i], 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); } } // stash point so we can connect-the-dots later - VectorCopy( trace.endpos, client->saber[saberNum].blade[bladeNum].trail.oldPos[i] ); - VectorCopy( trace.plane.normal, client->saber[saberNum].blade[bladeNum].trail.oldNormal[i] ); - } - else - { - if ( client->saber[saberNum].blade[bladeNum].trail.haveOldPos[i] ) - { + VectorCopy(trace.endpos, client->saber[saberNum].blade[bladeNum].trail.oldPos[i]); + VectorCopy(trace.plane.normal, client->saber[saberNum].blade[bladeNum].trail.oldNormal[i]); + } else { + if (client->saber[saberNum].blade[bladeNum].trail.haveOldPos[i]) { // Hmmm, no impact this frame, but we have an old point // Let's put the mark there, we should use an endcap mark to close the line, but we // can probably just get away with a round mark - // CG_ImpactMark( cgs.media.rivetMarkShader, client->saber[saberNum].blade[bladeNum].trail.oldPos[i], client->saber[saberNum].blade[bladeNum].trail.oldNormal[i], - // 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); + // CG_ImpactMark( cgs.media.rivetMarkShader, client->saber[saberNum].blade[bladeNum].trail.oldPos[i], + //client->saber[saberNum].blade[bladeNum].trail.oldNormal[i], 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, qfalse, 1.1f, qfalse ); } // we aren't impacting, so turn off our mark tracking mechanism @@ -6283,44 +5316,40 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in } CheckTrail: - if (!cg_saberTrail.integer) - { //don't do the trail in this case + if (!cg_saberTrail.integer) { // don't do the trail in this case goto JustDoIt; } - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) && client->saber[saberNum].trailStyle > 1 ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) && client->saber[saberNum].trailStyle2 > 1 ) ) - {//don't actually draw the trail at all + if ((!WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && client->saber[saberNum].trailStyle > 1) || + (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && + client->saber[saberNum].trailStyle2 > 1)) { // don't actually draw the trail at all goto JustDoIt; } - //FIXME: if trailStyle is 1, use the motion blur instead + // FIXME: if trailStyle is 1, use the motion blur instead saberTrail = &client->saber[saberNum].blade[bladeNum].trail; saberTrail->duration = saberMoveData[cent->currentState.saberMove].trailLength; - trailDur = (saberTrail->duration/5.0f); - if (!trailDur) - { //hmm.. ok, default - if ( BG_SuperBreakWinAnim(cent->currentState.torsoAnim) ) - { + trailDur = (saberTrail->duration / 5.0f); + if (!trailDur) { // hmm.. ok, default + if (BG_SuperBreakWinAnim(cent->currentState.torsoAnim)) { trailDur = 150; - } - else - { + } else { trailDur = SABER_TRAIL_TIME; } } // if we happen to be timescaled or running in a high framerate situation, we don't want to flood // the system with very small trail slices...but perhaps doing it by distance would yield better results? - if ( cg.time > saberTrail->lastTime + 2 || cg_saberTrail.integer == 2 ) // 2ms + if (cg.time > saberTrail->lastTime + 2 || cg_saberTrail.integer == 2) // 2ms { - if (!dontDraw) - { - if ( (BG_SuperBreakWinAnim(cent->currentState.torsoAnim) || saberMoveData[cent->currentState.saberMove].trailLength > 0 || ((cent->currentState.powerups & (1 << PW_SPEED) && cg_speedTrail.integer)) || (cent->currentState.saberInFlight && saberNum == 0)) && cg.time < saberTrail->lastTime + 2000 ) // if we have a stale segment, don't draw until we have a fresh one + if (!dontDraw) { + if ((BG_SuperBreakWinAnim(cent->currentState.torsoAnim) || saberMoveData[cent->currentState.saberMove].trailLength > 0 || + ((cent->currentState.powerups & (1 << PW_SPEED) && cg_speedTrail.integer)) || (cent->currentState.saberInFlight && saberNum == 0)) && + cg.time < saberTrail->lastTime + 2000) // if we have a stale segment, don't draw until we have a fresh one { - #if 0 +#if 0 if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) { polyVert_t verts[4]; @@ -6366,70 +5395,63 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in trap->R_AddPolyToScene( 2, 4, verts ); } else - #endif +#endif { - vec3_t rgb1={255.0f,255.0f,255.0f}; + vec3_t rgb1 = {255.0f, 255.0f, 255.0f}; - switch( scolor ) - { - case SABER_RED: - VectorSet( rgb1, 255.0f, 0.0f, 0.0f ); - break; - case SABER_ORANGE: - VectorSet( rgb1, 255.0f, 64.0f, 0.0f ); - break; - case SABER_YELLOW: - VectorSet( rgb1, 255.0f, 255.0f, 0.0f ); - break; - case SABER_GREEN: - VectorSet( rgb1, 0.0f, 255.0f, 0.0f ); - break; - case SABER_BLUE: - VectorSet( rgb1, 0.0f, 64.0f, 255.0f ); - break; - case SABER_PURPLE: - VectorSet( rgb1, 220.0f, 0.0f, 255.0f ); - break; - default: - VectorSet( rgb1, 0.0f, 64.0f, 255.0f ); - break; + switch (scolor) { + case SABER_RED: + VectorSet(rgb1, 255.0f, 0.0f, 0.0f); + break; + case SABER_ORANGE: + VectorSet(rgb1, 255.0f, 64.0f, 0.0f); + break; + case SABER_YELLOW: + VectorSet(rgb1, 255.0f, 255.0f, 0.0f); + break; + case SABER_GREEN: + VectorSet(rgb1, 0.0f, 255.0f, 0.0f); + break; + case SABER_BLUE: + VectorSet(rgb1, 0.0f, 64.0f, 255.0f); + break; + case SABER_PURPLE: + VectorSet(rgb1, 220.0f, 0.0f, 255.0f); + break; + default: + VectorSet(rgb1, 0.0f, 64.0f, 255.0f); + break; } - //Here we will use the happy process of filling a struct in with arguments and passing it to a trap function - //so that we can take the struct and fill in an actual CTrail type using the data within it once we get it - //into the effects area + // Here we will use the happy process of filling a struct in with arguments and passing it to a trap function + // so that we can take the struct and fill in an actual CTrail type using the data within it once we get it + // into the effects area // Go from new muzzle to new end...then to old end...back down to old muzzle...finally // connect back to the new muzzle...this is our trail quad - VectorCopy( org_, fx.mVerts[0].origin ); - VectorMA( end, 3.0f, axis_[0], fx.mVerts[1].origin ); + VectorCopy(org_, fx.mVerts[0].origin); + VectorMA(end, 3.0f, axis_[0], fx.mVerts[1].origin); - VectorCopy( saberTrail->tip, fx.mVerts[2].origin ); - VectorCopy( saberTrail->base, fx.mVerts[3].origin ); + VectorCopy(saberTrail->tip, fx.mVerts[2].origin); + VectorCopy(saberTrail->base, fx.mVerts[3].origin); diff = cg.time - saberTrail->lastTime; // I'm not sure that clipping this is really the best idea - //This prevents the trail from showing at all in low framerate situations. - //if ( diff <= SABER_TRAIL_TIME * 2 ) - if ( diff <= 10000 ) - { //don't draw it if the last time is way out of date - float oldAlpha = 1.0f - ( diff / trailDur ); - - if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) - {//does other stuff below - } - else - { - if ( (!WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) && client->saber[saberNum].trailStyle == 1 ) - || ( WP_SaberBladeUseSecondBladeStyle( &client->saber[saberNum], bladeNum ) && client->saber[saberNum].trailStyle2 == 1 ) ) - {//motion trail + // This prevents the trail from showing at all in low framerate situations. + // if ( diff <= SABER_TRAIL_TIME * 2 ) + if (diff <= 10000) { // don't draw it if the last time is way out of date + float oldAlpha = 1.0f - (diff / trailDur); + + if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) { // does other stuff below + } else { + if ((!WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && client->saber[saberNum].trailStyle == 1) || + (WP_SaberBladeUseSecondBladeStyle(&client->saber[saberNum], bladeNum) && + client->saber[saberNum].trailStyle2 == 1)) { // motion trail fx.mShader = cgs.media.swordTrailShader; - VectorSet( rgb1, 32.0f, 32.0f, 32.0f ); // make the sith sword trail pretty faint - trailDur *= 2.0f; // stay around twice as long? - } - else - { + VectorSet(rgb1, 32.0f, 32.0f, 32.0f); // make the sith sword trail pretty faint + trailDur *= 2.0f; // stay around twice as long? + } else { fx.mShader = cgs.media.saberBlurShader; } fx.mKillTime = trailDur; @@ -6437,7 +5459,7 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in } // New muzzle - VectorCopy( rgb1, fx.mVerts[0].rgb ); + VectorCopy(rgb1, fx.mVerts[0].rgb); fx.mVerts[0].alpha = 255.0f; fx.mVerts[0].ST[0] = 0.0f; @@ -6446,7 +5468,7 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in fx.mVerts[0].destST[1] = 1.0f; // new tip - VectorCopy( rgb1, fx.mVerts[1].rgb ); + VectorCopy(rgb1, fx.mVerts[1].rgb); fx.mVerts[1].alpha = 255.0f; fx.mVerts[1].ST[0] = 0.0f; @@ -6455,7 +5477,7 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in fx.mVerts[1].destST[1] = 0.0f; // old tip - VectorCopy( rgb1, fx.mVerts[2].rgb ); + VectorCopy(rgb1, fx.mVerts[2].rgb); fx.mVerts[2].alpha = 255.0f; fx.mVerts[2].ST[0] = 1.0f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -6464,7 +5486,7 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in fx.mVerts[2].destST[1] = 0.0f; // old muzzle - VectorCopy( rgb1, fx.mVerts[3].rgb ); + VectorCopy(rgb1, fx.mVerts[3].rgb); fx.mVerts[3].alpha = 255.0f; fx.mVerts[3].ST[0] = 1.0f - oldAlpha; // NOTE: this just happens to contain the value I want @@ -6472,20 +5494,16 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in fx.mVerts[3].destST[0] = 1.0f + fx.mVerts[2].ST[0]; fx.mVerts[3].destST[1] = 1.0f; - if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) - { - trap->R_SetRefractionProperties(1.0f, 0.0f, qtrue, qtrue); //don't need to do this every frame.. but.. + if (cg_saberTrail.integer == 2 && cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4) { + trap->R_SetRefractionProperties(1.0f, 0.0f, qtrue, qtrue); // don't need to do this every frame.. but.. - if (BG_SaberInAttack(cent->currentState.saberMove) - ||BG_SuperBreakWinAnim(cent->currentState.torsoAnim)) - { //in attack, strong trail + if (BG_SaberInAttack(cent->currentState.saberMove) || + BG_SuperBreakWinAnim(cent->currentState.torsoAnim)) { // in attack, strong trail fx.mKillTime = 300; - } - else - { //faded trail + } else { // faded trail fx.mKillTime = 40; } - fx.mShader = 2; //2 is always refractive shader + fx.mShader = 2; // 2 is always refractive shader fx.mSetFlags = FX_USE_ALPHA; } /* @@ -6504,67 +5522,53 @@ void CG_AddSaberBlade( centity_t *cent, centity_t *scent, refEntity_t *saber, in } // we must always do this, even if we aren't active..otherwise we won't know where to pick up from - VectorCopy( org_, saberTrail->base ); - VectorMA( end, 3.0f, axis_[0], saberTrail->tip ); + VectorCopy(org_, saberTrail->base); + VectorMA(end, 3.0f, axis_[0], saberTrail->tip); saberTrail->lastTime = cg.time; } JustDoIt: - if (dontDraw) - { + if (dontDraw) { return; } - if ( (client->saber[saberNum].saberFlags2&SFL2_NO_BLADE) ) - {//don't actually draw the blade at all - if ( client->saber[saberNum].numBlades < 3 - && !(client->saber[saberNum].saberFlags2&SFL2_NO_DLIGHT) ) - {//hmm, but still add the dlight - CG_DoSaberLight( &client->saber[saberNum] ); + if ((client->saber[saberNum].saberFlags2 & SFL2_NO_BLADE)) { // don't actually draw the blade at all + if (client->saber[saberNum].numBlades < 3 && !(client->saber[saberNum].saberFlags2 & SFL2_NO_DLIGHT)) { // hmm, but still add the dlight + CG_DoSaberLight(&client->saber[saberNum]); } return; } // Pass in the renderfx flags attached to the saber weapon model...this is done so that saber glows // will get rendered properly in a mirror...not sure if this is necessary?? - //CG_DoSaber( org_, axis_[0], saberLen, client->saber[saberNum].blade[bladeNum].lengthMax, client->saber[saberNum].blade[bladeNum].radius, + // CG_DoSaber( org_, axis_[0], saberLen, client->saber[saberNum].blade[bladeNum].lengthMax, client->saber[saberNum].blade[bladeNum].radius, // scolor, renderfx, (qboolean)(saberNum==0&&bladeNum==0) ); - CG_DoSaber( org_, axis_[0], saberLen, client->saber[saberNum].blade[bladeNum].lengthMax, client->saber[saberNum].blade[bladeNum].radius, - scolor, renderfx, (qboolean)(client->saber[saberNum].numBlades < 3 && !(client->saber[saberNum].saberFlags2&SFL2_NO_DLIGHT)) ); + CG_DoSaber(org_, axis_[0], saberLen, client->saber[saberNum].blade[bladeNum].lengthMax, client->saber[saberNum].blade[bladeNum].radius, scolor, renderfx, + (qboolean)(client->saber[saberNum].numBlades < 3 && !(client->saber[saberNum].saberFlags2 & SFL2_NO_DLIGHT))); } -int CG_IsMindTricked(int trickIndex1, int trickIndex2, int trickIndex3, int trickIndex4, int client) -{ +int CG_IsMindTricked(int trickIndex1, int trickIndex2, int trickIndex3, int trickIndex4, int client) { int checkIn; int sub = 0; - if (cg_entities[client].currentState.forcePowersActive & (1 << FP_SEE)) - { + if (cg_entities[client].currentState.forcePowersActive & (1 << FP_SEE)) { return 0; } - if (client > 47) - { + if (client > 47) { checkIn = trickIndex4; sub = 48; - } - else if (client > 31) - { + } else if (client > 31) { checkIn = trickIndex3; sub = 32; - } - else if (client > 15) - { + } else if (client > 15) { checkIn = trickIndex2; sub = 16; - } - else - { + } else { checkIn = trickIndex1; } - if (checkIn & (1 << (client-sub))) - { + if (checkIn & (1 << (client - sub))) { return 1; } @@ -6573,28 +5577,25 @@ int CG_IsMindTricked(int trickIndex1, int trickIndex2, int trickIndex3, int tric #define SPEED_TRAIL_DISTANCE 6 -void CG_DrawPlayerSphere(centity_t *cent, vec3_t origin, float scale, int shader) -{ +void CG_DrawPlayerSphere(centity_t *cent, vec3_t origin, float scale, int shader) { refEntity_t ent; vec3_t ang; float vLen; vec3_t viewDir; // Don't draw the shield when the player is dead. - if (cent->currentState.eFlags & EF_DEAD) - { + if (cent->currentState.eFlags & EF_DEAD) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); - VectorCopy( origin, ent.origin ); + VectorCopy(origin, ent.origin); ent.origin[2] += 9.0; VectorSubtract(ent.origin, cg.refdef.vieworg, ent.axis[0]); vLen = VectorLength(ent.axis[0]); - if (vLen <= 0.1f) - { // Entity is right on vieworg. quit. + if (vLen <= 0.1f) { // Entity is right on vieworg. quit. return; } @@ -6616,55 +5617,44 @@ void CG_DrawPlayerSphere(centity_t *cent, vec3_t origin, float scale, int shader ent.hModel = cgs.media.halfShieldModel; ent.customShader = shader; - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); - if (!cg.renderingThirdPerson && cent->currentState.number == cg.predictedPlayerState.clientNum) - { //don't do the rest then + if (!cg.renderingThirdPerson && cent->currentState.number == cg.predictedPlayerState.clientNum) { // don't do the rest then return; } - if (!cg_renderToTextureFX.integer) - { + if (!cg_renderToTextureFX.integer) { return; } ang[PITCH] -= 180.0f; AnglesToAxis(ang, ent.axis); - VectorScale(ent.axis[0], scale*0.5f, ent.axis[0]); - VectorScale(ent.axis[1], scale*0.5f, ent.axis[1]); - VectorScale(ent.axis[2], scale*0.5f, ent.axis[2]); + VectorScale(ent.axis[0], scale * 0.5f, ent.axis[0]); + VectorScale(ent.axis[1], scale * 0.5f, ent.axis[1]); + VectorScale(ent.axis[2], scale * 0.5f, ent.axis[2]); - ent.renderfx = (RF_DISTORTION|RF_FORCE_ENT_ALPHA); - if (shader == cgs.media.invulnerabilityShader) - { //ok, ok, this is a little hacky. sorry! + ent.renderfx = (RF_DISTORTION | RF_FORCE_ENT_ALPHA); + if (shader == cgs.media.invulnerabilityShader) { // ok, ok, this is a little hacky. sorry! ent.shaderRGBA[0] = 0; ent.shaderRGBA[1] = 255; ent.shaderRGBA[2] = 0; ent.shaderRGBA[3] = 100; - } - else if (shader == cgs.media.ysalimariShader) - { + } else if (shader == cgs.media.ysalimariShader) { ent.shaderRGBA[0] = 255; ent.shaderRGBA[1] = 255; ent.shaderRGBA[2] = 0; ent.shaderRGBA[3] = 100; - } - else if (shader == cgs.media.endarkenmentShader) - { + } else if (shader == cgs.media.endarkenmentShader) { ent.shaderRGBA[0] = 100; ent.shaderRGBA[1] = 0; ent.shaderRGBA[2] = 0; ent.shaderRGBA[3] = 20; - } - else if (shader == cgs.media.enlightenmentShader) - { + } else if (shader == cgs.media.enlightenmentShader) { ent.shaderRGBA[0] = 255; ent.shaderRGBA[1] = 255; ent.shaderRGBA[2] = 255; ent.shaderRGBA[3] = 20; - } - else - { //ysal red/blue, boon + } else { // ysal red/blue, boon ent.shaderRGBA[0] = 255.0f; ent.shaderRGBA[1] = 255.0f; ent.shaderRGBA[2] = 255.0f; @@ -6676,49 +5666,41 @@ void CG_DrawPlayerSphere(centity_t *cent, vec3_t origin, float scale, int shader VectorMA(ent.origin, 40.0f, viewDir, ent.origin); ent.customShader = trap->R_RegisterShader("effects/refract_2"); - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } -void CG_AddLightningBeam(vec3_t start, vec3_t end) -{ - vec3_t dir, chaos, - c1, c2, - v1, v2; - float len, - s1, s2, s3; +void CG_AddLightningBeam(vec3_t start, vec3_t end) { + vec3_t dir, chaos, c1, c2, v1, v2; + float len, s1, s2, s3; addbezierArgStruct_t b; VectorCopy(start, b.start); VectorCopy(end, b.end); - VectorSubtract( b.end, b.start, dir ); - len = VectorNormalize( dir ); + VectorSubtract(b.end, b.start, dir); + len = VectorNormalize(dir); // Get the base control points, we'll work from there - VectorMA( b.start, 0.3333f * len, dir, c1 ); - VectorMA( b.start, 0.6666f * len, dir, c2 ); + VectorMA(b.start, 0.3333f * len, dir, c1); + VectorMA(b.start, 0.6666f * len, dir, c2); // get some chaos values that really aren't very chaotic :) - s1 = sin( cg.time * 0.005f ) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; - s2 = sin( cg.time * 0.001f ); - s3 = sin( cg.time * 0.011f ); + s1 = sin(cg.time * 0.005f) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; + s2 = sin(cg.time * 0.001f); + s3 = sin(cg.time * 0.011f); - VectorSet( chaos, len * 0.01f * s1, - len * 0.02f * s2, - len * 0.04f * (s1 + s2 + s3)); + VectorSet(chaos, len * 0.01f * s1, len * 0.02f * s2, len * 0.04f * (s1 + s2 + s3)); - VectorAdd( c1, chaos, c1 ); - VectorScale( chaos, 4.0f, v1 ); + VectorAdd(c1, chaos, c1); + VectorScale(chaos, 4.0f, v1); - VectorSet( chaos, -len * 0.02f * s3, - len * 0.01f * (s1 * s2), - -len * 0.02f * (s1 + s2 * s3)); + VectorSet(chaos, -len * 0.02f * s3, len * 0.01f * (s1 * s2), -len * 0.02f * (s1 + s2 * s3)); - VectorAdd( c2, chaos, c2 ); - VectorScale( chaos, 2.0f, v2 ); + VectorAdd(c2, chaos, c2); + VectorScale(chaos, 2.0f, v2); - VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + VectorSet(chaos, 1.0f, 1.0f, 1.0f); VectorCopy(c1, b.control1); VectorCopy(vec3_origin, b.control1Vel); @@ -6744,48 +5726,38 @@ void CG_AddLightningBeam(vec3_t start, vec3_t end) b.rgbParm = 0.0f; b.killTime = 50; - b.shader = trap->R_RegisterShader( "gfx/misc/electric2" ); - b.flags = 0x00000001; //FX_ALPHA_LINEAR + b.shader = trap->R_RegisterShader("gfx/misc/electric2"); + b.flags = 0x00000001; // FX_ALPHA_LINEAR trap->FX_AddBezier(&b); } -void CG_AddRandomLightning(vec3_t start, vec3_t end) -{ +void CG_AddRandomLightning(vec3_t start, vec3_t end) { vec3_t inOrg, outOrg; VectorCopy(start, inOrg); VectorCopy(end, outOrg); - if ( rand() & 1 ) - { + if (rand() & 1) { outOrg[0] += Q_irand(0, 24); inOrg[0] += Q_irand(0, 8); - } - else - { + } else { outOrg[0] -= Q_irand(0, 24); inOrg[0] -= Q_irand(0, 8); } - if ( rand() & 1 ) - { + if (rand() & 1) { outOrg[1] += Q_irand(0, 24); inOrg[1] += Q_irand(0, 8); - } - else - { + } else { outOrg[1] -= Q_irand(0, 24); inOrg[1] -= Q_irand(0, 8); } - if ( rand() & 1 ) - { + if (rand() & 1) { outOrg[2] += Q_irand(0, 50); inOrg[2] += Q_irand(0, 40); - } - else - { + } else { outOrg[2] -= Q_irand(0, 64); inOrg[2] -= Q_irand(0, 40); } @@ -6795,17 +5767,14 @@ void CG_AddRandomLightning(vec3_t start, vec3_t end) extern char *forceHolocronModels[]; -qboolean CG_ThereIsAMaster(void) -{ +qboolean CG_ThereIsAMaster(void) { int i = 0; centity_t *cent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { cent = &cg_entities[i]; - if (cent && cent->currentState.isJediMaster) - { + if (cent && cent->currentState.isJediMaster) { return qtrue; } @@ -6865,51 +5834,43 @@ void CG_DrawNoForceSphere(centity_t *cent, vec3_t origin, float scale, int shade } #endif -//Checks to see if the model string has a * appended with a custom skin name after. -//If so, it terminates the model string correctly, parses the skin name out, and returns -//the handle of the registered skin. -int CG_HandleAppendedSkin(char *modelName) -{ +// Checks to see if the model string has a * appended with a custom skin name after. +// If so, it terminates the model string correctly, parses the skin name out, and returns +// the handle of the registered skin. +int CG_HandleAppendedSkin(char *modelName) { char skinName[MAX_QPATH]; char *p; qhandle_t skinID = 0; int i = 0; - //see if it has a skin name + // see if it has a skin name p = Q_strrchr(modelName, '*'); - if (p) - { //found a *, we should have a model name before it and a skin name after it. - *p = 0; //terminate the modelName string at this point, then go ahead and parse to the next 0 for the skin. + if (p) { // found a *, we should have a model name before it and a skin name after it. + *p = 0; // terminate the modelName string at this point, then go ahead and parse to the next 0 for the skin. p++; - while (p && *p) - { + while (p && *p) { skinName[i] = *p; i++; p++; } skinName[i] = 0; - if (skinName[0]) - { //got it, register the skin under the model path. + if (skinName[0]) { // got it, register the skin under the model path. char baseFolder[MAX_QPATH]; strcpy(baseFolder, modelName); - p = Q_strrchr(baseFolder, '/'); //go back to the first /, should be the path point + p = Q_strrchr(baseFolder, '/'); // go back to the first /, should be the path point - if (p) - { //got it.. terminate at the slash and register. + if (p) { // got it.. terminate at the slash and register. char *useSkinName; *p = 0; - if (strchr(skinName, '|')) - {//three part skin + if (strchr(skinName, '|')) { // three part skin useSkinName = va("%s/|%s", baseFolder, skinName); - } - else - { + } else { useSkinName = va("%s/model_%s.skin", baseFolder, skinName); } @@ -6921,40 +5882,34 @@ int CG_HandleAppendedSkin(char *modelName) return skinID; } -//Create a temporary ghoul2 instance and get the gla name so we can try loading animation data and sounds. +// Create a temporary ghoul2 instance and get the gla name so we can try loading animation data and sounds. void BG_GetVehicleModelName(char *modelName, const char *vehicleName, size_t len); void BG_GetVehicleSkinName(char *skinname, int len); -void CG_CacheG2AnimInfo(char *modelName) -{ +void CG_CacheG2AnimInfo(char *modelName) { void *g2 = NULL; char *slash; char useModel[MAX_QPATH] = {0}; char useSkin[MAX_QPATH] = {0}; int animIndex; - Q_strncpyz(useModel, modelName, sizeof( useModel ) ); - Q_strncpyz(useSkin, modelName, sizeof( useSkin ) ); + Q_strncpyz(useModel, modelName, sizeof(useModel)); + Q_strncpyz(useSkin, modelName, sizeof(useSkin)); - if (modelName[0] == '$') - { //it's a vehicle name actually, let's precache the whole vehicle - BG_GetVehicleModelName(useModel, useModel, sizeof( useModel ) ); - BG_GetVehicleSkinName(useSkin, sizeof( useSkin ) ); - if ( useSkin[0] ) - { //use a custom skin + if (modelName[0] == '$') { // it's a vehicle name actually, let's precache the whole vehicle + BG_GetVehicleModelName(useModel, useModel, sizeof(useModel)); + BG_GetVehicleSkinName(useSkin, sizeof(useSkin)); + if (useSkin[0]) { // use a custom skin trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", useModel, useSkin)); - } - else - { + } else { trap->R_RegisterSkin(va("models/players/%s/model_default.skin", useModel)); } - Q_strncpyz(useModel, va("models/players/%s/model.glm", useModel), sizeof( useModel ) ); + Q_strncpyz(useModel, va("models/players/%s/model.glm", useModel), sizeof(useModel)); } trap->G2API_InitGhoul2Model(&g2, useModel, 0, 0, 0, 0, 0); - if (g2) - { + if (g2) { char GLAName[MAX_QPATH]; char originalModelName[MAX_QPATH]; @@ -6963,21 +5918,18 @@ void CG_CacheG2AnimInfo(char *modelName) GLAName[0] = 0; trap->G2API_GetGLAName(g2, 0, GLAName); - Q_strncpyz(originalModelName, useModel, sizeof( originalModelName ) ); + Q_strncpyz(originalModelName, useModel, sizeof(originalModelName)); - slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { - strcpy(slash, "/animation.cfg" ); + slash = Q_strrchr(GLAName, '/'); + if (slash) { + strcpy(slash, "/animation.cfg"); animIndex = BG_ParseAnimationFile(GLAName, NULL, qfalse); } - if (animIndex != -1) - { - slash = Q_strrchr( originalModelName, '/' ); - if ( slash ) - { + if (animIndex != -1) { + slash = Q_strrchr(originalModelName, '/'); + if (slash) { slash++; *slash = 0; } @@ -6985,13 +5937,12 @@ void CG_CacheG2AnimInfo(char *modelName) BG_ParseAnimationEvtFile(originalModelName, animIndex, bgNumAnimEvents); } - //Now free the temp instance + // Now free the temp instance trap->G2API_CleanGhoul2Models(&g2); } } -static void CG_RegisterVehicleAssets( Vehicle_t *pVeh ) -{ +static void CG_RegisterVehicleAssets(Vehicle_t *pVeh) { /* if ( pVeh->m_pVehicleInfo->exhaustFX ) { @@ -7039,180 +5990,151 @@ static void CG_RegisterVehicleAssets( Vehicle_t *pVeh ) extern void CG_HandleNPCSounds(centity_t *cent); -extern void G_CreateAnimalNPC( Vehicle_t **pVeh, const char *strAnimalType ); -extern void G_CreateSpeederNPC( Vehicle_t **pVeh, const char *strType ); -extern void G_CreateWalkerNPC( Vehicle_t **pVeh, const char *strAnimalType ); -extern void G_CreateFighterNPC( Vehicle_t **pVeh, const char *strType ); +extern void G_CreateAnimalNPC(Vehicle_t **pVeh, const char *strAnimalType); +extern void G_CreateSpeederNPC(Vehicle_t **pVeh, const char *strType); +extern void G_CreateWalkerNPC(Vehicle_t **pVeh, const char *strAnimalType); +extern void G_CreateFighterNPC(Vehicle_t **pVeh, const char *strType); extern playerState_t *cgSendPS[MAX_GENTITIES]; -void CG_G2AnimEntModelLoad(centity_t *cent) -{ - const char *cModelName = CG_ConfigString( CS_MODELS+cent->currentState.modelindex ); +void CG_G2AnimEntModelLoad(centity_t *cent) { + const char *cModelName = CG_ConfigString(CS_MODELS + cent->currentState.modelindex); - if (!cent->npcClient) - { //have not init'd client yet + if (!cent->npcClient) { // have not init'd client yet return; } - if (cModelName && cModelName[0]) - { + if (cModelName && cModelName[0]) { char modelName[MAX_QPATH]; int skinID; char *slash; strcpy(modelName, cModelName); - if (cent->currentState.NPC_class == CLASS_VEHICLE && modelName[0] == '$') - { //vehicles pass their veh names over as model names, then we get the model name from the veh type - //create a vehicle object clientside for this type + if (cent->currentState.NPC_class == CLASS_VEHICLE && + modelName[0] == '$') { // vehicles pass their veh names over as model names, then we get the model name from the veh type + // create a vehicle object clientside for this type char *vehType = &modelName[1]; - int iVehIndex = BG_VehicleGetIndex( vehType ); + int iVehIndex = BG_VehicleGetIndex(vehType); - switch( g_vehicleInfo[iVehIndex].type ) - { - case VH_ANIMAL: - // Create the animal (making sure all it's data is initialized). - G_CreateAnimalNPC( ¢->m_pVehicle, vehType ); - break; - case VH_SPEEDER: - // Create the speeder (making sure all it's data is initialized). - G_CreateSpeederNPC( ¢->m_pVehicle, vehType ); - break; - case VH_FIGHTER: - // Create the fighter (making sure all it's data is initialized). - G_CreateFighterNPC( ¢->m_pVehicle, vehType ); - break; - case VH_WALKER: - // Create the walker (making sure all it's data is initialized). - G_CreateWalkerNPC( ¢->m_pVehicle, vehType ); - break; + switch (g_vehicleInfo[iVehIndex].type) { + case VH_ANIMAL: + // Create the animal (making sure all it's data is initialized). + G_CreateAnimalNPC(¢->m_pVehicle, vehType); + break; + case VH_SPEEDER: + // Create the speeder (making sure all it's data is initialized). + G_CreateSpeederNPC(¢->m_pVehicle, vehType); + break; + case VH_FIGHTER: + // Create the fighter (making sure all it's data is initialized). + G_CreateFighterNPC(¢->m_pVehicle, vehType); + break; + case VH_WALKER: + // Create the walker (making sure all it's data is initialized). + G_CreateWalkerNPC(¢->m_pVehicle, vehType); + break; - default: - assert(!"vehicle with an unknown type - couldn't create vehicle_t"); - break; + default: + assert(!"vehicle with an unknown type - couldn't create vehicle_t"); + break; } - //set up my happy prediction hack + // set up my happy prediction hack cent->m_pVehicle->m_vOrientation = &cgSendPS[cent->currentState.number]->vehOrientation[0]; cent->m_pVehicle->m_pParentEntity = (bgEntity_t *)cent; - //attach the handles for fx cgame-side + // attach the handles for fx cgame-side CG_RegisterVehicleAssets(cent->m_pVehicle); - BG_GetVehicleModelName(modelName, modelName, sizeof( modelName ) ); - if (cent->m_pVehicle->m_pVehicleInfo->skin && - cent->m_pVehicle->m_pVehicleInfo->skin[0]) - { //use a custom skin + BG_GetVehicleModelName(modelName, modelName, sizeof(modelName)); + if (cent->m_pVehicle->m_pVehicleInfo->skin && cent->m_pVehicle->m_pVehicleInfo->skin[0]) { // use a custom skin skinID = trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", modelName, cent->m_pVehicle->m_pVehicleInfo->skin)); - } - else - { + } else { skinID = trap->R_RegisterSkin(va("models/players/%s/model_default.skin", modelName)); } strcpy(modelName, va("models/players/%s/model.glm", modelName)); - //this sound is *only* used for vehicles now - cgs.media.noAmmoSound = trap->S_RegisterSound( "sound/weapons/noammo.wav" ); - } - else - { - skinID = CG_HandleAppendedSkin(modelName); //get the skin if there is one. + // this sound is *only* used for vehicles now + cgs.media.noAmmoSound = trap->S_RegisterSound("sound/weapons/noammo.wav"); + } else { + skinID = CG_HandleAppendedSkin(modelName); // get the skin if there is one. } - if (cent->ghoul2) - { //clean it first! - trap->G2API_CleanGhoul2Models(¢->ghoul2); + if (cent->ghoul2) { // clean it first! + trap->G2API_CleanGhoul2Models(¢->ghoul2); } trap->G2API_InitGhoul2Model(¢->ghoul2, modelName, 0, skinID, 0, 0, 0); - if (cent->ghoul2) - { + if (cent->ghoul2) { char GLAName[MAX_QPATH]; char originalModelName[MAX_QPATH]; char *saber; int j = 0; - if (cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle) - { //do special vehicle stuff + if (cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle) { // do special vehicle stuff char strTemp[128]; int i; // Setup the default first bolt - i = trap->G2API_AddBolt( cent->ghoul2, 0, "model_root" ); + i = trap->G2API_AddBolt(cent->ghoul2, 0, "model_root"); // Setup the droid unit. - cent->m_pVehicle->m_iDroidUnitTag = trap->G2API_AddBolt( cent->ghoul2, 0, "*droidunit" ); + cent->m_pVehicle->m_iDroidUnitTag = trap->G2API_AddBolt(cent->ghoul2, 0, "*droidunit"); // Setup the Exhausts. - for ( i = 0; i < MAX_VEHICLE_EXHAUSTS; i++ ) - { - Com_sprintf( strTemp, 128, "*exhaust%i", i + 1 ); - cent->m_pVehicle->m_iExhaustTag[i] = trap->G2API_AddBolt( cent->ghoul2, 0, strTemp ); + for (i = 0; i < MAX_VEHICLE_EXHAUSTS; i++) { + Com_sprintf(strTemp, 128, "*exhaust%i", i + 1); + cent->m_pVehicle->m_iExhaustTag[i] = trap->G2API_AddBolt(cent->ghoul2, 0, strTemp); } // Setup the Muzzles. - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - Com_sprintf( strTemp, 128, "*muzzle%i", i + 1 ); - cent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt( cent->ghoul2, 0, strTemp ); - if ( cent->m_pVehicle->m_iMuzzleTag[i] == -1 ) - {//ergh, try *flash? - Com_sprintf( strTemp, 128, "*flash%i", i + 1 ); - cent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt( cent->ghoul2, 0, strTemp ); + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + Com_sprintf(strTemp, 128, "*muzzle%i", i + 1); + cent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt(cent->ghoul2, 0, strTemp); + if (cent->m_pVehicle->m_iMuzzleTag[i] == -1) { // ergh, try *flash? + Com_sprintf(strTemp, 128, "*flash%i", i + 1); + cent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt(cent->ghoul2, 0, strTemp); } } // Setup the Turrets. - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - if ( cent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag ) - { - cent->m_pVehicle->m_iGunnerViewTag[i] = trap->G2API_AddBolt( cent->ghoul2, 0, cent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag ); - } - else - { + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + if (cent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag) { + cent->m_pVehicle->m_iGunnerViewTag[i] = trap->G2API_AddBolt(cent->ghoul2, 0, cent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag); + } else { cent->m_pVehicle->m_iGunnerViewTag[i] = -1; } } } - if (cent->currentState.npcSaber1) - { - saber = (char *)CG_ConfigString(CS_MODELS+cent->currentState.npcSaber1); + if (cent->currentState.npcSaber1) { + saber = (char *)CG_ConfigString(CS_MODELS + cent->currentState.npcSaber1); assert(!saber || !saber[0] || saber[0] == '@'); - //valid saber names should always start with '@' for NPCs + // valid saber names should always start with '@' for NPCs - if (saber && saber[0]) - { - saber++; //skip over the @ + if (saber && saber[0]) { + saber++; // skip over the @ WP_SetSaber(cent->currentState.number, cent->npcClient->saber, 0, saber); } } - if (cent->currentState.npcSaber2) - { - saber = (char *)CG_ConfigString(CS_MODELS+cent->currentState.npcSaber2); + if (cent->currentState.npcSaber2) { + saber = (char *)CG_ConfigString(CS_MODELS + cent->currentState.npcSaber2); assert(!saber || !saber[0] || saber[0] == '@'); - //valid saber names should always start with '@' for NPCs + // valid saber names should always start with '@' for NPCs - if (saber && saber[0]) - { - saber++; //skip over the @ + if (saber && saber[0]) { + saber++; // skip over the @ WP_SetSaber(cent->currentState.number, cent->npcClient->saber, 1, saber); } } // If this is a not vehicle, give it saber stuff... - if ( cent->currentState.NPC_class != CLASS_VEHICLE ) - { - while (j < MAX_SABERS) - { - if (cent->npcClient->saber[j].model[0]) - { - if (cent->npcClient->ghoul2Weapons[j]) - { //free the old instance(s) + if (cent->currentState.NPC_class != CLASS_VEHICLE) { + while (j < MAX_SABERS) { + if (cent->npcClient->saber[j].model[0]) { + if (cent->npcClient->ghoul2Weapons[j]) { // free the old instance(s) trap->G2API_CleanGhoul2Models(¢->npcClient->ghoul2Weapons[j]); cent->npcClient->ghoul2Weapons[j] = 0; } @@ -7236,67 +6158,53 @@ void CG_G2AnimEntModelLoad(centity_t *cent) !strstr(GLAName, "players/_humanoid/") /*&& !strstr(GLAName, "players/rockettrooper/")*/) { //it doesn't use humanoid anims. - slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { + slash = Q_strrchr(GLAName, '/'); + if (slash) { strcpy(slash, "/animation.cfg"); cent->localAnimIndex = BG_ParseAnimationFile(GLAName, NULL, qfalse); } - } - else - { //humanoid index. + } else { // humanoid index. trap->G2API_AddBolt(cent->ghoul2, 0, "*r_hand"); trap->G2API_AddBolt(cent->ghoul2, 0, "*l_hand"); - //rhand must always be first bolt. lhand always second. Whichever you want the - //jetpack bolted to must always be third. + // rhand must always be first bolt. lhand always second. Whichever you want the + // jetpack bolted to must always be third. trap->G2API_AddBolt(cent->ghoul2, 0, "*chestg"); - //claw bolts + // claw bolts trap->G2API_AddBolt(cent->ghoul2, 0, "*r_hand_cap_r_arm"); trap->G2API_AddBolt(cent->ghoul2, 0, "*l_hand_cap_l_arm"); - if (strstr(GLAName, "players/rockettrooper/")) - { + if (strstr(GLAName, "players/rockettrooper/")) { cent->localAnimIndex = 1; - } - else - { + } else { cent->localAnimIndex = 0; } - if (trap->G2API_AddBolt(cent->ghoul2, 0, "*head_top") == -1) - { + if (trap->G2API_AddBolt(cent->ghoul2, 0, "*head_top") == -1) { trap->G2API_AddBolt(cent->ghoul2, 0, "ceyebrow"); } trap->G2API_AddBolt(cent->ghoul2, 0, "Motion"); } // If this is a not vehicle... - if ( cent->currentState.NPC_class != CLASS_VEHICLE ) - { - if (trap->G2API_AddBolt(cent->ghoul2, 0, "lower_lumbar") == -1) - { //check now to see if we have this bone for setting anims and such + if (cent->currentState.NPC_class != CLASS_VEHICLE) { + if (trap->G2API_AddBolt(cent->ghoul2, 0, "lower_lumbar") == -1) { // check now to see if we have this bone for setting anims and such cent->noLumbar = qtrue; } - if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cent->noFace = qtrue; } - } - else - { + } else { cent->noLumbar = qtrue; cent->noFace = qtrue; } - if (cent->localAnimIndex != -1) - { - slash = Q_strrchr( originalModelName, '/' ); - if ( slash ) - { + if (cent->localAnimIndex != -1) { + slash = Q_strrchr(originalModelName, '/'); + if (slash) { slash++; *slash = 0; } @@ -7307,144 +6215,101 @@ void CG_G2AnimEntModelLoad(centity_t *cent) } trap->S_Shutup(qtrue); - CG_HandleNPCSounds(cent); //handle sound loading here as well. + CG_HandleNPCSounds(cent); // handle sound loading here as well. trap->S_Shutup(qfalse); } -//for now this is just gonna create a big explosion on the area of the surface, -//because I am lazy. -static void CG_CreateSurfaceDebris(centity_t *cent, int surfNum, int fxID, qboolean throwPart) -{ +// for now this is just gonna create a big explosion on the area of the surface, +// because I am lazy. +static void CG_CreateSurfaceDebris(centity_t *cent, int surfNum, int fxID, qboolean throwPart) { int lostPartFX = 0; int b; vec3_t v, d; mdxaBone_t boltMatrix; const char *surfName = bgToggleableSurfaces[surfNum]; - if (!cent->ghoul2) - { //oh no + if (!cent->ghoul2) { // oh no return; } - //let's add the surface as a bolt so we can get the base point of it - if (bgToggleableSurfaceDebris[surfNum] == 3) - { //right wing flame + // let's add the surface as a bolt so we can get the base point of it + if (bgToggleableSurfaceDebris[surfNum] == 3) { // right wing flame b = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_wingdamage"); - if ( throwPart - && cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo ) - { + if (throwPart && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo) { lostPartFX = cent->m_pVehicle->m_pVehicleInfo->iRWingFX; } - } - else if (bgToggleableSurfaceDebris[surfNum] == 4) - { //left wing flame + } else if (bgToggleableSurfaceDebris[surfNum] == 4) { // left wing flame b = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_wingdamage"); - if ( throwPart - && cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo ) - { + if (throwPart && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo) { lostPartFX = cent->m_pVehicle->m_pVehicleInfo->iLWingFX; } - } - else if (bgToggleableSurfaceDebris[surfNum] == 5) - { //right wing flame 2 + } else if (bgToggleableSurfaceDebris[surfNum] == 5) { // right wing flame 2 b = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_wingdamage"); - if ( throwPart - && cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo ) - { + if (throwPart && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo) { lostPartFX = cent->m_pVehicle->m_pVehicleInfo->iRWingFX; } - } - else if (bgToggleableSurfaceDebris[surfNum] == 6) - { //left wing flame 2 + } else if (bgToggleableSurfaceDebris[surfNum] == 6) { // left wing flame 2 b = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_wingdamage"); - if ( throwPart - && cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo ) - { + if (throwPart && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo) { lostPartFX = cent->m_pVehicle->m_pVehicleInfo->iLWingFX; } - } - else if (bgToggleableSurfaceDebris[surfNum] == 7) - { //nose flame + } else if (bgToggleableSurfaceDebris[surfNum] == 7) { // nose flame b = trap->G2API_AddBolt(cent->ghoul2, 0, "*nosedamage"); - if ( cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo ) - { + if (cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo) { lostPartFX = cent->m_pVehicle->m_pVehicleInfo->iNoseFX; } - } - else - { + } else { b = trap->G2API_AddBolt(cent->ghoul2, 0, surfName); } - if (b == -1) - { //couldn't find this surface apparently + if (b == -1) { // couldn't find this surface apparently return; } - //now let's get the position and direction of this surface and make a big explosion - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, b, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, - cgs.gameModels, cent->modelScale); + // now let's get the position and direction of this surface and make a big explosion + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, b, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, v); BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, d); trap->FX_PlayEffectID(fxID, v, d, -1, -1, qfalse); - if ( throwPart && lostPartFX ) - {//throw off a ship part, too - vec3_t fxFwd; - AngleVectors( cent->lerpAngles, fxFwd, NULL, NULL ); + if (throwPart && lostPartFX) { // throw off a ship part, too + vec3_t fxFwd; + AngleVectors(cent->lerpAngles, fxFwd, NULL, NULL); trap->FX_PlayEffectID(lostPartFX, v, fxFwd, -1, -1, qfalse); } } -//for now this is just gonna create a big explosion on the area of the surface, -//because I am lazy. -static void CG_CreateSurfaceSmoke(centity_t *cent, int shipSurf, int fxID) -{ +// for now this is just gonna create a big explosion on the area of the surface, +// because I am lazy. +static void CG_CreateSurfaceSmoke(centity_t *cent, int shipSurf, int fxID) { int b = -1; vec3_t v, d; mdxaBone_t boltMatrix; const char *surfName = NULL; - if (!cent->ghoul2) - { //oh no + if (!cent->ghoul2) { // oh no return; } - //let's add the surface as a bolt so we can get the base point of it - if ( shipSurf == SHIPSURF_FRONT ) - { //front flame/smoke + // let's add the surface as a bolt so we can get the base point of it + if (shipSurf == SHIPSURF_FRONT) { // front flame/smoke surfName = "*nosedamage"; - } - else if (shipSurf == SHIPSURF_BACK ) - { //back flame/smoke - surfName = "*exhaust1";//FIXME: random? Some point in-between? - } - else if (shipSurf == SHIPSURF_RIGHT ) - { //right wing flame/smoke + } else if (shipSurf == SHIPSURF_BACK) { // back flame/smoke + surfName = "*exhaust1"; // FIXME: random? Some point in-between? + } else if (shipSurf == SHIPSURF_RIGHT) { // right wing flame/smoke surfName = "*r_wingdamage"; - } - else if (shipSurf == SHIPSURF_LEFT ) - { //left wing flame/smoke + } else if (shipSurf == SHIPSURF_LEFT) { // left wing flame/smoke surfName = "*l_wingdamage"; - } - else - {//unknown surf! + } else { // unknown surf! return; } b = trap->G2API_AddBolt(cent->ghoul2, 0, surfName); - if (b == -1) - { //couldn't find this surface apparently + if (b == -1) { // couldn't find this surface apparently return; } - //now let's get the position and direction of this surface and make a big explosion - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, b, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, - cgs.gameModels, cent->modelScale); + // now let's get the position and direction of this surface and make a big explosion + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, b, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, v); BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, d); @@ -7453,13 +6318,9 @@ static void CG_CreateSurfaceSmoke(centity_t *cent, int shipSurf, int fxID) #define SMOOTH_G2ANIM_LERPANGLES -qboolean CG_VehicleShouldDrawShields( centity_t *vehCent ) -{ - if ( vehCent->damageTime > cg.time //ship shields currently taking damage - && vehCent->currentState.NPC_class == CLASS_VEHICLE - && vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo ) - { +qboolean CG_VehicleShouldDrawShields(centity_t *vehCent) { + if (vehCent->damageTime > cg.time // ship shields currently taking damage + && vehCent->currentState.NPC_class == CLASS_VEHICLE && vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo) { return qtrue; } return qfalse; @@ -7469,30 +6330,24 @@ qboolean CG_VehicleShouldDrawShields( centity_t *vehCent ) extern vmCvar_t cg_showVehBounds; extern void BG_VehicleAdjustBBoxForOrientation( Vehicle_t *veh, vec3_t origin, vec3_t mins, vec3_t maxs, int clientNum, int tracemask, - void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask)); // bg_pmove.c + void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int +passEntityNum, int contentMask)); // bg_pmove.c */ -qboolean CG_VehicleAttachDroidUnit( centity_t *droidCent, refEntity_t *legs ) -{ - if ( droidCent - && droidCent->currentState.owner - && droidCent->currentState.clientNum >= MAX_CLIENTS ) - {//the only NPCs that can ride a vehicle are droids...??? +qboolean CG_VehicleAttachDroidUnit(centity_t *droidCent, refEntity_t *legs) { + if (droidCent && droidCent->currentState.owner && + droidCent->currentState.clientNum >= MAX_CLIENTS) { // the only NPCs that can ride a vehicle are droids...??? centity_t *vehCent = &cg_entities[droidCent->currentState.owner]; - if ( vehCent - && vehCent->m_pVehicle - && vehCent->ghoul2 - && vehCent->m_pVehicle->m_iDroidUnitTag != -1 ) - { + if (vehCent && vehCent->m_pVehicle && vehCent->ghoul2 && vehCent->m_pVehicle->m_iDroidUnitTag != -1) { mdxaBone_t boltMatrix; - vec3_t fwd, rt, tempAng; + vec3_t fwd, rt, tempAng; trap->G2API_GetBoltMatrix(vehCent->ghoul2, 0, vehCent->m_pVehicle->m_iDroidUnitTag, &boltMatrix, vehCent->lerpAngles, vehCent->lerpOrigin, cg.time, - cgs.gameModels, vehCent->modelScale); + cgs.gameModels, vehCent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droidCent->lerpOrigin); - BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, fwd);//WTF??? - BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, rt);//WTF??? - vectoangles( fwd, droidCent->lerpAngles ); - vectoangles( rt, tempAng ); + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, fwd); // WTF??? + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, rt); // WTF??? + vectoangles(fwd, droidCent->lerpAngles); + vectoangles(rt, tempAng); droidCent->lerpAngles[ROLL] = tempAng[PITCH]; return qtrue; @@ -7501,15 +6356,12 @@ qboolean CG_VehicleAttachDroidUnit( centity_t *droidCent, refEntity_t *legs ) return qfalse; } -void CG_G2Animated( centity_t *cent ) -{ +void CG_G2Animated(centity_t *cent) { #ifdef SMOOTH_G2ANIM_LERPANGLES float angSmoothFactor = 0.7f; #endif - - if (!cent->ghoul2) - { //Initialize this g2 anim ent, then return (will start rendering next frame) + if (!cent->ghoul2) { // Initialize this g2 anim ent, then return (will start rendering next frame) CG_G2AnimEntModelLoad(cent); cent->npcLocalSurfOff = 0; cent->npcLocalSurfOn = 0; @@ -7517,27 +6369,21 @@ void CG_G2Animated( centity_t *cent ) } if (cent->npcLocalSurfOff != cent->currentState.surfacesOff || - cent->npcLocalSurfOn != cent->currentState.surfacesOn) - { //looks like it's time for an update. + cent->npcLocalSurfOn != cent->currentState.surfacesOn) { // looks like it's time for an update. int i = 0; - while (i < BG_NUM_TOGGLEABLE_SURFACES && bgToggleableSurfaces[i]) - { + while (i < BG_NUM_TOGGLEABLE_SURFACES && bgToggleableSurfaces[i]) { if (!(cent->npcLocalSurfOff & (1 << i)) && - (cent->currentState.surfacesOff & (1 << i))) - { //it wasn't off before but it's off now, so reflect this change in the g2 instance. - if (bgToggleableSurfaceDebris[i] > 0) - { //make some local debris of this thing? - //FIXME: throw off the proper model effect, too + (cent->currentState.surfacesOff & (1 << i))) { // it wasn't off before but it's off now, so reflect this change in the g2 instance. + if (bgToggleableSurfaceDebris[i] > 0) { // make some local debris of this thing? + // FIXME: throw off the proper model effect, too CG_CreateSurfaceDebris(cent, i, cgs.effects.mShipDestDestroyed, qtrue); } trap->G2API_SetSurfaceOnOff(cent->ghoul2, bgToggleableSurfaces[i], TURN_OFF); } - if (!(cent->npcLocalSurfOn & (1 << i)) && - (cent->currentState.surfacesOn & (1 << i))) - { //same as above, but on instead of off. + if (!(cent->npcLocalSurfOn & (1 << i)) && (cent->currentState.surfacesOn & (1 << i))) { // same as above, but on instead of off. trap->G2API_SetSurfaceOnOff(cent->ghoul2, bgToggleableSurfaces[i], TURN_ON); } @@ -7548,7 +6394,6 @@ void CG_G2Animated( centity_t *cent ) cent->npcLocalSurfOn = cent->currentState.surfacesOn; } - /* if (cent->currentState.weapon && !trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1) && @@ -7563,13 +6408,11 @@ void CG_G2Animated( centity_t *cent ) } */ - if (cent->torsoBolt && !(cent->currentState.eFlags & EF_DEAD)) - { //he's alive and has a limb missing still, reattach it and reset the weapon + if (cent->torsoBolt && !(cent->currentState.eFlags & EF_DEAD)) { // he's alive and has a limb missing still, reattach it and reset the weapon CG_ReattachLimb(cent); } - if (((cent->currentState.eFlags & EF_DEAD) || (cent->currentState.eFlags & EF_RAG)) && !cent->localAnimIndex) - { + if (((cent->currentState.eFlags & EF_DEAD) || (cent->currentState.eFlags & EF_RAG)) && !cent->localAnimIndex) { vec3_t forcedAngles; VectorClear(forcedAngles); @@ -7580,15 +6423,14 @@ void CG_G2Animated( centity_t *cent ) #ifdef SMOOTH_G2ANIM_LERPANGLES if ((cent->lerpAngles[YAW] > 0 && cent->smoothYaw < 0) || - (cent->lerpAngles[YAW] < 0 && cent->smoothYaw > 0)) - { //keep it from snapping around on the threshold + (cent->lerpAngles[YAW] < 0 && cent->smoothYaw > 0)) { // keep it from snapping around on the threshold cent->smoothYaw = -cent->smoothYaw; } - cent->lerpAngles[YAW] = cent->smoothYaw+(cent->lerpAngles[YAW]-cent->smoothYaw)*angSmoothFactor; + cent->lerpAngles[YAW] = cent->smoothYaw + (cent->lerpAngles[YAW] - cent->smoothYaw) * angSmoothFactor; cent->smoothYaw = cent->lerpAngles[YAW]; #endif - //now just render as a player + // now just render as a player CG_Player(cent); /* @@ -7617,9 +6459,9 @@ void CG_G2Animated( centity_t *cent ) } */ } -//rww - here ends the majority of my g2animent stuff. +// rww - here ends the majority of my g2animent stuff. -//Disabled for now, I'm too lazy to keep it working with all the stuff changing around. +// Disabled for now, I'm too lazy to keep it working with all the stuff changing around. #if 0 int cgFPLSState = 0; @@ -7729,32 +6571,29 @@ void CG_ForceFPLSPlayerModel(centity_t *cent, clientInfo_t *ci) } #endif -//for allocating and freeing npc clientinfo structures. -//Remember to free this before game shutdown no matter what -//and don't stomp over it, as it is dynamic memory from the -//exe. -void CG_CreateNPCClient(clientInfo_t **ci) -{ - //trap->TrueMalloc((void **)ci, sizeof(clientInfo_t)); - *ci = (clientInfo_t *) BG_Alloc(sizeof(clientInfo_t)); +// for allocating and freeing npc clientinfo structures. +// Remember to free this before game shutdown no matter what +// and don't stomp over it, as it is dynamic memory from the +// exe. +void CG_CreateNPCClient(clientInfo_t **ci) { + // trap->TrueMalloc((void **)ci, sizeof(clientInfo_t)); + *ci = (clientInfo_t *)BG_Alloc(sizeof(clientInfo_t)); } -void CG_DestroyNPCClient(clientInfo_t **ci) -{ +void CG_DestroyNPCClient(clientInfo_t **ci) { memset(*ci, 0, sizeof(clientInfo_t)); - //trap->TrueFree((void **)ci); + // trap->TrueFree((void **)ci); } -static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t tempAngles, qhandle_t shader, qboolean alwaysDo ) -{ +static void CG_ForceElectrocution(centity_t *cent, const vec3_t origin, vec3_t tempAngles, qhandle_t shader, qboolean alwaysDo) { // Undoing for now, at least this code should compile if I ( or anyone else ) decides to work on this effect - qboolean found = qfalse; - vec3_t fxOrg, fxOrg2, dir; - vec3_t rgb; - mdxaBone_t boltMatrix; - trace_t tr; - int bolt=-1; - int iter=0; + qboolean found = qfalse; + vec3_t fxOrg, fxOrg2, dir; + vec3_t rgb; + mdxaBone_t boltMatrix; + trace_t tr; + int bolt = -1; + int iter = 0; int torsoBolt = -1; int elbowLBolt = -1; int elbowRBolt = -1; @@ -7765,8 +6604,7 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t VectorSet(rgb, 1, 1, 1); - if (cent->localAnimIndex <= 1) - { //humanoid + if (cent->localAnimIndex <= 1) { // humanoid torsoBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "lower_lumbar"); elbowLBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_arm_elbow"); elbowRBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_arm_elbow"); @@ -7774,9 +6612,7 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t handRBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_hand"); footLBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*l_leg_foot"); footRBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*r_leg_foot"); - } - else if (cent->currentState.NPC_class == CLASS_PROTOCOL) - { //any others that can use these bolts too? + } else if (cent->currentState.NPC_class == CLASS_PROTOCOL) { // any others that can use these bolts too? torsoBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "lower_lumbar"); elbowLBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*bicep_lg"); elbowRBolt = trap->G2API_AddBolt(cent->ghoul2, 0, "*bicep_rg"); @@ -7787,84 +6623,69 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t } // Pick a random start point - while (bolt<0) - { + while (bolt < 0) { int test; - if (iter>5) - { - test=iter-5; - } - else - { - test=Q_irand(0,6); + if (iter > 5) { + test = iter - 5; + } else { + test = Q_irand(0, 6); } - switch(test) - { + switch (test) { case 0: // Right Elbow - bolt=elbowRBolt; + bolt = elbowRBolt; break; case 1: // Left Hand - bolt=handLBolt; + bolt = handLBolt; break; case 2: // Right hand - bolt=handRBolt; + bolt = handRBolt; break; case 3: // Left Foot - bolt=footLBolt; + bolt = footLBolt; break; case 4: // Right foot - bolt=footRBolt; + bolt = footRBolt; break; case 5: // Torso - bolt=torsoBolt; + bolt = torsoBolt; break; case 6: default: // Left Elbow - bolt=elbowLBolt; + bolt = elbowLBolt; break; } - if (++iter==20) + if (++iter == 20) break; } - if (bolt>=0) - { - found = trap->G2API_GetBoltMatrix( cent->ghoul2, 0, bolt, - &boltMatrix, tempAngles, origin, cg.time, - cgs.gameModels, cent->modelScale); + if (bolt >= 0) { + found = trap->G2API_GetBoltMatrix(cent->ghoul2, 0, bolt, &boltMatrix, tempAngles, origin, cg.time, cgs.gameModels, cent->modelScale); } // Make sure that it's safe to even try and get these values out of the Matrix, otherwise the values could be garbage - if ( found ) - { - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, fxOrg ); - if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, dir ); - } - else - { - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); + if (found) { + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, fxOrg); + if (Q_flrand(0.0f, 1.0f) > 0.5f) { + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, dir); + } else { + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); } // Add some fudge, makes us not normalized, but that isn't really important dir[0] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[1] += Q_flrand(-1.0f, 1.0f) * 0.4f; dir[2] += Q_flrand(-1.0f, 1.0f) * 0.4f; - } - else - { + } else { // Just use the lerp Origin and a random direction - VectorCopy( cent->lerpOrigin, fxOrg ); - VectorSet( dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f) ); // Not normalized, but who cares. - switch ( cent->currentState.NPC_class ) - { + VectorCopy(cent->lerpOrigin, fxOrg); + VectorSet(dir, Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f), Q_flrand(-1.0f, 1.0f)); // Not normalized, but who cares. + switch (cent->currentState.NPC_class) { case CLASS_PROBE: fxOrg[2] += 50; break; @@ -7879,12 +6700,11 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t } } - VectorMA( fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2 ); + VectorMA(fxOrg, Q_flrand(0.0f, 1.0f) * 40 + 40, dir, fxOrg2); - CG_Trace( &tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID ); + CG_Trace(&tr, fxOrg, NULL, NULL, fxOrg2, -1, CONTENTS_SOLID); - if ( tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f || alwaysDo ) - { + if (tr.fraction < 1.0f || Q_flrand(0.0f, 1.0f) > 0.94f || alwaysDo) { addElectricityArgStruct_t p; VectorCopy(fxOrg, p.start); @@ -7905,7 +6725,7 @@ static void CG_ForceElectrocution( centity_t *cent, const vec3_t origin, vec3_t trap->FX_AddElectricity(&p); - //In other words: + // In other words: /* FX_AddElectricity( fxOrg, tr.endpos, 1.5f, 4.0f, 0.0f, @@ -7920,10 +6740,8 @@ void *cg_g2JetpackInstance = NULL; #define JETPACK_MODEL "models/weapons2/jetpack/model.glm" -void CG_InitJetpackGhoul2(void) -{ - if (cg_g2JetpackInstance) - { +void CG_InitJetpackGhoul2(void) { + if (cg_g2JetpackInstance) { assert(!"Tried to init jetpack inst, already init'd"); return; } @@ -7932,28 +6750,26 @@ void CG_InitJetpackGhoul2(void) assert(cg_g2JetpackInstance); - //Indicate which bolt on the player we will be attached to - //In this case bolt 0 is rhand, 1 is lhand, and 2 is the bolt - //for the jetpack (*chestg) + // Indicate which bolt on the player we will be attached to + // In this case bolt 0 is rhand, 1 is lhand, and 2 is the bolt + // for the jetpack (*chestg) trap->G2API_SetBoltInfo(cg_g2JetpackInstance, 0, 2); - //Add the bolts jet effects will be played from + // Add the bolts jet effects will be played from trap->G2API_AddBolt(cg_g2JetpackInstance, 0, "torso_ljet"); trap->G2API_AddBolt(cg_g2JetpackInstance, 0, "torso_rjet"); } -void CG_CleanJetpackGhoul2(void) -{ - if (cg_g2JetpackInstance) - { +void CG_CleanJetpackGhoul2(void) { + if (cg_g2JetpackInstance) { trap->G2API_CleanGhoul2Models(&cg_g2JetpackInstance); cg_g2JetpackInstance = NULL; } } -#define RARMBIT (1 << (G2_MODELPART_RARM-10)) -#define RHANDBIT (1 << (G2_MODELPART_RHAND-10)) -#define WAISTBIT (1 << (G2_MODELPART_WAIST-10)) +#define RARMBIT (1 << (G2_MODELPART_RARM - 10)) +#define RHANDBIT (1 << (G2_MODELPART_RHAND - 10)) +#define WAISTBIT (1 << (G2_MODELPART_WAIST - 10)) #if 0 static void CG_VehicleHeatEffect( vec3_t org, centity_t *cent ) @@ -8008,70 +6824,54 @@ static void CG_VehicleHeatEffect( vec3_t org, centity_t *cent ) #endif static int lastFlyBySound[MAX_GENTITIES] = {0}; -#define FLYBYSOUNDTIME 2000 -int cg_lastHyperSpaceEffectTime = 0; -static QINLINE void CG_VehicleEffects(centity_t *cent) -{ +#define FLYBYSOUNDTIME 2000 +int cg_lastHyperSpaceEffectTime = 0; +static QINLINE void CG_VehicleEffects(centity_t *cent) { Vehicle_t *pVehNPC; - if (cent->currentState.eType != ET_NPC || - cent->currentState.NPC_class != CLASS_VEHICLE || - !cent->m_pVehicle) - { + if (cent->currentState.eType != ET_NPC || cent->currentState.NPC_class != CLASS_VEHICLE || !cent->m_pVehicle) { return; } pVehNPC = cent->m_pVehicle; - if ( cent->currentState.clientNum == cg.predictedPlayerState.m_iVehicleNum//my vehicle - && (cent->currentState.eFlags2&EF2_HYPERSPACE) )//hyperspacing - {//in hyperspace! - if ( cg.predictedVehicleState.hyperSpaceTime - && (cg.time-cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME ) - { - if ( !cg_lastHyperSpaceEffectTime - || (cg.time - cg_lastHyperSpaceEffectTime) > HYPERSPACE_TIME+500 ) - {//can't be from the last time we were in hyperspace, so play the effect! - trap->FX_PlayBoltedEffectID( cgs.effects.mHyperspaceStars, cent->lerpOrigin, cent->ghoul2, 0, - cent->currentState.number, 0, 0, qtrue ); + if (cent->currentState.clientNum == cg.predictedPlayerState.m_iVehicleNum // my vehicle + && (cent->currentState.eFlags2 & EF2_HYPERSPACE)) // hyperspacing + { // in hyperspace! + if (cg.predictedVehicleState.hyperSpaceTime && (cg.time - cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME) { + if (!cg_lastHyperSpaceEffectTime || + (cg.time - cg_lastHyperSpaceEffectTime) > HYPERSPACE_TIME + 500) { // can't be from the last time we were in hyperspace, so play the effect! + trap->FX_PlayBoltedEffectID(cgs.effects.mHyperspaceStars, cent->lerpOrigin, cent->ghoul2, 0, cent->currentState.number, 0, 0, qtrue); cg_lastHyperSpaceEffectTime = cg.time; } } } - //FLYBY sound - if ( cent->currentState.clientNum != cg.predictedPlayerState.m_iVehicleNum - && (pVehNPC->m_pVehicleInfo->soundFlyBy||pVehNPC->m_pVehicleInfo->soundFlyBy2) ) - {//not my vehicle - if ( cent->currentState.speed && cg.predictedPlayerState.speed+cent->currentState.speed > 500 ) - {//he's moving and between the two of us, we're moving fast + // FLYBY sound + if (cent->currentState.clientNum != cg.predictedPlayerState.m_iVehicleNum && + (pVehNPC->m_pVehicleInfo->soundFlyBy || pVehNPC->m_pVehicleInfo->soundFlyBy2)) { // not my vehicle + if (cent->currentState.speed && + cg.predictedPlayerState.speed + cent->currentState.speed > 500) { // he's moving and between the two of us, we're moving fast vec3_t diff; - VectorSubtract( cent->lerpOrigin, cg.predictedPlayerState.origin, diff ); - if ( VectorLength( diff ) < 2048 ) - {//close - vec3_t myFwd, theirFwd; - AngleVectors( cg.predictedPlayerState.viewangles, myFwd, NULL, NULL ); - VectorScale( myFwd, cg.predictedPlayerState.speed, myFwd ); - AngleVectors( cent->lerpAngles, theirFwd, NULL, NULL ); - VectorScale( theirFwd, cent->currentState.speed, theirFwd ); - if ( lastFlyBySound[cent->currentState.clientNum]+FLYBYSOUNDTIME < cg.time ) - {//okay to do a flyby sound on this vehicle - if ( DotProduct( myFwd, theirFwd ) < 500 ) - { + VectorSubtract(cent->lerpOrigin, cg.predictedPlayerState.origin, diff); + if (VectorLength(diff) < 2048) { // close + vec3_t myFwd, theirFwd; + AngleVectors(cg.predictedPlayerState.viewangles, myFwd, NULL, NULL); + VectorScale(myFwd, cg.predictedPlayerState.speed, myFwd); + AngleVectors(cent->lerpAngles, theirFwd, NULL, NULL); + VectorScale(theirFwd, cent->currentState.speed, theirFwd); + if (lastFlyBySound[cent->currentState.clientNum] + FLYBYSOUNDTIME < cg.time) { // okay to do a flyby sound on this vehicle + if (DotProduct(myFwd, theirFwd) < 500) { int flyBySound = 0; - if ( pVehNPC->m_pVehicleInfo->soundFlyBy && pVehNPC->m_pVehicleInfo->soundFlyBy2 ) - { - flyBySound = Q_irand(0,1)?pVehNPC->m_pVehicleInfo->soundFlyBy:pVehNPC->m_pVehicleInfo->soundFlyBy2; - } - else if ( pVehNPC->m_pVehicleInfo->soundFlyBy ) - { + if (pVehNPC->m_pVehicleInfo->soundFlyBy && pVehNPC->m_pVehicleInfo->soundFlyBy2) { + flyBySound = Q_irand(0, 1) ? pVehNPC->m_pVehicleInfo->soundFlyBy : pVehNPC->m_pVehicleInfo->soundFlyBy2; + } else if (pVehNPC->m_pVehicleInfo->soundFlyBy) { flyBySound = pVehNPC->m_pVehicleInfo->soundFlyBy; - } - else //if ( pVehNPC->m_pVehicleInfo->soundFlyBy2 ) + } else // if ( pVehNPC->m_pVehicleInfo->soundFlyBy2 ) { flyBySound = pVehNPC->m_pVehicleInfo->soundFlyBy2; } - trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_LESS_ATTEN, flyBySound ); + trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_LESS_ATTEN, flyBySound); lastFlyBySound[cent->currentState.clientNum] = cg.time; } } @@ -8079,187 +6879,152 @@ static QINLINE void CG_VehicleEffects(centity_t *cent) } } - if ( !cent->currentState.speed//was stopped - && cent->nextState.speed > 0//now moving forward - && cent->m_pVehicle->m_pVehicleInfo->soundEngineStart ) - {//engines rev up for the first time - trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_LESS_ATTEN, cent->m_pVehicle->m_pVehicleInfo->soundEngineStart ); + if (!cent->currentState.speed // was stopped + && cent->nextState.speed > 0 // now moving forward + && cent->m_pVehicle->m_pVehicleInfo->soundEngineStart) { // engines rev up for the first time + trap->S_StartSound(NULL, cent->currentState.clientNum, CHAN_LESS_ATTEN, cent->m_pVehicle->m_pVehicleInfo->soundEngineStart); } // Animals don't exude any effects... - if ( pVehNPC->m_pVehicleInfo->type != VH_ANIMAL ) - { - if (pVehNPC->m_pVehicleInfo->surfDestruction && cent->ghoul2) - { //see if anything has been blown off + if (pVehNPC->m_pVehicleInfo->type != VH_ANIMAL) { + if (pVehNPC->m_pVehicleInfo->surfDestruction && cent->ghoul2) { // see if anything has been blown off int i = 0; qboolean surfDmg = qfalse; - while (i < BG_NUM_TOGGLEABLE_SURFACES) - { - if (bgToggleableSurfaceDebris[i] > 1) - { //this is decidedly a destroyable surface, let's check its status + while (i < BG_NUM_TOGGLEABLE_SURFACES) { + if (bgToggleableSurfaceDebris[i] > 1) { // this is decidedly a destroyable surface, let's check its status int surfTest = trap->G2API_GetSurfaceRenderStatus(cent->ghoul2, 0, bgToggleableSurfaces[i]); - if ( surfTest != -1 - && (surfTest&TURN_OFF) ) - { //it exists, but it's off... + if (surfTest != -1 && (surfTest & TURN_OFF)) { // it exists, but it's off... surfDmg = qtrue; - //create some flames - CG_CreateSurfaceDebris(cent, i, cgs.effects.mShipDestBurning, qfalse); + // create some flames + CG_CreateSurfaceDebris(cent, i, cgs.effects.mShipDestBurning, qfalse); } } i++; } - if (surfDmg) - { //if any surface are damaged, neglect exhaust etc effects (so we don't have exhaust trails coming out of invisible surfaces) + if (surfDmg) { // if any surface are damaged, neglect exhaust etc effects (so we don't have exhaust trails coming out of invisible surfaces) return; } } - if ( pVehNPC->m_iLastFXTime <= cg.time ) - {//until we attach it, we need to debounce this - vec3_t fwd, rt, up; - vec3_t flat; + if (pVehNPC->m_iLastFXTime <= cg.time) { // until we attach it, we need to debounce this + vec3_t fwd, rt, up; + vec3_t flat; float nextFXDelay = 50; VectorSet(flat, 0, cent->lerpAngles[1], cent->lerpAngles[2]); - AngleVectors( flat, fwd, rt, up ); - if ( cent->currentState.speed > 0 ) - {//FIXME: only do this when accelerator is being pressed! (must have a driver?) - vec3_t org; + AngleVectors(flat, fwd, rt, up); + if (cent->currentState.speed > 0) { // FIXME: only do this when accelerator is being pressed! (must have a driver?) + vec3_t org; qboolean doExhaust = qfalse; - VectorMA( cent->lerpOrigin, -16, up, org ); - VectorMA( org, -42, fwd, org ); + VectorMA(cent->lerpOrigin, -16, up, org); + VectorMA(org, -42, fwd, org); // Play damage effects. - //if ( pVehNPC->m_iArmor <= 75 ) - if (0) - {//hurt - trap->FX_PlayEffectID( cgs.effects.mBlackSmoke, org, fwd, -1, -1, qfalse ); - } - else if ( pVehNPC->m_pVehicleInfo->iTrailFX ) - {//okay, do normal trail - trap->FX_PlayEffectID( pVehNPC->m_pVehicleInfo->iTrailFX, org, fwd, -1, -1, qfalse ); + // if ( pVehNPC->m_iArmor <= 75 ) + if (0) { // hurt + trap->FX_PlayEffectID(cgs.effects.mBlackSmoke, org, fwd, -1, -1, qfalse); + } else if (pVehNPC->m_pVehicleInfo->iTrailFX) { // okay, do normal trail + trap->FX_PlayEffectID(pVehNPC->m_pVehicleInfo->iTrailFX, org, fwd, -1, -1, qfalse); } //===================================================================== - //EXHAUST FX + // EXHAUST FX //===================================================================== - //do exhaust - if ( (cent->currentState.eFlags&EF_JETPACK_ACTIVE) ) - {//cheap way of telling us the vehicle is in "turbo" mode - doExhaust = (pVehNPC->m_pVehicleInfo->iTurboFX!=0); - } - else - { - doExhaust = (pVehNPC->m_pVehicleInfo->iExhaustFX!=0); + // do exhaust + if ((cent->currentState.eFlags & EF_JETPACK_ACTIVE)) { // cheap way of telling us the vehicle is in "turbo" mode + doExhaust = (pVehNPC->m_pVehicleInfo->iTurboFX != 0); + } else { + doExhaust = (pVehNPC->m_pVehicleInfo->iExhaustFX != 0); } - if ( doExhaust && cent->ghoul2 ) - { + if (doExhaust && cent->ghoul2) { int i; int fx; - for ( i = 0; i < MAX_VEHICLE_EXHAUSTS; i++ ) - { + for (i = 0; i < MAX_VEHICLE_EXHAUSTS; i++) { // We hit an invalid tag, we quit (they should be created in order so tough luck if not). - if ( pVehNPC->m_iExhaustTag[i] == -1 ) - { + if (pVehNPC->m_iExhaustTag[i] == -1) { break; } - if ( (cent->currentState.brokenLimbs&(1<currentState.brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_HEAVY))) { // engine has taken heavy damage + if (!Q_irand(0, 1)) { // 50% chance of not drawing this engine glow this frame continue; } - } - else if ( (cent->currentState.brokenLimbs&(1<currentState.brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_LIGHT))) { // engine has taken light damage + if (!Q_irand(0, 4)) { // 20% chance of not drawing this engine glow this frame continue; } } - if ( (cent->currentState.eFlags&EF_JETPACK_ACTIVE) //cheap way of telling us the vehicle is in "turbo" mode - && pVehNPC->m_pVehicleInfo->iTurboFX )//they have a valid turbo exhaust effect to play + if ((cent->currentState.eFlags & EF_JETPACK_ACTIVE) // cheap way of telling us the vehicle is in "turbo" mode + && pVehNPC->m_pVehicleInfo->iTurboFX) // they have a valid turbo exhaust effect to play { fx = pVehNPC->m_pVehicleInfo->iTurboFX; - } - else - {//play the normal one + } else { // play the normal one fx = pVehNPC->m_pVehicleInfo->iExhaustFX; } - if (pVehNPC->m_pVehicleInfo->type == VH_FIGHTER) - { - trap->FX_PlayBoltedEffectID(fx, cent->lerpOrigin, cent->ghoul2, pVehNPC->m_iExhaustTag[i], - cent->currentState.number, 0, 0, qtrue); - } - else - { //fixme: bolt these too + if (pVehNPC->m_pVehicleInfo->type == VH_FIGHTER) { + trap->FX_PlayBoltedEffectID(fx, cent->lerpOrigin, cent->ghoul2, pVehNPC->m_iExhaustTag[i], cent->currentState.number, 0, 0, qtrue); + } else { // fixme: bolt these too mdxaBone_t boltMatrix; vec3_t boltOrg, boltDir; - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, pVehNPC->m_iExhaustTag[i], &boltMatrix, flat, - cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, pVehNPC->m_iExhaustTag[i], &boltMatrix, flat, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); - VectorCopy(fwd, boltDir); //fixme? + VectorCopy(fwd, boltDir); // fixme? - trap->FX_PlayEffectID( fx, boltOrg, boltDir, -1, -1, qfalse ); + trap->FX_PlayEffectID(fx, boltOrg, boltDir, -1, -1, qfalse); } } } //===================================================================== - //WING TRAIL FX + // WING TRAIL FX //===================================================================== - //do trail - //FIXME: not in space!!! - if ( pVehNPC->m_pVehicleInfo->iTrailFX != 0 && cent->ghoul2 ) - { + // do trail + // FIXME: not in space!!! + if (pVehNPC->m_pVehicleInfo->iTrailFX != 0 && cent->ghoul2) { int i; vec3_t boltOrg, boltDir; mdxaBone_t boltMatrix; vec3_t getBoltAngles; VectorCopy(cent->lerpAngles, getBoltAngles); - if (pVehNPC->m_pVehicleInfo->type != VH_FIGHTER) - { //only fighters use pitch/roll in refent axis - getBoltAngles[PITCH] = getBoltAngles[ROLL] = 0.0f; + if (pVehNPC->m_pVehicleInfo->type != VH_FIGHTER) { // only fighters use pitch/roll in refent axis + getBoltAngles[PITCH] = getBoltAngles[ROLL] = 0.0f; } - for ( i = 1; i < 5; i++ ) - { - int trailBolt = trap->G2API_AddBolt(cent->ghoul2, 0, va("*trail%d",i) ); + for (i = 1; i < 5; i++) { + int trailBolt = trap->G2API_AddBolt(cent->ghoul2, 0, va("*trail%d", i)); // We hit an invalid tag, we quit (they should be created in order so tough luck if not). - if ( trailBolt == -1 ) - { + if (trailBolt == -1) { break; } - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, trailBolt, &boltMatrix, getBoltAngles, - cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, trailBolt, &boltMatrix, getBoltAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); - VectorCopy(fwd, boltDir); //fixme? + VectorCopy(fwd, boltDir); // fixme? - trap->FX_PlayEffectID( pVehNPC->m_pVehicleInfo->iTrailFX, boltOrg, boltDir, -1, -1, qfalse ); + trap->FX_PlayEffectID(pVehNPC->m_pVehicleInfo->iTrailFX, boltOrg, boltDir, -1, -1, qfalse); } } } - //FIXME armor needs to be sent over network + // FIXME armor needs to be sent over network { - if ( (cent->currentState.eFlags&EF_DEAD) ) - {//just plain dead, use flames - vec3_t up ={0,0,1}; + if ((cent->currentState.eFlags & EF_DEAD)) { // just plain dead, use flames + vec3_t up = {0, 0, 1}; vec3_t boltOrg; - //if ( pVehNPC->m_iDriverTag == -1 ) - {//doh! no tag - VectorCopy( cent->lerpOrigin, boltOrg ); + // if ( pVehNPC->m_iDriverTag == -1 ) + { // doh! no tag + VectorCopy(cent->lerpOrigin, boltOrg); } - //else + // else //{ // mdxaBone_t boltMatrix; // vec3_t getBoltAngles; @@ -8275,32 +7040,23 @@ static QINLINE void CG_VehicleEffects(centity_t *cent) // BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); //} - trap->FX_PlayEffectID( cgs.effects.mShipDestBurning, boltOrg, up, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.mShipDestBurning, boltOrg, up, -1, -1, qfalse); } } - if ( cent->currentState.brokenLimbs ) - { + if (cent->currentState.brokenLimbs) { int i; - if ( !Q_irand( 0, 5 ) ) - { - for ( i = SHIPSURF_FRONT; i <= SHIPSURF_LEFT; i++ ) - { - if ( (cent->currentState.brokenLimbs&(1<<((i-SHIPSURF_FRONT)+SHIPSURF_DAMAGE_FRONT_HEAVY))) ) - {//heavy damage, do both effects - if ( pVehNPC->m_pVehicleInfo->iInjureFX ) - { - CG_CreateSurfaceSmoke( cent, i, pVehNPC->m_pVehicleInfo->iInjureFX ); + if (!Q_irand(0, 5)) { + for (i = SHIPSURF_FRONT; i <= SHIPSURF_LEFT; i++) { + if ((cent->currentState.brokenLimbs & (1 << ((i - SHIPSURF_FRONT) + SHIPSURF_DAMAGE_FRONT_HEAVY)))) { // heavy damage, do both effects + if (pVehNPC->m_pVehicleInfo->iInjureFX) { + CG_CreateSurfaceSmoke(cent, i, pVehNPC->m_pVehicleInfo->iInjureFX); } - if ( pVehNPC->m_pVehicleInfo->iDmgFX ) - { - CG_CreateSurfaceSmoke( cent, i, pVehNPC->m_pVehicleInfo->iDmgFX ); + if (pVehNPC->m_pVehicleInfo->iDmgFX) { + CG_CreateSurfaceSmoke(cent, i, pVehNPC->m_pVehicleInfo->iDmgFX); } - } - else if ( (cent->currentState.brokenLimbs&(1<<((i-SHIPSURF_FRONT)+SHIPSURF_DAMAGE_FRONT_LIGHT))) ) - {//only light damage - if ( pVehNPC->m_pVehicleInfo->iInjureFX ) - { - CG_CreateSurfaceSmoke( cent, i, pVehNPC->m_pVehicleInfo->iInjureFX ); + } else if ((cent->currentState.brokenLimbs & (1 << ((i - SHIPSURF_FRONT) + SHIPSURF_DAMAGE_FRONT_LIGHT)))) { // only light damage + if (pVehNPC->m_pVehicleInfo->iInjureFX) { + CG_CreateSurfaceSmoke(cent, i, pVehNPC->m_pVehicleInfo->iInjureFX); } } } @@ -8337,252 +7093,195 @@ CG_Player */ int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); -float CG_RadiusForCent( centity_t *cent ) -{ - if ( cent->currentState.eType == ET_NPC ) - { - if (cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle && - cent->m_pVehicle->m_pVehicleInfo->g2radius) - { //has override +float CG_RadiusForCent(centity_t *cent) { + if (cent->currentState.eType == ET_NPC) { + if (cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->g2radius) { // has override return cent->m_pVehicle->m_pVehicleInfo->g2radius; - } - else if ( cent->currentState.g2radius ) - { + } else if (cent->currentState.g2radius) { return cent->currentState.g2radius; } - } - else if ( cent->currentState.g2radius ) - { + } else if (cent->currentState.g2radius) { return cent->currentState.g2radius; } return 64.0f; } static float cg_vehThirdPersonAlpha = 1.0f; -extern vec3_t cg_crosshairPos; -extern vec3_t cameraCurLoc; -void CG_CheckThirdPersonAlpha( centity_t *cent, refEntity_t *legs ) -{ +extern vec3_t cg_crosshairPos; +extern vec3_t cameraCurLoc; +void CG_CheckThirdPersonAlpha(centity_t *cent, refEntity_t *legs) { float alpha = 1.0f; - int setFlags = 0; + int setFlags = 0; - if ( cent->m_pVehicle ) - {//a vehicle - if ( cg.predictedPlayerState.m_iVehicleNum != cent->currentState.clientNum//not mine - && cent->m_pVehicle->m_pVehicleInfo - && cent->m_pVehicle->m_pVehicleInfo->cameraOverride - && cent->m_pVehicle->m_pVehicleInfo->cameraAlpha )//it has alpha - {//make sure it's not using any alpha + if (cent->m_pVehicle) { // a vehicle + if (cg.predictedPlayerState.m_iVehicleNum != cent->currentState.clientNum // not mine + && cent->m_pVehicle->m_pVehicleInfo && cent->m_pVehicle->m_pVehicleInfo->cameraOverride && + cent->m_pVehicle->m_pVehicleInfo->cameraAlpha) // it has alpha + { // make sure it's not using any alpha legs->renderfx |= RF_FORCE_ENT_ALPHA; legs->shaderRGBA[3] = 255; return; } } - if ( !cg.renderingThirdPerson ) - { + if (!cg.renderingThirdPerson) { return; } - if ( cg.predictedPlayerState.m_iVehicleNum ) - {//in a vehicle - if ( cg.predictedPlayerState.m_iVehicleNum == cent->currentState.clientNum ) - {//this is my vehicle - if ( cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo - && cent->m_pVehicle->m_pVehicleInfo->cameraOverride - && cent->m_pVehicle->m_pVehicleInfo->cameraAlpha ) - {//vehicle has auto third-person alpha on + if (cg.predictedPlayerState.m_iVehicleNum) { // in a vehicle + if (cg.predictedPlayerState.m_iVehicleNum == cent->currentState.clientNum) { // this is my vehicle + if (cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo && cent->m_pVehicle->m_pVehicleInfo->cameraOverride && + cent->m_pVehicle->m_pVehicleInfo->cameraAlpha) { // vehicle has auto third-person alpha on trace_t trace; - vec3_t dir2Crosshair, end; - VectorSubtract( cg_crosshairPos, cameraCurLoc, dir2Crosshair ); - VectorNormalize( dir2Crosshair ); - VectorMA( cameraCurLoc, cent->m_pVehicle->m_pVehicleInfo->cameraRange*2.0f, dir2Crosshair, end ); - CG_G2Trace( &trace, cameraCurLoc, vec3_origin, vec3_origin, end, ENTITYNUM_NONE, CONTENTS_BODY ); - if ( trace.entityNum == cent->currentState.clientNum - || trace.entityNum == cg.predictedPlayerState.clientNum) - {//hit me or the vehicle I'm in - cg_vehThirdPersonAlpha -= 0.1f*cg.frametime/50.0f; - if ( cg_vehThirdPersonAlpha < cent->m_pVehicle->m_pVehicleInfo->cameraAlpha ) - { + vec3_t dir2Crosshair, end; + VectorSubtract(cg_crosshairPos, cameraCurLoc, dir2Crosshair); + VectorNormalize(dir2Crosshair); + VectorMA(cameraCurLoc, cent->m_pVehicle->m_pVehicleInfo->cameraRange * 2.0f, dir2Crosshair, end); + CG_G2Trace(&trace, cameraCurLoc, vec3_origin, vec3_origin, end, ENTITYNUM_NONE, CONTENTS_BODY); + if (trace.entityNum == cent->currentState.clientNum || trace.entityNum == cg.predictedPlayerState.clientNum) { // hit me or the vehicle I'm in + cg_vehThirdPersonAlpha -= 0.1f * cg.frametime / 50.0f; + if (cg_vehThirdPersonAlpha < cent->m_pVehicle->m_pVehicleInfo->cameraAlpha) { cg_vehThirdPersonAlpha = cent->m_pVehicle->m_pVehicleInfo->cameraAlpha; } - } - else - { - cg_vehThirdPersonAlpha += 0.1f*cg.frametime/50.0f; - if ( cg_vehThirdPersonAlpha > 1.0f ) - { + } else { + cg_vehThirdPersonAlpha += 0.1f * cg.frametime / 50.0f; + if (cg_vehThirdPersonAlpha > 1.0f) { cg_vehThirdPersonAlpha = 1.0f; } } alpha = cg_vehThirdPersonAlpha; - } - else - {//use the cvar - //reset this + } else { // use the cvar + // reset this cg_vehThirdPersonAlpha = 1.0f; - //use the cvar + // use the cvar alpha = cg_thirdPersonAlpha.value; } } - } - else if ( cg.predictedPlayerState.clientNum == cent->currentState.clientNum ) - {//it's me - //reset this + } else if (cg.predictedPlayerState.clientNum == cent->currentState.clientNum) { // it's me + // reset this cg_vehThirdPersonAlpha = 1.0f; - //use the cvar + // use the cvar setFlags = RF_FORCE_ENT_ALPHA; alpha = cg_thirdPersonAlpha.value; } - if ( alpha < 1.0f ) - { + if (alpha < 1.0f) { legs->renderfx |= setFlags; legs->shaderRGBA[3] = (unsigned char)(alpha * 255.0f); } } -void CG_Player( centity_t *cent ) { - clientInfo_t *ci; - refEntity_t legs; - refEntity_t torso; - int clientNum; - int renderfx; - qboolean shadow = qfalse; - float shadowPlane = 0; - vec3_t rootAngles; - float angle; - vec3_t angles, dir, elevated, enang, seekorg; - int iwantout = 0, successchange = 0; - int team; - mdxaBone_t boltMatrix, lHandMatrix; - int doAlpha = 0; - qboolean gotLHandMatrix = qfalse; - qboolean g2HasWeapon = qfalse; - qboolean drawPlayerSaber = qfalse; - qboolean checkDroidShields = qfalse; - - //first if we are not an npc and we are using an emplaced gun then make sure our - //angles are visually capped to the constraints (otherwise it's possible to lerp - //a little outside and look kind of twitchy) - if (cent->currentState.weapon == WP_EMPLACED_GUN && - cent->currentState.otherEntityNum2) - { +void CG_Player(centity_t *cent) { + clientInfo_t *ci; + refEntity_t legs; + refEntity_t torso; + int clientNum; + int renderfx; + qboolean shadow = qfalse; + float shadowPlane = 0; + vec3_t rootAngles; + float angle; + vec3_t angles, dir, elevated, enang, seekorg; + int iwantout = 0, successchange = 0; + int team; + mdxaBone_t boltMatrix, lHandMatrix; + int doAlpha = 0; + qboolean gotLHandMatrix = qfalse; + qboolean g2HasWeapon = qfalse; + qboolean drawPlayerSaber = qfalse; + qboolean checkDroidShields = qfalse; + + // first if we are not an npc and we are using an emplaced gun then make sure our + // angles are visually capped to the constraints (otherwise it's possible to lerp + // a little outside and look kind of twitchy) + if (cent->currentState.weapon == WP_EMPLACED_GUN && cent->currentState.otherEntityNum2) { float empYaw; - if (BG_EmplacedView(cent->lerpAngles, cg_entities[cent->currentState.otherEntityNum2].currentState.angles, &empYaw, cg_entities[cent->currentState.otherEntityNum2].currentState.origin2[0])) - { + if (BG_EmplacedView(cent->lerpAngles, cg_entities[cent->currentState.otherEntityNum2].currentState.angles, &empYaw, + cg_entities[cent->currentState.otherEntityNum2].currentState.origin2[0])) { cent->lerpAngles[YAW] = empYaw; } } - if (cent->currentState.iModelScale) - { //if the server says we have a custom scale then set it now. - cent->modelScale[0] = cent->modelScale[1] = cent->modelScale[2] = cent->currentState.iModelScale/100.0f; - if ( cent->currentState.NPC_class != CLASS_VEHICLE ) - { - if (cent->modelScale[2] && cent->modelScale[2] != 1.0f) - { + if (cent->currentState.iModelScale) { // if the server says we have a custom scale then set it now. + cent->modelScale[0] = cent->modelScale[1] = cent->modelScale[2] = cent->currentState.iModelScale / 100.0f; + if (cent->currentState.NPC_class != CLASS_VEHICLE) { + if (cent->modelScale[2] && cent->modelScale[2] != 1.0f) { cent->lerpOrigin[2] += 24 * (cent->modelScale[2] - 1); } } - } - else - { + } else { VectorClear(cent->modelScale); } - if ((cg_smoothClients.integer || cent->currentState.heldByClient) && (cent->currentState.groundEntityNum >= ENTITYNUM_WORLD || cent->currentState.eType == ET_TERRAIN) && - !(cent->currentState.eFlags2 & EF2_HYPERSPACE) && cg.predictedPlayerState.m_iVehicleNum != cent->currentState.number) - { //always smooth when being thrown - vec3_t posDif; - float smoothFactor; - int k = 0; - float fTolerance = 20000.0f; + if ((cg_smoothClients.integer || cent->currentState.heldByClient) && + (cent->currentState.groundEntityNum >= ENTITYNUM_WORLD || cent->currentState.eType == ET_TERRAIN) && !(cent->currentState.eFlags2 & EF2_HYPERSPACE) && + cg.predictedPlayerState.m_iVehicleNum != cent->currentState.number) { // always smooth when being thrown + vec3_t posDif; + float smoothFactor; + int k = 0; + float fTolerance = 20000.0f; - if (cent->currentState.heldByClient) - { //smooth the origin more when in this state, because movement is origin-based on server. + if (cent->currentState.heldByClient) { // smooth the origin more when in this state, because movement is origin-based on server. smoothFactor = 0.2f; - } - else if ( (cent->currentState.powerups & (1 << PW_SPEED)) || - (cent->currentState.forcePowersActive & (1 << FP_RAGE)) ) - { //we're moving fast so don't smooth as much + } else if ((cent->currentState.powerups & (1 << PW_SPEED)) || + (cent->currentState.forcePowersActive & (1 << FP_RAGE))) { // we're moving fast so don't smooth as much smoothFactor = 0.6f; - } - else if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //greater smoothing for flying vehicles, since they move so fast - fTolerance = 6000000.0f;//500000.0f; //yeah, this is so wrong..but.. + } else if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle && + cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // greater smoothing for flying vehicles, since they move so fast + fTolerance = 6000000.0f; // 500000.0f; //yeah, this is so wrong..but.. smoothFactor = 0.5f; - } - else - { + } else { smoothFactor = 0.5f; } - if (DistanceSquared(cent->beamEnd,cent->lerpOrigin) > smoothFactor*fTolerance) //10000 + if (DistanceSquared(cent->beamEnd, cent->lerpOrigin) > smoothFactor * fTolerance) // 10000 { VectorCopy(cent->lerpOrigin, cent->beamEnd); } VectorSubtract(cent->lerpOrigin, cent->beamEnd, posDif); - for (k=0;k<3;k++) - { - cent->beamEnd[k]=(cent->beamEnd[k]+posDif[k]*smoothFactor); - cent->lerpOrigin[k]=cent->beamEnd[k]; + for (k = 0; k < 3; k++) { + cent->beamEnd[k] = (cent->beamEnd[k] + posDif[k] * smoothFactor); + cent->lerpOrigin[k] = cent->beamEnd[k]; } - } - else - { + } else { VectorCopy(cent->lerpOrigin, cent->beamEnd); } - if (cent->currentState.m_iVehicleNum && - cent->currentState.NPC_class != CLASS_VEHICLE) - { //this player is riding a vehicle + if (cent->currentState.m_iVehicleNum && cent->currentState.NPC_class != CLASS_VEHICLE) { // this player is riding a vehicle centity_t *veh = &cg_entities[cent->currentState.m_iVehicleNum]; cent->lerpAngles[YAW] = veh->lerpAngles[YAW]; - //Attach ourself to the vehicle - if (veh->m_pVehicle && - cent->playerState && - veh->playerState && - cent->ghoul2 && - veh->ghoul2 ) - { - if ( veh->currentState.owner != cent->currentState.clientNum ) - {//FIXME: what about visible passengers? - if ( CG_VehicleAttachDroidUnit( cent, &legs ) ) - { + // Attach ourself to the vehicle + if (veh->m_pVehicle && cent->playerState && veh->playerState && cent->ghoul2 && veh->ghoul2) { + if (veh->currentState.owner != cent->currentState.clientNum) { // FIXME: what about visible passengers? + if (CG_VehicleAttachDroidUnit(cent, &legs)) { checkDroidShields = qtrue; } } // fix for screen blinking when spectating person on vehicle and then // switching to someone else, often happens on siege - else if ( veh->currentState.owner != ENTITYNUM_NONE && - (cent->playerState->clientNum != cg.snap->ps.clientNum)) - {//has a pilot...??? + else if (veh->currentState.owner != ENTITYNUM_NONE && (cent->playerState->clientNum != cg.snap->ps.clientNum)) { // has a pilot...??? vec3_t oldPSOrg; - //make sure it has its pilot and parent set + // make sure it has its pilot and parent set veh->m_pVehicle->m_pPilot = (bgEntity_t *)&cg_entities[veh->currentState.owner]; veh->m_pVehicle->m_pParentEntity = (bgEntity_t *)veh; VectorCopy(veh->playerState->origin, oldPSOrg); - //update the veh's playerstate org for getting the bolt + // update the veh's playerstate org for getting the bolt VectorCopy(veh->lerpOrigin, veh->playerState->origin); VectorCopy(cent->lerpOrigin, cent->playerState->origin); - //Now do the attach + // Now do the attach VectorCopy(veh->lerpAngles, veh->playerState->viewangles); veh->m_pVehicle->m_pVehicleInfo->AttachRiders(veh->m_pVehicle); - //copy the "playerstate origin" to the lerpOrigin since that's what we use to display + // copy the "playerstate origin" to the lerpOrigin since that's what we use to display VectorCopy(cent->playerState->origin, cent->lerpOrigin); VectorCopy(oldPSOrg, veh->playerState->origin); @@ -8593,22 +7292,17 @@ void CG_Player( centity_t *cent ) { // the client number is stored in clientNum. It can't be derived // from the entity number, because a single client may have // multiple corpses on the level using the same clientinfo - if (cent->currentState.eType != ET_NPC) - { + if (cent->currentState.eType != ET_NPC) { clientNum = cent->currentState.clientNum; - if ( clientNum < 0 || clientNum >= MAX_CLIENTS ) { - trap->Error( ERR_DROP, "Bad clientNum on player entity"); + if (clientNum < 0 || clientNum >= MAX_CLIENTS) { + trap->Error(ERR_DROP, "Bad clientNum on player entity"); } - ci = &cgs.clientinfo[ clientNum ]; - } - else - { - if (!cent->npcClient) - { - CG_CreateNPCClient(¢->npcClient); //allocate memory for it + ci = &cgs.clientinfo[clientNum]; + } else { + if (!cent->npcClient) { + CG_CreateNPCClient(¢->npcClient); // allocate memory for it - if (!cent->npcClient) - { + if (!cent->npcClient) { assert(0); return; } @@ -8619,32 +7313,27 @@ void CG_Player( centity_t *cent ) { assert(cent->npcClient); - if (cent->npcClient->ghoul2Model != cent->ghoul2 && cent->ghoul2) - { + if (cent->npcClient->ghoul2Model != cent->ghoul2 && cent->ghoul2) { cent->npcClient->ghoul2Model = cent->ghoul2; - if (cent->localAnimIndex <= 1) - { + if (cent->localAnimIndex <= 1) { cent->npcClient->bolt_rhand = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*r_hand"); cent->npcClient->bolt_lhand = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*l_hand"); - //rhand must always be first bolt. lhand always second. Whichever you want the - //jetpack bolted to must always be third. + // rhand must always be first bolt. lhand always second. Whichever you want the + // jetpack bolted to must always be third. trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*chestg"); - //claw bolts + // claw bolts trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*r_hand_cap_r_arm"); trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*l_hand_cap_l_arm"); cent->npcClient->bolt_head = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "*head_top"); - if (cent->npcClient->bolt_head == -1) - { + if (cent->npcClient->bolt_head == -1) { cent->npcClient->bolt_head = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "ceyebrow"); } cent->npcClient->bolt_motion = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "Motion"); cent->npcClient->bolt_llumbar = trap->G2API_AddBolt(cent->npcClient->ghoul2Model, 0, "lower_lumbar"); - } - else - { + } else { cent->npcClient->bolt_rhand = -1; cent->npcClient->bolt_lhand = -1; cent->npcClient->bolt_head = -1; @@ -8659,56 +7348,43 @@ void CG_Player( centity_t *cent ) { // it is possible to see corpses from disconnected players that may // not have valid clientinfo - if ( !ci->infoValid ) { + if (!ci->infoValid) { return; } // Add the player to the radar if on the same team and its a team game - if (cgs.gametype >= GT_TEAM) - { - if ( cent->currentState.eType != ET_NPC && - cg.snap->ps.clientNum != cent->currentState.number && - ci->team == cg.snap->ps.persistant[PERS_TEAM] ) - { + if (cgs.gametype >= GT_TEAM) { + if (cent->currentState.eType != ET_NPC && cg.snap->ps.clientNum != cent->currentState.number && ci->team == cg.snap->ps.persistant[PERS_TEAM]) { CG_AddRadarEnt(cent); } } - if (cent->currentState.eType == ET_NPC && - cent->currentState.NPC_class == CLASS_VEHICLE) - { //add vehicles + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class == CLASS_VEHICLE) { // add vehicles CG_AddRadarEnt(cent); - if ( CG_InFighter() ) - {//this is a vehicle, bracket it - if ( cg.predictedPlayerState.m_iVehicleNum != cent->currentState.clientNum ) - {//don't add the vehicle I'm in... :) + if (CG_InFighter()) { // this is a vehicle, bracket it + if (cg.predictedPlayerState.m_iVehicleNum != cent->currentState.clientNum) { // don't add the vehicle I'm in... :) CG_AddBracketedEnt(cent); } } - } - if (!cent->ghoul2) - { //not ready yet? + if (!cent->ghoul2) { // not ready yet? #ifdef _DEBUG Com_Printf("WARNING: Client %i has a null ghoul2 instance\n", cent->currentState.number); #endif trap->G2API_ClearAttachedInstance(cent->currentState.number); - if (ci->ghoul2Model && - trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { + if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { #ifdef _DEBUG Com_Printf("Clientinfo instance was valid, duplicating for cent\n"); #endif trap->G2API_DuplicateGhoul2Instance(ci->ghoul2Model, ¢->ghoul2); - //Attach the instance to this entity num so we can make use of client-server - //shared operations if possible. + // Attach the instance to this entity num so we can make use of client-server + // shared operations if possible. trap->G2API_AttachInstanceToEntNum(cent->ghoul2, cent->currentState.number, qfalse); - if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cent->noFace = qtrue; } @@ -8718,182 +7394,138 @@ void CG_Player( centity_t *cent ) { return; } - if (ci->superSmoothTime) - { //do crazy smoothing - if (ci->superSmoothTime > cg.time) - { //do it + if (ci->superSmoothTime) { // do crazy smoothing + if (ci->superSmoothTime > cg.time) { // do it trap->G2API_AbsurdSmoothing(cent->ghoul2, qtrue); - } - else - { //turn it off + } else { // turn it off ci->superSmoothTime = 0; trap->G2API_AbsurdSmoothing(cent->ghoul2, qfalse); } } - if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) - { //don't show all this shit during intermission - if ( cent->currentState.eType == ET_NPC - && cent->currentState.NPC_class != CLASS_VEHICLE ) - {//NPC in intermission - } - else - {//don't render players or vehicles in intermissions, allow other NPCs for scripts + if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) { // don't show all this shit during intermission + if (cent->currentState.eType == ET_NPC && cent->currentState.NPC_class != CLASS_VEHICLE) { // NPC in intermission + } else { // don't render players or vehicles in intermissions, allow other NPCs for scripts return; } } CG_VehicleEffects(cent); - if ((cent->currentState.eFlags & EF_JETPACK) && !(cent->currentState.eFlags & EF_DEAD) && - cg_g2JetpackInstance) - { //should have a jetpack attached - //1 is rhand weap, 2 is lhand weap (akimbo sabs), 3 is jetpack - if (!trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 3)) - { + if ((cent->currentState.eFlags & EF_JETPACK) && !(cent->currentState.eFlags & EF_DEAD) && cg_g2JetpackInstance) { // should have a jetpack attached + // 1 is rhand weap, 2 is lhand weap (akimbo sabs), 3 is jetpack + if (!trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 3)) { trap->G2API_CopySpecificGhoul2Model(cg_g2JetpackInstance, 0, cent->ghoul2, 3); } - if (cent->currentState.eFlags & EF_JETPACK_ACTIVE) - { + if (cent->currentState.eFlags & EF_JETPACK_ACTIVE) { mdxaBone_t mat; vec3_t flamePos, flameDir; int n = 0; - while (n < 2) - { - //Get the position/dir of the flame bolt on the jetpack model bolted to the player + while (n < 2) { + // Get the position/dir of the flame bolt on the jetpack model bolted to the player trap->G2API_GetBoltMatrix(cent->ghoul2, 3, n, &mat, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&mat, ORIGIN, flamePos); - if (n == 0) - { + if (n == 0) { BG_GiveMeVectorFromMatrix(&mat, NEGATIVE_Y, flameDir); VectorMA(flamePos, -9.5f, flameDir, flamePos); BG_GiveMeVectorFromMatrix(&mat, POSITIVE_X, flameDir); VectorMA(flamePos, -13.5f, flameDir, flamePos); - } - else - { + } else { BG_GiveMeVectorFromMatrix(&mat, POSITIVE_X, flameDir); VectorMA(flamePos, -9.5f, flameDir, flamePos); BG_GiveMeVectorFromMatrix(&mat, NEGATIVE_Y, flameDir); VectorMA(flamePos, -13.5f, flameDir, flamePos); } - if (cent->currentState.eFlags & EF_JETPACK_FLAMING) - { //create effects - //FIXME: Just one big effect - //Play the effect + if (cent->currentState.eFlags & EF_JETPACK_FLAMING) { // create effects + // FIXME: Just one big effect + // Play the effect trap->FX_PlayEffectID(cgs.effects.mBobaJet, flamePos, flameDir, -1, -1, qfalse); trap->FX_PlayEffectID(cgs.effects.mBobaJet, flamePos, flameDir, -1, -1, qfalse); - //Keep the jet fire sound looping - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, - trap->S_RegisterSound( "sound/effects/fire_lp" ) ); - } - else - { //just idling - //FIXME: Different smaller effect for idle - //Play the effect + // Keep the jet fire sound looping + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, trap->S_RegisterSound("sound/effects/fire_lp")); + } else { // just idling + // FIXME: Different smaller effect for idle + // Play the effect trap->FX_PlayEffectID(cgs.effects.mBobaJet, flamePos, flameDir, -1, -1, qfalse); } n++; } - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, - trap->S_RegisterSound( "sound/boba/JETHOVER" ) ); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, trap->S_RegisterSound("sound/boba/JETHOVER")); } - } - else if (trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 3)) - { //fixme: would be good if this could be done not every frame + } else if (trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 3)) { // fixme: would be good if this could be done not every frame trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 3); } g2HasWeapon = trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1); - if (!g2HasWeapon) - { //force a redup of the weapon instance onto the client instance + if (!g2HasWeapon) { // force a redup of the weapon instance onto the client instance cent->ghoul2weapon = NULL; cent->weapon = 0; } - if (cent->torsoBolt && !(cent->currentState.eFlags & EF_DEAD)) - { //he's alive and has a limb missing still, reattach it and reset the weapon + if (cent->torsoBolt && !(cent->currentState.eFlags & EF_DEAD)) { // he's alive and has a limb missing still, reattach it and reset the weapon CG_ReattachLimb(cent); } - if (cent->isRagging && !(cent->currentState.eFlags & EF_DEAD) && !(cent->currentState.eFlags & EF_RAG)) - { //make sure we don't ragdoll ever while alive unless directly told to with eFlags + if (cent->isRagging && !(cent->currentState.eFlags & EF_DEAD) && + !(cent->currentState.eFlags & EF_RAG)) { // make sure we don't ragdoll ever while alive unless directly told to with eFlags cent->isRagging = qfalse; - trap->G2API_SetRagDoll(cent->ghoul2, NULL); //calling with null parms resets to no ragdoll. + trap->G2API_SetRagDoll(cent->ghoul2, NULL); // calling with null parms resets to no ragdoll. } - if (cent->ghoul2 && cent->torsoBolt && ((cent->torsoBolt & RARMBIT) || (cent->torsoBolt & RHANDBIT) || (cent->torsoBolt & WAISTBIT)) && g2HasWeapon) - { //kill the weapon if the limb holding it is no longer on the model + if (cent->ghoul2 && cent->torsoBolt && ((cent->torsoBolt & RARMBIT) || (cent->torsoBolt & RHANDBIT) || (cent->torsoBolt & WAISTBIT)) && + g2HasWeapon) { // kill the weapon if the limb holding it is no longer on the model trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); g2HasWeapon = qfalse; } - if (!cent->trickAlphaTime || (cg.time - cent->trickAlphaTime) > 1000) - { //things got out of sync, perhaps a new client is trying to fill in this slot + if (!cent->trickAlphaTime || (cg.time - cent->trickAlphaTime) > 1000) { // things got out of sync, perhaps a new client is trying to fill in this slot cent->trickAlpha = 255; cent->trickAlphaTime = cg.time; } - if (cent->currentState.eFlags & EF_NODRAW) - { //If nodraw, return here + if (cent->currentState.eFlags & EF_NODRAW) { // If nodraw, return here return; - } - else if (cent->currentState.eFlags2 & EF2_SHIP_DEATH) - { //died in ship, don't draw, we were "obliterated" + } else if (cent->currentState.eFlags2 & EF2_SHIP_DEATH) { // died in ship, don't draw, we were "obliterated" return; } - //If this client has tricked you. - if (CG_IsMindTricked(cent->currentState.trickedentindex, - cent->currentState.trickedentindex2, - cent->currentState.trickedentindex3, - cent->currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - if (cent->trickAlpha > 1) - { - cent->trickAlpha -= (cg.time - cent->trickAlphaTime)*0.5; + // If this client has tricked you. + if (CG_IsMindTricked(cent->currentState.trickedentindex, cent->currentState.trickedentindex2, cent->currentState.trickedentindex3, + cent->currentState.trickedentindex4, cg.snap->ps.clientNum)) { + if (cent->trickAlpha > 1) { + cent->trickAlpha -= (cg.time - cent->trickAlphaTime) * 0.5; cent->trickAlphaTime = cg.time; - if (cent->trickAlpha < 0) - { + if (cent->trickAlpha < 0) { cent->trickAlpha = 0; } doAlpha = 1; - } - else - { + } else { doAlpha = 1; cent->trickAlpha = 1; cent->trickAlphaTime = cg.time; iwantout = 1; } - } - else - { - if (cent->trickAlpha < 255) - { + } else { + if (cent->trickAlpha < 255) { cent->trickAlpha += (cg.time - cent->trickAlphaTime); cent->trickAlphaTime = cg.time; - if (cent->trickAlpha > 255) - { + if (cent->trickAlpha > 255) { cent->trickAlpha = 255; } doAlpha = 1; - } - else - { + } else { cent->trickAlpha = 255; cent->trickAlphaTime = cg.time; } @@ -8901,7 +7533,7 @@ void CG_Player( centity_t *cent ) { // get the player model information renderfx = 0; - if ( cent->currentState.number == cg.snap->ps.clientNum) { + if (cent->currentState.number == cg.snap->ps.clientNum) { if (!cg.renderingThirdPerson) { #if 0 if (!cg_fpls.integer || cent->currentState.weapon != WP_SABER) @@ -8909,13 +7541,12 @@ void CG_Player( centity_t *cent ) { if (cent->currentState.weapon != WP_SABER) #endif { - renderfx = RF_THIRD_PERSON; // only draw in mirrors + renderfx = RF_THIRD_PERSON; // only draw in mirrors } } else { if (com_cameraMode.integer) { iwantout = 1; - // goto minimal_add; // NOTENOTE Temporary @@ -8931,59 +7562,43 @@ void CG_Player( centity_t *cent ) { // Save the old weapon, to verify that it is or is not the same as the new weapon. // rww - Make sure weapons don't get set BEFORE cent->ghoul2 is initialized or else we'll have no // weapon bolted on - if (cent->currentState.saberInFlight) - { + if (cent->currentState.saberInFlight) { cent->ghoul2weapon = CG_G2WeaponInstance(cent, WP_SABER); } if (cent->ghoul2 && - (cent->currentState.eType != ET_NPC || (cent->currentState.NPC_class != CLASS_VEHICLE&¢->currentState.NPC_class != CLASS_REMOTE&¢->currentState.NPC_class != CLASS_SEEKER)) && //don't add weapon models to NPCs that have no bolt for them! + (cent->currentState.eType != ET_NPC || (cent->currentState.NPC_class != CLASS_VEHICLE && cent->currentState.NPC_class != CLASS_REMOTE && + cent->currentState.NPC_class != CLASS_SEEKER)) && // don't add weapon models to NPCs that have no bolt for them! cent->ghoul2weapon != CG_G2WeaponInstance(cent, cent->currentState.weapon) && - !(cent->currentState.eFlags & EF_DEAD) && !cent->torsoBolt && - cg.snap && (cent->currentState.number != cg.snap->ps.clientNum || (cg.snap->ps.pm_flags & PMF_FOLLOW))) - { - if (ci->team == TEAM_SPECTATOR) - { + !(cent->currentState.eFlags & EF_DEAD) && !cent->torsoBolt && cg.snap && + (cent->currentState.number != cg.snap->ps.clientNum || (cg.snap->ps.pm_flags & PMF_FOLLOW))) { + if (ci->team == TEAM_SPECTATOR) { cent->ghoul2weapon = NULL; cent->weapon = 0; - } - else - { + } else { CG_CopyG2WeaponInstance(cent, cent->currentState.weapon, cent->ghoul2); - if (cent->currentState.eType != ET_NPC) - { - if (cent->weapon == WP_SABER - && cent->weapon != cent->currentState.weapon - && !cent->currentState.saberHolstered) - { //switching away from the saber - //trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" )); - if (ci->saber[0].soundOff - && !cent->currentState.saberHolstered) - { + if (cent->currentState.eType != ET_NPC) { + if (cent->weapon == WP_SABER && cent->weapon != cent->currentState.weapon && + !cent->currentState.saberHolstered) { // switching away from the saber + // trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" + // )); + if (ci->saber[0].soundOff && !cent->currentState.saberHolstered) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, ci->saber[0].soundOff); } - if (ci->saber[1].soundOff && - ci->saber[1].model[0] && - !cent->currentState.saberHolstered) - { + if (ci->saber[1].soundOff && ci->saber[1].model[0] && !cent->currentState.saberHolstered) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, ci->saber[1].soundOff); } - } - else if (cent->currentState.weapon == WP_SABER - && cent->weapon != cent->currentState.weapon - && !cent->saberWasInFlight) - { //switching to the saber - //trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" )); - if (ci->saber[0].soundOn) - { + } else if (cent->currentState.weapon == WP_SABER && cent->weapon != cent->currentState.weapon && + !cent->saberWasInFlight) { // switching to the saber + // trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" )); + if (ci->saber[0].soundOn) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, ci->saber[0].soundOn); } - if (ci->saber[1].soundOn) - { + if (ci->saber[1].soundOn) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, ci->saber[1].soundOn); } @@ -8995,125 +7610,83 @@ void CG_Player( centity_t *cent ) { cent->weapon = cent->currentState.weapon; cent->ghoul2weapon = CG_G2WeaponInstance(cent, cent->currentState.weapon); } - } - else if ((cent->currentState.eFlags & EF_DEAD) || cent->torsoBolt) - { - cent->ghoul2weapon = NULL; //be sure to update after respawning/getting limb regrown + } else if ((cent->currentState.eFlags & EF_DEAD) || cent->torsoBolt) { + cent->ghoul2weapon = NULL; // be sure to update after respawning/getting limb regrown } - - if (cent->saberWasInFlight && g2HasWeapon) - { - cent->saberWasInFlight = qfalse; + if (cent->saberWasInFlight && g2HasWeapon) { + cent->saberWasInFlight = qfalse; } - memset (&legs, 0, sizeof(legs)); + memset(&legs, 0, sizeof(legs)); CG_SetGhoul2Info(&legs, cent); VectorCopy(cent->modelScale, legs.modelScale); - legs.radius = CG_RadiusForCent( cent ); + legs.radius = CG_RadiusForCent(cent); VectorClear(legs.angles); - if (ci->colorOverride[0] != 0.0f || - ci->colorOverride[1] != 0.0f || - ci->colorOverride[2] != 0.0f) - { - legs.shaderRGBA[0] = ci->colorOverride[0]*255.0f; - legs.shaderRGBA[1] = ci->colorOverride[1]*255.0f; - legs.shaderRGBA[2] = ci->colorOverride[2]*255.0f; + if (ci->colorOverride[0] != 0.0f || ci->colorOverride[1] != 0.0f || ci->colorOverride[2] != 0.0f) { + legs.shaderRGBA[0] = ci->colorOverride[0] * 255.0f; + legs.shaderRGBA[1] = ci->colorOverride[1] * 255.0f; + legs.shaderRGBA[2] = ci->colorOverride[2] * 255.0f; legs.shaderRGBA[3] = cent->currentState.customRGBA[3]; - } - else - { + } else { legs.shaderRGBA[0] = cent->currentState.customRGBA[0]; legs.shaderRGBA[1] = cent->currentState.customRGBA[1]; legs.shaderRGBA[2] = cent->currentState.customRGBA[2]; legs.shaderRGBA[3] = cent->currentState.customRGBA[3]; } -// minimal_add: + // minimal_add: team = ci->team; - if (cgs.gametype >= GT_TEAM && cg_drawFriend.integer && - cent->currentState.number != cg.snap->ps.clientNum && - cent->currentState.eType != ET_NPC) - { // If the view is either a spectator or on the same team as this character, show a symbol above their head. - if ((cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.persistant[PERS_TEAM] == team) && - !(cent->currentState.eFlags & EF_DEAD)) - { - if (cgs.gametype == GT_SIEGE) - { //check for per-map team shaders - if (team == SIEGETEAM_TEAM1) - { - if (cgSiegeTeam1PlShader) - { - CG_PlayerFloatSprite( cent, cgSiegeTeam1PlShader); - } - else - { //if there isn't one fallback to default - CG_PlayerFloatSprite( cent, cgs.media.teamRedShader); - } - } - else - { - if (cgSiegeTeam2PlShader) - { - CG_PlayerFloatSprite( cent, cgSiegeTeam2PlShader); + if (cgs.gametype >= GT_TEAM && cg_drawFriend.integer && cent->currentState.number != cg.snap->ps.clientNum && + cent->currentState.eType != ET_NPC) { // If the view is either a spectator or on the same team as this character, show a symbol above their head. + if ((cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.persistant[PERS_TEAM] == team) && !(cent->currentState.eFlags & EF_DEAD)) { + if (cgs.gametype == GT_SIEGE) { // check for per-map team shaders + if (team == SIEGETEAM_TEAM1) { + if (cgSiegeTeam1PlShader) { + CG_PlayerFloatSprite(cent, cgSiegeTeam1PlShader); + } else { // if there isn't one fallback to default + CG_PlayerFloatSprite(cent, cgs.media.teamRedShader); } - else - { //if there isn't one fallback to default - CG_PlayerFloatSprite( cent, cgs.media.teamBlueShader); + } else { + if (cgSiegeTeam2PlShader) { + CG_PlayerFloatSprite(cent, cgSiegeTeam2PlShader); + } else { // if there isn't one fallback to default + CG_PlayerFloatSprite(cent, cgs.media.teamBlueShader); } } - } - else - { //generic teamplay - if (team == TEAM_RED) - { - CG_PlayerFloatSprite( cent, cgs.media.teamRedShader); - } - else // if (team == TEAM_BLUE) + } else { // generic teamplay + if (team == TEAM_RED) { + CG_PlayerFloatSprite(cent, cgs.media.teamRedShader); + } else // if (team == TEAM_BLUE) { - CG_PlayerFloatSprite( cent, cgs.media.teamBlueShader); + CG_PlayerFloatSprite(cent, cgs.media.teamBlueShader); } } } - } - else if (cgs.gametype == GT_POWERDUEL && cg_drawFriend.integer && - cent->currentState.number != cg.snap->ps.clientNum) - { - if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR && - cent->currentState.number < MAX_CLIENTS && - !(cent->currentState.eFlags & EF_DEAD) && - ci && - cgs.clientinfo[cg.snap->ps.clientNum].duelTeam == ci->duelTeam) - { //ally in powerduel, so draw the icon - CG_PlayerFloatSprite( cent, cgs.media.powerDuelAllyShader); - } - else if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR && - cent->currentState.number < MAX_CLIENTS && - !(cent->currentState.eFlags & EF_DEAD) && - ci->duelTeam == DUELTEAM_DOUBLE) - { - CG_PlayerFloatSprite( cent, cgs.media.powerDuelAllyShader); + } else if (cgs.gametype == GT_POWERDUEL && cg_drawFriend.integer && cent->currentState.number != cg.snap->ps.clientNum) { + if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR && cent->currentState.number < MAX_CLIENTS && + !(cent->currentState.eFlags & EF_DEAD) && ci && + cgs.clientinfo[cg.snap->ps.clientNum].duelTeam == ci->duelTeam) { // ally in powerduel, so draw the icon + CG_PlayerFloatSprite(cent, cgs.media.powerDuelAllyShader); + } else if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR && cent->currentState.number < MAX_CLIENTS && + !(cent->currentState.eFlags & EF_DEAD) && ci->duelTeam == DUELTEAM_DOUBLE) { + CG_PlayerFloatSprite(cent, cgs.media.powerDuelAllyShader); } } if (cgs.gametype == GT_JEDIMASTER && cg_drawFriend.integer && - cent->currentState.number != cg.snap->ps.clientNum) // Don't show a sprite above a player's own head in 3rd person. - { // If the view is either a spectator or on the same team as this character, show a symbol above their head. - if ((cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.persistant[PERS_TEAM] == team) && - !(cent->currentState.eFlags & EF_DEAD)) - { - if (CG_ThereIsAMaster()) - { - if (!cg.snap->ps.isJediMaster) - { - if (!cent->currentState.isJediMaster) - { - CG_PlayerFloatSprite( cent, cgs.media.teamRedShader); + cent->currentState.number != cg.snap->ps.clientNum) // Don't show a sprite above a player's own head in 3rd person. + { // If the view is either a spectator or on the same team as this character, show a symbol above their head. + if ((cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.persistant[PERS_TEAM] == team) && !(cent->currentState.eFlags & EF_DEAD)) { + if (CG_ThereIsAMaster()) { + if (!cg.snap->ps.isJediMaster) { + if (!cent->currentState.isJediMaster) { + CG_PlayerFloatSprite(cent, cgs.media.teamRedShader); } } } @@ -9121,21 +7694,20 @@ void CG_Player( centity_t *cent ) { } // add the shadow - shadow = CG_PlayerShadow( cent, &shadowPlane ); + shadow = CG_PlayerShadow(cent, &shadowPlane); - if ( ((cent->currentState.eFlags & EF_SEEKERDRONE) || cent->currentState.genericenemyindex != -1) && cent->currentState.eType != ET_NPC ) - { - refEntity_t seeker; + if (((cent->currentState.eFlags & EF_SEEKERDRONE) || cent->currentState.genericenemyindex != -1) && cent->currentState.eType != ET_NPC) { + refEntity_t seeker; - memset( &seeker, 0, sizeof(seeker) ); + memset(&seeker, 0, sizeof(seeker)); VectorCopy(cent->lerpOrigin, elevated); elevated[2] += 40; - VectorCopy( elevated, seeker.lightingOrigin ); + VectorCopy(elevated, seeker.lightingOrigin); seeker.shadowPlane = shadowPlane; - seeker.renderfx = 0; //renderfx; - //don't show in first person? + seeker.renderfx = 0; // renderfx; + // don't show in first person? angle = ((cg.time / 12) & 255) * (M_PI * 2) / 255; dir[0] = cos(angle) * 20; @@ -9145,33 +7717,26 @@ void CG_Player( centity_t *cent ) { VectorCopy(seeker.origin, seekorg); - if (cent->currentState.genericenemyindex > MAX_GENTITIES) - { - float prefig = (cent->currentState.genericenemyindex-cg.time)/80; + if (cent->currentState.genericenemyindex > MAX_GENTITIES) { + float prefig = (cent->currentState.genericenemyindex - cg.time) / 80; - if (prefig > 55) - { + if (prefig > 55) { prefig = 55; - } - else if (prefig < 1) - { + } else if (prefig < 1) { prefig = 1; } - elevated[2] -= 55-prefig; + elevated[2] -= 55 - prefig; angle = ((cg.time / 12) & 255) * (M_PI * 2) / 255; dir[0] = cos(angle) * 20; dir[1] = sin(angle) * 20; dir[2] = cos(angle) * 5; VectorAdd(elevated, dir, seeker.origin); - } - else if (cent->currentState.genericenemyindex != ENTITYNUM_NONE && cent->currentState.genericenemyindex != -1) - { + } else if (cent->currentState.genericenemyindex != ENTITYNUM_NONE && cent->currentState.genericenemyindex != -1) { centity_t *enent = &cg_entities[cent->currentState.genericenemyindex]; - if (enent) - { + if (enent) { VectorSubtract(enent->lerpOrigin, seekorg, enang); VectorNormalize(enang); vectoangles(enang, angles); @@ -9179,8 +7744,7 @@ void CG_Player( centity_t *cent ) { } } - if (!successchange) - { + if (!successchange) { angles[0] = sin(angle) * 30; angles[1] = (angle * 180 / M_PI) + 90; if (angles[1] > 360) @@ -9188,73 +7752,63 @@ void CG_Player( centity_t *cent ) { angles[2] = 0; } - AnglesToAxis( angles, seeker.axis ); + AnglesToAxis(angles, seeker.axis); seeker.hModel = trap->R_RegisterModel("models/items/remote.md3"); - trap->R_AddRefEntityToScene( &seeker ); + trap->R_AddRefEntityToScene(&seeker); } // add a water splash if partially in and out of water - CG_PlayerSplash( cent ); + CG_PlayerSplash(cent); - if ( (cg_shadows.integer == 3 || cg_shadows.integer == 2) && shadow ) { + if ((cg_shadows.integer == 3 || cg_shadows.integer == 2) && shadow) { renderfx |= RF_SHADOW_PLANE; } - renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all + renderfx |= RF_LIGHTING_ORIGIN; // use the same origin for all // if we've been hit, display proper fullscreen fx CG_PlayerHitFX(cent); - VectorCopy( cent->lerpOrigin, legs.origin ); + VectorCopy(cent->lerpOrigin, legs.origin); - VectorCopy( cent->lerpOrigin, legs.lightingOrigin ); + VectorCopy(cent->lerpOrigin, legs.lightingOrigin); legs.shadowPlane = shadowPlane; legs.renderfx = renderfx; - if (cg_shadows.integer == 2 && (renderfx & RF_THIRD_PERSON)) - { //can see own shadow + if (cg_shadows.integer == 2 && (renderfx & RF_THIRD_PERSON)) { // can see own shadow legs.renderfx |= RF_SHADOW_ONLY; } - VectorCopy (legs.origin, legs.oldorigin); // don't positionally lerp at all + VectorCopy(legs.origin, legs.oldorigin); // don't positionally lerp at all - CG_G2PlayerAngles( cent, legs.axis, rootAngles ); - CG_G2PlayerHeadAnims( cent ); + CG_G2PlayerAngles(cent, legs.axis, rootAngles); + CG_G2PlayerHeadAnims(cent); - if ( (cent->currentState.eFlags2&EF2_HELD_BY_MONSTER) - && cent->currentState.hasLookTarget )//NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... + if ((cent->currentState.eFlags2 & EF2_HELD_BY_MONSTER) && + cent->currentState.hasLookTarget) // NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... { - centity_t *rancor = &cg_entities[cent->currentState.lookTarget]; - if ( rancor ) - { - BG_AttachToRancor( rancor->ghoul2, //ghoul2 info - rancor->lerpAngles[YAW], - rancor->lerpOrigin, - cg.time, - cgs.gameModels, - rancor->modelScale, - (rancor->currentState.eFlags2&EF2_GENERIC_NPC_FLAG), - legs.origin, - legs.angles, - NULL ); - - if ( cent->isRagging ) - {//hack, ragdoll has you way at bottom of bounding box - VectorMA( legs.origin, 32, legs.axis[2], legs.origin ); - } - VectorCopy( legs.origin, legs.oldorigin ); - VectorCopy( legs.origin, legs.lightingOrigin ); - - VectorCopy( legs.angles, cent->lerpAngles ); - VectorCopy( cent->lerpAngles, rootAngles );//??? tempAngles );//tempAngles is needed a lot below - VectorCopy( cent->lerpAngles, cent->turAngles ); - VectorCopy( legs.origin, cent->lerpOrigin ); - } - } - //This call is mainly just to reconstruct the skeleton. But we'll get the left hand matrix while we're at it. - //If we don't reconstruct the skeleton after setting the bone angles, we will get bad bolt points on the model + centity_t *rancor = &cg_entities[cent->currentState.lookTarget]; + if (rancor) { + BG_AttachToRancor(rancor->ghoul2, // ghoul2 info + rancor->lerpAngles[YAW], rancor->lerpOrigin, cg.time, cgs.gameModels, rancor->modelScale, + (rancor->currentState.eFlags2 & EF2_GENERIC_NPC_FLAG), legs.origin, legs.angles, NULL); + + if (cent->isRagging) { // hack, ragdoll has you way at bottom of bounding box + VectorMA(legs.origin, 32, legs.axis[2], legs.origin); + } + VectorCopy(legs.origin, legs.oldorigin); + VectorCopy(legs.origin, legs.lightingOrigin); + + VectorCopy(legs.angles, cent->lerpAngles); + VectorCopy(cent->lerpAngles, rootAngles); //??? tempAngles );//tempAngles is needed a lot below + VectorCopy(cent->lerpAngles, cent->turAngles); + VectorCopy(legs.origin, cent->lerpOrigin); + } + } + // This call is mainly just to reconstruct the skeleton. But we'll get the left hand matrix while we're at it. + // If we don't reconstruct the skeleton after setting the bone angles, we will get bad bolt points on the model //(e.g. the weapon model bolt will look "lagged") if there's no other GetBoltMatrix call for the rest of the - //frame. Yes, this is stupid and needs to be fixed properly. - //The current solution is to force it not to reconstruct the skeleton for the first GBM call in G2PlayerAngles. - //It works and we end up only reconstructing it once, but it doesn't seem like the best solution. + // frame. Yes, this is stupid and needs to be fixed properly. + // The current solution is to force it not to reconstruct the skeleton for the first GBM call in G2PlayerAngles. + // It works and we end up only reconstructing it once, but it doesn't seem like the best solution. trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); gotLHandMatrix = qtrue; #if 0 @@ -9314,35 +7868,30 @@ void CG_Player( centity_t *cent ) { } #endif - if (cent->currentState.eFlags & EF_DEAD) - { - //rww - since our angles are fixed when we're dead this shouldn't be an issue anyway - //we need to render the dying/dead player because we are now spawning the body on respawn instead of death - //return; + if (cent->currentState.eFlags & EF_DEAD) { + // rww - since our angles are fixed when we're dead this shouldn't be an issue anyway + // we need to render the dying/dead player because we are now spawning the body on respawn instead of death + // return; } ScaleModelAxis(&legs); - memset( &torso, 0, sizeof(torso) ); + memset(&torso, 0, sizeof(torso)); - //rww - force speed "trail" effect - if (!(cent->currentState.powerups & (1 << PW_SPEED)) || doAlpha || !cg_speedTrail.integer) - { + // rww - force speed "trail" effect + if (!(cent->currentState.powerups & (1 << PW_SPEED)) || doAlpha || !cg_speedTrail.integer) { cent->frame_minus1_refreshed = 0; cent->frame_minus2_refreshed = 0; } - if (cent->frame_minus1_refreshed || - cent->frame_minus2_refreshed) - { - vec3_t tDir; - int distVelBase; + if (cent->frame_minus1_refreshed || cent->frame_minus2_refreshed) { + vec3_t tDir; + int distVelBase; VectorCopy(cent->currentState.pos.trDelta, tDir); - distVelBase = SPEED_TRAIL_DISTANCE*(VectorNormalize(tDir)*0.004); + distVelBase = SPEED_TRAIL_DISTANCE * (VectorNormalize(tDir) * 0.004); - if (cent->frame_minus1_refreshed) - { + if (cent->frame_minus1_refreshed) { refEntity_t reframe_minus1 = legs; reframe_minus1.renderfx |= RF_FORCE_ENT_ALPHA; reframe_minus1.shaderRGBA[0] = legs.shaderRGBA[0]; @@ -9350,26 +7899,25 @@ void CG_Player( centity_t *cent ) { reframe_minus1.shaderRGBA[2] = legs.shaderRGBA[2]; reframe_minus1.shaderRGBA[3] = 100; - //rww - if the client gets a bad framerate we will only receive frame positions - //once per frame anyway, so we might end up with speed trails very spread out. - //in order to avoid that, we'll get the direction of the last trail from the player - //and place the trail refent a set distance from the player location this frame + // rww - if the client gets a bad framerate we will only receive frame positions + // once per frame anyway, so we might end up with speed trails very spread out. + // in order to avoid that, we'll get the direction of the last trail from the player + // and place the trail refent a set distance from the player location this frame VectorSubtract(cent->frame_minus1, legs.origin, tDir); VectorNormalize(tDir); - cent->frame_minus1[0] = legs.origin[0]+tDir[0]*distVelBase; - cent->frame_minus1[1] = legs.origin[1]+tDir[1]*distVelBase; - cent->frame_minus1[2] = legs.origin[2]+tDir[2]*distVelBase; + cent->frame_minus1[0] = legs.origin[0] + tDir[0] * distVelBase; + cent->frame_minus1[1] = legs.origin[1] + tDir[1] * distVelBase; + cent->frame_minus1[2] = legs.origin[2] + tDir[2] * distVelBase; VectorCopy(cent->frame_minus1, reframe_minus1.origin); - //reframe_minus1.customShader = 2; + // reframe_minus1.customShader = 2; trap->R_AddRefEntityToScene(&reframe_minus1); } - if (cent->frame_minus2_refreshed) - { + if (cent->frame_minus2_refreshed) { refEntity_t reframe_minus2 = legs; reframe_minus2.renderfx |= RF_FORCE_ENT_ALPHA; @@ -9378,67 +7926,60 @@ void CG_Player( centity_t *cent ) { reframe_minus2.shaderRGBA[2] = legs.shaderRGBA[2]; reframe_minus2.shaderRGBA[3] = 50; - //Same as above but do it between trail points instead of the player and first trail entry + // Same as above but do it between trail points instead of the player and first trail entry VectorSubtract(cent->frame_minus2, cent->frame_minus1, tDir); VectorNormalize(tDir); - cent->frame_minus2[0] = cent->frame_minus1[0]+tDir[0]*distVelBase; - cent->frame_minus2[1] = cent->frame_minus1[1]+tDir[1]*distVelBase; - cent->frame_minus2[2] = cent->frame_minus1[2]+tDir[2]*distVelBase; + cent->frame_minus2[0] = cent->frame_minus1[0] + tDir[0] * distVelBase; + cent->frame_minus2[1] = cent->frame_minus1[1] + tDir[1] * distVelBase; + cent->frame_minus2[2] = cent->frame_minus1[2] + tDir[2] * distVelBase; VectorCopy(cent->frame_minus2, reframe_minus2.origin); - //reframe_minus2.customShader = 2; + // reframe_minus2.customShader = 2; trap->R_AddRefEntityToScene(&reframe_minus2); } } - //trigger animation-based sounds, done before next lerp frame. + // trigger animation-based sounds, done before next lerp frame. CG_TriggerAnimSounds(cent); // get the animation state (after rotation, to allow feet shuffle) - CG_PlayerAnimation( cent, &legs.oldframe, &legs.frame, &legs.backlerp, - &torso.oldframe, &torso.frame, &torso.backlerp ); + CG_PlayerAnimation(cent, &legs.oldframe, &legs.frame, &legs.backlerp, &torso.oldframe, &torso.frame, &torso.backlerp); // add the talk baloon or disconnect icon - CG_PlayerSprites( cent ); + CG_PlayerSprites(cent); - if (cent->currentState.eFlags & EF_DEAD) - { //keep track of death anim frame for when we copy off the bodyqueue + if (cent->currentState.eFlags & EF_DEAD) { // keep track of death anim frame for when we copy off the bodyqueue ci->frame = cent->pe.torso.frame; } - if (cent->currentState.activeForcePass > FORCE_LEVEL_3 - && cent->currentState.NPC_class != CLASS_VEHICLE) - { + if (cent->currentState.activeForcePass > FORCE_LEVEL_3 && cent->currentState.NPC_class != CLASS_VEHICLE) { matrix3_t axis; vec3_t tAng, fAng, fxDir; vec3_t efOrg; int realForceLev = (cent->currentState.activeForcePass - FORCE_LEVEL_3); - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); - VectorSet( fAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); + VectorSet(fAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0); - AngleVectors( fAng, fxDir, NULL, NULL ); + AngleVectors(fAng, fxDir, NULL, NULL); - if ( cent->currentState.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD - && Q_irand( 0, 1 ) ) - {//alternate back and forth between left and right - mdxaBone_t rHandMatrix; - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_rhand, &rHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + if (cent->currentState.torsoAnim == BOTH_FORCE_2HANDEDLIGHTNING_HOLD && Q_irand(0, 1)) { // alternate back and forth between left and right + mdxaBone_t rHandMatrix; + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_rhand, &rHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); efOrg[0] = rHandMatrix.matrix[0][3]; efOrg[1] = rHandMatrix.matrix[1][3]; efOrg[2] = rHandMatrix.matrix[2][3]; - } - else - { - //trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); - if (!gotLHandMatrix) - { - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + } else { + // trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + if (!gotLHandMatrix) { + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); gotLHandMatrix = qtrue; } efOrg[0] = lHandMatrix.matrix[0][3]; @@ -9446,18 +7987,15 @@ void CG_Player( centity_t *cent ) { efOrg[2] = lHandMatrix.matrix[2][3]; } - AnglesToAxis( fAng, axis ); + AnglesToAxis(fAng, axis); - if ( realForceLev > FORCE_LEVEL_2 ) - {//arc - //trap->FX_PlayEffectID( cgs.effects.forceLightningWide, efOrg, fxDir ); - //trap->FX_PlayEntityEffectID(cgs.effects.forceDrainWide, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); + if (realForceLev > FORCE_LEVEL_2) { // arc + // trap->FX_PlayEffectID( cgs.effects.forceLightningWide, efOrg, fxDir ); + // trap->FX_PlayEntityEffectID(cgs.effects.forceDrainWide, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); trap->FX_PlayEntityEffectID(cgs.effects.forceDrainWide, efOrg, axis, -1, -1, -1, -1); - } - else - {//line - //trap->FX_PlayEffectID( cgs.effects.forceLightning, efOrg, fxDir ); - //trap->FX_PlayEntityEffectID(cgs.effects.forceDrain, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); + } else { // line + // trap->FX_PlayEffectID( cgs.effects.forceLightning, efOrg, fxDir ); + // trap->FX_PlayEntityEffectID(cgs.effects.forceDrain, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); trap->FX_PlayEntityEffectID(cgs.effects.forceDrain, efOrg, axis, -1, -1, -1, -1); } @@ -9468,24 +8006,21 @@ void CG_Player( centity_t *cent ) { trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound("sound/weapons/force/drain.wav") ); } */ - } - else if ( cent->currentState.activeForcePass - && cent->currentState.NPC_class != CLASS_VEHICLE) - {//doing the electrocuting + } else if (cent->currentState.activeForcePass && cent->currentState.NPC_class != CLASS_VEHICLE) { // doing the electrocuting matrix3_t axis; vec3_t tAng, fAng, fxDir; vec3_t efOrg; - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); - VectorSet( fAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0 ); + VectorSet(fAng, cent->pe.torso.pitchAngle, cent->pe.torso.yawAngle, 0); - AngleVectors( fAng, fxDir, NULL, NULL ); + AngleVectors(fAng, fxDir, NULL, NULL); - //trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); - if (!gotLHandMatrix) - { - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + // trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + if (!gotLHandMatrix) { + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); gotLHandMatrix = qtrue; } @@ -9493,18 +8028,15 @@ void CG_Player( centity_t *cent ) { efOrg[1] = lHandMatrix.matrix[1][3]; efOrg[2] = lHandMatrix.matrix[2][3]; - AnglesToAxis( fAng, axis ); + AnglesToAxis(fAng, axis); - if ( cent->currentState.activeForcePass > FORCE_LEVEL_2 ) - {//arc - //trap->FX_PlayEffectID( cgs.effects.forceLightningWide, efOrg, fxDir ); - //trap->FX_PlayEntityEffectID(cgs.effects.forceLightningWide, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); + if (cent->currentState.activeForcePass > FORCE_LEVEL_2) { // arc + // trap->FX_PlayEffectID( cgs.effects.forceLightningWide, efOrg, fxDir ); + // trap->FX_PlayEntityEffectID(cgs.effects.forceLightningWide, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); trap->FX_PlayEntityEffectID(cgs.effects.forceLightningWide, efOrg, axis, -1, -1, -1, -1); - } - else - {//line - //trap->FX_PlayEffectID( cgs.effects.forceLightning, efOrg, fxDir ); - //trap->FX_PlayEntityEffectID(cgs.effects.forceLightning, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); + } else { // line + // trap->FX_PlayEffectID( cgs.effects.forceLightning, efOrg, fxDir ); + // trap->FX_PlayEntityEffectID(cgs.effects.forceLightning, efOrg, axis, cent->boltInfo, cent->currentState.number, -1, -1); trap->FX_PlayEntityEffectID(cgs.effects.forceLightning, efOrg, axis, -1, -1, -1, -1); } @@ -9517,24 +8049,22 @@ void CG_Player( centity_t *cent ) { */ } - //fullbody push effect - if (cent->currentState.eFlags & EF_BODYPUSH) - { + // fullbody push effect + if (cent->currentState.eFlags & EF_BODYPUSH) { CG_ForcePushBodyBlur(cent); } - if ( cent->currentState.powerups & (1 << PW_DISINT_4) ) - { + if (cent->currentState.powerups & (1 << PW_DISINT_4)) { vec3_t tAng; vec3_t efOrg; - //VectorSet( tAng, 0, cent->pe.torso.yawAngle, 0 ); - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + // VectorSet( tAng, 0, cent->pe.torso.yawAngle, 0 ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); - //trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); - if (!gotLHandMatrix) - { - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + // trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); + if (!gotLHandMatrix) { + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_lhand, &lHandMatrix, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); gotLHandMatrix = qtrue; } @@ -9542,16 +8072,14 @@ void CG_Player( centity_t *cent ) { efOrg[1] = lHandMatrix.matrix[1][3]; efOrg[2] = lHandMatrix.matrix[2][3]; - if ( (cent->currentState.forcePowersActive & (1 << FP_GRIP)) && - (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum) ) - { + if ((cent->currentState.forcePowersActive & (1 << FP_GRIP)) && (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) { vec3_t boltDir; vec3_t origBolt; VectorCopy(efOrg, origBolt); - BG_GiveMeVectorFromMatrix( &lHandMatrix, NEGATIVE_Y, boltDir ); + BG_GiveMeVectorFromMatrix(&lHandMatrix, NEGATIVE_Y, boltDir); - CG_ForceGripEffect( efOrg ); - CG_ForceGripEffect( efOrg ); + CG_ForceGripEffect(efOrg); + CG_ForceGripEffect(efOrg); /* //Render a scaled version of the model's hand with a n337 looking shader @@ -9636,50 +8164,36 @@ void CG_Player( centity_t *cent ) { trap->R_AddRefEntityToScene( ®rip_arm ); } */ + } else if (!(cent->currentState.forcePowersActive & (1 << FP_GRIP))) { + // use refractive effect + CG_ForcePushBlur(efOrg, cent); } - else if (!(cent->currentState.forcePowersActive & (1 << FP_GRIP))) - { - //use refractive effect - CG_ForcePushBlur( efOrg, cent ); - } - } - else if (cent->bodyFadeTime) - { //reset the counter for keeping track of push refraction effect state + } else if (cent->bodyFadeTime) { // reset the counter for keeping track of push refraction effect state cent->bodyFadeTime = 0; } - if (cent->currentState.weapon == WP_STUN_BATON && cent->currentState.number == cg.snap->ps.clientNum) - { - trap->S_AddLoopingSound( cent->currentState.number, cg.refdef.vieworg, vec3_origin, - trap->S_RegisterSound( "sound/weapons/baton/idle.wav" ) ); + if (cent->currentState.weapon == WP_STUN_BATON && cent->currentState.number == cg.snap->ps.clientNum) { + trap->S_AddLoopingSound(cent->currentState.number, cg.refdef.vieworg, vec3_origin, trap->S_RegisterSound("sound/weapons/baton/idle.wav")); } - //NOTE: All effects that should be visible during mindtrick should go above here + // NOTE: All effects that should be visible during mindtrick should go above here - if (iwantout) - { + if (iwantout) { goto stillDoSaber; - //return; - } - else if (doAlpha) - { + // return; + } else if (doAlpha) { legs.renderfx |= RF_FORCE_ENT_ALPHA; legs.shaderRGBA[3] = cent->trickAlpha; - if (legs.shaderRGBA[3] < 1) - { //don't cancel it out even if it's < 1 + if (legs.shaderRGBA[3] < 1) { // don't cancel it out even if it's < 1 legs.shaderRGBA[3] = 1; } } - if (cent->teamPowerEffectTime > cg.time) - { - if (cent->teamPowerType == 3) - { //absorb is a somewhat different effect entirely - //Guess I'll take care of it where it's always been, just checking these values instead. - } - else - { + if (cent->teamPowerEffectTime > cg.time) { + if (cent->teamPowerType == 3) { // absorb is a somewhat different effect entirely + // Guess I'll take care of it where it's always been, just checking these values instead. + } else { vec4_t preCol; int preRFX; @@ -9693,28 +8207,23 @@ void CG_Player( centity_t *cent ) { preCol[2] = legs.shaderRGBA[2]; preCol[3] = legs.shaderRGBA[3]; - if (cent->teamPowerType == 1) - { //heal + if (cent->teamPowerType == 1) { // heal legs.shaderRGBA[0] = 0; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 0; - } - else if (cent->teamPowerType == 0) - { //regen + } else if (cent->teamPowerType == 0) { // regen legs.shaderRGBA[0] = 0; legs.shaderRGBA[1] = 0; legs.shaderRGBA[2] = 255; - } - else - { //drain + } else { // drain legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 0; legs.shaderRGBA[2] = 0; } - legs.shaderRGBA[3] = ((cent->teamPowerEffectTime - cg.time)/8); + legs.shaderRGBA[3] = ((cent->teamPowerEffectTime - cg.time) / 8); - legs.customShader = trap->R_RegisterShader( "powerups/ysalimarishell" ); + legs.customShader = trap->R_RegisterShader("powerups/ysalimarishell"); trap->R_AddRefEntityToScene(&legs); legs.customShader = 0; @@ -9725,66 +8234,57 @@ void CG_Player( centity_t *cent ) { legs.shaderRGBA[3] = preCol[3]; } } - - //If you've tricked this client. - if (CG_IsMindTricked(cg.snap->ps.fd.forceMindtrickTargetIndex, - cg.snap->ps.fd.forceMindtrickTargetIndex2, - cg.snap->ps.fd.forceMindtrickTargetIndex3, - cg.snap->ps.fd.forceMindtrickTargetIndex4, - cent->currentState.number)) - { - if (cent->ghoul2) - { + + // If you've tricked this client. + if (CG_IsMindTricked(cg.snap->ps.fd.forceMindtrickTargetIndex, cg.snap->ps.fd.forceMindtrickTargetIndex2, cg.snap->ps.fd.forceMindtrickTargetIndex3, + cg.snap->ps.fd.forceMindtrickTargetIndex4, cent->currentState.number)) { + if (cent->ghoul2) { vec3_t efOrg; vec3_t tAng, fxAng; matrix3_t axis; - //VectorSet( tAng, 0, cent->pe.torso.yawAngle, 0 ); - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + // VectorSet( tAng, 0, cent->pe.torso.yawAngle, 0 ); + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_head, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, efOrg); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fxAng); - axis[0][0] = boltMatrix.matrix[0][0]; - axis[0][1] = boltMatrix.matrix[1][0]; - axis[0][2] = boltMatrix.matrix[2][0]; + axis[0][0] = boltMatrix.matrix[0][0]; + axis[0][1] = boltMatrix.matrix[1][0]; + axis[0][2] = boltMatrix.matrix[2][0]; - axis[1][0] = boltMatrix.matrix[0][1]; - axis[1][1] = boltMatrix.matrix[1][1]; - axis[1][2] = boltMatrix.matrix[2][1]; + axis[1][0] = boltMatrix.matrix[0][1]; + axis[1][1] = boltMatrix.matrix[1][1]; + axis[1][2] = boltMatrix.matrix[2][1]; - axis[2][0] = boltMatrix.matrix[0][2]; - axis[2][1] = boltMatrix.matrix[1][2]; - axis[2][2] = boltMatrix.matrix[2][2]; + axis[2][0] = boltMatrix.matrix[0][2]; + axis[2][1] = boltMatrix.matrix[1][2]; + axis[2][2] = boltMatrix.matrix[2][2]; - //trap->FX_PlayEntityEffectID(trap->FX_RegisterEffect("force/confusion.efx"), efOrg, axis, cent->boltInfo, cent->currentState.number); + // trap->FX_PlayEntityEffectID(trap->FX_RegisterEffect("force/confusion.efx"), efOrg, axis, cent->boltInfo, cent->currentState.number); trap->FX_PlayEntityEffectID(cgs.effects.mForceConfustionOld, efOrg, axis, -1, -1, -1, -1); } } - if (cgs.gametype == GT_HOLOCRON && cent->currentState.time2 && (cg.renderingThirdPerson || cg.snap->ps.clientNum != cent->currentState.number)) - { + if (cgs.gametype == GT_HOLOCRON && cent->currentState.time2 && (cg.renderingThirdPerson || cg.snap->ps.clientNum != cent->currentState.number)) { int i = 0; int renderedHolos = 0; - refEntity_t holoRef; + refEntity_t holoRef; - while (i < NUM_FORCE_POWERS && renderedHolos < 3) - { - if (cent->currentState.time2 & (1 << i)) - { - memset( &holoRef, 0, sizeof(holoRef) ); + while (i < NUM_FORCE_POWERS && renderedHolos < 3) { + if (cent->currentState.time2 & (1 << i)) { + memset(&holoRef, 0, sizeof(holoRef)); VectorCopy(cent->lerpOrigin, elevated); elevated[2] += 8; - VectorCopy( elevated, holoRef.lightingOrigin ); + VectorCopy(elevated, holoRef.lightingOrigin); holoRef.shadowPlane = shadowPlane; - holoRef.renderfx = 0;//RF_THIRD_PERSON; + holoRef.renderfx = 0; // RF_THIRD_PERSON; - if (renderedHolos == 0) - { + if (renderedHolos == 0) { angle = ((cg.time / 8) & 255) * (M_PI * 2) / 255; dir[0] = cos(angle) * 20; dir[1] = sin(angle) * 20; @@ -9796,10 +8296,8 @@ void CG_Player( centity_t *cent ) { if (angles[1] > 360) angles[1] -= 360; angles[2] = 0; - AnglesToAxis( angles, holoRef.axis ); - } - else if (renderedHolos == 1) - { + AnglesToAxis(angles, holoRef.axis); + } else if (renderedHolos == 1) { angle = ((cg.time / 8) & 255) * (M_PI * 2) / 255 + M_PI; if (angle > M_PI * 2) angle -= (float)M_PI * 2; @@ -9813,10 +8311,8 @@ void CG_Player( centity_t *cent ) { if (angles[1] > 360) angles[1] -= 360; angles[2] = 0; - AnglesToAxis( angles, holoRef.axis ); - } - else - { + AnglesToAxis(angles, holoRef.axis); + } else { angle = ((cg.time / 6) & 255) * (M_PI * 2) / 255 + 0.5 * M_PI; if (angle > M_PI * 2) angle -= (float)M_PI * 2; @@ -9841,34 +8337,31 @@ void CG_Player( centity_t *cent ) { addspriteArgStruct_t fxSArgs; vec3_t holoCenter; - holoCenter[0] = holoRef.origin[0] + holoRef.axis[2][0]*18; - holoCenter[1] = holoRef.origin[1] + holoRef.axis[2][1]*18; - holoCenter[2] = holoRef.origin[2] + holoRef.axis[2][2]*18; + holoCenter[0] = holoRef.origin[0] + holoRef.axis[2][0] * 18; + holoCenter[1] = holoRef.origin[1] + holoRef.axis[2][1] * 18; + holoCenter[2] = holoRef.origin[2] + holoRef.axis[2][2] * 18; - wv = sin( cg.time * 0.004f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.004f) * 0.08f + 0.1f; VectorCopy(holoCenter, fxSArgs.origin); VectorClear(fxSArgs.vel); VectorClear(fxSArgs.accel); - fxSArgs.scale = wv*60; - fxSArgs.dscale = wv*60; - fxSArgs.sAlpha = wv*12; - fxSArgs.eAlpha = wv*12; + fxSArgs.scale = wv * 60; + fxSArgs.dscale = wv * 60; + fxSArgs.sAlpha = wv * 12; + fxSArgs.eAlpha = wv * 12; fxSArgs.rotation = 0.0f; fxSArgs.bounce = 0.0f; fxSArgs.life = 1.0f; - fxSArgs.flags = 0x08000000|0x00000001; + fxSArgs.flags = 0x08000000 | 0x00000001; - if (forcePowerDarkLight[i] == FORCE_DARKSIDE) - { //dark + if (forcePowerDarkLight[i] == FORCE_DARKSIDE) { // dark fxSArgs.sAlpha *= 3; fxSArgs.eAlpha *= 3; fxSArgs.shader = cgs.media.redSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else if (forcePowerDarkLight[i] == FORCE_LIGHTSIDE) - { //light + } else if (forcePowerDarkLight[i] == FORCE_LIGHTSIDE) { // light fxSArgs.sAlpha *= 1.5; fxSArgs.eAlpha *= 1.5; fxSArgs.shader = cgs.media.redSaberGlowShader; @@ -9877,20 +8370,13 @@ void CG_Player( centity_t *cent ) { trap->FX_AddSprite(&fxSArgs); fxSArgs.shader = cgs.media.blueSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else - { //neutral - if (i == FP_SABER_OFFENSE || - i == FP_SABER_DEFENSE || - i == FP_SABERTHROW) - { //saber power + } else { // neutral + if (i == FP_SABER_OFFENSE || i == FP_SABER_DEFENSE || i == FP_SABERTHROW) { // saber power fxSArgs.sAlpha *= 1.5; fxSArgs.eAlpha *= 1.5; fxSArgs.shader = cgs.media.greenSaberGlowShader; trap->FX_AddSprite(&fxSArgs); - } - else - { + } else { fxSArgs.sAlpha *= 0.5; fxSArgs.eAlpha *= 0.5; fxSArgs.shader = cgs.media.greenSaberGlowShader; @@ -9902,7 +8388,7 @@ void CG_Player( centity_t *cent ) { } holoRef.hModel = trap->R_RegisterModel(forceHolocronModels[i]); - trap->R_AddRefEntityToScene( &holoRef ); + trap->R_AddRefEntityToScene(&holoRef); renderedHolos++; } @@ -9911,169 +8397,128 @@ void CG_Player( centity_t *cent ) { } if ((cent->currentState.powerups & (1 << PW_YSALAMIRI)) || - (cgs.gametype == GT_CTY && ((cent->currentState.powerups & (1 << PW_REDFLAG)) || (cent->currentState.powerups & (1 << PW_BLUEFLAG)))) ) - { - if (cgs.gametype == GT_CTY && (cent->currentState.powerups & (1 << PW_REDFLAG))) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysaliredShader ); - } - else if (cgs.gametype == GT_CTY && (cent->currentState.powerups & (1 << PW_BLUEFLAG))) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysaliblueShader ); - } - else - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysalimariShader ); + (cgs.gametype == GT_CTY && ((cent->currentState.powerups & (1 << PW_REDFLAG)) || (cent->currentState.powerups & (1 << PW_BLUEFLAG))))) { + if (cgs.gametype == GT_CTY && (cent->currentState.powerups & (1 << PW_REDFLAG))) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysaliredShader); + } else if (cgs.gametype == GT_CTY && (cent->currentState.powerups & (1 << PW_BLUEFLAG))) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysaliblueShader); + } else { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.4f, cgs.media.ysalimariShader); } } - if (cent->currentState.powerups & (1 << PW_FORCE_BOON)) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.boonShader ); + if (cent->currentState.powerups & (1 << PW_FORCE_BOON)) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.boonShader); } - if (cent->currentState.powerups & (1 << PW_FORCE_ENLIGHTENED_DARK)) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.endarkenmentShader ); - } - else if (cent->currentState.powerups & (1 << PW_FORCE_ENLIGHTENED_LIGHT)) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.enlightenmentShader ); + if (cent->currentState.powerups & (1 << PW_FORCE_ENLIGHTENED_DARK)) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.endarkenmentShader); + } else if (cent->currentState.powerups & (1 << PW_FORCE_ENLIGHTENED_LIGHT)) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 2.0f, cgs.media.enlightenmentShader); } - if (cent->currentState.eFlags & EF_INVULNERABLE) - { - CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.0f, cgs.media.invulnerabilityShader ); + if (cent->currentState.eFlags & EF_INVULNERABLE) { + CG_DrawPlayerSphere(cent, cent->lerpOrigin, 1.0f, cgs.media.invulnerabilityShader); } stillDoSaber: - if ((cent->currentState.eFlags & EF_DEAD) && cent->currentState.weapon == WP_SABER) - { - //cent->saberLength = 0; + if ((cent->currentState.eFlags & EF_DEAD) && cent->currentState.weapon == WP_SABER) { + // cent->saberLength = 0; BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); drawPlayerSaber = qtrue; - } - else if (cent->currentState.weapon == WP_SABER - && cent->currentState.saberHolstered < 2 ) - { - if ( (!cent->currentState.saberInFlight //saber not in flight - || ci->saber[1].soundLoop) //??? - && !(cent->currentState.eFlags & EF_DEAD))//still alive + } else if (cent->currentState.weapon == WP_SABER && cent->currentState.saberHolstered < 2) { + if ((!cent->currentState.saberInFlight // saber not in flight + || ci->saber[1].soundLoop) //??? + && !(cent->currentState.eFlags & EF_DEAD)) // still alive { vec3_t soundSpot; qboolean didFirstSound = qfalse; - if (cg.snap->ps.clientNum == cent->currentState.number) - { - //trap->S_AddLoopingSound( cent->currentState.number, cg.refdef.vieworg, vec3_origin, + if (cg.snap->ps.clientNum == cent->currentState.number) { + // trap->S_AddLoopingSound( cent->currentState.number, cg.refdef.vieworg, vec3_origin, // trap->S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ) ); VectorCopy(cg.refdef.vieworg, soundSpot); - } - else - { - //trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, + } else { + // trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, // trap->S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ) ); VectorCopy(cent->lerpOrigin, soundSpot); } - if (ci->saber[0].model[0] - && ci->saber[0].soundLoop - && !cent->currentState.saberInFlight) - { + if (ci->saber[0].model[0] && ci->saber[0].soundLoop && !cent->currentState.saberInFlight) { int i = 0; qboolean hasLen = qfalse; - while (i < ci->saber[0].numBlades) - { - if (ci->saber[0].blade[i].length) - { + while (i < ci->saber[0].numBlades) { + if (ci->saber[0].blade[i].length) { hasLen = qtrue; break; } i++; } - if (hasLen) - { - trap->S_AddLoopingSound( cent->currentState.number, soundSpot, vec3_origin, - ci->saber[0].soundLoop ); + if (hasLen) { + trap->S_AddLoopingSound(cent->currentState.number, soundSpot, vec3_origin, ci->saber[0].soundLoop); didFirstSound = qtrue; } } - if (ci->saber[1].model[0] - && ci->saber[1].soundLoop - && (!didFirstSound || ci->saber[0].soundLoop != ci->saber[1].soundLoop)) - { + if (ci->saber[1].model[0] && ci->saber[1].soundLoop && (!didFirstSound || ci->saber[0].soundLoop != ci->saber[1].soundLoop)) { int i = 0; qboolean hasLen = qfalse; - while (i < ci->saber[1].numBlades) - { - if (ci->saber[1].blade[i].length) - { + while (i < ci->saber[1].numBlades) { + if (ci->saber[1].blade[i].length) { hasLen = qtrue; break; } i++; } - if (hasLen) - { - trap->S_AddLoopingSound( cent->currentState.number, soundSpot, vec3_origin, - ci->saber[1].soundLoop ); + if (hasLen) { + trap->S_AddLoopingSound(cent->currentState.number, soundSpot, vec3_origin, ci->saber[1].soundLoop); } } } - if (iwantout - && !cent->currentState.saberInFlight) - { - if (cent->currentState.eFlags & EF_DEAD) - { - if (cent->ghoul2 - && cent->currentState.saberInFlight - && g2HasWeapon) - { //special case, kill the saber on a freshly dead player if another source says to. + if (iwantout && !cent->currentState.saberInFlight) { + if (cent->currentState.eFlags & EF_DEAD) { + if (cent->ghoul2 && cent->currentState.saberInFlight && + g2HasWeapon) { // special case, kill the saber on a freshly dead player if another source says to. trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); g2HasWeapon = qfalse; } } return; - //goto endOfCall; + // goto endOfCall; } - if (g2HasWeapon - && cent->currentState.saberInFlight) - { //keep this set, so we don't re-unholster the thing when we get it back, even if it's knocked away. + if (g2HasWeapon && + cent->currentState.saberInFlight) { // keep this set, so we don't re-unholster the thing when we get it back, even if it's knocked away. cent->saberWasInFlight = qtrue; } - if (cent->currentState.saberInFlight - && cent->currentState.saberEntityNum) - { + if (cent->currentState.saberInFlight && cent->currentState.saberEntityNum) { centity_t *saberEnt; saberEnt = &cg_entities[cent->currentState.saberEntityNum]; if (/*!cent->bolt4 &&*/ g2HasWeapon || !cent->bolt3 || - saberEnt->serverSaberHitIndex != saberEnt->currentState.modelindex/*|| !cent->saberLength*/) - { //saber is in flight, do not have it as a standard weapon model + saberEnt->serverSaberHitIndex != + saberEnt->currentState.modelindex /*|| !cent->saberLength*/) { // saber is in flight, do not have it as a standard weapon model qboolean addBolts = qfalse; mdxaBone_t boltMat; - if (g2HasWeapon) - { - //ah well, just stick it over the right hand right now. - trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_rhand, &boltMat, cent->turAngles, cent->lerpOrigin, - cg.time, cgs.gameModels, cent->modelScale); + if (g2HasWeapon) { + // ah well, just stick it over the right hand right now. + trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_rhand, &boltMat, cent->turAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale); BG_GiveMeVectorFromMatrix(&boltMat, ORIGIN, saberEnt->currentState.pos.trBase); trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); g2HasWeapon = qfalse; } - //cent->bolt4 = 1; + // cent->bolt4 = 1; saberEnt->currentState.pos.trTime = cg.time; saberEnt->currentState.apos.trTime = cg.time; @@ -10082,50 +8527,38 @@ void CG_Player( centity_t *cent ) { VectorCopy(saberEnt->currentState.apos.trBase, saberEnt->lerpAngles); cent->bolt3 = saberEnt->currentState.apos.trBase[0]; - if (!cent->bolt3) - { + if (!cent->bolt3) { cent->bolt3 = 1; } cent->bolt2 = 0; saberEnt->currentState.bolt2 = 123; - if (saberEnt->ghoul2 && - saberEnt->serverSaberHitIndex == saberEnt->currentState.modelindex) - { + if (saberEnt->ghoul2 && saberEnt->serverSaberHitIndex == saberEnt->currentState.modelindex) { // now set up the gun bolt on it addBolts = qtrue; - } - else - { - const char *saberModel = CG_ConfigString( CS_MODELS+saberEnt->currentState.modelindex ); + } else { + const char *saberModel = CG_ConfigString(CS_MODELS + saberEnt->currentState.modelindex); saberEnt->serverSaberHitIndex = saberEnt->currentState.modelindex; - if (saberEnt->ghoul2) - { //clean if we already have one (because server changed model string index) + if (saberEnt->ghoul2) { // clean if we already have one (because server changed model string index) trap->G2API_CleanGhoul2Models(&(saberEnt->ghoul2)); saberEnt->ghoul2 = 0; } - if (saberModel && saberModel[0]) - { + if (saberModel && saberModel[0]) { trap->G2API_InitGhoul2Model(&saberEnt->ghoul2, saberModel, 0, 0, 0, 0, 0); - } - else if (ci->saber[0].model[0]) - { + } else if (ci->saber[0].model[0]) { trap->G2API_InitGhoul2Model(&saberEnt->ghoul2, ci->saber[0].model, 0, 0, 0, 0, 0); - } - else - { + } else { trap->G2API_InitGhoul2Model(&saberEnt->ghoul2, DEFAULT_SABER_MODEL, 0, 0, 0, 0, 0); } - //trap->G2API_DuplicateGhoul2Instance(cent->ghoul2, &saberEnt->ghoul2); + // trap->G2API_DuplicateGhoul2Instance(cent->ghoul2, &saberEnt->ghoul2); - if (saberEnt->ghoul2) - { + if (saberEnt->ghoul2) { addBolts = qtrue; - //cent->bolt4 = 2; + // cent->bolt4 = 2; VectorCopy(saberEnt->currentState.pos.trBase, saberEnt->lerpOrigin); VectorCopy(saberEnt->currentState.apos.trBase, saberEnt->lerpAngles); @@ -10134,32 +8567,26 @@ void CG_Player( centity_t *cent ) { } } - if (addBolts) - { + if (addBolts) { int m = 0; int tagBolt; char *tagName; - while (m < ci->saber[0].numBlades) - { - tagName = va("*blade%i", m+1); + while (m < ci->saber[0].numBlades) { + tagName = va("*blade%i", m + 1); tagBolt = trap->G2API_AddBolt(saberEnt->ghoul2, 0, tagName); - if (tagBolt == -1) - { - if (m == 0) - { //guess this is an 0ldsk3wl saber + if (tagBolt == -1) { + if (m == 0) { // guess this is an 0ldsk3wl saber tagBolt = trap->G2API_AddBolt(saberEnt->ghoul2, 0, "*flash"); - if (tagBolt == -1) - { + if (tagBolt == -1) { assert(0); } break; } - if (tagBolt == -1) - { + if (tagBolt == -1) { assert(0); break; } @@ -10178,8 +8605,7 @@ void CG_Player( centity_t *cent ) { } }*/ - if (saberEnt && saberEnt->ghoul2 /*&& cent->bolt4 == 2*/) - { + if (saberEnt && saberEnt->ghoul2 /*&& cent->bolt4 == 2*/) { vec3_t bladeAngles; vec3_t tAng; vec3_t efOrg; @@ -10188,28 +8614,21 @@ void CG_Player( centity_t *cent ) { int l = 0; addspriteArgStruct_t fxSArgs; - if (!cent->bolt2) - { + if (!cent->bolt2) { cent->bolt2 = cg.time; } - if (cent->bolt3 != 90) - { - if (cent->bolt3 < 90) - { - cent->bolt3 += (cg.time - cent->bolt2)*0.5; + if (cent->bolt3 != 90) { + if (cent->bolt3 < 90) { + cent->bolt3 += (cg.time - cent->bolt2) * 0.5; - if (cent->bolt3 > 90) - { + if (cent->bolt3 > 90) { cent->bolt3 = 90; } - } - else if (cent->bolt3 > 90) - { - cent->bolt3 -= (cg.time - cent->bolt2)*0.5; + } else if (cent->bolt3 > 90) { + cent->bolt3 -= (cg.time - cent->bolt2) * 0.5; - if (cent->bolt3 < 90) - { + if (cent->bolt3 < 90) { cent->bolt3 = 90; } } @@ -10220,11 +8639,8 @@ void CG_Player( centity_t *cent ) { saberEnt->currentState.apos.trBase[0] = cent->bolt3; saberEnt->lerpAngles[0] = cent->bolt3; - if (!saberEnt->currentState.saberInFlight && saberEnt->currentState.bolt2 != 123) - { //owner is pulling is back - if ( !(ci->saber[0].saberFlags&SFL_RETURN_DAMAGE) - || cent->currentState.saberHolstered ) - { + if (!saberEnt->currentState.saberInFlight && saberEnt->currentState.bolt2 != 123) { // owner is pulling is back + if (!(ci->saber[0].saberFlags & SFL_RETURN_DAMAGE) || cent->currentState.saberHolstered) { vec3_t owndir; VectorSubtract(saberEnt->lerpOrigin, cent->lerpOrigin, owndir); @@ -10240,11 +8656,12 @@ void CG_Player( centity_t *cent ) { } } - //We don't actually want to rely entirely on server updates to render the position of the saber, because we actually know generally where - //it's going to be before the first position update even gets here, and it needs to start getting rendered the instant the saber model is - //removed from the player hand. So we'll just render it manually and let normal rendering for the entity be ignored. - if (!saberEnt->currentState.saberInFlight && saberEnt->currentState.bolt2 != 123) - { //tell it that we're a saber and to render the glow around our handle because we're being pulled back + // We don't actually want to rely entirely on server updates to render the position of the saber, because we actually know generally where + // it's going to be before the first position update even gets here, and it needs to start getting rendered the instant the saber model is + // removed from the player hand. So we'll just render it manually and let normal rendering for the entity be ignored. + if (!saberEnt->currentState.saberInFlight && + saberEnt->currentState.bolt2 != + 123) { // tell it that we're a saber and to render the glow around our handle because we're being pulled back saberEnt->bolt3 = 999; } @@ -10256,63 +8673,53 @@ void CG_Player( centity_t *cent ) { VectorCopy(saberEnt->lerpAngles, bladeAngles); bladeAngles[ROLL] = 0; - if ( ci->saber[0].numBlades > 1//staff - && cent->currentState.saberHolstered == 1 )//extra blades off - {//only first blade should be on + if (ci->saber[0].numBlades > 1 // staff + && cent->currentState.saberHolstered == 1) // extra blades off + { // only first blade should be on BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[0], -1, 0); - } - else - { + } else { BG_SI_SetDesiredLength(&ci->saber[0], -1, -1); } - if ( ci->saber[1].model[0] //dual sabers - && cent->currentState.saberHolstered == 1 )//second one off + if (ci->saber[1].model[0] // dual sabers + && cent->currentState.saberHolstered == 1) // second one off { BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); - } - else - { + } else { BG_SI_SetDesiredLength(&ci->saber[1], -1, -1); } - //while (l < MAX_SABERS) - //Only want to do for the first saber actually, it's the one in flight. - while (l < 1) - { - if (!ci->saber[l].model[0]) - { + // while (l < MAX_SABERS) + // Only want to do for the first saber actually, it's the one in flight. + while (l < 1) { + if (!ci->saber[l].model[0]) { break; } k = 0; - while (k < ci->saber[l].numBlades) - { - if ( //cent->currentState.fireflag == SS_STAFF&& //in saberstaff style - l == 0//first saber - && cent->currentState.saberHolstered == 1 //extra blades should be off - && k > 0 )//this is an extra blade - {//extra blades off - //don't draw them + while (k < ci->saber[l].numBlades) { + if ( // cent->currentState.fireflag == SS_STAFF&& //in saberstaff style + l == 0 // first saber + && cent->currentState.saberHolstered == 1 // extra blades should be off + && k > 0) // this is an extra blade + { // extra blades off + // don't draw them CG_AddSaberBlade(cent, saberEnt, NULL, 0, 0, l, k, saberEnt->lerpOrigin, bladeAngles, qtrue, qtrue); - } - else - { + } else { CG_AddSaberBlade(cent, saberEnt, NULL, 0, 0, l, k, saberEnt->lerpOrigin, bladeAngles, qtrue, qfalse); } k++; } - if ( ci->saber[l].numBlades > 2 ) - {//add a single glow for the saber based on all the blade colors combined - CG_DoSaberLight( &ci->saber[l] ); + if (ci->saber[l].numBlades > 2) { // add a single glow for the saber based on all the blade colors combined + CG_DoSaberLight(&ci->saber[l]); } l++; } - //Make the player's hand glow while guiding the saber - VectorSet( tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL] ); + // Make the player's hand glow while guiding the saber + VectorSet(tAng, cent->turAngles[PITCH], cent->turAngles[YAW], cent->turAngles[ROLL]); trap->G2API_GetBoltMatrix(cent->ghoul2, 0, ci->bolt_rhand, &boltMatrix, tAng, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale); @@ -10320,9 +8727,9 @@ void CG_Player( centity_t *cent ) { efOrg[1] = boltMatrix.matrix[1][3]; efOrg[2] = boltMatrix.matrix[2][3]; - wv = sin( cg.time * 0.003f ) * 0.08f + 0.1f; + wv = sin(cg.time * 0.003f) * 0.08f + 0.1f; - //trap->FX_AddSprite( NULL, efOrg, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); + // trap->FX_AddSprite( NULL, efOrg, NULL, NULL, 8.0f, 8.0f, wv, wv, 0.0f, 0.0f, 1.0f, cgs.media.yellowSaberGlowShader, 0x08000000 ); VectorCopy(efOrg, fxSArgs.origin); VectorClear(fxSArgs.vel); VectorClear(fxSArgs.accel); @@ -10337,47 +8744,39 @@ void CG_Player( centity_t *cent ) { fxSArgs.flags = 0x08000000; trap->FX_AddSprite(&fxSArgs); } - } - else - { - if ( ci->saber[0].numBlades > 1//staff - && cent->currentState.saberHolstered == 1 )//extra blades off - {//only first blade should be on + } else { + if (ci->saber[0].numBlades > 1 // staff + && cent->currentState.saberHolstered == 1) // extra blades off + { // only first blade should be on BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[0], -1, 0); - } - else - { + } else { BG_SI_SetDesiredLength(&ci->saber[0], -1, -1); } - if ( ci->saber[1].model[0] //dual sabers - && cent->currentState.saberHolstered == 1 )//second one off + if (ci->saber[1].model[0] // dual sabers + && cent->currentState.saberHolstered == 1) // second one off { BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); - } - else - { + } else { BG_SI_SetDesiredLength(&ci->saber[1], -1, -1); } } - //If the arm the saber is in is broken, turn it off. + // If the arm the saber is in is broken, turn it off. /* if (cent->currentState.brokenLimbs & (1 << BROKENLIMB_RARM)) { BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); } */ - //Leaving right arm on, at least for now. - if (cent->currentState.brokenLimbs & (1 << BROKENLIMB_LARM)) - { + // Leaving right arm on, at least for now. + if (cent->currentState.brokenLimbs & (1 << BROKENLIMB_LARM)) { BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); } - if (!cent->currentState.saberEntityNum) - { + if (!cent->currentState.saberEntityNum) { BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); - //BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); + // BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); } /* else @@ -10387,18 +8786,14 @@ void CG_Player( centity_t *cent ) { } */ drawPlayerSaber = qtrue; - } - else if (cent->currentState.weapon == WP_SABER) - { - //cent->saberLength = 0; + } else if (cent->currentState.weapon == WP_SABER) { + // cent->saberLength = 0; BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); drawPlayerSaber = qtrue; - } - else - { - //cent->saberLength = 0; + } else { + // cent->saberLength = 0; BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); @@ -10407,38 +8802,30 @@ void CG_Player( centity_t *cent ) { } #ifdef _RAG_BOLT_TESTING - if (cent->currentState.eFlags & EF_RAG) - { + if (cent->currentState.eFlags & EF_RAG) { CG_TempTestFunction(cent, cent->turAngles); } #endif - if (cent->currentState.weapon == WP_SABER) - { + if (cent->currentState.weapon == WP_SABER) { BG_SI_SetLengthGradual(&ci->saber[0], cg.time); BG_SI_SetLengthGradual(&ci->saber[1], cg.time); } - if (drawPlayerSaber) - { + if (drawPlayerSaber) { centity_t *saberEnt; int k = 0; int l = 0; - if (!cent->currentState.saberEntityNum) - { - l = 1; //The "primary" saber is missing or in flight or something, so only try to draw in the second one - } - else if (!cent->currentState.saberInFlight) - { + if (!cent->currentState.saberEntityNum) { + l = 1; // The "primary" saber is missing or in flight or something, so only try to draw in the second one + } else if (!cent->currentState.saberInFlight) { saberEnt = &cg_entities[cent->currentState.saberEntityNum]; - if (/*cent->bolt4 && */!g2HasWeapon) - { + if (/*cent->bolt4 && */ !g2HasWeapon) { trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, WP_SABER), 0, cent->ghoul2, 1); - if (saberEnt && saberEnt->ghoul2) - { + if (saberEnt && saberEnt->ghoul2) { trap->G2API_CleanGhoul2Models(&(saberEnt->ghoul2)); } @@ -10449,24 +8836,19 @@ void CG_Player( centity_t *cent ) { cent->bolt3 = 0; cent->bolt2 = 0; - } - else - { - l = 1; //The "primary" saber is missing or in flight or something, so only try to draw in the second one + } else { + l = 1; // The "primary" saber is missing or in flight or something, so only try to draw in the second one } - while (l < MAX_SABERS) - { + while (l < MAX_SABERS) { k = 0; - if (!ci->saber[l].model[0]) - { + if (!ci->saber[l].model[0]) { break; } - if (cent->currentState.eFlags2&EF2_HELD_BY_MONSTER) - { - //vectoangles(legs.axis[0], rootAngles); + if (cent->currentState.eFlags2 & EF2_HELD_BY_MONSTER) { + // vectoangles(legs.axis[0], rootAngles); #if 0 if ( cent->currentState.hasLookTarget )//NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... { @@ -10490,46 +8872,39 @@ void CG_Player( centity_t *cent ) { #endif } - while (k < ci->saber[l].numBlades) - { - if ( //cent->currentState.fireflag == SS_STAFF&& //in saberstaff style - cent->currentState.saberHolstered == 1 //extra blades should be off - && k > 0 //this is an extra blade - && ci->saber[l].blade[k].length <= 0 )//it's completely off - {//extra blades off - //don't draw them - CG_AddSaberBlade( cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qtrue); - } - else if ( ci->saber[1].model[0]//we have a second saber - && cent->currentState.saberHolstered == 1 //it should be off - && l > 0//and this is the second one - && ci->saber[l].blade[k].length <= 0 )//it's completely off - {//second saber is turned off and this blade is done with turning off - CG_AddSaberBlade( cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qtrue); - } - else - { - CG_AddSaberBlade( cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qfalse); + while (k < ci->saber[l].numBlades) { + if ( // cent->currentState.fireflag == SS_STAFF&& //in saberstaff style + cent->currentState.saberHolstered == 1 // extra blades should be off + && k > 0 // this is an extra blade + && ci->saber[l].blade[k].length <= 0) // it's completely off + { // extra blades off + // don't draw them + CG_AddSaberBlade(cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qtrue); + } else if (ci->saber[1].model[0] // we have a second saber + && cent->currentState.saberHolstered == 1 // it should be off + && l > 0 // and this is the second one + && ci->saber[l].blade[k].length <= 0) // it's completely off + { // second saber is turned off and this blade is done with turning off + CG_AddSaberBlade(cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qtrue); + } else { + CG_AddSaberBlade(cent, cent, NULL, 0, 0, l, k, legs.origin, rootAngles, qfalse, qfalse); } k++; } - if ( ci->saber[l].numBlades > 2 ) - {//add a single glow for the saber based on all the blade colors combined - CG_DoSaberLight( &ci->saber[l] ); + if (ci->saber[l].numBlades > 2) { // add a single glow for the saber based on all the blade colors combined + CG_DoSaberLight(&ci->saber[l]); } l++; } } - if (cent->currentState.saberInFlight && !cent->currentState.saberEntityNum) - { //reset the length if the saber is knocked away + if (cent->currentState.saberInFlight && !cent->currentState.saberEntityNum) { // reset the length if the saber is knocked away BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); - if (g2HasWeapon) - { //and remember to kill the bolton model in case we didn't get a thrown saber update first + if (g2HasWeapon) { // and remember to kill the bolton model in case we didn't get a thrown saber update first trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); g2HasWeapon = qfalse; } @@ -10537,60 +8912,50 @@ void CG_Player( centity_t *cent ) { cent->bolt2 = 0; } - if (cent->currentState.eFlags & EF_DEAD) - { - if (cent->ghoul2 && cent->currentState.saberInFlight && g2HasWeapon) - { //special case, kill the saber on a freshly dead player if another source says to. + if (cent->currentState.eFlags & EF_DEAD) { + if (cent->ghoul2 && cent->currentState.saberInFlight && + g2HasWeapon) { // special case, kill the saber on a freshly dead player if another source says to. trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); g2HasWeapon = qfalse; } } - if (iwantout) - { + if (iwantout) { return; - //goto endOfCall; + // goto endOfCall; } - if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number) - { + if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number) { legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 0; legs.renderfx |= RF_MINLIGHT; } - if (cg.snap->ps.duelInProgress /*&& cent->currentState.number != cg.snap->ps.clientNum*/) - { //I guess go ahead and glow your own client too in a duel + if (cg.snap->ps.duelInProgress /*&& cent->currentState.number != cg.snap->ps.clientNum*/) { // I guess go ahead and glow your own client too in a duel if (cent->currentState.number != cg.snap->ps.duelIndex && - cent->currentState.number != cg.snap->ps.clientNum) - { //everyone not involved in the duel is drawn very dark + cent->currentState.number != cg.snap->ps.clientNum) { // everyone not involved in the duel is drawn very dark legs.shaderRGBA[0] /= 5.0f; legs.shaderRGBA[1] /= 5.0f; legs.shaderRGBA[2] /= 5.0f; legs.renderfx |= RF_RGB_TINT; - } - else - { //adjust the glow by how far away you are from your dueling partner + } else { // adjust the glow by how far away you are from your dueling partner centity_t *duelEnt; duelEnt = &cg_entities[cg.snap->ps.duelIndex]; - if (duelEnt) - { + if (duelEnt) { vec3_t vecSub; float subLen = 0; VectorSubtract(duelEnt->lerpOrigin, cg.snap->ps.origin, vecSub); subLen = VectorLength(vecSub); - if (subLen < 1) - { + if (subLen < 1) { subLen = 1; } - if (subLen > 1020) - { + if (subLen > 1020) { subLen = 1020; } @@ -10599,34 +8964,31 @@ void CG_Player( centity_t *cent ) { savRGBA[0] = legs.shaderRGBA[0]; savRGBA[1] = legs.shaderRGBA[1]; savRGBA[2] = legs.shaderRGBA[2]; - legs.shaderRGBA[0] = Q_max(255-subLen/4,1); - legs.shaderRGBA[1] = Q_max(255-subLen/4,1); - legs.shaderRGBA[2] = Q_max(255-subLen/4,1); + legs.shaderRGBA[0] = Q_max(255 - subLen / 4, 1); + legs.shaderRGBA[1] = Q_max(255 - subLen / 4, 1); + legs.shaderRGBA[2] = Q_max(255 - subLen / 4, 1); legs.renderfx &= ~RF_RGB_TINT; legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.customShader = cgs.media.forceShell; - trap->R_AddRefEntityToScene( &legs ); //draw the shell + trap->R_AddRefEntityToScene(&legs); // draw the shell - legs.customShader = 0; //reset to player model + legs.customShader = 0; // reset to player model - legs.shaderRGBA[0] = Q_max(savRGBA[0]-subLen/8,1); - legs.shaderRGBA[1] = Q_max(savRGBA[1]-subLen/8,1); - legs.shaderRGBA[2] = Q_max(savRGBA[2]-subLen/8,1); + legs.shaderRGBA[0] = Q_max(savRGBA[0] - subLen / 8, 1); + legs.shaderRGBA[1] = Q_max(savRGBA[1] - subLen / 8, 1); + legs.shaderRGBA[2] = Q_max(savRGBA[2] - subLen / 8, 1); } - if (subLen <= 1024) - { + if (subLen <= 1024) { legs.renderfx |= RF_RGB_TINT; } } } - } - else - { - if (cent->currentState.bolt1 && !(cent->currentState.eFlags & EF_DEAD) && cent->currentState.number != cg.snap->ps.clientNum && (!cg.snap->ps.duelInProgress || cg.snap->ps.duelIndex != cent->currentState.number)) - { + } else { + if (cent->currentState.bolt1 && !(cent->currentState.eFlags & EF_DEAD) && cent->currentState.number != cg.snap->ps.clientNum && + (!cg.snap->ps.duelInProgress || cg.snap->ps.duelIndex != cent->currentState.number)) { legs.shaderRGBA[0] = 50; legs.shaderRGBA[1] = 50; legs.shaderRGBA[2] = 50; @@ -10634,101 +8996,77 @@ void CG_Player( centity_t *cent ) { } } - if (cent->currentState.eFlags & EF_DISINTEGRATION) - { - if (!cent->dustTrailTime) - { + if (cent->currentState.eFlags & EF_DISINTEGRATION) { + if (!cent->dustTrailTime) { cent->dustTrailTime = cg.time; cent->miscTime = legs.frame; } - if ((cg.time - cent->dustTrailTime) > 1500) - { //avoid rendering the entity after disintegration has finished anyway - //goto endOfCall; + if ((cg.time - cent->dustTrailTime) > 1500) { // avoid rendering the entity after disintegration has finished anyway + // goto endOfCall; return; } trap->G2API_SetBoneAnim(legs.ghoul2, 0, "model_root", cent->miscTime, cent->miscTime, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->miscTime, -1); - if (!cent->noLumbar) - { - trap->G2API_SetBoneAnim(legs.ghoul2, 0, "lower_lumbar", cent->miscTime, cent->miscTime, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->miscTime, -1); + if (!cent->noLumbar) { + trap->G2API_SetBoneAnim(legs.ghoul2, 0, "lower_lumbar", cent->miscTime, cent->miscTime, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->miscTime, + -1); - if (cent->localAnimIndex <= 1) - { + if (cent->localAnimIndex <= 1) { trap->G2API_SetBoneAnim(legs.ghoul2, 0, "Motion", cent->miscTime, cent->miscTime, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->miscTime, -1); } } CG_Disintegration(cent, &legs); - //goto endOfCall; + // goto endOfCall; return; - } - else - { + } else { cent->dustTrailTime = 0; cent->miscTime = 0; } - if (cent->currentState.powerups & (1 << PW_CLOAKED)) - { - if (!cent->cloaked) - { + if (cent->currentState.powerups & (1 << PW_CLOAKED)) { + if (!cent->cloaked) { cent->cloaked = qtrue; cent->uncloaking = cg.time + 2000; } - } - else if (cent->cloaked) - { + } else if (cent->cloaked) { cent->cloaked = qfalse; cent->uncloaking = cg.time + 2000; } - if (cent->uncloaking > cg.time) - {//in the middle of cloaking - if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number) - {//just draw him - trap->R_AddRefEntityToScene( &legs ); - } - else - { + if (cent->uncloaking > cg.time) { // in the middle of cloaking + if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number) { // just draw him + trap->R_AddRefEntityToScene(&legs); + } else { float perc = (float)(cent->uncloaking - cg.time) / 2000.0f; - if (( cent->currentState.powerups & ( 1 << PW_CLOAKED ))) - {//actually cloaking, so reverse it + if ((cent->currentState.powerups & (1 << PW_CLOAKED))) { // actually cloaking, so reverse it perc = 1.0f - perc; } - if ( perc >= 0.0f && perc <= 1.0f ) - { + if (perc >= 0.0f && perc <= 1.0f) { legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.renderfx |= RF_RGB_TINT; legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = 255.0f * perc; legs.shaderRGBA[3] = 0; legs.customShader = cgs.media.cloakedShader; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = 255; legs.shaderRGBA[3] = 255 * (1.0f - perc); // let model alpha in - legs.customShader = 0; // use regular skin + legs.customShader = 0; // use regular skin legs.renderfx &= ~RF_RGB_TINT; legs.renderfx |= RF_FORCE_ENT_ALPHA; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } } - } - else if (( cent->currentState.powerups & ( 1 << PW_CLOAKED ))) - {//fully cloaked - if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) - && cg.snap->ps.clientNum != cent->currentState.number) - {//just draw him - trap->R_AddRefEntityToScene( &legs ); - } - else - { - if (cg.renderingThirdPerson || cent->currentState.number != cg.predictedPlayerState.clientNum) - { + } else if ((cent->currentState.powerups & (1 << PW_CLOAKED))) { // fully cloaked + if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number) { // just draw him + trap->R_AddRefEntityToScene(&legs); + } else { + if (cg.renderingThirdPerson || cent->currentState.number != cg.predictedPlayerState.clientNum) { /* legs.renderfx = 0;//&= ~(RF_RGB_TINT|RF_ALPHA_FADE); legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = legs.shaderRGBA[3] = 255; @@ -10757,58 +9095,49 @@ void CG_Player( centity_t *cent ) { ScaleModelAxis(&legs); */ - if (cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4 && cg_renderToTextureFX.integer) - { - trap->R_SetRefractionProperties(1.0f, 0.0f, qfalse, qfalse); //don't need to do this every frame.. but.. - legs.customShader = 2; //crazy "refractive" shader - trap->R_AddRefEntityToScene( &legs ); + if (cg_shadows.integer != 2 && cgs.glconfig.stencilBits >= 4 && cg_renderToTextureFX.integer) { + trap->R_SetRefractionProperties(1.0f, 0.0f, qfalse, qfalse); // don't need to do this every frame.. but.. + legs.customShader = 2; // crazy "refractive" shader + trap->R_AddRefEntityToScene(&legs); legs.customShader = 0; - } - else - { //stencil buffer's in use, sorry - legs.renderfx = 0;//&= ~(RF_RGB_TINT|RF_ALPHA_FADE); + } else { // stencil buffer's in use, sorry + legs.renderfx = 0; //&= ~(RF_RGB_TINT|RF_ALPHA_FADE); legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = legs.shaderRGBA[3] = 255; legs.customShader = cgs.media.cloakedShader; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); legs.customShader = 0; } } } } - if (!(cent->currentState.powerups & (1 << PW_CLOAKED))) - { //don't add the normal model if cloaked - CG_CheckThirdPersonAlpha( cent, &legs ); + if (!(cent->currentState.powerups & (1 << PW_CLOAKED))) { // don't add the normal model if cloaked + CG_CheckThirdPersonAlpha(cent, &legs); trap->R_AddRefEntityToScene(&legs); } - //cent->frame_minus2 = cent->frame_minus1; + // cent->frame_minus2 = cent->frame_minus1; VectorCopy(cent->frame_minus1, cent->frame_minus2); - if (cent->frame_minus1_refreshed) - { + if (cent->frame_minus1_refreshed) { cent->frame_minus2_refreshed = 1; } - //cent->frame_minus1 = legs; + // cent->frame_minus1 = legs; VectorCopy(legs.origin, cent->frame_minus1); cent->frame_minus1_refreshed = 1; - if (!cent->frame_hold_refreshed && (cent->currentState.powerups & (1 << PW_SPEEDBURST))) - { + if (!cent->frame_hold_refreshed && (cent->currentState.powerups & (1 << PW_SPEEDBURST))) { cent->frame_hold_time = cg.time + 254; } - if (cent->frame_hold_time >= cg.time) - { + if (cent->frame_hold_time >= cg.time) { refEntity_t reframe_hold; - if (!cent->frame_hold_refreshed) - { //We're taking the ghoul2 instance from the original refent and duplicating it onto our refent alias so that we can then freeze the frame and fade it for the effect - if (cent->frame_hold && trap->G2_HaveWeGhoul2Models(cent->frame_hold) && - cent->frame_hold != cent->ghoul2) - { + if (!cent->frame_hold_refreshed) { // We're taking the ghoul2 instance from the original refent and duplicating it onto our refent alias so that we can + // then freeze the frame and fade it for the effect + if (cent->frame_hold && trap->G2_HaveWeGhoul2Models(cent->frame_hold) && cent->frame_hold != cent->ghoul2) { trap->G2API_CleanGhoul2Models(&(cent->frame_hold)); } reframe_hold = legs; @@ -10817,49 +9146,41 @@ void CG_Player( centity_t *cent ) { trap->G2API_DuplicateGhoul2Instance(cent->ghoul2, ¢->frame_hold); - //Set the animation to the current frame and freeze on end - //trap->G2API_SetBoneAnim(cent->frame_hold.ghoul2, 0, "model_root", cent->frame_hold.frame, cent->frame_hold.frame, BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->frame_hold.frame, -1); + // Set the animation to the current frame and freeze on end + // trap->G2API_SetBoneAnim(cent->frame_hold.ghoul2, 0, "model_root", cent->frame_hold.frame, cent->frame_hold.frame, + // BONE_ANIM_OVERRIDE_FREEZE, 1.0f, cg.time, cent->frame_hold.frame, -1); trap->G2API_SetBoneAnim(cent->frame_hold, 0, "model_root", legs.frame, legs.frame, 0, 1.0f, cg.time, legs.frame, -1); - } - else - { + } else { reframe_hold = legs; reframe_hold.ghoul2 = cent->frame_hold; } reframe_hold.renderfx |= RF_FORCE_ENT_ALPHA; reframe_hold.shaderRGBA[3] = (cent->frame_hold_time - cg.time); - if (reframe_hold.shaderRGBA[3] > 254) - { + if (reframe_hold.shaderRGBA[3] > 254) { reframe_hold.shaderRGBA[3] = 254; } - if (reframe_hold.shaderRGBA[3] < 1) - { + if (reframe_hold.shaderRGBA[3] < 1) { reframe_hold.shaderRGBA[3] = 1; } reframe_hold.ghoul2 = cent->frame_hold; trap->R_AddRefEntityToScene(&reframe_hold); - } - else - { + } else { cent->frame_hold_refreshed = 0; } // // add the gun / barrel / flash // - if (cent->currentState.weapon != WP_EMPLACED_GUN) - { - CG_AddPlayerWeapon( &legs, NULL, cent, ci->team, rootAngles, qtrue ); + if (cent->currentState.weapon != WP_EMPLACED_GUN) { + CG_AddPlayerWeapon(&legs, NULL, cent, ci->team, rootAngles, qtrue); } // add powerups floating behind the player - CG_PlayerPowerups( cent, &legs ); + CG_PlayerPowerups(cent, &legs); - if ((cent->currentState.forcePowersActive & (1 << FP_RAGE)) && - (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) - { - //legs.customShader = cgs.media.rageShader; + if ((cent->currentState.forcePowersActive & (1 << FP_RAGE)) && (cg.renderingThirdPerson || cent->currentState.number != cg.snap->ps.clientNum)) { + // legs.customShader = cgs.media.rageShader; legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.renderfx &= ~RF_MINLIGHT; @@ -10868,20 +9189,17 @@ void CG_Player( centity_t *cent ) { legs.shaderRGBA[1] = legs.shaderRGBA[2] = 0; legs.shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { legs.customShader = cgs.media.electricBodyShader; - } - else - { + } else { legs.customShader = cgs.media.electricBody2Shader; } trap->R_AddRefEntityToScene(&legs); } - if (!cg.snap->ps.duelInProgress && cent->currentState.bolt1 && !(cent->currentState.eFlags & EF_DEAD) && cent->currentState.number != cg.snap->ps.clientNum && (!cg.snap->ps.duelInProgress || cg.snap->ps.duelIndex != cent->currentState.number)) - { + if (!cg.snap->ps.duelInProgress && cent->currentState.bolt1 && !(cent->currentState.eFlags & EF_DEAD) && + cent->currentState.number != cg.snap->ps.clientNum && (!cg.snap->ps.duelInProgress || cg.snap->ps.duelIndex != cent->currentState.number)) { legs.shaderRGBA[0] = 50; legs.shaderRGBA[1] = 50; legs.shaderRGBA[2] = 255; @@ -10890,42 +9208,36 @@ void CG_Player( centity_t *cent ) { legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.customShader = cgs.media.forceSightBubble; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } - if ( CG_VehicleShouldDrawShields( cent ) //vehicle - || (checkDroidShields && CG_VehicleShouldDrawShields( &cg_entities[cent->currentState.m_iVehicleNum] )) )//droid in vehicle - {//Vehicles have form-fitting shields + if (CG_VehicleShouldDrawShields(cent) // vehicle + || (checkDroidShields && CG_VehicleShouldDrawShields(&cg_entities[cent->currentState.m_iVehicleNum]))) // droid in vehicle + { // Vehicles have form-fitting shields Vehicle_t *pVeh = cent->m_pVehicle; - if ( checkDroidShields ) - { + if (checkDroidShields) { pVeh = cg_entities[cent->currentState.m_iVehicleNum].m_pVehicle; } legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 255; - legs.shaderRGBA[3] = 10.0f+(sin((float)(cg.time/4))*128.0f);//112.0 * ((cent->damageTime - cg.time) / MIN_SHIELD_TIME) + Q_flrand(0.0f, 1.0f)*16; + legs.shaderRGBA[3] = 10.0f + (sin((float)(cg.time / 4)) * 128.0f); // 112.0 * ((cent->damageTime - cg.time) / MIN_SHIELD_TIME) + + // Q_flrand(0.0f, 1.0f)*16; legs.renderfx &= ~RF_RGB_TINT; legs.renderfx &= ~RF_FORCE_ENT_ALPHA; - if ( pVeh - && pVeh->m_pVehicleInfo - && pVeh->m_pVehicleInfo->shieldShaderHandle ) - {//use the vehicle-specific shader + if (pVeh && pVeh->m_pVehicleInfo && pVeh->m_pVehicleInfo->shieldShaderHandle) { // use the vehicle-specific shader legs.customShader = pVeh->m_pVehicleInfo->shieldShaderHandle; - } - else - { + } else { legs.customShader = cgs.media.playerShieldDamage; } - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } - //For now, these two are using the old shield shader. This is just so that you - //can tell it apart from the JM/duel shaders, but it's still very obvious. - if (cent->currentState.forcePowersActive & (1 << FP_PROTECT)) - { //aborb is represented by green.. + // For now, these two are using the old shield shader. This is just so that you + // can tell it apart from the JM/duel shaders, but it's still very obvious. + if (cent->currentState.forcePowersActive & (1 << FP_PROTECT)) { // aborb is represented by green.. refEntity_t prot; memcpy(&prot, &legs, sizeof(prot)); @@ -10949,15 +9261,14 @@ void CG_Player( centity_t *cent ) { ScaleModelAxis(&prot); */ - trap->R_AddRefEntityToScene( &prot ); + trap->R_AddRefEntityToScene(&prot); } - //if (cent->currentState.forcePowersActive & (1 << FP_ABSORB)) - //Showing only when the power has been active (absorbed something) recently now, instead of always. - //AND - //always show if it is you with the absorb on - if ((cent->currentState.number == cg.predictedPlayerState.clientNum && (cg.predictedPlayerState.fd.forcePowersActive & (1<teamPowerEffectTime > cg.time && cent->teamPowerType == 3)) - { //aborb is represented by blue.. + // if (cent->currentState.forcePowersActive & (1 << FP_ABSORB)) + // Showing only when the power has been active (absorbed something) recently now, instead of always. + // AND + // always show if it is you with the absorb on + if ((cent->currentState.number == cg.predictedPlayerState.clientNum && (cg.predictedPlayerState.fd.forcePowersActive & (1 << FP_ABSORB))) || + (cent->teamPowerEffectTime > cg.time && cent->teamPowerType == 3)) { // aborb is represented by blue.. legs.shaderRGBA[0] = 0; legs.shaderRGBA[1] = 0; legs.shaderRGBA[2] = 255; @@ -10967,11 +9278,10 @@ void CG_Player( centity_t *cent ) { legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.customShader = cgs.media.playerShieldDamage; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } - if (cent->currentState.isJediMaster && cg.snap->ps.clientNum != cent->currentState.number) - { + if (cent->currentState.isJediMaster && cg.snap->ps.clientNum != cent->currentState.number) { legs.shaderRGBA[0] = 100; legs.shaderRGBA[1] = 100; legs.shaderRGBA[2] = 255; @@ -10981,38 +9291,28 @@ void CG_Player( centity_t *cent ) { legs.renderfx |= RF_NODEPTH; legs.customShader = cgs.media.forceShell; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); legs.renderfx &= ~RF_NODEPTH; } - if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && cg_auraShell.integer) - { - if (cgs.gametype == GT_SIEGE) - { // A team game - if ( ci->team == TEAM_SPECTATOR || ci->team == TEAM_FREE ) - {//yellow + if ((cg.snap->ps.fd.forcePowersActive & (1 << FP_SEE)) && cg.snap->ps.clientNum != cent->currentState.number && cg_auraShell.integer) { + if (cgs.gametype == GT_SIEGE) { // A team game + if (ci->team == TEAM_SPECTATOR || ci->team == TEAM_FREE) { // yellow legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 0; - } - else if ( ci->team != cgs.clientinfo[cg.snap->ps.clientNum].team ) - {//red + } else if (ci->team != cgs.clientinfo[cg.snap->ps.clientNum].team) { // red legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 50; legs.shaderRGBA[2] = 50; - } - else - {//green + } else { // green legs.shaderRGBA[0] = 50; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 50; } - } - else if (cgs.gametype >= GT_TEAM) - { // A team game - switch(ci->team) - { + } else if (cgs.gametype >= GT_TEAM) { // A team game + switch (ci->team) { case TEAM_RED: legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 50; @@ -11030,24 +9330,22 @@ void CG_Player( centity_t *cent ) { legs.shaderRGBA[2] = 0; break; } - } - else - { // Not a team game + } else { // Not a team game legs.shaderRGBA[0] = 255; legs.shaderRGBA[1] = 255; legs.shaderRGBA[2] = 0; } -/* if (cg.snap->ps.fd.forcePowerLevel[FP_SEE] <= FORCE_LEVEL_1) - { - legs.renderfx |= RF_MINLIGHT; - } - else -*/ { // See through walls. + /* if (cg.snap->ps.fd.forcePowerLevel[FP_SEE] <= FORCE_LEVEL_1) + { + legs.renderfx |= RF_MINLIGHT; + } + else + */ + { // See through walls. legs.renderfx |= RF_MINLIGHT | RF_NODEPTH; - if (cg.snap->ps.fd.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) - { //only level 2+ can see players through walls + if (cg.snap->ps.fd.forcePowerLevel[FP_SEE] < FORCE_LEVEL_2) { // only level 2+ can see players through walls legs.renderfx &= ~RF_NODEPTH; } } @@ -11056,24 +9354,21 @@ void CG_Player( centity_t *cent ) { legs.renderfx &= ~RF_FORCE_ENT_ALPHA; legs.customShader = cgs.media.sightShell; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } // Electricity //------------------------------------------------ - if ( cent->currentState.emplacedOwner > cg.time ) - { - int dif = cent->currentState.emplacedOwner - cg.time; + if (cent->currentState.emplacedOwner > cg.time) { + int dif = cent->currentState.emplacedOwner - cg.time; vec3_t tempAngles; - if ( dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f ) - { + if (dif > 0 && Q_flrand(0.0f, 1.0f) > 0.4f) { // fade out over the last 500 ms int brightness = 255; - if ( dif < 500 ) - { - brightness = floor((dif - 500.0f) / 500.0f * 255.0f ); + if (dif < 500) { + brightness = floor((dif - 500.0f) / 500.0f * 255.0f); } legs.renderfx &= ~RF_FORCE_ENT_ALPHA; @@ -11083,27 +9378,23 @@ void CG_Player( centity_t *cent ) { legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = brightness; legs.shaderRGBA[3] = 255; - if ( rand() & 1 ) - { + if (rand() & 1) { legs.customShader = cgs.media.electricBodyShader; - } - else - { + } else { legs.customShader = cgs.media.electricBody2Shader; } - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); - if ( Q_flrand(0.0f, 1.0f) > 0.9f ) - trap->S_StartSound ( NULL, cent->currentState.number, CHAN_AUTO, cgs.media.crackleSound ); + if (Q_flrand(0.0f, 1.0f) > 0.9f) + trap->S_StartSound(NULL, cent->currentState.number, CHAN_AUTO, cgs.media.crackleSound); } VectorSet(tempAngles, 0, cent->lerpAngles[YAW], 0); - CG_ForceElectrocution( cent, legs.origin, tempAngles, cgs.media.boltShader, qfalse ); + CG_ForceElectrocution(cent, legs.origin, tempAngles, cgs.media.boltShader, qfalse); } - if (cent->currentState.powerups & (1 << PW_SHIELDHIT)) - { + if (cent->currentState.powerups & (1 << PW_SHIELDHIT)) { /* legs.shaderRGBA[0] = legs.shaderRGBA[1] = legs.shaderRGBA[2] = 255.0f * 0.5f;//t; legs.shaderRGBA[3] = 255; @@ -11118,7 +9409,7 @@ void CG_Player( centity_t *cent ) { legs.renderfx &= ~RF_RGB_TINT; legs.customShader = cgs.media.playerShieldDamage; - trap->R_AddRefEntityToScene( &legs ); + trap->R_AddRefEntityToScene(&legs); } #if 0 endOfCall: @@ -11134,7 +9425,6 @@ void CG_Player( centity_t *cent ) { #endif } - //===================================================================== /* @@ -11144,33 +9434,25 @@ CG_ResetPlayerEntity A player just came into view or teleported, so reset all animation info =============== */ -void CG_ResetPlayerEntity( centity_t *cent ) -{ +void CG_ResetPlayerEntity(centity_t *cent) { clientInfo_t *ci; int i = 0; int j = 0; -// cent->errorTime = -99999; // guarantee no error decay added -// cent->extrapolated = qfalse; + // cent->errorTime = -99999; // guarantee no error decay added + // cent->extrapolated = qfalse; - if (cent->currentState.eType == ET_NPC) - { - if (cent->currentState.NPC_class == CLASS_VEHICLE && - cent->m_pVehicle && - cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && - cg.predictedPlayerState.m_iVehicleNum && - cent->currentState.number == cg.predictedPlayerState.m_iVehicleNum) - { //holy hackery, batman! - //I don't think this will break anything. But really, do I ever? + if (cent->currentState.eType == ET_NPC) { + if (cent->currentState.NPC_class == CLASS_VEHICLE && cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && + cg.predictedPlayerState.m_iVehicleNum && cent->currentState.number == cg.predictedPlayerState.m_iVehicleNum) { // holy hackery, batman! + // I don't think this will break anything. But really, do I ever? return; } - if (!cent->npcClient) - { - CG_CreateNPCClient(¢->npcClient); //allocate memory for it + if (!cent->npcClient) { + CG_CreateNPCClient(¢->npcClient); // allocate memory for it - if (!cent->npcClient) - { + if (!cent->npcClient) { assert(0); return; } @@ -11183,21 +9465,17 @@ void CG_ResetPlayerEntity( centity_t *cent ) assert(ci); - //just force these guys to be set again, it won't hurt anything if they're - //already set. + // just force these guys to be set again, it won't hurt anything if they're + // already set. cent->npcLocalSurfOff = 0; cent->npcLocalSurfOn = 0; - } - else - { - ci = &cgs.clientinfo[ cent->currentState.clientNum ]; + } else { + ci = &cgs.clientinfo[cent->currentState.clientNum]; } - while (i < MAX_SABERS) - { + while (i < MAX_SABERS) { j = 0; - while (j < ci->saber[i].numBlades) - { + while (j < ci->saber[i].numBlades) { ci->saber[i].blade[j].trail.lastTime = -20000; j++; } @@ -11209,83 +9487,71 @@ void CG_ResetPlayerEntity( centity_t *cent ) ci->facial_aux = 0; ci->superSmoothTime = 0; - //reset lerp origin smooth point + // reset lerp origin smooth point VectorCopy(cent->lerpOrigin, cent->beamEnd); - if (cent->currentState.eType != ET_NPC || - !(cent->currentState.eFlags & EF_DEAD)) - { - CG_ClearLerpFrame( cent, ci, ¢->pe.legs, cent->currentState.legsAnim, qfalse); - CG_ClearLerpFrame( cent, ci, ¢->pe.torso, cent->currentState.torsoAnim, qtrue); + if (cent->currentState.eType != ET_NPC || !(cent->currentState.eFlags & EF_DEAD)) { + CG_ClearLerpFrame(cent, ci, ¢->pe.legs, cent->currentState.legsAnim, qfalse); + CG_ClearLerpFrame(cent, ci, ¢->pe.torso, cent->currentState.torsoAnim, qtrue); - BG_EvaluateTrajectory( ¢->currentState.pos, cg.time, cent->lerpOrigin ); - BG_EvaluateTrajectory( ¢->currentState.apos, cg.time, cent->lerpAngles ); + BG_EvaluateTrajectory(¢->currentState.pos, cg.time, cent->lerpOrigin); + BG_EvaluateTrajectory(¢->currentState.apos, cg.time, cent->lerpAngles); -// VectorCopy( cent->lerpOrigin, cent->rawOrigin ); - VectorCopy( cent->lerpAngles, cent->rawAngles ); + // VectorCopy( cent->lerpOrigin, cent->rawOrigin ); + VectorCopy(cent->lerpAngles, cent->rawAngles); - memset( ¢->pe.legs, 0, sizeof( cent->pe.legs ) ); + memset(¢->pe.legs, 0, sizeof(cent->pe.legs)); cent->pe.legs.yawAngle = cent->rawAngles[YAW]; cent->pe.legs.yawing = qfalse; cent->pe.legs.pitchAngle = 0; cent->pe.legs.pitching = qfalse; - memset( ¢->pe.torso, 0, sizeof( cent->pe.torso ) ); + memset(¢->pe.torso, 0, sizeof(cent->pe.torso)); cent->pe.torso.yawAngle = cent->rawAngles[YAW]; cent->pe.torso.yawing = qfalse; cent->pe.torso.pitchAngle = cent->rawAngles[PITCH]; cent->pe.torso.pitching = qfalse; - if (cent->currentState.eType == ET_NPC) - { //just start them off at 0 pitch + if (cent->currentState.eType == ET_NPC) { // just start them off at 0 pitch cent->pe.torso.pitchAngle = 0; } - if ((cent->ghoul2 == NULL) && ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { + if ((cent->ghoul2 == NULL) && ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { trap->G2API_DuplicateGhoul2Instance(ci->ghoul2Model, ¢->ghoul2); cent->weapon = 0; cent->ghoul2weapon = NULL; - //Attach the instance to this entity num so we can make use of client-server - //shared operations if possible. + // Attach the instance to this entity num so we can make use of client-server + // shared operations if possible. trap->G2API_AttachInstanceToEntNum(cent->ghoul2, cent->currentState.number, qfalse); - if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cent->ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cent->noFace = qtrue; } cent->localAnimIndex = CG_G2SkelForModel(cent->ghoul2); cent->eventAnimIndex = CG_G2EvIndexForModel(cent->ghoul2, cent->localAnimIndex); - //CG_CopyG2WeaponInstance(cent->currentState.weapon, ci->ghoul2Model); - //cent->weapon = cent->currentState.weapon; + // CG_CopyG2WeaponInstance(cent->currentState.weapon, ci->ghoul2Model); + // cent->weapon = cent->currentState.weapon; } } - //do this to prevent us from making a saber unholster sound the first time we enter the pvs - if (cent->currentState.number != cg.predictedPlayerState.clientNum && - cent->currentState.weapon == WP_SABER && - cent->weapon != cent->currentState.weapon) - { + // do this to prevent us from making a saber unholster sound the first time we enter the pvs + if (cent->currentState.number != cg.predictedPlayerState.clientNum && cent->currentState.weapon == WP_SABER && cent->weapon != cent->currentState.weapon) { cent->weapon = cent->currentState.weapon; - if (cent->ghoul2 && ci->ghoul2Model) - { + if (cent->ghoul2 && ci->ghoul2Model) { CG_CopyG2WeaponInstance(cent, cent->currentState.weapon, cent->ghoul2); cent->ghoul2weapon = CG_G2WeaponInstance(cent, cent->currentState.weapon); } - if (!cent->currentState.saberHolstered) - { //if not holstered set length and desired length for both blades to full right now. + if (!cent->currentState.saberHolstered) { // if not holstered set length and desired length for both blades to full right now. BG_SI_SetDesiredLength(&ci->saber[0], 0, -1); BG_SI_SetDesiredLength(&ci->saber[1], 0, -1); i = 0; - while (i < MAX_SABERS) - { + while (i < MAX_SABERS) { j = 0; - while (j < ci->saber[i].numBlades) - { + while (j < ci->saber[i].numBlades) { ci->saber[i].blade[j].length = ci->saber[i].blade[j].lengthMax; j++; } @@ -11294,9 +9560,7 @@ void CG_ResetPlayerEntity( centity_t *cent ) } } - - if ( cg_debugPosition.integer ) { - trap->Print("%i ResetPlayerEntity yaw=%i\n", cent->currentState.number, cent->pe.torso.yawAngle ); + if (cg_debugPosition.integer) { + trap->Print("%i ResetPlayerEntity yaw=%i\n", cent->currentState.number, cent->pe.torso.yawAngle); } } - diff --git a/codemp/cgame/cg_playerstate.c b/codemp/cgame/cg_playerstate.c index 3fa6c36284..b6280cdcef 100644 --- a/codemp/cgame/cg_playerstate.c +++ b/codemp/cgame/cg_playerstate.c @@ -35,7 +35,7 @@ CG_CheckAmmo If the ammo has gone low enough to generate the warning, play a sound ============== */ -void CG_CheckAmmo( void ) { +void CG_CheckAmmo(void) { #if 0 int i; int total; @@ -95,7 +95,7 @@ void CG_CheckAmmo( void ) { trap->S_StartLocalSound( cgs.media.noAmmoSound, CHAN_LOCAL_SOUND ); } #endif - //disabled silly ammo warning stuff for now + // disabled silly ammo warning stuff for now } /* @@ -103,22 +103,22 @@ void CG_CheckAmmo( void ) { CG_DamageFeedback ============== */ -void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { - float left, front, up; - float kick; - int health; - float scale; - vec3_t dir; - vec3_t angles; - float dist; - float yaw, pitch; +void CG_DamageFeedback(int yawByte, int pitchByte, int damage) { + float left, front, up; + float kick; + int health; + float scale; + vec3_t dir; + vec3_t angles; + float dist; + float yaw, pitch; // show the attacking player's head and name in corner cg.attackerTime = cg.time; // the lower on health you are, the greater the view kick will be health = cg.snap->ps.stats[STAT_HEALTH]; - if ( health < 40 ) { + if (health < 40) { scale = 1; } else { scale = 40.0 / health; @@ -131,7 +131,7 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { kick = 10; // if yaw and pitch are both 255, make the damage always centered (falling, etc) - if ( yawByte == 255 && pitchByte == 255 ) { + if (yawByte == 255 && pitchByte == 255) { cg.damageX = 0; cg.damageY = 0; cg.v_dmg_roll = 0; @@ -145,18 +145,18 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { angles[YAW] = yaw; angles[ROLL] = 0; - AngleVectors( angles, dir, NULL, NULL ); - VectorSubtract( vec3_origin, dir, dir ); + AngleVectors(angles, dir, NULL, NULL); + VectorSubtract(vec3_origin, dir, dir); - front = DotProduct (dir, cg.refdef.viewaxis[0] ); - left = DotProduct (dir, cg.refdef.viewaxis[1] ); - up = DotProduct (dir, cg.refdef.viewaxis[2] ); + front = DotProduct(dir, cg.refdef.viewaxis[0]); + left = DotProduct(dir, cg.refdef.viewaxis[1]); + up = DotProduct(dir, cg.refdef.viewaxis[2]); dir[0] = front; dir[1] = left; dir[2] = 0; - dist = VectorLength( dir ); - if ( dist < 0.1 ) { + dist = VectorLength(dir); + if (dist < 0.1) { dist = 0.1f; } @@ -164,7 +164,7 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { cg.v_dmg_pitch = -kick * front; - if ( front <= 0.1 ) { + if (front <= 0.1) { front = 0.1f; } cg.damageX = -left / front; @@ -172,22 +172,22 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { } // clamp the position - if ( cg.damageX > 1.0 ) { + if (cg.damageX > 1.0) { cg.damageX = 1.0; } - if ( cg.damageX < - 1.0 ) { + if (cg.damageX < -1.0) { cg.damageX = -1.0; } - if ( cg.damageY > 1.0 ) { + if (cg.damageY > 1.0) { cg.damageY = 1.0; } - if ( cg.damageY < - 1.0 ) { + if (cg.damageY < -1.0) { cg.damageY = -1.0; } // don't let the screen flashes vary as much - if ( kick > 10 ) { + if (kick > 10) { kick = 10; } cg.damageValue = kick; @@ -195,9 +195,6 @@ void CG_DamageFeedback( int yawByte, int pitchByte, int damage ) { cg.damageTime = cg.snap->serverTime; } - - - /* ================ CG_Respawn @@ -205,7 +202,7 @@ CG_Respawn A respawn happened this snapshot ================ */ -void CG_Respawn( void ) { +void CG_Respawn(void) { // no error decay on player movement cg.thisFrameTeleport = qtrue; @@ -221,35 +218,35 @@ void CG_Respawn( void ) { CG_CheckPlayerstateEvents ============== */ -void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { - int i; - int event; - centity_t *cent; +void CG_CheckPlayerstateEvents(playerState_t *ps, playerState_t *ops) { + int i; + int event; + centity_t *cent; - if ( ps->externalEvent && ps->externalEvent != ops->externalEvent ) { - cent = &cg_entities[ ps->clientNum ]; + if (ps->externalEvent && ps->externalEvent != ops->externalEvent) { + cent = &cg_entities[ps->clientNum]; cent->currentState.event = ps->externalEvent; cent->currentState.eventParm = ps->externalEventParm; - CG_EntityEvent( cent, cent->lerpOrigin ); + CG_EntityEvent(cent, cent->lerpOrigin); } - cent = &cg_entities[ ps->clientNum ]; + cent = &cg_entities[ps->clientNum]; // go through the predictable events buffer - for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) { + for (i = ps->eventSequence - MAX_PS_EVENTS; i < ps->eventSequence; i++) { // if we have a new predictable event - if ( i >= ops->eventSequence + if (i >= ops->eventSequence // or the server told us to play another event instead of a predicted event we already issued // or something the server told us changed our prediction causing a different event - || (i > ops->eventSequence - MAX_PS_EVENTS && ps->events[i & (MAX_PS_EVENTS-1)] != ops->events[i & (MAX_PS_EVENTS-1)]) ) { + || (i > ops->eventSequence - MAX_PS_EVENTS && ps->events[i & (MAX_PS_EVENTS - 1)] != ops->events[i & (MAX_PS_EVENTS - 1)])) { - event = ps->events[ i & (MAX_PS_EVENTS-1) ]; + event = ps->events[i & (MAX_PS_EVENTS - 1)]; cent->currentState.event = event; - cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ]; -//JLF ADDED to hopefully mark events as player event + cent->currentState.eventParm = ps->eventParms[i & (MAX_PS_EVENTS - 1)]; + // JLF ADDED to hopefully mark events as player event cent->playerState = ps; - CG_EntityEvent( cent, cent->lerpOrigin ); + CG_EntityEvent(cent, cent->lerpOrigin); - cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event; + cg.predictableEvents[i & (MAX_PREDICTED_EVENTS - 1)] = event; cg.eventSequence++; } @@ -261,13 +258,13 @@ void CG_CheckPlayerstateEvents( playerState_t *ps, playerState_t *ops ) { CG_CheckChangedPredictableEvents ================== */ -void CG_CheckChangedPredictableEvents( playerState_t *ps ) { +void CG_CheckChangedPredictableEvents(playerState_t *ps) { int i; int event; - centity_t *cent; + centity_t *cent; cent = &cg_entities[ps->clientNum]; - for ( i = ps->eventSequence - MAX_PS_EVENTS ; i < ps->eventSequence ; i++ ) { + for (i = ps->eventSequence - MAX_PS_EVENTS; i < ps->eventSequence; i++) { // if (i >= cg.eventSequence) { continue; @@ -275,16 +272,16 @@ void CG_CheckChangedPredictableEvents( playerState_t *ps ) { // if this event is not further back in than the maximum predictable events we remember if (i > cg.eventSequence - MAX_PREDICTED_EVENTS) { // if the new playerstate event is different from a previously predicted one - if ( ps->events[i & (MAX_PS_EVENTS-1)] != cg.predictableEvents[i & (MAX_PREDICTED_EVENTS-1) ] ) { + if (ps->events[i & (MAX_PS_EVENTS - 1)] != cg.predictableEvents[i & (MAX_PREDICTED_EVENTS - 1)]) { - event = ps->events[ i & (MAX_PS_EVENTS-1) ]; + event = ps->events[i & (MAX_PS_EVENTS - 1)]; cent->currentState.event = event; - cent->currentState.eventParm = ps->eventParms[ i & (MAX_PS_EVENTS-1) ]; - CG_EntityEvent( cent, cent->lerpOrigin ); + cent->currentState.eventParm = ps->eventParms[i & (MAX_PS_EVENTS - 1)]; + CG_EntityEvent(cent, cent->lerpOrigin); - cg.predictableEvents[ i & (MAX_PREDICTED_EVENTS-1) ] = event; + cg.predictableEvents[i & (MAX_PREDICTED_EVENTS - 1)] = event; - if ( cg_showMiss.integer ) { + if (cg_showMiss.integer) { trap->Print("WARNING: changed predicted event\n"); } } @@ -299,7 +296,7 @@ pushReward */ #ifdef JK2AWARDS static void pushReward(sfxHandle_t sfx, qhandle_t shader, int rewardCount) { - if (cg.rewardStack < (MAX_REWARDSTACK-1)) { + if (cg.rewardStack < (MAX_REWARDSTACK - 1)) { cg.rewardStack++; cg.rewardSound[cg.rewardStack] = sfx; cg.rewardShader[cg.rewardStack] = shader; @@ -308,39 +305,36 @@ static void pushReward(sfxHandle_t sfx, qhandle_t shader, int rewardCount) { } #endif -int cgAnnouncerTime = 0; //to prevent announce sounds from playing on top of each other +int cgAnnouncerTime = 0; // to prevent announce sounds from playing on top of each other /* ================== CG_CheckLocalSounds ================== */ -void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) { - int highScore, health, armor, reward; +void CG_CheckLocalSounds(playerState_t *ps, playerState_t *ops) { + int highScore, health, armor, reward; #ifdef JK2AWARDS sfxHandle_t sfx; #endif // don't play the sounds if the player just changed teams - if ( ps->persistant[PERS_TEAM] != ops->persistant[PERS_TEAM] ) { + if (ps->persistant[PERS_TEAM] != ops->persistant[PERS_TEAM]) { return; } // hit changes - if ( ps->persistant[PERS_HITS] > ops->persistant[PERS_HITS] ) { - armor = ps->persistant[PERS_ATTACKEE_ARMOR] & 0xff; + if (ps->persistant[PERS_HITS] > ops->persistant[PERS_HITS]) { + armor = ps->persistant[PERS_ATTACKEE_ARMOR] & 0xff; health = ps->persistant[PERS_ATTACKEE_ARMOR] >> 8; - if (armor > health/2) - { // We also hit shields along the way, so consider them "pierced". -// trap->S_StartLocalSound( cgs.media.shieldPierceSound, CHAN_LOCAL_SOUND ); - } - else - { // Shields didn't really stand in our way. -// trap->S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND ); + if (armor > health / 2) { // We also hit shields along the way, so consider them "pierced". + // trap->S_StartLocalSound( cgs.media.shieldPierceSound, CHAN_LOCAL_SOUND ); + } else { // Shields didn't really stand in our way. + // trap->S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND ); } - //FIXME: Hit sounds? + // FIXME: Hit sounds? /* if (armor > 50 ) { trap->S_StartLocalSound( cgs.media.hitSoundHighArmor, CHAN_LOCAL_SOUND ); @@ -350,24 +344,21 @@ void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) { trap->S_StartLocalSound( cgs.media.hitSound, CHAN_LOCAL_SOUND ); } */ - } else if ( ps->persistant[PERS_HITS] < ops->persistant[PERS_HITS] ) { - //trap->S_StartLocalSound( cgs.media.hitTeamSound, CHAN_LOCAL_SOUND ); + } else if (ps->persistant[PERS_HITS] < ops->persistant[PERS_HITS]) { + // trap->S_StartLocalSound( cgs.media.hitTeamSound, CHAN_LOCAL_SOUND ); } // health changes of more than -3 should make pain sounds - if (cg_oldPainSounds.integer) - { - if ( ps->stats[STAT_HEALTH] < (ops->stats[STAT_HEALTH] - 3)) - { - if ( ps->stats[STAT_HEALTH] > 0 ) - { - CG_PainEvent( &cg_entities[cg.predictedPlayerState.clientNum], ps->stats[STAT_HEALTH] ); + if (cg_oldPainSounds.integer) { + if (ps->stats[STAT_HEALTH] < (ops->stats[STAT_HEALTH] - 3)) { + if (ps->stats[STAT_HEALTH] > 0) { + CG_PainEvent(&cg_entities[cg.predictedPlayerState.clientNum], ps->stats[STAT_HEALTH]); } } } // if we are going into the intermission, don't start any voices - if ( cg.intermissionStarted || (cg.snap && cg.snap->ps.pm_type == PM_INTERMISSION) ) { + if (cg.intermissionStarted || (cg.snap && cg.snap->ps.pm_type == PM_INTERMISSION)) { return; } @@ -377,46 +368,43 @@ void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) { if (ps->persistant[PERS_CAPTURES] != ops->persistant[PERS_CAPTURES]) { pushReward(cgs.media.captureAwardSound, cgs.media.medalCapture, ps->persistant[PERS_CAPTURES]); reward = qtrue; - //Com_Printf("capture\n"); + // Com_Printf("capture\n"); } if (ps->persistant[PERS_IMPRESSIVE_COUNT] != ops->persistant[PERS_IMPRESSIVE_COUNT]) { sfx = cgs.media.impressiveSound; pushReward(sfx, cgs.media.medalImpressive, ps->persistant[PERS_IMPRESSIVE_COUNT]); reward = qtrue; - //Com_Printf("impressive\n"); + // Com_Printf("impressive\n"); } if (ps->persistant[PERS_EXCELLENT_COUNT] != ops->persistant[PERS_EXCELLENT_COUNT]) { sfx = cgs.media.excellentSound; pushReward(sfx, cgs.media.medalExcellent, ps->persistant[PERS_EXCELLENT_COUNT]); reward = qtrue; - //Com_Printf("excellent\n"); + // Com_Printf("excellent\n"); } if (ps->persistant[PERS_GAUNTLET_FRAG_COUNT] != ops->persistant[PERS_GAUNTLET_FRAG_COUNT]) { sfx = cgs.media.humiliationSound; pushReward(sfx, cgs.media.medalGauntlet, ps->persistant[PERS_GAUNTLET_FRAG_COUNT]); reward = qtrue; - //Com_Printf("gauntlet frag\n"); + // Com_Printf("gauntlet frag\n"); } if (ps->persistant[PERS_DEFEND_COUNT] != ops->persistant[PERS_DEFEND_COUNT]) { pushReward(cgs.media.defendSound, cgs.media.medalDefend, ps->persistant[PERS_DEFEND_COUNT]); reward = qtrue; - //Com_Printf("defend\n"); + // Com_Printf("defend\n"); } if (ps->persistant[PERS_ASSIST_COUNT] != ops->persistant[PERS_ASSIST_COUNT]) { - //pushReward(cgs.media.assistSound, cgs.media.medalAssist, ps->persistant[PERS_ASSIST_COUNT]); - //reward = qtrue; - //Com_Printf("assist\n"); + // pushReward(cgs.media.assistSound, cgs.media.medalAssist, ps->persistant[PERS_ASSIST_COUNT]); + // reward = qtrue; + // Com_Printf("assist\n"); } // if any of the player event bits changed if (ps->persistant[PERS_PLAYEREVENTS] != ops->persistant[PERS_PLAYEREVENTS]) { - if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD) != - (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD)) { - trap->S_StartLocalSound( cgs.media.deniedSound, CHAN_ANNOUNCER ); - } - else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD) != - (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD)) { - trap->S_StartLocalSound( cgs.media.humiliationSound, CHAN_ANNOUNCER ); + if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD) != (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_DENIEDREWARD)) { + trap->S_StartLocalSound(cgs.media.deniedSound, CHAN_ANNOUNCER); + } else if ((ps->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD) != (ops->persistant[PERS_PLAYEREVENTS] & PLAYEREVENT_GAUNTLETREWARD)) { + trap->S_StartLocalSound(cgs.media.humiliationSound, CHAN_ANNOUNCER); } reward = qtrue; } @@ -426,10 +414,10 @@ void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) { // lead changes if (!reward && cgAnnouncerTime < cg.time) { // - if ( !cg.warmup && cgs.gametype != GT_POWERDUEL ) { + if (!cg.warmup && cgs.gametype != GT_POWERDUEL) { // never play lead changes during warmup and powerduel - if ( ps->persistant[PERS_RANK] != ops->persistant[PERS_RANK] ) { - if ( cgs.gametype < GT_TEAM) { + if (ps->persistant[PERS_RANK] != ops->persistant[PERS_RANK]) { + if (cgs.gametype < GT_TEAM) { /* if ( ps->persistant[PERS_RANK] == 0 ) { CG_AddBufferedSound(cgs.media.takenLeadSound); @@ -452,43 +440,40 @@ void CG_CheckLocalSounds( playerState_t *ps, playerState_t *ops ) { } // timelimit warnings - if ( cgs.timelimit > 0 && cgAnnouncerTime < cg.time ) { - int msec; + if (cgs.timelimit > 0 && cgAnnouncerTime < cg.time) { + int msec; msec = cg.time - cgs.levelStartTime; - if ( !( cg.timelimitWarnings & 4 ) && msec > ( cgs.timelimit * 60 + 2 ) * 1000 ) { + if (!(cg.timelimitWarnings & 4) && msec > (cgs.timelimit * 60 + 2) * 1000) { cg.timelimitWarnings |= 1 | 2 | 4; - //trap->S_StartLocalSound( cgs.media.suddenDeathSound, CHAN_ANNOUNCER ); - } - else if ( !( cg.timelimitWarnings & 2 ) && msec > (cgs.timelimit - 1) * 60 * 1000 ) { + // trap->S_StartLocalSound( cgs.media.suddenDeathSound, CHAN_ANNOUNCER ); + } else if (!(cg.timelimitWarnings & 2) && msec > (cgs.timelimit - 1) * 60 * 1000) { cg.timelimitWarnings |= 1 | 2; - trap->S_StartLocalSound( cgs.media.oneMinuteSound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.oneMinuteSound, CHAN_ANNOUNCER); cgAnnouncerTime = cg.time + 3000; - } - else if ( cgs.timelimit > 5 && !( cg.timelimitWarnings & 1 ) && msec > (cgs.timelimit - 5) * 60 * 1000 ) { + } else if (cgs.timelimit > 5 && !(cg.timelimitWarnings & 1) && msec > (cgs.timelimit - 5) * 60 * 1000) { cg.timelimitWarnings |= 1; - trap->S_StartLocalSound( cgs.media.fiveMinuteSound, CHAN_ANNOUNCER ); + trap->S_StartLocalSound(cgs.media.fiveMinuteSound, CHAN_ANNOUNCER); cgAnnouncerTime = cg.time + 3000; } } // fraglimit warnings - if ( cgs.fraglimit > 0 && cgs.gametype < GT_CTF && cgs.gametype != GT_DUEL && cgs.gametype != GT_POWERDUEL && cgs.gametype != GT_SIEGE && cgAnnouncerTime < cg.time) { + if (cgs.fraglimit > 0 && cgs.gametype < GT_CTF && cgs.gametype != GT_DUEL && cgs.gametype != GT_POWERDUEL && cgs.gametype != GT_SIEGE && + cgAnnouncerTime < cg.time) { highScore = cgs.scores1; - if ( cgs.gametype == GT_TEAM && cgs.scores2 > highScore ) + if (cgs.gametype == GT_TEAM && cgs.scores2 > highScore) highScore = cgs.scores2; - if ( !( cg.fraglimitWarnings & 4 ) && highScore == (cgs.fraglimit - 1) ) { + if (!(cg.fraglimitWarnings & 4) && highScore == (cgs.fraglimit - 1)) { cg.fraglimitWarnings |= 1 | 2 | 4; CG_AddBufferedSound(cgs.media.oneFragSound); cgAnnouncerTime = cg.time + 3000; - } - else if ( cgs.fraglimit > 2 && !( cg.fraglimitWarnings & 2 ) && highScore == (cgs.fraglimit - 2) ) { + } else if (cgs.fraglimit > 2 && !(cg.fraglimitWarnings & 2) && highScore == (cgs.fraglimit - 2)) { cg.fraglimitWarnings |= 1 | 2; CG_AddBufferedSound(cgs.media.twoFragSound); cgAnnouncerTime = cg.time + 3000; - } - else if ( cgs.fraglimit > 3 && !( cg.fraglimitWarnings & 1 ) && highScore == (cgs.fraglimit - 3) ) { + } else if (cgs.fraglimit > 3 && !(cg.fraglimitWarnings & 1) && highScore == (cgs.fraglimit - 3)) { cg.fraglimitWarnings |= 1; CG_AddBufferedSound(cgs.media.threeFragSound); cgAnnouncerTime = cg.time + 3000; @@ -502,44 +487,42 @@ CG_TransitionPlayerState =============== */ -void CG_TransitionPlayerState( playerState_t *ps, playerState_t *ops ) { +void CG_TransitionPlayerState(playerState_t *ps, playerState_t *ops) { // check for changing follow mode - if ( ps->clientNum != ops->clientNum ) { + if (ps->clientNum != ops->clientNum) { cg.thisFrameTeleport = qtrue; // make sure we don't get any unwanted transition effects *ops = *ps; } // damage events (player is getting wounded) - if ( ps->damageEvent != ops->damageEvent && ps->damageCount ) { - CG_DamageFeedback( ps->damageYaw, ps->damagePitch, ps->damageCount ); + if (ps->damageEvent != ops->damageEvent && ps->damageCount) { + CG_DamageFeedback(ps->damageYaw, ps->damagePitch, ps->damageCount); } // respawning - if ( ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT] ) { + if (ps->persistant[PERS_SPAWN_COUNT] != ops->persistant[PERS_SPAWN_COUNT]) { CG_Respawn(); } - if ( cg.mapRestart ) { + if (cg.mapRestart) { CG_Respawn(); cg.mapRestart = qfalse; } - if ( cg.snap->ps.pm_type != PM_INTERMISSION - && ps->persistant[PERS_TEAM] != TEAM_SPECTATOR ) { - CG_CheckLocalSounds( ps, ops ); + if (cg.snap->ps.pm_type != PM_INTERMISSION && ps->persistant[PERS_TEAM] != TEAM_SPECTATOR) { + CG_CheckLocalSounds(ps, ops); } // check for going low on ammo CG_CheckAmmo(); // run events - CG_CheckPlayerstateEvents( ps, ops ); + CG_CheckPlayerstateEvents(ps, ops); // smooth the ducking viewheight change - if ( ps->viewheight != ops->viewheight ) { + if (ps->viewheight != ops->viewheight) { cg.duckChange = ps->viewheight - ops->viewheight; cg.duckTime = cg.time; } } - diff --git a/codemp/cgame/cg_predict.c b/codemp/cgame/cg_predict.c index 9ef7c3e905..c02ae46ab0 100644 --- a/codemp/cgame/cg_predict.c +++ b/codemp/cgame/cg_predict.c @@ -28,27 +28,24 @@ along with this program; if not, see . #include "cg_local.h" -static pmove_t cg_pmove; +static pmove_t cg_pmove; -static int cg_numSolidEntities; -static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; -static int cg_numTriggerEntities; -static centity_t *cg_triggerEntities[MAX_ENTITIES_IN_SNAPSHOT]; +static int cg_numSolidEntities; +static centity_t *cg_solidEntities[MAX_ENTITIES_IN_SNAPSHOT]; +static int cg_numTriggerEntities; +static centity_t *cg_triggerEntities[MAX_ENTITIES_IN_SNAPSHOT]; -//is this client piloting this veh? -static QINLINE qboolean CG_Piloting(int vehNum) -{ +// is this client piloting this veh? +static QINLINE qboolean CG_Piloting(int vehNum) { centity_t *veh; - if (!vehNum) - { + if (!vehNum) { return qfalse; } veh = &cg_entities[vehNum]; - if (veh->currentState.owner != cg.predictedPlayerState.clientNum) - { //the owner should be the current pilot + if (veh->currentState.owner != cg.predictedPlayerState.clientNum) { // the owner should be the current pilot return qfalse; } @@ -64,152 +61,130 @@ of the entities that are actually solid, to make for more efficient collision detection ==================== */ -void CG_BuildSolidList( void ) { - int i; - centity_t *cent; - snapshot_t *snap; - entityState_t *ent; - vec3_t difference; - float dsquared; +void CG_BuildSolidList(void) { + int i; + centity_t *cent; + snapshot_t *snap; + entityState_t *ent; + vec3_t difference; + float dsquared; cg_numSolidEntities = 0; cg_numTriggerEntities = 0; - if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) { + if (cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport) { snap = cg.nextSnap; } else { snap = cg.snap; } - for ( i = 0 ; i < snap->numEntities ; i++ ) { - cent = &cg_entities[ snap->entities[ i ].number ]; + for (i = 0; i < snap->numEntities; i++) { + cent = &cg_entities[snap->entities[i].number]; ent = ¢->currentState; - if ( ent->eType == ET_ITEM || ent->eType == ET_PUSH_TRIGGER || ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_ITEM || ent->eType == ET_PUSH_TRIGGER || ent->eType == ET_TELEPORT_TRIGGER) { cg_triggerEntities[cg_numTriggerEntities] = cent; cg_numTriggerEntities++; continue; } - if ( cent->nextState.solid ) { + if (cent->nextState.solid) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; continue; } } - //rww - Horrible, terrible, awful hack. - //We don't send your client entity from the server, - //so it isn't added into the solid list from the snapshot, - //and in addition, it has no solid data. So we will force - //adding it in based on a hardcoded player bbox size. - //This will cause issues if the player box size is ever - //changed.. - if (cg_numSolidEntities < MAX_ENTITIES_IN_SNAPSHOT) - { - vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; - vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; + // rww - Horrible, terrible, awful hack. + // We don't send your client entity from the server, + // so it isn't added into the solid list from the snapshot, + // and in addition, it has no solid data. So we will force + // adding it in based on a hardcoded player bbox size. + // This will cause issues if the player box size is ever + // changed.. + if (cg_numSolidEntities < MAX_ENTITIES_IN_SNAPSHOT) { + vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; + vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; int i, j, k; i = playerMaxs[0]; - if (i<1) + if (i < 1) i = 1; - if (i>255) + if (i > 255) i = 255; // z is not symetric j = (-playerMins[2]); - if (j<1) + if (j < 1) j = 1; - if (j>255) + if (j > 255) j = 255; // and z playerMaxs can be negative... - k = (playerMaxs[2]+32); - if (k<1) + k = (playerMaxs[2] + 32); + if (k < 1) k = 1; - if (k>255) + if (k > 255) k = 255; cg_solidEntities[cg_numSolidEntities] = &cg_entities[cg.predictedPlayerState.clientNum]; - cg_solidEntities[cg_numSolidEntities]->currentState.solid = (k<<16) | (j<<8) | i; + cg_solidEntities[cg_numSolidEntities]->currentState.solid = (k << 16) | (j << 8) | i; cg_numSolidEntities++; } - dsquared = /*RMG_distancecull.value*/5000+500; + dsquared = /*RMG_distancecull.value*/ 5000 + 500; dsquared *= dsquared; - for(i=0;ilerpOrigin, snap->ps.origin, difference); if (cent->currentState.eType == ET_TERRAIN || - ((difference[0]*difference[0]) + (difference[1]*difference[1]) + (difference[2]*difference[2])) <= dsquared) - { + ((difference[0] * difference[0]) + (difference[1] * difference[1]) + (difference[2] * difference[2])) <= dsquared) { cent->currentValid = qtrue; - if ( cent->nextState.solid ) - { + if (cent->nextState.solid) { cg_solidEntities[cg_numSolidEntities] = cent; cg_numSolidEntities++; } - } - else - { + } else { cent->currentValid = qfalse; } } } -static QINLINE qboolean CG_VehicleClipCheck(centity_t *ignored, trace_t *trace) -{ - if (!trace || trace->entityNum < 0 || trace->entityNum >= ENTITYNUM_WORLD) - { //it's alright then +static QINLINE qboolean CG_VehicleClipCheck(centity_t *ignored, trace_t *trace) { + if (!trace || trace->entityNum < 0 || trace->entityNum >= ENTITYNUM_WORLD) { // it's alright then return qtrue; } - if (ignored->currentState.eType != ET_PLAYER && - ignored->currentState.eType != ET_NPC) - { //can't possibly be valid then + if (ignored->currentState.eType != ET_PLAYER && ignored->currentState.eType != ET_NPC) { // can't possibly be valid then return qtrue; } - if (ignored->currentState.m_iVehicleNum) - { //see if the ignore ent is a vehicle/rider - if so, see if the ent we supposedly hit is a vehicle/rider. - //if they belong to each other, we don't want to collide them. + if (ignored->currentState.m_iVehicleNum) { // see if the ignore ent is a vehicle/rider - if so, see if the ent we supposedly hit is a vehicle/rider. + // if they belong to each other, we don't want to collide them. centity_t *otherguy = &cg_entities[trace->entityNum]; - if (otherguy->currentState.eType != ET_PLAYER && - otherguy->currentState.eType != ET_NPC) - { //can't possibly be valid then + if (otherguy->currentState.eType != ET_PLAYER && otherguy->currentState.eType != ET_NPC) { // can't possibly be valid then return qtrue; } - if (otherguy->currentState.m_iVehicleNum) - { //alright, both of these are either a vehicle or a player who is on a vehicle + if (otherguy->currentState.m_iVehicleNum) { // alright, both of these are either a vehicle or a player who is on a vehicle int index; - if (ignored->currentState.eType == ET_PLAYER - || (ignored->currentState.eType == ET_NPC && ignored->currentState.NPC_class != CLASS_VEHICLE) ) - { //must be a player or NPC riding a vehicle + if (ignored->currentState.eType == ET_PLAYER || + (ignored->currentState.eType == ET_NPC && ignored->currentState.NPC_class != CLASS_VEHICLE)) { // must be a player or NPC riding a vehicle index = ignored->currentState.m_iVehicleNum; - } - else - { //a vehicle - index = ignored->currentState.m_iVehicleNum-1; + } else { // a vehicle + index = ignored->currentState.m_iVehicleNum - 1; } - if (index == otherguy->currentState.number) - { //this means we're riding or being ridden by this guy, so don't collide + if (index == otherguy->currentState.number) { // this means we're riding or being ridden by this guy, so don't collide return qfalse; - } - else - {//see if I'm hitting one of my own passengers - if (otherguy->currentState.eType == ET_PLAYER - || (otherguy->currentState.eType == ET_NPC && otherguy->currentState.NPC_class != CLASS_VEHICLE) ) - { //must be a player or NPC riding a vehicle - if (otherguy->currentState.m_iVehicleNum==ignored->currentState.number) - { //this means we're other guy is riding the ignored ent + } else { // see if I'm hitting one of my own passengers + if (otherguy->currentState.eType == ET_PLAYER || + (otherguy->currentState.eType == ET_NPC && otherguy->currentState.NPC_class != CLASS_VEHICLE)) { // must be a player or NPC riding a vehicle + if (otherguy->currentState.m_iVehicleNum == ignored->currentState.number) { // this means we're other guy is riding the ignored ent return qfalse; } } @@ -226,80 +201,74 @@ CG_ClipMoveToEntities ==================== */ -extern void BG_VehicleAdjustBBoxForOrientation( Vehicle_t *veh, vec3_t origin, vec3_t mins, vec3_t maxs, - int clientNum, int tracemask, - void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask)); // bg_pmove.c -static void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask, trace_t *tr, qboolean g2Check ) { - int i, x, zd, zu; - trace_t trace, oldTrace; - entityState_t *ent; - clipHandle_t cmodel; - vec3_t bmins, bmaxs; - vec3_t origin, angles; - centity_t *cent; - centity_t *ignored = NULL; - - if (skipNumber != -1 && skipNumber != ENTITYNUM_NONE) - { +extern void BG_VehicleAdjustBBoxForOrientation(Vehicle_t *veh, vec3_t origin, vec3_t mins, vec3_t maxs, int clientNum, int tracemask, + void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, + int passEntityNum, int contentMask)); // bg_pmove.c +static void CG_ClipMoveToEntities(const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask, trace_t *tr, + qboolean g2Check) { + int i, x, zd, zu; + trace_t trace, oldTrace; + entityState_t *ent; + clipHandle_t cmodel; + vec3_t bmins, bmaxs; + vec3_t origin, angles; + centity_t *cent; + centity_t *ignored = NULL; + + if (skipNumber != -1 && skipNumber != ENTITYNUM_NONE) { ignored = &cg_entities[skipNumber]; } - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == skipNumber ) { + if (ent->number == skipNumber) { continue; } - if ( ent->number > MAX_CLIENTS && - (ent->genericenemyindex-MAX_GENTITIES==cg.predictedPlayerState.clientNum || ent->genericenemyindex-MAX_GENTITIES==cg.predictedVehicleState.clientNum) ) -// if (ent->number > MAX_CLIENTS && cg.snap && ent->genericenemyindex && (ent->genericenemyindex-MAX_GENTITIES) == cg.snap->ps.clientNum) - { //rww - method of keeping objects from colliding in client-prediction (in case of ownership) + if (ent->number > MAX_CLIENTS && (ent->genericenemyindex - MAX_GENTITIES == cg.predictedPlayerState.clientNum || + ent->genericenemyindex - MAX_GENTITIES == cg.predictedVehicleState.clientNum)) + // if (ent->number > MAX_CLIENTS && cg.snap && ent->genericenemyindex && (ent->genericenemyindex-MAX_GENTITIES) == cg.snap->ps.clientNum) + { // rww - method of keeping objects from colliding in client-prediction (in case of ownership) continue; } - if ( ent->solid == SOLID_BMODEL ) { + if (ent->solid == SOLID_BMODEL) { // special value for bmodel - cmodel = trap->CM_InlineModel( ent->modelindex ); - VectorCopy( cent->lerpAngles, angles ); - BG_EvaluateTrajectory( ¢->currentState.pos, cg.physicsTime, origin ); + cmodel = trap->CM_InlineModel(ent->modelindex); + VectorCopy(cent->lerpAngles, angles); + BG_EvaluateTrajectory(¢->currentState.pos, cg.physicsTime, origin); } else { // encoded bbox x = (ent->solid & 255); - zd = ((ent->solid>>8) & 255); - zu = ((ent->solid>>16) & 255) - 32; + zd = ((ent->solid >> 8) & 255); + zu = ((ent->solid >> 16) & 255) - 32; bmins[0] = bmins[1] = -x; bmaxs[0] = bmaxs[1] = x; bmins[2] = -zd; bmaxs[2] = zu; - if (ent->eType == ET_NPC && ent->NPC_class == CLASS_VEHICLE && - cent->m_pVehicle) - { //try to dynamically adjust his bbox dynamically, if possible + if (ent->eType == ET_NPC && ent->NPC_class == CLASS_VEHICLE && cent->m_pVehicle) { // try to dynamically adjust his bbox dynamically, if possible float *old = cent->m_pVehicle->m_vOrientation; cent->m_pVehicle->m_vOrientation = ¢->lerpAngles[0]; - BG_VehicleAdjustBBoxForOrientation(cent->m_pVehicle, cent->lerpOrigin, bmins, bmaxs, - cent->currentState.number, MASK_PLAYERSOLID, NULL); + BG_VehicleAdjustBBoxForOrientation(cent->m_pVehicle, cent->lerpOrigin, bmins, bmaxs, cent->currentState.number, MASK_PLAYERSOLID, NULL); cent->m_pVehicle->m_vOrientation = old; } - cmodel = trap->CM_TempModel( bmins, bmaxs, 0 ); - VectorCopy( vec3_origin, angles ); + cmodel = trap->CM_TempModel(bmins, bmaxs, 0); + VectorCopy(vec3_origin, angles); - VectorCopy( cent->lerpOrigin, origin ); + VectorCopy(cent->lerpOrigin, origin); } - - trap->CM_TransformedTrace ( &trace, start, end, mins, maxs, cmodel, mask, origin, angles, 0); + trap->CM_TransformedTrace(&trace, start, end, mins, maxs, cmodel, mask, origin, angles, 0); trace.entityNum = trace.fraction != 1.0 ? ent->number : ENTITYNUM_NONE; - if (g2Check || (ignored && ignored->currentState.m_iVehicleNum)) - { - //keep these older variables around for a bit, incase we need to replace them in the Ghoul2 Collision check - //or in the vehicle owner trace check + if (g2Check || (ignored && ignored->currentState.m_iVehicleNum)) { + // keep these older variables around for a bit, incase we need to replace them in the Ghoul2 Collision check + // or in the vehicle owner trace check oldTrace = *tr; } @@ -309,55 +278,40 @@ static void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const } else if (trace.startsolid) { tr->startsolid = qtrue; - //rww 12-02-02 + // rww 12-02-02 tr->entityNum = trace.entityNum = ent->number; } - if ( tr->allsolid ) - { - if (ignored && ignored->currentState.m_iVehicleNum) - { + if (tr->allsolid) { + if (ignored && ignored->currentState.m_iVehicleNum) { trace.entityNum = ent->number; - if (CG_VehicleClipCheck(ignored, &trace)) - { //this isn't our vehicle, we're really stuck + if (CG_VehicleClipCheck(ignored, &trace)) { // this isn't our vehicle, we're really stuck return; - } - else - { //it's alright, keep going + } else { // it's alright, keep going trace = oldTrace; *tr = trace; } - } - else - { + } else { return; } } - if (g2Check) - { - if (trace.entityNum == ent->number && cent->ghoul2) - { + if (g2Check) { + if (trace.entityNum == ent->number && cent->ghoul2) { CG_G2TraceCollide(&trace, mins, maxs, start, end); - if (trace.entityNum == ENTITYNUM_NONE) - { //g2 trace failed, so put it back where it was. + if (trace.entityNum == ENTITYNUM_NONE) { // g2 trace failed, so put it back where it was. trace = oldTrace; *tr = trace; } } } - if (ignored && ignored->currentState.m_iVehicleNum) - { //see if this is the vehicle we hit + if (ignored && ignored->currentState.m_iVehicleNum) { // see if this is the vehicle we hit centity_t *hit = &cg_entities[trace.entityNum]; - if (!CG_VehicleClipCheck(ignored, &trace)) - { //looks like it + if (!CG_VehicleClipCheck(ignored, &trace)) { // looks like it trace = oldTrace; *tr = trace; - } - else if (hit->currentState.eType == ET_MISSILE && - hit->currentState.owner == ignored->currentState.number) - { //hack, don't hit own missiles + } else if (hit->currentState.eType == ET_MISSILE && hit->currentState.owner == ignored->currentState.number) { // hack, don't hit own missiles trace = oldTrace; *tr = trace; } @@ -370,14 +324,13 @@ static void CG_ClipMoveToEntities ( const vec3_t start, const vec3_t mins, const CG_Trace ================ */ -void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask ) { - trace_t t; +void CG_Trace(trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask) { + trace_t t; - trap->CM_Trace ( &t, start, end, mins, maxs, 0, mask, 0); + trap->CM_Trace(&t, start, end, mins, maxs, 0, mask, 0); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models - CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t, qfalse); + CG_ClipMoveToEntities(start, mins, maxs, end, skipNumber, mask, &t, qfalse); *result = t; } @@ -387,14 +340,13 @@ void CG_Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec CG_G2Trace ================ */ -void CG_G2Trace( trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, - int skipNumber, int mask ) { - trace_t t; +void CG_G2Trace(trace_t *result, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int skipNumber, int mask) { + trace_t t; - trap->CM_Trace ( &t, start, end, mins, maxs, 0, mask, 0); + trap->CM_Trace(&t, start, end, mins, maxs, 0, mask, 0); t.entityNum = t.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; // check all other solid models - CG_ClipMoveToEntities (start, mins, maxs, end, skipNumber, mask, &t, qtrue); + CG_ClipMoveToEntities(start, mins, maxs, end, skipNumber, mask, &t, qtrue); *result = t; } @@ -404,21 +356,21 @@ void CG_G2Trace( trace_t *result, const vec3_t start, const vec3_t mins, const v CG_PointContents ================ */ -int CG_PointContents( const vec3_t point, int passEntityNum ) { - int i; - entityState_t *ent; - centity_t *cent; +int CG_PointContents(const vec3_t point, int passEntityNum) { + int i; + entityState_t *ent; + centity_t *cent; clipHandle_t cmodel; - int contents; + int contents; - contents = trap->CM_PointContents (point, 0); + contents = trap->CM_PointContents(point, 0); - for ( i = 0 ; i < cg_numSolidEntities ; i++ ) { - cent = cg_solidEntities[ i ]; + for (i = 0; i < cg_numSolidEntities; i++) { + cent = cg_solidEntities[i]; ent = ¢->currentState; - if ( ent->number == passEntityNum ) { + if (ent->number == passEntityNum) { continue; } @@ -426,18 +378,17 @@ int CG_PointContents( const vec3_t point, int passEntityNum ) { continue; } - cmodel = trap->CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = trap->CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - contents |= trap->CM_TransformedPointContents( point, cmodel, cent->lerpOrigin, cent->lerpAngles ); + contents |= trap->CM_TransformedPointContents(point, cmodel, cent->lerpOrigin, cent->lerpAngles); } return contents; } - /* ======================== CG_InterpolatePlayerState @@ -446,11 +397,11 @@ Generates cg.predictedPlayerState by interpolating between cg.snap->ps and cg.nextFrame->ps ======================== */ -static void CG_InterpolatePlayerState( qboolean grabAngles ) { - float f; - int i; - playerState_t *out; - snapshot_t *prev, *next; +static void CG_InterpolatePlayerState(qboolean grabAngles) { + float f; + int i; + playerState_t *out; + snapshot_t *prev, *next; out = &cg.predictedPlayerState; prev = cg.snap; @@ -459,50 +410,47 @@ static void CG_InterpolatePlayerState( qboolean grabAngles ) { *out = cg.snap->ps; // if we are still allowing local input, short circuit the view angles - if ( grabAngles ) { - usercmd_t cmd; - int cmdNum; + if (grabAngles) { + usercmd_t cmd; + int cmdNum; cmdNum = trap->GetCurrentCmdNumber(); - trap->GetUserCmd( cmdNum, &cmd ); + trap->GetUserCmd(cmdNum, &cmd); - PM_UpdateViewAngles( out, &cmd ); + PM_UpdateViewAngles(out, &cmd); } // if the next frame is a teleport, we can't lerp to it - if ( cg.nextFrameTeleport ) { + if (cg.nextFrameTeleport) { return; } - if ( !next || next->serverTime <= prev->serverTime ) { + if (!next || next->serverTime <= prev->serverTime) { return; } - f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime ); + f = (float)(cg.time - prev->serverTime) / (next->serverTime - prev->serverTime); i = next->ps.bobCycle; - if ( i < prev->ps.bobCycle ) { - i += 256; // handle wraparound + if (i < prev->ps.bobCycle) { + i += 256; // handle wraparound } - out->bobCycle = prev->ps.bobCycle + f * ( i - prev->ps.bobCycle ); + out->bobCycle = prev->ps.bobCycle + f * (i - prev->ps.bobCycle); - for ( i = 0 ; i < 3 ; i++ ) { - out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i] ); - if ( !grabAngles ) { - out->viewangles[i] = LerpAngle( - prev->ps.viewangles[i], next->ps.viewangles[i], f ); + for (i = 0; i < 3; i++) { + out->origin[i] = prev->ps.origin[i] + f * (next->ps.origin[i] - prev->ps.origin[i]); + if (!grabAngles) { + out->viewangles[i] = LerpAngle(prev->ps.viewangles[i], next->ps.viewangles[i], f); } - out->velocity[i] = prev->ps.velocity[i] + - f * (next->ps.velocity[i] - prev->ps.velocity[i] ); + out->velocity[i] = prev->ps.velocity[i] + f * (next->ps.velocity[i] - prev->ps.velocity[i]); } - } -static void CG_InterpolateVehiclePlayerState( qboolean grabAngles ) { - float f; - int i; - playerState_t *out; - snapshot_t *prev, *next; +static void CG_InterpolateVehiclePlayerState(qboolean grabAngles) { + float f; + int i; + playerState_t *out; + snapshot_t *prev, *next; out = &cg.predictedVehicleState; prev = cg.snap; @@ -511,43 +459,40 @@ static void CG_InterpolateVehiclePlayerState( qboolean grabAngles ) { *out = cg.snap->vps; // if we are still allowing local input, short circuit the view angles - if ( grabAngles ) { - usercmd_t cmd; - int cmdNum; + if (grabAngles) { + usercmd_t cmd; + int cmdNum; cmdNum = trap->GetCurrentCmdNumber(); - trap->GetUserCmd( cmdNum, &cmd ); + trap->GetUserCmd(cmdNum, &cmd); - PM_UpdateViewAngles( out, &cmd ); + PM_UpdateViewAngles(out, &cmd); } // if the next frame is a teleport, we can't lerp to it - if ( cg.nextFrameTeleport ) { + if (cg.nextFrameTeleport) { return; } - if ( !next || next->serverTime <= prev->serverTime ) { + if (!next || next->serverTime <= prev->serverTime) { return; } - f = (float)( cg.time - prev->serverTime ) / ( next->serverTime - prev->serverTime ); + f = (float)(cg.time - prev->serverTime) / (next->serverTime - prev->serverTime); i = next->vps.bobCycle; - if ( i < prev->vps.bobCycle ) { - i += 256; // handle wraparound + if (i < prev->vps.bobCycle) { + i += 256; // handle wraparound } - out->bobCycle = prev->vps.bobCycle + f * ( i - prev->vps.bobCycle ); + out->bobCycle = prev->vps.bobCycle + f * (i - prev->vps.bobCycle); - for ( i = 0 ; i < 3 ; i++ ) { - out->origin[i] = prev->vps.origin[i] + f * (next->vps.origin[i] - prev->vps.origin[i] ); - if ( !grabAngles ) { - out->viewangles[i] = LerpAngle( - prev->vps.viewangles[i], next->vps.viewangles[i], f ); + for (i = 0; i < 3; i++) { + out->origin[i] = prev->vps.origin[i] + f * (next->vps.origin[i] - prev->vps.origin[i]); + if (!grabAngles) { + out->viewangles[i] = LerpAngle(prev->vps.viewangles[i], next->vps.viewangles[i], f); } - out->velocity[i] = prev->vps.velocity[i] + - f * (next->vps.velocity[i] - prev->vps.velocity[i] ); + out->velocity[i] = prev->vps.velocity[i] + f * (next->vps.velocity[i] - prev->vps.velocity[i]); } - } /* @@ -555,109 +500,96 @@ static void CG_InterpolateVehiclePlayerState( qboolean grabAngles ) { CG_TouchItem =================== */ -static void CG_TouchItem( centity_t *cent ) { - gitem_t *item; +static void CG_TouchItem(centity_t *cent) { + gitem_t *item; - if ( !cg_predictItems.integer ) { + if (!cg_predictItems.integer) { return; } - if ( !BG_PlayerTouchesItem( &cg.predictedPlayerState, ¢->currentState, cg.time ) ) { + if (!BG_PlayerTouchesItem(&cg.predictedPlayerState, ¢->currentState, cg.time)) { return; } - if (cent->currentState.brokenLimbs) - { //dropped item + if (cent->currentState.brokenLimbs) { // dropped item return; } - if (cent->currentState.eFlags & EF_ITEMPLACEHOLDER) - { + if (cent->currentState.eFlags & EF_ITEMPLACEHOLDER) { return; } - if (cent->currentState.eFlags & EF_NODRAW) - { + if (cent->currentState.eFlags & EF_NODRAW) { return; } // never pick an item up twice in a prediction - if ( cent->miscTime == cg.time ) { + if (cent->miscTime == cg.time) { return; } - if ( !BG_CanItemBeGrabbed( cgs.gametype, ¢->currentState, &cg.predictedPlayerState ) ) { - return; // can't hold it + if (!BG_CanItemBeGrabbed(cgs.gametype, ¢->currentState, &cg.predictedPlayerState)) { + return; // can't hold it } - item = &bg_itemlist[ cent->currentState.modelindex ]; + item = &bg_itemlist[cent->currentState.modelindex]; - //Currently there is no reliable way of knowing if the client has touched a certain item before another if they are next to each other, or rather - //if the server has touched them in the same order. This results often in grabbing an item in the prediction and the server giving you the other - //item. So for now prediction of armor, health, and ammo is disabled. -/* - if (item->giType == IT_ARMOR) - { //rww - this will be stomped next update, but it's set so that we don't try to pick up two shields in one prediction and have the server cancel one - // cg.predictedPlayerState.stats[STAT_ARMOR] += item->quantity; + // Currently there is no reliable way of knowing if the client has touched a certain item before another if they are next to each other, or rather + // if the server has touched them in the same order. This results often in grabbing an item in the prediction and the server giving you the other + // item. So for now prediction of armor, health, and ammo is disabled. + /* + if (item->giType == IT_ARMOR) + { //rww - this will be stomped next update, but it's set so that we don't try to pick up two shields in one prediction and have the server cancel one + // cg.predictedPlayerState.stats[STAT_ARMOR] += item->quantity; - //FIXME: This can't be predicted properly at the moment - return; - } + //FIXME: This can't be predicted properly at the moment + return; + } - if (item->giType == IT_HEALTH) - { //same as above, for health - // cg.predictedPlayerState.stats[STAT_HEALTH] += item->quantity; + if (item->giType == IT_HEALTH) + { //same as above, for health + // cg.predictedPlayerState.stats[STAT_HEALTH] += item->quantity; - //FIXME: This can't be predicted properly at the moment - return; - } + //FIXME: This can't be predicted properly at the moment + return; + } - if (item->giType == IT_AMMO) - { //same as above, for ammo - // cg.predictedPlayerState.ammo[item->giTag] += item->quantity; + if (item->giType == IT_AMMO) + { //same as above, for ammo + // cg.predictedPlayerState.ammo[item->giTag] += item->quantity; - //FIXME: This can't be predicted properly at the moment - return; - } + //FIXME: This can't be predicted properly at the moment + return; + } - if (item->giType == IT_HOLDABLE) - { //same as above, for holdables - // cg.predictedPlayerState.stats[STAT_HOLDABLE_ITEMS] |= (1 << item->giTag); - } -*/ + if (item->giType == IT_HOLDABLE) + { //same as above, for holdables + // cg.predictedPlayerState.stats[STAT_HOLDABLE_ITEMS] |= (1 << item->giTag); + } + */ // Special case for flags. // We don't predict touching our own flag // Make sure the item type is also a flag too - if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY ) { - if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_RED && - item->giType == IT_TEAM && item->giTag == PW_REDFLAG) + if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTY) { + if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_RED && item->giType == IT_TEAM && item->giTag == PW_REDFLAG) return; - if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_BLUE && - item->giType == IT_TEAM && item->giTag == PW_BLUEFLAG) + if (cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_BLUE && item->giType == IT_TEAM && item->giTag == PW_BLUEFLAG) return; } - if (item->giType == IT_POWERUP && - (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || item->giTag == PW_FORCE_ENLIGHTENED_DARK)) - { - if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) - { - if (cg.predictedPlayerState.fd.forceSide != FORCE_LIGHTSIDE) - { + if (item->giType == IT_POWERUP && (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || item->giTag == PW_FORCE_ENLIGHTENED_DARK)) { + if (item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) { + if (cg.predictedPlayerState.fd.forceSide != FORCE_LIGHTSIDE) { return; } - } - else - { - if (cg.predictedPlayerState.fd.forceSide != FORCE_DARKSIDE) - { + } else { + if (cg.predictedPlayerState.fd.forceSide != FORCE_DARKSIDE) { return; } } } - // grab it - BG_AddPredictableEventToPlayerstate( EV_ITEM_PICKUP, cent->currentState.number , &cg.predictedPlayerState); + BG_AddPredictableEventToPlayerstate(EV_ITEM_PICKUP, cent->currentState.number, &cg.predictedPlayerState); // remove it from the frame so it won't be drawn cent->currentState.eFlags |= EF_NODRAW; @@ -666,15 +598,14 @@ static void CG_TouchItem( centity_t *cent ) { cent->miscTime = cg.time; // if its a weapon, give them some predicted ammo so the autoswitch will work - if ( item->giType == IT_WEAPON ) { - cg.predictedPlayerState.stats[ STAT_WEAPONS ] |= 1 << item->giTag; - if ( !cg.predictedPlayerState.ammo[ item->giTag ] ) { - cg.predictedPlayerState.ammo[ item->giTag ] = 1; + if (item->giType == IT_WEAPON) { + cg.predictedPlayerState.stats[STAT_WEAPONS] |= 1 << item->giTag; + if (!cg.predictedPlayerState.ammo[item->giTag]) { + cg.predictedPlayerState.ammo[item->giTag] = 1; } } } - /* ========================= CG_TouchTriggerPrediction @@ -682,58 +613,59 @@ CG_TouchTriggerPrediction Predict push triggers and items ========================= */ -static void CG_TouchTriggerPrediction( void ) { - int i; - trace_t trace; - entityState_t *ent; +static void CG_TouchTriggerPrediction(void) { + int i; + trace_t trace; + entityState_t *ent; clipHandle_t cmodel; - centity_t *cent; - qboolean spectator; + centity_t *cent; + qboolean spectator; // dead clients don't activate triggers - if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 ) { + if (cg.predictedPlayerState.stats[STAT_HEALTH] <= 0) { return; } - spectator = ( cg.predictedPlayerState.pm_type == PM_SPECTATOR ); + spectator = (cg.predictedPlayerState.pm_type == PM_SPECTATOR); - if ( cg.predictedPlayerState.pm_type != PM_NORMAL && cg.predictedPlayerState.pm_type != PM_JETPACK && cg.predictedPlayerState.pm_type != PM_FLOAT && !spectator ) { + if (cg.predictedPlayerState.pm_type != PM_NORMAL && cg.predictedPlayerState.pm_type != PM_JETPACK && cg.predictedPlayerState.pm_type != PM_FLOAT && + !spectator) { return; } - for ( i = 0 ; i < cg_numTriggerEntities ; i++ ) { - cent = cg_triggerEntities[ i ]; + for (i = 0; i < cg_numTriggerEntities; i++) { + cent = cg_triggerEntities[i]; ent = ¢->currentState; - if ( ent->eType == ET_ITEM && !spectator ) { - CG_TouchItem( cent ); + if (ent->eType == ET_ITEM && !spectator) { + CG_TouchItem(cent); continue; } - if ( ent->solid != SOLID_BMODEL ) { + if (ent->solid != SOLID_BMODEL) { continue; } - cmodel = trap->CM_InlineModel( ent->modelindex ); - if ( !cmodel ) { + cmodel = trap->CM_InlineModel(ent->modelindex); + if (!cmodel) { continue; } - trap->CM_Trace( &trace, cg.predictedPlayerState.origin, cg.predictedPlayerState.origin, cg_pmove.mins, cg_pmove.maxs, cmodel, -1, 0 ); + trap->CM_Trace(&trace, cg.predictedPlayerState.origin, cg.predictedPlayerState.origin, cg_pmove.mins, cg_pmove.maxs, cmodel, -1, 0); - if ( !trace.startsolid ) { + if (!trace.startsolid) { continue; } - if ( ent->eType == ET_TELEPORT_TRIGGER ) { + if (ent->eType == ET_TELEPORT_TRIGGER) { cg.hyperspace = qtrue; - } else if ( ent->eType == ET_PUSH_TRIGGER ) { - BG_TouchJumpPad( &cg.predictedPlayerState, ent ); + } else if (ent->eType == ET_PUSH_TRIGGER) { + BG_TouchJumpPad(&cg.predictedPlayerState, ent); } } // if we didn't touch a jump pad this pmove frame - if ( cg.predictedPlayerState.jumppad_frame != cg.predictedPlayerState.pmove_framecount ) { + if (cg.predictedPlayerState.jumppad_frame != cg.predictedPlayerState.pmove_framecount) { cg.predictedPlayerState.jumppad_frame = 0; cg.predictedPlayerState.jumppad_ent = 0; } @@ -848,7 +780,7 @@ static QINLINE void CG_EntityStateToPlayerState( entityState_t *s, playerState_t } #endif -playerState_t cgSendPSPool[ MAX_GENTITIES ]; +playerState_t cgSendPSPool[MAX_GENTITIES]; playerState_t *cgSendPS[MAX_GENTITIES]; //#define _PROFILE_ES_TO_PS @@ -857,36 +789,32 @@ playerState_t *cgSendPS[MAX_GENTITIES]; int g_cgEStoPSTime = 0; #endif -//Assign all the entity playerstate pointers to the corresponding one -//so that we can access playerstate stuff in bg code (and then translate -//it back to entitystate data) -void CG_PmoveClientPointerUpdate() -{ +// Assign all the entity playerstate pointers to the corresponding one +// so that we can access playerstate stuff in bg code (and then translate +// it back to entitystate data) +void CG_PmoveClientPointerUpdate() { int i; memset(&cgSendPSPool[0], 0, sizeof(cgSendPSPool)); - for ( i = 0 ; i < MAX_GENTITIES ; i++ ) - { + for (i = 0; i < MAX_GENTITIES; i++) { cgSendPS[i] = &cgSendPSPool[i]; // These will be invalid at this point on Xbox cg_entities[i].playerState = cgSendPS[i]; } - //Set up bg entity data + // Set up bg entity data cg_pmove.baseEnt = (bgEntity_t *)cg_entities; cg_pmove.entSize = sizeof(centity_t); cg_pmove.ghoul2 = NULL; } -//check if local client is on an eweb -qboolean CG_UsingEWeb(void) -{ +// check if local client is on an eweb +qboolean CG_UsingEWeb(void) { if (cg.predictedPlayerState.weapon == WP_EMPLACED_GUN && cg.predictedPlayerState.emplacedIndex && - cg_entities[cg.predictedPlayerState.emplacedIndex].currentState.weapon == WP_NONE) - { + cg_entities[cg.predictedPlayerState.emplacedIndex].currentState.weapon == WP_NONE) { return qtrue; } @@ -919,50 +847,47 @@ We detect prediction errors and allow them to be decayed off over several frames to ease the jerk. ================= */ -extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern vmCvar_t cg_showVehBounds; +extern void CG_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern vmCvar_t cg_showVehBounds; pmove_t cg_vehPmove; qboolean cg_vehPmoveSet = qfalse; -void CG_PredictPlayerState( void ) { - int cmdNum, current, i; - playerState_t oldPlayerState; - playerState_t oldVehicleState; - qboolean moved; - usercmd_t oldestCmd; - usercmd_t latestCmd; +void CG_PredictPlayerState(void) { + int cmdNum, current, i; + playerState_t oldPlayerState; + playerState_t oldVehicleState; + qboolean moved; + usercmd_t oldestCmd; + usercmd_t latestCmd; centity_t *pEnt; clientInfo_t *ci; - cg.hyperspace = qfalse; // will be set if touching a trigger_teleport + cg.hyperspace = qfalse; // will be set if touching a trigger_teleport // if this is the first frame we must guarantee // predictedPlayerState is valid even if there is some // other error condition - if ( !cg.validPPS ) { + if (!cg.validPPS) { cg.validPPS = qtrue; cg.predictedPlayerState = cg.snap->ps; - if (CG_Piloting(cg.snap->ps.m_iVehicleNum)) - { + if (CG_Piloting(cg.snap->ps.m_iVehicleNum)) { cg.predictedVehicleState = cg.snap->vps; } } // demo playback just copies the moves - if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) ) { - CG_InterpolatePlayerState( qfalse ); - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { + if (cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW)) { + CG_InterpolatePlayerState(qfalse); + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { CG_InterpolateVehiclePlayerState(qfalse); } return; } // non-predicting local movement will grab the latest angles - if ( cg_noPredict.integer || g_synchronousClients.integer || CG_UsingEWeb() ) { - CG_InterpolatePlayerState( qtrue ); - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { + if (cg_noPredict.integer || g_synchronousClients.integer || CG_UsingEWeb()) { + CG_InterpolatePlayerState(qtrue); + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { CG_InterpolateVehiclePlayerState(qtrue); } return; @@ -974,45 +899,37 @@ void CG_PredictPlayerState( void ) { cg_pmove.pointcontents = CG_PointContents; pEnt = &cg_entities[cg.predictedPlayerState.clientNum]; - //rww - bgghoul2 - if (cg_pmove.ghoul2 != pEnt->ghoul2) //only update it if the g2 instance has changed + // rww - bgghoul2 + if (cg_pmove.ghoul2 != pEnt->ghoul2) // only update it if the g2 instance has changed { - if (cg.snap && - pEnt->ghoul2 && - !(cg.snap->ps.pm_flags & PMF_FOLLOW) && - cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) - { + if (cg.snap && pEnt->ghoul2 && !(cg.snap->ps.pm_flags & PMF_FOLLOW) && cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) { cg_pmove.ghoul2 = pEnt->ghoul2; cg_pmove.g2Bolts_LFoot = trap->G2API_AddBolt(pEnt->ghoul2, 0, "*l_leg_foot"); cg_pmove.g2Bolts_RFoot = trap->G2API_AddBolt(pEnt->ghoul2, 0, "*r_leg_foot"); - } - else - { + } else { cg_pmove.ghoul2 = NULL; } } ci = &cgs.clientinfo[cg.predictedPlayerState.clientNum]; - //I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that) + // I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that) VectorCopy(pEnt->modelScale, cg_pmove.modelScale); - //rww end bgghoul2 + // rww end bgghoul2 - if ( cg_pmove.ps->pm_type == PM_DEAD ) { + if (cg_pmove.ps->pm_type == PM_DEAD) { cg_pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; - } - else { + } else { cg_pmove.tracemask = MASK_PLAYERSOLID; } - if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.pm_type == PM_SPECTATOR ) { - cg_pmove.tracemask &= ~CONTENTS_BODY; // spectators can fly through bodies + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cg.snap->ps.pm_type == PM_SPECTATOR) { + cg_pmove.tracemask &= ~CONTENTS_BODY; // spectators can fly through bodies } - cg_pmove.noFootsteps = ( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; + cg_pmove.noFootsteps = (cgs.dmflags & DF_NO_FOOTSTEPS) > 0; // save the state before the pmove so we can detect transitions oldPlayerState = cg.predictedPlayerState; - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { oldVehicleState = cg.predictedVehicleState; } @@ -1022,64 +939,57 @@ void CG_PredictPlayerState( void ) { // can't accurately predict a current position, so just freeze at // the last good position we had cmdNum = current - CMD_BACKUP + 1; - trap->GetUserCmd( cmdNum, &oldestCmd ); - if ( oldestCmd.serverTime > cg.snap->ps.commandTime - && oldestCmd.serverTime < cg.time ) { // special check for map_restart - if ( cg_showMiss.integer ) { - trap->Print ("exceeded PACKET_BACKUP on commands\n"); + trap->GetUserCmd(cmdNum, &oldestCmd); + if (oldestCmd.serverTime > cg.snap->ps.commandTime && oldestCmd.serverTime < cg.time) { // special check for map_restart + if (cg_showMiss.integer) { + trap->Print("exceeded PACKET_BACKUP on commands\n"); } return; } // get the latest command so we can know which commands are from previous map_restarts - trap->GetUserCmd( current, &latestCmd ); + trap->GetUserCmd(current, &latestCmd); // get the most recent information we have, even if // the server time is beyond our current cg.time, // because predicted player positions are going to // be ahead of everything else anyway - if ( cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport ) { - cg.nextSnap->ps.slopeRecalcTime = cg.predictedPlayerState.slopeRecalcTime; //this is the only value we want to maintain seperately on server/client + if (cg.nextSnap && !cg.nextFrameTeleport && !cg.thisFrameTeleport) { + cg.nextSnap->ps.slopeRecalcTime = cg.predictedPlayerState.slopeRecalcTime; // this is the only value we want to maintain seperately on server/client cg.predictedPlayerState = cg.nextSnap->ps; - if (CG_Piloting(cg.nextSnap->ps.m_iVehicleNum)) - { + if (CG_Piloting(cg.nextSnap->ps.m_iVehicleNum)) { cg.predictedVehicleState = cg.nextSnap->vps; } cg.physicsTime = cg.nextSnap->serverTime; } else { - cg.snap->ps.slopeRecalcTime = cg.predictedPlayerState.slopeRecalcTime; //this is the only value we want to maintain seperately on server/client + cg.snap->ps.slopeRecalcTime = cg.predictedPlayerState.slopeRecalcTime; // this is the only value we want to maintain seperately on server/client cg.predictedPlayerState = cg.snap->ps; - if (CG_Piloting(cg.snap->ps.m_iVehicleNum)) - { + if (CG_Piloting(cg.snap->ps.m_iVehicleNum)) { cg.predictedVehicleState = cg.snap->vps; } cg.physicsTime = cg.snap->serverTime; } - if ( pmove_msec.integer < 8 ) { + if (pmove_msec.integer < 8) { trap->Cvar_Set("pmove_msec", "8"); - } - else if (pmove_msec.integer > 33) { + } else if (pmove_msec.integer > 33) { trap->Cvar_Set("pmove_msec", "33"); } - cg_pmove.pmove_fixed = pmove_fixed.integer;// | cg_pmove_fixed.integer; + cg_pmove.pmove_fixed = pmove_fixed.integer; // | cg_pmove_fixed.integer; cg_pmove.pmove_float = pmove_float.integer; cg_pmove.pmove_msec = pmove_msec.integer; - for ( i = 0 ; i < MAX_GENTITIES ; i++ ) - { - //Written this way for optimal speed, even though it doesn't look pretty. + for (i = 0; i < MAX_GENTITIES; i++) { + // Written this way for optimal speed, even though it doesn't look pretty. //(we don't want to spend the time assigning pointers as it does take - //a small precious fraction of time and adds up in the loop.. so says - //the precision timer!) + // a small precious fraction of time and adds up in the loop.. so says + // the precision timer!) - if (cg_entities[i].currentState.eType == ET_PLAYER || - cg_entities[i].currentState.eType == ET_NPC) - { + if (cg_entities[i].currentState.eType == ET_PLAYER || cg_entities[i].currentState.eType == ET_NPC) { // Need a new playerState_t on Xbox - VectorCopy( cg_entities[i].currentState.pos.trBase, cgSendPS[i]->origin ); - VectorCopy( cg_entities[i].currentState.pos.trDelta, cgSendPS[i]->velocity ); + VectorCopy(cg_entities[i].currentState.pos.trBase, cgSendPS[i]->origin); + VectorCopy(cg_entities[i].currentState.pos.trDelta, cgSendPS[i]->velocity); cgSendPS[i]->saberLockFrame = cg_entities[i].currentState.forceFrame; cgSendPS[i]->legsAnim = cg_entities[i].currentState.legsAnim; cgSendPS[i]->torsoAnim = cg_entities[i].currentState.torsoAnim; @@ -1090,34 +1000,32 @@ void CG_PredictPlayerState( void ) { } } - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { cg_entities[cg.predictedPlayerState.clientNum].playerState = &cg.predictedPlayerState; cg_entities[cg.predictedPlayerState.m_iVehicleNum].playerState = &cg.predictedVehicleState; - //use the player command time, because we are running with the player cmds (this is even the case - //on the server) + // use the player command time, because we are running with the player cmds (this is even the case + // on the server) cg.predictedVehicleState.commandTime = cg.predictedPlayerState.commandTime; } // run cmds moved = qfalse; - for ( cmdNum = current - CMD_BACKUP + 1 ; cmdNum <= current ; cmdNum++ ) { + for (cmdNum = current - CMD_BACKUP + 1; cmdNum <= current; cmdNum++) { // get the command - trap->GetUserCmd( cmdNum, &cg_pmove.cmd ); + trap->GetUserCmd(cmdNum, &cg_pmove.cmd); - if ( cg_pmove.pmove_fixed ) { - PM_UpdateViewAngles( cg_pmove.ps, &cg_pmove.cmd ); + if (cg_pmove.pmove_fixed) { + PM_UpdateViewAngles(cg_pmove.ps, &cg_pmove.cmd); } // don't do anything if the time is before the snapshot player time - if ( cg_pmove.cmd.serverTime <= cg.predictedPlayerState.commandTime ) - { + if (cg_pmove.cmd.serverTime <= cg.predictedPlayerState.commandTime) { continue; } // don't do anything if the command was from a previous map_restart - if ( cg_pmove.cmd.serverTime > latestCmd.serverTime ) { + if (cg_pmove.cmd.serverTime > latestCmd.serverTime) { continue; } @@ -1126,118 +1034,115 @@ void CG_PredictPlayerState( void ) { // from the snapshot, but on a wan we will have // to predict several commands to get to the point // we want to compare - if ( CG_Piloting(oldPlayerState.m_iVehicleNum) && - cg.predictedVehicleState.commandTime == oldVehicleState.commandTime ) - { - vec3_t delta; - float len; + if (CG_Piloting(oldPlayerState.m_iVehicleNum) && cg.predictedVehicleState.commandTime == oldVehicleState.commandTime) { + vec3_t delta; + float len; - if ( cg.thisFrameTeleport ) { + if (cg.thisFrameTeleport) { // a teleport will not cause an error decay - VectorClear( cg.predictedError ); - if ( cg_showVehMiss.integer ) { - trap->Print( "VEH PredictionTeleport\n" ); + VectorClear(cg.predictedError); + if (cg_showVehMiss.integer) { + trap->Print("VEH PredictionTeleport\n"); } cg.thisFrameTeleport = qfalse; } else { - vec3_t adjusted; - CG_AdjustPositionForMover( cg.predictedVehicleState.origin, - cg.predictedVehicleState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted ); + vec3_t adjusted; + CG_AdjustPositionForMover(cg.predictedVehicleState.origin, cg.predictedVehicleState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted); - if ( cg_showVehMiss.integer ) { - if (!VectorCompare( oldVehicleState.origin, adjusted )) { + if (cg_showVehMiss.integer) { + if (!VectorCompare(oldVehicleState.origin, adjusted)) { trap->Print("VEH prediction error\n"); } } - VectorSubtract( oldVehicleState.origin, adjusted, delta ); - len = VectorLength( delta ); - if ( len > 0.1 ) { - if ( cg_showVehMiss.integer ) { + VectorSubtract(oldVehicleState.origin, adjusted, delta); + len = VectorLength(delta); + if (len > 0.1) { + if (cg_showVehMiss.integer) { trap->Print("VEH Prediction miss: %f\n", len); } - if ( cg_errorDecay.integer ) { - int t; - float f; + if (cg_errorDecay.integer) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f < 0 ) { + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f < 0) { f = 0; } - if ( f > 0 && cg_showVehMiss.integer ) { + if (f > 0 && cg_showVehMiss.integer) { trap->Print("VEH Double prediction decay: %f\n", f); } - VectorScale( cg.predictedError, f, cg.predictedError ); + VectorScale(cg.predictedError, f, cg.predictedError); } else { - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); } - VectorAdd( delta, cg.predictedError, cg.predictedError ); + VectorAdd(delta, cg.predictedError, cg.predictedError); cg.predictedErrorTime = cg.oldTime; } // - if ( cg_showVehMiss.integer ) { - if (!VectorCompare( oldVehicleState.vehOrientation, cg.predictedVehicleState.vehOrientation )) { + if (cg_showVehMiss.integer) { + if (!VectorCompare(oldVehicleState.vehOrientation, cg.predictedVehicleState.vehOrientation)) { trap->Print("VEH orient prediction error\n"); - trap->Print("VEH pitch prediction miss: %f\n", AngleSubtract( oldVehicleState.vehOrientation[0], cg.predictedVehicleState.vehOrientation[0] ) ); - trap->Print("VEH yaw prediction miss: %f\n", AngleSubtract( oldVehicleState.vehOrientation[1], cg.predictedVehicleState.vehOrientation[1] ) ); - trap->Print("VEH roll prediction miss: %f\n", AngleSubtract( oldVehicleState.vehOrientation[2], cg.predictedVehicleState.vehOrientation[2] ) ); + trap->Print("VEH pitch prediction miss: %f\n", + AngleSubtract(oldVehicleState.vehOrientation[0], cg.predictedVehicleState.vehOrientation[0])); + trap->Print("VEH yaw prediction miss: %f\n", + AngleSubtract(oldVehicleState.vehOrientation[1], cg.predictedVehicleState.vehOrientation[1])); + trap->Print("VEH roll prediction miss: %f\n", + AngleSubtract(oldVehicleState.vehOrientation[2], cg.predictedVehicleState.vehOrientation[2])); } } } - } - else if ( !oldPlayerState.m_iVehicleNum && //don't do pred err on ps while riding veh - cg.predictedPlayerState.commandTime == oldPlayerState.commandTime ) - { - vec3_t delta; - float len; + } else if (!oldPlayerState.m_iVehicleNum && // don't do pred err on ps while riding veh + cg.predictedPlayerState.commandTime == oldPlayerState.commandTime) { + vec3_t delta; + float len; - if ( cg.thisFrameTeleport ) { + if (cg.thisFrameTeleport) { // a teleport will not cause an error decay - VectorClear( cg.predictedError ); - if ( cg_showMiss.integer ) { - trap->Print( "PredictionTeleport\n" ); + VectorClear(cg.predictedError); + if (cg_showMiss.integer) { + trap->Print("PredictionTeleport\n"); } cg.thisFrameTeleport = qfalse; } else { - vec3_t adjusted; - CG_AdjustPositionForMover( cg.predictedPlayerState.origin, - cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted ); + vec3_t adjusted; + CG_AdjustPositionForMover(cg.predictedPlayerState.origin, cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.oldTime, adjusted); - if ( cg_showMiss.integer ) { - if (!VectorCompare( oldPlayerState.origin, adjusted )) { + if (cg_showMiss.integer) { + if (!VectorCompare(oldPlayerState.origin, adjusted)) { trap->Print("prediction error\n"); } } - VectorSubtract( oldPlayerState.origin, adjusted, delta ); - len = VectorLength( delta ); - if ( len > 0.1 ) { - if ( cg_showMiss.integer ) { + VectorSubtract(oldPlayerState.origin, adjusted, delta); + len = VectorLength(delta); + if (len > 0.1) { + if (cg_showMiss.integer) { trap->Print("Prediction miss: %f\n", len); } - if ( cg_errorDecay.integer ) { - int t; - float f; + if (cg_errorDecay.integer) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f < 0 ) { + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f < 0) { f = 0; } - if ( f > 0 && cg_showMiss.integer ) { + if (f > 0 && cg_showMiss.integer) { trap->Print("Double prediction decay: %f\n", f); } - VectorScale( cg.predictedError, f, cg.predictedError ); + VectorScale(cg.predictedError, f, cg.predictedError); } else { - VectorClear( cg.predictedError ); + VectorClear(cg.predictedError); } - VectorAdd( delta, cg.predictedError, cg.predictedError ); + VectorAdd(delta, cg.predictedError, cg.predictedError); cg.predictedErrorTime = cg.oldTime; } } } - if ( cg_pmove.pmove_fixed ) { - cg_pmove.cmd.serverTime = ((cg_pmove.cmd.serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer; + if (cg_pmove.pmove_fixed) { + cg_pmove.cmd.serverTime = ((cg_pmove.cmd.serverTime + pmove_msec.integer - 1) / pmove_msec.integer) * pmove_msec.integer; } cg_pmove.animations = bgAllAnims[pEnt->localAnimIndex].anims; @@ -1249,54 +1154,45 @@ void CG_PredictPlayerState( void ) { cg_pmove.nonHumanoid = (pEnt->localAnimIndex > 0); - if (cg.snap && cg.snap->ps.saberLockTime > cg.time) - { + if (cg.snap && cg.snap->ps.saberLockTime > cg.time) { centity_t *blockOpp = &cg_entities[cg.snap->ps.saberLockEnemy]; - if (blockOpp) - { + if (blockOpp) { vec3_t lockDir, lockAng; - VectorSubtract( blockOpp->lerpOrigin, cg.snap->ps.origin, lockDir ); + VectorSubtract(blockOpp->lerpOrigin, cg.snap->ps.origin, lockDir); vectoangles(lockDir, lockAng); VectorCopy(lockAng, cg_pmove.ps->viewangles); } } - //THIS is pretty much bad, but... + // THIS is pretty much bad, but... cg_pmove.ps->fd.saberAnimLevelBase = cg_pmove.ps->fd.saberAnimLevel; - if ( cg_pmove.ps->saberHolstered == 1 ) - { - if ( ci->saber[0].numBlades > 0 ) - { + if (cg_pmove.ps->saberHolstered == 1) { + if (ci->saber[0].numBlades > 0) { cg_pmove.ps->fd.saberAnimLevelBase = SS_STAFF; - } - else if ( ci->saber[1].model[0] ) - { + } else if (ci->saber[1].model[0]) { cg_pmove.ps->fd.saberAnimLevelBase = SS_DUAL; } } - Pmove (&cg_pmove); + Pmove(&cg_pmove); if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum) && - cg.predictedPlayerState.pm_type != PM_INTERMISSION) - { //we're riding a vehicle, let's predict it + cg.predictedPlayerState.pm_type != PM_INTERMISSION) { // we're riding a vehicle, let's predict it centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; int x, zd, zu; - if (veh->m_pVehicle) - { //make sure pointer is set up to go to our predicted state + if (veh->m_pVehicle) { // make sure pointer is set up to go to our predicted state veh->m_pVehicle->m_vOrientation = &cg.predictedVehicleState.vehOrientation[0]; - //keep this updated based on what the playerstate says + // keep this updated based on what the playerstate says veh->m_pVehicle->m_iRemovedSurfaces = cg.predictedVehicleState.vehSurfaces; - trap->GetUserCmd( cmdNum, &veh->m_pVehicle->m_ucmd ); + trap->GetUserCmd(cmdNum, &veh->m_pVehicle->m_ucmd); - if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) - { //forced input if "chat bubble" is up + if (veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK) { // forced input if "chat bubble" is up veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; veh->m_pVehicle->m_ucmd.forwardmove = 0; veh->m_pVehicle->m_ucmd.rightmove = 0; @@ -1326,15 +1222,15 @@ void CG_PredictPlayerState( void ) { cg_vehPmove.mins[2] = -zd; cg_vehPmove.maxs[2] = zu; */ - //I think this was actually wrong.. just copy-pasted from id code. Oh well. - x = (veh->currentState.solid)&255; - zd = (veh->currentState.solid>>8)&255; - zu = (veh->currentState.solid>>15)&255; + // I think this was actually wrong.. just copy-pasted from id code. Oh well. + x = (veh->currentState.solid) & 255; + zd = (veh->currentState.solid >> 8) & 255; + zu = (veh->currentState.solid >> 15) & 255; - zu -= 32; //I don't quite get the reason for this. + zu -= 32; // I don't quite get the reason for this. zd = -zd; - //z/y must be symmetrical (blah) + // z/y must be symmetrical (blah) cg_vehPmove.mins[0] = cg_vehPmove.mins[1] = -x; cg_vehPmove.maxs[0] = cg_vehPmove.maxs[1] = x; cg_vehPmove.mins[2] = zd; @@ -1342,8 +1238,7 @@ void CG_PredictPlayerState( void ) { VectorCopy(veh->modelScale, cg_vehPmove.modelScale); - if (!cg_vehPmoveSet) - { //do all the one-time things + if (!cg_vehPmoveSet) { // do all the one-time things cg_vehPmove.trace = CG_Trace; cg_vehPmove.pointcontents = CG_PointContents; cg_vehPmove.tracemask = MASK_PLAYERSOLID; @@ -1357,30 +1252,30 @@ void CG_PredictPlayerState( void ) { cg_vehPmoveSet = qtrue; } - cg_vehPmove.noFootsteps = ( cgs.dmflags & DF_NO_FOOTSTEPS ) > 0; + cg_vehPmove.noFootsteps = (cgs.dmflags & DF_NO_FOOTSTEPS) > 0; cg_vehPmove.pmove_fixed = pmove_fixed.integer; cg_vehPmove.pmove_msec = pmove_msec.integer; cg_entities[cg.predictedPlayerState.clientNum].playerState = &cg.predictedPlayerState; veh->playerState = &cg.predictedVehicleState; - //update boarding value sent from server. boarding is not predicted, but no big deal + // update boarding value sent from server. boarding is not predicted, but no big deal veh->m_pVehicle->m_iBoarding = cg.predictedVehicleState.vehBoarding; Pmove(&cg_vehPmove); /* if ( !cg_paused.integer ) { - Com_Printf( "%d - PITCH change %4.2f\n", cg.time, AngleSubtract(veh->m_pVehicle->m_vOrientation[0],veh->m_pVehicle->m_vPrevOrientation[0]) ); + Com_Printf( "%d - PITCH change %4.2f\n", cg.time, AngleSubtract(veh->m_pVehicle->m_vOrientation[0],veh->m_pVehicle->m_vPrevOrientation[0]) + ); } */ - if ( cg_showVehBounds.integer ) - { + if (cg_showVehBounds.integer) { vec3_t NPCDEBUG_RED = {1.0, 0.0, 0.0}; vec3_t absmin, absmax; - VectorAdd( cg_vehPmove.ps->origin, cg_vehPmove.mins, absmin ); - VectorAdd( cg_vehPmove.ps->origin, cg_vehPmove.maxs, absmax ); - CG_Cube( absmin, absmax, NPCDEBUG_RED, 0.25 ); + VectorAdd(cg_vehPmove.ps->origin, cg_vehPmove.mins, absmin); + VectorAdd(cg_vehPmove.ps->origin, cg_vehPmove.maxs, absmax); + CG_Cube(absmin, absmax, NPCDEBUG_RED, 0.25); } } } @@ -1391,66 +1286,57 @@ void CG_PredictPlayerState( void ) { CG_TouchTriggerPrediction(); // check for predictable events that changed from previous predictions - //CG_CheckChangedPredictableEvents(&cg.predictedPlayerState); + // CG_CheckChangedPredictableEvents(&cg.predictedPlayerState); } - if ( cg_showMiss.integer > 1 ) { - trap->Print( "[%i : %i] ", cg_pmove.cmd.serverTime, cg.time ); + if (cg_showMiss.integer > 1) { + trap->Print("[%i : %i] ", cg_pmove.cmd.serverTime, cg.time); } - if ( !moved ) { - if ( cg_showMiss.integer ) { - trap->Print( "not moved\n" ); + if (!moved) { + if (cg_showMiss.integer) { + trap->Print("not moved\n"); } goto revertES; } - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { - CG_AdjustPositionForMover( cg.predictedVehicleState.origin, - cg.predictedVehicleState.groundEntityNum, - cg.physicsTime, cg.time, cg.predictedVehicleState.origin ); - } - else - { + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { + CG_AdjustPositionForMover(cg.predictedVehicleState.origin, cg.predictedVehicleState.groundEntityNum, cg.physicsTime, cg.time, + cg.predictedVehicleState.origin); + } else { // adjust for the movement of the groundentity - CG_AdjustPositionForMover( cg.predictedPlayerState.origin, - cg.predictedPlayerState.groundEntityNum, - cg.physicsTime, cg.time, cg.predictedPlayerState.origin ); + CG_AdjustPositionForMover(cg.predictedPlayerState.origin, cg.predictedPlayerState.groundEntityNum, cg.physicsTime, cg.time, + cg.predictedPlayerState.origin); } - if ( cg_showMiss.integer ) { + if (cg_showMiss.integer) { if (cg.predictedPlayerState.eventSequence > oldPlayerState.eventSequence + MAX_PS_EVENTS) { trap->Print("WARNING: dropped event\n"); } } // fire events and other transition triggered things - CG_TransitionPlayerState( &cg.predictedPlayerState, &oldPlayerState ); + CG_TransitionPlayerState(&cg.predictedPlayerState, &oldPlayerState); - if ( cg_showMiss.integer ) { + if (cg_showMiss.integer) { if (cg.eventSequence > cg.predictedPlayerState.eventSequence) { trap->Print("WARNING: double event\n"); cg.eventSequence = cg.predictedPlayerState.eventSequence; } } - if (cg.predictedPlayerState.m_iVehicleNum && - !CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { //a passenger on this vehicle, bolt them in + if (cg.predictedPlayerState.m_iVehicleNum && !CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { // a passenger on this vehicle, bolt them in centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; VectorCopy(veh->lerpAngles, cg.predictedPlayerState.viewangles); VectorCopy(veh->lerpOrigin, cg.predictedPlayerState.origin); } revertES: - if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) - { + if (CG_Piloting(cg.predictedPlayerState.m_iVehicleNum)) { centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if (veh->m_pVehicle) - { - //switch ptr back for this ent in case we stop riding it + if (veh->m_pVehicle) { + // switch ptr back for this ent in case we stop riding it veh->m_pVehicle->m_vOrientation = &cgSendPS[veh->currentState.number]->vehOrientation[0]; } @@ -1458,12 +1344,9 @@ void CG_PredictPlayerState( void ) { veh->playerState = cgSendPS[veh->currentState.number]; } - //copy some stuff back into the entstates to help actually "predict" them if applicable - for ( i = 0 ; i < MAX_GENTITIES ; i++ ) - { - if (cg_entities[i].currentState.eType == ET_PLAYER || - cg_entities[i].currentState.eType == ET_NPC) - { + // copy some stuff back into the entstates to help actually "predict" them if applicable + for (i = 0; i < MAX_GENTITIES; i++) { + if (cg_entities[i].currentState.eType == ET_PLAYER || cg_entities[i].currentState.eType == ET_NPC) { cg_entities[i].currentState.torsoAnim = cgSendPS[i]->torsoAnim; cg_entities[i].currentState.legsAnim = cgSendPS[i]->legsAnim; cg_entities[i].currentState.forceFrame = cgSendPS[i]->saberLockFrame; diff --git a/codemp/cgame/cg_saga.c b/codemp/cgame/cg_saga.c index 9d688fbdef..cd2bf48702 100644 --- a/codemp/cgame/cg_saga.c +++ b/codemp/cgame/cg_saga.c @@ -35,82 +35,66 @@ along with this program; if not, see . int cgSiegeRoundState = 0; int cgSiegeRoundTime = 0; -static char team1[512]; -static char team2[512]; +static char team1[512]; +static char team2[512]; -int team1Timed = 0; -int team2Timed = 0; +int team1Timed = 0; +int team2Timed = 0; -int cgSiegeTeam1PlShader = 0; -int cgSiegeTeam2PlShader = 0; +int cgSiegeTeam1PlShader = 0; +int cgSiegeTeam2PlShader = 0; static char cgParseObjectives[MAX_SIEGE_INFO_SIZE]; -extern void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded); //cg_players.c +extern void CG_LoadCISounds(clientInfo_t *ci, qboolean modelloaded); // cg_players.c -void CG_DrawSiegeMessage( const char *str, int objectiveScreen ); -void CG_DrawSiegeMessageNonMenu( const char *str ); +void CG_DrawSiegeMessage(const char *str, int objectiveScreen); +void CG_DrawSiegeMessageNonMenu(const char *str); void CG_SiegeBriefingDisplay(int team, int dontshow); -void CG_PrecacheSiegeObjectiveAssetsForTeam(int myTeam) -{ - char teamstr[64]; - char objstr[256]; - char foundobjective[MAX_SIEGE_INFO_SIZE]; +void CG_PrecacheSiegeObjectiveAssetsForTeam(int myTeam) { + char teamstr[64]; + char objstr[256]; + char foundobjective[MAX_SIEGE_INFO_SIZE]; - if (!siege_valid) - { - trap->Error( ERR_DROP, "Siege data does not exist on client!\n"); + if (!siege_valid) { + trap->Error(ERR_DROP, "Siege data does not exist on client!\n"); return; } - if (myTeam == SIEGETEAM_TEAM1) - { + if (myTeam == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { int i = 1; - while (i < 32) - { //eh, just try 32 I guess + while (i < 32) { // eh, just try 32 I guess Com_sprintf(objstr, sizeof(objstr), "Objective%i", i); - if (BG_SiegeGetValueGroup(cgParseObjectives, objstr, foundobjective)) - { + if (BG_SiegeGetValueGroup(cgParseObjectives, objstr, foundobjective)) { char str[MAX_QPATH]; - if (BG_SiegeGetPairedValue(foundobjective, "sound_team1", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "sound_team1", str)) { trap->S_RegisterSound(str); } - if (BG_SiegeGetPairedValue(foundobjective, "sound_team2", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "sound_team2", str)) { trap->S_RegisterSound(str); } - if (BG_SiegeGetPairedValue(foundobjective, "objgfx", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "objgfx", str)) { trap->R_RegisterShaderNoMip(str); } - if (BG_SiegeGetPairedValue(foundobjective, "mapicon", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "mapicon", str)) { trap->R_RegisterShaderNoMip(str); } - if (BG_SiegeGetPairedValue(foundobjective, "litmapicon", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "litmapicon", str)) { trap->R_RegisterShaderNoMip(str); } - if (BG_SiegeGetPairedValue(foundobjective, "donemapicon", str)) - { + if (BG_SiegeGetPairedValue(foundobjective, "donemapicon", str)) { trap->R_RegisterShaderNoMip(str); } - } - else - { //no more + } else { // no more break; } i++; @@ -118,41 +102,34 @@ void CG_PrecacheSiegeObjectiveAssetsForTeam(int myTeam) } } -void CG_PrecachePlayersForSiegeTeam(int team) -{ +void CG_PrecachePlayersForSiegeTeam(int team) { siegeTeam_t *stm; int i = 0; stm = BG_SiegeFindThemeForTeam(team); - if (!stm) - { //invalid team/no theme for team? + if (!stm) { // invalid team/no theme for team? return; } - while (i < stm->numClasses) - { + while (i < stm->numClasses) { siegeClass_t *scl = stm->classes[i]; - if (scl->forcedModel[0]) - { + if (scl->forcedModel[0]) { clientInfo_t fake; memset(&fake, 0, sizeof(fake)); Q_strncpyz(fake.modelName, scl->forcedModel, sizeof(fake.modelName)); trap->R_RegisterModel(va("models/players/%s/model.glm", scl->forcedModel)); - if (scl->forcedSkin[0]) - { + if (scl->forcedSkin[0]) { trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", scl->forcedModel, scl->forcedSkin)); Q_strncpyz(fake.skinName, scl->forcedSkin, sizeof(fake.modelName)); - } - else - { + } else { Q_strncpyz(fake.skinName, "default", sizeof(fake.skinName)); } - //precache the sounds for the model... + // precache the sounds for the model... CG_LoadCISounds(&fake, qtrue); } @@ -160,39 +137,36 @@ void CG_PrecachePlayersForSiegeTeam(int team) } } -void CG_InitSiegeMode(void) -{ - char levelname[MAX_QPATH]; - char btime[1024]; - char teams[2048]; - char teamInfo[MAX_SIEGE_INFO_SIZE]; - int len = 0; - int i = 0; - int j = 0; - siegeClass_t *cl; - siegeTeam_t *sTeam; - fileHandle_t f; - char teamIcon[128]; - - if (cgs.gametype != GT_SIEGE) - { +void CG_InitSiegeMode(void) { + char levelname[MAX_QPATH]; + char btime[1024]; + char teams[2048]; + char teamInfo[MAX_SIEGE_INFO_SIZE]; + int len = 0; + int i = 0; + int j = 0; + siegeClass_t *cl; + siegeTeam_t *sTeam; + fileHandle_t f; + char teamIcon[128]; + + if (cgs.gametype != GT_SIEGE) { goto failure; } Com_sprintf(levelname, sizeof(levelname), "%s.siege", cgs.rawmapname); - if (!levelname[0]) - { + if (!levelname[0]) { goto failure; } len = trap->FS_Open(levelname, &f, FS_READ); - if ( !f ) { + if (!f) { goto failure; } - if ( len >= MAX_SIEGE_INFO_SIZE ) { - trap->FS_Close( f ); + if (len >= MAX_SIEGE_INFO_SIZE) { + trap->FS_Close(f); goto failure; } @@ -202,211 +176,153 @@ void CG_InitSiegeMode(void) siege_valid = 1; - if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) - { + if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) { char buf[1024]; trap->Cvar_VariableStringBuffer("cg_siegeTeam1", buf, 1024); - if (buf[0] && Q_stricmp(buf, "none")) - { + if (buf[0] && Q_stricmp(buf, "none")) { Q_strncpyz(team1, buf, sizeof(team1)); - } - else - { + } else { BG_SiegeGetPairedValue(teams, "team1", team1); } - if (team1[0] == '@') - { //it's a damn stringed reference. + if (team1[0] == '@') { // it's a damn stringed reference. char b[256]; - trap->SE_GetStringTextString(team1+1, b, 256); + trap->SE_GetStringTextString(team1 + 1, b, 256); trap->Cvar_Set("cg_siegeTeam1Name", b); - } - else - { + } else { trap->Cvar_Set("cg_siegeTeam1Name", team1); } trap->Cvar_VariableStringBuffer("cg_siegeTeam2", buf, 1024); - if (buf[0] && Q_stricmp(buf, "none")) - { + if (buf[0] && Q_stricmp(buf, "none")) { Q_strncpyz(team2, buf, sizeof(team2)); - } - else - { + } else { BG_SiegeGetPairedValue(teams, "team2", team2); } - if (team2[0] == '@') - { //it's a damn stringed reference. + if (team2[0] == '@') { // it's a damn stringed reference. char b[256]; - trap->SE_GetStringTextString(team2+1, b, 256); + trap->SE_GetStringTextString(team2 + 1, b, 256); trap->Cvar_Set("cg_siegeTeam2Name", b); - } - else - { + } else { trap->Cvar_Set("cg_siegeTeam2Name", team2); } - } - else - { - trap->Error( ERR_DROP, "Siege teams not defined"); + } else { + trap->Error(ERR_DROP, "Siege teams not defined"); } - if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "TeamIcon", teamIcon)) - { - trap->Cvar_Set( "team1_icon", teamIcon); + if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "TeamIcon", teamIcon)) { + trap->Cvar_Set("team1_icon", teamIcon); } - if (BG_SiegeGetPairedValue(teamInfo, "Timed", btime)) - { - team1Timed = atoi(btime)*1000; - CG_SetSiegeTimerCvar ( team1Timed ); - } - else - { + if (BG_SiegeGetPairedValue(teamInfo, "Timed", btime)) { + team1Timed = atoi(btime) * 1000; + CG_SetSiegeTimerCvar(team1Timed); + } else { team1Timed = 0; } - } - else - { - trap->Error( ERR_DROP, "No team entry for '%s'\n", team1); + } else { + trap->Error(ERR_DROP, "No team entry for '%s'\n", team1); } - if (BG_SiegeGetPairedValue(siege_info, "mapgraphic", teamInfo)) - { + if (BG_SiegeGetPairedValue(siege_info, "mapgraphic", teamInfo)) { trap->Cvar_Set("siege_mapgraphic", teamInfo); - } - else - { + } else { trap->Cvar_Set("siege_mapgraphic", "gfx/mplevels/siege1_hoth"); } - if (BG_SiegeGetPairedValue(siege_info, "missionname", teamInfo)) - { + if (BG_SiegeGetPairedValue(siege_info, "missionname", teamInfo)) { trap->Cvar_Set("siege_missionname", teamInfo); - } - else - { + } else { trap->Cvar_Set("siege_missionname", " "); } - if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "TeamIcon", teamIcon)) - { - trap->Cvar_Set( "team2_icon", teamIcon); + if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "TeamIcon", teamIcon)) { + trap->Cvar_Set("team2_icon", teamIcon); } - if (BG_SiegeGetPairedValue(teamInfo, "Timed", btime)) - { - team2Timed = atoi(btime)*1000; - CG_SetSiegeTimerCvar ( team2Timed ); - } - else - { + if (BG_SiegeGetPairedValue(teamInfo, "Timed", btime)) { + team2Timed = atoi(btime) * 1000; + CG_SetSiegeTimerCvar(team2Timed); + } else { team2Timed = 0; } - } - else - { - trap->Error( ERR_DROP, "No team entry for '%s'\n", team2); + } else { + trap->Error(ERR_DROP, "No team entry for '%s'\n", team2); } - //Load the player class types + // Load the player class types BG_SiegeLoadClasses(NULL); - if (!bgNumSiegeClasses) - { //We didn't find any?! - trap->Error( ERR_DROP, "Couldn't find any player classes for Siege"); + if (!bgNumSiegeClasses) { // We didn't find any?! + trap->Error(ERR_DROP, "Couldn't find any player classes for Siege"); } - //Now load the teams since we have class data. + // Now load the teams since we have class data. BG_SiegeLoadTeams(); - if (!bgNumSiegeTeams) - { //React same as with classes. - trap->Error( ERR_DROP, "Couldn't find any player teams for Siege"); + if (!bgNumSiegeTeams) { // React same as with classes. + trap->Error(ERR_DROP, "Couldn't find any player teams for Siege"); } - //Get and set the team themes for each team. This will control which classes can be - //used on each team. - if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) - { + // Get and set the team themes for each team. This will control which classes can be + // used on each team. + if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM1, btime); } - if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", btime)) - { + if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", btime)) { cgSiegeTeam1PlShader = trap->R_RegisterShaderNoMip(btime); - } - else - { + } else { cgSiegeTeam1PlShader = 0; } } - if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) - { + if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM2, btime); } - if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", btime)) - { + if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", btime)) { cgSiegeTeam2PlShader = trap->R_RegisterShaderNoMip(btime); - } - else - { + } else { cgSiegeTeam2PlShader = 0; } } - //Now go through the classes used by the loaded teams and try to precache - //any forced models or forced skins. + // Now go through the classes used by the loaded teams and try to precache + // any forced models or forced skins. i = SIEGETEAM_TEAM1; - while (i <= SIEGETEAM_TEAM2) - { + while (i <= SIEGETEAM_TEAM2) { j = 0; sTeam = BG_SiegeFindThemeForTeam(i); - if (!sTeam) - { + if (!sTeam) { i++; continue; } - //Get custom team shaders while we're at it. - if (i == SIEGETEAM_TEAM1) - { + // Get custom team shaders while we're at it. + if (i == SIEGETEAM_TEAM1) { cgSiegeTeam1PlShader = sTeam->friendlyShader; - } - else if (i == SIEGETEAM_TEAM2) - { + } else if (i == SIEGETEAM_TEAM2) { cgSiegeTeam2PlShader = sTeam->friendlyShader; } - while (j < sTeam->numClasses) - { + while (j < sTeam->numClasses) { cl = sTeam->classes[j]; - if (cl->forcedModel[0]) - { //This class has a forced model, so precache it. + if (cl->forcedModel[0]) { // This class has a forced model, so precache it. trap->R_RegisterModel(va("models/players/%s/model.glm", cl->forcedModel)); - if (cl->forcedSkin[0]) - { //also has a forced skin, precache it. + if (cl->forcedSkin[0]) { // also has a forced skin, precache it. char *useSkinName; - if (strchr(cl->forcedSkin, '|')) - {//three part skin + if (strchr(cl->forcedSkin, '|')) { // three part skin useSkinName = va("models/players/%s/|%s", cl->forcedModel, cl->forcedSkin); - } - else - { + } else { useSkinName = va("models/players/%s/model_%s.skin", cl->forcedModel, cl->forcedSkin); } @@ -419,7 +335,7 @@ void CG_InitSiegeMode(void) i++; } - //precache saber data for classes that use sabers on both teams + // precache saber data for classes that use sabers on both teams BG_PrecacheSabersForSiegeTeam(SIEGETEAM_TEAM1); BG_PrecacheSabersForSiegeTeam(SIEGETEAM_TEAM2); @@ -437,24 +353,18 @@ void CG_InitSiegeMode(void) siege_valid = 0; } -static char QINLINE *CG_SiegeObjectiveBuffer(int team, int objective) -{ +static char QINLINE *CG_SiegeObjectiveBuffer(int team, int objective) { static char buf[8192]; char teamstr[1024]; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { //found the team group - if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), buf)) - { //found the objective group + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { // found the team group + if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), buf)) { // found the objective group return buf; } } @@ -462,103 +372,75 @@ static char QINLINE *CG_SiegeObjectiveBuffer(int team, int objective) return NULL; } -void CG_ParseSiegeObjectiveStatus(const char *str) -{ +void CG_ParseSiegeObjectiveStatus(const char *str) { int i = 0; - int team = SIEGETEAM_TEAM1; + int team = SIEGETEAM_TEAM1; char *cvarName; char *s; int objectiveNum = 0; - if (!str || !str[0]) - { + if (!str || !str[0]) { return; } - while (str[i]) - { - if (str[i] == '|') - { //switch over to team2, this is the next section - team = SIEGETEAM_TEAM2; + while (str[i]) { + if (str[i] == '|') { // switch over to team2, this is the next section + team = SIEGETEAM_TEAM2; objectiveNum = 0; - } - else if (str[i] == '-') - { + } else if (str[i] == '-') { objectiveNum++; i++; cvarName = va("team%i_objective%i", team, objectiveNum); - if (str[i] == '1') - { //it's completed + if (str[i] == '1') { // it's completed trap->Cvar_Set(cvarName, "1"); - } - else - { //otherwise assume it is not + } else { // otherwise assume it is not trap->Cvar_Set(cvarName, "0"); } s = CG_SiegeObjectiveBuffer(team, objectiveNum); - if (s && s[0]) - { //now set the description and graphic cvars to by read by the menu + if (s && s[0]) { // now set the description and graphic cvars to by read by the menu char buffer[8192]; cvarName = va("team%i_objective%i_longdesc", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "objdesc", buffer)) - { + if (BG_SiegeGetPairedValue(s, "objdesc", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "UNSPECIFIED"); } cvarName = va("team%i_objective%i_gfx", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "objgfx", buffer)) - { + if (BG_SiegeGetPairedValue(s, "objgfx", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "UNSPECIFIED"); } cvarName = va("team%i_objective%i_mapicon", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "mapicon", buffer)) - { + if (BG_SiegeGetPairedValue(s, "mapicon", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "UNSPECIFIED"); } cvarName = va("team%i_objective%i_litmapicon", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "litmapicon", buffer)) - { + if (BG_SiegeGetPairedValue(s, "litmapicon", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "UNSPECIFIED"); } cvarName = va("team%i_objective%i_donemapicon", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "donemapicon", buffer)) - { + if (BG_SiegeGetPairedValue(s, "donemapicon", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "UNSPECIFIED"); } cvarName = va("team%i_objective%i_mappos", team, objectiveNum); - if (BG_SiegeGetPairedValue(s, "mappos", buffer)) - { + if (BG_SiegeGetPairedValue(s, "mappos", buffer)) { trap->Cvar_Set(cvarName, buffer); - } - else - { + } else { trap->Cvar_Set(cvarName, "0 0 32 32"); } } @@ -566,88 +448,68 @@ void CG_ParseSiegeObjectiveStatus(const char *str) i++; } - if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR) - { //update menu cvars + if (cg.predictedPlayerState.persistant[PERS_TEAM] != TEAM_SPECTATOR) { // update menu cvars CG_SiegeBriefingDisplay(cg.predictedPlayerState.persistant[PERS_TEAM], 1); } } -void CG_SiegeRoundOver(centity_t *ent, int won) -{ - int myTeam; - char teamstr[64]; - char appstring[1024]; - char soundstr[1024]; - int success = 0; - playerState_t *ps = NULL; - - if (!siege_valid) - { - trap->Error( ERR_DROP, "ERROR: Siege data does not exist on client!\n"); +void CG_SiegeRoundOver(centity_t *ent, int won) { + int myTeam; + char teamstr[64]; + char appstring[1024]; + char soundstr[1024]; + int success = 0; + playerState_t *ps = NULL; + + if (!siege_valid) { + trap->Error(ERR_DROP, "ERROR: Siege data does not exist on client!\n"); return; } - if (cg.snap) - { //this should always be true, if it isn't though use the predicted ps as a fallback + if (cg.snap) { // this should always be true, if it isn't though use the predicted ps as a fallback ps = &cg.snap->ps; - } - else - { + } else { ps = &cg.predictedPlayerState; } - if (!ps) - { + if (!ps) { assert(0); return; } myTeam = ps->persistant[PERS_TEAM]; - if (myTeam == TEAM_SPECTATOR) - { + if (myTeam == TEAM_SPECTATOR) { return; } - if (myTeam == SIEGETEAM_TEAM1) - { + if (myTeam == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { - if (won == myTeam) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { + if (won == myTeam) { success = BG_SiegeGetPairedValue(cgParseObjectives, "wonround", appstring); - } - else - { + } else { success = BG_SiegeGetPairedValue(cgParseObjectives, "lostround", appstring); } - if (success) - { + if (success) { CG_DrawSiegeMessage(appstring, 0); } appstring[0] = 0; soundstr[0] = 0; - if (myTeam == won) - { + if (myTeam == won) { Com_sprintf(teamstr, sizeof(teamstr), "roundover_sound_wewon"); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), "roundover_sound_welost"); } - if (BG_SiegeGetPairedValue(cgParseObjectives, teamstr, appstring)) - { + if (BG_SiegeGetPairedValue(cgParseObjectives, teamstr, appstring)) { Com_sprintf(soundstr, sizeof(soundstr), appstring); } /* @@ -664,194 +526,151 @@ void CG_SiegeRoundOver(centity_t *ent, int won) } */ - if (soundstr[0]) - { + if (soundstr[0]) { trap->S_StartLocalSound(trap->S_RegisterSound(soundstr), CHAN_ANNOUNCER); } } } -void CG_SiegeGetObjectiveDescription(int team, int objective, char *buffer) -{ +void CG_SiegeGetObjectiveDescription(int team, int objective, char *buffer) { char teamstr[1024]; char objectiveStr[8192]; - buffer[0] = 0; //set to 0 ahead of time in case we fail to find the objective group/name + buffer[0] = 0; // set to 0 ahead of time in case we fail to find the objective group/name - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { //found the team group - if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), objectiveStr)) - { //found the objective group - //Parse the name right into the buffer. + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { // found the team group + if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), objectiveStr)) { // found the objective group + // Parse the name right into the buffer. BG_SiegeGetPairedValue(objectiveStr, "goalname", buffer); } } } -int CG_SiegeGetObjectiveFinal(int team, int objective ) -{ +int CG_SiegeGetObjectiveFinal(int team, int objective) { char finalStr[64]; char teamstr[1024]; char objectiveStr[8192]; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { //found the team group - if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), objectiveStr)) - { //found the objective group - //Parse the name right into the buffer. + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { // found the team group + if (BG_SiegeGetValueGroup(cgParseObjectives, va("Objective%i", objective), objectiveStr)) { // found the objective group + // Parse the name right into the buffer. BG_SiegeGetPairedValue(objectiveStr, "final", finalStr); - return (atoi( finalStr )); + return (atoi(finalStr)); } } return 0; } -void CG_SiegeBriefingDisplay(int team, int dontshow) -{ - char teamstr[64]; - char briefing[8192]; - char properValue[1024]; - char objectiveDesc[1024]; - int i = 1; - int useTeam = team; - qboolean primary = qfalse; - - if (!siege_valid) - { +void CG_SiegeBriefingDisplay(int team, int dontshow) { + char teamstr[64]; + char briefing[8192]; + char properValue[1024]; + char objectiveDesc[1024]; + int i = 1; + int useTeam = team; + qboolean primary = qfalse; + + if (!siege_valid) { return; } - if (team == TEAM_SPECTATOR) - { + if (team == TEAM_SPECTATOR) { return; } - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (useTeam != SIEGETEAM_TEAM1 && useTeam != SIEGETEAM_TEAM2) - { //This shouldn't be happening. But just fall back to team 2 anyway. + if (useTeam != SIEGETEAM_TEAM1 && useTeam != SIEGETEAM_TEAM2) { // This shouldn't be happening. But just fall back to team 2 anyway. useTeam = SIEGETEAM_TEAM2; } trap->Cvar_Set(va("siege_primobj_inuse"), "0"); - while (i < 16) - { //do up to 16 objectives I suppose - //Get the value for this objective on this team - //Now set the cvar for the menu to display. + while (i < 16) { // do up to 16 objectives I suppose + // Get the value for this objective on this team + // Now set the cvar for the menu to display. - //primary = (CG_SiegeGetObjectiveFinal(useTeam, i)>-1)?qtrue:qfalse; - primary = (CG_SiegeGetObjectiveFinal(useTeam, i)>0)?qtrue:qfalse; + // primary = (CG_SiegeGetObjectiveFinal(useTeam, i)>-1)?qtrue:qfalse; + primary = (CG_SiegeGetObjectiveFinal(useTeam, i) > 0) ? qtrue : qfalse; properValue[0] = 0; trap->Cvar_VariableStringBuffer(va("team%i_objective%i", useTeam, i), properValue, 1024); - if (primary) - { + if (primary) { trap->Cvar_Set(va("siege_primobj"), properValue); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i", i), properValue); } - //Now set the long desc cvar for the menu to display. + // Now set the long desc cvar for the menu to display. properValue[0] = 0; trap->Cvar_VariableStringBuffer(va("team%i_objective%i_longdesc", useTeam, i), properValue, 1024); - if (primary) - { + if (primary) { trap->Cvar_Set(va("siege_primobj_longdesc"), properValue); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i_longdesc", i), properValue); } - //Now set the gfx cvar for the menu to display. + // Now set the gfx cvar for the menu to display. properValue[0] = 0; trap->Cvar_VariableStringBuffer(va("team%i_objective%i_gfx", useTeam, i), properValue, 1024); - if (primary) - { + if (primary) { trap->Cvar_Set(va("siege_primobj_gfx"), properValue); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i_gfx", i), properValue); } - //Now set the mapicon cvar for the menu to display. + // Now set the mapicon cvar for the menu to display. properValue[0] = 0; trap->Cvar_VariableStringBuffer(va("team%i_objective%i_mapicon", useTeam, i), properValue, 1024); - if (primary) - { + if (primary) { trap->Cvar_Set(va("siege_primobj_mapicon"), properValue); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i_mapicon", i), properValue); } - //Now set the mappos cvar for the menu to display. + // Now set the mappos cvar for the menu to display. properValue[0] = 0; trap->Cvar_VariableStringBuffer(va("team%i_objective%i_mappos", useTeam, i), properValue, 1024); - if (primary) - { + if (primary) { trap->Cvar_Set(va("siege_primobj_mappos"), properValue); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i_mappos", i), properValue); } - //Now set the description cvar for the objective + // Now set the description cvar for the objective CG_SiegeGetObjectiveDescription(useTeam, i, objectiveDesc); - if (objectiveDesc[0]) - { //found a valid objective description - if ( primary ) - { + if (objectiveDesc[0]) { // found a valid objective description + if (primary) { trap->Cvar_Set(va("siege_primobj_desc"), objectiveDesc); - //this one is marked not in use because it gets primobj + // this one is marked not in use because it gets primobj trap->Cvar_Set(va("siege_objective%i_inuse", i), "0"); trap->Cvar_Set(va("siege_primobj_inuse"), "1"); trap->Cvar_Set(va("team%i_objective%i_inuse", useTeam, i), "1"); - } - else - { + } else { trap->Cvar_Set(va("siege_objective%i_desc", i), objectiveDesc); trap->Cvar_Set(va("siege_objective%i_inuse", i), "2"); trap->Cvar_Set(va("team%i_objective%i_inuse", useTeam, i), "2"); - } - } - else - { //didn't find one, so set the "inuse" cvar to 0 for the objective and mark it non-complete. + } else { // didn't find one, so set the "inuse" cvar to 0 for the objective and mark it non-complete. trap->Cvar_Set(va("siege_objective%i_inuse", i), "0"); trap->Cvar_Set(va("siege_objective%i", i), "0"); trap->Cvar_Set(va("team%i_objective%i_inuse", useTeam, i), "0"); @@ -868,102 +687,79 @@ void CG_SiegeBriefingDisplay(int team, int dontshow) i++; } - if (dontshow) - { + if (dontshow) { return; } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { - if (BG_SiegeGetPairedValue(cgParseObjectives, "briefing", briefing)) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { + if (BG_SiegeGetPairedValue(cgParseObjectives, "briefing", briefing)) { CG_DrawSiegeMessage(briefing, 1); } } } -void CG_SiegeObjectiveCompleted(centity_t *ent, int won, int objectivenum) -{ - int myTeam; - char teamstr[64]; - char objstr[256]; - char foundobjective[MAX_SIEGE_INFO_SIZE]; - char appstring[1024]; - char soundstr[1024]; - int success = 0; - playerState_t *ps = NULL; - - if (!siege_valid) - { - trap->Error( ERR_DROP, "Siege data does not exist on client!\n"); +void CG_SiegeObjectiveCompleted(centity_t *ent, int won, int objectivenum) { + int myTeam; + char teamstr[64]; + char objstr[256]; + char foundobjective[MAX_SIEGE_INFO_SIZE]; + char appstring[1024]; + char soundstr[1024]; + int success = 0; + playerState_t *ps = NULL; + + if (!siege_valid) { + trap->Error(ERR_DROP, "Siege data does not exist on client!\n"); return; } - if (cg.snap) - { //this should always be true, if it isn't though use the predicted ps as a fallback + if (cg.snap) { // this should always be true, if it isn't though use the predicted ps as a fallback ps = &cg.snap->ps; - } - else - { + } else { ps = &cg.predictedPlayerState; } - if (!ps) - { + if (!ps) { assert(0); return; } myTeam = ps->persistant[PERS_TEAM]; - if (myTeam == TEAM_SPECTATOR) - { + if (myTeam == TEAM_SPECTATOR) { return; } - if (won == SIEGETEAM_TEAM1) - { + if (won == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, cgParseObjectives)) { Com_sprintf(objstr, sizeof(objstr), "Objective%i", objectivenum); - if (BG_SiegeGetValueGroup(cgParseObjectives, objstr, foundobjective)) - { - if (myTeam == SIEGETEAM_TEAM1) - { + if (BG_SiegeGetValueGroup(cgParseObjectives, objstr, foundobjective)) { + if (myTeam == SIEGETEAM_TEAM1) { success = BG_SiegeGetPairedValue(foundobjective, "message_team1", appstring); - } - else - { + } else { success = BG_SiegeGetPairedValue(foundobjective, "message_team2", appstring); } - if (success) - { + if (success) { CG_DrawSiegeMessageNonMenu(appstring); } appstring[0] = 0; soundstr[0] = 0; - if (myTeam == SIEGETEAM_TEAM1) - { + if (myTeam == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), "sound_team1"); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), "sound_team2"); } - if (BG_SiegeGetPairedValue(foundobjective, teamstr, appstring)) - { + if (BG_SiegeGetPairedValue(foundobjective, teamstr, appstring)) { Com_sprintf(soundstr, sizeof(soundstr), appstring); } /* @@ -980,8 +776,7 @@ void CG_SiegeObjectiveCompleted(centity_t *ent, int won, int objectivenum) } */ - if (soundstr[0]) - { + if (soundstr[0]) { trap->S_StartLocalSound(trap->S_RegisterSound(soundstr), CHAN_ANNOUNCER); } } @@ -990,9 +785,8 @@ void CG_SiegeObjectiveCompleted(centity_t *ent, int won, int objectivenum) siegeExtended_t cg_siegeExtendedData[MAX_CLIENTS]; -//parse a single extended siege data entry -void CG_ParseSiegeExtendedDataEntry(const char *conStr) -{ +// parse a single extended siege data entry +void CG_ParseSiegeExtendedDataEntry(const char *conStr) { char s[MAX_STRING_CHARS]; char *str = (char *)conStr; int argParses = 0; @@ -1000,23 +794,19 @@ void CG_ParseSiegeExtendedDataEntry(const char *conStr) int maxAmmo = 0, clNum = -1, health = 1, maxhealth = 1, ammo = 1; centity_t *cent; - if (!conStr || !conStr[0]) - { + if (!conStr || !conStr[0]) { return; } - while (*str && argParses < 4) - { + while (*str && argParses < 4) { i = 0; - while (*str && *str != '|') - { + while (*str && *str != '|') { s[i] = *str; i++; str++; } s[i] = 0; - switch (argParses) - { + switch (argParses) { case 0: clNum = atoi(s); break; @@ -1036,8 +826,7 @@ void CG_ParseSiegeExtendedDataEntry(const char *conStr) str++; } - if (clNum < 0 || clNum >= MAX_CLIENTS) - { + if (clNum < 0 || clNum >= MAX_CLIENTS) { return; } @@ -1048,45 +837,37 @@ void CG_ParseSiegeExtendedDataEntry(const char *conStr) cent = &cg_entities[clNum]; maxAmmo = ammoData[weaponData[cent->currentState.weapon].ammoIndex].max; - if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) ) - { + if ((cent->currentState.eFlags & EF_DOUBLE_AMMO)) { maxAmmo *= 2.0f; } - if (ammo >= 0 && ammo <= maxAmmo ) - { //assure the weapon number is valid and not over max - //keep the weapon so if it changes before our next ext data update we'll know - //that the ammo is not applicable. + if (ammo >= 0 && ammo <= maxAmmo) { // assure the weapon number is valid and not over max + // keep the weapon so if it changes before our next ext data update we'll know + // that the ammo is not applicable. cg_siegeExtendedData[clNum].weapon = cent->currentState.weapon; - } - else - { //not valid? Oh well, just invalidate the weapon too then so we don't display ammo + } else { // not valid? Oh well, just invalidate the weapon too then so we don't display ammo cg_siegeExtendedData[clNum].weapon = -1; } cg_siegeExtendedData[clNum].lastUpdated = cg.time; } -//parse incoming siege data, see counterpart in g_saga.c -void CG_ParseSiegeExtendedData(void) -{ +// parse incoming siege data, see counterpart in g_saga.c +void CG_ParseSiegeExtendedData(void) { int numEntries = trap->Cmd_Argc(); int i = 0; - if (numEntries < 1) - { + if (numEntries < 1) { assert(!"Bad numEntries for sxd"); return; } - while (i < numEntries) - { - CG_ParseSiegeExtendedDataEntry(CG_Argv(i+1)); + while (i < numEntries) { + CG_ParseSiegeExtendedDataEntry(CG_Argv(i + 1)); i++; } } -void CG_SetSiegeTimerCvar ( int msec ) -{ +void CG_SetSiegeTimerCvar(int msec) { int seconds; int mins; int tens; @@ -1097,5 +878,5 @@ void CG_SetSiegeTimerCvar ( int msec ) tens = seconds / 10; seconds -= tens * 10; - trap->Cvar_Set("ui_siegeTimer", va( "%i:%i%i", mins, tens, seconds ) ); + trap->Cvar_Set("ui_siegeTimer", va("%i:%i%i", mins, tens, seconds)); } diff --git a/codemp/cgame/cg_scoreboard.c b/codemp/cgame/cg_scoreboard.c index b46108483a..10df1ebf08 100644 --- a/codemp/cgame/cg_scoreboard.c +++ b/codemp/cgame/cg_scoreboard.c @@ -26,40 +26,38 @@ along with this program; if not, see . #include "ui/ui_shared.h" #include "game/bg_saga.h" -#define SCOREBOARD_X (0) +#define SCOREBOARD_X (0) -#define SB_HEADER 86 -#define SB_TOP (SB_HEADER+32) +#define SB_HEADER 86 +#define SB_TOP (SB_HEADER + 32) // Where the status bar starts, so we don't overwrite it -#define SB_STATUSBAR 420 +#define SB_STATUSBAR 420 -#define SB_NORMAL_HEIGHT 25 -#define SB_INTER_HEIGHT 15 // interleaved height +#define SB_NORMAL_HEIGHT 25 +#define SB_INTER_HEIGHT 15 // interleaved height -#define SB_MAXCLIENTS_NORMAL ((SB_STATUSBAR - SB_TOP) / SB_NORMAL_HEIGHT) -#define SB_MAXCLIENTS_INTER ((SB_STATUSBAR - SB_TOP) / SB_INTER_HEIGHT - 1) +#define SB_MAXCLIENTS_NORMAL ((SB_STATUSBAR - SB_TOP) / SB_NORMAL_HEIGHT) +#define SB_MAXCLIENTS_INTER ((SB_STATUSBAR - SB_TOP) / SB_INTER_HEIGHT - 1) // Used when interleaved - - -#define SB_LEFT_BOTICON_X (SCOREBOARD_X+0) -#define SB_LEFT_HEAD_X (SCOREBOARD_X+32) -#define SB_RIGHT_BOTICON_X (SCOREBOARD_X+64) -#define SB_RIGHT_HEAD_X (SCOREBOARD_X+96) +#define SB_LEFT_BOTICON_X (SCOREBOARD_X + 0) +#define SB_LEFT_HEAD_X (SCOREBOARD_X + 32) +#define SB_RIGHT_BOTICON_X (SCOREBOARD_X + 64) +#define SB_RIGHT_HEAD_X (SCOREBOARD_X + 96) // Normal -#define SB_BOTICON_X (SCOREBOARD_X+32) -#define SB_HEAD_X (SCOREBOARD_X+64) +#define SB_BOTICON_X (SCOREBOARD_X + 32) +#define SB_HEAD_X (SCOREBOARD_X + 64) -#define SB_SCORELINE_X 100 -#define SB_SCORELINE_WIDTH (640 - SB_SCORELINE_X * 2) +#define SB_SCORELINE_X 100 +#define SB_SCORELINE_WIDTH (640 - SB_SCORELINE_X * 2) -#define SB_RATING_WIDTH 0 // (6 * BIGCHAR_WIDTH) -#define SB_NAME_X (SB_SCORELINE_X) -#define SB_SCORE_X (SB_SCORELINE_X + .55 * SB_SCORELINE_WIDTH) -#define SB_PING_X (SB_SCORELINE_X + .70 * SB_SCORELINE_WIDTH) -#define SB_TIME_X (SB_SCORELINE_X + .85 * SB_SCORELINE_WIDTH) +#define SB_RATING_WIDTH 0 // (6 * BIGCHAR_WIDTH) +#define SB_NAME_X (SB_SCORELINE_X) +#define SB_SCORE_X (SB_SCORELINE_X + .55 * SB_SCORELINE_WIDTH) +#define SB_PING_X (SB_SCORELINE_X + .70 * SB_SCORELINE_WIDTH) +#define SB_TIME_X (SB_SCORELINE_X + .85 * SB_SCORELINE_WIDTH) // The new and improved score board // @@ -74,84 +72,74 @@ along with this program; if not, see . static qboolean localClient; // true if local client has been displayed - - /* +/* ================= CG_DrawScoreboard ================= */ -static void CG_DrawClientScore( int y, score_t *score, float *color, float fade, qboolean largeFormat ) -{ - //vec3_t headAngles; - clientInfo_t *ci; - int iconx = SB_BOTICON_X + (SB_RATING_WIDTH / 2); - float scale = largeFormat ? 1.0f : 0.75f, - iconSize = largeFormat ? SB_NORMAL_HEIGHT : SB_INTER_HEIGHT; - - if ( score->client < 0 || score->client >= cgs.maxclients ) { - Com_Printf( "Bad score->client: %i\n", score->client ); +static void CG_DrawClientScore(int y, score_t *score, float *color, float fade, qboolean largeFormat) { + // vec3_t headAngles; + clientInfo_t *ci; + int iconx = SB_BOTICON_X + (SB_RATING_WIDTH / 2); + float scale = largeFormat ? 1.0f : 0.75f, iconSize = largeFormat ? SB_NORMAL_HEIGHT : SB_INTER_HEIGHT; + + if (score->client < 0 || score->client >= cgs.maxclients) { + Com_Printf("Bad score->client: %i\n", score->client); return; } ci = &cgs.clientinfo[score->client]; // draw the handicap or bot skill marker (unless player has flag) - if ( ci->powerups & (1<powerups & (1 << PW_NEUTRALFLAG)) { + if (largeFormat) + CG_DrawFlagModel(iconx, y - (32 - BIGCHAR_HEIGHT) / 2, iconSize, iconSize, TEAM_FREE, qfalse); else - CG_DrawFlagModel( iconx, y, iconSize, iconSize, TEAM_FREE, qfalse ); + CG_DrawFlagModel(iconx, y, iconSize, iconSize, TEAM_FREE, qfalse); } - else if ( ci->powerups & ( 1 << PW_REDFLAG ) ) - CG_DrawFlagModel( iconx, y, iconSize, iconSize, TEAM_RED, qfalse ); + else if (ci->powerups & (1 << PW_REDFLAG)) + CG_DrawFlagModel(iconx, y, iconSize, iconSize, TEAM_RED, qfalse); - else if ( ci->powerups & ( 1 << PW_BLUEFLAG ) ) - CG_DrawFlagModel( iconx, y, iconSize, iconSize, TEAM_BLUE, qfalse ); + else if (ci->powerups & (1 << PW_BLUEFLAG)) + CG_DrawFlagModel(iconx, y, iconSize, iconSize, TEAM_BLUE, qfalse); - else if ( cgs.gametype == GT_POWERDUEL && (ci->duelTeam == DUELTEAM_LONE || ci->duelTeam == DUELTEAM_DOUBLE) ) - { - CG_DrawPic( iconx, y, iconSize, iconSize, trap->R_RegisterShaderNoMip( - (ci->duelTeam == DUELTEAM_LONE) ? "gfx/mp/pduel_icon_lone" : "gfx/mp/pduel_icon_double" ) ); + else if (cgs.gametype == GT_POWERDUEL && (ci->duelTeam == DUELTEAM_LONE || ci->duelTeam == DUELTEAM_DOUBLE)) { + CG_DrawPic(iconx, y, iconSize, iconSize, + trap->R_RegisterShaderNoMip((ci->duelTeam == DUELTEAM_LONE) ? "gfx/mp/pduel_icon_lone" : "gfx/mp/pduel_icon_double")); } - else if (cgs.gametype == GT_SIEGE) - { //try to draw the shader for this class on the scoreboard - if (ci->siegeIndex != -1) - { + else if (cgs.gametype == GT_SIEGE) { // try to draw the shader for this class on the scoreboard + if (ci->siegeIndex != -1) { siegeClass_t *scl = &bgSiegeClasses[ci->siegeIndex]; - if (scl->classShader) - { - CG_DrawPic (iconx, y, largeFormat?24:12, largeFormat?24:12, scl->classShader); + if (scl->classShader) { + CG_DrawPic(iconx, y, largeFormat ? 24 : 12, largeFormat ? 24 : 12, scl->classShader); } } } // highlight your position - if ( score->client == cg.snap->ps.clientNum ) - { - float hcolor[4]; - int rank; + if (score->client == cg.snap->ps.clientNum) { + float hcolor[4]; + int rank; localClient = qtrue; - if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR - || cgs.gametype >= GT_TEAM ) { + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR || cgs.gametype >= GT_TEAM) { rank = -1; } else { rank = cg.snap->ps.persistant[PERS_RANK] & ~RANK_TIED_FLAG; } - if ( rank == 0 ) { + if (rank == 0) { hcolor[0] = 0; hcolor[1] = 0; hcolor[2] = 0.7f; - } else if ( rank == 1 ) { + } else if (rank == 1) { hcolor[0] = 0.7f; hcolor[1] = 0; hcolor[2] = 0; - } else if ( rank == 2 ) { + } else if (rank == 2) { hcolor[0] = 0.7f; hcolor[1] = 0.7f; hcolor[2] = 0; @@ -162,42 +150,34 @@ static void CG_DrawClientScore( int y, score_t *score, float *color, float fade, } hcolor[3] = fade * 0.7; - CG_FillRect( SB_SCORELINE_X - 5, y + 2, 640 - SB_SCORELINE_X * 2 + 10, largeFormat?SB_NORMAL_HEIGHT:SB_INTER_HEIGHT, hcolor ); + CG_FillRect(SB_SCORELINE_X - 5, y + 2, 640 - SB_SCORELINE_X * 2 + 10, largeFormat ? SB_NORMAL_HEIGHT : SB_INTER_HEIGHT, hcolor); } - CG_Text_Paint (SB_NAME_X, y, 0.9f * scale, colorWhite, ci->name,0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + CG_Text_Paint(SB_NAME_X, y, 0.9f * scale, colorWhite, ci->name, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); - if ( score->ping != -1 ) - { - if ( ci->team != TEAM_SPECTATOR || cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL ) - { - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) - { - CG_Text_Paint (SB_SCORE_X, y, 1.0f * scale, colorWhite, va("%i/%i", ci->wins, ci->losses),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - } - else - { - CG_Text_Paint (SB_SCORE_X, y, 1.0f * scale, colorWhite, va("%i", score->score),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); + if (score->ping != -1) { + if (ci->team != TEAM_SPECTATOR || cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { + CG_Text_Paint(SB_SCORE_X, y, 1.0f * scale, colorWhite, va("%i/%i", ci->wins, ci->losses), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + } else { + CG_Text_Paint(SB_SCORE_X, y, 1.0f * scale, colorWhite, va("%i", score->score), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); } } - if ( cg_scoreboardBots.integer && ci->botSkill != -1 ) - CG_Text_Paint( SB_PING_X, y, 1.0f * scale, colorWhite, "BOT", 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); + if (cg_scoreboardBots.integer && ci->botSkill != -1) + CG_Text_Paint(SB_PING_X, y, 1.0f * scale, colorWhite, "BOT", 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); else - CG_Text_Paint (SB_PING_X, y, 1.0f * scale, colorWhite, va("%i", score->ping),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - CG_Text_Paint (SB_TIME_X, y, 1.0f * scale, colorWhite, va("%i", score->time),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - } - else - { - CG_Text_Paint (SB_SCORE_X, y, 1.0f * scale, colorWhite, "-",0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - CG_Text_Paint (SB_PING_X, y, 1.0f * scale, colorWhite, "-",0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); - CG_Text_Paint (SB_TIME_X, y, 1.0f * scale, colorWhite, "-",0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL ); + CG_Text_Paint(SB_PING_X, y, 1.0f * scale, colorWhite, va("%i", score->ping), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + CG_Text_Paint(SB_TIME_X, y, 1.0f * scale, colorWhite, va("%i", score->time), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + } else { + CG_Text_Paint(SB_SCORE_X, y, 1.0f * scale, colorWhite, "-", 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + CG_Text_Paint(SB_PING_X, y, 1.0f * scale, colorWhite, "-", 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); + CG_Text_Paint(SB_TIME_X, y, 1.0f * scale, colorWhite, "-", 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL); } // add the "ready" marker for intermission exiting - if ( cg.snap->ps.stats[ STAT_CLIENTS_READY ] & ( 1 << score->client ) ) - { - CG_Text_Paint (SB_NAME_X - 64, y + 2, 0.7f * scale, colorWhite, CG_GetStringEdString("MP_INGAME", "READY"),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + if (cg.snap->ps.stats[STAT_CLIENTS_READY] & (1 << score->client)) { + CG_Text_Paint(SB_NAME_X - 64, y + 2, 0.7f * scale, colorWhite, CG_GetStringEdString("MP_INGAME", "READY"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); } } @@ -206,29 +186,27 @@ static void CG_DrawClientScore( int y, score_t *score, float *color, float fade, CG_TeamScoreboard ================= */ -static int CG_TeamScoreboard( int y, team_t team, float fade, int maxClients, int lineHeight, qboolean countOnly ) -{ - int i; - score_t *score; - float color[4]; - int count; - clientInfo_t *ci; +static int CG_TeamScoreboard(int y, team_t team, float fade, int maxClients, int lineHeight, qboolean countOnly) { + int i; + score_t *score; + float color[4]; + int count; + clientInfo_t *ci; color[0] = color[1] = color[2] = 1.0; color[3] = fade; count = 0; - for ( i = 0 ; i < cg.numScores && count < maxClients ; i++ ) { + for (i = 0; i < cg.numScores && count < maxClients; i++) { score = &cg.scores[i]; - ci = &cgs.clientinfo[ score->client ]; + ci = &cgs.clientinfo[score->client]; - if ( team != ci->team ) { + if (team != ci->team) { continue; } - if ( !countOnly ) - { - CG_DrawClientScore( y + lineHeight * count, score, color, fade, lineHeight == SB_NORMAL_HEIGHT ); + if (!countOnly) { + CG_DrawClientScore(y + lineHeight * count, score, color, fade, lineHeight == SB_NORMAL_HEIGHT); } count++; @@ -237,71 +215,60 @@ static int CG_TeamScoreboard( int y, team_t team, float fade, int maxClients, in return count; } -int CG_GetClassCount(team_t team,int siegeClass ) -{ +int CG_GetClassCount(team_t team, int siegeClass) { int i = 0; int count = 0; - clientInfo_t *ci; + clientInfo_t *ci; siegeClass_t *scl; - for ( i = 0 ; i < cgs.maxclients ; i++ ) - { - ci = &cgs.clientinfo[ i ]; + for (i = 0; i < cgs.maxclients; i++) { + ci = &cgs.clientinfo[i]; - if ((!ci->infoValid) || ( team != ci->team )) - { + if ((!ci->infoValid) || (team != ci->team)) { continue; } scl = &bgSiegeClasses[ci->siegeIndex]; // Correct class? - if ( siegeClass != scl->classShader ) - { + if (siegeClass != scl->classShader) { continue; } count++; } - return count; - + return count; } -int CG_GetTeamNonScoreCount(team_t team) -{ - int i = 0,count=0; - clientInfo_t *ci; +int CG_GetTeamNonScoreCount(team_t team) { + int i = 0, count = 0; + clientInfo_t *ci; - for ( i = 0 ; i < cgs.maxclients ; i++ ) - { - ci = &cgs.clientinfo[ i ]; + for (i = 0; i < cgs.maxclients; i++) { + ci = &cgs.clientinfo[i]; - if ( (!ci->infoValid) || (team != ci->team && team != ci->siegeDesiredTeam) ) - { + if ((!ci->infoValid) || (team != ci->team && team != ci->siegeDesiredTeam)) { continue; } count++; } - return count; + return count; } -int CG_GetTeamCount(team_t team, int maxClients) -{ +int CG_GetTeamCount(team_t team, int maxClients) { int i = 0; int count = 0; - clientInfo_t *ci; - score_t *score; + clientInfo_t *ci; + score_t *score; - for ( i = 0 ; i < cg.numScores && count < maxClients ; i++ ) - { + for (i = 0; i < cg.numScores && count < maxClients; i++) { score = &cg.scores[i]; - ci = &cgs.clientinfo[ score->client ]; + ci = &cgs.clientinfo[score->client]; - if ( team != ci->team ) - { + if (team != ci->team) { continue; } @@ -309,7 +276,6 @@ int CG_GetTeamCount(team_t team, int maxClients) } return count; - } /* ================= @@ -319,34 +285,33 @@ Draw the normal in-game scoreboard ================= */ int cg_siegeWinTeam = 0; -qboolean CG_DrawOldScoreboard( void ) { - int x, y, i, n1, n2; - float fade; - float *fadeColor; - char *s; +qboolean CG_DrawOldScoreboard(void) { + int x, y, i, n1, n2; + float fade; + float *fadeColor; + char *s; int maxClients, realMaxClients; int lineHeight; int topBorderSize, bottomBorderSize; // don't draw amuthing if the menu or console is up - if ( cl_paused.integer ) { + if (cl_paused.integer) { cg.deferredPlayerLoading = 0; return qfalse; } // don't draw scoreboard during death while warmup up - if ( cg.warmup && !cg.showScores ) { + if (cg.warmup && !cg.showScores) { return qfalse; } - if ( cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD || - cg.predictedPlayerState.pm_type == PM_INTERMISSION ) { + if (cg.showScores || cg.predictedPlayerState.pm_type == PM_DEAD || cg.predictedPlayerState.pm_type == PM_INTERMISSION) { fade = 1.0; fadeColor = colorWhite; } else { - fadeColor = CG_FadeColor( cg.scoreFadeTime, FADE_TIME ); + fadeColor = CG_FadeColor(cg.scoreFadeTime, FADE_TIME); - if ( !fadeColor ) { + if (!fadeColor) { // next time scoreboard comes up, don't print killer cg.deferredPlayerLoading = 0; cg.killerName[0] = 0; @@ -357,136 +322,111 @@ qboolean CG_DrawOldScoreboard( void ) { // fragged by ... line // or if in intermission and duel, prints the winner of the duel round - if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelWinner != -1 && - cg.predictedPlayerState.pm_type == PM_INTERMISSION) - { - s = va("%s^7 %s", cgs.clientinfo[cgs.duelWinner].name, CG_GetStringEdString("MP_INGAME", "DUEL_WINS") ); + if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelWinner != -1 && cg.predictedPlayerState.pm_type == PM_INTERMISSION) { + s = va("%s^7 %s", cgs.clientinfo[cgs.duelWinner].name, CG_GetStringEdString("MP_INGAME", "DUEL_WINS")); /*w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 40; CG_DrawBigString( x, y, s, fade ); */ - x = ( SCREEN_WIDTH ) / 2; + x = (SCREEN_WIDTH) / 2; y = 40; - CG_Text_Paint ( x - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - } - else if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelist1 != -1 && cgs.duelist2 != -1 && - cg.predictedPlayerState.pm_type == PM_INTERMISSION) - { - if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) - { - s = va("%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name ); - } - else - { - s = va("%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name ); + CG_Text_Paint(x - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + } else if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.duelist1 != -1 && cgs.duelist2 != -1 && + cg.predictedPlayerState.pm_type == PM_INTERMISSION) { + if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1) { + s = va("%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), + cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name); + } else { + s = va("%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name); } /*w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 40; CG_DrawBigString( x, y, s, fade ); */ - x = ( SCREEN_WIDTH ) / 2; + x = (SCREEN_WIDTH) / 2; y = 40; - CG_Text_Paint ( x - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - } - else if ( cg.killerName[0] ) { - s = va("%s %s", CG_GetStringEdString("MP_INGAME", "KILLEDBY"), cg.killerName ); + CG_Text_Paint(x - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + } else if (cg.killerName[0]) { + s = va("%s %s", CG_GetStringEdString("MP_INGAME", "KILLEDBY"), cg.killerName); /*w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; x = ( SCREEN_WIDTH - w ) / 2; y = 40; CG_DrawBigString( x, y, s, fade ); */ - x = ( SCREEN_WIDTH ) / 2; + x = (SCREEN_WIDTH) / 2; y = 40; - CG_Text_Paint ( x - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + CG_Text_Paint(x - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); } // current rank - if (cgs.gametype == GT_POWERDUEL) - { //do nothing? - } - else if ( cgs.gametype < GT_TEAM) { - if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR ) - { + if (cgs.gametype == GT_POWERDUEL) { // do nothing? + } else if (cgs.gametype < GT_TEAM) { + if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR) { char sPlace[256]; char sOf[256]; char sWith[256]; - trap->SE_GetStringTextString("MP_INGAME_PLACE", sPlace, sizeof(sPlace)); - trap->SE_GetStringTextString("MP_INGAME_OF", sOf, sizeof(sOf)); - trap->SE_GetStringTextString("MP_INGAME_WITH", sWith, sizeof(sWith)); - - s = va("%s %s (%s %i) %s %i", - CG_PlaceString( cg.snap->ps.persistant[PERS_RANK] + 1 ), - sPlace, - sOf, - cg.numScores, - sWith, - cg.snap->ps.persistant[PERS_SCORE] ); - // w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; - x = ( SCREEN_WIDTH ) / 2; + trap->SE_GetStringTextString("MP_INGAME_PLACE", sPlace, sizeof(sPlace)); + trap->SE_GetStringTextString("MP_INGAME_OF", sOf, sizeof(sOf)); + trap->SE_GetStringTextString("MP_INGAME_WITH", sWith, sizeof(sWith)); + + s = va("%s %s (%s %i) %s %i", CG_PlaceString(cg.snap->ps.persistant[PERS_RANK] + 1), sPlace, sOf, cg.numScores, sWith, + cg.snap->ps.persistant[PERS_SCORE]); + // w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH; + x = (SCREEN_WIDTH) / 2; y = 60; - //CG_DrawBigString( x, y, s, fade ); - CG_DrawProportionalString(x, y, s, UI_CENTER|UI_DROPSHADOW, colorTable[CT_WHITE]); + // CG_DrawBigString( x, y, s, fade ); + CG_DrawProportionalString(x, y, s, UI_CENTER | UI_DROPSHADOW, colorTable[CT_WHITE]); } - } - else if (cgs.gametype != GT_SIEGE) - { - if ( cg.teamScores[0] == cg.teamScores[1] ) { - s = va("%s %i", CG_GetStringEdString("MP_INGAME", "TIEDAT"), cg.teamScores[0] ); - } else if ( cg.teamScores[0] >= cg.teamScores[1] ) { - s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "RED_LEADS"), cg.teamScores[0], cg.teamScores[1] ); + } else if (cgs.gametype != GT_SIEGE) { + if (cg.teamScores[0] == cg.teamScores[1]) { + s = va("%s %i", CG_GetStringEdString("MP_INGAME", "TIEDAT"), cg.teamScores[0]); + } else if (cg.teamScores[0] >= cg.teamScores[1]) { + s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "RED_LEADS"), cg.teamScores[0], cg.teamScores[1]); } else { - s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "BLUE_LEADS"), cg.teamScores[1], cg.teamScores[0] ); + s = va("%s, %i / %i", CG_GetStringEdString("MP_INGAME", "BLUE_LEADS"), cg.teamScores[1], cg.teamScores[0]); } - x = ( SCREEN_WIDTH ) / 2; + x = (SCREEN_WIDTH) / 2; y = 60; - CG_Text_Paint ( x - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - } - else if (cgs.gametype == GT_SIEGE && (cg_siegeWinTeam == 1 || cg_siegeWinTeam == 2)) - { - if (cg_siegeWinTeam == 1) - { - s = va("%s", CG_GetStringEdString("MP_INGAME", "SIEGETEAM1WIN") ); - } - else - { - s = va("%s", CG_GetStringEdString("MP_INGAME", "SIEGETEAM2WIN") ); + CG_Text_Paint(x - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + } else if (cgs.gametype == GT_SIEGE && (cg_siegeWinTeam == 1 || cg_siegeWinTeam == 2)) { + if (cg_siegeWinTeam == 1) { + s = va("%s", CG_GetStringEdString("MP_INGAME", "SIEGETEAM1WIN")); + } else { + s = va("%s", CG_GetStringEdString("MP_INGAME", "SIEGETEAM2WIN")); } - x = ( SCREEN_WIDTH ) / 2; + x = (SCREEN_WIDTH) / 2; y = 60; - CG_Text_Paint ( x - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + CG_Text_Paint(x - CG_Text_Width(s, 1.0f, FONT_MEDIUM) / 2, y, 1.0f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); } // scoreboard y = SB_HEADER; - CG_DrawPic ( SB_SCORELINE_X - 40, y - 5, SB_SCORELINE_WIDTH + 80, 40, trap->R_RegisterShaderNoMip ( "gfx/menus/menu_buttonback.tga" ) ); + CG_DrawPic(SB_SCORELINE_X - 40, y - 5, SB_SCORELINE_WIDTH + 80, 40, trap->R_RegisterShaderNoMip("gfx/menus/menu_buttonback.tga")); - CG_Text_Paint ( SB_NAME_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "NAME"),0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) - { + CG_Text_Paint(SB_NAME_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "NAME"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) { char sWL[100]; - trap->SE_GetStringTextString("MP_INGAME_W_L", sWL, sizeof(sWL)); + trap->SE_GetStringTextString("MP_INGAME_W_L", sWL, sizeof(sWL)); - CG_Text_Paint ( SB_SCORE_X, y, 1.0f, colorWhite, sWL, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - } - else - { - CG_Text_Paint ( SB_SCORE_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "SCORE"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + CG_Text_Paint(SB_SCORE_X, y, 1.0f, colorWhite, sWL, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + } else { + CG_Text_Paint(SB_SCORE_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "SCORE"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); } - CG_Text_Paint ( SB_PING_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "PING"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); - CG_Text_Paint ( SB_TIME_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "TIME"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM ); + CG_Text_Paint(SB_PING_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "PING"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); + CG_Text_Paint(SB_TIME_X, y, 1.0f, colorWhite, CG_GetStringEdString("MP_INGAME", "TIME"), 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_MEDIUM); y = SB_TOP; // If there are more than SB_MAXCLIENTS_NORMAL, use the interleaved scores - if ( cg.numScores > SB_MAXCLIENTS_NORMAL ) { + if (cg.numScores > SB_MAXCLIENTS_NORMAL) { maxClients = SB_MAXCLIENTS_INTER; lineHeight = SB_INTER_HEIGHT; topBorderSize = 8; @@ -501,113 +441,108 @@ qboolean CG_DrawOldScoreboard( void ) { localClient = qfalse; + // I guess this should end up being able to display 19 clients at once. + // In a team game, if there are 9 or more clients on the team not in the lead, + // we only want to show 10 of the clients on the team in the lead, so that we + // have room to display the clients in the lead on the losing team. - //I guess this should end up being able to display 19 clients at once. - //In a team game, if there are 9 or more clients on the team not in the lead, - //we only want to show 10 of the clients on the team in the lead, so that we - //have room to display the clients in the lead on the losing team. - - //I guess this can be accomplished simply by printing the first teams score with a maxClients - //value passed in related to how many players are on both teams. - if ( cgs.gametype >= GT_TEAM ) { + // I guess this can be accomplished simply by printing the first teams score with a maxClients + // value passed in related to how many players are on both teams. + if (cgs.gametype >= GT_TEAM) { // // teamplay scoreboard // - y += lineHeight/2; + y += lineHeight / 2; - if ( cg.teamScores[0] >= cg.teamScores[1] ) { + if (cg.teamScores[0] >= cg.teamScores[1]) { int team1MaxCl = CG_GetTeamCount(TEAM_RED, maxClients); int team2MaxCl = CG_GetTeamCount(TEAM_BLUE, maxClients); - if (team1MaxCl > 10 && (team1MaxCl+team2MaxCl) > maxClients) - { + if (team1MaxCl > 10 && (team1MaxCl + team2MaxCl) > maxClients) { team1MaxCl -= team2MaxCl; - //subtract as many as you have to down to 10, once we get there - //we just set it to 10 + // subtract as many as you have to down to 10, once we get there + // we just set it to 10 - if (team1MaxCl < 10) - { + if (team1MaxCl < 10) { team1MaxCl = 10; } } - team2MaxCl = (maxClients-team1MaxCl); //team2 can display however many is left over after team1's display + team2MaxCl = (maxClients - team1MaxCl); // team2 can display however many is left over after team1's display - n1 = CG_TeamScoreboard( y, TEAM_RED, fade, team1MaxCl, lineHeight, qtrue ); - CG_DrawTeamBackground( SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED ); - CG_TeamScoreboard( y, TEAM_RED, fade, team1MaxCl, lineHeight, qfalse ); + n1 = CG_TeamScoreboard(y, TEAM_RED, fade, team1MaxCl, lineHeight, qtrue); + CG_DrawTeamBackground(SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED); + CG_TeamScoreboard(y, TEAM_RED, fade, team1MaxCl, lineHeight, qfalse); y += (n1 * lineHeight) + BIGCHAR_HEIGHT; - //maxClients -= n1; + // maxClients -= n1; - n2 = CG_TeamScoreboard( y, TEAM_BLUE, fade, team2MaxCl, lineHeight, qtrue ); - CG_DrawTeamBackground( SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE ); - CG_TeamScoreboard( y, TEAM_BLUE, fade, team2MaxCl, lineHeight, qfalse ); + n2 = CG_TeamScoreboard(y, TEAM_BLUE, fade, team2MaxCl, lineHeight, qtrue); + CG_DrawTeamBackground(SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE); + CG_TeamScoreboard(y, TEAM_BLUE, fade, team2MaxCl, lineHeight, qfalse); y += (n2 * lineHeight) + BIGCHAR_HEIGHT; - //maxClients -= n2; + // maxClients -= n2; - maxClients -= (team1MaxCl+team2MaxCl); + maxClients -= (team1MaxCl + team2MaxCl); } else { int team1MaxCl = CG_GetTeamCount(TEAM_BLUE, maxClients); int team2MaxCl = CG_GetTeamCount(TEAM_RED, maxClients); - if (team1MaxCl > 10 && (team1MaxCl+team2MaxCl) > maxClients) - { + if (team1MaxCl > 10 && (team1MaxCl + team2MaxCl) > maxClients) { team1MaxCl -= team2MaxCl; - //subtract as many as you have to down to 10, once we get there - //we just set it to 10 + // subtract as many as you have to down to 10, once we get there + // we just set it to 10 - if (team1MaxCl < 10) - { + if (team1MaxCl < 10) { team1MaxCl = 10; } } - team2MaxCl = (maxClients-team1MaxCl); //team2 can display however many is left over after team1's display + team2MaxCl = (maxClients - team1MaxCl); // team2 can display however many is left over after team1's display - n1 = CG_TeamScoreboard( y, TEAM_BLUE, fade, team1MaxCl, lineHeight, qtrue ); - CG_DrawTeamBackground( SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE ); - CG_TeamScoreboard( y, TEAM_BLUE, fade, team1MaxCl, lineHeight, qfalse ); + n1 = CG_TeamScoreboard(y, TEAM_BLUE, fade, team1MaxCl, lineHeight, qtrue); + CG_DrawTeamBackground(SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n1 * lineHeight + bottomBorderSize, 0.33f, TEAM_BLUE); + CG_TeamScoreboard(y, TEAM_BLUE, fade, team1MaxCl, lineHeight, qfalse); y += (n1 * lineHeight) + BIGCHAR_HEIGHT; - //maxClients -= n1; + // maxClients -= n1; - n2 = CG_TeamScoreboard( y, TEAM_RED, fade, team2MaxCl, lineHeight, qtrue ); - CG_DrawTeamBackground( SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED ); - CG_TeamScoreboard( y, TEAM_RED, fade, team2MaxCl, lineHeight, qfalse ); + n2 = CG_TeamScoreboard(y, TEAM_RED, fade, team2MaxCl, lineHeight, qtrue); + CG_DrawTeamBackground(SB_SCORELINE_X - 5, y - topBorderSize, 640 - SB_SCORELINE_X * 2 + 10, n2 * lineHeight + bottomBorderSize, 0.33f, TEAM_RED); + CG_TeamScoreboard(y, TEAM_RED, fade, team2MaxCl, lineHeight, qfalse); y += (n2 * lineHeight) + BIGCHAR_HEIGHT; - //maxClients -= n2; + // maxClients -= n2; - maxClients -= (team1MaxCl+team2MaxCl); + maxClients -= (team1MaxCl + team2MaxCl); } maxClients = realMaxClients; - n1 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients, lineHeight, qfalse ); + n1 = CG_TeamScoreboard(y, TEAM_SPECTATOR, fade, maxClients, lineHeight, qfalse); y += (n1 * lineHeight) + BIGCHAR_HEIGHT; } else { // // free for all scoreboard // - n1 = CG_TeamScoreboard( y, TEAM_FREE, fade, maxClients, lineHeight, qfalse ); + n1 = CG_TeamScoreboard(y, TEAM_FREE, fade, maxClients, lineHeight, qfalse); y += (n1 * lineHeight) + BIGCHAR_HEIGHT; - n2 = CG_TeamScoreboard( y, TEAM_SPECTATOR, fade, maxClients - n1, lineHeight, qfalse ); + n2 = CG_TeamScoreboard(y, TEAM_SPECTATOR, fade, maxClients - n1, lineHeight, qfalse); y += (n2 * lineHeight) + BIGCHAR_HEIGHT; } if (!localClient) { // draw local client at the bottom - for ( i = 0 ; i < cg.numScores ; i++ ) { - if ( cg.scores[i].client == cg.snap->ps.clientNum ) { - CG_DrawClientScore( y, &cg.scores[i], fadeColor, fade, lineHeight == SB_NORMAL_HEIGHT ); + for (i = 0; i < cg.numScores; i++) { + if (cg.scores[i].client == cg.snap->ps.clientNum) { + CG_DrawClientScore(y, &cg.scores[i], fadeColor, fade, lineHeight == SB_NORMAL_HEIGHT); break; } } } // load any models that have been deferred - if ( ++cg.deferredPlayerLoading > 10 ) { + if (++cg.deferredPlayerLoading > 10) { CG_LoadDeferredPlayers(); } @@ -615,4 +550,3 @@ qboolean CG_DrawOldScoreboard( void ) { } //================================================================================ - diff --git a/codemp/cgame/cg_servercmds.c b/codemp/cgame/cg_servercmds.c index 82f4e20254..3201d171ce 100644 --- a/codemp/cgame/cg_servercmds.c +++ b/codemp/cgame/cg_servercmds.c @@ -38,50 +38,50 @@ CG_ParseScores ================= */ #define SCORE_OFFSET (14) -static void CG_ParseScores( void ) { +static void CG_ParseScores(void) { int i, powerups, readScores; - cg.numScores = atoi( CG_Argv( 1 ) ); + cg.numScores = atoi(CG_Argv(1)); readScores = cg.numScores; if (readScores > MAX_CLIENT_SCORE_SEND) readScores = MAX_CLIENT_SCORE_SEND; - if ( cg.numScores > MAX_CLIENTS ) + if (cg.numScores > MAX_CLIENTS) cg.numScores = MAX_CLIENTS; cg.numScores = readScores; - cg.teamScores[0] = atoi( CG_Argv( 2 ) ); - cg.teamScores[1] = atoi( CG_Argv( 3 ) ); - - memset( cg.scores, 0, sizeof( cg.scores ) ); - for ( i=0; i= MAX_CLIENTS ) + cg.teamScores[0] = atoi(CG_Argv(2)); + cg.teamScores[1] = atoi(CG_Argv(3)); + + memset(cg.scores, 0, sizeof(cg.scores)); + for (i = 0; i < readScores; i++) { + cg.scores[i].client = atoi(CG_Argv(i * SCORE_OFFSET + 4)); + cg.scores[i].score = atoi(CG_Argv(i * SCORE_OFFSET + 5)); + cg.scores[i].ping = atoi(CG_Argv(i * SCORE_OFFSET + 6)); + cg.scores[i].time = atoi(CG_Argv(i * SCORE_OFFSET + 7)); + cg.scores[i].scoreFlags = atoi(CG_Argv(i * SCORE_OFFSET + 8)); + powerups = atoi(CG_Argv(i * SCORE_OFFSET + 9)); + cg.scores[i].accuracy = atoi(CG_Argv(i * SCORE_OFFSET + 10)); + cg.scores[i].impressiveCount = atoi(CG_Argv(i * SCORE_OFFSET + 11)); + cg.scores[i].excellentCount = atoi(CG_Argv(i * SCORE_OFFSET + 12)); + cg.scores[i].gauntletCount = atoi(CG_Argv(i * SCORE_OFFSET + 13)); + cg.scores[i].defendCount = atoi(CG_Argv(i * SCORE_OFFSET + 14)); + cg.scores[i].assistCount = atoi(CG_Argv(i * SCORE_OFFSET + 15)); + cg.scores[i].perfect = atoi(CG_Argv(i * SCORE_OFFSET + 16)); + cg.scores[i].captures = atoi(CG_Argv(i * SCORE_OFFSET + 17)); + + if (cg.scores[i].client < 0 || cg.scores[i].client >= MAX_CLIENTS) cg.scores[i].client = 0; - cgs.clientinfo[ cg.scores[i].client ].score = cg.scores[i].score; - cgs.clientinfo[ cg.scores[i].client ].powerups = powerups; + cgs.clientinfo[cg.scores[i].client].score = cg.scores[i].score; + cgs.clientinfo[cg.scores[i].client].powerups = powerups; cg.scores[i].team = cgs.clientinfo[cg.scores[i].client].team; } - CG_SetScoreSelection( NULL ); + CG_SetScoreSelection(NULL); } /* @@ -91,33 +91,32 @@ CG_ParseTeamInfo ================= */ #define TEAMINFO_OFFSET (6) -static void CG_ParseTeamInfo( void ) { +static void CG_ParseTeamInfo(void) { int i, client; - numSortedTeamPlayers = atoi( CG_Argv( 1 ) ); - if ( numSortedTeamPlayers < 0 || numSortedTeamPlayers > TEAM_MAXOVERLAY ) { - trap->Error( ERR_DROP, "CG_ParseTeamInfo: numSortedTeamPlayers out of range (%d)", numSortedTeamPlayers ); + numSortedTeamPlayers = atoi(CG_Argv(1)); + if (numSortedTeamPlayers < 0 || numSortedTeamPlayers > TEAM_MAXOVERLAY) { + trap->Error(ERR_DROP, "CG_ParseTeamInfo: numSortedTeamPlayers out of range (%d)", numSortedTeamPlayers); return; } - for ( i=0; i= MAX_CLIENTS ) { - trap->Error( ERR_DROP, "CG_ParseTeamInfo: bad client number: %d", client ); + for (i = 0; i < numSortedTeamPlayers; i++) { + client = atoi(CG_Argv(i * TEAMINFO_OFFSET + 2)); + if (client < 0 || client >= MAX_CLIENTS) { + trap->Error(ERR_DROP, "CG_ParseTeamInfo: bad client number: %d", client); return; } sortedTeamPlayers[i] = client; - cgs.clientinfo[client].location = atoi( CG_Argv( i*TEAMINFO_OFFSET + 3 ) ); - cgs.clientinfo[client].health = atoi( CG_Argv( i*TEAMINFO_OFFSET + 4 ) ); - cgs.clientinfo[client].armor = atoi( CG_Argv( i*TEAMINFO_OFFSET + 5 ) ); - cgs.clientinfo[client].curWeapon = atoi( CG_Argv( i*TEAMINFO_OFFSET + 6 ) ); - cgs.clientinfo[client].powerups = atoi( CG_Argv( i*TEAMINFO_OFFSET + 7 ) ); + cgs.clientinfo[client].location = atoi(CG_Argv(i * TEAMINFO_OFFSET + 3)); + cgs.clientinfo[client].health = atoi(CG_Argv(i * TEAMINFO_OFFSET + 4)); + cgs.clientinfo[client].armor = atoi(CG_Argv(i * TEAMINFO_OFFSET + 5)); + cgs.clientinfo[client].curWeapon = atoi(CG_Argv(i * TEAMINFO_OFFSET + 6)); + cgs.clientinfo[client].powerups = atoi(CG_Argv(i * TEAMINFO_OFFSET + 7)); } } - /* ================ CG_ParseServerinfo @@ -126,95 +125,92 @@ This is called explicitly when the gamestate is first received, and whenever the server updates any serverinfo flagged cvars ================ */ -void CG_ParseServerinfo( void ) { +void CG_ParseServerinfo(void) { const char *info = NULL; char *mapname; int i, value; - info = CG_ConfigString( CS_SERVERINFO ); + info = CG_ConfigString(CS_SERVERINFO); - cgs.debugMelee = atoi( Info_ValueForKey( info, "g_debugMelee" ) ); //trap->Cvar_GetHiddenVarValue("g_iknowkungfu"); - cgs.stepSlideFix = atoi( Info_ValueForKey( info, "g_stepSlideFix" ) ); + cgs.debugMelee = atoi(Info_ValueForKey(info, "g_debugMelee")); // trap->Cvar_GetHiddenVarValue("g_iknowkungfu"); + cgs.stepSlideFix = atoi(Info_ValueForKey(info, "g_stepSlideFix")); - cgs.noSpecMove = atoi( Info_ValueForKey( info, "g_noSpecMove" ) ); + cgs.noSpecMove = atoi(Info_ValueForKey(info, "g_noSpecMove")); - cgs.siegeTeamSwitch = atoi( Info_ValueForKey( info, "g_siegeTeamSwitch" ) ); + cgs.siegeTeamSwitch = atoi(Info_ValueForKey(info, "g_siegeTeamSwitch")); - cgs.showDuelHealths = atoi( Info_ValueForKey( info, "g_showDuelHealths" ) ); + cgs.showDuelHealths = atoi(Info_ValueForKey(info, "g_showDuelHealths")); - cgs.gametype = atoi( Info_ValueForKey( info, "g_gametype" ) ); + cgs.gametype = atoi(Info_ValueForKey(info, "g_gametype")); trap->Cvar_Set("g_gametype", va("%i", cgs.gametype)); - cgs.needpass = atoi( Info_ValueForKey( info, "g_needpass" ) ); - cgs.jediVmerc = atoi( Info_ValueForKey( info, "g_jediVmerc" ) ); + cgs.needpass = atoi(Info_ValueForKey(info, "g_needpass")); + cgs.jediVmerc = atoi(Info_ValueForKey(info, "g_jediVmerc")); // this changes on map_restart, attempt to precache weapons - value = atoi( Info_ValueForKey( info, "g_weaponDisable" ) ); - if ( cgs.wDisable != value ) { + value = atoi(Info_ValueForKey(info, "g_weaponDisable")); + if (cgs.wDisable != value) { gitem_t *item = NULL; itemInfo_t *itemInfo = NULL; cgs.wDisable = value; - for ( i=1, item=bg_itemlist, itemInfo = cg_items; - igiType == IT_WEAPON ) - CG_RegisterWeapon( item->giTag ); + for (i = 1, item = bg_itemlist, itemInfo = cg_items; i < bg_numItems; i++, item++, itemInfo++) { // register all weapons that aren't disabled + if (item->giType == IT_WEAPON) + CG_RegisterWeapon(item->giTag); } } - cgs.fDisable = atoi( Info_ValueForKey( info, "g_forcePowerDisable" ) ); - cgs.dmflags = atoi( Info_ValueForKey( info, "dmflags" ) ); - cgs.duel_fraglimit = atoi( Info_ValueForKey( info, "duel_fraglimit" ) ); - cgs.capturelimit = atoi( Info_ValueForKey( info, "capturelimit" ) ); + cgs.fDisable = atoi(Info_ValueForKey(info, "g_forcePowerDisable")); + cgs.dmflags = atoi(Info_ValueForKey(info, "dmflags")); + cgs.duel_fraglimit = atoi(Info_ValueForKey(info, "duel_fraglimit")); + cgs.capturelimit = atoi(Info_ValueForKey(info, "capturelimit")); // reset fraglimit warnings - i = atoi( Info_ValueForKey( info, "fraglimit" ) ); - if ( cgs.fraglimit < i ) - cg.fraglimitWarnings &= ~(1|2|4); + i = atoi(Info_ValueForKey(info, "fraglimit")); + if (cgs.fraglimit < i) + cg.fraglimitWarnings &= ~(1 | 2 | 4); cgs.fraglimit = i; // reset timelimit warnings - i = atoi( Info_ValueForKey( info, "timelimit" ) ); - if ( cgs.timelimit != i ) - cg.timelimitWarnings &= ~(1|2); + i = atoi(Info_ValueForKey(info, "timelimit")); + if (cgs.timelimit != i) + cg.timelimitWarnings &= ~(1 | 2); cgs.timelimit = i; - cgs.maxclients = Com_Clampi( 0, MAX_CLIENTS, atoi( Info_ValueForKey( info, "sv_maxclients" ) ) ); - mapname = Info_ValueForKey( info, "mapname" ); - - //rww - You must do this one here, Info_ValueForKey always uses the same memory pointer. - trap->Cvar_Set ( "ui_about_mapname", mapname ); - - Com_sprintf( cgs.mapname, sizeof( cgs.mapname ), "maps/%s.bsp", mapname ); - Com_sprintf( cgs.rawmapname, sizeof( cgs.rawmapname ), "maps/%s", mapname ); -// Q_strncpyz( cgs.redTeam, Info_ValueForKey( info, "g_redTeam" ), sizeof(cgs.redTeam) ); -// trap->Cvar_Set("g_redTeam", cgs.redTeam); -// Q_strncpyz( cgs.blueTeam, Info_ValueForKey( info, "g_blueTeam" ), sizeof(cgs.blueTeam) ); -// trap->Cvar_Set("g_blueTeam", cgs.blueTeam); - - trap->Cvar_Set ( "ui_about_gametype", va("%i", cgs.gametype ) ); - trap->Cvar_Set ( "ui_about_fraglimit", va("%i", cgs.fraglimit ) ); - trap->Cvar_Set ( "ui_about_duellimit", va("%i", cgs.duel_fraglimit ) ); - trap->Cvar_Set ( "ui_about_capturelimit", va("%i", cgs.capturelimit ) ); - trap->Cvar_Set ( "ui_about_timelimit", va("%i", cgs.timelimit ) ); - trap->Cvar_Set ( "ui_about_maxclients", va("%i", cgs.maxclients ) ); - trap->Cvar_Set ( "ui_about_dmflags", va("%i", cgs.dmflags ) ); - trap->Cvar_Set ( "ui_about_hostname", Info_ValueForKey( info, "sv_hostname" ) ); - trap->Cvar_Set ( "ui_about_needpass", Info_ValueForKey( info, "g_needpass" ) ); - trap->Cvar_Set ( "ui_about_botminplayers", Info_ValueForKey ( info, "bot_minplayers" ) ); - - //Set the siege teams based on what the server has for overrides. + cgs.maxclients = Com_Clampi(0, MAX_CLIENTS, atoi(Info_ValueForKey(info, "sv_maxclients"))); + mapname = Info_ValueForKey(info, "mapname"); + + // rww - You must do this one here, Info_ValueForKey always uses the same memory pointer. + trap->Cvar_Set("ui_about_mapname", mapname); + + Com_sprintf(cgs.mapname, sizeof(cgs.mapname), "maps/%s.bsp", mapname); + Com_sprintf(cgs.rawmapname, sizeof(cgs.rawmapname), "maps/%s", mapname); + // Q_strncpyz( cgs.redTeam, Info_ValueForKey( info, "g_redTeam" ), sizeof(cgs.redTeam) ); + // trap->Cvar_Set("g_redTeam", cgs.redTeam); + // Q_strncpyz( cgs.blueTeam, Info_ValueForKey( info, "g_blueTeam" ), sizeof(cgs.blueTeam) ); + // trap->Cvar_Set("g_blueTeam", cgs.blueTeam); + + trap->Cvar_Set("ui_about_gametype", va("%i", cgs.gametype)); + trap->Cvar_Set("ui_about_fraglimit", va("%i", cgs.fraglimit)); + trap->Cvar_Set("ui_about_duellimit", va("%i", cgs.duel_fraglimit)); + trap->Cvar_Set("ui_about_capturelimit", va("%i", cgs.capturelimit)); + trap->Cvar_Set("ui_about_timelimit", va("%i", cgs.timelimit)); + trap->Cvar_Set("ui_about_maxclients", va("%i", cgs.maxclients)); + trap->Cvar_Set("ui_about_dmflags", va("%i", cgs.dmflags)); + trap->Cvar_Set("ui_about_hostname", Info_ValueForKey(info, "sv_hostname")); + trap->Cvar_Set("ui_about_needpass", Info_ValueForKey(info, "g_needpass")); + trap->Cvar_Set("ui_about_botminplayers", Info_ValueForKey(info, "bot_minplayers")); + + // Set the siege teams based on what the server has for overrides. trap->Cvar_Set("cg_siegeTeam1", Info_ValueForKey(info, "g_siegeTeam1")); trap->Cvar_Set("cg_siegeTeam2", Info_ValueForKey(info, "g_siegeTeam2")); - Q_strncpyz( cgs.voteString, CG_ConfigString( CS_VOTE_STRING ), sizeof( cgs.voteString ) ); + Q_strncpyz(cgs.voteString, CG_ConfigString(CS_VOTE_STRING), sizeof(cgs.voteString)); // synchronise our expected snaps/sec with the server's framerate - i = atoi( Info_ValueForKey( info, "sv_fps" ) ); - if ( i ) - trap->Cvar_Set( "snaps", va( "%i", i ) ); + i = atoi(Info_ValueForKey(info, "sv_fps")); + if (i) + trap->Cvar_Set("snaps", va("%i", i)); } /* @@ -222,27 +218,25 @@ void CG_ParseServerinfo( void ) { CG_ParseWarmup ================== */ -static void CG_ParseWarmup( void ) { - const char *info; - int warmup; +static void CG_ParseWarmup(void) { + const char *info; + int warmup; - info = CG_ConfigString( CS_WARMUP ); + info = CG_ConfigString(CS_WARMUP); - warmup = atoi( info ); + warmup = atoi(info); cg.warmupCount = -1; cg.warmup = warmup; } // this is a reverse map of flag statuses as seen in g_team.c -//static char ctfFlagStatusRemap[] = { '0', '1', '*', '*', '2' }; -static char ctfFlagStatusRemap[] = { - FLAG_ATBASE, - FLAG_TAKEN, // CTF - // server doesn't use FLAG_TAKEN_RED or FLAG_TAKEN_BLUE - // which was originally for 1-flag CTF. - FLAG_DROPPED -}; +// static char ctfFlagStatusRemap[] = { '0', '1', '*', '*', '2' }; +static char ctfFlagStatusRemap[] = {FLAG_ATBASE, + FLAG_TAKEN, // CTF + // server doesn't use FLAG_TAKEN_RED or FLAG_TAKEN_BLUE + // which was originally for 1-flag CTF. + FLAG_DROPPED}; /* ================ @@ -251,64 +245,60 @@ CG_SetConfigValues Called on load to set the initial values from configure strings ================ */ -void CG_SetConfigValues( void ) -{ +void CG_SetConfigValues(void) { const char *s; const char *str; - cgs.scores1 = atoi( CG_ConfigString( CS_SCORES1 ) ); - cgs.scores2 = atoi( CG_ConfigString( CS_SCORES2 ) ); - cgs.levelStartTime = atoi( CG_ConfigString( CS_LEVEL_START_TIME ) ); - if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY ) { + cgs.scores1 = atoi(CG_ConfigString(CS_SCORES1)); + cgs.scores2 = atoi(CG_ConfigString(CS_SCORES2)); + cgs.levelStartTime = atoi(CG_ConfigString(CS_LEVEL_START_TIME)); + if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTY) { int redflagId = 0, blueflagId = 0; - s = CG_ConfigString( CS_FLAGSTATUS ); + s = CG_ConfigString(CS_FLAGSTATUS); redflagId = s[0] - '0'; blueflagId = s[1] - '0'; // fix: proper flag statuses mapping for dropped flag - if ( redflagId >= 0 && redflagId < ARRAY_LEN( ctfFlagStatusRemap ) ) + if (redflagId >= 0 && redflagId < ARRAY_LEN(ctfFlagStatusRemap)) cgs.redflag = ctfFlagStatusRemap[redflagId]; - if ( blueflagId >= 0 && blueflagId < ARRAY_LEN( ctfFlagStatusRemap ) ) + if (blueflagId >= 0 && blueflagId < ARRAY_LEN(ctfFlagStatusRemap)) cgs.blueflag = ctfFlagStatusRemap[blueflagId]; } - cg.warmup = atoi( CG_ConfigString( CS_WARMUP ) ); + cg.warmup = atoi(CG_ConfigString(CS_WARMUP)); // Track who the jedi master is - cgs.jediMaster = atoi ( CG_ConfigString ( CS_CLIENT_JEDIMASTER ) ); - cgs.duelWinner = atoi ( CG_ConfigString ( CS_CLIENT_DUELWINNER ) ); + cgs.jediMaster = atoi(CG_ConfigString(CS_CLIENT_JEDIMASTER)); + cgs.duelWinner = atoi(CG_ConfigString(CS_CLIENT_DUELWINNER)); str = CG_ConfigString(CS_CLIENT_DUELISTS); - if (str && str[0]) - { + if (str && str[0]) { char buf[64]; int c = 0; int i = 0; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist1 = atoi ( buf ); + cgs.duelist1 = atoi(buf); c = 0; i++; - while (str[i]) - { + while (str[i]) { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist2 = atoi ( buf ); + cgs.duelist2 = atoi(buf); } } @@ -322,29 +312,29 @@ void CG_ShaderStateChanged(void) { char newShader[MAX_QPATH]; char timeOffset[16]; const char *o; - char *n,*t; + char *n, *t; - o = CG_ConfigString( CS_SHADERSTATE ); + o = CG_ConfigString(CS_SHADERSTATE); while (o && *o) { n = strstr(o, "="); if (n && *n) { - strncpy(originalShader, o, n-o); - originalShader[n-o] = 0; + strncpy(originalShader, o, n - o); + originalShader[n - o] = 0; n++; t = strstr(n, ":"); if (t && *t) { - strncpy(newShader, n, t-n); - newShader[t-n] = 0; + strncpy(newShader, n, t - n); + newShader[t - n] = 0; } else { break; } t++; o = strstr(t, "@"); if (o) { - strncpy(timeOffset, t, o-t); - timeOffset[o-t] = 0; + strncpy(timeOffset, t, o - t); + timeOffset[o - t] = 0; o++; - trap->R_RemapShader( originalShader, newShader, timeOffset ); + trap->R_RemapShader(originalShader, newShader, timeOffset); } } else { break; @@ -358,10 +348,8 @@ extern const char *cg_customExtraSoundNames[MAX_CUSTOM_EXTRA_SOUNDS]; extern const char *cg_customJediSoundNames[MAX_CUSTOM_JEDI_SOUNDS]; extern const char *cg_customDuelSoundNames[MAX_CUSTOM_DUEL_SOUNDS]; -static const char *GetCustomSoundForType(int setType, int index) -{ - switch (setType) - { +static const char *GetCustomSoundForType(int setType, int index) { + switch (setType) { case 1: return cg_customSoundNames[index]; case 2: @@ -380,10 +368,8 @@ static const char *GetCustomSoundForType(int setType, int index) } } -void SetCustomSoundForType(clientInfo_t *ci, int setType, int index, sfxHandle_t sfx) -{ - switch (setType) - { +void SetCustomSoundForType(clientInfo_t *ci, int setType, int index, sfxHandle_t sfx) { + switch (setType) { case 1: ci->sounds[index] = sfx; break; @@ -408,13 +394,11 @@ void SetCustomSoundForType(clientInfo_t *ci, int setType, int index, sfxHandle_t } } -static void CG_RegisterCustomSounds(clientInfo_t *ci, int setType, const char *psDir) -{ +static void CG_RegisterCustomSounds(clientInfo_t *ci, int setType, const char *psDir) { int iTableEntries = 0; int i; - switch (setType) - { + switch (setType) { case 1: iTableEntries = MAX_CUSTOM_SOUNDS; break; @@ -435,44 +419,39 @@ static void CG_RegisterCustomSounds(clientInfo_t *ci, int setType, const char *p return; } - for ( i = 0 ; iS_RegisterSound( va("sound/chars/%s/misc/%s", psDir, s) ); + hSFX = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", psDir, s)); - if (hSFX == 0) - { + if (hSFX == 0) { char modifiedSound[MAX_QPATH]; char *p; strcpy(modifiedSound, s); - p = strchr(modifiedSound,'.'); + p = strchr(modifiedSound, '.'); - if (p) - { + if (p) { char testNumber[2]; p--; - //before we destroy it.. we want to see if this is actually a number. - //If it isn't a number then don't try decrementing and registering as - //it will only cause a disk hit (we don't try precaching such files) + // before we destroy it.. we want to see if this is actually a number. + // If it isn't a number then don't try decrementing and registering as + // it will only cause a disk hit (we don't try precaching such files) testNumber[0] = *p; testNumber[1] = 0; - if (atoi(testNumber)) - { + if (atoi(testNumber)) { *p = 0; strcat(modifiedSound, "1.wav"); - hSFX = trap->S_RegisterSound( va("sound/chars/%s/misc/%s", psDir, modifiedSound) ); + hSFX = trap->S_RegisterSound(va("sound/chars/%s/misc/%s", psDir, modifiedSound)); } } } @@ -481,8 +460,7 @@ static void CG_RegisterCustomSounds(clientInfo_t *ci, int setType, const char *p } } -void CG_PrecacheNPCSounds(const char *str) -{ +void CG_PrecacheNPCSounds(const char *str) { char sEnd[MAX_QPATH]; char pEnd[MAX_QPATH]; int i = 0; @@ -491,37 +469,31 @@ void CG_PrecacheNPCSounds(const char *str) k = 2; - while (str[k]) - { - pEnd[k-2] = str[k]; + while (str[k]) { + pEnd[k - 2] = str[k]; k++; } - pEnd[k-2] = 0; + pEnd[k - 2] = 0; - while (i < 4) //4 types - { //It would be better if we knew what type this actually was (extra, combat, jedi, etc). - //But that would require extra configstring indexing and that is a bad thing. + while (i < 4) // 4 types + { // It would be better if we knew what type this actually was (extra, combat, jedi, etc). + // But that would require extra configstring indexing and that is a bad thing. - while (j < MAX_CUSTOM_SOUNDS) - { - const char *s = GetCustomSoundForType(i+1, j); + while (j < MAX_CUSTOM_SOUNDS) { + const char *s = GetCustomSoundForType(i + 1, j); - if (s && s[0]) - { //whatever it is, try registering it under this folder. + if (s && s[0]) { // whatever it is, try registering it under this folder. k = 1; - while (s[k]) - { - sEnd[k-1] = s[k]; + while (s[k]) { + sEnd[k - 1] = s[k]; k++; } - sEnd[k-1] = 0; + sEnd[k - 1] = 0; trap->S_Shutup(qtrue); - trap->S_RegisterSound( va("sound/chars/%s/misc/%s", pEnd, sEnd) ); + trap->S_RegisterSound(va("sound/chars/%s/misc/%s", pEnd, sEnd)); trap->S_Shutup(qfalse); - } - else - { //move onto the next set + } else { // move onto the next set break; } @@ -533,28 +505,23 @@ void CG_PrecacheNPCSounds(const char *str) } } -void CG_HandleNPCSounds(centity_t *cent) -{ - if (!cent->npcClient) - { +void CG_HandleNPCSounds(centity_t *cent) { + if (!cent->npcClient) { return; } - //standard - if (cent->currentState.csSounds_Std) - { - const char *s = CG_ConfigString( CS_SOUNDS + cent->currentState.csSounds_Std ); + // standard + if (cent->currentState.csSounds_Std) { + const char *s = CG_ConfigString(CS_SOUNDS + cent->currentState.csSounds_Std); - if (s && s[0]) - { + if (s && s[0]) { char sEnd[MAX_QPATH]; int i = 2; int j = 0; - //Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates - //it is an NPC custom sound dir. - while (s[i]) - { + // Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates + // it is an NPC custom sound dir. + while (s[i]) { sEnd[j] = s[i]; j++; i++; @@ -563,27 +530,22 @@ void CG_HandleNPCSounds(centity_t *cent) CG_RegisterCustomSounds(cent->npcClient, 1, sEnd); } - } - else - { + } else { memset(¢->npcClient->sounds, 0, sizeof(cent->npcClient->sounds)); } - //combat - if (cent->currentState.csSounds_Combat) - { - const char *s = CG_ConfigString( CS_SOUNDS + cent->currentState.csSounds_Combat ); + // combat + if (cent->currentState.csSounds_Combat) { + const char *s = CG_ConfigString(CS_SOUNDS + cent->currentState.csSounds_Combat); - if (s && s[0]) - { + if (s && s[0]) { char sEnd[MAX_QPATH]; int i = 2; int j = 0; - //Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates - //it is an NPC custom sound dir. - while (s[i]) - { + // Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates + // it is an NPC custom sound dir. + while (s[i]) { sEnd[j] = s[i]; j++; i++; @@ -592,27 +554,22 @@ void CG_HandleNPCSounds(centity_t *cent) CG_RegisterCustomSounds(cent->npcClient, 2, sEnd); } - } - else - { + } else { memset(¢->npcClient->combatSounds, 0, sizeof(cent->npcClient->combatSounds)); } - //extra - if (cent->currentState.csSounds_Extra) - { - const char *s = CG_ConfigString( CS_SOUNDS + cent->currentState.csSounds_Extra ); + // extra + if (cent->currentState.csSounds_Extra) { + const char *s = CG_ConfigString(CS_SOUNDS + cent->currentState.csSounds_Extra); - if (s && s[0]) - { + if (s && s[0]) { char sEnd[MAX_QPATH]; int i = 2; int j = 0; - //Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates - //it is an NPC custom sound dir. - while (s[i]) - { + // Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates + // it is an NPC custom sound dir. + while (s[i]) { sEnd[j] = s[i]; j++; i++; @@ -621,27 +578,22 @@ void CG_HandleNPCSounds(centity_t *cent) CG_RegisterCustomSounds(cent->npcClient, 3, sEnd); } - } - else - { + } else { memset(¢->npcClient->extraSounds, 0, sizeof(cent->npcClient->extraSounds)); } - //jedi - if (cent->currentState.csSounds_Jedi) - { - const char *s = CG_ConfigString( CS_SOUNDS + cent->currentState.csSounds_Jedi ); + // jedi + if (cent->currentState.csSounds_Jedi) { + const char *s = CG_ConfigString(CS_SOUNDS + cent->currentState.csSounds_Jedi); - if (s && s[0]) - { + if (s && s[0]) { char sEnd[MAX_QPATH]; int i = 2; int j = 0; - //Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates - //it is an NPC custom sound dir. - while (s[i]) - { + // Parse past the initial "*" which indicates this is a custom sound, and the $ which indicates + // it is an NPC custom sound dir. + while (s[i]) { sEnd[j] = s[i]; j++; i++; @@ -650,9 +602,7 @@ void CG_HandleNPCSounds(centity_t *cent) CG_RegisterCustomSounds(cent->npcClient, 4, sEnd); } - } - else - { + } else { memset(¢->npcClient->jediSounds, 0, sizeof(cent->npcClient->jediSounds)); } } @@ -661,50 +611,46 @@ int CG_HandleAppendedSkin(char *modelName); void CG_CacheG2AnimInfo(char *modelName); // nmckenzie: DUEL_HEALTH - fixme - we could really clean this up immensely with some helper functions. -void SetDuelistHealthsFromConfigString ( const char *str ) { +void SetDuelistHealthsFromConfigString(const char *str) { char buf[64]; int c = 0; int i = 0; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist1health = atoi ( buf ); + cgs.duelist1health = atoi(buf); c = 0; i++; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist2health = atoi ( buf ); + cgs.duelist2health = atoi(buf); c = 0; i++; - if ( str[i] == '!' ) - { // we only have 2 duelists, apparently. + if (str[i] == '!') { // we only have 2 duelists, apparently. cgs.duelist3health = -1; return; } - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist3health = atoi ( buf ); + cgs.duelist3health = atoi(buf); } /* @@ -717,75 +663,67 @@ extern int cgSiegeRoundState; extern int cgSiegeRoundTime; void CG_ParseSiegeObjectiveStatus(const char *str); void CG_ParseWeatherEffect(const char *str); -extern void CG_ParseSiegeState(const char *str); //cg_main.c +extern void CG_ParseSiegeState(const char *str); // cg_main.c extern int cg_beatingSiegeTime; extern int cg_siegeWinTeam; -static void CG_ConfigStringModified( void ) { - const char *str; - int num; +static void CG_ConfigStringModified(void) { + const char *str; + int num; - num = atoi( CG_Argv( 1 ) ); + num = atoi(CG_Argv(1)); // get the gamestate from the client system, which will have the // new configstring already integrated - trap->GetGameState( &cgs.gameState ); + trap->GetGameState(&cgs.gameState); // look up the individual string that was modified - str = CG_ConfigString( num ); + str = CG_ConfigString(num); // do something with it if necessary - if ( num == CS_MUSIC ) { - CG_StartMusic( qtrue ); - } else if ( num == CS_SERVERINFO ) { + if (num == CS_MUSIC) { + CG_StartMusic(qtrue); + } else if (num == CS_SERVERINFO) { CG_ParseServerinfo(); - } else if ( num == CS_WARMUP ) { + } else if (num == CS_WARMUP) { CG_ParseWarmup(); - } else if ( num == CS_SCORES1 ) { - cgs.scores1 = atoi( str ); - } else if ( num == CS_SCORES2 ) { - cgs.scores2 = atoi( str ); - } else if ( num == CS_CLIENT_JEDIMASTER ) { - cgs.jediMaster = atoi ( str ); - } - else if ( num == CS_CLIENT_DUELWINNER ) - { - cgs.duelWinner = atoi ( str ); - } - else if ( num == CS_CLIENT_DUELISTS ) - { + } else if (num == CS_SCORES1) { + cgs.scores1 = atoi(str); + } else if (num == CS_SCORES2) { + cgs.scores2 = atoi(str); + } else if (num == CS_CLIENT_JEDIMASTER) { + cgs.jediMaster = atoi(str); + } else if (num == CS_CLIENT_DUELWINNER) { + cgs.duelWinner = atoi(str); + } else if (num == CS_CLIENT_DUELISTS) { char buf[64]; int c = 0; int i = 0; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist1 = atoi ( buf ); + cgs.duelist1 = atoi(buf); c = 0; i++; - while (str[i] && str[i] != '|') - { + while (str[i] && str[i] != '|') { buf[c] = str[i]; c++; i++; } buf[c] = 0; - cgs.duelist2 = atoi ( buf ); + cgs.duelist2 = atoi(buf); - if (str[i]) - { + if (str[i]) { c = 0; i++; - while (str[i]) - { + while (str[i]) { buf[c] = str[i]; c++; i++; @@ -794,166 +732,127 @@ static void CG_ConfigStringModified( void ) { cgs.duelist3 = atoi(buf); } - } - else if ( num == CS_CLIENT_DUELHEALTHS ) { // nmckenzie: DUEL_HEALTH + } else if (num == CS_CLIENT_DUELHEALTHS) { // nmckenzie: DUEL_HEALTH SetDuelistHealthsFromConfigString(str); - } - else if ( num == CS_LEVEL_START_TIME ) { - cgs.levelStartTime = atoi( str ); - } else if ( num == CS_VOTE_TIME ) { - cgs.voteTime = atoi( str ); + } else if (num == CS_LEVEL_START_TIME) { + cgs.levelStartTime = atoi(str); + } else if (num == CS_VOTE_TIME) { + cgs.voteTime = atoi(str); cgs.voteModified = qtrue; - } else if ( num == CS_VOTE_YES ) { - cgs.voteYes = atoi( str ); + } else if (num == CS_VOTE_YES) { + cgs.voteYes = atoi(str); cgs.voteModified = qtrue; - } else if ( num == CS_VOTE_NO ) { - cgs.voteNo = atoi( str ); + } else if (num == CS_VOTE_NO) { + cgs.voteNo = atoi(str); cgs.voteModified = qtrue; - } else if ( num == CS_VOTE_STRING ) { - Q_strncpyz( cgs.voteString, str, sizeof( cgs.voteString ) ); - } else if ( num >= CS_TEAMVOTE_TIME && num <= CS_TEAMVOTE_TIME + 1) { - cgs.teamVoteTime[num-CS_TEAMVOTE_TIME] = atoi( str ); - cgs.teamVoteModified[num-CS_TEAMVOTE_TIME] = qtrue; - } else if ( num >= CS_TEAMVOTE_YES && num <= CS_TEAMVOTE_YES + 1) { - cgs.teamVoteYes[num-CS_TEAMVOTE_YES] = atoi( str ); - cgs.teamVoteModified[num-CS_TEAMVOTE_YES] = qtrue; - } else if ( num >= CS_TEAMVOTE_NO && num <= CS_TEAMVOTE_NO + 1) { - cgs.teamVoteNo[num-CS_TEAMVOTE_NO] = atoi( str ); - cgs.teamVoteModified[num-CS_TEAMVOTE_NO] = qtrue; - } else if ( num >= CS_TEAMVOTE_STRING && num <= CS_TEAMVOTE_STRING + 1) { - Q_strncpyz( cgs.teamVoteString[num-CS_TEAMVOTE_STRING], str, sizeof( cgs.teamVoteString ) ); - } else if ( num == CS_INTERMISSION ) { - cg.intermissionStarted = atoi( str ); - } else if ( num >= CS_MODELS && num < CS_MODELS+MAX_MODELS ) { + } else if (num == CS_VOTE_STRING) { + Q_strncpyz(cgs.voteString, str, sizeof(cgs.voteString)); + } else if (num >= CS_TEAMVOTE_TIME && num <= CS_TEAMVOTE_TIME + 1) { + cgs.teamVoteTime[num - CS_TEAMVOTE_TIME] = atoi(str); + cgs.teamVoteModified[num - CS_TEAMVOTE_TIME] = qtrue; + } else if (num >= CS_TEAMVOTE_YES && num <= CS_TEAMVOTE_YES + 1) { + cgs.teamVoteYes[num - CS_TEAMVOTE_YES] = atoi(str); + cgs.teamVoteModified[num - CS_TEAMVOTE_YES] = qtrue; + } else if (num >= CS_TEAMVOTE_NO && num <= CS_TEAMVOTE_NO + 1) { + cgs.teamVoteNo[num - CS_TEAMVOTE_NO] = atoi(str); + cgs.teamVoteModified[num - CS_TEAMVOTE_NO] = qtrue; + } else if (num >= CS_TEAMVOTE_STRING && num <= CS_TEAMVOTE_STRING + 1) { + Q_strncpyz(cgs.teamVoteString[num - CS_TEAMVOTE_STRING], str, sizeof(cgs.teamVoteString)); + } else if (num == CS_INTERMISSION) { + cg.intermissionStarted = atoi(str); + } else if (num >= CS_MODELS && num < CS_MODELS + MAX_MODELS) { char modelName[MAX_QPATH]; strcpy(modelName, str); - if (strstr(modelName, ".glm") || modelName[0] == '$') - { //Check to see if it has a custom skin attached. + if (strstr(modelName, ".glm") || modelName[0] == '$') { // Check to see if it has a custom skin attached. CG_HandleAppendedSkin(modelName); CG_CacheG2AnimInfo(modelName); } - if (modelName[0] != '$' && modelName[0] != '@') - { //don't register vehicle names and saber names as models. - cgs.gameModels[ num-CS_MODELS ] = trap->R_RegisterModel( modelName ); - } - else - { - cgs.gameModels[ num-CS_MODELS ] = 0; + if (modelName[0] != '$' && modelName[0] != '@') { // don't register vehicle names and saber names as models. + cgs.gameModels[num - CS_MODELS] = trap->R_RegisterModel(modelName); + } else { + cgs.gameModels[num - CS_MODELS] = 0; } -// GHOUL2 Insert start + // GHOUL2 Insert start /* } else if ( num >= CS_CHARSKINS && num < CS_CHARSKINS+MAX_CHARSKINS ) { cgs.skins[ num-CS_CHARSKINS ] = trap->R_RegisterSkin( str ); */ - //rww - removed and replaced with CS_G2BONES -// Ghoul2 Insert end - } else if ( num >= CS_SOUNDS && num < CS_SOUNDS+MAX_SOUNDS ) { - if ( str[0] != '*' ) { // player specific sounds don't register here - cgs.gameSounds[ num-CS_SOUNDS] = trap->S_RegisterSound( str ); - } - else if (str[1] == '$') - { //an NPC soundset + // rww - removed and replaced with CS_G2BONES + // Ghoul2 Insert end + } else if (num >= CS_SOUNDS && num < CS_SOUNDS + MAX_SOUNDS) { + if (str[0] != '*') { // player specific sounds don't register here + cgs.gameSounds[num - CS_SOUNDS] = trap->S_RegisterSound(str); + } else if (str[1] == '$') { // an NPC soundset CG_PrecacheNPCSounds(str); } - } else if ( num >= CS_EFFECTS && num < CS_EFFECTS+MAX_FX ) { - if (str[0] == '*') - { //it's a special global weather effect + } else if (num >= CS_EFFECTS && num < CS_EFFECTS + MAX_FX) { + if (str[0] == '*') { // it's a special global weather effect CG_ParseWeatherEffect(str); - cgs.gameEffects[ num-CS_EFFECTS] = 0; - } - else - { - cgs.gameEffects[ num-CS_EFFECTS] = trap->FX_RegisterEffect( str ); + cgs.gameEffects[num - CS_EFFECTS] = 0; + } else { + cgs.gameEffects[num - CS_EFFECTS] = trap->FX_RegisterEffect(str); } - } - else if ( num >= CS_SIEGE_STATE && num < CS_SIEGE_STATE+1 ) - { - if (str[0]) - { + } else if (num >= CS_SIEGE_STATE && num < CS_SIEGE_STATE + 1) { + if (str[0]) { CG_ParseSiegeState(str); } - } - else if ( num >= CS_SIEGE_WINTEAM && num < CS_SIEGE_WINTEAM+1 ) - { - if (str[0]) - { + } else if (num >= CS_SIEGE_WINTEAM && num < CS_SIEGE_WINTEAM + 1) { + if (str[0]) { cg_siegeWinTeam = atoi(str); } - } - else if ( num >= CS_SIEGE_OBJECTIVES && num < CS_SIEGE_OBJECTIVES+1 ) - { + } else if (num >= CS_SIEGE_OBJECTIVES && num < CS_SIEGE_OBJECTIVES + 1) { CG_ParseSiegeObjectiveStatus(str); - } - else if (num >= CS_SIEGE_TIMEOVERRIDE && num < CS_SIEGE_TIMEOVERRIDE+1) - { + } else if (num >= CS_SIEGE_TIMEOVERRIDE && num < CS_SIEGE_TIMEOVERRIDE + 1) { cg_beatingSiegeTime = atoi(str); - CG_SetSiegeTimerCvar ( cg_beatingSiegeTime ); - } - else if ( num >= CS_PLAYERS && num < CS_PLAYERS+MAX_CLIENTS ) - { - CG_NewClientInfo( num - CS_PLAYERS, qtrue); + CG_SetSiegeTimerCvar(cg_beatingSiegeTime); + } else if (num >= CS_PLAYERS && num < CS_PLAYERS + MAX_CLIENTS) { + CG_NewClientInfo(num - CS_PLAYERS, qtrue); CG_BuildSpectatorString(); - } else if ( num == CS_FLAGSTATUS ) { - if( cgs.gametype == GT_CTF || cgs.gametype == GT_CTY ) { + } else if (num == CS_FLAGSTATUS) { + if (cgs.gametype == GT_CTF || cgs.gametype == GT_CTY) { // format is rb where its red/blue, 0 is at base, 1 is taken, 2 is dropped int redflagId = str[0] - '0', blueflagId = str[1] - '0'; - if ( redflagId >= 0 && redflagId < ARRAY_LEN( ctfFlagStatusRemap ) ) + if (redflagId >= 0 && redflagId < ARRAY_LEN(ctfFlagStatusRemap)) cgs.redflag = ctfFlagStatusRemap[redflagId]; - if ( blueflagId >= 0 && blueflagId < ARRAY_LEN( ctfFlagStatusRemap ) ) + if (blueflagId >= 0 && blueflagId < ARRAY_LEN(ctfFlagStatusRemap)) cgs.blueflag = ctfFlagStatusRemap[blueflagId]; } - } - else if ( num == CS_SHADERSTATE ) { + } else if (num == CS_SHADERSTATE) { CG_ShaderStateChanged(); - } - else if ( num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES * 3)) - { + } else if (num >= CS_LIGHT_STYLES && num < CS_LIGHT_STYLES + (MAX_LIGHT_STYLES * 3)) { CG_SetLightstyle(num - CS_LIGHT_STYLES); } - } -//frees all ghoul2 stuff and npc stuff from a centity -rww -void CG_KillCEntityG2(int entNum) -{ +// frees all ghoul2 stuff and npc stuff from a centity -rww +void CG_KillCEntityG2(int entNum) { int j; clientInfo_t *ci = NULL; centity_t *cent = &cg_entities[entNum]; - if (entNum < MAX_CLIENTS) - { + if (entNum < MAX_CLIENTS) { ci = &cgs.clientinfo[entNum]; - } - else - { + } else { ci = cent->npcClient; } - if (ci) - { - if (ci == cent->npcClient) - { //never going to be != cent->ghoul2, unless cent->ghoul2 has already been removed (and then this ptr is not valid) + if (ci) { + if (ci == cent->npcClient) { // never going to be != cent->ghoul2, unless cent->ghoul2 has already been removed (and then this ptr is not valid) ci->ghoul2Model = NULL; - } - else if (ci->ghoul2Model == cent->ghoul2) - { + } else if (ci->ghoul2Model == cent->ghoul2) { ci->ghoul2Model = NULL; - } - else if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) - { + } else if (ci->ghoul2Model && trap->G2_HaveWeGhoul2Models(ci->ghoul2Model)) { trap->G2API_CleanGhoul2Models(&ci->ghoul2Model); ci->ghoul2Model = NULL; } - //Clean up any weapon instances for custom saber stuff + // Clean up any weapon instances for custom saber stuff j = 0; - while (j < MAX_SABERS) - { - if (ci->ghoul2Weapons[j] && trap->G2_HaveWeGhoul2Models(ci->ghoul2Weapons[j])) - { + while (j < MAX_SABERS) { + if (ci->ghoul2Weapons[j] && trap->G2_HaveWeGhoul2Models(ci->ghoul2Weapons[j])) { trap->G2API_CleanGhoul2Models(&ci->ghoul2Weapons[j]); ci->ghoul2Weapons[j] = NULL; } @@ -962,46 +861,39 @@ void CG_KillCEntityG2(int entNum) } } - if (cent->ghoul2 && trap->G2_HaveWeGhoul2Models(cent->ghoul2)) - { + if (cent->ghoul2 && trap->G2_HaveWeGhoul2Models(cent->ghoul2)) { trap->G2API_CleanGhoul2Models(¢->ghoul2); cent->ghoul2 = NULL; } - if (cent->grip_arm && trap->G2_HaveWeGhoul2Models(cent->grip_arm)) - { + if (cent->grip_arm && trap->G2_HaveWeGhoul2Models(cent->grip_arm)) { trap->G2API_CleanGhoul2Models(¢->grip_arm); cent->grip_arm = NULL; } - if (cent->frame_hold && trap->G2_HaveWeGhoul2Models(cent->frame_hold)) - { + if (cent->frame_hold && trap->G2_HaveWeGhoul2Models(cent->frame_hold)) { trap->G2API_CleanGhoul2Models(¢->frame_hold); cent->frame_hold = NULL; } - if (cent->npcClient) - { + if (cent->npcClient) { CG_DestroyNPCClient(¢->npcClient); } - cent->isRagging = qfalse; //just in case. + cent->isRagging = qfalse; // just in case. cent->ikStatus = qfalse; cent->localAnimIndex = 0; } -void CG_KillCEntityInstances(void) -{ +void CG_KillCEntityInstances(void) { int i = 0; centity_t *cent; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { cent = &cg_entities[i]; - if (i >= MAX_CLIENTS && cent->currentState.number == i) - { //do not clear G2 instances on client ents, they are constant + if (i >= MAX_CLIENTS && cent->currentState.number == i) { // do not clear G2 instances on client ents, they are constant CG_KillCEntityG2(i); } @@ -1010,8 +902,8 @@ void CG_KillCEntityInstances(void) cent->bolt3 = 0; cent->bolt4 = 0; - cent->bodyHeight = 0;//SABER_LENGTH_MAX; - //cent->saberExtendTime = 0; + cent->bodyHeight = 0; // SABER_LENGTH_MAX; + // cent->saberExtendTime = 0; cent->boltInfo = 0; @@ -1019,7 +911,7 @@ void CG_KillCEntityInstances(void) cent->frame_minus2_refreshed = 0; cent->dustTrailTime = 0; cent->ghoul2weapon = NULL; - //cent->torsoBolt = 0; + // cent->torsoBolt = 0; cent->trailTime = 0; cent->frame_hold_time = 0; cent->frame_hold_refreshed = 0; @@ -1048,13 +940,13 @@ A tournament restart will clear everything, but doesn't require a reload of all the media =============== */ -static void CG_MapRestart( void ) { - if ( cg_showMiss.integer ) { - trap->Print( "CG_MapRestart\n" ); +static void CG_MapRestart(void) { + if (cg_showMiss.integer) { + trap->Print("CG_MapRestart\n"); } - trap->R_ClearDecals ( ); - //FIXME: trap->FX_Reset? + trap->R_ClearDecals(); + // FIXME: trap->FX_Reset? CG_InitLocalEntities(); CG_InitMarkPolys(); @@ -1078,9 +970,9 @@ static void CG_MapRestart( void ) { // we really should clear more parts of cg here and stop sounds // play the "fight" sound if this is a restart without warmup - if ( cg.warmup == 0 && cgs.gametype != GT_SIEGE && cgs.gametype != GT_POWERDUEL/* && cgs.gametype == GT_DUEL */) { - trap->S_StartLocalSound( cgs.media.countFightSound, CHAN_ANNOUNCER ); - CG_CenterPrint( CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH*2 ); + if (cg.warmup == 0 && cgs.gametype != GT_SIEGE && cgs.gametype != GT_POWERDUEL /* && cgs.gametype == GT_DUEL */) { + trap->S_StartLocalSound(cgs.media.countFightSound, CHAN_ANNOUNCER); + CG_CenterPrint(CG_GetStringEdString("MP_SVGAME", "BEGIN_DUEL"), 120, GIANTCHAR_WIDTH * 2); } /* if (cg_singlePlayerActive.integer) { @@ -1090,7 +982,7 @@ static void CG_MapRestart( void ) { } } */ -// trap->Cvar_Set("cg_thirdPerson", "0"); + // trap->Cvar_Set("cg_thirdPerson", "0"); } /* @@ -1098,11 +990,11 @@ static void CG_MapRestart( void ) { CG_RemoveChatEscapeChar ================= */ -static void CG_RemoveChatEscapeChar( char *text ) { +static void CG_RemoveChatEscapeChar(char *text) { int i, l; l = 0; - for ( i = 0; text[i]; i++ ) { + for (i = 0; text[i]; i++) { if (text[i] == '\x19') continue; text[l++] = text[i]; @@ -1110,19 +1002,16 @@ static void CG_RemoveChatEscapeChar( char *text ) { text[l] = '\0'; } -#define MAX_STRINGED_SV_STRING 1024 // this is an quake-engine limit, not a StringEd limit +#define MAX_STRINGED_SV_STRING 1024 // this is an quake-engine limit, not a StringEd limit -void CG_CheckSVStringEdRef(char *buf, const char *str) -{ //I don't really like doing this. But it utilizes the system that was already in place. +void CG_CheckSVStringEdRef(char *buf, const char *str) { // I don't really like doing this. But it utilizes the system that was already in place. int i = 0; int b = 0; int strLen = 0; qboolean gotStrip = qfalse; - if (!str || !str[0]) - { - if (str) - { + if (!str || !str[0]) { + if (str) { strcpy(buf, str); } return; @@ -1132,31 +1021,24 @@ void CG_CheckSVStringEdRef(char *buf, const char *str) strLen = strlen(str); - if (strLen >= MAX_STRINGED_SV_STRING) - { + if (strLen >= MAX_STRINGED_SV_STRING) { return; } - while (i < strLen && str[i]) - { + while (i < strLen && str[i]) { gotStrip = qfalse; - if (str[i] == '@' && (i+1) < strLen) - { - if (str[i+1] == '@' && (i+2) < strLen) - { - if (str[i+2] == '@' && (i+3) < strLen) - { //@@@ should mean to insert a StringEd reference here, so insert it into buf at the current place + if (str[i] == '@' && (i + 1) < strLen) { + if (str[i + 1] == '@' && (i + 2) < strLen) { + if (str[i + 2] == '@' && (i + 3) < strLen) { //@@@ should mean to insert a StringEd reference here, so insert it into buf at the current place char stringRef[MAX_STRINGED_SV_STRING]; int r = 0; - while (i < strLen && str[i] == '@') - { + while (i < strLen && str[i] == '@') { i++; } - while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') - { + while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') { stringRef[r] = str[i]; r++; i++; @@ -1170,8 +1052,7 @@ void CG_CheckSVStringEdRef(char *buf, const char *str) } } - if (!gotStrip) - { + if (!gotStrip) { buf[b] = str[i]; b++; } @@ -1181,37 +1062,32 @@ void CG_CheckSVStringEdRef(char *buf, const char *str) buf[b] = 0; } -static void CG_BodyQueueCopy(centity_t *cent, int clientNum, int knownWeapon) -{ - centity_t *source; - animation_t *anim; - float animSpeed; - int flags=BONE_ANIM_OVERRIDE_FREEZE; +static void CG_BodyQueueCopy(centity_t *cent, int clientNum, int knownWeapon) { + centity_t *source; + animation_t *anim; + float animSpeed; + int flags = BONE_ANIM_OVERRIDE_FREEZE; - if (cent->ghoul2) - { + if (cent->ghoul2) { trap->G2API_CleanGhoul2Models(¢->ghoul2); } - if (clientNum < 0 || clientNum >= MAX_CLIENTS) - { + if (clientNum < 0 || clientNum >= MAX_CLIENTS) { return; } - source = &cg_entities[ clientNum ]; + source = &cg_entities[clientNum]; - if (!source) - { + if (!source) { return; } - if (!source->ghoul2) - { + if (!source->ghoul2) { return; } - cent->isRagging = qfalse; //reset in case it's still set from another body that was in this cent slot. - cent->ownerRagging = source->isRagging; //if the owner was in ragdoll state, then we want to go into it too right away. + cent->isRagging = qfalse; // reset in case it's still set from another body that was in this cent slot. + cent->ownerRagging = source->isRagging; // if the owner was in ragdoll state, then we want to go into it too right away. #if 0 VectorCopy(source->lerpOriginOffset, cent->lerpOriginOffset); @@ -1224,403 +1100,380 @@ static void CG_BodyQueueCopy(centity_t *cent, int clientNum, int knownWeapon) trap->G2API_DuplicateGhoul2Instance(source->ghoul2, ¢->ghoul2); - if (source->isRagging) - { //just reset it now. + if (source->isRagging) { // just reset it now. source->isRagging = qfalse; - trap->G2API_SetRagDoll(source->ghoul2, NULL); //calling with null parms resets to no ragdoll. + trap->G2API_SetRagDoll(source->ghoul2, NULL); // calling with null parms resets to no ragdoll. } - //either force the weapon from when we died or remove it if it was a dropped weapon - if (knownWeapon > WP_BRYAR_PISTOL && trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) - { + // either force the weapon from when we died or remove it if it was a dropped weapon + if (knownWeapon > WP_BRYAR_PISTOL && trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) { trap->G2API_RemoveGhoul2Model(&(cent->ghoul2), 1); - } - else if (trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) - { + } else if (trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) { trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, knownWeapon), 0, cent->ghoul2, 1); } - if (!cent->ownerRagging) - { + if (!cent->ownerRagging) { int aNum; int eFrame; qboolean fallBack = qfalse; - //anim = &bgAllAnims[cent->localAnimIndex].anims[ cent->currentState.torsoAnim ]; - if (!BG_InDeathAnim(source->currentState.torsoAnim)) - { //then just snap the corpse into a default - anim = &bgAllAnims[source->localAnimIndex].anims[ BOTH_DEAD1 ]; + // anim = &bgAllAnims[cent->localAnimIndex].anims[ cent->currentState.torsoAnim ]; + if (!BG_InDeathAnim(source->currentState.torsoAnim)) { // then just snap the corpse into a default + anim = &bgAllAnims[source->localAnimIndex].anims[BOTH_DEAD1]; fallBack = qtrue; - } - else - { - anim = &bgAllAnims[source->localAnimIndex].anims[ source->currentState.torsoAnim ]; + } else { + anim = &bgAllAnims[source->localAnimIndex].anims[source->currentState.torsoAnim]; } animSpeed = 50.0f / anim->frameLerp; - if (!fallBack) - { - //this will just set us to the last frame of the animation, in theory - aNum = cgs.clientinfo[source->currentState.number].frame+1; + if (!fallBack) { + // this will just set us to the last frame of the animation, in theory + aNum = cgs.clientinfo[source->currentState.number].frame + 1; - while (aNum >= anim->firstFrame+anim->numFrames) - { + while (aNum >= anim->firstFrame + anim->numFrames) { aNum--; } - if (aNum < anim->firstFrame-1) - { //wrong animation...? - aNum = (anim->firstFrame+anim->numFrames)-1; + if (aNum < anim->firstFrame - 1) { // wrong animation...? + aNum = (anim->firstFrame + anim->numFrames) - 1; } - } - else - { + } else { aNum = anim->firstFrame; } eFrame = anim->firstFrame + anim->numFrames; - //if (!cgs.clientinfo[source->currentState.number].frame || (cent->currentState.torsoAnim) != (source->currentState.torsoAnim) ) + // if (!cgs.clientinfo[source->currentState.number].frame || (cent->currentState.torsoAnim) != (source->currentState.torsoAnim) ) //{ // aNum = (anim->firstFrame+anim->numFrames)-1; - //} + // } trap->G2API_SetBoneAnim(cent->ghoul2, 0, "upper_lumbar", aNum, eFrame, flags, animSpeed, cg.time, -1, 150); trap->G2API_SetBoneAnim(cent->ghoul2, 0, "model_root", aNum, eFrame, flags, animSpeed, cg.time, -1, 150); trap->G2API_SetBoneAnim(cent->ghoul2, 0, "Motion", aNum, eFrame, flags, animSpeed, cg.time, -1, 150); } - //After we create the bodyqueue, regenerate any limbs on the real instance - if (source->torsoBolt) - { + // After we create the bodyqueue, regenerate any limbs on the real instance + if (source->torsoBolt) { CG_ReattachLimb(source); } } void CG_SiegeBriefingDisplay(int team, int dontshow); void CG_ParseSiegeExtendedData(void); -static void CG_SiegeBriefingDisplay_f( void ) { - CG_SiegeBriefingDisplay( atoi( CG_Argv( 1 ) ), 0 ); -} +static void CG_SiegeBriefingDisplay_f(void) { CG_SiegeBriefingDisplay(atoi(CG_Argv(1)), 0); } -static void CG_SiegeClassSelect_f( void ) { - //if (!( trap->Key_GetCatcher() & KEYCATCH_UI )) - //Well, I want it to come up even if the briefing display is up. - trap->OpenUIMenu( UIMENU_CLASSSEL ); //UIMENU_CLASSSEL +static void CG_SiegeClassSelect_f(void) { + // if (!( trap->Key_GetCatcher() & KEYCATCH_UI )) + // Well, I want it to come up even if the briefing display is up. + trap->OpenUIMenu(UIMENU_CLASSSEL); // UIMENU_CLASSSEL } -static void CG_SiegeProfileMenu_f( void ) { - if ( !cg.demoPlayback ) { - trap->Cvar_Set( "ui_myteam", "3" ); - trap->OpenUIMenu( UIMENU_PLAYERCONFIG ); //UIMENU_CLASSSEL +static void CG_SiegeProfileMenu_f(void) { + if (!cg.demoPlayback) { + trap->Cvar_Set("ui_myteam", "3"); + trap->OpenUIMenu(UIMENU_PLAYERCONFIG); // UIMENU_CLASSSEL } } -static void CG_NewForceRank_f( void ) { +static void CG_NewForceRank_f(void) { //"nfr" == "new force rank" (want a short string) int doMenu = 0; int setTeam = 0; int newRank = 0; - if ( trap->Cmd_Argc() < 3 ) { + if (trap->Cmd_Argc() < 3) { #ifdef _DEBUG trap->Print("WARNING: Invalid newForceRank string\n"); #endif return; } - newRank = atoi( CG_Argv( 1 ) ); - doMenu = atoi( CG_Argv( 2 ) ); - setTeam = atoi( CG_Argv( 3 ) ); + newRank = atoi(CG_Argv(1)); + doMenu = atoi(CG_Argv(2)); + setTeam = atoi(CG_Argv(3)); - trap->Cvar_Set( "ui_rankChange", va( "%i", newRank ) ); + trap->Cvar_Set("ui_rankChange", va("%i", newRank)); - trap->Cvar_Set( "ui_myteam", va( "%i", setTeam ) ); + trap->Cvar_Set("ui_myteam", va("%i", setTeam)); - if ( !( trap->Key_GetCatcher() & KEYCATCH_UI ) && doMenu && !cg.demoPlayback ) - trap->OpenUIMenu( UIMENU_PLAYERCONFIG ); + if (!(trap->Key_GetCatcher() & KEYCATCH_UI) && doMenu && !cg.demoPlayback) + trap->OpenUIMenu(UIMENU_PLAYERCONFIG); } -static void CG_KillGhoul2_f( void ) { - //Kill a ghoul2 instance in this slot. - //If it has been occupied since this message was sent somehow, the worst that can (should) happen - //is the instance will have to reinit with its current info. +static void CG_KillGhoul2_f(void) { + // Kill a ghoul2 instance in this slot. + // If it has been occupied since this message was sent somehow, the worst that can (should) happen + // is the instance will have to reinit with its current info. int indexNum = 0; int argNum = trap->Cmd_Argc(); int i; - if ( argNum < 1 ) + if (argNum < 1) return; - for ( i=1; iG2_HaveWeGhoul2Models( cg_entities[indexNum].ghoul2 ) ) { - if ( indexNum < MAX_CLIENTS ) { //You try to do very bad thing! + if (cg_entities[indexNum].ghoul2 && trap->G2_HaveWeGhoul2Models(cg_entities[indexNum].ghoul2)) { + if (indexNum < MAX_CLIENTS) { // You try to do very bad thing! #ifdef _DEBUG Com_Printf("WARNING: Tried to kill a client ghoul2 instance with a kg2 command!\n"); #endif return; } - CG_KillCEntityG2( indexNum ); + CG_KillCEntityG2(indexNum); } } } -static void CG_KillLoopSounds_f( void ) { - //kill looping sounds +static void CG_KillLoopSounds_f(void) { + // kill looping sounds int indexNum = 0; int argNum = trap->Cmd_Argc(); centity_t *clent = NULL; centity_t *trackerent = NULL; - if ( argNum < 1 ) { - assert( 0 ); + if (argNum < 1) { + assert(0); return; } - indexNum = atoi( CG_Argv( 1 ) ); + indexNum = atoi(CG_Argv(1)); - if ( indexNum >= 0 && indexNum < MAX_GENTITIES ) + if (indexNum >= 0 && indexNum < MAX_GENTITIES) clent = &cg_entities[indexNum]; - if ( argNum >= 2 ) { - indexNum = atoi( CG_Argv( 2 ) ); + if (argNum >= 2) { + indexNum = atoi(CG_Argv(2)); - if ( indexNum >= 0 && indexNum < MAX_GENTITIES ) + if (indexNum >= 0 && indexNum < MAX_GENTITIES) trackerent = &cg_entities[indexNum]; } - if ( clent ) - CG_S_StopLoopingSound( clent->currentState.number, -1 ); - if ( trackerent ) - CG_S_StopLoopingSound( trackerent->currentState.number, -1 ); + if (clent) + CG_S_StopLoopingSound(clent->currentState.number, -1); + if (trackerent) + CG_S_StopLoopingSound(trackerent->currentState.number, -1); } -static void CG_RestoreClientGhoul_f( void ) { - //rcg - Restore Client Ghoul (make sure limbs are reattached and ragdoll state is reset - this must be done reliably) - int indexNum = 0; - int argNum = trap->Cmd_Argc(); - centity_t *clent; - qboolean IRCG = qfalse; +static void CG_RestoreClientGhoul_f(void) { + // rcg - Restore Client Ghoul (make sure limbs are reattached and ragdoll state is reset - this must be done reliably) + int indexNum = 0; + int argNum = trap->Cmd_Argc(); + centity_t *clent; + qboolean IRCG = qfalse; - if ( !strcmp( CG_Argv( 0 ), "ircg" ) ) + if (!strcmp(CG_Argv(0), "ircg")) IRCG = qtrue; - if ( argNum < 1 ) { - assert( 0 ); + if (argNum < 1) { + assert(0); return; } - indexNum = atoi( CG_Argv( 1 ) ); - if ( indexNum < 0 || indexNum >= MAX_CLIENTS ) { - assert( 0 ); + indexNum = atoi(CG_Argv(1)); + if (indexNum < 0 || indexNum >= MAX_CLIENTS) { + assert(0); return; } clent = &cg_entities[indexNum]; - //assert( clent->ghoul2 ); - //this can happen while connecting as a client - if ( !clent->ghoul2 ) + // assert( clent->ghoul2 ); + // this can happen while connecting as a client + if (!clent->ghoul2) return; #ifdef _DEBUG - if ( !trap->G2_HaveWeGhoul2Models( clent->ghoul2 ) ) - assert( !"Tried to reset state on a bad instance. Crash is inevitable." ); + if (!trap->G2_HaveWeGhoul2Models(clent->ghoul2)) + assert(!"Tried to reset state on a bad instance. Crash is inevitable."); #endif - if ( IRCG ) { + if (IRCG) { int bodyIndex = 0; int weaponIndex = 0; int side = 0; centity_t *body; - assert( argNum >= 3 ); - bodyIndex = atoi( CG_Argv( 2 ) ); - weaponIndex = atoi( CG_Argv( 3 ) ); - side = atoi( CG_Argv( 4 ) ); + assert(argNum >= 3); + bodyIndex = atoi(CG_Argv(2)); + weaponIndex = atoi(CG_Argv(3)); + side = atoi(CG_Argv(4)); body = &cg_entities[bodyIndex]; - if ( side ) - body->teamPowerType = 1; //light side + if (side) + body->teamPowerType = 1; // light side else - body->teamPowerType = 0; //dark side + body->teamPowerType = 0; // dark side - CG_BodyQueueCopy( body, clent->currentState.number, weaponIndex ); + CG_BodyQueueCopy(body, clent->currentState.number, weaponIndex); } - //reattach any missing limbs - if ( clent->torsoBolt ) + // reattach any missing limbs + if (clent->torsoBolt) CG_ReattachLimb(clent); - //make sure ragdoll state is reset - if ( clent->isRagging ) { + // make sure ragdoll state is reset + if (clent->isRagging) { clent->isRagging = qfalse; - trap->G2API_SetRagDoll( clent->ghoul2, NULL ); //calling with null parms resets to no ragdoll. + trap->G2API_SetRagDoll(clent->ghoul2, NULL); // calling with null parms resets to no ragdoll. } - //clear all the decals as well - trap->G2API_ClearSkinGore( clent->ghoul2 ); + // clear all the decals as well + trap->G2API_ClearSkinGore(clent->ghoul2); clent->weapon = 0; - clent->ghoul2weapon = NULL; //force a weapon reinit + clent->ghoul2weapon = NULL; // force a weapon reinit } -static void CG_CenterPrint_f( void ) { +static void CG_CenterPrint_f(void) { char strEd[MAX_STRINGED_SV_STRING] = {0}; - CG_CheckSVStringEdRef( strEd, CG_Argv( 1 ) ); - CG_CenterPrint( strEd, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + CG_CheckSVStringEdRef(strEd, CG_Argv(1)); + CG_CenterPrint(strEd, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); } -static void CG_CenterPrintSE_f( void ) { +static void CG_CenterPrintSE_f(void) { char strEd[MAX_STRINGED_SV_STRING] = {0}; - char *x = (char *)CG_Argv( 1 ); + char *x = (char *)CG_Argv(1); - if ( x[0] == '@' ) + if (x[0] == '@') x++; - trap->SE_GetStringTextString( x, strEd, MAX_STRINGED_SV_STRING ); - CG_CenterPrint( strEd, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH ); + trap->SE_GetStringTextString(x, strEd, MAX_STRINGED_SV_STRING); + CG_CenterPrint(strEd, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH); } -static void CG_Print_f( void ) { +static void CG_Print_f(void) { char strEd[MAX_STRINGED_SV_STRING] = {0}; - CG_CheckSVStringEdRef( strEd, CG_Argv( 1 ) ); - trap->Print( "%s", strEd ); + CG_CheckSVStringEdRef(strEd, CG_Argv(1)); + trap->Print("%s", strEd); } void CG_ChatBox_AddString(char *chatStr); -static void CG_Chat_f( void ) { +static void CG_Chat_f(void) { char cmd[MAX_STRING_CHARS] = {0}, text[MAX_SAY_TEXT] = {0}; - trap->Cmd_Argv( 0, cmd, sizeof( cmd ) ); + trap->Cmd_Argv(0, cmd, sizeof(cmd)); - if ( !strcmp( cmd, "chat" ) ) { - if ( !cg_teamChatsOnly.integer ) { - if( cg_chatBeep.integer ) - trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); - trap->Cmd_Argv( 1, text, sizeof( text ) ); - CG_RemoveChatEscapeChar( text ); - CG_ChatBox_AddString( text ); - trap->Print( "*%s\n", text ); + if (!strcmp(cmd, "chat")) { + if (!cg_teamChatsOnly.integer) { + if (cg_chatBeep.integer) + trap->S_StartLocalSound(cgs.media.talkSound, CHAN_LOCAL_SOUND); + trap->Cmd_Argv(1, text, sizeof(text)); + CG_RemoveChatEscapeChar(text); + CG_ChatBox_AddString(text); + trap->Print("*%s\n", text); } - } - else if ( !strcmp( cmd, "lchat" ) ) { - if ( !cg_teamChatsOnly.integer ) { - char name[MAX_NETNAME]={0}, loc[MAX_STRING_CHARS]={0}, - color[8]={0}, message[MAX_STRING_CHARS]={0}; + } else if (!strcmp(cmd, "lchat")) { + if (!cg_teamChatsOnly.integer) { + char name[MAX_NETNAME] = {0}, loc[MAX_STRING_CHARS] = {0}, color[8] = {0}, message[MAX_STRING_CHARS] = {0}; - if ( trap->Cmd_Argc() < 4 ) + if (trap->Cmd_Argc() < 4) return; - trap->Cmd_Argv( 1, name, sizeof( name ) ); - trap->Cmd_Argv( 2, loc, sizeof( loc ) ); - trap->Cmd_Argv( 3, color, sizeof( color ) ); - trap->Cmd_Argv( 4, message, sizeof( message ) ); - - //get localized text - if ( loc[0] == '@' ) - trap->SE_GetStringTextString( loc+1, loc, sizeof( loc ) ); - - if( cg_chatBeep.integer ) - trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); - Com_sprintf( text, sizeof( text ), "%s^7<%s> ^%s%s", name, loc, color, message ); - CG_RemoveChatEscapeChar( text ); - CG_ChatBox_AddString( text ); - trap->Print( "*%s\n", text ); + trap->Cmd_Argv(1, name, sizeof(name)); + trap->Cmd_Argv(2, loc, sizeof(loc)); + trap->Cmd_Argv(3, color, sizeof(color)); + trap->Cmd_Argv(4, message, sizeof(message)); + + // get localized text + if (loc[0] == '@') + trap->SE_GetStringTextString(loc + 1, loc, sizeof(loc)); + + if (cg_chatBeep.integer) + trap->S_StartLocalSound(cgs.media.talkSound, CHAN_LOCAL_SOUND); + Com_sprintf(text, sizeof(text), "%s^7<%s> ^%s%s", name, loc, color, message); + CG_RemoveChatEscapeChar(text); + CG_ChatBox_AddString(text); + trap->Print("*%s\n", text); } - } - else if ( !strcmp( cmd, "tchat" ) ) { - if( cg_teamChatBeep.integer ) - trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); - trap->Cmd_Argv( 1, text, sizeof( text ) ); - CG_RemoveChatEscapeChar( text ); - CG_ChatBox_AddString( text ); - trap->Print( "*%s\n", text ); - } - else if ( !strcmp( cmd, "ltchat" ) ) { - char name[MAX_NETNAME]={0}, loc[MAX_STRING_CHARS]={0}, - color[8]={0}, message[MAX_STRING_CHARS]={0}; - - if ( trap->Cmd_Argc() < 4 ) + } else if (!strcmp(cmd, "tchat")) { + if (cg_teamChatBeep.integer) + trap->S_StartLocalSound(cgs.media.talkSound, CHAN_LOCAL_SOUND); + trap->Cmd_Argv(1, text, sizeof(text)); + CG_RemoveChatEscapeChar(text); + CG_ChatBox_AddString(text); + trap->Print("*%s\n", text); + } else if (!strcmp(cmd, "ltchat")) { + char name[MAX_NETNAME] = {0}, loc[MAX_STRING_CHARS] = {0}, color[8] = {0}, message[MAX_STRING_CHARS] = {0}; + + if (trap->Cmd_Argc() < 4) return; - trap->Cmd_Argv( 1, name, sizeof( name ) ); - trap->Cmd_Argv( 2, loc, sizeof( loc ) ); - trap->Cmd_Argv( 3, color, sizeof( color ) ); - trap->Cmd_Argv( 4, message, sizeof( message ) ); - - //get localized text - if ( loc[0] == '@' ) - trap->SE_GetStringTextString( loc+1, loc, sizeof( loc ) ); - - if( cg_teamChatBeep.integer ) - trap->S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND ); - Com_sprintf( text, sizeof( text ), "%s^7<%s> ^%s%s", name, loc, color, message ); - CG_RemoveChatEscapeChar( text ); - CG_ChatBox_AddString( text ); - trap->Print( "*%s\n", text ); + trap->Cmd_Argv(1, name, sizeof(name)); + trap->Cmd_Argv(2, loc, sizeof(loc)); + trap->Cmd_Argv(3, color, sizeof(color)); + trap->Cmd_Argv(4, message, sizeof(message)); + + // get localized text + if (loc[0] == '@') + trap->SE_GetStringTextString(loc + 1, loc, sizeof(loc)); + + if (cg_teamChatBeep.integer) + trap->S_StartLocalSound(cgs.media.talkSound, CHAN_LOCAL_SOUND); + Com_sprintf(text, sizeof(text), "%s^7<%s> ^%s%s", name, loc, color, message); + CG_RemoveChatEscapeChar(text); + CG_ChatBox_AddString(text); + trap->Print("*%s\n", text); } } -static void CG_RemapShader_f( void ) { - if ( trap->Cmd_Argc() == 4 ) { - char shader1[MAX_QPATH]={0}, shader2[MAX_QPATH]={0}; +static void CG_RemapShader_f(void) { + if (trap->Cmd_Argc() == 4) { + char shader1[MAX_QPATH] = {0}, shader2[MAX_QPATH] = {0}; - trap->Cmd_Argv( 1, shader1, sizeof( shader1 ) ); - trap->Cmd_Argv( 2, shader2, sizeof( shader2 ) ); - trap->R_RemapShader( shader1, shader2, CG_Argv( 3 ) ); + trap->Cmd_Argv(1, shader1, sizeof(shader1)); + trap->Cmd_Argv(2, shader2, sizeof(shader2)); + trap->R_RemapShader(shader1, shader2, CG_Argv(3)); } } -static void CG_ClientLevelShot_f( void ) { +static void CG_ClientLevelShot_f(void) { // clientLevelShot is sent before taking a special screenshot for // the menu system during development cg.levelShot = qtrue; } typedef struct serverCommand_s { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } serverCommand_t; -int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((serverCommand_t*)b)->cmd ); -} - -static serverCommand_t commands[] = { - { "chat", CG_Chat_f }, - { "clientLevelShot", CG_ClientLevelShot_f }, - { "cp", CG_CenterPrint_f }, - { "cps", CG_CenterPrintSE_f }, - { "cs", CG_ConfigStringModified }, - { "ircg", CG_RestoreClientGhoul_f }, - { "kg2", CG_KillGhoul2_f }, - { "kls", CG_KillLoopSounds_f }, - { "lchat", CG_Chat_f }, +int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((serverCommand_t *)b)->cmd); } + +static serverCommand_t commands[] = { + {"chat", CG_Chat_f}, + {"clientLevelShot", CG_ClientLevelShot_f}, + {"cp", CG_CenterPrint_f}, + {"cps", CG_CenterPrintSE_f}, + {"cs", CG_ConfigStringModified}, + {"ircg", CG_RestoreClientGhoul_f}, + {"kg2", CG_KillGhoul2_f}, + {"kls", CG_KillLoopSounds_f}, + {"lchat", CG_Chat_f}, // loaddeferred can be both a servercmd and a consolecmd - { "loaddefered", CG_LoadDeferredPlayers }, // FIXME: spelled wrong, but not changing for demo - { "ltchat", CG_Chat_f }, - { "map_restart", CG_MapRestart }, - { "nfr", CG_NewForceRank_f }, - { "print", CG_Print_f }, - { "rcg", CG_RestoreClientGhoul_f }, - { "remapShader", CG_RemapShader_f }, - { "sb", CG_SiegeBriefingDisplay_f }, - { "scl", CG_SiegeClassSelect_f }, - { "scores", CG_ParseScores }, - { "spc", CG_SiegeProfileMenu_f }, - { "sxd", CG_ParseSiegeExtendedData }, - { "tchat", CG_Chat_f }, - { "tinfo", CG_ParseTeamInfo }, + {"loaddefered", CG_LoadDeferredPlayers}, // FIXME: spelled wrong, but not changing for demo + {"ltchat", CG_Chat_f}, + {"map_restart", CG_MapRestart}, + {"nfr", CG_NewForceRank_f}, + {"print", CG_Print_f}, + {"rcg", CG_RestoreClientGhoul_f}, + {"remapShader", CG_RemapShader_f}, + {"sb", CG_SiegeBriefingDisplay_f}, + {"scl", CG_SiegeClassSelect_f}, + {"scores", CG_ParseScores}, + {"spc", CG_SiegeProfileMenu_f}, + {"sxd", CG_ParseSiegeExtendedData}, + {"tchat", CG_Chat_f}, + {"tinfo", CG_ParseTeamInfo}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -1630,23 +1483,23 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -static void CG_ServerCommand( void ) { - const char *cmd = CG_Argv( 0 ); - serverCommand_t *command = NULL; +static void CG_ServerCommand(void) { + const char *cmd = CG_Argv(0); + serverCommand_t *command = NULL; - if ( !cmd[0] ) { + if (!cmd[0]) { // server claimed the command return; } - command = (serverCommand_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), svcmdcmp ); + command = (serverCommand_t *)Q_LinearSearch(cmd, commands, numCommands, sizeof(commands[0]), svcmdcmp); - if ( command ) { + if (command) { command->func(); return; } - trap->Print( "Unknown client game command: %s\n", cmd ); + trap->Print("Unknown client game command: %s\n", cmd); } /* @@ -1657,9 +1510,9 @@ Execute all of the server commands that were received along with this this snapshot. ==================== */ -void CG_ExecuteNewServerCommands( int latestSequence ) { - while ( cgs.serverCommandSequence < latestSequence ) { - if ( trap->GetServerCommand( ++cgs.serverCommandSequence ) ) { +void CG_ExecuteNewServerCommands(int latestSequence) { + while (cgs.serverCommandSequence < latestSequence) { + if (trap->GetServerCommand(++cgs.serverCommandSequence)) { CG_ServerCommand(); } } diff --git a/codemp/cgame/cg_snapshot.c b/codemp/cgame/cg_snapshot.c index 5d7a990e0e..86d23d1c39 100644 --- a/codemp/cgame/cg_snapshot.c +++ b/codemp/cgame/cg_snapshot.c @@ -26,27 +26,24 @@ along with this program; if not, see . #include "cg_local.h" - - /* ================== CG_ResetEntity ================== */ -static void CG_ResetEntity( centity_t *cent ) { +static void CG_ResetEntity(centity_t *cent) { // if the previous snapshot this entity was updated in is at least // an event window back in time then we can reset the previous event - if ( cent->snapShotTime < cg.time - EVENT_VALID_MSEC ) { + if (cent->snapShotTime < cg.time - EVENT_VALID_MSEC) { cent->previousEvent = 0; } cent->trailTime = cg.snap->serverTime; - VectorCopy (cent->currentState.origin, cent->lerpOrigin); - VectorCopy (cent->currentState.angles, cent->lerpAngles); + VectorCopy(cent->currentState.origin, cent->lerpOrigin); + VectorCopy(cent->currentState.angles, cent->lerpAngles); - if (cent->currentState.eFlags & EF_G2ANIMATING) - { //reset the animation state + if (cent->currentState.eFlags & EF_G2ANIMATING) { // reset the animation state cent->pe.torso.animationNumber = -1; cent->pe.legs.animationNumber = -1; } @@ -58,8 +55,8 @@ static void CG_ResetEntity( centity_t *cent ) { } #endif - if ( cent->currentState.eType == ET_PLAYER || cent->currentState.eType == ET_NPC ) { - CG_ResetPlayerEntity( cent ); + if (cent->currentState.eType == ET_PLAYER || cent->currentState.eType == ET_NPC) { + CG_ResetPlayerEntity(cent); } } @@ -70,23 +67,22 @@ CG_TransitionEntity cent->nextState is moved to cent->currentState and events are fired =============== */ -static void CG_TransitionEntity( centity_t *cent ) { +static void CG_TransitionEntity(centity_t *cent) { cent->currentState = cent->nextState; cent->currentValid = qtrue; // reset if the entity wasn't in the last frame or was teleported - if ( !cent->interpolate ) { - CG_ResetEntity( cent ); + if (!cent->interpolate) { + CG_ResetEntity(cent); } // clear the next state. if will be set by the next CG_SetNextSnap cent->interpolate = qfalse; // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } - /* ================== CG_SetInitialSnapshot @@ -98,51 +94,48 @@ CG_TransitionSnapshot instead. FIXME: Also called by map_restart? ================== */ -void CG_SetInitialSnapshot( snapshot_t *snap ) { - int i; - centity_t *cent; - entityState_t *state; +void CG_SetInitialSnapshot(snapshot_t *snap) { + int i; + centity_t *cent; + entityState_t *state; cg.snap = snap; - if ((cg_entities[snap->ps.clientNum].ghoul2 == NULL) && trap->G2_HaveWeGhoul2Models(cgs.clientinfo[snap->ps.clientNum].ghoul2Model)) - { + if ((cg_entities[snap->ps.clientNum].ghoul2 == NULL) && trap->G2_HaveWeGhoul2Models(cgs.clientinfo[snap->ps.clientNum].ghoul2Model)) { trap->G2API_DuplicateGhoul2Instance(cgs.clientinfo[snap->ps.clientNum].ghoul2Model, &cg_entities[snap->ps.clientNum].ghoul2); CG_CopyG2WeaponInstance(&cg_entities[snap->ps.clientNum], FIRST_WEAPON, cg_entities[snap->ps.clientNum].ghoul2); - if (trap->G2API_AddBolt(cg_entities[snap->ps.clientNum].ghoul2, 0, "face") == -1) - { //check now to see if we have this bone for setting anims and such + if (trap->G2API_AddBolt(cg_entities[snap->ps.clientNum].ghoul2, 0, "face") == -1) { // check now to see if we have this bone for setting anims and such cg_entities[snap->ps.clientNum].noFace = qtrue; } } - BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].currentState, qfalse ); + BG_PlayerStateToEntityState(&snap->ps, &cg_entities[snap->ps.clientNum].currentState, qfalse); // sort out solid entities CG_BuildSolidList(); - CG_ExecuteNewServerCommands( snap->serverCommandSequence ); + CG_ExecuteNewServerCommands(snap->serverCommandSequence); // set our local weapon selection pointer to // what the server has indicated the current weapon is CG_Respawn(); - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - state = &cg.snap->entities[ i ]; - cent = &cg_entities[ state->number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + state = &cg.snap->entities[i]; + cent = &cg_entities[state->number]; memcpy(¢->currentState, state, sizeof(entityState_t)); - //cent->currentState = *state; + // cent->currentState = *state; cent->interpolate = qfalse; cent->currentValid = qtrue; - CG_ResetEntity( cent ); + CG_ResetEntity(cent); // check for events - CG_CheckEvents( cent ); + CG_CheckEvents(cent); } } - /* =================== CG_TransitionSnapshot @@ -150,29 +143,29 @@ CG_TransitionSnapshot The transition point from snap to nextSnap has passed =================== */ -extern qboolean CG_UsingEWeb(void); //cg_predict.c -static void CG_TransitionSnapshot( void ) { - centity_t *cent; - snapshot_t *oldFrame; - int i; - - if ( !cg.snap ) { - trap->Error( ERR_DROP, "CG_TransitionSnapshot: NULL cg.snap" ); +extern qboolean CG_UsingEWeb(void); // cg_predict.c +static void CG_TransitionSnapshot(void) { + centity_t *cent; + snapshot_t *oldFrame; + int i; + + if (!cg.snap) { + trap->Error(ERR_DROP, "CG_TransitionSnapshot: NULL cg.snap"); } - if ( !cg.nextSnap ) { - trap->Error( ERR_DROP, "CG_TransitionSnapshot: NULL cg.nextSnap" ); + if (!cg.nextSnap) { + trap->Error(ERR_DROP, "CG_TransitionSnapshot: NULL cg.nextSnap"); } // execute any server string commands before transitioning entities - CG_ExecuteNewServerCommands( cg.nextSnap->serverCommandSequence ); + CG_ExecuteNewServerCommands(cg.nextSnap->serverCommandSequence); // if we had a map_restart, set everthing with initial - if ( !cg.snap ) { + if (!cg.snap) { } // clear the currentValid flag for all entities in the existing snapshot - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; cent->currentValid = qfalse; } @@ -180,14 +173,14 @@ static void CG_TransitionSnapshot( void ) { oldFrame = cg.snap; cg.snap = cg.nextSnap; - //CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg_entities[cg.snap->ps.clientNum]); - //CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg.predictedPlayerEntity); - BG_PlayerStateToEntityState( &cg.snap->ps, &cg_entities[ cg.snap->ps.clientNum ].currentState, qfalse ); - cg_entities[ cg.snap->ps.clientNum ].interpolate = qfalse; + // CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg_entities[cg.snap->ps.clientNum]); + // CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg.predictedPlayerEntity); + BG_PlayerStateToEntityState(&cg.snap->ps, &cg_entities[cg.snap->ps.clientNum].currentState, qfalse); + cg_entities[cg.snap->ps.clientNum].interpolate = qfalse; - for ( i = 0 ; i < cg.snap->numEntities ; i++ ) { - cent = &cg_entities[ cg.snap->entities[ i ].number ]; - CG_TransitionEntity( cent ); + for (i = 0; i < cg.snap->numEntities; i++) { + cent = &cg_entities[cg.snap->entities[i].number]; + CG_TransitionEntity(cent); // remember time of snapshot this entity was last updated in cent->snapShotTime = cg.snap->serverTime; @@ -196,27 +189,24 @@ static void CG_TransitionSnapshot( void ) { cg.nextSnap = NULL; // check for playerstate transition events - if ( oldFrame ) { - playerState_t *ops, *ps; + if (oldFrame) { + playerState_t *ops, *ps; ops = &oldFrame->ps; ps = &cg.snap->ps; // teleporting checks are irrespective of prediction - if ( ( ps->eFlags ^ ops->eFlags ) & EF_TELEPORT_BIT ) { - cg.thisFrameTeleport = qtrue; // will be cleared by prediction code + if ((ps->eFlags ^ ops->eFlags) & EF_TELEPORT_BIT) { + cg.thisFrameTeleport = qtrue; // will be cleared by prediction code } // if we are not doing client side movement prediction for any // reason, then the client events and view changes will be issued now - if ( cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) - || cg_noPredict.integer || g_synchronousClients.integer || CG_UsingEWeb() ) { - CG_TransitionPlayerState( ps, ops ); + if (cg.demoPlayback || (cg.snap->ps.pm_flags & PMF_FOLLOW) || cg_noPredict.integer || g_synchronousClients.integer || CG_UsingEWeb()) { + CG_TransitionPlayerState(ps, ops); } } - } - /* =================== CG_SetNextSnap @@ -224,31 +214,30 @@ CG_SetNextSnap A new snapshot has just been read in from the client system. =================== */ -static void CG_SetNextSnap( snapshot_t *snap ) { - int num; - entityState_t *es; - centity_t *cent; +static void CG_SetNextSnap(snapshot_t *snap) { + int num; + entityState_t *es; + centity_t *cent; cg.nextSnap = snap; - //CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg_entities[cg.snap->ps.clientNum]); - //CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg.predictedPlayerEntity); - BG_PlayerStateToEntityState( &snap->ps, &cg_entities[ snap->ps.clientNum ].nextState, qfalse ); - //cg_entities[ cg.snap->ps.clientNum ].interpolate = qtrue; - //No longer want to do this, as the cg_entities[clnum] and cg.predictedPlayerEntity are one in the same. + // CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg_entities[cg.snap->ps.clientNum]); + // CG_CheckPlayerG2Weapons(&cg.snap->ps, &cg.predictedPlayerEntity); + BG_PlayerStateToEntityState(&snap->ps, &cg_entities[snap->ps.clientNum].nextState, qfalse); + // cg_entities[ cg.snap->ps.clientNum ].interpolate = qtrue; + // No longer want to do this, as the cg_entities[clnum] and cg.predictedPlayerEntity are one in the same. // check for extrapolation errors - for ( num = 0 ; num < snap->numEntities ; num++ ) - { + for (num = 0; num < snap->numEntities; num++) { es = &snap->entities[num]; - cent = &cg_entities[ es->number ]; + cent = &cg_entities[es->number]; memcpy(¢->nextState, es, sizeof(entityState_t)); - //cent->nextState = *es; + // cent->nextState = *es; // if this frame is a teleport, or the entity wasn't in the // previous frame, don't interpolate - if ( !cent->currentValid || ( ( cent->currentState.eFlags ^ es->eFlags ) & EF_TELEPORT_BIT ) ) { + if (!cent->currentValid || ((cent->currentState.eFlags ^ es->eFlags) & EF_TELEPORT_BIT)) { cent->interpolate = qfalse; } else { cent->interpolate = qtrue; @@ -257,19 +246,19 @@ static void CG_SetNextSnap( snapshot_t *snap ) { // if the next frame is a teleport for the playerstate, we // can't interpolate during demos - if ( cg.snap && ( ( snap->ps.eFlags ^ cg.snap->ps.eFlags ) & EF_TELEPORT_BIT ) ) { + if (cg.snap && ((snap->ps.eFlags ^ cg.snap->ps.eFlags) & EF_TELEPORT_BIT)) { cg.nextFrameTeleport = qtrue; } else { cg.nextFrameTeleport = qfalse; } // if changing follow mode, don't interpolate - if ( cg.nextSnap->ps.clientNum != cg.snap->ps.clientNum ) { + if (cg.nextSnap->ps.clientNum != cg.snap->ps.clientNum) { cg.nextFrameTeleport = qtrue; } // if changing server restarts, don't interpolate - if ( ( cg.nextSnap->snapFlags ^ cg.snap->snapFlags ) & SNAPFLAG_SERVERCOUNT ) { + if ((cg.nextSnap->snapFlags ^ cg.snap->snapFlags) & SNAPFLAG_SERVERCOUNT) { cg.nextFrameTeleport = qtrue; } @@ -277,7 +266,6 @@ static void CG_SetNextSnap( snapshot_t *snap ) { CG_BuildSolidList(); } - /* ======================== CG_ReadNextSnapshot @@ -288,18 +276,17 @@ times if the client system fails to return a valid snapshot. ======================== */ -static snapshot_t *CG_ReadNextSnapshot( void ) { - qboolean r; - snapshot_t *dest; +static snapshot_t *CG_ReadNextSnapshot(void) { + qboolean r; + snapshot_t *dest; - if ( cg.latestSnapshotNum > cgs.processedSnapshotNum + 1000 ) { - trap->Print( "WARNING: CG_ReadNextSnapshot: way out of range, %i > %i\n", - cg.latestSnapshotNum, cgs.processedSnapshotNum ); + if (cg.latestSnapshotNum > cgs.processedSnapshotNum + 1000) { + trap->Print("WARNING: CG_ReadNextSnapshot: way out of range, %i > %i\n", cg.latestSnapshotNum, cgs.processedSnapshotNum); } - while ( cgs.processedSnapshotNum < cg.latestSnapshotNum ) { + while (cgs.processedSnapshotNum < cg.latestSnapshotNum) { // decide which of the two slots to load it into - if ( cg.snap == &cg.activeSnapshots[0] ) { + if (cg.snap == &cg.activeSnapshots[0]) { dest = &cg.activeSnapshots[1]; } else { dest = &cg.activeSnapshots[0]; @@ -307,23 +294,22 @@ static snapshot_t *CG_ReadNextSnapshot( void ) { // try to read the snapshot from the client system cgs.processedSnapshotNum++; - r = trap->GetSnapshot( cgs.processedSnapshotNum, dest ); + r = trap->GetSnapshot(cgs.processedSnapshotNum, dest); // FIXME: why would trap->GetSnapshot return a snapshot with the same server time - if ( cg.snap && r && dest->serverTime == cg.snap->serverTime ) { + if (cg.snap && r && dest->serverTime == cg.snap->serverTime) { //[BugFix30] - //According to dumbledore, this situation occurs when you're playing back a demo that was record when - //the game was running in local mode. As such, we need to skip those snaps or the demo looks laggy. - if ( cg.demoPlayback ) - { + // According to dumbledore, this situation occurs when you're playing back a demo that was record when + // the game was running in local mode. As such, we need to skip those snaps or the demo looks laggy. + if (cg.demoPlayback) { continue; } //[/BugFix30] } // if it succeeded, return - if ( r ) { - CG_AddLagometerSnapshotInfo( dest ); + if (r) { + CG_AddLagometerSnapshotInfo(dest); return dest; } @@ -333,7 +319,7 @@ static snapshot_t *CG_ReadNextSnapshot( void ) { // buffer in the client system. // record as a dropped packet - CG_AddLagometerSnapshotInfo( NULL ); + CG_AddLagometerSnapshotInfo(NULL); // If there are additional snapshots, continue trying to // read them. @@ -343,7 +329,6 @@ static snapshot_t *CG_ReadNextSnapshot( void ) { return NULL; } - /* ============ CG_ProcessSnapshots @@ -363,16 +348,16 @@ of an interpolating one) ============ */ -void CG_ProcessSnapshots( void ) { - snapshot_t *snap; - int n; +void CG_ProcessSnapshots(void) { + snapshot_t *snap; + int n; // see what the latest snapshot the client system has is - trap->GetCurrentSnapshotNumber( &n, &cg.latestSnapshotTime ); - if ( n != cg.latestSnapshotNum ) { - if ( n < cg.latestSnapshotNum ) { + trap->GetCurrentSnapshotNumber(&n, &cg.latestSnapshotTime); + if (n != cg.latestSnapshotNum) { + if (n < cg.latestSnapshotNum) { // this should never happen - trap->Error( ERR_DROP, "CG_ProcessSnapshots: n < cg.latestSnapshotNum" ); + trap->Error(ERR_DROP, "CG_ProcessSnapshots: n < cg.latestSnapshotNum"); } cg.latestSnapshotNum = n; } @@ -380,17 +365,17 @@ void CG_ProcessSnapshots( void ) { // If we have yet to receive a snapshot, check for it. // Once we have gotten the first snapshot, cg.snap will // always have valid data for the rest of the game - while ( !cg.snap ) { + while (!cg.snap) { snap = CG_ReadNextSnapshot(); - if ( !snap ) { + if (!snap) { // we can't continue until we get a snapshot return; } // set our weapon selection to what // the playerstate is currently using - if ( !( snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) { - CG_SetInitialSnapshot( snap ); + if (!(snap->snapFlags & SNAPFLAG_NOT_ACTIVE)) { + CG_SetInitialSnapshot(snap); } } @@ -399,44 +384,41 @@ void CG_ProcessSnapshots( void ) { // out of available snapshots do { // if we don't have a nextframe, try and read a new one in - if ( !cg.nextSnap ) { + if (!cg.nextSnap) { snap = CG_ReadNextSnapshot(); // if we still don't have a nextframe, we will just have to // extrapolate - if ( !snap ) { + if (!snap) { break; } - CG_SetNextSnap( snap ); - + CG_SetNextSnap(snap); // if time went backwards, we have a level restart - if ( cg.nextSnap->serverTime < cg.snap->serverTime ) { - trap->Error( ERR_DROP, "CG_ProcessSnapshots: Server time went backwards" ); + if (cg.nextSnap->serverTime < cg.snap->serverTime) { + trap->Error(ERR_DROP, "CG_ProcessSnapshots: Server time went backwards"); } } // if our time is < nextFrame's, we have a nice interpolating state - if ( cg.time >= cg.snap->serverTime && cg.time < cg.nextSnap->serverTime ) { + if (cg.time >= cg.snap->serverTime && cg.time < cg.nextSnap->serverTime) { break; } // we have passed the transition from nextFrame to frame CG_TransitionSnapshot(); - } while ( 1 ); + } while (1); // assert our valid conditions upon exiting - if ( cg.snap == NULL ) { - trap->Error( ERR_DROP, "CG_ProcessSnapshots: cg.snap == NULL" ); + if (cg.snap == NULL) { + trap->Error(ERR_DROP, "CG_ProcessSnapshots: cg.snap == NULL"); } - if ( cg.time < cg.snap->serverTime ) { + if (cg.time < cg.snap->serverTime) { // this can happen right after a vid_restart cg.time = cg.snap->serverTime; } - if ( cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time ) { - trap->Error( ERR_DROP, "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time" ); + if (cg.nextSnap != NULL && cg.nextSnap->serverTime <= cg.time) { + trap->Error(ERR_DROP, "CG_ProcessSnapshots: cg.nextSnap->serverTime <= cg.time"); } - } - diff --git a/codemp/cgame/cg_spawn.c b/codemp/cgame/cg_spawn.c index c10886394a..0aee8fba06 100644 --- a/codemp/cgame/cg_spawn.c +++ b/codemp/cgame/cg_spawn.c @@ -83,65 +83,63 @@ char *CG_NewString( const char *string ) { } #endif -qboolean CG_SpawnString( const char *key, const char *defaultString, char **out ) { +qboolean CG_SpawnString(const char *key, const char *defaultString, char **out) { int i; - if( !cg.spawning ) { - *out = (char*)defaultString; + if (!cg.spawning) { + *out = (char *)defaultString; // trap->Error( ERR_DROP, "CG_SpawnString() called while not spawning" ); } - for( i = 0; i < cg.numSpawnVars; i++ ) { - if( !Q_stricmp( key, cg.spawnVars[i][0] ) ) { + for (i = 0; i < cg.numSpawnVars; i++) { + if (!Q_stricmp(key, cg.spawnVars[i][0])) { *out = cg.spawnVars[i][1]; return qtrue; } } - *out = (char*)defaultString; + *out = (char *)defaultString; return qfalse; } -qboolean CG_SpawnFloat( const char *key, const char *defaultString, float *out ) { +qboolean CG_SpawnFloat(const char *key, const char *defaultString, float *out) { char *s; qboolean present; - present = CG_SpawnString( key, defaultString, &s ); - *out = atof( s ); + present = CG_SpawnString(key, defaultString, &s); + *out = atof(s); return present; } -qboolean CG_SpawnInt( const char *key, const char *defaultString, int *out ) { +qboolean CG_SpawnInt(const char *key, const char *defaultString, int *out) { char *s; qboolean present; - present = CG_SpawnString( key, defaultString, &s ); - *out = atoi( s ); + present = CG_SpawnString(key, defaultString, &s); + *out = atoi(s); return present; } -qboolean CG_SpawnBoolean( const char *key, const char *defaultString, qboolean *out ) { +qboolean CG_SpawnBoolean(const char *key, const char *defaultString, qboolean *out) { char *s; qboolean present; - present = CG_SpawnString( key, defaultString, &s ); - if( !Q_stricmp( s, "qfalse" ) || !Q_stricmp( s, "false" ) || !Q_stricmp( s, "no" ) || !Q_stricmp( s, "0" ) ) { + present = CG_SpawnString(key, defaultString, &s); + if (!Q_stricmp(s, "qfalse") || !Q_stricmp(s, "false") || !Q_stricmp(s, "no") || !Q_stricmp(s, "0")) { *out = qfalse; - } - else if( !Q_stricmp( s, "qtrue" ) || !Q_stricmp( s, "true" ) || !Q_stricmp( s, "yes" ) || !Q_stricmp( s, "1" ) ) { + } else if (!Q_stricmp(s, "qtrue") || !Q_stricmp(s, "true") || !Q_stricmp(s, "yes") || !Q_stricmp(s, "1")) { *out = qtrue; - } - else { + } else { *out = qfalse; } return present; } -qboolean CG_SpawnVector( const char *key, const char *defaultString, float *out ) { +qboolean CG_SpawnVector(const char *key, const char *defaultString, float *out) { char *s; qboolean present; - present = CG_SpawnString( key, defaultString, &s ); - if ( sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] ) != 3 ) { - trap->Print( "CG_SpawnVector: Failed sscanf on %s (default: %s)\n", key, defaultString ); - VectorClear( out ); + present = CG_SpawnString(key, defaultString, &s); + if (sscanf(s, "%f %f %f", &out[0], &out[1], &out[2]) != 3) { + trap->Print("CG_SpawnVector: Failed sscanf on %s (default: %s)\n", key, defaultString); + VectorClear(out); return qfalse; } return present; @@ -154,21 +152,21 @@ This is just a convenience function for printing vectors ============= */ -char *vtos( const vec3_t v ) { +char *vtos(const vec3_t v) { static int index; static char str[8][32]; char *s; // use an array so that multiple vtos won't collide - s = str[index]; - index = ( index + 1 ) & 7; + s = str[index]; + index = (index + 1) & 7; - Com_sprintf( s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2] ); + Com_sprintf(s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2]); return s; } -void SP_misc_model_static( void ) { - char* model; +void SP_misc_model_static(void) { + char *model; float angle; vec3_t angles; float scale; @@ -179,106 +177,105 @@ void SP_misc_model_static( void ) { int modelIndex; cg_staticmodel_t *staticmodel; - if( cgs.numMiscStaticModels >= MAX_STATIC_MODELS ) { - trap->Error( ERR_DROP, "MAX_STATIC_MODELS(%i) hit", MAX_STATIC_MODELS ); + if (cgs.numMiscStaticModels >= MAX_STATIC_MODELS) { + trap->Error(ERR_DROP, "MAX_STATIC_MODELS(%i) hit", MAX_STATIC_MODELS); } - CG_SpawnString( "model", "", &model ); + CG_SpawnString("model", "", &model); - if( !model || !model[0] ) { - trap->Error( ERR_DROP, "misc_model_static with no model." ); + if (!model || !model[0]) { + trap->Error(ERR_DROP, "misc_model_static with no model."); } - CG_SpawnVector( "origin", "0 0 0", org ); - CG_SpawnFloat( "zoffset", "0", &zoffset ); + CG_SpawnVector("origin", "0 0 0", org); + CG_SpawnFloat("zoffset", "0", &zoffset); - if( !CG_SpawnVector( "angles", "0 0 0", angles ) ) { - if( CG_SpawnFloat( "angle", "0", &angle ) ) { + if (!CG_SpawnVector("angles", "0 0 0", angles)) { + if (CG_SpawnFloat("angle", "0", &angle)) { angles[YAW] = angle; } } - if( !CG_SpawnVector( "modelscale_vec", "1 1 1", vScale ) ) { - if( CG_SpawnFloat( "modelscale", "1", &scale ) ) { - VectorSet( vScale, scale, scale, scale ); + if (!CG_SpawnVector("modelscale_vec", "1 1 1", vScale)) { + if (CG_SpawnFloat("modelscale", "1", &scale)) { + VectorSet(vScale, scale, scale, scale); } } - modelIndex = trap->R_RegisterModel( model ); - if( modelIndex == 0 ) { - trap->Error( ERR_DROP, "misc_model_static failed to load model '%s'", model ); + modelIndex = trap->R_RegisterModel(model); + if (modelIndex == 0) { + trap->Error(ERR_DROP, "misc_model_static failed to load model '%s'", model); return; } - staticmodel = &cgs.miscStaticModels[cgs.numMiscStaticModels++]; - staticmodel->model = modelIndex; - AnglesToAxis( angles, staticmodel->axes ); - for( i = 0; i < 3; i++ ) { - VectorScale( staticmodel->axes[i], vScale[i], staticmodel->axes[i] ); + staticmodel = &cgs.miscStaticModels[cgs.numMiscStaticModels++]; + staticmodel->model = modelIndex; + AnglesToAxis(angles, staticmodel->axes); + for (i = 0; i < 3; i++) { + VectorScale(staticmodel->axes[i], vScale[i], staticmodel->axes[i]); } - VectorCopy( org, staticmodel->org ); + VectorCopy(org, staticmodel->org); staticmodel->zoffset = zoffset; - if( staticmodel->model ) { + if (staticmodel->model) { vec3_t mins, maxs; - trap->R_ModelBounds( staticmodel->model, mins, maxs ); + trap->R_ModelBounds(staticmodel->model, mins, maxs); - VectorScaleVector( mins, vScale, mins ); - VectorScaleVector( maxs, vScale, maxs ); + VectorScaleVector(mins, vScale, mins); + VectorScaleVector(maxs, vScale, maxs); - staticmodel->radius = RadiusFromBounds( mins, maxs ); - } - else { + staticmodel->radius = RadiusFromBounds(mins, maxs); + } else { staticmodel->radius = 0; } } qboolean cg_noFogOutsidePortal = qfalse; -void SP_misc_skyportal( void ) { +void SP_misc_skyportal(void) { qboolean onlyfoghere; - CG_SpawnBoolean( "onlyfoghere", "0", &onlyfoghere ); + CG_SpawnBoolean("onlyfoghere", "0", &onlyfoghere); - if( onlyfoghere ) + if (onlyfoghere) cg_noFogOutsidePortal = qtrue; } qboolean cg_skyOri = qfalse; vec3_t cg_skyOriPos; float cg_skyOriScale = 0.0f; -void SP_misc_skyportal_orient( void ) { - if( cg_skyOri ) - trap->Print( S_COLOR_YELLOW "WARNING: multiple misc_skyportal_orients found.\n" ); +void SP_misc_skyportal_orient(void) { + if (cg_skyOri) + trap->Print(S_COLOR_YELLOW "WARNING: multiple misc_skyportal_orients found.\n"); cg_skyOri = qtrue; - CG_SpawnVector( "origin", "0 0 0", cg_skyOriPos ); - CG_SpawnFloat( "modelscale", "0", &cg_skyOriScale ); + CG_SpawnVector("origin", "0 0 0", cg_skyOriPos); + CG_SpawnFloat("modelscale", "0", &cg_skyOriScale); } -void SP_misc_weather_zone( void ) { +void SP_misc_weather_zone(void) { char *model; vec3_t mins, maxs; - CG_SpawnString( "model", "", &model ); + CG_SpawnString("model", "", &model); - if( !model || !model[0] ) { - trap->Error( ERR_DROP, "misc_weather_zone with invalid brush model data." ); + if (!model || !model[0]) { + trap->Error(ERR_DROP, "misc_weather_zone with invalid brush model data."); return; } - trap->R_ModelBounds( trap->R_RegisterModel( model ), mins, maxs ); + trap->R_ModelBounds(trap->R_RegisterModel(model), mins, maxs); - trap->WE_AddWeatherZone( mins, maxs ); + trap->WE_AddWeatherZone(mins, maxs); } typedef struct spawn_s { - const char *name; - void (*spawn)( void ); + const char *name; + void (*spawn)(void); } spawn_t; -spawn_t spawns [] = { - { "misc_model_static", SP_misc_model_static }, - { "misc_skyportal", SP_misc_skyportal }, - { "misc_skyportal_orient", SP_misc_skyportal_orient }, - { "misc_weather_zone", SP_misc_weather_zone }, +spawn_t spawns[] = { + {"misc_model_static", SP_misc_model_static}, + {"misc_skyportal", SP_misc_skyportal}, + {"misc_skyportal_orient", SP_misc_skyportal_orient}, + {"misc_weather_zone", SP_misc_weather_zone}, }; /* @@ -289,53 +286,50 @@ Spawn an entity and fill in all of the level fields from cg.spawnVars[], then call the class specfic spawn function =================== */ -static int spawncmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((spawn_t*)b)->name ); -} +static int spawncmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((spawn_t *)b)->name); } -void CG_ParseEntityFromSpawnVars( void ) { +void CG_ParseEntityFromSpawnVars(void) { spawn_t *s; int i; char *classname; char *p, *value, *gametypeName; - static char *gametypeNames[GT_MAX_GAME_TYPE] = { "ffa", "holocron", "jedimaster", "duel", "powerduel", "single", "team", "siege", "ctf", "cty" }; + static char *gametypeNames[GT_MAX_GAME_TYPE] = {"ffa", "holocron", "jedimaster", "duel", "powerduel", "single", "team", "siege", "ctf", "cty"}; // check for "notsingle" flag - if( cgs.gametype == GT_SINGLE_PLAYER ) { - CG_SpawnInt( "notsingle", "0", &i ); - if( i ) { + if (cgs.gametype == GT_SINGLE_PLAYER) { + CG_SpawnInt("notsingle", "0", &i); + if (i) { return; } } // check for "notteam" flag (GT_FFA, GT_DUEL, GT_SINGLE_PLAYER) - if( cgs.gametype >= GT_TEAM ) { - CG_SpawnInt( "notteam", "0", &i ); - if( i ) { + if (cgs.gametype >= GT_TEAM) { + CG_SpawnInt("notteam", "0", &i); + if (i) { return; } - } - else { - CG_SpawnInt( "notfree", "0", &i ); - if( i ) { + } else { + CG_SpawnInt("notfree", "0", &i); + if (i) { return; } } - if( CG_SpawnString( "gametype", NULL, &value ) ) { - if( cgs.gametype >= GT_FFA && cgs.gametype < GT_MAX_GAME_TYPE ) { + if (CG_SpawnString("gametype", NULL, &value)) { + if (cgs.gametype >= GT_FFA && cgs.gametype < GT_MAX_GAME_TYPE) { gametypeName = gametypeNames[cgs.gametype]; - p = strstr( value, gametypeName ); - if( !p ) { + p = strstr(value, gametypeName); + if (!p) { return; } } } - if( CG_SpawnString( "classname", "", &classname ) ) { - s = (spawn_t *)Q_LinearSearch( classname, spawns, ARRAY_LEN( spawns ), sizeof( spawn_t ), spawncmp ); - if ( s ) + if (CG_SpawnString("classname", "", &classname)) { + s = (spawn_t *)Q_LinearSearch(classname, spawns, ARRAY_LEN(spawns), sizeof(spawn_t), spawncmp); + if (s) s->spawn(); } } @@ -344,17 +338,17 @@ void CG_ParseEntityFromSpawnVars( void ) { CG_AddSpawnVarToken ==================== */ -char *CG_AddSpawnVarToken( const char *string ) { +char *CG_AddSpawnVarToken(const char *string) { int l; char *dest; - l = strlen( string ); - if( cg.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) { - trap->Error( ERR_DROP, "CG_AddSpawnVarToken: MAX_SPAWN_VARS_CHARS" ); + l = strlen(string); + if (cg.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS) { + trap->Error(ERR_DROP, "CG_AddSpawnVarToken: MAX_SPAWN_VARS_CHARS"); } dest = cg.spawnVarChars + cg.numSpawnVarChars; - memcpy( dest, string, l + 1 ); + memcpy(dest, string, l + 1); cg.numSpawnVarChars += l + 1; @@ -370,66 +364,66 @@ level's entity strings into cg.spawnVars[] This does not actually spawn an entity. ==================== */ -qboolean CG_ParseSpawnVars( void ) { +qboolean CG_ParseSpawnVars(void) { char keyname[MAX_TOKEN_CHARS]; char com_token[MAX_TOKEN_CHARS]; - cg.numSpawnVars = 0; - cg.numSpawnVarChars = 0; + cg.numSpawnVars = 0; + cg.numSpawnVarChars = 0; // parse the opening brace - if( !trap->R_GetEntityToken( com_token, sizeof( com_token ) ) ) { + if (!trap->R_GetEntityToken(com_token, sizeof(com_token))) { // end of spawn string return qfalse; } - if( com_token[0] != '{' ) { - trap->Error( ERR_DROP, "CG_ParseSpawnVars: found %s when expecting {", com_token ); + if (com_token[0] != '{') { + trap->Error(ERR_DROP, "CG_ParseSpawnVars: found %s when expecting {", com_token); } // go through all the key / value pairs - while( 1 ) { + while (1) { // parse key - if( !trap->R_GetEntityToken( keyname, sizeof( keyname ) ) ) { - trap->Error( ERR_DROP, "CG_ParseSpawnVars: EOF without closing brace" ); + if (!trap->R_GetEntityToken(keyname, sizeof(keyname))) { + trap->Error(ERR_DROP, "CG_ParseSpawnVars: EOF without closing brace"); } - if( keyname[0] == '}' ) { + if (keyname[0] == '}') { break; } // parse value - if( !trap->R_GetEntityToken( com_token, sizeof( com_token ) ) ) { - trap->Error( ERR_DROP, "CG_ParseSpawnVars: EOF without closing brace" ); + if (!trap->R_GetEntityToken(com_token, sizeof(com_token))) { + trap->Error(ERR_DROP, "CG_ParseSpawnVars: EOF without closing brace"); } - if( com_token[0] == '}' ) { - trap->Error( ERR_DROP, "CG_ParseSpawnVars: closing brace without data" ); + if (com_token[0] == '}') { + trap->Error(ERR_DROP, "CG_ParseSpawnVars: closing brace without data"); } - if( cg.numSpawnVars == MAX_SPAWN_VARS ) { - trap->Error( ERR_DROP, "CG_ParseSpawnVars: MAX_SPAWN_VARS" ); + if (cg.numSpawnVars == MAX_SPAWN_VARS) { + trap->Error(ERR_DROP, "CG_ParseSpawnVars: MAX_SPAWN_VARS"); } - cg.spawnVars[cg.numSpawnVars][0] = CG_AddSpawnVarToken( keyname ); - cg.spawnVars[cg.numSpawnVars][1] = CG_AddSpawnVarToken( com_token ); + cg.spawnVars[cg.numSpawnVars][0] = CG_AddSpawnVarToken(keyname); + cg.spawnVars[cg.numSpawnVars][1] = CG_AddSpawnVarToken(com_token); cg.numSpawnVars++; } return qtrue; } -extern float cg_linearFogOverride; // cg_view.c -extern float cg_radarRange; // cg_draw.c -void SP_worldspawn( void ) { +extern float cg_linearFogOverride; // cg_view.c +extern float cg_radarRange; // cg_draw.c +void SP_worldspawn(void) { char *s; - CG_SpawnString( "classname", "", &s ); - if( Q_stricmp( s, "worldspawn" ) ) { - trap->Error( ERR_DROP, "SP_worldspawn: The first entity isn't 'worldspawn'" ); + CG_SpawnString("classname", "", &s); + if (Q_stricmp(s, "worldspawn")) { + trap->Error(ERR_DROP, "SP_worldspawn: The first entity isn't 'worldspawn'"); } - CG_SpawnFloat( "fogstart", "0", &cg_linearFogOverride ); - CG_SpawnFloat( "radarrange", "2500", &cg_radarRange ); + CG_SpawnFloat("fogstart", "0", &cg_linearFogOverride); + CG_SpawnFloat("radarrange", "2500", &cg_radarRange); } /* ============== @@ -438,25 +432,25 @@ CG_ParseEntitiesFromString Parses textual entity definitions out of an entstring ============== */ -void CG_ParseEntitiesFromString( void ) { +void CG_ParseEntitiesFromString(void) { // make sure it is reset - trap->R_GetEntityToken( NULL, -1 ); + trap->R_GetEntityToken(NULL, -1); // allow calls to CG_Spawn*() - cg.spawning = qtrue; + cg.spawning = qtrue; cg.numSpawnVars = 0; // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) - if( !CG_ParseSpawnVars() ) { - trap->Error( ERR_DROP, "ParseEntities: no entities" ); + if (!CG_ParseSpawnVars()) { + trap->Error(ERR_DROP, "ParseEntities: no entities"); } SP_worldspawn(); // parse ents - while( CG_ParseSpawnVars() ) { + while (CG_ParseSpawnVars()) { CG_ParseEntityFromSpawnVars(); } diff --git a/codemp/cgame/cg_syscalls.c b/codemp/cgame/cg_syscalls.c index 2c905d67fd..d7aeefcf22 100644 --- a/codemp/cgame/cg_syscalls.c +++ b/codemp/cgame/cg_syscalls.c @@ -25,923 +25,669 @@ along with this program; if not, see . // cg_syscalls.c -- this file is only included when building a dll #include "cg_local.h" -static intptr_t (QDECL *Q_syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; +static intptr_t(QDECL *Q_syscall)(intptr_t arg, ...) = (intptr_t(QDECL *)(intptr_t, ...)) - 1; -static void TranslateSyscalls( void ); +static void TranslateSyscalls(void); -Q_EXPORT void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) { +Q_EXPORT void dllEntry(intptr_t(QDECL *syscallptr)(intptr_t arg, ...)) { Q_syscall = syscallptr; TranslateSyscalls(); } -int PASSFLOAT( float x ) { +int PASSFLOAT(float x) { byteAlias_t fi; fi.f = x; return fi.i; } -void trap_Print( const char *fmt ) { - Q_syscall( CG_PRINT, fmt ); -} -NORETURN void trap_Error( const char *fmt ) { - Q_syscall( CG_ERROR, fmt ); +void trap_Print(const char *fmt) { Q_syscall(CG_PRINT, fmt); } +NORETURN void trap_Error(const char *fmt) { + Q_syscall(CG_ERROR, fmt); exit(1); } -int trap_Milliseconds( void ) { - return Q_syscall( CG_MILLISECONDS ); -} -void trap_PrecisionTimer_Start( void **theNewTimer ) { - Q_syscall( CG_PRECISIONTIMER_START, theNewTimer ); -} -int trap_PrecisionTimer_End( void *theTimer ) { - return Q_syscall(CG_PRECISIONTIMER_END, theTimer); -} -void trap_Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, uint32_t flags ) { - Q_syscall( CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags ); -} -void trap_Cvar_Update( vmCvar_t *vmCvar ) { - Q_syscall( CG_CVAR_UPDATE, vmCvar ); -} -void trap_Cvar_Set( const char *var_name, const char *value ) { - Q_syscall( CG_CVAR_SET, var_name, value ); -} -void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { - Q_syscall( CG_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize ); -} -int trap_Cvar_GetHiddenVarValue( const char *name ) { - return Q_syscall(CG_CVAR_GETHIDDENVALUE, name); -} -int trap_Argc( void ) { - return Q_syscall( CG_ARGC ); -} -void trap_Argv( int n, char *buffer, int bufferLength ) { - Q_syscall( CG_ARGV, n, buffer, bufferLength ); -} -void trap_Args( char *buffer, int bufferLength ) { - Q_syscall( CG_ARGS, buffer, bufferLength ); -} -int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - return Q_syscall( CG_FS_FOPENFILE, qpath, f, mode ); -} -void trap_FS_Read( void *buffer, int len, fileHandle_t f ) { - Q_syscall( CG_FS_READ, buffer, len, f ); -} -void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) { - Q_syscall( CG_FS_WRITE, buffer, len, f ); -} -void trap_FS_FCloseFile( fileHandle_t f ) { - Q_syscall( CG_FS_FCLOSEFILE, f ); -} -int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { - return Q_syscall( CG_FS_GETFILELIST, path, extension, listbuf, bufsize ); -} -void trap_SendConsoleCommand( const char *text ) { - Q_syscall( CG_SENDCONSOLECOMMAND, text ); -} -void trap_AddCommand( const char *cmdName ) { - Q_syscall( CG_ADDCOMMAND, cmdName ); -} -void trap_RemoveCommand( const char *cmdName ) { - Q_syscall( CG_REMOVECOMMAND, cmdName ); -} -void trap_SendClientCommand( const char *s ) { - Q_syscall( CG_SENDCLIENTCOMMAND, s ); -} -void trap_UpdateScreen( void ) { - Q_syscall( CG_UPDATESCREEN ); -} -void trap_CM_LoadMap( const char *mapname, qboolean SubBSP ) { - Q_syscall( CG_CM_LOADMAP, mapname, SubBSP ); -} -int trap_CM_NumInlineModels( void ) { - return Q_syscall( CG_CM_NUMINLINEMODELS ); -} -clipHandle_t trap_CM_InlineModel( int index ) { - return Q_syscall( CG_CM_INLINEMODEL, index ); -} -clipHandle_t trap_CM_TempBoxModel( const vec3_t mins, const vec3_t maxs ) { - return Q_syscall( CG_CM_TEMPBOXMODEL, mins, maxs ); -} -clipHandle_t trap_CM_TempCapsuleModel( const vec3_t mins, const vec3_t maxs ) { - return Q_syscall( CG_CM_TEMPCAPSULEMODEL, mins, maxs ); -} -int trap_CM_PointContents( const vec3_t p, clipHandle_t model ) { - return Q_syscall( CG_CM_POINTCONTENTS, p, model ); -} -int trap_CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles ) { - return Q_syscall( CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles ); -} -void trap_CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask ) { - Q_syscall( CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask ); -} -void trap_CM_CapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask ) { - Q_syscall( CG_CM_CAPSULETRACE, results, start, end, mins, maxs, model, brushmask ); -} -void trap_CM_TransformedBoxTrace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, const vec3_t origin, const vec3_t angles ) { - Q_syscall( CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles ); -} -void trap_CM_TransformedCapsuleTrace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, const vec3_t origin, const vec3_t angles ) { - Q_syscall( CG_CM_TRANSFORMEDCAPSULETRACE, results, start, end, mins, maxs, model, brushmask, origin, angles ); -} -int trap_CM_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) { - return Q_syscall( CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer ); -} -int trap_S_GetVoiceVolume( int entityNum ) { - return Q_syscall( CG_S_GETVOICEVOLUME, entityNum ); -} -void trap_S_MuteSound( int entityNum, int entchannel ) { - Q_syscall( CG_S_MUTESOUND, entityNum, entchannel ); -} -void trap_S_StartSound( const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ) { - Q_syscall( CG_S_STARTSOUND, origin, entityNum, entchannel, sfx ); -} -void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) { - Q_syscall( CG_S_STARTLOCALSOUND, sfx, channelNum ); -} -void trap_S_ClearLoopingSounds(void) { - Q_syscall( CG_S_CLEARLOOPINGSOUNDS ); -} -void trap_S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) { - Q_syscall( CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx ); -} -void trap_S_UpdateEntityPosition( int entityNum, const vec3_t origin ) { - Q_syscall( CG_S_UPDATEENTITYPOSITION, entityNum, origin ); -} -void trap_S_AddRealLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx ) { - Q_syscall( CG_S_ADDREALLOOPINGSOUND, entityNum, origin, velocity, sfx ); -} -void trap_S_StopLoopingSound( int entityNum ) { - Q_syscall( CG_S_STOPLOOPINGSOUND, entityNum ); -} -void trap_S_Respatialize( int entityNum, const vec3_t origin, matrix3_t axis, int inwater ) { - Q_syscall( CG_S_RESPATIALIZE, entityNum, origin, axis, inwater ); -} -void trap_S_ShutUp(qboolean shutUpFactor) { - Q_syscall(CG_S_SHUTUP, shutUpFactor); -} -sfxHandle_t trap_S_RegisterSound( const char *sample ) { - return Q_syscall( CG_S_REGISTERSOUND, sample ); -} -void trap_S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bReturnWithoutStarting ) { - Q_syscall( CG_S_STARTBACKGROUNDTRACK, intro, loop, bReturnWithoutStarting ); -} -void trap_S_UpdateAmbientSet( const char *name, vec3_t origin ) { - Q_syscall(CG_S_UPDATEAMBIENTSET, name, origin); -} -void trap_AS_ParseSets( void ) { - Q_syscall(CG_AS_PARSESETS); -} -void trap_AS_AddPrecacheEntry( const char *name ) { - Q_syscall(CG_AS_ADDPRECACHEENTRY, name); -} -int trap_S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ) { +int trap_Milliseconds(void) { return Q_syscall(CG_MILLISECONDS); } +void trap_PrecisionTimer_Start(void **theNewTimer) { Q_syscall(CG_PRECISIONTIMER_START, theNewTimer); } +int trap_PrecisionTimer_End(void *theTimer) { return Q_syscall(CG_PRECISIONTIMER_END, theTimer); } +void trap_Cvar_Register(vmCvar_t *vmCvar, const char *varName, const char *defaultValue, uint32_t flags) { + Q_syscall(CG_CVAR_REGISTER, vmCvar, varName, defaultValue, flags); +} +void trap_Cvar_Update(vmCvar_t *vmCvar) { Q_syscall(CG_CVAR_UPDATE, vmCvar); } +void trap_Cvar_Set(const char *var_name, const char *value) { Q_syscall(CG_CVAR_SET, var_name, value); } +void trap_Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize) { Q_syscall(CG_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize); } +int trap_Cvar_GetHiddenVarValue(const char *name) { return Q_syscall(CG_CVAR_GETHIDDENVALUE, name); } +int trap_Argc(void) { return Q_syscall(CG_ARGC); } +void trap_Argv(int n, char *buffer, int bufferLength) { Q_syscall(CG_ARGV, n, buffer, bufferLength); } +void trap_Args(char *buffer, int bufferLength) { Q_syscall(CG_ARGS, buffer, bufferLength); } +int trap_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode) { return Q_syscall(CG_FS_FOPENFILE, qpath, f, mode); } +void trap_FS_Read(void *buffer, int len, fileHandle_t f) { Q_syscall(CG_FS_READ, buffer, len, f); } +void trap_FS_Write(const void *buffer, int len, fileHandle_t f) { Q_syscall(CG_FS_WRITE, buffer, len, f); } +void trap_FS_FCloseFile(fileHandle_t f) { Q_syscall(CG_FS_FCLOSEFILE, f); } +int trap_FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize) { + return Q_syscall(CG_FS_GETFILELIST, path, extension, listbuf, bufsize); +} +void trap_SendConsoleCommand(const char *text) { Q_syscall(CG_SENDCONSOLECOMMAND, text); } +void trap_AddCommand(const char *cmdName) { Q_syscall(CG_ADDCOMMAND, cmdName); } +void trap_RemoveCommand(const char *cmdName) { Q_syscall(CG_REMOVECOMMAND, cmdName); } +void trap_SendClientCommand(const char *s) { Q_syscall(CG_SENDCLIENTCOMMAND, s); } +void trap_UpdateScreen(void) { Q_syscall(CG_UPDATESCREEN); } +void trap_CM_LoadMap(const char *mapname, qboolean SubBSP) { Q_syscall(CG_CM_LOADMAP, mapname, SubBSP); } +int trap_CM_NumInlineModels(void) { return Q_syscall(CG_CM_NUMINLINEMODELS); } +clipHandle_t trap_CM_InlineModel(int index) { return Q_syscall(CG_CM_INLINEMODEL, index); } +clipHandle_t trap_CM_TempBoxModel(const vec3_t mins, const vec3_t maxs) { return Q_syscall(CG_CM_TEMPBOXMODEL, mins, maxs); } +clipHandle_t trap_CM_TempCapsuleModel(const vec3_t mins, const vec3_t maxs) { return Q_syscall(CG_CM_TEMPCAPSULEMODEL, mins, maxs); } +int trap_CM_PointContents(const vec3_t p, clipHandle_t model) { return Q_syscall(CG_CM_POINTCONTENTS, p, model); } +int trap_CM_TransformedPointContents(const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { + return Q_syscall(CG_CM_TRANSFORMEDPOINTCONTENTS, p, model, origin, angles); +} +void trap_CM_BoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask) { + Q_syscall(CG_CM_BOXTRACE, results, start, end, mins, maxs, model, brushmask); +} +void trap_CM_CapsuleTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask) { + Q_syscall(CG_CM_CAPSULETRACE, results, start, end, mins, maxs, model, brushmask); +} +void trap_CM_TransformedBoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, + int brushmask, const vec3_t origin, const vec3_t angles) { + Q_syscall(CG_CM_TRANSFORMEDBOXTRACE, results, start, end, mins, maxs, model, brushmask, origin, angles); +} +void trap_CM_TransformedCapsuleTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, + int brushmask, const vec3_t origin, const vec3_t angles) { + Q_syscall(CG_CM_TRANSFORMEDCAPSULETRACE, results, start, end, mins, maxs, model, brushmask, origin, angles); +} +int trap_CM_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + return Q_syscall(CG_CM_MARKFRAGMENTS, numPoints, points, projection, maxPoints, pointBuffer, maxFragments, fragmentBuffer); +} +int trap_S_GetVoiceVolume(int entityNum) { return Q_syscall(CG_S_GETVOICEVOLUME, entityNum); } +void trap_S_MuteSound(int entityNum, int entchannel) { Q_syscall(CG_S_MUTESOUND, entityNum, entchannel); } +void trap_S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx) { Q_syscall(CG_S_STARTSOUND, origin, entityNum, entchannel, sfx); } +void trap_S_StartLocalSound(sfxHandle_t sfx, int channelNum) { Q_syscall(CG_S_STARTLOCALSOUND, sfx, channelNum); } +void trap_S_ClearLoopingSounds(void) { Q_syscall(CG_S_CLEARLOOPINGSOUNDS); } +void trap_S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) { + Q_syscall(CG_S_ADDLOOPINGSOUND, entityNum, origin, velocity, sfx); +} +void trap_S_UpdateEntityPosition(int entityNum, const vec3_t origin) { Q_syscall(CG_S_UPDATEENTITYPOSITION, entityNum, origin); } +void trap_S_AddRealLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfx) { + Q_syscall(CG_S_ADDREALLOOPINGSOUND, entityNum, origin, velocity, sfx); +} +void trap_S_StopLoopingSound(int entityNum) { Q_syscall(CG_S_STOPLOOPINGSOUND, entityNum); } +void trap_S_Respatialize(int entityNum, const vec3_t origin, matrix3_t axis, int inwater) { Q_syscall(CG_S_RESPATIALIZE, entityNum, origin, axis, inwater); } +void trap_S_ShutUp(qboolean shutUpFactor) { Q_syscall(CG_S_SHUTUP, shutUpFactor); } +sfxHandle_t trap_S_RegisterSound(const char *sample) { return Q_syscall(CG_S_REGISTERSOUND, sample); } +void trap_S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bReturnWithoutStarting) { + Q_syscall(CG_S_STARTBACKGROUNDTRACK, intro, loop, bReturnWithoutStarting); +} +void trap_S_UpdateAmbientSet(const char *name, vec3_t origin) { Q_syscall(CG_S_UPDATEAMBIENTSET, name, origin); } +void trap_AS_ParseSets(void) { Q_syscall(CG_AS_PARSESETS); } +void trap_AS_AddPrecacheEntry(const char *name) { Q_syscall(CG_AS_ADDPRECACHEENTRY, name); } +int trap_S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time) { return Q_syscall(CG_S_ADDLOCALSET, name, listener_origin, origin, entID, time); } -sfxHandle_t trap_AS_GetBModelSound( const char *name, int stage ) { - return Q_syscall(CG_AS_GETBMODELSOUND, name, stage); -} -void trap_R_LoadWorldMap( const char *mapname ) { - Q_syscall( CG_R_LOADWORLDMAP, mapname ); -} -qhandle_t trap_R_RegisterModel( const char *name ) { - return Q_syscall( CG_R_REGISTERMODEL, name ); -} -qhandle_t trap_R_RegisterSkin( const char *name ) { - return Q_syscall( CG_R_REGISTERSKIN, name ); -} -qhandle_t trap_R_RegisterShader( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADER, name ); -} -qhandle_t trap_R_RegisterShaderNoMip( const char *name ) { - return Q_syscall( CG_R_REGISTERSHADERNOMIP, name ); -} -qhandle_t trap_R_RegisterFont( const char *fontName ) { - return Q_syscall( CG_R_REGISTERFONT, fontName); -} +sfxHandle_t trap_AS_GetBModelSound(const char *name, int stage) { return Q_syscall(CG_AS_GETBMODELSOUND, name, stage); } +void trap_R_LoadWorldMap(const char *mapname) { Q_syscall(CG_R_LOADWORLDMAP, mapname); } +qhandle_t trap_R_RegisterModel(const char *name) { return Q_syscall(CG_R_REGISTERMODEL, name); } +qhandle_t trap_R_RegisterSkin(const char *name) { return Q_syscall(CG_R_REGISTERSKIN, name); } +qhandle_t trap_R_RegisterShader(const char *name) { return Q_syscall(CG_R_REGISTERSHADER, name); } +qhandle_t trap_R_RegisterShaderNoMip(const char *name) { return Q_syscall(CG_R_REGISTERSHADERNOMIP, name); } +qhandle_t trap_R_RegisterFont(const char *fontName) { return Q_syscall(CG_R_REGISTERFONT, fontName); } int trap_R_Font_StrLenPixels(const char *text, const int iFontIndex, const float scale) { - //HACK! RE_Font_StrLenPixels works better with 1.0f scale - float width = (float)Q_syscall( CG_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); + // HACK! RE_Font_StrLenPixels works better with 1.0f scale + float width = (float)Q_syscall(CG_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); return width * scale; } float trap_R_Font_StrLenPixelsFloat(const char *text, const int iFontIndex, const float scale) { - //HACK! RE_Font_StrLenPixels works better with 1.0f scale - float width = (float)Q_syscall( CG_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); + // HACK! RE_Font_StrLenPixels works better with 1.0f scale + float width = (float)Q_syscall(CG_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); return width * scale; } -int trap_R_Font_StrLenChars(const char *text) { - return Q_syscall( CG_R_FONT_STRLENCHARS, text); -} +int trap_R_Font_StrLenChars(const char *text) { return Q_syscall(CG_R_FONT_STRLENCHARS, text); } int trap_R_Font_HeightPixels(const int iFontIndex, const float scale) { - float height = (float)Q_syscall( CG_R_FONT_STRHEIGHTPIXELS, iFontIndex, PASSFLOAT(1.0f) ); + float height = (float)Q_syscall(CG_R_FONT_STRHEIGHTPIXELS, iFontIndex, PASSFLOAT(1.0f)); return height * scale; } void trap_R_Font_DrawString(int ox, int oy, const char *text, const float *rgba, const int setIndex, int iCharLimit, const float scale) { - Q_syscall( CG_R_FONT_DRAWSTRING, ox, oy, text, rgba, setIndex, iCharLimit, PASSFLOAT(scale)); + Q_syscall(CG_R_FONT_DRAWSTRING, ox, oy, text, rgba, setIndex, iCharLimit, PASSFLOAT(scale)); } -qboolean trap_Language_IsAsian(void) { - return Q_syscall( CG_LANGUAGE_ISASIAN ); +qboolean trap_Language_IsAsian(void) { return Q_syscall(CG_LANGUAGE_ISASIAN); } +qboolean trap_Language_UsesSpaces(void) { return Q_syscall(CG_LANGUAGE_USESSPACES); } +unsigned int trap_AnyLanguage_ReadCharFromString(const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL*/) { + return Q_syscall(CG_ANYLANGUAGE_READCHARFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation); } -qboolean trap_Language_UsesSpaces(void) { - return Q_syscall( CG_LANGUAGE_USESSPACES ); +void trap_R_ClearScene(void) { Q_syscall(CG_R_CLEARSCENE); } +void trap_R_ClearDecals(void) { Q_syscall(CG_R_CLEARDECALS); } +void trap_R_AddRefEntityToScene(const refEntity_t *re) { Q_syscall(CG_R_ADDREFENTITYTOSCENE, re); } +void trap_R_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts) { Q_syscall(CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts); } +void trap_R_AddPolysToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts, int num) { + Q_syscall(CG_R_ADDPOLYSTOSCENE, hShader, numVerts, verts, num); } -unsigned int trap_AnyLanguage_ReadCharFromString( const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation/* = NULL*/ ) { - return Q_syscall( CG_ANYLANGUAGE_READCHARFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation); +void trap_R_AddDecalToScene(qhandle_t shader, const vec3_t origin, const vec3_t dir, float orientation, float r, float g, float b, float a, qboolean alphaFade, + float radius, qboolean temporary) { + Q_syscall(CG_R_ADDDECALTOSCENE, shader, origin, dir, PASSFLOAT(orientation), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b), PASSFLOAT(a), alphaFade, + PASSFLOAT(radius), temporary); } -void trap_R_ClearScene( void ) { - Q_syscall( CG_R_CLEARSCENE ); +int trap_R_LightForPoint(vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { + return Q_syscall(CG_R_LIGHTFORPOINT, point, ambientLight, directedLight, lightDir); } -void trap_R_ClearDecals ( void ) { - Q_syscall ( CG_R_CLEARDECALS ); +void trap_R_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + Q_syscall(CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b)); } -void trap_R_AddRefEntityToScene( const refEntity_t *re ) { - Q_syscall( CG_R_ADDREFENTITYTOSCENE, re ); +void trap_R_AddAdditiveLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + Q_syscall(CG_R_ADDADDITIVELIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b)); } -void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) { - Q_syscall( CG_R_ADDPOLYTOSCENE, hShader, numVerts, verts ); +void trap_R_RenderScene(const refdef_t *fd) { Q_syscall(CG_R_RENDERSCENE, fd); } +void trap_R_SetColor(const float *rgba) { Q_syscall(CG_R_SETCOLOR, rgba); } +void trap_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + Q_syscall(CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader); } -void trap_R_AddPolysToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ) { - Q_syscall( CG_R_ADDPOLYSTOSCENE, hShader, numVerts, verts, num ); +void trap_R_ModelBounds(clipHandle_t model, vec3_t mins, vec3_t maxs) { Q_syscall(CG_R_MODELBOUNDS, model, mins, maxs); } +int trap_R_LerpTag(orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName) { + return Q_syscall(CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName); } -void trap_R_AddDecalToScene ( qhandle_t shader, const vec3_t origin, const vec3_t dir, float orientation, float r, float g, float b, float a, qboolean alphaFade, float radius, qboolean temporary ) { - Q_syscall( CG_R_ADDDECALTOSCENE, shader, origin, dir, PASSFLOAT(orientation), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b), PASSFLOAT(a), alphaFade, PASSFLOAT(radius), temporary ); +void trap_R_DrawRotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } -int trap_R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) { - return Q_syscall( CG_R_LIGHTFORPOINT, point, ambientLight, directedLight, lightDir ); -} -void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - Q_syscall( CG_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) ); -} -void trap_R_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - Q_syscall( CG_R_ADDADDITIVELIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) ); -} -void trap_R_RenderScene( const refdef_t *fd ) { - Q_syscall( CG_R_RENDERSCENE, fd ); -} -void trap_R_SetColor( const float *rgba ) { - Q_syscall( CG_R_SETCOLOR, rgba ); -} -void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ) { - Q_syscall( CG_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader ); -} -void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) { - Q_syscall( CG_R_MODELBOUNDS, model, mins, maxs ); -} -int trap_R_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName ) { - return Q_syscall( CG_R_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName ); -} -void trap_R_DrawRotatePic( float x, float y, float w, float h, float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - Q_syscall( CG_R_DRAWROTATEPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); -} -void trap_R_DrawRotatePic2( float x, float y, float w, float h, float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - Q_syscall( CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), PASSFLOAT(a), hShader ); -} -void trap_R_SetRangeFog(float range) { - Q_syscall(CG_R_SETRANGEFOG, PASSFLOAT(range)); +void trap_R_DrawRotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + Q_syscall(CG_R_DRAWROTATEPIC2, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), + PASSFLOAT(a), hShader); } +void trap_R_SetRangeFog(float range) { Q_syscall(CG_R_SETRANGEFOG, PASSFLOAT(range)); } void trap_R_SetRefractProp(float alpha, float stretch, qboolean prepost, qboolean negate) { Q_syscall(CG_R_SETREFRACTIONPROP, PASSFLOAT(alpha), PASSFLOAT(stretch), prepost, negate); } -void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) { - Q_syscall( CG_R_REMAP_SHADER, oldShader, newShader, timeOffset ); -} -void trap_R_GetLightStyle(int style, color4ub_t color) { - Q_syscall( CG_R_GET_LIGHT_STYLE, style, color ); -} -void trap_R_SetLightStyle(int style, int color) { - Q_syscall( CG_R_SET_LIGHT_STYLE, style, color ); -} -void trap_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal ) { - Q_syscall( CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal ); -} -void trap_R_GetDistanceCull(float *f) { - Q_syscall(CG_R_GETDISTANCECULL, f); -} -void trap_R_GetRealRes(int *w, int *h) { - Q_syscall( CG_R_GETREALRES, w, h ); -} -void trap_R_AutomapElevAdj(float newHeight) { - Q_syscall( CG_R_AUTOMAPELEVADJ, PASSFLOAT(newHeight) ); -} -qboolean trap_R_InitWireframeAutomap(void) { - return Q_syscall( CG_R_INITWIREFRAMEAUTO ); -} -void trap_FX_AddLine( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int flags) { - Q_syscall( CG_FX_ADDLINE, start, end, PASSFLOAT(size1), PASSFLOAT(size2), PASSFLOAT(sizeParm), PASSFLOAT(alpha1), PASSFLOAT(alpha2), PASSFLOAT(alphaParm), sRGB, eRGB, PASSFLOAT(rgbParm), killTime, shader, flags); -} -void trap_GetGlconfig( glconfig_t *glconfig ) { - Q_syscall( CG_GETGLCONFIG, glconfig ); -} -void trap_GetGameState( gameState_t *gamestate ) { - Q_syscall( CG_GETGAMESTATE, gamestate ); -} -void trap_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { - Q_syscall( CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime ); -} -qboolean trap_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { - return Q_syscall( CG_GETSNAPSHOT, snapshotNumber, snapshot ); -} -qboolean trap_GetDefaultState(int entityIndex, entityState_t *state ) { - return Q_syscall( CG_GETDEFAULTSTATE, entityIndex, state ); -} -qboolean trap_GetServerCommand( int serverCommandNumber ) { - return Q_syscall( CG_GETSERVERCOMMAND, serverCommandNumber ); -} -int trap_GetCurrentCmdNumber( void ) { - return Q_syscall( CG_GETCURRENTCMDNUMBER ); -} -qboolean trap_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { - return Q_syscall( CG_GETUSERCMD, cmdNumber, ucmd ); -} -void trap_SetUserCmdValue( int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, int invenSel, qboolean fighterControls ) { - Q_syscall( CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride), PASSFLOAT(mSensitivityOverride), fpSel, invenSel, fighterControls ); -} -void trap_SetClientForceAngle(int time, vec3_t angle) { - Q_syscall( CG_SETCLIENTFORCEANGLE, time, angle ); -} +void trap_R_RemapShader(const char *oldShader, const char *newShader, const char *timeOffset) { + Q_syscall(CG_R_REMAP_SHADER, oldShader, newShader, timeOffset); +} +void trap_R_GetLightStyle(int style, color4ub_t color) { Q_syscall(CG_R_GET_LIGHT_STYLE, style, color); } +void trap_R_SetLightStyle(int style, int color) { Q_syscall(CG_R_SET_LIGHT_STYLE, style, color); } +void trap_R_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { Q_syscall(CG_R_GET_BMODEL_VERTS, bmodelIndex, verts, normal); } +void trap_R_GetDistanceCull(float *f) { Q_syscall(CG_R_GETDISTANCECULL, f); } +void trap_R_GetRealRes(int *w, int *h) { Q_syscall(CG_R_GETREALRES, w, h); } +void trap_R_AutomapElevAdj(float newHeight) { Q_syscall(CG_R_AUTOMAPELEVADJ, PASSFLOAT(newHeight)); } +qboolean trap_R_InitWireframeAutomap(void) { return Q_syscall(CG_R_INITWIREFRAMEAUTO); } +void trap_FX_AddLine(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, + float rgbParm, int killTime, qhandle_t shader, int flags) { + Q_syscall(CG_FX_ADDLINE, start, end, PASSFLOAT(size1), PASSFLOAT(size2), PASSFLOAT(sizeParm), PASSFLOAT(alpha1), PASSFLOAT(alpha2), PASSFLOAT(alphaParm), + sRGB, eRGB, PASSFLOAT(rgbParm), killTime, shader, flags); +} +void trap_GetGlconfig(glconfig_t *glconfig) { Q_syscall(CG_GETGLCONFIG, glconfig); } +void trap_GetGameState(gameState_t *gamestate) { Q_syscall(CG_GETGAMESTATE, gamestate); } +void trap_GetCurrentSnapshotNumber(int *snapshotNumber, int *serverTime) { Q_syscall(CG_GETCURRENTSNAPSHOTNUMBER, snapshotNumber, serverTime); } +qboolean trap_GetSnapshot(int snapshotNumber, snapshot_t *snapshot) { return Q_syscall(CG_GETSNAPSHOT, snapshotNumber, snapshot); } +qboolean trap_GetDefaultState(int entityIndex, entityState_t *state) { return Q_syscall(CG_GETDEFAULTSTATE, entityIndex, state); } +qboolean trap_GetServerCommand(int serverCommandNumber) { return Q_syscall(CG_GETSERVERCOMMAND, serverCommandNumber); } +int trap_GetCurrentCmdNumber(void) { return Q_syscall(CG_GETCURRENTCMDNUMBER); } +qboolean trap_GetUserCmd(int cmdNumber, usercmd_t *ucmd) { return Q_syscall(CG_GETUSERCMD, cmdNumber, ucmd); } +void trap_SetUserCmdValue(int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, int invenSel, + qboolean fighterControls) { + Q_syscall(CG_SETUSERCMDVALUE, stateValue, PASSFLOAT(sensitivityScale), PASSFLOAT(mPitchOverride), PASSFLOAT(mYawOverride), PASSFLOAT(mSensitivityOverride), + fpSel, invenSel, fighterControls); +} +void trap_SetClientForceAngle(int time, vec3_t angle) { Q_syscall(CG_SETCLIENTFORCEANGLE, time, angle); } void trap_SetClientTurnExtent(float turnAdd, float turnSub, int turnTime) { - Q_syscall( CG_SETCLIENTTURNEXTENT, PASSFLOAT(turnAdd), PASSFLOAT(turnSub), turnTime ); -} -void trap_OpenUIMenu(int menuID) { - Q_syscall( CG_OPENUIMENU, menuID ); -} -void testPrintInt( char *string, int i ) { - Q_syscall( CG_TESTPRINTINT, string, i ); -} -void testPrintFloat( char *string, float f ) { - Q_syscall( CG_TESTPRINTFLOAT, string, PASSFLOAT(f) ); -} -int trap_MemoryRemaining( void ) { - return Q_syscall( CG_MEMORY_REMAINING ); -} -qboolean trap_Key_IsDown( int keynum ) { - return Q_syscall( CG_KEY_ISDOWN, keynum ); -} -int trap_Key_GetCatcher( void ) { - return Q_syscall( CG_KEY_GETCATCHER ); -} -void trap_Key_SetCatcher( int catcher ) { - Q_syscall( CG_KEY_SETCATCHER, catcher ); -} -int trap_Key_GetKey( const char *binding ) { - return Q_syscall( CG_KEY_GETKEY, binding ); -} -int trap_PC_AddGlobalDefine( char *define ) { - return Q_syscall( CG_PC_ADD_GLOBAL_DEFINE, define ); -} -int trap_PC_LoadSource( const char *filename ) { - return Q_syscall( CG_PC_LOAD_SOURCE, filename ); -} -int trap_PC_FreeSource( int handle ) { - return Q_syscall( CG_PC_FREE_SOURCE, handle ); -} -int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) { - return Q_syscall( CG_PC_READ_TOKEN, handle, pc_token ); -} -int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) { - return Q_syscall( CG_PC_SOURCE_FILE_AND_LINE, handle, filename, line ); -} -int trap_PC_LoadGlobalDefines ( const char* filename ) { - return Q_syscall ( CG_PC_LOAD_GLOBAL_DEFINES, filename ); -} -void trap_PC_RemoveAllGlobalDefines ( void ) { - Q_syscall ( CG_PC_REMOVE_ALL_GLOBAL_DEFINES ); -} -void trap_S_StopBackgroundTrack( void ) { - Q_syscall( CG_S_STOPBACKGROUNDTRACK ); -} -int trap_RealTime(qtime_t *qtime) { - return Q_syscall( CG_REAL_TIME, qtime ); -} -void trap_SnapVector( float *v ) { - Q_syscall( CG_SNAPVECTOR, v ); -} -int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) { - return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits); -} -e_status trap_CIN_StopCinematic(int handle) { - return Q_syscall(CG_CIN_STOPCINEMATIC, handle); -} -e_status trap_CIN_RunCinematic (int handle) { - return Q_syscall(CG_CIN_RUNCINEMATIC, handle); -} -void trap_CIN_DrawCinematic (int handle) { - Q_syscall(CG_CIN_DRAWCINEMATIC, handle); -} -void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) { - Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); -} -qboolean trap_GetEntityToken( char *buffer, int bufferSize ) { - return Q_syscall( CG_GET_ENTITY_TOKEN, buffer, bufferSize ); -} -qboolean trap_R_inPVS( const vec3_t p1, const vec3_t p2, byte *mask ) { - return Q_syscall( CG_R_INPVS, p1, p2, mask ); -} -int trap_FX_RegisterEffect(const char *file) { - return Q_syscall( CG_FX_REGISTER_EFFECT, file); -} -void trap_FX_PlayEffect( const char *file, vec3_t org, vec3_t fwd, int vol, int rad ) { - Q_syscall( CG_FX_PLAY_EFFECT, file, org, fwd, vol, rad); -} -void trap_FX_PlayEntityEffect( const char *file, vec3_t org, matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad ) { - Q_syscall( CG_FX_PLAY_ENTITY_EFFECT, file, org, axis, boltInfo, entNum, vol, rad ); -} -void trap_FX_PlayEffectID( int id, vec3_t org, vec3_t fwd, int vol, int rad ) { - Q_syscall( CG_FX_PLAY_EFFECT_ID, id, org, fwd, vol, rad ); -} -void trap_FX_PlayPortalEffectID( int id, vec3_t org, vec3_t fwd, int vol, int rad ) { - Q_syscall( CG_FX_PLAY_PORTAL_EFFECT_ID, id, org, fwd); -} -void trap_FX_PlayEntityEffectID( int id, vec3_t org, matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad ) { - Q_syscall( CG_FX_PLAY_ENTITY_EFFECT_ID, id, org, axis, boltInfo, entNum, vol, rad ); -} -qboolean trap_FX_PlayBoltedEffectID( int id, vec3_t org, void *ghoul2, const int boltNum, const int entNum, const int modelNum, int iLooptime, qboolean isRelative ) { - return Q_syscall( CG_FX_PLAY_BOLTED_EFFECT_ID, id, org, ghoul2, boltNum, entNum, modelNum, iLooptime, isRelative ); -} -void trap_FX_AddScheduledEffects( qboolean skyPortal ) { - Q_syscall( CG_FX_ADD_SCHEDULED_EFFECTS, skyPortal ); -} -void trap_FX_Draw2DEffects ( float screenXScale, float screenYScale ) { - Q_syscall( CG_FX_DRAW_2D_EFFECTS, PASSFLOAT(screenXScale), PASSFLOAT(screenYScale) ); -} -int trap_FX_InitSystem( refdef_t* refdef ) { - return Q_syscall( CG_FX_INIT_SYSTEM, refdef ); -} -void trap_FX_SetRefDef( refdef_t* refdef ) { - Q_syscall( CG_FX_SET_REFDEF, refdef ); -} -qboolean trap_FX_FreeSystem( void ) { - return Q_syscall( CG_FX_FREE_SYSTEM ); -} -void trap_FX_Reset ( void ) { - Q_syscall ( CG_FX_RESET ); -} -void trap_FX_AdjustTime( int time ) { - Q_syscall( CG_FX_ADJUST_TIME, time ); -} -void trap_FX_AddPoly( addpolyArgStruct_t *p ) { - Q_syscall( CG_FX_ADDPOLY, p ); -} -void trap_FX_AddBezier( addbezierArgStruct_t *p ) { - Q_syscall( CG_FX_ADDBEZIER, p ); -} -void trap_FX_AddPrimitive( effectTrailArgStruct_t *p ) { - Q_syscall( CG_FX_ADDPRIMITIVE, p ); -} -void trap_FX_AddSprite( addspriteArgStruct_t *p ) { - Q_syscall( CG_FX_ADDSPRITE, p ); -} -void trap_FX_AddElectricity( addElectricityArgStruct_t *p ) { - Q_syscall( CG_FX_ADDELECTRICITY, p ); -} + Q_syscall(CG_SETCLIENTTURNEXTENT, PASSFLOAT(turnAdd), PASSFLOAT(turnSub), turnTime); +} +void trap_OpenUIMenu(int menuID) { Q_syscall(CG_OPENUIMENU, menuID); } +void testPrintInt(char *string, int i) { Q_syscall(CG_TESTPRINTINT, string, i); } +void testPrintFloat(char *string, float f) { Q_syscall(CG_TESTPRINTFLOAT, string, PASSFLOAT(f)); } +int trap_MemoryRemaining(void) { return Q_syscall(CG_MEMORY_REMAINING); } +qboolean trap_Key_IsDown(int keynum) { return Q_syscall(CG_KEY_ISDOWN, keynum); } +int trap_Key_GetCatcher(void) { return Q_syscall(CG_KEY_GETCATCHER); } +void trap_Key_SetCatcher(int catcher) { Q_syscall(CG_KEY_SETCATCHER, catcher); } +int trap_Key_GetKey(const char *binding) { return Q_syscall(CG_KEY_GETKEY, binding); } +int trap_PC_AddGlobalDefine(char *define) { return Q_syscall(CG_PC_ADD_GLOBAL_DEFINE, define); } +int trap_PC_LoadSource(const char *filename) { return Q_syscall(CG_PC_LOAD_SOURCE, filename); } +int trap_PC_FreeSource(int handle) { return Q_syscall(CG_PC_FREE_SOURCE, handle); } +int trap_PC_ReadToken(int handle, pc_token_t *pc_token) { return Q_syscall(CG_PC_READ_TOKEN, handle, pc_token); } +int trap_PC_SourceFileAndLine(int handle, char *filename, int *line) { return Q_syscall(CG_PC_SOURCE_FILE_AND_LINE, handle, filename, line); } +int trap_PC_LoadGlobalDefines(const char *filename) { return Q_syscall(CG_PC_LOAD_GLOBAL_DEFINES, filename); } +void trap_PC_RemoveAllGlobalDefines(void) { Q_syscall(CG_PC_REMOVE_ALL_GLOBAL_DEFINES); } +void trap_S_StopBackgroundTrack(void) { Q_syscall(CG_S_STOPBACKGROUNDTRACK); } +int trap_RealTime(qtime_t *qtime) { return Q_syscall(CG_REAL_TIME, qtime); } +void trap_SnapVector(float *v) { Q_syscall(CG_SNAPVECTOR, v); } +int trap_CIN_PlayCinematic(const char *arg0, int xpos, int ypos, int width, int height, int bits) { + return Q_syscall(CG_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits); +} +e_status trap_CIN_StopCinematic(int handle) { return Q_syscall(CG_CIN_STOPCINEMATIC, handle); } +e_status trap_CIN_RunCinematic(int handle) { return Q_syscall(CG_CIN_RUNCINEMATIC, handle); } +void trap_CIN_DrawCinematic(int handle) { Q_syscall(CG_CIN_DRAWCINEMATIC, handle); } +void trap_CIN_SetExtents(int handle, int x, int y, int w, int h) { Q_syscall(CG_CIN_SETEXTENTS, handle, x, y, w, h); } +qboolean trap_GetEntityToken(char *buffer, int bufferSize) { return Q_syscall(CG_GET_ENTITY_TOKEN, buffer, bufferSize); } +qboolean trap_R_inPVS(const vec3_t p1, const vec3_t p2, byte *mask) { return Q_syscall(CG_R_INPVS, p1, p2, mask); } +int trap_FX_RegisterEffect(const char *file) { return Q_syscall(CG_FX_REGISTER_EFFECT, file); } +void trap_FX_PlayEffect(const char *file, vec3_t org, vec3_t fwd, int vol, int rad) { Q_syscall(CG_FX_PLAY_EFFECT, file, org, fwd, vol, rad); } +void trap_FX_PlayEntityEffect(const char *file, vec3_t org, matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad) { + Q_syscall(CG_FX_PLAY_ENTITY_EFFECT, file, org, axis, boltInfo, entNum, vol, rad); +} +void trap_FX_PlayEffectID(int id, vec3_t org, vec3_t fwd, int vol, int rad) { Q_syscall(CG_FX_PLAY_EFFECT_ID, id, org, fwd, vol, rad); } +void trap_FX_PlayPortalEffectID(int id, vec3_t org, vec3_t fwd, int vol, int rad) { Q_syscall(CG_FX_PLAY_PORTAL_EFFECT_ID, id, org, fwd); } +void trap_FX_PlayEntityEffectID(int id, vec3_t org, matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad) { + Q_syscall(CG_FX_PLAY_ENTITY_EFFECT_ID, id, org, axis, boltInfo, entNum, vol, rad); +} +qboolean trap_FX_PlayBoltedEffectID(int id, vec3_t org, void *ghoul2, const int boltNum, const int entNum, const int modelNum, int iLooptime, + qboolean isRelative) { + return Q_syscall(CG_FX_PLAY_BOLTED_EFFECT_ID, id, org, ghoul2, boltNum, entNum, modelNum, iLooptime, isRelative); +} +void trap_FX_AddScheduledEffects(qboolean skyPortal) { Q_syscall(CG_FX_ADD_SCHEDULED_EFFECTS, skyPortal); } +void trap_FX_Draw2DEffects(float screenXScale, float screenYScale) { Q_syscall(CG_FX_DRAW_2D_EFFECTS, PASSFLOAT(screenXScale), PASSFLOAT(screenYScale)); } +int trap_FX_InitSystem(refdef_t *refdef) { return Q_syscall(CG_FX_INIT_SYSTEM, refdef); } +void trap_FX_SetRefDef(refdef_t *refdef) { Q_syscall(CG_FX_SET_REFDEF, refdef); } +qboolean trap_FX_FreeSystem(void) { return Q_syscall(CG_FX_FREE_SYSTEM); } +void trap_FX_Reset(void) { Q_syscall(CG_FX_RESET); } +void trap_FX_AdjustTime(int time) { Q_syscall(CG_FX_ADJUST_TIME, time); } +void trap_FX_AddPoly(addpolyArgStruct_t *p) { Q_syscall(CG_FX_ADDPOLY, p); } +void trap_FX_AddBezier(addbezierArgStruct_t *p) { Q_syscall(CG_FX_ADDBEZIER, p); } +void trap_FX_AddPrimitive(effectTrailArgStruct_t *p) { Q_syscall(CG_FX_ADDPRIMITIVE, p); } +void trap_FX_AddSprite(addspriteArgStruct_t *p) { Q_syscall(CG_FX_ADDSPRITE, p); } +void trap_FX_AddElectricity(addElectricityArgStruct_t *p) { Q_syscall(CG_FX_ADDELECTRICITY, p); } qboolean trap_SE_GetStringTextString(const char *text, char *buffer, int bufferLength) { - return Q_syscall( CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength ); -} -qboolean trap_ROFF_Clean( void ) { - return Q_syscall( CG_ROFF_CLEAN ); -} -void trap_ROFF_UpdateEntities( void ) { - Q_syscall( CG_ROFF_UPDATE_ENTITIES ); -} -int trap_ROFF_Cache( char *file ) { - return Q_syscall( CG_ROFF_CACHE, file ); -} -qboolean trap_ROFF_Play( int entID, int roffID, qboolean doTranslation ) { - return Q_syscall( CG_ROFF_PLAY, entID, roffID, doTranslation ); -} -qboolean trap_ROFF_Purge_Ent( int entID ) { - return Q_syscall( CG_ROFF_PURGE_ENT, entID ); -} -void trap_TrueMalloc(void **ptr, int size) { - Q_syscall(CG_TRUEMALLOC, ptr, size); -} -void trap_TrueFree(void **ptr) { - Q_syscall(CG_TRUEFREE, ptr); -} -void trap_G2_ListModelSurfaces(void *ghlInfo) { - Q_syscall( CG_G2_LISTSURFACES, ghlInfo); -} -void trap_G2_ListModelBones(void *ghlInfo, int frame) { - Q_syscall( CG_G2_LISTBONES, ghlInfo, frame); -} -void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { - Q_syscall( CG_G2_SETMODELS, ghoul2, modelList, skinList); -} -qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { - return (qboolean)(Q_syscall(CG_G2_HAVEWEGHOULMODELS, ghoul2)); -} -qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + return Q_syscall(CG_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength); +} +qboolean trap_ROFF_Clean(void) { return Q_syscall(CG_ROFF_CLEAN); } +void trap_ROFF_UpdateEntities(void) { Q_syscall(CG_ROFF_UPDATE_ENTITIES); } +int trap_ROFF_Cache(char *file) { return Q_syscall(CG_ROFF_CACHE, file); } +qboolean trap_ROFF_Play(int entID, int roffID, qboolean doTranslation) { return Q_syscall(CG_ROFF_PLAY, entID, roffID, doTranslation); } +qboolean trap_ROFF_Purge_Ent(int entID) { return Q_syscall(CG_ROFF_PURGE_ENT, entID); } +void trap_TrueMalloc(void **ptr, int size) { Q_syscall(CG_TRUEMALLOC, ptr, size); } +void trap_TrueFree(void **ptr) { Q_syscall(CG_TRUEFREE, ptr); } +void trap_G2_ListModelSurfaces(void *ghlInfo) { Q_syscall(CG_G2_LISTSURFACES, ghlInfo); } +void trap_G2_ListModelBones(void *ghlInfo, int frame) { Q_syscall(CG_G2_LISTBONES, ghlInfo, frame); } +void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { Q_syscall(CG_G2_SETMODELS, ghoul2, modelList, skinList); } +qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { return (qboolean)(Q_syscall(CG_G2_HAVEWEGHOULMODELS, ghoul2)); } +qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(CG_G2_GETBOLT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { +qboolean trap_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(CG_G2_GETBOLT_NOREC, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { +qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(CG_G2_GETBOLT_NOREC_NOROT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias) { +int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { return Q_syscall(CG_G2_INITGHOUL2MODEL, ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } qboolean trap_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { return Q_syscall(CG_G2_SETSKIN, ghoul2, modelIndex, customSkin, renderSkin); } -void trap_G2API_CollisionDetect ( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( CG_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); +void trap_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(CG_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, + PASSFLOAT(fRadius)); } -void trap_G2API_CollisionDetectCache ( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position,int frameNumber, int entNum, const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( CG_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); +void trap_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(CG_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, + PASSFLOAT(fRadius)); } -void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { - Q_syscall(CG_G2_CLEANMODELS, ghoul2Ptr); -} -qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, const int forward, qhandle_t *modelList, int blendTime , int currentTime ) { +void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { Q_syscall(CG_G2_CLEANMODELS, ghoul2Ptr); } +qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { return (Q_syscall(CG_G2_ANGLEOVERRIDE, ghoul2, modelIndex, boneName, angles, flags, up, right, forward, modelList, blendTime, currentTime)); } -qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame , const int blendTime ) { - return Q_syscall(CG_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), blendTime); +qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + return Q_syscall(CG_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), + blendTime); } -qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList, const int modelIndex) { +qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { return Q_syscall(CG_G2_GETBONEANIM, ghoul2, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, modelIndex); } qboolean trap_G2API_GetBoneFrame(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *modelList, const int modelIndex) { return Q_syscall(CG_G2_GETBONEFRAME, ghoul2, boneName, currentTime, currentFrame, modelList, modelIndex); } -void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { - Q_syscall(CG_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); -} -int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { - return Q_syscall(CG_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); -} +void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { Q_syscall(CG_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); } +int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { return Q_syscall(CG_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); } void trap_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { Q_syscall(CG_G2_COPYSPECIFICGHOUL2MODEL, g2From, modelFrom, g2To, modelTo); } -void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { - Q_syscall(CG_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); -} -qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { - return Q_syscall(CG_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); -} -qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { - return Q_syscall(CG_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); -} -qboolean trap_G2API_SkinlessModel(void *ghlInfo, int modelIndex) { - return Q_syscall(CG_G2_SKINLESSMODEL, ghlInfo, modelIndex); -} -int trap_G2API_GetNumGoreMarks(void *ghlInfo, int modelIndex) { - return Q_syscall(CG_G2_GETNUMGOREMARKS, ghlInfo, modelIndex); -} -void trap_G2API_AddSkinGore(void *ghlInfo,SSkinGoreData *gore) { - Q_syscall(CG_G2_ADDSKINGORE, ghlInfo, gore); -} -void trap_G2API_ClearSkinGore ( void* ghlInfo ) { - Q_syscall(CG_G2_CLEARSKINGORE, ghlInfo ); -} -int trap_G2API_Ghoul2Size ( void* ghlInfo ) { - return Q_syscall(CG_G2_SIZE, ghlInfo ); -} -int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { - return Q_syscall(CG_G2_ADDBOLT, ghoul2, modelIndex, boneName); -} +void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { Q_syscall(CG_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); } +qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { return Q_syscall(CG_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); } +qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { return Q_syscall(CG_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); } +qboolean trap_G2API_SkinlessModel(void *ghlInfo, int modelIndex) { return Q_syscall(CG_G2_SKINLESSMODEL, ghlInfo, modelIndex); } +int trap_G2API_GetNumGoreMarks(void *ghlInfo, int modelIndex) { return Q_syscall(CG_G2_GETNUMGOREMARKS, ghlInfo, modelIndex); } +void trap_G2API_AddSkinGore(void *ghlInfo, SSkinGoreData *gore) { Q_syscall(CG_G2_ADDSKINGORE, ghlInfo, gore); } +void trap_G2API_ClearSkinGore(void *ghlInfo) { Q_syscall(CG_G2_CLEARSKINGORE, ghlInfo); } +int trap_G2API_Ghoul2Size(void *ghlInfo) { return Q_syscall(CG_G2_SIZE, ghlInfo); } +int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { return Q_syscall(CG_G2_ADDBOLT, ghoul2, modelIndex, boneName); } qboolean trap_G2API_AttachEnt(int *boltInfo, void *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum) { return Q_syscall(CG_G2_ATTACHENT, boltInfo, ghlInfoTo, toBoltIndex, entNum, toModelNum); } -void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { - Q_syscall(CG_G2_SETBOLTON, ghoul2, modelIndex, boltInfo); -} +void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { Q_syscall(CG_G2_SETBOLTON, ghoul2, modelIndex, boltInfo); } qboolean trap_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const char *surfaceName) { return Q_syscall(CG_G2_SETROOTSURFACE, ghoul2, modelIndex, surfaceName); } qboolean trap_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { return Q_syscall(CG_G2_SETSURFACEONOFF, ghoul2, surfaceName, flags); } -qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { - return Q_syscall(CG_G2_SETNEWORIGIN, ghoul2, boltIndex); -} -qboolean trap_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { - return Q_syscall(CG_G2_DOESBONEEXIST, ghoul2, modelIndex, boneName); -} +qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { return Q_syscall(CG_G2_SETNEWORIGIN, ghoul2, boltIndex); } +qboolean trap_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { return Q_syscall(CG_G2_DOESBONEEXIST, ghoul2, modelIndex, boneName); } int trap_G2API_GetSurfaceRenderStatus(void *ghoul2, const int modelIndex, const char *surfaceName) { return Q_syscall(CG_G2_GETSURFACERENDERSTATUS, ghoul2, modelIndex, surfaceName); } -int trap_G2API_GetTime(void) { - return Q_syscall(CG_G2_GETTIME); -} -void trap_G2API_SetTime(int time, int clock) { - Q_syscall(CG_G2_SETTIME, time, clock); -} -void trap_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { - Q_syscall(CG_G2_ABSURDSMOOTHING, ghoul2, status); -} -void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { - Q_syscall(CG_G2_SETRAGDOLL, ghoul2, params); -} -void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { - Q_syscall(CG_G2_ANIMATEG2MODELS, ghoul2, time, params); -} +int trap_G2API_GetTime(void) { return Q_syscall(CG_G2_GETTIME); } +void trap_G2API_SetTime(int time, int clock) { Q_syscall(CG_G2_SETTIME, time, clock); } +void trap_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { Q_syscall(CG_G2_ABSURDSMOOTHING, ghoul2, status); } +void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { Q_syscall(CG_G2_SETRAGDOLL, ghoul2, params); } +void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { Q_syscall(CG_G2_ANIMATEG2MODELS, ghoul2, time, params); } qboolean trap_G2API_RagPCJConstraint(void *ghoul2, const char *boneName, vec3_t min, vec3_t max) { return Q_syscall(CG_G2_RAGPCJCONSTRAINT, ghoul2, boneName, min, max); } qboolean trap_G2API_RagPCJGradientSpeed(void *ghoul2, const char *boneName, const float speed) { return Q_syscall(CG_G2_RAGPCJGRADIENTSPEED, ghoul2, boneName, PASSFLOAT(speed)); } -qboolean trap_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { - return Q_syscall(CG_G2_RAGEFFECTORGOAL, ghoul2, boneName, pos); -} +qboolean trap_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { return Q_syscall(CG_G2_RAGEFFECTORGOAL, ghoul2, boneName, pos); } qboolean trap_G2API_GetRagBonePos(void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { return Q_syscall(CG_G2_GETRAGBONEPOS, ghoul2, boneName, pos, entAngles, entPos, entScale); } qboolean trap_G2API_RagEffectorKick(void *ghoul2, const char *boneName, vec3_t velocity) { return Q_syscall(CG_G2_RAGEFFECTORKICK, ghoul2, boneName, velocity); } -qboolean trap_G2API_RagForceSolve(void *ghoul2, qboolean force) { - return Q_syscall(CG_G2_RAGFORCESOLVE, ghoul2, force); -} +qboolean trap_G2API_RagForceSolve(void *ghoul2, qboolean force) { return Q_syscall(CG_G2_RAGFORCESOLVE, ghoul2, force); } qboolean trap_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return Q_syscall(CG_G2_SETBONEIKSTATE, ghoul2, time, boneName, ikState, params); } -qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { - return Q_syscall(CG_G2_IKMOVE, ghoul2, time, params); -} -qboolean trap_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { - return Q_syscall(CG_G2_REMOVEBONE, ghoul2, boneName, modelIndex); -} -void trap_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { - Q_syscall(CG_G2_ATTACHINSTANCETOENTNUM, ghoul2, entityNum, server); +qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { return Q_syscall(CG_G2_IKMOVE, ghoul2, time, params); } +qboolean trap_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { return Q_syscall(CG_G2_REMOVEBONE, ghoul2, boneName, modelIndex); } +void trap_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { Q_syscall(CG_G2_ATTACHINSTANCETOENTNUM, ghoul2, entityNum, server); } +void trap_G2API_ClearAttachedInstance(int entityNum) { Q_syscall(CG_G2_CLEARATTACHEDINSTANCE, entityNum); } +void trap_G2API_CleanEntAttachments(void) { Q_syscall(CG_G2_CLEANENTATTACHMENTS); } +qboolean trap_G2API_OverrideServer(void *serverInstance) { return Q_syscall(CG_G2_OVERRIDESERVER, serverInstance); } +void trap_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { + Q_syscall(CG_G2_GETSURFACENAME, ghoul2, surfNumber, modelIndex, fillBuf); } -void trap_G2API_ClearAttachedInstance(int entityNum) { - Q_syscall(CG_G2_CLEARATTACHEDINSTANCE, entityNum); +void trap_CG_RegisterSharedMemory(char *memory) { Q_syscall(CG_SET_SHARED_BUFFER, memory); } +void trap_R_WeatherContentsOverride(int contents) { Q_syscall(CG_R_WEATHER_CONTENTS_OVERRIDE, contents); } +void trap_R_WorldEffectCommand(const char *cmd) { Q_syscall(CG_R_WORLDEFFECTCOMMAND, cmd); } +void trap_WE_AddWeatherZone(vec3_t mins, vec3_t maxs) { Q_syscall(CG_WE_ADDWEATHERZONE, mins, maxs); } + +// Translate import table funcptrs to syscalls + +int CGSyscall_FS_Read(void *buffer, int len, fileHandle_t f) { + trap_FS_Read(buffer, len, f); + return 0; } -void trap_G2API_CleanEntAttachments(void) { - Q_syscall(CG_G2_CLEANENTATTACHMENTS); +int CGSyscall_FS_Write(const void *buffer, int len, fileHandle_t f) { + trap_FS_Write(buffer, len, f); + return 0; } -qboolean trap_G2API_OverrideServer(void *serverInstance) { - return Q_syscall(CG_G2_OVERRIDESERVER, serverInstance); +clipHandle_t CGSyscall_CM_TempModel(const vec3_t mins, const vec3_t maxs, int capsule) { + if (capsule) + return trap_CM_TempCapsuleModel(mins, maxs); + else + return trap_CM_TempBoxModel(mins, maxs); } -void trap_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { - Q_syscall(CG_G2_GETSURFACENAME, ghoul2, surfNumber, modelIndex, fillBuf); +void CGSyscall_CM_Trace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, + int capsule) { + if (capsule) + trap_CM_CapsuleTrace(results, start, end, mins, maxs, model, brushmask); + else + trap_CM_BoxTrace(results, start, end, mins, maxs, model, brushmask); } -void trap_CG_RegisterSharedMemory(char *memory) { - Q_syscall(CG_SET_SHARED_BUFFER, memory); +void CGSyscall_CM_TransformedTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, + int brushmask, const vec3_t origin, const vec3_t angles, int capsule) { + if (capsule) + trap_CM_TransformedCapsuleTrace(results, start, end, mins, maxs, model, brushmask, origin, angles); + else + trap_CM_TransformedBoxTrace(results, start, end, mins, maxs, model, brushmask, origin, angles); } -void trap_R_WeatherContentsOverride( int contents ) { - Q_syscall(CG_R_WEATHER_CONTENTS_OVERRIDE, contents); +void CGSyscall_R_AddPolysToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts, int num) { trap_R_AddPolyToScene(hShader, numVerts, verts); } +float CGSyscall_R_GetDistanceCull(void) { + float tmp; + trap_R_GetDistanceCull(&tmp); + return tmp; } -void trap_R_WorldEffectCommand(const char *cmd) { - Q_syscall(CG_R_WORLDEFFECTCOMMAND, cmd); +void CGSyscall_FX_PlayEffectID(int id, vec3_t org, vec3_t fwd, int vol, int rad, qboolean isPortal) { + if (isPortal) + trap_FX_PlayPortalEffectID(id, org, fwd, vol, rad); + else + trap_FX_PlayEffectID(id, org, fwd, vol, rad); } -void trap_WE_AddWeatherZone( vec3_t mins, vec3_t maxs ) { - Q_syscall( CG_WE_ADDWEATHERZONE, mins, maxs ); +void CGSyscall_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + trap_G2API_CollisionDetect(collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, fRadius); } - -// Translate import table funcptrs to syscalls - -int CGSyscall_FS_Read( void *buffer, int len, fileHandle_t f ) { trap_FS_Read( buffer, len, f ); return 0; } -int CGSyscall_FS_Write( const void *buffer, int len, fileHandle_t f ) { trap_FS_Write( buffer, len, f ); return 0; } -clipHandle_t CGSyscall_CM_TempModel( const vec3_t mins, const vec3_t maxs, int capsule ) { if ( capsule ) return trap_CM_TempCapsuleModel( mins, maxs ); else return trap_CM_TempBoxModel( mins, maxs ); } -void CGSyscall_CM_Trace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, int capsule ) { if ( capsule ) trap_CM_CapsuleTrace( results, start, end, mins, maxs, model, brushmask ); else trap_CM_BoxTrace( results, start, end, mins, maxs, model, brushmask ); } -void CGSyscall_CM_TransformedTrace( trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, const vec3_t origin, const vec3_t angles, int capsule ) { if ( capsule ) trap_CM_TransformedCapsuleTrace( results, start, end, mins, maxs, model, brushmask, origin, angles ); else trap_CM_TransformedBoxTrace( results, start, end, mins, maxs, model, brushmask, origin, angles ); } -void CGSyscall_R_AddPolysToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int num ) { trap_R_AddPolyToScene( hShader, numVerts, verts ); } -float CGSyscall_R_GetDistanceCull( void ) { float tmp; trap_R_GetDistanceCull( &tmp ); return tmp; } -void CGSyscall_FX_PlayEffectID( int id, vec3_t org, vec3_t fwd, int vol, int rad, qboolean isPortal ) { if ( isPortal ) trap_FX_PlayPortalEffectID( id, org, fwd, vol, rad ); else trap_FX_PlayEffectID( id, org, fwd, vol, rad ); } -void CGSyscall_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { trap_G2API_CollisionDetect( collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, fRadius ); } - -NORETURN void QDECL CG_Error( int level, const char *error, ... ) { +NORETURN void QDECL CG_Error(int level, const char *error, ...) { va_list argptr; char text[1024] = {0}; - va_start( argptr, error ); - Q_vsnprintf( text, sizeof( text ), error, argptr ); - va_end( argptr ); + va_start(argptr, error); + Q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); - trap_Error( text ); + trap_Error(text); } -void QDECL CG_Printf( const char *msg, ... ) { +void QDECL CG_Printf(const char *msg, ...) { va_list argptr; char text[4096] = {0}; int ret; - va_start( argptr, msg ); - ret = Q_vsnprintf( text, sizeof( text ), msg, argptr ); - va_end( argptr ); + va_start(argptr, msg); + ret = Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - if ( ret == -1 ) - trap_Print( "CG_Printf: overflow of 4096 bytes buffer\n" ); + if (ret == -1) + trap_Print("CG_Printf: overflow of 4096 bytes buffer\n"); else - trap_Print( text ); + trap_Print(text); } -static void TranslateSyscalls( void ) { +static void TranslateSyscalls(void) { static cgameImport_t import; - memset( &import, 0, sizeof( import ) ); + memset(&import, 0, sizeof(import)); trap = &import; - Com_Error = CG_Error; - Com_Printf = CG_Printf; + Com_Error = CG_Error; + Com_Printf = CG_Printf; - trap->Print = CG_Printf; - trap->Error = CG_Error; - trap->SnapVector = trap_SnapVector; - trap->MemoryRemaining = trap_MemoryRemaining; - trap->RegisterSharedMemory = trap_CG_RegisterSharedMemory; - trap->TrueMalloc = trap_TrueMalloc; - trap->TrueFree = trap_TrueFree; - trap->Milliseconds = trap_Milliseconds; - trap->RealTime = trap_RealTime; - trap->PrecisionTimerStart = trap_PrecisionTimer_Start; - trap->PrecisionTimerEnd = trap_PrecisionTimer_End; - trap->Cvar_Register = trap_Cvar_Register; - trap->Cvar_Set = trap_Cvar_Set; - trap->Cvar_Update = trap_Cvar_Update; - trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; - trap->AddCommand = trap_AddCommand; - trap->Cmd_Argc = trap_Argc; - trap->Cmd_Args = trap_Args; - trap->Cmd_Argv = trap_Argv; - trap->RemoveCommand = trap_RemoveCommand; - trap->SendClientCommand = trap_SendClientCommand; - trap->SendConsoleCommand = trap_SendConsoleCommand; - trap->FS_Close = trap_FS_FCloseFile; - trap->FS_GetFileList = trap_FS_GetFileList; - trap->FS_Open = trap_FS_FOpenFile; - trap->FS_Read = CGSyscall_FS_Read; - trap->FS_Write = CGSyscall_FS_Write; - trap->UpdateScreen = trap_UpdateScreen; - trap->CM_InlineModel = trap_CM_InlineModel; - trap->CM_LoadMap = trap_CM_LoadMap; - trap->CM_NumInlineModels = trap_CM_NumInlineModels; - trap->CM_PointContents = trap_CM_PointContents; - trap->CM_TempModel = CGSyscall_CM_TempModel; - trap->CM_Trace = CGSyscall_CM_Trace; - trap->CM_TransformedPointContents = trap_CM_TransformedPointContents; - trap->CM_TransformedTrace = CGSyscall_CM_TransformedTrace; - trap->S_AddLocalSet = trap_S_AddLocalSet; - trap->S_AddLoopingSound = trap_S_AddLoopingSound; - trap->S_ClearLoopingSounds = trap_S_ClearLoopingSounds; - trap->S_GetVoiceVolume = trap_S_GetVoiceVolume; - trap->S_MuteSound = trap_S_MuteSound; - trap->S_RegisterSound = trap_S_RegisterSound; - trap->S_Respatialize = trap_S_Respatialize; - trap->S_Shutup = trap_S_ShutUp; - trap->S_StartBackgroundTrack = trap_S_StartBackgroundTrack; - trap->S_StartLocalSound = trap_S_StartLocalSound; - trap->S_StartSound = trap_S_StartSound; - trap->S_StopBackgroundTrack = trap_S_StopBackgroundTrack; - trap->S_StopLoopingSound = trap_S_StopLoopingSound; - trap->S_UpdateEntityPosition = trap_S_UpdateEntityPosition; - trap->S_UpdateAmbientSet = trap_S_UpdateAmbientSet; - trap->AS_AddPrecacheEntry = trap_AS_AddPrecacheEntry; - trap->AS_GetBModelSound = trap_AS_GetBModelSound; - trap->AS_ParseSets = trap_AS_ParseSets; - trap->R_AddAdditiveLightToScene = trap_R_AddAdditiveLightToScene; - trap->R_AddDecalToScene = trap_R_AddDecalToScene; - trap->R_AddLightToScene = trap_R_AddLightToScene; - trap->R_AddPolysToScene = CGSyscall_R_AddPolysToScene; - trap->R_AddRefEntityToScene = trap_R_AddRefEntityToScene; - trap->R_AnyLanguage_ReadCharFromString = trap_AnyLanguage_ReadCharFromString; - trap->R_AutomapElevationAdjustment = trap_R_AutomapElevAdj; - trap->R_ClearDecals = trap_R_ClearDecals; - trap->R_ClearScene = trap_R_ClearScene; - trap->R_DrawStretchPic = trap_R_DrawStretchPic; - trap->R_DrawRotatePic = trap_R_DrawRotatePic; - trap->R_DrawRotatePic2 = trap_R_DrawRotatePic2; - trap->R_Font_DrawString = trap_R_Font_DrawString; - trap->R_Font_HeightPixels = trap_R_Font_HeightPixels; - trap->R_Font_StrLenChars = trap_R_Font_StrLenChars; - trap->R_Font_StrLenPixels = trap_R_Font_StrLenPixels; - trap->R_GetBModelVerts = trap_R_GetBModelVerts; - trap->R_GetDistanceCull = CGSyscall_R_GetDistanceCull; - trap->R_GetEntityToken = trap_GetEntityToken; - trap->R_GetLightStyle = trap_R_GetLightStyle; - trap->R_GetRealRes = trap_R_GetRealRes; - trap->R_InitializeWireframeAutomap = trap_R_InitWireframeAutomap; - trap->R_InPVS = trap_R_inPVS; - trap->R_Language_IsAsian = trap_Language_IsAsian; - trap->R_Language_UsesSpaces = trap_Language_UsesSpaces; - trap->R_LerpTag = trap_R_LerpTag; - trap->R_LightForPoint = trap_R_LightForPoint; - trap->R_LoadWorld = trap_R_LoadWorldMap; - trap->R_MarkFragments = trap_CM_MarkFragments; - trap->R_ModelBounds = trap_R_ModelBounds; - trap->R_RegisterFont = trap_R_RegisterFont; - trap->R_RegisterModel = trap_R_RegisterModel; - trap->R_RegisterShader = trap_R_RegisterShader; - trap->R_RegisterShaderNoMip = trap_R_RegisterShaderNoMip; - trap->R_RegisterSkin = trap_R_RegisterSkin; - trap->R_RemapShader = trap_R_RemapShader; - trap->R_RenderScene = trap_R_RenderScene; - trap->R_SetColor = trap_R_SetColor; - trap->R_SetLightStyle = trap_R_SetLightStyle; - trap->R_SetRangedFog = trap_R_SetRangeFog; - trap->R_SetRefractionProperties = trap_R_SetRefractProp; - trap->R_WorldEffectCommand = trap_R_WorldEffectCommand; - trap->WE_AddWeatherZone = trap_WE_AddWeatherZone; - trap->GetCurrentSnapshotNumber = trap_GetCurrentSnapshotNumber; - trap->GetCurrentCmdNumber = trap_GetCurrentCmdNumber; - trap->GetDefaultState = trap_GetDefaultState; - trap->GetGameState = trap_GetGameState; - trap->GetGlconfig = trap_GetGlconfig; - trap->GetServerCommand = trap_GetServerCommand; - trap->GetSnapshot = trap_GetSnapshot; - trap->GetUserCmd = trap_GetUserCmd; - trap->OpenUIMenu = trap_OpenUIMenu; - trap->SetClientForceAngle = trap_SetClientForceAngle; - trap->SetUserCmdValue = trap_SetUserCmdValue; - trap->Key_GetCatcher = trap_Key_GetCatcher; - trap->Key_GetKey = trap_Key_GetKey; - trap->Key_IsDown = trap_Key_IsDown; - trap->Key_SetCatcher = trap_Key_SetCatcher; - trap->PC_AddGlobalDefine = trap_PC_AddGlobalDefine; - trap->PC_FreeSource = trap_PC_FreeSource; - trap->PC_LoadGlobalDefines = trap_PC_LoadGlobalDefines; - trap->PC_LoadSource = trap_PC_LoadSource; - trap->PC_ReadToken = trap_PC_ReadToken; - trap->PC_RemoveAllGlobalDefines = trap_PC_RemoveAllGlobalDefines; - trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; - trap->CIN_DrawCinematic = trap_CIN_DrawCinematic; - trap->CIN_PlayCinematic = trap_CIN_PlayCinematic; - trap->CIN_RunCinematic = trap_CIN_RunCinematic; - trap->CIN_SetExtents = trap_CIN_SetExtents; - trap->CIN_StopCinematic = trap_CIN_StopCinematic; - trap->FX_AddLine = trap_FX_AddLine; - trap->FX_RegisterEffect = trap_FX_RegisterEffect; - trap->FX_PlayEffect = trap_FX_PlayEffect; - trap->FX_PlayEffectID = CGSyscall_FX_PlayEffectID; - trap->FX_PlayEntityEffectID = trap_FX_PlayEntityEffectID; - trap->FX_PlayBoltedEffectID = trap_FX_PlayBoltedEffectID; - trap->FX_AddScheduledEffects = trap_FX_AddScheduledEffects; - trap->FX_InitSystem = trap_FX_InitSystem; - trap->FX_SetRefDef = trap_FX_SetRefDef; - trap->FX_FreeSystem = trap_FX_FreeSystem; - trap->FX_AdjustTime = trap_FX_AdjustTime; - trap->FX_Draw2DEffects = trap_FX_Draw2DEffects; - trap->FX_AddPoly = trap_FX_AddPoly; - trap->FX_AddBezier = trap_FX_AddBezier; - trap->FX_AddPrimitive = trap_FX_AddPrimitive; - trap->FX_AddSprite = trap_FX_AddSprite; - trap->FX_AddElectricity = trap_FX_AddElectricity; - trap->SE_GetStringTextString = trap_SE_GetStringTextString; - trap->ROFF_Clean = trap_ROFF_Clean; - trap->ROFF_UpdateEntities = trap_ROFF_UpdateEntities; - trap->ROFF_Cache = trap_ROFF_Cache; - trap->ROFF_Play = trap_ROFF_Play; - trap->ROFF_Purge_Ent = trap_ROFF_Purge_Ent; - trap->G2_ListModelSurfaces = trap_G2_ListModelSurfaces; - trap->G2_ListModelBones = trap_G2_ListModelBones; - trap->G2_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; - trap->G2_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; - trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; - trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; - trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; - trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; - trap->G2API_SetSkin = trap_G2API_SetSkin; - trap->G2API_CollisionDetect = CGSyscall_G2API_CollisionDetect; - trap->G2API_CollisionDetectCache = CGSyscall_G2API_CollisionDetect; - trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; - trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; - trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; - trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; - trap->G2API_GetBoneFrame = trap_G2API_GetBoneFrame; - trap->G2API_GetGLAName = trap_G2API_GetGLAName; - trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; - trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; - trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; - trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; - trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; - trap->G2API_SkinlessModel = trap_G2API_SkinlessModel; - trap->G2API_GetNumGoreMarks = trap_G2API_GetNumGoreMarks; - trap->G2API_AddSkinGore = trap_G2API_AddSkinGore; - trap->G2API_ClearSkinGore = trap_G2API_ClearSkinGore; - trap->G2API_Ghoul2Size = trap_G2API_Ghoul2Size; - trap->G2API_AddBolt = trap_G2API_AddBolt; - trap->G2API_AttachEnt = trap_G2API_AttachEnt; - trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; - trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; - trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; - trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; - trap->G2API_DoesBoneExist = trap_G2API_DoesBoneExist; - trap->G2API_GetSurfaceRenderStatus = trap_G2API_GetSurfaceRenderStatus; - trap->G2API_GetTime = trap_G2API_GetTime; - trap->G2API_SetTime = trap_G2API_SetTime; - trap->G2API_AbsurdSmoothing = trap_G2API_AbsurdSmoothing; - trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; - trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; - trap->G2API_RagPCJConstraint = trap_G2API_RagPCJConstraint; - trap->G2API_RagPCJGradientSpeed = trap_G2API_RagPCJGradientSpeed; - trap->G2API_RagEffectorGoal = trap_G2API_RagEffectorGoal; - trap->G2API_GetRagBonePos = trap_G2API_GetRagBonePos; - trap->G2API_RagEffectorKick = trap_G2API_RagEffectorKick; - trap->G2API_RagForceSolve = trap_G2API_RagForceSolve; - trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; - trap->G2API_IKMove = trap_G2API_IKMove; - trap->G2API_RemoveBone = trap_G2API_RemoveBone; - trap->G2API_AttachInstanceToEntNum = trap_G2API_AttachInstanceToEntNum; - trap->G2API_ClearAttachedInstance = trap_G2API_ClearAttachedInstance; - trap->G2API_CleanEntAttachments = trap_G2API_CleanEntAttachments; - trap->G2API_OverrideServer = trap_G2API_OverrideServer; - trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; + trap->Print = CG_Printf; + trap->Error = CG_Error; + trap->SnapVector = trap_SnapVector; + trap->MemoryRemaining = trap_MemoryRemaining; + trap->RegisterSharedMemory = trap_CG_RegisterSharedMemory; + trap->TrueMalloc = trap_TrueMalloc; + trap->TrueFree = trap_TrueFree; + trap->Milliseconds = trap_Milliseconds; + trap->RealTime = trap_RealTime; + trap->PrecisionTimerStart = trap_PrecisionTimer_Start; + trap->PrecisionTimerEnd = trap_PrecisionTimer_End; + trap->Cvar_Register = trap_Cvar_Register; + trap->Cvar_Set = trap_Cvar_Set; + trap->Cvar_Update = trap_Cvar_Update; + trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; + trap->AddCommand = trap_AddCommand; + trap->Cmd_Argc = trap_Argc; + trap->Cmd_Args = trap_Args; + trap->Cmd_Argv = trap_Argv; + trap->RemoveCommand = trap_RemoveCommand; + trap->SendClientCommand = trap_SendClientCommand; + trap->SendConsoleCommand = trap_SendConsoleCommand; + trap->FS_Close = trap_FS_FCloseFile; + trap->FS_GetFileList = trap_FS_GetFileList; + trap->FS_Open = trap_FS_FOpenFile; + trap->FS_Read = CGSyscall_FS_Read; + trap->FS_Write = CGSyscall_FS_Write; + trap->UpdateScreen = trap_UpdateScreen; + trap->CM_InlineModel = trap_CM_InlineModel; + trap->CM_LoadMap = trap_CM_LoadMap; + trap->CM_NumInlineModels = trap_CM_NumInlineModels; + trap->CM_PointContents = trap_CM_PointContents; + trap->CM_TempModel = CGSyscall_CM_TempModel; + trap->CM_Trace = CGSyscall_CM_Trace; + trap->CM_TransformedPointContents = trap_CM_TransformedPointContents; + trap->CM_TransformedTrace = CGSyscall_CM_TransformedTrace; + trap->S_AddLocalSet = trap_S_AddLocalSet; + trap->S_AddLoopingSound = trap_S_AddLoopingSound; + trap->S_ClearLoopingSounds = trap_S_ClearLoopingSounds; + trap->S_GetVoiceVolume = trap_S_GetVoiceVolume; + trap->S_MuteSound = trap_S_MuteSound; + trap->S_RegisterSound = trap_S_RegisterSound; + trap->S_Respatialize = trap_S_Respatialize; + trap->S_Shutup = trap_S_ShutUp; + trap->S_StartBackgroundTrack = trap_S_StartBackgroundTrack; + trap->S_StartLocalSound = trap_S_StartLocalSound; + trap->S_StartSound = trap_S_StartSound; + trap->S_StopBackgroundTrack = trap_S_StopBackgroundTrack; + trap->S_StopLoopingSound = trap_S_StopLoopingSound; + trap->S_UpdateEntityPosition = trap_S_UpdateEntityPosition; + trap->S_UpdateAmbientSet = trap_S_UpdateAmbientSet; + trap->AS_AddPrecacheEntry = trap_AS_AddPrecacheEntry; + trap->AS_GetBModelSound = trap_AS_GetBModelSound; + trap->AS_ParseSets = trap_AS_ParseSets; + trap->R_AddAdditiveLightToScene = trap_R_AddAdditiveLightToScene; + trap->R_AddDecalToScene = trap_R_AddDecalToScene; + trap->R_AddLightToScene = trap_R_AddLightToScene; + trap->R_AddPolysToScene = CGSyscall_R_AddPolysToScene; + trap->R_AddRefEntityToScene = trap_R_AddRefEntityToScene; + trap->R_AnyLanguage_ReadCharFromString = trap_AnyLanguage_ReadCharFromString; + trap->R_AutomapElevationAdjustment = trap_R_AutomapElevAdj; + trap->R_ClearDecals = trap_R_ClearDecals; + trap->R_ClearScene = trap_R_ClearScene; + trap->R_DrawStretchPic = trap_R_DrawStretchPic; + trap->R_DrawRotatePic = trap_R_DrawRotatePic; + trap->R_DrawRotatePic2 = trap_R_DrawRotatePic2; + trap->R_Font_DrawString = trap_R_Font_DrawString; + trap->R_Font_HeightPixels = trap_R_Font_HeightPixels; + trap->R_Font_StrLenChars = trap_R_Font_StrLenChars; + trap->R_Font_StrLenPixels = trap_R_Font_StrLenPixels; + trap->R_GetBModelVerts = trap_R_GetBModelVerts; + trap->R_GetDistanceCull = CGSyscall_R_GetDistanceCull; + trap->R_GetEntityToken = trap_GetEntityToken; + trap->R_GetLightStyle = trap_R_GetLightStyle; + trap->R_GetRealRes = trap_R_GetRealRes; + trap->R_InitializeWireframeAutomap = trap_R_InitWireframeAutomap; + trap->R_InPVS = trap_R_inPVS; + trap->R_Language_IsAsian = trap_Language_IsAsian; + trap->R_Language_UsesSpaces = trap_Language_UsesSpaces; + trap->R_LerpTag = trap_R_LerpTag; + trap->R_LightForPoint = trap_R_LightForPoint; + trap->R_LoadWorld = trap_R_LoadWorldMap; + trap->R_MarkFragments = trap_CM_MarkFragments; + trap->R_ModelBounds = trap_R_ModelBounds; + trap->R_RegisterFont = trap_R_RegisterFont; + trap->R_RegisterModel = trap_R_RegisterModel; + trap->R_RegisterShader = trap_R_RegisterShader; + trap->R_RegisterShaderNoMip = trap_R_RegisterShaderNoMip; + trap->R_RegisterSkin = trap_R_RegisterSkin; + trap->R_RemapShader = trap_R_RemapShader; + trap->R_RenderScene = trap_R_RenderScene; + trap->R_SetColor = trap_R_SetColor; + trap->R_SetLightStyle = trap_R_SetLightStyle; + trap->R_SetRangedFog = trap_R_SetRangeFog; + trap->R_SetRefractionProperties = trap_R_SetRefractProp; + trap->R_WorldEffectCommand = trap_R_WorldEffectCommand; + trap->WE_AddWeatherZone = trap_WE_AddWeatherZone; + trap->GetCurrentSnapshotNumber = trap_GetCurrentSnapshotNumber; + trap->GetCurrentCmdNumber = trap_GetCurrentCmdNumber; + trap->GetDefaultState = trap_GetDefaultState; + trap->GetGameState = trap_GetGameState; + trap->GetGlconfig = trap_GetGlconfig; + trap->GetServerCommand = trap_GetServerCommand; + trap->GetSnapshot = trap_GetSnapshot; + trap->GetUserCmd = trap_GetUserCmd; + trap->OpenUIMenu = trap_OpenUIMenu; + trap->SetClientForceAngle = trap_SetClientForceAngle; + trap->SetUserCmdValue = trap_SetUserCmdValue; + trap->Key_GetCatcher = trap_Key_GetCatcher; + trap->Key_GetKey = trap_Key_GetKey; + trap->Key_IsDown = trap_Key_IsDown; + trap->Key_SetCatcher = trap_Key_SetCatcher; + trap->PC_AddGlobalDefine = trap_PC_AddGlobalDefine; + trap->PC_FreeSource = trap_PC_FreeSource; + trap->PC_LoadGlobalDefines = trap_PC_LoadGlobalDefines; + trap->PC_LoadSource = trap_PC_LoadSource; + trap->PC_ReadToken = trap_PC_ReadToken; + trap->PC_RemoveAllGlobalDefines = trap_PC_RemoveAllGlobalDefines; + trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; + trap->CIN_DrawCinematic = trap_CIN_DrawCinematic; + trap->CIN_PlayCinematic = trap_CIN_PlayCinematic; + trap->CIN_RunCinematic = trap_CIN_RunCinematic; + trap->CIN_SetExtents = trap_CIN_SetExtents; + trap->CIN_StopCinematic = trap_CIN_StopCinematic; + trap->FX_AddLine = trap_FX_AddLine; + trap->FX_RegisterEffect = trap_FX_RegisterEffect; + trap->FX_PlayEffect = trap_FX_PlayEffect; + trap->FX_PlayEffectID = CGSyscall_FX_PlayEffectID; + trap->FX_PlayEntityEffectID = trap_FX_PlayEntityEffectID; + trap->FX_PlayBoltedEffectID = trap_FX_PlayBoltedEffectID; + trap->FX_AddScheduledEffects = trap_FX_AddScheduledEffects; + trap->FX_InitSystem = trap_FX_InitSystem; + trap->FX_SetRefDef = trap_FX_SetRefDef; + trap->FX_FreeSystem = trap_FX_FreeSystem; + trap->FX_AdjustTime = trap_FX_AdjustTime; + trap->FX_Draw2DEffects = trap_FX_Draw2DEffects; + trap->FX_AddPoly = trap_FX_AddPoly; + trap->FX_AddBezier = trap_FX_AddBezier; + trap->FX_AddPrimitive = trap_FX_AddPrimitive; + trap->FX_AddSprite = trap_FX_AddSprite; + trap->FX_AddElectricity = trap_FX_AddElectricity; + trap->SE_GetStringTextString = trap_SE_GetStringTextString; + trap->ROFF_Clean = trap_ROFF_Clean; + trap->ROFF_UpdateEntities = trap_ROFF_UpdateEntities; + trap->ROFF_Cache = trap_ROFF_Cache; + trap->ROFF_Play = trap_ROFF_Play; + trap->ROFF_Purge_Ent = trap_ROFF_Purge_Ent; + trap->G2_ListModelSurfaces = trap_G2_ListModelSurfaces; + trap->G2_ListModelBones = trap_G2_ListModelBones; + trap->G2_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; + trap->G2_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; + trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; + trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; + trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; + trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; + trap->G2API_SetSkin = trap_G2API_SetSkin; + trap->G2API_CollisionDetect = CGSyscall_G2API_CollisionDetect; + trap->G2API_CollisionDetectCache = CGSyscall_G2API_CollisionDetect; + trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; + trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; + trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; + trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; + trap->G2API_GetBoneFrame = trap_G2API_GetBoneFrame; + trap->G2API_GetGLAName = trap_G2API_GetGLAName; + trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; + trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; + trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; + trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; + trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; + trap->G2API_SkinlessModel = trap_G2API_SkinlessModel; + trap->G2API_GetNumGoreMarks = trap_G2API_GetNumGoreMarks; + trap->G2API_AddSkinGore = trap_G2API_AddSkinGore; + trap->G2API_ClearSkinGore = trap_G2API_ClearSkinGore; + trap->G2API_Ghoul2Size = trap_G2API_Ghoul2Size; + trap->G2API_AddBolt = trap_G2API_AddBolt; + trap->G2API_AttachEnt = trap_G2API_AttachEnt; + trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; + trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; + trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; + trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; + trap->G2API_DoesBoneExist = trap_G2API_DoesBoneExist; + trap->G2API_GetSurfaceRenderStatus = trap_G2API_GetSurfaceRenderStatus; + trap->G2API_GetTime = trap_G2API_GetTime; + trap->G2API_SetTime = trap_G2API_SetTime; + trap->G2API_AbsurdSmoothing = trap_G2API_AbsurdSmoothing; + trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; + trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; + trap->G2API_RagPCJConstraint = trap_G2API_RagPCJConstraint; + trap->G2API_RagPCJGradientSpeed = trap_G2API_RagPCJGradientSpeed; + trap->G2API_RagEffectorGoal = trap_G2API_RagEffectorGoal; + trap->G2API_GetRagBonePos = trap_G2API_GetRagBonePos; + trap->G2API_RagEffectorKick = trap_G2API_RagEffectorKick; + trap->G2API_RagForceSolve = trap_G2API_RagForceSolve; + trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; + trap->G2API_IKMove = trap_G2API_IKMove; + trap->G2API_RemoveBone = trap_G2API_RemoveBone; + trap->G2API_AttachInstanceToEntNum = trap_G2API_AttachInstanceToEntNum; + trap->G2API_ClearAttachedInstance = trap_G2API_ClearAttachedInstance; + trap->G2API_CleanEntAttachments = trap_G2API_CleanEntAttachments; + trap->G2API_OverrideServer = trap_G2API_OverrideServer; + trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; - trap->ext.R_Font_StrLenPixels = trap_R_Font_StrLenPixelsFloat; + trap->ext.R_Font_StrLenPixels = trap_R_Font_StrLenPixelsFloat; } diff --git a/codemp/cgame/cg_turret.c b/codemp/cgame/cg_turret.c index 906cdb4455..dd44c09a5f 100644 --- a/codemp/cgame/cg_turret.c +++ b/codemp/cgame/cg_turret.c @@ -24,10 +24,9 @@ along with this program; if not, see . #include "qcommon/q_shared.h" #include "ghoul2/G2.h" -//rww - The turret is heavily dependant on bone angles. We can't happily set that on the server, so it is done client-only. +// rww - The turret is heavily dependant on bone angles. We can't happily set that on the server, so it is done client-only. -void CreepToPosition(vec3_t ideal, vec3_t current) -{ +void CreepToPosition(vec3_t ideal, vec3_t current) { float max_degree_switch = 90; int degrees_negative = 0; int degrees_positive = 0; @@ -39,55 +38,43 @@ void CreepToPosition(vec3_t ideal, vec3_t current) angle_ideal = (int)ideal[YAW]; angle_current = (int)current[YAW]; - if (angle_ideal <= angle_current) - { + if (angle_ideal <= angle_current) { degrees_negative = (angle_current - angle_ideal); degrees_positive = (360 - angle_current) + angle_ideal; - } - else - { + } else { degrees_negative = angle_current + (360 - angle_ideal); degrees_positive = (angle_ideal - angle_current); } - if (degrees_negative < degrees_positive) - { + if (degrees_negative < degrees_positive) { doNegative = 1; } - if (doNegative) - { + if (doNegative) { current[YAW] -= max_degree_switch; - if (current[YAW] < ideal[YAW] && (current[YAW]+(max_degree_switch*2)) >= ideal[YAW]) - { + if (current[YAW] < ideal[YAW] && (current[YAW] + (max_degree_switch * 2)) >= ideal[YAW]) { current[YAW] = ideal[YAW]; } - if (current[YAW] < 0) - { + if (current[YAW] < 0) { current[YAW] += 361; } - } - else - { + } else { current[YAW] += max_degree_switch; - if (current[YAW] > ideal[YAW] && (current[YAW]-(max_degree_switch*2)) <= ideal[YAW]) - { + if (current[YAW] > ideal[YAW] && (current[YAW] - (max_degree_switch * 2)) <= ideal[YAW]) { current[YAW] = ideal[YAW]; } - if (current[YAW] > 360) - { + if (current[YAW] > 360) { current[YAW] -= 361; } } - if (ideal[PITCH] < 0) - { + if (ideal[PITCH] < 0) { ideal[PITCH] += 360; } @@ -96,74 +83,60 @@ void CreepToPosition(vec3_t ideal, vec3_t current) doNegative = 0; - if (angle_ideal <= angle_current) - { + if (angle_ideal <= angle_current) { degrees_negative = (angle_current - angle_ideal); degrees_positive = (360 - angle_current) + angle_ideal; - } - else - { + } else { degrees_negative = angle_current + (360 - angle_ideal); degrees_positive = (angle_ideal - angle_current); } - if (degrees_negative < degrees_positive) - { + if (degrees_negative < degrees_positive) { doNegative = 1; } - if (doNegative) - { + if (doNegative) { current[PITCH] -= max_degree_switch; - if (current[PITCH] < ideal[PITCH] && (current[PITCH]+(max_degree_switch*2)) >= ideal[PITCH]) - { + if (current[PITCH] < ideal[PITCH] && (current[PITCH] + (max_degree_switch * 2)) >= ideal[PITCH]) { current[PITCH] = ideal[PITCH]; } - if (current[PITCH] < 0) - { + if (current[PITCH] < 0) { current[PITCH] += 361; } - } - else - { + } else { current[PITCH] += max_degree_switch; - if (current[PITCH] > ideal[PITCH] && (current[PITCH]-(max_degree_switch*2)) <= ideal[PITCH]) - { + if (current[PITCH] > ideal[PITCH] && (current[PITCH] - (max_degree_switch * 2)) <= ideal[PITCH]) { current[PITCH] = ideal[PITCH]; } - if (current[PITCH] > 360) - { + if (current[PITCH] > 360) { current[PITCH] -= 361; } } } -void TurretClientRun(centity_t *ent) -{ - if (!ent->ghoul2) - { - weaponInfo_t *weaponInfo; +void TurretClientRun(centity_t *ent) { + if (!ent->ghoul2) { + weaponInfo_t *weaponInfo; - trap->G2API_InitGhoul2Model(&ent->ghoul2, CG_ConfigString( CS_MODELS+ent->currentState.modelindex ), 0, 0, 0, 0, 0); + trap->G2API_InitGhoul2Model(&ent->ghoul2, CG_ConfigString(CS_MODELS + ent->currentState.modelindex), 0, 0, 0, 0, 0); - if (!ent->ghoul2) - { //bad + if (!ent->ghoul2) { // bad return; } - ent->torsoBolt = trap->G2API_AddBolt( ent->ghoul2, 0, "*flash02" ); + ent->torsoBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*flash02"); - trap->G2API_SetBoneAngles( ent->ghoul2, 0, "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time ); - trap->G2API_SetBoneAngles( ent->ghoul2, 0, "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time ); - trap->G2API_SetBoneAngles( ent->ghoul2, 0, "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time ); + trap->G2API_SetBoneAngles(ent->ghoul2, 0, "bone_hinge", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time); + trap->G2API_SetBoneAngles(ent->ghoul2, 0, "bone_gback", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time); + trap->G2API_SetBoneAngles(ent->ghoul2, 0, "bone_barrel", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL, 100, cg.time); - trap->G2API_SetBoneAnim( ent->ghoul2, 0, "model_root", 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, 0, 0 ); + trap->G2API_SetBoneAnim(ent->ghoul2, 0, "model_root", 0, 11, BONE_ANIM_OVERRIDE_FREEZE, 0.8f, cg.time, 0, 0); ent->turAngles[ROLL] = 0; ent->turAngles[PITCH] = 90; @@ -171,41 +144,34 @@ void TurretClientRun(centity_t *ent) weaponInfo = &cg_weapons[WP_TURRET]; - if ( !weaponInfo->registered ) - { + if (!weaponInfo->registered) { CG_RegisterWeapon(WP_TURRET); } } - if (ent->currentState.fireflag == 2) - { //I'm about to blow - trap->G2API_SetBoneAngles( ent->ghoul2, 0, "bone_hinge", ent->turAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_Z, NEGATIVE_X, NULL, 100, cg.time ); + if (ent->currentState.fireflag == 2) { // I'm about to blow + trap->G2API_SetBoneAngles(ent->ghoul2, 0, "bone_hinge", ent->turAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_Z, NEGATIVE_X, NULL, 100, cg.time); return; - } - else if (ent->currentState.fireflag && ent->bolt4 != ent->currentState.fireflag) - { + } else if (ent->currentState.fireflag && ent->bolt4 != ent->currentState.fireflag) { vec3_t muzzleOrg, muzzleDir; mdxaBone_t boltMatrix; - trap->G2API_GetBoltMatrix(ent->ghoul2, 0, ent->torsoBolt, &boltMatrix, /*ent->lerpAngles*/vec3_origin, ent->lerpOrigin, cg.time, cgs.gameModels, ent->modelScale); + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, ent->torsoBolt, &boltMatrix, /*ent->lerpAngles*/ vec3_origin, ent->lerpOrigin, cg.time, cgs.gameModels, + ent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzleOrg); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, muzzleDir); trap->FX_PlayEffectID(cgs.effects.mTurretMuzzleFlash, muzzleOrg, muzzleDir, -1, -1, qfalse); ent->bolt4 = ent->currentState.fireflag; - } - else if (!ent->currentState.fireflag) - { + } else if (!ent->currentState.fireflag) { ent->bolt4 = 0; } - if (ent->currentState.bolt2 != ENTITYNUM_NONE) - { //turn toward the enemy + if (ent->currentState.bolt2 != ENTITYNUM_NONE) { // turn toward the enemy centity_t *enemy = &cg_entities[ent->currentState.bolt2]; - if (enemy) - { + if (enemy) { vec3_t enAng; vec3_t enPos; @@ -219,26 +185,21 @@ void TurretClientRun(centity_t *ent) CreepToPosition(enAng, ent->turAngles); } - } - else - { + } else { vec3_t idleAng; float turnAmount; - if (ent->turAngles[YAW] > 360) - { + if (ent->turAngles[YAW] > 360) { ent->turAngles[YAW] -= 361; } - if (!ent->dustTrailTime) - { + if (!ent->dustTrailTime) { ent->dustTrailTime = cg.time; } - turnAmount = (cg.time-ent->dustTrailTime)*0.03; + turnAmount = (cg.time - ent->dustTrailTime) * 0.03; - if (turnAmount > 360) - { + if (turnAmount > 360) { turnAmount = 360; } @@ -250,12 +211,11 @@ void TurretClientRun(centity_t *ent) CreepToPosition(idleAng, ent->turAngles); } - if (cg.time < ent->frame_minus1_refreshed) - { + if (cg.time < ent->frame_minus1_refreshed) { ent->frame_minus1_refreshed = cg.time; return; } ent->frame_minus1_refreshed = cg.time; - trap->G2API_SetBoneAngles( ent->ghoul2, 0, "bone_hinge", ent->turAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_Z, NEGATIVE_X, NULL, 100, cg.time ); + trap->G2API_SetBoneAngles(ent->ghoul2, 0, "bone_hinge", ent->turAngles, BONE_ANGLES_REPLACE, NEGATIVE_Y, NEGATIVE_Z, NEGATIVE_X, NULL, 100, cg.time); } diff --git a/codemp/cgame/cg_view.c b/codemp/cgame/cg_view.c index 228024c2c5..dc65cdab76 100644 --- a/codemp/cgame/cg_view.c +++ b/codemp/cgame/cg_view.c @@ -26,9 +26,8 @@ along with this program; if not, see . #include "cg_local.h" #include "game/bg_saga.h" -#define MASK_CAMERACLIP (MASK_SOLID|CONTENTS_PLAYERCLIP) -#define CAMERA_SIZE 4 - +#define MASK_CAMERACLIP (MASK_SOLID | CONTENTS_PLAYERCLIP) +#define CAMERA_SIZE 4 /* ============================================================================= @@ -73,34 +72,34 @@ Creates an entity in front of the current position, which can then be moved around ================= */ -void CG_TestModel_f (void) { - vec3_t angles; +void CG_TestModel_f(void) { + vec3_t angles; - memset( &cg.testModelEntity, 0, sizeof(cg.testModelEntity) ); - if ( trap->Cmd_Argc() < 2 ) { + memset(&cg.testModelEntity, 0, sizeof(cg.testModelEntity)); + if (trap->Cmd_Argc() < 2) { return; } - Q_strncpyz (cg.testModelName, CG_Argv( 1 ), MAX_QPATH ); - cg.testModelEntity.hModel = trap->R_RegisterModel( cg.testModelName ); + Q_strncpyz(cg.testModelName, CG_Argv(1), MAX_QPATH); + cg.testModelEntity.hModel = trap->R_RegisterModel(cg.testModelName); - if ( trap->Cmd_Argc() == 3 ) { - cg.testModelEntity.backlerp = atof( CG_Argv( 2 ) ); + if (trap->Cmd_Argc() == 3) { + cg.testModelEntity.backlerp = atof(CG_Argv(2)); cg.testModelEntity.frame = 1; cg.testModelEntity.oldframe = 0; } - if (! cg.testModelEntity.hModel ) { - trap->Print( "Can't register model\n" ); + if (!cg.testModelEntity.hModel) { + trap->Print("Can't register model\n"); return; } - VectorMA( cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin ); + VectorMA(cg.refdef.vieworg, 100, cg.refdef.viewaxis[0], cg.testModelEntity.origin); angles[PITCH] = 0; angles[YAW] = 180 + cg.refdef.viewangles[1]; angles[ROLL] = 0; - AnglesToAxis( angles, cg.testModelEntity.axis ); + AnglesToAxis(angles, cg.testModelEntity.axis); cg.testGun = qfalse; } @@ -111,75 +110,71 @@ CG_TestGun_f Replaces the current view weapon with the given model ================= */ -void CG_TestGun_f (void) { +void CG_TestGun_f(void) { CG_TestModel_f(); cg.testGun = qtrue; - //cg.testModelEntity.renderfx = RF_MINLIGHT | RF_DEPTHHACK | RF_FIRST_PERSON; + // cg.testModelEntity.renderfx = RF_MINLIGHT | RF_DEPTHHACK | RF_FIRST_PERSON; // rww - 9-13-01 [1-26-01-sof2] cg.testModelEntity.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON; } - -void CG_TestModelNextFrame_f (void) { +void CG_TestModelNextFrame_f(void) { cg.testModelEntity.frame++; - trap->Print( "frame %i\n", cg.testModelEntity.frame ); + trap->Print("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelPrevFrame_f (void) { +void CG_TestModelPrevFrame_f(void) { cg.testModelEntity.frame--; - if ( cg.testModelEntity.frame < 0 ) { + if (cg.testModelEntity.frame < 0) { cg.testModelEntity.frame = 0; } - trap->Print( "frame %i\n", cg.testModelEntity.frame ); + trap->Print("frame %i\n", cg.testModelEntity.frame); } -void CG_TestModelNextSkin_f (void) { +void CG_TestModelNextSkin_f(void) { cg.testModelEntity.skinNum++; - trap->Print( "skin %i\n", cg.testModelEntity.skinNum ); + trap->Print("skin %i\n", cg.testModelEntity.skinNum); } -void CG_TestModelPrevSkin_f (void) { +void CG_TestModelPrevSkin_f(void) { cg.testModelEntity.skinNum--; - if ( cg.testModelEntity.skinNum < 0 ) { + if (cg.testModelEntity.skinNum < 0) { cg.testModelEntity.skinNum = 0; } - trap->Print( "skin %i\n", cg.testModelEntity.skinNum ); + trap->Print("skin %i\n", cg.testModelEntity.skinNum); } -static void CG_AddTestModel (void) { - int i; +static void CG_AddTestModel(void) { + int i; // re-register the model, because the level may have changed - cg.testModelEntity.hModel = trap->R_RegisterModel( cg.testModelName ); - if (! cg.testModelEntity.hModel ) { - trap->Print ("Can't register model\n"); + cg.testModelEntity.hModel = trap->R_RegisterModel(cg.testModelName); + if (!cg.testModelEntity.hModel) { + trap->Print("Can't register model\n"); return; } // if testing a gun, set the origin reletive to the view origin - if ( cg.testGun ) { - VectorCopy( cg.refdef.vieworg, cg.testModelEntity.origin ); - VectorCopy( cg.refdef.viewaxis[0], cg.testModelEntity.axis[0] ); - VectorCopy( cg.refdef.viewaxis[1], cg.testModelEntity.axis[1] ); - VectorCopy( cg.refdef.viewaxis[2], cg.testModelEntity.axis[2] ); + if (cg.testGun) { + VectorCopy(cg.refdef.vieworg, cg.testModelEntity.origin); + VectorCopy(cg.refdef.viewaxis[0], cg.testModelEntity.axis[0]); + VectorCopy(cg.refdef.viewaxis[1], cg.testModelEntity.axis[1]); + VectorCopy(cg.refdef.viewaxis[2], cg.testModelEntity.axis[2]); // allow the position to be adjusted - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { cg.testModelEntity.origin[i] += cg.refdef.viewaxis[0][i] * cg_gunX.value; cg.testModelEntity.origin[i] += cg.refdef.viewaxis[1][i] * cg_gunY.value; cg.testModelEntity.origin[i] += cg.refdef.viewaxis[2][i] * cg_gunZ.value; } } - trap->R_AddRefEntityToScene( &cg.testModelEntity ); + trap->R_AddRefEntityToScene(&cg.testModelEntity); } - - //============================================================================ - /* ================= CG_CalcVrect @@ -187,35 +182,34 @@ CG_CalcVrect Sets the coordinates of the rendered window ================= */ -static void CG_CalcVrect (void) { - int size; +static void CG_CalcVrect(void) { + int size; // the intermission should allways be full screen - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { + if (cg.snap->ps.pm_type == PM_INTERMISSION) { size = 100; } else { // bound normal viewsize - if ( cg_viewsize.integer < 30 ) { - trap->Cvar_Set( "cg_viewsize", "30" ); - trap->Cvar_Update( &cg_viewsize ); + if (cg_viewsize.integer < 30) { + trap->Cvar_Set("cg_viewsize", "30"); + trap->Cvar_Update(&cg_viewsize); size = 30; - } else if ( cg_viewsize.integer > 100 ) { - trap->Cvar_Set( "cg_viewsize", "100" ); - trap->Cvar_Update( &cg_viewsize ); + } else if (cg_viewsize.integer > 100) { + trap->Cvar_Set("cg_viewsize", "100"); + trap->Cvar_Update(&cg_viewsize); size = 100; } else { size = cg_viewsize.integer; } - } - cg.refdef.width = cgs.glconfig.vidWidth*size/100; + cg.refdef.width = cgs.glconfig.vidWidth * size / 100; cg.refdef.width &= ~1; - cg.refdef.height = cgs.glconfig.vidHeight*size/100; + cg.refdef.height = cgs.glconfig.vidHeight * size / 100; cg.refdef.height &= ~1; - cg.refdef.x = (cgs.glconfig.vidWidth - cg.refdef.width)/2; - cg.refdef.y = (cgs.glconfig.vidHeight - cg.refdef.height)/2; + cg.refdef.x = (cgs.glconfig.vidWidth - cg.refdef.width) / 2; + cg.refdef.y = (cgs.glconfig.vidHeight - cg.refdef.height) / 2; } //============================================================================== @@ -223,31 +217,30 @@ static void CG_CalcVrect (void) { //============================================================================== //============================================================================== // this causes a compiler bug on mac MrC compiler -static void CG_StepOffset( void ) { - int timeDelta; +static void CG_StepOffset(void) { + int timeDelta; // smooth out stair climbing timeDelta = cg.time - cg.stepTime; - if ( timeDelta < STEP_TIME ) { - cg.refdef.vieworg[2] -= cg.stepChange - * (STEP_TIME - timeDelta) / STEP_TIME; + if (timeDelta < STEP_TIME) { + cg.refdef.vieworg[2] -= cg.stepChange * (STEP_TIME - timeDelta) / STEP_TIME; } } -#define CAMERA_DAMP_INTERVAL 50 +#define CAMERA_DAMP_INTERVAL 50 -static vec3_t cameramins = { -CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE }; -static vec3_t cameramaxs = { CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE }; -vec3_t camerafwd, cameraup; +static vec3_t cameramins = {-CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE}; +static vec3_t cameramaxs = {CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE}; +vec3_t camerafwd, cameraup; -vec3_t cameraFocusAngles, cameraFocusLoc; -vec3_t cameraIdealTarget, cameraIdealLoc; -vec3_t cameraCurTarget={0,0,0}, cameraCurLoc={0,0,0}; -vec3_t cameraOldLoc={0,0,0}, cameraNewLoc={0,0,0}; -int cameraLastFrame=0; +vec3_t cameraFocusAngles, cameraFocusLoc; +vec3_t cameraIdealTarget, cameraIdealLoc; +vec3_t cameraCurTarget = {0, 0, 0}, cameraCurLoc = {0, 0, 0}; +vec3_t cameraOldLoc = {0, 0, 0}, cameraNewLoc = {0, 0, 0}; +int cameraLastFrame = 0; -float cameraLastYaw=0; -float cameraStiffFactor=0.0f; +float cameraLastYaw = 0; +float cameraStiffFactor = 0.0f; /* =============== @@ -272,15 +265,11 @@ CG_CalcTargetThirdPersonViewLocation =============== */ -static void CG_CalcIdealThirdPersonViewTarget(void) -{ +static void CG_CalcIdealThirdPersonViewTarget(void) { // Initialize IdealTarget - if (gCGHasFallVector) - { + if (gCGHasFallVector) { VectorCopy(gCGFallVector, cameraFocusLoc); - } - else - { + } else { VectorCopy(cg.refdef.vieworg, cameraFocusLoc); } @@ -288,111 +277,79 @@ static void CG_CalcIdealThirdPersonViewTarget(void) cameraFocusLoc[2] += cg.snap->ps.viewheight; // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. -// VectorMA(cameraFocusLoc, thirdPersonVertOffset, cameraup, cameraIdealTarget); + // VectorMA(cameraFocusLoc, thirdPersonVertOffset, cameraup, cameraIdealTarget); // Add in a vertical offset from the viewpoint, which puts the actual target above the head, regardless of angle. - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); { float vertOffset = cg_thirdPersonVertOffset.value; - if (cg.snap && cg.snap->ps.m_iVehicleNum) - { + if (cg.snap && cg.snap->ps.m_iVehicleNum) { centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->cameraOverride) - { //override the range with what the vehicle wants it to be - if ( veh->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset ) - { - if ( cg.snap->ps.viewangles[PITCH] > 0 ) - { - vertOffset = 130+cg.predictedPlayerState.viewangles[PITCH]*-10; - if ( vertOffset < -170 ) - { + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->cameraOverride) { // override the range with what the vehicle wants it to be + if (veh->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset) { + if (cg.snap->ps.viewangles[PITCH] > 0) { + vertOffset = 130 + cg.predictedPlayerState.viewangles[PITCH] * -10; + if (vertOffset < -170) { vertOffset = -170; } - } - else if ( cg.snap->ps.viewangles[PITCH] < 0 ) - { - vertOffset = 130+cg.predictedPlayerState.viewangles[PITCH]*-5; - if ( vertOffset > 130 ) - { + } else if (cg.snap->ps.viewangles[PITCH] < 0) { + vertOffset = 130 + cg.predictedPlayerState.viewangles[PITCH] * -5; + if (vertOffset > 130) { vertOffset = 130; } - } - else - { + } else { vertOffset = 30; } - } - else - { + } else { vertOffset = veh->m_pVehicle->m_pVehicleInfo->cameraVertOffset; } - } - else if ( veh->m_pVehicle - && veh->m_pVehicle->m_pVehicleInfo - && veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + } else if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { vertOffset = 0; } } cameraIdealTarget[2] += vertOffset; } - //VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); + // VectorMA(cameraFocusLoc, cg_thirdPersonVertOffset.value, cameraup, cameraIdealTarget); } - - /* =============== CG_CalcTargetThirdPersonViewLocation =============== */ -static void CG_CalcIdealThirdPersonViewLocation(void) -{ +static void CG_CalcIdealThirdPersonViewLocation(void) { float thirdPersonRange = cg_thirdPersonRange.value; - if (cg.snap && cg.snap->ps.m_iVehicleNum) - { + if (cg.snap && cg.snap->ps.m_iVehicleNum) { centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->cameraOverride) - { //override the range with what the vehicle wants it to be + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->cameraOverride) { // override the range with what the vehicle wants it to be thirdPersonRange = veh->m_pVehicle->m_pVehicleInfo->cameraRange; - if ( veh->playerState->hackingTime ) - { - thirdPersonRange += fabs(((float)veh->playerState->hackingTime)/MAX_STRAFE_TIME) * 100.0f; + if (veh->playerState->hackingTime) { + thirdPersonRange += fabs(((float)veh->playerState->hackingTime) / MAX_STRAFE_TIME) * 100.0f; } } } - if ( cg.snap - && (cg.snap->ps.eFlags2&EF2_HELD_BY_MONSTER) - && cg.snap->ps.hasLookTarget - && cg_entities[cg.snap->ps.lookTarget].currentState.NPC_class == CLASS_RANCOR )//only possibility for now, may add Wampa and sand creature later - {//stay back - //thirdPersonRange = 180.0f; + if (cg.snap && (cg.snap->ps.eFlags2 & EF2_HELD_BY_MONSTER) && cg.snap->ps.hasLookTarget && + cg_entities[cg.snap->ps.lookTarget].currentState.NPC_class == CLASS_RANCOR) // only possibility for now, may add Wampa and sand creature later + { // stay back + // thirdPersonRange = 180.0f; thirdPersonRange = 120.0f; } VectorMA(cameraIdealTarget, -(thirdPersonRange), camerafwd, cameraIdealLoc); } - - -static void CG_ResetThirdPersonViewDamp(void) -{ +static void CG_ResetThirdPersonViewDamp(void) { trace_t trace; // Cap the pitch within reasonable limits - if (cameraFocusAngles[PITCH] > 89.0) - { + if (cameraFocusAngles[PITCH] > 89.0) { cameraFocusAngles[PITCH] = 89.0; - } - else if (cameraFocusAngles[PITCH] < -89.0) - { + } else if (cameraFocusAngles[PITCH] < -89.0) { cameraFocusAngles[PITCH] = -89.0; } @@ -410,15 +367,13 @@ static void CG_ResetThirdPersonViewDamp(void) // First thing we do is trace from the first person viewpoint out to the new target location. CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.snap->ps.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } // Now we trace from the new target location to the new view location, to make sure there is nothing in the way. CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.snap->ps.clientNum, MASK_CAMERACLIP); - if (trace.fraction <= 1.0) - { + if (trace.fraction <= 1.0) { VectorCopy(trace.endpos, cameraCurLoc); } @@ -428,41 +383,34 @@ static void CG_ResetThirdPersonViewDamp(void) } // This is called every frame. -static void CG_UpdateThirdPersonTargetDamp(void) -{ +static void CG_UpdateThirdPersonTargetDamp(void) { trace_t trace; - vec3_t targetdiff; - float dampfactor, dtime, ratio; + vec3_t targetdiff; + float dampfactor, dtime, ratio; // Set the cameraIdealTarget // Automatically get the ideal target, to avoid jittering. CG_CalcIdealThirdPersonViewTarget(); - if ( cg.predictedVehicleState.hyperSpaceTime - && (cg.time-cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME ) - {//hyperspacing, no damp + if (cg.predictedVehicleState.hyperSpaceTime && (cg.time - cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME) { // hyperspacing, no damp VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=1.0||cg.thisFrameTeleport||cg.predictedPlayerState.m_iVehicleNum) - { // No damping. + } else if (cg_thirdPersonTargetDamp.value >= 1.0 || cg.thisFrameTeleport || cg.predictedPlayerState.m_iVehicleNum) { // No damping. VectorCopy(cameraIdealTarget, cameraCurTarget); - } - else if (cg_thirdPersonTargetDamp.value>=0.0) - { + } else if (cg_thirdPersonTargetDamp.value >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealTarget, cameraCurTarget, targetdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - cg_thirdPersonTargetDamp.value; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. - if ( cg_smoothCamera.integer ) + if (cg_smoothCamera.integer) ratio = powf(dampfactor, dtime); else - ratio = Q_powf( dampfactor, dtime ); + ratio = Q_powf(dampfactor, dtime); // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealTarget, -ratio, targetdiff, cameraCurTarget); @@ -473,8 +421,7 @@ static void CG_UpdateThirdPersonTargetDamp(void) // First thing we do is trace from the first person viewpoint out to the new target location. CG_Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, cg.snap->ps.clientNum, MASK_CAMERACLIP); - if (trace.fraction < 1.0) - { + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } @@ -485,35 +432,26 @@ static void CG_UpdateThirdPersonTargetDamp(void) } // This can be called every interval, at the user's discretion. -extern void CG_CalcEntityLerpPositions( centity_t *cent ); //cg_ents.c -static void CG_UpdateThirdPersonCameraDamp(void) -{ +extern void CG_CalcEntityLerpPositions(centity_t *cent); // cg_ents.c +static void CG_UpdateThirdPersonCameraDamp(void) { trace_t trace; - vec3_t locdiff; + vec3_t locdiff; float dampfactor, dtime, ratio; // Set the cameraIdealLoc CG_CalcIdealThirdPersonViewLocation(); - // First thing we do is calculate the appropriate damping factor for the camera. - dampfactor=0.0; - if ( cg.predictedVehicleState.hyperSpaceTime - && (cg.time-cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME ) - {//hyperspacing - don't damp camera + dampfactor = 0.0; + if (cg.predictedVehicleState.hyperSpaceTime && (cg.time - cg.predictedVehicleState.hyperSpaceTime) < HYPERSPACE_TIME) { // hyperspacing - don't damp camera dampfactor = 1.0f; - } - else if (cg_thirdPersonCameraDamp.value != 0.0) - { + } else if (cg_thirdPersonCameraDamp.value != 0.0) { float pitch; float dFactor; - if (!cg.predictedPlayerState.m_iVehicleNum) - { + if (!cg.predictedPlayerState.m_iVehicleNum) { dFactor = cg_thirdPersonCameraDamp.value; - } - else - { + } else { dFactor = 1.0f; } @@ -522,37 +460,34 @@ static void CG_UpdateThirdPersonCameraDamp(void) // The higher the pitch, the larger the factor, so as you look up, it damps a lot less. pitch /= 115.0; - dampfactor = (1.0-dFactor)*(pitch*pitch); + dampfactor = (1.0 - dFactor) * (pitch * pitch); dampfactor += dFactor; // Now we also multiply in the stiff factor, so that faster yaw changes are stiffer. - if (cameraStiffFactor > 0.0f) - { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. - dampfactor += (1.0-dampfactor)*cameraStiffFactor; + if (cameraStiffFactor > + 0.0f) { // The cameraStiffFactor is how much of the remaining damp below 1 should be shaved off, i.e. approach 1 as stiffening increases. + dampfactor += (1.0 - dampfactor) * cameraStiffFactor; } } - if (dampfactor>=1.0||cg.thisFrameTeleport) - { // No damping. + if (dampfactor >= 1.0 || cg.thisFrameTeleport) { // No damping. VectorCopy(cameraIdealLoc, cameraCurLoc); - } - else if (dampfactor>=0.0) - { + } else if (dampfactor >= 0.0) { // Calculate the difference from the current position to the new one. VectorSubtract(cameraIdealLoc, cameraCurLoc, locdiff); // Now we calculate how much of the difference we cover in the time allotted. // The equation is (Damp)^(time) - dampfactor = 1.0-dampfactor; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(cg.time-cameraLastFrame) * (1.0/(float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - dampfactor; // We must exponent the amount LEFT rather than the amount bled off + dtime = (float)(cg.time - cameraLastFrame) * (1.0 / (float)CAMERA_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. - if ( cg_smoothCamera.integer ) + if (cg_smoothCamera.integer) ratio = powf(dampfactor, dtime); else - ratio = Q_powf( dampfactor, dtime ); + ratio = Q_powf(dampfactor, dtime); // This value is how much distance is "left" from the ideal. VectorMA(cameraIdealLoc, -ratio, locdiff, cameraCurLoc); @@ -562,48 +497,40 @@ static void CG_UpdateThirdPersonCameraDamp(void) // Now we trace from the new target location to the new view location, to make sure there is nothing in the way. CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.snap->ps.clientNum, MASK_CAMERACLIP); - if (trace.fraction < 1.0) - { - if (trace.entityNum < ENTITYNUM_WORLD && - cg_entities[trace.entityNum].currentState.solid == SOLID_BMODEL && - cg_entities[trace.entityNum].currentState.eType == ET_MOVER) - { //get a different position for movers -rww + if (trace.fraction < 1.0) { + if (trace.entityNum < ENTITYNUM_WORLD && cg_entities[trace.entityNum].currentState.solid == SOLID_BMODEL && + cg_entities[trace.entityNum].currentState.eType == ET_MOVER) { // get a different position for movers -rww centity_t *mover = &cg_entities[trace.entityNum]; - //this is absolutely hackiful, since we calc view values before we add packet ents and lerp, - //if we hit a mover we want to update its lerp pos and force it when we do the trace against - //it. - if (mover->currentState.pos.trType != TR_STATIONARY && - mover->currentState.pos.trType != TR_LINEAR) - { + // this is absolutely hackiful, since we calc view values before we add packet ents and lerp, + // if we hit a mover we want to update its lerp pos and force it when we do the trace against + // it. + if (mover->currentState.pos.trType != TR_STATIONARY && mover->currentState.pos.trType != TR_LINEAR) { int curTr = mover->currentState.pos.trType; vec3_t curTrB; VectorCopy(mover->currentState.pos.trBase, curTrB); - //calc lerporigin for this client frame + // calc lerporigin for this client frame CG_CalcEntityLerpPositions(mover); - //force the calc'd lerp to be the base and say we are stationary so we don't try to extrapolate - //out further. + // force the calc'd lerp to be the base and say we are stationary so we don't try to extrapolate + // out further. mover->currentState.pos.trType = TR_STATIONARY; VectorCopy(mover->lerpOrigin, mover->currentState.pos.trBase); - //retrace + // retrace CG_Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, cg.snap->ps.clientNum, MASK_CAMERACLIP); - //copy old data back in - mover->currentState.pos.trType = (trType_t) curTr; + // copy old data back in + mover->currentState.pos.trType = (trType_t)curTr; VectorCopy(curTrB, mover->currentState.pos.trBase); } - if (trace.fraction < 1.0f) - { //still hit it, so take the proper trace endpos and use that. + if (trace.fraction < 1.0f) { // still hit it, so take the proper trace endpos and use that. VectorCopy(trace.endpos, cameraCurLoc); } - } - else - { - VectorCopy( trace.endpos, cameraCurLoc ); + } else { + VectorCopy(trace.endpos, cameraCurLoc); } } @@ -613,9 +540,6 @@ static void CG_UpdateThirdPersonCameraDamp(void) // however two full volume traces each frame is a bit scary to think about. } - - - /* ===============` CG_OffsetThirdPersonView @@ -623,23 +547,18 @@ CG_OffsetThirdPersonView =============== */ extern vmCvar_t cg_thirdPersonHorzOffset; -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); -static void CG_OffsetThirdPersonView( void ) -{ +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); +static void CG_OffsetThirdPersonView(void) { vec3_t diff; float thirdPersonHorzOffset = cg_thirdPersonHorzOffset.value; float deltayaw; - if (cg.snap && cg.snap->ps.m_iVehicleNum) - { + if (cg.snap && cg.snap->ps.m_iVehicleNum) { centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->cameraOverride) - { //override the range with what the vehicle wants it to be + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->cameraOverride) { // override the range with what the vehicle wants it to be thirdPersonHorzOffset = veh->m_pVehicle->m_pVehicleInfo->cameraHorzOffset; - if ( veh->playerState->hackingTime ) - { - thirdPersonHorzOffset += (((float)veh->playerState->hackingTime)/MAX_STRAFE_TIME) * -80.0f; + if (veh->playerState->hackingTime) { + thirdPersonHorzOffset += (((float)veh->playerState->hackingTime) / MAX_STRAFE_TIME) * -80.0f; } } } @@ -647,63 +566,47 @@ static void CG_OffsetThirdPersonView( void ) cameraStiffFactor = 0.0; // Set camera viewing direction. - VectorCopy( cg.refdef.viewangles, cameraFocusAngles ); + VectorCopy(cg.refdef.viewangles, cameraFocusAngles); // if dead, look at killer - if ( cg.snap - && (cg.snap->ps.eFlags2&EF2_HELD_BY_MONSTER) - && cg.snap->ps.hasLookTarget - && cg_entities[cg.snap->ps.lookTarget].currentState.NPC_class == CLASS_RANCOR )//only possibility for now, may add Wampa and sand creature later - {//being held - //vec3_t monsterPos, dir2Me; - centity_t *monster = &cg_entities[cg.snap->ps.lookTarget]; - VectorSet( cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW]+180), 0 ); - //make the look angle the vector from his mouth to me + if (cg.snap && (cg.snap->ps.eFlags2 & EF2_HELD_BY_MONSTER) && cg.snap->ps.hasLookTarget && + cg_entities[cg.snap->ps.lookTarget].currentState.NPC_class == CLASS_RANCOR) // only possibility for now, may add Wampa and sand creature later + { // being held + // vec3_t monsterPos, dir2Me; + centity_t *monster = &cg_entities[cg.snap->ps.lookTarget]; + VectorSet(cameraFocusAngles, 0, AngleNormalize180(monster->lerpAngles[YAW] + 180), 0); + // make the look angle the vector from his mouth to me /* VectorCopy( monster->lerpOrigin, monsterPos ); monsterPos[2] = cg.snap->ps.origin[2]; VectorSubtract( monsterPos, cg.snap->ps.origin, dir2Me ); vectoangles( dir2Me, cameraFocusAngles ); */ - } - else if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + } else if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { cameraFocusAngles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW]; - } - else - { // Add in the third Person Angle. + } else { // Add in the third Person Angle. cameraFocusAngles[YAW] += cg_thirdPersonAngle.value; { float pitchOffset = cg_thirdPersonPitchOffset.value; - if (cg.snap && cg.snap->ps.m_iVehicleNum) - { + if (cg.snap && cg.snap->ps.m_iVehicleNum) { centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->cameraOverride) - { //override the range with what the vehicle wants it to be - if ( veh->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset ) - { - if ( cg.snap->ps.viewangles[PITCH] > 0 ) - { - pitchOffset = cg.predictedPlayerState.viewangles[PITCH]*-0.75; - } - else if ( cg.snap->ps.viewangles[PITCH] < 0 ) - { - pitchOffset = cg.predictedPlayerState.viewangles[PITCH]*-0.75; - } - else - { + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->cameraOverride) { // override the range with what the vehicle wants it to be + if (veh->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset) { + if (cg.snap->ps.viewangles[PITCH] > 0) { + pitchOffset = cg.predictedPlayerState.viewangles[PITCH] * -0.75; + } else if (cg.snap->ps.viewangles[PITCH] < 0) { + pitchOffset = cg.predictedPlayerState.viewangles[PITCH] * -0.75; + } else { pitchOffset = 0; } - } - else - { + } else { pitchOffset = veh->m_pVehicle->m_pVehicleInfo->cameraPitchOffset; } } } /*if ( 0 && cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without restriction + && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without + restriction { float pitchPerc = ((90.0f-fabs(cameraFocusAngles[ROLL]))/90.0f); cameraFocusAngles[PITCH] += pitchOffset*pitchPerc; @@ -717,35 +620,26 @@ static void CG_OffsetThirdPersonView( void ) } } else*/ - { - cameraFocusAngles[PITCH] += pitchOffset; - } + { cameraFocusAngles[PITCH] += pitchOffset; } } } // The next thing to do is to see if we need to calculate a new camera target location. // If we went back in time for some reason, or if we just started, reset the sample. - if (cameraLastFrame == 0 || cameraLastFrame > cg.time) - { + if (cameraLastFrame == 0 || cameraLastFrame > cg.time) { CG_ResetThirdPersonViewDamp(); - } - else - { + } else { // Cap the pitch within reasonable limits - if ( cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without restriction - {//no clamp on pitch - //FIXME: when pitch >= 90 or <= -90, camera rotates oddly... need to CrossProduct not just vectoangles - } - else - { - if (cameraFocusAngles[PITCH] > 80.0) - { + if (cg.predictedPlayerState.m_iVehicleNum // in a vehicle + && BG_UnrestrainedPitchRoll(&cg.predictedPlayerState, + cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle)) // can roll/pitch without restriction + { // no clamp on pitch + // FIXME: when pitch >= 90 or <= -90, camera rotates oddly... need to CrossProduct not just vectoangles + } else { + if (cameraFocusAngles[PITCH] > 80.0) { cameraFocusAngles[PITCH] = 80.0; - } - else if (cameraFocusAngles[PITCH] < -80.0) - { + } else if (cameraFocusAngles[PITCH] < -80.0) { cameraFocusAngles[PITCH] = -80.0; } } @@ -753,22 +647,16 @@ static void CG_OffsetThirdPersonView( void ) AngleVectors(cameraFocusAngles, camerafwd, NULL, cameraup); deltayaw = fabs(cameraFocusAngles[YAW] - cameraLastYaw); - if (deltayaw > 180.0f) - { // Normalize this angle so that it is between 0 and 180. + if (deltayaw > 180.0f) { // Normalize this angle so that it is between 0 and 180. deltayaw = fabs(deltayaw - 360.0f); } - cameraStiffFactor = deltayaw / (float)(cg.time-cameraLastFrame); - if (cameraStiffFactor < 1.0) - { + cameraStiffFactor = deltayaw / (float)(cg.time - cameraLastFrame); + if (cameraStiffFactor < 1.0) { cameraStiffFactor = 0.0; - } - else if (cameraStiffFactor > 2.5) - { + } else if (cameraStiffFactor > 2.5) { cameraStiffFactor = 0.75; - } - else - { // 1 to 2 scales from 0.0 to 0.5 - cameraStiffFactor = (cameraStiffFactor-1.0f)*0.5f; + } else { // 1 to 2 scales from 0.0 to 0.5 + cameraStiffFactor = (cameraStiffFactor - 1.0f) * 0.5f; } cameraLastYaw = cameraFocusAngles[YAW]; @@ -787,41 +675,35 @@ static void CG_OffsetThirdPersonView( void ) VectorSubtract(cameraCurTarget, cameraCurLoc, diff); { float dist = VectorNormalize(diff); - //under normal circumstances, should never be 0.00000 and so on. - if ( !dist || (diff[0] == 0 || diff[1] == 0) ) - {//must be hitting something, need some value to calc angles, so use cam forward - VectorCopy( camerafwd, diff ); + // under normal circumstances, should never be 0.00000 and so on. + if (!dist || (diff[0] == 0 || diff[1] == 0)) { // must be hitting something, need some value to calc angles, so use cam forward + VectorCopy(camerafwd, diff); } } /*if ( 0 && cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without restriction + && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without + restriction {//FIXME: this causes camera jerkiness, need to blend the roll? float sav_Roll = cg.refdef.viewangles[ROLL]; vectoangles(diff, cg.refdef.viewangles); cg.refdef.viewangles[ROLL] = sav_Roll; } else*/ - { - vectoangles(diff, cg.refdef.viewangles); - } + { vectoangles(diff, cg.refdef.viewangles); } // Temp: just move the camera to the side a bit - if ( thirdPersonHorzOffset != 0.0f ) - { - AnglesToAxis( cg.refdef.viewangles, cg.refdef.viewaxis ); - VectorMA( cameraCurLoc, thirdPersonHorzOffset, cg.refdef.viewaxis[1], cameraCurLoc ); + if (thirdPersonHorzOffset != 0.0f) { + AnglesToAxis(cg.refdef.viewangles, cg.refdef.viewaxis); + VectorMA(cameraCurLoc, thirdPersonHorzOffset, cg.refdef.viewaxis[1], cameraCurLoc); } // ...and of course we should copy the new view location to the proper spot too. VectorCopy(cameraCurLoc, cg.refdef.vieworg); - cameraLastFrame=cg.time; + cameraLastFrame = cg.time; } -void CG_GetVehicleCamPos( vec3_t camPos ) -{ - VectorCopy( cg.refdef.vieworg, camPos ); -} +void CG_GetVehicleCamPos(vec3_t camPos) { VectorCopy(cg.refdef.vieworg, camPos); } /* =============== @@ -920,19 +802,19 @@ CG_OffsetFirstPersonView =============== */ -static void CG_OffsetFirstPersonView( void ) { - float *origin; - float *angles; - float bob; - float ratio; - float delta; - float speed; - float f; - vec3_t predictedVelocity; - int timeDelta; - int kickTime; - - if ( cg.snap->ps.pm_type == PM_INTERMISSION ) { +static void CG_OffsetFirstPersonView(void) { + float *origin; + float *angles; + float bob; + float ratio; + float delta; + float speed; + float f; + vec3_t predictedVelocity; + int timeDelta; + int kickTime; + + if (cg.snap->ps.pm_type == PM_INTERMISSION) { return; } @@ -940,7 +822,7 @@ static void CG_OffsetFirstPersonView( void ) { angles = cg.refdef.viewangles; // if dead, fix the angle and don't add any kick - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { angles[ROLL] = 40; angles[PITCH] = -15; angles[YAW] = cg.snap->ps.stats[STAT_DEAD_YAW]; @@ -950,30 +832,26 @@ static void CG_OffsetFirstPersonView( void ) { // add angles based on weapon kick kickTime = (cg.time - cg.kick_time); - if ( kickTime < 800 ) - {//kicks are always 1 second long. Deal with it. + if (kickTime < 800) { // kicks are always 1 second long. Deal with it. float kickPerc = 0.0f; - if ( kickTime <= 200 ) - {//winding up - kickPerc = kickTime/200.0f; - } - else - {//returning to normal + if (kickTime <= 200) { // winding up + kickPerc = kickTime / 200.0f; + } else { // returning to normal kickTime = 800 - kickTime; - kickPerc = kickTime/600.0f; + kickPerc = kickTime / 600.0f; } - VectorMA( angles, kickPerc, cg.kick_angles, angles ); + VectorMA(angles, kickPerc, cg.kick_angles, angles); } // add angles based on damage kick - if ( cg.damageTime ) { + if (cg.damageTime) { ratio = cg.time - cg.damageTime; - if ( ratio < DAMAGE_DEFLECT_TIME ) { + if (ratio < DAMAGE_DEFLECT_TIME) { ratio /= DAMAGE_DEFLECT_TIME; angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } else { - ratio = 1.0 - ( ratio - DAMAGE_DEFLECT_TIME ) / DAMAGE_RETURN_TIME; - if ( ratio > 0 ) { + ratio = 1.0 - (ratio - DAMAGE_DEFLECT_TIME) / DAMAGE_RETURN_TIME; + if (ratio > 0) { angles[PITCH] += ratio * cg.v_dmg_pitch; angles[ROLL] += ratio * cg.v_dmg_roll; } @@ -989,12 +867,12 @@ static void CG_OffsetFirstPersonView( void ) { #endif // add angles based on velocity - VectorCopy( cg.predictedPlayerState.velocity, predictedVelocity ); + VectorCopy(cg.predictedPlayerState.velocity, predictedVelocity); - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[0]); + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[0]); angles[PITCH] += delta * cg_runPitch.value; - delta = DotProduct ( predictedVelocity, cg.refdef.viewaxis[1]); + delta = DotProduct(predictedVelocity, cg.refdef.viewaxis[1]); angles[ROLL] -= delta * cg_runRoll.value; // add angles based on bob @@ -1004,25 +882,24 @@ static void CG_OffsetFirstPersonView( void ) { delta = cg.bobfracsin * cg_bobPitch.value * speed; if (cg.predictedPlayerState.pm_flags & PMF_DUCKED) - delta *= 3; // crouching + delta *= 3; // crouching angles[PITCH] += delta; delta = cg.bobfracsin * cg_bobRoll.value * speed; if (cg.predictedPlayerState.pm_flags & PMF_DUCKED) - delta *= 3; // crouching accentuates roll + delta *= 3; // crouching accentuates roll if (cg.bobcycle & 1) delta = -delta; angles[ROLL] += delta; -//=================================== + //=================================== // add view height origin[2] += cg.predictedPlayerState.viewheight; // smooth out duck height changes timeDelta = cg.time - cg.duckTime; - if ( timeDelta < DUCK_TIME) { - cg.refdef.vieworg[2] -= cg.duckChange - * (DUCK_TIME - timeDelta) / DUCK_TIME; + if (timeDelta < DUCK_TIME) { + cg.refdef.vieworg[2] -= cg.duckChange * (DUCK_TIME - timeDelta) / DUCK_TIME; } // add bob height @@ -1033,15 +910,14 @@ static void CG_OffsetFirstPersonView( void ) { origin[2] += bob; - // add fall height delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { + if (delta < LAND_DEFLECT_TIME) { f = delta / LAND_DEFLECT_TIME; cg.refdef.vieworg[2] += cg.landChange * f; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { delta -= LAND_DEFLECT_TIME; - f = 1.0 - ( delta / LAND_RETURN_TIME ); + f = 1.0 - (delta / LAND_RETURN_TIME); cg.refdef.vieworg[2] += cg.landChange * f; } @@ -1050,12 +926,12 @@ static void CG_OffsetFirstPersonView( void ) { // add kick offset - VectorAdd (origin, cg.kick_origin, origin); + VectorAdd(origin, cg.kick_origin, origin); // pivot the eye based on a neck length #if 0 { -#define NECK_LENGTH 8 +#define NECK_LENGTH 8 vec3_t forward, up; cg.refdef.vieworg[2] -= NECK_LENGTH; @@ -1066,62 +942,57 @@ static void CG_OffsetFirstPersonView( void ) { #endif } -static void CG_OffsetFighterView( void ) -{ +static void CG_OffsetFighterView(void) { vec3_t vehFwd, vehRight, vehUp, backDir; - vec3_t camOrg, camBackOrg; + vec3_t camOrg, camBackOrg; float horzOffset = cg_thirdPersonHorzOffset.value; float vertOffset = cg_thirdPersonVertOffset.value; float pitchOffset = cg_thirdPersonPitchOffset.value; float yawOffset = cg_thirdPersonAngle.value; float range = cg_thirdPersonRange.value; - trace_t trace; + trace_t trace; centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - AngleVectors( cg.refdef.viewangles, vehFwd, vehRight, vehUp ); + AngleVectors(cg.refdef.viewangles, vehFwd, vehRight, vehUp); - if ( veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->cameraOverride ) - { //override the horizontal offset with what the vehicle wants it to be + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo->cameraOverride) { // override the horizontal offset with what the vehicle wants it to be horzOffset = veh->m_pVehicle->m_pVehicleInfo->cameraHorzOffset; vertOffset = veh->m_pVehicle->m_pVehicleInfo->cameraVertOffset; - //NOTE: no yaw offset? + // NOTE: no yaw offset? pitchOffset = veh->m_pVehicle->m_pVehicleInfo->cameraPitchOffset; range = veh->m_pVehicle->m_pVehicleInfo->cameraRange; - if ( veh->playerState->hackingTime ) - { - horzOffset += (((float)veh->playerState->hackingTime)/MAX_STRAFE_TIME) * -80.0f; - range += fabs(((float)veh->playerState->hackingTime)/MAX_STRAFE_TIME) * 100.0f; + if (veh->playerState->hackingTime) { + horzOffset += (((float)veh->playerState->hackingTime) / MAX_STRAFE_TIME) * -80.0f; + range += fabs(((float)veh->playerState->hackingTime) / MAX_STRAFE_TIME) * 100.0f; } } - //Set camera viewing position - VectorMA( cg.refdef.vieworg, horzOffset, vehRight, camOrg ); - VectorMA( camOrg, vertOffset, vehUp, camOrg ); + // Set camera viewing position + VectorMA(cg.refdef.vieworg, horzOffset, vehRight, camOrg); + VectorMA(camOrg, vertOffset, vehUp, camOrg); - //trace to that pos + // trace to that pos CG_Trace(&trace, cg.refdef.vieworg, cameramins, cameramaxs, camOrg, cg.snap->ps.clientNum, MASK_CAMERACLIP); - if ( trace.fraction < 1.0 ) - { - VectorCopy( trace.endpos, camOrg ); + if (trace.fraction < 1.0) { + VectorCopy(trace.endpos, camOrg); } // Set camera viewing direction. cg.refdef.viewangles[YAW] += yawOffset; cg.refdef.viewangles[PITCH] += pitchOffset; - //Now bring the cam back from that pos and angles at range - AngleVectors( cg.refdef.viewangles, backDir, NULL, NULL ); - VectorScale( backDir, -1, backDir ); + // Now bring the cam back from that pos and angles at range + AngleVectors(cg.refdef.viewangles, backDir, NULL, NULL); + VectorScale(backDir, -1, backDir); - VectorMA( camOrg, range, backDir, camBackOrg ); + VectorMA(camOrg, range, backDir, camBackOrg); - //trace to that pos + // trace to that pos CG_Trace(&trace, camOrg, cameramins, cameramaxs, camBackOrg, cg.snap->ps.clientNum, MASK_CAMERACLIP); - VectorCopy( trace.endpos, camOrg ); + VectorCopy(trace.endpos, camOrg); - //FIXME: do we need to smooth the org? - // ...and of course we should copy the new view location to the proper spot too. + // FIXME: do we need to smooth the org? + // ...and of course we should copy the new view location to the proper spot too. VectorCopy(camOrg, cg.refdef.vieworg); } //====================================================================== @@ -1133,135 +1004,113 @@ CG_CalcFov Fixed fov at intermissions, otherwise account for fov variable and zooms. ==================== */ -#define WAVE_AMPLITUDE 1 -#define WAVE_FREQUENCY 0.4 -float zoomFov; //this has to be global client-side - -static int CG_CalcFov( void ) { - float x; - float phase; - float v; - float fov_x, fov_y; - float f; - int inwater; - float cgFov = cg_fov.value; - - if (cgFov < 1) - { +#define WAVE_AMPLITUDE 1 +#define WAVE_FREQUENCY 0.4 +float zoomFov; // this has to be global client-side + +static int CG_CalcFov(void) { + float x; + float phase; + float v; + float fov_x, fov_y; + float f; + int inwater; + float cgFov = cg_fov.value; + + if (cgFov < 1) { cgFov = 1; } - if (cgFov > 130) - { + if (cgFov > 130) { cgFov = 130; } - if ( cg.predictedPlayerState.pm_type == PM_INTERMISSION ) { + if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) { // if in intermission, use a fixed value - fov_x = 80;//90; + fov_x = 80; // 90; } else { // user selectable - if ( cgs.dmflags & DF_FIXED_FOV ) { + if (cgs.dmflags & DF_FIXED_FOV) { // dmflag to prevent wide fov for all clients - fov_x = 80;//90; + fov_x = 80; // 90; } else { fov_x = cgFov; - if ( fov_x < 1 ) { + if (fov_x < 1) { fov_x = 1; - } else if ( fov_x > 160 ) { + } else if (fov_x > 160) { fov_x = 160; } } - if (cg.predictedPlayerState.zoomMode == 2) - { //binoculars - if (zoomFov > 40.0f) - { + if (cg.predictedPlayerState.zoomMode == 2) { // binoculars + if (zoomFov > 40.0f) { zoomFov -= cg.frametime * 0.075f; - if (zoomFov < 40.0f) - { + if (zoomFov < 40.0f) { zoomFov = 40.0f; - } - else if (zoomFov > cgFov) - { + } else if (zoomFov > cgFov) { zoomFov = cgFov; } } fov_x = zoomFov; - } - else if (cg.predictedPlayerState.zoomMode) - { - if (!cg.predictedPlayerState.zoomLocked) - { - if (zoomFov > 50) - { //Now starting out at nearly half zoomed in + } else if (cg.predictedPlayerState.zoomMode) { + if (!cg.predictedPlayerState.zoomLocked) { + if (zoomFov > 50) { // Now starting out at nearly half zoomed in zoomFov = 50; } - zoomFov -= cg.frametime * 0.035f;//0.075f; + zoomFov -= cg.frametime * 0.035f; // 0.075f; - if (zoomFov < MAX_ZOOM_FOV) - { + if (zoomFov < MAX_ZOOM_FOV) { zoomFov = MAX_ZOOM_FOV; - } - else if (zoomFov > cgFov) - { + } else if (zoomFov > cgFov) { zoomFov = cgFov; - } - else - { // Still zooming + } else { // Still zooming static int zoomSoundTime = 0; - if (zoomSoundTime < cg.time || zoomSoundTime > cg.time + 10000) - { + if (zoomSoundTime < cg.time || zoomSoundTime > cg.time + 10000) { trap->S_StartSound(cg.refdef.vieworg, ENTITYNUM_WORLD, CHAN_LOCAL, cgs.media.disruptorZoomLoop); zoomSoundTime = cg.time + 300; } } } - if (zoomFov < MAX_ZOOM_FOV) - { - zoomFov = 50; // hack to fix zoom during vid restart + if (zoomFov < MAX_ZOOM_FOV) { + zoomFov = 50; // hack to fix zoom during vid restart } fov_x = zoomFov; - } - else - { + } else { zoomFov = 80; - f = ( cg.time - cg.predictedPlayerState.zoomTime ) / ZOOM_OUT_TIME; - if ( f <= 1.0 ) - { - fov_x = cg.predictedPlayerState.zoomFov + f * ( fov_x - cg.predictedPlayerState.zoomFov ); + f = (cg.time - cg.predictedPlayerState.zoomTime) / ZOOM_OUT_TIME; + if (f <= 1.0) { + fov_x = cg.predictedPlayerState.zoomFov + f * (fov_x - cg.predictedPlayerState.zoomFov); } } } - if ( cg_fovAspectAdjust.integer ) { + if (cg_fovAspectAdjust.integer) { // Based on LordHavoc's code for Darkplaces // http://www.quakeworld.nu/forum/topic/53/what-does-your-qw-look-like/page/30 const float baseAspect = 0.75f; // 3/4 - const float aspect = (float)cgs.glconfig.vidWidth/(float)cgs.glconfig.vidHeight; + const float aspect = (float)cgs.glconfig.vidWidth / (float)cgs.glconfig.vidHeight; const float desiredFov = fov_x; - fov_x = atan( tan( desiredFov*M_PI / 360.0f ) * baseAspect*aspect )*360.0f / M_PI; + fov_x = atan(tan(desiredFov * M_PI / 360.0f) * baseAspect * aspect) * 360.0f / M_PI; } - x = cg.refdef.width / tan( fov_x / 360 * M_PI ); - fov_y = atan2( cg.refdef.height, x ); + x = cg.refdef.width / tan(fov_x / 360 * M_PI); + fov_y = atan2(cg.refdef.height, x); fov_y = fov_y * 360 / M_PI; // warp if underwater - cg.refdef.viewContents = CG_PointContents( cg.refdef.vieworg, -1 ); - if ( cg.refdef.viewContents & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ){ + cg.refdef.viewContents = CG_PointContents(cg.refdef.vieworg, -1); + if (cg.refdef.viewContents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA)) { phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2; - v = WAVE_AMPLITUDE * sin( phase ); + v = WAVE_AMPLITUDE * sin(phase); fov_x += v; fov_y -= v; inwater = qtrue; - } - else { + } else { inwater = qfalse; } @@ -1269,11 +1118,9 @@ static int CG_CalcFov( void ) { cg.refdef.fov_x = fov_x; cg.refdef.fov_y = fov_y; - if (cg.predictedPlayerState.zoomMode) - { - cg.zoomSensitivity = zoomFov/cgFov; - } - else if ( !cg.zoomed ) { + if (cg.predictedPlayerState.zoomMode) { + cg.zoomSensitivity = zoomFov / cgFov; + } else if (!cg.zoomed) { cg.zoomSensitivity = 1; } else { cg.zoomSensitivity = cg.refdef.fov_y / 75.0; @@ -1282,210 +1129,176 @@ static int CG_CalcFov( void ) { return inwater; } - /* =============== CG_DamageBlendBlob =============== */ -static void CG_DamageBlendBlob( void ) -{ - int t; - int maxTime; - refEntity_t ent; +static void CG_DamageBlendBlob(void) { + int t; + int maxTime; + refEntity_t ent; - if ( !cg.damageValue ) { + if (!cg.damageValue) { return; } maxTime = DAMAGE_TIME; t = cg.time - cg.damageTime; - if ( t <= 0 || t >= maxTime ) { + if (t <= 0 || t >= maxTime) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); ent.reType = RT_SPRITE; ent.renderfx = RF_FIRST_PERSON; - VectorMA( cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin ); - VectorMA( ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin ); - VectorMA( ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin ); + VectorMA(cg.refdef.vieworg, 8, cg.refdef.viewaxis[0], ent.origin); + VectorMA(ent.origin, cg.damageX * -8, cg.refdef.viewaxis[1], ent.origin); + VectorMA(ent.origin, cg.damageY * 8, cg.refdef.viewaxis[2], ent.origin); - ent.radius = cg.damageValue * 3 * ( 1.0 - ((float)t / maxTime) ); + ent.radius = cg.damageValue * 3 * (1.0 - ((float)t / maxTime)); - if (cg.snap->ps.damageType == 0) - { //pure health + if (cg.snap->ps.damageType == 0) { // pure health ent.customShader = cgs.media.viewPainShader; - ent.shaderRGBA[0] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[1] = 50 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[2] = 50 * ( 1.0 - ((float)t / maxTime) ); + ent.shaderRGBA[0] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[1] = 50 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[2] = 50 * (1.0 - ((float)t / maxTime)); ent.shaderRGBA[3] = 255; - } - else if (cg.snap->ps.damageType == 1) - { //pure shields + } else if (cg.snap->ps.damageType == 1) { // pure shields ent.customShader = cgs.media.viewPainShader_Shields; - ent.shaderRGBA[0] = 50 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[1] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[2] = 50 * ( 1.0 - ((float)t / maxTime) ); + ent.shaderRGBA[0] = 50 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[1] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[2] = 50 * (1.0 - ((float)t / maxTime)); ent.shaderRGBA[3] = 255; - } - else - { //shields and health + } else { // shields and health ent.customShader = cgs.media.viewPainShader_ShieldsAndHealth; - ent.shaderRGBA[0] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[1] = 180 * ( 1.0 - ((float)t / maxTime) ); - ent.shaderRGBA[2] = 50 * ( 1.0 - ((float)t / maxTime) ); + ent.shaderRGBA[0] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[1] = 180 * (1.0 - ((float)t / maxTime)); + ent.shaderRGBA[2] = 50 * (1.0 - ((float)t / maxTime)); ent.shaderRGBA[3] = 255; } - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } int cg_actionCamLastTime = 0; vec3_t cg_actionCamLastPos; -//action cam routine -rww -static qboolean CG_ThirdPersonActionCam(void) -{ - centity_t *cent = &cg_entities[cg.snap->ps.clientNum]; +// action cam routine -rww +static qboolean CG_ThirdPersonActionCam(void) { + centity_t *cent = &cg_entities[cg.snap->ps.clientNum]; clientInfo_t *ci = &cgs.clientinfo[cg.snap->ps.clientNum]; trace_t tr; vec3_t positionDir; vec3_t desiredAngles; vec3_t desiredPos; vec3_t v; - const float smoothFactor = 0.1f*timescale.value; + const float smoothFactor = 0.1f * timescale.value; int i; - if (!cent->ghoul2) - { //if we don't have a g2 instance this frame for whatever reason then do nothing + if (!cent->ghoul2) { // if we don't have a g2 instance this frame for whatever reason then do nothing return qfalse; } - if (cent->currentState.weapon != WP_SABER) - { //just being safe, should not ever happen + if (cent->currentState.weapon != WP_SABER) { // just being safe, should not ever happen return qfalse; } - if ((cg.time - ci->saber[0].blade[0].trail.lastTime) > 300) - { //too long since we last got the blade position + if ((cg.time - ci->saber[0].blade[0].trail.lastTime) > 300) { // too long since we last got the blade position return qfalse; } - //get direction from base to ent origin + // get direction from base to ent origin VectorSubtract(ci->saber[0].blade[0].trail.base, cent->lerpOrigin, positionDir); VectorNormalize(positionDir); - //position the cam based on the direction and saber position - VectorMA(cent->lerpOrigin, cg_thirdPersonRange.value*2, positionDir, desiredPos); + // position the cam based on the direction and saber position + VectorMA(cent->lerpOrigin, cg_thirdPersonRange.value * 2, positionDir, desiredPos); - //trace to the desired pos to see how far that way we can actually go before we hit something - //the endpos will be valid for our desiredpos no matter what + // trace to the desired pos to see how far that way we can actually go before we hit something + // the endpos will be valid for our desiredpos no matter what CG_Trace(&tr, cent->lerpOrigin, NULL, NULL, desiredPos, cent->currentState.number, MASK_SOLID); VectorCopy(tr.endpos, desiredPos); - if ((cg.time - cg_actionCamLastTime) > 300) - { - //do a third person offset first and grab the initial point from that + if ((cg.time - cg_actionCamLastTime) > 300) { + // do a third person offset first and grab the initial point from that CG_OffsetThirdPersonView(); VectorCopy(cg.refdef.vieworg, cg_actionCamLastPos); } cg_actionCamLastTime = cg.time; - //lerp the vieworg to the desired pos from the last valid + // lerp the vieworg to the desired pos from the last valid VectorSubtract(desiredPos, cg_actionCamLastPos, v); - if (VectorLength(v) > 64.0f) - { //don't bother moving yet if not far from the last pos - for (i = 0; i < 3; i++) - { - cg_actionCamLastPos[i] = (cg_actionCamLastPos[i] + (v[i]*smoothFactor)); + if (VectorLength(v) > 64.0f) { // don't bother moving yet if not far from the last pos + for (i = 0; i < 3; i++) { + cg_actionCamLastPos[i] = (cg_actionCamLastPos[i] + (v[i] * smoothFactor)); cg.refdef.vieworg[i] = cg_actionCamLastPos[i]; } - } - else - { + } else { VectorCopy(cg_actionCamLastPos, cg.refdef.vieworg); } - //Make sure the point is alright + // Make sure the point is alright CG_Trace(&tr, cent->lerpOrigin, NULL, NULL, cg.refdef.vieworg, cent->currentState.number, MASK_SOLID); VectorCopy(tr.endpos, cg.refdef.vieworg); VectorSubtract(cent->lerpOrigin, cg.refdef.vieworg, positionDir); vectoangles(positionDir, desiredAngles); - //just set the angles for now + // just set the angles for now VectorCopy(desiredAngles, cg.refdef.viewangles); return qtrue; } -vec3_t cg_lastTurretViewAngles={0}; -qboolean CG_CheckPassengerTurretView( void ) -{ - if ( cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && cg.predictedPlayerState.generic1 )//as a passenger - {//passenger in a vehicle +vec3_t cg_lastTurretViewAngles = {0}; +qboolean CG_CheckPassengerTurretView(void) { + if (cg.predictedPlayerState.m_iVehicleNum // in a vehicle + && cg.predictedPlayerState.generic1) // as a passenger + { // passenger in a vehicle centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( vehCent->m_pVehicle - && vehCent->m_pVehicle->m_pVehicleInfo - && vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers ) - {//a vehicle capable of carrying passengers + if (vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo && + vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers) { // a vehicle capable of carrying passengers int turretNum; - for ( turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++ ) - { - if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax ) - {// valid turret - if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1 ) - {//I control this turret + for (turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++) { + if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax) { // valid turret + if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1) { // I control this turret int boltIndex = -1; qboolean hackPosAndAngle = qfalse; - if ( vehCent->m_pVehicle->m_iGunnerViewTag[turretNum] != -1 ) - { + if (vehCent->m_pVehicle->m_iGunnerViewTag[turretNum] != -1) { boltIndex = vehCent->m_pVehicle->m_iGunnerViewTag[turretNum]; - } - else - {//crap... guess? + } else { // crap... guess? hackPosAndAngle = qtrue; - if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].yawBone ) - { - boltIndex = trap->G2API_AddBolt( vehCent->ghoul2, 0, vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].yawBone ); - } - else if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].pitchBone ) - { - boltIndex = trap->G2API_AddBolt( vehCent->ghoul2, 0, vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].pitchBone ); - } - else - {//well, no way of knowing, so screw it + if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].yawBone) { + boltIndex = trap->G2API_AddBolt(vehCent->ghoul2, 0, vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].yawBone); + } else if (vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].pitchBone) { + boltIndex = trap->G2API_AddBolt(vehCent->ghoul2, 0, vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].pitchBone); + } else { // well, no way of knowing, so screw it return qfalse; } } - if ( boltIndex != -1 ) - { + if (boltIndex != -1) { mdxaBone_t boltMatrix; vec3_t fwd, up; - trap->G2API_GetBoltMatrix_NoRecNoRot(vehCent->ghoul2, 0, boltIndex, &boltMatrix, vehCent->lerpAngles, - vehCent->lerpOrigin, cg.time, NULL, vehCent->modelScale); + trap->G2API_GetBoltMatrix_NoRecNoRot(vehCent->ghoul2, 0, boltIndex, &boltMatrix, vehCent->lerpAngles, vehCent->lerpOrigin, cg.time, + NULL, vehCent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, cg.refdef.vieworg); - if ( hackPosAndAngle ) - { - //FIXME: these are assumptions, externalize? BETTER YET: give me a controller view bolt/tag for each turret + if (hackPosAndAngle) { + // FIXME: these are assumptions, externalize? BETTER YET: give me a controller view bolt/tag for each turret BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, fwd); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, up); - VectorMA( cg.refdef.vieworg, 8.0f, fwd, cg.refdef.vieworg ); - VectorMA( cg.refdef.vieworg, 4.0f, up, cg.refdef.vieworg ); - } - else - { + VectorMA(cg.refdef.vieworg, 8.0f, fwd, cg.refdef.vieworg); + VectorMA(cg.refdef.vieworg, 4.0f, up, cg.refdef.vieworg); + } else { BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd); } { - vec3_t newAngles, deltaAngles; - vectoangles( fwd, newAngles ); - AnglesSubtract( newAngles, cg_lastTurretViewAngles, deltaAngles ); - VectorMA( cg_lastTurretViewAngles, 0.5f*(float)cg.frametime/100.0f, deltaAngles, cg.refdef.viewangles ); + vec3_t newAngles, deltaAngles; + vectoangles(fwd, newAngles); + AnglesSubtract(newAngles, cg_lastTurretViewAngles, deltaAngles); + VectorMA(cg_lastTurretViewAngles, 0.5f * (float)cg.frametime / 100.0f, deltaAngles, cg.refdef.viewangles); } return qtrue; } @@ -1504,11 +1317,11 @@ Sets cg.refdef view values =============== */ void CG_EmplacedView(vec3_t angles); -static int CG_CalcViewValues( void ) { +static int CG_CalcViewValues(void) { qboolean manningTurret = qfalse; - playerState_t *ps; + playerState_t *ps; - memset( &cg.refdef, 0, sizeof( cg.refdef ) ); + memset(&cg.refdef, 0, sizeof(cg.refdef)); // strings for in game rendering // Q_strncpyz( cg.refdef.text[0], "Park Ranger", sizeof(cg.refdef.text[0]) ); @@ -1518,75 +1331,69 @@ static int CG_CalcViewValues( void ) { CG_CalcVrect(); ps = &cg.predictedPlayerState; -/* - if (cg.cameraMode) { - vec3_t origin, angles; - if (trap->getCameraInfo(cg.time, &origin, &angles)) { - VectorCopy(origin, cg.refdef.vieworg); - angles[ROLL] = 0; - VectorCopy(angles, cg.refdef.viewangles); - AnglesToAxis( cg.refdef.viewangles, cg.refdef.viewaxis ); - return CG_CalcFov(); - } else { - cg.cameraMode = qfalse; + /* + if (cg.cameraMode) { + vec3_t origin, angles; + if (trap->getCameraInfo(cg.time, &origin, &angles)) { + VectorCopy(origin, cg.refdef.vieworg); + angles[ROLL] = 0; + VectorCopy(angles, cg.refdef.viewangles); + AnglesToAxis( cg.refdef.viewangles, cg.refdef.viewaxis ); + return CG_CalcFov(); + } else { + cg.cameraMode = qfalse; + } } - } -*/ + */ // intermission view - if ( ps->pm_type == PM_INTERMISSION ) { - VectorCopy( ps->origin, cg.refdef.vieworg ); - VectorCopy( ps->viewangles, cg.refdef.viewangles ); - AnglesToAxis( cg.refdef.viewangles, cg.refdef.viewaxis ); + if (ps->pm_type == PM_INTERMISSION) { + VectorCopy(ps->origin, cg.refdef.vieworg); + VectorCopy(ps->viewangles, cg.refdef.viewangles); + AnglesToAxis(cg.refdef.viewangles, cg.refdef.viewaxis); return CG_CalcFov(); } - cg.bobcycle = ( ps->bobCycle & 128 ) >> 7; - cg.bobfracsin = fabs( sin( ( ps->bobCycle & 127 ) / 127.0 * M_PI ) ); - cg.xyspeed = sqrt( ps->velocity[0] * ps->velocity[0] + - ps->velocity[1] * ps->velocity[1] ); + cg.bobcycle = (ps->bobCycle & 128) >> 7; + cg.bobfracsin = fabs(sin((ps->bobCycle & 127) / 127.0 * M_PI)); + cg.xyspeed = sqrt(ps->velocity[0] * ps->velocity[0] + ps->velocity[1] * ps->velocity[1]); - if (cg.xyspeed > 270) - { + if (cg.xyspeed > 270) { cg.xyspeed = 270; } manningTurret = CG_CheckPassengerTurretView(); - if ( !manningTurret ) - {//not manning a turret on a vehicle - VectorCopy( ps->origin, cg.refdef.vieworg ); + if (!manningTurret) { // not manning a turret on a vehicle + VectorCopy(ps->origin, cg.refdef.vieworg); #ifdef VEH_CONTROL_SCHEME_4 - if ( cg.predictedPlayerState.m_iVehicleNum )//in a vehicle + if (cg.predictedPlayerState.m_iVehicleNum) // in a vehicle { Vehicle_t *pVeh = cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle; - if ( BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, pVeh ) )//can roll/pitch without restriction - {//use the vehicle's viewangles to render view! - VectorCopy( cg.predictedVehicleState.viewangles, cg.refdef.viewangles ); - } - else if ( pVeh //valid vehicle data pointer - && pVeh->m_pVehicleInfo//valid vehicle info - && pVeh->m_pVehicleInfo->type == VH_FIGHTER )//fighter + if (BG_UnrestrainedPitchRoll(&cg.predictedPlayerState, pVeh)) // can roll/pitch without restriction + { // use the vehicle's viewangles to render view! + VectorCopy(cg.predictedVehicleState.viewangles, cg.refdef.viewangles); + } else if (pVeh // valid vehicle data pointer + && pVeh->m_pVehicleInfo // valid vehicle info + && pVeh->m_pVehicleInfo->type == VH_FIGHTER) // fighter { - VectorCopy( cg.predictedVehicleState.viewangles, cg.refdef.viewangles ); - cg.refdef.viewangles[PITCH] = AngleNormalize180( cg.refdef.viewangles[PITCH] ); - } - else - { - VectorCopy( ps->viewangles, cg.refdef.viewangles ); + VectorCopy(cg.predictedVehicleState.viewangles, cg.refdef.viewangles); + cg.refdef.viewangles[PITCH] = AngleNormalize180(cg.refdef.viewangles[PITCH]); + } else { + VectorCopy(ps->viewangles, cg.refdef.viewangles); } } -#else// VEH_CONTROL_SCHEME_4 - if ( cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without restriction - {//use the vehicle's viewangles to render view! - VectorCopy( cg.predictedVehicleState.viewangles, cg.refdef.viewangles ); +#else // VEH_CONTROL_SCHEME_4 + if (cg.predictedPlayerState.m_iVehicleNum // in a vehicle + && BG_UnrestrainedPitchRoll(&cg.predictedPlayerState, + cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle)) // can roll/pitch without restriction + { // use the vehicle's viewangles to render view! + VectorCopy(cg.predictedVehicleState.viewangles, cg.refdef.viewangles); } -#endif// VEH_CONTROL_SCHEME_4 - else - { - VectorCopy( ps->viewangles, cg.refdef.viewangles ); +#endif // VEH_CONTROL_SCHEME_4 + else { + VectorCopy(ps->viewangles, cg.refdef.viewangles); } } - VectorCopy( cg.refdef.viewangles, cg_lastTurretViewAngles ); + VectorCopy(cg.refdef.viewangles, cg_lastTurretViewAngles); if (cg_cameraOrbit.integer) { if (cg.time > cg.nextOrbitTime) { @@ -1595,44 +1402,36 @@ static int CG_CalcViewValues( void ) { } } // add error decay - if ( cg_errorDecay.value > 0 ) { - int t; - float f; + if (cg_errorDecay.value > 0) { + int t; + float f; t = cg.time - cg.predictedErrorTime; - f = ( cg_errorDecay.value - t ) / cg_errorDecay.value; - if ( f > 0 && f < 1 ) { - VectorMA( cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg ); + f = (cg_errorDecay.value - t) / cg_errorDecay.value; + if (f > 0 && f < 1) { + VectorMA(cg.refdef.vieworg, f, cg.predictedError, cg.refdef.vieworg); } else { cg.predictedErrorTime = 0; } } - if (cg.snap->ps.weapon == WP_EMPLACED_GUN && - cg.snap->ps.emplacedIndex) - { //constrain the view properly for emplaced guns + if (cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) { // constrain the view properly for emplaced guns CG_EmplacedView(cg_entities[cg.snap->ps.emplacedIndex].currentState.angles); } - if ( !manningTurret ) - { - if ( cg.predictedPlayerState.m_iVehicleNum //in a vehicle - && BG_UnrestrainedPitchRoll( &cg.predictedPlayerState, cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle ) )//can roll/pitch without restriction - {//use the vehicle's viewangles to render view! + if (!manningTurret) { + if (cg.predictedPlayerState.m_iVehicleNum // in a vehicle + && BG_UnrestrainedPitchRoll(&cg.predictedPlayerState, + cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle)) // can roll/pitch without restriction + { // use the vehicle's viewangles to render view! CG_OffsetFighterView(); - } - else if ( cg.renderingThirdPerson ) { + } else if (cg.renderingThirdPerson) { // back away from character - if (cg_thirdPersonSpecialCam.integer && - BG_SaberInSpecial(cg.snap->ps.saberMove)) - { //the action cam - if (!CG_ThirdPersonActionCam()) - { //couldn't do it for whatever reason, resort back to third person then + if (cg_thirdPersonSpecialCam.integer && BG_SaberInSpecial(cg.snap->ps.saberMove)) { // the action cam + if (!CG_ThirdPersonActionCam()) { // couldn't do it for whatever reason, resort back to third person then CG_OffsetThirdPersonView(); } - } - else - { + } else { CG_OffsetThirdPersonView(); } } else { @@ -1642,9 +1441,9 @@ static int CG_CalcViewValues( void ) { } // position eye relative to origin - AnglesToAxis( cg.refdef.viewangles, cg.refdef.viewaxis ); + AnglesToAxis(cg.refdef.viewangles, cg.refdef.viewaxis); - if ( cg.hyperspace ) { + if (cg.hyperspace) { cg.refdef.rdflags |= RDF_NOWORLDMODEL | RDF_HYPERSPACE; } @@ -1652,27 +1451,26 @@ static int CG_CalcViewValues( void ) { return CG_CalcFov(); } - /* ===================== CG_PowerupTimerSounds ===================== */ -static void CG_PowerupTimerSounds( void ) { - int i; - int t; +static void CG_PowerupTimerSounds(void) { + int i; + int t; // powerup timers going away - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { + for (i = 0; i < MAX_POWERUPS; i++) { t = cg.snap->ps.powerups[i]; - if ( t <= cg.time ) { + if (t <= cg.time) { continue; } - if ( t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME ) { + if (t - cg.time >= POWERUP_BLINKS * POWERUP_BLINK_TIME) { continue; } - if ( ( t - cg.time ) / POWERUP_BLINK_TIME != ( t - cg.oldTime ) / POWERUP_BLINK_TIME ) { - //trap->S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.wearOffSound ); + if ((t - cg.time) / POWERUP_BLINK_TIME != (t - cg.oldTime) / POWERUP_BLINK_TIME) { + // trap->S_StartSound( NULL, cg.snap->ps.clientNum, CHAN_ITEM, cgs.media.wearOffSound ); } } } @@ -1686,8 +1484,7 @@ extern qboolean cg_skyOri; extern vec3_t cg_skyOriPos; extern float cg_skyOriScale; extern qboolean cg_noFogOutsidePortal; -void CG_DrawSkyBoxPortal(const char *cstr) -{ +void CG_DrawSkyBoxPortal(const char *cstr) { refdef_t backuprefdef; float fov_x; float fov_y; @@ -1697,85 +1494,69 @@ void CG_DrawSkyBoxPortal(const char *cstr) backuprefdef = cg.refdef; - COM_BeginParseSession ("CG_DrawSkyBoxPortal"); + COM_BeginParseSession("CG_DrawSkyBoxPortal"); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - trap->Error( ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + trap->Error(ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[0] = atof(token); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - trap->Error( ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + trap->Error(ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[1] = atof(token); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - trap->Error( ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + trap->Error(ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } cg.refdef.vieworg[2] = atof(token); token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - trap->Error( ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); + if (!token || !token[0]) { + trap->Error(ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring\n"); } fov_x = atoi(token); - if (!fov_x) - { + if (!fov_x) { fov_x = cg_fov.value; } // setup fog the first time, ignore this part of the configstring after that token = COM_ParseExt(&cstr, qfalse); - if (!token || !token[0]) - { - trap->Error( ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog state\n"); + if (!token || !token[0]) { + trap->Error(ERR_DROP, "CG_DrawSkyBoxPortal: error parsing skybox configstring. No fog state\n"); } - if ( cg.predictedPlayerState.pm_type == PM_INTERMISSION ) - { + if (cg.predictedPlayerState.pm_type == PM_INTERMISSION) { // if in intermission, use a fixed value fov_x = cg_fov.value; - } - else - { + } else { fov_x = cg_fov.value; - if ( fov_x < 1 ) - { + if (fov_x < 1) { fov_x = 1; - } - else if ( fov_x > 160 ) - { + } else if (fov_x > 160) { fov_x = 160; } - if (cg.predictedPlayerState.zoomMode) - { + if (cg.predictedPlayerState.zoomMode) { fov_x = zoomFov; } // do smooth transitions for zooming - if (cg.predictedPlayerState.zoomMode) - { //zoomed/zooming in - f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; - if ( f > 1.0 ) { + if (cg.predictedPlayerState.zoomMode) { // zoomed/zooming in + f = (cg.time - cg.zoomTime) / (float)ZOOM_OUT_TIME; + if (f > 1.0) { fov_x = zoomFov; } else { - fov_x = fov_x + f * ( zoomFov - fov_x ); + fov_x = fov_x + f * (zoomFov - fov_x); } - } - else - { //zooming out - f = ( cg.time - cg.zoomTime ) / (float)ZOOM_OUT_TIME; - if ( f <= 1.0 ) { - fov_x = zoomFov + f * ( fov_x - zoomFov); + } else { // zooming out + f = (cg.time - cg.zoomTime) / (float)ZOOM_OUT_TIME; + if (f <= 1.0) { + fov_x = zoomFov + f * (fov_x - zoomFov); } } } @@ -1787,11 +1568,11 @@ void CG_DrawSkyBoxPortal(const char *cstr) const float aspect = (float)cgs.glconfig.vidWidth / (float)cgs.glconfig.vidHeight; const float desiredFov = fov_x; - fov_x = atan(tan(desiredFov*M_PI / 360.0f) * baseAspect*aspect)*360.0f / M_PI; + fov_x = atan(tan(desiredFov * M_PI / 360.0f) * baseAspect * aspect) * 360.0f / M_PI; } - x = cg.refdef.width / tan( fov_x / 360 * M_PI ); - fov_y = atan2( cg.refdef.height, x ); + x = cg.refdef.width / tan(fov_x / 360 * M_PI); + fov_y = atan2(cg.refdef.height, x); fov_y = fov_y * 360 / M_PI; cg.refdef.fov_x = fov_x; @@ -1802,16 +1583,14 @@ void CG_DrawSkyBoxPortal(const char *cstr) cg.refdef.time = cg.time; - if ( !cg.hyperspace) - { //rww - also had to add this to add effects being rendered in portal sky areas properly. + if (!cg.hyperspace) { // rww - also had to add this to add effects being rendered in portal sky areas properly. trap->FX_AddScheduledEffects(qtrue); } - CG_AddPacketEntities(qtrue); //rww - There was no proper way to put real entities inside the portal view before. - //This will put specially flagged entities in the render. + CG_AddPacketEntities(qtrue); // rww - There was no proper way to put real entities inside the portal view before. + // This will put specially flagged entities in the render. - if (cg_skyOri) - { //ok, we want to orient the sky refdef vieworg based on the normal vieworg's relation to the ori pos + if (cg_skyOri) { // ok, we want to orient the sky refdef vieworg based on the normal vieworg's relation to the ori pos vec3_t dif; VectorSubtract(backuprefdef.vieworg, cg_skyOriPos, dif); @@ -1819,14 +1598,13 @@ void CG_DrawSkyBoxPortal(const char *cstr) VectorAdd(cg.refdef.vieworg, dif, cg.refdef.vieworg); } - if (cg_noFogOutsidePortal) - { //make sure no fog flag is stripped first, and make sure it is set on the normal refdef + if (cg_noFogOutsidePortal) { // make sure no fog flag is stripped first, and make sure it is set on the normal refdef cg.refdef.rdflags &= ~RDF_NOFOG; backuprefdef.rdflags |= RDF_NOFOG; } // draw the skybox - trap->R_RenderScene( &cg.refdef ); + trap->R_RenderScene(&cg.refdef); cg.refdef = backuprefdef; } @@ -1836,8 +1614,8 @@ void CG_DrawSkyBoxPortal(const char *cstr) CG_AddBufferedSound ===================== */ -void CG_AddBufferedSound( sfxHandle_t sfx ) { - if ( !sfx ) +void CG_AddBufferedSound(sfxHandle_t sfx) { + if (!sfx) return; cg.soundBuffer[cg.soundBufferIn] = sfx; cg.soundBufferIn = (cg.soundBufferIn + 1) % MAX_SOUNDBUFFER; @@ -1851,8 +1629,8 @@ void CG_AddBufferedSound( sfxHandle_t sfx ) { CG_PlayBufferedSounds ===================== */ -static void CG_PlayBufferedSounds( void ) { - if ( cg.soundTime < cg.time ) { +static void CG_PlayBufferedSounds(void) { + if (cg.soundTime < cg.time) { if (cg.soundBufferOut != cg.soundBufferIn && cg.soundBuffer[cg.soundBufferOut]) { trap->S_StartLocalSound(cg.soundBuffer[cg.soundBufferOut], CHAN_ANNOUNCER); cg.soundBuffer[cg.soundBufferOut] = 0; @@ -1862,32 +1640,27 @@ static void CG_PlayBufferedSounds( void ) { } } -void CG_UpdateSoundTrackers() -{ +void CG_UpdateSoundTrackers() { int num; centity_t *cent; - for ( num = 0 ; num < ENTITYNUM_NONE ; num++ ) - { + for (num = 0; num < ENTITYNUM_NONE; num++) { cent = &cg_entities[num]; if (cent && (cent->currentState.eFlags & EF_SOUNDTRACKER) && cent->currentState.number == num) - //make sure the thing is valid at least. - { //keep sound for this entity updated in accordance with its attached entity at all times - if (cg.snap && cent->currentState.trickedentindex == cg.snap->ps.clientNum) - { //this is actually the player, so center the sound origin right on top of us + // make sure the thing is valid at least. + { // keep sound for this entity updated in accordance with its attached entity at all times + if (cg.snap && + cent->currentState.trickedentindex == cg.snap->ps.clientNum) { // this is actually the player, so center the sound origin right on top of us VectorCopy(cg.refdef.vieworg, cent->lerpOrigin); - trap->S_UpdateEntityPosition( cent->currentState.number, cent->lerpOrigin ); - } - else - { - trap->S_UpdateEntityPosition( cent->currentState.number, cg_entities[cent->currentState.trickedentindex].lerpOrigin ); + trap->S_UpdateEntityPosition(cent->currentState.number, cent->lerpOrigin); + } else { + trap->S_UpdateEntityPosition(cent->currentState.number, cg_entities[cent->currentState.trickedentindex].lerpOrigin); } } - if (cent->currentState.number == num) - { - //update all looping sounds.. + if (cent->currentState.number == num) { + // update all looping sounds.. CG_S_UpdateLoopingSounds(num); } } @@ -1900,22 +1673,20 @@ void CG_UpdateSoundTrackers() Screen Effect stuff starts here ================================ */ -#define CAMERA_DEFAULT_FOV 90.0f -#define MAX_SHAKE_INTENSITY 16.0f +#define CAMERA_DEFAULT_FOV 90.0f +#define MAX_SHAKE_INTENSITY 16.0f cgscreffects_t cgScreenEffects; -void CG_SE_UpdateShake( vec3_t origin, vec3_t angles ) -{ - vec3_t moveDir; - float intensity_scale, intensity; - int i; +void CG_SE_UpdateShake(vec3_t origin, vec3_t angles) { + vec3_t moveDir; + float intensity_scale, intensity; + int i; - if ( cgScreenEffects.shake_duration <= 0 ) + if (cgScreenEffects.shake_duration <= 0) return; - if ( cg.time > ( cgScreenEffects.shake_start + cgScreenEffects.shake_duration ) ) - { + if (cg.time > (cgScreenEffects.shake_start + cgScreenEffects.shake_duration)) { cgScreenEffects.shake_intensity = 0; cgScreenEffects.shake_duration = 0; cgScreenEffects.shake_start = 0; @@ -1925,55 +1696,47 @@ void CG_SE_UpdateShake( vec3_t origin, vec3_t angles ) cgScreenEffects.FOV = CAMERA_DEFAULT_FOV; cgScreenEffects.FOV2 = CAMERA_DEFAULT_FOV; - //intensity_scale now also takes into account FOV with 90.0 as normal - intensity_scale = 1.0f - ( (float) ( cg.time - cgScreenEffects.shake_start ) / (float) cgScreenEffects.shake_duration ) * (((cgScreenEffects.FOV+cgScreenEffects.FOV2)/2.0f)/90.0f); + // intensity_scale now also takes into account FOV with 90.0 as normal + intensity_scale = 1.0f - ((float)(cg.time - cgScreenEffects.shake_start) / (float)cgScreenEffects.shake_duration) * + (((cgScreenEffects.FOV + cgScreenEffects.FOV2) / 2.0f) / 90.0f); intensity = cgScreenEffects.shake_intensity * intensity_scale; - for ( i = 0; i < 3; i++ ) - { - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (i = 0; i < 3; i++) { + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); } - //Move the camera - VectorAdd( origin, moveDir, origin ); + // Move the camera + VectorAdd(origin, moveDir, origin); - for ( i=0; i < 2; i++ ) // Don't do ROLL - moveDir[i] = ( Q_flrand(-1.0f, 1.0f) * intensity ); + for (i = 0; i < 2; i++) // Don't do ROLL + moveDir[i] = (Q_flrand(-1.0f, 1.0f) * intensity); - //Move the angles - VectorAdd( angles, moveDir, angles ); + // Move the angles + VectorAdd(angles, moveDir, angles); } -void CG_SE_UpdateMusic(void) -{ - if (cgScreenEffects.music_volume_multiplier < 0.1) - { +void CG_SE_UpdateMusic(void) { + if (cgScreenEffects.music_volume_multiplier < 0.1) { cgScreenEffects.music_volume_multiplier = 1.0; return; } - if (cgScreenEffects.music_volume_time < cg.time) - { - if (cgScreenEffects.music_volume_multiplier != 1.0f || cgScreenEffects.music_volume_set) - { + if (cgScreenEffects.music_volume_time < cg.time) { + if (cgScreenEffects.music_volume_multiplier != 1.0f || cgScreenEffects.music_volume_set) { char musMultStr[512]; cgScreenEffects.music_volume_multiplier += 0.1f; - if (cgScreenEffects.music_volume_multiplier > 1.0f) - { + if (cgScreenEffects.music_volume_multiplier > 1.0f) { cgScreenEffects.music_volume_multiplier = 1.0f; } Com_sprintf(musMultStr, sizeof(musMultStr), "%f", cgScreenEffects.music_volume_multiplier); trap->Cvar_Set("s_musicMult", musMultStr); - if (cgScreenEffects.music_volume_multiplier == 1.0f) - { + if (cgScreenEffects.music_volume_multiplier == 1.0f) { cgScreenEffects.music_volume_set = qfalse; - } - else - { + } else { cgScreenEffects.music_volume_time = cg.time + 200; } } @@ -1981,8 +1744,7 @@ void CG_SE_UpdateMusic(void) return; } - if (!cgScreenEffects.music_volume_set) - { //if the volume_time is >= cg.time, we should have a volume multiplier set + if (!cgScreenEffects.music_volume_set) { // if the volume_time is >= cg.time, we should have a volume multiplier set char musMultStr[512]; Com_sprintf(musMultStr, sizeof(musMultStr), "%f", cgScreenEffects.music_volume_multiplier); @@ -1998,55 +1760,48 @@ CG_CalcScreenEffects Currently just for screen shaking (and music volume management) ================= */ -void CG_CalcScreenEffects(void) -{ +void CG_CalcScreenEffects(void) { CG_SE_UpdateShake(cg.refdef.vieworg, cg.refdef.viewangles); CG_SE_UpdateMusic(); } -void CGCam_Shake( float intensity, int duration ) -{ - if ( intensity > MAX_SHAKE_INTENSITY ) +void CGCam_Shake(float intensity, int duration) { + if (intensity > MAX_SHAKE_INTENSITY) intensity = MAX_SHAKE_INTENSITY; cgScreenEffects.shake_intensity = intensity; cgScreenEffects.shake_duration = duration; - cgScreenEffects.shake_start = cg.time; } -void CG_DoCameraShake( vec3_t origin, float intensity, int radius, int time ) -{ - //FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s +void CG_DoCameraShake(vec3_t origin, float intensity, int radius, int time) { + // FIXME: When exactly is the vieworg calculated in relation to the rest of the frame?s - vec3_t dir; - float dist, intensityScale; - float realIntensity; + vec3_t dir; + float dist, intensityScale; + float realIntensity; - VectorSubtract( cg.refdef.vieworg, origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(cg.refdef.vieworg, origin, dir); + dist = VectorNormalize(dir); - //Use the dir to add kick to the explosion + // Use the dir to add kick to the explosion - if ( dist > radius ) + if (dist > radius) return; - intensityScale = 1 - ( dist / (float) radius ); + intensityScale = 1 - (dist / (float)radius); realIntensity = intensity * intensityScale; - CGCam_Shake( realIntensity, time ); + CGCam_Shake(realIntensity, time); } -void CGCam_SetMusicMult( float multiplier, int duration ) -{ - if (multiplier < 0.1f) - { +void CGCam_SetMusicMult(float multiplier, int duration) { + if (multiplier < 0.1f) { multiplier = 0.1f; } - if (multiplier > 1.0f) - { + if (multiplier > 1.0f) { multiplier = 1.0f; } @@ -2070,42 +1825,34 @@ Keep view reasonably constrained in relation to gun -rww */ int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); -void CG_EmplacedView(vec3_t angles) -{ +void CG_EmplacedView(vec3_t angles) { float yaw; int override; - override = BG_EmplacedView(cg.refdef.viewangles, angles, &yaw, - cg_entities[cg.snap->ps.emplacedIndex].currentState.origin2[0]); + override = BG_EmplacedView(cg.refdef.viewangles, angles, &yaw, cg_entities[cg.snap->ps.emplacedIndex].currentState.origin2[0]); - if (override) - { - cg.refdef.viewangles[YAW] = yaw; + if (override) { + cg.refdef.viewangles[YAW] = yaw; AnglesToAxis(cg.refdef.viewangles, cg.refdef.viewaxis); - if (override == 2) - { + if (override == 2) { trap->SetClientForceAngle(cg.time + 5000, cg.refdef.viewangles); } } - //we want to constrain the predicted player state viewangles as well - override = BG_EmplacedView(cg.predictedPlayerState.viewangles, angles, &yaw, - cg_entities[cg.snap->ps.emplacedIndex].currentState.origin2[0]); - if (override) - { - cg.predictedPlayerState.viewangles[YAW] = yaw; + // we want to constrain the predicted player state viewangles as well + override = BG_EmplacedView(cg.predictedPlayerState.viewangles, angles, &yaw, cg_entities[cg.snap->ps.emplacedIndex].currentState.origin2[0]); + if (override) { + cg.predictedPlayerState.viewangles[YAW] = yaw; } } -//specially add cent's for automap -static void CG_AddRefentForAutoMap(centity_t *cent) -{ +// specially add cent's for automap +static void CG_AddRefentForAutoMap(centity_t *cent) { refEntity_t ent; vec3_t flat; - if (cent->currentState.eFlags & EF_NODRAW) - { + if (cent->currentState.eFlags & EF_NODRAW) { return; } @@ -2120,36 +1867,28 @@ static void CG_AddRefentForAutoMap(centity_t *cent) AnglesToAxis(flat, ent.axis); if (cent->ghoul2 && - (cent->currentState.eType == ET_PLAYER || - cent->currentState.eType == ET_NPC || - cent->currentState.modelGhoul2)) - { //using a ghoul2 model + (cent->currentState.eType == ET_PLAYER || cent->currentState.eType == ET_NPC || cent->currentState.modelGhoul2)) { // using a ghoul2 model ent.ghoul2 = cent->ghoul2; ent.radius = cent->currentState.g2radius; - if (!ent.radius) - { + if (!ent.radius) { ent.radius = 64.0f; } - } - else - { //then assume a standard indexed model + } else { // then assume a standard indexed model ent.hModel = cgs.gameModels[cent->currentState.modelindex]; } trap->R_AddRefEntityToScene(&ent); } -//add all entities that would be on the radar -void CG_AddRadarAutomapEnts(void) -{ +// add all entities that would be on the radar +void CG_AddRadarAutomapEnts(void) { int i = 0; - //first add yourself + // first add yourself CG_AddRefentForAutoMap(&cg_entities[cg.predictedPlayerState.clientNum]); - while (i < cg.radarEntityCount) - { + while (i < cg.radarEntityCount) { CG_AddRefentForAutoMap(&cg_entities[cg.radarEntities[i]]); i++; } @@ -2167,90 +1906,76 @@ float cg_autoMapZoomMainOffset = 0.0f; vec3_t cg_autoMapAngle = {90.0f, 0.0f, 0.0f}; autoMapInput_t cg_autoMapInput; int cg_autoMapInputTime = 0; -#define SIDEFRAME_WIDTH 16 -#define SIDEFRAME_HEIGHT 32 -void CG_DrawAutoMap(void) -{ - clientInfo_t *local; - refdef_t refdef; - trace_t tr; - vec3_t fwd; - vec3_t playerMins, playerMaxs; - int vWidth, vHeight; - float hScale, vScale; - float x, y, w, h; - - if (!r_autoMap.integer) - { //don't do anything then +#define SIDEFRAME_WIDTH 16 +#define SIDEFRAME_HEIGHT 32 +void CG_DrawAutoMap(void) { + clientInfo_t *local; + refdef_t refdef; + trace_t tr; + vec3_t fwd; + vec3_t playerMins, playerMaxs; + int vWidth, vHeight; + float hScale, vScale; + float x, y, w, h; + + if (!r_autoMap.integer) { // don't do anything then return; } - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { //don't show when dead + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { // don't show when dead return; } - if ( (cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR ) - { //don't show when spec + if ((cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR) { // don't show when spec return; } - local = &cgs.clientinfo[ cg.predictedPlayerState.clientNum ]; - if ( !local->infoValid ) - { //don't show if bad ci + local = &cgs.clientinfo[cg.predictedPlayerState.clientNum]; + if (!local->infoValid) { // don't show if bad ci return; } - if (cgs.gametype < GT_TEAM) - { //don't show in non-team gametypes + if (cgs.gametype < GT_TEAM) { // don't show in non-team gametypes return; } - if (cg_autoMapInputTime >= cg.time) - { - if (cg_autoMapInput.up) - { + if (cg_autoMapInputTime >= cg.time) { + if (cg_autoMapInput.up) { cg_autoMapZoom -= cg_autoMapInput.up; - if (cg_autoMapZoom < cg_autoMapZoomMainOffset+64.0f) - { - cg_autoMapZoom = cg_autoMapZoomMainOffset+64.0f; + if (cg_autoMapZoom < cg_autoMapZoomMainOffset + 64.0f) { + cg_autoMapZoom = cg_autoMapZoomMainOffset + 64.0f; } } - if (cg_autoMapInput.down) - { + if (cg_autoMapInput.down) { cg_autoMapZoom += cg_autoMapInput.down; - if (cg_autoMapZoom > cg_autoMapZoomMainOffset+4096.0f) - { - cg_autoMapZoom = cg_autoMapZoomMainOffset+4096.0f; + if (cg_autoMapZoom > cg_autoMapZoomMainOffset + 4096.0f) { + cg_autoMapZoom = cg_autoMapZoomMainOffset + 4096.0f; } } - if (cg_autoMapInput.yaw) - { + if (cg_autoMapInput.yaw) { cg_autoMapAngle[YAW] += cg_autoMapInput.yaw; } - if (cg_autoMapInput.pitch) - { + if (cg_autoMapInput.pitch) { cg_autoMapAngle[PITCH] += cg_autoMapInput.pitch; } - if (cg_autoMapInput.goToDefaults) - { + if (cg_autoMapInput.goToDefaults) { cg_autoMapZoom = 512.0f; VectorSet(cg_autoMapAngle, 90.0f, 0.0f, 0.0f); } } - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); - refdef.rdflags = (RDF_NOWORLDMODEL|RDF_AUTOMAP); + refdef.rdflags = (RDF_NOWORLDMODEL | RDF_AUTOMAP); VectorCopy(cg.predictedPlayerState.origin, refdef.vieworg); VectorCopy(cg_autoMapAngle, refdef.viewangles); - //scale out in the direction of the view angles base on the zoom factor + // scale out in the direction of the view angles base on the zoom factor AngleVectors(refdef.viewangles, fwd, 0, 0); VectorMA(refdef.vieworg, -cg_autoMapZoom, fwd, refdef.vieworg); @@ -2259,44 +1984,40 @@ void CG_DrawAutoMap(void) refdef.fov_x = 50; refdef.fov_y = 50; - //guess this doesn't need to be done every frame, but eh + // guess this doesn't need to be done every frame, but eh trap->R_GetRealRes(&vWidth, &vHeight); - //set scaling values so that the 640x480 will result at 1.0/1.0 - hScale = vWidth/640.0f; - vScale = vHeight/480.0f; + // set scaling values so that the 640x480 will result at 1.0/1.0 + hScale = vWidth / 640.0f; + vScale = vHeight / 480.0f; x = r_autoMapX.value; y = r_autoMapY.value; w = r_autoMapW.value; h = r_autoMapH.value; - refdef.x = x*hScale; - refdef.y = y*vScale; - refdef.width = w*hScale; - refdef.height = h*vScale; + refdef.x = x * hScale; + refdef.y = y * vScale; + refdef.width = w * hScale; + refdef.height = h * vScale; - CG_DrawPic(x-SIDEFRAME_WIDTH, y, SIDEFRAME_WIDTH, h, cgs.media.wireframeAutomapFrame_left); - CG_DrawPic(x+w, y, SIDEFRAME_WIDTH, h, cgs.media.wireframeAutomapFrame_right); - CG_DrawPic(x-SIDEFRAME_WIDTH, y-SIDEFRAME_HEIGHT, w+(SIDEFRAME_WIDTH*2), SIDEFRAME_HEIGHT, cgs.media.wireframeAutomapFrame_top); - CG_DrawPic(x-SIDEFRAME_WIDTH, y+h, w+(SIDEFRAME_WIDTH*2), SIDEFRAME_HEIGHT, cgs.media.wireframeAutomapFrame_bottom); + CG_DrawPic(x - SIDEFRAME_WIDTH, y, SIDEFRAME_WIDTH, h, cgs.media.wireframeAutomapFrame_left); + CG_DrawPic(x + w, y, SIDEFRAME_WIDTH, h, cgs.media.wireframeAutomapFrame_right); + CG_DrawPic(x - SIDEFRAME_WIDTH, y - SIDEFRAME_HEIGHT, w + (SIDEFRAME_WIDTH * 2), SIDEFRAME_HEIGHT, cgs.media.wireframeAutomapFrame_top); + CG_DrawPic(x - SIDEFRAME_WIDTH, y + h, w + (SIDEFRAME_WIDTH * 2), SIDEFRAME_HEIGHT, cgs.media.wireframeAutomapFrame_bottom); refdef.time = cg.time; trap->R_ClearScene(); CG_AddRadarAutomapEnts(); - if (cg.predictedPlayerState.m_iVehicleNum && - cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState.eType == ET_NPC && + if (cg.predictedPlayerState.m_iVehicleNum && cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState.eType == ET_NPC && cg_entities[cg.predictedPlayerState.m_iVehicleNum].currentState.NPC_class == CLASS_VEHICLE && cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle && - cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //constantly adjust to current height + cg_entities[cg.predictedPlayerState.m_iVehicleNum].m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // constantly adjust to current height trap->R_AutomapElevationAdjustment(cg.predictedPlayerState.origin[2]); - } - else - { - //Trace down and set the ground elevation as the main automap elevation point + } else { + // Trace down and set the ground elevation as the main automap elevation point VectorSet(playerMins, -15, -15, DEFAULT_MINS_2); VectorSet(playerMaxs, 15, 15, DEFAULT_MAXS_2); @@ -2304,12 +2025,11 @@ void CG_DrawAutoMap(void) fwd[2] -= 4096.0f; CG_Trace(&tr, cg.predictedPlayerState.origin, playerMins, playerMaxs, fwd, cg.predictedPlayerState.clientNum, MASK_SOLID); - if (!tr.startsolid && !tr.allsolid) - { + if (!tr.startsolid && !tr.allsolid) { trap->R_AutomapElevationAdjustment(tr.endpos[2]); } } - trap->R_RenderScene( &refdef ); + trap->R_RenderScene(&refdef); } //========================================================================= @@ -2329,69 +2049,69 @@ static plane_t frustum[4]; // // CG_SetupFrustum // -void CG_SetupFrustum( void ) { +void CG_SetupFrustum(void) { int i; float xs, xc; float ang; ang = cg.refdef.fov_x / 180 * M_PI * 0.5f; - xs = sin( ang ); - xc = cos( ang ); + xs = sin(ang); + xc = cos(ang); - VectorScale( cg.refdef.viewaxis[0], xs, frustum[0].normal ); - VectorMA( frustum[0].normal, xc, cg.refdef.viewaxis[1], frustum[0].normal ); + VectorScale(cg.refdef.viewaxis[0], xs, frustum[0].normal); + VectorMA(frustum[0].normal, xc, cg.refdef.viewaxis[1], frustum[0].normal); - VectorScale( cg.refdef.viewaxis[0], xs, frustum[1].normal ); - VectorMA( frustum[1].normal, -xc, cg.refdef.viewaxis[1], frustum[1].normal ); + VectorScale(cg.refdef.viewaxis[0], xs, frustum[1].normal); + VectorMA(frustum[1].normal, -xc, cg.refdef.viewaxis[1], frustum[1].normal); ang = cg.refdef.fov_y / 180 * M_PI * 0.5f; - xs = sin( ang ); - xc = cos( ang ); + xs = sin(ang); + xc = cos(ang); - VectorScale( cg.refdef.viewaxis[0], xs, frustum[2].normal ); - VectorMA( frustum[2].normal, xc, cg.refdef.viewaxis[2], frustum[2].normal ); + VectorScale(cg.refdef.viewaxis[0], xs, frustum[2].normal); + VectorMA(frustum[2].normal, xc, cg.refdef.viewaxis[2], frustum[2].normal); - VectorScale( cg.refdef.viewaxis[0], xs, frustum[3].normal ); - VectorMA( frustum[3].normal, -xc, cg.refdef.viewaxis[2], frustum[3].normal ); + VectorScale(cg.refdef.viewaxis[0], xs, frustum[3].normal); + VectorMA(frustum[3].normal, -xc, cg.refdef.viewaxis[2], frustum[3].normal); - for ( i = 0 ; i < 4 ; i++ ) { - frustum[i].dist = DotProduct( cg.refdef.vieworg, frustum[i].normal ); + for (i = 0; i < 4; i++) { + frustum[i].dist = DotProduct(cg.refdef.vieworg, frustum[i].normal); } } // // CG_CullPoint - returns true if culled // -qboolean CG_CullPoint( vec3_t pt ) { +qboolean CG_CullPoint(vec3_t pt) { int i; plane_t *frust; // check against frustum planes - for ( i = 0 ; i < 4 ; i++ ) { + for (i = 0; i < 4; i++) { frust = &frustum[i]; - if ( ( DotProduct( pt, frust->normal ) - frust->dist ) < 0 ) { - return( qtrue ); + if ((DotProduct(pt, frust->normal) - frust->dist) < 0) { + return (qtrue); } } - return( qfalse ); + return (qfalse); } -qboolean CG_CullPointAndRadius( const vec3_t pt, float radius ) { +qboolean CG_CullPointAndRadius(const vec3_t pt, float radius) { int i; plane_t *frust; // check against frustum planes - for ( i = 0 ; i < 4 ; i++ ) { + for (i = 0; i < 4; i++) { frust = &frustum[i]; - if ( ( DotProduct( pt, frust->normal ) - frust->dist ) < -radius ) { - return( qtrue ); + if ((DotProduct(pt, frust->normal) - frust->dist) < -radius) { + return (qtrue); } } - return( qfalse ); + return (qfalse); } //========================================================================= @@ -2403,19 +2123,19 @@ CG_DrawActiveFrame Generates and draws a game scene and status information at the given time. ================= */ -static qboolean cg_rangedFogging = qfalse; //so we know if we should go back to normal fog -float cg_linearFogOverride = 0.0f; //designer-specified override for linear fogging style +static qboolean cg_rangedFogging = qfalse; // so we know if we should go back to normal fog +float cg_linearFogOverride = 0.0f; // designer-specified override for linear fogging style -extern void BG_VehicleTurnRateForSpeed( Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride ); -extern qboolean PM_InKnockDown( playerState_t *ps ); +extern void BG_VehicleTurnRateForSpeed(Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride); +extern qboolean PM_InKnockDown(playerState_t *ps); extern qboolean cgQueueLoad; -extern void CG_ActualLoadDeferredPlayers( void ); +extern void CG_ActualLoadDeferredPlayers(void); static int cg_siegeClassIndex = -2; -void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback ) { - int inwater; +void CG_DrawActiveFrame(int serverTime, stereoFrame_t stereoView, qboolean demoPlayback) { + int inwater; const char *cstr; float mSensitivity = cg.zoomSensitivity; float mPitchOverride = 0.0f; @@ -2424,11 +2144,10 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo #ifdef VEH_CONTROL_SCHEME_4 float mSensitivityOverride = 0.0f; qboolean bUseFighterPitch = qfalse; - qboolean isFighter = qfalse; + qboolean isFighter = qfalse; #endif - if (cgQueueLoad) - { //do this before you start messing around with adding ghoul2 refents and crap + if (cgQueueLoad) { // do this before you start messing around with adding ghoul2 refents and crap CG_ActualLoadDeferredPlayers(); cgQueueLoad = qfalse; } @@ -2436,21 +2155,14 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo cg.time = serverTime; cg.demoPlayback = demoPlayback; - if (cg.snap && ui_myteam.integer != cg.snap->ps.persistant[PERS_TEAM]) - { - trap->Cvar_Set ( "ui_myteam", va("%i", cg.snap->ps.persistant[PERS_TEAM]) ); + if (cg.snap && ui_myteam.integer != cg.snap->ps.persistant[PERS_TEAM]) { + trap->Cvar_Set("ui_myteam", va("%i", cg.snap->ps.persistant[PERS_TEAM])); } - if (cgs.gametype == GT_SIEGE && - cg.snap && - cg_siegeClassIndex != cgs.clientinfo[cg.snap->ps.clientNum].siegeIndex) - { + if (cgs.gametype == GT_SIEGE && cg.snap && cg_siegeClassIndex != cgs.clientinfo[cg.snap->ps.clientNum].siegeIndex) { cg_siegeClassIndex = cgs.clientinfo[cg.snap->ps.clientNum].siegeIndex; - if (cg_siegeClassIndex == -1) - { + if (cg_siegeClassIndex == -1) { trap->Cvar_Set("ui_mySiegeClass", ""); - } - else - { + } else { trap->Cvar_Set("ui_mySiegeClass", bgSiegeClasses[cg_siegeClassIndex].name); } } @@ -2460,12 +2172,12 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo // if we are only updating the screen as a loading // pacifier, don't even try to read snapshots - if ( cg.infoScreenText[0] != 0 ) { + if (cg.infoScreenText[0] != 0) { CG_DrawInformation(); return; } - trap->FX_AdjustTime( cg.time ); + trap->FX_AdjustTime(cg.time); CG_RunLightStyles(); @@ -2483,8 +2195,7 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo // if we haven't received any snapshots yet, all // we can draw is the information screen - if ( !cg.snap || ( cg.snap->snapFlags & SNAPFLAG_NOT_ACTIVE ) ) - { + if (!cg.snap || (cg.snap->snapFlags & SNAPFLAG_NOT_ACTIVE)) { #if 0 // Transition from zero to negative one on the snapshot timeout. // The reason we do this is because the first client frame is responsible for @@ -2513,52 +2224,39 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo } // let the client system know what our weapon and zoom settings are - if (cg.snap && cg.snap->ps.saberLockTime > cg.time) - { + if (cg.snap && cg.snap->ps.saberLockTime > cg.time) { mSensitivity = 0.01f; - } - else if (cg.predictedPlayerState.weapon == WP_EMPLACED_GUN) - { //lower sens for emplaced guns and vehicles + } else if (cg.predictedPlayerState.weapon == WP_EMPLACED_GUN) { // lower sens for emplaced guns and vehicles mSensitivity = 0.2f; } #ifdef VEH_CONTROL_SCHEME_4 - else if (cg.predictedPlayerState.m_iVehicleNum//in a vehicle - && !cg.predictedPlayerState.generic1 )//not as a passenger + else if (cg.predictedPlayerState.m_iVehicleNum // in a vehicle + && !cg.predictedPlayerState.generic1) // not as a passenger { centity_t *cent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; - if ( cent->m_pVehicle - && cent->m_pVehicle->m_pVehicleInfo - && cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - { - BG_VehicleTurnRateForSpeed( cent->m_pVehicle, cent->currentState.speed, &mPitchOverride, &mYawOverride ); - //mSensitivityOverride = 5.0f;//old default value + if (cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo && cent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { + BG_VehicleTurnRateForSpeed(cent->m_pVehicle, cent->currentState.speed, &mPitchOverride, &mYawOverride); + // mSensitivityOverride = 5.0f;//old default value mSensitivityOverride = 0.0f; bUseFighterPitch = qtrue; - trap->SetUserCmdValue( cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, mSensitivityOverride, cg.forceSelect, cg.itemSelect, bUseFighterPitch ); + trap->SetUserCmdValue(cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, mSensitivityOverride, cg.forceSelect, cg.itemSelect, + bUseFighterPitch); isFighter = qtrue; } } - if ( !isFighter ) -#endif //VEH_CONTROL_SCHEME_4 + if (!isFighter) +#endif // VEH_CONTROL_SCHEME_4 { - if (cg.predictedPlayerState.m_iVehicleNum) - { + if (cg.predictedPlayerState.m_iVehicleNum) { veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum]; } - if (veh && - veh->currentState.eType == ET_NPC && - veh->currentState.NPC_class == CLASS_VEHICLE && - veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && - bg_fighterAltControl.integer) - { - trap->SetUserCmdValue( cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, 0.0f, cg.forceSelect, cg.itemSelect, qtrue ); - veh = NULL; //this is done because I don't want an extra assign each frame because I am so perfect and super efficient. - } - else - { - trap->SetUserCmdValue( cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, 0.0f, cg.forceSelect, cg.itemSelect, qfalse ); + if (veh && veh->currentState.eType == ET_NPC && veh->currentState.NPC_class == CLASS_VEHICLE && veh->m_pVehicle && + veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && bg_fighterAltControl.integer) { + trap->SetUserCmdValue(cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, 0.0f, cg.forceSelect, cg.itemSelect, qtrue); + veh = NULL; // this is done because I don't want an extra assign each frame because I am so perfect and super efficient. + } else { + trap->SetUserCmdValue(cg.weaponSelect, mSensitivity, mPitchOverride, mYawOverride, 0.0f, cg.forceSelect, cg.itemSelect, qfalse); } } @@ -2571,18 +2269,15 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo // decide on third person view cg.renderingThirdPerson = cg_thirdPerson.integer || (cg.snap->ps.stats[STAT_HEALTH] <= 0); - if (cg.snap->ps.stats[STAT_HEALTH] > 0) - { + if (cg.snap->ps.stats[STAT_HEALTH] > 0) { if (cg.predictedPlayerState.weapon == WP_EMPLACED_GUN && cg.predictedPlayerState.emplacedIndex /*&& cg_entities[cg.predictedPlayerState.emplacedIndex].currentState.weapon == WP_NONE*/) { //force third person for e-web and emplaced use cg.renderingThirdPerson = 1; - } - else if (cg.predictedPlayerState.weapon == WP_SABER || cg.predictedPlayerState.weapon == WP_MELEE || - BG_InGrappleMove(cg.predictedPlayerState.torsoAnim) || BG_InGrappleMove(cg.predictedPlayerState.legsAnim) || - cg.predictedPlayerState.forceHandExtend == HANDEXTEND_KNOCKDOWN || cg.predictedPlayerState.fallingToDeath || - cg.predictedPlayerState.m_iVehicleNum || PM_InKnockDown(&cg.predictedPlayerState)) - { + } else if (cg.predictedPlayerState.weapon == WP_SABER || cg.predictedPlayerState.weapon == WP_MELEE || + BG_InGrappleMove(cg.predictedPlayerState.torsoAnim) || BG_InGrappleMove(cg.predictedPlayerState.legsAnim) || + cg.predictedPlayerState.forceHandExtend == HANDEXTEND_KNOCKDOWN || cg.predictedPlayerState.fallingToDeath || + cg.predictedPlayerState.m_iVehicleNum || PM_InKnockDown(&cg.predictedPlayerState)) { #if 0 if (cg_fpls.integer && cg.predictedPlayerState.weapon == WP_SABER) { //force to first person for fpls @@ -2590,23 +2285,17 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo } else #endif - { - cg.renderingThirdPerson = 1; - } - } - else if (cg.snap->ps.zoomMode) - { //always force first person when zoomed + { cg.renderingThirdPerson = 1; } + } else if (cg.snap->ps.zoomMode) { // always force first person when zoomed cg.renderingThirdPerson = 0; } } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { //always first person for spec + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { // always first person for spec cg.renderingThirdPerson = 0; } - if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR) - { + if (cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR) { cg.renderingThirdPerson = 0; } @@ -2614,46 +2303,39 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo inwater = CG_CalcViewValues(); CG_SetupFrustum(); - if (cg_linearFogOverride) - { + if (cg_linearFogOverride) { trap->R_SetRangedFog(-cg_linearFogOverride); - } - else if (cg.predictedPlayerState.zoomMode) - { //zooming with binoculars or sniper, set the fog range based on the zoom level -rww + } else if (cg.predictedPlayerState.zoomMode) { // zooming with binoculars or sniper, set the fog range based on the zoom level -rww cg_rangedFogging = qtrue; - //smaller the fov the less fog we have between the view and cull dist - trap->R_SetRangedFog(cg.refdef.fov_x*64.0f); - } - else if (cg_rangedFogging) - { //disable it + // smaller the fov the less fog we have between the view and cull dist + trap->R_SetRangedFog(cg.refdef.fov_x * 64.0f); + } else if (cg_rangedFogging) { // disable it cg_rangedFogging = qfalse; trap->R_SetRangedFog(0.0f); } cstr = CG_ConfigString(CS_SKYBOXORG); - if (cstr && cstr[0]) - { //we have a skyportal + if (cstr && cstr[0]) { // we have a skyportal CG_DrawSkyBoxPortal(cstr); } CG_CalcScreenEffects(); // first person blend blobs, done after AnglesToAxis - if ( !cg.renderingThirdPerson && cg.predictedPlayerState.pm_type != PM_SPECTATOR ) { + if (!cg.renderingThirdPerson && cg.predictedPlayerState.pm_type != PM_SPECTATOR) { CG_DamageBlendBlob(); } // build the render lists - if ( !cg.hyperspace ) { - CG_AddPacketEntities(qfalse); // adter calcViewValues, so predicted player state is correct + if (!cg.hyperspace) { + CG_AddPacketEntities(qfalse); // adter calcViewValues, so predicted player state is correct CG_AddMarks(); CG_AddLocalEntities(); } - CG_AddViewWeapon( &cg.predictedPlayerState ); + CG_AddViewWeapon(&cg.predictedPlayerState); - if ( !cg.hyperspace) - { + if (!cg.hyperspace) { trap->FX_AddScheduledEffects(qfalse); } @@ -2661,11 +2343,11 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo CG_PlayBufferedSounds(); // finish up the rest of the refdef - if ( cg.testModelEntity.hModel ) { + if (cg.testModelEntity.hModel) { CG_AddTestModel(); } cg.refdef.time = cg.time; - memcpy( cg.refdef.areamask, cg.snap->areamask, sizeof( cg.refdef.areamask ) ); + memcpy(cg.refdef.areamask, cg.snap->areamask, sizeof(cg.refdef.areamask)); // warning sounds when powerup is wearing off CG_PowerupTimerSounds(); @@ -2673,8 +2355,7 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo // if there are any entities flagged as sound trackers and attached to other entities, update their sound pos CG_UpdateSoundTrackers(); - if (gCGHasFallVector) - { + if (gCGHasFallVector) { vec3_t lookAng; VectorSubtract(cg.snap->ps.origin, cg.refdef.vieworg, lookAng); @@ -2685,21 +2366,20 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo AnglesToAxis(lookAng, cg.refdef.viewaxis); } - //This is done from the vieworg to get origin for non-attenuated sounds - cstr = CG_ConfigString( CS_GLOBAL_AMBIENT_SET ); + // This is done from the vieworg to get origin for non-attenuated sounds + cstr = CG_ConfigString(CS_GLOBAL_AMBIENT_SET); - if (cstr && cstr[0]) - { - trap->S_UpdateAmbientSet( cstr, cg.refdef.vieworg ); + if (cstr && cstr[0]) { + trap->S_UpdateAmbientSet(cstr, cg.refdef.vieworg); } // update audio positions - trap->S_Respatialize( cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater ); + trap->S_Respatialize(cg.snap->ps.clientNum, cg.refdef.vieworg, cg.refdef.viewaxis, inwater); // make sure the lagometerSample and frame timing isn't done twice when in stereo - if ( stereoView != STEREO_RIGHT ) { + if (stereoView != STEREO_RIGHT) { cg.frametime = cg.time - cg.oldTime; - if ( cg.frametime < 0 ) { + if (cg.frametime < 0) { cg.frametime = 0; } cg.oldTime = cg.time; @@ -2710,8 +2390,7 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo timescale.value += cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000; if (timescale.value > cg_timescaleFadeEnd.value) timescale.value = cg_timescaleFadeEnd.value; - } - else { + } else { timescale.value -= cg_timescaleFadeSpeed.value * ((float)cg.frametime) / 1000; if (timescale.value < cg_timescaleFadeEnd.value) timescale.value = cg_timescaleFadeEnd.value; @@ -2722,12 +2401,11 @@ void CG_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demo } // actually issue the rendering calls - CG_DrawActive( stereoView ); + CG_DrawActive(stereoView); CG_DrawAutoMap(); - if ( cg_stats.integer ) { - trap->Print( "cg.clientFrame:%i\n", cg.clientFrame ); + if (cg_stats.integer) { + trap->Print("cg.clientFrame:%i\n", cg.clientFrame); } } - diff --git a/codemp/cgame/cg_weaponinit.c b/codemp/cgame/cg_weaponinit.c index 88259344f3..db21224cdb 100644 --- a/codemp/cgame/cg_weaponinit.c +++ b/codemp/cgame/cg_weaponinit.c @@ -25,7 +25,6 @@ along with this program; if not, see . #include "cg_local.h" #include "fx_local.h" - /* ================= CG_RegisterWeapon @@ -33,124 +32,109 @@ CG_RegisterWeapon The server says this item is used on this level ================= */ -void CG_RegisterWeapon( int weaponNum) { - weaponInfo_t *weaponInfo; - gitem_t *item, *ammo; - char path[MAX_QPATH]; - vec3_t mins, maxs; - int i; - - if ( weaponNum <= WP_NONE || weaponNum >= WP_NUM_WEAPONS ) { +void CG_RegisterWeapon(int weaponNum) { + weaponInfo_t *weaponInfo; + gitem_t *item, *ammo; + char path[MAX_QPATH]; + vec3_t mins, maxs; + int i; + + if (weaponNum <= WP_NONE || weaponNum >= WP_NUM_WEAPONS) { return; } weaponInfo = &cg_weapons[weaponNum]; - if ( weaponInfo->registered ) { + if (weaponInfo->registered) { return; } - //if ( cgs.wDisable & (1<registered = qtrue; - for ( item = bg_itemlist + 1 ; item->classname ; item++ ) { - if ( item->giType == IT_WEAPON && item->giTag == weaponNum ) { + for (item = bg_itemlist + 1; item->classname; item++) { + if (item->giType == IT_WEAPON && item->giTag == weaponNum) { weaponInfo->item = item; break; } } - if ( !item->classname ) { - trap->Error( ERR_DROP, "Couldn't find weapon %i", weaponNum ); + if (!item->classname) { + trap->Error(ERR_DROP, "Couldn't find weapon %i", weaponNum); } - CG_RegisterItemVisuals( item - bg_itemlist ); + CG_RegisterItemVisuals(item - bg_itemlist); // load cmodel before model so filecache works - weaponInfo->weaponModel = trap->R_RegisterModel( item->world_model[0] ); + weaponInfo->weaponModel = trap->R_RegisterModel(item->world_model[0]); // load in-view model also weaponInfo->viewModel = trap->R_RegisterModel(item->view_model); // calc midpoint for rotation - trap->R_ModelBounds( weaponInfo->weaponModel, mins, maxs ); - for ( i = 0 ; i < 3 ; i++ ) { - weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * ( maxs[i] - mins[i] ); + trap->R_ModelBounds(weaponInfo->weaponModel, mins, maxs); + for (i = 0; i < 3; i++) { + weaponInfo->weaponMidpoint[i] = mins[i] + 0.5 * (maxs[i] - mins[i]); } - weaponInfo->weaponIcon = trap->R_RegisterShader( item->icon ); - weaponInfo->ammoIcon = trap->R_RegisterShader( item->icon ); + weaponInfo->weaponIcon = trap->R_RegisterShader(item->icon); + weaponInfo->ammoIcon = trap->R_RegisterShader(item->icon); - for ( ammo = bg_itemlist + 1 ; ammo->classname ; ammo++ ) { - if ( ammo->giType == IT_AMMO && ammo->giTag == weaponNum ) { + for (ammo = bg_itemlist + 1; ammo->classname; ammo++) { + if (ammo->giType == IT_AMMO && ammo->giTag == weaponNum) { break; } } - if ( ammo->classname && ammo->world_model[0] ) { - weaponInfo->ammoModel = trap->R_RegisterModel( ammo->world_model[0] ); + if (ammo->classname && ammo->world_model[0]) { + weaponInfo->ammoModel = trap->R_RegisterModel(ammo->world_model[0]); } -// strcpy( path, item->view_model ); -// COM_StripExtension( path, path ); -// strcat( path, "_flash.md3" ); - weaponInfo->flashModel = 0;//trap->R_RegisterModel( path ); - - if (weaponNum == WP_DISRUPTOR || - weaponNum == WP_FLECHETTE || - weaponNum == WP_REPEATER || - weaponNum == WP_ROCKET_LAUNCHER || - weaponNum == WP_CONCUSSION) - { - Q_strncpyz( path, item->view_model, sizeof(path) ); - COM_StripExtension( path, path, sizeof( path ) ); - Q_strcat( path, sizeof(path), "_barrel.md3" ); - weaponInfo->barrelModel = trap->R_RegisterModel( path ); - } - else if (weaponNum == WP_STUN_BATON) - { //only weapon with more than 1 barrel.. + // strcpy( path, item->view_model ); + // COM_StripExtension( path, path ); + // strcat( path, "_flash.md3" ); + weaponInfo->flashModel = 0; // trap->R_RegisterModel( path ); + + if (weaponNum == WP_DISRUPTOR || weaponNum == WP_FLECHETTE || weaponNum == WP_REPEATER || weaponNum == WP_ROCKET_LAUNCHER || weaponNum == WP_CONCUSSION) { + Q_strncpyz(path, item->view_model, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + Q_strcat(path, sizeof(path), "_barrel.md3"); + weaponInfo->barrelModel = trap->R_RegisterModel(path); + } else if (weaponNum == WP_STUN_BATON) { // only weapon with more than 1 barrel.. trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel.md3"); trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel2.md3"); trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel3.md3"); - } - else - { + } else { weaponInfo->barrelModel = 0; } - if (weaponNum != WP_SABER) - { - Q_strncpyz( path, item->view_model, sizeof(path) ); - COM_StripExtension( path, path, sizeof( path ) ); - Q_strcat( path, sizeof(path), "_hand.md3" ); - weaponInfo->handsModel = trap->R_RegisterModel( path ); - } - else - { + if (weaponNum != WP_SABER) { + Q_strncpyz(path, item->view_model, sizeof(path)); + COM_StripExtension(path, path, sizeof(path)); + Q_strcat(path, sizeof(path), "_hand.md3"); + weaponInfo->handsModel = trap->R_RegisterModel(path); + } else { weaponInfo->handsModel = 0; } -// if ( !weaponInfo->handsModel ) { -// weaponInfo->handsModel = trap->R_RegisterModel( "models/weapons2/shotgun/shotgun_hand.md3" ); -// } + // if ( !weaponInfo->handsModel ) { + // weaponInfo->handsModel = trap->R_RegisterModel( "models/weapons2/shotgun/shotgun_hand.md3" ); + // } - switch ( weaponNum ) { + switch (weaponNum) { case WP_STUN_BATON: case WP_MELEE: -/* MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f ); - weaponInfo->firingSound = trap->S_RegisterSound( "sound/weapons/saber/saberhum.wav" ); -// weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/melee/fstatck.wav" ); -*/ - //trap->R_RegisterShader( "gfx/effects/stunPass" ); - trap->FX_RegisterEffect( "stunBaton/flesh_impact" ); - - if (weaponNum == WP_STUN_BATON) - { - trap->S_RegisterSound( "sound/weapons/baton/idle.wav" ); - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/baton/fire.mp3" ); - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/baton/fire.mp3" ); - } - else - { + /* MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f ); + weaponInfo->firingSound = trap->S_RegisterSound( "sound/weapons/saber/saberhum.wav" ); + // weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/melee/fstatck.wav" ); + */ + // trap->R_RegisterShader( "gfx/effects/stunPass" ); + trap->FX_RegisterEffect("stunBaton/flesh_impact"); + + if (weaponNum == WP_STUN_BATON) { + trap->S_RegisterSound("sound/weapons/baton/idle.wav"); + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/baton/fire.mp3"); + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/baton/fire.mp3"); + } else { /* int j = 0; @@ -161,83 +145,83 @@ void CG_RegisterWeapon( int weaponNum) { j++; } */ - //No longer needed, animsound config plays them for us + // No longer needed, animsound config plays them for us } break; case WP_SABER: - MAKERGB( weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f ); - weaponInfo->firingSound = trap->S_RegisterSound( "sound/weapons/saber/saberhum1.wav" ); - weaponInfo->missileModel = trap->R_RegisterModel( DEFAULT_SABER_MODEL ); + MAKERGB(weaponInfo->flashDlightColor, 0.6f, 0.6f, 1.0f); + weaponInfo->firingSound = trap->S_RegisterSound("sound/weapons/saber/saberhum1.wav"); + weaponInfo->missileModel = trap->R_RegisterModel(DEFAULT_SABER_MODEL); break; case WP_CONCUSSION: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/concussion/select.wav"); - - weaponInfo->flashSound[0] = NULL_SOUND; - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "concussion/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; - //weaponInfo->missileDlightColor= {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_ConcussionProjectileThink; - - weaponInfo->altFlashSound[0] = NULL_SOUND; - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = trap->S_RegisterSound( "sound/weapons/bryar/altcharge.wav"); - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "concussion/altmuzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; - //weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/concussion/select.wav"); + + weaponInfo->flashSound[0] = NULL_SOUND; + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("concussion/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor= {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_ConcussionProjectileThink; + + weaponInfo->altFlashSound[0] = NULL_SOUND; + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/bryar/altcharge.wav"); + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("concussion/altmuzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_ConcussionProjectileThink; - cgs.effects.disruptorAltMissEffect = trap->FX_RegisterEffect( "disruptor/alt_miss" ); + cgs.effects.disruptorAltMissEffect = trap->FX_RegisterEffect("disruptor/alt_miss"); - cgs.effects.concussionShotEffect = trap->FX_RegisterEffect( "concussion/shot" ); - cgs.effects.concussionImpactEffect = trap->FX_RegisterEffect( "concussion/explosion" ); + cgs.effects.concussionShotEffect = trap->FX_RegisterEffect("concussion/shot"); + cgs.effects.concussionImpactEffect = trap->FX_RegisterEffect("concussion/explosion"); trap->R_RegisterShader("gfx/effects/blueLine"); trap->R_RegisterShader("gfx/misc/whiteline2"); break; case WP_BRYAR_PISTOL: case WP_BRYAR_OLD: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/bryar/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/bryar/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "bryar/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; - //weaponInfo->missileDlightColor= {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_BryarProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/bryar/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = trap->S_RegisterSound( "sound/weapons/bryar/altcharge.wav"); - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "bryar/muzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; - //weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/bryar/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/bryar/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("bryar/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor= {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_BryarProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/bryar/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/bryar/altcharge.wav"); + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("bryar/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_BryarAltProjectileThink; - cgs.effects.bryarShotEffect = trap->FX_RegisterEffect( "bryar/shot" ); - cgs.effects.bryarPowerupShotEffect = trap->FX_RegisterEffect( "bryar/crackleShot" ); - cgs.effects.bryarWallImpactEffect = trap->FX_RegisterEffect( "bryar/wall_impact" ); - cgs.effects.bryarWallImpactEffect2 = trap->FX_RegisterEffect( "bryar/wall_impact2" ); - cgs.effects.bryarWallImpactEffect3 = trap->FX_RegisterEffect( "bryar/wall_impact3" ); - cgs.effects.bryarFleshImpactEffect = trap->FX_RegisterEffect( "bryar/flesh_impact" ); - cgs.effects.bryarDroidImpactEffect = trap->FX_RegisterEffect( "bryar/droid_impact" ); + cgs.effects.bryarShotEffect = trap->FX_RegisterEffect("bryar/shot"); + cgs.effects.bryarPowerupShotEffect = trap->FX_RegisterEffect("bryar/crackleShot"); + cgs.effects.bryarWallImpactEffect = trap->FX_RegisterEffect("bryar/wall_impact"); + cgs.effects.bryarWallImpactEffect2 = trap->FX_RegisterEffect("bryar/wall_impact2"); + cgs.effects.bryarWallImpactEffect3 = trap->FX_RegisterEffect("bryar/wall_impact3"); + cgs.effects.bryarFleshImpactEffect = trap->FX_RegisterEffect("bryar/flesh_impact"); + cgs.effects.bryarDroidImpactEffect = trap->FX_RegisterEffect("bryar/droid_impact"); - cgs.media.bryarFrontFlash = trap->R_RegisterShader( "gfx/effects/bryarFrontFlash" ); + cgs.media.bryarFrontFlash = trap->R_RegisterShader("gfx/effects/bryarFrontFlash"); // Note these are temp shared effects trap->FX_RegisterEffect("blaster/wall_impact.efx"); @@ -246,373 +230,373 @@ void CG_RegisterWeapon( int weaponNum) { break; case WP_BLASTER: - case WP_EMPLACED_GUN: //rww - just use the same as this for now.. - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/blaster/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/blaster/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "blaster/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_BlasterProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/blaster/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "blaster/muzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + case WP_EMPLACED_GUN: // rww - just use the same as this for now.. + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/blaster/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/blaster/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("blaster/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_BlasterProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/blaster/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("blaster/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_BlasterProjectileThink; - trap->FX_RegisterEffect( "blaster/deflect" ); - cgs.effects.blasterShotEffect = trap->FX_RegisterEffect( "blaster/shot" ); - cgs.effects.blasterWallImpactEffect = trap->FX_RegisterEffect( "blaster/wall_impact" ); - cgs.effects.blasterFleshImpactEffect = trap->FX_RegisterEffect( "blaster/flesh_impact" ); - cgs.effects.blasterDroidImpactEffect = trap->FX_RegisterEffect( "blaster/droid_impact" ); + trap->FX_RegisterEffect("blaster/deflect"); + cgs.effects.blasterShotEffect = trap->FX_RegisterEffect("blaster/shot"); + cgs.effects.blasterWallImpactEffect = trap->FX_RegisterEffect("blaster/wall_impact"); + cgs.effects.blasterFleshImpactEffect = trap->FX_RegisterEffect("blaster/flesh_impact"); + cgs.effects.blasterDroidImpactEffect = trap->FX_RegisterEffect("blaster/droid_impact"); break; case WP_DISRUPTOR: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/disruptor/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/disruptor/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "disruptor/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = 0; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/disruptor/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/disruptor/altCharge.wav"); - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "disruptor/muzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/disruptor/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/disruptor/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("disruptor/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = 0; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/disruptor/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/disruptor/altCharge.wav"); + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("disruptor/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = 0; - cgs.effects.disruptorRingsEffect = trap->FX_RegisterEffect( "disruptor/rings" ); - cgs.effects.disruptorProjectileEffect = trap->FX_RegisterEffect( "disruptor/projectile" ); - cgs.effects.disruptorWallImpactEffect = trap->FX_RegisterEffect( "disruptor/wall_impact" ); - cgs.effects.disruptorFleshImpactEffect = trap->FX_RegisterEffect( "disruptor/flesh_impact" ); - cgs.effects.disruptorAltMissEffect = trap->FX_RegisterEffect( "disruptor/alt_miss" ); - cgs.effects.disruptorAltHitEffect = trap->FX_RegisterEffect( "disruptor/alt_hit" ); + cgs.effects.disruptorRingsEffect = trap->FX_RegisterEffect("disruptor/rings"); + cgs.effects.disruptorProjectileEffect = trap->FX_RegisterEffect("disruptor/projectile"); + cgs.effects.disruptorWallImpactEffect = trap->FX_RegisterEffect("disruptor/wall_impact"); + cgs.effects.disruptorFleshImpactEffect = trap->FX_RegisterEffect("disruptor/flesh_impact"); + cgs.effects.disruptorAltMissEffect = trap->FX_RegisterEffect("disruptor/alt_miss"); + cgs.effects.disruptorAltHitEffect = trap->FX_RegisterEffect("disruptor/alt_hit"); - trap->R_RegisterShader( "gfx/effects/redLine" ); - trap->R_RegisterShader( "gfx/misc/whiteline2" ); - trap->R_RegisterShader( "gfx/effects/smokeTrail" ); + trap->R_RegisterShader("gfx/effects/redLine"); + trap->R_RegisterShader("gfx/misc/whiteline2"); + trap->R_RegisterShader("gfx/effects/smokeTrail"); trap->S_RegisterSound("sound/weapons/disruptor/zoomstart.wav"); trap->S_RegisterSound("sound/weapons/disruptor/zoomend.wav"); // Disruptor gun zoom interface - cgs.media.disruptorMask = trap->R_RegisterShader( "gfx/2d/cropCircle2"); - cgs.media.disruptorInsert = trap->R_RegisterShader( "gfx/2d/cropCircle"); - cgs.media.disruptorLight = trap->R_RegisterShader( "gfx/2d/cropCircleGlow" ); - cgs.media.disruptorInsertTick = trap->R_RegisterShader( "gfx/2d/insertTick" ); - cgs.media.disruptorChargeShader = trap->R_RegisterShaderNoMip("gfx/2d/crop_charge"); + cgs.media.disruptorMask = trap->R_RegisterShader("gfx/2d/cropCircle2"); + cgs.media.disruptorInsert = trap->R_RegisterShader("gfx/2d/cropCircle"); + cgs.media.disruptorLight = trap->R_RegisterShader("gfx/2d/cropCircleGlow"); + cgs.media.disruptorInsertTick = trap->R_RegisterShader("gfx/2d/insertTick"); + cgs.media.disruptorChargeShader = trap->R_RegisterShaderNoMip("gfx/2d/crop_charge"); - cgs.media.disruptorZoomLoop = trap->S_RegisterSound( "sound/weapons/disruptor/zoomloop.wav" ); + cgs.media.disruptorZoomLoop = trap->S_RegisterSound("sound/weapons/disruptor/zoomloop.wav"); break; case WP_BOWCASTER: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/bowcaster/select.wav"); - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/bowcaster/fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "bowcaster/muzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor = {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; - weaponInfo->altMissileTrailFunc = FX_BowcasterProjectileThink; - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/bowcaster/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = trap->S_RegisterSound( "sound/weapons/bowcaster/altcharge.wav"); - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "bowcaster/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor= {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/bowcaster/select.wav"); + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/bowcaster/fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("bowcaster/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor = {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->altMissileTrailFunc = FX_BowcasterProjectileThink; + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/bowcaster/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = trap->S_RegisterSound("sound/weapons/bowcaster/altcharge.wav"); + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("bowcaster/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor= {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; weaponInfo->missileTrailFunc = FX_BowcasterAltProjectileThink; - cgs.effects.bowcasterShotEffect = trap->FX_RegisterEffect( "bowcaster/shot" ); - cgs.effects.bowcasterImpactEffect = trap->FX_RegisterEffect( "bowcaster/explosion" ); + cgs.effects.bowcasterShotEffect = trap->FX_RegisterEffect("bowcaster/shot"); + cgs.effects.bowcasterImpactEffect = trap->FX_RegisterEffect("bowcaster/explosion"); - trap->FX_RegisterEffect( "bowcaster/deflect" ); + trap->FX_RegisterEffect("bowcaster/deflect"); - cgs.media.greenFrontFlash = trap->R_RegisterShader( "gfx/effects/greenFrontFlash" ); + cgs.media.greenFrontFlash = trap->R_RegisterShader("gfx/effects/greenFrontFlash"); break; case WP_REPEATER: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/repeater/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/repeater/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "repeater/muzzle_flash" ); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_RepeaterProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/repeater/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "repeater/muzzle_flash" ); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/repeater/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/repeater/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("repeater/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_RepeaterProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/repeater/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("repeater/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_RepeaterAltProjectileThink; - cgs.effects.repeaterProjectileEffect = trap->FX_RegisterEffect( "repeater/projectile" ); - cgs.effects.repeaterAltProjectileEffect = trap->FX_RegisterEffect( "repeater/alt_projectile" ); - cgs.effects.repeaterWallImpactEffect = trap->FX_RegisterEffect( "repeater/wall_impact" ); - cgs.effects.repeaterFleshImpactEffect = trap->FX_RegisterEffect( "repeater/flesh_impact" ); - //cgs.effects.repeaterAltWallImpactEffect = trap->FX_RegisterEffect( "repeater/alt_wall_impact" ); - cgs.effects.repeaterAltWallImpactEffect = trap->FX_RegisterEffect( "repeater/concussion" ); + cgs.effects.repeaterProjectileEffect = trap->FX_RegisterEffect("repeater/projectile"); + cgs.effects.repeaterAltProjectileEffect = trap->FX_RegisterEffect("repeater/alt_projectile"); + cgs.effects.repeaterWallImpactEffect = trap->FX_RegisterEffect("repeater/wall_impact"); + cgs.effects.repeaterFleshImpactEffect = trap->FX_RegisterEffect("repeater/flesh_impact"); + // cgs.effects.repeaterAltWallImpactEffect = trap->FX_RegisterEffect( "repeater/alt_wall_impact" ); + cgs.effects.repeaterAltWallImpactEffect = trap->FX_RegisterEffect("repeater/concussion"); break; case WP_DEMP2: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/demp2/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/demp2/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect("demp2/muzzle_flash"); - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_DEMP2_ProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/demp2/altfire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/demp2/altCharge.wav"); - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("demp2/muzzle_flash"); - weaponInfo->altMissileModel = NULL_HANDLE; - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/demp2/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/demp2/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("demp2/muzzle_flash"); + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_DEMP2_ProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/demp2/altfire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/demp2/altCharge.wav"); + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("demp2/muzzle_flash"); + weaponInfo->altMissileModel = NULL_HANDLE; + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = 0; - cgs.effects.demp2ProjectileEffect = trap->FX_RegisterEffect( "demp2/projectile" ); - cgs.effects.demp2WallImpactEffect = trap->FX_RegisterEffect( "demp2/wall_impact" ); - cgs.effects.demp2FleshImpactEffect = trap->FX_RegisterEffect( "demp2/flesh_impact" ); + cgs.effects.demp2ProjectileEffect = trap->FX_RegisterEffect("demp2/projectile"); + cgs.effects.demp2WallImpactEffect = trap->FX_RegisterEffect("demp2/wall_impact"); + cgs.effects.demp2FleshImpactEffect = trap->FX_RegisterEffect("demp2/flesh_impact"); - cgs.media.demp2Shell = trap->R_RegisterModel( "models/items/sphere.md3" ); - cgs.media.demp2ShellShader = trap->R_RegisterShader( "gfx/effects/demp2shell" ); + cgs.media.demp2Shell = trap->R_RegisterModel("models/items/sphere.md3"); + cgs.media.demp2ShellShader = trap->R_RegisterShader("gfx/effects/demp2shell"); cgs.media.lightningFlash = trap->R_RegisterShader("gfx/misc/lightningFlash"); break; case WP_FLECHETTE: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/flechette/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/flechette/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "flechette/muzzle_flash" ); - weaponInfo->missileModel = trap->R_RegisterModel("models/weapons2/golan_arms/projectileMain.md3"); - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_FlechetteProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/flechette/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "flechette/muzzle_flash" ); - weaponInfo->altMissileModel = trap->R_RegisterModel( "models/weapons2/golan_arms/projectile.md3" ); - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/flechette/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/flechette/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("flechette/muzzle_flash"); + weaponInfo->missileModel = trap->R_RegisterModel("models/weapons2/golan_arms/projectileMain.md3"); + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_FlechetteProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/flechette/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("flechette/muzzle_flash"); + weaponInfo->altMissileModel = trap->R_RegisterModel("models/weapons2/golan_arms/projectile.md3"); + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_FlechetteAltProjectileThink; - cgs.effects.flechetteShotEffect = trap->FX_RegisterEffect( "flechette/shot" ); - cgs.effects.flechetteAltShotEffect = trap->FX_RegisterEffect( "flechette/alt_shot" ); - cgs.effects.flechetteWallImpactEffect = trap->FX_RegisterEffect( "flechette/wall_impact" ); - cgs.effects.flechetteFleshImpactEffect = trap->FX_RegisterEffect( "flechette/flesh_impact" ); + cgs.effects.flechetteShotEffect = trap->FX_RegisterEffect("flechette/shot"); + cgs.effects.flechetteAltShotEffect = trap->FX_RegisterEffect("flechette/alt_shot"); + cgs.effects.flechetteWallImpactEffect = trap->FX_RegisterEffect("flechette/wall_impact"); + cgs.effects.flechetteFleshImpactEffect = trap->FX_RegisterEffect("flechette/flesh_impact"); break; case WP_ROCKET_LAUNCHER: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/rocket/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/rocket/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = trap->FX_RegisterEffect( "rocket/muzzle_flash" ); //trap->FX_RegisterEffect( "rocket/muzzle_flash2" ); - //flash2 still looks crappy with the fx bolt stuff. Because the fx bolt stuff doesn't work entirely right. - weaponInfo->missileModel = trap->R_RegisterModel( "models/weapons2/merr_sonn/projectile.md3" ); - weaponInfo->missileSound = trap->S_RegisterSound( "sound/weapons/rocket/missleloop.wav"); - weaponInfo->missileDlight = 125; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/rocket/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/rocket/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = trap->FX_RegisterEffect("rocket/muzzle_flash"); // trap->FX_RegisterEffect( "rocket/muzzle_flash2" ); + // flash2 still looks crappy with the fx bolt stuff. Because the fx bolt stuff doesn't work entirely right. + weaponInfo->missileModel = trap->R_RegisterModel("models/weapons2/merr_sonn/projectile.md3"); + weaponInfo->missileSound = trap->S_RegisterSound("sound/weapons/rocket/missleloop.wav"); + weaponInfo->missileDlight = 125; VectorSet(weaponInfo->missileDlightColor, 1.0, 1.0, 0.5); - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_RocketProjectileThink; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/rocket/alt_fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect( "rocket/altmuzzle_flash" ); - weaponInfo->altMissileModel = trap->R_RegisterModel( "models/weapons2/merr_sonn/projectile.md3" ); - weaponInfo->altMissileSound = trap->S_RegisterSound( "sound/weapons/rocket/missleloop.wav"); - weaponInfo->altMissileDlight = 125; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_RocketProjectileThink; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/rocket/alt_fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = trap->FX_RegisterEffect("rocket/altmuzzle_flash"); + weaponInfo->altMissileModel = trap->R_RegisterModel("models/weapons2/merr_sonn/projectile.md3"); + weaponInfo->altMissileSound = trap->S_RegisterSound("sound/weapons/rocket/missleloop.wav"); + weaponInfo->altMissileDlight = 125; VectorSet(weaponInfo->altMissileDlightColor, 1.0, 1.0, 0.5); - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = FX_RocketAltProjectileThink; - cgs.effects.rocketShotEffect = trap->FX_RegisterEffect( "rocket/shot" ); - cgs.effects.rocketExplosionEffect = trap->FX_RegisterEffect( "rocket/explosion" ); + cgs.effects.rocketShotEffect = trap->FX_RegisterEffect("rocket/shot"); + cgs.effects.rocketExplosionEffect = trap->FX_RegisterEffect("rocket/explosion"); - trap->R_RegisterShaderNoMip( "gfx/2d/wedge" ); - trap->R_RegisterShaderNoMip( "gfx/2d/lock" ); + trap->R_RegisterShaderNoMip("gfx/2d/wedge"); + trap->R_RegisterShaderNoMip("gfx/2d/lock"); - trap->S_RegisterSound( "sound/weapons/rocket/lock.wav" ); - trap->S_RegisterSound( "sound/weapons/rocket/tick.wav" ); + trap->S_RegisterSound("sound/weapons/rocket/lock.wav"); + trap->S_RegisterSound("sound/weapons/rocket/tick.wav"); break; case WP_THERMAL: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/thermal/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/thermal/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = trap->S_RegisterSound( "sound/weapons/thermal/charge.wav"); - weaponInfo->muzzleEffect = NULL_FX; - weaponInfo->missileModel = trap->R_RegisterModel( "models/weapons2/thermal/thermal_proj.md3" ); - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = 0; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/thermal/fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = trap->S_RegisterSound( "sound/weapons/thermal/charge.wav"); - weaponInfo->altMuzzleEffect = NULL_FX; - weaponInfo->altMissileModel = trap->R_RegisterModel( "models/weapons2/thermal/thermal_proj.md3" ); - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/thermal/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/thermal/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = trap->S_RegisterSound("sound/weapons/thermal/charge.wav"); + weaponInfo->muzzleEffect = NULL_FX; + weaponInfo->missileModel = trap->R_RegisterModel("models/weapons2/thermal/thermal_proj.md3"); + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = 0; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/thermal/fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = trap->S_RegisterSound("sound/weapons/thermal/charge.wav"); + weaponInfo->altMuzzleEffect = NULL_FX; + weaponInfo->altMissileModel = trap->R_RegisterModel("models/weapons2/thermal/thermal_proj.md3"); + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = 0; - cgs.effects.thermalExplosionEffect = trap->FX_RegisterEffect( "thermal/explosion" ); - cgs.effects.thermalShockwaveEffect = trap->FX_RegisterEffect( "thermal/shockwave" ); + cgs.effects.thermalExplosionEffect = trap->FX_RegisterEffect("thermal/explosion"); + cgs.effects.thermalShockwaveEffect = trap->FX_RegisterEffect("thermal/shockwave"); - cgs.media.grenadeBounce1 = trap->S_RegisterSound( "sound/weapons/thermal/bounce1.wav" ); - cgs.media.grenadeBounce2 = trap->S_RegisterSound( "sound/weapons/thermal/bounce2.wav" ); + cgs.media.grenadeBounce1 = trap->S_RegisterSound("sound/weapons/thermal/bounce1.wav"); + cgs.media.grenadeBounce2 = trap->S_RegisterSound("sound/weapons/thermal/bounce2.wav"); - trap->S_RegisterSound( "sound/weapons/thermal/thermloop.wav" ); - trap->S_RegisterSound( "sound/weapons/thermal/warning.wav" ); + trap->S_RegisterSound("sound/weapons/thermal/thermloop.wav"); + trap->S_RegisterSound("sound/weapons/thermal/warning.wav"); break; case WP_TRIP_MINE: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/detpack/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/laser_trap/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = NULL_FX; - weaponInfo->missileModel = 0;//trap->R_RegisterModel( "models/weapons2/laser_trap/laser_trap_w.md3" ); - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = 0; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/laser_trap/fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = NULL_FX; - weaponInfo->altMissileModel = 0;//trap->R_RegisterModel( "models/weapons2/laser_trap/laser_trap_w.md3" ); - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/detpack/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/laser_trap/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = NULL_FX; + weaponInfo->missileModel = 0; // trap->R_RegisterModel( "models/weapons2/laser_trap/laser_trap_w.md3" ); + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = 0; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/laser_trap/fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = NULL_FX; + weaponInfo->altMissileModel = 0; // trap->R_RegisterModel( "models/weapons2/laser_trap/laser_trap_w.md3" ); + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = 0; cgs.effects.tripmineLaserFX = trap->FX_RegisterEffect("tripMine/laserMP.efx"); cgs.effects.tripmineGlowFX = trap->FX_RegisterEffect("tripMine/glowbit.efx"); - trap->FX_RegisterEffect( "tripMine/explosion" ); + trap->FX_RegisterEffect("tripMine/explosion"); // NOTENOTE temp stuff - trap->S_RegisterSound( "sound/weapons/laser_trap/stick.wav" ); - trap->S_RegisterSound( "sound/weapons/laser_trap/warning.wav" ); + trap->S_RegisterSound("sound/weapons/laser_trap/stick.wav"); + trap->S_RegisterSound("sound/weapons/laser_trap/warning.wav"); break; case WP_DET_PACK: - weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/detpack/select.wav"); - - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/detpack/fire.wav"); - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = NULL_FX; - weaponInfo->missileModel = trap->R_RegisterModel( "models/weapons2/detpack/det_pack.md3" ); - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; -// weaponInfo->missileDlightColor = {0,0,0}; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = 0; - - weaponInfo->altFlashSound[0] = trap->S_RegisterSound( "sound/weapons/detpack/fire.wav"); - weaponInfo->altFiringSound = NULL_SOUND; - weaponInfo->altChargeSound = NULL_SOUND; - weaponInfo->altMuzzleEffect = NULL_FX; - weaponInfo->altMissileModel = trap->R_RegisterModel( "models/weapons2/detpack/det_pack.md3" ); - weaponInfo->altMissileSound = NULL_SOUND; - weaponInfo->altMissileDlight = 0; -// weaponInfo->altMissileDlightColor= {0,0,0}; - weaponInfo->altMissileHitSound = NULL_SOUND; + weaponInfo->selectSound = trap->S_RegisterSound("sound/weapons/detpack/select.wav"); + + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/detpack/fire.wav"); + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = NULL_FX; + weaponInfo->missileModel = trap->R_RegisterModel("models/weapons2/detpack/det_pack.md3"); + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + // weaponInfo->missileDlightColor = {0,0,0}; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = 0; + + weaponInfo->altFlashSound[0] = trap->S_RegisterSound("sound/weapons/detpack/fire.wav"); + weaponInfo->altFiringSound = NULL_SOUND; + weaponInfo->altChargeSound = NULL_SOUND; + weaponInfo->altMuzzleEffect = NULL_FX; + weaponInfo->altMissileModel = trap->R_RegisterModel("models/weapons2/detpack/det_pack.md3"); + weaponInfo->altMissileSound = NULL_SOUND; + weaponInfo->altMissileDlight = 0; + // weaponInfo->altMissileDlightColor= {0,0,0}; + weaponInfo->altMissileHitSound = NULL_SOUND; weaponInfo->altMissileTrailFunc = 0; - trap->R_RegisterModel( "models/weapons2/detpack/det_pack.md3" ); - trap->S_RegisterSound( "sound/weapons/detpack/stick.wav" ); - trap->S_RegisterSound( "sound/weapons/detpack/warning.wav" ); - trap->S_RegisterSound( "sound/weapons/explosions/explode5.wav" ); + trap->R_RegisterModel("models/weapons2/detpack/det_pack.md3"); + trap->S_RegisterSound("sound/weapons/detpack/stick.wav"); + trap->S_RegisterSound("sound/weapons/detpack/warning.wav"); + trap->S_RegisterSound("sound/weapons/explosions/explode5.wav"); break; case WP_TURRET: - weaponInfo->flashSound[0] = NULL_SOUND; - weaponInfo->firingSound = NULL_SOUND; - weaponInfo->chargeSound = NULL_SOUND; - weaponInfo->muzzleEffect = NULL_HANDLE; - weaponInfo->missileModel = NULL_HANDLE; - weaponInfo->missileSound = NULL_SOUND; - weaponInfo->missileDlight = 0; - weaponInfo->missileHitSound = NULL_SOUND; - weaponInfo->missileTrailFunc = FX_TurretProjectileThink; + weaponInfo->flashSound[0] = NULL_SOUND; + weaponInfo->firingSound = NULL_SOUND; + weaponInfo->chargeSound = NULL_SOUND; + weaponInfo->muzzleEffect = NULL_HANDLE; + weaponInfo->missileModel = NULL_HANDLE; + weaponInfo->missileSound = NULL_SOUND; + weaponInfo->missileDlight = 0; + weaponInfo->missileHitSound = NULL_SOUND; + weaponInfo->missileTrailFunc = FX_TurretProjectileThink; trap->FX_RegisterEffect("effects/blaster/wall_impact.efx"); trap->FX_RegisterEffect("effects/blaster/flesh_impact.efx"); break; - default: - MAKERGB( weaponInfo->flashDlightColor, 1, 1, 1 ); - weaponInfo->flashSound[0] = trap->S_RegisterSound( "sound/weapons/rocket/rocklf1a.wav" ); + default: + MAKERGB(weaponInfo->flashDlightColor, 1, 1, 1); + weaponInfo->flashSound[0] = trap->S_RegisterSound("sound/weapons/rocket/rocklf1a.wav"); break; } } diff --git a/codemp/cgame/cg_weapons.c b/codemp/cgame/cg_weapons.c index f6f191e0e9..34f10689cd 100644 --- a/codemp/cgame/cg_weapons.c +++ b/codemp/cgame/cg_weapons.c @@ -29,12 +29,11 @@ along with this program; if not, see . Ghoul2 Insert Start */ // set up the appropriate ghoul2 info to a refent -void CG_SetGhoul2InfoRef( refEntity_t *ent, refEntity_t *s1) -{ +void CG_SetGhoul2InfoRef(refEntity_t *ent, refEntity_t *s1) { ent->ghoul2 = s1->ghoul2; - VectorCopy( s1->modelScale, ent->modelScale); + VectorCopy(s1->modelScale, ent->modelScale); ent->radius = s1->radius; - VectorCopy( s1->angles, ent->angles); + VectorCopy(s1->angles, ent->angles); } /* @@ -48,90 +47,70 @@ CG_RegisterItemVisuals The server says this item is used on this level ================= */ -void CG_RegisterItemVisuals( int itemNum ) { - itemInfo_t *itemInfo; - gitem_t *item; - int handle; +void CG_RegisterItemVisuals(int itemNum) { + itemInfo_t *itemInfo; + gitem_t *item; + int handle; - if ( itemNum < 0 || itemNum >= bg_numItems ) { - trap->Error( ERR_DROP, "CG_RegisterItemVisuals: itemNum %d out of range [0-%d]", itemNum, bg_numItems-1 ); + if (itemNum < 0 || itemNum >= bg_numItems) { + trap->Error(ERR_DROP, "CG_RegisterItemVisuals: itemNum %d out of range [0-%d]", itemNum, bg_numItems - 1); } - itemInfo = &cg_items[ itemNum ]; - if ( itemInfo->registered ) { + itemInfo = &cg_items[itemNum]; + if (itemInfo->registered) { return; } - item = &bg_itemlist[ itemNum ]; + item = &bg_itemlist[itemNum]; - memset( itemInfo, 0, sizeof( *itemInfo ) ); + memset(itemInfo, 0, sizeof(*itemInfo)); itemInfo->registered = qtrue; - if (item->giType == IT_TEAM && - (item->giTag == PW_REDFLAG || item->giTag == PW_BLUEFLAG) && - cgs.gametype == GT_CTY) - { //in CTY the flag model is different - itemInfo->models[0] = trap->R_RegisterModel( item->world_model[1] ); - } - else if (item->giType == IT_WEAPON && - (item->giTag == WP_THERMAL || item->giTag == WP_TRIP_MINE || item->giTag == WP_DET_PACK)) - { - itemInfo->models[0] = trap->R_RegisterModel( item->world_model[1] ); - } - else - { - itemInfo->models[0] = trap->R_RegisterModel( item->world_model[0] ); + if (item->giType == IT_TEAM && (item->giTag == PW_REDFLAG || item->giTag == PW_BLUEFLAG) && cgs.gametype == GT_CTY) { // in CTY the flag model is different + itemInfo->models[0] = trap->R_RegisterModel(item->world_model[1]); + } else if (item->giType == IT_WEAPON && (item->giTag == WP_THERMAL || item->giTag == WP_TRIP_MINE || item->giTag == WP_DET_PACK)) { + itemInfo->models[0] = trap->R_RegisterModel(item->world_model[1]); + } else { + itemInfo->models[0] = trap->R_RegisterModel(item->world_model[0]); } -/* -Ghoul2 Insert Start -*/ - if (!Q_stricmp(&item->world_model[0][strlen(item->world_model[0]) - 4], ".glm")) - { - handle = trap->G2API_InitGhoul2Model(&itemInfo->g2Models[0], item->world_model[0], 0 , 0, 0, 0, 0); - if (handle<0) - { + /* + Ghoul2 Insert Start + */ + if (!Q_stricmp(&item->world_model[0][strlen(item->world_model[0]) - 4], ".glm")) { + handle = trap->G2API_InitGhoul2Model(&itemInfo->g2Models[0], item->world_model[0], 0, 0, 0, 0, 0); + if (handle < 0) { itemInfo->g2Models[0] = NULL; - } - else - { + } else { itemInfo->radius[0] = 60; } } -/* -Ghoul2 Insert End -*/ - if (item->icon) - { - if (item->giType == IT_HEALTH) - { //medpack gets nomip'd by the ui or something I guess. - itemInfo->icon = trap->R_RegisterShaderNoMip( item->icon ); - } - else - { - itemInfo->icon = trap->R_RegisterShader( item->icon ); + /* + Ghoul2 Insert End + */ + if (item->icon) { + if (item->giType == IT_HEALTH) { // medpack gets nomip'd by the ui or something I guess. + itemInfo->icon = trap->R_RegisterShaderNoMip(item->icon); + } else { + itemInfo->icon = trap->R_RegisterShader(item->icon); } - } - else - { + } else { itemInfo->icon = 0; } - if ( item->giType == IT_WEAPON ) { - CG_RegisterWeapon( item->giTag ); + if (item->giType == IT_WEAPON) { + CG_RegisterWeapon(item->giTag); } // // powerups have an accompanying ring or sphere // - if ( item->giType == IT_POWERUP || item->giType == IT_HEALTH || - item->giType == IT_ARMOR || item->giType == IT_HOLDABLE ) { - if ( item->world_model[1] ) { - itemInfo->models[1] = trap->R_RegisterModel( item->world_model[1] ); + if (item->giType == IT_POWERUP || item->giType == IT_HEALTH || item->giType == IT_ARMOR || item->giType == IT_HOLDABLE) { + if (item->world_model[1]) { + itemInfo->models[1] = trap->R_RegisterModel(item->world_model[1]); } } } - /* ======================================================================================== @@ -143,7 +122,7 @@ VIEW WEAPON #define WEAPON_FORCE_BUSY_HOLSTER #ifdef WEAPON_FORCE_BUSY_HOLSTER -//rww - this was done as a last resort. Forgive me. +// rww - this was done as a last resort. Forgive me. static int cgWeapFrame = 0; static int cgWeapFrameTime = 0; #endif @@ -154,44 +133,40 @@ CG_MapTorsoToWeaponFrame ================= */ -static int CG_MapTorsoToWeaponFrame( clientInfo_t *ci, int frame, int animNum ) { +static int CG_MapTorsoToWeaponFrame(clientInfo_t *ci, int frame, int animNum) { animation_t *animations = bgHumanoidAnimations; #ifdef WEAPON_FORCE_BUSY_HOLSTER - if ( cg.snap->ps.forceHandExtend != HANDEXTEND_NONE || cgWeapFrameTime > cg.time ) { + if (cg.snap->ps.forceHandExtend != HANDEXTEND_NONE || cgWeapFrameTime > cg.time) { // the reason for the after delay is so that it doesn't snap the weapon frame to the "idle" (0) frame for a very quick moment - if ( cgWeapFrame < 6 ) { + if (cgWeapFrame < 6) { cgWeapFrame = 6; cgWeapFrameTime = cg.time + 10; } - else if ( cgWeapFrameTime < cg.time && cgWeapFrame < 10 ) { + else if (cgWeapFrameTime < cg.time && cgWeapFrame < 10) { cgWeapFrame++; cgWeapFrameTime = cg.time + 10; } - else if ( cg.snap->ps.forceHandExtend != HANDEXTEND_NONE && cgWeapFrame == 10 ) + else if (cg.snap->ps.forceHandExtend != HANDEXTEND_NONE && cgWeapFrame == 10) cgWeapFrameTime = cg.time + 100; return cgWeapFrame; - } - else { + } else { cgWeapFrame = 0; cgWeapFrameTime = 0; } #endif - switch( animNum ) - { + switch (animNum) { case TORSO_DROPWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 5) { return frame - animations[animNum].firstFrame + 6; } break; case TORSO_RAISEWEAP1: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4 ) - { + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 4) { return frame - animations[animNum].firstFrame + 6 + 4; } break; @@ -201,9 +176,8 @@ static int CG_MapTorsoToWeaponFrame( clientInfo_t *ci, int frame, int animNum ) case BOTH_ATTACK4: case BOTH_ATTACK10: case BOTH_THERMAL_THROW: - if ( frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6 ) - { - return 1 + ( frame - animations[animNum].firstFrame ); + if (frame >= animations[animNum].firstFrame && frame < animations[animNum].firstFrame + 6) { + return 1 + (frame - animations[animNum].firstFrame); } break; @@ -211,42 +185,40 @@ static int CG_MapTorsoToWeaponFrame( clientInfo_t *ci, int frame, int animNum ) return -1; } - /* ============== CG_CalculateWeaponPosition ============== */ -static void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) { - float scale; - int delta; - float fracsin; +static void CG_CalculateWeaponPosition(vec3_t origin, vec3_t angles) { + float scale; + int delta; + float fracsin; - VectorCopy( cg.refdef.vieworg, origin ); - VectorCopy( cg.refdef.viewangles, angles ); + VectorCopy(cg.refdef.vieworg, origin); + VectorCopy(cg.refdef.viewangles, angles); // on odd legs, invert some angles - if ( cg.bobcycle & 1 ) { + if (cg.bobcycle & 1) { scale = -cg.xyspeed; } else { scale = cg.xyspeed; } - if ( cg_weaponBob.value ) { + if (cg_weaponBob.value) { // gun angles from bobbing angles[ROLL] += scale * cg.bobfracsin * 0.005; angles[YAW] += scale * cg.bobfracsin * 0.01; angles[PITCH] += cg.xyspeed * cg.bobfracsin * 0.005; } - if ( cg_fallingBob.value ) { + if (cg_fallingBob.value) { // drop the weapon when landing delta = cg.time - cg.landTime; - if ( delta < LAND_DEFLECT_TIME ) { - origin[2] += cg.landChange*0.25 * delta / LAND_DEFLECT_TIME; - } else if ( delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME ) { - origin[2] += cg.landChange*0.25 * - (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; + if (delta < LAND_DEFLECT_TIME) { + origin[2] += cg.landChange * 0.25 * delta / LAND_DEFLECT_TIME; + } else if (delta < LAND_DEFLECT_TIME + LAND_RETURN_TIME) { + origin[2] += cg.landChange * 0.25 * (LAND_DEFLECT_TIME + LAND_RETURN_TIME - delta) / LAND_RETURN_TIME; } } @@ -260,17 +232,16 @@ static void CG_CalculateWeaponPosition( vec3_t origin, vec3_t angles ) { } #endif - if ( cg_weaponBob.value ) { + if (cg_weaponBob.value) { // idle drift scale = cg.xyspeed + 40; - fracsin = sin( cg.time * 0.001 ); + fracsin = sin(cg.time * 0.001); angles[ROLL] += scale * fracsin * 0.01; angles[YAW] += scale * fracsin * 0.01; angles[PITCH] += scale * fracsin * 0.01; } } - /* =============== CG_LightningBolt @@ -282,132 +253,124 @@ so the endpoint will reflect the simulated strike (lagging the predicted angle) =============== */ -static void CG_LightningBolt( centity_t *cent, vec3_t origin ) { -// trace_t trace; - refEntity_t beam; -// vec3_t forward; -// vec3_t muzzlePoint, endPoint; - - //Must be a durational weapon that continuously generates an effect. - if ( cent->currentState.weapon == WP_DEMP2 && cent->currentState.eFlags & EF_ALT_FIRING ) - { /*nothing*/ } - else - { +static void CG_LightningBolt(centity_t *cent, vec3_t origin) { + // trace_t trace; + refEntity_t beam; + // vec3_t forward; + // vec3_t muzzlePoint, endPoint; + + // Must be a durational weapon that continuously generates an effect. + if (cent->currentState.weapon == WP_DEMP2 && cent->currentState.eFlags & EF_ALT_FIRING) { /*nothing*/ + } else { return; } - memset( &beam, 0, sizeof( beam ) ); + memset(&beam, 0, sizeof(beam)); // NOTENOTE No lightning gun-ish stuff yet. -/* - // CPMA "true" lightning - if ((cent->currentState.number == cg.predictedPlayerState.clientNum) && (cg_trueLightning.value != 0)) { - vec3_t angle; - int i; - - for (i = 0; i < 3; i++) { - float a = cent->lerpAngles[i] - cg.refdef.viewangles[i]; - if (a > 180) { - a -= 360; - } - if (a < -180) { - a += 360; - } + /* + // CPMA "true" lightning + if ((cent->currentState.number == cg.predictedPlayerState.clientNum) && (cg_trueLightning.value != 0)) { + vec3_t angle; + int i; + + for (i = 0; i < 3; i++) { + float a = cent->lerpAngles[i] - cg.refdef.viewangles[i]; + if (a > 180) { + a -= 360; + } + if (a < -180) { + a += 360; + } - angle[i] = cg.refdef.viewangles[i] + a * (1.0 - cg_trueLightning.value); - if (angle[i] < 0) { - angle[i] += 360; - } - if (angle[i] > 360) { - angle[i] -= 360; + angle[i] = cg.refdef.viewangles[i] + a * (1.0 - cg_trueLightning.value); + if (angle[i] < 0) { + angle[i] += 360; + } + if (angle[i] > 360) { + angle[i] -= 360; + } } - } - AngleVectors(angle, forward, NULL, NULL ); - VectorCopy(cent->lerpOrigin, muzzlePoint ); -// VectorCopy(cg.refdef.vieworg, muzzlePoint ); - } else { - // !CPMA - AngleVectors( cent->lerpAngles, forward, NULL, NULL ); - VectorCopy(cent->lerpOrigin, muzzlePoint ); - } + AngleVectors(angle, forward, NULL, NULL ); + VectorCopy(cent->lerpOrigin, muzzlePoint ); + // VectorCopy(cg.refdef.vieworg, muzzlePoint ); + } else { + // !CPMA + AngleVectors( cent->lerpAngles, forward, NULL, NULL ); + VectorCopy(cent->lerpOrigin, muzzlePoint ); + } - // FIXME: crouch - muzzlePoint[2] += DEFAULT_VIEWHEIGHT; + // FIXME: crouch + muzzlePoint[2] += DEFAULT_VIEWHEIGHT; - VectorMA( muzzlePoint, 14, forward, muzzlePoint ); + VectorMA( muzzlePoint, 14, forward, muzzlePoint ); - // project forward by the lightning range - VectorMA( muzzlePoint, LIGHTNING_RANGE, forward, endPoint ); + // project forward by the lightning range + VectorMA( muzzlePoint, LIGHTNING_RANGE, forward, endPoint ); - // see if it hit a wall - CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint, - cent->currentState.number, MASK_SHOT ); + // see if it hit a wall + CG_Trace( &trace, muzzlePoint, vec3_origin, vec3_origin, endPoint, + cent->currentState.number, MASK_SHOT ); - // this is the endpoint - VectorCopy( trace.endpos, beam.oldorigin ); + // this is the endpoint + VectorCopy( trace.endpos, beam.oldorigin ); - // use the provided origin, even though it may be slightly - // different than the muzzle origin - VectorCopy( origin, beam.origin ); + // use the provided origin, even though it may be slightly + // different than the muzzle origin + VectorCopy( origin, beam.origin ); - beam.reType = RT_LIGHTNING; - beam.customShader = cgs.media.lightningShader; - trap->R_AddRefEntityToScene( &beam ); -*/ + beam.reType = RT_LIGHTNING; + beam.customShader = cgs.media.lightningShader; + trap->R_AddRefEntityToScene( &beam ); + */ // NOTENOTE No lightning gun-ish stuff yet. -/* - // add the impact flare if it hit something - if ( trace.fraction < 1.0 ) { - vec3_t angles; - vec3_t dir; + /* + // add the impact flare if it hit something + if ( trace.fraction < 1.0 ) { + vec3_t angles; + vec3_t dir; - VectorSubtract( beam.oldorigin, beam.origin, dir ); - VectorNormalize( dir ); + VectorSubtract( beam.oldorigin, beam.origin, dir ); + VectorNormalize( dir ); - memset( &beam, 0, sizeof( beam ) ); - beam.hModel = cgs.media.lightningExplosionModel; + memset( &beam, 0, sizeof( beam ) ); + beam.hModel = cgs.media.lightningExplosionModel; - VectorMA( trace.endpos, -16, dir, beam.origin ); + VectorMA( trace.endpos, -16, dir, beam.origin ); - // make a random orientation - angles[0] = rand() % 360; - angles[1] = rand() % 360; - angles[2] = rand() % 360; - AnglesToAxis( angles, beam.axis ); - trap->R_AddRefEntityToScene( &beam ); - } -*/ + // make a random orientation + angles[0] = rand() % 360; + angles[1] = rand() % 360; + angles[2] = rand() % 360; + AnglesToAxis( angles, beam.axis ); + trap->R_AddRefEntityToScene( &beam ); + } + */ } - /* ======================== CG_AddWeaponWithPowerups ======================== */ -static void CG_AddWeaponWithPowerups( refEntity_t *gun, int powerups ) { +static void CG_AddWeaponWithPowerups(refEntity_t *gun, int powerups) { // add powerup effects - trap->R_AddRefEntityToScene( gun ); + trap->R_AddRefEntityToScene(gun); - if (cg.predictedPlayerState.electrifyTime > cg.time) - { //add electrocution shell + if (cg.predictedPlayerState.electrifyTime > cg.time) { // add electrocution shell int preShader = gun->customShader; - if ( rand() & 1 ) - { + if (rand() & 1) { gun->customShader = cgs.media.electricBodyShader; - } - else - { + } else { gun->customShader = cgs.media.electricBody2Shader; } - trap->R_AddRefEntityToScene( gun ); - gun->customShader = preShader; //set back just to be safe + trap->R_AddRefEntityToScene(gun); + gun->customShader = preShader; // set back just to be safe } } - /* ============= CG_AddPlayerWeapon @@ -417,78 +380,67 @@ The main player will have this called for BOTH cases, so effects like light and sound should only be done on the world model case. ============= */ -void CG_AddPlayerWeapon( refEntity_t *parent, playerState_t *ps, centity_t *cent, int team, vec3_t newAngles, qboolean thirdPerson ) { - refEntity_t gun; - refEntity_t barrel; - vec3_t angles; - weapon_t weaponNum; - weaponInfo_t *weapon; - centity_t *nonPredictedCent; - refEntity_t flash; +void CG_AddPlayerWeapon(refEntity_t *parent, playerState_t *ps, centity_t *cent, int team, vec3_t newAngles, qboolean thirdPerson) { + refEntity_t gun; + refEntity_t barrel; + vec3_t angles; + weapon_t weaponNum; + weaponInfo_t *weapon; + centity_t *nonPredictedCent; + refEntity_t flash; weaponNum = cent->currentState.weapon; - if (cent->currentState.weapon == WP_EMPLACED_GUN) - { + if (cent->currentState.weapon == WP_EMPLACED_GUN) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR && - cent->currentState.number == cg.predictedPlayerState.clientNum) - { //spectator mode, don't draw it... + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR && cent->currentState.number == cg.predictedPlayerState.clientNum) { // spectator mode, don't draw it... return; } - CG_RegisterWeapon( weaponNum ); + CG_RegisterWeapon(weaponNum); weapon = &cg_weapons[weaponNum]; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - memset( &gun, 0, sizeof( gun ) ); + memset(&gun, 0, sizeof(gun)); // only do this if we are in first person, since world weapons are now handled on the server by Ghoul2 - if (!thirdPerson) - { + if (!thirdPerson) { // add the weapon - VectorCopy( parent->lightingOrigin, gun.lightingOrigin ); + VectorCopy(parent->lightingOrigin, gun.lightingOrigin); gun.shadowPlane = parent->shadowPlane; gun.renderfx = parent->renderfx; - if (ps) - { // this player, in first person view + if (ps) { // this player, in first person view gun.hModel = weapon->viewModel; - } - else - { + } else { gun.hModel = weapon->weaponModel; } if (!gun.hModel) { return; } - if ( !ps ) { + if (!ps) { // add weapon ready sound cent->pe.lightningFiring = qfalse; - if ( ( cent->currentState.eFlags & EF_FIRING ) && weapon->firingSound ) { + if ((cent->currentState.eFlags & EF_FIRING) && weapon->firingSound) { // lightning gun and gauntlet make a different sound when fire is held down - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound ); + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->firingSound); cent->pe.lightningFiring = qtrue; - } else if ( weapon->readySound ) { - trap->S_AddLoopingSound( cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->readySound ); + } else if (weapon->readySound) { + trap->S_AddLoopingSound(cent->currentState.number, cent->lerpOrigin, vec3_origin, weapon->readySound); } } - CG_PositionEntityOnTag( &gun, parent, parent->hModel, "tag_weapon"); + CG_PositionEntityOnTag(&gun, parent, parent->hModel, "tag_weapon"); - if (!CG_IsMindTricked(cent->currentState.trickedentindex, - cent->currentState.trickedentindex2, - cent->currentState.trickedentindex3, - cent->currentState.trickedentindex4, - cg.snap->ps.clientNum)) - { - CG_AddWeaponWithPowerups( &gun, cent->currentState.powerups ); //don't draw the weapon if the player is invisible + if (!CG_IsMindTricked(cent->currentState.trickedentindex, cent->currentState.trickedentindex2, cent->currentState.trickedentindex3, + cent->currentState.trickedentindex4, cg.snap->ps.clientNum)) { + CG_AddWeaponWithPowerups(&gun, cent->currentState.powerups); // don't draw the weapon if the player is invisible /* if ( weaponNum == WP_STUN_BATON ) { @@ -501,58 +453,44 @@ Ghoul2 Insert Start */ } - if (weaponNum == WP_STUN_BATON) - { + if (weaponNum == WP_STUN_BATON) { int i = 0; - while (i < 3) - { - memset( &barrel, 0, sizeof( barrel ) ); - VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); + while (i < 3) { + memset(&barrel, 0, sizeof(barrel)); + VectorCopy(parent->lightingOrigin, barrel.lightingOrigin); barrel.shadowPlane = parent->shadowPlane; barrel.renderfx = parent->renderfx; - if (i == 0) - { + if (i == 0) { barrel.hModel = trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel.md3"); - } - else if (i == 1) - { + } else if (i == 1) { barrel.hModel = trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel2.md3"); - } - else - { + } else { barrel.hModel = trap->R_RegisterModel("models/weapons2/stun_baton/baton_barrel3.md3"); } angles[YAW] = 0; angles[PITCH] = 0; angles[ROLL] = 0; - AnglesToAxis( angles, barrel.axis ); + AnglesToAxis(angles, barrel.axis); - if (i == 0) - { - CG_PositionRotatedEntityOnTag( &barrel, parent/*&gun*/, /*weapon->weaponModel*/weapon->handsModel, "tag_barrel" ); - } - else if (i == 1) - { - CG_PositionRotatedEntityOnTag( &barrel, parent/*&gun*/, /*weapon->weaponModel*/weapon->handsModel, "tag_barrel2" ); - } - else - { - CG_PositionRotatedEntityOnTag( &barrel, parent/*&gun*/, /*weapon->weaponModel*/weapon->handsModel, "tag_barrel3" ); + if (i == 0) { + CG_PositionRotatedEntityOnTag(&barrel, parent /*&gun*/, /*weapon->weaponModel*/ weapon->handsModel, "tag_barrel"); + } else if (i == 1) { + CG_PositionRotatedEntityOnTag(&barrel, parent /*&gun*/, /*weapon->weaponModel*/ weapon->handsModel, "tag_barrel2"); + } else { + CG_PositionRotatedEntityOnTag(&barrel, parent /*&gun*/, /*weapon->weaponModel*/ weapon->handsModel, "tag_barrel3"); } - CG_AddWeaponWithPowerups( &barrel, cent->currentState.powerups ); + CG_AddWeaponWithPowerups(&barrel, cent->currentState.powerups); i++; } - } - else - { + } else { // add the spinning barrel - if ( weapon->barrelModel ) { - memset( &barrel, 0, sizeof( barrel ) ); - VectorCopy( parent->lightingOrigin, barrel.lightingOrigin ); + if (weapon->barrelModel) { + memset(&barrel, 0, sizeof(barrel)); + VectorCopy(parent->lightingOrigin, barrel.lightingOrigin); barrel.shadowPlane = parent->shadowPlane; barrel.renderfx = parent->renderfx; @@ -561,54 +499,51 @@ Ghoul2 Insert Start angles[PITCH] = 0; angles[ROLL] = 0; - AnglesToAxis( angles, barrel.axis ); + AnglesToAxis(angles, barrel.axis); - CG_PositionRotatedEntityOnTag( &barrel, parent/*&gun*/, /*weapon->weaponModel*/weapon->handsModel, "tag_barrel" ); + CG_PositionRotatedEntityOnTag(&barrel, parent /*&gun*/, /*weapon->weaponModel*/ weapon->handsModel, "tag_barrel"); - CG_AddWeaponWithPowerups( &barrel, cent->currentState.powerups ); + CG_AddWeaponWithPowerups(&barrel, cent->currentState.powerups); } } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ - memset (&flash, 0, sizeof(flash)); - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + memset(&flash, 0, sizeof(flash)); + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); VectorCopy(flash.origin, cg.lastFPFlashPoint); // Do special charge bits //----------------------- - if ( (ps || cg.renderingThirdPerson || cg.predictedPlayerState.clientNum != cent->currentState.number) && - ( ( cent->currentState.modelindex2 == WEAPON_CHARGING_ALT && cent->currentState.weapon == WP_BRYAR_PISTOL ) || - ( cent->currentState.modelindex2 == WEAPON_CHARGING_ALT && cent->currentState.weapon == WP_BRYAR_OLD ) || - ( cent->currentState.weapon == WP_BOWCASTER && cent->currentState.modelindex2 == WEAPON_CHARGING ) || - ( cent->currentState.weapon == WP_DEMP2 && cent->currentState.modelindex2 == WEAPON_CHARGING_ALT) ) ) - { - int shader = 0; - float val = 0.0f; - float scale = 1.0f; + if ((ps || cg.renderingThirdPerson || cg.predictedPlayerState.clientNum != cent->currentState.number) && + ((cent->currentState.modelindex2 == WEAPON_CHARGING_ALT && cent->currentState.weapon == WP_BRYAR_PISTOL) || + (cent->currentState.modelindex2 == WEAPON_CHARGING_ALT && cent->currentState.weapon == WP_BRYAR_OLD) || + (cent->currentState.weapon == WP_BOWCASTER && cent->currentState.modelindex2 == WEAPON_CHARGING) || + (cent->currentState.weapon == WP_DEMP2 && cent->currentState.modelindex2 == WEAPON_CHARGING_ALT))) { + int shader = 0; + float val = 0.0f; + float scale = 1.0f; addspriteArgStruct_t fxSArgs; vec3_t flashorigin, flashdir; - if (!thirdPerson) - { + if (!thirdPerson) { VectorCopy(flash.origin, flashorigin); VectorCopy(flash.axis[0], flashdir); - } - else - { - mdxaBone_t boltMatrix; + } else { + mdxaBone_t boltMatrix; - if (!trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) - { //it's quite possible that we may have have no weapon model and be in a valid state, so return here if this is the case + if (!trap->G2API_HasGhoul2ModelOnIndex( + &(cent->ghoul2), + 1)) { // it's quite possible that we may have have no weapon model and be in a valid state, so return here if this is the case return; } // go away and get me the bolt position for this frame please - if (!(trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, newAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale))) - { // Couldn't find bolt point. + if (!(trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, newAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale))) { // Couldn't find bolt point. return; } @@ -616,43 +551,30 @@ Ghoul2 Insert End BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, flashdir); } - if ( cent->currentState.weapon == WP_BRYAR_PISTOL || - cent->currentState.weapon == WP_BRYAR_OLD) - { + if (cent->currentState.weapon == WP_BRYAR_PISTOL || cent->currentState.weapon == WP_BRYAR_OLD) { // Hardcoded max charge time of 1 second - val = ( cg.time - cent->currentState.constantLight ) * 0.001f; + val = (cg.time - cent->currentState.constantLight) * 0.001f; shader = cgs.media.bryarFrontFlash; - } - else if ( cent->currentState.weapon == WP_BOWCASTER ) - { + } else if (cent->currentState.weapon == WP_BOWCASTER) { // Hardcoded max charge time of 1 second - val = ( cg.time - cent->currentState.constantLight ) * 0.001f; + val = (cg.time - cent->currentState.constantLight) * 0.001f; shader = cgs.media.greenFrontFlash; - } - else if ( cent->currentState.weapon == WP_DEMP2 ) - { - val = ( cg.time - cent->currentState.constantLight ) * 0.001f; + } else if (cent->currentState.weapon == WP_DEMP2) { + val = (cg.time - cent->currentState.constantLight) * 0.001f; shader = cgs.media.lightningFlash; scale = 1.75f; } - if ( val < 0.0f ) - { + if (val < 0.0f) { val = 0.0f; - } - else if ( val > 1.0f ) - { + } else if (val > 1.0f) { val = 1.0f; - if (ps && cent->currentState.number == ps->clientNum) - { - CGCam_Shake( /*0.1f*/0.2f, 100 ); + if (ps && cent->currentState.number == ps->clientNum) { + CGCam_Shake(/*0.1f*/ 0.2f, 100); } - } - else - { - if (ps && cent->currentState.number == ps->clientNum) - { - CGCam_Shake( val * val * /*0.3f*/0.6f, 100 ); + } else { + if (ps && cent->currentState.number == ps->clientNum) { + CGCam_Shake(val * val * /*0.3f*/ 0.6f, 100); } } @@ -661,17 +583,17 @@ Ghoul2 Insert End VectorCopy(flashorigin, fxSArgs.origin); VectorClear(fxSArgs.vel); VectorClear(fxSArgs.accel); - fxSArgs.scale = 3.0f*val*scale; + fxSArgs.scale = 3.0f * val * scale; fxSArgs.dscale = 0.0f; fxSArgs.sAlpha = 0.7f; fxSArgs.eAlpha = 0.7f; - fxSArgs.rotation = Q_flrand(0.0f, 1.0f)*360; + fxSArgs.rotation = Q_flrand(0.0f, 1.0f) * 360; fxSArgs.bounce = 0.0f; fxSArgs.life = 1.0f; fxSArgs.shader = shader; fxSArgs.flags = 0x08000000; - //FX_AddSprite( flash.origin, NULL, NULL, 3.0f * val, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA ); + // FX_AddSprite( flash.origin, NULL, NULL, 3.0f * val, 0.0f, 0.7f, 0.7f, WHITE, WHITE, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, shader, FX_USE_ALPHA ); trap->FX_AddSprite(&fxSArgs); } @@ -681,48 +603,44 @@ Ghoul2 Insert End // if the index of the nonPredictedCent is not the same as the clientNum // then this is a fake player (like on teh single player podiums), so // go ahead and use the cent - if( ( nonPredictedCent - cg_entities ) != cent->currentState.clientNum ) { + if ((nonPredictedCent - cg_entities) != cent->currentState.clientNum) { nonPredictedCent = cent; } // add the flash - if ( ( weaponNum == WP_DEMP2) - && ( nonPredictedCent->currentState.eFlags & EF_FIRING ) ) - { + if ((weaponNum == WP_DEMP2) && (nonPredictedCent->currentState.eFlags & EF_FIRING)) { // continuous flash } else { // impulse flash - if ( cg.time - cent->muzzleFlashTime > MUZZLE_FLASH_TIME) { + if (cg.time - cent->muzzleFlashTime > MUZZLE_FLASH_TIME) { return; } } - if ( ps || cg.renderingThirdPerson || - cent->currentState.number != cg.predictedPlayerState.clientNum ) - { // Make sure we don't do the thirdperson model effects for the local player if we're in first person + if (ps || cg.renderingThirdPerson || + cent->currentState.number != + cg.predictedPlayerState.clientNum) { // Make sure we don't do the thirdperson model effects for the local player if we're in first person vec3_t flashorigin, flashdir; - refEntity_t flash; + refEntity_t flash; - memset (&flash, 0, sizeof(flash)); + memset(&flash, 0, sizeof(flash)); - if (!thirdPerson) - { - CG_PositionEntityOnTag( &flash, &gun, gun.hModel, "tag_flash"); + if (!thirdPerson) { + CG_PositionEntityOnTag(&flash, &gun, gun.hModel, "tag_flash"); VectorCopy(flash.origin, flashorigin); VectorCopy(flash.axis[0], flashdir); - } - else - { - mdxaBone_t boltMatrix; + } else { + mdxaBone_t boltMatrix; - if (!trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) - { //it's quite possible that we may have have no weapon model and be in a valid state, so return here if this is the case + if (!trap->G2API_HasGhoul2ModelOnIndex( + &(cent->ghoul2), + 1)) { // it's quite possible that we may have have no weapon model and be in a valid state, so return here if this is the case return; } // go away and get me the bolt position for this frame please - if (!(trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, newAngles, cent->lerpOrigin, cg.time, cgs.gameModels, cent->modelScale))) - { // Couldn't find bolt point. + if (!(trap->G2API_GetBoltMatrix(cent->ghoul2, 1, 0, &boltMatrix, newAngles, cent->lerpOrigin, cg.time, cgs.gameModels, + cent->modelScale))) { // Couldn't find bolt point. return; } @@ -730,32 +648,20 @@ Ghoul2 Insert End BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, flashdir); } - if ( cg.time - cent->muzzleFlashTime <= MUZZLE_FLASH_TIME + 10 ) - { // Handle muzzle flashes - if ( cent->currentState.eFlags & EF_ALT_FIRING ) - { // Check the alt firing first. - if (weapon->altMuzzleEffect) - { - if (!thirdPerson) - { - trap->FX_PlayEntityEffectID(weapon->altMuzzleEffect, flashorigin, flash.axis, -1, -1, -1, -1 ); - } - else - { + if (cg.time - cent->muzzleFlashTime <= MUZZLE_FLASH_TIME + 10) { // Handle muzzle flashes + if (cent->currentState.eFlags & EF_ALT_FIRING) { // Check the alt firing first. + if (weapon->altMuzzleEffect) { + if (!thirdPerson) { + trap->FX_PlayEntityEffectID(weapon->altMuzzleEffect, flashorigin, flash.axis, -1, -1, -1, -1); + } else { trap->FX_PlayEffectID(weapon->altMuzzleEffect, flashorigin, flashdir, -1, -1, qfalse); } } - } - else - { // Regular firing - if (weapon->muzzleEffect) - { - if (!thirdPerson) - { - trap->FX_PlayEntityEffectID(weapon->muzzleEffect, flashorigin, flash.axis, -1, -1, -1, -1 ); - } - else - { + } else { // Regular firing + if (weapon->muzzleEffect) { + if (!thirdPerson) { + trap->FX_PlayEntityEffectID(weapon->muzzleEffect, flashorigin, flash.axis, -1, -1, -1, -1); + } else { trap->FX_PlayEffectID(weapon->muzzleEffect, flashorigin, flashdir, -1, -1, qfalse); } } @@ -763,11 +669,10 @@ Ghoul2 Insert End } // add lightning bolt - CG_LightningBolt( nonPredictedCent, flashorigin ); + CG_LightningBolt(nonPredictedCent, flashorigin); - if ( weapon->flashDlightColor[0] || weapon->flashDlightColor[1] || weapon->flashDlightColor[2] ) { - trap->R_AddLightToScene( flashorigin, 300 + (rand()&31), weapon->flashDlightColor[0], - weapon->flashDlightColor[1], weapon->flashDlightColor[2] ); + if (weapon->flashDlightColor[0] || weapon->flashDlightColor[1] || weapon->flashDlightColor[2]) { + trap->R_AddLightToScene(flashorigin, 300 + (rand() & 31), weapon->flashDlightColor[0], weapon->flashDlightColor[1], weapon->flashDlightColor[2]); } } } @@ -779,13 +684,13 @@ CG_AddViewWeapon Add the weapon, and flash for the player's view ============== */ -void CG_AddViewWeapon( playerState_t *ps ) { - refEntity_t hand; - centity_t *cent; - clientInfo_t *ci; - float fovOffset; - vec3_t angles; - weaponInfo_t *weapon; +void CG_AddViewWeapon(playerState_t *ps) { + refEntity_t hand; + centity_t *cent; + clientInfo_t *ci; + float fovOffset; + vec3_t angles; + weaponInfo_t *weapon; float cgFov = cg_fovViewmodel.integer ? cg_fovViewmodel.value : cg_fov.value; if (cgFov < 1) @@ -793,112 +698,104 @@ void CG_AddViewWeapon( playerState_t *ps ) { if (cgFov > 130) cgFov = 130; - if ( ps->persistant[PERS_TEAM] == TEAM_SPECTATOR ) { + if (ps->persistant[PERS_TEAM] == TEAM_SPECTATOR) { return; } - if ( ps->pm_type == PM_INTERMISSION ) { + if (ps->pm_type == PM_INTERMISSION) { return; } // no gun if in third person view or a camera is active - //if ( cg.renderingThirdPerson || cg.cameraMode) { - if ( cg.renderingThirdPerson ) { + // if ( cg.renderingThirdPerson || cg.cameraMode) { + if (cg.renderingThirdPerson) { return; } // allow the gun to be completely removed - if ( !cg_drawGun.integer || cg.predictedPlayerState.zoomMode) { - vec3_t origin; + if (!cg_drawGun.integer || cg.predictedPlayerState.zoomMode) { + vec3_t origin; - if ( cg.predictedPlayerState.eFlags & EF_FIRING ) { + if (cg.predictedPlayerState.eFlags & EF_FIRING) { // special hack for lightning gun... - VectorCopy( cg.refdef.vieworg, origin ); - VectorMA( origin, -8, cg.refdef.viewaxis[2], origin ); - CG_LightningBolt( &cg_entities[ps->clientNum], origin ); + VectorCopy(cg.refdef.vieworg, origin); + VectorMA(origin, -8, cg.refdef.viewaxis[2], origin); + CG_LightningBolt(&cg_entities[ps->clientNum], origin); } return; } // don't draw if testing a gun model - if ( cg.testGun ) { + if (cg.testGun) { return; } // drop gun lower at higher fov - if ( cg_fovViewmodelAdjust.integer && cgFov > 90 ) - fovOffset = -0.2f * ( cgFov - 90 ); + if (cg_fovViewmodelAdjust.integer && cgFov > 90) + fovOffset = -0.2f * (cgFov - 90); else fovOffset = 0; cent = &cg_entities[cg.predictedPlayerState.clientNum]; - CG_RegisterWeapon( ps->weapon ); - weapon = &cg_weapons[ ps->weapon ]; + CG_RegisterWeapon(ps->weapon); + weapon = &cg_weapons[ps->weapon]; - memset (&hand, 0, sizeof(hand)); + memset(&hand, 0, sizeof(hand)); // set up gun position - CG_CalculateWeaponPosition( hand.origin, angles ); + CG_CalculateWeaponPosition(hand.origin, angles); - VectorMA( hand.origin, cg_gunX.value, cg.refdef.viewaxis[0], hand.origin ); - VectorMA( hand.origin, cg_gunY.value, cg.refdef.viewaxis[1], hand.origin ); - VectorMA( hand.origin, (cg_gunZ.value+fovOffset), cg.refdef.viewaxis[2], hand.origin ); + VectorMA(hand.origin, cg_gunX.value, cg.refdef.viewaxis[0], hand.origin); + VectorMA(hand.origin, cg_gunY.value, cg.refdef.viewaxis[1], hand.origin); + VectorMA(hand.origin, (cg_gunZ.value + fovOffset), cg.refdef.viewaxis[2], hand.origin); - AnglesToAxis( angles, hand.axis ); + AnglesToAxis(angles, hand.axis); - if ( cg_fovViewmodel.integer ) - { - float fracDistFOV = tanf( cg.refdef.fov_x * ( M_PI/180 ) * 0.5f ); - float fracWeapFOV = ( 1.0f / fracDistFOV ) * tanf( cgFov * ( M_PI/180 ) * 0.5f ); - VectorScale( hand.axis[0], fracWeapFOV, hand.axis[0] ); + if (cg_fovViewmodel.integer) { + float fracDistFOV = tanf(cg.refdef.fov_x * (M_PI / 180) * 0.5f); + float fracWeapFOV = (1.0f / fracDistFOV) * tanf(cgFov * (M_PI / 180) * 0.5f); + VectorScale(hand.axis[0], fracWeapFOV, hand.axis[0]); } // map torso animations to weapon animations - if ( cg_debugGun.integer ) { + if (cg_debugGun.integer) { // development tool hand.frame = hand.oldframe = cg_debugGun.integer; hand.backlerp = 0; } else { float currentFrame; // get clientinfo for animation map - if (cent->currentState.eType == ET_NPC) - { - if (!cent->npcClient) - { + if (cent->currentState.eType == ET_NPC) { + if (!cent->npcClient) { return; } ci = cent->npcClient; - } - else - { - ci = &cgs.clientinfo[ cent->currentState.clientNum ]; + } else { + ci = &cgs.clientinfo[cent->currentState.clientNum]; } trap->G2API_GetBoneFrame(cent->ghoul2, "lower_lumbar", cg.time, ¤tFrame, cgs.gameModels, 0); - hand.frame = CG_MapTorsoToWeaponFrame( ci, ceil( currentFrame ), ps->torsoAnim ); - hand.oldframe = CG_MapTorsoToWeaponFrame( ci, floor( currentFrame ), ps->torsoAnim ); - hand.backlerp = 1.0f - (currentFrame-floor(currentFrame)); + hand.frame = CG_MapTorsoToWeaponFrame(ci, ceil(currentFrame), ps->torsoAnim); + hand.oldframe = CG_MapTorsoToWeaponFrame(ci, floor(currentFrame), ps->torsoAnim); + hand.backlerp = 1.0f - (currentFrame - floor(currentFrame)); // Handle the fringe situation where oldframe is invalid - if ( hand.frame == -1 ) - { + if (hand.frame == -1) { hand.frame = 0; hand.oldframe = 0; hand.backlerp = 0; - } - else if ( hand.oldframe == -1 ) - { + } else if (hand.oldframe == -1) { hand.oldframe = hand.frame; hand.backlerp = 0; } } hand.hModel = weapon->handsModel; - hand.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON;// | RF_MINLIGHT; + hand.renderfx = RF_DEPTHHACK | RF_FIRST_PERSON; // | RF_MINLIGHT; // add everything onto the hand - CG_AddPlayerWeapon( &hand, ps, &cg_entities[cg.predictedPlayerState.clientNum], ps->persistant[PERS_TEAM], angles, qfalse ); + CG_AddPlayerWeapon(&hand, ps, &cg_entities[cg.predictedPlayerState.clientNum], ps->persistant[PERS_TEAM], angles, qfalse); } /* @@ -908,141 +805,121 @@ WEAPON SELECTION ============================================================================== */ -#define ICON_WEAPONS 0 -#define ICON_FORCE 1 -#define ICON_INVENTORY 2 - - -void CG_DrawIconBackground(void) -{ - int /*height, xAdd, x2, y2,*/ t; -// int prongLeftX,prongRightX; - float inTime = cg.invenSelectTime+WEAPON_SELECT_TIME; - float wpTime = cg.weaponSelectTime+WEAPON_SELECT_TIME; - float fpTime = cg.forceSelectTime+WEAPON_SELECT_TIME; -// int drawType = cgs.media.weaponIconBackground; -// int yOffset = 0; +#define ICON_WEAPONS 0 +#define ICON_FORCE 1 +#define ICON_INVENTORY 2 + +void CG_DrawIconBackground(void) { + int /*height, xAdd, x2, y2,*/ t; + // int prongLeftX,prongRightX; + float inTime = cg.invenSelectTime + WEAPON_SELECT_TIME; + float wpTime = cg.weaponSelectTime + WEAPON_SELECT_TIME; + float fpTime = cg.forceSelectTime + WEAPON_SELECT_TIME; + // int drawType = cgs.media.weaponIconBackground; + // int yOffset = 0; // don't display if dead - if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 ) - { + if (cg.snap->ps.stats[STAT_HEALTH] <= 0) { return; } - if (cg_hudFiles.integer) - { //simple hud + if (cg_hudFiles.integer) { // simple hud return; } -// x2 = 30; -// y2 = SCREEN_HEIGHT-70; + // x2 = 30; + // y2 = SCREEN_HEIGHT-70; - //prongLeftX =x2+37; - //prongRightX =x2+544; + // prongLeftX =x2+37; + // prongRightX =x2+544; - if (inTime > wpTime) - { -// drawType = cgs.media.inventoryIconBackground; + if (inTime > wpTime) { + // drawType = cgs.media.inventoryIconBackground; cg.iconSelectTime = cg.invenSelectTime; - } - else - { -// drawType = cgs.media.weaponIconBackground; + } else { + // drawType = cgs.media.weaponIconBackground; cg.iconSelectTime = cg.weaponSelectTime; } - if (fpTime > inTime && fpTime > wpTime) - { -// drawType = cgs.media.forceIconBackground; + if (fpTime > inTime && fpTime > wpTime) { + // drawType = cgs.media.forceIconBackground; cg.iconSelectTime = cg.forceSelectTime; } - if ((cg.iconSelectTime+WEAPON_SELECT_TIME)1) - { + if (cg.iconHUDPercent > 1) { cg.iconHUDActive = qtrue; - cg.iconHUDPercent=1; - } - else if (cg.iconHUDPercent<0) - { - cg.iconHUDPercent=0; + cg.iconHUDPercent = 1; + } else if (cg.iconHUDPercent < 0) { + cg.iconHUDPercent = 0; } - } - else - { - cg.iconHUDPercent=1; + } else { + cg.iconHUDPercent = 1; } - //trap->R_SetColor( colorTable[CT_WHITE] ); - //height = (int) (60.0f*cg.iconHUDPercent); - //CG_DrawPic( x2+60, y2+30+yOffset, 460, -height, drawType); // Top half - //CG_DrawPic( x2+60, y2+30-2+yOffset, 460, height, drawType); // Bottom half + // trap->R_SetColor( colorTable[CT_WHITE] ); + // height = (int) (60.0f*cg.iconHUDPercent); + // CG_DrawPic( x2+60, y2+30+yOffset, 460, -height, drawType); // Top half + // CG_DrawPic( x2+60, y2+30-2+yOffset, 460, height, drawType); // Bottom half // And now for the prongs -/* if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) - { - cgs.media.currentBackground = ICON_INVENTORY; - background = &cgs.media.inventoryProngsOn; - } - else if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) - { - cgs.media.currentBackground = ICON_WEAPONS; - } - else - { - cgs.media.currentBackground = ICON_FORCE; - background = &cgs.media.forceProngsOn; - } -*/ + /* if ((cg.inventorySelectTime+WEAPON_SELECT_TIME)>cg.time) + { + cgs.media.currentBackground = ICON_INVENTORY; + background = &cgs.media.inventoryProngsOn; + } + else if ((cg.weaponSelectTime+WEAPON_SELECT_TIME)>cg.time) + { + cgs.media.currentBackground = ICON_WEAPONS; + } + else + { + cgs.media.currentBackground = ICON_FORCE; + background = &cgs.media.forceProngsOn; + } + */ // Side Prongs -// trap->R_SetColor( colorTable[CT_WHITE]); -// xAdd = (int) 8*cg.iconHUDPercent; -// CG_DrawPic( prongLeftX+xAdd, y2-10, 40, 80, background); -// CG_DrawPic( prongRightX-xAdd, y2-10, -40, 80, background); - + // trap->R_SetColor( colorTable[CT_WHITE]); + // xAdd = (int) 8*cg.iconHUDPercent; + // CG_DrawPic( prongLeftX+xAdd, y2-10, 40, 80, background); + // CG_DrawPic( prongRightX-xAdd, y2-10, -40, 80, background); } -qboolean CG_WeaponCheck(int weap) -{ +qboolean CG_WeaponCheck(int weap) { if (cg.snap->ps.ammo[weaponData[weap].ammoIndex] < weaponData[weap].energyPerShot && - cg.snap->ps.ammo[weaponData[weap].ammoIndex] < weaponData[weap].altEnergyPerShot) - { + cg.snap->ps.ammo[weaponData[weap].ammoIndex] < weaponData[weap].altEnergyPerShot) { return qfalse; } @@ -1054,28 +931,24 @@ qboolean CG_WeaponCheck(int weap) CG_WeaponSelectable =============== */ -static qboolean CG_WeaponSelectable( int i ) { +static qboolean CG_WeaponSelectable(int i) { /*if ( !cg.snap->ps.ammo[weaponData[i].ammoIndex] ) { return qfalse; }*/ - if (!i) - { + if (!i) { return qfalse; } if (cg.predictedPlayerState.ammo[weaponData[i].ammoIndex] < weaponData[i].energyPerShot && - cg.predictedPlayerState.ammo[weaponData[i].ammoIndex] < weaponData[i].altEnergyPerShot) - { + cg.predictedPlayerState.ammo[weaponData[i].ammoIndex] < weaponData[i].altEnergyPerShot) { return qfalse; } - if (i == WP_DET_PACK && cg.predictedPlayerState.ammo[weaponData[i].ammoIndex] < 1 && - !cg.predictedPlayerState.hasDetPackPlanted) - { + if (i == WP_DET_PACK && cg.predictedPlayerState.ammo[weaponData[i].ammoIndex] < 1 && !cg.predictedPlayerState.hasDetPackPlanted) { return qfalse; } - if ( ! (cg.predictedPlayerState.stats[ STAT_WEAPONS ] & ( 1 << i ) ) ) { + if (!(cg.predictedPlayerState.stats[STAT_WEAPONS] & (1 << i))) { return qfalse; } @@ -1087,96 +960,84 @@ static qboolean CG_WeaponSelectable( int i ) { CG_DrawWeaponSelect =================== */ -void CG_DrawWeaponSelect( void ) { - int i; - int bits; - int count; - int smallIconSize,bigIconSize; - int holdX,x,y,pad; - int sideLeftIconCnt,sideRightIconCnt; - int sideMax,holdCount,iconCnt; -// int height; - int yOffset = 0; +void CG_DrawWeaponSelect(void) { + int i; + int bits; + int count; + int smallIconSize, bigIconSize; + int holdX, x, y, pad; + int sideLeftIconCnt, sideRightIconCnt; + int sideMax, holdCount, iconCnt; + // int height; + int yOffset = 0; qboolean drewConc = qfalse; - if (cg.predictedPlayerState.emplacedIndex) - { //can't cycle when on a weapon + if (cg.predictedPlayerState.emplacedIndex) { // can't cycle when on a weapon cg.weaponSelectTime = 0; } - if ((cg.weaponSelectTime+WEAPON_SELECT_TIME) (2*sideMax)) // Go to the max on each side + } else if (count > (2 * sideMax)) // Go to the max on each side { sideLeftIconCnt = sideMax; sideRightIconCnt = sideMax; - } - else // Less than max, so do the calc + } else // Less than max, so do the calc { - sideLeftIconCnt = holdCount/2; + sideLeftIconCnt = holdCount / 2; sideRightIconCnt = holdCount - sideLeftIconCnt; } - if ( cg.weaponSelect == WP_CONCUSSION ) - { + if (cg.weaponSelect == WP_CONCUSSION) { i = WP_FLECHETTE; - } - else - { + } else { i = cg.weaponSelect - 1; } - if (i<1) - { + if (i < 1) { i = LAST_USEABLE_WEAPON; } @@ -1188,257 +1049,208 @@ void CG_DrawWeaponSelect( void ) { y = 410; // Background -// memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); -// calcColor[3] = .35f; -// trap->R_SetColor( calcColor); + // memcpy(calcColor, colorTable[CT_WHITE], sizeof(vec4_t)); + // calcColor[3] = .35f; + // trap->R_SetColor( calcColor); // Left side ICONS trap->R_SetColor(colorTable[CT_WHITE]); // Work backwards from current icon - holdX = x - ((bigIconSize/2) + pad + smallIconSize); -// height = smallIconSize * 1;//cg.iconHUDPercent; + holdX = x - ((bigIconSize / 2) + pad + smallIconSize); + // height = smallIconSize * 1;//cg.iconHUDPercent; drewConc = qfalse; - for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--) - { - if ( i == WP_CONCUSSION ) - { + for (iconCnt = 1; iconCnt < (sideLeftIconCnt + 1); i--) { + if (i == WP_CONCUSSION) { i--; - } - else if ( i == WP_FLECHETTE && !drewConc && cg.weaponSelect != WP_CONCUSSION ) - { + } else if (i == WP_FLECHETTE && !drewConc && cg.weaponSelect != WP_CONCUSSION) { i = WP_CONCUSSION; } - if (i<1) - { - //i = 13; + if (i < 1) { + // i = 13; //...don't ever do this. i = LAST_USEABLE_WEAPON; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } continue; } - if ( !CG_WeaponSelectable(i) && - (i == WP_THERMAL || i == WP_TRIP_MINE) ) - { //Don't show thermal and tripmine when out of them + if (!CG_WeaponSelectable(i) && (i == WP_THERMAL || i == WP_TRIP_MINE)) { // Don't show thermal and tripmine when out of them continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (cgs.media.weaponIcons[i]) - { - // weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); - // weaponInfo = &cg_weapons[i]; + if (cgs.media.weaponIcons[i]) { + // weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); + // weaponInfo = &cg_weapons[i]; trap->R_SetColor(colorTable[CT_WHITE]); - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, /*weaponInfo->weaponIconNoAmmo*/cgs.media.weaponIcons_NA[i] ); - } - else - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, /*weaponInfo->weaponIcon*/cgs.media.weaponIcons[i] ); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, /*weaponInfo->weaponIconNoAmmo*/ cgs.media.weaponIcons_NA[i]); + } else { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, /*weaponInfo->weaponIcon*/ cgs.media.weaponIcons[i]); } - holdX -= (smallIconSize+pad); + holdX -= (smallIconSize + pad); } - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_ROCKET_LAUNCHER; } } // Current Center Icon -// height = bigIconSize * cg.iconHUDPercent; - if (cgs.media.weaponIcons[cg.weaponSelect]) - { - // weaponInfo_t *weaponInfo; - CG_RegisterWeapon( cg.weaponSelect ); - // weaponInfo = &cg_weapons[cg.weaponSelect]; + // height = bigIconSize * cg.iconHUDPercent; + if (cgs.media.weaponIcons[cg.weaponSelect]) { + // weaponInfo_t *weaponInfo; + CG_RegisterWeapon(cg.weaponSelect); + // weaponInfo = &cg_weapons[cg.weaponSelect]; - trap->R_SetColor( colorTable[CT_WHITE]); - if (!CG_WeaponCheck(cg.weaponSelect)) - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10+yOffset, bigIconSize, bigIconSize, cgs.media.weaponIcons_NA[cg.weaponSelect] ); - } - else - { - CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10+yOffset, bigIconSize, bigIconSize, cgs.media.weaponIcons[cg.weaponSelect] ); + trap->R_SetColor(colorTable[CT_WHITE]); + if (!CG_WeaponCheck(cg.weaponSelect)) { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize, bigIconSize, + cgs.media.weaponIcons_NA[cg.weaponSelect]); + } else { + CG_DrawPic(x - (bigIconSize / 2), (y - ((bigIconSize - smallIconSize) / 2)) + 10 + yOffset, bigIconSize, bigIconSize, + cgs.media.weaponIcons[cg.weaponSelect]); } } - if ( cg.weaponSelect == WP_CONCUSSION ) - { + if (cg.weaponSelect == WP_CONCUSSION) { i = WP_ROCKET_LAUNCHER; - } - else - { + } else { i = cg.weaponSelect + 1; } - if (i> LAST_USEABLE_WEAPON) - { + if (i > LAST_USEABLE_WEAPON) { i = 1; } // Right side ICONS // Work forwards from current icon - holdX = x + (bigIconSize/2) + pad; -// height = smallIconSize * cg.iconHUDPercent; - for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++) - { - if ( i == WP_CONCUSSION ) - { + holdX = x + (bigIconSize / 2) + pad; + // height = smallIconSize * cg.iconHUDPercent; + for (iconCnt = 1; iconCnt < (sideRightIconCnt + 1); i++) { + if (i == WP_CONCUSSION) { i++; - } - else if ( i == WP_ROCKET_LAUNCHER && !drewConc && cg.weaponSelect != WP_CONCUSSION ) - { + } else if (i == WP_ROCKET_LAUNCHER && !drewConc && cg.weaponSelect != WP_CONCUSSION) { i = WP_CONCUSSION; } - if (i>LAST_USEABLE_WEAPON) - { + if (i > LAST_USEABLE_WEAPON) { i = 1; } - if ( !(bits & ( 1 << i ))) // Does he have this weapon? + if (!(bits & (1 << i))) // Does he have this weapon? { - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_FLECHETTE; } continue; } - if ( !CG_WeaponSelectable(i) && - (i == WP_THERMAL || i == WP_TRIP_MINE) ) - { //Don't show thermal and tripmine when out of them + if (!CG_WeaponSelectable(i) && (i == WP_THERMAL || i == WP_TRIP_MINE)) { // Don't show thermal and tripmine when out of them continue; } - ++iconCnt; // Good icon + ++iconCnt; // Good icon - if (/*weaponData[i].weaponIcon[0]*/cgs.media.weaponIcons[i]) - { - // weaponInfo_t *weaponInfo; - CG_RegisterWeapon( i ); - // weaponInfo = &cg_weapons[i]; + if (/*weaponData[i].weaponIcon[0]*/ cgs.media.weaponIcons[i]) { + // weaponInfo_t *weaponInfo; + CG_RegisterWeapon(i); + // weaponInfo = &cg_weapons[i]; // No ammo for this weapon? - trap->R_SetColor( colorTable[CT_WHITE]); - if (!CG_WeaponCheck(i)) - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, cgs.media.weaponIcons_NA[i] ); - } - else - { - CG_DrawPic( holdX, y+10+yOffset, smallIconSize, smallIconSize, cgs.media.weaponIcons[i] ); + trap->R_SetColor(colorTable[CT_WHITE]); + if (!CG_WeaponCheck(i)) { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, cgs.media.weaponIcons_NA[i]); + } else { + CG_DrawPic(holdX, y + 10 + yOffset, smallIconSize, smallIconSize, cgs.media.weaponIcons[i]); } - - holdX += (smallIconSize+pad); + holdX += (smallIconSize + pad); } - if ( i == WP_CONCUSSION ) - { + if (i == WP_CONCUSSION) { drewConc = qtrue; i = WP_FLECHETTE; } } // draw the selected name - if ( cg_weapons[ cg.weaponSelect ].item ) - { - vec4_t textColor = { .875f, .718f, .121f, 1.0f }; - char text[1024]; - char upperKey[1024]; + if (cg_weapons[cg.weaponSelect].item) { + vec4_t textColor = {.875f, .718f, .121f, 1.0f}; + char text[1024]; + char upperKey[1024]; - strcpy(upperKey, cg_weapons[ cg.weaponSelect ].item->classname); + strcpy(upperKey, cg_weapons[cg.weaponSelect].item->classname); - if ( trap->SE_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text ))) - { - CG_DrawProportionalString(320, y+45+yOffset, text, UI_CENTER|UI_SMALLFONT, textColor); - } - else - { - CG_DrawProportionalString(320, y+45+yOffset, cg_weapons[ cg.weaponSelect ].item->classname, UI_CENTER|UI_SMALLFONT, textColor); + if (trap->SE_GetStringTextString(va("SP_INGAME_%s", Q_strupr(upperKey)), text, sizeof(text))) { + CG_DrawProportionalString(320, y + 45 + yOffset, text, UI_CENTER | UI_SMALLFONT, textColor); + } else { + CG_DrawProportionalString(320, y + 45 + yOffset, cg_weapons[cg.weaponSelect].item->classname, UI_CENTER | UI_SMALLFONT, textColor); } } - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } - /* =============== CG_NextWeapon_f =============== */ -void CG_NextWeapon_f( void ) { - int i; - int original; +void CG_NextWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } - if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } - if (cg.snap->ps.emplacedIndex) - { + if (cg.snap->ps.emplacedIndex) { return; } cg.weaponSelectTime = cg.time; original = cg.weaponSelect; - for ( i = 0 ; i < WP_NUM_WEAPONS ; i++ ) { + for (i = 0; i < WP_NUM_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.weaponSelect == WP_FLECHETTE ) - { + if (cg.weaponSelect == WP_FLECHETTE) { cg.weaponSelect = WP_CONCUSSION; - } - else if ( cg.weaponSelect == WP_CONCUSSION ) - { + } else if (cg.weaponSelect == WP_CONCUSSION) { cg.weaponSelect = WP_ROCKET_LAUNCHER; - } - else if ( cg.weaponSelect == WP_DET_PACK ) - { + } else if (cg.weaponSelect == WP_DET_PACK) { cg.weaponSelect = WP_BRYAR_OLD; - } - else - { + } else { cg.weaponSelect++; } - if ( cg.weaponSelect == WP_NUM_WEAPONS ) { + if (cg.weaponSelect == WP_NUM_WEAPONS) { cg.weaponSelect = 0; } - // if ( cg.weaponSelect == WP_STUN_BATON ) { - // continue; // never cycle to gauntlet - // } - if ( CG_WeaponSelectable( cg.weaponSelect ) ) { + // if ( cg.weaponSelect == WP_STUN_BATON ) { + // continue; // never cycle to gauntlet + // } + if (CG_WeaponSelectable(cg.weaponSelect)) { break; } } - if ( i == WP_NUM_WEAPONS ) { + if (i == WP_NUM_WEAPONS) { cg.weaponSelect = original; - } - else - { + } else { trap->S_MuteSound(cg.snap->ps.clientNum, CHAN_WEAPON); } } @@ -1448,63 +1260,52 @@ void CG_NextWeapon_f( void ) { CG_PrevWeapon_f =============== */ -void CG_PrevWeapon_f( void ) { - int i; - int original; +void CG_PrevWeapon_f(void) { + int i; + int original; - if ( !cg.snap ) { + if (!cg.snap) { return; } - if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) - { + if (cg.predictedPlayerState.pm_type == PM_SPECTATOR) { return; } - if (cg.snap->ps.emplacedIndex) - { + if (cg.snap->ps.emplacedIndex) { return; } cg.weaponSelectTime = cg.time; original = cg.weaponSelect; - for ( i = 0 ; i < WP_NUM_WEAPONS ; i++ ) { + for (i = 0; i < WP_NUM_WEAPONS; i++) { //*SIGH*... Hack to put concussion rifle before rocketlauncher - if ( cg.weaponSelect == WP_ROCKET_LAUNCHER ) - { + if (cg.weaponSelect == WP_ROCKET_LAUNCHER) { cg.weaponSelect = WP_CONCUSSION; - } - else if ( cg.weaponSelect == WP_CONCUSSION ) - { + } else if (cg.weaponSelect == WP_CONCUSSION) { cg.weaponSelect = WP_FLECHETTE; - } - else if ( cg.weaponSelect == WP_BRYAR_OLD ) - { + } else if (cg.weaponSelect == WP_BRYAR_OLD) { cg.weaponSelect = WP_DET_PACK; - } - else - { + } else { cg.weaponSelect--; } - if ( cg.weaponSelect == -1 ) { - cg.weaponSelect = WP_NUM_WEAPONS-1; + if (cg.weaponSelect == -1) { + cg.weaponSelect = WP_NUM_WEAPONS - 1; } - // if ( cg.weaponSelect == WP_STUN_BATON ) { - // continue; // never cycle to gauntlet - // } - if ( CG_WeaponSelectable( cg.weaponSelect ) ) { + // if ( cg.weaponSelect == WP_STUN_BATON ) { + // continue; // never cycle to gauntlet + // } + if (CG_WeaponSelectable(cg.weaponSelect)) { break; } } - if ( i == WP_NUM_WEAPONS ) { + if (i == WP_NUM_WEAPONS) { cg.weaponSelect = original; - } - else - { + } else { trap->S_MuteSound(cg.snap->ps.clientNum, CHAN_WEAPON); } } @@ -1514,86 +1315,69 @@ void CG_PrevWeapon_f( void ) { CG_Weapon_f =============== */ -void CG_Weapon_f( void ) { - int num; +void CG_Weapon_f(void) { + int num; - if ( !cg.snap ) { + if (!cg.snap) { return; } - if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.snap->ps.emplacedIndex) - { + if (cg.snap->ps.emplacedIndex) { return; } - num = atoi( CG_Argv( 1 ) ); + num = atoi(CG_Argv(1)); - if ( num < 1 || num > LAST_USEABLE_WEAPON ) { + if (num < 1 || num > LAST_USEABLE_WEAPON) { return; } - if (num == 1 && cg.snap->ps.weapon == WP_SABER) - { + if (num == 1 && cg.snap->ps.weapon == WP_SABER) { if (cg.predictedPlayerState.weaponTime < 1) - // if (cg.snap->ps.weaponTime < 1) + // if (cg.snap->ps.weaponTime < 1) { trap->SendConsoleCommand("sv_saberswitch\n"); } return; } - //rww - hack to make weapon numbers same as single player - if (num > WP_STUN_BATON) - { - //num++; - num += 2; //I suppose this is getting kind of crazy, what with the wp_melee in there too now. - } - else - { - if (cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) - { + // rww - hack to make weapon numbers same as single player + if (num > WP_STUN_BATON) { + // num++; + num += 2; // I suppose this is getting kind of crazy, what with the wp_melee in there too now. + } else { + if (cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { num = WP_SABER; - } - else - { + } else { num = WP_MELEE; } } - if (num > LAST_USEABLE_WEAPON+1) - { //other weapons are off limits due to not actually being weapon weapons + if (num > LAST_USEABLE_WEAPON + 1) { // other weapons are off limits due to not actually being weapon weapons return; } - if (num >= WP_THERMAL && num <= WP_DET_PACK) - { + if (num >= WP_THERMAL && num <= WP_DET_PACK) { int weap, i = 0; - if (cg.snap->ps.weapon >= WP_THERMAL && - cg.snap->ps.weapon <= WP_DET_PACK) - { + if (cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK) { // already in cycle range so start with next cycle item weap = cg.snap->ps.weapon + 1; - } - else - { + } else { // not in cycle range, so start with thermal detonator weap = WP_THERMAL; } // prevent an endless loop - while ( i <= 4 ) - { - if (weap > WP_DET_PACK) - { + while (i <= 4) { + if (weap > WP_DET_PACK) { weap = WP_THERMAL; } - if (CG_WeaponSelectable(weap)) - { + if (CG_WeaponSelectable(weap)) { num = weap; break; } @@ -1603,113 +1387,90 @@ void CG_Weapon_f( void ) { } } - if (!CG_WeaponSelectable(num)) - { + if (!CG_WeaponSelectable(num)) { return; } cg.weaponSelectTime = cg.time; - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - { - if (num == WP_SABER) - { //don't have saber, try melee on the same slot + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { + if (num == WP_SABER) { // don't have saber, try melee on the same slot num = WP_MELEE; - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - { + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { return; } - } - else - { - return; // don't have the weapon + } else { + return; // don't have the weapon } } - if (cg.weaponSelect != num) - { + if (cg.weaponSelect != num) { trap->S_MuteSound(cg.snap->ps.clientNum, CHAN_WEAPON); } cg.weaponSelect = num; } +// Version of the above which doesn't add +2 to a weapon. The above can't +// triger WP_MELEE or WP_STUN_BATON. Derogatory comments go here. +void CG_WeaponClean_f(void) { + int num; -//Version of the above which doesn't add +2 to a weapon. The above can't -//triger WP_MELEE or WP_STUN_BATON. Derogatory comments go here. -void CG_WeaponClean_f( void ) { - int num; - - if ( !cg.snap ) { + if (!cg.snap) { return; } - if ( cg.snap->ps.pm_flags & PMF_FOLLOW ) { + if (cg.snap->ps.pm_flags & PMF_FOLLOW) { return; } - if (cg.snap->ps.emplacedIndex) - { + if (cg.snap->ps.emplacedIndex) { return; } - num = atoi( CG_Argv( 1 ) ); + num = atoi(CG_Argv(1)); - if ( num < 1 || num > LAST_USEABLE_WEAPON ) { + if (num < 1 || num > LAST_USEABLE_WEAPON) { return; } - if (num == 1 && cg.snap->ps.weapon == WP_SABER) - { - if (cg.snap->ps.weaponTime < 1) - { + if (num == 1 && cg.snap->ps.weapon == WP_SABER) { + if (cg.snap->ps.weaponTime < 1) { trap->SendConsoleCommand("sv_saberswitch\n"); } return; } - if(num == WP_STUN_BATON) { - if (cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) - { + if (num == WP_STUN_BATON) { + if (cg.snap->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { num = WP_SABER; - } - else - { + } else { num = WP_MELEE; } } - if (num > LAST_USEABLE_WEAPON+1) - { //other weapons are off limits due to not actually being weapon weapons + if (num > LAST_USEABLE_WEAPON + 1) { // other weapons are off limits due to not actually being weapon weapons return; } - if (num >= WP_THERMAL && num <= WP_DET_PACK) - { + if (num >= WP_THERMAL && num <= WP_DET_PACK) { int weap, i = 0; - if (cg.snap->ps.weapon >= WP_THERMAL && - cg.snap->ps.weapon <= WP_DET_PACK) - { + if (cg.snap->ps.weapon >= WP_THERMAL && cg.snap->ps.weapon <= WP_DET_PACK) { // already in cycle range so start with next cycle item weap = cg.snap->ps.weapon + 1; - } - else - { + } else { // not in cycle range, so start with thermal detonator weap = WP_THERMAL; } // prevent an endless loop - while ( i <= 4 ) - { - if (weap > WP_DET_PACK) - { + while (i <= 4) { + if (weap > WP_DET_PACK) { weap = WP_THERMAL; } - if (CG_WeaponSelectable(weap)) - { + if (CG_WeaponSelectable(weap)) { num = weap; break; } @@ -1719,40 +1480,31 @@ void CG_WeaponClean_f( void ) { } } - if (!CG_WeaponSelectable(num)) - { + if (!CG_WeaponSelectable(num)) { return; } cg.weaponSelectTime = cg.time; - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - { - if (num == WP_SABER) - { //don't have saber, try melee on the same slot + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { + if (num == WP_SABER) { // don't have saber, try melee on the same slot num = WP_MELEE; - if ( ! ( cg.snap->ps.stats[STAT_WEAPONS] & ( 1 << num ) ) ) - { + if (!(cg.snap->ps.stats[STAT_WEAPONS] & (1 << num))) { return; } - } - else - { - return; // don't have the weapon + } else { + return; // don't have the weapon } } - if (cg.weaponSelect != num) - { + if (cg.weaponSelect != num) { trap->S_MuteSound(cg.snap->ps.clientNum, CHAN_WEAPON); } cg.weaponSelect = num; } - - /* =================== CG_OutOfAmmoChange @@ -1760,25 +1512,21 @@ CG_OutOfAmmoChange The current weapon has just run out of ammo =================== */ -void CG_OutOfAmmoChange( int oldWeapon ) -{ - int i; +void CG_OutOfAmmoChange(int oldWeapon) { + int i; cg.weaponSelectTime = cg.time; - for ( i = LAST_USEABLE_WEAPON ; i > 0 ; i-- ) //We don't want the emplaced or turret + for (i = LAST_USEABLE_WEAPON; i > 0; i--) // We don't want the emplaced or turret { - if ( CG_WeaponSelectable( i ) ) - { + if (CG_WeaponSelectable(i)) { /* if ( 1 == cg_autoswitch.integer && ( i == WP_TRIP_MINE || i == WP_DET_PACK || i == WP_THERMAL || i == WP_ROCKET_LAUNCHER) ) // safe weapon switch */ - //rww - Don't we want to make sure i != one of these if autoswitch is 1 (safe)? - if (cg_autoSwitch.integer != 1 || (i != WP_TRIP_MINE && i != WP_DET_PACK && i != WP_THERMAL && i != WP_ROCKET_LAUNCHER)) - { - if (i != oldWeapon) - { //don't even do anything if we're just selecting the weapon we already have/had + // rww - Don't we want to make sure i != one of these if autoswitch is 1 (safe)? + if (cg_autoSwitch.integer != 1 || (i != WP_TRIP_MINE && i != WP_DET_PACK && i != WP_THERMAL && i != WP_ROCKET_LAUNCHER)) { + if (i != oldWeapon) { // don't even do anything if we're just selecting the weapon we already have/had cg.weaponSelect = i; break; } @@ -1789,8 +1537,6 @@ void CG_OutOfAmmoChange( int oldWeapon ) trap->S_MuteSound(cg.snap->ps.clientNum, CHAN_WEAPON); } - - /* =================================================================================================== @@ -1799,21 +1545,17 @@ WEAPON EVENTS =================================================================================================== */ -void CG_GetClientWeaponMuzzleBoltPoint(int clIndex, vec3_t to) -{ +void CG_GetClientWeaponMuzzleBoltPoint(int clIndex, vec3_t to) { centity_t *cent; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; - if (clIndex < 0 || clIndex >= MAX_CLIENTS) - { + if (clIndex < 0 || clIndex >= MAX_CLIENTS) { return; } cent = &cg_entities[clIndex]; - if (!cent || !cent->ghoul2 || !trap->G2_HaveWeGhoul2Models(cent->ghoul2) || - !trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) - { + if (!cent || !cent->ghoul2 || !trap->G2_HaveWeGhoul2Models(cent->ghoul2) || !trap->G2API_HasGhoul2ModelOnIndex(&(cent->ghoul2), 1)) { return; } @@ -1828,145 +1570,117 @@ CG_FireWeapon Caused by an EV_FIRE_WEAPON event ================ */ -void CG_FireWeapon( centity_t *cent, qboolean altFire ) { +void CG_FireWeapon(centity_t *cent, qboolean altFire) { entityState_t *ent; - int c; - weaponInfo_t *weap; + int c; + weaponInfo_t *weap; ent = ¢->currentState; - if ( ent->weapon == WP_NONE ) { + if (ent->weapon == WP_NONE) { return; } - if ( ent->weapon >= WP_NUM_WEAPONS ) { - trap->Error( ERR_DROP, "CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS" ); + if (ent->weapon >= WP_NUM_WEAPONS) { + trap->Error(ERR_DROP, "CG_FireWeapon: ent->weapon >= WP_NUM_WEAPONS"); return; } - weap = &cg_weapons[ ent->weapon ]; + weap = &cg_weapons[ent->weapon]; // mark the entity as muzzle flashing, so when it is added it will // append the flash to the weapon model cent->muzzleFlashTime = cg.time; - if (cg.predictedPlayerState.clientNum == cent->currentState.number) - { - if ((ent->weapon == WP_BRYAR_PISTOL && altFire) || - (ent->weapon == WP_BRYAR_OLD && altFire) || - (ent->weapon == WP_BOWCASTER && !altFire) || - (ent->weapon == WP_DEMP2 && altFire)) - { - float val = ( cg.time - cent->currentState.constantLight ) * 0.001f; + if (cg.predictedPlayerState.clientNum == cent->currentState.number) { + if ((ent->weapon == WP_BRYAR_PISTOL && altFire) || (ent->weapon == WP_BRYAR_OLD && altFire) || (ent->weapon == WP_BOWCASTER && !altFire) || + (ent->weapon == WP_DEMP2 && altFire)) { + float val = (cg.time - cent->currentState.constantLight) * 0.001f; - if (val > 3.0f) - { + if (val > 3.0f) { val = 3.0f; } - if (val < 0.2f) - { + if (val < 0.2f) { val = 0.2f; } val *= 2; - CGCam_Shake( val, 250 ); - } - else if (ent->weapon == WP_ROCKET_LAUNCHER || - (ent->weapon == WP_REPEATER && altFire) || - ent->weapon == WP_FLECHETTE || - (ent->weapon == WP_CONCUSSION && !altFire)) - { - if (ent->weapon == WP_CONCUSSION) - { - if (!cg.renderingThirdPerson )//gives an advantage to being in 3rd person, but would look silly otherwise - {//kick the view back - cg.kick_angles[PITCH] = flrand( -10, -15 ); + CGCam_Shake(val, 250); + } else if (ent->weapon == WP_ROCKET_LAUNCHER || (ent->weapon == WP_REPEATER && altFire) || ent->weapon == WP_FLECHETTE || + (ent->weapon == WP_CONCUSSION && !altFire)) { + if (ent->weapon == WP_CONCUSSION) { + if (!cg.renderingThirdPerson) // gives an advantage to being in 3rd person, but would look silly otherwise + { // kick the view back + cg.kick_angles[PITCH] = flrand(-10, -15); cg.kick_time = cg.time; } - } - else if (ent->weapon == WP_ROCKET_LAUNCHER) - { + } else if (ent->weapon == WP_ROCKET_LAUNCHER) { CGCam_Shake(flrand(2, 3), 350); - } - else if (ent->weapon == WP_REPEATER) - { + } else if (ent->weapon == WP_REPEATER) { CGCam_Shake(flrand(2, 3), 350); - } - else if (ent->weapon == WP_FLECHETTE) - { - if (altFire) - { + } else if (ent->weapon == WP_FLECHETTE) { + if (altFire) { CGCam_Shake(flrand(2, 3), 350); - } - else - { + } else { CGCam_Shake(1.5, 250); } } } } // lightning gun only does this this on initial press - if ( ent->weapon == WP_DEMP2 ) { - if ( cent->pe.lightningFiring ) { + if (ent->weapon == WP_DEMP2) { + if (cent->pe.lightningFiring) { return; } } - #ifdef BASE_COMPAT - // play quad sound if needed - if ( cent->currentState.powerups & ( 1 << PW_QUAD ) ) { - //trap->S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.media.quadSound ); - } - #endif // BASE_COMPAT - +#ifdef BASE_COMPAT + // play quad sound if needed + if (cent->currentState.powerups & (1 << PW_QUAD)) { + // trap->S_StartSound (NULL, cent->currentState.number, CHAN_ITEM, cgs.media.quadSound ); + } +#endif // BASE_COMPAT // play a sound - if (altFire) - { + if (altFire) { // play a sound - for ( c = 0 ; c < 4 ; c++ ) { - if ( !weap->altFlashSound[c] ) { + for (c = 0; c < 4; c++) { + if (!weap->altFlashSound[c]) { break; } } - if ( c > 0 ) { + if (c > 0) { c = rand() % c; - if ( weap->altFlashSound[c] ) - { - trap->S_StartSound( NULL, ent->number, CHAN_WEAPON, weap->altFlashSound[c] ); + if (weap->altFlashSound[c]) { + trap->S_StartSound(NULL, ent->number, CHAN_WEAPON, weap->altFlashSound[c]); } } -// if ( weap->altFlashSnd ) -// { -// trap->S_StartSound( NULL, ent->number, CHAN_WEAPON, weap->altFlashSnd ); -// } - } - else - { + // if ( weap->altFlashSnd ) + // { + // trap->S_StartSound( NULL, ent->number, CHAN_WEAPON, weap->altFlashSnd ); + // } + } else { // play a sound - for ( c = 0 ; c < 4 ; c++ ) { - if ( !weap->flashSound[c] ) { + for (c = 0; c < 4; c++) { + if (!weap->flashSound[c]) { break; } } - if ( c > 0 ) { + if (c > 0) { c = rand() % c; - if ( weap->flashSound[c] ) - { - trap->S_StartSound( NULL, ent->number, CHAN_WEAPON, weap->flashSound[c] ); + if (weap->flashSound[c]) { + trap->S_StartSound(NULL, ent->number, CHAN_WEAPON, weap->flashSound[c]); } } } } -qboolean CG_VehicleWeaponImpact( centity_t *cent ) -{//see if this is a missile entity that's owned by a vehicle and should do a special, overridden impact effect - if ((cent->currentState.eFlags&EF_JETPACK_ACTIVE)//hack so we know we're a vehicle Weapon shot - && cent->currentState.otherEntityNum2 - && g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX) - {//missile is from a special vehWeapon +qboolean CG_VehicleWeaponImpact(centity_t *cent) { // see if this is a missile entity that's owned by a vehicle and should do a special, overridden impact + // effect + if ((cent->currentState.eFlags & EF_JETPACK_ACTIVE) // hack so we know we're a vehicle Weapon shot + && cent->currentState.otherEntityNum2 && g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX) { // missile is from a special vehWeapon vec3_t normal; - ByteToDir( cent->currentState.eventParm, normal ); + ByteToDir(cent->currentState.eventParm, normal); - trap->FX_PlayEffectID( g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX, cent->lerpOrigin, normal, -1, -1, qfalse ); + trap->FX_PlayEffectID(g_vehWeaponInfo[cent->currentState.otherEntityNum2].iImpactFX, cent->lerpOrigin, normal, -1, -1, qfalse); return qtrue; } return qfalse; @@ -1979,76 +1693,62 @@ CG_MissileHitWall Caused by an EV_MISSILE_MISS event, or directly by local bullet tracing ================= */ -void CG_MissileHitWall(int weapon, int clientNum, vec3_t origin, vec3_t dir, impactSound_t soundType, qboolean altFire, int charge) -{ +void CG_MissileHitWall(int weapon, int clientNum, vec3_t origin, vec3_t dir, impactSound_t soundType, qboolean altFire, int charge) { int parm; - vec3_t up={0,0,1}; + vec3_t up = {0, 0, 1}; - switch( weapon ) - { + switch (weapon) { case WP_BRYAR_PISTOL: - if ( altFire ) - { + if (altFire) { parm = charge; - FX_BryarAltHitWall( origin, dir, parm ); - } - else - { - FX_BryarHitWall( origin, dir ); + FX_BryarAltHitWall(origin, dir, parm); + } else { + FX_BryarHitWall(origin, dir); } break; case WP_CONCUSSION: - FX_ConcussionHitWall( origin, dir ); + FX_ConcussionHitWall(origin, dir); break; case WP_BRYAR_OLD: - if ( altFire ) - { + if (altFire) { parm = charge; - FX_BryarAltHitWall( origin, dir, parm ); - } - else - { - FX_BryarHitWall( origin, dir ); + FX_BryarAltHitWall(origin, dir, parm); + } else { + FX_BryarHitWall(origin, dir); } break; case WP_TURRET: - FX_TurretHitWall( origin, dir ); + FX_TurretHitWall(origin, dir); break; case WP_BLASTER: - FX_BlasterWeaponHitWall( origin, dir ); + FX_BlasterWeaponHitWall(origin, dir); break; case WP_DISRUPTOR: - FX_DisruptorAltMiss( origin, dir ); + FX_DisruptorAltMiss(origin, dir); break; case WP_BOWCASTER: - FX_BowcasterHitWall( origin, dir ); + FX_BowcasterHitWall(origin, dir); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitWall( origin, dir ); - } - else - { - FX_RepeaterHitWall( origin, dir ); + if (altFire) { + FX_RepeaterAltHitWall(origin, dir); + } else { + FX_RepeaterHitWall(origin, dir); } break; case WP_DEMP2: - if (altFire) - { + if (altFire) { trap->FX_PlayEffectID(cgs.effects.mAltDetonate, origin, dir, -1, -1, qfalse); - } - else - { - FX_DEMP2_HitWall( origin, dir ); + } else { + FX_DEMP2_HitWall(origin, dir); } break; @@ -2059,38 +1759,35 @@ void CG_MissileHitWall(int weapon, int clientNum, vec3_t origin, vec3_t dir, imp } else */ - if (!altFire) - { - FX_FlechetteWeaponHitWall( origin, dir ); + if (!altFire) { + FX_FlechetteWeaponHitWall(origin, dir); } break; case WP_ROCKET_LAUNCHER: - FX_RocketHitWall( origin, dir ); + FX_RocketHitWall(origin, dir); break; case WP_THERMAL: - trap->FX_PlayEffectID( cgs.effects.thermalExplosionEffect, origin, dir, -1, -1, qfalse ); - trap->FX_PlayEffectID( cgs.effects.thermalShockwaveEffect, origin, up, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.thermalExplosionEffect, origin, dir, -1, -1, qfalse); + trap->FX_PlayEffectID(cgs.effects.thermalShockwaveEffect, origin, up, -1, -1, qfalse); break; case WP_EMPLACED_GUN: - FX_BlasterWeaponHitWall( origin, dir ); - //FIXME: Give it its own hit wall effect + FX_BlasterWeaponHitWall(origin, dir); + // FIXME: Give it its own hit wall effect break; } } - /* ================= CG_MissileHitPlayer ================= */ -void CG_MissileHitPlayer(int weapon, vec3_t origin, vec3_t dir, int entityNum, qboolean altFire) -{ - qboolean humanoid = qtrue; - vec3_t up={0,0,1}; +void CG_MissileHitPlayer(int weapon, vec3_t origin, vec3_t dir, int entityNum, qboolean altFire) { + qboolean humanoid = qtrue; + vec3_t up = {0, 0, 1}; /* // NOTENOTE Non-portable code from single player @@ -2107,57 +1804,48 @@ void CG_MissileHitPlayer(int weapon, vec3_t origin, vec3_t dir, int entityNum, q // some weapons will make an explosion with the blood, while // others will just make the blood - switch ( weapon ) { + switch (weapon) { case WP_BRYAR_PISTOL: - if ( altFire ) - { - FX_BryarAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_BryarHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_BryarAltHitPlayer(origin, dir, humanoid); + } else { + FX_BryarHitPlayer(origin, dir, humanoid); } break; case WP_CONCUSSION: - FX_ConcussionHitPlayer( origin, dir, humanoid ); + FX_ConcussionHitPlayer(origin, dir, humanoid); break; case WP_BRYAR_OLD: - if ( altFire ) - { - FX_BryarAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_BryarHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_BryarAltHitPlayer(origin, dir, humanoid); + } else { + FX_BryarHitPlayer(origin, dir, humanoid); } break; case WP_TURRET: - FX_TurretHitPlayer( origin, dir, humanoid ); + FX_TurretHitPlayer(origin, dir, humanoid); break; case WP_BLASTER: - FX_BlasterWeaponHitPlayer( origin, dir, humanoid ); + FX_BlasterWeaponHitPlayer(origin, dir, humanoid); break; case WP_DISRUPTOR: - FX_DisruptorAltHit( origin, dir); + FX_DisruptorAltHit(origin, dir); break; case WP_BOWCASTER: - FX_BowcasterHitPlayer( origin, dir, humanoid ); + FX_BowcasterHitPlayer(origin, dir, humanoid); break; case WP_REPEATER: - if ( altFire ) - { - FX_RepeaterAltHitPlayer( origin, dir, humanoid ); - } - else - { - FX_RepeaterHitPlayer( origin, dir, humanoid ); + if (altFire) { + FX_RepeaterAltHitPlayer(origin, dir, humanoid); + } else { + FX_RepeaterHitPlayer(origin, dir, humanoid); } break; @@ -2171,31 +1859,28 @@ void CG_MissileHitPlayer(int weapon, vec3_t origin, vec3_t dir, int entityNum, q other->client->ps.powerups[PW_DISINT_1] = cg.time + 650; } */ - if (altFire) - { + if (altFire) { trap->FX_PlayEffectID(cgs.effects.mAltDetonate, origin, dir, -1, -1, qfalse); - } - else - { - FX_DEMP2_HitPlayer( origin, dir, humanoid ); + } else { + FX_DEMP2_HitPlayer(origin, dir, humanoid); } break; case WP_FLECHETTE: - FX_FlechetteWeaponHitPlayer( origin, dir, humanoid ); + FX_FlechetteWeaponHitPlayer(origin, dir, humanoid); break; case WP_ROCKET_LAUNCHER: - FX_RocketHitPlayer( origin, dir, humanoid ); + FX_RocketHitPlayer(origin, dir, humanoid); break; case WP_THERMAL: - trap->FX_PlayEffectID( cgs.effects.thermalExplosionEffect, origin, dir, -1, -1, qfalse ); - trap->FX_PlayEffectID( cgs.effects.thermalShockwaveEffect, origin, up, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.thermalExplosionEffect, origin, dir, -1, -1, qfalse); + trap->FX_PlayEffectID(cgs.effects.thermalShockwaveEffect, origin, up, -1, -1, qfalse); break; case WP_EMPLACED_GUN: - //FIXME: Its own effect? - FX_BlasterWeaponHitPlayer( origin, dir, humanoid ); + // FIXME: Its own effect? + FX_BlasterWeaponHitPlayer(origin, dir, humanoid); break; default: @@ -2203,7 +1888,6 @@ void CG_MissileHitPlayer(int weapon, vec3_t origin, vec3_t dir, int entityNum, q } } - /* ============================================================================ @@ -2212,67 +1896,55 @@ BULLETS ============================================================================ */ - /* ====================== CG_CalcMuzzlePoint ====================== */ -qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ) { - vec3_t forward, right; - vec3_t gunpoint; - centity_t *cent; - int anim; - - if ( entityNum == cg.snap->ps.clientNum ) - { //I'm not exactly sure why we'd be rendering someone else's crosshair, but hey. +qboolean CG_CalcMuzzlePoint(int entityNum, vec3_t muzzle) { + vec3_t forward, right; + vec3_t gunpoint; + centity_t *cent; + int anim; + + if (entityNum == cg.snap->ps.clientNum) { // I'm not exactly sure why we'd be rendering someone else's crosshair, but hey. int weapontype = cg.snap->ps.weapon; vec3_t weaponMuzzle; centity_t *pEnt = &cg_entities[cg.predictedPlayerState.clientNum]; VectorCopy(WP_MuzzlePoint[weapontype], weaponMuzzle); - if (weapontype == WP_DISRUPTOR || weapontype == WP_STUN_BATON || weapontype == WP_MELEE || weapontype == WP_SABER) - { + if (weapontype == WP_DISRUPTOR || weapontype == WP_STUN_BATON || weapontype == WP_MELEE || weapontype == WP_SABER) { VectorClear(weaponMuzzle); } - if (cg.renderingThirdPerson) - { - VectorCopy( pEnt->lerpOrigin, gunpoint ); - AngleVectors( pEnt->lerpAngles, forward, right, NULL ); - } - else - { - VectorCopy( cg.refdef.vieworg, gunpoint ); - AngleVectors( cg.refdef.viewangles, forward, right, NULL ); + if (cg.renderingThirdPerson) { + VectorCopy(pEnt->lerpOrigin, gunpoint); + AngleVectors(pEnt->lerpAngles, forward, right, NULL); + } else { + VectorCopy(cg.refdef.vieworg, gunpoint); + AngleVectors(cg.refdef.viewangles, forward, right, NULL); } - if (weapontype == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) - { + if (weapontype == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) { centity_t *gunEnt = &cg_entities[cg.snap->ps.emplacedIndex]; - if (gunEnt) - { + if (gunEnt) { vec3_t pitchConstraint; VectorCopy(gunEnt->lerpOrigin, gunpoint); gunpoint[2] += 46; - if (cg.renderingThirdPerson) - { + if (cg.renderingThirdPerson) { VectorCopy(pEnt->lerpAngles, pitchConstraint); - } - else - { + } else { VectorCopy(cg.refdef.viewangles, pitchConstraint); } - if (pitchConstraint[PITCH] > 40) - { + if (pitchConstraint[PITCH] > 40) { pitchConstraint[PITCH] = 40; } - AngleVectors( pitchConstraint, forward, right, NULL ); + AngleVectors(pitchConstraint, forward, right, NULL); } } @@ -2281,16 +1953,11 @@ qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ) { VectorMA(muzzle, weaponMuzzle[0], forward, muzzle); VectorMA(muzzle, weaponMuzzle[1], right, muzzle); - if (weapontype == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) - { - //Do nothing - } - else if (cg.renderingThirdPerson) - { + if (weapontype == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex) { + // Do nothing + } else if (cg.renderingThirdPerson) { muzzle[2] += cg.snap->ps.viewheight + weaponMuzzle[2]; - } - else - { + } else { muzzle[2] += weaponMuzzle[2]; } @@ -2298,28 +1965,25 @@ qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle ) { } cent = &cg_entities[entityNum]; - if ( !cent->currentValid ) { + if (!cent->currentValid) { return qfalse; } - VectorCopy( cent->currentState.pos.trBase, muzzle ); + VectorCopy(cent->currentState.pos.trBase, muzzle); - AngleVectors( cent->currentState.apos.trBase, forward, NULL, NULL ); + AngleVectors(cent->currentState.apos.trBase, forward, NULL, NULL); anim = cent->currentState.legsAnim; - if ( anim == BOTH_CROUCH1WALK || anim == BOTH_CROUCH1IDLE ) { + if (anim == BOTH_CROUCH1WALK || anim == BOTH_CROUCH1IDLE) { muzzle[2] += CROUCH_VIEWHEIGHT; } else { muzzle[2] += DEFAULT_VIEWHEIGHT; } - VectorMA( muzzle, 14, forward, muzzle ); + VectorMA(muzzle, 14, forward, muzzle); return qtrue; - } - - /* Ghoul2 Insert Start */ @@ -2327,136 +1991,100 @@ Ghoul2 Insert Start // create one instance of all the weapons we are going to use so we can just copy this info into each clients gun ghoul2 object in fast way static void *g2WeaponInstances[MAX_WEAPONS]; -void CG_InitG2Weapons(void) -{ +void CG_InitG2Weapons(void) { int i = 0; - gitem_t *item; + gitem_t *item; memset(g2WeaponInstances, 0, sizeof(g2WeaponInstances)); - for ( item = bg_itemlist + 1 ; item->classname ; item++ ) - { - if ( item->giType == IT_WEAPON ) - { + for (item = bg_itemlist + 1; item->classname; item++) { + if (item->giType == IT_WEAPON) { assert(item->giTag < MAX_WEAPONS); // initialise model - trap->G2API_InitGhoul2Model(&g2WeaponInstances[/*i*/item->giTag], item->world_model[0], 0, 0, 0, 0, 0); -// trap->G2API_InitGhoul2Model(&g2WeaponInstances[i], item->world_model[0],G_ModelIndex( item->world_model[0] ) , 0, 0, 0, 0); - if (g2WeaponInstances[/*i*/item->giTag]) - { + trap->G2API_InitGhoul2Model(&g2WeaponInstances[/*i*/ item->giTag], item->world_model[0], 0, 0, 0, 0, 0); + // trap->G2API_InitGhoul2Model(&g2WeaponInstances[i], item->world_model[0],G_ModelIndex( item->world_model[0] ) , 0, 0, 0, 0); + if (g2WeaponInstances[/*i*/ item->giTag]) { // indicate we will be bolted to model 0 (ie the player) on bolt 0 (always the right hand) when we get copied - trap->G2API_SetBoltInfo(g2WeaponInstances[/*i*/item->giTag], 0, 0); + trap->G2API_SetBoltInfo(g2WeaponInstances[/*i*/ item->giTag], 0, 0); // now set up the gun bolt on it - if (item->giTag == WP_SABER) - { - trap->G2API_AddBolt(g2WeaponInstances[/*i*/item->giTag], 0, "*blade1"); - } - else - { - trap->G2API_AddBolt(g2WeaponInstances[/*i*/item->giTag], 0, "*flash"); + if (item->giTag == WP_SABER) { + trap->G2API_AddBolt(g2WeaponInstances[/*i*/ item->giTag], 0, "*blade1"); + } else { + trap->G2API_AddBolt(g2WeaponInstances[/*i*/ item->giTag], 0, "*flash"); } i++; } - if (i == MAX_WEAPONS) - { + if (i == MAX_WEAPONS) { assert(0); break; } - } } } // clean out any g2 models we instanciated for copying purposes -void CG_ShutDownG2Weapons(void) -{ +void CG_ShutDownG2Weapons(void) { int i; - for (i=0; iG2API_CleanGhoul2Models(&g2WeaponInstances[i]); } } -void *CG_G2WeaponInstance(centity_t *cent, int weapon) -{ +void *CG_G2WeaponInstance(centity_t *cent, int weapon) { clientInfo_t *ci = NULL; - if (weapon != WP_SABER) - { + if (weapon != WP_SABER) { return g2WeaponInstances[weapon]; } - if (cent->currentState.eType != ET_PLAYER && - cent->currentState.eType != ET_NPC) - { + if (cent->currentState.eType != ET_PLAYER && cent->currentState.eType != ET_NPC) { return g2WeaponInstances[weapon]; } - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { ci = cent->npcClient; - } - else - { + } else { ci = &cgs.clientinfo[cent->currentState.number]; } - if (!ci) - { + if (!ci) { return g2WeaponInstances[weapon]; } - //Try to return the custom saber instance if we can. - if (ci->saber[0].model[0] && - ci->ghoul2Weapons[0]) - { + // Try to return the custom saber instance if we can. + if (ci->saber[0].model[0] && ci->ghoul2Weapons[0]) { return ci->ghoul2Weapons[0]; } - //If no custom then just use the default. + // If no custom then just use the default. return g2WeaponInstances[weapon]; } // what ghoul2 model do we want to copy ? -void CG_CopyG2WeaponInstance(centity_t *cent, int weaponNum, void *toGhoul2) -{ - //rww - the -1 is because there is no "weapon" for WP_NONE +void CG_CopyG2WeaponInstance(centity_t *cent, int weaponNum, void *toGhoul2) { + // rww - the -1 is because there is no "weapon" for WP_NONE assert(weaponNum < MAX_WEAPONS); - if (CG_G2WeaponInstance(cent, weaponNum/*-1*/)) - { - if (weaponNum == WP_SABER) - { + if (CG_G2WeaponInstance(cent, weaponNum /*-1*/)) { + if (weaponNum == WP_SABER) { clientInfo_t *ci = NULL; - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { ci = cent->npcClient; - } - else - { + } else { ci = &cgs.clientinfo[cent->currentState.number]; } - if (!ci) - { - trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, weaponNum/*-1*/), 0, toGhoul2, 1); - } - else - { //Try both the left hand saber and the right hand saber + if (!ci) { + trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, weaponNum /*-1*/), 0, toGhoul2, 1); + } else { // Try both the left hand saber and the right hand saber int i = 0; - while (i < MAX_SABERS) - { - if (ci->saber[i].model[0] && - ci->ghoul2Weapons[i]) - { - trap->G2API_CopySpecificGhoul2Model(ci->ghoul2Weapons[i], 0, toGhoul2, i+1); - } - else if (ci->ghoul2Weapons[i]) - { //if the second saber has been removed, then be sure to remove it and free the instance. + while (i < MAX_SABERS) { + if (ci->saber[i].model[0] && ci->ghoul2Weapons[i]) { + trap->G2API_CopySpecificGhoul2Model(ci->ghoul2Weapons[i], 0, toGhoul2, i + 1); + } else if (ci->ghoul2Weapons[i]) { // if the second saber has been removed, then be sure to remove it and free the instance. qboolean g2HasSecondSaber = trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 2); - if (g2HasSecondSaber) - { //remove it now since we're switching away from sabers + if (g2HasSecondSaber) { // remove it now since we're switching away from sabers trap->G2API_RemoveGhoul2Model(&(toGhoul2), 2); } trap->G2API_CleanGhoul2Models(&ci->ghoul2Weapons[i]); @@ -2465,113 +2093,85 @@ void CG_CopyG2WeaponInstance(centity_t *cent, int weaponNum, void *toGhoul2) i++; } } - } - else - { + } else { qboolean g2HasSecondSaber = trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 2); - if (g2HasSecondSaber) - { //remove it now since we're switching away from sabers + if (g2HasSecondSaber) { // remove it now since we're switching away from sabers trap->G2API_RemoveGhoul2Model(&(toGhoul2), 2); } - if (weaponNum == WP_EMPLACED_GUN) - { //a bit of a hack to remove gun model when using an emplaced weap - if (trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 1)) - { + if (weaponNum == WP_EMPLACED_GUN) { // a bit of a hack to remove gun model when using an emplaced weap + if (trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 1)) { trap->G2API_RemoveGhoul2Model(&(toGhoul2), 1); } - } - else if (weaponNum == WP_MELEE) - { //don't want a weapon on the model for this one - if (trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 1)) - { + } else if (weaponNum == WP_MELEE) { // don't want a weapon on the model for this one + if (trap->G2API_HasGhoul2ModelOnIndex(&(toGhoul2), 1)) { trap->G2API_RemoveGhoul2Model(&(toGhoul2), 1); } - } - else - { - trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, weaponNum/*-1*/), 0, toGhoul2, 1); + } else { + trap->G2API_CopySpecificGhoul2Model(CG_G2WeaponInstance(cent, weaponNum /*-1*/), 0, toGhoul2, 1); } } } } -void CG_CheckPlayerG2Weapons(playerState_t *ps, centity_t *cent) -{ - if (!ps) - { +void CG_CheckPlayerG2Weapons(playerState_t *ps, centity_t *cent) { + if (!ps) { assert(0); return; } - if (ps->pm_flags & PMF_FOLLOW) - { + if (ps->pm_flags & PMF_FOLLOW) { return; } - if (cent->currentState.eType == ET_NPC) - { + if (cent->currentState.eType == ET_NPC) { assert(0); return; } // should we change the gun model on this player? - if (cent->currentState.saberInFlight) - { + if (cent->currentState.saberInFlight) { cent->ghoul2weapon = CG_G2WeaponInstance(cent, WP_SABER); } - if (cent->currentState.eFlags & EF_DEAD) - { //no updating weapons when dead + if (cent->currentState.eFlags & EF_DEAD) { // no updating weapons when dead cent->ghoul2weapon = NULL; return; } - if (cent->torsoBolt) - { //got our limb cut off, no updating weapons until it's restored + if (cent->torsoBolt) { // got our limb cut off, no updating weapons until it's restored cent->ghoul2weapon = NULL; return; } - if (cgs.clientinfo[ps->clientNum].team == TEAM_SPECTATOR || - ps->persistant[PERS_TEAM] == TEAM_SPECTATOR) - { + if (cgs.clientinfo[ps->clientNum].team == TEAM_SPECTATOR || ps->persistant[PERS_TEAM] == TEAM_SPECTATOR) { cent->ghoul2weapon = cg_entities[ps->clientNum].ghoul2weapon = NULL; cent->weapon = cg_entities[ps->clientNum].weapon = 0; return; } if (cent->ghoul2 && cent->ghoul2weapon != CG_G2WeaponInstance(cent, ps->weapon) && - ps->clientNum == cent->currentState.number) //don't want spectator mode forcing one client's weapon instance over another's + ps->clientNum == cent->currentState.number) // don't want spectator mode forcing one client's weapon instance over another's { CG_CopyG2WeaponInstance(cent, ps->weapon, cent->ghoul2); cent->ghoul2weapon = CG_G2WeaponInstance(cent, ps->weapon); - if (cent->weapon == WP_SABER && cent->weapon != ps->weapon && !ps->saberHolstered) - { //switching away from the saber - //trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" )); - if (cgs.clientinfo[ps->clientNum].saber[0].soundOff && !ps->saberHolstered) - { + if (cent->weapon == WP_SABER && cent->weapon != ps->weapon && !ps->saberHolstered) { // switching away from the saber + // trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberoffquick.wav" )); + if (cgs.clientinfo[ps->clientNum].saber[0].soundOff && !ps->saberHolstered) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, cgs.clientinfo[ps->clientNum].saber[0].soundOff); } - if (cgs.clientinfo[ps->clientNum].saber[1].soundOff && - cgs.clientinfo[ps->clientNum].saber[1].model[0] && - !ps->saberHolstered) - { + if (cgs.clientinfo[ps->clientNum].saber[1].soundOff && cgs.clientinfo[ps->clientNum].saber[1].model[0] && !ps->saberHolstered) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, cgs.clientinfo[ps->clientNum].saber[1].soundOff); } - } - else if (ps->weapon == WP_SABER && cent->weapon != ps->weapon && !cent->saberWasInFlight) - { //switching to the saber - //trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" )); - if (cgs.clientinfo[ps->clientNum].saber[0].soundOn) - { + } else if (ps->weapon == WP_SABER && cent->weapon != ps->weapon && !cent->saberWasInFlight) { // switching to the saber + // trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, trap->S_RegisterSound( "sound/weapons/saber/saberon.wav" )); + if (cgs.clientinfo[ps->clientNum].saber[0].soundOn) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, cgs.clientinfo[ps->clientNum].saber[0].soundOn); } - if (cgs.clientinfo[ps->clientNum].saber[1].soundOn) - { + if (cgs.clientinfo[ps->clientNum].saber[1].soundOn) { trap->S_StartSound(cent->lerpOrigin, cent->currentState.number, CHAN_AUTO, cgs.clientinfo[ps->clientNum].saber[1].soundOn); } @@ -2582,7 +2182,6 @@ void CG_CheckPlayerG2Weapons(playerState_t *ps, centity_t *cent) } } - /* Ghoul2 Insert End */ diff --git a/codemp/cgame/fx_blaster.c b/codemp/cgame/fx_blaster.c index d57c30bf0b..ca854c25e1 100644 --- a/codemp/cgame/fx_blaster.c +++ b/codemp/cgame/fx_blaster.c @@ -30,16 +30,14 @@ FX_BlasterProjectileThink ------------------------- */ -void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BlasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.blasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.blasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -47,16 +45,14 @@ void FX_BlasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weap FX_BlasterAltFireThink ------------------------- */ -void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BlasterAltFireThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.blasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.blasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -64,24 +60,17 @@ void FX_BlasterAltFireThink( centity_t *cent, const struct weaponInfo_s *weapon FX_BlasterWeaponHitWall ------------------------- */ -void FX_BlasterWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.blasterWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_BlasterWeaponHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.blasterWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------- FX_BlasterWeaponHitPlayer ------------------------- */ -void FX_BlasterWeaponHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - trap->FX_PlayEffectID( cgs.effects.blasterFleshImpactEffect, origin, normal, -1, -1, qfalse ); - } - else - { - trap->FX_PlayEffectID( cgs.effects.blasterDroidImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_BlasterWeaponHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + trap->FX_PlayEffectID(cgs.effects.blasterFleshImpactEffect, origin, normal, -1, -1, qfalse); + } else { + trap->FX_PlayEffectID(cgs.effects.blasterDroidImpactEffect, origin, normal, -1, -1, qfalse); } } diff --git a/codemp/cgame/fx_bowcaster.c b/codemp/cgame/fx_bowcaster.c index 04f966fc65..ddb0dac0b5 100644 --- a/codemp/cgame/fx_bowcaster.c +++ b/codemp/cgame/fx_bowcaster.c @@ -30,16 +30,14 @@ FX_BowcasterProjectileThink --------------------------- */ -void FX_BowcasterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BowcasterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -48,10 +46,7 @@ FX_BowcasterHitWall --------------------------- */ -void FX_BowcasterHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_BowcasterHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse); } /* --------------------------- @@ -59,9 +54,8 @@ FX_BowcasterHitPlayer --------------------------- */ -void FX_BowcasterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_BowcasterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.bowcasterImpactEffect, origin, normal, -1, -1, qfalse); } /* @@ -70,15 +64,12 @@ FX_BowcasterAltProjectileThink ------------------------------ */ -void FX_BowcasterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BowcasterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bowcasterShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } - diff --git a/codemp/cgame/fx_bryarpistol.c b/codemp/cgame/fx_bryarpistol.c index 58ae911592..f2beddd298 100644 --- a/codemp/cgame/fx_bryarpistol.c +++ b/codemp/cgame/fx_bryarpistol.c @@ -34,16 +34,14 @@ along with this program; if not, see . FX_BryarProjectileThink ------------------------- */ -void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -51,29 +49,21 @@ void FX_BryarProjectileThink( centity_t *cent, const struct weaponInfo_s *weapo FX_BryarHitWall ------------------------- */ -void FX_BryarHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_BryarHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------- FX_BryarHitPlayer ------------------------- */ -void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - trap->FX_PlayEffectID( cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse ); - } - else - { - trap->FX_PlayEffectID( cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_BryarHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + trap->FX_PlayEffectID(cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse); + } else { + trap->FX_PlayEffectID(cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse); } } - /* ------------------------- @@ -83,26 +73,23 @@ void FX_BryarHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_BryarAltProjectileThink ------------------------- */ -void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_BryarAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; int t; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } // see if we have some sort of extra charge going on - for (t = 1; t < cent->currentState.generic1; t++ ) - { + for (t = 1; t < cent->currentState.generic1; t++) { // just add ourselves over, and over, and over when we are charged - trap->FX_PlayEffectID( cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarPowerupShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } // for ( int t = 1; t < cent->gent->count; t++ ) // The single player stores the charge in count, which isn't accessible on the client - trap->FX_PlayEffectID( cgs.effects.bryarShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -110,22 +97,20 @@ void FX_BryarAltProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_BryarAltHitWall ------------------------- */ -void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) -{ - switch( power ) - { +void FX_BryarAltHitWall(vec3_t origin, vec3_t normal, int power) { + switch (power) { case 4: case 5: - trap->FX_PlayEffectID( cgs.effects.bryarWallImpactEffect3, origin, normal, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarWallImpactEffect3, origin, normal, -1, -1, qfalse); break; case 2: case 3: - trap->FX_PlayEffectID( cgs.effects.bryarWallImpactEffect2, origin, normal, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarWallImpactEffect2, origin, normal, -1, -1, qfalse); break; default: - trap->FX_PlayEffectID( cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse); break; } } @@ -135,35 +120,28 @@ void FX_BryarAltHitWall( vec3_t origin, vec3_t normal, int power ) FX_BryarAltHitPlayer ------------------------- */ -void FX_BryarAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - trap->FX_PlayEffectID( cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse ); - } - else - { - trap->FX_PlayEffectID( cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_BryarAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + trap->FX_PlayEffectID(cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse); + } else { + trap->FX_PlayEffectID(cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse); } } - -//TURRET +// TURRET /* ------------------------- FX_TurretProjectileThink ------------------------- */ -void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_TurretProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.turretShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.turretShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -171,49 +149,36 @@ void FX_TurretProjectileThink( centity_t *cent, const struct weaponInfo_s *weap FX_TurretHitWall ------------------------- */ -void FX_TurretHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_TurretHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.bryarWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------- FX_TurretHitPlayer ------------------------- */ -void FX_TurretHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - if ( humanoid ) - { - trap->FX_PlayEffectID( cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse ); - } - else - { - trap->FX_PlayEffectID( cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_TurretHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + if (humanoid) { + trap->FX_PlayEffectID(cgs.effects.bryarFleshImpactEffect, origin, normal, -1, -1, qfalse); + } else { + trap->FX_PlayEffectID(cgs.effects.bryarDroidImpactEffect, origin, normal, -1, -1, qfalse); } } - - -//CONCUSSION (yeah, should probably make a new file for this.. or maybe just move all these stupid semi-redundant fx_ functions into one file) +// CONCUSSION (yeah, should probably make a new file for this.. or maybe just move all these stupid semi-redundant fx_ functions into one file) /* ------------------------- FX_ConcussionHitWall ------------------------- */ -void FX_ConcussionHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.concussionImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_ConcussionHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.concussionImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------- FX_ConcussionHitPlayer ------------------------- */ -void FX_ConcussionHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.concussionImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_ConcussionHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.concussionImpactEffect, origin, normal, -1, -1, qfalse); } /* @@ -221,16 +186,14 @@ void FX_ConcussionHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_ConcussionProjectileThink ------------------------- */ -void FX_ConcussionProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_ConcussionProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.concussionShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.concussionShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -238,22 +201,15 @@ void FX_ConcussionProjectileThink( centity_t *cent, const struct weaponInfo_s * FX_ConcAltShot --------------------------- */ -static vec3_t WHITE ={1.0f,1.0f,1.0f}; -static vec3_t BRIGHT={0.75f,0.5f,1.0f}; +static vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +static vec3_t BRIGHT = {0.75f, 0.5f, 1.0f}; -void FX_ConcAltShot( vec3_t start, vec3_t end ) -{ +void FX_ConcAltShot(vec3_t start, vec3_t end) { //"concussion/beam" - trap->FX_AddLine( start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, trap->R_RegisterShader( "gfx/effects/blueLine" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + trap->FX_AddLine(start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, trap->R_RegisterShader("gfx/effects/blueLine"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); // add some beef - trap->FX_AddLine( start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - BRIGHT, BRIGHT, 0.0f, - 150, trap->R_RegisterShader( "gfx/misc/whiteline2" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + trap->FX_AddLine(start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, BRIGHT, BRIGHT, 0.0f, 150, trap->R_RegisterShader("gfx/misc/whiteline2"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } diff --git a/codemp/cgame/fx_demp2.c b/codemp/cgame/fx_demp2.c index ff06911d19..7487513b66 100644 --- a/codemp/cgame/fx_demp2.c +++ b/codemp/cgame/fx_demp2.c @@ -30,16 +30,14 @@ FX_DEMP2_ProjectileThink --------------------------- */ -void FX_DEMP2_ProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_DEMP2_ProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.demp2ProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.demp2ProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -48,10 +46,7 @@ FX_DEMP2_HitWall --------------------------- */ -void FX_DEMP2_HitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.demp2WallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_DEMP2_HitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.demp2WallImpactEffect, origin, normal, -1, -1, qfalse); } /* --------------------------- @@ -59,9 +54,8 @@ FX_DEMP2_HitPlayer --------------------------- */ -void FX_DEMP2_HitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.demp2FleshImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_DEMP2_HitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.demp2FleshImpactEffect, origin, normal, -1, -1, qfalse); } /* @@ -69,213 +63,211 @@ void FX_DEMP2_HitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) FX_DEMP2_AltBeam --------------------------- */ -void FX_DEMP2_AltBeam( vec3_t start, vec3_t end, vec3_t normal, //qboolean spark, - vec3_t targ1, vec3_t targ2 ) -{ -//NOTENOTE Fix this after trap calls for all primitives are created. -/* - vec3_t dir, chaos, - c1, c2, - v1, v2; - float len, - s1, s2, s3; - - VectorSubtract( end, start, dir ); - len = VectorNormalize( dir ); - - // Get the base control points, we'll work from there - VectorMA( start, 0.3333f * len, dir, c1 ); - VectorMA( start, 0.6666f * len, dir, c2 ); - - // get some chaos values that really aren't very chaotic :) - s1 = sin( cg.time * 0.005f ) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; - s2 = sin( cg.time * 0.001f ); - s3 = sin( cg.time * 0.011f ); - - VectorSet( chaos, len * 0.01f * s1, - len * 0.02f * s2, - len * 0.04f * (s1 + s2 + s3)); - - VectorAdd( c1, chaos, c1 ); - VectorScale( chaos, 4.0f, v1 ); - - VectorSet( chaos, -len * 0.02f * s3, - len * 0.01f * (s1 * s2), - -len * 0.02f * (s1 + s2 * s3)); +void FX_DEMP2_AltBeam(vec3_t start, vec3_t end, vec3_t normal, // qboolean spark, + vec3_t targ1, vec3_t targ2) { + // NOTENOTE Fix this after trap calls for all primitives are created. + /* + vec3_t dir, chaos, + c1, c2, + v1, v2; + float len, + s1, s2, s3; - VectorAdd( c2, chaos, c2 ); - VectorScale( chaos, 2.0f, v2 ); + VectorSubtract( end, start, dir ); + len = VectorNormalize( dir ); + + // Get the base control points, we'll work from there + VectorMA( start, 0.3333f * len, dir, c1 ); + VectorMA( start, 0.6666f * len, dir, c2 ); + + // get some chaos values that really aren't very chaotic :) + s1 = sin( cg.time * 0.005f ) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; + s2 = sin( cg.time * 0.001f ); + s3 = sin( cg.time * 0.011f ); - VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + VectorSet( chaos, len * 0.01f * s1, + len * 0.02f * s2, + len * 0.04f * (s1 + s2 + s3)); - FX_AddBezier( start, targ1, - c1, v1, c2, v2, - 5.0f + s1 * 2, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + VectorAdd( c1, chaos, c1 ); + VectorScale( chaos, 4.0f, v1 ); - FX_AddBezier( start, targ1, - c2, v2, c1, v1, - 3.0f + s3, 3.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - s1 = sin( cg.time * 0.0005f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; - s2 = sin( cg.time * 0.0025f ); - float cc2 = cos( cg.time * 0.0025f ); - s3 = sin( cg.time * 0.01f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; + VectorSet( chaos, -len * 0.02f * s3, + len * 0.01f * (s1 * s2), + -len * 0.02f * (s1 + s2 * s3)); - VectorSet( chaos, len * 0.08f * s2, - len * 0.04f * cc2,//s1 * -s3, - len * 0.06f * s3 ); + VectorAdd( c2, chaos, c2 ); + VectorScale( chaos, 2.0f, v2 ); + + VectorSet( chaos, 1.0f, 1.0f, 1.0f ); - VectorAdd( c1, chaos, c1 ); - VectorScale( chaos, 4.0f, v1 ); + FX_AddBezier( start, targ1, + c1, v1, c2, v2, + 5.0f + s1 * 2, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + + FX_AddBezier( start, targ1, + c2, v2, c1, v1, + 3.0f + s3, 3.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + + s1 = sin( cg.time * 0.0005f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; + s2 = sin( cg.time * 0.0025f ); + float cc2 = cos( cg.time * 0.0025f ); + s3 = sin( cg.time * 0.01f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; + + VectorSet( chaos, len * 0.08f * s2, + len * 0.04f * cc2,//s1 * -s3, + len * 0.06f * s3 ); + + VectorAdd( c1, chaos, c1 ); + VectorScale( chaos, 4.0f, v1 ); + + VectorSet( chaos, len * 0.02f * s1 * s3, + len * 0.04f * s2, + len * 0.03f * s1 * s2 ); + + VectorAdd( c2, chaos, c2 ); + VectorScale( chaos, 3.0f, v2 ); + + VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + + FX_AddBezier( start, targ1, + c1, v1, c2, v2, + 4.0f + s3, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + + FX_AddBezier( start, targ1, + c2, v1, c1, v2, + 5.0f + s1 * 2, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + + + VectorMA( start, 14.0f, dir, c1 ); + + FX_AddSprite( c1, NULL, NULL, 12.0f + Q_flrand(-1.0f, 1.0f) * 4, 0.0f, 1.0f, 1.0f, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + FX_AddSprite( c1, NULL, NULL, 6.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 1.0f, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + + FX_AddSprite( targ1, NULL, NULL, 4.0f + Q_flrand(-1.0f, 1.0f), 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + FX_AddSprite( targ1, NULL, NULL, 8.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + + + //-------------------------------------------- + + VectorSubtract( targ2, targ1, dir ); + len = VectorNormalize( dir ); + + // Get the base control points, we'll work from there + VectorMA( targ1, 0.3333f * len, dir, c1 ); + VectorMA( targ1, 0.6666f * len, dir, c2 ); - VectorSet( chaos, len * 0.02f * s1 * s3, - len * 0.04f * s2, - len * 0.03f * s1 * s2 ); + // get some chaos values that really aren't very chaotic :) + s1 = sin( cg.time * 0.005f ) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; + s2 = sin( cg.time * 0.001f ); + s3 = sin( cg.time * 0.011f ); + + VectorSet( chaos, len * 0.01f * s1, + len * 0.02f * s2, + len * 0.04f * (s1 + s2 + s3)); + + VectorAdd( c1, chaos, c1 ); + VectorScale( chaos, 4.0f, v1 ); - VectorAdd( c2, chaos, c2 ); - VectorScale( chaos, 3.0f, v2 ); + VectorSet( chaos, -len * 0.02f * s3, + len * 0.01f * (s1 * s2), + -len * 0.02f * (s1 + s2 * s3)); - VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + VectorAdd( c2, chaos, c2 ); + VectorScale( chaos, 2.0f, v2 ); - FX_AddBezier( start, targ1, - c1, v1, c2, v2, - 4.0f + s3, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - FX_AddBezier( start, targ1, - c2, v1, c1, v2, - 5.0f + s1 * 2, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - - VectorMA( start, 14.0f, dir, c1 ); - - FX_AddSprite( c1, NULL, NULL, 12.0f + Q_flrand(-1.0f, 1.0f) * 4, 0.0f, 1.0f, 1.0f, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); - FX_AddSprite( c1, NULL, NULL, 6.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 1.0f, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 1.0f, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); - - FX_AddSprite( targ1, NULL, NULL, 4.0f + Q_flrand(-1.0f, 1.0f), 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); - FX_AddSprite( targ1, NULL, NULL, 8.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); - - - //-------------------------------------------- - - VectorSubtract( targ2, targ1, dir ); - len = VectorNormalize( dir ); - - // Get the base control points, we'll work from there - VectorMA( targ1, 0.3333f * len, dir, c1 ); - VectorMA( targ1, 0.6666f * len, dir, c2 ); + VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + + FX_AddBezier( targ1, targ2, + c1, v1, c2, v2, + 5.0f + s1 * 2, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + + FX_AddBezier( targ1, targ2, + c2, v2, c1, v1, + 3.0f + s3, 3.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - // get some chaos values that really aren't very chaotic :) - s1 = sin( cg.time * 0.005f ) * 2 + Q_flrand(-1.0f, 1.0f) * 0.2f; - s2 = sin( cg.time * 0.001f ); - s3 = sin( cg.time * 0.011f ); + s1 = sin( cg.time * 0.0005f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; + s2 = sin( cg.time * 0.0025f ); + cc2 = cos( cg.time * 0.0025f ); + s3 = sin( cg.time * 0.01f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; - VectorSet( chaos, len * 0.01f * s1, - len * 0.02f * s2, - len * 0.04f * (s1 + s2 + s3)); + VectorSet( chaos, len * 0.08f * s2, + len * 0.04f * cc2,//s1 * -s3, + len * 0.06f * s3 ); - VectorAdd( c1, chaos, c1 ); - VectorScale( chaos, 4.0f, v1 ); + VectorAdd( c1, chaos, c1 ); + VectorScale( chaos, 4.0f, v1 ); - VectorSet( chaos, -len * 0.02f * s3, - len * 0.01f * (s1 * s2), - -len * 0.02f * (s1 + s2 * s3)); + VectorSet( chaos, len * 0.02f * s1 * s3, + len * 0.04f * s2, + len * 0.03f * s1 * s2 ); - VectorAdd( c2, chaos, c2 ); - VectorScale( chaos, 2.0f, v2 ); + VectorAdd( c2, chaos, c2 ); + VectorScale( chaos, 3.0f, v2 ); - VectorSet( chaos, 1.0f, 1.0f, 1.0f ); + VectorSet( chaos, 1.0f, 1.0f, 1.0f ); - FX_AddBezier( targ1, targ2, - c1, v1, c2, v2, - 5.0f + s1 * 2, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - FX_AddBezier( targ1, targ2, - c2, v2, c1, v1, - 3.0f + s3, 3.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); + FX_AddBezier( targ1, targ2, + c1, v1, c2, v2, + 4.0f + s3, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - s1 = sin( cg.time * 0.0005f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; - s2 = sin( cg.time * 0.0025f ); - cc2 = cos( cg.time * 0.0025f ); - s3 = sin( cg.time * 0.01f ) + Q_flrand(-1.0f, 1.0f) * 0.1f; + FX_AddBezier( targ1, targ2, + c2, v1, c1, v2, + 5.0f + s1 * 2, 8.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + chaos, chaos, 0.0f, + 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - VectorSet( chaos, len * 0.08f * s2, - len * 0.04f * cc2,//s1 * -s3, - len * 0.06f * s3 ); - VectorAdd( c1, chaos, c1 ); - VectorScale( chaos, 4.0f, v1 ); - - VectorSet( chaos, len * 0.02f * s1 * s3, - len * 0.04f * s2, - len * 0.03f * s1 * s2 ); - - VectorAdd( c2, chaos, c2 ); - VectorScale( chaos, 3.0f, v2 ); - - VectorSet( chaos, 1.0f, 1.0f, 1.0f ); - - FX_AddBezier( targ1, targ2, - c1, v1, c2, v2, - 4.0f + s3, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - FX_AddBezier( targ1, targ2, - c2, v1, c1, v2, - 5.0f + s1 * 2, 8.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - chaos, chaos, 0.0f, - 1.0f, trap->R_RegisterShader( "gfx/misc/electric2" ), FX_ALPHA_LINEAR ); - - - FX_AddSprite( targ2, NULL, NULL, 4.0f + Q_flrand(-1.0f, 1.0f), 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); - FX_AddSprite( targ2, NULL, NULL, 8.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, - trap->R_RegisterShader( "gfx/misc/lightningFlash" )); -*/ + FX_AddSprite( targ2, NULL, NULL, 4.0f + Q_flrand(-1.0f, 1.0f), 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + FX_AddSprite( targ2, NULL, NULL, 8.0f + Q_flrand(-1.0f, 1.0f) * 2, 0.0f, 1.0f, 0.0f, chaos, chaos, Q_flrand(0.0f, 1.0f) * 360, 0.0f, 10, + trap->R_RegisterShader( "gfx/misc/lightningFlash" )); + */ } //--------------------------------------------- -void FX_DEMP2_AltDetonate( vec3_t org, float size ) -{ - localEntity_t *ex; +void FX_DEMP2_AltDetonate(vec3_t org, float size) { + localEntity_t *ex; ex = CG_AllocLocalEntity(); ex->leType = LE_FADE_SCALE_MODEL; - memset( &ex->refEntity, 0, sizeof( refEntity_t )); + memset(&ex->refEntity, 0, sizeof(refEntity_t)); ex->refEntity.renderfx |= RF_VOLUMETRIC; ex->startTime = cg.time; - ex->endTime = ex->startTime + 800;//1600; + ex->endTime = ex->startTime + 800; // 1600; ex->radius = size; ex->refEntity.customShader = cgs.media.demp2ShellShader; ex->refEntity.hModel = cgs.media.demp2Shell; - VectorCopy( org, ex->refEntity.origin ); + VectorCopy(org, ex->refEntity.origin); ex->color[0] = ex->color[1] = ex->color[2] = 255.0f; } diff --git a/codemp/cgame/fx_disruptor.c b/codemp/cgame/fx_disruptor.c index dd2d5fd183..411e51b755 100644 --- a/codemp/cgame/fx_disruptor.c +++ b/codemp/cgame/fx_disruptor.c @@ -30,76 +30,61 @@ along with this program; if not, see . FX_DisruptorMainShot --------------------------- */ -static vec3_t WHITE={1.0f,1.0f,1.0f}; - -void FX_DisruptorMainShot( vec3_t start, vec3_t end ) -{ -// vec3_t dir; -// float len; - - trap->FX_AddLine( start, end, 0.1f, 6.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 150, trap->R_RegisterShader( "gfx/effects/redLine" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); - -// VectorSubtract( end, start, dir ); -// len = VectorNormalize( dir ); - -// FX_AddCylinder( start, dir, 5.0f, 5.0f, 0.0f, -// 5.0f, 5.0f, 0.0f, -// len, len, 0.0f, -// 1.0f, 1.0f, 0.0f, -// WHITE, WHITE, 0.0f, -// 400, cgi_R_RegisterShader( "gfx/effects/spiral" ), 0 ); -} +static vec3_t WHITE = {1.0f, 1.0f, 1.0f}; + +void FX_DisruptorMainShot(vec3_t start, vec3_t end) { + // vec3_t dir; + // float len; + + trap->FX_AddLine(start, end, 0.1f, 6.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 150, trap->R_RegisterShader("gfx/effects/redLine"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); + // VectorSubtract( end, start, dir ); + // len = VectorNormalize( dir ); + + // FX_AddCylinder( start, dir, 5.0f, 5.0f, 0.0f, + // 5.0f, 5.0f, 0.0f, + // len, len, 0.0f, + // 1.0f, 1.0f, 0.0f, + // WHITE, WHITE, 0.0f, + // 400, cgi_R_RegisterShader( "gfx/effects/spiral" ), 0 ); +} /* --------------------------- FX_DisruptorAltShot --------------------------- */ -void FX_DisruptorAltShot( vec3_t start, vec3_t end, qboolean fullCharge ) -{ - trap->FX_AddLine( start, end, 0.1f, 10.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - WHITE, WHITE, 0.0f, - 175, trap->R_RegisterShader( "gfx/effects/redLine" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); - - if ( fullCharge ) - { - vec3_t YELLER={0.8f,0.7f,0.0f}; +void FX_DisruptorAltShot(vec3_t start, vec3_t end, qboolean fullCharge) { + trap->FX_AddLine(start, end, 0.1f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, WHITE, WHITE, 0.0f, 175, trap->R_RegisterShader("gfx/effects/redLine"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); + + if (fullCharge) { + vec3_t YELLER = {0.8f, 0.7f, 0.0f}; // add some beef - trap->FX_AddLine( start, end, 0.1f, 7.0f, 0.0f, - 1.0f, 0.0f, 0.0f, - YELLER, YELLER, 0.0f, - 150, trap->R_RegisterShader( "gfx/misc/whiteline2" ), - FX_SIZE_LINEAR | FX_ALPHA_LINEAR ); + trap->FX_AddLine(start, end, 0.1f, 7.0f, 0.0f, 1.0f, 0.0f, 0.0f, YELLER, YELLER, 0.0f, 150, trap->R_RegisterShader("gfx/misc/whiteline2"), + FX_SIZE_LINEAR | FX_ALPHA_LINEAR); } } - /* --------------------------- FX_DisruptorAltMiss --------------------------- */ -#define FX_ALPHA_WAVE 0x00000008 +#define FX_ALPHA_WAVE 0x00000008 -void FX_DisruptorAltMiss( vec3_t origin, vec3_t normal ) -{ +void FX_DisruptorAltMiss(vec3_t origin, vec3_t normal) { vec3_t pos, c1, c2; addbezierArgStruct_t b; - VectorMA( origin, 4.0f, normal, c1 ); - VectorCopy( c1, c2 ); + VectorMA(origin, 4.0f, normal, c1); + VectorCopy(c1, c2); c1[2] += 4; c2[2] += 12; - VectorAdd( origin, normal, pos ); + VectorAdd(origin, normal, pos); pos[2] += 28; /* @@ -126,12 +111,12 @@ void FX_DisruptorAltMiss( vec3_t origin, vec3_t normal ) b.rgbParm = 0.0f; b.killTime = 4000; - b.shader = trap->R_RegisterShader( "gfx/effects/smokeTrail" ); + b.shader = trap->R_RegisterShader("gfx/effects/smokeTrail"); b.flags = FX_ALPHA_WAVE; trap->FX_AddBezier(&b); - trap->FX_PlayEffectID( cgs.effects.disruptorAltMissEffect, origin, normal, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.disruptorAltMissEffect, origin, normal, -1, -1, qfalse); } /* @@ -140,12 +125,7 @@ FX_DisruptorAltHit --------------------------- */ -void FX_DisruptorAltHit( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.disruptorAltHitEffect, origin, normal, -1, -1, qfalse ); -} - - +void FX_DisruptorAltHit(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.disruptorAltHitEffect, origin, normal, -1, -1, qfalse); } /* --------------------------- @@ -153,10 +133,7 @@ FX_DisruptorHitWall --------------------------- */ -void FX_DisruptorHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.disruptorWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_DisruptorHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.disruptorWallImpactEffect, origin, normal, -1, -1, qfalse); } /* --------------------------- @@ -164,7 +141,6 @@ FX_DisruptorHitPlayer --------------------------- */ -void FX_DisruptorHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.disruptorFleshImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_DisruptorHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.disruptorFleshImpactEffect, origin, normal, -1, -1, qfalse); } diff --git a/codemp/cgame/fx_flechette.c b/codemp/cgame/fx_flechette.c index acf5dbd70a..ed3dbe2ed5 100644 --- a/codemp/cgame/fx_flechette.c +++ b/codemp/cgame/fx_flechette.c @@ -30,16 +30,14 @@ FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.flechetteShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -47,43 +45,36 @@ void FX_FlechetteProjectileThink( centity_t *cent, const struct weaponInfo_s *we FX_FlechetteWeaponHitWall ------------------------- */ -void FX_FlechetteWeaponHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.flechetteWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_FlechetteWeaponHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.flechetteWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------- FX_FlechetteWeaponHitPlayer ------------------------- */ -void FX_FlechetteWeaponHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ -// if ( humanoid ) -// { - trap->FX_PlayEffectID( cgs.effects.flechetteFleshImpactEffect, origin, normal, -1, -1, qfalse ); -// } -// else -// { -// trap->FX_PlayEffect( "blaster/droid_impact", origin, normal ); -// } +void FX_FlechetteWeaponHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + // if ( humanoid ) + // { + trap->FX_PlayEffectID(cgs.effects.flechetteFleshImpactEffect, origin, normal, -1, -1, qfalse); + // } + // else + // { + // trap->FX_PlayEffect( "blaster/droid_impact", origin, normal ); + // } } - /* ------------------------- FX_FlechetteProjectileThink ------------------------- */ -void FX_FlechetteAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_FlechetteAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.flechetteAltShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } diff --git a/codemp/cgame/fx_force.c b/codemp/cgame/fx_force.c index 1d6766982f..330990cf32 100644 --- a/codemp/cgame/fx_force.c +++ b/codemp/cgame/fx_force.c @@ -30,9 +30,7 @@ FX_ForceDrained ------------------------- */ // This effect is not generic because of possible enhancements -void FX_ForceDrained(vec3_t origin, vec3_t dir) -{ +void FX_ForceDrained(vec3_t origin, vec3_t dir) { VectorScale(dir, -1.0, dir); trap->FX_PlayEffectID(cgs.effects.forceDrained, origin, dir, -1, -1, qfalse); } - diff --git a/codemp/cgame/fx_heavyrepeater.c b/codemp/cgame/fx_heavyrepeater.c index f20353980a..86ee1f2ac5 100644 --- a/codemp/cgame/fx_heavyrepeater.c +++ b/codemp/cgame/fx_heavyrepeater.c @@ -30,16 +30,14 @@ FX_RepeaterProjectileThink --------------------------- */ -void FX_RepeaterProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.repeaterProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.repeaterProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -48,10 +46,7 @@ FX_RepeaterHitWall ------------------------ */ -void FX_RepeaterHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.repeaterWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_RepeaterHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.repeaterWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------ @@ -59,55 +54,44 @@ FX_RepeaterHitPlayer ------------------------ */ -void FX_RepeaterHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.repeaterFleshImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_RepeaterHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.repeaterFleshImpactEffect, origin, normal, -1, -1, qfalse); } -static void CG_DistortionOrb( centity_t *cent ) -{ +static void CG_DistortionOrb(centity_t *cent) { refEntity_t ent; vec3_t ang; float scale = 0.5f; float vLen; - if (!cg_renderToTextureFX.integer) - { + if (!cg_renderToTextureFX.integer) { return; } - memset( &ent, 0, sizeof( ent ) ); + memset(&ent, 0, sizeof(ent)); - VectorCopy( cent->lerpOrigin, ent.origin ); + VectorCopy(cent->lerpOrigin, ent.origin); VectorSubtract(ent.origin, cg.refdef.vieworg, ent.axis[0]); vLen = VectorLength(ent.axis[0]); - if (VectorNormalize(ent.axis[0]) <= 0.1f) - { // Entity is right on vieworg. quit. + if (VectorNormalize(ent.axis[0]) <= 0.1f) { // Entity is right on vieworg. quit. return; } -// VectorCopy(cg.refdef.viewaxis[2], ent.axis[2]); -// CrossProduct(ent.axis[0], ent.axis[2], ent.axis[1]); + // VectorCopy(cg.refdef.viewaxis[2], ent.axis[2]); + // CrossProduct(ent.axis[0], ent.axis[2], ent.axis[1]); vectoangles(ent.axis[0], ang); ang[ROLL] = cent->trickAlpha; - cent->trickAlpha += 16; //spin the half-sphere to give a "screwdriver" effect + cent->trickAlpha += 16; // spin the half-sphere to give a "screwdriver" effect AnglesToAxis(ang, ent.axis); - //radius must be a power of 2, and is the actual captured texture size - if (vLen < 128) - { + // radius must be a power of 2, and is the actual captured texture size + if (vLen < 128) { ent.radius = 256; - } - else if (vLen < 256) - { + } else if (vLen < 256) { ent.radius = 128; - } - else if (vLen < 512) - { + } else if (vLen < 512) { ent.radius = 64; - } - else - { + } else { ent.radius = 32; } @@ -116,20 +100,20 @@ static void CG_DistortionOrb( centity_t *cent ) VectorScale(ent.axis[2], -scale, ent.axis[2]); ent.hModel = cgs.media.halfShieldModel; - ent.customShader = 0;//cgs.media.halfShieldShader; + ent.customShader = 0; // cgs.media.halfShieldShader; #if 1 - ent.renderfx = (RF_DISTORTION|RF_RGB_TINT); + ent.renderfx = (RF_DISTORTION | RF_RGB_TINT); - //tint the whole thing a shade of blue + // tint the whole thing a shade of blue ent.shaderRGBA[0] = 200.0f; ent.shaderRGBA[1] = 200.0f; ent.shaderRGBA[2] = 255.0f; -#else //no tint +#else // no tint ent.renderfx = RF_DISTORTION; #endif - trap->R_AddRefEntityToScene( &ent ); + trap->R_AddRefEntityToScene(&ent); } /* @@ -138,20 +122,17 @@ FX_RepeaterAltProjectileThink ----------------------------- */ -void FX_RepeaterAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RepeaterAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - if (cg_repeaterOrb.integer) - { + if (cg_repeaterOrb.integer) { CG_DistortionOrb(cent); } - trap->FX_PlayEffectID( cgs.effects.repeaterAltProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.repeaterAltProjectileEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -160,10 +141,7 @@ FX_RepeaterAltHitWall ------------------------ */ -void FX_RepeaterAltHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.repeaterAltWallImpactEffect, origin, normal, -1, -1, qfalse ); -} +void FX_RepeaterAltHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.repeaterAltWallImpactEffect, origin, normal, -1, -1, qfalse); } /* ------------------------ @@ -171,7 +149,6 @@ FX_RepeaterAltHitPlayer ------------------------ */ -void FX_RepeaterAltHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.repeaterAltWallImpactEffect, origin, normal, -1, -1, qfalse ); +void FX_RepeaterAltHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.repeaterAltWallImpactEffect, origin, normal, -1, -1, qfalse); } diff --git a/codemp/cgame/fx_rocketlauncher.c b/codemp/cgame/fx_rocketlauncher.c index 10a74184c8..ae5764b238 100644 --- a/codemp/cgame/fx_rocketlauncher.c +++ b/codemp/cgame/fx_rocketlauncher.c @@ -30,16 +30,14 @@ FX_RocketProjectileThink --------------------------- */ -void FX_RocketProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.rocketShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.rocketShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } /* @@ -48,10 +46,7 @@ FX_RocketHitWall --------------------------- */ -void FX_RocketHitWall( vec3_t origin, vec3_t normal ) -{ - trap->FX_PlayEffectID( cgs.effects.rocketExplosionEffect, origin, normal, -1, -1, qfalse ); -} +void FX_RocketHitWall(vec3_t origin, vec3_t normal) { trap->FX_PlayEffectID(cgs.effects.rocketExplosionEffect, origin, normal, -1, -1, qfalse); } /* --------------------------- @@ -59,9 +54,8 @@ FX_RocketHitPlayer --------------------------- */ -void FX_RocketHitPlayer( vec3_t origin, vec3_t normal, qboolean humanoid ) -{ - trap->FX_PlayEffectID( cgs.effects.rocketExplosionEffect, origin, normal, -1, -1, qfalse ); +void FX_RocketHitPlayer(vec3_t origin, vec3_t normal, qboolean humanoid) { + trap->FX_PlayEffectID(cgs.effects.rocketExplosionEffect, origin, normal, -1, -1, qfalse); } /* @@ -70,14 +64,12 @@ FX_RocketAltProjectileThink --------------------------- */ -void FX_RocketAltProjectileThink( centity_t *cent, const struct weaponInfo_s *weapon ) -{ +void FX_RocketAltProjectileThink(centity_t *cent, const struct weaponInfo_s *weapon) { vec3_t forward; - if ( VectorNormalize2( cent->currentState.pos.trDelta, forward ) == 0.0f ) - { + if (VectorNormalize2(cent->currentState.pos.trDelta, forward) == 0.0f) { forward[2] = 1.0f; } - trap->FX_PlayEffectID( cgs.effects.rocketShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse ); + trap->FX_PlayEffectID(cgs.effects.rocketShotEffect, cent->lerpOrigin, forward, -1, -1, qfalse); } diff --git a/codemp/client/FXExport.cpp b/codemp/client/FXExport.cpp index ecd0c6fc0d..d823eb8646 100644 --- a/codemp/client/FXExport.cpp +++ b/codemp/client/FXExport.cpp @@ -26,27 +26,20 @@ along with this program; if not, see . //#define __FXCHECKER #ifdef __FXCHECKER - #include +#include #endif // __FXCHECKER -int FX_RegisterEffect(const char *file) -{ - return theFxScheduler.RegisterEffect(file, true); -} +int FX_RegisterEffect(const char *file) { return theFxScheduler.RegisterEffect(file, true); } -void FX_PlayEffect( const char *file, vec3_t org, vec3_t fwd, int vol, int rad ) -{ +void FX_PlayEffect(const char *file, vec3_t org, vec3_t fwd, int vol, int rad) { #ifdef __FXCHECKER - if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) - { + if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) { assert(0); } - if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2])) - { + if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2])) { assert(0); } - if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1) - { + if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1) { assert(0); } #endif // __FXCHECKER @@ -54,71 +47,44 @@ void FX_PlayEffect( const char *file, vec3_t org, vec3_t fwd, int vol, int rad ) theFxScheduler.PlayEffect(file, org, fwd, vol, rad); } -void FX_PlayEffectID( int id, vec3_t org, vec3_t fwd, int vol, int rad, qboolean isPortal ) -{ +void FX_PlayEffectID(int id, vec3_t org, vec3_t fwd, int vol, int rad, qboolean isPortal) { #ifdef __FXCHECKER - if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) - { + if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) { assert(0); } - if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2])) - { + if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2])) { assert(0); } - if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1) - { + if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1) { assert(0); } #endif // __FXCHECKER - theFxScheduler.PlayEffect(id, org, fwd, vol, rad, !!isPortal ); + theFxScheduler.PlayEffect(id, org, fwd, vol, rad, !!isPortal); } -void FX_PlayBoltedEffectID( int id, vec3_t org, - const int boltInfo, CGhoul2Info_v *ghoul2, int iLooptime, qboolean isRelative ) -{ - theFxScheduler.PlayEffect(id, org, 0, boltInfo, ghoul2, -1, -1, -1, qfalse, iLooptime, !!isRelative ); +void FX_PlayBoltedEffectID(int id, vec3_t org, const int boltInfo, CGhoul2Info_v *ghoul2, int iLooptime, qboolean isRelative) { + theFxScheduler.PlayEffect(id, org, 0, boltInfo, ghoul2, -1, -1, -1, qfalse, iLooptime, !!isRelative); } -void FX_PlayEntityEffectID( int id, vec3_t org, - matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad ) -{ +void FX_PlayEntityEffectID(int id, vec3_t org, matrix3_t axis, const int boltInfo, const int entNum, int vol, int rad) { #ifdef __FXCHECKER - if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) - { + if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2])) { assert(0); } #endif // __FXCHECKER - theFxScheduler.PlayEffect(id, org, axis, boltInfo, 0, -1, vol, rad ); + theFxScheduler.PlayEffect(id, org, axis, boltInfo, 0, -1, vol, rad); } -void FX_AddScheduledEffects( qboolean portal ) -{ - theFxScheduler.AddScheduledEffects(!!portal); -} +void FX_AddScheduledEffects(qboolean portal) { theFxScheduler.AddScheduledEffects(!!portal); } -void FX_Draw2DEffects( float screenXScale, float screenYScale ) -{ - theFxScheduler.Draw2DEffects( screenXScale, screenYScale ); -} +void FX_Draw2DEffects(float screenXScale, float screenYScale) { theFxScheduler.Draw2DEffects(screenXScale, screenYScale); } -int FX_InitSystem( refdef_t* refdef ) -{ - return FX_Init( refdef ); -} +int FX_InitSystem(refdef_t *refdef) { return FX_Init(refdef); } -void FX_SetRefDefFromCGame( refdef_t* refdef ) -{ - FX_SetRefDef( refdef ); -} +void FX_SetRefDefFromCGame(refdef_t *refdef) { FX_SetRefDef(refdef); } -qboolean FX_FreeSystem( void ) -{ - return (qboolean)FX_Free( true ); -} +qboolean FX_FreeSystem(void) { return (qboolean)FX_Free(true); } -void FX_AdjustTime( int time ) -{ - theFxHelper.AdjustTime(time); -} +void FX_AdjustTime(int time) { theFxHelper.AdjustTime(time); } diff --git a/codemp/client/FxPrimitives.cpp b/codemp/client/FxPrimitives.cpp index 1497924f6a..4aab0d37e4 100644 --- a/codemp/client/FxPrimitives.cpp +++ b/codemp/client/FxPrimitives.cpp @@ -24,21 +24,15 @@ along with this program; if not, see . #include "cl_cgameapi.h" #include "FxScheduler.h" -extern int drawnFx; +extern int drawnFx; //-------------------------- // // Base Effect Class // //-------------------------- -CEffect::CEffect(void) : - mFlags(0), - mMatImpactFX(MATIMPACTFX_NONE), - mMatImpactParm(-1), - mSoundRadius(-1), - mSoundVolume(-1) -{ - memset( &mRefEnt, 0, sizeof( mRefEnt )); +CEffect::CEffect(void) : mFlags(0), mMatImpactFX(MATIMPACTFX_NONE), mMatImpactParm(-1), mSoundRadius(-1), mSoundVolume(-1) { + memset(&mRefEnt, 0, sizeof(mRefEnt)); } //-------------------------- @@ -48,60 +42,52 @@ CEffect::CEffect(void) : //-------------------------- //---------------------------- -void CParticle::Init(void) -{ +void CParticle::Init(void) { mRefEnt.radius = 0.0f; - if (mFlags & FX_PLAYER_VIEW) - { + if (mFlags & FX_PLAYER_VIEW) { mOrigin1[0] = irand(0, 639); mOrigin1[1] = irand(0, 479); } } //---------------------------- -void CParticle::Die(void) -{ - if ( mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT) ) - { - vec3_t norm; +void CParticle::Die(void) { + if (mFlags & FX_DEATH_RUNS_FX && !(mFlags & FX_KILL_ON_IMPACT)) { + vec3_t norm; // Man, this just seems so, like, uncool and stuff... - VectorSet( norm, flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f)); - VectorNormalize( norm ); + VectorSet(norm, flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f), flrand(-1.0f, 1.0f)); + VectorNormalize(norm); - theFxScheduler.PlayEffect( mDeathFxID, mOrigin1, norm ); + theFxScheduler.PlayEffect(mDeathFxID, mOrigin1, norm); } } //---------------------------- -bool CParticle::Cull(void) -{ - vec3_t dir; +bool CParticle::Cull(void) { + vec3_t dir; - if (mFlags & FX_PLAYER_VIEW) - { + if (mFlags & FX_PLAYER_VIEW) { // this will be drawn as a 2D effect so don't cull it return false; } // Get the direction to the view - VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mOrigin1, theFxHelper.refdef->vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0) // cg.cosHalfFOV * (len - mRadius) ) + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) < 0) // cg.cosHalfFOV * (len - mRadius) ) { return true; } // don't cull if this is hacked to show up close to the inview wpn - if (mFlags & FX_DEPTH_HACK) - { + if (mFlags & FX_DEPTH_HACK) { return false; } // Can't be too close - float len = VectorLengthSquared( dir ); - if ( len < fx_nearCull->value ) - { + float len = VectorLengthSquared(dir); + if (len < fx_nearCull->value) { return true; } @@ -109,17 +95,14 @@ bool CParticle::Cull(void) } //---------------------------- -void CParticle::Draw(void) -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CParticle::Draw(void) { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - if (mFlags & FX_PLAYER_VIEW) - { - vec4_t color; + if (mFlags & FX_PLAYER_VIEW) { + vec4_t color; color[0] = mRefEnt.shaderRGBA[0] / 255.0; color[1] = mRefEnt.shaderRGBA[1] / 255.0; @@ -128,11 +111,9 @@ void CParticle::Draw(void) // add this 2D effect to the proper list. it will get drawn after the trap->RenderScene call theFxScheduler.Add2DEffect(mOrigin1[0], mOrigin1[1], mRefEnt.radius, mRefEnt.radius, color, mRefEnt.customShader); - } - else - { + } else { // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); theFxHelper.AddFxToScene(&mRefEnt); } @@ -142,62 +123,53 @@ void CParticle::Draw(void) //---------------------------- // Update //---------------------------- -bool CParticle::Update(void) -{ +bool CParticle::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - vec3_t org; - matrix3_t ax; + vec3_t org; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // calc the real velocity and accel vectors - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); - //realVel[2] += 0.5f * mGravity * time; + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); + // realVel[2] += 0.5f * mGravity * time; - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); + VectorMA(org, time, realVel, mOrigin1); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - - if ( !Cull() ) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateRGB(); @@ -213,115 +185,95 @@ bool CParticle::Update(void) //---------------------------- // Update Origin //---------------------------- -bool CParticle::UpdateOrigin(void) -{ - vec3_t new_origin; +bool CParticle::UpdateOrigin(void) { + vec3_t new_origin; - VectorMA( mVel, theFxHelper.mRealTime, mAccel, mVel ); + VectorMA(mVel, theFxHelper.mRealTime, mAccel, mVel); // Predict the new position - new_origin[0] = mOrigin1[0] + (theFxHelper.mRealTime * mVel[0]);// + (theFxHelper.mHalfRealTimeSq * mVel[0]); - new_origin[1] = mOrigin1[1] + (theFxHelper.mRealTime * mVel[1]);// + (theFxHelper.mHalfRealTimeSq * mVel[1]); - new_origin[2] = mOrigin1[2] + (theFxHelper.mRealTime * mVel[2]);// + (theFxHelper.mHalfRealTimeSq * mVel[2]); + new_origin[0] = mOrigin1[0] + (theFxHelper.mRealTime * mVel[0]); // + (theFxHelper.mHalfRealTimeSq * mVel[0]); + new_origin[1] = mOrigin1[1] + (theFxHelper.mRealTime * mVel[1]); // + (theFxHelper.mHalfRealTimeSq * mVel[1]); + new_origin[2] = mOrigin1[2] + (theFxHelper.mRealTime * mVel[2]); // + (theFxHelper.mHalfRealTimeSq * mVel[2]); // Only perform physics if this object is tagged to do so - if ( (mFlags & FX_APPLY_PHYSICS) && !(mFlags & FX_PLAYER_VIEW) ) - { - if ( mFlags & FX_EXPENSIVE_PHYSICS ) - { - trace_t trace; - float dot; - - if ( mFlags & FX_USE_BBOX ) - { - if (mFlags & FX_GHOUL2_TRACE) - { - theFxHelper.G2Trace( trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID ); - } - else - { - theFxHelper.Trace( trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID ); + if ((mFlags & FX_APPLY_PHYSICS) && !(mFlags & FX_PLAYER_VIEW)) { + if (mFlags & FX_EXPENSIVE_PHYSICS) { + trace_t trace; + float dot; + + if (mFlags & FX_USE_BBOX) { + if (mFlags & FX_GHOUL2_TRACE) { + theFxHelper.G2Trace(trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID); + } else { + theFxHelper.Trace(trace, mOrigin1, mMin, mMax, new_origin, -1, MASK_SOLID); } - } - else - { - if (mFlags & FX_GHOUL2_TRACE) - { - theFxHelper.G2Trace( trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_PLAYERSOLID ); - } - else - { - theFxHelper.Trace( trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_SOLID ); + } else { + if (mFlags & FX_GHOUL2_TRACE) { + theFxHelper.G2Trace(trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_PLAYERSOLID); + } else { + theFxHelper.Trace(trace, mOrigin1, NULL, NULL, new_origin, -1, MASK_SOLID); } } // Hit something - if (trace.startsolid || trace.allsolid) - { - VectorClear( mVel ); - VectorClear( mAccel ); + if (trace.startsolid || trace.allsolid) { + VectorClear(mVel); + VectorClear(mAccel); - if ((mFlags & FX_GHOUL2_TRACE) && (mFlags & FX_IMPACT_RUNS_FX)) - { + if ((mFlags & FX_GHOUL2_TRACE) && (mFlags & FX_IMPACT_RUNS_FX)) { static vec3_t bsNormal = {0, 1, 0}; - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, bsNormal ); + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, bsNormal); } mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX); return true; - } - else if ( trace.fraction < 1.0f )//&& !trace.startsolid && !trace.allsolid ) + } else if (trace.fraction < 1.0f) //&& !trace.startsolid && !trace.allsolid ) { - if ( mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT )) - { - theFxScheduler.PlayEffect( mImpactFxID, trace.endpos, trace.plane.normal ); + if (mFlags & FX_IMPACT_RUNS_FX && !(trace.surfaceFlags & SURF_NOIMPACT)) { + theFxScheduler.PlayEffect(mImpactFxID, trace.endpos, trace.plane.normal); } // may need to interact with the material type we hit - theFxScheduler.MaterialImpact(&trace, (CEffect*)this); + theFxScheduler.MaterialImpact(&trace, (CEffect *)this); - if ( mFlags & FX_KILL_ON_IMPACT ) - { + if (mFlags & FX_KILL_ON_IMPACT) { // time to die return false; } - VectorMA( mVel, theFxHelper.mRealTime * trace.fraction, mAccel, mVel ); + VectorMA(mVel, theFxHelper.mRealTime * trace.fraction, mAccel, mVel); - dot = DotProduct( mVel, trace.plane.normal ); + dot = DotProduct(mVel, trace.plane.normal); - VectorMA( mVel, -2.0f * dot, trace.plane.normal, mVel ); + VectorMA(mVel, -2.0f * dot, trace.plane.normal, mVel); - VectorScale( mVel, mElasticity, mVel ); + VectorScale(mVel, mElasticity, mVel); mElasticity *= 0.5f; // If the velocity is too low, make it stop moving, rotating, and turn off physics to avoid // doing expensive operations when they aren't needed - //if ( trace.plane.normal[2] > 0.33f && mVel[2] < 10.0f ) - if (VectorLengthSquared(mVel) < 100.0f) - { - VectorClear( mVel ); - VectorClear( mAccel ); + // if ( trace.plane.normal[2] > 0.33f && mVel[2] < 10.0f ) + if (VectorLengthSquared(mVel) < 100.0f) { + VectorClear(mVel); + VectorClear(mAccel); mFlags &= ~(FX_APPLY_PHYSICS | FX_IMPACT_RUNS_FX); } // Set the origin to the exact impact point - VectorMA( trace.endpos, 1.0f, trace.plane.normal, mOrigin1 ); + VectorMA(trace.endpos, 1.0f, trace.plane.normal, mOrigin1); return true; } } } // No physics were done to this object, move it - VectorCopy( new_origin, mOrigin1 ); + VectorCopy(new_origin, mOrigin1); - if (mFlags & FX_PLAYER_VIEW) - { - if (mOrigin1[0] < 0 || mOrigin1[0] > 639 || mOrigin1[1] < 0 || mOrigin1[1] > 479) - { + if (mFlags & FX_PLAYER_VIEW) { + if (mOrigin1[0] < 0 || mOrigin1[0] > 639 || mOrigin1[1] < 0 || mOrigin1[1] > 479) { return false; } } @@ -332,69 +284,51 @@ bool CParticle::UpdateOrigin(void) //---------------------------- // Update Size //---------------------------- -void CParticle::UpdateSize(void) -{ +void CParticle::UpdateSize(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // calculate element biasing perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE_RAND ) - { + if (mFlags & FX_SIZE_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } @@ -402,16 +336,15 @@ void CParticle::UpdateSize(void) mRefEnt.radius = (mSizeStart * perc1) + (mSizeEnd * (1.0f - perc1)); } -void ClampRGB( const vec3_t in, byte *out ) -{ +void ClampRGB(const vec3_t in, byte *out) { int r; - for ( int i=0; i<3; i++ ) { + for (int i = 0; i < 3; i++) { r = Q_ftol(in[i] * 255.0f); - if ( r < 0 ) + if (r < 0) r = 0; - else if ( r > 255 ) + else if (r > 255) r = 255; out[i] = (byte)r; @@ -421,141 +354,106 @@ void ClampRGB( const vec3_t in, byte *out ) //---------------------------- // Update RGB //---------------------------- -void CParticle::UpdateRGB(void) -{ +void CParticle::UpdateRGB(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( (mFlags & FX_RGB_LINEAR) ) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if (( mFlags & FX_RGB_LINEAR )) - { + if ((mFlags & FX_RGB_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_RGB_RAND ) - { + if (mFlags & FX_RGB_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); - VectorMA( res, 1.0f - perc1, mRGBEnd, res ); + VectorScale(mRGBStart, perc1, res); + VectorMA(res, 1.0f - perc1, mRGBEnd, res); - ClampRGB( res, (byte*)(&mRefEnt.shaderRGBA) ); + ClampRGB(res, (byte *)(&mRefEnt.shaderRGBA)); } //---------------------------- // Update Alpha //---------------------------- -void CParticle::UpdateAlpha(void) -{ - int alpha; +void CParticle::UpdateAlpha(void) { + int alpha; // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( (mFlags & FX_ALPHA_LINEAR) ) - { + if ((mFlags & FX_ALPHA_LINEAR)) { // calculate element biasing perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR, FX_WAVE, or FX_CLAMP - if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_NONLINEAR ) - { - if ( theFxHelper.mTime > mAlphaParm ) - { + if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_NONLINEAR) { + if (theFxHelper.mTime > mAlphaParm) { // get percent done, using parm as the start of the non-linear fade perc2 = 1.0f - (float)(theFxHelper.mTime - mAlphaParm) / (float)(mTimeEnd - mAlphaParm); } - if (( mFlags & FX_ALPHA_LINEAR )) - { + if ((mFlags & FX_ALPHA_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mAlphaParm ); - } - else if (( mFlags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_CLAMP ) - { - if ( theFxHelper.mTime < mAlphaParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mAlphaParm); + } else if ((mFlags & FX_ALPHA_PARM_MASK) == FX_ALPHA_CLAMP) { + if (theFxHelper.mTime < mAlphaParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mAlphaParm - theFxHelper.mTime) / (float)(mAlphaParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if (( mFlags & FX_ALPHA_LINEAR )) - { + if ((mFlags & FX_ALPHA_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } @@ -567,20 +465,16 @@ void CParticle::UpdateAlpha(void) perc1 = Com_Clamp(0.0f, 1.0f, perc1); // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_ALPHA_RAND ) - { + if (mFlags & FX_ALPHA_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } alpha = Com_Clamp(0, 255, perc1 * 255.0f); - if ( mFlags & FX_USE_ALPHA ) - { + if (mFlags & FX_USE_ALPHA) { // should use this when using art that has an alpha channel - mRefEnt.shaderRGBA[3] = (byte)alpha; - } - else - { + mRefEnt.shaderRGBA[3] = (byte)alpha; + } else { // Modulate the rgb fields by the alpha value to do the fade, works fine for additive blending mRefEnt.shaderRGBA[0] = ((int)mRefEnt.shaderRGBA[0] * alpha) >> 8; mRefEnt.shaderRGBA[1] = ((int)mRefEnt.shaderRGBA[1] * alpha) >> 8; @@ -589,145 +483,126 @@ void CParticle::UpdateAlpha(void) } //-------------------------- -void CParticle::UpdateRotation(void) -{ +void CParticle::UpdateRotation(void) { mRefEnt.rotation += theFxHelper.mFrameTime * 0.01f * mRotationDelta; - mRotationDelta *= ( 1.0f - ( theFxHelper.mFrameTime * 0.0007f )); // decay rotationDelta + mRotationDelta *= (1.0f - (theFxHelper.mFrameTime * 0.0007f)); // decay rotationDelta } - //-------------------------------- // // Derived Oriented Particle Class // //-------------------------------- -COrientedParticle::COrientedParticle(void) -{ - mRefEnt.reType = RT_ORIENTED_QUAD; -} +COrientedParticle::COrientedParticle(void) { mRefEnt.reType = RT_ORIENTED_QUAD; } //---------------------------- -bool COrientedParticle::Cull(void) -{ - vec3_t dir; -// float len; +bool COrientedParticle::Cull(void) { + vec3_t dir; + // float len; // Get the direction to the view - VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mOrigin1, theFxHelper.refdef->vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) < 0) { return true; } -// len = VectorLengthSquared( dir ); + // len = VectorLengthSquared( dir ); // don't cull stuff that's associated with inview wpns - if ( mFlags & FX_DEPTH_HACK ) - { + if (mFlags & FX_DEPTH_HACK) { return false; } // Can't be too close -// if ( len < fx_nearCull->value * fx_nearCull->value) -// { -// return true; -// } + // if ( len < fx_nearCull->value * fx_nearCull->value) + // { + // return true; + // } return false; } //---------------------------- -void COrientedParticle::Draw(void) -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void COrientedParticle::Draw(void) { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } // Add our refEntity to the scene - VectorCopy( mOrigin1, mRefEnt.origin ); - if ( !(mFlags&FX_RELATIVE) ) - { - VectorCopy( mNormal, mRefEnt.axis[0] ); - MakeNormalVectors( mRefEnt.axis[0], mRefEnt.axis[1], mRefEnt.axis[2] ); + VectorCopy(mOrigin1, mRefEnt.origin); + if (!(mFlags & FX_RELATIVE)) { + VectorCopy(mNormal, mRefEnt.axis[0]); + MakeNormalVectors(mRefEnt.axis[0], mRefEnt.axis[1], mRefEnt.axis[2]); } - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } //---------------------------- // Update //---------------------------- -bool COrientedParticle::Update(void) -{ +bool COrientedParticle::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - vec3_t org; - matrix3_t ax; + vec3_t org; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // calc the real velocity and accel vectors - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); -// realVel[2] += 0.5f * mGravity * time; + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); + // realVel[2] += 0.5f * mGravity * time; - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); // Get our real velocity at the current time, taking into account the effects of acceleartion. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); - - //use the normalOffset and add that to the actual normal of the bolt - //NOTE: not tested!!! - VectorCopy( ax[0], mRefEnt.axis[0] ); - VectorCopy( ax[1], mRefEnt.axis[1] ); - VectorCopy( ax[2], mRefEnt.axis[2] ); - - //vec3_t offsetAngles; - //VectorSet( offsetAngles, 0, 90, 90 ); - - matrix3_t offsetAxis; - //NOTE: mNormal is actually PITCH YAW and ROLL offsets - AnglesToAxis( mNormal, offsetAxis ); - MatrixMultiply( offsetAxis, ax, mRefEnt.axis ); - } - else if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + VectorMA(org, time, realVel, mOrigin1); + + // use the normalOffset and add that to the actual normal of the bolt + // NOTE: not tested!!! + VectorCopy(ax[0], mRefEnt.axis[0]); + VectorCopy(ax[1], mRefEnt.axis[1]); + VectorCopy(ax[2], mRefEnt.axis[2]); + + // vec3_t offsetAngles; + // VectorSet( offsetAngles, 0, 90, 90 ); + + matrix3_t offsetAxis; + // NOTE: mNormal is actually PITCH YAW and ROLL offsets + AnglesToAxis(mNormal, offsetAxis); + MatrixMultiply(offsetAxis, ax, mRefEnt.axis); + } else if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull() ) - { // Only update these if the thing is visible. + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateRGB(); UpdateAlpha(); @@ -739,65 +614,53 @@ bool COrientedParticle::Update(void) return true; } - //---------------------------- // // Derived Line Class // //---------------------------- -CLine::CLine(void) -{ - mRefEnt.reType = RT_LINE; -} +CLine::CLine(void) { mRefEnt.reType = RT_LINE; } //---------------------------- -void CLine::Draw(void) -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CLine::Draw(void) { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } //---------------------------- -bool CLine::Update(void) -{ +bool CLine::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - matrix3_t ax; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point + VectorAdd(mOrigin1, mOrgOffset, mOrigin1); // add the offset to the bolt point - VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 ); - VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 ); - VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 ); + VectorMA(mOrigin1, mVel[0], ax[0], mOrigin2); + VectorMA(mOrigin2, mVel[1], ax[1], mOrigin2); + VectorMA(mOrigin2, mVel[2], ax[2], mOrigin2); } - if ( !Cull()) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateRGB(); @@ -814,82 +677,67 @@ bool CLine::Update(void) // Derived Electricity Class // //---------------------------- -CElectricity::CElectricity(void) -{ - mRefEnt.reType = RT_ELECTRICITY; -} +CElectricity::CElectricity(void) { mRefEnt.reType = RT_ELECTRICITY; } //---------------------------- -void CElectricity::Initialize(void) -{ +void CElectricity::Initialize(void) { mRefEnt.frame = flrand(0.0f, 1.0f) * 1265536.0f; mRefEnt.axis[0][2] = theFxHelper.mTime + (mTimeEnd - mTimeStart); // endtime - if ( mFlags & FX_DEPTH_HACK ) - { + if (mFlags & FX_DEPTH_HACK) { mRefEnt.renderfx |= RF_DEPTHHACK; } - if ( mFlags & FX_BRANCH ) - { + if (mFlags & FX_BRANCH) { mRefEnt.renderfx |= RF_FORKED; } - if ( mFlags & FX_TAPER ) - { + if (mFlags & FX_TAPER) { mRefEnt.renderfx |= RF_TAPERED; } - if ( mFlags & FX_GROW ) - { + if (mFlags & FX_GROW) { mRefEnt.renderfx |= RF_GROW; } } //---------------------------- -void CElectricity::Draw(void) -{ - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorCopy( mOrigin2, mRefEnt.oldorigin ); +void CElectricity::Draw(void) { + VectorCopy(mOrigin1, mRefEnt.origin); + VectorCopy(mOrigin2, mRefEnt.oldorigin); mRefEnt.axis[0][0] = mChaos; mRefEnt.axis[0][1] = mTimeEnd - mTimeStart; - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } //---------------------------- -bool CElectricity::Update(void) -{ +bool CElectricity::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - matrix3_t ax; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point + VectorAdd(mOrigin1, mOrgOffset, mOrigin1); // add the offset to the bolt point - VectorMA( mOrigin1, mVel[0], ax[0], mOrigin2 ); - VectorMA( mOrigin2, mVel[1], ax[1], mOrigin2 ); - VectorMA( mOrigin2, mVel[2], ax[2], mOrigin2 ); + VectorMA(mOrigin1, mVel[0], ax[0], mOrigin2); + VectorMA(mOrigin2, mVel[1], ax[1], mOrigin2); + VectorMA(mOrigin2, mVel[2], ax[2], mOrigin2); } - if ( !Cull()) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateRGB(); @@ -906,95 +754,84 @@ bool CElectricity::Update(void) // Derived Tail Class // //---------------------------- -CTail::CTail(void) -{ - mRefEnt.reType = RT_LINE; -} +CTail::CTail(void) { mRefEnt.reType = RT_LINE; } //---------------------------- -void CTail::Draw(void) -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CTail::Draw(void) { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; } //---------------------------- -bool CTail::Update(void) -{ +bool CTail::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - vec3_t org; - matrix3_t ax; - if (mModelNum>=0 && mBoltNum>=0) //bolt style + vec3_t org; + matrix3_t ax; + if (mModelNum >= 0 && mBoltNum >= 0) // bolt style { - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, org, ax)) { // could not get bolt return false; } } - vec3_t realVel, realAccel; + vec3_t realVel, realAccel; - VectorMA( org, mOrgOffset[0], ax[0], org ); - VectorMA( org, mOrgOffset[1], ax[1], org ); - VectorMA( org, mOrgOffset[2], ax[2], org ); + VectorMA(org, mOrgOffset[0], ax[0], org); + VectorMA(org, mOrgOffset[1], ax[1], org); + VectorMA(org, mOrgOffset[2], ax[2], org); // calc the real velocity and accel vectors - // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra work - VectorScale( ax[0], mVel[0], realVel ); - VectorMA( realVel, mVel[1], ax[1], realVel ); - VectorMA( realVel, mVel[2], ax[2], realVel ); + // FIXME: if you want right and up movement in addition to the forward movement, you'll have to convert dir into a set of perp. axes and do some extra + // work + VectorScale(ax[0], mVel[0], realVel); + VectorMA(realVel, mVel[1], ax[1], realVel); + VectorMA(realVel, mVel[2], ax[2], realVel); - VectorScale( ax[0], mAccel[0], realAccel ); - VectorMA( realAccel, mAccel[1], ax[1], realAccel ); - VectorMA( realAccel, mAccel[2], ax[2], realAccel ); + VectorScale(ax[0], mAccel[0], realAccel); + VectorMA(realAccel, mAccel[1], ax[1], realAccel); + VectorMA(realAccel, mAccel[2], ax[2], realAccel); - const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; + const float time = (theFxHelper.mTime - mTimeStart) * 0.001f; // Get our real velocity at the current time, taking into account the effects of acceleration. NOTE: not sure if this is even 100% correct math-wise - VectorMA( realVel, time, realAccel, realVel ); + VectorMA(realVel, time, realAccel, realVel); // Now move us to where we should be at the given time - VectorMA( org, time, realVel, mOrigin1 ); + VectorMA(org, time, realVel, mOrigin1); // Just calc an old point some time in the past, doesn't really matter when - VectorMA( org, (time - 0.003f), realVel, mOldOrigin ); + VectorMA(org, (time - 0.003f), realVel, mOldOrigin); } #ifdef _DEBUG - else if ( !fx_freeze->integer ) + else if (!fx_freeze->integer) #else else #endif { - VectorCopy( mOrigin1, mOldOrigin ); + VectorCopy(mOrigin1, mOldOrigin); } - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } - if ( !Cull() ) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateLength(); @@ -1009,69 +846,51 @@ bool CTail::Update(void) } //---------------------------- -void CTail::UpdateLength(void) -{ +void CTail::UpdateLength(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // calculate element biasing perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_NONLINEAR ) - { - if ( theFxHelper.mTime > mLengthParm ) - { + if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_NONLINEAR) { + if (theFxHelper.mTime > mLengthParm) { // get percent done, using parm as the start of the non-linear fade perc2 = 1.0f - (float)(theFxHelper.mTime - mLengthParm) / (float)(mTimeEnd - mLengthParm); } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mLengthParm ); - } - else if (( mFlags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_CLAMP ) - { - if ( theFxHelper.mTime < mLengthParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mLengthParm); + } else if ((mFlags & FX_LENGTH_PARM_MASK) == FX_LENGTH_CLAMP) { + if (theFxHelper.mTime < mLengthParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mLengthParm - theFxHelper.mTime) / (float)(mLengthParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_LENGTH_LINEAR ) - { + if (mFlags & FX_LENGTH_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_LENGTH_RAND ) - { + if (mFlags & FX_LENGTH_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } @@ -1079,72 +898,60 @@ void CTail::UpdateLength(void) mLength = (mLengthStart * perc1) + (mLengthEnd * (1.0f - perc1)); } - //---------------------------- -void CTail::CalcNewEndpoint(void) -{ +void CTail::CalcNewEndpoint(void) { vec3_t temp; // FIXME: Hmmm, this looks dumb when physics are on and a bounce happens - VectorSubtract( mOldOrigin, mOrigin1, temp ); + VectorSubtract(mOldOrigin, mOrigin1, temp); // I wish we didn't have to do a VectorNormalize every frame..... - VectorNormalize( temp ); + VectorNormalize(temp); - VectorMA( mOrigin1, mLength, temp, mRefEnt.oldorigin ); + VectorMA(mOrigin1, mLength, temp, mRefEnt.oldorigin); } - //---------------------------- // // Derived Cylinder Class // //---------------------------- -CCylinder::CCylinder(void) -{ +CCylinder::CCylinder(void) { mRefEnt.reType = RT_CYLINDER; mTraceEnd = qfalse; } -bool CCylinder::Cull(void) -{ - if (mTraceEnd) - { //eh, don't cull variable-length cylinders +bool CCylinder::Cull(void) { + if (mTraceEnd) { // eh, don't cull variable-length cylinders return false; } return CTail::Cull(); } -void CCylinder::UpdateLength(void) -{ - if (mTraceEnd) - { +void CCylinder::UpdateLength(void) { + if (mTraceEnd) { vec3_t temp; trace_t tr; - VectorMA( mOrigin1, FX_MAX_TRACE_DIST, mRefEnt.axis[0], temp ); - theFxHelper.Trace( tr, mOrigin1, NULL, NULL, temp, -1, MASK_SOLID ); - VectorSubtract( tr.endpos, mOrigin1, temp ); + VectorMA(mOrigin1, FX_MAX_TRACE_DIST, mRefEnt.axis[0], temp); + theFxHelper.Trace(tr, mOrigin1, NULL, NULL, temp, -1, MASK_SOLID); + VectorSubtract(tr.endpos, mOrigin1, temp); mLength = VectorLength(temp); - } - else - { + } else { CTail::UpdateLength(); } } //---------------------------- -void CCylinder::Draw(void) -{ - if ( mFlags & FX_DEPTH_HACK ) - { +void CCylinder::Draw(void) { + if (mFlags & FX_DEPTH_HACK) { // Not sure if first person needs to be set, but it can't hurt? mRefEnt.renderfx |= RF_DEPTHHACK; } - VectorCopy( mOrigin1, mRefEnt.origin ); - VectorMA( mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin ); + VectorCopy(mOrigin1, mRefEnt.origin); + VectorMA(mOrigin1, mLength, mRefEnt.axis[0], mRefEnt.oldorigin); theFxHelper.AddFxToScene(&mRefEnt); drawnFx++; @@ -1153,69 +960,51 @@ void CCylinder::Draw(void) //---------------------------- // Update Size2 //---------------------------- -void CCylinder::UpdateSize2(void) -{ +void CCylinder::UpdateSize2(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // calculate element biasing perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_NONLINEAR ) - { - if ( theFxHelper.mTime > mSize2Parm ) - { + if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_NONLINEAR) { + if (theFxHelper.mTime > mSize2Parm) { // get percent done, using parm as the start of the non-linear fade perc2 = 1.0f - (float)(theFxHelper.mTime - mSize2Parm) / (float)(mTimeEnd - mSize2Parm); } - if ( (mFlags & FX_SIZE2_LINEAR) ) - { + if ((mFlags & FX_SIZE2_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSize2Parm ); - } - else if (( mFlags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_CLAMP ) - { - if ( theFxHelper.mTime < mSize2Parm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mSize2Parm); + } else if ((mFlags & FX_SIZE2_PARM_MASK) == FX_SIZE2_CLAMP) { + if (theFxHelper.mTime < mSize2Parm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mSize2Parm - theFxHelper.mTime) / (float)(mSize2Parm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE2_LINEAR ) - { + if (mFlags & FX_SIZE2_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE2_RAND ) - { + if (mFlags & FX_SIZE2_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } @@ -1224,32 +1013,27 @@ void CCylinder::UpdateSize2(void) } //---------------------------- -bool CCylinder::Update(void) -{ +bool CCylinder::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - matrix3_t ax; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - VectorAdd(mOrigin1, mOrgOffset, mOrigin1); //add the offset to the bolt point + VectorAdd(mOrigin1, mOrgOffset, mOrigin1); // add the offset to the bolt point - VectorCopy( ax[0], mRefEnt.axis[0] ); - //FIXME: should mNormal be a modifier on the forward axis? + VectorCopy(ax[0], mRefEnt.axis[0]); + // FIXME: should mNormal be a modifier on the forward axis? /* VectorMA( mOrigin1, mNormal[0], ax[0], mOrigin2 ); VectorMA( mOrigin2, mNormal[1], ax[1], mOrigin2 ); @@ -1257,8 +1041,7 @@ bool CCylinder::Update(void) */ } - if ( !Cull() ) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateSize(); UpdateSize2(); @@ -1272,53 +1055,46 @@ bool CCylinder::Update(void) return true; } - //---------------------------- // // Derived Emitter Class // //---------------------------- -CEmitter::CEmitter(void) -{ +CEmitter::CEmitter(void) { // There may or may not be a model, but if there isn't one, // we just won't bother adding the refEnt in our Draw func mRefEnt.reType = RT_MODEL; } //---------------------------- -CEmitter::~CEmitter(void) -{ -} +CEmitter::~CEmitter(void) {} //---------------------------- // Draw //---------------------------- -void CEmitter::Draw(void) -{ +void CEmitter::Draw(void) { // Emitters don't draw themselves, but they may need to add an attached model - if ( mFlags & FX_ATTACHED_MODEL ) - { + if (mFlags & FX_ATTACHED_MODEL) { mRefEnt.nonNormalizedAxes = qtrue; - VectorCopy( mOrigin1, mRefEnt.origin ); + VectorCopy(mOrigin1, mRefEnt.origin); - VectorScale( mRefEnt.axis[0], mRefEnt.radius, mRefEnt.axis[0] ); - VectorScale( mRefEnt.axis[1], mRefEnt.radius, mRefEnt.axis[1] ); - VectorScale( mRefEnt.axis[2], mRefEnt.radius, mRefEnt.axis[2] ); + VectorScale(mRefEnt.axis[0], mRefEnt.radius, mRefEnt.axis[0]); + VectorScale(mRefEnt.axis[1], mRefEnt.radius, mRefEnt.axis[1]); + VectorScale(mRefEnt.axis[2], mRefEnt.radius, mRefEnt.axis[2]); - theFxHelper.AddFxToScene((miniRefEntity_t*)0);// I hate having to do this, but this needs to get added as a regular refEntity + theFxHelper.AddFxToScene((miniRefEntity_t *)0); // I hate having to do this, but this needs to get added as a regular refEntity theFxHelper.AddFxToScene(&mRefEnt); } // If we are emitting effects, we had better be careful because just calling it every cgame frame could // either choke up the effects system on a fast machine, or look really nasty on a low end one. - if ( mFlags & FX_EMIT_FX ) - { - vec3_t org, v; - float ftime, time2, step; - int t, dif; + if (mFlags & FX_EMIT_FX) { + vec3_t org, v; + float ftime, time2, step; + int t, dif; -#define TRAIL_RATE 12 // we "think" at about a 60hz rate +#define TRAIL_RATE 12 // we "think" at about a 60hz rate // Pick a target step distance and square it step = mDensity + flrand(-mVariance, mVariance); @@ -1326,12 +1102,11 @@ void CEmitter::Draw(void) dif = 0; - for ( t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE ) - { + for (t = mOldTime; t <= theFxHelper.mTime; t += TRAIL_RATE) { dif += TRAIL_RATE; // ?Not sure if it's better to update this before or after updating the origin - VectorMA( mOldVelocity, dif * 0.001f, mAccel, v ); + VectorMA(mOldVelocity, dif * 0.001f, mAccel, v); // Calc the time differences ftime = dif * 0.001f; @@ -1343,17 +1118,16 @@ void CEmitter::Draw(void) org[2] = mOldOrigin[2] + (ftime * v[2]) + (time2 * v[2]); // Is it time to draw an effect? - if ( DistanceSquared( org, mOldOrigin ) >= step ) - { + if (DistanceSquared(org, mOldOrigin) >= step) { // Pick a new target step distance and square it step = mDensity + flrand(-mVariance, mVariance); step *= step; // We met the step criteria so, we should add in the effect - theFxScheduler.PlayEffect( mEmitterFxID, org, mRefEnt.axis ); + theFxScheduler.PlayEffect(mEmitterFxID, org, mRefEnt.axis); - VectorCopy( org, mOldOrigin ); - VectorCopy( v, mOldVelocity ); + VectorCopy(org, mOldOrigin); + VectorCopy(v, mOldVelocity); dif = 0; mOldTime = t; } @@ -1363,29 +1137,23 @@ void CEmitter::Draw(void) } //---------------------------- -bool CEmitter::Update(void) -{ +bool CEmitter::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } // Use this to track if we've stopped moving - VectorCopy( mOrigin1, mOldOrigin ); - VectorCopy( mVel, mOldVelocity ); + VectorCopy(mOrigin1, mOldOrigin); + VectorCopy(mVel, mOldVelocity); - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - assert(0);//need this? - + assert(0); // need this? } - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } @@ -1394,42 +1162,36 @@ bool CEmitter::Update(void) // If the thing is no longer moving, kill the angle delta, but don't do it too quickly or it will // look very artificial. Don't do it too slowly or it will look like there is no friction. - if ( VectorCompare( mOldOrigin, mOrigin1 )) - { - VectorScale( mAngleDelta, 0.7f, mAngleDelta ); - } - else - { + if (VectorCompare(mOldOrigin, mOrigin1)) { + VectorScale(mAngleDelta, 0.7f, mAngleDelta); + } else { moving = true; } - if ( mFlags & FX_PAPER_PHYSICS ) - { + if (mFlags & FX_PAPER_PHYSICS) { // do this in a more framerate independent manner - float sc = ( 20.0f / theFxHelper.mFrameTime); + float sc = (20.0f / theFxHelper.mFrameTime); // bah, evil clamping - if ( sc >= 1.0f ) - { + if (sc >= 1.0f) { sc = 1.0f; } - if ( moving ) - { + if (moving) { // scale the velocity down, basically inducing drag. Acceleration ( gravity ) should keep it pulling down, which is what we want. - VectorScale( mVel, (sc * 0.8f + 0.2f ) * 0.92f, mVel ); + VectorScale(mVel, (sc * 0.8f + 0.2f) * 0.92f, mVel); // add some chaotic motion based on the way we are oriented - VectorMA( mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[0], mVel ); - VectorMA( mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[1], mVel ); + VectorMA(mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[0], mVel); + VectorMA(mVel, (1.5f - sc) * 4.0f, mRefEnt.axis[1], mVel); } // make us settle so we can lay flat - mAngles[0] *= (0.97f * (sc * 0.4f + 0.6f )); - mAngles[2] *= (0.97f * (sc * 0.4f + 0.6f )); + mAngles[0] *= (0.97f * (sc * 0.4f + 0.6f)); + mAngles[2] *= (0.97f * (sc * 0.4f + 0.6f)); // decay our angle delta so we don't rotate as quickly - VectorScale( mAngleDelta, (0.96f * (sc * 0.1f + 0.9f )), mAngleDelta ); + VectorScale(mAngleDelta, (0.96f * (sc * 0.1f + 0.9f)), mAngleDelta); } UpdateAngles(); @@ -1441,13 +1203,12 @@ bool CEmitter::Update(void) } //---------------------------- -void CEmitter::UpdateAngles(void) -{ - VectorMA( mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, mAngles ); // was 0.001f, but then you really have to jack up the delta to even notice anything - AnglesToAxis( mAngles, mRefEnt.axis ); +void CEmitter::UpdateAngles(void) { + VectorMA(mAngles, theFxHelper.mFrameTime * 0.01f, mAngleDelta, + mAngles); // was 0.001f, but then you really have to jack up the delta to even notice anything + AnglesToAxis(mAngles, mRefEnt.axis); } - //-------------------------- // // Derived Light Class @@ -1455,40 +1216,34 @@ void CEmitter::UpdateAngles(void) //-------------------------- //---------------------------- -void CLight::Draw(void) -{ - theFxHelper.AddLightToScene( mOrigin1, mRefEnt.radius, mRefEnt.origin[0], mRefEnt.origin[1], mRefEnt.origin[2] ); +void CLight::Draw(void) { + theFxHelper.AddLightToScene(mOrigin1, mRefEnt.radius, mRefEnt.origin[0], mRefEnt.origin[1], mRefEnt.origin[2]); drawnFx++; } //---------------------------- // Update //---------------------------- -bool CLight::Update(void) -{ +bool CLight::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } - if ( mFlags & FX_RELATIVE ) - { - if ( !re->G2API_IsGhoul2InfovValid (*mGhoul2)) - { // the thing we are bolted to is no longer valid, so we may as well just die. + if (mFlags & FX_RELATIVE) { + if (!re->G2API_IsGhoul2InfovValid(*mGhoul2)) { // the thing we are bolted to is no longer valid, so we may as well just die. return false; } - matrix3_t ax; + matrix3_t ax; // Get our current position and direction - if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) - { //could not get bolt + if (!theFxHelper.GetOriginAxisFromBolt(mGhoul2, mEntNum, mModelNum, mBoltNum, mOrigin1, ax)) { // could not get bolt return false; } - VectorMA( mOrigin1, mOrgOffset[0], ax[0], mOrigin1 ); - VectorMA( mOrigin1, mOrgOffset[1], ax[1], mOrigin1 ); - VectorMA( mOrigin1, mOrgOffset[2], ax[2], mOrigin1 ); + VectorMA(mOrigin1, mOrgOffset[0], ax[0], mOrigin1); + VectorMA(mOrigin1, mOrgOffset[1], ax[1], mOrigin1); + VectorMA(mOrigin1, mOrgOffset[2], ax[2], mOrigin1); } UpdateSize(); @@ -1502,69 +1257,51 @@ bool CLight::Update(void) //---------------------------- // Update Size //---------------------------- -void CLight::UpdateSize(void) -{ +void CLight::UpdateSize(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; + float perc1 = 1.0f, perc2 = 1.0f; - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // calculate element biasing perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_NONLINEAR ) - { - if ( theFxHelper.mTime > mSizeParm ) - { + if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_NONLINEAR) { + if (theFxHelper.mTime > mSizeParm) { // get percent done, using parm as the start of the non-linear fade perc2 = 1.0f - (float)(theFxHelper.mTime - mSizeParm) / (float)(mTimeEnd - mSizeParm); } - if ( (mFlags & FX_SIZE_LINEAR) ) - { + if ((mFlags & FX_SIZE_LINEAR)) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf( (theFxHelper.mTime - mTimeStart) * mSizeParm ); - } - else if (( mFlags & FX_SIZE_PARM_MASK ) == FX_SIZE_CLAMP ) - { - if ( theFxHelper.mTime < mSizeParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mSizeParm); + } else if ((mFlags & FX_SIZE_PARM_MASK) == FX_SIZE_CLAMP) { + if (theFxHelper.mTime < mSizeParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mSizeParm - theFxHelper.mTime) / (float)(mSizeParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_SIZE_LINEAR ) - { + if (mFlags & FX_SIZE_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_SIZE_RAND ) - { + if (mFlags & FX_SIZE_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } @@ -1575,77 +1312,59 @@ void CLight::UpdateSize(void) //---------------------------- // Update RGB //---------------------------- -void CLight::UpdateRGB(void) -{ +void CLight::UpdateRGB(void) { // completely biased towards start if it doesn't get overridden - float perc1 = 1.0f, perc2 = 1.0f; - vec3_t res; + float perc1 = 1.0f, perc2 = 1.0f; + vec3_t res; - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // calculate element biasing - perc1 = 1.0f - (float)( theFxHelper.mTime - mTimeStart ) / (float)( mTimeEnd - mTimeStart ); + perc1 = 1.0f - (float)(theFxHelper.mTime - mTimeStart) / (float)(mTimeEnd - mTimeStart); } // We can combine FX_LINEAR with _either_ FX_NONLINEAR or FX_WAVE - if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_NONLINEAR ) - { - if ( theFxHelper.mTime > mRGBParm ) - { + if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_NONLINEAR) { + if (theFxHelper.mTime > mRGBParm) { // get percent done, using parm as the start of the non-linear fade - perc2 = 1.0f - (float)( theFxHelper.mTime - mRGBParm ) / (float)( mTimeEnd - mRGBParm ); + perc2 = 1.0f - (float)(theFxHelper.mTime - mRGBParm) / (float)(mTimeEnd - mRGBParm); } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { // wave gen, with parm being the frequency multiplier - perc1 = perc1 * cosf(( theFxHelper.mTime - mTimeStart ) * mRGBParm ); - } - else if (( mFlags & FX_RGB_PARM_MASK ) == FX_RGB_CLAMP ) - { - if ( theFxHelper.mTime < mRGBParm ) - { + perc1 = perc1 * cosf((theFxHelper.mTime - mTimeStart) * mRGBParm); + } else if ((mFlags & FX_RGB_PARM_MASK) == FX_RGB_CLAMP) { + if (theFxHelper.mTime < mRGBParm) { // get percent done, using parm as the start of the non-linear fade perc2 = (float)(mRGBParm - theFxHelper.mTime) / (float)(mRGBParm - mTimeStart); - } - else - { + } else { perc2 = 0.0f; // make it full size?? } - if ( mFlags & FX_RGB_LINEAR ) - { + if (mFlags & FX_RGB_LINEAR) { // do an even blend perc1 = perc1 * 0.5f + perc2 * 0.5f; - } - else - { + } else { // just copy it over...sigh perc1 = perc2; } } // If needed, RAND can coexist with linear and either non-linear or wave. - if ( mFlags & FX_RGB_RAND ) - { + if (mFlags & FX_RGB_RAND) { // Random simply modulates the existing value perc1 = flrand(0.0f, perc1); } // Now get the correct color - VectorScale( mRGBStart, perc1, res ); - VectorMA(res, ( 1.0f - perc1 ), mRGBEnd, mRefEnt.origin); + VectorScale(mRGBStart, perc1, res); + VectorMA(res, (1.0f - perc1), mRGBEnd, mRefEnt.origin); } //-------------------------- @@ -1653,35 +1372,34 @@ void CLight::UpdateRGB(void) // Derived Trail Class // //-------------------------- -#define NEW_MUZZLE 0 -#define NEW_TIP 1 -#define OLD_TIP 2 -#define OLD_MUZZLE 3 +#define NEW_MUZZLE 0 +#define NEW_TIP 1 +#define OLD_TIP 2 +#define OLD_MUZZLE 3 //---------------------------- -void CTrail::Draw() -{ - polyVert_t verts[3]; -// vec3_t color; +void CTrail::Draw() { + polyVert_t verts[3]; + // vec3_t color; // build the first tri out of the new muzzle...new tip...old muzzle - VectorCopy( mVerts[NEW_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[2].xyz ); + VectorCopy(mVerts[NEW_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[2].xyz); -// VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[NEW_MUZZLE].curRGB, mVerts[NEW_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[NEW_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[NEW_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[NEW_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[NEW_MUZZLE].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[1].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[1].modulate[2] = mVerts[NEW_TIP].rgb[2]; verts[1].modulate[3] = mVerts[NEW_TIP].alpha; -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[2].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[2].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[2].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; @@ -1695,26 +1413,26 @@ void CTrail::Draw() verts[2].st[1] = mVerts[OLD_MUZZLE].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); // build the second tri out of the old muzzle...old tip...new tip - VectorCopy( mVerts[OLD_MUZZLE].origin, verts[0].xyz ); - VectorCopy( mVerts[OLD_TIP].origin, verts[1].xyz ); - VectorCopy( mVerts[NEW_TIP].origin, verts[2].xyz ); + VectorCopy(mVerts[OLD_MUZZLE].origin, verts[0].xyz); + VectorCopy(mVerts[OLD_TIP].origin, verts[1].xyz); + VectorCopy(mVerts[NEW_TIP].origin, verts[2].xyz); -// VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); + // VectorScale( mVerts[OLD_MUZZLE].curRGB, mVerts[OLD_MUZZLE].curAlpha, color ); verts[0].modulate[0] = mVerts[OLD_MUZZLE].rgb[0]; verts[0].modulate[1] = mVerts[OLD_MUZZLE].rgb[1]; verts[0].modulate[2] = mVerts[OLD_MUZZLE].rgb[2]; verts[0].modulate[3] = mVerts[OLD_MUZZLE].alpha; -// VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); + // VectorScale( mVerts[OLD_TIP].curRGB, mVerts[OLD_TIP].curAlpha, color ); verts[1].modulate[0] = mVerts[OLD_TIP].rgb[0]; verts[1].modulate[1] = mVerts[OLD_TIP].rgb[1]; verts[1].modulate[2] = mVerts[OLD_TIP].rgb[2]; verts[0].modulate[3] = mVerts[OLD_TIP].alpha; -// VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); + // VectorScale( mVerts[NEW_TIP].curRGB, mVerts[NEW_TIP].curAlpha, color ); verts[2].modulate[0] = mVerts[NEW_TIP].rgb[0]; verts[2].modulate[1] = mVerts[NEW_TIP].rgb[1]; verts[2].modulate[2] = mVerts[NEW_TIP].rgb[2]; @@ -1728,7 +1446,7 @@ void CTrail::Draw() verts[2].st[1] = mVerts[NEW_TIP].curST[1]; // Add this tri - theFxHelper.AddPolyToScene( mShader, 3, verts ); + theFxHelper.AddPolyToScene(mShader, 3, verts); drawnFx++; } @@ -1736,32 +1454,28 @@ void CTrail::Draw() //---------------------------- // Update //---------------------------- -bool CTrail::Update() -{ +bool CTrail::Update() { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } float perc = (float)(mTimeEnd - theFxHelper.mTime) / (float)(mTimeEnd - mTimeStart); - for ( int t = 0; t < 4; t++ ) - { -// mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); -// if ( mVerts[t].curAlpha < 0.0f ) -// { -// mVerts[t].curAlpha = 0.0f; -// } - -// VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); -// VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); - mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * ( 1.0f - perc ); - if ( mVerts[t].curST[0] > 1.0f ) - { + for (int t = 0; t < 4; t++) { + // mVerts[t].curAlpha = mVerts[t].alpha * perc + mVerts[t].destAlpha * ( 1.0f - perc ); + // if ( mVerts[t].curAlpha < 0.0f ) + // { + // mVerts[t].curAlpha = 0.0f; + // } + + // VectorScale( mVerts[t].rgb, perc, mVerts[t].curRGB ); + // VectorMA( mVerts[t].curRGB, ( 1.0f - perc ), mVerts[t].destrgb, mVerts[t].curRGB ); + mVerts[t].curST[0] = mVerts[t].ST[0] * perc + mVerts[t].destST[0] * (1.0f - perc); + if (mVerts[t].curST[0] > 1.0f) { mVerts[t].curST[0] = 1.0f; } - mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * ( 1.0f - perc ); + mVerts[t].curST[1] = mVerts[t].ST[1] * perc + mVerts[t].destST[1] * (1.0f - perc); } Draw(); @@ -1776,24 +1490,21 @@ bool CTrail::Update() //-------------------------- //---------------------------- -bool CPoly::Cull(void) -{ - vec3_t dir; +bool CPoly::Cull(void) { + vec3_t dir; // Get the direction to the view - VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mOrigin1, theFxHelper.refdef->vieworg, dir); // Check if it's behind the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) < 0 ) - { + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) < 0) { return true; } - float len = VectorLengthSquared( dir ); + float len = VectorLengthSquared(dir); // Can't be too close - if ( len < fx_nearCull->value * fx_nearCull->value) - { + if (len < fx_nearCull->value * fx_nearCull->value) { return true; } @@ -1801,49 +1512,46 @@ bool CPoly::Cull(void) } //---------------------------- -void CPoly::Draw(void) -{ - polyVert_t verts[MAX_CPOLY_VERTS]; +void CPoly::Draw(void) { + polyVert_t verts[MAX_CPOLY_VERTS]; - for ( int i = 0; i < mCount; i++ ) - { + for (int i = 0; i < mCount; i++) { // Add our midpoint and vert offset to get the actual vertex - VectorAdd( mOrigin1, mOrg[i], verts[i].xyz ); + VectorAdd(mOrigin1, mOrg[i], verts[i].xyz); // Assign the same color to each vert - for ( int k=0; k<4; k++ ) + for (int k = 0; k < 4; k++) verts[i].modulate[k] = mRefEnt.shaderRGBA[k]; // Copy the ST coords - VectorCopy2( mST[i], verts[i].st ); + VectorCopy2(mST[i], verts[i].st); } // Add this poly - theFxHelper.AddPolyToScene( mRefEnt.customShader, mCount, verts ); + theFxHelper.AddPolyToScene(mRefEnt.customShader, mCount, verts); drawnFx++; } //---------------------------- -void CPoly::CalcRotateMatrix(void) -{ - float cosX, cosZ; - float sinX, sinZ; - float rad; +void CPoly::CalcRotateMatrix(void) { + float cosX, cosZ; + float sinX, sinZ; + float rad; // rotate around Z - rad = DEG2RAD( mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f ); - cosZ = cosf( rad ); - sinZ = sinf( rad ); + rad = DEG2RAD(mRotDelta[YAW] * theFxHelper.mFrameTime * 0.01f); + cosZ = cosf(rad); + sinZ = sinf(rad); // rotate around X - rad = DEG2RAD( mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f ); - cosX = cosf( rad ); - sinX = sinf( rad ); - -/*Pitch - aroundx Yaw - around z -1 0 0 c -s 0 -0 c -s s c 0 -0 s c 0 0 1 -*/ + rad = DEG2RAD(mRotDelta[PITCH] * theFxHelper.mFrameTime * 0.01f); + cosX = cosf(rad); + sinX = sinf(rad); + + /*Pitch - aroundx Yaw - around z + 1 0 0 c -s 0 + 0 c -s s c 0 + 0 s c 0 0 1 + */ mRot[0][0] = cosZ; mRot[1][0] = -sinZ; mRot[2][0] = 0; @@ -1853,69 +1561,60 @@ void CPoly::CalcRotateMatrix(void) mRot[0][2] = sinX * sinZ; mRot[1][2] = sinX * cosZ; mRot[2][2] = cosX; -/* -// ROLL is not supported unless anyone complains, if it needs to be added, use this format -Roll - - c 0 s - 0 1 0 --s 0 c -*/ + /* + // ROLL is not supported unless anyone complains, if it needs to be added, use this format + Roll + + c 0 s + 0 1 0 + -s 0 c + */ mLastFrameTime = theFxHelper.mFrameTime; } //-------------------------------- -void CPoly::Rotate(void) -{ - vec3_t temp[MAX_CPOLY_VERTS]; - float dif = fabs( (float)(mLastFrameTime - theFxHelper.mFrameTime) ); +void CPoly::Rotate(void) { + vec3_t temp[MAX_CPOLY_VERTS]; + float dif = fabs((float)(mLastFrameTime - theFxHelper.mFrameTime)); - if ( dif > 0.1f * mLastFrameTime ) - { + if (dif > 0.1f * mLastFrameTime) { CalcRotateMatrix(); } // Multiply our rotation matrix by each of the offset verts to get their new position - for ( int i = 0; i < mCount; i++ ) - { - VectorRotate( mOrg[i], mRot, temp[i] ); - VectorCopy( temp[i], mOrg[i] ); + for (int i = 0; i < mCount; i++) { + VectorRotate(mOrg[i], mRot, temp[i]); + VectorCopy(temp[i], mOrg[i]); } } //---------------------------- // Update //---------------------------- -bool CPoly::Update(void) -{ +bool CPoly::Update(void) { // Game pausing can cause dumb time things to happen, so kill the effect in this instance - if ( mTimeStart > theFxHelper.mTime ) - { + if (mTimeStart > theFxHelper.mTime) { return false; } // If our timestamp hasn't exired yet, we won't even consider doing any kind of motion - if ( theFxHelper.mTime > mTimeStamp ) - { + if (theFxHelper.mTime > mTimeStamp) { vec3_t mOldOrigin; - VectorCopy( mOrigin1, mOldOrigin ); + VectorCopy(mOrigin1, mOldOrigin); - if (( mTimeStart < theFxHelper.mTime ) && UpdateOrigin() == false ) - { + if ((mTimeStart < theFxHelper.mTime) && UpdateOrigin() == false) { // we are marked for death return false; } // Only rotate whilst moving - if ( !VectorCompare( mOldOrigin, mOrigin1 )) - { + if (!VectorCompare(mOldOrigin, mOrigin1)) { Rotate(); } } - if ( !Cull()) - { + if (!Cull()) { // Only update these if the thing is visible. UpdateRGB(); UpdateAlpha(); @@ -1927,32 +1626,28 @@ bool CPoly::Update(void) } //---------------------------- -void CPoly::PolyInit(void) -{ - if ( mCount < 3 ) - { +void CPoly::PolyInit(void) { + if (mCount < 3) { return; } - int i; - vec3_t org = {0.0f, 0.0f ,0.0f}; + int i; + vec3_t org = {0.0f, 0.0f, 0.0f}; // Find our midpoint - for ( i = 0; i < mCount; i++ ) - { - VectorAdd( org, mOrg[i], org ); + for (i = 0; i < mCount; i++) { + VectorAdd(org, mOrg[i], org); } - VectorScale( org, (float)(1.0f / mCount), org ); + VectorScale(org, (float)(1.0f / mCount), org); // now store our midpoint for physics purposes - VectorCopy( org, mOrigin1 ); + VectorCopy(org, mOrigin1); // Now we process the passed in points and make it so that they aren't actually the point... // rather, they are the offset from mOrigin1. - for ( i = 0; i < mCount; i++ ) - { - VectorSubtract( mOrg[i], mOrigin1, mOrg[i] ); + for (i = 0; i < mCount; i++) { + VectorSubtract(mOrg[i], mOrigin1, mOrg[i]); } CalcRotateMatrix(); @@ -1965,41 +1660,36 @@ CBezier Bezier curve line ------------------------- */ -bool CBezier::Cull( void ) -{ - vec3_t dir; +bool CBezier::Cull(void) { + vec3_t dir; - VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mOrigin1, theFxHelper.refdef->vieworg, dir); - //Check if it's in front of the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 ) - { - return false; //don't cull + // Check if it's in front of the viewer + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) >= 0) { + return false; // don't cull } - VectorSubtract( mOrigin2, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mOrigin2, theFxHelper.refdef->vieworg, dir); - //Check if it's in front of the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 ) - { + // Check if it's in front of the viewer + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) >= 0) { return false; } - VectorSubtract( mControl1, theFxHelper.refdef->vieworg, dir ); + VectorSubtract(mControl1, theFxHelper.refdef->vieworg, dir); - //Check if it's in front of the viewer - if ( (DotProduct( theFxHelper.refdef->viewaxis[0], dir )) >= 0 ) - { + // Check if it's in front of the viewer + if ((DotProduct(theFxHelper.refdef->viewaxis[0], dir)) >= 0) { return false; } - return true; //all points behind viewer + return true; // all points behind viewer } //---------------------------- -bool CBezier::Update( void ) -{ - float ftime, time2; +bool CBezier::Update(void) { + float ftime, time2; ftime = theFxHelper.mFrameTime * 0.001f; time2 = ftime * ftime * 0.5f; @@ -2011,8 +1701,7 @@ bool CBezier::Update( void ) mControl1[2] = mControl1[2] + (ftime * mControl1Vel[2]) + (time2 * mControl1Vel[2]); mControl2[2] = mControl2[2] + (ftime * mControl2Vel[2]) + (time2 * mControl2Vel[2]); - if ( Cull() == false ) - { + if (Cull() == false) { // Only update these if the thing is visible. UpdateSize(); UpdateRGB(); @@ -2024,121 +1713,113 @@ bool CBezier::Update( void ) } //---------------------------- -inline void CBezier::DrawSegment( vec3_t start, vec3_t end, float texcoord1, float texcoord2, float segPercent, float lastSegPercent ) -{ - vec3_t lineDir, cross, viewDir; - static vec3_t lastEnd[2]; - polyVert_t verts[4]; - float scaleBottom = 0.0f, scaleTop = 0.0f; +inline void CBezier::DrawSegment(vec3_t start, vec3_t end, float texcoord1, float texcoord2, float segPercent, float lastSegPercent) { + vec3_t lineDir, cross, viewDir; + static vec3_t lastEnd[2]; + polyVert_t verts[4]; + float scaleBottom = 0.0f, scaleTop = 0.0f; - VectorSubtract( end, start, lineDir ); - VectorSubtract( end, theFxHelper.refdef->vieworg, viewDir ); - CrossProduct( lineDir, viewDir, cross ); - VectorNormalize( cross ); + VectorSubtract(end, start, lineDir); + VectorSubtract(end, theFxHelper.refdef->vieworg, viewDir); + CrossProduct(lineDir, viewDir, cross); + VectorNormalize(cross); // scaleBottom is the width of the bottom edge of the quad, scaleTop is the width of the top edge scaleBottom = (mSizeStart + ((mSizeEnd - mSizeStart) * lastSegPercent)) * 0.5f; scaleTop = (mSizeStart + ((mSizeEnd - mSizeStart) * segPercent)) * 0.5f; - //Construct the oriented quad - if ( mInit ) - { - VectorCopy( lastEnd[0], verts[0].xyz ); - VectorCopy( lastEnd[1], verts[1].xyz ); - } - else - { - VectorMA( start, -scaleBottom, cross, verts[0].xyz ); - VectorMA( start, scaleBottom, cross, verts[1].xyz ); + // Construct the oriented quad + if (mInit) { + VectorCopy(lastEnd[0], verts[0].xyz); + VectorCopy(lastEnd[1], verts[1].xyz); + } else { + VectorMA(start, -scaleBottom, cross, verts[0].xyz); + VectorMA(start, scaleBottom, cross, verts[1].xyz); } verts[0].st[0] = 0.0f; verts[0].st[1] = texcoord1; - verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[0].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[0].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[0].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[0].modulate[3] = mRefEnt.shaderRGBA[3]; verts[1].st[0] = 1.0f; verts[1].st[1] = texcoord1; - verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord1 ); - verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord1 ); - verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord1 ); + verts[1].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord1); + verts[1].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord1); + verts[1].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord1); verts[1].modulate[3] = mRefEnt.shaderRGBA[3]; - if ( texcoord1 == 0.0f ) - { - for ( int k=0; k<4; k++ ) { + if (texcoord1 == 0.0f) { + for (int k = 0; k < 4; k++) { verts[0].modulate[k] = verts[1].modulate[k] = 0; } } - VectorMA( end, scaleTop, cross, verts[2].xyz ); + VectorMA(end, scaleTop, cross, verts[2].xyz); verts[2].st[0] = 1.0f; verts[2].st[1] = texcoord2; - verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[2].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[2].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[2].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[2].modulate[3] = mRefEnt.shaderRGBA[3]; - VectorMA( end, -scaleTop, cross, verts[3].xyz ); + VectorMA(end, -scaleTop, cross, verts[3].xyz); verts[3].st[0] = 0.0f; verts[3].st[1] = texcoord2; - verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * ( 1.0f - texcoord2 ); - verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * ( 1.0f - texcoord2 ); - verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * ( 1.0f - texcoord2 ); + verts[3].modulate[0] = mRefEnt.shaderRGBA[0] * (1.0f - texcoord2); + verts[3].modulate[1] = mRefEnt.shaderRGBA[1] * (1.0f - texcoord2); + verts[3].modulate[2] = mRefEnt.shaderRGBA[2] * (1.0f - texcoord2); verts[3].modulate[3] = mRefEnt.shaderRGBA[3]; - theFxHelper.AddPolyToScene( mRefEnt.customShader, 4, verts ); + theFxHelper.AddPolyToScene(mRefEnt.customShader, 4, verts); - VectorCopy( verts[2].xyz, lastEnd[1] ); - VectorCopy( verts[3].xyz, lastEnd[0] ); + VectorCopy(verts[2].xyz, lastEnd[1]); + VectorCopy(verts[3].xyz, lastEnd[0]); mInit = true; } -const float BEZIER_RESOLUTION = 16.0f; +const float BEZIER_RESOLUTION = 16.0f; //---------------------------- -void CBezier::Draw( void ) -{ - vec3_t pos, old_pos; - float mu, mum1; - float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; - int i = 0; +void CBezier::Draw(void) { + vec3_t pos, old_pos; + float mu, mum1; + float incr = 1.0f / BEZIER_RESOLUTION, tex = 1.0f, tc1, tc2; + int i = 0; - VectorCopy( mOrigin1, old_pos ); + VectorCopy(mOrigin1, old_pos); - mInit = false; //Signify a new batch for vert gluing + mInit = false; // Signify a new batch for vert gluing float mum13, mu3, group1, group2; tc1 = 0.0f; - for ( mu = incr; mu <= 1.0f; mu += incr) - { - //Four point curve - mum1 = 1 - mu; - mum13 = mum1 * mum1 * mum1; - mu3 = mu * mu * mu; - group1 = 3 * mu * mum1 * mum1; - group2 = 3 * mu * mu *mum1; - - for ( i = 0; i < 3; i++ ) - { + for (mu = incr; mu <= 1.0f; mu += incr) { + // Four point curve + mum1 = 1 - mu; + mum13 = mum1 * mum1 * mum1; + mu3 = mu * mu * mu; + group1 = 3 * mu * mum1 * mum1; + group2 = 3 * mu * mu * mum1; + + for (i = 0; i < 3; i++) { pos[i] = mum13 * mOrigin1[i] + group1 * mControl1[i] + group2 * mControl2[i] + mu3 * mOrigin2[i]; } tc2 = mu * tex; - //Draw it - DrawSegment( old_pos, pos, tc1, tc2, mu, mu - incr ); + // Draw it + DrawSegment(old_pos, pos, tc1, tc2, mu, mu - incr); - VectorCopy( pos, old_pos ); + VectorCopy(pos, old_pos); tc1 = tc2; } drawnFx++; @@ -2153,10 +1834,8 @@ Full screen flash */ //---------------------------- -bool CFlash::Update( void ) -{ - if ( UpdateOrigin() == false ) - { +bool CFlash::Update(void) { + if (UpdateOrigin() == false) { // we are marked for death return false; } @@ -2170,33 +1849,31 @@ bool CFlash::Update( void ) return true; } -bool FX_WorldToScreen(vec3_t worldCoord, float *x, float *y) -{ - int xcenter, ycenter; - vec3_t local, transformed; - vec3_t vfwd, vright, vup; +bool FX_WorldToScreen(vec3_t worldCoord, float *x, float *y) { + int xcenter, ycenter; + vec3_t local, transformed; + vec3_t vfwd, vright, vup; - //NOTE: did it this way because most draw functions expect virtual 640x480 coords + // NOTE: did it this way because most draw functions expect virtual 640x480 coords // and adjust them for current resolution - xcenter = 640 / 2;//gives screen coords in virtual 640x480, to be adjusted when drawn - ycenter = 480 / 2;//gives screen coords in virtual 640x480, to be adjusted when drawn + xcenter = 640 / 2; // gives screen coords in virtual 640x480, to be adjusted when drawn + ycenter = 480 / 2; // gives screen coords in virtual 640x480, to be adjusted when drawn - VectorSubtract (worldCoord, theFxHelper.refdef->vieworg, local); + VectorSubtract(worldCoord, theFxHelper.refdef->vieworg, local); - AngleVectors (theFxHelper.refdef->viewangles, vfwd, vright, vup); + AngleVectors(theFxHelper.refdef->viewangles, vfwd, vright, vup); - transformed[0] = DotProduct(local,vright); - transformed[1] = DotProduct(local,vup); - transformed[2] = DotProduct(local,vfwd); + transformed[0] = DotProduct(local, vright); + transformed[1] = DotProduct(local, vup); + transformed[2] = DotProduct(local, vfwd); // Make sure Z is not negative. - if(transformed[2] < 0.01) - { + if (transformed[2] < 0.01) { return false; } // Simple convert to screen coords. - float xzi = xcenter / transformed[2] * (90.0/theFxHelper.refdef->fov_x); - float yzi = ycenter / transformed[2] * (90.0/theFxHelper.refdef->fov_y); + float xzi = xcenter / transformed[2] * (90.0 / theFxHelper.refdef->fov_x); + float yzi = ycenter / transformed[2] * (90.0 / theFxHelper.refdef->fov_y); *x = (xcenter + xzi * transformed[0]); *y = (ycenter - yzi * transformed[1]); @@ -2205,57 +1882,49 @@ bool FX_WorldToScreen(vec3_t worldCoord, float *x, float *y) } //---------------------------- -void CFlash::Init( void ) -{ +void CFlash::Init(void) { // 10/19/01 kef -- maybe we want to do something different here for localized flashes, but right - //now I want to be sure that whatever RGB changes occur to a non-localized flash will also occur - //to a localized flash (so I'll have the same initial RGBA values for both...I need them sync'd for an effect) + // now I want to be sure that whatever RGB changes occur to a non-localized flash will also occur + // to a localized flash (so I'll have the same initial RGBA values for both...I need them sync'd for an effect) - vec3_t dif; - float mod = 1.0f, dis = 0.0f, maxRange = 900; + vec3_t dif; + float mod = 1.0f, dis = 0.0f, maxRange = 900; - VectorSubtract( mOrigin1, theFxHelper.refdef->vieworg, dif ); - dis = VectorNormalize( dif ); + VectorSubtract(mOrigin1, theFxHelper.refdef->vieworg, dif); + dis = VectorNormalize(dif); - mod = DotProduct( dif, theFxHelper.refdef->viewaxis[0] ); + mod = DotProduct(dif, theFxHelper.refdef->viewaxis[0]); - if ( dis > maxRange || ( mod < 0.5f && dis > 100 )) - { + if (dis > maxRange || (mod < 0.5f && dis > 100)) { mod = 0.0f; - } - else if ( mod < 0.5f && dis <= 100 ) - { + } else if (mod < 0.5f && dis <= 100) { mod += 1.1f; } mod *= (1.0f - ((dis * dis) / (maxRange * maxRange))); - VectorScale( mRGBStart, mod, mRGBStart ); - VectorScale( mRGBEnd, mod, mRGBEnd ); + VectorScale(mRGBStart, mod, mRGBStart); + VectorScale(mRGBEnd, mod, mRGBEnd); - if ( mFlags & FX_LOCALIZED_FLASH ) - { + if (mFlags & FX_LOCALIZED_FLASH) { FX_WorldToScreen(mOrigin1, &mScreenX, &mScreenY); // modify size of localized flash based on distance to effect (but not orientation) - if (dis > 100 && dis < maxRange) - { + if (dis > 100 && dis < maxRange) { mRadiusModifier = (1.0f - ((dis * dis) / (maxRange * maxRange))); } } } //---------------------------- -void CFlash::Draw( void ) -{ - // Interestingly, if znear is set > than this, then the flash - // doesn't appear at all. - const float FLASH_DISTANCE_FROM_VIEWER = 12.0f; +void CFlash::Draw(void) { + // Interestingly, if znear is set > than this, then the flash + // doesn't appear at all. + const float FLASH_DISTANCE_FROM_VIEWER = 12.0f; mRefEnt.reType = RT_SPRITE; - if ( mFlags & FX_LOCALIZED_FLASH ) - { - vec4_t color; + if (mFlags & FX_LOCALIZED_FLASH) { + vec4_t color; color[0] = mRefEnt.shaderRGBA[0] / 255.0; color[1] = mRefEnt.shaderRGBA[1] / 255.0; @@ -2264,28 +1933,24 @@ void CFlash::Draw( void ) // add this 2D effect to the proper list. it will get drawn after the trap->RenderScene call theFxScheduler.Add2DEffect(mScreenX, mScreenY, mRefEnt.radius, mRefEnt.radius, color, mRefEnt.customShader); - } - else - { - VectorCopy( theFxHelper.refdef->vieworg, mRefEnt.origin ); - VectorMA( mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, theFxHelper.refdef->viewaxis[0], mRefEnt.origin ); + } else { + VectorCopy(theFxHelper.refdef->vieworg, mRefEnt.origin); + VectorMA(mRefEnt.origin, FLASH_DISTANCE_FROM_VIEWER, theFxHelper.refdef->viewaxis[0], mRefEnt.origin); - // This is assuming that the screen is wider than it is tall. - mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan (DEG2RAD (theFxHelper.refdef->fov_x * 0.5f)); + // This is assuming that the screen is wider than it is tall. + mRefEnt.radius = FLASH_DISTANCE_FROM_VIEWER * tan(DEG2RAD(theFxHelper.refdef->fov_x * 0.5f)); - theFxHelper.AddFxToScene( &mRefEnt ); + theFxHelper.AddFxToScene(&mRefEnt); } drawnFx++; } -void FX_AddPrimitive( CEffect **pEffect, int killTime ); -void FX_FeedTrail(effectTrailArgStruct_t *a) -{ +void FX_AddPrimitive(CEffect **pEffect, int killTime); +void FX_FeedTrail(effectTrailArgStruct_t *a) { CTrail *fx = new CTrail; int i = 0; - while (i < 4) - { + while (i < 4) { VectorCopy(a->mVerts[i].origin, fx->mVerts[i].origin); VectorCopy(a->mVerts[i].rgb, fx->mVerts[i].rgb); VectorCopy(a->mVerts[i].destrgb, fx->mVerts[i].destrgb); diff --git a/codemp/client/FxScheduler.cpp b/codemp/client/FxScheduler.cpp index 15a3ecce5c..b19847ff08 100644 --- a/codemp/client/FxScheduler.cpp +++ b/codemp/client/FxScheduler.cpp @@ -29,145 +29,123 @@ along with this program; if not, see . #include #include -CFxScheduler theFxScheduler; +CFxScheduler theFxScheduler; //----------------------------------------------------------- -CMediaHandles &CMediaHandles::operator=(const CMediaHandles &that ) -{ +CMediaHandles &CMediaHandles::operator=(const CMediaHandles &that) { mMediaList.clear(); - for ( size_t i = 0; i < that.mMediaList.size(); i++ ) - { - mMediaList.push_back( that.mMediaList[i] ); + for (size_t i = 0; i < that.mMediaList.size(); i++) { + mMediaList.push_back(that.mMediaList[i]); } return *this; } //------------------------------------------------------ -CFxScheduler::CFxScheduler() -{ +CFxScheduler::CFxScheduler() { mNextFree2DEffect = 0; - memset( &mEffectTemplates, 0, sizeof( mEffectTemplates )); - memset( &mLoopedEffectArray, 0, sizeof( mLoopedEffectArray )); + memset(&mEffectTemplates, 0, sizeof(mEffectTemplates)); + memset(&mLoopedEffectArray, 0, sizeof(mLoopedEffectArray)); } -int CFxScheduler::ScheduleLoopedEffect( int id, int boltInfo, CGhoul2Info_v *ghoul2, bool isPortal, int iLoopTime, bool isRelative ) -{ +int CFxScheduler::ScheduleLoopedEffect(int id, int boltInfo, CGhoul2Info_v *ghoul2, bool isPortal, int iLoopTime, bool isRelative) { int i; assert(id); - assert(boltInfo!=-1); + assert(boltInfo != -1); - for (i=0;i> ENTITY_SHIFT ) & ENTITY_AND; + for (i = 0; i < MAX_LOOPED_FX; i++) { + if (mLoopedEffectArray[i].mId && mLoopedEffectArray[i].mNextTime < theFxHelper.mTime) { + const int entNum = (mLoopedEffectArray[i].mBoltInfo >> ENTITY_SHIFT) & ENTITY_AND; // Find out where the entity currently is - TCGVectorData *data = (TCGVectorData*)cl.mSharedMemory; + TCGVectorData *data = (TCGVectorData *)cl.mSharedMemory; data->mEntityNum = entNum; CGVM_GetLerpOrigin(); - PlayEffect( mLoopedEffectArray[i].mId, data->mPoint, 0, mLoopedEffectArray[i].mBoltInfo, mLoopedEffectArray[i].mGhoul2, -1, mLoopedEffectArray[i].mPortalEffect, false, mLoopedEffectArray[i].mIsRelative ); //very important to send FALSE to not recursively add me! + PlayEffect(mLoopedEffectArray[i].mId, data->mPoint, 0, mLoopedEffectArray[i].mBoltInfo, mLoopedEffectArray[i].mGhoul2, -1, + mLoopedEffectArray[i].mPortalEffect, false, + mLoopedEffectArray[i].mIsRelative); // very important to send FALSE to not recursively add me! mLoopedEffectArray[i].mNextTime = theFxHelper.mTime + mEffectTemplates[mLoopedEffectArray[i].mId].mRepeatDelay; - if (mLoopedEffectArray[i].mLoopStopTime && mLoopedEffectArray[i].mLoopStopTime < theFxHelper.mTime) //time's up - {//kill this entry - memset( &mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i]) ); + if (mLoopedEffectArray[i].mLoopStopTime && mLoopedEffectArray[i].mLoopStopTime < theFxHelper.mTime) // time's up + { // kill this entry + memset(&mLoopedEffectArray[i], 0, sizeof(mLoopedEffectArray[i])); } } } - } //----------------------------------------------------------- -SEffectTemplate &SEffectTemplate::operator=(const SEffectTemplate &that) -{ +SEffectTemplate &SEffectTemplate::operator=(const SEffectTemplate &that) { mCopy = true; - strcpy( mEffectName, that.mEffectName ); + strcpy(mEffectName, that.mEffectName); mPrimitiveCount = that.mPrimitiveCount; - for( int i = 0; i < mPrimitiveCount; i++ ) - { + for (int i = 0; i < mPrimitiveCount; i++) { mPrimitives[i] = new CPrimitiveTemplate; *(mPrimitives[i]) = *(that.mPrimitives[i]); // Mark use as a copy so that we know that we should be chucked when used up @@ -187,40 +165,33 @@ SEffectTemplate &SEffectTemplate::operator=(const SEffectTemplate &that) // None // //------------------------------------------------------ -void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) -{ - int i, j; - TScheduledEffect::iterator itr, next; +void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= 0*/) { + int i, j; + TScheduledEffect::iterator itr, next; // Ditch any scheduled effects itr = mFxSchedule.begin(); - while ( itr != mFxSchedule.end() ) - { + while (itr != mFxSchedule.end()) { next = itr; ++next; - mScheduledEffectsPool.Free (*itr); + mScheduledEffectsPool.Free(*itr); mFxSchedule.erase(itr); itr = next; } - if (bRemoveTemplates) - { + if (bRemoveTemplates) { // Ditch any effect templates - for ( i = 1; i < FX_MAX_EFFECTS; i++ ) - { - if ( i == idToPreserve) - { + for (i = 1; i < FX_MAX_EFFECTS; i++) { + if (i == idToPreserve) { continue; } - if ( mEffectTemplates[i].mInUse ) - { + if (mEffectTemplates[i].mInUse) { // Ditch the primitives - for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) - { + for (j = 0; j < mEffectTemplates[i].mPrimitiveCount; j++) { delete mEffectTemplates[i].mPrimitives[j]; } } @@ -228,21 +199,16 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= mEffectTemplates[i].mInUse = false; } - if (idToPreserve == 0) - { + if (idToPreserve == 0) { mEffectIDs.clear(); - } - else - { + } else { // Clear the effect names, but first get the name of the effect to preserve, // and restore it after clearing. std::string str; TEffectID::iterator iter; - for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) - { - if ((*iter).second == idToPreserve) - { + for (iter = mEffectIDs.begin(); iter != mEffectIDs.end(); ++iter) { + if ((*iter).second == idToPreserve) { str = (*iter).first; break; } @@ -266,8 +232,7 @@ void CFxScheduler::Clean(bool bRemoveTemplates /*= true*/, int idToPreserve /*= // Return: // int handle to the effect //------------------------------------------------------ -int CFxScheduler::RegisterEffect( const char *file, bool bHasCorrectPath /*= false*/ ) -{ +int CFxScheduler::RegisterEffect(const char *file, bool bHasCorrectPath /*= false*/) { // Dealing with file names: // File names can come from two places - the editor, in which case we should use the given // path as is, and the effect file, in which case we should add the correct path and extension. @@ -276,7 +241,7 @@ int CFxScheduler::RegisterEffect( const char *file, bool bHasCorrectPath /*= fal char sfile[MAX_QPATH]; - COM_StripExtension( file, sfile, sizeof( sfile ) ); + COM_StripExtension(file, sfile, sizeof(sfile)); std::string s = sfile; std::transform(s.begin(), s.end(), s.begin(), ::tolower); @@ -286,39 +251,36 @@ int CFxScheduler::RegisterEffect( const char *file, bool bHasCorrectPath /*= fal // see if the specified file is already registered. If it is, just return the id of that file TEffectID::iterator itr; - itr = mEffectIDs.find( sfile ); + itr = mEffectIDs.find(sfile); - if ( itr != mEffectIDs.end() ) - { + if (itr != mEffectIDs.end()) { return (*itr).second; } - CGenericParser2 parser; - int len = 0; - fileHandle_t fh; - char data[65536]; - char *bufParse = 0; + CGenericParser2 parser; + int len = 0; + fileHandle_t fh; + char data[65536]; + char *bufParse = 0; // if our file doesn't have an extension, add one std::string finalFilename = file; std::string effectsSubstr = finalFilename.substr(0, 7); - if (finalFilename.find('.') == std::string::npos) - { + if (finalFilename.find('.') == std::string::npos) { // didn't find an extension so add one finalFilename += ".efx"; } // kef - grr. this angers me. every filename everywhere should start from the base dir - if (effectsSubstr.compare("effects") != 0) - { - //theFxHelper.Print("Hey!!! '%s' should be pathed from the base directory!!!\n", finalFilename.c_str()); + if (effectsSubstr.compare("effects") != 0) { + // theFxHelper.Print("Hey!!! '%s' should be pathed from the base directory!!!\n", finalFilename.c_str()); std::string strTemp = finalFilename; finalFilename = "effects/"; finalFilename += strTemp; } - len = theFxHelper.OpenFile( finalFilename.c_str(), &fh, FS_READ ); + len = theFxHelper.OpenFile(finalFilename.c_str(), &fh, FS_READ); /* if (bHasCorrectPath) @@ -334,42 +296,37 @@ int CFxScheduler::RegisterEffect( const char *file, bool bHasCorrectPath /*= fal len = theFxHelper.OpenFile( pfile, &fh, FS_READ ); */ - - if ( len < 0 ) - { - theFxHelper.Print( "Effect file load failed: %s\n", finalFilename.c_str() ); + if (len < 0) { + theFxHelper.Print("Effect file load failed: %s\n", finalFilename.c_str()); return 0; } - if (len == 0) - { - theFxHelper.Print( "INVALID Effect file: %s\n", finalFilename.c_str() ); - theFxHelper.CloseFile( fh ); + if (len == 0) { + theFxHelper.Print("INVALID Effect file: %s\n", finalFilename.c_str()); + theFxHelper.CloseFile(fh); return 0; } // If we'll overflow our buffer, bail out--not a particularly elegant solution - if ((unsigned)len >= sizeof(data) - 1 ) - { - theFxHelper.CloseFile( fh ); + if ((unsigned)len >= sizeof(data) - 1) { + theFxHelper.CloseFile(fh); return 0; } // Get the goods and ensure Null termination - theFxHelper.ReadFile( data, len, fh ); + theFxHelper.ReadFile(data, len, fh); data[len] = '\0'; bufParse = data; // Let the generic parser process the whole file - parser.Parse( &bufParse ); + parser.Parse(&bufParse); - theFxHelper.CloseFile( fh ); + theFxHelper.CloseFile(fh); // Lets convert the effect file into something that we can work with - return ParseEffect( sfile, parser.GetBaseParseGroup() ); + return ParseEffect(sfile, parser.GetBaseParseGroup()); } - //------------------------------------------------------ // ParseEffect // Starts at ground zero, using each group header to @@ -384,76 +341,62 @@ int CFxScheduler::RegisterEffect( const char *file, bool bHasCorrectPath /*= fal // int handle of the effect //------------------------------------------------------ -struct primitiveType_s { const char *name; EPrimType type; } primitiveTypes[] = { - { "particle", Particle }, - { "line", Line }, - { "tail", Tail }, - { "sound", Sound }, - { "cylinder", Cylinder }, - { "electricity", Electricity }, - { "emitter", Emitter }, - { "decal", Decal }, - { "orientedparticle", OrientedParticle }, - { "fxrunner", FxRunner }, - { "light", Light }, - { "cameraShake", CameraShake }, - { "flash", ScreenFlash }, +struct primitiveType_s { + const char *name; + EPrimType type; +} primitiveTypes[] = { + {"particle", Particle}, {"line", Line}, {"tail", Tail}, + {"sound", Sound}, {"cylinder", Cylinder}, {"electricity", Electricity}, + {"emitter", Emitter}, {"decal", Decal}, {"orientedparticle", OrientedParticle}, + {"fxrunner", FxRunner}, {"light", Light}, {"cameraShake", CameraShake}, + {"flash", ScreenFlash}, }; -static const size_t numPrimitiveTypes = ARRAY_LEN( primitiveTypes ); +static const size_t numPrimitiveTypes = ARRAY_LEN(primitiveTypes); -int CFxScheduler::ParseEffect( const char *file, CGPGroup *base ) -{ - CGPGroup *primitiveGroup; - CPrimitiveTemplate *prim; - const char *grpName; - SEffectTemplate *effect = 0; - EPrimType type; - int handle; - CGPValue *pair; +int CFxScheduler::ParseEffect(const char *file, CGPGroup *base) { + CGPGroup *primitiveGroup; + CPrimitiveTemplate *prim; + const char *grpName; + SEffectTemplate *effect = 0; + EPrimType type; + int handle; + CGPValue *pair; - effect = GetNewEffectTemplate( &handle, file ); + effect = GetNewEffectTemplate(&handle, file); - if ( !handle || !effect ) - { + if (!handle || !effect) { // failure return 0; } - if ((pair = base->GetPairs())!=0) - { + if ((pair = base->GetPairs()) != 0) { grpName = pair->GetName(); - if ( !Q_stricmp( grpName, "repeatDelay" )) - { + if (!Q_stricmp(grpName, "repeatDelay")) { effect->mRepeatDelay = atoi(pair->GetTopValue()); - } - else - {//unknown - + } else { // unknown } } primitiveGroup = base->GetSubGroups(); - while ( primitiveGroup ) - { + while (primitiveGroup) { grpName = primitiveGroup->GetName(); type = None; - for ( size_t i=0; imType = type; - prim->ParsePrimitive( primitiveGroup ); + prim->ParsePrimitive(primitiveGroup); // Add our primitive template to the effect list - AddPrimitiveToEffect( effect, prim ); + AddPrimitiveToEffect(effect, prim); } primitiveGroup = (CGPGroup *)primitiveGroup->GetNext(); @@ -462,7 +405,6 @@ int CFxScheduler::ParseEffect( const char *file, CGPGroup *base ) return handle; } - //------------------------------------------------------ // AddPrimitiveToEffect // Takes a primitive and attaches it to the effect. @@ -474,16 +416,12 @@ int CFxScheduler::ParseEffect( const char *file, CGPGroup *base ) // Return: // None //------------------------------------------------------ -void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate *prim ) -{ +void CFxScheduler::AddPrimitiveToEffect(SEffectTemplate *fx, CPrimitiveTemplate *prim) { int ct = fx->mPrimitiveCount; - if ( ct >= FX_MAX_EFFECT_COMPONENTS ) - { - theFxHelper.Print( "FxScheduler: Error--too many primitives in an effect\n" ); - } - else - { + if (ct >= FX_MAX_EFFECT_COMPONENTS) { + theFxHelper.Print("FxScheduler: Error--too many primitives in an effect\n"); + } else { fx->mPrimitives[ct] = prim; fx->mPrimitiveCount++; } @@ -501,25 +439,21 @@ void CFxScheduler::AddPrimitiveToEffect( SEffectTemplate *fx, CPrimitiveTemplate // Return: // the id of the added effect template //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) -{ +SEffectTemplate *CFxScheduler::GetNewEffectTemplate(int *id, const char *file) { SEffectTemplate *effect; // wanted zero to be a bogus effect ID, so we just skip it. - for ( int i = 1; i < FX_MAX_EFFECTS; i++ ) - { + for (int i = 1; i < FX_MAX_EFFECTS; i++) { effect = &mEffectTemplates[i]; - if ( !effect->mInUse ) - { + if (!effect->mInUse) { *id = i; - memset( effect, 0, sizeof( SEffectTemplate )); + memset(effect, 0, sizeof(SEffectTemplate)); // If we are a copy, we really won't have a name that we care about saving for later - if ( file ) - { + if (file) { mEffectIDs[file] = i; - strcpy( effect->mEffectName, file ); + strcpy(effect->mEffectName, file); } effect->mInUse = true; @@ -528,7 +462,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) } } - theFxHelper.Print( "FxScheduler: Error--reached max effects\n" ); + theFxHelper.Print("FxScheduler: Error--reached max effects\n"); *id = 0; return 0; } @@ -546,10 +480,7 @@ SEffectTemplate *CFxScheduler::GetNewEffectTemplate( int *id, const char *file ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) -{ - return ( GetEffectCopy( mEffectIDs[file], newHandle ) ); -} +SEffectTemplate *CFxScheduler::GetEffectCopy(const char *file, int *newHandle) { return (GetEffectCopy(mEffectIDs[file], newHandle)); } //------------------------------------------------------ // GetEffectCopy @@ -564,21 +495,18 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( const char *file, int *newHandle ) // Return: // the pointer to the copy //------------------------------------------------------ -SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) -{ - if ( fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS) - { +SEffectTemplate *CFxScheduler::GetEffectCopy(int fxHandle, int *newHandle) { + if (fxHandle < 1 || fxHandle >= FX_MAX_EFFECTS) { // Didn't even request a valid effect to copy!!! - theFxHelper.Print( "FxScheduler: Bad effect file copy request: id = %d\n", fxHandle ); + theFxHelper.Print("FxScheduler: Bad effect file copy request: id = %d\n", fxHandle); *newHandle = 0; return 0; } - if (!mEffectTemplates[fxHandle].mInUse ) - { + if (!mEffectTemplates[fxHandle].mInUse) { // Didn't even request a valid effect to copy!!! - theFxHelper.Print( "FxScheduler: Bad effect file copy request: id %d not inuse\n", fxHandle ); + theFxHelper.Print("FxScheduler: Bad effect file copy request: id %d not inuse\n", fxHandle); *newHandle = 0; return 0; @@ -586,17 +514,15 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) #ifdef _DEBUG // never get a copy when time is frozen - if ( fx_freeze->integer ) - { + if (fx_freeze->integer) { return 0; } #endif // Copies shouldn't have names, otherwise they could trash our stl map used for getting ID from name - SEffectTemplate *copy = GetNewEffectTemplate( newHandle, NULL ); + SEffectTemplate *copy = GetNewEffectTemplate(newHandle, NULL); - if ( copy && *newHandle ) - { + if (copy && *newHandle) { // do the effect copy and mark us as what we are *copy = mEffectTemplates[fxHandle]; copy->mCopy = true; @@ -621,17 +547,13 @@ SEffectTemplate *CFxScheduler::GetEffectCopy( int fxHandle, int *newHandle ) // Return: // the pointer to the desired primitive //------------------------------------------------------ -CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, const char *componentName ) -{ - if ( !effectCopy || !effectCopy->mInUse ) - { +CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy(SEffectTemplate *effectCopy, const char *componentName) { + if (!effectCopy || !effectCopy->mInUse) { return NULL; } - for ( int i = 0; i < effectCopy->mPrimitiveCount; i++ ) - { - if ( !Q_stricmp( effectCopy->mPrimitives[i]->mName, componentName )) - { + for (int i = 0; i < effectCopy->mPrimitiveCount; i++) { + if (!Q_stricmp(effectCopy->mPrimitives[i]->mName, componentName)) { // we found a match, so return it return effectCopy->mPrimitives[i]; } @@ -641,38 +563,31 @@ CPrimitiveTemplate *CFxScheduler::GetPrimitiveCopy( SEffectTemplate *effectCopy, return NULL; } +void CFxScheduler::MaterialImpact(trace_t *tr, CEffect *effect) { + /* EMatImpactEffect matImpactEffect = effect->GetMatImpactFX(); + int impactParm = effect->GetMatImpactParm(); -void CFxScheduler::MaterialImpact(trace_t *tr, CEffect *effect) -{ -/* EMatImpactEffect matImpactEffect = effect->GetMatImpactFX(); - int impactParm = effect->GetMatImpactParm(); - - if (matImpactEffect == MATIMPACTFX_NONE) - { - return; - } - else if (matImpactEffect == MATIMPACTFX_SHELLSOUND) - { - // only want to play this for the first impact - effect->SetMatImpactFX(MATIMPACTFX_NONE); - - int material = tr->surfaceFlags & MATERIAL_MASK; - const char *ammoName = CWeaponSystem::GetAmmoName(impactParm); - - if(ammoName && materials[material].HasShellSound(ammoName)) + if (matImpactEffect == MATIMPACTFX_NONE) { - theFxHelper.PlaySound( tr->endpos, ENTITYNUM_NONE, CHAN_AUTO, materials[material].GetShellSoundHandle(ammoName) ); + return; } - }*/ -} + else if (matImpactEffect == MATIMPACTFX_SHELLSOUND) + { + // only want to play this for the first impact + effect->SetMatImpactFX(MATIMPACTFX_NONE); + int material = tr->surfaceFlags & MATERIAL_MASK; + const char *ammoName = CWeaponSystem::GetAmmoName(impactParm); -//------------------------------------------------------ -static void ReportPlayEffectError(int id) -{ - theFxHelper.Print( "CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id ); + if(ammoName && materials[material].HasShellSound(ammoName)) + { + theFxHelper.PlaySound( tr->endpos, ENTITYNUM_NONE, CHAN_AUTO, materials[material].GetShellSoundHandle(ammoName) ); + } + }*/ } +//------------------------------------------------------ +static void ReportPlayEffectError(int id) { theFxHelper.Print("CFxScheduler::PlayEffect called with invalid effect ID: %i\n", id); } //------------------------------------------------------ // PlayEffect @@ -709,18 +624,16 @@ static void ReportPlayEffectError(int id) // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward, int vol, int rad, bool isPortal ) -{ - matrix3_t axis; +void CFxScheduler::PlayEffect(int id, vec3_t origin, vec3_t forward, int vol, int rad, bool isPortal) { + matrix3_t axis; // Take the forward vector and create two arbitrary but perpendicular vectors - VectorCopy( forward, axis[0] ); - MakeNormalVectors( forward, axis[1], axis[2] ); + VectorCopy(forward, axis[0]); + MakeNormalVectors(forward, axis[1], axis[2]); - PlayEffect( id, origin, axis, -1, 0, -1, vol, rad, isPortal ); + PlayEffect(id, origin, axis, -1, 0, -1, vol, rad, isPortal); } - //------------------------------------------------------ // PlayEffect // Handles scheduling an effect so all the components @@ -734,43 +647,37 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, vec3_t forward, int vol, i // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, matrix3_t axis, const int boltInfo, CGhoul2Info_v *ghoul2, - int fxParm /*-1*/, int vol, int rad, int iLoopTime, bool isRelative ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, matrix3_t axis, const int boltInfo, CGhoul2Info_v *ghoul2, int fxParm /*-1*/, int vol, int rad, + int iLoopTime, bool isRelative) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof( sfile ) ); + COM_StripExtension(file, sfile, sizeof(sfile)); #ifndef FINAL_BUILD - if ( mEffectIDs[sfile] == 0 ) - { - theFxHelper.Print( "CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile ); + if (mEffectIDs[sfile] == 0) { + theFxHelper.Print("CFxScheduler::PlayEffect unregistered/non-existent effect: %s\n", sfile); return; } #endif - PlayEffect( mEffectIDs[sfile], origin, axis, boltInfo, ghoul2, fxParm, vol, rad, qfalse, iLoopTime, isRelative ); + PlayEffect(mEffectIDs[sfile], origin, axis, boltInfo, ghoul2, fxParm, vol, rad, qfalse, iLoopTime, isRelative); } -int totalPrimitives = 0; -int totalEffects = 0; +int totalPrimitives = 0; +int totalEffects = 0; -void GetRGB_Colors( CPrimitiveTemplate *fx, vec3_t outStartRGB, vec3_t outEndRGB ) -{ - float percent; +void GetRGB_Colors(CPrimitiveTemplate *fx, vec3_t outStartRGB, vec3_t outEndRGB) { + float percent; - if ( fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP ) - { + if (fx->mSpawnFlags & FX_RGB_COMPONENT_INTERP) { percent = flrand(0.0f, 1.0f); - VectorSet( outStartRGB, fx->mRedStart.GetVal(percent), fx->mGreenStart.GetVal(percent), fx->mBlueStart.GetVal(percent) ); - VectorSet( outEndRGB, fx->mRedEnd.GetVal(percent), fx->mGreenEnd.GetVal(percent), fx->mBlueEnd.GetVal(percent) ); - } - else - { - VectorSet( outStartRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal() ); - VectorSet( outEndRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal() ); + VectorSet(outStartRGB, fx->mRedStart.GetVal(percent), fx->mGreenStart.GetVal(percent), fx->mBlueStart.GetVal(percent)); + VectorSet(outEndRGB, fx->mRedEnd.GetVal(percent), fx->mGreenEnd.GetVal(percent), fx->mBlueEnd.GetVal(percent)); + } else { + VectorSet(outStartRGB, fx->mRedStart.GetVal(), fx->mGreenStart.GetVal(), fx->mBlueStart.GetVal()); + VectorSet(outEndRGB, fx->mRedEnd.GetVal(), fx->mGreenEnd.GetVal(), fx->mBlueEnd.GetVal()); } } @@ -787,17 +694,16 @@ void GetRGB_Colors( CPrimitiveTemplate *fx, vec3_t outStartRGB, vec3_t outEndRGB // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int boltInfo, CGhoul2Info_v *ghoul2, int fxParm /*-1*/, int vol, int rad, bool isPortal/*false*/, int iLoopTime/*0*/, bool isRelative ) -{ - SEffectTemplate *fx; - CPrimitiveTemplate *prim; - int i = 0; - int count = 0, delay = 0; - float factor = 0.0f, fxscale; - bool forceScheduling = false; - - if ( id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse ) - { +void CFxScheduler::PlayEffect(int id, vec3_t origin, matrix3_t axis, const int boltInfo, CGhoul2Info_v *ghoul2, int fxParm /*-1*/, int vol, int rad, + bool isPortal /*false*/, int iLoopTime /*0*/, bool isRelative) { + SEffectTemplate *fx; + CPrimitiveTemplate *prim; + int i = 0; + int count = 0, delay = 0; + float factor = 0.0f, fxscale; + bool forceScheduling = false; + + if (id < 1 || id >= FX_MAX_EFFECTS || !mEffectTemplates[id].mInUse) { // Now you've done it! ReportPlayEffectError(id); return; @@ -805,27 +711,25 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int #ifdef _DEBUG // Don't bother scheduling the effect if the system is currently frozen - if ( fx_freeze->integer ) - { + if (fx_freeze->integer) { return; } #endif - int modelNum = 0, boltNum = -1; - int entityNum = -1; + int modelNum = 0, boltNum = -1; + int entityNum = -1; - if ( boltInfo > 0 ) - { + if (boltInfo > 0) { // extract the wraith ID from the bolt info - modelNum = ( boltInfo >> MODEL_SHIFT ) & MODEL_AND; - boltNum = ( boltInfo >> BOLT_SHIFT ) & BOLT_AND; - entityNum = ( boltInfo >> ENTITY_SHIFT ) & ENTITY_AND; + modelNum = (boltInfo >> MODEL_SHIFT) & MODEL_AND; + boltNum = (boltInfo >> BOLT_SHIFT) & BOLT_AND; + entityNum = (boltInfo >> ENTITY_SHIFT) & ENTITY_AND; // We always force ghoul bolted objects to be scheduled so that they don't play right away. forceScheduling = true; - if (iLoopTime)//0 = not looping, 1 for infinite, else duration - {//store off the id to reschedule every frame + if (iLoopTime) // 0 = not looping, 1 for infinite, else duration + { // store off the id to reschedule every frame ScheduleLoopedEffect(id, boltInfo, ghoul2, !!isPortal, iLoopTime, isRelative); } } @@ -834,24 +738,21 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int fx = &mEffectTemplates[id]; #ifndef FINAL_BUILD - if ( fx_debug->integer == 2 ) - { - Com_Printf( "> %s\n", fx->mEffectName); + if (fx_debug->integer == 2) { + Com_Printf("> %s\n", fx->mEffectName); } #endif // Loop through the primitives and schedule each bit - for ( i = 0; i < fx->mPrimitiveCount; i++ ) - { + for (i = 0; i < fx->mPrimitiveCount; i++) { totalPrimitives++; prim = fx->mPrimitives[i]; prim->mSoundRadius = rad; prim->mSoundVolume = vol; - if ( prim->mCullRange ) - { - if ( DistanceSquared( origin, theFxHelper.refdef->vieworg ) > prim->mCullRange ) // cullrange gets squared on load + if (prim->mCullRange) { + if (DistanceSquared(origin, theFxHelper.refdef->vieworg) > prim->mCullRange) // cullrange gets squared on load { // is too far away continue; @@ -860,75 +761,57 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int // Scale the particles based on the countscale factor. Never, ever scale the particles upwards, however. fxscale = fx_countScale->value; - if (fxscale > 1.0) - { + if (fxscale > 1.0) { fxscale = 1.0; } // Only use scalability if there is a range // Temp fix until I have time to reweight all the scalability files - if(fabsf(prim->mSpawnCount.GetMax() - prim->mSpawnCount.GetMin()) > 1.0f) - { + if (fabsf(prim->mSpawnCount.GetMax() - prim->mSpawnCount.GetMin()) > 1.0f) { count = Round(prim->mSpawnCount.GetVal() * fxscale); - } - else - { + } else { count = Round(prim->mSpawnCount.GetVal()); } // Make sure we have at least one particle after scaling - if(prim->mSpawnCount.GetMin() >= 1.0f && count < 1) - { + if (prim->mSpawnCount.GetMin() >= 1.0f && count < 1) { count = 1; } - if ( prim->mCopy ) - { + if (prim->mCopy) { // If we are a copy, we need to store a "how many references count" so that we // can keep the primitive template around for the correct amount of time. prim->mRefCount = count; } - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { factor = abs(prim->mSpawnDelay.GetMax() - prim->mSpawnDelay.GetMin()) / (float)count; } // Schedule the random number of bits - for ( int t = 0; t < count; t++ ) - { + for (int t = 0; t < count; t++) { totalEffects++; - if ( prim->mSpawnFlags & FX_EVEN_DISTRIBUTION ) - { + if (prim->mSpawnFlags & FX_EVEN_DISTRIBUTION) { delay = t * factor; - } - else - { + } else { delay = prim->mSpawnDelay.GetVal(); } // if the delay is so small, we may as well just create this bit right now - if ( delay < 1 && !forceScheduling && !isPortal ) - { - if ( boltInfo == -1 && entityNum != -1 ) - { + if (delay < 1 && !forceScheduling && !isPortal) { + if (boltInfo == -1 && entityNum != -1) { // Find out where the entity currently is - TCGVectorData *data = (TCGVectorData*)cl.mSharedMemory; + TCGVectorData *data = (TCGVectorData *)cl.mSharedMemory; data->mEntityNum = entityNum; CGVM_GetLerpOrigin(); - CreateEffect( prim, data->mPoint, axis, -delay, fxParm ); + CreateEffect(prim, data->mPoint, axis, -delay, fxParm); + } else { + CreateEffect(prim, origin, axis, -delay, fxParm); } - else - { - CreateEffect( prim, origin, axis, -delay, fxParm ); - } - } - else - { - SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); + } else { + SScheduledEffect *sfx = mScheduledEffectsPool.Alloc(); - if ( sfx == NULL ) - { - Com_Error (ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); + if (sfx == NULL) { + Com_Error(ERR_DROP, "ERROR: Failed to allocate EFX from memory pool."); return; } @@ -937,39 +820,30 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int sfx->mIsRelative = isRelative; sfx->mPortalEffect = isPortal; - if ( boltInfo == -1 ) - { + if (boltInfo == -1) { sfx->ghoul2 = NULL; - if ( entityNum == -1 ) - { + if (entityNum == -1) { // we aren't bolting, so make sure the spawn system knows this by putting -1's in these fields sfx->mBoltNum = -1; sfx->mEntNum = ENTITYNUM_NONE; sfx->mModelNum = 0; - if ( origin ) - { - VectorCopy( origin, sfx->mOrigin ); - } - else - { - VectorClear( sfx->mOrigin ); + if (origin) { + VectorCopy(origin, sfx->mOrigin); + } else { + VectorClear(sfx->mOrigin); } - AxisCopy( axis, sfx->mAxis ); - } - else - { + AxisCopy(axis, sfx->mAxis); + } else { // we are doing bolting onto the origin of the entity, so use a cheaper method sfx->mBoltNum = -1; sfx->mEntNum = entityNum; sfx->mModelNum = 0; - AxisCopy( axis, sfx->mAxis ); + AxisCopy(axis, sfx->mAxis); } - } - else - { + } else { // we are bolting, so store the extra info sfx->mBoltNum = boltNum; sfx->mEntNum = entityNum; @@ -980,14 +854,13 @@ void CFxScheduler::PlayEffect( int id, vec3_t origin, matrix3_t axis, const int sfx->mStartTime++; } - mFxSchedule.push_front( sfx ); + mFxSchedule.push_front(sfx); } } } // We track effect templates and primitive templates separately. - if ( fx->mCopy ) - { + if (fx->mCopy) { // We don't use dynamic memory allocation, so just mark us as dead fx->mInUse = false; } @@ -1028,14 +901,13 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, int vol, int rad // Return: // none //------------------------------------------------------ -void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward, int vol, int rad ) -{ - char sfile[MAX_QPATH]; +void CFxScheduler::PlayEffect(const char *file, vec3_t origin, vec3_t forward, int vol, int rad) { + char sfile[MAX_QPATH]; // Get an extenstion stripped version of the file - COM_StripExtension( file, sfile, sizeof( sfile ) ); + COM_StripExtension(file, sfile, sizeof(sfile)); - PlayEffect( mEffectIDs[sfile], origin, forward, vol, rad ); + PlayEffect(mEffectIDs[sfile], origin, forward, vol, rad); } //------------------------------------------------------ @@ -1050,58 +922,39 @@ void CFxScheduler::PlayEffect( const char *file, vec3_t origin, vec3_t forward, // Return: // none //------------------------------------------------------ -bool gEffectsInPortal = qfalse; //this is just because I don't want to have to add an mPortalEffect field to every actual effect. +bool gEffectsInPortal = qfalse; // this is just because I don't want to have to add an mPortalEffect field to every actual effect. -void CFxScheduler::AddScheduledEffects( bool portal ) -{ - TScheduledEffect::iterator itr, next; - vec3_t origin; - matrix3_t axis; - int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; - qboolean doesBoltExist = qfalse; +void CFxScheduler::AddScheduledEffects(bool portal) { + TScheduledEffect::iterator itr, next; + vec3_t origin; + matrix3_t axis; + int oldEntNum = -1, oldBoltIndex = -1, oldModelNum = -1; + qboolean doesBoltExist = qfalse; - if (portal) - { + if (portal) { gEffectsInPortal = true; - } - else - { + } else { AddLoopedEffects(); } - for ( itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */ ) - { + for (itr = mFxSchedule.begin(); itr != mFxSchedule.end(); /* do nothing */) { SScheduledEffect *effect = *itr; - if (portal == effect->mPortalEffect && effect->mStartTime <= theFxHelper.mTime ) - { //only render portal fx on the skyportal pass and vice versa - if (effect->mBoltNum == -1) - {// ok, are we spawning a bolt on effect or a normal one? - if ( effect->mEntNum != ENTITYNUM_NONE ) - { + if (portal == effect->mPortalEffect && effect->mStartTime <= theFxHelper.mTime) { // only render portal fx on the skyportal pass and vice versa + if (effect->mBoltNum == -1) { // ok, are we spawning a bolt on effect or a normal one? + if (effect->mEntNum != ENTITYNUM_NONE) { // Find out where the entity currently is - TCGVectorData *data = (TCGVectorData*)cl.mSharedMemory; + TCGVectorData *data = (TCGVectorData *)cl.mSharedMemory; data->mEntityNum = effect->mEntNum; CGVM_GetLerpOrigin(); - CreateEffect( effect->mpTemplate, - data->mPoint, effect->mAxis, - theFxHelper.mTime - effect->mStartTime ); + CreateEffect(effect->mpTemplate, data->mPoint, effect->mAxis, theFxHelper.mTime - effect->mStartTime); + } else { + CreateEffect(effect->mpTemplate, effect->mOrigin, effect->mAxis, theFxHelper.mTime - effect->mStartTime); } - else - { - CreateEffect( effect->mpTemplate, - effect->mOrigin, effect->mAxis, - theFxHelper.mTime - effect->mStartTime ); - } - } - else - { //bolted on effect + } else { // bolted on effect // do we need to go and re-get the bolt matrix again? Since it takes time lets try to do it only once - if ((effect->mModelNum != oldModelNum) || - (effect->mEntNum != oldEntNum) || - (effect->mBoltNum != oldBoltIndex)) - { + if ((effect->mModelNum != oldModelNum) || (effect->mEntNum != oldEntNum) || (effect->mBoltNum != oldBoltIndex)) { oldModelNum = effect->mModelNum; oldEntNum = effect->mEntNum; oldBoltIndex = effect->mBoltNum; @@ -1110,49 +963,37 @@ void CFxScheduler::AddScheduledEffects( bool portal ) } // only do this if we found the bolt - if (doesBoltExist) - { - if (effect->mIsRelative ) - { - CreateEffect( effect->mpTemplate, - origin, axis, 0, -1, - effect->ghoul2, effect->mEntNum, effect->mModelNum, effect->mBoltNum ); - } - else - { - CreateEffect( effect->mpTemplate, - origin, axis, - theFxHelper.mTime - effect->mStartTime ); + if (doesBoltExist) { + if (effect->mIsRelative) { + CreateEffect(effect->mpTemplate, origin, axis, 0, -1, effect->ghoul2, effect->mEntNum, effect->mModelNum, effect->mBoltNum); + } else { + CreateEffect(effect->mpTemplate, origin, axis, theFxHelper.mTime - effect->mStartTime); } } } - mScheduledEffectsPool.Free (effect); + mScheduledEffectsPool.Free(effect); itr = mFxSchedule.erase(itr); - } - else - { + } else { ++itr; } } // Add all active effects into the scene - FX_Add( !!portal ); + FX_Add(!!portal); gEffectsInPortal = false; } -bool CFxScheduler::Add2DEffect(float x, float y, float w, float h, vec4_t color, qhandle_t shaderHandle) -{ +bool CFxScheduler::Add2DEffect(float x, float y, float w, float h, vec4_t color, qhandle_t shaderHandle) { // need some sort of scale here because the effect was created using world units, not pixels - float fxScale2D = 10.0f; + float fxScale2D = 10.0f; - if (mNextFree2DEffect < FX_MAX_2DEFFECTS) - { + if (mNextFree2DEffect < FX_MAX_2DEFFECTS) { m2DEffects[mNextFree2DEffect].mScreenX = x; m2DEffects[mNextFree2DEffect].mScreenY = y; - m2DEffects[mNextFree2DEffect].mWidth = w*fxScale2D; - m2DEffects[mNextFree2DEffect].mHeight = h*fxScale2D; + m2DEffects[mNextFree2DEffect].mWidth = w * fxScale2D; + m2DEffects[mNextFree2DEffect].mHeight = h * fxScale2D; VectorCopy4(color, m2DEffects[mNextFree2DEffect].mColor); m2DEffects[mNextFree2DEffect].mShaderHandle = shaderHandle; @@ -1162,12 +1003,10 @@ bool CFxScheduler::Add2DEffect(float x, float y, float w, float h, vec4_t color, return false; } -void CFxScheduler::Draw2DEffects(float screenXScale, float screenYScale) -{ - float x = 0, y = 0, w = 0, h = 0; +void CFxScheduler::Draw2DEffects(float screenXScale, float screenYScale) { + float x = 0, y = 0, w = 0, h = 0; - for (int i = 0; i < mNextFree2DEffect; i++) - { + for (int i = 0; i < mNextFree2DEffect; i++) { x = m2DEffects[i].mScreenX; y = m2DEffects[i].mScreenY; w = m2DEffects[i].mWidth; @@ -1178,8 +1017,8 @@ void CFxScheduler::Draw2DEffects(float screenXScale, float screenYScale) y *= screenYScale; h *= screenYScale; - //allow 2d effect coloring? - re->DrawStretchPic(x - (w*0.5f), y - (h*0.5f), w, h, 0, 0, 1, 1, /*m2DEffects[i].mColor,*/ m2DEffects[i].mShaderHandle); + // allow 2d effect coloring? + re->DrawStretchPic(x - (w * 0.5f), y - (h * 0.5f), w, h, 0, 0, 1, 1, /*m2DEffects[i].mColor,*/ m2DEffects[i].mShaderHandle); } // now that all 2D effects have been drawn we can consider the entire array to be free mNextFree2DEffect = 0; @@ -1198,24 +1037,18 @@ void CFxScheduler::Draw2DEffects(float screenXScale, float screenYScale) // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, matrix3_t axis, int lateTime, int fxParm /*-1*/, CGhoul2Info_v *ghoul2, int entNum, int modelNum, int boltNum ) -{ - vec3_t org, org2, temp, - vel, accel, - sRGB, eRGB, - ang, angDelta, - ax[3]; - trace_t tr; - int emitterModel; +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, const vec3_t origin, matrix3_t axis, int lateTime, int fxParm /*-1*/, CGhoul2Info_v *ghoul2, int entNum, + int modelNum, int boltNum) { + vec3_t org, org2, temp, vel, accel, sRGB, eRGB, ang, angDelta, ax[3]; + trace_t tr; + int emitterModel; // We may modify the axis, so make a work copy - AxisCopy( axis, ax ); + AxisCopy(axis, ax); int flags = fx->mFlags; - if (ghoul2 != NULL && modelNum>=0 && boltNum>=0) - {//since you passed in these values, mark as relative to use them if it is supported - switch( fx->mType ) - { + if (ghoul2 != NULL && modelNum >= 0 && boltNum >= 0) { // since you passed in these values, mark as relative to use them if it is supported + switch (fx->mType) { case Particle: case Line: case Tail: @@ -1229,140 +1062,119 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma case Decal: case FxRunner: case ScreenFlash: - //not supported yet + // not supported yet case Sound: case CameraShake: - //does not work bolted + // does not work bolted break; default: break; } } - if( fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD ) - { - RotatePointAroundVector( ax[1], ax[0], axis[1], flrand(0.0f, 360.0f) ); - CrossProduct( ax[0], ax[1], ax[2] ); + if (fx->mSpawnFlags & FX_RAND_ROT_AROUND_FWD) { + RotatePointAroundVector(ax[1], ax[0], axis[1], flrand(0.0f, 360.0f)); + CrossProduct(ax[0], ax[1], ax[2]); } // Origin calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_CHEAP_ORG_CALC || flags & FX_RELATIVE ) - { // let's take the easy way out - VectorSet( org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal() ); - } - else - { // time for some extra work - VectorScale( ax[0], fx->mOrigin1X.GetVal(), org ); - VectorMA( org, fx->mOrigin1Y.GetVal(), ax[1], org ); - VectorMA( org, fx->mOrigin1Z.GetVal(), ax[2], org ); + if (fx->mSpawnFlags & FX_CHEAP_ORG_CALC || flags & FX_RELATIVE) { // let's take the easy way out + VectorSet(org, fx->mOrigin1X.GetVal(), fx->mOrigin1Y.GetVal(), fx->mOrigin1Z.GetVal()); + } else { // time for some extra work + VectorScale(ax[0], fx->mOrigin1X.GetVal(), org); + VectorMA(org, fx->mOrigin1Y.GetVal(), ax[1], org); + VectorMA(org, fx->mOrigin1Z.GetVal(), ax[2], org); } // We always add our calculated offset to the passed in origin, unless relative! - if( !(flags & FX_RELATIVE) ) - { - VectorAdd( org, origin, org ); + if (!(flags & FX_RELATIVE)) { + VectorAdd(org, origin, org); } // Now, we may need to calc a point on a sphere/ellipsoid/cylinder/disk and add that to it //---------------------------------------------------------------- - if ( fx->mSpawnFlags & FX_ORG_ON_SPHERE ) - { + if (fx->mSpawnFlags & FX_ORG_ON_SPHERE) { float x, y; float width, height; - x = DEG2RAD( flrand(0.0f, 360.0f) ); - y = DEG2RAD( flrand(0.0f, 180.0f) ); + x = DEG2RAD(flrand(0.0f, 360.0f)); + y = DEG2RAD(flrand(0.0f, 180.0f)); width = fx->mRadius.GetVal(); height = fx->mHeight.GetVal(); // calculate point on ellipse - VectorSet( temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height ); // sinx * siny, cosx * siny, cosy - VectorAdd( org, temp, org ); + VectorSet(temp, sin(x) * width * sin(y), cos(x) * width * sin(y), cos(y) * height); // sinx * siny, cosx * siny, cosy + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); - MakeNormalVectors( ax[0], ax[1], ax[2] ); + VectorNormalize2(temp, ax[0]); + MakeNormalVectors(ax[0], ax[1], ax[2]); } - } - else if ( fx->mSpawnFlags & FX_ORG_ON_CYLINDER ) - { - vec3_t pt; + } else if (fx->mSpawnFlags & FX_ORG_ON_CYLINDER) { + vec3_t pt; // set up our point, then rotate around the current direction to. Make unrotated cylinder centered around 0,0,0 - VectorScale( ax[1], fx->mRadius.GetVal(), pt ); - VectorMA( pt, flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt ); - RotatePointAroundVector( temp, ax[0], pt, flrand(0.0f, 360.0f) ); + VectorScale(ax[1], fx->mRadius.GetVal(), pt); + VectorMA(pt, flrand(-1.0f, 1.0f) * 0.5f * fx->mHeight.GetVal(), ax[0], pt); + RotatePointAroundVector(temp, ax[0], pt, flrand(0.0f, 360.0f)); - VectorAdd( org, temp, org ); + VectorAdd(org, temp, org); - if ( fx->mSpawnFlags & FX_AXIS_FROM_SPHERE ) - { - vec3_t up={0,0,1}; + if (fx->mSpawnFlags & FX_AXIS_FROM_SPHERE) { + vec3_t up = {0, 0, 1}; // well, we will now override the axis at the users request - VectorNormalize2( temp, ax[0] ); + VectorNormalize2(temp, ax[0]); - if ( ax[0][2] == 1.0f ) - { + if (ax[0][2] == 1.0f) { // readjust up - VectorSet( up, 0, 1, 0 ); + VectorSet(up, 0, 1, 0); } - CrossProduct( up, ax[0], ax[1] ); - CrossProduct( ax[0], ax[1], ax[2] ); + CrossProduct(up, ax[0], ax[1]); + CrossProduct(ax[0], ax[1], ax[2]); } } - if ( fx->mType == OrientedParticle ) - {//bolted oriented particles use origin2 as an angular rotation offset... - if ( flags & FX_RELATIVE ) - { - VectorSet( ax[0], fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); + if (fx->mType == OrientedParticle) { // bolted oriented particles use origin2 as an angular rotation offset... + if (flags & FX_RELATIVE) { + VectorSet(ax[0], fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); } } // There are only a few types that really use velocity and acceleration, so do extra work for those types //-------------------------------------------------------------------------------------------------------- - if ( fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter ) - { + if (fx->mType == Particle || fx->mType == OrientedParticle || fx->mType == Tail || fx->mType == Emitter) { // Velocity calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE || flags & FX_RELATIVE ) - { - VectorSet( vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal() ); - } - else - { // bah, do some extra work to coerce it - VectorScale( ax[0], fx->mVelX.GetVal(), vel ); - VectorMA( vel, fx->mVelY.GetVal(), ax[1], vel ); - VectorMA( vel, fx->mVelZ.GetVal(), ax[2], vel ); + if (fx->mSpawnFlags & FX_VEL_IS_ABSOLUTE || flags & FX_RELATIVE) { + VectorSet(vel, fx->mVelX.GetVal(), fx->mVelY.GetVal(), fx->mVelZ.GetVal()); + } else { // bah, do some extra work to coerce it + VectorScale(ax[0], fx->mVelX.GetVal(), vel); + VectorMA(vel, fx->mVelY.GetVal(), ax[1], vel); + VectorMA(vel, fx->mVelZ.GetVal(), ax[2], vel); } //------------------------------------- - if ( fx->mSpawnFlags & FX_AFFECTED_BY_WIND ) - { -/*rjr vec3_t wind; + if (fx->mSpawnFlags & FX_AFFECTED_BY_WIND) { + /*rjr vec3_t wind; - // wind is affecting us, so modify our initial velocity. ideally, we would update throughout our lives, but this is easier - CL_GetWindVector( wind ); - VectorMA( vel, fx->mWindModifier.GetVal() * 0.01f, wind, vel ); - */ + // wind is affecting us, so modify our initial velocity. ideally, we would update throughout our lives, but this is easier + CL_GetWindVector( wind ); + VectorMA( vel, fx->mWindModifier.GetVal() * 0.01f, wind, vel ); + */ } // Acceleration calculations //------------------------------------- - if ( fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE || flags & FX_RELATIVE ) - { - VectorSet( accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal() ); - } - else - { - VectorScale( ax[0], fx->mAccelX.GetVal(), accel ); - VectorMA( accel, fx->mAccelY.GetVal(), ax[1], accel ); - VectorMA( accel, fx->mAccelZ.GetVal(), ax[2], accel ); + if (fx->mSpawnFlags & FX_ACCEL_IS_ABSOLUTE || flags & FX_RELATIVE) { + VectorSet(accel, fx->mAccelX.GetVal(), fx->mAccelY.GetVal(), fx->mAccelZ.GetVal()); + } else { + VectorScale(ax[0], fx->mAccelX.GetVal(), accel); + VectorMA(accel, fx->mAccelY.GetVal(), ax[1], accel); + VectorMA(accel, fx->mAccelZ.GetVal(), ax[2], accel); } // Gravity is completely decoupled from acceleration since it is __always__ absolute @@ -1371,17 +1183,15 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma // There may be a lag between when the effect should be created and when it actually gets created. // Since we know what the discrepancy is, we can attempt to compensate... - if ( lateTime > 0 ) - { + if (lateTime > 0) { // Calc the time differences float ftime = lateTime * 0.001f; float time2 = ftime * ftime * 0.5f; - VectorMA( vel, ftime, accel, vel ); + VectorMA(vel, ftime, accel, vel); // Predict the new position - for ( int i = 0 ; i < 3 ; i++ ) - { + for (int i = 0; i < 3; i++) { org[i] = org[i] + ftime * vel[i] + time2 * vel[i]; } } @@ -1389,211 +1199,175 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma // Line type primitives work with an origin2, so do the extra work for them //-------------------------------------------------------------------------- - if ( fx->mType == Line || fx->mType == Electricity ) - { + if (fx->mType == Line || fx->mType == Electricity) { // We may have to do a trace to find our endpoint - if ( fx->mSpawnFlags & FX_ORG2_FROM_TRACE ) - { - VectorMA( org, FX_MAX_TRACE_DIST, ax[0], temp ); + if (fx->mSpawnFlags & FX_ORG2_FROM_TRACE) { + VectorMA(org, FX_MAX_TRACE_DIST, ax[0], temp); - if ( fx->mSpawnFlags & FX_ORG2_IS_OFFSET ) - { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much + if (fx->mSpawnFlags & FX_ORG2_IS_OFFSET) { // add a random flair to the endpoint...note: org2 will have to be pretty large to affect this much // we also do this pre-trace as opposed to post trace since we may have to render an impact effect // and we will want the normal at the exact endpos... - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); - VectorAdd( org2, temp, temp ); - } - else - { // I can only imagine a few cases where you might want to do this... - VectorMA( temp, fx->mOrigin2X.GetVal(), ax[0], temp ); - VectorMA( temp, fx->mOrigin2Y.GetVal(), ax[1], temp ); - VectorMA( temp, fx->mOrigin2Z.GetVal(), ax[2], temp ); + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + VectorAdd(org2, temp, temp); + } else { // I can only imagine a few cases where you might want to do this... + VectorMA(temp, fx->mOrigin2X.GetVal(), ax[0], temp); + VectorMA(temp, fx->mOrigin2Y.GetVal(), ax[1], temp); + VectorMA(temp, fx->mOrigin2Z.GetVal(), ax[2], temp); } } - theFxHelper.Trace( tr, org, NULL, NULL, temp, -1, MASK_SOLID ); + theFxHelper.Trace(tr, org, NULL, NULL, temp, -1, MASK_SOLID); - VectorCopy( tr.endpos, org2 ); + VectorCopy(tr.endpos, org2); - if ( fx->mSpawnFlags & FX_TRACE_IMPACT_FX ) - { - PlayEffect( fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal ); - } - } - else - { - if ( fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE ) - { - VectorSet( org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal() ); + if (fx->mSpawnFlags & FX_TRACE_IMPACT_FX) { + PlayEffect(fx->mImpactFxHandles.GetHandle(), org2, tr.plane.normal); } - else - { - VectorScale( ax[0], fx->mOrigin2X.GetVal(), org2 ); - VectorMA( org2, fx->mOrigin2Y.GetVal(), ax[1], org2 ); - VectorMA( org2, fx->mOrigin2Z.GetVal(), ax[2], org2 ); + } else { + if (fx->mSpawnFlags & FX_CHEAP_ORG2_CALC || flags & FX_RELATIVE) { + VectorSet(org2, fx->mOrigin2X.GetVal(), fx->mOrigin2Y.GetVal(), fx->mOrigin2Z.GetVal()); + } else { + VectorScale(ax[0], fx->mOrigin2X.GetVal(), org2); + VectorMA(org2, fx->mOrigin2Y.GetVal(), ax[1], org2); + VectorMA(org2, fx->mOrigin2Z.GetVal(), ax[2], org2); } - if( !(flags & FX_RELATIVE) ) - { - VectorAdd( org2, origin, org2 ); + if (!(flags & FX_RELATIVE)) { + VectorAdd(org2, origin, org2); } } } // end special org2 types // handle RGB color, but only for types that will use it //--------------------------------------------------------------------------- - if ( fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake ) - { - GetRGB_Colors( fx, sRGB, eRGB ); + if (fx->mType != Sound && fx->mType != FxRunner && fx->mType != CameraShake) { + GetRGB_Colors(fx, sRGB, eRGB); } // Now create the appropriate effect entity //------------------------ - switch( fx->mType ) - { + switch (fx->mType) { //--------- case Particle: - //--------- + //--------- - FX_AddParticle( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum ); + FX_AddParticle(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), + fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, ghoul2, entNum, modelNum, boltNum); break; //--------- case Line: - //--------- + //--------- - FX_AddLine( org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum); + FX_AddLine(org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, + fxParm, ghoul2, entNum, modelNum, boltNum); break; //--------- case Tail: - //--------- + //--------- - FX_AddTail( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum); + FX_AddTail(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), + fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), + fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, ghoul2, entNum, modelNum, boltNum); break; //---------------- case Electricity: - //---------------- + //---------------- - FX_AddElectricity( org, org2, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mElasticity.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, - fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum); + FX_AddElectricity(org, org2, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mElasticity.GetVal(), fx->mLife.GetVal(), + fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, ghoul2, entNum, modelNum, boltNum); break; //--------- case Cylinder: - //--------- + //--------- - FX_AddCylinder( org, ax[0], - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mSize2Start.GetVal(), fx->mSize2End.GetVal(), fx->mSize2Parm.GetVal(), - fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum, - (qboolean)( fx->mSpawnFlags & FX_ORG2_FROM_TRACE )); + FX_AddCylinder(org, ax[0], fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mSize2Start.GetVal(), fx->mSize2End.GetVal(), + fx->mSize2Parm.GetVal(), fx->mLengthStart.GetVal(), fx->mLengthEnd.GetVal(), fx->mLengthParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), + flags, fx->mMatImpactFX, fxParm, ghoul2, entNum, modelNum, boltNum, (qboolean)(fx->mSpawnFlags & FX_ORG2_FROM_TRACE)); break; //--------- case Emitter: - //--------- + //--------- // for chunk angles, you don't really need much control over the end result...you just want variation.. - VectorSet( ang, - fx->mAngle1.GetVal(), - fx->mAngle2.GetVal(), - fx->mAngle3.GetVal() ); + VectorSet(ang, fx->mAngle1.GetVal(), fx->mAngle2.GetVal(), fx->mAngle3.GetVal()); - vectoangles( ax[0], temp ); - VectorAdd( ang, temp, ang ); + vectoangles(ax[0], temp); + VectorAdd(ang, temp, ang); - VectorSet( angDelta, - fx->mAngle1Delta.GetVal(), - fx->mAngle2Delta.GetVal(), - fx->mAngle3Delta.GetVal() ); + VectorSet(angDelta, fx->mAngle1Delta.GetVal(), fx->mAngle2Delta.GetVal(), fx->mAngle3Delta.GetVal()); emitterModel = fx->mMediaHandles.GetHandle(); - FX_AddEmitter( org, vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - ang, angDelta, - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mEmitterFxHandles.GetHandle(), - fx->mDensity.GetVal(), fx->mVariance.GetVal(), - fx->mLife.GetVal(), emitterModel, flags, fx->mMatImpactFX, fxParm ); + FX_AddEmitter(org, vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), ang, angDelta, fx->mMin, fx->mMax, fx->mElasticity.GetVal(), + fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), fx->mEmitterFxHandles.GetHandle(), fx->mDensity.GetVal(), + fx->mVariance.GetVal(), fx->mLife.GetVal(), emitterModel, flags, fx->mMatImpactFX, fxParm); break; //--------- case Decal: - //--------- + //--------- -/* rjr - // This function is a somewhat higher-cost function for projecting a decal mark onto a surface. - // We shouldn't always need this, only for big hits or when a decal is very close-up. + /* rjr + // This function is a somewhat higher-cost function for projecting a decal mark onto a surface. + // We shouldn't always need this, only for big hits or when a decal is very close-up. - // If the impact size is greater than 6, don't even try to use cheap sprites. Big marks need real decals. - if (fx->mSizeStart.GetVal()<6) - { - vec3_t dest, normal; - int findmarkret; - - findmarkret = CG_FindMark(org, ax[0], dest, normal); - - if (findmarkret) - { // Legal to put down a mark. - - if ( findmarkret == FINDMARK_CHEAP || // If we can't put down a decal OR if and distance > 200 - DistanceSquared( dest, cg.refdef.vieworg ) > 40000) - { // Use cheap oriented particle decals. - vec3_t zerovec={0,0,0}; - - FX_AddOrientedParticle( effectCloud, org, ax[0], - zerovec, // velocity - zerovec, // acceleration - fx->mSizeStart.GetVal(), fx->mSizeStart.GetVal(), 0, // size params - fx->mAlphaStart.GetVal(), 0, 0.75, // alpha params (start fading at 75% life) - sRGB, sRGB, 0, // rgb params - fx->mRotation.GetVal(), 0, // rotation delta - zerovec, // min - zerovec, // max - 0, // bounce - 0, // deathID - 0, // impactID - 20000, // lifetime - fx->mMediaHandles.GetHandle(), - (fx->mFlags&~FX_ALPHA_PARM_MASK)|FX_ALPHA_NONLINEAR, - MATIMPACTFX_NONE, -1); + // If the impact size is greater than 6, don't even try to use cheap sprites. Big marks need real decals. + if (fx->mSizeStart.GetVal()<6) + { + vec3_t dest, normal; + int findmarkret; + + findmarkret = CG_FindMark(org, ax[0], dest, normal); + + if (findmarkret) + { // Legal to put down a mark. + + if ( findmarkret == FINDMARK_CHEAP || // If we can't put down a decal OR if and distance > 200 + DistanceSquared( dest, cg.refdef.vieworg ) > 40000) + { // Use cheap oriented particle decals. + vec3_t zerovec={0,0,0}; + + FX_AddOrientedParticle( effectCloud, org, ax[0], + zerovec, // velocity + zerovec, // acceleration + fx->mSizeStart.GetVal(), fx->mSizeStart.GetVal(), 0, // size params + fx->mAlphaStart.GetVal(), 0, 0.75, // alpha params (start fading at 75% life) + sRGB, sRGB, 0, // rgb params + fx->mRotation.GetVal(), 0, // rotation delta + zerovec, // min + zerovec, // max + 0, // bounce + 0, // deathID + 0, // impactID + 20000, // lifetime + fx->mMediaHandles.GetHandle(), + (fx->mFlags&~FX_ALPHA_PARM_MASK)|FX_ALPHA_NONLINEAR, + MATIMPACTFX_NONE, -1); + } + else + { // Use the expensive kind. + color.rgba.r = sRGB[0] * 0xff; + color.rgba.g = sRGB[1] * 0xff; + color.rgba.b = sRGB[2] * 0xff; + color.rgba.a = fx->mAlphaStart.GetVal() * 0xff; + + CG_ImpactMark( fx->mMediaHandles.GetHandle(), org, ax[0], + fx->mRotation.GetVal(), color.c, 12000, 8000, + true, fx->mSizeStart.GetVal(), false ); + } + } } else { // Use the expensive kind. @@ -1605,25 +1379,12 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma CG_ImpactMark( fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), color.c, 12000, 8000, true, fx->mSizeStart.GetVal(), false ); - } - } - } - else - { // Use the expensive kind. - color.rgba.r = sRGB[0] * 0xff; - color.rgba.g = sRGB[1] * 0xff; - color.rgba.b = sRGB[2] * 0xff; - color.rgba.a = fx->mAlphaStart.GetVal() * 0xff; - - CG_ImpactMark( fx->mMediaHandles.GetHandle(), org, ax[0], - fx->mRotation.GetVal(), color.c, 12000, 8000, - true, fx->mSizeStart.GetVal(), false ); - } */ + } */ - theFxHelper.AddDecalToScene ( fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), qtrue, fx->mSizeStart.GetVal(), qfalse ); + theFxHelper.AddDecalToScene(fx->mMediaHandles.GetHandle(), org, ax[0], fx->mRotation.GetVal(), sRGB[0], sRGB[1], sRGB[2], fx->mAlphaStart.GetVal(), + qtrue, fx->mSizeStart.GetVal(), qfalse); - if (fx->mFlags & FX_GHOUL2_DECALS) - { + if (fx->mFlags & FX_GHOUL2_DECALS) { theFxHelper.AddGhoul2Decal(fx->mMediaHandles.GetHandle(), org, ax[0], fx->mSizeStart.GetVal()); } @@ -1631,66 +1392,57 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma //------------------- case OrientedParticle: - //------------------- + //------------------- - FX_AddOrientedParticle( org, ax[0], vel, accel, - fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mRotation.GetVal(), fx->mRotationDelta.GetVal(), - fx->mMin, fx->mMax, fx->mElasticity.GetVal(), - fx->mDeathFxHandles.GetHandle(), fx->mImpactFxHandles.GetHandle(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum); + FX_AddOrientedParticle(org, ax[0], vel, accel, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), + fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mRotation.GetVal(), + fx->mRotationDelta.GetVal(), fx->mMin, fx->mMax, fx->mElasticity.GetVal(), fx->mDeathFxHandles.GetHandle(), + fx->mImpactFxHandles.GetHandle(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm, ghoul2, + entNum, modelNum, boltNum); break; //--------- case Sound: - //--------- - if (gEffectsInPortal) - { //could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so just make it a local sound. - theFxHelper.PlayLocalSound( fx->mMediaHandles.GetHandle(), CHAN_AUTO ); - } - else - { - theFxHelper.PlaySound( org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle(), fx->mSoundVolume, fx->mSoundRadius ); + //--------- + if (gEffectsInPortal) { // could orient this anyway for panning, but eh. It's going to appear to the player in the sky the same place no matter what, so + // just make it a local sound. + theFxHelper.PlayLocalSound(fx->mMediaHandles.GetHandle(), CHAN_AUTO); + } else { + theFxHelper.PlaySound(org, ENTITYNUM_NONE, CHAN_AUTO, fx->mMediaHandles.GetHandle(), fx->mSoundVolume, fx->mSoundRadius); } break; //--------- case FxRunner: - //--------- + //--------- - PlayEffect( fx->mPlayFxHandles.GetHandle(), org, ax ); + PlayEffect(fx->mPlayFxHandles.GetHandle(), org, ax); break; //--------- case Light: - //--------- + //--------- - FX_AddLight( org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), flags, fx->mMatImpactFX, fxParm, - ghoul2, entNum, modelNum, boltNum); + FX_AddLight(org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), flags, + fx->mMatImpactFX, fxParm, ghoul2, entNum, modelNum, boltNum); break; //--------- case CameraShake: - //--------- + //--------- // It calculates how intense the shake should be based on how close you are to the origin you pass in here // elasticity is actually the intensity...radius is the distance in which the shake will have some effect // life is how long the effect lasts. - theFxHelper.CameraShake( org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal() ); + theFxHelper.CameraShake(org, fx->mElasticity.GetVal(), fx->mRadius.GetVal(), fx->mLife.GetVal()); break; //-------------- case ScreenFlash: - //-------------- + //-------------- - FX_AddFlash( org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), - fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), fx->mAlphaParm.GetVal(), - sRGB, eRGB, fx->mRGBParm.GetVal(), - fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, fxParm ); + FX_AddFlash(org, fx->mSizeStart.GetVal(), fx->mSizeEnd.GetVal(), fx->mSizeParm.GetVal(), fx->mAlphaStart.GetVal(), fx->mAlphaEnd.GetVal(), + fx->mAlphaParm.GetVal(), sRGB, eRGB, fx->mRGBParm.GetVal(), fx->mLife.GetVal(), fx->mMediaHandles.GetHandle(), flags, fx->mMatImpactFX, + fxParm); break; default: @@ -1699,12 +1451,10 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma } // Track when we need to clean ourselves up if we are a copy - if ( fx->mCopy ) - { + if (fx->mCopy) { fx->mRefCount--; - if ( fx->mRefCount <= 0 ) - { + if (fx->mRefCount <= 0) { delete fx; } } @@ -1720,15 +1470,13 @@ void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, const vec3_t origin, ma // Return: // none //------------------------------------------------------ -void CFxScheduler::CreateEffect( CPrimitiveTemplate *fx, SScheduledEffect *scheduledFx ) -{ +void CFxScheduler::CreateEffect(CPrimitiveTemplate *fx, SScheduledEffect *scheduledFx) { int boltInfo; // annoying bit....we have to pack the values back into an int before calling playEffect since there isn't the ideal overload we can already use. - boltInfo = (( scheduledFx->mModelNum & MODEL_AND ) << MODEL_SHIFT ); - boltInfo |= (( scheduledFx->mBoltNum & BOLT_AND ) << BOLT_SHIFT ); - boltInfo |= (( scheduledFx->mEntNum & ENTITY_AND ) << ENTITY_SHIFT ); + boltInfo = ((scheduledFx->mModelNum & MODEL_AND) << MODEL_SHIFT); + boltInfo |= ((scheduledFx->mBoltNum & BOLT_AND) << BOLT_SHIFT); + boltInfo |= ((scheduledFx->mEntNum & ENTITY_AND) << ENTITY_SHIFT); - PlayEffect( fx->mPlayFxHandles.GetHandle(), scheduledFx->mOrigin, scheduledFx->mAxis, boltInfo ); + PlayEffect(fx->mPlayFxHandles.GetHandle(), scheduledFx->mOrigin, scheduledFx->mAxis, boltInfo); } - diff --git a/codemp/client/FxSystem.cpp b/codemp/client/FxSystem.cpp index f54d9915f2..406b3c6ce6 100644 --- a/codemp/client/FxSystem.cpp +++ b/codemp/client/FxSystem.cpp @@ -25,28 +25,20 @@ along with this program; if not, see . #include "FxScheduler.h" #include "ghoul2/G2.h" -cvar_t *fx_debug; +cvar_t *fx_debug; #ifdef _DEBUG -cvar_t *fx_freeze; +cvar_t *fx_freeze; #endif -cvar_t *fx_countScale; -cvar_t *fx_nearCull; +cvar_t *fx_countScale; +cvar_t *fx_nearCull; -#define DEFAULT_EXPLOSION_RADIUS 512 +#define DEFAULT_EXPLOSION_RADIUS 512 // Stuff for the FxHelper //------------------------------------------------------ -SFxHelper::SFxHelper() : - mTime(0), - mOldTime(0), - mFrameTime(0), - mTimeFrozen(false), - refdef(0) -{ -} +SFxHelper::SFxHelper() : mTime(0), mOldTime(0), mFrameTime(0), mTimeFrozen(false), refdef(0) {} -void SFxHelper::ReInit(refdef_t* pRefdef) -{ +void SFxHelper::ReInit(refdef_t *pRefdef) { mTime = 0; mOldTime = 0; mFrameTime = 0; @@ -55,52 +47,46 @@ void SFxHelper::ReInit(refdef_t* pRefdef) } //------------------------------------------------------ -void SFxHelper::Print( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void SFxHelper::Print(const char *msg, ...) { + va_list argptr; + char text[1024]; - va_start( argptr, msg ); + va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); - va_end( argptr ); + va_end(argptr); - Com_DPrintf( text ); + Com_DPrintf(text); } //------------------------------------------------------ -void SFxHelper::AdjustTime( int frametime ) -{ +void SFxHelper::AdjustTime(int frametime) { #ifdef _DEBUG - if ( fx_freeze->integer || ( frametime <= 0 )) + if (fx_freeze->integer || (frametime <= 0)) #else - if ( frametime <= 0 ) + if (frametime <= 0) #endif { // Allow no time progression when we are paused. mFrameTime = 0; mRealTime = 0.0f; - } - else - { + } else { mOldTime = mTime; mTime = frametime; mFrameTime = mTime - mOldTime; mRealTime = mFrameTime * 0.001f; + /* mFrameTime = frametime; + mTime += mFrameTime; + mRealTime = mFrameTime * 0.001f;*/ -/* mFrameTime = frametime; - mTime += mFrameTime; - mRealTime = mFrameTime * 0.001f;*/ - -// mHalfRealTimeSq = mRealTime * mRealTime * 0.5f; + // mHalfRealTimeSq = mRealTime * mRealTime * 0.5f; } } //------------------------------------------------------ -void SFxHelper::CameraShake( vec3_t origin, float intensity, int radius, int time ) -{ - TCGCameraShake *data = (TCGCameraShake *)cl.mSharedMemory; +void SFxHelper::CameraShake(vec3_t origin, float intensity, int radius, int time) { + TCGCameraShake *data = (TCGCameraShake *)cl.mSharedMemory; VectorCopy(origin, data->mOrigin); data->mIntensity = intensity; @@ -111,23 +97,20 @@ void SFxHelper::CameraShake( vec3_t origin, float intensity, int radius, int tim } //------------------------------------------------------ -qboolean SFxHelper::GetOriginAxisFromBolt(CGhoul2Info_v *pGhoul2, int mEntNum, int modelNum, int boltNum, vec3_t /*out*/origin, vec3_t /*out*/axis[3]) -{ +qboolean SFxHelper::GetOriginAxisFromBolt(CGhoul2Info_v *pGhoul2, int mEntNum, int modelNum, int boltNum, vec3_t /*out*/ origin, vec3_t /*out*/ axis[3]) { qboolean doesBoltExist; - mdxaBone_t boltMatrix; - TCGGetBoltData *data = (TCGGetBoltData*)cl.mSharedMemory; + mdxaBone_t boltMatrix; + TCGGetBoltData *data = (TCGGetBoltData *)cl.mSharedMemory; data->mEntityNum = mEntNum; - CGVM_GetLerpData();//this func will zero out pitch and roll for players, and ridable vehicles + CGVM_GetLerpData(); // this func will zero out pitch and roll for players, and ridable vehicles - //Fixme: optimize these VM calls away by storing + // Fixme: optimize these VM calls away by storing // go away and get me the bolt position for this frame please - doesBoltExist = re->G2API_GetBoltMatrix(*pGhoul2, modelNum, boltNum, - &boltMatrix, data->mAngles, data->mOrigin, theFxHelper.mOldTime, 0, data->mScale); + doesBoltExist = re->G2API_GetBoltMatrix(*pGhoul2, modelNum, boltNum, &boltMatrix, data->mAngles, data->mOrigin, theFxHelper.mOldTime, 0, data->mScale); - if (doesBoltExist) - { // set up the axis and origin we need for the actual effect spawning - origin[0] = boltMatrix.matrix[0][3]; + if (doesBoltExist) { // set up the axis and origin we need for the actual effect spawning + origin[0] = boltMatrix.matrix[0][3]; origin[1] = boltMatrix.matrix[1][3]; origin[2] = boltMatrix.matrix[2][3]; diff --git a/codemp/client/FxTemplate.cpp b/codemp/client/FxTemplate.cpp index 83f404c94c..9f98fd67b1 100644 --- a/codemp/client/FxTemplate.cpp +++ b/codemp/client/FxTemplate.cpp @@ -33,8 +33,7 @@ along with this program; if not, see . // Return: // none //------------------------------------------------------ -CPrimitiveTemplate::CPrimitiveTemplate() -{ +CPrimitiveTemplate::CPrimitiveTemplate() { // We never start out as a copy or with a name mCopy = false; mName[0] = 0; @@ -48,137 +47,136 @@ CPrimitiveTemplate::CPrimitiveTemplate() mMatImpactFX = MATIMPACTFX_NONE; - mLife.SetRange( 50.0f, 50.0f ); - mSpawnCount.SetRange( 1.0f, 1.0f ); - mRadius.SetRange( 10.0f, 10.0f ); - mHeight.SetRange( 10.0f, 10.0f ); - mWindModifier.SetRange( 1.0f, 1.0f ); + mLife.SetRange(50.0f, 50.0f); + mSpawnCount.SetRange(1.0f, 1.0f); + mRadius.SetRange(10.0f, 10.0f); + mHeight.SetRange(10.0f, 10.0f); + mWindModifier.SetRange(1.0f, 1.0f); - VectorSet( mMin, 0.0f, 0.0f, 0.0f ); - VectorSet( mMax, 0.0f, 0.0f, 0.0f ); + VectorSet(mMin, 0.0f, 0.0f, 0.0f); + VectorSet(mMax, 0.0f, 0.0f, 0.0f); - mRedStart.SetRange( 1.0f, 1.0f ); - mGreenStart.SetRange( 1.0f, 1.0f ); - mBlueStart.SetRange( 1.0f, 1.0f ); + mRedStart.SetRange(1.0f, 1.0f); + mGreenStart.SetRange(1.0f, 1.0f); + mBlueStart.SetRange(1.0f, 1.0f); - mRedEnd.SetRange( 1.0f, 1.0f ); - mGreenEnd.SetRange( 1.0f, 1.0f ); - mBlueEnd.SetRange( 1.0f, 1.0f ); + mRedEnd.SetRange(1.0f, 1.0f); + mGreenEnd.SetRange(1.0f, 1.0f); + mBlueEnd.SetRange(1.0f, 1.0f); - mAlphaStart.SetRange( 1.0f, 1.0f ); - mAlphaEnd.SetRange( 1.0f, 1.0f ); + mAlphaStart.SetRange(1.0f, 1.0f); + mAlphaEnd.SetRange(1.0f, 1.0f); - mSizeStart.SetRange( 1.0f, 1.0f ); - mSizeEnd.SetRange( 1.0f, 1.0f ); + mSizeStart.SetRange(1.0f, 1.0f); + mSizeEnd.SetRange(1.0f, 1.0f); - mSize2Start.SetRange( 1.0f, 1.0f ); - mSize2End.SetRange( 1.0f, 1.0f ); + mSize2Start.SetRange(1.0f, 1.0f); + mSize2End.SetRange(1.0f, 1.0f); - mLengthStart.SetRange( 1.0f, 1.0f ); - mLengthEnd.SetRange( 1.0f, 1.0f ); + mLengthStart.SetRange(1.0f, 1.0f); + mLengthEnd.SetRange(1.0f, 1.0f); - mTexCoordS.SetRange( 1.0f, 1.0f ); - mTexCoordT.SetRange( 1.0f, 1.0f ); + mTexCoordS.SetRange(1.0f, 1.0f); + mTexCoordT.SetRange(1.0f, 1.0f); - mVariance.SetRange( 1.0f, 1.0f ); - mDensity.SetRange( 10.0f, 10.0f );// default this high so it doesn't do bad things + mVariance.SetRange(1.0f, 1.0f); + mDensity.SetRange(10.0f, 10.0f); // default this high so it doesn't do bad things } //----------------------------------------------------------- -CPrimitiveTemplate &CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) -{ +CPrimitiveTemplate &CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that) { // I'm assuming that doing a memcpy wouldn't work here // If you are looking at this and know a better way to do this, please tell me. - strcpy( mName, that.mName ); + strcpy(mName, that.mName); - mType = that.mType; + mType = that.mType; - mSpawnDelay = that.mSpawnDelay; - mSpawnCount = that.mSpawnCount; - mLife = that.mLife; - mCullRange = that.mCullRange; + mSpawnDelay = that.mSpawnDelay; + mSpawnCount = that.mSpawnCount; + mLife = that.mLife; + mCullRange = that.mCullRange; - mMediaHandles = that.mMediaHandles; - mImpactFxHandles = that.mImpactFxHandles; - mDeathFxHandles = that.mDeathFxHandles; - mEmitterFxHandles = that.mEmitterFxHandles; - mPlayFxHandles = that.mPlayFxHandles; + mMediaHandles = that.mMediaHandles; + mImpactFxHandles = that.mImpactFxHandles; + mDeathFxHandles = that.mDeathFxHandles; + mEmitterFxHandles = that.mEmitterFxHandles; + mPlayFxHandles = that.mPlayFxHandles; - mFlags = that.mFlags; - mSpawnFlags = that.mSpawnFlags; + mFlags = that.mFlags; + mSpawnFlags = that.mSpawnFlags; - VectorCopy( that.mMin, mMin ); - VectorCopy( that.mMax, mMax ); + VectorCopy(that.mMin, mMin); + VectorCopy(that.mMax, mMax); - mOrigin1X = that.mOrigin1X; - mOrigin1Y = that.mOrigin1Y; - mOrigin1Z = that.mOrigin1Z; + mOrigin1X = that.mOrigin1X; + mOrigin1Y = that.mOrigin1Y; + mOrigin1Z = that.mOrigin1Z; - mOrigin2X = that.mOrigin2X; - mOrigin2Y = that.mOrigin2Y; - mOrigin2Z = that.mOrigin2Z; + mOrigin2X = that.mOrigin2X; + mOrigin2Y = that.mOrigin2Y; + mOrigin2Z = that.mOrigin2Z; - mRadius = that.mRadius; - mHeight = that.mHeight; - mWindModifier = that.mWindModifier; + mRadius = that.mRadius; + mHeight = that.mHeight; + mWindModifier = that.mWindModifier; - mRotation = that.mRotation; - mRotationDelta = that.mRotationDelta; + mRotation = that.mRotation; + mRotationDelta = that.mRotationDelta; - mAngle1 = that.mAngle1; - mAngle2 = that.mAngle2; - mAngle3 = that.mAngle3; + mAngle1 = that.mAngle1; + mAngle2 = that.mAngle2; + mAngle3 = that.mAngle3; - mAngle1Delta = that.mAngle1Delta; - mAngle2Delta = that.mAngle2Delta; - mAngle3Delta = that.mAngle3Delta; + mAngle1Delta = that.mAngle1Delta; + mAngle2Delta = that.mAngle2Delta; + mAngle3Delta = that.mAngle3Delta; - mVelX = that.mVelX; - mVelY = that.mVelY; - mVelZ = that.mVelZ; + mVelX = that.mVelX; + mVelY = that.mVelY; + mVelZ = that.mVelZ; - mAccelX = that.mAccelX; - mAccelY = that.mAccelY; - mAccelZ = that.mAccelZ; + mAccelX = that.mAccelX; + mAccelY = that.mAccelY; + mAccelZ = that.mAccelZ; - mGravity = that.mGravity; + mGravity = that.mGravity; - mDensity = that.mDensity; - mVariance = that.mVariance; + mDensity = that.mDensity; + mVariance = that.mVariance; - mRedStart = that.mRedStart; - mGreenStart = that.mGreenStart; - mBlueStart = that.mBlueStart; + mRedStart = that.mRedStart; + mGreenStart = that.mGreenStart; + mBlueStart = that.mBlueStart; - mRedEnd = that.mRedEnd; - mGreenEnd = that.mGreenEnd; - mBlueEnd = that.mBlueEnd; + mRedEnd = that.mRedEnd; + mGreenEnd = that.mGreenEnd; + mBlueEnd = that.mBlueEnd; - mRGBParm = that.mRGBParm; + mRGBParm = that.mRGBParm; - mAlphaStart = that.mAlphaStart; - mAlphaEnd = that.mAlphaEnd; - mAlphaParm = that.mAlphaParm; + mAlphaStart = that.mAlphaStart; + mAlphaEnd = that.mAlphaEnd; + mAlphaParm = that.mAlphaParm; - mSizeStart = that.mSizeStart; - mSizeEnd = that.mSizeEnd; - mSizeParm = that.mSizeParm; + mSizeStart = that.mSizeStart; + mSizeEnd = that.mSizeEnd; + mSizeParm = that.mSizeParm; - mSize2Start = that.mSize2Start; - mSize2End = that.mSize2End; - mSize2Parm = that.mSize2Parm; + mSize2Start = that.mSize2Start; + mSize2End = that.mSize2End; + mSize2Parm = that.mSize2Parm; - mLengthStart = that.mLengthStart; - mLengthEnd = that.mLengthEnd; - mLengthParm = that.mLengthParm; + mLengthStart = that.mLengthStart; + mLengthEnd = that.mLengthEnd; + mLengthParm = that.mLengthParm; - mTexCoordS = that.mTexCoordS; - mTexCoordT = that.mTexCoordT; + mTexCoordS = that.mTexCoordS; + mTexCoordT = that.mTexCoordT; - mElasticity = that.mElasticity; + mElasticity = that.mElasticity; - mSoundRadius = that.mSoundRadius; - mSoundVolume = that.mSoundVolume; + mSoundRadius = that.mSoundRadius; + mSoundVolume = that.mSoundVolume; return *this; } @@ -196,30 +194,24 @@ CPrimitiveTemplate &CPrimitiveTemplate::operator=(const CPrimitiveTemplate &that // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFloat( const char *val, float *min, float *max ) -{ +bool CPrimitiveTemplate::ParseFloat(const char *val, float *min, float *max) { // We don't allow passing in a null for either of the fields - if ( min == 0 || max == 0 ) - { // failue + if (min == 0 || max == 0) { // failue return false; } // attempt to read out the values - int v = sscanf( val, "%f %f", min, max ); + int v = sscanf(val, "%f %f", min, max); - if ( v == 0 ) - { // nothing was there, failure + if (v == 0) { // nothing was there, failure return false; - } - else if ( v == 1 ) - { // only one field entered, this is ok, but we should copy min into max + } else if (v == 1) { // only one field entered, this is ok, but we should copy min into max *max = *min; } return true; } - //------------------------------------------------------ // ParseVector // Removes up to six values from a passed in string and @@ -233,25 +225,20 @@ bool CPrimitiveTemplate::ParseFloat( const char *val, float *min, float *max ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVector( const char *val, vec3_t min, vec3_t max ) -{ +bool CPrimitiveTemplate::ParseVector(const char *val, vec3_t min, vec3_t max) { // we don't allow passing in a null - if ( min == 0 || max == 0 ) - { + if (min == 0 || max == 0) { return false; } // attempt to read out our values - int v = sscanf( val, "%f %f %f %f %f %f", &min[0], &min[1], &min[2], &max[0], &max[1], &max[2] ); + int v = sscanf(val, "%f %f %f %f %f %f", &min[0], &min[1], &min[2], &max[0], &max[1], &max[2]); // Check for completeness - if ( v < 3 || v == 4 || v == 5 ) - { // not a complete value + if (v < 3 || v == 4 || v == 5) { // not a complete value return false; - } - else if ( v == 3 ) - { // only a min was entered, so copy the result into max - VectorCopy( min, max ); + } else if (v == 3) { // only a min was entered, so copy the result into max + VectorCopy(min, max); } return true; @@ -270,43 +257,38 @@ bool CPrimitiveTemplate::ParseVector( const char *val, vec3_t min, vec3_t max ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGroupFlags( const char *val, int *flags ) -{ +bool CPrimitiveTemplate::ParseGroupFlags(const char *val, int *flags) { // Must pass in a non-null pointer - if ( flags == 0 ) - { + if (flags == 0) { return false; } - char flag[][32] = {"\0","\0","\0","0"}; - bool ok = true; + char flag[][32] = {"\0", "\0", "\0", "0"}; + bool ok = true; // For a sub group, really you probably only have one or two flags set - int v = sscanf( val, "%s %s %s %s", flag[0], flag[1], flag[2], flag[3] ); + int v = sscanf(val, "%s %s %s %s", flag[0], flag[1], flag[2], flag[3]); // Clear out the flags field, then convert the flag string to an actual value ( use generic flags ) *flags = 0; - for ( int i = 0; i < 4; i++ ) - { - if ( i + 1 > v ) - { + for (int i = 0; i < 4; i++) { + if (i + 1 > v) { return true; } - if ( !Q_stricmp( flag[i], "linear" ) ) + if (!Q_stricmp(flag[i], "linear")) *flags |= FX_LINEAR; - else if ( !Q_stricmp( flag[i], "nonlinear" ) ) + else if (!Q_stricmp(flag[i], "nonlinear")) *flags |= FX_NONLINEAR; - else if ( !Q_stricmp( flag[i], "wave" ) ) + else if (!Q_stricmp(flag[i], "wave")) *flags |= FX_WAVE; - else if ( !Q_stricmp( flag[i], "random" ) ) + else if (!Q_stricmp(flag[i], "random")) *flags |= FX_RAND; - else if ( !Q_stricmp( flag[i], "clamp" ) ) + else if (!Q_stricmp(flag[i], "clamp")) *flags |= FX_CLAMP; - else - { // we have badness going on, but continue on in case there are any valid fields in here + else { // we have badness going on, but continue on in case there are any valid fields in here ok = false; } } @@ -324,13 +306,11 @@ bool CPrimitiveTemplate::ParseGroupFlags( const char *val, int *flags ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMin( const char *val ) -{ +bool CPrimitiveTemplate::ParseMin(const char *val) { vec3_t min; - if ( ParseVector( val, min, min ) == true ) - { - VectorCopy( min, mMin ); + if (ParseVector(val, min, min) == true) { + VectorCopy(min, mMin); // We assume that if a min is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -350,13 +330,11 @@ bool CPrimitiveTemplate::ParseMin( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseMax( const char *val ) -{ +bool CPrimitiveTemplate::ParseMax(const char *val) { vec3_t max; - if ( ParseVector( val, max, max ) == true ) - { - VectorCopy( max, mMax ); + if (ParseVector(val, max, max) == true) { + VectorCopy(max, mMax); // We assume that if a max is being set that we are using physics and a bounding box mFlags |= (FX_USE_BBOX | FX_APPLY_PHYSICS); @@ -376,13 +354,11 @@ bool CPrimitiveTemplate::ParseMax( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLife( const char *val ) -{ +bool CPrimitiveTemplate::ParseLife(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mLife.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mLife.SetRange(min, max); return true; } @@ -399,13 +375,11 @@ bool CPrimitiveTemplate::ParseLife( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDelay( const char *val ) -{ +bool CPrimitiveTemplate::ParseDelay(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSpawnDelay.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSpawnDelay.SetRange(min, max); return true; } @@ -422,13 +396,11 @@ bool CPrimitiveTemplate::ParseDelay( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseCount( const char *val ) -{ +bool CPrimitiveTemplate::ParseCount(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSpawnCount.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSpawnCount.SetRange(min, max); return true; } @@ -445,13 +417,11 @@ bool CPrimitiveTemplate::ParseCount( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseElasticity( const char *val ) -{ +bool CPrimitiveTemplate::ParseElasticity(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mElasticity.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mElasticity.SetRange(min, max); // We assume that if elasticity is set that we are using physics, but don't assume we are // using a bounding box unless a min/max are explicitly set @@ -472,15 +442,13 @@ bool CPrimitiveTemplate::ParseElasticity( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin1( const char *val ) -{ +bool CPrimitiveTemplate::ParseOrigin1(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin1X.SetRange( min[0], max[0] ); - mOrigin1Y.SetRange( min[1], max[1] ); - mOrigin1Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin1X.SetRange(min[0], max[0]); + mOrigin1Y.SetRange(min[1], max[1]); + mOrigin1Z.SetRange(min[2], max[2]); return true; } @@ -497,15 +465,13 @@ bool CPrimitiveTemplate::ParseOrigin1( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseOrigin2( const char *val ) -{ +bool CPrimitiveTemplate::ParseOrigin2(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mOrigin2X.SetRange( min[0], max[0] ); - mOrigin2Y.SetRange( min[1], max[1] ); - mOrigin2Z.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mOrigin2X.SetRange(min[0], max[0]); + mOrigin2Y.SetRange(min[1], max[1]); + mOrigin2Z.SetRange(min[2], max[2]); return true; } @@ -522,13 +488,11 @@ bool CPrimitiveTemplate::ParseOrigin2( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRadius( const char *val ) -{ +bool CPrimitiveTemplate::ParseRadius(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mRadius.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mRadius.SetRange(min, max); return true; } @@ -545,13 +509,11 @@ bool CPrimitiveTemplate::ParseRadius( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseHeight( const char *val ) -{ +bool CPrimitiveTemplate::ParseHeight(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mHeight.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mHeight.SetRange(min, max); return true; } @@ -568,13 +530,11 @@ bool CPrimitiveTemplate::ParseHeight( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseWindModifier( const char *val ) -{ +bool CPrimitiveTemplate::ParseWindModifier(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mWindModifier.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mWindModifier.SetRange(min, max); return true; } @@ -591,13 +551,11 @@ bool CPrimitiveTemplate::ParseWindModifier( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotation( const char *val ) -{ +bool CPrimitiveTemplate::ParseRotation(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == qtrue ) - { - mRotation.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == qtrue) { + mRotation.SetRange(min, max); return true; } @@ -614,13 +572,11 @@ bool CPrimitiveTemplate::ParseRotation( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRotationDelta( const char *val ) -{ +bool CPrimitiveTemplate::ParseRotationDelta(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == qtrue ) - { - mRotationDelta.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == qtrue) { + mRotationDelta.SetRange(min, max); return true; } @@ -637,15 +593,13 @@ bool CPrimitiveTemplate::ParseRotationDelta( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngle( const char *val ) -{ +bool CPrimitiveTemplate::ParseAngle(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1.SetRange( min[0], max[0] ); - mAngle2.SetRange( min[1], max[1] ); - mAngle3.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1.SetRange(min[0], max[0]); + mAngle2.SetRange(min[1], max[1]); + mAngle3.SetRange(min[2], max[2]); return true; } @@ -662,15 +616,13 @@ bool CPrimitiveTemplate::ParseAngle( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAngleDelta( const char *val ) -{ +bool CPrimitiveTemplate::ParseAngleDelta(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAngle1Delta.SetRange( min[0], max[0] ); - mAngle2Delta.SetRange( min[1], max[1] ); - mAngle3Delta.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAngle1Delta.SetRange(min[0], max[0]); + mAngle2Delta.SetRange(min[1], max[1]); + mAngle3Delta.SetRange(min[2], max[2]); return true; } @@ -687,15 +639,13 @@ bool CPrimitiveTemplate::ParseAngleDelta( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVelocity( const char *val ) -{ +bool CPrimitiveTemplate::ParseVelocity(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mVelX.SetRange( min[0], max[0] ); - mVelY.SetRange( min[1], max[1] ); - mVelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mVelX.SetRange(min[0], max[0]); + mVelY.SetRange(min[1], max[1]); + mVelZ.SetRange(min[2], max[2]); return true; } @@ -713,59 +663,55 @@ bool CPrimitiveTemplate::ParseVelocity( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseFlags( const char *val ) -{ - char flag[][32] = {"\0","\0","\0","\0","\0","\0","\0"}; - bool ok = true; +bool CPrimitiveTemplate::ParseFlags(const char *val) { + char flag[][32] = {"\0", "\0", "\0", "\0", "\0", "\0", "\0"}; + bool ok = true; // For a primitive, really you probably only have two or less flags set - int v = sscanf( val, "%s %s %s %s %s %s %s", flag[0], flag[1], flag[2], flag[3], flag[4], flag[5], flag[6] ); + int v = sscanf(val, "%s %s %s %s %s %s %s", flag[0], flag[1], flag[2], flag[3], flag[4], flag[5], flag[6]); - for ( int i = 0; i < 7; i++ ) - { - if ( i + 1 > v ) - { + for (int i = 0; i < 7; i++) { + if (i + 1 > v) { return true; } - if ( !Q_stricmp( flag[i], "useModel" )) + if (!Q_stricmp(flag[i], "useModel")) mFlags |= FX_ATTACHED_MODEL; - else if ( !Q_stricmp( flag[i], "useBBox" )) + else if (!Q_stricmp(flag[i], "useBBox")) mFlags |= FX_USE_BBOX; - else if ( !Q_stricmp( flag[i], "usePhysics" )) + else if (!Q_stricmp(flag[i], "usePhysics")) mFlags |= FX_APPLY_PHYSICS; - else if ( !Q_stricmp( flag[i], "expensivePhysics" )) + else if (!Q_stricmp(flag[i], "expensivePhysics")) mFlags |= FX_EXPENSIVE_PHYSICS; - //rww - begin g2 stuff - else if ( !Q_stricmp( flag[i], "ghoul2Collision" )) - mFlags |= (FX_GHOUL2_TRACE|FX_APPLY_PHYSICS|FX_EXPENSIVE_PHYSICS); - else if ( !Q_stricmp( flag[i], "ghoul2Decals" )) + // rww - begin g2 stuff + else if (!Q_stricmp(flag[i], "ghoul2Collision")) + mFlags |= (FX_GHOUL2_TRACE | FX_APPLY_PHYSICS | FX_EXPENSIVE_PHYSICS); + else if (!Q_stricmp(flag[i], "ghoul2Decals")) mFlags |= FX_GHOUL2_DECALS; - //rww - end - else if ( !Q_stricmp( flag[i], "impactKills" )) + // rww - end + else if (!Q_stricmp(flag[i], "impactKills")) mFlags |= FX_KILL_ON_IMPACT; - else if ( !Q_stricmp( flag[i], "impactFx" )) + else if (!Q_stricmp(flag[i], "impactFx")) mFlags |= FX_IMPACT_RUNS_FX; - else if ( !Q_stricmp( flag[i], "deathFx" )) + else if (!Q_stricmp(flag[i], "deathFx")) mFlags |= FX_DEATH_RUNS_FX; - else if ( !Q_stricmp( flag[i], "useAlpha" )) + else if (!Q_stricmp(flag[i], "useAlpha")) mFlags |= FX_USE_ALPHA; - else if ( !Q_stricmp( flag[i], "emitFx" )) + else if (!Q_stricmp(flag[i], "emitFx")) mFlags |= FX_EMIT_FX; - else if ( !Q_stricmp( flag[i], "depthHack" )) + else if (!Q_stricmp(flag[i], "depthHack")) mFlags |= FX_DEPTH_HACK; - else if ( !Q_stricmp( flag[i], "relative" )) + else if (!Q_stricmp(flag[i], "relative")) mFlags |= FX_RELATIVE; - else if ( !Q_stricmp( flag[i], "setShaderTime" )) + else if (!Q_stricmp(flag[i], "setShaderTime")) mFlags |= FX_SET_SHADER_TIME; - else if ( !Q_stricmp( flag[i], "paperPhysics" )) - mFlags |= FX_PAPER_PHYSICS; //warning! shared flag. You use this with a cylinder and you can expect evilness to ensue - else if ( !Q_stricmp( flag[i], "localizedFlash" )) - mFlags |= FX_LOCALIZED_FLASH; //warning! shared flag. You use this with a cylinder and you can expect evilness to ensue - else if ( !Q_stricmp( flag[i], "playerView" )) - mFlags |= FX_PLAYER_VIEW; //warning! shared flag. You use this with a cylinder and you can expect evilness to ensue - else - { // we have badness going on, but continue on in case there are any valid fields in here + else if (!Q_stricmp(flag[i], "paperPhysics")) + mFlags |= FX_PAPER_PHYSICS; // warning! shared flag. You use this with a cylinder and you can expect evilness to ensue + else if (!Q_stricmp(flag[i], "localizedFlash")) + mFlags |= FX_LOCALIZED_FLASH; // warning! shared flag. You use this with a cylinder and you can expect evilness to ensue + else if (!Q_stricmp(flag[i], "playerView")) + mFlags |= FX_PLAYER_VIEW; // warning! shared flag. You use this with a cylinder and you can expect evilness to ensue + else { // we have badness going on, but continue on in case there are any valid fields in here ok = false; } } @@ -784,51 +730,47 @@ bool CPrimitiveTemplate::ParseFlags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSpawnFlags( const char *val ) -{ - char flag[][32] = {"\0","\0","\0","\0","\0","\0","\0"}; - bool ok = true; +bool CPrimitiveTemplate::ParseSpawnFlags(const char *val) { + char flag[][32] = {"\0", "\0", "\0", "\0", "\0", "\0", "\0"}; + bool ok = true; // For a primitive, really you probably only have two or less flags set - int v = sscanf( val, "%s %s %s %s %s %s %s", flag[0], flag[1], flag[2], flag[3], flag[4], flag[5], flag[6] ); + int v = sscanf(val, "%s %s %s %s %s %s %s", flag[0], flag[1], flag[2], flag[3], flag[4], flag[5], flag[6]); - for ( int i = 0; i < 7; i++ ) - { - if ( i + 1 > v ) - { + for (int i = 0; i < 7; i++) { + if (i + 1 > v) { return true; } - if ( !Q_stricmp( flag[i], "org2fromTrace" ) ) + if (!Q_stricmp(flag[i], "org2fromTrace")) mSpawnFlags |= FX_ORG2_FROM_TRACE; - else if ( !Q_stricmp( flag[i], "traceImpactFx" ) ) + else if (!Q_stricmp(flag[i], "traceImpactFx")) mSpawnFlags |= FX_TRACE_IMPACT_FX; - else if ( !Q_stricmp( flag[i], "org2isOffset" ) ) + else if (!Q_stricmp(flag[i], "org2isOffset")) mSpawnFlags |= FX_ORG2_IS_OFFSET; - else if ( !Q_stricmp( flag[i], "cheapOrgCalc" ) ) + else if (!Q_stricmp(flag[i], "cheapOrgCalc")) mSpawnFlags |= FX_CHEAP_ORG_CALC; - else if ( !Q_stricmp( flag[i], "cheapOrg2Calc" ) ) + else if (!Q_stricmp(flag[i], "cheapOrg2Calc")) mSpawnFlags |= FX_CHEAP_ORG2_CALC; - else if ( !Q_stricmp( flag[i], "absoluteVel" ) ) + else if (!Q_stricmp(flag[i], "absoluteVel")) mSpawnFlags |= FX_VEL_IS_ABSOLUTE; - else if ( !Q_stricmp( flag[i], "absoluteAccel" ) ) + else if (!Q_stricmp(flag[i], "absoluteAccel")) mSpawnFlags |= FX_ACCEL_IS_ABSOLUTE; - else if ( !Q_stricmp( flag[i], "orgOnSphere" ) ) // sphere/ellipsoid + else if (!Q_stricmp(flag[i], "orgOnSphere")) // sphere/ellipsoid mSpawnFlags |= FX_ORG_ON_SPHERE; - else if ( !Q_stricmp( flag[i], "orgOnCylinder" ) ) // cylinder/disk + else if (!Q_stricmp(flag[i], "orgOnCylinder")) // cylinder/disk mSpawnFlags |= FX_ORG_ON_CYLINDER; - else if ( !Q_stricmp( flag[i], "axisFromSphere" ) ) + else if (!Q_stricmp(flag[i], "axisFromSphere")) mSpawnFlags |= FX_AXIS_FROM_SPHERE; - else if ( !Q_stricmp( flag[i], "randrotaroundfwd" ) ) + else if (!Q_stricmp(flag[i], "randrotaroundfwd")) mSpawnFlags |= FX_RAND_ROT_AROUND_FWD; - else if ( !Q_stricmp( flag[i], "evenDistribution" ) ) + else if (!Q_stricmp(flag[i], "evenDistribution")) mSpawnFlags |= FX_EVEN_DISTRIBUTION; - else if ( !Q_stricmp( flag[i], "rgbComponentInterpolation" ) ) + else if (!Q_stricmp(flag[i], "rgbComponentInterpolation")) mSpawnFlags |= FX_RGB_COMPONENT_INTERP; - else if ( !Q_stricmp( flag[i], "affectedByWind" ) ) + else if (!Q_stricmp(flag[i], "affectedByWind")) mSpawnFlags |= FX_AFFECTED_BY_WIND; - else - { // we have badness going on, but continue on in case there are any valid fields in here + else { // we have badness going on, but continue on in case there are any valid fields in here ok = false; } } @@ -836,24 +778,17 @@ bool CPrimitiveTemplate::ParseSpawnFlags( const char *val ) return ok; } - - -bool CPrimitiveTemplate::ParseMaterialImpact(const char *val) -{ - if (!Q_stricmp(val, "shellsound")) - { +bool CPrimitiveTemplate::ParseMaterialImpact(const char *val) { + if (!Q_stricmp(val, "shellsound")) { mMatImpactFX = MATIMPACTFX_SHELLSOUND; - } - else - { + } else { mMatImpactFX = MATIMPACTFX_NONE; - theFxHelper.Print( "CPrimitiveTemplate::ParseMaterialImpact -- unknown materialImpact type!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseMaterialImpact -- unknown materialImpact type!\n"); return false; } return true; } - //------------------------------------------------------ // ParseAcceleration // Reads in a ranged acceleration field in vector format @@ -864,15 +799,13 @@ bool CPrimitiveTemplate::ParseMaterialImpact(const char *val) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAcceleration( const char *val ) -{ +bool CPrimitiveTemplate::ParseAcceleration(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mAccelX.SetRange( min[0], max[0] ); - mAccelY.SetRange( min[1], max[1] ); - mAccelZ.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mAccelX.SetRange(min[0], max[0]); + mAccelY.SetRange(min[1], max[1]); + mAccelZ.SetRange(min[2], max[2]); return true; } @@ -889,13 +822,11 @@ bool CPrimitiveTemplate::ParseAcceleration( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseGravity( const char *val ) -{ +bool CPrimitiveTemplate::ParseGravity(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mGravity.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mGravity.SetRange(min, max); return true; } @@ -914,13 +845,11 @@ bool CPrimitiveTemplate::ParseGravity( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDensity( const char *val ) -{ +bool CPrimitiveTemplate::ParseDensity(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mDensity.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mDensity.SetRange(min, max); return true; } @@ -940,13 +869,11 @@ bool CPrimitiveTemplate::ParseDensity( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseVariance( const char *val ) -{ +bool CPrimitiveTemplate::ParseVariance(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mVariance.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mVariance.SetRange(min, max); return true; } @@ -963,15 +890,13 @@ bool CPrimitiveTemplate::ParseVariance( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBStart( const char *val ) -{ +bool CPrimitiveTemplate::ParseRGBStart(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedStart.SetRange( min[0], max[0] ); - mGreenStart.SetRange( min[1], max[1] ); - mBlueStart.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedStart.SetRange(min[0], max[0]); + mGreenStart.SetRange(min[1], max[1]); + mBlueStart.SetRange(min[2], max[2]); return true; } @@ -988,15 +913,13 @@ bool CPrimitiveTemplate::ParseRGBStart( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBEnd( const char *val ) -{ +bool CPrimitiveTemplate::ParseRGBEnd(const char *val) { vec3_t min, max; - if ( ParseVector( val, min, max ) == true ) - { - mRedEnd.SetRange( min[0], max[0] ); - mGreenEnd.SetRange( min[1], max[1] ); - mBlueEnd.SetRange( min[2], max[2] ); + if (ParseVector(val, min, max) == true) { + mRedEnd.SetRange(min[0], max[0]); + mGreenEnd.SetRange(min[1], max[1]); + mBlueEnd.SetRange(min[2], max[2]); return true; } @@ -1013,13 +936,11 @@ bool CPrimitiveTemplate::ParseRGBEnd( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBParm( const char *val ) -{ +bool CPrimitiveTemplate::ParseRGBParm(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mRGBParm.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mRGBParm.SetRange(min, max); return true; } @@ -1036,14 +957,12 @@ bool CPrimitiveTemplate::ParseRGBParm( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGBFlags( const char *val ) -{ +bool CPrimitiveTemplate::ParseRGBFlags(const char *val) { int flags; - if ( ParseGroupFlags( val, &flags ) == true ) - { + if (ParseGroupFlags(val, &flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_RGB_SHIFT ); + mFlags |= (flags << FX_RGB_SHIFT); return true; } @@ -1060,13 +979,11 @@ bool CPrimitiveTemplate::ParseRGBFlags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaStart( const char *val ) -{ +bool CPrimitiveTemplate::ParseAlphaStart(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mAlphaStart.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mAlphaStart.SetRange(min, max); return true; } @@ -1083,13 +1000,11 @@ bool CPrimitiveTemplate::ParseAlphaStart( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaEnd( const char *val ) -{ +bool CPrimitiveTemplate::ParseAlphaEnd(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mAlphaEnd.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mAlphaEnd.SetRange(min, max); return true; } @@ -1106,13 +1021,11 @@ bool CPrimitiveTemplate::ParseAlphaEnd( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaParm( const char *val ) -{ +bool CPrimitiveTemplate::ParseAlphaParm(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mAlphaParm.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mAlphaParm.SetRange(min, max); return true; } @@ -1129,14 +1042,12 @@ bool CPrimitiveTemplate::ParseAlphaParm( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlphaFlags( const char *val ) -{ +bool CPrimitiveTemplate::ParseAlphaFlags(const char *val) { int flags; - if ( ParseGroupFlags( val, &flags ) == true ) - { + if (ParseGroupFlags(val, &flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_ALPHA_SHIFT ); + mFlags |= (flags << FX_ALPHA_SHIFT); return true; } @@ -1153,13 +1064,11 @@ bool CPrimitiveTemplate::ParseAlphaFlags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeStart( const char *val ) -{ +bool CPrimitiveTemplate::ParseSizeStart(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSizeStart.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSizeStart.SetRange(min, max); return true; } @@ -1176,13 +1085,11 @@ bool CPrimitiveTemplate::ParseSizeStart( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeEnd( const char *val ) -{ +bool CPrimitiveTemplate::ParseSizeEnd(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSizeEnd.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSizeEnd.SetRange(min, max); return true; } @@ -1199,13 +1106,11 @@ bool CPrimitiveTemplate::ParseSizeEnd( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeParm( const char *val ) -{ +bool CPrimitiveTemplate::ParseSizeParm(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSizeParm.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSizeParm.SetRange(min, max); return true; } @@ -1222,14 +1127,12 @@ bool CPrimitiveTemplate::ParseSizeParm( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSizeFlags( const char *val ) -{ +bool CPrimitiveTemplate::ParseSizeFlags(const char *val) { int flags; - if ( ParseGroupFlags( val, &flags ) == true ) - { + if (ParseGroupFlags(val, &flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE_SHIFT ); + mFlags |= (flags << FX_SIZE_SHIFT); return true; } @@ -1246,13 +1149,11 @@ bool CPrimitiveTemplate::ParseSizeFlags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Start( const char *val ) -{ +bool CPrimitiveTemplate::ParseSize2Start(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSize2Start.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSize2Start.SetRange(min, max); return true; } @@ -1269,13 +1170,11 @@ bool CPrimitiveTemplate::ParseSize2Start( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2End( const char *val ) -{ +bool CPrimitiveTemplate::ParseSize2End(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSize2End.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSize2End.SetRange(min, max); return true; } @@ -1292,13 +1191,11 @@ bool CPrimitiveTemplate::ParseSize2End( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Parm( const char *val ) -{ +bool CPrimitiveTemplate::ParseSize2Parm(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mSize2Parm.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mSize2Parm.SetRange(min, max); return true; } @@ -1315,14 +1212,12 @@ bool CPrimitiveTemplate::ParseSize2Parm( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2Flags( const char *val ) -{ +bool CPrimitiveTemplate::ParseSize2Flags(const char *val) { int flags; - if ( ParseGroupFlags( val, &flags ) == true ) - { + if (ParseGroupFlags(val, &flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_SIZE2_SHIFT ); + mFlags |= (flags << FX_SIZE2_SHIFT); return true; } @@ -1339,13 +1234,11 @@ bool CPrimitiveTemplate::ParseSize2Flags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthStart( const char *val ) -{ +bool CPrimitiveTemplate::ParseLengthStart(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mLengthStart.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mLengthStart.SetRange(min, max); return true; } @@ -1362,13 +1255,11 @@ bool CPrimitiveTemplate::ParseLengthStart( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthEnd( const char *val ) -{ +bool CPrimitiveTemplate::ParseLengthEnd(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mLengthEnd.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mLengthEnd.SetRange(min, max); return true; } @@ -1385,13 +1276,11 @@ bool CPrimitiveTemplate::ParseLengthEnd( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthParm( const char *val ) -{ +bool CPrimitiveTemplate::ParseLengthParm(const char *val) { float min, max; - if ( ParseFloat( val, &min, &max ) == true ) - { - mLengthParm.SetRange( min, max ); + if (ParseFloat(val, &min, &max) == true) { + mLengthParm.SetRange(min, max); return true; } @@ -1408,14 +1297,12 @@ bool CPrimitiveTemplate::ParseLengthParm( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLengthFlags( const char *val ) -{ +bool CPrimitiveTemplate::ParseLengthFlags(const char *val) { int flags; - if ( ParseGroupFlags( val, &flags ) == true ) - { + if (ParseGroupFlags(val, &flags) == true) { // Convert our generic flag values into type specific ones - mFlags |= ( flags << FX_LENGTH_SHIFT ); + mFlags |= (flags << FX_LENGTH_SHIFT); return true; } @@ -1432,41 +1319,33 @@ bool CPrimitiveTemplate::ParseLengthFlags( const char *val ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseShaders( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseShaders(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxHelper.RegisterShader( val ); - mMediaHandles.AddHandle( handle ); + handle = theFxHelper.RegisterShader(val); + mMediaHandles.AddHandle(handle); list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxHelper.RegisterShader( val ); - mMediaHandles.AddHandle( handle ); - } - else - { + if (val) { + handle = theFxHelper.RegisterShader(val); + mMediaHandles.AddHandle(handle); + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseShaders called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseShaders called with an empty list!\n"); return false; } } @@ -1484,41 +1363,33 @@ bool CPrimitiveTemplate::ParseShaders( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSounds( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseSounds(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxHelper.RegisterSound( val ); - mMediaHandles.AddHandle( handle ); + handle = theFxHelper.RegisterSound(val); + mMediaHandles.AddHandle(handle); list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxHelper.RegisterSound( val ); - mMediaHandles.AddHandle( handle ); - } - else - { + if (val) { + handle = theFxHelper.RegisterSound(val); + mMediaHandles.AddHandle(handle); + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseSounds called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseSounds called with an empty list!\n"); return false; } } @@ -1536,41 +1407,33 @@ bool CPrimitiveTemplate::ParseSounds( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseModels( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseModels(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxHelper.RegisterModel( val ); - mMediaHandles.AddHandle( handle ); + handle = theFxHelper.RegisterModel(val); + mMediaHandles.AddHandle(handle); list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxHelper.RegisterModel( val ); - mMediaHandles.AddHandle( handle ); - } - else - { + if (val) { + handle = theFxHelper.RegisterModel(val); + mMediaHandles.AddHandle(handle); + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseModels called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseModels called with an empty list!\n"); return false; } } @@ -1590,58 +1453,44 @@ bool CPrimitiveTemplate::ParseModels( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseImpactFxStrings( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseImpactFxStrings(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxScheduler.RegisterEffect( val ); + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mImpactFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Impact effect file not found.\n" ); + if (handle) { + mImpactFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Impact effect file not found.\n"); return false; } list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxScheduler.RegisterEffect( val ); + if (val) { + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mImpactFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Impact effect file not found.\n" ); + if (handle) { + mImpactFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Impact effect file not found.\n"); return false; } - } - else - { + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseImpactFxStrings called with an empty list!\n"); return false; } } @@ -1661,58 +1510,44 @@ bool CPrimitiveTemplate::ParseImpactFxStrings( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseDeathFxStrings( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseDeathFxStrings(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxScheduler.RegisterEffect( val ); + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mDeathFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Death effect file not found.\n" ); + if (handle) { + mDeathFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Death effect file not found.\n"); return false; } list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxScheduler.RegisterEffect( val ); + if (val) { + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mDeathFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Death effect file not found.\n" ); + if (handle) { + mDeathFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Death effect file not found.\n"); return false; } - } - else - { + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseDeathFxStrings called with an empty list!\n"); return false; } } @@ -1732,58 +1567,44 @@ bool CPrimitiveTemplate::ParseDeathFxStrings( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseEmitterFxStrings( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParseEmitterFxStrings(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxScheduler.RegisterEffect( val ); + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mEmitterFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Emitter effect file not found.\n" ); + if (handle) { + mEmitterFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Emitter effect file not found.\n"); return false; } list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxScheduler.RegisterEffect( val ); + if (val) { + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mEmitterFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Emitter effect file not found.\n" ); + if (handle) { + mEmitterFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Emitter effect file not found.\n"); return false; } - } - else - { + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParseEmitterFxStrings called with an empty list!\n"); return false; } } @@ -1803,58 +1624,44 @@ bool CPrimitiveTemplate::ParseEmitterFxStrings( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePlayFxStrings( CGPValue *grp ) -{ - const char *val; - int handle; +bool CPrimitiveTemplate::ParsePlayFxStrings(CGPValue *grp) { + const char *val; + int handle; - if ( grp->IsList() ) - { + if (grp->IsList()) { // If we are a list we have to do separate processing CGPObject *list = grp->GetList(); - while ( list ) - { + while (list) { // name is actually the value contained in the list val = list->GetName(); - handle = theFxScheduler.RegisterEffect( val ); + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mPlayFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Effect file not found.\n" ); + if (handle) { + mPlayFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Effect file not found.\n"); return false; } list = (CGPValue *)list->GetNext(); } - } - else - { + } else { // Let's get a value val = grp->GetTopValue(); - if ( val ) - { - handle = theFxScheduler.RegisterEffect( val ); + if (val) { + handle = theFxScheduler.RegisterEffect(val); - if ( handle ) - { - mPlayFxHandles.AddHandle( handle ); - } - else - { - theFxHelper.Print( "FxTemplate: Effect file not found.\n" ); + if (handle) { + mPlayFxHandles.AddHandle(handle); + } else { + theFxHelper.Print("FxTemplate: Effect file not found.\n"); return false; } - } - else - { + } else { // empty "list" - theFxHelper.Print( "CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n" ); + theFxHelper.Print("CPrimitiveTemplate::ParsePlayFxStrings called with an empty list!\n"); return false; } } @@ -1873,32 +1680,30 @@ bool CPrimitiveTemplate::ParsePlayFxStrings( CGPValue *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseRGB( CGPGroup *grp ) -{ - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParseRGB(CGPGroup *grp) { + CGPValue *pairs; + const char *key; + const char *val; // Inside of the group, we should have a series of pairs pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // Let's get the key field key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "start" ) ) - ParseRGBStart( val ); - else if ( !Q_stricmp( key, "end" ) ) - ParseRGBEnd( val ); - else if ( !Q_stricmp( key, "parm" ) || !Q_stricmp( key, "parms" ) ) - ParseRGBParm( val ); - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" ) ) - ParseRGBFlags( val ); + if (!Q_stricmp(key, "start")) + ParseRGBStart(val); + else if (!Q_stricmp(key, "end")) + ParseRGBEnd(val); + else if (!Q_stricmp(key, "parm") || !Q_stricmp(key, "parms")) + ParseRGBParm(val); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseRGBFlags(val); else - theFxHelper.Print( "Unknown key parsing an RGB group: %s\n", key ); + theFxHelper.Print("Unknown key parsing an RGB group: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -1917,32 +1722,30 @@ bool CPrimitiveTemplate::ParseRGB( CGPGroup *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseAlpha( CGPGroup *grp ) -{ - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParseAlpha(CGPGroup *grp) { + CGPValue *pairs; + const char *key; + const char *val; // Inside of the group, we should have a series of pairs pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // Let's get the key field key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "start" ) ) - ParseAlphaStart( val ); - else if ( !Q_stricmp( key, "end" ) ) - ParseAlphaEnd( val ); - else if ( !Q_stricmp( key, "parm" ) || !Q_stricmp( key, "parms" ) ) - ParseAlphaParm( val ); - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" ) ) - ParseAlphaFlags( val ); + if (!Q_stricmp(key, "start")) + ParseAlphaStart(val); + else if (!Q_stricmp(key, "end")) + ParseAlphaEnd(val); + else if (!Q_stricmp(key, "parm") || !Q_stricmp(key, "parms")) + ParseAlphaParm(val); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseAlphaFlags(val); else - theFxHelper.Print( "Unknown key parsing an Alpha group: %s\n", key ); + theFxHelper.Print("Unknown key parsing an Alpha group: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -1961,32 +1764,30 @@ bool CPrimitiveTemplate::ParseAlpha( CGPGroup *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize( CGPGroup *grp ) -{ - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParseSize(CGPGroup *grp) { + CGPValue *pairs; + const char *key; + const char *val; // Inside of the group, we should have a series of pairs pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // Let's get the key field key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "start" ) ) - ParseSizeStart( val ); - else if ( !Q_stricmp( key, "end" ) ) - ParseSizeEnd( val ); - else if ( !Q_stricmp( key, "parm" ) || !Q_stricmp( key, "parms" ) ) - ParseSizeParm( val ); - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" ) ) - ParseSizeFlags( val ); + if (!Q_stricmp(key, "start")) + ParseSizeStart(val); + else if (!Q_stricmp(key, "end")) + ParseSizeEnd(val); + else if (!Q_stricmp(key, "parm") || !Q_stricmp(key, "parms")) + ParseSizeParm(val); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseSizeFlags(val); else - theFxHelper.Print( "Unknown key parsing a Size group: %s\n", key ); + theFxHelper.Print("Unknown key parsing a Size group: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -2005,32 +1806,30 @@ bool CPrimitiveTemplate::ParseSize( CGPGroup *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseSize2( CGPGroup *grp ) -{ - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParseSize2(CGPGroup *grp) { + CGPValue *pairs; + const char *key; + const char *val; // Inside of the group, we should have a series of pairs pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // Let's get the key field key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "start" ) ) - ParseSize2Start( val ); - else if ( !Q_stricmp( key, "end" ) ) - ParseSize2End( val ); - else if ( !Q_stricmp( key, "parm" ) || !Q_stricmp( key, "parms" ) ) - ParseSize2Parm( val ); - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" ) ) - ParseSize2Flags( val ); + if (!Q_stricmp(key, "start")) + ParseSize2Start(val); + else if (!Q_stricmp(key, "end")) + ParseSize2End(val); + else if (!Q_stricmp(key, "parm") || !Q_stricmp(key, "parms")) + ParseSize2Parm(val); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseSize2Flags(val); else - theFxHelper.Print( "Unknown key parsing a Size2 group: %s\n", key ); + theFxHelper.Print("Unknown key parsing a Size2 group: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -2049,32 +1848,30 @@ bool CPrimitiveTemplate::ParseSize2( CGPGroup *grp ) // return: // success of parse operation. //------------------------------------------------------ -bool CPrimitiveTemplate::ParseLength( CGPGroup *grp ) -{ - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParseLength(CGPGroup *grp) { + CGPValue *pairs; + const char *key; + const char *val; // Inside of the group, we should have a series of pairs pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // Let's get the key field key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "start" )) - ParseLengthStart( val ); - else if ( !Q_stricmp( key, "end" )) - ParseLengthEnd( val ); - else if ( !Q_stricmp( key, "parm" ) || !Q_stricmp( key, "parms" )) - ParseLengthParm( val ); - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" )) - ParseLengthFlags( val ); + if (!Q_stricmp(key, "start")) + ParseLengthStart(val); + else if (!Q_stricmp(key, "end")) + ParseLengthEnd(val); + else if (!Q_stricmp(key, "parm") || !Q_stricmp(key, "parms")) + ParseLengthParm(val); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseLengthFlags(val); else - theFxHelper.Print( "Unknown key parsing a Length group: %s\n", key ); + theFxHelper.Print("Unknown key parsing a Length group: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -2085,95 +1882,91 @@ bool CPrimitiveTemplate::ParseLength( CGPGroup *grp ) // Parse a primitive, apply defaults first, grab any base level // key pairs, then process any sub groups we may contain. //------------------------------------------------------ -bool CPrimitiveTemplate::ParsePrimitive( CGPGroup *grp ) -{ - CGPGroup *subGrp; - CGPValue *pairs; - const char *key; - const char *val; +bool CPrimitiveTemplate::ParsePrimitive(CGPGroup *grp) { + CGPGroup *subGrp; + CGPValue *pairs; + const char *key; + const char *val; // Lets work with the pairs first pairs = grp->GetPairs(); - while( pairs ) - { + while (pairs) { // the fields key = pairs->GetName(); val = pairs->GetTopValue(); // Huge Q_stricmp lists suxor - if ( !Q_stricmp( key, "count" ) ) - ParseCount( val ); - else if ( !Q_stricmp( key, "shaders" ) || !Q_stricmp( key, "shader" ) ) - ParseShaders( pairs ); - else if ( !Q_stricmp( key, "models" ) || !Q_stricmp( key, "model" ) ) - ParseModels( pairs ); - else if ( !Q_stricmp( key, "sounds" ) || !Q_stricmp( key, "sound" ) ) - ParseSounds( pairs ); - else if ( !Q_stricmp( key, "impactfx" ) ) - ParseImpactFxStrings( pairs ); - else if ( !Q_stricmp( key, "deathfx" ) ) - ParseDeathFxStrings( pairs ); - else if ( !Q_stricmp( key, "emitfx" ) ) - ParseEmitterFxStrings( pairs ); - else if ( !Q_stricmp( key, "playfx" ) ) - ParsePlayFxStrings( pairs ); - else if ( !Q_stricmp( key, "life" ) ) - ParseLife( val ); - else if ( !Q_stricmp( key, "delay" ) ) - ParseDelay( val ); - else if ( !Q_stricmp( key, "cullrange" ) ) { -// mCullRange = atoi( val ); -// mCullRange *= mCullRange; // square it now so we don't have to square every time we compare - } - else if ( !Q_stricmp( key, "bounce" ) || !Q_stricmp( key, "intensity" ) ) // me==bad for reusing this...but it shouldn't hurt anything) - ParseElasticity( val ); - else if ( !Q_stricmp( key, "min" ) ) - ParseMin( val ); - else if ( !Q_stricmp( key, "max" ) ) - ParseMax( val ); - else if ( !Q_stricmp( key, "angle" ) || !Q_stricmp( key, "angles" ) ) - ParseAngle( val ); - else if ( !Q_stricmp( key, "angleDelta" ) ) - ParseAngleDelta( val ); - else if ( !Q_stricmp( key, "velocity" ) || !Q_stricmp( key, "vel" ) ) - ParseVelocity( val ); - else if ( !Q_stricmp( key, "acceleration" ) || !Q_stricmp( key, "accel" ) ) - ParseAcceleration( val ); - else if ( !Q_stricmp( key, "gravity" ) ) - ParseGravity( val ); - else if ( !Q_stricmp( key, "density" ) ) - ParseDensity( val ); - else if ( !Q_stricmp( key, "variance" ) ) - ParseVariance( val ); - else if ( !Q_stricmp( key, "origin" ) ) - ParseOrigin1( val ); - else if ( !Q_stricmp( key, "origin2" ) ) - ParseOrigin2( val ); - else if ( !Q_stricmp( key, "radius" ) ) // part of ellipse/cylinder calcs. - ParseRadius( val ); - else if ( !Q_stricmp( key, "height" ) ) // part of ellipse/cylinder calcs. - ParseHeight( val ); - else if ( !Q_stricmp( key, "wind" ) ) - ParseWindModifier( val ); - else if ( !Q_stricmp( key, "rotation" ) ) - ParseRotation( val ); - else if ( !Q_stricmp( key, "rotationDelta" ) ) - ParseRotationDelta( val ); + if (!Q_stricmp(key, "count")) + ParseCount(val); + else if (!Q_stricmp(key, "shaders") || !Q_stricmp(key, "shader")) + ParseShaders(pairs); + else if (!Q_stricmp(key, "models") || !Q_stricmp(key, "model")) + ParseModels(pairs); + else if (!Q_stricmp(key, "sounds") || !Q_stricmp(key, "sound")) + ParseSounds(pairs); + else if (!Q_stricmp(key, "impactfx")) + ParseImpactFxStrings(pairs); + else if (!Q_stricmp(key, "deathfx")) + ParseDeathFxStrings(pairs); + else if (!Q_stricmp(key, "emitfx")) + ParseEmitterFxStrings(pairs); + else if (!Q_stricmp(key, "playfx")) + ParsePlayFxStrings(pairs); + else if (!Q_stricmp(key, "life")) + ParseLife(val); + else if (!Q_stricmp(key, "delay")) + ParseDelay(val); + else if (!Q_stricmp(key, "cullrange")) { + // mCullRange = atoi( val ); + // mCullRange *= mCullRange; // square it now so we don't have to square every time we compare + } else if (!Q_stricmp(key, "bounce") || !Q_stricmp(key, "intensity")) // me==bad for reusing this...but it shouldn't hurt anything) + ParseElasticity(val); + else if (!Q_stricmp(key, "min")) + ParseMin(val); + else if (!Q_stricmp(key, "max")) + ParseMax(val); + else if (!Q_stricmp(key, "angle") || !Q_stricmp(key, "angles")) + ParseAngle(val); + else if (!Q_stricmp(key, "angleDelta")) + ParseAngleDelta(val); + else if (!Q_stricmp(key, "velocity") || !Q_stricmp(key, "vel")) + ParseVelocity(val); + else if (!Q_stricmp(key, "acceleration") || !Q_stricmp(key, "accel")) + ParseAcceleration(val); + else if (!Q_stricmp(key, "gravity")) + ParseGravity(val); + else if (!Q_stricmp(key, "density")) + ParseDensity(val); + else if (!Q_stricmp(key, "variance")) + ParseVariance(val); + else if (!Q_stricmp(key, "origin")) + ParseOrigin1(val); + else if (!Q_stricmp(key, "origin2")) + ParseOrigin2(val); + else if (!Q_stricmp(key, "radius")) // part of ellipse/cylinder calcs. + ParseRadius(val); + else if (!Q_stricmp(key, "height")) // part of ellipse/cylinder calcs. + ParseHeight(val); + else if (!Q_stricmp(key, "wind")) + ParseWindModifier(val); + else if (!Q_stricmp(key, "rotation")) + ParseRotation(val); + else if (!Q_stricmp(key, "rotationDelta")) + ParseRotationDelta(val); // these need to get passed on to the primitive - else if ( !Q_stricmp( key, "flags" ) || !Q_stricmp( key, "flag" ) ) - ParseFlags( val ); + else if (!Q_stricmp(key, "flags") || !Q_stricmp(key, "flag")) + ParseFlags(val); // these are used to spawn things in cool ways, but don't ever get passed on to prims. - else if ( !Q_stricmp( key, "spawnFlags" ) || !Q_stricmp( key, "spawnFlag" ) ) - ParseSpawnFlags( val ); - else if ( !Q_stricmp( key, "name" ) ) { - if ( val ) // just stash the descriptive name of the primitive - strcpy( mName, val ); - } - else if ( !Q_stricmp( key, "materialImpact" ) ) - ParseMaterialImpact( val ); + else if (!Q_stricmp(key, "spawnFlags") || !Q_stricmp(key, "spawnFlag")) + ParseSpawnFlags(val); + else if (!Q_stricmp(key, "name")) { + if (val) // just stash the descriptive name of the primitive + strcpy(mName, val); + } else if (!Q_stricmp(key, "materialImpact")) + ParseMaterialImpact(val); else - theFxHelper.Print( "Unknown key parsing an effect primitive: %s\n", key ); + theFxHelper.Print("Unknown key parsing an effect primitive: %s\n", key); pairs = (CGPValue *)pairs->GetNext(); } @@ -2181,22 +1974,21 @@ bool CPrimitiveTemplate::ParsePrimitive( CGPGroup *grp ) subGrp = grp->GetSubGroups(); // Lets chomp on the groups now - while ( subGrp ) - { + while (subGrp) { key = subGrp->GetName(); - if ( !Q_stricmp( key, "rgb" ) ) - ParseRGB( subGrp ); - else if ( !Q_stricmp( key, "alpha" ) ) - ParseAlpha( subGrp ); - else if ( !Q_stricmp( key, "size" ) || !Q_stricmp( key, "width" ) ) - ParseSize( subGrp ); - else if ( !Q_stricmp( key, "size2" ) || !Q_stricmp( key, "width2" ) ) - ParseSize2( subGrp ); - else if ( !Q_stricmp( key, "length" ) || !Q_stricmp( key, "height" ) ) - ParseLength( subGrp ); + if (!Q_stricmp(key, "rgb")) + ParseRGB(subGrp); + else if (!Q_stricmp(key, "alpha")) + ParseAlpha(subGrp); + else if (!Q_stricmp(key, "size") || !Q_stricmp(key, "width")) + ParseSize(subGrp); + else if (!Q_stricmp(key, "size2") || !Q_stricmp(key, "width2")) + ParseSize2(subGrp); + else if (!Q_stricmp(key, "length") || !Q_stricmp(key, "height")) + ParseLength(subGrp); else - theFxHelper.Print( "Unknown group key parsing a particle: %s\n", key ); + theFxHelper.Print("Unknown group key parsing a particle: %s\n", key); subGrp = (CGPGroup *)subGrp->GetNext(); } diff --git a/codemp/client/FxUtil.cpp b/codemp/client/FxUtil.cpp index aaf29fd430..36f6a7a013 100644 --- a/codemp/client/FxUtil.cpp +++ b/codemp/client/FxUtil.cpp @@ -23,36 +23,32 @@ along with this program; if not, see . #include "client.h" #include "FxScheduler.h" -vec3_t WHITE = {1.0f, 1.0f, 1.0f}; +vec3_t WHITE = {1.0f, 1.0f, 1.0f}; -struct SEffectList -{ +struct SEffectList { CEffect *mEffect; - int mKillTime; - bool mPortal; + int mKillTime; + bool mPortal; }; -#define PI 3.14159f +#define PI 3.14159f -SEffectList effectList[MAX_EFFECTS]; -SEffectList *nextValidEffect; -SFxHelper theFxHelper; +SEffectList effectList[MAX_EFFECTS]; +SEffectList *nextValidEffect; +SFxHelper theFxHelper; -int activeFx = 0; -int drawnFx; -qboolean fxInitialized = qfalse; +int activeFx = 0; +int drawnFx; +qboolean fxInitialized = qfalse; //------------------------- // FX_Free // // Frees all FX //------------------------- -bool FX_Free( bool templates ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +bool FX_Free(bool templates) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -61,7 +57,7 @@ bool FX_Free( bool templates ) activeFx = 0; - theFxScheduler.Clean( templates ); + theFxScheduler.Clean(templates); return true; } @@ -70,12 +66,9 @@ bool FX_Free( bool templates ) // // Frees all active FX but leaves the templates //------------------------- -void FX_Stop( void ) -{ - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { - if ( effectList[i].mEffect ) - { +void FX_Stop(void) { + for (int i = 0; i < MAX_EFFECTS; i++) { + if (effectList[i].mEffect) { delete effectList[i].mEffect; } @@ -92,15 +85,12 @@ void FX_Stop( void ) // // Preps system for use //------------------------- -int FX_Init( refdef_t* refdef ) -{ -// FX_Free( true ); - if ( fxInitialized == qfalse ) - { +int FX_Init(refdef_t *refdef) { + // FX_Free( true ); + if (fxInitialized == qfalse) { fxInitialized = qtrue; - for ( int i = 0; i < MAX_EFFECTS; i++ ) - { + for (int i = 0; i < MAX_EFFECTS; i++) { effectList[i].mEffect = 0; } } @@ -118,16 +108,12 @@ int FX_Init( refdef_t* refdef ) return true; } -void FX_SetRefDef(refdef_t *refdef) -{ - theFxHelper.refdef = refdef; -} +void FX_SetRefDef(refdef_t *refdef) { theFxHelper.refdef = refdef; } //------------------------- // FX_FreeMember //------------------------- -static void FX_FreeMember( SEffectList *obj ) -{ +static void FX_FreeMember(SEffectList *obj) { obj->mEffect->Die(); delete obj->mEffect; obj->mEffect = 0; @@ -138,7 +124,6 @@ static void FX_FreeMember( SEffectList *obj ) activeFx--; } - //------------------------- // FX_GetValidEffect // @@ -147,32 +132,28 @@ static void FX_FreeMember( SEffectList *obj ) // Note - in the editor, this function may return NULL, indicating that all // effects are being stopped. //------------------------- -static SEffectList *FX_GetValidEffect() -{ - if ( nextValidEffect->mEffect == 0 ) - { +static SEffectList *FX_GetValidEffect() { + if (nextValidEffect->mEffect == 0) { return nextValidEffect; } - int i; - SEffectList *ef; + int i; + SEffectList *ef; // Blah..plow through the list till we find something that is currently untainted - for ( i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++ ) - { - if ( ef->mEffect == 0 ) - { + for (i = 0, ef = effectList; i < MAX_EFFECTS; i++, ef++) { + if (ef->mEffect == 0) { return ef; } } // report the error. #ifndef FINAL_BUILD - theFxHelper.Print( "FX system out of effects\n" ); + theFxHelper.Print("FX system out of effects\n"); #endif // Hmmm.. just trashing the first effect in the list is a poor approach - FX_FreeMember( &effectList[0] ); + FX_FreeMember(&effectList[0]); // Recursive call return nextValidEffect; @@ -183,344 +164,272 @@ static SEffectList *FX_GetValidEffect() // // Adds all fx to the view //------------------------- -void FX_Add( bool portal ) -{ - int i; - SEffectList *ef; +void FX_Add(bool portal) { + int i; + SEffectList *ef; drawnFx = 0; - int numFx = activeFx; //but stop when there can't be any more left! - for ( i = 0, ef = effectList; i < MAX_EFFECTS && numFx; i++, ef++ ) - { - if ( ef->mEffect != 0) - { + int numFx = activeFx; // but stop when there can't be any more left! + for (i = 0, ef = effectList; i < MAX_EFFECTS && numFx; i++, ef++) { + if (ef->mEffect != 0) { --numFx; - if (portal != ef->mPortal) - { - continue; //this one does not render in this scene + if (portal != ef->mPortal) { + continue; // this one does not render in this scene } // Effect is active - if ( theFxHelper.mTime > ef->mKillTime ) - { + if (theFxHelper.mTime > ef->mKillTime) { // Clean up old effects, calling any death effects as needed // this flag just has to be cleared otherwise death effects might not happen correctly - ef->mEffect->ClearFlags( FX_KILL_ON_IMPACT ); - FX_FreeMember( ef ); - } - else - { - if ( ef->mEffect->Update() == false ) - { + ef->mEffect->ClearFlags(FX_KILL_ON_IMPACT); + FX_FreeMember(ef); + } else { + if (ef->mEffect->Update() == false) { // We've been marked for death - FX_FreeMember( ef ); + FX_FreeMember(ef); continue; } } } } - - if ( fx_debug->integer && !portal) - { - theFxHelper.Print( "Active FX: %i\n", activeFx ); - theFxHelper.Print( "Drawn FX: %i\n", drawnFx ); - theFxHelper.Print( "Scheduled FX: %i High: %i\n", theFxScheduler.NumScheduledFx(), theFxScheduler.GetHighWatermark() ); + if (fx_debug->integer && !portal) { + theFxHelper.Print("Active FX: %i\n", activeFx); + theFxHelper.Print("Drawn FX: %i\n", drawnFx); + theFxHelper.Print("Scheduled FX: %i High: %i\n", theFxScheduler.NumScheduledFx(), theFxScheduler.GetHighWatermark()); } } - - //------------------------- // FX_AddPrimitive // // Note - in the editor, this function may change *pEffect to NULL, indicating that // all effects are being stopped. //------------------------- -extern bool gEffectsInPortal; //from FXScheduler.cpp so i don't have to pass it in on EVERY FX_ADD* -void FX_AddPrimitive( CEffect **pEffect, int killTime ) -{ +extern bool gEffectsInPortal; // from FXScheduler.cpp so i don't have to pass it in on EVERY FX_ADD* +void FX_AddPrimitive(CEffect **pEffect, int killTime) { SEffectList *item = FX_GetValidEffect(); item->mEffect = *pEffect; item->mKillTime = theFxHelper.mTime + killTime; - item->mPortal = gEffectsInPortal; //global set in AddScheduledEffects + item->mPortal = gEffectsInPortal; // global set in AddScheduledEffects activeFx++; // Stash these in the primitive so it has easy access to the vals - (*pEffect)->SetTimeStart( theFxHelper.mTime ); - (*pEffect)->SetTimeEnd( theFxHelper.mTime + killTime ); + (*pEffect)->SetTimeStart(theFxHelper.mTime); + (*pEffect)->SetTimeEnd(theFxHelper.mTime + killTime); } //------------------------- // FX_AddParticle //------------------------- -CParticle *FX_AddParticle( vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - float rotation, float rotationDelta, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CParticle *FX_AddParticle(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, + vec3_t sRGB, vec3_t eRGB, float rgbParm, float rotation, float rotationDelta, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int killTime, qhandle_t shader, int flags = 0, EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, + CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CParticle *fx = new CParticle; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } - else - { - fx->SetOrigin1( org ); - } - fx->SetOrigin1( org ); + fx->SetOrigin1(org); fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); fx->Init(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; } - - //------------------------- // FX_AddLine //------------------------- -CLine *FX_AddLine( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CLine *FX_AddLine(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, + float rgbParm, int killTime, qhandle_t shader, int flags = 0, EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, + CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CLine *fx = new CLine; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start ); //offset from bolt pos - fx->SetVel( end ); //vel is the vector offset from bolt+orgOffset - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset from bolt pos + fx->SetVel(end); // vel is the vector offset from bolt+orgOffset + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(start); + fx->SetOrigin2(end); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; } - //------------------------- // FX_AddElectricity //------------------------- -CElectricity *FX_AddElectricity( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - float chaos, int killTime, qhandle_t shader, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CElectricity *FX_AddElectricity(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, + vec3_t eRGB, float rgbParm, float chaos, int killTime, qhandle_t shader, int flags = 0, + EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, + int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CElectricity *fx = new CElectricity; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start );//offset - fx->SetVel( end ); //vel is the vector offset from bolt+orgOffset - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset + fx->SetVel(end); // vel is the vector offset from bolt+orgOffset + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(start); + fx->SetOrigin2(end); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); - fx->SetChaos( chaos ); + fx->SetShader(shader); + fx->SetFlags(flags); + fx->SetChaos(chaos); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); // in the editor, fx may now be NULL? - if ( fx ) - { + if (fx) { fx->Initialize(); } } @@ -528,224 +437,171 @@ CElectricity *FX_AddElectricity( vec3_t start, vec3_t end, float size1, float si return fx; } - //------------------------- // FX_AddTail //------------------------- -CTail *FX_AddTail( vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CTail *FX_AddTail(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float length1, float length2, float lengthParm, float alpha1, + float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, vec3_t min, vec3_t max, float elasticity, int deathID, int impactID, + int killTime, qhandle_t shader, int flags = 0, EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, + CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CTail *fx = new CTail; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org ); - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Length---------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetSTScale( 1.0f, 1.0f ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetSTScale(1.0f, 1.0f); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; } - //------------------------- // FX_AddCylinder //------------------------- -CCylinder *FX_AddCylinder( vec3_t start, vec3_t normal, - float size1s, float size1e, float size1Parm, - float size2s, float size2e, float size2Parm, - float length1, float length2, float lengthParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, qhandle_t shader, int flags, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/, - qboolean traceEnd) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CCylinder *FX_AddCylinder(vec3_t start, vec3_t normal, float size1s, float size1e, float size1Parm, float size2s, float size2e, float size2Parm, float length1, + float length2, float lengthParm, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, int killTime, + qhandle_t shader, int flags, EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, CGhoul2Info_v *ghoul2 /*0*/, + int entNum /*-1*/, int modelNum /*-1*/, int boltNum /*-1*/, qboolean traceEnd) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CCylinder *fx = new CCylinder; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( start );//offset - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( start ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(start); // offset + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(start); } fx->SetTraceEnd(traceEnd); fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetOrigin1( start ); - fx->SetNormal( normal ); + fx->SetOrigin1(start); + fx->SetNormal(normal); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size1---------------- - fx->SetSizeStart( size1s ); - fx->SetSizeEnd( size1e ); + fx->SetSizeStart(size1s); + fx->SetSizeEnd(size1e); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( size1Parm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( size1Parm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(size1Parm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(size1Parm * 0.01f * killTime + theFxHelper.mTime); } // Size2---------------- - fx->SetSize2Start( size2s ); - fx->SetSize2End( size2e ); + fx->SetSize2Start(size2s); + fx->SetSize2End(size2e); - if (( flags & FX_SIZE2_PARM_MASK ) == FX_SIZE2_WAVE ) - { - fx->SetSize2Parm( size2Parm * PI * 0.001f ); - } - else if ( flags & FX_SIZE2_PARM_MASK ) - { - fx->SetSize2Parm( size2Parm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE2_PARM_MASK) == FX_SIZE2_WAVE) { + fx->SetSize2Parm(size2Parm * PI * 0.001f); + } else if (flags & FX_SIZE2_PARM_MASK) { + fx->SetSize2Parm(size2Parm * 0.01f * killTime + theFxHelper.mTime); } // Length1--------------- - fx->SetLengthStart( length1 ); - fx->SetLengthEnd( length2 ); + fx->SetLengthStart(length1); + fx->SetLengthEnd(length2); - if (( flags & FX_LENGTH_PARM_MASK ) == FX_LENGTH_WAVE ) - { - fx->SetLengthParm( lengthParm * PI * 0.001f ); - } - else if ( flags & FX_LENGTH_PARM_MASK ) - { - fx->SetLengthParm( lengthParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_LENGTH_PARM_MASK) == FX_LENGTH_WAVE) { + fx->SetLengthParm(lengthParm * PI * 0.001f); + } else if (flags & FX_LENGTH_PARM_MASK) { + fx->SetLengthParm(lengthParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -754,96 +610,77 @@ CCylinder *FX_AddCylinder( vec3_t start, vec3_t normal, //------------------------- // FX_AddEmitter //------------------------- -CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t angs, vec3_t deltaAngs, - vec3_t min, vec3_t max, float elasticity, - int deathID, int impactID, int emitterID, - float density, float variance, - int killTime, qhandle_t model, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CEmitter *FX_AddEmitter(vec3_t org, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, + vec3_t rgb1, vec3_t rgb2, float rgbParm, vec3_t angs, vec3_t deltaAngs, vec3_t min, vec3_t max, float elasticity, int deathID, + int impactID, int emitterID, float density, float variance, int killTime, qhandle_t model, int flags = 0, + EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, + int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CEmitter *fx = new CEmitter; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - assert(0);//not done -// fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + assert(0); // not done + // fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetOrigin1( org ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetOrigin1(org); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); - - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetAngles( angs ); - fx->SetAngleDelta( deltaAngs ); - fx->SetFlags( flags ); - fx->SetModel( model ); - fx->SetElasticity( elasticity ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - fx->SetEmitterFxID( emitterID ); - fx->SetDensity( density ); - fx->SetVariance( variance ); - fx->SetOldTime( theFxHelper.mTime ); - - fx->SetLastOrg( org ); - fx->SetLastVel( vel ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); + + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetAngles(angs); + fx->SetAngleDelta(deltaAngs); + fx->SetFlags(flags); + fx->SetModel(model); + fx->SetElasticity(elasticity); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + fx->SetEmitterFxID(emitterID); + fx->SetDensity(density); + fx->SetVariance(variance); + fx->SetOldTime(theFxHelper.mTime); + + fx->SetLastOrg(org); + fx->SetLastVel(vel); + + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -852,318 +689,249 @@ CEmitter *FX_AddEmitter( vec3_t org, vec3_t vel, vec3_t accel, //------------------------- // FX_AddLight //------------------------- -CLight *FX_AddLight( vec3_t org, float size1, float size2, float sizeParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - int killTime, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +CLight *FX_AddLight(vec3_t org, float size1, float size2, float sizeParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, int killTime, int flags = 0, + EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, int modelNum /*-1*/, + int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } CLight *fx = new CLight; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org );//offset - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); // offset + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); + fx->SetFlags(flags); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; - } - //------------------------- // FX_AddOrientedParticle //------------------------- -COrientedParticle *FX_AddOrientedParticle( vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - float rotation, float rotationDelta, - vec3_t min, vec3_t max, float bounce, - int deathID, int impactID, - int killTime, qhandle_t shader, int flags = 0, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, - CGhoul2Info_v *ghoul2/*0*/, int entNum/*-1*/, int modelNum/*-1*/, int boltNum/*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding effects when the system is paused +COrientedParticle *FX_AddOrientedParticle(vec3_t org, vec3_t norm, vec3_t vel, vec3_t accel, float size1, float size2, float sizeParm, float alpha1, + float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, float rgbParm, float rotation, float rotationDelta, + vec3_t min, vec3_t max, float bounce, int deathID, int impactID, int killTime, qhandle_t shader, int flags = 0, + EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/, CGhoul2Info_v *ghoul2 /*0*/, int entNum /*-1*/, + int modelNum /*-1*/, int boltNum /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding effects when the system is paused return 0; } COrientedParticle *fx = new COrientedParticle; - if ( fx ) - { - if (flags&FX_RELATIVE && ghoul2 != NULL) - { - fx->SetOrigin1( NULL ); - fx->SetOrgOffset( org );//offset - fx->SetBoltinfo( ghoul2, entNum, modelNum, boltNum ); - } - else - { - fx->SetOrigin1( org ); + if (fx) { + if (flags & FX_RELATIVE && ghoul2 != NULL) { + fx->SetOrigin1(NULL); + fx->SetOrgOffset(org); // offset + fx->SetBoltinfo(ghoul2, entNum, modelNum, boltNum); + } else { + fx->SetOrigin1(org); } fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetOrigin1( org ); - fx->SetNormal( norm ); - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetOrigin1(org); + fx->SetNormal(norm); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); - - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); - } - - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRotation( rotation ); - fx->SetRotationDelta( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMin( min ); - fx->SetMax( max ); - fx->SetDeathFxID( deathID ); - fx->SetImpactFxID( impactID ); - - FX_AddPrimitive( (CEffect**)&fx, killTime ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); + + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); + } + + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRotation(rotation); + fx->SetRotationDelta(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMin(min); + fx->SetMax(max); + fx->SetDeathFxID(deathID); + fx->SetImpactFxID(impactID); + + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; } - //------------------------- // FX_AddPoly //------------------------- -CPoly *FX_AddPoly( vec3_t *verts, vec2_t *st, int numVerts, - vec3_t vel, vec3_t accel, - float alpha1, float alpha2, float alphaParm, - vec3_t rgb1, vec3_t rgb2, float rgbParm, - vec3_t rotationDelta, float bounce, int motionDelay, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 || !verts ) - { // disallow adding effects when the system is paused or the user doesn't pass in a vert array +CPoly *FX_AddPoly(vec3_t *verts, vec2_t *st, int numVerts, vec3_t vel, vec3_t accel, float alpha1, float alpha2, float alphaParm, vec3_t rgb1, vec3_t rgb2, + float rgbParm, vec3_t rotationDelta, float bounce, int motionDelay, int killTime, qhandle_t shader, int flags) { + if (theFxHelper.mFrameTime < 1 || !verts) { // disallow adding effects when the system is paused or the user doesn't pass in a vert array return 0; } CPoly *fx = new CPoly; - if ( fx ) - { + if (fx) { // Do a cheesy copy of the verts and texture coords into our own structure - for ( int i = 0; i < numVerts; i++ ) - { - VectorCopy( verts[i], fx->mOrg[i] ); - VectorCopy2( st[i], fx->mST[i] ); + for (int i = 0; i < numVerts; i++) { + VectorCopy(verts[i], fx->mOrg[i]); + VectorCopy2(st[i], fx->mST[i]); } - fx->SetVel( vel ); - fx->SetAccel( accel ); + fx->SetVel(vel); + fx->SetAccel(accel); // RGB---------------- - fx->SetRGBStart( rgb1 ); - fx->SetRGBEnd( rgb2 ); + fx->SetRGBStart(rgb1); + fx->SetRGBEnd(rgb2); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetFlags( flags ); - fx->SetShader( shader ); - fx->SetRot( rotationDelta ); - fx->SetElasticity( bounce ); - fx->SetMotionTimeStamp( motionDelay ); - fx->SetNumVerts( numVerts ); + fx->SetFlags(flags); + fx->SetShader(shader); + fx->SetRot(rotationDelta); + fx->SetElasticity(bounce); + fx->SetMotionTimeStamp(motionDelay); + fx->SetNumVerts(numVerts); // Now that we've set our data up, let's process it into a useful format fx->PolyInit(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; } - //------------------------- // FX_AddFlash //------------------------- -CFlash *FX_AddFlash( vec3_t origin, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags, - EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/ ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CFlash *FX_AddFlash(vec3_t origin, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, + float rgbParm, int killTime, qhandle_t shader, int flags, EMatImpactEffect matImpactFX /*MATIMPACTFX_NONE*/, int fxParm /*-1*/) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } - if (!shader) - { //yeah..this is bad, I guess, but SP seems to handle it by not drawing the flash, so I will too. + if (!shader) { // yeah..this is bad, I guess, but SP seems to handle it by not drawing the flash, so I will too. assert(shader); return 0; } CFlash *fx = new CFlash; - if ( fx ) - { + if (fx) { fx->SetMatImpactFX(matImpactFX); fx->SetMatImpactParm(fxParm); - fx->SetOrigin1( origin ); + fx->SetOrigin1(origin); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); -// fx->SetSTScale( 1.0f, 1.0f ); + // fx->SetSTScale( 1.0f, 1.0f ); fx->Init(); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; @@ -1172,75 +940,59 @@ CFlash *FX_AddFlash( vec3_t origin, //------------------------- // FX_AddBezier //------------------------- -CBezier *FX_AddBezier( vec3_t start, vec3_t end, - vec3_t control1, vec3_t control1Vel, - vec3_t control2, vec3_t control2Vel, - float size1, float size2, float sizeParm, - float alpha1, float alpha2, float alphaParm, - vec3_t sRGB, vec3_t eRGB, float rgbParm, - int killTime, qhandle_t shader, int flags ) -{ - if ( theFxHelper.mFrameTime < 1 ) - { // disallow adding new effects when the system is paused +CBezier *FX_AddBezier(vec3_t start, vec3_t end, vec3_t control1, vec3_t control1Vel, vec3_t control2, vec3_t control2Vel, float size1, float size2, + float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, + int flags) { + if (theFxHelper.mFrameTime < 1) { // disallow adding new effects when the system is paused return 0; } CBezier *fx = new CBezier; - if ( fx ) - { - fx->SetOrigin1( start ); - fx->SetOrigin2( end ); + if (fx) { + fx->SetOrigin1(start); + fx->SetOrigin2(end); - fx->SetControlPoints( control1, control2 ); - fx->SetControlVel( control1Vel, control2Vel ); + fx->SetControlPoints(control1, control2); + fx->SetControlVel(control1Vel, control2Vel); // RGB---------------- - fx->SetRGBStart( sRGB ); - fx->SetRGBEnd( eRGB ); + fx->SetRGBStart(sRGB); + fx->SetRGBEnd(eRGB); - if (( flags & FX_RGB_PARM_MASK ) == FX_RGB_WAVE ) - { - fx->SetRGBParm( rgbParm * PI * 0.001f ); - } - else if ( flags & FX_RGB_PARM_MASK ) - { + if ((flags & FX_RGB_PARM_MASK) == FX_RGB_WAVE) { + fx->SetRGBParm(rgbParm * PI * 0.001f); + } else if (flags & FX_RGB_PARM_MASK) { // rgbParm should be a value from 0-100.. - fx->SetRGBParm( rgbParm * 0.01f * killTime + theFxHelper.mTime ); + fx->SetRGBParm(rgbParm * 0.01f * killTime + theFxHelper.mTime); } // Alpha---------------- - fx->SetAlphaStart( alpha1 ); - fx->SetAlphaEnd( alpha2 ); + fx->SetAlphaStart(alpha1); + fx->SetAlphaEnd(alpha2); - if (( flags & FX_ALPHA_PARM_MASK ) == FX_ALPHA_WAVE ) - { - fx->SetAlphaParm( alphaParm * PI * 0.001f ); - } - else if ( flags & FX_ALPHA_PARM_MASK ) - { - fx->SetAlphaParm( alphaParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_ALPHA_PARM_MASK) == FX_ALPHA_WAVE) { + fx->SetAlphaParm(alphaParm * PI * 0.001f); + } else if (flags & FX_ALPHA_PARM_MASK) { + fx->SetAlphaParm(alphaParm * 0.01f * killTime + theFxHelper.mTime); } // Size---------------- - fx->SetSizeStart( size1 ); - fx->SetSizeEnd( size2 ); + fx->SetSizeStart(size1); + fx->SetSizeEnd(size2); - if (( flags & FX_SIZE_PARM_MASK ) == FX_SIZE_WAVE ) - { - fx->SetSizeParm( sizeParm * PI * 0.001f ); - } - else if ( flags & FX_SIZE_PARM_MASK ) - { - fx->SetSizeParm( sizeParm * 0.01f * killTime + theFxHelper.mTime ); + if ((flags & FX_SIZE_PARM_MASK) == FX_SIZE_WAVE) { + fx->SetSizeParm(sizeParm * PI * 0.001f); + } else if (flags & FX_SIZE_PARM_MASK) { + fx->SetSizeParm(sizeParm * 0.01f * killTime + theFxHelper.mTime); } - fx->SetShader( shader ); - fx->SetFlags( flags ); + fx->SetShader(shader); + fx->SetFlags(flags); - fx->SetSTScale( 1.0f, 1.0f ); + fx->SetSTScale(1.0f, 1.0f); - FX_AddPrimitive( (CEffect**)&fx, killTime ); + FX_AddPrimitive((CEffect **)&fx, killTime); } return fx; diff --git a/codemp/client/cl_avi.cpp b/codemp/client/cl_avi.cpp index 2a8c268390..e467e5359b 100644 --- a/codemp/client/cl_avi.cpp +++ b/codemp/client/cl_avi.cpp @@ -27,62 +27,59 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #define MAX_RIFF_CHUNKS 16 -typedef struct audioFormat_s -{ - int rate; - int format; - int channels; - int bits; - - int sampleSize; - int totalBytes; +typedef struct audioFormat_s { + int rate; + int format; + int channels; + int bits; + + int sampleSize; + int totalBytes; } audioFormat_t; -typedef struct aviFileData_s -{ - qboolean fileOpen; - fileHandle_t f; - char fileName[ MAX_QPATH ]; - int fileSize; - int moviOffset; - int moviSize; - - fileHandle_t idxF; - int numIndices; - - int frameRate; - int framePeriod; - int width, height; - int numVideoFrames; - int maxRecordSize; - qboolean motionJpeg; - - qboolean audio; - audioFormat_t a; - int numAudioFrames; - - int chunkStack[ MAX_RIFF_CHUNKS ]; - int chunkStackTop; - - byte *cBuffer, *eBuffer; +typedef struct aviFileData_s { + qboolean fileOpen; + fileHandle_t f; + char fileName[MAX_QPATH]; + int fileSize; + int moviOffset; + int moviSize; + + fileHandle_t idxF; + int numIndices; + + int frameRate; + int framePeriod; + int width, height; + int numVideoFrames; + int maxRecordSize; + qboolean motionJpeg; + + qboolean audio; + audioFormat_t a; + int numAudioFrames; + + int chunkStack[MAX_RIFF_CHUNKS]; + int chunkStackTop; + + byte *cBuffer, *eBuffer; } aviFileData_t; static aviFileData_t afd; #define MAX_AVI_BUFFER 2048 -static byte buffer[ MAX_AVI_BUFFER ]; -static int bufIndex; +static byte buffer[MAX_AVI_BUFFER]; +static int bufIndex; /* =============== SafeFS_Write =============== */ -static QINLINE void SafeFS_Write( const void *buffer, int len, fileHandle_t f ) -{ - if( FS_Write( buffer, len, f ) < len ) - Com_Error( ERR_DROP, "Failed to write avi file" ); +static QINLINE void SafeFS_Write(const void *buffer, int len, fileHandle_t f) { + if (FS_Write(buffer, len, f) < len) + Com_Error(ERR_DROP, "Failed to write avi file"); } /* @@ -90,10 +87,9 @@ static QINLINE void SafeFS_Write( const void *buffer, int len, fileHandle_t f ) WRITE_STRING =============== */ -static QINLINE void WRITE_STRING( const char *s ) -{ - Com_Memcpy( &buffer[ bufIndex ], s, strlen( s ) ); - bufIndex += strlen( s ); +static QINLINE void WRITE_STRING(const char *s) { + Com_Memcpy(&buffer[bufIndex], s, strlen(s)); + bufIndex += strlen(s); } /* @@ -101,13 +97,12 @@ static QINLINE void WRITE_STRING( const char *s ) WRITE_4BYTES =============== */ -static QINLINE void WRITE_4BYTES( int x ) -{ - buffer[ bufIndex + 0 ] = (byte)( ( x >> 0 ) & 0xFF ); - buffer[ bufIndex + 1 ] = (byte)( ( x >> 8 ) & 0xFF ); - buffer[ bufIndex + 2 ] = (byte)( ( x >> 16 ) & 0xFF ); - buffer[ bufIndex + 3 ] = (byte)( ( x >> 24 ) & 0xFF ); - bufIndex += 4; +static QINLINE void WRITE_4BYTES(int x) { + buffer[bufIndex + 0] = (byte)((x >> 0) & 0xFF); + buffer[bufIndex + 1] = (byte)((x >> 8) & 0xFF); + buffer[bufIndex + 2] = (byte)((x >> 16) & 0xFF); + buffer[bufIndex + 3] = (byte)((x >> 24) & 0xFF); + bufIndex += 4; } /* @@ -115,11 +110,10 @@ static QINLINE void WRITE_4BYTES( int x ) WRITE_2BYTES =============== */ -static QINLINE void WRITE_2BYTES( int x ) -{ - buffer[ bufIndex + 0 ] = (byte)( ( x >> 0 ) & 0xFF ); - buffer[ bufIndex + 1 ] = (byte)( ( x >> 8 ) & 0xFF ); - bufIndex += 2; +static QINLINE void WRITE_2BYTES(int x) { + buffer[bufIndex + 0] = (byte)((x >> 0) & 0xFF); + buffer[bufIndex + 1] = (byte)((x >> 8) & 0xFF); + bufIndex += 2; } /* @@ -138,17 +132,15 @@ WRITE_1BYTES START_CHUNK =============== */ -static QINLINE void START_CHUNK( const char *s ) -{ - if( afd.chunkStackTop == MAX_RIFF_CHUNKS ) - { - Com_Error( ERR_DROP, "ERROR: Top of chunkstack breached" ); - } - - afd.chunkStack[ afd.chunkStackTop ] = bufIndex; - afd.chunkStackTop++; - WRITE_STRING( s ); - WRITE_4BYTES( 0 ); +static QINLINE void START_CHUNK(const char *s) { + if (afd.chunkStackTop == MAX_RIFF_CHUNKS) { + Com_Error(ERR_DROP, "ERROR: Top of chunkstack breached"); + } + + afd.chunkStack[afd.chunkStackTop] = bufIndex; + afd.chunkStackTop++; + WRITE_STRING(s); + WRITE_4BYTES(0); } /* @@ -156,21 +148,19 @@ static QINLINE void START_CHUNK( const char *s ) END_CHUNK =============== */ -static QINLINE void END_CHUNK( void ) -{ - int endIndex = bufIndex; - - if( afd.chunkStackTop <= 0 ) - { - Com_Error( ERR_DROP, "ERROR: Bottom of chunkstack breached" ); - } - - afd.chunkStackTop--; - bufIndex = afd.chunkStack[ afd.chunkStackTop ]; - bufIndex += 4; - WRITE_4BYTES( endIndex - bufIndex - 4 ); - bufIndex = endIndex; - bufIndex = PAD( bufIndex, 2 ); +static QINLINE void END_CHUNK(void) { + int endIndex = bufIndex; + + if (afd.chunkStackTop <= 0) { + Com_Error(ERR_DROP, "ERROR: Bottom of chunkstack breached"); + } + + afd.chunkStackTop--; + bufIndex = afd.chunkStack[afd.chunkStackTop]; + bufIndex += 4; + WRITE_4BYTES(endIndex - bufIndex - 4); + bufIndex = endIndex; + bufIndex = PAD(bufIndex, 2); } /* @@ -178,150 +168,138 @@ static QINLINE void END_CHUNK( void ) CL_WriteAVIHeader =============== */ -void CL_WriteAVIHeader( void ) -{ - bufIndex = 0; - afd.chunkStackTop = 0; - - START_CHUNK( "RIFF" ); - { - WRITE_STRING( "AVI " ); - { - START_CHUNK( "LIST" ); - { - WRITE_STRING( "hdrl" ); - WRITE_STRING( "avih" ); - WRITE_4BYTES( 56 ); //"avih" "chunk" size - WRITE_4BYTES( afd.framePeriod ); //dwMicroSecPerFrame - WRITE_4BYTES( afd.maxRecordSize * - afd.frameRate ); //dwMaxBytesPerSec - WRITE_4BYTES( 0 ); //dwReserved1 - WRITE_4BYTES( 0x110 ); //dwFlags bits HAS_INDEX and IS_INTERLEAVED - WRITE_4BYTES( afd.numVideoFrames ); //dwTotalFrames - WRITE_4BYTES( 0 ); //dwInitialFrame - - if( afd.audio ) //dwStreams - WRITE_4BYTES( 2 ); - else - WRITE_4BYTES( 1 ); - - WRITE_4BYTES( afd.maxRecordSize ); //dwSuggestedBufferSize - WRITE_4BYTES( afd.width ); //dwWidth - WRITE_4BYTES( afd.height ); //dwHeight - WRITE_4BYTES( 0 ); //dwReserved[ 0 ] - WRITE_4BYTES( 0 ); //dwReserved[ 1 ] - WRITE_4BYTES( 0 ); //dwReserved[ 2 ] - WRITE_4BYTES( 0 ); //dwReserved[ 3 ] - - START_CHUNK( "LIST" ); - { - WRITE_STRING( "strl" ); - WRITE_STRING( "strh" ); - WRITE_4BYTES( 56 ); //"strh" "chunk" size - WRITE_STRING( "vids" ); - - if( afd.motionJpeg ) - WRITE_STRING( "MJPG" ); - else - WRITE_4BYTES( 0 ); // BI_RGB - - WRITE_4BYTES( 0 ); //dwFlags - WRITE_4BYTES( 0 ); //dwPriority - WRITE_4BYTES( 0 ); //dwInitialFrame - - WRITE_4BYTES( 1 ); //dwTimescale - WRITE_4BYTES( afd.frameRate ); //dwDataRate - WRITE_4BYTES( 0 ); //dwStartTime - WRITE_4BYTES( afd.numVideoFrames ); //dwDataLength - - WRITE_4BYTES( afd.maxRecordSize ); //dwSuggestedBufferSize - WRITE_4BYTES( -1 ); //dwQuality - WRITE_4BYTES( 0 ); //dwSampleSize - WRITE_2BYTES( 0 ); //rcFrame - WRITE_2BYTES( 0 ); //rcFrame - WRITE_2BYTES( afd.width ); //rcFrame - WRITE_2BYTES( afd.height ); //rcFrame - - WRITE_STRING( "strf" ); - WRITE_4BYTES( 40 ); //"strf" "chunk" size - WRITE_4BYTES( 40 ); //biSize - WRITE_4BYTES( afd.width ); //biWidth - WRITE_4BYTES( afd.height ); //biHeight - WRITE_2BYTES( 1 ); //biPlanes - WRITE_2BYTES( 24 ); //biBitCount - - if( afd.motionJpeg ) //biCompression - { - WRITE_STRING( "MJPG" ); - WRITE_4BYTES( afd.width * - afd.height ); //biSizeImage - } - else - { - WRITE_4BYTES( 0 ); // BI_RGB - WRITE_4BYTES( afd.width * - afd.height * 3 ); //biSizeImage - } - - WRITE_4BYTES( 0 ); //biXPelsPetMeter - WRITE_4BYTES( 0 ); //biYPelsPetMeter - WRITE_4BYTES( 0 ); //biClrUsed - WRITE_4BYTES( 0 ); //biClrImportant - } - END_CHUNK( ); - - if( afd.audio ) - { - START_CHUNK( "LIST" ); - { - WRITE_STRING( "strl" ); - WRITE_STRING( "strh" ); - WRITE_4BYTES( 56 ); //"strh" "chunk" size - WRITE_STRING( "auds" ); - WRITE_4BYTES( 0 ); //FCC - WRITE_4BYTES( 0 ); //dwFlags - WRITE_4BYTES( 0 ); //dwPriority - WRITE_4BYTES( 0 ); //dwInitialFrame - - WRITE_4BYTES( afd.a.sampleSize ); //dwTimescale - WRITE_4BYTES( afd.a.sampleSize * - afd.a.rate ); //dwDataRate - WRITE_4BYTES( 0 ); //dwStartTime - WRITE_4BYTES( afd.a.totalBytes / - afd.a.sampleSize ); //dwDataLength - - WRITE_4BYTES( 0 ); //dwSuggestedBufferSize - WRITE_4BYTES( -1 ); //dwQuality - WRITE_4BYTES( afd.a.sampleSize ); //dwSampleSize - WRITE_2BYTES( 0 ); //rcFrame - WRITE_2BYTES( 0 ); //rcFrame - WRITE_2BYTES( 0 ); //rcFrame - WRITE_2BYTES( 0 ); //rcFrame - - WRITE_STRING( "strf" ); - WRITE_4BYTES( 18 ); //"strf" "chunk" size - WRITE_2BYTES( afd.a.format ); //wFormatTag - WRITE_2BYTES( afd.a.channels ); //nChannels - WRITE_4BYTES( afd.a.rate ); //nSamplesPerSec - WRITE_4BYTES( afd.a.sampleSize * - afd.a.rate ); //nAvgBytesPerSec - WRITE_2BYTES( afd.a.sampleSize ); //nBlockAlign - WRITE_2BYTES( afd.a.bits ); //wBitsPerSample - WRITE_2BYTES( 0 ); //cbSize - } - END_CHUNK( ); - } - } - END_CHUNK( ); - - afd.moviOffset = bufIndex; - - START_CHUNK( "LIST" ); - { - WRITE_STRING( "movi" ); - } - } - } +void CL_WriteAVIHeader(void) { + bufIndex = 0; + afd.chunkStackTop = 0; + + START_CHUNK("RIFF"); + { + WRITE_STRING("AVI "); + { + START_CHUNK("LIST"); + { + WRITE_STRING("hdrl"); + WRITE_STRING("avih"); + WRITE_4BYTES(56); //"avih" "chunk" size + WRITE_4BYTES(afd.framePeriod); // dwMicroSecPerFrame + WRITE_4BYTES(afd.maxRecordSize * afd.frameRate); // dwMaxBytesPerSec + WRITE_4BYTES(0); // dwReserved1 + WRITE_4BYTES(0x110); // dwFlags bits HAS_INDEX and IS_INTERLEAVED + WRITE_4BYTES(afd.numVideoFrames); // dwTotalFrames + WRITE_4BYTES(0); // dwInitialFrame + + if (afd.audio) // dwStreams + WRITE_4BYTES(2); + else + WRITE_4BYTES(1); + + WRITE_4BYTES(afd.maxRecordSize); // dwSuggestedBufferSize + WRITE_4BYTES(afd.width); // dwWidth + WRITE_4BYTES(afd.height); // dwHeight + WRITE_4BYTES(0); // dwReserved[ 0 ] + WRITE_4BYTES(0); // dwReserved[ 1 ] + WRITE_4BYTES(0); // dwReserved[ 2 ] + WRITE_4BYTES(0); // dwReserved[ 3 ] + + START_CHUNK("LIST"); + { + WRITE_STRING("strl"); + WRITE_STRING("strh"); + WRITE_4BYTES(56); //"strh" "chunk" size + WRITE_STRING("vids"); + + if (afd.motionJpeg) + WRITE_STRING("MJPG"); + else + WRITE_4BYTES(0); // BI_RGB + + WRITE_4BYTES(0); // dwFlags + WRITE_4BYTES(0); // dwPriority + WRITE_4BYTES(0); // dwInitialFrame + + WRITE_4BYTES(1); // dwTimescale + WRITE_4BYTES(afd.frameRate); // dwDataRate + WRITE_4BYTES(0); // dwStartTime + WRITE_4BYTES(afd.numVideoFrames); // dwDataLength + + WRITE_4BYTES(afd.maxRecordSize); // dwSuggestedBufferSize + WRITE_4BYTES(-1); // dwQuality + WRITE_4BYTES(0); // dwSampleSize + WRITE_2BYTES(0); // rcFrame + WRITE_2BYTES(0); // rcFrame + WRITE_2BYTES(afd.width); // rcFrame + WRITE_2BYTES(afd.height); // rcFrame + + WRITE_STRING("strf"); + WRITE_4BYTES(40); //"strf" "chunk" size + WRITE_4BYTES(40); // biSize + WRITE_4BYTES(afd.width); // biWidth + WRITE_4BYTES(afd.height); // biHeight + WRITE_2BYTES(1); // biPlanes + WRITE_2BYTES(24); // biBitCount + + if (afd.motionJpeg) // biCompression + { + WRITE_STRING("MJPG"); + WRITE_4BYTES(afd.width * afd.height); // biSizeImage + } else { + WRITE_4BYTES(0); // BI_RGB + WRITE_4BYTES(afd.width * afd.height * 3); // biSizeImage + } + + WRITE_4BYTES(0); // biXPelsPetMeter + WRITE_4BYTES(0); // biYPelsPetMeter + WRITE_4BYTES(0); // biClrUsed + WRITE_4BYTES(0); // biClrImportant + } + END_CHUNK(); + + if (afd.audio) { + START_CHUNK("LIST"); + { + WRITE_STRING("strl"); + WRITE_STRING("strh"); + WRITE_4BYTES(56); //"strh" "chunk" size + WRITE_STRING("auds"); + WRITE_4BYTES(0); // FCC + WRITE_4BYTES(0); // dwFlags + WRITE_4BYTES(0); // dwPriority + WRITE_4BYTES(0); // dwInitialFrame + + WRITE_4BYTES(afd.a.sampleSize); // dwTimescale + WRITE_4BYTES(afd.a.sampleSize * afd.a.rate); // dwDataRate + WRITE_4BYTES(0); // dwStartTime + WRITE_4BYTES(afd.a.totalBytes / afd.a.sampleSize); // dwDataLength + + WRITE_4BYTES(0); // dwSuggestedBufferSize + WRITE_4BYTES(-1); // dwQuality + WRITE_4BYTES(afd.a.sampleSize); // dwSampleSize + WRITE_2BYTES(0); // rcFrame + WRITE_2BYTES(0); // rcFrame + WRITE_2BYTES(0); // rcFrame + WRITE_2BYTES(0); // rcFrame + + WRITE_STRING("strf"); + WRITE_4BYTES(18); //"strf" "chunk" size + WRITE_2BYTES(afd.a.format); // wFormatTag + WRITE_2BYTES(afd.a.channels); // nChannels + WRITE_4BYTES(afd.a.rate); // nSamplesPerSec + WRITE_4BYTES(afd.a.sampleSize * afd.a.rate); // nAvgBytesPerSec + WRITE_2BYTES(afd.a.sampleSize); // nBlockAlign + WRITE_2BYTES(afd.a.bits); // wBitsPerSample + WRITE_2BYTES(0); // cbSize + } + END_CHUNK(); + } + } + END_CHUNK(); + + afd.moviOffset = bufIndex; + + START_CHUNK("LIST"); + { WRITE_STRING("movi"); } + } + } } /* @@ -332,105 +310,94 @@ Creates an AVI file and gets it into a state where writing the actual data can begin =============== */ -qboolean CL_OpenAVIForWriting( const char *fileName ) -{ - if( afd.fileOpen ) - return qfalse; - - Com_Memset( &afd, 0, sizeof( aviFileData_t ) ); - - // Don't start if a framerate has not been chosen - if( cl_aviFrameRate->integer <= 0 ) - { - Com_Printf( S_COLOR_RED "cl_aviFrameRate must be >= 1\n" ); - return qfalse; - } - - if( ( afd.f = FS_FOpenFileWrite( fileName ) ) <= 0 ) - return qfalse; - - if( ( afd.idxF = FS_FOpenFileWrite( - va( "%s" INDEX_FILE_EXTENSION, fileName ) ) ) <= 0 ) - { - FS_FCloseFile( afd.f ); - return qfalse; - } - - Q_strncpyz( afd.fileName, fileName, MAX_QPATH ); - - afd.frameRate = cl_aviFrameRate->integer; - afd.framePeriod = (int)( 1000000.0f / afd.frameRate ); - afd.width = cls.glconfig.vidWidth; - afd.height = cls.glconfig.vidHeight; - - if( cl_aviMotionJpeg->integer ) - afd.motionJpeg = qtrue; - else - afd.motionJpeg = qfalse; - - // Buffers only need to store RGB pixels. - // Allocate a bit more space for the capture buffer to account for possible - // padding at the end of pixel lines, and padding for alignment - #define MAX_PACK_LEN 16 - afd.cBuffer = (byte *)Z_Malloc((afd.width * 3 + MAX_PACK_LEN - 1) * afd.height + MAX_PACK_LEN - 1, TAG_AVI, qtrue); - // raw avi files have pixel lines start on 4-byte boundaries - afd.eBuffer = (byte *)Z_Malloc(PAD(afd.width * 3, AVI_LINE_PADDING) * afd.height, TAG_AVI, qtrue); - - afd.a.rate = dma.speed; - afd.a.format = WAV_FORMAT_PCM; - afd.a.channels = dma.channels; - afd.a.bits = dma.samplebits; - afd.a.sampleSize = ( afd.a.bits / 8 ) * afd.a.channels; - - if( afd.a.rate % afd.frameRate ) - { - int suggestRate = afd.frameRate; - - while( ( afd.a.rate % suggestRate ) && suggestRate >= 1 ) - suggestRate--; - - Com_Printf( S_COLOR_YELLOW "WARNING: cl_aviFrameRate is not a divisor " - "of the audio rate, suggest %d\n", suggestRate ); - } - - if( !Cvar_VariableIntegerValue( "s_initsound" ) ) - { - afd.audio = qfalse; - } - else if( Cvar_VariableIntegerValue( "s_UseOpenAL" ) == 0 ) - //else if( Q_stricmp( Cvar_VariableString( "s_backend" ), "OpenAL" ) ) - { - if( afd.a.bits != 16 || afd.a.channels != 2 ) - { - Com_Printf( S_COLOR_YELLOW "WARNING: Audio format of %d bit/%d channels not supported", - afd.a.bits, afd.a.channels ); - afd.audio = qfalse; - } - else - afd.audio = qtrue; - } - else - { - afd.audio = qfalse; - Com_Printf( S_COLOR_YELLOW "WARNING: Audio capture is not supported " - "with OpenAL. Set s_UseOpenAL to 0 for audio capture\n" ); - } - - // This doesn't write a real header, but allocates the - // correct amount of space at the beginning of the file - CL_WriteAVIHeader( ); - - SafeFS_Write( buffer, bufIndex, afd.f ); - afd.fileSize = bufIndex; - - bufIndex = 0; - START_CHUNK( "idx1" ); - SafeFS_Write( buffer, bufIndex, afd.idxF ); - - afd.moviSize = 4; // For the "movi" - afd.fileOpen = qtrue; - - return qtrue; +qboolean CL_OpenAVIForWriting(const char *fileName) { + if (afd.fileOpen) + return qfalse; + + Com_Memset(&afd, 0, sizeof(aviFileData_t)); + + // Don't start if a framerate has not been chosen + if (cl_aviFrameRate->integer <= 0) { + Com_Printf(S_COLOR_RED "cl_aviFrameRate must be >= 1\n"); + return qfalse; + } + + if ((afd.f = FS_FOpenFileWrite(fileName)) <= 0) + return qfalse; + + if ((afd.idxF = FS_FOpenFileWrite(va("%s" INDEX_FILE_EXTENSION, fileName))) <= 0) { + FS_FCloseFile(afd.f); + return qfalse; + } + + Q_strncpyz(afd.fileName, fileName, MAX_QPATH); + + afd.frameRate = cl_aviFrameRate->integer; + afd.framePeriod = (int)(1000000.0f / afd.frameRate); + afd.width = cls.glconfig.vidWidth; + afd.height = cls.glconfig.vidHeight; + + if (cl_aviMotionJpeg->integer) + afd.motionJpeg = qtrue; + else + afd.motionJpeg = qfalse; + +// Buffers only need to store RGB pixels. +// Allocate a bit more space for the capture buffer to account for possible +// padding at the end of pixel lines, and padding for alignment +#define MAX_PACK_LEN 16 + afd.cBuffer = (byte *)Z_Malloc((afd.width * 3 + MAX_PACK_LEN - 1) * afd.height + MAX_PACK_LEN - 1, TAG_AVI, qtrue); + // raw avi files have pixel lines start on 4-byte boundaries + afd.eBuffer = (byte *)Z_Malloc(PAD(afd.width * 3, AVI_LINE_PADDING) * afd.height, TAG_AVI, qtrue); + + afd.a.rate = dma.speed; + afd.a.format = WAV_FORMAT_PCM; + afd.a.channels = dma.channels; + afd.a.bits = dma.samplebits; + afd.a.sampleSize = (afd.a.bits / 8) * afd.a.channels; + + if (afd.a.rate % afd.frameRate) { + int suggestRate = afd.frameRate; + + while ((afd.a.rate % suggestRate) && suggestRate >= 1) + suggestRate--; + + Com_Printf(S_COLOR_YELLOW "WARNING: cl_aviFrameRate is not a divisor " + "of the audio rate, suggest %d\n", + suggestRate); + } + + if (!Cvar_VariableIntegerValue("s_initsound")) { + afd.audio = qfalse; + } else if (Cvar_VariableIntegerValue("s_UseOpenAL") == 0) + // else if( Q_stricmp( Cvar_VariableString( "s_backend" ), "OpenAL" ) ) + { + if (afd.a.bits != 16 || afd.a.channels != 2) { + Com_Printf(S_COLOR_YELLOW "WARNING: Audio format of %d bit/%d channels not supported", afd.a.bits, afd.a.channels); + afd.audio = qfalse; + } else + afd.audio = qtrue; + } else { + afd.audio = qfalse; + Com_Printf(S_COLOR_YELLOW "WARNING: Audio capture is not supported " + "with OpenAL. Set s_UseOpenAL to 0 for audio capture\n"); + } + + // This doesn't write a real header, but allocates the + // correct amount of space at the beginning of the file + CL_WriteAVIHeader(); + + SafeFS_Write(buffer, bufIndex, afd.f); + afd.fileSize = bufIndex; + + bufIndex = 0; + START_CHUNK("idx1"); + SafeFS_Write(buffer, bufIndex, afd.idxF); + + afd.moviSize = 4; // For the "movi" + afd.fileOpen = qtrue; + + return qtrue; } /* @@ -438,33 +405,29 @@ qboolean CL_OpenAVIForWriting( const char *fileName ) CL_CheckFileSize =============== */ -static qboolean CL_CheckFileSize( int bytesToAdd ) -{ - unsigned int newFileSize; - - newFileSize = - afd.fileSize + // Current file size - bytesToAdd + // What we want to add - ( afd.numIndices * 16 ) + // The index - 4; // The index size - - if ( cl_avi2GBLimit->integer ) - { - // I assume all the operating systems - // we target can handle a 2Gb file - if ( newFileSize > INT_MAX ) - { - // Close the current file... - CL_CloseAVI(); - - // ...And open a new one - CL_OpenAVIForWriting( va( "%s_", afd.fileName ) ); - - return qtrue; - } - } - - return qfalse; +static qboolean CL_CheckFileSize(int bytesToAdd) { + unsigned int newFileSize; + + newFileSize = afd.fileSize + // Current file size + bytesToAdd + // What we want to add + (afd.numIndices * 16) + // The index + 4; // The index size + + if (cl_avi2GBLimit->integer) { + // I assume all the operating systems + // we target can handle a 2Gb file + if (newFileSize > INT_MAX) { + // Close the current file... + CL_CloseAVI(); + + // ...And open a new one + CL_OpenAVIForWriting(va("%s_", afd.fileName)); + + return qtrue; + } + } + + return qfalse; } /* @@ -472,44 +435,43 @@ static qboolean CL_CheckFileSize( int bytesToAdd ) CL_WriteAVIVideoFrame =============== */ -void CL_WriteAVIVideoFrame( const byte *imageBuffer, int size ) -{ - int chunkOffset = afd.fileSize - afd.moviOffset - 8; - int chunkSize = 8 + size; - int paddingSize = PADLEN(size, 2); - byte padding[ 4 ] = { 0 }; - - if( !afd.fileOpen ) - return; - - // Chunk header + contents + padding - if( CL_CheckFileSize( 8 + size + 2 ) ) - return; - - bufIndex = 0; - WRITE_STRING( "00dc" ); - WRITE_4BYTES( size ); - - SafeFS_Write( buffer, 8, afd.f ); - SafeFS_Write( imageBuffer, size, afd.f ); - SafeFS_Write( padding, paddingSize, afd.f ); - afd.fileSize += ( chunkSize + paddingSize ); - - afd.numVideoFrames++; - afd.moviSize += ( chunkSize + paddingSize ); - - if( size > afd.maxRecordSize ) - afd.maxRecordSize = size; - - // Index - bufIndex = 0; - WRITE_STRING( "00dc" ); //dwIdentifier - WRITE_4BYTES( 0x00000010 ); //dwFlags (all frames are KeyFrames) - WRITE_4BYTES( chunkOffset ); //dwOffset - WRITE_4BYTES( size ); //dwLength - SafeFS_Write( buffer, 16, afd.idxF ); - - afd.numIndices++; +void CL_WriteAVIVideoFrame(const byte *imageBuffer, int size) { + int chunkOffset = afd.fileSize - afd.moviOffset - 8; + int chunkSize = 8 + size; + int paddingSize = PADLEN(size, 2); + byte padding[4] = {0}; + + if (!afd.fileOpen) + return; + + // Chunk header + contents + padding + if (CL_CheckFileSize(8 + size + 2)) + return; + + bufIndex = 0; + WRITE_STRING("00dc"); + WRITE_4BYTES(size); + + SafeFS_Write(buffer, 8, afd.f); + SafeFS_Write(imageBuffer, size, afd.f); + SafeFS_Write(padding, paddingSize, afd.f); + afd.fileSize += (chunkSize + paddingSize); + + afd.numVideoFrames++; + afd.moviSize += (chunkSize + paddingSize); + + if (size > afd.maxRecordSize) + afd.maxRecordSize = size; + + // Index + bufIndex = 0; + WRITE_STRING("00dc"); // dwIdentifier + WRITE_4BYTES(0x00000010); // dwFlags (all frames are KeyFrames) + WRITE_4BYTES(chunkOffset); // dwOffset + WRITE_4BYTES(size); // dwLength + SafeFS_Write(buffer, 16, afd.idxF); + + afd.numIndices++; } #define PCM_BUFFER_SIZE 44100 @@ -519,65 +481,60 @@ void CL_WriteAVIVideoFrame( const byte *imageBuffer, int size ) CL_WriteAVIAudioFrame =============== */ -void CL_WriteAVIAudioFrame( const byte *pcmBuffer, int size ) -{ - static byte pcmCaptureBuffer[ PCM_BUFFER_SIZE ] = { 0 }; - static int bytesInBuffer = 0; - - if( !afd.audio ) - return; - - if( !afd.fileOpen ) - return; - - // Chunk header + contents + padding - if( CL_CheckFileSize( 8 + bytesInBuffer + size + 2 ) ) - return; - - if( bytesInBuffer + size > PCM_BUFFER_SIZE ) - { - Com_Printf( S_COLOR_YELLOW - "WARNING: Audio capture buffer overflow -- truncating\n" ); - size = PCM_BUFFER_SIZE - bytesInBuffer; - } - - Com_Memcpy( &pcmCaptureBuffer[ bytesInBuffer ], pcmBuffer, size ); - bytesInBuffer += size; - - // Only write if we have a frame's worth of audio - if( bytesInBuffer >= (int)ceil( (float)afd.a.rate / (float)afd.frameRate ) * - afd.a.sampleSize ) - { - int chunkOffset = afd.fileSize - afd.moviOffset - 8; - int chunkSize = 8 + bytesInBuffer; - int paddingSize = PADLEN(bytesInBuffer, 2); - byte padding[ 4 ] = { 0 }; - - bufIndex = 0; - WRITE_STRING( "01wb" ); - WRITE_4BYTES( bytesInBuffer ); - - SafeFS_Write( buffer, 8, afd.f ); - SafeFS_Write( pcmCaptureBuffer, bytesInBuffer, afd.f ); - SafeFS_Write( padding, paddingSize, afd.f ); - afd.fileSize += ( chunkSize + paddingSize ); - - afd.numAudioFrames++; - afd.moviSize += ( chunkSize + paddingSize ); - afd.a.totalBytes += bytesInBuffer; - - // Index - bufIndex = 0; - WRITE_STRING( "01wb" ); //dwIdentifier - WRITE_4BYTES( 0 ); //dwFlags - WRITE_4BYTES( chunkOffset ); //dwOffset - WRITE_4BYTES( bytesInBuffer ); //dwLength - SafeFS_Write( buffer, 16, afd.idxF ); - - afd.numIndices++; - - bytesInBuffer = 0; - } +void CL_WriteAVIAudioFrame(const byte *pcmBuffer, int size) { + static byte pcmCaptureBuffer[PCM_BUFFER_SIZE] = {0}; + static int bytesInBuffer = 0; + + if (!afd.audio) + return; + + if (!afd.fileOpen) + return; + + // Chunk header + contents + padding + if (CL_CheckFileSize(8 + bytesInBuffer + size + 2)) + return; + + if (bytesInBuffer + size > PCM_BUFFER_SIZE) { + Com_Printf(S_COLOR_YELLOW "WARNING: Audio capture buffer overflow -- truncating\n"); + size = PCM_BUFFER_SIZE - bytesInBuffer; + } + + Com_Memcpy(&pcmCaptureBuffer[bytesInBuffer], pcmBuffer, size); + bytesInBuffer += size; + + // Only write if we have a frame's worth of audio + if (bytesInBuffer >= (int)ceil((float)afd.a.rate / (float)afd.frameRate) * afd.a.sampleSize) { + int chunkOffset = afd.fileSize - afd.moviOffset - 8; + int chunkSize = 8 + bytesInBuffer; + int paddingSize = PADLEN(bytesInBuffer, 2); + byte padding[4] = {0}; + + bufIndex = 0; + WRITE_STRING("01wb"); + WRITE_4BYTES(bytesInBuffer); + + SafeFS_Write(buffer, 8, afd.f); + SafeFS_Write(pcmCaptureBuffer, bytesInBuffer, afd.f); + SafeFS_Write(padding, paddingSize, afd.f); + afd.fileSize += (chunkSize + paddingSize); + + afd.numAudioFrames++; + afd.moviSize += (chunkSize + paddingSize); + afd.a.totalBytes += bytesInBuffer; + + // Index + bufIndex = 0; + WRITE_STRING("01wb"); // dwIdentifier + WRITE_4BYTES(0); // dwFlags + WRITE_4BYTES(chunkOffset); // dwOffset + WRITE_4BYTES(bytesInBuffer); // dwLength + SafeFS_Write(buffer, 16, afd.idxF); + + afd.numIndices++; + + bytesInBuffer = 0; + } } /* @@ -585,14 +542,12 @@ void CL_WriteAVIAudioFrame( const byte *pcmBuffer, int size ) CL_TakeVideoFrame =============== */ -void CL_TakeVideoFrame( void ) -{ - // AVI file isn't open - if( !afd.fileOpen ) - return; +void CL_TakeVideoFrame(void) { + // AVI file isn't open + if (!afd.fileOpen) + return; - re->TakeVideoFrame( afd.width, afd.height, - afd.cBuffer, afd.eBuffer, afd.motionJpeg ); + re->TakeVideoFrame(afd.width, afd.height, afd.cBuffer, afd.eBuffer, afd.motionJpeg); } /* @@ -602,71 +557,67 @@ CL_CloseAVI Closes the AVI file and writes an index chunk =============== */ -qboolean CL_CloseAVI( void ) -{ - int indexRemainder; - int indexSize = afd.numIndices * 16; - const char *idxFileName = va( "%s" INDEX_FILE_EXTENSION, afd.fileName ); +qboolean CL_CloseAVI(void) { + int indexRemainder; + int indexSize = afd.numIndices * 16; + const char *idxFileName = va("%s" INDEX_FILE_EXTENSION, afd.fileName); - // AVI file isn't open - if( !afd.fileOpen ) - return qfalse; + // AVI file isn't open + if (!afd.fileOpen) + return qfalse; - afd.fileOpen = qfalse; + afd.fileOpen = qfalse; - FS_Seek( afd.idxF, 4, FS_SEEK_SET ); - bufIndex = 0; - WRITE_4BYTES( indexSize ); - SafeFS_Write( buffer, bufIndex, afd.idxF ); - FS_FCloseFile( afd.idxF ); + FS_Seek(afd.idxF, 4, FS_SEEK_SET); + bufIndex = 0; + WRITE_4BYTES(indexSize); + SafeFS_Write(buffer, bufIndex, afd.idxF); + FS_FCloseFile(afd.idxF); - // Write index + // Write index - // Open the temp index file - if( ( indexSize = FS_FOpenFileRead( idxFileName, - &afd.idxF, qtrue ) ) <= 0 ) - { - FS_FCloseFile( afd.f ); - return qfalse; - } + // Open the temp index file + if ((indexSize = FS_FOpenFileRead(idxFileName, &afd.idxF, qtrue)) <= 0) { + FS_FCloseFile(afd.f); + return qfalse; + } - indexRemainder = indexSize; + indexRemainder = indexSize; - // Append index to end of avi file - while( indexRemainder > MAX_AVI_BUFFER ) - { - FS_Read( buffer, MAX_AVI_BUFFER, afd.idxF ); - SafeFS_Write( buffer, MAX_AVI_BUFFER, afd.f ); - afd.fileSize += MAX_AVI_BUFFER; - indexRemainder -= MAX_AVI_BUFFER; - } - FS_Read( buffer, indexRemainder, afd.idxF ); - SafeFS_Write( buffer, indexRemainder, afd.f ); - afd.fileSize += indexRemainder; - FS_FCloseFile( afd.idxF ); + // Append index to end of avi file + while (indexRemainder > MAX_AVI_BUFFER) { + FS_Read(buffer, MAX_AVI_BUFFER, afd.idxF); + SafeFS_Write(buffer, MAX_AVI_BUFFER, afd.f); + afd.fileSize += MAX_AVI_BUFFER; + indexRemainder -= MAX_AVI_BUFFER; + } + FS_Read(buffer, indexRemainder, afd.idxF); + SafeFS_Write(buffer, indexRemainder, afd.f); + afd.fileSize += indexRemainder; + FS_FCloseFile(afd.idxF); - // Remove temp index file - FS_HomeRemove( idxFileName ); + // Remove temp index file + FS_HomeRemove(idxFileName); - // Write the real header - FS_Seek( afd.f, 0, FS_SEEK_SET ); - CL_WriteAVIHeader( ); + // Write the real header + FS_Seek(afd.f, 0, FS_SEEK_SET); + CL_WriteAVIHeader(); - bufIndex = 4; - WRITE_4BYTES( afd.fileSize - 8 ); // "RIFF" size + bufIndex = 4; + WRITE_4BYTES(afd.fileSize - 8); // "RIFF" size - bufIndex = afd.moviOffset + 4; // Skip "LIST" - WRITE_4BYTES( afd.moviSize ); + bufIndex = afd.moviOffset + 4; // Skip "LIST" + WRITE_4BYTES(afd.moviSize); - SafeFS_Write( buffer, bufIndex, afd.f ); + SafeFS_Write(buffer, bufIndex, afd.f); - Z_Free( afd.cBuffer ); - Z_Free( afd.eBuffer ); - FS_FCloseFile( afd.f ); + Z_Free(afd.cBuffer); + Z_Free(afd.eBuffer); + FS_FCloseFile(afd.f); - Com_Printf( "Wrote %d:%d frames to %s\n", afd.numVideoFrames, afd.numAudioFrames, afd.fileName ); + Com_Printf("Wrote %d:%d frames to %s\n", afd.numVideoFrames, afd.numAudioFrames, afd.fileName); - return qtrue; + return qtrue; } /* @@ -674,7 +625,4 @@ qboolean CL_CloseAVI( void ) CL_VideoRecording =============== */ -qboolean CL_VideoRecording( void ) -{ - return afd.fileOpen; -} +qboolean CL_VideoRecording(void) { return afd.fileOpen; } diff --git a/codemp/client/cl_cgame.cpp b/codemp/client/cl_cgame.cpp index 8d228f19bc..7b20ac83dc 100644 --- a/codemp/client/cl_cgame.cpp +++ b/codemp/client/cl_cgame.cpp @@ -40,7 +40,7 @@ extern IHeapAllocator *G2VertSpaceClient; Ghoul2 Insert End */ -extern botlib_export_t *botlib_export; +extern botlib_export_t *botlib_export; extern qboolean loadCamera(const char *name); extern void startCamera(int time); @@ -51,21 +51,21 @@ extern qboolean getCameraInfo(int time, vec3_t *origin, vec3_t *angles); CL_GetUserCmd ==================== */ -qboolean CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { +qboolean CL_GetUserCmd(int cmdNumber, usercmd_t *ucmd) { // cmds[cmdNumber] is the last properly generated command // can't return anything that we haven't created yet - if ( cmdNumber > cl.cmdNumber ) { - Com_Error( ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber ); + if (cmdNumber > cl.cmdNumber) { + Com_Error(ERR_DROP, "CL_GetUserCmd: %i >= %i", cmdNumber, cl.cmdNumber); } // the usercmd has been overwritten in the wrapping // buffer because it is too far out of date - if ( cmdNumber <= cl.cmdNumber - CMD_BACKUP ) { + if (cmdNumber <= cl.cmdNumber - CMD_BACKUP) { return qfalse; } - *ucmd = cl.cmds[ cmdNumber & CMD_MASK ]; + *ucmd = cl.cmds[cmdNumber & CMD_MASK]; return qtrue; } @@ -75,19 +75,18 @@ qboolean CL_GetUserCmd( int cmdNumber, usercmd_t *ucmd ) { CL_GetParseEntityState ==================== */ -qboolean CL_GetParseEntityState( int parseEntityNumber, entityState_t *state ) { +qboolean CL_GetParseEntityState(int parseEntityNumber, entityState_t *state) { // can't return anything that hasn't been parsed yet - if ( parseEntityNumber >= cl.parseEntitiesNum ) { - Com_Error( ERR_DROP, "CL_GetParseEntityState: %i >= %i", - parseEntityNumber, cl.parseEntitiesNum ); + if (parseEntityNumber >= cl.parseEntitiesNum) { + Com_Error(ERR_DROP, "CL_GetParseEntityState: %i >= %i", parseEntityNumber, cl.parseEntitiesNum); } // can't return anything that has been overwritten in the circular buffer - if ( parseEntityNumber <= cl.parseEntitiesNum - MAX_PARSE_ENTITIES ) { + if (parseEntityNumber <= cl.parseEntitiesNum - MAX_PARSE_ENTITIES) { return qfalse; } - *state = cl.parseEntities[ parseEntityNumber & ( MAX_PARSE_ENTITIES - 1 ) ]; + *state = cl.parseEntities[parseEntityNumber & (MAX_PARSE_ENTITIES - 1)]; return qtrue; } @@ -96,28 +95,28 @@ qboolean CL_GetParseEntityState( int parseEntityNumber, entityState_t *state ) { CL_GetSnapshot ==================== */ -qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { - clSnapshot_t *clSnap; - int i, count; +qboolean CL_GetSnapshot(int snapshotNumber, snapshot_t *snapshot) { + clSnapshot_t *clSnap; + int i, count; - if ( snapshotNumber > cl.snap.messageNum ) { - Com_Error( ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.snapshot.messageNum" ); + if (snapshotNumber > cl.snap.messageNum) { + Com_Error(ERR_DROP, "CL_GetSnapshot: snapshotNumber > cl.snapshot.messageNum"); } // if the frame has fallen out of the circular buffer, we can't return it - if ( cl.snap.messageNum - snapshotNumber >= PACKET_BACKUP ) { + if (cl.snap.messageNum - snapshotNumber >= PACKET_BACKUP) { return qfalse; } // if the frame is not valid, we can't return it clSnap = &cl.snapshots[snapshotNumber & PACKET_MASK]; - if ( !clSnap->valid ) { + if (!clSnap->valid) { return qfalse; } // if the entities in the frame have fallen out of their // circular buffer, we can't return it - if ( cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES ) { + if (cl.parseEntitiesNum - clSnap->parseEntitiesNum >= MAX_PARSE_ENTITIES) { return qfalse; } @@ -126,22 +125,22 @@ qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { snapshot->serverCommandSequence = clSnap->serverCommandNum; snapshot->ping = clSnap->ping; snapshot->serverTime = clSnap->serverTime; - Com_Memcpy( snapshot->areamask, clSnap->areamask, sizeof( snapshot->areamask ) ); + Com_Memcpy(snapshot->areamask, clSnap->areamask, sizeof(snapshot->areamask)); snapshot->ps = clSnap->ps; - snapshot->vps = clSnap->vps; //get the vehicle ps + snapshot->vps = clSnap->vps; // get the vehicle ps count = clSnap->numEntities; - if ( count > MAX_ENTITIES_IN_SNAPSHOT ) { - Com_DPrintf( "CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT ); + if (count > MAX_ENTITIES_IN_SNAPSHOT) { + Com_DPrintf("CL_GetSnapshot: truncated %i entities to %i\n", count, MAX_ENTITIES_IN_SNAPSHOT); count = MAX_ENTITIES_IN_SNAPSHOT; } snapshot->numEntities = count; - for ( i = 0 ; i < count ; i++ ) { + for (i = 0; i < count; i++) { - int entNum = ( clSnap->parseEntitiesNum + i ) & (MAX_PARSE_ENTITIES-1) ; + int entNum = (clSnap->parseEntitiesNum + i) & (MAX_PARSE_ENTITIES - 1); // copy everything but the ghoul2 pointer - memcpy(&snapshot->entities[i], &cl.parseEntities[ entNum ], sizeof(entityState_t)); + memcpy(&snapshot->entities[i], &cl.parseEntities[entNum], sizeof(entityState_t)); } // FIXME: configstring changes and server commands!!! @@ -149,15 +148,12 @@ qboolean CL_GetSnapshot( int snapshotNumber, snapshot_t *snapshot ) { return qtrue; } -qboolean CL_GetDefaultState(int index, entityState_t *state) -{ - if (index < 0 || index >= MAX_GENTITIES) - { +qboolean CL_GetDefaultState(int index, entityState_t *state) { + if (index < 0 || index >= MAX_GENTITIES) { return qfalse; } - if (!(cl.entityBaselines[index].eFlags & EF_PERMANENT)) - { + if (!(cl.entityBaselines[index].eFlags & EF_PERMANENT)) { return qfalse; } @@ -174,7 +170,8 @@ CL_SetUserCmdValue extern float cl_mPitchOverride; extern float cl_mYawOverride; extern float cl_mSensitivityOverride; -void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, int invenSel ) { +void CL_SetUserCmdValue(int userCmdValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, + int invenSel) { cl.cgameUserCmdValue = userCmdValue; cl.cgameSensitivity = sensitivityScale; cl_mPitchOverride = mPitchOverride; @@ -185,21 +182,18 @@ void CL_SetUserCmdValue( int userCmdValue, float sensitivityScale, float mPitchO } int gCLTotalClientNum = 0; -//keep track of the total number of clients -extern cvar_t *cl_autolodscale; -//if we want to do autolodscaling +// keep track of the total number of clients +extern cvar_t *cl_autolodscale; +// if we want to do autolodscaling -void CL_DoAutoLODScale(void) -{ +void CL_DoAutoLODScale(void) { float finalLODScaleFactor = 0; - if ( gCLTotalClientNum >= 8 ) - { - finalLODScaleFactor = (gCLTotalClientNum/-8.0f); + if (gCLTotalClientNum >= 8) { + finalLODScaleFactor = (gCLTotalClientNum / -8.0f); } - - Cvar_Set( "r_autolodscalevalue", va("%f", finalLODScaleFactor) ); + Cvar_Set("r_autolodscalevalue", va("%f", finalLODScaleFactor)); } /* @@ -207,69 +201,64 @@ void CL_DoAutoLODScale(void) CL_ConfigstringModified ===================== */ -void CL_ConfigstringModified( void ) { - char *old, *s; - int i, index; - char *dup; - gameState_t oldGs; - int len; +void CL_ConfigstringModified(void) { + char *old, *s; + int i, index; + char *dup; + gameState_t oldGs; + int len; - index = atoi( Cmd_Argv(1) ); - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error( ERR_DROP, "CL_ConfigstringModified: bad index %i", index ); + index = atoi(Cmd_Argv(1)); + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "CL_ConfigstringModified: bad index %i", index); } // get everything after "cs " s = Cmd_ArgsFrom(2); - old = cl.gameState.stringData + cl.gameState.stringOffsets[ index ]; - if ( !strcmp( old, s ) ) { - return; // unchanged + old = cl.gameState.stringData + cl.gameState.stringOffsets[index]; + if (!strcmp(old, s)) { + return; // unchanged } // build the new gameState_t oldGs = cl.gameState; - Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) ); + Com_Memset(&cl.gameState, 0, sizeof(cl.gameState)); // leave the first 0 for uninitialized strings cl.gameState.dataCount = 1; - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( i == index ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (i == index) { dup = s; } else { - dup = oldGs.stringData + oldGs.stringOffsets[ i ]; + dup = oldGs.stringData + oldGs.stringOffsets[i]; } - if ( !dup[0] ) { - continue; // leave with the default empty string + if (!dup[0]) { + continue; // leave with the default empty string } - len = strlen( dup ); + len = strlen(dup); - if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) { - Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" ); + if (len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS) { + Com_Error(ERR_DROP, "MAX_GAMESTATE_CHARS exceeded"); } // append it to the gameState string buffer - cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount; - Com_Memcpy( cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1 ); + cl.gameState.stringOffsets[i] = cl.gameState.dataCount; + Com_Memcpy(cl.gameState.stringData + cl.gameState.dataCount, dup, len + 1); cl.gameState.dataCount += len + 1; } - if (cl_autolodscale && cl_autolodscale->integer) - { - if (index >= CS_PLAYERS && - index < CS_G2BONES) - { //this means that a client was updated in some way. Go through and count the clients. + if (cl_autolodscale && cl_autolodscale->integer) { + if (index >= CS_PLAYERS && index < CS_G2BONES) { // this means that a client was updated in some way. Go through and count the clients. int clientCount = 0; i = CS_PLAYERS; - while (i < CS_G2BONES) - { - s = cl.gameState.stringData + cl.gameState.stringOffsets[ i ]; + while (i < CS_G2BONES) { + s = cl.gameState.stringData + cl.gameState.stringOffsets[i]; - if (s && s[0]) - { + if (s && s[0]) { clientCount++; } @@ -286,27 +275,23 @@ void CL_ConfigstringModified( void ) { } } - if ( index == CS_SYSTEMINFO ) { + if (index == CS_SYSTEMINFO) { // parse serverId and other cvars CL_SystemInfoChanged(); } - } #ifndef MAX_STRINGED_SV_STRING - #define MAX_STRINGED_SV_STRING 1024 +#define MAX_STRINGED_SV_STRING 1024 #endif // just copied it from CG_CheckSVStringEdRef( -void CL_CheckSVStringEdRef(char *buf, const char *str) -{ //I don't really like doing this. But it utilizes the system that was already in place. +void CL_CheckSVStringEdRef(char *buf, const char *str) { // I don't really like doing this. But it utilizes the system that was already in place. int i = 0; int b = 0; int strLen = 0; qboolean gotStrip = qfalse; - if (!str || !str[0]) - { - if (str) - { + if (!str || !str[0]) { + if (str) { strcpy(buf, str); } return; @@ -316,31 +301,24 @@ void CL_CheckSVStringEdRef(char *buf, const char *str) strLen = strlen(str); - if (strLen >= MAX_STRINGED_SV_STRING) - { + if (strLen >= MAX_STRINGED_SV_STRING) { return; } - while (i < strLen && str[i]) - { + while (i < strLen && str[i]) { gotStrip = qfalse; - if (str[i] == '@' && (i+1) < strLen) - { - if (str[i+1] == '@' && (i+2) < strLen) - { - if (str[i+2] == '@' && (i+3) < strLen) - { //@@@ should mean to insert a StringEd reference here, so insert it into buf at the current place + if (str[i] == '@' && (i + 1) < strLen) { + if (str[i + 1] == '@' && (i + 2) < strLen) { + if (str[i + 2] == '@' && (i + 3) < strLen) { //@@@ should mean to insert a StringEd reference here, so insert it into buf at the current place char stringRef[MAX_STRINGED_SV_STRING]; int r = 0; - while (i < strLen && str[i] == '@') - { + while (i < strLen && str[i] == '@') { i++; } - while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') - { + while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') { stringRef[r] = str[i]; r++; i++; @@ -354,8 +332,7 @@ void CL_CheckSVStringEdRef(char *buf, const char *str) } } - if (!gotStrip) - { + if (!gotStrip) { buf[b] = str[i]; b++; } @@ -371,92 +348,89 @@ CL_GetServerCommand Set up argc/argv for the given command =================== */ -qboolean CL_GetServerCommand( int serverCommandNumber ) { - char *s; - char *cmd; +qboolean CL_GetServerCommand(int serverCommandNumber) { + char *s; + char *cmd; static char bigConfigString[BIG_INFO_STRING]; // if we have irretrievably lost a reliable command, drop the connection - if ( serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS ) - { + if (serverCommandNumber <= clc.serverCommandSequence - MAX_RELIABLE_COMMANDS) { int i = 0; // when a demo record was started after the client got a whole bunch of // reliable commands then the client never got those first reliable commands - if ( clc.demoplaying ) + if (clc.demoplaying) return qfalse; - while (i < MAX_RELIABLE_COMMANDS) - { //spew out the reliable command buffer - if (clc.reliableCommands[i][0]) - { + while (i < MAX_RELIABLE_COMMANDS) { // spew out the reliable command buffer + if (clc.reliableCommands[i][0]) { Com_Printf("%i: %s\n", i, clc.reliableCommands[i]); } i++; } - Com_Error( ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out" ); + Com_Error(ERR_DROP, "CL_GetServerCommand: a reliable command was cycled out"); return qfalse; } - if ( serverCommandNumber > clc.serverCommandSequence ) { - Com_Error( ERR_DROP, "CL_GetServerCommand: requested a command not received" ); + if (serverCommandNumber > clc.serverCommandSequence) { + Com_Error(ERR_DROP, "CL_GetServerCommand: requested a command not received"); return qfalse; } - s = clc.serverCommands[ serverCommandNumber & ( MAX_RELIABLE_COMMANDS - 1 ) ]; + s = clc.serverCommands[serverCommandNumber & (MAX_RELIABLE_COMMANDS - 1)]; clc.lastExecutedServerCommand = serverCommandNumber; - Com_DPrintf( "serverCommand: %i : %s\n", serverCommandNumber, s ); + Com_DPrintf("serverCommand: %i : %s\n", serverCommandNumber, s); rescan: - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); cmd = Cmd_Argv(0); - if ( !strcmp( cmd, "disconnect" ) ) { + if (!strcmp(cmd, "disconnect")) { char strEd[MAX_STRINGED_SV_STRING]; CL_CheckSVStringEdRef(strEd, Cmd_Argv(1)); - Com_Error (ERR_SERVERDISCONNECT, "%s: %s\n", SE_GetString("MP_SVGAME_SERVER_DISCONNECTED"), strEd ); + Com_Error(ERR_SERVERDISCONNECT, "%s: %s\n", SE_GetString("MP_SVGAME_SERVER_DISCONNECTED"), strEd); } - if ( !strcmp( cmd, "bcs0" ) ) { - Com_sprintf( bigConfigString, BIG_INFO_STRING, "cs %s \"%s", Cmd_Argv(1), Cmd_Argv(2) ); + if (!strcmp(cmd, "bcs0")) { + Com_sprintf(bigConfigString, BIG_INFO_STRING, "cs %s \"%s", Cmd_Argv(1), Cmd_Argv(2)); return qfalse; } - if ( !strcmp( cmd, "bcs1" ) ) { + if (!strcmp(cmd, "bcs1")) { s = Cmd_Argv(2); - if( strlen(bigConfigString) + strlen(s) >= BIG_INFO_STRING ) { - Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" ); + if (strlen(bigConfigString) + strlen(s) >= BIG_INFO_STRING) { + Com_Error(ERR_DROP, "bcs exceeded BIG_INFO_STRING"); } - strcat( bigConfigString, s ); + strcat(bigConfigString, s); return qfalse; } - if ( !strcmp( cmd, "bcs2" ) ) { + if (!strcmp(cmd, "bcs2")) { s = Cmd_Argv(2); - if( strlen(bigConfigString) + strlen(s) + 1 >= BIG_INFO_STRING ) { - Com_Error( ERR_DROP, "bcs exceeded BIG_INFO_STRING" ); + if (strlen(bigConfigString) + strlen(s) + 1 >= BIG_INFO_STRING) { + Com_Error(ERR_DROP, "bcs exceeded BIG_INFO_STRING"); } - strcat( bigConfigString, s ); - strcat( bigConfigString, "\"" ); + strcat(bigConfigString, s); + strcat(bigConfigString, "\""); s = bigConfigString; goto rescan; } - if ( !strcmp( cmd, "cs" ) ) { + if (!strcmp(cmd, "cs")) { CL_ConfigstringModified(); // reparse the string, because CL_ConfigstringModified may have done another Cmd_TokenizeString() - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); return qtrue; } - if ( !strcmp( cmd, "map_restart" ) ) { + if (!strcmp(cmd, "map_restart")) { // clear notify lines and outgoing commands before passing // the restart to the cgame Con_ClearNotify(); // reparse the string, because Con_ClearNotify() may have done another Cmd_TokenizeString() - Cmd_TokenizeString( s ); - Com_Memset( cl.cmds, 0, sizeof( cl.cmds ) ); + Cmd_TokenizeString(s); + Com_Memset(cl.cmds, 0, sizeof(cl.cmds)); return qtrue; } @@ -465,17 +439,17 @@ qboolean CL_GetServerCommand( int serverCommandNumber ) { // point of levels for the menu system to use // we pass it along to the cgame to make appropriate adjustments, // but we also clear the console and notify lines here - if ( !strcmp( cmd, "clientLevelShot" ) ) { + if (!strcmp(cmd, "clientLevelShot")) { // don't do it if we aren't running the server locally, // otherwise malicious remote servers could overwrite // the existing thumbnails - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return qfalse; } // close the console Con_Close(); // take a special screenshot next frame - Cbuf_AddText( "wait ; wait ; wait ; wait ; screenshot levelshot\n" ); + Cbuf_AddText("wait ; wait ; wait ; wait ; screenshot levelshot\n"); return qtrue; } @@ -491,10 +465,10 @@ CL_ShutdonwCGame ==================== */ -void CL_ShutdownCGame( void ) { - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CGAME ); +void CL_ShutdownCGame(void) { + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_CGAME); - if ( !cls.cgameStarted ) + if (!cls.cgameStarted) return; cls.cgameStarted = qfalse; @@ -510,10 +484,10 @@ Should only be called by CL_StartHunkUsers ==================== */ -void CL_InitCGame( void ) { - const char *info; - const char *mapname; - int t1, t2; +void CL_InitCGame(void) { + const char *info; + const char *mapname; + int t1, t2; t1 = Sys_Milliseconds(); @@ -521,9 +495,9 @@ void CL_InitCGame( void ) { Con_Close(); // find the current mapname - info = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SERVERINFO ]; - mapname = Info_ValueForKey( info, "mapname" ); - Com_sprintf( cl.mapname, sizeof( cl.mapname ), "maps/%s.bsp", mapname ); + info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SERVERINFO]; + mapname = Info_ValueForKey(info, "mapname"); + Com_sprintf(cl.mapname, sizeof(cl.mapname), "maps/%s.bsp", mapname); // load the dll CL_BindCGame(); @@ -533,15 +507,15 @@ void CL_InitCGame( void ) { // init for this gamestate // use the lastExecutedServerCommand instead of the serverCommandSequence // otherwise server commands sent just before a gamestate are dropped - CGVM_Init( clc.serverMessageSequence, clc.lastExecutedServerCommand, clc.clientNum ); + CGVM_Init(clc.serverMessageSequence, clc.lastExecutedServerCommand, clc.clientNum); - int clRate = Cvar_VariableIntegerValue( "rate" ); - if ( clRate == 4000 ) { - Com_Printf( S_COLOR_YELLOW "WARNING: Old default /rate value detected (4000). Suggest typing /rate 25000 into console for a smoother connection!\n" ); + int clRate = Cvar_VariableIntegerValue("rate"); + if (clRate == 4000) { + Com_Printf(S_COLOR_YELLOW "WARNING: Old default /rate value detected (4000). Suggest typing /rate 25000 into console for a smoother connection!\n"); } // reset any CVAR_CHEAT cvars registered by cgame - if ( !clc.demoplaying && !cl_connectedToCheatServer ) + if (!clc.demoplaying && !cl_connectedToCheatServer) Cvar_SetCheatState(); // we will send a usercmd this frame, which @@ -550,23 +524,20 @@ void CL_InitCGame( void ) { t2 = Sys_Milliseconds(); - Com_Printf( "CL_InitCGame: %5.2f seconds\n", (t2-t1)/1000.0 ); + Com_Printf("CL_InitCGame: %5.2f seconds\n", (t2 - t1) / 1000.0); // have the renderer touch all its images, so they are present // on the card even if the driver does deferred loading re->EndRegistration(); // make sure everything is paged in -// if (!Sys_LowPhysicalMemory()) - { - Com_TouchMemory(); - } + // if (!Sys_LowPhysicalMemory()) + { Com_TouchMemory(); } // clear anything that got printed - Con_ClearNotify (); + Con_ClearNotify(); } - /* ==================== CL_GameCommand @@ -574,33 +545,29 @@ CL_GameCommand See if the current console command is claimed by the cgame ==================== */ -qboolean CL_GameCommand( void ) { - if ( !cls.cgameStarted ) +qboolean CL_GameCommand(void) { + if (!cls.cgameStarted) return qfalse; return CGVM_ConsoleCommand(); } - - /* ===================== CL_CGameRendering ===================== */ -void CL_CGameRendering( stereoFrame_t stereo ) { - //rww - RAGDOLL_BEGIN - if (!com_sv_running->integer) - { //set the server time to match the client time, if we don't have a server going. +void CL_CGameRendering(stereoFrame_t stereo) { + // rww - RAGDOLL_BEGIN + if (!com_sv_running->integer) { // set the server time to match the client time, if we don't have a server going. re->G2API_SetTime(cl.serverTime, 0); } re->G2API_SetTime(cl.serverTime, 1); - //rww - RAGDOLL_END + // rww - RAGDOLL_END - CGVM_DrawActiveFrame( cl.serverTime, stereo, clc.demoplaying ); + CGVM_DrawActiveFrame(cl.serverTime, stereo, clc.demoplaying); } - /* ================= CL_AdjustTimeDelta @@ -621,43 +588,43 @@ or bursted delayed packets. ================= */ -#define RESET_TIME 500 +#define RESET_TIME 500 -void CL_AdjustTimeDelta( void ) { - int newDelta; - int deltaDelta; +void CL_AdjustTimeDelta(void) { + int newDelta; + int deltaDelta; cl.newSnapshots = qfalse; // the delta never drifts when replaying a demo - if ( clc.demoplaying ) { + if (clc.demoplaying) { return; } newDelta = cl.snap.serverTime - cls.realtime; - deltaDelta = abs( newDelta - cl.serverTimeDelta ); + deltaDelta = abs(newDelta - cl.serverTimeDelta); - if ( deltaDelta > RESET_TIME ) { + if (deltaDelta > RESET_TIME) { cl.serverTimeDelta = newDelta; - cl.oldServerTime = cl.snap.serverTime; // FIXME: is this a problem for cgame? + cl.oldServerTime = cl.snap.serverTime; // FIXME: is this a problem for cgame? cl.serverTime = cl.snap.serverTime; - if ( cl_showTimeDelta->integer ) { - Com_Printf( " " ); + if (cl_showTimeDelta->integer) { + Com_Printf(" "); } - } else if ( deltaDelta > 100 ) { + } else if (deltaDelta > 100) { // fast adjust, cut the difference in half - if ( cl_showTimeDelta->integer ) { - Com_Printf( " " ); + if (cl_showTimeDelta->integer) { + Com_Printf(" "); } - cl.serverTimeDelta = ( cl.serverTimeDelta + newDelta ) >> 1; + cl.serverTimeDelta = (cl.serverTimeDelta + newDelta) >> 1; } else { // slow drift adjust, only move 1 or 2 msec // if any of the frames between this and the previous snapshot // had to be extrapolated, nudge our sense of time back a little // the granularity of +1 / -2 is too high for timescale modified frametimes - if ( com_timescale->value == 0 || com_timescale->value == 1 ) { - if ( cl.extrapolatedSnapshot ) { + if (com_timescale->value == 0 || com_timescale->value == 1) { + if (cl.extrapolatedSnapshot) { cl.extrapolatedSnapshot = qfalse; cl.serverTimeDelta -= 2; } else { @@ -667,20 +634,19 @@ void CL_AdjustTimeDelta( void ) { } } - if ( cl_showTimeDelta->integer ) { - Com_Printf( "%i ", cl.serverTimeDelta ); + if (cl_showTimeDelta->integer) { + Com_Printf("%i ", cl.serverTimeDelta); } } - /* ================== CL_FirstSnapshot ================== */ -void CL_FirstSnapshot( void ) { +void CL_FirstSnapshot(void) { // ignore snapshots that don't have entities - if ( cl.snap.snapFlags & SNAPFLAG_NOT_ACTIVE ) { + if (cl.snap.snapFlags & SNAPFLAG_NOT_ACTIVE) { return; } @@ -698,9 +664,9 @@ void CL_FirstSnapshot( void ) { // execute the contents of activeAction now // this is to allow scripting a timedemo to start right // after loading - if ( cl_activeAction->string[0] ) { - Cbuf_AddText( cl_activeAction->string ); - Cvar_Set( "activeAction", "" ); + if (cl_activeAction->string[0]) { + Cbuf_AddText(cl_activeAction->string); + Cvar_Set("activeAction", ""); } } @@ -709,53 +675,51 @@ void CL_FirstSnapshot( void ) { CL_SetCGameTime ================== */ -void CL_SetCGameTime( void ) { +void CL_SetCGameTime(void) { // getting a valid frame message ends the connection process - if ( cls.state != CA_ACTIVE ) { - if ( cls.state != CA_PRIMED ) { + if (cls.state != CA_ACTIVE) { + if (cls.state != CA_PRIMED) { return; } - if ( clc.demoplaying ) { + if (clc.demoplaying) { // we shouldn't get the first snapshot on the same frame // as the gamestate, because it causes a bad time skip - if ( !clc.firstDemoFrameSkipped ) { + if (!clc.firstDemoFrameSkipped) { clc.firstDemoFrameSkipped = qtrue; return; } CL_ReadDemoMessage(); } - if ( cl.newSnapshots ) { + if (cl.newSnapshots) { cl.newSnapshots = qfalse; CL_FirstSnapshot(); } - if ( cls.state != CA_ACTIVE ) { + if (cls.state != CA_ACTIVE) { return; } } // if we have gotten to this point, cl.snap is guaranteed to be valid - if ( !cl.snap.valid ) { - Com_Error( ERR_DROP, "CL_SetCGameTime: !cl.snap.valid" ); + if (!cl.snap.valid) { + Com_Error(ERR_DROP, "CL_SetCGameTime: !cl.snap.valid"); } // allow pause in single player - if ( sv_paused->integer && CL_CheckPaused() && com_sv_running->integer ) { + if (sv_paused->integer && CL_CheckPaused() && com_sv_running->integer) { // paused return; } - if ( cl.snap.serverTime < cl.oldFrameServerTime ) { - Com_Error( ERR_DROP, "cl.snap.serverTime < cl.oldFrameServerTime" ); + if (cl.snap.serverTime < cl.oldFrameServerTime) { + Com_Error(ERR_DROP, "cl.snap.serverTime < cl.oldFrameServerTime"); } cl.oldFrameServerTime = cl.snap.serverTime; - // get our current view of time - if ( clc.demoplaying && cl_freezeDemo->integer ) { + if (clc.demoplaying && cl_freezeDemo->integer) { // cl_freezeDemo is used to lock a demo in place for single frame advances - } else - { + } else { // cl_timeNudge is a user adjustable cvar that allows more // or less latency to be added in the interest of better // smoothness or better responsiveness. @@ -763,15 +727,15 @@ void CL_SetCGameTime( void ) { tn = cl_timeNudge->integer; #ifdef _DEBUG - if (tn<-900) { + if (tn < -900) { tn = -900; - } else if (tn>900) { + } else if (tn > 900) { tn = 900; } #else - if (tn<-30) { + if (tn < -30) { tn = -30; - } else if (tn>30) { + } else if (tn > 30) { tn = 30; } #endif @@ -780,14 +744,14 @@ void CL_SetCGameTime( void ) { // guarantee that time will never flow backwards, even if // serverTimeDelta made an adjustment or cl_timeNudge was changed - if ( cl.serverTime < cl.oldServerTime ) { + if (cl.serverTime < cl.oldServerTime) { cl.serverTime = cl.oldServerTime; } cl.oldServerTime = cl.serverTime; // note if we are almost past the latest frame (without timeNudge), // so we will try and adjust back a bit when the next snapshot arrives - if ( cls.realtime + cl.serverTimeDelta >= cl.snap.serverTime - 5 ) { + if (cls.realtime + cl.serverTimeDelta >= cl.snap.serverTime - 5) { cl.extrapolatedSnapshot = qtrue; } } @@ -795,11 +759,11 @@ void CL_SetCGameTime( void ) { // if we have gotten new snapshots, drift serverTimeDelta // don't do this every frame, or a period of packet loss would // make a huge adjustment - if ( cl.newSnapshots ) { + if (cl.newSnapshots) { CL_AdjustTimeDelta(); } - if ( !clc.demoplaying ) { + if (!clc.demoplaying) { return; } @@ -811,7 +775,7 @@ void CL_SetCGameTime( void ) { // no matter what speed machine it is run on, // while a normal demo may have different time samples // each time it is played back - if ( cl_timedemo->integer ) { + if (cl_timedemo->integer) { if (!clc.timeDemoStart) { clc.timeDemoStart = Sys_Milliseconds(); } @@ -819,12 +783,12 @@ void CL_SetCGameTime( void ) { cl.serverTime = clc.timeDemoBaseTime + clc.timeDemoFrames * 50; } - while ( cl.serverTime >= cl.snap.serverTime ) { + while (cl.serverTime >= cl.snap.serverTime) { // feed another messag, which should change // the contents of cl.snap CL_ReadDemoMessage(); - if ( cls.state != CA_ACTIVE ) { - return; // end of demo + if (cls.state != CA_ACTIVE) { + return; // end of demo } } } diff --git a/codemp/client/cl_cgameapi.cpp b/codemp/client/cl_cgameapi.cpp index 15267443a6..3f1036a871 100644 --- a/codemp/client/cl_cgameapi.cpp +++ b/codemp/client/cl_cgameapi.cpp @@ -35,524 +35,518 @@ extern botlib_export_t *botlib_export; // cgame interface static cgameExport_t *cge; // cgame export table -static vm_t *cgvm; // cgame vm, valid for legacy and new api +static vm_t *cgvm; // cgame vm, valid for legacy and new api // // cgame vmMain calls // -void CGVM_Init( int serverMessageNum, int serverCommandSequence, int clientNum ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_INIT, serverMessageNum, serverCommandSequence, clientNum ); +void CGVM_Init(int serverMessageNum, int serverCommandSequence, int clientNum) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_INIT, serverMessageNum, serverCommandSequence, clientNum); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->Init( serverMessageNum, serverCommandSequence, clientNum ); + cge->Init(serverMessageNum, serverCommandSequence, clientNum); } -void CGVM_Shutdown( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_SHUTDOWN ); +void CGVM_Shutdown(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_SHUTDOWN); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->Shutdown(); } -qboolean CGVM_ConsoleCommand( void ) { - if ( cgvm->isLegacy ) { - return (qboolean)VM_Call( cgvm, CG_CONSOLE_COMMAND ); +qboolean CGVM_ConsoleCommand(void) { + if (cgvm->isLegacy) { + return (qboolean)VM_Call(cgvm, CG_CONSOLE_COMMAND); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->ConsoleCommand(); } -void CGVM_DrawActiveFrame( int serverTime, stereoFrame_t stereoView, qboolean demoPlayback ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_DRAW_ACTIVE_FRAME, serverTime, stereoView, demoPlayback ); +void CGVM_DrawActiveFrame(int serverTime, stereoFrame_t stereoView, qboolean demoPlayback) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_DRAW_ACTIVE_FRAME, serverTime, stereoView, demoPlayback); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->DrawActiveFrame( serverTime, stereoView, demoPlayback ); + cge->DrawActiveFrame(serverTime, stereoView, demoPlayback); } -int CGVM_CrosshairPlayer( void ) { - if ( cgvm->isLegacy ) { - return VM_Call( cgvm, CG_CROSSHAIR_PLAYER ); +int CGVM_CrosshairPlayer(void) { + if (cgvm->isLegacy) { + return VM_Call(cgvm, CG_CROSSHAIR_PLAYER); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->CrosshairPlayer(); } -int CGVM_LastAttacker( void ) { - if ( cgvm->isLegacy ) { - return VM_Call( cgvm, CG_LAST_ATTACKER ); +int CGVM_LastAttacker(void) { + if (cgvm->isLegacy) { + return VM_Call(cgvm, CG_LAST_ATTACKER); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->LastAttacker(); } -void CGVM_KeyEvent( int key, qboolean down ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_KEY_EVENT, key, down ); +void CGVM_KeyEvent(int key, qboolean down) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_KEY_EVENT, key, down); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->KeyEvent( key, down ); + cge->KeyEvent(key, down); } -void CGVM_MouseEvent( int x, int y ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_MOUSE_EVENT, x, y ); +void CGVM_MouseEvent(int x, int y) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_MOUSE_EVENT, x, y); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->MouseEvent( x, y ); + cge->MouseEvent(x, y); } -void CGVM_EventHandling( int type ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_EVENT_HANDLING, type ); +void CGVM_EventHandling(int type) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_EVENT_HANDLING, type); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->EventHandling( type ); + cge->EventHandling(type); } -int CGVM_PointContents( void ) { - if ( cgvm->isLegacy ) { - return VM_Call( cgvm, CG_POINT_CONTENTS ); +int CGVM_PointContents(void) { + if (cgvm->isLegacy) { + return VM_Call(cgvm, CG_POINT_CONTENTS); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->PointContents(); } -void CGVM_GetLerpOrigin( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_GET_LERP_ORIGIN ); +void CGVM_GetLerpOrigin(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_GET_LERP_ORIGIN); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->GetLerpOrigin(); } -void CGVM_GetLerpData( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_GET_LERP_DATA ); +void CGVM_GetLerpData(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_GET_LERP_DATA); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->GetLerpData(); } -void CGVM_Trace( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_TRACE ); +void CGVM_Trace(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_TRACE); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->Trace(); } -void CGVM_G2Trace( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_G2TRACE ); +void CGVM_G2Trace(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_G2TRACE); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->G2Trace(); } -void CGVM_G2Mark( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_G2MARK ); +void CGVM_G2Mark(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_G2MARK); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->G2Mark(); } -int CGVM_RagCallback( int callType ) { - if ( cgvm->isLegacy ) { - return VM_Call( cgvm, CG_RAG_CALLBACK, callType ); +int CGVM_RagCallback(int callType) { + if (cgvm->isLegacy) { + return VM_Call(cgvm, CG_RAG_CALLBACK, callType); } - VMSwap v( cgvm ); + VMSwap v(cgvm); - return cge->RagCallback( callType ); + return cge->RagCallback(callType); } -qboolean CGVM_IncomingConsoleCommand( void ) { - if ( cgvm->isLegacy ) { - return (qboolean)VM_Call( cgvm, CG_INCOMING_CONSOLE_COMMAND ); +qboolean CGVM_IncomingConsoleCommand(void) { + if (cgvm->isLegacy) { + return (qboolean)VM_Call(cgvm, CG_INCOMING_CONSOLE_COMMAND); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->IncomingConsoleCommand(); } -qboolean CGVM_NoUseableForce( void ) { - if ( cgvm->isLegacy ) { - return (qboolean)VM_Call( cgvm, CG_GET_USEABLE_FORCE ); +qboolean CGVM_NoUseableForce(void) { + if (cgvm->isLegacy) { + return (qboolean)VM_Call(cgvm, CG_GET_USEABLE_FORCE); } - VMSwap v( cgvm ); + VMSwap v(cgvm); return cge->NoUseableForce(); } -void CGVM_GetOrigin( int entID, vec3_t out ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_GET_ORIGIN, entID, reinterpret_cast< intptr_t >( out ) ); +void CGVM_GetOrigin(int entID, vec3_t out) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_GET_ORIGIN, entID, reinterpret_cast(out)); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->GetOrigin( entID, out ); + cge->GetOrigin(entID, out); } -void CGVM_GetAngles( int entID, vec3_t out ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_GET_ANGLES, entID, reinterpret_cast< intptr_t >( out ) ); +void CGVM_GetAngles(int entID, vec3_t out) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_GET_ANGLES, entID, reinterpret_cast(out)); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->GetAngles( entID, out ); + cge->GetAngles(entID, out); } -trajectory_t *CGVM_GetOriginTrajectory( int entID ) { - if ( cgvm->isLegacy ) { - return (trajectory_t *)VM_Call( cgvm, CG_GET_ORIGIN_TRAJECTORY, entID ); +trajectory_t *CGVM_GetOriginTrajectory(int entID) { + if (cgvm->isLegacy) { + return (trajectory_t *)VM_Call(cgvm, CG_GET_ORIGIN_TRAJECTORY, entID); } - VMSwap v( cgvm ); + VMSwap v(cgvm); - return cge->GetOriginTrajectory( entID ); + return cge->GetOriginTrajectory(entID); } -trajectory_t *CGVM_GetAngleTrajectory( int entID ) { - if ( cgvm->isLegacy ) { - return (trajectory_t *)VM_Call( cgvm, CG_GET_ANGLE_TRAJECTORY, entID ); +trajectory_t *CGVM_GetAngleTrajectory(int entID) { + if (cgvm->isLegacy) { + return (trajectory_t *)VM_Call(cgvm, CG_GET_ANGLE_TRAJECTORY, entID); } - VMSwap v( cgvm ); + VMSwap v(cgvm); - return cge->GetAngleTrajectory( entID ); + return cge->GetAngleTrajectory(entID); } -void CGVM_ROFF_NotetrackCallback( int entID, const char *notetrack ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_ROFF_NOTETRACK_CALLBACK, entID, reinterpret_cast< intptr_t >( notetrack ) ); +void CGVM_ROFF_NotetrackCallback(int entID, const char *notetrack) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_ROFF_NOTETRACK_CALLBACK, entID, reinterpret_cast(notetrack)); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); - cge->ROFF_NotetrackCallback( entID, notetrack ); + cge->ROFF_NotetrackCallback(entID, notetrack); } -void CGVM_MapChange( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_MAP_CHANGE ); +void CGVM_MapChange(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_MAP_CHANGE); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->MapChange(); } -void CGVM_AutomapInput( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_AUTOMAP_INPUT ); +void CGVM_AutomapInput(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_AUTOMAP_INPUT); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->AutomapInput(); } -void CGVM_MiscEnt( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_MISC_ENT ); +void CGVM_MiscEnt(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_MISC_ENT); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->MiscEnt(); } -void CGVM_CameraShake( void ) { - if ( cgvm->isLegacy ) { - VM_Call( cgvm, CG_FX_CAMERASHAKE ); +void CGVM_CameraShake(void) { + if (cgvm->isLegacy) { + VM_Call(cgvm, CG_FX_CAMERASHAKE); return; } - VMSwap v( cgvm ); + VMSwap v(cgvm); cge->CameraShake(); } - // // cgame syscalls // only used by legacy mods! // -extern int CL_GetValueForHidden( const char *s ); //cl_parse.cpp -extern qboolean cl_bUseFighterPitch; //cl_input.cpp -int CM_LoadSubBSP( const char *name, qboolean clientload ); //cm_load.cpp -void FX_FeedTrail( effectTrailArgStruct_t *a ); //FxPrimitives.cpp +extern int CL_GetValueForHidden(const char *s); // cl_parse.cpp +extern qboolean cl_bUseFighterPitch; // cl_input.cpp +int CM_LoadSubBSP(const char *name, qboolean clientload); // cm_load.cpp +void FX_FeedTrail(effectTrailArgStruct_t *a); // FxPrimitives.cpp // wrappers and such -static void CL_AddCgameCommand( const char *cmdName ) { - Cmd_AddCommand( cmdName, NULL ); -} +static void CL_AddCgameCommand(const char *cmdName) { Cmd_AddCommand(cmdName, NULL); } -static void CL_CM_LoadMap( const char *mapname, qboolean subBSP ) { - if ( subBSP ) CM_LoadSubBSP( va( "maps/%s.bsp", mapname+1 ), qfalse ); - else CM_LoadMap( mapname, qtrue, NULL ); +static void CL_CM_LoadMap(const char *mapname, qboolean subBSP) { + if (subBSP) + CM_LoadSubBSP(va("maps/%s.bsp", mapname + 1), qfalse); + else + CM_LoadMap(mapname, qtrue, NULL); } -static void CL_GetGlconfig( glconfig_t *glconfig ) { - *glconfig = cls.glconfig; -} +static void CL_GetGlconfig(glconfig_t *glconfig) { *glconfig = cls.glconfig; } -static void CL_GetGameState( gameState_t *gs ) { - *gs = cl.gameState; -} +static void CL_GetGameState(gameState_t *gs) { *gs = cl.gameState; } -static void RegisterSharedMemory( char *memory ) { - cl.mSharedMemory = memory; -} +static void RegisterSharedMemory(char *memory) { cl.mSharedMemory = memory; } -static int CL_Milliseconds( void ) { - return Sys_Milliseconds(); -} +static int CL_Milliseconds(void) { return Sys_Milliseconds(); } -static void CL_AddReliableCommand2( const char *cmd ) { - CL_AddReliableCommand( cmd, qfalse ); -} +static void CL_AddReliableCommand2(const char *cmd) { CL_AddReliableCommand(cmd, qfalse); } -static int CL_CM_RegisterTerrain( const char *config ) { - return 0; -} +static int CL_CM_RegisterTerrain(const char *config) { return 0; } extern int s_entityWavVol[MAX_GENTITIES]; -static int CL_S_GetVoiceVolume( int entID ) { - return s_entityWavVol[entID]; -} +static int CL_S_GetVoiceVolume(int entID) { return s_entityWavVol[entID]; } -static void CL_S_Shutup( qboolean shutup ) { - s_shutUp = shutup; -} +static void CL_S_Shutup(qboolean shutup) { s_shutUp = shutup; } -static int CL_GetCurrentCmdNumber( void ) { - return cl.cmdNumber; -} +static int CL_GetCurrentCmdNumber(void) { return cl.cmdNumber; } -static void _CL_SetUserCmdValue( int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, int invenSel, qboolean fighterControls ) { +static void _CL_SetUserCmdValue(int stateValue, float sensitivityScale, float mPitchOverride, float mYawOverride, float mSensitivityOverride, int fpSel, + int invenSel, qboolean fighterControls) { cl_bUseFighterPitch = fighterControls; - CL_SetUserCmdValue( stateValue, sensitivityScale, mPitchOverride, mYawOverride, mSensitivityOverride, fpSel, invenSel ); + CL_SetUserCmdValue(stateValue, sensitivityScale, mPitchOverride, mYawOverride, mSensitivityOverride, fpSel, invenSel); } -static void CL_OpenUIMenu( int menuID ) { - UIVM_SetActiveMenu( (uiMenuCommand_t)menuID ); -} +static void CL_OpenUIMenu(int menuID) { UIVM_SetActiveMenu((uiMenuCommand_t)menuID); } -static void CGFX_AddLine( vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int flags ) { - FX_AddLine( start, end, size1, size2, sizeParm, alpha1, alpha2, alphaParm, sRGB, eRGB, rgbParm, killTime, shader, flags ); +static void CGFX_AddLine(vec3_t start, vec3_t end, float size1, float size2, float sizeParm, float alpha1, float alpha2, float alphaParm, vec3_t sRGB, + vec3_t eRGB, float rgbParm, int killTime, qhandle_t shader, int flags) { + FX_AddLine(start, end, size1, size2, sizeParm, alpha1, alpha2, alphaParm, sRGB, eRGB, rgbParm, killTime, shader, flags); } -static void CGFX_AddPoly( addpolyArgStruct_t *p ) { - FX_AddPoly( p->p, p->ev, p->numVerts, p->vel, p->accel, p->alpha1, p->alpha2, p->alphaParm, p->rgb1, p->rgb2, p->rgbParm, p->rotationDelta, p->bounce, p->motionDelay, p->killTime, p->shader, p->flags ); +static void CGFX_AddPoly(addpolyArgStruct_t *p) { + FX_AddPoly(p->p, p->ev, p->numVerts, p->vel, p->accel, p->alpha1, p->alpha2, p->alphaParm, p->rgb1, p->rgb2, p->rgbParm, p->rotationDelta, p->bounce, + p->motionDelay, p->killTime, p->shader, p->flags); } -static void CGFX_AddBezier( addbezierArgStruct_t *b ) { - FX_AddBezier( b->start, b->end, b->control1, b->control1Vel, b->control2, b->control2Vel, b->size1, b->size2, b->sizeParm, b->alpha1, b->alpha2, b->alphaParm, b->sRGB, b->eRGB, b->rgbParm, b->killTime, b->shader, b->flags ); +static void CGFX_AddBezier(addbezierArgStruct_t *b) { + FX_AddBezier(b->start, b->end, b->control1, b->control1Vel, b->control2, b->control2Vel, b->size1, b->size2, b->sizeParm, b->alpha1, b->alpha2, + b->alphaParm, b->sRGB, b->eRGB, b->rgbParm, b->killTime, b->shader, b->flags); } -static void CGFX_AddPrimitive( effectTrailArgStruct_t *e ) { - FX_FeedTrail( e ); -} +static void CGFX_AddPrimitive(effectTrailArgStruct_t *e) { FX_FeedTrail(e); } -static void CGFX_AddSprite( addspriteArgStruct_t *s ) { - vec3_t rgb = { 1.0f, 1.0f, 1.0f }; - FX_AddParticle( s->origin, s->vel, s->accel, s->scale, s->dscale, 0, s->sAlpha, s->eAlpha, 0, rgb, rgb, 0, s->rotation, 0, vec3_origin, vec3_origin, s->bounce, 0, 0, s->life, s->shader, s->flags ); +static void CGFX_AddSprite(addspriteArgStruct_t *s) { + vec3_t rgb = {1.0f, 1.0f, 1.0f}; + FX_AddParticle(s->origin, s->vel, s->accel, s->scale, s->dscale, 0, s->sAlpha, s->eAlpha, 0, rgb, rgb, 0, s->rotation, 0, vec3_origin, vec3_origin, + s->bounce, 0, 0, s->life, s->shader, s->flags); } -static void CGFX_AddElectricity( addElectricityArgStruct_t *p ) { - FX_AddElectricity( p->start, p->end, p->size1, p->size2, p->sizeParm, p->alpha1, p->alpha2, p->alphaParm, p->sRGB, p->eRGB, p->rgbParm, p->chaos, p->killTime, p->shader, p->flags ); +static void CGFX_AddElectricity(addElectricityArgStruct_t *p) { + FX_AddElectricity(p->start, p->end, p->size1, p->size2, p->sizeParm, p->alpha1, p->alpha2, p->alphaParm, p->sRGB, p->eRGB, p->rgbParm, p->chaos, + p->killTime, p->shader, p->flags); } -static qboolean CL_ROFF_Clean( void ) { - return theROFFSystem.Clean( qtrue ); -} +static qboolean CL_ROFF_Clean(void) { return theROFFSystem.Clean(qtrue); } -static void CL_ROFF_UpdateEntities( void ) { - theROFFSystem.UpdateEntities( qtrue ); -} +static void CL_ROFF_UpdateEntities(void) { theROFFSystem.UpdateEntities(qtrue); } -static int CL_ROFF_Cache( char *file ) { - return theROFFSystem.Cache( file, qtrue ); -} +static int CL_ROFF_Cache(char *file) { return theROFFSystem.Cache(file, qtrue); } -static qboolean CL_ROFF_Play( int entID, int roffID, qboolean doTranslation ) { - return theROFFSystem.Play( entID, roffID, doTranslation, qtrue ); -} +static qboolean CL_ROFF_Play(int entID, int roffID, qboolean doTranslation) { return theROFFSystem.Play(entID, roffID, doTranslation, qtrue); } -static qboolean CL_ROFF_Purge_Ent( int entID ) { - return theROFFSystem.PurgeEnt( entID, qtrue ); -} +static qboolean CL_ROFF_Purge_Ent(int entID) { return theROFFSystem.PurgeEnt(entID, qtrue); } -static void CL_GetCurrentSnapshotNumber( int *snapshotNumber, int *serverTime ) { +static void CL_GetCurrentSnapshotNumber(int *snapshotNumber, int *serverTime) { *snapshotNumber = cl.snap.messageNum; *serverTime = cl.snap.serverTime; } -static void CL_SetClientForceAngle( int time, vec3_t angle ) { +static void CL_SetClientForceAngle(int time, vec3_t angle) { cl.cgameViewAngleForceTime = time; VectorCopy(angle, cl.cgameViewAngleForce); } -static void CL_PrecisionTimerStart( void **p ) { - timing_c *newTimer = new timing_c; //create the new timer - *p = newTimer; //assign the pointer within the pointer to point at the mem addr of our new timer - newTimer->Start(); //start the timer +static void CL_PrecisionTimerStart(void **p) { + timing_c *newTimer = new timing_c; // create the new timer + *p = newTimer; // assign the pointer within the pointer to point at the mem addr of our new timer + newTimer->Start(); // start the timer } -static int CL_PrecisionTimerEnd( void *p ) { +static int CL_PrecisionTimerEnd(void *p) { int r = 0; - timing_c *timer = (timing_c *)p; //this is the pointer we assigned in start, so we can directly cast it back - r = timer->End(); //get the result - delete timer; //delete the timer since we're done with it - return r; //return the result + timing_c *timer = (timing_c *)p; // this is the pointer we assigned in start, so we can directly cast it back + r = timer->End(); // get the result + delete timer; // delete the timer since we're done with it + return r; // return the result } -static void CL_RMG_Init( int /* terrainID */, const char * /* terrainInfo */ ) { } +static void CL_RMG_Init(int /* terrainID */, const char * /* terrainInfo */) {} -static qboolean CGFX_PlayBoltedEffectID( int id, vec3_t org, void *ghoul2, const int boltNum, const int entNum, const int modelNum, int iLooptime, qboolean isRelative ) { - if ( !ghoul2 ) return qfalse; +static qboolean CGFX_PlayBoltedEffectID(int id, vec3_t org, void *ghoul2, const int boltNum, const int entNum, const int modelNum, int iLooptime, + qboolean isRelative) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - int boltInfo=0; - if ( re->G2API_AttachEnt( &boltInfo, g2, modelNum, boltNum, entNum, modelNum ) ) - { - FX_PlayBoltedEffectID(id, org, boltInfo, &g2, iLooptime, isRelative ); + int boltInfo = 0; + if (re->G2API_AttachEnt(&boltInfo, g2, modelNum, boltNum, entNum, modelNum)) { + FX_PlayBoltedEffectID(id, org, boltInfo, &g2, iLooptime, isRelative); return qtrue; } return qfalse; } -static qboolean CL_SE_GetStringTextString( const char *text, char *buffer, int bufferLength ) { +static qboolean CL_SE_GetStringTextString(const char *text, char *buffer, int bufferLength) { const char *str; - assert( text && buffer ); + assert(text && buffer); - str = SE_GetString( text ); + str = SE_GetString(text); - if ( str[0] ) { - Q_strncpyz( buffer, str, bufferLength ); + if (str[0]) { + Q_strncpyz(buffer, str, bufferLength); return qtrue; } - Com_sprintf( buffer, bufferLength, "??%s", str ); + Com_sprintf(buffer, bufferLength, "??%s", str); return qfalse; } -static void CL_G2API_ListModelSurfaces( void *ghlInfo ) { - re->G2API_ListSurfaces( (CGhoul2Info *)ghlInfo ); -} +static void CL_G2API_ListModelSurfaces(void *ghlInfo) { re->G2API_ListSurfaces((CGhoul2Info *)ghlInfo); } -static void CL_G2API_ListModelBones( void *ghlInfo, int frame ) { - re->G2API_ListBones( (CGhoul2Info *)ghlInfo, frame ); -} +static void CL_G2API_ListModelBones(void *ghlInfo, int frame) { re->G2API_ListBones((CGhoul2Info *)ghlInfo, frame); } -static void CL_G2API_SetGhoul2ModelIndexes( void *ghoul2, qhandle_t *modelList, qhandle_t *skinList ) { - if ( !ghoul2 ) return; - re->G2API_SetGhoul2ModelIndexes( *((CGhoul2Info_v *)ghoul2), modelList, skinList ); +static void CL_G2API_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + if (!ghoul2) + return; + re->G2API_SetGhoul2ModelIndexes(*((CGhoul2Info_v *)ghoul2), modelList, skinList); } -static qboolean CL_G2API_HaveWeGhoul2Models( void *ghoul2) { - if ( !ghoul2 ) return qfalse; - return re->G2API_HaveWeGhoul2Models( *((CGhoul2Info_v *)ghoul2) ); +static qboolean CL_G2API_HaveWeGhoul2Models(void *ghoul2) { + if (!ghoul2) + return qfalse; + return re->G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ghoul2)); } -static qboolean CL_G2API_GetBoltMatrix( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); +static qboolean CL_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean CL_G2API_GetBoltMatrix_NoReconstruct( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; - re->G2API_BoltMatrixReconstruction( qfalse ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); +static qboolean CL_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; + re->G2API_BoltMatrixReconstruction(qfalse); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean CL_G2API_GetBoltMatrix_NoRecNoRot( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; // Intentionally not setting bolt matrix reconstruction state per original code comments - re->G2API_BoltMatrixSPMethod( qtrue ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); + re->G2API_BoltMatrixSPMethod(qtrue); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static int CL_G2API_InitGhoul2Model( void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias ) { +static int CL_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - return re->G2API_InitGhoul2Model( (CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias ); + return re->G2API_InitGhoul2Model((CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } -static qboolean CL_G2API_SetSkin( void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_SetSkin( g2, modelIndex, customSkin, renderSkin ); + return re->G2API_SetSkin(g2, modelIndex, customSkin, renderSkin); } -static void CL_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - if ( !ghoul2 ) return; - re->G2API_CollisionDetect( collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, traceFlags, useLod, fRadius ); +static void CL_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) + return; + re->G2API_CollisionDetect(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, + traceFlags, useLod, fRadius); } -static void CL_G2API_CollisionDetectCache( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - if ( !ghoul2 ) return; - re->G2API_CollisionDetectCache( collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, traceFlags, useLod, fRadius ); +static void CL_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) + return; + re->G2API_CollisionDetectCache(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, + traceFlags, useLod, fRadius); } -static void CL_G2API_CleanGhoul2Models( void **ghoul2Ptr ) { +static void CL_G2API_CleanGhoul2Models(void **ghoul2Ptr) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - re->G2API_CleanGhoul2Models( (CGhoul2Info_v **)ghoul2Ptr ); + re->G2API_CleanGhoul2Models((CGhoul2Info_v **)ghoul2Ptr); } -static qboolean CL_G2API_SetBoneAngles( void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, const int forward, qhandle_t *modelList, int blendTime , int currentTime ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetBoneAngles( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName, angles, flags, (const Eorientations)up, (const Eorientations)right, (const Eorientations)forward, modelList, blendTime , currentTime ); +static qboolean CL_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (!ghoul2) + return qfalse; + return re->G2API_SetBoneAngles(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, angles, flags, (const Eorientations)up, (const Eorientations)right, + (const Eorientations)forward, modelList, blendTime, currentTime); } -static qboolean CL_G2API_SetBoneAnim( void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame, const int blendTime ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetBoneAnim( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime ); +static qboolean CL_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + if (!ghoul2) + return qfalse; + return re->G2API_SetBoneAnim(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } -static qboolean CL_G2API_GetBoneAnim( void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList, const int modelIndex ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_GetBoneAnim( g2, modelIndex, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList ); + return re->G2API_GetBoneAnim(g2, modelIndex, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList); } -static qboolean CL_G2API_GetBoneFrame( void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *modelList, const int modelIndex ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_GetBoneFrame(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *modelList, const int modelIndex) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); int iDontCare1 = 0, iDontCare2 = 0, iDontCare3 = 0; float fDontCare1 = 0; @@ -560,157 +554,168 @@ static qboolean CL_G2API_GetBoneFrame( void *ghoul2, const char *boneName, const return re->G2API_GetBoneAnim(g2, modelIndex, boneName, currentTime, currentFrame, &iDontCare1, &iDontCare2, &iDontCare3, &fDontCare1, modelList); } -static void CL_G2API_GetGLAName( void *ghoul2, int modelIndex, char *fillBuf ) { - if ( !ghoul2 ) - { +static void CL_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { + if (!ghoul2) { fillBuf[0] = '\0'; return; } - char *tmp = re->G2API_GetGLAName( *((CGhoul2Info_v *)ghoul2), modelIndex ); - if ( tmp ) - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetGLAName(*((CGhoul2Info_v *)ghoul2), modelIndex); + if (tmp) + strcpy(fillBuf, tmp); else fillBuf[0] = '\0'; } -static int CL_G2API_CopyGhoul2Instance( void *g2From, void *g2To, int modelIndex ) { - if ( !g2From || !g2To ) return 0; +static int CL_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { + if (!g2From || !g2To) + return 0; - return re->G2API_CopyGhoul2Instance( *((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex ); + return re->G2API_CopyGhoul2Instance(*((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex); } -static void CL_G2API_CopySpecificGhoul2Model( void *g2From, int modelFrom, void *g2To, int modelTo ) { - if ( !g2From || !g2To) return; - re->G2API_CopySpecificG2Model( *((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo ); +static void CL_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { + if (!g2From || !g2To) + return; + re->G2API_CopySpecificG2Model(*((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo); } -static void CL_G2API_DuplicateGhoul2Instance( void *g2From, void **g2To ) { +static void CL_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - if ( !g2From || !g2To ) return; - re->G2API_DuplicateGhoul2Instance( *((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To ); + if (!g2From || !g2To) + return; + re->G2API_DuplicateGhoul2Instance(*((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To); } -static qboolean CL_G2API_HasGhoul2ModelOnIndex( void *ghlInfo, int modelIndex ) { - return re->G2API_HasGhoul2ModelOnIndex( (CGhoul2Info_v **)ghlInfo, modelIndex ); -} +static qboolean CL_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { return re->G2API_HasGhoul2ModelOnIndex((CGhoul2Info_v **)ghlInfo, modelIndex); } -static qboolean CL_G2API_RemoveGhoul2Model( void *ghlInfo, int modelIndex ) { +static qboolean CL_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - return re->G2API_RemoveGhoul2Model( (CGhoul2Info_v **)ghlInfo, modelIndex ); + return re->G2API_RemoveGhoul2Model((CGhoul2Info_v **)ghlInfo, modelIndex); } -static qboolean CL_G2API_SkinlessModel( void *ghlInfo, int modelIndex ) { - if ( !ghlInfo ) return qfalse; +static qboolean CL_G2API_SkinlessModel(void *ghlInfo, int modelIndex) { + if (!ghlInfo) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghlInfo); - return re->G2API_SkinlessModel( g2, modelIndex ); + return re->G2API_SkinlessModel(g2, modelIndex); } -static int CL_G2API_GetNumGoreMarks( void *ghlInfo, int modelIndex ) { +static int CL_G2API_GetNumGoreMarks(void *ghlInfo, int modelIndex) { #ifdef _G2_GORE - if ( !ghlInfo ) return 0; + if (!ghlInfo) + return 0; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghlInfo); - return re->G2API_GetNumGoreMarks( g2, modelIndex ); + return re->G2API_GetNumGoreMarks(g2, modelIndex); #else return 0; #endif } -static void CL_G2API_AddSkinGore( void *ghlInfo, SSkinGoreData *gore ) { +static void CL_G2API_AddSkinGore(void *ghlInfo, SSkinGoreData *gore) { #ifdef _G2_GORE - if ( !ghlInfo ) return; - re->G2API_AddSkinGore( *((CGhoul2Info_v *)ghlInfo), *(SSkinGoreData *)gore ); + if (!ghlInfo) + return; + re->G2API_AddSkinGore(*((CGhoul2Info_v *)ghlInfo), *(SSkinGoreData *)gore); #endif } -static void CL_G2API_ClearSkinGore( void *ghlInfo ) { +static void CL_G2API_ClearSkinGore(void *ghlInfo) { #ifdef _G2_GORE - if ( !ghlInfo ) return; - re->G2API_ClearSkinGore( *((CGhoul2Info_v *)ghlInfo) ); + if (!ghlInfo) + return; + re->G2API_ClearSkinGore(*((CGhoul2Info_v *)ghlInfo)); #endif } -static int CL_G2API_Ghoul2Size( void *ghlInfo ) { - if ( !ghlInfo ) return 0; - return re->G2API_Ghoul2Size( *((CGhoul2Info_v *)ghlInfo) ); +static int CL_G2API_Ghoul2Size(void *ghlInfo) { + if (!ghlInfo) + return 0; + return re->G2API_Ghoul2Size(*((CGhoul2Info_v *)ghlInfo)); } -static int CL_G2API_AddBolt( void *ghoul2, int modelIndex, const char *boneName ) { - if ( !ghoul2 ) return -1; - return re->G2API_AddBolt( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName ); +static int CL_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { + if (!ghoul2) + return -1; + return re->G2API_AddBolt(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName); } -static qboolean CL_G2API_AttachEnt( int *boltInfo, void *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum ) { - if ( !ghlInfoTo ) return qfalse; +static qboolean CL_G2API_AttachEnt(int *boltInfo, void *ghlInfoTo, int toBoltIndex, int entNum, int toModelNum) { + if (!ghlInfoTo) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghlInfoTo); - return re->G2API_AttachEnt( boltInfo, g2, 0, toBoltIndex, entNum, toModelNum ); + return re->G2API_AttachEnt(boltInfo, g2, 0, toBoltIndex, entNum, toModelNum); } -static void CL_G2API_SetBoltInfo( void *ghoul2, int modelIndex, int boltInfo ) { - if ( !ghoul2 ) return; - re->G2API_SetBoltInfo( *((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo ); +static void CL_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { + if (!ghoul2) + return; + re->G2API_SetBoltInfo(*((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo); } -static qboolean CL_G2API_SetRootSurface( void *ghoul2, const int modelIndex, const char *surfaceName ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetRootSurface( *((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName ); +static qboolean CL_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const char *surfaceName) { + if (!ghoul2) + return qfalse; + return re->G2API_SetRootSurface(*((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName); } -static qboolean CL_G2API_SetSurfaceOnOff( void *ghoul2, const char *surfaceName, const int flags ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetSurfaceOnOff( *((CGhoul2Info_v *)ghoul2), surfaceName, flags ); +static qboolean CL_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { + if (!ghoul2) + return qfalse; + return re->G2API_SetSurfaceOnOff(*((CGhoul2Info_v *)ghoul2), surfaceName, flags); } -static qboolean CL_G2API_SetNewOrigin( void *ghoul2, const int boltIndex ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetNewOrigin( *((CGhoul2Info_v *)ghoul2), boltIndex ); +static qboolean CL_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { + if (!ghoul2) + return qfalse; + return re->G2API_SetNewOrigin(*((CGhoul2Info_v *)ghoul2), boltIndex); } -static qboolean CL_G2API_DoesBoneExist( void *ghoul2, int modelIndex, const char *boneName ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_DoesBoneExist( g2, modelIndex, boneName ); + return re->G2API_DoesBoneExist(g2, modelIndex, boneName); } -static int CL_G2API_GetSurfaceRenderStatus( void *ghoul2, const int modelIndex, const char *surfaceName ) { - if ( !ghoul2 ) return -1; +static int CL_G2API_GetSurfaceRenderStatus(void *ghoul2, const int modelIndex, const char *surfaceName) { + if (!ghoul2) + return -1; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_GetSurfaceRenderStatus( g2, modelIndex, surfaceName ); + return re->G2API_GetSurfaceRenderStatus(g2, modelIndex, surfaceName); } -static int CL_G2API_GetTime( void ) { - return re->G2API_GetTime( 0 ); -} +static int CL_G2API_GetTime(void) { return re->G2API_GetTime(0); } -static void CL_G2API_SetTime( int time, int clock ) { - re->G2API_SetTime( time, clock ); -} +static void CL_G2API_SetTime(int time, int clock) { re->G2API_SetTime(time, clock); } -static void CL_G2API_AbsurdSmoothing( void *ghoul2, qboolean status ) { - if ( !ghoul2 ) return; +static void CL_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { + if (!ghoul2) + return; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - re->G2API_AbsurdSmoothing( g2, status ); + re->G2API_AbsurdSmoothing(g2, status); } -static void CL_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { - if ( !ghoul2 ) return; +static void CL_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { + if (!ghoul2) + return; CRagDollParams rdParams; - if ( !params ) { - re->G2API_ResetRagDoll( *((CGhoul2Info_v *)ghoul2) ); + if (!params) { + re->G2API_ResetRagDoll(*((CGhoul2Info_v *)ghoul2)); return; } - VectorCopy( params->angles, rdParams.angles ); - VectorCopy( params->position, rdParams.position ); - VectorCopy( params->scale, rdParams.scale ); - VectorCopy( params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset ); - VectorCopy( params->pelvisPositionOffset, rdParams.pelvisPositionOffset ); + VectorCopy(params->angles, rdParams.angles); + VectorCopy(params->position, rdParams.position); + VectorCopy(params->scale, rdParams.scale); + VectorCopy(params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset); + VectorCopy(params->pelvisPositionOffset, rdParams.pelvisPositionOffset); rdParams.fImpactStrength = params->fImpactStrength; rdParams.fShotStrength = params->fShotStrength; @@ -725,158 +730,164 @@ static void CL_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { rdParams.RagPhase = (CRagDollParams::ERagPhase)params->RagPhase; rdParams.effectorsToTurnOff = (CRagDollParams::ERagEffector)params->effectorsToTurnOff; - re->G2API_SetRagDoll( *((CGhoul2Info_v *)ghoul2), &rdParams ); + re->G2API_SetRagDoll(*((CGhoul2Info_v *)ghoul2), &rdParams); } -static void CL_G2API_AnimateG2Models( void *ghoul2, int time, sharedRagDollUpdateParams_t *params ) { - if ( !ghoul2 ) return; - if ( !params ) return; +static void CL_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { + if (!ghoul2) + return; + if (!params) + return; CRagDollUpdateParams rduParams; - VectorCopy( params->angles, rduParams.angles ); - VectorCopy( params->position, rduParams.position ); - VectorCopy( params->scale, rduParams.scale ); - VectorCopy( params->velocity, rduParams.velocity ); + VectorCopy(params->angles, rduParams.angles); + VectorCopy(params->position, rduParams.position); + VectorCopy(params->scale, rduParams.scale); + VectorCopy(params->velocity, rduParams.velocity); rduParams.me = params->me; rduParams.settleFrame = params->settleFrame; - re->G2API_AnimateG2ModelsRag( *((CGhoul2Info_v *)ghoul2), time, &rduParams ); + re->G2API_AnimateG2ModelsRag(*((CGhoul2Info_v *)ghoul2), time, &rduParams); } -static qboolean CL_G2API_RagPCJConstraint( void *ghoul2, const char *boneName, vec3_t min, vec3_t max ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_RagPCJConstraint( *((CGhoul2Info_v *)ghoul2), boneName, min, max ); +static qboolean CL_G2API_RagPCJConstraint(void *ghoul2, const char *boneName, vec3_t min, vec3_t max) { + if (!ghoul2) + return qfalse; + return re->G2API_RagPCJConstraint(*((CGhoul2Info_v *)ghoul2), boneName, min, max); } -static qboolean CL_G2API_RagPCJGradientSpeed( void *ghoul2, const char *boneName, const float speed ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_RagPCJGradientSpeed( *((CGhoul2Info_v *)ghoul2), boneName, speed ); +static qboolean CL_G2API_RagPCJGradientSpeed(void *ghoul2, const char *boneName, const float speed) { + if (!ghoul2) + return qfalse; + return re->G2API_RagPCJGradientSpeed(*((CGhoul2Info_v *)ghoul2), boneName, speed); } -static qboolean CL_G2API_RagEffectorGoal( void *ghoul2, const char *boneName, vec3_t pos ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_RagEffectorGoal( *((CGhoul2Info_v *)ghoul2), boneName, pos ); +static qboolean CL_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { + if (!ghoul2) + return qfalse; + return re->G2API_RagEffectorGoal(*((CGhoul2Info_v *)ghoul2), boneName, pos); } -static qboolean CL_G2API_GetRagBonePos( void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_GetRagBonePos( *((CGhoul2Info_v *)ghoul2), boneName, pos, entAngles, entPos, entScale ); +static qboolean CL_G2API_GetRagBonePos(void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { + if (!ghoul2) + return qfalse; + return re->G2API_GetRagBonePos(*((CGhoul2Info_v *)ghoul2), boneName, pos, entAngles, entPos, entScale); } -static qboolean CL_G2API_RagEffectorKick( void *ghoul2, const char *boneName, vec3_t velocity ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_RagEffectorKick( *((CGhoul2Info_v *)ghoul2), boneName, velocity ); +static qboolean CL_G2API_RagEffectorKick(void *ghoul2, const char *boneName, vec3_t velocity) { + if (!ghoul2) + return qfalse; + return re->G2API_RagEffectorKick(*((CGhoul2Info_v *)ghoul2), boneName, velocity); } -static qboolean CL_G2API_RagForceSolve( void *ghoul2, qboolean force ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_RagForceSolve( *((CGhoul2Info_v *)ghoul2), force ); +static qboolean CL_G2API_RagForceSolve(void *ghoul2, qboolean force) { + if (!ghoul2) + return qfalse; + return re->G2API_RagForceSolve(*((CGhoul2Info_v *)ghoul2), force); } -static qboolean CL_G2API_SetBoneIKState( void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetBoneIKState( *((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params ); +static qboolean CL_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + if (!ghoul2) + return qfalse; + return re->G2API_SetBoneIKState(*((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params); } -static qboolean CL_G2API_IKMove( void *ghoul2, int time, sharedIKMoveParams_t *params ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_IKMove( *((CGhoul2Info_v *)ghoul2), time, params ); +static qboolean CL_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { + if (!ghoul2) + return qfalse; + return re->G2API_IKMove(*((CGhoul2Info_v *)ghoul2), time, params); } -static qboolean CL_G2API_RemoveBone( void *ghoul2, const char *boneName, int modelIndex ) { - if ( !ghoul2 ) return qfalse; +static qboolean CL_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_RemoveBone( g2, modelIndex, boneName ); + return re->G2API_RemoveBone(g2, modelIndex, boneName); } -static void CL_G2API_AttachInstanceToEntNum( void *ghoul2, int entityNum, qboolean server ) { - if ( !ghoul2 ) return; - re->G2API_AttachInstanceToEntNum( *((CGhoul2Info_v *)ghoul2), entityNum, server ); +static void CL_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { + if (!ghoul2) + return; + re->G2API_AttachInstanceToEntNum(*((CGhoul2Info_v *)ghoul2), entityNum, server); } -static void CL_G2API_ClearAttachedInstance( int entityNum ) { - re->G2API_ClearAttachedInstance( entityNum ); -} +static void CL_G2API_ClearAttachedInstance(int entityNum) { re->G2API_ClearAttachedInstance(entityNum); } -static void CL_G2API_CleanEntAttachments( void ) { - re->G2API_CleanEntAttachments(); -} +static void CL_G2API_CleanEntAttachments(void) { re->G2API_CleanEntAttachments(); } -static qboolean CL_G2API_OverrideServer( void *serverInstance ) { - if ( !serverInstance ) return qfalse; +static qboolean CL_G2API_OverrideServer(void *serverInstance) { + if (!serverInstance) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)serverInstance); - return re->G2API_OverrideServerWithClientData( g2, 0 ); + return re->G2API_OverrideServerWithClientData(g2, 0); } -static void CL_G2API_GetSurfaceName( void *ghoul2, int surfNumber, int modelIndex, char *fillBuf ) { - if ( !ghoul2 ) return; +static void CL_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { + if (!ghoul2) + return; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - char *tmp = re->G2API_GetSurfaceName( g2, modelIndex, surfNumber ); - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetSurfaceName(g2, modelIndex, surfNumber); + strcpy(fillBuf, tmp); } -static void CL_Key_SetCatcher( int catcher ) { +static void CL_Key_SetCatcher(int catcher) { // Don't allow the cgame module to close the console - Key_SetCatcher( catcher | ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ); + Key_SetCatcher(catcher | (Key_GetCatcher() & KEYCATCH_CONSOLE)); } -static void CGVM_Cvar_Set( const char *var_name, const char *value ) { - Cvar_VM_Set( var_name, value, VM_CGAME ); -} +static void CGVM_Cvar_Set(const char *var_name, const char *value) { Cvar_VM_Set(var_name, value, VM_CGAME); } -static void CGVM_Cmd_RemoveCommand( const char *cmd_name ) { - Cmd_VM_RemoveCommand( cmd_name, VM_CGAME ); -} +static void CGVM_Cmd_RemoveCommand(const char *cmd_name) { Cmd_VM_RemoveCommand(cmd_name, VM_CGAME); } // legacy syscall -intptr_t CL_CgameSystemCalls( intptr_t *args ) { - switch ( args[0] ) { - //rww - alright, DO NOT EVER add a GAME/CGAME/UI generic call without adding a trap to match, and - //all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also - //all be in the same order, and start at 100. +intptr_t CL_CgameSystemCalls(intptr_t *args) { + switch (args[0]) { + // rww - alright, DO NOT EVER add a GAME/CGAME/UI generic call without adding a trap to match, and + // all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also + // all be in the same order, and start at 100. case TRAP_MEMSET: - Com_Memset( VMA(1), args[2], args[3] ); + Com_Memset(VMA(1), args[2], args[3]); return 0; case TRAP_MEMCPY: - Com_Memcpy( VMA(1), VMA(2), args[3] ); + Com_Memcpy(VMA(1), VMA(2), args[3]); return 0; case TRAP_STRNCPY: - strncpy( (char *)VMA(1), (const char *)VMA(2), args[3] ); + strncpy((char *)VMA(1), (const char *)VMA(2), args[3]); return args[1]; case TRAP_SIN: - return FloatAsInt( sin( VMF(1) ) ); + return FloatAsInt(sin(VMF(1))); case TRAP_COS: - return FloatAsInt( cos( VMF(1) ) ); + return FloatAsInt(cos(VMF(1))); case TRAP_ATAN2: - return FloatAsInt( atan2( VMF(1), VMF(2) ) ); + return FloatAsInt(atan2(VMF(1), VMF(2))); case TRAP_SQRT: - return FloatAsInt( sqrt( VMF(1) ) ); + return FloatAsInt(sqrt(VMF(1))); case TRAP_MATRIXMULTIPLY: - MatrixMultiply( (vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3) ); + MatrixMultiply((vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3)); return 0; case TRAP_ANGLEVECTORS: - AngleVectors( (const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4) ); + AngleVectors((const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4)); return 0; case TRAP_PERPENDICULARVECTOR: - PerpendicularVector( (float *)VMA(1), (const float *)VMA(2) ); + PerpendicularVector((float *)VMA(1), (const float *)VMA(2)); return 0; case TRAP_FLOOR: - return FloatAsInt( floor( VMF(1) ) ); + return FloatAsInt(floor(VMF(1))); case TRAP_CEIL: - return FloatAsInt( ceil( VMF(1) ) ); + return FloatAsInt(ceil(VMF(1))); case TRAP_TESTPRINTINT: return 0; @@ -885,45 +896,45 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case TRAP_ACOS: - return FloatAsInt( Q_acos( VMF(1) ) ); + return FloatAsInt(Q_acos(VMF(1))); case TRAP_ASIN: - return FloatAsInt( Q_asin( VMF(1) ) ); + return FloatAsInt(Q_asin(VMF(1))); case CG_PRINT: - Com_Printf( "%s", (const char*)VMA(1) ); + Com_Printf("%s", (const char *)VMA(1)); return 0; case CG_ERROR: - Com_Error( ERR_DROP, "%s", (const char*)VMA(1) ); + Com_Error(ERR_DROP, "%s", (const char *)VMA(1)); return 0; case CG_MILLISECONDS: return CL_Milliseconds(); - //rww - precision timer funcs... -ALWAYS- call end after start with supplied ptr, or you'll get a nasty memory leak. - //not that you should be using these outside of debug anyway.. because you shouldn't be. So don't. + // rww - precision timer funcs... -ALWAYS- call end after start with supplied ptr, or you'll get a nasty memory leak. + // not that you should be using these outside of debug anyway.. because you shouldn't be. So don't. case CG_PRECISIONTIMER_START: - CL_PrecisionTimerStart( (void **)VMA(1) ); + CL_PrecisionTimerStart((void **)VMA(1)); return 0; case CG_PRECISIONTIMER_END: - return CL_PrecisionTimerEnd( (void *)args[1] ); + return CL_PrecisionTimerEnd((void *)args[1]); case CG_CVAR_REGISTER: - Cvar_Register( (vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4] ); + Cvar_Register((vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4]); return 0; case CG_CVAR_UPDATE: - Cvar_Update( (vmCvar_t *)VMA(1) ); + Cvar_Update((vmCvar_t *)VMA(1)); return 0; case CG_CVAR_SET: - Cvar_VM_Set( (const char *)VMA(1), (const char *)VMA(2), VM_CGAME ); + Cvar_VM_Set((const char *)VMA(1), (const char *)VMA(2), VM_CGAME); return 0; case CG_CVAR_VARIABLESTRINGBUFFER: - Cvar_VariableStringBuffer( (const char *)VMA(1), (char *)VMA(2), args[3] ); + Cvar_VariableStringBuffer((const char *)VMA(1), (char *)VMA(2), args[3]); return 0; case CG_CVAR_GETHIDDENVALUE: @@ -933,45 +944,45 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return Cmd_Argc(); case CG_ARGV: - Cmd_ArgvBuffer( args[1], (char *)VMA(2), args[3] ); + Cmd_ArgvBuffer(args[1], (char *)VMA(2), args[3]); return 0; case CG_ARGS: - Cmd_ArgsBuffer( (char *)VMA(1), args[2] ); + Cmd_ArgsBuffer((char *)VMA(1), args[2]); return 0; case CG_FS_FOPENFILE: - return FS_FOpenFileByMode( (const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3] ); + return FS_FOpenFileByMode((const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3]); case CG_FS_READ: - FS_Read( VMA(1), args[2], args[3] ); + FS_Read(VMA(1), args[2], args[3]); return 0; case CG_FS_WRITE: - FS_Write( VMA(1), args[2], args[3] ); + FS_Write(VMA(1), args[2], args[3]); return 0; case CG_FS_FCLOSEFILE: - FS_FCloseFile( args[1] ); + FS_FCloseFile(args[1]); return 0; case CG_FS_GETFILELIST: - return FS_GetFileList( (const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4] ); + return FS_GetFileList((const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4]); case CG_SENDCONSOLECOMMAND: - Cbuf_AddText( (const char *)VMA(1) ); + Cbuf_AddText((const char *)VMA(1)); return 0; case CG_ADDCOMMAND: - CL_AddCgameCommand( (const char *)VMA(1) ); + CL_AddCgameCommand((const char *)VMA(1)); return 0; case CG_REMOVECOMMAND: - Cmd_VM_RemoveCommand( (const char *)VMA(1), VM_CGAME ); + Cmd_VM_RemoveCommand((const char *)VMA(1), VM_CGAME); return 0; case CG_SENDCLIENTCOMMAND: - CL_AddReliableCommand2( (const char *)VMA(1) ); + CL_AddReliableCommand2((const char *)VMA(1)); return 0; case CG_UPDATESCREEN: @@ -984,59 +995,63 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_CM_LOADMAP: - CL_CM_LoadMap( (const char *)VMA(1), (qboolean)args[2] ); + CL_CM_LoadMap((const char *)VMA(1), (qboolean)args[2]); return 0; case CG_CM_NUMINLINEMODELS: return CM_NumInlineModels(); case CG_CM_INLINEMODEL: - return CM_InlineModel( args[1] ); + return CM_InlineModel(args[1]); case CG_CM_TEMPBOXMODEL: - return CM_TempBoxModel( (const float *)VMA(1), (const float *)VMA(2), /*int capsule*/ qfalse ); + return CM_TempBoxModel((const float *)VMA(1), (const float *)VMA(2), /*int capsule*/ qfalse); case CG_CM_TEMPCAPSULEMODEL: - return CM_TempBoxModel( (const float *)VMA(1), (const float *)VMA(2), /*int capsule*/ qtrue ); + return CM_TempBoxModel((const float *)VMA(1), (const float *)VMA(2), /*int capsule*/ qtrue); case CG_CM_POINTCONTENTS: - return CM_PointContents( (const float *)VMA(1), args[2] ); + return CM_PointContents((const float *)VMA(1), args[2]); case CG_CM_TRANSFORMEDPOINTCONTENTS: - return CM_TransformedPointContents( (const float *)VMA(1), args[2], (const float *)VMA(3), (const float *)VMA(4) ); + return CM_TransformedPointContents((const float *)VMA(1), args[2], (const float *)VMA(3), (const float *)VMA(4)); case CG_CM_BOXTRACE: - CM_BoxTrace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], /*int capsule*/ qfalse ); + CM_BoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + /*int capsule*/ qfalse); return 0; case CG_CM_CAPSULETRACE: - CM_BoxTrace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], /*int capsule*/ qtrue ); + CM_BoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + /*int capsule*/ qtrue); return 0; case CG_CM_TRANSFORMEDBOXTRACE: - CM_TransformedBoxTrace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], (const float *)VMA(8), (const float *)VMA(9), /*int capsule*/ qfalse ); + CM_TransformedBoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + (const float *)VMA(8), (const float *)VMA(9), /*int capsule*/ qfalse); return 0; case CG_CM_TRANSFORMEDCAPSULETRACE: - CM_TransformedBoxTrace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], (const float *)VMA(8), (const float *)VMA(9), /*int capsule*/ qtrue ); + CM_TransformedBoxTrace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + (const float *)VMA(8), (const float *)VMA(9), /*int capsule*/ qtrue); return 0; case CG_CM_MARKFRAGMENTS: - return re->MarkFragments( args[1], (const vec3_t *)VMA(2), (const float *)VMA(3), args[4], (float *)VMA(5), args[6], (markFragment_t *)VMA(7) ); + return re->MarkFragments(args[1], (const vec3_t *)VMA(2), (const float *)VMA(3), args[4], (float *)VMA(5), args[6], (markFragment_t *)VMA(7)); case CG_S_GETVOICEVOLUME: - return CL_S_GetVoiceVolume( args[1] ); + return CL_S_GetVoiceVolume(args[1]); case CG_S_MUTESOUND: - S_MuteSound( args[1], args[2] ); + S_MuteSound(args[1], args[2]); return 0; case CG_S_STARTSOUND: - S_StartSound( (float *)VMA(1), args[2], args[3], args[4] ); + S_StartSound((float *)VMA(1), args[2], args[3], args[4]); return 0; case CG_S_STARTLOCALSOUND: - S_StartLocalSound( args[1], args[2] ); + S_StartLocalSound(args[1], args[2]); return 0; case CG_S_CLEARLOOPINGSOUNDS: @@ -1044,34 +1059,34 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_S_ADDLOOPINGSOUND: - S_AddLoopingSound( args[1], (const float *)VMA(2), (const float *)VMA(3), args[4] ); + S_AddLoopingSound(args[1], (const float *)VMA(2), (const float *)VMA(3), args[4]); return 0; case CG_S_ADDREALLOOPINGSOUND: - /*S_AddRealLoopingSound*/S_AddLoopingSound( args[1], (const float *)VMA(2), (const float *)VMA(3), args[4] ); + /*S_AddRealLoopingSound*/ S_AddLoopingSound(args[1], (const float *)VMA(2), (const float *)VMA(3), args[4]); return 0; case CG_S_STOPLOOPINGSOUND: - S_StopLoopingSound( args[1] ); + S_StopLoopingSound(args[1]); return 0; case CG_S_UPDATEENTITYPOSITION: - S_UpdateEntityPosition( args[1], (const float *)VMA(2) ); + S_UpdateEntityPosition(args[1], (const float *)VMA(2)); return 0; case CG_S_RESPATIALIZE: - S_Respatialize( args[1], (const float *)VMA(2), (vec3_t *)VMA(3), args[4] ); + S_Respatialize(args[1], (const float *)VMA(2), (vec3_t *)VMA(3), args[4]); return 0; case CG_S_SHUTUP: - CL_S_Shutup( (qboolean)args[1] ); + CL_S_Shutup((qboolean)args[1]); return 0; case CG_S_REGISTERSOUND: - return S_RegisterSound( (const char *)VMA(1) ); + return S_RegisterSound((const char *)VMA(1)); case CG_S_STARTBACKGROUNDTRACK: - S_StartBackgroundTrack( (const char *)VMA(1), (const char *)VMA(2), args[3]?qtrue:qfalse ); + S_StartBackgroundTrack((const char *)VMA(1), (const char *)VMA(2), args[3] ? qtrue : qfalse); return 0; case CG_S_UPDATEAMBIENTSET: @@ -1093,35 +1108,35 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return AS_GetBModelSound((const char *)VMA(1), args[2]); case CG_R_LOADWORLDMAP: - re->LoadWorld( (const char *)VMA(1) ); + re->LoadWorld((const char *)VMA(1)); return 0; case CG_R_REGISTERMODEL: - return re->RegisterModel( (const char *)VMA(1) ); + return re->RegisterModel((const char *)VMA(1)); case CG_R_REGISTERSKIN: - return re->RegisterSkin( (const char *)VMA(1) ); + return re->RegisterSkin((const char *)VMA(1)); case CG_R_REGISTERSHADER: - return re->RegisterShader( (const char *)VMA(1) ); + return re->RegisterShader((const char *)VMA(1)); case CG_R_REGISTERSHADERNOMIP: - return re->RegisterShaderNoMip( (const char *)VMA(1) ); + return re->RegisterShaderNoMip((const char *)VMA(1)); case CG_R_REGISTERFONT: - return re->RegisterFont( (const char *)VMA(1) ); + return re->RegisterFont((const char *)VMA(1)); case CG_R_FONT_STRLENPIXELS: - return re->Font_StrLenPixels( (const char *)VMA(1), args[2], VMF(3) ); + return re->Font_StrLenPixels((const char *)VMA(1), args[2], VMF(3)); case CG_R_FONT_STRLENCHARS: - return re->Font_StrLenChars( (const char *)VMA(1) ); + return re->Font_StrLenChars((const char *)VMA(1)); case CG_R_FONT_STRHEIGHTPIXELS: - return re->Font_HeightPixels( args[1], VMF(2) ); + return re->Font_HeightPixels(args[1], VMF(2)); case CG_R_FONT_DRAWSTRING: - re->Font_DrawString( args[1], args[2], (const char *)VMA(3), (const float *) VMA(4), args[5], args[6], VMF(7) ); + re->Font_DrawString(args[1], args[2], (const char *)VMA(3), (const float *)VMA(4), args[5], args[6], VMF(7)); return 0; case CG_LANGUAGE_ISASIAN: @@ -1131,7 +1146,7 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return re->Language_UsesSpaces(); case CG_ANYLANGUAGE_READCHARFROMSTRING: - return re->AnyLanguage_ReadCharFromString( (const char *) VMA(1), (int *) VMA(2), (qboolean *) VMA(3) ); + return re->AnyLanguage_ReadCharFromString((const char *)VMA(1), (int *)VMA(2), (qboolean *)VMA(3)); case CG_R_CLEARSCENE: re->ClearScene(); @@ -1142,96 +1157,97 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_R_ADDREFENTITYTOSCENE: - re->AddRefEntityToScene( (const refEntity_t *)VMA(1) ); + re->AddRefEntityToScene((const refEntity_t *)VMA(1)); return 0; case CG_R_ADDPOLYTOSCENE: - re->AddPolyToScene( args[1], args[2], (const polyVert_t *)VMA(3), 1 ); + re->AddPolyToScene(args[1], args[2], (const polyVert_t *)VMA(3), 1); return 0; case CG_R_ADDPOLYSTOSCENE: - re->AddPolyToScene( args[1], args[2], (const polyVert_t *)VMA(3), args[4] ); + re->AddPolyToScene(args[1], args[2], (const polyVert_t *)VMA(3), args[4]); return 0; case CG_R_ADDDECALTOSCENE: - re->AddDecalToScene( (qhandle_t)args[1], (const float*)VMA(2), (const float*)VMA(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), (qboolean)args[9], VMF(10), (qboolean)args[11] ); + re->AddDecalToScene((qhandle_t)args[1], (const float *)VMA(2), (const float *)VMA(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), (qboolean)args[9], + VMF(10), (qboolean)args[11]); return 0; case CG_R_LIGHTFORPOINT: - return re->LightForPoint( (float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4) ); + return re->LightForPoint((float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4)); case CG_R_ADDLIGHTTOSCENE: - re->AddLightToScene( (const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) ); + re->AddLightToScene((const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5)); return 0; case CG_R_ADDADDITIVELIGHTTOSCENE: - re->AddAdditiveLightToScene( (const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) ); + re->AddAdditiveLightToScene((const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5)); return 0; case CG_R_RENDERSCENE: - re->RenderScene( (const refdef_t *)VMA(1) ); + re->RenderScene((const refdef_t *)VMA(1)); return 0; case CG_R_SETCOLOR: - re->SetColor( (const float *)VMA(1) ); + re->SetColor((const float *)VMA(1)); return 0; case CG_R_DRAWSTRETCHPIC: - re->DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] ); + re->DrawStretchPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9]); return 0; case CG_R_MODELBOUNDS: - re->ModelBounds( args[1], (float *)VMA(2), (float *)VMA(3) ); + re->ModelBounds(args[1], (float *)VMA(2), (float *)VMA(3)); return 0; case CG_R_LERPTAG: - return re->LerpTag( (orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6) ); + return re->LerpTag((orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6)); case CG_R_DRAWROTATEPIC: - re->DrawRotatePic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10] ); + re->DrawRotatePic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10]); return 0; case CG_R_DRAWROTATEPIC2: - re->DrawRotatePic2( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10] ); + re->DrawRotatePic2(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), VMF(9), args[10]); return 0; case CG_R_SETRANGEFOG: - re->SetRangedFog( VMF(1) ); + re->SetRangedFog(VMF(1)); return 0; case CG_R_SETREFRACTIONPROP: - re->SetRefractionProperties( VMF(1), VMF(2), (qboolean)args[3], (qboolean)args[4] ); + re->SetRefractionProperties(VMF(1), VMF(2), (qboolean)args[3], (qboolean)args[4]); return 0; case CG_GETGLCONFIG: - CL_GetGlconfig( (glconfig_t *)VMA(1) ); + CL_GetGlconfig((glconfig_t *)VMA(1)); return 0; case CG_GETGAMESTATE: - CL_GetGameState( (gameState_t *)VMA(1) ); + CL_GetGameState((gameState_t *)VMA(1)); return 0; case CG_GETCURRENTSNAPSHOTNUMBER: - CL_GetCurrentSnapshotNumber( (int *)VMA(1), (int *)VMA(2) ); + CL_GetCurrentSnapshotNumber((int *)VMA(1), (int *)VMA(2)); return 0; case CG_GETSNAPSHOT: - return CL_GetSnapshot( args[1], (snapshot_t *)VMA(2) ); + return CL_GetSnapshot(args[1], (snapshot_t *)VMA(2)); case CG_GETDEFAULTSTATE: return CL_GetDefaultState(args[1], (entityState_t *)VMA(2)); case CG_GETSERVERCOMMAND: - return CL_GetServerCommand( args[1] ); + return CL_GetServerCommand(args[1]); case CG_GETCURRENTCMDNUMBER: return CL_GetCurrentCmdNumber(); case CG_GETUSERCMD: - return CL_GetUserCmd( args[1], (struct usercmd_s *)VMA(2) ); + return CL_GetUserCmd(args[1], (struct usercmd_s *)VMA(2)); case CG_SETUSERCMDVALUE: - _CL_SetUserCmdValue( args[1], VMF(2), VMF(3), VMF(4), VMF(5), args[6], args[7], (qboolean)args[8] ); + _CL_SetUserCmdValue(args[1], VMF(2), VMF(3), VMF(4), VMF(5), args[6], args[7], (qboolean)args[8]); return 0; case CG_SETCLIENTFORCEANGLE: @@ -1242,45 +1258,45 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_OPENUIMENU: - CL_OpenUIMenu( args[1] ); + CL_OpenUIMenu(args[1]); return 0; case CG_MEMORY_REMAINING: return Hunk_MemoryRemaining(); case CG_KEY_ISDOWN: - return Key_IsDown( args[1] ); + return Key_IsDown(args[1]); case CG_KEY_GETCATCHER: return Key_GetCatcher(); case CG_KEY_SETCATCHER: - CL_Key_SetCatcher( args[1] ); + CL_Key_SetCatcher(args[1]); return 0; case CG_KEY_GETKEY: - return Key_GetKey( (const char *)VMA(1) ); + return Key_GetKey((const char *)VMA(1)); case CG_PC_ADD_GLOBAL_DEFINE: - return botlib_export->PC_AddGlobalDefine( (char *)VMA(1) ); + return botlib_export->PC_AddGlobalDefine((char *)VMA(1)); case CG_PC_LOAD_SOURCE: - return botlib_export->PC_LoadSourceHandle( (const char *)VMA(1) ); + return botlib_export->PC_LoadSourceHandle((const char *)VMA(1)); case CG_PC_FREE_SOURCE: - return botlib_export->PC_FreeSourceHandle( args[1] ); + return botlib_export->PC_FreeSourceHandle(args[1]); case CG_PC_READ_TOKEN: - return botlib_export->PC_ReadTokenHandle( args[1], (struct pc_token_s *)VMA(2) ); + return botlib_export->PC_ReadTokenHandle(args[1], (struct pc_token_s *)VMA(2)); case CG_PC_SOURCE_FILE_AND_LINE: - return botlib_export->PC_SourceFileAndLine( args[1], (char *)VMA(2), (int *)VMA(3) ); + return botlib_export->PC_SourceFileAndLine(args[1], (char *)VMA(2), (int *)VMA(3)); case CG_PC_LOAD_GLOBAL_DEFINES: - return botlib_export->PC_LoadGlobalDefines ( (char *)VMA(1) ); + return botlib_export->PC_LoadGlobalDefines((char *)VMA(1)); case CG_PC_REMOVE_ALL_GLOBAL_DEFINES: - botlib_export->PC_RemoveAllGlobalDefines ( ); + botlib_export->PC_RemoveAllGlobalDefines(); return 0; case CG_S_STOPBACKGROUNDTRACK: @@ -1288,10 +1304,10 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_REAL_TIME: - return Com_RealTime( (struct qtime_s *)VMA(1) ); + return Com_RealTime((struct qtime_s *)VMA(1)); case CG_SNAPVECTOR: - Sys_SnapVector( (float *)VMA(1) ); + Sys_SnapVector((float *)VMA(1)); return 0; case CG_CIN_PLAYCINEMATIC: @@ -1312,7 +1328,7 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_R_REMAP_SHADER: - re->RemapShader( (const char *)VMA(1), (const char *)VMA(2), (const char *)VMA(3) ); + re->RemapShader((const char *)VMA(1), (const char *)VMA(2), (const char *)VMA(3)); return 0; case CG_R_GET_LIGHT_STYLE: @@ -1324,22 +1340,20 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_R_GET_BMODEL_VERTS: - re->GetBModelVerts( args[1], (float (*)[3])VMA(2), (float *)VMA(3) ); + re->GetBModelVerts(args[1], (float(*)[3])VMA(2), (float *)VMA(3)); return 0; - case CG_R_GETDISTANCECULL: - { - float *f = (float *)VMA(1); - *f = re->GetDistanceCull(); - } + case CG_R_GETDISTANCECULL: { + float *f = (float *)VMA(1); + *f = re->GetDistanceCull(); + } return 0; - case CG_R_GETREALRES: - { - int *w = (int *)VMA(1); - int *h = (int *)VMA(2); - re->GetRealRes( w, h ); - } + case CG_R_GETREALRES: { + int *w = (int *)VMA(1); + int *h = (int *)VMA(2); + re->GetRealRes(w, h); + } return 0; case CG_R_AUTOMAPELEVADJ: @@ -1350,23 +1364,21 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return re->InitializeWireframeAutomap(); case CG_GET_ENTITY_TOKEN: - return re->GetEntityToken( (char *)VMA(1), args[2] ); + return re->GetEntityToken((char *)VMA(1), args[2]); case CG_R_INPVS: - return re->inPVS( (const float *)VMA(1), (const float *)VMA(2), (byte *)VMA(3) ); + return re->inPVS((const float *)VMA(1), (const float *)VMA(2), (byte *)VMA(3)); #ifndef DEBUG_DISABLEFXCALLS case CG_FX_ADDLINE: - CGFX_AddLine( (float *)VMA(1), (float *)VMA(2), VMF(3), VMF(4), VMF(5), - VMF(6), VMF(7), VMF(8), - (float *)VMA(9), (float *)VMA(10), VMF(11), - args[12], args[13], args[14]); + CGFX_AddLine((float *)VMA(1), (float *)VMA(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), (float *)VMA(9), (float *)VMA(10), VMF(11), args[12], + args[13], args[14]); return 0; case CG_FX_REGISTER_EFFECT: return FX_RegisterEffect((const char *)VMA(1)); case CG_FX_PLAY_EFFECT: - FX_PlayEffect((const char *)VMA(1), (float *)VMA(2), (float *)VMA(3), args[4], args[5] ); + FX_PlayEffect((const char *)VMA(1), (float *)VMA(2), (float *)VMA(3), args[4], args[5]); return 0; case CG_FX_PLAY_ENTITY_EFFECT: @@ -1374,33 +1386,33 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_FX_PLAY_EFFECT_ID: - FX_PlayEffectID(args[1], (float *)VMA(2), (float *)VMA(3), args[4], args[5] ); + FX_PlayEffectID(args[1], (float *)VMA(2), (float *)VMA(3), args[4], args[5]); return 0; case CG_FX_PLAY_PORTAL_EFFECT_ID: - FX_PlayEffectID(args[1], (float *)VMA(2), (float *)VMA(3), args[4], args[5], qtrue ); + FX_PlayEffectID(args[1], (float *)VMA(2), (float *)VMA(3), args[4], args[5], qtrue); return 0; case CG_FX_PLAY_ENTITY_EFFECT_ID: - FX_PlayEntityEffectID(args[1], (float *)VMA(2), (vec3_t *)VMA(3), args[4], args[5], args[6], args[7] ); + FX_PlayEntityEffectID(args[1], (float *)VMA(2), (vec3_t *)VMA(3), args[4], args[5], args[6], args[7]); return 0; case CG_FX_PLAY_BOLTED_EFFECT_ID: - return CGFX_PlayBoltedEffectID( args[1], (float *)VMA(2), (void *)args[3], args[4], args[5], args[6], args[7], (qboolean)args[8] ); + return CGFX_PlayBoltedEffectID(args[1], (float *)VMA(2), (void *)args[3], args[4], args[5], args[6], args[7], (qboolean)args[8]); case CG_FX_ADD_SCHEDULED_EFFECTS: FX_AddScheduledEffects((qboolean)args[1]); return 0; case CG_FX_DRAW_2D_EFFECTS: - FX_Draw2DEffects ( VMF(1), VMF(2) ); + FX_Draw2DEffects(VMF(1), VMF(2)); return 0; case CG_FX_INIT_SYSTEM: - return FX_InitSystem( (refdef_t*)VMA(1) ); + return FX_InitSystem((refdef_t *)VMA(1)); case CG_FX_SET_REFDEF: - FX_SetRefDefFromCGame( (refdef_t*)VMA(1) ); + FX_SetRefDefFromCGame((refdef_t *)VMA(1)); return 0; case CG_FX_FREE_SYSTEM: @@ -1411,23 +1423,23 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_FX_RESET: - FX_Free ( false ); + FX_Free(false); return 0; case CG_FX_ADDPOLY: - CGFX_AddPoly( (addpolyArgStruct_t *)VMA(1) ); + CGFX_AddPoly((addpolyArgStruct_t *)VMA(1)); return 0; case CG_FX_ADDBEZIER: - CGFX_AddBezier( (addbezierArgStruct_t *)VMA(1) ); + CGFX_AddBezier((addbezierArgStruct_t *)VMA(1)); return 0; case CG_FX_ADDPRIMITIVE: - CGFX_AddPrimitive( (effectTrailArgStruct_t *)VMA(1) ); + CGFX_AddPrimitive((effectTrailArgStruct_t *)VMA(1)); return 0; case CG_FX_ADDSPRITE: - CGFX_AddSprite( (addspriteArgStruct_t *)VMA(1) ); + CGFX_AddSprite((addspriteArgStruct_t *)VMA(1)); return 0; case CG_FX_ADDELECTRICITY: - CGFX_AddElectricity( (addElectricityArgStruct_t *)VMA(1) ); + CGFX_AddElectricity((addElectricityArgStruct_t *)VMA(1)); return 0; #else case CG_FX_REGISTER_EFFECT: @@ -1457,13 +1469,13 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_ROFF_CACHE: - return CL_ROFF_Cache( (char *)VMA(1) ); + return CL_ROFF_Cache((char *)VMA(1)); case CG_ROFF_PLAY: - return CL_ROFF_Play( args[1], args[2], (qboolean)args[3] ); + return CL_ROFF_Play(args[1], args[2], (qboolean)args[3]); case CG_ROFF_PURGE_ENT: - return CL_ROFF_Purge_Ent( args[1] ); + return CL_ROFF_Purge_Ent(args[1]); case CG_TRUEMALLOC: VM_Shifted_Alloc((void **)VMA(1), args[2]); @@ -1474,121 +1486,128 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_G2_LISTSURFACES: - CL_G2API_ListModelSurfaces( VMA(1) ); + CL_G2API_ListModelSurfaces(VMA(1)); return 0; case CG_G2_LISTBONES: - CL_G2API_ListModelBones( VMA(1), args[2]); + CL_G2API_ListModelBones(VMA(1), args[2]); return 0; case CG_G2_HAVEWEGHOULMODELS: - return CL_G2API_HaveWeGhoul2Models( VMA(1) ); + return CL_G2API_HaveWeGhoul2Models(VMA(1)); case CG_G2_SETMODELS: - CL_G2API_SetGhoul2ModelIndexes( VMA(1), (qhandle_t *)VMA(2), (qhandle_t *)VMA(3) ); + CL_G2API_SetGhoul2ModelIndexes(VMA(1), (qhandle_t *)VMA(2), (qhandle_t *)VMA(3)); return 0; case CG_G2_GETBOLT: - return CL_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case CG_G2_GETBOLT_NOREC: - return CL_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case CG_G2_GETBOLT_NOREC_NOROT: - return CL_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case CG_G2_INITGHOUL2MODEL: - return CL_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t) args[4], (qhandle_t) args[5], args[6], args[7]); + return CL_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t)args[4], (qhandle_t)args[5], args[6], args[7]); case CG_G2_SETSKIN: - return CL_G2API_SetSkin( VMA(1), args[2], args[3], args[4] ); + return CL_G2API_SetSkin(VMA(1), args[2], args[3], args[4]); case CG_G2_COLLISIONDETECT: - CL_G2API_CollisionDetect ( (CollisionRecord_t*)VMA(1), VMA(2), (const float*)VMA(3), (const float*)VMA(4), args[5], args[6], (float*)VMA(7), (float*)VMA(8), (float*)VMA(9), args[10], args[11], VMF(12) ); + CL_G2API_CollisionDetect((CollisionRecord_t *)VMA(1), VMA(2), (const float *)VMA(3), (const float *)VMA(4), args[5], args[6], (float *)VMA(7), + (float *)VMA(8), (float *)VMA(9), args[10], args[11], VMF(12)); return 0; case CG_G2_COLLISIONDETECTCACHE: - CL_G2API_CollisionDetectCache ( (CollisionRecord_t*)VMA(1), VMA(2), (const float*)VMA(3), (const float*)VMA(4), args[5], args[6], (float*)VMA(7), (float*)VMA(8), (float*)VMA(9), args[10], args[11], VMF(12) ); + CL_G2API_CollisionDetectCache((CollisionRecord_t *)VMA(1), VMA(2), (const float *)VMA(3), (const float *)VMA(4), args[5], args[6], (float *)VMA(7), + (float *)VMA(8), (float *)VMA(9), args[10], args[11], VMF(12)); return 0; case CG_G2_ANGLEOVERRIDE: - return CL_G2API_SetBoneAngles( VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], args[6], args[7], args[8], (qhandle_t *)VMA(9), args[10], args[11] ); + return CL_G2API_SetBoneAngles(VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], args[6], args[7], args[8], (qhandle_t *)VMA(9), args[10], + args[11]); case CG_G2_CLEANMODELS: - CL_G2API_CleanGhoul2Models( (void **)VMA(1) ); + CL_G2API_CleanGhoul2Models((void **)VMA(1)); return 0; case CG_G2_PLAYANIM: - return CL_G2API_SetBoneAnim( VMA(1), args[2], (const char *)VMA(3), args[4], args[5], args[6], VMF(7), args[8], VMF(9), args[10] ); + return CL_G2API_SetBoneAnim(VMA(1), args[2], (const char *)VMA(3), args[4], args[5], args[6], VMF(7), args[8], VMF(9), args[10]); case CG_G2_GETBONEANIM: - return CL_G2API_GetBoneAnim( VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), (int *)VMA(9), args[10] ); + return CL_G2API_GetBoneAnim(VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), + (int *)VMA(9), args[10]); case CG_G2_GETBONEFRAME: - return CL_G2API_GetBoneFrame( VMA(1), (const char*)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), args[6] ); + return CL_G2API_GetBoneFrame(VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), args[6]); case CG_G2_GETGLANAME: - CL_G2API_GetGLAName( VMA(1), args[2], (char *)VMA(3) ); + CL_G2API_GetGLAName(VMA(1), args[2], (char *)VMA(3)); return 0; case CG_G2_COPYGHOUL2INSTANCE: - return CL_G2API_CopyGhoul2Instance( VMA(1), VMA(2), args[3] ); + return CL_G2API_CopyGhoul2Instance(VMA(1), VMA(2), args[3]); case CG_G2_COPYSPECIFICGHOUL2MODEL: - CL_G2API_CopySpecificGhoul2Model( VMA(1), args[2], VMA(3), args[4] ); + CL_G2API_CopySpecificGhoul2Model(VMA(1), args[2], VMA(3), args[4]); return 0; case CG_G2_DUPLICATEGHOUL2INSTANCE: - CL_G2API_DuplicateGhoul2Instance( VMA(1), (void **)VMA(2) ); + CL_G2API_DuplicateGhoul2Instance(VMA(1), (void **)VMA(2)); return 0; case CG_G2_HASGHOUL2MODELONINDEX: - return CL_G2API_HasGhoul2ModelOnIndex( VMA(1), args[2]); + return CL_G2API_HasGhoul2ModelOnIndex(VMA(1), args[2]); case CG_G2_REMOVEGHOUL2MODEL: - return CL_G2API_RemoveGhoul2Model( VMA(1), args[2]); + return CL_G2API_RemoveGhoul2Model(VMA(1), args[2]); case CG_G2_SKINLESSMODEL: - return CL_G2API_SkinlessModel( VMA(1), args[2] ); + return CL_G2API_SkinlessModel(VMA(1), args[2]); case CG_G2_GETNUMGOREMARKS: - return CL_G2API_GetNumGoreMarks( VMA(1), args[2] ); + return CL_G2API_GetNumGoreMarks(VMA(1), args[2]); case CG_G2_ADDSKINGORE: - CL_G2API_AddSkinGore( VMA(1), (SSkinGoreData *)VMA(2)); + CL_G2API_AddSkinGore(VMA(1), (SSkinGoreData *)VMA(2)); return 0; case CG_G2_CLEARSKINGORE: - CL_G2API_ClearSkinGore ( VMA(1) ); + CL_G2API_ClearSkinGore(VMA(1)); return 0; case CG_G2_SIZE: - return CL_G2API_Ghoul2Size ( VMA(1) ); + return CL_G2API_Ghoul2Size(VMA(1)); case CG_G2_ADDBOLT: - return CL_G2API_AddBolt( VMA(1), args[2], (const char *)VMA(3)); + return CL_G2API_AddBolt(VMA(1), args[2], (const char *)VMA(3)); case CG_G2_ATTACHENT: - return CL_G2API_AttachEnt( (int*)VMA(1), VMA(2), args[3], args[4], args[5] ); + return CL_G2API_AttachEnt((int *)VMA(1), VMA(2), args[3], args[4], args[5]); case CG_G2_SETBOLTON: - CL_G2API_SetBoltInfo( VMA(1), args[2], args[3] ); + CL_G2API_SetBoltInfo(VMA(1), args[2], args[3]); return 0; case CG_G2_SETROOTSURFACE: - return CL_G2API_SetRootSurface( VMA(1), args[2], (const char *)VMA(3)); + return CL_G2API_SetRootSurface(VMA(1), args[2], (const char *)VMA(3)); case CG_G2_SETSURFACEONOFF: - return CL_G2API_SetSurfaceOnOff( VMA(1), (const char *)VMA(2), args[3]); + return CL_G2API_SetSurfaceOnOff(VMA(1), (const char *)VMA(2), args[3]); case CG_G2_SETNEWORIGIN: - return CL_G2API_SetNewOrigin( VMA(1), args[2]); + return CL_G2API_SetNewOrigin(VMA(1), args[2]); case CG_G2_DOESBONEEXIST: - return CL_G2API_DoesBoneExist( VMA(1), args[2], (const char *)VMA(3)); + return CL_G2API_DoesBoneExist(VMA(1), args[2], (const char *)VMA(3)); case CG_G2_GETSURFACERENDERSTATUS: - return CL_G2API_GetSurfaceRenderStatus( VMA(1), args[2], (const char *)VMA(3)); + return CL_G2API_GetSurfaceRenderStatus(VMA(1), args[2], (const char *)VMA(3)); case CG_G2_GETTIME: return CL_G2API_GetTime(); @@ -1598,48 +1617,47 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_G2_ABSURDSMOOTHING: - CL_G2API_AbsurdSmoothing( VMA(1), (qboolean)args[2]); + CL_G2API_AbsurdSmoothing(VMA(1), (qboolean)args[2]); return 0; - case CG_G2_SETRAGDOLL: - CL_G2API_SetRagDoll( VMA(1), (sharedRagDollParams_t *)VMA(2) ); + CL_G2API_SetRagDoll(VMA(1), (sharedRagDollParams_t *)VMA(2)); return 0; case CG_G2_ANIMATEG2MODELS: - CL_G2API_AnimateG2Models( VMA(1), args[2], (sharedRagDollUpdateParams_t *)VMA(3) ); + CL_G2API_AnimateG2Models(VMA(1), args[2], (sharedRagDollUpdateParams_t *)VMA(3)); return 0; - //additional ragdoll options -rww + // additional ragdoll options -rww case CG_G2_RAGPCJCONSTRAINT: - return CL_G2API_RagPCJConstraint( VMA(1), (const char *)VMA(2), (float *)VMA(3), (float *)VMA(4)); + return CL_G2API_RagPCJConstraint(VMA(1), (const char *)VMA(2), (float *)VMA(3), (float *)VMA(4)); case CG_G2_RAGPCJGRADIENTSPEED: - return CL_G2API_RagPCJGradientSpeed( VMA(1), (const char *)VMA(2), VMF(3)); + return CL_G2API_RagPCJGradientSpeed(VMA(1), (const char *)VMA(2), VMF(3)); case CG_G2_RAGEFFECTORGOAL: - return CL_G2API_RagEffectorGoal( VMA(1), (const char *)VMA(2), (float *)VMA(3)); + return CL_G2API_RagEffectorGoal(VMA(1), (const char *)VMA(2), (float *)VMA(3)); case CG_G2_GETRAGBONEPOS: - return CL_G2API_GetRagBonePos( VMA(1), (const char *)VMA(2), (float *)VMA(3), (float *)VMA(4), (float *)VMA(5), (float *)VMA(6)); + return CL_G2API_GetRagBonePos(VMA(1), (const char *)VMA(2), (float *)VMA(3), (float *)VMA(4), (float *)VMA(5), (float *)VMA(6)); case CG_G2_RAGEFFECTORKICK: - return CL_G2API_RagEffectorKick( VMA(1), (const char *)VMA(2), (float *)VMA(3)); + return CL_G2API_RagEffectorKick(VMA(1), (const char *)VMA(2), (float *)VMA(3)); case CG_G2_RAGFORCESOLVE: - return CL_G2API_RagForceSolve( VMA(1), (qboolean)args[2]); + return CL_G2API_RagForceSolve(VMA(1), (qboolean)args[2]); case CG_G2_SETBONEIKSTATE: - return CL_G2API_SetBoneIKState( VMA(1), args[2], (const char *)VMA(3), args[4], (sharedSetBoneIKStateParams_t *)VMA(5)); + return CL_G2API_SetBoneIKState(VMA(1), args[2], (const char *)VMA(3), args[4], (sharedSetBoneIKStateParams_t *)VMA(5)); case CG_G2_IKMOVE: - return CL_G2API_IKMove( VMA(1), args[2], (sharedIKMoveParams_t *)VMA(3)); + return CL_G2API_IKMove(VMA(1), args[2], (sharedIKMoveParams_t *)VMA(3)); case CG_G2_REMOVEBONE: - return CL_G2API_RemoveBone( VMA(1), (const char *)VMA(2), args[3] ); + return CL_G2API_RemoveBone(VMA(1), (const char *)VMA(2), args[3]); case CG_G2_ATTACHINSTANCETOENTNUM: - CL_G2API_AttachInstanceToEntNum( VMA(1), args[2], (qboolean)args[3]); + CL_G2API_AttachInstanceToEntNum(VMA(1), args[2], (qboolean)args[3]); return 0; case CG_G2_CLEARATTACHEDINSTANCE: @@ -1651,17 +1669,17 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_G2_OVERRIDESERVER: - return CL_G2API_OverrideServer( VMA(1) ); + return CL_G2API_OverrideServer(VMA(1)); case CG_G2_GETSURFACENAME: - CL_G2API_GetSurfaceName( VMA(1), args[2], args[3], (char *)VMA(4) ); + CL_G2API_GetSurfaceName(VMA(1), args[2], args[3], (char *)VMA(4)); return 0; case CG_SP_GETSTRINGTEXTSTRING: - return CL_SE_GetStringTextString( (const char *)VMA(1), (char *)VMA(2), args[3] ); + return CL_SE_GetStringTextString((const char *)VMA(1), (char *)VMA(2), args[3]); case CG_SET_SHARED_BUFFER: - RegisterSharedMemory( (char *)VMA(1) ); + RegisterSharedMemory((char *)VMA(1)); return 0; case CG_CM_REGISTER_TERRAIN: @@ -1674,7 +1692,7 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_R_WEATHER_CONTENTS_OVERRIDE: - //contentOverride = args[1]; + // contentOverride = args[1]; return 0; case CG_R_WORLDEFFECTCOMMAND: @@ -1682,242 +1700,242 @@ intptr_t CL_CgameSystemCalls( intptr_t *args ) { return 0; case CG_WE_ADDWEATHERZONE: - re->AddWeatherZone( (float *)VMA(1), (float *)VMA(2) ); + re->AddWeatherZone((float *)VMA(1), (float *)VMA(2)); return 0; default: assert(0); // bk010102 - Com_Error( ERR_DROP, "Bad cgame system trap: %ld", (long int) args[0] ); + Com_Error(ERR_DROP, "Bad cgame system trap: %ld", (long int)args[0]); } return 0; } // Stub function for old RMG system. -static void RE_InitRendererTerrain ( const char * /*info*/ ) {} +static void RE_InitRendererTerrain(const char * /*info*/) {} -void CL_BindCGame( void ) { +void CL_BindCGame(void) { static cgameImport_t cgi; - cgameExport_t *ret; - GetCGameAPI_t GetCGameAPI; - char dllName[MAX_OSPATH] = "cgame" ARCH_STRING DLL_EXT; - - memset( &cgi, 0, sizeof( cgi ) ); - - cgvm = VM_Create( VM_CGAME ); - if ( cgvm && !cgvm->isLegacy ) { - cgi.Print = Com_Printf; - cgi.Error = Com_Error; - cgi.SnapVector = Sys_SnapVector; - cgi.MemoryRemaining = Hunk_MemoryRemaining; - cgi.RegisterSharedMemory = RegisterSharedMemory; - cgi.TrueMalloc = VM_Shifted_Alloc; - cgi.TrueFree = VM_Shifted_Free; - cgi.Milliseconds = CL_Milliseconds; - cgi.RealTime = Com_RealTime; - cgi.PrecisionTimerStart = CL_PrecisionTimerStart; - cgi.PrecisionTimerEnd = CL_PrecisionTimerEnd; - cgi.Cvar_Register = Cvar_Register; - cgi.Cvar_Set = CGVM_Cvar_Set; - cgi.Cvar_Update = Cvar_Update; - cgi.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; - cgi.AddCommand = CL_AddCgameCommand; - cgi.Cmd_Argc = Cmd_Argc; - cgi.Cmd_Args = Cmd_ArgsBuffer; - cgi.Cmd_Argv = Cmd_ArgvBuffer; - cgi.RemoveCommand = CGVM_Cmd_RemoveCommand; - cgi.SendClientCommand = CL_AddReliableCommand2; - cgi.SendConsoleCommand = Cbuf_AddText; - cgi.FS_Close = FS_FCloseFile; - cgi.FS_GetFileList = FS_GetFileList; - cgi.FS_Open = FS_FOpenFileByMode; - cgi.FS_Read = FS_Read; - cgi.FS_Write = FS_Write; - cgi.UpdateScreen = SCR_UpdateScreen; - cgi.CM_InlineModel = CM_InlineModel; - cgi.CM_LoadMap = CL_CM_LoadMap; - cgi.CM_NumInlineModels = CM_NumInlineModels; - cgi.CM_PointContents = CM_PointContents; - cgi.CM_RegisterTerrain = CL_CM_RegisterTerrain; - cgi.CM_TempModel = CM_TempBoxModel; - cgi.CM_Trace = CM_BoxTrace; - cgi.CM_TransformedPointContents = CM_TransformedPointContents; - cgi.CM_TransformedTrace = CM_TransformedBoxTrace; - cgi.RMG_Init = CL_RMG_Init; - cgi.S_AddLocalSet = S_AddLocalSet; - cgi.S_AddLoopingSound = S_AddLoopingSound; - cgi.S_ClearLoopingSounds = S_ClearLoopingSounds; - cgi.S_GetVoiceVolume = CL_S_GetVoiceVolume; - cgi.S_MuteSound = S_MuteSound; - cgi.S_RegisterSound = S_RegisterSound; - cgi.S_Respatialize = S_Respatialize; - cgi.S_Shutup = CL_S_Shutup; - cgi.S_StartBackgroundTrack = S_StartBackgroundTrack; - cgi.S_StartLocalSound = S_StartLocalSound; - cgi.S_StartSound = S_StartSound; - cgi.S_StopBackgroundTrack = S_StopBackgroundTrack; - cgi.S_StopLoopingSound = S_StopLoopingSound; - cgi.S_UpdateEntityPosition = S_UpdateEntityPosition; - cgi.S_UpdateAmbientSet = S_UpdateAmbientSet; - cgi.AS_AddPrecacheEntry = AS_AddPrecacheEntry; - cgi.AS_GetBModelSound = AS_GetBModelSound; - cgi.AS_ParseSets = AS_ParseSets; - cgi.R_AddAdditiveLightToScene = re->AddAdditiveLightToScene; - cgi.R_AddDecalToScene = re->AddDecalToScene; - cgi.R_AddLightToScene = re->AddLightToScene; - cgi.R_AddPolysToScene = re->AddPolyToScene; - cgi.R_AddRefEntityToScene = re->AddRefEntityToScene; - cgi.R_AnyLanguage_ReadCharFromString = re->AnyLanguage_ReadCharFromString; - cgi.R_AutomapElevationAdjustment = re->AutomapElevationAdjustment; - cgi.R_ClearDecals = re->ClearDecals; - cgi.R_ClearScene = re->ClearScene; - cgi.R_DrawStretchPic = re->DrawStretchPic; - cgi.R_DrawRotatePic = re->DrawRotatePic; - cgi.R_DrawRotatePic2 = re->DrawRotatePic2; - cgi.R_Font_DrawString = re->Font_DrawString; - cgi.R_Font_HeightPixels = re->Font_HeightPixels; - cgi.R_Font_StrLenChars = re->Font_StrLenChars; - cgi.R_Font_StrLenPixels = re->Font_StrLenPixels; - cgi.R_GetBModelVerts = re->GetBModelVerts; - cgi.R_GetDistanceCull = re->GetDistanceCull; - cgi.R_GetEntityToken = re->GetEntityToken; - cgi.R_GetLightStyle = re->GetLightStyle; - cgi.R_GetRealRes = re->GetRealRes; - cgi.R_InitializeWireframeAutomap = re->InitializeWireframeAutomap; - cgi.R_InPVS = re->inPVS; - cgi.R_Language_IsAsian = re->Language_IsAsian; - cgi.R_Language_UsesSpaces = re->Language_UsesSpaces; - cgi.R_LerpTag = re->LerpTag; - cgi.R_LightForPoint = re->LightForPoint; - cgi.R_LoadWorld = re->LoadWorld; - cgi.R_MarkFragments = re->MarkFragments; - cgi.R_ModelBounds = re->ModelBounds; - cgi.R_RegisterFont = re->RegisterFont; - cgi.R_RegisterModel = re->RegisterModel; - cgi.R_RegisterShader = re->RegisterShader; - cgi.R_RegisterShaderNoMip = re->RegisterShaderNoMip; - cgi.R_RegisterSkin = re->RegisterSkin; - cgi.R_RemapShader = re->RemapShader; - cgi.R_RenderScene = re->RenderScene; - cgi.R_SetColor = re->SetColor; - cgi.R_SetLightStyle = re->SetLightStyle; - cgi.R_SetRangedFog = re->SetRangedFog; - cgi.R_SetRefractionProperties = re->SetRefractionProperties; - cgi.R_WorldEffectCommand = re->WorldEffectCommand; - cgi.RE_InitRendererTerrain = RE_InitRendererTerrain; - cgi.WE_AddWeatherZone = re->AddWeatherZone; - cgi.GetCurrentSnapshotNumber = CL_GetCurrentSnapshotNumber; - cgi.GetCurrentCmdNumber = CL_GetCurrentCmdNumber; - cgi.GetDefaultState = CL_GetDefaultState; - cgi.GetGameState = CL_GetGameState; - cgi.GetGlconfig = CL_GetGlconfig; - cgi.GetServerCommand = CL_GetServerCommand; - cgi.GetSnapshot = CL_GetSnapshot; - cgi.GetUserCmd = CL_GetUserCmd; - cgi.OpenUIMenu = CL_OpenUIMenu; - cgi.SetClientForceAngle = CL_SetClientForceAngle; - cgi.SetUserCmdValue = _CL_SetUserCmdValue; - cgi.Key_GetCatcher = Key_GetCatcher; - cgi.Key_GetKey = Key_GetKey; - cgi.Key_IsDown = Key_IsDown; - cgi.Key_SetCatcher = CL_Key_SetCatcher; - cgi.PC_AddGlobalDefine = botlib_export->PC_AddGlobalDefine; - cgi.PC_FreeSource = botlib_export->PC_FreeSourceHandle; - cgi.PC_LoadGlobalDefines = botlib_export->PC_LoadGlobalDefines; - cgi.PC_LoadSource = botlib_export->PC_LoadSourceHandle; - cgi.PC_ReadToken = botlib_export->PC_ReadTokenHandle; - cgi.PC_RemoveAllGlobalDefines = botlib_export->PC_RemoveAllGlobalDefines; - cgi.PC_SourceFileAndLine = botlib_export->PC_SourceFileAndLine; - cgi.CIN_DrawCinematic = CIN_DrawCinematic; - cgi.CIN_PlayCinematic = CIN_PlayCinematic; - cgi.CIN_RunCinematic = CIN_RunCinematic; - cgi.CIN_SetExtents = CIN_SetExtents; - cgi.CIN_StopCinematic = CIN_StopCinematic; - cgi.FX_AddLine = CGFX_AddLine; - cgi.FX_RegisterEffect = FX_RegisterEffect; - cgi.FX_PlayEffect = FX_PlayEffect; - cgi.FX_PlayEffectID = FX_PlayEffectID; - cgi.FX_PlayEntityEffectID = FX_PlayEntityEffectID; - cgi.FX_PlayBoltedEffectID = CGFX_PlayBoltedEffectID; - cgi.FX_AddScheduledEffects = FX_AddScheduledEffects; - cgi.FX_InitSystem = FX_InitSystem; - cgi.FX_SetRefDef = FX_SetRefDef; - cgi.FX_FreeSystem = FX_FreeSystem; - cgi.FX_AdjustTime = FX_AdjustTime; - cgi.FX_Draw2DEffects = FX_Draw2DEffects; - cgi.FX_AddPoly = CGFX_AddPoly; - cgi.FX_AddBezier = CGFX_AddBezier; - cgi.FX_AddPrimitive = CGFX_AddPrimitive; - cgi.FX_AddSprite = CGFX_AddSprite; - cgi.FX_AddElectricity = CGFX_AddElectricity; - cgi.SE_GetStringTextString = CL_SE_GetStringTextString; - cgi.ROFF_Clean = CL_ROFF_Clean; - cgi.ROFF_UpdateEntities = CL_ROFF_UpdateEntities; - cgi.ROFF_Cache = CL_ROFF_Cache; - cgi.ROFF_Play = CL_ROFF_Play; - cgi.ROFF_Purge_Ent = CL_ROFF_Purge_Ent; - cgi.G2_ListModelSurfaces = CL_G2API_ListModelSurfaces; - cgi.G2_ListModelBones = CL_G2API_ListModelBones; - cgi.G2_SetGhoul2ModelIndexes = CL_G2API_SetGhoul2ModelIndexes; - cgi.G2_HaveWeGhoul2Models = CL_G2API_HaveWeGhoul2Models; - cgi.G2API_GetBoltMatrix = CL_G2API_GetBoltMatrix; - cgi.G2API_GetBoltMatrix_NoReconstruct = CL_G2API_GetBoltMatrix_NoReconstruct; - cgi.G2API_GetBoltMatrix_NoRecNoRot = CL_G2API_GetBoltMatrix_NoRecNoRot; - cgi.G2API_InitGhoul2Model = CL_G2API_InitGhoul2Model; - cgi.G2API_SetSkin = CL_G2API_SetSkin; - cgi.G2API_CollisionDetect = CL_G2API_CollisionDetect; - cgi.G2API_CollisionDetectCache = CL_G2API_CollisionDetectCache; - cgi.G2API_CleanGhoul2Models = CL_G2API_CleanGhoul2Models; - cgi.G2API_SetBoneAngles = CL_G2API_SetBoneAngles; - cgi.G2API_SetBoneAnim = CL_G2API_SetBoneAnim; - cgi.G2API_GetBoneAnim = CL_G2API_GetBoneAnim; - cgi.G2API_GetBoneFrame = CL_G2API_GetBoneFrame; - cgi.G2API_GetGLAName = CL_G2API_GetGLAName; - cgi.G2API_CopyGhoul2Instance = CL_G2API_CopyGhoul2Instance; - cgi.G2API_CopySpecificGhoul2Model = CL_G2API_CopySpecificGhoul2Model; - cgi.G2API_DuplicateGhoul2Instance = CL_G2API_DuplicateGhoul2Instance; - cgi.G2API_HasGhoul2ModelOnIndex = CL_G2API_HasGhoul2ModelOnIndex; - cgi.G2API_RemoveGhoul2Model = CL_G2API_RemoveGhoul2Model; - cgi.G2API_SkinlessModel = CL_G2API_SkinlessModel; - cgi.G2API_GetNumGoreMarks = CL_G2API_GetNumGoreMarks; - cgi.G2API_AddSkinGore = CL_G2API_AddSkinGore; - cgi.G2API_ClearSkinGore = CL_G2API_ClearSkinGore; - cgi.G2API_Ghoul2Size = CL_G2API_Ghoul2Size; - cgi.G2API_AddBolt = CL_G2API_AddBolt; - cgi.G2API_AttachEnt = CL_G2API_AttachEnt; - cgi.G2API_SetBoltInfo = CL_G2API_SetBoltInfo; - cgi.G2API_SetRootSurface = CL_G2API_SetRootSurface; - cgi.G2API_SetSurfaceOnOff = CL_G2API_SetSurfaceOnOff; - cgi.G2API_SetNewOrigin = CL_G2API_SetNewOrigin; - cgi.G2API_DoesBoneExist = CL_G2API_DoesBoneExist; - cgi.G2API_GetSurfaceRenderStatus = CL_G2API_GetSurfaceRenderStatus; - cgi.G2API_GetTime = CL_G2API_GetTime; - cgi.G2API_SetTime = CL_G2API_SetTime; - cgi.G2API_AbsurdSmoothing = CL_G2API_AbsurdSmoothing; - cgi.G2API_SetRagDoll = CL_G2API_SetRagDoll; - cgi.G2API_AnimateG2Models = CL_G2API_AnimateG2Models; - cgi.G2API_RagPCJConstraint = CL_G2API_RagPCJConstraint; - cgi.G2API_RagPCJGradientSpeed = CL_G2API_RagPCJGradientSpeed; - cgi.G2API_RagEffectorGoal = CL_G2API_RagEffectorGoal; - cgi.G2API_GetRagBonePos = CL_G2API_GetRagBonePos; - cgi.G2API_RagEffectorKick = CL_G2API_RagEffectorKick; - cgi.G2API_RagForceSolve = CL_G2API_RagForceSolve; - cgi.G2API_SetBoneIKState = CL_G2API_SetBoneIKState; - cgi.G2API_IKMove = CL_G2API_IKMove; - cgi.G2API_RemoveBone = CL_G2API_RemoveBone; - cgi.G2API_AttachInstanceToEntNum = CL_G2API_AttachInstanceToEntNum; - cgi.G2API_ClearAttachedInstance = CL_G2API_ClearAttachedInstance; - cgi.G2API_CleanEntAttachments = CL_G2API_CleanEntAttachments; - cgi.G2API_OverrideServer = CL_G2API_OverrideServer; - cgi.G2API_GetSurfaceName = CL_G2API_GetSurfaceName; - - cgi.ext.R_Font_StrLenPixels = re->ext.Font_StrLenPixels; + cgameExport_t *ret; + GetCGameAPI_t GetCGameAPI; + char dllName[MAX_OSPATH] = "cgame" ARCH_STRING DLL_EXT; + + memset(&cgi, 0, sizeof(cgi)); + + cgvm = VM_Create(VM_CGAME); + if (cgvm && !cgvm->isLegacy) { + cgi.Print = Com_Printf; + cgi.Error = Com_Error; + cgi.SnapVector = Sys_SnapVector; + cgi.MemoryRemaining = Hunk_MemoryRemaining; + cgi.RegisterSharedMemory = RegisterSharedMemory; + cgi.TrueMalloc = VM_Shifted_Alloc; + cgi.TrueFree = VM_Shifted_Free; + cgi.Milliseconds = CL_Milliseconds; + cgi.RealTime = Com_RealTime; + cgi.PrecisionTimerStart = CL_PrecisionTimerStart; + cgi.PrecisionTimerEnd = CL_PrecisionTimerEnd; + cgi.Cvar_Register = Cvar_Register; + cgi.Cvar_Set = CGVM_Cvar_Set; + cgi.Cvar_Update = Cvar_Update; + cgi.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; + cgi.AddCommand = CL_AddCgameCommand; + cgi.Cmd_Argc = Cmd_Argc; + cgi.Cmd_Args = Cmd_ArgsBuffer; + cgi.Cmd_Argv = Cmd_ArgvBuffer; + cgi.RemoveCommand = CGVM_Cmd_RemoveCommand; + cgi.SendClientCommand = CL_AddReliableCommand2; + cgi.SendConsoleCommand = Cbuf_AddText; + cgi.FS_Close = FS_FCloseFile; + cgi.FS_GetFileList = FS_GetFileList; + cgi.FS_Open = FS_FOpenFileByMode; + cgi.FS_Read = FS_Read; + cgi.FS_Write = FS_Write; + cgi.UpdateScreen = SCR_UpdateScreen; + cgi.CM_InlineModel = CM_InlineModel; + cgi.CM_LoadMap = CL_CM_LoadMap; + cgi.CM_NumInlineModels = CM_NumInlineModels; + cgi.CM_PointContents = CM_PointContents; + cgi.CM_RegisterTerrain = CL_CM_RegisterTerrain; + cgi.CM_TempModel = CM_TempBoxModel; + cgi.CM_Trace = CM_BoxTrace; + cgi.CM_TransformedPointContents = CM_TransformedPointContents; + cgi.CM_TransformedTrace = CM_TransformedBoxTrace; + cgi.RMG_Init = CL_RMG_Init; + cgi.S_AddLocalSet = S_AddLocalSet; + cgi.S_AddLoopingSound = S_AddLoopingSound; + cgi.S_ClearLoopingSounds = S_ClearLoopingSounds; + cgi.S_GetVoiceVolume = CL_S_GetVoiceVolume; + cgi.S_MuteSound = S_MuteSound; + cgi.S_RegisterSound = S_RegisterSound; + cgi.S_Respatialize = S_Respatialize; + cgi.S_Shutup = CL_S_Shutup; + cgi.S_StartBackgroundTrack = S_StartBackgroundTrack; + cgi.S_StartLocalSound = S_StartLocalSound; + cgi.S_StartSound = S_StartSound; + cgi.S_StopBackgroundTrack = S_StopBackgroundTrack; + cgi.S_StopLoopingSound = S_StopLoopingSound; + cgi.S_UpdateEntityPosition = S_UpdateEntityPosition; + cgi.S_UpdateAmbientSet = S_UpdateAmbientSet; + cgi.AS_AddPrecacheEntry = AS_AddPrecacheEntry; + cgi.AS_GetBModelSound = AS_GetBModelSound; + cgi.AS_ParseSets = AS_ParseSets; + cgi.R_AddAdditiveLightToScene = re->AddAdditiveLightToScene; + cgi.R_AddDecalToScene = re->AddDecalToScene; + cgi.R_AddLightToScene = re->AddLightToScene; + cgi.R_AddPolysToScene = re->AddPolyToScene; + cgi.R_AddRefEntityToScene = re->AddRefEntityToScene; + cgi.R_AnyLanguage_ReadCharFromString = re->AnyLanguage_ReadCharFromString; + cgi.R_AutomapElevationAdjustment = re->AutomapElevationAdjustment; + cgi.R_ClearDecals = re->ClearDecals; + cgi.R_ClearScene = re->ClearScene; + cgi.R_DrawStretchPic = re->DrawStretchPic; + cgi.R_DrawRotatePic = re->DrawRotatePic; + cgi.R_DrawRotatePic2 = re->DrawRotatePic2; + cgi.R_Font_DrawString = re->Font_DrawString; + cgi.R_Font_HeightPixels = re->Font_HeightPixels; + cgi.R_Font_StrLenChars = re->Font_StrLenChars; + cgi.R_Font_StrLenPixels = re->Font_StrLenPixels; + cgi.R_GetBModelVerts = re->GetBModelVerts; + cgi.R_GetDistanceCull = re->GetDistanceCull; + cgi.R_GetEntityToken = re->GetEntityToken; + cgi.R_GetLightStyle = re->GetLightStyle; + cgi.R_GetRealRes = re->GetRealRes; + cgi.R_InitializeWireframeAutomap = re->InitializeWireframeAutomap; + cgi.R_InPVS = re->inPVS; + cgi.R_Language_IsAsian = re->Language_IsAsian; + cgi.R_Language_UsesSpaces = re->Language_UsesSpaces; + cgi.R_LerpTag = re->LerpTag; + cgi.R_LightForPoint = re->LightForPoint; + cgi.R_LoadWorld = re->LoadWorld; + cgi.R_MarkFragments = re->MarkFragments; + cgi.R_ModelBounds = re->ModelBounds; + cgi.R_RegisterFont = re->RegisterFont; + cgi.R_RegisterModel = re->RegisterModel; + cgi.R_RegisterShader = re->RegisterShader; + cgi.R_RegisterShaderNoMip = re->RegisterShaderNoMip; + cgi.R_RegisterSkin = re->RegisterSkin; + cgi.R_RemapShader = re->RemapShader; + cgi.R_RenderScene = re->RenderScene; + cgi.R_SetColor = re->SetColor; + cgi.R_SetLightStyle = re->SetLightStyle; + cgi.R_SetRangedFog = re->SetRangedFog; + cgi.R_SetRefractionProperties = re->SetRefractionProperties; + cgi.R_WorldEffectCommand = re->WorldEffectCommand; + cgi.RE_InitRendererTerrain = RE_InitRendererTerrain; + cgi.WE_AddWeatherZone = re->AddWeatherZone; + cgi.GetCurrentSnapshotNumber = CL_GetCurrentSnapshotNumber; + cgi.GetCurrentCmdNumber = CL_GetCurrentCmdNumber; + cgi.GetDefaultState = CL_GetDefaultState; + cgi.GetGameState = CL_GetGameState; + cgi.GetGlconfig = CL_GetGlconfig; + cgi.GetServerCommand = CL_GetServerCommand; + cgi.GetSnapshot = CL_GetSnapshot; + cgi.GetUserCmd = CL_GetUserCmd; + cgi.OpenUIMenu = CL_OpenUIMenu; + cgi.SetClientForceAngle = CL_SetClientForceAngle; + cgi.SetUserCmdValue = _CL_SetUserCmdValue; + cgi.Key_GetCatcher = Key_GetCatcher; + cgi.Key_GetKey = Key_GetKey; + cgi.Key_IsDown = Key_IsDown; + cgi.Key_SetCatcher = CL_Key_SetCatcher; + cgi.PC_AddGlobalDefine = botlib_export->PC_AddGlobalDefine; + cgi.PC_FreeSource = botlib_export->PC_FreeSourceHandle; + cgi.PC_LoadGlobalDefines = botlib_export->PC_LoadGlobalDefines; + cgi.PC_LoadSource = botlib_export->PC_LoadSourceHandle; + cgi.PC_ReadToken = botlib_export->PC_ReadTokenHandle; + cgi.PC_RemoveAllGlobalDefines = botlib_export->PC_RemoveAllGlobalDefines; + cgi.PC_SourceFileAndLine = botlib_export->PC_SourceFileAndLine; + cgi.CIN_DrawCinematic = CIN_DrawCinematic; + cgi.CIN_PlayCinematic = CIN_PlayCinematic; + cgi.CIN_RunCinematic = CIN_RunCinematic; + cgi.CIN_SetExtents = CIN_SetExtents; + cgi.CIN_StopCinematic = CIN_StopCinematic; + cgi.FX_AddLine = CGFX_AddLine; + cgi.FX_RegisterEffect = FX_RegisterEffect; + cgi.FX_PlayEffect = FX_PlayEffect; + cgi.FX_PlayEffectID = FX_PlayEffectID; + cgi.FX_PlayEntityEffectID = FX_PlayEntityEffectID; + cgi.FX_PlayBoltedEffectID = CGFX_PlayBoltedEffectID; + cgi.FX_AddScheduledEffects = FX_AddScheduledEffects; + cgi.FX_InitSystem = FX_InitSystem; + cgi.FX_SetRefDef = FX_SetRefDef; + cgi.FX_FreeSystem = FX_FreeSystem; + cgi.FX_AdjustTime = FX_AdjustTime; + cgi.FX_Draw2DEffects = FX_Draw2DEffects; + cgi.FX_AddPoly = CGFX_AddPoly; + cgi.FX_AddBezier = CGFX_AddBezier; + cgi.FX_AddPrimitive = CGFX_AddPrimitive; + cgi.FX_AddSprite = CGFX_AddSprite; + cgi.FX_AddElectricity = CGFX_AddElectricity; + cgi.SE_GetStringTextString = CL_SE_GetStringTextString; + cgi.ROFF_Clean = CL_ROFF_Clean; + cgi.ROFF_UpdateEntities = CL_ROFF_UpdateEntities; + cgi.ROFF_Cache = CL_ROFF_Cache; + cgi.ROFF_Play = CL_ROFF_Play; + cgi.ROFF_Purge_Ent = CL_ROFF_Purge_Ent; + cgi.G2_ListModelSurfaces = CL_G2API_ListModelSurfaces; + cgi.G2_ListModelBones = CL_G2API_ListModelBones; + cgi.G2_SetGhoul2ModelIndexes = CL_G2API_SetGhoul2ModelIndexes; + cgi.G2_HaveWeGhoul2Models = CL_G2API_HaveWeGhoul2Models; + cgi.G2API_GetBoltMatrix = CL_G2API_GetBoltMatrix; + cgi.G2API_GetBoltMatrix_NoReconstruct = CL_G2API_GetBoltMatrix_NoReconstruct; + cgi.G2API_GetBoltMatrix_NoRecNoRot = CL_G2API_GetBoltMatrix_NoRecNoRot; + cgi.G2API_InitGhoul2Model = CL_G2API_InitGhoul2Model; + cgi.G2API_SetSkin = CL_G2API_SetSkin; + cgi.G2API_CollisionDetect = CL_G2API_CollisionDetect; + cgi.G2API_CollisionDetectCache = CL_G2API_CollisionDetectCache; + cgi.G2API_CleanGhoul2Models = CL_G2API_CleanGhoul2Models; + cgi.G2API_SetBoneAngles = CL_G2API_SetBoneAngles; + cgi.G2API_SetBoneAnim = CL_G2API_SetBoneAnim; + cgi.G2API_GetBoneAnim = CL_G2API_GetBoneAnim; + cgi.G2API_GetBoneFrame = CL_G2API_GetBoneFrame; + cgi.G2API_GetGLAName = CL_G2API_GetGLAName; + cgi.G2API_CopyGhoul2Instance = CL_G2API_CopyGhoul2Instance; + cgi.G2API_CopySpecificGhoul2Model = CL_G2API_CopySpecificGhoul2Model; + cgi.G2API_DuplicateGhoul2Instance = CL_G2API_DuplicateGhoul2Instance; + cgi.G2API_HasGhoul2ModelOnIndex = CL_G2API_HasGhoul2ModelOnIndex; + cgi.G2API_RemoveGhoul2Model = CL_G2API_RemoveGhoul2Model; + cgi.G2API_SkinlessModel = CL_G2API_SkinlessModel; + cgi.G2API_GetNumGoreMarks = CL_G2API_GetNumGoreMarks; + cgi.G2API_AddSkinGore = CL_G2API_AddSkinGore; + cgi.G2API_ClearSkinGore = CL_G2API_ClearSkinGore; + cgi.G2API_Ghoul2Size = CL_G2API_Ghoul2Size; + cgi.G2API_AddBolt = CL_G2API_AddBolt; + cgi.G2API_AttachEnt = CL_G2API_AttachEnt; + cgi.G2API_SetBoltInfo = CL_G2API_SetBoltInfo; + cgi.G2API_SetRootSurface = CL_G2API_SetRootSurface; + cgi.G2API_SetSurfaceOnOff = CL_G2API_SetSurfaceOnOff; + cgi.G2API_SetNewOrigin = CL_G2API_SetNewOrigin; + cgi.G2API_DoesBoneExist = CL_G2API_DoesBoneExist; + cgi.G2API_GetSurfaceRenderStatus = CL_G2API_GetSurfaceRenderStatus; + cgi.G2API_GetTime = CL_G2API_GetTime; + cgi.G2API_SetTime = CL_G2API_SetTime; + cgi.G2API_AbsurdSmoothing = CL_G2API_AbsurdSmoothing; + cgi.G2API_SetRagDoll = CL_G2API_SetRagDoll; + cgi.G2API_AnimateG2Models = CL_G2API_AnimateG2Models; + cgi.G2API_RagPCJConstraint = CL_G2API_RagPCJConstraint; + cgi.G2API_RagPCJGradientSpeed = CL_G2API_RagPCJGradientSpeed; + cgi.G2API_RagEffectorGoal = CL_G2API_RagEffectorGoal; + cgi.G2API_GetRagBonePos = CL_G2API_GetRagBonePos; + cgi.G2API_RagEffectorKick = CL_G2API_RagEffectorKick; + cgi.G2API_RagForceSolve = CL_G2API_RagForceSolve; + cgi.G2API_SetBoneIKState = CL_G2API_SetBoneIKState; + cgi.G2API_IKMove = CL_G2API_IKMove; + cgi.G2API_RemoveBone = CL_G2API_RemoveBone; + cgi.G2API_AttachInstanceToEntNum = CL_G2API_AttachInstanceToEntNum; + cgi.G2API_ClearAttachedInstance = CL_G2API_ClearAttachedInstance; + cgi.G2API_CleanEntAttachments = CL_G2API_CleanEntAttachments; + cgi.G2API_OverrideServer = CL_G2API_OverrideServer; + cgi.G2API_GetSurfaceName = CL_G2API_GetSurfaceName; + + cgi.ext.R_Font_StrLenPixels = re->ext.Font_StrLenPixels; GetCGameAPI = (GetCGameAPI_t)cgvm->GetModuleAPI; - ret = GetCGameAPI( CGAME_API_VERSION, &cgi ); - if ( !ret ) { - //free VM? + ret = GetCGameAPI(CGAME_API_VERSION, &cgi); + if (!ret) { + // free VM? cls.cgameStarted = qfalse; - Com_Error( ERR_FATAL, "GetGameAPI failed on %s", dllName ); + Com_Error(ERR_FATAL, "GetGameAPI failed on %s", dllName); } cge = ret; @@ -1925,15 +1943,15 @@ void CL_BindCGame( void ) { } // fall back to legacy syscall/vm_call api - cgvm = VM_CreateLegacy( VM_CGAME, CL_CgameSystemCalls ); - if ( !cgvm ) { + cgvm = VM_CreateLegacy(VM_CGAME, CL_CgameSystemCalls); + if (!cgvm) { cls.cgameStarted = qfalse; - Com_Error( ERR_DROP, "VM_CreateLegacy on cgame failed" ); + Com_Error(ERR_DROP, "VM_CreateLegacy on cgame failed"); } } -void CL_UnbindCGame( void ) { +void CL_UnbindCGame(void) { CGVM_Shutdown(); - VM_Free( cgvm ); + VM_Free(cgvm); cgvm = NULL; } diff --git a/codemp/client/cl_cin.cpp b/codemp/client/cl_cin.cpp index fde74076ab..4ea667f851 100644 --- a/codemp/client/cl_cin.cpp +++ b/codemp/client/cl_cin.cpp @@ -44,131 +44,127 @@ along with this program; if not, see . #include #endif -#define MAXSIZE 8 -#define MINSIZE 4 +#define MAXSIZE 8 +#define MINSIZE 4 -#define DEFAULT_CIN_WIDTH 512 -#define DEFAULT_CIN_HEIGHT 512 +#define DEFAULT_CIN_WIDTH 512 +#define DEFAULT_CIN_HEIGHT 512 -#define ROQ_QUAD 0x1000 -#define ROQ_QUAD_INFO 0x1001 -#define ROQ_CODEBOOK 0x1002 -#define ROQ_QUAD_VQ 0x1011 -#define ROQ_QUAD_JPEG 0x1012 -#define ROQ_QUAD_HANG 0x1013 -#define ROQ_PACKET 0x1030 -#define ZA_SOUND_MONO 0x1020 -#define ZA_SOUND_STEREO 0x1021 +#define ROQ_QUAD 0x1000 +#define ROQ_QUAD_INFO 0x1001 +#define ROQ_CODEBOOK 0x1002 +#define ROQ_QUAD_VQ 0x1011 +#define ROQ_QUAD_JPEG 0x1012 +#define ROQ_QUAD_HANG 0x1013 +#define ROQ_PACKET 0x1030 +#define ZA_SOUND_MONO 0x1020 +#define ZA_SOUND_STEREO 0x1021 -#define MAX_VIDEO_HANDLES 16 +#define MAX_VIDEO_HANDLES 16 -static void RoQ_init( void ); +static void RoQ_init(void); /****************************************************************************** -* -* Class: trFMV -* -* Description: RoQ/RnR manipulation routines -* not entirely complete for first run -* -******************************************************************************/ - -static long ROQ_YY_tab[256]; -static long ROQ_UB_tab[256]; -static long ROQ_UG_tab[256]; -static long ROQ_VG_tab[256]; -static long ROQ_VR_tab[256]; -static unsigned short vq2[256*16*4]; -static unsigned short vq4[256*64*4]; -static unsigned short vq8[256*256*4]; + * + * Class: trFMV + * + * Description: RoQ/RnR manipulation routines + * not entirely complete for first run + * + ******************************************************************************/ +static long ROQ_YY_tab[256]; +static long ROQ_UB_tab[256]; +static long ROQ_UG_tab[256]; +static long ROQ_VG_tab[256]; +static long ROQ_VR_tab[256]; +static unsigned short vq2[256 * 16 * 4]; +static unsigned short vq4[256 * 64 * 4]; +static unsigned short vq8[256 * 256 * 4]; typedef struct cinematics_s { - byte linbuf[DEFAULT_CIN_WIDTH*DEFAULT_CIN_HEIGHT*4*2]; - byte file[65536]; - short sqrTable[256]; + byte linbuf[DEFAULT_CIN_WIDTH * DEFAULT_CIN_HEIGHT * 4 * 2]; + byte file[65536]; + short sqrTable[256]; - int mcomp[256]; - byte *qStatus[2][32768]; + int mcomp[256]; + byte *qStatus[2][32768]; - long oldXOff, oldYOff, oldysize, oldxsize; + long oldXOff, oldYOff, oldysize, oldxsize; - int currentHandle; + int currentHandle; } cinematics_t; typedef struct cin_cache_s { - char fileName[MAX_OSPATH]; - int CIN_WIDTH, CIN_HEIGHT; - int xpos, ypos, width, height; - qboolean looping, holdAtEnd, dirty, alterGameState, silent, shader; - fileHandle_t iFile; - e_status status; - unsigned int startTime; - unsigned int lastTime; - long tfps; - long RoQPlayed; - long ROQSize; - unsigned int RoQFrameSize; - long onQuad; - long numQuads; - long samplesPerLine; - unsigned int roq_id; - long screenDelta; - - void ( *VQ0)(byte *status, void *qdata ); - void ( *VQ1)(byte *status, void *qdata ); - void ( *VQNormal)(byte *status, void *qdata ); - void ( *VQBuffer)(byte *status, void *qdata ); - - long samplesPerPixel; // defaults to 2 - byte* gray; - unsigned int xsize, ysize, maxsize, minsize; - - qboolean half, smootheddouble, inMemory; - long normalBuffer0; - long roq_flags; - long roqF0; - long roqF1; - long t[2]; - long roqFPS; - int playonwalls; - byte* buf; - long drawX, drawY; + char fileName[MAX_OSPATH]; + int CIN_WIDTH, CIN_HEIGHT; + int xpos, ypos, width, height; + qboolean looping, holdAtEnd, dirty, alterGameState, silent, shader; + fileHandle_t iFile; + e_status status; + unsigned int startTime; + unsigned int lastTime; + long tfps; + long RoQPlayed; + long ROQSize; + unsigned int RoQFrameSize; + long onQuad; + long numQuads; + long samplesPerLine; + unsigned int roq_id; + long screenDelta; + + void (*VQ0)(byte *status, void *qdata); + void (*VQ1)(byte *status, void *qdata); + void (*VQNormal)(byte *status, void *qdata); + void (*VQBuffer)(byte *status, void *qdata); + + long samplesPerPixel; // defaults to 2 + byte *gray; + unsigned int xsize, ysize, maxsize, minsize; + + qboolean half, smootheddouble, inMemory; + long normalBuffer0; + long roq_flags; + long roqF0; + long roqF1; + long t[2]; + long roqFPS; + int playonwalls; + byte *buf; + long drawX, drawY; } cin_cache_t; -static cinematics_t cin; -static cin_cache_t cinTable[MAX_VIDEO_HANDLES]; -static int currentHandle = -1; -static int CL_handle = -1; - -extern int s_soundtime; // sample PAIRS -extern int s_paintedtime; // sample PAIRS +static cinematics_t cin; +static cin_cache_t cinTable[MAX_VIDEO_HANDLES]; +static int currentHandle = -1; +static int CL_handle = -1; +extern int s_soundtime; // sample PAIRS +extern int s_paintedtime; // sample PAIRS void CIN_CloseAllVideos(void) { - int i; + int i; - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if (cinTable[i].fileName[0] != 0 ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (cinTable[i].fileName[0] != 0) { CIN_StopCinematic(i); } } } - static int CIN_HandleForVideo(void) { - int i; + int i; - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if ( cinTable[i].fileName[0] == 0 ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (cinTable[i].fileName[0] == 0) { return i; } } - Com_Error( ERR_DROP, "CIN_HandleForVideo: none free" ); + Com_Error(ERR_DROP, "CIN_HandleForVideo: none free"); return -1; } - //----------------------------------------------------------------------------- // RllSetupTable // @@ -178,18 +174,15 @@ static int CIN_HandleForVideo(void) { // // Returns: Nothing //----------------------------------------------------------------------------- -static void RllSetupTable( void ) -{ +static void RllSetupTable(void) { int z; - for (z=0;z<128;z++) { - cin.sqrTable[z] = (short)(z*z); - cin.sqrTable[z+128] = (short)(-cin.sqrTable[z]); + for (z = 0; z < 128; z++) { + cin.sqrTable[z] = (short)(z * z); + cin.sqrTable[z + 128] = (short)(-cin.sqrTable[z]); } } - - //----------------------------------------------------------------------------- // RllDecodeMonoToMono // @@ -221,7 +214,6 @@ static long RllDecodeMonoToMono(unsigned char *from,short *to,unsigned int size, } */ - //----------------------------------------------------------------------------- // RllDecodeMonoToStereo // @@ -236,25 +228,23 @@ static long RllDecodeMonoToMono(unsigned char *from,short *to,unsigned int size, // // Returns: Number of samples placed in output buffer //----------------------------------------------------------------------------- -static long RllDecodeMonoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput,unsigned short flag) -{ +static long RllDecodeMonoToStereo(unsigned char *from, short *to, unsigned int size, char signedOutput, unsigned short flag) { unsigned int z; int prev; if (signedOutput) - prev = flag - 0x8000; + prev = flag - 0x8000; else prev = flag; for (z = 0; z < size; z++) { prev = (short)(prev + cin.sqrTable[from[z]]); - to[z*2+0] = to[z*2+1] = (short)(prev); + to[z * 2 + 0] = to[z * 2 + 1] = (short)(prev); } - return size; // * 2 * sizeof(short)); + return size; // * 2 * sizeof(short)); } - //----------------------------------------------------------------------------- // RllDecodeStereoToStereo // @@ -268,11 +258,10 @@ static long RllDecodeMonoToStereo(unsigned char *from,short *to,unsigned int siz // // Returns: Number of samples placed in output buffer //----------------------------------------------------------------------------- -static long RllDecodeStereoToStereo(unsigned char *from,short *to,unsigned int size,char signedOutput, unsigned short flag) -{ +static long RllDecodeStereoToStereo(unsigned char *from, short *to, unsigned int size, char signedOutput, unsigned short flag) { unsigned int z; unsigned char *zz = from; - int prevL, prevR; + int prevL, prevR; if (signedOutput) { prevL = (flag & 0xff00) - 0x8000; @@ -282,17 +271,16 @@ static long RllDecodeStereoToStereo(unsigned char *from,short *to,unsigned int s prevR = (flag & 0x00ff) << 8; } - for (z=0;z>1); //*sizeof(short)); + return (size >> 1); //*sizeof(short)); } - //----------------------------------------------------------------------------- // RllDecodeStereoToMono // @@ -330,19 +318,17 @@ static long RllDecodeStereoToMono(unsigned char *from,short *to,unsigned int siz } */ /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void move8_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void move8_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 8; ++i) - { + for (i = 0; i < 8; ++i) { memcpy(dst, src, 32); src += spl; dst += spl; @@ -350,19 +336,17 @@ static void move8_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void move4_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void move4_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 4; ++i) - { + for (i = 0; i < 4; ++i) { memcpy(dst, src, 16); src += spl; dst += spl; @@ -370,19 +354,17 @@ static void move4_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blit8_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blit8_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 8; ++i) - { + for (i = 0; i < 8; ++i) { memcpy(dst, src, 32); src += 32; dst += spl; @@ -390,18 +372,16 @@ static void blit8_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ -static void blit4_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ +static void blit4_32(byte *src, byte *dst, int spl) { int i; - for(i = 0; i < 4; ++i) - { + for (i = 0; i < 4; ++i) { memmove(dst, src, 16); src += 16; dst += spl; @@ -409,190 +389,193 @@ static void blit4_32( byte *src, byte *dst, int spl ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blit2_32( byte *src, byte *dst, int spl ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blit2_32(byte *src, byte *dst, int spl) { memcpy(dst, src, 8); - memcpy(dst+spl, src+8, 8); + memcpy(dst + spl, src + 8, 8); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void blitVQQuad32fs( byte **status, unsigned char *data ) -{ -unsigned short newd, celdata, code; -unsigned int index, i; -int spl; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void blitVQQuad32fs(byte **status, unsigned char *data) { + unsigned short newd, celdata, code; + unsigned int index, i; + int spl; - newd = 0; + newd = 0; celdata = 0; - index = 0; + index = 0; - spl = cinTable[currentHandle].samplesPerLine; + spl = cinTable[currentHandle].samplesPerLine; do { if (!newd) { newd = 7; - celdata = data[0] + data[1]*256; + celdata = data[0] + data[1] * 256; data += 2; } else { newd--; } - code = (unsigned short)(celdata&0xc000); + code = (unsigned short)(celdata & 0xc000); celdata <<= 2; switch (code) { - case 0x8000: // vq code - blit8_32( (byte *)&vq8[(*data)*128], status[index], spl ); - data++; - index += 5; - break; - case 0xc000: // drop - index++; // skip 8x8 - for(i=0;i<4;i++) { - if (!newd) { - newd = 7; - celdata = data[0] + data[1]*256; - data += 2; - } else { - newd--; - } + case 0x8000: // vq code + blit8_32((byte *)&vq8[(*data) * 128], status[index], spl); + data++; + index += 5; + break; + case 0xc000: // drop + index++; // skip 8x8 + for (i = 0; i < 4; i++) { + if (!newd) { + newd = 7; + celdata = data[0] + data[1] * 256; + data += 2; + } else { + newd--; + } - code = (unsigned short)(celdata&0xc000); celdata <<= 2; - - switch (code) { // code in top two bits of code - case 0x8000: // 4x4 vq code - blit4_32( (byte *)&vq4[(*data)*32], status[index], spl ); - data++; - break; - case 0xc000: // 2x2 vq code - blit2_32( (byte *)&vq2[(*data)*8], status[index], spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+8, spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2, spl ); - data++; - blit2_32( (byte *)&vq2[(*data)*8], status[index]+spl*2+8, spl ); - data++; - break; - case 0x4000: // motion compensation - move4_32( status[index] + cin.mcomp[(*data)], status[index], spl ); - data++; - break; - } - index++; + code = (unsigned short)(celdata & 0xc000); + celdata <<= 2; + + switch (code) { // code in top two bits of code + case 0x8000: // 4x4 vq code + blit4_32((byte *)&vq4[(*data) * 32], status[index], spl); + data++; + break; + case 0xc000: // 2x2 vq code + blit2_32((byte *)&vq2[(*data) * 8], status[index], spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + 8, spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + spl * 2, spl); + data++; + blit2_32((byte *)&vq2[(*data) * 8], status[index] + spl * 2 + 8, spl); + data++; + break; + case 0x4000: // motion compensation + move4_32(status[index] + cin.mcomp[(*data)], status[index], spl); + data++; + break; } - break; - case 0x4000: // motion compensation - move8_32( status[index] + cin.mcomp[(*data)], status[index], spl ); - data++; - index += 5; - break; - case 0x0000: - index += 5; - break; + index++; + } + break; + case 0x4000: // motion compensation + move8_32(status[index] + cin.mcomp[(*data)], status[index], spl); + data++; + index += 5; + break; + case 0x0000: + index += 5; + break; } - } while ( status[index] != NULL ); + } while (status[index] != NULL); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void ROQ_GenYUVTables( void ) -{ - float t_ub,t_vr,t_ug,t_vg; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void ROQ_GenYUVTables(void) { + float t_ub, t_vr, t_ug, t_vg; long i; - t_ub = (1.77200f/2.0f) * (float)(1<<6) + 0.5f; - t_vr = (1.40200f/2.0f) * (float)(1<<6) + 0.5f; - t_ug = (0.34414f/2.0f) * (float)(1<<6) + 0.5f; - t_vg = (0.71414f/2.0f) * (float)(1<<6) + 0.5f; - for(i=0;i<256;i++) { + t_ub = (1.77200f / 2.0f) * (float)(1 << 6) + 0.5f; + t_vr = (1.40200f / 2.0f) * (float)(1 << 6) + 0.5f; + t_ug = (0.34414f / 2.0f) * (float)(1 << 6) + 0.5f; + t_vg = (0.71414f / 2.0f) * (float)(1 << 6) + 0.5f; + for (i = 0; i < 256; i++) { float x = (float)(2 * i - 255); - ROQ_UB_tab[i] = (long)( ( t_ub * x) + (1<<5)); - ROQ_VR_tab[i] = (long)( ( t_vr * x) + (1<<5)); - ROQ_UG_tab[i] = (long)( (-t_ug * x) ); - ROQ_VG_tab[i] = (long)( (-t_vg * x) + (1<<5)); - ROQ_YY_tab[i] = (long)( (i << 6) | (i >> 2) ); + ROQ_UB_tab[i] = (long)((t_ub * x) + (1 << 5)); + ROQ_VR_tab[i] = (long)((t_vr * x) + (1 << 5)); + ROQ_UG_tab[i] = (long)((-t_ug * x)); + ROQ_VG_tab[i] = (long)((-t_vg * x) + (1 << 5)); + ROQ_YY_tab[i] = (long)((i << 6) | (i >> 2)); } } -#define VQ2TO4(a,b,c,d) { \ - *c++ = a[0]; \ - *d++ = a[0]; \ - *d++ = a[0]; \ - *c++ = a[1]; \ - *d++ = a[1]; \ - *d++ = a[1]; \ - *c++ = b[0]; \ - *d++ = b[0]; \ - *d++ = b[0]; \ - *c++ = b[1]; \ - *d++ = b[1]; \ - *d++ = b[1]; \ - *d++ = a[0]; \ - *d++ = a[0]; \ - *d++ = a[1]; \ - *d++ = a[1]; \ - *d++ = b[0]; \ - *d++ = b[0]; \ - *d++ = b[1]; \ - *d++ = b[1]; \ - a += 2; b += 2; } - -#define VQ2TO2(a,b,c,d) { \ - *c++ = *a; \ - *d++ = *a; \ - *d++ = *a; \ - *c++ = *b; \ - *d++ = *b; \ - *d++ = *b; \ - *d++ = *a; \ - *d++ = *a; \ - *d++ = *b; \ - *d++ = *b; \ - a++; b++; } +#define VQ2TO4(a, b, c, d) \ + { \ + *c++ = a[0]; \ + *d++ = a[0]; \ + *d++ = a[0]; \ + *c++ = a[1]; \ + *d++ = a[1]; \ + *d++ = a[1]; \ + *c++ = b[0]; \ + *d++ = b[0]; \ + *d++ = b[0]; \ + *c++ = b[1]; \ + *d++ = b[1]; \ + *d++ = b[1]; \ + *d++ = a[0]; \ + *d++ = a[0]; \ + *d++ = a[1]; \ + *d++ = a[1]; \ + *d++ = b[0]; \ + *d++ = b[0]; \ + *d++ = b[1]; \ + *d++ = b[1]; \ + a += 2; \ + b += 2; \ + } + +#define VQ2TO2(a, b, c, d) \ + { \ + *c++ = *a; \ + *d++ = *a; \ + *d++ = *a; \ + *c++ = *b; \ + *d++ = *b; \ + *d++ = *b; \ + *d++ = *a; \ + *d++ = *a; \ + *d++ = *b; \ + *d++ = *b; \ + a++; \ + b++; \ + } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static unsigned short yuv_to_rgb( long y, long u, long v ) -{ - long r,g,b,YY = (long)(ROQ_YY_tab[(y)]); + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static unsigned short yuv_to_rgb(long y, long u, long v) { + long r, g, b, YY = (long)(ROQ_YY_tab[(y)]); r = (YY + ROQ_VR_tab[v]) >> 9; g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 8; b = (YY + ROQ_UB_tab[u]) >> 9; - if (r<0) + if (r < 0) r = 0; - if (g<0) + if (g < 0) g = 0; - if (b<0) + if (b < 0) b = 0; if (r > 31) r = 31; @@ -601,29 +584,28 @@ static unsigned short yuv_to_rgb( long y, long u, long v ) if (b > 31) b = 31; - return (unsigned short)((r<<11)+(g<<5)+(b)); + return (unsigned short)((r << 11) + (g << 5) + (b)); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ -static unsigned int yuv_to_rgb24( long y, long u, long v ) -{ - long r,g,b,YY = (long)(ROQ_YY_tab[(y)]); + * + * Function: + * + * Description: + * + ******************************************************************************/ +static unsigned int yuv_to_rgb24(long y, long u, long v) { + long r, g, b, YY = (long)(ROQ_YY_tab[(y)]); r = (YY + ROQ_VR_tab[v]) >> 6; g = (YY + ROQ_UG_tab[u] + ROQ_VG_tab[v]) >> 6; b = (YY + ROQ_UB_tab[u]) >> 6; - if (r<0) + if (r < 0) r = 0; - if (g<0) + if (g < 0) g = 0; - if (b<0) + if (b < 0) b = 0; if (r > 255) r = 255; @@ -632,23 +614,22 @@ static unsigned int yuv_to_rgb24( long y, long u, long v ) if (b > 255) b = 255; - return LittleLong ((r)|(g<<8)|(b<<16)|(255<<24)); + return LittleLong((r) | (g << 8) | (b << 16) | (255 << 24)); } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void decodeCodeBook( byte *input, unsigned short roq_flags ) -{ - long i, j, two, four; - unsigned short *aptr, *bptr, *cptr, *dptr; - long y0,y1,y2,y3,cr,cb; - byte *bbptr, *baptr, *bcptr, *bdptr; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void decodeCodeBook(byte *input, unsigned short roq_flags) { + long i, j, two, four; + unsigned short *aptr, *bptr, *cptr, *dptr; + long y0, y1, y2, y3, cr, cb; + byte *bbptr, *baptr, *bcptr, *bdptr; union { unsigned int *i; unsigned short *s; @@ -657,9 +638,10 @@ static void decodeCodeBook( byte *input, unsigned short roq_flags ) if (!roq_flags) { two = four = 256; } else { - two = roq_flags>>8; - if (!two) two = 256; - four = roq_flags&0xff; + two = roq_flags >> 8; + if (!two) + two = 256; + four = roq_flags & 0xff; } four *= 2; @@ -668,155 +650,157 @@ static void decodeCodeBook( byte *input, unsigned short roq_flags ) if (!cinTable[currentHandle].half) { if (!cinTable[currentHandle].smootheddouble) { -// -// normal height -// - if (cinTable[currentHandle].samplesPerPixel==2) { - for(i=0;i cinTable[currentHandle].CIN_WIDTH) bigx = cinTable[currentHandle].CIN_WIDTH; - if (bigy > cinTable[currentHandle].CIN_HEIGHT) bigy = cinTable[currentHandle].CIN_HEIGHT; + if (bigx > cinTable[currentHandle].CIN_WIDTH) + bigx = cinTable[currentHandle].CIN_WIDTH; + if (bigy > cinTable[currentHandle].CIN_HEIGHT) + bigy = cinTable[currentHandle].CIN_HEIGHT; - if ( (startX >= lowx) && (startX+quadSize) <= (bigx) && (startY+quadSize) <= (bigy) && (startY >= lowy) && quadSize <= MAXSIZE) { + if ((startX >= lowx) && (startX + quadSize) <= (bigx) && (startY + quadSize) <= (bigy) && (startY >= lowy) && quadSize <= MAXSIZE) { useY = startY; - scroff = cin.linbuf + (useY+((cinTable[currentHandle].CIN_HEIGHT-bigy)>>1)+yOff)*(cinTable[currentHandle].samplesPerLine) + (((startX+xOff))*cinTable[currentHandle].samplesPerPixel); + scroff = cin.linbuf + (useY + ((cinTable[currentHandle].CIN_HEIGHT - bigy) >> 1) + yOff) * (cinTable[currentHandle].samplesPerLine) + + (((startX + xOff)) * cinTable[currentHandle].samplesPerPixel); - cin.qStatus[0][cinTable[currentHandle].onQuad ] = scroff; - cin.qStatus[1][cinTable[currentHandle].onQuad++] = scroff+offset; + cin.qStatus[0][cinTable[currentHandle].onQuad] = scroff; + cin.qStatus[1][cinTable[currentHandle].onQuad++] = scroff + offset; } - if ( quadSize != MINSIZE ) { + if (quadSize != MINSIZE) { quadSize >>= 1; - recurseQuad( startX, startY , quadSize, xOff, yOff ); - recurseQuad( startX+quadSize, startY , quadSize, xOff, yOff ); - recurseQuad( startX, startY+quadSize , quadSize, xOff, yOff ); - recurseQuad( startX+quadSize, startY+quadSize , quadSize, xOff, yOff ); + recurseQuad(startX, startY, quadSize, xOff, yOff); + recurseQuad(startX + quadSize, startY, quadSize, xOff, yOff); + recurseQuad(startX, startY + quadSize, quadSize, xOff, yOff); + recurseQuad(startX + quadSize, startY + quadSize, quadSize, xOff, yOff); } } - /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void setupQuad( long xOff, long yOff ) -{ - long numQuadCels, i,x,y; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void setupQuad(long xOff, long yOff) { + long numQuadCels, i, x, y; byte *temp; - if (xOff == cin.oldXOff && yOff == cin.oldYOff && cinTable[currentHandle].ysize == (unsigned)cin.oldysize && cinTable[currentHandle].xsize == (unsigned)cin.oldxsize) { + if (xOff == cin.oldXOff && yOff == cin.oldYOff && cinTable[currentHandle].ysize == (unsigned)cin.oldysize && + cinTable[currentHandle].xsize == (unsigned)cin.oldxsize) { return; } @@ -965,52 +956,52 @@ static void setupQuad( long xOff, long yOff ) cin.oldYOff = yOff; cin.oldysize = cinTable[currentHandle].ysize; cin.oldxsize = cinTable[currentHandle].xsize; -/* Enisform: Not in q3 source - numQuadCels = (cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].CIN_HEIGHT) / (16); - numQuadCels += numQuadCels/4 + numQuadCels/16; - numQuadCels += 64; // for overflow -*/ + /* Enisform: Not in q3 source + numQuadCels = (cinTable[currentHandle].CIN_WIDTH*cinTable[currentHandle].CIN_HEIGHT) / (16); + numQuadCels += numQuadCels/4 + numQuadCels/16; + numQuadCels += 64; // for overflow + */ - numQuadCels = (cinTable[currentHandle].xsize*cinTable[currentHandle].ysize) / (16); - numQuadCels += numQuadCels/4; - numQuadCels += 64; // for overflow + numQuadCels = (cinTable[currentHandle].xsize * cinTable[currentHandle].ysize) / (16); + numQuadCels += numQuadCels / 4; + numQuadCels += 64; // for overflow cinTable[currentHandle].onQuad = 0; - for(y=0;y<(long)cinTable[currentHandle].ysize;y+=16) - for(x=0;x<(long)cinTable[currentHandle].xsize;x+=16) - recurseQuad( x, y, 16, xOff, yOff ); + for (y = 0; y < (long)cinTable[currentHandle].ysize; y += 16) + for (x = 0; x < (long)cinTable[currentHandle].xsize; x += 16) + recurseQuad(x, y, 16, xOff, yOff); temp = NULL; - for(i=(numQuadCels-64);i256) { - cinTable[currentHandle].drawX = 256; - } - if (cinTable[currentHandle].drawY>256) { - cinTable[currentHandle].drawY = 256; - } + if (cls.glconfig.maxTextureSize <= 256) { + if (cinTable[currentHandle].drawX > 256) { + cinTable[currentHandle].drawX = 256; + } + if (cinTable[currentHandle].drawY > 256) { + cinTable[currentHandle].drawY = 256; + } if (cinTable[currentHandle].CIN_WIDTH != 256 || cinTable[currentHandle].CIN_HEIGHT != 256) { Com_Printf("HACK: approxmimating cinematic for Rage Pro or Voodoo\n"); } @@ -1038,40 +1029,43 @@ static void readQuadInfo( byte *qData ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQPrepMcomp( long xoff, long yoff ) -{ + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQPrepMcomp(long xoff, long yoff) { long i, j, x, y, temp, temp2; - i=cinTable[currentHandle].samplesPerLine; j=cinTable[currentHandle].samplesPerPixel; - if ( cinTable[currentHandle].xsize == (cinTable[currentHandle].ysize*4) && !cinTable[currentHandle].half ) { j = j+j; i = i+i; } + i = cinTable[currentHandle].samplesPerLine; + j = cinTable[currentHandle].samplesPerPixel; + if (cinTable[currentHandle].xsize == (cinTable[currentHandle].ysize * 4) && !cinTable[currentHandle].half) { + j = j + j; + i = i + i; + } - for(y=0;y<16;y++) { - temp2 = (y+yoff-8)*i; - for(x=0;x<16;x++) { - temp = (x+xoff-8)*j; - cin.mcomp[(x*16)+y] = cinTable[currentHandle].normalBuffer0-(temp2+temp); + for (y = 0; y < 16; y++) { + temp2 = (y + yoff - 8) * i; + for (x = 0; x < 16; x++) { + temp = (x + xoff - 8) * j; + cin.mcomp[(x * 16) + y] = cinTable[currentHandle].normalBuffer0 - (temp2 + temp); } } } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void initRoQ( void ) -{ - if (currentHandle < 0) return; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void initRoQ(void) { + if (currentHandle < 0) + return; cinTable[currentHandle].VQNormal = (void (*)(byte *, void *))blitVQQuad32fs; cinTable[currentHandle].VQBuffer = (void (*)(byte *, void *))blitVQQuad32fs; @@ -1081,12 +1075,12 @@ static void initRoQ( void ) } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ + * + * Function: + * + * Description: + * + ******************************************************************************/ /* static byte* RoQFetchInterlaced( byte *source ) { int x, *src, *dst; @@ -1103,37 +1097,38 @@ static byte* RoQFetchInterlaced( byte *source ) { return cinTable[currentHandle].buf2; } */ -static void RoQReset( void ) { +static void RoQReset(void) { - if (currentHandle < 0) return; + if (currentHandle < 0) + return; - FS_FCloseFile( cinTable[currentHandle].iFile ); - FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); + FS_FCloseFile(cinTable[currentHandle].iFile); + FS_FOpenFileRead(cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); // let the background thread start reading ahead - FS_Read (cin.file, 16, cinTable[currentHandle].iFile); + FS_Read(cin.file, 16, cinTable[currentHandle].iFile); RoQ_init(); cinTable[currentHandle].status = FMV_LOOPED; } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQInterrupt(void) -{ - byte *framedata; - short sbuf[32768]; - int ssize; + * + * Function: + * + * Description: + * + ******************************************************************************/ - if (currentHandle < 0) return; +static void RoQInterrupt(void) { + byte *framedata; + short sbuf[32768]; + int ssize; + + if (currentHandle < 0) + return; - FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); - if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) { - if (cinTable[currentHandle].holdAtEnd==qfalse) { + FS_Read(cin.file, cinTable[currentHandle].RoQFrameSize + 8, cinTable[currentHandle].iFile); + if (cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize) { + if (cinTable[currentHandle].holdAtEnd == qfalse) { if (cinTable[currentHandle].looping) { RoQReset(); } else { @@ -1150,71 +1145,71 @@ static void RoQInterrupt(void) // new frame is ready // redump: - switch(cinTable[currentHandle].roq_id) - { - case ROQ_QUAD_VQ: - if ((cinTable[currentHandle].numQuads&1)) { - cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[1]; - RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 ); - cinTable[currentHandle].VQ1( (byte *)cin.qStatus[1], framedata); - cinTable[currentHandle].buf = cin.linbuf + cinTable[currentHandle].screenDelta; - } else { - cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[0]; - RoQPrepMcomp( cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1 ); - cinTable[currentHandle].VQ0( (byte *)cin.qStatus[0], framedata ); - cinTable[currentHandle].buf = cin.linbuf; - } - if (cinTable[currentHandle].numQuads == 0) { // first frame - Com_Memcpy(cin.linbuf+cinTable[currentHandle].screenDelta, cin.linbuf, cinTable[currentHandle].samplesPerLine*cinTable[currentHandle].ysize); - } - cinTable[currentHandle].numQuads++; - cinTable[currentHandle].dirty = qtrue; - break; - case ROQ_CODEBOOK: - decodeCodeBook( framedata, (unsigned short)cinTable[currentHandle].roq_flags ); - break; - case ZA_SOUND_MONO: - if (!cinTable[currentHandle].silent) { - ssize = RllDecodeMonoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); - S_RawSamples( ssize, 22050, 2, 1, (byte *)sbuf, s_volume->value, 1 ); - } - break; - case ZA_SOUND_STEREO: - if (!cinTable[currentHandle].silent) { - if (cinTable[currentHandle].numQuads == -1) { - S_Update(); - s_rawend = s_soundtime; - } - ssize = RllDecodeStereoToStereo( framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); - S_RawSamples( ssize, 22050, 2, 2, (byte *)sbuf, s_volume->value, 1 ); - } - break; - case ROQ_QUAD_INFO: + switch (cinTable[currentHandle].roq_id) { + case ROQ_QUAD_VQ: + if ((cinTable[currentHandle].numQuads & 1)) { + cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[1]; + RoQPrepMcomp(cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1); + cinTable[currentHandle].VQ1((byte *)cin.qStatus[1], framedata); + cinTable[currentHandle].buf = cin.linbuf + cinTable[currentHandle].screenDelta; + } else { + cinTable[currentHandle].normalBuffer0 = cinTable[currentHandle].t[0]; + RoQPrepMcomp(cinTable[currentHandle].roqF0, cinTable[currentHandle].roqF1); + cinTable[currentHandle].VQ0((byte *)cin.qStatus[0], framedata); + cinTable[currentHandle].buf = cin.linbuf; + } + if (cinTable[currentHandle].numQuads == 0) { // first frame + Com_Memcpy(cin.linbuf + cinTable[currentHandle].screenDelta, cin.linbuf, cinTable[currentHandle].samplesPerLine * cinTable[currentHandle].ysize); + } + cinTable[currentHandle].numQuads++; + cinTable[currentHandle].dirty = qtrue; + break; + case ROQ_CODEBOOK: + decodeCodeBook(framedata, (unsigned short)cinTable[currentHandle].roq_flags); + break; + case ZA_SOUND_MONO: + if (!cinTable[currentHandle].silent) { + ssize = RllDecodeMonoToStereo(framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); + S_RawSamples(ssize, 22050, 2, 1, (byte *)sbuf, s_volume->value, 1); + } + break; + case ZA_SOUND_STEREO: + if (!cinTable[currentHandle].silent) { if (cinTable[currentHandle].numQuads == -1) { - readQuadInfo( framedata ); - setupQuad( 0, 0 ); - cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds()*com_timescale->value; + S_Update(); + s_rawend = s_soundtime; } - if (cinTable[currentHandle].numQuads != 1) cinTable[currentHandle].numQuads = 0; - break; - case ROQ_PACKET: - cinTable[currentHandle].inMemory = (qboolean)cinTable[currentHandle].roq_flags; - cinTable[currentHandle].RoQFrameSize = 0; // for header - break; - case ROQ_QUAD_HANG: - cinTable[currentHandle].RoQFrameSize = 0; - break; - case ROQ_QUAD_JPEG: - break; - default: - cinTable[currentHandle].status = FMV_EOF; - break; + ssize = RllDecodeStereoToStereo(framedata, sbuf, cinTable[currentHandle].RoQFrameSize, 0, (unsigned short)cinTable[currentHandle].roq_flags); + S_RawSamples(ssize, 22050, 2, 2, (byte *)sbuf, s_volume->value, 1); + } + break; + case ROQ_QUAD_INFO: + if (cinTable[currentHandle].numQuads == -1) { + readQuadInfo(framedata); + setupQuad(0, 0); + cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds() * com_timescale->value; + } + if (cinTable[currentHandle].numQuads != 1) + cinTable[currentHandle].numQuads = 0; + break; + case ROQ_PACKET: + cinTable[currentHandle].inMemory = (qboolean)cinTable[currentHandle].roq_flags; + cinTable[currentHandle].RoQFrameSize = 0; // for header + break; + case ROQ_QUAD_HANG: + cinTable[currentHandle].RoQFrameSize = 0; + break; + case ROQ_QUAD_JPEG: + break; + default: + cinTable[currentHandle].status = FMV_EOF; + break; } -// -// read in next frame data -// - if ( cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize ) { - if (cinTable[currentHandle].holdAtEnd==qfalse) { + // + // read in next frame data + // + if (cinTable[currentHandle].RoQPlayed >= cinTable[currentHandle].ROQSize) { + if (cinTable[currentHandle].holdAtEnd == qfalse) { if (cinTable[currentHandle].looping) { RoQReset(); } else { @@ -1226,14 +1221,14 @@ static void RoQInterrupt(void) return; } - framedata += cinTable[currentHandle].RoQFrameSize; - cinTable[currentHandle].roq_id = framedata[0] + framedata[1]*256; - cinTable[currentHandle].RoQFrameSize = framedata[2] + framedata[3]*256 + framedata[4]*65536; - cinTable[currentHandle].roq_flags = framedata[6] + framedata[7]*256; - cinTable[currentHandle].roqF0 = (signed char)framedata[7]; - cinTable[currentHandle].roqF1 = (signed char)framedata[6]; + framedata += cinTable[currentHandle].RoQFrameSize; + cinTable[currentHandle].roq_id = framedata[0] + framedata[1] * 256; + cinTable[currentHandle].RoQFrameSize = framedata[2] + framedata[3] * 256 + framedata[4] * 65536; + cinTable[currentHandle].roq_flags = framedata[6] + framedata[7] * 256; + cinTable[currentHandle].roqF0 = (signed char)framedata[7]; + cinTable[currentHandle].roqF1 = (signed char)framedata[6]; - if (cinTable[currentHandle].RoQFrameSize>65536||cinTable[currentHandle].roq_id==0x1084) { + if (cinTable[currentHandle].RoQFrameSize > 65536 || cinTable[currentHandle].roq_id == 0x1084) { Com_DPrintf("roq_size>65536||roq_id==0x1084\n"); cinTable[currentHandle].status = FMV_EOF; if (cinTable[currentHandle].looping) { @@ -1241,74 +1236,72 @@ static void RoQInterrupt(void) } return; } - if (cinTable[currentHandle].inMemory && (cinTable[currentHandle].status != FMV_EOF)) - { - cinTable[currentHandle].inMemory = (qboolean)(((int)cinTable[currentHandle].inMemory)-1); + if (cinTable[currentHandle].inMemory && (cinTable[currentHandle].status != FMV_EOF)) { + cinTable[currentHandle].inMemory = (qboolean)(((int)cinTable[currentHandle].inMemory) - 1); framedata += 8; goto redump; } -// -// one more frame hits the dust -// -// assert(cinTable[currentHandle].RoQFrameSize <= 65536); -// r = FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); - cinTable[currentHandle].RoQPlayed += cinTable[currentHandle].RoQFrameSize+8; + // + // one more frame hits the dust + // + // assert(cinTable[currentHandle].RoQFrameSize <= 65536); + // r = FS_Read( cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile ); + cinTable[currentHandle].RoQPlayed += cinTable[currentHandle].RoQFrameSize + 8; } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQ_init( void ) -{ - cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds()*com_timescale->value; + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQ_init(void) { + cinTable[currentHandle].startTime = cinTable[currentHandle].lastTime = Sys_Milliseconds() * com_timescale->value; cinTable[currentHandle].RoQPlayed = 24; -/* get frame rate */ - cinTable[currentHandle].roqFPS = cin.file[ 6] + cin.file[ 7]*256; + /* get frame rate */ + cinTable[currentHandle].roqFPS = cin.file[6] + cin.file[7] * 256; - if (!cinTable[currentHandle].roqFPS) cinTable[currentHandle].roqFPS = 30; + if (!cinTable[currentHandle].roqFPS) + cinTable[currentHandle].roqFPS = 30; cinTable[currentHandle].numQuads = -1; - cinTable[currentHandle].roq_id = cin.file[ 8] + cin.file[ 9]*256; - cinTable[currentHandle].RoQFrameSize = cin.file[10] + cin.file[11]*256 + cin.file[12]*65536; - cinTable[currentHandle].roq_flags = cin.file[14] + cin.file[15]*256; + cinTable[currentHandle].roq_id = cin.file[8] + cin.file[9] * 256; + cinTable[currentHandle].RoQFrameSize = cin.file[10] + cin.file[11] * 256 + cin.file[12] * 65536; + cinTable[currentHandle].roq_flags = cin.file[14] + cin.file[15] * 256; if (cinTable[currentHandle].RoQFrameSize > 65536 || !cinTable[currentHandle].RoQFrameSize) { return; } - } /****************************************************************************** -* -* Function: -* -* Description: -* -******************************************************************************/ - -static void RoQShutdown( void ) { + * + * Function: + * + * Description: + * + ******************************************************************************/ + +static void RoQShutdown(void) { const char *s; if (!cinTable[currentHandle].buf) { return; } - if ( cinTable[currentHandle].status == FMV_IDLE ) { + if (cinTable[currentHandle].status == FMV_IDLE) { return; } Com_DPrintf("finished cinematic\n"); cinTable[currentHandle].status = FMV_IDLE; if (cinTable[currentHandle].iFile) { - FS_FCloseFile( cinTable[currentHandle].iFile ); + FS_FCloseFile(cinTable[currentHandle].iFile); cinTable[currentHandle].iFile = 0; } @@ -1318,10 +1311,10 @@ static void RoQShutdown( void ) { // if we are aborting the intro cinematic with // a devmap command, nextmap would be valid by // the time it was referenced - s = Cvar_VariableString( "nextmap" ); - if ( s[0] ) { - Cbuf_ExecuteText( EXEC_APPEND, va("%s\n", s) ); - Cvar_Set( "nextmap", "" ); + s = Cvar_VariableString("nextmap"); + if (s[0]) { + Cbuf_ExecuteText(EXEC_APPEND, va("%s\n", s)); + Cvar_Set("nextmap", ""); } CL_handle = -1; } @@ -1336,7 +1329,8 @@ CIN_StopCinematic */ e_status CIN_StopCinematic(int handle) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return FMV_EOF; currentHandle = handle; Com_DPrintf("trFMV::stop(), closing %s\n", cinTable[currentHandle].fileName); @@ -1346,7 +1340,7 @@ e_status CIN_StopCinematic(int handle) { } if (cinTable[currentHandle].alterGameState) { - if ( cls.state != CA_CINEMATIC ) { + if (cls.state != CA_CINEMATIC) { return cinTable[currentHandle].status; } } @@ -1364,13 +1358,12 @@ Fetch and decompress the pending frame ================== */ +e_status CIN_RunCinematic(int handle) { + int start = 0; + int thisTime = 0; -e_status CIN_RunCinematic (int handle) -{ - int start = 0; - int thisTime = 0; - - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return FMV_EOF; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return FMV_EOF; if (cin.currentHandle != handle) { currentHandle = handle; @@ -1379,15 +1372,14 @@ e_status CIN_RunCinematic (int handle) RoQReset(); } - if (cinTable[handle].playonwalls < -1) - { + if (cinTable[handle].playonwalls < -1) { return cinTable[handle].status; } currentHandle = handle; if (cinTable[currentHandle].alterGameState) { - if ( cls.state != CA_CINEMATIC ) { + if (cls.state != CA_CINEMATIC) { return cinTable[currentHandle].status; } } @@ -1396,20 +1388,19 @@ e_status CIN_RunCinematic (int handle) return cinTable[currentHandle].status; } - thisTime = Sys_Milliseconds()*com_timescale->value; - if (cinTable[currentHandle].shader && (abs(thisTime - (double)cinTable[currentHandle].lastTime))>100) { + thisTime = Sys_Milliseconds() * com_timescale->value; + if (cinTable[currentHandle].shader && (abs(thisTime - (double)cinTable[currentHandle].lastTime)) > 100) { cinTable[currentHandle].startTime += thisTime - cinTable[currentHandle].lastTime; } - cinTable[currentHandle].tfps = ((((Sys_Milliseconds()*com_timescale->value) - cinTable[currentHandle].startTime)*cinTable[currentHandle].roqFPS)/1000); + cinTable[currentHandle].tfps = + ((((Sys_Milliseconds() * com_timescale->value) - cinTable[currentHandle].startTime) * cinTable[currentHandle].roqFPS) / 1000); start = cinTable[currentHandle].startTime; - while( (cinTable[currentHandle].tfps != cinTable[currentHandle].numQuads) - && (cinTable[currentHandle].status == FMV_PLAY) ) - { + while ((cinTable[currentHandle].tfps != cinTable[currentHandle].numQuads) && (cinTable[currentHandle].status == FMV_PLAY)) { RoQInterrupt(); if ((unsigned)start != cinTable[currentHandle].startTime) { - cinTable[currentHandle].tfps = ((((Sys_Milliseconds()*com_timescale->value) - - cinTable[currentHandle].startTime)*cinTable[currentHandle].roqFPS)/1000); + cinTable[currentHandle].tfps = + ((((Sys_Milliseconds() * com_timescale->value) - cinTable[currentHandle].startTime) * cinTable[currentHandle].roqFPS) / 1000); start = cinTable[currentHandle].startTime; } } @@ -1421,11 +1412,11 @@ e_status CIN_RunCinematic (int handle) } if (cinTable[currentHandle].status == FMV_EOF) { - if (cinTable[currentHandle].looping) { - RoQReset(); - } else { - RoQShutdown(); - } + if (cinTable[currentHandle].looping) { + RoQReset(); + } else { + RoQShutdown(); + } } return cinTable[currentHandle].status; @@ -1436,21 +1427,21 @@ e_status CIN_RunCinematic (int handle) CIN_PlayCinematic ================== */ -int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBits ) { +int CIN_PlayCinematic(const char *arg, int x, int y, int w, int h, int systemBits) { unsigned short RoQID; - char name[MAX_OSPATH]; - int i; + char name[MAX_OSPATH]; + int i; if (strstr(arg, "/") == NULL && strstr(arg, "\\") == NULL) { - Com_sprintf (name, sizeof(name), "video/%s", arg); + Com_sprintf(name, sizeof(name), "video/%s", arg); } else { - Com_sprintf (name, sizeof(name), "%s", arg); + Com_sprintf(name, sizeof(name), "%s", arg); } - COM_DefaultExtension(name,sizeof(name),".roq"); + COM_DefaultExtension(name, sizeof(name), ".roq"); if (!(systemBits & CIN_system)) { - for ( i = 0 ; i < MAX_VIDEO_HANDLES ; i++ ) { - if (!strcmp(cinTable[i].fileName, name) ) { + for (i = 0; i < MAX_VIDEO_HANDLES; i++) { + if (!strcmp(cinTable[i].fileName, name)) { return i; } } @@ -1458,7 +1449,7 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi Com_DPrintf("CIN_PlayCinematic( %s )\n", arg); - Com_Memset(&cin, 0, sizeof(cinematics_t) ); + Com_Memset(&cin, 0, sizeof(cinematics_t)); currentHandle = CIN_HandleForVideo(); cin.currentHandle = currentHandle; @@ -1466,19 +1457,19 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi strcpy(cinTable[currentHandle].fileName, name); cinTable[currentHandle].ROQSize = 0; - cinTable[currentHandle].ROQSize = FS_FOpenFileRead (cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); + cinTable[currentHandle].ROQSize = FS_FOpenFileRead(cinTable[currentHandle].fileName, &cinTable[currentHandle].iFile, qtrue); - if (cinTable[currentHandle].ROQSize<=0) { + if (cinTable[currentHandle].ROQSize <= 0) { Com_DPrintf("cinematic failed to open %s\n", arg); cinTable[currentHandle].fileName[0] = 0; return -1; } CIN_SetExtents(currentHandle, x, y, w, h); - CIN_SetLooping(currentHandle, (qboolean)((systemBits & CIN_loop)!=0)); + CIN_SetLooping(currentHandle, (qboolean)((systemBits & CIN_loop) != 0)); cinTable[currentHandle].CIN_HEIGHT = DEFAULT_CIN_HEIGHT; - cinTable[currentHandle].CIN_WIDTH = DEFAULT_CIN_WIDTH; + cinTable[currentHandle].CIN_WIDTH = DEFAULT_CIN_WIDTH; cinTable[currentHandle].holdAtEnd = (qboolean)((systemBits & CIN_hold) != 0); cinTable[currentHandle].alterGameState = (qboolean)((systemBits & CIN_system) != 0); cinTable[currentHandle].playonwalls = 1; @@ -1487,8 +1478,8 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi if (cinTable[currentHandle].alterGameState) { // close the menu - if ( cls.uiStarted ) { - UIVM_SetActiveMenu( UIMENU_NONE ); + if (cls.uiStarted) { + UIVM_SetActiveMenu(UIMENU_NONE); } } else { cinTable[currentHandle].playonwalls = cl_inGameVideo->integer; @@ -1496,13 +1487,12 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi initRoQ(); - FS_Read (cin.file, 16, cinTable[currentHandle].iFile); + FS_Read(cin.file, 16, cinTable[currentHandle].iFile); - RoQID = (unsigned short)(cin.file[0]) + (unsigned short)(cin.file[1])*256; - if (RoQID == 0x1084) - { + RoQID = (unsigned short)(cin.file[0]) + (unsigned short)(cin.file[1]) * 256; + if (RoQID == 0x1084) { RoQ_init(); -// FS_Read (cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile); + // FS_Read (cin.file, cinTable[currentHandle].RoQFrameSize+8, cinTable[currentHandle].iFile); cinTable[currentHandle].status = FMV_PLAY; Com_DPrintf("trFMV::play(), playing %s\n", arg); @@ -1513,7 +1503,7 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi Con_Close(); - if ( !cinTable[currentHandle].silent ) + if (!cinTable[currentHandle].silent) s_rawend = s_soundtime; return currentHandle; @@ -1524,8 +1514,9 @@ int CIN_PlayCinematic( const char *arg, int x, int y, int w, int h, int systemBi return -1; } -void CIN_SetExtents (int handle, int x, int y, int w, int h) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; +void CIN_SetExtents(int handle, int x, int y, int w, int h) { + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; cinTable[handle].xpos = x; cinTable[handle].ypos = y; cinTable[handle].width = w; @@ -1534,7 +1525,8 @@ void CIN_SetExtents (int handle, int x, int y, int w, int h) { } void CIN_SetLooping(int handle, qboolean loop) { - if (handle < 0 || handle>= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; cinTable[handle].looping = loop; } @@ -1547,52 +1539,52 @@ Resample cinematic to 256x256 and store in buf2 */ void CIN_ResampleCinematic(int handle, int *buf2) { int ix, iy, *buf3, xm, ym, ll; - byte *buf; + byte *buf; buf = cinTable[handle].buf; - xm = cinTable[handle].CIN_WIDTH/256; - ym = cinTable[handle].CIN_HEIGHT/256; + xm = cinTable[handle].CIN_WIDTH / 256; + ym = cinTable[handle].CIN_HEIGHT / 256; ll = 8; - if (cinTable[handle].CIN_WIDTH==512) { + if (cinTable[handle].CIN_WIDTH == 512) { ll = 9; } - buf3 = (int*)buf; - if (xm==2 && ym==2) { + buf3 = (int *)buf; + if (xm == 2 && ym == 2) { byte *bc2, *bc3; - int ic, iiy; + int ic, iiy; bc2 = (byte *)buf2; bc3 = (byte *)buf3; - for (iy = 0; iy<256; iy++) { - iiy = iy<<12; - for (ix = 0; ix<2048; ix+=8) { - for(ic = ix;ic<(ix+4);ic++) { - *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic]+bc3[iiy+2048+ic]+bc3[iiy+2048+4+ic])>>2; + for (iy = 0; iy < 256; iy++) { + iiy = iy << 12; + for (ix = 0; ix < 2048; ix += 8) { + for (ic = ix; ic < (ix + 4); ic++) { + *bc2 = (bc3[iiy + ic] + bc3[iiy + 4 + ic] + bc3[iiy + 2048 + ic] + bc3[iiy + 2048 + 4 + ic]) >> 2; bc2++; } } } - } else if (xm==2 && ym==1) { + } else if (xm == 2 && ym == 1) { byte *bc2, *bc3; - int ic, iiy; + int ic, iiy; bc2 = (byte *)buf2; bc3 = (byte *)buf3; - for (iy = 0; iy<256; iy++) { - iiy = iy<<11; - for (ix = 0; ix<2048; ix+=8) { - for(ic = ix;ic<(ix+4);ic++) { - *bc2=(bc3[iiy+ic]+bc3[iiy+4+ic])>>1; + for (iy = 0; iy < 256; iy++) { + iiy = iy << 11; + for (ix = 0; ix < 2048; ix += 8) { + for (ic = ix; ic < (ix + 4); ic++) { + *bc2 = (bc3[iiy + ic] + bc3[iiy + 4 + ic]) >> 1; bc2++; } } } } else { - for (iy = 0; iy<256; iy++) { - for (ix = 0; ix<256; ix++) { - buf2[(iy<<8)+ix] = buf3[((iy*ym)<= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) return; + if (handle < 0 || handle >= MAX_VIDEO_HANDLES || cinTable[handle].status == FMV_EOF) + return; if (!cinTable[handle].buf) { return; @@ -1622,17 +1615,17 @@ void CIN_DrawCinematic (int handle) { if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { int *buf2; - buf2 = (int *)Hunk_AllocateTempMemory( 256*256*4 ); + buf2 = (int *)Hunk_AllocateTempMemory(256 * 256 * 4); CIN_ResampleCinematic(handle, buf2); - re->DrawStretchRaw( x, y, w, h, 256, 256, (byte *)buf2, handle, qtrue); + re->DrawStretchRaw(x, y, w, h, 256, 256, (byte *)buf2, handle, qtrue); cinTable[handle].dirty = qfalse; Hunk_FreeTempMemory(buf2); return; } - re->DrawStretchRaw( x, y, w, h, cinTable[handle].drawX, cinTable[handle].drawY, buf, handle, cinTable[handle].dirty); + re->DrawStretchRaw(x, y, w, h, cinTable[handle].drawX, cinTable[handle].drawY, buf, handle, cinTable[handle].dirty); cinTable[handle].dirty = qfalse; } @@ -1646,36 +1639,32 @@ void CL_PlayCinematic_f(void) { const char *s = Cmd_Argv(2); int bits = CIN_system; - if ((s && s[0] == '1') || Q_stricmp(arg,"demoend.roq")==0 || Q_stricmp(arg,"end.roq")==0) { + if ((s && s[0] == '1') || Q_stricmp(arg, "demoend.roq") == 0 || Q_stricmp(arg, "end.roq") == 0) { bits |= CIN_hold; } if (s && s[0] == '2') { bits |= CIN_loop; } - S_StopAllSounds (); + S_StopAllSounds(); - CL_handle = CIN_PlayCinematic( arg, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, bits ); + CL_handle = CIN_PlayCinematic(arg, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, bits); if (CL_handle >= 0) { do { SCR_RunCinematic(); - } while (cinTable[currentHandle].buf == NULL && cinTable[currentHandle].status == FMV_PLAY); // wait for first frame (load codebook and sound) - } - else - { + } while (cinTable[currentHandle].buf == NULL && cinTable[currentHandle].status == FMV_PLAY); // wait for first frame (load codebook and sound) + } else { Com_Printf(S_COLOR_RED "PlayCinematic(): Failed to open \"%s\"\n", arg); } } - -void SCR_DrawCinematic (void) { +void SCR_DrawCinematic(void) { if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) { CIN_DrawCinematic(CL_handle); } } -void SCR_RunCinematic (void) -{ +void SCR_RunCinematic(void) { if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) { CIN_RunCinematic(CL_handle); } @@ -1684,7 +1673,7 @@ void SCR_RunCinematic (void) void SCR_StopCinematic(void) { if (CL_handle >= 0 && CL_handle < MAX_VIDEO_HANDLES) { CIN_StopCinematic(CL_handle); - S_StopAllSounds (); + S_StopAllSounds(); CL_handle = -1; } } @@ -1707,27 +1696,25 @@ void CIN_UploadCinematic(int handle) { } // Resample the video if needed - if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { + if (cinTable[handle].dirty && (cinTable[handle].CIN_WIDTH != cinTable[handle].drawX || cinTable[handle].CIN_HEIGHT != cinTable[handle].drawY)) { int *buf2; - buf2 = (int *)Hunk_AllocateTempMemory( 256*256*4 ); + buf2 = (int *)Hunk_AllocateTempMemory(256 * 256 * 4); CIN_ResampleCinematic(handle, buf2); - re->UploadCinematic( 256, 256, (byte *)buf2, handle, qtrue); + re->UploadCinematic(256, 256, (byte *)buf2, handle, qtrue); cinTable[handle].dirty = qfalse; Hunk_FreeTempMemory(buf2); } else { // Upload video at normal resolution - re->UploadCinematic( cinTable[handle].drawX, cinTable[handle].drawY, - cinTable[handle].buf, handle, cinTable[handle].dirty); + re->UploadCinematic(cinTable[handle].drawX, cinTable[handle].drawY, cinTable[handle].buf, handle, cinTable[handle].dirty); cinTable[handle].dirty = qfalse; } if (cl_inGameVideo->integer == 0 && cinTable[handle].playonwalls == 1) { cinTable[handle].playonwalls--; - } - else if (cl_inGameVideo->integer != 0 && cinTable[handle].playonwalls != 1) { + } else if (cl_inGameVideo->integer != 0 && cinTable[handle].playonwalls != 1) { cinTable[handle].playonwalls = 1; } } diff --git a/codemp/client/cl_console.cpp b/codemp/client/cl_console.cpp index 68968dd941..f7c0902efe 100644 --- a/codemp/client/cl_console.cpp +++ b/codemp/client/cl_console.cpp @@ -29,51 +29,49 @@ along with this program; if not, see . #include "qcommon/stringed_ingame.h" #include "qcommon/game_version.h" - int g_console_field_width = 78; -console_t con; - -cvar_t *con_conspeed; -cvar_t *con_notifytime; -cvar_t *con_opacity; // background alpha multiplier -cvar_t *con_autoclear; -cvar_t *con_height; -cvar_t *con_scale; -cvar_t *con_timestamps; +console_t con; -#define DEFAULT_CONSOLE_WIDTH 78 +cvar_t *con_conspeed; +cvar_t *con_notifytime; +cvar_t *con_opacity; // background alpha multiplier +cvar_t *con_autoclear; +cvar_t *con_height; +cvar_t *con_scale; +cvar_t *con_timestamps; -#define CON_BLANK_CHAR ' ' -#define CON_SCROLL_L_CHAR '$' -#define CON_SCROLL_R_CHAR '$' -#define CON_TIMESTAMP_LEN 11 // "[13:37:00] " -#define CON_MIN_WIDTH 20 +#define DEFAULT_CONSOLE_WIDTH 78 +#define CON_BLANK_CHAR ' ' +#define CON_SCROLL_L_CHAR '$' +#define CON_SCROLL_R_CHAR '$' +#define CON_TIMESTAMP_LEN 11 // "[13:37:00] " +#define CON_MIN_WIDTH 20 -static const conChar_t CON_WRAP = { { ColorIndex(COLOR_GREY), '\\' } }; -static const conChar_t CON_BLANK = { { ColorIndex(COLOR_WHITE), CON_BLANK_CHAR } }; +static const conChar_t CON_WRAP = {{ColorIndex(COLOR_GREY), '\\'}}; +static const conChar_t CON_BLANK = {{ColorIndex(COLOR_WHITE), CON_BLANK_CHAR}}; -vec4_t console_color = {0.509f, 0.609f, 0.847f, 1.0f}; +vec4_t console_color = {0.509f, 0.609f, 0.847f, 1.0f}; /* ================ Con_ToggleConsole_f ================ */ -void Con_ToggleConsole_f (void) { +void Con_ToggleConsole_f(void) { // closing a full screen console restarts the demo loop - if ( cls.state == CA_DISCONNECTED && Key_GetCatcher( ) == KEYCATCH_CONSOLE ) { + if (cls.state == CA_DISCONNECTED && Key_GetCatcher() == KEYCATCH_CONSOLE) { CL_StartDemoLoop(); return; } - if( con_autoclear->integer ) - Field_Clear( &g_consoleField ); + if (con_autoclear->integer) + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - Con_ClearNotify (); - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_CONSOLE ); + Con_ClearNotify(); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_CONSOLE); } /* @@ -81,9 +79,9 @@ void Con_ToggleConsole_f (void) { Con_ToggleMenu_f =================== */ -void Con_ToggleMenu_f( void ) { - CL_KeyEvent( A_ESCAPE, qtrue, Sys_Milliseconds() ); - CL_KeyEvent( A_ESCAPE, qfalse, Sys_Milliseconds() ); +void Con_ToggleMenu_f(void) { + CL_KeyEvent(A_ESCAPE, qtrue, Sys_Milliseconds()); + CL_KeyEvent(A_ESCAPE, qfalse, Sys_Milliseconds()); } /* @@ -91,13 +89,13 @@ void Con_ToggleMenu_f( void ) { Con_MessageMode_f ================ */ -void Con_MessageMode_f (void) { //yell +void Con_MessageMode_f(void) { // yell chat_playerNum = -1; chat_team = qfalse; - Field_Clear( &chatField ); + Field_Clear(&chatField); chatField.widthInChars = 30; - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE ); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_MESSAGE); } /* @@ -105,12 +103,12 @@ void Con_MessageMode_f (void) { //yell Con_MessageMode2_f ================ */ -void Con_MessageMode2_f (void) { //team chat +void Con_MessageMode2_f(void) { // team chat chat_playerNum = -1; chat_team = qtrue; - Field_Clear( &chatField ); + Field_Clear(&chatField); chatField.widthInChars = 25; - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE ); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_MESSAGE); } /* @@ -118,23 +116,21 @@ void Con_MessageMode2_f (void) { //team chat Con_MessageMode3_f ================ */ -void Con_MessageMode3_f (void) -{ //target chat - if (!cls.cgameStarted) - { +void Con_MessageMode3_f(void) { // target chat + if (!cls.cgameStarted) { assert(!"null cgvm"); return; } chat_playerNum = CGVM_CrosshairPlayer(); - if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) { + if (chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS) { chat_playerNum = -1; return; } chat_team = qfalse; - Field_Clear( &chatField ); + Field_Clear(&chatField); chatField.widthInChars = 30; - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE ); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_MESSAGE); } /* @@ -142,23 +138,21 @@ void Con_MessageMode3_f (void) Con_MessageMode4_f ================ */ -void Con_MessageMode4_f (void) -{ //attacker - if (!cls.cgameStarted) - { +void Con_MessageMode4_f(void) { // attacker + if (!cls.cgameStarted) { assert(!"null cgvm"); return; } chat_playerNum = CGVM_LastAttacker(); - if ( chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS ) { + if (chat_playerNum < 0 || chat_playerNum >= MAX_CLIENTS) { chat_playerNum = -1; return; } chat_team = qfalse; - Field_Clear( &chatField ); + Field_Clear(&chatField); chatField.widthInChars = 30; - Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE ); + Key_SetCatcher(Key_GetCatcher() ^ KEYCATCH_MESSAGE); } /* @@ -166,17 +160,16 @@ void Con_MessageMode4_f (void) Con_Clear_f ================ */ -void Con_Clear_f (void) { - int i; +void Con_Clear_f(void) { + int i; - for ( i = 0 ; i < CON_TEXTSIZE ; i++ ) { + for (i = 0; i < CON_TEXTSIZE; i++) { con.text[i] = CON_BLANK; } - Con_Bottom(); // go to end + Con_Bottom(); // go to end } - /* ================ Con_Dump_f @@ -184,56 +177,50 @@ Con_Dump_f Save the console contents out to a file ================ */ -void Con_Dump_f (void) -{ - char filename[MAX_QPATH]; - qboolean empty; - int l, i, j; - int line; - int lineLen; - fileHandle_t f; +void Con_Dump_f(void) { + char filename[MAX_QPATH]; + qboolean empty; + int l, i, j; + int line; + int lineLen; + fileHandle_t f; #ifdef WIN32 - char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 2]; + char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 2]; #else - char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 1]; + char buffer[CON_TIMESTAMP_LEN + MAXPRINTMSG + 1]; #endif - if (Cmd_Argc() != 2) - { - Com_Printf ("%s\n", SE_GetString("CON_TEXT_DUMP_USAGE")); + if (Cmd_Argc() != 2) { + Com_Printf("%s\n", SE_GetString("CON_TEXT_DUMP_USAGE")); return; } - Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".txt"); - if(!COM_CompareExtension(filename, ".txt")) - { - Com_Printf( "Con_Dump_f: Only the \".txt\" extension is supported by this command!\n" ); + if (!COM_CompareExtension(filename, ".txt")) { + Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } - f = FS_FOpenFileWrite( filename ); - if (!f) - { - Com_Printf ("ERROR: couldn't open %s.\n", filename); + f = FS_FOpenFileWrite(filename); + if (!f) { + Com_Printf("ERROR: couldn't open %s.\n", filename); return; } - Com_Printf ("Dumped console text to %s.\n", filename ); + Com_Printf("Dumped console text to %s.\n", filename); // skip empty lines - for (l = 1, empty = qtrue ; l < con.totallines && empty ; l++) - { + for (l = 1, empty = qtrue; l < con.totallines && empty; l++) { line = ((con.current + l) % con.totallines) * con.rowwidth; - for (j = CON_TIMESTAMP_LEN ; j < con.rowwidth - 1 ; j++) + for (j = CON_TIMESTAMP_LEN; j < con.rowwidth - 1; j++) if (con.text[line + j].f.character != CON_BLANK_CHAR) empty = qfalse; } - for ( ; l < con.totallines ; l++) - { + for (; l < con.totallines; l++) { lineLen = 0; i = 0; @@ -248,8 +235,7 @@ void Con_Dump_f (void) } // Concatenate wrapped lines - for ( ; l < con.totallines ; l++) - { + for (; l < con.totallines; l++) { line = ((con.current + l) % con.totallines) * con.rowwidth; for (j = CON_TIMESTAMP_LEN; j < con.rowwidth - 1 && i < (int)sizeof(buffer) - 1; j++, i++) { @@ -268,7 +254,7 @@ void Con_Dump_f (void) #ifdef WIN32 // I really don't like this inconsistency, but OpenJK has been doing this since April 2013 buffer[lineLen] = '\r'; - buffer[lineLen+1] = '\n'; + buffer[lineLen + 1] = '\n'; FS_Write(buffer, lineLen + 2, f); #else buffer[lineLen] = '\n'; @@ -276,19 +262,18 @@ void Con_Dump_f (void) #endif } - FS_FCloseFile( f ); + FS_FCloseFile(f); } - /* ================ Con_ClearNotify ================ */ -void Con_ClearNotify( void ) { - int i; +void Con_ClearNotify(void) { + int i; - for ( i = 0 ; i < NUM_CON_TIMES ; i++ ) { + for (i = 0; i < NUM_CON_TIMES; i++) { con.times[i] = 0; } } @@ -300,9 +285,8 @@ Con_Initialize Initialize console for the first time. ================ */ -void Con_Initialize(void) -{ - int i; +void Con_Initialize(void) { + int i; VectorCopy4(colorWhite, con.color); con.charWidth = SMALLCHAR_WIDTH; @@ -314,16 +298,13 @@ void Con_Initialize(void) con.display = con.current; con.xadjust = 1.0f; con.yadjust = 1.0f; - for(i=0; i= SMALLCHAR_WIDTH); @@ -463,21 +440,19 @@ void Con_CheckResize (void) con.yadjust = ((float)SCREEN_HEIGHT) / cls.glconfig.vidHeight; g_consoleField.widthInChars = width - 1; // Command prompt - if (con.rowwidth != rowwidth) - { + if (con.rowwidth != rowwidth) { Con_Resize(rowwidth); } } - /* ================== Cmd_CompleteTxtName ================== */ -void Cmd_CompleteTxtName( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "", "txt", qfalse, qtrue ); +void Cmd_CompleteTxtName(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("", "txt", qfalse, qtrue); } /* @@ -485,38 +460,38 @@ void Cmd_CompleteTxtName( char *args, int argNum ) { Con_Init ================ */ -void Con_Init (void) { - int i; +void Con_Init(void) { + int i; - con_notifytime = Cvar_Get ("con_notifytime", "3", 0, "How many seconds notify messages should be shown before they fade away"); - con_conspeed = Cvar_Get ("scr_conspeed", "3", 0, "Console open/close speed"); - Cvar_CheckRange (con_conspeed, 1.0f, 100.0f, qfalse); + con_notifytime = Cvar_Get("con_notifytime", "3", 0, "How many seconds notify messages should be shown before they fade away"); + con_conspeed = Cvar_Get("scr_conspeed", "3", 0, "Console open/close speed"); + Cvar_CheckRange(con_conspeed, 1.0f, 100.0f, qfalse); - con_opacity = Cvar_Get ("con_opacity", "1.0", CVAR_ARCHIVE_ND, "Opacity of console background"); - con_autoclear = Cvar_Get ("con_autoclear", "1", CVAR_ARCHIVE_ND, "Automatically clear console input on close"); - con_height = Cvar_Get ("con_height", "0.5", CVAR_ARCHIVE_ND); + con_opacity = Cvar_Get("con_opacity", "1.0", CVAR_ARCHIVE_ND, "Opacity of console background"); + con_autoclear = Cvar_Get("con_autoclear", "1", CVAR_ARCHIVE_ND, "Automatically clear console input on close"); + con_height = Cvar_Get("con_height", "0.5", CVAR_ARCHIVE_ND); - con_scale = Cvar_Get ("con_scale", "1", CVAR_ARCHIVE_ND, "Scale console font"); - con_timestamps = Cvar_Get ("con_timestamps", "0", CVAR_ARCHIVE_ND, "Display timestamps infront of console lines"); + con_scale = Cvar_Get("con_scale", "1", CVAR_ARCHIVE_ND, "Scale console font"); + con_timestamps = Cvar_Get("con_timestamps", "0", CVAR_ARCHIVE_ND, "Display timestamps infront of console lines"); - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - for ( i = 0 ; i < COMMAND_HISTORY ; i++ ) { - Field_Clear( &historyEditLines[i] ); + for (i = 0; i < COMMAND_HISTORY; i++) { + Field_Clear(&historyEditLines[i]); historyEditLines[i].widthInChars = g_console_field_width; } - Cmd_AddCommand( "toggleconsole", Con_ToggleConsole_f, "Show/hide console" ); - Cmd_AddCommand( "togglemenu", Con_ToggleMenu_f, "Show/hide the menu" ); - Cmd_AddCommand( "messagemode", Con_MessageMode_f, "Global Chat" ); - Cmd_AddCommand( "messagemode2", Con_MessageMode2_f, "Team Chat" ); - Cmd_AddCommand( "messagemode3", Con_MessageMode3_f, "Private Chat with Target Player" ); - Cmd_AddCommand( "messagemode4", Con_MessageMode4_f, "Private Chat with Last Attacker" ); - Cmd_AddCommand( "clear", Con_Clear_f, "Clear console text" ); - Cmd_AddCommand( "condump", Con_Dump_f, "Dump console text to file" ); - Cmd_SetCommandCompletionFunc( "condump", Cmd_CompleteTxtName ); - - //Initialize values on first print + Cmd_AddCommand("toggleconsole", Con_ToggleConsole_f, "Show/hide console"); + Cmd_AddCommand("togglemenu", Con_ToggleMenu_f, "Show/hide the menu"); + Cmd_AddCommand("messagemode", Con_MessageMode_f, "Global Chat"); + Cmd_AddCommand("messagemode2", Con_MessageMode2_f, "Team Chat"); + Cmd_AddCommand("messagemode3", Con_MessageMode3_f, "Private Chat with Target Player"); + Cmd_AddCommand("messagemode4", Con_MessageMode4_f, "Private Chat with Last Attacker"); + Cmd_AddCommand("clear", Con_Clear_f, "Clear console text"); + Cmd_AddCommand("condump", Con_Dump_f, "Dump console text to file"); + Cmd_SetCommandCompletionFunc("condump", Cmd_CompleteTxtName); + + // Initialize values on first print con.initialized = qfalse; } @@ -525,8 +500,7 @@ void Con_Init (void) { Con_Shutdown ================ */ -void Con_Shutdown(void) -{ +void Con_Shutdown(void) { Cmd_RemoveCommand("toggleconsole"); Cmd_RemoveCommand("togglemenu"); Cmd_RemoveCommand("messagemode"); @@ -542,23 +516,21 @@ void Con_Shutdown(void) Con_Linefeed =============== */ -static void Con_Linefeed (qboolean skipnotify) -{ - int i; - int line = (con.current % con.totallines) * con.rowwidth; +static void Con_Linefeed(qboolean skipnotify) { + int i; + int line = (con.current % con.totallines) * con.rowwidth; // print timestamp on the PREVIOUS line { - time_t t = time( NULL ); - struct tm *tms = localtime( &t ); - char timestamp[CON_TIMESTAMP_LEN + 1]; + time_t t = time(NULL); + struct tm *tms = localtime(&t); + char timestamp[CON_TIMESTAMP_LEN + 1]; const unsigned char color = ColorIndex(COLOR_GREY); - Com_sprintf(timestamp, sizeof(timestamp), "[%02d:%02d:%02d] ", - tms->tm_hour, tms->tm_min, tms->tm_sec); + Com_sprintf(timestamp, sizeof(timestamp), "[%02d:%02d:%02d] ", tms->tm_hour, tms->tm_min, tms->tm_sec); - for ( i = 0; i < CON_TIMESTAMP_LEN; i++ ) { - con.text[line + i].f = { color, timestamp[i] }; + for (i = 0; i < CON_TIMESTAMP_LEN; i++) { + con.text[line + i].f = {color, timestamp[i]}; } } @@ -574,7 +546,7 @@ static void Con_Linefeed (qboolean skipnotify) line = (con.current % con.totallines) * con.rowwidth; - for ( i = 0; i < con.rowwidth; i++ ) + for (i = 0; i < con.rowwidth; i++) con.text[line + i] = CON_BLANK; } @@ -587,26 +559,26 @@ All console printing must go through this in order to be logged to disk If no console is visible, the text will appear at the top of the game window ================ */ -void CL_ConsolePrint( const char *txt) { - int y; - char c; - unsigned char color; - qboolean skipnotify = qfalse; // NERVE - SMF - int prev; // NERVE - SMF +void CL_ConsolePrint(const char *txt) { + int y; + char c; + unsigned char color; + qboolean skipnotify = qfalse; // NERVE - SMF + int prev; // NERVE - SMF // TTimo - prefix for text that shows up in console but not in notify // backported from RTCW - if ( !Q_strncmp( txt, "[skipnotify]", 12 ) ) { + if (!Q_strncmp(txt, "[skipnotify]", 12)) { skipnotify = qtrue; txt += 12; } - if ( txt[0] == '*' ) { + if (txt[0] == '*') { skipnotify = qtrue; txt += 1; } // for some demos we don't want to ever show anything on the console - if ( cl_noprint && cl_noprint->integer ) { + if (cl_noprint && cl_noprint->integer) { return; } @@ -616,57 +588,52 @@ void CL_ConsolePrint( const char *txt) { color = ColorIndex(COLOR_WHITE); - while ( (c = (unsigned char) *txt) != 0 ) { - if ( Q_IsColorString( (unsigned char*) txt ) ) { - color = ColorIndex( *(txt+1) ); + while ((c = (unsigned char)*txt) != 0) { + if (Q_IsColorString((unsigned char *)txt)) { + color = ColorIndex(*(txt + 1)); txt += 2; continue; } txt++; - switch (c) - { + switch (c) { case '\n': - Con_Linefeed (skipnotify); + Con_Linefeed(skipnotify); break; case '\r': con.x = 0; break; - default: // display character and advance + default: // display character and advance y = con.current % con.totallines; if (con.x == con.rowwidth - CON_TIMESTAMP_LEN - 1) { con.text[y * con.rowwidth + CON_TIMESTAMP_LEN + con.x] = CON_WRAP; - Con_Linefeed( skipnotify ); + Con_Linefeed(skipnotify); y = con.current % con.totallines; } - con.text[y * con.rowwidth + CON_TIMESTAMP_LEN + con.x].f = { color, c }; + con.text[y * con.rowwidth + CON_TIMESTAMP_LEN + con.x].f = {color, c}; con.x++; break; } } - // mark time for transparent overlay - if (con.current >= 0 ) - { + if (con.current >= 0) { // NERVE - SMF - if ( skipnotify ) { + if (skipnotify) { prev = con.current % NUM_CON_TIMES - 1; - if ( prev < 0 ) + if (prev < 0) prev = NUM_CON_TIMES - 1; con.times[prev] = 0; - } - else - // -NERVE - SMF + } else + // -NERVE - SMF con.times[con.current % NUM_CON_TIMES] = cls.realtime; } } - /* ============================================================================== @@ -675,7 +642,6 @@ DRAWING ============================================================================== */ - /* ================ Con_DrawInput @@ -683,35 +649,32 @@ Con_DrawInput Draw the editline after a ] prompt ================ */ -void Con_DrawInput (void) { - int y; +void Con_DrawInput(void) { + int y; - if ( cls.state != CA_DISCONNECTED && !(Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) { + if (cls.state != CA_DISCONNECTED && !(Key_GetCatcher() & KEYCATCH_CONSOLE)) { return; } - y = con.vislines - ( con.charHeight * (re->Language_IsAsian() ? 1.5 : 2) ); + y = con.vislines - (con.charHeight * (re->Language_IsAsian() ? 1.5 : 2)); - re->SetColor( con.color ); + re->SetColor(con.color); - Field_Draw( &g_consoleField, 2 * con.charWidth, y, qtrue, qtrue ); + Field_Draw(&g_consoleField, 2 * con.charWidth, y, qtrue, qtrue); - SCR_DrawSmallChar( con.charWidth, y, CONSOLE_PROMPT_CHAR ); + SCR_DrawSmallChar(con.charWidth, y, CONSOLE_PROMPT_CHAR); - re->SetColor( g_color_table[ColorIndex(COLOR_GREY)] ); + re->SetColor(g_color_table[ColorIndex(COLOR_GREY)]); - if ( g_consoleField.scroll > 0 ) - SCR_DrawSmallChar( 0, y, CON_SCROLL_L_CHAR ); + if (g_consoleField.scroll > 0) + SCR_DrawSmallChar(0, y, CON_SCROLL_L_CHAR); - int len = Q_PrintStrlen( g_consoleField.buffer ); - int pos = Q_PrintStrLenTo( g_consoleField.buffer, g_consoleField.scroll, NULL ); - if ( pos + g_consoleField.widthInChars < len ) - SCR_DrawSmallChar( cls.glconfig.vidWidth - con.charWidth, y, CON_SCROLL_R_CHAR ); + int len = Q_PrintStrlen(g_consoleField.buffer); + int pos = Q_PrintStrLenTo(g_consoleField.buffer, g_consoleField.scroll, NULL); + if (pos + g_consoleField.widthInChars < len) + SCR_DrawSmallChar(cls.glconfig.vidWidth - con.charWidth, y, CON_SCROLL_R_CHAR); } - - - /* ================ Con_DrawNotify @@ -719,129 +682,113 @@ Con_DrawNotify Draws the last few lines of output transparently over the game top ================ */ -void Con_DrawNotify (void) -{ - int x, v; - conChar_t *text; - int i; - int time; - int skip; - int currentColor; - const char* chattext; +void Con_DrawNotify(void) { + int x, v; + conChar_t *text; + int i; + int time; + int skip; + int currentColor; + const char *chattext; currentColor = 7; - re->SetColor( g_color_table[currentColor] ); + re->SetColor(g_color_table[currentColor]); int iFontIndex = cls.consoleFont; float fFontScale = 1.0f; int iPixelHeightToAdvance = 0; - if (re->Language_IsAsian()) - { - fFontScale = con.charWidth * 10.0f / - re->Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); + if (re->Language_IsAsian()) { + fFontScale = con.charWidth * 10.0f / re->Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); fFontScale *= con.yadjust; - iPixelHeightToAdvance = 2+(1.3/con.yadjust) * re->Font_HeightPixels(iFontIndex, fFontScale); + iPixelHeightToAdvance = 2 + (1.3 / con.yadjust) * re->Font_HeightPixels(iFontIndex, fFontScale); } v = 0; - for (i= con.current-NUM_CON_TIMES+1 ; i<=con.current ; i++) - { + for (i = con.current - NUM_CON_TIMES + 1; i <= con.current; i++) { if (i < 0) continue; time = con.times[i % NUM_CON_TIMES]; if (time == 0) continue; time = cls.realtime - time; - if (time > con_notifytime->value*1000) + if (time > con_notifytime->value * 1000) continue; - text = con.text + (i % con.totallines)*con.rowwidth; + text = con.text + (i % con.totallines) * con.rowwidth; if (!con_timestamps->integer) text += CON_TIMESTAMP_LEN; - if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) { + if (cl.snap.ps.pm_type != PM_INTERMISSION && Key_GetCatcher() & (KEYCATCH_UI | KEYCATCH_CGAME)) { continue; } - - if (!cl_conXOffset) - { - cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); + if (!cl_conXOffset) { + cl_conXOffset = Cvar_Get("cl_conXOffset", "0", 0); } // asian language needs to use the new font system to print glyphs... // // (ignore colours since we're going to print the whole thing as one string) // - if (re->Language_IsAsian()) - { + if (re->Language_IsAsian()) { // concat the text to be printed... // - char sTemp[4096]; // ott + char sTemp[4096]; // ott sTemp[0] = '\0'; - for (x = 0 ; x < con.linewidth ; x++) - { - if ( text[x].f.color != currentColor ) { + for (x = 0; x < con.linewidth; x++) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - strcat(sTemp,va("^%i", currentColor )); + strcat(sTemp, va("^%i", currentColor)); } - strcat(sTemp,va("%c",text[x].f.character)); + strcat(sTemp, va("%c", text[x].f.character)); } // // and print... // - re->Font_DrawString(cl_conXOffset->integer + con.xadjust * (con.xadjust + con.charWidth), con.yadjust * v, sTemp, - g_color_table[currentColor], iFontIndex, -1, fFontScale); + re->Font_DrawString(cl_conXOffset->integer + con.xadjust * (con.xadjust + con.charWidth), con.yadjust * v, sTemp, g_color_table[currentColor], + iFontIndex, -1, fFontScale); - v += iPixelHeightToAdvance; - } - else - { - for (x = 0 ; x < con.linewidth ; x++) { - if ( text[x].f.character == ' ' ) { + v += iPixelHeightToAdvance; + } else { + for (x = 0; x < con.linewidth; x++) { + if (text[x].f.character == ' ') { continue; } - if ( text[x].f.color != currentColor ) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - re->SetColor( g_color_table[currentColor] ); + re->SetColor(g_color_table[currentColor]); } - if (!cl_conXOffset) - { - cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); + if (!cl_conXOffset) { + cl_conXOffset = Cvar_Get("cl_conXOffset", "0", 0); } - SCR_DrawSmallChar( (int)(cl_conXOffset->integer + (x+1)*con.charWidth), v, text[x].f.character ); + SCR_DrawSmallChar((int)(cl_conXOffset->integer + (x + 1) * con.charWidth), v, text[x].f.character); } v += con.charHeight; } } - re->SetColor( NULL ); + re->SetColor(NULL); - if (Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME) ) { + if (Key_GetCatcher() & (KEYCATCH_UI | KEYCATCH_CGAME)) { return; } // draw the chat line - if ( Key_GetCatcher( ) & KEYCATCH_MESSAGE ) - { - if (chat_team) - { + if (Key_GetCatcher() & KEYCATCH_MESSAGE) { + if (chat_team) { chattext = SE_GetString("MP_SVGAME", "SAY_TEAM"); - SCR_DrawBigString (8, v, chattext, 1.0f, qfalse ); - skip = strlen(chattext)+1; - } - else - { + SCR_DrawBigString(8, v, chattext, 1.0f, qfalse); + skip = strlen(chattext) + 1; + } else { chattext = SE_GetString("MP_SVGAME", "SAY"); - SCR_DrawBigString (8, v, chattext, 1.0f, qfalse ); - skip = strlen(chattext)+1; + SCR_DrawBigString(8, v, chattext, 1.0f, qfalse); + skip = strlen(chattext) + 1; } - Field_BigDraw( &chatField, skip * BIGCHAR_WIDTH, v, qtrue, qtrue ); + Field_BigDraw(&chatField, skip * BIGCHAR_WIDTH, v, qtrue, qtrue); v += BIGCHAR_HEIGHT; } - } /* @@ -851,96 +798,87 @@ Con_DrawSolidConsole Draws the console with the solid background ================ */ -void Con_DrawSolidConsole( float frac ) { - int i, x, y; - int rows; - conChar_t *text; - int row; - int lines; -// qhandle_t conShader; - int currentColor; - - lines = (int) (cls.glconfig.vidHeight * frac); +void Con_DrawSolidConsole(float frac) { + int i, x, y; + int rows; + conChar_t *text; + int row; + int lines; + // qhandle_t conShader; + int currentColor; + + lines = (int)(cls.glconfig.vidHeight * frac); if (lines <= 0) return; - if (lines > cls.glconfig.vidHeight ) + if (lines > cls.glconfig.vidHeight) lines = cls.glconfig.vidHeight; // draw the background - y = (int) (frac * SCREEN_HEIGHT - 2); - if ( y < 1 ) { + y = (int)(frac * SCREEN_HEIGHT - 2); + if (y < 1) { y = 0; - } - else { + } else { // draw the background at full opacity only if fullscreen - if (frac < 1.0f) - { + if (frac < 1.0f) { vec4_t con_color; MAKERGBA(con_color, 1.0f, 1.0f, 1.0f, Com_Clamp(0.0f, 1.0f, con_opacity->value)); re->SetColor(con_color); - } - else - { + } else { re->SetColor(NULL); } - SCR_DrawPic( 0, 0, SCREEN_WIDTH, (float) y, cls.consoleShader ); + SCR_DrawPic(0, 0, SCREEN_WIDTH, (float)y, cls.consoleShader); } // draw the bottom bar and version number - re->SetColor( console_color ); - re->DrawStretchPic( 0, y, SCREEN_WIDTH, 2, 0, 0, 0, 0, cls.whiteShader ); + re->SetColor(console_color); + re->DrawStretchPic(0, y, SCREEN_WIDTH, 2, 0, 0, 0, 0, cls.whiteShader); - i = strlen( JK_VERSION ); + i = strlen(JK_VERSION); - for (x=0 ; xSetColor( console_color ); - for (x=0 ; xSetColor(console_color); + for (x = 0; x < con.linewidth; x += 4) + SCR_DrawSmallChar((x + 1) * con.charWidth, y, '^'); y -= con.charHeight; rows--; } row = con.display; - if ( con.x == 0 ) { + if (con.x == 0) { row--; } currentColor = 7; - re->SetColor( g_color_table[currentColor] ); + re->SetColor(g_color_table[currentColor]); int iFontIndex = cls.consoleFont; float fFontScale = 1.0f; int iPixelHeightToAdvance = con.charHeight; - if (re->Language_IsAsian()) - { - fFontScale = con.charWidth * 10.0f / - re->Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); + if (re->Language_IsAsian()) { + fFontScale = con.charWidth * 10.0f / re->Font_StrLenPixels("aaaaaaaaaa", iFontIndex, 1.0f); fFontScale *= con.yadjust; - iPixelHeightToAdvance = 2+(1.3/con.yadjust) * re->Font_HeightPixels(iFontIndex, fFontScale); + iPixelHeightToAdvance = 2 + (1.3 / con.yadjust) * re->Font_HeightPixels(iFontIndex, fFontScale); } - for (i=0 ; i= con.totallines) { @@ -948,7 +886,7 @@ void Con_DrawSolidConsole( float frac ) { continue; } - text = con.text + (row % con.totallines)*con.rowwidth; + text = con.text + (row % con.totallines) * con.rowwidth; if (!con_timestamps->integer) text += CON_TIMESTAMP_LEN; @@ -956,70 +894,63 @@ void Con_DrawSolidConsole( float frac ) { // // (ignore colours since we're going to print the whole thing as one string) // - if (re->Language_IsAsian()) - { + if (re->Language_IsAsian()) { // concat the text to be printed... // - char sTemp[4096]; // ott + char sTemp[4096]; // ott sTemp[0] = '\0'; - for (x = 0 ; x < con.linewidth + 1 ; x++) - { - if ( text[x].f.color != currentColor ) { + for (x = 0; x < con.linewidth + 1; x++) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - strcat(sTemp,va("^%i", currentColor )); + strcat(sTemp, va("^%i", currentColor)); } - strcat(sTemp,va("%c",text[x].f.character)); + strcat(sTemp, va("%c", text[x].f.character)); } // // and print... // - re->Font_DrawString(con.xadjust*(con.xadjust + con.charWidth), con.yadjust * y, sTemp, g_color_table[currentColor], - iFontIndex, -1, fFontScale); - } - else - { - for (x = 0; x < con.linewidth + 1 ; x++) { - if ( text[x].f.character == ' ' ) { + re->Font_DrawString(con.xadjust * (con.xadjust + con.charWidth), con.yadjust * y, sTemp, g_color_table[currentColor], iFontIndex, -1, fFontScale); + } else { + for (x = 0; x < con.linewidth + 1; x++) { + if (text[x].f.character == ' ') { continue; } - if ( text[x].f.color != currentColor ) { + if (text[x].f.color != currentColor) { currentColor = text[x].f.color; - re->SetColor( g_color_table[currentColor] ); + re->SetColor(g_color_table[currentColor]); } - SCR_DrawSmallChar( (x+1)*con.charWidth, y, text[x].f.character ); + SCR_DrawSmallChar((x + 1) * con.charWidth, y, text[x].f.character); } } } - re->SetColor( NULL ); + re->SetColor(NULL); } - - /* ================== Con_DrawConsole ================== */ -void Con_DrawConsole( void ) { +void Con_DrawConsole(void) { // check for console width changes from a vid mode change - Con_CheckResize (); + Con_CheckResize(); // if disconnected, render console full screen - if ( cls.state == CA_DISCONNECTED ) { - if ( !( Key_GetCatcher( ) & (KEYCATCH_UI | KEYCATCH_CGAME)) ) { - Con_DrawSolidConsole( 1.0 ); + if (cls.state == CA_DISCONNECTED) { + if (!(Key_GetCatcher() & (KEYCATCH_UI | KEYCATCH_CGAME))) { + Con_DrawSolidConsole(1.0); return; } } - if ( con.displayFrac ) { - Con_DrawSolidConsole( con.displayFrac ); + if (con.displayFrac) { + Con_DrawSolidConsole(con.displayFrac); } else { // draw notify lines - if ( cls.state == CA_ACTIVE ) { - Con_DrawNotify (); + if (cls.state == CA_ACTIVE) { + Con_DrawNotify(); } } } @@ -1033,64 +964,56 @@ Con_RunConsole Scroll it up or down ================== */ -void Con_RunConsole (void) { +void Con_RunConsole(void) { // decide on the destination height of the console - if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) + if (Key_GetCatcher() & KEYCATCH_CONSOLE) con.finalFrac = con_height->value; else - con.finalFrac = 0; // none visible + con.finalFrac = 0; // none visible // scroll towards the destination height - if (con.finalFrac < con.displayFrac) - { - con.displayFrac -= con_conspeed->value*(float)(cls.realFrametime*0.001); + if (con.finalFrac < con.displayFrac) { + con.displayFrac -= con_conspeed->value * (float)(cls.realFrametime * 0.001); if (con.finalFrac > con.displayFrac) con.displayFrac = con.finalFrac; - } - else if (con.finalFrac > con.displayFrac) - { - con.displayFrac += con_conspeed->value*(float)(cls.realFrametime*0.001); + } else if (con.finalFrac > con.displayFrac) { + con.displayFrac += con_conspeed->value * (float)(cls.realFrametime * 0.001); if (con.finalFrac < con.displayFrac) con.displayFrac = con.finalFrac; } - } - -void Con_PageUp( void ) { +void Con_PageUp(void) { con.display -= 2; - if ( con.current - con.display >= con.totallines ) { + if (con.current - con.display >= con.totallines) { con.display = con.current - con.totallines + 1; } } -void Con_PageDown( void ) { +void Con_PageDown(void) { con.display += 2; if (con.display > con.current) { con.display = con.current; } } -void Con_Top( void ) { +void Con_Top(void) { con.display = con.totallines; - if ( con.current - con.display >= con.totallines ) { + if (con.current - con.display >= con.totallines) { con.display = con.current - con.totallines + 1; } } -void Con_Bottom( void ) { - con.display = con.current; -} - +void Con_Bottom(void) { con.display = con.current; } -void Con_Close( void ) { - if ( !com_cl_running->integer ) { +void Con_Close(void) { + if (!com_cl_running->integer) { return; } - Field_Clear( &g_consoleField ); - Con_ClearNotify (); - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CONSOLE ); - con.finalFrac = 0; // none visible + Field_Clear(&g_consoleField); + Con_ClearNotify(); + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_CONSOLE); + con.finalFrac = 0; // none visible con.displayFrac = 0; } diff --git a/codemp/client/cl_input.cpp b/codemp/client/cl_input.cpp index fbbf624281..26e70a92a3 100644 --- a/codemp/client/cl_input.cpp +++ b/codemp/client/cl_input.cpp @@ -29,8 +29,8 @@ along with this program; if not, see . #ifndef _WIN32 #include #endif -unsigned frame_msec; -int old_com_frameTime; +unsigned frame_msec; +int old_com_frameTime; float cl_mPitchOverride = 0.0f; float cl_mYawOverride = 0.0f; @@ -39,10 +39,10 @@ qboolean cl_bUseFighterPitch = qfalse; qboolean cl_crazyShipControls = qfalse; #ifdef VEH_CONTROL_SCHEME_4 -#define OVERRIDE_MOUSE_SENSITIVITY 5.0f//20.0f = 180 degree turn in one mouse swipe across keyboard -#else// VEH_CONTROL_SCHEME_4 -#define OVERRIDE_MOUSE_SENSITIVITY 10.0f//20.0f = 180 degree turn in one mouse swipe across keyboard -#endif// VEH_CONTROL_SCHEME_4 +#define OVERRIDE_MOUSE_SENSITIVITY 5.0f // 20.0f = 180 degree turn in one mouse swipe across keyboard +#else // VEH_CONTROL_SCHEME_4 +#define OVERRIDE_MOUSE_SENSITIVITY 10.0f // 20.0f = 180 degree turn in one mouse swipe across keyboard +#endif // VEH_CONTROL_SCHEME_4 /* =============================================================================== @@ -63,18 +63,16 @@ at the same time. =============================================================================== */ - -kbutton_t in_left, in_right, in_forward, in_back; -kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; -kbutton_t in_strafe, in_speed; -kbutton_t in_up, in_down; +kbutton_t in_left, in_right, in_forward, in_back; +kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; +kbutton_t in_strafe, in_speed; +kbutton_t in_up, in_down; #define MAX_KBUTTONS 16 -kbutton_t in_buttons[MAX_KBUTTONS]; - +kbutton_t in_buttons[MAX_KBUTTONS]; -qboolean in_mlooking; +qboolean in_mlooking; void IN_Button11Down(void); void IN_Button11Up(void); @@ -82,19 +80,18 @@ void IN_Button10Down(void); void IN_Button10Up(void); void IN_Button6Down(void); void IN_Button6Up(void); -void IN_UseGivenForce(void) -{ +void IN_UseGivenForce(void) { char *c = Cmd_Argv(1); - int forceNum =-1; + int forceNum = -1; int genCmdNum = 0; - if(c) { + if (c) { forceNum = atoi(c); } else { return; } - switch(forceNum) { + switch (forceNum) { case FP_DRAIN: IN_Button11Down(); IN_Button11Up(); @@ -145,226 +142,187 @@ void IN_UseGivenForce(void) break; } - if(genCmdNum != 0) { + if (genCmdNum != 0) { cl.gcmdSendValue = qtrue; cl.gcmdValue = genCmdNum; } } -void IN_MLookDown( void ) { - in_mlooking = qtrue; -} +void IN_MLookDown(void) { in_mlooking = qtrue; } -void IN_CenterView( void ); -void IN_MLookUp( void ) { +void IN_CenterView(void); +void IN_MLookUp(void) { in_mlooking = qfalse; - if ( !cl_freelook->integer ) { - IN_CenterView (); + if (!cl_freelook->integer) { + IN_CenterView(); } } -void IN_GenCMD1( void ) -{ +void IN_GenCMD1(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_SABERSWITCH; } -void IN_GenCMD2( void ) -{ +void IN_GenCMD2(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_ENGAGE_DUEL; } -void IN_GenCMD3( void ) -{ +void IN_GenCMD3(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_HEAL; } -void IN_GenCMD4( void ) -{ +void IN_GenCMD4(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_SPEED; } -void IN_GenCMD5( void ) -{ +void IN_GenCMD5(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_PULL; } -void IN_GenCMD6( void ) -{ +void IN_GenCMD6(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_DISTRACT; } -void IN_GenCMD7( void ) -{ +void IN_GenCMD7(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_RAGE; } -void IN_GenCMD8( void ) -{ +void IN_GenCMD8(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_PROTECT; } -void IN_GenCMD9( void ) -{ +void IN_GenCMD9(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_ABSORB; } -void IN_GenCMD10( void ) -{ +void IN_GenCMD10(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_HEALOTHER; } -void IN_GenCMD11( void ) -{ +void IN_GenCMD11(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_FORCEPOWEROTHER; } -void IN_GenCMD12( void ) -{ +void IN_GenCMD12(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_SEEING; } -void IN_GenCMD13( void ) -{ +void IN_GenCMD13(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_SEEKER; } -void IN_GenCMD14( void ) -{ +void IN_GenCMD14(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_FIELD; } -void IN_GenCMD15( void ) -{ +void IN_GenCMD15(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_BACTA; } -void IN_GenCMD16( void ) -{ +void IN_GenCMD16(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_ELECTROBINOCULARS; } -void IN_GenCMD17( void ) -{ +void IN_GenCMD17(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_ZOOM; } -void IN_GenCMD18( void ) -{ +void IN_GenCMD18(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_SENTRY; } -void IN_GenCMD19( void ) -{ - if (Cvar_VariableIntegerValue("d_saberStanceDebug")) - { +void IN_GenCMD19(void) { + if (Cvar_VariableIntegerValue("d_saberStanceDebug")) { Com_Printf("SABERSTANCEDEBUG: Gencmd on client set successfully.\n"); } cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_SABERATTACKCYCLE; } -void IN_GenCMD20( void ) -{ +void IN_GenCMD20(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FORCE_THROW; } -void IN_GenCMD21( void ) -{ +void IN_GenCMD21(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_JETPACK; } -void IN_GenCMD22( void ) -{ +void IN_GenCMD22(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_BACTABIG; } -void IN_GenCMD23( void ) -{ +void IN_GenCMD23(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_HEALTHDISP; } -void IN_GenCMD24( void ) -{ +void IN_GenCMD24(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_AMMODISP; } -void IN_GenCMD25( void ) -{ +void IN_GenCMD25(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_EWEB; } -void IN_GenCMD26( void ) -{ +void IN_GenCMD26(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_USE_CLOAK; } -void IN_GenCMD27( void ) -{ +void IN_GenCMD27(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_TAUNT; } -void IN_GenCMD28( void ) -{ +void IN_GenCMD28(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_BOW; } -void IN_GenCMD29( void ) -{ +void IN_GenCMD29(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_MEDITATE; } -void IN_GenCMD30( void ) -{ +void IN_GenCMD30(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_FLOURISH; } -void IN_GenCMD31( void ) -{ +void IN_GenCMD31(void) { cl.gcmdSendValue = qtrue; cl.gcmdValue = GENCMD_GLOAT; } - -//toggle automap view mode +// toggle automap view mode static bool g_clAutoMapMode = false; -void IN_AutoMapButton(void) -{ - g_clAutoMapMode = !g_clAutoMapMode; -} +void IN_AutoMapButton(void) { g_clAutoMapMode = !g_clAutoMapMode; } -//toggle between automap, radar, nothing +// toggle between automap, radar, nothing extern cvar_t *r_autoMap; -void IN_AutoMapToggle(void) -{ +void IN_AutoMapToggle(void) { Cvar_User_SetValue("cg_drawRadar", !Cvar_VariableValue("cg_drawRadar")); /* if (r_autoMap && r_autoMap->integer) @@ -383,41 +341,39 @@ void IN_AutoMapToggle(void) */ } -void IN_VoiceChatButton(void) -{ - if (!cls.uiStarted) - { //ui not loaded so this command is useless +void IN_VoiceChatButton(void) { + if (!cls.uiStarted) { // ui not loaded so this command is useless return; } - UIVM_SetActiveMenu( UIMENU_VOICECHAT ); + UIVM_SetActiveMenu(UIMENU_VOICECHAT); } -void IN_KeyDown( kbutton_t *b ) { - int k; - char *c; +void IN_KeyDown(kbutton_t *b) { + int k; + char *c; c = Cmd_Argv(1); - if ( c[0] ) { + if (c[0]) { k = atoi(c); } else { - k = -1; // typed manually at the console for continuous down + k = -1; // typed manually at the console for continuous down } - if ( k == b->down[0] || k == b->down[1] ) { - return; // repeating key + if (k == b->down[0] || k == b->down[1]) { + return; // repeating key } - if ( !b->down[0] ) { + if (!b->down[0]) { b->down[0] = k; - } else if ( !b->down[1] ) { + } else if (!b->down[1]) { b->down[1] = k; } else { - Com_Printf ("Three keys down for a button!\n"); + Com_Printf("Three keys down for a button!\n"); return; } - if ( b->active ) { - return; // still down + if (b->active) { + return; // still down } // save timestamp for partial frame summing @@ -428,13 +384,13 @@ void IN_KeyDown( kbutton_t *b ) { b->wasPressed = qtrue; } -void IN_KeyUp( kbutton_t *b ) { - int k; - char *c; - unsigned uptime; +void IN_KeyUp(kbutton_t *b) { + int k; + char *c; + unsigned uptime; c = Cmd_Argv(1); - if ( c[0] ) { + if (c[0]) { k = atoi(c); } else { // typed manually at the console, assume for unsticking, so clear all @@ -443,15 +399,15 @@ void IN_KeyUp( kbutton_t *b ) { return; } - if ( b->down[0] == k ) { + if (b->down[0] == k) { b->down[0] = 0; - } else if ( b->down[1] == k ) { + } else if (b->down[1] == k) { b->down[1] = 0; } else { - return; // key up without coresponding down (menu pass through) + return; // key up without coresponding down (menu pass through) } - if ( b->down[0] || b->down[1] ) { - return; // some other key is still holding it down + if (b->down[0] || b->down[1]) { + return; // some other key is still holding it down } b->active = qfalse; @@ -459,7 +415,7 @@ void IN_KeyUp( kbutton_t *b ) { // save timestamp for partial frame summing c = Cmd_Argv(2); uptime = atoi(c); - if ( uptime ) { + if (uptime) { b->msec += uptime - b->downtime; } else { b->msec += frame_msec / 2; @@ -468,8 +424,6 @@ void IN_KeyUp( kbutton_t *b ) { b->active = qfalse; } - - /* =============== CL_KeyState @@ -477,16 +431,16 @@ CL_KeyState Returns the fraction of the frame that the key was down =============== */ -float CL_KeyState( kbutton_t *key ) { - float val; - int msec; +float CL_KeyState(kbutton_t *key) { + float val; + int msec; msec = key->msec; key->msec = 0; - if ( key->active ) { + if (key->active) { // still down - if ( !key->downtime ) { + if (!key->downtime) { msec = com_frameTime; } else { msec += com_frameTime - key->downtime; @@ -501,88 +455,68 @@ float CL_KeyState( kbutton_t *key ) { #endif val = (float)msec / frame_msec; - if ( val < 0 ) { + if (val < 0) { val = 0; } - if ( val > 1 ) { + if (val > 1) { val = 1; } return val; } -#define AUTOMAP_KEY_FORWARD 1 -#define AUTOMAP_KEY_BACK 2 -#define AUTOMAP_KEY_YAWLEFT 3 -#define AUTOMAP_KEY_YAWRIGHT 4 -#define AUTOMAP_KEY_PITCHUP 5 -#define AUTOMAP_KEY_PITCHDOWN 6 -#define AUTOMAP_KEY_DEFAULTVIEW 7 -static autoMapInput_t g_clAutoMapInput; -//intercept certain keys during automap mode -static void CL_AutoMapKey(int autoMapKey, qboolean up) -{ +#define AUTOMAP_KEY_FORWARD 1 +#define AUTOMAP_KEY_BACK 2 +#define AUTOMAP_KEY_YAWLEFT 3 +#define AUTOMAP_KEY_YAWRIGHT 4 +#define AUTOMAP_KEY_PITCHUP 5 +#define AUTOMAP_KEY_PITCHDOWN 6 +#define AUTOMAP_KEY_DEFAULTVIEW 7 +static autoMapInput_t g_clAutoMapInput; +// intercept certain keys during automap mode +static void CL_AutoMapKey(int autoMapKey, qboolean up) { autoMapInput_t *data = (autoMapInput_t *)cl.mSharedMemory; - switch (autoMapKey) - { + switch (autoMapKey) { case AUTOMAP_KEY_FORWARD: - if (up) - { + if (up) { g_clAutoMapInput.up = 0.0f; - } - else - { + } else { g_clAutoMapInput.up = 16.0f; } break; case AUTOMAP_KEY_BACK: - if (up) - { + if (up) { g_clAutoMapInput.down = 0.0f; - } - else - { + } else { g_clAutoMapInput.down = 16.0f; } break; case AUTOMAP_KEY_YAWLEFT: - if (up) - { + if (up) { g_clAutoMapInput.yaw = 0.0f; - } - else - { + } else { g_clAutoMapInput.yaw = -4.0f; } break; case AUTOMAP_KEY_YAWRIGHT: - if (up) - { + if (up) { g_clAutoMapInput.yaw = 0.0f; - } - else - { + } else { g_clAutoMapInput.yaw = 4.0f; } break; case AUTOMAP_KEY_PITCHUP: - if (up) - { + if (up) { g_clAutoMapInput.pitch = 0.0f; - } - else - { + } else { g_clAutoMapInput.pitch = -4.0f; } break; case AUTOMAP_KEY_PITCHDOWN: - if (up) - { + if (up) { g_clAutoMapInput.pitch = 0.0f; - } - else - { + } else { g_clAutoMapInput.pitch = 4.0f; } break; @@ -596,221 +530,165 @@ static void CL_AutoMapKey(int autoMapKey, qboolean up) memcpy(data, &g_clAutoMapInput, sizeof(autoMapInput_t)); - if (cls.cgameStarted) - { + if (cls.cgameStarted) { CGVM_AutomapInput(); } g_clAutoMapInput.goToDefaults = qfalse; } - -void IN_UpDown(void) -{ - if (g_clAutoMapMode) - { +void IN_UpDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_PITCHUP, qfalse); - } - else - { + } else { IN_KeyDown(&in_up); } } -void IN_UpUp(void) -{ - if (g_clAutoMapMode) - { +void IN_UpUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_PITCHUP, qtrue); - } - else - { + } else { IN_KeyUp(&in_up); } } -void IN_DownDown(void) -{ - if (g_clAutoMapMode) - { +void IN_DownDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_PITCHDOWN, qfalse); - } - else - { + } else { IN_KeyDown(&in_down); } } -void IN_DownUp(void) -{ - if (g_clAutoMapMode) - { +void IN_DownUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_PITCHDOWN, qtrue); - } - else - { + } else { IN_KeyUp(&in_down); } } -void IN_LeftDown(void) {IN_KeyDown(&in_left);} -void IN_LeftUp(void) {IN_KeyUp(&in_left);} -void IN_RightDown(void) {IN_KeyDown(&in_right);} -void IN_RightUp(void) {IN_KeyUp(&in_right);} -void IN_ForwardDown(void) -{ - if (g_clAutoMapMode) - { +void IN_LeftDown(void) { IN_KeyDown(&in_left); } +void IN_LeftUp(void) { IN_KeyUp(&in_left); } +void IN_RightDown(void) { IN_KeyDown(&in_right); } +void IN_RightUp(void) { IN_KeyUp(&in_right); } +void IN_ForwardDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_FORWARD, qfalse); - } - else - { + } else { IN_KeyDown(&in_forward); } } -void IN_ForwardUp(void) -{ - if (g_clAutoMapMode) - { +void IN_ForwardUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_FORWARD, qtrue); - } - else - { + } else { IN_KeyUp(&in_forward); } } -void IN_BackDown(void) -{ - if (g_clAutoMapMode) - { +void IN_BackDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_BACK, qfalse); - } - else - { + } else { IN_KeyDown(&in_back); } } -void IN_BackUp(void) -{ - if (g_clAutoMapMode) - { +void IN_BackUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_BACK, qtrue); - } - else - { + } else { IN_KeyUp(&in_back); } } -void IN_LookupDown(void) {IN_KeyDown(&in_lookup);} -void IN_LookupUp(void) {IN_KeyUp(&in_lookup);} -void IN_LookdownDown(void) {IN_KeyDown(&in_lookdown);} -void IN_LookdownUp(void) {IN_KeyUp(&in_lookdown);} -void IN_MoveleftDown(void) -{ - if (g_clAutoMapMode) - { +void IN_LookupDown(void) { IN_KeyDown(&in_lookup); } +void IN_LookupUp(void) { IN_KeyUp(&in_lookup); } +void IN_LookdownDown(void) { IN_KeyDown(&in_lookdown); } +void IN_LookdownUp(void) { IN_KeyUp(&in_lookdown); } +void IN_MoveleftDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_YAWLEFT, qfalse); - } - else - { + } else { IN_KeyDown(&in_moveleft); } } -void IN_MoveleftUp(void) -{ - if (g_clAutoMapMode) - { +void IN_MoveleftUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_YAWLEFT, qtrue); - } - else - { + } else { IN_KeyUp(&in_moveleft); } } -void IN_MoverightDown(void) -{ - if (g_clAutoMapMode) - { +void IN_MoverightDown(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_YAWRIGHT, qfalse); - } - else - { + } else { IN_KeyDown(&in_moveright); } } -void IN_MoverightUp(void) -{ - if (g_clAutoMapMode) - { +void IN_MoverightUp(void) { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_YAWRIGHT, qtrue); - } - else - { + } else { IN_KeyUp(&in_moveright); } } -void IN_SpeedDown(void) {IN_KeyDown(&in_speed);} -void IN_SpeedUp(void) {IN_KeyUp(&in_speed);} -void IN_StrafeDown(void) {IN_KeyDown(&in_strafe);} -void IN_StrafeUp(void) {IN_KeyUp(&in_strafe);} +void IN_SpeedDown(void) { IN_KeyDown(&in_speed); } +void IN_SpeedUp(void) { IN_KeyUp(&in_speed); } +void IN_StrafeDown(void) { IN_KeyDown(&in_strafe); } +void IN_StrafeUp(void) { IN_KeyUp(&in_strafe); } -void IN_Button0Down(void) {IN_KeyDown(&in_buttons[0]);} -void IN_Button0Up(void) {IN_KeyUp(&in_buttons[0]);} -void IN_Button1Down(void) {IN_KeyDown(&in_buttons[1]);} -void IN_Button1Up(void) {IN_KeyUp(&in_buttons[1]);} -void IN_Button2Down(void) {IN_KeyDown(&in_buttons[2]);} -void IN_Button2Up(void) {IN_KeyUp(&in_buttons[2]);} -void IN_Button3Down(void) {IN_KeyDown(&in_buttons[3]);} -void IN_Button3Up(void) {IN_KeyUp(&in_buttons[3]);} -void IN_Button4Down(void) {IN_KeyDown(&in_buttons[4]);} -void IN_Button4Up(void) {IN_KeyUp(&in_buttons[4]);} -void IN_Button5Down(void) //use key +void IN_Button0Down(void) { IN_KeyDown(&in_buttons[0]); } +void IN_Button0Up(void) { IN_KeyUp(&in_buttons[0]); } +void IN_Button1Down(void) { IN_KeyDown(&in_buttons[1]); } +void IN_Button1Up(void) { IN_KeyUp(&in_buttons[1]); } +void IN_Button2Down(void) { IN_KeyDown(&in_buttons[2]); } +void IN_Button2Up(void) { IN_KeyUp(&in_buttons[2]); } +void IN_Button3Down(void) { IN_KeyDown(&in_buttons[3]); } +void IN_Button3Up(void) { IN_KeyUp(&in_buttons[3]); } +void IN_Button4Down(void) { IN_KeyDown(&in_buttons[4]); } +void IN_Button4Up(void) { IN_KeyUp(&in_buttons[4]); } +void IN_Button5Down(void) // use key { - if (g_clAutoMapMode) - { + if (g_clAutoMapMode) { CL_AutoMapKey(AUTOMAP_KEY_DEFAULTVIEW, qfalse); - } - else - { + } else { IN_KeyDown(&in_buttons[5]); } } -void IN_Button5Up(void) {IN_KeyUp(&in_buttons[5]);} -void IN_Button6Down(void) {IN_KeyDown(&in_buttons[6]);} -void IN_Button6Up(void) {IN_KeyUp(&in_buttons[6]);} -void IN_Button7Down(void) {IN_KeyDown(&in_buttons[7]);} -void IN_Button7Up(void){IN_KeyUp(&in_buttons[7]);} -void IN_Button8Down(void) {IN_KeyDown(&in_buttons[8]);} -void IN_Button8Up(void) {IN_KeyUp(&in_buttons[8]);} -void IN_Button9Down(void) {IN_KeyDown(&in_buttons[9]);} -void IN_Button9Up(void) {IN_KeyUp(&in_buttons[9]);} -void IN_Button10Down(void) {IN_KeyDown(&in_buttons[10]);} -void IN_Button10Up(void) {IN_KeyUp(&in_buttons[10]);} -void IN_Button11Down(void) {IN_KeyDown(&in_buttons[11]);} -void IN_Button11Up(void) {IN_KeyUp(&in_buttons[11]);} -void IN_Button12Down(void) {IN_KeyDown(&in_buttons[12]);} -void IN_Button12Up(void) {IN_KeyUp(&in_buttons[12]);} -void IN_Button13Down(void) {IN_KeyDown(&in_buttons[13]);} -void IN_Button13Up(void) {IN_KeyUp(&in_buttons[13]);} -void IN_Button14Down(void) {IN_KeyDown(&in_buttons[14]);} -void IN_Button14Up(void) {IN_KeyUp(&in_buttons[14]);} -void IN_Button15Down(void) {IN_KeyDown(&in_buttons[15]);} -void IN_Button15Up(void) {IN_KeyUp(&in_buttons[15]);} - -void IN_CenterView (void) { - cl.viewangles[PITCH] = -SHORT2ANGLE(cl.snap.ps.delta_angles[PITCH]); -} +void IN_Button5Up(void) { IN_KeyUp(&in_buttons[5]); } +void IN_Button6Down(void) { IN_KeyDown(&in_buttons[6]); } +void IN_Button6Up(void) { IN_KeyUp(&in_buttons[6]); } +void IN_Button7Down(void) { IN_KeyDown(&in_buttons[7]); } +void IN_Button7Up(void) { IN_KeyUp(&in_buttons[7]); } +void IN_Button8Down(void) { IN_KeyDown(&in_buttons[8]); } +void IN_Button8Up(void) { IN_KeyUp(&in_buttons[8]); } +void IN_Button9Down(void) { IN_KeyDown(&in_buttons[9]); } +void IN_Button9Up(void) { IN_KeyUp(&in_buttons[9]); } +void IN_Button10Down(void) { IN_KeyDown(&in_buttons[10]); } +void IN_Button10Up(void) { IN_KeyUp(&in_buttons[10]); } +void IN_Button11Down(void) { IN_KeyDown(&in_buttons[11]); } +void IN_Button11Up(void) { IN_KeyUp(&in_buttons[11]); } +void IN_Button12Down(void) { IN_KeyDown(&in_buttons[12]); } +void IN_Button12Up(void) { IN_KeyUp(&in_buttons[12]); } +void IN_Button13Down(void) { IN_KeyDown(&in_buttons[13]); } +void IN_Button13Up(void) { IN_KeyUp(&in_buttons[13]); } +void IN_Button14Down(void) { IN_KeyDown(&in_buttons[14]); } +void IN_Button14Up(void) { IN_KeyUp(&in_buttons[14]); } +void IN_Button15Down(void) { IN_KeyDown(&in_buttons[15]); } +void IN_Button15Up(void) { IN_KeyUp(&in_buttons[15]); } + +void IN_CenterView(void) { cl.viewangles[PITCH] = -SHORT2ANGLE(cl.snap.ps.delta_angles[PITCH]); } //========================================================================== -cvar_t *cl_upspeed; -cvar_t *cl_forwardspeed; -cvar_t *cl_sidespeed; +cvar_t *cl_upspeed; +cvar_t *cl_forwardspeed; +cvar_t *cl_sidespeed; -cvar_t *cl_yawspeed; -cvar_t *cl_pitchspeed; +cvar_t *cl_yawspeed; +cvar_t *cl_pitchspeed; -cvar_t *cl_run; - -cvar_t *cl_anglespeedkey; +cvar_t *cl_run; +cvar_t *cl_anglespeedkey; /* ================ @@ -819,53 +697,41 @@ CL_AdjustAngles Moves the local angle positions ================ */ -void CL_AdjustAngles( void ) { - float speed; +void CL_AdjustAngles(void) { + float speed; - if ( in_speed.active ) { + if (in_speed.active) { speed = 0.001 * cls.frametime * cl_anglespeedkey->value; } else { speed = 0.001 * cls.frametime; } - if ( !in_strafe.active ) { - if ( cl_mYawOverride ) - { - if ( cl_mSensitivityOverride ) - { - cl.viewangles[YAW] -= cl_mYawOverride*cl_mSensitivityOverride*speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += cl_mYawOverride*cl_mSensitivityOverride*speed*cl_yawspeed->value*CL_KeyState (&in_left); - } - else - { - cl.viewangles[YAW] -= cl_mYawOverride*OVERRIDE_MOUSE_SENSITIVITY*speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += cl_mYawOverride*OVERRIDE_MOUSE_SENSITIVITY*speed*cl_yawspeed->value*CL_KeyState (&in_left); + if (!in_strafe.active) { + if (cl_mYawOverride) { + if (cl_mSensitivityOverride) { + cl.viewangles[YAW] -= cl_mYawOverride * cl_mSensitivityOverride * speed * cl_yawspeed->value * CL_KeyState(&in_right); + cl.viewangles[YAW] += cl_mYawOverride * cl_mSensitivityOverride * speed * cl_yawspeed->value * CL_KeyState(&in_left); + } else { + cl.viewangles[YAW] -= cl_mYawOverride * OVERRIDE_MOUSE_SENSITIVITY * speed * cl_yawspeed->value * CL_KeyState(&in_right); + cl.viewangles[YAW] += cl_mYawOverride * OVERRIDE_MOUSE_SENSITIVITY * speed * cl_yawspeed->value * CL_KeyState(&in_left); } - } - else - { - cl.viewangles[YAW] -= speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += speed*cl_yawspeed->value*CL_KeyState (&in_left); + } else { + cl.viewangles[YAW] -= speed * cl_yawspeed->value * CL_KeyState(&in_right); + cl.viewangles[YAW] += speed * cl_yawspeed->value * CL_KeyState(&in_left); } } - if ( cl_mPitchOverride ) - { - if ( cl_mSensitivityOverride ) - { - cl.viewangles[PITCH] -= cl_mPitchOverride*cl_mSensitivityOverride*speed*cl_pitchspeed->value * CL_KeyState (&in_lookup); - cl.viewangles[PITCH] += cl_mPitchOverride*cl_mSensitivityOverride*speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown); - } - else - { - cl.viewangles[PITCH] -= cl_mPitchOverride*OVERRIDE_MOUSE_SENSITIVITY*speed*cl_pitchspeed->value * CL_KeyState (&in_lookup); - cl.viewangles[PITCH] += cl_mPitchOverride*OVERRIDE_MOUSE_SENSITIVITY*speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown); + if (cl_mPitchOverride) { + if (cl_mSensitivityOverride) { + cl.viewangles[PITCH] -= cl_mPitchOverride * cl_mSensitivityOverride * speed * cl_pitchspeed->value * CL_KeyState(&in_lookup); + cl.viewangles[PITCH] += cl_mPitchOverride * cl_mSensitivityOverride * speed * cl_pitchspeed->value * CL_KeyState(&in_lookdown); + } else { + cl.viewangles[PITCH] -= cl_mPitchOverride * OVERRIDE_MOUSE_SENSITIVITY * speed * cl_pitchspeed->value * CL_KeyState(&in_lookup); + cl.viewangles[PITCH] += cl_mPitchOverride * OVERRIDE_MOUSE_SENSITIVITY * speed * cl_pitchspeed->value * CL_KeyState(&in_lookdown); } - } - else - { - cl.viewangles[PITCH] -= speed*cl_pitchspeed->value * CL_KeyState (&in_lookup); - cl.viewangles[PITCH] += speed*cl_pitchspeed->value * CL_KeyState (&in_lookdown); + } else { + cl.viewangles[PITCH] -= speed * cl_pitchspeed->value * CL_KeyState(&in_lookup); + cl.viewangles[PITCH] += speed * cl_pitchspeed->value * CL_KeyState(&in_lookdown); } } @@ -876,16 +742,16 @@ CL_KeyMove Sets the usercmd_t based on key states ================ */ -void CL_KeyMove( usercmd_t *cmd ) { - int movespeed; - int forward, side, up; +void CL_KeyMove(usercmd_t *cmd) { + int movespeed; + int forward, side, up; // // adjust for speed key / running // the walking flag is to keep animations consistant // even during acceleration and develeration // - if ( in_speed.active ^ cl_run->integer ) { + if (in_speed.active ^ cl_run->integer) { movespeed = 127; cmd->buttons &= ~BUTTON_WALKING; } else { @@ -896,24 +762,23 @@ void CL_KeyMove( usercmd_t *cmd ) { forward = 0; side = 0; up = 0; - if ( in_strafe.active ) { - side += movespeed * CL_KeyState (&in_right); - side -= movespeed * CL_KeyState (&in_left); + if (in_strafe.active) { + side += movespeed * CL_KeyState(&in_right); + side -= movespeed * CL_KeyState(&in_left); } - side += movespeed * CL_KeyState (&in_moveright); - side -= movespeed * CL_KeyState (&in_moveleft); - + side += movespeed * CL_KeyState(&in_moveright); + side -= movespeed * CL_KeyState(&in_moveleft); - up += movespeed * CL_KeyState (&in_up); - up -= movespeed * CL_KeyState (&in_down); + up += movespeed * CL_KeyState(&in_up); + up -= movespeed * CL_KeyState(&in_down); - forward += movespeed * CL_KeyState (&in_forward); - forward -= movespeed * CL_KeyState (&in_back); + forward += movespeed * CL_KeyState(&in_forward); + forward -= movespeed * CL_KeyState(&in_back); - cmd->forwardmove = ClampChar( forward ); - cmd->rightmove = ClampChar( side ); - cmd->upmove = ClampChar( up ); + cmd->forwardmove = ClampChar(forward); + cmd->rightmove = ClampChar(side); + cmd->upmove = ClampChar(up); } /* @@ -921,9 +786,8 @@ void CL_KeyMove( usercmd_t *cmd ) { CL_MouseEvent ================= */ -void CL_MouseEvent( int dx, int dy, int time ) { - if (g_clAutoMapMode && cls.cgameStarted) - { //automap input +void CL_MouseEvent(int dx, int dy, int time) { + if (g_clAutoMapMode && cls.cgameStarted) { // automap input autoMapInput_t *data = (autoMapInput_t *)cl.mSharedMemory; g_clAutoMapInput.yaw = dx; @@ -933,11 +797,10 @@ void CL_MouseEvent( int dx, int dy, int time ) { g_clAutoMapInput.yaw = 0.0f; g_clAutoMapInput.pitch = 0.0f; - } - else if ( Key_GetCatcher( ) & KEYCATCH_UI ) { - UIVM_MouseEvent( dx, dy ); - } else if ( Key_GetCatcher( ) & KEYCATCH_CGAME ) { - CGVM_MouseEvent( dx, dy ); + } else if (Key_GetCatcher() & KEYCATCH_UI) { + UIVM_MouseEvent(dx, dy); + } else if (Key_GetCatcher() & KEYCATCH_CGAME) { + CGVM_MouseEvent(dx, dy); } else { cl.mouseDx[cl.mouseIndex] += dx; cl.mouseDy[cl.mouseIndex] += dy; @@ -951,9 +814,9 @@ CL_JoystickEvent Joystick values stay set until changed ================= */ -void CL_JoystickEvent( int axis, int value, int time ) { - if ( axis < 0 || axis >= MAX_JOYSTICK_AXIS ) { - Com_Error( ERR_DROP, "CL_JoystickEvent: bad axis %i", axis ); +void CL_JoystickEvent(int axis, int value, int time) { + if (axis < 0 || axis >= MAX_JOYSTICK_AXIS) { + Com_Error(ERR_DROP, "CL_JoystickEvent: bad axis %i", axis); } cl.joystickAxis[axis] = value; } @@ -964,68 +827,52 @@ CL_JoystickMove ================= */ extern cvar_t *in_joystick; -void CL_JoystickMove( usercmd_t *cmd ) { - float anglespeed; +void CL_JoystickMove(usercmd_t *cmd) { + float anglespeed; - if ( !in_joystick->integer ) - { + if (!in_joystick->integer) { return; } - if ( !(in_speed.active ^ cl_run->integer) ) { + if (!(in_speed.active ^ cl_run->integer)) { cmd->buttons |= BUTTON_WALKING; } - if ( in_speed.active ) { + if (in_speed.active) { anglespeed = 0.001 * cls.frametime * cl_anglespeedkey->value; } else { anglespeed = 0.001 * cls.frametime; } - if ( !in_strafe.active ) { - if ( cl_mYawOverride ) - { - if ( cl_mSensitivityOverride ) - { - cl.viewangles[YAW] += cl_mYawOverride * cl_mSensitivityOverride * cl.joystickAxis[AXIS_SIDE]/2.0f; + if (!in_strafe.active) { + if (cl_mYawOverride) { + if (cl_mSensitivityOverride) { + cl.viewangles[YAW] += cl_mYawOverride * cl_mSensitivityOverride * cl.joystickAxis[AXIS_SIDE] / 2.0f; + } else { + cl.viewangles[YAW] += cl_mYawOverride * OVERRIDE_MOUSE_SENSITIVITY * cl.joystickAxis[AXIS_SIDE] / 2.0f; } - else - { - cl.viewangles[YAW] += cl_mYawOverride * OVERRIDE_MOUSE_SENSITIVITY * cl.joystickAxis[AXIS_SIDE]/2.0f; - } - } - else - { + } else { cl.viewangles[YAW] += anglespeed * (cl_yawspeed->value / 100.0f) * cl.joystickAxis[AXIS_SIDE]; } - } - else - { - cmd->rightmove = ClampChar( cmd->rightmove + cl.joystickAxis[AXIS_SIDE] ); + } else { + cmd->rightmove = ClampChar(cmd->rightmove + cl.joystickAxis[AXIS_SIDE]); } - if ( in_mlooking || cl_freelook->integer ) { - if ( cl_mPitchOverride ) - { - if ( cl_mSensitivityOverride ) - { - cl.viewangles[PITCH] += cl_mPitchOverride * cl_mSensitivityOverride * cl.joystickAxis[AXIS_FORWARD]/2.0f; + if (in_mlooking || cl_freelook->integer) { + if (cl_mPitchOverride) { + if (cl_mSensitivityOverride) { + cl.viewangles[PITCH] += cl_mPitchOverride * cl_mSensitivityOverride * cl.joystickAxis[AXIS_FORWARD] / 2.0f; + } else { + cl.viewangles[PITCH] += cl_mPitchOverride * OVERRIDE_MOUSE_SENSITIVITY * cl.joystickAxis[AXIS_FORWARD] / 2.0f; } - else - { - cl.viewangles[PITCH] += cl_mPitchOverride * OVERRIDE_MOUSE_SENSITIVITY * cl.joystickAxis[AXIS_FORWARD]/2.0f; - } - } - else - { + } else { cl.viewangles[PITCH] += anglespeed * (cl_pitchspeed->value / 100.0f) * cl.joystickAxis[AXIS_FORWARD]; } - } else - { - cmd->forwardmove = ClampChar( cmd->forwardmove + cl.joystickAxis[AXIS_FORWARD] ); + } else { + cmd->forwardmove = ClampChar(cmd->forwardmove + cl.joystickAxis[AXIS_FORWARD]); } - cmd->upmove = ClampChar( cmd->upmove + cl.joystickAxis[AXIS_UP] ); + cmd->upmove = ClampChar(cmd->upmove + cl.joystickAxis[AXIS_UP]); } /* @@ -1033,14 +880,14 @@ void CL_JoystickMove( usercmd_t *cmd ) { CL_MouseMove ================= */ -void CL_MouseMove( usercmd_t *cmd ) { - float mx, my; - const float speed = static_cast(frame_msec); +void CL_MouseMove(usercmd_t *cmd) { + float mx, my; + const float speed = static_cast(frame_msec); // allow mouse smoothing - if ( m_filter->integer ) { - mx = ( cl.mouseDx[0] + cl.mouseDx[1] ) * 0.5; - my = ( cl.mouseDy[0] + cl.mouseDy[1] ) * 0.5; + if (m_filter->integer) { + mx = (cl.mouseDx[0] + cl.mouseDx[1]) * 0.5; + my = (cl.mouseDy[0] + cl.mouseDy[1]) * 0.5; } else { mx = cl.mouseDx[cl.mouseIndex]; my = cl.mouseDy[cl.mouseIndex]; @@ -1050,43 +897,33 @@ void CL_MouseMove( usercmd_t *cmd ) { cl.mouseDx[cl.mouseIndex] = 0; cl.mouseDy[cl.mouseIndex] = 0; - if ( mx == 0.0f && my == 0.0f ) + if (mx == 0.0f && my == 0.0f) return; - if ( cl_mouseAccel->value != 0.0f ) - { - if ( cl_mouseAccelStyle->integer == 0 ) - { + if (cl_mouseAccel->value != 0.0f) { + if (cl_mouseAccelStyle->integer == 0) { float accelSensitivity; float rate; - rate = SQRTFAST( mx * mx + my * my ) / speed; + rate = SQRTFAST(mx * mx + my * my) / speed; - if ( cl_mYawOverride || cl_mPitchOverride ) - {//FIXME: different people have different speed mouses, - if ( cl_mSensitivityOverride ) - { - //this will fuck things up for them, need to clamp - //max input? + if (cl_mYawOverride || cl_mPitchOverride) { // FIXME: different people have different speed mouses, + if (cl_mSensitivityOverride) { + // this will fuck things up for them, need to clamp + // max input? accelSensitivity = cl_mSensitivityOverride; - } - else - { + } else { accelSensitivity = cl_sensitivity->value + rate * cl_mouseAccel->value; } - } - else - { + } else { accelSensitivity = cl_sensitivity->value + rate * cl_mouseAccel->value; } mx *= accelSensitivity; my *= accelSensitivity; - if ( cl_showMouseRate->integer ) - Com_Printf( "rate: %f, accelSensitivity: %f\n", rate, accelSensitivity ); - } - else - { + if (cl_showMouseRate->integer) + Com_Printf("rate: %f, accelSensitivity: %f\n", rate, accelSensitivity); + } else { float rate[2]; float power[2]; @@ -1095,55 +932,41 @@ void CL_MouseMove( usercmd_t *cmd ) { // cl_mouseAccelOffset is the rate for which the acceleration will have doubled the non accelerated amplification // NOTE: decouple the config cvars for independent acceleration setup along X and Y? - rate[0] = fabs( mx ) / speed; - rate[1] = fabs( my ) / speed; - power[0] = powf( rate[0] / cl_mouseAccelOffset->value, cl_mouseAccel->value ); - power[1] = powf( rate[1] / cl_mouseAccelOffset->value, cl_mouseAccel->value ); - - if ( cl_mYawOverride || cl_mPitchOverride ) - {//FIXME: different people have different speed mouses, - if ( cl_mSensitivityOverride ) - { - //this will fuck things up for them, need to clamp - //max input? + rate[0] = fabs(mx) / speed; + rate[1] = fabs(my) / speed; + power[0] = powf(rate[0] / cl_mouseAccelOffset->value, cl_mouseAccel->value); + power[1] = powf(rate[1] / cl_mouseAccelOffset->value, cl_mouseAccel->value); + + if (cl_mYawOverride || cl_mPitchOverride) { // FIXME: different people have different speed mouses, + if (cl_mSensitivityOverride) { + // this will fuck things up for them, need to clamp + // max input? mx = cl_mSensitivityOverride * (mx + ((mx < 0) ? -power[0] : power[0]) * cl_mouseAccelOffset->value); my = cl_mSensitivityOverride * (my + ((my < 0) ? -power[1] : power[1]) * cl_mouseAccelOffset->value); - } - else - { + } else { mx = cl_sensitivity->value * (mx + ((mx < 0) ? -power[0] : power[0]) * cl_mouseAccelOffset->value); my = cl_sensitivity->value * (my + ((my < 0) ? -power[1] : power[1]) * cl_mouseAccelOffset->value); } - } - else - { + } else { mx = cl_sensitivity->value * (mx + ((mx < 0) ? -power[0] : power[0]) * cl_mouseAccelOffset->value); my = cl_sensitivity->value * (my + ((my < 0) ? -power[1] : power[1]) * cl_mouseAccelOffset->value); } - if ( cl_showMouseRate->integer ) - Com_Printf( "ratex: %f, ratey: %f, powx: %f, powy: %f\n", rate[0], rate[1], power[0], power[1] ); + if (cl_showMouseRate->integer) + Com_Printf("ratex: %f, ratey: %f, powx: %f, powy: %f\n", rate[0], rate[1], power[0], power[1]); } - } - else - { - if ( cl_mYawOverride || cl_mPitchOverride ) - {//FIXME: different people have different speed mouses, - if ( cl_mSensitivityOverride ) - { - //this will fuck things up for them, need to clamp - //max input? + } else { + if (cl_mYawOverride || cl_mPitchOverride) { // FIXME: different people have different speed mouses, + if (cl_mSensitivityOverride) { + // this will fuck things up for them, need to clamp + // max input? mx *= cl_mSensitivityOverride; my *= cl_mSensitivityOverride; - } - else - { + } else { mx *= cl_sensitivity->value; my *= cl_sensitivity->value; } - } - else - { + } else { mx *= cl_sensitivity->value; my *= cl_sensitivity->value; } @@ -1154,36 +977,32 @@ void CL_MouseMove( usercmd_t *cmd ) { my *= cl.cgameSensitivity; // add mouse X/Y movement to cmd - if ( in_strafe.active ) - cmd->rightmove = ClampChar( cmd->rightmove + m_side->value * mx ); + if (in_strafe.active) + cmd->rightmove = ClampChar(cmd->rightmove + m_side->value * mx); else { - if ( cl_mYawOverride ) + if (cl_mYawOverride) cl.viewangles[YAW] -= cl_mYawOverride * mx; else cl.viewangles[YAW] -= m_yaw->value * mx; } - if ( (in_mlooking || cl_freelook->integer) && !in_strafe.active ) { + if ((in_mlooking || cl_freelook->integer) && !in_strafe.active) { // VVFIXME - This is supposed to be a CVAR const float cl_pitchSensitivity = 1.0f; const float pitch = cl_bUseFighterPitch ? m_pitchVeh->value : m_pitch->value; - if ( cl_mPitchOverride ) { - if ( pitch > 0 ) + if (cl_mPitchOverride) { + if (pitch > 0) cl.viewangles[PITCH] += cl_mPitchOverride * my * cl_pitchSensitivity; else cl.viewangles[PITCH] -= cl_mPitchOverride * my * cl_pitchSensitivity; - } - else + } else cl.viewangles[PITCH] += pitch * my * cl_pitchSensitivity; - } - else - cmd->forwardmove = ClampChar( cmd->forwardmove - m_forward->value * my ); + } else + cmd->forwardmove = ClampChar(cmd->forwardmove - m_forward->value * my); } -qboolean CL_NoUseableForce(void) -{ - if (!cls.cgameStarted) - { //ahh, no cgame loaded +qboolean CL_NoUseableForce(void) { + if (!cls.cgameStarted) { // ahh, no cgame loaded return qfalse; } @@ -1195,65 +1014,59 @@ qboolean CL_NoUseableForce(void) CL_CmdButtons ============== */ -void CL_CmdButtons( usercmd_t *cmd ) { - int i; +void CL_CmdButtons(usercmd_t *cmd) { + int i; // // figure button bits // send a button bit even if the key was pressed and released in // less than a frame // - for (i = 0 ; i < MAX_KBUTTONS ; i++) { - if ( in_buttons[i].active || in_buttons[i].wasPressed ) { + for (i = 0; i < MAX_KBUTTONS; i++) { + if (in_buttons[i].active || in_buttons[i].wasPressed) { cmd->buttons |= 1 << i; } in_buttons[i].wasPressed = qfalse; } - if (cmd->buttons & BUTTON_FORCEPOWER) - { //check for transferring a use force to a use inventory... - if ((cmd->buttons & BUTTON_USE) || CL_NoUseableForce()) - { //it's pushed, remap it! + if (cmd->buttons & BUTTON_FORCEPOWER) { // check for transferring a use force to a use inventory... + if ((cmd->buttons & BUTTON_USE) || CL_NoUseableForce()) { // it's pushed, remap it! cmd->buttons &= ~BUTTON_FORCEPOWER; cmd->buttons |= BUTTON_USE_HOLDABLE; } } - if ( Key_GetCatcher( ) ) { + if (Key_GetCatcher()) { cmd->buttons |= BUTTON_TALK; } // allow the game to know if any key at all is // currently pressed, even if it isn't bound to anything - if ( kg.anykeydown && Key_GetCatcher( ) == 0 ) { + if (kg.anykeydown && Key_GetCatcher() == 0) { cmd->buttons |= BUTTON_ANY; } } - /* ============== CL_FinishMove ============== */ -vec3_t cl_sendAngles={0}; -vec3_t cl_lastViewAngles={0}; -void CL_FinishMove( usercmd_t *cmd ) { - int i; +vec3_t cl_sendAngles = {0}; +vec3_t cl_lastViewAngles = {0}; +void CL_FinishMove(usercmd_t *cmd) { + int i; // copy the state that the cgame is currently sending cmd->weapon = cl.cgameUserCmdValue; cmd->forcesel = cl.cgameForceSelection; cmd->invensel = cl.cgameInvenSelection; - if (cl.gcmdSendValue) - { + if (cl.gcmdSendValue) { cmd->generic_cmd = cl.gcmdValue; - //cl.gcmdSendValue = qfalse; + // cl.gcmdSendValue = qfalse; cl.gcmdSentValue = qtrue; - } - else - { + } else { cmd->generic_cmd = 0; } @@ -1261,66 +1074,57 @@ void CL_FinishMove( usercmd_t *cmd ) { // can be determined without allowing cheating cmd->serverTime = cl.serverTime; - if (cl.cgameViewAngleForceTime > cl.serverTime) - { + if (cl.cgameViewAngleForceTime > cl.serverTime) { cl.cgameViewAngleForce[YAW] -= SHORT2ANGLE(cl.snap.ps.delta_angles[YAW]); cl.viewangles[YAW] = cl.cgameViewAngleForce[YAW]; cl.cgameViewAngleForceTime = 0; } - if ( cl_crazyShipControls ) - { + if (cl_crazyShipControls) { float pitchSubtract, pitchDelta, yawDelta; - yawDelta = AngleSubtract(cl.viewangles[YAW],cl_lastViewAngles[YAW]); - //yawDelta *= (4.0f*pVeh->m_fTimeModifier); + yawDelta = AngleSubtract(cl.viewangles[YAW], cl_lastViewAngles[YAW]); + // yawDelta *= (4.0f*pVeh->m_fTimeModifier); cl_sendAngles[ROLL] -= yawDelta; float nRoll = fabs(cl_sendAngles[ROLL]); - pitchDelta = AngleSubtract(cl.viewangles[PITCH],cl_lastViewAngles[PITCH]); - //pitchDelta *= (2.0f*pVeh->m_fTimeModifier); - pitchSubtract = pitchDelta * (nRoll/90.0f); - cl_sendAngles[PITCH] += pitchDelta-pitchSubtract; + pitchDelta = AngleSubtract(cl.viewangles[PITCH], cl_lastViewAngles[PITCH]); + // pitchDelta *= (2.0f*pVeh->m_fTimeModifier); + pitchSubtract = pitchDelta * (nRoll / 90.0f); + cl_sendAngles[PITCH] += pitchDelta - pitchSubtract; - //yaw-roll calc should be different - if (nRoll > 90.0f) - { + // yaw-roll calc should be different + if (nRoll > 90.0f) { nRoll -= 180.0f; } - if (nRoll < 0.0f) - { + if (nRoll < 0.0f) { nRoll = -nRoll; } - pitchSubtract = pitchDelta * (nRoll/90.0f); - if ( cl_sendAngles[ROLL] > 0.0f ) - { + pitchSubtract = pitchDelta * (nRoll / 90.0f); + if (cl_sendAngles[ROLL] > 0.0f) { cl_sendAngles[YAW] += pitchSubtract; - } - else - { + } else { cl_sendAngles[YAW] -= pitchSubtract; } - cl_sendAngles[PITCH] = AngleNormalize180( cl_sendAngles[PITCH] ); - cl_sendAngles[YAW] = AngleNormalize360( cl_sendAngles[YAW] ); - cl_sendAngles[ROLL] = AngleNormalize180( cl_sendAngles[ROLL] ); + cl_sendAngles[PITCH] = AngleNormalize180(cl_sendAngles[PITCH]); + cl_sendAngles[YAW] = AngleNormalize360(cl_sendAngles[YAW]); + cl_sendAngles[ROLL] = AngleNormalize180(cl_sendAngles[ROLL]); - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { cmd->angles[i] = ANGLE2SHORT(cl_sendAngles[i]); } - } - else - { - for (i=0 ; i<3 ; i++) { + } else { + for (i = 0; i < 3; i++) { cmd->angles[i] = ANGLE2SHORT(cl.viewangles[i]); } - //in case we switch to the cl_crazyShipControls - VectorCopy( cl.viewangles, cl_sendAngles ); + // in case we switch to the cl_crazyShipControls + VectorCopy(cl.viewangles, cl_sendAngles); } - //always needed in for the cl_crazyShipControls - VectorCopy( cl.viewangles, cl_lastViewAngles ); + // always needed in for the cl_crazyShipControls + VectorCopy(cl.viewangles, cl_lastViewAngles); } /* @@ -1328,52 +1132,51 @@ void CL_FinishMove( usercmd_t *cmd ) { CL_CreateCmd ================= */ -usercmd_t CL_CreateCmd( void ) { - usercmd_t cmd; - vec3_t oldAngles; +usercmd_t CL_CreateCmd(void) { + usercmd_t cmd; + vec3_t oldAngles; - VectorCopy( cl.viewangles, oldAngles ); + VectorCopy(cl.viewangles, oldAngles); // keyboard angle adjustment - CL_AdjustAngles (); + CL_AdjustAngles(); - Com_Memset( &cmd, 0, sizeof( cmd ) ); + Com_Memset(&cmd, 0, sizeof(cmd)); - CL_CmdButtons( &cmd ); + CL_CmdButtons(&cmd); // get basic movement from keyboard - CL_KeyMove( &cmd ); + CL_KeyMove(&cmd); // get basic movement from mouse - CL_MouseMove( &cmd ); + CL_MouseMove(&cmd); // get basic movement from joystick - CL_JoystickMove( &cmd ); + CL_JoystickMove(&cmd); // check to make sure the angles haven't wrapped - if ( cl.viewangles[PITCH] - oldAngles[PITCH] > 90 ) { + if (cl.viewangles[PITCH] - oldAngles[PITCH] > 90) { cl.viewangles[PITCH] = oldAngles[PITCH] + 90; - } else if ( oldAngles[PITCH] - cl.viewangles[PITCH] > 90 ) { + } else if (oldAngles[PITCH] - cl.viewangles[PITCH] > 90) { cl.viewangles[PITCH] = oldAngles[PITCH] - 90; } // store out the final values - CL_FinishMove( &cmd ); + CL_FinishMove(&cmd); // draw debug graphs of turning for mouse testing - if ( cl_debugMove->integer ) { - if ( cl_debugMove->integer == 1 ) { - SCR_DebugGraph( abs(cl.viewangles[YAW] - oldAngles[YAW]), 0 ); + if (cl_debugMove->integer) { + if (cl_debugMove->integer == 1) { + SCR_DebugGraph(abs(cl.viewangles[YAW] - oldAngles[YAW]), 0); } - if ( cl_debugMove->integer == 2 ) { - SCR_DebugGraph( abs(cl.viewangles[PITCH] - oldAngles[PITCH]), 0 ); + if (cl_debugMove->integer == 2) { + SCR_DebugGraph(abs(cl.viewangles[PITCH] - oldAngles[PITCH]), 0); } } return cmd; } - /* ================= CL_CreateNewCommands @@ -1381,23 +1184,23 @@ CL_CreateNewCommands Create a new usercmd_t structure for this frame ================= */ -void CL_CreateNewCommands( void ) { - int cmdNum; +void CL_CreateNewCommands(void) { + int cmdNum; // no need to create usercmds until we have a gamestate - if ( cls.state < CA_PRIMED ) + if (cls.state < CA_PRIMED) return; frame_msec = com_frameTime - old_com_frameTime; // if running over 1000fps, act as if each frame is 1ms // prevents divisions by zero - if ( frame_msec < 1 ) + if (frame_msec < 1) frame_msec = 1; // if running less than 5fps, truncate the extra time to prevent // unexpected moves after a hitch - if ( frame_msec > 200 ) + if (frame_msec > 200) frame_msec = 200; old_com_frameTime = com_frameTime; @@ -1419,50 +1222,45 @@ delivered in the next packet, but saving a header and getting more delta compression will reduce total bandwidth. ================= */ -qboolean CL_ReadyToSendPacket( void ) { - int oldPacketNum; - int delta; +qboolean CL_ReadyToSendPacket(void) { + int oldPacketNum; + int delta; // don't send anything if playing back a demo - if ( clc.demoplaying || cls.state == CA_CINEMATIC ) { + if (clc.demoplaying || cls.state == CA_CINEMATIC) { return qfalse; } // If we are downloading, we send no less than 50ms between packets - if ( *clc.downloadTempName && - cls.realtime - clc.lastPacketSentTime < 50 ) { + if (*clc.downloadTempName && cls.realtime - clc.lastPacketSentTime < 50) { return qfalse; } // if we don't have a valid gamestate yet, only send // one packet a second - if ( cls.state != CA_ACTIVE && - cls.state != CA_PRIMED && - !*clc.downloadTempName && - cls.realtime - clc.lastPacketSentTime < 1000 ) { + if (cls.state != CA_ACTIVE && cls.state != CA_PRIMED && !*clc.downloadTempName && cls.realtime - clc.lastPacketSentTime < 1000) { return qfalse; } // send every frame for loopbacks - if ( clc.netchan.remoteAddress.type == NA_LOOPBACK ) { + if (clc.netchan.remoteAddress.type == NA_LOOPBACK) { return qtrue; } // send every frame for LAN - if ( cl_lanForcePackets->integer && Sys_IsLANAddress( clc.netchan.remoteAddress ) ) { + if (cl_lanForcePackets->integer && Sys_IsLANAddress(clc.netchan.remoteAddress)) { return qtrue; } // check for exceeding cl_maxpackets - if ( cl_maxpackets->integer < 20 ) { - Cvar_Set( "cl_maxpackets", "20" ); - } - else if ( cl_maxpackets->integer > 1000 ) { - Cvar_Set( "cl_maxpackets", "1000" ); + if (cl_maxpackets->integer < 20) { + Cvar_Set("cl_maxpackets", "20"); + } else if (cl_maxpackets->integer > 1000) { + Cvar_Set("cl_maxpackets", "1000"); } oldPacketNum = (clc.netchan.outgoingSequence - 1) & PACKET_MASK; - delta = cls.realtime - cl.outPackets[ oldPacketNum ].p_realtime; - if ( delta < 1000 / cl_maxpackets->integer ) { + delta = cls.realtime - cl.outPackets[oldPacketNum].p_realtime; + if (delta < 1000 / cl_maxpackets->integer) { // the accumulated commands will go out in the next packet return qfalse; } @@ -1491,94 +1289,91 @@ During normal gameplay, a client packet will contain something like: =================== */ -void CL_WritePacket( void ) { - msg_t buf; - byte data[MAX_MSGLEN]; - int i, j; - usercmd_t *cmd, *oldcmd; - usercmd_t nullcmd; - int packetNum; - int oldPacketNum; - int count, key; +void CL_WritePacket(void) { + msg_t buf; + byte data[MAX_MSGLEN]; + int i, j; + usercmd_t *cmd, *oldcmd; + usercmd_t nullcmd; + int packetNum; + int oldPacketNum; + int count, key; // don't send anything if playing back a demo - if ( clc.demoplaying || cls.state == CA_CINEMATIC ) { + if (clc.demoplaying || cls.state == CA_CINEMATIC) { return; } - Com_Memset( &nullcmd, 0, sizeof(nullcmd) ); + Com_Memset(&nullcmd, 0, sizeof(nullcmd)); oldcmd = &nullcmd; - MSG_Init( &buf, data, sizeof(data) ); + MSG_Init(&buf, data, sizeof(data)); - MSG_Bitstream( &buf ); + MSG_Bitstream(&buf); // write the current serverId so the server // can tell if this is from the current gameState - MSG_WriteLong( &buf, cl.serverId ); + MSG_WriteLong(&buf, cl.serverId); // write the last message we received, which can // be used for delta compression, and is also used // to tell if we dropped a gamestate - MSG_WriteLong( &buf, clc.serverMessageSequence ); + MSG_WriteLong(&buf, clc.serverMessageSequence); // write the last reliable message we received - MSG_WriteLong( &buf, clc.serverCommandSequence ); + MSG_WriteLong(&buf, clc.serverCommandSequence); // write any unacknowledged clientCommands - for ( i = clc.reliableAcknowledge + 1 ; i <= clc.reliableSequence ; i++ ) { - MSG_WriteByte( &buf, clc_clientCommand ); - MSG_WriteLong( &buf, i ); - MSG_WriteString( &buf, clc.reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] ); + for (i = clc.reliableAcknowledge + 1; i <= clc.reliableSequence; i++) { + MSG_WriteByte(&buf, clc_clientCommand); + MSG_WriteLong(&buf, i); + MSG_WriteString(&buf, clc.reliableCommands[i & (MAX_RELIABLE_COMMANDS - 1)]); } // we want to send all the usercmds that were generated in the last // few packet, so even if a couple packets are dropped in a row, // all the cmds will make it to the server - if ( cl_packetdup->integer < 0 ) { - Cvar_Set( "cl_packetdup", "0" ); - } else if ( cl_packetdup->integer > 5 ) { - Cvar_Set( "cl_packetdup", "5" ); + if (cl_packetdup->integer < 0) { + Cvar_Set("cl_packetdup", "0"); + } else if (cl_packetdup->integer > 5) { + Cvar_Set("cl_packetdup", "5"); } oldPacketNum = (clc.netchan.outgoingSequence - 1 - cl_packetdup->integer) & PACKET_MASK; - count = cl.cmdNumber - cl.outPackets[ oldPacketNum ].p_cmdNumber; - if ( count > MAX_PACKET_USERCMDS ) { + count = cl.cmdNumber - cl.outPackets[oldPacketNum].p_cmdNumber; + if (count > MAX_PACKET_USERCMDS) { count = MAX_PACKET_USERCMDS; Com_Printf("MAX_PACKET_USERCMDS\n"); } - if ( count >= 1 ) { - if ( cl_showSend->integer ) { - Com_Printf( "(%i)", count ); + if (count >= 1) { + if (cl_showSend->integer) { + Com_Printf("(%i)", count); } // begin a client move command - if ( cl_nodelta->integer || !cl.snap.valid - || clc.demowaiting - || clc.serverMessageSequence != cl.snap.messageNum ) { - MSG_WriteByte (&buf, clc_moveNoDelta); + if (cl_nodelta->integer || !cl.snap.valid || clc.demowaiting || clc.serverMessageSequence != cl.snap.messageNum) { + MSG_WriteByte(&buf, clc_moveNoDelta); } else { - MSG_WriteByte (&buf, clc_move); + MSG_WriteByte(&buf, clc_move); } // write the command count - MSG_WriteByte( &buf, count ); + MSG_WriteByte(&buf, count); // use the checksum feed in the key key = clc.checksumFeed; // also use the message acknowledge key ^= clc.serverMessageSequence; // also use the last acknowledged server command in the key - key ^= Com_HashKey(clc.serverCommands[ clc.serverCommandSequence & (MAX_RELIABLE_COMMANDS-1) ], 32); + key ^= Com_HashKey(clc.serverCommands[clc.serverCommandSequence & (MAX_RELIABLE_COMMANDS - 1)], 32); // write all the commands, including the predicted command - for ( i = 0 ; i < count ; i++ ) { + for (i = 0; i < count; i++) { j = (cl.cmdNumber - count + i + 1) & CMD_MASK; cmd = &cl.cmds[j]; - MSG_WriteDeltaUsercmdKey (&buf, key, oldcmd, cmd); + MSG_WriteDeltaUsercmdKey(&buf, key, oldcmd, cmd); oldcmd = cmd; } - if (cl.gcmdSentValue) - { //hmm, just clear here, I guess.. hoping it will resolve issues with gencmd values sometimes not going through. + if (cl.gcmdSentValue) { // hmm, just clear here, I guess.. hoping it will resolve issues with gencmd values sometimes not going through. cl.gcmdSendValue = qfalse; cl.gcmdSentValue = qfalse; cl.gcmdValue = 0; @@ -1589,22 +1384,22 @@ void CL_WritePacket( void ) { // deliver the message // packetNum = clc.netchan.outgoingSequence & PACKET_MASK; - cl.outPackets[ packetNum ].p_realtime = cls.realtime; - cl.outPackets[ packetNum ].p_serverTime = oldcmd->serverTime; - cl.outPackets[ packetNum ].p_cmdNumber = cl.cmdNumber; + cl.outPackets[packetNum].p_realtime = cls.realtime; + cl.outPackets[packetNum].p_serverTime = oldcmd->serverTime; + cl.outPackets[packetNum].p_cmdNumber = cl.cmdNumber; clc.lastPacketSentTime = cls.realtime; - if ( cl_showSend->integer ) { - Com_Printf( "%i ", buf.cursize ); + if (cl_showSend->integer) { + Com_Printf("%i ", buf.cursize); } - CL_Netchan_Transmit (&clc.netchan, &buf); + CL_Netchan_Transmit(&clc.netchan, &buf); // clients never really should have messages large enough // to fragment, but in case they do, fire them all off // at once - while ( clc.netchan.unsentFragments ) { - CL_Netchan_TransmitNextFragment( &clc.netchan ); + while (clc.netchan.unsentFragments) { + CL_Netchan_TransmitNextFragment(&clc.netchan); } } @@ -1615,14 +1410,14 @@ CL_SendCmd Called every frame to builds and sends a command packet to the server. ================= */ -void CL_SendCmd( void ) { +void CL_SendCmd(void) { // don't send any message if not connected - if ( cls.state < CA_CONNECTED ) { + if (cls.state < CA_CONNECTED) { return; } // don't send commands if paused - if ( com_sv_running->integer && sv_paused->integer && cl_paused->integer ) { + if (com_sv_running->integer && sv_paused->integer && cl_paused->integer) { return; } @@ -1630,9 +1425,9 @@ void CL_SendCmd( void ) { CL_CreateNewCommands(); // don't send a packet if the last packet was sent too recently - if ( !CL_ReadyToSendPacket() ) { - if ( cl_showSend->integer ) { - Com_Printf( ". " ); + if (!CL_ReadyToSendPacket()) { + if (cl_showSend->integer) { + Com_Printf(". "); } return; } @@ -1640,129 +1435,126 @@ void CL_SendCmd( void ) { CL_WritePacket(); } -static const cmdList_t inputCmds[] = -{ - { "centerview", "Centers view on screen", IN_CenterView, NULL }, - { "+moveup", "Jump", IN_UpDown, NULL }, - { "-moveup", NULL, IN_UpUp, NULL }, - { "+movedown", "Crouch", IN_DownDown, NULL }, - { "-movedown", NULL, IN_DownUp, NULL }, - { "+left", "Rotate camera left", IN_LeftDown, NULL }, - { "-left", NULL, IN_LeftUp, NULL }, - { "+right", "Rotate camera right", IN_RightDown, NULL }, - { "-right", NULL, IN_RightUp, NULL }, - { "+forward", "Move forward", IN_ForwardDown, NULL }, - { "-forward", NULL, IN_ForwardUp, NULL }, - { "+back", "Move backward", IN_BackDown, NULL }, - { "-back", NULL, IN_BackUp, NULL }, - { "+lookup", "Tilt camera up", IN_LookupDown, NULL }, - { "-lookup", NULL, IN_LookupUp, NULL }, - { "+lookdown", "Tilt camera down", IN_LookdownDown, NULL }, - { "-lookdown", NULL, IN_LookdownUp, NULL }, - { "+strafe", "Hold to strafe", IN_StrafeDown, NULL }, - { "-strafe", NULL, IN_StrafeUp, NULL }, - { "+moveleft", "Strafe left", IN_MoveleftDown, NULL }, - { "-moveleft", NULL, IN_MoveleftUp, NULL }, - { "+moveright", "Strafe right", IN_MoverightDown, NULL }, - { "-moveright", NULL, IN_MoverightUp, NULL }, - { "+speed", "Walk or run", IN_SpeedDown, NULL }, - { "-speed", NULL, IN_SpeedUp, NULL }, - { "+attack", "Primary Attack", IN_Button0Down, NULL }, - { "-attack", NULL, IN_Button0Up, NULL }, - { "+use", "Use item", IN_Button5Down, NULL }, - { "-use", NULL, IN_Button5Up, NULL }, - { "+force_grip", "Hold to use grip force power", IN_Button6Down, NULL }, - { "-force_grip", NULL, IN_Button6Up, NULL }, - { "+altattack", "Alternate Attack", IN_Button7Down, NULL }, - { "-altattack", NULL, IN_Button7Up, NULL }, - { "+useforce", "Use selected force power", IN_Button9Down, NULL }, - { "-useforce", NULL, IN_Button9Up, NULL }, - { "+force_lightning", "Hold to use lightning force power", IN_Button10Down, NULL }, - { "-force_lightning", NULL, IN_Button10Up, NULL }, - { "+force_drain", "Hold to use drain force power", IN_Button11Down, NULL }, - { "-force_drain", NULL, IN_Button11Up, NULL }, - { "+button0", "Button 0", IN_Button0Down, NULL }, - { "-button0", NULL, IN_Button0Up, NULL }, - { "+button1", "Button 1", IN_Button1Down, NULL }, - { "-button1", NULL, IN_Button1Up, NULL }, - { "+button2", "Button 2", IN_Button2Down, NULL }, - { "-button2", NULL, IN_Button2Up, NULL }, - { "+button3", "Button 3", IN_Button3Down, NULL }, - { "-button3", NULL, IN_Button3Up, NULL }, - { "+button4", "Button 4", IN_Button4Down, NULL }, - { "-button4", NULL, IN_Button4Up, NULL }, - { "+button5", "Button 5", IN_Button5Down, NULL }, - { "-button5", NULL, IN_Button5Up, NULL }, - { "+button6", "Button 6", IN_Button6Down, NULL }, - { "-button6", NULL, IN_Button6Up, NULL }, - { "+button7", "Button 7", IN_Button7Down, NULL }, - { "-button7", NULL, IN_Button7Up, NULL }, - { "+button8", "Button 8", IN_Button8Down, NULL }, - { "-button8", NULL, IN_Button8Up, NULL }, - { "+button9", "Button 9", IN_Button9Down, NULL }, - { "-button9", NULL, IN_Button9Up, NULL }, - { "+button10", "Button 10", IN_Button10Down, NULL }, - { "-button10", NULL, IN_Button10Up, NULL }, - { "+button11", "Button 11", IN_Button11Down, NULL }, - { "-button11", NULL, IN_Button11Up, NULL }, - { "+button12", "Button 12", IN_Button12Down, NULL }, - { "-button12", NULL, IN_Button12Up, NULL }, - { "+button13", "Button 13", IN_Button13Down, NULL }, - { "-button13", NULL, IN_Button13Up, NULL }, - { "+button14", "Button 14", IN_Button14Down, NULL }, - { "-button14", NULL, IN_Button14Up, NULL }, - { "+button15", "Button 15", IN_Button15Down, NULL }, - { "-button15", NULL, IN_Button15Up, NULL }, - { "+mlook", "Hold to use mouse look", IN_MLookDown, NULL }, - { "-mlook", NULL, IN_MLookUp, NULL }, - { "sv_saberswitch", "Holster/activate lightsaber", IN_GenCMD1, NULL }, - { "engage_duel", "Engage private duel", IN_GenCMD2, NULL }, - { "force_heal", "Use heal force power", IN_GenCMD3, NULL }, - { "force_speed", "Activate speed force power", IN_GenCMD4, NULL }, - { "force_pull", "Use pull force power", IN_GenCMD5, NULL }, - { "force_distract", "Activate mind trick force power", IN_GenCMD6, NULL }, - { "force_rage", "Activate rage force power", IN_GenCMD7, NULL }, - { "force_protect", "Activate protect force power", IN_GenCMD8, NULL }, - { "force_absorb", "Activate absorb force power", IN_GenCMD9, NULL }, - { "force_healother", "Use team heal force power", IN_GenCMD10, NULL }, - { "force_forcepowerother", "Use team energize force power", IN_GenCMD11, NULL }, - { "force_seeing", "Activate seeing force power", IN_GenCMD12, NULL }, - { "use_seeker", "Use seeker drone item", IN_GenCMD13, NULL }, - { "use_field", "Use forcefield item", IN_GenCMD14, NULL }, - { "use_bacta", "Use bacta item", IN_GenCMD15, NULL }, - { "use_electrobinoculars", "Use electro binoculars item", IN_GenCMD16, NULL }, - { "zoom", "Use binoculars item", IN_GenCMD17, NULL }, - { "use_sentry", "Use sentry gun item", IN_GenCMD18, NULL }, - { "saberAttackCycle", "Switch lightsaber attack styles", IN_GenCMD19, NULL }, - { "force_throw", "Use push force power", IN_GenCMD20, NULL }, - { "use_jetpack", "Use jetpack item", IN_GenCMD21, NULL }, - { "use_bactabig", "Use big bacta item", IN_GenCMD22, NULL }, - { "use_healthdisp", "Use health dispenser item", IN_GenCMD23, NULL }, - { "use_ammodisp", "Use ammo dispenser item", IN_GenCMD24, NULL }, - { "use_eweb", "Use e-web item", IN_GenCMD25, NULL }, - { "use_cloak", "Use cloaking item", IN_GenCMD26, NULL }, - { "taunt", "Taunt", IN_GenCMD27, NULL }, - { "bow", "Bow", IN_GenCMD28, NULL }, - { "meditate", "Meditate", IN_GenCMD29, NULL }, - { "flourish", "Flourish", IN_GenCMD30, NULL }, - { "gloat", "Gloat", IN_GenCMD31, NULL }, - { "useGivenForce", "Use specified force power", IN_UseGivenForce, NULL }, - { "automap_button", "Show/hide automap", IN_AutoMapButton, NULL }, - { "automap_toggle", "Show/hide radar", IN_AutoMapToggle, NULL }, - { "voicechat", "Open voice chat menu", IN_VoiceChatButton, NULL }, - { NULL, NULL, NULL, NULL } -}; +static const cmdList_t inputCmds[] = {{"centerview", "Centers view on screen", IN_CenterView, NULL}, + {"+moveup", "Jump", IN_UpDown, NULL}, + {"-moveup", NULL, IN_UpUp, NULL}, + {"+movedown", "Crouch", IN_DownDown, NULL}, + {"-movedown", NULL, IN_DownUp, NULL}, + {"+left", "Rotate camera left", IN_LeftDown, NULL}, + {"-left", NULL, IN_LeftUp, NULL}, + {"+right", "Rotate camera right", IN_RightDown, NULL}, + {"-right", NULL, IN_RightUp, NULL}, + {"+forward", "Move forward", IN_ForwardDown, NULL}, + {"-forward", NULL, IN_ForwardUp, NULL}, + {"+back", "Move backward", IN_BackDown, NULL}, + {"-back", NULL, IN_BackUp, NULL}, + {"+lookup", "Tilt camera up", IN_LookupDown, NULL}, + {"-lookup", NULL, IN_LookupUp, NULL}, + {"+lookdown", "Tilt camera down", IN_LookdownDown, NULL}, + {"-lookdown", NULL, IN_LookdownUp, NULL}, + {"+strafe", "Hold to strafe", IN_StrafeDown, NULL}, + {"-strafe", NULL, IN_StrafeUp, NULL}, + {"+moveleft", "Strafe left", IN_MoveleftDown, NULL}, + {"-moveleft", NULL, IN_MoveleftUp, NULL}, + {"+moveright", "Strafe right", IN_MoverightDown, NULL}, + {"-moveright", NULL, IN_MoverightUp, NULL}, + {"+speed", "Walk or run", IN_SpeedDown, NULL}, + {"-speed", NULL, IN_SpeedUp, NULL}, + {"+attack", "Primary Attack", IN_Button0Down, NULL}, + {"-attack", NULL, IN_Button0Up, NULL}, + {"+use", "Use item", IN_Button5Down, NULL}, + {"-use", NULL, IN_Button5Up, NULL}, + {"+force_grip", "Hold to use grip force power", IN_Button6Down, NULL}, + {"-force_grip", NULL, IN_Button6Up, NULL}, + {"+altattack", "Alternate Attack", IN_Button7Down, NULL}, + {"-altattack", NULL, IN_Button7Up, NULL}, + {"+useforce", "Use selected force power", IN_Button9Down, NULL}, + {"-useforce", NULL, IN_Button9Up, NULL}, + {"+force_lightning", "Hold to use lightning force power", IN_Button10Down, NULL}, + {"-force_lightning", NULL, IN_Button10Up, NULL}, + {"+force_drain", "Hold to use drain force power", IN_Button11Down, NULL}, + {"-force_drain", NULL, IN_Button11Up, NULL}, + {"+button0", "Button 0", IN_Button0Down, NULL}, + {"-button0", NULL, IN_Button0Up, NULL}, + {"+button1", "Button 1", IN_Button1Down, NULL}, + {"-button1", NULL, IN_Button1Up, NULL}, + {"+button2", "Button 2", IN_Button2Down, NULL}, + {"-button2", NULL, IN_Button2Up, NULL}, + {"+button3", "Button 3", IN_Button3Down, NULL}, + {"-button3", NULL, IN_Button3Up, NULL}, + {"+button4", "Button 4", IN_Button4Down, NULL}, + {"-button4", NULL, IN_Button4Up, NULL}, + {"+button5", "Button 5", IN_Button5Down, NULL}, + {"-button5", NULL, IN_Button5Up, NULL}, + {"+button6", "Button 6", IN_Button6Down, NULL}, + {"-button6", NULL, IN_Button6Up, NULL}, + {"+button7", "Button 7", IN_Button7Down, NULL}, + {"-button7", NULL, IN_Button7Up, NULL}, + {"+button8", "Button 8", IN_Button8Down, NULL}, + {"-button8", NULL, IN_Button8Up, NULL}, + {"+button9", "Button 9", IN_Button9Down, NULL}, + {"-button9", NULL, IN_Button9Up, NULL}, + {"+button10", "Button 10", IN_Button10Down, NULL}, + {"-button10", NULL, IN_Button10Up, NULL}, + {"+button11", "Button 11", IN_Button11Down, NULL}, + {"-button11", NULL, IN_Button11Up, NULL}, + {"+button12", "Button 12", IN_Button12Down, NULL}, + {"-button12", NULL, IN_Button12Up, NULL}, + {"+button13", "Button 13", IN_Button13Down, NULL}, + {"-button13", NULL, IN_Button13Up, NULL}, + {"+button14", "Button 14", IN_Button14Down, NULL}, + {"-button14", NULL, IN_Button14Up, NULL}, + {"+button15", "Button 15", IN_Button15Down, NULL}, + {"-button15", NULL, IN_Button15Up, NULL}, + {"+mlook", "Hold to use mouse look", IN_MLookDown, NULL}, + {"-mlook", NULL, IN_MLookUp, NULL}, + {"sv_saberswitch", "Holster/activate lightsaber", IN_GenCMD1, NULL}, + {"engage_duel", "Engage private duel", IN_GenCMD2, NULL}, + {"force_heal", "Use heal force power", IN_GenCMD3, NULL}, + {"force_speed", "Activate speed force power", IN_GenCMD4, NULL}, + {"force_pull", "Use pull force power", IN_GenCMD5, NULL}, + {"force_distract", "Activate mind trick force power", IN_GenCMD6, NULL}, + {"force_rage", "Activate rage force power", IN_GenCMD7, NULL}, + {"force_protect", "Activate protect force power", IN_GenCMD8, NULL}, + {"force_absorb", "Activate absorb force power", IN_GenCMD9, NULL}, + {"force_healother", "Use team heal force power", IN_GenCMD10, NULL}, + {"force_forcepowerother", "Use team energize force power", IN_GenCMD11, NULL}, + {"force_seeing", "Activate seeing force power", IN_GenCMD12, NULL}, + {"use_seeker", "Use seeker drone item", IN_GenCMD13, NULL}, + {"use_field", "Use forcefield item", IN_GenCMD14, NULL}, + {"use_bacta", "Use bacta item", IN_GenCMD15, NULL}, + {"use_electrobinoculars", "Use electro binoculars item", IN_GenCMD16, NULL}, + {"zoom", "Use binoculars item", IN_GenCMD17, NULL}, + {"use_sentry", "Use sentry gun item", IN_GenCMD18, NULL}, + {"saberAttackCycle", "Switch lightsaber attack styles", IN_GenCMD19, NULL}, + {"force_throw", "Use push force power", IN_GenCMD20, NULL}, + {"use_jetpack", "Use jetpack item", IN_GenCMD21, NULL}, + {"use_bactabig", "Use big bacta item", IN_GenCMD22, NULL}, + {"use_healthdisp", "Use health dispenser item", IN_GenCMD23, NULL}, + {"use_ammodisp", "Use ammo dispenser item", IN_GenCMD24, NULL}, + {"use_eweb", "Use e-web item", IN_GenCMD25, NULL}, + {"use_cloak", "Use cloaking item", IN_GenCMD26, NULL}, + {"taunt", "Taunt", IN_GenCMD27, NULL}, + {"bow", "Bow", IN_GenCMD28, NULL}, + {"meditate", "Meditate", IN_GenCMD29, NULL}, + {"flourish", "Flourish", IN_GenCMD30, NULL}, + {"gloat", "Gloat", IN_GenCMD31, NULL}, + {"useGivenForce", "Use specified force power", IN_UseGivenForce, NULL}, + {"automap_button", "Show/hide automap", IN_AutoMapButton, NULL}, + {"automap_toggle", "Show/hide radar", IN_AutoMapToggle, NULL}, + {"voicechat", "Open voice chat menu", IN_VoiceChatButton, NULL}, + {NULL, NULL, NULL, NULL}}; /* ============ CL_InitInput ============ */ -void CL_InitInput( void ) { - Cmd_AddCommandList( inputCmds ); +void CL_InitInput(void) { + Cmd_AddCommandList(inputCmds); - cl_nodelta = Cvar_Get ("cl_nodelta", "0", 0); - cl_debugMove = Cvar_Get ("cl_debugMove", "0", 0); + cl_nodelta = Cvar_Get("cl_nodelta", "0", 0); + cl_debugMove = Cvar_Get("cl_debugMove", "0", 0); } /* @@ -1770,6 +1562,4 @@ void CL_InitInput( void ) { CL_ShutdownInput ============ */ -void CL_ShutdownInput( void ) { - Cmd_RemoveCommandList( inputCmds ); -} +void CL_ShutdownInput(void) { Cmd_RemoveCommandList(inputCmds); } diff --git a/codemp/client/cl_keys.cpp b/codemp/client/cl_keys.cpp index 294b9c3053..6a709d3c98 100644 --- a/codemp/client/cl_keys.cpp +++ b/codemp/client/cl_keys.cpp @@ -33,356 +33,351 @@ key up events are sent even if in console mode */ // console -field_t g_consoleField; -int nextHistoryLine; // the last line in the history buffer, not masked -int historyLine; // the line being displayed from history buffer will be <= nextHistoryLine -field_t historyEditLines[COMMAND_HISTORY]; +field_t g_consoleField; +int nextHistoryLine; // the last line in the history buffer, not masked +int historyLine; // the line being displayed from history buffer will be <= nextHistoryLine +field_t historyEditLines[COMMAND_HISTORY]; // chat -field_t chatField; -qboolean chat_team; -int chat_playerNum; +field_t chatField; +qboolean chat_team; +int chat_playerNum; -keyGlobals_t kg; +keyGlobals_t kg; // do NOT blithely change any of the key names (3rd field) here, since they have to match the key binds // in the CFG files, they're also prepended with "KEYNAME_" when looking up StringEd references // -keyname_t keynames[MAX_KEYS] = -{ - { 0x00, 0x00, NULL, A_NULL, false }, - { 0x01, 0x01, "SHIFT", A_SHIFT, false }, - { 0x02, 0x02, "CTRL", A_CTRL, false }, - { 0x03, 0x03, "ALT", A_ALT, false }, - { 0x04, 0x04, "CAPSLOCK", A_CAPSLOCK, false }, - { 0x05, 0x05, "KP_NUMLOCK", A_NUMLOCK, false }, - { 0x06, 0x06, "SCROLLLOCK", A_SCROLLLOCK, false }, - { 0x07, 0x07, "PAUSE", A_PAUSE, false }, - { 0x08, 0x08, "BACKSPACE", A_BACKSPACE, false }, - { 0x09, 0x09, "TAB", A_TAB, false }, - { 0x0a, 0x0a, "ENTER", A_ENTER, false }, - { 0x0b, 0x0b, "KP_PLUS", A_KP_PLUS, false }, - { 0x0c, 0x0c, "KP_MINUS", A_KP_MINUS, false }, - { 0x0d, 0x0d, "KP_ENTER", A_KP_ENTER, false }, - { 0x0e, 0x0e, "KP_DEL", A_KP_PERIOD, false }, - { 0x0f, 0x0f, NULL, A_PRINTSCREEN, false }, - { 0x10, 0x10, "KP_INS", A_KP_0, false }, - { 0x11, 0x11, "KP_END", A_KP_1, false }, - { 0x12, 0x12, "KP_DOWNARROW", A_KP_2, false }, - { 0x13, 0x13, "KP_PGDN", A_KP_3, false }, - { 0x14, 0x14, "KP_LEFTARROW", A_KP_4, false }, - { 0x15, 0x15, "KP_5", A_KP_5, false }, - { 0x16, 0x16, "KP_RIGHTARROW", A_KP_6, false }, - { 0x17, 0x17, "KP_HOME", A_KP_7, false }, - { 0x18, 0x18, "KP_UPARROW", A_KP_8, false }, - { 0x19, 0x19, "KP_PGUP", A_KP_9, false }, - { 0x1a, 0x1a, "CONSOLE", A_CONSOLE, false }, - { 0x1b, 0x1b, "ESCAPE", A_ESCAPE, false }, - { 0x1c, 0x1c, "F1", A_F1, true }, - { 0x1d, 0x1d, "F2", A_F2, true }, - { 0x1e, 0x1e, "F3", A_F3, true }, - { 0x1f, 0x1f, "F4", A_F4, true }, - - { 0x20, 0x20, "SPACE", A_SPACE, false }, - { (word)'!', (word)'!', NULL, A_PLING, false }, - { (word)'"', (word)'"', NULL, A_DOUBLE_QUOTE, false }, - { (word)'#', (word)'#', NULL, A_HASH, false }, - { (word)'$', (word)'$', NULL, A_STRING, false }, - { (word)'%', (word)'%', NULL, A_PERCENT, false }, - { (word)'&', (word)'&', NULL, A_AND, false }, - { 0x27, 0x27, NULL, A_SINGLE_QUOTE, false }, - { (word)'(', (word)'(', NULL, A_OPEN_BRACKET, false }, - { (word)')', (word)')', NULL, A_CLOSE_BRACKET, false }, - { (word)'*', (word)'*', NULL, A_STAR, false }, - { (word)'+', (word)'+', NULL, A_PLUS, false }, - { (word)',', (word)',', NULL, A_COMMA, false }, - { (word)'-', (word)'-', NULL, A_MINUS, false }, - { (word)'.', (word)'.', NULL, A_PERIOD, false }, - { (word)'/', (word)'/', NULL, A_FORWARD_SLASH, false }, - { (word)'0', (word)'0', NULL, A_0, false }, - { (word)'1', (word)'1', NULL, A_1, false }, - { (word)'2', (word)'2', NULL, A_2, false }, - { (word)'3', (word)'3', NULL, A_3, false }, - { (word)'4', (word)'4', NULL, A_4, false }, - { (word)'5', (word)'5', NULL, A_5, false }, - { (word)'6', (word)'6', NULL, A_6, false }, - { (word)'7', (word)'7', NULL, A_7, false }, - { (word)'8', (word)'8', NULL, A_8, false }, - { (word)'9', (word)'9', NULL, A_9, false }, - { (word)':', (word)':', NULL, A_COLON, false }, - { (word)';', (word)';', "SEMICOLON", A_SEMICOLON, false }, - { (word)'<', (word)'<', NULL, A_LESSTHAN, false }, - { (word)'=', (word)'=', NULL, A_EQUALS, false }, - { (word)'>', (word)'>', NULL, A_GREATERTHAN, false }, - { (word)'?', (word)'?', NULL, A_QUESTION, false }, - - { (word)'@', (word)'@', NULL, A_AT, false }, - { (word)'A', (word)'a', NULL, A_CAP_A, false }, - { (word)'B', (word)'b', NULL, A_CAP_B, false }, - { (word)'C', (word)'c', NULL, A_CAP_C, false }, - { (word)'D', (word)'d', NULL, A_CAP_D, false }, - { (word)'E', (word)'e', NULL, A_CAP_E, false }, - { (word)'F', (word)'f', NULL, A_CAP_F, false }, - { (word)'G', (word)'g', NULL, A_CAP_G, false }, - { (word)'H', (word)'h', NULL, A_CAP_H, false }, - { (word)'I', (word)'i', NULL, A_CAP_I, false }, - { (word)'J', (word)'j', NULL, A_CAP_J, false }, - { (word)'K', (word)'k', NULL, A_CAP_K, false }, - { (word)'L', (word)'l', NULL, A_CAP_L, false }, - { (word)'M', (word)'m', NULL, A_CAP_M, false }, - { (word)'N', (word)'n', NULL, A_CAP_N, false }, - { (word)'O', (word)'o', NULL, A_CAP_O, false }, - { (word)'P', (word)'p', NULL, A_CAP_P, false }, - { (word)'Q', (word)'q', NULL, A_CAP_Q, false }, - { (word)'R', (word)'r', NULL, A_CAP_R, false }, - { (word)'S', (word)'s', NULL, A_CAP_S, false }, - { (word)'T', (word)'t', NULL, A_CAP_T, false }, - { (word)'U', (word)'u', NULL, A_CAP_U, false }, - { (word)'V', (word)'v', NULL, A_CAP_V, false }, - { (word)'W', (word)'w', NULL, A_CAP_W, false }, - { (word)'X', (word)'x', NULL, A_CAP_X, false }, - { (word)'Y', (word)'y', NULL, A_CAP_Y, false }, - { (word)'Z', (word)'z', NULL, A_CAP_Z, false }, - { (word)'[', (word)'[', NULL, A_OPEN_SQUARE, false }, - { 0x5c, 0x5c, NULL, A_BACKSLASH, false }, - { (word)']', (word)']', NULL, A_CLOSE_SQUARE, false }, - { (word)'^', (word)'^', NULL, A_CARET, false }, - { (word)'_', (word)'_', NULL, A_UNDERSCORE, false }, - - { 0x60, 0x60, NULL, A_LEFT_SINGLE_QUOTE, false }, - { (word)'A', (word)'a', NULL, A_LOW_A, false }, - { (word)'B', (word)'b', NULL, A_LOW_B, false }, - { (word)'C', (word)'c', NULL, A_LOW_C, false }, - { (word)'D', (word)'d', NULL, A_LOW_D, false }, - { (word)'E', (word)'e', NULL, A_LOW_E, false }, - { (word)'F', (word)'f', NULL, A_LOW_F, false }, - { (word)'G', (word)'g', NULL, A_LOW_G, false }, - { (word)'H', (word)'h', NULL, A_LOW_H, false }, - { (word)'I', (word)'i', NULL, A_LOW_I, false }, - { (word)'J', (word)'j', NULL, A_LOW_J, false }, - { (word)'K', (word)'k', NULL, A_LOW_K, false }, - { (word)'L', (word)'l', NULL, A_LOW_L, false }, - { (word)'M', (word)'m', NULL, A_LOW_M, false }, - { (word)'N', (word)'n', NULL, A_LOW_N, false }, - { (word)'O', (word)'o', NULL, A_LOW_O, false }, - { (word)'P', (word)'p', NULL, A_LOW_P, false }, - { (word)'Q', (word)'q', NULL, A_LOW_Q, false }, - { (word)'R', (word)'r', NULL, A_LOW_R, false }, - { (word)'S', (word)'s', NULL, A_LOW_S, false }, - { (word)'T', (word)'t', NULL, A_LOW_T, false }, - { (word)'U', (word)'u', NULL, A_LOW_U, false }, - { (word)'V', (word)'v', NULL, A_LOW_V, false }, - { (word)'W', (word)'w', NULL, A_LOW_W, false }, - { (word)'X', (word)'x', NULL, A_LOW_X, false }, - { (word)'Y', (word)'y', NULL, A_LOW_Y, false }, - { (word)'Z', (word)'z', NULL, A_LOW_Z, false }, - { (word)'{', (word)'{', NULL, A_OPEN_BRACE, false }, - { (word)'|', (word)'|', NULL, A_BAR, false }, - { (word)'}', (word)'}', NULL, A_CLOSE_BRACE, false }, - { (word)'~', (word)'~', NULL, A_TILDE, false }, - { 0x7f, 0x7f, "DEL", A_DELETE, false }, - - { 0x80, 0x80, "EURO", A_EURO, false }, - { 0x81, 0x81, "SHIFT", A_SHIFT2, false }, - { 0x82, 0x82, "CTRL", A_CTRL2, false }, - { 0x83, 0x83, "ALT", A_ALT2, false }, - { 0x84, 0x84, "F5", A_F5, true }, - { 0x85, 0x85, "F6", A_F6, true }, - { 0x86, 0x86, "F7", A_F7, true }, - { 0x87, 0x87, "F8", A_F8, true }, - { 0x88, 0x88, "CIRCUMFLEX", A_CIRCUMFLEX, false }, - { 0x89, 0x89, "MWHEELUP", A_MWHEELUP, false }, - { 0x8a, 0x9a, NULL, A_CAP_SCARON, false }, // ****** - { 0x8b, 0x8b, "MWHEELDOWN", A_MWHEELDOWN, false }, - { 0x8c, 0x9c, NULL, A_CAP_OE, false }, // ****** - { 0x8d, 0x8d, "MOUSE1", A_MOUSE1, false }, - { 0x8e, 0x8e, "MOUSE2", A_MOUSE2, false }, - { 0x8f, 0x8f, "INS", A_INSERT, false }, - { 0x90, 0x90, "HOME", A_HOME, false }, - { 0x91, 0x91, "PGUP", A_PAGE_UP, false }, - { 0x92, 0x92, NULL, A_RIGHT_SINGLE_QUOTE, false }, - { 0x93, 0x93, NULL, A_LEFT_DOUBLE_QUOTE, false }, - { 0x94, 0x94, NULL, A_RIGHT_DOUBLE_QUOTE, false }, - { 0x95, 0x95, "F9", A_F9, true }, - { 0x96, 0x96, "F10", A_F10, true }, - { 0x97, 0x97, "F11", A_F11, true }, - { 0x98, 0x98, "F12", A_F12, true }, - { 0x99, 0x99, NULL, A_TRADEMARK, false }, - { 0x8a, 0x9a, NULL, A_LOW_SCARON, false }, // ****** - { 0x9b, 0x9b, "SHIFT_ENTER", A_ENTER, false }, - { 0x8c, 0x9c, NULL, A_LOW_OE, false }, // ****** - { 0x9d, 0x9d, "END", A_END, false }, - { 0x9e, 0x9e, "PGDN", A_PAGE_DOWN, false }, - { 0x9f, 0xff, NULL, A_CAP_YDIERESIS, false }, // ****** - - { 0xa0, 0, "SHIFT_SPACE", A_SPACE, false }, - { 0xa1, 0xa1, NULL, A_EXCLAMDOWN, false }, // upside down '!' - undisplayable - { L'\u00A2', L'\u00A2', NULL, A_CENT, false }, // cent sign - { L'\u00A3', L'\u00A3', NULL, A_POUND, false }, // pound (as in currency) symbol - { 0xa4, 0, "SHIFT_KP_ENTER", A_KP_ENTER, false }, - { L'\u00A5', L'\u00A5', NULL, A_YEN, false }, // yen symbol - { 0xa6, 0xa6, "MOUSE3", A_MOUSE3, false }, - { 0xa7, 0xa7, "MOUSE4", A_MOUSE4, false }, - { 0xa8, 0xa8, "MOUSE5", A_MOUSE5, false }, - { L'\u00A9', L'\u00A9', NULL, A_COPYRIGHT, false }, // copyright symbol - { 0xaa, 0xaa, "UPARROW", A_CURSOR_UP, false }, - { 0xab, 0xab, "DOWNARROW", A_CURSOR_DOWN, false }, - { 0xac, 0xac, "LEFTARROW", A_CURSOR_LEFT, false }, - { 0xad, 0xad, "RIGHTARROW", A_CURSOR_RIGHT, false }, - { L'\u00AE', L'\u00AE', NULL, A_REGISTERED, false }, // registered trademark symbol - { 0xaf, 0, NULL, A_UNDEFINED_7, false }, - { 0xb0, 0, NULL, A_UNDEFINED_8, false }, - { 0xb1, 0, NULL, A_UNDEFINED_9, false }, - { 0xb2, 0, NULL, A_UNDEFINED_10, false }, - { 0xb3, 0, NULL, A_UNDEFINED_11, false }, - { 0xb4, 0, NULL, A_UNDEFINED_12, false }, - { 0xb5, 0, NULL, A_UNDEFINED_13, false }, - { 0xb6, 0, NULL, A_UNDEFINED_14, false }, - { 0xb7, 0, NULL, A_UNDEFINED_15, false }, - { 0xb8, 0, NULL, A_UNDEFINED_16, false }, - { 0xb9, 0, NULL, A_UNDEFINED_17, false }, - { 0xba, 0, NULL, A_UNDEFINED_18, false }, - { 0xbb, 0, NULL, A_UNDEFINED_19, false }, - { 0xbc, 0, NULL, A_UNDEFINED_20, false }, - { 0xbd, 0, NULL, A_UNDEFINED_21, false }, - { 0xbe, 0, NULL, A_UNDEFINED_22, false }, - { L'\u00BF', L'\u00BF', NULL, A_QUESTION_DOWN, false }, // upside-down question mark - - { L'\u00C0', L'\u00E0', NULL, A_CAP_AGRAVE, false }, - { L'\u00C1', L'\u00E1', NULL, A_CAP_AACUTE, false }, - { L'\u00C2', L'\u00E2', NULL, A_CAP_ACIRCUMFLEX, false }, - { L'\u00C3', L'\u00E3', NULL, A_CAP_ATILDE, false }, - { L'\u00C4', L'\u00E4', NULL, A_CAP_ADIERESIS, false }, - { L'\u00C5', L'\u00E5', NULL, A_CAP_ARING, false }, - { L'\u00C6', L'\u00E6', NULL, A_CAP_AE, false }, - { L'\u00C7', L'\u00E7', NULL, A_CAP_CCEDILLA, false }, - { L'\u00C8', L'\u00E8', NULL, A_CAP_EGRAVE, false }, - { L'\u00C9', L'\u00E9', NULL, A_CAP_EACUTE, false }, - { L'\u00CA', L'\u00EA', NULL, A_CAP_ECIRCUMFLEX, false }, - { L'\u00CB', L'\u00EB', NULL, A_CAP_EDIERESIS, false }, - { L'\u00CC', L'\u00EC', NULL, A_CAP_IGRAVE, false }, - { L'\u00CD', L'\u00ED', NULL, A_CAP_IACUTE, false }, - { L'\u00CE', L'\u00EE', NULL, A_CAP_ICIRCUMFLEX, false }, - { L'\u00CF', L'\u00EF', NULL, A_CAP_IDIERESIS, false }, - { L'\u00D0', L'\u00F0', NULL, A_CAP_ETH, false }, - { L'\u00D1', L'\u00F1', NULL, A_CAP_NTILDE, false }, - { L'\u00D2', L'\u00F2', NULL, A_CAP_OGRAVE, false }, - { L'\u00D3', L'\u00F3', NULL, A_CAP_OACUTE, false }, - { L'\u00D4', L'\u00F4', NULL, A_CAP_OCIRCUMFLEX, false }, - { L'\u00D5', L'\u00F5', NULL, A_CAP_OTILDE, false }, - { L'\u00D6', L'\u00F6', NULL, A_CAP_ODIERESIS, false }, - { L'\u00D7', L'\u00D7', "KP_STAR", A_MULTIPLY, false }, - { L'\u00D8', L'\u00F8', NULL, A_CAP_OSLASH, false }, - { L'\u00D9', L'\u00F9', NULL, A_CAP_UGRAVE, false }, - { L'\u00DA', L'\u00FA', NULL, A_CAP_UACUTE, false }, - { L'\u00DB', L'\u00FB', NULL, A_CAP_UCIRCUMFLEX, false }, - { L'\u00DC', L'\u00FC', NULL, A_CAP_UDIERESIS, false }, - { L'\u00DD', L'\u00FD', NULL, A_CAP_YACUTE, false }, - { L'\u00DE', L'\u00FE', NULL, A_CAP_THORN, false }, - { L'\u00DF', L'\u00DF', NULL, A_GERMANDBLS, false }, - - { L'\u00C0', L'\u00E0', NULL, A_LOW_AGRAVE, false }, - { L'\u00C1', L'\u00E1', NULL, A_LOW_AACUTE, false }, - { L'\u00C2', L'\u00E2', NULL, A_LOW_ACIRCUMFLEX, false }, - { L'\u00C3', L'\u00E3', NULL, A_LOW_ATILDE, false }, - { L'\u00C4', L'\u00E4', NULL, A_LOW_ADIERESIS, false }, - { L'\u00C5', L'\u00E5', NULL, A_LOW_ARING, false }, - { L'\u00C6', L'\u00E6', NULL, A_LOW_AE, false }, - { L'\u00C7', L'\u00E7', NULL, A_LOW_CCEDILLA, false }, - { L'\u00C8', L'\u00E8', NULL, A_LOW_EGRAVE, false }, - { L'\u00C9', L'\u00E9', NULL, A_LOW_EACUTE, false }, - { L'\u00CA', L'\u00EA', NULL, A_LOW_ECIRCUMFLEX, false }, - { L'\u00CB', L'\u00EB', NULL, A_LOW_EDIERESIS, false }, - { L'\u00CC', L'\u00EC', NULL, A_LOW_IGRAVE, false }, - { L'\u00CD', L'\u00ED', NULL, A_LOW_IACUTE, false }, - { L'\u00CE', L'\u00EE', NULL, A_LOW_ICIRCUMFLEX, false }, - { L'\u00CF', L'\u00EF', NULL, A_LOW_IDIERESIS, false }, - { L'\u00D0', L'\u00F0', NULL, A_LOW_ETH, false }, - { L'\u00D1', L'\u00F1', NULL, A_LOW_NTILDE, false }, - { L'\u00D2', L'\u00F2', NULL, A_LOW_OGRAVE, false }, - { L'\u00D3', L'\u00F3', NULL, A_LOW_OACUTE, false }, - { L'\u00D4', L'\u00F4', NULL, A_LOW_OCIRCUMFLEX, false }, - { L'\u00D5', L'\u00F5', NULL, A_LOW_OTILDE, false }, - { L'\u00D6', L'\u00F6', NULL, A_LOW_ODIERESIS, false }, - { L'\u00F7', L'\u00F7', "KP_SLASH", A_DIVIDE, false }, - { L'\u00D8', L'\u00F8', NULL, A_LOW_OSLASH, false }, - { L'\u00D9', L'\u00F9', NULL, A_LOW_UGRAVE, false }, - { L'\u00DA', L'\u00FA', NULL, A_LOW_UACUTE, false }, - { L'\u00DB', L'\u00FB', NULL, A_LOW_UCIRCUMFLEX, false }, - { L'\u00DC', L'\u00FC', NULL, A_LOW_UDIERESIS, false }, - { L'\u00DD', L'\u00FD', NULL, A_LOW_YACUTE, false }, - { L'\u00DE', L'\u00FE', NULL, A_LOW_THORN, false }, - { 0x9f, 0xff, NULL, A_LOW_YDIERESIS, false }, // ******* - - { 0x100, 0x100, "JOY0", A_JOY0, false }, - { 0x101, 0x101, "JOY1", A_JOY1, false }, - { 0x102, 0x102, "JOY2", A_JOY2, false }, - { 0x103, 0x103, "JOY3", A_JOY3, false }, - { 0x104, 0x104, "JOY4", A_JOY4, false }, - { 0x105, 0x105, "JOY5", A_JOY5, false }, - { 0x106, 0x106, "JOY6", A_JOY6, false }, - { 0x107, 0x107, "JOY7", A_JOY7, false }, - { 0x108, 0x108, "JOY8", A_JOY8, false }, - { 0x109, 0x109, "JOY9", A_JOY9, false }, - { 0x10a, 0x10a, "JOY10", A_JOY10, false }, - { 0x10b, 0x10b, "JOY11", A_JOY11, false }, - { 0x10c, 0x10c, "JOY12", A_JOY12, false }, - { 0x10d, 0x10d, "JOY13", A_JOY13, false }, - { 0x10e, 0x10e, "JOY14", A_JOY14, false }, - { 0x10f, 0x10f, "JOY15", A_JOY15, false }, - { 0x110, 0x110, "JOY16", A_JOY16, false }, - { 0x111, 0x111, "JOY17", A_JOY17, false }, - { 0x112, 0x112, "JOY18", A_JOY18, false }, - { 0x113, 0x113, "JOY19", A_JOY19, false }, - { 0x114, 0x114, "JOY20", A_JOY20, false }, - { 0x115, 0x115, "JOY21", A_JOY21, false }, - { 0x116, 0x116, "JOY22", A_JOY22, false }, - { 0x117, 0x117, "JOY23", A_JOY23, false }, - { 0x118, 0x118, "JOY24", A_JOY24, false }, - { 0x119, 0x119, "JOY25", A_JOY25, false }, - { 0x11a, 0x11a, "JOY26", A_JOY26, false }, - { 0x11b, 0x11b, "JOY27", A_JOY27, false }, - { 0x11c, 0x11c, "JOY28", A_JOY28, false }, - { 0x11d, 0x11d, "JOY29", A_JOY29, false }, - { 0x11e, 0x11e, "JOY30", A_JOY30, false }, - { 0x11f, 0x11f, "JOY31", A_JOY31, false }, - - { 0x120, 0x120, "AUX0", A_AUX0, false }, - { 0x121, 0x121, "AUX1", A_AUX1, false }, - { 0x122, 0x122, "AUX2", A_AUX2, false }, - { 0x123, 0x123, "AUX3", A_AUX3, false }, - { 0x124, 0x124, "AUX4", A_AUX4, false }, - { 0x125, 0x125, "AUX5", A_AUX5, false }, - { 0x126, 0x126, "AUX6", A_AUX6, false }, - { 0x127, 0x127, "AUX7", A_AUX7, false }, - { 0x128, 0x128, "AUX8", A_AUX8, false }, - { 0x129, 0x129, "AUX9", A_AUX9, false }, - { 0x12a, 0x12a, "AUX10", A_AUX10, false }, - { 0x12b, 0x12b, "AUX11", A_AUX11, false }, - { 0x12c, 0x12c, "AUX12", A_AUX12, false }, - { 0x12d, 0x12d, "AUX13", A_AUX13, false }, - { 0x12e, 0x12e, "AUX14", A_AUX14, false }, - { 0x12f, 0x12f, "AUX15", A_AUX15, false }, - { 0x130, 0x130, "AUX16", A_AUX16, false }, - { 0x131, 0x131, "AUX17", A_AUX17, false }, - { 0x132, 0x132, "AUX18", A_AUX18, false }, - { 0x133, 0x133, "AUX19", A_AUX19, false }, - { 0x134, 0x134, "AUX20", A_AUX20, false }, - { 0x135, 0x135, "AUX21", A_AUX21, false }, - { 0x136, 0x136, "AUX22", A_AUX22, false }, - { 0x137, 0x137, "AUX23", A_AUX23, false }, - { 0x138, 0x138, "AUX24", A_AUX24, false }, - { 0x139, 0x139, "AUX25", A_AUX25, false }, - { 0x13a, 0x13a, "AUX26", A_AUX26, false }, - { 0x13b, 0x13b, "AUX27", A_AUX27, false }, - { 0x13c, 0x13c, "AUX28", A_AUX28, false }, - { 0x13d, 0x13d, "AUX29", A_AUX29, false }, - { 0x13e, 0x13e, "AUX30", A_AUX30, false }, - { 0x13f, 0x13f, "AUX31", A_AUX31, false } -}; -static const size_t numKeynames = ARRAY_LEN( keynames ); - - +keyname_t keynames[MAX_KEYS] = {{0x00, 0x00, NULL, A_NULL, false}, + {0x01, 0x01, "SHIFT", A_SHIFT, false}, + {0x02, 0x02, "CTRL", A_CTRL, false}, + {0x03, 0x03, "ALT", A_ALT, false}, + {0x04, 0x04, "CAPSLOCK", A_CAPSLOCK, false}, + {0x05, 0x05, "KP_NUMLOCK", A_NUMLOCK, false}, + {0x06, 0x06, "SCROLLLOCK", A_SCROLLLOCK, false}, + {0x07, 0x07, "PAUSE", A_PAUSE, false}, + {0x08, 0x08, "BACKSPACE", A_BACKSPACE, false}, + {0x09, 0x09, "TAB", A_TAB, false}, + {0x0a, 0x0a, "ENTER", A_ENTER, false}, + {0x0b, 0x0b, "KP_PLUS", A_KP_PLUS, false}, + {0x0c, 0x0c, "KP_MINUS", A_KP_MINUS, false}, + {0x0d, 0x0d, "KP_ENTER", A_KP_ENTER, false}, + {0x0e, 0x0e, "KP_DEL", A_KP_PERIOD, false}, + {0x0f, 0x0f, NULL, A_PRINTSCREEN, false}, + {0x10, 0x10, "KP_INS", A_KP_0, false}, + {0x11, 0x11, "KP_END", A_KP_1, false}, + {0x12, 0x12, "KP_DOWNARROW", A_KP_2, false}, + {0x13, 0x13, "KP_PGDN", A_KP_3, false}, + {0x14, 0x14, "KP_LEFTARROW", A_KP_4, false}, + {0x15, 0x15, "KP_5", A_KP_5, false}, + {0x16, 0x16, "KP_RIGHTARROW", A_KP_6, false}, + {0x17, 0x17, "KP_HOME", A_KP_7, false}, + {0x18, 0x18, "KP_UPARROW", A_KP_8, false}, + {0x19, 0x19, "KP_PGUP", A_KP_9, false}, + {0x1a, 0x1a, "CONSOLE", A_CONSOLE, false}, + {0x1b, 0x1b, "ESCAPE", A_ESCAPE, false}, + {0x1c, 0x1c, "F1", A_F1, true}, + {0x1d, 0x1d, "F2", A_F2, true}, + {0x1e, 0x1e, "F3", A_F3, true}, + {0x1f, 0x1f, "F4", A_F4, true}, + + {0x20, 0x20, "SPACE", A_SPACE, false}, + {(word)'!', (word)'!', NULL, A_PLING, false}, + {(word)'"', (word)'"', NULL, A_DOUBLE_QUOTE, false}, + {(word)'#', (word)'#', NULL, A_HASH, false}, + {(word)'$', (word)'$', NULL, A_STRING, false}, + {(word)'%', (word)'%', NULL, A_PERCENT, false}, + {(word)'&', (word)'&', NULL, A_AND, false}, + {0x27, 0x27, NULL, A_SINGLE_QUOTE, false}, + {(word)'(', (word)'(', NULL, A_OPEN_BRACKET, false}, + {(word)')', (word)')', NULL, A_CLOSE_BRACKET, false}, + {(word)'*', (word)'*', NULL, A_STAR, false}, + {(word)'+', (word)'+', NULL, A_PLUS, false}, + {(word)',', (word)',', NULL, A_COMMA, false}, + {(word)'-', (word)'-', NULL, A_MINUS, false}, + {(word)'.', (word)'.', NULL, A_PERIOD, false}, + {(word)'/', (word)'/', NULL, A_FORWARD_SLASH, false}, + {(word)'0', (word)'0', NULL, A_0, false}, + {(word)'1', (word)'1', NULL, A_1, false}, + {(word)'2', (word)'2', NULL, A_2, false}, + {(word)'3', (word)'3', NULL, A_3, false}, + {(word)'4', (word)'4', NULL, A_4, false}, + {(word)'5', (word)'5', NULL, A_5, false}, + {(word)'6', (word)'6', NULL, A_6, false}, + {(word)'7', (word)'7', NULL, A_7, false}, + {(word)'8', (word)'8', NULL, A_8, false}, + {(word)'9', (word)'9', NULL, A_9, false}, + {(word)':', (word)':', NULL, A_COLON, false}, + {(word)';', (word)';', "SEMICOLON", A_SEMICOLON, false}, + {(word)'<', (word)'<', NULL, A_LESSTHAN, false}, + {(word)'=', (word)'=', NULL, A_EQUALS, false}, + {(word)'>', (word)'>', NULL, A_GREATERTHAN, false}, + {(word)'?', (word)'?', NULL, A_QUESTION, false}, + + {(word)'@', (word)'@', NULL, A_AT, false}, + {(word)'A', (word)'a', NULL, A_CAP_A, false}, + {(word)'B', (word)'b', NULL, A_CAP_B, false}, + {(word)'C', (word)'c', NULL, A_CAP_C, false}, + {(word)'D', (word)'d', NULL, A_CAP_D, false}, + {(word)'E', (word)'e', NULL, A_CAP_E, false}, + {(word)'F', (word)'f', NULL, A_CAP_F, false}, + {(word)'G', (word)'g', NULL, A_CAP_G, false}, + {(word)'H', (word)'h', NULL, A_CAP_H, false}, + {(word)'I', (word)'i', NULL, A_CAP_I, false}, + {(word)'J', (word)'j', NULL, A_CAP_J, false}, + {(word)'K', (word)'k', NULL, A_CAP_K, false}, + {(word)'L', (word)'l', NULL, A_CAP_L, false}, + {(word)'M', (word)'m', NULL, A_CAP_M, false}, + {(word)'N', (word)'n', NULL, A_CAP_N, false}, + {(word)'O', (word)'o', NULL, A_CAP_O, false}, + {(word)'P', (word)'p', NULL, A_CAP_P, false}, + {(word)'Q', (word)'q', NULL, A_CAP_Q, false}, + {(word)'R', (word)'r', NULL, A_CAP_R, false}, + {(word)'S', (word)'s', NULL, A_CAP_S, false}, + {(word)'T', (word)'t', NULL, A_CAP_T, false}, + {(word)'U', (word)'u', NULL, A_CAP_U, false}, + {(word)'V', (word)'v', NULL, A_CAP_V, false}, + {(word)'W', (word)'w', NULL, A_CAP_W, false}, + {(word)'X', (word)'x', NULL, A_CAP_X, false}, + {(word)'Y', (word)'y', NULL, A_CAP_Y, false}, + {(word)'Z', (word)'z', NULL, A_CAP_Z, false}, + {(word)'[', (word)'[', NULL, A_OPEN_SQUARE, false}, + {0x5c, 0x5c, NULL, A_BACKSLASH, false}, + {(word)']', (word)']', NULL, A_CLOSE_SQUARE, false}, + {(word)'^', (word)'^', NULL, A_CARET, false}, + {(word)'_', (word)'_', NULL, A_UNDERSCORE, false}, + + {0x60, 0x60, NULL, A_LEFT_SINGLE_QUOTE, false}, + {(word)'A', (word)'a', NULL, A_LOW_A, false}, + {(word)'B', (word)'b', NULL, A_LOW_B, false}, + {(word)'C', (word)'c', NULL, A_LOW_C, false}, + {(word)'D', (word)'d', NULL, A_LOW_D, false}, + {(word)'E', (word)'e', NULL, A_LOW_E, false}, + {(word)'F', (word)'f', NULL, A_LOW_F, false}, + {(word)'G', (word)'g', NULL, A_LOW_G, false}, + {(word)'H', (word)'h', NULL, A_LOW_H, false}, + {(word)'I', (word)'i', NULL, A_LOW_I, false}, + {(word)'J', (word)'j', NULL, A_LOW_J, false}, + {(word)'K', (word)'k', NULL, A_LOW_K, false}, + {(word)'L', (word)'l', NULL, A_LOW_L, false}, + {(word)'M', (word)'m', NULL, A_LOW_M, false}, + {(word)'N', (word)'n', NULL, A_LOW_N, false}, + {(word)'O', (word)'o', NULL, A_LOW_O, false}, + {(word)'P', (word)'p', NULL, A_LOW_P, false}, + {(word)'Q', (word)'q', NULL, A_LOW_Q, false}, + {(word)'R', (word)'r', NULL, A_LOW_R, false}, + {(word)'S', (word)'s', NULL, A_LOW_S, false}, + {(word)'T', (word)'t', NULL, A_LOW_T, false}, + {(word)'U', (word)'u', NULL, A_LOW_U, false}, + {(word)'V', (word)'v', NULL, A_LOW_V, false}, + {(word)'W', (word)'w', NULL, A_LOW_W, false}, + {(word)'X', (word)'x', NULL, A_LOW_X, false}, + {(word)'Y', (word)'y', NULL, A_LOW_Y, false}, + {(word)'Z', (word)'z', NULL, A_LOW_Z, false}, + {(word)'{', (word)'{', NULL, A_OPEN_BRACE, false}, + {(word)'|', (word)'|', NULL, A_BAR, false}, + {(word)'}', (word)'}', NULL, A_CLOSE_BRACE, false}, + {(word)'~', (word)'~', NULL, A_TILDE, false}, + {0x7f, 0x7f, "DEL", A_DELETE, false}, + + {0x80, 0x80, "EURO", A_EURO, false}, + {0x81, 0x81, "SHIFT", A_SHIFT2, false}, + {0x82, 0x82, "CTRL", A_CTRL2, false}, + {0x83, 0x83, "ALT", A_ALT2, false}, + {0x84, 0x84, "F5", A_F5, true}, + {0x85, 0x85, "F6", A_F6, true}, + {0x86, 0x86, "F7", A_F7, true}, + {0x87, 0x87, "F8", A_F8, true}, + {0x88, 0x88, "CIRCUMFLEX", A_CIRCUMFLEX, false}, + {0x89, 0x89, "MWHEELUP", A_MWHEELUP, false}, + {0x8a, 0x9a, NULL, A_CAP_SCARON, false}, // ****** + {0x8b, 0x8b, "MWHEELDOWN", A_MWHEELDOWN, false}, + {0x8c, 0x9c, NULL, A_CAP_OE, false}, // ****** + {0x8d, 0x8d, "MOUSE1", A_MOUSE1, false}, + {0x8e, 0x8e, "MOUSE2", A_MOUSE2, false}, + {0x8f, 0x8f, "INS", A_INSERT, false}, + {0x90, 0x90, "HOME", A_HOME, false}, + {0x91, 0x91, "PGUP", A_PAGE_UP, false}, + {0x92, 0x92, NULL, A_RIGHT_SINGLE_QUOTE, false}, + {0x93, 0x93, NULL, A_LEFT_DOUBLE_QUOTE, false}, + {0x94, 0x94, NULL, A_RIGHT_DOUBLE_QUOTE, false}, + {0x95, 0x95, "F9", A_F9, true}, + {0x96, 0x96, "F10", A_F10, true}, + {0x97, 0x97, "F11", A_F11, true}, + {0x98, 0x98, "F12", A_F12, true}, + {0x99, 0x99, NULL, A_TRADEMARK, false}, + {0x8a, 0x9a, NULL, A_LOW_SCARON, false}, // ****** + {0x9b, 0x9b, "SHIFT_ENTER", A_ENTER, false}, + {0x8c, 0x9c, NULL, A_LOW_OE, false}, // ****** + {0x9d, 0x9d, "END", A_END, false}, + {0x9e, 0x9e, "PGDN", A_PAGE_DOWN, false}, + {0x9f, 0xff, NULL, A_CAP_YDIERESIS, false}, // ****** + + {0xa0, 0, "SHIFT_SPACE", A_SPACE, false}, + {0xa1, 0xa1, NULL, A_EXCLAMDOWN, false}, // upside down '!' - undisplayable + {L'\u00A2', L'\u00A2', NULL, A_CENT, false}, // cent sign + {L'\u00A3', L'\u00A3', NULL, A_POUND, false}, // pound (as in currency) symbol + {0xa4, 0, "SHIFT_KP_ENTER", A_KP_ENTER, false}, + {L'\u00A5', L'\u00A5', NULL, A_YEN, false}, // yen symbol + {0xa6, 0xa6, "MOUSE3", A_MOUSE3, false}, + {0xa7, 0xa7, "MOUSE4", A_MOUSE4, false}, + {0xa8, 0xa8, "MOUSE5", A_MOUSE5, false}, + {L'\u00A9', L'\u00A9', NULL, A_COPYRIGHT, false}, // copyright symbol + {0xaa, 0xaa, "UPARROW", A_CURSOR_UP, false}, + {0xab, 0xab, "DOWNARROW", A_CURSOR_DOWN, false}, + {0xac, 0xac, "LEFTARROW", A_CURSOR_LEFT, false}, + {0xad, 0xad, "RIGHTARROW", A_CURSOR_RIGHT, false}, + {L'\u00AE', L'\u00AE', NULL, A_REGISTERED, false}, // registered trademark symbol + {0xaf, 0, NULL, A_UNDEFINED_7, false}, + {0xb0, 0, NULL, A_UNDEFINED_8, false}, + {0xb1, 0, NULL, A_UNDEFINED_9, false}, + {0xb2, 0, NULL, A_UNDEFINED_10, false}, + {0xb3, 0, NULL, A_UNDEFINED_11, false}, + {0xb4, 0, NULL, A_UNDEFINED_12, false}, + {0xb5, 0, NULL, A_UNDEFINED_13, false}, + {0xb6, 0, NULL, A_UNDEFINED_14, false}, + {0xb7, 0, NULL, A_UNDEFINED_15, false}, + {0xb8, 0, NULL, A_UNDEFINED_16, false}, + {0xb9, 0, NULL, A_UNDEFINED_17, false}, + {0xba, 0, NULL, A_UNDEFINED_18, false}, + {0xbb, 0, NULL, A_UNDEFINED_19, false}, + {0xbc, 0, NULL, A_UNDEFINED_20, false}, + {0xbd, 0, NULL, A_UNDEFINED_21, false}, + {0xbe, 0, NULL, A_UNDEFINED_22, false}, + {L'\u00BF', L'\u00BF', NULL, A_QUESTION_DOWN, false}, // upside-down question mark + + {L'\u00C0', L'\u00E0', NULL, A_CAP_AGRAVE, false}, + {L'\u00C1', L'\u00E1', NULL, A_CAP_AACUTE, false}, + {L'\u00C2', L'\u00E2', NULL, A_CAP_ACIRCUMFLEX, false}, + {L'\u00C3', L'\u00E3', NULL, A_CAP_ATILDE, false}, + {L'\u00C4', L'\u00E4', NULL, A_CAP_ADIERESIS, false}, + {L'\u00C5', L'\u00E5', NULL, A_CAP_ARING, false}, + {L'\u00C6', L'\u00E6', NULL, A_CAP_AE, false}, + {L'\u00C7', L'\u00E7', NULL, A_CAP_CCEDILLA, false}, + {L'\u00C8', L'\u00E8', NULL, A_CAP_EGRAVE, false}, + {L'\u00C9', L'\u00E9', NULL, A_CAP_EACUTE, false}, + {L'\u00CA', L'\u00EA', NULL, A_CAP_ECIRCUMFLEX, false}, + {L'\u00CB', L'\u00EB', NULL, A_CAP_EDIERESIS, false}, + {L'\u00CC', L'\u00EC', NULL, A_CAP_IGRAVE, false}, + {L'\u00CD', L'\u00ED', NULL, A_CAP_IACUTE, false}, + {L'\u00CE', L'\u00EE', NULL, A_CAP_ICIRCUMFLEX, false}, + {L'\u00CF', L'\u00EF', NULL, A_CAP_IDIERESIS, false}, + {L'\u00D0', L'\u00F0', NULL, A_CAP_ETH, false}, + {L'\u00D1', L'\u00F1', NULL, A_CAP_NTILDE, false}, + {L'\u00D2', L'\u00F2', NULL, A_CAP_OGRAVE, false}, + {L'\u00D3', L'\u00F3', NULL, A_CAP_OACUTE, false}, + {L'\u00D4', L'\u00F4', NULL, A_CAP_OCIRCUMFLEX, false}, + {L'\u00D5', L'\u00F5', NULL, A_CAP_OTILDE, false}, + {L'\u00D6', L'\u00F6', NULL, A_CAP_ODIERESIS, false}, + {L'\u00D7', L'\u00D7', "KP_STAR", A_MULTIPLY, false}, + {L'\u00D8', L'\u00F8', NULL, A_CAP_OSLASH, false}, + {L'\u00D9', L'\u00F9', NULL, A_CAP_UGRAVE, false}, + {L'\u00DA', L'\u00FA', NULL, A_CAP_UACUTE, false}, + {L'\u00DB', L'\u00FB', NULL, A_CAP_UCIRCUMFLEX, false}, + {L'\u00DC', L'\u00FC', NULL, A_CAP_UDIERESIS, false}, + {L'\u00DD', L'\u00FD', NULL, A_CAP_YACUTE, false}, + {L'\u00DE', L'\u00FE', NULL, A_CAP_THORN, false}, + {L'\u00DF', L'\u00DF', NULL, A_GERMANDBLS, false}, + + {L'\u00C0', L'\u00E0', NULL, A_LOW_AGRAVE, false}, + {L'\u00C1', L'\u00E1', NULL, A_LOW_AACUTE, false}, + {L'\u00C2', L'\u00E2', NULL, A_LOW_ACIRCUMFLEX, false}, + {L'\u00C3', L'\u00E3', NULL, A_LOW_ATILDE, false}, + {L'\u00C4', L'\u00E4', NULL, A_LOW_ADIERESIS, false}, + {L'\u00C5', L'\u00E5', NULL, A_LOW_ARING, false}, + {L'\u00C6', L'\u00E6', NULL, A_LOW_AE, false}, + {L'\u00C7', L'\u00E7', NULL, A_LOW_CCEDILLA, false}, + {L'\u00C8', L'\u00E8', NULL, A_LOW_EGRAVE, false}, + {L'\u00C9', L'\u00E9', NULL, A_LOW_EACUTE, false}, + {L'\u00CA', L'\u00EA', NULL, A_LOW_ECIRCUMFLEX, false}, + {L'\u00CB', L'\u00EB', NULL, A_LOW_EDIERESIS, false}, + {L'\u00CC', L'\u00EC', NULL, A_LOW_IGRAVE, false}, + {L'\u00CD', L'\u00ED', NULL, A_LOW_IACUTE, false}, + {L'\u00CE', L'\u00EE', NULL, A_LOW_ICIRCUMFLEX, false}, + {L'\u00CF', L'\u00EF', NULL, A_LOW_IDIERESIS, false}, + {L'\u00D0', L'\u00F0', NULL, A_LOW_ETH, false}, + {L'\u00D1', L'\u00F1', NULL, A_LOW_NTILDE, false}, + {L'\u00D2', L'\u00F2', NULL, A_LOW_OGRAVE, false}, + {L'\u00D3', L'\u00F3', NULL, A_LOW_OACUTE, false}, + {L'\u00D4', L'\u00F4', NULL, A_LOW_OCIRCUMFLEX, false}, + {L'\u00D5', L'\u00F5', NULL, A_LOW_OTILDE, false}, + {L'\u00D6', L'\u00F6', NULL, A_LOW_ODIERESIS, false}, + {L'\u00F7', L'\u00F7', "KP_SLASH", A_DIVIDE, false}, + {L'\u00D8', L'\u00F8', NULL, A_LOW_OSLASH, false}, + {L'\u00D9', L'\u00F9', NULL, A_LOW_UGRAVE, false}, + {L'\u00DA', L'\u00FA', NULL, A_LOW_UACUTE, false}, + {L'\u00DB', L'\u00FB', NULL, A_LOW_UCIRCUMFLEX, false}, + {L'\u00DC', L'\u00FC', NULL, A_LOW_UDIERESIS, false}, + {L'\u00DD', L'\u00FD', NULL, A_LOW_YACUTE, false}, + {L'\u00DE', L'\u00FE', NULL, A_LOW_THORN, false}, + {0x9f, 0xff, NULL, A_LOW_YDIERESIS, false}, // ******* + + {0x100, 0x100, "JOY0", A_JOY0, false}, + {0x101, 0x101, "JOY1", A_JOY1, false}, + {0x102, 0x102, "JOY2", A_JOY2, false}, + {0x103, 0x103, "JOY3", A_JOY3, false}, + {0x104, 0x104, "JOY4", A_JOY4, false}, + {0x105, 0x105, "JOY5", A_JOY5, false}, + {0x106, 0x106, "JOY6", A_JOY6, false}, + {0x107, 0x107, "JOY7", A_JOY7, false}, + {0x108, 0x108, "JOY8", A_JOY8, false}, + {0x109, 0x109, "JOY9", A_JOY9, false}, + {0x10a, 0x10a, "JOY10", A_JOY10, false}, + {0x10b, 0x10b, "JOY11", A_JOY11, false}, + {0x10c, 0x10c, "JOY12", A_JOY12, false}, + {0x10d, 0x10d, "JOY13", A_JOY13, false}, + {0x10e, 0x10e, "JOY14", A_JOY14, false}, + {0x10f, 0x10f, "JOY15", A_JOY15, false}, + {0x110, 0x110, "JOY16", A_JOY16, false}, + {0x111, 0x111, "JOY17", A_JOY17, false}, + {0x112, 0x112, "JOY18", A_JOY18, false}, + {0x113, 0x113, "JOY19", A_JOY19, false}, + {0x114, 0x114, "JOY20", A_JOY20, false}, + {0x115, 0x115, "JOY21", A_JOY21, false}, + {0x116, 0x116, "JOY22", A_JOY22, false}, + {0x117, 0x117, "JOY23", A_JOY23, false}, + {0x118, 0x118, "JOY24", A_JOY24, false}, + {0x119, 0x119, "JOY25", A_JOY25, false}, + {0x11a, 0x11a, "JOY26", A_JOY26, false}, + {0x11b, 0x11b, "JOY27", A_JOY27, false}, + {0x11c, 0x11c, "JOY28", A_JOY28, false}, + {0x11d, 0x11d, "JOY29", A_JOY29, false}, + {0x11e, 0x11e, "JOY30", A_JOY30, false}, + {0x11f, 0x11f, "JOY31", A_JOY31, false}, + + {0x120, 0x120, "AUX0", A_AUX0, false}, + {0x121, 0x121, "AUX1", A_AUX1, false}, + {0x122, 0x122, "AUX2", A_AUX2, false}, + {0x123, 0x123, "AUX3", A_AUX3, false}, + {0x124, 0x124, "AUX4", A_AUX4, false}, + {0x125, 0x125, "AUX5", A_AUX5, false}, + {0x126, 0x126, "AUX6", A_AUX6, false}, + {0x127, 0x127, "AUX7", A_AUX7, false}, + {0x128, 0x128, "AUX8", A_AUX8, false}, + {0x129, 0x129, "AUX9", A_AUX9, false}, + {0x12a, 0x12a, "AUX10", A_AUX10, false}, + {0x12b, 0x12b, "AUX11", A_AUX11, false}, + {0x12c, 0x12c, "AUX12", A_AUX12, false}, + {0x12d, 0x12d, "AUX13", A_AUX13, false}, + {0x12e, 0x12e, "AUX14", A_AUX14, false}, + {0x12f, 0x12f, "AUX15", A_AUX15, false}, + {0x130, 0x130, "AUX16", A_AUX16, false}, + {0x131, 0x131, "AUX17", A_AUX17, false}, + {0x132, 0x132, "AUX18", A_AUX18, false}, + {0x133, 0x133, "AUX19", A_AUX19, false}, + {0x134, 0x134, "AUX20", A_AUX20, false}, + {0x135, 0x135, "AUX21", A_AUX21, false}, + {0x136, 0x136, "AUX22", A_AUX22, false}, + {0x137, 0x137, "AUX23", A_AUX23, false}, + {0x138, 0x138, "AUX24", A_AUX24, false}, + {0x139, 0x139, "AUX25", A_AUX25, false}, + {0x13a, 0x13a, "AUX26", A_AUX26, false}, + {0x13b, 0x13b, "AUX27", A_AUX27, false}, + {0x13c, 0x13c, "AUX28", A_AUX28, false}, + {0x13d, 0x13d, "AUX29", A_AUX29, false}, + {0x13e, 0x13e, "AUX30", A_AUX30, false}, + {0x13f, 0x13f, "AUX31", A_AUX31, false}}; +static const size_t numKeynames = ARRAY_LEN(keynames); /* ============================================================================= @@ -392,7 +387,6 @@ EDIT FIELDS ============================================================================= */ - /* =================== Field_Draw @@ -402,88 +396,86 @@ x, y, amd width are in pixels =================== */ extern console_t con; -void Field_VariableSizeDraw( field_t *edit, int x, int y, int size, qboolean showCursor, qboolean noColorEscape ) { - int len; - int drawLen; - int prestep; - int cursorChar; - char str[MAX_STRING_CHARS]; - int i; +void Field_VariableSizeDraw(field_t *edit, int x, int y, int size, qboolean showCursor, qboolean noColorEscape) { + int len; + int drawLen; + int prestep; + int cursorChar; + char str[MAX_STRING_CHARS]; + int i; drawLen = edit->widthInChars - 1; // - 1 so there is always a space for the cursor - len = strlen( edit->buffer ); + len = strlen(edit->buffer); // guarantee that cursor will be visible - if ( len <= drawLen ) { + if (len <= drawLen) { prestep = 0; } else { - if ( edit->scroll + drawLen > len ) { + if (edit->scroll + drawLen > len) { edit->scroll = len - drawLen; - if ( edit->scroll < 0 ) { + if (edit->scroll < 0) { edit->scroll = 0; } } prestep = edit->scroll; } - if ( prestep + drawLen > len ) { + if (prestep + drawLen > len) { drawLen = len - prestep; } - if ( drawLen < 0 ) + if (drawLen < 0) return; // extract characters from the field at - if ( drawLen >= MAX_STRING_CHARS ) { - Com_Error( ERR_DROP, "drawLen >= MAX_STRING_CHARS" ); + if (drawLen >= MAX_STRING_CHARS) { + Com_Error(ERR_DROP, "drawLen >= MAX_STRING_CHARS"); } - Com_Memcpy( str, edit->buffer + prestep, drawLen ); - str[ drawLen ] = 0; + Com_Memcpy(str, edit->buffer + prestep, drawLen); + str[drawLen] = 0; // draw it - if ( size == con.charWidth ) { - float color[4]; + if (size == con.charWidth) { + float color[4]; color[0] = color[1] = color[2] = color[3] = 1.0; - SCR_DrawSmallStringExt( x, y, str, color, qfalse, noColorEscape ); + SCR_DrawSmallStringExt(x, y, str, color, qfalse, noColorEscape); } else { // draw big string with drop shadow - SCR_DrawBigString( x, y, str, 1.0, noColorEscape ); + SCR_DrawBigString(x, y, str, 1.0, noColorEscape); } // draw the cursor - if ( showCursor ) { - if ( (int)( cls.realtime >> 8 ) & 1 ) { - return; // off blink + if (showCursor) { + if ((int)(cls.realtime >> 8) & 1) { + return; // off blink } - if ( kg.key_overstrikeMode ) { + if (kg.key_overstrikeMode) { cursorChar = 11; } else { cursorChar = 10; } - i = drawLen - strlen( str ); + i = drawLen - strlen(str); - if ( size == con.charWidth ) { - SCR_DrawSmallChar( x + ( edit->cursor - prestep - i ) * size, y, cursorChar ); + if (size == con.charWidth) { + SCR_DrawSmallChar(x + (edit->cursor - prestep - i) * size, y, cursorChar); } else { str[0] = cursorChar; str[1] = 0; - SCR_DrawBigString( x + ( edit->cursor - prestep - i ) * size, y, str, 1.0, qfalse ); + SCR_DrawBigString(x + (edit->cursor - prestep - i) * size, y, str, 1.0, qfalse); } } } -void Field_Draw( field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape ) -{ - Field_VariableSizeDraw( edit, x, y, con.charWidth, showCursor, noColorEscape ); +void Field_Draw(field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape) { + Field_VariableSizeDraw(edit, x, y, con.charWidth, showCursor, noColorEscape); } -void Field_BigDraw( field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape ) -{ - Field_VariableSizeDraw( edit, x, y, BIGCHAR_WIDTH, showCursor, noColorEscape ); +void Field_BigDraw(field_t *edit, int x, int y, qboolean showCursor, qboolean noColorEscape) { + Field_VariableSizeDraw(edit, x, y, BIGCHAR_WIDTH, showCursor, noColorEscape); } /* @@ -491,23 +483,22 @@ void Field_BigDraw( field_t *edit, int x, int y, qboolean showCursor, qboolean n Field_Paste ================ */ -void Field_Paste( field_t *edit ) { - char *cbd, *c; +void Field_Paste(field_t *edit) { + char *cbd, *c; c = cbd = Sys_GetClipboardData(); - if ( !cbd ) { + if (!cbd) { return; } // send as if typed, so insert / overstrike works properly - while( *c ) - { - uint32_t utf32 = ConvertUTF8ToUTF32( c, &c ); - Field_CharEvent( edit, ConvertUTF32ToExpectedCharset( utf32 ) ); + while (*c) { + uint32_t utf32 = ConvertUTF8ToUTF32(c, &c); + Field_CharEvent(edit, ConvertUTF32ToExpectedCharset(utf32)); } - Z_Free( cbd ); + Z_Free(cbd); } /* @@ -520,60 +511,59 @@ in-game talk, and menu fields Key events are used for non-printable characters, others are gotten from char events. ================= */ -void Field_KeyDownEvent( field_t *edit, int key ) { - int len; +void Field_KeyDownEvent(field_t *edit, int key) { + int len; // shift-insert is paste - if ( ( ( key == A_INSERT ) || ( key == A_KP_0 ) ) && kg.keys[A_SHIFT].down ) { - Field_Paste( edit ); + if (((key == A_INSERT) || (key == A_KP_0)) && kg.keys[A_SHIFT].down) { + Field_Paste(edit); return; } - key = tolower( key ); - len = strlen( edit->buffer ); + key = tolower(key); + len = strlen(edit->buffer); - switch ( key ) { - case A_DELETE: - if ( edit->cursor < len ) { - memmove( edit->buffer + edit->cursor, - edit->buffer + edit->cursor + 1, len - edit->cursor ); - } - break; + switch (key) { + case A_DELETE: + if (edit->cursor < len) { + memmove(edit->buffer + edit->cursor, edit->buffer + edit->cursor + 1, len - edit->cursor); + } + break; - case A_CURSOR_RIGHT: - if ( edit->cursor < len ) { - edit->cursor++; - } - break; + case A_CURSOR_RIGHT: + if (edit->cursor < len) { + edit->cursor++; + } + break; - case A_CURSOR_LEFT: - if ( edit->cursor > 0 ) { - edit->cursor--; - } - break; + case A_CURSOR_LEFT: + if (edit->cursor > 0) { + edit->cursor--; + } + break; - case A_HOME: - edit->cursor = 0; - break; + case A_HOME: + edit->cursor = 0; + break; - case A_END: - edit->cursor = len; - break; + case A_END: + edit->cursor = len; + break; - case A_INSERT: - kg.key_overstrikeMode = (qboolean)!kg.key_overstrikeMode; - break; + case A_INSERT: + kg.key_overstrikeMode = (qboolean)!kg.key_overstrikeMode; + break; - default: - break; - } + default: + break; + } // Change scroll if cursor is no longer visible - if ( edit->cursor < edit->scroll ) { + if (edit->cursor < edit->scroll) { edit->scroll = edit->cursor; - } else if ( edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len ) { + } else if (edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len) { edit->scroll = edit->cursor - edit->widthInChars + 1; - } + } } /* @@ -581,41 +571,39 @@ void Field_KeyDownEvent( field_t *edit, int key ) { Field_CharEvent ================== */ -void Field_CharEvent( field_t *edit, int ch ) { - int len; +void Field_CharEvent(field_t *edit, int ch) { + int len; - if ( ch == 'v' - 'a' + 1 ) { // ctrl-v is paste - Field_Paste( edit ); + if (ch == 'v' - 'a' + 1) { // ctrl-v is paste + Field_Paste(edit); return; } - if ( ch == 'c' - 'a' + 1 ) { // ctrl-c clears the field - Field_Clear( edit ); + if (ch == 'c' - 'a' + 1) { // ctrl-c clears the field + Field_Clear(edit); return; } - len = strlen( edit->buffer ); + len = strlen(edit->buffer); - if ( ch == 'h' - 'a' + 1 ) { // ctrl-h is backspace - if ( edit->cursor > 0 ) { - memmove( edit->buffer + edit->cursor - 1, - edit->buffer + edit->cursor, len + 1 - edit->cursor ); + if (ch == 'h' - 'a' + 1) { // ctrl-h is backspace + if (edit->cursor > 0) { + memmove(edit->buffer + edit->cursor - 1, edit->buffer + edit->cursor, len + 1 - edit->cursor); edit->cursor--; - if ( edit->cursor < edit->scroll ) - { + if (edit->cursor < edit->scroll) { edit->scroll--; } } return; } - if ( ch == 'a' - 'a' + 1 ) { // ctrl-a is home + if (ch == 'a' - 'a' + 1) { // ctrl-a is home edit->cursor = 0; edit->scroll = 0; return; } - if ( ch == 'e' - 'a' + 1 ) { // ctrl-e is end + if (ch == 'e' - 'a' + 1) { // ctrl-e is end edit->cursor = len; edit->scroll = edit->cursor - edit->widthInChars; return; @@ -624,32 +612,31 @@ void Field_CharEvent( field_t *edit, int ch ) { // // ignore any other non printable chars // - if ( ch < 32 ) { + if (ch < 32) { return; } - if ( kg.key_overstrikeMode ) { + if (kg.key_overstrikeMode) { // - 2 to leave room for the leading slash and trailing \0 - if ( edit->cursor == MAX_EDIT_LINE - 2 ) + if (edit->cursor == MAX_EDIT_LINE - 2) return; edit->buffer[edit->cursor] = ch; edit->cursor++; - } else { // insert mode + } else { // insert mode // - 2 to leave room for the leading slash and trailing \0 - if ( len == MAX_EDIT_LINE - 2 ) { + if (len == MAX_EDIT_LINE - 2) { return; // all full } - memmove( edit->buffer + edit->cursor + 1, - edit->buffer + edit->cursor, len + 1 - edit->cursor ); + memmove(edit->buffer + edit->cursor + 1, edit->buffer + edit->cursor, len + 1 - edit->cursor); edit->buffer[edit->cursor] = ch; edit->cursor++; } - if ( edit->cursor >= edit->widthInChars ) { + if (edit->cursor >= edit->widthInChars) { edit->scroll++; } - if ( edit->cursor == len + 1) { + if (edit->cursor == len + 1) { edit->buffer[edit->cursor] = 0; } } @@ -661,55 +648,51 @@ Console_Key Handles history and console scrollback ==================== */ -void Console_Key( int key ) { +void Console_Key(int key) { // ctrl-L clears screen - if ( keynames[key].lower == 'l' && kg.keys[A_CTRL].down ) { - Cbuf_AddText( "clear\n" ); + if (keynames[key].lower == 'l' && kg.keys[A_CTRL].down) { + Cbuf_AddText("clear\n"); return; } // enter finishes the line - if ( key == A_ENTER || key == A_KP_ENTER ) { + if (key == A_ENTER || key == A_KP_ENTER) { // legacy hack: strip any prepended slashes. they're not necessary anymore - if ( g_consoleField.buffer[0] && - (g_consoleField.buffer[0] == '\\' || g_consoleField.buffer[0] == '/') ) { - char temp[MAX_EDIT_LINE-1]; + if (g_consoleField.buffer[0] && (g_consoleField.buffer[0] == '\\' || g_consoleField.buffer[0] == '/')) { + char temp[MAX_EDIT_LINE - 1]; - Q_strncpyz( temp, g_consoleField.buffer+1, sizeof( temp ) ); - Com_sprintf( g_consoleField.buffer, sizeof( g_consoleField.buffer ), "%s", temp ); + Q_strncpyz(temp, g_consoleField.buffer + 1, sizeof(temp)); + Com_sprintf(g_consoleField.buffer, sizeof(g_consoleField.buffer), "%s", temp); g_consoleField.cursor--; } - // else - // Field_AutoComplete( &g_consoleField ); + // else + // Field_AutoComplete( &g_consoleField ); // print executed command - Com_Printf( "%c%s\n", CONSOLE_PROMPT_CHAR, g_consoleField.buffer ); + Com_Printf("%c%s\n", CONSOLE_PROMPT_CHAR, g_consoleField.buffer); // check if cgame wants to eat the command...? - if ( cls.cgameStarted && cl.mSharedMemory ) { + if (cls.cgameStarted && cl.mSharedMemory) { TCGIncomingConsoleCommand *icc = (TCGIncomingConsoleCommand *)cl.mSharedMemory; - Q_strncpyz( icc->conCommand, g_consoleField.buffer, sizeof( icc->conCommand ) ); + Q_strncpyz(icc->conCommand, g_consoleField.buffer, sizeof(icc->conCommand)); - if ( CGVM_IncomingConsoleCommand() ) { + if (CGVM_IncomingConsoleCommand()) { // valid command - Cbuf_AddText( g_consoleField.buffer ); - Cbuf_AddText( "\n" ); - } - else if ( icc->conCommand[0] ) { + Cbuf_AddText(g_consoleField.buffer); + Cbuf_AddText("\n"); + } else if (icc->conCommand[0]) { // cgame ate it and substituted their own - Cbuf_AddText( icc->conCommand ); - Cbuf_AddText( "\n" ); + Cbuf_AddText(icc->conCommand); + Cbuf_AddText("\n"); } - } - else { + } else { // cgame didn't eat it, execute it - Cbuf_AddText( g_consoleField.buffer ); - Cbuf_AddText( "\n" ); + Cbuf_AddText(g_consoleField.buffer); + Cbuf_AddText("\n"); } - if (!g_consoleField.buffer[0]) - { + if (!g_consoleField.buffer[0]) { return; // empty lines just scroll the console without adding to history } @@ -718,44 +701,40 @@ void Console_Key( int key ) { nextHistoryLine++; historyLine = nextHistoryLine; - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; - // CL_SaveConsoleHistory(); + // CL_SaveConsoleHistory(); - if ( cls.state == CA_DISCONNECTED ) - SCR_UpdateScreen (); // force an update, because the command may take some time + if (cls.state == CA_DISCONNECTED) + SCR_UpdateScreen(); // force an update, because the command may take some time return; } // tab completion - if ( key == A_TAB ) { - Field_AutoComplete( &g_consoleField ); + if (key == A_TAB) { + Field_AutoComplete(&g_consoleField); return; } // history scrolling - if ( key == A_CURSOR_UP || key == A_KP_8 - || (kg.keys[A_SHIFT].down && key == A_MWHEELUP) - || (kg.keys[A_CTRL].down && keynames[key].lower == 'p') ) - {// scroll up: arrow-up, numpad-up, shift + mwheelup, ctrl + p - if ( nextHistoryLine - historyLine < COMMAND_HISTORY && historyLine > 0 ) + if (key == A_CURSOR_UP || key == A_KP_8 || (kg.keys[A_SHIFT].down && key == A_MWHEELUP) || + (kg.keys[A_CTRL].down && keynames[key].lower == 'p')) { // scroll up: arrow-up, numpad-up, shift + mwheelup, ctrl + p + if (nextHistoryLine - historyLine < COMMAND_HISTORY && historyLine > 0) historyLine--; g_consoleField = historyEditLines[historyLine % COMMAND_HISTORY]; return; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 - || (kg.keys[A_SHIFT].down && key == A_MWHEELDOWN) - || (kg.keys[A_CTRL].down && keynames[key].lower == 'n') ) - {// scroll down: arrow-down, numpad-down, shift + mwheeldown, ctrl + n + if (key == A_CURSOR_DOWN || key == A_KP_2 || (kg.keys[A_SHIFT].down && key == A_MWHEELDOWN) || + (kg.keys[A_CTRL].down && keynames[key].lower == 'n')) { // scroll down: arrow-down, numpad-down, shift + mwheeldown, ctrl + n historyLine++; if (historyLine >= nextHistoryLine) { historyLine = nextHistoryLine; - Field_Clear( &g_consoleField ); + Field_Clear(&g_consoleField); g_consoleField.widthInChars = g_console_field_width; return; } @@ -764,39 +743,38 @@ void Console_Key( int key ) { } // console scrolling (ctrl to scroll fast) - if ( key == A_PAGE_UP || key == A_MWHEELUP ) { + if (key == A_PAGE_UP || key == A_MWHEELUP) { int count = kg.keys[A_CTRL].down ? 5 : 1; - for ( int i=0; i= MAX_KEYS ) +qboolean Key_IsDown(int keynum) { + if (keynum < 0 || keynum >= MAX_KEYS) return qfalse; return kg.keys[keynames[keynum].upper].down; } - /* =================== Key_StringToKeynum @@ -867,25 +840,25 @@ the K_* names are matched up. to be configured even if they don't have defined names. =================== */ -int Key_StringToKeynum( char *str ) { - if ( !VALIDSTRING( str ) ) +int Key_StringToKeynum(char *str) { + if (!VALIDSTRING(str)) return -1; // If single char bind, presume ascii char bind - if ( !str[1] ) + if (!str[1]) return keynames[(unsigned char)str[0]].upper; // scan for a text match - for ( int i=0; i= 0 ) + if (n >= 0) return n; } @@ -893,33 +866,34 @@ int Key_StringToKeynum( char *str ) { } static char tinyString[16]; -static const char *Key_KeynumValid( int keynum ) { - if ( keynum == -1 ) +static const char *Key_KeynumValid(int keynum) { + if (keynum == -1) return ""; - if ( keynum < 0 || keynum >= MAX_KEYS ) + if (keynum < 0 || keynum >= MAX_KEYS) return ""; return NULL; } -static const char *Key_KeyToName( int keynum ) { - return keynames[keynum].name; -} - +static const char *Key_KeyToName(int keynum) { return keynames[keynum].name; } -static const char *Key_KeyToAscii( int keynum ) { - if ( !keynames[keynum].lower ) +static const char *Key_KeyToAscii(int keynum) { + if (!keynames[keynum].lower) return NULL; - if ( keynum == A_SPACE ) tinyString[0] = (char)A_SHIFT_SPACE; - else if ( keynum == A_ENTER ) tinyString[0] = (char)A_SHIFT_ENTER; - else if ( keynum == A_KP_ENTER ) tinyString[0] = (char)A_SHIFT_KP_ENTER; - else tinyString[0] = keynames[keynum].upper; + if (keynum == A_SPACE) + tinyString[0] = (char)A_SHIFT_SPACE; + else if (keynum == A_ENTER) + tinyString[0] = (char)A_SHIFT_ENTER; + else if (keynum == A_KP_ENTER) + tinyString[0] = (char)A_SHIFT_KP_ENTER; + else + tinyString[0] = keynames[keynum].upper; tinyString[1] = '\0'; return tinyString; } -static const char *Key_KeyToHex( int keynum ) { +static const char *Key_KeyToHex(int keynum) { int i = keynum >> 4; int j = keynum & 15; @@ -933,25 +907,24 @@ static const char *Key_KeyToHex( int keynum ) { } // Returns the ascii code of the keynum -const char *Key_KeynumToAscii( int keynum ) { +const char *Key_KeynumToAscii(int keynum) { const char *name = Key_KeynumValid(keynum); // check for printable ascii - if ( !name && keynum > 0 && keynum < 256 ) - name = Key_KeyToAscii( keynum ); + if (!name && keynum > 0 && keynum < 256) + name = Key_KeyToAscii(keynum); // Check for name (for JOYx and AUXx buttons) - if ( !name ) - name = Key_KeyToName( keynum ); + if (!name) + name = Key_KeyToName(keynum); // Fallback to hex number - if ( !name ) - name = Key_KeyToHex( keynum ); + if (!name) + name = Key_KeyToHex(keynum); return name; } - /* =================== Key_KeynumToString @@ -961,22 +934,22 @@ given keynum. =================== */ // Returns a console/config file friendly name for the key -const char *Key_KeynumToString( int keynum ) { +const char *Key_KeynumToString(int keynum) { const char *name; - name = Key_KeynumValid( keynum ); + name = Key_KeynumValid(keynum); // Check for friendly name - if ( !name ) - name = Key_KeyToName( keynum ); + if (!name) + name = Key_KeyToName(keynum); // check for printable ascii - if ( !name && keynum > 0 && keynum < 256) - name = Key_KeyToAscii( keynum ); + if (!name && keynum > 0 && keynum < 256) + name = Key_KeyToAscii(keynum); // Fallback to hex number - if ( !name ) - name = Key_KeyToHex( keynum ); + if (!name) + name = Key_KeyToHex(keynum); return name; } @@ -986,19 +959,19 @@ const char *Key_KeynumToString( int keynum ) { Key_SetBinding =================== */ -void Key_SetBinding( int keynum, const char *binding ) { - if ( keynum < 0 || keynum >= MAX_KEYS ) +void Key_SetBinding(int keynum, const char *binding) { + if (keynum < 0 || keynum >= MAX_KEYS) return; // free old bindings - if ( kg.keys[keynames[keynum].upper].binding ) { - Z_Free( kg.keys[keynames[keynum].upper].binding ); + if (kg.keys[keynames[keynum].upper].binding) { + Z_Free(kg.keys[keynames[keynum].upper].binding); kg.keys[keynames[keynum].upper].binding = NULL; } // allocate memory for new binding - if ( binding ) - kg.keys[keynames[keynum].upper].binding = CopyString( binding ); + if (binding) + kg.keys[keynames[keynum].upper].binding = CopyString(binding); // consider this like modifying an archived cvar, so the // file write will be triggered at the next oportunity @@ -1010,8 +983,8 @@ void Key_SetBinding( int keynum, const char *binding ) { Key_GetBinding =================== */ -char *Key_GetBinding( int keynum ) { - if ( keynum < 0 || keynum >= MAX_KEYS ) +char *Key_GetBinding(int keynum) { + if (keynum < 0 || keynum >= MAX_KEYS) return ""; return kg.keys[keynum].binding; @@ -1022,10 +995,10 @@ char *Key_GetBinding( int keynum ) { Key_GetKey =================== */ -int Key_GetKey( const char *binding ) { - if ( binding ) { - for ( int i=0; i : remove commands from a key\n" ); +void Key_Unbind_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf("unbind : remove commands from a key\n"); return; } - int b = Key_StringToKeynum( Cmd_Argv( 1 ) ); - if ( b == -1 ) { - Com_Printf( "\"%s\" isn't a valid key\n", Cmd_Argv( 1 ) ); + int b = Key_StringToKeynum(Cmd_Argv(1)); + if (b == -1) { + Com_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - Key_SetBinding( b, "" ); + Key_SetBinding(b, ""); } /* @@ -1058,10 +1031,10 @@ void Key_Unbind_f( void ) { Key_Unbindall_f =================== */ -void Key_Unbindall_f( void ) { - for ( int i=0; i [command] : attach a command to a key\n" ); + if (c < 2) { + Com_Printf("bind [command] : attach a command to a key\n"); return; } - int b = Key_StringToKeynum( Cmd_Argv( 1 ) ); - if ( b == -1 ) { - Com_Printf( "\"%s\" isn't a valid key\n", Cmd_Argv( 1 ) ); + int b = Key_StringToKeynum(Cmd_Argv(1)); + if (b == -1) { + Com_Printf("\"%s\" isn't a valid key\n", Cmd_Argv(1)); return; } - if ( c == 2 ) { - if ( kg.keys[b].binding && kg.keys[b].binding[0] ) - Com_Printf( S_COLOR_GREY "Bind " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", Key_KeynumToString( b ), kg.keys[b].binding ); + if (c == 2) { + if (kg.keys[b].binding && kg.keys[b].binding[0]) + Com_Printf(S_COLOR_GREY "Bind " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", + Key_KeynumToString(b), kg.keys[b].binding); else - Com_Printf( "\"%s\" is not bound\n", Key_KeynumToString( b ) ); + Com_Printf("\"%s\" is not bound\n", Key_KeynumToString(b)); return; } - Key_SetBinding( b, Cmd_ArgsFrom( 2 ) ); + Key_SetBinding(b, Cmd_ArgsFrom(2)); } /* @@ -1102,17 +1076,17 @@ Key_WriteBindings Writes lines containing "bind key value" ============ */ -void Key_WriteBindings( fileHandle_t f ) { - FS_Printf( f, "unbindall\n" ); - for ( size_t i=0; i args ) + char *p = Com_SkipTokens(args, 1, " "); + if (p > args) Field_CompleteKeyname(); } } @@ -1161,22 +1136,21 @@ static void Key_CompleteUnbind( char *args, int argNum ) { Key_CompleteBind ==================== */ -static void Key_CompleteBind( char *args, int argNum ) { +static void Key_CompleteBind(char *args, int argNum) { char *p; - if ( argNum == 2 ) { + if (argNum == 2) { // Skip "bind " - p = Com_SkipTokens( args, 1, " " ); + p = Com_SkipTokens(args, 1, " "); - if ( p > args ) + if (p > args) Field_CompleteKeyname(); - } - else if ( argNum >= 3 ) { + } else if (argNum >= 3) { // Skip "bind " - p = Com_SkipTokens( args, 2, " " ); + p = Com_SkipTokens(args, 2, " "); - if ( p > args ) - Field_CompleteCommand( p, qtrue, qtrue ); + if (p > args) + Field_CompleteCommand(p, qtrue, qtrue); } } @@ -1185,14 +1159,14 @@ static void Key_CompleteBind( char *args, int argNum ) { CL_InitKeyCommands =================== */ -void CL_InitKeyCommands( void ) { +void CL_InitKeyCommands(void) { // register our functions - Cmd_AddCommand( "bind", Key_Bind_f, "Bind a key to a console command" ); - Cmd_SetCommandCompletionFunc( "bind", Key_CompleteBind ); - Cmd_AddCommand( "unbind", Key_Unbind_f, "Unbind a key" ); - Cmd_SetCommandCompletionFunc( "unbind", Key_CompleteUnbind ); - Cmd_AddCommand( "unbindall", Key_Unbindall_f, "Delete all key bindings" ); - Cmd_AddCommand( "bindlist", Key_Bindlist_f, "Show all bindings in the console" ); + Cmd_AddCommand("bind", Key_Bind_f, "Bind a key to a console command"); + Cmd_SetCommandCompletionFunc("bind", Key_CompleteBind); + Cmd_AddCommand("unbind", Key_Unbind_f, "Unbind a key"); + Cmd_SetCommandCompletionFunc("unbind", Key_CompleteUnbind); + Cmd_AddCommand("unbindall", Key_Unbindall_f, "Delete all key bindings"); + Cmd_AddCommand("bindlist", Key_Bindlist_f, "Show all bindings in the console"); } /* @@ -1202,13 +1176,13 @@ CL_BindUICommand Returns qtrue if bind command should be executed while user interface is shown =================== */ -static qboolean CL_BindUICommand( const char *cmd ) { - if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) +static qboolean CL_BindUICommand(const char *cmd) { + if (Key_GetCatcher() & KEYCATCH_CONSOLE) return qfalse; - if ( !Q_stricmp( cmd, "toggleconsole" ) ) + if (!Q_stricmp(cmd, "toggleconsole")) return qtrue; - if ( !Q_stricmp( cmd, "togglemenu" ) ) + if (!Q_stricmp(cmd, "togglemenu")) return qtrue; return qfalse; @@ -1221,72 +1195,64 @@ CL_ParseBinding Execute the commands in the bind string =================== */ -void CL_ParseBinding( int key, qboolean down, unsigned time ) -{ - char buf[ MAX_STRING_CHARS ], *p = buf, *end; +void CL_ParseBinding(int key, qboolean down, unsigned time) { + char buf[MAX_STRING_CHARS], *p = buf, *end; qboolean allCommands, allowUpCmds; - if( cls.state == CA_DISCONNECTED && Key_GetCatcher( ) == 0 ) + if (cls.state == CA_DISCONNECTED && Key_GetCatcher() == 0) return; - if( !kg.keys[keynames[key].upper].binding || !kg.keys[keynames[key].upper].binding[0] ) + if (!kg.keys[keynames[key].upper].binding || !kg.keys[keynames[key].upper].binding[0]) return; - Q_strncpyz( buf, kg.keys[keynames[key].upper].binding, sizeof( buf ) ); + Q_strncpyz(buf, kg.keys[keynames[key].upper].binding, sizeof(buf)); // run all bind commands if console, ui, etc aren't reading keys - allCommands = (qboolean)( Key_GetCatcher( ) == 0 ); + allCommands = (qboolean)(Key_GetCatcher() == 0); // allow button up commands if in game even if key catcher is set - allowUpCmds = (qboolean)( cls.state != CA_DISCONNECTED ); + allowUpCmds = (qboolean)(cls.state != CA_DISCONNECTED); - while( 1 ) - { - while( isspace( *p ) ) + while (1) { + while (isspace(*p)) p++; - end = strchr( p, ';' ); - if( end ) + end = strchr(p, ';'); + if (end) *end = '\0'; - if( *p == '+' ) - { + if (*p == '+') { // button commands add keynum and time as parameters // so that multiple sources can be discriminated and // subframe corrected - if ( allCommands || ( allowUpCmds && !down ) ) { + if (allCommands || (allowUpCmds && !down)) { char cmd[1024]; - Com_sprintf( cmd, sizeof( cmd ), "%c%s %d %d\n", - ( down ) ? '+' : '-', p + 1, key, time ); - Cbuf_AddText( cmd ); + Com_sprintf(cmd, sizeof(cmd), "%c%s %d %d\n", (down) ? '+' : '-', p + 1, key, time); + Cbuf_AddText(cmd); } - } - else if( down ) - { + } else if (down) { // normal commands only execute on key press - if ( allCommands || CL_BindUICommand( p ) ) { + if (allCommands || CL_BindUICommand(p)) { // down-only command - if ( cls.cgameStarted && cl.mSharedMemory ) { + if (cls.cgameStarted && cl.mSharedMemory) { // don't do this unless cgame is inited and shared memory is valid TCGIncomingConsoleCommand *icc = (TCGIncomingConsoleCommand *)cl.mSharedMemory; - Q_strncpyz( icc->conCommand, p, sizeof(icc->conCommand) ); + Q_strncpyz(icc->conCommand, p, sizeof(icc->conCommand)); - if ( CGVM_IncomingConsoleCommand() ) { - //rww - let mod authors filter client console messages so they can cut them off if they want. - Cbuf_AddText( p ); - Cbuf_AddText( "\n" ); - } - else if ( icc->conCommand[0] ) { - //the vm call says to execute this command in place - Cbuf_AddText( icc->conCommand ); - Cbuf_AddText( "\n" ); + if (CGVM_IncomingConsoleCommand()) { + // rww - let mod authors filter client console messages so they can cut them off if they want. + Cbuf_AddText(p); + Cbuf_AddText("\n"); + } else if (icc->conCommand[0]) { + // the vm call says to execute this command in place + Cbuf_AddText(icc->conCommand); + Cbuf_AddText("\n"); } - } - else { - //otherwise just add it - Cbuf_AddText( p ); - Cbuf_AddText( "\n" ); + } else { + // otherwise just add it + Cbuf_AddText(p); + Cbuf_AddText("\n"); } } } - if( !end ) + if (!end) break; p = end + 1; } @@ -1299,95 +1265,93 @@ CL_KeyDownEvent Called by CL_KeyEvent to handle a keypress =================== */ -void CL_KeyDownEvent( int key, unsigned time ) -{ +void CL_KeyDownEvent(int key, unsigned time) { kg.keys[keynames[key].upper].down = qtrue; kg.keys[keynames[key].upper].repeats++; - if( kg.keys[keynames[key].upper].repeats == 1 ) { + if (kg.keys[keynames[key].upper].repeats == 1) { kg.keyDownCount++; kg.anykeydown = qtrue; } - if ( cl_allowAltEnter->integer && kg.keys[A_ALT].down && key == A_ENTER ) - { - Cvar_SetValue( "r_fullscreen", !Cvar_VariableIntegerValue( "r_fullscreen" ) ); + if (cl_allowAltEnter->integer && kg.keys[A_ALT].down && key == A_ENTER) { + Cvar_SetValue("r_fullscreen", !Cvar_VariableIntegerValue("r_fullscreen")); return; } // console key is hardcoded, so the user can never unbind it - if ( key == A_CONSOLE || (kg.keys[A_SHIFT].down && key == A_ESCAPE) ) { + if (key == A_CONSOLE || (kg.keys[A_SHIFT].down && key == A_ESCAPE)) { Con_ToggleConsole_f(); - Key_ClearStates (); + Key_ClearStates(); return; } // keys can still be used for bound actions - if ( cls.state == CA_CINEMATIC && !Key_GetCatcher() ) { - if ( !com_cameraMode->integer ) { - Cvar_Set( "nextdemo", "" ); + if (cls.state == CA_CINEMATIC && !Key_GetCatcher()) { + if (!com_cameraMode->integer) { + Cvar_Set("nextdemo", ""); key = A_ESCAPE; } } // escape is always handled special - if ( key == A_ESCAPE ) { - if ( !kg.keys[A_SHIFT].down && ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) { + if (key == A_ESCAPE) { + if (!kg.keys[A_SHIFT].down && (Key_GetCatcher() & KEYCATCH_CONSOLE)) { Con_ToggleConsole_f(); Key_ClearStates(); return; } - if ( Key_GetCatcher() & KEYCATCH_MESSAGE ) { + if (Key_GetCatcher() & KEYCATCH_MESSAGE) { // clear message mode - Message_Key( key ); + Message_Key(key); return; } // escape always gets out of CGAME stuff - if ( Key_GetCatcher() & KEYCATCH_CGAME ) { - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_CGAME ); - CGVM_EventHandling( CGAME_EVENT_NONE ); + if (Key_GetCatcher() & KEYCATCH_CGAME) { + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_CGAME); + CGVM_EventHandling(CGAME_EVENT_NONE); return; } - if ( !(Key_GetCatcher() & KEYCATCH_UI) ) { - if ( cls.state == CA_ACTIVE && !clc.demoplaying ) - UIVM_SetActiveMenu( UIMENU_INGAME ); + if (!(Key_GetCatcher() & KEYCATCH_UI)) { + if (cls.state == CA_ACTIVE && !clc.demoplaying) + UIVM_SetActiveMenu(UIMENU_INGAME); else { CL_Disconnect_f(); S_StopAllSounds(); - UIVM_SetActiveMenu( UIMENU_MAIN ); + UIVM_SetActiveMenu(UIMENU_MAIN); } return; } - UIVM_KeyEvent( key, qtrue ); + UIVM_KeyEvent(key, qtrue); return; } // send the bound action - CL_ParseBinding( key, qtrue, time ); + CL_ParseBinding(key, qtrue, time); // distribute the key down event to the appropriate handler // console - if ( Key_GetCatcher() & KEYCATCH_CONSOLE ) - Console_Key( key ); + if (Key_GetCatcher() & KEYCATCH_CONSOLE) + Console_Key(key); // ui - else if ( Key_GetCatcher() & KEYCATCH_UI ) { - if ( cls.uiStarted ) - UIVM_KeyEvent( key, qtrue ); + else if (Key_GetCatcher() & KEYCATCH_UI) { + if (cls.uiStarted) + UIVM_KeyEvent(key, qtrue); } // cgame - else if ( Key_GetCatcher() & KEYCATCH_CGAME ) { - if ( cls.cgameStarted ) - CGVM_KeyEvent( key, qtrue ); + else if (Key_GetCatcher() & KEYCATCH_CGAME) { + if (cls.cgameStarted) + CGVM_KeyEvent(key, qtrue); } // chatbox - else if ( Key_GetCatcher() & KEYCATCH_MESSAGE ) - Message_Key( key ); + else if (Key_GetCatcher() & KEYCATCH_MESSAGE) + Message_Key(key); // console - else if ( cls.state == CA_DISCONNECTED ) - Console_Key( key ); + else if (cls.state == CA_DISCONNECTED) + Console_Key(key); } /* @@ -1397,8 +1361,7 @@ CL_KeyUpEvent Called by CL_KeyEvent to handle a keyrelease =================== */ -void CL_KeyUpEvent( int key, unsigned time ) -{ +void CL_KeyUpEvent(int key, unsigned time) { kg.keys[keynames[key].upper].repeats = 0; kg.keys[keynames[key].upper].down = qfalse; kg.keyDownCount--; @@ -1409,7 +1372,7 @@ void CL_KeyUpEvent( int key, unsigned time ) } // don't process key-up events for the console key - if ( key == A_CONSOLE || ( key == A_ESCAPE && kg.keys[A_SHIFT].down ) ) + if (key == A_CONSOLE || (key == A_ESCAPE && kg.keys[A_SHIFT].down)) return; // @@ -1418,12 +1381,12 @@ void CL_KeyUpEvent( int key, unsigned time ) // console mode and menu mode, to keep the character from continuing // an action started before a mode switch. // - CL_ParseBinding( key, qfalse, time ); + CL_ParseBinding(key, qfalse, time); - if ( Key_GetCatcher( ) & KEYCATCH_UI && cls.uiStarted ) - UIVM_KeyEvent( key, qfalse ); - else if ( Key_GetCatcher( ) & KEYCATCH_CGAME && cls.cgameStarted ) - CGVM_KeyEvent( key, qfalse ); + if (Key_GetCatcher() & KEYCATCH_UI && cls.uiStarted) + UIVM_KeyEvent(key, qfalse); + else if (Key_GetCatcher() & KEYCATCH_CGAME && cls.cgameStarted) + CGVM_KeyEvent(key, qfalse); } /* @@ -1433,11 +1396,11 @@ CL_KeyEvent Called by the system for both key up and key down events =================== */ -void CL_KeyEvent (int key, qboolean down, unsigned time) { - if( down ) - CL_KeyDownEvent( key, time ); +void CL_KeyEvent(int key, qboolean down, unsigned time) { + if (down) + CL_KeyDownEvent(key, time); else - CL_KeyUpEvent( key, time ); + CL_KeyUpEvent(key, time); } /* @@ -1447,17 +1410,22 @@ CL_CharEvent Normal keyboard characters, already shifted / capslocked / etc =================== */ -void CL_CharEvent( int key ) { +void CL_CharEvent(int key) { // delete is not a printable character and is otherwise handled by Field_KeyDownEvent - if ( key == 127 ) + if (key == 127) return; // distribute the key down event to the appropriate handler - if ( Key_GetCatcher() & KEYCATCH_CONSOLE ) Field_CharEvent( &g_consoleField, key ); - else if ( Key_GetCatcher() & KEYCATCH_UI ) UIVM_KeyEvent( key|K_CHAR_FLAG, qtrue ); - else if ( Key_GetCatcher() & KEYCATCH_CGAME ) CGVM_KeyEvent( key|K_CHAR_FLAG, qtrue ); - else if ( Key_GetCatcher() & KEYCATCH_MESSAGE ) Field_CharEvent( &chatField, key ); - else if ( cls.state == CA_DISCONNECTED ) Field_CharEvent( &g_consoleField, key ); + if (Key_GetCatcher() & KEYCATCH_CONSOLE) + Field_CharEvent(&g_consoleField, key); + else if (Key_GetCatcher() & KEYCATCH_UI) + UIVM_KeyEvent(key | K_CHAR_FLAG, qtrue); + else if (Key_GetCatcher() & KEYCATCH_CGAME) + CGVM_KeyEvent(key | K_CHAR_FLAG, qtrue); + else if (Key_GetCatcher() & KEYCATCH_MESSAGE) + Field_CharEvent(&chatField, key); + else if (cls.state == CA_DISCONNECTED) + Field_CharEvent(&g_consoleField, key); } /* @@ -1465,12 +1433,12 @@ void CL_CharEvent( int key ) { Key_ClearStates =================== */ -void Key_ClearStates( void ) { +void Key_ClearStates(void) { kg.anykeydown = qfalse; - for ( int i=0; i. // This is for compatibility of old servercache only // Remove when 64-bit -int cls_nummplayerservers; -serverInfo_t cls_mplayerServers[MAX_OTHER_SERVERS]; +int cls_nummplayerservers; +serverInfo_t cls_mplayerServers[MAX_OTHER_SERVERS]; /* ==================== LAN_LoadCachedServers ==================== */ -void LAN_LoadCachedServers( ) { +void LAN_LoadCachedServers() { int size; fileHandle_t fileIn; cls.numglobalservers = cls_nummplayerservers = cls.numfavoriteservers = 0; @@ -60,7 +60,7 @@ void LAN_LoadCachedServers( ) { LAN_SaveServersToCache ==================== */ -void LAN_SaveServersToCache( ) { +void LAN_SaveServersToCache() { int size; fileHandle_t fileOut = FS_SV_FOpenFileWrite("servercache.dat"); FS_Write(&cls.numglobalservers, sizeof(int), fileOut); @@ -80,24 +80,24 @@ LAN_ResetPings ==================== */ void LAN_ResetPings(int source) { - int count,i; + int count, i; serverInfo_t *servers = NULL; count = 0; switch (source) { - case AS_LOCAL : - servers = &cls.localServers[0]; - count = MAX_OTHER_SERVERS; - break; - case AS_MPLAYER: - case AS_GLOBAL : - servers = &cls.globalServers[0]; - count = MAX_GLOBAL_SERVERS; - break; - case AS_FAVORITES : - servers = &cls.favoriteServers[0]; - count = MAX_OTHER_SERVERS; - break; + case AS_LOCAL: + servers = &cls.localServers[0]; + count = MAX_OTHER_SERVERS; + break; + case AS_MPLAYER: + case AS_GLOBAL: + servers = &cls.globalServers[0]; + count = MAX_GLOBAL_SERVERS; + break; + case AS_FAVORITES: + servers = &cls.favoriteServers[0]; + count = MAX_OTHER_SERVERS; + break; } if (servers) { for (i = 0; i < count; i++) { @@ -119,24 +119,24 @@ int LAN_AddServer(int source, const char *name, const char *address) { count = NULL; switch (source) { - case AS_LOCAL : - count = &cls.numlocalservers; - servers = &cls.localServers[0]; - break; - case AS_MPLAYER: - case AS_GLOBAL : - max = MAX_GLOBAL_SERVERS; - count = &cls.numglobalservers; - servers = &cls.globalServers[0]; - break; - case AS_FAVORITES : - count = &cls.numfavoriteservers; - servers = &cls.favoriteServers[0]; - break; + case AS_LOCAL: + count = &cls.numlocalservers; + servers = &cls.localServers[0]; + break; + case AS_MPLAYER: + case AS_GLOBAL: + max = MAX_GLOBAL_SERVERS; + count = &cls.numglobalservers; + servers = &cls.globalServers[0]; + break; + case AS_FAVORITES: + count = &cls.numfavoriteservers; + servers = &cls.favoriteServers[0]; + break; } if (servers && *count < max) { - NET_StringToAdr( address, &adr ); - for ( i = 0; i < *count; i++ ) { + NET_StringToAdr(address, &adr); + for (i = 0; i < *count; i++) { if (NET_CompareAdr(servers[i].adr, adr)) { break; } @@ -153,24 +153,23 @@ int LAN_AddServer(int source, const char *name, const char *address) { return -1; } -int LAN_AddFavAddr( const char *address ) { - if ( cls.numfavoriteservers < MAX_OTHER_SERVERS ) { +int LAN_AddFavAddr(const char *address) { + if (cls.numfavoriteservers < MAX_OTHER_SERVERS) { netadr_t adr; - if ( !NET_StringToAdr( address, &adr ) ) { + if (!NET_StringToAdr(address, &adr)) { return 2; } - if ( adr.type == NA_BAD ) { + if (adr.type == NA_BAD) { return 3; } - for ( int i = 0; i < cls.numfavoriteservers; i++ ) { - if ( NET_CompareAdr( cls.favoriteServers[i].adr, adr ) ) { + for (int i = 0; i < cls.numfavoriteservers; i++) { + if (NET_CompareAdr(cls.favoriteServers[i].adr, adr)) { return 0; } } cls.favoriteServers[cls.numfavoriteservers].adr = adr; - Q_strncpyz( cls.favoriteServers[cls.numfavoriteservers].hostName, address, - sizeof(cls.favoriteServers[cls.numfavoriteservers].hostName) ); + Q_strncpyz(cls.favoriteServers[cls.numfavoriteservers].hostName, address, sizeof(cls.favoriteServers[cls.numfavoriteservers].hostName)); cls.favoriteServers[cls.numfavoriteservers].visible = qtrue; cls.numfavoriteservers++; return 1; @@ -189,28 +188,28 @@ void LAN_RemoveServer(int source, const char *addr) { serverInfo_t *servers = NULL; count = NULL; switch (source) { - case AS_LOCAL : - count = &cls.numlocalservers; - servers = &cls.localServers[0]; - break; - case AS_MPLAYER: - case AS_GLOBAL : - count = &cls.numglobalservers; - servers = &cls.globalServers[0]; - break; - case AS_FAVORITES : - count = &cls.numfavoriteservers; - servers = &cls.favoriteServers[0]; - break; + case AS_LOCAL: + count = &cls.numlocalservers; + servers = &cls.localServers[0]; + break; + case AS_MPLAYER: + case AS_GLOBAL: + count = &cls.numglobalservers; + servers = &cls.globalServers[0]; + break; + case AS_FAVORITES: + count = &cls.numfavoriteservers; + servers = &cls.favoriteServers[0]; + break; } if (servers) { netadr_t comp; - NET_StringToAdr( addr, &comp ); + NET_StringToAdr(addr, &comp); for (i = 0; i < *count; i++) { - if (NET_CompareAdr( comp, servers[i].adr)) { + if (NET_CompareAdr(comp, servers[i].adr)) { int j = i; while (j < *count - 1) { - Com_Memcpy(&servers[j], &servers[j+1], sizeof(servers[j])); + Com_Memcpy(&servers[j], &servers[j + 1], sizeof(servers[j])); j++; } (*count)--; @@ -220,24 +219,23 @@ void LAN_RemoveServer(int source, const char *addr) { } } - /* ==================== LAN_GetServerCount ==================== */ -int LAN_GetServerCount( int source ) { +int LAN_GetServerCount(int source) { switch (source) { - case AS_LOCAL : - return cls.numlocalservers; - break; - case AS_MPLAYER: - case AS_GLOBAL : - return cls.numglobalservers; - break; - case AS_FAVORITES : - return cls.numfavoriteservers; - break; + case AS_LOCAL: + return cls.numlocalservers; + break; + case AS_MPLAYER: + case AS_GLOBAL: + return cls.numglobalservers; + break; + case AS_FAVORITES: + return cls.numfavoriteservers; + break; } return 0; } @@ -247,27 +245,27 @@ int LAN_GetServerCount( int source ) { LAN_GetLocalServerAddressString ==================== */ -void LAN_GetServerAddressString( int source, int n, char *buf, int buflen ) { +void LAN_GetServerAddressString(int source, int n, char *buf, int buflen) { switch (source) { - case AS_LOCAL : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - Q_strncpyz(buf, NET_AdrToString( cls.localServers[n].adr) , buflen ); - return; - } - break; - case AS_MPLAYER: - case AS_GLOBAL : - if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - Q_strncpyz(buf, NET_AdrToString( cls.globalServers[n].adr) , buflen ); - return; - } - break; - case AS_FAVORITES : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - Q_strncpyz(buf, NET_AdrToString( cls.favoriteServers[n].adr) , buflen ); - return; - } - break; + case AS_LOCAL: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + Q_strncpyz(buf, NET_AdrToString(cls.localServers[n].adr), buflen); + return; + } + break; + case AS_MPLAYER: + case AS_GLOBAL: + if (n >= 0 && n < MAX_GLOBAL_SERVERS) { + Q_strncpyz(buf, NET_AdrToString(cls.globalServers[n].adr), buflen); + return; + } + break; + case AS_FAVORITES: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + Q_strncpyz(buf, NET_AdrToString(cls.favoriteServers[n].adr), buflen); + return; + } + break; } buf[0] = '\0'; } @@ -277,49 +275,49 @@ void LAN_GetServerAddressString( int source, int n, char *buf, int buflen ) { LAN_GetServerInfo ==================== */ -void LAN_GetServerInfo( int source, int n, char *buf, int buflen ) { +void LAN_GetServerInfo(int source, int n, char *buf, int buflen) { char info[MAX_STRING_CHARS]; serverInfo_t *server = NULL; info[0] = '\0'; switch (source) { - case AS_LOCAL : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - server = &cls.localServers[n]; - } - break; - case AS_MPLAYER: - case AS_GLOBAL : - if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - server = &cls.globalServers[n]; - } - break; - case AS_FAVORITES : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - server = &cls.favoriteServers[n]; - } - break; + case AS_LOCAL: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + server = &cls.localServers[n]; + } + break; + case AS_MPLAYER: + case AS_GLOBAL: + if (n >= 0 && n < MAX_GLOBAL_SERVERS) { + server = &cls.globalServers[n]; + } + break; + case AS_FAVORITES: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + server = &cls.favoriteServers[n]; + } + break; } if (server && buf) { buf[0] = '\0'; - Info_SetValueForKey( info, "hostname", server->hostName); - Info_SetValueForKey( info, "mapname", server->mapName); - Info_SetValueForKey( info, "clients", va("%i",server->clients)); - Info_SetValueForKey( info, "sv_maxclients", va("%i",server->maxClients)); - Info_SetValueForKey( info, "ping", va("%i",server->ping)); - Info_SetValueForKey( info, "minping", va("%i",server->minPing)); - Info_SetValueForKey( info, "maxping", va("%i",server->maxPing)); - Info_SetValueForKey( info, "nettype", va("%i",server->netType)); - Info_SetValueForKey( info, "needpass", va("%i", server->needPassword ) ); - Info_SetValueForKey( info, "truejedi", va("%i", server->trueJedi ) ); - Info_SetValueForKey( info, "wdisable", va("%i", server->weaponDisable ) ); - Info_SetValueForKey( info, "fdisable", va("%i", server->forceDisable ) ); - Info_SetValueForKey( info, "game", server->game); - Info_SetValueForKey( info, "gametype", va("%i",server->gameType)); - Info_SetValueForKey( info, "addr", NET_AdrToString(server->adr)); - Info_SetValueForKey( info, "g_humanplayers", va( "%i", server->humans ) ); - Info_SetValueForKey( info, "bots", va( "%i", server->bots ) ); -// Info_SetValueForKey( info, "sv_allowAnonymous", va("%i", server->allowAnonymous)); -// Info_SetValueForKey( info, "pure", va("%i", server->pure ) ); + Info_SetValueForKey(info, "hostname", server->hostName); + Info_SetValueForKey(info, "mapname", server->mapName); + Info_SetValueForKey(info, "clients", va("%i", server->clients)); + Info_SetValueForKey(info, "sv_maxclients", va("%i", server->maxClients)); + Info_SetValueForKey(info, "ping", va("%i", server->ping)); + Info_SetValueForKey(info, "minping", va("%i", server->minPing)); + Info_SetValueForKey(info, "maxping", va("%i", server->maxPing)); + Info_SetValueForKey(info, "nettype", va("%i", server->netType)); + Info_SetValueForKey(info, "needpass", va("%i", server->needPassword)); + Info_SetValueForKey(info, "truejedi", va("%i", server->trueJedi)); + Info_SetValueForKey(info, "wdisable", va("%i", server->weaponDisable)); + Info_SetValueForKey(info, "fdisable", va("%i", server->forceDisable)); + Info_SetValueForKey(info, "game", server->game); + Info_SetValueForKey(info, "gametype", va("%i", server->gameType)); + Info_SetValueForKey(info, "addr", NET_AdrToString(server->adr)); + Info_SetValueForKey(info, "g_humanplayers", va("%i", server->humans)); + Info_SetValueForKey(info, "bots", va("%i", server->bots)); + // Info_SetValueForKey( info, "sv_allowAnonymous", va("%i", server->allowAnonymous)); + // Info_SetValueForKey( info, "pure", va("%i", server->pure ) ); Q_strncpyz(buf, info, buflen); } else { if (buf) { @@ -333,25 +331,25 @@ void LAN_GetServerInfo( int source, int n, char *buf, int buflen ) { LAN_GetServerPing ==================== */ -int LAN_GetServerPing( int source, int n ) { +int LAN_GetServerPing(int source, int n) { serverInfo_t *server = NULL; switch (source) { - case AS_LOCAL : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - server = &cls.localServers[n]; - } - break; - case AS_MPLAYER: - case AS_GLOBAL : - if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - server = &cls.globalServers[n]; - } - break; - case AS_FAVORITES : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - server = &cls.favoriteServers[n]; - } - break; + case AS_LOCAL: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + server = &cls.localServers[n]; + } + break; + case AS_MPLAYER: + case AS_GLOBAL: + if (n >= 0 && n < MAX_GLOBAL_SERVERS) { + server = &cls.globalServers[n]; + } + break; + case AS_FAVORITES: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + server = &cls.favoriteServers[n]; + } + break; } if (server) { return server->ping; @@ -364,24 +362,24 @@ int LAN_GetServerPing( int source, int n ) { LAN_GetServerPtr ==================== */ -static serverInfo_t *LAN_GetServerPtr( int source, int n ) { +static serverInfo_t *LAN_GetServerPtr(int source, int n) { switch (source) { - case AS_LOCAL : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - return &cls.localServers[n]; - } - break; - case AS_MPLAYER: - case AS_GLOBAL : - if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - return &cls.globalServers[n]; - } - break; - case AS_FAVORITES : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - return &cls.favoriteServers[n]; - } - break; + case AS_LOCAL: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + return &cls.localServers[n]; + } + break; + case AS_MPLAYER: + case AS_GLOBAL: + if (n >= 0 && n < MAX_GLOBAL_SERVERS) { + return &cls.globalServers[n]; + } + break; + case AS_FAVORITES: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + return &cls.favoriteServers[n]; + } + break; } return NULL; } @@ -391,7 +389,7 @@ static serverInfo_t *LAN_GetServerPtr( int source, int n ) { LAN_CompareServers ==================== */ -int LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) { +int LAN_CompareServers(int source, int sortKey, int sortDir, int s1, int s2) { int res; serverInfo_t *server1, *server2; @@ -402,47 +400,41 @@ int LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) { } res = 0; - switch( sortKey ) { - case SORT_HOST: - res = Q_stricmp( server1->hostName, server2->hostName ); - break; - - case SORT_MAP: - res = Q_stricmp( server1->mapName, server2->mapName ); - break; - case SORT_CLIENTS: - if (server1->clients < server2->clients) { - res = -1; - } - else if (server1->clients > server2->clients) { - res = 1; - } - else { - res = 0; - } - break; - case SORT_GAME: - if (server1->gameType < server2->gameType) { - res = -1; - } - else if (server1->gameType > server2->gameType) { - res = 1; - } - else { - res = 0; - } - break; - case SORT_PING: - if (server1->ping < server2->ping) { - res = -1; - } - else if (server1->ping > server2->ping) { - res = 1; - } - else { - res = 0; - } - break; + switch (sortKey) { + case SORT_HOST: + res = Q_stricmp(server1->hostName, server2->hostName); + break; + + case SORT_MAP: + res = Q_stricmp(server1->mapName, server2->mapName); + break; + case SORT_CLIENTS: + if (server1->clients < server2->clients) { + res = -1; + } else if (server1->clients > server2->clients) { + res = 1; + } else { + res = 0; + } + break; + case SORT_GAME: + if (server1->gameType < server2->gameType) { + res = -1; + } else if (server1->gameType > server2->gameType) { + res = 1; + } else { + res = 0; + } + break; + case SORT_PING: + if (server1->ping < server2->ping) { + res = -1; + } else if (server1->ping > server2->ping) { + res = 1; + } else { + res = 0; + } + break; } if (sortDir) { @@ -460,58 +452,50 @@ int LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) { LAN_GetPingQueueCount ==================== */ -int LAN_GetPingQueueCount( void ) { - return (CL_GetPingQueueCount()); -} +int LAN_GetPingQueueCount(void) { return (CL_GetPingQueueCount()); } /* ==================== LAN_ClearPing ==================== */ -void LAN_ClearPing( int n ) { - CL_ClearPing( n ); -} +void LAN_ClearPing(int n) { CL_ClearPing(n); } /* ==================== LAN_GetPing ==================== */ -void LAN_GetPing( int n, char *buf, int buflen, int *pingtime ) { - CL_GetPing( n, buf, buflen, pingtime ); -} +void LAN_GetPing(int n, char *buf, int buflen, int *pingtime) { CL_GetPing(n, buf, buflen, pingtime); } /* ==================== LAN_GetPingInfo ==================== */ -void LAN_GetPingInfo( int n, char *buf, int buflen ) { - CL_GetPingInfo( n, buf, buflen ); -} +void LAN_GetPingInfo(int n, char *buf, int buflen) { CL_GetPingInfo(n, buf, buflen); } /* ==================== LAN_MarkServerVisible ==================== */ -void LAN_MarkServerVisible(int source, int n, qboolean visible ) { +void LAN_MarkServerVisible(int source, int n, qboolean visible) { if (n == -1) { int count = MAX_OTHER_SERVERS; serverInfo_t *server = NULL; switch (source) { - case AS_LOCAL : - server = &cls.localServers[0]; - break; - case AS_MPLAYER: - case AS_GLOBAL : - server = &cls.globalServers[0]; - count = MAX_GLOBAL_SERVERS; - break; - case AS_FAVORITES : - server = &cls.favoriteServers[0]; - break; + case AS_LOCAL: + server = &cls.localServers[0]; + break; + case AS_MPLAYER: + case AS_GLOBAL: + server = &cls.globalServers[0]; + count = MAX_GLOBAL_SERVERS; + break; + case AS_FAVORITES: + server = &cls.favoriteServers[0]; + break; } if (server) { for (n = 0; n < count; n++) { @@ -521,50 +505,49 @@ void LAN_MarkServerVisible(int source, int n, qboolean visible ) { } else { switch (source) { - case AS_LOCAL : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - cls.localServers[n].visible = visible; - } - break; - case AS_MPLAYER: - case AS_GLOBAL : - if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - cls.globalServers[n].visible = visible; - } - break; - case AS_FAVORITES : - if (n >= 0 && n < MAX_OTHER_SERVERS) { - cls.favoriteServers[n].visible = visible; - } - break; - } - } -} - - -/* -======================= -LAN_ServerIsVisible -======================= -*/ -int LAN_ServerIsVisible(int source, int n ) { - switch (source) { - case AS_LOCAL : + case AS_LOCAL: if (n >= 0 && n < MAX_OTHER_SERVERS) { - return cls.localServers[n].visible; + cls.localServers[n].visible = visible; } break; case AS_MPLAYER: - case AS_GLOBAL : + case AS_GLOBAL: if (n >= 0 && n < MAX_GLOBAL_SERVERS) { - return cls.globalServers[n].visible; + cls.globalServers[n].visible = visible; } break; - case AS_FAVORITES : + case AS_FAVORITES: if (n >= 0 && n < MAX_OTHER_SERVERS) { - return cls.favoriteServers[n].visible; + cls.favoriteServers[n].visible = visible; } break; + } + } +} + +/* +======================= +LAN_ServerIsVisible +======================= +*/ +int LAN_ServerIsVisible(int source, int n) { + switch (source) { + case AS_LOCAL: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + return cls.localServers[n].visible; + } + break; + case AS_MPLAYER: + case AS_GLOBAL: + if (n >= 0 && n < MAX_GLOBAL_SERVERS) { + return cls.globalServers[n].visible; + } + break; + case AS_FAVORITES: + if (n >= 0 && n < MAX_OTHER_SERVERS) { + return cls.favoriteServers[n].visible; + } + break; } return qfalse; } @@ -574,15 +557,11 @@ int LAN_ServerIsVisible(int source, int n ) { LAN_UpdateVisiblePings ======================= */ -qboolean LAN_UpdateVisiblePings(int source ) { - return CL_UpdateVisiblePings_f(source); -} +qboolean LAN_UpdateVisiblePings(int source) { return CL_UpdateVisiblePings_f(source); } /* ==================== LAN_GetServerStatus ==================== */ -int LAN_GetServerStatus( const char *serverAddress, char *serverStatus, int maxLen ) { - return CL_ServerStatus( serverAddress, serverStatus, maxLen ); -} +int LAN_GetServerStatus(const char *serverAddress, char *serverStatus, int maxLen) { return CL_ServerStatus(serverAddress, serverStatus, maxLen); } diff --git a/codemp/client/cl_main.cpp b/codemp/client/cl_main.cpp index dca664073a..7d8900b7f3 100644 --- a/codemp/client/cl_main.cpp +++ b/codemp/client/cl_main.cpp @@ -37,96 +37,94 @@ along with this program; if not, see . #include "snd_local.h" #include "sys/sys_loadlib.h" -cvar_t *cl_renderer; +cvar_t *cl_renderer; -cvar_t *cl_nodelta; -cvar_t *cl_debugMove; +cvar_t *cl_nodelta; +cvar_t *cl_debugMove; -cvar_t *cl_noprint; -cvar_t *cl_motd; -cvar_t *cl_motdServer[MAX_MASTER_SERVERS]; +cvar_t *cl_noprint; +cvar_t *cl_motd; +cvar_t *cl_motdServer[MAX_MASTER_SERVERS]; -cvar_t *rcon_client_password; -cvar_t *rconAddress; +cvar_t *rcon_client_password; +cvar_t *rconAddress; -cvar_t *cl_timeout; -cvar_t *cl_maxpackets; -cvar_t *cl_packetdup; -cvar_t *cl_timeNudge; -cvar_t *cl_showTimeDelta; -cvar_t *cl_freezeDemo; +cvar_t *cl_timeout; +cvar_t *cl_maxpackets; +cvar_t *cl_packetdup; +cvar_t *cl_timeNudge; +cvar_t *cl_showTimeDelta; +cvar_t *cl_freezeDemo; -cvar_t *cl_shownet; -cvar_t *cl_showSend; -cvar_t *cl_timedemo; -cvar_t *cl_aviFrameRate; -cvar_t *cl_aviMotionJpeg; -cvar_t *cl_avi2GBLimit; -cvar_t *cl_forceavidemo; +cvar_t *cl_shownet; +cvar_t *cl_showSend; +cvar_t *cl_timedemo; +cvar_t *cl_aviFrameRate; +cvar_t *cl_aviMotionJpeg; +cvar_t *cl_avi2GBLimit; +cvar_t *cl_forceavidemo; -cvar_t *cl_freelook; -cvar_t *cl_sensitivity; +cvar_t *cl_freelook; +cvar_t *cl_sensitivity; -cvar_t *cl_mouseAccel; -cvar_t *cl_mouseAccelOffset; -cvar_t *cl_mouseAccelStyle; -cvar_t *cl_showMouseRate; +cvar_t *cl_mouseAccel; +cvar_t *cl_mouseAccelOffset; +cvar_t *cl_mouseAccelStyle; +cvar_t *cl_showMouseRate; -cvar_t *m_pitchVeh; -cvar_t *m_pitch; -cvar_t *m_yaw; -cvar_t *m_forward; -cvar_t *m_side; -cvar_t *m_filter; +cvar_t *m_pitchVeh; +cvar_t *m_pitch; +cvar_t *m_yaw; +cvar_t *m_forward; +cvar_t *m_side; +cvar_t *m_filter; -cvar_t *cl_activeAction; +cvar_t *cl_activeAction; -cvar_t *cl_motdString; +cvar_t *cl_motdString; -cvar_t *cl_allowDownload; -cvar_t *cl_allowAltEnter; -cvar_t *cl_conXOffset; -cvar_t *cl_inGameVideo; +cvar_t *cl_allowDownload; +cvar_t *cl_allowAltEnter; +cvar_t *cl_conXOffset; +cvar_t *cl_inGameVideo; -cvar_t *cl_serverStatusResendTime; -cvar_t *cl_framerate; +cvar_t *cl_serverStatusResendTime; +cvar_t *cl_framerate; // cvar to enable sending a "ja_guid" player identifier in userinfo to servers // ja_guid is a persistent "cookie" that allows servers to track players across game sessions -cvar_t *cl_enableGuid; -cvar_t *cl_guidServerUniq; +cvar_t *cl_enableGuid; +cvar_t *cl_guidServerUniq; -cvar_t *cl_autolodscale; +cvar_t *cl_autolodscale; -cvar_t *cl_consoleKeys; -cvar_t *cl_consoleUseScanCode; -cvar_t *cl_consoleShiftRequirement; +cvar_t *cl_consoleKeys; +cvar_t *cl_consoleUseScanCode; +cvar_t *cl_consoleShiftRequirement; -cvar_t *cl_lanForcePackets; +cvar_t *cl_lanForcePackets; -cvar_t *cl_drawRecording; +cvar_t *cl_drawRecording; -cvar_t *cl_filterGames; +cvar_t *cl_filterGames; vec3_t cl_windVec; - -clientActive_t cl; -clientConnection_t clc; -clientStatic_t cls; +clientActive_t cl; +clientConnection_t clc; +clientStatic_t cls; netadr_t rcon_address; char cl_reconnectArgs[MAX_OSPATH] = {0}; // Structure containing functions exported from refresh DLL -refexport_t *re = NULL; -static void *rendererLib = NULL; +refexport_t *re = NULL; +static void *rendererLib = NULL; -ping_t cl_pinglist[MAX_PINGREQUESTS]; +ping_t cl_pinglist[MAX_PINGREQUESTS]; -typedef struct serverStatus_s -{ +typedef struct serverStatus_s { char string[BIG_INFO_STRING]; netadr_t address; int time, startTime; @@ -140,12 +138,12 @@ int serverStatusCount; IHeapAllocator *G2VertSpaceClient = 0; -extern void SV_BotFrame( int time ); -void CL_CheckForResend( void ); +extern void SV_BotFrame(int time); +void CL_CheckForResend(void); void CL_ShowIP_f(void); void CL_ServerStatus_f(void); -void CL_ServerStatusResponse( netadr_t from, msg_t *msg ); -static void CL_ShutdownRef( qboolean restarting ); +void CL_ServerStatusResponse(netadr_t from, msg_t *msg); +static void CL_ShutdownRef(qboolean restarting); /* ======================================================================= @@ -163,24 +161,21 @@ The given command will be transmitted to the server, and is gauranteed to not have future usercmd_t executed before it is executed ====================== */ -void CL_AddReliableCommand( const char *cmd, qboolean isDisconnectCmd ) { +void CL_AddReliableCommand(const char *cmd, qboolean isDisconnectCmd) { int unacknowledged = clc.reliableSequence - clc.reliableAcknowledge; // if we would be losing an old command that hasn't been acknowledged, // we must drop the connection // also leave one slot open for the disconnect command in this case. - if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) || - (!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS)) - { - if(com_errorEntered) + if ((isDisconnectCmd && unacknowledged > MAX_RELIABLE_COMMANDS) || (!isDisconnectCmd && unacknowledged >= MAX_RELIABLE_COMMANDS)) { + if (com_errorEntered) return; else Com_Error(ERR_DROP, "Client command overflow"); } - Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)], - cmd, sizeof(*clc.reliableCommands)); + Q_strncpyz(clc.reliableCommands[++clc.reliableSequence & (MAX_RELIABLE_COMMANDS - 1)], cmd, sizeof(*clc.reliableCommands)); } /* @@ -198,22 +193,21 @@ CL_WriteDemoMessage Dumps the current net message, prefixed by the length ==================== */ -void CL_WriteDemoMessage ( msg_t *msg, int headerBytes ) { - int len, swlen; +void CL_WriteDemoMessage(msg_t *msg, int headerBytes) { + int len, swlen; // write the packet sequence len = clc.serverMessageSequence; - swlen = LittleLong( len ); - FS_Write (&swlen, 4, clc.demofile); + swlen = LittleLong(len); + FS_Write(&swlen, 4, clc.demofile); // skip the packet sequencing information len = msg->cursize - headerBytes; swlen = LittleLong(len); - FS_Write (&swlen, 4, clc.demofile); - FS_Write ( msg->data + headerBytes, len, clc.demofile ); + FS_Write(&swlen, 4, clc.demofile); + FS_Write(msg->data + headerBytes, len, clc.demofile); } - /* ==================== CL_StopRecording_f @@ -221,23 +215,23 @@ CL_StopRecording_f stop recording a demo ==================== */ -void CL_StopRecord_f( void ) { - int len; +void CL_StopRecord_f(void) { + int len; - if ( !clc.demorecording ) { - Com_Printf ("Not recording a demo.\n"); + if (!clc.demorecording) { + Com_Printf("Not recording a demo.\n"); return; } // finish up len = -1; - FS_Write (&len, 4, clc.demofile); - FS_Write (&len, 4, clc.demofile); - FS_FCloseFile (clc.demofile); + FS_Write(&len, 4, clc.demofile); + FS_Write(&len, 4, clc.demofile); + FS_FCloseFile(clc.demofile); clc.demofile = 0; clc.demorecording = qfalse; clc.spDemoRecording = qfalse; - Com_Printf ("Stopped demo.\n"); + Com_Printf("Stopped demo.\n"); } /* @@ -245,14 +239,14 @@ void CL_StopRecord_f( void ) { CL_DemoFilename ================== */ -void CL_DemoFilename( char *buf, int bufSize ) { +void CL_DemoFilename(char *buf, int bufSize) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "demo%s", timeStr ); + Com_sprintf(buf, bufSize, "demo%s", timeStr); } /* @@ -264,108 +258,108 @@ record Begins recording a demo from the current position ==================== */ -static char demoName[MAX_QPATH]; // compiler bug workaround -void CL_Record_f( void ) { - char name[MAX_OSPATH]; - byte bufData[MAX_MSGLEN]; - msg_t buf; - int i; - int len; - entityState_t *ent; - entityState_t nullstate; - char *s; +static char demoName[MAX_QPATH]; // compiler bug workaround +void CL_Record_f(void) { + char name[MAX_OSPATH]; + byte bufData[MAX_MSGLEN]; + msg_t buf; + int i; + int len; + entityState_t *ent; + entityState_t nullstate; + char *s; - if ( Cmd_Argc() > 2 ) { - Com_Printf ("record \n"); + if (Cmd_Argc() > 2) { + Com_Printf("record \n"); return; } - if ( clc.demorecording ) { + if (clc.demorecording) { if (!clc.spDemoRecording) { - Com_Printf ("Already recording.\n"); + Com_Printf("Already recording.\n"); } return; } - if ( cls.state != CA_ACTIVE ) { - Com_Printf ("You must be in a level to record.\n"); + if (cls.state != CA_ACTIVE) { + Com_Printf("You must be in a level to record.\n"); return; } // sync 0 doesn't prevent recording, so not forcing it off .. everyone does g_sync 1 ; record ; g_sync 0 .. - if ( NET_IsLocalAddress( clc.serverAddress ) && !Cvar_VariableValue( "g_synchronousClients" ) ) { - Com_Printf (S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n"); + if (NET_IsLocalAddress(clc.serverAddress) && !Cvar_VariableValue("g_synchronousClients")) { + Com_Printf(S_COLOR_YELLOW "WARNING: You should set 'g_synchronousClients 1' for smoother demo recording\n"); } - if ( Cmd_Argc() == 2 ) { + if (Cmd_Argc() == 2) { s = Cmd_Argv(1); - Q_strncpyz( demoName, s, sizeof( demoName ) ); - Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); + Q_strncpyz(demoName, s, sizeof(demoName)); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION); } else { // timestamp the file - CL_DemoFilename( demoName, sizeof( demoName ) ); + CL_DemoFilename(demoName, sizeof(demoName)); - Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION); - if ( FS_FileExists( name ) ) { - Com_Printf( "Record: Couldn't create a file\n"); + if (FS_FileExists(name)) { + Com_Printf("Record: Couldn't create a file\n"); return; - } + } } // open the demo file - Com_Printf ("recording to %s.\n", name); - clc.demofile = FS_FOpenFileWrite( name ); - if ( !clc.demofile ) { - Com_Printf ("ERROR: couldn't open.\n"); + Com_Printf("recording to %s.\n", name); + clc.demofile = FS_FOpenFileWrite(name); + if (!clc.demofile) { + Com_Printf("ERROR: couldn't open.\n"); return; } clc.demorecording = qtrue; if (Cvar_VariableValue("ui_recordSPDemo")) { - clc.spDemoRecording = qtrue; + clc.spDemoRecording = qtrue; } else { - clc.spDemoRecording = qfalse; + clc.spDemoRecording = qfalse; } - Q_strncpyz( clc.demoName, demoName, sizeof( clc.demoName ) ); + Q_strncpyz(clc.demoName, demoName, sizeof(clc.demoName)); // don't start saving messages until a non-delta compressed message is received clc.demowaiting = qtrue; // write out the gamestate message - MSG_Init (&buf, bufData, sizeof(bufData)); + MSG_Init(&buf, bufData, sizeof(bufData)); MSG_Bitstream(&buf); // NOTE, MRE: all server->client messages now acknowledge - MSG_WriteLong( &buf, clc.reliableSequence ); + MSG_WriteLong(&buf, clc.reliableSequence); - MSG_WriteByte (&buf, svc_gamestate); - MSG_WriteLong (&buf, clc.serverCommandSequence ); + MSG_WriteByte(&buf, svc_gamestate); + MSG_WriteLong(&buf, clc.serverCommandSequence); // configstrings - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( !cl.gameState.stringOffsets[i] ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (!cl.gameState.stringOffsets[i]) { continue; } s = cl.gameState.stringData + cl.gameState.stringOffsets[i]; - MSG_WriteByte (&buf, svc_configstring); - MSG_WriteShort (&buf, i); - MSG_WriteBigString (&buf, s); + MSG_WriteByte(&buf, svc_configstring); + MSG_WriteShort(&buf, i); + MSG_WriteBigString(&buf, s); } // baselines - Com_Memset (&nullstate, 0, sizeof(nullstate)); - for ( i = 0; i < MAX_GENTITIES ; i++ ) { + Com_Memset(&nullstate, 0, sizeof(nullstate)); + for (i = 0; i < MAX_GENTITIES; i++) { ent = &cl.entityBaselines[i]; - if ( !ent->number ) { + if (!ent->number) { continue; } - MSG_WriteByte (&buf, svc_baseline); - MSG_WriteDeltaEntity (&buf, &nullstate, ent, qtrue ); + MSG_WriteByte(&buf, svc_baseline); + MSG_WriteDeltaEntity(&buf, &nullstate, ent, qtrue); } - MSG_WriteByte( &buf, svc_EOF ); + MSG_WriteByte(&buf, svc_EOF); // finished writing the gamestate stuff @@ -375,18 +369,18 @@ void CL_Record_f( void ) { MSG_WriteLong(&buf, clc.checksumFeed); // Filler for old RMG system. - MSG_WriteShort ( &buf, 0 ); + MSG_WriteShort(&buf, 0); // finished writing the client packet - MSG_WriteByte( &buf, svc_EOF ); + MSG_WriteByte(&buf, svc_EOF); // write it to the demo file - len = LittleLong( clc.serverMessageSequence - 1 ); - FS_Write (&len, 4, clc.demofile); + len = LittleLong(clc.serverMessageSequence - 1); + FS_Write(&len, 4, clc.demofile); - len = LittleLong (buf.cursize); - FS_Write (&len, 4, clc.demofile); - FS_Write (buf.data, buf.cursize, clc.demofile); + len = LittleLong(buf.cursize); + FS_Write(&len, 4, clc.demofile); + FS_Write(buf.data, buf.cursize, clc.demofile); // the rest of the demo file will be copied from net messages } @@ -404,27 +398,26 @@ CLIENT SIDE DEMO PLAYBACK CL_DemoCompleted ================= */ -void CL_DemoCompleted( void ) { +void CL_DemoCompleted(void) { if (cl_timedemo && cl_timedemo->integer) { - int time; + int time; time = Sys_Milliseconds() - clc.timeDemoStart; - if ( time > 0 ) { - Com_Printf ("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames, - time/1000.0, clc.timeDemoFrames*1000.0 / time); + if (time > 0) { + Com_Printf("%i frames, %3.1f seconds: %3.1f fps\n", clc.timeDemoFrames, time / 1000.0, clc.timeDemoFrames * 1000.0 / time); } } -/* CL_Disconnect( qtrue ); - CL_NextDemo(); - */ + /* CL_Disconnect( qtrue ); + CL_NextDemo(); + */ - //rww - The above code seems to just stick you in a no-menu state and you can't do anything there. - //I'm not sure why it ever worked in TA, but whatever. This code will bring us back to the main menu - //after a demo is finished playing instead. + // rww - The above code seems to just stick you in a no-menu state and you can't do anything there. + // I'm not sure why it ever worked in TA, but whatever. This code will bring us back to the main menu + // after a demo is finished playing instead. CL_Disconnect_f(); S_StopAllSounds(); - UIVM_SetActiveMenu( UIMENU_MAIN ); + UIVM_SetActiveMenu(UIMENU_MAIN); CL_NextDemo(); } @@ -434,52 +427,52 @@ void CL_DemoCompleted( void ) { CL_ReadDemoMessage ================= */ -void CL_ReadDemoMessage( void ) { - int r; - msg_t buf; - byte bufData[ MAX_MSGLEN ]; - int s; +void CL_ReadDemoMessage(void) { + int r; + msg_t buf; + byte bufData[MAX_MSGLEN]; + int s; - if ( !clc.demofile ) { - CL_DemoCompleted (); + if (!clc.demofile) { + CL_DemoCompleted(); return; } // get the sequence number - r = FS_Read( &s, 4, clc.demofile); - if ( r != 4 ) { - CL_DemoCompleted (); + r = FS_Read(&s, 4, clc.demofile); + if (r != 4) { + CL_DemoCompleted(); return; } - clc.serverMessageSequence = LittleLong( s ); + clc.serverMessageSequence = LittleLong(s); // init the message - MSG_Init( &buf, bufData, sizeof( bufData ) ); + MSG_Init(&buf, bufData, sizeof(bufData)); // get the length - r = FS_Read (&buf.cursize, 4, clc.demofile); - if ( r != 4 ) { - CL_DemoCompleted (); + r = FS_Read(&buf.cursize, 4, clc.demofile); + if (r != 4) { + CL_DemoCompleted(); return; } - buf.cursize = LittleLong( buf.cursize ); - if ( buf.cursize == -1 ) { - CL_DemoCompleted (); + buf.cursize = LittleLong(buf.cursize); + if (buf.cursize == -1) { + CL_DemoCompleted(); return; } - if ( buf.cursize > buf.maxsize ) { - Com_Error (ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN"); + if (buf.cursize > buf.maxsize) { + Com_Error(ERR_DROP, "CL_ReadDemoMessage: demoMsglen > MAX_MSGLEN"); } - r = FS_Read( buf.data, buf.cursize, clc.demofile ); - if ( r != buf.cursize ) { - Com_Printf( "Demo file was truncated.\n"); - CL_DemoCompleted (); + r = FS_Read(buf.data, buf.cursize, clc.demofile); + if (r != buf.cursize) { + Com_Printf("Demo file was truncated.\n"); + CL_DemoCompleted(); return; } clc.lastPacketTime = cls.realtime; buf.readcount = 0; - CL_ParseServerMessage( &buf ); + CL_ParseServerMessage(&buf); } /* @@ -487,14 +480,12 @@ void CL_ReadDemoMessage( void ) { CL_CompleteDemoName ==================== */ -static void CL_CompleteDemoName( char *args, int argNum ) -{ - if( argNum == 2 ) - { +static void CL_CompleteDemoName(char *args, int argNum) { + if (argNum == 2) { char demoExt[16]; Com_sprintf(demoExt, sizeof(demoExt), ".dm_%d", PROTOCOL_VERSION); - Field_CompleteFilename( "demos", demoExt, qtrue, qtrue ); + Field_CompleteFilename("demos", demoExt, qtrue, qtrue); } } @@ -506,53 +497,50 @@ demo ==================== */ -void CL_PlayDemo_f( void ) { - char name[MAX_OSPATH], extension[32]; - char *arg; +void CL_PlayDemo_f(void) { + char name[MAX_OSPATH], extension[32]; + char *arg; if (Cmd_Argc() != 2) { - Com_Printf ("demo \n"); + Com_Printf("demo \n"); return; } // make sure a local server is killed // 2 means don't force disconnect of local client - Cvar_Set( "sv_killserver", "2" ); + Cvar_Set("sv_killserver", "2"); // open the demo file arg = Cmd_Argv(1); - CL_Disconnect( qtrue ); + CL_Disconnect(qtrue); Com_sprintf(extension, sizeof(extension), ".dm_%d", PROTOCOL_VERSION); - if ( !Q_stricmp( arg + strlen(arg) - strlen(extension), extension ) ) { - Com_sprintf (name, sizeof(name), "demos/%s", arg); + if (!Q_stricmp(arg + strlen(arg) - strlen(extension), extension)) { + Com_sprintf(name, sizeof(name), "demos/%s", arg); } else { - Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", arg, PROTOCOL_VERSION); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", arg, PROTOCOL_VERSION); } - FS_FOpenFileRead( name, &clc.demofile, qtrue ); + FS_FOpenFileRead(name, &clc.demofile, qtrue); if (!clc.demofile) { - if (!Q_stricmp(arg, "(null)")) - { - Com_Error( ERR_DROP, SE_GetString("CON_TEXT_NO_DEMO_SELECTED") ); - } - else - { - Com_Error( ERR_DROP, "couldn't open %s", name); + if (!Q_stricmp(arg, "(null)")) { + Com_Error(ERR_DROP, SE_GetString("CON_TEXT_NO_DEMO_SELECTED")); + } else { + Com_Error(ERR_DROP, "couldn't open %s", name); } return; } - Q_strncpyz( clc.demoName, Cmd_Argv(1), sizeof( clc.demoName ) ); + Q_strncpyz(clc.demoName, Cmd_Argv(1), sizeof(clc.demoName)); Con_Close(); cls.state = CA_CONNECTED; clc.demoplaying = qtrue; - Q_strncpyz( cls.servername, Cmd_Argv(1), sizeof( cls.servername ) ); + Q_strncpyz(cls.servername, Cmd_Argv(1), sizeof(cls.servername)); // read demo messages until connected - while ( cls.state >= CA_CONNECTED && cls.state < CA_PRIMED ) { + while (cls.state >= CA_CONNECTED && cls.state < CA_PRIMED) { CL_ReadDemoMessage(); } // don't get the first snapshot this frame, to prevent the long @@ -560,7 +548,6 @@ void CL_PlayDemo_f( void ) { clc.firstDemoFrameSkipped = qfalse; } - /* ==================== CL_StartDemoLoop @@ -568,10 +555,10 @@ CL_StartDemoLoop Closing the main menu will restart the demo loop ==================== */ -void CL_StartDemoLoop( void ) { +void CL_StartDemoLoop(void) { // start the demo loop again - Cbuf_AddText ("d1\n"); - Key_SetCatcher( 0 ); + Cbuf_AddText("d1\n"); + Key_SetCatcher(0); } /* @@ -582,19 +569,19 @@ Called when a demo or cinematic finishes If the "nextdemo" cvar is set, that command will be issued ================== */ -void CL_NextDemo( void ) { - char v[MAX_STRING_CHARS]; +void CL_NextDemo(void) { + char v[MAX_STRING_CHARS]; - Q_strncpyz( v, Cvar_VariableString ("nextdemo"), sizeof(v) ); - v[MAX_STRING_CHARS-1] = 0; - Com_DPrintf("CL_NextDemo: %s\n", v ); + Q_strncpyz(v, Cvar_VariableString("nextdemo"), sizeof(v)); + v[MAX_STRING_CHARS - 1] = 0; + Com_DPrintf("CL_NextDemo: %s\n", v); if (!v[0]) { return; } - Cvar_Set ("nextdemo",""); - Cbuf_AddText (v); - Cbuf_AddText ("\n"); + Cvar_Set("nextdemo", ""); + Cbuf_AddText(v); + Cbuf_AddText("\n"); Cbuf_Execute(); } @@ -605,14 +592,14 @@ void CL_NextDemo( void ) { CL_ShutdownAll ===================== */ -void CL_ShutdownAll( qboolean shutdownRef ) { - if(CL_VideoRecording()) +void CL_ShutdownAll(qboolean shutdownRef) { + if (CL_VideoRecording()) CL_CloseAVI(); - if(clc.demorecording) + if (clc.demorecording) CL_StopRecord_f(); -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. //so it doesn't barf on shutdown saying refentities belong to each other tr.refdef.num_entities = 0; #endif @@ -625,10 +612,10 @@ void CL_ShutdownAll( qboolean shutdownRef ) { CL_ShutdownUI(); // shutdown the renderer - if(shutdownRef) - CL_ShutdownRef( qfalse ); - if ( re && re->Shutdown ) { - re->Shutdown( qfalse, qfalse ); // don't destroy window or context + if (shutdownRef) + CL_ShutdownRef(qfalse); + if (re && re->Shutdown) { + re->Shutdown(qfalse, qfalse); // don't destroy window or context } cls.uiStarted = qfalse; @@ -646,19 +633,18 @@ ways a client gets into a game Also called by Com_Error ================= */ -void CL_FlushMemory( void ) { +void CL_FlushMemory(void) { // shutdown all the client stuff - CL_ShutdownAll( qfalse ); + CL_ShutdownAll(qfalse); // if not running a server clear the whole hunk - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { // clear collision map data CM_ClearMap(); // clear the whole hunk Hunk_Clear(); - } - else { + } else { // clear all the client data on the hunk Hunk_ClearToMark(); } @@ -675,36 +661,36 @@ screen to let the user know about it, then dump all client memory on the hunk from cgame, ui, and renderer ===================== */ -void CL_MapLoading( void ) { - if ( !com_cl_running->integer ) { +void CL_MapLoading(void) { + if (!com_cl_running->integer) { return; } // Set this to localhost. - Cvar_Set( "cl_currentServerAddress", "Localhost"); - Cvar_Set( "cl_currentServerIP", "loopback"); + Cvar_Set("cl_currentServerAddress", "Localhost"); + Cvar_Set("cl_currentServerIP", "loopback"); Con_Close(); - Key_SetCatcher( 0 ); + Key_SetCatcher(0); // if we are already connected to the local host, stay connected - if ( cls.state >= CA_CONNECTED && !Q_stricmp( cls.servername, "localhost" ) ) { - cls.state = CA_CONNECTED; // so the connect screen is drawn - Com_Memset( cls.updateInfoString, 0, sizeof( cls.updateInfoString ) ); - Com_Memset( clc.serverMessage, 0, sizeof( clc.serverMessage ) ); - Com_Memset( &cl.gameState, 0, sizeof( cl.gameState ) ); + if (cls.state >= CA_CONNECTED && !Q_stricmp(cls.servername, "localhost")) { + cls.state = CA_CONNECTED; // so the connect screen is drawn + Com_Memset(cls.updateInfoString, 0, sizeof(cls.updateInfoString)); + Com_Memset(clc.serverMessage, 0, sizeof(clc.serverMessage)); + Com_Memset(&cl.gameState, 0, sizeof(cl.gameState)); clc.lastPacketSentTime = -9999; SCR_UpdateScreen(); } else { // clear nextmap so the cinematic shutdown doesn't execute it - Cvar_Set( "nextmap", "" ); - CL_Disconnect( qtrue ); - Q_strncpyz( cls.servername, "localhost", sizeof(cls.servername) ); - cls.state = CA_CHALLENGING; // so the connect screen is drawn - Key_SetCatcher( 0 ); + Cvar_Set("nextmap", ""); + CL_Disconnect(qtrue); + Q_strncpyz(cls.servername, "localhost", sizeof(cls.servername)); + cls.state = CA_CHALLENGING; // so the connect screen is drawn + Key_SetCatcher(0); SCR_UpdateScreen(); clc.connectTime = -RETRANSMIT_TIMEOUT; - NET_StringToAdr( cls.servername, &clc.serverAddress); + NET_StringToAdr(cls.servername, &clc.serverAddress); // we don't need a challenge on the localhost CL_CheckForResend(); @@ -718,10 +704,10 @@ CL_ClearState Called before parsing a gamestate ===================== */ -void CL_ClearState (void) { +void CL_ClearState(void) { -// S_StopAllSounds(); - Com_Memset( &cl, 0, sizeof( cl ) ); + // S_StopAllSounds(); + Com_Memset(&cl, 0, sizeof(cl)); } /* @@ -731,31 +717,29 @@ CL_UpdateGUID update cl_guid using QKEY_FILE and optional prefix ==================== */ -static void CL_UpdateGUID( const char *prefix, int prefix_len ) -{ +static void CL_UpdateGUID(const char *prefix, int prefix_len) { if (cl_enableGuid->integer) { fileHandle_t f; int len; - len = FS_SV_FOpenFileRead( QKEY_FILE, &f ); - FS_FCloseFile( f ); + len = FS_SV_FOpenFileRead(QKEY_FILE, &f); + FS_FCloseFile(f); // initialize the cvar here in case it's unset or was user-created // while tracking was disabled (removes CVAR_USER_CREATED) - Cvar_Get( "ja_guid", "", CVAR_USERINFO | CVAR_ROM, "Client GUID" ); + Cvar_Get("ja_guid", "", CVAR_USERINFO | CVAR_ROM, "Client GUID"); - if( len != QKEY_SIZE ) { - Cvar_Set( "ja_guid", "" ); + if (len != QKEY_SIZE) { + Cvar_Set("ja_guid", ""); } else { - Cvar_Set( "ja_guid", Com_MD5File( QKEY_FILE, QKEY_SIZE, - prefix, prefix_len ) ); + Cvar_Set("ja_guid", Com_MD5File(QKEY_FILE, QKEY_SIZE, prefix, prefix_len)); } } else { // Remove the cvar entirely if tracking is disabled uint32_t flags = Cvar_Flags("ja_guid"); // keep the cvar if it's user-created, but destroy it otherwise if (flags != CVAR_NONEXISTENT && !(flags & CVAR_USER_CREATED)) { - cvar_t *ja_guid = Cvar_Get("ja_guid", "", 0, "Client GUID" ); + cvar_t *ja_guid = Cvar_Get("ja_guid", "", 0, "Client GUID"); Cvar_Unset(ja_guid); } } @@ -771,41 +755,41 @@ Sends a disconnect message to the server This is also called on Com_Error and Com_Quit, so it shouldn't cause any errors ===================== */ -void CL_Disconnect( qboolean showMainMenu ) { - if ( !com_cl_running || !com_cl_running->integer ) { +void CL_Disconnect(qboolean showMainMenu) { + if (!com_cl_running || !com_cl_running->integer) { return; } // shutting down the client so enter full screen ui mode Cvar_Set("r_uiFullScreen", "1"); - if ( clc.demorecording ) { - CL_StopRecord_f (); + if (clc.demorecording) { + CL_StopRecord_f(); } if (clc.download) { - FS_FCloseFile( clc.download ); + FS_FCloseFile(clc.download); clc.download = 0; } *clc.downloadTempName = *clc.downloadName = 0; - Cvar_Set( "cl_downloadName", "" ); + Cvar_Set("cl_downloadName", ""); - if ( clc.demofile ) { - FS_FCloseFile( clc.demofile ); + if (clc.demofile) { + FS_FCloseFile(clc.demofile); clc.demofile = 0; } - if ( cls.uiStarted && showMainMenu ) { - UIVM_SetActiveMenu( UIMENU_NONE ); + if (cls.uiStarted && showMainMenu) { + UIVM_SetActiveMenu(UIMENU_NONE); } - SCR_StopCinematic (); + SCR_StopCinematic(); S_ClearSoundBuffer(); // send a disconnect message to the server // send it a few times in case one is dropped - if ( cls.state >= CA_CONNECTED ) { - CL_AddReliableCommand( "disconnect", qtrue ); + if (cls.state >= CA_CONNECTED) { + CL_AddReliableCommand("disconnect", qtrue); CL_WritePacket(); CL_WritePacket(); CL_WritePacket(); @@ -815,30 +799,29 @@ void CL_Disconnect( qboolean showMainMenu ) { FS_PureServerSetLoadedPaks("", ""); FS_PureServerSetReferencedPaks("", ""); - CL_ClearState (); + CL_ClearState(); // wipe the client connection - Com_Memset( &clc, 0, sizeof( clc ) ); + Com_Memset(&clc, 0, sizeof(clc)); cls.state = CA_DISCONNECTED; // allow cheats locally - Cvar_Set( "sv_cheats", "1" ); + Cvar_Set("sv_cheats", "1"); // not connected to a pure server anymore cl_connectedToPureServer = qfalse; // Stop recording any video - if( CL_VideoRecording( ) ) { + if (CL_VideoRecording()) { // Finish rendering current frame - SCR_UpdateScreen( ); - CL_CloseAVI( ); + SCR_UpdateScreen(); + CL_CloseAVI(); } - CL_UpdateGUID( NULL, 0 ); + CL_UpdateGUID(NULL, 0); } - /* =================== CL_ForwardCommandToServer @@ -848,25 +831,25 @@ things like godmode, noclip, etc, are commands directed to the server, so when they are typed in at the console, they will need to be forwarded. =================== */ -void CL_ForwardCommandToServer( const char *string ) { - char *cmd; +void CL_ForwardCommandToServer(const char *string) { + char *cmd; cmd = Cmd_Argv(0); // ignore key up commands - if ( cmd[0] == '-' ) { + if (cmd[0] == '-') { return; } - if (clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+' ) { - Com_Printf ("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd); + if (clc.demoplaying || cls.state < CA_CONNECTED || cmd[0] == '+') { + Com_Printf("Unknown command \"%s" S_COLOR_WHITE "\"\n", cmd); return; } - if ( Cmd_Argc() > 1 ) { - CL_AddReliableCommand( string, qfalse ); + if (Cmd_Argc() > 1) { + CL_AddReliableCommand(string, qfalse); } else { - CL_AddReliableCommand( cmd, qfalse ); + CL_AddReliableCommand(cmd, qfalse); } } @@ -876,70 +859,67 @@ CL_RequestMotd =================== */ -void CL_RequestMotd( void ) { - netadr_t to; - int i; - char command[MAX_STRING_CHARS], info[MAX_INFO_STRING]; - char *motdaddress; +void CL_RequestMotd(void) { + netadr_t to; + int i; + char command[MAX_STRING_CHARS], info[MAX_INFO_STRING]; + char *motdaddress; - if ( !cl_motd->integer ) { + if (!cl_motd->integer) { return; } - if ( cl_motd->integer < 1 || cl_motd->integer > MAX_MASTER_SERVERS ) { - Com_Printf( "CL_RequestMotd: Invalid motd server num. Valid values are 1-%d or 0 to disable\n", MAX_MASTER_SERVERS ); + if (cl_motd->integer < 1 || cl_motd->integer > MAX_MASTER_SERVERS) { + Com_Printf("CL_RequestMotd: Invalid motd server num. Valid values are 1-%d or 0 to disable\n", MAX_MASTER_SERVERS); return; } - Com_sprintf( command, sizeof(command), "cl_motdServer%d", cl_motd->integer ); - motdaddress = Cvar_VariableString( command ); + Com_sprintf(command, sizeof(command), "cl_motdServer%d", cl_motd->integer); + motdaddress = Cvar_VariableString(command); - if ( !*motdaddress ) - { - Com_Printf( "CL_RequestMotd: Error: No motd server address given.\n" ); + if (!*motdaddress) { + Com_Printf("CL_RequestMotd: Error: No motd server address given.\n"); return; } - i = NET_StringToAdr( motdaddress, &to ); + i = NET_StringToAdr(motdaddress, &to); - if ( !i ) - { - Com_Printf( "CL_RequestMotd: Error: could not resolve address of motd server %s\n", motdaddress ); + if (!i) { + Com_Printf("CL_RequestMotd: Error: could not resolve address of motd server %s\n", motdaddress); return; } to.type = NA_IP; - to.port = BigShort( PORT_UPDATE ); + to.port = BigShort(PORT_UPDATE); - Com_Printf( "Requesting motd from update %s (%s)...\n", motdaddress, NET_AdrToString( to ) ); + Com_Printf("Requesting motd from update %s (%s)...\n", motdaddress, NET_AdrToString(to)); cls.updateServer = to; info[0] = 0; - // NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization - // only srand I could catch before here is tr_noise.c l:26 srand(1001) - // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382 - // NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word, - // but I decided it was enough randomization - Com_sprintf( cls.updateChallenge, sizeof( cls.updateChallenge ), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds()); - - Info_SetValueForKey( info, "challenge", cls.updateChallenge ); - Info_SetValueForKey( info, "renderer", cls.glconfig.renderer_string ); - Info_SetValueForKey( info, "rvendor", cls.glconfig.vendor_string ); - Info_SetValueForKey( info, "version", com_version->string ); - - //If raven starts filtering for this, add this code back in + // NOTE TTimo xoring against Com_Milliseconds, otherwise we may not have a true randomization + // only srand I could catch before here is tr_noise.c l:26 srand(1001) + // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=382 + // NOTE: the Com_Milliseconds xoring only affects the lower 16-bit word, + // but I decided it was enough randomization + Com_sprintf(cls.updateChallenge, sizeof(cls.updateChallenge), "%i", ((rand() << 16) ^ rand()) ^ Com_Milliseconds()); + + Info_SetValueForKey(info, "challenge", cls.updateChallenge); + Info_SetValueForKey(info, "renderer", cls.glconfig.renderer_string); + Info_SetValueForKey(info, "rvendor", cls.glconfig.vendor_string); + Info_SetValueForKey(info, "version", com_version->string); + + // If raven starts filtering for this, add this code back in #if 0 Info_SetValueForKey( info, "cputype", "Intel Pentium IV"); Info_SetValueForKey( info, "mhz", "3000" ); Info_SetValueForKey( info, "memory", "4096" ); #endif - Info_SetValueForKey( info, "joystick", Cvar_VariableString("in_joystick") ); - Info_SetValueForKey( info, "colorbits", va("%d",cls.glconfig.colorBits) ); + Info_SetValueForKey(info, "joystick", Cvar_VariableString("in_joystick")); + Info_SetValueForKey(info, "colorbits", va("%d", cls.glconfig.colorBits)); - NET_OutOfBandPrint( NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info ); + NET_OutOfBandPrint(NS_CLIENT, cls.updateServer, "getmotd \"%s\"\n", info); } - /* ====================================================================== @@ -953,45 +933,43 @@ CONSOLE COMMANDS CL_ForwardToServer_f ================== */ -void CL_ForwardToServer_f( void ) { - if ( cls.state != CA_ACTIVE || clc.demoplaying ) { - Com_Printf ("Not connected to a server.\n"); +void CL_ForwardToServer_f(void) { + if (cls.state != CA_ACTIVE || clc.demoplaying) { + Com_Printf("Not connected to a server.\n"); return; } // don't forward the first argument - if ( Cmd_Argc() > 1 ) { - CL_AddReliableCommand( Cmd_Args(), qfalse ); + if (Cmd_Argc() > 1) { + CL_AddReliableCommand(Cmd_Args(), qfalse); } } - /* ================== CL_Disconnect_f ================== */ -void CL_Disconnect_f( void ) { +void CL_Disconnect_f(void) { SCR_StopCinematic(); Cvar_Set("ui_singlePlayerActive", "0"); - if ( cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC ) { - Com_Error (ERR_DISCONNECT, "Disconnected from server"); + if (cls.state != CA_DISCONNECTED && cls.state != CA_CINEMATIC) { + Com_Error(ERR_DISCONNECT, "Disconnected from server"); } } - /* ================ CL_Reconnect_f ================ */ -void CL_Reconnect_f( void ) { - if ( !strlen( cl_reconnectArgs ) ) { +void CL_Reconnect_f(void) { + if (!strlen(cl_reconnectArgs)) { return; } Cvar_Set("ui_singlePlayerActive", "0"); - Cbuf_AddText( va("connect %s\n", cl_reconnectArgs ) ); + Cbuf_AddText(va("connect %s\n", cl_reconnectArgs)); } /* @@ -1000,17 +978,17 @@ CL_Connect_f ================ */ -void CL_Connect_f( void ) { - char *server; - const char *serverString; +void CL_Connect_f(void) { + char *server; + const char *serverString; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "usage: connect [server]\n"); + if (Cmd_Argc() != 2) { + Com_Printf("usage: connect [server]\n"); return; } // save arguments for reconnect - Q_strncpyz( cl_reconnectArgs, Cmd_Args(), sizeof( cl_reconnectArgs ) ); + Q_strncpyz(cl_reconnectArgs, Cmd_Args(), sizeof(cl_reconnectArgs)); Cvar_Set("ui_singlePlayerActive", "0"); @@ -1020,42 +998,42 @@ void CL_Connect_f( void ) { // clear any previous "server full" type messages clc.serverMessage[0] = 0; - server = Cmd_Argv (1); + server = Cmd_Argv(1); - if ( com_sv_running->integer && !strcmp( server, "localhost" ) ) { + if (com_sv_running->integer && !strcmp(server, "localhost")) { // if running a local server, kill it - SV_Shutdown( "Server quit\n" ); + SV_Shutdown("Server quit\n"); } // make sure a local server is killed - Cvar_Set( "sv_killserver", "1" ); - SV_Frame( 0 ); + Cvar_Set("sv_killserver", "1"); + SV_Frame(0); - CL_Disconnect( qtrue ); + CL_Disconnect(qtrue); Con_Close(); - Q_strncpyz( cls.servername, server, sizeof(cls.servername) ); + Q_strncpyz(cls.servername, server, sizeof(cls.servername)); - if (!NET_StringToAdr( cls.servername, &clc.serverAddress) ) { - Com_Printf ("Bad server address\n"); + if (!NET_StringToAdr(cls.servername, &clc.serverAddress)) { + Com_Printf("Bad server address\n"); cls.state = CA_DISCONNECTED; return; } if (clc.serverAddress.port == 0) { - clc.serverAddress.port = BigShort( PORT_SERVER ); + clc.serverAddress.port = BigShort(PORT_SERVER); } serverString = NET_AdrToString(clc.serverAddress); - Com_Printf( "%s resolved to %s\n", cls.servername, serverString ); + Com_Printf("%s resolved to %s\n", cls.servername, serverString); - if( cl_guidServerUniq->integer ) - CL_UpdateGUID( serverString, strlen( serverString ) ); + if (cl_guidServerUniq->integer) + CL_UpdateGUID(serverString, strlen(serverString)); else - CL_UpdateGUID( NULL, 0 ); + CL_UpdateGUID(NULL, 0); // if we aren't playing on a lan, we need to authenticate - if ( NET_IsLocalAddress( clc.serverAddress ) ) { + if (NET_IsLocalAddress(clc.serverAddress)) { cls.state = CA_CHALLENGING; } else { cls.state = CA_CONNECTING; @@ -1064,13 +1042,13 @@ void CL_Connect_f( void ) { clc.challenge = ((rand() << 16) ^ rand()) ^ Com_Milliseconds(); } - Key_SetCatcher( 0 ); - clc.connectTime = -99999; // CL_CheckForResend() will fire immediately + Key_SetCatcher(0); + clc.connectTime = -99999; // CL_CheckForResend() will fire immediately clc.connectPacketCount = 0; // server connection string - Cvar_Set( "cl_currentServerAddress", server ); - Cvar_Set( "cl_currentServerIP", serverString ); + Cvar_Set("cl_currentServerAddress", server); + Cvar_Set("cl_currentServerIP", serverString); } #define MAX_RCON_MESSAGE 1024 @@ -1080,15 +1058,13 @@ void CL_Connect_f( void ) { CL_CompleteRcon ================== */ -static void CL_CompleteRcon( char *args, int argNum ) -{ - if( argNum == 2 ) - { +static void CL_CompleteRcon(char *args, int argNum) { + if (argNum == 2) { // Skip "rcon " - char *p = Com_SkipTokens( args, 1, " " ); + char *p = Com_SkipTokens(args, 1, " "); - if( p > args ) - Field_CompleteCommand( p, qtrue, qtrue ); + if (p > args) + Field_CompleteCommand(p, qtrue, qtrue); } } @@ -1100,11 +1076,11 @@ CL_Rcon_f an unconnected command. ===================== */ -void CL_Rcon_f( void ) { - char message[MAX_RCON_MESSAGE]; +void CL_Rcon_f(void) { + char message[MAX_RCON_MESSAGE]; - if ( !rcon_client_password->string[0] ) { - Com_Printf( "You must set 'rconpassword' before issuing an rcon command.\n" ); + if (!rcon_client_password->string[0]) { + Com_Printf("You must set 'rconpassword' before issuing an rcon command.\n"); return; } @@ -1114,31 +1090,31 @@ void CL_Rcon_f( void ) { message[3] = -1; message[4] = 0; - Q_strcat (message, MAX_RCON_MESSAGE, "rcon "); + Q_strcat(message, MAX_RCON_MESSAGE, "rcon "); - Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string); - Q_strcat (message, MAX_RCON_MESSAGE, " "); + Q_strcat(message, MAX_RCON_MESSAGE, rcon_client_password->string); + Q_strcat(message, MAX_RCON_MESSAGE, " "); // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543 - Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5); + Q_strcat(message, MAX_RCON_MESSAGE, Cmd_Cmd() + 5); - if ( cls.state >= CA_CONNECTED ) { + if (cls.state >= CA_CONNECTED) { rcon_address = clc.netchan.remoteAddress; } else { if (!strlen(rconAddress->string)) { - Com_Printf ("You must either be connected,\n" - "or set the 'rconAddress' cvar\n" - "to issue rcon commands\n"); + Com_Printf("You must either be connected,\n" + "or set the 'rconAddress' cvar\n" + "to issue rcon commands\n"); return; } - NET_StringToAdr (rconAddress->string, &rcon_address); + NET_StringToAdr(rconAddress->string, &rcon_address); if (rcon_address.port == 0) { - rcon_address.port = BigShort (PORT_SERVER); + rcon_address.port = BigShort(PORT_SERVER); } } - NET_SendPacket (NS_CLIENT, strlen(message)+1, message, rcon_address); + NET_SendPacket(NS_CLIENT, strlen(message) + 1, message, rcon_address); } /* @@ -1146,13 +1122,13 @@ void CL_Rcon_f( void ) { CL_SendPureChecksums ================= */ -void CL_SendPureChecksums( void ) { +void CL_SendPureChecksums(void) { char cMsg[MAX_INFO_VALUE]; // if we are pure we need to send back a command with our referenced pk3 checksums Com_sprintf(cMsg, sizeof(cMsg), "cp %s", FS_ReferencedPakPureChecksums()); - CL_AddReliableCommand( cMsg, qfalse ); + CL_AddReliableCommand(cMsg, qfalse); } /* @@ -1160,9 +1136,7 @@ void CL_SendPureChecksums( void ) { CL_ResetPureClientAtServer ================= */ -void CL_ResetPureClientAtServer( void ) { - CL_AddReliableCommand( "vdr", qfalse ); -} +void CL_ResetPureClientAtServer(void) { CL_AddReliableCommand("vdr", qfalse); } /* ================= @@ -1175,18 +1149,18 @@ doesn't know what graphics to reload ================= */ extern bool g_nOverrideChecked; -void CL_Vid_Restart_f( void ) { +void CL_Vid_Restart_f(void) { // Settings may have changed so stop recording now - if( CL_VideoRecording( ) ) { - CL_CloseAVI( ); + if (CL_VideoRecording()) { + CL_CloseAVI(); } - if(clc.demorecording) + if (clc.demorecording) CL_StopRecord_f(); - //rww - sort of nasty, but when a user selects a mod - //from the menu all it does is a vid_restart, so we - //have to check for new net overrides for the mod then. + // rww - sort of nasty, but when a user selects a mod + // from the menu all it does is a vid_restart, so we + // have to check for new net overrides for the mod then. g_nOverrideChecked = false; // don't let them loop during the restart @@ -1196,13 +1170,13 @@ void CL_Vid_Restart_f( void ) { // shutdown the CGame CL_ShutdownCGame(); // shutdown the renderer and clear the renderer interface - CL_ShutdownRef( qtrue ); + CL_ShutdownRef(qtrue); // client is no longer pure untill new checksums are sent CL_ResetPureClientAtServer(); // clear pak references - FS_ClearPakReferences( FS_UI_REF | FS_CGAME_REF ); + FS_ClearPakReferences(FS_UI_REF | FS_CGAME_REF); // reinitialize the filesystem if the game directory or checksum has changed - FS_ConditionalRestart( clc.checksumFeed ); + FS_ConditionalRestart(clc.checksumFeed); cls.rendererStarted = qfalse; cls.uiStarted = qfalse; @@ -1210,15 +1184,14 @@ void CL_Vid_Restart_f( void ) { cls.soundRegistered = qfalse; // unpause so the cgame definately gets a snapshot and renders a frame - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); // if not running a server clear the whole hunk - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { CM_ClearMap(); // clear the whole hunk Hunk_Clear(); - } - else { + } else { // clear all the client data on the hunk Hunk_ClearToMark(); } @@ -1230,7 +1203,7 @@ void CL_Vid_Restart_f( void ) { CL_StartHunkUsers(); // start the cgame if connected - if ( cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC ) { + if (cls.state > CA_CONNECTED && cls.state != CA_CINEMATIC) { cls.cgameStarted = qtrue; CL_InitCGame(); // send pure checksums @@ -1248,61 +1221,56 @@ handles will be invalid ================= */ // extern void S_UnCacheDynamicMusic( void ); -void CL_Snd_Restart_f( void ) { +void CL_Snd_Restart_f(void) { S_Shutdown(); S_Init(); -// S_FreeAllSFXMem(); // These two removed by BTO (VV) -// S_UnCacheDynamicMusic(); // S_Shutdown() already does this! + // S_FreeAllSFXMem(); // These two removed by BTO (VV) + // S_UnCacheDynamicMusic(); // S_Shutdown() already does this! -// CL_Vid_Restart_f(); + // CL_Vid_Restart_f(); - extern qboolean s_soundMuted; - s_soundMuted = qfalse; // we can play again + extern qboolean s_soundMuted; + s_soundMuted = qfalse; // we can play again - extern void S_RestartMusic( void ); + extern void S_RestartMusic(void); S_RestartMusic(); } - /* ================== CL_PK3List_f ================== */ -void CL_OpenedPK3List_f( void ) { - Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames()); -} +void CL_OpenedPK3List_f(void) { Com_Printf("Opened PK3 Names: %s\n", FS_LoadedPakNames()); } /* ================== CL_PureList_f ================== */ -void CL_ReferencedPK3List_f( void ) { - Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames()); -} +void CL_ReferencedPK3List_f(void) { Com_Printf("Referenced PK3 Names: %s\n", FS_ReferencedPakNames()); } /* ================== CL_Configstrings_f ================== */ -void CL_Configstrings_f( void ) { - int i; - int ofs; +void CL_Configstrings_f(void) { + int i; + int ofs; - if ( cls.state != CA_ACTIVE ) { - Com_Printf( "Not connected to a server.\n"); + if (cls.state != CA_ACTIVE) { + Com_Printf("Not connected to a server.\n"); return; } - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - ofs = cl.gameState.stringOffsets[ i ]; - if ( !ofs ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + ofs = cl.gameState.stringOffsets[i]; + if (!ofs) { continue; } - Com_Printf( "%4i: %s\n", i, cl.gameState.stringData + ofs ); + Com_Printf("%4i: %s\n", i, cl.gameState.stringData + ofs); } } @@ -1311,16 +1279,15 @@ void CL_Configstrings_f( void ) { CL_Clientinfo_f ============== */ -void CL_Clientinfo_f( void ) { - Com_Printf( "--------- Client Information ---------\n" ); - Com_Printf( "state: %i\n", cls.state ); - Com_Printf( "Server: %s\n", cls.servername ); - Com_Printf ("User info settings:\n"); - Info_Print( Cvar_InfoString( CVAR_USERINFO ) ); - Com_Printf( "--------------------------------------\n" ); +void CL_Clientinfo_f(void) { + Com_Printf("--------- Client Information ---------\n"); + Com_Printf("state: %i\n", cls.state); + Com_Printf("Server: %s\n", cls.servername); + Com_Printf("User info settings:\n"); + Info_Print(Cvar_InfoString(CVAR_USERINFO)); + Com_Printf("--------------------------------------\n"); } - //==================================================================== /* @@ -1330,7 +1297,7 @@ CL_DownloadsComplete Called when all downloading has been completed ================= */ -void CL_DownloadsComplete( void ) { +void CL_DownloadsComplete(void) { // if we downloaded files we need to restart the file system if (clc.downloadRestart) { @@ -1339,7 +1306,7 @@ void CL_DownloadsComplete( void ) { FS_Restart(clc.checksumFeed); // We possibly downloaded a pak, restart the file system to load it // inform the server so we get new gamestate info - CL_AddReliableCommand( "donedl", qfalse ); + CL_AddReliableCommand("donedl", qfalse); // by sending the donedl command we request a new gamestate // so we don't want to load stuff yet @@ -1354,7 +1321,7 @@ void CL_DownloadsComplete( void ) { // if the gamestate was changed by calling Com_EventLoop // then we loaded everything already and we don't want to do it again. - if ( cls.state != CA_LOADING ) { + if (cls.state != CA_LOADING) { return; } @@ -1388,26 +1355,27 @@ game directory. ================= */ -void CL_BeginDownload( const char *localName, const char *remoteName ) { +void CL_BeginDownload(const char *localName, const char *remoteName) { Com_DPrintf("***** CL_BeginDownload *****\n" "Localname: %s\n" "Remotename: %s\n" - "****************************\n", localName, remoteName); + "****************************\n", + localName, remoteName); - Q_strncpyz ( clc.downloadName, localName, sizeof(clc.downloadName) ); - Com_sprintf( clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName ); + Q_strncpyz(clc.downloadName, localName, sizeof(clc.downloadName)); + Com_sprintf(clc.downloadTempName, sizeof(clc.downloadTempName), "%s.tmp", localName); // Set so UI gets access to it - Cvar_Set( "cl_downloadName", remoteName ); - Cvar_Set( "cl_downloadSize", "0" ); - Cvar_Set( "cl_downloadCount", "0" ); - Cvar_SetValue( "cl_downloadTime", (float) cls.realtime ); + Cvar_Set("cl_downloadName", remoteName); + Cvar_Set("cl_downloadSize", "0"); + Cvar_Set("cl_downloadCount", "0"); + Cvar_SetValue("cl_downloadTime", (float)cls.realtime); clc.downloadBlock = 0; // Starting new file clc.downloadCount = 0; - CL_AddReliableCommand( va("download %s", remoteName), qfalse ); + CL_AddReliableCommand(va("download %s", remoteName), qfalse); } /* @@ -1422,12 +1390,11 @@ void CL_NextDownload(void) { char *remoteName, *localName; // A download has finished, check whether this matches a referenced checksum - if(*clc.downloadName) - { + if (*clc.downloadName) { char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, ""); - zippath[strlen(zippath)-1] = '\0'; + zippath[strlen(zippath) - 1] = '\0'; - if(!FS_CompareZipChecksum(zippath)) + if (!FS_CompareZipChecksum(zippath)) Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName); } @@ -1445,14 +1412,14 @@ void CL_NextDownload(void) { s++; remoteName = s; - if ( (s = strchr(s, '@')) == NULL ) { + if ((s = strchr(s, '@')) == NULL) { CL_DownloadsComplete(); return; } *s++ = 0; localName = s; - if ( (s = strchr(s, '@')) != NULL ) + if ((s = strchr(s, '@')) != NULL) *s++ = 0; else s = localName + strlen(localName); // point at the nul byte @@ -1460,15 +1427,14 @@ void CL_NextDownload(void) { if (!cl_allowDownload->integer) { Com_Error(ERR_DROP, "UDP Downloads are disabled on your client. (cl_allowDownload is %d)", cl_allowDownload->integer); return; - } - else { - CL_BeginDownload( localName, remoteName ); + } else { + CL_BeginDownload(localName, remoteName); } clc.downloadRestart = qtrue; // move over the rest - memmove( clc.downloadList, s, strlen(s) + 1); + memmove(clc.downloadList, s, strlen(s) + 1); return; } @@ -1485,36 +1451,33 @@ and determine if we need to download them ================= */ void CL_InitDownloads(void) { - char missingfiles[1024]; + char missingfiles[1024]; - if ( !cl_allowDownload->integer ) - { + if (!cl_allowDownload->integer) { // autodownload is disabled on the client // but it's possible that some referenced files on the server are missing - if (FS_ComparePaks( missingfiles, sizeof( missingfiles ), qfalse ) ) - { + if (FS_ComparePaks(missingfiles, sizeof(missingfiles), qfalse)) { // NOTE TTimo I would rather have that printed as a modal message box // but at this point while joining the game we don't know wether we will successfully join or not - Com_Printf( "\nWARNING: You are missing some files referenced by the server:\n%s" - "You might not be able to join the game\n" - "Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", missingfiles ); + Com_Printf("\nWARNING: You are missing some files referenced by the server:\n%s" + "You might not be able to join the game\n" + "Go to the setting menu to turn on autodownload, or get the file elsewhere\n\n", + missingfiles); } - } - else if ( FS_ComparePaks( clc.downloadList, sizeof( clc.downloadList ) , qtrue ) ) { + } else if (FS_ComparePaks(clc.downloadList, sizeof(clc.downloadList), qtrue)) { - Com_Printf("Need paks: %s\n", clc.downloadList ); + Com_Printf("Need paks: %s\n", clc.downloadList); - if ( *clc.downloadList ) { + if (*clc.downloadList) { // if autodownloading is not enabled on the server cls.state = CA_CONNECTED; *clc.downloadTempName = *clc.downloadName = 0; - Cvar_Set( "cl_downloadName", "" ); + Cvar_Set("cl_downloadName", ""); CL_NextDownload(); return; } - } CL_DownloadsComplete(); } @@ -1526,30 +1489,29 @@ CL_CheckForResend Resend a connect message if the last one has timed out ================= */ -void CL_CheckForResend( void ) { - int port; - char info[MAX_INFO_STRING]; - char data[MAX_INFO_STRING+10]; +void CL_CheckForResend(void) { + int port; + char info[MAX_INFO_STRING]; + char data[MAX_INFO_STRING + 10]; // don't send anything if playing back a demo - if ( clc.demoplaying ) { + if (clc.demoplaying) { return; } // resend if we haven't gotten a reply yet - if ( cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING ) { + if (cls.state != CA_CONNECTING && cls.state != CA_CHALLENGING) { return; } - if ( cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT ) { + if (cls.realtime - clc.connectTime < RETRANSMIT_TIMEOUT) { return; } - clc.connectTime = cls.realtime; // for retransmit requests + clc.connectTime = cls.realtime; // for retransmit requests clc.connectPacketCount++; - - switch ( cls.state ) { + switch (cls.state) { case CA_CONNECTING: // requesting a challenge @@ -1561,15 +1523,15 @@ void CL_CheckForResend( void ) { case CA_CHALLENGING: // sending back the challenge - port = (int) Cvar_VariableValue ("net_qport"); + port = (int)Cvar_VariableValue("net_qport"); - Q_strncpyz( info, Cvar_InfoString( CVAR_USERINFO ), sizeof( info ) ); - Info_SetValueForKey( info, "protocol", va("%i", PROTOCOL_VERSION ) ); - Info_SetValueForKey( info, "qport", va("%i", port ) ); - Info_SetValueForKey( info, "challenge", va("%i", clc.challenge ) ); + Q_strncpyz(info, Cvar_InfoString(CVAR_USERINFO), sizeof(info)); + Info_SetValueForKey(info, "protocol", va("%i", PROTOCOL_VERSION)); + Info_SetValueForKey(info, "qport", va("%i", port)); + Info_SetValueForKey(info, "challenge", va("%i", clc.challenge)); - Com_sprintf(data, sizeof(data), "connect \"%s\"", info ); - NET_OutOfBandData( NS_CLIENT, clc.serverAddress, (byte *)data, strlen(data) ); + Com_sprintf(data, sizeof(data), "connect \"%s\"", info); + NET_OutOfBandData(NS_CLIENT, clc.serverAddress, (byte *)data, strlen(data)); // the most current userinfo has been sent, so watch for any // newer changes to userinfo variables @@ -1577,11 +1539,10 @@ void CL_CheckForResend( void ) { break; default: - Com_Error( ERR_FATAL, "CL_CheckForResend: bad cls.state" ); + Com_Error(ERR_FATAL, "CL_CheckForResend: bad cls.state"); } } - /* =================== CL_DisconnectPacket @@ -1592,56 +1553,55 @@ to the server, the server will send out of band disconnect packets to the client so it doesn't have to wait for the full timeout period. =================== */ -void CL_DisconnectPacket( netadr_t from ) { - if ( cls.state < CA_AUTHORIZING ) { +void CL_DisconnectPacket(netadr_t from) { + if (cls.state < CA_AUTHORIZING) { return; } // if not from our server, ignore it - if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { + if (!NET_CompareAdr(from, clc.netchan.remoteAddress)) { return; } // if we have received packets within three seconds, ignore it // (it might be a malicious spoof) - if ( cls.realtime - clc.lastPacketTime < 3000 ) { + if (cls.realtime - clc.lastPacketTime < 3000) { return; } // drop the connection (FIXME: connection dropped dialog) - Com_Printf( "Server disconnected for unknown reason\n" ); + Com_Printf("Server disconnected for unknown reason\n"); - CL_Disconnect( qtrue ); + CL_Disconnect(qtrue); } - /* =================== CL_MotdPacket =================== */ -void CL_MotdPacket( netadr_t from ) { - char *challenge; - char *info; +void CL_MotdPacket(netadr_t from) { + char *challenge; + char *info; // if not from our server, ignore it - if ( !NET_CompareAdr( from, cls.updateServer ) ) { + if (!NET_CompareAdr(from, cls.updateServer)) { return; } info = Cmd_Argv(1); // check challenge - challenge = Info_ValueForKey( info, "challenge" ); - if ( strcmp( challenge, cls.updateChallenge ) ) { + challenge = Info_ValueForKey(info, "challenge"); + if (strcmp(challenge, cls.updateChallenge)) { return; } - challenge = Info_ValueForKey( info, "motd" ); + challenge = Info_ValueForKey(info, "motd"); - Q_strncpyz( cls.updateInfoString, info, sizeof( cls.updateInfoString ) ); - Cvar_Set( "cl_motdString", challenge ); + Q_strncpyz(cls.updateInfoString, info, sizeof(cls.updateInfoString)); + Cvar_Set("cl_motdString", challenge); } /* @@ -1649,7 +1609,7 @@ void CL_MotdPacket( netadr_t from ) { CL_InitServerInfo =================== */ -void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) { +void CL_InitServerInfo(serverInfo_t *server, netadr_t *address) { server->adr = *address; server->clients = 0; server->hostName[0] = '\0'; @@ -1668,21 +1628,21 @@ void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) { server->humans = server->bots = 0; } -#define MAX_SERVERSPERPACKET 256 +#define MAX_SERVERSPERPACKET 256 /* =================== CL_ServersResponsePacket =================== */ -void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) { - int i, j, count, total; +void CL_ServersResponsePacket(const netadr_t *from, msg_t *msg) { + int i, j, count, total; netadr_t addresses[MAX_SERVERSPERPACKET]; - int numservers; - byte* buffptr; - byte* buffend; + int numservers; + byte *buffptr; + byte *buffend; - Com_Printf("CL_ServersResponsePacket from %s\n", NET_AdrToString( *from ) ); + Com_Printf("CL_ServersResponsePacket from %s\n", NET_AdrToString(*from)); if (cls.numglobalservers == -1) { // state to detect lack of servers or lack of response @@ -1692,41 +1652,37 @@ void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) { // parse through server response string numservers = 0; - buffptr = msg->data; - buffend = buffptr + msg->cursize; + buffptr = msg->data; + buffend = buffptr + msg->cursize; // advance to initial token - do - { - if(*buffptr == '\\') + do { + if (*buffptr == '\\') break; buffptr++; } while (buffptr < buffend); - while (buffptr + 1 < buffend) - { + while (buffptr + 1 < buffend) { // IPv4 address - if (*buffptr == '\\') - { + if (*buffptr == '\\') { buffptr++; if (buffend - buffptr < (int)(sizeof(addresses[numservers].ip) + sizeof(addresses[numservers].port) + 1)) break; - for(size_t i = 0; i < sizeof(addresses[numservers].ip); i++) + for (size_t i = 0; i < sizeof(addresses[numservers].ip); i++) addresses[numservers].ip[i] = *buffptr++; addresses[numservers].type = NA_IP; - } - else + } else // syntax error! break; // parse out port addresses[numservers].port = (*buffptr++) << 8; addresses[numservers].port += *buffptr++; - addresses[numservers].port = BigShort( addresses[numservers].port ); + addresses[numservers].port = BigShort(addresses[numservers].port); // syntax check if (*buffptr != '\\') @@ -1746,8 +1702,7 @@ void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) { // Tequila: It's possible to have sent many master server requests. Then // we may receive many times the same addresses from the master server. // We just avoid to add a server if it is still in the global servers list. - for (j = 0; j < count; j++) - { + for (j = 0; j < count; j++) { if (NET_CompareAdr(cls.globalServers[j].adr, addresses[i])) break; } @@ -1755,17 +1710,15 @@ void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) { if (j < count) continue; - CL_InitServerInfo( server, &addresses[i] ); + CL_InitServerInfo(server, &addresses[i]); // advance to next slot count++; } // if getting the global list - if ( count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS ) - { + if (count >= MAX_GLOBAL_SERVERS && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS) { // if we couldn't store the servers in the main list anymore - for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++) - { + for (; i < numservers && cls.numGlobalServerAddresses < MAX_GLOBAL_SERVERS; i++) { // just store the addresses in an additional list cls.globalServerAddresses[cls.numGlobalServerAddresses++] = addresses[i]; } @@ -1780,17 +1733,14 @@ void CL_ServersResponsePacket( const netadr_t *from, msg_t *msg ) { #ifndef MAX_STRINGED_SV_STRING #define MAX_STRINGED_SV_STRING 1024 #endif -static void CL_CheckSVStringEdRef(char *buf, const char *str) -{ //I don't really like doing this. But it utilizes the system that was already in place. +static void CL_CheckSVStringEdRef(char *buf, const char *str) { // I don't really like doing this. But it utilizes the system that was already in place. int i = 0; int b = 0; int strLen = 0; qboolean gotStrip = qfalse; - if (!str || !str[0]) - { - if (str) - { + if (!str || !str[0]) { + if (str) { strcpy(buf, str); } return; @@ -1800,31 +1750,24 @@ static void CL_CheckSVStringEdRef(char *buf, const char *str) strLen = strlen(str); - if (strLen >= MAX_STRINGED_SV_STRING) - { + if (strLen >= MAX_STRINGED_SV_STRING) { return; } - while (i < strLen && str[i]) - { + while (i < strLen && str[i]) { gotStrip = qfalse; - if (str[i] == '@' && (i+1) < strLen) - { - if (str[i+1] == '@' && (i+2) < strLen) - { - if (str[i+2] == '@' && (i+3) < strLen) - { //@@@ should mean to insert a stringed reference here, so insert it into buf at the current place + if (str[i] == '@' && (i + 1) < strLen) { + if (str[i + 1] == '@' && (i + 2) < strLen) { + if (str[i + 2] == '@' && (i + 3) < strLen) { //@@@ should mean to insert a stringed reference here, so insert it into buf at the current place char stripRef[MAX_STRINGED_SV_STRING]; int r = 0; - while (i < strLen && str[i] == '@') - { + while (i < strLen && str[i] == '@') { i++; } - while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') - { + while (i < strLen && str[i] && str[i] != ' ' && str[i] != ':' && str[i] != '.' && str[i] != '\n') { stripRef[r] = str[i]; r++; i++; @@ -1838,8 +1781,7 @@ static void CL_CheckSVStringEdRef(char *buf, const char *str) } } - if (!gotStrip) - { + if (!gotStrip) { buf[b] = str[i]; b++; } @@ -1849,7 +1791,6 @@ static void CL_CheckSVStringEdRef(char *buf, const char *str) buf[b] = 0; } - /* ================= CL_ConnectionlessPacket @@ -1857,45 +1798,41 @@ CL_ConnectionlessPacket Responses to broadcasts, etc ================= */ -void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { - char *s; - char *c; +void CL_ConnectionlessPacket(netadr_t from, msg_t *msg) { + char *s; + char *c; int challenge = 0; - MSG_BeginReadingOOB( msg ); - MSG_ReadLong( msg ); // skip the -1 + MSG_BeginReadingOOB(msg); + MSG_ReadLong(msg); // skip the -1 - s = MSG_ReadStringLine( msg ); + s = MSG_ReadStringLine(msg); - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); - c = Cmd_Argv( 0 ); + c = Cmd_Argv(0); - if ( com_developer->integer ) { - Com_Printf( "CL packet %s: %s\n", NET_AdrToString( from ), c ); + if (com_developer->integer) { + Com_Printf("CL packet %s: %s\n", NET_AdrToString(from), c); } // challenge from the server we are connecting to - if ( !Q_stricmp(c, "challengeResponse") ) - { - if ( cls.state != CA_CONNECTING ) - { - Com_Printf( "Unwanted challenge response received. Ignored.\n" ); + if (!Q_stricmp(c, "challengeResponse")) { + if (cls.state != CA_CONNECTING) { + Com_Printf("Unwanted challenge response received. Ignored.\n"); return; } c = Cmd_Argv(2); - if(*c) + if (*c) challenge = atoi(c); - if(!NET_CompareAdr(from, clc.serverAddress)) - { + if (!NET_CompareAdr(from, clc.serverAddress)) { // This challenge response is not coming from the expected address. // Check whether we have a matching client challenge to prevent // connection hi-jacking. - if(!*c || challenge != clc.challenge) - { + if (!*c || challenge != clc.challenge) { Com_DPrintf("Challenge response received from unexpected source. Ignored.\n"); return; } @@ -1910,93 +1847,90 @@ void CL_ConnectionlessPacket( netadr_t from, msg_t *msg ) { // take this address as the new server address. This allows // a server proxy to hand off connections to multiple servers clc.serverAddress = from; - Com_DPrintf ("challengeResponse: %d\n", clc.challenge); + Com_DPrintf("challengeResponse: %d\n", clc.challenge); return; } // server connection - if ( !Q_stricmp(c, "connectResponse") ) { - if ( cls.state >= CA_CONNECTED ) { - Com_Printf ("Dup connect received. Ignored.\n"); + if (!Q_stricmp(c, "connectResponse")) { + if (cls.state >= CA_CONNECTED) { + Com_Printf("Dup connect received. Ignored.\n"); return; } - if ( cls.state != CA_CHALLENGING ) { - Com_Printf ("connectResponse packet while not connecting. Ignored.\n"); + if (cls.state != CA_CHALLENGING) { + Com_Printf("connectResponse packet while not connecting. Ignored.\n"); return; } - if ( !NET_CompareAdr( from, clc.serverAddress ) ) { - Com_Printf( "connectResponse from wrong address. Ignored.\n" ); + if (!NET_CompareAdr(from, clc.serverAddress)) { + Com_Printf("connectResponse from wrong address. Ignored.\n"); return; } - Netchan_Setup (NS_CLIENT, &clc.netchan, from, Cvar_VariableValue( "net_qport" ) ); + Netchan_Setup(NS_CLIENT, &clc.netchan, from, Cvar_VariableValue("net_qport")); cls.state = CA_CONNECTED; - clc.lastPacketSentTime = -9999; // send first packet immediately + clc.lastPacketSentTime = -9999; // send first packet immediately return; } // server responding to an info broadcast - if ( !Q_stricmp(c, "infoResponse") ) { - CL_ServerInfoPacket( from, msg ); + if (!Q_stricmp(c, "infoResponse")) { + CL_ServerInfoPacket(from, msg); return; } // server responding to a get playerlist - if ( !Q_stricmp(c, "statusResponse") ) { - CL_ServerStatusResponse( from, msg ); + if (!Q_stricmp(c, "statusResponse")) { + CL_ServerStatusResponse(from, msg); return; } // a disconnect message from the server, which will happen if the server // dropped the connection but it is still getting packets from us if (!Q_stricmp(c, "disconnect")) { - CL_DisconnectPacket( from ); + CL_DisconnectPacket(from); return; } // echo request from server - if ( !Q_stricmp(c, "echo") ) { - NET_OutOfBandPrint( NS_CLIENT, from, "%s", Cmd_Argv(1) ); + if (!Q_stricmp(c, "echo")) { + NET_OutOfBandPrint(NS_CLIENT, from, "%s", Cmd_Argv(1)); return; } // cd check - if ( !Q_stricmp(c, "keyAuthorize") ) { + if (!Q_stricmp(c, "keyAuthorize")) { // we don't use these now, so dump them on the floor return; } // global MOTD from id - if ( !Q_stricmp(c, "motd") ) { - CL_MotdPacket( from ); + if (!Q_stricmp(c, "motd")) { + CL_MotdPacket(from); return; } // echo request from server - if ( !Q_stricmp(c, "print") ) - { + if (!Q_stricmp(c, "print")) { // NOTE: we may have to add exceptions for auth and update servers - if (NET_CompareAdr(from, clc.serverAddress) || NET_CompareAdr(from, rcon_address)) - { + if (NET_CompareAdr(from, clc.serverAddress) || NET_CompareAdr(from, rcon_address)) { char sTemp[MAX_STRINGED_SV_STRING]; - s = MSG_ReadString( msg ); + s = MSG_ReadString(msg); CL_CheckSVStringEdRef(sTemp, s); - Q_strncpyz( clc.serverMessage, sTemp, sizeof( clc.serverMessage ) ); - Com_Printf( "%s", sTemp ); + Q_strncpyz(clc.serverMessage, sTemp, sizeof(clc.serverMessage)); + Com_Printf("%s", sTemp); } return; } // list of servers sent back by a master server (classic) - if ( !Q_strncmp(c, "getserversResponse", 18) ) { - CL_ServersResponsePacket( &from, msg ); + if (!Q_strncmp(c, "getserversResponse", 18)) { + CL_ServersResponsePacket(&from, msg); return; } - Com_DPrintf ("Unknown connectionless packet command.\n"); + Com_DPrintf("Unknown connectionless packet command.\n"); } - /* ================= CL_PacketEvent @@ -2004,39 +1938,38 @@ CL_PacketEvent A packet has arrived from the main event loop ================= */ -void CL_PacketEvent( netadr_t from, msg_t *msg ) { - int headerBytes; +void CL_PacketEvent(netadr_t from, msg_t *msg) { + int headerBytes; clc.lastPacketTime = cls.realtime; - if ( msg->cursize >= 4 && *(int *)msg->data == -1 ) { - CL_ConnectionlessPacket( from, msg ); + if (msg->cursize >= 4 && *(int *)msg->data == -1) { + CL_ConnectionlessPacket(from, msg); return; } - if ( cls.state < CA_CONNECTED ) { - return; // can't be a valid sequenced packet + if (cls.state < CA_CONNECTED) { + return; // can't be a valid sequenced packet } - if ( msg->cursize < 4 ) { - Com_Printf ("%s: Runt packet\n",NET_AdrToString( from )); + if (msg->cursize < 4) { + Com_Printf("%s: Runt packet\n", NET_AdrToString(from)); return; } // // packet from server // - if ( !NET_CompareAdr( from, clc.netchan.remoteAddress ) ) { - if ( com_developer->integer ) { - Com_Printf( "%s:sequenced packet without connection\n", - NET_AdrToString( from ) ); + if (!NET_CompareAdr(from, clc.netchan.remoteAddress)) { + if (com_developer->integer) { + Com_Printf("%s:sequenced packet without connection\n", NET_AdrToString(from)); } // FIXME: send a client disconnect? return; } - if (!CL_Netchan_Process( &clc.netchan, msg) ) { - return; // out of order, duplicated, etc + if (!CL_Netchan_Process(&clc.netchan, msg)) { + return; // out of order, duplicated, etc } // the header is different lengths for reliable and unreliable messages @@ -2045,17 +1978,17 @@ void CL_PacketEvent( netadr_t from, msg_t *msg ) { // track the last message received so it can be returned in // client messages, allowing the server to detect a dropped // gamestate - clc.serverMessageSequence = LittleLong( *(int *)msg->data ); + clc.serverMessageSequence = LittleLong(*(int *)msg->data); clc.lastPacketTime = cls.realtime; - CL_ParseServerMessage( msg ); + CL_ParseServerMessage(msg); // // we don't know if it is ok to save a demo message until // after we have parsed the frame // - if ( clc.demorecording && !clc.demowaiting ) { - CL_WriteDemoMessage( msg, headerBytes ); + if (clc.demorecording && !clc.demowaiting) { + CL_WriteDemoMessage(msg, headerBytes); } } @@ -2065,18 +1998,17 @@ CL_CheckTimeout ================== */ -void CL_CheckTimeout( void ) { +void CL_CheckTimeout(void) { // // check timeout // - if ( ( !CL_CheckPaused() || !sv_paused->integer ) - && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC - && cls.realtime - clc.lastPacketTime > cl_timeout->value*1000) { - if (++cl.timeoutcount > 5) { // timeoutcount saves debugger + if ((!CL_CheckPaused() || !sv_paused->integer) && cls.state >= CA_CONNECTED && cls.state != CA_CINEMATIC && + cls.realtime - clc.lastPacketTime > cl_timeout->value * 1000) { + if (++cl.timeoutcount > 5) { // timeoutcount saves debugger const char *psTimedOut = SE_GetString("MP_SVGAME_SERVER_CONNECTION_TIMED_OUT"); - Com_Printf ("\n%s\n",psTimedOut); + Com_Printf("\n%s\n", psTimedOut); Com_Error(ERR_DROP, psTimedOut); - //CL_Disconnect( qtrue ); + // CL_Disconnect( qtrue ); return; } } else { @@ -2090,12 +2022,11 @@ CL_CheckPaused Check whether client has been paused. ================== */ -qboolean CL_CheckPaused(void) -{ +qboolean CL_CheckPaused(void) { // if cl_paused->modified is set, the cvar has only been changed in // this frame. Keep paused in this frame to ensure the server doesn't // lag behind. - if(cl_paused->integer || cl_paused->modified) + if (cl_paused->integer || cl_paused->modified) return qtrue; return qfalse; @@ -2109,21 +2040,20 @@ CL_CheckUserinfo ================== */ -void CL_CheckUserinfo( void ) { +void CL_CheckUserinfo(void) { // don't add reliable commands when not yet connected - if ( cls.state < CA_CONNECTED ) { + if (cls.state < CA_CONNECTED) { return; } // don't overflow the reliable command buffer when paused - if ( CL_CheckPaused() ) { + if (CL_CheckPaused()) { return; } // send a reliable userinfo update if needed - if ( cvar_modifiedFlags & CVAR_USERINFO ) { + if (cvar_modifiedFlags & CVAR_USERINFO) { cvar_modifiedFlags &= ~CVAR_USERINFO; - CL_AddReliableCommand( va("userinfo \"%s\"", Cvar_InfoString( CVAR_USERINFO ) ), qfalse ); + CL_AddReliableCommand(va("userinfo \"%s\"", Cvar_InfoString(CVAR_USERINFO)), qfalse); } - } /* @@ -2133,28 +2063,27 @@ CL_Frame ================== */ static unsigned int frameCount; -static float avgFrametime=0.0; +static float avgFrametime = 0.0; extern void SE_CheckForLanguageUpdates(void); -void CL_Frame ( int msec ) { +void CL_Frame(int msec) { qboolean takeVideoFrame = qfalse; - if ( !com_cl_running->integer ) { + if (!com_cl_running->integer) { return; } - SE_CheckForLanguageUpdates(); // will take zero time to execute unless language changes, then will reload strings. - // of course this still doesn't work for menus... + SE_CheckForLanguageUpdates(); // will take zero time to execute unless language changes, then will reload strings. + // of course this still doesn't work for menus... - if ( cls.state == CA_DISCONNECTED && !( Key_GetCatcher( ) & KEYCATCH_UI ) - && !com_sv_running->integer && cls.uiStarted ) { + if (cls.state == CA_DISCONNECTED && !(Key_GetCatcher() & KEYCATCH_UI) && !com_sv_running->integer && cls.uiStarted) { // if disconnected, bring up the menu S_StopAllSounds(); - UIVM_SetActiveMenu( UIMENU_MAIN ); + UIVM_SetActiveMenu(UIMENU_MAIN); } // if recording an avi, lock to a fixed fps - if ( CL_VideoRecording( ) && cl_aviFrameRate->integer && msec) { - if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) { + if (CL_VideoRecording() && cl_aviFrameRate->integer && msec) { + if (cls.state == CA_ACTIVE || cl_forceavidemo->integer) { float fps = Q_min(cl_aviFrameRate->value * com_timescale->value, 1000.0f); float frameDuration = Q_max(1000.0f / fps, 1.0f) + clc.aviVideoFrameRemainder; takeVideoFrame = qtrue; @@ -2169,24 +2098,22 @@ void CL_Frame ( int msec ) { // decide the simulation time cls.frametime = msec; - if(cl_framerate->integer) - { - avgFrametime+=msec; + if (cl_framerate->integer) { + avgFrametime += msec; char mess[256]; - if(!(frameCount&0x1f)) - { - Com_sprintf(mess,sizeof(mess),"Frame rate=%f\n\n",1000.0f*(1.0/(avgFrametime/32.0f))); - // Com_OPrintf("%s", mess); + if (!(frameCount & 0x1f)) { + Com_sprintf(mess, sizeof(mess), "Frame rate=%f\n\n", 1000.0f * (1.0 / (avgFrametime / 32.0f))); + // Com_OPrintf("%s", mess); Com_Printf("%s", mess); - avgFrametime=0.0f; + avgFrametime = 0.0f; } frameCount++; } cls.realtime += cls.frametime; - if ( cl_timegraph->integer ) { - SCR_DebugGraph ( cls.realFrametime * 0.25, 0 ); + if (cl_timegraph->integer) { + SCR_DebugGraph(cls.realFrametime * 0.25, 0); } // see if we need to update any userinfo @@ -2217,20 +2144,18 @@ void CL_Frame ( int msec ) { Con_RunConsole(); // reset the heap for Ghoul2 vert transform space gameside - if (G2VertSpaceServer) - { + if (G2VertSpaceServer) { G2VertSpaceServer->ResetHeap(); } cls.framecount++; - if ( takeVideoFrame ) { + if (takeVideoFrame) { // save the current screen - CL_TakeVideoFrame( ); + CL_TakeVideoFrame(); } } - //============================================================================ /* @@ -2240,43 +2165,39 @@ CL_RefPrintf DLL glue ================ */ -void QDECL CL_RefPrintf( int print_level, const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL CL_RefPrintf(int print_level, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf(msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_end(argptr); - if ( print_level == PRINT_ALL ) { - Com_Printf ("%s", msg); - } else if ( print_level == PRINT_WARNING ) { - Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow - } else if ( print_level == PRINT_DEVELOPER ) { - Com_DPrintf (S_COLOR_RED "%s", msg); // red + if (print_level == PRINT_ALL) { + Com_Printf("%s", msg); + } else if (print_level == PRINT_WARNING) { + Com_Printf(S_COLOR_YELLOW "%s", msg); // yellow + } else if (print_level == PRINT_DEVELOPER) { + Com_DPrintf(S_COLOR_RED "%s", msg); // red } } - - /* ============ CL_ShutdownRef ============ */ -static void CL_ShutdownRef( qboolean restarting ) { - if ( re ) - { - if ( re->Shutdown ) - { - re->Shutdown( qtrue, restarting ); +static void CL_ShutdownRef(qboolean restarting) { + if (re) { + if (re->Shutdown) { + re->Shutdown(qtrue, restarting); } } re = NULL; - if ( rendererLib != NULL ) { - Sys_UnloadDll (rendererLib); + if (rendererLib != NULL) { + Sys_UnloadDll(rendererLib); rendererLib = NULL; } } @@ -2286,16 +2207,16 @@ static void CL_ShutdownRef( qboolean restarting ) { CL_InitRenderer ============ */ -void CL_InitRenderer( void ) { +void CL_InitRenderer(void) { // this sets up the renderer and calls R_Init - re->BeginRegistration( &cls.glconfig ); + re->BeginRegistration(&cls.glconfig); // load character sets cls.charSetShader = re->RegisterShaderNoMip("gfx/2d/charsgrid_med"); - cls.consoleFont = re->RegisterFont( "ocr_a" ); + cls.consoleFont = re->RegisterFont("ocr_a"); - cls.whiteShader = re->RegisterShader( "white" ); - cls.consoleShader = re->RegisterShader( "console" ); + cls.whiteShader = re->RegisterShader("white"); + cls.consoleShader = re->RegisterShader("console"); g_console_field_width = cls.glconfig.vidWidth / SMALLCHAR_WIDTH - 2; g_consoleField.widthInChars = g_console_field_width; } @@ -2308,31 +2229,31 @@ After the server has cleared the hunk, these will need to be restarted This is the only place that any of these functions are called from ============================ */ -void CL_StartHunkUsers( void ) { +void CL_StartHunkUsers(void) { if (!com_cl_running) { return; } - if ( !com_cl_running->integer ) { + if (!com_cl_running->integer) { return; } - if ( !cls.rendererStarted ) { + if (!cls.rendererStarted) { cls.rendererStarted = qtrue; CL_InitRenderer(); } - if ( !cls.soundStarted ) { + if (!cls.soundStarted) { cls.soundStarted = qtrue; S_Init(); } - if ( !cls.soundRegistered ) { + if (!cls.soundRegistered) { cls.soundRegistered = qtrue; S_BeginRegistration(); } - if ( !cls.uiStarted ) { + if (!cls.uiStarted) { cls.uiStarted = qtrue; CL_InitUI(); } @@ -2345,63 +2266,60 @@ CL_InitRef */ qboolean Com_TheHunkMarkHasBeenMade(void); -//qcommon/cm_load.cpp +// qcommon/cm_load.cpp extern void *gpvCachedMapDiskImage; extern qboolean gbUsingCachedMapDataRightNow; -static char *GetSharedMemory( void ) { return cl.mSharedMemory; } -static vm_t *GetCurrentVM( void ) { return currentVM; } -static qboolean CGVMLoaded( void ) { return (qboolean)cls.cgameStarted; } -static void *CM_GetCachedMapDiskImage( void ) { return gpvCachedMapDiskImage; } -static void CM_SetCachedMapDiskImage( void *ptr ) { gpvCachedMapDiskImage = ptr; } -static void CM_SetUsingCache( qboolean usingCache ) { gbUsingCachedMapDataRightNow = usingCache; } +static char *GetSharedMemory(void) { return cl.mSharedMemory; } +static vm_t *GetCurrentVM(void) { return currentVM; } +static qboolean CGVMLoaded(void) { return (qboolean)cls.cgameStarted; } +static void *CM_GetCachedMapDiskImage(void) { return gpvCachedMapDiskImage; } +static void CM_SetCachedMapDiskImage(void *ptr) { gpvCachedMapDiskImage = ptr; } +static void CM_SetUsingCache(qboolean usingCache) { gbUsingCachedMapDataRightNow = usingCache; } #define G2_VERT_SPACE_SERVER_SIZE 256 IHeapAllocator *G2VertSpaceServer = NULL; CMiniHeap IHeapAllocator_singleton(G2_VERT_SPACE_SERVER_SIZE * 1024); -static IHeapAllocator *GetG2VertSpaceServer( void ) { - return G2VertSpaceServer; -} +static IHeapAllocator *GetG2VertSpaceServer(void) { return G2VertSpaceServer; } #define DEFAULT_RENDER_LIBRARY "rd-vanilla" -void CL_InitRef( void ) { +void CL_InitRef(void) { static refimport_t ri; - refexport_t *ret; - GetRefAPI_t GetRefAPI; - char dllName[MAX_OSPATH]; + refexport_t *ret; + GetRefAPI_t GetRefAPI; + char dllName[MAX_OSPATH]; - Com_Printf( "----- Initializing Renderer ----\n" ); + Com_Printf("----- Initializing Renderer ----\n"); - cl_renderer = Cvar_Get( "cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE|CVAR_LATCH, "Which renderer library to use" ); + cl_renderer = Cvar_Get("cl_renderer", DEFAULT_RENDER_LIBRARY, CVAR_ARCHIVE | CVAR_LATCH, "Which renderer library to use"); - Com_sprintf( dllName, sizeof( dllName ), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string ); + Com_sprintf(dllName, sizeof(dllName), "%s_" ARCH_STRING DLL_EXT, cl_renderer->string); - if( !(rendererLib = Sys_LoadDll( dllName, qfalse )) && strcmp( cl_renderer->string, cl_renderer->resetString ) ) - { - Com_Printf( "failed: trying to load fallback renderer\n" ); - Cvar_ForceReset( "cl_renderer" ); + if (!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { + Com_Printf("failed: trying to load fallback renderer\n"); + Cvar_ForceReset("cl_renderer"); - Com_sprintf( dllName, sizeof( dllName ), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT ); - rendererLib = Sys_LoadDll( dllName, qfalse ); + Com_sprintf(dllName, sizeof(dllName), DEFAULT_RENDER_LIBRARY "_" ARCH_STRING DLL_EXT); + rendererLib = Sys_LoadDll(dllName, qfalse); } - if ( !rendererLib ) { - Com_Error( ERR_FATAL, "Failed to load renderer\n" ); + if (!rendererLib) { + Com_Error(ERR_FATAL, "Failed to load renderer\n"); } - memset( &ri, 0, sizeof( ri ) ); + memset(&ri, 0, sizeof(ri)); - GetRefAPI = (GetRefAPI_t)Sys_LoadFunction( rendererLib, "GetRefAPI" ); - if ( !GetRefAPI ) - Com_Error( ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError() ); + GetRefAPI = (GetRefAPI_t)Sys_LoadFunction(rendererLib, "GetRefAPI"); + if (!GetRefAPI) + Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); - //set up the import table + // set up the import table ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.OPrintf = Com_OPrintf; - ri.Milliseconds = Sys_Milliseconds2; //FIXME: unix+mac need this + ri.Milliseconds = Sys_Milliseconds2; // FIXME: unix+mac need this ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.Hunk_Alloc = Hunk_Alloc; @@ -2463,10 +2381,10 @@ void CL_InitRef( void ) { ri.CGVMLoaded = CGVMLoaded; ri.CGVM_RagCallback = CGVM_RagCallback; - ri.WIN_Init = WIN_Init; + ri.WIN_Init = WIN_Init; ri.WIN_SetGamma = WIN_SetGamma; - ri.WIN_Shutdown = WIN_Shutdown; - ri.WIN_Present = WIN_Present; + ri.WIN_Shutdown = WIN_Shutdown; + ri.WIN_Present = WIN_Present; ri.GL_GetProcAddress = WIN_GL_GetProcAddress; ri.GL_ExtensionSupported = WIN_GL_ExtensionSupported; @@ -2474,40 +2392,38 @@ void CL_InitRef( void ) { ri.CM_SetCachedMapDiskImage = CM_SetCachedMapDiskImage; ri.CM_SetUsingCache = CM_SetUsingCache; - //FIXME: Might have to do something about this... + // FIXME: Might have to do something about this... ri.GetG2VertSpaceServer = GetG2VertSpaceServer; G2VertSpaceServer = &IHeapAllocator_singleton; ri.PD_Store = PD_Store; ri.PD_Load = PD_Load; - ret = GetRefAPI( REF_API_VERSION, &ri ); + ret = GetRefAPI(REF_API_VERSION, &ri); -// Com_Printf( "-------------------------------\n"); + // Com_Printf( "-------------------------------\n"); - if ( !ret ) { - Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); + if (!ret) { + Com_Error(ERR_FATAL, "Couldn't initialize refresh"); } re = ret; // unpause so the cgame definately gets a snapshot and renders a frame - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } - //=========================================================================================== #define MODEL_CHANGE_DELAY 5000 int gCLModelDelay = 0; -void CL_SetModel_f( void ) { - char *arg; - char name[256]; +void CL_SetModel_f(void) { + char *arg; + char name[256]; - arg = Cmd_Argv( 1 ); - if (arg[0]) - { + arg = Cmd_Argv(1); + if (arg[0]) { /* //If you wanted to be foolproof you would put this on the server I guess. But that //tends to put things out of sync regarding cvar status. And I sort of doubt someone @@ -2522,33 +2438,29 @@ void CL_SetModel_f( void ) { gCLModelDelay = curTime + MODEL_CHANGE_DELAY; */ - //rwwFIXMEFIXME: This is currently broken and doesn't seem to work for connecting clients - Cvar_Set( "model", arg ); - } - else - { - Cvar_VariableStringBuffer( "model", name, sizeof(name) ); + // rwwFIXMEFIXME: This is currently broken and doesn't seem to work for connecting clients + Cvar_Set("model", arg); + } else { + Cvar_VariableStringBuffer("model", name, sizeof(name)); Com_Printf("model is set to %s\n", name); } } -void CL_SetForcePowers_f( void ) { - return; -} +void CL_SetForcePowers_f(void) { return; } /* ================== CL_VideoFilename ================== */ -void CL_VideoFilename( char *buf, int bufSize ) { +void CL_VideoFilename(char *buf, int bufSize) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "videos/video%s.avi", timeStr ); + Com_sprintf(buf, bufSize, "videos/video%s.avi", timeStr); } /* @@ -2559,32 +2471,27 @@ video video [filename] =============== */ -void CL_Video_f( void ) -{ - char filename[ MAX_OSPATH ]; +void CL_Video_f(void) { + char filename[MAX_OSPATH]; - if( !clc.demoplaying ) - { - Com_Printf( "The video command can only be used when playing back demos\n" ); + if (!clc.demoplaying) { + Com_Printf("The video command can only be used when playing back demos\n"); return; } - if( Cmd_Argc( ) == 2 ) - { + if (Cmd_Argc() == 2) { // explicit filename - Com_sprintf( filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv( 1 ) ); - } - else - { - CL_VideoFilename( filename, MAX_OSPATH ); + Com_sprintf(filename, MAX_OSPATH, "videos/%s.avi", Cmd_Argv(1)); + } else { + CL_VideoFilename(filename, MAX_OSPATH); - if ( FS_FileExists( filename ) ) { - Com_Printf( "Video: Couldn't create a file\n"); + if (FS_FileExists(filename)) { + Com_Printf("Video: Couldn't create a file\n"); return; - } + } } - CL_OpenAVIForWriting( filename ); + CL_OpenAVIForWriting(filename); } /* @@ -2592,33 +2499,30 @@ void CL_Video_f( void ) CL_StopVideo_f =============== */ -void CL_StopVideo_f( void ) -{ - CL_CloseAVI( ); -} +void CL_StopVideo_f(void) { CL_CloseAVI(); } -static void CL_AddFavorite_f( void ) { +static void CL_AddFavorite_f(void) { const bool connected = (cls.state == CA_ACTIVE) && !clc.demoplaying; const int argc = Cmd_Argc(); - if ( !connected && argc != 2 ) { - Com_Printf( "syntax: addFavorite \n" ); + if (!connected && argc != 2) { + Com_Printf("syntax: addFavorite \n"); return; } - const char *server = (argc == 2) ? Cmd_Argv( 1 ) : NET_AdrToString( clc.serverAddress ); - const int status = LAN_AddFavAddr( server ); - switch ( status ) { + const char *server = (argc == 2) ? Cmd_Argv(1) : NET_AdrToString(clc.serverAddress); + const int status = LAN_AddFavAddr(server); + switch (status) { case -1: - Com_Printf( "error adding favorite server: too many favorite servers\n" ); + Com_Printf("error adding favorite server: too many favorite servers\n"); break; case 0: - Com_Printf( "error adding favorite server: server already exists\n" ); + Com_Printf("error adding favorite server: server already exists\n"); break; case 1: - Com_Printf( "successfully added favorite server \"%s\"\n", server ); + Com_Printf("successfully added favorite server \"%s\"\n", server); break; default: - Com_Printf( "unknown error (%i) adding favorite server\n", status ); + Com_Printf("unknown error (%i) adding favorite server\n", status); break; } } @@ -2634,37 +2538,33 @@ it by filling it with 2048 bytes of random data. =============== */ -static void CL_GenerateQKey(void) -{ +static void CL_GenerateQKey(void) { if (cl_enableGuid->integer) { int len = 0; - unsigned char buff[ QKEY_SIZE ]; + unsigned char buff[QKEY_SIZE]; fileHandle_t f; - len = FS_SV_FOpenFileRead( QKEY_FILE, &f ); - FS_FCloseFile( f ); - if( len == QKEY_SIZE ) { - Com_Printf( "QKEY found.\n" ); + len = FS_SV_FOpenFileRead(QKEY_FILE, &f); + FS_FCloseFile(f); + if (len == QKEY_SIZE) { + Com_Printf("QKEY found.\n"); return; - } - else { - if( len > 0 ) { - Com_Printf( "QKEY file size != %d, regenerating\n", - QKEY_SIZE ); + } else { + if (len > 0) { + Com_Printf("QKEY file size != %d, regenerating\n", QKEY_SIZE); } - Com_Printf( "QKEY building random string\n" ); - Com_RandomBytes( buff, sizeof(buff) ); + Com_Printf("QKEY building random string\n"); + Com_RandomBytes(buff, sizeof(buff)); - f = FS_SV_FOpenFileWrite( QKEY_FILE ); - if( !f ) { - Com_Printf( "QKEY could not open %s for write\n", - QKEY_FILE ); + f = FS_SV_FOpenFileWrite(QKEY_FILE); + if (!f) { + Com_Printf("QKEY could not open %s for write\n", QKEY_FILE); return; } - FS_Write( buff, sizeof(buff), f ); - FS_FCloseFile( f ); - Com_Printf( "QKEY generated\n" ); + FS_Write(buff, sizeof(buff), f); + FS_FCloseFile(f); + Com_Printf("QKEY generated\n"); } } } @@ -2674,283 +2574,278 @@ static void CL_GenerateQKey(void) CL_Init ==================== */ -void CL_Init( void ) { -// Com_Printf( "----- Client Initialization -----\n" ); +void CL_Init(void) { + // Com_Printf( "----- Client Initialization -----\n" ); - Con_Init (); + Con_Init(); - CL_ClearState (); + CL_ClearState(); - cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED + cls.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cls.realtime = 0; - CL_InitInput (); + CL_InitInput(); // // register our variables // - cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); - cl_motd = Cvar_Get ("cl_motd", "1", CVAR_ARCHIVE_ND, "Display welcome message from master server on the bottom of connection screen" ); - cl_motdServer[0] = Cvar_Get( "cl_motdServer1", UPDATE_SERVER_NAME, 0 ); - cl_motdServer[1] = Cvar_Get( "cl_motdServer2", JKHUB_UPDATE_SERVER_NAME, 0 ); - for ( int index = 2; index < MAX_MASTER_SERVERS; index++ ) - cl_motdServer[index] = Cvar_Get( va( "cl_motdServer%d", index + 1 ), "", CVAR_ARCHIVE_ND ); - - cl_timeout = Cvar_Get ("cl_timeout", "200", 0); - - cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); - cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); - cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); - cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); - cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); - rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP, "Password for remote console access" ); - cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); - - cl_timedemo = Cvar_Get ("timedemo", "0", 0); - cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); - cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); - cl_avi2GBLimit = Cvar_Get ("cl_avi2GBLimit", "1", CVAR_ARCHIVE ); - cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); - - rconAddress = Cvar_Get ("rconAddress", "", 0, "Alternate server address to remotely access via rcon protocol"); - - cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE_ND ); - cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE_ND ); - cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_ARCHIVE_ND ); - - cl_maxpackets = Cvar_Get ("cl_maxpackets", "63", CVAR_ARCHIVE ); - cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE_ND ); - - cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE_ND, "Always run"); - cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE, "Mouse sensitivity value"); - cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE_ND, "Mouse acceleration value"); - cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE_ND, "Mouse look" ); + cl_noprint = Cvar_Get("cl_noprint", "0", 0); + cl_motd = Cvar_Get("cl_motd", "1", CVAR_ARCHIVE_ND, "Display welcome message from master server on the bottom of connection screen"); + cl_motdServer[0] = Cvar_Get("cl_motdServer1", UPDATE_SERVER_NAME, 0); + cl_motdServer[1] = Cvar_Get("cl_motdServer2", JKHUB_UPDATE_SERVER_NAME, 0); + for (int index = 2; index < MAX_MASTER_SERVERS; index++) + cl_motdServer[index] = Cvar_Get(va("cl_motdServer%d", index + 1), "", CVAR_ARCHIVE_ND); + + cl_timeout = Cvar_Get("cl_timeout", "200", 0); + + cl_timeNudge = Cvar_Get("cl_timeNudge", "0", CVAR_TEMP); + cl_shownet = Cvar_Get("cl_shownet", "0", CVAR_TEMP); + cl_showSend = Cvar_Get("cl_showSend", "0", CVAR_TEMP); + cl_showTimeDelta = Cvar_Get("cl_showTimeDelta", "0", CVAR_TEMP); + cl_freezeDemo = Cvar_Get("cl_freezeDemo", "0", CVAR_TEMP); + rcon_client_password = Cvar_Get("rconPassword", "", CVAR_TEMP, "Password for remote console access"); + cl_activeAction = Cvar_Get("activeAction", "", CVAR_TEMP); + + cl_timedemo = Cvar_Get("timedemo", "0", 0); + cl_aviFrameRate = Cvar_Get("cl_aviFrameRate", "25", CVAR_ARCHIVE); + cl_aviMotionJpeg = Cvar_Get("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); + cl_avi2GBLimit = Cvar_Get("cl_avi2GBLimit", "1", CVAR_ARCHIVE); + cl_forceavidemo = Cvar_Get("cl_forceavidemo", "0", 0); + + rconAddress = Cvar_Get("rconAddress", "", 0, "Alternate server address to remotely access via rcon protocol"); + + cl_yawspeed = Cvar_Get("cl_yawspeed", "140", CVAR_ARCHIVE_ND); + cl_pitchspeed = Cvar_Get("cl_pitchspeed", "140", CVAR_ARCHIVE_ND); + cl_anglespeedkey = Cvar_Get("cl_anglespeedkey", "1.5", CVAR_ARCHIVE_ND); + + cl_maxpackets = Cvar_Get("cl_maxpackets", "63", CVAR_ARCHIVE); + cl_packetdup = Cvar_Get("cl_packetdup", "1", CVAR_ARCHIVE_ND); + + cl_run = Cvar_Get("cl_run", "1", CVAR_ARCHIVE_ND, "Always run"); + cl_sensitivity = Cvar_Get("sensitivity", "5", CVAR_ARCHIVE, "Mouse sensitivity value"); + cl_mouseAccel = Cvar_Get("cl_mouseAccel", "0", CVAR_ARCHIVE_ND, "Mouse acceleration value"); + cl_freelook = Cvar_Get("cl_freelook", "1", CVAR_ARCHIVE_ND, "Mouse look"); // 0: legacy mouse acceleration // 1: new implementation - cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE_ND, "Mouse accelration style (0:legacy, 1:QuakeLive)" ); + cl_mouseAccelStyle = Cvar_Get("cl_mouseAccelStyle", "0", CVAR_ARCHIVE_ND, "Mouse accelration style (0:legacy, 1:QuakeLive)"); // offset for the power function (for style 1, ignored otherwise) // this should be set to the max rate value - cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE_ND, "Mouse acceleration offset for style 1" ); + cl_mouseAccelOffset = Cvar_Get("cl_mouseAccelOffset", "5", CVAR_ARCHIVE_ND, "Mouse acceleration offset for style 1"); - cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); - cl_framerate = Cvar_Get ("cl_framerate", "0", CVAR_TEMP); - cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE_ND, "Allow downloading custom paks from server"); - cl_allowAltEnter = Cvar_Get ("cl_allowAltEnter", "1", CVAR_ARCHIVE_ND, "Enables use of ALT+ENTER keyboard combo to toggle fullscreen" ); + cl_showMouseRate = Cvar_Get("cl_showmouserate", "0", 0); + cl_framerate = Cvar_Get("cl_framerate", "0", CVAR_TEMP); + cl_allowDownload = Cvar_Get("cl_allowDownload", "0", CVAR_ARCHIVE_ND, "Allow downloading custom paks from server"); + cl_allowAltEnter = Cvar_Get("cl_allowAltEnter", "1", CVAR_ARCHIVE_ND, "Enables use of ALT+ENTER keyboard combo to toggle fullscreen"); - cl_autolodscale = Cvar_Get( "cl_autolodscale", "1", CVAR_ARCHIVE_ND ); + cl_autolodscale = Cvar_Get("cl_autolodscale", "1", CVAR_ARCHIVE_ND); - cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); - cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE_ND ); + cl_conXOffset = Cvar_Get("cl_conXOffset", "0", 0); + cl_inGameVideo = Cvar_Get("r_inGameVideo", "1", CVAR_ARCHIVE_ND); - cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); + cl_serverStatusResendTime = Cvar_Get("cl_serverStatusResendTime", "750", 0); // init autoswitch so the ui will have it correctly even // if the cgame hasn't been started - Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); + Cvar_Get("cg_autoswitch", "1", CVAR_ARCHIVE); - m_pitchVeh = Cvar_Get ("m_pitchVeh", "0.022", CVAR_ARCHIVE_ND); - m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE_ND); - m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE_ND); - m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE_ND); - m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE_ND); + m_pitchVeh = Cvar_Get("m_pitchVeh", "0.022", CVAR_ARCHIVE_ND); + m_pitch = Cvar_Get("m_pitch", "0.022", CVAR_ARCHIVE_ND); + m_yaw = Cvar_Get("m_yaw", "0.022", CVAR_ARCHIVE_ND); + m_forward = Cvar_Get("m_forward", "0.25", CVAR_ARCHIVE_ND); + m_side = Cvar_Get("m_side", "0.25", CVAR_ARCHIVE_ND); #ifdef MACOS_X - // Input is jittery on OS X w/o this - m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE_ND); + // Input is jittery on OS X w/o this + m_filter = Cvar_Get("m_filter", "1", CVAR_ARCHIVE_ND); #else - m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE_ND); + m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE_ND); #endif - cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); + cl_motdString = Cvar_Get("cl_motdString", "", CVAR_ROM); - Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE_ND, "Max. ping for servers when searching the serverlist" ); + Cvar_Get("cl_maxPing", "800", CVAR_ARCHIVE_ND, "Max. ping for servers when searching the serverlist"); - cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE_ND); + cl_lanForcePackets = Cvar_Get("cl_lanForcePackets", "1", CVAR_ARCHIVE_ND); cl_drawRecording = Cvar_Get("cl_drawRecording", "1", CVAR_ARCHIVE); // enable the ja_guid player identifier in userinfo by default in OpenJK - cl_enableGuid = Cvar_Get("cl_enableGuid", "1", CVAR_ARCHIVE_ND, "Enable GUID userinfo identifier" ); - cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE_ND, "Use a unique guid value per server" ); + cl_enableGuid = Cvar_Get("cl_enableGuid", "1", CVAR_ARCHIVE_ND, "Enable GUID userinfo identifier"); + cl_guidServerUniq = Cvar_Get("cl_guidServerUniq", "1", CVAR_ARCHIVE_ND, "Use a unique guid value per server"); // ~ and `, as keys and characters - cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE, "Which keys are used to toggle the console"); - cl_consoleUseScanCode = Cvar_Get( "cl_consoleUseScanCode", "1", CVAR_ARCHIVE, "Use native console key detection" ); - cl_consoleShiftRequirement = Cvar_Get( "cl_consoleShiftRequirement", "0", CVAR_ARCHIVE, "Require shift key to be pressed for native console key detection" ); + cl_consoleKeys = Cvar_Get("cl_consoleKeys", "~ ` 0x7e 0x60 0xb2", CVAR_ARCHIVE, "Which keys are used to toggle the console"); + cl_consoleUseScanCode = Cvar_Get("cl_consoleUseScanCode", "1", CVAR_ARCHIVE, "Use native console key detection"); + cl_consoleShiftRequirement = Cvar_Get("cl_consoleShiftRequirement", "0", CVAR_ARCHIVE, "Require shift key to be pressed for native console key detection"); - cl_filterGames = Cvar_Get( "cl_filterGames", "MBII MBIIOpenBeta", CVAR_ARCHIVE_ND, "List of fs_game to filter (space separated)" ); + cl_filterGames = Cvar_Get("cl_filterGames", "MBII MBIIOpenBeta", CVAR_ARCHIVE_ND, "List of fs_game to filter (space separated)"); // userinfo - Cvar_Get ("name", "Padawan", CVAR_USERINFO | CVAR_ARCHIVE_ND, "Player name" ); - Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE, "Data rate" ); - Cvar_Get ("snaps", "40", CVAR_USERINFO | CVAR_ARCHIVE, "Client snapshots per second" ); - Cvar_Get ("model", DEFAULT_MODEL"/default", CVAR_USERINFO | CVAR_ARCHIVE, "Player model" ); - Cvar_Get ("forcepowers", "7-1-032330000000001333", CVAR_USERINFO | CVAR_ARCHIVE, "Player forcepowers" ); -// Cvar_Get ("g_redTeam", DEFAULT_REDTEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE); -// Cvar_Get ("g_blueTeam", DEFAULT_BLUETEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE); - Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber1 color" ); - Cvar_Get ("color2", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber2 color" ); - Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE, "Player handicap" ); - Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE, "Player sex" ); - Cvar_Get ("password", "", CVAR_USERINFO, "Password to join server" ); - Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); - - //default sabers - Cvar_Get ("saber1", DEFAULT_SABER, CVAR_USERINFO | CVAR_ARCHIVE, "Player default right hand saber" ); - Cvar_Get ("saber2", "none", CVAR_USERINFO | CVAR_ARCHIVE, "Player left hand saber" ); - - //skin color - Cvar_Get ("char_color_red", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Red)" ); - Cvar_Get ("char_color_green", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Green)" ); - Cvar_Get ("char_color_blue", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Blue)" ); + Cvar_Get("name", "Padawan", CVAR_USERINFO | CVAR_ARCHIVE_ND, "Player name"); + Cvar_Get("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE, "Data rate"); + Cvar_Get("snaps", "40", CVAR_USERINFO | CVAR_ARCHIVE, "Client snapshots per second"); + Cvar_Get("model", DEFAULT_MODEL "/default", CVAR_USERINFO | CVAR_ARCHIVE, "Player model"); + Cvar_Get("forcepowers", "7-1-032330000000001333", CVAR_USERINFO | CVAR_ARCHIVE, "Player forcepowers"); + // Cvar_Get ("g_redTeam", DEFAULT_REDTEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE); + // Cvar_Get ("g_blueTeam", DEFAULT_BLUETEAM_NAME, CVAR_SERVERINFO | CVAR_ARCHIVE); + Cvar_Get("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber1 color"); + Cvar_Get("color2", "4", CVAR_USERINFO | CVAR_ARCHIVE, "Player saber2 color"); + Cvar_Get("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE, "Player handicap"); + Cvar_Get("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE, "Player sex"); + Cvar_Get("password", "", CVAR_USERINFO, "Password to join server"); + Cvar_Get("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE); + + // default sabers + Cvar_Get("saber1", DEFAULT_SABER, CVAR_USERINFO | CVAR_ARCHIVE, "Player default right hand saber"); + Cvar_Get("saber2", "none", CVAR_USERINFO | CVAR_ARCHIVE, "Player left hand saber"); + + // skin color + Cvar_Get("char_color_red", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Red)"); + Cvar_Get("char_color_green", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Green)"); + Cvar_Get("char_color_blue", "255", CVAR_USERINFO | CVAR_ARCHIVE, "Player tint (Blue)"); // cgame might not be initialized before menu is used - Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE_ND ); + Cvar_Get("cg_viewsize", "100", CVAR_ARCHIVE_ND); // // register our commands // - Cmd_AddCommand ("cmd", CL_ForwardToServer_f, "Forward command to server" ); - Cmd_AddCommand ("globalservers", CL_GlobalServers_f, "Query the masterserver for serverlist" ); - Cmd_AddCommand( "addFavorite", CL_AddFavorite_f, "Add server to favorites" ); - Cmd_AddCommand ("record", CL_Record_f, "Record a demo" ); - Cmd_AddCommand ("demo", CL_PlayDemo_f, "Playback a demo" ); - Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); - Cmd_AddCommand ("stoprecord", CL_StopRecord_f, "Stop recording a demo" ); - Cmd_AddCommand ("configstrings", CL_Configstrings_f, "Prints the configstrings list" ); - Cmd_AddCommand ("clientinfo", CL_Clientinfo_f, "Prints the userinfo variables" ); - Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f, "Restart sound" ); - Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f, "Restart the renderer - or change the resolution" ); - Cmd_AddCommand ("disconnect", CL_Disconnect_f, "Disconnect from current server" ); - Cmd_AddCommand ("cinematic", CL_PlayCinematic_f, "Play a cinematic video" ); - Cmd_AddCommand ("connect", CL_Connect_f, "Connect to a server" ); - Cmd_AddCommand ("reconnect", CL_Reconnect_f, "Reconnect to current server" ); - Cmd_AddCommand ("localservers", CL_LocalServers_f, "Query LAN for local servers" ); - Cmd_AddCommand ("rcon", CL_Rcon_f, "Execute commands remotely to a server" ); - Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); - Cmd_AddCommand ("ping", CL_Ping_f, "Ping a server for info response" ); - Cmd_AddCommand ("serverstatus", CL_ServerStatus_f, "Retrieve current or specified server's status" ); - Cmd_AddCommand ("showip", CL_ShowIP_f, "Shows local IP" ); - Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f, "Lists open pak files" ); - Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f, "Lists referenced pak files" ); - Cmd_AddCommand ("model", CL_SetModel_f, "Set the player model" ); - Cmd_AddCommand ("forcepowers", CL_SetForcePowers_f ); - Cmd_AddCommand ("video", CL_Video_f, "Record demo to avi" ); - Cmd_AddCommand ("stopvideo", CL_StopVideo_f, "Stop avi recording" ); + Cmd_AddCommand("cmd", CL_ForwardToServer_f, "Forward command to server"); + Cmd_AddCommand("globalservers", CL_GlobalServers_f, "Query the masterserver for serverlist"); + Cmd_AddCommand("addFavorite", CL_AddFavorite_f, "Add server to favorites"); + Cmd_AddCommand("record", CL_Record_f, "Record a demo"); + Cmd_AddCommand("demo", CL_PlayDemo_f, "Playback a demo"); + Cmd_SetCommandCompletionFunc("demo", CL_CompleteDemoName); + Cmd_AddCommand("stoprecord", CL_StopRecord_f, "Stop recording a demo"); + Cmd_AddCommand("configstrings", CL_Configstrings_f, "Prints the configstrings list"); + Cmd_AddCommand("clientinfo", CL_Clientinfo_f, "Prints the userinfo variables"); + Cmd_AddCommand("snd_restart", CL_Snd_Restart_f, "Restart sound"); + Cmd_AddCommand("vid_restart", CL_Vid_Restart_f, "Restart the renderer - or change the resolution"); + Cmd_AddCommand("disconnect", CL_Disconnect_f, "Disconnect from current server"); + Cmd_AddCommand("cinematic", CL_PlayCinematic_f, "Play a cinematic video"); + Cmd_AddCommand("connect", CL_Connect_f, "Connect to a server"); + Cmd_AddCommand("reconnect", CL_Reconnect_f, "Reconnect to current server"); + Cmd_AddCommand("localservers", CL_LocalServers_f, "Query LAN for local servers"); + Cmd_AddCommand("rcon", CL_Rcon_f, "Execute commands remotely to a server"); + Cmd_SetCommandCompletionFunc("rcon", CL_CompleteRcon); + Cmd_AddCommand("ping", CL_Ping_f, "Ping a server for info response"); + Cmd_AddCommand("serverstatus", CL_ServerStatus_f, "Retrieve current or specified server's status"); + Cmd_AddCommand("showip", CL_ShowIP_f, "Shows local IP"); + Cmd_AddCommand("fs_openedList", CL_OpenedPK3List_f, "Lists open pak files"); + Cmd_AddCommand("fs_referencedList", CL_ReferencedPK3List_f, "Lists referenced pak files"); + Cmd_AddCommand("model", CL_SetModel_f, "Set the player model"); + Cmd_AddCommand("forcepowers", CL_SetForcePowers_f); + Cmd_AddCommand("video", CL_Video_f, "Record demo to avi"); + Cmd_AddCommand("stopvideo", CL_StopVideo_f, "Stop avi recording"); CL_InitRef(); - SCR_Init (); + SCR_Init(); - Cbuf_Execute (); + Cbuf_Execute(); - Cvar_Set( "cl_running", "1" ); + Cvar_Set("cl_running", "1"); - G2VertSpaceClient = new CMiniHeap (G2_VERT_SPACE_CLIENT_SIZE * 1024); + G2VertSpaceClient = new CMiniHeap(G2_VERT_SPACE_CLIENT_SIZE * 1024); CL_GenerateQKey(); - CL_UpdateGUID( NULL, 0 ); + CL_UpdateGUID(NULL, 0); -// Com_Printf( "----- Client Initialization Complete -----\n" ); + // Com_Printf( "----- Client Initialization Complete -----\n" ); } - /* =============== CL_Shutdown =============== */ -void CL_Shutdown( void ) { +void CL_Shutdown(void) { static qboolean recursive = qfalse; - //Com_Printf( "----- CL_Shutdown -----\n" ); + // Com_Printf( "----- CL_Shutdown -----\n" ); - if ( recursive ) { - Com_Printf ("WARNING: Recursive CL_Shutdown called!\n"); + if (recursive) { + Com_Printf("WARNING: Recursive CL_Shutdown called!\n"); return; } recursive = qtrue; - if (G2VertSpaceClient) - { + if (G2VertSpaceClient) { delete G2VertSpaceClient; G2VertSpaceClient = 0; } - CL_Disconnect( qtrue ); + CL_Disconnect(qtrue); // RJ: added the shutdown all to close down the cgame (to free up some memory, such as in the fx system) - CL_ShutdownAll( qtrue ); + CL_ShutdownAll(qtrue); S_Shutdown(); - //CL_ShutdownUI(); - - Cmd_RemoveCommand ("cmd"); - Cmd_RemoveCommand ("configstrings"); - Cmd_RemoveCommand ("clientinfo"); - Cmd_RemoveCommand ("snd_restart"); - Cmd_RemoveCommand ("vid_restart"); - Cmd_RemoveCommand ("disconnect"); - Cmd_RemoveCommand ("record"); - Cmd_RemoveCommand ("demo"); - Cmd_RemoveCommand ("cinematic"); - Cmd_RemoveCommand ("stoprecord"); - Cmd_RemoveCommand ("connect"); - Cmd_RemoveCommand ("reconnect"); - Cmd_RemoveCommand ("localservers"); - Cmd_RemoveCommand ("globalservers"); - Cmd_RemoveCommand( "addFavorite" ); - Cmd_RemoveCommand ("rcon"); - Cmd_RemoveCommand ("ping"); - Cmd_RemoveCommand ("serverstatus"); - Cmd_RemoveCommand ("showip"); - Cmd_RemoveCommand ("fs_openedList"); - Cmd_RemoveCommand ("fs_referencedList"); - Cmd_RemoveCommand ("model"); - Cmd_RemoveCommand ("forcepowers"); - Cmd_RemoveCommand ("video"); - Cmd_RemoveCommand ("stopvideo"); + // CL_ShutdownUI(); + + Cmd_RemoveCommand("cmd"); + Cmd_RemoveCommand("configstrings"); + Cmd_RemoveCommand("clientinfo"); + Cmd_RemoveCommand("snd_restart"); + Cmd_RemoveCommand("vid_restart"); + Cmd_RemoveCommand("disconnect"); + Cmd_RemoveCommand("record"); + Cmd_RemoveCommand("demo"); + Cmd_RemoveCommand("cinematic"); + Cmd_RemoveCommand("stoprecord"); + Cmd_RemoveCommand("connect"); + Cmd_RemoveCommand("reconnect"); + Cmd_RemoveCommand("localservers"); + Cmd_RemoveCommand("globalservers"); + Cmd_RemoveCommand("addFavorite"); + Cmd_RemoveCommand("rcon"); + Cmd_RemoveCommand("ping"); + Cmd_RemoveCommand("serverstatus"); + Cmd_RemoveCommand("showip"); + Cmd_RemoveCommand("fs_openedList"); + Cmd_RemoveCommand("fs_referencedList"); + Cmd_RemoveCommand("model"); + Cmd_RemoveCommand("forcepowers"); + Cmd_RemoveCommand("video"); + Cmd_RemoveCommand("stopvideo"); CL_ShutdownInput(); Con_Shutdown(); - Cvar_Set( "cl_running", "0" ); + Cvar_Set("cl_running", "0"); recursive = qfalse; - Com_Memset( &cls, 0, sizeof( cls ) ); - Key_SetCatcher( 0 ); - - //Com_Printf( "-----------------------\n" ); + Com_Memset(&cls, 0, sizeof(cls)); + Key_SetCatcher(0); + // Com_Printf( "-----------------------\n" ); } -qboolean CL_ConnectedToRemoteServer( void ) { - return (qboolean)( com_sv_running && !com_sv_running->integer && cls.state >= CA_CONNECTED && !clc.demoplaying ); -} +qboolean CL_ConnectedToRemoteServer(void) { return (qboolean)(com_sv_running && !com_sv_running->integer && cls.state >= CA_CONNECTED && !clc.demoplaying); } static void CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) { if (server) { if (info) { server->clients = atoi(Info_ValueForKey(info, "clients")); - Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH); + Q_strncpyz(server->hostName, Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH); Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH); server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients")); - Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH); + Q_strncpyz(server->game, Info_ValueForKey(info, "game"), MAX_NAME_LENGTH); server->gameType = atoi(Info_ValueForKey(info, "gametype")); server->netType = atoi(Info_ValueForKey(info, "nettype")); server->minPing = atoi(Info_ValueForKey(info, "minping")); server->maxPing = atoi(Info_ValueForKey(info, "maxping")); -// server->allowAnonymous = atoi(Info_ValueForKey(info, "sv_allowAnonymous")); - server->needPassword = (qboolean)atoi(Info_ValueForKey(info, "needpass" )); - server->trueJedi = atoi(Info_ValueForKey(info, "truejedi" )); - server->weaponDisable = atoi(Info_ValueForKey(info, "wdisable" )); - server->forceDisable = atoi(Info_ValueForKey(info, "fdisable" )); - server->humans = atoi( Info_ValueForKey( info, "g_humanplayers" ) ); - server->bots = atoi( Info_ValueForKey( info, "bots" ) ); -// server->pure = (qboolean)atoi(Info_ValueForKey(info, "pure" )); + // server->allowAnonymous = atoi(Info_ValueForKey(info, "sv_allowAnonymous")); + server->needPassword = (qboolean)atoi(Info_ValueForKey(info, "needpass")); + server->trueJedi = atoi(Info_ValueForKey(info, "truejedi")); + server->weaponDisable = atoi(Info_ValueForKey(info, "wdisable")); + server->forceDisable = atoi(Info_ValueForKey(info, "fdisable")); + server->humans = atoi(Info_ValueForKey(info, "g_humanplayers")); + server->bots = atoi(Info_ValueForKey(info, "bots")); + // server->pure = (qboolean)atoi(Info_ValueForKey(info, "pure" )); } server->ping = ping; } @@ -2983,66 +2878,64 @@ static void CL_SetServerInfoByAddress(netadr_t from, const char *info, int ping) CL_ServerInfoPacket =================== */ -void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) { - int i, type; - char info[MAX_INFO_STRING]; - char *infoString; - int prot; +void CL_ServerInfoPacket(netadr_t from, msg_t *msg) { + int i, type; + char info[MAX_INFO_STRING]; + char *infoString; + int prot; - infoString = MSG_ReadString( msg ); + infoString = MSG_ReadString(msg); // if this isn't the correct protocol version, ignore it - prot = atoi( Info_ValueForKey( infoString, "protocol" ) ); - if ( prot != PROTOCOL_VERSION ) { - Com_DPrintf( "Different protocol info packet: %s\n", infoString ); + prot = atoi(Info_ValueForKey(infoString, "protocol")); + if (prot != PROTOCOL_VERSION) { + Com_DPrintf("Different protocol info packet: %s\n", infoString); return; } - if ( cl_filterGames && cl_filterGames->string && cl_filterGames->string[0] ) { - const char *gameFolder = Info_ValueForKey( infoString, "game" ); + if (cl_filterGames && cl_filterGames->string && cl_filterGames->string[0]) { + const char *gameFolder = Info_ValueForKey(infoString, "game"); // If no game folder was specified the server is using base. Use the BASEGAME string so we can filter for it. - if ( !gameFolder[0] ) gameFolder = BASEGAME; + if (!gameFolder[0]) + gameFolder = BASEGAME; // NOTE: As the command tokenization doesn't support nested quotes we can't filter fs_game with spaces using // this approach, but fs_game with spaces cause other issues as well, like downloads not working and at // the time of writing this no public servers actually use an fs_game with spaces... - Cmd_TokenizeString( cl_filterGames->string ); - for ( i = 0; i < Cmd_Argc(); i++ ) { - if ( !Q_stricmp(Cmd_Argv(i), gameFolder) && Q_stricmp(Cmd_Argv(i), FS_GetCurrentGameDir(false)) ) { + Cmd_TokenizeString(cl_filterGames->string); + for (i = 0; i < Cmd_Argc(); i++) { + if (!Q_stricmp(Cmd_Argv(i), gameFolder) && Q_stricmp(Cmd_Argv(i), FS_GetCurrentGameDir(false))) { return; } } } // iterate servers waiting for ping response - for (i=0; iinteger ) { - Com_Printf( "ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString( from ) ); + if (com_developer->integer) { + Com_Printf("ping time %dms from %s\n", cl_pinglist[i].time, NET_AdrToString(from)); } // save of info - Q_strncpyz( cl_pinglist[i].info, infoString, sizeof( cl_pinglist[i].info ) ); + Q_strncpyz(cl_pinglist[i].info, infoString, sizeof(cl_pinglist[i].info)); // tack on the net type // NOTE: make sure these types are in sync with the netnames strings in the UI - switch (from.type) - { - case NA_BROADCAST: - case NA_IP: - type = 1; - break; - - default: - type = 0; - break; + switch (from.type) { + case NA_BROADCAST: + case NA_IP: + type = 1; + break; + + default: + type = 0; + break; } - Info_SetValueForKey( cl_pinglist[i].info, "nettype", va("%d", type) ); + Info_SetValueForKey(cl_pinglist[i].info, "nettype", va("%d", type)); CL_SetServerInfoByAddress(from, infoString, cl_pinglist[i].time); return; @@ -3054,33 +2947,33 @@ void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) { return; } - for ( i = 0 ; i < MAX_OTHER_SERVERS ; i++ ) { + for (i = 0; i < MAX_OTHER_SERVERS; i++) { // empty slot - if ( cls.localServers[i].adr.port == 0 ) { + if (cls.localServers[i].adr.port == 0) { break; } // avoid duplicate - if ( NET_CompareAdr( from, cls.localServers[i].adr ) ) { + if (NET_CompareAdr(from, cls.localServers[i].adr)) { return; } } - if ( i == MAX_OTHER_SERVERS ) { - Com_DPrintf( "MAX_OTHER_SERVERS hit, dropping infoResponse\n" ); + if (i == MAX_OTHER_SERVERS) { + Com_DPrintf("MAX_OTHER_SERVERS hit, dropping infoResponse\n"); return; } // add this to the list - cls.numlocalservers = i+1; - CL_InitServerInfo( &cls.localServers[i], &from ); + cls.numlocalservers = i + 1; + CL_InitServerInfo(&cls.localServers[i], &from); - Q_strncpyz( info, MSG_ReadString( msg ), MAX_INFO_STRING ); + Q_strncpyz(info, MSG_ReadString(msg), MAX_INFO_STRING); if (strlen(info)) { - if (info[strlen(info)-1] != '\n') { + if (info[strlen(info) - 1] != '\n') { Q_strcat(info, sizeof(info), "\n"); } - Com_Printf( "%s: %s", NET_AdrToString( from ), info ); + Com_Printf("%s: %s", NET_AdrToString(from), info); } } @@ -3089,16 +2982,16 @@ void CL_ServerInfoPacket( netadr_t from, msg_t *msg ) { CL_GetServerStatus =================== */ -serverStatus_t *CL_GetServerStatus( netadr_t from ) { +serverStatus_t *CL_GetServerStatus(netadr_t from) { int i, oldest, oldestTime; for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { - if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) { + if (NET_CompareAdr(from, cl_serverStatusList[i].address)) { return &cl_serverStatusList[i]; } } for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { - if ( cl_serverStatusList[i].retrieved ) { + if (cl_serverStatusList[i].retrieved) { return &cl_serverStatusList[i]; } } @@ -3114,7 +3007,7 @@ serverStatus_t *CL_GetServerStatus( netadr_t from ) { return &cl_serverStatusList[oldest]; } serverStatusCount++; - return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS-1)]; + return &cl_serverStatusList[serverStatusCount & (MAX_SERVERSTATUSREQUESTS - 1)]; } /* @@ -3122,13 +3015,13 @@ serverStatus_t *CL_GetServerStatus( netadr_t from ) { CL_ServerStatus =================== */ -int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int maxLen ) { +int CL_ServerStatus(const char *serverAddress, char *serverStatusString, int maxLen) { int i; - netadr_t to; + netadr_t to; serverStatus_t *serverStatus; // if no server address then reset all server status requests - if ( !serverAddress ) { + if (!serverAddress) { for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { cl_serverStatusList[i].address.port = 0; cl_serverStatusList[i].retrieved = qtrue; @@ -3136,18 +3029,18 @@ int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int ma return qfalse; } // get the address - if ( !NET_StringToAdr( serverAddress, &to ) ) { + if (!NET_StringToAdr(serverAddress, &to)) { return qfalse; } - serverStatus = CL_GetServerStatus( to ); + serverStatus = CL_GetServerStatus(to); // if no server status string then reset the server status request for this address - if ( !serverStatusString ) { + if (!serverStatusString) { serverStatus->retrieved = qtrue; return qfalse; } // if this server status request has the same address - if ( NET_CompareAdr( to, serverStatus->address) ) { + if (NET_CompareAdr(to, serverStatus->address)) { // if we received a response for this server status request if (!serverStatus->pending) { Q_strncpyz(serverStatusString, serverStatus->string, maxLen); @@ -3156,25 +3049,25 @@ int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int ma return qtrue; } // resend the request regularly - else if ( serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer ) { + else if (serverStatus->startTime < Com_Milliseconds() - cl_serverStatusResendTime->integer) { serverStatus->print = qfalse; serverStatus->pending = qtrue; serverStatus->retrieved = qfalse; serverStatus->time = 0; serverStatus->startTime = Com_Milliseconds(); - NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" ); + NET_OutOfBandPrint(NS_CLIENT, to, "getstatus"); return qfalse; } } // if retrieved - else if ( serverStatus->retrieved ) { + else if (serverStatus->retrieved) { serverStatus->address = to; serverStatus->print = qfalse; serverStatus->pending = qtrue; serverStatus->retrieved = qfalse; serverStatus->startTime = Com_Milliseconds(); serverStatus->time = 0; - NET_OutOfBandPrint( NS_CLIENT, to, "getstatus" ); + NET_OutOfBandPrint(NS_CLIENT, to, "getstatus"); return qfalse; } return qfalse; @@ -3185,16 +3078,16 @@ int CL_ServerStatus( const char *serverAddress, char *serverStatusString, int ma CL_ServerStatusResponse =================== */ -void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { - char *s; - char info[MAX_INFO_STRING]; - int i, l, score, ping; - int len; +void CL_ServerStatusResponse(netadr_t from, msg_t *msg) { + char *s; + char info[MAX_INFO_STRING]; + int i, l, score, ping; + int len; serverStatus_t *serverStatus; serverStatus = NULL; for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) { - if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) { + if (NET_CompareAdr(from, cl_serverStatusList[i].address)) { serverStatus = &cl_serverStatusList[i]; break; } @@ -3204,14 +3097,13 @@ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { return; } - s = MSG_ReadStringLine( msg ); + s = MSG_ReadStringLine(msg); len = 0; - Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s); + Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string) - len, "%s", s); if (serverStatus->print) { - Com_Printf( "Server (%s)\n", - NET_AdrToString( serverStatus->address ) ); + Com_Printf("Server (%s)\n", NET_AdrToString(serverStatus->address)); Com_Printf("Server settings:\n"); // print cvars while (*s) { @@ -3221,7 +3113,7 @@ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { l = 0; while (*s) { info[l++] = *s; - if (l >= MAX_INFO_STRING-1) + if (l >= MAX_INFO_STRING - 1) break; s++; if (*s == '\\') { @@ -3231,8 +3123,7 @@ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { info[l] = '\0'; if (i) { Com_Printf("%s\n", info); - } - else { + } else { Com_Printf("%-24s", info); } } @@ -3240,32 +3131,32 @@ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { } len = strlen(serverStatus->string); - Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\"); + Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string) - len, "\\"); if (serverStatus->print) { Com_Printf("\nPlayers:\n"); Com_Printf("num: score: ping: name:\n"); } - for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) { + for (i = 0, s = MSG_ReadStringLine(msg); *s; s = MSG_ReadStringLine(msg), i++) { len = strlen(serverStatus->string); - Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s); + Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string) - len, "\\%s", s); if (serverStatus->print) { score = ping = 0; sscanf(s, "%d %d", &score, &ping); s = strchr(s, ' '); if (s) - s = strchr(s+1, ' '); + s = strchr(s + 1, ' '); if (s) s++; else s = "unknown"; - Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s ); + Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s); } } len = strlen(serverStatus->string); - Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\"); + Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string) - len, "\\"); serverStatus->time = Com_Milliseconds(); serverStatus->address = from; @@ -3280,12 +3171,12 @@ void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) { CL_LocalServers_f ================== */ -void CL_LocalServers_f( void ) { - char *message; - int i, j; - netadr_t to; +void CL_LocalServers_f(void) { + char *message; + int i, j; + netadr_t to; - Com_Printf( "Scanning for servers on the local network...\n"); + Com_Printf("Scanning for servers on the local network...\n"); // reset the list, waiting for response cls.numlocalservers = 0; @@ -3296,7 +3187,7 @@ void CL_LocalServers_f( void ) { Com_Memset(&cls.localServers[i], 0, sizeof(cls.localServers[i])); cls.localServers[i].visible = b; } - Com_Memset( &to, 0, sizeof( to ) ); + Com_Memset(&to, 0, sizeof(to)); // The 'xxx' in the message is a challenge that will be echoed back // by the server. We don't care about that here, but master servers @@ -3304,15 +3195,15 @@ void CL_LocalServers_f( void ) { message = "\377\377\377\377getinfo xxx"; // send each message twice in case one is dropped - for ( i = 0 ; i < 2 ; i++ ) { + for (i = 0; i < 2; i++) { // send a broadcast packet on each server port // we support multiple server ports so a single machine // can nicely run multiple servers - for ( j = 0 ; j < NUM_SERVER_PORTS ; j++ ) { - to.port = BigShort( (short)(PORT_SERVER + j) ); + for (j = 0; j < NUM_SERVER_PORTS; j++) { + to.port = BigShort((short)(PORT_SERVER + j)); to.type = NA_BROADCAST; - NET_SendPacket( NS_CLIENT, strlen( message ), message, to ); + NET_SendPacket(NS_CLIENT, strlen(message), message, to); } } } @@ -3329,26 +3220,25 @@ OpenJK July 2017; made master 0 fetch all master servers and 1-5 request a singl ================== */ -void CL_GlobalServers_f( void ) { - netadr_t to; - int count, i, masterNum; - char command[1024], *masteraddress; +void CL_GlobalServers_f(void) { + netadr_t to; + int count, i, masterNum; + char command[1024], *masteraddress; - if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS) - { + if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS) { Com_Printf("usage: globalservers [keywords]\n", MAX_MASTER_SERVERS); return; } // request from all master servers - if ( masterNum == 0 ) { + if (masterNum == 0) { int numAddress = 0; - for ( i = 1; i <= MAX_MASTER_SERVERS; i++ ) { - Com_sprintf( command, sizeof(command), "sv_master%d", i ); + for (i = 1; i <= MAX_MASTER_SERVERS; i++) { + Com_sprintf(command, sizeof(command), "sv_master%d", i); masteraddress = Cvar_VariableString(command); - if(!*masteraddress) + if (!*masteraddress) continue; numAddress++; @@ -3357,35 +3247,33 @@ void CL_GlobalServers_f( void ) { Cbuf_AddText(command); } - if ( !numAddress ) { - Com_Printf( "CL_GlobalServers_f: Error: No master server addresses.\n"); + if (!numAddress) { + Com_Printf("CL_GlobalServers_f: Error: No master server addresses.\n"); } return; } - Com_sprintf( command, sizeof(command), "sv_master%d", masterNum ); - masteraddress = Cvar_VariableString( command ); + Com_sprintf(command, sizeof(command), "sv_master%d", masterNum); + masteraddress = Cvar_VariableString(command); - if ( !*masteraddress ) - { - Com_Printf( "CL_GlobalServers_f: Error: No master server address given for %s.\n", command ); + if (!*masteraddress) { + Com_Printf("CL_GlobalServers_f: Error: No master server address given for %s.\n", command); return; } // reset the list, waiting for response // -1 is used to distinguish a "no response" - i = NET_StringToAdr( masteraddress, &to ); + i = NET_StringToAdr(masteraddress, &to); - if (!i) - { - Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress ); + if (!i) { + Com_Printf("CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress); return; } to.type = NA_IP; to.port = BigShort(PORT_MASTER); - Com_Printf( "Requesting servers from the master %s (%s)...\n", masteraddress, NET_AdrToString( to ) ); + Com_Printf("Requesting servers from the master %s (%s)...\n", masteraddress, NET_AdrToString(to)); cls.numglobalservers = -1; cls.pingUpdateSource = AS_GLOBAL; @@ -3393,13 +3281,12 @@ void CL_GlobalServers_f( void ) { Com_sprintf(command, sizeof(command), "getservers %s", Cmd_Argv(2)); // tack on keywords - for (i = 3; i < count; i++) - { + for (i = 3; i < count; i++) { Q_strcat(command, sizeof(command), " "); Q_strcat(command, sizeof(command), Cmd_Argv(i)); } - NET_OutOfBandPrint( NS_SERVER, to, "%s", command ); + NET_OutOfBandPrint(NS_SERVER, to, "%s", command); } /* @@ -3407,34 +3294,30 @@ void CL_GlobalServers_f( void ) { CL_GetPing ================== */ -void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) -{ - const char *str; - int time; - int maxPing; +void CL_GetPing(int n, char *buf, int buflen, int *pingtime) { + const char *str; + int time; + int maxPing; - if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port) - { + if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port) { // empty or invalid slot - buf[0] = '\0'; + buf[0] = '\0'; *pingtime = 0; return; } - str = NET_AdrToString( cl_pinglist[n].adr ); - Q_strncpyz( buf, str, buflen ); + str = NET_AdrToString(cl_pinglist[n].adr); + Q_strncpyz(buf, str, buflen); time = cl_pinglist[n].time; - if (!time) - { + if (!time) { // check for timeout time = Sys_Milliseconds() - cl_pinglist[n].start; - maxPing = Cvar_VariableIntegerValue( "cl_maxPing" ); - if( maxPing < 100 ) { + maxPing = Cvar_VariableIntegerValue("cl_maxPing"); + if (maxPing < 100) { maxPing = 100; } - if (time < maxPing) - { + if (time < maxPing) { // not timed out yet time = 0; } @@ -3450,17 +3333,15 @@ void CL_GetPing( int n, char *buf, int buflen, int *pingtime ) CL_GetPingInfo ================== */ -void CL_GetPingInfo( int n, char *buf, int buflen ) -{ - if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port) - { +void CL_GetPingInfo(int n, char *buf, int buflen) { + if (n < 0 || n >= MAX_PINGREQUESTS || !cl_pinglist[n].adr.port) { // empty or invalid slot if (buflen) buf[0] = '\0'; return; } - Q_strncpyz( buf, cl_pinglist[n].info, buflen ); + Q_strncpyz(buf, cl_pinglist[n].info, buflen); } /* @@ -3468,8 +3349,7 @@ void CL_GetPingInfo( int n, char *buf, int buflen ) CL_ClearPing ================== */ -void CL_ClearPing( int n ) -{ +void CL_ClearPing(int n) { if (n < 0 || n >= MAX_PINGREQUESTS) return; @@ -3481,16 +3361,15 @@ void CL_ClearPing( int n ) CL_GetPingQueueCount ================== */ -int CL_GetPingQueueCount( void ) -{ - int i; - int count; - ping_t* pingptr; +int CL_GetPingQueueCount(void) { + int i; + int count; + ping_t *pingptr; - count = 0; + count = 0; pingptr = cl_pinglist; - for (i=0; iadr.port) { count++; } @@ -3504,30 +3383,23 @@ int CL_GetPingQueueCount( void ) CL_GetFreePing ================== */ -ping_t* CL_GetFreePing( void ) -{ - ping_t* pingptr; - ping_t* best; - int oldest; - int i; - int time; +ping_t *CL_GetFreePing(void) { + ping_t *pingptr; + ping_t *best; + int oldest; + int i; + int time; pingptr = cl_pinglist; - for (i=0; iadr.port) - { - if (!pingptr->time) - { - if (Sys_Milliseconds() - pingptr->start < 500) - { + if (pingptr->adr.port) { + if (!pingptr->time) { + if (Sys_Milliseconds() - pingptr->start < 500) { // still waiting for response continue; } - } - else if (pingptr->time < 500) - { + } else if (pingptr->time < 500) { // results have not been queried continue; } @@ -3540,16 +3412,14 @@ ping_t* CL_GetFreePing( void ) // use oldest entry pingptr = cl_pinglist; - best = cl_pinglist; - oldest = INT_MIN; - for (i=0; istart; - if (time > oldest) - { + if (time > oldest) { oldest = time; - best = pingptr; + best = pingptr; } } @@ -3561,33 +3431,33 @@ ping_t* CL_GetFreePing( void ) CL_Ping_f ================== */ -void CL_Ping_f( void ) { - netadr_t to; - ping_t* pingptr; - char* server; +void CL_Ping_f(void) { + netadr_t to; + ping_t *pingptr; + char *server; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "usage: ping [server]\n"); + if (Cmd_Argc() != 2) { + Com_Printf("usage: ping [server]\n"); return; } - Com_Memset( &to, 0, sizeof(netadr_t) ); + Com_Memset(&to, 0, sizeof(netadr_t)); server = Cmd_Argv(1); - if ( !NET_StringToAdr( server, &to ) ) { + if (!NET_StringToAdr(server, &to)) { return; } pingptr = CL_GetFreePing(); - memcpy( &pingptr->adr, &to, sizeof (netadr_t) ); + memcpy(&pingptr->adr, &to, sizeof(netadr_t)); pingptr->start = Sys_Milliseconds(); - pingptr->time = 0; + pingptr->time = 0; CL_SetServerInfoByAddress(pingptr->adr, NULL, 0); - NET_OutOfBandPrint( NS_CLIENT, to, "getinfo xxx" ); + NET_OutOfBandPrint(NS_CLIENT, to, "getinfo xxx"); } /* @@ -3596,10 +3466,10 @@ CL_UpdateVisiblePings_f ================== */ qboolean CL_UpdateVisiblePings_f(int source) { - int slots, i; - char buff[MAX_STRING_CHARS]; - int pingTime; - int max; + int slots, i; + char buff[MAX_STRING_CHARS]; + int pingTime; + int max; qboolean status = qfalse; if (source < 0 || source > AS_FAVORITES) { @@ -3613,20 +3483,20 @@ qboolean CL_UpdateVisiblePings_f(int source) { serverInfo_t *server = NULL; switch (source) { - case AS_LOCAL : - server = &cls.localServers[0]; - max = cls.numlocalservers; + case AS_LOCAL: + server = &cls.localServers[0]; + max = cls.numlocalservers; break; - case AS_GLOBAL : - server = &cls.globalServers[0]; - max = cls.numglobalservers; + case AS_GLOBAL: + server = &cls.globalServers[0]; + max = cls.numglobalservers; break; - case AS_FAVORITES : - server = &cls.favoriteServers[0]; - max = cls.numfavoriteservers; + case AS_FAVORITES: + server = &cls.favoriteServers[0]; + max = cls.numfavoriteservers; break; - default: - return qfalse; + default: + return qfalse; } for (i = 0; i < max; i++) { if (server[i].visible) { @@ -3640,7 +3510,7 @@ qboolean CL_UpdateVisiblePings_f(int source) { if (!cl_pinglist[j].adr.port) { continue; } - if (NET_CompareAdr( cl_pinglist[j].adr, server[i].adr)) { + if (NET_CompareAdr(cl_pinglist[j].adr, server[i].adr)) { // already on the list break; } @@ -3655,7 +3525,7 @@ qboolean CL_UpdateVisiblePings_f(int source) { memcpy(&cl_pinglist[j].adr, &server[i].adr, sizeof(netadr_t)); cl_pinglist[j].start = Sys_Milliseconds(); cl_pinglist[j].time = 0; - NET_OutOfBandPrint( NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx" ); + NET_OutOfBandPrint(NS_CLIENT, cl_pinglist[j].adr, "getinfo xxx"); slots++; } } @@ -3665,7 +3535,7 @@ qboolean CL_UpdateVisiblePings_f(int source) { // if we are updating global servers if (source == AS_GLOBAL) { // - if ( cls.numGlobalServerAddresses > 0 ) { + if (cls.numGlobalServerAddresses > 0) { // overwrite this server with one from the additional global servers cls.numGlobalServerAddresses--; CL_InitServerInfo(&server[i], &cls.globalServerAddresses[cls.numGlobalServerAddresses]); @@ -3684,7 +3554,7 @@ qboolean CL_UpdateVisiblePings_f(int source) { if (!cl_pinglist[i].adr.port) { continue; } - CL_GetPing( i, buff, MAX_STRING_CHARS, &pingTime ); + CL_GetPing(i, buff, MAX_STRING_CHARS, &pingTime); if (pingTime != 0) { CL_ClearPing(i); status = qtrue; @@ -3700,34 +3570,33 @@ CL_ServerStatus_f ================== */ void CL_ServerStatus_f(void) { - netadr_t to, *toptr = NULL; - char *server; + netadr_t to, *toptr = NULL; + char *server; serverStatus_t *serverStatus; - if ( Cmd_Argc() != 2 ) { - if ( cls.state != CA_ACTIVE || clc.demoplaying ) { - Com_Printf ("Not connected to a server.\n"); - Com_Printf( "Usage: serverstatus [server]\n"); + if (Cmd_Argc() != 2) { + if (cls.state != CA_ACTIVE || clc.demoplaying) { + Com_Printf("Not connected to a server.\n"); + Com_Printf("Usage: serverstatus [server]\n"); return; } toptr = &clc.serverAddress; } - if(!toptr) - { - Com_Memset( &to, 0, sizeof(netadr_t) ); + if (!toptr) { + Com_Memset(&to, 0, sizeof(netadr_t)); server = Cmd_Argv(1); toptr = &to; - if ( !NET_StringToAdr( server, toptr ) ) + if (!NET_StringToAdr(server, toptr)) return; } - NET_OutOfBandPrint( NS_CLIENT, *toptr, "getstatus" ); + NET_OutOfBandPrint(NS_CLIENT, *toptr, "getstatus"); - serverStatus = CL_GetServerStatus( *toptr ); + serverStatus = CL_GetServerStatus(*toptr); serverStatus->address = *toptr; serverStatus->print = qtrue; serverStatus->pending = qtrue; @@ -3738,7 +3607,4 @@ void CL_ServerStatus_f(void) { CL_ShowIP_f ================== */ -void CL_ShowIP_f(void) { - Sys_ShowIP(); -} - +void CL_ShowIP_f(void) { Sys_ShowIP(); } diff --git a/codemp/client/cl_net_chan.cpp b/codemp/client/cl_net_chan.cpp index d34317bbad..3b10c6fb0b 100644 --- a/codemp/client/cl_net_chan.cpp +++ b/codemp/client/cl_net_chan.cpp @@ -36,32 +36,32 @@ CL_Netchan_Encode ============== */ -static void CL_Netchan_Encode( msg_t *msg ) { +static void CL_Netchan_Encode(msg_t *msg) { int serverId, messageAcknowledge, reliableAcknowledge; int i, index, srdc, sbit, soob; byte key, *string; - if ( msg->cursize <= CL_ENCODE_START ) { + if (msg->cursize <= CL_ENCODE_START) { return; } - srdc = msg->readcount; - sbit = msg->bit; - soob = msg->oob; + srdc = msg->readcount; + sbit = msg->bit; + soob = msg->oob; - msg->bit = 0; - msg->readcount = 0; - msg->oob = (qboolean)0; + msg->bit = 0; + msg->readcount = 0; + msg->oob = (qboolean)0; - serverId = MSG_ReadLong(msg); + serverId = MSG_ReadLong(msg); messageAcknowledge = MSG_ReadLong(msg); reliableAcknowledge = MSG_ReadLong(msg); - msg->oob = (qboolean)soob; - msg->bit = sbit; - msg->readcount = srdc; + msg->oob = (qboolean)soob; + msg->bit = sbit; + msg->readcount = srdc; - string = (byte *)clc.serverCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ]; + string = (byte *)clc.serverCommands[reliableAcknowledge & (MAX_RELIABLE_COMMANDS - 1)]; index = 0; // key = clc.challenge ^ serverId ^ messageAcknowledge; @@ -69,12 +69,10 @@ static void CL_Netchan_Encode( msg_t *msg ) { // modify the key with the last received now acknowledged server command if (!string[index]) index = 0; - if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste - string[index] == '%') - { + if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste + string[index] == '%') { key ^= '.' << (i & 1); - } - else { + } else { key ^= string[index] << (i & 1); } index++; @@ -92,37 +90,35 @@ CL_Netchan_Decode ============== */ -static void CL_Netchan_Decode( msg_t *msg ) { +static void CL_Netchan_Decode(msg_t *msg) { long reliableAcknowledge, i, index; byte key, *string; - int srdc, sbit, soob; + int srdc, sbit, soob; - srdc = msg->readcount; - sbit = msg->bit; - soob = msg->oob; + srdc = msg->readcount; + sbit = msg->bit; + soob = msg->oob; - msg->oob = (qboolean)0; + msg->oob = (qboolean)0; reliableAcknowledge = MSG_ReadLong(msg); - msg->oob = (qboolean)soob; - msg->bit = sbit; - msg->readcount = srdc; + msg->oob = (qboolean)soob; + msg->bit = sbit; + msg->readcount = srdc; - string = (unsigned char *)clc.reliableCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ]; + string = (unsigned char *)clc.reliableCommands[reliableAcknowledge & (MAX_RELIABLE_COMMANDS - 1)]; index = 0; // xor the client challenge with the netchan sequence number (need something that changes every message) - key = clc.challenge ^ LittleLong( *(unsigned *)msg->data ); + key = clc.challenge ^ LittleLong(*(unsigned *)msg->data); for (i = msg->readcount + CL_DECODE_START; i < msg->cursize; i++) { // modify the key with the last sent and with this message acknowledged client command if (!string[index]) index = 0; - if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste - string[index] == '%') - { + if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste + string[index] == '%') { key ^= '.' << (i & 1); - } - else { + } else { key ^= string[index] << (i & 1); } index++; @@ -137,30 +133,28 @@ static void CL_Netchan_Decode( msg_t *msg ) { CL_Netchan_TransmitNextFragment ================= */ -void CL_Netchan_TransmitNextFragment( netchan_t *chan ) { - Netchan_TransmitNextFragment( chan ); -} +void CL_Netchan_TransmitNextFragment(netchan_t *chan) { Netchan_TransmitNextFragment(chan); } -//byte chksum[65536]; +// byte chksum[65536]; /* =============== CL_Netchan_Transmit ================ */ -void CL_Netchan_Transmit( netchan_t *chan, msg_t* msg ) { -// int i; - MSG_WriteByte( msg, clc_EOF ); -// for(i=CL_ENCODE_START;icursize;i++) { -// chksum[i-CL_ENCODE_START] = msg->data[i]; -// } - -// Huff_Compress( msg, CL_ENCODE_START ); - CL_Netchan_Encode( msg ); - Netchan_Transmit( chan, msg->cursize, msg->data ); +void CL_Netchan_Transmit(netchan_t *chan, msg_t *msg) { + // int i; + MSG_WriteByte(msg, clc_EOF); + // for(i=CL_ENCODE_START;icursize;i++) { + // chksum[i-CL_ENCODE_START] = msg->data[i]; + // } + + // Huff_Compress( msg, CL_ENCODE_START ); + CL_Netchan_Encode(msg); + Netchan_Transmit(chan, msg->cursize, msg->data); } -extern int oldsize; +extern int oldsize; int newsize = 0; /* @@ -168,22 +162,22 @@ int newsize = 0; CL_Netchan_Process ================= */ -qboolean CL_Netchan_Process( netchan_t *chan, msg_t *msg ) { +qboolean CL_Netchan_Process(netchan_t *chan, msg_t *msg) { int ret; -// int i; -// static int newsize = 0; + // int i; + // static int newsize = 0; - ret = Netchan_Process( chan, msg ); + ret = Netchan_Process(chan, msg); if (!ret) return qfalse; - CL_Netchan_Decode( msg ); -// Huff_Decompress( msg, CL_DECODE_START ); -// for(i=CL_DECODE_START+msg->readcount;icursize;i++) { -// if (msg->data[i] != chksum[i-(CL_DECODE_START+msg->readcount)]) { -// Com_Error(ERR_DROP,"bad %d v %d\n", msg->data[i], chksum[i-(CL_DECODE_START+msg->readcount)]); -// } -// } + CL_Netchan_Decode(msg); + // Huff_Decompress( msg, CL_DECODE_START ); + // for(i=CL_DECODE_START+msg->readcount;icursize;i++) { + // if (msg->data[i] != chksum[i-(CL_DECODE_START+msg->readcount)]) { + // Com_Error(ERR_DROP,"bad %d v %d\n", msg->data[i], chksum[i-(CL_DECODE_START+msg->readcount)]); + // } + // } newsize += msg->cursize; -// Com_Printf("saved %d to %d (%d%%)\n", (oldsize>>3), newsize, 100-(newsize*100/(oldsize>>3))); + // Com_Printf("saved %d to %d (%d%%)\n", (oldsize>>3), newsize, 100-(newsize*100/(oldsize>>3))); return qtrue; } diff --git a/codemp/client/cl_parse.cpp b/codemp/client/cl_parse.cpp index 379c458ee1..25d9e2115f 100644 --- a/codemp/client/cl_parse.cpp +++ b/codemp/client/cl_parse.cpp @@ -39,20 +39,12 @@ static char hiddenCvarVal[128]; char *svc_strings[256] = { "svc_bad", - "svc_nop", - "svc_gamestate", - "svc_configstring", - "svc_baseline", - "svc_serverCommand", - "svc_download", - "svc_snapshot", - "svc_setgame", - "svc_mapchange", + "svc_nop", "svc_gamestate", "svc_configstring", "svc_baseline", "svc_serverCommand", "svc_download", "svc_snapshot", "svc_setgame", "svc_mapchange", }; -void SHOWNET( msg_t *msg, char *s) { - if ( cl_shownet->integer >= 2) { - Com_Printf ("%3i:%s\n", msg->readcount-1, s); +void SHOWNET(msg_t *msg, char *s) { + if (cl_shownet->integer >= 2) { + Com_Printf("%3i:%s\n", msg->readcount - 1, s); } } @@ -72,25 +64,21 @@ Parses deltas from the given base and adds the resulting entity to the current frame ================== */ -void CL_DeltaEntity (msg_t *msg, clSnapshot_t *frame, int newnum, entityState_t *old, - qboolean unchanged) { - entityState_t *state; +void CL_DeltaEntity(msg_t *msg, clSnapshot_t *frame, int newnum, entityState_t *old, qboolean unchanged) { + entityState_t *state; // save the parsed entity state into the big circular buffer so // it can be used as the source for a later delta - state = &cl.parseEntities[cl.parseEntitiesNum & (MAX_PARSE_ENTITIES-1)]; + state = &cl.parseEntities[cl.parseEntitiesNum & (MAX_PARSE_ENTITIES - 1)]; - if ( unchanged ) - { + if (unchanged) { *state = *old; - } - else - { - MSG_ReadDeltaEntity( msg, old, state, newnum ); + } else { + MSG_ReadDeltaEntity(msg, old, state, newnum); } - if ( state->number == (MAX_GENTITIES-1) ) { - return; // entity was delta removed + if (state->number == (MAX_GENTITIES - 1)) { + return; // entity was delta removed } cl.parseEntitiesNum++; frame->numEntities++; @@ -102,10 +90,10 @@ CL_ParsePacketEntities ================== */ -void CL_ParsePacketEntities( msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *newframe) { - int newnum; - entityState_t *oldstate; - int oldindex, oldnum; +void CL_ParsePacketEntities(msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *newframe) { + int newnum; + entityState_t *oldstate; + int oldindex, oldnum; newframe->parseEntitiesNum = cl.parseEntitiesNum; newframe->numEntities = 0; @@ -116,95 +104,89 @@ void CL_ParsePacketEntities( msg_t *msg, clSnapshot_t *oldframe, clSnapshot_t *n if (!oldframe) { oldnum = 99999; } else { - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } - while ( 1 ) { + while (1) { // read the entity index number - newnum = MSG_ReadBits( msg, GENTITYNUM_BITS ); + newnum = MSG_ReadBits(msg, GENTITYNUM_BITS); - if ( newnum == (MAX_GENTITIES-1) ) { + if (newnum == (MAX_GENTITIES - 1)) { break; } - if ( msg->readcount > msg->cursize ) { - Com_Error (ERR_DROP,"CL_ParsePacketEntities: end of message"); + if (msg->readcount > msg->cursize) { + Com_Error(ERR_DROP, "CL_ParsePacketEntities: end of message"); } - while ( oldnum < newnum ) { + while (oldnum < newnum) { // one or more entities from the old packet are unchanged - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: unchanged: %i\n", msg->readcount, oldnum); } - CL_DeltaEntity( msg, newframe, oldnum, oldstate, qtrue ); + CL_DeltaEntity(msg, newframe, oldnum, oldstate, qtrue); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } if (oldnum == newnum) { // delta from previous state - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: delta: %i\n", msg->readcount, newnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: delta: %i\n", msg->readcount, newnum); } - CL_DeltaEntity( msg, newframe, newnum, oldstate, qfalse ); + CL_DeltaEntity(msg, newframe, newnum, oldstate, qfalse); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } continue; } - if ( oldnum > newnum ) { + if (oldnum > newnum) { // delta from baseline - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: baseline: %i\n", msg->readcount, newnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: baseline: %i\n", msg->readcount, newnum); } - CL_DeltaEntity( msg, newframe, newnum, &cl.entityBaselines[newnum], qfalse ); + CL_DeltaEntity(msg, newframe, newnum, &cl.entityBaselines[newnum], qfalse); continue; } - } // any remaining entities in the old frame are copied over - while ( oldnum != 99999 ) { + while (oldnum != 99999) { // one or more entities from the old packet are unchanged - if ( cl_shownet->integer == 3 ) { - Com_Printf ("%3i: unchanged: %i\n", msg->readcount, oldnum); + if (cl_shownet->integer == 3) { + Com_Printf("%3i: unchanged: %i\n", msg->readcount, oldnum); } - CL_DeltaEntity( msg, newframe, oldnum, oldstate, qtrue ); + CL_DeltaEntity(msg, newframe, oldnum, oldstate, qtrue); oldindex++; - if ( oldindex >= oldframe->numEntities ) { + if (oldindex >= oldframe->numEntities) { oldnum = 99999; } else { - oldstate = &cl.parseEntities[ - (oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES-1)]; + oldstate = &cl.parseEntities[(oldframe->parseEntitiesNum + oldindex) & (MAX_PARSE_ENTITIES - 1)]; oldnum = oldstate->number; } } } - /* ================ CL_ParseSnapshot @@ -214,27 +196,27 @@ cl.snap and saved in cl.snapshots[]. If the snapshot is invalid for any reason, no changes to the state will be made at all. ================ */ -void CL_ParseSnapshot( msg_t *msg ) { - int len; - clSnapshot_t *old; - clSnapshot_t newSnap; - int deltaNum; - int oldMessageNum; - int i, packetNum; +void CL_ParseSnapshot(msg_t *msg) { + int len; + clSnapshot_t *old; + clSnapshot_t newSnap; + int deltaNum; + int oldMessageNum; + int i, packetNum; // get the reliable sequence acknowledge number // NOTE: now sent with all server to client messages - //clc.reliableAcknowledge = MSG_ReadLong( msg ); + // clc.reliableAcknowledge = MSG_ReadLong( msg ); // read in the new snapshot to a temporary buffer // we will only copy to cl.snap if it is valid - Com_Memset (&newSnap, 0, sizeof(newSnap)); + Com_Memset(&newSnap, 0, sizeof(newSnap)); // we will have read any new server commands in this // message before we got to svc_snapshot newSnap.serverCommandNum = clc.serverCommandSequence; - newSnap.serverTime = MSG_ReadLong( msg ); + newSnap.serverTime = MSG_ReadLong(msg); // if we were just unpaused, we can only *now* really let the // change come into effect or the client hangs. @@ -242,82 +224,79 @@ void CL_ParseSnapshot( msg_t *msg ) { newSnap.messageNum = clc.serverMessageSequence; - deltaNum = MSG_ReadByte( msg ); - if ( !deltaNum ) { + deltaNum = MSG_ReadByte(msg); + if (!deltaNum) { newSnap.deltaNum = -1; } else { newSnap.deltaNum = newSnap.messageNum - deltaNum; } - newSnap.snapFlags = MSG_ReadByte( msg ); + newSnap.snapFlags = MSG_ReadByte(msg); // If the frame is delta compressed from data that we // no longer have available, we must suck up the rest of // the frame, but not use it, then ask for a non-compressed // message - if ( newSnap.deltaNum <= 0 ) { - newSnap.valid = qtrue; // uncompressed frame + if (newSnap.deltaNum <= 0) { + newSnap.valid = qtrue; // uncompressed frame old = NULL; - clc.demowaiting = qfalse; // we can start recording now + clc.demowaiting = qfalse; // we can start recording now } else { old = &cl.snapshots[newSnap.deltaNum & PACKET_MASK]; - if ( !old->valid ) { + if (!old->valid) { // should never happen - Com_Printf ("Delta from invalid frame (not supposed to happen!).\n"); - while ( ( newSnap.deltaNum & PACKET_MASK ) != ( newSnap.messageNum & PACKET_MASK ) && !old->valid ) { + Com_Printf("Delta from invalid frame (not supposed to happen!).\n"); + while ((newSnap.deltaNum & PACKET_MASK) != (newSnap.messageNum & PACKET_MASK) && !old->valid) { newSnap.deltaNum++; old = &cl.snapshots[newSnap.deltaNum & PACKET_MASK]; } - if ( old->valid ) { - Com_Printf ("Found more recent frame to delta from.\n"); + if (old->valid) { + Com_Printf("Found more recent frame to delta from.\n"); } } - if ( !old->valid ) { - Com_Printf ("Failed to find more recent frame to delta from.\n"); - } else if ( old->messageNum != newSnap.deltaNum ) { + if (!old->valid) { + Com_Printf("Failed to find more recent frame to delta from.\n"); + } else if (old->messageNum != newSnap.deltaNum) { // The frame that the server did the delta from // is too old, so we can't reconstruct it properly. - Com_Printf ("Delta frame too old.\n"); - } else if ( cl.parseEntitiesNum - old->parseEntitiesNum > MAX_PARSE_ENTITIES-128 ) { - Com_DPrintf ("Delta parseEntitiesNum too old.\n"); + Com_Printf("Delta frame too old.\n"); + } else if (cl.parseEntitiesNum - old->parseEntitiesNum > MAX_PARSE_ENTITIES - 128) { + Com_DPrintf("Delta parseEntitiesNum too old.\n"); } else { - newSnap.valid = qtrue; // valid delta parse + newSnap.valid = qtrue; // valid delta parse } } // read areamask - len = MSG_ReadByte( msg ); + len = MSG_ReadByte(msg); - if((unsigned)len > sizeof(newSnap.areamask)) - { - Com_Error (ERR_DROP,"CL_ParseSnapshot: Invalid size %d for areamask", len); + if ((unsigned)len > sizeof(newSnap.areamask)) { + Com_Error(ERR_DROP, "CL_ParseSnapshot: Invalid size %d for areamask", len); return; } - MSG_ReadData( msg, &newSnap.areamask, len); + MSG_ReadData(msg, &newSnap.areamask, len); // read playerinfo - SHOWNET( msg, "playerstate" ); - if ( old ) { - MSG_ReadDeltaPlayerstate( msg, &old->ps, &newSnap.ps ); - if (newSnap.ps.m_iVehicleNum) - { //this means we must have written our vehicle's ps too - MSG_ReadDeltaPlayerstate( msg, &old->vps, &newSnap.vps, qtrue ); + SHOWNET(msg, "playerstate"); + if (old) { + MSG_ReadDeltaPlayerstate(msg, &old->ps, &newSnap.ps); + if (newSnap.ps.m_iVehicleNum) { // this means we must have written our vehicle's ps too + MSG_ReadDeltaPlayerstate(msg, &old->vps, &newSnap.vps, qtrue); } } else { - MSG_ReadDeltaPlayerstate( msg, NULL, &newSnap.ps ); - if (newSnap.ps.m_iVehicleNum) - { //this means we must have written our vehicle's ps too - MSG_ReadDeltaPlayerstate( msg, NULL, &newSnap.vps, qtrue ); + MSG_ReadDeltaPlayerstate(msg, NULL, &newSnap.ps); + if (newSnap.ps.m_iVehicleNum) { // this means we must have written our vehicle's ps too + MSG_ReadDeltaPlayerstate(msg, NULL, &newSnap.vps, qtrue); } } // read packet entities - SHOWNET( msg, "packet entities" ); - CL_ParsePacketEntities( msg, old, &newSnap ); + SHOWNET(msg, "packet entities"); + CL_ParsePacketEntities(msg, old, &newSnap); // if not valid, dump the entire thing now that it has // been properly read - if ( !newSnap.valid ) { + if (!newSnap.valid) { return; } @@ -327,10 +306,10 @@ void CL_ParseSnapshot( msg_t *msg ) { // time we wrap around in the buffer oldMessageNum = cl.snap.messageNum + 1; - if ( newSnap.messageNum - oldMessageNum >= PACKET_BACKUP ) { - oldMessageNum = newSnap.messageNum - ( PACKET_BACKUP - 1 ); + if (newSnap.messageNum - oldMessageNum >= PACKET_BACKUP) { + oldMessageNum = newSnap.messageNum - (PACKET_BACKUP - 1); } - for ( ; oldMessageNum < newSnap.messageNum ; oldMessageNum++ ) { + for (; oldMessageNum < newSnap.messageNum; oldMessageNum++) { cl.snapshots[oldMessageNum & PACKET_MASK].valid = qfalse; } @@ -338,10 +317,10 @@ void CL_ParseSnapshot( msg_t *msg ) { cl.snap = newSnap; cl.snap.ping = 999; // calculate ping time - for ( i = 0 ; i < PACKET_BACKUP ; i++ ) { - packetNum = ( clc.netchan.outgoingSequence - 1 - i ) & PACKET_MASK; - if ( cl.snap.ps.commandTime >= cl.outPackets[ packetNum ].p_serverTime ) { - cl.snap.ping = cls.realtime - cl.outPackets[ packetNum ].p_realtime; + for (i = 0; i < PACKET_BACKUP; i++) { + packetNum = (clc.netchan.outgoingSequence - 1 - i) & PACKET_MASK; + if (cl.snap.ps.commandTime >= cl.outPackets[packetNum].p_serverTime) { + cl.snap.ping = cls.realtime - cl.outPackets[packetNum].p_realtime; break; } } @@ -349,14 +328,12 @@ void CL_ParseSnapshot( msg_t *msg ) { cl.snapshots[cl.snap.messageNum & PACKET_MASK] = cl.snap; if (cl_shownet->integer == 3) { - Com_Printf( " snapshot:%i delta:%i ping:%i\n", cl.snap.messageNum, - cl.snap.deltaNum, cl.snap.ping ); + Com_Printf(" snapshot:%i delta:%i ping:%i\n", cl.snap.messageNum, cl.snap.deltaNum, cl.snap.ping); } cl.newSnapshots = qtrue; } - /* ================ CL_ParseSetGame @@ -367,51 +344,44 @@ rww - Update fs_game, this message is so we can use the ext_data */ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides); void FS_UpdateGamedir(void); -void CL_ParseSetGame( msg_t *msg ) -{ +void CL_ParseSetGame(msg_t *msg) { char newGameDir[MAX_QPATH]; int i = 0; char next; - while (i < MAX_QPATH) - { - next = MSG_ReadByte( msg ); + while (i < MAX_QPATH) { + next = MSG_ReadByte(msg); - if (next) - { //if next is 0 then we have finished reading to the end of the message + if (next) { // if next is 0 then we have finished reading to the end of the message newGameDir[i] = next; - } - else - { + } else { break; } i++; } newGameDir[i] = 0; - if(FS_CheckDirTraversal(newGameDir)) - { + if (FS_CheckDirTraversal(newGameDir)) { Com_Printf(S_COLOR_YELLOW "WARNING: Server sent invalid fs_game value %s\n", newGameDir); return; } - if(!FS_FilenameCompare(newGameDir, BASEGAME)) + if (!FS_FilenameCompare(newGameDir, BASEGAME)) Cvar_Set("fs_game", ""); else Cvar_Set("fs_game", newGameDir); - if(!(Cvar_Flags("fs_game") & CVAR_MODIFIED)) + if (!(Cvar_Flags("fs_game") & CVAR_MODIFIED)) return; - //Update the search path for the mod dir + // Update the search path for the mod dir FS_UpdateGamedir(); - //Now update the overrides manually + // Now update the overrides manually MSG_CheckNETFPSFOverrides(qfalse); MSG_CheckNETFPSFOverrides(qtrue); } - //===================================================================== int cl_connectedToPureServer; @@ -426,71 +396,68 @@ new information out of it. This will happen at every gamestate, and possibly during gameplay. ================== */ -void CL_SystemInfoChanged( void ) { - char *systemInfo; - const char *s, *t; - char key[BIG_INFO_KEY]; - char value[BIG_INFO_VALUE]; - qboolean gameSet; - - systemInfo = cl.gameState.stringData + cl.gameState.stringOffsets[ CS_SYSTEMINFO ]; +void CL_SystemInfoChanged(void) { + char *systemInfo; + const char *s, *t; + char key[BIG_INFO_KEY]; + char value[BIG_INFO_VALUE]; + qboolean gameSet; + + systemInfo = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SYSTEMINFO]; // NOTE TTimo: // when the serverId changes, any further messages we send to the server will use this new serverId // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=475 // in some cases, outdated cp commands might get sent with this new serverId - cl.serverId = atoi( Info_ValueForKey( systemInfo, "sv_serverid" ) ); + cl.serverId = atoi(Info_ValueForKey(systemInfo, "sv_serverid")); // don't set any vars when playing a demo - if ( clc.demoplaying ) { + if (clc.demoplaying) { return; } - s = Info_ValueForKey( systemInfo, "sv_cheats" ); - cl_connectedToCheatServer = atoi( s ); - if ( !cl_connectedToCheatServer ) - { + s = Info_ValueForKey(systemInfo, "sv_cheats"); + cl_connectedToCheatServer = atoi(s); + if (!cl_connectedToCheatServer) { Cvar_SetCheatState(); } // check pure server string - s = Info_ValueForKey( systemInfo, "sv_paks" ); - t = Info_ValueForKey( systemInfo, "sv_pakNames" ); - FS_PureServerSetLoadedPaks( s, t ); + s = Info_ValueForKey(systemInfo, "sv_paks"); + t = Info_ValueForKey(systemInfo, "sv_pakNames"); + FS_PureServerSetLoadedPaks(s, t); - s = Info_ValueForKey( systemInfo, "sv_referencedPaks" ); - t = Info_ValueForKey( systemInfo, "sv_referencedPakNames" ); - FS_PureServerSetReferencedPaks( s, t ); + s = Info_ValueForKey(systemInfo, "sv_referencedPaks"); + t = Info_ValueForKey(systemInfo, "sv_referencedPakNames"); + FS_PureServerSetReferencedPaks(s, t); gameSet = qfalse; // scan through all the variables in the systeminfo and locally set cvars to match s = systemInfo; - while ( s ) { - Info_NextPair( &s, key, value ); - if ( !key[0] ) { + while (s) { + Info_NextPair(&s, key, value); + if (!key[0]) { break; } // ehw! - if ( !Q_stricmp( key, "fs_game" ) ) { - if(FS_CheckDirTraversal(value)) - { + if (!Q_stricmp(key, "fs_game")) { + if (FS_CheckDirTraversal(value)) { Com_Printf(S_COLOR_YELLOW "WARNING: Server sent invalid fs_game value %s\n", value); continue; } - if(!FS_FilenameCompare(value, BASEGAME)) - { + if (!FS_FilenameCompare(value, BASEGAME)) { Q_strncpyz(value, "", sizeof(value)); } gameSet = qtrue; } - Cvar_Server_Set( key, value ); + Cvar_Server_Set(key, value); } // if game folder should not be set and it is set at the client side - if ( !gameSet && *Cvar_VariableString("fs_game") ) { - Cvar_Set( "fs_game", "" ); + if (!gameSet && *Cvar_VariableString("fs_game")) { + Cvar_Set("fs_game", ""); } - cl_connectedToPureServer = Cvar_VariableValue( "sv_pure" ); + cl_connectedToPureServer = Cvar_VariableValue("sv_pure"); } /* @@ -498,13 +465,13 @@ void CL_SystemInfoChanged( void ) { CL_ParseGamestate ================== */ -void CL_ParseGamestate( msg_t *msg ) { - int i; - entityState_t *es; - int newnum; - entityState_t nullstate; - int cmd; - char *s; +void CL_ParseGamestate(msg_t *msg) { + int i; + entityState_t *es; + int newnum; + entityState_t nullstate; + int cmd; + char *s; Con_Close(); @@ -514,30 +481,29 @@ void CL_ParseGamestate( msg_t *msg ) { CL_ClearState(); // a gamestate always marks a server command sequence - clc.serverCommandSequence = MSG_ReadLong( msg ); + clc.serverCommandSequence = MSG_ReadLong(msg); // parse all the configstrings and baselines - cl.gameState.dataCount = 1; // leave a 0 at the beginning for uninitialized configstrings - while ( 1 ) { - cmd = MSG_ReadByte( msg ); + cl.gameState.dataCount = 1; // leave a 0 at the beginning for uninitialized configstrings + while (1) { + cmd = MSG_ReadByte(msg); - if ( cmd == svc_EOF ) { + if (cmd == svc_EOF) { break; } - if ( cmd == svc_configstring ) { - int len, start; + if (cmd == svc_configstring) { + int len, start; start = msg->readcount; - i = MSG_ReadShort( msg ); - if ( i < 0 || i >= MAX_CONFIGSTRINGS ) { - Com_Error( ERR_DROP, "configstring > MAX_CONFIGSTRINGS" ); + i = MSG_ReadShort(msg); + if (i < 0 || i >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "configstring > MAX_CONFIGSTRINGS"); } - s = MSG_ReadBigString( msg ); + s = MSG_ReadBigString(msg); - if (cl_shownet->integer >= 2) - { + if (cl_shownet->integer >= 2) { Com_Printf("%3i: %d: %s\n", start, i, s); } @@ -571,46 +537,45 @@ void CL_ParseGamestate( msg_t *msg ) { } */ - len = strlen( s ); + len = strlen(s); - if ( len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS ) { - Com_Error( ERR_DROP, "MAX_GAMESTATE_CHARS exceeded" ); + if (len + 1 + cl.gameState.dataCount > MAX_GAMESTATE_CHARS) { + Com_Error(ERR_DROP, "MAX_GAMESTATE_CHARS exceeded"); } // append it to the gameState string buffer - cl.gameState.stringOffsets[ i ] = cl.gameState.dataCount; - Com_Memcpy( cl.gameState.stringData + cl.gameState.dataCount, s, len + 1 ); + cl.gameState.stringOffsets[i] = cl.gameState.dataCount; + Com_Memcpy(cl.gameState.stringData + cl.gameState.dataCount, s, len + 1); cl.gameState.dataCount += len + 1; - } else if ( cmd == svc_baseline ) { - newnum = MSG_ReadBits( msg, GENTITYNUM_BITS ); - if ( newnum < 0 || newnum >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "Baseline number out of range: %i", newnum ); + } else if (cmd == svc_baseline) { + newnum = MSG_ReadBits(msg, GENTITYNUM_BITS); + if (newnum < 0 || newnum >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "Baseline number out of range: %i", newnum); } - Com_Memset (&nullstate, 0, sizeof(nullstate)); - es = &cl.entityBaselines[ newnum ]; - MSG_ReadDeltaEntity( msg, &nullstate, es, newnum ); + Com_Memset(&nullstate, 0, sizeof(nullstate)); + es = &cl.entityBaselines[newnum]; + MSG_ReadDeltaEntity(msg, &nullstate, es, newnum); } else { - Com_Error( ERR_DROP, "CL_ParseGamestate: bad command byte" ); + Com_Error(ERR_DROP, "CL_ParseGamestate: bad command byte"); } } clc.clientNum = MSG_ReadLong(msg); // read the checksum feed - clc.checksumFeed = MSG_ReadLong( msg ); + clc.checksumFeed = MSG_ReadLong(msg); // Throw away the info for the old RMG system. - MSG_ReadShort (msg); - + MSG_ReadShort(msg); // parse serverId and other cvars CL_SystemInfoChanged(); // reinitialize the filesystem if the game directory has changed - if( FS_ConditionalRestart( clc.checksumFeed ) ) { + if (FS_ConditionalRestart(clc.checksumFeed)) { // don't set to true because we yet have to start downloading // enabling this can cause double loading of a map when connecting to // a server which has a different game directory set - //clc.downloadRestart = qtrue; + // clc.downloadRestart = qtrue; } // This used to call CL_StartHunkUsers, but now we enter the download state before loading the @@ -618,10 +583,9 @@ void CL_ParseGamestate( msg_t *msg ) { CL_InitDownloads(); // make sure the game starts - Cvar_Set( "cl_paused", "0" ); + Cvar_Set("cl_paused", "0"); } - //===================================================================== /* @@ -631,8 +595,8 @@ CL_ParseDownload A download message has been received from the server ===================== */ -void CL_ParseDownload ( msg_t *msg ) { - int size; +void CL_ParseDownload(msg_t *msg) { + int size; unsigned char data[MAX_MSGLEN]; uint16_t block; @@ -643,68 +607,63 @@ void CL_ParseDownload ( msg_t *msg ) { } // read the data - block = MSG_ReadShort ( msg ); + block = MSG_ReadShort(msg); - if ( !block && !clc.downloadBlock ) - { + if (!block && !clc.downloadBlock) { // block zero is special, contains file size - clc.downloadSize = MSG_ReadLong ( msg ); + clc.downloadSize = MSG_ReadLong(msg); - Cvar_SetValue( "cl_downloadSize", clc.downloadSize ); + Cvar_SetValue("cl_downloadSize", clc.downloadSize); - if (clc.downloadSize < 0) - { - Com_Error(ERR_DROP, "%s", MSG_ReadString( msg ) ); + if (clc.downloadSize < 0) { + Com_Error(ERR_DROP, "%s", MSG_ReadString(msg)); return; } } - size = /*(unsigned short)*/MSG_ReadShort ( msg ); - if (size < 0 || size > (int)sizeof(data)) - { + size = /*(unsigned short)*/ MSG_ReadShort(msg); + if (size < 0 || size > (int)sizeof(data)) { Com_Error(ERR_DROP, "CL_ParseDownload: Invalid size %d for download chunk", size); return; } - MSG_ReadData( msg, data, size ); + MSG_ReadData(msg, data, size); - if((clc.downloadBlock & 0xFFFF) != block) - { - Com_DPrintf( "CL_ParseDownload: Expected block %d, got %d\n", (clc.downloadBlock & 0xFFFF), block); + if ((clc.downloadBlock & 0xFFFF) != block) { + Com_DPrintf("CL_ParseDownload: Expected block %d, got %d\n", (clc.downloadBlock & 0xFFFF), block); return; } // open the file if not opened yet - if (!clc.download) - { - clc.download = FS_SV_FOpenFileWrite( clc.downloadTempName ); + if (!clc.download) { + clc.download = FS_SV_FOpenFileWrite(clc.downloadTempName); if (!clc.download) { - Com_Printf( "Could not create %s\n", clc.downloadTempName ); - CL_AddReliableCommand( "stopdl", qfalse ); + Com_Printf("Could not create %s\n", clc.downloadTempName); + CL_AddReliableCommand("stopdl", qfalse); CL_NextDownload(); return; } } if (size) - FS_Write( data, size, clc.download ); + FS_Write(data, size, clc.download); - CL_AddReliableCommand( va("nextdl %d", clc.downloadBlock), qfalse ); + CL_AddReliableCommand(va("nextdl %d", clc.downloadBlock), qfalse); clc.downloadBlock++; clc.downloadCount += size; // So UI gets access to it - Cvar_SetValue( "cl_downloadCount", clc.downloadCount ); + Cvar_SetValue("cl_downloadCount", clc.downloadCount); if (!size) { // A zero length block means EOF if (clc.download) { - FS_FCloseFile( clc.download ); + FS_FCloseFile(clc.download); clc.download = 0; // rename the file - FS_SV_Rename ( clc.downloadTempName, clc.downloadName, qfalse ); + FS_SV_Rename(clc.downloadTempName, clc.downloadName, qfalse); } // send intentions now @@ -716,12 +675,11 @@ void CL_ParseDownload ( msg_t *msg ) { CL_WritePacket(); // get another file if needed - CL_NextDownload (); + CL_NextDownload(); } } -int CL_GetValueForHidden(const char *s) -{ //string arg here just in case I want to add more sometime and make a lookup table +int CL_GetValueForHidden(const char *s) { // string arg here just in case I want to add more sometime and make a lookup table return atoi(hiddenCvarVal); } @@ -733,21 +691,21 @@ Command strings are just saved off until cgame asks for them when it transitions a snapshot ===================== */ -void CL_ParseCommandString( msg_t *msg ) { - char *s; - int seq; - int index; +void CL_ParseCommandString(msg_t *msg) { + char *s; + int seq; + int index; - seq = MSG_ReadLong( msg ); - s = MSG_ReadString( msg ); + seq = MSG_ReadLong(msg); + s = MSG_ReadString(msg); // see if we have already executed stored it off - if ( clc.serverCommandSequence >= seq ) { + if (clc.serverCommandSequence >= seq) { return; } clc.serverCommandSequence = seq; - index = seq & (MAX_RELIABLE_COMMANDS-1); + index = seq & (MAX_RELIABLE_COMMANDS - 1); /* if (s[0] == 'c' && s[1] == 's' && s[2] == ' ' && s[3] == '0' && s[4] == ' ') { //yes.. we seem to have an incoming server info. @@ -795,81 +753,80 @@ void CL_ParseCommandString( msg_t *msg ) { } } */ - Q_strncpyz( clc.serverCommands[ index ], s, sizeof( clc.serverCommands[ index ] ) ); + Q_strncpyz(clc.serverCommands[index], s, sizeof(clc.serverCommands[index])); } - /* ===================== CL_ParseServerMessage ===================== */ -void CL_ParseServerMessage( msg_t *msg ) { - int cmd; +void CL_ParseServerMessage(msg_t *msg) { + int cmd; - if ( cl_shownet->integer == 1 ) { - Com_Printf ("%i ",msg->cursize); - } else if ( cl_shownet->integer >= 2 ) { - Com_Printf ("------------------\n"); + if (cl_shownet->integer == 1) { + Com_Printf("%i ", msg->cursize); + } else if (cl_shownet->integer >= 2) { + Com_Printf("------------------\n"); } MSG_Bitstream(msg); // get the reliable sequence acknowledge number - clc.reliableAcknowledge = MSG_ReadLong( msg ); + clc.reliableAcknowledge = MSG_ReadLong(msg); // - if ( clc.reliableAcknowledge < clc.reliableSequence - MAX_RELIABLE_COMMANDS ) { + if (clc.reliableAcknowledge < clc.reliableSequence - MAX_RELIABLE_COMMANDS) { clc.reliableAcknowledge = clc.reliableSequence; } // // parse the message // - while ( 1 ) { - if ( msg->readcount > msg->cursize ) { - Com_Error (ERR_DROP,"CL_ParseServerMessage: read past end of server message"); + while (1) { + if (msg->readcount > msg->cursize) { + Com_Error(ERR_DROP, "CL_ParseServerMessage: read past end of server message"); break; } - cmd = MSG_ReadByte( msg ); + cmd = MSG_ReadByte(msg); - if ( cmd == svc_EOF) { - SHOWNET( msg, "END OF MESSAGE" ); + if (cmd == svc_EOF) { + SHOWNET(msg, "END OF MESSAGE"); break; } - if ( cl_shownet->integer >= 2 ) { - if ( !svc_strings[cmd] ) { - Com_Printf( "%3i:BAD CMD %i\n", msg->readcount-1, cmd ); + if (cl_shownet->integer >= 2) { + if (!svc_strings[cmd]) { + Com_Printf("%3i:BAD CMD %i\n", msg->readcount - 1, cmd); } else { - SHOWNET( msg, svc_strings[cmd] ); + SHOWNET(msg, svc_strings[cmd]); } } - // other commands - switch ( cmd ) { + // other commands + switch (cmd) { default: - Com_Error (ERR_DROP,"CL_ParseServerMessage: Illegible server message\n"); + Com_Error(ERR_DROP, "CL_ParseServerMessage: Illegible server message\n"); break; case svc_nop: break; case svc_serverCommand: - CL_ParseCommandString( msg ); + CL_ParseCommandString(msg); break; case svc_gamestate: - CL_ParseGamestate( msg ); + CL_ParseGamestate(msg); break; case svc_snapshot: - CL_ParseSnapshot( msg ); + CL_ParseSnapshot(msg); break; case svc_setgame: - CL_ParseSetGame( msg ); + CL_ParseSetGame(msg); break; case svc_download: - CL_ParseDownload( msg ); + CL_ParseDownload(msg); break; case svc_mapchange: - if ( cls.cgameStarted ) + if (cls.cgameStarted) CGVM_MapChange(); break; } diff --git a/codemp/client/cl_scrn.cpp b/codemp/client/cl_scrn.cpp index fb1c18b884..41307d396c 100644 --- a/codemp/client/cl_scrn.cpp +++ b/codemp/client/cl_scrn.cpp @@ -28,13 +28,13 @@ along with this program; if not, see . #include "cl_uiapi.h" extern console_t con; -qboolean scr_initialized; // ready to draw +qboolean scr_initialized; // ready to draw -cvar_t *cl_timegraph; -cvar_t *cl_debuggraph; -cvar_t *cl_graphheight; -cvar_t *cl_graphscale; -cvar_t *cl_graphshift; +cvar_t *cl_timegraph; +cvar_t *cl_debuggraph; +cvar_t *cl_graphheight; +cvar_t *cl_graphscale; +cvar_t *cl_graphshift; /* ================ @@ -43,16 +43,15 @@ SCR_DrawNamedPic Coordinates are 640*480 virtual values ================= */ -void SCR_DrawNamedPic( float x, float y, float width, float height, const char *picname ) { - qhandle_t hShader; +void SCR_DrawNamedPic(float x, float y, float width, float height, const char *picname) { + qhandle_t hShader; - assert( width != 0 ); + assert(width != 0); - hShader = re->RegisterShader( picname ); - re->DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); + hShader = re->RegisterShader(picname); + re->DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } - /* ================ SCR_FillRect @@ -60,15 +59,14 @@ SCR_FillRect Coordinates are 640*480 virtual values ================= */ -void SCR_FillRect( float x, float y, float width, float height, const float *color ) { - re->SetColor( color ); +void SCR_FillRect(float x, float y, float width, float height, const float *color) { + re->SetColor(color); - re->DrawStretchPic( x, y, width, height, 0, 0, 0, 0, cls.whiteShader ); + re->DrawStretchPic(x, y, width, height, 0, 0, 0, 0, cls.whiteShader); - re->SetColor( NULL ); + re->SetColor(NULL); } - /* ================ SCR_DrawPic @@ -76,28 +74,24 @@ SCR_DrawPic Coordinates are 640*480 virtual values ================= */ -void SCR_DrawPic( float x, float y, float width, float height, qhandle_t hShader ) { - re->DrawStretchPic( x, y, width, height, 0, 0, 1, 1, hShader ); -} - - +void SCR_DrawPic(float x, float y, float width, float height, qhandle_t hShader) { re->DrawStretchPic(x, y, width, height, 0, 0, 1, 1, hShader); } /* ** SCR_DrawChar ** chars are drawn at 640*480 virtual screen size */ -static void SCR_DrawChar( int x, int y, float size, int ch ) { +static void SCR_DrawChar(int x, int y, float size, int ch) { int row, col; float frow, fcol; - float ax, ay, aw, ah; + float ax, ay, aw, ah; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } - if ( y < -size ) { + if (y < -size) { return; } @@ -106,62 +100,55 @@ static void SCR_DrawChar( int x, int y, float size, int ch ) { aw = size; ah = size; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; size2 = 0.0625; - re->DrawStretchPic( ax, ay, aw, ah, - fcol, frow, - fcol + size, frow + size2, - cls.charSetShader ); + re->DrawStretchPic(ax, ay, aw, ah, fcol, frow, fcol + size, frow + size2, cls.charSetShader); } /* ** SCR_DrawSmallChar ** small chars are drawn at native screen resolution */ -void SCR_DrawSmallChar( int x, int y, int ch ) { +void SCR_DrawSmallChar(int x, int y, int ch) { int row, col; float frow, fcol; float size; ch &= 255; - if ( ch == ' ' ) { + if (ch == ' ') { return; } - if ( y < -con.charHeight ) { + if (y < -con.charHeight) { return; } - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; float size2; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.03125; -// size = 0.0625; + // size = 0.0625; size2 = 0.0625; - re->DrawStretchPic( x * con.xadjust, y * con.yadjust, - con.charWidth * con.xadjust, con.charHeight * con.yadjust, - fcol, frow, - fcol + size, frow + size2, - cls.charSetShader ); + re->DrawStretchPic(x * con.xadjust, y * con.yadjust, con.charWidth * con.xadjust, con.charHeight * con.yadjust, fcol, frow, fcol + size, frow + size2, + cls.charSetShader); } - /* ================== SCR_DrawBigString[Color] @@ -172,65 +159,62 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -void SCR_DrawStringExt( int x, int y, float size, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape ) { - vec4_t color; - const char *s; - int xx; +void SCR_DrawStringExt(int x, int y, float size, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape) { + vec4_t color; + const char *s; + int xx; // draw the drop shadow color[0] = color[1] = color[2] = 0; color[3] = setColor[3]; - re->SetColor( color ); + re->SetColor(color); s = string; xx = x; - while ( *s ) { - if ( !noColorEscape && Q_IsColorString( s ) ) { + while (*s) { + if (!noColorEscape && Q_IsColorString(s)) { s += 2; continue; } - SCR_DrawChar( xx+2, y+2, size, *s ); + SCR_DrawChar(xx + 2, y + 2, size, *s); xx += size; s++; } - // draw the colored text s = string; xx = x; - re->SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - Com_Memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + re->SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + Com_Memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - re->SetColor( color ); + re->SetColor(color); } - if ( !noColorEscape ) { + if (!noColorEscape) { s += 2; continue; } } - SCR_DrawChar( xx, y, size, *s ); + SCR_DrawChar(xx, y, size, *s); xx += size; s++; } - re->SetColor( NULL ); + re->SetColor(NULL); } - -void SCR_DrawBigString( int x, int y, const char *s, float alpha, qboolean noColorEscape ) { - float color[4]; +void SCR_DrawBigString(int x, int y, const char *s, float alpha, qboolean noColorEscape) { + float color[4]; color[0] = color[1] = color[2] = 1.0; color[3] = alpha; - SCR_DrawStringExt( x, y, BIGCHAR_WIDTH, s, color, qfalse, noColorEscape ); + SCR_DrawStringExt(x, y, BIGCHAR_WIDTH, s, color, qfalse, noColorEscape); } -void SCR_DrawBigStringColor( int x, int y, const char *s, vec4_t color, qboolean noColorEscape ) { - SCR_DrawStringExt( x, y, BIGCHAR_WIDTH, s, color, qtrue, noColorEscape ); +void SCR_DrawBigStringColor(int x, int y, const char *s, vec4_t color, qboolean noColorEscape) { + SCR_DrawStringExt(x, y, BIGCHAR_WIDTH, s, color, qtrue, noColorEscape); } - /* ================== SCR_DrawSmallString[Color] @@ -241,45 +225,43 @@ to a fixed color. Coordinates are at 640 by 480 virtual resolution ================== */ -void SCR_DrawSmallStringExt( int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape ) { - vec4_t color; - const char *s; - int xx; +void SCR_DrawSmallStringExt(int x, int y, const char *string, float *setColor, qboolean forceColor, qboolean noColorEscape) { + vec4_t color; + const char *s; + int xx; // draw the colored text s = string; xx = x; - re->SetColor( setColor ); - while ( *s ) { - if ( Q_IsColorString( s ) ) { - if ( !forceColor ) { - Com_Memcpy( color, g_color_table[ColorIndex(*(s+1))], sizeof( color ) ); + re->SetColor(setColor); + while (*s) { + if (Q_IsColorString(s)) { + if (!forceColor) { + Com_Memcpy(color, g_color_table[ColorIndex(*(s + 1))], sizeof(color)); color[3] = setColor[3]; - re->SetColor( color ); + re->SetColor(color); } - if ( !noColorEscape ) { + if (!noColorEscape) { s += 2; continue; } } - SCR_DrawSmallChar( xx, y, *s ); + SCR_DrawSmallChar(xx, y, *s); xx += con.charWidth; s++; } - re->SetColor( NULL ); + re->SetColor(NULL); } - - /* ** SCR_Strlen -- skips color escape codes */ -static int SCR_Strlen( const char *str ) { +static int SCR_Strlen(const char *str) { const char *s = str; int count = 0; - while ( *s ) { - if ( Q_IsColorString( s ) ) { + while (*s) { + if (Q_IsColorString(s)) { s += 2; } else { count++; @@ -293,10 +275,7 @@ static int SCR_Strlen( const char *str ) { /* ** SCR_GetBigStringWidth */ -int SCR_GetBigStringWidth( const char *str ) { - return SCR_Strlen( str ) * BIGCHAR_WIDTH; -} - +int SCR_GetBigStringWidth(const char *str) { return SCR_Strlen(str) * BIGCHAR_WIDTH; } //=============================================================================== @@ -305,26 +284,25 @@ int SCR_GetBigStringWidth( const char *str ) { SCR_DrawDemoRecording ================= */ -void SCR_DrawDemoRecording( void ) { - char string[1024]; - int pos; +void SCR_DrawDemoRecording(void) { + char string[1024]; + int pos; - if ( !clc.demorecording ) { + if (!clc.demorecording) { return; } - if ( clc.spDemoRecording ) { + if (clc.spDemoRecording) { return; } if (!cl_drawRecording->integer) { return; } - pos = FS_FTell( clc.demofile ); - Com_sprintf( string, sizeof(string), "RECORDING %s: %ik", clc.demoName, pos / 1024 ); + pos = FS_FTell(clc.demofile); + Com_sprintf(string, sizeof(string), "RECORDING %s: %ik", clc.demoName, pos / 1024); - SCR_DrawStringExt( 320 - strlen( string ) * 4, 20, 8, string, g_color_table[7], qtrue, qfalse ); + SCR_DrawStringExt(320 - strlen(string) * 4, 20, 8, string, g_color_table[7], qtrue, qfalse); } - /* =============================================================================== @@ -334,22 +312,21 @@ DEBUG GRAPH */ typedef struct graphsamp_s { - float value; - int color; + float value; + int color; } graphsamp_t; -static int current; -static graphsamp_t values[1024]; +static int current; +static graphsamp_t values[1024]; /* ============== SCR_DebugGraph ============== */ -void SCR_DebugGraph (float value, int color) -{ - values[current&1023].value = value; - values[current&1023].color = color; +void SCR_DebugGraph(float value, int color) { + values[current & 1023].value = value; + values[current & 1023].color = color; current++; } @@ -358,10 +335,9 @@ void SCR_DebugGraph (float value, int color) SCR_DrawDebugGraph ============== */ -void SCR_DrawDebugGraph (void) -{ - int a, x, y, w, i, h; - float v; +void SCR_DrawDebugGraph(void) { + int a, x, y, w, i, h; + float v; // // draw the graph @@ -369,21 +345,19 @@ void SCR_DrawDebugGraph (void) w = 640; x = 0; y = 480; - re->SetColor( g_color_table[0] ); - re->DrawStretchPic(x, y - cl_graphheight->integer, - w, cl_graphheight->integer, 0, 0, 0, 0, cls.whiteShader ); - re->SetColor( NULL ); - - for (a=0 ; aSetColor(g_color_table[0]); + re->DrawStretchPic(x, y - cl_graphheight->integer, w, cl_graphheight->integer, 0, 0, 0, 0, cls.whiteShader); + re->SetColor(NULL); + + for (a = 0; a < w; a++) { + i = (current - 1 - a + 1024) & 1023; v = values[i].value; v = v * cl_graphscale->integer + cl_graphshift->integer; if (v < 0) - v += cl_graphheight->integer * (1+(int)(-v / cl_graphheight->integer)); + v += cl_graphheight->integer * (1 + (int)(-v / cl_graphheight->integer)); h = (int)v % cl_graphheight->integer; - re->DrawStretchPic( x+w-1-a, y - h, 1, h, 0, 0, 0, 0, cls.whiteShader ); + re->DrawStretchPic(x + w - 1 - a, y - h, 1, h, 0, 0, 0, 0, cls.whiteShader); } } @@ -394,17 +368,16 @@ void SCR_DrawDebugGraph (void) SCR_Init ================== */ -void SCR_Init( void ) { - cl_timegraph = Cvar_Get ("timegraph", "0", CVAR_CHEAT); - cl_debuggraph = Cvar_Get ("debuggraph", "0", CVAR_CHEAT); - cl_graphheight = Cvar_Get ("graphheight", "32", CVAR_CHEAT); - cl_graphscale = Cvar_Get ("graphscale", "1", CVAR_CHEAT); - cl_graphshift = Cvar_Get ("graphshift", "0", CVAR_CHEAT); +void SCR_Init(void) { + cl_timegraph = Cvar_Get("timegraph", "0", CVAR_CHEAT); + cl_debuggraph = Cvar_Get("debuggraph", "0", CVAR_CHEAT); + cl_graphheight = Cvar_Get("graphheight", "32", CVAR_CHEAT); + cl_graphscale = Cvar_Get("graphscale", "1", CVAR_CHEAT); + cl_graphshift = Cvar_Get("graphshift", "0", CVAR_CHEAT); scr_initialized = qtrue; } - //======================================================= /* @@ -414,24 +387,24 @@ SCR_DrawScreenField This will be called twice if rendering in stereo mode ================== */ -void SCR_DrawScreenField( stereoFrame_t stereoFrame ) { - re->BeginFrame( stereoFrame ); +void SCR_DrawScreenField(stereoFrame_t stereoFrame) { + re->BeginFrame(stereoFrame); qboolean uiFullscreen = (qboolean)(cls.uiStarted && UIVM_IsFullscreen()); - if ( !cls.uiStarted ) { + if (!cls.uiStarted) { Com_DPrintf("draw screen without UI loaded\n"); return; } // if the menu is going to cover the entire screen, we // don't need to render anything under it - //actually, yes you do, unless you want clients to cycle out their reliable - //commands from sitting in the menu. -rww - if ( (cls.uiStarted && !uiFullscreen) || (!(cls.framecount&7) && cls.state == CA_ACTIVE) ) { - switch( cls.state ) { + // actually, yes you do, unless you want clients to cycle out their reliable + // commands from sitting in the menu. -rww + if ((cls.uiStarted && !uiFullscreen) || (!(cls.framecount & 7) && cls.state == CA_ACTIVE)) { + switch (cls.state) { default: - Com_Error( ERR_FATAL, "SCR_DrawScreenField: bad cls.state" ); + Com_Error(ERR_FATAL, "SCR_DrawScreenField: bad cls.state"); break; case CA_CINEMATIC: SCR_DrawCinematic(); @@ -439,45 +412,45 @@ void SCR_DrawScreenField( stereoFrame_t stereoFrame ) { case CA_DISCONNECTED: // force menu up S_StopAllSounds(); - UIVM_SetActiveMenu( UIMENU_MAIN ); + UIVM_SetActiveMenu(UIMENU_MAIN); break; case CA_CONNECTING: case CA_CHALLENGING: case CA_CONNECTED: // connecting clients will only show the connection dialog // refresh to update the time - UIVM_Refresh( cls.realtime ); - UIVM_DrawConnectScreen( qfalse ); + UIVM_Refresh(cls.realtime); + UIVM_DrawConnectScreen(qfalse); break; case CA_LOADING: case CA_PRIMED: // draw the game information screen and loading progress - CL_CGameRendering( stereoFrame ); + CL_CGameRendering(stereoFrame); // also draw the connection information, so it doesn't // flash away too briefly on local or lan games // refresh to update the time - UIVM_Refresh( cls.realtime ); - UIVM_DrawConnectScreen( qtrue ); + UIVM_Refresh(cls.realtime); + UIVM_DrawConnectScreen(qtrue); break; case CA_ACTIVE: - CL_CGameRendering( stereoFrame ); + CL_CGameRendering(stereoFrame); SCR_DrawDemoRecording(); break; } } // the menu draws next - if ( Key_GetCatcher( ) & KEYCATCH_UI && cls.uiStarted ) { - UIVM_Refresh( cls.realtime ); + if (Key_GetCatcher() & KEYCATCH_UI && cls.uiStarted) { + UIVM_Refresh(cls.realtime); } // console draws next - Con_DrawConsole (); + Con_DrawConsole(); // debug graph can be drawn on top of anything - if ( cl_debuggraph->integer || cl_timegraph->integer || cl_debugMove->integer ) { - SCR_DrawDebugGraph (); + if (cl_debuggraph->integer || cl_timegraph->integer || cl_debugMove->integer) { + SCR_DrawDebugGraph(); } } @@ -489,34 +462,33 @@ This is called every frame, and can also be called explicitly to flush text to the screen. ================== */ -void SCR_UpdateScreen( void ) { - static int recursive; +void SCR_UpdateScreen(void) { + static int recursive; - if ( !scr_initialized ) { - return; // not initialized yet + if (!scr_initialized) { + return; // not initialized yet } - if ( ++recursive > 2 ) { - Com_Error( ERR_FATAL, "SCR_UpdateScreen: recursively called" ); + if (++recursive > 2) { + Com_Error(ERR_FATAL, "SCR_UpdateScreen: recursively called"); } recursive = 1; // If there is no VM, there are also no rendering commands issued. Stop the renderer in // that case. - if( cls.uiStarted || com_dedicated->integer ) - { + if (cls.uiStarted || com_dedicated->integer) { // if running in stereo, we need to draw the frame twice - if ( cls.glconfig.stereoEnabled ) { - SCR_DrawScreenField( STEREO_LEFT ); - SCR_DrawScreenField( STEREO_RIGHT ); + if (cls.glconfig.stereoEnabled) { + SCR_DrawScreenField(STEREO_LEFT); + SCR_DrawScreenField(STEREO_RIGHT); } else { - SCR_DrawScreenField( STEREO_CENTER ); + SCR_DrawScreenField(STEREO_CENTER); } - if ( com_speeds->integer ) { - re->EndFrame( &time_frontend, &time_backend ); + if (com_speeds->integer) { + re->EndFrame(&time_frontend, &time_backend); } else { - re->EndFrame( NULL, NULL ); + re->EndFrame(NULL, NULL); } } diff --git a/codemp/client/cl_ui.cpp b/codemp/client/cl_ui.cpp index 76feaffae7..cfbb9c8c9d 100644 --- a/codemp/client/cl_ui.cpp +++ b/codemp/client/cl_ui.cpp @@ -29,10 +29,10 @@ along with this program; if not, see . CL_ShutdownUI ==================== */ -void CL_ShutdownUI( void ) { - Key_SetCatcher( Key_GetCatcher( ) & ~KEYCATCH_UI ); +void CL_ShutdownUI(void) { + Key_SetCatcher(Key_GetCatcher() & ~KEYCATCH_UI); - if ( !cls.uiStarted ) + if (!cls.uiStarted) return; cls.uiStarted = qfalse; @@ -46,15 +46,15 @@ CL_InitUI ==================== */ -void CL_InitUI( void ) { +void CL_InitUI(void) { // load the dll CL_BindUI(); // init for this gamestate - //rww - changed to <= CA_ACTIVE, because that is the state when we did a vid_restart - //ingame (was just < CA_ACTIVE before, resulting in ingame menus getting wiped and - //not reloaded on vid restart from ingame menu) - UIVM_Init( (qboolean)(cls.state >= CA_AUTHORIZING && cls.state <= CA_ACTIVE) ); + // rww - changed to <= CA_ACTIVE, because that is the state when we did a vid_restart + // ingame (was just < CA_ACTIVE before, resulting in ingame menus getting wiped and + // not reloaded on vid restart from ingame menu) + UIVM_Init((qboolean)(cls.state >= CA_AUTHORIZING && cls.state <= CA_ACTIVE)); } /* @@ -64,9 +64,9 @@ UI_GameCommand See if the current console command is claimed by the ui ==================== */ -qboolean UI_GameCommand( void ) { - if ( !cls.uiStarted ) +qboolean UI_GameCommand(void) { + if (!cls.uiStarted) return qfalse; - return UIVM_ConsoleCommand( cls.realtime ); + return UIVM_ConsoleCommand(cls.realtime); } diff --git a/codemp/client/cl_uiapi.cpp b/codemp/client/cl_uiapi.cpp index 29cf09b06a..5f72f4d866 100644 --- a/codemp/client/cl_uiapi.cpp +++ b/codemp/client/cl_uiapi.cpp @@ -34,99 +34,99 @@ extern botlib_export_t *botlib_export; // ui interface static uiExport_t *uie; // ui export table -static vm_t *uivm; // ui vm, valid for legacy and new api +static vm_t *uivm; // ui vm, valid for legacy and new api // // ui vmMain calls // -void UIVM_Init( qboolean inGameLoad ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_INIT, inGameLoad ); +void UIVM_Init(qboolean inGameLoad) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_INIT, inGameLoad); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->Init( inGameLoad ); + uie->Init(inGameLoad); } -void UIVM_Shutdown( void ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_SHUTDOWN ); - VM_Call( uivm, UI_MENU_RESET ); +void UIVM_Shutdown(void) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_SHUTDOWN); + VM_Call(uivm, UI_MENU_RESET); return; } - VMSwap v( uivm ); + VMSwap v(uivm); uie->Shutdown(); uie->MenuReset(); } -void UIVM_KeyEvent( int key, qboolean down ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_KEY_EVENT, key, down ); +void UIVM_KeyEvent(int key, qboolean down) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_KEY_EVENT, key, down); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->KeyEvent( key, down ); + uie->KeyEvent(key, down); } -void UIVM_MouseEvent( int dx, int dy ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_MOUSE_EVENT, dx, dy ); +void UIVM_MouseEvent(int dx, int dy) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_MOUSE_EVENT, dx, dy); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->MouseEvent( dx, dy ); + uie->MouseEvent(dx, dy); } -void UIVM_Refresh( int realtime ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_REFRESH, realtime ); +void UIVM_Refresh(int realtime) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_REFRESH, realtime); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->Refresh( realtime ); + uie->Refresh(realtime); } -qboolean UIVM_IsFullscreen( void ) { - if ( uivm->isLegacy ) { - return (qboolean)VM_Call( uivm, UI_IS_FULLSCREEN ); +qboolean UIVM_IsFullscreen(void) { + if (uivm->isLegacy) { + return (qboolean)VM_Call(uivm, UI_IS_FULLSCREEN); } - VMSwap v( uivm ); + VMSwap v(uivm); return uie->IsFullscreen(); } -void UIVM_SetActiveMenu( uiMenuCommand_t menu ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_SET_ACTIVE_MENU, menu ); +void UIVM_SetActiveMenu(uiMenuCommand_t menu) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_SET_ACTIVE_MENU, menu); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->SetActiveMenu( menu ); + uie->SetActiveMenu(menu); } -qboolean UIVM_ConsoleCommand( int realTime ) { - if ( uivm->isLegacy ) { - return (qboolean)VM_Call( uivm, UI_CONSOLE_COMMAND, realTime ); +qboolean UIVM_ConsoleCommand(int realTime) { + if (uivm->isLegacy) { + return (qboolean)VM_Call(uivm, UI_CONSOLE_COMMAND, realTime); } - VMSwap v( uivm ); + VMSwap v(uivm); - return uie->ConsoleCommand( realTime ); + return uie->ConsoleCommand(realTime); } -void UIVM_DrawConnectScreen( qboolean overlay ) { - if ( uivm->isLegacy ) { - VM_Call( uivm, UI_DRAW_CONNECT_SCREEN, overlay ); +void UIVM_DrawConnectScreen(qboolean overlay) { + if (uivm->isLegacy) { + VM_Call(uivm, UI_DRAW_CONNECT_SCREEN, overlay); return; } - VMSwap v( uivm ); + VMSwap v(uivm); - uie->DrawConnectScreen( overlay ); + uie->DrawConnectScreen(overlay); } // @@ -136,363 +136,238 @@ void UIVM_DrawConnectScreen( qboolean overlay ) { // wrappers and such -static int CL_Milliseconds( void ) { - return Sys_Milliseconds(); -} +static int CL_Milliseconds(void) { return Sys_Milliseconds(); } -static void CL_Cvar_Get( const char *var_name, const char *value, uint32_t flags ) { - Cvar_Register( NULL, var_name, value, flags ); -} +static void CL_Cvar_Get(const char *var_name, const char *value, uint32_t flags) { Cvar_Register(NULL, var_name, value, flags); } -static void CL_GetClientState( uiClientState_t *state ) { +static void CL_GetClientState(uiClientState_t *state) { state->connectPacketCount = clc.connectPacketCount; state->connState = cls.state; - Q_strncpyz( state->servername, cls.servername, sizeof( state->servername ) ); - Q_strncpyz( state->updateInfoString, cls.updateInfoString, sizeof( state->updateInfoString ) ); - Q_strncpyz( state->messageString, clc.serverMessage, sizeof( state->messageString ) ); + Q_strncpyz(state->servername, cls.servername, sizeof(state->servername)); + Q_strncpyz(state->updateInfoString, cls.updateInfoString, sizeof(state->updateInfoString)); + Q_strncpyz(state->messageString, clc.serverMessage, sizeof(state->messageString)); state->clientNum = cl.snap.ps.clientNum; } -static void CL_GetGlconfig( glconfig_t *config ) { - *config = cls.glconfig; -} +static void CL_GetGlconfig(glconfig_t *config) { *config = cls.glconfig; } -static void GetClipboardData( char *buf, int buflen ) { - char *cbd, *c; +static void GetClipboardData(char *buf, int buflen) { + char *cbd, *c; c = cbd = Sys_GetClipboardData(); - if ( !cbd ) { + if (!cbd) { *buf = 0; return; } - for ( int i = 0, end = buflen - 1; *c && i < end; i++ ) - { - uint32_t utf32 = ConvertUTF8ToUTF32( c, &c ); - buf[i] = ConvertUTF32ToExpectedCharset( utf32 ); + for (int i = 0, end = buflen - 1; *c && i < end; i++) { + uint32_t utf32 = ConvertUTF8ToUTF32(c, &c); + buf[i] = ConvertUTF32ToExpectedCharset(utf32); } - Z_Free( cbd ); + Z_Free(cbd); } -static int GetConfigString(int index, char *buf, int size) -{ - int offset; +static int GetConfigString(int index, char *buf, int size) { + int offset; if (index < 0 || index >= MAX_CONFIGSTRINGS) return qfalse; offset = cl.gameState.stringOffsets[index]; if (!offset) { - if( size ) { + if (size) { buf[0] = 0; } return qfalse; } - Q_strncpyz( buf, cl.gameState.stringData+offset, size); + Q_strncpyz(buf, cl.gameState.stringData + offset, size); return qtrue; } -static void Key_GetBindingBuf( int keynum, char *buf, int buflen ) { - char *value; +static void Key_GetBindingBuf(int keynum, char *buf, int buflen) { + char *value; - value = Key_GetBinding( keynum ); - if ( value ) { - Q_strncpyz( buf, value, buflen ); - } - else { + value = Key_GetBinding(keynum); + if (value) { + Q_strncpyz(buf, value, buflen); + } else { *buf = 0; } } -static void Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) -{ - const char *psKeyName = Key_KeynumToString( keynum/*, qtrue */); +static void Key_KeynumToStringBuf(int keynum, char *buf, int buflen) { + const char *psKeyName = Key_KeynumToString(keynum /*, qtrue */); // see if there's a more friendly (or localised) name... // - const char *psKeyNameFriendly = SE_GetString( va("KEYNAMES_KEYNAME_%s",psKeyName) ); + const char *psKeyNameFriendly = SE_GetString(va("KEYNAMES_KEYNAME_%s", psKeyName)); - Q_strncpyz( buf, (psKeyNameFriendly && psKeyNameFriendly[0]) ? psKeyNameFriendly : psKeyName, buflen ); + Q_strncpyz(buf, (psKeyNameFriendly && psKeyNameFriendly[0]) ? psKeyNameFriendly : psKeyName, buflen); } -static void CL_SE_GetLanguageName( const int languageIndex, char *buffer ) { - Q_strncpyz( buffer, SE_GetLanguageName( languageIndex ), 128 ); -} +static void CL_SE_GetLanguageName(const int languageIndex, char *buffer) { Q_strncpyz(buffer, SE_GetLanguageName(languageIndex), 128); } -static qboolean CL_SE_GetStringTextString( const char *text, char *buffer, int bufferLength ) { - assert( text && buffer ); - Q_strncpyz( buffer, SE_GetString( text ), bufferLength ); +static qboolean CL_SE_GetStringTextString(const char *text, char *buffer, int bufferLength) { + assert(text && buffer); + Q_strncpyz(buffer, SE_GetString(text), bufferLength); return qtrue; } -static void CL_R_ShaderNameFromIndex( char *name, int index ) { - const char *retMem = re->ShaderNameFromIndex( index ); - if ( retMem ) - strcpy( name, retMem ); +static void CL_R_ShaderNameFromIndex(char *name, int index) { + const char *retMem = re->ShaderNameFromIndex(index); + if (retMem) + strcpy(name, retMem); else name[0] = '\0'; } -static void CL_G2API_ListModelSurfaces( void *ghlInfo ) { - if ( !ghlInfo ) { +static void CL_G2API_ListModelSurfaces(void *ghlInfo) { + if (!ghlInfo) { return; } - re->G2API_ListSurfaces( (CGhoul2Info *)ghlInfo ); + re->G2API_ListSurfaces((CGhoul2Info *)ghlInfo); } -static void CL_G2API_ListModelBones( void *ghlInfo, int frame ) { - if ( !ghlInfo ) { +static void CL_G2API_ListModelBones(void *ghlInfo, int frame) { + if (!ghlInfo) { return; } - re->G2API_ListBones( (CGhoul2Info *)ghlInfo, frame ); + re->G2API_ListBones((CGhoul2Info *)ghlInfo, frame); } -static void CL_G2API_SetGhoul2ModelIndexes( void *ghoul2, qhandle_t *modelList, qhandle_t *skinList ) { - if ( !ghoul2 ) { +static void CL_G2API_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + if (!ghoul2) { return; } - re->G2API_SetGhoul2ModelIndexes( *((CGhoul2Info_v *)ghoul2), modelList, skinList ); + re->G2API_SetGhoul2ModelIndexes(*((CGhoul2Info_v *)ghoul2), modelList, skinList); } -static qboolean CL_G2API_HaveWeGhoul2Models( void *ghoul2) { - if ( !ghoul2 ) { +static qboolean CL_G2API_HaveWeGhoul2Models(void *ghoul2) { + if (!ghoul2) { return qfalse; } - return re->G2API_HaveWeGhoul2Models( *((CGhoul2Info_v *)ghoul2) ); + return re->G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ghoul2)); } -static qboolean CL_G2API_GetBoltMatrix( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) { return qfalse; - } - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean CL_G2API_GetBoltMatrix_NoReconstruct( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) { return qfalse; } - re->G2API_BoltMatrixReconstruction( qfalse ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); + re->G2API_BoltMatrixReconstruction(qfalse); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean CL_G2API_GetBoltMatrix_NoRecNoRot( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) { return qfalse; } - re->G2API_BoltMatrixReconstruction( qfalse ); - re->G2API_BoltMatrixSPMethod( qtrue ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); + re->G2API_BoltMatrixReconstruction(qfalse); + re->G2API_BoltMatrixSPMethod(qtrue); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static int CL_G2API_InitGhoul2Model( void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias ) { - if ( !ghoul2Ptr ) { +static int CL_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { + if (!ghoul2Ptr) { return 0; } #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - return re->G2API_InitGhoul2Model( (CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias ); + return re->G2API_InitGhoul2Model((CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } -static qboolean CL_G2API_SetSkin( void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { + if (!ghoul2) { return qfalse; } CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_SetSkin( g2, modelIndex, customSkin, renderSkin ); + return re->G2API_SetSkin(g2, modelIndex, customSkin, renderSkin); } -static void CL_G2API_CollisionDetect( - CollisionRecord_t *collRecMap, - void* ghoul2, - const vec3_t angles, - const vec3_t position, - int frameNumber, - int entNum, - vec3_t rayStart, - vec3_t rayEnd, - vec3_t scale, - int traceFlags, - int useLod, - float fRadius ) -{ - if ( !ghoul2 ) { +static void CL_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) { return; } - re->G2API_CollisionDetect( - collRecMap, - *((CGhoul2Info_v *)ghoul2), - angles, - position, - frameNumber, - entNum, - rayStart, - rayEnd, - scale, - G2VertSpaceClient, - traceFlags, - useLod, - fRadius); + re->G2API_CollisionDetect(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, + traceFlags, useLod, fRadius); } -static void CL_G2API_CollisionDetectCache( - CollisionRecord_t *collRecMap, - void* ghoul2, - const vec3_t angles, - const vec3_t position, - int frameNumber, - int entNum, - vec3_t rayStart, - vec3_t rayEnd, - vec3_t scale, - int traceFlags, - int useLod, - float fRadius) -{ - if ( !ghoul2 ) { +static void CL_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) { return; } - re->G2API_CollisionDetectCache( - collRecMap, - *((CGhoul2Info_v *)ghoul2), - angles, - position, - frameNumber, - entNum, - rayStart, - rayEnd, - scale, - G2VertSpaceClient, - traceFlags, - useLod, - fRadius); + re->G2API_CollisionDetectCache(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceClient, + traceFlags, useLod, fRadius); } -static void CL_G2API_CleanGhoul2Models( void **ghoul2Ptr ) { - if ( !ghoul2Ptr ) { +static void CL_G2API_CleanGhoul2Models(void **ghoul2Ptr) { + if (!ghoul2Ptr) { return; } #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - re->G2API_CleanGhoul2Models( (CGhoul2Info_v **)ghoul2Ptr ); + re->G2API_CleanGhoul2Models((CGhoul2Info_v **)ghoul2Ptr); } -static qboolean CL_G2API_SetBoneAngles( - void *ghoul2, - int modelIndex, - const char *boneName, - const vec3_t angles, - const int flags, - const int up, - const int right, - const int forward, - qhandle_t *modelList, - int blendTime , - int currentTime) -{ - if ( !ghoul2 ) { +static qboolean CL_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetBoneAngles( - *((CGhoul2Info_v *)ghoul2), - modelIndex, - boneName, - angles, - flags, - (const Eorientations)up, - (const Eorientations)right, - (const Eorientations)forward, - modelList, - blendTime, - currentTime); + return re->G2API_SetBoneAngles(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, angles, flags, (const Eorientations)up, (const Eorientations)right, + (const Eorientations)forward, modelList, blendTime, currentTime); } -static qboolean CL_G2API_SetBoneAnim( - void *ghoul2, - const int modelIndex, - const char *boneName, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime) -{ - if ( !ghoul2 ) { +static qboolean CL_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetBoneAnim( - *((CGhoul2Info_v *)ghoul2), - modelIndex, - boneName, - startFrame, - endFrame, - flags, - animSpeed, - currentTime, - setFrame, - blendTime); + return re->G2API_SetBoneAnim(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } -static qboolean CL_G2API_GetBoneAnim( - void *ghoul2, - const char *boneName, - const int currentTime, - float *currentFrame, - int *startFrame, - int *endFrame, - int *flags, - float *animSpeed, - int *modelList, - const int modelIndex) -{ - if ( !ghoul2 ) { +static qboolean CL_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { + if (!ghoul2) { return qfalse; } CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_GetBoneAnim( - g2, - modelIndex, - boneName, - currentTime, - currentFrame, - startFrame, - endFrame, - flags, - animSpeed, - modelList); + return re->G2API_GetBoneAnim(g2, modelIndex, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList); } -static qboolean CL_G2API_GetBoneFrame( - void *ghoul2, - const char *boneName, - const int currentTime, - float *currentFrame, - int *modelList, - const int modelIndex) -{ - if ( !ghoul2 ) { +static qboolean CL_G2API_GetBoneFrame(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *modelList, const int modelIndex) { + if (!ghoul2) { return qfalse; } @@ -500,144 +375,129 @@ static qboolean CL_G2API_GetBoneFrame( int iDontCare1 = 0, iDontCare2 = 0, iDontCare3 = 0; float fDontCare1 = 0; - return re->G2API_GetBoneAnim( - g2, - modelIndex, - boneName, - currentTime, - currentFrame, - &iDontCare1, - &iDontCare2, - &iDontCare3, - &fDontCare1, - modelList); + return re->G2API_GetBoneAnim(g2, modelIndex, boneName, currentTime, currentFrame, &iDontCare1, &iDontCare2, &iDontCare3, &fDontCare1, modelList); } -static void CL_G2API_GetGLAName( void *ghoul2, int modelIndex, char *fillBuf ) { - if ( !ghoul2 ) - { +static void CL_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { + if (!ghoul2) { fillBuf[0] = '\0'; return; } - char *tmp = re->G2API_GetGLAName( *((CGhoul2Info_v *)ghoul2), modelIndex ); - if ( tmp ) - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetGLAName(*((CGhoul2Info_v *)ghoul2), modelIndex); + if (tmp) + strcpy(fillBuf, tmp); else fillBuf[0] = '\0'; } -static int CL_G2API_CopyGhoul2Instance( void *g2From, void *g2To, int modelIndex ) { - if ( !g2From || !g2To ) { +static int CL_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { + if (!g2From || !g2To) { return 0; } - return re->G2API_CopyGhoul2Instance( *((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex ); + return re->G2API_CopyGhoul2Instance(*((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex); } -static void CL_G2API_CopySpecificGhoul2Model( void *g2From, int modelFrom, void *g2To, int modelTo ) { - if ( !g2From || !g2To ) { +static void CL_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { + if (!g2From || !g2To) { return; } - re->G2API_CopySpecificG2Model( *((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo ); + re->G2API_CopySpecificG2Model(*((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo); } -static void CL_G2API_DuplicateGhoul2Instance( void *g2From, void **g2To ) { - if ( !g2From || !g2To ) { +static void CL_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { + if (!g2From || !g2To) { return; } #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - re->G2API_DuplicateGhoul2Instance( *((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To ); + re->G2API_DuplicateGhoul2Instance(*((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To); } -static qboolean CL_G2API_HasGhoul2ModelOnIndex( void *ghlInfo, int modelIndex ) { - if ( !ghlInfo ) { +static qboolean CL_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { + if (!ghlInfo) { return qfalse; } - return re->G2API_HasGhoul2ModelOnIndex( (CGhoul2Info_v **)ghlInfo, modelIndex ); + return re->G2API_HasGhoul2ModelOnIndex((CGhoul2Info_v **)ghlInfo, modelIndex); } -static qboolean CL_G2API_RemoveGhoul2Model( void *ghlInfo, int modelIndex ) { - if ( !ghlInfo ) { +static qboolean CL_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { + if (!ghlInfo) { return qfalse; } #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 0; + g_G2AllocServer = 0; #endif - return re->G2API_RemoveGhoul2Model( (CGhoul2Info_v **)ghlInfo, modelIndex ); + return re->G2API_RemoveGhoul2Model((CGhoul2Info_v **)ghlInfo, modelIndex); } -static int CL_G2API_AddBolt( void *ghoul2, int modelIndex, const char *boneName ) { - if ( !ghoul2 ) { +static int CL_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { + if (!ghoul2) { return -1; } - return re->G2API_AddBolt( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName ); + return re->G2API_AddBolt(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName); } -static void CL_G2API_SetBoltInfo( void *ghoul2, int modelIndex, int boltInfo ) { - if ( !ghoul2 ) { +static void CL_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { + if (!ghoul2) { return; } - re->G2API_SetBoltInfo( *((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo ); + re->G2API_SetBoltInfo(*((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo); } -static qboolean CL_G2API_SetRootSurface( void *ghoul2, const int modelIndex, const char *surfaceName ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const char *surfaceName) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetRootSurface( *((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName ); + return re->G2API_SetRootSurface(*((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName); } -static qboolean CL_G2API_SetSurfaceOnOff( void *ghoul2, const char *surfaceName, const int flags ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetSurfaceOnOff( *((CGhoul2Info_v *)ghoul2), surfaceName, flags ); + return re->G2API_SetSurfaceOnOff(*((CGhoul2Info_v *)ghoul2), surfaceName, flags); } -static qboolean CL_G2API_SetNewOrigin( void *ghoul2, const int boltIndex ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetNewOrigin( *((CGhoul2Info_v *)ghoul2), boltIndex ); + return re->G2API_SetNewOrigin(*((CGhoul2Info_v *)ghoul2), boltIndex); } -static int CL_G2API_GetTime( void ) { - return re->G2API_GetTime( 0 ); -} +static int CL_G2API_GetTime(void) { return re->G2API_GetTime(0); } -static void CL_G2API_SetTime( int time, int clock ) { - re->G2API_SetTime( time, clock ); -} +static void CL_G2API_SetTime(int time, int clock) { re->G2API_SetTime(time, clock); } -static void CL_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { - if ( !ghoul2 ) { +static void CL_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { + if (!ghoul2) { return; } CRagDollParams rdParams; - if ( !params ) { - re->G2API_ResetRagDoll( *((CGhoul2Info_v *)ghoul2) ); + if (!params) { + re->G2API_ResetRagDoll(*((CGhoul2Info_v *)ghoul2)); return; } - VectorCopy( params->angles, rdParams.angles ); - VectorCopy( params->position, rdParams.position ); - VectorCopy( params->scale, rdParams.scale ); - VectorCopy( params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset ); - VectorCopy( params->pelvisPositionOffset, rdParams.pelvisPositionOffset ); + VectorCopy(params->angles, rdParams.angles); + VectorCopy(params->position, rdParams.position); + VectorCopy(params->scale, rdParams.scale); + VectorCopy(params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset); + VectorCopy(params->pelvisPositionOffset, rdParams.pelvisPositionOffset); rdParams.fImpactStrength = params->fImpactStrength; rdParams.fShotStrength = params->fShotStrength; @@ -652,58 +512,58 @@ static void CL_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { rdParams.RagPhase = (CRagDollParams::ERagPhase)params->RagPhase; rdParams.effectorsToTurnOff = (CRagDollParams::ERagEffector)params->effectorsToTurnOff; - re->G2API_SetRagDoll( *((CGhoul2Info_v *)ghoul2), &rdParams ); + re->G2API_SetRagDoll(*((CGhoul2Info_v *)ghoul2), &rdParams); } -static void CL_G2API_AnimateG2Models( void *ghoul2, int time, sharedRagDollUpdateParams_t *params ) { - if ( !ghoul2 ) { +static void CL_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { + if (!ghoul2) { return; } CRagDollUpdateParams rduParams; - if ( !params ) + if (!params) return; - VectorCopy( params->angles, rduParams.angles ); - VectorCopy( params->position, rduParams.position ); - VectorCopy( params->scale, rduParams.scale ); - VectorCopy( params->velocity, rduParams.velocity ); + VectorCopy(params->angles, rduParams.angles); + VectorCopy(params->position, rduParams.position); + VectorCopy(params->scale, rduParams.scale); + VectorCopy(params->velocity, rduParams.velocity); rduParams.me = params->me; rduParams.settleFrame = params->settleFrame; - re->G2API_AnimateG2ModelsRag( *((CGhoul2Info_v *)ghoul2), time, &rduParams ); + re->G2API_AnimateG2ModelsRag(*((CGhoul2Info_v *)ghoul2), time, &rduParams); } -static qboolean CL_G2API_SetBoneIKState( void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + if (!ghoul2) { return qfalse; } - return re->G2API_SetBoneIKState( *((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params ); + return re->G2API_SetBoneIKState(*((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params); } -static qboolean CL_G2API_IKMove( void *ghoul2, int time, sharedIKMoveParams_t *params ) { - if ( !ghoul2 ) { +static qboolean CL_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { + if (!ghoul2) { return qfalse; } - return re->G2API_IKMove( *((CGhoul2Info_v *)ghoul2), time, params ); + return re->G2API_IKMove(*((CGhoul2Info_v *)ghoul2), time, params); } -static void CL_G2API_GetSurfaceName( void *ghoul2, int surfNumber, int modelIndex, char *fillBuf ) { - if ( !ghoul2 ) { +static void CL_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { + if (!ghoul2) { return; } CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - char *tmp = re->G2API_GetSurfaceName( g2, modelIndex, surfNumber ); - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetSurfaceName(g2, modelIndex, surfNumber); + strcpy(fillBuf, tmp); } -static qboolean CL_G2API_AttachG2Model( void *ghoul2From, int modelIndexFrom, void *ghoul2To, int toBoltIndex, int toModel ) { - if ( !ghoul2From || !ghoul2To ) { +static qboolean CL_G2API_AttachG2Model(void *ghoul2From, int modelIndexFrom, void *ghoul2To, int toBoltIndex, int toModel) { + if (!ghoul2From || !ghoul2To) { return qfalse; } @@ -713,75 +573,67 @@ static qboolean CL_G2API_AttachG2Model( void *ghoul2From, int modelIndexFrom, vo return re->G2API_AttachG2Model(*g2From, modelIndexFrom, *g2To, toBoltIndex, toModel); } -static void CL_Key_SetCatcher( int catcher ) { +static void CL_Key_SetCatcher(int catcher) { // Don't allow the ui module to close the console - Key_SetCatcher( catcher | ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ); + Key_SetCatcher(catcher | (Key_GetCatcher() & KEYCATCH_CONSOLE)); } -static void UIVM_Cvar_Set( const char *var_name, const char *value ) { - Cvar_VM_Set( var_name, value, VM_UI ); -} +static void UIVM_Cvar_Set(const char *var_name, const char *value) { Cvar_VM_Set(var_name, value, VM_UI); } -static void UIVM_Cvar_SetValue( const char *var_name, float value ) { - Cvar_VM_SetValue( var_name, value, VM_UI ); -} +static void UIVM_Cvar_SetValue(const char *var_name, float value) { Cvar_VM_SetValue(var_name, value, VM_UI); } -static void CL_AddUICommand( const char *cmdName ) { - Cmd_AddCommand( cmdName, NULL ); -} +static void CL_AddUICommand(const char *cmdName) { Cmd_AddCommand(cmdName, NULL); } -static void UIVM_Cmd_RemoveCommand( const char *cmd_name ) { - Cmd_VM_RemoveCommand( cmd_name, VM_UI ); -} +static void UIVM_Cmd_RemoveCommand(const char *cmd_name) { Cmd_VM_RemoveCommand(cmd_name, VM_UI); } // legacy syscall -intptr_t CL_UISystemCalls( intptr_t *args ) { - switch ( args[0] ) { - //rww - alright, DO NOT EVER add a GAME/CGAME/UI generic call without adding a trap to match, and - //all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also - //all be in the same order, and start at 100. +intptr_t CL_UISystemCalls(intptr_t *args) { + switch (args[0]) { + // rww - alright, DO NOT EVER add a GAME/CGAME/UI generic call without adding a trap to match, and + // all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also + // all be in the same order, and start at 100. case TRAP_MEMSET: - Com_Memset( VMA(1), args[2], args[3] ); + Com_Memset(VMA(1), args[2], args[3]); return 0; case TRAP_MEMCPY: - Com_Memcpy( VMA(1), VMA(2), args[3] ); + Com_Memcpy(VMA(1), VMA(2), args[3]); return 0; case TRAP_STRNCPY: - strncpy( (char *)VMA(1), (const char *)VMA(2), args[3] ); + strncpy((char *)VMA(1), (const char *)VMA(2), args[3]); return args[1]; case TRAP_SIN: - return FloatAsInt( sin( VMF(1) ) ); + return FloatAsInt(sin(VMF(1))); case TRAP_COS: - return FloatAsInt( cos( VMF(1) ) ); + return FloatAsInt(cos(VMF(1))); case TRAP_ATAN2: - return FloatAsInt( atan2( VMF(1), VMF(2) ) ); + return FloatAsInt(atan2(VMF(1), VMF(2))); case TRAP_SQRT: - return FloatAsInt( sqrt( VMF(1) ) ); + return FloatAsInt(sqrt(VMF(1))); case TRAP_MATRIXMULTIPLY: - MatrixMultiply( (vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3) ); + MatrixMultiply((vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3)); return 0; case TRAP_ANGLEVECTORS: - AngleVectors( (const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4) ); + AngleVectors((const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4)); return 0; case TRAP_PERPENDICULARVECTOR: - PerpendicularVector( (float *)VMA(1), (const float *)VMA(2) ); + PerpendicularVector((float *)VMA(1), (const float *)VMA(2)); return 0; case TRAP_FLOOR: - return FloatAsInt( floor( VMF(1) ) ); + return FloatAsInt(floor(VMF(1))); case TRAP_CEIL: - return FloatAsInt( ceil( VMF(1) ) ); + return FloatAsInt(ceil(VMF(1))); case TRAP_TESTPRINTINT: return 0; @@ -790,97 +642,97 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case TRAP_ACOS: - return FloatAsInt( Q_acos( VMF(1) ) ); + return FloatAsInt(Q_acos(VMF(1))); case TRAP_ASIN: - return FloatAsInt( Q_asin( VMF(1) ) ); + return FloatAsInt(Q_asin(VMF(1))); case UI_ERROR: - Com_Error( ERR_DROP, "%s", VMA(1) ); + Com_Error(ERR_DROP, "%s", VMA(1)); return 0; case UI_PRINT: - Com_Printf( "%s", VMA(1) ); + Com_Printf("%s", VMA(1)); return 0; case UI_MILLISECONDS: return Sys_Milliseconds(); case UI_CVAR_REGISTER: - Cvar_Register( (vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4] ); + Cvar_Register((vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4]); return 0; case UI_CVAR_UPDATE: - Cvar_Update( (vmCvar_t *)VMA(1) ); + Cvar_Update((vmCvar_t *)VMA(1)); return 0; case UI_CVAR_SET: - Cvar_VM_Set( (const char *)VMA(1), (const char *)VMA(2), VM_UI ); + Cvar_VM_Set((const char *)VMA(1), (const char *)VMA(2), VM_UI); return 0; case UI_CVAR_VARIABLEVALUE: - return FloatAsInt( Cvar_VariableValue( (const char *)VMA(1) ) ); + return FloatAsInt(Cvar_VariableValue((const char *)VMA(1))); case UI_CVAR_VARIABLESTRINGBUFFER: - Cvar_VariableStringBuffer( (const char *)VMA(1), (char *)VMA(2), args[3] ); + Cvar_VariableStringBuffer((const char *)VMA(1), (char *)VMA(2), args[3]); return 0; case UI_CVAR_SETVALUE: - Cvar_VM_SetValue( (const char *)VMA(1), VMF(2), VM_UI ); + Cvar_VM_SetValue((const char *)VMA(1), VMF(2), VM_UI); return 0; case UI_CVAR_RESET: - Cvar_Reset( (const char *)VMA(1) ); + Cvar_Reset((const char *)VMA(1)); return 0; case UI_CVAR_CREATE: - Cvar_Get( (const char *)VMA(1), (const char *)VMA(2), args[3] ); + Cvar_Get((const char *)VMA(1), (const char *)VMA(2), args[3]); return 0; case UI_CVAR_INFOSTRINGBUFFER: - Cvar_InfoStringBuffer( args[1], (char *)VMA(2), args[3] ); + Cvar_InfoStringBuffer(args[1], (char *)VMA(2), args[3]); return 0; case UI_ARGC: return Cmd_Argc(); case UI_ARGV: - Cmd_ArgvBuffer( args[1], (char *)VMA(2), args[3] ); + Cmd_ArgvBuffer(args[1], (char *)VMA(2), args[3]); return 0; case UI_CMD_EXECUTETEXT: - Cbuf_ExecuteText( args[1], (const char *)VMA(2) ); + Cbuf_ExecuteText(args[1], (const char *)VMA(2)); return 0; case UI_FS_FOPENFILE: - return FS_FOpenFileByMode( (const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3] ); + return FS_FOpenFileByMode((const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3]); case UI_FS_READ: - FS_Read( VMA(1), args[2], args[3] ); + FS_Read(VMA(1), args[2], args[3]); return 0; case UI_FS_WRITE: - FS_Write( VMA(1), args[2], args[3] ); + FS_Write(VMA(1), args[2], args[3]); return 0; case UI_FS_FCLOSEFILE: - FS_FCloseFile( args[1] ); + FS_FCloseFile(args[1]); return 0; case UI_FS_GETFILELIST: - return FS_GetFileList( (const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4] ); + return FS_GetFileList((const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4]); case UI_R_REGISTERMODEL: - return re->RegisterModel( (const char *)VMA(1) ); + return re->RegisterModel((const char *)VMA(1)); case UI_R_REGISTERSKIN: - return re->RegisterSkin( (const char *)VMA(1) ); + return re->RegisterSkin((const char *)VMA(1)); case UI_R_REGISTERSHADERNOMIP: - return re->RegisterShaderNoMip( (const char *)VMA(1) ); + return re->RegisterShaderNoMip((const char *)VMA(1)); case UI_R_SHADERNAMEFROMINDEX: - CL_R_ShaderNameFromIndex( (char *)VMA(1), args[2] ); + CL_R_ShaderNameFromIndex((char *)VMA(1), args[2]); return 0; case UI_R_CLEARSCENE: @@ -888,31 +740,31 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case UI_R_ADDREFENTITYTOSCENE: - re->AddRefEntityToScene( (const refEntity_t *)VMA(1) ); + re->AddRefEntityToScene((const refEntity_t *)VMA(1)); return 0; case UI_R_ADDPOLYTOSCENE: - re->AddPolyToScene( args[1], args[2], (const polyVert_t *)VMA(3), 1 ); + re->AddPolyToScene(args[1], args[2], (const polyVert_t *)VMA(3), 1); return 0; case UI_R_ADDLIGHTTOSCENE: - re->AddLightToScene( (const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5) ); + re->AddLightToScene((const float *)VMA(1), VMF(2), VMF(3), VMF(4), VMF(5)); return 0; case UI_R_RENDERSCENE: - re->RenderScene( (const refdef_t *)VMA(1) ); + re->RenderScene((const refdef_t *)VMA(1)); return 0; case UI_R_SETCOLOR: - re->SetColor( (const float *)VMA(1) ); + re->SetColor((const float *)VMA(1)); return 0; case UI_R_DRAWSTRETCHPIC: - re->DrawStretchPic( VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9] ); + re->DrawStretchPic(VMF(1), VMF(2), VMF(3), VMF(4), VMF(5), VMF(6), VMF(7), VMF(8), args[9]); return 0; case UI_R_MODELBOUNDS: - re->ModelBounds( args[1], (float *)VMA(2), (float *)VMA(3) ); + re->ModelBounds(args[1], (float *)VMA(2), (float *)VMA(3)); return 0; case UI_UPDATESCREEN: @@ -920,36 +772,36 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case UI_CM_LERPTAG: - re->LerpTag( (orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6) ); + re->LerpTag((orientation_t *)VMA(1), args[2], args[3], args[4], VMF(5), (const char *)VMA(6)); return 0; case UI_S_REGISTERSOUND: - return S_RegisterSound( (const char *)VMA(1) ); + return S_RegisterSound((const char *)VMA(1)); case UI_S_STARTLOCALSOUND: - S_StartLocalSound( args[1], args[2] ); + S_StartLocalSound(args[1], args[2]); return 0; case UI_KEY_KEYNUMTOSTRINGBUF: - Key_KeynumToStringBuf( args[1], (char *)VMA(2), args[3] ); + Key_KeynumToStringBuf(args[1], (char *)VMA(2), args[3]); return 0; case UI_KEY_GETBINDINGBUF: - Key_GetBindingBuf( args[1], (char *)VMA(2), args[3] ); + Key_GetBindingBuf(args[1], (char *)VMA(2), args[3]); return 0; case UI_KEY_SETBINDING: - Key_SetBinding( args[1], (const char *)VMA(2) ); + Key_SetBinding(args[1], (const char *)VMA(2)); return 0; case UI_KEY_ISDOWN: - return Key_IsDown( args[1] ); + return Key_IsDown(args[1]); case UI_KEY_GETOVERSTRIKEMODE: return Key_GetOverstrikeMode(); case UI_KEY_SETOVERSTRIKEMODE: - Key_SetOverstrikeMode( (qboolean)args[1] ); + Key_SetOverstrikeMode((qboolean)args[1]); return 0; case UI_KEY_CLEARSTATES: @@ -960,23 +812,23 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return Key_GetCatcher(); case UI_KEY_SETCATCHER: - CL_Key_SetCatcher( args[1] ); + CL_Key_SetCatcher(args[1]); return 0; case UI_GETCLIPBOARDDATA: - GetClipboardData( (char *)VMA(1), args[2] ); + GetClipboardData((char *)VMA(1), args[2]); return 0; case UI_GETCLIENTSTATE: - CL_GetClientState( (uiClientState_t *)VMA(1) ); + CL_GetClientState((uiClientState_t *)VMA(1)); return 0; case UI_GETGLCONFIG: - CL_GetGlconfig( (glconfig_t *)VMA(1) ); + CL_GetGlconfig((glconfig_t *)VMA(1)); return 0; case UI_GETCONFIGSTRING: - return GetConfigString( args[1], (char *)VMA(2), args[3] ); + return GetConfigString(args[1], (char *)VMA(2), args[3]); case UI_LAN_LOADCACHEDSERVERS: LAN_LoadCachedServers(); @@ -997,68 +849,68 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return LAN_GetPingQueueCount(); case UI_LAN_CLEARPING: - LAN_ClearPing( args[1] ); + LAN_ClearPing(args[1]); return 0; case UI_LAN_GETPING: - LAN_GetPing( args[1], (char *)VMA(2), args[3], (int *)VMA(4) ); + LAN_GetPing(args[1], (char *)VMA(2), args[3], (int *)VMA(4)); return 0; case UI_LAN_GETPINGINFO: - LAN_GetPingInfo( args[1], (char *)VMA(2), args[3] ); + LAN_GetPingInfo(args[1], (char *)VMA(2), args[3]); return 0; case UI_LAN_GETSERVERCOUNT: return LAN_GetServerCount(args[1]); case UI_LAN_GETSERVERADDRESSSTRING: - LAN_GetServerAddressString( args[1], args[2], (char *)VMA(3), args[4] ); + LAN_GetServerAddressString(args[1], args[2], (char *)VMA(3), args[4]); return 0; case UI_LAN_GETSERVERINFO: - LAN_GetServerInfo( args[1], args[2], (char *)VMA(3), args[4] ); + LAN_GetServerInfo(args[1], args[2], (char *)VMA(3), args[4]); return 0; case UI_LAN_GETSERVERPING: - return LAN_GetServerPing( args[1], args[2] ); + return LAN_GetServerPing(args[1], args[2]); case UI_LAN_MARKSERVERVISIBLE: - LAN_MarkServerVisible( args[1], args[2], (qboolean)args[3] ); + LAN_MarkServerVisible(args[1], args[2], (qboolean)args[3]); return 0; case UI_LAN_SERVERISVISIBLE: - return LAN_ServerIsVisible( args[1], args[2] ); + return LAN_ServerIsVisible(args[1], args[2]); case UI_LAN_UPDATEVISIBLEPINGS: - return LAN_UpdateVisiblePings( args[1] ); + return LAN_UpdateVisiblePings(args[1]); case UI_LAN_RESETPINGS: - LAN_ResetPings( args[1] ); + LAN_ResetPings(args[1]); return 0; case UI_LAN_SERVERSTATUS: - return LAN_GetServerStatus( (char *)VMA(1), (char *)VMA(2), args[3] ); + return LAN_GetServerStatus((char *)VMA(1), (char *)VMA(2), args[3]); case UI_LAN_COMPARESERVERS: - return LAN_CompareServers( args[1], args[2], args[3], args[4], args[5] ); + return LAN_CompareServers(args[1], args[2], args[3], args[4], args[5]); case UI_MEMORY_REMAINING: return Hunk_MemoryRemaining(); case UI_R_REGISTERFONT: - return re->RegisterFont( (const char *)VMA(1) ); + return re->RegisterFont((const char *)VMA(1)); case UI_R_FONT_STRLENPIXELS: - return re->Font_StrLenPixels( (const char *)VMA(1), args[2], VMF(3) ); + return re->Font_StrLenPixels((const char *)VMA(1), args[2], VMF(3)); case UI_R_FONT_STRLENCHARS: - return re->Font_StrLenChars( (const char *)VMA(1) ); + return re->Font_StrLenChars((const char *)VMA(1)); case UI_R_FONT_STRHEIGHTPIXELS: - return re->Font_HeightPixels( args[1], VMF(2) ); + return re->Font_HeightPixels(args[1], VMF(2)); case UI_R_FONT_DRAWSTRING: - re->Font_DrawString( args[1], args[2], (const char *)VMA(3), (const float *) VMA(4), args[5], args[6], VMF(7) ); + re->Font_DrawString(args[1], args[2], (const char *)VMA(3), (const float *)VMA(4), args[5], args[6], VMF(7)); return 0; case UI_LANGUAGE_ISASIAN: @@ -1068,28 +920,28 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return re->Language_UsesSpaces(); case UI_ANYLANGUAGE_READCHARFROMSTRING: - return re->AnyLanguage_ReadCharFromString( (const char *)VMA(1), (int *) VMA(2), (qboolean *) VMA(3) ); + return re->AnyLanguage_ReadCharFromString((const char *)VMA(1), (int *)VMA(2), (qboolean *)VMA(3)); case UI_PC_ADD_GLOBAL_DEFINE: - return botlib_export->PC_AddGlobalDefine( (char *)VMA(1) ); + return botlib_export->PC_AddGlobalDefine((char *)VMA(1)); case UI_PC_LOAD_SOURCE: - return botlib_export->PC_LoadSourceHandle( (const char *)VMA(1) ); + return botlib_export->PC_LoadSourceHandle((const char *)VMA(1)); case UI_PC_FREE_SOURCE: - return botlib_export->PC_FreeSourceHandle( args[1] ); + return botlib_export->PC_FreeSourceHandle(args[1]); case UI_PC_READ_TOKEN: - return botlib_export->PC_ReadTokenHandle( args[1], (struct pc_token_s *)VMA(2) ); + return botlib_export->PC_ReadTokenHandle(args[1], (struct pc_token_s *)VMA(2)); case UI_PC_SOURCE_FILE_AND_LINE: - return botlib_export->PC_SourceFileAndLine( args[1], (char *)VMA(2), (int *)VMA(3) ); + return botlib_export->PC_SourceFileAndLine(args[1], (char *)VMA(2), (int *)VMA(3)); case UI_PC_LOAD_GLOBAL_DEFINES: - return botlib_export->PC_LoadGlobalDefines ( (char *)VMA(1) ); + return botlib_export->PC_LoadGlobalDefines((char *)VMA(1)); case UI_PC_REMOVE_ALL_GLOBAL_DEFINES: - botlib_export->PC_RemoveAllGlobalDefines ( ); + botlib_export->PC_RemoveAllGlobalDefines(); return 0; case UI_S_STOPBACKGROUNDTRACK: @@ -1097,11 +949,11 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case UI_S_STARTBACKGROUNDTRACK: - S_StartBackgroundTrack( (const char *)VMA(1), (const char *)VMA(2), qfalse ); + S_StartBackgroundTrack((const char *)VMA(1), (const char *)VMA(2), qfalse); return 0; case UI_REAL_TIME: - return Com_RealTime( (struct qtime_s *)VMA(1) ); + return Com_RealTime((struct qtime_s *)VMA(1)); case UI_CIN_PLAYCINEMATIC: Com_DPrintf("UI_CIN_PlayCinematic\n"); @@ -1122,55 +974,59 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case UI_R_REMAP_SHADER: - re->RemapShader( (const char *)VMA(1), (const char *)VMA(2), (const char *)VMA(3) ); + re->RemapShader((const char *)VMA(1), (const char *)VMA(2), (const char *)VMA(3)); return 0; case UI_SP_GETNUMLANGUAGES: return SE_GetNumLanguages(); case UI_SP_GETLANGUAGENAME: - CL_SE_GetLanguageName( args[1], (char *)VMA(2) ); + CL_SE_GetLanguageName(args[1], (char *)VMA(2)); return 0; case UI_SP_GETSTRINGTEXTSTRING: - return CL_SE_GetStringTextString( (const char *)VMA(1), (char *)VMA(2), args[3] ); + return CL_SE_GetStringTextString((const char *)VMA(1), (char *)VMA(2), args[3]); case UI_G2_LISTSURFACES: - CL_G2API_ListModelSurfaces( VMA(1) ); + CL_G2API_ListModelSurfaces(VMA(1)); return 0; case UI_G2_LISTBONES: - CL_G2API_ListModelBones( VMA(1), args[2]); + CL_G2API_ListModelBones(VMA(1), args[2]); return 0; case UI_G2_HAVEWEGHOULMODELS: - return CL_G2API_HaveWeGhoul2Models( VMA(1) ); + return CL_G2API_HaveWeGhoul2Models(VMA(1)); case UI_G2_SETMODELS: - CL_G2API_SetGhoul2ModelIndexes( VMA(1),(qhandle_t *)VMA(2),(qhandle_t *)VMA(3)); + CL_G2API_SetGhoul2ModelIndexes(VMA(1), (qhandle_t *)VMA(2), (qhandle_t *)VMA(3)); return 0; case UI_G2_GETBOLT: - return CL_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case UI_G2_GETBOLT_NOREC: - return CL_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case UI_G2_GETBOLT_NOREC_NOROT: - return CL_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return CL_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case UI_G2_INITGHOUL2MODEL: #ifdef _FULL_G2_LEAK_CHECKING g_G2AllocServer = 0; #endif - return CL_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t) args[4], (qhandle_t) args[5], args[6], args[7]); + return CL_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t)args[4], (qhandle_t)args[5], args[6], args[7]); case UI_G2_COLLISIONDETECT: case UI_G2_COLLISIONDETECTCACHE: - return 0; //not supported for ui + return 0; // not supported for ui case UI_G2_ANGLEOVERRIDE: - return CL_G2API_SetBoneAngles(VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], (const Eorientations) args[6], (const Eorientations) args[7], (const Eorientations) args[8], (qhandle_t *)VMA(9), args[10], args[11] ); + return CL_G2API_SetBoneAngles(VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], (const Eorientations)args[6], + (const Eorientations)args[7], (const Eorientations)args[8], (qhandle_t *)VMA(9), args[10], args[11]); case UI_G2_CLEANMODELS: #ifdef _FULL_G2_LEAK_CHECKING @@ -1183,13 +1039,14 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return CL_G2API_SetBoneAnim(VMA(1), args[2], (const char *)VMA(3), args[4], args[5], args[6], VMF(7), args[8], VMF(9), args[10]); case UI_G2_GETBONEANIM: - return CL_G2API_GetBoneAnim(VMA(1), (const char*)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), (int *)VMA(9), args[10]); + return CL_G2API_GetBoneAnim(VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), + (int *)VMA(9), args[10]); case UI_G2_GETBONEFRAME: - return CL_G2API_GetBoneFrame(VMA(1), (const char*)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), args[6]); + return CL_G2API_GetBoneFrame(VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), args[6]); case UI_G2_GETGLANAME: - CL_G2API_GetGLAName( VMA(1), args[2], (char *)VMA(3) ); + CL_G2API_GetGLAName(VMA(1), args[2], (char *)VMA(3)); return 0; case UI_G2_COPYGHOUL2INSTANCE: @@ -1239,11 +1096,11 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return 0; case UI_G2_SETRAGDOLL: - return 0; //not supported for ui + return 0; // not supported for ui break; case UI_G2_ANIMATEG2MODELS: - return 0; //not supported for ui + return 0; // not supported for ui break; case UI_G2_SETBONEIKSTATE: @@ -1253,7 +1110,7 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return CL_G2API_IKMove(VMA(1), args[2], (sharedIKMoveParams_t *)VMA(3)); case UI_G2_GETSURFACENAME: - CL_G2API_GetSurfaceName( (void *)args[1], args[2], args[3], (char *)VMA( 4 ) ); + CL_G2API_GetSurfaceName((void *)args[1], args[2], args[3], (char *)VMA(4)); return 0; case UI_G2_SETSKIN: @@ -1263,177 +1120,176 @@ intptr_t CL_UISystemCalls( intptr_t *args ) { return CL_G2API_AttachG2Model(VMA(1), args[2], VMA(3), args[4], args[5]); default: - Com_Error( ERR_DROP, "Bad UI system trap: %ld", (long int) args[0] ); - + Com_Error(ERR_DROP, "Bad UI system trap: %ld", (long int)args[0]); } return 0; } -void CL_BindUI( void ) { +void CL_BindUI(void) { static uiImport_t uii; - uiExport_t *ret; - GetUIAPI_t GetUIAPI; - char dllName[MAX_OSPATH] = "ui" ARCH_STRING DLL_EXT; - - memset( &uii, 0, sizeof( uii ) ); - - uivm = VM_Create( VM_UI ); - if ( uivm && !uivm->isLegacy ) { - uii.Print = Com_Printf; - uii.Error = Com_Error; - uii.Milliseconds = CL_Milliseconds; - uii.RealTime = Com_RealTime; - uii.MemoryRemaining = Hunk_MemoryRemaining; - - uii.Cvar_Create = CL_Cvar_Get; - uii.Cvar_InfoStringBuffer = Cvar_InfoStringBuffer; - uii.Cvar_Register = Cvar_Register; - uii.Cvar_Reset = Cvar_Reset; - uii.Cvar_Set = UIVM_Cvar_Set; - uii.Cvar_SetValue = UIVM_Cvar_SetValue; - uii.Cvar_Update = Cvar_Update; - uii.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; - uii.Cvar_VariableValue = Cvar_VariableValue; - - uii.Cmd_Argc = Cmd_Argc; - uii.Cmd_Argv = Cmd_ArgvBuffer; - uii.Cmd_ExecuteText = Cbuf_ExecuteText; - - uii.FS_Close = FS_FCloseFile; - uii.FS_GetFileList = FS_GetFileList; - uii.FS_Open = FS_FOpenFileByMode; - uii.FS_Read = FS_Read; - uii.FS_Write = FS_Write; - - uii.GetClientState = CL_GetClientState; - uii.GetClipboardData = GetClipboardData; - uii.GetConfigString = GetConfigString; - uii.GetGlconfig = CL_GetGlconfig; - uii.UpdateScreen = SCR_UpdateScreen; - - uii.Key_ClearStates = Key_ClearStates; - uii.Key_GetBindingBuf = Key_GetBindingBuf; - uii.Key_IsDown = Key_IsDown; - uii.Key_KeynumToStringBuf = Key_KeynumToStringBuf; - uii.Key_SetBinding = Key_SetBinding; - uii.Key_GetCatcher = Key_GetCatcher; - uii.Key_GetOverstrikeMode = Key_GetOverstrikeMode; - uii.Key_SetCatcher = CL_Key_SetCatcher; - uii.Key_SetOverstrikeMode = Key_SetOverstrikeMode; - - uii.PC_AddGlobalDefine = botlib_export->PC_AddGlobalDefine; - uii.PC_FreeSource = botlib_export->PC_FreeSourceHandle; - uii.PC_LoadGlobalDefines = botlib_export->PC_LoadGlobalDefines; - uii.PC_LoadSource = botlib_export->PC_LoadSourceHandle; - uii.PC_ReadToken = botlib_export->PC_ReadTokenHandle; - uii.PC_RemoveAllGlobalDefines = botlib_export->PC_RemoveAllGlobalDefines; - uii.PC_SourceFileAndLine = botlib_export->PC_SourceFileAndLine; - - uii.CIN_DrawCinematic = CIN_DrawCinematic; - uii.CIN_PlayCinematic = CIN_PlayCinematic; - uii.CIN_RunCinematic = CIN_RunCinematic; - uii.CIN_SetExtents = CIN_SetExtents; - uii.CIN_StopCinematic = CIN_StopCinematic; - - uii.LAN_AddServer = LAN_AddServer; - uii.LAN_ClearPing = LAN_ClearPing; - uii.LAN_CompareServers = LAN_CompareServers; - uii.LAN_GetPing = LAN_GetPing; - uii.LAN_GetPingInfo = LAN_GetPingInfo; - uii.LAN_GetPingQueueCount = LAN_GetPingQueueCount; - uii.LAN_GetServerAddressString = LAN_GetServerAddressString; - uii.LAN_GetServerCount = LAN_GetServerCount; - uii.LAN_GetServerInfo = LAN_GetServerInfo; - uii.LAN_GetServerPing = LAN_GetServerPing; - uii.LAN_LoadCachedServers = LAN_LoadCachedServers; - uii.LAN_MarkServerVisible = LAN_MarkServerVisible; - uii.LAN_RemoveServer = LAN_RemoveServer; - uii.LAN_ResetPings = LAN_ResetPings; - uii.LAN_SaveCachedServers = LAN_SaveServersToCache; - uii.LAN_ServerIsVisible = LAN_ServerIsVisible; - uii.LAN_ServerStatus = LAN_GetServerStatus; - uii.LAN_UpdateVisiblePings = LAN_UpdateVisiblePings; - - uii.S_StartBackgroundTrack = S_StartBackgroundTrack; - uii.S_StartLocalSound = S_StartLocalSound; - uii.S_StopBackgroundTrack = S_StopBackgroundTrack; - uii.S_RegisterSound = S_RegisterSound; - - uii.SE_GetLanguageName = CL_SE_GetLanguageName; - uii.SE_GetNumLanguages = SE_GetNumLanguages; - uii.SE_GetStringTextString = CL_SE_GetStringTextString; - - uii.R_Language_IsAsian = re->Language_IsAsian; - uii.R_Language_UsesSpaces = re->Language_UsesSpaces; - uii.R_AnyLanguage_ReadCharFromString = re->AnyLanguage_ReadCharFromString; - - uii.R_AddLightToScene = re->AddLightToScene; - uii.R_AddPolysToScene = re->AddPolyToScene; - uii.R_AddRefEntityToScene = re->AddRefEntityToScene; - uii.R_ClearScene = re->ClearScene; - uii.R_DrawStretchPic = re->DrawStretchPic; - uii.R_Font_DrawString = re->Font_DrawString; - uii.R_Font_HeightPixels = re->Font_HeightPixels; - uii.R_Font_StrLenChars = re->Font_StrLenChars; - uii.R_Font_StrLenPixels = re->Font_StrLenPixels; - uii.R_LerpTag = re->LerpTag; - uii.R_ModelBounds = re->ModelBounds; - uii.R_RegisterFont = re->RegisterFont; - uii.R_RegisterModel = re->RegisterModel; - uii.R_RegisterShaderNoMip = re->RegisterShaderNoMip; - uii.R_RegisterSkin = re->RegisterSkin; - uii.R_RemapShader = re->RemapShader; - uii.R_RenderScene = re->RenderScene; - uii.R_SetColor = re->SetColor; - uii.R_ShaderNameFromIndex = CL_R_ShaderNameFromIndex; - - uii.G2_ListModelSurfaces = CL_G2API_ListModelSurfaces; - uii.G2_ListModelBones = CL_G2API_ListModelBones; - uii.G2_SetGhoul2ModelIndexes = CL_G2API_SetGhoul2ModelIndexes; - uii.G2_HaveWeGhoul2Models = CL_G2API_HaveWeGhoul2Models; - uii.G2API_GetBoltMatrix = CL_G2API_GetBoltMatrix; - uii.G2API_GetBoltMatrix_NoReconstruct = CL_G2API_GetBoltMatrix_NoReconstruct; - uii.G2API_GetBoltMatrix_NoRecNoRot = CL_G2API_GetBoltMatrix_NoRecNoRot; - uii.G2API_InitGhoul2Model = CL_G2API_InitGhoul2Model; - uii.G2API_SetSkin = CL_G2API_SetSkin; - uii.G2API_CollisionDetect = CL_G2API_CollisionDetect; - uii.G2API_CollisionDetectCache = CL_G2API_CollisionDetectCache; - uii.G2API_CleanGhoul2Models = CL_G2API_CleanGhoul2Models; - uii.G2API_SetBoneAngles = CL_G2API_SetBoneAngles; - uii.G2API_SetBoneAnim = CL_G2API_SetBoneAnim; - uii.G2API_GetBoneAnim = CL_G2API_GetBoneAnim; - uii.G2API_GetBoneFrame = CL_G2API_GetBoneFrame; - uii.G2API_GetGLAName = CL_G2API_GetGLAName; - uii.G2API_CopyGhoul2Instance = CL_G2API_CopyGhoul2Instance; - uii.G2API_CopySpecificGhoul2Model = CL_G2API_CopySpecificGhoul2Model; - uii.G2API_DuplicateGhoul2Instance = CL_G2API_DuplicateGhoul2Instance; - uii.G2API_HasGhoul2ModelOnIndex = CL_G2API_HasGhoul2ModelOnIndex; - uii.G2API_RemoveGhoul2Model = CL_G2API_RemoveGhoul2Model; - uii.G2API_AddBolt = CL_G2API_AddBolt; - uii.G2API_SetBoltInfo = CL_G2API_SetBoltInfo; - uii.G2API_SetRootSurface = CL_G2API_SetRootSurface; - uii.G2API_SetSurfaceOnOff = CL_G2API_SetSurfaceOnOff; - uii.G2API_SetNewOrigin = CL_G2API_SetNewOrigin; - uii.G2API_GetTime = CL_G2API_GetTime; - uii.G2API_SetTime = CL_G2API_SetTime; - uii.G2API_SetRagDoll = CL_G2API_SetRagDoll; - uii.G2API_AnimateG2Models = CL_G2API_AnimateG2Models; - uii.G2API_SetBoneIKState = CL_G2API_SetBoneIKState; - uii.G2API_IKMove = CL_G2API_IKMove; - uii.G2API_GetSurfaceName = CL_G2API_GetSurfaceName; - uii.G2API_AttachG2Model = CL_G2API_AttachG2Model; - - uii.ext.R_Font_StrLenPixels = re->ext.Font_StrLenPixels; - uii.ext.AddCommand = CL_AddUICommand; - uii.ext.RemoveCommand = UIVM_Cmd_RemoveCommand; + uiExport_t *ret; + GetUIAPI_t GetUIAPI; + char dllName[MAX_OSPATH] = "ui" ARCH_STRING DLL_EXT; + + memset(&uii, 0, sizeof(uii)); + + uivm = VM_Create(VM_UI); + if (uivm && !uivm->isLegacy) { + uii.Print = Com_Printf; + uii.Error = Com_Error; + uii.Milliseconds = CL_Milliseconds; + uii.RealTime = Com_RealTime; + uii.MemoryRemaining = Hunk_MemoryRemaining; + + uii.Cvar_Create = CL_Cvar_Get; + uii.Cvar_InfoStringBuffer = Cvar_InfoStringBuffer; + uii.Cvar_Register = Cvar_Register; + uii.Cvar_Reset = Cvar_Reset; + uii.Cvar_Set = UIVM_Cvar_Set; + uii.Cvar_SetValue = UIVM_Cvar_SetValue; + uii.Cvar_Update = Cvar_Update; + uii.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; + uii.Cvar_VariableValue = Cvar_VariableValue; + + uii.Cmd_Argc = Cmd_Argc; + uii.Cmd_Argv = Cmd_ArgvBuffer; + uii.Cmd_ExecuteText = Cbuf_ExecuteText; + + uii.FS_Close = FS_FCloseFile; + uii.FS_GetFileList = FS_GetFileList; + uii.FS_Open = FS_FOpenFileByMode; + uii.FS_Read = FS_Read; + uii.FS_Write = FS_Write; + + uii.GetClientState = CL_GetClientState; + uii.GetClipboardData = GetClipboardData; + uii.GetConfigString = GetConfigString; + uii.GetGlconfig = CL_GetGlconfig; + uii.UpdateScreen = SCR_UpdateScreen; + + uii.Key_ClearStates = Key_ClearStates; + uii.Key_GetBindingBuf = Key_GetBindingBuf; + uii.Key_IsDown = Key_IsDown; + uii.Key_KeynumToStringBuf = Key_KeynumToStringBuf; + uii.Key_SetBinding = Key_SetBinding; + uii.Key_GetCatcher = Key_GetCatcher; + uii.Key_GetOverstrikeMode = Key_GetOverstrikeMode; + uii.Key_SetCatcher = CL_Key_SetCatcher; + uii.Key_SetOverstrikeMode = Key_SetOverstrikeMode; + + uii.PC_AddGlobalDefine = botlib_export->PC_AddGlobalDefine; + uii.PC_FreeSource = botlib_export->PC_FreeSourceHandle; + uii.PC_LoadGlobalDefines = botlib_export->PC_LoadGlobalDefines; + uii.PC_LoadSource = botlib_export->PC_LoadSourceHandle; + uii.PC_ReadToken = botlib_export->PC_ReadTokenHandle; + uii.PC_RemoveAllGlobalDefines = botlib_export->PC_RemoveAllGlobalDefines; + uii.PC_SourceFileAndLine = botlib_export->PC_SourceFileAndLine; + + uii.CIN_DrawCinematic = CIN_DrawCinematic; + uii.CIN_PlayCinematic = CIN_PlayCinematic; + uii.CIN_RunCinematic = CIN_RunCinematic; + uii.CIN_SetExtents = CIN_SetExtents; + uii.CIN_StopCinematic = CIN_StopCinematic; + + uii.LAN_AddServer = LAN_AddServer; + uii.LAN_ClearPing = LAN_ClearPing; + uii.LAN_CompareServers = LAN_CompareServers; + uii.LAN_GetPing = LAN_GetPing; + uii.LAN_GetPingInfo = LAN_GetPingInfo; + uii.LAN_GetPingQueueCount = LAN_GetPingQueueCount; + uii.LAN_GetServerAddressString = LAN_GetServerAddressString; + uii.LAN_GetServerCount = LAN_GetServerCount; + uii.LAN_GetServerInfo = LAN_GetServerInfo; + uii.LAN_GetServerPing = LAN_GetServerPing; + uii.LAN_LoadCachedServers = LAN_LoadCachedServers; + uii.LAN_MarkServerVisible = LAN_MarkServerVisible; + uii.LAN_RemoveServer = LAN_RemoveServer; + uii.LAN_ResetPings = LAN_ResetPings; + uii.LAN_SaveCachedServers = LAN_SaveServersToCache; + uii.LAN_ServerIsVisible = LAN_ServerIsVisible; + uii.LAN_ServerStatus = LAN_GetServerStatus; + uii.LAN_UpdateVisiblePings = LAN_UpdateVisiblePings; + + uii.S_StartBackgroundTrack = S_StartBackgroundTrack; + uii.S_StartLocalSound = S_StartLocalSound; + uii.S_StopBackgroundTrack = S_StopBackgroundTrack; + uii.S_RegisterSound = S_RegisterSound; + + uii.SE_GetLanguageName = CL_SE_GetLanguageName; + uii.SE_GetNumLanguages = SE_GetNumLanguages; + uii.SE_GetStringTextString = CL_SE_GetStringTextString; + + uii.R_Language_IsAsian = re->Language_IsAsian; + uii.R_Language_UsesSpaces = re->Language_UsesSpaces; + uii.R_AnyLanguage_ReadCharFromString = re->AnyLanguage_ReadCharFromString; + + uii.R_AddLightToScene = re->AddLightToScene; + uii.R_AddPolysToScene = re->AddPolyToScene; + uii.R_AddRefEntityToScene = re->AddRefEntityToScene; + uii.R_ClearScene = re->ClearScene; + uii.R_DrawStretchPic = re->DrawStretchPic; + uii.R_Font_DrawString = re->Font_DrawString; + uii.R_Font_HeightPixels = re->Font_HeightPixels; + uii.R_Font_StrLenChars = re->Font_StrLenChars; + uii.R_Font_StrLenPixels = re->Font_StrLenPixels; + uii.R_LerpTag = re->LerpTag; + uii.R_ModelBounds = re->ModelBounds; + uii.R_RegisterFont = re->RegisterFont; + uii.R_RegisterModel = re->RegisterModel; + uii.R_RegisterShaderNoMip = re->RegisterShaderNoMip; + uii.R_RegisterSkin = re->RegisterSkin; + uii.R_RemapShader = re->RemapShader; + uii.R_RenderScene = re->RenderScene; + uii.R_SetColor = re->SetColor; + uii.R_ShaderNameFromIndex = CL_R_ShaderNameFromIndex; + + uii.G2_ListModelSurfaces = CL_G2API_ListModelSurfaces; + uii.G2_ListModelBones = CL_G2API_ListModelBones; + uii.G2_SetGhoul2ModelIndexes = CL_G2API_SetGhoul2ModelIndexes; + uii.G2_HaveWeGhoul2Models = CL_G2API_HaveWeGhoul2Models; + uii.G2API_GetBoltMatrix = CL_G2API_GetBoltMatrix; + uii.G2API_GetBoltMatrix_NoReconstruct = CL_G2API_GetBoltMatrix_NoReconstruct; + uii.G2API_GetBoltMatrix_NoRecNoRot = CL_G2API_GetBoltMatrix_NoRecNoRot; + uii.G2API_InitGhoul2Model = CL_G2API_InitGhoul2Model; + uii.G2API_SetSkin = CL_G2API_SetSkin; + uii.G2API_CollisionDetect = CL_G2API_CollisionDetect; + uii.G2API_CollisionDetectCache = CL_G2API_CollisionDetectCache; + uii.G2API_CleanGhoul2Models = CL_G2API_CleanGhoul2Models; + uii.G2API_SetBoneAngles = CL_G2API_SetBoneAngles; + uii.G2API_SetBoneAnim = CL_G2API_SetBoneAnim; + uii.G2API_GetBoneAnim = CL_G2API_GetBoneAnim; + uii.G2API_GetBoneFrame = CL_G2API_GetBoneFrame; + uii.G2API_GetGLAName = CL_G2API_GetGLAName; + uii.G2API_CopyGhoul2Instance = CL_G2API_CopyGhoul2Instance; + uii.G2API_CopySpecificGhoul2Model = CL_G2API_CopySpecificGhoul2Model; + uii.G2API_DuplicateGhoul2Instance = CL_G2API_DuplicateGhoul2Instance; + uii.G2API_HasGhoul2ModelOnIndex = CL_G2API_HasGhoul2ModelOnIndex; + uii.G2API_RemoveGhoul2Model = CL_G2API_RemoveGhoul2Model; + uii.G2API_AddBolt = CL_G2API_AddBolt; + uii.G2API_SetBoltInfo = CL_G2API_SetBoltInfo; + uii.G2API_SetRootSurface = CL_G2API_SetRootSurface; + uii.G2API_SetSurfaceOnOff = CL_G2API_SetSurfaceOnOff; + uii.G2API_SetNewOrigin = CL_G2API_SetNewOrigin; + uii.G2API_GetTime = CL_G2API_GetTime; + uii.G2API_SetTime = CL_G2API_SetTime; + uii.G2API_SetRagDoll = CL_G2API_SetRagDoll; + uii.G2API_AnimateG2Models = CL_G2API_AnimateG2Models; + uii.G2API_SetBoneIKState = CL_G2API_SetBoneIKState; + uii.G2API_IKMove = CL_G2API_IKMove; + uii.G2API_GetSurfaceName = CL_G2API_GetSurfaceName; + uii.G2API_AttachG2Model = CL_G2API_AttachG2Model; + + uii.ext.R_Font_StrLenPixels = re->ext.Font_StrLenPixels; + uii.ext.AddCommand = CL_AddUICommand; + uii.ext.RemoveCommand = UIVM_Cmd_RemoveCommand; GetUIAPI = (GetUIAPI_t)uivm->GetModuleAPI; - ret = GetUIAPI( UI_API_VERSION, &uii ); - if ( !ret ) { - //free VM? + ret = GetUIAPI(UI_API_VERSION, &uii); + if (!ret) { + // free VM? cls.uiStarted = qfalse; - Com_Error( ERR_FATAL, "GetGameAPI failed on %s", dllName ); + Com_Error(ERR_FATAL, "GetGameAPI failed on %s", dllName); } uie = ret; @@ -1441,15 +1297,15 @@ void CL_BindUI( void ) { } // fall back to legacy syscall/vm_call api - uivm = VM_CreateLegacy( VM_UI, CL_UISystemCalls ); - if ( !uivm ) { + uivm = VM_CreateLegacy(VM_UI, CL_UISystemCalls); + if (!uivm) { cls.uiStarted = qfalse; - Com_Error( ERR_DROP, "VM_CreateLegacy on ui failed" ); + Com_Error(ERR_DROP, "VM_CreateLegacy on ui failed"); } } -void CL_UnbindUI( void ) { +void CL_UnbindUI(void) { UIVM_Shutdown(); - VM_Free( uivm ); + VM_Free(uivm); uivm = NULL; } diff --git a/codemp/client/snd_ambient.cpp b/codemp/client/snd_ambient.cpp index 0b187088c9..68630c12dd 100644 --- a/codemp/client/snd_ambient.cpp +++ b/codemp/client/snd_ambient.cpp @@ -26,77 +26,62 @@ along with this program; if not, see . #include "snd_ambient.h" #include "snd_local.h" -static const int MAX_SET_VOLUME = 255; +static const int MAX_SET_VOLUME = 255; -static void AS_GetGeneralSet( ambientSet_t & ); -static void AS_GetLocalSet( ambientSet_t & ); -static void AS_GetBModelSet( ambientSet_t & ); +static void AS_GetGeneralSet(ambientSet_t &); +static void AS_GetLocalSet(ambientSet_t &); +static void AS_GetBModelSet(ambientSet_t &); -//Current set and old set for crossfading -static int currentSet = -1; -static int oldSet = -1; -static int crossDelay = 1000; //1 second +// Current set and old set for crossfading +static int currentSet = -1; +static int oldSet = -1; +static int crossDelay = 1000; // 1 second static int currentSetTime = 0; static int oldSetTime = 0; // Globals for debug purposes -static int numSets = 0; +static int numSets = 0; // Main ambient sound group -static CSetGroup* aSets = NULL; +static CSetGroup *aSets = NULL; // Globals for speed, blech -static char *parseBuffer = NULL; -static int parseSize = 0; -static int parsePos = 0; -static char tempBuffer[1024]; +static char *parseBuffer = NULL; +static int parseSize = 0; +static int parsePos = 0; +static char tempBuffer[1024]; -//NOTENOTE: Be sure to change the mirrored code in g_spawn.cpp, and cg_main.cpp -typedef std::map namePrecache_m; -static namePrecache_m* pMap = NULL; +// NOTENOTE: Be sure to change the mirrored code in g_spawn.cpp, and cg_main.cpp +typedef std::map namePrecache_m; +static namePrecache_m *pMap = NULL; // Used for enum / string matching -static const char *setNames[NUM_AS_SETS] = - { - "generalSet", - "localSet", - "bmodelSet", - }; +static const char *setNames[NUM_AS_SETS] = { + "generalSet", + "localSet", + "bmodelSet", +}; // Used for enum / function matching -static const parseFunc_t parseFuncs[NUM_AS_SETS] = - { - AS_GetGeneralSet, - AS_GetLocalSet, - AS_GetBModelSet, - }; +static const parseFunc_t parseFuncs[NUM_AS_SETS] = { + AS_GetGeneralSet, + AS_GetLocalSet, + AS_GetBModelSet, +}; // Used for keyword / enum matching -static const char *keywordNames[NUM_AS_KEYWORDS]= - { - "timeBetweenWaves", - "subWaves", - "loopedWave", - "volRange", - "radius", - "type", - "amsdir", - "outdir", - "basedir", - }; - - -CSetGroup::CSetGroup(void) -{ - m_ambientSets = new std::vector; - m_setMap = new std::map; +static const char *keywordNames[NUM_AS_KEYWORDS] = { + "timeBetweenWaves", "subWaves", "loopedWave", "volRange", "radius", "type", "amsdir", "outdir", "basedir", +}; + +CSetGroup::CSetGroup(void) { + m_ambientSets = new std::vector; + m_setMap = new std::map; m_numSets = 0; } - -CSetGroup::~CSetGroup(void) -{ +CSetGroup::~CSetGroup(void) { delete m_ambientSets; delete m_setMap; } @@ -107,20 +92,18 @@ Free ------------------------- */ -void CSetGroup::Free( void ) -{ - std::vector < ambientSet_t * >::iterator ai; +void CSetGroup::Free(void) { + std::vector::iterator ai; - for ( ai = m_ambientSets->begin(); ai != m_ambientSets->end(); ++ai ) - { - Z_Free ( (*ai) ); + for (ai = m_ambientSets->begin(); ai != m_ambientSets->end(); ++ai) { + Z_Free((*ai)); } - //Do this in place of clear() so it *really* frees the memory. + // Do this in place of clear() so it *really* frees the memory. delete m_ambientSets; delete m_setMap; - m_ambientSets = new std::vector; - m_setMap = new std::map; + m_ambientSets = new std::vector; + m_setMap = new std::map; m_numSets = 0; } @@ -131,29 +114,28 @@ AddSet ------------------------- */ -ambientSet_t *CSetGroup::AddSet( const char *name ) -{ - ambientSet_t *set; +ambientSet_t *CSetGroup::AddSet(const char *name) { + ambientSet_t *set; - //Allocate the memory - set = (ambientSet_t *) Z_Malloc( sizeof( ambientSet_t ), TAG_AMBIENTSET, qtrue); + // Allocate the memory + set = (ambientSet_t *)Z_Malloc(sizeof(ambientSet_t), TAG_AMBIENTSET, qtrue); - //Set up some defaults - Q_strncpyz(set->name,name,sizeof(set->name)); + // Set up some defaults + Q_strncpyz(set->name, name, sizeof(set->name)); set->loopedVolume = MAX_SET_VOLUME; set->masterVolume = MAX_SET_VOLUME; set->radius = 250; set->time_start = 10; - set->time_end = 25; + set->time_end = 25; set->volRange_start = MAX_SET_VOLUME; - set->volRange_end = MAX_SET_VOLUME; + set->volRange_end = MAX_SET_VOLUME; - m_ambientSets->insert( m_ambientSets->end(), set ); + m_ambientSets->insert(m_ambientSets->end(), set); set->id = m_numSets++; - //Map the name to the pointer for reference later + // Map the name to the pointer for reference later (*m_setMap)[name] = set; return set; @@ -165,36 +147,33 @@ GetSet ------------------------- */ -ambientSet_t *CSetGroup::GetSet( const char *name ) -{ - std::map < sstring_t, ambientSet_t *>::iterator mi; +ambientSet_t *CSetGroup::GetSet(const char *name) { + std::map::iterator mi; - if ( name == NULL ) + if (name == NULL) return NULL; - mi = m_setMap->find( name ); + mi = m_setMap->find(name); - if ( mi == m_setMap->end() ) + if (mi == m_setMap->end()) return NULL; return (*mi).second; } -ambientSet_t *CSetGroup::GetSet( int ID ) -{ - if ( m_ambientSets->empty() ) +ambientSet_t *CSetGroup::GetSet(int ID) { + if (m_ambientSets->empty()) return NULL; - if ( ID < 0 ) + if (ID < 0) return NULL; - if ( ID >= m_numSets ) + if (ID >= m_numSets) return NULL; return (*m_ambientSets)[ID]; } - /* =============================================== @@ -209,15 +188,13 @@ AS_GetSetNameIDForString ------------------------- */ -static int AS_GetSetNameIDForString( const char *name ) -{ - //Make sure it's valid - if ( name == NULL || name[0] == '\0' ) +static int AS_GetSetNameIDForString(const char *name) { + // Make sure it's valid + if (name == NULL || name[0] == '\0') return -1; - for ( int i = 0; i < NUM_AS_SETS; i++ ) - { - if ( Q_stricmp( name, setNames[i] ) == 0 ) + for (int i = 0; i < NUM_AS_SETS; i++) { + if (Q_stricmp(name, setNames[i]) == 0) return i; } @@ -230,15 +207,13 @@ AS_GetKeywordIDForString ------------------------- */ -static int AS_GetKeywordIDForString( const char *name ) -{ - //Make sure it's valid - if ( name == NULL || name[0] == '\0' ) +static int AS_GetKeywordIDForString(const char *name) { + // Make sure it's valid + if (name == NULL || name[0] == '\0') return -1; - for ( int i = 0; i < NUM_AS_KEYWORDS; i++ ) - { - if ( Q_stricmp( name, keywordNames[i] ) == 0 ) + for (int i = 0; i < NUM_AS_KEYWORDS; i++) { + if (Q_stricmp(name, keywordNames[i]) == 0) return i; } @@ -253,16 +228,14 @@ Skips a line in the character buffer ------------------------- */ -static void AS_SkipLine( void ) -{ - if ( parsePos > parseSize ) // needed to avoid a crash because of some OOR access that shouldn't be done +static void AS_SkipLine(void) { + if (parsePos > parseSize) // needed to avoid a crash because of some OOR access that shouldn't be done return; - while ( (parseBuffer[parsePos] != '\n') && (parseBuffer[parsePos] != '\r') ) - { + while ((parseBuffer[parsePos] != '\n') && (parseBuffer[parsePos] != '\r')) { parsePos++; - if ( parsePos > parseSize ) + if (parsePos > parseSize) return; } @@ -277,28 +250,26 @@ getTimeBetweenWaves ------------------------- */ -static void AS_GetTimeBetweenWaves( ambientSet_t &set ) -{ - int startTime, endTime; +static void AS_GetTimeBetweenWaves(ambientSet_t &set) { + int startTime, endTime; - //Get the data - sscanf( parseBuffer+parsePos, "%s %d %d", tempBuffer, &startTime, &endTime ); + // Get the data + sscanf(parseBuffer + parsePos, "%s %d %d", tempBuffer, &startTime, &endTime); - //Check for swapped start / end - if ( startTime > endTime ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Corrected swapped start / end times in a \"timeBetweenWaves\" keyword\n"); - #endif + // Check for swapped start / end + if (startTime > endTime) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Corrected swapped start / end times in a \"timeBetweenWaves\" keyword\n"); +#endif int swap = startTime; startTime = endTime; endTime = swap; } - //Store it - set.time_start = startTime; - set.time_end = endTime; + // Store it + set.time_start = startTime; + set.time_end = endTime; AS_SkipLine(); } @@ -311,48 +282,42 @@ subWaves ... ------------------------- */ -static void AS_GetSubWaves( ambientSet_t &set ) -{ - char dirBuffer[512], waveBuffer[256], waveName[1024]; +static void AS_GetSubWaves(ambientSet_t &set) { + char dirBuffer[512], waveBuffer[256], waveName[1024]; - //Get the directory for these sets - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, dirBuffer ); + // Get the directory for these sets + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, dirBuffer); - //Move the pointer past these two strings - parsePos += ((strlen(keywordNames[SET_KEYWORD_SUBWAVES])+1) + (strlen(dirBuffer)+1)); + // Move the pointer past these two strings + parsePos += ((strlen(keywordNames[SET_KEYWORD_SUBWAVES]) + 1) + (strlen(dirBuffer) + 1)); - //Get all the subwaves - while ( parsePos <= parseSize ) - { - //Get the data - sscanf( parseBuffer+parsePos, "%s", waveBuffer ); - - if ( set.numSubWaves >= MAX_WAVES_PER_GROUP ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Too many subwaves on set \"%s\"\n", set.name ); - #endif - } - else - { - //Construct the wave name - Com_sprintf( waveName, sizeof(waveName), "sound/%s/%s.wav", dirBuffer, waveBuffer ); - - //Place this onto the sound directory name - - //Precache the file at this point and store off the ID instead of the name - if ( ( set.subWaves[set.numSubWaves++] = S_RegisterSound( waveName ) ) <= 0 ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Unable to load ambient sound \"%s\"\n", waveName); - #endif + // Get all the subwaves + while (parsePos <= parseSize) { + // Get the data + sscanf(parseBuffer + parsePos, "%s", waveBuffer); + + if (set.numSubWaves >= MAX_WAVES_PER_GROUP) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Too many subwaves on set \"%s\"\n", set.name); +#endif + } else { + // Construct the wave name + Com_sprintf(waveName, sizeof(waveName), "sound/%s/%s.wav", dirBuffer, waveBuffer); + + // Place this onto the sound directory name + + // Precache the file at this point and store off the ID instead of the name + if ((set.subWaves[set.numSubWaves++] = S_RegisterSound(waveName)) <= 0) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unable to load ambient sound \"%s\"\n", waveName); +#endif } } - //Move the pointer past this string - parsePos += strlen(waveBuffer)+1; + // Move the pointer past this string + parsePos += strlen(waveBuffer) + 1; - if ( ( (parseBuffer+parsePos)[0] == '\n') || ( (parseBuffer+parsePos)[0] == '\r') ) + if (((parseBuffer + parsePos)[0] == '\n') || ((parseBuffer + parsePos)[0] == '\r')) break; } @@ -367,22 +332,20 @@ loopedWave ------------------------- */ -static void AS_GetLoopedWave( ambientSet_t &set ) -{ - char waveBuffer[256], waveName[1024]; +static void AS_GetLoopedWave(ambientSet_t &set) { + char waveBuffer[256], waveName[1024]; - //Get the looped wave name - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, waveBuffer ); + // Get the looped wave name + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, waveBuffer); - //Construct the wave name - Com_sprintf( waveName, sizeof(waveName), "sound/%s.wav", waveBuffer ); + // Construct the wave name + Com_sprintf(waveName, sizeof(waveName), "sound/%s.wav", waveBuffer); - //Precache the file at this point and store off the ID instead of the name - if ( ( set.loopedWave = S_RegisterSound( waveName ) ) <= 0 ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Unable to load ambient sound \"%s\"\n", waveName); - #endif + // Precache the file at this point and store off the ID instead of the name + if ((set.loopedWave = S_RegisterSound(waveName)) <= 0) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unable to load ambient sound \"%s\"\n", waveName); +#endif } AS_SkipLine(); @@ -394,28 +357,26 @@ AS_GetVolumeRange ------------------------- */ -static void AS_GetVolumeRange( ambientSet_t &set ) -{ - int min, max; +static void AS_GetVolumeRange(ambientSet_t &set) { + int min, max; - //Get the data - sscanf( parseBuffer+parsePos, "%s %d %d", tempBuffer, &min, &max ); + // Get the data + sscanf(parseBuffer + parsePos, "%s %d %d", tempBuffer, &min, &max); - //Check for swapped min / max - if ( min > max ) - { - #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW"WARNING: Corrected swapped min / max range in a \"volRange\" keyword\n"); - #endif + // Check for swapped min / max + if (min > max) { +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Corrected swapped min / max range in a \"volRange\" keyword\n"); +#endif - int swap = min; - min = max; - max = swap; + int swap = min; + min = max; + max = swap; } - //Store the data - set.volRange_start = min; - set.volRange_end = max; + // Store the data + set.volRange_start = min; + set.volRange_end = max; AS_SkipLine(); } @@ -426,10 +387,9 @@ AS_GetRadius ------------------------- */ -static void AS_GetRadius( ambientSet_t &set ) -{ - //Get the data - sscanf( parseBuffer+parsePos, "%s %d", tempBuffer, &set.radius ); +static void AS_GetRadius(ambientSet_t &set) { + // Get the data + sscanf(parseBuffer + parsePos, "%s %d", tempBuffer, &set.radius); AS_SkipLine(); } @@ -440,51 +400,47 @@ AS_GetGeneralSet ------------------------- */ -static void AS_GetGeneralSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetGeneralSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_TIMEBETWEENWAVES: - AS_GetTimeBetweenWaves( set ); + AS_GetTimeBetweenWaves(set); break; case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; case SET_KEYWORD_LOOPEDWAVE: - AS_GetLoopedWave( set ); + AS_GetLoopedWave(set); break; case SET_KEYWORD_VOLRANGE: - AS_GetVolumeRange( set ); + AS_GetVolumeRange(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -499,55 +455,51 @@ AS_GetLocalSet ------------------------- */ -static void AS_GetLocalSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetLocalSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_TIMEBETWEENWAVES: - AS_GetTimeBetweenWaves( set ); + AS_GetTimeBetweenWaves(set); break; case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; case SET_KEYWORD_LOOPEDWAVE: - AS_GetLoopedWave( set ); + AS_GetLoopedWave(set); break; case SET_KEYWORD_VOLRANGE: - AS_GetVolumeRange( set ); + AS_GetVolumeRange(set); break; case SET_KEYWORD_RADIUS: - AS_GetRadius( set ); + AS_GetRadius(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -562,39 +514,35 @@ AS_GetBModelSet ------------------------- */ -static void AS_GetBModelSet( ambientSet_t &set ) -{ - int keywordID; +static void AS_GetBModelSet(ambientSet_t &set) { + int keywordID; - //The other parameters of the set come in a specific order - while ( parsePos <= parseSize ) - { - int iFieldsScanned = sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // The other parameters of the set come in a specific order + while (parsePos <= parseSize) { + int iFieldsScanned = sscanf(parseBuffer + parsePos, "%s", tempBuffer); if (iFieldsScanned <= 0) return; - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - //Find and parse the keyword info - switch ( keywordID ) - { + // Find and parse the keyword info + switch (keywordID) { case SET_KEYWORD_SUBWAVES: - AS_GetSubWaves( set ); + AS_GetSubWaves(set); break; default: - //Check to see if we've finished this group - if ( AS_GetSetNameIDForString( (const char *) &tempBuffer ) == -1 ) - { - //Ignore comments - if ( tempBuffer[0] == ';' ) + // Check to see if we've finished this group + if (AS_GetSetNameIDForString((const char *)&tempBuffer) == -1) { + // Ignore comments + if (tempBuffer[0] == ';') return; - //This wasn't a set name, so it's an error - #ifndef FINAL_BUILD - Com_Printf( S_COLOR_YELLOW"WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer ); - #endif +// This wasn't a set name, so it's an error +#ifndef FINAL_BUILD + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown ambient set keyword \"%s\"\n", tempBuffer); +#endif } return; @@ -611,53 +559,49 @@ Parses an individual set group out of a set file buffer ------------------------- */ -static qboolean AS_ParseSet( int setID, CSetGroup *sg ) -{ - ambientSet_t *set; - const char *name; +static qboolean AS_ParseSet(int setID, CSetGroup *sg) { + ambientSet_t *set; + const char *name; - //Make sure we're not overstepping the name array - if ( setID >= NUM_AS_SETS ) + // Make sure we're not overstepping the name array + if (setID >= NUM_AS_SETS) return qfalse; - //Reset the pointers for this run through + // Reset the pointers for this run through parsePos = 0; name = setNames[setID]; - //Iterate through the whole file and find every occurance of a set - while ( parsePos <= parseSize ) - { - //Check for a valid set group - if ( Q_strncmp( parseBuffer+parsePos, name, strlen(name) ) == 0 ) - { - //Update the debug info + // Iterate through the whole file and find every occurance of a set + while (parsePos <= parseSize) { + // Check for a valid set group + if (Q_strncmp(parseBuffer + parsePos, name, strlen(name)) == 0) { + // Update the debug info numSets++; - //Push past the set specifier and on to the name - parsePos+=strlen(name)+1; //Also take the following space out + // Push past the set specifier and on to the name + parsePos += strlen(name) + 1; // Also take the following space out - //Get the set name (this MUST be first) - sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + // Get the set name (this MUST be first) + sscanf(parseBuffer + parsePos, "%s", tempBuffer); AS_SkipLine(); - //Test the string against the precaches - if ( tempBuffer[0] ) - { - //Not in our precache listings, so skip it - if ( ( pMap->find( (const char *) &tempBuffer ) == pMap->end() ) ) + // Test the string against the precaches + if (tempBuffer[0]) { + // Not in our precache listings, so skip it + if ((pMap->find((const char *)&tempBuffer) == pMap->end())) continue; } - //Create a new set - set = sg->AddSet( (const char *) &tempBuffer ); + // Create a new set + set = sg->AddSet((const char *)&tempBuffer); - //Run the function to parse the data out - parseFuncs[setID]( *set ); + // Run the function to parse the data out + parseFuncs[setID](*set); continue; } - //If not found on this line, go down another and check again + // If not found on this line, go down another and check again AS_SkipLine(); } @@ -672,40 +616,36 @@ Parses the directory information out of the beginning of the file ------------------------- */ -static void AS_ParseHeader( void ) -{ - char typeBuffer[128]; - int keywordID; +static void AS_ParseHeader(void) { + char typeBuffer[128]; + int keywordID; - while ( parsePos <= parseSize ) - { - sscanf( parseBuffer+parsePos, "%s", tempBuffer ); + while (parsePos <= parseSize) { + sscanf(parseBuffer + parsePos, "%s", tempBuffer); - keywordID = AS_GetKeywordIDForString( (const char *) &tempBuffer ); + keywordID = AS_GetKeywordIDForString((const char *)&tempBuffer); - switch ( keywordID ) - { + switch (keywordID) { case SET_KEYWORD_TYPE: - sscanf( parseBuffer+parsePos, "%s %s", tempBuffer, typeBuffer ); + sscanf(parseBuffer + parsePos, "%s %s", tempBuffer, typeBuffer); - if ( !Q_stricmp( (const char *) typeBuffer, "ambientSet" ) ) - { + if (!Q_stricmp((const char *)typeBuffer, "ambientSet")) { return; } - Com_Error( ERR_DROP, "AS_ParseHeader: Set type \"%s\" is not a valid set type!\n", typeBuffer ); + Com_Error(ERR_DROP, "AS_ParseHeader: Set type \"%s\" is not a valid set type!\n", typeBuffer); break; case SET_KEYWORD_AMSDIR: - //TODO: Implement + // TODO: Implement break; case SET_KEYWORD_OUTDIR: - //TODO: Implement + // TODO: Implement break; case SET_KEYWORD_BASEDIR: - //TODO: Implement + // TODO: Implement break; } @@ -721,23 +661,22 @@ Opens and parses a sound set file ------------------------- */ -static qboolean AS_ParseFile( const char *filename, CSetGroup *sg ) -{ - //Open the file and read the information from it - parseSize = FS_ReadFile( filename, (void **) &parseBuffer ); +static qboolean AS_ParseFile(const char *filename, CSetGroup *sg) { + // Open the file and read the information from it + parseSize = FS_ReadFile(filename, (void **)&parseBuffer); - if ( parseSize <= 0 ) + if (parseSize <= 0) return qfalse; - //Parse the directory information out of the file + // Parse the directory information out of the file AS_ParseHeader(); - //Parse all the relevent sets out of it - for ( int i = 0; i < NUM_AS_SETS; i++ ) - AS_ParseSet( i, sg ); + // Parse all the relevent sets out of it + for (int i = 0; i < NUM_AS_SETS; i++) + AS_ParseSet(i, sg); - //Free the memory and close the file - FS_FreeFile( parseBuffer ); + // Free the memory and close the file + FS_FreeFile(parseBuffer); return qtrue; } @@ -758,15 +697,13 @@ Loads the ambient sound sets and prepares to play them when needed ------------------------- */ -void AS_Init( void ) -{ - if (!aSets) - { +void AS_Init(void) { + if (!aSets) { numSets = 0; pMap = new namePrecache_m; - //Setup the structure + // Setup the structure aSets = new CSetGroup(); aSets->Init(); } @@ -778,21 +715,17 @@ AS_AddPrecacheEntry ------------------------- */ -void AS_AddPrecacheEntry( const char *name ) -{ - if (!pMap) //s_initsound 0 probably +void AS_AddPrecacheEntry(const char *name) { + if (!pMap) // s_initsound 0 probably { return; } - if (!Q_stricmp(name,"#clear")) - { + if (!Q_stricmp(name, "#clear")) { pMap->clear(); - currentSet = -1; - oldSet = -1; - } - else - { - (*pMap)[ name ] = 1; + currentSet = -1; + oldSet = -1; + } else { + (*pMap)[name] = 1; } } @@ -804,42 +737,37 @@ Called on the client side to load and precache all the ambient sound sets ------------------------- */ -void AS_ParseSets( void ) -{ - if ( !s_initsound->integer ) { +void AS_ParseSets(void) { + if (!s_initsound->integer) { return; } AS_Init(); - //Parse all the sets - if ( AS_ParseFile( AMBIENT_SET_FILENAME, aSets ) == qfalse ) - { - Com_Error ( ERR_FATAL, S_COLOR_RED"ERROR: Couldn't load ambient sound sets from %s", AMBIENT_SET_FILENAME ); + // Parse all the sets + if (AS_ParseFile(AMBIENT_SET_FILENAME, aSets) == qfalse) { + Com_Error(ERR_FATAL, S_COLOR_RED "ERROR: Couldn't load ambient sound sets from %s", AMBIENT_SET_FILENAME); } -// Com_Printf( "AS_ParseFile: Loaded %d of %d ambient set(s)\n", pMap.size(), numSets ); + // Com_Printf( "AS_ParseFile: Loaded %d of %d ambient set(s)\n", pMap.size(), numSets ); int iErrorsOccured = 0; - for (namePrecache_m::iterator it = pMap->begin(); it != pMap->end(); ++it) - { - const char* str = (*it).first.c_str(); - ambientSet_t *aSet = aSets->GetSet( str ); - if (!aSet) - { + for (namePrecache_m::iterator it = pMap->begin(); it != pMap->end(); ++it) { + const char *str = (*it).first.c_str(); + ambientSet_t *aSet = aSets->GetSet(str); + if (!aSet) { // I print these red instead of yellow because they're going to cause an ERR_DROP if they occur - Com_Printf( S_COLOR_RED"ERROR: AS_ParseSets: Unable to find ambient soundset \"%s\"!\n",str); + Com_Printf(S_COLOR_RED "ERROR: AS_ParseSets: Unable to find ambient soundset \"%s\"!\n", str); iErrorsOccured++; } } - if (iErrorsOccured) - { - Com_Error( ERR_DROP, "....%d missing sound sets! (see above)\n", iErrorsOccured); + if (iErrorsOccured) { + Com_Error(ERR_DROP, "....%d missing sound sets! (see above)\n", iErrorsOccured); } -// //Done with the precache info, it will be rebuilt on a restart -// pMap->clear(); // do NOT do this here now + // //Done with the precache info, it will be rebuilt on a restart + // pMap->clear(); // do NOT do this here now } /* @@ -850,37 +778,32 @@ Frees up the ambient sound system ------------------------- */ -void AS_Free( void ) -{ - if (aSets) - { +void AS_Free(void) { + if (aSets) { aSets->Free(); delete aSets; aSets = NULL; - currentSet = -1; - oldSet = -1; + currentSet = -1; + oldSet = -1; currentSetTime = 0; oldSetTime = 0; - numSets = 0; + numSets = 0; } } - -void AS_FreePartial(void) -{ - if (aSets) - { +void AS_FreePartial(void) { + if (aSets) { aSets->Free(); - currentSet = -1; - oldSet = -1; + currentSet = -1; + oldSet = -1; currentSetTime = 0; oldSetTime = 0; - numSets = 0; + numSets = 0; delete pMap; pMap = new namePrecache_m; @@ -904,47 +827,47 @@ Fades volumes up or down depending on the action being taken on them. ------------------------- */ -static void AS_UpdateSetVolumes( void ){ - if ( !aSets ) { +static void AS_UpdateSetVolumes(void) { + if (!aSets) { return; } - //Get the sets and validate them - ambientSet_t *current = aSets->GetSet( currentSet ); - if ( !current ) { + // Get the sets and validate them + ambientSet_t *current = aSets->GetSet(currentSet); + if (!current) { return; } float scale; int deltaTime; - if ( current->masterVolume < MAX_SET_VOLUME ) { + if (current->masterVolume < MAX_SET_VOLUME) { deltaTime = cls.realtime - current->fadeTime; - scale = ((float)(deltaTime)/(float)(crossDelay)); + scale = ((float)(deltaTime) / (float)(crossDelay)); current->masterVolume = (int)((scale) * (float)MAX_SET_VOLUME); } - if ( current->masterVolume > MAX_SET_VOLUME ) { + if (current->masterVolume > MAX_SET_VOLUME) { current->masterVolume = MAX_SET_VOLUME; } - //Only update the old set if it's still valid - if ( oldSet == -1 ) { + // Only update the old set if it's still valid + if (oldSet == -1) { return; } - ambientSet_t *old = aSets->GetSet( oldSet ); - if ( !old ) { + ambientSet_t *old = aSets->GetSet(oldSet); + if (!old) { return; } - //Update the volumes - if ( old->masterVolume > 0 ) { + // Update the volumes + if (old->masterVolume > 0) { deltaTime = cls.realtime - old->fadeTime; - scale = ((float)(deltaTime)/(float)(crossDelay)); + scale = ((float)(deltaTime) / (float)(crossDelay)); old->masterVolume = MAX_SET_VOLUME - (int)((scale) * (float)MAX_SET_VOLUME); } - if ( old->masterVolume <= 0 ) { + if (old->masterVolume <= 0) { old->masterVolume = 0; oldSet = -1; } @@ -958,36 +881,36 @@ Does internal maintenance to keep track of changing sets. ------------------------- */ -static void AS_UpdateCurrentSet( int id ) { - if ( !aSets ) { +static void AS_UpdateCurrentSet(int id) { + if (!aSets) { return; } - //Check for a change - if ( id != currentSet ) { - //This is new, so start the fading + // Check for a change + if (id != currentSet) { + // This is new, so start the fading oldSet = currentSet; currentSet = id; - ambientSet_t *current = aSets->GetSet( currentSet ); + ambientSet_t *current = aSets->GetSet(currentSet); // Ste, I just put this null check in for now, not sure if there's a more graceful way to exit this function - dmv - if ( !current ) { + if (!current) { return; } - ambientSet_t *old = aSets->GetSet( oldSet ); - if ( old ) { + ambientSet_t *old = aSets->GetSet(oldSet); + if (old) { old->masterVolume = MAX_SET_VOLUME; old->fadeTime = cls.realtime; } current->masterVolume = 0; - //Set the fading starts + // Set the fading starts current->fadeTime = cls.realtime; } - //Update their volumes if fading + // Update their volumes if fading AS_UpdateSetVolumes(); } @@ -1000,41 +923,41 @@ Alters lastTime to reflect the time updates. ------------------------- */ -static void AS_PlayLocalSet( vec3_t listener_origin, vec3_t origin, const ambientSet_t *set, int entID, int *lastTime ) { - //Make sure it's valid - if ( !set ) { +static void AS_PlayLocalSet(vec3_t listener_origin, vec3_t origin, const ambientSet_t *set, int entID, int *lastTime) { + // Make sure it's valid + if (!set) { return; } vec3_t dir; - VectorSubtract( origin, listener_origin, dir ); - float dist = VectorLength( dir ); + VectorSubtract(origin, listener_origin, dir); + float dist = VectorLength(dir); - //Determine the volume based on distance (NOTE: This sits on top of what SpatializeOrigin does) - float distScale = ( dist < ( set->radius * 0.5f ) ) ? 1 : ( set->radius - dist ) / ( set->radius * 0.5f ); - unsigned char volume = ( distScale > 1.0f || distScale < 0.0f ) ? 0 : (unsigned char) ( set->masterVolume * distScale ); + // Determine the volume based on distance (NOTE: This sits on top of what SpatializeOrigin does) + float distScale = (dist < (set->radius * 0.5f)) ? 1 : (set->radius - dist) / (set->radius * 0.5f); + unsigned char volume = (distScale > 1.0f || distScale < 0.0f) ? 0 : (unsigned char)(set->masterVolume * distScale); - //Add the looping sound - if ( set->loopedWave ) { - S_AddAmbientLoopingSound( origin, volume, set->loopedWave ); + // Add the looping sound + if (set->loopedWave) { + S_AddAmbientLoopingSound(origin, volume, set->loopedWave); } - //Check the time to start another one-shot subwave + // Check the time to start another one-shot subwave int time = cl.serverTime; - if ( ( time - *lastTime ) < ( ( Q_irand( set->time_start, set->time_end ) ) * 1000 ) ) { + if ((time - *lastTime) < ((Q_irand(set->time_start, set->time_end)) * 1000)) { return; } - //Update the time + // Update the time *lastTime = time; - //Scale the volume ranges for the subwaves based on the overall master volume - float volScale = (float) volume / (float) MAX_SET_VOLUME; - volume = (unsigned char) Q_irand( (int)(volScale*set->volRange_start), (int)(volScale*set->volRange_end) ); + // Scale the volume ranges for the subwaves based on the overall master volume + float volScale = (float)volume / (float)MAX_SET_VOLUME; + volume = (unsigned char)Q_irand((int)(volScale * set->volRange_start), (int)(volScale * set->volRange_end)); - //Add the random subwave - if ( set->numSubWaves ) { - S_StartAmbientSound( origin, entID, volume, set->subWaves[Q_irand( 0, set->numSubWaves-1)] ); + // Add the random subwave + if (set->numSubWaves) { + S_StartAmbientSound(origin, entID, volume, set->subWaves[Q_irand(0, set->numSubWaves - 1)]); } } @@ -1047,38 +970,38 @@ Alters lastTime to reflect the time updates. ------------------------- */ -static void AS_PlayAmbientSet( vec3_t origin, const ambientSet_t *set, int *lastTime ) { - //Make sure it's valid - if ( !set ) { +static void AS_PlayAmbientSet(vec3_t origin, const ambientSet_t *set, int *lastTime) { + // Make sure it's valid + if (!set) { return; } - //Add the looping sound - if ( set->loopedWave ) { - S_AddAmbientLoopingSound( origin, (unsigned char) set->masterVolume, set->loopedWave ); + // Add the looping sound + if (set->loopedWave) { + S_AddAmbientLoopingSound(origin, (unsigned char)set->masterVolume, set->loopedWave); } - //Check the time to start another one-shot subwave + // Check the time to start another one-shot subwave int time = cls.realtime; - if ( ( time - *lastTime ) < ( ( Q_irand( set->time_start, set->time_end ) ) * 1000 ) ) { + if ((time - *lastTime) < ((Q_irand(set->time_start, set->time_end)) * 1000)) { return; } - //Update the time + // Update the time *lastTime = time; - //Scale the volume ranges for the subwaves based on the overall master volume - float volScale = (float) set->masterVolume / (float) MAX_SET_VOLUME; - unsigned char volume = Q_irand( (int)(volScale*set->volRange_start), (int)(volScale*set->volRange_end) ); + // Scale the volume ranges for the subwaves based on the overall master volume + float volScale = (float)set->masterVolume / (float)MAX_SET_VOLUME; + unsigned char volume = Q_irand((int)(volScale * set->volRange_start), (int)(volScale * set->volRange_end)); - //Allow for softer noises than the masterVolume, but not louder - if ( volume > set->masterVolume ) { + // Allow for softer noises than the masterVolume, but not louder + if (volume > set->masterVolume) { volume = set->masterVolume; } - //Add the random subwave - if ( set->numSubWaves ) { - S_StartAmbientSound( origin, 0, volume, set->subWaves[Q_irand( 0, set->numSubWaves-1)] ); + // Add the random subwave + if (set->numSubWaves) { + S_StartAmbientSound(origin, 0, volume, set->subWaves[Q_irand(0, set->numSubWaves - 1)]); } } @@ -1090,27 +1013,27 @@ Does maintenance and plays the ambient sets (two if crossfading) ------------------------- */ -void S_UpdateAmbientSet( const char *name, vec3_t origin ) { - if ( !aSets ) { +void S_UpdateAmbientSet(const char *name, vec3_t origin) { + if (!aSets) { return; } - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set ) { + const ambientSet_t *set = aSets->GetSet(name); + if (!set) { return; } - //Update the current and old set for crossfading - AS_UpdateCurrentSet( set->id ); + // Update the current and old set for crossfading + AS_UpdateCurrentSet(set->id); - const ambientSet_t *current = aSets->GetSet( currentSet ); - if ( current ) { - AS_PlayAmbientSet( origin, set, ¤tSetTime ); + const ambientSet_t *current = aSets->GetSet(currentSet); + if (current) { + AS_PlayAmbientSet(origin, set, ¤tSetTime); } - const ambientSet_t *old = aSets->GetSet( oldSet ); - if ( old ) { - AS_PlayAmbientSet( origin, old, &oldSetTime ); + const ambientSet_t *old = aSets->GetSet(oldSet); + if (old) { + AS_PlayAmbientSet(origin, old, &oldSetTime); } } @@ -1120,18 +1043,18 @@ S_AddLocalSet ------------------------- */ -int S_AddLocalSet( const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time ) { - if ( !aSets ) { +int S_AddLocalSet(const char *name, vec3_t listener_origin, vec3_t origin, int entID, int time) { + if (!aSets) { return cl.serverTime; } - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set ) { + const ambientSet_t *set = aSets->GetSet(name); + if (!set) { return cl.serverTime; } int currentTime = time; - AS_PlayLocalSet( listener_origin, origin, set, entID, ¤tTime ); + AS_PlayLocalSet(listener_origin, origin, set, entID, ¤tTime); return currentTime; } @@ -1141,14 +1064,14 @@ AS_GetBModelSound ------------------------- */ -sfxHandle_t AS_GetBModelSound( const char *name, int stage ) { - if ( !aSets ) { +sfxHandle_t AS_GetBModelSound(const char *name, int stage) { + if (!aSets) { return -1; } - //Stage must be within a valid range - const ambientSet_t *set = aSets->GetSet( name ); - if ( !set || stage < 0 || stage > (set->numSubWaves - 1) ) { + // Stage must be within a valid range + const ambientSet_t *set = aSets->GetSet(name); + if (!set || stage < 0 || stage > (set->numSubWaves - 1)) { return -1; } diff --git a/codemp/client/snd_dma.cpp b/codemp/client/snd_dma.cpp index 736203492a..f140fe12cc 100644 --- a/codemp/client/snd_dma.cpp +++ b/codemp/client/snd_dma.cpp @@ -50,8 +50,8 @@ static void S_SetDynamicMusic_f(void); void S_Update_(); void S_StopAllSounds(void); -static void S_UpdateBackgroundTrack( void ); -sfx_t *S_FindName( const char *name ); +static void S_UpdateBackgroundTrack(void); +sfx_t *S_FindName(const char *name); static int SND_FreeSFXMem(sfx_t *sfx); extern qboolean Sys_LowPhysicalMemory(); @@ -60,118 +60,115 @@ extern qboolean Sys_LowPhysicalMemory(); // // vars for bgrnd music track... // -const int iMP3MusicStream_DiskBytesToRead = 10000;//4096; -const int iMP3MusicStream_DiskBufferSize = iMP3MusicStream_DiskBytesToRead*2; //*10; +const int iMP3MusicStream_DiskBytesToRead = 10000; // 4096; +const int iMP3MusicStream_DiskBufferSize = iMP3MusicStream_DiskBytesToRead * 2; //*10; typedef struct MusicInfo_s { - qboolean bIsMP3; + qboolean bIsMP3; // // MP3 specific... // - sfx_t sfxMP3_Bgrnd; - MP3STREAM streamMP3_Bgrnd; // this one is pointed at by the sfx_t's ptr, and is NOT the one the decoder uses every cycle - channel_t chMP3_Bgrnd; // ... but the one in this struct IS. + sfx_t sfxMP3_Bgrnd; + MP3STREAM streamMP3_Bgrnd; // this one is pointed at by the sfx_t's ptr, and is NOT the one the decoder uses every cycle + channel_t chMP3_Bgrnd; // ... but the one in this struct IS. // // MP3 disk streamer stuff... (if music is non-dynamic) // - byte byMP3MusicStream_DiskBuffer[iMP3MusicStream_DiskBufferSize]; - int iMP3MusicStream_DiskReadPos; - int iMP3MusicStream_DiskWindowPos; + byte byMP3MusicStream_DiskBuffer[iMP3MusicStream_DiskBufferSize]; + int iMP3MusicStream_DiskReadPos; + int iMP3MusicStream_DiskWindowPos; // // MP3 disk-load stuff (for use during dynamic music, which is mem-resident) // - byte *pLoadedData; // Z_Malloc, Z_Free // these two MUST be kept as valid/invalid together - char sLoadedDataName[MAX_QPATH]; // " " " " " - int iLoadedDataLen; + byte *pLoadedData; // Z_Malloc, Z_Free // these two MUST be kept as valid/invalid together + char sLoadedDataName[MAX_QPATH]; // " " " " " + int iLoadedDataLen; // // remaining dynamic fields... // - int iXFadeVolumeSeekTime; - int iXFadeVolumeSeekTo; // when changing this, set the above timer to Sys_Milliseconds(). - // Note that this should be thought of more as an up/down bool rather than as a - // number now, in other words set it only to 0 or 255. I'll probably change this - // to actually be a bool later. - int iXFadeVolume; // 0 = silent, 255 = max mixer vol, though still modulated via overall music_volume - float fSmoothedOutVolume; - qboolean bActive; // whether playing or not - qboolean bExists; // whether was even loaded for this level (ie don't try and start playing it) + int iXFadeVolumeSeekTime; + int iXFadeVolumeSeekTo; // when changing this, set the above timer to Sys_Milliseconds(). + // Note that this should be thought of more as an up/down bool rather than as a + // number now, in other words set it only to 0 or 255. I'll probably change this + // to actually be a bool later. + int iXFadeVolume; // 0 = silent, 255 = max mixer vol, though still modulated via overall music_volume + float fSmoothedOutVolume; + qboolean bActive; // whether playing or not + qboolean bExists; // whether was even loaded for this level (ie don't try and start playing it) // // new dynamic fields... // - qboolean bTrackSwitchPending; + qboolean bTrackSwitchPending; MusicState_e eTS_NewState; - float fTS_NewTime; + float fTS_NewTime; // // Generic... // - fileHandle_t s_backgroundFile; // valid handle, else -1 if an MP3 (so that NZ compares still work) - wavinfo_t s_backgroundInfo; - int s_backgroundSamples; + fileHandle_t s_backgroundFile; // valid handle, else -1 if an MP3 (so that NZ compares still work) + wavinfo_t s_backgroundInfo; + int s_backgroundSamples; - void Rewind() - { - MP3Stream_Rewind( &chMP3_Bgrnd ); + void Rewind() { + MP3Stream_Rewind(&chMP3_Bgrnd); s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples; } - void SeekTo(float fTime) - { + void SeekTo(float fTime) { chMP3_Bgrnd.iMP3SlidingDecodeWindowPos = 0; chMP3_Bgrnd.iMP3SlidingDecodeWritePos = 0; - MP3Stream_SeekTo( &chMP3_Bgrnd, fTime ); + MP3Stream_SeekTo(&chMP3_Bgrnd, fTime); s_backgroundSamples = sfxMP3_Bgrnd.iSoundLengthInSamples; } } MusicInfo_t; -static void S_SetDynamicMusicState( MusicState_e musicState ); +static void S_SetDynamicMusicState(MusicState_e musicState); #define fDYNAMIC_XFADE_SECONDS (1.0f) -static MusicInfo_t tMusic_Info[eBGRNDTRACK_NUMBEROF] = {}; -static qboolean bMusic_IsDynamic = qfalse; -static MusicState_e eMusic_StateActual = eBGRNDTRACK_EXPLORE; // actual state, can be any enum -static MusicState_e eMusic_StateRequest = eBGRNDTRACK_EXPLORE; // requested state, can only be explore, action, boss, or silence -static char sMusic_BackgroundLoop[MAX_QPATH] = {0}; // only valid for non-dynamic music -static char sInfoOnly_CurrentDynamicMusicSet[64]; // any old reasonable size, only has to fit stuff like "kejim_post" +static MusicInfo_t tMusic_Info[eBGRNDTRACK_NUMBEROF] = {}; +static qboolean bMusic_IsDynamic = qfalse; +static MusicState_e eMusic_StateActual = eBGRNDTRACK_EXPLORE; // actual state, can be any enum +static MusicState_e eMusic_StateRequest = eBGRNDTRACK_EXPLORE; // requested state, can only be explore, action, boss, or silence +static char sMusic_BackgroundLoop[MAX_QPATH] = {0}; // only valid for non-dynamic music +static char sInfoOnly_CurrentDynamicMusicSet[64]; // any old reasonable size, only has to fit stuff like "kejim_post" // ////////////////////////// - // ======================================================================= // Internal sound data & structures // ======================================================================= // only begin attenuating sound volumes when outside the FULLVOLUME range -#define SOUND_FULLVOLUME 256 +#define SOUND_FULLVOLUME 256 -#define SOUND_ATTENUATE 0.0008f -#define VOICE_ATTENUATE 0.004f +#define SOUND_ATTENUATE 0.0008f +#define VOICE_ATTENUATE 0.004f -const float SOUND_FMAXVOL=0.75;//1.0; -const int SOUND_MAXVOL=255; +const float SOUND_FMAXVOL = 0.75; // 1.0; +const int SOUND_MAXVOL = 255; -channel_t s_channels[MAX_CHANNELS]; +channel_t s_channels[MAX_CHANNELS]; -int s_soundStarted; -qboolean s_soundMuted; +int s_soundStarted; +qboolean s_soundMuted; -dma_t dma; +dma_t dma; -int listener_number; -vec3_t listener_origin; -matrix3_t listener_axis; +int listener_number; +vec3_t listener_origin; +matrix3_t listener_axis; -int s_soundtime; // sample PAIRS -int s_paintedtime; // sample PAIRS +int s_soundtime; // sample PAIRS +int s_paintedtime; // sample PAIRS // MAX_SFX may be larger than MAX_SOUNDS because // of custom player sounds -#define MAX_SFX 10000 //512 * 2 -sfx_t s_knownSfx[MAX_SFX]; -int s_numSfx; +#define MAX_SFX 10000 // 512 * 2 +sfx_t s_knownSfx[MAX_SFX]; +int s_numSfx; -#define LOOP_HASH 128 -static sfx_t *sfxHash[LOOP_HASH]; +#define LOOP_HASH 128 +static sfx_t *sfxHash[LOOP_HASH]; cvar_t *s_allowDynamicMusic; cvar_t *s_debugdynamic; @@ -179,7 +176,7 @@ cvar_t *s_doppler; cvar_t *s_dynamix; cvar_t *s_initsound; cvar_t *s_khz; -cvar_t *s_language; // note that this is distinct from "g_language" +cvar_t *s_language; // note that this is distinct from "g_language" cvar_t *s_lip_threshold_1; cvar_t *s_lip_threshold_2; cvar_t *s_lip_threshold_3; @@ -193,35 +190,34 @@ cvar_t *s_testsound; cvar_t *s_volume; cvar_t *s_volumeVoice; -typedef struct -{ - unsigned char volume; - vec3_t origin; - vec3_t velocity; - sfx_t *sfx; - int mergeFrame; - int entnum; +typedef struct { + unsigned char volume; + vec3_t origin; + vec3_t velocity; + sfx_t *sfx; + int mergeFrame; + int entnum; - qboolean doppler; - float dopplerScale; + qboolean doppler; + float dopplerScale; // For Open AL - bool bProcessed; - bool bRelative; + bool bProcessed; + bool bRelative; } loopSound_t; -#define MAX_LOOP_SOUNDS 32 +#define MAX_LOOP_SOUNDS 32 -int numLoopSounds; -loopSound_t loopSounds[MAX_LOOP_SOUNDS]; +int numLoopSounds; +loopSound_t loopSounds[MAX_LOOP_SOUNDS]; -int s_rawend; -portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; -vec3_t s_entityPosition[MAX_GENTITIES]; -int s_entityWavVol[MAX_GENTITIES]; -int s_entityWavVol_back[MAX_GENTITIES]; +int s_rawend; +portable_samplepair_t s_rawsamples[MAX_RAW_SAMPLES]; +vec3_t s_entityPosition[MAX_GENTITIES]; +int s_entityWavVol[MAX_GENTITIES]; +int s_entityWavVol_back[MAX_GENTITIES]; -int s_numChannels; // Number of AL Sources == Num of Channels +int s_numChannels; // Number of AL Sources == Num of Channels #ifdef USE_OPENAL @@ -231,23 +227,23 @@ int s_numChannels; // Number of AL Sources == Num of Channels * \**************************************************************************************************/ -#define sqr(a) ((a)*(a)) -#define ENV_UPDATE_RATE 100 // Environmental audio update rate (in ms) +#define sqr(a) ((a) * (a)) +#define ENV_UPDATE_RATE 100 // Environmental audio update rate (in ms) //#define DISPLAY_CLOSEST_ENVS // Displays the closest env. zones (including the one the listener is in) -#define DEFAULT_REF_DISTANCE 300.0f // Default reference distance -#define DEFAULT_VOICE_REF_DISTANCE 1500.0f // Default voice reference distance +#define DEFAULT_REF_DISTANCE 300.0f // Default reference distance +#define DEFAULT_VOICE_REF_DISTANCE 1500.0f // Default voice reference distance -int s_UseOpenAL = 0; // Determines if using Open AL or the default software mixer +int s_UseOpenAL = 0; // Determines if using Open AL or the default software mixer -ALfloat listener_pos[3]; // Listener Position -ALfloat listener_ori[6]; // Listener Orientation +ALfloat listener_pos[3]; // Listener Position +ALfloat listener_ori[6]; // Listener Orientation -short s_rawdata[MAX_RAW_SAMPLES*2]; // Used for Raw Samples (Music etc...) +short s_rawdata[MAX_RAW_SAMPLES * 2]; // Used for Raw Samples (Music etc...) channel_t *S_OpenALPickChannel(int entnum, int entchannel); -int S_MP3PreProcessLipSync(channel_t *ch, short *data); +int S_MP3PreProcessLipSync(channel_t *ch, short *data); void UpdateSingleShotSounds(); void UpdateLoopingSounds(); void AL_UpdateRawSamples(); @@ -256,11 +252,10 @@ void S_SetLipSyncs(); // EAX Related typedef struct ENVTABLE_s { - ALuint ulNumApertures; - ALint lFXSlotID; - ALboolean bUsed; - struct - { + ALuint ulNumApertures; + ALint lFXSlotID; + ALboolean bUsed; + struct { ALfloat vPos1[3]; ALfloat vPos2[3]; ALfloat vCenter[3]; @@ -274,25 +269,25 @@ typedef struct REVERBDATA_s { } REVERBDATA, *LPREVERBDATA; typedef struct FXSLOTINFO_s { - GUID FXSlotGuid; - ALint lEnvID; + GUID FXSlotGuid; + ALint lEnvID; } FXSLOTINFO, *LPFXSLOTINFO; -ALboolean s_bEAX; // Is EAX 4.0 support available -bool s_bEALFileLoaded; // Has an .eal file been loaded for the current level -bool s_bInWater; // Underwater effect currently active -int s_EnvironmentID; // EAGLE ID of current environment - -LPEAXMANAGER s_lpEAXManager; // Pointer to EAXManager object -HINSTANCE s_hEAXManInst; // Handle of EAXManager DLL -EAXSet s_eaxSet; // EAXSet() function -EAXGet s_eaxGet; // EAXGet() function -EAXREVERBPROPERTIES s_eaxLPCur; // Current EAX Parameters -LPENVTABLE s_lpEnvTable=NULL; // Stores information about each environment zone -long s_lLastEnvUpdate; // Time of last EAX update -long s_lNumEnvironments; // Number of environment zones -long s_NumFXSlots; // Number of EAX 4.0 FX Slots -FXSLOTINFO s_FXSlotInfo[EAX_MAX_FXSLOTS]; // Stores information about the EAX 4.0 FX Slots +ALboolean s_bEAX; // Is EAX 4.0 support available +bool s_bEALFileLoaded; // Has an .eal file been loaded for the current level +bool s_bInWater; // Underwater effect currently active +int s_EnvironmentID; // EAGLE ID of current environment + +LPEAXMANAGER s_lpEAXManager; // Pointer to EAXManager object +HINSTANCE s_hEAXManInst; // Handle of EAXManager DLL +EAXSet s_eaxSet; // EAXSet() function +EAXGet s_eaxGet; // EAXGet() function +EAXREVERBPROPERTIES s_eaxLPCur; // Current EAX Parameters +LPENVTABLE s_lpEnvTable = NULL; // Stores information about each environment zone +long s_lLastEnvUpdate; // Time of last EAX update +long s_lNumEnvironments; // Number of environment zones +long s_NumFXSlots; // Number of EAX 4.0 FX Slots +FXSLOTINFO s_FXSlotInfo[EAX_MAX_FXSLOTS]; // Stores information about the EAX 4.0 FX Slots void InitEAXManager(); void ReleaseEAXManager(); @@ -303,8 +298,7 @@ void UpdateEAXBuffer(channel_t *ch); void EALFileInit(const char *level); float CalcDistance(EMPOINT A, EMPOINT B); -void Normalize(EAXVECTOR *v) -{ +void Normalize(EAXVECTOR *v) { float flMagnitude; flMagnitude = (float)sqrt(sqr(v->x) + sqr(v->y) + sqr(v->z)); @@ -316,23 +310,23 @@ void Normalize(EAXVECTOR *v) // EAX 4.0 GUIDS ... confidential information ... -const GUID EAXPROPERTYID_EAX40_FXSlot0 = { 0xc4d79f1e, 0xf1ac, 0x436b, { 0xa8, 0x1d, 0xa7, 0x38, 0xe7, 0x4, 0x54, 0x69} }; +const GUID EAXPROPERTYID_EAX40_FXSlot0 = {0xc4d79f1e, 0xf1ac, 0x436b, {0xa8, 0x1d, 0xa7, 0x38, 0xe7, 0x4, 0x54, 0x69}}; -const GUID EAXPROPERTYID_EAX40_FXSlot1 = { 0x8c00e96, 0x74be, 0x4491, { 0x93, 0xaa, 0xe8, 0xad, 0x35, 0xa4, 0x91, 0x17} }; +const GUID EAXPROPERTYID_EAX40_FXSlot1 = {0x8c00e96, 0x74be, 0x4491, {0x93, 0xaa, 0xe8, 0xad, 0x35, 0xa4, 0x91, 0x17}}; -const GUID EAXPROPERTYID_EAX40_FXSlot2 = { 0x1d433b88, 0xf0f6, 0x4637, { 0x91, 0x9f, 0x60, 0xe7, 0xe0, 0x6b, 0x5e, 0xdd} }; +const GUID EAXPROPERTYID_EAX40_FXSlot2 = {0x1d433b88, 0xf0f6, 0x4637, {0x91, 0x9f, 0x60, 0xe7, 0xe0, 0x6b, 0x5e, 0xdd}}; -const GUID EAXPROPERTYID_EAX40_FXSlot3 = { 0xefff08ea, 0xc7d8, 0x44ab, { 0x93, 0xad, 0x6d, 0xbd, 0x5f, 0x91, 0x0, 0x64} }; +const GUID EAXPROPERTYID_EAX40_FXSlot3 = {0xefff08ea, 0xc7d8, 0x44ab, {0x93, 0xad, 0x6d, 0xbd, 0x5f, 0x91, 0x0, 0x64}}; -const GUID EAXPROPERTYID_EAX40_Context = { 0x1d4870ad, 0xdef, 0x43c0, { 0xa4, 0xc, 0x52, 0x36, 0x32, 0x29, 0x63, 0x42} }; +const GUID EAXPROPERTYID_EAX40_Context = {0x1d4870ad, 0xdef, 0x43c0, {0xa4, 0xc, 0x52, 0x36, 0x32, 0x29, 0x63, 0x42}}; -const GUID EAXPROPERTYID_EAX40_Source = { 0x1b86b823, 0x22df, 0x4eae, { 0x8b, 0x3c, 0x12, 0x78, 0xce, 0x54, 0x42, 0x27} }; +const GUID EAXPROPERTYID_EAX40_Source = {0x1b86b823, 0x22df, 0x4eae, {0x8b, 0x3c, 0x12, 0x78, 0xce, 0x54, 0x42, 0x27}}; -const GUID EAX_NULL_GUID = { 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; +const GUID EAX_NULL_GUID = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; -const GUID EAX_PrimaryFXSlotID = { 0xf317866d, 0x924c, 0x450c, { 0x86, 0x1b, 0xe6, 0xda, 0xa2, 0x5e, 0x7c, 0x20} }; +const GUID EAX_PrimaryFXSlotID = {0xf317866d, 0x924c, 0x450c, {0x86, 0x1b, 0xe6, 0xda, 0xa2, 0x5e, 0x7c, 0x20}}; -const GUID EAX_REVERB_EFFECT = { 0xcf95c8f, 0xa3cc, 0x4849, { 0xb0, 0xb6, 0x83, 0x2e, 0xcc, 0x18, 0x22, 0xdf} }; +const GUID EAX_REVERB_EFFECT = {0xcf95c8f, 0xa3cc, 0x4849, {0xb0, 0xb6, 0x83, 0x2e, 0xcc, 0x18, 0x22, 0xdf}}; /**************************************************************************************************\ * @@ -346,95 +340,79 @@ const GUID EAX_REVERB_EFFECT = { 0xcf95c8f, 0xa3cc, 0x4849, { 0xb0, 0xb6, 0x83, #ifndef offsetof #include #endif -static inline void Channel_Clear(channel_t *ch) -{ +static inline void Channel_Clear(channel_t *ch) { // memset (ch, 0, sizeof(*ch)); - memset(ch,0,offsetof(channel_t,MP3SlidingDecodeBuffer)); + memset(ch, 0, offsetof(channel_t, MP3SlidingDecodeBuffer)); - byte *const p = (byte *)ch + offsetof(channel_t,MP3SlidingDecodeBuffer) + sizeof(ch->MP3SlidingDecodeBuffer); + byte *const p = (byte *)ch + offsetof(channel_t, MP3SlidingDecodeBuffer) + sizeof(ch->MP3SlidingDecodeBuffer); - memset(p,0,(sizeof(*ch) - offsetof(channel_t,MP3SlidingDecodeBuffer)) - sizeof(ch->MP3SlidingDecodeBuffer)); + memset(p, 0, (sizeof(*ch) - offsetof(channel_t, MP3SlidingDecodeBuffer)) - sizeof(ch->MP3SlidingDecodeBuffer)); } // ==================================================================== // User-setable variables // ==================================================================== -static void DynamicMusicInfoPrint(void) -{ - if (bMusic_IsDynamic) - { +static void DynamicMusicInfoPrint(void) { + if (bMusic_IsDynamic) { // horribly lazy... ;-) // - const char *psRequestMusicState = Music_BaseStateToString( eMusic_StateRequest ); - const char *psActualMusicState = Music_BaseStateToString( eMusic_StateActual, qtrue ); - if (psRequestMusicState == NULL) - { + const char *psRequestMusicState = Music_BaseStateToString(eMusic_StateRequest); + const char *psActualMusicState = Music_BaseStateToString(eMusic_StateActual, qtrue); + if (psRequestMusicState == NULL) { psRequestMusicState = ""; } - if (psActualMusicState == NULL) - { - psActualMusicState = ""; + if (psActualMusicState == NULL) { + psActualMusicState = ""; } - Com_Printf("( Dynamic music ON, request state: '%s'(%d), actual: '%s' (%d) )\n", psRequestMusicState, eMusic_StateRequest, psActualMusicState, eMusic_StateActual); - } - else - { + Com_Printf("( Dynamic music ON, request state: '%s'(%d), actual: '%s' (%d) )\n", psRequestMusicState, eMusic_StateRequest, psActualMusicState, + eMusic_StateActual); + } else { Com_Printf("( Dynamic music OFF )\n"); } } void S_SoundInfo_f(void) { - Com_Printf("----- Sound Info -----\n" ); + Com_Printf("----- Sound Info -----\n"); if (!s_soundStarted) { - Com_Printf ("sound system not started\n"); + Com_Printf("sound system not started\n"); } else { #ifdef USE_OPENAL - if (s_UseOpenAL) - { - Com_Printf("EAX 4.0 %s supported\n",s_bEAX?"is":"not"); - Com_Printf("Eal file %s loaded\n",s_bEALFileLoaded?"is":"not"); - Com_Printf("s_EnvironmentID = %d\n",s_EnvironmentID); - Com_Printf("s_bInWater = %s\n",s_bInWater?"true":"false"); - } - else - { + if (s_UseOpenAL) { + Com_Printf("EAX 4.0 %s supported\n", s_bEAX ? "is" : "not"); + Com_Printf("Eal file %s loaded\n", s_bEALFileLoaded ? "is" : "not"); + Com_Printf("s_EnvironmentID = %d\n", s_EnvironmentID); + Com_Printf("s_bInWater = %s\n", s_bInWater ? "true" : "false"); + } else { #endif Com_Printf("%5d stereo\n", dma.channels - 1); Com_Printf("%5d samples\n", dma.samples); Com_Printf("%5d samplebits\n", dma.samplebits); Com_Printf("%5d submission_chunk\n", dma.submission_chunk); Com_Printf("%5d speed\n", dma.speed); - Com_Printf( "0x%" PRIxPTR " dma buffer\n", dma.buffer ); + Com_Printf("0x%" PRIxPTR " dma buffer\n", dma.buffer); #ifdef USE_OPENAL } #endif - if (bMusic_IsDynamic) - { + if (bMusic_IsDynamic) { DynamicMusicInfoPrint(); - Com_Printf("( Dynamic music set name: \"%s\" )\n",sInfoOnly_CurrentDynamicMusicSet); - } - else - { - if (!s_allowDynamicMusic->integer) - { - Com_Printf("( Dynamic music inhibited (s_allowDynamicMusic == 0) )\n", sMusic_BackgroundLoop ); - } - if ( tMusic_Info[eBGRNDTRACK_NONDYNAMIC].s_backgroundFile ) - { - Com_Printf("Background file: %s\n", sMusic_BackgroundLoop ); + Com_Printf("( Dynamic music set name: \"%s\" )\n", sInfoOnly_CurrentDynamicMusicSet); + } else { + if (!s_allowDynamicMusic->integer) { + Com_Printf("( Dynamic music inhibited (s_allowDynamicMusic == 0) )\n", sMusic_BackgroundLoop); } - else - { - Com_Printf("No background file.\n" ); + if (tMusic_Info[eBGRNDTRACK_NONDYNAMIC].s_backgroundFile) { + Com_Printf("Background file: %s\n", sMusic_BackgroundLoop); + } else { + Com_Printf("No background file.\n"); } } } S_DisplayFreeMemory(); - Com_Printf("----------------------\n" ); + Com_Printf("----------------------\n"); } /* @@ -442,66 +420,65 @@ void S_SoundInfo_f(void) { S_Init ================ */ -void S_Init( void ) { - qboolean r; +void S_Init(void) { + qboolean r; Com_Printf("\n------- sound initialization -------\n"); - s_allowDynamicMusic = Cvar_Get( "s_allowDynamicMusic", "1", CVAR_ARCHIVE_ND ); - s_debugdynamic = Cvar_Get( "s_debugdynamic", "0", CVAR_CHEAT ); - s_doppler = Cvar_Get( "s_doppler", "1", CVAR_ARCHIVE_ND ); - s_initsound = Cvar_Get( "s_initsound", "1", CVAR_ARCHIVE ); - s_khz = Cvar_Get( "s_khz", "44", CVAR_ARCHIVE | CVAR_LATCH ); - s_language = Cvar_Get( "s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, "Sound language" ); - s_lip_threshold_1 = Cvar_Get( "s_threshold1", "0.5", 0 ); - s_lip_threshold_2 = Cvar_Get( "s_threshold2", "4.0", 0 ); - s_lip_threshold_3 = Cvar_Get( "s_threshold3", "7.0", 0 ); - s_lip_threshold_4 = Cvar_Get( "s_threshold4", "8.0", 0 ); - s_mixahead = Cvar_Get( "s_mixahead", "0.2", CVAR_ARCHIVE ); - s_mixPreStep = Cvar_Get( "s_mixPreStep", "0.05", CVAR_ARCHIVE ); - s_musicVolume = Cvar_Get( "s_musicvolume", "0.25", CVAR_ARCHIVE, "Music Volume" ); - s_separation = Cvar_Get( "s_separation", "0.5", CVAR_ARCHIVE ); - s_show = Cvar_Get( "s_show", "0", CVAR_CHEAT ); - s_testsound = Cvar_Get( "s_testsound", "0", CVAR_CHEAT ); - s_volume = Cvar_Get( "s_volume", "0.5", CVAR_ARCHIVE, "Volume" ); - s_volumeVoice = Cvar_Get( "s_volumeVoice", "1.0", CVAR_ARCHIVE, "Volume for voice channels" ); + s_allowDynamicMusic = Cvar_Get("s_allowDynamicMusic", "1", CVAR_ARCHIVE_ND); + s_debugdynamic = Cvar_Get("s_debugdynamic", "0", CVAR_CHEAT); + s_doppler = Cvar_Get("s_doppler", "1", CVAR_ARCHIVE_ND); + s_initsound = Cvar_Get("s_initsound", "1", CVAR_ARCHIVE); + s_khz = Cvar_Get("s_khz", "44", CVAR_ARCHIVE | CVAR_LATCH); + s_language = Cvar_Get("s_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, "Sound language"); + s_lip_threshold_1 = Cvar_Get("s_threshold1", "0.5", 0); + s_lip_threshold_2 = Cvar_Get("s_threshold2", "4.0", 0); + s_lip_threshold_3 = Cvar_Get("s_threshold3", "7.0", 0); + s_lip_threshold_4 = Cvar_Get("s_threshold4", "8.0", 0); + s_mixahead = Cvar_Get("s_mixahead", "0.2", CVAR_ARCHIVE); + s_mixPreStep = Cvar_Get("s_mixPreStep", "0.05", CVAR_ARCHIVE); + s_musicVolume = Cvar_Get("s_musicvolume", "0.25", CVAR_ARCHIVE, "Music Volume"); + s_separation = Cvar_Get("s_separation", "0.5", CVAR_ARCHIVE); + s_show = Cvar_Get("s_show", "0", CVAR_CHEAT); + s_testsound = Cvar_Get("s_testsound", "0", CVAR_CHEAT); + s_volume = Cvar_Get("s_volume", "0.5", CVAR_ARCHIVE, "Volume"); + s_volumeVoice = Cvar_Get("s_volumeVoice", "1.0", CVAR_ARCHIVE, "Volume for voice channels"); MP3_InitCvars(); - if ( !s_initsound->integer ) { - s_soundStarted = 0; // needed in case you set s_initsound to 0 midgame then snd_restart (div0 err otherwise later) - Com_Printf ("not initializing.\n"); + if (!s_initsound->integer) { + s_soundStarted = 0; // needed in case you set s_initsound to 0 midgame then snd_restart (div0 err otherwise later) + Com_Printf("not initializing.\n"); Com_Printf("------------------------------------\n"); return; } - Cmd_AddCommand("play", S_Play_f, "Plays a sound fx file" ); - Cmd_AddCommand("music", S_Music_f, "Plays a music file" ); - Cmd_AddCommand("stopmusic", S_StopMusic_f, "Stops all music" ); - Cmd_AddCommand("soundlist", S_SoundList_f, "Lists all cached sound and music files" ); - Cmd_AddCommand("soundinfo", S_SoundInfo_f, "Display information about the sound backend" ); - Cmd_AddCommand("soundstop", S_StopAllSounds, "Stops all sounds including music" ); + Cmd_AddCommand("play", S_Play_f, "Plays a sound fx file"); + Cmd_AddCommand("music", S_Music_f, "Plays a music file"); + Cmd_AddCommand("stopmusic", S_StopMusic_f, "Stops all music"); + Cmd_AddCommand("soundlist", S_SoundList_f, "Lists all cached sound and music files"); + Cmd_AddCommand("soundinfo", S_SoundInfo_f, "Display information about the sound backend"); + Cmd_AddCommand("soundstop", S_StopAllSounds, "Stops all sounds including music"); Cmd_AddCommand("mp3_calcvols", S_MP3_CalcVols_f); - Cmd_AddCommand("s_dynamic", S_SetDynamicMusic_f, "Change dynamic music state" ); + Cmd_AddCommand("s_dynamic", S_SetDynamicMusic_f, "Change dynamic music state"); #ifdef USE_OPENAL - cvar_t *cv = Cvar_Get("s_UseOpenAL" , "0",CVAR_ARCHIVE|CVAR_LATCH); + cvar_t *cv = Cvar_Get("s_UseOpenAL", "0", CVAR_ARCHIVE | CVAR_LATCH); s_UseOpenAL = !!(cv->integer); - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i, j; - ALCdevice *ALCDevice = alcOpenDevice((ALubyte*)"DirectSound3D"); + ALCdevice *ALCDevice = alcOpenDevice((ALubyte *)"DirectSound3D"); if (!ALCDevice) return; - //Create context(s) + // Create context(s) ALCcontext *ALCContext = alcCreateContext(ALCDevice, NULL); if (!ALCContext) return; - //Set active context + // Set active context alcMakeContextCurrent(ALCContext); if (alcGetError(ALCDevice) != ALC_NO_ERROR) return; @@ -517,12 +494,12 @@ void S_Init( void ) { S_SoundInfo_f(); // Set Listener attributes - ALfloat listenerPos[]={0.0,0.0,0.0}; - ALfloat listenerVel[]={0.0,0.0,0.0}; - ALfloat listenerOri[]={0.0,0.0,-1.0, 0.0,1.0,0.0}; - alListenerfv(AL_POSITION,listenerPos); - alListenerfv(AL_VELOCITY,listenerVel); - alListenerfv(AL_ORIENTATION,listenerOri); + ALfloat listenerPos[] = {0.0, 0.0, 0.0}; + ALfloat listenerVel[] = {0.0, 0.0, 0.0}; + ALfloat listenerOri[] = {0.0, 0.0, -1.0, 0.0, 1.0, 0.0}; + alListenerfv(AL_POSITION, listenerPos); + alListenerfv(AL_VELOCITY, listenerVel); + alListenerfv(AL_ORIENTATION, listenerOri); InitEAXManager(); @@ -531,25 +508,21 @@ void S_Init( void ) { s_numChannels = 0; // Create as many AL Sources (up to Max) as possible - for (i = 0; i < MAX_CHANNELS; i++) - { + for (i = 0; i < MAX_CHANNELS; i++) { alGenSources(1, &s_channels[i].alSource); // &g_Sources[i]); - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { // Reached limit of sources break; } alSourcef(s_channels[i].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { break; } // Sources / Channels are not sending to any Slots (other than the Listener / Primary FX Slot) s_channels[i].lSlotID = -1; - if (s_bEAX) - { + if (s_bEAX) { // Remove the RoomAuto flag from each Source (to remove Reverb Engine Statistical // model that is assuming units are in metres) // Without this call reverb sends from the sources will attenuate too quickly @@ -557,8 +530,7 @@ void S_Init( void ) { unsigned long ulFlags = 0; - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_FLAGS, - s_channels[i].alSource, &ulFlags, sizeof(ulFlags)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_FLAGS, s_channels[i].alSource, &ulFlags, sizeof(ulFlags)); } s_numChannels++; @@ -566,10 +538,8 @@ void S_Init( void ) { // Generate AL Buffers for streaming audio playback (used for MP3s) channel_t *ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { alGenBuffers(1, &(ch->buffers[j].BufferID)); ch->buffers[j].Status = UNQUEUED; ch->buffers[j].Data = (char *)Z_Malloc(STREAMING_BUFFER_SIZE, TAG_SND_RAWDATA, qfalse); @@ -606,24 +576,22 @@ void S_Init( void ) { // s_init could be called in game, if so there may be an .eal file // for this level - const char *mapname = Cvar_VariableString( "mapname" ); + const char *mapname = Cvar_VariableString("mapname"); EALFileInit(mapname); - } - else - { + } else { #endif r = SNDDMA_Init(s_khz->integer); - if ( r ) { + if (r) { s_soundStarted = 1; s_soundMuted = qtrue; - // s_numSfx = 0; // do NOT do this here now!!! + // s_numSfx = 0; // do NOT do this here now!!! s_soundtime = 0; s_paintedtime = 0; - S_StopAllSounds (); + S_StopAllSounds(); S_SoundInfo_f(); } @@ -640,17 +608,15 @@ void S_Init( void ) { // only called from snd_restart. QA request... // -void S_ReloadAllUsedSounds(void) -{ - if (s_soundStarted && !s_soundMuted ) - { +void S_ReloadAllUsedSounds(void) { + if (s_soundStarted && !s_soundMuted) { // new bit, reload all soundsthat are used on the current level... // - for (int i=1 ; i < s_numSfx ; i++) // start @ 1 to skip freeing default sound + for (int i = 1; i < s_numSfx; i++) // start @ 1 to skip freeing default sound { sfx_t *sfx = &s_knownSfx[i]; - if (!sfx->bInMemory && !sfx->bDefaultSound && sfx->iLastLevelUsedOn == re->RegisterMedia_GetLevel()){ + if (!sfx->bInMemory && !sfx->bDefaultSound && sfx->iLastLevelUsedOn == re->RegisterMedia_GetLevel()) { S_memoryLoad(sfx); } } @@ -661,9 +627,8 @@ void S_ReloadAllUsedSounds(void) // Shutdown sound engine // ======================================================================= -void S_Shutdown( void ) -{ - if ( !s_soundStarted ) { +void S_Shutdown(void) { + if (!s_soundStarted) { return; } @@ -671,26 +636,21 @@ void S_Shutdown( void ) S_UnCacheDynamicMusic(); #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i, j; // Release all the AL Sources (including Music channel (Source 0)) - for (i = 0; i < s_numChannels; i++) - { + for (i = 0; i < s_numChannels; i++) { alDeleteSources(1, &(s_channels[i].alSource)); } // Release Streaming AL Buffers channel_t *ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { alDeleteBuffers(1, &(ch->buffers[j].BufferID)); ch->buffers[j].BufferID = 0; ch->buffers[j].Status = UNQUEUED; - if (ch->buffers[j].Data) - { + if (ch->buffers[j].Data) { Z_Free(ch->buffers[j].Data); ch->buffers[j].Data = NULL; } @@ -710,9 +670,7 @@ void S_Shutdown( void ) s_numChannels = 0; - } - else - { + } else { #endif SNDDMA_Shutdown(); #ifdef USE_OPENAL @@ -737,22 +695,18 @@ void S_Shutdown( void ) Mutes / Unmutes all OpenAL sound */ #ifdef USE_OPENAL -void S_AL_MuteAllSounds(qboolean bMute) -{ - if (!s_soundStarted) - return; - - if (!s_UseOpenAL) - return; - - if (bMute) - { - alListenerf(AL_GAIN, 0.0f); - } - else - { - alListenerf(AL_GAIN, 1.0f); - } +void S_AL_MuteAllSounds(qboolean bMute) { + if (!s_soundStarted) + return; + + if (!s_UseOpenAL) + return; + + if (bMute) { + alListenerf(AL_GAIN, 0.0f); + } else { + alListenerf(AL_GAIN, 1.0f); + } } #endif @@ -765,20 +719,22 @@ return a hash value for the sfx name ================ */ static long S_HashSFXName(const char *name) { - int i; - long hash; - char letter; + int i; + long hash; + char letter; hash = 0; i = 0; while (name[i] != '\0') { letter = tolower(name[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (LOOP_HASH-1); + hash &= (LOOP_HASH - 1); return hash; } @@ -789,59 +745,57 @@ S_FindName Will allocate a new sfx if it isn't found ================== */ -sfx_t *S_FindName( const char *name ) { - int i; - int hash; +sfx_t *S_FindName(const char *name) { + int i; + int hash; - sfx_t *sfx; + sfx_t *sfx; if (!name) { - Com_Error (ERR_FATAL, "S_FindName: NULL"); + Com_Error(ERR_FATAL, "S_FindName: NULL"); } if (!name[0]) { - Com_Error (ERR_FATAL, "S_FindName: empty name"); + Com_Error(ERR_FATAL, "S_FindName: empty name"); } if (strlen(name) >= MAX_QPATH) { - Com_Error (ERR_FATAL, "Sound name too long: %s", name); + Com_Error(ERR_FATAL, "Sound name too long: %s", name); } char sSoundNameNoExt[MAX_QPATH]; - COM_StripExtension(name,sSoundNameNoExt, sizeof( sSoundNameNoExt )); + COM_StripExtension(name, sSoundNameNoExt, sizeof(sSoundNameNoExt)); hash = S_HashSFXName(sSoundNameNoExt); sfx = sfxHash[hash]; // see if already loaded while (sfx) { - if (!Q_stricmp(sfx->sSoundName, sSoundNameNoExt) ) { + if (!Q_stricmp(sfx->sSoundName, sSoundNameNoExt)) { return sfx; } sfx = sfx->next; } -/* - // find a free sfx - for (i=0 ; i < s_numSfx ; i++) { - if (!s_knownSfx[i].soundName[0]) { - break; + /* + // find a free sfx + for (i=0 ; i < s_numSfx ; i++) { + if (!s_knownSfx[i].soundName[0]) { + break; + } } - } -*/ - i = s_numSfx; //we don't clear the soundName after failed loads any more, so it'll always be the last entry + */ + i = s_numSfx; // we don't clear the soundName after failed loads any more, so it'll always be the last entry - if (s_numSfx == MAX_SFX) - { + if (s_numSfx == MAX_SFX) { // ok, no sfx's free, but are there any with defaultSound set? (which the registering ent will never // see because he gets zero returned if it's default...) // - for (i=0 ; i < s_numSfx ; i++) { + for (i = 0; i < s_numSfx; i++) { if (s_knownSfx[i].bDefaultSound) { break; } } - if (i==s_numSfx) - { + if (i == s_numSfx) { // genuinely out of handles... // if we ever reach this, let me know and I'll either boost the array or put in a map-used-on @@ -850,18 +804,16 @@ sfx_t *S_FindName( const char *name ) { // events, so current MAX_SFX limit should do, or only need a small boost... -ste // - Com_Error (ERR_FATAL, "S_FindName: out of sfx_t"); + Com_Error(ERR_FATAL, "S_FindName: out of sfx_t"); } - } - else - { + } else { s_numSfx++; } sfx = &s_knownSfx[i]; - memset (sfx, 0, sizeof(*sfx)); + memset(sfx, 0, sizeof(*sfx)); Q_strncpyz(sfx->sSoundName, sSoundNameNoExt, sizeof(sfx->sSoundName)); - Q_strlwr(sfx->sSoundName);//force it down low + Q_strlwr(sfx->sSoundName); // force it down low sfx->next = sfxHash[hash]; sfxHash[hash] = sfx; @@ -874,16 +826,15 @@ sfx_t *S_FindName( const char *name ) { S_DefaultSound ================= */ -void S_DefaultSound( sfx_t *sfx ) { +void S_DefaultSound(sfx_t *sfx) { - int i; + int i; - sfx->iSoundLengthInSamples = 512; // #samples, ie shorts - sfx->pSoundData = (short *) SND_malloc(512*2, sfx); // ... so *2 for alloc bytes - sfx->bInMemory = qtrue; + sfx->iSoundLengthInSamples = 512; // #samples, ie shorts + sfx->pSoundData = (short *)SND_malloc(512 * 2, sfx); // ... so *2 for alloc bytes + sfx->bInMemory = qtrue; - for ( i=0 ; i < sfx->iSoundLengthInSamples ; i++ ) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i++) { sfx->pSoundData[i] = i; } } @@ -897,7 +848,7 @@ This is called when the hunk is cleared and the sounds are no longer valid. =================== */ -void S_DisableSounds( void ) { +void S_DisableSounds(void) { S_StopAllSounds(); s_soundMuted = qtrue; } @@ -908,19 +859,16 @@ S_BeginRegistration ===================== */ -void S_BeginRegistration( void ) -{ - s_soundMuted = qfalse; // we can play again +void S_BeginRegistration(void) { + s_soundMuted = qfalse; // we can play again #ifdef USE_OPENAL // Find name of level so we can load in the appropriate EAL file - if (s_UseOpenAL) - { - const char *mapname = Cvar_VariableString( "mapname" ); + if (s_UseOpenAL) { + const char *mapname = Cvar_VariableString("mapname"); EALFileInit(mapname); // clear carry crap from previous map - for (int i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (int i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].lEnvID = -1; } } @@ -930,12 +878,12 @@ void S_BeginRegistration( void ) SND_setup(); s_numSfx = 0; - memset( s_knownSfx, 0, sizeof( s_knownSfx ) ); - memset(sfxHash, 0, sizeof(sfx_t *)*LOOP_HASH); + memset(s_knownSfx, 0, sizeof(s_knownSfx)); + memset(sfxHash, 0, sizeof(sfx_t *) * LOOP_HASH); #ifdef _DEBUG - sfx_t *sfx = S_FindName( "***DEFAULT***" ); - S_DefaultSound( sfx ); + sfx_t *sfx = S_FindName("***DEFAULT***"); + S_DefaultSound(sfx); #else S_RegisterSound("sound/null.wav"); #endif @@ -943,11 +891,9 @@ void S_BeginRegistration( void ) } #ifdef USE_OPENAL -void EALFileInit(const char *level) -{ +void EALFileInit(const char *level) { // If an EAL File is already unloaded, remove it - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { UnloadEALFile(); } @@ -955,33 +901,26 @@ void EALFileInit(const char *level) s_bInWater = false; // Try and load an EAL file for the new level - char name[MAX_QPATH]; - char szEALFilename[MAX_QPATH]; - COM_StripExtension(level, name, sizeof( name )); + char name[MAX_QPATH]; + char szEALFilename[MAX_QPATH]; + COM_StripExtension(level, name, sizeof(name)); Com_sprintf(szEALFilename, MAX_QPATH, "eagle/%s.eal", name); s_bEALFileLoaded = LoadEALFile(szEALFilename); - if (!s_bEALFileLoaded) - { + if (!s_bEALFileLoaded) { Com_sprintf(szEALFilename, MAX_QPATH, "base/eagle/%s.eal", name); s_bEALFileLoaded = LoadEALFile(szEALFilename); } - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { s_lLastEnvUpdate = timeGetTime(); - } - else - { + } else { // Mute reverbs if no EAL file is found - if ((s_bEAX)&&(s_eaxSet)) - { + if ((s_bEAX) && (s_eaxSet)) { long lRoom = -10000; - for (int i = 0; i < s_NumFXSlots; i++) - { - s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_ROOM, NULL, - &lRoom, sizeof(long)); + for (int i = 0; i < s_NumFXSlots; i++) { + s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_ROOM, NULL, &lRoom, sizeof(long)); } } } @@ -995,37 +934,33 @@ S_RegisterSound Creates a default buzz sound if the file can't be loaded ================== */ -sfxHandle_t S_RegisterSound( const char *name) -{ - sfx_t *sfx; +sfxHandle_t S_RegisterSound(const char *name) { + sfx_t *sfx; if (!s_soundStarted) { return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( S_COLOR_RED"Sound name exceeds MAX_QPATH - %s\n", name ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf(S_COLOR_RED "Sound name exceeds MAX_QPATH - %s\n", name); return 0; } - sfx = S_FindName( name ); + sfx = S_FindName(name); SND_TouchSFX(sfx); - if ( sfx->bDefaultSound ) + if (sfx->bDefaultSound) return 0; #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if ((sfx->pSoundData) || (sfx->Buffer)) return sfx - s_knownSfx; - } - else + } else #endif { - if ( sfx->pSoundData ) - { + if (sfx->pSoundData) { return sfx - s_knownSfx; } } @@ -1034,11 +969,10 @@ sfxHandle_t S_RegisterSound( const char *name) S_memoryLoad(sfx); - if ( sfx->bDefaultSound ) { + if (sfx->bDefaultSound) { #ifndef FINAL_BUILD - if (!s_shutUp) - { - Com_Printf( S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->sSoundName ); + if (!s_shutUp) { + Com_Printf(S_COLOR_YELLOW "WARNING: could not find %s - using default\n", sfx->sSoundName); } #endif return 0; @@ -1047,33 +981,29 @@ sfxHandle_t S_RegisterSound( const char *name) return sfx - s_knownSfx; } -void S_memoryLoad(sfx_t *sfx) -{ +void S_memoryLoad(sfx_t *sfx) { // load the sound file... // - if ( !S_LoadSound( sfx ) ) - { -// Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->sSoundName ); + if (!S_LoadSound(sfx)) { + // Com_Printf( S_COLOR_YELLOW "WARNING: couldn't load sound: %s\n", sfx->sSoundName ); sfx->bDefaultSound = qtrue; } sfx->bInMemory = qtrue; } //============================================================================= -static qboolean S_CheckChannelStomp( int chan1, int chan2 ) -{ +static qboolean S_CheckChannelStomp(int chan1, int chan2) { #ifdef USE_OPENAL if (!s_UseOpenAL) #endif { - if ( chan1 == chan2 ) - { + if (chan1 == chan2) { return qtrue; } } - if ( ( chan1 == CHAN_VOICE || chan1 == CHAN_VOICE_ATTEN || chan1 == CHAN_VOICE_GLOBAL ) && ( chan2 == CHAN_VOICE || chan2 == CHAN_VOICE_ATTEN || chan2 == CHAN_VOICE_GLOBAL ) ) - { + if ((chan1 == CHAN_VOICE || chan1 == CHAN_VOICE_ATTEN || chan1 == CHAN_VOICE_GLOBAL) && + (chan2 == CHAN_VOICE || chan2 == CHAN_VOICE_ATTEN || chan2 == CHAN_VOICE_GLOBAL)) { return qtrue; } @@ -1085,44 +1015,37 @@ static qboolean S_CheckChannelStomp( int chan1, int chan2 ) S_PickChannel ================= */ -channel_t *S_PickChannel(int entnum, int entchannel) -{ - int ch_idx; - channel_t *ch, *firstToDie; - qboolean foundChan = qfalse; +channel_t *S_PickChannel(int entnum, int entchannel) { + int ch_idx; + channel_t *ch, *firstToDie; + qboolean foundChan = qfalse; #ifdef USE_OPENAL if (s_UseOpenAL) return S_OpenALPickChannel(entnum, entchannel); #endif - if ( entchannel<0 ) { - Com_Error (ERR_DROP, "S_PickChannel: entchannel<0"); + if (entchannel < 0) { + Com_Error(ERR_DROP, "S_PickChannel: entchannel<0"); } // Check for replacement sound, or find the best one to replace - firstToDie = &s_channels[0]; + firstToDie = &s_channels[0]; - for ( int pass = 0; (pass < ((entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN)?1:2)) && !foundChan; pass++ ) - { - for (ch_idx = 0, ch = &s_channels[0]; ch_idx < MAX_CHANNELS ; ch_idx++, ch++ ) - { - if ( entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN || pass > 0 ) - {//if we're on the second pass, just find the first open chan - if ( !ch->thesfx ) - {//grab the first open channel + for (int pass = 0; (pass < ((entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN) ? 1 : 2)) && !foundChan; pass++) { + for (ch_idx = 0, ch = &s_channels[0]; ch_idx < MAX_CHANNELS; ch_idx++, ch++) { + if (entchannel == CHAN_AUTO || entchannel == CHAN_LESS_ATTEN || pass > 0) { // if we're on the second pass, just find the first open chan + if (!ch->thesfx) { // grab the first open channel firstToDie = ch; break; } - } - else if ( ch->entnum == entnum && S_CheckChannelStomp( ch->entchannel, entchannel ) ) - { + } else if (ch->entnum == entnum && S_CheckChannelStomp(ch->entchannel, entchannel)) { // always override sound from same entity - if ( s_show->integer == 1 && ch->thesfx ) { - Com_Printf( S_COLOR_YELLOW"...overrides %s\n", ch->thesfx->sSoundName ); - ch->thesfx = 0; //just to clear the next error msg + if (s_show->integer == 1 && ch->thesfx) { + Com_Printf(S_COLOR_YELLOW "...overrides %s\n", ch->thesfx->sSoundName); + ch->thesfx = 0; // just to clear the next error msg } firstToDie = ch; foundChan = qtrue; @@ -1130,26 +1053,26 @@ channel_t *S_PickChannel(int entnum, int entchannel) } // don't let anything else override local player sounds - if ( ch->entnum == listener_number && entnum != listener_number && ch->thesfx) { + if (ch->entnum == listener_number && entnum != listener_number && ch->thesfx) { continue; } // don't override loop sounds - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } - if ( ch->startSample < firstToDie->startSample ) { + if (ch->startSample < firstToDie->startSample) { firstToDie = ch; } } } - if ( s_show->integer == 1 && firstToDie->thesfx ) { - Com_Printf( S_COLOR_RED"***kicking %s\n", firstToDie->thesfx->sSoundName ); + if (s_show->integer == 1 && firstToDie->thesfx) { + Com_Printf(S_COLOR_RED "***kicking %s\n", firstToDie->thesfx->sSoundName); } - Channel_Clear(firstToDie); // memset(firstToDie, 0, sizeof(*firstToDie)); + Channel_Clear(firstToDie); // memset(firstToDie, 0, sizeof(*firstToDie)); return firstToDie; } @@ -1161,30 +1084,26 @@ channel_t *S_PickChannel(int entnum, int entchannel) on hardware this way esp. rapid fire modes of weapons! */ #ifdef USE_OPENAL -channel_t *S_OpenALPickChannel(int entnum, int entchannel) -{ - int ch_idx; - channel_t *ch, *ch_firstToDie; - bool foundChan = false; - float source_pos[3]; - - if ( entchannel < 0 ) - { - Com_Error (ERR_DROP, "S_PickChannel: entchannel<0"); +channel_t *S_OpenALPickChannel(int entnum, int entchannel) { + int ch_idx; + channel_t *ch, *ch_firstToDie; + bool foundChan = false; + float source_pos[3]; + + if (entchannel < 0) { + Com_Error(ERR_DROP, "S_PickChannel: entchannel<0"); } // Check for replacement sound, or find the best one to replace - ch_firstToDie = s_channels + 1; // channel 0 is reserved for Music + ch_firstToDie = s_channels + 1; // channel 0 is reserved for Music - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if ( ch->entnum == entnum && S_CheckChannelStomp( ch->entchannel, entchannel ) ) - { + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if (ch->entnum == entnum && S_CheckChannelStomp(ch->entchannel, entchannel)) { // always override sound from same entity - if ( s_show->integer == 1 && ch->thesfx ) { - Com_Printf( S_COLOR_YELLOW"...overrides %s\n", ch->thesfx->sSoundName ); - ch->thesfx = 0; //just to clear the next error msg + if (s_show->integer == 1 && ch->thesfx) { + Com_Printf(S_COLOR_YELLOW "...overrides %s\n", ch->thesfx->sSoundName); + ch->thesfx = 0; // just to clear the next error msg } ch_firstToDie = ch; foundChan = true; @@ -1193,24 +1112,18 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } if (!foundChan) - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - // See if the channel is free - if (!ch->thesfx) - { - ch_firstToDie = ch; - foundChan = true; - break; + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + // See if the channel is free + if (!ch->thesfx) { + ch_firstToDie = ch; + foundChan = true; + break; + } } - } - if (!foundChan) - { - for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if ( (ch->entnum == entnum) && (ch->entchannel == entchannel) && (ch->entchannel != CHAN_AMBIENT) - && (ch->entnum != listener_number) ) - { + if (!foundChan) { + for (ch_idx = 1, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if ((ch->entnum == entnum) && (ch->entchannel == entchannel) && (ch->entchannel != CHAN_AMBIENT) && (ch->entnum != listener_number)) { // Same entity and same type of sound effect (entchannel) ch_firstToDie = ch; foundChan = true; @@ -1222,13 +1135,11 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) int longestDist; int dist; - if (!foundChan) - { + if (!foundChan) { // Find sound effect furthest from listener ch = s_channels + 1; - if (ch->fixed_origin) - { + if (ch->fixed_origin) { // Convert to Open AL co-ordinates source_pos[0] = ch->origin[0]; source_pos[1] = ch->origin[2]; @@ -1237,22 +1148,16 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) longestDist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); - } - else - { + } else { if (ch->entnum == listener_number) longestDist = 0; - else - { - if (ch->bLooping) - { + else { + if (ch->bLooping) { // Convert to Open AL co-ordinates source_pos[0] = loopSounds[ch->entnum].origin[0]; source_pos[1] = loopSounds[ch->entnum].origin[2]; source_pos[2] = -loopSounds[ch->entnum].origin[1]; - } - else - { + } else { // Convert to Open AL co-ordinates source_pos[0] = s_entityPosition[ch->entnum][0]; source_pos[1] = s_entityPosition[ch->entnum][2]; @@ -1265,10 +1170,8 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } } - for (ch_idx = 2, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) - { - if (ch->fixed_origin) - { + for (ch_idx = 2, ch = s_channels + ch_idx; ch_idx < s_numChannels; ch_idx++, ch++) { + if (ch->fixed_origin) { // Convert to Open AL co-ordinates source_pos[0] = ch->origin[0]; source_pos[1] = ch->origin[2]; @@ -1277,22 +1180,16 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) dist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); - } - else - { + } else { if (ch->entnum == listener_number) dist = 0; - else - { - if (ch->bLooping) - { + else { + if (ch->bLooping) { // Convert to Open AL co-ordinates source_pos[0] = loopSounds[ch->entnum].origin[0]; source_pos[1] = loopSounds[ch->entnum].origin[2]; source_pos[2] = -loopSounds[ch->entnum].origin[1]; - } - else - { + } else { // Convert to Open AL co-ordinates source_pos[0] = s_entityPosition[ch->entnum][0]; source_pos[1] = s_entityPosition[ch->entnum][2]; @@ -1300,24 +1197,21 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) } dist = ((listener_pos[0] - source_pos[0]) * (listener_pos[0] - source_pos[0])) + - ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + + ((listener_pos[1] - source_pos[1]) * (listener_pos[1] - source_pos[1])) + ((listener_pos[2] - source_pos[2]) * (listener_pos[2] - source_pos[2])); } } - if (dist > longestDist) - { + if (dist > longestDist) { longestDist = dist; ch_firstToDie = ch; } } } - if (ch_firstToDie->bPlaying) - { - if (s_show->integer == 1 && ch_firstToDie->thesfx ) - { - Com_Printf(S_COLOR_RED"***kicking %s\n", ch_firstToDie->thesfx->sSoundName ); + if (ch_firstToDie->bPlaying) { + if (s_show->integer == 1 && ch_firstToDie->thesfx) { + Com_Printf(S_COLOR_RED "***kicking %s\n", ch_firstToDie->thesfx->sSoundName); } // Stop sound @@ -1331,7 +1225,7 @@ channel_t *S_OpenALPickChannel(int entnum, int entchannel) ch_firstToDie->bProcessed = false; ch_firstToDie->bStreaming = false; - return ch_firstToDie; + return ch_firstToDie; } #endif @@ -1342,82 +1236,67 @@ S_SpatializeOrigin Used for spatializing s_channels ================= */ -void S_SpatializeOrigin (const vec3_t origin, float master_vol, int *left_vol, int *right_vol, int channel) -{ - float dot; - float dist; - float lscale, rscale, scale; - vec3_t source_vec; - float dist_mult = SOUND_ATTENUATE; +void S_SpatializeOrigin(const vec3_t origin, float master_vol, int *left_vol, int *right_vol, int channel) { + float dot; + float dist; + float lscale, rscale, scale; + vec3_t source_vec; + float dist_mult = SOUND_ATTENUATE; // calculate stereo seperation and distance attenuation VectorSubtract(origin, listener_origin, source_vec); dist = VectorNormalize(source_vec); - if ( channel == CHAN_VOICE ) - { + if (channel == CHAN_VOICE) { dist -= SOUND_FULLVOLUME * 3.0f; -// dist_mult = VOICE_ATTENUATE; // tweak added (this fixes an NPC dialogue "in your ears" bug, but we're not sure if it'll make a bunch of others fade too early. Too close to shipping...) - } - else if ( channel == CHAN_LESS_ATTEN ) - { + // dist_mult = VOICE_ATTENUATE; // tweak added (this fixes an NPC dialogue "in your ears" bug, but we're not sure if it'll make a bunch of others + //fade too early. Too close to shipping...) + } else if (channel == CHAN_LESS_ATTEN) { dist -= SOUND_FULLVOLUME * 8.0f; // maybe is too large - } - else if ( channel == CHAN_VOICE_ATTEN ) - { + } else if (channel == CHAN_VOICE_ATTEN) { dist -= SOUND_FULLVOLUME * 1.35f; // used to be 0.15f, dropped off too sharply - dmv dist_mult = VOICE_ATTENUATE; - } - else if ( channel == CHAN_VOICE_GLOBAL ) - { + } else if (channel == CHAN_VOICE_GLOBAL) { dist = -1; - } - else // use normal attenuation. + } else // use normal attenuation. { dist -= SOUND_FULLVOLUME; } - if (dist < 0) - { - dist = 0; // close enough to be at full volume + if (dist < 0) { + dist = 0; // close enough to be at full volume } - dist *= dist_mult; // different attenuation levels + dist *= dist_mult; // different attenuation levels dot = -DotProduct(listener_axis[1], source_vec); - if (dma.channels == 1) // || !dist_mult) - { // no attenuation = no spatialization + if (dma.channels == 1) // || !dist_mult) + { // no attenuation = no spatialization rscale = SOUND_FMAXVOL; lscale = SOUND_FMAXVOL; - } - else - { - //rscale = 0.5 * (1.0 + dot); - //lscale = 0.5 * (1.0 - dot); - rscale = s_separation->value + ( 1.0f - s_separation->value ) * dot; - lscale = s_separation->value - ( 1.0f - s_separation->value ) * dot; - if ( rscale < 0 ) - { + } else { + // rscale = 0.5 * (1.0 + dot); + // lscale = 0.5 * (1.0 - dot); + rscale = s_separation->value + (1.0f - s_separation->value) * dot; + lscale = s_separation->value - (1.0f - s_separation->value) * dot; + if (rscale < 0) { rscale = 0; } - if ( lscale < 0 ) - { + if (lscale < 0) { lscale = 0; } } // add in distance effect scale = (1.0f - dist) * rscale; - *right_vol = (int) (master_vol * scale); - if (*right_vol < 0) - { + *right_vol = (int)(master_vol * scale); + if (*right_vol < 0) { *right_vol = 0; } scale = (1.0f - dist) * lscale; - *left_vol = (int) (master_vol * scale); - if (*left_vol < 0) - { + *left_vol = (int)(master_vol * scale); + if (*left_vol < 0) { *left_vol = 0; } } @@ -1434,51 +1313,46 @@ Starts an ambient, 'one-shot" sound. ==================== */ -void S_StartAmbientSound( const vec3_t origin, int entityNum, unsigned char volume, sfxHandle_t sfxHandle ) -{ - channel_t *ch; +void S_StartAmbientSound(const vec3_t origin, int entityNum, unsigned char volume, sfxHandle_t sfxHandle) { + channel_t *ch; /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( !origin && ( entityNum < 0 || entityNum >= MAX_GENTITIES ) ) - Com_Error( ERR_DROP, "S_StartAmbientSound: bad entitynum %i", entityNum ); + if (!origin && (entityNum < 0 || entityNum >= MAX_GENTITIES)) + Com_Error(ERR_DROP, "S_StartAmbientSound: bad entitynum %i", entityNum); - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) - Com_Error( ERR_DROP, "S_StartAmbientSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) + Com_Error(ERR_DROP, "S_StartAmbientSound: handle %i out of range", sfxHandle); - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if (volume==0) + if (s_UseOpenAL) { + if (volume == 0) return; } #endif - if ( s_show->integer == 1 ) { - Com_Printf( "%i : %s on (%d) Ambient\n", s_paintedtime, sfx->sSoundName, entityNum ); + if (s_show->integer == 1) { + Com_Printf("%i : %s on (%d) Ambient\n", s_paintedtime, sfx->sSoundName, entityNum); } // pick a channel to play on - ch = S_PickChannel( entityNum, CHAN_AMBIENT ); + ch = S_PickChannel(entityNum, CHAN_AMBIENT); if (!ch) { return; } - if (origin) - { - VectorCopy (origin, ch->origin); + if (origin) { + VectorCopy(origin, ch->origin); ch->fixed_origin = qtrue; - } - else - { + } else { ch->fixed_origin = qfalse; } @@ -1488,18 +1362,15 @@ void S_StartAmbientSound( const vec3_t origin, int entityNum, unsigned char volu ch->thesfx = sfx; ch->startSample = START_SAMPLE_IMMEDIATE; - ch->leftvol = ch->master_vol; // these will get calced at next spatialize - ch->rightvol = ch->master_vol; // unless the game isn't running + ch->leftvol = ch->master_vol; // these will get calced at next spatialize + ch->rightvol = ch->master_vol; // unless the game isn't running - if (sfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader,sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); - //ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... - //ch->iMP3SlidingDecodeWindowPos= 0; // - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (sfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + // ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... + // ch->iMP3SlidingDecodeWindowPos= 0; // + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } @@ -1510,13 +1381,11 @@ S_MuteSound Mutes sound on specified channel for specified entity. ==================== */ -void S_MuteSound(int entityNum, int entchannel) -{ - //I guess this works. - channel_t *ch = S_PickChannel( entityNum, entchannel ); +void S_MuteSound(int entityNum, int entchannel) { + // I guess this works. + channel_t *ch = S_PickChannel(entityNum, entchannel); - if (!ch) - { + if (!ch) { return; } @@ -1539,45 +1408,40 @@ if pos is NULL, the sound will be dynamically sourced from the entity entchannel 0 will never override a playing sound ==================== */ -void S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfxHandle ) -{ - channel_t *ch; +void S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfxHandle) { + channel_t *ch; /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( !origin && ( entityNum < 0 || entityNum >= MAX_GENTITIES ) ) { - Com_Error( ERR_DROP, "S_StartSound: bad entitynum %i", entityNum ); + if (!origin && (entityNum < 0 || entityNum >= MAX_GENTITIES)) { + Com_Error(ERR_DROP, "S_StartSound: bad entitynum %i", entityNum); } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( s_show->integer == 1 ) { - Com_Printf( "%i : %s on (%d)\n", s_paintedtime, sfx->sSoundName, entityNum ); + if (s_show->integer == 1) { + Com_Printf("%i : %s on (%d)\n", s_paintedtime, sfx->sSoundName, entityNum); } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i; - if (entchannel == CHAN_WEAPON) - { + if (entchannel == CHAN_WEAPON) { // Check if we are playing a 'charging' sound, if so, stop it now .. ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->entnum == entityNum) && (ch->entchannel == CHAN_WEAPON) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "altcharge") != NULL)) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->entnum == entityNum) && (ch->entchannel == CHAN_WEAPON) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "altcharge") != NULL)) { // Stop this sound alSourceStop(ch->alSource); alSourcei(ch->alSource, AL_BUFFER, NULL); @@ -1586,14 +1450,10 @@ void S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_ break; } } - } - else - { + } else { ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->entnum == entityNum) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "falling") != NULL)) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->entnum == entityNum) && (ch->thesfx) && (strstr(ch->thesfx->sSoundName, "falling") != NULL)) { // Stop this sound alSourceStop(ch->alSource); alSourcei(ch->alSource, AL_BUFFER, NULL); @@ -1608,44 +1468,40 @@ void S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_ // pick a channel to play on - ch = S_PickChannel( entityNum, entchannel ); + ch = S_PickChannel(entityNum, entchannel); if (!ch) { return; } if (origin) { - VectorCopy (origin, ch->origin); + VectorCopy(origin, ch->origin); ch->fixed_origin = qtrue; } else { ch->fixed_origin = qfalse; } - ch->master_vol = SOUND_MAXVOL; //FIXME: Um.. control? + ch->master_vol = SOUND_MAXVOL; // FIXME: Um.. control? ch->entnum = entityNum; ch->entchannel = entchannel; ch->thesfx = sfx; ch->startSample = START_SAMPLE_IMMEDIATE; - ch->leftvol = ch->master_vol; // these will get calced at next spatialize - ch->rightvol = ch->master_vol; // unless the game isn't running + ch->leftvol = ch->master_vol; // these will get calced at next spatialize + ch->rightvol = ch->master_vol; // unless the game isn't running - if (entchannel < CHAN_AMBIENT && entityNum == listener_number) { //only do it for body sounds not local sounds - ch->master_vol = SOUND_MAXVOL * SOUND_FMAXVOL; //this won't be attenuated so let it scale down + if (entchannel < CHAN_AMBIENT && entityNum == listener_number) { // only do it for body sounds not local sounds + ch->master_vol = SOUND_MAXVOL * SOUND_FMAXVOL; // this won't be attenuated so let it scale down } - if ( entchannel == CHAN_VOICE || entchannel == CHAN_VOICE_ATTEN || entchannel == CHAN_VOICE_GLOBAL ) - { - s_entityWavVol[ ch->entnum ] = -1; //we've started the sound but it's silent for now + if (entchannel == CHAN_VOICE || entchannel == CHAN_VOICE_ATTEN || entchannel == CHAN_VOICE_GLOBAL) { + s_entityWavVol[ch->entnum] = -1; // we've started the sound but it's silent for now } - if (sfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader,sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); - //ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... - //ch->iMP3SlidingDecodeWindowPos= 0; // - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (sfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, sfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + // ch->iMP3SlidingDecodeWritePos = 0; // These will be zero from the memset in S_PickChannel(), but keep them here for reference... + // ch->iMP3SlidingDecodeWindowPos= 0; // + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } @@ -1654,61 +1510,56 @@ void S_StartSound(const vec3_t origin, int entityNum, int entchannel, sfxHandle_ S_StartLocalSound ================== */ -void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) { - if ( !s_soundStarted || s_soundMuted ) { +void S_StartLocalSound(sfxHandle_t sfxHandle, int channelNum) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartLocalSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartLocalSound: handle %i out of range", sfxHandle); } - S_StartSound (NULL, listener_number, channelNum, sfxHandle ); + S_StartSound(NULL, listener_number, channelNum, sfxHandle); } - /* ================== S_StartLocalLoopingSound ================== */ -void S_StartLocalLoopingSound( sfxHandle_t sfxHandle) { - vec3_t nullVec = {0,0,0}; +void S_StartLocalLoopingSound(sfxHandle_t sfxHandle) { + vec3_t nullVec = {0, 0, 0}; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartLocalLoopingSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartLocalLoopingSound: handle %i out of range", sfxHandle); } - S_AddLoopingSound( listener_number, nullVec, nullVec, sfxHandle ); - + S_AddLoopingSound(listener_number, nullVec, nullVec, sfxHandle); } // returns length in milliseconds of supplied sound effect... (else 0 for bad handle now) // -float S_GetSampleLengthInMilliSeconds( sfxHandle_t sfxHandle) -{ +float S_GetSampleLengthInMilliSeconds(sfxHandle_t sfxHandle) { sfx_t *sfx; - if (!s_soundStarted) - { //we have no sound, so let's just make a reasonable guess + if (!s_soundStarted) { // we have no sound, so let's just make a reasonable guess return 512 * 1000; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) + if (sfxHandle < 0 || sfxHandle >= s_numSfx) return 0.0f; - sfx = &s_knownSfx[ sfxHandle ]; + sfx = &s_knownSfx[sfxHandle]; float f = (float)sfx->iSoundLengthInSamples / (float)dma.speed; return (f * 1000); } - /* ================== S_ClearSoundBuffer @@ -1717,13 +1568,13 @@ If we are about to perform file access, clear the buffer so sound doesn't stutter. ================== */ -void S_ClearSoundBuffer( void ) { - int clear; +void S_ClearSoundBuffer(void) { + int clear; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } -#if 0 //this causes scripts to freak when the sounds get cut... +#if 0 // this causes scripts to freak when the sounds get cut... // clear all the sounds so they don't // start back up after the load finishes memset( s_channels, 0, sizeof( s_channels ) ); @@ -1741,47 +1592,41 @@ void S_ClearSoundBuffer( void ) { else clear = 0; - SNDDMA_BeginPainting (); + SNDDMA_BeginPainting(); if (dma.buffer) - memset(dma.buffer, clear, dma.samples * dma.samplebits/8); - SNDDMA_Submit (); + memset(dma.buffer, clear, dma.samples * dma.samplebits / 8); + SNDDMA_Submit(); } #ifdef USE_OPENAL - else - { + else { s_paintedtime = 0; s_soundtime = 0; } #endif } - // kinda kludgy way to stop a special-use sfx_t playing... // -void S_CIN_StopSound(sfxHandle_t sfxHandle) -{ - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_CIN_StopSound: handle %i out of range", sfxHandle ); +void S_CIN_StopSound(sfxHandle_t sfxHandle) { + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_CIN_StopSound: handle %i out of range", sfxHandle); } - sfx_t *sfx = &s_knownSfx[ sfxHandle ]; + sfx_t *sfx = &s_knownSfx[sfxHandle]; channel_t *ch = s_channels; int i; - for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) - { - if ( !ch->thesfx || (ch->leftvol<0.25 && ch->rightvol<0.25 )) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx || (ch->leftvol < 0.25 && ch->rightvol < 0.25)) { continue; } - if (ch->thesfx == sfx) - { + if (ch->thesfx == sfx) { #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { alSourceStop(s_channels[i].alSource); } #endif - SND_FreeSFXMem(ch->thesfx); // heh, may as well... + SND_FreeSFXMem(ch->thesfx); // heh, may as well... ch->thesfx = NULL; memset(&ch->MP3StreamHeader, 0, sizeof(MP3STREAM)); ch->bLooping = false; @@ -1793,16 +1638,14 @@ void S_CIN_StopSound(sfxHandle_t sfxHandle) } } - /* ================== S_StopAllSounds ================== */ -void S_StopSounds(void) -{ +void S_StopSounds(void) { - if ( !s_soundStarted ) { + if (!s_soundStarted) { return; } @@ -1811,12 +1654,10 @@ void S_StopSounds(void) #ifdef USE_OPENAL // clear all the s_channels - if (s_UseOpenAL) - { + if (s_UseOpenAL) { int i; //, j; channel_t *ch = s_channels; - for (i = 0; i < s_numChannels; i++, ch++) - { + for (i = 0; i < s_numChannels; i++, ch++) { alSourceStop(s_channels[i].alSource); alSourcei(s_channels[i].alSource, AL_BUFFER, NULL); ch->thesfx = NULL; @@ -1826,9 +1667,7 @@ void S_StopSounds(void) ch->bPlaying = false; ch->bStreaming = false; } - } - else - { + } else { #endif memset(s_channels, 0, sizeof(s_channels)); #ifdef USE_OPENAL @@ -1836,9 +1675,9 @@ void S_StopSounds(void) #endif // clear out the lip synching override array - memset(s_entityWavVol, 0,sizeof(s_entityWavVol)); + memset(s_entityWavVol, 0, sizeof(s_entityWavVol)); - S_ClearSoundBuffer (); + S_ClearSoundBuffer(); } /* @@ -1848,7 +1687,7 @@ S_StopAllSounds ================== */ void S_StopAllSounds(void) { - if ( !s_soundStarted ) { + if (!s_soundStarted) { return; } // stop the background music @@ -1871,11 +1710,9 @@ S_ClearLoopingSounds ================== */ -void S_ClearLoopingSounds( void ) -{ +void S_ClearLoopingSounds(void) { #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { for (int i = 0; i < MAX_LOOP_SOUNDS; i++) loopSounds[i].bProcessed = false; } @@ -1891,18 +1728,14 @@ Stops all active looping sounds on a specified entity. Sort of a slow method though, isn't there some better way? ================== */ -void S_StopLoopingSound( int entityNum ) -{ +void S_StopLoopingSound(int entityNum) { int i = 0; - while (i < numLoopSounds) - { - if (loopSounds[i].entnum == entityNum) - { - int x = i+1; - while (x < numLoopSounds) - { - memcpy(&loopSounds[x-1], &loopSounds[x], sizeof(loopSounds[x])); + while (i < numLoopSounds) { + if (loopSounds[i].entnum == entityNum) { + int x = i + 1; + while (x < numLoopSounds) { + memcpy(&loopSounds[x - 1], &loopSounds[x], sizeof(loopSounds[x])); x++; } numLoopSounds--; @@ -1911,7 +1744,7 @@ void S_StopLoopingSound( int entityNum ) } } -#define MAX_DOPPLER_SCALE 50.0f //arbitrary +#define MAX_DOPPLER_SCALE 50.0f // arbitrary /* ================== @@ -1921,109 +1754,104 @@ Called during entity generation for a frame Include velocity in case I get around to doing doppler... ================== */ -void S_AddLoopingSound( int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle ) { +void S_AddLoopingSound(int entityNum, const vec3_t origin, const vec3_t velocity, sfxHandle_t sfxHandle) { /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( numLoopSounds >= MAX_LOOP_SOUNDS ) { + if (numLoopSounds >= MAX_LOOP_SOUNDS) { return; } - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_AddLoopingSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_AddLoopingSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; + sfx = &s_knownSfx[sfxHandle]; if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( !sfx->iSoundLengthInSamples ) { - Com_Error( ERR_DROP, "%s has length 0", sfx->sSoundName ); + if (!sfx->iSoundLengthInSamples) { + Com_Error(ERR_DROP, "%s has length 0", sfx->sSoundName); } assert(!sfx->pMP3StreamHeader); - VectorCopy( origin, loopSounds[numLoopSounds].origin ); - VectorCopy( velocity, loopSounds[numLoopSounds].velocity ); + VectorCopy(origin, loopSounds[numLoopSounds].origin); + VectorCopy(velocity, loopSounds[numLoopSounds].velocity); loopSounds[numLoopSounds].doppler = qfalse; loopSounds[numLoopSounds].dopplerScale = 1.0; loopSounds[numLoopSounds].sfx = sfx; loopSounds[numLoopSounds].volume = SOUND_MAXVOL; loopSounds[numLoopSounds].entnum = entityNum; - if ( s_doppler->integer && VectorLengthSquared(velocity) > 0.0 ) { - vec3_t out; - float lena, lenb; + if (s_doppler->integer && VectorLengthSquared(velocity) > 0.0) { + vec3_t out; + float lena, lenb; loopSounds[numLoopSounds].doppler = qtrue; lena = DistanceSquared(listener_origin, loopSounds[numLoopSounds].origin); VectorAdd(loopSounds[numLoopSounds].origin, loopSounds[numLoopSounds].velocity, out); lenb = DistanceSquared(listener_origin, out); - loopSounds[numLoopSounds].dopplerScale = lenb/(lena*100); + loopSounds[numLoopSounds].dopplerScale = lenb / (lena * 100); if (loopSounds[numLoopSounds].dopplerScale > MAX_DOPPLER_SCALE) { loopSounds[numLoopSounds].dopplerScale = MAX_DOPPLER_SCALE; } else if (loopSounds[numLoopSounds].dopplerScale <= 1.0) { - loopSounds[numLoopSounds].doppler = qfalse; // don't bother doing the math + loopSounds[numLoopSounds].doppler = qfalse; // don't bother doing the math } } numLoopSounds++; } - /* ================== S_AddAmbientLoopingSound ================== */ -void S_AddAmbientLoopingSound( const vec3_t origin, unsigned char volume, sfxHandle_t sfxHandle ) -{ +void S_AddAmbientLoopingSound(const vec3_t origin, unsigned char volume, sfxHandle_t sfxHandle) { /*const*/ sfx_t *sfx; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } - if ( numLoopSounds >= MAX_LOOP_SOUNDS ) { + if (numLoopSounds >= MAX_LOOP_SOUNDS) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if (volume == 0) return; } #endif - if ( sfxHandle < 0 || sfxHandle >= s_numSfx ) { - Com_Error( ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle ); + if (sfxHandle < 0 || sfxHandle >= s_numSfx) { + Com_Error(ERR_DROP, "S_StartSound: handle %i out of range", sfxHandle); } - sfx = &s_knownSfx[ sfxHandle ]; - if (sfx->bInMemory == qfalse){ + sfx = &s_knownSfx[sfxHandle]; + if (sfx->bInMemory == qfalse) { S_memoryLoad(sfx); } SND_TouchSFX(sfx); - if ( !sfx->iSoundLengthInSamples ) { - Com_Error( ERR_DROP, "%s has length 0", sfx->sSoundName ); + if (!sfx->iSoundLengthInSamples) { + Com_Error(ERR_DROP, "%s has length 0", sfx->sSoundName); } - VectorCopy( origin, loopSounds[numLoopSounds].origin ); + VectorCopy(origin, loopSounds[numLoopSounds].origin); loopSounds[numLoopSounds].doppler = qfalse; loopSounds[numLoopSounds].dopplerScale = 1.0; loopSounds[numLoopSounds].sfx = sfx; assert(!sfx->pMP3StreamHeader); - //TODO: Calculate the distance falloff + // TODO: Calculate the distance falloff loopSounds[numLoopSounds].volume = volume; numLoopSounds++; } - - /* ================== S_AddLoopSounds @@ -2033,39 +1861,38 @@ All sounds are on the same cycle, so any duplicates can just sum up the channel multipliers. ================== */ -void S_AddLoopSounds (void) -{ - int i, j; - int left, right, left_total, right_total; - channel_t *ch; - loopSound_t *loop, *loop2; - static int loopFrame; +void S_AddLoopSounds(void) { + int i, j; + int left, right, left_total, right_total; + channel_t *ch; + loopSound_t *loop, *loop2; + static int loopFrame; loopFrame++; - for ( i = 0 ; i < numLoopSounds ; i++) { + for (i = 0; i < numLoopSounds; i++) { loop = &loopSounds[i]; - if ( loop->mergeFrame == loopFrame ) { - continue; // already merged into an earlier sound + if (loop->mergeFrame == loopFrame) { + continue; // already merged into an earlier sound } // find the total contribution of all sounds of this type left_total = right_total = 0; - for ( j = i ; j < numLoopSounds ; j++) { + for (j = i; j < numLoopSounds; j++) { loop2 = &loopSounds[j]; - if ( loop2->sfx != loop->sfx ) { + if (loop2->sfx != loop->sfx) { continue; } - loop2->mergeFrame = loopFrame; // don't check this again later + loop2->mergeFrame = loopFrame; // don't check this again later - S_SpatializeOrigin( loop2->origin, loop2->volume, &left, &right, CHAN_AUTO); //FIXME: Allow for volume change!! + S_SpatializeOrigin(loop2->origin, loop2->volume, &left, &right, CHAN_AUTO); // FIXME: Allow for volume change!! left_total += left; right_total += right; } if (left_total == 0 && right_total == 0) - continue; // not audible + continue; // not audible // allocate a channel ch = S_PickChannel(0, 0); @@ -2078,7 +1905,7 @@ void S_AddLoopSounds (void) right_total = SOUND_MAXVOL; ch->leftvol = left_total; ch->rightvol = right_total; - ch->loopSound = qtrue; // remove next frame + ch->loopSound = qtrue; // remove next frame ch->thesfx = loop->sfx; ch->doppler = loop->doppler; @@ -2086,13 +1913,10 @@ void S_AddLoopSounds (void) // you cannot use MP3 files here because they offer only streaming access, not random // - if (loop->sfx->pMP3StreamHeader) - { - Com_Error( ERR_DROP, "S_AddLoopSounds(): Cannot use streamed MP3 files here for random access (%s)\n",loop->sfx->sSoundName ); - } - else - { - memset(&ch->MP3StreamHeader,0, sizeof(ch->MP3StreamHeader)); + if (loop->sfx->pMP3StreamHeader) { + Com_Error(ERR_DROP, "S_AddLoopSounds(): Cannot use streamed MP3 files here for random access (%s)\n", loop->sfx->sSoundName); + } else { + memset(&ch->MP3StreamHeader, 0, sizeof(ch->MP3StreamHeader)); } } } @@ -2107,29 +1931,25 @@ If raw data has been loaded in little endian binary form, this must be done. If raw data was calculated, as with ADPCM, this should not be called. ================= */ -void S_ByteSwapRawSamples( int samples, int width, int s_channels, const byte *data ) { - int i; +void S_ByteSwapRawSamples(int samples, int width, int s_channels, const byte *data) { + int i; - if ( width != 2 ) { + if (width != 2) { return; } - if ( LittleShort( 256 ) == 256 ) { + if (LittleShort(256) == 256) { return; } - if ( s_channels == 2 ) { + if (s_channels == 2) { samples <<= 1; } - for ( i = 0 ; i < samples ; i++ ) { - ((short *)data)[i] = LittleShort( ((short *)data)[i] ); + for (i = 0; i < samples; i++) { + ((short *)data)[i] = LittleShort(((short *)data)[i]); } } - -portable_samplepair_t *S_GetRawSamplePointer() { - return s_rawsamples; -} - +portable_samplepair_t *S_GetRawSamplePointer() { return s_rawsamples; } /* ============ @@ -2138,176 +1958,140 @@ S_RawSamples Music streaming ============ */ -void S_RawSamples( int samples, int rate, int width, int channels, const byte *data, float volume, int bFirstOrOnlyUpdateThisFrame ) -{ - int i; - int src, dst; - float scale; - int intVolume; - - if ( !s_soundStarted || s_soundMuted ) { +void S_RawSamples(int samples, int rate, int width, int channels, const byte *data, float volume, int bFirstOrOnlyUpdateThisFrame) { + int i; + int src, dst; + float scale; + int intVolume; + + if (!s_soundStarted || s_soundMuted) { return; } intVolume = 256 * volume; - if ( s_rawend < s_soundtime ) { - Com_DPrintf( "S_RawSamples: resetting minimum: %i < %i\n", s_rawend, s_soundtime ); + if (s_rawend < s_soundtime) { + Com_DPrintf("S_RawSamples: resetting minimum: %i < %i\n", s_rawend, s_soundtime); s_rawend = s_soundtime; } scale = (float)rate / dma.speed; -//Com_Printf ("%i < %i < %i\n", s_soundtime, s_paintedtime, s_rawend); - if (channels == 2 && width == 2) - { - if (scale == 1.0) - { // optimized case - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; i= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left = ((short *)data)[src*2] * intVolume; - s_rawsamples[dst].right = ((short *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left = ((short *)data)[src * 2] * intVolume; + s_rawsamples[dst].right = ((short *)data)[src * 2 + 1] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left += ((short *)data)[src*2] * intVolume; - s_rawsamples[dst].right += ((short *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left += ((short *)data)[src * 2] * intVolume; + s_rawsamples[dst].right += ((short *)data)[src * 2 + 1] * intVolume; } } } - } - else if (channels == 1 && width == 2) - { - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + } else if (channels == 1 && width == 2) { + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; s_rawsamples[dst].left = ((short *)data)[src] * intVolume; s_rawsamples[dst].right = ((short *)data)[src] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left += ((short *)data)[src] * intVolume; + s_rawsamples[dst].left += ((short *)data)[src] * intVolume; s_rawsamples[dst].right += ((short *)data)[src] * intVolume; } } - } - else if (channels == 2 && width == 1) - { + } else if (channels == 2 && width == 1) { intVolume *= 256; - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left = ((char *)data)[src*2] * intVolume; - s_rawsamples[dst].right = ((char *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left = ((char *)data)[src * 2] * intVolume; + s_rawsamples[dst].right = ((char *)data)[src * 2 + 1] * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left += ((char *)data)[src*2] * intVolume; - s_rawsamples[dst].right += ((char *)data)[src*2+1] * intVolume; + s_rawsamples[dst].left += ((char *)data)[src * 2] * intVolume; + s_rawsamples[dst].right += ((char *)data)[src * 2 + 1] * intVolume; } } - } - else if (channels == 1 && width == 1) - { + } else if (channels == 1 && width == 1) { intVolume *= 256; - if (bFirstOrOnlyUpdateThisFrame) - { - for (i=0 ; ; i++) - { - src = i*scale; + if (bFirstOrOnlyUpdateThisFrame) { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left = (((byte *)data)[src]-128) * intVolume; - s_rawsamples[dst].right = (((byte *)data)[src]-128) * intVolume; + s_rawsamples[dst].left = (((byte *)data)[src] - 128) * intVolume; + s_rawsamples[dst].right = (((byte *)data)[src] - 128) * intVolume; } - } - else - { - for (i=0 ; ; i++) - { - src = i*scale; + } else { + for (i = 0;; i++) { + src = i * scale; if (src >= samples) break; - dst = s_rawend&(MAX_RAW_SAMPLES-1); + dst = s_rawend & (MAX_RAW_SAMPLES - 1); s_rawend++; - s_rawsamples[dst].left += (((byte *)data)[src]-128) * intVolume; - s_rawsamples[dst].right += (((byte *)data)[src]-128) * intVolume; + s_rawsamples[dst].left += (((byte *)data)[src] - 128) * intVolume; + s_rawsamples[dst].right += (((byte *)data)[src] - 128) * intVolume; } } } - if ( s_rawend > s_soundtime + MAX_RAW_SAMPLES ) { - Com_DPrintf( "S_RawSamples: overflowed %i > %i\n", s_rawend, s_soundtime ); + if (s_rawend > s_soundtime + MAX_RAW_SAMPLES) { + Com_DPrintf("S_RawSamples: overflowed %i > %i\n", s_rawend, s_soundtime); } } @@ -2320,27 +2104,22 @@ S_UpdateEntityPosition let the sound system know where an entity currently is ====================== */ -void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) -{ - if ( entityNum < 0 || entityNum >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum ); +void S_UpdateEntityPosition(int entityNum, const vec3_t origin) { + if (entityNum < 0 || entityNum >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "S_UpdateEntityPosition: bad entitynum %i", entityNum); } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { if (entityNum == 0) return; int i; channel_t *ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((s_channels[i].bPlaying) && (s_channels[i].entnum == entityNum) && (!s_channels[i].bLooping)) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((s_channels[i].bPlaying) && (s_channels[i].entnum == entityNum) && (!s_channels[i].bLooping)) { // Ignore position updates for CHAN_VOICE_GLOBAL - if (ch->entchannel != CHAN_VOICE_GLOBAL && ch->entchannel != CHAN_ANNOUNCER) - { + if (ch->entchannel != CHAN_VOICE_GLOBAL && ch->entchannel != CHAN_ANNOUNCER) { ALfloat pos[3]; pos[0] = origin[0]; pos[1] = origin[2]; @@ -2350,100 +2129,90 @@ void S_UpdateEntityPosition( int entityNum, const vec3_t origin ) UpdateEAXBuffer(ch); } -/* pos[0] = origin[0]; - pos[1] = origin[2]; - pos[2] = -origin[1]; - alSourcefv(s_channels[i].alSource, AL_POSITION, pos); + /* pos[0] = origin[0]; + pos[1] = origin[2]; + pos[2] = -origin[1]; + alSourcefv(s_channels[i].alSource, AL_POSITION, pos); - if ((s_bEALFileLoaded) && !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) ) - { - UpdateEAXBuffer(ch); - } -*/ + if ((s_bEALFileLoaded) && !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == + CHAN_VOICE_GLOBAL ) ) + { + UpdateEAXBuffer(ch); + } + */ } } } #endif - VectorCopy( origin, s_entityPosition[entityNum] ); + VectorCopy(origin, s_entityPosition[entityNum]); } - // Given a current wav we are playing, and our position within it, lets figure out its volume... // // (this is mostly Jake's code from EF1, which explains a lot...:-) // static int next_amplitude = 0; -static int S_CheckAmplitude(channel_t *ch, const unsigned int s_oldpaintedtime ) -{ +static int S_CheckAmplitude(channel_t *ch, const unsigned int s_oldpaintedtime) { // now, is this a cycle - or have we just started a new sample - where we should update the backup table, and write this value // into the new table? or should we just take the value FROM the back up table and feed it out. - assert( ch->startSample != START_SAMPLE_IMMEDIATE ); - if ( ch->startSample == s_oldpaintedtime || (next_amplitude < s_soundtime) )//(ch->startSample == START_SAMPLE_IMMEDIATE)//!s_entityWavVol_back[ch->entnum] + assert(ch->startSample != START_SAMPLE_IMMEDIATE); + if (ch->startSample == s_oldpaintedtime || (next_amplitude < s_soundtime)) //(ch->startSample == START_SAMPLE_IMMEDIATE)//!s_entityWavVol_back[ch->entnum] { - int sample; - int sample_total = 0; - int count = 0; + int sample; + int sample_total = 0; + int count = 0; short *current_pos_s; -// char *current_pos_c; - int offset = 0; + // char *current_pos_c; + int offset = 0; // if we haven't started the sample yet, we must be at the beginning - current_pos_s = ((short*)ch->thesfx->pSoundData); -// current_pos_c = ((char*)ch->thesfx->data); + current_pos_s = ((short *)ch->thesfx->pSoundData); + // current_pos_c = ((char*)ch->thesfx->data); - //if (ch->startSample != START_SAMPLE_IMMEDIATE) + // if (ch->startSample != START_SAMPLE_IMMEDIATE) //{ - // figure out where we are in the sample right now. - offset = s_oldpaintedtime - ch->startSample;//s_paintedtime - current_pos_s += offset; -// current_pos_c += offset; + // figure out where we are in the sample right now. + offset = s_oldpaintedtime - ch->startSample; // s_paintedtime + current_pos_s += offset; + // current_pos_c += offset; //} // scan through 10 samples 100( at 11hz or 200 at 22hz) samples apart. // - for (int i=0; i<10; i++) - { + for (int i = 0; i < 10; i++) { // // have we run off the end? - if ((offset + (i*100)) > ch->thesfx->iSoundLengthInSamples) - { + if ((offset + (i * 100)) > ch->thesfx->iSoundLengthInSamples) { break; } -// if (ch->thesfx->width == 1) -// { -// sample = current_pos_c[i*100]; -// } -// else + // if (ch->thesfx->width == 1) + // { + // sample = current_pos_c[i*100]; + // } + // else { - switch (ch->thesfx->eSoundCompressionMethod) - { - case ct_16: - { - sample = current_pos_s[i*100]; - } - break; - - case ct_MP3: - { - const int iIndex = (i*100) + ((offset * /*ch->thesfx->width*/2) - ch->iMP3SlidingDecodeWindowPos); - const short* pwSamples = (short*) (ch->MP3SlidingDecodeBuffer + iIndex); - - sample = *pwSamples; - } - break; - - default: - { - assert(0); - sample = 0; - } - break; + switch (ch->thesfx->eSoundCompressionMethod) { + case ct_16: { + sample = current_pos_s[i * 100]; + } break; + + case ct_MP3: { + const int iIndex = (i * 100) + ((offset * /*ch->thesfx->width*/ 2) - ch->iMP3SlidingDecodeWindowPos); + const short *pwSamples = (short *)(ch->MP3SlidingDecodeBuffer + iIndex); + + sample = *pwSamples; + } break; + + default: { + assert(0); + sample = 0; + } break; } -// if (sample < 0) -// sample = -sample; - sample = sample>>8; + // if (sample < 0) + // sample = -sample; + sample = sample >> 8; } // square it for better accuracy sample_total += (sample * sample); @@ -2451,47 +2220,34 @@ static int S_CheckAmplitude(channel_t *ch, const unsigned int s_oldpaintedtime ) } // if we are already done with this sample, then its silence - if (!count) - { - return(0); + if (!count) { + return (0); } sample_total /= count; // I hate doing this, but its the simplest way - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_1->value) - { - // tell the scripts that are relying on this that we are still going, but actually silent right now. + if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_1->value) { + // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_2->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_2->value) { sample = 1; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_3->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_3->value) { sample = 2; - } - else - if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_4->value) - { + } else if (sample_total < ch->thesfx->fVolRange * s_lip_threshold_4->value) { sample = 3; - } - else - { + } else { sample = 4; } -// Com_OPrintf("Returning sample %d\n",sample); + // Com_OPrintf("Returning sample %d\n",sample); // store away the value we got into the back up table - s_entityWavVol_back[ ch->entnum ] = sample; + s_entityWavVol_back[ch->entnum] = sample; return (sample); } // no, just get last value calculated from backup table - assert( s_entityWavVol_back[ch->entnum] ); - return (s_entityWavVol_back[ ch->entnum]); + assert(s_entityWavVol_back[ch->entnum]); + return (s_entityWavVol_back[ch->entnum]); } /* ============ @@ -2500,23 +2256,21 @@ S_Respatialize Change the volumes of all the playing sounds for changes in their positions ============ */ -void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwater ) -{ +void S_Respatialize(int entityNum, const vec3_t head, matrix3_t axis, int inwater) { #ifdef USE_OPENAL EAXOCCLUSIONPROPERTIES eaxOCProp; EAXACTIVEFXSLOTS eaxActiveSlots; #endif - int i; - channel_t *ch; - vec3_t origin; + int i; + channel_t *ch; + vec3_t origin; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { listener_pos[0] = head[0]; listener_pos[1] = head[2]; listener_pos[2] = -head[1]; @@ -2531,28 +2285,22 @@ void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwat alListenerfv(AL_ORIENTATION, listener_ori); // Update EAX effects here - if (s_bEALFileLoaded) - { + if (s_bEALFileLoaded) { // Check if the Listener is underwater - if (inwater) - { + if (inwater) { // Check if we have already applied Underwater effect - if (!s_bInWater) - { + if (!s_bInWater) { // New underwater fix - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].lEnvID = -1; } // Load underwater reverb effect into FX Slot 0, and set this as the Primary FX Slot unsigned int ulEnvironment = EAX_ENVIRONMENT_UNDERWATER; - s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ENVIRONMENT, - NULL, &ulEnvironment, sizeof(unsigned int)); + s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ENVIRONMENT, NULL, &ulEnvironment, sizeof(unsigned int)); s_EnvironmentID = 999; - s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, (ALvoid*)&EAXPROPERTYID_EAX40_FXSlot0, - sizeof(GUID)); + s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, (ALvoid *)&EAXPROPERTYID_EAX40_FXSlot0, sizeof(GUID)); // Occlude all sounds into this environment, and mute all their sends to other reverbs eaxOCProp.lOcclusion = -3000; @@ -2564,46 +2312,35 @@ void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwat eaxActiveSlots.guidActiveFXSlots[1] = EAX_PrimaryFXSlotID; ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { // New underwater fix s_channels[i].lSlotID = -1; - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, - &eaxActiveSlots, 2*sizeof(GUID)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &eaxActiveSlots, 2 * sizeof(GUID)); } s_bInWater = true; } - } - else - { + } else { // Not underwater ... check if the underwater effect is still present - if (s_bInWater) - { + if (s_bInWater) { s_bInWater = false; // Remove underwater Reverb effect, and reset Occlusion / Obstruction amount on all Sources UpdateEAXListener(); ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { UpdateEAXBuffer(ch); } - } - else - { + } else { UpdateEAXListener(); } } } - } - else - { + } else { #endif listener_number = entityNum; VectorCopy(head, listener_origin); @@ -2613,12 +2350,12 @@ void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwat // update spatialization for dynamic sounds ch = s_channels; - for ( i = 0 ; i < MAX_CHANNELS ; i++, ch++ ) { - if ( !ch->thesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { // loopSounds are regenerated fresh each frame - Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); + if (ch->loopSound) { // loopSounds are regenerated fresh each frame + Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); continue; } @@ -2628,24 +2365,24 @@ void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwat ch->rightvol = ch->master_vol; } else { if (ch->fixed_origin) { - VectorCopy( ch->origin, origin ); + VectorCopy(ch->origin, origin); } else { - VectorCopy( s_entityPosition[ ch->entnum ], origin ); + VectorCopy(s_entityPosition[ch->entnum], origin); } - S_SpatializeOrigin (origin, (float)ch->master_vol, &ch->leftvol, &ch->rightvol, ch->entchannel); + S_SpatializeOrigin(origin, (float)ch->master_vol, &ch->leftvol, &ch->rightvol, ch->entchannel); } - //NOTE: Made it so that voice sounds keep playing, even out of range + // NOTE: Made it so that voice sounds keep playing, even out of range // so that tasks waiting for sound completion keep proper timing - if ( !( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) && !ch->leftvol && !ch->rightvol ) { - Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); + if (!(ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) && !ch->leftvol && !ch->rightvol) { + Channel_Clear(ch); // memset (ch, 0, sizeof(*ch)); continue; } } // add loopsounds - S_AddLoopSounds (); + S_AddLoopSounds(); #ifdef USE_OPENAL } #endif @@ -2653,7 +2390,6 @@ void S_Respatialize( int entityNum, const vec3_t head, matrix3_t axis, int inwat return; } - /* ======================== S_ScanChannelStarts @@ -2661,32 +2397,32 @@ S_ScanChannelStarts Returns qtrue if any new sounds were started since the last mix ======================== */ -qboolean S_ScanChannelStarts( void ) { - channel_t *ch; - int i; - qboolean newSamples; +qboolean S_ScanChannelStarts(void) { + channel_t *ch; + int i; + qboolean newSamples; newSamples = qfalse; ch = s_channels; - for (i=0; ithesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } // if this channel was just started this frame, // set the sample count to it begins mixing // into the very first sample - if ( ch->startSample == START_SAMPLE_IMMEDIATE ) { + if (ch->startSample == START_SAMPLE_IMMEDIATE) { ch->startSample = s_paintedtime; newSamples = qtrue; continue; } // if it is completely finished by now, clear it - if ( (int)(ch->startSample + ch->thesfx->iSoundLengthInSamples) <= s_paintedtime ) { + if ((int)(ch->startSample + ch->thesfx->iSoundLengthInSamples) <= s_paintedtime) { ch->thesfx = NULL; continue; } @@ -2698,36 +2434,34 @@ qboolean S_ScanChannelStarts( void ) { // this is now called AFTER the DMA painting, since it's only the painter calls that cause the MP3s to be unpacked, // and therefore to have data readable by the lip-sync volume calc code. // -void S_DoLipSynchs( const unsigned s_oldpaintedtime ) -{ - channel_t *ch; - int i; +void S_DoLipSynchs(const unsigned s_oldpaintedtime) { + channel_t *ch; + int i; // clear out the lip synching override array for this frame - memset(s_entityWavVol, 0,(MAX_GENTITIES * 4)); + memset(s_entityWavVol, 0, (MAX_GENTITIES * 4)); ch = s_channels; - for (i=0; ithesfx ) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx) { continue; } - if ( ch->loopSound ) { + if (ch->loopSound) { continue; } // if we are playing a sample that should override the lip texture on its owning model, lets figure out // what the amplitude is, stick it in a table, then return it - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { // go away and work out amplitude for this sound we are playing right now. - s_entityWavVol[ ch->entnum ] = S_CheckAmplitude( ch, s_oldpaintedtime ); - if ( s_show->integer == 3 ) { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + s_entityWavVol[ch->entnum] = S_CheckAmplitude(ch, s_oldpaintedtime); + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } } - if (next_amplitude < s_soundtime) { + if (next_amplitude < s_soundtime) { next_amplitude = s_soundtime + 800; } } @@ -2739,36 +2473,35 @@ S_Update Called once each time through the main loop ============ */ -void S_Update( void ) { - int i; - int total; - channel_t *ch; +void S_Update(void) { + int i; + int total; + channel_t *ch; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } // // debugging output // - if ( s_show->integer == 2 ) { + if (s_show->integer == 2) { total = 0; - int totalMeg =0; + int totalMeg = 0; ch = s_channels; - for (i=0 ; ithesfx && (ch->leftvol || ch->rightvol) ) { - Com_Printf ("(%i) %3i %3i %s\n", ch->entnum, ch->leftvol, ch->rightvol, ch->thesfx->sSoundName); + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (ch->thesfx && (ch->leftvol || ch->rightvol)) { + Com_Printf("(%i) %3i %3i %s\n", ch->entnum, ch->leftvol, ch->rightvol, ch->thesfx->sSoundName); total++; totalMeg += Z_Size(ch->thesfx->pSoundData); - if (ch->thesfx->pMP3StreamHeader) - { + if (ch->thesfx->pMP3StreamHeader) { totalMeg += sizeof(*ch->thesfx->pMP3StreamHeader); } } } if (total) - Com_Printf ("----(%i)---- painted: %i, SND %.2fMB\n", total, s_paintedtime, totalMeg/1024.0f/1024.0f); + Com_Printf("----(%i)---- painted: %i, SND %.2fMB\n", total, s_paintedtime, totalMeg / 1024.0f / 1024.0f); } // The Open AL code, handles background music in the S_UpdateRawSamples function @@ -2784,17 +2517,15 @@ void S_Update( void ) { S_Update_(); } -void S_GetSoundtime(void) -{ - int samplepos; - static int buffers; - static int oldsamplepos; - int fullsamples; +void S_GetSoundtime(void) { + int samplepos; + static int buffers; + static int oldsamplepos; + int fullsamples; fullsamples = dma.samples / dma.channels; - if( CL_VideoRecording( ) ) - { + if (CL_VideoRecording()) { float fps = Q_min(cl_aviFrameRate->value, 1000.0f); float frameDuration = Q_max(dma.speed / fps, 1.0f) + clc.aviSoundFrameRemainder; int msec = (int)frameDuration; @@ -2806,20 +2537,18 @@ void S_GetSoundtime(void) // it is possible to miscount buffers if it has wrapped twice between // calls to S_Update. Oh well. samplepos = SNDDMA_GetDMAPos(); - if (samplepos < oldsamplepos) - { - buffers++; // buffer wrapped + if (samplepos < oldsamplepos) { + buffers++; // buffer wrapped - if (s_paintedtime > 0x40000000) - { // time to chop things off to avoid 32 bit limits + if (s_paintedtime > 0x40000000) { // time to chop things off to avoid 32 bit limits buffers = 0; s_paintedtime = fullsamples; - S_StopAllSounds (); + S_StopAllSounds(); } } oldsamplepos = samplepos; - s_soundtime = buffers*fullsamples + samplepos/dma.channels; + s_soundtime = buffers * fullsamples + samplepos / dma.channels; #if 0 // check to make sure that we haven't overshot @@ -2830,39 +2559,35 @@ void S_GetSoundtime(void) } #endif - if ( dma.submission_chunk < 256 ) { + if (dma.submission_chunk < 256) { s_paintedtime = (int)(s_soundtime + s_mixPreStep->value * dma.speed); } else { s_paintedtime = s_soundtime + dma.submission_chunk; } } - void S_Update_(void) { - unsigned endtime; - int samps; + unsigned endtime; + int samps; - if ( !s_soundStarted || s_soundMuted ) { + if (!s_soundStarted || s_soundMuted) { return; } #ifdef USE_OPENAL - if (s_UseOpenAL) - { - int i,j; - float pos[3]; + if (s_UseOpenAL) { + int i, j; + float pos[3]; UpdateSingleShotSounds(); channel_t *ch = s_channels + 1; - for ( i = 1; i < MAX_CHANNELS ; i++, ch++ ) - { - if ( !ch->thesfx || (ch->bPlaying)) + for (i = 1; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx || (ch->bPlaying)) continue; int source = ch - s_channels; - if (ch->entchannel == CHAN_VOICE_GLOBAL || ch->entchannel == CHAN_ANNOUNCER) - { + if (ch->entchannel == CHAN_VOICE_GLOBAL || ch->entchannel == CHAN_ANNOUNCER) { // Always play these sounds at 0,0,-1 (in front of listener) pos[0] = 0.0f; pos[1] = 0.0f; @@ -2871,45 +2596,31 @@ void S_Update_(void) { alSourcefv(s_channels[source].alSource, AL_POSITION, pos); alSourcei(s_channels[source].alSource, AL_LOOPING, AL_FALSE); alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_TRUE); - if (ch->entchannel == CHAN_ANNOUNCER) - { + if (ch->entchannel == CHAN_ANNOUNCER) { alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.0f); - } - else - { + } else { alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); } - } - else - { + } else { // Get position of source - if (ch->fixed_origin) - { + if (ch->fixed_origin) { pos[0] = ch->origin[0]; pos[1] = ch->origin[2]; pos[2] = -ch->origin[1]; alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_FALSE); - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { pos[0] = 0.0f; pos[1] = 0.0f; pos[2] = 0.0f; alSourcei(s_channels[source].alSource, AL_SOURCE_RELATIVE, AL_TRUE); - } - else - { + } else { // Get position of Entity - if (ch->bLooping) - { - pos[0] = loopSounds[ ch->entnum ].origin[0]; - pos[1] = loopSounds[ ch->entnum ].origin[2]; - pos[2] = -loopSounds[ ch->entnum ].origin[1]; - } - else - { + if (ch->bLooping) { + pos[0] = loopSounds[ch->entnum].origin[0]; + pos[1] = loopSounds[ch->entnum].origin[2]; + pos[2] = -loopSounds[ch->entnum].origin[1]; + } else { pos[0] = s_entityPosition[ch->entnum][0]; pos[1] = s_entityPosition[ch->entnum][2]; pos[2] = -s_entityPosition[ch->entnum][1]; @@ -2921,26 +2632,19 @@ void S_Update_(void) { alSourcefv(s_channels[source].alSource, AL_POSITION, pos); alSourcei(s_channels[source].alSource, AL_LOOPING, AL_FALSE); - if (ch->entchannel == CHAN_VOICE) - { + if (ch->entchannel == CHAN_VOICE) { // Reduced fall-off (Large Reference Distance), affected by Voice Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_VOICE_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); - } - else if (ch->entchannel == CHAN_VOICE_ATTEN) - { + } else if (ch->entchannel == CHAN_VOICE_ATTEN) { // Normal fall-off, affected by Voice Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volumeVoice->value) / 255.0f); - } - else if (ch->entchannel == CHAN_LESS_ATTEN) - { + } else if (ch->entchannel == CHAN_LESS_ATTEN) { // Reduced fall-off, affected by Sound Effect Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_VOICE_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); - } - else - { + } else { // Normal fall-off, affect by Sound Effect Volume alSourcef(s_channels[source].alSource, AL_REFERENCE_DISTANCE, DEFAULT_REF_DISTANCE); alSourcef(s_channels[source].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); @@ -2954,33 +2658,27 @@ void S_Update_(void) { int nTotalBytesDecoded = 0; int nBuffersToAdd = 0; - if (ch->thesfx->pMP3StreamHeader) - { - memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); + if (ch->thesfx->pMP3StreamHeader) { + memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); ch->iMP3SlidingDecodeWritePos = 0; - ch->iMP3SlidingDecodeWindowPos= 0; + ch->iMP3SlidingDecodeWindowPos = 0; // Reset streaming buffers status's for (i = 0; i < NUM_STREAMING_BUFFERS; i++) ch->buffers[i].Status = UNQUEUED; // Decode (STREAMING_BUFFER_SIZE / 1152) MP3 frames for each of the NUM_STREAMING_BUFFERS AL Buffers - for (i = 0; i < NUM_STREAMING_BUFFERS; i++) - { + for (i = 0; i < NUM_STREAMING_BUFFERS; i++) { nTotalBytesDecoded = 0; - for (j = 0; j < (STREAMING_BUFFER_SIZE / 1152); j++) - { - nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 ? + for (j = 0; j < (STREAMING_BUFFER_SIZE / 1152); j++) { + nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 ? memcpy(ch->buffers[i].Data + nTotalBytesDecoded, ch->MP3StreamHeader.bDecodeBuffer, nBytesDecoded); - if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { - ch->thesfx->lipSyncData[(i*NUM_STREAMING_BUFFERS)+j] = S_MP3PreProcessLipSync(ch, (short *)(ch->MP3StreamHeader.bDecodeBuffer)); - } - else - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { + ch->thesfx->lipSyncData[(i * NUM_STREAMING_BUFFERS) + j] = + S_MP3PreProcessLipSync(ch, (short *)(ch->MP3StreamHeader.bDecodeBuffer)); + } else { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif @@ -2989,8 +2687,7 @@ void S_Update_(void) { nTotalBytesDecoded += nBytesDecoded; } - if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) - { + if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) { memset(ch->buffers[i].Data + nTotalBytesDecoded, 0, (STREAMING_BUFFER_SIZE - nTotalBytesDecoded)); break; } @@ -3004,15 +2701,13 @@ void S_Update_(void) { // Make sure queue is empty first alSourcei(s_channels[source].alSource, AL_BUFFER, NULL); - for (i = 0; i < nBuffersToAdd; i++) - { + for (i = 0; i < nBuffersToAdd; i++) { // Copy decoded data to AL Buffer alBufferData(ch->buffers[i].BufferID, AL_FORMAT_MONO16, ch->buffers[i].Data, STREAMING_BUFFER_SIZE, 22050); // Queue AL Buffer on Source alSourceQueueBuffers(s_channels[source].alSource, 1, &(ch->buffers[i].BufferID)); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { ch->buffers[i].Status = QUEUED; } } @@ -3025,18 +2720,14 @@ void S_Update_(void) { ch->bStreaming = true; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { // Record start time for Lip-syncing s_channels[source].iStartTime = timeGetTime(); // Prepare lipsync value(s) - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[0]; - } - else - { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[0]; + } else { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif @@ -3044,9 +2735,7 @@ void S_Update_(void) { } return; - } - else - { + } else { // Attach buffer to source alSourcei(s_channels[source].alSource, AL_BUFFER, ch->thesfx->Buffer); @@ -3058,18 +2747,14 @@ void S_Update_(void) { if (alGetError() == AL_NO_ERROR) s_channels[source].bPlaying = true; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { // Record start time for Lip-syncing s_channels[source].iStartTime = timeGetTime(); // Prepare lipsync value(s) - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[0]; - } - else - { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[0]; + } else { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif @@ -3083,9 +2768,7 @@ void S_Update_(void) { UpdateLoopingSounds(); AL_UpdateRawSamples(); - } - else - { + } else { #endif // Updates s_soundtime S_GetSoundtime(); @@ -3100,30 +2783,27 @@ void S_Update_(void) { endtime = (int)(s_soundtime + s_mixahead->value * dma.speed); // mix to an even submission block size - endtime = (endtime + dma.submission_chunk-1) - & ~(dma.submission_chunk-1); + endtime = (endtime + dma.submission_chunk - 1) & ~(dma.submission_chunk - 1); // never mix more than the complete buffer - samps = dma.samples >> (dma.channels-1); + samps = dma.samples >> (dma.channels - 1); if (endtime - s_soundtime > (unsigned)samps) endtime = s_soundtime + samps; + SNDDMA_BeginPainting(); - SNDDMA_BeginPainting (); + S_PaintChannels(endtime); - S_PaintChannels (endtime); + SNDDMA_Submit(); - SNDDMA_Submit (); - - S_DoLipSynchs( s_oldpaintedtime ); + S_DoLipSynchs(s_oldpaintedtime); #ifdef USE_OPENAL } #endif } #ifdef USE_OPENAL -void UpdateSingleShotSounds() -{ +void UpdateSingleShotSounds() { int i, j, k; ALint state; ALint processed; @@ -3132,23 +2812,17 @@ void UpdateSingleShotSounds() // Firstly, check if any single-shot sounds have completed, or if they need more data (for streaming Sources), // and/or if any of the currently playing (non-Ambient) looping sounds need to be stopped ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { + for (i = 1; i < s_numChannels; i++, ch++) { ch->bProcessed = false; - if ((s_channels[i].bPlaying) && (!ch->bLooping)) - { + if ((s_channels[i].bPlaying) && (!ch->bLooping)) { // Single-shot - if (s_channels[i].bStreaming == false) - { + if (s_channels[i].bStreaming == false) { alGetSourcei(s_channels[i].alSource, AL_SOURCE_STATE, &state); - if (state == AL_STOPPED) - { + if (state == AL_STOPPED) { s_channels[i].thesfx = NULL; s_channels[i].bPlaying = false; } - } - else - { + } else { // Process streaming sample // Procedure :- @@ -3164,14 +2838,11 @@ void UpdateSingleShotSounds() int nBytesDecoded; - if (ch->thesfx->pMP3StreamHeader) - { - if (ch->MP3StreamHeader.iSourceBytesRemaining == 0) - { + if (ch->thesfx->pMP3StreamHeader) { + if (ch->MP3StreamHeader.iSourceBytesRemaining == 0) { // Finished decoding data - if the source has finished playing then we're done alGetSourcei(ch->alSource, AL_SOURCE_STATE, &state); - if (state == AL_STOPPED) - { + if (state == AL_STOPPED) { // Attach NULL buffer to Source to remove any buffers left in the queue alSourcei(ch->alSource, AL_BUFFER, NULL); ch->thesfx = NULL; @@ -3185,13 +2856,10 @@ void UpdateSingleShotSounds() alGetSourcei(ch->alSource, AL_BUFFERS_PROCESSED, &processed); ALuint buffer; - while (processed) - { + while (processed) { alSourceUnqueueBuffers(ch->alSource, 1, &buffer); - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { - if (ch->buffers[j].BufferID == buffer) - { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { + if (ch->buffers[j].BufferID == buffer) { ch->buffers[j].Status = UNQUEUED; break; } @@ -3201,48 +2869,36 @@ void UpdateSingleShotSounds() int nTotalBytesDecoded = 0; - for (j = 0; j < NUM_STREAMING_BUFFERS; j++) - { - if ((ch->buffers[j].Status == UNQUEUED) && (ch->MP3StreamHeader.iSourceBytesRemaining > 0)) - { + for (j = 0; j < NUM_STREAMING_BUFFERS; j++) { + if ((ch->buffers[j].Status == UNQUEUED) && (ch->MP3StreamHeader.iSourceBytesRemaining > 0)) { nTotalBytesDecoded = 0; - for (k = 0; k < (STREAMING_BUFFER_SIZE / 1152); k++) - { + for (k = 0; k < (STREAMING_BUFFER_SIZE / 1152); k++) { nBytesDecoded = C_MP3Stream_Decode(&ch->MP3StreamHeader, 0); // added ,0 - if (nBytesDecoded > 0) - { + if (nBytesDecoded > 0) { memcpy(ch->buffers[j].Data + nTotalBytesDecoded, ch->MP3StreamHeader.bDecodeBuffer, nBytesDecoded); - if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { - if (ch->thesfx->lipSyncData) - { - ch->thesfx->lipSyncData[(j*4)+k] = S_MP3PreProcessLipSync(ch, (short *)(ch->buffers[j].Data)); - } - else - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { + if (ch->thesfx->lipSyncData) { + ch->thesfx->lipSyncData[(j * 4) + k] = S_MP3PreProcessLipSync(ch, (short *)(ch->buffers[j].Data)); + } else { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif } } nTotalBytesDecoded += nBytesDecoded; - } - else - { + } else { // Make sure that iSourceBytesRemaining is 0 - if (ch->MP3StreamHeader.iSourceBytesRemaining != 0) - { + if (ch->MP3StreamHeader.iSourceBytesRemaining != 0) { ch->MP3StreamHeader.iSourceBytesRemaining = 0; break; } } } - if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) - { + if (nTotalBytesDecoded != STREAMING_BUFFER_SIZE) { memset(ch->buffers[j].Data + nTotalBytesDecoded, 0, (STREAMING_BUFFER_SIZE - nTotalBytesDecoded)); // Move data to buffer @@ -3255,9 +2911,7 @@ void UpdateSingleShotSounds() ch->buffers[j].Status = QUEUED; break; - } - else - { + } else { // Move data to buffer alBufferData(ch->buffers[j].BufferID, AL_FORMAT_MONO16, ch->buffers[j].Data, STREAMING_BUFFER_SIZE, 22050); @@ -3272,11 +2926,11 @@ void UpdateSingleShotSounds() // Get state of Buffer alGetSourcei(ch->alSource, AL_SOURCE_STATE, &state); - if (state != AL_PLAYING) - { + if (state != AL_PLAYING) { alSourcePlay(ch->alSource); #ifdef _DEBUG - Com_OPrintf("[%d] Restarting playback of single-shot streaming MP3 sample - still have %d bytes to decode\n", i, ch->MP3StreamHeader.iSourceBytesRemaining); + Com_OPrintf("[%d] Restarting playback of single-shot streaming MP3 sample - still have %d bytes to decode\n", i, + ch->MP3StreamHeader.iSourceBytesRemaining); #endif } } @@ -3285,34 +2939,26 @@ void UpdateSingleShotSounds() } } -void UpdateLoopingSounds() -{ - int i,j; +void UpdateLoopingSounds() { + int i, j; ALuint source; channel_t *ch; - loopSound_t *loop; + loopSound_t *loop; float pos[3]; // First check to see if any of the looping sounds are already playing at the correct positions ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if (ch->bLooping && s_channels[i].bPlaying) - { - for (j = 0; j < numLoopSounds; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if (ch->bLooping && s_channels[i].bPlaying) { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; // If this channel is playing the right sound effect at the right position then mark this channel and looping sound // as processed - if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) ) - { - if ( (loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) - && (loop->origin[2] == listener_pos[1]) ) - { + if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) { + if ((loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) && (loop->origin[2] == listener_pos[1])) { // Assume that this sound is head relative - if (!loop->bRelative) - { + if (!loop->bRelative) { // Set position to 0,0,0 and turn on Head Relative Mode float pos[3]; pos[0] = 0.f; @@ -3325,24 +2971,20 @@ void UpdateLoopingSounds() } // Make sure Gain is set correctly - if (ch->master_vol != loop->volume) - { + if (ch->master_vol != loop->volume) { ch->master_vol = loop->volume; alSourcef(s_channels[i].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); } ch->bProcessed = true; loop->bProcessed = true; - } - else if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) && (!memcmp(ch->origin, loop->origin, sizeof(ch->origin)))) - { + } else if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx) && (!memcmp(ch->origin, loop->origin, sizeof(ch->origin)))) { // Match ! ch->bProcessed = true; loop->bProcessed = true; // Make sure Gain is set correctly - if (ch->master_vol != loop->volume) - { + if (ch->master_vol != loop->volume) { ch->master_vol = loop->volume; alSourcef(s_channels[i].alSource, AL_GAIN, ((float)(ch->master_vol) * s_volume->value) / 255.f); } @@ -3356,16 +2998,12 @@ void UpdateLoopingSounds() // Next check if the correct looping sound is playing, but at the wrong position ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((ch->bLooping) && (ch->bProcessed == false) && s_channels[i].bPlaying) - { - for (j = 0; j < numLoopSounds; j++) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if ((ch->bLooping) && (ch->bProcessed == false) && s_channels[i].bPlaying) { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; - if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) - { + if ((loop->bProcessed == false) && (ch->thesfx == loop->sfx)) { // Same sound - wrong position ch->origin[0] = loop->origin[0]; ch->origin[1] = loop->origin[1]; @@ -3393,10 +3031,8 @@ void UpdateLoopingSounds() // If any non-procesed looping sounds are still playing on a channel, they can be removed as they are no longer // required ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if (s_channels[i].bPlaying && ch->bLooping && !ch->bProcessed) - { + for (i = 1; i < s_numChannels; i++, ch++) { + if (s_channels[i].bPlaying && ch->bLooping && !ch->bProcessed) { // Sound no longer needed alSourceStop(s_channels[i].alSource); ch->thesfx = NULL; @@ -3408,32 +3044,26 @@ void UpdateLoopingSounds() alGetError(); #endif // Finally if there are any non-processed sounds left, we need to try and play them - for (j = 0; j < numLoopSounds; j++) - { + for (j = 0; j < numLoopSounds; j++) { loop = &loopSounds[j]; - if (loop->bProcessed == false) - { - ch = S_PickChannel(0,0); + if (loop->bProcessed == false) { + ch = S_PickChannel(0, 0); ch->master_vol = loop->volume; ch->entnum = loop->entnum; - ch->entchannel = CHAN_AMBIENT; // Make sure this gets set to something + ch->entchannel = CHAN_AMBIENT; // Make sure this gets set to something ch->thesfx = loop->sfx; ch->bLooping = true; // Check if the Source is positioned at exactly the same location as the listener - if ( (loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) - && (loop->origin[2] == listener_pos[1]) ) - { + if ((loop->origin[0] == listener_pos[0]) && (loop->origin[1] == -listener_pos[2]) && (loop->origin[2] == listener_pos[1])) { // Assume that this sound is head relative loop->bRelative = true; ch->origin[0] = 0.f; ch->origin[1] = 0.f; ch->origin[2] = 0.f; - } - else - { + } else { ch->origin[0] = loop->origin[0]; ch->origin[1] = loop->origin[1]; ch->origin[2] = loop->origin[2]; @@ -3464,13 +3094,12 @@ void UpdateLoopingSounds() } } -void AL_UpdateRawSamples() -{ +void AL_UpdateRawSamples() { ALuint buffer; ALint size; ALint processed; ALint state; - int i,j,src; + int i, j, src; #ifdef _DEBUG // Clear Open AL Error @@ -3482,8 +3111,7 @@ void AL_UpdateRawSamples() // Find out how many buffers have been processed (played) by the Source alGetSourcei(s_channels[0].alSource, AL_BUFFERS_PROCESSED, &processed); - while (processed) - { + while (processed) { // Unqueue each buffer, determine the length of the buffer, and then delete it alSourceUnqueueBuffers(s_channels[0].alSource, 1, &buffer); alGetBufferi(buffer, AL_SIZE, &size); @@ -3496,22 +3124,19 @@ void AL_UpdateRawSamples() } // Add new data to a new Buffer and queue it on the Source - if (s_rawend > s_paintedtime) - { - size = (s_rawend - s_paintedtime)<<2; - if (size > (MAX_RAW_SAMPLES<<2)) - { + if (s_rawend > s_paintedtime) { + size = (s_rawend - s_paintedtime) << 2; + if (size > (MAX_RAW_SAMPLES << 2)) { Com_OPrintf("UpdateRawSamples :- Raw Sample buffer has overflowed !!!\n"); - size = MAX_RAW_SAMPLES<<2; + size = MAX_RAW_SAMPLES << 2; s_paintedtime = s_rawend - MAX_RAW_SAMPLES; } // Copy samples from RawSamples to audio buffer (sg.rawdata) - for (i = s_paintedtime, j = 0; i < s_rawend; i++, j+=2) - { + for (i = s_paintedtime, j = 0; i < s_rawend; i++, j += 2) { src = i & (MAX_RAW_SAMPLES - 1); - s_rawdata[j] = (short)(s_rawsamples[src].left>>8); - s_rawdata[j+1] = (short)(s_rawsamples[src].right>>8); + s_rawdata[j] = (short)(s_rawsamples[src].left >> 8); + s_rawdata[j + 1] = (short)(s_rawsamples[src].right >> 8); } // Need to generate more than 1 buffer for music playback @@ -3529,19 +3154,15 @@ void AL_UpdateRawSamples() // iterations++; int iterations = 0; - int largestBufferSize = MAX_RAW_SAMPLES; // in bytes (== quarter of Raw Samples data) - while (size) - { + int largestBufferSize = MAX_RAW_SAMPLES; // in bytes (== quarter of Raw Samples data) + while (size) { alGenBuffers(1, &buffer); - if (size > largestBufferSize) - { - alBufferData(buffer, AL_FORMAT_STEREO16, (char*)(s_rawdata + ((iterations * largestBufferSize)>>1)), largestBufferSize, 22050); + if (size > largestBufferSize) { + alBufferData(buffer, AL_FORMAT_STEREO16, (char *)(s_rawdata + ((iterations * largestBufferSize) >> 1)), largestBufferSize, 22050); size -= largestBufferSize; - } - else - { - alBufferData(buffer, AL_FORMAT_STEREO16, (char*)(s_rawdata + ((iterations * largestBufferSize)>>1)), size, 22050); + } else { + alBufferData(buffer, AL_FORMAT_STEREO16, (char *)(s_rawdata + ((iterations * largestBufferSize) >> 1)), size, 22050); size = 0; } @@ -3554,13 +3175,11 @@ void AL_UpdateRawSamples() // Check that the Source is actually playing alGetSourcei(s_channels[0].alSource, AL_SOURCE_STATE, &state); - if (state != AL_PLAYING) - { + if (state != AL_PLAYING) { // Stopped playing ... due to buffer underrun // Unqueue any buffers still on the Source (they will be PROCESSED), and restart playback alGetSourcei(s_channels[0].alSource, AL_BUFFERS_PROCESSED, &processed); - while (processed) - { + while (processed) { alSourceUnqueueBuffers(s_channels[0].alSource, 1, &buffer); processed--; alGetBufferi(buffer, AL_SIZE, &size); @@ -3584,14 +3203,12 @@ void AL_UpdateRawSamples() } #endif -int S_MP3PreProcessLipSync(channel_t *ch, short *data) -{ +int S_MP3PreProcessLipSync(channel_t *ch, short *data) { int i; int sample; int sampleTotal = 0; - for (i = 0; i < 576; i += 100) - { + for (i = 0; i < 576; i += 100) { sample = LittleShort(data[i]); sample = sample >> 8; sampleTotal += sample * sample; @@ -3613,8 +3230,7 @@ int S_MP3PreProcessLipSync(channel_t *ch, short *data) return sample; } -void S_SetLipSyncs() -{ +void S_SetLipSyncs() { int i; unsigned int samples; int currentTime, timePlayed; @@ -3630,60 +3246,49 @@ void S_SetLipSyncs() memset(s_entityWavVol, 0, sizeof(s_entityWavVol)); ch = s_channels + 1; - for (i = 1; i < s_numChannels; i++, ch++) - { - if ((!ch->thesfx)||(!ch->bPlaying)) + for (i = 1; i < s_numChannels; i++, ch++) { + if ((!ch->thesfx) || (!ch->bPlaying)) continue; - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) - { + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) { // Calculate how much time has passed since the sample was started timePlayed = currentTime - ch->iStartTime; - if (ch->thesfx->eSoundCompressionMethod==ct_16) - { + if (ch->thesfx->eSoundCompressionMethod == ct_16) { // There is a new computed lip-sync value every 1000 samples - so find out how many samples // have been played and lookup the value in the lip-sync table samples = (timePlayed * 22050) / 1000; - if (ch->thesfx->lipSyncData == NULL) - { + if (ch->thesfx->lipSyncData == NULL) { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif } - if ((ch->thesfx->lipSyncData) && ((int)samples < ch->thesfx->iSoundLengthInSamples)) - { - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[samples / 1000]; - if ( s_show->integer == 3 ) - { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + if ((ch->thesfx->lipSyncData) && ((int)samples < ch->thesfx->iSoundLengthInSamples)) { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[samples / 1000]; + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } - } - else - { + } else { // MP3 // There is a new computed lip-sync value every 576 samples - so find out how many samples // have been played and lookup the value in the lip-sync table samples = (timePlayed * 22050) / 1000; - if (ch->thesfx->lipSyncData == NULL) - { + if (ch->thesfx->lipSyncData == NULL) { #ifdef _DEBUG Com_OPrintf("Missing lip-sync info. for %s\n", ch->thesfx->sSoundName); #endif } - if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) - { - s_entityWavVol[ ch->entnum ] = ch->thesfx->lipSyncData[(samples / 576) % 16]; + if ((ch->thesfx->lipSyncData) && (samples < (unsigned)ch->thesfx->iSoundLengthInSamples)) { + s_entityWavVol[ch->entnum] = ch->thesfx->lipSyncData[(samples / 576) % 16]; - if ( s_show->integer == 3 ) - { - Com_Printf( "(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ ch->entnum ] ); + if (s_show->integer == 3) { + Com_Printf("(%i)%i %s vol = %i\n", ch->entnum, i, ch->thesfx->sSoundName, s_entityWavVol[ch->entnum]); } } } @@ -3699,105 +3304,79 @@ console functions =============================================================================== */ -static void S_Play_f( void ) { - int i; - sfxHandle_t h; +static void S_Play_f(void) { + int i; + sfxHandle_t h; char name[256]; i = 1; - while ( i [loopfile]\n"); + Com_Printf("music [loopfile]\n"); return; } } -static void S_StopMusic_f( void ) { - S_StopBackgroundTrack(); -} +static void S_StopMusic_f(void) { S_StopBackgroundTrack(); } // a debug function, but no harm to leave in... // -static void S_SetDynamicMusic_f(void) -{ +static void S_SetDynamicMusic_f(void) { int c = Cmd_Argc(); - if ( c == 2 ) - { - if (bMusic_IsDynamic) - { + if (c == 2) { + if (bMusic_IsDynamic) { // don't need to check existance of 'explore' or 'action' music, since music wouldn't // be counted as dynamic if either were missing, but other types are optional... // - if (!Q_stricmp(Cmd_Argv(1),"explore")) - { - S_SetDynamicMusicState( eBGRNDTRACK_EXPLORE ); + if (!Q_stricmp(Cmd_Argv(1), "explore")) { + S_SetDynamicMusicState(eBGRNDTRACK_EXPLORE); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"action")) - { - S_SetDynamicMusicState( eBGRNDTRACK_ACTION ); + } else if (!Q_stricmp(Cmd_Argv(1), "action")) { + S_SetDynamicMusicState(eBGRNDTRACK_ACTION); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"silence")) - { - S_SetDynamicMusicState( eBGRNDTRACK_SILENCE ); + } else if (!Q_stricmp(Cmd_Argv(1), "silence")) { + S_SetDynamicMusicState(eBGRNDTRACK_SILENCE); return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"boss")) - { - if (tMusic_Info[ eBGRNDTRACK_BOSS ].bExists) - { - S_SetDynamicMusicState( eBGRNDTRACK_BOSS ); - } - else - { + } else if (!Q_stricmp(Cmd_Argv(1), "boss")) { + if (tMusic_Info[eBGRNDTRACK_BOSS].bExists) { + S_SetDynamicMusicState(eBGRNDTRACK_BOSS); + } else { Com_Printf("No 'boss' music defined in current dynamic set\n"); } return; - } - else - if (!Q_stricmp(Cmd_Argv(1),"death")) - { - if (tMusic_Info[ eBGRNDTRACK_DEATH ].bExists) - { - S_SetDynamicMusicState( eBGRNDTRACK_DEATH ); - } - else - { + } else if (!Q_stricmp(Cmd_Argv(1), "death")) { + if (tMusic_Info[eBGRNDTRACK_DEATH].bExists) { + S_SetDynamicMusicState(eBGRNDTRACK_DEATH); + } else { Com_Printf("No 'death' music defined in current dynamic set\n"); } return; } - } - else - { - DynamicMusicInfoPrint(); // print "inactive" string + } else { + DynamicMusicInfoPrint(); // print "inactive" string return; } } @@ -3810,54 +3389,38 @@ static void S_SetDynamicMusic_f(void) // this table needs to be in-sync with the typedef'd enum "SoundCompressionMethod_t"... -ste // -static const char *sSoundCompressionMethodStrings[ct_NUMBEROF] = -{ - "16b", // ct_16 - "mp3" // ct_MP3 +static const char *sSoundCompressionMethodStrings[ct_NUMBEROF] = { + "16b", // ct_16 + "mp3" // ct_MP3 }; -void S_SoundList_f( void ) { - int i; - sfx_t *sfx; - int size, total; - int iVariantCap = -1; // for %d-inquiry stuff - int iTotalBytes = 0; - char *arg = NULL; +void S_SoundList_f(void) { + int i; + sfx_t *sfx; + int size, total; + int iVariantCap = -1; // for %d-inquiry stuff + int iTotalBytes = 0; + char *arg = NULL; qboolean bWavOnly = qfalse; qboolean bShouldBeMP3 = qfalse; - if ( Cmd_Argc() == 2 ) - { + if (Cmd_Argc() == 2) { arg = Cmd_Argv(1); - if (!Q_stricmp(arg, "shouldbeMP3")) - { + if (!Q_stricmp(arg, "shouldbeMP3")) { bShouldBeMP3 = qtrue; - } - else if (!Q_stricmp(arg, "wavonly")) - { + } else if (!Q_stricmp(arg, "wavonly")) { bWavOnly = qtrue; - } - else - { - if (!Q_stricmp(arg, "1")) - { + } else { + if (!Q_stricmp(arg, "1")) { iVariantCap = 1; - } - else - if (!Q_stricmp(arg, "2")) - { + } else if (!Q_stricmp(arg, "2")) { iVariantCap = 2; - } - else - if (!Q_stricmp(arg, "3")) - { + } else if (!Q_stricmp(arg, "3")) { iVariantCap = 3; } } - } - else - { - Com_Printf("( additional (mutually exclusive) options available:\n'wavonly', 'ShouldBeMP3', '1'/'2'/'3' for %%d-variant capping )\n" ); + } else { + Com_Printf("( additional (mutually exclusive) options available:\n'wavonly', 'ShouldBeMP3', '1'/'2'/'3' for %%d-variant capping )\n"); } total = 0; @@ -3869,38 +3432,33 @@ void S_SoundList_f( void ) { Com_Printf(" | |\n"); Com_Printf(" | |\n"); Com_Printf(" Slot Smpls Type | | Name\n"); -// Com_Printf(" Slot Smpls Type InMem? Name\n"); + // Com_Printf(" Slot Smpls Type InMem? Name\n"); - for (sfx=s_knownSfx, i=0 ; ibDefaultSound && !sfx->pMP3StreamHeader && sfx->pSoundData && (Z_Size(sfx->pSoundData) > cv_MP3overhead->integer)); + qboolean bMP3DumpOverride = (qboolean)(bShouldBeMP3 && cv_MP3overhead && !sfx->bDefaultSound && !sfx->pMP3StreamHeader && sfx->pSoundData && + (Z_Size(sfx->pSoundData) > cv_MP3overhead->integer)); - if (bMP3DumpOverride || (!bShouldBeMP3 && (!bWavOnly || sfx->eSoundCompressionMethod == ct_16))) - { + if (bMP3DumpOverride || (!bShouldBeMP3 && (!bWavOnly || sfx->eSoundCompressionMethod == ct_16))) { qboolean bDumpThisOne = qtrue; - if (iVariantCap >= 1 && iVariantCap <= 3) - { + if (iVariantCap >= 1 && iVariantCap <= 3) { int iStrLen = strlen(sfx->sSoundName); - if (iStrLen > 2) // crash-safety, jic. + if (iStrLen > 2) // crash-safety, jic. { - char c = sfx->sSoundName[iStrLen-1]; - char c2 = sfx->sSoundName[iStrLen-2]; + char c = sfx->sSoundName[iStrLen - 1]; + char c2 = sfx->sSoundName[iStrLen - 2]; if (!isdigit(c2) // quick-avoid of stuff like "pain75" - && isdigit(c) && atoi(va("%c",c)) > iVariantCap) - { + && isdigit(c) && atoi(va("%c", c)) > iVariantCap) { // need to see if this %d-variant should be omitted, in other words if there's a %1 version then skip this... // char sFindName[MAX_QPATH]; - Q_strncpyz(sFindName,sfx->sSoundName,sizeof(sFindName)); - sFindName[iStrLen-1] = '1'; + Q_strncpyz(sFindName, sfx->sSoundName, sizeof(sFindName)); + sFindName[iStrLen - 1] = '1'; int i2; sfx_t *sfx2; - for (sfx2 = s_knownSfx, i2=0 ; i2sSoundName)) - { - bDumpThisOne = qfalse; // found a %1-variant of this, so use variant capping and ignore this sfx_t + for (sfx2 = s_knownSfx, i2 = 0; i2 < s_numSfx; i2++, sfx2++) { + if (!Q_stricmp(sFindName, sfx2->sSoundName)) { + bDumpThisOne = qfalse; // found a %1-variant of this, so use variant capping and ignore this sfx_t break; } } @@ -3909,24 +3467,20 @@ void S_SoundList_f( void ) { } size = sfx->iSoundLengthInSamples; - if (sfx->bDefaultSound) - { - Com_Printf("%5d Missing file: \"%s\"\n", i, sfx->sSoundName ); - } - else - { - if (bDumpThisOne) - { + if (sfx->bDefaultSound) { + Com_Printf("%5d Missing file: \"%s\"\n", i, sfx->sSoundName); + } else { + if (bDumpThisOne) { iTotalBytes += (sfx->bInMemory && sfx->pSoundData) ? Z_Size(sfx->pSoundData) : 0; iTotalBytes += (sfx->bInMemory && sfx->pMP3StreamHeader) ? sizeof(*sfx->pMP3StreamHeader) : 0; - total += sfx->bInMemory ? size : 0; + total += sfx->bInMemory ? size : 0; } - Com_Printf("%5d %7i [%s] %s %2d %s", i, size, sSoundCompressionMethodStrings[sfx->eSoundCompressionMethod], sfx->bInMemory?"y":"n", sfx->iLastLevelUsedOn, sfx->sSoundName ); + Com_Printf("%5d %7i [%s] %s %2d %s", i, size, sSoundCompressionMethodStrings[sfx->eSoundCompressionMethod], sfx->bInMemory ? "y" : "n", + sfx->iLastLevelUsedOn, sfx->sSoundName); - if (!bDumpThisOne) - { + if (!bDumpThisOne) { Com_Printf(" ( Skipping, variant capped )"); - //Com_OPrintf("Variant capped: %s\n",sfx->sSoundName); + // Com_OPrintf("Variant capped: %s\n",sfx->sSoundName); } Com_Printf("\n"); } @@ -3934,9 +3488,9 @@ void S_SoundList_f( void ) { } Com_Printf(" Slot Smpls Type In? Lev Name\n"); - Com_Printf ("Total resident samples: %i %s ( not mem usage, see 'meminfo' ).\n", total, bWavOnly?"(WAV only)":""); - Com_Printf ("%d out of %d sfx_t slots used\n", s_numSfx, MAX_SFX); - Com_Printf ("%.2fMB bytes used when counting sfx_t->pSoundData + MP3 headers (if any)\n", (float)iTotalBytes / 1024.0f / 1024.0f); + Com_Printf("Total resident samples: %i %s ( not mem usage, see 'meminfo' ).\n", total, bWavOnly ? "(WAV only)" : ""); + Com_Printf("%d out of %d sfx_t slots used\n", s_numSfx, MAX_SFX); + Com_Printf("%.2fMB bytes used when counting sfx_t->pSoundData + MP3 headers (if any)\n", (float)iTotalBytes / 1024.0f / 1024.0f); S_DisplayFreeMemory(); } @@ -3948,43 +3502,43 @@ background music functions =============================================================================== */ -int FGetLittleLong( fileHandle_t f ) { - int v; +int FGetLittleLong(fileHandle_t f) { + int v; - FS_Read( &v, sizeof(v), f ); + FS_Read(&v, sizeof(v), f); - return LittleLong( v); + return LittleLong(v); } -int FGetLittleShort( fileHandle_t f ) { - short v; +int FGetLittleShort(fileHandle_t f) { + short v; - FS_Read( &v, sizeof(v), f ); + FS_Read(&v, sizeof(v), f); - return LittleShort( v); + return LittleShort(v); } // returns the length of the data in the chunk, or 0 if not found -int S_FindWavChunk( fileHandle_t f, char *chunk ) { - char name[5]; - int len; - int r; +int S_FindWavChunk(fileHandle_t f, char *chunk) { + char name[5]; + int len; + int r; name[4] = 0; len = 0; - r = FS_Read( name, 4, f ); - if ( r != 4 ) { + r = FS_Read(name, 4, f); + if (r != 4) { return 0; } - len = FGetLittleLong( f ); - if ( len < 0 || len > 0xfffffff ) { + len = FGetLittleLong(f); + if (len < 0 || len > 0xfffffff) { len = 0; return 0; } - len = (len + 1 ) & ~1; // pad to word boundary -// s_nextWavChunk += len + 8; + len = (len + 1) & ~1; // pad to word boundary + // s_nextWavChunk += len + 8; - if ( strcmp( name, chunk ) ) { + if (strcmp(name, chunk)) { return 0; } return len; @@ -3995,11 +3549,10 @@ int S_FindWavChunk( fileHandle_t f, char *chunk ) { // // DO NOT replace this with a call to FS_FileExists, that's for checking about writing out, and doesn't work for this. // -qboolean S_FileExists( const char *psFilename ) -{ +qboolean S_FileExists(const char *psFilename) { fileHandle_t fhTemp; - FS_FOpenFileRead (psFilename, &fhTemp, qtrue); // qtrue so I can fclose the handle without closing a PAK + FS_FOpenFileRead(psFilename, &fhTemp, qtrue); // qtrue so I can fclose the handle without closing a PAK if (!fhTemp) return qfalse; @@ -4009,43 +3562,40 @@ qboolean S_FileExists( const char *psFilename ) // some stuff for streaming MP3 files from disk (not pleasant, but nothing about MP3 is, other than compression ratios...) // -static void MP3MusicStream_Reset(MusicInfo_t *pMusicInfo) -{ - pMusicInfo->iMP3MusicStream_DiskReadPos = 0; - pMusicInfo->iMP3MusicStream_DiskWindowPos = 0; +static void MP3MusicStream_Reset(MusicInfo_t *pMusicInfo) { + pMusicInfo->iMP3MusicStream_DiskReadPos = 0; + pMusicInfo->iMP3MusicStream_DiskWindowPos = 0; } // // return is where the decoder should read from... // -static byte *MP3MusicStream_ReadFromDisk(MusicInfo_t *pMusicInfo, int iReadOffset, int iReadBytesNeeded) -{ - if (iReadOffset < pMusicInfo->iMP3MusicStream_DiskWindowPos) - { - assert(0); // should never happen - return pMusicInfo->byMP3MusicStream_DiskBuffer; // ...but return something safe anyway +static byte *MP3MusicStream_ReadFromDisk(MusicInfo_t *pMusicInfo, int iReadOffset, int iReadBytesNeeded) { + if (iReadOffset < pMusicInfo->iMP3MusicStream_DiskWindowPos) { + assert(0); // should never happen + return pMusicInfo->byMP3MusicStream_DiskBuffer; // ...but return something safe anyway } - while (iReadOffset + iReadBytesNeeded > pMusicInfo->iMP3MusicStream_DiskReadPos) - { - int iBytesRead = FS_Read( pMusicInfo->byMP3MusicStream_DiskBuffer + (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos), iMP3MusicStream_DiskBytesToRead, pMusicInfo->s_backgroundFile ); + while (iReadOffset + iReadBytesNeeded > pMusicInfo->iMP3MusicStream_DiskReadPos) { + int iBytesRead = + FS_Read(pMusicInfo->byMP3MusicStream_DiskBuffer + (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos), + iMP3MusicStream_DiskBytesToRead, pMusicInfo->s_backgroundFile); pMusicInfo->iMP3MusicStream_DiskReadPos += iBytesRead; - if (iBytesRead != iMP3MusicStream_DiskBytesToRead) // quietly ignore any requests to read past file end + if (iBytesRead != iMP3MusicStream_DiskBytesToRead) // quietly ignore any requests to read past file end { - break; // we need to do this because the disk read code can't know how much source data we need to - // read for a given number of requested output bytes, so we'll always be asking for too many + break; // we need to do this because the disk read code can't know how much source data we need to + // read for a given number of requested output bytes, so we'll always be asking for too many } } // if reached halfway point in buffer (approx 20k), backscroll it... // - if (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos > iMP3MusicStream_DiskBufferSize/2) - { + if (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos > iMP3MusicStream_DiskBufferSize / 2) { int iMoveSrcOffset = iReadOffset - pMusicInfo->iMP3MusicStream_DiskWindowPos; - int iMoveCount = (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos ) - iMoveSrcOffset; - memmove( &pMusicInfo->byMP3MusicStream_DiskBuffer, &pMusicInfo->byMP3MusicStream_DiskBuffer[iMoveSrcOffset], iMoveCount); + int iMoveCount = (pMusicInfo->iMP3MusicStream_DiskReadPos - pMusicInfo->iMP3MusicStream_DiskWindowPos) - iMoveSrcOffset; + memmove(&pMusicInfo->byMP3MusicStream_DiskBuffer, &pMusicInfo->byMP3MusicStream_DiskBuffer[iMoveSrcOffset], iMoveCount); pMusicInfo->iMP3MusicStream_DiskWindowPos += iMoveSrcOffset; } @@ -4054,99 +3604,83 @@ static byte *MP3MusicStream_ReadFromDisk(MusicInfo_t *pMusicInfo, int iReadOffse // does NOT set s_rawend!... // -static void S_StopBackgroundTrack_Actual( MusicInfo_t *pMusicInfo ) -{ - if ( pMusicInfo->s_backgroundFile ) - { - if ( pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); +static void S_StopBackgroundTrack_Actual(MusicInfo_t *pMusicInfo) { + if (pMusicInfo->s_backgroundFile) { + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } } -static void FreeMusic( MusicInfo_t *pMusicInfo ) -{ - if (pMusicInfo->pLoadedData) - { +static void FreeMusic(MusicInfo_t *pMusicInfo) { + if (pMusicInfo->pLoadedData) { Z_Free(pMusicInfo->pLoadedData); - pMusicInfo->pLoadedData = NULL; // these two MUST be kept as valid/invalid together - pMusicInfo->sLoadedDataName[0]= '\0'; // - pMusicInfo->iLoadedDataLen = 0; + pMusicInfo->pLoadedData = NULL; // these two MUST be kept as valid/invalid together + pMusicInfo->sLoadedDataName[0] = '\0'; // + pMusicInfo->iLoadedDataLen = 0; } } // called only by snd_shutdown (from snd_restart or app exit) // -void S_UnCacheDynamicMusic( void ) -{ - for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) - { - FreeMusic( &tMusic_Info[i]); +void S_UnCacheDynamicMusic(void) { + for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) { + FreeMusic(&tMusic_Info[i]); } } -static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean qbDynamic, const char *intro, const char *loop ) -{ - int len; - char dump[16]; - char name[MAX_QPATH]; +static qboolean S_StartBackgroundTrack_Actual(MusicInfo_t *pMusicInfo, qboolean qbDynamic, const char *intro, const char *loop) { + int len; + char dump[16]; + char name[MAX_QPATH]; - Q_strncpyz( sMusic_BackgroundLoop, loop, sizeof( sMusic_BackgroundLoop )); + Q_strncpyz(sMusic_BackgroundLoop, loop, sizeof(sMusic_BackgroundLoop)); - Q_strncpyz( name, intro, sizeof( name ) - 4 ); // this seems to be so that if the filename hasn't got an extension - // but doesn't have the room to append on either then you'll just - // get the "soft" fopen() error, rather than the ERR_DROP you'd get - // if COM_DefaultExtension didn't have room to add it on. - COM_DefaultExtension( name, sizeof( name ), ".mp3" ); + Q_strncpyz(name, intro, sizeof(name) - 4); // this seems to be so that if the filename hasn't got an extension + // but doesn't have the room to append on either then you'll just + // get the "soft" fopen() error, rather than the ERR_DROP you'd get + // if COM_DefaultExtension didn't have room to add it on. + COM_DefaultExtension(name, sizeof(name), ".mp3"); // close the background track, but DON'T reset s_rawend (or remaining music bits that haven't been output yet will be cut off) // - S_StopBackgroundTrack_Actual( pMusicInfo ); + S_StopBackgroundTrack_Actual(pMusicInfo); pMusicInfo->bIsMP3 = qfalse; - if ( !intro[0] ) { + if (!intro[0]) { return qfalse; } // new bit, if file requested is not same any loaded one (if prev was in-mem), ditch it... // - if (Q_stricmp(name, pMusicInfo->sLoadedDataName)) - { - FreeMusic( pMusicInfo ); + if (Q_stricmp(name, pMusicInfo->sLoadedDataName)) { + FreeMusic(pMusicInfo); } - if (!Q_stricmpn(name+(strlen(name)-4),".mp3",4)) - { - if (pMusicInfo->pLoadedData) - { + if (!Q_stricmpn(name + (strlen(name) - 4), ".mp3", 4)) { + if (pMusicInfo->pLoadedData) { pMusicInfo->s_backgroundFile = -1; - } - else - { - pMusicInfo->iLoadedDataLen = FS_FOpenFileRead( name, &pMusicInfo->s_backgroundFile, qtrue ); + } else { + pMusicInfo->iLoadedDataLen = FS_FOpenFileRead(name, &pMusicInfo->s_backgroundFile, qtrue); } - if (!pMusicInfo->s_backgroundFile) - { - Com_Printf( S_COLOR_RED"Couldn't open music file %s\n", name ); + if (!pMusicInfo->s_backgroundFile) { + Com_Printf(S_COLOR_RED "Couldn't open music file %s\n", name); return qfalse; } - MP3MusicStream_Reset( pMusicInfo ); + MP3MusicStream_Reset(pMusicInfo); - byte *pbMP3DataSegment = NULL; - int iInitialMP3ReadSize = 8192; // fairly arbitrary, whatever size this is then the decoder is allowed to - // scan up to halfway of it to find floating headers, so don't make it - // too small. 8k works fine. + byte *pbMP3DataSegment = NULL; + int iInitialMP3ReadSize = 8192; // fairly arbitrary, whatever size this is then the decoder is allowed to + // scan up to halfway of it to find floating headers, so don't make it + // too small. 8k works fine. qboolean bMusicSucceeded = qfalse; - if (qbDynamic) - { - if (!pMusicInfo->pLoadedData) - { - pMusicInfo->pLoadedData = (byte *) Z_Malloc(pMusicInfo->iLoadedDataLen, TAG_SND_DYNAMICMUSIC, qfalse); + if (qbDynamic) { + if (!pMusicInfo->pLoadedData) { + pMusicInfo->pLoadedData = (byte *)Z_Malloc(pMusicInfo->iLoadedDataLen, TAG_SND_DYNAMICMUSIC, qfalse); S_ClearSoundBuffer(); FS_Read(pMusicInfo->pLoadedData, pMusicInfo->iLoadedDataLen, pMusicInfo->s_backgroundFile); @@ -4155,94 +3689,79 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean // enable the rest of the code to work as before... // - pbMP3DataSegment = pMusicInfo->pLoadedData; + pbMP3DataSegment = pMusicInfo->pLoadedData; iInitialMP3ReadSize = pMusicInfo->iLoadedDataLen; - } - else - { + } else { pbMP3DataSegment = MP3MusicStream_ReadFromDisk(pMusicInfo, 0, iInitialMP3ReadSize); } - if (MP3_IsValid(name, pbMP3DataSegment, iInitialMP3ReadSize, qtrue /*bStereoDesired*/)) - { + if (MP3_IsValid(name, pbMP3DataSegment, iInitialMP3ReadSize, qtrue /*bStereoDesired*/)) { // init stream struct... // - memset(&pMusicInfo->streamMP3_Bgrnd,0,sizeof(pMusicInfo->streamMP3_Bgrnd)); - char *psError = C_MP3Stream_DecodeInit( &pMusicInfo->streamMP3_Bgrnd, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, - dma.speed, - 16, // sfx->width * 8, - qtrue // bStereoDesired - ); - - if (psError == NULL) - { + memset(&pMusicInfo->streamMP3_Bgrnd, 0, sizeof(pMusicInfo->streamMP3_Bgrnd)); + char *psError = C_MP3Stream_DecodeInit(&pMusicInfo->streamMP3_Bgrnd, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, dma.speed, + 16, // sfx->width * 8, + qtrue // bStereoDesired + ); + + if (psError == NULL) { // init sfx struct & setup the few fields I actually need... // - memset( &pMusicInfo->sfxMP3_Bgrnd,0,sizeof(pMusicInfo->sfxMP3_Bgrnd)); + memset(&pMusicInfo->sfxMP3_Bgrnd, 0, sizeof(pMusicInfo->sfxMP3_Bgrnd)); // pMusicInfo->sfxMP3_Bgrnd.width = 2; // read by MP3_GetSamples() - pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples = 0x7FFFFFFF; // max possible +ve int, since music finishes when decoder stops - pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader = &pMusicInfo->streamMP3_Bgrnd; - Q_strncpyz( pMusicInfo->sfxMP3_Bgrnd.sSoundName, name, sizeof(pMusicInfo->sfxMP3_Bgrnd.sSoundName) ); + pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples = 0x7FFFFFFF; // max possible +ve int, since music finishes when decoder stops + pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader = &pMusicInfo->streamMP3_Bgrnd; + Q_strncpyz(pMusicInfo->sfxMP3_Bgrnd.sSoundName, name, sizeof(pMusicInfo->sfxMP3_Bgrnd.sSoundName)); - if (qbDynamic) - { - MP3Stream_InitPlayingTimeFields ( &pMusicInfo->streamMP3_Bgrnd, name, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, qtrue); + if (qbDynamic) { + MP3Stream_InitPlayingTimeFields(&pMusicInfo->streamMP3_Bgrnd, name, pbMP3DataSegment, pMusicInfo->iLoadedDataLen, qtrue); } - pMusicInfo->s_backgroundInfo.format = WAV_FORMAT_MP3; // not actually used this way, but just ensures we don't match one of the legit formats - pMusicInfo->s_backgroundInfo.channels = 2; // always, for our MP3s when used for music (else 1 for FX) - pMusicInfo->s_backgroundInfo.rate = dma.speed; - pMusicInfo->s_backgroundInfo.width = 2; // always, for our MP3s - pMusicInfo->s_backgroundInfo.samples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; - pMusicInfo->s_backgroundSamples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; + pMusicInfo->s_backgroundInfo.format = WAV_FORMAT_MP3; // not actually used this way, but just ensures we don't match one of the legit formats + pMusicInfo->s_backgroundInfo.channels = 2; // always, for our MP3s when used for music (else 1 for FX) + pMusicInfo->s_backgroundInfo.rate = dma.speed; + pMusicInfo->s_backgroundInfo.width = 2; // always, for our MP3s + pMusicInfo->s_backgroundInfo.samples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; + pMusicInfo->s_backgroundSamples = pMusicInfo->sfxMP3_Bgrnd.iSoundLengthInSamples; - memset(&pMusicInfo->chMP3_Bgrnd,0,sizeof(pMusicInfo->chMP3_Bgrnd)); - pMusicInfo->chMP3_Bgrnd.thesfx = &pMusicInfo->sfxMP3_Bgrnd; + memset(&pMusicInfo->chMP3_Bgrnd, 0, sizeof(pMusicInfo->chMP3_Bgrnd)); + pMusicInfo->chMP3_Bgrnd.thesfx = &pMusicInfo->sfxMP3_Bgrnd; memcpy(&pMusicInfo->chMP3_Bgrnd.MP3StreamHeader, pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader, sizeof(*pMusicInfo->sfxMP3_Bgrnd.pMP3StreamHeader)); - if (qbDynamic) - { - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundFile = -1; // special mp3 value for "valid, but not a real file" + if (qbDynamic) { + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundFile = -1; // special mp3 value for "valid, but not a real file" } } pMusicInfo->bIsMP3 = qtrue; bMusicSucceeded = qtrue; - } - else - { - Com_Printf(S_COLOR_RED"Error streaming file %s: %s\n", name, psError); - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + } else { + Com_Printf(S_COLOR_RED "Error streaming file %s: %s\n", name, psError); + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } - } - else - { + } else { // MP3_IsValid() will already have printed any errors via Com_Printf at this point... // - if (pMusicInfo->s_backgroundFile != -1) - { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if (pMusicInfo->s_backgroundFile != -1) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); } pMusicInfo->s_backgroundFile = 0; } return bMusicSucceeded; - } - else // not an mp3 file + } else // not an mp3 file { // // open up a wav file and get all the info // - FS_FOpenFileRead( name, &pMusicInfo->s_backgroundFile, qtrue ); - if ( !pMusicInfo->s_backgroundFile ) { - Com_Printf( S_COLOR_YELLOW "WARNING: couldn't open music file %s\n", name ); + FS_FOpenFileRead(name, &pMusicInfo->s_backgroundFile, qtrue); + if (!pMusicInfo->s_backgroundFile) { + Com_Printf(S_COLOR_YELLOW "WARNING: couldn't open music file %s\n", name); return qfalse; } @@ -4250,34 +3769,34 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean FS_Read(dump, 12, pMusicInfo->s_backgroundFile); - if ( !S_FindWavChunk( pMusicInfo->s_backgroundFile, "fmt " ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: No fmt chunk in %s\n", name ); - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if (!S_FindWavChunk(pMusicInfo->s_backgroundFile, "fmt ")) { + Com_Printf(S_COLOR_YELLOW "WARNING: No fmt chunk in %s\n", name); + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; return qfalse; } // save name for soundinfo - pMusicInfo->s_backgroundInfo.format = FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.channels = FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.rate = FGetLittleLong( pMusicInfo->s_backgroundFile ); - FGetLittleLong( pMusicInfo->s_backgroundFile ); - FGetLittleShort( pMusicInfo->s_backgroundFile ); - pMusicInfo->s_backgroundInfo.width = FGetLittleShort( pMusicInfo->s_backgroundFile ) / 8; - - if ( pMusicInfo->s_backgroundInfo.format != WAV_FORMAT_PCM ) { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + pMusicInfo->s_backgroundInfo.format = FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.channels = FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.rate = FGetLittleLong(pMusicInfo->s_backgroundFile); + FGetLittleLong(pMusicInfo->s_backgroundFile); + FGetLittleShort(pMusicInfo->s_backgroundFile); + pMusicInfo->s_backgroundInfo.width = FGetLittleShort(pMusicInfo->s_backgroundFile) / 8; + + if (pMusicInfo->s_backgroundInfo.format != WAV_FORMAT_PCM) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; Com_Printf(S_COLOR_YELLOW "WARNING: Not a microsoft PCM format wav: %s\n", name); return qfalse; } - if ( pMusicInfo->s_backgroundInfo.channels != 2 || pMusicInfo->s_backgroundInfo.rate != 22050 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: music file %s is not 22k stereo\n", name ); + if (pMusicInfo->s_backgroundInfo.channels != 2 || pMusicInfo->s_backgroundInfo.rate != 22050) { + Com_Printf(S_COLOR_YELLOW "WARNING: music file %s is not 22k stereo\n", name); } - if ( ( len = S_FindWavChunk( pMusicInfo->s_backgroundFile, "data" ) ) == 0 ) { - FS_FCloseFile( pMusicInfo->s_backgroundFile ); + if ((len = S_FindWavChunk(pMusicInfo->s_backgroundFile, "data")) == 0) { + FS_FCloseFile(pMusicInfo->s_backgroundFile); pMusicInfo->s_backgroundFile = 0; Com_Printf(S_COLOR_YELLOW "WARNING: No data chunk in %s\n", name); return qfalse; @@ -4291,35 +3810,33 @@ static qboolean S_StartBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolean return qtrue; } -static void S_SwitchDynamicTracks( MusicState_e eOldState, MusicState_e eNewState, qboolean bNewTrackStartsFullVolume ) -{ +static void S_SwitchDynamicTracks(MusicState_e eOldState, MusicState_e eNewState, qboolean bNewTrackStartsFullVolume) { // copy old track into fader... // - tMusic_Info[ eBGRNDTRACK_FADE ] = tMusic_Info[ eOldState ]; -// tMusic_Info[ eBGRNDTRACK_FADE ].bActive = qtrue; // inherent -// tMusic_Info[ eBGRNDTRACK_FADE ].bExists = qtrue; // inherent - tMusic_Info[ eBGRNDTRACK_FADE ].iXFadeVolumeSeekTime= Sys_Milliseconds(); - tMusic_Info[ eBGRNDTRACK_FADE ].iXFadeVolumeSeekTo = 0; + tMusic_Info[eBGRNDTRACK_FADE] = tMusic_Info[eOldState]; + // tMusic_Info[ eBGRNDTRACK_FADE ].bActive = qtrue; // inherent + // tMusic_Info[ eBGRNDTRACK_FADE ].bExists = qtrue; // inherent + tMusic_Info[eBGRNDTRACK_FADE].iXFadeVolumeSeekTime = Sys_Milliseconds(); + tMusic_Info[eBGRNDTRACK_FADE].iXFadeVolumeSeekTo = 0; // // ... and deactivate... // - tMusic_Info[ eOldState ].bActive = qfalse; + tMusic_Info[eOldState].bActive = qfalse; // // set new track to either full volume or fade up... // - tMusic_Info[eNewState].bActive = qtrue; - tMusic_Info[eNewState].iXFadeVolumeSeekTime = Sys_Milliseconds(); - tMusic_Info[eNewState].iXFadeVolumeSeekTo = 255; - tMusic_Info[eNewState].iXFadeVolume = bNewTrackStartsFullVolume ? 255 : 0; + tMusic_Info[eNewState].bActive = qtrue; + tMusic_Info[eNewState].iXFadeVolumeSeekTime = Sys_Milliseconds(); + tMusic_Info[eNewState].iXFadeVolumeSeekTo = 255; + tMusic_Info[eNewState].iXFadeVolume = bNewTrackStartsFullVolume ? 255 : 0; eMusic_StateActual = eNewState; - if (s_debugdynamic->integer) - { - const char *psNewStateString = Music_BaseStateToString( eNewState, qtrue ); - psNewStateString = psNewStateString?psNewStateString:""; + if (s_debugdynamic->integer) { + const char *psNewStateString = Music_BaseStateToString(eNewState, qtrue); + psNewStateString = psNewStateString ? psNewStateString : ""; - Com_Printf( S_COLOR_MAGENTA "S_SwitchDynamicTracks( \"%s\" )\n", psNewStateString ); + Com_Printf(S_COLOR_MAGENTA "S_SwitchDynamicTracks( \"%s\" )\n", psNewStateString); } } @@ -4328,185 +3845,159 @@ static void S_SwitchDynamicTracks( MusicState_e eOldState, MusicState_e eNewStat // This either changes the music right now (copying track structures etc), or leaves the new state as pending // so it gets picked up by the general music player if in a transition that can't be overridden... // -static void S_SetDynamicMusicState( MusicState_e eNewState ) -{ - if (eMusic_StateRequest != eNewState) - { - eMusic_StateRequest = eNewState; +static void S_SetDynamicMusicState(MusicState_e eNewState) { + if (eMusic_StateRequest != eNewState) { + eMusic_StateRequest = eNewState; - if (s_debugdynamic->integer) - { - const char *psNewStateString = Music_BaseStateToString( eNewState, qtrue ); - psNewStateString = psNewStateString?psNewStateString:""; + if (s_debugdynamic->integer) { + const char *psNewStateString = Music_BaseStateToString(eNewState, qtrue); + psNewStateString = psNewStateString ? psNewStateString : ""; - Com_Printf( S_COLOR_MAGENTA "S_SetDynamicMusicState( Request: \"%s\" )\n", psNewStateString ); + Com_Printf(S_COLOR_MAGENTA "S_SetDynamicMusicState( Request: \"%s\" )\n", psNewStateString); } } } -static void S_HandleDynamicMusicStateChange( void ) -{ - if (eMusic_StateRequest != eMusic_StateActual) - { +static void S_HandleDynamicMusicStateChange(void) { + if (eMusic_StateRequest != eMusic_StateActual) { // check whether or not the new request can be honoured, given what's currently playing... // - if (Music_StateCanBeInterrupted( eMusic_StateActual, eMusic_StateRequest )) - { - LP_MP3STREAM pMP3StreamActual = &tMusic_Info[ eMusic_StateActual ].chMP3_Bgrnd.MP3StreamHeader; + if (Music_StateCanBeInterrupted(eMusic_StateActual, eMusic_StateRequest)) { + LP_MP3STREAM pMP3StreamActual = &tMusic_Info[eMusic_StateActual].chMP3_Bgrnd.MP3StreamHeader; - switch (eMusic_StateRequest) + switch (eMusic_StateRequest) { + case eBGRNDTRACK_EXPLORE: // ... from action or silence { - case eBGRNDTRACK_EXPLORE: // ... from action or silence + switch (eMusic_StateActual) { + case eBGRNDTRACK_ACTION: // action->explore { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_ACTION: // action->explore - { - // find the transition track to play, and the entry point for explore when we get there, - // and also see if we're at a permitted exit point to switch at all... - // - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( pMP3StreamActual ) - MP3Stream_GetRemainingTimeInSeconds( pMP3StreamActual ); - - // supply: - // - // playing point in float seconds - // enum of track being queried - // - // get: - // - // enum of transition track to switch to - // float time of entry point of new track *after* transition - - MusicState_e eTransition; - float fNewTrackEntryTime = 0.0f; - if (Music_AllowedToTransition( fPlayingTimeElapsed, eBGRNDTRACK_ACTION, &eTransition, &fNewTrackEntryTime)) - { - S_SwitchDynamicTracks( eMusic_StateActual, eTransition, qfalse ); // qboolean bNewTrackStartsFullVolume + // find the transition track to play, and the entry point for explore when we get there, + // and also see if we're at a permitted exit point to switch at all... + // + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(pMP3StreamActual) - MP3Stream_GetRemainingTimeInSeconds(pMP3StreamActual); - tMusic_Info[eTransition].Rewind(); - tMusic_Info[eTransition].bTrackSwitchPending = qtrue; - tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; - tMusic_Info[eTransition].fTS_NewTime = fNewTrackEntryTime; - } - } - break; + // supply: + // + // playing point in float seconds + // enum of track being queried + // + // get: + // + // enum of transition track to switch to + // float time of entry point of new track *after* transition + + MusicState_e eTransition; + float fNewTrackEntryTime = 0.0f; + if (Music_AllowedToTransition(fPlayingTimeElapsed, eBGRNDTRACK_ACTION, &eTransition, &fNewTrackEntryTime)) { + S_SwitchDynamicTracks(eMusic_StateActual, eTransition, qfalse); // qboolean bNewTrackStartsFullVolume + + tMusic_Info[eTransition].Rewind(); + tMusic_Info[eTransition].bTrackSwitchPending = qtrue; + tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; + tMusic_Info[eTransition].fTS_NewTime = fNewTrackEntryTime; + } + } break; - case eBGRNDTRACK_SILENCE: // silence->explore - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume + case eBGRNDTRACK_SILENCE: // silence->explore + { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume -// float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); -// tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); - tMusic_Info[ eMusic_StateRequest ].Rewind(); - } - break; + // float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); + // tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); + tMusic_Info[eMusic_StateRequest].Rewind(); + } break; - default: // trying to transition from some state I wasn't aware you could transition from (shouldn't happen), so ignore - { - assert(0); - S_SwitchDynamicTracks( eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse ); // qboolean bNewTrackStartsFullVolume - } - break; - } + default: // trying to transition from some state I wasn't aware you could transition from (shouldn't happen), so ignore + { + assert(0); + S_SwitchDynamicTracks(eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse); // qboolean bNewTrackStartsFullVolume + } break; } - break; + } break; - case eBGRNDTRACK_SILENCE: // from explore or action + case eBGRNDTRACK_SILENCE: // from explore or action + { + switch (eMusic_StateActual) { + case eBGRNDTRACK_ACTION: // action->silence + case eBGRNDTRACK_EXPLORE: // explore->silence { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_ACTION: // action->silence - case eBGRNDTRACK_EXPLORE: // explore->silence - { - // find the transition track to play, and the entry point for explore when we get there, - // and also see if we're at a permitted exit point to switch at all... - // - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( pMP3StreamActual ) - MP3Stream_GetRemainingTimeInSeconds( pMP3StreamActual ); - - MusicState_e eTransition; - float fNewTrackEntryTime = 0.0f; - if (Music_AllowedToTransition( fPlayingTimeElapsed, eMusic_StateActual, &eTransition, &fNewTrackEntryTime)) - { - S_SwitchDynamicTracks( eMusic_StateActual, eTransition, qfalse ); // qboolean bNewTrackStartsFullVolume - - tMusic_Info[eTransition].Rewind(); - tMusic_Info[eTransition].bTrackSwitchPending = qtrue; - tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; - tMusic_Info[eTransition].fTS_NewTime = 0.0f; //fNewTrackEntryTime; irrelevant when switching to silence - } - } - break; + // find the transition track to play, and the entry point for explore when we get there, + // and also see if we're at a permitted exit point to switch at all... + // + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(pMP3StreamActual) - MP3Stream_GetRemainingTimeInSeconds(pMP3StreamActual); - default: // some unhandled type switching to silence - assert(0); // fall through since boss case just does silence->switch anyway + MusicState_e eTransition; + float fNewTrackEntryTime = 0.0f; + if (Music_AllowedToTransition(fPlayingTimeElapsed, eMusic_StateActual, &eTransition, &fNewTrackEntryTime)) { + S_SwitchDynamicTracks(eMusic_StateActual, eTransition, qfalse); // qboolean bNewTrackStartsFullVolume - case eBGRNDTRACK_BOSS: // boss->silence - { - S_SwitchDynamicTracks( eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse ); // qboolean bNewTrackStartsFullVolume - } - break; + tMusic_Info[eTransition].Rewind(); + tMusic_Info[eTransition].bTrackSwitchPending = qtrue; + tMusic_Info[eTransition].eTS_NewState = eMusic_StateRequest; + tMusic_Info[eTransition].fTS_NewTime = 0.0f; // fNewTrackEntryTime; irrelevant when switching to silence } - } - break; + } break; - case eBGRNDTRACK_ACTION: // anything->action - { - switch (eMusic_StateActual) - { - case eBGRNDTRACK_SILENCE: // silence->action - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume - tMusic_Info[ eMusic_StateRequest ].Rewind(); - } - break; + default: // some unhandled type switching to silence + assert(0); // fall through since boss case just does silence->switch anyway - default: // !silence->action - { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qtrue ); // qboolean bNewTrackStartsFullVolume - float fEntryTime = Music_GetRandomEntryTime( eMusic_StateRequest ); - tMusic_Info[ eMusic_StateRequest ].SeekTo(fEntryTime); - } - break; - } + case eBGRNDTRACK_BOSS: // boss->silence + { + S_SwitchDynamicTracks(eMusic_StateActual, eBGRNDTRACK_SILENCE, qfalse); // qboolean bNewTrackStartsFullVolume + } break; } - break; + } break; - case eBGRNDTRACK_BOSS: + case eBGRNDTRACK_ACTION: // anything->action + { + switch (eMusic_StateActual) { + case eBGRNDTRACK_SILENCE: // silence->action { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qfalse ); // qboolean bNewTrackStartsFullVolume - // - // ( no need to fast forward or rewind, boss track is only entered into once, at start, and can't exit ) - // - } - break; + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume + tMusic_Info[eMusic_StateRequest].Rewind(); + } break; - case eBGRNDTRACK_DEATH: + default: // !silence->action { - S_SwitchDynamicTracks( eMusic_StateActual, eMusic_StateRequest, qtrue ); // qboolean bNewTrackStartsFullVolume - // - // ( no need to fast forward or rewind, death track is only entered into once, at start, and can't exit or loop) - // + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qtrue); // qboolean bNewTrackStartsFullVolume + float fEntryTime = Music_GetRandomEntryTime(eMusic_StateRequest); + tMusic_Info[eMusic_StateRequest].SeekTo(fEntryTime); + } break; } - break; + } break; + + case eBGRNDTRACK_BOSS: { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qfalse); // qboolean bNewTrackStartsFullVolume + // + // ( no need to fast forward or rewind, boss track is only entered into once, at start, and can't exit ) + // + } break; - default: assert(0); break; // unknown new mode request, so just ignore it + case eBGRNDTRACK_DEATH: { + S_SwitchDynamicTracks(eMusic_StateActual, eMusic_StateRequest, qtrue); // qboolean bNewTrackStartsFullVolume + // + // ( no need to fast forward or rewind, death track is only entered into once, at start, and can't exit or loop) + // + } break; + + default: + assert(0); + break; // unknown new mode request, so just ignore it } } } } -static char gsIntroMusic[MAX_QPATH]={0}; -static char gsLoopMusic [MAX_QPATH]={0}; +static char gsIntroMusic[MAX_QPATH] = {0}; +static char gsLoopMusic[MAX_QPATH] = {0}; -void S_RestartMusic( void ) -{ - if (s_soundStarted && !s_soundMuted ) - { - //if (gsIntroMusic[0] || gsLoopMusic[0]) // dont test this anymore (but still *use* them), they're blank for JK2 dynamic-music levels anyway +void S_RestartMusic(void) { + if (s_soundStarted && !s_soundMuted) { + // if (gsIntroMusic[0] || gsLoopMusic[0]) // dont test this anymore (but still *use* them), they're blank for JK2 dynamic-music levels anyway { - MusicState_e ePrevState = eMusic_StateRequest; - S_StartBackgroundTrack( gsIntroMusic, gsLoopMusic, qfalse ); // ( default music start will set the state to EXPLORE ) - S_SetDynamicMusicState( ePrevState ); // restore to prev state + MusicState_e ePrevState = eMusic_StateRequest; + S_StartBackgroundTrack(gsIntroMusic, gsLoopMusic, qfalse); // ( default music start will set the state to EXPLORE ) + S_SetDynamicMusicState(ePrevState); // restore to prev state } } } @@ -4518,94 +4009,83 @@ void S_RestartMusic( void ) // to be honest, although the code still plays WAVs some of the file-check logic only works for MP3s, so if you ever want // to use WAV music you'll have to do some tweaking below (but I've got other things to do so it'll have to wait - Ste) // -void S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bCalledByCGameStart ) -{ +void S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bCalledByCGameStart) { bMusic_IsDynamic = qfalse; - if (!s_soundStarted) - { //we have no sound, so don't even bother trying + if (!s_soundStarted) { // we have no sound, so don't even bother trying return; } - if ( !intro ) { + if (!intro) { intro = ""; } - if ( !loop || !loop[0] ) { + if (!loop || !loop[0]) { loop = intro; } - if ( intro != gsIntroMusic ) { - Q_strncpyz( gsIntroMusic, intro, sizeof(gsIntroMusic) ); + if (intro != gsIntroMusic) { + Q_strncpyz(gsIntroMusic, intro, sizeof(gsIntroMusic)); } - if ( loop != gsLoopMusic ) { - Q_strncpyz( gsLoopMusic, loop, sizeof(gsLoopMusic) ); + if (loop != gsLoopMusic) { + Q_strncpyz(gsLoopMusic, loop, sizeof(gsLoopMusic)); } char sNameIntro[MAX_QPATH]; - char sNameLoop [MAX_QPATH]; - Q_strncpyz(sNameIntro, intro, sizeof(sNameIntro)); - Q_strncpyz(sNameLoop, loop, sizeof(sNameLoop)); + char sNameLoop[MAX_QPATH]; + Q_strncpyz(sNameIntro, intro, sizeof(sNameIntro)); + Q_strncpyz(sNameLoop, loop, sizeof(sNameLoop)); - COM_DefaultExtension( sNameIntro, sizeof( sNameIntro ), ".mp3" ); - COM_DefaultExtension( sNameLoop, sizeof( sNameLoop), ".mp3" ); + COM_DefaultExtension(sNameIntro, sizeof(sNameIntro), ".mp3"); + COM_DefaultExtension(sNameLoop, sizeof(sNameLoop), ".mp3"); // if dynamic music not allowed, then just stream the explore music instead of playing dynamic... // - if (!s_allowDynamicMusic->integer && Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) + if (!s_allowDynamicMusic->integer && Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) { - const char *psMusicName = Music_GetFileNameForState( eBGRNDTRACK_DATABEGIN ); - if (psMusicName && S_FileExists( psMusicName )) - { - Q_strncpyz(sNameIntro,psMusicName,sizeof(sNameIntro)); - Q_strncpyz(sNameLoop, psMusicName,sizeof(sNameLoop )); + const char *psMusicName = Music_GetFileNameForState(eBGRNDTRACK_DATABEGIN); + if (psMusicName && S_FileExists(psMusicName)) { + Q_strncpyz(sNameIntro, psMusicName, sizeof(sNameIntro)); + Q_strncpyz(sNameLoop, psMusicName, sizeof(sNameLoop)); } } // conceptually we always play the 'intro'[/sName] track, intro-to-loop transition is handled in UpdateBackGroundTrack(). // - if ( (strstr(sNameIntro,"/") && S_FileExists( sNameIntro )) ) // strstr() check avoids extra file-exists check at runtime if reverting from streamed music to dynamic since literal files all need at least one slash in their name (eg "music/blah") + if ((strstr(sNameIntro, "/") && S_FileExists(sNameIntro))) // strstr() check avoids extra file-exists check at runtime if reverting from streamed music to + // dynamic since literal files all need at least one slash in their name (eg "music/blah") { - const char *psLoopName = S_FileExists( sNameLoop ) ? sNameLoop : sNameIntro; + const char *psLoopName = S_FileExists(sNameLoop) ? sNameLoop : sNameIntro; Com_DPrintf("S_StartBackgroundTrack: Found/using non-dynamic music track '%s' (loop: '%s')\n", sNameIntro, psLoopName); - S_StartBackgroundTrack_Actual( &tMusic_Info[eBGRNDTRACK_NONDYNAMIC], bMusic_IsDynamic, sNameIntro, psLoopName ); - } - else - { - if (Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) + S_StartBackgroundTrack_Actual(&tMusic_Info[eBGRNDTRACK_NONDYNAMIC], bMusic_IsDynamic, sNameIntro, psLoopName); + } else { + if (Music_DynamicDataAvailable(intro)) // "intro", NOT "sName" (i.e. don't use version with ".mp3" extension) { extern const char *Music_GetLevelSetName(void); Q_strncpyz(sInfoOnly_CurrentDynamicMusicSet, Music_GetLevelSetName(), sizeof(sInfoOnly_CurrentDynamicMusicSet)); - for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) - { + for (int i = eBGRNDTRACK_DATABEGIN; i != eBGRNDTRACK_DATAEND; i++) { qboolean bOk = qfalse; - const char *psMusicName = Music_GetFileNameForState( (MusicState_e) i); - if (psMusicName && (!Q_stricmp(tMusic_Info[i].sLoadedDataName, psMusicName) || S_FileExists( psMusicName )) ) - { - bOk = S_StartBackgroundTrack_Actual( &tMusic_Info[i], qtrue, psMusicName, loop ); + const char *psMusicName = Music_GetFileNameForState((MusicState_e)i); + if (psMusicName && (!Q_stricmp(tMusic_Info[i].sLoadedDataName, psMusicName) || S_FileExists(psMusicName))) { + bOk = S_StartBackgroundTrack_Actual(&tMusic_Info[i], qtrue, psMusicName, loop); } tMusic_Info[i].bExists = bOk; - if (!tMusic_Info[i].bExists) - { - FreeMusic( &tMusic_Info[i] ); + if (!tMusic_Info[i].bExists) { + FreeMusic(&tMusic_Info[i]); } } // // default all tracks to OFF first (and set any other vars) // - for (int i=0; ibActive = qtrue; - pMusicInfo->iXFadeVolumeSeekTime= Sys_Milliseconds(); - pMusicInfo->iXFadeVolumeSeekTo = 255; - pMusicInfo->iXFadeVolume = 0; + pMusicInfo->bActive = qtrue; + pMusicInfo->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfo->iXFadeVolumeSeekTo = 255; + pMusicInfo->iXFadeVolume = 0; - //#ifdef _DEBUG - // float fRemaining = MP3Stream_GetPlayingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader); - //#endif - } - else - { - Com_Printf( S_COLOR_RED "Dynamic music did not have both 'action' and 'explore' versions, inhibiting...\n"); + //#ifdef _DEBUG + // float fRemaining = MP3Stream_GetPlayingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader); + //#endif + } else { + Com_Printf(S_COLOR_RED "Dynamic music did not have both 'action' and 'explore' versions, inhibiting...\n"); S_StopBackgroundTrack(); } - } - else - { - if (sNameIntro[0]!='.') // blank name with ".mp3" or whatever attached - no error print out + } else { + if (sNameIntro[0] != '.') // blank name with ".mp3" or whatever attached - no error print out { - Com_Printf( S_COLOR_RED "Unable to find music \"%s\" as explicit track or dynamic music entry!\n",sNameIntro); + Com_Printf(S_COLOR_RED "Unable to find music \"%s\" as explicit track or dynamic music entry!\n", sNameIntro); S_StopBackgroundTrack(); } } } - if (bCalledByCGameStart) - { + if (bCalledByCGameStart) { S_StopBackgroundTrack(); } } -void S_StopBackgroundTrack( void ) -{ - for (int i=0; ivalue; - if (bMusic_IsDynamic) - { + if (bMusic_IsDynamic) { // step xfade volume... // - if ( pMusicInfo->iXFadeVolume != pMusicInfo->iXFadeVolumeSeekTo ) - { + if (pMusicInfo->iXFadeVolume != pMusicInfo->iXFadeVolumeSeekTo) { int iFadeMillisecondsElapsed = Sys_Milliseconds() - pMusicInfo->iXFadeVolumeSeekTime; - if (iFadeMillisecondsElapsed > (fDYNAMIC_XFADE_SECONDS * 1000)) - { + if (iFadeMillisecondsElapsed > (fDYNAMIC_XFADE_SECONDS * 1000)) { pMusicInfo->iXFadeVolume = pMusicInfo->iXFadeVolumeSeekTo; - } - else - { - pMusicInfo->iXFadeVolume = (int) (255.0f * ((float)iFadeMillisecondsElapsed/(fDYNAMIC_XFADE_SECONDS * 1000.0f))); - if (pMusicInfo->iXFadeVolumeSeekTo == 0) // bleurgh + } else { + pMusicInfo->iXFadeVolume = (int)(255.0f * ((float)iFadeMillisecondsElapsed / (fDYNAMIC_XFADE_SECONDS * 1000.0f))); + if (pMusicInfo->iXFadeVolumeSeekTo == 0) // bleurgh pMusicInfo->iXFadeVolume = 255 - pMusicInfo->iXFadeVolume; } } @@ -4697,27 +4164,26 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea // normal sfx buffer painting, and allowing sufficient sliding room, even though the music file never goes back in time. // #define SIZEOF_RAW_BUFFER_FOR_MP3 4096 -#define RAWSIZE (pMusicInfo->bIsMP3?SIZEOF_RAW_BUFFER_FOR_MP3:sizeof(raw)) +#define RAWSIZE (pMusicInfo->bIsMP3 ? SIZEOF_RAW_BUFFER_FOR_MP3 : sizeof(raw)) - if ( !pMusicInfo->s_backgroundFile ) { + if (!pMusicInfo->s_backgroundFile) { return qfalse; } - pMusicInfo->fSmoothedOutVolume = (pMusicInfo->fSmoothedOutVolume + fMasterVol)/2.0f; -// Com_OPrintf("%f\n",pMusicInfo->fSmoothedOutVolume); + pMusicInfo->fSmoothedOutVolume = (pMusicInfo->fSmoothedOutVolume + fMasterVol) / 2.0f; + // Com_OPrintf("%f\n",pMusicInfo->fSmoothedOutVolume); // don't bother playing anything if musicvolume is 0 - if ( pMusicInfo->fSmoothedOutVolume <= 0 ) { + if (pMusicInfo->fSmoothedOutVolume <= 0) { return qfalse; } // see how many samples should be copied into the raw buffer - if ( s_rawend < s_soundtime ) { + if (s_rawend < s_soundtime) { s_rawend = s_soundtime; } - while ( s_rawend < s_soundtime + MAX_RAW_SAMPLES ) - { + while (s_rawend < s_soundtime + MAX_RAW_SAMPLES) { bufferSamples = MAX_RAW_SAMPLES - (s_rawend - s_soundtime); // decide how much data needs to be read from the file @@ -4729,34 +4195,30 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea } // don't try and read past the end of the file - if ( fileSamples > pMusicInfo->s_backgroundSamples ) { + if (fileSamples > pMusicInfo->s_backgroundSamples) { fileSamples = pMusicInfo->s_backgroundSamples; } // our max buffer size fileBytes = fileSamples * (pMusicInfo->s_backgroundInfo.width * pMusicInfo->s_backgroundInfo.channels); - if (fileBytes > (int)RAWSIZE ) { + if (fileBytes > (int)RAWSIZE) { fileBytes = RAWSIZE; fileSamples = fileBytes / (pMusicInfo->s_backgroundInfo.width * pMusicInfo->s_backgroundInfo.channels); } qboolean qbForceFinish = qfalse; - if (pMusicInfo->bIsMP3) - { - int iStartingSampleNum = pMusicInfo->chMP3_Bgrnd.thesfx->iSoundLengthInSamples - pMusicInfo->s_backgroundSamples; // but this IS relevant + if (pMusicInfo->bIsMP3) { + int iStartingSampleNum = pMusicInfo->chMP3_Bgrnd.thesfx->iSoundLengthInSamples - pMusicInfo->s_backgroundSamples; // but this IS relevant // Com_Printf(S_COLOR_YELLOW "Requesting MP3 samples: sample %d\n",iStartingSampleNum); - - if (pMusicInfo->s_backgroundFile == -1) - { + if (pMusicInfo->s_backgroundFile == -1) { // in-mem... // - qbForceFinish = (MP3Stream_GetSamples( &pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes/2, (short*) raw, qtrue ))?qfalse:qtrue; + qbForceFinish = (MP3Stream_GetSamples(&pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes / 2, (short *)raw, qtrue)) ? qfalse : qtrue; - //Com_Printf(S_COLOR_YELLOW "Music time remaining: %f seconds\n", MP3Stream_GetRemainingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader )); - } - else - { + // Com_Printf(S_COLOR_YELLOW "Music time remaining: %f seconds\n", MP3Stream_GetRemainingTimeInSeconds( &pMusicInfo->chMP3_Bgrnd.MP3StreamHeader + // )); + } else { // streaming an MP3 file instead... (note that the 'fileBytes' request size isn't that relevant for MP3s, // since code here can't know how much the MP3 needs to decompress) // @@ -4764,67 +4226,56 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea pMusicInfo->chMP3_Bgrnd.MP3StreamHeader.pbSourceData = pbScrolledStreamData - pMusicInfo->chMP3_Bgrnd.MP3StreamHeader.iSourceReadIndex; - qbForceFinish = (MP3Stream_GetSamples( &pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes/2, (short*) raw, qtrue ))?qfalse:qtrue; + qbForceFinish = (MP3Stream_GetSamples(&pMusicInfo->chMP3_Bgrnd, iStartingSampleNum, fileBytes / 2, (short *)raw, qtrue)) ? qfalse : qtrue; } - } - else - { + } else { // streaming a WAV off disk... // - r = FS_Read ( raw, fileBytes, pMusicInfo->s_backgroundFile ); - if ( r != fileBytes ) { - Com_Printf(S_COLOR_RED"StreamedRead failure on music track\n"); + r = FS_Read(raw, fileBytes, pMusicInfo->s_backgroundFile); + if (r != fileBytes) { + Com_Printf(S_COLOR_RED "StreamedRead failure on music track\n"); S_StopBackgroundTrack(); return qfalse; } // byte swap if needed (do NOT do for MP3 decoder, that has an internal big/little endian handler) // - S_ByteSwapRawSamples( fileSamples, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw ); + S_ByteSwapRawSamples(fileSamples, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw); } // add to raw buffer - S_RawSamples( fileSamples, pMusicInfo->s_backgroundInfo.rate, - pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw, pMusicInfo->fSmoothedOutVolume, - bFirstOrOnlyMusicTrack - ); + S_RawSamples(fileSamples, pMusicInfo->s_backgroundInfo.rate, pMusicInfo->s_backgroundInfo.width, pMusicInfo->s_backgroundInfo.channels, raw, + pMusicInfo->fSmoothedOutVolume, bFirstOrOnlyMusicTrack); pMusicInfo->s_backgroundSamples -= fileSamples; - if ( !pMusicInfo->s_backgroundSamples || qbForceFinish ) - { + if (!pMusicInfo->s_backgroundSamples || qbForceFinish) { // loop the music, or play the next piece if we were on the intro... // (but not for dynamic, that can only be used for loop music) // - if (bMusic_IsDynamic) // needs special logic for this, different call + if (bMusic_IsDynamic) // needs special logic for this, different call { pMusicInfo->Rewind(); - } - else - { + } else { // for non-dynamic music we need to check if "sMusic_BackgroundLoop" is an actual filename, // or if it's a dynamic music specifier (which can't literally exist), in which case it should set // a return flag then exit... // - char sTestName[MAX_QPATH*2];// *2 so COM_DefaultExtension doesn't do an ERR_DROP if there was no space - // for an extension, since this is a "soft" test - Q_strncpyz( sTestName, sMusic_BackgroundLoop, sizeof(sTestName)); + char sTestName[MAX_QPATH * 2]; // *2 so COM_DefaultExtension doesn't do an ERR_DROP if there was no space + // for an extension, since this is a "soft" test + Q_strncpyz(sTestName, sMusic_BackgroundLoop, sizeof(sTestName)); COM_DefaultExtension(sTestName, sizeof(sTestName), ".mp3"); - if (S_FileExists( sTestName )) - { - S_StartBackgroundTrack_Actual( pMusicInfo, qfalse, sMusic_BackgroundLoop, sMusic_BackgroundLoop ); - } - else - { + if (S_FileExists(sTestName)) { + S_StartBackgroundTrack_Actual(pMusicInfo, qfalse, sMusic_BackgroundLoop, sMusic_BackgroundLoop); + } else { // proposed file doesn't exist, but this may be a dynamic track we're wanting to loop, // so exit with a special flag... // return qtrue; } } - if ( !pMusicInfo->s_backgroundFile ) - { - return qfalse; // loop failed to restart + if (!pMusicInfo->s_backgroundFile) { + return qfalse; // loop failed to restart } } } @@ -4837,8 +4288,7 @@ static qboolean S_UpdateBackgroundTrack_Actual( MusicInfo_t *pMusicInfo, qboolea // used to be just for dynamic, but now even non-dynamic music has to know whether it should be silent or not... // -static const char *S_Music_GetRequestedState(void) -{ +static const char *S_Music_GetRequestedState(void) { /* int iStringOffset = cl.gameState.stringOffsets[CS_DYNAMIC_MUSIC_STATE]; if (iStringOffset) @@ -4848,7 +4298,7 @@ static const char *S_Music_GetRequestedState(void) return psCommand; } */ - //rwwFIXMEFIXME: Maybe use the above for something in MP? + // rwwFIXMEFIXME: Maybe use the above for something in MP? return NULL; } @@ -4858,179 +4308,144 @@ static const char *S_Music_GetRequestedState(void) // // then go on to do transition handling etc... // -static void S_CheckDynamicMusicState(void) -{ +static void S_CheckDynamicMusicState(void) { const char *psCommand = S_Music_GetRequestedState(); - if (psCommand) - { + if (psCommand) { MusicState_e eNewState; - if ( !Q_stricmpn( psCommand, "silence", 7) ) - { + if (!Q_stricmpn(psCommand, "silence", 7)) { eNewState = eBGRNDTRACK_SILENCE; - } - else if ( !Q_stricmpn( psCommand, "action", 6) ) - { + } else if (!Q_stricmpn(psCommand, "action", 6)) { eNewState = eBGRNDTRACK_ACTION; - } - else if ( !Q_stricmpn( psCommand, "boss", 4) ) - { + } else if (!Q_stricmpn(psCommand, "boss", 4)) { // special case, boss music is optional and may not be defined... // - if (tMusic_Info[ eBGRNDTRACK_BOSS ].bExists) - { + if (tMusic_Info[eBGRNDTRACK_BOSS].bExists) { eNewState = eBGRNDTRACK_BOSS; - } - else - { + } else { // ( leave it playing current track ) // eNewState = eMusic_StateActual; } - } - else if ( !Q_stricmpn( psCommand, "death", 5) ) - { + } else if (!Q_stricmpn(psCommand, "death", 5)) { // special case, death music is optional and may not be defined... // - if (tMusic_Info[ eBGRNDTRACK_DEATH ].bExists) - { + if (tMusic_Info[eBGRNDTRACK_DEATH].bExists) { eNewState = eBGRNDTRACK_DEATH; - } - else - { + } else { // ( leave it playing current track, typically either boss or action ) // eNewState = eMusic_StateActual; } - } - else - { + } else { // seems a reasonable default... // eNewState = eBGRNDTRACK_EXPLORE; } - S_SetDynamicMusicState( eNewState ); + S_SetDynamicMusicState(eNewState); } S_HandleDynamicMusicStateChange(); } -static void S_UpdateBackgroundTrack( void ) -{ - if (bMusic_IsDynamic) - { - if (s_debugdynamic->integer == 2) - { +static void S_UpdateBackgroundTrack(void) { + if (bMusic_IsDynamic) { + if (s_debugdynamic->integer == 2) { DynamicMusicInfoPrint(); } S_CheckDynamicMusicState(); - if (eMusic_StateActual != eBGRNDTRACK_SILENCE) - { - MusicInfo_t *pMusicInfoCurrent = &tMusic_Info[ (eMusic_StateActual == eBGRNDTRACK_FADE)?eBGRNDTRACK_EXPLORE:eMusic_StateActual ]; - MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[ eBGRNDTRACK_FADE ]; + if (eMusic_StateActual != eBGRNDTRACK_SILENCE) { + MusicInfo_t *pMusicInfoCurrent = &tMusic_Info[(eMusic_StateActual == eBGRNDTRACK_FADE) ? eBGRNDTRACK_EXPLORE : eMusic_StateActual]; + MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[eBGRNDTRACK_FADE]; - if ( pMusicInfoCurrent->s_backgroundFile == -1) - { + if (pMusicInfoCurrent->s_backgroundFile == -1) { int iRawEnd = s_rawend; - S_UpdateBackgroundTrack_Actual( pMusicInfoCurrent, qtrue, s_musicVolume->value ); + S_UpdateBackgroundTrack_Actual(pMusicInfoCurrent, qtrue, s_musicVolume->value); - /* static int iPrevFrontVol = 0; - if (iPrevFrontVol != pMusicInfoCurrent->iXFadeVolume) - { - iPrevFrontVol = pMusicInfoCurrent->iXFadeVolume; - Com_Printf("front vol = %d\n",pMusicInfoCurrent->iXFadeVolume); - } - */ - if (pMusicInfoFadeOut->bActive) - { + /* static int iPrevFrontVol = 0; + if (iPrevFrontVol != pMusicInfoCurrent->iXFadeVolume) + { + iPrevFrontVol = pMusicInfoCurrent->iXFadeVolume; + Com_Printf("front vol = %d\n",pMusicInfoCurrent->iXFadeVolume); + } + */ + if (pMusicInfoFadeOut->bActive) { s_rawend = iRawEnd; - S_UpdateBackgroundTrack_Actual( pMusicInfoFadeOut, qfalse, s_musicVolume->value ); // inactive-checked internally - /* - static int iPrevFadeVol = 0; - if (iPrevFadeVol != pMusicInfoFadeOut->iXFadeVolume) - { - iPrevFadeVol = pMusicInfoFadeOut->iXFadeVolume; - Com_Printf("fade vol = %d\n",pMusicInfoFadeOut->iXFadeVolume); - } - */ + S_UpdateBackgroundTrack_Actual(pMusicInfoFadeOut, qfalse, s_musicVolume->value); // inactive-checked internally + /* + static int iPrevFadeVol = 0; + if (iPrevFadeVol != pMusicInfoFadeOut->iXFadeVolume) + { + iPrevFadeVol = pMusicInfoFadeOut->iXFadeVolume; + Com_Printf("fade vol = %d\n",pMusicInfoFadeOut->iXFadeVolume); + } + */ // // only do this for the fader!... // - if (pMusicInfoFadeOut->iXFadeVolume == 0) - { + if (pMusicInfoFadeOut->iXFadeVolume == 0) { pMusicInfoFadeOut->bActive = qfalse; } } - float fRemainingTimeInSeconds = MP3Stream_GetRemainingTimeInSeconds( &pMusicInfoCurrent->chMP3_Bgrnd.MP3StreamHeader ); + float fRemainingTimeInSeconds = MP3Stream_GetRemainingTimeInSeconds(&pMusicInfoCurrent->chMP3_Bgrnd.MP3StreamHeader); // Com_Printf("Remaining: %3.3f\n",fRemainingTimeInSeconds); - if ( fRemainingTimeInSeconds < fDYNAMIC_XFADE_SECONDS*2 ) - { + if (fRemainingTimeInSeconds < fDYNAMIC_XFADE_SECONDS * 2) { // now either loop current track, switch if finishing a transition, or stop if finished a death... // - if (pMusicInfoCurrent->bTrackSwitchPending) - { - pMusicInfoCurrent->bTrackSwitchPending = qfalse; // ack - S_SwitchDynamicTracks( eMusic_StateActual, pMusicInfoCurrent->eTS_NewState, qfalse); // qboolean bNewTrackStartsFullVolume - if (tMusic_Info[ pMusicInfoCurrent->eTS_NewState ].bExists) // don't do this if switching to silence + if (pMusicInfoCurrent->bTrackSwitchPending) { + pMusicInfoCurrent->bTrackSwitchPending = qfalse; // ack + S_SwitchDynamicTracks(eMusic_StateActual, pMusicInfoCurrent->eTS_NewState, qfalse); // qboolean bNewTrackStartsFullVolume + if (tMusic_Info[pMusicInfoCurrent->eTS_NewState].bExists) // don't do this if switching to silence { - tMusic_Info[ pMusicInfoCurrent->eTS_NewState ].SeekTo(pMusicInfoCurrent->fTS_NewTime); + tMusic_Info[pMusicInfoCurrent->eTS_NewState].SeekTo(pMusicInfoCurrent->fTS_NewTime); } - } - else - { + } else { // normal looping, so set rewind current track, set volume to 0 and fade up to full (unless death track playing, then stays quiet) // (while fader copy of end-section fades down) // // copy current track to fader... // - *pMusicInfoFadeOut = *pMusicInfoCurrent; // struct copy - pMusicInfoFadeOut->iXFadeVolumeSeekTime = Sys_Milliseconds(); - pMusicInfoFadeOut->iXFadeVolumeSeekTo = 0; + *pMusicInfoFadeOut = *pMusicInfoCurrent; // struct copy + pMusicInfoFadeOut->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfoFadeOut->iXFadeVolumeSeekTo = 0; // pMusicInfoCurrent->Rewind(); - pMusicInfoCurrent->iXFadeVolumeSeekTime = Sys_Milliseconds(); - pMusicInfoCurrent->iXFadeVolumeSeekTo = (eMusic_StateActual == eBGRNDTRACK_DEATH) ? 0: 255; - pMusicInfoCurrent->iXFadeVolume = 0; + pMusicInfoCurrent->iXFadeVolumeSeekTime = Sys_Milliseconds(); + pMusicInfoCurrent->iXFadeVolumeSeekTo = (eMusic_StateActual == eBGRNDTRACK_DEATH) ? 0 : 255; + pMusicInfoCurrent->iXFadeVolume = 0; } } } - } - else - { + } else { // special case, when foreground music is shut off but fader still running to fade off previous track... // - MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[ eBGRNDTRACK_FADE ]; - if (pMusicInfoFadeOut->bActive) - { - S_UpdateBackgroundTrack_Actual( pMusicInfoFadeOut, qtrue, s_musicVolume->value ); - if (pMusicInfoFadeOut->iXFadeVolume == 0) - { + MusicInfo_t *pMusicInfoFadeOut = &tMusic_Info[eBGRNDTRACK_FADE]; + if (pMusicInfoFadeOut->bActive) { + S_UpdateBackgroundTrack_Actual(pMusicInfoFadeOut, qtrue, s_musicVolume->value); + if (pMusicInfoFadeOut->iXFadeVolume == 0) { pMusicInfoFadeOut->bActive = qfalse; } } } - } - else - { + } else { // standard / non-dynamic one-track music... // - const char *psCommand = S_Music_GetRequestedState(); // special check just for "silence" case... - qboolean bShouldBeSilent = (qboolean)(psCommand && !Q_stricmp(psCommand,"silence")); + const char *psCommand = S_Music_GetRequestedState(); // special check just for "silence" case... + qboolean bShouldBeSilent = (qboolean)(psCommand && !Q_stricmp(psCommand, "silence")); float fDesiredVolume = bShouldBeSilent ? 0.0f : s_musicVolume->value; // // internal to this code is a volume-smoother... // qboolean bNewTrackDesired = S_UpdateBackgroundTrack_Actual(&tMusic_Info[eBGRNDTRACK_NONDYNAMIC], qtrue, fDesiredVolume); - if (bNewTrackDesired) - { - S_StartBackgroundTrack( sMusic_BackgroundLoop, sMusic_BackgroundLoop, qfalse ); + if (bNewTrackDesired) { + S_StartBackgroundTrack(sMusic_BackgroundLoop, sMusic_BackgroundLoop, qfalse); } } } @@ -5039,19 +4454,16 @@ cvar_t *s_soundpoolmegs = NULL; // currently passing in sfx as a param in case I want to do something with it later. // -byte *SND_malloc(int iSize, sfx_t *sfx) -{ - byte *pData = (byte *) Z_Malloc(iSize, TAG_SND_RAWDATA, qfalse); // don't bother asking for zeroed mem +byte *SND_malloc(int iSize, sfx_t *sfx) { + byte *pData = (byte *)Z_Malloc(iSize, TAG_SND_RAWDATA, qfalse); // don't bother asking for zeroed mem // if "s_soundpoolmegs" is < 0, then the -ve of the value is the maximum amount of sounds we're allowed to have loaded... // - if (s_soundpoolmegs && s_soundpoolmegs->integer < 0) - { - while ( (Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR)) > ((-s_soundpoolmegs->integer) * 1024 * 1024)) - { + if (s_soundpoolmegs && s_soundpoolmegs->integer < 0) { + while ((Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR)) > ((-s_soundpoolmegs->integer) * 1024 * 1024)) { int iBytesFreed = SND_FreeOldestSound(sfx); if (iBytesFreed == 0) - break; // sanity + break; // sanity } } @@ -5060,11 +4472,9 @@ byte *SND_malloc(int iSize, sfx_t *sfx) // called once-only in EXE lifetime... // -void SND_setup() -{ +void SND_setup() { s_soundpoolmegs = Cvar_Get("s_soundpoolmegs", "25", CVAR_ARCHIVE); - if (Sys_LowPhysicalMemory() ) - { + if (Sys_LowPhysicalMemory()) { Cvar_Set("s_soundpoolmegs", "0"); } @@ -5073,10 +4483,9 @@ void SND_setup() // ask how much mem an sfx has allocated... // -static int SND_MemUsed(sfx_t *sfx) -{ +static int SND_MemUsed(sfx_t *sfx) { int iSize = 0; - if (sfx->pSoundData){ + if (sfx->pSoundData) { iSize += Z_Size(sfx->pSoundData); } @@ -5091,92 +4500,79 @@ static int SND_MemUsed(sfx_t *sfx) // // now returns # bytes freed to help with z_malloc()-fail recovery // -static int SND_FreeSFXMem(sfx_t *sfx) -{ +static int SND_FreeSFXMem(sfx_t *sfx) { int iBytesFreed = 0; #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { alGetError(); - if (sfx->Buffer) - { + if (sfx->Buffer) { alDeleteBuffers(1, &(sfx->Buffer)); #ifdef _DEBUG - if (alGetError() != AL_NO_ERROR) - { + if (alGetError() != AL_NO_ERROR) { Com_OPrintf("Failed to delete AL Buffer (%s) ... !\n", sfx->sSoundName); } #endif sfx->Buffer = 0; } - if (sfx->lipSyncData) - { - iBytesFreed += Z_Size( sfx->lipSyncData); - Z_Free( sfx->lipSyncData); - sfx->lipSyncData = NULL; + if (sfx->lipSyncData) { + iBytesFreed += Z_Size(sfx->lipSyncData); + Z_Free(sfx->lipSyncData); + sfx->lipSyncData = NULL; } } #endif - if ( sfx->pSoundData) { - iBytesFreed += Z_Size( sfx->pSoundData); - Z_Free( sfx->pSoundData ); - sfx->pSoundData = NULL; + if (sfx->pSoundData) { + iBytesFreed += Z_Size(sfx->pSoundData); + Z_Free(sfx->pSoundData); + sfx->pSoundData = NULL; } sfx->bInMemory = qfalse; - if ( sfx->pMP3StreamHeader) { - iBytesFreed += Z_Size( sfx->pMP3StreamHeader); - Z_Free( sfx->pMP3StreamHeader ); - sfx->pMP3StreamHeader = NULL; + if (sfx->pMP3StreamHeader) { + iBytesFreed += Z_Size(sfx->pMP3StreamHeader); + Z_Free(sfx->pMP3StreamHeader); + sfx->pMP3StreamHeader = NULL; } return iBytesFreed; } -void S_DisplayFreeMemory() -{ - int iSoundDataSize = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); - int iMusicDataSize = Z_MemSize ( TAG_SND_DYNAMICMUSIC ); +void S_DisplayFreeMemory() { + int iSoundDataSize = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); + int iMusicDataSize = Z_MemSize(TAG_SND_DYNAMICMUSIC); - if (iSoundDataSize || iMusicDataSize) - { - Com_Printf("\n%.2fMB audio data: ( %.2fMB WAV/MP3 ) + ( %.2fMB Music )\n", - ((float)(iSoundDataSize+iMusicDataSize))/1024.0f/1024.0f, - ((float)(iSoundDataSize))/1024.0f/1024.0f, - ((float)(iMusicDataSize))/1024.0f/1024.0f - ); + if (iSoundDataSize || iMusicDataSize) { + Com_Printf("\n%.2fMB audio data: ( %.2fMB WAV/MP3 ) + ( %.2fMB Music )\n", ((float)(iSoundDataSize + iMusicDataSize)) / 1024.0f / 1024.0f, + ((float)(iSoundDataSize)) / 1024.0f / 1024.0f, ((float)(iMusicDataSize)) / 1024.0f / 1024.0f); // now count up amount used on this level... // iSoundDataSize = 0; - for (int i=1; iiLastLevelUsedOn == re->RegisterMedia_GetLevel()){ + if (sfx->iLastLevelUsedOn == re->RegisterMedia_GetLevel()) { iSoundDataSize += SND_MemUsed(sfx); } } - Com_Printf("%.2fMB in sfx_t alloc data (WAV/MP3) loaded this level\n",(float)iSoundDataSize/1024.0f/1024.0f); + Com_Printf("%.2fMB in sfx_t alloc data (WAV/MP3) loaded this level\n", (float)iSoundDataSize / 1024.0f / 1024.0f); } } -void SND_TouchSFX(sfx_t *sfx) -{ - sfx->iLastTimeUsed = Com_Milliseconds()+1; - sfx->iLastLevelUsedOn = re->RegisterMedia_GetLevel(); +void SND_TouchSFX(sfx_t *sfx) { + sfx->iLastTimeUsed = Com_Milliseconds() + 1; + sfx->iLastLevelUsedOn = re->RegisterMedia_GetLevel(); } // currently this is only called during snd_shutdown or snd_restart // -void S_FreeAllSFXMem(void) -{ - for (int i=1 ; i < s_numSfx ; i++) // start @ 1 to skip freeing default sound +void S_FreeAllSFXMem(void) { + for (int i = 1; i < s_numSfx; i++) // start @ 1 to skip freeing default sound { SND_FreeSFXMem(&s_knownSfx[i]); } @@ -5186,36 +4582,30 @@ void S_FreeAllSFXMem(void) // // new param is so we can be usre of not freeing ourselves (without having to rely on possible uninitialised timers etc) // -int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) -{ +int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) { int iBytesFreed = 0; sfx_t *sfx; - int iOldest = Com_Milliseconds(); - int iUsed = 0; + int iOldest = Com_Milliseconds(); + int iUsed = 0; // start on 1 so we never dump the default sound... // - for (int i=1 ; i < s_numSfx ; i++) - { + for (int i = 1; i < s_numSfx; i++) { sfx = &s_knownSfx[i]; - if (sfx != pButNotThisOne) - { - if (!sfx->bDefaultSound && sfx->bInMemory && sfx->iLastTimeUsed < iOldest) - { + if (sfx != pButNotThisOne) { + if (!sfx->bDefaultSound && sfx->bInMemory && sfx->iLastTimeUsed < iOldest) { // new bit, we can't throw away any sfx_t struct in use by a channel, else the paint code will crash... // int iChannel; - for (iChannel=0; iChannelthesfx == sfx) - break; // damn, being used + break; // damn, being used } - if (iChannel == MAX_CHANNELS) - { + if (iChannel == MAX_CHANNELS) { // this sfx_t struct wasn't used by any channels, so we can lose it... // iUsed = i; @@ -5225,9 +4615,8 @@ int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) } } - if (iUsed) - { - sfx = &s_knownSfx[ iUsed ]; + if (iUsed) { + sfx = &s_knownSfx[iUsed]; Com_DPrintf("SND_FreeOldestSound: freeing sound %s\n", sfx->sSoundName); @@ -5236,9 +4625,8 @@ int SND_FreeOldestSound(sfx_t *pButNotThisOne /* = NULL */) return iBytesFreed; } -int SND_FreeOldestSound(void) -{ - return SND_FreeOldestSound(NULL); // I had to add a void-arg version of this because of link issues, sigh +int SND_FreeOldestSound(void) { + return SND_FreeOldestSound(NULL); // I had to add a void-arg version of this because of link issues, sigh } // just before we drop into a level, ensure the audio pool is under whatever the maximum @@ -5247,54 +4635,45 @@ int SND_FreeOldestSound(void) // returns qtrue if at least one sound was dropped out, so z_malloc-fail recovery code knows if anything changed // extern qboolean gbInsideLoadSound; -qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */) -{ +qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* 99% qfalse */) { qboolean bAtLeastOneSoundDropped = qfalse; - Com_DPrintf( "SND_RegisterAudio_LevelLoadEnd():\n"); + Com_DPrintf("SND_RegisterAudio_LevelLoadEnd():\n"); - if (gbInsideLoadSound) - { - Com_DPrintf( "(Inside S_LoadSound (z_malloc recovery?), exiting...\n"); - } - else - { - int iLoadedAudioBytes = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); + if (gbInsideLoadSound) { + Com_DPrintf("(Inside S_LoadSound (z_malloc recovery?), exiting...\n"); + } else { + int iLoadedAudioBytes = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); const int iMaxAudioBytes = s_soundpoolmegs->integer * 1024 * 1024; - for (int i=1; i iMaxAudioBytes || bDeleteEverythingNotUsedThisLevel) ; i++) // i=1 so we never page out default sound + for (int i = 1; i < s_numSfx && (iLoadedAudioBytes > iMaxAudioBytes || bDeleteEverythingNotUsedThisLevel); + i++) // i=1 so we never page out default sound { sfx_t *sfx = &s_knownSfx[i]; - if (sfx->bInMemory) - { + if (sfx->bInMemory) { qboolean bDeleteThis = qfalse; - if (bDeleteEverythingNotUsedThisLevel) - { + if (bDeleteEverythingNotUsedThisLevel) { bDeleteThis = (qboolean)(sfx->iLastLevelUsedOn != re->RegisterMedia_GetLevel()); - } - else - { + } else { bDeleteThis = (qboolean)(sfx->iLastLevelUsedOn < re->RegisterMedia_GetLevel()); } - if (bDeleteThis) - { - Com_DPrintf( "Dumping sfx_t \"%s\"\n",sfx->sSoundName); + if (bDeleteThis) { + Com_DPrintf("Dumping sfx_t \"%s\"\n", sfx->sSoundName); - if (SND_FreeSFXMem(sfx)) - { + if (SND_FreeSFXMem(sfx)) { bAtLeastOneSoundDropped = qtrue; } - iLoadedAudioBytes = Z_MemSize ( TAG_SND_RAWDATA ) + Z_MemSize( TAG_SND_MP3STREAMHDR ); + iLoadedAudioBytes = Z_MemSize(TAG_SND_RAWDATA) + Z_MemSize(TAG_SND_MP3STREAMHDR); } } } } - Com_DPrintf( "SND_RegisterAudio_LevelLoadEnd(): Ok\n"); + Com_DPrintf("SND_RegisterAudio_LevelLoadEnd(): Ok\n"); return bAtLeastOneSoundDropped; } @@ -5309,59 +4688,48 @@ qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLev /* Initialize the EAX Manager */ -void InitEAXManager() -{ +void InitEAXManager() { LPEAXMANAGERCREATE lpEAXManagerCreateFn; EAXFXSLOTPROPERTIES FXSlotProp; - GUID Effect; - GUID FXSlotGuids[4]; + GUID Effect; + GUID FXSlotGuids[4]; int i; s_bEALFileLoaded = false; // Check for EAX 4.0 support - s_bEAX = alIsExtensionPresent((ALubyte*)"EAX4.0"); + s_bEAX = alIsExtensionPresent((ALubyte *)"EAX4.0"); - if (s_bEAX) - { + if (s_bEAX) { Com_Printf("Found EAX 4.0 native support\n"); - } - else - { + } else { // Support for EAXUnified (automatic translation of EAX 4.0 calls into EAX 3.0) - if ((alIsExtensionPresent((ALubyte*)"EAX3.0")) && (alIsExtensionPresent((ALubyte*)"EAX4.0Emulated"))) - { + if ((alIsExtensionPresent((ALubyte *)"EAX3.0")) && (alIsExtensionPresent((ALubyte *)"EAX4.0Emulated"))) { s_bEAX = AL_TRUE; Com_Printf("Found EAX 4.0 EMULATION support\n"); } } - if (s_bEAX) - { - s_eaxSet = (EAXSet)alGetProcAddress((ALubyte*)"EAXSet"); + if (s_bEAX) { + s_eaxSet = (EAXSet)alGetProcAddress((ALubyte *)"EAXSet"); if (s_eaxSet == NULL) s_bEAX = false; - s_eaxGet = (EAXGet)alGetProcAddress((ALubyte*)"EAXGet"); + s_eaxGet = (EAXGet)alGetProcAddress((ALubyte *)"EAXGet"); if (s_eaxGet == NULL) s_bEAX = false; } // If we have detected EAX support, then try and load the EAX Manager DLL - if (s_bEAX) - { + if (s_bEAX) { s_hEAXManInst = LoadLibrary("EAXMan.dll"); - if (s_hEAXManInst) - { + if (s_hEAXManInst) { lpEAXManagerCreateFn = (LPEAXMANAGERCREATE)GetProcAddress(s_hEAXManInst, "EaxManagerCreate"); - if (lpEAXManagerCreateFn) - { - if (lpEAXManagerCreateFn(&s_lpEAXManager)==EM_OK) - { + if (lpEAXManagerCreateFn) { + if (lpEAXManagerCreateFn(&s_lpEAXManager) == EM_OK) { // Configure our EAX 4.0 Effect Slots s_NumFXSlots = 0; - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { s_FXSlotInfo[i].FXSlotGuid = EAX_NULL_GUID; s_FXSlotInfo[i].lEnvID = -1; } @@ -5377,22 +4745,16 @@ void InitEAXManager() FXSlotProp.lLock = EAXFXSLOT_LOCKED; FXSlotProp.ulFlags = EAXFXSLOTFLAGS_ENVIRONMENT; - for (i = 0; i < EAX_MAX_FXSLOTS; i++) - { - if (s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_ALLPARAMETERS, NULL, &FXSlotProp, sizeof(EAXFXSLOTPROPERTIES))==AL_NO_ERROR) - { + for (i = 0; i < EAX_MAX_FXSLOTS; i++) { + if (s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_ALLPARAMETERS, NULL, &FXSlotProp, sizeof(EAXFXSLOTPROPERTIES)) == AL_NO_ERROR) { // We can use this slot s_FXSlotInfo[s_NumFXSlots].FXSlotGuid = FXSlotGuids[i]; s_NumFXSlots++; - } - else - { + } else { // If this slot already contains a reverb, then we will use it anyway (Slot 0 will // be in this category). (It probably means that Slot 0 is locked) - if (s_eaxGet(&FXSlotGuids[i], EAXFXSLOT_LOADEFFECT, NULL, &Effect, sizeof(GUID))==AL_NO_ERROR) - { - if (Effect == EAX_REVERB_EFFECT) - { + if (s_eaxGet(&FXSlotGuids[i], EAXFXSLOT_LOADEFFECT, NULL, &Effect, sizeof(GUID)) == AL_NO_ERROR) { + if (Effect == EAX_REVERB_EFFECT) { // We can use this slot // Make sure the environment flag is on s_eaxSet(&FXSlotGuids[i], EAXFXSLOT_FLAGS, NULL, &FXSlotProp.ulFlags, sizeof(unsigned long)); @@ -5410,8 +4772,7 @@ void InitEAXManager() } // If the EAXManager library was loaded (and there was a problem), then unload it - if (s_hEAXManInst) - { + if (s_hEAXManInst) { FreeLibrary(s_hEAXManInst); s_hEAXManInst = NULL; } @@ -5425,19 +4786,16 @@ void InitEAXManager() /* Release the EAX Manager */ -void ReleaseEAXManager() -{ +void ReleaseEAXManager() { s_bEAX = false; UnloadEALFile(); - if (s_lpEAXManager) - { + if (s_lpEAXManager) { s_lpEAXManager->Release(); s_lpEAXManager = NULL; } - if (s_hEAXManInst) - { + if (s_hEAXManInst) { FreeLibrary(s_hEAXManInst); s_hEAXManInst = NULL; } @@ -5446,19 +4804,18 @@ void ReleaseEAXManager() /* Try to load the given .eal file */ -bool LoadEALFile(char *szEALFilename) -{ - char *ealData = NULL; - HRESULT hr; - long i, j, lID, lEnvID; - EMPOINT EMPoint; - char szAperture[128]; - char szFullEALFilename[MAX_QPATH]; - long lNumInst, lNumInstA, lNumInstB; - bool bLoaded = false; - bool bValid = true; - int result; - char szString[256]; +bool LoadEALFile(char *szEALFilename) { + char *ealData = NULL; + HRESULT hr; + long i, j, lID, lEnvID; + EMPOINT EMPoint; + char szAperture[128]; + char szFullEALFilename[MAX_QPATH]; + long lNumInst, lNumInstA, lNumInstB; + bool bLoaded = false; + bool bValid = true; + int result; + char szString[256]; if ((!s_lpEAXManager) || (!s_bEAX)) return false; @@ -5474,197 +4831,147 @@ bool LoadEALFile(char *szEALFilename) // Load EAL file from PAK file result = FS_ReadFile(szEALFilename, (void **)&ealData); - if ((ealData) && (result != -1)) - { + if ((ealData) && (result != -1)) { hr = s_lpEAXManager->LoadDataSet(ealData, EMFLAG_LOADFROMMEMORY); // Unload EAL file - FS_FreeFile (ealData); + FS_FreeFile(ealData); - if (hr == EM_OK) - { + if (hr == EM_OK) { Com_DPrintf("Loaded %s by Quake loader\n", szEALFilename); bLoaded = true; } - } - else - { + } else { // Failed to load via Quake loader, try manually Com_sprintf(szFullEALFilename, MAX_QPATH, "base/%s", szEALFilename); - if (SUCCEEDED(s_lpEAXManager->LoadDataSet(szFullEALFilename, 0))) - { + if (SUCCEEDED(s_lpEAXManager->LoadDataSet(szFullEALFilename, 0))) { Com_DPrintf("Loaded %s by EAXManager\n", szEALFilename); bLoaded = true; } } - if (bLoaded) - { + if (bLoaded) { // For a valid eal file ... need to find 'Center' tag, record num of instances, and then find // the right number of instances of 'Aperture0a' and 'Aperture0b'. - if (s_lpEAXManager->GetSourceID("Center", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &s_lNumEnvironments)==EM_OK) - { - if (s_lpEAXManager->GetSourceID("Aperture0a", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - if (lNumInst == s_lNumEnvironments) - { - if (s_lpEAXManager->GetSourceID("Aperture0b", &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - if (lNumInst == s_lNumEnvironments) - { + if (s_lpEAXManager->GetSourceID("Center", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &s_lNumEnvironments) == EM_OK) { + if (s_lpEAXManager->GetSourceID("Aperture0a", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + if (lNumInst == s_lNumEnvironments) { + if (s_lpEAXManager->GetSourceID("Aperture0b", &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + if (lNumInst == s_lNumEnvironments) { // Check equal numbers of ApertureXa and ApertureXb i = 1; - while (true) - { + while (true) { lNumInstA = lNumInstB = 0; - sprintf(szAperture,"Aperture%da",i); - if ((s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) && (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstA)==EM_OK)) - { - sprintf(szAperture,"Aperture%db",i); + sprintf(szAperture, "Aperture%da", i); + if ((s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) && + (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstA) == EM_OK)) { + sprintf(szAperture, "Aperture%db", i); s_lpEAXManager->GetSourceID(szAperture, &lID); s_lpEAXManager->GetSourceNumInstances(lID, &lNumInstB); - if (lNumInstA!=lNumInstB) - { - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL file - %d Aperture%da tags, and %d Aperture%db tags\n", lNumInstA, i, lNumInstB, i); + if (lNumInstA != lNumInstB) { + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL file - %d Aperture%da tags, and %d Aperture%db tags\n", lNumInstA, + i, lNumInstB, i); bValid = false; } - } - else - { + } else { break; } i++; } - if (bValid) - { + if (bValid) { s_lpEnvTable = (LPENVTABLE)Z_Malloc(s_lNumEnvironments * sizeof(ENVTABLE), TAG_GENERAL, qtrue); } - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - expected %d instances of Aperture0b, found %d\n", s_lNumEnvironments, lNumInst); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0b' source-tag\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - found %d instances of the 'Center' tag, but only %d instances of 'Aperture0a'\n", s_lNumEnvironments, lNumInst); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0a' source-tag\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); - } - else - Com_DPrintf( S_COLOR_YELLOW "Invalid EAL File - no instances of 'Center' source-tag\n"); - - - if (s_lpEnvTable) - { + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - expected %d instances of Aperture0b, found %d\n", s_lNumEnvironments, + lNumInst); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0b' source-tag\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - found %d instances of the 'Center' tag, but only %d instances of 'Aperture0a'\n", + s_lNumEnvironments, lNumInst); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Aperture0a' source-tag\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "EAXManager- failed GetSourceNumInstances()\n"); + } else + Com_DPrintf(S_COLOR_YELLOW "Invalid EAL File - no instances of 'Center' source-tag\n"); + + if (s_lpEnvTable) { i = 0; - while (true) - { + while (true) { sprintf(szAperture, "Aperture%da", i); - if (s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - for (j = 0; j < s_lNumEnvironments; j++) - { + if (s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + for (j = 0; j < s_lNumEnvironments; j++) { s_lpEnvTable[j].bUsed = false; } - for (j = 0; j < lNumInst; j++) - { - if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint)==EM_OK) - { - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0)==EM_OK) - { - if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) - { - if (!s_lpEnvTable[lEnvID].bUsed) - { + for (j = 0; j < lNumInst; j++) { + if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint) == EM_OK) { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0) == EM_OK) { + if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) { + if (!s_lpEnvTable[lEnvID].bUsed) { s_lpEnvTable[lEnvID].bUsed = true; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0] = EMPoint.fX; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1] = EMPoint.fY; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2] = EMPoint.fZ; - } - else - { + } else { s_lpEAXManager->GetEnvironmentName(lEnvID, szString, 256); - Com_DPrintf( S_COLOR_YELLOW "Found more than one occurance of Aperture%da in %s sub-space\n", i, szString); - Com_DPrintf( S_COLOR_YELLOW "One tag at %.3f,%.3f,%.3f, other at %.3f,%.3f,%.3f\n", EMPoint.fX, EMPoint.fY, EMPoint.fZ, - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0], s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1], - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2]); + Com_DPrintf(S_COLOR_YELLOW "Found more than one occurance of Aperture%da in %s sub-space\n", i, szString); + Com_DPrintf(S_COLOR_YELLOW "One tag at %.3f,%.3f,%.3f, other at %.3f,%.3f,%.3f\n", EMPoint.fX, EMPoint.fY, + EMPoint.fZ, s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0], + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1], + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2]); bValid = false; } - } - else - { - if (lEnvID==-1) - Com_DPrintf( S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, EMPoint.fY, EMPoint.fZ); + } else { + if (lEnvID == -1) + Com_DPrintf(S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, + EMPoint.fY, EMPoint.fZ); else - Com_DPrintf( S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); + Com_DPrintf(S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); bValid = false; } } } } } - } - else - { + } else { break; } - if (bValid) - { + if (bValid) { sprintf(szAperture, "Aperture%db", i); - if (s_lpEAXManager->GetSourceID(szAperture, &lID)==EM_OK) - { - if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst)==EM_OK) - { - for (j = 0; j < s_lNumEnvironments; j++) - { + if (s_lpEAXManager->GetSourceID(szAperture, &lID) == EM_OK) { + if (s_lpEAXManager->GetSourceNumInstances(lID, &lNumInst) == EM_OK) { + for (j = 0; j < s_lNumEnvironments; j++) { s_lpEnvTable[j].bUsed = false; } - for (j = 0; j < lNumInst; j++) - { - if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint)==EM_OK) - { - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0)==EM_OK) - { - if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) - { - if (!s_lpEnvTable[lEnvID].bUsed) - { + for (j = 0; j < lNumInst; j++) { + if (s_lpEAXManager->GetSourceInstancePos(lID, j, &EMPoint) == EM_OK) { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMPoint, &lEnvID, 0) == EM_OK) { + if ((lEnvID >= 0) && (lEnvID < s_lNumEnvironments)) { + if (!s_lpEnvTable[lEnvID].bUsed) { s_lpEnvTable[lEnvID].bUsed = true; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0] = EMPoint.fX; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1] = EMPoint.fY; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2] = EMPoint.fZ; - } - else - { + } else { s_lpEAXManager->GetEnvironmentName(lEnvID, szString, 256); - Com_DPrintf( S_COLOR_YELLOW "Found more than one occurance of Aperture%db in %s sub-space\n", i, szString); + Com_DPrintf(S_COLOR_YELLOW "Found more than one occurance of Aperture%db in %s sub-space\n", i, szString); bValid = false; } @@ -5672,24 +4979,26 @@ bool LoadEALFile(char *szEALFilename) s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[0] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[0] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[0]) / + 2; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[1] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[1] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[1]) / + 2; s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vCenter[2] = (s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos1[2] + - s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2]) / 2; + s_lpEnvTable[lEnvID].Aperture[s_lpEnvTable[lEnvID].ulNumApertures].vPos2[2]) / + 2; s_lpEnvTable[lEnvID].ulNumApertures++; - } - else - { - if (lEnvID==-1) - Com_DPrintf( S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, EMPoint.fX, EMPoint.fY, EMPoint.fZ); + } else { + if (lEnvID == -1) + Com_DPrintf(S_COLOR_YELLOW "%s (%.3f,%.3f,%.3f) in Default Environment - please remove\n", szAperture, + EMPoint.fX, EMPoint.fY, EMPoint.fZ); else - Com_DPrintf( S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); + Com_DPrintf(S_COLOR_YELLOW "Detected more reverb presets than zones - please delete unused presets\n"); bValid = false; } } @@ -5699,36 +5008,32 @@ bool LoadEALFile(char *szEALFilename) } } - if (!bValid) - { + if (!bValid) { // Found a problem - Com_DPrintf( S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); + Com_DPrintf(S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); - Z_Free( s_lpEnvTable ); + Z_Free(s_lpEnvTable); s_lpEnvTable = NULL; break; } i++; } - } - else - { - Com_DPrintf( S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); + } else { + Com_DPrintf(S_COLOR_YELLOW "EAX legacy behaviour invoked (one reverb)\n"); } return true; } - Com_DPrintf( S_COLOR_YELLOW "Failed to load %s\n", szEALFilename); + Com_DPrintf(S_COLOR_YELLOW "Failed to load %s\n", szEALFilename); return false; } /* Unload current .eal file */ -void UnloadEALFile() -{ +void UnloadEALFile() { HRESULT hr; if ((!s_lpEAXManager) || (!s_bEAX)) @@ -5737,9 +5042,8 @@ void UnloadEALFile() hr = s_lpEAXManager->FreeDataSet(0); s_bEALFileLoaded = false; - if (s_lpEnvTable) - { - Z_Free( s_lpEnvTable ); + if (s_lpEnvTable) { + Z_Free(s_lpEnvTable); s_lpEnvTable = NULL; } @@ -5749,8 +5053,7 @@ void UnloadEALFile() /* Updates the current EAX Reverb setting, based on the location of the listener */ -void UpdateEAXListener() -{ +void UpdateEAXListener() { EMPOINT ListPos, ListOri; EMPOINT EMAperture; EMPOINT EMSourcePoint; @@ -5761,8 +5064,8 @@ void UpdateEAXListener() bool bFound; long lVolume; long lCurTime; - channel_t *ch; - EAXVECTOR LR, LP1, LP2, Pan; + channel_t *ch; + EAXVECTOR LR, LP1, LP2, Pan; REVERBDATA ReverbData[3]; // Hardcoded to three (maximum no of reverbs) #ifdef DISPLAY_CLOSEST_ENVS char szEnvName[256]; @@ -5773,37 +5076,31 @@ void UpdateEAXListener() lCurTime = timeGetTime(); - if ((s_lLastEnvUpdate + ENV_UPDATE_RATE) < lCurTime) - { + if ((s_lLastEnvUpdate + ENV_UPDATE_RATE) < lCurTime) { // Update closest reverbs s_lLastEnvUpdate = lCurTime; // No panning information in .eal file, or we only have 1 FX Slot to use, revert to legacy // behaviour (i.e only one reverb) - if ((!s_lpEnvTable) || (s_NumFXSlots==1)) - { + if ((!s_lpEnvTable) || (s_NumFXSlots == 1)) { // Convert Listener co-ordinate to left-handed system ListPos.fX = listener_pos[0]; ListPos.fY = listener_pos[1]; ListPos.fZ = -listener_pos[2]; - if (SUCCEEDED(s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION))) - { - if (lID != s_EnvironmentID) - { + if (SUCCEEDED(s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION))) { + if (lID != s_EnvironmentID) { #ifdef DISPLAY_CLOSEST_ENVS if (SUCCEEDED(s_lpEAXManager->GetEnvironmentName(lID, szEnvName, 256))) Com_Printf("Changing to '%s' zone !\n", szEnvName); #endif // Get EAX Preset info. - if (SUCCEEDED(s_lpEAXManager->GetEnvironmentAttributes(lID, &s_eaxLPCur))) - { + if (SUCCEEDED(s_lpEAXManager->GetEnvironmentAttributes(lID, &s_eaxLPCur))) { // Override s_eaxLPCur.flAirAbsorptionHF = 0.0f; // Set Environment - s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ALLPARAMETERS, - NULL, &s_eaxLPCur, sizeof(EAXREVERBPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_FXSlot0, EAXREVERB_ALLPARAMETERS, NULL, &s_eaxLPCur, sizeof(EAXREVERBPROPERTIES)); s_EnvironmentID = lID; } @@ -5824,12 +5121,10 @@ void UpdateEAXListener() // Need to find closest s_NumFXSlots (including the Listener's slot) - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION)==EM_OK) - { - if (lID == -1) - { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &ListPos, &lID, EMFLAG_LOCKPOSITION) == EM_OK) { + if (lID == -1) { // Found default environment -// Com_Printf( S_COLOR_YELLOW "Listener in default environment - ignoring zone !\n"); + // Com_Printf( S_COLOR_YELLOW "Listener in default environment - ignoring zone !\n"); return; } @@ -5845,24 +5140,20 @@ void UpdateEAXListener() ReverbData[2].lApertureNum = -1; ReverbData[2].flDist = 0.0f; - for (i = 0; i < s_lNumEnvironments; i++) - { + for (i = 0; i < s_lNumEnvironments; i++) { // Ignore Environment id lID as this one will always be used - if (i != lID) - { + if (i != lID) { flNearest = FLT_MAX; - lApertureNum = 0; //shut up compile warning + lApertureNum = 0; // shut up compile warning - for (j = 0; j < s_lpEnvTable[i].ulNumApertures; j++) - { + for (j = 0; j < s_lpEnvTable[i].ulNumApertures; j++) { EMAperture.fX = s_lpEnvTable[i].Aperture[j].vCenter[0]; EMAperture.fY = s_lpEnvTable[i].Aperture[j].vCenter[1]; EMAperture.fZ = s_lpEnvTable[i].Aperture[j].vCenter[2]; flDistance = CalcDistance(EMAperture, ListPos); - if (flDistance < flNearest) - { + if (flDistance < flNearest) { flNearest = flDistance; lApertureNum = j; } @@ -5870,17 +5161,13 @@ void UpdateEAXListener() // Now have closest point for this Environment - see if this is closer than any others - if (flNearest < ReverbData[1].flDist) - { - if (flNearest < ReverbData[0].flDist) - { + if (flNearest < ReverbData[1].flDist) { + if (flNearest < ReverbData[0].flDist) { ReverbData[1] = ReverbData[0]; ReverbData[0].flDist = flNearest; ReverbData[0].lApertureNum = lApertureNum; ReverbData[0].lEnvID = i; - } - else - { + } else { ReverbData[1].flDist = flNearest; ReverbData[1].lApertureNum = lApertureNum; ReverbData[1].lEnvID = i; @@ -5888,7 +5175,6 @@ void UpdateEAXListener() } } } - } #ifdef DISPLAY_CLOSEST_ENVS @@ -5900,31 +5186,26 @@ void UpdateEAXListener() s_lpEAXManager->GetEnvironmentName(ReverbData[1].lEnvID, szEnvName2, 256); s_lpEAXManager->GetEnvironmentName(ReverbData[2].lEnvID, szEnvName3, 256); - Com_Printf("Closest zones are %s, %s (Listener in %s)\n", szEnvName1, - szEnvName2, szEnvName3); + Com_Printf("Closest zones are %s, %s (Listener in %s)\n", szEnvName1, szEnvName2, szEnvName3); #endif // Mute any reverbs no longer required ... - for (i = 0; i < s_NumFXSlots; i++) - { - if ((s_FXSlotInfo[i].lEnvID != -1) && (s_FXSlotInfo[i].lEnvID != ReverbData[0].lEnvID) && (s_FXSlotInfo[i].lEnvID != ReverbData[1].lEnvID) - && (s_FXSlotInfo[i].lEnvID != ReverbData[2].lEnvID)) - { + for (i = 0; i < s_NumFXSlots; i++) { + if ((s_FXSlotInfo[i].lEnvID != -1) && (s_FXSlotInfo[i].lEnvID != ReverbData[0].lEnvID) && (s_FXSlotInfo[i].lEnvID != ReverbData[1].lEnvID) && + (s_FXSlotInfo[i].lEnvID != ReverbData[2].lEnvID)) { // This environment is no longer needed // Mute it lVolume = -10000; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long)) != AL_NO_ERROR) Com_OPrintf("Failed to Mute FX Slot\n"); // If any source is sending to this Slot ID then we need to stop them sending to the slot - for (j = 1; j < s_numChannels; j++) - { - if (s_channels[j].lSlotID == i) - { - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, s_channels[j].alSource, (void*)&EAX_NULL_GUID, sizeof(GUID))!=AL_NO_ERROR) - { + for (j = 1; j < s_numChannels; j++) { + if (s_channels[j].lSlotID == i) { + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, s_channels[j].alSource, (void *)&EAX_NULL_GUID, sizeof(GUID)) != + AL_NO_ERROR) { Com_OPrintf("Failed to set Source ActiveFXSlotID to NULL\n"); } @@ -5933,44 +5214,35 @@ void UpdateEAXListener() } assert(s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0); - if (s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0) - { + if (s_FXSlotInfo[i].lEnvID < s_lNumEnvironments && s_FXSlotInfo[i].lEnvID >= 0) { s_lpEnvTable[s_FXSlotInfo[i].lEnvID].lFXSlotID = -1; } s_FXSlotInfo[i].lEnvID = -1; } } - // Make sure all the reverbs we want are being rendered, if not, find an empty slot // and apply appropriate reverb settings - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { bFound = false; - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == ReverbData[j].lEnvID) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == ReverbData[j].lEnvID) { bFound = true; break; } } - if (!bFound) - { + if (!bFound) { // Find the first available slot and use that one - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == -1) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == -1) { // Found slot // load reverb here // Retrieve reverb properties from EAX Manager - if (s_lpEAXManager->GetEnvironmentAttributes(ReverbData[j].lEnvID, &Reverb)==EM_OK) - { + if (s_lpEAXManager->GetEnvironmentAttributes(ReverbData[j].lEnvID, &Reverb) == EM_OK) { // Override Air Absorption HF Reverb.flAirAbsorptionHF = 0.0f; @@ -5978,44 +5250,36 @@ void UpdateEAXListener() // See if any Sources are in this environment, if they are, enable their sends ch = s_channels + 1; - for (k = 1; k < s_numChannels; k++, ch++) - { - if (ch->fixed_origin) - { + for (k = 1; k < s_numChannels; k++, ch++) { + if (ch->fixed_origin) { // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z EMSourcePoint.fX = ch->origin[0]; EMSourcePoint.fY = ch->origin[2]; EMSourcePoint.fZ = ch->origin[1]; - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { // Source at same position as listener // Probably won't be any Occlusion / Obstruction effect -- unless the listener is underwater // Converting from Open AL -> DS3D (for EAGLE) ... invert Z EMSourcePoint.fX = listener_pos[0]; EMSourcePoint.fY = listener_pos[1]; EMSourcePoint.fZ = -listener_pos[2]; - } - else - { + } else { // Get position of Entity // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z - EMSourcePoint.fX = loopSounds[ ch->entnum ].origin[0]; - EMSourcePoint.fY = loopSounds[ ch->entnum ].origin[2]; - EMSourcePoint.fZ = loopSounds[ ch->entnum ].origin[1]; + EMSourcePoint.fX = loopSounds[ch->entnum].origin[0]; + EMSourcePoint.fY = loopSounds[ch->entnum].origin[2]; + EMSourcePoint.fZ = loopSounds[ch->entnum].origin[1]; } } // Get Source Environment point - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0)!=EM_OK) + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0) != EM_OK) Com_OPrintf("Failed to get environment zone for Source\n"); - if (lSourceID == i) - { - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, (void*)&(s_FXSlotInfo[i].FXSlotGuid), sizeof(GUID))!=AL_NO_ERROR) - { + if (lSourceID == i) { + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, (void *)&(s_FXSlotInfo[i].FXSlotGuid), + sizeof(GUID)) != AL_NO_ERROR) { Com_OPrintf("Failed to set Source ActiveFXSlotID to new environment\n"); } @@ -6024,8 +5288,7 @@ void UpdateEAXListener() } assert(ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0); - if (ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0) - { + if (ReverbData[j].lEnvID < s_lNumEnvironments && ReverbData[j].lEnvID >= 0) { s_FXSlotInfo[i].lEnvID = ReverbData[j].lEnvID; s_lpEnvTable[ReverbData[j].lEnvID].lFXSlotID = i; } @@ -6037,15 +5300,14 @@ void UpdateEAXListener() } // Make sure Primary FX Slot ID is set correctly - if (s_EnvironmentID != ReverbData[2].lEnvID) - { - s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, &(s_FXSlotInfo[s_lpEnvTable[ReverbData[2].lEnvID].lFXSlotID].FXSlotGuid), sizeof(GUID)); + if (s_EnvironmentID != ReverbData[2].lEnvID) { + s_eaxSet(&EAXPROPERTYID_EAX40_Context, EAXCONTEXT_PRIMARYFXSLOTID, NULL, &(s_FXSlotInfo[s_lpEnvTable[ReverbData[2].lEnvID].lFXSlotID].FXSlotGuid), + sizeof(GUID)); s_EnvironmentID = ReverbData[2].lEnvID; } // Have right reverbs loaded ... now to pan them and adjust volume - // We need to rotate the vector from the Listener to the reverb Aperture by minus the listener // orientation @@ -6063,27 +5325,23 @@ void UpdateEAXListener() float flSin = (float)sin(-flTheta); float flCos = (float)cos(-flTheta); - for (i = 0; i < Q_min(s_NumFXSlots,s_lNumEnvironments); i++) - { - if (s_FXSlotInfo[i].lEnvID == s_EnvironmentID) - { + for (i = 0; i < Q_min(s_NumFXSlots, s_lNumEnvironments); i++) { + if (s_FXSlotInfo[i].lEnvID == s_EnvironmentID) { // Listener's environment // Find the closest Aperture in *this* environment flNearest = FLT_MAX; - lApertureNum = 0; //shut up compile warning + lApertureNum = 0; // shut up compile warning - for (j = 0; j < s_lpEnvTable[s_EnvironmentID].ulNumApertures; j++) - { + for (j = 0; j < s_lpEnvTable[s_EnvironmentID].ulNumApertures; j++) { EMAperture.fX = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[0]; EMAperture.fY = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[1]; EMAperture.fZ = s_lpEnvTable[s_EnvironmentID].Aperture[j].vCenter[2]; flDistance = CalcDistance(EMAperture, ListPos); - if (flDistance < flNearest) - { + if (flDistance < flNearest) { flNearest = flDistance; lApertureNum = j; } @@ -6101,14 +5359,12 @@ void UpdateEAXListener() Normalize(&Pan); - // Adjust magnitude ... // Magnitude is based on the angle subtended by the aperture, so compute the angle between // the vector from the Listener to Pos1 of the aperture, and the vector from the // Listener to Pos2 of the aperture. - LP1.x = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[0] - ListPos.fX; LP1.y = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[1] - ListPos.fY; LP1.z = s_lpEnvTable[s_EnvironmentID].Aperture[lApertureNum].vPos1[2] - ListPos.fZ; @@ -6123,21 +5379,19 @@ void UpdateEAXListener() float flGamma = acos((LP1.x * LP2.x) + (LP1.y * LP2.y) + (LP1.z * LP2.z)); // We want opposite magnitude (because we are 'in' this environment) - float flMagnitude = 1.0f - ((2.0f * (float)sin(flGamma/2.0f)) / flGamma); + float flMagnitude = 1.0f - ((2.0f * (float)sin(flGamma / 2.0f)) / flGamma); // Negative (because pan should be 180 degrees) Pan.x *= -flMagnitude; Pan.y *= -flMagnitude; Pan.z *= -flMagnitude; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) Com_OPrintf("Failed to set Listener Reverb Pan\n"); - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) Com_OPrintf("Failed to set Listener Reflections Pan\n"); - } - else - { + } else { // Find out which Reverb this is if (ReverbData[0].lEnvID == s_FXSlotInfo[i].lEnvID) k = 0; @@ -6162,7 +5416,6 @@ void UpdateEAXListener() // the vector from the Listener to Pos1 of the aperture, and the vector from the // Listener to Pos2 of the aperture. - LP1.x = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[0] - ListPos.fX; LP1.y = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[1] - ListPos.fY; LP1.z = s_lpEnvTable[ReverbData[k].lEnvID].Aperture[ReverbData[k].lApertureNum].vPos1[2] - ListPos.fZ; @@ -6175,24 +5428,23 @@ void UpdateEAXListener() Normalize(&LP2); float flGamma = acos((LP1.x * LP2.x) + (LP1.y * LP2.y) + (LP1.z * LP2.z)); - float flMagnitude = (2.0f * (float)sin(flGamma/2.0f)) / flGamma; + float flMagnitude = (2.0f * (float)sin(flGamma / 2.0f)) / flGamma; Pan.x *= flMagnitude; Pan.y *= flMagnitude; Pan.z *= flMagnitude; - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REVERBPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) Com_OPrintf("Failed to set Reverb Pan\n"); - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR))!=AL_NO_ERROR) + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXREVERB_REFLECTIONSPAN, NULL, &Pan, sizeof(EAXVECTOR)) != AL_NO_ERROR) Com_OPrintf("Failed to set Reflections Pan\n"); } } lVolume = 0; - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long))!=AL_NO_ERROR) + for (i = 0; i < s_NumFXSlots; i++) { + if (s_eaxSet(&s_FXSlotInfo[i].FXSlotGuid, EAXFXSLOT_VOLUME, NULL, &lVolume, sizeof(long)) != AL_NO_ERROR) Com_OPrintf("Failed to set FX Slot Volume to 0\n"); } } @@ -6203,8 +5455,7 @@ void UpdateEAXListener() /* Updates the EAX Buffer related effects on the given Source */ -void UpdateEAXBuffer(channel_t *ch) -{ +void UpdateEAXBuffer(channel_t *ch) { HRESULT hr; EMPOINT EMSourcePoint; EMPOINT EMVirtualSourcePoint; @@ -6223,36 +5474,27 @@ void UpdateEAXBuffer(channel_t *ch) eaxOCProp.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO; // Convert Source co-ordinate to left-handed system - if (ch->fixed_origin) - { + if (ch->fixed_origin) { // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z EMSourcePoint.fX = ch->origin[0]; EMSourcePoint.fY = ch->origin[2]; EMSourcePoint.fZ = ch->origin[1]; - } - else - { - if (ch->entnum == listener_number) - { + } else { + if (ch->entnum == listener_number) { // Source at same position as listener // Probably won't be any Occlusion / Obstruction effect -- unless the listener is underwater // Converting from Open AL -> DS3D (for EAGLE) ... invert Z EMSourcePoint.fX = listener_pos[0]; EMSourcePoint.fY = listener_pos[1]; EMSourcePoint.fZ = -listener_pos[2]; - } - else - { + } else { // Get position of Entity // Converting from Quake -> DS3D (for EAGLE) ... swap Y and Z - if (ch->bLooping) - { - EMSourcePoint.fX = loopSounds[ ch->entnum ].origin[0]; - EMSourcePoint.fY = loopSounds[ ch->entnum ].origin[2]; - EMSourcePoint.fZ = loopSounds[ ch->entnum ].origin[1]; - } - else - { + if (ch->bLooping) { + EMSourcePoint.fX = loopSounds[ch->entnum].origin[0]; + EMSourcePoint.fY = loopSounds[ch->entnum].origin[2]; + EMSourcePoint.fZ = loopSounds[ch->entnum].origin[1]; + } else { EMSourcePoint.fX = s_entityPosition[ch->entnum][0]; EMSourcePoint.fY = s_entityPosition[ch->entnum][2]; EMSourcePoint.fZ = s_entityPosition[ch->entnum][1]; @@ -6263,18 +5505,14 @@ void UpdateEAXBuffer(channel_t *ch) long lExclusion; // Just determine what environment the source is in - if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0)==EM_OK) - { + if (s_lpEAXManager->GetListenerDynamicAttributes(0, &EMSourcePoint, &lSourceID, 0) == EM_OK) { // See if a Slot is rendering this environment - for (i = 0; i < s_NumFXSlots; i++) - { - if (s_FXSlotInfo[i].lEnvID == lSourceID) - { + for (i = 0; i < s_NumFXSlots; i++) { + if (s_FXSlotInfo[i].lEnvID == lSourceID) { // If the Source is not sending to this slot, then enable the send now - if (ch->lSlotID != i) - { + if (ch->lSlotID != i) { // Set this - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &s_FXSlotInfo[i].FXSlotGuid, sizeof(GUID))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_ACTIVEFXSLOTID, ch->alSource, &s_FXSlotInfo[i].FXSlotGuid, sizeof(GUID)) != AL_NO_ERROR) Com_OPrintf("UpdateEAXBuffer = failed to set ActiveFXSlotID\n"); ch->lSlotID = i; @@ -6283,28 +5521,22 @@ void UpdateEAXBuffer(channel_t *ch) break; } } - } - else - { + } else { Com_OPrintf("UpdateEAXBuffer::Failed to get Source environment zone\n"); } // Add some Exclusion to sounds that are not located in the Listener's environment - if (s_FXSlotInfo[ch->lSlotID].lEnvID == s_EnvironmentID) - { + if (s_FXSlotInfo[ch->lSlotID].lEnvID == s_EnvironmentID) { lExclusion = 0; - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long)) != AL_NO_ERROR) Com_OPrintf("UpdateEAXBuffer : Failed to set exclusion to 0\n"); - } - else - { + } else { lExclusion = -1000; - if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long))!=AL_NO_ERROR) + if (s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_EXCLUSION, ch->alSource, &lExclusion, sizeof(long)) != AL_NO_ERROR) Com_OPrintf("UpdateEAXBuffer : Failed to set exclusion to -1000\n"); } - if ((ch->entchannel == CHAN_VOICE) || (ch->entchannel == CHAN_VOICE_ATTEN) || (ch->entchannel == CHAN_VOICE_GLOBAL)) - { + if ((ch->entchannel == CHAN_VOICE) || (ch->entchannel == CHAN_VOICE_ATTEN) || (ch->entchannel == CHAN_VOICE_GLOBAL)) { // Remove any Occlusion + Obstruction eaxOBProp.lObstruction = EAXSOURCE_DEFAULTOBSTRUCTION; eaxOBProp.flObstructionLFRatio = EAXSOURCE_DEFAULTOBSTRUCTIONLFRATIO; @@ -6314,33 +5546,23 @@ void UpdateEAXBuffer(channel_t *ch) eaxOCProp.flOcclusionRoomRatio = EAXSOURCE_DEFAULTOCCLUSIONROOMRATIO; eaxOCProp.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO; - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, - ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); - } - else - { + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + } else { // Check for Occlusion + Obstruction - hr = s_lpEAXManager->GetSourceDynamicAttributes(0, &EMSourcePoint, &eaxOBProp.lObstruction, &eaxOBProp.flObstructionLFRatio, - &eaxOCProp.lOcclusion, &eaxOCProp.flOcclusionLFRatio, &eaxOCProp.flOcclusionRoomRatio, &EMVirtualSourcePoint, 0); - if (hr == EM_OK) - { + hr = s_lpEAXManager->GetSourceDynamicAttributes(0, &EMSourcePoint, &eaxOBProp.lObstruction, &eaxOBProp.flObstructionLFRatio, &eaxOCProp.lOcclusion, + &eaxOCProp.flOcclusionLFRatio, &eaxOCProp.flOcclusionRoomRatio, &EMVirtualSourcePoint, 0); + if (hr == EM_OK) { // Set EAX effect ! - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, - ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OBSTRUCTIONPARAMETERS, ch->alSource, &eaxOBProp, sizeof(EAXOBSTRUCTIONPROPERTIES)); - s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, - ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); + s_eaxSet(&EAXPROPERTYID_EAX40_Source, EAXSOURCE_OCCLUSIONPARAMETERS, ch->alSource, &eaxOCProp, sizeof(EAXOCCLUSIONPROPERTIES)); } } return; } -float CalcDistance(EMPOINT A, EMPOINT B) -{ - return (float)sqrt(sqr(A.fX - B.fX)+sqr(A.fY - B.fY) + sqr(A.fZ - B.fZ)); -} +float CalcDistance(EMPOINT A, EMPOINT B) { return (float)sqrt(sqr(A.fX - B.fX) + sqr(A.fY - B.fY) + sqr(A.fZ - B.fZ)); } #endif diff --git a/codemp/client/snd_mem.cpp b/codemp/client/snd_mem.cpp index 8270fc91d6..65d12f014c 100644 --- a/codemp/client/snd_mem.cpp +++ b/codemp/client/snd_mem.cpp @@ -42,84 +42,74 @@ WAV loading =============================================================================== */ -byte *data_p; -byte *iff_end; -byte *last_chunk; -byte *iff_data; -int iff_chunk_len; -extern sfx_t s_knownSfx[]; -extern int s_numSfx; - -extern cvar_t *s_lip_threshold_1; -extern cvar_t *s_lip_threshold_2; -extern cvar_t *s_lip_threshold_3; -extern cvar_t *s_lip_threshold_4; - -short GetLittleShort(void) -{ +byte *data_p; +byte *iff_end; +byte *last_chunk; +byte *iff_data; +int iff_chunk_len; +extern sfx_t s_knownSfx[]; +extern int s_numSfx; + +extern cvar_t *s_lip_threshold_1; +extern cvar_t *s_lip_threshold_2; +extern cvar_t *s_lip_threshold_3; +extern cvar_t *s_lip_threshold_4; + +short GetLittleShort(void) { short val = 0; val = *data_p; - val = (short)(val + (*(data_p+1)<<8)); + val = (short)(val + (*(data_p + 1) << 8)); data_p += 2; return val; } -int GetLittleLong(void) -{ +int GetLittleLong(void) { int val = 0; val = *data_p; - val = val + (*(data_p+1)<<8); - val = val + (*(data_p+2)<<16); - val = val + (*(data_p+3)<<24); + val = val + (*(data_p + 1) << 8); + val = val + (*(data_p + 2) << 16); + val = val + (*(data_p + 3) << 24); data_p += 4; return val; } -void FindNextChunk(char *name) -{ - while (1) - { - data_p=last_chunk; +void FindNextChunk(char *name) { + while (1) { + data_p = last_chunk; - if (data_p >= iff_end) - { // didn't find the chunk + if (data_p >= iff_end) { // didn't find the chunk data_p = NULL; return; } data_p += 4; iff_chunk_len = GetLittleLong(); - if (iff_chunk_len < 0) - { + if (iff_chunk_len < 0) { data_p = NULL; return; } data_p -= 8; - last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 ); + last_chunk = data_p + 8 + ((iff_chunk_len + 1) & ~1); if (!Q_strncmp((char *)data_p, name, 4)) return; } } -void FindChunk(char *name) -{ +void FindChunk(char *name) { last_chunk = iff_data; - FindNextChunk (name); + FindNextChunk(name); } - -void DumpChunks(void) -{ - char str[5]; +void DumpChunks(void) { + char str[5]; str[4] = 0; - data_p=iff_data; - do - { - memcpy (str, data_p, 4); + data_p = iff_data; + do { + memcpy(str, data_p, 4); data_p += 4; iff_chunk_len = GetLittleLong(); - Com_Printf ("0x%x : %s (%d)\n", (intptr_t)(data_p - 4), str, iff_chunk_len); + Com_Printf("0x%x : %s (%d)\n", (intptr_t)(data_p - 4), str, iff_chunk_len); data_p += (iff_chunk_len + 1) & ~1; } while (data_p < iff_end); } @@ -129,12 +119,11 @@ void DumpChunks(void) GetWavinfo ============ */ -wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) -{ - wavinfo_t info; - int samples; +wavinfo_t GetWavinfo(const char *name, byte *wav, int wavlength) { + wavinfo_t info; + int samples; - memset (&info, 0, sizeof(info)); + memset(&info, 0, sizeof(info)); if (!wav) return info; @@ -142,21 +131,19 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) iff_data = wav; iff_end = wav + wavlength; -// find "RIFF" chunk + // find "RIFF" chunk FindChunk("RIFF"); - if (!(data_p && !Q_strncmp((char *)data_p+8, "WAVE", 4))) - { + if (!(data_p && !Q_strncmp((char *)data_p + 8, "WAVE", 4))) { Com_Printf("Missing RIFF/WAVE chunks\n"); return info; } -// get "fmt " chunk + // get "fmt " chunk iff_data = data_p + 12; -// DumpChunks (); + // DumpChunks (); FindChunk("fmt "); - if (!data_p) - { + if (!data_p) { Com_Printf("Missing fmt chunk\n"); return info; } @@ -164,42 +151,35 @@ wavinfo_t GetWavinfo (const char *name, byte *wav, int wavlength) info.format = GetLittleShort(); info.channels = GetLittleShort(); info.rate = GetLittleLong(); - data_p += 4+2; + data_p += 4 + 2; info.width = GetLittleShort() / 8; - if (info.format != 1) - { + if (info.format != 1) { Com_Printf("Microsoft PCM format only\n"); return info; } - -// find data chunk + // find data chunk FindChunk("data"); - if (!data_p) - { + if (!data_p) { Com_Printf("Missing data chunk\n"); return info; } data_p += 4; - samples = GetLittleLong () / info.width; + samples = GetLittleLong() / info.width; - if (info.samples) - { + if (info.samples) { if (samples < info.samples) - Com_Error (ERR_DROP, "Sound %s has a bad loop length", name); - } - else + Com_Error(ERR_DROP, "Sound %s has a bad loop length", name); + } else info.samples = samples; info.dataofs = data_p - wav; - return info; } - /* ================ ResampleSfx @@ -207,36 +187,34 @@ ResampleSfx resample / decimate to the current source rate ================ */ -void ResampleSfx (sfx_t *sfx, int iInRate, int iInWidth, byte *pData) -{ - int iOutCount; - int iSrcSample; - float fStepScale; - int i; - int iSample; - unsigned int uiSampleFrac, uiFracStep; // uiSampleFrac MUST be unsigned, or large samples (eg music tracks) crash +void ResampleSfx(sfx_t *sfx, int iInRate, int iInWidth, byte *pData) { + int iOutCount; + int iSrcSample; + float fStepScale; + int i; + int iSample; + unsigned int uiSampleFrac, uiFracStep; // uiSampleFrac MUST be unsigned, or large samples (eg music tracks) crash - fStepScale = (float)iInRate / dma.speed; // this is usually 0.5, 1, or 2 + fStepScale = (float)iInRate / dma.speed; // this is usually 0.5, 1, or 2 // When stepscale is > 1 (we're downsampling), we really ought to run a low pass filter on the samples iOutCount = (int)(sfx->iSoundLengthInSamples / fStepScale); sfx->iSoundLengthInSamples = iOutCount; - sfx->pSoundData = (short *) SND_malloc( sfx->iSoundLengthInSamples*2 ,sfx ); + sfx->pSoundData = (short *)SND_malloc(sfx->iSoundLengthInSamples * 2, sfx); - sfx->fVolRange = 0; - uiSampleFrac = 0; - uiFracStep = (int)(fStepScale*256); + sfx->fVolRange = 0; + uiSampleFrac = 0; + uiFracStep = (int)(fStepScale * 256); - for (i=0 ; iiSoundLengthInSamples ; i++) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i++) { iSrcSample = uiSampleFrac >> 8; uiSampleFrac += uiFracStep; if (iInWidth == 2) { - iSample = LittleShort ( ((short *)pData)[iSrcSample] ); + iSample = LittleShort(((short *)pData)[iSrcSample]); } else { - iSample = (unsigned int)( (unsigned char)(pData[iSrcSample]) - 128) << 8; + iSample = (unsigned int)((unsigned char)(pData[iSrcSample]) - 128) << 8; } sfx->pSoundData[i] = (short)iSample; @@ -245,71 +223,57 @@ void ResampleSfx (sfx_t *sfx, int iInRate, int iInWidth, byte *pData) // if (iSample < 0) iSample = -iSample; - if (sfx->fVolRange < (iSample >> 8) ) - { - sfx->fVolRange = iSample >> 8; + if (sfx->fVolRange < (iSample >> 8)) { + sfx->fVolRange = iSample >> 8; } } } - //============================================================================= +void S_LoadSound_Finalize(wavinfo_t *info, sfx_t *sfx, byte *data) { + // float stepscale = (float)info->rate / dma.speed; + // int len = (int)(info->samples / stepscale); -void S_LoadSound_Finalize(wavinfo_t *info, sfx_t *sfx, byte *data) -{ - //float stepscale = (float)info->rate / dma.speed; - //int len = (int)(info->samples / stepscale); - - //len *= info->width; + // len *= info->width; sfx->eSoundCompressionMethod = ct_16; - sfx->iSoundLengthInSamples = info->samples; - ResampleSfx( sfx, info->rate, info->width, data + info->dataofs ); + sfx->iSoundLengthInSamples = info->samples; + ResampleSfx(sfx, info->rate, info->width, data + info->dataofs); } - - - - // maybe I'm re-inventing the wheel, here, but I can't see any functions that already do this, so... // -char *Filename_WithoutPath(const char *psFilename) -{ - static char sString[MAX_QPATH]; // !! - const char *p = strrchr(psFilename,'\\'); +char *Filename_WithoutPath(const char *psFilename) { + static char sString[MAX_QPATH]; // !! + const char *p = strrchr(psFilename, '\\'); - if (!p++) - p=psFilename; + if (!p++) + p = psFilename; - strcpy(sString,p); + strcpy(sString, p); return sString; - } // returns (eg) "\dir\name" for "\dir\name.bmp" // -char *Filename_WithoutExt(const char *psFilename) -{ - static char sString[MAX_QPATH]; // ! +char *Filename_WithoutExt(const char *psFilename) { + static char sString[MAX_QPATH]; // ! - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p = strrchr(sString,'.'); - char *p2= strrchr(sString,'\\'); + char *p = strrchr(sString, '.'); + char *p2 = strrchr(sString, '\\'); // special check, make sure the first suffix we found from the end wasn't just a directory suffix (eg on a path'd filename with no extension anyway) // - if (p && (p2==0 || (p2 && p>p2))) - *p=0; + if (p && (p2 == 0 || (p2 && p > p2))) + *p = 0; return sString; - } - - int iFilesFound; int iFilesUpdated; int iErrors; @@ -317,50 +281,44 @@ qboolean qbForceRescan; qboolean qbForceStereo; std::string strErrors; -void R_CheckMP3s( const char *psDir ) -{ -// Com_Printf(va("Scanning Dir: %s\n",psDir)); - Com_Printf("."); // stops useful info scrolling off screen +void R_CheckMP3s(const char *psDir) { + // Com_Printf(va("Scanning Dir: %s\n",psDir)); + Com_Printf("."); // stops useful info scrolling off screen - char **sysFiles, **dirFiles; - int numSysFiles, i, numdirs; + char **sysFiles, **dirFiles; + int numSysFiles, i, numdirs; - dirFiles = FS_ListFiles( psDir, "/", &numdirs); - if (numdirs > 2) - { - for (i=2;i 2) { + for (i = 2; i < numdirs; i++) { + char sDirName[MAX_QPATH]; sprintf(sDirName, "%s\\%s", psDir, dirFiles[i]); R_CheckMP3s(sDirName); } } - sysFiles = FS_ListFiles( psDir, ".mp3", &numSysFiles ); - for(i=0; ifVolRange; // free sfx->data... // { - #ifndef INT_MIN - #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ - #endif +#ifndef INT_MIN +#define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ +#endif // - pSFX->iLastTimeUsed = INT_MIN; // force this to be oldest sound file, therefore disposable... + pSFX->iLastTimeUsed = INT_MIN; // force this to be oldest sound file, therefore disposable... pSFX->bInMemory = qtrue; - SND_FreeOldestSound(); // ... and do the disposal + SND_FreeOldestSound(); // ... and do the disposal // now set our temp SFX struct back to default name so nothing else accidentally uses it... // @@ -429,7 +385,7 @@ void R_CheckMP3s( const char *psDir ) pSFX->bDefaultSound = qfalse; } -// Com_OPrintf("File: \"%s\" MaxVol %f\n",sFilename,pSFX->fVolRange); + // Com_OPrintf("File: \"%s\" MaxVol %f\n",sFilename,pSFX->fVolRange); // other stuff... // @@ -438,90 +394,74 @@ void R_CheckMP3s( const char *psDir ) // well, time to update the file now... // - fileHandle_t f = FS_FOpenFileWrite( sFilename ); - if (f) - { + fileHandle_t f = FS_FOpenFileWrite(sFilename); + if (f) { // write the file back out, but omitting the tag if there was one... // - int iWritten = FS_Write(pbData, iSize-(pTAG?sizeof(*pTAG):0), f); + int iWritten = FS_Write(pbData, iSize - (pTAG ? sizeof(*pTAG) : 0), f); - if (iWritten) - { + if (iWritten) { // make up a new tag if we didn't find one in the original file... // id3v1_1 TAG; - if (!pTAG) - { + if (!pTAG) { pTAG = &TAG; - memset(&TAG,0,sizeof(TAG)); - strncpy(pTAG->id,"TAG",3); + memset(&TAG, 0, sizeof(TAG)); + strncpy(pTAG->id, "TAG", 3); } - strncpy(pTAG->title, Filename_WithoutPath(Filename_WithoutExt(sFilename)), sizeof(pTAG->title)); - strncpy(pTAG->artist, "Raven Software", sizeof(pTAG->artist) ); - strncpy(pTAG->year, "2002", sizeof(pTAG->year) ); - strncpy(pTAG->comment, va("%s %g",sKEY_MAXVOL,fMaxVol), sizeof(pTAG->comment) ); - strncpy(pTAG->album, va("%s %d",sKEY_UNCOMP,iActualUnpackedSize),sizeof(pTAG->album) ); + strncpy(pTAG->title, Filename_WithoutPath(Filename_WithoutExt(sFilename)), sizeof(pTAG->title)); + strncpy(pTAG->artist, "Raven Software", sizeof(pTAG->artist)); + strncpy(pTAG->year, "2002", sizeof(pTAG->year)); + strncpy(pTAG->comment, va("%s %g", sKEY_MAXVOL, fMaxVol), sizeof(pTAG->comment)); + strncpy(pTAG->album, va("%s %d", sKEY_UNCOMP, iActualUnpackedSize), sizeof(pTAG->album)); - if (FS_Write( pTAG, sizeof(*pTAG), f )) // NZ = success + if (FS_Write(pTAG, sizeof(*pTAG), f)) // NZ = success { iFilesUpdated++; - } - else - { - Com_Printf("*********** Failed write to file \"%s\"!\n",sFilename); + } else { + Com_Printf("*********** Failed write to file \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to write: \"%s\"\n",sFilename); + strErrors += va("Failed to write: \"%s\"\n", sFilename); } - } - else - { - Com_Printf("*********** Failed write to file \"%s\"!\n",sFilename); + } else { + Com_Printf("*********** Failed write to file \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to write: \"%s\"\n",sFilename); + strErrors += va("Failed to write: \"%s\"\n", sFilename); } - FS_FCloseFile( f ); - } - else - { - Com_Printf("*********** Failed to re-open for write \"%s\"!\n",sFilename); + FS_FCloseFile(f); + } else { + Com_Printf("*********** Failed to re-open for write \"%s\"!\n", sFilename); iErrors++; - strErrors += va("Failed to re-open for write: \"%s\"\n",sFilename); + strErrors += va("Failed to re-open for write: \"%s\"\n", sFilename); } + } else { + Com_Error(ERR_DROP, "******* This MP3 should be deleted: \"%s\"\n", sFilename); } - else - { - Com_Error(ERR_DROP, "******* This MP3 should be deleted: \"%s\"\n",sFilename); - } - } - else - { - Com_Printf("*********** File was not a valid MP3!: \"%s\"\n",sFilename); + } else { + Com_Printf("*********** File was not a valid MP3!: \"%s\"\n", sFilename); iErrors++; - strErrors += va("Not game-legal MP3 format: \"%s\"\n",sFilename); + strErrors += va("Not game-legal MP3 format: \"%s\"\n", sFilename); } - } - else - { + } else { Com_Printf(" ( OK )\n"); } - FS_FreeFile( pbData ); + FS_FreeFile(pbData); } } - FS_FreeFileList( sysFiles ); - FS_FreeFileList( dirFiles ); + FS_FreeFileList(sysFiles); + FS_FreeFileList(dirFiles); } // this console-function is for development purposes, and makes sure that sound/*.mp3 /s have tags in them // specifying stuff like their max volume (and uncompressed size) etc... // -void S_MP3_CalcVols_f( void ) -{ +void S_MP3_CalcVols_f(void) { char sStartDir[MAX_QPATH] = {"sound"}; const char sUsage[] = "Usage: mp3_calcvols [-rescan] \ne.g. mp3_calcvols sound/chars"; - if (Cmd_Argc() == 1 || Cmd_Argc()>4) // 3 optional arguments + if (Cmd_Argc() == 1 || Cmd_Argc() > 4) // 3 optional arguments { Com_Printf(sUsage); return; @@ -529,29 +469,20 @@ void S_MP3_CalcVols_f( void ) S_StopAllSounds(); - qbForceRescan = qfalse; qbForceStereo = qfalse; - iFilesFound = 0; - iFilesUpdated = 0; - iErrors = 0; - strErrors = ""; - - for (int i=1; iinteger) - { + if (com_buildScript->integer) { fileHandle_t hFile; - //German - strncpy(psVoice,"chr_d",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + // German + strncpy(psVoice, "chr_d", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav - - //French - strncpy(psVoice,"chr_f",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav + + // French + strncpy(psVoice, "chr_f", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav - - //Spanish - strncpy(psVoice,"chr_e",5); // same number of letters as "chars" - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the wav - if (!hFile) - { - strcpy(&psFilename[iNameStrlen-3],"mp3"); //not there try mp3 - FS_FOpenFileRead(psFilename, &hFile, qfalse); //cache the mp3 + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav + + // Spanish + strncpy(psVoice, "chr_e", 5); // same number of letters as "chars" + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the wav + if (!hFile) { + strcpy(&psFilename[iNameStrlen - 3], "mp3"); // not there try mp3 + FS_FOpenFileRead(psFilename, &hFile, qfalse); // cache the mp3 } - if (hFile) - { + if (hFile) { FS_FCloseFile(hFile); } - strcpy(&psFilename[iNameStrlen-3],"wav"); //put it back to wav + strcpy(&psFilename[iNameStrlen - 3], "wav"); // put it back to wav - strncpy(psVoice,"chars",5); //put it back to chars + strncpy(psVoice, "chars", 5); // put it back to chars } // account for foreign voices... // - extern cvar_t* s_language; - if ( s_language ) { - if ( !Q_stricmp( "DEUTSCH", s_language->string ) ) - strncpy( psVoice, "chr_d", 5 ); // same number of letters as "chars" - else if ( !Q_stricmp( "FRANCAIS", s_language->string ) ) - strncpy( psVoice, "chr_f", 5 ); // same number of letters as "chars" - else if ( !Q_stricmp( "ESPANOL", s_language->string ) ) - strncpy( psVoice, "chr_e", 5 ); // same number of letters as "chars" + extern cvar_t *s_language; + if (s_language) { + if (!Q_stricmp("DEUTSCH", s_language->string)) + strncpy(psVoice, "chr_d", 5); // same number of letters as "chars" + else if (!Q_stricmp("FRANCAIS", s_language->string)) + strncpy(psVoice, "chr_f", 5); // same number of letters as "chars" + else if (!Q_stricmp("ESPANOL", s_language->string)) + strncpy(psVoice, "chr_e", 5); // same number of letters as "chars" else psVoice = NULL; - } - else - { - psVoice = NULL; // use this ptr as a flag as to whether or not we substituted with a foreign version + } else { + psVoice = NULL; // use this ptr as a flag as to whether or not we substituted with a foreign version } } - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try WAV - if ( !*pData ) { - psFilename[iNameStrlen-3] = 'm'; - psFilename[iNameStrlen-2] = 'p'; - psFilename[iNameStrlen-1] = '3'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try MP3 + *piSize = FS_ReadFile(psFilename, (void **)pData); // try WAV + if (!*pData) { + psFilename[iNameStrlen - 3] = 'm'; + psFilename[iNameStrlen - 2] = 'p'; + psFilename[iNameStrlen - 1] = '3'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try MP3 - if ( !*pData ) - { - //hmmm, not found, ok, maybe we were trying a foreign noise ("arghhhhh.mp3" that doesn't matter?) but it - // was missing? Can't tell really, since both types are now in sound/chars. Oh well, fall back to English for now... + if (!*pData) { + // hmmm, not found, ok, maybe we were trying a foreign noise ("arghhhhh.mp3" that doesn't matter?) but it + // was missing? Can't tell really, since both types are now in sound/chars. Oh well, fall back to English for now... - if (psVoice) // were we trying to load foreign? + if (psVoice) // were we trying to load foreign? { // yep, so fallback to re-try the english... // #ifndef FINAL_BUILD - Com_Printf(S_COLOR_YELLOW "Foreign file missing: \"%s\"! (using English...)\n",psFilename); + Com_Printf(S_COLOR_YELLOW "Foreign file missing: \"%s\"! (using English...)\n", psFilename); #endif - strncpy(psVoice,"chars",5); - - psFilename[iNameStrlen-3] = 'w'; - psFilename[iNameStrlen-2] = 'a'; - psFilename[iNameStrlen-1] = 'v'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try English WAV - if ( !*pData ) - { - psFilename[iNameStrlen-3] = 'm'; - psFilename[iNameStrlen-2] = 'p'; - psFilename[iNameStrlen-1] = '3'; - *piSize = FS_ReadFile( psFilename, (void **)pData ); // try English MP3 + strncpy(psVoice, "chars", 5); + + psFilename[iNameStrlen - 3] = 'w'; + psFilename[iNameStrlen - 2] = 'a'; + psFilename[iNameStrlen - 1] = 'v'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try English WAV + if (!*pData) { + psFilename[iNameStrlen - 3] = 'm'; + psFilename[iNameStrlen - 2] = 'p'; + psFilename[iNameStrlen - 1] = '3'; + *piSize = FS_ReadFile(psFilename, (void **)pData); // try English MP3 } } - if (!*pData) - { - return qfalse; // sod it, give up... + if (!*pData) { + return qfalse; // sod it, give up... } } } @@ -712,10 +624,9 @@ static qboolean S_LoadSound_FileLoadAndNameAdjuster(char *psFilename, byte **pDa // #define SOUND_CHARS_DIR "sound/chars/" #define SOUND_CHARS_DIR_LENGTH 12 // strlen( SOUND_CHARS_DIR ) -static qboolean S_LoadSound_DirIsAllowedToKeepMP3s(const char *psFilename) -{ - if ( Q_stricmpn( psFilename, SOUND_CHARS_DIR, SOUND_CHARS_DIR_LENGTH ) == 0 ) - return qtrue; // found a dir that's allowed to keep MP3s +static qboolean S_LoadSound_DirIsAllowedToKeepMP3s(const char *psFilename) { + if (Q_stricmpn(psFilename, SOUND_CHARS_DIR, SOUND_CHARS_DIR_LENGTH) == 0) + return qtrue; // found a dir that's allowed to keep MP3s return qfalse; } @@ -729,68 +640,58 @@ of a forced fallback of a player specific sound (or of a wav/mp3 substitution no ============== */ qboolean gbInsideLoadSound = qfalse; -static qboolean S_LoadSound_Actual( sfx_t *sfx ) -{ - byte *data; - short *samples; - wavinfo_t info; - int size; - char *psExt; - char sLoadName[MAX_QPATH]; - - int len = strlen(sfx->sSoundName); - if (len<5) - { +static qboolean S_LoadSound_Actual(sfx_t *sfx) { + byte *data; + short *samples; + wavinfo_t info; + int size; + char *psExt; + char sLoadName[MAX_QPATH]; + + int len = strlen(sfx->sSoundName); + if (len < 5) { return qfalse; } // player specific sounds are never directly loaded... // - if ( sfx->sSoundName[0] == '*') { + if (sfx->sSoundName[0] == '*') { return qfalse; } // make up a local filename to try wav/mp3 substitutes... // Q_strncpyz(sLoadName, sfx->sSoundName, sizeof(sLoadName)); - Q_strlwr( sLoadName ); + Q_strlwr(sLoadName); // // Ensure name has an extension (which it must have, but you never know), and get ptr to it... // - psExt = &sLoadName[strlen(sLoadName)-4]; - if (*psExt != '.') - { - //Com_Printf( "WARNING: soundname '%s' does not have 3-letter extension\n",sLoadName); - COM_DefaultExtension(sLoadName,sizeof(sLoadName),".wav"); // so psExt below is always valid - psExt = &sLoadName[strlen(sLoadName)-4]; + psExt = &sLoadName[strlen(sLoadName) - 4]; + if (*psExt != '.') { + // Com_Printf( "WARNING: soundname '%s' does not have 3-letter extension\n",sLoadName); + COM_DefaultExtension(sLoadName, sizeof(sLoadName), ".wav"); // so psExt below is always valid + psExt = &sLoadName[strlen(sLoadName) - 4]; len = strlen(sLoadName); } - if (!S_LoadSound_FileLoadAndNameAdjuster(sLoadName, &data, &size, len)) - { + if (!S_LoadSound_FileLoadAndNameAdjuster(sLoadName, &data, &size, len)) { return qfalse; } SND_TouchSFX(sfx); -//========= - if (Q_stricmpn(psExt,".mp3",4)==0) - { + //========= + if (Q_stricmpn(psExt, ".mp3", 4) == 0) { // load MP3 file instead... // - if (MP3_IsValid(sLoadName,data, size, qfalse)) - { - int iRawPCMDataSize = MP3_GetUnpackedSize(sLoadName,data,size,qfalse,qfalse); - - if (S_LoadSound_DirIsAllowedToKeepMP3s(sfx->sSoundName) // NOT sLoadName, this uses original un-languaged name - && - MP3Stream_InitFromFile(sfx, data, size, sLoadName, iRawPCMDataSize + 2304 /* + 1 MP3 frame size, jic */,qfalse) - ) - { -// Com_DPrintf("(Keeping file \"%s\" as MP3)\n",sLoadName); + if (MP3_IsValid(sLoadName, data, size, qfalse)) { + int iRawPCMDataSize = MP3_GetUnpackedSize(sLoadName, data, size, qfalse, qfalse); + + if (S_LoadSound_DirIsAllowedToKeepMP3s(sfx->sSoundName) // NOT sLoadName, this uses original un-languaged name + && MP3Stream_InitFromFile(sfx, data, size, sLoadName, iRawPCMDataSize + 2304 /* + 1 MP3 frame size, jic */, qfalse)) { + // Com_DPrintf("(Keeping file \"%s\" as MP3)\n",sLoadName); #ifdef USE_OPENAL - if (s_UseOpenAL) - { + if (s_UseOpenAL) { // Create space for lipsync data (4 lip sync values per streaming AL buffer) if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) sfx->lipSyncData = (char *)Z_Malloc(16, TAG_SND_RAWDATA, qfalse); @@ -798,51 +699,45 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) sfx->lipSyncData = NULL; } #endif - } - else - { + } else { // small file, not worth keeping as MP3 since it would increase in size (with MP3 header etc)... // - Com_DPrintf("S_LoadSound: Unpacking MP3 file(%i) \"%s\" to wav(%i).\n",size,sLoadName,iRawPCMDataSize); + Com_DPrintf("S_LoadSound: Unpacking MP3 file(%i) \"%s\" to wav(%i).\n", size, sLoadName, iRawPCMDataSize); // // unpack and convert into WAV... // { - byte *pbUnpackBuffer = (byte *) Z_Malloc( iRawPCMDataSize+10 +2304 /* */, TAG_TEMP_WORKSPACE, qfalse ); // won't return if fails + byte *pbUnpackBuffer = (byte *)Z_Malloc(iRawPCMDataSize + 10 + 2304 /* */, TAG_TEMP_WORKSPACE, qfalse); // won't return if fails { - int iResultBytes = MP3_UnpackRawPCM( sLoadName, data, size, pbUnpackBuffer, qfalse ); + int iResultBytes = MP3_UnpackRawPCM(sLoadName, data, size, pbUnpackBuffer, qfalse); - if (iResultBytes!= iRawPCMDataSize){ - Com_Printf(S_COLOR_YELLOW"**** MP3 %s final unpack size %d different to previous value %d\n",sLoadName,iResultBytes,iRawPCMDataSize); - //assert (iResultBytes == iRawPCMDataSize); + if (iResultBytes != iRawPCMDataSize) { + Com_Printf(S_COLOR_YELLOW "**** MP3 %s final unpack size %d different to previous value %d\n", sLoadName, iResultBytes, + iRawPCMDataSize); + // assert (iResultBytes == iRawPCMDataSize); } - // fake up a WAV structure so I can use the other post-load sound code such as volume calc for lip-synching // // (this is a bit crap really, but it lets me drop through into existing code)... // - MP3_FakeUpWAVInfo( sLoadName, data, size, iResultBytes, - // these params are all references... - info.format, info.rate, info.width, info.channels, info.samples, info.dataofs, - qfalse - ); + MP3_FakeUpWAVInfo(sLoadName, data, size, iResultBytes, + // these params are all references... + info.format, info.rate, info.width, info.channels, info.samples, info.dataofs, qfalse); - S_LoadSound_Finalize(&info,sfx,pbUnpackBuffer); + S_LoadSound_Finalize(&info, sfx, pbUnpackBuffer); #ifdef Q3_BIG_ENDIAN // the MP3 decoder returns the samples in the correct endianness, but ResampleSfx byteswaps them, // so we have to swap them again... - sfx->fVolRange = 0; + sfx->fVolRange = 0; - for (int i = 0; i < sfx->iSoundLengthInSamples; i++) - { + for (int i = 0; i < sfx->iSoundLengthInSamples; i++) { sfx->pSoundData[i] = LittleShort(sfx->pSoundData[i]); // C++11 defines double abs(short) which is not what we want here, // because double >> int is not defined. Force interpretation as int - if (sfx->fVolRange < (abs(static_cast(sfx->pSoundData[i])) >> 8)) - { + if (sfx->fVolRange < (abs(static_cast(sfx->pSoundData[i])) >> 8)) { sfx->fVolRange = abs(static_cast(sfx->pSoundData[i])) >> 8; } } @@ -850,28 +745,23 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) // Open AL #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) - { + if (s_UseOpenAL) { + if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) { sfx->lipSyncData = (char *)Z_Malloc((sfx->iSoundLengthInSamples / 1000) + 1, TAG_SND_RAWDATA, qfalse); S_PreProcessLipSync(sfx); - } - else + } else sfx->lipSyncData = NULL; // Clear Open AL Error state alGetError(); // Generate AL Buffer - ALuint Buffer; + ALuint Buffer; alGenBuffers(1, &Buffer); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { // Copy audio data to AL Buffer - alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples*2, 22050); - if (alGetError() == AL_NO_ERROR) - { + alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples * 2, 22050); + if (alGetError() == AL_NO_ERROR) { sfx->Buffer = Buffer; Z_Free(sfx->pSoundData); sfx->pSoundData = NULL; @@ -884,67 +774,58 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) } } } - } - else - { + } else { // MP3_IsValid() will already have printed any errors via Com_Printf at this point... // - FS_FreeFile (data); + FS_FreeFile(data); return qfalse; } - } - else - { + } else { // loading a WAV, presumably... -//========= + //========= - info = GetWavinfo( sLoadName, data, size ); - if ( info.channels != 1 ) { - Com_Printf ("%s is a stereo wav file\n", sLoadName); - FS_FreeFile (data); + info = GetWavinfo(sLoadName, data, size); + if (info.channels != 1) { + Com_Printf("%s is a stereo wav file\n", sLoadName); + FS_FreeFile(data); return qfalse; } -/* if ( info.width == 1 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: %s is a 8 bit wav file\n", sLoadName); - } + /* if ( info.width == 1 ) { + Com_Printf(S_COLOR_YELLOW "WARNING: %s is a 8 bit wav file\n", sLoadName); + } - if ( info.rate != 22050 ) { - Com_Printf(S_COLOR_YELLOW "WARNING: %s is not a 22kHz wav file\n", sLoadName); - } -*/ + if ( info.rate != 22050 ) { + Com_Printf(S_COLOR_YELLOW "WARNING: %s is not a 22kHz wav file\n", sLoadName); + } + */ samples = (short *)Z_Malloc(info.samples * sizeof(short) * 2, TAG_TEMP_WORKSPACE, qfalse); sfx->eSoundCompressionMethod = ct_16; - sfx->iSoundLengthInSamples = info.samples; + sfx->iSoundLengthInSamples = info.samples; sfx->pSoundData = NULL; - ResampleSfx( sfx, info.rate, info.width, data + info.dataofs ); + ResampleSfx(sfx, info.rate, info.width, data + info.dataofs); // Open AL #ifdef USE_OPENAL - if (s_UseOpenAL) - { - if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) - { + if (s_UseOpenAL) { + if ((strstr(sfx->sSoundName, "chars")) || (strstr(sfx->sSoundName, "CHARS"))) { sfx->lipSyncData = (char *)Z_Malloc((sfx->iSoundLengthInSamples / 1000) + 1, TAG_SND_RAWDATA, qfalse); S_PreProcessLipSync(sfx); - } - else + } else sfx->lipSyncData = NULL; // Clear Open AL Error State alGetError(); // Generate AL Buffer - ALuint Buffer; + ALuint Buffer; alGenBuffers(1, &Buffer); - if (alGetError() == AL_NO_ERROR) - { + if (alGetError() == AL_NO_ERROR) { // Copy audio data to AL Buffer - alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples*2, 22050); - if (alGetError() == AL_NO_ERROR) - { + alBufferData(Buffer, AL_FORMAT_MONO16, sfx->pSoundData, sfx->iSoundLengthInSamples * 2, 22050); + if (alGetError() == AL_NO_ERROR) { // Store AL Buffer in sfx struct, and release sample data sfx->Buffer = Buffer; Z_Free(sfx->pSoundData); @@ -957,22 +838,20 @@ static qboolean S_LoadSound_Actual( sfx_t *sfx ) Z_Free(samples); } - FS_FreeFile( data ); + FS_FreeFile(data); return qtrue; } - // wrapper function for above so I can guarantee that we don't attempt any audio-dumping during this call because // of a z_malloc() fail recovery... // -qboolean S_LoadSound( sfx_t *sfx ) -{ - gbInsideLoadSound = qtrue; // !!!!!!!!!!!!! +qboolean S_LoadSound(sfx_t *sfx) { + gbInsideLoadSound = qtrue; // !!!!!!!!!!!!! - qboolean bReturn = S_LoadSound_Actual( sfx ); + qboolean bReturn = S_LoadSound_Actual(sfx); - gbInsideLoadSound = qfalse; // !!!!!!!!!!!!! + gbInsideLoadSound = qfalse; // !!!!!!!!!!!!! return bReturn; } @@ -981,29 +860,24 @@ qboolean S_LoadSound( sfx_t *sfx ) /* Precalculate the lipsync values for the whole sample */ -void S_PreProcessLipSync(sfx_t *sfx) -{ +void S_PreProcessLipSync(sfx_t *sfx) { int i, j; int sample; int sampleTotal = 0; j = 0; - for (i = 0; i < sfx->iSoundLengthInSamples; i += 100) - { + for (i = 0; i < sfx->iSoundLengthInSamples; i += 100) { sample = LittleShort(sfx->pSoundData[i]); sample = sample >> 8; sampleTotal += sample * sample; - if (((i + 100) % 1000) == 0) - { + if (((i + 100) % 1000) == 0) { sampleTotal /= 10; - if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) - { + if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) { // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) + } else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) sample = 1; else if (sampleTotal < sfx->fVolRange * s_lip_threshold_3->value) sample = 2; @@ -1031,12 +905,10 @@ void S_PreProcessLipSync(sfx_t *sfx) else sampleTotal = 0; - if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) - { + if (sampleTotal < sfx->fVolRange * s_lip_threshold_1->value) { // tell the scripts that are relying on this that we are still going, but actually silent right now. sample = -1; - } - else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) + } else if (sampleTotal < sfx->fVolRange * s_lip_threshold_2->value) sample = 1; else if (sampleTotal < sfx->fVolRange * s_lip_threshold_3->value) sample = 2; diff --git a/codemp/client/snd_mix.cpp b/codemp/client/snd_mix.cpp index e418b4802b..5059a38360 100644 --- a/codemp/client/snd_mix.cpp +++ b/codemp/client/snd_mix.cpp @@ -27,21 +27,17 @@ along with this program; if not, see . #include "snd_local.h" portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE]; -int *snd_p, snd_linear_count, snd_vol; -short *snd_out; - - +int *snd_p, snd_linear_count, snd_vol; +short *snd_out; // FIXME: proper fix for that ? #if !defined(_MSC_VER) || !id386 -void S_WriteLinearBlastStereo16 (void) -{ - int i; - int val; - - for (i=0 ; i>8; +void S_WriteLinearBlastStereo16(void) { + int i; + int val; + + for (i = 0; i < snd_linear_count; i += 2) { + val = snd_p[i] >> 8; if (val > 0x7fff) snd_out[i] = 0x7fff; else if (val < (short)0x8000) @@ -49,33 +45,32 @@ void S_WriteLinearBlastStereo16 (void) else snd_out[i] = val; - val = snd_p[i+1]>>8; + val = snd_p[i + 1] >> 8; if (val > 0x7fff) - snd_out[i+1] = 0x7fff; + snd_out[i + 1] = 0x7fff; else if (val < (short)0x8000) - snd_out[i+1] = (short)0x8000; + snd_out[i + 1] = (short)0x8000; else - snd_out[i+1] = val; + snd_out[i + 1] = val; } } #else -unsigned int uiMMXAvailable = 0; // leave as 32 bit -__declspec( naked ) void S_WriteLinearBlastStereo16 (void) -{ +unsigned int uiMMXAvailable = 0; // leave as 32 bit +__declspec(naked) void S_WriteLinearBlastStereo16(void) { __asm { push edi push ebx - mov ecx,ds:dword ptr[snd_linear_count] // snd_linear_count is always even at this point, but not nec. mult of 4 + mov ecx,ds:dword ptr[snd_linear_count] // snd_linear_count is always even at this point, but not nec. mult of 4 mov ebx,ds:dword ptr[snd_p] mov edi,ds:dword ptr[snd_out] cmp [uiMMXAvailable], dword ptr 0 je NoMMX -// writes 8 items (128 bits) per loop pass... -// + // writes 8 items (128 bits) per loop pass... + // cmp ecx,8 jb NoMMX @@ -100,14 +95,14 @@ __declspec( naked ) void S_WriteLinearBlastStereo16 (void) emms - // now deal with any remaining count... - // + // now deal with any remaining count... + // jecxz LExit NoMMX: -// writes 2 items (32 bits) per loop pass... -// + // writes 2 items (32 bits) per loop pass... + // LWLBLoopTop: mov eax,ds:dword ptr[-8+ebx+ecx*4] sar eax,8 @@ -148,38 +143,34 @@ __declspec( naked ) void S_WriteLinearBlastStereo16 (void) #endif +void S_TransferStereo16(unsigned long *pbuf, int endtime) { + int lpos; + int ls_paintedtime; -void S_TransferStereo16 (unsigned long *pbuf, int endtime) -{ - int lpos; - int ls_paintedtime; - - snd_p = (int *) paintbuffer; + snd_p = (int *)paintbuffer; ls_paintedtime = s_paintedtime; - while (ls_paintedtime < endtime) - { - // handle recirculating buffer issues - lpos = ls_paintedtime & ((dma.samples>>1)-1); + while (ls_paintedtime < endtime) { + // handle recirculating buffer issues + lpos = ls_paintedtime & ((dma.samples >> 1) - 1); - snd_out = (short *) pbuf + (lpos<<1); + snd_out = (short *)pbuf + (lpos << 1); - snd_linear_count = (dma.samples>>1) - lpos; + snd_linear_count = (dma.samples >> 1) - lpos; if (ls_paintedtime + snd_linear_count > endtime) snd_linear_count = endtime - ls_paintedtime; snd_linear_count <<= 1; - // write a linear blast of samples - S_WriteLinearBlastStereo16 (); + // write a linear blast of samples + S_WriteLinearBlastStereo16(); snd_p += snd_linear_count; - ls_paintedtime += (snd_linear_count>>1); + ls_paintedtime += (snd_linear_count >> 1); - if( CL_VideoRecording( ) ) - { - if ( cls.state == CA_ACTIVE || cl_forceavidemo->integer) { - CL_WriteAVIAudioFrame( (byte *)snd_out, snd_linear_count << 1 ); + if (CL_VideoRecording()) { + if (cls.state == CA_ACTIVE || cl_forceavidemo->integer) { + CL_WriteAVIAudioFrame((byte *)snd_out, snd_linear_count << 1); } } } @@ -191,49 +182,41 @@ S_TransferPaintBuffer =================== */ -void S_TransferPaintBuffer(int endtime) -{ - int out_idx; - int count; - int out_mask; - int *p; - int step; - int val; +void S_TransferPaintBuffer(int endtime) { + int out_idx; + int count; + int out_mask; + int *p; + int step; + int val; unsigned long *pbuf; pbuf = (unsigned long *)dma.buffer; - - if ( s_testsound->integer ) { - int i; - int count; + if (s_testsound->integer) { + int i; + int count; // write a fixed sine wave count = (endtime - s_paintedtime); - for (i=0 ; i> 8; - p+= step; + p += step; if (val > 0x7fff) val = 0x7fff; else if (val < (short)0x8000) @@ -241,26 +224,22 @@ void S_TransferPaintBuffer(int endtime) out[out_idx] = (short)val; out_idx = (out_idx + 1) & out_mask; } - } - else if (dma.samplebits == 8) - { - unsigned char *out = (unsigned char *) pbuf; - while (count--) - { + } else if (dma.samplebits == 8) { + unsigned char *out = (unsigned char *)pbuf; + while (count--) { val = *p >> 8; - p+= step; + p += step; if (val > 0x7fff) val = 0x7fff; else if (val < (short)0x8000) val = (short)0x8000; - out[out_idx] = (short)((val>>8) + 128); + out[out_idx] = (short)((val >> 8) + 128); out_idx = (out_idx + 1) & out_mask; } } } } - /* =============================================================================== @@ -268,23 +247,21 @@ CHANNEL MIXING =============================================================================== */ -static void S_PaintChannelFrom16( channel_t *ch, const sfx_t *sfx, int count, int sampleOffset, int bufferOffset ) -{ - portable_samplepair_t *pSamplesDest; +static void S_PaintChannelFrom16(channel_t *ch, const sfx_t *sfx, int count, int sampleOffset, int bufferOffset) { + portable_samplepair_t *pSamplesDest; int iData; float ofst = sampleOffset; - int iLeftVol = ch->leftvol * snd_vol; - int iRightVol = ch->rightvol * snd_vol; + int iLeftVol = ch->leftvol * snd_vol; + int iRightVol = ch->rightvol * snd_vol; - pSamplesDest = &paintbuffer[ bufferOffset ]; + pSamplesDest = &paintbuffer[bufferOffset]; - for ( int i=0 ; ipSoundData[ (int)ofst ]; + for (int i = 0; i < count; i++) { + iData = sfx->pSoundData[(int)ofst]; - pSamplesDest[i].left += (iData * iLeftVol )>>8; - pSamplesDest[i].right += (iData * iRightVol)>>8; + pSamplesDest[i].left += (iData * iLeftVol) >> 8; + pSamplesDest[i].right += (iData * iRightVol) >> 8; if (ch->doppler && ch->dopplerScale > 1) { ofst += 1 * ch->dopplerScale; } else { @@ -293,136 +270,127 @@ static void S_PaintChannelFrom16( channel_t *ch, const sfx_t *sfx, int count, in } } - -void S_PaintChannelFromMP3( channel_t *ch, const sfx_t *sc, int count, int sampleOffset, int bufferOffset ) -{ +void S_PaintChannelFromMP3(channel_t *ch, const sfx_t *sc, int count, int sampleOffset, int bufferOffset) { int data; int leftvol, rightvol; signed short *sfx; - int i; - portable_samplepair_t *samp; + int i; + portable_samplepair_t *samp; static short tempMP3Buffer[PAINTBUFFER_SIZE]; - MP3Stream_GetSamples( ch, sampleOffset, count, tempMP3Buffer, qfalse ); // qfalse = not stereo + MP3Stream_GetSamples(ch, sampleOffset, count, tempMP3Buffer, qfalse); // qfalse = not stereo - leftvol = ch->leftvol*snd_vol; - rightvol = ch->rightvol*snd_vol; + leftvol = ch->leftvol * snd_vol; + rightvol = ch->rightvol * snd_vol; sfx = tempMP3Buffer; - samp = &paintbuffer[ bufferOffset ]; + samp = &paintbuffer[bufferOffset]; - - while ( count & 3 ) { + while (count & 3) { data = *sfx; - samp->left += (data * leftvol)>>8; - samp->right += (data * rightvol)>>8; + samp->left += (data * leftvol) >> 8; + samp->right += (data * rightvol) >> 8; sfx++; samp++; count--; } - for ( i=0 ; i>8; - samp[i].right += (data * rightvol)>>8; + samp[i].left += (data * leftvol) >> 8; + samp[i].right += (data * rightvol) >> 8; - data = sfx[i+1]; - samp[i+1].left += (data * leftvol)>>8; - samp[i+1].right += (data * rightvol)>>8; + data = sfx[i + 1]; + samp[i + 1].left += (data * leftvol) >> 8; + samp[i + 1].right += (data * rightvol) >> 8; - data = sfx[i+2]; - samp[i+2].left += (data * leftvol)>>8; - samp[i+2].right += (data * rightvol)>>8; + data = sfx[i + 2]; + samp[i + 2].left += (data * leftvol) >> 8; + samp[i + 2].right += (data * rightvol) >> 8; - data = sfx[i+3]; - samp[i+3].left += (data * leftvol)>>8; - samp[i+3].right += (data * rightvol)>>8; + data = sfx[i + 3]; + samp[i + 3].left += (data * leftvol) >> 8; + samp[i + 3].right += (data * rightvol) >> 8; } } - // subroutinised to save code dup (called twice) -ste // -void ChannelPaint(channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset) -{ - switch (sc->eSoundCompressionMethod) - { - case ct_16: +void ChannelPaint(channel_t *ch, sfx_t *sc, int count, int sampleOffset, int bufferOffset) { + switch (sc->eSoundCompressionMethod) { + case ct_16: - S_PaintChannelFrom16 (ch, sc, count, sampleOffset, bufferOffset); - break; + S_PaintChannelFrom16(ch, sc, count, sampleOffset, bufferOffset); + break; - case ct_MP3: + case ct_MP3: - S_PaintChannelFromMP3 (ch, sc, count, sampleOffset, bufferOffset); - break; + S_PaintChannelFromMP3(ch, sc, count, sampleOffset, bufferOffset); + break; - default: + default: - assert(0); // debug aid, ignored in release. FIXME: Should we ERR_DROP here for badness-catch? - break; + assert(0); // debug aid, ignored in release. FIXME: Should we ERR_DROP here for badness-catch? + break; } } - - -void S_PaintChannels( int endtime ) { - int i; - int end; +void S_PaintChannels(int endtime) { + int i; + int end; channel_t *ch; - sfx_t *sc; - int ltime, count; - int sampleOffset; - int normal_vol,voice_vol; + sfx_t *sc; + int ltime, count; + int sampleOffset; + int normal_vol, voice_vol; - snd_vol = normal_vol = s_volume->value*256; - voice_vol = (int)(s_volumeVoice->value*256); + snd_vol = normal_vol = s_volume->value * 256; + voice_vol = (int)(s_volumeVoice->value * 256); -//Com_Printf ("%i to %i\n", s_paintedtime, endtime); - while ( s_paintedtime < endtime ) { + // Com_Printf ("%i to %i\n", s_paintedtime, endtime); + while (s_paintedtime < endtime) { // if paintbuffer is smaller than DMA buffer // we may need to fill it multiple times end = endtime; - if ( endtime - s_paintedtime > PAINTBUFFER_SIZE ) { + if (endtime - s_paintedtime > PAINTBUFFER_SIZE) { end = s_paintedtime + PAINTBUFFER_SIZE; } // clear the paint buffer to either music or zeros - if ( s_rawend < s_paintedtime ) { - if ( s_rawend ) { - //Com_DPrintf ("background sound underrun\n"); + if (s_rawend < s_paintedtime) { + if (s_rawend) { + // Com_DPrintf ("background sound underrun\n"); } memset(paintbuffer, 0, (end - s_paintedtime) * sizeof(portable_samplepair_t)); } else { // copy from the streaming sound source - int s; - int stop; + int s; + int stop; stop = (end < s_rawend) ? end : s_rawend; - for ( i = s_paintedtime ; i < stop ; i++ ) { - s = i&(MAX_RAW_SAMPLES-1); - paintbuffer[i-s_paintedtime] = s_rawsamples[s]; + for (i = s_paintedtime; i < stop; i++) { + s = i & (MAX_RAW_SAMPLES - 1); + paintbuffer[i - s_paintedtime] = s_rawsamples[s]; } -// if (i != end) -// Com_Printf ("partial stream\n"); -// else -// Com_Printf ("full stream\n"); - for ( ; i < end ; i++ ) { - paintbuffer[i-s_paintedtime].left = - paintbuffer[i-s_paintedtime].right = 0; + // if (i != end) + // Com_Printf ("partial stream\n"); + // else + // Com_Printf ("full stream\n"); + for (; i < end; i++) { + paintbuffer[i - s_paintedtime].left = paintbuffer[i - s_paintedtime].right = 0; } } // paint in the channels. ch = s_channels; - for ( i = 0; i < MAX_CHANNELS ; i++, ch++ ) { - if ( !ch->thesfx || (ch->leftvol<0.25 && ch->rightvol<0.25 )) { + for (i = 0; i < MAX_CHANNELS; i++, ch++) { + if (!ch->thesfx || (ch->leftvol < 0.25 && ch->rightvol < 0.25)) { continue; } - if ( ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL ) + if (ch->entchannel == CHAN_VOICE || ch->entchannel == CHAN_VOICE_ATTEN || ch->entchannel == CHAN_VOICE_GLOBAL) snd_vol = voice_vol; else snd_vol = normal_vol; @@ -434,8 +402,7 @@ void S_PaintChannels( int endtime ) { // a looping sound effect and the end of // the sameple is hit... // - do - { + do { if (ch->loopSound) { sampleOffset = ltime % sc->iSoundLengthInSamples; } else { @@ -443,67 +410,67 @@ void S_PaintChannels( int endtime ) { } count = end - ltime; - if ( ch->doppler && ch->dopplerScale > 1 ) { - if ( sampleOffset + (count * ch->dopplerScale) > sc->iSoundLengthInSamples ) { + if (ch->doppler && ch->dopplerScale > 1) { + if (sampleOffset + (count * ch->dopplerScale) > sc->iSoundLengthInSamples) { count = (sc->iSoundLengthInSamples - sampleOffset) / ch->dopplerScale; // avoid infinite loop once length of remaining pSoundData (numerator) // is smaller than dopplerScale (denominator), resulting in 0. - if ( count == 0 ) { + if (count == 0) { break; } } } else { - if ( sampleOffset + count > sc->iSoundLengthInSamples ) { + if (sampleOffset + count > sc->iSoundLengthInSamples) { count = sc->iSoundLengthInSamples - sampleOffset; } } - if ( count > 0 ) { + if (count > 0) { ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); ltime += count; } - } while ( ltime < end && ch->loopSound ); + } while (ltime < end && ch->loopSound); } -/* temprem - // paint in the looped channels. - ch = loop_channels; - for ( i = 0; i < numLoopChannels ; i++, ch++ ) { - if ( !ch->thesfx || (!ch->leftvol && !ch->rightvol )) { - continue; - } - - { - - ltime = s_paintedtime; - sc = ch->thesfx; - - if (sc->soundData==NULL || sc->soundLength==0) { - continue; - } - // we might have to make two passes if it - // is a looping sound effect and the end of - // the sample is hit - do { - sampleOffset = (ltime % sc->soundLength); - - count = end - ltime; - if ( sampleOffset + count > sc->soundLength ) { - count = sc->soundLength - sampleOffset; + /* temprem + // paint in the looped channels. + ch = loop_channels; + for ( i = 0; i < numLoopChannels ; i++, ch++ ) { + if ( !ch->thesfx || (!ch->leftvol && !ch->rightvol )) { + continue; } - if ( count > 0 ) { - ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); - ltime += count; - } - } while ( ltime < end); - } - } -*/ + ltime = s_paintedtime; + sc = ch->thesfx; + + if (sc->soundData==NULL || sc->soundLength==0) { + continue; + } + // we might have to make two passes if it + // is a looping sound effect and the end of + // the sample is hit + do { + sampleOffset = (ltime % sc->soundLength); + + count = end - ltime; + if ( sampleOffset + count > sc->soundLength ) { + count = sc->soundLength - sampleOffset; + } + + if ( count > 0 ) + { + ChannelPaint(ch, sc, count, sampleOffset, ltime - s_paintedtime); + ltime += count; + } + + } while ( ltime < end); + } + } + */ // transfer out according to DMA format - S_TransferPaintBuffer( end ); + S_TransferPaintBuffer(end); s_paintedtime = end; } } diff --git a/codemp/client/snd_mp3.cpp b/codemp/client/snd_mp3.cpp index 452d21082a..f16d17139f 100644 --- a/codemp/client/snd_mp3.cpp +++ b/codemp/client/snd_mp3.cpp @@ -25,48 +25,43 @@ along with this program; if not, see . // // (The interface module between all the MP3 stuff and the game) - #include "client.h" -#include "snd_mp3.h" // only included directly by a few snd_xxxx.cpp files plus this one -#include "mp3code/mp3struct.h" // keep this rather awful file secret from the rest of the program +#include "snd_mp3.h" // only included directly by a few snd_xxxx.cpp files plus this one +#include "mp3code/mp3struct.h" // keep this rather awful file secret from the rest of the program // expects data already loaded, filename arg is for error printing only // // returns success/fail // -qboolean MP3_IsValid( const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) -{ +qboolean MP3_IsValid(const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) { char *psError = C_MP3_IsValid(pvData, iDataLen, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s(%s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s(%s)\n", psError, psLocalFilename)); } return (qboolean)!psError; } - - // expects data already loaded, filename arg is for error printing only // // returns unpacked length, or 0 for errors (which will be printed internally) // -int MP3_GetUnpackedSize( const char *psLocalFilename, void *pvData, int iDataLen, qboolean qbIgnoreID3Tag /* = qfalse */ - , qboolean bStereoDesired /* = qfalse */ - ) -{ - int iUnpackedSize = 0; - - // always do this now that we have fast-unpack code for measuring output size... (much safer than relying on tags that may have been edited, or if MP3 has been re-saved with same tag) +int MP3_GetUnpackedSize(const char *psLocalFilename, void *pvData, int iDataLen, qboolean qbIgnoreID3Tag /* = qfalse */ + , + qboolean bStereoDesired /* = qfalse */ +) { + int iUnpackedSize = 0; + + // always do this now that we have fast-unpack code for measuring output size... (much safer than relying on tags that may have been edited, or if MP3 has + // been re-saved with same tag) // - if (1)//qbIgnoreID3Tag || !MP3_ReadSpecialTagInfo((byte *)pvData, iDataLen, NULL, &iUnpackedSize)) + if (1) // qbIgnoreID3Tag || !MP3_ReadSpecialTagInfo((byte *)pvData, iDataLen, NULL, &iUnpackedSize)) { - char *psError = C_MP3_GetUnpackedSize( pvData, iDataLen, &iUnpackedSize, bStereoDesired); + char *psError = C_MP3_GetUnpackedSize(pvData, iDataLen, &iUnpackedSize, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); return 0; } } @@ -74,50 +69,41 @@ int MP3_GetUnpackedSize( const char *psLocalFilename, void *pvData, int iDataLen return iUnpackedSize; } - - // expects data already loaded, filename arg is for error printing only // // returns byte count of unpacked data (effectively a success/fail bool) // -int MP3_UnpackRawPCM( const char *psLocalFilename, void *pvData, int iDataLen, byte *pbUnpackBuffer, qboolean bStereoDesired /* = qfalse */) -{ +int MP3_UnpackRawPCM(const char *psLocalFilename, void *pvData, int iDataLen, byte *pbUnpackBuffer, qboolean bStereoDesired /* = qfalse */) { int iUnpackedSize; - char *psError = C_MP3_UnpackRawPCM( pvData, iDataLen, &iUnpackedSize, pbUnpackBuffer, bStereoDesired); + char *psError = C_MP3_UnpackRawPCM(pvData, iDataLen, &iUnpackedSize, pbUnpackBuffer, bStereoDesired); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); return 0; } return iUnpackedSize; } - // psLocalFilename is just for error reporting (if any)... // -qboolean MP3Stream_InitPlayingTimeFields( LP_MP3STREAM lpMP3Stream, const char *psLocalFilename, void *pvData, int iDataLen, qboolean bStereoDesired /* = qfalse */) -{ +qboolean MP3Stream_InitPlayingTimeFields(LP_MP3STREAM lpMP3Stream, const char *psLocalFilename, void *pvData, int iDataLen, + qboolean bStereoDesired /* = qfalse */) { qboolean bRetval = qfalse; int iRate, iWidth, iChannels; - char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &iRate, &iWidth, &iChannels, bStereoDesired ); - if (psError) - { - Com_Printf(va(S_COLOR_RED"MP3Stream_InitPlayingTimeFields(): %s\n(File: %s)\n",psError, psLocalFilename)); - } - else - { - int iUnpackLength = MP3_GetUnpackedSize( psLocalFilename, pvData, iDataLen, qfalse, // qboolean qbIgnoreID3Tag - bStereoDesired); - if (iUnpackLength) - { - lpMP3Stream->iTimeQuery_UnpackedLength = iUnpackLength; - lpMP3Stream->iTimeQuery_SampleRate = iRate; - lpMP3Stream->iTimeQuery_Channels = iChannels; - lpMP3Stream->iTimeQuery_Width = iWidth; + char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &iRate, &iWidth, &iChannels, bStereoDesired); + if (psError) { + Com_Printf(va(S_COLOR_RED "MP3Stream_InitPlayingTimeFields(): %s\n(File: %s)\n", psError, psLocalFilename)); + } else { + int iUnpackLength = MP3_GetUnpackedSize(psLocalFilename, pvData, iDataLen, qfalse, // qboolean qbIgnoreID3Tag + bStereoDesired); + if (iUnpackLength) { + lpMP3Stream->iTimeQuery_UnpackedLength = iUnpackLength; + lpMP3Stream->iTimeQuery_SampleRate = iRate; + lpMP3Stream->iTimeQuery_Channels = iChannels; + lpMP3Stream->iTimeQuery_Width = iWidth; bRetval = qtrue; } @@ -126,84 +112,72 @@ qboolean MP3Stream_InitPlayingTimeFields( LP_MP3STREAM lpMP3Stream, const char * return bRetval; } -float MP3Stream_GetPlayingTimeInSeconds( LP_MP3STREAM lpMP3Stream ) -{ - if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? - return (float)((((double)lpMP3Stream->iTimeQuery_UnpackedLength / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / (double)lpMP3Stream->iTimeQuery_Width); +float MP3Stream_GetPlayingTimeInSeconds(LP_MP3STREAM lpMP3Stream) { + if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? + return ( + float)((((double)lpMP3Stream->iTimeQuery_UnpackedLength / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / + (double)lpMP3Stream->iTimeQuery_Width); return 0.0f; } -float MP3Stream_GetRemainingTimeInSeconds( LP_MP3STREAM lpMP3Stream ) -{ - if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? - return (float)(((((double)(lpMP3Stream->iTimeQuery_UnpackedLength - (lpMP3Stream->iBytesDecodedTotal * (lpMP3Stream->iTimeQuery_SampleRate / dma.speed)))) / (double)lpMP3Stream->iTimeQuery_SampleRate) / (double)lpMP3Stream->iTimeQuery_Channels) / (double)lpMP3Stream->iTimeQuery_Width); +float MP3Stream_GetRemainingTimeInSeconds(LP_MP3STREAM lpMP3Stream) { + if (lpMP3Stream->iTimeQuery_UnpackedLength) // fields initialised? + return ( + float)(((((double)(lpMP3Stream->iTimeQuery_UnpackedLength - (lpMP3Stream->iBytesDecodedTotal * (lpMP3Stream->iTimeQuery_SampleRate / dma.speed)))) / + (double)lpMP3Stream->iTimeQuery_SampleRate) / + (double)lpMP3Stream->iTimeQuery_Channels) / + (double)lpMP3Stream->iTimeQuery_Width); return 0.0f; } - - - // expects data already loaded, filename arg is for error printing only // -qboolean MP3_FakeUpWAVInfo( const char *psLocalFilename, void *pvData, int iDataLen, int iUnpackedDataLength, - int &format, int &rate, int &width, int &channels, int &samples, int &dataofs, - qboolean bStereoDesired /* = qfalse */ - ) -{ +qboolean MP3_FakeUpWAVInfo(const char *psLocalFilename, void *pvData, int iDataLen, int iUnpackedDataLength, int &format, int &rate, int &width, int &channels, + int &samples, int &dataofs, qboolean bStereoDesired /* = qfalse */ +) { // some things can be done instantly... // - format = 1; // 1 for MS format - dataofs= 0; // will be 0 for me (since there's no header in the unpacked data) + format = 1; // 1 for MS format + dataofs = 0; // will be 0 for me (since there's no header in the unpacked data) // some things need to be read... (though the whole stereo flag thing is crap) // - char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &rate, &width, &channels, bStereoDesired ); - if (psError) - { - Com_Printf(va(S_COLOR_RED"%s\n(File: %s)\n",psError, psLocalFilename)); + char *psError = C_MP3_GetHeaderData(pvData, iDataLen, &rate, &width, &channels, bStereoDesired); + if (psError) { + Com_Printf(va(S_COLOR_RED "%s\n(File: %s)\n", psError, psLocalFilename)); } // and some stuff needs calculating... // - samples = iUnpackedDataLength / width; + samples = iUnpackedDataLength / width; return (qboolean)!psError; } - - -const char sKEY_MAXVOL[]="#MAXVOL"; // formerly #defines -const char sKEY_UNCOMP[]="#UNCOMP"; // " " +const char sKEY_MAXVOL[] = "#MAXVOL"; // formerly #defines +const char sKEY_UNCOMP[] = "#UNCOMP"; // " " // returns qtrue for success... // -qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, - id3v1_1** ppTAG /* = NULL */, - int *piUncompressedSize /* = NULL */, +qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, id3v1_1 **ppTAG /* = NULL */, int *piUncompressedSize /* = NULL */, float *pfMaxVol /* = NULL */ - ) -{ +) { qboolean qbError = qfalse; - id3v1_1* pTAG = (id3v1_1*) ((pbLoadedFile+iLoadedFileLen)-sizeof(id3v1_1)); // sizeof = 128 + id3v1_1 *pTAG = (id3v1_1 *)((pbLoadedFile + iLoadedFileLen) - sizeof(id3v1_1)); // sizeof = 128 - if (!Q_strncmp(pTAG->id, "TAG", 3)) - { + if (!Q_strncmp(pTAG->id, "TAG", 3)) { // TAG found... // // read MAXVOL key... // - if (Q_strncmp(pTAG->comment, sKEY_MAXVOL, strlen(sKEY_MAXVOL))) - { + if (Q_strncmp(pTAG->comment, sKEY_MAXVOL, strlen(sKEY_MAXVOL))) { qbError = qtrue; - } - else - { - if ( pfMaxVol) - { + } else { + if (pfMaxVol) { *pfMaxVol = atof(pTAG->comment + strlen(sKEY_MAXVOL)); } } @@ -211,42 +185,30 @@ qboolean MP3_ReadSpecialTagInfo(byte *pbLoadedFile, int iLoadedFileLen, // // read UNCOMP key... // - if (Q_strncmp(pTAG->album, sKEY_UNCOMP, strlen(sKEY_UNCOMP))) - { + if (Q_strncmp(pTAG->album, sKEY_UNCOMP, strlen(sKEY_UNCOMP))) { qbError = qtrue; - } - else - { - if ( piUncompressedSize) - { + } else { + if (piUncompressedSize) { *piUncompressedSize = atoi(pTAG->album + strlen(sKEY_UNCOMP)); } } - } - else - { + } else { pTAG = NULL; } - if (ppTAG) - { + if (ppTAG) { *ppTAG = pTAG; } return (qboolean)(pTAG && !qbError); } +#define FUZZY_AMOUNT \ + (5 * 1024) // so it has to be significantly over, not just break even, because of + // the xtra CPU time versus memory saving - -#define FUZZY_AMOUNT (5*1024) // so it has to be significantly over, not just break even, because of - // the xtra CPU time versus memory saving - -cvar_t* cv_MP3overhead = NULL; -void MP3_InitCvars(void) -{ - cv_MP3overhead = Cvar_Get("s_mp3overhead", va("%d", sizeof(MP3STREAM) + FUZZY_AMOUNT), CVAR_ARCHIVE ); -} - +cvar_t *cv_MP3overhead = NULL; +void MP3_InitCvars(void) { cv_MP3overhead = Cvar_Get("s_mp3overhead", va("%d", sizeof(MP3STREAM) + FUZZY_AMOUNT), CVAR_ARCHIVE); } // a file has been loaded in memory, see if we want to keep it as MP3, else as normal WAV... // @@ -254,55 +216,47 @@ void MP3_InitCvars(void) // // (note: the reason I pass in the unpacked size rather than working it out here is simply because I already have it) // -qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, const char *psSrcDataFilename, - int iMP3UnPackedSize, qboolean bStereoDesired /* = qfalse */ - ) -{ +qboolean MP3Stream_InitFromFile(sfx_t *sfx, byte *pbSrcData, int iSrcDatalen, const char *psSrcDataFilename, int iMP3UnPackedSize, + qboolean bStereoDesired /* = qfalse */ +) { // first, make a decision based on size here as to whether or not it's worth it because of MP3 buffer space // making small files much bigger (and therefore best left as WAV)... // - if (cv_MP3overhead && - ( - //iSrcDatalen + sizeof(MP3STREAM) + FUZZY_AMOUNT < iMP3UnPackedSize - iSrcDatalen + cv_MP3overhead->integer < iMP3UnPackedSize - ) - ) - { + if (cv_MP3overhead && ( + // iSrcDatalen + sizeof(MP3STREAM) + FUZZY_AMOUNT < iMP3UnPackedSize + iSrcDatalen + cv_MP3overhead->integer < iMP3UnPackedSize)) { // ok, let's keep it as MP3 then... // - float fMaxVol = 128; // seems to be a reasonable typical default for maxvol (for lip synch). Naturally there's no #define I can use instead... + float fMaxVol = 128; // seems to be a reasonable typical default for maxvol (for lip synch). Naturally there's no #define I can use instead... - MP3_ReadSpecialTagInfo(pbSrcData, iSrcDatalen, NULL, NULL, &fMaxVol ); // try and read a read maxvol from MP3 header + MP3_ReadSpecialTagInfo(pbSrcData, iSrcDatalen, NULL, NULL, &fMaxVol); // try and read a read maxvol from MP3 header // fill in some sfx_t fields... // -// Q_strncpyz( sfx->name, psSrcDataFilename, sizeof(sfx->name) ); + // Q_strncpyz( sfx->name, psSrcDataFilename, sizeof(sfx->name) ); sfx->eSoundCompressionMethod = ct_MP3; sfx->fVolRange = fMaxVol; - //sfx->width = 2; - sfx->iSoundLengthInSamples = ((iMP3UnPackedSize / 2/*sfx->width*/) / (44100 / dma.speed)) / (bStereoDesired?2:1); + // sfx->width = 2; + sfx->iSoundLengthInSamples = ((iMP3UnPackedSize / 2 /*sfx->width*/) / (44100 / dma.speed)) / (bStereoDesired ? 2 : 1); // // alloc mem for data and store it (raw MP3 in this case)... // - sfx->pSoundData = (short *) SND_malloc( iSrcDatalen, sfx ); - memcpy( sfx->pSoundData, pbSrcData, iSrcDatalen ); + sfx->pSoundData = (short *)SND_malloc(iSrcDatalen, sfx); + memcpy(sfx->pSoundData, pbSrcData, iSrcDatalen); // now init the low-level MP3 stuff... // - MP3STREAM SFX_MP3Stream = {}; // important to init to all zeroes! - char *psError = C_MP3Stream_DecodeInit( &SFX_MP3Stream, /*sfx->data*/ /*sfx->soundData*/ pbSrcData, iSrcDatalen, - dma.speed,//(s_khz->value == 44)?44100:(s_khz->value == 22)?22050:11025, - 2/*sfx->width*/ * 8, - bStereoDesired - ); - SFX_MP3Stream.pbSourceData = (byte *) sfx->pSoundData; - if (psError) - { + MP3STREAM SFX_MP3Stream = {}; // important to init to all zeroes! + char *psError = C_MP3Stream_DecodeInit(&SFX_MP3Stream, /*sfx->data*/ /*sfx->soundData*/ pbSrcData, iSrcDatalen, + dma.speed, //(s_khz->value == 44)?44100:(s_khz->value == 22)?22050:11025, + 2 /*sfx->width*/ * 8, bStereoDesired); + SFX_MP3Stream.pbSourceData = (byte *)sfx->pSoundData; + if (psError) { // This should never happen, since any errors or problems with the MP3 file would have stopped us getting // to this whole function, but just in case... // - Com_Printf(va(S_COLOR_YELLOW"File \"%s\": %s\n",psSrcDataFilename,psError)); + Com_Printf(va(S_COLOR_YELLOW "File \"%s\": %s\n", psSrcDataFilename, psError)); // This will leave iSrcDatalen bytes on the hunk stack (since you can't dealloc that), but MP3 files are // usually small, and like I say, it should never happen. @@ -318,8 +272,8 @@ qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, c // // make a copy of the filled-in stream struct and attach to the sfx_t struct... // - sfx->pMP3StreamHeader = (MP3STREAM *) Z_Malloc( sizeof(MP3STREAM), TAG_SND_MP3STREAMHDR, qfalse ); - memcpy( sfx->pMP3StreamHeader, &SFX_MP3Stream, sizeof(MP3STREAM) ); + sfx->pMP3StreamHeader = (MP3STREAM *)Z_Malloc(sizeof(MP3STREAM), TAG_SND_MP3STREAMHDR, qfalse); + memcpy(sfx->pMP3StreamHeader, &SFX_MP3Stream, sizeof(MP3STREAM)); // return qtrue; } @@ -327,17 +281,14 @@ qboolean MP3Stream_InitFromFile( sfx_t* sfx, byte *pbSrcData, int iSrcDatalen, c return qfalse; } - - // decode one packet of MP3 data only (typical output size is 2304, or 2304*2 for stereo, so input size is less // // return is decoded byte count, else 0 for finished // -int MP3Stream_Decode( LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic ) -{ +int MP3Stream_Decode(LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic) { lpMP3Stream->iCopyOffset = 0; - if (0)//!bDoingMusic) + if (0) //! bDoingMusic) { /* // SOF2: need to make a local buffer up so we can decode the piece we want from a contiguous bitstream rather than @@ -409,164 +360,140 @@ int MP3Stream_Decode( LP_MP3STREAM lpMP3Stream, qboolean bDoingMusic ) } } */ - } - else - { + } else { // SOF2 music, or EF1 anything... // - return C_MP3Stream_Decode( lpMP3Stream, qfalse ); // bFastForwarding + return C_MP3Stream_Decode(lpMP3Stream, qfalse); // bFastForwarding } } +qboolean MP3Stream_SeekTo(channel_t *ch, float fTimeToSeekTo) { + const float fEpsilon = 0.05f; // accurate to 1/50 of a second, but plus or minus this gives 1/10 of second -qboolean MP3Stream_SeekTo( channel_t *ch, float fTimeToSeekTo ) -{ - const float fEpsilon = 0.05f; // accurate to 1/50 of a second, but plus or minus this gives 1/10 of second - - MP3Stream_Rewind( ch ); + MP3Stream_Rewind(ch); // // sanity... :-) // - const float fTrackLengthInSeconds = MP3Stream_GetPlayingTimeInSeconds( &ch->MP3StreamHeader ); - if (fTimeToSeekTo > fTrackLengthInSeconds) - { + const float fTrackLengthInSeconds = MP3Stream_GetPlayingTimeInSeconds(&ch->MP3StreamHeader); + if (fTimeToSeekTo > fTrackLengthInSeconds) { fTimeToSeekTo = fTrackLengthInSeconds; } // now do the seek... // - while (1) - { - float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds( &ch->MP3StreamHeader ) - MP3Stream_GetRemainingTimeInSeconds( &ch->MP3StreamHeader ); + while (1) { + float fPlayingTimeElapsed = MP3Stream_GetPlayingTimeInSeconds(&ch->MP3StreamHeader) - MP3Stream_GetRemainingTimeInSeconds(&ch->MP3StreamHeader); float fAbsTimeDiff = fabs(fTimeToSeekTo - fPlayingTimeElapsed); - if ( fAbsTimeDiff <= fEpsilon) + if (fAbsTimeDiff <= fEpsilon) return qtrue; // when decoding, use fast-forward until within 3 seconds, then slow-decode (which should init stuff properly?)... // - int iBytesDecodedThisPacket = C_MP3Stream_Decode( &ch->MP3StreamHeader, (fAbsTimeDiff > 3.0f) ); // bFastForwarding + int iBytesDecodedThisPacket = C_MP3Stream_Decode(&ch->MP3StreamHeader, (fAbsTimeDiff > 3.0f)); // bFastForwarding if (iBytesDecodedThisPacket == 0) - break; // EOS + break; // EOS } return qfalse; } - // returns qtrue for all ok // -qboolean MP3Stream_Rewind( channel_t *ch ) -{ +qboolean MP3Stream_Rewind(channel_t *ch) { ch->iMP3SlidingDecodeWritePos = 0; - ch->iMP3SlidingDecodeWindowPos= 0; + ch->iMP3SlidingDecodeWindowPos = 0; -/* - char *psError = C_MP3Stream_Rewind( &ch->MP3StreamHeader ); + /* + char *psError = C_MP3Stream_Rewind( &ch->MP3StreamHeader ); - if (psError) - { - Com_Printf(S_COLOR_YELLOW"%s\n",psError); - return qfalse; - } + if (psError) + { + Com_Printf(S_COLOR_YELLOW"%s\n",psError); + return qfalse; + } - return qtrue; -*/ + return qtrue; + */ // speed opt, since I know I already have the right data setup here... // memcpy(&ch->MP3StreamHeader, ch->thesfx->pMP3StreamHeader, sizeof(ch->MP3StreamHeader)); return qtrue; - } - // returns qtrue while still playing normally, else qfalse for either finished or request-offset-error // -qboolean MP3Stream_GetSamples( channel_t *ch, int startingSampleNum, int count, short *buf, qboolean bStereo ) -{ +qboolean MP3Stream_GetSamples(channel_t *ch, int startingSampleNum, int count, short *buf, qboolean bStereo) { qboolean qbStreamStillGoing = qtrue; - const int iQuarterOfSlidingBuffer = sizeof(ch->MP3SlidingDecodeBuffer)/4; - const int iThreeQuartersOfSlidingBuffer = (sizeof(ch->MP3SlidingDecodeBuffer)*3)/4; + const int iQuarterOfSlidingBuffer = sizeof(ch->MP3SlidingDecodeBuffer) / 4; + const int iThreeQuartersOfSlidingBuffer = (sizeof(ch->MP3SlidingDecodeBuffer) * 3) / 4; -// Com_Printf("startingSampleNum %d\n",startingSampleNum); + // Com_Printf("startingSampleNum %d\n",startingSampleNum); - count *= 2/* <- = SOF2; ch->sfx->width*/; // count arg was for words, so double it for bytes; + count *= 2 /* <- = SOF2; ch->sfx->width*/; // count arg was for words, so double it for bytes; // convert sample number into a byte offset... (make new variable for clarity?) // - startingSampleNum *= 2 /* <- = SOF2; ch->sfx->width*/ * (bStereo?2:1); + startingSampleNum *= 2 /* <- = SOF2; ch->sfx->width*/ * (bStereo ? 2 : 1); - if ( startingSampleNum < ch->iMP3SlidingDecodeWindowPos) - { + if (startingSampleNum < ch->iMP3SlidingDecodeWindowPos) { // what?!?!?! smegging time travel needed or something?, forget it - memset(buf,0,count); + memset(buf, 0, count); return qfalse; } -// Com_OPrintf("\nRequest: startingSampleNum %d, count %d\n",startingSampleNum,count); -// Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos); + // Com_OPrintf("\nRequest: startingSampleNum %d, count %d\n",startingSampleNum,count); + // Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos); -// qboolean _bDecoded = qfalse; + // qboolean _bDecoded = qfalse; - while (! - ( - (startingSampleNum >= ch->iMP3SlidingDecodeWindowPos) - && - (startingSampleNum + count < ch->iMP3SlidingDecodeWindowPos + ch->iMP3SlidingDecodeWritePos) - ) - ) - { -// if (!_bDecoded) -// { -// Com_Printf(S_COLOR_YELLOW"Decode needed!\n"); -// } -// _bDecoded = qtrue; -// Com_OPrintf("Scrolling..."); - - int _iBytesDecoded = MP3Stream_Decode( (LP_MP3STREAM) &ch->MP3StreamHeader, bStereo ); // stereo only for music, so this is safe -// Com_OPrintf("%d bytes decoded\n",_iBytesDecoded); - if (_iBytesDecoded == 0) - { + while (!((startingSampleNum >= ch->iMP3SlidingDecodeWindowPos) && + (startingSampleNum + count < ch->iMP3SlidingDecodeWindowPos + ch->iMP3SlidingDecodeWritePos))) { + // if (!_bDecoded) + // { + // Com_Printf(S_COLOR_YELLOW"Decode needed!\n"); + // } + // _bDecoded = qtrue; + // Com_OPrintf("Scrolling..."); + + int _iBytesDecoded = MP3Stream_Decode((LP_MP3STREAM)&ch->MP3StreamHeader, bStereo); // stereo only for music, so this is safe + // Com_OPrintf("%d bytes decoded\n",_iBytesDecoded); + if (_iBytesDecoded == 0) { // no more source data left so clear the remainder of the buffer... // - memset(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, 0, sizeof(ch->MP3SlidingDecodeBuffer)-ch->iMP3SlidingDecodeWritePos); -// Com_OPrintf("Finished\n"); + memset(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, 0, sizeof(ch->MP3SlidingDecodeBuffer) - ch->iMP3SlidingDecodeWritePos); + // Com_OPrintf("Finished\n"); qbStreamStillGoing = qfalse; break; - } - else - { - memcpy(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos,ch->MP3StreamHeader.bDecodeBuffer,_iBytesDecoded); + } else { + memcpy(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, ch->MP3StreamHeader.bDecodeBuffer, _iBytesDecoded); ch->iMP3SlidingDecodeWritePos += _iBytesDecoded; // if reached 3/4 of buffer pos, backscroll the decode window by one quarter... // - if (ch->iMP3SlidingDecodeWritePos > iThreeQuartersOfSlidingBuffer) - { + if (ch->iMP3SlidingDecodeWritePos > iThreeQuartersOfSlidingBuffer) { memmove(ch->MP3SlidingDecodeBuffer, ((byte *)ch->MP3SlidingDecodeBuffer + iQuarterOfSlidingBuffer), iThreeQuartersOfSlidingBuffer); ch->iMP3SlidingDecodeWritePos -= iQuarterOfSlidingBuffer; - ch->iMP3SlidingDecodeWindowPos+= iQuarterOfSlidingBuffer; + ch->iMP3SlidingDecodeWindowPos += iQuarterOfSlidingBuffer; } } -// Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos); + // Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos); } -// if (!_bDecoded) -// { -// Com_Printf(S_COLOR_YELLOW"No decode needed\n"); -// } + // if (!_bDecoded) + // { + // Com_Printf(S_COLOR_YELLOW"No decode needed\n"); + // } assert(startingSampleNum >= ch->iMP3SlidingDecodeWindowPos); - memcpy( buf, ch->MP3SlidingDecodeBuffer + (startingSampleNum-ch->iMP3SlidingDecodeWindowPos), count); + memcpy(buf, ch->MP3SlidingDecodeBuffer + (startingSampleNum - ch->iMP3SlidingDecodeWindowPos), count); -// Com_OPrintf("OK\n\n"); + // Com_OPrintf("OK\n\n"); return qbStreamStillGoing; } - ///////////// eof ///////////// - diff --git a/codemp/client/snd_music.cpp b/codemp/client/snd_music.cpp index 499190448e..d0ba5c77fe 100644 --- a/codemp/client/snd_music.cpp +++ b/codemp/client/snd_music.cpp @@ -35,86 +35,83 @@ along with this program; if not, see . #include "snd_music.h" #include "snd_ambient.h" - -extern qboolean S_FileExists( const char *psFilename ); - -#define sKEY_MUSICFILES "musicfiles" -#define sKEY_ENTRY "entry" -#define sKEY_EXIT "exit" -#define sKEY_MARKER "marker" -#define sKEY_TIME "time" -#define sKEY_NEXTFILE "nextfile" -#define sKEY_NEXTMARK "nextmark" -#define sKEY_LEVELMUSIC "levelmusic" -#define sKEY_EXPLORE "explore" -#define sKEY_ACTION "action" -#define sKEY_BOSS "boss" -#define sKEY_DEATH "death" -#define sKEY_USES "uses" -#define sKEY_USEBOSS "useboss" - -#define sKEY_PLACEHOLDER "placeholder" // ignore these - -#define sFILENAME_DMS "ext_data/dms.dat" - - -#define MUSIC_PARSE_ERROR(_string) Music_Parse_Error(_string) // only use during parse, not run-time use, and bear in mid that data is zapped after error message, so exit any loops immediately -#define MUSIC_PARSE_WARNING(_string) Music_Parse_Warning(_string) +extern qboolean S_FileExists(const char *psFilename); + +#define sKEY_MUSICFILES "musicfiles" +#define sKEY_ENTRY "entry" +#define sKEY_EXIT "exit" +#define sKEY_MARKER "marker" +#define sKEY_TIME "time" +#define sKEY_NEXTFILE "nextfile" +#define sKEY_NEXTMARK "nextmark" +#define sKEY_LEVELMUSIC "levelmusic" +#define sKEY_EXPLORE "explore" +#define sKEY_ACTION "action" +#define sKEY_BOSS "boss" +#define sKEY_DEATH "death" +#define sKEY_USES "uses" +#define sKEY_USEBOSS "useboss" + +#define sKEY_PLACEHOLDER "placeholder" // ignore these + +#define sFILENAME_DMS "ext_data/dms.dat" + +#define MUSIC_PARSE_ERROR(_string) \ + Music_Parse_Error( \ + _string) // only use during parse, not run-time use, and bear in mid that data is zapped after error message, so exit any loops immediately +#define MUSIC_PARSE_WARNING(_string) Music_Parse_Warning(_string) typedef struct MusicExitPoint_s { - sstring_t sNextFile; - sstring_t sNextMark; // blank if used for an explore piece, name of marker point to enter new file at + sstring_t sNextFile; + sstring_t sNextMark; // blank if used for an explore piece, name of marker point to enter new file at } MusicExitPoint_t; -struct MusicExitTime_t // need to declare this way for operator < below +struct MusicExitTime_t // need to declare this way for operator < below { - float fTime; - int iExitPoint; + float fTime; + int iExitPoint; // I'm defining this '<' operator so STL's sort algorithm will work // - bool operator < (const MusicExitTime_t& X) const {return (fTime < X.fTime);} + bool operator<(const MusicExitTime_t &X) const { return (fTime < X.fTime); } }; // it's possible for all 3 of these to be empty if it's boss or death music // -typedef std::vector MusicExitPoints_t; -typedef std::vector MusicExitTimes_t; -typedef std::map MusicEntryTimes_t; // key eg "marker1" +typedef std::vector MusicExitPoints_t; +typedef std::vector MusicExitTimes_t; +typedef std::map MusicEntryTimes_t; // key eg "marker1" typedef struct MusicFile_s { - sstring_t sFileNameBase; - MusicEntryTimes_t MusicEntryTimes; - MusicExitPoints_t MusicExitPoints; - MusicExitTimes_t MusicExitTimes; + sstring_t sFileNameBase; + MusicEntryTimes_t MusicEntryTimes; + MusicExitPoints_t MusicExitPoints; + MusicExitTimes_t MusicExitTimes; } MusicFile_t; -typedef std::map MusicData_t; // string is "explore", "action", "boss" etc - MusicData_t* MusicData = NULL; +typedef std::map MusicData_t; // string is "explore", "action", "boss" etc +MusicData_t *MusicData = NULL; // there are now 2 of these, because of the new "uses" keyword... // -sstring_t gsLevelNameForLoad; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths -sstring_t gsLevelNameForCompare; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths -sstring_t gsLevelNameForBossLoad; // eg "kejim_base', special case for enabling boss music to come from a different dir - sigh.... +sstring_t gsLevelNameForLoad; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths +sstring_t gsLevelNameForCompare; // eg "kejim_base", formed from literal BSP name, but also used as dir name for music paths +sstring_t gsLevelNameForBossLoad; // eg "kejim_base', special case for enabling boss music to come from a different dir - sigh.... -void Music_Free(void) -{ +void Music_Free(void) { delete MusicData; MusicData = NULL; } // some sort of error in the music data... // -static void Music_Parse_Error(const char *psError) -{ +static void Music_Parse_Error(const char *psError) { #ifdef FINAL_BUILD extern cvar_t *s_debugdynamic; - if (s_debugdynamic && s_debugdynamic->integer) - { + if (s_debugdynamic && s_debugdynamic->integer) { #endif - Com_Printf(S_COLOR_RED "Error parsing music data ( in \"%s\" ):\n%s\n",sFILENAME_DMS,psError); + Com_Printf(S_COLOR_RED "Error parsing music data ( in \"%s\" ):\n%s\n", sFILENAME_DMS, psError); #ifdef FINAL_BUILD } #endif @@ -123,12 +120,10 @@ static void Music_Parse_Error(const char *psError) // something to just mention if interested... // -static void Music_Parse_Warning(const char *psError) -{ +static void Music_Parse_Warning(const char *psError) { #ifdef FINAL_BUILD extern cvar_t *s_debugdynamic; - if (s_debugdynamic && s_debugdynamic->integer) - { + if (s_debugdynamic && s_debugdynamic->integer) { #endif Com_Printf(S_COLOR_YELLOW "%s", psError); #ifdef FINAL_BUILD @@ -140,138 +135,140 @@ static void Music_Parse_Warning(const char *psError) // Unfortunately two of the places that calls this doesn't have much other access to the state other than // a string, not an enum, so for those cases they only pass in BOSS or EXPLORE, so don't rely on it totally. // -static const char *Music_BuildFileName(const char *psFileNameBase, MusicState_e eMusicState ) -{ +static const char *Music_BuildFileName(const char *psFileNameBase, MusicState_e eMusicState) { static sstring_t sFileName; - //HACK! - if (eMusicState == eBGRNDTRACK_DEATH) - { + // HACK! + if (eMusicState == eBGRNDTRACK_DEATH) { return "music/death_music.mp3"; } const char *psDirName = (eMusicState == eBGRNDTRACK_BOSS) ? gsLevelNameForBossLoad.c_str() : gsLevelNameForLoad.c_str(); - sFileName = va("music/%s/%s.mp3",psDirName,psFileNameBase); + sFileName = va("music/%s/%s.mp3", psDirName, psFileNameBase); return sFileName.c_str(); } // this MUST return NULL for non-base states unless doing debug-query -const char *Music_BaseStateToString( MusicState_e eMusicState, qboolean bDebugPrintQuery /* = qfalse */ ) -{ - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: return "explore"; - case eBGRNDTRACK_ACTION: return "action"; - case eBGRNDTRACK_BOSS: return "boss"; - case eBGRNDTRACK_SILENCE: return "silence"; // not used in this module, but snd_dma uses it now it's de-static'd - case eBGRNDTRACK_DEATH: return "death"; - - // info only, not map<> lookup keys (unlike above)... - // - case eBGRNDTRACK_ACTIONTRANS0: if (bDebugPrintQuery) return "action_tr0"; - case eBGRNDTRACK_ACTIONTRANS1: if (bDebugPrintQuery) return "action_tr1"; - case eBGRNDTRACK_ACTIONTRANS2: if (bDebugPrintQuery) return "action_tr2"; - case eBGRNDTRACK_ACTIONTRANS3: if (bDebugPrintQuery) return "action_tr3"; - case eBGRNDTRACK_EXPLORETRANS0: if (bDebugPrintQuery) return "explore_tr0"; - case eBGRNDTRACK_EXPLORETRANS1: if (bDebugPrintQuery) return "explore_tr1"; - case eBGRNDTRACK_EXPLORETRANS2: if (bDebugPrintQuery) return "explore_tr2"; - case eBGRNDTRACK_EXPLORETRANS3: if (bDebugPrintQuery) return "explore_tr3"; - case eBGRNDTRACK_FADE: if (bDebugPrintQuery) return "fade"; - default: break; +const char *Music_BaseStateToString(MusicState_e eMusicState, qboolean bDebugPrintQuery /* = qfalse */) { + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: + return "explore"; + case eBGRNDTRACK_ACTION: + return "action"; + case eBGRNDTRACK_BOSS: + return "boss"; + case eBGRNDTRACK_SILENCE: + return "silence"; // not used in this module, but snd_dma uses it now it's de-static'd + case eBGRNDTRACK_DEATH: + return "death"; + + // info only, not map<> lookup keys (unlike above)... + // + case eBGRNDTRACK_ACTIONTRANS0: + if (bDebugPrintQuery) + return "action_tr0"; + case eBGRNDTRACK_ACTIONTRANS1: + if (bDebugPrintQuery) + return "action_tr1"; + case eBGRNDTRACK_ACTIONTRANS2: + if (bDebugPrintQuery) + return "action_tr2"; + case eBGRNDTRACK_ACTIONTRANS3: + if (bDebugPrintQuery) + return "action_tr3"; + case eBGRNDTRACK_EXPLORETRANS0: + if (bDebugPrintQuery) + return "explore_tr0"; + case eBGRNDTRACK_EXPLORETRANS1: + if (bDebugPrintQuery) + return "explore_tr1"; + case eBGRNDTRACK_EXPLORETRANS2: + if (bDebugPrintQuery) + return "explore_tr2"; + case eBGRNDTRACK_EXPLORETRANS3: + if (bDebugPrintQuery) + return "explore_tr3"; + case eBGRNDTRACK_FADE: + if (bDebugPrintQuery) + return "fade"; + default: + break; } return NULL; } -static qboolean Music_ParseMusic(CGenericParser2 &Parser, MusicData_t *MusicData, CGPGroup *pgMusicFiles, const char *psMusicName, const char *psMusicNameKey, MusicState_e eMusicState) -{ +static qboolean Music_ParseMusic(CGenericParser2 &Parser, MusicData_t *MusicData, CGPGroup *pgMusicFiles, const char *psMusicName, const char *psMusicNameKey, + MusicState_e eMusicState) { qboolean bReturn = qfalse; MusicFile_t MusicFile; CGPGroup *pgMusicFile = pgMusicFiles->FindSubGroup(psMusicName); - if (pgMusicFile) - { + if (pgMusicFile) { // read subgroups... // qboolean bEntryFound = qfalse; - qboolean bExitFound = qfalse; + qboolean bExitFound = qfalse; // // (read entry points first, so I can check exit points aren't too close in time) // CGPGroup *pEntryGroup = pgMusicFile->FindSubGroup(sKEY_ENTRY); - if (pEntryGroup) - { + if (pEntryGroup) { // read entry points... // - for (CGPValue *pValue = pEntryGroup->GetPairs(); pValue; pValue = pValue->GetNext()) - { - const char *psKey = pValue->GetName(); - const char *psValue = pValue->GetTopValue(); + for (CGPValue *pValue = pEntryGroup->GetPairs(); pValue; pValue = pValue->GetNext()) { + const char *psKey = pValue->GetName(); + const char *psValue = pValue->GetTopValue(); - //if (!Q_strncmp(psKey,sKEY_MARKER,strlen(sKEY_MARKER))) // for now, assume anything is a marker + // if (!Q_strncmp(psKey,sKEY_MARKER,strlen(sKEY_MARKER))) // for now, assume anything is a marker { MusicFile.MusicEntryTimes[psKey] = atof(psValue); - bEntryFound = qtrue; // harmless to keep setting + bEntryFound = qtrue; // harmless to keep setting } } } - for (CGPGroup *pGroup = pgMusicFile->GetSubGroups(); pGroup; pGroup = pGroup->GetNext()) - { + for (CGPGroup *pGroup = pgMusicFile->GetSubGroups(); pGroup; pGroup = pGroup->GetNext()) { const char *psGroupName = pGroup->GetName(); - if (!strcmp(psGroupName,sKEY_ENTRY)) - { + if (!strcmp(psGroupName, sKEY_ENTRY)) { // skip entry points, I've already read them in above // - } - else - if (!strcmp(psGroupName,sKEY_EXIT)) - { - int iThisExitPointIndex = MusicFile.MusicExitPoints.size(); // must eval this first, so unaffected by push_back etc + } else if (!strcmp(psGroupName, sKEY_EXIT)) { + int iThisExitPointIndex = MusicFile.MusicExitPoints.size(); // must eval this first, so unaffected by push_back etc // // read this set of exit points... // MusicExitPoint_t MusicExitPoint; - for (CGPValue *pValue = pGroup->GetPairs(); pValue; pValue = pValue->GetNext()) - { - const char *psKey = pValue->GetName(); - const char *psValue = pValue->GetTopValue(); + for (CGPValue *pValue = pGroup->GetPairs(); pValue; pValue = pValue->GetNext()) { + const char *psKey = pValue->GetName(); + const char *psValue = pValue->GetTopValue(); - if (!strcmp(psKey,sKEY_NEXTFILE)) - { + if (!strcmp(psKey, sKEY_NEXTFILE)) { MusicExitPoint.sNextFile = psValue; - bExitFound = qtrue; // harmless to keep setting - } - else - if (!strcmp(psKey,sKEY_NEXTMARK)) - { + bExitFound = qtrue; // harmless to keep setting + } else if (!strcmp(psKey, sKEY_NEXTMARK)) { MusicExitPoint.sNextMark = psValue; - } - else - if (!Q_strncmp(psKey,sKEY_TIME,strlen(sKEY_TIME))) - { + } else if (!Q_strncmp(psKey, sKEY_TIME, strlen(sKEY_TIME))) { MusicExitTime_t MusicExitTime; - MusicExitTime.fTime = atof(psValue); - MusicExitTime.iExitPoint= iThisExitPointIndex; + MusicExitTime.fTime = atof(psValue); + MusicExitTime.iExitPoint = iThisExitPointIndex; // new check, don't keep this this exit point if it's within 1.5 seconds either way of an entry point... // qboolean bTooCloseToEntryPoint = qfalse; - for (MusicEntryTimes_t::iterator itEntryTimes = MusicFile.MusicEntryTimes.begin(); itEntryTimes != MusicFile.MusicEntryTimes.end(); ++itEntryTimes) - { + for (MusicEntryTimes_t::iterator itEntryTimes = MusicFile.MusicEntryTimes.begin(); itEntryTimes != MusicFile.MusicEntryTimes.end(); + ++itEntryTimes) { float fThisEntryTime = (*itEntryTimes).second; - if (Q_fabs(fThisEntryTime - MusicExitTime.fTime) < 1.5f) - { -// bTooCloseToEntryPoint = qtrue; // not sure about this, ignore for now + if (Q_fabs(fThisEntryTime - MusicExitTime.fTime) < 1.5f) { + // bTooCloseToEntryPoint = qtrue; // not sure about this, ignore for now break; } } - if (!bTooCloseToEntryPoint) - { + if (!bTooCloseToEntryPoint) { MusicFile.MusicExitTimes.push_back(MusicExitTime); } } @@ -282,32 +279,29 @@ static qboolean Music_ParseMusic(CGenericParser2 &Parser, MusicData_t *MusicData // error checking... // - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: - if (iNumExitPoints > iMAX_EXPLORE_TRANSITIONS) - { - MUSIC_PARSE_ERROR( va("\"%s\" has > %d %s transitions defined!\n",psMusicName,iMAX_EXPLORE_TRANSITIONS,psMusicNameKey) ); - return qfalse; - } - break; + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: + if (iNumExitPoints > iMAX_EXPLORE_TRANSITIONS) { + MUSIC_PARSE_ERROR(va("\"%s\" has > %d %s transitions defined!\n", psMusicName, iMAX_EXPLORE_TRANSITIONS, psMusicNameKey)); + return qfalse; + } + break; - case eBGRNDTRACK_ACTION: - if (iNumExitPoints > iMAX_ACTION_TRANSITIONS) - { - MUSIC_PARSE_ERROR( va("\"%s\" has > %d %s transitions defined!\n",psMusicName,iMAX_ACTION_TRANSITIONS,psMusicNameKey) ); - return qfalse; - } - break; + case eBGRNDTRACK_ACTION: + if (iNumExitPoints > iMAX_ACTION_TRANSITIONS) { + MUSIC_PARSE_ERROR(va("\"%s\" has > %d %s transitions defined!\n", psMusicName, iMAX_ACTION_TRANSITIONS, psMusicNameKey)); + return qfalse; + } + break; - case eBGRNDTRACK_BOSS: - case eBGRNDTRACK_DEATH: + case eBGRNDTRACK_BOSS: + case eBGRNDTRACK_DEATH: - MUSIC_PARSE_ERROR( va("\"%s\" has %s transitions defined, this is not allowed!\n",psMusicName,psMusicNameKey) ); - break; + MUSIC_PARSE_ERROR(va("\"%s\" has %s transitions defined, this is not allowed!\n", psMusicName, psMusicNameKey)); + break; - default: - break; + default: + break; } } } @@ -316,148 +310,122 @@ static qboolean Music_ParseMusic(CGenericParser2 &Parser, MusicData_t *MusicData // bReturn = qtrue; - if (eMusicState != eBGRNDTRACK_BOSS && eMusicState != eBGRNDTRACK_DEATH) // boss & death pieces can omit entry/exit stuff + if (eMusicState != eBGRNDTRACK_BOSS && eMusicState != eBGRNDTRACK_DEATH) // boss & death pieces can omit entry/exit stuff { - if (!bEntryFound) - { - MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\" in group \"%s\"\n",sKEY_ENTRY,psMusicName)); + if (!bEntryFound) { + MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\" in group \"%s\"\n", sKEY_ENTRY, psMusicName)); bReturn = qfalse; } - if (!bExitFound) - { - MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\" in group \"%s\"\n",sKEY_EXIT,psMusicName)); + if (!bExitFound) { + MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\" in group \"%s\"\n", sKEY_EXIT, psMusicName)); bReturn = qfalse; } } - } - else - { - MUSIC_PARSE_ERROR(va("Unable to find musicfiles entry \"%s\"\n",psMusicName)); + } else { + MUSIC_PARSE_ERROR(va("Unable to find musicfiles entry \"%s\"\n", psMusicName)); } - if (bReturn) - { - MusicFile.sFileNameBase = psMusicName; - (*MusicData)[ psMusicNameKey ] = MusicFile; + if (bReturn) { + MusicFile.sFileNameBase = psMusicName; + (*MusicData)[psMusicNameKey] = MusicFile; } return bReturn; } - - - // I only need this because GP2 can't cope with trailing whitespace (for !@#$%^'s sake!!!!)... // // (output buffer will always be just '\n' seperated, regardless of possible "\r\n" pairs) // // (remember to Z_Free() the returned char * when done with it!!!) // -static char *StripTrailingWhiteSpaceOnEveryLine(char *pText) -{ +static char *StripTrailingWhiteSpaceOnEveryLine(char *pText) { std::string strNewText; - while (*pText) - { - char sOneLine[1024]; // BTO: was 16k + while (*pText) { + char sOneLine[1024]; // BTO: was 16k // find end of line... // char *pThisLineEnd = pText; - while (*pThisLineEnd && *pThisLineEnd != '\r' && ((unsigned)(pThisLineEnd-pText) < sizeof(sOneLine)-1)) - { + while (*pThisLineEnd && *pThisLineEnd != '\r' && ((unsigned)(pThisLineEnd - pText) < sizeof(sOneLine) - 1)) { pThisLineEnd++; } unsigned int iCharsToCopy = pThisLineEnd - pText; strncpy(sOneLine, pText, iCharsToCopy); - sOneLine[iCharsToCopy]='\0'; + sOneLine[iCharsToCopy] = '\0'; pText += iCharsToCopy; - while (*pText == '\n' || *pText == '\r') pText++; + while (*pText == '\n' || *pText == '\r') + pText++; // trim trailing... // qboolean bTrimmed = qfalse; - do - { + do { bTrimmed = qfalse; int iStrLen = strlen(sOneLine); - if (iStrLen) - { - if (sOneLine[iStrLen-1] == '\t' || sOneLine[iStrLen-1] == ' ') - { - sOneLine[iStrLen-1] = '\0'; + if (iStrLen) { + if (sOneLine[iStrLen - 1] == '\t' || sOneLine[iStrLen - 1] == ' ') { + sOneLine[iStrLen - 1] = '\0'; bTrimmed = qtrue; } } - } - while (bTrimmed); + } while (bTrimmed); strNewText += sOneLine; strNewText += "\n"; } - char *pNewText = (char *) Z_Malloc( strlen(strNewText.c_str())+1, TAG_TEMP_WORKSPACE, qfalse); + char *pNewText = (char *)Z_Malloc(strlen(strNewText.c_str()) + 1, TAG_TEMP_WORKSPACE, qfalse); strcpy(pNewText, strNewText.c_str()); return pNewText; } - // called from SV_SpawnServer, but before map load and music start etc. // // This just initialises the Lucas music structs so the background music player can interrogate them... // sstring_t gsLevelNameFromServer; -void Music_SetLevelName(const char *psLevelName) -{ - gsLevelNameFromServer = psLevelName; -} +void Music_SetLevelName(const char *psLevelName) { gsLevelNameFromServer = psLevelName; } -static qboolean Music_ParseLeveldata(const char *psLevelName) -{ +static qboolean Music_ParseLeveldata(const char *psLevelName) { qboolean bReturn = qfalse; - if (MusicData == NULL) - { + if (MusicData == NULL) { MusicData = new MusicData_t; } - // already got this data? + // already got this data? // - if (MusicData->size() && !Q_stricmp(psLevelName,gsLevelNameForCompare.c_str())) - { + if (MusicData->size() && !Q_stricmp(psLevelName, gsLevelNameForCompare.c_str())) { return qtrue; } MusicData->clear(); char sLevelName[MAX_QPATH]; - Q_strncpyz(sLevelName,psLevelName,sizeof(sLevelName)); + Q_strncpyz(sLevelName, psLevelName, sizeof(sLevelName)); - gsLevelNameForLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file - gsLevelNameForCompare = sLevelName; // harmless to init here even if we fail to parse dms.dat file - gsLevelNameForBossLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForCompare = sLevelName; // harmless to init here even if we fail to parse dms.dat file + gsLevelNameForBossLoad = sLevelName; // harmless to init here even if we fail to parse dms.dat file char *pText = NULL; - /*int iTotalBytesLoaded = */FS_ReadFile(sFILENAME_DMS, (void **)&pText ); - if (pText) - { + /*int iTotalBytesLoaded = */ FS_ReadFile(sFILENAME_DMS, (void **)&pText); + if (pText) { char *psStrippedText = StripTrailingWhiteSpaceOnEveryLine(pText); CGenericParser2 Parser; - char *psDataPtr = psStrippedText; // because ptr gets advanced, so we supply a clone that GP can alter - if (Parser.Parse(&psDataPtr, true)) - { + char *psDataPtr = psStrippedText; // because ptr gets advanced, so we supply a clone that GP can alter + if (Parser.Parse(&psDataPtr, true)) { CGPGroup *pFileGroup = Parser.GetBaseParseGroup(); - if (pFileGroup) - { + if (pFileGroup) { CGPGroup *pgMusicFiles = pFileGroup->FindSubGroup(sKEY_MUSICFILES); - if (pgMusicFiles) - { + if (pgMusicFiles) { CGPGroup *pgLevelMusic = pFileGroup->FindSubGroup(sKEY_LEVELMUSIC); - if (pgLevelMusic) - { + if (pgLevelMusic) { CGPGroup *pgThisLevelMusic = NULL; // // check for new USE keyword... @@ -465,32 +433,25 @@ static qboolean Music_ParseLeveldata(const char *psLevelName) int iSanityLimit = 0; sstring_t sSearchName(sLevelName); - while (sSearchName.c_str()[0] && iSanityLimit < 10) - { - gsLevelNameForLoad = sSearchName; - gsLevelNameForBossLoad = sSearchName; + while (sSearchName.c_str()[0] && iSanityLimit < 10) { + gsLevelNameForLoad = sSearchName; + gsLevelNameForBossLoad = sSearchName; pgThisLevelMusic = pgLevelMusic->FindSubGroup(sSearchName.c_str()); - if (pgThisLevelMusic) - { + if (pgThisLevelMusic) { CGPValue *pValue = pgThisLevelMusic->FindPair(sKEY_USES); - if (pValue) - { + if (pValue) { // re-search using the USE param... // sSearchName = pValue->GetTopValue(); iSanityLimit++; -// Com_DPrintf("Using \"%s\"\n",sSearchName.c_str()); - } - else - { + // Com_DPrintf("Using \"%s\"\n",sSearchName.c_str()); + } else { // no new USE keyword found... // sSearchName = ""; } - } - else - { + } else { // level entry not found... // break; @@ -499,41 +460,29 @@ static qboolean Music_ParseLeveldata(const char *psLevelName) // now go ahead and use the final music set we've decided on... // - if (pgThisLevelMusic && iSanityLimit < 10) - { + if (pgThisLevelMusic && iSanityLimit < 10) { // these are optional fields, so see which ones we find... // const char *psName_Explore = NULL; - const char *psName_Action = NULL; - const char *psName_Boss = NULL; - //const char *psName_Death = NULL; + const char *psName_Action = NULL; + const char *psName_Boss = NULL; + // const char *psName_Death = NULL; // const char *psName_UseBoss = NULL; - for (CGPValue *pValue = pgThisLevelMusic->GetPairs(); pValue; pValue = pValue->GetNext()) - { - const char *psKey = pValue->GetName(); - const char *psValue = pValue->GetTopValue(); + for (CGPValue *pValue = pgThisLevelMusic->GetPairs(); pValue; pValue = pValue->GetNext()) { + const char *psKey = pValue->GetName(); + const char *psValue = pValue->GetTopValue(); - if (Q_stricmp(psValue,sKEY_PLACEHOLDER)) // ignore "placeholder" items + if (Q_stricmp(psValue, sKEY_PLACEHOLDER)) // ignore "placeholder" items { - if (!Q_stricmp(psKey,sKEY_EXPLORE)) - { + if (!Q_stricmp(psKey, sKEY_EXPLORE)) { psName_Explore = psValue; - } - else - if (!Q_stricmp(psKey,sKEY_ACTION)) - { - psName_Action = psValue; - } - else - if (!Q_stricmp(psKey,sKEY_USEBOSS)) - { + } else if (!Q_stricmp(psKey, sKEY_ACTION)) { + psName_Action = psValue; + } else if (!Q_stricmp(psKey, sKEY_USEBOSS)) { psName_UseBoss = psValue; - } - else - if (!Q_stricmp(psKey,sKEY_BOSS)) - { + } else if (!Q_stricmp(psKey, sKEY_BOSS)) { psName_Boss = psValue; } /*else @@ -544,153 +493,124 @@ static qboolean Music_ParseLeveldata(const char *psLevelName) } } - bReturn = qtrue; // defualt to ON now, so I can turn it off if "useboss" fails + bReturn = qtrue; // defualt to ON now, so I can turn it off if "useboss" fails - if (psName_UseBoss) - { + if (psName_UseBoss) { CGPGroup *pgLevelMusicOfBoss = pgLevelMusic->FindSubGroup(psName_UseBoss); - if (pgLevelMusicOfBoss) - { + if (pgLevelMusicOfBoss) { CGPValue *pValueBoss = pgLevelMusicOfBoss->FindPair(sKEY_BOSS); - if (pValueBoss) - { + if (pValueBoss) { psName_Boss = pValueBoss->GetTopValue(); gsLevelNameForBossLoad = psName_UseBoss; - } - else - { - MUSIC_PARSE_ERROR(va("'useboss' \"%s\" has no \"boss\" entry!\n",psName_UseBoss)); + } else { + MUSIC_PARSE_ERROR(va("'useboss' \"%s\" has no \"boss\" entry!\n", psName_UseBoss)); bReturn = qfalse; } - } - else - { - MUSIC_PARSE_ERROR(va("Unable to find 'useboss' entry \"%s\"\n",psName_UseBoss)); + } else { + MUSIC_PARSE_ERROR(va("Unable to find 'useboss' entry \"%s\"\n", psName_UseBoss)); bReturn = qfalse; } } - // done this way in case I want to conditionally pass any bools depending on music type... // - if (bReturn && psName_Explore) - { - bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Explore, sKEY_EXPLORE, eBGRNDTRACK_EXPLORE); + if (bReturn && psName_Explore) { + bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Explore, sKEY_EXPLORE, eBGRNDTRACK_EXPLORE); } - if (bReturn && psName_Action) - { - bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Action, sKEY_ACTION, eBGRNDTRACK_ACTION); + if (bReturn && psName_Action) { + bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Action, sKEY_ACTION, eBGRNDTRACK_ACTION); } - if (bReturn && psName_Boss) - { - bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Boss, sKEY_BOSS, eBGRNDTRACK_BOSS); + if (bReturn && psName_Boss) { + bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Boss, sKEY_BOSS, eBGRNDTRACK_BOSS); } - if (bReturn /*&& psName_Death*/) // LAST MINUTE HACK!!, always force in some death music!!!! + if (bReturn /*&& psName_Death*/) // LAST MINUTE HACK!!, always force in some death music!!!! { - //bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Death, sKEY_DEATH, eBGRNDTRACK_DEATH); + // bReturn = Music_ParseMusic(Parser, MusicData, pgMusicFiles, psName_Death, sKEY_DEATH, eBGRNDTRACK_DEATH); MusicFile_t m; - m.sFileNameBase = "death_music"; - (*MusicData)[ sKEY_DEATH ] = m; + m.sFileNameBase = "death_music"; + (*MusicData)[sKEY_DEATH] = m; } + } else { + MUSIC_PARSE_WARNING(va("Unable to find entry for \"%s\" in \"%s\"\n", sLevelName, sFILENAME_DMS)); } - else - { - MUSIC_PARSE_WARNING(va("Unable to find entry for \"%s\" in \"%s\"\n",sLevelName,sFILENAME_DMS)); - } + } else { + MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\"\n", sKEY_LEVELMUSIC)); } - else - { - MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\"\n",sKEY_LEVELMUSIC)); - } - } - else - { - MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\"\n",sKEY_MUSICFILES)); + } else { + MUSIC_PARSE_ERROR(va("Unable to find subgroup \"%s\"\n", sKEY_MUSICFILES)); } + } else { + MUSIC_PARSE_ERROR("Error calling GP2.GetBaseParseGroup()\n"); } - else - { - MUSIC_PARSE_ERROR( "Error calling GP2.GetBaseParseGroup()\n" ); - } - } - else - { - MUSIC_PARSE_ERROR( "Error using GP to parse file\n" ); + } else { + MUSIC_PARSE_ERROR("Error using GP to parse file\n"); } Z_Free(psStrippedText); - FS_FreeFile( pText ); - } - else - { - MUSIC_PARSE_ERROR( "Unable to even read main file\n" ); // file name specified in error message + FS_FreeFile(pText); + } else { + MUSIC_PARSE_ERROR("Unable to even read main file\n"); // file name specified in error message } - if (bReturn) - { + if (bReturn) { // sort exit points, and do some error checking... // - for (MusicData_t::iterator itMusicData = MusicData->begin(); itMusicData != MusicData->end(); ++itMusicData) - { - const char *psMusicStateType = (*itMusicData).first.c_str(); - MusicFile_t &MusicFile = (*itMusicData).second; + for (MusicData_t::iterator itMusicData = MusicData->begin(); itMusicData != MusicData->end(); ++itMusicData) { + const char *psMusicStateType = (*itMusicData).first.c_str(); + MusicFile_t &MusicFile = (*itMusicData).second; // kludge up an enum, only interested in boss or not at the moment, so... // - MusicState_e eMusicState = !Q_stricmp(psMusicStateType,"boss") ? eBGRNDTRACK_BOSS : !Q_stricmp(psMusicStateType,"death") ? eBGRNDTRACK_DEATH : eBGRNDTRACK_EXPLORE; + MusicState_e eMusicState = !Q_stricmp(psMusicStateType, "boss") ? eBGRNDTRACK_BOSS + : !Q_stricmp(psMusicStateType, "death") ? eBGRNDTRACK_DEATH + : eBGRNDTRACK_EXPLORE; - if (!MusicFile.MusicExitTimes.empty()) - { - sort(MusicFile.MusicExitTimes.begin(),MusicFile.MusicExitTimes.end()); + if (!MusicFile.MusicExitTimes.empty()) { + sort(MusicFile.MusicExitTimes.begin(), MusicFile.MusicExitTimes.end()); } // check music exists... // - const char *psMusicFileName = Music_BuildFileName( MusicFile.sFileNameBase.c_str(), eMusicState ); - if (!S_FileExists( psMusicFileName )) - { - MUSIC_PARSE_ERROR(va("Music file \"%s\" not found!\n",psMusicFileName)); - return qfalse; // have to return, because music data destroyed now + const char *psMusicFileName = Music_BuildFileName(MusicFile.sFileNameBase.c_str(), eMusicState); + if (!S_FileExists(psMusicFileName)) { + MUSIC_PARSE_ERROR(va("Music file \"%s\" not found!\n", psMusicFileName)); + return qfalse; // have to return, because music data destroyed now } // check all transition music pieces exist, and that entry points into new pieces after transitions also exist... // - for (size_t iExitPoint=0; iExitPoint < MusicFile.MusicExitPoints.size(); iExitPoint++) - { - MusicExitPoint_t &MusicExitPoint = MusicFile.MusicExitPoints[ iExitPoint ]; + for (size_t iExitPoint = 0; iExitPoint < MusicFile.MusicExitPoints.size(); iExitPoint++) { + MusicExitPoint_t &MusicExitPoint = MusicFile.MusicExitPoints[iExitPoint]; - const char *psTransitionFileName = Music_BuildFileName( MusicExitPoint.sNextFile.c_str(), eMusicState ); - if (!S_FileExists( psTransitionFileName )) - { - MUSIC_PARSE_ERROR(va("Transition file \"%s\" (entry \"%s\" ) not found!\n",psTransitionFileName, MusicExitPoint.sNextFile.c_str())); - return qfalse; // have to return, because music data destroyed now + const char *psTransitionFileName = Music_BuildFileName(MusicExitPoint.sNextFile.c_str(), eMusicState); + if (!S_FileExists(psTransitionFileName)) { + MUSIC_PARSE_ERROR(va("Transition file \"%s\" (entry \"%s\" ) not found!\n", psTransitionFileName, MusicExitPoint.sNextFile.c_str())); + return qfalse; // have to return, because music data destroyed now } const char *psNextMark = MusicExitPoint.sNextMark.c_str(); - if (strlen(psNextMark)) // always NZ ptr + if (strlen(psNextMark)) // always NZ ptr { // then this must be "action" music under current rules... // - assert( !strcmp(psMusicStateType, Music_BaseStateToString(eBGRNDTRACK_ACTION) ? Music_BaseStateToString(eBGRNDTRACK_ACTION):"") ); + assert(!strcmp(psMusicStateType, Music_BaseStateToString(eBGRNDTRACK_ACTION) ? Music_BaseStateToString(eBGRNDTRACK_ACTION) : "")); // // does this marker exist in the explore piece? // - MusicData_t::iterator itExploreMusicData = MusicData->find( Music_BaseStateToString(eBGRNDTRACK_EXPLORE) ); - if (itExploreMusicData != MusicData->end()) - { + MusicData_t::iterator itExploreMusicData = MusicData->find(Music_BaseStateToString(eBGRNDTRACK_EXPLORE)); + if (itExploreMusicData != MusicData->end()) { MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; - if (!MusicFile_Explore.MusicEntryTimes.count(psNextMark)) - { - MUSIC_PARSE_ERROR( va("Unable to find entry point \"%s\" in description for \"%s\"\n",psNextMark,MusicFile_Explore.sFileNameBase.c_str()) ); - return qfalse; // have to return, because music data destroyed now + if (!MusicFile_Explore.MusicEntryTimes.count(psNextMark)) { + MUSIC_PARSE_ERROR( + va("Unable to find entry point \"%s\" in description for \"%s\"\n", psNextMark, MusicFile_Explore.sFileNameBase.c_str())); + return qfalse; // have to return, because music data destroyed now } - } - else - { - MUSIC_PARSE_ERROR( va("Unable to find %s piece to match \"%s\"\n", Music_BaseStateToString(eBGRNDTRACK_EXPLORE), MusicFile.sFileNameBase.c_str() ) ); - return qfalse; // have to return, because music data destroyed now + } else { + MUSIC_PARSE_ERROR( + va("Unable to find %s piece to match \"%s\"\n", Music_BaseStateToString(eBGRNDTRACK_EXPLORE), MusicFile.sFileNameBase.c_str())); + return qfalse; // have to return, because music data destroyed now } } } @@ -745,14 +665,12 @@ static qboolean Music_ParseLeveldata(const char *psLevelName) return bReturn; } - // returns ptr to music file, or NULL for error/missing... // -static MusicFile_t *Music_GetBaseMusicFile( const char *psMusicState ) // where psMusicState is (eg) "explore", "action" or "boss" +static MusicFile_t *Music_GetBaseMusicFile(const char *psMusicState) // where psMusicState is (eg) "explore", "action" or "boss" { - MusicData_t::iterator it = MusicData->find( psMusicState ); - if (it != MusicData->end()) - { + MusicData_t::iterator it = MusicData->find(psMusicState); + if (it != MusicData->end()) { MusicFile_t *pMusicFile = &(*it).second; return pMusicFile; } @@ -760,109 +678,94 @@ static MusicFile_t *Music_GetBaseMusicFile( const char *psMusicState ) // where return NULL; } -static MusicFile_t *Music_GetBaseMusicFile( MusicState_e eMusicState ) -{ - const char *psMusicStateString = Music_BaseStateToString( eMusicState ); - if ( psMusicStateString ) - { - return Music_GetBaseMusicFile( psMusicStateString ); +static MusicFile_t *Music_GetBaseMusicFile(MusicState_e eMusicState) { + const char *psMusicStateString = Music_BaseStateToString(eMusicState); + if (psMusicStateString) { + return Music_GetBaseMusicFile(psMusicStateString); } return NULL; } - // where label is (eg) "kejim_base"... // -qboolean Music_DynamicDataAvailable(const char *psDynamicMusicLabel) -{ +qboolean Music_DynamicDataAvailable(const char *psDynamicMusicLabel) { char sLevelName[MAX_QPATH]; - Q_strncpyz(sLevelName,COM_SkipPath( const_cast( (psDynamicMusicLabel&&psDynamicMusicLabel[0])?psDynamicMusicLabel:gsLevelNameFromServer.c_str() ) ),sizeof(sLevelName)); + Q_strncpyz(sLevelName, + COM_SkipPath(const_cast((psDynamicMusicLabel && psDynamicMusicLabel[0]) ? psDynamicMusicLabel : gsLevelNameFromServer.c_str())), + sizeof(sLevelName)); std::string s = sLevelName; std::transform(s.begin(), s.end(), s.begin(), ::tolower); - if (strlen(sLevelName)) // avoid error messages when there's no music waiting to be played and we try and restart it... + if (strlen(sLevelName)) // avoid error messages when there's no music waiting to be played and we try and restart it... { - if (Music_ParseLeveldata(sLevelName)) - { - return (qboolean)(!!(Music_GetBaseMusicFile (eBGRNDTRACK_EXPLORE) && Music_GetBaseMusicFile (eBGRNDTRACK_ACTION))); + if (Music_ParseLeveldata(sLevelName)) { + return (qboolean)(!!(Music_GetBaseMusicFile(eBGRNDTRACK_EXPLORE) && Music_GetBaseMusicFile(eBGRNDTRACK_ACTION))); } } return qfalse; } -const char *Music_GetFileNameForState( MusicState_e eMusicState) -{ +const char *Music_GetFileNameForState(MusicState_e eMusicState) { MusicFile_t *pMusicFile = NULL; - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: - case eBGRNDTRACK_ACTION: - case eBGRNDTRACK_BOSS: - case eBGRNDTRACK_DEATH: - - pMusicFile = Music_GetBaseMusicFile( eMusicState ); - if (pMusicFile) - { - return Music_BuildFileName( pMusicFile->sFileNameBase.c_str(), eMusicState ); + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: + case eBGRNDTRACK_ACTION: + case eBGRNDTRACK_BOSS: + case eBGRNDTRACK_DEATH: + + pMusicFile = Music_GetBaseMusicFile(eMusicState); + if (pMusicFile) { + return Music_BuildFileName(pMusicFile->sFileNameBase.c_str(), eMusicState); + } + break; + + case eBGRNDTRACK_ACTIONTRANS0: + case eBGRNDTRACK_ACTIONTRANS1: + case eBGRNDTRACK_ACTIONTRANS2: + case eBGRNDTRACK_ACTIONTRANS3: + + pMusicFile = Music_GetBaseMusicFile(eBGRNDTRACK_ACTION); + if (pMusicFile) { + unsigned int iTransNum = eMusicState - eBGRNDTRACK_ACTIONTRANS0; + if (iTransNum < pMusicFile->MusicExitPoints.size()) { + return Music_BuildFileName(pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState); } - break; - - case eBGRNDTRACK_ACTIONTRANS0: - case eBGRNDTRACK_ACTIONTRANS1: - case eBGRNDTRACK_ACTIONTRANS2: - case eBGRNDTRACK_ACTIONTRANS3: - - pMusicFile = Music_GetBaseMusicFile( eBGRNDTRACK_ACTION ); - if (pMusicFile) - { - unsigned int iTransNum = eMusicState - eBGRNDTRACK_ACTIONTRANS0; - if (iTransNum < pMusicFile->MusicExitPoints.size()) - { - return Music_BuildFileName( pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState ); - } + } + break; + + case eBGRNDTRACK_EXPLORETRANS0: + case eBGRNDTRACK_EXPLORETRANS1: + case eBGRNDTRACK_EXPLORETRANS2: + case eBGRNDTRACK_EXPLORETRANS3: + + pMusicFile = Music_GetBaseMusicFile(eBGRNDTRACK_EXPLORE); + if (pMusicFile) { + unsigned int iTransNum = eMusicState - eBGRNDTRACK_EXPLORETRANS0; + if (iTransNum < pMusicFile->MusicExitPoints.size()) { + return Music_BuildFileName(pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState); } - break; - - case eBGRNDTRACK_EXPLORETRANS0: - case eBGRNDTRACK_EXPLORETRANS1: - case eBGRNDTRACK_EXPLORETRANS2: - case eBGRNDTRACK_EXPLORETRANS3: + } + break; - pMusicFile = Music_GetBaseMusicFile( eBGRNDTRACK_EXPLORE ); - if (pMusicFile) - { - unsigned int iTransNum = eMusicState - eBGRNDTRACK_EXPLORETRANS0; - if (iTransNum < pMusicFile->MusicExitPoints.size()) - { - return Music_BuildFileName( pMusicFile->MusicExitPoints[iTransNum].sNextFile.c_str(), eMusicState ); - } - } - break; - - default: - #ifndef FINAL_BUILD - assert(0); // duh....what state are they asking for? - Com_Printf( S_COLOR_RED "Music_GetFileNameForState( %d ) unhandled case!\n",eMusicState ); - #endif - break; + default: +#ifndef FINAL_BUILD + assert(0); // duh....what state are they asking for? + Com_Printf(S_COLOR_RED "Music_GetFileNameForState( %d ) unhandled case!\n", eMusicState); +#endif + break; } return NULL; } - - -qboolean Music_StateIsTransition( MusicState_e eMusicState ) -{ +qboolean Music_StateIsTransition(MusicState_e eMusicState) { return (qboolean)(eMusicState >= eBGRNDTRACK_FIRSTTRANSITION && eMusicState <= eBGRNDTRACK_LASTTRANSITION); } - -qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e eProposedMusicState ) -{ +qboolean Music_StateCanBeInterrupted(MusicState_e eMusicState, MusicState_e eProposedMusicState) { // death music can interrupt anything... // if (eProposedMusicState == eBGRNDTRACK_DEATH) @@ -870,8 +773,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // // ... and can't be interrupted once started...(though it will internally-switch to silence at the end, rather than loop) // - if (eMusicState == eBGRNDTRACK_DEATH) - { + if (eMusicState == eBGRNDTRACK_DEATH) { return qfalse; } @@ -882,8 +784,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // // ... and can't be interrupted once started... // - if (eMusicState == eBGRNDTRACK_BOSS) - { + if (eMusicState == eBGRNDTRACK_BOSS) { // ...except by silence (or death, but again, that's already handled above) // if (eProposedMusicState == eBGRNDTRACK_SILENCE) @@ -899,7 +800,7 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // nothing can interrupt a transition (after above filters)... // - if (Music_StateIsTransition( eMusicState )) + if (Music_StateIsTransition(eMusicState)) return qfalse; // current state is therefore interruptable... @@ -907,8 +808,6 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr return qtrue; } - - // returns qtrue if music is allowed to transition out of current state, based on current play position... // (doesn't bother returning final state after transition (eg action->transition->explore) becuase it's fairly obvious) // @@ -922,143 +821,119 @@ qboolean Music_StateCanBeInterrupted( MusicState_e eMusicState, MusicState_e ePr // enum of transition track to switch to // float time of entry point of new track *after* transition // -qboolean Music_AllowedToTransition( float fPlayingTimeElapsed, - MusicState_e eMusicState, - // - MusicState_e *peTransition /* = NULL */, - float *pfNewTrackEntryTime /* = NULL */ - ) -{ - const float fTimeEpsilon = 0.3f; // arb., how close we have to be to an exit point to take it. - // if set too high then music change is sloppy - // if set too low[/precise] then we might miss an exit if client fps is poor - - - MusicFile_t *pMusicFile = Music_GetBaseMusicFile( eMusicState ); - if (pMusicFile && !pMusicFile->MusicExitTimes.empty()) - { - MusicExitTime_t T; - T.fTime = fPlayingTimeElapsed; +qboolean Music_AllowedToTransition(float fPlayingTimeElapsed, MusicState_e eMusicState, + // + MusicState_e *peTransition /* = NULL */, float *pfNewTrackEntryTime /* = NULL */ +) { + const float fTimeEpsilon = 0.3f; // arb., how close we have to be to an exit point to take it. + // if set too high then music change is sloppy + // if set too low[/precise] then we might miss an exit if client fps is poor + + MusicFile_t *pMusicFile = Music_GetBaseMusicFile(eMusicState); + if (pMusicFile && !pMusicFile->MusicExitTimes.empty()) { + MusicExitTime_t T; + T.fTime = fPlayingTimeElapsed; // since a MusicExitTimes_t item is a sorted array, we can use the equal_range algorithm... // - std::pair itp = equal_range( pMusicFile->MusicExitTimes.begin(), pMusicFile->MusicExitTimes.end(), T); + std::pair itp = + equal_range(pMusicFile->MusicExitTimes.begin(), pMusicFile->MusicExitTimes.end(), T); if (itp.first != pMusicFile->MusicExitTimes.begin()) - itp.first--; // encompass the one before, in case we've just missed an exit point by < fTimeEpsilon - if (itp.second!= pMusicFile->MusicExitTimes.end()) - itp.second++; // increase range to one beyond, so we can do normal STL being/end looping below - for (MusicExitTimes_t::iterator it = itp.first; it != itp.second; ++it) - { + itp.first--; // encompass the one before, in case we've just missed an exit point by < fTimeEpsilon + if (itp.second != pMusicFile->MusicExitTimes.end()) + itp.second++; // increase range to one beyond, so we can do normal STL being/end looping below + for (MusicExitTimes_t::iterator it = itp.first; it != itp.second; ++it) { MusicExitTimes_t::iterator pExitTime = it; - if ( Q_fabs(pExitTime->fTime - fPlayingTimeElapsed) <= fTimeEpsilon ) - { + if (Q_fabs(pExitTime->fTime - fPlayingTimeElapsed) <= fTimeEpsilon) { // got an exit point!, work out feedback params... // int iExitPoint = pExitTime->iExitPoint; // // the two params to give back... // - MusicState_e eFeedBackTransition = eBGRNDTRACK_EXPLORETRANS0; // any old default - float fFeedBackNewTrackEntryTime = 0.0f; + MusicState_e eFeedBackTransition = eBGRNDTRACK_EXPLORETRANS0; // any old default + float fFeedBackNewTrackEntryTime = 0.0f; // // check legality in case of crap data... // - if ((unsigned)iExitPoint < pMusicFile->MusicExitPoints.size()) - { - MusicExitPoint_t &ExitPoint = pMusicFile->MusicExitPoints[ iExitPoint ]; + if ((unsigned)iExitPoint < pMusicFile->MusicExitPoints.size()) { + MusicExitPoint_t &ExitPoint = pMusicFile->MusicExitPoints[iExitPoint]; - switch (eMusicState) - { - case eBGRNDTRACK_EXPLORE: - { - assert(iExitPoint < iMAX_EXPLORE_TRANSITIONS); // already been checked, but sanity - assert(!ExitPoint.sNextMark.c_str()[0]); // simple error checking, but harmless if tripped. explore transitions go to silence, hence no entry time for [silence] state after transition + switch (eMusicState) { + case eBGRNDTRACK_EXPLORE: { + assert(iExitPoint < iMAX_EXPLORE_TRANSITIONS); // already been checked, but sanity + assert(!ExitPoint.sNextMark.c_str()[0]); // simple error checking, but harmless if tripped. explore transitions go to silence, hence no + // entry time for [silence] state after transition - eFeedBackTransition = (MusicState_e) (eBGRNDTRACK_EXPLORETRANS0 + iExitPoint); - } - break; + eFeedBackTransition = (MusicState_e)(eBGRNDTRACK_EXPLORETRANS0 + iExitPoint); + } break; - case eBGRNDTRACK_ACTION: - { - assert(iExitPoint < iMAX_ACTION_TRANSITIONS); // already been checked, but sanity + case eBGRNDTRACK_ACTION: { + assert(iExitPoint < iMAX_ACTION_TRANSITIONS); // already been checked, but sanity - // if there's an entry marker point defined... + // if there's an entry marker point defined... + // + if (ExitPoint.sNextMark.c_str()[0]) { + MusicData_t::iterator itExploreMusicData = MusicData->find(Music_BaseStateToString(eBGRNDTRACK_EXPLORE)); // - if (ExitPoint.sNextMark.c_str()[0]) - { - MusicData_t::iterator itExploreMusicData = MusicData->find( Music_BaseStateToString(eBGRNDTRACK_EXPLORE) ); + // find "explore" music... + // + if (itExploreMusicData != MusicData->end()) { + MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; // - // find "explore" music... + // find the entry marker within the music and read the time there... // - if (itExploreMusicData != MusicData->end()) - { - MusicFile_t &MusicFile_Explore = (*itExploreMusicData).second; - // - // find the entry marker within the music and read the time there... - // - MusicEntryTimes_t::iterator itEntryTime = MusicFile_Explore.MusicEntryTimes.find( ExitPoint.sNextMark.c_str() ); - if (itEntryTime != MusicFile_Explore.MusicEntryTimes.end()) - { - fFeedBackNewTrackEntryTime = (*itEntryTime).second; - eFeedBackTransition = (MusicState_e) (eBGRNDTRACK_ACTIONTRANS0 + iExitPoint); - } - else - { - #ifndef FINAL_BUILD - assert(0); // sanity, should have been caught elsewhere, but harmless to do this - Com_Printf( S_COLOR_RED "Music_AllowedToTransition() unable to find entry marker \"%s\" in \"%s\"",ExitPoint.sNextMark.c_str(), MusicFile_Explore.sFileNameBase.c_str()); - #endif - return qfalse; - } - } - else - { - #ifndef FINAL_BUILD - assert(0); // sanity, should have been caught elsewhere, but harmless to do this - Com_Printf( S_COLOR_RED "Music_AllowedToTransition() unable to find %s version of \"%s\"\n",Music_BaseStateToString(eBGRNDTRACK_EXPLORE), pMusicFile->sFileNameBase.c_str()); - #endif + MusicEntryTimes_t::iterator itEntryTime = MusicFile_Explore.MusicEntryTimes.find(ExitPoint.sNextMark.c_str()); + if (itEntryTime != MusicFile_Explore.MusicEntryTimes.end()) { + fFeedBackNewTrackEntryTime = (*itEntryTime).second; + eFeedBackTransition = (MusicState_e)(eBGRNDTRACK_ACTIONTRANS0 + iExitPoint); + } else { +#ifndef FINAL_BUILD + assert(0); // sanity, should have been caught elsewhere, but harmless to do this + Com_Printf(S_COLOR_RED "Music_AllowedToTransition() unable to find entry marker \"%s\" in \"%s\"", + ExitPoint.sNextMark.c_str(), MusicFile_Explore.sFileNameBase.c_str()); +#endif return qfalse; } + } else { +#ifndef FINAL_BUILD + assert(0); // sanity, should have been caught elsewhere, but harmless to do this + Com_Printf(S_COLOR_RED "Music_AllowedToTransition() unable to find %s version of \"%s\"\n", + Music_BaseStateToString(eBGRNDTRACK_EXPLORE), pMusicFile->sFileNameBase.c_str()); +#endif + return qfalse; } - else - { - eFeedBackTransition = eBGRNDTRACK_ACTIONTRANS0; - fFeedBackNewTrackEntryTime = 0.0f; // already set to this, but FYI - } - } - break; - - default: - { - #ifndef FINAL_BUILD - assert(0); - Com_Printf( S_COLOR_RED "Music_AllowedToTransition(): No code to transition from music type %d\n",eMusicState); - #endif - return qfalse; + } else { + eFeedBackTransition = eBGRNDTRACK_ACTIONTRANS0; + fFeedBackNewTrackEntryTime = 0.0f; // already set to this, but FYI } - break; + } break; + + default: { +#ifndef FINAL_BUILD + assert(0); + Com_Printf(S_COLOR_RED "Music_AllowedToTransition(): No code to transition from music type %d\n", eMusicState); +#endif + return qfalse; + } break; } - } - else - { - #ifndef FINAL_BUILD + } else { +#ifndef FINAL_BUILD assert(0); - Com_Printf( S_COLOR_RED "Music_AllowedToTransition(): Illegal exit point %d, max = %d (music: \"%s\")\n",iExitPoint, pMusicFile->MusicExitPoints.size()-1, pMusicFile->sFileNameBase.c_str() ); - #endif + Com_Printf(S_COLOR_RED "Music_AllowedToTransition(): Illegal exit point %d, max = %d (music: \"%s\")\n", iExitPoint, + pMusicFile->MusicExitPoints.size() - 1, pMusicFile->sFileNameBase.c_str()); +#endif return qfalse; } - // feed back answers... // - if ( peTransition) - { + if (peTransition) { *peTransition = eFeedBackTransition; } - if ( pfNewTrackEntryTime ) - { + if (pfNewTrackEntryTime) { *pfNewTrackEntryTime = fFeedBackNewTrackEntryTime; } @@ -1070,18 +945,15 @@ qboolean Music_AllowedToTransition( float fPlayingTimeElapsed, return qfalse; } - // typically used to get a (predefined) random entry point for the action music, but will work on any defined type with entry points, // defaults safely to 0.0f if no info available... // -float Music_GetRandomEntryTime( MusicState_e eMusicState ) -{ - MusicData_t::iterator itMusicData = MusicData->find( Music_BaseStateToString( eMusicState ) ); - if (itMusicData != MusicData->end()) - { +float Music_GetRandomEntryTime(MusicState_e eMusicState) { + MusicData_t::iterator itMusicData = MusicData->find(Music_BaseStateToString(eMusicState)); + if (itMusicData != MusicData->end()) { MusicFile_t &MusicFile = (*itMusicData).second; - if (MusicFile.MusicEntryTimes.size()) // make sure at least one defined, else default to start + if (MusicFile.MusicEntryTimes.size()) // make sure at least one defined, else default to start { // Quake's random number generator isn't very good, so instead of this: // @@ -1089,23 +961,20 @@ float Music_GetRandomEntryTime( MusicState_e eMusicState ) // // ... I'll do this (ensuring we don't get the same result on two consecutive calls, but without while-loop)... // - static int iPrevRandomNumber = -1; - static int iCallCount = 0; - iCallCount++; - int iRandomEntryNum = (rand()+iCallCount) % (MusicFile.MusicEntryTimes.size()); // legal range - if (iRandomEntryNum == iPrevRandomNumber && MusicFile.MusicEntryTimes.size()>1) - { + static int iPrevRandomNumber = -1; + static int iCallCount = 0; + iCallCount++; + int iRandomEntryNum = (rand() + iCallCount) % (MusicFile.MusicEntryTimes.size()); // legal range + if (iRandomEntryNum == iPrevRandomNumber && MusicFile.MusicEntryTimes.size() > 1) { iRandomEntryNum += 1; iRandomEntryNum %= (MusicFile.MusicEntryTimes.size()); } iPrevRandomNumber = iRandomEntryNum; -// Com_OPrintf("Music_GetRandomEntryTime(): Entry %d\n",iRandomEntryNum); + // Com_OPrintf("Music_GetRandomEntryTime(): Entry %d\n",iRandomEntryNum); - for (MusicEntryTimes_t::iterator itEntryTime = MusicFile.MusicEntryTimes.begin(); itEntryTime != MusicFile.MusicEntryTimes.end(); ++itEntryTime) - { - if (!iRandomEntryNum--) - { + for (MusicEntryTimes_t::iterator itEntryTime = MusicFile.MusicEntryTimes.begin(); itEntryTime != MusicFile.MusicEntryTimes.end(); ++itEntryTime) { + if (!iRandomEntryNum--) { return (*itEntryTime).second; } } @@ -1117,17 +986,14 @@ float Music_GetRandomEntryTime( MusicState_e eMusicState ) // info only, used in "soundinfo" command... // -const char *Music_GetLevelSetName(void) -{ - if (Q_stricmp(gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str())) - { +const char *Music_GetLevelSetName(void) { + if (Q_stricmp(gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str())) { // music remap via USES command... // - return va("%s -> %s",gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str()); + return va("%s -> %s", gsLevelNameForCompare.c_str(), gsLevelNameForLoad.c_str()); } return gsLevelNameForLoad.c_str(); } ///////////////// eof ///////////////////// - diff --git a/codemp/game/AnimalNPC.c b/codemp/game/AnimalNPC.c index 8eaec59174..f6d1afc63f 100644 --- a/codemp/game/AnimalNPC.c +++ b/codemp/game/AnimalNPC.c @@ -20,109 +20,101 @@ along with this program; if not, see . =========================================================================== */ -#ifdef _GAME //including game headers on cgame is FORBIDDEN ^_^ - #include "g_local.h" +#ifdef _GAME // including game headers on cgame is FORBIDDEN ^_^ +#include "g_local.h" #endif #include "bg_public.h" #include "bg_vehicles.h" -#ifdef _GAME //we only want a few of these functions for BG +#ifdef _GAME // we only want a few of these functions for BG -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); extern vec3_t playerMins; extern vec3_t playerMaxs; -extern int PM_AnimLength( int index, animNumber_t anim ); +extern int PM_AnimLength(int index, animNumber_t anim); -extern void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); +extern void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); // Update death sequence. -static void DeathUpdate( Vehicle_t *pVeh ) -{ - if ( level.time >= pVeh->m_iDieTime ) - { +static void DeathUpdate(Vehicle_t *pVeh) { + if (level.time >= pVeh->m_iDieTime) { // If the vehicle is not empty. - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); - } - else - { + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); + } else { // Waste this sucker. } // Die now... -/* else - { - vec3_t mins, maxs, bottom; - trace_t trace; - - if ( pVeh->m_pVehicleInfo->explodeFX ) - { - G_PlayEffect( pVeh->m_pVehicleInfo->explodeFX, parent->currentOrigin ); - //trace down and place mark - VectorCopy( parent->currentOrigin, bottom ); - bottom[2] -= 80; - trap->trace( &trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); - if ( trace.fraction < 1.0f ) + /* else { - VectorCopy( trace.endpos, bottom ); - bottom[2] += 2; - G_PlayEffect( "ships/ship_explosion_mark", trace.endpos ); - } - } - - parent->takedamage = qfalse;//so we don't recursively damage ourselves - if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) - { - VectorCopy( parent->mins, mins ); - mins[2] = -4;//to keep it off the ground a *little* - VectorCopy( parent->maxs, maxs ); - VectorCopy( parent->currentOrigin, bottom ); - bottom[2] += parent->mins[2] - 32; - trap->trace( &trace, parent->currentOrigin, mins, maxs, bottom, parent->s.number, CONTENTS_SOLID ); - G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, MOD_EXPLOSIVE );//FIXME: extern damage and radius or base on fuel - } - - parent->e_ThinkFunc = thinkF_G_FreeEntity; - parent->nextthink = level.time + FRAMETIME; - }*/ + vec3_t mins, maxs, bottom; + trace_t trace; + + if ( pVeh->m_pVehicleInfo->explodeFX ) + { + G_PlayEffect( pVeh->m_pVehicleInfo->explodeFX, parent->currentOrigin ); + //trace down and place mark + VectorCopy( parent->currentOrigin, bottom ); + bottom[2] -= 80; + trap->trace( &trace, parent->currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); + if ( trace.fraction < 1.0f ) + { + VectorCopy( trace.endpos, bottom ); + bottom[2] += 2; + G_PlayEffect( "ships/ship_explosion_mark", trace.endpos ); + } + } + + parent->takedamage = qfalse;//so we don't recursively damage ourselves + if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) + { + VectorCopy( parent->mins, mins ); + mins[2] = -4;//to keep it off the ground a *little* + VectorCopy( parent->maxs, maxs ); + VectorCopy( parent->currentOrigin, bottom ); + bottom[2] += parent->mins[2] - 32; + trap->trace( &trace, parent->currentOrigin, mins, maxs, bottom, parent->s.number, CONTENTS_SOLID ); + G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, MOD_EXPLOSIVE + );//FIXME: extern damage and radius or base on fuel + } + + parent->e_ThinkFunc = thinkF_G_FreeEntity; + parent->nextthink = level.time + FRAMETIME; + }*/ } } // Like a think or move command, this updates various vehicle properties. -static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ - return g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ); -} +static qboolean Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { return g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd); } #endif //_GAME -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations + // Client sets ucmds and such for speed alterations float speedInc, speedIdleDec, speedIdle, speedMin, speedMax; float fWalkSpeedMax; - int curTime; + int curTime; bgEntity_t *parent = pVeh->m_pParentEntity; playerState_t *parentPS = parent->playerState; #ifdef _GAME curTime = level.time; #elif defined(_CGAME) - //FIXME: pass in ucmd? Not sure if this is reliable... + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif @@ -130,90 +122,63 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedMax = pVeh->m_pVehicleInfo->speedMax; speedIdle = pVeh->m_pVehicleInfo->speedIdle; -// speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; + // speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; - - - if ( pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && - (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && pVeh->m_pVehicleInfo->turboSpeed ) - { - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if (pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && + pVeh->m_pVehicleInfo->turboSpeed) { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); - parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed + parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed } } - if ( curTime < pVeh->m_iTurboTime ) - { + if (curTime < pVeh->m_iTurboTime) { speedMax = pVeh->m_pVehicleInfo->turboSpeed; - } - else - { + } else { speedMax = pVeh->m_pVehicleInfo->speedMax; } - if ( !parentPS->m_iVehicleNum ) - {//drifts to a stop + if (!parentPS->m_iVehicleNum) { // drifts to a stop speedInc = speedIdle * pVeh->m_fTimeModifier; - VectorClear( parentPS->moveDir ); - //m_ucmd.forwardmove = 127; + VectorClear(parentPS->moveDir); + // m_ucmd.forwardmove = 127; parentPS->speed = 0; - } - else - { + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } - //pVeh->m_ucmd.rightmove = 0; + // pVeh->m_ucmd.rightmove = 0; /*if ( !pVeh->m_pVehicleInfo->strafePerc || (!g_speederControlScheme->value && !parent->s.number) ) @@ -223,16 +188,11 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) } fWalkSpeedMax = speedMax * 0.275f; - if ( curTime>pVeh->m_iTurboTime && (pVeh->m_ucmd.buttons & BUTTON_WALKING) && parentPS->speed > fWalkSpeedMax ) - { + if (curTime > pVeh->m_iTurboTime && (pVeh->m_ucmd.buttons & BUTTON_WALKING) && parentPS->speed > fWalkSpeedMax) { parentPS->speed = fWalkSpeedMax; - } - else if ( parentPS->speed > speedMax ) - { + } else if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } @@ -241,15 +201,14 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -257,110 +216,94 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) playerState_t *parentPS, *riderPS; bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } - if ( !rider ) - { + if (!rider) { rider = parent; } - - parentPS = parent->playerState; - if (rider) - { + if (rider) { float angDif; riderPS = rider->playerState; angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*4.0f; //magic number hackery - if (s < 0.0f) - { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 4.0f; // magic number hackery + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } + /* speed = VectorLength( parentPS->velocity ); -/* speed = VectorLength( parentPS->velocity ); - - // If the player is the rider... - if ( rider->s.number < MAX_CLIENTS ) - {//FIXME: use the vehicle's turning stat in this calc - pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; - } - else - { - float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; - if ( !pVeh->m_pVehicleInfo->turnWhenStopped - && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? - {//can't turn when not moving - //FIXME: or ramp up to max turnSpeed? - turnSpeed = 0.0f; + // If the player is the rider... + if ( rider->s.number < MAX_CLIENTS ) + {//FIXME: use the vehicle's turning stat in this calc + pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; } - if (rider->s.eType == ET_NPC) - {//help NPCs out some - turnSpeed *= 2.0f; - if (parentPS->speed > 200.0f) - { - turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + else + { + float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; + if ( !pVeh->m_pVehicleInfo->turnWhenStopped + && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? + {//can't turn when not moving + //FIXME: or ramp up to max turnSpeed? + turnSpeed = 0.0f; } - } - turnSpeed *= pVeh->m_fTimeModifier; + if (rider->s.eType == ET_NPC) + {//help NPCs out some + turnSpeed *= 2.0f; + if (parentPS->speed > 200.0f) + { + turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + } + } + turnSpeed *= pVeh->m_fTimeModifier; - //default control scheme: strafing turns, mouselook aims - if ( pVeh->m_ucmd.rightmove < 0 ) - { - pVeh->m_vOrientation[YAW] += turnSpeed; - } - else if ( pVeh->m_ucmd.rightmove > 0 ) - { - pVeh->m_vOrientation[YAW] -= turnSpeed; - } + //default control scheme: strafing turns, mouselook aims + if ( pVeh->m_ucmd.rightmove < 0 ) + { + pVeh->m_vOrientation[YAW] += turnSpeed; + } + else if ( pVeh->m_ucmd.rightmove > 0 ) + { + pVeh->m_vOrientation[YAW] -= turnSpeed; + } - if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) - {//damaged badly - } - }*/ + if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) + {//damaged badly + } + }*/ /********************************************************************************/ /* END Here is where make sure the vehicle is properly oriented. END */ /********************************************************************************/ } -void AnimalProcessOri(Vehicle_t *pVeh) -{ - ProcessOrientCommands(pVeh); -} +void AnimalProcessOri(Vehicle_t *pVeh) { ProcessOrientCommands(pVeh); } -#ifdef _GAME //back to our game-only functions -static void AnimateVehicle( Vehicle_t *pVeh ) -{ - animNumber_t Anim = BOTH_VT_IDLE; - int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; - gentity_t * pilot = (gentity_t *)pVeh->m_pPilot; - gentity_t * parent = (gentity_t *)pVeh->m_pParentEntity; - float fSpeedPercToMax; +#ifdef _GAME // back to our game-only functions +static void AnimateVehicle(Vehicle_t *pVeh) { + animNumber_t Anim = BOTH_VT_IDLE; + int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; + gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; + gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; + float fSpeedPercToMax; // We're dead (boarding is reused here so I don't have to make another variable :-). - if ( parent->health <= 0 ) - { + if (parent->health <= 0) { /* if ( pVeh->m_iBoarding != -999 ) // Animate the death just once! { @@ -375,115 +318,91 @@ static void AnimateVehicle( Vehicle_t *pVeh ) } // If they're bucking, play the animation and leave... - if ( parent->client->ps.legsAnim == BOTH_VT_BUCK ) - { + if (parent->client->ps.legsAnim == BOTH_VT_BUCK) { // Done with animation? Erase the flag. - if ( parent->client->ps.legsTimer <= 0 ) - { + if (parent->client->ps.legsTimer <= 0) { pVeh->m_ulFlags &= ~VEH_BUCKING; - } - else - { + } else { return; } - } - else if ( pVeh->m_ulFlags & VEH_BUCKING ) - { + } else if (pVeh->m_ulFlags & VEH_BUCKING) { iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; Anim = BOTH_VT_BUCK; iBlend = 500; - Vehicle_SetAnim( parent, SETANIM_LEGS, BOTH_VT_BUCK, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, BOTH_VT_BUCK, iFlags, iBlend); return; } // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { // We've just started boarding, set the amount of time it will take to finish boarding. - if ( pVeh->m_iBoarding < 0 ) - { + if (pVeh->m_iBoarding < 0) { int iAnimLen; // Boarding from left... - if ( pVeh->m_iBoarding == -1 ) - { + if (pVeh->m_iBoarding == -1) { Anim = BOTH_VT_MOUNT_L; - } - else if ( pVeh->m_iBoarding == -2 ) - { + } else if (pVeh->m_iBoarding == -2) { Anim = BOTH_VT_MOUNT_R; - } - else if ( pVeh->m_iBoarding == -3 ) - { + } else if (pVeh->m_iBoarding == -3) { Anim = BOTH_VT_MOUNT_B; } // Set the delay time (which happens to be the time it takes for the animation to complete). // NOTE: Here I made it so the delay is actually 70% (0.7f) of the animation time. - iAnimLen = BG_AnimLength( parent->localAnimIndex, Anim ) * 0.7f; + iAnimLen = BG_AnimLength(parent->localAnimIndex, Anim) * 0.7f; pVeh->m_iBoarding = level.time + iAnimLen; // Set the animation, which won't be interrupted until it's completed. // TODO: But what if he's killed? Should the animation remain persistant??? iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); - if (pilot) - { - Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); + if (pilot) { + Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend); } return; } // Otherwise we're done. - else if ( pVeh->m_iBoarding <= level.time ) - { + else if (pVeh->m_iBoarding <= level.time) { pVeh->m_iBoarding = 0; } } // Percentage of maximum speed relative to current speed. - //float fSpeed = VectorLength( client->ps.velocity ); + // float fSpeed = VectorLength( client->ps.velocity ); fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; - // Going in reverse... - if ( fSpeedPercToMax < -0.01f ) - { + if (fSpeedPercToMax < -0.01f) { Anim = BOTH_VT_WALK_REV; iBlend = 600; - } - else - { - qboolean Turbo = (fSpeedPercToMax>0.0f && level.timem_iTurboTime); - qboolean Walking = (fSpeedPercToMax>0.0f && ((pVeh->m_ucmd.buttons&BUTTON_WALKING) || fSpeedPercToMax<=0.275f)); - qboolean Running = (fSpeedPercToMax>0.275f); - + } else { + qboolean Turbo = (fSpeedPercToMax > 0.0f && level.time < pVeh->m_iTurboTime); + qboolean Walking = (fSpeedPercToMax > 0.0f && ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax <= 0.275f)); + qboolean Running = (fSpeedPercToMax > 0.275f); // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - if (Turbo) - {// Kicked In Turbo - iBlend = 50; - iFlags = SETANIM_FLAG_OVERRIDE; - Anim = BOTH_VT_TURBO; - } - else - {// No Special Moves - iBlend = 300; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - Anim = (Walking)?(BOTH_VT_WALK_FWD ):((Running)?(BOTH_VT_RUN_FWD ):(BOTH_VT_IDLE1)); + if (Turbo) { // Kicked In Turbo + iBlend = 50; + iFlags = SETANIM_FLAG_OVERRIDE; + Anim = BOTH_VT_TURBO; + } else { // No Special Moves + iBlend = 300; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + Anim = (Walking) ? (BOTH_VT_WALK_FWD) : ((Running) ? (BOTH_VT_RUN_FWD) : (BOTH_VT_IDLE1)); } } - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); } -//rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful -//and lagged -// This function makes sure that the rider's in this vehicle are properly animated. -static void AnimateRiders( Vehicle_t *pVeh ) -{ +// rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful +// and lagged +// This function makes sure that the rider's in this vehicle are properly animated. +static void AnimateRiders(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_VT_IDLE; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 500; gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; @@ -494,8 +413,7 @@ static void AnimateRiders( Vehicle_t *pVeh ) pilotPS = pVeh->m_pPilot->playerState; // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { return; } @@ -503,188 +421,174 @@ static void AnimateRiders( Vehicle_t *pVeh ) fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; // Going in reverse... - if (0) - { + if (0) { Anim = BOTH_VT_WALK_REV; iBlend = 600; - } - else - { - qboolean HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - qboolean Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons&BUTTON_ATTACK)); - qboolean Right = (pVeh->m_ucmd.rightmove>0); - qboolean Left = (pVeh->m_ucmd.rightmove<0); - qboolean Turbo = (fSpeedPercToMax>0.0f && level.timem_iTurboTime); - qboolean Walking = (fSpeedPercToMax>0.0f && ((pVeh->m_ucmd.buttons&BUTTON_WALKING) || fSpeedPercToMax<=0.275f)); - qboolean Running = (fSpeedPercToMax>0.275f); - EWeaponPose WeaponPose = WPOSE_NONE; - + } else { + qboolean HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + qboolean Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons & BUTTON_ATTACK)); + qboolean Right = (pVeh->m_ucmd.rightmove > 0); + qboolean Left = (pVeh->m_ucmd.rightmove < 0); + qboolean Turbo = (fSpeedPercToMax > 0.0f && level.time < pVeh->m_iTurboTime); + qboolean Walking = (fSpeedPercToMax > 0.0f && ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax <= 0.275f)); + qboolean Running = (fSpeedPercToMax > 0.275f); + EWeaponPose WeaponPose = WPOSE_NONE; // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - // Put Away Saber When It Is Not Active //-------------------------------------- // Don't Interrupt Attack Anims //------------------------------ - if (pilotPS->weaponTime>0) - { + if (pilotPS->weaponTime > 0) { return; } // Compute The Weapon Pose //-------------------------- - if (pilotPS->weapon==WP_BLASTER) - { + if (pilotPS->weapon == WP_BLASTER) { WeaponPose = WPOSE_BLASTER; - } - else if (pilotPS->weapon==WP_SABER) - { - if ( (pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VT_ATL_TO_R_S) - { - pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; + } else if (pilotPS->weapon == WP_SABER) { + if ((pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VT_ATL_TO_R_S) { + pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; } - if (!(pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VT_ATR_TO_L_S) - { - pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; + if (!(pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VT_ATR_TO_L_S) { + pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; } - WeaponPose = (pVeh->m_ulFlags&VEH_SABERINLEFTHAND)?(WPOSE_SABERLEFT):(WPOSE_SABERRIGHT); + WeaponPose = (pVeh->m_ulFlags & VEH_SABERINLEFTHAND) ? (WPOSE_SABERLEFT) : (WPOSE_SABERRIGHT); } + if (Attacking && WeaponPose) { // Attack! + iBlend = 100; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART; - if (Attacking && WeaponPose) - {// Attack! - iBlend = 100; - iFlags = SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART; - - if (Turbo) - { + if (Turbo) { Right = qtrue; Left = qfalse; } // Auto Aiming //=============================================== - if (!Left && !Right) // Allow player strafe keys to override + if (!Left && !Right) // Allow player strafe keys to override { - if (pilotPS->weapon==WP_SABER && !Left && !Right) - { - Left = (WeaponPose==WPOSE_SABERLEFT); - Right = !Left; + if (pilotPS->weapon == WP_SABER && !Left && !Right) { + Left = (WeaponPose == WPOSE_SABERLEFT); + Right = !Left; } } - - if (Left) - {// Attack Left - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_ATL_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_ATR_TO_L_S; break; - default: assert(0); + if (Left) { // Attack Left + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_ATL_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_ATR_TO_L_S; + break; + default: + assert(0); } - } - else if (Right) - {// Attack Right - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_ATL_TO_R_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_ATR_S; break; - default: assert(0); + } else if (Right) { // Attack Right + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_ATL_TO_R_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_ATR_S; + break; + default: + assert(0); } - } - else - {// Attack Ahead - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_ATF_G; break; - default: assert(0); + } else { // Attack Ahead + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_ATF_G; + break; + default: + assert(0); } } - } - else if (Turbo) - {// Kicked In Turbo - iBlend = 50; - iFlags = SETANIM_FLAG_OVERRIDE; - Anim = BOTH_VT_TURBO; - } - else - {// No Special Moves - iBlend = 300; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - if (WeaponPose==WPOSE_NONE) - { - if (Walking) - { + } else if (Turbo) { // Kicked In Turbo + iBlend = 50; + iFlags = SETANIM_FLAG_OVERRIDE; + Anim = BOTH_VT_TURBO; + } else { // No Special Moves + iBlend = 300; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + if (WeaponPose == WPOSE_NONE) { + if (Walking) { Anim = BOTH_VT_WALK_FWD; - } - else if (Running) - { + } else if (Running) { Anim = BOTH_VT_RUN_FWD; + } else { + Anim = BOTH_VT_IDLE1; //(Q_irand(0,1)==0)?(BOTH_VT_IDLE):(BOTH_VT_IDLE1); } - else - { - Anim = BOTH_VT_IDLE1;//(Q_irand(0,1)==0)?(BOTH_VT_IDLE):(BOTH_VT_IDLE1); - } - } - else - { - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VT_IDLE_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VT_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VT_IDLE_SR; break; - default: assert(0); + } else { + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VT_IDLE_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VT_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VT_IDLE_SR; + break; + default: + assert(0); } } - }// No Special Moves + } // No Special Moves } - Vehicle_SetAnim( pilot, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(pilot, SETANIM_BOTH, Anim, iFlags, iBlend); } #endif //_GAME #ifdef _CGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -//on the client this function will only set up the process command funcs -void G_SetAnimalVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +// on the client this function will only set up the process command funcs +void G_SetAnimalVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef _GAME - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; -// pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; - pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + // pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; #endif //_GAME - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifdef _CGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifdef _CGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } #ifdef _GAME @@ -692,21 +596,19 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -//this is a BG function too in MP so don't un-bg-compatibilify it -rww -void G_CreateAnimalNPC( Vehicle_t **pVeh, const char *strAnimalType ) -{ +// this is a BG function too in MP so don't un-bg-compatibilify it -rww +void G_CreateAnimalNPC(Vehicle_t **pVeh, const char *strAnimalType) { // Allocate the Vehicle. #ifdef _GAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; } diff --git a/codemp/game/FighterNPC.c b/codemp/game/FighterNPC.c index db2bf74c48..63e9a4c2f1 100644 --- a/codemp/game/FighterNPC.c +++ b/codemp/game/FighterNPC.c @@ -24,64 +24,56 @@ along with this program; if not, see . #include "bg_vehicles.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #endif -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -#ifdef _GAME //SP or gameside MP - extern vmCvar_t cg_thirdPersonAlpha; - extern vec3_t playerMins; - extern vec3_t playerMaxs; - extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - extern int PM_AnimLength( int index, animNumber_t anim ); - extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +#ifdef _GAME // SP or gameside MP +extern vmCvar_t cg_thirdPersonAlpha; +extern vec3_t playerMins; +extern vec3_t playerMaxs; +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); #endif -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags); +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags); extern int BG_GetTime(void); -//this stuff has got to be predicted, so.. -qboolean BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins, vec3_t trMaxs, float gravity, void (*traceFunc)( trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, int passEntityNum, int contentMask )) -{ - vec3_t bottom; +// this stuff has got to be predicted, so.. +qboolean BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins, vec3_t trMaxs, float gravity, + void (*traceFunc)(trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, int passEntityNum, + int contentMask)) { + vec3_t bottom; playerState_t *parentPS; - //qboolean isDead = qfalse; -#ifdef _GAME //don't do this on client + // qboolean isDead = qfalse; +#ifdef _GAME // don't do this on client int i; // Make sure the riders are not visible or collidable. - pVeh->m_pVehicleInfo->Ghost( pVeh, pVeh->m_pPilot ); - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - pVeh->m_pVehicleInfo->Ghost( pVeh, pVeh->m_ppPassengers[i] ); + pVeh->m_pVehicleInfo->Ghost(pVeh, pVeh->m_pPilot); + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + pVeh->m_pVehicleInfo->Ghost(pVeh, pVeh->m_ppPassengers[i]); } #endif - parentPS = pVeh->m_pParentEntity->playerState; - if (!parentPS) - { + if (!parentPS) { Com_Error(ERR_DROP, "NULL PS in BG_FighterUpdate (%s)", pVeh->m_pVehicleInfo->name); return qfalse; } // If we have a pilot, take out gravity (it's a flying craft...). - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { parentPS->gravity = 0; - } - else - { - if (pVeh->m_pVehicleInfo->gravity) - { + } else { + if (pVeh->m_pVehicleInfo->gravity) { parentPS->gravity = pVeh->m_pVehicleInfo->gravity; - } - else - { //it doesn't have gravity specified apparently + } else { // it doesn't have gravity specified apparently parentPS->gravity = gravity; } } @@ -102,34 +94,29 @@ qboolean BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins else { */ - //argh, no, I need to have a way to see when they impact the ground while damaged. -rww + // argh, no, I need to have a way to see when they impact the ground while damaged. -rww - // Check to see if the fighter has taken off yet (if it's a certain height above ground). - VectorCopy( parentPS->origin, bottom ); - bottom[2] -= pVeh->m_pVehicleInfo->landingHeight; + // Check to see if the fighter has taken off yet (if it's a certain height above ground). + VectorCopy(parentPS->origin, bottom); + bottom[2] -= pVeh->m_pVehicleInfo->landingHeight; - traceFunc( &pVeh->m_LandTrace, parentPS->origin, trMins, trMaxs, bottom, pVeh->m_pParentEntity->s.number, (MASK_NPCSOLID&~CONTENTS_BODY) ); + traceFunc(&pVeh->m_LandTrace, parentPS->origin, trMins, trMaxs, bottom, pVeh->m_pParentEntity->s.number, (MASK_NPCSOLID & ~CONTENTS_BODY)); //} return qtrue; } -#ifdef _GAME //ONLY in SP or on server, not cgame +#ifdef _GAME // ONLY in SP or on server, not cgame // Like a think or move command, this updates various vehicle properties. -static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ +static qboolean Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { assert(pVeh->m_pParentEntity); - if (!BG_FighterUpdate(pVeh, pUcmd, ((gentity_t *)pVeh->m_pParentEntity)->r.mins, - ((gentity_t *)pVeh->m_pParentEntity)->r.maxs, - g_gravity.value, - G_VehicleTrace)) - { + if (!BG_FighterUpdate(pVeh, pUcmd, ((gentity_t *)pVeh->m_pParentEntity)->r.mins, ((gentity_t *)pVeh->m_pParentEntity)->r.maxs, g_gravity.value, + G_VehicleTrace)) { return qfalse; } - if ( !g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ) ) - { + if (!g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd)) { return qfalse; } @@ -137,9 +124,8 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) } // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -static qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Board( pVeh, pEnt ) ) +static qboolean Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { + if (!g_vehicleInfo[VEHICLE_BASE].Board(pVeh, pEnt)) return qfalse; // Set the board wait time (they won't be able to do anything, including getting off, for this amount of time). @@ -149,50 +135,40 @@ static qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) } // Eject an entity from the vehicle. -static qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) -{ - if ( g_vehicleInfo[VEHICLE_BASE].Eject( pVeh, pEnt, forceEject ) ) - { +static qboolean Eject(Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject) { + if (g_vehicleInfo[VEHICLE_BASE].Eject(pVeh, pEnt, forceEject)) { return qtrue; } return qfalse; } -#endif //end game-side only +#endif // end game-side only -//method of decrementing the given angle based on the given taking variable frame times into account -static float PredictedAngularDecrement(float scale, float timeMod, float originalAngle) -{ - float fixedBaseDec = originalAngle*0.05f; +// method of decrementing the given angle based on the given taking variable frame times into account +static float PredictedAngularDecrement(float scale, float timeMod, float originalAngle) { + float fixedBaseDec = originalAngle * 0.05f; float r = 0.0f; - if (fixedBaseDec < 0.0f) - { + if (fixedBaseDec < 0.0f) { fixedBaseDec = -fixedBaseDec; } - fixedBaseDec *= (1.0f+(1.0f-scale)); + fixedBaseDec *= (1.0f + (1.0f - scale)); - if (fixedBaseDec < 0.1f) - { //don't increment in incredibly small fractions, it would eat up unnecessary bandwidth. + if (fixedBaseDec < 0.1f) { // don't increment in incredibly small fractions, it would eat up unnecessary bandwidth. fixedBaseDec = 0.1f; } - fixedBaseDec *= (timeMod*0.1f); - if (originalAngle > 0.0f) - { //subtract - r = (originalAngle-fixedBaseDec); - if (r < 0.0f) - { + fixedBaseDec *= (timeMod * 0.1f); + if (originalAngle > 0.0f) { // subtract + r = (originalAngle - fixedBaseDec); + if (r < 0.0f) { r = 0.0f; } - } - else if (originalAngle < 0.0f) - { //add - r = (originalAngle+fixedBaseDec); - if (r > 0.0f) - { + } else if (originalAngle < 0.0f) { // add + r = (originalAngle + fixedBaseDec); + if (r > 0.0f) { r = 0.0f; } } @@ -200,79 +176,67 @@ static float PredictedAngularDecrement(float scale, float timeMod, float origina return r; } -#ifdef _GAME//only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver -qboolean FighterIsInSpace( gentity_t *gParent ) -{ - if ( gParent - && gParent->client - && gParent->client->inSpaceIndex - && gParent->client->inSpaceIndex < ENTITYNUM_WORLD ) - { +#ifdef _GAME // only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver +qboolean FighterIsInSpace(gentity_t *gParent) { + if (gParent && gParent->client && gParent->client->inSpaceIndex && gParent->client->inSpaceIndex < ENTITYNUM_WORLD) { return qtrue; } return qfalse; } #endif -qboolean FighterOverValidLandingSurface( Vehicle_t *pVeh ) -{ - if ( pVeh->m_LandTrace.fraction < 1.0f //ground present - && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE )//flat enough - //FIXME: also check for a certain surface flag ... "landing zones"? +qboolean FighterOverValidLandingSurface(Vehicle_t *pVeh) { + if (pVeh->m_LandTrace.fraction < 1.0f // ground present + && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE) // flat enough + // FIXME: also check for a certain surface flag ... "landing zones"? { return qtrue; } return qfalse; } -qboolean FighterIsLanded( Vehicle_t *pVeh, playerState_t *parentPS ) -{ - if ( FighterOverValidLandingSurface( pVeh ) - && !parentPS->speed )//stopped +qboolean FighterIsLanded(Vehicle_t *pVeh, playerState_t *parentPS) { + if (FighterOverValidLandingSurface(pVeh) && !parentPS->speed) // stopped { return qtrue; } return qfalse; } -qboolean FighterIsLanding( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +qboolean FighterIsLanding(Vehicle_t *pVeh, playerState_t *parentPS) { - if ( FighterOverValidLandingSurface( pVeh ) -#ifdef _GAME//only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing + if (FighterOverValidLandingSurface(pVeh) +#ifdef _GAME // only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing #endif - && (pVeh->m_ucmd.forwardmove < 0||pVeh->m_ucmd.upmove<0) //decelerating or holding crouch button - && parentPS->speed <= MIN_LANDING_SPEED )//going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast + && (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0) // decelerating or holding crouch button + && parentPS->speed <= MIN_LANDING_SPEED) // going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast { return qtrue; } return qfalse; } -qboolean FighterIsLaunching( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +qboolean FighterIsLaunching(Vehicle_t *pVeh, playerState_t *parentPS) { - if ( FighterOverValidLandingSurface( pVeh ) -#ifdef _GAME//only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing + if (FighterOverValidLandingSurface(pVeh) +#ifdef _GAME // only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing #endif - && pVeh->m_ucmd.upmove > 0 //trying to take off - && parentPS->speed <= 200.0f )//going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast + && pVeh->m_ucmd.upmove > 0 // trying to take off + && parentPS->speed <= 200.0f) // going slow enough to start landing - was using pVeh->m_pVehicleInfo->speedIdle, but that's still too fast { return qtrue; } return qfalse; } -qboolean FighterSuspended( Vehicle_t *pVeh, playerState_t *parentPS ) -{ -#ifdef _GAME//only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver - if (!pVeh->m_pPilot//empty - && !parentPS->speed//not moving - && pVeh->m_ucmd.forwardmove <= 0//not trying to go forward for whatever reason - && pVeh->m_pParentEntity != NULL - && (((gentity_t *)pVeh->m_pParentEntity)->spawnflags&2) )//SUSPENDED spawnflag is on +qboolean FighterSuspended(Vehicle_t *pVeh, playerState_t *parentPS) { +#ifdef _GAME // only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver + if (!pVeh->m_pPilot // empty + && !parentPS->speed // not moving + && pVeh->m_ucmd.forwardmove <= 0 // not trying to go forward for whatever reason + && pVeh->m_pParentEntity != NULL && (((gentity_t *)pVeh->m_pParentEntity)->spawnflags & 2)) // SUSPENDED spawnflag is on { return qtrue; } @@ -282,155 +246,133 @@ qboolean FighterSuspended( Vehicle_t *pVeh, playerState_t *parentPS ) #endif } -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. #define FIGHTER_MIN_TAKEOFF_FRACTION 0.7f -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations + // Client sets ucmds and such for speed alterations float speedInc, speedIdleDec, speedIdle, speedIdleAccel, speedMin, speedMax; bgEntity_t *parent = pVeh->m_pParentEntity; qboolean isLandingOrLaunching = qfalse; - //this function should only be called from pmove.. if it gets called elsehwere, - //obviously this will explode. + // this function should only be called from pmove.. if it gets called elsehwere, + // obviously this will explode. int curTime = pm->cmd.serverTime; playerState_t *parentPS = parent->playerState; - if ( parentPS->hyperSpaceTime - && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME ) - {//Going to Hyperspace - //totally override movement - float timeFrac = ((float)(curTime-parentPS->hyperSpaceTime))/HYPERSPACE_TIME; - if ( timeFrac < HYPERSPACE_TELEPORT_FRAC ) - {//for first half, instantly jump to top speed! - if ( !(parentPS->eFlags2&EF2_HYPERSPACE) ) - {//waiting to face the right direction, do nothing + if (parentPS->hyperSpaceTime && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME) { // Going to Hyperspace + // totally override movement + float timeFrac = ((float)(curTime - parentPS->hyperSpaceTime)) / HYPERSPACE_TIME; + if (timeFrac < HYPERSPACE_TELEPORT_FRAC) { // for first half, instantly jump to top speed! + if (!(parentPS->eFlags2 & EF2_HYPERSPACE)) { // waiting to face the right direction, do nothing parentPS->speed = 0.0f; - } - else - { - if ( parentPS->speed < HYPERSPACE_SPEED ) - {//just started hyperspace -//MIKE: This is going to play the sound twice for the predicting client, I suggest using -//a predicted event or only doing it game-side. -rich + } else { + if (parentPS->speed < + HYPERSPACE_SPEED) { // just started hyperspace +// MIKE: This is going to play the sound twice for the predicting client, I suggest using +// a predicted event or only doing it game-side. -rich #ifdef _GAME - //G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); + // G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); #elif _CGAME - trap->S_StartSound( NULL, pm->ps->clientNum, CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper ); + trap->S_StartSound(NULL, pm->ps->clientNum, CHAN_LOCAL, pVeh->m_pVehicleInfo->soundHyper); #endif } parentPS->speed = HYPERSPACE_SPEED; } - } - else - {//slow from top speed to 200... - parentPS->speed = 200.0f + ((1.0f-timeFrac)*(1.0f/HYPERSPACE_TELEPORT_FRAC)*(HYPERSPACE_SPEED-200.0f)); - //don't mess with acceleration, just pop to the high velocity - if ( VectorLength( parentPS->velocity ) < parentPS->speed ) - { - VectorScale( parentPS->moveDir, parentPS->speed, parentPS->velocity ); + } else { // slow from top speed to 200... + parentPS->speed = 200.0f + ((1.0f - timeFrac) * (1.0f / HYPERSPACE_TELEPORT_FRAC) * (HYPERSPACE_SPEED - 200.0f)); + // don't mess with acceleration, just pop to the high velocity + if (VectorLength(parentPS->velocity) < parentPS->speed) { + VectorScale(parentPS->moveDir, parentPS->speed, parentPS->velocity); } } return; } - if ( pVeh->m_iDropTime >= curTime ) - {//no speed, just drop + if (pVeh->m_iDropTime >= curTime) { // no speed, just drop parentPS->speed = 0.0f; parentPS->gravity = 800; return; } - isLandingOrLaunching = (FighterIsLanding( pVeh, parentPS )||FighterIsLaunching( pVeh, parentPS )); + isLandingOrLaunching = (FighterIsLanding(pVeh, parentPS) || FighterIsLaunching(pVeh, parentPS)); // If we are hitting the ground, just allow the fighter to go up and down. - if ( isLandingOrLaunching//going slow enough to start landing - && (pVeh->m_ucmd.forwardmove<=0||pVeh->m_LandTrace.fraction<=FIGHTER_MIN_TAKEOFF_FRACTION) )//not trying to accelerate away already (or: you are trying to, but not high enough off the ground yet) - {//FIXME: if start to move forward and fly over something low while still going relatively slow, you may try to land even though you don't mean to... - //float fInvFrac = 1.0f - pVeh->m_LandTrace.fraction; - - if ( pVeh->m_ucmd.upmove > 0 ) - { - if ( parentPS->velocity[2] <= 0 - && pVeh->m_pVehicleInfo->soundTakeOff ) - {//taking off for the first time - #ifdef _GAME//MP GAME-side - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTakeOff ); - #endif + if (isLandingOrLaunching // going slow enough to start landing + && (pVeh->m_ucmd.forwardmove <= 0 || + pVeh->m_LandTrace.fraction <= + FIGHTER_MIN_TAKEOFF_FRACTION)) // not trying to accelerate away already (or: you are trying to, but not high enough off the ground yet) + { // FIXME: if start to move forward and fly over something low while still going relatively slow, you may try to land even though you don't mean to... + // float fInvFrac = 1.0f - pVeh->m_LandTrace.fraction; + + if (pVeh->m_ucmd.upmove > 0) { + if (parentPS->velocity[2] <= 0 && pVeh->m_pVehicleInfo->soundTakeOff) { // taking off for the first time +#ifdef _GAME // MP GAME-side + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTakeOff); +#endif } - parentPS->velocity[2] += pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier;// * ( /*fInvFrac **/ 1.5f ); - } - else if ( pVeh->m_ucmd.upmove < 0 ) - { - parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier;// * ( /*fInvFrac **/ 1.8f ); - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( pVeh->m_LandTrace.fraction != 0.0f ) - { + parentPS->velocity[2] += pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; // * ( /*fInvFrac **/ 1.5f ); + } else if (pVeh->m_ucmd.upmove < 0) { + parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; // * ( /*fInvFrac **/ 1.8f ); + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (pVeh->m_LandTrace.fraction != 0.0f) { parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( pVeh->m_LandTrace.fraction <= FIGHTER_MIN_TAKEOFF_FRACTION ) - { - //pVeh->m_pParentEntity->client->ps.velocity[0] *= pVeh->m_LandTrace.fraction; - //pVeh->m_pParentEntity->client->ps.velocity[1] *= pVeh->m_LandTrace.fraction; + if (pVeh->m_LandTrace.fraction <= FIGHTER_MIN_TAKEOFF_FRACTION) { + // pVeh->m_pParentEntity->client->ps.velocity[0] *= pVeh->m_LandTrace.fraction; + // pVeh->m_pParentEntity->client->ps.velocity[1] *= pVeh->m_LandTrace.fraction; - //remember to always base this stuff on the time modifier! otherwise, you create - //framerate-dependancy issues and break prediction in MP -rww - //parentPS->velocity[2] *= pVeh->m_LandTrace.fraction; - //it's not an angle, but hey - parentPS->velocity[2] = PredictedAngularDecrement(pVeh->m_LandTrace.fraction, pVeh->m_fTimeModifier*5.0f, parentPS->velocity[2]); + // remember to always base this stuff on the time modifier! otherwise, you create + // framerate-dependancy issues and break prediction in MP -rww + // parentPS->velocity[2] *= pVeh->m_LandTrace.fraction; + // it's not an angle, but hey + parentPS->velocity[2] = PredictedAngularDecrement(pVeh->m_LandTrace.fraction, pVeh->m_fTimeModifier * 5.0f, parentPS->velocity[2]); parentPS->speed = 0; } } // Make sure they don't pitch as they near the ground. - //pVeh->m_vOrientation[PITCH] *= 0.7f; - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.7f, pVeh->m_fTimeModifier*10.0f, pVeh->m_vOrientation[PITCH]); + // pVeh->m_vOrientation[PITCH] *= 0.7f; + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.7f, pVeh->m_fTimeModifier * 10.0f, pVeh->m_vOrientation[PITCH]); return; } - if ( (pVeh->m_ucmd.upmove > 0) && pVeh->m_pVehicleInfo->turboSpeed ) - { - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if ((pVeh->m_ucmd.upmove > 0) && pVeh->m_pVehicleInfo->turboSpeed) { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); -#ifdef _GAME//MP GAME-side - //NOTE: turbo sound can't be part of effect if effect is played on every muzzle! - if ( pVeh->m_pVehicleInfo->soundTurbo ) - { - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo ); +#ifdef _GAME // MP GAME-side + // NOTE: turbo sound can't be part of effect if effect is played on every muzzle! + if (pVeh->m_pVehicleInfo->soundTurbo) { + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundTurbo); } #endif } } speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; - if ( curTime < pVeh->m_iTurboTime ) - {//going turbo speed + if (curTime < pVeh->m_iTurboTime) { // going turbo speed speedMax = pVeh->m_pVehicleInfo->turboSpeed; - //double our acceleration - //speedInc *= 2.0f; - //no no no! this would el breako el predictiono! we want the following... -rww - speedInc = (pVeh->m_pVehicleInfo->acceleration*2.0f) * pVeh->m_fTimeModifier; + // double our acceleration + // speedInc *= 2.0f; + // no no no! this would el breako el predictiono! we want the following... -rww + speedInc = (pVeh->m_pVehicleInfo->acceleration * 2.0f) * pVeh->m_fTimeModifier; - //force us to move forward + // force us to move forward pVeh->m_ucmd.forwardmove = 127; - //add flag to let cgame know to draw the iTurboFX effect + // add flag to let cgame know to draw the iTurboFX effect parentPS->eFlags |= EF_JETPACK_ACTIVE; } /* @@ -440,11 +382,9 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedMax = pVeh->m_pVehicleInfo->speedMax*0.75; } */ - else - {//normal max speed + else { // normal max speed speedMax = pVeh->m_pVehicleInfo->speedMax; - if ( (parentPS->eFlags&EF_JETPACK_ACTIVE) ) - {//stop cgame from playing the turbo exhaust effect + if ((parentPS->eFlags & EF_JETPACK_ACTIVE)) { // stop cgame from playing the turbo exhaust effect parentPS->eFlags &= ~EF_JETPACK_ACTIVE; } } @@ -453,324 +393,227 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedIdleAccel = pVeh->m_pVehicleInfo->accelIdle * pVeh->m_fTimeModifier; speedMin = pVeh->m_pVehicleInfo->speedMin; - if ( (parentPS->brokenLimbs&(1<brokenLimbs&(1<brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_HEAVY))) { // engine has taken heavy damage + speedMax *= 0.8f; // at 80% speed + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_BACK_LIGHT))) { // engine has taken light damage + speedMax *= 0.6f; // at 60% speed } - if (pVeh->m_iRemovedSurfaces - || parentPS->electrifyTime>=curTime) - { //go out of control + if (pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) { // go out of control parentPS->speed += speedInc; - //Why set forwardmove? PMove code doesn't use it... does it? + // Why set forwardmove? PMove code doesn't use it... does it? pVeh->m_ucmd.forwardmove = 127; } -#ifdef _GAME //well, the thing is always going to be inhabited if it's being predicted! - else if ( FighterSuspended( pVeh, parentPS ) ) - { +#ifdef _GAME // well, the thing is always going to be inhabited if it's being predicted! + else if (FighterSuspended(pVeh, parentPS)) { parentPS->speed = 0; pVeh->m_ucmd.forwardmove = 0; - } - else if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) - && parentPS->speed > 0 ) - {//pilot jumped out while we were moving forward (not landing or landed) so just keep the throttle locked - //Why set forwardmove? PMove code doesn't use it... does it? + } else if (!pVeh->m_pVehicleInfo->Inhabited(pVeh) && + parentPS->speed > 0) { // pilot jumped out while we were moving forward (not landing or landed) so just keep the throttle locked + // Why set forwardmove? PMove code doesn't use it... does it? pVeh->m_ucmd.forwardmove = 127; } #endif - else if ( ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) && pVeh->m_LandTrace.fraction >= 0.05f ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + else if ((parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) && + pVeh->m_LandTrace.fraction >= 0.05f) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; pVeh->m_ucmd.forwardmove = 127; - } - else if ( pVeh->m_ucmd.forwardmove < 0 - || pVeh->m_ucmd.upmove < 0 ) - {//decelerating or braking - if ( pVeh->m_ucmd.upmove < 0 ) - {//braking (trying to land?), slow down faster - if ( pVeh->m_ucmd.forwardmove ) - {//decelerator + brakes + } else if (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0) { // decelerating or braking + if (pVeh->m_ucmd.upmove < 0) { // braking (trying to land?), slow down faster + if (pVeh->m_ucmd.forwardmove) { // decelerator + brakes speedInc += pVeh->m_pVehicleInfo->braking; speedIdleDec += pVeh->m_pVehicleInfo->braking; - } - else - {//just brakes + } else { // just brakes speedInc = speedIdleDec = pVeh->m_pVehicleInfo->braking; } } - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { - if ( FighterOverValidLandingSurface( pVeh ) ) - {//there's ground below us and we're trying to slow down, slow down faster + } else if (parentPS->speed > speedMin) { + if (FighterOverValidLandingSurface(pVeh)) { // there's ground below us and we're trying to slow down, slow down faster parentPS->speed -= speedInc; - } - else - { + } else { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < MIN_LANDING_SPEED ) - {//unless you can land, don't drop below the landing speed!!! This way you can't come to a dead stop in mid-air + if (parentPS->speed < + MIN_LANDING_SPEED) { // unless you can land, don't drop below the landing speed!!! This way you can't come to a dead stop in mid-air parentPS->speed = MIN_LANDING_SPEED; } } } - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { pVeh->m_ucmd.forwardmove = 127; - } - else if ( speedMin >= 0 ) - { + } else if (speedMin >= 0) { pVeh->m_ucmd.forwardmove = 0; } } - //else not accel, decel or braking - else if ( pVeh->m_pVehicleInfo->throttleSticks ) - {//we're using a throttle that sticks at current speed - if ( parentPS->speed <= MIN_LANDING_SPEED ) - {//going less than landing speed - if ( FighterOverValidLandingSurface( pVeh ) ) - {//close to ground and not going very fast - //slow to a stop if within landing height and not accel/decel/braking - if ( parentPS->speed > 0 ) - {//slow down + // else not accel, decel or braking + else if (pVeh->m_pVehicleInfo->throttleSticks) { // we're using a throttle that sticks at current speed + if (parentPS->speed <= MIN_LANDING_SPEED) { // going less than landing speed + if (FighterOverValidLandingSurface(pVeh)) { // close to ground and not going very fast + // slow to a stop if within landing height and not accel/decel/braking + if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - } - else if ( parentPS->speed < 0 ) - {//going backwards, slow down + } else if (parentPS->speed < 0) { // going backwards, slow down parentPS->speed += speedIdleDec; } - } - else - {//not over a valid landing surf, but going too slow - //speed up to idle speed if not over a valid landing surf and not accel/decel/braking - if ( parentPS->speed < speedIdle ) - { + } else { // not over a valid landing surf, but going too slow + // speed up to idle speed if not over a valid landing surf and not accel/decel/braking + if (parentPS->speed < speedIdle) { parentPS->speed += speedIdleAccel; - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed = speedIdle; } } } } - } - else - {//then speed up or slow down to idle speed - //accelerate to cruising speed only, otherwise, just coast - // If they've launched, apply some constant motion. - if ( (pVeh->m_LandTrace.fraction >= 1.0f //no ground - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE )//or can't land on ground below us - && speedIdle > 0 ) - {//not above ground and have an idle speed - //float fSpeed = pVeh->m_pParentEntity->client->ps.speed; - if ( parentPS->speed < speedIdle ) - { + } else { // then speed up or slow down to idle speed + // accelerate to cruising speed only, otherwise, just coast + // If they've launched, apply some constant motion. + if ((pVeh->m_LandTrace.fraction >= 1.0f // no ground + || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) // or can't land on ground below us + && speedIdle > 0) { // not above ground and have an idle speed + // float fSpeed = pVeh->m_pParentEntity->client->ps.speed; + if (parentPS->speed < speedIdle) { parentPS->speed += speedIdleAccel; - if ( parentPS->speed > speedIdle ) - { + if (parentPS->speed > speedIdle) { parentPS->speed = speedIdle; } - } - else if ( parentPS->speed > 0 ) - {//slow down + } else if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - if ( parentPS->speed < speedIdle ) - { + if (parentPS->speed < speedIdle) { parentPS->speed = speedIdle; } } - } - else//either close to ground or no idle speed - {//slow to a stop if no idle speed or within landing height and not accel/decel/braking - if ( parentPS->speed > 0 ) - {//slow down + } else // either close to ground or no idle speed + { // slow to a stop if no idle speed or within landing height and not accel/decel/braking + if (parentPS->speed > 0) { // slow down parentPS->speed -= speedIdleDec; - } - else if ( parentPS->speed < 0 ) - {//going backwards, slow down + } else if (parentPS->speed < 0) { // going backwards, slow down parentPS->speed += speedIdleDec; } } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } } -#if 1//This is working now, but there are some transitional jitters... Rich? -//STRAFING============================================================================== - if ( pVeh->m_pVehicleInfo->strafePerc -#ifdef _GAME//only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver - && pVeh->m_pVehicleInfo->Inhabited( pVeh )//has to have a driver in order to be capable of landing +#if 1 // This is working now, but there are some transitional jitters... Rich? + // STRAFING============================================================================== + if (pVeh->m_pVehicleInfo->strafePerc +#ifdef _GAME // only do this check on game side, because if it's cgame, it's being predicted, and it's only predicted if the local client is the driver + && pVeh->m_pVehicleInfo->Inhabited(pVeh) // has to have a driver in order to be capable of landing #endif - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_LandTrace.fraction >= 1.0f//no grounf - ||pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE//can't land here - ||parentPS->speed>MIN_LANDING_SPEED)//going too fast to land - && pVeh->m_ucmd.rightmove ) - {//strafe + && !pVeh->m_iRemovedSurfaces && parentPS->electrifyTime < curTime && + (pVeh->m_LandTrace.fraction >= 1.0f // no grounf + || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE // can't land here + || parentPS->speed > MIN_LANDING_SPEED) // going too fast to land + && pVeh->m_ucmd.rightmove) { // strafe vec3_t vAngles, vRight; - float strafeSpeed = (pVeh->m_pVehicleInfo->strafePerc*speedMax)*5.0f; - VectorCopy( pVeh->m_vOrientation, vAngles ); + float strafeSpeed = (pVeh->m_pVehicleInfo->strafePerc * speedMax) * 5.0f; + VectorCopy(pVeh->m_vOrientation, vAngles); vAngles[PITCH] = vAngles[ROLL] = 0; - AngleVectors( vAngles, NULL, vRight, NULL ); + AngleVectors(vAngles, NULL, vRight, NULL); - if ( pVeh->m_ucmd.rightmove > 0 ) - {//strafe right - //FIXME: this will probably make it possible to cheat and + if (pVeh->m_ucmd.rightmove > 0) { // strafe right + // FIXME: this will probably make it possible to cheat and // go faster than max speed if you keep turning and strafing... - if ( parentPS->hackingTime > -MAX_STRAFE_TIME ) - {//can strafe right for 2 seconds - float curStrafeSpeed = DotProduct( parentPS->velocity, vRight ); - if ( curStrafeSpeed > 0.0f ) - {//if > 0, already strafing right - strafeSpeed -= curStrafeSpeed;//so it doesn't add up + if (parentPS->hackingTime > -MAX_STRAFE_TIME) { // can strafe right for 2 seconds + float curStrafeSpeed = DotProduct(parentPS->velocity, vRight); + if (curStrafeSpeed > 0.0f) { // if > 0, already strafing right + strafeSpeed -= curStrafeSpeed; // so it doesn't add up } - if ( strafeSpeed > 0 ) - { - VectorMA( parentPS->velocity, strafeSpeed*pVeh->m_fTimeModifier, vRight, parentPS->velocity ); + if (strafeSpeed > 0) { + VectorMA(parentPS->velocity, strafeSpeed * pVeh->m_fTimeModifier, vRight, parentPS->velocity); } - parentPS->hackingTime -= 50*pVeh->m_fTimeModifier; + parentPS->hackingTime -= 50 * pVeh->m_fTimeModifier; } - } - else - {//strafe left - if ( parentPS->hackingTime < MAX_STRAFE_TIME ) - {//can strafe left for 2 seconds - float curStrafeSpeed = DotProduct( parentPS->velocity, vRight ); - if ( curStrafeSpeed < 0.0f ) - {//if < 0, already strafing left - strafeSpeed += curStrafeSpeed;//so it doesn't add up + } else { // strafe left + if (parentPS->hackingTime < MAX_STRAFE_TIME) { // can strafe left for 2 seconds + float curStrafeSpeed = DotProduct(parentPS->velocity, vRight); + if (curStrafeSpeed < 0.0f) { // if < 0, already strafing left + strafeSpeed += curStrafeSpeed; // so it doesn't add up } - if ( strafeSpeed > 0 ) - { - VectorMA( parentPS->velocity, -strafeSpeed*pVeh->m_fTimeModifier, vRight, parentPS->velocity ); + if (strafeSpeed > 0) { + VectorMA(parentPS->velocity, -strafeSpeed * pVeh->m_fTimeModifier, vRight, parentPS->velocity); } - parentPS->hackingTime += 50*pVeh->m_fTimeModifier; + parentPS->hackingTime += 50 * pVeh->m_fTimeModifier; } } - //strafing takes away from forward speed? If so, strafePerc above should use speedMax - //parentPS->speed *= (1.0f-pVeh->m_pVehicleInfo->strafePerc); - } - else//if ( parentPS->hackingTimef ) + // strafing takes away from forward speed? If so, strafePerc above should use speedMax + // parentPS->speed *= (1.0f-pVeh->m_pVehicleInfo->strafePerc); + } else // if ( parentPS->hackingTimef ) { - if ( parentPS->hackingTime > 0 ) - { - parentPS->hackingTime -= 50*pVeh->m_fTimeModifier; - if ( parentPS->hackingTime < 0 ) - { + if (parentPS->hackingTime > 0) { + parentPS->hackingTime -= 50 * pVeh->m_fTimeModifier; + if (parentPS->hackingTime < 0) { parentPS->hackingTime = 0.0f; } - } - else if ( parentPS->hackingTime < 0 ) - { - parentPS->hackingTime += 50*pVeh->m_fTimeModifier; - if ( parentPS->hackingTime > 0 ) - { + } else if (parentPS->hackingTime < 0) { + parentPS->hackingTime += 50 * pVeh->m_fTimeModifier; + if (parentPS->hackingTime > 0) { parentPS->hackingTime = 0.0f; } } } -//STRAFING============================================================================== +// STRAFING============================================================================== #endif - if ( parentPS->speed > speedMax ) - { + if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } -#ifdef _GAME//FIXME: get working in game and cgame - if ((pVeh->m_vOrientation[PITCH]*0.1f) > 10.0f) - { //pitched downward, increase speed more and more based on our tilt - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//in space, do nothing with speed base on pitch... - } - else - { - //really should only do this when on a planet - float mult = pVeh->m_vOrientation[PITCH]*0.1f; - if (mult < 1.0f) - { +#ifdef _GAME // FIXME: get working in game and cgame + if ((pVeh->m_vOrientation[PITCH] * 0.1f) > 10.0f) { // pitched downward, increase speed more and more based on our tilt + if (FighterIsInSpace((gentity_t *)parent)) { // in space, do nothing with speed base on pitch... + } else { + // really should only do this when on a planet + float mult = pVeh->m_vOrientation[PITCH] * 0.1f; + if (mult < 1.0f) { mult = 1.0f; } - parentPS->speed = PredictedAngularDecrement(mult, pVeh->m_fTimeModifier*10.0f, parentPS->speed); + parentPS->speed = PredictedAngularDecrement(mult, pVeh->m_fTimeModifier * 10.0f, parentPS->speed); } } - if (pVeh->m_iRemovedSurfaces - || parentPS->electrifyTime>=curTime) - { //going down - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//we're in a valid trigger_space brush - //simulate randomness - if ( !(parent->s.number&3) ) - {//even multiple of 3, don't do anything + if (pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) { // going down + if (FighterIsInSpace((gentity_t *)parent)) { // we're in a valid trigger_space brush + // simulate randomness + if (!(parent->s.number & 3)) { // even multiple of 3, don't do anything parentPS->gravity = 0; - } - else if ( !(parent->s.number&2) ) - {//even multiple of 2, go up + } else if (!(parent->s.number & 2)) { // even multiple of 2, go up parentPS->gravity = -500.0f; parentPS->velocity[2] = 80.0f; - } - else - {//odd number, go down + } else { // odd number, go down parentPS->gravity = 500.0f; parentPS->velocity[2] = -80.0f; } - } - else - {//over a planet + } else { // over a planet parentPS->gravity = 500.0f; parentPS->velocity[2] = -80.0f; } - } - else if ( FighterSuspended( pVeh, parentPS ) ) - { + } else if (FighterSuspended(pVeh, parentPS)) { parentPS->gravity = 0; - } - else if ( (!parentPS->speed||parentPS->speed < speedIdle) && pVeh->m_ucmd.upmove <= 0 ) - {//slowing down or stopped and not trying to take off - if ( FighterIsInSpace( (gentity_t *)parent ) ) - {//we're in space, stopping doesn't make us drift downward - if ( FighterOverValidLandingSurface( pVeh ) ) - {//well, there's something below us to land on, so go ahead and lower us down to it - parentPS->gravity = (speedIdle - parentPS->speed)/4; + } else if ((!parentPS->speed || parentPS->speed < speedIdle) && pVeh->m_ucmd.upmove <= 0) { // slowing down or stopped and not trying to take off + if (FighterIsInSpace((gentity_t *)parent)) { // we're in space, stopping doesn't make us drift downward + if (FighterOverValidLandingSurface(pVeh)) { // well, there's something below us to land on, so go ahead and lower us down to it + parentPS->gravity = (speedIdle - parentPS->speed) / 4; } + } else { // over a planet + parentPS->gravity = (speedIdle - parentPS->speed) / 4; } - else - {//over a planet - parentPS->gravity = (speedIdle - parentPS->speed)/4; - } - } - else - { + } else { parentPS->gravity = 0; } -#else//FIXME: get above checks working in game and cgame +#else // FIXME: get above checks working in game and cgame parentPS->gravity = 0; #endif @@ -779,150 +622,112 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -extern void BG_VehicleTurnRateForSpeed( Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride ); -static void FighterWingMalfunctionCheck( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +extern void BG_VehicleTurnRateForSpeed(Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride); +static void FighterWingMalfunctionCheck(Vehicle_t *pVeh, playerState_t *parentPS) { float mPitchOverride = 1.0f; float mYawOverride = 1.0f; - BG_VehicleTurnRateForSpeed( pVeh, parentPS->speed, &mPitchOverride, &mYawOverride ); - //check right wing damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] += (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*50.0f; - } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] += (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*12.5f; + BG_VehicleTurnRateForSpeed(pVeh, parentPS->speed, &mPitchOverride, &mYawOverride); + // check right wing damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_RIGHT_HEAVY))) { // right wing has taken heavy damage + pVeh->m_vOrientation[ROLL] += (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_RIGHT_LIGHT))) { // right wing has taken light damage + pVeh->m_vOrientation[ROLL] += (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 12.5f; } - //check left wing damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] -= (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*50.0f; + // check left wing damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_LEFT_HEAVY))) { // left wing has taken heavy damage + pVeh->m_vOrientation[ROLL] -= (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_LEFT_LIGHT))) { // left wing has taken light damage + pVeh->m_vOrientation[ROLL] -= (sin(pVeh->m_ucmd.serverTime * 0.001) + 1.0f) * pVeh->m_fTimeModifier * mYawOverride * 12.5f; } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[ROLL] -= (sin( pVeh->m_ucmd.serverTime*0.001 )+1.0f)*pVeh->m_fTimeModifier*mYawOverride*12.5f; - } - } -static void FighterNoseMalfunctionCheck( Vehicle_t *pVeh, playerState_t *parentPS ) -{ +static void FighterNoseMalfunctionCheck(Vehicle_t *pVeh, playerState_t *parentPS) { float mPitchOverride = 1.0f; float mYawOverride = 1.0f; - BG_VehicleTurnRateForSpeed( pVeh, parentPS->speed, &mPitchOverride, &mYawOverride ); - //check nose damage - if ( (parentPS->brokenLimbs&(1<m_vOrientation[PITCH] += sin( pVeh->m_ucmd.serverTime*0.001 )*pVeh->m_fTimeModifier*mPitchOverride*50.0f; - } - else if ( (parentPS->brokenLimbs&(1<m_vOrientation[PITCH] += sin( pVeh->m_ucmd.serverTime*0.001 )*pVeh->m_fTimeModifier*mPitchOverride*20.0f; + BG_VehicleTurnRateForSpeed(pVeh, parentPS->speed, &mPitchOverride, &mYawOverride); + // check nose damage + if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_FRONT_HEAVY))) { // nose has taken heavy damage + // pitch up and down over time + pVeh->m_vOrientation[PITCH] += sin(pVeh->m_ucmd.serverTime * 0.001) * pVeh->m_fTimeModifier * mPitchOverride * 50.0f; + } else if ((parentPS->brokenLimbs & (1 << SHIPSURF_DAMAGE_FRONT_LIGHT))) { // nose has taken heavy damage + // pitch up and down over time + pVeh->m_vOrientation[PITCH] += sin(pVeh->m_ucmd.serverTime * 0.001) * pVeh->m_fTimeModifier * mPitchOverride * 20.0f; } } -static void FighterDamageRoutine( Vehicle_t *pVeh, bgEntity_t *parent, playerState_t *parentPS, playerState_t *riderPS, qboolean isDead ) -{ - if ( !pVeh->m_iRemovedSurfaces ) - {//still in one piece - if ( pVeh->m_pParentEntity && isDead ) - {//death spiral +static void FighterDamageRoutine(Vehicle_t *pVeh, bgEntity_t *parent, playerState_t *parentPS, playerState_t *riderPS, qboolean isDead) { + if (!pVeh->m_iRemovedSurfaces) { // still in one piece + if (pVeh->m_pParentEntity && isDead) { // death spiral pVeh->m_ucmd.upmove = 0; - //FIXME: don't bias toward pitching down when not in space + // FIXME: don't bias toward pitching down when not in space /* if ( FighterIsInSpace( pVeh->m_pParentEntity ) ) { } else */ - if ( !(pVeh->m_pParentEntity->s.number%3) ) - {//NOT everyone should do this + if (!(pVeh->m_pParentEntity->s.number % 3)) { // NOT everyone should do this pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } - } - else if ( !(pVeh->m_pParentEntity->s.number%2) ) - { + } else if (!(pVeh->m_pParentEntity->s.number % 2)) { pVeh->m_vOrientation[PITCH] -= pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > -60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > -60.0f) { pVeh->m_vOrientation[PITCH] = -60.0f; } } } - if ( (pVeh->m_pParentEntity->s.number%2) ) - { + if ((pVeh->m_pParentEntity->s.number % 2)) { pVeh->m_vOrientation[YAW] += pVeh->m_fTimeModifier; - pVeh->m_vOrientation[ROLL] += pVeh->m_fTimeModifier*4.0f; - } - else - { + pVeh->m_vOrientation[ROLL] += pVeh->m_fTimeModifier * 4.0f; + } else { pVeh->m_vOrientation[YAW] -= pVeh->m_fTimeModifier; - pVeh->m_vOrientation[ROLL] -= pVeh->m_fTimeModifier*4.0f; + pVeh->m_vOrientation[ROLL] -= pVeh->m_fTimeModifier * 4.0f; } } return; } - //if we get into here we have at least one broken piece + // if we get into here we have at least one broken piece pVeh->m_ucmd.upmove = 0; - //if you're off the ground and not suspended, pitch down - //FIXME: not in space! - if ( pVeh->m_LandTrace.fraction >= 0.1f ) - { - if ( !FighterSuspended( pVeh, parentPS ) ) - { - //pVeh->m_ucmd.forwardmove = 0; - //FIXME: don't bias towards pitching down when in space... - if ( !(pVeh->m_pParentEntity->s.number%2) ) - {//NOT everyone should do this + // if you're off the ground and not suspended, pitch down + // FIXME: not in space! + if (pVeh->m_LandTrace.fraction >= 0.1f) { + if (!FighterSuspended(pVeh, parentPS)) { + // pVeh->m_ucmd.forwardmove = 0; + // FIXME: don't bias towards pitching down when in space... + if (!(pVeh->m_pParentEntity->s.number % 2)) { // NOT everyone should do this pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } - } - else if ( !(pVeh->m_pParentEntity->s.number%3) ) - { + } else if (!(pVeh->m_pParentEntity->s.number % 3)) { pVeh->m_vOrientation[PITCH] -= pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > -60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > -60.0f) { pVeh->m_vOrientation[PITCH] = -60.0f; } } } - //else: just keep going forward + // else: just keep going forward } } #ifdef _GAME - if ( pVeh->m_LandTrace.fraction < 1.0f ) - { //if you land at all when pieces of your ship are missing, then die + if (pVeh->m_LandTrace.fraction < 1.0f) { // if you land at all when pieces of your ship are missing, then die gentity_t *vparent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *killer = vparent; - if (vparent->client->ps.otherKiller < ENTITYNUM_WORLD && - vparent->client->ps.otherKillerTime > level.time) - { + if (vparent->client->ps.otherKiller < ENTITYNUM_WORLD && vparent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[vparent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } @@ -930,73 +735,54 @@ static void FighterDamageRoutine( Vehicle_t *pVeh, bgEntity_t *parent, playerSta } #endif - if ( ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) && - ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) ) - { //wings on both side broken + if (((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) && + ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F))) { // wings on both side broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //all wings broken + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // all wings broken factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] += (pVeh->m_fTimeModifier*factor); //do some spiralling - } - else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //left wing broken + pVeh->m_vOrientation[ROLL] += (pVeh->m_fTimeModifier * factor); // do some spiralling + } else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // left wing broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { //if both are broken.. + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { // if both are broken.. factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] += factor*pVeh->m_fTimeModifier; - } - else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { //right wing broken + pVeh->m_vOrientation[ROLL] += factor * pVeh->m_fTimeModifier; + } else if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { // right wing broken float factor = 2.0f; - if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { //if both are broken.. + if ((pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { // if both are broken.. factor *= 2.0f; } - if ( !(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5) ) - {//won't yaw, so increase roll factor + if (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5)) { // won't yaw, so increase roll factor factor *= 4.0f; } - pVeh->m_vOrientation[ROLL] -= factor*pVeh->m_fTimeModifier; + pVeh->m_vOrientation[ROLL] -= factor * pVeh->m_fTimeModifier; } } #ifdef VEH_CONTROL_SCHEME_4 -#define FIGHTER_TURNING_MULTIPLIER 0.8f//was 1.6f //magic number hackery -#define FIGHTER_TURNING_DEADZONE 0.25f//no turning if offset is this much -void FighterRollAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ -/* - float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); -*/ - float angDif = AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW],riderPS->viewangles[YAW]);///2.0f;//AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], riderPS->viewangles[YAW]); +#define FIGHTER_TURNING_MULTIPLIER 0.8f // was 1.6f //magic number hackery +#define FIGHTER_TURNING_DEADZONE 0.25f // no turning if offset is this much +void FighterRollAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { + /* + float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); + */ + float angDif = AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], + riderPS->viewangles[YAW]); /// 2.0f;//AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], riderPS->viewangles[YAW]); /* if ( fabs( angDif ) < FIGHTER_TURNING_DEADZONE ) { @@ -1013,268 +799,194 @@ void FighterRollAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *p */ angDif *= 0.5f; - if ( angDif > 0.0f ) - { + if (angDif > 0.0f) { angDif *= angDif; - } - else if ( angDif < 0.0f ) - { + } else if (angDif < 0.0f) { angDif *= -angDif; } - if (parentPS && parentPS->speed) - { - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*FIGHTER_TURNING_MULTIPLIER; + if (parentPS && parentPS->speed) { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * FIGHTER_TURNING_MULTIPLIER; - if ( pVeh->m_pVehicleInfo->speedDependantTurning ) - { + if (pVeh->m_pVehicleInfo->speedDependantTurning) { float speedFrac = 1.0f; - if ( pVeh->m_LandTrace.fraction >= 1.0f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - { + if (pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { float s = parentPS->speed; - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - speedFrac = (s/(pVeh->m_pVehicleInfo->speedMax*0.75f)); - if ( speedFrac < 0.25f ) - { + speedFrac = (s / (pVeh->m_pVehicleInfo->speedMax * 0.75f)); + if (speedFrac < 0.25f) { speedFrac = 0.25f; - } - else if ( speedFrac > 1.0f ) - { + } else if (speedFrac > 1.0f) { speedFrac = 1.0f; } } angDif *= speedFrac; } - if (angDif > maxDif) - { + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL] + angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL] + angDif * (pVeh->m_fTimeModifier * 0.2f)); } } -void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ - float angDif = AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW],riderPS->viewangles[YAW]);///2.0f;//AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], riderPS->viewangles[YAW]); - if ( fabs( angDif ) < FIGHTER_TURNING_DEADZONE ) - { +void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { + float angDif = AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], + riderPS->viewangles[YAW]); /// 2.0f;//AngleSubtract(pVeh->m_vPrevRiderViewAngles[YAW], riderPS->viewangles[YAW]); + if (fabs(angDif) < FIGHTER_TURNING_DEADZONE) { angDif = 0.0f; - } - else if ( angDif >= FIGHTER_TURNING_DEADZONE ) - { + } else if (angDif >= FIGHTER_TURNING_DEADZONE) { angDif -= FIGHTER_TURNING_DEADZONE; - } - else if ( angDif <= -FIGHTER_TURNING_DEADZONE ) - { + } else if (angDif <= -FIGHTER_TURNING_DEADZONE) { angDif += FIGHTER_TURNING_DEADZONE; } angDif *= 0.5f; - if ( angDif > 0.0f ) - { + if (angDif > 0.0f) { angDif *= angDif; - } - else if ( angDif < 0.0f ) - { + } else if (angDif < 0.0f) { angDif *= -angDif; } - if (parentPS && parentPS->speed) - { - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*FIGHTER_TURNING_MULTIPLIER; + if (parentPS && parentPS->speed) { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * FIGHTER_TURNING_MULTIPLIER; - if ( pVeh->m_pVehicleInfo->speedDependantTurning ) - { + if (pVeh->m_pVehicleInfo->speedDependantTurning) { float speedFrac = 1.0f; - if ( pVeh->m_LandTrace.fraction >= 1.0f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - { + if (pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { float s = parentPS->speed; - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - speedFrac = (s/(pVeh->m_pVehicleInfo->speedMax*0.75f)); - if ( speedFrac < 0.25f ) - { + speedFrac = (s / (pVeh->m_pVehicleInfo->speedMax * 0.75f)); + if (speedFrac < 0.25f) { speedFrac = 0.25f; - } - else if ( speedFrac > 1.0f ) - { + } else if (speedFrac > 1.0f) { speedFrac = 1.0f; } } angDif *= speedFrac; } - if (angDif > maxDif) - { + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - (angDif*(pVeh->m_fTimeModifier*0.2f)) ); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - (angDif * (pVeh->m_fTimeModifier * 0.2f))); } } -void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ - float angDif = AngleSubtract(0,riderPS->viewangles[PITCH]);//AngleSubtract(pVeh->m_vPrevRiderViewAngles[PITCH], riderPS->viewangles[PITCH]); - if ( fabs( angDif ) < FIGHTER_TURNING_DEADZONE ) - { +void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { + float angDif = AngleSubtract(0, riderPS->viewangles[PITCH]); // AngleSubtract(pVeh->m_vPrevRiderViewAngles[PITCH], riderPS->viewangles[PITCH]); + if (fabs(angDif) < FIGHTER_TURNING_DEADZONE) { angDif = 0.0f; - } - else if ( angDif >= FIGHTER_TURNING_DEADZONE ) - { + } else if (angDif >= FIGHTER_TURNING_DEADZONE) { angDif -= FIGHTER_TURNING_DEADZONE; - } - else if ( angDif <= -FIGHTER_TURNING_DEADZONE ) - { + } else if (angDif <= -FIGHTER_TURNING_DEADZONE) { angDif += FIGHTER_TURNING_DEADZONE; } angDif *= 0.5f; - if ( angDif > 0.0f ) - { + if (angDif > 0.0f) { angDif *= angDif; - } - else if ( angDif < 0.0f ) - { + } else if (angDif < 0.0f) { angDif *= -angDif; } - if (parentPS && parentPS->speed) - { - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*FIGHTER_TURNING_MULTIPLIER; + if (parentPS && parentPS->speed) { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * FIGHTER_TURNING_MULTIPLIER; - if ( pVeh->m_pVehicleInfo->speedDependantTurning ) - { + if (pVeh->m_pVehicleInfo->speedDependantTurning) { float speedFrac = 1.0f; - if ( pVeh->m_LandTrace.fraction >= 1.0f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - { + if (pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { float s = parentPS->speed; - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - speedFrac = (s/(pVeh->m_pVehicleInfo->speedMax*0.75f)); - if ( speedFrac < 0.25f ) - { + speedFrac = (s / (pVeh->m_pVehicleInfo->speedMax * 0.75f)); + if (speedFrac < 0.25f) { speedFrac = 0.25f; - } - else if ( speedFrac > 1.0f ) - { + } else if (speedFrac > 1.0f) { speedFrac = 1.0f; } } angDif *= speedFrac; } - if (angDif > maxDif) - { + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[PITCH] = AngleNormalize180(pVeh->m_vOrientation[PITCH] - (angDif*(pVeh->m_fTimeModifier*0.2f)) ); + pVeh->m_vOrientation[PITCH] = AngleNormalize180(pVeh->m_vOrientation[PITCH] - (angDif * (pVeh->m_fTimeModifier * 0.2f))); } } -#else// VEH_CONTROL_SCHEME_4 +#else // VEH_CONTROL_SCHEME_4 -void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ +void FighterYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*0.8f; //magic number hackery + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 0.8f; // magic number hackery - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } -void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ +void FighterPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { float angDif = AngleSubtract(pVeh->m_vOrientation[PITCH], riderPS->viewangles[PITCH]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*0.8f; //magic number hackery + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 0.8f; // magic number hackery - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[PITCH] = AngleNormalize360(pVeh->m_vOrientation[PITCH] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[PITCH] = AngleNormalize360(pVeh->m_vOrientation[PITCH] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } -#endif// VEH_CONTROL_SCHEME_4 - -void FighterPitchClamp(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS, int curTime ) -{ - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - {//cap pitch reasonably - if ( pVeh->m_pVehicleInfo->pitchLimit != -1 - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTime < curTime ) - { - if (pVeh->m_vOrientation[PITCH] > pVeh->m_pVehicleInfo->pitchLimit ) - { +#endif // VEH_CONTROL_SCHEME_4 + +void FighterPitchClamp(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS, int curTime) { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { // cap pitch reasonably + if (pVeh->m_pVehicleInfo->pitchLimit != -1 && !pVeh->m_iRemovedSurfaces && parentPS->electrifyTime < curTime) { + if (pVeh->m_vOrientation[PITCH] > pVeh->m_pVehicleInfo->pitchLimit) { pVeh->m_vOrientation[PITCH] = pVeh->m_pVehicleInfo->pitchLimit; - } - else if (pVeh->m_vOrientation[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit) - { + } else if (pVeh->m_vOrientation[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit) { pVeh->m_vOrientation[PITCH] = -pVeh->m_pVehicleInfo->pitchLimit; } } } } -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -1285,196 +997,160 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) #ifdef _GAME const float groundFraction = 0.1f; #endif - float curRoll = 0.0f; + float curRoll = 0.0f; qboolean isDead = qfalse; qboolean isLandingOrLanded = qfalse; #ifdef _GAME int curTime = level.time; #elif _CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... + // FIXME: pass in ucmd? Not sure if this is reliable... int curTime = pm->cmd.serverTime; #endif bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } - if ( !rider ) - { + if (!rider) { rider = parent; } parentPS = parent->playerState; riderPS = rider->playerState; - isDead = (qboolean)((parentPS->eFlags&EF_DEAD)!=0); + isDead = (qboolean)((parentPS->eFlags & EF_DEAD) != 0); #ifdef VEH_CONTROL_SCHEME_4 - if ( parentPS->hyperSpaceTime - && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME ) - {//Going to Hyperspace - //VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - //VectorCopy( riderPS->viewangles, parentPS->viewangles ); - VectorCopy( parentPS->viewangles, pVeh->m_vOrientation ); - VectorClear( pVeh->m_vPrevRiderViewAngles ); + if (parentPS->hyperSpaceTime && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME) { // Going to Hyperspace + // VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); + // VectorCopy( riderPS->viewangles, parentPS->viewangles ); + VectorCopy(parentPS->viewangles, pVeh->m_vOrientation); + VectorClear(pVeh->m_vPrevRiderViewAngles); pVeh->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(riderPS->viewangles[YAW]); - FighterPitchClamp( pVeh, riderPS, parentPS, curTime ); + FighterPitchClamp(pVeh, riderPS, parentPS, curTime); return; - } - else if ( parentPS->vehTurnaroundIndex - && parentPS->vehTurnaroundTime > curTime ) - {//in turn-around brush - //VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - //VectorCopy( riderPS->viewangles, parentPS->viewangles ); - VectorCopy( parentPS->viewangles, pVeh->m_vOrientation ); - VectorClear( pVeh->m_vPrevRiderViewAngles ); + } else if (parentPS->vehTurnaroundIndex && parentPS->vehTurnaroundTime > curTime) { // in turn-around brush + // VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); + // VectorCopy( riderPS->viewangles, parentPS->viewangles ); + VectorCopy(parentPS->viewangles, pVeh->m_vOrientation); + VectorClear(pVeh->m_vPrevRiderViewAngles); pVeh->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(riderPS->viewangles[YAW]); - FighterPitchClamp( pVeh, riderPS, parentPS, curTime ); + FighterPitchClamp(pVeh, riderPS, parentPS, curTime); return; } -#else// VEH_CONTROL_SCHEME_4 +#else // VEH_CONTROL_SCHEME_4 - if ( parentPS->hyperSpaceTime - && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME ) - {//Going to Hyperspace - VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - VectorCopy( riderPS->viewangles, parentPS->viewangles ); + if (parentPS->hyperSpaceTime && (curTime - parentPS->hyperSpaceTime) < HYPERSPACE_TIME) { // Going to Hyperspace + VectorCopy(riderPS->viewangles, pVeh->m_vOrientation); + VectorCopy(riderPS->viewangles, parentPS->viewangles); return; } -#endif// VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 - if ( pVeh->m_iDropTime >= curTime ) - {//you can only YAW during this + if (pVeh->m_iDropTime >= curTime) { // you can only YAW during this parentPS->viewangles[YAW] = pVeh->m_vOrientation[YAW] = riderPS->viewangles[YAW]; #ifdef VEH_CONTROL_SCHEME_4 - VectorClear( pVeh->m_vPrevRiderViewAngles ); + VectorClear(pVeh->m_vPrevRiderViewAngles); pVeh->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(riderPS->viewangles[YAW]); -#endif// VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 return; } angleTimeMod = pVeh->m_fTimeModifier; - if ( isDead || parentPS->electrifyTime>=curTime || - (pVeh->m_pVehicleInfo->surfDestruction && - pVeh->m_iRemovedSurfaces && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && - (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) ) - { //do some special stuff for when all the wings are torn off + if (isDead || parentPS->electrifyTime >= curTime || + (pVeh->m_pVehicleInfo->surfDestruction && pVeh->m_iRemovedSurfaces && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) && (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) && + (pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F))) { // do some special stuff for when all the wings are torn off FighterDamageRoutine(pVeh, parent, parentPS, riderPS, isDead); - pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); + pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL]); return; } - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - pVeh->m_vOrientation[ROLL] = PredictedAngularDecrement(0.95f, angleTimeMod*2.0f, pVeh->m_vOrientation[ROLL]); + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + pVeh->m_vOrientation[ROLL] = PredictedAngularDecrement(0.95f, angleTimeMod * 2.0f, pVeh->m_vOrientation[ROLL]); } - isLandingOrLanded = (FighterIsLanding( pVeh, parentPS )||FighterIsLanded( pVeh, parentPS )); + isLandingOrLanded = (FighterIsLanding(pVeh, parentPS) || FighterIsLanded(pVeh, parentPS)); - if (!isLandingOrLanded) - { //don't do this stuff while landed.. I guess. I don't want ships spinning in place, looks silly. + if (!isLandingOrLanded) { // don't do this stuff while landed.. I guess. I don't want ships spinning in place, looks silly. int m = 0; float aVelDif; float dForVel; - FighterWingMalfunctionCheck( pVeh, parentPS ); + FighterWingMalfunctionCheck(pVeh, parentPS); - while (m < 3) - { + while (m < 3) { aVelDif = pVeh->m_vFullAngleVelocity[m]; - if (aVelDif != 0.0f) - { - dForVel = (aVelDif*0.1f)*pVeh->m_fTimeModifier; - if (dForVel > 1.0f || dForVel < -1.0f) - { + if (aVelDif != 0.0f) { + dForVel = (aVelDif * 0.1f) * pVeh->m_fTimeModifier; + if (dForVel > 1.0f || dForVel < -1.0f) { pVeh->m_vOrientation[m] += dForVel; pVeh->m_vOrientation[m] = AngleNormalize180(pVeh->m_vOrientation[m]); - if (m == PITCH) - { //don't pitch downward into ground even more. - if (pVeh->m_vOrientation[m] > 90.0f && (pVeh->m_vOrientation[m]-dForVel) < 90.0f) - { + if (m == PITCH) { // don't pitch downward into ground even more. + if (pVeh->m_vOrientation[m] > 90.0f && (pVeh->m_vOrientation[m] - dForVel) < 90.0f) { pVeh->m_vOrientation[m] = 90.0f; pVeh->m_vFullAngleVelocity[m] = -pVeh->m_vFullAngleVelocity[m]; } } pVeh->m_vFullAngleVelocity[m] -= dForVel; - } - else - { + } else { pVeh->m_vFullAngleVelocity[m] = 0.0f; } } m++; } - } - else - { //clear decr/incr angles once landed. + } else { // clear decr/incr angles once landed. VectorClear(pVeh->m_vFullAngleVelocity); } curRoll = pVeh->m_vOrientation[ROLL]; // If we're landed, we shouldn't be able to do anything but take off. - if ( isLandingOrLanded //going slow enough to start landing - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_iRemovedSurfaces && parentPS->electrifyTime < curTime) // not spiraling out of control { - if ( parentPS->speed > 0.0f ) - {//Uh... what? Why? - if ( pVeh->m_LandTrace.fraction < 0.3f ) - { + if (parentPS->speed > 0.0f) { // Uh... what? Why? + if (pVeh->m_LandTrace.fraction < 0.3f) { pVeh->m_vOrientation[PITCH] = 0.0f; - } - else - { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.83f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + } else { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.83f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); } } - if ( pVeh->m_LandTrace.fraction > 0.1f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - {//off the ground, at least (or not on a valid landing surf) + if (pVeh->m_LandTrace.fraction > 0.1f || + pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { // off the ground, at least (or not on a valid landing surf) // Dampen the turn rate based on the current height. FighterYawAdjust(pVeh, riderPS, parentPS); } #ifdef VEH_CONTROL_SCHEME_4 - else - { - VectorClear( pVeh->m_vPrevRiderViewAngles ); + else { + VectorClear(pVeh->m_vPrevRiderViewAngles); pVeh->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(riderPS->viewangles[YAW]); } -#endif// VEH_CONTROL_SCHEME_4 - } - else if ( (pVeh->m_iRemovedSurfaces||parentPS->electrifyTime>=curTime)//spiralling out of control - && (!(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5)) ) - {//no yaw control - } - else if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS && parentPS->speed > 0.0f )//&& !( pVeh->m_ucmd.forwardmove > 0 && pVeh->m_LandTrace.fraction != 1.0f ) ) +#endif // VEH_CONTROL_SCHEME_4 + } else if ((pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) // spiralling out of control + && (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5))) { // no yaw control + } else if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS && + parentPS->speed > 0.0f) //&& !( pVeh->m_ucmd.forwardmove > 0 && pVeh->m_LandTrace.fraction != 1.0f ) ) { #ifdef VEH_CONTROL_SCHEME_4 - if ( 0 ) -#else// VEH_CONTROL_SCHEME_4 - if ( BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) -#endif// VEH_CONTROL_SCHEME_4 + if (0) +#else // VEH_CONTROL_SCHEME_4 + if (BG_UnrestrainedPitchRoll(riderPS, pVeh)) +#endif // VEH_CONTROL_SCHEME_4 { - VectorCopy( riderPS->viewangles, pVeh->m_vOrientation ); - VectorCopy( riderPS->viewangles, parentPS->viewangles ); + VectorCopy(riderPS->viewangles, pVeh->m_vOrientation); + VectorCopy(riderPS->viewangles, parentPS->viewangles); curRoll = pVeh->m_vOrientation[ROLL]; - FighterNoseMalfunctionCheck( pVeh, parentPS ); + FighterNoseMalfunctionCheck(pVeh, parentPS); - //VectorCopy( pVeh->m_vOrientation, parentPS->viewangles ); - } - else - { + // VectorCopy( pVeh->m_vOrientation, parentPS->viewangles ); + } else { /* float fTurnAmt[3]; //PITCH @@ -1492,7 +1168,7 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) fTurnAmt[2] = 0.0f; */ - //Actal YAW + // Actal YAW /* pVeh->m_vOrientation[ROLL] = curRoll; FighterRollAdjust(pVeh, riderPS, parentPS); @@ -1501,253 +1177,195 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) FighterYawAdjust(pVeh, riderPS, parentPS); // If we are not hitting the ground, allow the fighter to pitch up and down. - if ( !FighterOverValidLandingSurface( pVeh ) - || parentPS->speed > MIN_LANDING_SPEED ) - //if ( ( pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_ucmd.forwardmove != 0 ) && pVeh->m_LandTrace.fraction >= 0.0f ) + if (!FighterOverValidLandingSurface(pVeh) || parentPS->speed > MIN_LANDING_SPEED) + // if ( ( pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_ucmd.forwardmove != 0 ) && pVeh->m_LandTrace.fraction >= 0.0f ) { float fYawDelta; FighterPitchAdjust(pVeh, riderPS, parentPS); #ifdef VEH_CONTROL_SCHEME_4 - FighterPitchClamp( pVeh, riderPS, parentPS, curTime ); -#endif// VEH_CONTROL_SCHEME_4 + FighterPitchClamp(pVeh, riderPS, parentPS, curTime); +#endif // VEH_CONTROL_SCHEME_4 - FighterNoseMalfunctionCheck( pVeh, parentPS ); + FighterNoseMalfunctionCheck(pVeh, parentPS); // Adjust the roll based on the turn amount and dampen it a little. - fYawDelta = AngleSubtract(pVeh->m_vOrientation[YAW], pVeh->m_vPrevOrientation[YAW]); //pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; - if ( fYawDelta > 8.0f ) - { + fYawDelta = + AngleSubtract(pVeh->m_vOrientation[YAW], pVeh->m_vPrevOrientation[YAW]); // pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; + if (fYawDelta > 8.0f) { fYawDelta = 8.0f; - } - else if ( fYawDelta < -8.0f ) - { + } else if (fYawDelta < -8.0f) { fYawDelta = -8.0f; } curRoll -= fYawDelta; - curRoll = PredictedAngularDecrement(0.93f, angleTimeMod*2.0f, curRoll); + curRoll = PredictedAngularDecrement(0.93f, angleTimeMod * 2.0f, curRoll); - //cap it reasonably - //NOTE: was hardcoded to 40.0f, now using extern data + // cap it reasonably + // NOTE: was hardcoded to 40.0f, now using extern data #ifdef VEH_CONTROL_SCHEME_4 - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_pVehicleInfo->rollLimit != -1 ) - { - if (curRoll > pVeh->m_pVehicleInfo->rollLimit ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_pVehicleInfo->rollLimit != -1) { + if (curRoll > pVeh->m_pVehicleInfo->rollLimit) { curRoll = pVeh->m_pVehicleInfo->rollLimit; - } - else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) - { + } else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) { curRoll = -pVeh->m_pVehicleInfo->rollLimit; } } } -#else// VEH_CONTROL_SCHEME_4 - if ( pVeh->m_pVehicleInfo->rollLimit != -1 ) - { - if (curRoll > pVeh->m_pVehicleInfo->rollLimit ) - { +#else // VEH_CONTROL_SCHEME_4 + if (pVeh->m_pVehicleInfo->rollLimit != -1) { + if (curRoll > pVeh->m_pVehicleInfo->rollLimit) { curRoll = pVeh->m_pVehicleInfo->rollLimit; - } - else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) - { + } else if (curRoll < -pVeh->m_pVehicleInfo->rollLimit) { curRoll = -pVeh->m_pVehicleInfo->rollLimit; } } -#endif// VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 } } } // If you are directly impacting the ground, even out your pitch. - if ( isLandingOrLanded ) - {//only if capable of landing - if ( !isDead - && parentPS->electrifyTimem_pVehicleInfo->surfDestruction || !pVeh->m_iRemovedSurfaces ) ) - {//not crashing or spiralling out of control... - if ( pVeh->m_vOrientation[PITCH] > 0 ) + if (isLandingOrLanded) { // only if capable of landing + if (!isDead && parentPS->electrifyTime < curTime && + (!pVeh->m_pVehicleInfo->surfDestruction || !pVeh->m_iRemovedSurfaces)) { // not crashing or spiralling out of control... + if (pVeh->m_vOrientation[PITCH] > 0) { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.2f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); + } else { + pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.75f, angleTimeMod * 10.0f, pVeh->m_vOrientation[PITCH]); + } + } + } + + /* + //NOTE: all this is redundant now since we have the FighterDamageRoutine func... + if ( isDead ) + {//going to explode + //FIXME: maybe make it erratically jerk or spin or start and stop? + if (1) { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.2f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + pVeh->m_ucmd.rightmove = Q_irand( -64, 64 ); } else { - pVeh->m_vOrientation[PITCH] = PredictedAngularDecrement(0.75f, angleTimeMod*10.0f, pVeh->m_vOrientation[PITCH]); + pVeh->m_ucmd.rightmove = 0; + } + pVeh->m_ucmd.forwardmove = Q_irand( -32, 127 ); + pVeh->m_ucmd.upmove = Q_irand( -127, 127 ); + pVeh->m_vOrientation[YAW] += Q_flrand( -10, 10 ); + pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; + if ( pVeh->m_vOrientation[PITCH] > 60.0f ) + { + pVeh->m_vOrientation[PITCH] = 60.0f; + } + if ( pVeh->m_LandTrace.fraction != 0.0f ) + { + parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } } - } - - -/* -//NOTE: all this is redundant now since we have the FighterDamageRoutine func... - if ( isDead ) - {//going to explode - //FIXME: maybe make it erratically jerk or spin or start and stop? - if (1) - { - pVeh->m_ucmd.rightmove = Q_irand( -64, 64 ); - } - else - { - pVeh->m_ucmd.rightmove = 0; - } - pVeh->m_ucmd.forwardmove = Q_irand( -32, 127 ); - pVeh->m_ucmd.upmove = Q_irand( -127, 127 ); - pVeh->m_vOrientation[YAW] += Q_flrand( -10, 10 ); - pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { - pVeh->m_vOrientation[PITCH] = 60.0f; - } - if ( pVeh->m_LandTrace.fraction != 0.0f ) - { - parentPS->velocity[2] -= pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; - } - } -*/ + */ // If no one is in this vehicle and it's up in the sky, pitch it forward as it comes tumbling down. -#ifdef _GAME //never gonna happen on client anyway, we can't be getting predicted unless the predicting client is boarded - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) - && pVeh->m_LandTrace.fraction >= groundFraction - && !FighterIsInSpace( (gentity_t *)parent ) - && !FighterSuspended( pVeh, parentPS ) ) - { +#ifdef _GAME // never gonna happen on client anyway, we can't be getting predicted unless the predicting client is boarded + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh) && pVeh->m_LandTrace.fraction >= groundFraction && !FighterIsInSpace((gentity_t *)parent) && + !FighterSuspended(pVeh, parentPS)) { pVeh->m_ucmd.upmove = 0; - //pVeh->m_ucmd.forwardmove = 0; + // pVeh->m_ucmd.forwardmove = 0; pVeh->m_vOrientation[PITCH] += pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - if ( pVeh->m_vOrientation[PITCH] > 60.0f ) - { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + if (pVeh->m_vOrientation[PITCH] > 60.0f) { pVeh->m_vOrientation[PITCH] = 60.0f; } } } #endif - if ( !parentPS->hackingTime ) - {//use that roll + if (!parentPS->hackingTime) { // use that roll pVeh->m_vOrientation[ROLL] = curRoll; - //NOTE: this seems really backwards... - if ( pVeh->m_vOrientation[ROLL] ) - { //continually adjust the yaw based on the roll.. - if ( (pVeh->m_iRemovedSurfaces||parentPS->electrifyTime>=curTime)//spiralling out of control - && (!(pVeh->m_pParentEntity->s.number%4)||!(pVeh->m_pParentEntity->s.number%5)) ) - {//leave YAW alone - } - else - { - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - { - pVeh->m_vOrientation[YAW] -= ((pVeh->m_vOrientation[ROLL])*0.05f)*pVeh->m_fTimeModifier; + // NOTE: this seems really backwards... + if (pVeh->m_vOrientation[ROLL]) { // continually adjust the yaw based on the roll.. + if ((pVeh->m_iRemovedSurfaces || parentPS->electrifyTime >= curTime) // spiralling out of control + && (!(pVeh->m_pParentEntity->s.number % 4) || !(pVeh->m_pParentEntity->s.number % 5))) { // leave YAW alone + } else { + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { + pVeh->m_vOrientation[YAW] -= ((pVeh->m_vOrientation[ROLL]) * 0.05f) * pVeh->m_fTimeModifier; } } } - } - else - {//add in strafing roll - float strafeRoll = (parentPS->hackingTime/MAX_STRAFE_TIME)*pVeh->m_pVehicleInfo->rollLimit;//pVeh->m_pVehicleInfo->bankingSpeed* + } else { // add in strafing roll + float strafeRoll = (parentPS->hackingTime / MAX_STRAFE_TIME) * pVeh->m_pVehicleInfo->rollLimit; // pVeh->m_pVehicleInfo->bankingSpeed* float strafeDif = AngleSubtract(strafeRoll, pVeh->m_vOrientation[ROLL]); - pVeh->m_vOrientation[ROLL] += (strafeDif*0.1f)*pVeh->m_fTimeModifier; - if ( !BG_UnrestrainedPitchRoll( riderPS, pVeh ) ) - {//cap it reasonably - if ( pVeh->m_pVehicleInfo->rollLimit != -1 - && !pVeh->m_iRemovedSurfaces - && parentPS->electrifyTimem_vOrientation[ROLL] > pVeh->m_pVehicleInfo->rollLimit ) - { + pVeh->m_vOrientation[ROLL] += (strafeDif * 0.1f) * pVeh->m_fTimeModifier; + if (!BG_UnrestrainedPitchRoll(riderPS, pVeh)) { // cap it reasonably + if (pVeh->m_pVehicleInfo->rollLimit != -1 && !pVeh->m_iRemovedSurfaces && parentPS->electrifyTime < curTime) { + if (pVeh->m_vOrientation[ROLL] > pVeh->m_pVehicleInfo->rollLimit) { pVeh->m_vOrientation[ROLL] = pVeh->m_pVehicleInfo->rollLimit; - } - else if (pVeh->m_vOrientation[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) - { + } else if (pVeh->m_vOrientation[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) { pVeh->m_vOrientation[ROLL] = -pVeh->m_pVehicleInfo->rollLimit; } } } } - if (pVeh->m_pVehicleInfo->surfDestruction) - { + if (pVeh->m_pVehicleInfo->surfDestruction) { FighterDamageRoutine(pVeh, parent, parentPS, riderPS, isDead); } - pVeh->m_vOrientation[ROLL] = AngleNormalize180( pVeh->m_vOrientation[ROLL] ); + pVeh->m_vOrientation[ROLL] = AngleNormalize180(pVeh->m_vOrientation[ROLL]); /********************************************************************************/ /* END Here is where make sure the vehicle is properly oriented. END */ /********************************************************************************/ } -#ifdef _GAME //ONLY on server, not cgame +#ifdef _GAME // ONLY on server, not cgame // This function makes sure that the vehicle is properly animated. -static void AnimateVehicle( Vehicle_t *pVeh ) -{ +static void AnimateVehicle(Vehicle_t *pVeh) { int Anim = -1; int iFlags = SETANIM_FLAG_NORMAL; qboolean isLanding = qfalse, isLanded = qfalse; playerState_t *parentPS = pVeh->m_pParentEntity->playerState; int curTime = level.time; - if ( parentPS->hyperSpaceTime - && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME ) - {//Going to Hyperspace - //close the wings (FIXME: makes sense on X-Wing, not Shuttle?) - if ( pVeh->m_ulFlags & VEH_WINGSOPEN ) - { + if (parentPS->hyperSpaceTime && curTime - parentPS->hyperSpaceTime < HYPERSPACE_TIME) { // Going to Hyperspace + // close the wings (FIXME: makes sense on X-Wing, not Shuttle?) + if (pVeh->m_ulFlags & VEH_WINGSOPEN) { pVeh->m_ulFlags &= ~VEH_WINGSOPEN; Anim = BOTH_WINGS_CLOSE; } - } - else - { - isLanding = FighterIsLanding( pVeh, parentPS ); - isLanded = FighterIsLanded( pVeh, parentPS ); + } else { + isLanding = FighterIsLanding(pVeh, parentPS); + isLanded = FighterIsLanded(pVeh, parentPS); // if we're above launch height (way up in the air)... - if ( !isLanding && !isLanded ) - { - if ( !( pVeh->m_ulFlags & VEH_WINGSOPEN ) ) - { + if (!isLanding && !isLanded) { + if (!(pVeh->m_ulFlags & VEH_WINGSOPEN)) { pVeh->m_ulFlags |= VEH_WINGSOPEN; pVeh->m_ulFlags &= ~VEH_GEARSOPEN; Anim = BOTH_WINGS_OPEN; } } // otherwise we're below launch height and still taking off. - else - { - if ( (pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0||isLanded) - && pVeh->m_LandTrace.fraction <= 0.4f - && pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE ) - {//already landed or trying to land and close to ground + else { + if ((pVeh->m_ucmd.forwardmove < 0 || pVeh->m_ucmd.upmove < 0 || isLanded) && pVeh->m_LandTrace.fraction <= 0.4f && + pVeh->m_LandTrace.plane.normal[2] >= MIN_LANDING_SLOPE) { // already landed or trying to land and close to ground // Open gears. - if ( !( pVeh->m_ulFlags & VEH_GEARSOPEN ) ) - { - if ( pVeh->m_pVehicleInfo->soundLand ) - {//just landed? - G_EntitySound( ((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand ); + if (!(pVeh->m_ulFlags & VEH_GEARSOPEN)) { + if (pVeh->m_pVehicleInfo->soundLand) { // just landed? + G_EntitySound(((gentity_t *)(pVeh->m_pParentEntity)), CHAN_AUTO, pVeh->m_pVehicleInfo->soundLand); } pVeh->m_ulFlags |= VEH_GEARSOPEN; Anim = BOTH_GEARS_OPEN; } - } - else - {//trying to take off and almost halfway off the ground + } else { // trying to take off and almost halfway off the ground // Close gears (if they're open). - if ( pVeh->m_ulFlags & VEH_GEARSOPEN ) - { + if (pVeh->m_ulFlags & VEH_GEARSOPEN) { pVeh->m_ulFlags &= ~VEH_GEARSOPEN; Anim = BOTH_GEARS_CLOSE; - //iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + // iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; } // If gears are closed, and we are below launch height, close the wings. - else - { - if ( pVeh->m_ulFlags & VEH_WINGSOPEN ) - { + else { + if (pVeh->m_ulFlags & VEH_WINGSOPEN) { pVeh->m_ulFlags &= ~VEH_WINGSOPEN; Anim = BOTH_WINGS_CLOSE; } @@ -1756,53 +1374,49 @@ static void AnimateVehicle( Vehicle_t *pVeh ) } } - if ( Anim != -1 ) - { + if (Anim != -1) { BG_SetAnim(pVeh->m_pParentEntity->playerState, bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags); } } // This function makes sure that the rider's in this vehicle are properly animated. -static void AnimateRiders( Vehicle_t *pVeh ) -{ -} +static void AnimateRiders(Vehicle_t *pVeh) {} -#endif //game-only +#endif // game-only #ifdef _CGAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -void G_SetFighterVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ -#ifdef _GAME //ONLY in SP or on server, not cgame - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; - pVehInfo->Board = Board; - pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; +void G_SetFighterVehicleFunctions(vehicleInfo_t *pVehInfo) { +#ifdef _GAME // ONLY in SP or on server, not cgame + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; -#endif //game-only - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; +#endif // game-only + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifdef _CGAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifdef _CGAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -1811,20 +1425,18 @@ extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif // Create/Allocate a new Animal Vehicle (initializing it as well). -void G_CreateFighterNPC( Vehicle_t **pVeh, const char *strType ) -{ +void G_CreateFighterNPC(Vehicle_t **pVeh, const char *strType) { // Allocate the Vehicle. #ifdef _GAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strType)]; } diff --git a/codemp/game/NPC.c b/codemp/game/NPC.c index c199544276..3e56074b1b 100644 --- a/codemp/game/NPC.c +++ b/codemp/game/NPC.c @@ -30,88 +30,76 @@ along with this program; if not, see . extern vec3_t playerMins; extern vec3_t playerMaxs; -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); -extern void NPC_BSNoClip ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_ApplyRoff (void); -extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern void NPC_CheckPlayerAim ( void ); -extern void NPC_CheckAllClear ( void ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void Mark1_dying( gentity_t *self ); -extern void NPC_BSCinematic( void ); -extern int GetTime ( int lastTime ); -extern void NPC_BSGM_Default( void ); -extern void NPC_CheckCharmed( void ); -extern qboolean Boba_Flying( gentity_t *self ); - -//Local Variables +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); +extern void NPC_BSNoClip(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_ApplyRoff(void); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern void NPC_CheckPlayerAim(void); +extern void NPC_CheckAllClear(void); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void Mark1_dying(gentity_t *self); +extern void NPC_BSCinematic(void); +extern int GetTime(int lastTime); +extern void NPC_BSGM_Default(void); +extern void NPC_CheckCharmed(void); +extern qboolean Boba_Flying(gentity_t *self); + +// Local Variables npcStatic_t NPCS; -void NPC_SetAnim(gentity_t *ent,int type,int anim,int priority); -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); -extern void GM_Dying( gentity_t *self ); +void NPC_SetAnim(gentity_t *ent, int type, int anim, int priority); +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope); +extern void GM_Dying(gentity_t *self); extern int eventClearTime; -void CorpsePhysics( gentity_t *self ) -{ +void CorpsePhysics(gentity_t *self) { // run the bot through the server like it was a real client - memset( &NPCS.ucmd, 0, sizeof( NPCS.ucmd ) ); - ClientThink( self->s.number, &NPCS.ucmd ); - //VectorCopy( self->s.origin, self->s.origin2 ); - //rww - don't get why this is happening. + memset(&NPCS.ucmd, 0, sizeof(NPCS.ucmd)); + ClientThink(self->s.number, &NPCS.ucmd); + // VectorCopy( self->s.origin, self->s.origin2 ); + // rww - don't get why this is happening. - if ( self->client->NPC_class == CLASS_GALAKMECH ) - { - GM_Dying( self ); + if (self->client->NPC_class == CLASS_GALAKMECH) { + GM_Dying(self); } - //FIXME: match my pitch and roll for the slope of my groundPlane - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->s.eFlags&EF_DISINTEGRATION) ) - {//on the ground - //FIXME: check 4 corners - pitch_roll_for_slope( self, NULL ); + // FIXME: match my pitch and roll for the slope of my groundPlane + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !(self->s.eFlags & EF_DISINTEGRATION)) { // on the ground + // FIXME: check 4 corners + pitch_roll_for_slope(self, NULL); } - if ( eventClearTime == level.time + ALERT_CLEAR_TIME ) - {//events were just cleared out so add me again - if ( !(self->client->ps.eFlags&EF_NODRAW) ) - { - AddSightEvent( self->enemy, self->r.currentOrigin, 384, AEL_DISCOVERED, 0.0f ); + if (eventClearTime == level.time + ALERT_CLEAR_TIME) { // events were just cleared out so add me again + if (!(self->client->ps.eFlags & EF_NODRAW)) { + AddSightEvent(self->enemy, self->r.currentOrigin, 384, AEL_DISCOVERED, 0.0f); } } - if ( level.time - self->s.time > 3000 ) - {//been dead for 3 seconds - if ( g_dismember.integer < 11381138 && !g_saberRealisticCombat.integer ) - {//can't be dismembered once dead - if ( self->client->NPC_class != CLASS_PROTOCOL ) - { - // self->client->dismembered = qtrue; + if (level.time - self->s.time > 3000) { // been dead for 3 seconds + if (g_dismember.integer < 11381138 && !g_saberRealisticCombat.integer) { // can't be dismembered once dead + if (self->client->NPC_class != CLASS_PROTOCOL) { + // self->client->dismembered = qtrue; } } } - //if ( level.time - self->s.time > 500 ) - if (self->client->respawnTime < (level.time+500)) - {//don't turn "nonsolid" until about 1 second after actual death + // if ( level.time - self->s.time > 500 ) + if (self->client->respawnTime < (level.time + 500)) { // don't turn "nonsolid" until about 1 second after actual death - if (self->client->ps.eFlags & EF_DISINTEGRATION) - { + if (self->client->ps.eFlags & EF_DISINTEGRATION) { self->r.contents = 0; - } - else if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. + } else if ((self->client->NPC_class != CLASS_MARK1) && (self->client->NPC_class != CLASS_INTERROGATOR)) // The Mark1 & Interrogator stays solid. { self->r.contents = CONTENTS_CORPSE; - //self->r.maxs[2] = -8; + // self->r.maxs[2] = -8; } - if ( self->message ) - { + if (self->message) { self->r.contents |= CONTENTS_TRIGGER; } } @@ -124,71 +112,57 @@ NPC_RemoveBody Determines when it's ok to ditch the corpse ---------------------------------------- */ -#define REMOVE_DISTANCE 128 +#define REMOVE_DISTANCE 128 #define REMOVE_DISTANCE_SQR (REMOVE_DISTANCE * REMOVE_DISTANCE) -void NPC_RemoveBody( gentity_t *self ) -{ - CorpsePhysics( self ); +void NPC_RemoveBody(gentity_t *self) { + CorpsePhysics(self); self->nextthink = level.time + FRAMETIME; - if ( self->NPC->nextBStateThink <= level.time ) - { + if (self->NPC->nextBStateThink <= level.time) { trap->ICARUS_MaintainTaskManager(self->s.number); } self->NPC->nextBStateThink = level.time + FRAMETIME; - if ( self->message ) - {//I still have a key + if (self->message) { // I still have a key return; } // I don't consider this a hack, it's creative coding . . . // I agree, very creative... need something like this for ATST and GALAKMECH too! - if (self->client->NPC_class == CLASS_MARK1) - { - Mark1_dying( self ); + if (self->client->NPC_class == CLASS_MARK1) { + Mark1_dying(self); } // Since these blow up, remove the bounding box. - if ( self->client->NPC_class == CLASS_REMOTE - || self->client->NPC_class == CLASS_SENTRY - || self->client->NPC_class == CLASS_PROBE - || self->client->NPC_class == CLASS_INTERROGATOR - || self->client->NPC_class == CLASS_MARK2 ) - { - //if ( !self->taskManager || !self->taskManager->IsRunning() ) - if (!trap->ICARUS_IsRunning(self->s.number)) - { - if ( !self->activator || !self->activator->client || !(self->activator->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//not being held by a Rancor - G_FreeEntity( self ); + if (self->client->NPC_class == CLASS_REMOTE || self->client->NPC_class == CLASS_SENTRY || self->client->NPC_class == CLASS_PROBE || + self->client->NPC_class == CLASS_INTERROGATOR || self->client->NPC_class == CLASS_MARK2) { + // if ( !self->taskManager || !self->taskManager->IsRunning() ) + if (!trap->ICARUS_IsRunning(self->s.number)) { + if (!self->activator || !self->activator->client || !(self->activator->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // not being held by a Rancor + G_FreeEntity(self); } } return; } - //FIXME: don't ever inflate back up? + // FIXME: don't ever inflate back up? self->r.maxs[2] = self->client->renderInfo.eyePoint[2] - self->r.currentOrigin[2] + 4; - if ( self->r.maxs[2] < -8 ) - { + if (self->r.maxs[2] < -8) { self->r.maxs[2] = -8; } - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//never disappears + if (self->client->NPC_class == CLASS_GALAKMECH) { // never disappears return; } - if ( self->NPC && self->NPC->timeOfDeath <= level.time ) - { + if (self->NPC && self->NPC->timeOfDeath <= level.time) { self->NPC->timeOfDeath = level.time + 1000; // Only do all of this nonsense for Scav boys ( and girls ) - /// if ( self->client->playerTeam == NPCTEAM_SCAVENGERS || self->client->playerTeam == NPCTEAM_KLINGON - // || self->client->playerTeam == NPCTEAM_HIROGEN || self->client->playerTeam == NPCTEAM_MALON ) + /// if ( self->client->playerTeam == NPCTEAM_SCAVENGERS || self->client->playerTeam == NPCTEAM_KLINGON + // || self->client->playerTeam == NPCTEAM_HIROGEN || self->client->playerTeam == NPCTEAM_MALON ) // should I check NPC_class here instead of TEAM ? - dmv - if( self->client->playerTeam == NPCTEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL ) - { + if (self->client->playerTeam == NPCTEAM_ENEMY || self->client->NPC_class == CLASS_PROTOCOL) { self->nextthink = level.time + FRAMETIME; // try back in a second /* @@ -205,31 +179,27 @@ void NPC_RemoveBody( gentity_t *self ) } } */ - //Don't care about this for MP I guess. + // Don't care about this for MP I guess. } - //FIXME: there are some conditions - such as heavy combat - in which we want + // FIXME: there are some conditions - such as heavy combat - in which we want // to remove the bodies... but in other cases it's just weird, like // when they're right behind you in a closed room and when they've been // placed as dead NPCs by a designer... // For now we just assume that a corpse with no enemy was // placed in the map as a corpse - if ( self->enemy ) - { - //if ( !self->taskManager || !self->taskManager->IsRunning() ) - if (!trap->ICARUS_IsRunning(self->s.number)) - { - if ( !self->activator || !self->activator->client || !(self->activator->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//not being held by a Rancor - if ( self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD ) - { + if (self->enemy) { + // if ( !self->taskManager || !self->taskManager->IsRunning() ) + if (!trap->ICARUS_IsRunning(self->s.number)) { + if (!self->activator || !self->activator->client || !(self->activator->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // not being held by a + // Rancor + if (self->client && self->client->ps.saberEntityNum > 0 && self->client->ps.saberEntityNum < ENTITYNUM_WORLD) { gentity_t *saberent = &g_entities[self->client->ps.saberEntityNum]; - if ( saberent ) - { - G_FreeEntity( saberent ); + if (saberent) { + G_FreeEntity(saberent); } } - G_FreeEntity( self ); + G_FreeEntity(self); } } } @@ -244,21 +214,19 @@ Determines when it's ok to ditch the corpse ---------------------------------------- */ -int BodyRemovalPadTime( gentity_t *ent ) -{ - int time; +int BodyRemovalPadTime(gentity_t *ent) { + int time; - if ( !ent || !ent->client ) + if (!ent || !ent->client) return 0; // team no longer indicates species/race, so in this case we'd use NPC_class, but - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_MOUSE: case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_PROBE: @@ -270,18 +238,15 @@ int BodyRemovalPadTime( gentity_t *ent ) break; default: // never go away - // time = Q3_INFINITE; + // time = Q3_INFINITE; // for now I'm making default 10000 time = 10000; break; - } - return time; } - /* ---------------------------------------- NPC_RemoveBodyEffect @@ -290,19 +255,17 @@ Effect to be applied when ditching the corpse ---------------------------------------- */ -static void NPC_RemoveBodyEffect(void) -{ -// vec3_t org; -// gentity_t *tent; +static void NPC_RemoveBodyEffect(void) { + // vec3_t org; + // gentity_t *tent; - if ( !NPCS.NPC || !NPCS.NPC->client || (NPCS.NPC->s.eFlags & EF_NODRAW) ) + if (!NPCS.NPC || !NPCS.NPC->client || (NPCS.NPC->s.eFlags & EF_NODRAW)) return; // team no longer indicates species/race, so in this case we'd use NPC_class, but // stub code - switch(NPCS.NPC->client->NPC_class) - { + switch (NPCS.NPC->client->NPC_class) { case CLASS_PROBE: case CLASS_SEEKER: case CLASS_REMOTE: @@ -310,24 +273,21 @@ static void NPC_RemoveBodyEffect(void) case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: - //case CLASS_PROTOCOL: + // case CLASS_PROTOCOL: case CLASS_MARK1: case CLASS_MARK2: case CLASS_INTERROGATOR: case CLASS_ATST: // yeah, this is a little weird, but for now I'm listing all droids - // VectorCopy( NPC->r.currentOrigin, org ); - // org[2] -= 16; - // tent = G_TempEntity( org, EV_BOT_EXPLODE ); - // tent->owner = NPC; + // VectorCopy( NPC->r.currentOrigin, org ); + // org[2] -= 16; + // tent = G_TempEntity( org, EV_BOT_EXPLODE ); + // tent->owner = NPC; break; default: break; } - - } - /* ==================================================================== void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ) @@ -342,140 +302,124 @@ and returns. ==================================================================== */ -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ) -{ - vec3_t slope; - vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = { 0, 0, 0 }; - float pitch, mod, dot; +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope) { + vec3_t slope; + vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = {0, 0, 0}; + float pitch, mod, dot; - //if we don't have a slope, get one - if( !pass_slope || VectorCompare( vec3_origin, pass_slope ) ) - { + // if we don't have a slope, get one + if (!pass_slope || VectorCompare(vec3_origin, pass_slope)) { trace_t trace; - VectorCopy( forwhom->r.currentOrigin, startspot ); + VectorCopy(forwhom->r.currentOrigin, startspot); startspot[2] += forwhom->r.mins[2] + 4; - VectorCopy( startspot, endspot ); + VectorCopy(startspot, endspot); endspot[2] -= 300; - trap->Trace( &trace, forwhom->r.currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, qfalse, 0, 0 ); -// if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) -// forwhom.flags(-)FL_ONGROUND; + trap->Trace(&trace, forwhom->r.currentOrigin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID, qfalse, 0, 0); + // if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) + // forwhom.flags(-)FL_ONGROUND; - if ( trace.fraction >= 1.0 ) + if (trace.fraction >= 1.0) return; - if ( VectorCompare( vec3_origin, trace.plane.normal ) ) + if (VectorCompare(vec3_origin, trace.plane.normal)) return; - VectorCopy( trace.plane.normal, slope ); - } - else - { - VectorCopy( pass_slope, slope ); + VectorCopy(trace.plane.normal, slope); + } else { + VectorCopy(pass_slope, slope); } - AngleVectors( forwhom->r.currentAngles, ovf, ovr, NULL ); + AngleVectors(forwhom->r.currentAngles, ovf, ovr, NULL); - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod<0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); - if ( forwhom->client ) - { + if (forwhom->client) { float oldmins2; forwhom->client->ps.viewangles[PITCH] = dot * pitch; - forwhom->client->ps.viewangles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->client->ps.viewangles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); oldmins2 = forwhom->r.mins[2]; - forwhom->r.mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH])/180.0f; - //FIXME: if it gets bigger, move up - if ( oldmins2 > forwhom->r.mins[2] ) - {//our mins is now lower, need to move up - //FIXME: trace? + forwhom->r.mins[2] = -24 + 12 * fabs(forwhom->client->ps.viewangles[PITCH]) / 180.0f; + // FIXME: if it gets bigger, move up + if (oldmins2 > forwhom->r.mins[2]) { // our mins is now lower, need to move up + // FIXME: trace? forwhom->client->ps.origin[2] += (oldmins2 - forwhom->r.mins[2]); forwhom->r.currentOrigin[2] = forwhom->client->ps.origin[2]; - trap->LinkEntity( (sharedEntity_t *)forwhom ); + trap->LinkEntity((sharedEntity_t *)forwhom); } - } - else - { + } else { forwhom->r.currentAngles[PITCH] = dot * pitch; - forwhom->r.currentAngles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + forwhom->r.currentAngles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } } - /* ---------------------------------------- DeadThink ---------------------------------------- */ -static void DeadThink ( void ) -{ - trace_t trace; +static void DeadThink(void) { + trace_t trace; - //HACKHACKHACKHACKHACK - //We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only - //FIXME: don't ever inflate back up? + // HACKHACKHACKHACKHACK + // We should really have a seperate G2 bounding box (seperate from the physics bbox) for G2 collisions only + // FIXME: don't ever inflate back up? NPCS.NPC->r.maxs[2] = NPCS.NPC->client->renderInfo.eyePoint[2] - NPCS.NPC->r.currentOrigin[2] + 4; - if ( NPCS.NPC->r.maxs[2] < -8 ) - { + if (NPCS.NPC->r.maxs[2] < -8) { NPCS.NPC->r.maxs[2] = -8; } - if ( VectorCompare( NPCS.NPC->client->ps.velocity, vec3_origin ) ) - {//not flying through the air - if ( NPCS.NPC->r.mins[0] > -32 ) - { + if (VectorCompare(NPCS.NPC->client->ps.velocity, vec3_origin)) { // not flying through the air + if (NPCS.NPC->r.mins[0] > -32) { NPCS.NPC->r.mins[0] -= 1; - trap->Trace (&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid ) - { + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, + NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.allsolid) { NPCS.NPC->r.mins[0] += 1; } } - if ( NPCS.NPC->r.maxs[0] < 32 ) - { + if (NPCS.NPC->r.maxs[0] < 32) { NPCS.NPC->r.maxs[0] += 1; - trap->Trace (&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid ) - { + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, + NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.allsolid) { NPCS.NPC->r.maxs[0] -= 1; } } - if ( NPCS.NPC->r.mins[1] > -32 ) - { + if (NPCS.NPC->r.mins[1] > -32) { NPCS.NPC->r.mins[1] -= 1; - trap->Trace (&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid ) - { + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, + NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.allsolid) { NPCS.NPC->r.mins[1] += 1; } } - if ( NPCS.NPC->r.maxs[1] < 32 ) - { + if (NPCS.NPC->r.maxs[1] < 32) { NPCS.NPC->r.maxs[1] += 1; - trap->Trace (&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid ) - { + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, + NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.allsolid) { NPCS.NPC->r.maxs[1] -= 1; } } } - //HACKHACKHACKHACKHACK + // HACKHACKHACKHACKHACK - //FIXME: tilt and fall off of ledges? - //NPC_PostDeathThink(); + // FIXME: tilt and fall off of ledges? + // NPC_PostDeathThink(); /* if ( !NPCInfo->timeOfDeath && NPC->client != NULL && NPCInfo != NULL ) @@ -496,41 +440,36 @@ static void DeadThink ( void ) else */ { - //death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove - if ( level.time >= NPCS.NPCInfo->timeOfDeath + BodyRemovalPadTime( NPCS.NPC ) ) - { - if ( NPCS.NPC->client->ps.eFlags & EF_NODRAW ) - { + // death anim done (or were given a specific amount of time to wait before removal), wait the requisite amount of time them remove + if (level.time >= NPCS.NPCInfo->timeOfDeath + BodyRemovalPadTime(NPCS.NPC)) { + if (NPCS.NPC->client->ps.eFlags & EF_NODRAW) { if (!trap->ICARUS_IsRunning(NPCS.NPC->s.number)) - //if ( !NPC->taskManager || !NPC->taskManager->IsRunning() ) + // if ( !NPC->taskManager || !NPC->taskManager->IsRunning() ) { NPCS.NPC->think = G_FreeEntity; NPCS.NPC->nextthink = level.time + FRAMETIME; } - } - else - { - class_t npc_class; + } else { + class_t npc_class; // Start the body effect first, then delay 400ms before ditching the corpse NPC_RemoveBodyEffect(); - //FIXME: keep it running through physics somehow? + // FIXME: keep it running through physics somehow? NPCS.NPC->think = NPC_RemoveBody; NPCS.NPC->nextthink = level.time + FRAMETIME; - // if ( NPC->client->playerTeam == NPCTEAM_FORGE ) - // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - // else if ( NPC->client->playerTeam == NPCTEAM_BOTS ) + // if ( NPC->client->playerTeam == NPCTEAM_FORGE ) + // NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; + // else if ( NPC->client->playerTeam == NPCTEAM_BOTS ) npc_class = NPCS.NPC->client->NPC_class; // check for droids - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_MARK2 || npc_class == CLASS_SENTRY )//npc_class == CLASS_PROTOCOL || + if (npc_class == CLASS_SEEKER || npc_class == CLASS_REMOTE || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_MARK2 || + npc_class == CLASS_SENTRY) // npc_class == CLASS_PROTOCOL || { NPCS.NPC->client->ps.eFlags |= EF_NODRAW; NPCS.NPCInfo->timeOfDeath = level.time + FRAMETIME * 8; - } - else + } else NPCS.NPCInfo->timeOfDeath = level.time + FRAMETIME * 4; } return; @@ -538,21 +477,18 @@ static void DeadThink ( void ) } // If the player is on the ground and the resting position contents haven't been set yet...(BounceCount tracks the contents) - if ( NPCS.NPC->bounceCount < 0 && NPCS.NPC->s.groundEntityNum >= 0 ) - { + if (NPCS.NPC->bounceCount < 0 && NPCS.NPC->s.groundEntityNum >= 0) { // if client is in a nodrop area, make him/her nodraw - int contents = NPCS.NPC->bounceCount = trap->PointContents( NPCS.NPC->r.currentOrigin, -1 ); + int contents = NPCS.NPC->bounceCount = trap->PointContents(NPCS.NPC->r.currentOrigin, -1); - if ( ( contents & CONTENTS_NODROP ) ) - { + if ((contents & CONTENTS_NODROP)) { NPCS.NPC->client->ps.eFlags |= EF_NODRAW; } } - CorpsePhysics( NPCS.NPC ); + CorpsePhysics(NPCS.NPC); } - /* =============== SetNPCGlobals @@ -560,141 +496,114 @@ SetNPCGlobals local function to set globals used throughout the AI code =============== */ -void SetNPCGlobals( gentity_t *ent ) -{ +void SetNPCGlobals(gentity_t *ent) { NPCS.NPC = ent; NPCS.NPCInfo = ent->NPC; NPCS.client = ent->client; - memset( &NPCS.ucmd, 0, sizeof( usercmd_t ) ); + memset(&NPCS.ucmd, 0, sizeof(usercmd_t)); } npcStatic_t _saved_NPCS; -void SaveNPCGlobals(void) -{ - memcpy( &_saved_NPCS, &NPCS, sizeof( _saved_NPCS ) ); -} +void SaveNPCGlobals(void) { memcpy(&_saved_NPCS, &NPCS, sizeof(_saved_NPCS)); } -void RestoreNPCGlobals(void) -{ - memcpy( &NPCS, &_saved_NPCS, sizeof( _saved_NPCS ) ); -} +void RestoreNPCGlobals(void) { memcpy(&NPCS, &_saved_NPCS, sizeof(_saved_NPCS)); } -//We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC -void ClearNPCGlobals( void ) -{ +// We MUST do this, other funcs were using NPC illegally when "self" wasn't the global NPC +void ClearNPCGlobals(void) { NPCS.NPC = NULL; NPCS.NPCInfo = NULL; NPCS.client = NULL; } //=============== -extern qboolean showBBoxes; +extern qboolean showBBoxes; vec3_t NPCDEBUG_RED = {1.0, 0.0, 0.0}; vec3_t NPCDEBUG_GREEN = {0.0, 1.0, 0.0}; vec3_t NPCDEBUG_BLUE = {0.0, 0.0, 1.0}; vec3_t NPCDEBUG_LIGHT_BLUE = {0.3f, 0.7f, 1.0}; -extern void G_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void G_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); -extern void G_Cylinder( vec3_t start, vec3_t end, float radius, vec3_t color ); - -void NPC_ShowDebugInfo (void) -{ - if ( showBBoxes ) - { - gentity_t *found = NULL; - vec3_t mins, maxs; - - while( (found = G_Find( found, FOFS(classname), "NPC" ) ) != NULL ) - { - if ( trap->InPVS( found->r.currentOrigin, g_entities[0].r.currentOrigin ) ) - { - VectorAdd( found->r.currentOrigin, found->r.mins, mins ); - VectorAdd( found->r.currentOrigin, found->r.maxs, maxs ); - G_Cube( mins, maxs, NPCDEBUG_RED, 0.25 ); +extern void G_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void G_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); +extern void G_Cylinder(vec3_t start, vec3_t end, float radius, vec3_t color); + +void NPC_ShowDebugInfo(void) { + if (showBBoxes) { + gentity_t *found = NULL; + vec3_t mins, maxs; + + while ((found = G_Find(found, FOFS(classname), "NPC")) != NULL) { + if (trap->InPVS(found->r.currentOrigin, g_entities[0].r.currentOrigin)) { + VectorAdd(found->r.currentOrigin, found->r.mins, mins); + VectorAdd(found->r.currentOrigin, found->r.maxs, maxs); + G_Cube(mins, maxs, NPCDEBUG_RED, 0.25); } } } } -void NPC_ApplyScriptFlags (void) -{ - if ( NPCS.NPCInfo->scriptFlags & SCF_CROUCHED ) - { - if ( NPCS.NPCInfo->charmedTime > level.time && (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the crouched command - } - else - { +void NPC_ApplyScriptFlags(void) { + if (NPCS.NPCInfo->scriptFlags & SCF_CROUCHED) { + if (NPCS.NPCInfo->charmedTime > level.time && + (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove)) { // ugh, if charmed and moving, ignore the crouched command + } else { NPCS.ucmd.upmove = -127; } } - if(NPCS.NPCInfo->scriptFlags & SCF_RUNNING) - { + if (NPCS.NPCInfo->scriptFlags & SCF_RUNNING) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - } - else if(NPCS.NPCInfo->scriptFlags & SCF_WALKING) - { - if ( NPCS.NPCInfo->charmedTime > level.time && (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove) ) - {//ugh, if charmed and moving, ignore the walking command - } - else - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_WALKING) { + if (NPCS.NPCInfo->charmedTime > level.time && (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove)) { // ugh, if charmed and moving, ignore the walking + // command + } else { NPCS.ucmd.buttons |= BUTTON_WALKING; } } -/* - if(NPCInfo->scriptFlags & SCF_CAREFUL) - { - ucmd.buttons |= BUTTON_CAREFUL; - } -*/ - if(NPCS.NPCInfo->scriptFlags & SCF_LEAN_RIGHT) - { + /* + if(NPCInfo->scriptFlags & SCF_CAREFUL) + { + ucmd.buttons |= BUTTON_CAREFUL; + } + */ + if (NPCS.NPCInfo->scriptFlags & SCF_LEAN_RIGHT) { NPCS.ucmd.buttons |= BUTTON_USE; NPCS.ucmd.rightmove = 127; NPCS.ucmd.forwardmove = 0; NPCS.ucmd.upmove = 0; - } - else if(NPCS.NPCInfo->scriptFlags & SCF_LEAN_LEFT) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LEAN_LEFT) { NPCS.ucmd.buttons |= BUTTON_USE; NPCS.ucmd.rightmove = -127; NPCS.ucmd.forwardmove = 0; NPCS.ucmd.upmove = 0; } - if ( (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) && (NPCS.ucmd.buttons & BUTTON_ATTACK) ) - {//Use altfire instead + if ((NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) && (NPCS.ucmd.buttons & BUTTON_ATTACK)) { // Use altfire instead NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; } } -void Q3_DebugPrint( int level, const char *format, ... ); -void NPC_HandleAIFlags (void) -{ - //FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers - if ( NPCS.NPCInfo->aiFlags & NPCAI_LOST ) - {//Print that you need help! - //FIXME: shouldn't remove this just yet if cg_draw needs it +void Q3_DebugPrint(int level, const char *format, ...); +void NPC_HandleAIFlags(void) { + // FIXME: make these flags checks a function call like NPC_CheckAIFlagsAndTimers + if (NPCS.NPCInfo->aiFlags & NPCAI_LOST) { // Print that you need help! + // FIXME: shouldn't remove this just yet if cg_draw needs it NPCS.NPCInfo->aiFlags &= ~NPCAI_LOST; /* if ( showWaypoints ) { - Q3_DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, NPC->waypoint, NPCInfo->goalEntity->waypoint ); + Q3_DebugPrint(WL_WARNING, "%s can't navigate to target %s (my wp: %d, goal wp: %d)\n", NPC->targetname, NPCInfo->goalEntity->targetname, + NPC->waypoint, NPCInfo->goalEntity->waypoint ); } */ - if ( NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//We can't nav to our enemy - //Drop enemy and see if we should search for him + if (NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // We can't nav to our enemy + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); } } - //MRJ Request: + // MRJ Request: /* if ( NPCInfo->aiFlags & NPCAI_GREET_ALLIES && !NPC->enemy )//what if "enemy" is the greetEnt? {//If no enemy, look for teammates to greet @@ -744,106 +653,89 @@ void NPC_HandleAIFlags (void) } } */ - //been told to play a victory sound after a delay - if ( NPCS.NPCInfo->greetingDebounceTime && NPCS.NPCInfo->greetingDebounceTime < level.time ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand( 2000, 4000 ) ); + // been told to play a victory sound after a delay + if (NPCS.NPCInfo->greetingDebounceTime && NPCS.NPCInfo->greetingDebounceTime < level.time) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), Q_irand(2000, 4000)); NPCS.NPCInfo->greetingDebounceTime = 0; } - if ( NPCS.NPCInfo->ffireCount > 0 ) - { - if ( NPCS.NPCInfo->ffireFadeDebounce < level.time ) - { + if (NPCS.NPCInfo->ffireCount > 0) { + if (NPCS.NPCInfo->ffireFadeDebounce < level.time) { NPCS.NPCInfo->ffireCount--; - //Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_npcspskill.integer)*2) ); + // Com_Printf( "drop: %d < %d\n", NPCInfo->ffireCount, 3+((2-g_npcspskill.integer)*2) ); NPCS.NPCInfo->ffireFadeDebounce = level.time + 3000; } } - if ( d_patched.integer ) - {//use patch-style navigation - if ( NPCS.NPCInfo->consecutiveBlockedMoves > 20 ) - {//been stuck for a while, try again? + if (d_patched.integer) { // use patch-style navigation + if (NPCS.NPCInfo->consecutiveBlockedMoves > 20) { // been stuck for a while, try again? NPCS.NPCInfo->consecutiveBlockedMoves = 0; } } } -void NPC_AvoidWallsAndCliffs (void) -{ +void NPC_AvoidWallsAndCliffs(void) { //... } -void NPC_CheckAttackScript(void) -{ - if(!(NPCS.ucmd.buttons & BUTTON_ATTACK)) - { +void NPC_CheckAttackScript(void) { + if (!(NPCS.ucmd.buttons & BUTTON_ATTACK)) { return; } G_ActivateBehavior(NPCS.NPC, BSET_ATTACK); } -float NPC_MaxDistSquaredForWeapon (void); -void NPC_CheckAttackHold(void) -{ - vec3_t vec; +float NPC_MaxDistSquaredForWeapon(void); +void NPC_CheckAttackHold(void) { + vec3_t vec; // If they don't have an enemy they shouldn't hold their attack anim. - if ( !NPCS.NPC->enemy ) - { + if (!NPCS.NPC->enemy) { NPCS.NPCInfo->attackHoldTime = 0; return; } -/* if ( ( NPC->client->ps.weapon == WP_BORG_ASSIMILATOR ) || ( NPC->client->ps.weapon == WP_BORG_DRILL ) ) - {//FIXME: don't keep holding this if can't hit enemy? + /* if ( ( NPC->client->ps.weapon == WP_BORG_ASSIMILATOR ) || ( NPC->client->ps.weapon == WP_BORG_DRILL ) ) + {//FIXME: don't keep holding this if can't hit enemy? - // If they don't have shields ( been disabled) they shouldn't hold their attack anim. - if ( !(NPC->NPC->aiFlags & NPCAI_SHIELDS) ) - { - NPCInfo->attackHoldTime = 0; - return; - } + // If they don't have shields ( been disabled) they shouldn't hold their attack anim. + if ( !(NPC->NPC->aiFlags & NPCAI_SHIELDS) ) + { + NPCInfo->attackHoldTime = 0; + return; + } - VectorSubtract(NPC->enemy->r.currentOrigin, NPC->r.currentOrigin, vec); - if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) - { - NPCInfo->attackHoldTime = 0; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); - } - else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) - { - ucmd.buttons |= BUTTON_ATTACK; - } - else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) - { - NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, NPCInfo->attackHold); - } - else - { - NPCInfo->attackHoldTime = 0; - PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + VectorSubtract(NPC->enemy->r.currentOrigin, NPC->r.currentOrigin, vec); + if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) + { + NPCInfo->attackHoldTime = 0; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + } + else if( NPCInfo->attackHoldTime && NPCInfo->attackHoldTime > level.time ) + { + ucmd.buttons |= BUTTON_ATTACK; + } + else if ( ( NPCInfo->attackHold ) && ( ucmd.buttons & BUTTON_ATTACK ) ) + { + NPCInfo->attackHoldTime = level.time + NPCInfo->attackHold; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, NPCInfo->attackHold); + } + else + { + NPCInfo->attackHoldTime = 0; + PM_SetTorsoAnimTimer(NPC, &NPC->client->ps.torsoAnimTimer, 0); + } } - } - else*/ - {//everyone else...? FIXME: need to tie this into AI somehow? + else*/ + { // everyone else...? FIXME: need to tie this into AI somehow? VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); - if( VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon() ) - { + if (VectorLengthSquared(vec) > NPC_MaxDistSquaredForWeapon()) { NPCS.NPCInfo->attackHoldTime = 0; - } - else if( NPCS.NPCInfo->attackHoldTime && NPCS.NPCInfo->attackHoldTime > level.time ) - { + } else if (NPCS.NPCInfo->attackHoldTime && NPCS.NPCInfo->attackHoldTime > level.time) { NPCS.ucmd.buttons |= BUTTON_ATTACK; - } - else if ( ( NPCS.NPCInfo->attackHold ) && ( NPCS.ucmd.buttons & BUTTON_ATTACK ) ) - { + } else if ((NPCS.NPCInfo->attackHold) && (NPCS.ucmd.buttons & BUTTON_ATTACK)) { NPCS.NPCInfo->attackHoldTime = level.time + NPCS.NPCInfo->attackHold; - } - else - { + } else { NPCS.NPCInfo->attackHoldTime = 0; } } @@ -854,16 +746,13 @@ void NPC_KeepCurrentFacing(void) Fills in a default ucmd to keep current angles facing */ -void NPC_KeepCurrentFacing(void) -{ - if(!NPCS.ucmd.angles[YAW]) - { - NPCS.ucmd.angles[YAW] = ANGLE2SHORT( NPCS.client->ps.viewangles[YAW] ) - NPCS.client->ps.delta_angles[YAW]; +void NPC_KeepCurrentFacing(void) { + if (!NPCS.ucmd.angles[YAW]) { + NPCS.ucmd.angles[YAW] = ANGLE2SHORT(NPCS.client->ps.viewangles[YAW]) - NPCS.client->ps.delta_angles[YAW]; } - if(!NPCS.ucmd.angles[PITCH]) - { - NPCS.ucmd.angles[PITCH] = ANGLE2SHORT( NPCS.client->ps.viewangles[PITCH] ) - NPCS.client->ps.delta_angles[PITCH]; + if (!NPCS.ucmd.angles[PITCH]) { + NPCS.ucmd.angles[PITCH] = ANGLE2SHORT(NPCS.client->ps.viewangles[PITCH]) - NPCS.client->ps.delta_angles[PITCH]; } } @@ -873,27 +762,25 @@ NPC_BehaviorSet_Charmed ------------------------- */ -void NPC_BehaviorSet_Charmed( int bState ) -{ - switch( bState ) - { - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across +void NPC_BehaviorSet_Charmed(int bState) { + switch (bState) { + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: NPC_BSFlee(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -904,32 +791,30 @@ NPC_BehaviorSet_Default ------------------------- */ -void NPC_BehaviorSet_Default( int bState ) -{ - switch( bState ) - { - case BS_ADVANCE_FIGHT://head toward captureGoal, shoot anything that gets in the way - NPC_BSAdvanceFight (); +void NPC_BehaviorSet_Default(int bState) { + switch (bState) { + case BS_ADVANCE_FIGHT: // head toward captureGoal, shoot anything that gets in the way + NPC_BSAdvanceFight(); break; - case BS_SLEEP://Follow a path, looking for enemies - NPC_BSSleep (); + case BS_SLEEP: // Follow a path, looking for enemies + NPC_BSSleep(); break; - case BS_FOLLOW_LEADER://# 40: Follow your leader and shoot any enemies you come across + case BS_FOLLOW_LEADER: //# 40: Follow your leader and shoot any enemies you come across NPC_BSFollowLeader(); break; - case BS_JUMP: //41: Face navgoal and jump to it. + case BS_JUMP: // 41: Face navgoal and jump to it. NPC_BSJump(); break; case BS_REMOVE: NPC_BSRemove(); break; - case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies + case BS_SEARCH: //# 43: Using current waypoint as a base, search the immediate branches of waypoints for enemies NPC_BSSearch(); break; case BS_NOCLIP: NPC_BSNoClip(); break; - case BS_WANDER: //# 46: Wander down random waypoint paths + case BS_WANDER: //# 46: Wander down random waypoint paths NPC_BSWander(); break; case BS_FLEE: @@ -942,7 +827,7 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BSCinematic(); break; default: - case BS_DEFAULT://whatever + case BS_DEFAULT: // whatever NPC_BSDefault(); break; } @@ -953,10 +838,8 @@ void NPC_BehaviorSet_Default( int bState ) NPC_BehaviorSet_Interrogator ------------------------- */ -void NPC_BehaviorSet_Interrogator( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Interrogator(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -965,13 +848,13 @@ void NPC_BehaviorSet_Interrogator( int bState ) NPC_BSInterrogator_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSImperialProbe_Attack( void ); -void NPC_BSImperialProbe_Patrol( void ); +void NPC_BSImperialProbe_Attack(void); +void NPC_BSImperialProbe_Patrol(void); void NPC_BSImperialProbe_Wait(void); /* @@ -979,10 +862,8 @@ void NPC_BSImperialProbe_Wait(void); NPC_BehaviorSet_ImperialProbe ------------------------- */ -void NPC_BehaviorSet_ImperialProbe( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ImperialProbe(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -991,23 +872,20 @@ void NPC_BehaviorSet_ImperialProbe( int bState ) NPC_BSImperialProbe_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } - -void NPC_BSSeeker_Default( void ); +void NPC_BSSeeker_Default(void); /* ------------------------- NPC_BehaviorSet_Seeker ------------------------- */ -void NPC_BehaviorSet_Seeker( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Seeker(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1016,34 +894,29 @@ void NPC_BehaviorSet_Seeker( int bState ) NPC_BSSeeker_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } -void NPC_BSRemote_Default( void ); +void NPC_BSRemote_Default(void); /* ------------------------- NPC_BehaviorSet_Remote ------------------------- */ -void NPC_BehaviorSet_Remote( int bState ) -{ - NPC_BSRemote_Default(); -} +void NPC_BehaviorSet_Remote(int bState) { NPC_BSRemote_Default(); } -void NPC_BSSentry_Default( void ); +void NPC_BSSentry_Default(void); /* ------------------------- NPC_BehaviorSet_Sentry ------------------------- */ -void NPC_BehaviorSet_Sentry( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sentry(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1052,7 +925,7 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BSSentry_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1062,10 +935,8 @@ void NPC_BehaviorSet_Sentry( int bState ) NPC_BehaviorSet_Grenadier ------------------------- */ -void NPC_BehaviorSet_Grenadier( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Grenadier(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1075,7 +946,7 @@ void NPC_BehaviorSet_Grenadier( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1084,10 +955,8 @@ void NPC_BehaviorSet_Grenadier( int bState ) NPC_BehaviorSet_Sniper ------------------------- */ -void NPC_BehaviorSet_Sniper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Sniper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1097,7 +966,7 @@ void NPC_BehaviorSet_Sniper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1107,10 +976,8 @@ NPC_BehaviorSet_Stormtrooper ------------------------- */ -void NPC_BehaviorSet_Stormtrooper( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Stormtrooper(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1128,7 +995,7 @@ void NPC_BehaviorSet_Stormtrooper( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1139,10 +1006,8 @@ NPC_BehaviorSet_Jedi ------------------------- */ -void NPC_BehaviorSet_Jedi( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Jedi(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1156,7 +1021,7 @@ void NPC_BehaviorSet_Jedi( int bState ) break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1166,17 +1031,15 @@ void NPC_BehaviorSet_Jedi( int bState ) NPC_BehaviorSet_Droid ------------------------- */ -void NPC_BehaviorSet_Droid( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Droid(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSDroid_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1186,17 +1049,15 @@ void NPC_BehaviorSet_Droid( int bState ) NPC_BehaviorSet_Mark1 ------------------------- */ -void NPC_BehaviorSet_Mark1( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark1(int bState) { + switch (bState) { case BS_DEFAULT: case BS_STAND_GUARD: case BS_PATROL: NPC_BSMark1_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1206,10 +1067,8 @@ void NPC_BehaviorSet_Mark1( int bState ) NPC_BehaviorSet_Mark2 ------------------------- */ -void NPC_BehaviorSet_Mark2( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Mark2(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1217,7 +1076,7 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BSMark2_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1227,10 +1086,8 @@ void NPC_BehaviorSet_Mark2( int bState ) NPC_BehaviorSet_ATST ------------------------- */ -void NPC_BehaviorSet_ATST( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_ATST(int bState) { + switch (bState) { case BS_DEFAULT: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1238,7 +1095,7 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BSATST_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1248,10 +1105,8 @@ void NPC_BehaviorSet_ATST( int bState ) NPC_BehaviorSet_MineMonster ------------------------- */ -void NPC_BehaviorSet_MineMonster( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_MineMonster(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1260,7 +1115,7 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BSMineMonster_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1270,10 +1125,8 @@ void NPC_BehaviorSet_MineMonster( int bState ) NPC_BehaviorSet_Howler ------------------------- */ -void NPC_BehaviorSet_Howler( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Howler(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1282,7 +1135,7 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_BSHowler_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1292,10 +1145,8 @@ void NPC_BehaviorSet_Howler( int bState ) NPC_BehaviorSet_Rancor ------------------------- */ -void NPC_BehaviorSet_Rancor( int bState ) -{ - switch( bState ) - { +void NPC_BehaviorSet_Rancor(int bState) { + switch (bState) { case BS_STAND_GUARD: case BS_PATROL: case BS_STAND_AND_SHOOT: @@ -1304,7 +1155,7 @@ void NPC_BehaviorSet_Rancor( int bState ) NPC_BSRancor_Default(); break; default: - NPC_BehaviorSet_Default( bState ); + NPC_BehaviorSet_Default(bState); break; } } @@ -1314,112 +1165,82 @@ void NPC_BehaviorSet_Rancor( int bState ) NPC_RunBehavior ------------------------- */ -extern void NPC_BSEmplaced( void ); -extern qboolean NPC_CheckSurrender( void ); -extern void Boba_FlyStop( gentity_t *self ); -extern void NPC_BSWampa_Default( void ); -extern qboolean Jedi_CultistDestroyer( gentity_t *self ); -void NPC_RunBehavior( int team, int bState ) -{ - if (NPCS.NPC->s.NPC_class == CLASS_VEHICLE && - NPCS.NPC->m_pVehicle) - { //vehicles don't do AI! +extern void NPC_BSEmplaced(void); +extern qboolean NPC_CheckSurrender(void); +extern void Boba_FlyStop(gentity_t *self); +extern void NPC_BSWampa_Default(void); +extern qboolean Jedi_CultistDestroyer(gentity_t *self); +void NPC_RunBehavior(int team, int bState) { + if (NPCS.NPC->s.NPC_class == CLASS_VEHICLE && NPCS.NPC->m_pVehicle) { // vehicles don't do AI! return; } - if ( bState == BS_CINEMATIC ) - { + if (bState == BS_CINEMATIC) { NPC_BSCinematic(); - } - else if ( NPCS.NPC->client->ps.weapon == WP_EMPLACED_GUN ) - { + } else if (NPCS.NPC->client->ps.weapon == WP_EMPLACED_GUN) { NPC_BSEmplaced(); NPC_CheckCharmed(); return; } -// else if ( NPCS.NPC->client->ps.weapon == WP_SABER ) // this is an _extremely_ shitty comparison.. FIXME: make a CLASS_CULTIST? --eez - else if ( NPCS.NPC->client->NPC_class == CLASS_JEDI || - NPCS.NPC->client->NPC_class == CLASS_REBORN || - NPCS.NPC->client->ps.weapon == WP_SABER ) - {//jedi - NPC_BehaviorSet_Jedi( bState ); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_WAMPA ) - {//wampa + // else if ( NPCS.NPC->client->ps.weapon == WP_SABER ) // this is an _extremely_ shitty comparison.. FIXME: make a CLASS_CULTIST? --eez + else if (NPCS.NPC->client->NPC_class == CLASS_JEDI || NPCS.NPC->client->NPC_class == CLASS_REBORN || NPCS.NPC->client->ps.weapon == WP_SABER) { // jedi + NPC_BehaviorSet_Jedi(bState); + } else if (NPCS.NPC->client->NPC_class == CLASS_WAMPA) { // wampa NPC_BSWampa_Default(); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_RANCOR ) - {//rancor - NPC_BehaviorSet_Rancor( bState ); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_REMOTE ) - { - NPC_BehaviorSet_Remote( bState ); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_SEEKER ) - { - NPC_BehaviorSet_Seeker( bState ); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - {//bounty hunter - if ( Boba_Flying( NPCS.NPC ) ) - { + } else if (NPCS.NPC->client->NPC_class == CLASS_RANCOR) { // rancor + NPC_BehaviorSet_Rancor(bState); + } else if (NPCS.NPC->client->NPC_class == CLASS_REMOTE) { + NPC_BehaviorSet_Remote(bState); + } else if (NPCS.NPC->client->NPC_class == CLASS_SEEKER) { + NPC_BehaviorSet_Seeker(bState); + } else if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { // bounty hunter + if (Boba_Flying(NPCS.NPC)) { NPC_BehaviorSet_Seeker(bState); + } else { + NPC_BehaviorSet_Jedi(bState); } - else - { - NPC_BehaviorSet_Jedi( bState ); - } - } - else if ( Jedi_CultistDestroyer( NPCS.NPC ) ) - { + } else if (Jedi_CultistDestroyer(NPCS.NPC)) { NPC_BSJedi_Default(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to march + } else if (NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to march NPC_BSDefault(); - } - else - { - switch( team ) - { - - // case NPCTEAM_SCAVENGERS: - // case NPCTEAM_IMPERIAL: - // case NPCTEAM_KLINGON: - // case NPCTEAM_HIROGEN: - // case NPCTEAM_MALON: - // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv + } else { + switch (team) { + + // case NPCTEAM_SCAVENGERS: + // case NPCTEAM_IMPERIAL: + // case NPCTEAM_KLINGON: + // case NPCTEAM_HIROGEN: + // case NPCTEAM_MALON: + // not sure if TEAM_ENEMY is appropriate here, I think I should be using NPC_class to check for behavior - dmv case NPCTEAM_ENEMY: // special cases for enemy droids - switch( NPCS.NPC->client->NPC_class) - { + switch (NPCS.NPC->client->NPC_class) { case CLASS_ATST: - NPC_BehaviorSet_ATST( bState ); + NPC_BehaviorSet_ATST(bState); return; case CLASS_PROBE: NPC_BehaviorSet_ImperialProbe(bState); return; case CLASS_REMOTE: - NPC_BehaviorSet_Remote( bState ); + NPC_BehaviorSet_Remote(bState); return; case CLASS_SENTRY: NPC_BehaviorSet_Sentry(bState); return; case CLASS_INTERROGATOR: - NPC_BehaviorSet_Interrogator( bState ); + NPC_BehaviorSet_Interrogator(bState); return; case CLASS_MINEMONSTER: - NPC_BehaviorSet_MineMonster( bState ); + NPC_BehaviorSet_MineMonster(bState); return; case CLASS_HOWLER: - NPC_BehaviorSet_Howler( bState ); + NPC_BehaviorSet_Howler(bState); return; case CLASS_MARK1: - NPC_BehaviorSet_Mark1( bState ); + NPC_BehaviorSet_Mark1(bState); return; case CLASS_MARK2: - NPC_BehaviorSet_Mark2( bState ); + NPC_BehaviorSet_Mark2(bState); return; case CLASS_GALAKMECH: NPC_BSGM_Default(); @@ -1428,74 +1249,58 @@ void NPC_RunBehavior( int team, int bState ) break; } - if ( NPCS.NPC->enemy && NPCS.NPC->s.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there - if ( bState != BS_FLEE ) - { - NPC_StartFlee( NPCS.NPC->enemy, NPCS.NPC->enemy->r.currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - } - else - { + if (NPCS.NPC->enemy && NPCS.NPC->s.weapon == WP_NONE && bState != BS_HUNT_AND_KILL && + !trap->ICARUS_TaskIDPending( + (sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // if in battle and have no weapon, run away, fixme: when in BS_HUNT_AND_KILL, they just stand there + if (bState != BS_FLEE) { + NPC_StartFlee(NPCS.NPC->enemy, NPCS.NPC->enemy->r.currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } else { NPC_BSFlee(); } return; } - if ( NPCS.NPC->client->ps.weapon == WP_SABER ) - {//special melee exception - NPC_BehaviorSet_Default( bState ); + if (NPCS.NPC->client->ps.weapon == WP_SABER) { // special melee exception + NPC_BehaviorSet_Default(bState); return; } - if ( NPCS.NPC->client->ps.weapon == WP_DISRUPTOR && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//a sniper - NPC_BehaviorSet_Sniper( bState ); + if (NPCS.NPC->client->ps.weapon == WP_DISRUPTOR && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // a sniper + NPC_BehaviorSet_Sniper(bState); return; } - if ( NPCS.NPC->client->ps.weapon == WP_THERMAL || NPCS.NPC->client->ps.weapon == WP_STUN_BATON )//FIXME: separate AI for melee fighters - {//a grenadier - NPC_BehaviorSet_Grenadier( bState ); + if (NPCS.NPC->client->ps.weapon == WP_THERMAL || NPCS.NPC->client->ps.weapon == WP_STUN_BATON) // FIXME: separate AI for melee fighters + { // a grenadier + NPC_BehaviorSet_Grenadier(bState); return; } - if ( NPC_CheckSurrender() ) - { + if (NPC_CheckSurrender()) { return; } - NPC_BehaviorSet_Stormtrooper( bState ); + NPC_BehaviorSet_Stormtrooper(bState); break; case NPCTEAM_NEUTRAL: // special cases for enemy droids - if ( NPCS.NPC->client->NPC_class == CLASS_PROTOCOL || NPCS.NPC->client->NPC_class == CLASS_UGNAUGHT || - NPCS.NPC->client->NPC_class == CLASS_JAWA) - { + if (NPCS.NPC->client->NPC_class == CLASS_PROTOCOL || NPCS.NPC->client->NPC_class == CLASS_UGNAUGHT || NPCS.NPC->client->NPC_class == CLASS_JAWA) { NPC_BehaviorSet_Default(bState); - } - else if ( NPCS.NPC->client->NPC_class == CLASS_VEHICLE ) - { + } else if (NPCS.NPC->client->NPC_class == CLASS_VEHICLE) { // TODO: Add vehicle behaviors here. - NPC_UpdateAngles( qtrue, qtrue );//just face our spawn angles for now - } - else - { + NPC_UpdateAngles(qtrue, qtrue); // just face our spawn angles for now + } else { // Just one of the average droids - NPC_BehaviorSet_Droid( bState ); + NPC_BehaviorSet_Droid(bState); } break; default: - if ( NPCS.NPC->client->NPC_class == CLASS_SEEKER ) - { + if (NPCS.NPC->client->NPC_class == CLASS_SEEKER) { NPC_BehaviorSet_Seeker(bState); - } - else - { - if ( NPCS.NPCInfo->charmedTime > level.time ) - { - NPC_BehaviorSet_Charmed( bState ); - } - else - { - NPC_BehaviorSet_Default( bState ); + } else { + if (NPCS.NPCInfo->charmedTime > level.time) { + NPC_BehaviorSet_Charmed(bState); + } else { + NPC_BehaviorSet_Default(bState); } NPC_CheckCharmed(); } @@ -1514,113 +1319,93 @@ NPC Behavior state thinking =============== */ -void NPC_ExecuteBState ( gentity_t *self)//, int msec ) +void NPC_ExecuteBState(gentity_t *self) //, int msec ) { - bState_t bState; + bState_t bState; NPC_HandleAIFlags(); - //FIXME: these next three bits could be a function call, some sort of setup/cleanup func - //Lookmode must be reset every think cycle - if(NPCS.NPC->delayScriptTime && NPCS.NPC->delayScriptTime <= level.time) - { - G_ActivateBehavior( NPCS.NPC, BSET_DELAYED); + // FIXME: these next three bits could be a function call, some sort of setup/cleanup func + // Lookmode must be reset every think cycle + if (NPCS.NPC->delayScriptTime && NPCS.NPC->delayScriptTime <= level.time) { + G_ActivateBehavior(NPCS.NPC, BSET_DELAYED); NPCS.NPC->delayScriptTime = 0; } - //Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func + // Clear this and let bState set it itself, so it automatically handles changing bStates... but we need a set bState wrapper func NPCS.NPCInfo->combatMove = qfalse; - //Execute our bState - if(NPCS.NPCInfo->tempBehavior) - {//Overrides normal behavior until cleared + // Execute our bState + if (NPCS.NPCInfo->tempBehavior) { // Overrides normal behavior until cleared bState = NPCS.NPCInfo->tempBehavior; - } - else - { - if(!NPCS.NPCInfo->behaviorState) + } else { + if (!NPCS.NPCInfo->behaviorState) NPCS.NPCInfo->behaviorState = NPCS.NPCInfo->defaultBehavior; bState = NPCS.NPCInfo->behaviorState; } - //Pick the proper bstate for us and run it - NPC_RunBehavior( self->client->playerTeam, bState ); - + // Pick the proper bstate for us and run it + NPC_RunBehavior(self->client->playerTeam, bState); -// if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) -// { - //level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; - //NPCInfo->combatPoint = -1; -// } + // if(bState != BS_POINT_COMBAT && NPCInfo->combatPoint != -1) + // { + // level.combatPoints[NPCInfo->combatPoint].occupied = qfalse; + // NPCInfo->combatPoint = -1; + // } - //Here we need to see what the scripted stuff told us to do -//Only process snapshot if independent and in combat mode- this would pick enemies and go after needed items -// ProcessSnapshot(); + // Here we need to see what the scripted stuff told us to do + // Only process snapshot if independent and in combat mode- this would pick enemies and go after needed items + // ProcessSnapshot(); -//Ignore my needs if I'm under script control- this would set needs for items -// CheckSelf(); + // Ignore my needs if I'm under script control- this would set needs for items + // CheckSelf(); - //Back to normal? All decisions made? + // Back to normal? All decisions made? - //FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface - //NPCPredict(); + // FIXME: don't walk off ledges unless we can get to our goal faster that way, or that's our goal's surface + // NPCPredict(); - if ( NPCS.NPC->enemy ) - { - if ( !NPCS.NPC->enemy->inuse ) - {//just in case bState doesn't catch this - G_ClearEnemy( NPCS.NPC ); + if (NPCS.NPC->enemy) { + if (!NPCS.NPC->enemy->inuse) { // just in case bState doesn't catch this + G_ClearEnemy(NPCS.NPC); } } - if ( NPCS.NPC->client->ps.saberLockTime && NPCS.NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE ) - { - NPC_SetLookTarget( NPCS.NPC, NPCS.NPC->client->ps.saberLockEnemy, level.time+1000 ); - } - else if ( !NPC_CheckLookTarget( NPCS.NPC ) ) - { - if ( NPCS.NPC->enemy ) - { - NPC_SetLookTarget( NPCS.NPC, NPCS.NPC->enemy->s.number, 0 ); + if (NPCS.NPC->client->ps.saberLockTime && NPCS.NPC->client->ps.saberLockEnemy != ENTITYNUM_NONE) { + NPC_SetLookTarget(NPCS.NPC, NPCS.NPC->client->ps.saberLockEnemy, level.time + 1000); + } else if (!NPC_CheckLookTarget(NPCS.NPC)) { + if (NPCS.NPC->enemy) { + NPC_SetLookTarget(NPCS.NPC, NPCS.NPC->enemy->s.number, 0); } } - if ( NPCS.NPC->enemy ) - { - if(NPCS.NPC->enemy->flags & FL_DONT_SHOOT) - { + if (NPCS.NPC->enemy) { + if (NPCS.NPC->enemy->flags & FL_DONT_SHOOT) { NPCS.ucmd.buttons &= ~BUTTON_ATTACK; NPCS.ucmd.buttons &= ~BUTTON_ALT_ATTACK; - } - else if ( NPCS.NPC->client->playerTeam != NPCTEAM_ENEMY && NPCS.NPC->enemy->NPC && (NPCS.NPC->enemy->NPC->surrenderTime > level.time || (NPCS.NPC->enemy->NPC->scriptFlags&SCF_FORCED_MARCH)) ) - {//don't shoot someone who's surrendering if you're a good guy + } else if (NPCS.NPC->client->playerTeam != NPCTEAM_ENEMY && NPCS.NPC->enemy->NPC && + (NPCS.NPC->enemy->NPC->surrenderTime > level.time || + (NPCS.NPC->enemy->NPC->scriptFlags & SCF_FORCED_MARCH))) { // don't shoot someone who's surrendering if you're a good guy NPCS.ucmd.buttons &= ~BUTTON_ATTACK; NPCS.ucmd.buttons &= ~BUTTON_ALT_ATTACK; } - if(NPCS.client->ps.weaponstate == WEAPON_IDLE) - { + if (NPCS.client->ps.weaponstate == WEAPON_IDLE) { NPCS.client->ps.weaponstate = WEAPON_READY; } - } - else - { - if(NPCS.client->ps.weaponstate == WEAPON_READY) - { + } else { + if (NPCS.client->ps.weaponstate == WEAPON_READY) { NPCS.client->ps.weaponstate = WEAPON_IDLE; } } - if(!(NPCS.ucmd.buttons & BUTTON_ATTACK) && NPCS.NPC->attackDebounceTime > level.time) - {//We just shot but aren't still shooting, so hold the gun up for a while - if(NPCS.client->ps.weapon == WP_SABER ) - {//One-handed - NPC_SetAnim(NPCS.NPC,SETANIM_TORSO,TORSO_WEAPONREADY1,SETANIM_FLAG_NORMAL); - } - else if(NPCS.client->ps.weapon == WP_BRYAR_PISTOL) - {//Sniper pose - NPC_SetAnim(NPCS.NPC,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); + if (!(NPCS.ucmd.buttons & BUTTON_ATTACK) && + NPCS.NPC->attackDebounceTime > level.time) { // We just shot but aren't still shooting, so hold the gun up for a while + if (NPCS.client->ps.weapon == WP_SABER) { // One-handed + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, TORSO_WEAPONREADY1, SETANIM_FLAG_NORMAL); + } else if (NPCS.client->ps.weapon == WP_BRYAR_PISTOL) { // Sniper pose + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL); } /*//FIXME: What's the proper solution here? else @@ -1628,39 +1413,34 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) NPC_SetAnim(NPC,SETANIM_TORSO,TORSO_WEAPONREADY3,SETANIM_FLAG_NORMAL); } */ - } - else if ( !NPCS.NPC->enemy )//HACK! + } else if (!NPCS.NPC->enemy) // HACK! { - if( NPCS.NPC->s.torsoAnim == TORSO_WEAPONREADY1 || NPCS.NPC->s.torsoAnim == TORSO_WEAPONREADY3 ) - {//we look ready for action, using one of the first 2 weapon, let's rest our weapon on our shoulder - NPC_SetAnim(NPCS.NPC,SETANIM_TORSO,TORSO_WEAPONIDLE3,SETANIM_FLAG_NORMAL); - } + if (NPCS.NPC->s.torsoAnim == TORSO_WEAPONREADY1 || + NPCS.NPC->s.torsoAnim == TORSO_WEAPONREADY3) { // we look ready for action, using one of the first 2 weapon, let's rest our weapon on our shoulder + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, TORSO_WEAPONIDLE3, SETANIM_FLAG_NORMAL); + } } NPC_CheckAttackHold(); NPC_ApplyScriptFlags(); - //cliff and wall avoidance + // cliff and wall avoidance NPC_AvoidWallsAndCliffs(); // run the bot through the server like it was a real client -//=== Save the ucmd for the second no-think Pmove ============================ + //=== Save the ucmd for the second no-think Pmove ============================ NPCS.ucmd.serverTime = level.time - 50; - memcpy( &NPCS.NPCInfo->last_ucmd, &NPCS.ucmd, sizeof( usercmd_t ) ); - if ( !NPCS.NPCInfo->attackHoldTime ) - { - NPCS.NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK);//so we don't fire twice in one think + memcpy(&NPCS.NPCInfo->last_ucmd, &NPCS.ucmd, sizeof(usercmd_t)); + if (!NPCS.NPCInfo->attackHoldTime) { + NPCS.NPCInfo->last_ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); // so we don't fire twice in one think } -//============================================================================ + //============================================================================ NPC_CheckAttackScript(); NPC_KeepCurrentFacing(); - if ( !NPCS.NPC->next_roff_time || NPCS.NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - ClientThink( NPCS.NPC->s.number, &NPCS.ucmd ); - } - else - { + if (!NPCS.NPC->next_roff_time || NPCS.NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + ClientThink(NPCS.NPC->s.number, &NPCS.ucmd); + } else { NPC_ApplyRoff(); } @@ -1694,61 +1474,53 @@ void NPC_ExecuteBState ( gentity_t *self)//, int msec ) if(la != -1 && ta != -1) {//FIXME: should never play same frame twice or restart an anim before finishing it - Com_Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, NPC->client->renderInfo.torsoFrame); + Com_Printf("LegsAnim: %s(%d) TorsoAnim: %s(%d)\n", animTable[la].name, NPC->renderInfo.legsFrame, animTable[ta].name, + NPC->client->renderInfo.torsoFrame); } }*/ } -void NPC_CheckInSolid(void) -{ - trace_t trace; - vec3_t point; +void NPC_CheckInSolid(void) { + trace_t trace; + vec3_t point; VectorCopy(NPCS.NPC->r.currentOrigin, point); point[2] -= 0.25; trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, point, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); - if(!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy(NPCS.NPC->r.currentOrigin, NPCS.NPCInfo->lastClearOrigin); - } - else - { - if(VectorLengthSquared(NPCS.NPCInfo->lastClearOrigin)) - { -// Com_Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->r.currentOrigin)); + } else { + if (VectorLengthSquared(NPCS.NPCInfo->lastClearOrigin)) { + // Com_Printf("%s stuck in solid at %s: fixing...\n", NPC->script_targetname, vtos(NPC->r.currentOrigin)); G_SetOrigin(NPCS.NPC, NPCS.NPCInfo->lastClearOrigin); trap->LinkEntity((sharedEntity_t *)NPCS.NPC); } } } -void G_DroidSounds( gentity_t *self ) -{ - if ( self->client ) - {//make the noises - if ( TIMER_Done( self, "patrolNoise" ) && !Q_irand( 0, 20 ) ) - { - switch( self->client->NPC_class ) - { - case CLASS_R2D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)) ); +void G_DroidSounds(gentity_t *self) { + if (self->client) { // make the noises + if (TIMER_Done(self, "patrolNoise") && !Q_irand(0, 20)) { + switch (self->client->NPC_class) { + case CLASS_R2D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); break; - case CLASS_R5D2: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)) ); + case CLASS_R5D2: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); break; - case CLASS_PROBE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav",Q_irand(1, 3)) ); + case CLASS_PROBE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d.wav", Q_irand(1, 3))); break; - case CLASS_MOUSE: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)) ); + case CLASS_MOUSE: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); break; - case CLASS_GONK: // droid - G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)) ); + case CLASS_GONK: // droid + G_SoundOnEnt(self, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); break; default: break; } - TIMER_Set( self, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(self, "patrolNoise", Q_irand(2000, 4000)); } } } @@ -1760,39 +1532,35 @@ NPC_Think Main NPC AI - called once per frame =============== */ -#if AI_TIMERS +#if AI_TIMERS extern int AITime; -#endif// AI_TIMERS -void NPC_Think ( gentity_t *self)//, int msec ) +#endif // AI_TIMERS +void NPC_Think(gentity_t *self) //, int msec ) { - vec3_t oldMoveDir; + vec3_t oldMoveDir; int i = 0; gentity_t *player; self->nextthink = level.time + FRAMETIME; - SetNPCGlobals( self ); + SetNPCGlobals(self); - memset( &NPCS.ucmd, 0, sizeof( NPCS.ucmd ) ); + memset(&NPCS.ucmd, 0, sizeof(NPCS.ucmd)); - VectorCopy( self->client->ps.moveDir, oldMoveDir ); - if (self->s.NPC_class != CLASS_VEHICLE) - { //YOU ARE BREAKING MY PREDICTION. Bad clear. - VectorClear( self->client->ps.moveDir ); + VectorCopy(self->client->ps.moveDir, oldMoveDir); + if (self->s.NPC_class != CLASS_VEHICLE) { // YOU ARE BREAKING MY PREDICTION. Bad clear. + VectorClear(self->client->ps.moveDir); } - if(!self || !self->NPC || !self->client) - { + if (!self || !self->NPC || !self->client) { return; } // dead NPCs have a special think, don't run scripts (for now) - //FIXME: this breaks deathscripts - if ( self->health <= 0 ) - { + // FIXME: this breaks deathscripts + if (self->health <= 0) { DeadThink(); - if ( NPCS.NPCInfo->nextBStateThink <= level.time ) - { + if (NPCS.NPCInfo->nextBStateThink <= level.time) { trap->ICARUS_MaintainTaskManager(self->s.number); } VectorCopy(self->r.currentOrigin, self->client->ps.origin); @@ -1800,35 +1568,30 @@ void NPC_Think ( gentity_t *self)//, int msec ) } // see if NPC ai is frozen - if ( d_npcfreeze.value || (NPCS.NPC->r.svFlags&SVF_ICARUS_FREEZE) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (d_npcfreeze.value || (NPCS.NPC->r.svFlags & SVF_ICARUS_FREEZE)) { + NPC_UpdateAngles(qtrue, qtrue); ClientThink(self->s.number, &NPCS.ucmd); - //VectorCopy(self->s.origin, self->s.origin2 ); + // VectorCopy(self->s.origin, self->s.origin2 ); VectorCopy(self->r.currentOrigin, self->client->ps.origin); return; } - self->nextthink = level.time + FRAMETIME/2; - + self->nextthink = level.time + FRAMETIME / 2; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { player = &g_entities[i]; - if (player->inuse && player->client && player->client->sess.sessionTeam != TEAM_SPECTATOR && - !(player->client->ps.pm_flags & PMF_FOLLOW)) - { - //if ( player->client->ps.viewEntity == self->s.number ) - if (0) //rwwFIXMEFIXME: Allow controlling ents - {//being controlled by player - G_DroidSounds( self ); - //FIXME: might want to at least make sounds or something? - //NPC_UpdateAngles(qtrue, qtrue); - //Which ucmd should we send? Does it matter, since it gets overridden anyway? + if (player->inuse && player->client && player->client->sess.sessionTeam != TEAM_SPECTATOR && !(player->client->ps.pm_flags & PMF_FOLLOW)) { + // if ( player->client->ps.viewEntity == self->s.number ) + if (0) // rwwFIXMEFIXME: Allow controlling ents + { // being controlled by player + G_DroidSounds(self); + // FIXME: might want to at least make sounds or something? + // NPC_UpdateAngles(qtrue, qtrue); + // Which ucmd should we send? Does it matter, since it gets overridden anyway? NPCS.NPCInfo->last_ucmd.serverTime = level.time - 50; - ClientThink( NPCS.NPC->s.number, &NPCS.ucmd ); - //VectorCopy(self->s.origin, self->s.origin2 ); + ClientThink(NPCS.NPC->s.number, &NPCS.ucmd); + // VectorCopy(self->s.origin, self->s.origin2 ); VectorCopy(self->r.currentOrigin, self->client->ps.origin); return; } @@ -1836,16 +1599,12 @@ void NPC_Think ( gentity_t *self)//, int msec ) i++; } - if ( self->client->NPC_class == CLASS_VEHICLE) - { - if (self->client->ps.m_iVehicleNum) - {//we don't think on our own - //well, run scripts, though... + if (self->client->NPC_class == CLASS_VEHICLE) { + if (self->client->ps.m_iVehicleNum) { // we don't think on our own + // well, run scripts, though... trap->ICARUS_MaintainTaskManager(self->s.number); return; - } - else - { + } else { VectorClear(self->client->ps.moveDir); self->client->pers.cmd.forwardmove = 0; self->client->pers.cmd.rightmove = 0; @@ -1853,73 +1612,59 @@ void NPC_Think ( gentity_t *self)//, int msec ) self->client->pers.cmd.buttons = 0; memcpy(&self->m_pVehicle->m_ucmd, &self->client->pers.cmd, sizeof(usercmd_t)); } - } - else if ( NPCS.NPC->s.m_iVehicleNum ) - {//droid in a vehicle? - G_DroidSounds( self ); + } else if (NPCS.NPC->s.m_iVehicleNum) { // droid in a vehicle? + G_DroidSounds(self); } - if ( NPCS.NPCInfo->nextBStateThink <= level.time - && !NPCS.NPC->s.m_iVehicleNum )//NPCs sitting in Vehicles do NOTHING + if (NPCS.NPCInfo->nextBStateThink <= level.time && !NPCS.NPC->s.m_iVehicleNum) // NPCs sitting in Vehicles do NOTHING { -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS - if ( NPCS.NPC->s.eType != ET_NPC ) - {//Something drastic happened in our script +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS + if (NPCS.NPC->s.eType != ET_NPC) { // Something drastic happened in our script return; } - if ( NPCS.NPC->s.weapon == WP_SABER && g_npcspskill.integer >= 2 && NPCS.NPCInfo->rank > RANK_LT_JG ) - {//Jedi think faster on hard difficulty, except low-rank (reborn) - NPCS.NPCInfo->nextBStateThink = level.time + FRAMETIME/2; - } - else - {//Maybe even 200 ms? + if (NPCS.NPC->s.weapon == WP_SABER && g_npcspskill.integer >= 2 && + NPCS.NPCInfo->rank > RANK_LT_JG) { // Jedi think faster on hard difficulty, except low-rank (reborn) + NPCS.NPCInfo->nextBStateThink = level.time + FRAMETIME / 2; + } else { // Maybe even 200 ms? NPCS.NPCInfo->nextBStateThink = level.time + FRAMETIME; } - //nextthink is set before this so something in here can override it - if (self->s.NPC_class != CLASS_VEHICLE || - !self->m_pVehicle) - { //ok, let's not do this at all for vehicles. - NPC_ExecuteBState( self ); + // nextthink is set before this so something in here can override it + if (self->s.NPC_class != CLASS_VEHICLE || !self->m_pVehicle) { // ok, let's not do this at all for vehicles. + NPC_ExecuteBState(self); } -#if AI_TIMERS - int addTime = GetTime( startTime ); - if ( addTime > 50 ) - { - Com_Printf( S_COLOR_RED"ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, vtos(NPC->r.currentOrigin), NPC->s.weapon, addTime ); +#if AI_TIMERS + int addTime = GetTime(startTime); + if (addTime > 50) { + Com_Printf(S_COLOR_RED "ERROR: NPC number %d, %s %s at %s, weaponnum: %d, using %d of AI time!!!\n", NPC->s.number, NPC->NPC_type, NPC->targetname, + vtos(NPC->r.currentOrigin), NPC->s.weapon, addTime); } AITime += addTime; -#endif// AI_TIMERS - } - else - { - VectorCopy( oldMoveDir, self->client->ps.moveDir ); - //or use client->pers.lastCommand? +#endif // AI_TIMERS + } else { + VectorCopy(oldMoveDir, self->client->ps.moveDir); + // or use client->pers.lastCommand? NPCS.NPCInfo->last_ucmd.serverTime = level.time - 50; - if ( !NPCS.NPC->next_roff_time || NPCS.NPC->next_roff_time < level.time ) - {//If we were following a roff, we don't do normal pmoves. - //FIXME: firing angles (no aim offset) or regular angles? + if (!NPCS.NPC->next_roff_time || NPCS.NPC->next_roff_time < level.time) { // If we were following a roff, we don't do normal pmoves. + // FIXME: firing angles (no aim offset) or regular angles? NPC_UpdateAngles(qtrue, qtrue); - memcpy( &NPCS.ucmd, &NPCS.NPCInfo->last_ucmd, sizeof( usercmd_t ) ); + memcpy(&NPCS.ucmd, &NPCS.NPCInfo->last_ucmd, sizeof(usercmd_t)); ClientThink(NPCS.NPC->s.number, &NPCS.ucmd); - } - else - { + } else { NPC_ApplyRoff(); } - //VectorCopy(self->s.origin, self->s.origin2 ); + // VectorCopy(self->s.origin, self->s.origin2 ); } - //must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands + // must update icarus *every* frame because of certain animation completions in the pmove stuff that can leave a 50ms gap between ICARUS animation commands trap->ICARUS_MaintainTaskManager(self->s.number); VectorCopy(self->r.currentOrigin, self->client->ps.origin); } -void NPC_InitAI ( void ) -{ +void NPC_InitAI(void) { /* trap->Cvar_Register(&g_saberRealisticCombat, "g_saberRealisticCombat", "0", CVAR_CHEAT); @@ -1978,14 +1723,13 @@ void NPC_InitAnimTable( void ) } */ -void NPC_InitGame( void ) -{ -// globals.NPCs = (gNPC_t *) trap->TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); -// trap->Cvar_Register(&debugNPCName, "d_npc", "0", CVAR_CHEAT); +void NPC_InitGame(void) { + // globals.NPCs = (gNPC_t *) trap->TagMalloc(game.maxclients * sizeof(game.bots[0]), TAG_GAME); + // trap->Cvar_Register(&debugNPCName, "d_npc", "0", CVAR_CHEAT); NPC_LoadParms(); NPC_InitAI(); -// NPC_InitAnimTable(); + // NPC_InitAnimTable(); /* ResetTeamCounters(); for ( int team = NPCTEAM_FREE; team < NPCTEAM_NUM_TEAMS; team++ ) @@ -1995,56 +1739,56 @@ void NPC_InitGame( void ) */ } -void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags) -{ // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players +void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, + int setAnimFlags) { // FIXME : once torsoAnim and legsAnim are in the same structure for NCP and Players // rename PM_SETAnimFinal to PM_SetAnim and have both NCP and Players call PM_SetAnim G_SetAnim(ent, NULL, setAnimParts, anim, setAnimFlags, 0); -/* - if(ent->client) - {//Players, NPCs - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) + /* + if(ent->client) + {//Players, NPCs + if (setAnimFlags&SETANIM_FLAG_OVERRIDE) { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim ) + if (setAnimParts & SETANIM_TORSO) { - PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoTimer, 0 ); + if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.torsoAnim != anim ) + { + PM_SetTorsoAnimTimer( ent, &ent->client->ps.torsoTimer, 0 ); + } } - } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim ) + if (setAnimParts & SETANIM_LEGS) { - PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); + if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->client->ps.legsAnim != anim ) + { + PM_SetLegsAnimTimer( ent, &ent->client->ps.legsAnimTimer, 0 ); + } } } - } - PM_SetAnimFinal(&ent->client->ps.torsoAnim,&ent->client->ps.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->client->ps.torsoAnimTimer,&ent->client->ps.legsAnimTimer,ent); - } - else - {//bodies, etc. - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) + PM_SetAnimFinal(&ent->client->ps.torsoAnim,&ent->client->ps.legsAnim,setAnimParts,anim,setAnimFlags, + &ent->client->ps.torsoAnimTimer,&ent->client->ps.legsAnimTimer,ent); + } + else + {//bodies, etc. + if (setAnimFlags&SETANIM_FLAG_OVERRIDE) { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim ) + if (setAnimParts & SETANIM_TORSO) { - PM_SetTorsoAnimTimer( ent, &ent->s.torsoAnimTimer, 0 ); + if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.torsoAnim != anim ) + { + PM_SetTorsoAnimTimer( ent, &ent->s.torsoAnimTimer, 0 ); + } } - } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim ) + if (setAnimParts & SETANIM_LEGS) { - PM_SetLegsAnimTimer( ent, &ent->s.legsAnimTimer, 0 ); + if( (setAnimFlags & SETANIM_FLAG_RESTART) || ent->s.legsAnim != anim ) + { + PM_SetLegsAnimTimer( ent, &ent->s.legsAnimTimer, 0 ); + } } } - } - PM_SetAnimFinal(&ent->s.torsoAnim,&ent->s.legsAnim,setAnimParts,anim,setAnimFlags, - &ent->s.torsoAnimTimer,&ent->s.legsAnimTimer,ent); - } - */ + PM_SetAnimFinal(&ent->s.torsoAnim,&ent->s.legsAnim,setAnimParts,anim,setAnimFlags, + &ent->s.torsoAnimTimer,&ent->s.legsAnimTimer,ent); + } + */ } diff --git a/codemp/game/NPC_AI_Atst.c b/codemp/game/NPC_AI_Atst.c index d4322c39eb..8af46c715b 100644 --- a/codemp/game/NPC_AI_Atst.c +++ b/codemp/game/NPC_AI_Atst.c @@ -22,37 +22,36 @@ along with this program; if not, see . #include "b_local.h" -#define MIN_MELEE_RANGE 640 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 640 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define TURN_OFF 0x00000100//G2SURFACEFLAG_NODESCENDANTS +#define TURN_OFF 0x00000100 // G2SURFACEFLAG_NODESCENDANTS #define LEFT_ARM_HEALTH 40 #define RIGHT_ARM_HEALTH 40 -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); /* ------------------------- NPC_ATST_Precache ------------------------- */ -void NPC_ATST_Precache(void) -{ - G_SoundIndex( "sound/chars/atst/atst_damaged1" ); - G_SoundIndex( "sound/chars/atst/atst_damaged2" ); - -// RegisterItem( BG_FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon - //rwwFIXMEFIXME: add this weapon - RegisterItem( BG_FindItemForWeapon( WP_BOWCASTER )); //precache the weapon - RegisterItem( BG_FindItemForWeapon( WP_ROCKET_LAUNCHER )); //precache the weapon - - G_EffectIndex( "env/med_explode2" ); -// G_EffectIndex( "smaller_chunks" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "explosions/droidexplosion1" ); +void NPC_ATST_Precache(void) { + G_SoundIndex("sound/chars/atst/atst_damaged1"); + G_SoundIndex("sound/chars/atst/atst_damaged2"); + + // RegisterItem( BG_FindItemForWeapon( WP_ATST_MAIN )); //precache the weapon + // rwwFIXMEFIXME: add this weapon + RegisterItem(BG_FindItemForWeapon(WP_BOWCASTER)); // precache the weapon + RegisterItem(BG_FindItemForWeapon(WP_ROCKET_LAUNCHER)); // precache the weapon + + G_EffectIndex("env/med_explode2"); + // G_EffectIndex( "smaller_chunks" ); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("explosions/droidexplosion1"); } //----------------------------------------------------------------- @@ -85,18 +84,14 @@ Called by NPC's and player in an ATST ------------------------- */ -void G_ATSTCheckPain( gentity_t *self, gentity_t *other, int damage ) -{ - //int newBolt; - //int hitLoc = gPainHitLoc; +void G_ATSTCheckPain(gentity_t *self, gentity_t *other, int damage) { + // int newBolt; + // int hitLoc = gPainHitLoc; - if ( rand() & 1 ) - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1" ); - } - else - { - G_SoundOnEnt( self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2" ); + if (rand() & 1) { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged1"); + } else { + G_SoundOnEnt(self, CHAN_LESS_ATTEN, "sound/chars/atst/atst_damaged2"); } /* @@ -138,10 +133,9 @@ void G_ATSTCheckPain( gentity_t *self, gentity_t *other, int damage ) NPC_ATST_Pain ------------------------- */ -void NPC_ATST_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - G_ATSTCheckPain( self, attacker, damage ); - NPC_Pain( self, attacker, damage ); +void NPC_ATST_Pain(gentity_t *self, gentity_t *attacker, int damage) { + G_ATSTCheckPain(self, attacker, damage); + NPC_Pain(self, attacker, damage); } /* @@ -149,18 +143,15 @@ void NPC_ATST_Pain(gentity_t *self, gentity_t *attacker, int damage) ATST_Hunt -------------------------` */ -void ATST_Hunt( qboolean visible, qboolean advance ) -{ +void ATST_Hunt(qboolean visible, qboolean advance) { - if ( NPCS.NPCInfo->goalEntity == NULL ) - {//hunt + if (NPCS.NPCInfo->goalEntity == NULL) { // hunt NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } NPCS.NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); - + NPC_MoveToGoal(qtrue); } /* @@ -168,26 +159,21 @@ void ATST_Hunt( qboolean visible, qboolean advance ) ATST_Ranged ------------------------- */ -void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) -{ +void ATST_Ranged(qboolean visible, qboolean advance, qboolean altAttack) { - if ( TIMER_Done( NPCS.NPC, "atkDelay" ) && visible ) // Attack? + if (TIMER_Done(NPCS.NPC, "atkDelay") && visible) // Attack? { - TIMER_Set( NPCS.NPC, "atkDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPCS.NPC, "atkDelay", Q_irand(500, 3000)); - if (altAttack) - { - NPCS.ucmd.buttons |= BUTTON_ATTACK|BUTTON_ALT_ATTACK; - } - else - { + if (altAttack) { + NPCS.ucmd.buttons |= BUTTON_ATTACK | BUTTON_ALT_ATTACK; + } else { NPCS.ucmd.buttons |= BUTTON_ATTACK; } } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); } } @@ -196,93 +182,77 @@ void ATST_Ranged( qboolean visible, qboolean advance, qboolean altAttack ) ATST_Attack ------------------------- */ -void ATST_Attack( void ) -{ - qboolean altAttack=qfalse; - int blasterTest,chargerTest,weapon; - float distance; - distance_e distRate; - qboolean visible; - qboolean advance; - - if ( NPC_CheckEnemyExt(qfalse) == qfalse )//!NPC->enemy )// +void ATST_Attack(void) { + qboolean altAttack = qfalse; + int blasterTest, chargerTest, weapon; + float distance; + distance_e distRate; + qboolean visible; + qboolean advance; + + if (NPC_CheckEnemyExt(qfalse) == qfalse) //! NPC->enemy )// { NPCS.NPC->enemy = NULL; return; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Rate our distance to the target, and our visibilty - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ATST_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ATST_Hunt(visible, advance); return; } } // Decide what type of attack to do - switch ( distRate ) - { + switch (distRate) { case DIST_MELEE: -// NPC_ChangeWeapon( WP_ATST_MAIN ); + // NPC_ChangeWeapon( WP_ATST_MAIN ); break; case DIST_LONG: -// NPC_ChangeWeapon( WP_ATST_SIDE ); - //rwwFIXMEFIXME: make atst weaps work. + // NPC_ChangeWeapon( WP_ATST_SIDE ); + // rwwFIXMEFIXME: make atst weaps work. // See if the side weapons are there - blasterTest = trap->G2API_GetSurfaceRenderStatus( NPCS.NPC->ghoul2, 0, "head_light_blaster_cann" ); - chargerTest = trap->G2API_GetSurfaceRenderStatus( NPCS.NPC->ghoul2, 0, "head_concussion_charger" ); + blasterTest = trap->G2API_GetSurfaceRenderStatus(NPCS.NPC->ghoul2, 0, "head_light_blaster_cann"); + chargerTest = trap->G2API_GetSurfaceRenderStatus(NPCS.NPC->ghoul2, 0, "head_concussion_charger"); // It has both side weapons - if ( blasterTest != -1 - && !(blasterTest&TURN_OFF) - && chargerTest != -1 - && !(chargerTest&TURN_OFF)) - { - weapon = Q_irand( 0, 1); // 0 is blaster, 1 is charger (ALT SIDE) + if (blasterTest != -1 && !(blasterTest & TURN_OFF) && chargerTest != -1 && !(chargerTest & TURN_OFF)) { + weapon = Q_irand(0, 1); // 0 is blaster, 1 is charger (ALT SIDE) - if (weapon) // Fire charger + if (weapon) // Fire charger { altAttack = qtrue; - } - else - { + } else { altAttack = qfalse; } - } - else if (blasterTest != -1 - && !(blasterTest & TURN_OFF)) // Blaster is on + } else if (blasterTest != -1 && !(blasterTest & TURN_OFF)) // Blaster is on { altAttack = qfalse; - } - else if (chargerTest != -1 - &&!(chargerTest & TURN_OFF)) // Blaster is on + } else if (chargerTest != -1 && !(chargerTest & TURN_OFF)) // Blaster is on { altAttack = qtrue; - } - else - { - NPC_ChangeWeapon( WP_NONE ); + } else { + NPC_ChangeWeapon(WP_NONE); } break; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - ATST_Ranged( visible, advance,altAttack ); + ATST_Ranged(visible, advance, altAttack); } /* @@ -290,25 +260,20 @@ void ATST_Attack( void ) ATST_Patrol ------------------------- */ -void ATST_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void ATST_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } } - } /* @@ -316,12 +281,11 @@ void ATST_Patrol( void ) ATST_Idle ------------------------- */ -void ATST_Idle( void ) -{ +void ATST_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); } /* @@ -329,22 +293,15 @@ void ATST_Idle( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSATST_Default( void ) -{ - if ( NPCS.NPC->enemy ) - { - if( (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) ) - { +void NPC_BSATST_Default(void) { + if (NPCS.NPC->enemy) { + if ((NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } ATST_Attack(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ATST_Patrol(); - } - else - { + } else { ATST_Idle(); } } diff --git a/codemp/game/NPC_AI_Default.c b/codemp/game/NPC_AI_Default.c index f8050a5245..c7748ad7f9 100644 --- a/codemp/game/NPC_AI_Default.c +++ b/codemp/game/NPC_AI_Default.c @@ -32,23 +32,20 @@ void NPC_LostEnemyDecideChase(void) We lost our enemy and want to drop him but see if we should chase him if we are in the proper bState */ -void NPC_LostEnemyDecideChase(void) -{ - switch( NPCS.NPCInfo->behaviorState ) - { +void NPC_LostEnemyDecideChase(void) { + switch (NPCS.NPCInfo->behaviorState) { case BS_HUNT_AND_KILL: - //We were chasing him and lost him, so try to find him - if ( NPCS.NPC->enemy == NPCS.NPCInfo->goalEntity && NPCS.NPC->enemy->lastWaypoint != WAYPOINT_NONE ) - {//Remember his last valid Wp, then check it out - //FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? - NPC_BSSearchStart( NPCS.NPC->enemy->lastWaypoint, BS_SEARCH ); + // We were chasing him and lost him, so try to find him + if (NPCS.NPC->enemy == NPCS.NPCInfo->goalEntity && NPCS.NPC->enemy->lastWaypoint != WAYPOINT_NONE) { // Remember his last valid Wp, then check it out + // FIXME: Should we only do this if there's no other enemies or we've got LOCKED_ENEMY on? + NPC_BSSearchStart(NPCS.NPC->enemy->lastWaypoint, BS_SEARCH); } - //If he's not our goalEntity, we're running somewhere else, so lose him + // If he's not our goalEntity, we're running somewhere else, so lose him break; default: break; } - G_ClearEnemy( NPCS.NPC ); + G_ClearEnemy(NPCS.NPC); } /* ------------------------- @@ -56,99 +53,87 @@ NPC_StandIdle ------------------------- */ -void NPC_StandIdle( void ) -{ -/* - //Must be done with any other animations - if ( NPC->client->ps.legsAnimTimer != 0 ) - return; +void NPC_StandIdle(void) { + /* + //Must be done with any other animations + if ( NPC->client->ps.legsAnimTimer != 0 ) + return; - //Not ready to do another one - if ( TIMER_Done( NPC, "idleAnim" ) == false ) - return; + //Not ready to do another one + if ( TIMER_Done( NPC, "idleAnim" ) == false ) + return; - int anim = NPC->client->ps.legsAnim; + int anim = NPC->client->ps.legsAnim; - if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) - return; + if ( anim != BOTH_STAND1 && anim != BOTH_STAND2 ) + return; - //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly - int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; + //FIXME: Account for STAND1 or STAND2 here and set the base anim accordingly + int baseSeq = ( anim == BOTH_STAND1 ) ? BOTH_STAND1_RANDOM1 : BOTH_STAND2_RANDOM1; - //Must have at least one random idle animation - //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay - if ( PM_HasAnimation( NPC, baseSeq ) == false ) - return; + //Must have at least one random idle animation + //NOTENOTE: This relies on proper ordering of animations, which SHOULD be okay + if ( PM_HasAnimation( NPC, baseSeq ) == false ) + return; - int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); + int newIdle = Q_irand( 0, MAX_IDLE_ANIMS-1 ); - //FIXME: Technically this could never complete.. but that's not really too likely - while( 1 ) - { - if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) - break; + //FIXME: Technically this could never complete.. but that's not really too likely + while( 1 ) + { + if ( PM_HasAnimation( NPC, baseSeq + newIdle ) ) + break; - newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); - } + newIdle = Q_irand( 0, MAX_IDLE_ANIMS ); + } - //Start that animation going - NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + //Start that animation going + NPC_SetAnim( NPC, SETANIM_BOTH, baseSeq + newIdle, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); + int newTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, (animNumber_t) (baseSeq + newIdle) ); - //Don't do this again for a random amount of time - TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); -*/ + //Don't do this again for a random amount of time + TIMER_Set( NPC, "idleAnim", newTime + Q_irand( 2000, 10000 ) ); + */ } -qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) -{ - qboolean attack_ok = qfalse; - qboolean duck_ok = qfalse; - qboolean faced = qfalse; - float attack_scale = 1.0; - - //First see if we're hurt bad- if so, duck - //FIXME: if even when ducked, we can shoot someone, we should. - //Maybe is can be shot even when ducked, we should run away to the nearest cover? - if ( canDuck ) - { - if ( NPC->health < 20 ) - { - // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) - if( Q_flrand(0.0f, 1.0f) ) - { +qboolean NPC_StandTrackAndShoot(gentity_t *NPC, qboolean canDuck) { + qboolean attack_ok = qfalse; + qboolean duck_ok = qfalse; + qboolean faced = qfalse; + float attack_scale = 1.0; + + // First see if we're hurt bad- if so, duck + // FIXME: if even when ducked, we can shoot someone, we should. + // Maybe is can be shot even when ducked, we should run away to the nearest cover? + if (canDuck) { + if (NPC->health < 20) { + // if( NPC->svFlags&SVF_HEALING || Q_flrand(0.0f, 1.0f) ) + if (Q_flrand(0.0f, 1.0f)) { duck_ok = qtrue; } - } - else if ( NPC->health < 40 ) - { -// if ( NPC->svFlags&SVF_HEALING ) -// {//Medic is on the way, get down! -// duck_ok = qtrue; -// } + } else if (NPC->health < 40) { + // if ( NPC->svFlags&SVF_HEALING ) + // {//Medic is on the way, get down! + // duck_ok = qtrue; + // } } } - //NPC_CheckEnemy( qtrue, qfalse, qtrue ); + // NPC_CheckEnemy( qtrue, qfalse, qtrue ); - if ( !duck_ok ) - {//made this whole part a function call - attack_ok = NPC_CheckCanAttack( attack_scale, qtrue ); + if (!duck_ok) { // made this whole part a function call + attack_ok = NPC_CheckCanAttack(attack_scale, qtrue); faced = qtrue; } - if ( canDuck && (duck_ok || (!attack_ok && NPCS.client->ps.weaponTime <= 0)) && NPCS.ucmd.upmove != -127 ) - {//if we didn't attack check to duck if we're not already - if( !duck_ok ) - { - if ( NPC->enemy->client ) - { - if ( NPC->enemy->enemy == NPC ) - { - if ( NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? + if (canDuck && (duck_ok || (!attack_ok && NPCS.client->ps.weaponTime <= 0)) && + NPCS.ucmd.upmove != -127) { // if we didn't attack check to duck if we're not already + if (!duck_ok) { + if (NPC->enemy->client) { + if (NPC->enemy->enemy == NPC) { + if (NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? { duck_ok = qtrue; } @@ -157,80 +142,66 @@ qboolean NPC_StandTrackAndShoot (gentity_t *NPC, qboolean canDuck) } } - if ( duck_ok ) - {//duck and don't shoot + if (duck_ok) { // duck and don't shoot NPCS.ucmd.upmove = -127; - NPCS.NPCInfo->duckDebounceTime = level.time + 1000;//duck for a full second + NPCS.NPCInfo->duckDebounceTime = level.time + 1000; // duck for a full second } } return faced; } - -void NPC_BSIdle( void ) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSIdle(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - if ( ( NPCS.ucmd.forwardmove == 0 ) && ( NPCS.ucmd.rightmove == 0 ) && ( NPCS.ucmd.upmove == 0 ) ) - { -// NPC_StandIdle(); + if ((NPCS.ucmd.forwardmove == 0) && (NPCS.ucmd.rightmove == 0) && (NPCS.ucmd.upmove == 0)) { + // NPC_StandIdle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCS.ucmd.buttons |= BUTTON_WALKING; } -void NPC_BSRun (void) -{ - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); +void NPC_BSRun(void) { + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSStandGuard (void) -{ - //FIXME: Use Snapshot info - if ( NPCS.NPC->enemy == NULL ) - {//Possible to pick one up by being shot - if( Q_flrand(0.0f, 1.0f) < 0.5 ) - { - if(NPCS.NPC->client->enemyTeam) - { - gentity_t *newenemy = NPC_PickEnemy(NPCS.NPC, NPCS.NPC->client->enemyTeam, (NPCS.NPC->cantHitEnemyCounter < 10), (NPCS.NPC->client->enemyTeam == NPCTEAM_PLAYER), qtrue); - //only checks for vis if couldn't hit last enemy - if(newenemy) - { - G_SetEnemy( NPCS.NPC, newenemy ); +void NPC_BSStandGuard(void) { + // FIXME: Use Snapshot info + if (NPCS.NPC->enemy == NULL) { // Possible to pick one up by being shot + if (Q_flrand(0.0f, 1.0f) < 0.5) { + if (NPCS.NPC->client->enemyTeam) { + gentity_t *newenemy = NPC_PickEnemy(NPCS.NPC, NPCS.NPC->client->enemyTeam, (NPCS.NPC->cantHitEnemyCounter < 10), + (NPCS.NPC->client->enemyTeam == NPCTEAM_PLAYER), qtrue); + // only checks for vis if couldn't hit last enemy + if (newenemy) { + G_SetEnemy(NPCS.NPC, newenemy); } } } } - if ( NPCS.NPC->enemy != NULL ) - { - if( NPCS.NPCInfo->tempBehavior == BS_STAND_GUARD ) - { + if (NPCS.NPC->enemy != NULL) { + if (NPCS.NPCInfo->tempBehavior == BS_STAND_GUARD) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; } - if( NPCS.NPCInfo->behaviorState == BS_STAND_GUARD ) - { + if (NPCS.NPCInfo->behaviorState == BS_STAND_GUARD) { NPCS.NPCInfo->behaviorState = BS_STAND_AND_SHOOT; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -239,92 +210,77 @@ NPC_BSHuntAndKill ------------------------- */ -void NPC_BSHuntAndKill( void ) -{ - qboolean turned = qfalse; - vec3_t vec; - float enemyDist; - visibility_t oEVis; - int curAnim; - - NPC_CheckEnemy( NPCS.NPCInfo->tempBehavior != BS_HUNT_AND_KILL, qfalse, qtrue );//don't find new enemy if this is tempbehav - - if ( NPCS.NPC->enemy ) - { - oEVis = NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|//CHECK_PVS| - if(NPCS.enemyVisibility > VIS_PVS) - { - if ( !NPC_EnemyTooFar( NPCS.NPC->enemy, 0, qtrue ) ) - {//Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here for info on whether ot not to turn later - NPC_CheckCanAttack( 1.0, qfalse ); +void NPC_BSHuntAndKill(void) { + qboolean turned = qfalse; + vec3_t vec; + float enemyDist; + visibility_t oEVis; + int curAnim; + + NPC_CheckEnemy(NPCS.NPCInfo->tempBehavior != BS_HUNT_AND_KILL, qfalse, qtrue); // don't find new enemy if this is tempbehav + + if (NPCS.NPC->enemy) { + oEVis = NPCS.enemyVisibility = NPC_CheckVisibility(NPCS.NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|//CHECK_PVS| + if (NPCS.enemyVisibility > VIS_PVS) { + if (!NPC_EnemyTooFar(NPCS.NPC->enemy, 0, qtrue)) { // Enemy is close enough to shoot - FIXME: this next func does this also, but need to know here + // for info on whether ot not to turn later + NPC_CheckCanAttack(1.0, qfalse); turned = qtrue; } } curAnim = NPCS.NPC->client->ps.legsAnim; - if(curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 ) - {//Don't move toward enemy if we're in a full-body attack anim - //FIXME, use IdealDistance to determin if we need to close distance + if (curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && + curAnim != BOTH_MELEE2) { // Don't move toward enemy if we're in a full-body attack anim + // FIXME, use IdealDistance to determin if we need to close distance VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); enemyDist = VectorLength(vec); - if( enemyDist > 48 && ((enemyDist*1.5)*(enemyDist*1.5) >= NPC_MaxDistSquaredForWeapon() || - oEVis != VIS_SHOOT || - //!(ucmd.buttons & BUTTON_ATTACK) || - enemyDist > IdealDistance(NPCS.NPC)*3 ) ) - {//We should close in? + if (enemyDist > 48 && ((enemyDist * 1.5) * (enemyDist * 1.5) >= NPC_MaxDistSquaredForWeapon() || oEVis != VIS_SHOOT || + //!(ucmd.buttons & BUTTON_ATTACK) || + enemyDist > IdealDistance(NPCS.NPC) * 3)) { // We should close in? NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPC_MoveToGoal( qtrue ); - } - else if(enemyDist < IdealDistance(NPCS.NPC)) - {//We should back off? - //if(ucmd.buttons & BUTTON_ATTACK) + NPC_MoveToGoal(qtrue); + } else if (enemyDist < IdealDistance(NPCS.NPC)) { // We should back off? + // if(ucmd.buttons & BUTTON_ATTACK) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); NPCS.ucmd.forwardmove *= -1; NPCS.ucmd.rightmove *= -1; - VectorScale( NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir ); + VectorScale(NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir); NPCS.ucmd.buttons |= BUTTON_WALKING; } - }//otherwise, stay where we are + } // otherwise, stay where we are } - } - else - {//ok, stand guard until we find an enemy - if( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { + } else { // ok, stand guard until we find an enemy + if (NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCS.NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } return; } - if(!turned) - { + if (!turned) { NPC_UpdateAngles(qtrue, qtrue); } } -void NPC_BSStandAndShoot (void) -{ - //FIXME: - //When our numbers outnumber enemies 3 to 1, or only one of them, - //go into hunt and kill mode +void NPC_BSStandAndShoot(void) { + // FIXME: + // When our numbers outnumber enemies 3 to 1, or only one of them, + // go into hunt and kill mode - //FIXME: - //When they're all dead, go to some script or wander off to sickbay? + // FIXME: + // When they're all dead, go to some script or wander off to sickbay? - if(NPCS.NPC->client->playerTeam && NPCS.NPC->client->enemyTeam) - { - //FIXME: don't realize this right away- or else enemies show up and we're standing around + if (NPCS.NPC->client->playerTeam && NPCS.NPC->client->enemyTeam) { + // FIXME: don't realize this right away- or else enemies show up and we're standing around /* if( teamNumbers[NPC->enemyTeam] == 0 ) {//ok, stand guard until we find another enemy @@ -373,36 +329,29 @@ void NPC_BSStandAndShoot (void) NPC_CheckEnemy(qtrue, qfalse, qtrue); - if(NPCS.NPCInfo->duckDebounceTime > level.time && NPCS.NPC->client->ps.weapon != WP_SABER ) - { + if (NPCS.NPCInfo->duckDebounceTime > level.time && NPCS.NPC->client->ps.weapon != WP_SABER) { NPCS.ucmd.upmove = -127; - if(NPCS.NPC->enemy) - { + if (NPCS.NPC->enemy) { NPC_CheckCanAttack(1.0, qtrue); } return; } - if(NPCS.NPC->enemy) - { - if(!NPC_StandTrackAndShoot( NPCS.NPC, qtrue )) - {//That func didn't update our angles + if (NPCS.NPC->enemy) { + if (!NPC_StandTrackAndShoot(NPCS.NPC, qtrue)) { // That func didn't update our angles NPCS.NPCInfo->desiredYaw = NPCS.NPC->client->ps.viewangles[YAW]; NPCS.NPCInfo->desiredPitch = NPCS.NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); } - } - else - { + } else { NPCS.NPCInfo->desiredYaw = NPCS.NPC->client->ps.viewangles[YAW]; NPCS.NPCInfo->desiredPitch = NPCS.NPC->client->ps.viewangles[PITCH]; NPC_UpdateAngles(qtrue, qtrue); -// NPC_BSIdle();//only moves if we have a goal + // NPC_BSIdle();//only moves if we have a goal } } -void NPC_BSRunAndShoot (void) -{ +void NPC_BSRunAndShoot(void) { /*if(NPC->playerTeam && NPC->enemyTeam) { //FIXME: don't realize this right away- or else enemies show up and we're standing around @@ -416,129 +365,111 @@ void NPC_BSRunAndShoot (void) } }*/ - //NOTE: are we sure we want ALL run and shoot people to move this way? - //Shouldn't it check to see if we have an enemy and our enemy is our goal?! - //Moved that check into NPC_MoveToGoal - //NPCInfo->combatMove = qtrue; + // NOTE: are we sure we want ALL run and shoot people to move this way? + // Shouldn't it check to see if we have an enemy and our enemy is our goal?! + // Moved that check into NPC_MoveToGoal + // NPCInfo->combatMove = qtrue; - NPC_CheckEnemy( qtrue, qfalse, qtrue ); + NPC_CheckEnemy(qtrue, qfalse, qtrue); - if ( NPCS.NPCInfo->duckDebounceTime > level.time ) // && NPCInfo->hidingGoal ) + if (NPCS.NPCInfo->duckDebounceTime > level.time) // && NPCInfo->hidingGoal ) { NPCS.ucmd.upmove = -127; - if ( NPCS.NPC->enemy ) - { - NPC_CheckCanAttack( 1.0, qfalse ); + if (NPCS.NPC->enemy) { + NPC_CheckCanAttack(1.0, qfalse); } return; } - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { int monitor = NPCS.NPC->cantHitEnemyCounter; - NPC_StandTrackAndShoot( NPCS.NPC, qfalse );//(NPCInfo->hidingGoal != NULL) ); + NPC_StandTrackAndShoot(NPCS.NPC, qfalse); //(NPCInfo->hidingGoal != NULL) ); - if ( !(NPCS.ucmd.buttons & BUTTON_ATTACK) && NPCS.ucmd.upmove >= 0 && NPCS.NPC->cantHitEnemyCounter > monitor ) - {//not crouching and not firing - vec3_t vec; + if (!(NPCS.ucmd.buttons & BUTTON_ATTACK) && NPCS.ucmd.upmove >= 0 && NPCS.NPC->cantHitEnemyCounter > monitor) { // not crouching and not firing + vec3_t vec; - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec ); + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); vec[2] = 0; - if ( VectorLength( vec ) > 128 || NPCS.NPC->cantHitEnemyCounter >= 10 ) - {//run at enemy if too far away - //The cantHitEnemyCounter getting high has other repercussions - //100 (10 seconds) will make you try to pick a new enemy... - //But we're chasing, so we clamp it at 50 here - if ( NPCS.NPC->cantHitEnemyCounter > 60 ) - { + if (VectorLength(vec) > 128 || NPCS.NPC->cantHitEnemyCounter >= 10) { // run at enemy if too far away + // The cantHitEnemyCounter getting high has other repercussions + // 100 (10 seconds) will make you try to pick a new enemy... + // But we're chasing, so we clamp it at 50 here + if (NPCS.NPC->cantHitEnemyCounter > 60) { NPCS.NPC->cantHitEnemyCounter = 60; } - if ( NPCS.NPC->cantHitEnemyCounter >= (NPCS.NPCInfo->stats.aggression+1) * 10 ) - { + if (NPCS.NPC->cantHitEnemyCounter >= (NPCS.NPCInfo->stats.aggression + 1) * 10) { NPC_LostEnemyDecideChase(); } - //chase and face + // chase and face NPCS.ucmd.angles[YAW] = 0; NPCS.ucmd.angles[PITCH] = 0; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - //NAV_ClearLastRoute(NPC); - NPC_MoveToGoal( qtrue ); + // NAV_ClearLastRoute(NPC); + NPC_MoveToGoal(qtrue); NPC_UpdateAngles(qtrue, qtrue); + } else { + // FIXME: this could happen if they're just on the other side + // of a thin wall or something else blocking out shot. That + // would make us just stand there and not go around it... + // but maybe it's okay- might look like we're waiting for + // him to come out...? + // Current solution: runs around if cantHitEnemyCounter gets + // to 10 (1 second). } - else - { - //FIXME: this could happen if they're just on the other side - //of a thin wall or something else blocking out shot. That - //would make us just stand there and not go around it... - //but maybe it's okay- might look like we're waiting for - //him to come out...? - //Current solution: runs around if cantHitEnemyCounter gets - //to 10 (1 second). - } - } - else - {//Clear the can't hit enemy counter here + } else { // Clear the can't hit enemy counter here NPCS.NPC->cantHitEnemyCounter = 0; } - } - else - { - if ( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + } else { + if (NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCS.NPCInfo->tempBehavior = BS_DEFAULT; return; } -// NPC_BSRun();//only moves if we have a goal + // NPC_BSRun();//only moves if we have a goal } } -//Simply turn until facing desired angles -void NPC_BSFace (void) -{ - //FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? - //Once this is over, it snaps back to what it was facing before- WHY??? - if( NPC_UpdateAngles ( qtrue, qtrue ) ) - { - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE ); +// Simply turn until facing desired angles +void NPC_BSFace(void) { + // FIXME: once you stop sending turning info, they reset to whatever their delta_angles was last???? + // Once this is over, it snaps back to what it was facing before- WHY??? + if (NPC_UpdateAngles(qtrue, qtrue)) { + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_BSTATE); NPCS.NPCInfo->desiredYaw = NPCS.client->ps.viewangles[YAW]; NPCS.NPCInfo->desiredPitch = NPCS.client->ps.viewangles[PITCH]; - NPCS.NPCInfo->aimTime = 0;//ok to turn normally now + NPCS.NPCInfo->aimTime = 0; // ok to turn normally now } } -void NPC_BSPointShoot (qboolean shoot) -{//FIXME: doesn't check for clear shot... - vec3_t muzzle, dir, angles, org; +void NPC_BSPointShoot(qboolean shoot) { // FIXME: doesn't check for clear shot... + vec3_t muzzle, dir, angles, org; - if ( !NPCS.NPC->enemy || !NPCS.NPC->enemy->inuse || (NPCS.NPC->enemy->NPC && NPCS.NPC->enemy->health <= 0) ) - {//FIXME: should still keep shooting for a second or two after they actually die... - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE ); + if (!NPCS.NPC->enemy || !NPCS.NPC->enemy->inuse || + (NPCS.NPC->enemy->NPC && NPCS.NPC->enemy->health <= 0)) { // FIXME: should still keep shooting for a second or two after they actually die... + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_BSTATE); goto finished; } CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); - CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, org);//Was spot_org - //Head is a little high, so let's aim for the chest: - if ( NPCS.NPC->enemy->client ) - { - org[2] -= 12;//NOTE: is this enough? + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, org); // Was spot_org + // Head is a little high, so let's aim for the chest: + if (NPCS.NPC->enemy->client) { + org[2] -= 12; // NOTE: is this enough? } VectorSubtract(org, muzzle, dir); vectoangles(dir, angles); - switch( NPCS.NPC->client->ps.weapon ) - { + switch (NPCS.NPC->client->ps.weapon) { case WP_NONE: case WP_STUN_BATON: case WP_SABER: - //don't do any pitch change if not holding a firing weapon + // don't do any pitch change if not holding a firing weapon break; default: NPCS.NPCInfo->desiredPitch = NPCS.NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); @@ -547,25 +478,21 @@ void NPC_BSPointShoot (qboolean shoot) NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); - if ( NPC_UpdateAngles ( qtrue, qtrue ) ) - {//FIXME: if angles clamped, this may never work! - //NPCInfo->shotTime = NPC->attackDebounceTime = 0; + if (NPC_UpdateAngles(qtrue, qtrue)) { // FIXME: if angles clamped, this may never work! + // NPCInfo->shotTime = NPC->attackDebounceTime = 0; - if ( shoot ) - {//FIXME: needs to hold this down if using a weapon that requires it, like phaser... + if (shoot) { // FIXME: needs to hold this down if using a weapon that requires it, like phaser... NPCS.ucmd.buttons |= BUTTON_ATTACK; } - //if ( !shoot || !(NPC->svFlags & SVF_LOCKEDENEMY) ) - if (1) - {//If locked_enemy is on, dont complete until it is destroyed... - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE ); + // if ( !shoot || !(NPC->svFlags & SVF_LOCKEDENEMY) ) + if (1) { // If locked_enemy is on, dont complete until it is destroyed... + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_BSTATE); goto finished; } } - //else if ( shoot && (NPC->svFlags & SVF_LOCKEDENEMY) ) - if (0) - {//shooting them till their dead, not aiming right at them yet... + // else if ( shoot && (NPC->svFlags & SVF_LOCKEDENEMY) ) + if (0) { // shooting them till their dead, not aiming right at them yet... /* qboolean movingTarget = qfalse; @@ -584,25 +511,22 @@ void NPC_BSPointShoot (qboolean shoot) if (movingTarget ) */ { - float dist = VectorLength( dir ); - float yawMiss, yawMissAllow = NPCS.NPC->enemy->r.maxs[0]; - float pitchMiss, pitchMissAllow = (NPCS.NPC->enemy->r.maxs[2] - NPCS.NPC->enemy->r.mins[2])/2; + float dist = VectorLength(dir); + float yawMiss, yawMissAllow = NPCS.NPC->enemy->r.maxs[0]; + float pitchMiss, pitchMissAllow = (NPCS.NPC->enemy->r.maxs[2] - NPCS.NPC->enemy->r.mins[2]) / 2; - if ( yawMissAllow < 8.0f ) - { + if (yawMissAllow < 8.0f) { yawMissAllow = 8.0f; } - if ( pitchMissAllow < 8.0f ) - { + if (pitchMissAllow < 8.0f) { pitchMissAllow = 8.0f; } - yawMiss = tan(DEG2RAD(AngleDelta ( NPCS.NPC->client->ps.viewangles[YAW], NPCS.NPCInfo->desiredYaw ))) * dist; - pitchMiss = tan(DEG2RAD(AngleDelta ( NPCS.NPC->client->ps.viewangles[PITCH], NPCS.NPCInfo->desiredPitch))) * dist; + yawMiss = tan(DEG2RAD(AngleDelta(NPCS.NPC->client->ps.viewangles[YAW], NPCS.NPCInfo->desiredYaw))) * dist; + pitchMiss = tan(DEG2RAD(AngleDelta(NPCS.NPC->client->ps.viewangles[PITCH], NPCS.NPCInfo->desiredPitch))) * dist; - if ( yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss ) - { + if (yawMissAllow >= yawMiss && pitchMissAllow > pitchMiss) { NPCS.ucmd.buttons |= BUTTON_ATTACK; } } @@ -614,31 +538,26 @@ void NPC_BSPointShoot (qboolean shoot) NPCS.NPCInfo->desiredYaw = NPCS.client->ps.viewangles[YAW]; NPCS.NPCInfo->desiredPitch = NPCS.client->ps.viewangles[PITCH]; - NPCS.NPCInfo->aimTime = 0;//ok to turn normally now + NPCS.NPCInfo->aimTime = 0; // ok to turn normally now } /* void NPC_BSMove(void) Move in a direction, face another */ -void NPC_BSMove(void) -{ - gentity_t *goal = NULL; +void NPC_BSMove(void) { + gentity_t *goal = NULL; NPC_CheckEnemy(qtrue, qfalse, qtrue); - if(NPCS.NPC->enemy) - { + if (NPCS.NPC->enemy) { NPC_CheckCanAttack(1.0, qfalse); - } - else - { + } else { NPC_UpdateAngles(qtrue, qtrue); } goal = UpdateGoal(); - if(goal) - { -// NPCInfo->moveToGoalMod = 1.0; + if (goal) { + // NPCInfo->moveToGoalMod = 1.0; NPC_SlideMoveToGoal(); } @@ -649,14 +568,12 @@ void NPC_BSShoot(void) Move in a direction, face another */ -void NPC_BSShoot(void) -{ -// NPC_BSMove(); +void NPC_BSShoot(void) { + // NPC_BSMove(); NPCS.enemyVisibility = VIS_SHOOT; - if ( NPCS.client->ps.weaponstate != WEAPON_READY && NPCS.client->ps.weaponstate != WEAPON_FIRING ) - { + if (NPCS.client->ps.weaponstate != WEAPON_READY && NPCS.client->ps.weaponstate != WEAPON_FIRING) { NPCS.client->ps.weaponstate = WEAPON_READY; } @@ -669,23 +586,20 @@ void NPC_BSPatrol( void ) Same as idle, but you look for enemies every "vigilance" using your angles, HFOV, VFOV and visrange, and listen for sounds within earshot... */ -void NPC_BSPatrol( void ) -{ - //int alertEventNum; +void NPC_BSPatrol(void) { + // int alertEventNum; - if(level.time > NPCS.NPCInfo->enemyCheckDebounceTime) - { + if (level.time > NPCS.NPCInfo->enemyCheckDebounceTime) { NPCS.NPCInfo->enemyCheckDebounceTime = level.time + (NPCS.NPCInfo->stats.vigilance * 1000); NPC_CheckEnemy(qtrue, qfalse, qtrue); - if(NPCS.NPC->enemy) - {//FIXME: do anger script + if (NPCS.NPC->enemy) { // FIXME: do anger script NPCS.NPCInfo->behaviorState = BS_HUNT_AND_KILL; - //NPC_AngerSound(); + // NPC_AngerSound(); return; } } - //FIXME: Implement generic sound alerts + // FIXME: Implement generic sound alerts /* alertEventNum = NPC_CheckAlertEvents( qtrue, qtrue ); if( alertEventNum != -1 ) @@ -698,14 +612,13 @@ void NPC_BSPatrol( void ) */ NPCS.NPCInfo->investigateSoundDebounceTime = 0; - //FIXME if there is no nav data, we need to do something else - // if we're stuck, try to move around it - if ( UpdateGoal() ) - { - NPC_MoveToGoal( qtrue ); + // FIXME if there is no nav data, we need to do something else + // if we're stuck, try to move around it + if (UpdateGoal()) { + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCS.ucmd.buttons |= BUTTON_WALKING; } @@ -714,252 +627,218 @@ void NPC_BSPatrol( void ) void NPC_BSDefault(void) uses various scriptflags to determine how an npc should behave */ -extern void NPC_CheckGetNewWeapon( void ); -extern void NPC_BSST_Attack( void ); - -void NPC_BSDefault( void ) -{ -// vec3_t enemyDir; -// float enemyDist; -// float shootDist; -// qboolean enemyFOV = qfalse; -// qboolean enemyShotFOV = qfalse; -// qboolean enemyPVS = qfalse; -// vec3_t enemyHead; -// vec3_t muzzle; -// qboolean enemyLOS = qfalse; -// qboolean enemyCS = qfalse; - qboolean move = qtrue; -// qboolean shoot = qfalse; - - - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); - } - - if ( NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - if( NPCS.NPC->client->ps.torsoAnim != TORSO_SURRENDER_START ) - { - NPC_SetAnim( NPCS.NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD ); - } - } - //look for a new enemy if don't have one and are allowed to look, validate current enemy if have one - NPC_CheckEnemy( (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES), qfalse, qtrue ); - if ( !NPCS.NPC->enemy ) - {//still don't have an enemy - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//check for alert events - //FIXME: Check Alert events, see if we should investigate or just look at it - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); - - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID ) - {//heard/saw something - if ( level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - {//was a big event - if ( level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPCS.NPC, level.alertEvents[alertEvent].owner ); +extern void NPC_CheckGetNewWeapon(void); +extern void NPC_BSST_Attack(void); + +void NPC_BSDefault(void) { + // vec3_t enemyDir; + // float enemyDist; + // float shootDist; + // qboolean enemyFOV = qfalse; + // qboolean enemyShotFOV = qfalse; + // qboolean enemyPVS = qfalse; + // vec3_t enemyHead; + // vec3_t muzzle; + // qboolean enemyLOS = qfalse; + // qboolean enemyCS = qfalse; + qboolean move = qtrue; + // qboolean shoot = qfalse; + + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); + } + + if (NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + if (NPCS.NPC->client->ps.torsoAnim != TORSO_SURRENDER_START) { + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD); + } + } + // look for a new enemy if don't have one and are allowed to look, validate current enemy if have one + NPC_CheckEnemy((NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES), qfalse, qtrue); + if (!NPCS.NPC->enemy) { // still don't have an enemy + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // check for alert events + // FIXME: Check Alert events, see if we should investigate or just look at it + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); + + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID) { // heard/saw something + if (level.alertEvents[alertEvent].level >= AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { // was a big event + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && + level.alertEvents[alertEvent].owner->health >= 0 && + level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPCS.NPC, level.alertEvents[alertEvent].owner); } - } - else - {//FIXME: investigate lesser events + } else { // FIXME: investigate lesser events } } - //FIXME: also check our allies' condition? + // FIXME: also check our allies' condition? } } - if ( NPCS.NPC->enemy && !(NPCS.NPCInfo->scriptFlags&SCF_FORCED_MARCH) ) - { + if (NPCS.NPC->enemy && !(NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH)) { // just use the stormtrooper attack AI... NPC_CheckGetNewWeapon(); - if ( NPCS.NPC->client->leader - && NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader - && !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - { + if (NPCS.NPC->client->leader && NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader && + !trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { NPC_ClearGoal(); } - NPC_BSST_Attack(); + NPC_BSST_Attack(); return; -/* - //have an enemy - //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? - VectorSubtract( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin, enemyDir ); - enemyDist = VectorNormalize( enemyDir ); - enemyDist *= enemyDist; - shootDist = NPC_MaxDistSquaredForWeapon(); - - enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); - enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); - enemyPVS = trap->inPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin ); - - if ( enemyPVS ) - {//in the pvs - trace_t tr; - - CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); - enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); - CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); - - trap->trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); - enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); - } - else - {//skip thr 2 traces since they would have to fail - enemyLOS = qfalse; - enemyCS = qfalse; - } + /* + //have an enemy + //FIXME: if one of these fails, meaning we can't shoot, do we really need to do the rest? + VectorSubtract( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin, enemyDir ); + enemyDist = VectorNormalize( enemyDir ); + enemyDist *= enemyDist; + shootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyCS && enemyShotFOV ) - {//can hit enemy if we want - NPC->cantHitEnemyCounter = 0; - } - else - {//can't hit - NPC->cantHitEnemyCounter++; - } + enemyFOV = InFOV( NPC->enemy, NPC, NPCInfo->stats.hfov, NPCInfo->stats.vfov ); + enemyShotFOV = InFOV( NPC->enemy, NPC, 20, 20 ); + enemyPVS = trap->inPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin ); - if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) - {//can shoot - shoot = qtrue; - if ( NPCInfo->goalEntity == NPC->enemy ) - {//my goal is my enemy and I have a clear shot, no need to chase right now - move = qfalse; - } - } - else - {//don't shoot yet, keep chasing - shoot = qfalse; - move = qtrue; - } + if ( enemyPVS ) + {//in the pvs + trace_t tr; - //shoot decision - if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//try to shoot - if ( NPC->enemy ) - { - if ( shoot ) - { - if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemyHead ); + enemyHead[2] -= Q_flrand( 0.0f, NPC->enemy->maxs[2]*0.5f ); + CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + enemyLOS = NPC_ClearLOS( muzzle, enemyHead ); + + trap->trace ( &tr, muzzle, vec3_origin, vec3_origin, enemyHead, NPC->s.number, MASK_SHOT ); + enemyCS = NPC_EvaluateShot( tr.entityNum, qtrue ); + } + else + {//skip thr 2 traces since they would have to fail + enemyLOS = qfalse; + enemyCS = qfalse; + } + + if ( enemyCS && enemyShotFOV ) + {//can hit enemy if we want + NPC->cantHitEnemyCounter = 0; + } + else + {//can't hit + NPC->cantHitEnemyCounter++; + } + + if ( enemyCS && enemyShotFOV && enemyDist < shootDist ) + {//can shoot + shoot = qtrue; + if ( NPCInfo->goalEntity == NPC->enemy ) + {//my goal is my enemy and I have a clear shot, no need to chase right now + move = qfalse; + } + } + else + {//don't shoot yet, keep chasing + shoot = qfalse; + move = qtrue; + } + + //shoot decision + if ( !(NPCInfo->scriptFlags&SCF_DONT_FIRE) ) + {//try to shoot + if ( NPC->enemy ) { - WeaponThink( qtrue ); + if ( shoot ) + { + if( !(NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + { + WeaponThink( qtrue ); + } + } } } - } - } - //chase decision - if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//go after him - NPCInfo->goalEntity = NPC->enemy; - //FIXME: don't need to chase when have a clear shot and in range? - if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) - {//haven't been able to shoot enemy for about 6 seconds, need to do something - //FIXME: combat points? Just chase? - if ( enemyPVS ) - {//in my PVS, just pick a combat point - //FIXME: implement + //chase decision + if ( NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + {//go after him + NPCInfo->goalEntity = NPC->enemy; + //FIXME: don't need to chase when have a clear shot and in range? + if ( !enemyCS && NPC->cantHitEnemyCounter > 60 ) + {//haven't been able to shoot enemy for about 6 seconds, need to do something + //FIXME: combat points? Just chase? + if ( enemyPVS ) + {//in my PVS, just pick a combat point + //FIXME: implement + } + else + {//just chase him + } + } + //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? } - else - {//just chase him + else if ( NPC->cantHitEnemyCounter > 60 ) + {//pick a new one + NPC_CheckEnemy( qtrue, qfalse, qtrue ); } - } - //FIXME: in normal behavior, should we use combat Points? Do we care? Is anyone actually going to ever use this AI? - } - else if ( NPC->cantHitEnemyCounter > 60 ) - {//pick a new one - NPC_CheckEnemy( qtrue, qfalse, qtrue ); - } - if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) - {//have a clear LOS to him//, but not looking at him - //Find the desired angles - vec3_t angles; + if ( enemyPVS && enemyLOS )//&& !enemyShotFOV ) + {//have a clear LOS to him//, but not looking at him + //Find the desired angles + vec3_t angles; - GetAnglesForDirection( muzzle, enemyHead, angles ); + GetAnglesForDirection( muzzle, enemyHead, angles ); - NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); - NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); - } - */ + NPCInfo->desiredYaw = AngleNormalize180( angles[YAW] ); + NPCInfo->desiredPitch = AngleNormalize180( angles[PITCH] ); + } + */ } - if ( UpdateGoal() ) - {//have a goal - if ( !NPCS.NPC->enemy - && NPCS.NPC->client->leader - && NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader - && !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - { + if (UpdateGoal()) { // have a goal + if (!NPCS.NPC->enemy && NPCS.NPC->client->leader && NPCS.NPCInfo->goalEntity == NPCS.NPC->client->leader && + !trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { NPC_BSFollowLeader(); - } - else - { - //set angles - if ( (NPCS.NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy ) - {//face direction of movement, NOTE: default behavior when not chasing enemy + } else { + // set angles + if ((NPCS.NPCInfo->scriptFlags & SCF_FACE_MOVE_DIR) || + NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy) { // face direction of movement, NOTE: default behavior when not chasing enemy NPCS.NPCInfo->combatMove = qfalse; - } - else - {//face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? - vec3_t dir, angles; + } else { // face goal.. FIXME: what if have a navgoal but want to face enemy while moving? Will this do that? + vec3_t dir, angles; NPCS.NPCInfo->combatMove = qfalse; - VectorSubtract( NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir); + vectoangles(dir, angles); NPCS.NPCInfo->desiredYaw = angles[YAW]; - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - { + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { NPCS.NPCInfo->desiredPitch = angles[PITCH]; } } - //set movement - //override default walk/run behavior - //NOTE: redundant, done in NPC_ApplyScriptFlags - if ( NPCS.NPCInfo->scriptFlags & SCF_RUNNING ) - { + // set movement + // override default walk/run behavior + // NOTE: redundant, done in NPC_ApplyScriptFlags + if (NPCS.NPCInfo->scriptFlags & SCF_RUNNING) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_WALKING ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_WALKING) { NPCS.ucmd.buttons |= BUTTON_WALKING; - } - else if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - { + } else if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - } - else - { + } else { NPCS.ucmd.buttons |= BUTTON_WALKING; } - if ( NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH ) - {//being forced to walk - //if ( g_crosshairEntNum != NPC->s.number ) - if (!NPC_SomeoneLookingAtMe(NPCS.NPC)) - {//don't walk if player isn't aiming at me + if (NPCS.NPCInfo->scriptFlags & SCF_FORCED_MARCH) { // being forced to walk + // if ( g_crosshairEntNum != NPC->s.number ) + if (!NPC_SomeoneLookingAtMe(NPCS.NPC)) { // don't walk if player isn't aiming at me move = qfalse; } } - if ( move ) - { - //move toward goal - NPC_MoveToGoal( qtrue ); + if (move) { + // move toward goal + NPC_MoveToGoal(qtrue); } } - } - else if ( !NPCS.NPC->enemy && NPCS.NPC->client->leader ) - { + } else if (!NPCS.NPC->enemy && NPCS.NPC->client->leader) { NPC_BSFollowLeader(); } - //update angles - NPC_UpdateAngles( qtrue, qtrue ); + // update angles + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codemp/game/NPC_AI_Droid.c b/codemp/game/NPC_AI_Droid.c index 4491e4bbcd..95e392f83b 100644 --- a/codemp/game/NPC_AI_Droid.c +++ b/codemp/game/NPC_AI_Droid.c @@ -22,48 +22,39 @@ along with this program; if not, see . #include "b_local.h" -//static void R5D2_LookAround( void ); -float NPC_GetPainChance( gentity_t *self, int damage ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +// static void R5D2_LookAround( void ); +float NPC_GetPainChance(gentity_t *self, int damage); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; /* ------------------------- R2D2_PartsMove ------------------------- */ -void R2D2_PartsMove(void) -{ +void R2D2_PartsMove(void) { // Front 'eye' lense - if ( TIMER_Done(NPCS.NPC,"eyeDelay") ) - { - NPCS.NPC->pos1[1] = AngleNormalize360( NPCS.NPC->pos1[1]); + if (TIMER_Done(NPCS.NPC, "eyeDelay")) { + NPCS.NPC->pos1[1] = AngleNormalize360(NPCS.NPC->pos1[1]); - NPCS.NPC->pos1[0]+=Q_irand( -20, 20 ); // Roll - NPCS.NPC->pos1[1]=Q_irand( -20, 20 ); - NPCS.NPC->pos1[2]=Q_irand( -20, 20 ); + NPCS.NPC->pos1[0] += Q_irand(-20, 20); // Roll + NPCS.NPC->pos1[1] = Q_irand(-20, 20); + NPCS.NPC->pos1[2] = Q_irand(-20, 20); /* if (NPC->genericBone1) { - trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL ); + trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + NEGATIVE_Z, NULL ); } */ NPC_SetBoneAngles(NPCS.NPC, "f_eye", NPCS.NPC->pos1); - - TIMER_Set( NPCS.NPC, "eyeDelay", Q_irand( 100, 1000 ) ); + TIMER_Set(NPCS.NPC, "eyeDelay", Q_irand(100, 1000)); } } @@ -72,11 +63,10 @@ void R2D2_PartsMove(void) NPC_BSDroid_Idle ------------------------- */ -void Droid_Idle( void ) -{ -// VectorCopy( NPCInfo->investigateGoal, lookPos ); +void Droid_Idle(void) { + // VectorCopy( NPCInfo->investigateGoal, lookPos ); -// NPC_FacePosition( lookPos ); + // NPC_FacePosition( lookPos ); } /* @@ -84,36 +74,26 @@ void Droid_Idle( void ) R2D2_TurnAnims ------------------------- */ -void R2D2_TurnAnims ( void ) -{ +void R2D2_TurnAnims(void) { float turndelta; - int anim; + int anim; turndelta = AngleDelta(NPCS.NPC->r.currentAngles[YAW], NPCS.NPCInfo->desiredYaw); - if ((fabs(turndelta) > 20) && ((NPCS.NPC->client->NPC_class == CLASS_R2D2) || (NPCS.NPC->client->NPC_class == CLASS_R5D2))) - { + if ((fabs(turndelta) > 20) && ((NPCS.NPC->client->NPC_class == CLASS_R2D2) || (NPCS.NPC->client->NPC_class == CLASS_R5D2))) { anim = NPCS.NPC->client->ps.legsAnim; - if (turndelta<0) - { - if (anim != BOTH_TURN_LEFT1) - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (turndelta < 0) { + if (anim != BOTH_TURN_LEFT1) { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_TURN_LEFT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - { - if (anim != BOTH_TURN_RIGHT1) - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + if (anim != BOTH_TURN_RIGHT1) { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_TURN_RIGHT1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } + } else { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - } /* @@ -121,72 +101,57 @@ void R2D2_TurnAnims ( void ) Droid_Patrol ------------------------- */ -void Droid_Patrol( void ) -{ +void Droid_Patrol(void) { - NPCS.NPC->pos1[1] = AngleNormalize360( NPCS.NPC->pos1[1]); + NPCS.NPC->pos1[1] = AngleNormalize360(NPCS.NPC->pos1[1]); - if ( NPCS.NPC->client && NPCS.NPC->client->NPC_class != CLASS_GONK ) - { - if (NPCS.NPC->client->NPC_class != CLASS_R5D2) - { //he doesn't have an eye. - R2D2_PartsMove(); // Get his eye moving. + if (NPCS.NPC->client && NPCS.NPC->client->NPC_class != CLASS_GONK) { + if (NPCS.NPC->client->NPC_class != CLASS_R5D2) { // he doesn't have an eye. + R2D2_PartsMove(); // Get his eye moving. } R2D2_TurnAnims(); } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); - if( NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_MOUSE ) - { - NPCS.NPCInfo->desiredYaw += sin(level.time*.5) * 25; // Weaves side to side a little + if (NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_MOUSE) { + NPCS.NPCInfo->desiredYaw += sin(level.time * .5) * 25; // Weaves side to side a little - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)) ); + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_R2D2 ) - { - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)) ); + } else if (NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_R2D2) { + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else if( NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_R5D2 ) - { - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)) ); + } else if (NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_R5D2) { + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } } - if( NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_GONK ) - { - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)) ); + if (NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_GONK) { + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } } -// else -// { -// R5D2_LookAround(); -// } + // else + // { + // R5D2_LookAround(); + // } } - NPC_UpdateAngles( qtrue, qtrue ); - + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -194,31 +159,25 @@ void Droid_Patrol( void ) Droid_Run ------------------------- */ -void Droid_Run( void ) -{ +void Droid_Run(void) { R2D2_PartsMove(); - if ( NPCS.NPCInfo->localState == LSTATE_BACKINGUP ) - { + if (NPCS.NPCInfo->localState == LSTATE_BACKINGUP) { NPCS.ucmd.forwardmove = -127; NPCS.NPCInfo->desiredYaw += 5; - NPCS.NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. - } - else - { + NPCS.NPCInfo->localState = LSTATE_NONE; // So he doesn't constantly backup. + } else { NPCS.ucmd.forwardmove = 64; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { - if (NPC_MoveToGoal( qfalse )) - { - NPCS.NPCInfo->desiredYaw += sin(level.time*.5) * 5; // Weaves side to side a little + // If we have somewhere to go, then do that + if (UpdateGoal()) { + if (NPC_MoveToGoal(qfalse)) { + NPCS.NPCInfo->desiredYaw += sin(level.time * .5) * 5; // Weaves side to side a little } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -226,65 +185,47 @@ void Droid_Run( void ) void Droid_Spin( void ) ------------------------- */ -void Droid_Spin( void ) -{ - vec3_t dir = {0,0,1}; +void Droid_Spin(void) { + vec3_t dir = {0, 0, 1}; R2D2_TurnAnims(); - // Head is gone, spin and spark - if ( NPCS.NPC->client->NPC_class == CLASS_R5D2 - || NPCS.NPC->client->NPC_class == CLASS_R2D2 ) - { + if (NPCS.NPC->client->NPC_class == CLASS_R5D2 || NPCS.NPC->client->NPC_class == CLASS_R2D2) { // No head? - if (trap->G2API_GetSurfaceRenderStatus( NPCS.NPC->ghoul2, 0, "head" )>0) - { - if (TIMER_Done(NPCS.NPC,"smoke") && !TIMER_Done(NPCS.NPC,"droidsmoketotal")) - { - TIMER_Set( NPCS.NPC, "smoke", 100); - G_PlayEffectID( G_EffectIndex("volumetric/droid_smoke") , NPCS.NPC->r.currentOrigin,dir); + if (trap->G2API_GetSurfaceRenderStatus(NPCS.NPC->ghoul2, 0, "head") > 0) { + if (TIMER_Done(NPCS.NPC, "smoke") && !TIMER_Done(NPCS.NPC, "droidsmoketotal")) { + TIMER_Set(NPCS.NPC, "smoke", 100); + G_PlayEffectID(G_EffectIndex("volumetric/droid_smoke"), NPCS.NPC->r.currentOrigin, dir); } - if (TIMER_Done(NPCS.NPC,"droidspark")) - { - TIMER_Set( NPCS.NPC, "droidspark", Q_irand(100,500)); - G_PlayEffectID( G_EffectIndex("sparks/spark"), NPCS.NPC->r.currentOrigin,dir); + if (TIMER_Done(NPCS.NPC, "droidspark")) { + TIMER_Set(NPCS.NPC, "droidspark", Q_irand(100, 500)); + G_PlayEffectID(G_EffectIndex("sparks/spark"), NPCS.NPC->r.currentOrigin, dir); } - NPCS.ucmd.forwardmove = Q_irand( -64, 64); + NPCS.ucmd.forwardmove = Q_irand(-64, 64); - if (TIMER_Done(NPCS.NPC,"roam")) - { - TIMER_Set( NPCS.NPC, "roam", Q_irand( 250, 1000 ) ); - NPCS.NPCInfo->desiredYaw = Q_irand( 0, 360 ); // Go in random directions + if (TIMER_Done(NPCS.NPC, "roam")) { + TIMER_Set(NPCS.NPC, "roam", Q_irand(250, 1000)); + NPCS.NPCInfo->desiredYaw = Q_irand(0, 360); // Go in random directions } - } - else - { - if (TIMER_Done(NPCS.NPC,"roam")) - { + } else { + if (TIMER_Done(NPCS.NPC, "roam")) { NPCS.NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCS.NPCInfo->desiredYaw = AngleNormalize360(NPCS.NPCInfo->desiredYaw + 40); // Spin around } } - } - else - { - if (TIMER_Done(NPCS.NPC,"roam")) - { + } else { + if (TIMER_Done(NPCS.NPC, "roam")) { NPCS.NPCInfo->localState = LSTATE_NONE; - } - else - { + } else { NPCS.NPCInfo->desiredYaw = AngleNormalize360(NPCS.NPCInfo->desiredYaw + 40); // Spin around } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -292,178 +233,147 @@ void Droid_Spin( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Droid_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Droid_Pain(gentity_t *self, gentity_t *attacker, int damage) { gentity_t *other = attacker; - int anim; - int mod = gPainMOD; - float pain_chance; + int anim; + int mod = gPainMOD; + float pain_chance; - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->client->NPC_class == CLASS_R5D2 ) - { - pain_chance = NPC_GetPainChance( self, damage ); + if (self->client->NPC_class == CLASS_R5D2) { + pain_chance = NPC_GetPainChance(self, damage); // Put it in pain - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { // Health is between 0-30 or was hit by a DEMP2 so pop his head - if ( !self->s.m_iVehicleNum - && ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) ) - { - if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE + if (!self->s.m_iVehicleNum && (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT)) { + if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE { - if ((self->NPC->localState != LSTATE_SPINNING) && - (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "head" ))) - { - NPC_SetSurfaceOnOff( self, "head", TURN_OFF ); - - if ( self->client->ps.m_iVehicleNum ) - { - vec3_t up; - AngleVectors( self->r.currentAngles, NULL, NULL, up ); - G_PlayEffectID( G_EffectIndex("chunks/r5d2head_veh"), self->r.currentOrigin, up ); - } - else - { - G_PlayEffectID( G_EffectIndex("small_chunks") , self->r.currentOrigin, vec3_origin ); - G_PlayEffectID( G_EffectIndex("chunks/r5d2head"), self->r.currentOrigin, vec3_origin ); + if ((self->NPC->localState != LSTATE_SPINNING) && (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "head"))) { + NPC_SetSurfaceOnOff(self, "head", TURN_OFF); + + if (self->client->ps.m_iVehicleNum) { + vec3_t up; + AngleVectors(self->r.currentAngles, NULL, NULL, up); + G_PlayEffectID(G_EffectIndex("chunks/r5d2head_veh"), self->r.currentOrigin, up); + } else { + G_PlayEffectID(G_EffectIndex("small_chunks"), self->r.currentOrigin, vec3_origin); + G_PlayEffectID(G_EffectIndex("chunks/r5d2head"), self->r.currentOrigin, vec3_origin); } - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->client->ps.electrifyTime = level.time + 3000; - TIMER_Set( self, "droidsmoketotal", 5000); - TIMER_Set( self, "droidspark", 100); + TIMER_Set(self, "droidsmoketotal", 5000); + TIMER_Set(self, "droidspark", 100); self->NPC->localState = LSTATE_SPINNING; } } } // Just give him normal pain for a little while - else - { + else { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); + TIMER_Set(self, "roam", Q_irand(1000, 2000)); } } - } - else if (self->client->NPC_class == CLASS_MOUSE) - { - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + } else if (self->client->NPC_class == CLASS_MOUSE) { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->localState = LSTATE_SPINNING; - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->client->ps.electrifyTime = level.time + 3000; - } - else - { + } else { self->NPC->localState = LSTATE_BACKINGUP; } self->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; - } - else if (self->client->NPC_class == CLASS_R2D2) - { + } else if (self->client->NPC_class == CLASS_R2D2) { - pain_chance = NPC_GetPainChance( self, damage ); + pain_chance = NPC_GetPainChance(self, damage); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? Demp2 always does this + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? Demp2 always does this { // Health is between 0-30 or was hit by a DEMP2 so pop his head - if ( !self->s.m_iVehicleNum - && ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) ) - { - if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE + if (!self->s.m_iVehicleNum && (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT)) { + if (!(self->spawnflags & 2)) // Doesn't have to ALWAYSDIE { - if ((self->NPC->localState != LSTATE_SPINNING) && - (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "head" ))) - { - NPC_SetSurfaceOnOff( self, "head", TURN_OFF ); - - if ( self->client->ps.m_iVehicleNum ) - { - vec3_t up; - AngleVectors( self->r.currentAngles, NULL, NULL, up ); - G_PlayEffectID( G_EffectIndex("chunks/r2d2head_veh"), self->r.currentOrigin, up ); - } - else - { - G_PlayEffectID( G_EffectIndex("small_chunks") , self->r.currentOrigin, vec3_origin ); - G_PlayEffectID( G_EffectIndex("chunks/r2d2head"), self->r.currentOrigin, vec3_origin ); + if ((self->NPC->localState != LSTATE_SPINNING) && (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "head"))) { + NPC_SetSurfaceOnOff(self, "head", TURN_OFF); + + if (self->client->ps.m_iVehicleNum) { + vec3_t up; + AngleVectors(self->r.currentAngles, NULL, NULL, up); + G_PlayEffectID(G_EffectIndex("chunks/r2d2head_veh"), self->r.currentOrigin, up); + } else { + G_PlayEffectID(G_EffectIndex("small_chunks"), self->r.currentOrigin, vec3_origin); + G_PlayEffectID(G_EffectIndex("chunks/r2d2head"), self->r.currentOrigin, vec3_origin); } - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->client->ps.electrifyTime = level.time + 3000; - TIMER_Set( self, "droidsmoketotal", 5000); - TIMER_Set( self, "droidspark", 100); + TIMER_Set(self, "droidsmoketotal", 5000); + TIMER_Set(self, "droidspark", 100); self->NPC->localState = LSTATE_SPINNING; } } } // Just give him normal pain for a little while - else - { + else { anim = self->client->ps.legsAnim; - if ( anim == BOTH_STAND2 ) // On two legs? + if (anim == BOTH_STAND2) // On two legs? { anim = BOTH_PAIN1; - } - else // On three legs + } else // On three legs { anim = BOTH_PAIN2; } - NPC_SetAnim( self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); // Spin around in pain self->NPC->localState = LSTATE_SPINNING; - TIMER_Set( self, "roam", Q_irand(1000,2000)); + TIMER_Set(self, "roam", Q_irand(1000, 2000)); } } - } - else if ( self->client->NPC_class == CLASS_INTERROGATOR && ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) && other ) - { + } else if (self->client->NPC_class == CLASS_INTERROGATOR && (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - VectorSubtract( self->r.currentOrigin, other->r.currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->r.currentOrigin, other->r.currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - NPC_Pain( self, attacker, damage); + NPC_Pain(self, attacker, damage); } - /* ------------------------- Droid_Pain ------------------------- */ -void Droid_Pain(void) -{ - if (TIMER_Done(NPCS.NPC,"droidpain")) //He's done jumping around +void Droid_Pain(void) { + if (TIMER_Done(NPCS.NPC, "droidpain")) // He's done jumping around { NPCS.NPCInfo->localState = LSTATE_NONE; } @@ -474,18 +384,16 @@ void Droid_Pain(void) NPC_Mouse_Precache ------------------------- */ -void NPC_Mouse_Precache( void ) -{ - int i; +void NPC_Mouse_Precache(void) { + int i; - for (i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/mouse/misc/mousego%d.wav", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", i)); } - G_EffectIndex( "env/small_explode" ); - G_SoundIndex( "sound/chars/mouse/misc/death1" ); - G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + G_EffectIndex("env/small_explode"); + G_SoundIndex("sound/chars/mouse/misc/death1"); + G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); } /* @@ -493,22 +401,20 @@ void NPC_Mouse_Precache( void ) NPC_R5D2_Precache ------------------------- */ -void NPC_R5D2_Precache(void) -{ +void NPC_R5D2_Precache(void) { int i; - for ( i = 1; i < 5; i++) - { - G_SoundIndex( va( "sound/chars/r5d2/misc/r5talk%d.wav", i ) ); + for (i = 1; i < 5; i++) { + G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", i)); } - //G_SoundIndex( "sound/chars/r5d2/misc/falling1.wav" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); - G_EffectIndex( "env/med_explode"); - G_EffectIndex( "volumetric/droid_smoke" ); + // G_SoundIndex( "sound/chars/r5d2/misc/falling1.wav" ); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); + G_EffectIndex("env/med_explode"); + G_EffectIndex("volumetric/droid_smoke"); G_EffectIndex("sparks/spark"); - G_EffectIndex( "chunks/r5d2head"); - G_EffectIndex( "chunks/r5d2head_veh"); + G_EffectIndex("chunks/r5d2head"); + G_EffectIndex("chunks/r5d2head_veh"); } /* @@ -516,22 +422,20 @@ void NPC_R5D2_Precache(void) NPC_R2D2_Precache ------------------------- */ -void NPC_R2D2_Precache(void) -{ +void NPC_R2D2_Precache(void) { int i; - for ( i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/r2d2/misc/r2d2talk0%d.wav", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", i)); } - //G_SoundIndex( "sound/chars/r2d2/misc/falling1.wav" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); // ?? - G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); - G_EffectIndex( "env/med_explode"); - G_EffectIndex( "volumetric/droid_smoke" ); + // G_SoundIndex( "sound/chars/r2d2/misc/falling1.wav" ); + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // ?? + G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); + G_EffectIndex("env/med_explode"); + G_EffectIndex("volumetric/droid_smoke"); G_EffectIndex("sparks/spark"); - G_EffectIndex( "chunks/r2d2head"); - G_EffectIndex( "chunks/r2d2head_veh"); + G_EffectIndex("chunks/r2d2head"); + G_EffectIndex("chunks/r2d2head_veh"); } /* @@ -539,8 +443,7 @@ void NPC_R2D2_Precache(void) NPC_Gonk_Precache ------------------------- */ -void NPC_Gonk_Precache( void ) -{ +void NPC_Gonk_Precache(void) { G_SoundIndex("sound/chars/gonk/misc/gonktalk1.wav"); G_SoundIndex("sound/chars/gonk/misc/gonktalk2.wav"); @@ -548,7 +451,7 @@ void NPC_Gonk_Precache( void ) G_SoundIndex("sound/chars/gonk/misc/death2.wav"); G_SoundIndex("sound/chars/gonk/misc/death3.wav"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("env/med_explode"); } /* @@ -556,10 +459,9 @@ void NPC_Gonk_Precache( void ) NPC_Protocol_Precache ------------------------- */ -void NPC_Protocol_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" ); - G_EffectIndex( "env/med_explode"); +void NPC_Protocol_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); + G_EffectIndex("env/med_explode"); } /* @@ -616,28 +518,18 @@ static void R5D2_LookAround( void ) NPC_BSDroid_Default ------------------------- */ -void NPC_BSDroid_Default( void ) -{ +void NPC_BSDroid_Default(void) { - if ( NPCS.NPCInfo->localState == LSTATE_SPINNING ) - { + if (NPCS.NPCInfo->localState == LSTATE_SPINNING) { Droid_Spin(); - } - else if ( NPCS.NPCInfo->localState == LSTATE_PAIN ) - { + } else if (NPCS.NPCInfo->localState == LSTATE_PAIN) { Droid_Pain(); - } - else if ( NPCS.NPCInfo->localState == LSTATE_DROP ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else if (NPCS.NPCInfo->localState == LSTATE_DROP) { + NPC_UpdateAngles(qtrue, qtrue); NPCS.ucmd.upmove = Q_flrand(-1.0f, 1.0f) * 64; - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Droid_Patrol(); - } - else - { + } else { Droid_Run(); } } diff --git a/codemp/game/NPC_AI_GalakMech.c b/codemp/game/NPC_AI_GalakMech.c index b8fd462f7c..b120b72b5c 100644 --- a/codemp/game/NPC_AI_GalakMech.c +++ b/codemp/game/NPC_AI_GalakMech.c @@ -25,28 +25,27 @@ along with this program; if not, see . #include "anims.h" #include "w_saber.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void NPC_AimAdjust( int change ); -extern qboolean WP_LobFire( gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, - vec3_t velocity, qboolean tracePath, int ignoreEntNum, int enemyNum, - float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit ); -extern void G_SoundOnEnt (gentity_t *ent, soundChannel_t channel, const char *soundPath); - -extern qboolean BG_CrouchAnim( int anim ); - -#define MELEE_DIST_SQUARED 6400//80*80 -#define MIN_LOB_DIST_SQUARED 65536//256*256 -#define MAX_LOB_DIST_SQUARED 200704//448*448 -#define REPEATER_ALT_SIZE 3 // half of bbox size -#define GENERATOR_HEALTH 25 -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 -#define GALAK_SHIELD_HEALTH 500 - -static vec3_t shieldMins = {-60, -60, -24 }; +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void NPC_AimAdjust(int change); +extern qboolean WP_LobFire(gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, vec3_t velocity, qboolean tracePath, + int ignoreEntNum, int enemyNum, float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +extern qboolean BG_CrouchAnim(int anim); + +#define MELEE_DIST_SQUARED 6400 // 80*80 +#define MIN_LOB_DIST_SQUARED 65536 // 256*256 +#define MAX_LOB_DIST_SQUARED 200704 // 448*448 +#define REPEATER_ALT_SIZE 3 // half of bbox size +#define GENERATOR_HEALTH 25 +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 +#define GALAK_SHIELD_HEALTH 500 + +static vec3_t shieldMins = {-60, -60, -24}; static vec3_t shieldMaxs = {60, 60, 80}; -extern qboolean NPC_CheckPlayerTeamStealth( void ); +extern qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS4; static qboolean enemyCS4; @@ -54,90 +53,77 @@ static qboolean hitAlly4; static qboolean faceEnemy4; static qboolean move4; static qboolean shoot4; -static float enemyDist4; -static vec3_t impactPos4; - -void NPC_GalakMech_Precache( void ) -{ - G_SoundIndex( "sound/weapons/galak/skewerhit.wav" ); - G_SoundIndex( "sound/weapons/galak/lasercharge.wav" ); - G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); - G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ); - - G_EffectIndex( "galak/trace_beam" ); - G_EffectIndex( "galak/beam_warmup" ); -// G_EffectIndex( "small_chunks"); - G_EffectIndex( "env/med_explode2"); - G_EffectIndex( "env/small_explode2"); - G_EffectIndex( "galak/explode"); - G_EffectIndex( "blaster/smoke_bolton"); -// G_EffectIndex( "env/exp_trail_comp"); +static float enemyDist4; +static vec3_t impactPos4; + +void NPC_GalakMech_Precache(void) { + G_SoundIndex("sound/weapons/galak/skewerhit.wav"); + G_SoundIndex("sound/weapons/galak/lasercharge.wav"); + G_SoundIndex("sound/weapons/galak/lasercutting.wav"); + G_SoundIndex("sound/weapons/galak/laserdamage.wav"); + + G_EffectIndex("galak/trace_beam"); + G_EffectIndex("galak/beam_warmup"); + // G_EffectIndex( "small_chunks"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("env/small_explode2"); + G_EffectIndex("galak/explode"); + G_EffectIndex("blaster/smoke_bolton"); + // G_EffectIndex( "env/exp_trail_comp"); } -void NPC_GalakMech_Init( gentity_t *ent ) -{ - if (ent->NPC->behaviorState != BS_CINEMATIC) - { +void NPC_GalakMech_Init(gentity_t *ent) { + if (ent->NPC->behaviorState != BS_CINEMATIC) { ent->client->ps.stats[STAT_ARMOR] = GALAK_SHIELD_HEALTH; ent->NPC->investigateCount = ent->NPC->investigateDebounceTime = 0; - ent->flags |= FL_SHIELDED;//reflect normal shots - //rwwFIXMEFIXME: Support PW_GALAK_SHIELD - //ent->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE;//temp, for effect - //ent->fx_time = level.time; - VectorSet( ent->r.mins, -60, -60, -24 ); - VectorSet( ent->r.maxs, 60, 60, 80 ); - ent->flags |= FL_NO_KNOCKBACK;//don't get pushed - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "smackTime", 0 ); - TIMER_Set( ent, "beamDelay", 0 ); - TIMER_Set( ent, "noLob", 0 ); - TIMER_Set( ent, "noRapid", 0 ); - TIMER_Set( ent, "talkDebounce", 0 ); - - NPC_SetSurfaceOnOff( ent, "torso_shield", TURN_ON ); - NPC_SetSurfaceOnOff( ent, "torso_galakface", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_galakhead", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_eyes_mouth", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_collar", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_galaktorso", TURN_OFF ); - } - else - { -// NPC_SetSurfaceOnOff( ent, "helmet", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_shield", TURN_OFF ); - NPC_SetSurfaceOnOff( ent, "torso_galakface", TURN_ON ); - NPC_SetSurfaceOnOff( ent, "torso_galakhead", TURN_ON ); - NPC_SetSurfaceOnOff( ent, "torso_eyes_mouth", TURN_ON ); - NPC_SetSurfaceOnOff( ent, "torso_collar", TURN_ON ); - NPC_SetSurfaceOnOff( ent, "torso_galaktorso", TURN_ON ); + ent->flags |= FL_SHIELDED; // reflect normal shots + // rwwFIXMEFIXME: Support PW_GALAK_SHIELD + // ent->client->ps.powerups[PW_GALAK_SHIELD] = Q3_INFINITE;//temp, for effect + // ent->fx_time = level.time; + VectorSet(ent->r.mins, -60, -60, -24); + VectorSet(ent->r.maxs, 60, 60, 80); + ent->flags |= FL_NO_KNOCKBACK; // don't get pushed + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "smackTime", 0); + TIMER_Set(ent, "beamDelay", 0); + TIMER_Set(ent, "noLob", 0); + TIMER_Set(ent, "noRapid", 0); + TIMER_Set(ent, "talkDebounce", 0); + + NPC_SetSurfaceOnOff(ent, "torso_shield", TURN_ON); + NPC_SetSurfaceOnOff(ent, "torso_galakface", TURN_OFF); + NPC_SetSurfaceOnOff(ent, "torso_galakhead", TURN_OFF); + NPC_SetSurfaceOnOff(ent, "torso_eyes_mouth", TURN_OFF); + NPC_SetSurfaceOnOff(ent, "torso_collar", TURN_OFF); + NPC_SetSurfaceOnOff(ent, "torso_galaktorso", TURN_OFF); + } else { + // NPC_SetSurfaceOnOff( ent, "helmet", TURN_OFF ); + NPC_SetSurfaceOnOff(ent, "torso_shield", TURN_OFF); + NPC_SetSurfaceOnOff(ent, "torso_galakface", TURN_ON); + NPC_SetSurfaceOnOff(ent, "torso_galakhead", TURN_ON); + NPC_SetSurfaceOnOff(ent, "torso_eyes_mouth", TURN_ON); + NPC_SetSurfaceOnOff(ent, "torso_collar", TURN_ON); + NPC_SetSurfaceOnOff(ent, "torso_galaktorso", TURN_ON); } - } //----------------------------------------------------------------- -static void GM_CreateExplosion( gentity_t *self, const int boltID, qboolean doSmall ) //doSmall = qfalse +static void GM_CreateExplosion(gentity_t *self, const int boltID, qboolean doSmall) // doSmall = qfalse { - if ( boltID >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; + if (boltID >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - trap->G2API_GetBoltMatrix( self->ghoul2, 0, - boltID, - &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, - NULL, self->modelScale ); + trap->G2API_GetBoltMatrix(self->ghoul2, 0, boltID, &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, self->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); - if ( doSmall ) - { - G_PlayEffectID( G_EffectIndex("env/small_explode2"), org, dir ); - } - else - { - G_PlayEffectID( G_EffectIndex("env/med_explode2"), org, dir ); + if (doSmall) { + G_PlayEffectID(G_EffectIndex("env/small_explode2"), org, dir); + } else { + G_PlayEffectID(G_EffectIndex("env/med_explode2"), org, dir); } } } @@ -148,99 +134,83 @@ GM_Dying ------------------------- */ -void GM_Dying( gentity_t *self ) -{ - if ( level.time - self->s.time < 4000 ) - {//FIXME: need a real effect - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + 1000; +void GM_Dying(gentity_t *self) { + if (level.time - self->s.time < 4000) { // FIXME: need a real effect + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + 1000; self->client->ps.electrifyTime = level.time + 1000; - if ( TIMER_Done( self, "dyingExplosion" ) ) - { - int newBolt; - switch ( Q_irand( 1, 14 ) ) - { + if (TIMER_Done(self, "dyingExplosion")) { + int newBolt; + switch (Q_irand(1, 14)) { // Find place to generate explosion case 1: - if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_hand" )) - {//r_hand still there - GM_CreateExplosion( self, trap->G2API_AddBolt(self->ghoul2, 0, "*flasha"), qtrue ); - NPC_SetSurfaceOnOff( self, "r_hand", TURN_OFF ); - } - else if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_arm_middle" )) - {//r_arm_middle still there - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*r_arm_elbow" ); - NPC_SetSurfaceOnOff( self, "r_arm_middle", TURN_OFF ); + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "r_hand")) { // r_hand still there + GM_CreateExplosion(self, trap->G2API_AddBolt(self->ghoul2, 0, "*flasha"), qtrue); + NPC_SetSurfaceOnOff(self, "r_hand", TURN_OFF); + } else if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "r_arm_middle")) { // r_arm_middle still there + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_arm_elbow"); + NPC_SetSurfaceOnOff(self, "r_arm_middle", TURN_OFF); } break; case 2: - //FIXME: do only once? - if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_hand" )) - {//l_hand still there - GM_CreateExplosion( self, trap->G2API_AddBolt(self->ghoul2, 0, "*flashc"), qfalse ); - NPC_SetSurfaceOnOff( self, "l_hand", TURN_OFF ); - } - else if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm_wrist" )) - {//l_arm_wrist still there - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_arm_cap_l_hand" ); - NPC_SetSurfaceOnOff( self, "l_arm_wrist", TURN_OFF ); - } - else if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm_middle" )) - {//l_arm_middle still there - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_arm_cap_l_hand" ); - NPC_SetSurfaceOnOff( self, "l_arm_middle", TURN_OFF ); - } - else if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm_augment" )) - {//l_arm_augment still there - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_arm_elbow" ); - NPC_SetSurfaceOnOff( self, "l_arm_augment", TURN_OFF ); + // FIXME: do only once? + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_hand")) { // l_hand still there + GM_CreateExplosion(self, trap->G2API_AddBolt(self->ghoul2, 0, "*flashc"), qfalse); + NPC_SetSurfaceOnOff(self, "l_hand", TURN_OFF); + } else if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_arm_wrist")) { // l_arm_wrist still there + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_arm_cap_l_hand"); + NPC_SetSurfaceOnOff(self, "l_arm_wrist", TURN_OFF); + } else if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_arm_middle")) { // l_arm_middle still there + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_arm_cap_l_hand"); + NPC_SetSurfaceOnOff(self, "l_arm_middle", TURN_OFF); + } else if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_arm_augment")) { // l_arm_augment still there + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_arm_elbow"); + NPC_SetSurfaceOnOff(self, "l_arm_augment", TURN_OFF); } break; case 3: case 4: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*hip_fr" ); - GM_CreateExplosion( self, newBolt, qfalse ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*hip_fr"); + GM_CreateExplosion(self, newBolt, qfalse); break; case 5: case 6: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*shldr_l" ); - GM_CreateExplosion( self, newBolt, qfalse ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*shldr_l"); + GM_CreateExplosion(self, newBolt, qfalse); break; case 7: case 8: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*uchest_r" ); - GM_CreateExplosion( self, newBolt, qfalse ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*uchest_r"); + GM_CreateExplosion(self, newBolt, qfalse); break; case 9: case 10: - GM_CreateExplosion( self, self->client->renderInfo.headBolt, qfalse ); + GM_CreateExplosion(self, self->client->renderInfo.headBolt, qfalse); break; case 11: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_leg_knee" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_leg_knee"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 12: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*r_leg_knee" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_leg_knee"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 13: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_leg_foot" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_leg_foot"); + GM_CreateExplosion(self, newBolt, qtrue); break; case 14: - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*r_leg_foot" ); - GM_CreateExplosion( self, newBolt, qtrue ); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_leg_foot"); + GM_CreateExplosion(self, newBolt, qtrue); break; } - TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1100 ) ); + TIMER_Set(self, "dyingExplosion", Q_irand(300, 1100)); } - } - else - {//one final, huge explosion - G_PlayEffectID( G_EffectIndex("galak/explode"), self->r.currentOrigin, vec3_origin ); -// G_PlayEffect( "small_chunks", self->r.currentOrigin ); -// G_PlayEffect( "env/exp_trail_comp", self->r.currentOrigin, self->currentAngles ); + } else { // one final, huge explosion + G_PlayEffectID(G_EffectIndex("galak/explode"), self->r.currentOrigin, vec3_origin); + // G_PlayEffect( "small_chunks", self->r.currentOrigin ); + // G_PlayEffect( "env/exp_trail_comp", self->r.currentOrigin, self->currentAngles ); self->nextthink = level.time + FRAMETIME; self->think = G_FreeEntity; } @@ -252,9 +222,8 @@ NPC_GM_Pain ------------------------- */ -extern void NPC_SetPainEvent( gentity_t *self ); -void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +extern void NPC_SetPainEvent(gentity_t *self); +void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage) { vec3_t point; gentity_t *inflictor = attacker; int hitLoc = 1; @@ -262,10 +231,10 @@ void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage) VectorCopy(gPainPoint, point); - //if ( self->client->ps.powerups[PW_GALAK_SHIELD] == 0 ) - if (0) //rwwFIXMEFIXME: do all of this - {//shield is currently down - //FIXME: allow for radius damage? + // if ( self->client->ps.powerups[PW_GALAK_SHIELD] == 0 ) + if (0) // rwwFIXMEFIXME: do all of this + { // shield is currently down + // FIXME: allow for radius damage? /* if ( (hitLoc==HL_GENERIC1) && (self->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH) ) { @@ -287,28 +256,21 @@ void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage) G_AddEvent( self, Q_irand( EV_DEATH1, EV_DEATH3 ), self->health ); } */ - } - else - {//store the point for shield impact + } else { // store the point for shield impact #ifdef _DISABLED - if ( point ) - { - // VectorCopy( point, self->pos4 ); - // self->client->poisonTime = level.time; - //rwwFIXMEFIXME: ..do this is as well. + if (point) { + // VectorCopy( point, self->pos4 ); + // self->client->poisonTime = level.time; + // rwwFIXMEFIXME: ..do this is as well. } #endif //_DISABLED } - if ( !self->lockCount && self->client->ps.torsoTimer <= 0 ) - {//don't interrupt laser sweep attack or other special attacks/moves - if ( self->count < 4 && self->health > 100 && hitLoc != HL_GENERIC1 ) - { - if ( self->delay < level.time ) - { + if (!self->lockCount && self->client->ps.torsoTimer <= 0) { // don't interrupt laser sweep attack or other special attacks/moves + if (self->count < 4 && self->health > 100 && hitLoc != HL_GENERIC1) { + if (self->delay < level.time) { int speech; - switch( self->count ) - { + switch (self->count) { default: case 0: speech = EV_PUSHED1; @@ -325,49 +287,35 @@ void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage) } self->count++; self->NPC->blockedSpeechDebounceTime = 0; - G_AddVoiceEvent( self, speech, Q_irand( 3000, 5000 ) ); - self->delay = level.time + Q_irand( 5000, 7000 ); + G_AddVoiceEvent(self, speech, Q_irand(3000, 5000)); + self->delay = level.time + Q_irand(5000, 7000); } - } - else - { + } else { NPC_Pain(self, attacker, damage); } - } - else if ( hitLoc == HL_GENERIC1 ) - { - NPC_SetPainEvent( self ); - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); + } else if (hitLoc == HL_GENERIC1) { + NPC_SetPainEvent(self); + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); self->client->ps.electrifyTime = level.time + Q_irand(500, 2500); } - if ( inflictor && inflictor->lastEnemy == self ) - {//He force-pushed my own lobfires back at me - if ( mod == MOD_REPEATER_ALT && !Q_irand( 0, 2 ) ) - { - if ( TIMER_Done( self, "noRapid" ) ) - { + if (inflictor && inflictor->lastEnemy == self) { // He force-pushed my own lobfires back at me + if (mod == MOD_REPEATER_ALT && !Q_irand(0, 2)) { + if (TIMER_Done(self, "noRapid")) { self->NPC->scriptFlags &= ~SCF_ALT_FIRE; self->alt_fire = qfalse; - TIMER_Set( self, "noLob", Q_irand( 2000, 6000 ) ); + TIMER_Set(self, "noLob", Q_irand(2000, 6000)); + } else { // hopefully this will make us fire the laser + TIMER_Set(self, "noLob", Q_irand(1000, 2000)); } - else - {//hopefully this will make us fire the laser - TIMER_Set( self, "noLob", Q_irand( 1000, 2000 ) ); - } - } - else if ( mod == MOD_REPEATER && !Q_irand( 0, 5 ) ) - { - if ( TIMER_Done( self, "noLob" ) ) - { + } else if (mod == MOD_REPEATER && !Q_irand(0, 5)) { + if (TIMER_Done(self, "noLob")) { self->NPC->scriptFlags |= SCF_ALT_FIRE; self->alt_fire = qtrue; - TIMER_Set( self, "noRapid", Q_irand( 2000, 6000 ) ); - } - else - {//hopefully this will make us fire the laser - TIMER_Set( self, "noRapid", Q_irand( 1000, 2000 ) ); + TIMER_Set(self, "noRapid", Q_irand(2000, 6000)); + } else { // hopefully this will make us fire the laser + TIMER_Set(self, "noRapid", Q_irand(1000, 2000)); } } } @@ -379,11 +327,10 @@ GM_HoldPosition ------------------------- */ -static void GM_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qtrue ); - if ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//don't have a script waiting for me to get to my point, okay to stop trying and stand +static void GM_HoldPosition(void) { + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qtrue); + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // don't have a script waiting for me to get to my point, okay to stop trying and stand NPCS.NPCInfo->goalEntity = NULL; } } @@ -393,33 +340,29 @@ static void GM_HoldPosition( void ) GM_Move ------------------------- */ -static qboolean GM_Move( void ) -{ +static qboolean GM_Move(void) { qboolean moved; navInfo_t info; - NPCS.NPCInfo->combatMove = qtrue;//always move straight toward our goal + NPCS.NPCInfo->combatMove = qtrue; // always move straight toward our goal - moved = NPC_MoveToGoal( qtrue ); + moved = NPC_MoveToGoal(qtrue); - //Get the move info - NAV_GetLastMove( &info ); + // Get the move info + NAV_GetLastMove(&info); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPCS.NPC->enemy ) - { + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPCS.NPC->enemy) { GM_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//FIXME: if we're going to a combat point, need to pick a different one - if ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//can't transfer movegoal or stop when a script we're running is waiting to complete + // If our move failed, then reset + if (moved == qfalse) { // FIXME: if we're going to a combat point, need to pick a different one + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // can't transfer movegoal or stop when a script we're running is waiting to complete GM_HoldPosition(); } } @@ -433,22 +376,19 @@ NPC_BSGM_Patrol ------------------------- */ -void NPC_BSGM_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGM_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -457,23 +397,21 @@ GM_CheckMoveState ------------------------- */ -static void GM_CheckMoveState( void ) -{ - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//moving toward a goal that a script is waiting on, so don't stop for anything! +static void GM_CheckMoveState(void) { + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { // moving toward a goal that a script is waiting on, so don't stop for anything! move4 = qtrue; } - //See if we're moving towards a goal, not the enemy - if ( ( NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy ) && ( NPCS.NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, qfalse ) || - ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) && enemyLOS4 && enemyDist4 <= 10000 ) ) - {//either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and found our enemy + // See if we're moving towards a goal, not the enemy + if ((NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy) && (NPCS.NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, qfalse) || + (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV) && enemyLOS4 && + enemyDist4 <= 10000)) { // either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and + // found our enemy NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels + // don't attack right away + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels return; } } @@ -485,86 +423,70 @@ GM_CheckFireState ------------------------- */ -static void GM_CheckFireState( void ) -{ - if ( enemyCS4 ) - {//if have a clear shot, always try +static void GM_CheckFireState(void) { + if (enemyCS4) { // if have a clear shot, always try return; } - if ( !VectorCompare( NPCS.NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPCS.NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //See if we should continue to fire on their last position - if ( !hitAlly4 && NPCS.NPCInfo->enemyLastSeenTime > 0 ) - { - if ( level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000 ) - { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + // See if we should continue to fire on their last position + if (!hitAlly4 && NPCS.NPCInfo->enemyLastSeenTime > 0) { + if (level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000) { + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; float distThreshold; float dist; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos4, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos4, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPCS.NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - trap->Trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - VectorCopy( tr.endpos, impactPos4 ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPCS.NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + trap->Trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + VectorCopy(tr.endpos, impactPos4); } - //see if impact would be too close to me - distThreshold = 16384/*128*128*/;//default - if ( NPCS.NPC->s.weapon == WP_REPEATER ) - { - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + // see if impact would be too close to me + distThreshold = 16384 /*128*128*/; // default + if (NPCS.NPC->s.weapon == WP_REPEATER) { + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } } - dist = DistanceSquared( impactPos4, muzzle ); + dist = DistanceSquared(impactPos4, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000 ) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - if ( NPCS.NPC->s.weapon == WP_REPEATER ) - { - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + } else if (level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + if (NPCS.NPC->s.weapon == WP_REPEATER) { + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } } - dist = DistanceSquared( impactPos4, NPCS.NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos4, NPCS.NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCS.NPCInfo->desiredYaw = angles[YAW]; - NPCS.NPCInfo->desiredPitch = angles[PITCH]; + NPCS.NPCInfo->desiredYaw = angles[YAW]; + NPCS.NPCInfo->desiredPitch = angles[PITCH]; shoot4 = qtrue; faceEnemy4 = qfalse; @@ -575,33 +497,30 @@ static void GM_CheckFireState( void ) } } -void NPC_GM_StartLaser( void ) -{ - if ( !NPCS.NPC->lockCount ) - {//haven't already started a laser attack - //warm up for the beam attack +void NPC_GM_StartLaser(void) { + if (!NPCS.NPC->lockCount) { // haven't already started a laser attack + // warm up for the beam attack #if 0 NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_RAISEWEAP2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); #endif - TIMER_Set( NPCS.NPC, "beamDelay", NPCS.NPC->client->ps.torsoTimer ); - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer+3000 ); + TIMER_Set(NPCS.NPC, "beamDelay", NPCS.NPC->client->ps.torsoTimer); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer + 3000); NPCS.NPC->lockCount = 1; - //turn on warmup effect - G_PlayEffectID( G_EffectIndex("galak/beam_warmup"), NPCS.NPC->r.currentOrigin, vec3_origin ); - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, "sound/weapons/galak/lasercharge.wav" ); + // turn on warmup effect + G_PlayEffectID(G_EffectIndex("galak/beam_warmup"), NPCS.NPC->r.currentOrigin, vec3_origin); + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, "sound/weapons/galak/lasercharge.wav"); } } -void GM_StartGloat( void ) -{ +void GM_StartGloat(void) { NPCS.NPC->wait = 0; - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_galakface", TURN_ON ); - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_galakhead", TURN_ON ); - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_eyes_mouth", TURN_ON ); - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_collar", TURN_ON ); - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_galaktorso", TURN_ON ); + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_galakface", TURN_ON); + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_galakhead", TURN_ON); + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_eyes_mouth", TURN_ON); + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_collar", TURN_ON); + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_galaktorso", TURN_ON); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_STAND2TO1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPC->client->ps.legsTimer += 500; NPCS.NPC->client->ps.torsoTimer += 500; } @@ -611,12 +530,10 @@ NPC_BSGM_Attack ------------------------- */ -void NPC_BSGM_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPCS.NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGM_Attack(void) { + // Don't do anything if we're hurt + if (NPCS.NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -684,9 +601,8 @@ void NPC_BSGM_Attack( void ) } #endif - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse || !NPCS.NPC->enemy ) - { + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt(qfalse) == qfalse || !NPCS.NPC->enemy) { NPCS.NPC->enemy = NULL; NPC_BSGM_Patrol(); return; @@ -697,62 +613,53 @@ void NPC_BSGM_Attack( void ) faceEnemy4 = qfalse; shoot4 = qfalse; hitAlly4 = qfalse; - VectorClear( impactPos4 ); - enemyDist4 = DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); + VectorClear(impactPos4); + enemyDist4 = DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); - //if ( NPC->client->ps.torsoAnim == BOTH_ATTACK4 || + // if ( NPC->client->ps.torsoAnim == BOTH_ATTACK4 || // NPC->client->ps.torsoAnim == BOTH_ATTACK5 ) - if (0) - { + if (0) { shoot4 = qfalse; - if ( TIMER_Done( NPCS.NPC, "smackTime" ) && !NPCS.NPCInfo->blockedDebounceTime ) - {//time to smack - //recheck enemyDist4 and InFront - if ( enemyDist4 < MELEE_DIST_SQUARED && InFront( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f ) ) - { - vec3_t smackDir; - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, smackDir ); + if (TIMER_Done(NPCS.NPC, "smackTime") && !NPCS.NPCInfo->blockedDebounceTime) { // time to smack + // recheck enemyDist4 and InFront + if (enemyDist4 < MELEE_DIST_SQUARED && + InFront(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f)) { + vec3_t smackDir; + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, smackDir); smackDir[2] += 30; - VectorNormalize( smackDir ); - //hurt them - G_Sound( NPCS.NPC->enemy, CHAN_AUTO, G_SoundIndex( "sound/weapons/galak/skewerhit.wav" ) ); - G_Damage( NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, smackDir, NPCS.NPC->r.currentOrigin, (g_npcspskill.integer+1)*Q_irand( 5, 10), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_CRUSH ); - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK4 ) - {//smackdown + VectorNormalize(smackDir); + // hurt them + G_Sound(NPCS.NPC->enemy, CHAN_AUTO, G_SoundIndex("sound/weapons/galak/skewerhit.wav")); + G_Damage(NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, smackDir, NPCS.NPC->r.currentOrigin, (g_npcspskill.integer + 1) * Q_irand(5, 10), + DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, MOD_CRUSH); + if (NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK4) { // smackdown int knockAnim = BOTH_KNOCKDOWN1; - if ( BG_CrouchAnim( NPCS.NPC->enemy->client->ps.legsAnim ) ) - {//knockdown from crouch + if (BG_CrouchAnim(NPCS.NPC->enemy->client->ps.legsAnim)) { // knockdown from crouch knockAnim = BOTH_KNOCKDOWN4; } - //throw them + // throw them smackDir[2] = 1; - VectorNormalize( smackDir ); - G_Throw( NPCS.NPC->enemy, smackDir, 50 ); - NPC_SetAnim( NPCS.NPC->enemy, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//uppercut - //throw them - G_Throw( NPCS.NPC->enemy, smackDir, 100 ); - //make them backflip - NPC_SetAnim( NPCS.NPC->enemy, SETANIM_BOTH, BOTH_KNOCKDOWN5, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + VectorNormalize(smackDir); + G_Throw(NPCS.NPC->enemy, smackDir, 50); + NPC_SetAnim(NPCS.NPC->enemy, SETANIM_BOTH, knockAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // uppercut + // throw them + G_Throw(NPCS.NPC->enemy, smackDir, 100); + // make them backflip + NPC_SetAnim(NPCS.NPC->enemy, SETANIM_BOTH, BOTH_KNOCKDOWN5, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //done with the damage + // done with the damage NPCS.NPCInfo->blockedDebounceTime = 1; } } - } - else if ( NPCS.NPC->lockCount ) //already shooting laser - {//sometimes use the laser beam attack, but only after he's taken down our generator + } else if (NPCS.NPC->lockCount) // already shooting laser + { // sometimes use the laser beam attack, but only after he's taken down our generator shoot4 = qfalse; - if ( NPCS.NPC->lockCount == 1 ) - {//charging up - if ( TIMER_Done( NPCS.NPC, "beamDelay" ) ) - {//time to start the beam + if (NPCS.NPC->lockCount == 1) { // charging up + if (TIMER_Done(NPCS.NPC, "beamDelay")) { // time to start the beam int laserAnim; - //if ( Q_irand( 0, 1 ) ) - if (1) - { + // if ( Q_irand( 0, 1 ) ) + if (1) { laserAnim = BOTH_ATTACK2; } /* @@ -761,75 +668,58 @@ void NPC_BSGM_Attack( void ) laserAnim = BOTH_ATTACK7; } */ - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, laserAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer + Q_irand( 1000, 3000 ) ); - //turn on beam effect + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, laserAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer + Q_irand(1000, 3000)); + // turn on beam effect NPCS.NPC->lockCount = 2; - G_PlayEffectID( G_EffectIndex("galak/trace_beam"), NPCS.NPC->r.currentOrigin, vec3_origin ); - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); - if ( !NPCS.NPCInfo->coverTarg ) - {//for moving looping sound at end of trace + G_PlayEffectID(G_EffectIndex("galak/trace_beam"), NPCS.NPC->r.currentOrigin, vec3_origin); + NPCS.NPC->s.loopSound = G_SoundIndex("sound/weapons/galak/lasercutting.wav"); + if (!NPCS.NPCInfo->coverTarg) { // for moving looping sound at end of trace NPCS.NPCInfo->coverTarg = G_Spawn(); - if ( NPCS.NPCInfo->coverTarg ) - { - G_SetOrigin( NPCS.NPCInfo->coverTarg, NPCS.NPC->client->renderInfo.muzzlePoint ); + if (NPCS.NPCInfo->coverTarg) { + G_SetOrigin(NPCS.NPCInfo->coverTarg, NPCS.NPC->client->renderInfo.muzzlePoint); NPCS.NPCInfo->coverTarg->r.svFlags |= SVF_BROADCAST; - NPCS.NPCInfo->coverTarg->s.loopSound = G_SoundIndex( "sound/weapons/galak/lasercutting.wav" ); + NPCS.NPCInfo->coverTarg->s.loopSound = G_SoundIndex("sound/weapons/galak/lasercutting.wav"); } } } - } - else - {//in the actual attack now - if ( NPCS.NPC->client->ps.torsoTimer <= 0 ) - {//attack done! + } else { // in the actual attack now + if (NPCS.NPC->client->ps.torsoTimer <= 0) { // attack done! NPCS.NPC->lockCount = 0; - G_FreeEntity( NPCS.NPCInfo->coverTarg ); + G_FreeEntity(NPCS.NPCInfo->coverTarg); NPCS.NPC->s.loopSound = 0; #if 0 NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_DROPWEAP2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); #endif - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer ); - } - else - {//attack still going - //do the trace and damage - trace_t trace; - vec3_t end, mins={-3,-3,-3}, maxs={3,3,3}; - VectorMA( NPCS.NPC->client->renderInfo.muzzlePoint, 1024, NPCS.NPC->client->renderInfo.muzzleDir, end ); - trap->Trace( &trace, NPCS.NPC->client->renderInfo.muzzlePoint, mins, maxs, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//oops, in a wall - if ( NPCS.NPCInfo->coverTarg ) - { - G_SetOrigin( NPCS.NPCInfo->coverTarg, NPCS.NPC->client->renderInfo.muzzlePoint ); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer); + } else { // attack still going + // do the trace and damage + trace_t trace; + vec3_t end, mins = {-3, -3, -3}, maxs = {3, 3, 3}; + VectorMA(NPCS.NPC->client->renderInfo.muzzlePoint, 1024, NPCS.NPC->client->renderInfo.muzzleDir, end); + trap->Trace(&trace, NPCS.NPC->client->renderInfo.muzzlePoint, mins, maxs, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + if (trace.allsolid || trace.startsolid) { // oops, in a wall + if (NPCS.NPCInfo->coverTarg) { + G_SetOrigin(NPCS.NPCInfo->coverTarg, NPCS.NPC->client->renderInfo.muzzlePoint); } - } - else - {//clear - if ( trace.fraction < 1.0f ) - {//hit something + } else { // clear + if (trace.fraction < 1.0f) { // hit something gentity_t *traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && traceEnt->takedamage ) - {//damage it - G_SoundAtLoc( trace.endpos, CHAN_AUTO, G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ) ); - G_Damage( traceEnt, NPCS.NPC, NPCS.NPC, NPCS.NPC->client->renderInfo.muzzleDir, trace.endpos, 10, 0, MOD_UNKNOWN ); + if (traceEnt && traceEnt->takedamage) { // damage it + G_SoundAtLoc(trace.endpos, CHAN_AUTO, G_SoundIndex("sound/weapons/galak/laserdamage.wav")); + G_Damage(traceEnt, NPCS.NPC, NPCS.NPC, NPCS.NPC->client->renderInfo.muzzleDir, trace.endpos, 10, 0, MOD_UNKNOWN); } } - if ( NPCS.NPCInfo->coverTarg ) - { - G_SetOrigin( NPCS.NPCInfo->coverTarg, trace.endpos ); + if (NPCS.NPCInfo->coverTarg) { + G_SetOrigin(NPCS.NPCInfo->coverTarg, trace.endpos); } - if ( !Q_irand( 0, 5 ) ) - { - G_SoundAtLoc( trace.endpos, CHAN_AUTO, G_SoundIndex( "sound/weapons/galak/laserdamage.wav" ) ); + if (!Q_irand(0, 5)) { + G_SoundAtLoc(trace.endpos, CHAN_AUTO, G_SoundIndex("sound/weapons/galak/laserdamage.wav")); } } } } - } - else - {//Okay, we're not in a special attack, see if we should switch weapons or start a special attack + } else { // Okay, we're not in a special attack, see if we should switch weapons or start a special attack /* if ( NPC->s.weapon == WP_REPEATER && !(NPCInfo->scriptFlags & SCF_ALT_FIRE)//using rapid-fire @@ -846,15 +736,13 @@ void NPC_BSGM_Attack( void ) } } else*/ - if (// !NPC->client->ps.powerups[PW_GALAK_SHIELD] - 1 //rwwFIXMEFIXME: just act like the shield is down til the effects and stuff are done - && enemyDist4 < MELEE_DIST_SQUARED - && InFront( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f ) - && NPCS.NPC->enemy->localAnimIndex <= 1 )//within 80 and in front - {//our shield is down, and enemy within 80, if very close, use melee attack to slap away - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - //animate me + if ( // !NPC->client->ps.powerups[PW_GALAK_SHIELD] + 1 // rwwFIXMEFIXME: just act like the shield is down til the effects and stuff are done + && enemyDist4 < MELEE_DIST_SQUARED && InFront(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f) && + NPCS.NPC->enemy->localAnimIndex <= 1) // within 80 and in front + { // our shield is down, and enemy within 80, if very close, use melee attack to slap away + if (TIMER_Done(NPCS.NPC, "attackDelay")) { + // animate me int swingAnim = BOTH_ATTACK1; #if 0 if ( NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH ) @@ -866,107 +754,82 @@ void NPC_BSGM_Attack( void ) swingAnim = BOTH_ATTACK5;//uppercut } #endif - //FIXME: swing sound - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, swingAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer + Q_irand( 1000, 3000 ) ); - //delay the hurt until the proper point in the anim - TIMER_Set( NPCS.NPC, "smackTime", 600 ); + // FIXME: swing sound + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, swingAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer + Q_irand(1000, 3000)); + // delay the hurt until the proper point in the anim + TIMER_Set(NPCS.NPC, "smackTime", 600); NPCS.NPCInfo->blockedDebounceTime = 0; - //FIXME: say something? + // FIXME: say something? } - } - else if ( !NPCS.NPC->lockCount && NPCS.NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH - && TIMER_Done( NPCS.NPC, "attackDelay" ) - && InFront( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f ) - && ((!Q_irand( 0, 10*(2-g_npcspskill.integer))&& enemyDist4 > MIN_LOB_DIST_SQUARED&& enemyDist4 < MAX_LOB_DIST_SQUARED) - ||(!TIMER_Done( NPCS.NPC, "noLob" )&&!TIMER_Done( NPCS.NPC, "noRapid" ))) - && NPCS.NPC->enemy->s.weapon != WP_TURRET ) - {//sometimes use the laser beam attack, but only after he's taken down our generator + } else if (!NPCS.NPC->lockCount && NPCS.NPC->locationDamage[HL_GENERIC1] > GENERATOR_HEALTH && TIMER_Done(NPCS.NPC, "attackDelay") && + InFront(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.3f) && + ((!Q_irand(0, 10 * (2 - g_npcspskill.integer)) && enemyDist4 > MIN_LOB_DIST_SQUARED && enemyDist4 < MAX_LOB_DIST_SQUARED) || + (!TIMER_Done(NPCS.NPC, "noLob") && !TIMER_Done(NPCS.NPC, "noRapid"))) && + NPCS.NPC->enemy->s.weapon != WP_TURRET) { // sometimes use the laser beam attack, but only after he's taken down our generator shoot4 = qfalse; NPC_GM_StartLaser(); - } - else if ( enemyDist4 < MIN_LOB_DIST_SQUARED - && (NPCS.NPC->enemy->s.weapon != WP_TURRET || Q_stricmp( "PAS", NPCS.NPC->enemy->classname )) - && TIMER_Done( NPCS.NPC, "noRapid" ) )//256 - {//enemy within 256 - if ( (NPCS.NPC->client->ps.weapon == WP_REPEATER) && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + } else if (enemyDist4 < MIN_LOB_DIST_SQUARED && (NPCS.NPC->enemy->s.weapon != WP_TURRET || Q_stricmp("PAS", NPCS.NPC->enemy->classname)) && + TIMER_Done(NPCS.NPC, "noRapid")) // 256 + { // enemy within 256 + if ((NPCS.NPC->client->ps.weapon == WP_REPEATER) && + (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; NPCS.NPC->alt_fire = qfalse; - //FIXME: use weap raise & lower anims - NPC_ChangeWeapon( WP_REPEATER ); + // FIXME: use weap raise & lower anims + NPC_ChangeWeapon(WP_REPEATER); } - } - else if ( (enemyDist4 > MAX_LOB_DIST_SQUARED || (NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPCS.NPC->enemy->classname ))) - && TIMER_Done( NPCS.NPC, "noLob" ) )//448 - {//enemy more than 448 away and we are ready to try lob fire again - if ( (NPCS.NPC->client->ps.weapon == WP_REPEATER) && !(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//enemy far enough away to use lobby explosives + } else if ((enemyDist4 > MAX_LOB_DIST_SQUARED || (NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPCS.NPC->enemy->classname))) && + TIMER_Done(NPCS.NPC, "noLob")) // 448 + { // enemy more than 448 away and we are ready to try lob fire again + if ((NPCS.NPC->client->ps.weapon == WP_REPEATER) && !(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // enemy far enough away to use lobby explosives NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; NPCS.NPC->alt_fire = qtrue; - //FIXME: use weap raise & lower anims - NPC_ChangeWeapon( WP_REPEATER ); + // FIXME: use weap raise & lower anims + NPC_ChangeWeapon(WP_REPEATER); } } } - //can we see our target? - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { - NPCS.NPCInfo->enemyLastSeenTime = level.time;//used here for aim debouncing, not always a clear LOS + // can we see our target? + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { + NPCS.NPCInfo->enemyLastSeenTime = level.time; // used here for aim debouncing, not always a clear LOS enemyLOS4 = qtrue; - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - { - enemyCS4 = qfalse;//not true, but should stop us from firing - NPC_AimAdjust( -1 );//adjust aim worse longer we have no weapon - } - else - {//can we shoot our target? - if ( ((NPCS.NPC->client->ps.weapon == WP_REPEATER && (NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist4 < MIN_LOB_DIST_SQUARED )//256 - { - enemyCS4 = qfalse;//not true, but should stop us from firing - hitAlly4 = qtrue;//us! - //FIXME: if too close, run away! - } - else + if (NPCS.NPC->client->ps.weapon == WP_NONE) { + enemyCS4 = qfalse; // not true, but should stop us from firing + NPC_AimAdjust(-1); // adjust aim worse longer we have no weapon + } else { // can we shoot our target? + if (((NPCS.NPC->client->ps.weapon == WP_REPEATER && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE))) && enemyDist4 < MIN_LOB_DIST_SQUARED) // 256 { - int hit = NPC_ShotEntity( NPCS.NPC->enemy, impactPos4 ); + enemyCS4 = qfalse; // not true, but should stop us from firing + hitAlly4 = qtrue; // us! + // FIXME: if too close, run away! + } else { + int hit = NPC_ShotEntity(NPCS.NPC->enemy, impactPos4); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other breakable, so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other breakable, so shoot anyway enemyCS4 = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + NPC_AimAdjust(1); // adjust aim better longer we can see enemy + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly4 = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } } } - } - else if ( trap->InPVS( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - { + } else if (trap->InPVS(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { int hit; gentity_t *hitEnt; - if ( TIMER_Done( NPCS.NPC, "talkDebounce" ) && !Q_irand( 0, 10 ) ) - { - if ( NPCS.NPCInfo->enemyCheckDebounceTime < 8 ) - { + if (TIMER_Done(NPCS.NPC, "talkDebounce") && !Q_irand(0, 10)) { + if (NPCS.NPCInfo->enemyCheckDebounceTime < 8) { int speech = -1; - switch( NPCS.NPCInfo->enemyCheckDebounceTime ) - { + switch (NPCS.NPCInfo->enemyCheckDebounceTime) { case 0: case 1: case 2: @@ -975,143 +838,115 @@ void NPC_BSGM_Attack( void ) case 3: case 4: case 5: - speech = EV_COVER1 + NPCS.NPCInfo->enemyCheckDebounceTime-3; + speech = EV_COVER1 + NPCS.NPCInfo->enemyCheckDebounceTime - 3; break; case 6: case 7: - speech = EV_ESCAPING1 + NPCS.NPCInfo->enemyCheckDebounceTime-6; + speech = EV_ESCAPING1 + NPCS.NPCInfo->enemyCheckDebounceTime - 6; break; } NPCS.NPCInfo->enemyCheckDebounceTime++; - if ( speech != -1 ) - { - G_AddVoiceEvent( NPCS.NPC, speech, Q_irand( 3000, 5000 ) ); - TIMER_Set( NPCS.NPC, "talkDebounce", Q_irand( 5000, 7000 ) ); + if (speech != -1) { + G_AddVoiceEvent(NPCS.NPC, speech, Q_irand(3000, 5000)); + TIMER_Set(NPCS.NPC, "talkDebounce", Q_irand(5000, 7000)); } } } NPCS.NPCInfo->enemyLastSeenTime = level.time; - hit = NPC_ShotEntity( NPCS.NPC->enemy, impactPos4 ); + hit = NPC_ShotEntity(NPCS.NPC->enemy, impactPos4); hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other breakable, so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other breakable, so shoot anyway enemyCS4 = qtrue; - } - else - { + } else { faceEnemy4 = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } } - if ( enemyLOS4 ) - { + if (enemyLOS4) { faceEnemy4 = qtrue; - } - else - { - if ( !NPCS.NPCInfo->goalEntity ) - { + } else { + if (!NPCS.NPCInfo->goalEntity) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//for now, always chase the enemy + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // for now, always chase the enemy move4 = qtrue; } } - if ( enemyCS4 ) - { + if (enemyCS4) { shoot4 = qtrue; - //NPCInfo->enemyCheckDebounceTime = level.time;//actually used here as a last actual LOS - } - else - { - if ( !NPCS.NPCInfo->goalEntity ) - { + // NPCInfo->enemyCheckDebounceTime = level.time;//actually used here as a last actual LOS + } else { + if (!NPCS.NPCInfo->goalEntity) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//for now, always chase the enemy + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // for now, always chase the enemy move4 = qtrue; } } - //Check for movement to take care of + // Check for movement to take care of GM_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations GM_CheckFireState(); - if ( NPCS.NPC->client->ps.weapon == WP_REPEATER && (NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE) && shoot4 && TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - vec3_t muzzle; - vec3_t angles; - vec3_t target; - vec3_t velocity = {0,0,0}; - vec3_t mins = {-REPEATER_ALT_SIZE,-REPEATER_ALT_SIZE,-REPEATER_ALT_SIZE}, maxs = {REPEATER_ALT_SIZE,REPEATER_ALT_SIZE,REPEATER_ALT_SIZE}; + if (NPCS.NPC->client->ps.weapon == WP_REPEATER && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) && shoot4 && TIMER_Done(NPCS.NPC, "attackDelay")) { + vec3_t muzzle; + vec3_t angles; + vec3_t target; + vec3_t velocity = {0, 0, 0}; + vec3_t mins = {-REPEATER_ALT_SIZE, -REPEATER_ALT_SIZE, -REPEATER_ALT_SIZE}, maxs = {REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE}; qboolean clearshot; - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, target ); + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, target); - target[0] += flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCS.NPCInfo->currentAim)*2); - target[1] += flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCS.NPCInfo->currentAim)*2); - target[2] += flrand( -5, 5 )+(Q_flrand(-1.0f, 1.0f)*(6-NPCS.NPCInfo->currentAim)*2); + target[0] += flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCS.NPCInfo->currentAim) * 2); + target[1] += flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCS.NPCInfo->currentAim) * 2); + target[2] += flrand(-5, 5) + (Q_flrand(-1.0f, 1.0f) * (6 - NPCS.NPCInfo->currentAim) * 2); - //Find the desired angles - clearshot = WP_LobFire( NPCS.NPC, muzzle, target, mins, maxs, MASK_SHOT|CONTENTS_LIGHTSABER, - velocity, qtrue, NPCS.NPC->s.number, NPCS.NPC->enemy->s.number, - 300, 1100, 1500, qtrue ); - if ( VectorCompare( vec3_origin, velocity ) || (!clearshot&&enemyLOS4&&enemyCS4) ) - {//no clear lob shot and no lob shot that will hit something breakable - if ( enemyLOS4 && enemyCS4 && TIMER_Done( NPCS.NPC, "noRapid" ) ) - {//have a clear straight shot, so switch to primary + // Find the desired angles + clearshot = WP_LobFire(NPCS.NPC, muzzle, target, mins, maxs, MASK_SHOT | CONTENTS_LIGHTSABER, velocity, qtrue, NPCS.NPC->s.number, + NPCS.NPC->enemy->s.number, 300, 1100, 1500, qtrue); + if (VectorCompare(vec3_origin, velocity) || + (!clearshot && enemyLOS4 && enemyCS4)) { // no clear lob shot and no lob shot that will hit something breakable + if (enemyLOS4 && enemyCS4 && TIMER_Done(NPCS.NPC, "noRapid")) { // have a clear straight shot, so switch to primary NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; NPCS.NPC->alt_fire = qfalse; - NPC_ChangeWeapon( WP_REPEATER ); - //keep this weap for a bit - TIMER_Set( NPCS.NPC, "noLob", Q_irand( 500, 1000 ) ); - } - else - { + NPC_ChangeWeapon(WP_REPEATER); + // keep this weap for a bit + TIMER_Set(NPCS.NPC, "noLob", Q_irand(500, 1000)); + } else { shoot4 = qfalse; } - } - else - { - vectoangles( velocity, angles ); + } else { + vectoangles(velocity, angles); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCS.NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCS.NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); - VectorCopy( velocity, NPCS.NPC->client->hiddenDir ); - NPCS.NPC->client->hiddenDist = VectorNormalize ( NPCS.NPC->client->hiddenDir ); + VectorCopy(velocity, NPCS.NPC->client->hiddenDir); + NPCS.NPC->client->hiddenDist = VectorNormalize(NPCS.NPC->client->hiddenDir); } - } - else if ( faceEnemy4 ) - {//face the enemy - NPC_FaceEnemy( qtrue ); + } else if (faceEnemy4) { // face the enemy + NPC_FaceEnemy(qtrue); } - if ( !TIMER_Done( NPCS.NPC, "standTime" ) ) - { + if (!TIMER_Done(NPCS.NPC, "standTime")) { move4 = qfalse; } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not supposed to chase my enemies - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//goal is my entity, so don't move + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not supposed to chase my enemies + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // goal is my entity, so don't move move4 = qfalse; } } - if ( move4 && !NPCS.NPC->lockCount ) - {//move toward goal + if (move4 && !NPCS.NPC->lockCount) { // move toward goal if ( NPCS.NPCInfo->goalEntity /*&& NPC->client->ps.legsAnim != BOTH_ALERT1 && NPC->client->ps.legsAnim != BOTH_ATTACK2 @@ -1120,179 +955,149 @@ void NPC_BSGM_Attack( void ) && NPC->client->ps.legsAnim != BOTH_ATTACK7*/ ) { move4 = GM_Move(); - } - else - { + } else { move4 = qfalse; } } - if ( !TIMER_Done( NPCS.NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPCS.NPC, "flee")) { // running away faceEnemy4 = qfalse; } - //FIXME: check scf_face_move_dir here? + // FIXME: check scf_face_move_dir here? - if ( !faceEnemy4 ) - {//we want to face in the dir we're running - if ( !move4 ) - {//if we haven't moved, we should look in the direction we last looked? - VectorCopy( NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->lastPathAngles ); + if (!faceEnemy4) { // we want to face in the dir we're running + if (!move4) { // if we haven't moved, we should look in the direction we last looked? + VectorCopy(NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->lastPathAngles); } - if ( move4 ) - {//don't run away and shoot + if (move4) { // don't run away and shoot NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lastPathAngles[YAW]; NPCS.NPCInfo->desiredPitch = 0; shoot4 = qfalse; } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot4 = qfalse; } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->enemy ) - { - if ( NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPCS.NPC->enemy && NPCS.NPC->enemy->enemy) { + if (NPCS.NPC->enemy->s.weapon == WP_SABER && + NPCS.NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing + // rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot4 = qfalse; } } - //FIXME: don't shoot right away! - if ( shoot4 ) - {//try to shoot if it's time - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - if( !(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: don't shoot right away! + if (shoot4) { // try to shoot if it's time + if (TIMER_Done(NPCS.NPC, "attackDelay")) { + if (!(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } } } - //also: - if ( NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPCS.NPC->enemy->classname ) ) - {//crush turrets - if ( G_BoundsOverlap( NPCS.NPC->r.absmin, NPCS.NPC->r.absmax, NPCS.NPC->enemy->r.absmin, NPCS.NPC->enemy->r.absmax ) ) - {//have to do this test because placed turrets are not solid to NPCs (so they don't obstruct navigation) - //if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) - if (0) - { - #ifdef BASE_COMPAT - NPCS.NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; - #endif - G_Damage( NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, NULL, NPCS.NPC->r.currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN ); - } - else - { - G_Damage( NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, NULL, NPCS.NPC->r.currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_CRUSH ); + // also: + if (NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPCS.NPC->enemy->classname)) { // crush turrets + if (G_BoundsOverlap( + NPCS.NPC->r.absmin, NPCS.NPC->r.absmax, NPCS.NPC->enemy->r.absmin, + NPCS.NPC->enemy->r.absmax)) { // have to do this test because placed turrets are not solid to NPCs (so they don't obstruct navigation) + // if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) + if (0) { +#ifdef BASE_COMPAT + NPCS.NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; +#endif + G_Damage(NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, NULL, NPCS.NPC->r.currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN); + } else { + G_Damage(NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, NULL, NPCS.NPC->r.currentOrigin, 100, DAMAGE_NO_KNOCKBACK, MOD_CRUSH); } } - } - else if ( NPCS.NPCInfo->touchedByPlayer != NULL && NPCS.NPCInfo->touchedByPlayer == NPCS.NPC->enemy ) - {//touched enemy - //if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) - if (0) - {//zap him! - vec3_t smackDir; - - //animate me + } else if (NPCS.NPCInfo->touchedByPlayer != NULL && NPCS.NPCInfo->touchedByPlayer == NPCS.NPC->enemy) { // touched enemy + // if ( NPC->client->ps.powerups[PW_GALAK_SHIELD] > 0 ) + if (0) { // zap him! + vec3_t smackDir; + + // animate me #if 0 NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK6, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); #endif - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer ); - TIMER_Set( NPCS.NPC, "standTime", NPCS.NPC->client->ps.legsTimer ); - //FIXME: debounce this? + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.torsoTimer); + TIMER_Set(NPCS.NPC, "standTime", NPCS.NPC->client->ps.legsTimer); + // FIXME: debounce this? NPCS.NPCInfo->touchedByPlayer = NULL; - //FIXME: some shield effect? - #ifdef BASE_COMPAT - NPCS.NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; - #endif +// FIXME: some shield effect? +#ifdef BASE_COMPAT + NPCS.NPC->client->ps.powerups[PW_BATTLESUIT] = level.time + ARMOR_EFFECT_TIME; +#endif - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, smackDir ); + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, smackDir); smackDir[2] += 30; - VectorNormalize( smackDir ); - G_Damage( NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, smackDir, NPCS.NPC->r.currentOrigin, (g_npcspskill.integer+1)*Q_irand( 5, 10), DAMAGE_NO_KNOCKBACK, MOD_UNKNOWN ); - //throw them - G_Throw( NPCS.NPC->enemy, smackDir, 100 ); - //NPC->enemy->s.powerups |= ( 1 << PW_SHOCKED ); - if ( NPCS.NPC->enemy->client ) - { - // NPC->enemy->client->ps.powerups[PW_SHOCKED] = level.time + 1000; + VectorNormalize(smackDir); + G_Damage(NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, smackDir, NPCS.NPC->r.currentOrigin, (g_npcspskill.integer + 1) * Q_irand(5, 10), DAMAGE_NO_KNOCKBACK, + MOD_UNKNOWN); + // throw them + G_Throw(NPCS.NPC->enemy, smackDir, 100); + // NPC->enemy->s.powerups |= ( 1 << PW_SHOCKED ); + if (NPCS.NPC->enemy->client) { + // NPC->enemy->client->ps.powerups[PW_SHOCKED] = level.time + 1000; NPCS.NPC->enemy->client->ps.electrifyTime = level.time + 1000; } - //stop any attacks + // stop any attacks NPCS.ucmd.buttons = 0; } } - if ( NPCS.NPCInfo->movementSpeech < 3 && NPCS.NPCInfo->blockedSpeechDebounceTime <= level.time ) - { - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0 && NPCS.NPC->enemy->painDebounceTime > level.time ) - { - if ( NPCS.NPC->enemy->health < 50 && NPCS.NPCInfo->movementSpeech == 2 ) - { - G_AddVoiceEvent( NPCS.NPC, EV_ANGER2, Q_irand( 2000, 4000 ) ); + if (NPCS.NPCInfo->movementSpeech < 3 && NPCS.NPCInfo->blockedSpeechDebounceTime <= level.time) { + if (NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0 && NPCS.NPC->enemy->painDebounceTime > level.time) { + if (NPCS.NPC->enemy->health < 50 && NPCS.NPCInfo->movementSpeech == 2) { + G_AddVoiceEvent(NPCS.NPC, EV_ANGER2, Q_irand(2000, 4000)); NPCS.NPCInfo->movementSpeech = 3; - } - else if ( NPCS.NPC->enemy->health < 75 && NPCS.NPCInfo->movementSpeech == 1 ) - { - G_AddVoiceEvent( NPCS.NPC, EV_ANGER1, Q_irand( 2000, 4000 ) ); + } else if (NPCS.NPC->enemy->health < 75 && NPCS.NPCInfo->movementSpeech == 1) { + G_AddVoiceEvent(NPCS.NPC, EV_ANGER1, Q_irand(2000, 4000)); NPCS.NPCInfo->movementSpeech = 2; - } - else if ( NPCS.NPC->enemy->health < 100 && NPCS.NPCInfo->movementSpeech == 0 ) - { - G_AddVoiceEvent( NPCS.NPC, EV_ANGER3, Q_irand( 2000, 4000 ) ); + } else if (NPCS.NPC->enemy->health < 100 && NPCS.NPCInfo->movementSpeech == 0) { + G_AddVoiceEvent(NPCS.NPC, EV_ANGER3, Q_irand(2000, 4000)); NPCS.NPCInfo->movementSpeech = 1; } } } } -void NPC_BSGM_Default( void ) -{ - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSGM_Default(void) { + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( NPCS.NPC->client->ps.stats[STAT_ARMOR] <= 0 ) - {//armor gone - // if ( !NPCInfo->investigateDebounceTime ) - if (0) - {//start regenerating the armor - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_shield", TURN_OFF ); - NPCS.NPC->flags &= ~FL_SHIELDED;//no more reflections - VectorSet( NPCS.NPC->r.mins, -20, -20, -24 ); - VectorSet( NPCS.NPC->r.maxs, 20, 20, 64 ); + if (NPCS.NPC->client->ps.stats[STAT_ARMOR] <= 0) { // armor gone + // if ( !NPCInfo->investigateDebounceTime ) + if (0) { // start regenerating the armor + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_shield", TURN_OFF); + NPCS.NPC->flags &= ~FL_SHIELDED; // no more reflections + VectorSet(NPCS.NPC->r.mins, -20, -20, -24); + VectorSet(NPCS.NPC->r.maxs, 20, 20, 64); NPCS.NPC->client->ps.crouchheight = NPCS.NPC->client->ps.standheight = 64; - if ( NPCS.NPC->locationDamage[HL_GENERIC1] < GENERATOR_HEALTH ) - {//still have the generator bolt-on - if ( NPCS.NPCInfo->investigateCount < 12 ) - { + if (NPCS.NPC->locationDamage[HL_GENERIC1] < GENERATOR_HEALTH) { // still have the generator bolt-on + if (NPCS.NPCInfo->investigateCount < 12) { NPCS.NPCInfo->investigateCount++; } NPCS.NPCInfo->investigateDebounceTime = level.time + (NPCS.NPCInfo->investigateCount * 5000); } - } - else if ( NPCS.NPCInfo->investigateDebounceTime < level.time ) - {//armor regenerated, turn shield back on - //do a trace and make sure we can turn this back on? - trace_t tr; - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, shieldMins, shieldMaxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( !tr.startsolid ) - { - VectorCopy( shieldMins, NPCS.NPC->r.mins ); - VectorCopy( shieldMaxs, NPCS.NPC->r.maxs ); + } else if (NPCS.NPCInfo->investigateDebounceTime < level.time) { // armor regenerated, turn shield back on + // do a trace and make sure we can turn this back on? + trace_t tr; + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, shieldMins, shieldMaxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, + 0); + if (!tr.startsolid) { + VectorCopy(shieldMins, NPCS.NPC->r.mins); + VectorCopy(shieldMaxs, NPCS.NPC->r.maxs); NPCS.NPC->client->ps.crouchheight = NPCS.NPC->client->ps.standheight = shieldMaxs[2]; NPCS.NPC->client->ps.stats[STAT_ARMOR] = GALAK_SHIELD_HEALTH; NPCS.NPCInfo->investigateDebounceTime = 0; - NPCS.NPC->flags |= FL_SHIELDED;//reflect normal shots - // NPC->fx_time = level.time; - NPC_SetSurfaceOnOff( NPCS.NPC, "torso_shield", TURN_ON ); + NPCS.NPC->flags |= FL_SHIELDED; // reflect normal shots + // NPC->fx_time = level.time; + NPC_SetSurfaceOnOff(NPCS.NPC, "torso_shield", TURN_ON); } } } @@ -1307,15 +1112,13 @@ void NPC_BSGM_Default( void ) NPC_SetSurfaceOnOff( NPC, "torso_shield", TURN_OFF ); } */ - //rwwFIXMEFIXME: Allow this stuff, and again, going to have to let the client know about it. - //Maybe a surface-off bitflag of some sort in the entity state? + // rwwFIXMEFIXME: Allow this stuff, and again, going to have to let the client know about it. + // Maybe a surface-off bitflag of some sort in the entity state? - if( !NPCS.NPC->enemy ) - {//don't have an enemy, look for one + if (!NPCS.NPC->enemy) { // don't have an enemy, look for one NPC_BSGM_Patrol(); - } - else //if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSGM_Attack(); } } diff --git a/codemp/game/NPC_AI_Grenadier.c b/codemp/game/NPC_AI_Grenadier.c index 549314b3d5..0326532ae4 100644 --- a/codemp/game/NPC_AI_Grenadier.c +++ b/codemp/game/NPC_AI_Grenadier.c @@ -24,100 +24,93 @@ along with this program; if not, see . #include "g_nav.h" #include "anims.h" -extern qboolean BG_SabersOff( playerState_t *ps ); +extern qboolean BG_SabersOff(playerState_t *ps); -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS3; static qboolean enemyCS3; static qboolean faceEnemy3; static qboolean move3; static qboolean shoot3; -static float enemyDist3; +static float enemyDist3; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Grenadier_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); +void Grenadier_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); } -void NPC_Grenadier_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Grenadier_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Grenadier_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Grenadier_Pain(gentity_t *self, gentity_t *attacker, int damage) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -127,9 +120,8 @@ ST_HoldPosition ------------------------- */ -static void Grenadier_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qtrue ); +static void Grenadier_HoldPosition(void) { + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qtrue); NPCS.NPCInfo->goalEntity = NULL; /*if ( TIMER_Done( NPC, "stand" ) ) @@ -145,55 +137,49 @@ ST_Move ------------------------- */ -static qboolean Grenadier_Move( void ) -{ - qboolean moved; - navInfo_t info; +static qboolean Grenadier_Move(void) { + qboolean moved; + navInfo_t info; - NPCS.NPCInfo->combatMove = qtrue;//always move straight toward our goal - moved = NPC_MoveToGoal( qtrue ); + NPCS.NPCInfo->combatMove = qtrue; // always move straight toward our goal + moved = NPC_MoveToGoal(qtrue); - //Get the move info - NAV_GetLastMove( &info ); + // Get the move info + NAV_GetLastMove(&info); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPCS.NPC->enemy ) - { + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPCS.NPC->enemy) { Grenadier_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPCS.NPC->client->ps.weapon == WP_THERMAL && NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); + // If our move failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPCS.NPC->client->ps.weapon == WP_THERMAL && NPCS.NPCInfo->goalEntity && + NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); int cp; - if ( NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1 ); - if ( cp == -1 && !(NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32, -1 ); + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1); + if (cp == -1 && !(NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, + CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32, -1); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL); return moved; } } - //just hang here + // just hang here Grenadier_HoldPosition(); } @@ -206,77 +192,61 @@ NPC_BSGrenadier_Patrol ------------------------- */ -void NPC_BSGrenadier_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Patrol(void) { // FIXME: pick up on bodies of dead buddies? + if (NPCS.NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be automatic now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID ) - { + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID) { NPCS.NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPCS.NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPCS.NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[alertEvent].position, NPCS.NPCInfo->investigateGoal ); - NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCS.NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[alertEvent].position, NPCS.NPCInfo->investigateGoal); + NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCS.NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCS.NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCS.NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCS.NPCInfo->investigateGoal, NPCS.NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCS.NPCInfo->investigateGoal, NPCS.NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCS.NPCInfo->desiredYaw; o_pitch = NPCS.NPCInfo->desiredPitch; NPCS.NPCInfo->desiredYaw = angles[YAW]; NPCS.NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCS.NPCInfo->desiredYaw = o_yaw; NPCS.NPCInfo->desiredPitch = o_pitch; @@ -285,14 +255,13 @@ void NPC_BSGrenadier_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -323,26 +292,20 @@ ST_CheckMoveState ------------------------- */ -static void Grenadier_CheckMoveState( void ) -{ - //See if we're a scout - if ( !(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//behaviorState == BS_STAND_AND_SHOOT ) +static void Grenadier_CheckMoveState(void) { + // See if we're a scout + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - { + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { move3 = qfalse; return; } } - //See if we're running away - else if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPCS.NPC, "flee" ) ) - { + // See if we're running away + else if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPCS.NPC, "flee")) { NPCS.NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy3 = qfalse; } } @@ -358,52 +321,47 @@ static void Grenadier_CheckMoveState( void ) } */ - //See if we're moving towards a goal, not the enemy - if ( ( NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy ) && ( NPCS.NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, FlyingCreature( NPCS.NPC ) ) || - ( NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS3 && enemyDist3 <= 10000 ) ) - { - // int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCS.NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - TIMER_Set( NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100 ); - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 3000, 7000 ) ); - // newSquadState = SQUAD_COVER; + // See if we're moving towards a goal, not the enemy + if ((NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy) && (NPCS.NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, + FlyingCreature(NPCS.NPC)) || + (NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS3 && enemyDist3 <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCS.NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + TIMER_Set(NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100); + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPCS.NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPCS.NPC, "flee", -level.time); NPCS.NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(4000, 8000)); } - if ( !NPCS.NPCInfo->goalEntity ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { + if (!NPCS.NPCInfo->goalEntity) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } } @@ -415,24 +373,21 @@ ST_CheckFireState ------------------------- */ -static void Grenadier_CheckFireState( void ) -{ - if ( enemyCS3 ) - {//if have a clear shot, always try +static void Grenadier_CheckFireState(void) { + if (enemyCS3) { // if have a clear shot, always try return; } - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || NPCS.NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || + NPCS.NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPCS.NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPCS.NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //continue to fire on their last position + // continue to fire on their last position /* if ( !Q_irand( 0, 1 ) && NPCInfo->enemyLastSeenTime && level.time - NPCInfo->enemyLastSeenTime < 4000 ) { @@ -457,15 +412,13 @@ static void Grenadier_CheckFireState( void ) */ } -qboolean Grenadier_EvaluateShot( int hit ) -{ - if ( !NPCS.NPC->enemy ) - { +qboolean Grenadier_EvaluateShot(int hit) { + if (!NPCS.NPC->enemy) { return qfalse; } - if ( hit == NPCS.NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].r.svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].r.svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -477,33 +430,29 @@ NPC_BSGrenadier_Attack ------------------------- */ -void NPC_BSGrenadier_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPCS.NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSGrenadier_Attack(void) { + // Don't do anything if we're hurt + if (NPCS.NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt(qfalse) == qfalse) //! NPC->enemy )// { NPCS.NPC->enemy = NULL; - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPCS.NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPCS.NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPCS.NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSGrenadier_Patrol();//FIXME: or patrol? + if (!NPCS.NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSGrenadier_Patrol(); // FIXME: or patrol? return; } @@ -511,82 +460,67 @@ void NPC_BSGrenadier_Attack( void ) move3 = qtrue; faceEnemy3 = qfalse; shoot3 = qfalse; - enemyDist3 = DistanceSquared( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ); - - //See if we should switch to melee attack - if ( enemyDist3 < 16384 //128 - && (!NPCS.NPC->enemy->client - || NPCS.NPC->enemy->client->ps.weapon != WP_SABER - || BG_SabersOff( &NPCS.NPC->enemy->client->ps ) - ) - ) - {//enemy is close and not using saber - if ( NPCS.NPC->client->ps.weapon == WP_THERMAL ) - {//grenadier - trace_t trace; - trap->Trace ( &trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.mins, NPCS.NPC->enemy->r.maxs, NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->s.number, NPCS.NPC->enemy->clipmask, qfalse, 0, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPCS.NPC->enemy->s.number ) ) - {//I can get right to him - //reset fire-timing variables - NPC_ChangeWeapon( WP_STUN_BATON ); - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) - {//FIXME: should we be overriding scriptFlags? - NPCS.NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES;//NPCInfo->behaviorState = BS_HUNT_AND_KILL; + enemyDist3 = DistanceSquared(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin); + + // See if we should switch to melee attack + if (enemyDist3 < 16384 // 128 + && (!NPCS.NPC->enemy->client || NPCS.NPC->enemy->client->ps.weapon != WP_SABER || + BG_SabersOff(&NPCS.NPC->enemy->client->ps))) { // enemy is close and not using saber + if (NPCS.NPC->client->ps.weapon == WP_THERMAL) { // grenadier + trace_t trace; + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.mins, NPCS.NPC->enemy->r.maxs, NPCS.NPC->enemy->r.currentOrigin, + NPCS.NPC->s.number, NPCS.NPC->enemy->clipmask, qfalse, 0, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPCS.NPC->enemy->s.number)) { // I can get right to him + // reset fire-timing variables + NPC_ChangeWeapon(WP_STUN_BATON); + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) + { // FIXME: should we be overriding scriptFlags? + NPCS.NPCInfo->scriptFlags |= SCF_CHASE_ENEMIES; // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } } } - } - else if ( enemyDist3 > 65536 || (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->ps.weapon == WP_SABER && !NPCS.NPC->enemy->client->ps.saberHolstered) )//256 - {//enemy is far or using saber - if ( NPCS.NPC->client->ps.weapon == WP_STUN_BATON && (NPCS.NPC->client->ps.stats[STAT_WEAPONS]&(1< 65536 || + (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->ps.weapon == WP_SABER && !NPCS.NPC->enemy->client->ps.saberHolstered)) // 256 + { // enemy is far or using saber + if (NPCS.NPC->client->ps.weapon == WP_STUN_BATON && + (NPCS.NPC->client->ps.stats[STAT_WEAPONS] & (1 << WP_THERMAL))) { // fisticuffs, make switch to thermal if have it + // reset fire-timing variables + NPC_ChangeWeapon(WP_THERMAL); } } - //can we see our target? - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { + // can we see our target? + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { NPCS.NPCInfo->enemyLastSeenTime = level.time; enemyLOS3 = qtrue; - if ( NPCS.NPC->client->ps.weapon == WP_STUN_BATON ) - { - if ( enemyDist3 <= 4096 && InFOV3( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 90, 45 ) )//within 64 & infront + if (NPCS.NPC->client->ps.weapon == WP_STUN_BATON) { + if (enemyDist3 <= 4096 && + InFOV3(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 90, 45)) // within 64 & infront { - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); enemyCS3 = qtrue; } - } - else if ( InFOV3( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 45, 90 ) ) - {//in front of me - //can we shoot our target? - //FIXME: how accurate/necessary is this check? - int hit = NPC_ShotEntity( NPCS.NPC->enemy, NULL ); + } else if (InFOV3(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 45, 90)) { // in front of me + // can we shoot our target? + // FIXME: how accurate/necessary is this check? + int hit = NPC_ShotEntity(NPCS.NPC->enemy, NULL); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) ) - { + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam)) { float enemyHorzDist; - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); - enemyHorzDist = DistanceHorizontalSquared( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ); - if ( enemyHorzDist < 1048576 ) - {//within 1024 + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); + enemyHorzDist = DistanceHorizontalSquared(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin); + if (enemyHorzDist < 1048576) { // within 1024 enemyCS3 = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - } - else - { - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + } else { + NPC_AimAdjust(1); // adjust aim better longer we can see enemy } } } - } - else - { - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } else { + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } /* else if ( trap->InPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin ) ) @@ -596,103 +530,81 @@ void NPC_BSGrenadier_Attack( void ) } */ - if ( enemyLOS3 ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS3) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy3 = qtrue; } - if ( enemyCS3 ) - { + if (enemyCS3) { shoot3 = qtrue; - if ( NPCS.NPC->client->ps.weapon == WP_THERMAL ) - {//don't chase and throw + if (NPCS.NPC->client->ps.weapon == WP_THERMAL) { // don't chase and throw move3 = qfalse; - } - else if ( NPCS.NPC->client->ps.weapon == WP_STUN_BATON && enemyDist3 < (NPCS.NPC->r.maxs[0]+NPCS.NPC->enemy->r.maxs[0]+16)*(NPCS.NPC->r.maxs[0]+NPCS.NPC->enemy->r.maxs[0]+16) ) - {//close enough + } else if (NPCS.NPC->client->ps.weapon == WP_STUN_BATON && enemyDist3 < (NPCS.NPC->r.maxs[0] + NPCS.NPC->enemy->r.maxs[0] + 16) * + (NPCS.NPC->r.maxs[0] + NPCS.NPC->enemy->r.maxs[0] + 16)) { // close enough move3 = qfalse; } - }//this should make him chase enemy when out of range...? + } // this should make him chase enemy when out of range...? - //Check for movement to take care of + // Check for movement to take care of Grenadier_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Grenadier_CheckFireState(); - if ( move3 ) - {//move toward goal - if ( NPCS.NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist3 > 10000 ) )//100 squared + if (move3) { // move toward goal + if (NPCS.NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist3 > 10000 ) )//100 squared { move3 = Grenadier_Move(); - } - else - { + } else { move3 = qfalse; } } - if ( !move3 ) - { - if ( !TIMER_Done( NPCS.NPC, "duck" ) ) - { + if (!move3) { + if (!TIMER_Done(NPCS.NPC, "duck")) { NPCS.ucmd.upmove = -127; } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPCS.NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPCS.NPC, "duck", -1); } - if ( !faceEnemy3 ) - {//we want to face in the dir we're running - if ( move3 ) - {//don't run away and shoot + if (!faceEnemy3) { // we want to face in the dir we're running + if (move3) { // don't run away and shoot NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lastPathAngles[YAW]; NPCS.NPCInfo->desiredPitch = 0; shoot3 = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy3 ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy3 ) + { // face the enemy NPC_FaceEnemy(qtrue); } - if ( NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot3 = qfalse; } - //FIXME: don't shoot right away! - if ( shoot3 ) - {//try to shoot if it's time - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - if( !(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + // FIXME: don't shoot right away! + if (shoot3) { // try to shoot if it's time + if (TIMER_Done(NPCS.NPC, "attackDelay")) { + if (!(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPCInfo->shotTime-level.time ); + WeaponThink(qtrue); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPCInfo->shotTime - level.time); } - } } } -void NPC_BSGrenadier_Default( void ) -{ - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSGrenadier_Default(void) { + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if( !NPCS.NPC->enemy ) - {//don't have an enemy, look for one + if (!NPCS.NPC->enemy) { // don't have an enemy, look for one NPC_BSGrenadier_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSGrenadier_Attack(); } } diff --git a/codemp/game/NPC_AI_Howler.c b/codemp/game/NPC_AI_Howler.c index 1d0df9d69d..7a0c598b9b 100644 --- a/codemp/game/NPC_AI_Howler.c +++ b/codemp/game/NPC_AI_Howler.c @@ -23,70 +23,58 @@ along with this program; if not, see . #include "b_local.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 /* ------------------------- NPC_Howler_Precache ------------------------- */ -void NPC_Howler_Precache( void ) -{ -} - +void NPC_Howler_Precache(void) {} /* ------------------------- Howler_Idle ------------------------- */ -void Howler_Idle( void ) { -} - +void Howler_Idle(void) {} /* ------------------------- Howler_Patrol ------------------------- */ -void Howler_Patrol( void ) -{ +void Howler_Patrol(void) { vec3_t dif; NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPCS.NPC, "patrolTime" )) - { - TIMER_Set( NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPCS.NPC, "patrolTime")) { + TIMER_Set(NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } - //rwwFIXMEFIXME: Care about all clients, not just client 0 - //OJK: clientnum 0 - VectorSubtract( g_entities[0].r.currentOrigin, NPCS.NPC->r.currentOrigin, dif ); + // rwwFIXMEFIXME: Care about all clients, not just client 0 + // OJK: clientnum 0 + VectorSubtract(g_entities[0].r.currentOrigin, NPCS.NPC->r.currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPCS.NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPCS.NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Howler_Idle(); return; } @@ -97,97 +85,82 @@ void Howler_Patrol( void ) Howler_Move ------------------------- */ -void Howler_Move( qboolean visible ) -{ - if ( NPCS.NPCInfo->localState != LSTATE_WAITING ) - { +void Howler_Move(qboolean visible) { + if (NPCS.NPCInfo->localState != LSTATE_WAITING) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPC_MoveToGoal( qtrue ); - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -void Howler_TryDamage( gentity_t *enemy, int damage ) -{ - vec3_t end, dir; - trace_t tr; +void Howler_TryDamage(gentity_t *enemy, int damage) { + vec3_t end, dir; + trace_t tr; - if ( !enemy ) - { + if (!enemy) { return; } - AngleVectors( NPCS.NPC->client->ps.viewangles, dir, NULL, NULL ); - VectorMA( NPCS.NPC->r.currentOrigin, MIN_DISTANCE, dir, end ); + AngleVectors(NPCS.NPC->client->ps.viewangles, dir, NULL, NULL); + VectorMA(NPCS.NPC->r.currentOrigin, MIN_DISTANCE, dir, end); // Should probably trace from the mouth, but, ah well. - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.entityNum != ENTITYNUM_WORLD ) - { - G_Damage( &g_entities[tr.entityNum], NPCS.NPC, NPCS.NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (tr.entityNum != ENTITYNUM_WORLD) { + G_Damage(&g_entities[tr.entityNum], NPCS.NPC, NPCS.NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); } } //------------------------------ -void Howler_Attack( void ) -{ - if ( !TIMER_Exists( NPCS.NPC, "attacking" )) - { +void Howler_Attack(void) { + if (!TIMER_Exists(NPCS.NPC, "attacking")) { // Going to do ATTACK1 - TIMER_Set( NPCS.NPC, "attacking", 1700 + Q_flrand(0.0f, 1.0f) * 200 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attacking", 1700 + Q_flrand(0.0f, 1.0f) * 200); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPCS.NPC, "attack_dmg", 200 ); // level two damage + TIMER_Set(NPCS.NPC, "attack_dmg", 200); // level two damage } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPCS.NPC, "attack_dmg", qtrue )) - { - Howler_TryDamage( NPCS.NPC->enemy, 5 ); + if (TIMER_Done2(NPCS.NPC, "attack_dmg", qtrue)) { + Howler_TryDamage(NPCS.NPC->enemy, 5); } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPCS.NPC, "attacking", qtrue ); + TIMER_Done2(NPCS.NPC, "attacking", qtrue); } //---------------------------------- -void Howler_Combat( void ) -{ +void Howler_Combat(void) { float distance; qboolean advance; // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS4( NPCS.NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS4(NPCS.NPC->enemy) || UpdateGoal()) { NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - distance = DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - advance = (qboolean)( distance > MIN_DISTANCE_SQR ? qtrue : qfalse ); + distance = DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + advance = (qboolean)(distance > MIN_DISTANCE_SQR ? qtrue : qfalse); - if (( advance || NPCS.NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPCS.NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCS.NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPCS.NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPCS.NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPCS.NPC, "takingPain", qtrue)) { NPCS.NPCInfo->localState = LSTATE_CLEAR; + } else { + Howler_Move(qtrue); } - else - { - Howler_Move( qtrue ); - } - } - else - { + } else { Howler_Attack(); } } @@ -197,38 +170,33 @@ void Howler_Combat( void ) NPC_Howler_Pain ------------------------- */ -void NPC_Howler_Pain( gentity_t *self, gentity_t *attacker, int damage ) -{ - if ( damage >= 10 ) - { - TIMER_Remove( self, "attacking" ); - TIMER_Set( self, "takingPain", 2900 ); +void NPC_Howler_Pain(gentity_t *self, gentity_t *attacker, int damage) { + if (damage >= 10) { + TIMER_Remove(self, "attacking"); + TIMER_Set(self, "takingPain", 2900); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } - /* ------------------------- NPC_BSHowler_Default ------------------------- */ -void NPC_BSHowler_Default( void ) -{ - if ( NPCS.NPC->enemy ) +void NPC_BSHowler_Default(void) { + if (NPCS.NPC->enemy) Howler_Combat(); - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) + else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) Howler_Patrol(); else Howler_Idle(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codemp/game/NPC_AI_ImperialProbe.c b/codemp/game/NPC_AI_ImperialProbe.c index ecfa3a6392..aa73b27f03 100644 --- a/codemp/game/NPC_AI_ImperialProbe.c +++ b/codemp/game/NPC_AI_ImperialProbe.c @@ -23,40 +23,31 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -gitem_t *BG_FindItemForAmmo( ammo_t ammo ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -//Local state enums -enum -{ - LSTATE_NONE = 0, - LSTATE_BACKINGUP, - LSTATE_SPINNING, - LSTATE_PAIN, - LSTATE_DROP -}; - -void ImperialProbe_Idle( void ); - -void NPC_Probe_Precache(void) -{ +gitem_t *BG_FindItemForAmmo(ammo_t ammo); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_BACKINGUP, LSTATE_SPINNING, LSTATE_PAIN, LSTATE_DROP }; + +void ImperialProbe_Idle(void); + +void NPC_Probe_Precache(void) { int i; - for ( i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/probe/misc/probetalk%d", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/probe/misc/probetalk%d", i)); } - G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + G_SoundIndex("sound/chars/probe/misc/probedroidloop"); G_SoundIndex("sound/chars/probe/misc/anger1"); G_SoundIndex("sound/chars/probe/misc/fire"); - G_EffectIndex( "chunks/probehead" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "explosions/probeexplosion1"); - G_EffectIndex( "bryar/muzzle_flash" ); + G_EffectIndex("chunks/probehead"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("explosions/probeexplosion1"); + G_EffectIndex("bryar/muzzle_flash"); - RegisterItem( BG_FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( BG_FindItemForWeapon( WP_BRYAR_PISTOL ) ); + RegisterItem(BG_FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(BG_FindItemForWeapon(WP_BRYAR_PISTOL)); } /* ------------------------- @@ -64,115 +55,102 @@ Hunter_MaintainHeight ------------------------- */ -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f -void ImperialProbe_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void ImperialProbe_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { // Find the height difference dif = NPCS.NPC->enemy->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > 16 ) - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 8) { + if (fabs(dif) > 16) + dif = (dif < 0 ? -16 : 16); - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCS.NPCInfo->goalEntity ) // Is there a goal? + if (NPCS.NPCInfo->goalEntity) // Is there a goal? goal = NPCS.NPCInfo->goalEntity; else goal = NPCS.NPCInfo->lastGoalEntity; - if ( goal ) - { + if (goal) { dif = goal->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; - if ( fabs( dif ) > 24 ) { - NPCS.ucmd.upmove = ( NPCS.ucmd.upmove < 0 ? -4 : 4 ); - } - else { - if ( NPCS.NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + NPCS.ucmd.upmove = (NPCS.ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 2 ) + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 2) NPCS.NPC->client->ps.velocity[2] = 0; } } } // Apply friction - else if ( NPCS.NPC->client->ps.velocity[2] ) - { + else if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabsf( NPCS.NPC->client->ps.velocity[2] ) < 1 ) + if (fabsf(NPCS.NPC->client->ps.velocity[2]) < 1) NPCS.NPC->client->ps.velocity[2] = 0; } // Stay at a given height until we take on an enemy -/* VectorSet( endPos, NPC->r.currentOrigin[0], NPC->r.currentOrigin[1], NPC->r.currentOrigin[2] - 512 ); - trap->Trace( &trace, NPC->r.currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); - - if ( trace.fraction != 1.0f ) - { - float length = ( trace.fraction * 512 ); + /* VectorSet( endPos, NPC->r.currentOrigin[0], NPC->r.currentOrigin[1], NPC->r.currentOrigin[2] - 512 ); + trap->Trace( &trace, NPC->r.currentOrigin, NULL, NULL, endPos, NPC->s.number, MASK_SOLID ); - if ( length < 80 ) - { - ucmd.upmove = 32; - } - else if ( length > 120 ) - { - ucmd.upmove = -32; - } - else - { - if ( NPC->client->ps.velocity[2] ) + if ( trace.fraction != 1.0f ) { - NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + float length = ( trace.fraction * 512 ); - if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + if ( length < 80 ) { - NPC->client->ps.velocity[2] = 0; + ucmd.upmove = 32; } - } - } - } */ + else if ( length > 120 ) + { + ucmd.upmove = -32; + } + else + { + if ( NPC->client->ps.velocity[2] ) + { + NPC->client->ps.velocity[2] *= VELOCITY_DECAY; + + if ( fabs( NPC->client->ps.velocity[2] ) < 1 ) + { + NPC->client->ps.velocity[2] = 0; + } + } + } + } */ } // Apply friction - if ( NPCS.NPC->client->ps.velocity[0] ) - { + if (NPCS.NPC->client->ps.velocity[0]) { NPCS.NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[0]) < 1) { NPCS.NPC->client->ps.velocity[0] = 0; } } - if ( NPCS.NPC->client->ps.velocity[1] ) - { + if (NPCS.NPC->client->ps.velocity[1]) { NPCS.NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[1]) < 1) { NPCS.NPC->client->ps.velocity[1] = 0; } } @@ -184,35 +162,33 @@ ImperialProbe_Strafe ------------------------- */ -#define HUNTER_STRAFE_VEL 256 -#define HUNTER_STRAFE_DIS 200 -#define HUNTER_UPWARD_PUSH 32 +#define HUNTER_STRAFE_VEL 256 +#define HUNTER_STRAFE_DIS 200 +#define HUNTER_UPWARD_PUSH 32 -void ImperialProbe_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void ImperialProbe_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPCS.NPC->r.currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPCS.NPC->r.currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPCS.NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPCS.NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity); // Add a slight upward push NPCS.NPC->client->ps.velocity[2] += HUNTER_UPWARD_PUSH; // Set the strafe start time so we can do a controlled roll - //NPC->fx_time = level.time; + // NPC->fx_time = level.time; NPCS.NPCInfo->standTime = level.time + 3000 + Q_flrand(0.0f, 1.0f) * 500; } } @@ -223,50 +199,44 @@ ImperialProbe_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 5 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 5 -void ImperialProbe_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void ImperialProbe_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - //If we're not supposed to stand still, pursue the player - if ( NPCS.NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCS.NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { ImperialProbe_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_npcspskill.integer; - VectorMA( NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity); } /* @@ -274,62 +244,51 @@ void ImperialProbe_Hunt( qboolean visible, qboolean advance ) ImperialProbe_FireBlaster ------------------------- */ -void ImperialProbe_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; -// static vec3_t muzzle; +void ImperialProbe_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + // static vec3_t muzzle; int genBolt1; - gentity_t *missile; - mdxaBone_t boltMatrix; + gentity_t *missile; + mdxaBone_t boltMatrix; genBolt1 = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash"); - //FIXME: use {0, NPC->client->ps.legsYaw, 0} - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - genBolt1, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + // FIXME: use {0, NPC->client->ps.legsYaw, 0} + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, genBolt1, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, vec3_origin ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle1, vec3_origin); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/probe/misc/fire" )); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/probe/misc/fire")); - if (NPCS.NPC->health) - { - CalcEntitySpot( NPCS.NPC->enemy, SPOT_CHEST, enemy_org1 ); - enemy_org1[0]+= Q_irand(0,10); - enemy_org1[1]+= Q_irand(0,10); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPCS.NPC->r.currentAngles, forward, vright, up); + if (NPCS.NPC->health) { + CalcEntitySpot(NPCS.NPC->enemy, SPOT_CHEST, enemy_org1); + enemy_org1[0] += Q_irand(0, 10); + enemy_org1[1] += Q_irand(0, 10); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPCS.NPC->r.currentAngles, forward, vright, up); } - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; - if ( g_npcspskill.integer <= 1 ) - { + if (g_npcspskill.integer <= 1) { missile->damage = 5; - } - else - { + } else { missile->damage = 10; } - missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_UNKNOWN; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -337,37 +296,30 @@ void ImperialProbe_FireBlaster(void) ImperialProbe_Ranged ------------------------- */ -void ImperialProbe_Ranged( qboolean visible, qboolean advance ) -{ - int delay_min, delay_max; +void ImperialProbe_Ranged(qboolean visible, qboolean advance) { + int delay_min, delay_max; - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - if ( g_npcspskill.integer == 0 ) - { + if (g_npcspskill.integer == 0) { delay_min = 500; delay_max = 3000; - } - else if ( g_npcspskill.integer > 1 ) - { + } else if (g_npcspskill.integer > 1) { delay_min = 500; delay_max = 2000; - } - else - { + } else { delay_min = 300; delay_max = 1500; } - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( delay_min, delay_max ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(delay_min, delay_max)); ImperialProbe_FireBlaster(); -// ucmd.buttons |= BUTTON_ATTACK; + // ucmd.buttons |= BUTTON_ATTACK; } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); } } @@ -377,60 +329,54 @@ ImperialProbe_AttackDecision ------------------------- */ -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -void ImperialProbe_AttackDecision( void ) -{ - float distance; - qboolean visible, advance; +void ImperialProbe_AttackDecision(void) { + float distance; + qboolean visible, advance; // Always keep a good height off the ground ImperialProbe_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPCS.NPC,"patrolNoise") ) - { - if (TIMER_Done(NPCS.NPC,"angerNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + if (TIMER_Done(NPCS.NPC, "angerNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse ) - { + if (NPC_CheckEnemyExt(qfalse) == qfalse) { ImperialProbe_Idle(); return; } - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); // Rate our distance to the target, and our visibilty - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - ImperialProbe_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + ImperialProbe_Hunt(visible, advance); return; } } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Decide what type of attack to do - ImperialProbe_Ranged( visible, advance ); + ImperialProbe_Ranged(visible, advance); } /* @@ -438,23 +384,22 @@ void ImperialProbe_AttackDecision( void ) NPC_BSDroid_Pain ------------------------- */ -void NPC_Probe_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - float pain_chance; +void NPC_Probe_Pain(gentity_t *self, gentity_t *attacker, int damage) { + float pain_chance; gentity_t *other = attacker; int mod = gPainMOD; - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) // demp2 always messes them up real good + if (self->health < 30 || mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) // demp2 always messes them up real good { vec3_t endPos; - trace_t trace; + trace_t trace; - VectorSet( endPos, self->r.currentOrigin[0], self->r.currentOrigin[1], self->r.currentOrigin[2] - 128 ); - trap->Trace( &trace, self->r.currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, qfalse, 0, 0 ); + VectorSet(endPos, self->r.currentOrigin[0], self->r.currentOrigin[1], self->r.currentOrigin[2] - 128); + trap->Trace(&trace, self->r.currentOrigin, NULL, NULL, endPos, self->s.number, MASK_SOLID, qfalse, 0, 0); - if ( trace.fraction == 1.0f || mod == MOD_DEMP2 ) // demp2 always does this + if (trace.fraction == 1.0f || mod == MOD_DEMP2) // demp2 always does this { /* if (self->client->clientInfo.headModel != 0) @@ -472,37 +417,34 @@ void NPC_Probe_Pain(gentity_t *self, gentity_t *attacker, int damage) } */ - if ( (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other ) - { + if ((mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) && other) { vec3_t dir; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - VectorSubtract( self->r.currentOrigin, other->r.currentOrigin, dir ); - VectorNormalize( dir ); + VectorSubtract(self->r.currentOrigin, other->r.currentOrigin, dir); + VectorNormalize(dir); - VectorMA( self->client->ps.velocity, 550, dir, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, 550, dir, self->client->ps.velocity); self->client->ps.velocity[2] -= 127; } - //self->s.powerups |= ( 1 << PW_SHOCKED ); - //self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + 3000; self->client->ps.electrifyTime = level.time + 3000; self->NPC->localState = LSTATE_DROP; } - } - else - { - pain_chance = NPC_GetPainChance( self, damage ); + } else { + pain_chance = NPC_GetPainChance(self, damage); - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) // Spin around in pain? + if (Q_flrand(0.0f, 1.0f) < pain_chance) // Spin around in pain? { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE); } } - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); } /* @@ -511,8 +453,7 @@ ImperialProbe_Idle ------------------------- */ -void ImperialProbe_Idle( void ) -{ +void ImperialProbe_Idle(void) { ImperialProbe_MaintainHeight(); NPC_BSIdle(); @@ -523,44 +464,38 @@ void ImperialProbe_Idle( void ) NPC_BSImperialProbe_Patrol ------------------------- */ -void ImperialProbe_Patrol( void ) -{ +void ImperialProbe_Patrol(void) { ImperialProbe_MaintainHeight(); - if ( NPC_CheckPlayerTeamStealth() ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (NPC_CheckPlayerTeamStealth()) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL ); + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1, SETANIM_FLAG_NORMAL); - if ( UpdateGoal() ) - { - //start loop sound once we move - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + if (UpdateGoal()) { + // start loop sound once we move + NPCS.NPC->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/probetalk%d", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } - } - else // He's got an enemy. Make him angry. + } else // He's got an enemy. Make him angry. { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1" ); - TIMER_Set( NPCS.NPC, "angerNoise", Q_irand( 2000, 4000 ) ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL; + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, "sound/chars/probe/misc/anger1"); + TIMER_Set(NPCS.NPC, "angerNoise", Q_irand(2000, 4000)); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -568,25 +503,22 @@ void ImperialProbe_Patrol( void ) ImperialProbe_Wait ------------------------- */ -void ImperialProbe_Wait(void) -{ - if ( NPCS.NPCInfo->localState == LSTATE_DROP ) - { +void ImperialProbe_Wait(void) { + if (NPCS.NPCInfo->localState == LSTATE_DROP) { vec3_t endPos; - trace_t trace; + trace_t trace; - NPCS.NPCInfo->desiredYaw = AngleNormalize360( NPCS.NPCInfo->desiredYaw + 25 ); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(NPCS.NPCInfo->desiredYaw + 25); - VectorSet( endPos, NPCS.NPC->r.currentOrigin[0], NPCS.NPC->r.currentOrigin[1], NPCS.NPC->r.currentOrigin[2] - 32 ); - trap->Trace( &trace, NPCS.NPC->r.currentOrigin, NULL, NULL, endPos, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + VectorSet(endPos, NPCS.NPC->r.currentOrigin[0], NPCS.NPC->r.currentOrigin[1], NPCS.NPC->r.currentOrigin[2] - 32); + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, NULL, NULL, endPos, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); - if ( trace.fraction != 1.0f ) - { - G_Damage(NPCS.NPC, NPCS.NPC->enemy, NPCS.NPC->enemy, NULL, NULL, 2000, 0,MOD_UNKNOWN); + if (trace.fraction != 1.0f) { + G_Damage(NPCS.NPC, NPCS.NPC->enemy, NPCS.NPC->enemy, NULL, NULL, 2000, 0, MOD_UNKNOWN); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -594,24 +526,16 @@ void ImperialProbe_Wait(void) NPC_BSImperialProbe_Default ------------------------- */ -void NPC_BSImperialProbe_Default( void ) -{ +void NPC_BSImperialProbe_Default(void) { - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; ImperialProbe_AttackDecision(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { ImperialProbe_Patrol(); - } - else if ( NPCS.NPCInfo->localState == LSTATE_DROP ) - { + } else if (NPCS.NPCInfo->localState == LSTATE_DROP) { ImperialProbe_Wait(); - } - else - { + } else { ImperialProbe_Idle(); } } diff --git a/codemp/game/NPC_AI_Interrogator.c b/codemp/game/NPC_AI_Interrogator.c index 722c935f80..42078d22ad 100644 --- a/codemp/game/NPC_AI_Interrogator.c +++ b/codemp/game/NPC_AI_Interrogator.c @@ -23,15 +23,14 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -void Interrogator_Idle( void ); -void DeathFX( gentity_t *ent ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -enum -{ -LSTATE_BLADESTOP=0, -LSTATE_BLADEUP, -LSTATE_BLADEDOWN, +void Interrogator_Idle(void); +void DeathFX(gentity_t *ent); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +enum { + LSTATE_BLADESTOP = 0, + LSTATE_BLADEUP, + LSTATE_BLADEDOWN, }; /* @@ -39,22 +38,20 @@ LSTATE_BLADEDOWN, NPC_Interrogator_Precache ------------------------- */ -void NPC_Interrogator_Precache(gentity_t *self) -{ - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); +void NPC_Interrogator_Precache(gentity_t *self) { + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); G_SoundIndex("sound/chars/mark1/misc/anger.wav"); - G_SoundIndex( "sound/chars/probe/misc/talk"); - G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject" ); - G_SoundIndex( "sound/chars/interrogator/misc/int_droid_explo" ); - G_EffectIndex( "explosions/droidexplosion1" ); + G_SoundIndex("sound/chars/probe/misc/talk"); + G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject"); + G_SoundIndex("sound/chars/interrogator/misc/int_droid_explo"); + G_EffectIndex("explosions/droidexplosion1"); } /* ------------------------- Interrogator_die ------------------------- */ -void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Interrogator_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { self->client->ps.velocity[2] = -100; /* self->locationDamage[HL_NONE] += damage; @@ -67,14 +64,14 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke else */ { - self->client->ps.eFlags2 &= ~EF2_FLYING;//moveType = MT_WALK; - self->client->ps.velocity[0] = Q_irand( -20, -10 ); - self->client->ps.velocity[1] = Q_irand( -20, -10 ); + self->client->ps.eFlags2 &= ~EF2_FLYING; // moveType = MT_WALK; + self->client->ps.velocity[0] = Q_irand(-20, -10); + self->client->ps.velocity[1] = Q_irand(-20, -10); self->client->ps.velocity[2] = -100; } - //self->takedamage = qfalse; - //self->client->ps.eFlags |= EF_NODRAW; - //self->contents = 0; + // self->takedamage = qfalse; + // self->client->ps.eFlags |= EF_NODRAW; + // self->contents = 0; return; } @@ -83,219 +80,185 @@ void Interrogator_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke Interrogator_PartsMove ------------------------- */ -void Interrogator_PartsMove(void) -{ +void Interrogator_PartsMove(void) { // Syringe - if ( TIMER_Done(NPCS.NPC,"syringeDelay") ) - { - NPCS.NPC->pos1[1] = AngleNormalize360( NPCS.NPC->pos1[1]); - - if ((NPCS.NPC->pos1[1] < 60) || (NPCS.NPC->pos1[1] > 300)) - { - NPCS.NPC->pos1[1]+=Q_irand( -20, 20 ); // Pitch - } - else if (NPCS.NPC->pos1[1] > 180) - { - NPCS.NPC->pos1[1]=Q_irand( 300, 360 ); // Pitch - } - else - { - NPCS.NPC->pos1[1]=Q_irand( 0, 60 ); // Pitch + if (TIMER_Done(NPCS.NPC, "syringeDelay")) { + NPCS.NPC->pos1[1] = AngleNormalize360(NPCS.NPC->pos1[1]); + + if ((NPCS.NPC->pos1[1] < 60) || (NPCS.NPC->pos1[1] > 300)) { + NPCS.NPC->pos1[1] += Q_irand(-20, 20); // Pitch + } else if (NPCS.NPC->pos1[1] > 180) { + NPCS.NPC->pos1[1] = Q_irand(300, 360); // Pitch + } else { + NPCS.NPC->pos1[1] = Q_irand(0, 60); // Pitch } - // trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL ); + // trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone1, NPC->pos1, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + //NEGATIVE_Z, NULL ); NPC_SetBoneAngles(NPCS.NPC, "left_arm", NPCS.NPC->pos1); - TIMER_Set( NPCS.NPC, "syringeDelay", Q_irand( 100, 1000 ) ); + TIMER_Set(NPCS.NPC, "syringeDelay", Q_irand(100, 1000)); } // Scalpel - if ( TIMER_Done(NPCS.NPC,"scalpelDelay") ) - { + if (TIMER_Done(NPCS.NPC, "scalpelDelay")) { // Change pitch - if ( NPCS.NPCInfo->localState == LSTATE_BLADEDOWN ) // Blade is moving down + if (NPCS.NPCInfo->localState == LSTATE_BLADEDOWN) // Blade is moving down { - NPCS.NPC->pos2[0]-= 30; - if (NPCS.NPC->pos2[0] < 180) - { + NPCS.NPC->pos2[0] -= 30; + if (NPCS.NPC->pos2[0] < 180) { NPCS.NPC->pos2[0] = 180; - NPCS.NPCInfo->localState = LSTATE_BLADEUP; // Make it move up + NPCS.NPCInfo->localState = LSTATE_BLADEUP; // Make it move up } - } - else // Blade is coming back up + } else // Blade is coming back up { - NPCS.NPC->pos2[0]+= 30; - if (NPCS.NPC->pos2[0] >= 360) - { + NPCS.NPC->pos2[0] += 30; + if (NPCS.NPC->pos2[0] >= 360) { NPCS.NPC->pos2[0] = 360; - NPCS.NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down - TIMER_Set( NPCS.NPC, "scalpelDelay", Q_irand( 100, 1000 ) ); + NPCS.NPCInfo->localState = LSTATE_BLADEDOWN; // Make it move down + TIMER_Set(NPCS.NPC, "scalpelDelay", Q_irand(100, 1000)); } } - NPCS.NPC->pos2[0] = AngleNormalize360( NPCS.NPC->pos2[0]); - // trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL ); + NPCS.NPC->pos2[0] = AngleNormalize360(NPCS.NPC->pos2[0]); + // trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone2, NPC->pos2, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, + //NEGATIVE_Z, NULL ); NPC_SetBoneAngles(NPCS.NPC, "right_arm", NPCS.NPC->pos2); } // Claw - NPCS.NPC->pos3[1] += Q_irand( 10, 30 ); - NPCS.NPC->pos3[1] = AngleNormalize360( NPCS.NPC->pos3[1]); - //trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL ); + NPCS.NPC->pos3[1] += Q_irand(10, 30); + NPCS.NPC->pos3[1] = AngleNormalize360(NPCS.NPC->pos3[1]); + // trap->G2API_SetBoneAnglesIndex( &NPC->ghoul2[NPC->playerModel], NPC->genericBone3, NPC->pos3, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, + // NULL ); NPC_SetBoneAngles(NPCS.NPC, "claw", NPCS.NPC->pos3); - } -#define VELOCITY_DECAY 0.85f -#define HUNTER_UPWARD_PUSH 2 +#define VELOCITY_DECAY 0.85f +#define HUNTER_UPWARD_PUSH 2 /* ------------------------- Interrogator_MaintainHeight ------------------------- */ -void Interrogator_MaintainHeight( void ) -{ - float dif; -// vec3_t endPos; -// trace_t trace; +void Interrogator_MaintainHeight(void) { + float dif; + // vec3_t endPos; + // trace_t trace; - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_lp" ); + NPCS.NPC->s.loopSound = G_SoundIndex("sound/chars/interrogator/misc/torture_droid_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { // Find the height difference dif = (NPCS.NPC->enemy->r.currentOrigin[2] + NPCS.NPC->enemy->r.maxs[2]) - NPCS.NPC->r.currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 16 ) - { - dif = ( dif < 0 ? -16 : 16 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 16) { + dif = (dif < 0 ? -16 : 16); } - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCS.NPCInfo->goalEntity ) // Is there a goal? + if (NPCS.NPCInfo->goalEntity) // Is there a goal? { goal = NPCS.NPCInfo->goalEntity; - } - else - { + } else { goal = NPCS.NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - NPCS.ucmd.upmove = ( NPCS.ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPCS.NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + NPCS.ucmd.upmove = (NPCS.ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 2) { NPCS.NPC->client->ps.velocity[2] = 0; } } } } // Apply friction - else if ( NPCS.NPC->client->ps.velocity[2] ) - { + else if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 1) { NPCS.NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPCS.NPC->client->ps.velocity[0] ) - { + if (NPCS.NPC->client->ps.velocity[0]) { NPCS.NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[0]) < 1) { NPCS.NPC->client->ps.velocity[0] = 0; } } - if ( NPCS.NPC->client->ps.velocity[1] ) - { + if (NPCS.NPC->client->ps.velocity[1]) { NPCS.NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[1]) < 1) { NPCS.NPC->client->ps.velocity[1] = 0; } } } -#define HUNTER_STRAFE_VEL 32 -#define HUNTER_STRAFE_DIS 200 +#define HUNTER_STRAFE_VEL 32 +#define HUNTER_STRAFE_DIS 200 /* ------------------------- Interrogator_Strafe ------------------------- */ -void Interrogator_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; - float dif; +void Interrogator_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; + float dif; - AngleVectors( NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPCS.NPC->r.currentOrigin, HUNTER_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPCS.NPC->r.currentOrigin, HUNTER_STRAFE_DIS * dir, right, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPCS.NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPCS.NPC->client->ps.velocity, HUNTER_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity); // Add a slight upward push - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { // Find the height difference dif = (NPCS.NPC->enemy->r.currentOrigin[2] + 32) - NPCS.NPC->r.currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - dif = ( dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH ); + if (fabs(dif) > 8) { + dif = (dif < 0 ? -HUNTER_UPWARD_PUSH : HUNTER_UPWARD_PUSH); } NPCS.NPC->client->ps.velocity[2] += dif; - } // Set the strafe start time - //NPCS.NPC->fx_time = level.time; + // NPCS.NPC->fx_time = level.time; NPCS.NPCInfo->standTime = level.time + 3000 + Q_flrand(0.0f, 1.0f) * 500; } } @@ -306,92 +269,83 @@ Interrogator_Hunt -------------------------` */ -#define HUNTER_FORWARD_BASE_SPEED 10 -#define HUNTER_FORWARD_MULTIPLIER 2 +#define HUNTER_FORWARD_BASE_SPEED 10 +#define HUNTER_FORWARD_MULTIPLIER 2 -void Interrogator_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Interrogator_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; Interrogator_PartsMove(); NPC_FaceEnemy(qfalse); - //If we're not supposed to stand still, pursue the player - if ( NPCS.NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCS.NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Interrogator_Strafe(); - if ( NPCS.NPCInfo->standTime > level.time ) - {//successfully strafed + if (NPCS.NPCInfo->standTime > level.time) { // successfully strafed return; } } } - //If we don't want to advance, stop here - if ( advance == qfalse ) + // If we don't want to advance, stop here + if (advance == qfalse) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = HUNTER_FORWARD_BASE_SPEED + HUNTER_FORWARD_MULTIPLIER * g_npcspskill.integer; - VectorMA( NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity); } -#define MIN_DISTANCE 64 +#define MIN_DISTANCE 64 /* ------------------------- Interrogator_Melee ------------------------- */ -void Interrogator_Melee( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? +void Interrogator_Melee(qboolean visible, qboolean advance) { + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { // Make sure that we are within the height range before we allow any damage to happen - if ( NPCS.NPC->r.currentOrigin[2] >= NPCS.NPC->enemy->r.currentOrigin[2]+NPCS.NPC->enemy->r.mins[2] && NPCS.NPC->r.currentOrigin[2]+NPCS.NPC->r.mins[2]+8 < NPCS.NPC->enemy->r.currentOrigin[2]+NPCS.NPC->enemy->r.maxs[2] ) - { - //gentity_t *tent; + if (NPCS.NPC->r.currentOrigin[2] >= NPCS.NPC->enemy->r.currentOrigin[2] + NPCS.NPC->enemy->r.mins[2] && + NPCS.NPC->r.currentOrigin[2] + NPCS.NPC->r.mins[2] + 8 < NPCS.NPC->enemy->r.currentOrigin[2] + NPCS.NPC->enemy->r.maxs[2]) { + // gentity_t *tent; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 3000 ) ); - G_Damage( NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 3000)); + G_Damage(NPCS.NPC->enemy, NPCS.NPC, NPCS.NPC, 0, 0, 2, DAMAGE_NO_KNOCKBACK, MOD_MELEE); - // NPC->enemy->client->poisonDamage = 18; - // NPC->enemy->client->poisonTime = level.time + 1000; + // NPC->enemy->client->poisonDamage = 18; + // NPC->enemy->client->poisonTime = level.time + 1000; // Drug our enemy up and do the wonky vision thing -// tent = G_TempEntity( NPC->enemy->r.currentOrigin, EV_DRUGGED ); -// tent->owner = NPC->enemy; + // tent = G_TempEntity( NPC->enemy->r.currentOrigin, EV_DRUGGED ); + // tent->owner = NPC->enemy; - //rwwFIXMEFIXME: poison damage + // rwwFIXMEFIXME: poison damage - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/interrogator/misc/torture_droid_inject.mp3" )); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/interrogator/misc/torture_droid_inject.mp3")); } } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } } @@ -400,52 +354,45 @@ void Interrogator_Melee( qboolean visible, qboolean advance ) Interrogator_Attack ------------------------- */ -void Interrogator_Attack( void ) -{ - float distance; - qboolean visible; - qboolean advance; +void Interrogator_Attack(void) { + float distance; + qboolean visible; + qboolean advance; // Always keep a good height off the ground Interrogator_MaintainHeight(); - //randomly talk - if ( TIMER_Done(NPCS.NPC,"patrolNoise") ) - { - if (TIMER_Done(NPCS.NPC,"angerNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + if (TIMER_Done(NPCS.NPC, "angerNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/probe/misc/talk.wav", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(4000, 10000)); } } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse ) - { + if (NPC_CheckEnemyExt(qfalse) == qfalse) { Interrogator_Idle(); return; } // Rate our distance to the target, and our visibilty - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE*MIN_DISTANCE ); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE * MIN_DISTANCE); - if ( !visible ) - { + if (!visible) { advance = qtrue; } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Interrogator_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Interrogator_Hunt(visible, advance); } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (!advance) - { - Interrogator_Melee( visible, advance ); + if (!advance) { + Interrogator_Melee(visible, advance); } } @@ -454,12 +401,10 @@ void Interrogator_Attack( void ) Interrogator_Idle ------------------------- */ -void Interrogator_Idle( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav" ); - NPC_UpdateAngles( qtrue, qtrue ); +void Interrogator_Idle(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, "sound/chars/mark1/misc/anger.wav"); + NPC_UpdateAngles(qtrue, qtrue); return; } @@ -473,17 +418,12 @@ void Interrogator_Idle( void ) NPC_BSInterrogator_Default ------------------------- */ -void NPC_BSInterrogator_Default( void ) -{ - //NPC->e_DieFunc = dieF_Interrogator_die; +void NPC_BSInterrogator_Default(void) { + // NPC->e_DieFunc = dieF_Interrogator_die; - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { Interrogator_Attack(); - } - else - { + } else { Interrogator_Idle(); } - } diff --git a/codemp/game/NPC_AI_Jedi.c b/codemp/game/NPC_AI_Jedi.c index 1fa89d91ca..2e97e478f1 100644 --- a/codemp/game/NPC_AI_Jedi.c +++ b/codemp/game/NPC_AI_Jedi.c @@ -25,232 +25,197 @@ along with this program; if not, see . #include "anims.h" #include "w_saber.h" -extern qboolean BG_SabersOff( playerState_t *ps ); - -extern void CG_DrawAlert( vec3_t origin, float rating ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void ForceJump( gentity_t *self, usercmd_t *ucmd ); - -#define MAX_VIEW_DIST 2048 -#define MAX_VIEW_SPEED 100 -#define JEDI_MAX_LIGHT_INTENSITY 64 -#define JEDI_MIN_LIGHT_THRESHOLD 10 -#define JEDI_MAX_LIGHT_THRESHOLD 50 - -#define DISTANCE_SCALE 0.25f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.3 ) - -#define MAX_CHECK_THRESHOLD 1 - -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean NPC_CheckEnemyStealth( void ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); - -extern gitem_t *BG_FindItemForAmmo( ammo_t ammo ); - -extern void ForceThrow( gentity_t *self, qboolean pull ); -extern void ForceLightning( gentity_t *self ); -extern void ForceHeal( gentity_t *self ); -extern void ForceRage( gentity_t *self ); -extern void ForceProtect( gentity_t *self ); -extern void ForceAbsorb( gentity_t *self ); -extern int WP_MissileBlockForBlock( int saberBlock ); -extern qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ); -extern qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ); -extern qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ); -extern void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ); -extern void WP_DeactivateSaber( gentity_t *self, qboolean clearLength ); //clearLength = qfalse -extern void WP_ActivateSaber( gentity_t *self ); - -extern qboolean PM_SaberInStart( int move ); -extern qboolean BG_SaberInSpecialAttack( int anim ); -extern qboolean BG_SaberInAttack( int move ); -extern qboolean PM_SaberInBounce( int move ); -extern qboolean PM_SaberInParry( int move ); -extern qboolean PM_SaberInKnockaway( int move ); -extern qboolean PM_SaberInBrokenParry( int move ); -extern qboolean PM_SaberInDeflect( int move ); -extern qboolean BG_SpinningSaberAnim( int anim ); -extern qboolean BG_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean BG_InRoll( playerState_t *ps, int anim ); -extern qboolean BG_CrouchAnim( int anim ); +extern qboolean BG_SabersOff(playerState_t *ps); + +extern void CG_DrawAlert(vec3_t origin, float rating); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void ForceJump(gentity_t *self, usercmd_t *ucmd); + +#define MAX_VIEW_DIST 2048 +#define MAX_VIEW_SPEED 100 +#define JEDI_MAX_LIGHT_INTENSITY 64 +#define JEDI_MIN_LIGHT_THRESHOLD 10 +#define JEDI_MAX_LIGHT_THRESHOLD 50 + +#define DISTANCE_SCALE 0.25f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.3) + +#define MAX_CHECK_THRESHOLD 1 + +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean NPC_CheckEnemyStealth(void); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); + +extern gitem_t *BG_FindItemForAmmo(ammo_t ammo); + +extern void ForceThrow(gentity_t *self, qboolean pull); +extern void ForceLightning(gentity_t *self); +extern void ForceHeal(gentity_t *self); +extern void ForceRage(gentity_t *self); +extern void ForceProtect(gentity_t *self); +extern void ForceAbsorb(gentity_t *self); +extern int WP_MissileBlockForBlock(int saberBlock); +extern qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod); +extern qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower); +extern qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt); +extern void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower); +extern void WP_DeactivateSaber(gentity_t *self, qboolean clearLength); // clearLength = qfalse +extern void WP_ActivateSaber(gentity_t *self); + +extern qboolean PM_SaberInStart(int move); +extern qboolean BG_SaberInSpecialAttack(int anim); +extern qboolean BG_SaberInAttack(int move); +extern qboolean PM_SaberInBounce(int move); +extern qboolean PM_SaberInParry(int move); +extern qboolean PM_SaberInKnockaway(int move); +extern qboolean PM_SaberInBrokenParry(int move); +extern qboolean PM_SaberInDeflect(int move); +extern qboolean BG_SpinningSaberAnim(int anim); +extern qboolean BG_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean BG_InRoll(playerState_t *ps, int anim); +extern qboolean BG_CrouchAnim(int anim); extern qboolean NPC_SomeoneLookingAtMe(gentity_t *ent); -extern int WP_GetVelocityForForceJump( gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd ); +extern int WP_GetVelocityForForceJump(gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd); extern void G_TestLine(vec3_t start, vec3_t end, int color, int time); -static void Jedi_Aggression( gentity_t *self, int change ); -qboolean Jedi_WaitingAmbush( gentity_t *self ); +static void Jedi_Aggression(gentity_t *self, int change); +qboolean Jedi_WaitingAmbush(gentity_t *self); extern int bg_parryDebounce[]; -static int jediSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several jedi from speaking all at once -//Local state enums -enum -{ +static int jediSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several jedi from speaking all at once +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void NPC_ShadowTrooper_Precache( void ) -{ - RegisterItem( BG_FindItemForAmmo( AMMO_FORCE ) ); - G_SoundIndex( "sound/chars/shadowtrooper/cloak.wav" ); - G_SoundIndex( "sound/chars/shadowtrooper/decloak.wav" ); +void NPC_ShadowTrooper_Precache(void) { + RegisterItem(BG_FindItemForAmmo(AMMO_FORCE)); + G_SoundIndex("sound/chars/shadowtrooper/cloak.wav"); + G_SoundIndex("sound/chars/shadowtrooper/decloak.wav"); } -void Jedi_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "strafeLeft", 0 ); - TIMER_Set( ent, "strafeRight", 0 ); - TIMER_Set( ent, "noStrafe", 0 ); - TIMER_Set( ent, "walking", 0 ); - TIMER_Set( ent, "taunting", 0 ); - TIMER_Set( ent, "parryTime", 0 ); - TIMER_Set( ent, "parryReCalcTime", 0 ); - TIMER_Set( ent, "forceJumpChasing", 0 ); - TIMER_Set( ent, "jumpChaseDebounce", 0 ); - TIMER_Set( ent, "moveforward", 0 ); - TIMER_Set( ent, "moveback", 0 ); - TIMER_Set( ent, "movenone", 0 ); - TIMER_Set( ent, "moveright", 0 ); - TIMER_Set( ent, "moveleft", 0 ); - TIMER_Set( ent, "movecenter", 0 ); - TIMER_Set( ent, "saberLevelDebounce", 0 ); - TIMER_Set( ent, "noRetreat", 0 ); - TIMER_Set( ent, "holdLightning", 0 ); - TIMER_Set( ent, "gripping", 0 ); - TIMER_Set( ent, "draining", 0 ); - TIMER_Set( ent, "noturn", 0 ); +void Jedi_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "strafeLeft", 0); + TIMER_Set(ent, "strafeRight", 0); + TIMER_Set(ent, "noStrafe", 0); + TIMER_Set(ent, "walking", 0); + TIMER_Set(ent, "taunting", 0); + TIMER_Set(ent, "parryTime", 0); + TIMER_Set(ent, "parryReCalcTime", 0); + TIMER_Set(ent, "forceJumpChasing", 0); + TIMER_Set(ent, "jumpChaseDebounce", 0); + TIMER_Set(ent, "moveforward", 0); + TIMER_Set(ent, "moveback", 0); + TIMER_Set(ent, "movenone", 0); + TIMER_Set(ent, "moveright", 0); + TIMER_Set(ent, "moveleft", 0); + TIMER_Set(ent, "movecenter", 0); + TIMER_Set(ent, "saberLevelDebounce", 0); + TIMER_Set(ent, "noRetreat", 0); + TIMER_Set(ent, "holdLightning", 0); + TIMER_Set(ent, "gripping", 0); + TIMER_Set(ent, "draining", 0); + TIMER_Set(ent, "noturn", 0); } -void Jedi_PlayBlockedPushSound( gentity_t *self ) -{ - if ( self->s.number >= 0 && self->s.number < MAX_CLIENTS ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, EV_PUSHFAIL, 3000 ); +void Jedi_PlayBlockedPushSound(gentity_t *self) { + if (self->s.number >= 0 && self->s.number < MAX_CLIENTS) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, EV_PUSHFAIL, 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void Jedi_PlayDeflectSound( gentity_t *self ) -{ - if ( self->s.number >= 0 && self->s.number < MAX_CLIENTS ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); - } - else if ( self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( self, Q_irand( EV_DEFLECT1, EV_DEFLECT3 ), 3000 ); +void Jedi_PlayDeflectSound(gentity_t *self) { + if (self->s.number >= 0 && self->s.number < MAX_CLIENTS) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); + } else if (self->health > 0 && self->NPC && self->NPC->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(self, Q_irand(EV_DEFLECT1, EV_DEFLECT3), 3000); self->NPC->blockedSpeechDebounceTime = level.time + 3000; } } -void NPC_Jedi_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->client && ( self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_DESANN ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE1, EV_CONFUSE3 ), 2000 ); - } - else if ( Q_irand( 0, 1 ) ) - { - G_AddVoiceEvent( self, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 2000 ); - } - else - { - G_AddVoiceEvent( self, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 2000 ); +void NPC_Jedi_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->client && (self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_DESANN)) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); + } else if (Q_irand(0, 1)) { + G_AddVoiceEvent(self, Q_irand(EV_TAUNT1, EV_TAUNT3), 2000); + } else { + G_AddVoiceEvent(self, Q_irand(EV_GLOAT1, EV_GLOAT3), 2000); } } } -qboolean Jedi_CultistDestroyer( gentity_t *self ) -{ - if ( !self || !self->client ) - { +qboolean Jedi_CultistDestroyer(gentity_t *self) { + if (!self || !self->client) { return qfalse; } - if( self->client->NPC_class == CLASS_REBORN && - self->s.weapon == WP_MELEE && - !Q_stricmp( "cultist_destroyer", self->NPC_type ) ) - { + if (self->client->NPC_class == CLASS_REBORN && self->s.weapon == WP_MELEE && !Q_stricmp("cultist_destroyer", self->NPC_type)) { return qtrue; } return qfalse; } -void Boba_Precache( void ) -{ - G_SoundIndex( "sound/boba/jeton.wav" ); - G_SoundIndex( "sound/boba/jethover.wav" ); - G_SoundIndex( "sound/effects/combustfire.mp3" ); - G_EffectIndex( "boba/jet" ); - G_EffectIndex( "boba/fthrw" ); +void Boba_Precache(void) { + G_SoundIndex("sound/boba/jeton.wav"); + G_SoundIndex("sound/boba/jethover.wav"); + G_SoundIndex("sound/effects/combustfire.mp3"); + G_EffectIndex("boba/jet"); + G_EffectIndex("boba/fthrw"); } -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -void Boba_ChangeWeapon( int wp ) -{ - if ( NPCS.NPC->s.weapon == wp ) - { +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +void Boba_ChangeWeapon(int wp) { + if (NPCS.NPC->s.weapon == wp) { return; } - NPC_ChangeWeapon( wp ); - G_AddEvent( NPCS.NPC, EV_GENERAL_SOUND, G_SoundIndex( "sound/weapons/change.wav" )); + NPC_ChangeWeapon(wp); + G_AddEvent(NPCS.NPC, EV_GENERAL_SOUND, G_SoundIndex("sound/weapons/change.wav")); } -void WP_ResistForcePush( gentity_t *self, gentity_t *pusher, qboolean noPenalty ) -{ +void WP_ResistForcePush(gentity_t *self, gentity_t *pusher, qboolean noPenalty) { int parts; qboolean runningResist = qfalse; - if ( !self || self->health <= 0 || !self->client || !pusher || !pusher->client ) - { + if (!self || self->health <= 0 || !self->client || !pusher || !pusher->client) { return; } - if ( ((self->s.number >= 0 && self->s.number < MAX_CLIENTS) || self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",self->NPC_type) || self->client->NPC_class == CLASS_LUKE) - && (VectorLengthSquared( self->client->ps.velocity ) > 10000 || self->client->ps.fd.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || self->client->ps.fd.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3 ) ) - { + if (((self->s.number >= 0 && self->s.number < MAX_CLIENTS) || self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", self->NPC_type) || + self->client->NPC_class == CLASS_LUKE) && + (VectorLengthSquared(self->client->ps.velocity) > 10000 || self->client->ps.fd.forcePowerLevel[FP_PUSH] >= FORCE_LEVEL_3 || + self->client->ps.fd.forcePowerLevel[FP_PULL] >= FORCE_LEVEL_3)) { runningResist = qtrue; } - if ( !runningResist - && self->client->ps.groundEntityNum != ENTITYNUM_NONE - && !BG_SpinningSaberAnim( self->client->ps.legsAnim ) - && !BG_FlippingAnim( self->client->ps.legsAnim ) - && !PM_RollingAnim( self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) - && !BG_CrouchAnim( self->client->ps.legsAnim )) - {//if on a surface and not in a spin or flip, play full body resist + if (!runningResist && self->client->ps.groundEntityNum != ENTITYNUM_NONE && !BG_SpinningSaberAnim(self->client->ps.legsAnim) && + !BG_FlippingAnim(self->client->ps.legsAnim) && !PM_RollingAnim(self->client->ps.legsAnim) && !PM_InKnockDown(&self->client->ps) && + !BG_CrouchAnim(self->client->ps.legsAnim)) { // if on a surface and not in a spin or flip, play full body resist parts = SETANIM_BOTH; - } - else - {//play resist just in torso + } else { // play resist just in torso parts = SETANIM_TORSO; } - NPC_SetAnim( self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( !noPenalty ) - { + NPC_SetAnim(self, parts, BOTH_RESISTPUSH, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (!noPenalty) { char buf[128]; float tFVal = 0; @@ -258,196 +223,162 @@ void WP_ResistForcePush( gentity_t *self, gentity_t *pusher, qboolean noPenalty tFVal = atof(buf); - if ( !runningResist ) - { - VectorClear( self->client->ps.velocity ); - //still stop them from attacking or moving for a bit, though - //FIXME: maybe push just a little (like, slide)? + if (!runningResist) { + VectorClear(self->client->ps.velocity); + // still stop them from attacking or moving for a bit, though + // FIXME: maybe push just a little (like, slide)? self->client->ps.weaponTime = 1000; - if ( self->client->ps.fd.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * tFVal ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * tFVal); } self->client->ps.pm_time = self->client->ps.weaponTime; self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //play the full body push effect on me - //self->forcePushTime = level.time + 600; // let the push effect last for 600 ms - //rwwFIXMEFIXME: Do this? - } - else - { + // play the full body push effect on me + // self->forcePushTime = level.time + 600; // let the push effect last for 600 ms + // rwwFIXMEFIXME: Do this? + } else { self->client->ps.weaponTime = 600; - if ( self->client->ps.fd.forcePowersActive&(1<client->ps.weaponTime = floor( self->client->ps.weaponTime * tFVal ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) { + self->client->ps.weaponTime = floor(self->client->ps.weaponTime * tFVal); } } } - //play my force push effect on my hand + // play my force push effect on my hand self->client->ps.powerups[PW_DISINT_4] = level.time + self->client->ps.torsoTimer + 500; self->client->ps.powerups[PW_PULL] = 0; - Jedi_PlayBlockedPushSound( self ); + Jedi_PlayBlockedPushSound(self); } -qboolean Boba_StopKnockdown( gentity_t *self, gentity_t *pusher, vec3_t pushDir, qboolean forceKnockdown ) //forceKnockdown = qfalse +qboolean Boba_StopKnockdown(gentity_t *self, gentity_t *pusher, vec3_t pushDir, qboolean forceKnockdown) // forceKnockdown = qfalse { - vec3_t pDir, fwd, right, ang; - float fDot, rDot; - int strafeTime; + vec3_t pDir, fwd, right, ang; + float fDot, rDot; + int strafeTime; - if ( self->client->NPC_class != CLASS_BOBAFETT ) - { + if (self->client->NPC_class != CLASS_BOBAFETT) { return qfalse; } - if ( (self->client->ps.eFlags2&EF2_FLYING) )//moveType == MT_FLYSWIM ) - {//can't knock me down when I'm flying + if ((self->client->ps.eFlags2 & EF2_FLYING)) // moveType == MT_FLYSWIM ) + { // can't knock me down when I'm flying return qtrue; } VectorSet(ang, 0, self->r.currentAngles[YAW], 0); - strafeTime = Q_irand( 1000, 2000 ); + strafeTime = Q_irand(1000, 2000); - AngleVectors( ang, fwd, right, NULL ); - VectorNormalize2( pushDir, pDir ); - fDot = DotProduct( pDir, fwd ); - rDot = DotProduct( pDir, right ); + AngleVectors(ang, fwd, right, NULL); + VectorNormalize2(pushDir, pDir); + fDot = DotProduct(pDir, fwd); + rDot = DotProduct(pDir, right); - if ( Q_irand( 0, 2 ) ) - {//flip or roll with it - usercmd_t tempCmd; - if ( fDot >= 0.4f ) - { + if (Q_irand(0, 2)) { // flip or roll with it + usercmd_t tempCmd; + if (fDot >= 0.4f) { tempCmd.forwardmove = 127; - TIMER_Set( self, "moveforward", strafeTime ); - } - else if ( fDot <= -0.4f ) - { + TIMER_Set(self, "moveforward", strafeTime); + } else if (fDot <= -0.4f) { tempCmd.forwardmove = -127; - TIMER_Set( self, "moveback", strafeTime ); - } - else if ( rDot > 0 ) - { + TIMER_Set(self, "moveback", strafeTime); + } else if (rDot > 0) { tempCmd.rightmove = 127; - TIMER_Set( self, "strafeRight", strafeTime ); - TIMER_Set( self, "strafeLeft", -1 ); - } - else - { + TIMER_Set(self, "strafeRight", strafeTime); + TIMER_Set(self, "strafeLeft", -1); + } else { tempCmd.rightmove = -127; - TIMER_Set( self, "strafeLeft", strafeTime ); - TIMER_Set( self, "strafeRight", -1 ); - } - G_AddEvent( self, EV_JUMP, 0 ); - if ( !Q_irand( 0, 1 ) ) - {//flip - self->client->ps.fd.forceJumpCharge = 280;//FIXME: calc this intelligently? - ForceJump( self, &tempCmd ); - } - else - {//roll - TIMER_Set( self, "duck", strafeTime ); - } - self->painDebounceTime = 0;//so we do something - } - else if ( !Q_irand( 0, 1 ) && forceKnockdown ) - {//resist - WP_ResistForcePush( self, pusher, qtrue ); - } - else - {//fall down + TIMER_Set(self, "strafeLeft", strafeTime); + TIMER_Set(self, "strafeRight", -1); + } + G_AddEvent(self, EV_JUMP, 0); + if (!Q_irand(0, 1)) { // flip + self->client->ps.fd.forceJumpCharge = 280; // FIXME: calc this intelligently? + ForceJump(self, &tempCmd); + } else { // roll + TIMER_Set(self, "duck", strafeTime); + } + self->painDebounceTime = 0; // so we do something + } else if (!Q_irand(0, 1) && forceKnockdown) { // resist + WP_ResistForcePush(self, pusher, qtrue); + } else { // fall down return qfalse; } return qtrue; } -void Boba_FlyStart( gentity_t *self ) -{//switch to seeker AI for a while - if ( TIMER_Done( self, "jetRecharge" ) ) - { +void Boba_FlyStart(gentity_t *self) { // switch to seeker AI for a while + if (TIMER_Done(self, "jetRecharge")) { self->client->ps.gravity = 0; - if ( self->NPC ) - { + if (self->NPC) { self->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; } - self->client->ps.eFlags2 |= EF2_FLYING;//moveType = MT_FLYSWIM; - self->client->jetPackTime = level.time + Q_irand( 3000, 10000 ); - //take-off sound - G_SoundOnEnt( self, CHAN_ITEM, "sound/boba/jeton.wav" ); - //jet loop sound - self->s.loopSound = G_SoundIndex( "sound/boba/jethover.wav" ); - if ( self->NPC ) - { + self->client->ps.eFlags2 |= EF2_FLYING; // moveType = MT_FLYSWIM; + self->client->jetPackTime = level.time + Q_irand(3000, 10000); + // take-off sound + G_SoundOnEnt(self, CHAN_ITEM, "sound/boba/jeton.wav"); + // jet loop sound + self->s.loopSound = G_SoundIndex("sound/boba/jethover.wav"); + if (self->NPC) { self->count = Q3_INFINITE; // SEEKER shot ammo count } } } -void Boba_FlyStop( gentity_t *self ) -{ +void Boba_FlyStop(gentity_t *self) { self->client->ps.gravity = g_gravity.value; - if ( self->NPC ) - { + if (self->NPC) { self->NPC->aiFlags &= ~NPCAI_CUSTOM_GRAVITY; } self->client->ps.eFlags2 &= ~EF2_FLYING; self->client->jetPackTime = 0; - //stop jet loop sound + // stop jet loop sound self->s.loopSound = 0; - if ( self->NPC ) - { + if (self->NPC) { self->count = 0; // SEEKER shot ammo count - TIMER_Set( self, "jetRecharge", Q_irand( 1000, 5000 ) ); - TIMER_Set( self, "jumpChaseDebounce", Q_irand( 500, 2000 ) ); + TIMER_Set(self, "jetRecharge", Q_irand(1000, 5000)); + TIMER_Set(self, "jumpChaseDebounce", Q_irand(500, 2000)); } } -qboolean Boba_Flying( gentity_t *self ) -{ - return ((qboolean)(self->client->ps.eFlags2&EF2_FLYING));//moveType==MT_FLYSWIM)); +qboolean Boba_Flying(gentity_t *self) { + return ((qboolean)(self->client->ps.eFlags2 & EF2_FLYING)); // moveType==MT_FLYSWIM)); } -void Boba_FireFlameThrower( gentity_t *self ) -{ - int damage = Q_irand( 20, 30 ); - trace_t tr; - gentity_t *traceEnt = NULL; - mdxaBone_t boltMatrix; - vec3_t start, end, dir, traceMins = {-4, -4, -4}, traceMaxs = {4, 4, 4}; +void Boba_FireFlameThrower(gentity_t *self) { + int damage = Q_irand(20, 30); + trace_t tr; + gentity_t *traceEnt = NULL; + mdxaBone_t boltMatrix; + vec3_t start, end, dir, traceMins = {-4, -4, -4}, traceMaxs = {4, 4, 4}; - trap->G2API_GetBoltMatrix( self->ghoul2, 0, self->client->renderInfo.handLBolt, - &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, - NULL, self->modelScale ); + trap->G2API_GetBoltMatrix(self->ghoul2, 0, self->client->renderInfo.handLBolt, &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, + self->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, start ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); - //G_PlayEffect( "boba/fthrw", start, dir ); - VectorMA( start, 128, dir, end ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, start); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); + // G_PlayEffect( "boba/fthrw", start, dir ); + VectorMA(start, 128, dir, end); - trap->Trace( &tr, start, traceMins, traceMaxs, end, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, start, traceMins, traceMaxs, end, self->s.number, MASK_SHOT, qfalse, 0, 0); traceEnt = &g_entities[tr.entityNum]; - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { - G_Damage( traceEnt, self, self, dir, tr.endpos, damage, DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|/*DAMAGE_NO_HIT_LOC|*/DAMAGE_IGNORE_TEAM, MOD_LAVA ); - //rwwFIXMEFIXME: add DAMAGE_NO_HIT_LOC? + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { + G_Damage(traceEnt, self, self, dir, tr.endpos, damage, DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | /*DAMAGE_NO_HIT_LOC|*/ DAMAGE_IGNORE_TEAM, MOD_LAVA); + // rwwFIXMEFIXME: add DAMAGE_NO_HIT_LOC? } } -void Boba_StartFlameThrower( gentity_t *self ) -{ - int flameTime = 4000;//Q_irand( 1000, 3000 ); - mdxaBone_t boltMatrix; - vec3_t org, dir; +void Boba_StartFlameThrower(gentity_t *self) { + int flameTime = 4000; // Q_irand( 1000, 3000 ); + mdxaBone_t boltMatrix; + vec3_t org, dir; - self->client->ps.torsoTimer = flameTime;//+1000; - if ( self->NPC ) - { - TIMER_Set( self, "nextAttackDelay", flameTime ); - TIMER_Set( self, "walking", 0 ); + self->client->ps.torsoTimer = flameTime; //+1000; + if (self->NPC) { + TIMER_Set(self, "nextAttackDelay", flameTime); + TIMER_Set(self, "walking", 0); } - TIMER_Set( self, "flameTime", flameTime ); + TIMER_Set(self, "flameTime", flameTime); /* gentity_t *fire = G_Spawn(); if ( fire != NULL ) @@ -476,45 +407,38 @@ void Boba_StartFlameThrower( gentity_t *self ) } */ - G_SoundOnEnt( self, CHAN_WEAPON, "sound/effects/combustfire.mp3" ); + G_SoundOnEnt(self, CHAN_WEAPON, "sound/effects/combustfire.mp3"); - trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, NPCS.NPC->client->renderInfo.handRBolt, &boltMatrix, NPCS.NPC->r.currentAngles, - NPCS.NPC->r.currentOrigin, level.time, NULL, NPCS.NPC->modelScale); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, NPCS.NPC->client->renderInfo.handRBolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, + level.time, NULL, NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); - G_PlayEffectID( G_EffectIndex("boba/fthrw"), org, dir); + G_PlayEffectID(G_EffectIndex("boba/fthrw"), org, dir); } -void Boba_DoFlameThrower( gentity_t *self ) -{ - NPC_SetAnim( self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( TIMER_Done( self, "nextAttackDelay" ) && TIMER_Done( self, "flameTime" ) ) - { - Boba_StartFlameThrower( self ); +void Boba_DoFlameThrower(gentity_t *self) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_FORCELIGHTNING_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (TIMER_Done(self, "nextAttackDelay") && TIMER_Done(self, "flameTime")) { + Boba_StartFlameThrower(self); } - Boba_FireFlameThrower( self ); + Boba_FireFlameThrower(self); } -void Boba_FireDecide( void ) -{ +void Boba_FireDecide(void) { qboolean enemyLOS = qfalse, enemyCS = qfalse, enemyInFOV = qfalse; - //qboolean move = qtrue; + // qboolean move = qtrue; qboolean shoot = qfalse, hitAlly = qfalse; - vec3_t impactPos, enemyDir, shootDir; - float enemyDist, dot; + vec3_t impactPos, enemyDir, shootDir; + float enemyDist, dot; - if ( NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE - && NPCS.NPC->client->ps.fd.forceJumpZStart - && !BG_FlippingAnim( NPCS.NPC->client->ps.legsAnim ) - && !Q_irand( 0, 10 ) ) - {//take off - Boba_FlyStart( NPCS.NPC ); + if (NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE && NPCS.NPC->client->ps.fd.forceJumpZStart && !BG_FlippingAnim(NPCS.NPC->client->ps.legsAnim) && + !Q_irand(0, 10)) { // take off + Boba_FlyStart(NPCS.NPC); } - if ( !NPCS.NPC->enemy ) - { + if (!NPCS.NPC->enemy) { return; } @@ -524,238 +448,198 @@ void Boba_FireDecide( void ) NPCInfo->scriptFlags |= SCF_ALT_FIRE; Boba_ChangeWeapon( WP_DISRUPTOR ); } - else */if ( NPCS.NPC->enemy->s.weapon == WP_SABER ) - { + else */ + if (NPCS.NPC->enemy->s.weapon == WP_SABER) { NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - Boba_ChangeWeapon( WP_ROCKET_LAUNCHER ); - } - else - { - if ( NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth*0.5f ) - { + Boba_ChangeWeapon(WP_ROCKET_LAUNCHER); + } else { + if (NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth * 0.5f) { NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; - Boba_ChangeWeapon( WP_BLASTER ); + Boba_ChangeWeapon(WP_BLASTER); NPCS.NPCInfo->burstMin = 3; NPCS.NPCInfo->burstMean = 12; NPCS.NPCInfo->burstMax = 20; - NPCS.NPCInfo->burstSpacing = Q_irand( 300, 750 );//attack debounce - } - else - { + NPCS.NPCInfo->burstSpacing = Q_irand(300, 750); // attack debounce + } else { NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - Boba_ChangeWeapon( WP_BLASTER ); + Boba_ChangeWeapon(WP_BLASTER); } } - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); + VectorClear(impactPos); + enemyDist = DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, enemyDir ); - VectorNormalize( enemyDir ); - AngleVectors( NPCS.NPC->client->ps.viewangles, shootDir, NULL, NULL ); - dot = DotProduct( enemyDir, shootDir ); - if ( dot > 0.5f ||( enemyDist * (1.0f-dot)) < 10000 ) - {//enemy is in front of me or they're very close and not behind me + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, enemyDir); + VectorNormalize(enemyDir); + AngleVectors(NPCS.NPC->client->ps.viewangles, shootDir, NULL, NULL); + dot = DotProduct(enemyDir, shootDir); + if (dot > 0.5f || (enemyDist * (1.0f - dot)) < 10000) { // enemy is in front of me or they're very close and not behind me enemyInFOV = qtrue; } - if ( (enemyDist < (128*128)&&enemyInFOV) || !TIMER_Done( NPCS.NPC, "flameTime" ) ) - {//flamethrower - Boba_DoFlameThrower( NPCS.NPC ); + if ((enemyDist < (128 * 128) && enemyInFOV) || !TIMER_Done(NPCS.NPC, "flameTime")) { // flamethrower + Boba_DoFlameThrower(NPCS.NPC); enemyCS = qfalse; shoot = qfalse; NPCS.NPCInfo->enemyLastSeenTime = level.time; - NPCS.ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); - } - else if ( enemyDist < MIN_ROCKET_DIST_SQUARED )//128 - {//enemy within 128 - if ( (NPCS.NPC->client->ps.weapon == WP_FLECHETTE || NPCS.NPC->client->ps.weapon == WP_REPEATER) && - (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + NPCS.ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); + } else if (enemyDist < MIN_ROCKET_DIST_SQUARED) // 128 + { // enemy within 128 + if ((NPCS.NPC->client->ps.weapon == WP_FLECHETTE || NPCS.NPC->client->ps.weapon == WP_REPEATER) && + (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... + // FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPCS.NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( !(NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPCS.NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (!(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //can we see our target? - if ( TIMER_Done( NPCS.NPC, "nextAttackDelay" ) && TIMER_Done( NPCS.NPC, "flameTime" ) ) - { - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { + // can we see our target? + if (TIMER_Done(NPCS.NPC, "nextAttackDelay") && TIMER_Done(NPCS.NPC, "flameTime")) { + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { NPCS.NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - } - else - {//can we shoot our target? - if ( (NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPCS.NPC->client->ps.weapon == WP_FLECHETTE && (NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist < MIN_ROCKET_DIST_SQUARED )//128*128 + if (NPCS.NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + } else { // can we shoot our target? + if ((NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || + (NPCS.NPC->client->ps.weapon == WP_FLECHETTE && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE))) && + enemyDist < MIN_ROCKET_DIST_SQUARED) // 128*128 { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else if ( enemyInFOV ) - {//if enemy is FOV, go ahead and check for shooting - int hit = NPC_ShotEntity( NPCS.NPC->enemy, impactPos ); + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else if (enemyInFOV) { // if enemy is FOV, go ahead and check for shooting + int hit = NPC_ShotEntity(NPCS.NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->r.svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPCS.NPC->s.weapon == WP_EMPLACED_GUN) ) ) - {//can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && + ((hitEnt->r.svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || + NPCS.NPC->s.weapon == WP_EMPLACED_GUN))) { // can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced + // gun), so shoot anyway enemyCS = qtrue; - //NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - //NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + // NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + // NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } - } - else - { - enemyCS = qfalse;//not true, but should stop us from firing + } else { + enemyCS = qfalse; // not true, but should stop us from firing } } - } - else if ( trap->InPVS( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - { + } else if (trap->InPVS(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { NPCS.NPCInfo->enemyLastSeenTime = level.time; - //NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + // NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy } - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - { + if (NPCS.NPC->client->ps.weapon == WP_NONE) { shoot = qfalse; - } - else - { - if ( enemyCS ) - { + } else { + if (enemyCS) { shoot = qtrue; } } - if ( !enemyCS ) - {//if have a clear shot, always try - //See if we should continue to fire on their last position - //!TIMER_Done( NPC, "stick" ) || - if ( !hitAlly //we're not going to hit an ally - && enemyInFOV //enemy is in our FOV //FIXME: or we don't have a clear LOS? - && NPCS.NPCInfo->enemyLastSeenTime > 0 )//we've seen the enemy + if (!enemyCS) { // if have a clear shot, always try + // See if we should continue to fire on their last position + //! TIMER_Done( NPC, "stick" ) || + if (!hitAlly // we're not going to hit an ally + && enemyInFOV // enemy is in our FOV //FIXME: or we don't have a clear LOS? + && NPCS.NPCInfo->enemyLastSeenTime > 0) // we've seen the enemy { - if ( level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000 )//we have seem the enemy in the last 10 seconds + if (level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000) // we have seem the enemy in the last 10 seconds { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; float distThreshold; float dist; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPCS.NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - trap->Trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPCS.NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + trap->Trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - distThreshold = 16384/*128*128*/;//default - switch ( NPCS.NPC->s.weapon ) - { + // see if impact would be too close to me + distThreshold = 16384 /*128*128*/; // default + switch (NPCS.NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - dist = DistanceSquared( impactPos, muzzle ); + dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000 || - (NPCS.NPCInfo->group && level.time - NPCS.NPCInfo->group->lastSeenEnemyTime > 5000 )) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - switch ( NPCS.NPC->s.weapon ) - { + } else if (level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000 || + (NPCS.NPCInfo->group && + level.time - NPCS.NPCInfo->group->lastSeenEnemyTime > 5000)) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + switch (NPCS.NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 262144/*512*512*/; + distThreshold = 262144 /*512*512*/; break; case WP_REPEATER: - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } break; default: break; } - dist = DistanceSquared( impactPos, NPCS.NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCS.NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCS.NPCInfo->desiredYaw = angles[YAW]; - NPCS.NPCInfo->desiredPitch = angles[PITCH]; + NPCS.NPCInfo->desiredYaw = angles[YAW]; + NPCS.NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; } @@ -764,99 +648,74 @@ void Boba_FireDecide( void ) } } - //FIXME: don't shoot right away! - if ( NPCS.NPC->client->ps.weaponTime > 0 ) - { - if ( NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { - if ( !enemyLOS || !enemyCS ) - {//cancel it + // FIXME: don't shoot right away! + if (NPCS.NPC->client->ps.weaponTime > 0) { + if (NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER) { + if (!enemyLOS || !enemyCS) { // cancel it NPCS.NPC->client->ps.weaponTime = 0; - } - else - {//delay our next attempt - TIMER_Set( NPCS.NPC, "nextAttackDelay", Q_irand( 500, 1000 ) ); + } else { // delay our next attempt + TIMER_Set(NPCS.NPC, "nextAttackDelay", Q_irand(500, 1000)); } } - } - else if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPCS.NPC, "nextAttackDelay" ) ) - { - if( !(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + } else if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPCS.NPC, "nextAttackDelay")) { + if (!(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } - //NASTY - if ( NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER - && (NPCS.ucmd.buttons&BUTTON_ATTACK) - && !Q_irand( 0, 3 ) ) - {//every now and then, shoot a homing rocket + // NASTY + if (NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER && (NPCS.ucmd.buttons & BUTTON_ATTACK) && + !Q_irand(0, 3)) { // every now and then, shoot a homing rocket NPCS.ucmd.buttons &= ~BUTTON_ATTACK; NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; - NPCS.NPC->client->ps.weaponTime = Q_irand( 500, 1500 ); + NPCS.NPC->client->ps.weaponTime = Q_irand(500, 1500); } } } } } -void Jedi_Cloak( gentity_t *self ) -{ - if ( self ) - { +void Jedi_Cloak(gentity_t *self) { + if (self) { self->flags |= FL_NOTARGET; - if ( self->client ) - { - if ( !self->client->ps.powerups[PW_CLOAKED] ) - {//cloak + if (self->client) { + if (!self->client->ps.powerups[PW_CLOAKED]) { // cloak self->client->ps.powerups[PW_CLOAKED] = Q3_INFINITE; - //FIXME: debounce attacks? - //FIXME: temp sound - G_Sound( self, CHAN_ITEM, G_SoundIndex("sound/chars/shadowtrooper/cloak.wav") ); + // FIXME: debounce attacks? + // FIXME: temp sound + G_Sound(self, CHAN_ITEM, G_SoundIndex("sound/chars/shadowtrooper/cloak.wav")); } } } } -void Jedi_Decloak( gentity_t *self ) -{ - if ( self ) - { +void Jedi_Decloak(gentity_t *self) { + if (self) { self->flags &= ~FL_NOTARGET; - if ( self->client ) - { - if ( self->client->ps.powerups[PW_CLOAKED] ) - {//Uncloak + if (self->client) { + if (self->client->ps.powerups[PW_CLOAKED]) { // Uncloak self->client->ps.powerups[PW_CLOAKED] = 0; - G_Sound( self, CHAN_ITEM, G_SoundIndex("sound/chars/shadowtrooper/decloak.wav") ); + G_Sound(self, CHAN_ITEM, G_SoundIndex("sound/chars/shadowtrooper/decloak.wav")); } } } } -void Jedi_CheckCloak( void ) -{ - if ( NPCS.NPC && NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - { - if ( !NPCS.NPC->client->ps.saberHolstered || - NPCS.NPC->health <= 0 || - NPCS.NPC->client->ps.saberInFlight || - // (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) || - // (NPC->client->ps.eFlags&EF_FORCE_DRAINED) || - NPCS.NPC->painDebounceTime > level.time ) - {//can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped - Jedi_Decloak( NPCS.NPC ); - } - else if ( NPCS.NPC->health > 0 - && !NPCS.NPC->client->ps.saberInFlight - // && !(NPC->client->ps.eFlags&EF_FORCE_GRIPPED) - // && !(NPC->client->ps.eFlags&EF_FORCE_DRAINED) - && NPCS.NPC->painDebounceTime < level.time ) - {//still alive, have saber in hand, not taking pain and not being gripped - Jedi_Cloak( NPCS.NPC ); +void Jedi_CheckCloak(void) { + if (NPCS.NPC && NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_SHADOWTROOPER) { + if (!NPCS.NPC->client->ps.saberHolstered || NPCS.NPC->health <= 0 || NPCS.NPC->client->ps.saberInFlight || + // (NPC->client->ps.eFlags&EF_FORCE_GRIPPED) || + // (NPC->client->ps.eFlags&EF_FORCE_DRAINED) || + NPCS.NPC->painDebounceTime > level.time) { // can't be cloaked if saber is on, or dead or saber in flight or taking pain or being gripped + Jedi_Decloak(NPCS.NPC); + } else if (NPCS.NPC->health > 0 && + !NPCS.NPC->client->ps.saberInFlight + // && !(NPC->client->ps.eFlags&EF_FORCE_GRIPPED) + // && !(NPC->client->ps.eFlags&EF_FORCE_DRAINED) + && NPCS.NPC->painDebounceTime < level.time) { // still alive, have saber in hand, not taking pain and not being gripped + Jedi_Cloak(NPCS.NPC); } } } @@ -865,115 +724,95 @@ void Jedi_CheckCloak( void ) AGGRESSION ========================================================================================== */ -static void Jedi_Aggression( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +static void Jedi_Aggression(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == NPCTEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == NPCTEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive - if ( self->client->NPC_class == CLASS_DESANN ) - { + } else { // bad guys are more aggressive + if (self->client->NPC_class == CLASS_DESANN) { upper_threshold = 20; lower_threshold = 5; - } - else - { + } else { upper_threshold = 10; lower_threshold = 3; } } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } - //Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); + // Com_Printf( "(%d) %s agg %d change: %d\n", level.time, self->NPC_type, self->NPC->stats.aggression, change ); } -static void Jedi_AggressionErosion( int amt ) -{ - if ( TIMER_Done( NPCS.NPC, "roamTime" ) ) - {//the longer we're not alerted and have no enemy, the more our aggression goes down - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 2000, 5000 ) ); - Jedi_Aggression( NPCS.NPC, amt ); +static void Jedi_AggressionErosion(int amt) { + if (TIMER_Done(NPCS.NPC, "roamTime")) { // the longer we're not alerted and have no enemy, the more our aggression goes down + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(2000, 5000)); + Jedi_Aggression(NPCS.NPC, amt); } - if ( NPCS.NPCInfo->stats.aggression < 4 || (NPCS.NPCInfo->stats.aggression < 6&&NPCS.NPC->client->NPC_class == CLASS_DESANN)) - {//turn off the saber - WP_DeactivateSaber( NPCS.NPC, qfalse ); + if (NPCS.NPCInfo->stats.aggression < 4 || (NPCS.NPCInfo->stats.aggression < 6 && NPCS.NPC->client->NPC_class == CLASS_DESANN)) { // turn off the saber + WP_DeactivateSaber(NPCS.NPC, qfalse); } } -void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ) -{ +void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy) { float healthAggression; float weaponAggression; int newAggression; - switch( enemy->s.weapon ) - { + switch (enemy->s.weapon) { case WP_SABER: - healthAggression = (float)self->health/200.0f*6.0f; - weaponAggression = 7;//go after him + healthAggression = (float)self->health / 200.0f * 6.0f; + weaponAggression = 7; // go after him break; case WP_BLASTER: - if ( DistanceSquared( self->r.currentOrigin, enemy->r.currentOrigin ) < 65536 )//256 squared - { - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 8;//go after him - } - else + if (DistanceSquared(self->r.currentOrigin, enemy->r.currentOrigin) < 65536) // 256 squared { - healthAggression = 8.0f - ((float)self->health/200.0f*8.0f); - weaponAggression = 2;//hang back for a second + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 8; // go after him + } else { + healthAggression = 8.0f - ((float)self->health / 200.0f * 8.0f); + weaponAggression = 2; // hang back for a second } break; default: - healthAggression = (float)self->health/200.0f*8.0f; - weaponAggression = 6;//approach + healthAggression = (float)self->health / 200.0f * 8.0f; + weaponAggression = 6; // approach break; } - //Average these with current aggression - newAggression = ceil( (healthAggression + weaponAggression + (float)self->NPC->stats.aggression )/3.0f); - //Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); - Jedi_Aggression( self, newAggression - self->NPC->stats.aggression ); + // Average these with current aggression + newAggression = ceil((healthAggression + weaponAggression + (float)self->NPC->stats.aggression) / 3.0f); + // Com_Printf( "(%d) new agg %d - new enemy\n", level.time, newAggression ); + Jedi_Aggression(self, newAggression - self->NPC->stats.aggression); - //don't taunt right away - TIMER_Set( self, "chatter", Q_irand( 4000, 7000 ) ); + // don't taunt right away + TIMER_Set(self, "chatter", Q_irand(4000, 7000)); } -static void Jedi_Rage( void ) -{ - Jedi_Aggression( NPCS.NPC, 10 - NPCS.NPCInfo->stats.aggression + Q_irand( -2, 2 ) ); - TIMER_Set( NPCS.NPC, "roamTime", 0 ); - TIMER_Set( NPCS.NPC, "chatter", 0 ); - TIMER_Set( NPCS.NPC, "walking", 0 ); - TIMER_Set( NPCS.NPC, "taunting", 0 ); - TIMER_Set( NPCS.NPC, "jumpChaseDebounce", 0 ); - TIMER_Set( NPCS.NPC, "movenone", 0 ); - TIMER_Set( NPCS.NPC, "movecenter", 0 ); - TIMER_Set( NPCS.NPC, "noturn", 0 ); - ForceRage( NPCS.NPC ); +static void Jedi_Rage(void) { + Jedi_Aggression(NPCS.NPC, 10 - NPCS.NPCInfo->stats.aggression + Q_irand(-2, 2)); + TIMER_Set(NPCS.NPC, "roamTime", 0); + TIMER_Set(NPCS.NPC, "chatter", 0); + TIMER_Set(NPCS.NPC, "walking", 0); + TIMER_Set(NPCS.NPC, "taunting", 0); + TIMER_Set(NPCS.NPC, "jumpChaseDebounce", 0); + TIMER_Set(NPCS.NPC, "movenone", 0); + TIMER_Set(NPCS.NPC, "movecenter", 0); + TIMER_Set(NPCS.NPC, "noturn", 0); + ForceRage(NPCS.NPC); } -void Jedi_RageStop( gentity_t *self ) -{ - if ( self->NPC ) - {//calm down and back off - TIMER_Set( self, "roamTime", 0 ); - Jedi_Aggression( self, Q_irand( -5, 0 ) ); +void Jedi_RageStop(gentity_t *self) { + if (self->NPC) { // calm down and back off + TIMER_Set(self, "roamTime", 0); + Jedi_Aggression(self, Q_irand(-5, 0)); } } /* @@ -982,34 +821,25 @@ SPEAKING ========================================================================================== */ -static qboolean Jedi_BattleTaunt( void ) -{ - if ( TIMER_Done( NPCS.NPC, "chatter" ) - && !Q_irand( 0, 3 ) - && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time ) - { +static qboolean Jedi_BattleTaunt(void) { + if (TIMER_Done(NPCS.NPC, "chatter") && !Q_irand(0, 3) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time) { int event = -1; - if ( NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER - && NPCS.NPC->enemy && NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//a jedi fighting a jedi - training - if ( NPCS.NPC->client->NPC_class == CLASS_JEDI && NPCS.NPCInfo->rank == RANK_COMMANDER ) - {//only trainer taunts + if (NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER && NPCS.NPC->enemy && NPCS.NPC->enemy->client && + NPCS.NPC->enemy->client->NPC_class == CLASS_JEDI) { // a jedi fighting a jedi - training + if (NPCS.NPC->client->NPC_class == CLASS_JEDI && NPCS.NPCInfo->rank == RANK_COMMANDER) { // only trainer taunts event = EV_TAUNT1; } + } else { // reborn or a jedi fighting an enemy + event = Q_irand(EV_TAUNT1, EV_TAUNT3); } - else - {//reborn or a jedi fighting an enemy - event = Q_irand( EV_TAUNT1, EV_TAUNT3 ); - } - if ( event != -1 ) - { - G_AddVoiceEvent( NPCS.NPC, event, 3000 ); + if (event != -1) { + G_AddVoiceEvent(NPCS.NPC, event, 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 6000; - TIMER_Set( NPCS.NPC, "chatter", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPCS.NPC, "chatter", Q_irand(5000, 10000)); - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->NPC && NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_JEDI ) - {//Have the enemy jedi say something in response when I'm done? + if (NPCS.NPC->enemy && NPCS.NPC->enemy->NPC && NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->client && + NPCS.NPC->enemy->client->NPC_class == CLASS_JEDI) { // Have the enemy jedi say something in response when I'm done? } return qtrue; } @@ -1022,86 +852,72 @@ static qboolean Jedi_BattleTaunt( void ) MOVEMENT ========================================================================================== */ -static qboolean Jedi_ClearPathToSpot( vec3_t dest, int impactEntNum ) -{ - trace_t trace; - vec3_t mins, start, end, dir; - float dist, drop, i; +static qboolean Jedi_ClearPathToSpot(vec3_t dest, int impactEntNum) { + trace_t trace; + vec3_t mins, start, end, dir; + float dist, drop, i; - //Offset the step height - VectorSet( mins, NPCS.NPC->r.mins[0], NPCS.NPC->r.mins[1], NPCS.NPC->r.mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, NPCS.NPC->r.mins[0], NPCS.NPC->r.mins[1], NPCS.NPC->r.mins[2] + STEPSIZE); - trap->Trace( &trace, NPCS.NPC->r.currentOrigin, mins, NPCS.NPC->r.maxs, dest, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, mins, NPCS.NPC->r.maxs, dest, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); - //Do a simple check - if ( trace.allsolid || trace.startsolid ) - {//inside solid + // Do a simple check + if (trace.allsolid || trace.startsolid) { // inside solid return qfalse; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum ) - {//hit what we're going after + if (trace.fraction < 1.0f) { // hit something + if (impactEntNum != ENTITYNUM_NONE && trace.entityNum == impactEntNum) { // hit what we're going after return qtrue; - } - else - { + } else { return qfalse; } } - //otherwise, clear path in a straight line. - //Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. - VectorSubtract( dest, NPCS.NPC->r.currentOrigin, dir ); - dist = VectorNormalize( dir ); - if ( dest[2] > NPCS.NPC->r.currentOrigin[2] ) - {//going up, check for steps + // otherwise, clear path in a straight line. + // Now at intervals of my size, go along the trace and trace down STEPSIZE to make sure there is a solid floor. + VectorSubtract(dest, NPCS.NPC->r.currentOrigin, dir); + dist = VectorNormalize(dir); + if (dest[2] > NPCS.NPC->r.currentOrigin[2]) { // going up, check for steps drop = STEPSIZE; - } - else - {//going down or level, check for moderate drops + } else { // going down or level, check for moderate drops drop = 64; } - for ( i = NPCS.NPC->r.maxs[0]*2; i < dist; i += NPCS.NPC->r.maxs[0]*2 ) - {//FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? - VectorMA( NPCS.NPC->r.currentOrigin, i, dir, start ); - VectorCopy( start, end ); + for (i = NPCS.NPC->r.maxs[0] * 2; i < dist; + i += NPCS.NPC->r.maxs[0] * 2) { // FIXME: does this check the last spot, too? We're assuming that should be okay since the enemy is there? + VectorMA(NPCS.NPC->r.currentOrigin, i, dir, start); + VectorCopy(start, end); end[2] -= drop; - trap->Trace( &trace, start, mins, NPCS.NPC->r.maxs, end, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 );//NPC->r.mins? - if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) - {//good to go + trap->Trace(&trace, start, mins, NPCS.NPC->r.maxs, end, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); // NPC->r.mins? + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) { // good to go continue; } - //no floor here! (or a long drop?) + // no floor here! (or a long drop?) return qfalse; } - //we made it! + // we made it! return qtrue; } -qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) -{ - vec3_t forward, right, testPos, angles, mins; - trace_t trace; - float fwdDist, rtDist; - float bottom_max = -STEPSIZE*4 - 1; - - if ( !forwardmove && !rightmove ) - {//not even moving - //Com_Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); +qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset) { + vec3_t forward, right, testPos, angles, mins; + trace_t trace; + float fwdDist, rtDist; + float bottom_max = -STEPSIZE * 4 - 1; + + if (!forwardmove && !rightmove) { // not even moving + // Com_Printf( "%d skipping walk-cliff check (not moving)\n", level.time ); return qtrue; } - if ( NPCS.ucmd.upmove > 0 || NPCS.NPC->client->ps.fd.forceJumpCharge ) - {//Going to jump - //Com_Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); + if (NPCS.ucmd.upmove > 0 || NPCS.NPC->client->ps.fd.forceJumpCharge) { // Going to jump + // Com_Printf( "%d skipping walk-cliff check (going to jump)\n", level.time ); return qtrue; } - if ( NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//in the air - //Com_Printf( "%d skipping walk-cliff check (in air)\n", level.time ); + if (NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // in the air + // Com_Printf( "%d skipping walk-cliff check (in air)\n", level.time ); return qtrue; } /* @@ -1117,81 +933,72 @@ qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ) } */ - //FIXME: to really do this right, we'd have to actually do a pmove to predict where we're - //going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows - //NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? - VectorCopy( NPCS.NPC->r.mins, mins ); + // FIXME: to really do this right, we'd have to actually do a pmove to predict where we're + // going to be... maybe this should be a flag and pmove handles it and sets a flag so AI knows + // NEXT frame? Or just incorporate current velocity, runspeed and possibly friction? + VectorCopy(NPCS.NPC->r.mins, mins); mins[2] += STEPSIZE; angles[PITCH] = angles[ROLL] = 0; - angles[YAW] = NPCS.NPC->client->ps.viewangles[YAW];//Add ucmd.angles[YAW]? - AngleVectors( angles, forward, right, NULL ); - fwdDist = ((float)forwardmove)/2.0f; - rtDist = ((float)rightmove)/2.0f; - VectorMA( NPCS.NPC->r.currentOrigin, fwdDist, forward, testPos ); - VectorMA( testPos, rtDist, right, testPos ); - trap->Trace( &trace, NPCS.NPC->r.currentOrigin, mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - if ( trace.allsolid || trace.startsolid ) - {//hmm, trace started inside this brush... how do we decide if we should continue? - //FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? - if ( reset ) - { + angles[YAW] = NPCS.NPC->client->ps.viewangles[YAW]; // Add ucmd.angles[YAW]? + AngleVectors(angles, forward, right, NULL); + fwdDist = ((float)forwardmove) / 2.0f; + rtDist = ((float)rightmove) / 2.0f; + VectorMA(NPCS.NPC->r.currentOrigin, fwdDist, forward, testPos); + VectorMA(testPos, rtDist, right, testPos); + trap->Trace(&trace, NPCS.NPC->r.currentOrigin, mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (trace.allsolid || trace.startsolid) { // hmm, trace started inside this brush... how do we decide if we should continue? + // FIXME: what do we do if we start INSIDE a CONTENTS_BOTCLIP? Try the trace again without that in the clipmask? + if (reset) { trace.fraction = 1.0f; } - VectorCopy( testPos, trace.endpos ); - //return qtrue; + VectorCopy(testPos, trace.endpos); + // return qtrue; } - if ( trace.fraction < 0.6 ) - {//Going to bump into something very close, don't move, just turn - if ( (NPCS.NPC->enemy && trace.entityNum == NPCS.NPC->enemy->s.number) || (NPCS.NPCInfo->goalEntity && trace.entityNum == NPCS.NPCInfo->goalEntity->s.number) ) - {//okay to bump into enemy or goal - //Com_Printf( "%d bump into enemy/goal okay\n", level.time ); + if (trace.fraction < 0.6) { // Going to bump into something very close, don't move, just turn + if ((NPCS.NPC->enemy && trace.entityNum == NPCS.NPC->enemy->s.number) || + (NPCS.NPCInfo->goalEntity && trace.entityNum == NPCS.NPCInfo->goalEntity->s.number)) { // okay to bump into enemy or goal + // Com_Printf( "%d bump into enemy/goal okay\n", level.time ); return qtrue; - } - else if ( reset ) - {//actually want to screw with the ucmd - //Com_Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); + } else if (reset) { // actually want to screw with the ucmd + // Com_Printf( "%d avoiding walk into wall (entnum %d)\n", level.time, trace.entityNum ); NPCS.ucmd.forwardmove = 0; NPCS.ucmd.rightmove = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } return qfalse; } - if ( NPCS.NPCInfo->goalEntity ) - { - if ( NPCS.NPCInfo->goalEntity->r.currentOrigin[2] < NPCS.NPC->r.currentOrigin[2] ) - {//goal is below me, okay to step off at least that far plus stepheight + if (NPCS.NPCInfo->goalEntity) { + if (NPCS.NPCInfo->goalEntity->r.currentOrigin[2] < + NPCS.NPC->r.currentOrigin[2]) { // goal is below me, okay to step off at least that far plus stepheight bottom_max += NPCS.NPCInfo->goalEntity->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; } } - VectorCopy( trace.endpos, testPos ); + VectorCopy(trace.endpos, testPos); testPos[2] += bottom_max; - trap->Trace( &trace, trace.endpos, mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); + trap->Trace(&trace, trace.endpos, mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); - //FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? - //OR: just put NPC clip brushes on these edges (still fall through when die) + // FIXME:Should we try to see if we can still get to our goal using the waypoint network from this trace.endpos? + // OR: just put NPC clip brushes on these edges (still fall through when die) - if ( trace.allsolid || trace.startsolid ) - {//Not going off a cliff - //Com_Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); + if (trace.allsolid || trace.startsolid) { // Not going off a cliff + // Com_Printf( "%d walk off cliff okay (droptrace in solid)\n", level.time ); return qtrue; } - if ( trace.fraction < 1.0 ) - {//Not going off a cliff - //FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... - //Com_Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); + if (trace.fraction < 1.0) { // Not going off a cliff + // FIXME: what if plane.normal is sloped? We'll slide off, not land... plus this doesn't account for slide-movement... + // Com_Printf( "%d walk off cliff okay will hit entnum %d at dropdist of %4.2f\n", level.time, trace.entityNum, (trace.fraction*bottom_max) ); return qtrue; } - //going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? - if ( reset ) - {//actually want to screw with the ucmd - //Com_Printf( "%d avoiding walk off cliff\n", level.time ); - NPCS.ucmd.forwardmove *= -1.0;//= 0; - NPCS.ucmd.rightmove *= -1.0;//= 0; - VectorScale( NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir ); + // going to fall at least bottom_max, don't move, just turn... is this bad, though? What if we want them to drop off? + if (reset) { // actually want to screw with the ucmd + // Com_Printf( "%d avoiding walk off cliff\n", level.time ); + NPCS.ucmd.forwardmove *= -1.0; //= 0; + NPCS.ucmd.rightmove *= -1.0; //= 0; + VectorScale(NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir); } return qfalse; } @@ -1201,9 +1008,8 @@ Jedi_HoldPosition ------------------------- */ -static void Jedi_HoldPosition( void ) -{ - //NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; +static void Jedi_HoldPosition(void) { + // NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; NPCS.NPCInfo->goalEntity = NULL; /* @@ -1220,62 +1026,51 @@ Jedi_Move ------------------------- */ -static void Jedi_Move( gentity_t *goal, qboolean retreat ) -{ - qboolean moved; - navInfo_t info; +static void Jedi_Move(gentity_t *goal, qboolean retreat) { + qboolean moved; + navInfo_t info; NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = goal; - moved = NPC_MoveToGoal( qtrue ); + moved = NPC_MoveToGoal(qtrue); - //FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy - if ( retreat ) - {//FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? + // FIXME: temp retreat behavior- should really make this toward a safe spot or maybe to outflank enemy + if (retreat) { // FIXME: should we trace and make sure we can go this way? Or somehow let NPC_MoveToGoal know we want to retreat and have it handle it? NPCS.ucmd.forwardmove *= -1; NPCS.ucmd.rightmove *= -1; - VectorScale( NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir ); + VectorScale(NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir); } - //Get the move info - NAV_GetLastMove( &info ); + // Get the move info + NAV_GetLastMove(&info); - //If we hit our target, then stop and fire! - if ( ( info.flags & NIF_COLLISION ) && ( info.blocker == NPCS.NPC->enemy ) ) - { + // If we hit our target, then stop and fire! + if ((info.flags & NIF_COLLISION) && (info.blocker == NPCS.NPC->enemy)) { Jedi_HoldPosition(); } - //If our move failed, then reset - if ( moved == qfalse ) - { + // If our move failed, then reset + if (moved == qfalse) { Jedi_HoldPosition(); } } -static qboolean Jedi_Hunt( void ) -{ - //Com_Printf( "Hunting\n" ); - //if we're at all interested in fighting, go after him - if ( NPCS.NPCInfo->stats.aggression > 1 ) - {//approach enemy +static qboolean Jedi_Hunt(void) { + // Com_Printf( "Hunting\n" ); + // if we're at all interested in fighting, go after him + if (NPCS.NPCInfo->stats.aggression > 1) { // approach enemy NPCS.NPCInfo->combatMove = qtrue; - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; - } - else - { - if ( NPCS.NPCInfo->goalEntity == NULL ) - {//hunt + } else { + if (NPCS.NPCInfo->goalEntity == NULL) { // hunt NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } - //Jedi_Move( NPC->enemy, qfalse ); - if ( NPC_MoveToGoal( qfalse ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // Jedi_Move( NPC->enemy, qfalse ); + if (NPC_MoveToGoal(qfalse)) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } } @@ -1301,60 +1096,47 @@ static qboolean Jedi_Track( void ) } */ -static void Jedi_Retreat( void ) -{ - if ( !TIMER_Done( NPCS.NPC, "noRetreat" ) ) - {//don't actually move +static void Jedi_Retreat(void) { + if (!TIMER_Done(NPCS.NPC, "noRetreat")) { // don't actually move return; } - //FIXME: when retreating, we should probably see if we can retreat - //in the direction we want. If not...? Evade? - //Com_Printf( "Retreating\n" ); - Jedi_Move( NPCS.NPC->enemy, qtrue ); + // FIXME: when retreating, we should probably see if we can retreat + // in the direction we want. If not...? Evade? + // Com_Printf( "Retreating\n" ); + Jedi_Move(NPCS.NPC->enemy, qtrue); } -static void Jedi_Advance( void ) -{ - if ( !NPCS.NPC->client->ps.saberInFlight ) - { - //NPC->client->ps.SaberActivate(); +static void Jedi_Advance(void) { + if (!NPCS.NPC->client->ps.saberInFlight) { + // NPC->client->ps.SaberActivate(); WP_ActivateSaber(NPCS.NPC); } - //Com_Printf( "Advancing\n" ); - Jedi_Move( NPCS.NPC->enemy, qfalse ); + // Com_Printf( "Advancing\n" ); + Jedi_Move(NPCS.NPC->enemy, qfalse); - //TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( NPC, "duck", 0 ); + // TIMER_Set( NPC, "roamTime", Q_irand( 2000, 4000 ) ); + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) ); + // TIMER_Set( NPC, "duck", 0 ); } -static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) -{ - if ( !self || !self->client ) - { +static void Jedi_AdjustSaberAnimLevel(gentity_t *self, int newLevel) { + if (!self || !self->client) { return; } - //FIXME: each NPC shold have a unique pattern of behavior for the order in which they - if ( self->client->NPC_class == CLASS_TAVION ) - {//special attacks + // FIXME: each NPC shold have a unique pattern of behavior for the order in which they + if (self->client->NPC_class == CLASS_TAVION) { // special attacks self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_5; return; - } - else if ( self->client->NPC_class == CLASS_DESANN ) - {//special attacks + } else if (self->client->NPC_class == CLASS_DESANN) { // special attacks self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_4; return; } - if ( self->client->playerTeam == NPCTEAM_ENEMY ) - { - if ( self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG ) - {//grunt and fencer always uses quick attacks + if (self->client->playerTeam == NPCTEAM_ENEMY) { + if (self->NPC->rank == RANK_CIVILIAN || self->NPC->rank == RANK_LT_JG) { // grunt and fencer always uses quick attacks self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; return; } - if ( self->NPC->rank == RANK_CREWMAN - || self->NPC->rank == RANK_ENSIGN ) - {//acrobat & force-users always use medium attacks + if (self->NPC->rank == RANK_CREWMAN || self->NPC->rank == RANK_ENSIGN) { // acrobat & force-users always use medium attacks self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_2; return; } @@ -1366,544 +1148,396 @@ static void Jedi_AdjustSaberAnimLevel( gentity_t *self, int newLevel ) } */ } - //use the different attacks, how often they switch and under what circumstances - if ( newLevel > self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] ) - {//cap it + // use the different attacks, how often they switch and under what circumstances + if (newLevel > self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { // cap it self->client->ps.fd.saberAnimLevel = self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]; - } - else if ( newLevel < FORCE_LEVEL_1 ) - { + } else if (newLevel < FORCE_LEVEL_1) { self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; - } - else - {//go ahead and set it + } else { // go ahead and set it self->client->ps.fd.saberAnimLevel = newLevel; } - if ( d_JediAI.integer ) - { - switch ( self->client->ps.fd.saberAnimLevel ) - { + if (d_JediAI.integer) { + switch (self->client->ps.fd.saberAnimLevel) { case FORCE_LEVEL_1: - Com_Printf( S_COLOR_GREEN"%s Saber Attack Set: fast\n", self->NPC_type ); + Com_Printf(S_COLOR_GREEN "%s Saber Attack Set: fast\n", self->NPC_type); break; case FORCE_LEVEL_2: - Com_Printf( S_COLOR_YELLOW"%s Saber Attack Set: medium\n", self->NPC_type ); + Com_Printf(S_COLOR_YELLOW "%s Saber Attack Set: medium\n", self->NPC_type); break; case FORCE_LEVEL_3: - Com_Printf( S_COLOR_RED"%s Saber Attack Set: strong\n", self->NPC_type ); + Com_Printf(S_COLOR_RED "%s Saber Attack Set: strong\n", self->NPC_type); break; } } } -static void Jedi_CheckDecreaseSaberAnimLevel( void ) -{ - if ( !NPCS.NPC->client->ps.weaponTime && !(NPCS.ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//not attacking - if ( TIMER_Done( NPCS.NPC, "saberLevelDebounce" ) && !Q_irand( 0, 10 ) ) - { - //Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.fd.saberAnimLevel-1) );//drop - Jedi_AdjustSaberAnimLevel( NPCS.NPC, Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ));//random - TIMER_Set( NPCS.NPC, "saberLevelDebounce", Q_irand( 3000, 10000 ) ); +static void Jedi_CheckDecreaseSaberAnimLevel(void) { + if (!NPCS.NPC->client->ps.weaponTime && !(NPCS.ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // not attacking + if (TIMER_Done(NPCS.NPC, "saberLevelDebounce") && !Q_irand(0, 10)) { + // Jedi_AdjustSaberAnimLevel( NPC, (NPC->client->ps.fd.saberAnimLevel-1) );//drop + Jedi_AdjustSaberAnimLevel(NPCS.NPC, Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3)); // random + TIMER_Set(NPCS.NPC, "saberLevelDebounce", Q_irand(3000, 10000)); } - } - else - { - TIMER_Set( NPCS.NPC, "saberLevelDebounce", Q_irand( 1000, 5000 ) ); + } else { + TIMER_Set(NPCS.NPC, "saberLevelDebounce", Q_irand(1000, 5000)); } } -extern void ForceDrain( gentity_t *self ); -static void Jedi_CombatDistance( int enemy_dist ) -{//FIXME: for many of these checks, what we really want is horizontal distance to enemy - if ( NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//when gripping, don't move +extern void ForceDrain(gentity_t *self); +static void Jedi_CombatDistance(int enemy_dist) { // FIXME: for many of these checks, what we really want is horizontal distance to enemy + if (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_GRIP) && + NPCS.NPC->client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // when gripping, don't move return; - } - else if ( !TIMER_Done( NPCS.NPC, "gripping" ) ) - {//stopped gripping, clear timers just in case - TIMER_Set( NPCS.NPC, "gripping", -level.time ); - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 0, 1000 ) ); + } else if (!TIMER_Done(NPCS.NPC, "gripping")) { // stopped gripping, clear timers just in case + TIMER_Set(NPCS.NPC, "gripping", -level.time); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(0, 1000)); } - if ( Jedi_CultistDestroyer( NPCS.NPC ) ) - { + if (Jedi_CultistDestroyer(NPCS.NPC)) { Jedi_Advance(); NPCS.NPC->client->ps.speed = NPCS.NPCInfo->stats.runSpeed; NPCS.ucmd.buttons &= ~BUTTON_WALKING; } - if ( NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 ) - {//when draining, don't move + if (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_DRAIN) && + NPCS.NPC->client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1) { // when draining, don't move return; - } - else if ( !TIMER_Done( NPCS.NPC, "draining" ) ) - {//stopped draining, clear timers just in case - TIMER_Set( NPCS.NPC, "draining", -level.time ); - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 0, 1000 ) ); + } else if (!TIMER_Done(NPCS.NPC, "draining")) { // stopped draining, clear timers just in case + TIMER_Set(NPCS.NPC, "draining", -level.time); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(0, 1000)); } - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( !TIMER_Done( NPCS.NPC, "flameTime" ) ) - { - if ( enemy_dist > 50 ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + if (!TIMER_Done(NPCS.NPC, "flameTime")) { + if (enemy_dist > 50) { Jedi_Advance(); - } - else if ( enemy_dist <= 0 ) - { + } else if (enemy_dist <= 0) { Jedi_Retreat(); } - } - else if ( enemy_dist < 200 ) - { + } else if (enemy_dist < 200) { Jedi_Retreat(); - } - else if ( enemy_dist > 1024 ) - { + } else if (enemy_dist > 1024) { Jedi_Advance(); } - } - else if ( NPCS.NPC->client->ps.saberInFlight && - !PM_SaberInBrokenParry( NPCS.NPC->client->ps.saberMove ) - && NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//maintain distance - if ( enemy_dist < NPCS.NPC->client->ps.saberEntityDist ) - { + } else if (NPCS.NPC->client->ps.saberInFlight && !PM_SaberInBrokenParry(NPCS.NPC->client->ps.saberMove) && + NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // maintain distance + if (enemy_dist < NPCS.NPC->client->ps.saberEntityDist) { Jedi_Retreat(); - } - else if ( enemy_dist > NPCS.NPC->client->ps.saberEntityDist && enemy_dist > 100 ) - { + } else if (enemy_dist > NPCS.NPC->client->ps.saberEntityDist && enemy_dist > 100) { Jedi_Advance(); } - if ( NPCS.NPC->client->ps.weapon == WP_SABER //using saber - && NPCS.NPC->client->ps.saberEntityState == SES_LEAVING //not returning yet - && NPCS.NPC->client->ps.fd.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 //2nd or 3rd level lightsaber - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1 << FP_SPEED)) - && !(NPCS.NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//hold it out there + if (NPCS.NPC->client->ps.weapon == WP_SABER // using saber + && NPCS.NPC->client->ps.saberEntityState == SES_LEAVING // not returning yet + && NPCS.NPC->client->ps.fd.forcePowerLevel[FP_SABERTHROW] > FORCE_LEVEL_1 // 2nd or 3rd level lightsaber + && !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) && !(NPCS.NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // hold it out there NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; - //FIXME: time limit? + // FIXME: time limit? } - } - else if ( !TIMER_Done( NPCS.NPC, "taunting" ) ) - { - if ( enemy_dist <= 64 ) - {//he's getting too close + } else if (!TIMER_Done(NPCS.NPC, "taunting")) { + if (enemy_dist <= 64) { // he's getting too close NPCS.ucmd.buttons |= BUTTON_ATTACK; - if ( !NPCS.NPC->client->ps.saberInFlight ) - { + if (!NPCS.NPC->client->ps.saberInFlight) { WP_ActivateSaber(NPCS.NPC); } - TIMER_Set( NPCS.NPC, "taunting", -level.time ); + TIMER_Set(NPCS.NPC, "taunting", -level.time); } - //else if ( NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoTimer < 2000 ) - else if (NPCS.NPC->client->ps.forceHandExtend == HANDEXTEND_JEDITAUNT && (NPCS.NPC->client->ps.forceHandExtendTime - level.time) < 200) - {//we're almost done with our special taunt - //FIXME: this doesn't always work, for some reason - if ( !NPCS.NPC->client->ps.saberInFlight ) - { + // else if ( NPC->client->ps.torsoAnim == BOTH_GESTURE1 && NPC->client->ps.torsoTimer < 2000 ) + else if (NPCS.NPC->client->ps.forceHandExtend == HANDEXTEND_JEDITAUNT && + (NPCS.NPC->client->ps.forceHandExtendTime - level.time) < 200) { // we're almost done with our special taunt + // FIXME: this doesn't always work, for some reason + if (!NPCS.NPC->client->ps.saberInFlight) { WP_ActivateSaber(NPCS.NPC); } } - } - else if ( NPCS.NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage - if ( enemy_dist > 0 ) - {//get closer so we can hit! + } else if (NPCS.NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage + if (enemy_dist > 0) { // get closer so we can hit! Jedi_Advance(); } - if ( enemy_dist > 128 ) - {//lost 'em + if (enemy_dist > 128) { // lost 'em NPCS.NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - if ( NPCS.NPC->enemy->painDebounceTime + 2000 < level.time ) - {//the window of opportunity is gone + if (NPCS.NPC->enemy->painDebounceTime + 2000 < level.time) { // the window of opportunity is gone NPCS.NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; } - //don't strafe? - TIMER_Set( NPCS.NPC, "strafeLeft", -1 ); - TIMER_Set( NPCS.NPC, "strafeRight", -1 ); - } - else if ( NPCS.NPC->enemy->client - && NPCS.NPC->enemy->s.weapon == WP_SABER - && NPCS.NPC->enemy->client->ps.saberLockTime > level.time - && NPCS.NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not - if ( enemy_dist < 64 ) - {//FIXME: maybe just pick another enemy? + // don't strafe? + TIMER_Set(NPCS.NPC, "strafeLeft", -1); + TIMER_Set(NPCS.NPC, "strafeRight", -1); + } else if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->client->ps.saberLockTime > level.time && + NPCS.NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not + if (enemy_dist < 64) { // FIXME: maybe just pick another enemy? Jedi_Retreat(); } } - //rwwFIXMEFIXME: Give them the ability to do this again (turret needs to be fixed up to allow it) - else if ( enemy_dist <= 64 - && ((NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE)||(!Q_stricmp("Yoda",NPCS.NPC->NPC_type)&&!Q_irand(0,10))) ) - {//can't use saber and they're in striking range - if ( !Q_irand( 0, 5 ) && InFront( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.2f ) ) - { - if ( ((NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE)||NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health > NPCS.NPC->client->pers.maxHealth*0.25f)//lost over 1/4 of our health or not firing - && NPCS.NPC->client->ps.fd.forcePowersKnown&(1<scriptFlags & SCF_DONT_FIRE) || + (!Q_stricmp("Yoda", NPCS.NPC->NPC_type) && !Q_irand(0, 10)))) { // can't use saber and they're in striking range + if (!Q_irand(0, 5) && InFront(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.2f)) { + if (((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) || + NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health > NPCS.NPC->client->pers.maxHealth * 0.25f) // lost over 1/4 of our health or not firing + && NPCS.NPC->client->ps.fd.forcePowersKnown & (1 << FP_DRAIN) // know how to drain + && WP_ForcePowerAvailable(NPCS.NPC, FP_DRAIN, 20) // have enough power + && !Q_irand(0, 2)) { // drain + TIMER_Set(NPCS.NPC, "draining", 3000); + TIMER_Set(NPCS.NPC, "attackDelay", 3000); Jedi_Advance(); return; - } - else - { - ForceThrow( NPCS.NPC, qfalse ); + } else { + ForceThrow(NPCS.NPC, qfalse); } } Jedi_Retreat(); - } - else if ( enemy_dist <= 64 - && NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health > NPCS.NPC->client->pers.maxHealth*0.25f//lost over 1/4 of our health - && NPCS.NPC->client->ps.fd.forcePowersKnown&(1<enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.2f ) ) - { - TIMER_Set( NPCS.NPC, "draining", 3000 ); - TIMER_Set( NPCS.NPC, "attackDelay", 3000 ); + } else if (enemy_dist <= 64 && NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health > NPCS.NPC->client->pers.maxHealth * 0.25f // lost over 1/4 of our health + && NPCS.NPC->client->ps.fd.forcePowersKnown & (1 << FP_DRAIN) // know how to drain + && WP_ForcePowerAvailable(NPCS.NPC, FP_DRAIN, 20) // have enough power + && !Q_irand(0, 10) && InFront(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, 0.2f)) { + TIMER_Set(NPCS.NPC, "draining", 3000); + TIMER_Set(NPCS.NPC, "attackDelay", 3000); Jedi_Advance(); return; - } - else if ( enemy_dist <= -16 ) - {//we're too damn close! + } else if (enemy_dist <= -16) { // we're too damn close! Jedi_Retreat(); - } - else if ( enemy_dist <= 0 ) - {//we're within striking range - //if we are attacking, see if we should stop - if ( NPCS.NPCInfo->stats.aggression < 4 ) - {//back off and defend + } else if (enemy_dist <= 0) { // we're within striking range + // if we are attacking, see if we should stop + if (NPCS.NPCInfo->stats.aggression < 4) { // back off and defend Jedi_Retreat(); } - } - else if ( enemy_dist > 256 ) - {//we're way out of range + } else if (enemy_dist > 256) { // we're way out of range qboolean usedForce = qfalse; - if ( NPCS.NPCInfo->stats.aggression < Q_irand( 0, 20 ) - && NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth*0.75f - && !Q_irand( 0, 2 ) ) - { - if ( (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<stats.aggression < Q_irand(0, 20) && NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth * 0.75f && !Q_irand(0, 2)) { + if ((NPCS.NPC->client->ps.fd.forcePowersKnown & (1 << FP_HEAL)) != 0 && (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_HEAL)) == 0 && + Q_irand(0, 1)) { + ForceHeal(NPCS.NPC); usedForce = qtrue; - //FIXME: check level of heal and know not to move or attack when healing - } - else if ( (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersKnown & (1 << FP_PROTECT)) != 0 && + (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_PROTECT)) == 0 && Q_irand(0, 1)) { + ForceProtect(NPCS.NPC); usedForce = qtrue; - } - else if ( (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersKnown & (1 << FP_ABSORB)) != 0 && + (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_ABSORB)) == 0 && Q_irand(0, 1)) { + ForceAbsorb(NPCS.NPC); usedForce = qtrue; - } - else if ( (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersKnown & (1 << FP_RAGE)) != 0 && (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) == 0 && + Q_irand(0, 1)) { Jedi_Rage(); usedForce = qtrue; } - //FIXME: what about things like mind tricks and force sight? + // FIXME: what about things like mind tricks and force sight? } - if ( enemy_dist > 384 ) - {//FIXME: check for enemy facing away and/or moving away - if ( !Q_irand( 0, 10 ) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time ) - { - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_JCHASE1, EV_JCHASE3 ), 3000 ); + if (enemy_dist > 384) { // FIXME: check for enemy facing away and/or moving away + if (!Q_irand(0, 10) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time) { + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_JCHASE1, EV_JCHASE3), 3000); } jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - //Unless we're totally hiding, go after him - if ( NPCS.NPCInfo->stats.aggression > 0 ) - {//approach enemy - if ( !usedForce ) - { + // Unless we're totally hiding, go after him + if (NPCS.NPCInfo->stats.aggression > 0) { // approach enemy + if (!usedForce) { Jedi_Advance(); } } } - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - else if ( enemy_dist > 50 )//FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax - {//we're out of striking range and we are allowed to attack - //first, check some tactical force power decisions - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client && (NPCS.NPC->enemy->client->ps.fd.forceGripBeingGripped > level.time) ) - {//They're being gripped, rush them! - if ( NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPCS.NPC, "parryTime" ) || NPCS.NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + else if (enemy_dist > 50) // FIXME: not hardcoded- base on our reach (modelScale?) and saberLengthMax + { // we're out of striking range and we are allowed to attack + // first, check some tactical force power decisions + if (NPCS.NPC->enemy && NPCS.NPC->enemy->client && + (NPCS.NPC->enemy->client->ps.fd.forceGripBeingGripped > level.time)) { // They're being gripped, rush them! + if (NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPCS.NPC, "parryTime") || NPCS.NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - if ( NPCS.NPCInfo->rank >= RANK_LT_JG - && !Q_irand( 0, 5 ) - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1 << FP_SPEED)) - && !(NPCS.NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + if (NPCS.NPCInfo->rank >= RANK_LT_JG && !Q_irand(0, 5) && !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) && + !(NPCS.NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; } - } - else if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client && //valid enemy - NPCS.NPC->enemy->client->ps.saberInFlight && /*NPC->enemy->client->ps.saber[0].Active()*/ NPCS.NPC->enemy->client->ps.saberEntityNum && //enemy throwing saber - NPCS.NPC->client->ps.weaponTime <= 0 && //I'm not busy - WP_ForcePowerAvailable( NPCS.NPC, FP_GRIP, 0 ) && //I can use the power - !Q_irand( 0, 10 ) && //don't do it all the time, averages to 1 check a second - Q_irand( 0, 6 ) < g_npcspskill.integer && //more likely on harder diff - Q_irand( RANK_CIVILIAN, RANK_CAPTAIN ) < NPCS.NPCInfo->rank )//more likely against harder enemies - {//They're throwing their saber, grip them! - //taunt - if ( TIMER_Done( NPCS.NPC, "chatter" ) && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); + } else if (NPCS.NPC->enemy && NPCS.NPC->enemy->client && // valid enemy + NPCS.NPC->enemy->client->ps.saberInFlight && + /*NPC->enemy->client->ps.saber[0].Active()*/ NPCS.NPC->enemy->client->ps.saberEntityNum && // enemy throwing saber + NPCS.NPC->client->ps.weaponTime <= 0 && // I'm not busy + WP_ForcePowerAvailable(NPCS.NPC, FP_GRIP, 0) && // I can use the power + !Q_irand(0, 10) && // don't do it all the time, averages to 1 check a second + Q_irand(0, 6) < g_npcspskill.integer && // more likely on harder diff + Q_irand(RANK_CIVILIAN, RANK_CAPTAIN) < NPCS.NPCInfo->rank) // more likely against harder enemies + { // They're throwing their saber, grip them! + // taunt + if (TIMER_Done(NPCS.NPC, "chatter") && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && + NPCS.NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - TIMER_Set( NPCS.NPC, "chatter", 3000 ); + TIMER_Set(NPCS.NPC, "chatter", 3000); } - //grip - TIMER_Set( NPCS.NPC, "gripping", 3000 ); - TIMER_Set( NPCS.NPC, "attackDelay", 3000 ); - } - else - { + // grip + TIMER_Set(NPCS.NPC, "gripping", 3000); + TIMER_Set(NPCS.NPC, "attackDelay", 3000); + } else { int chanceScale; - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client && (NPCS.NPC->enemy->client->ps.fd.forcePowersActive&(1<enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( TIMER_Done( NPCS.NPC, "parryTime" ) || NPCS.NPCInfo->rank > RANK_LT ) - {//not parrying - if ( enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + if (NPCS.NPC->enemy && NPCS.NPC->enemy->client && + (NPCS.NPC->enemy->client->ps.fd.forcePowersActive & + (1 << FP_GRIP))) { // They're choking someone, probably an ally, run at them and do some sort of attack + if (NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (TIMER_Done(NPCS.NPC, "parryTime") || NPCS.NPCInfo->rank > RANK_LT) { // not parrying + if (enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } } chanceScale = 0; - if ( NPCS.NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",NPCS.NPC->NPC_type) ) - { + if (NPCS.NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", NPCS.NPC->NPC_type)) { chanceScale = 1; - } - else if ( NPCS.NPCInfo->rank == RANK_ENSIGN ) - { + } else if (NPCS.NPCInfo->rank == RANK_ENSIGN) { chanceScale = 2; - } - else if ( NPCS.NPCInfo->rank >= RANK_LT_JG ) - { + } else if (NPCS.NPCInfo->rank >= RANK_LT_JG) { chanceScale = 5; } - if ( chanceScale - && (enemy_dist > Q_irand( 100, 200 ) || (NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) || (!Q_stricmp("Yoda",NPCS.NPC->NPC_type)&&!Q_irand(0,3)) ) - && enemy_dist < 500 - && (Q_irand( 0, chanceScale*10 )<5 || (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->ps.weapon != WP_SABER && !Q_irand( 0, chanceScale ) ) ) ) - {//else, randomly try some kind of attack every now and then - if ( ((NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && !Q_irand( 0, 1 )) || NPCS.NPC->s.weapon != WP_SABER ) - { - if ( WP_ForcePowerUsable( NPCS.NPC, FP_PULL ) && !Q_irand( 0, 2 ) ) - { - //force pull the guy to me! - //FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] - ForceThrow( NPCS.NPC, qtrue ); - //maybe strafe too? - TIMER_Set( NPCS.NPC, "duck", enemy_dist*3 ); - if ( Q_irand( 0, 1 ) ) - { + if (chanceScale && + (enemy_dist > Q_irand(100, 200) || (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) || (!Q_stricmp("Yoda", NPCS.NPC->NPC_type) && !Q_irand(0, 3))) && + enemy_dist < 500 && + (Q_irand(0, chanceScale * 10) < 5 || (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->ps.weapon != WP_SABER && + !Q_irand(0, chanceScale)))) { // else, randomly try some kind of attack every now and then + if (((NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && !Q_irand(0, 1)) || NPCS.NPC->s.weapon != WP_SABER) { + if (WP_ForcePowerUsable(NPCS.NPC, FP_PULL) && !Q_irand(0, 2)) { + // force pull the guy to me! + // FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] + ForceThrow(NPCS.NPC, qtrue); + // maybe strafe too? + TIMER_Set(NPCS.NPC, "duck", enemy_dist * 3); + if (Q_irand(0, 1)) { NPCS.ucmd.buttons |= BUTTON_ATTACK; } - } - else if ( (WP_ForcePowerUsable( NPCS.NPC, FP_LIGHTNING ) - && ((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) && Q_stricmp("cultist_lightning",NPCS.NPC->NPC_type))) || Q_irand( 0, 1 )) - { - ForceLightning( NPCS.NPC ); - if ( NPCS.NPC->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - { - NPCS.NPC->client->ps.weaponTime = Q_irand( 1000, 3000+(g_npcspskill.integer*500) ); - TIMER_Set( NPCS.NPC, "holdLightning", NPCS.NPC->client->ps.weaponTime ); + } else if ((WP_ForcePowerUsable(NPCS.NPC, FP_LIGHTNING) && + ((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) && Q_stricmp("cultist_lightning", NPCS.NPC->NPC_type))) || + Q_irand(0, 1)) { + ForceLightning(NPCS.NPC); + if (NPCS.NPC->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { + NPCS.NPC->client->ps.weaponTime = Q_irand(1000, 3000 + (g_npcspskill.integer * 500)); + TIMER_Set(NPCS.NPC, "holdLightning", NPCS.NPC->client->ps.weaponTime); } - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.weaponTime ); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.weaponTime); } - //rwwFIXMEFIXME: After new drain stuff from SP is in re-enable this. - else if ( (NPCS.NPC->health < NPCS.NPC->client->ps.stats[STAT_MAX_HEALTH] * 0.75f - && Q_irand( FORCE_LEVEL_0, NPCS.NPC->client->ps.fd.forcePowerLevel[FP_DRAIN] ) > FORCE_LEVEL_1 - && WP_ForcePowerUsable( NPCS.NPC, FP_DRAIN ) - && ((NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE)&&Q_stricmp("cultist_drain",NPCS.NPC->NPC_type))) || Q_irand( 0, 1 ) ) - { - ForceDrain( NPCS.NPC ); - NPCS.NPC->client->ps.weaponTime = Q_irand( 1000, 3000+(g_npcspskill.integer*500) ); - TIMER_Set( NPCS.NPC, "draining", NPCS.NPC->client->ps.weaponTime ); - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.weaponTime ); + // rwwFIXMEFIXME: After new drain stuff from SP is in re-enable this. + else if ((NPCS.NPC->health < NPCS.NPC->client->ps.stats[STAT_MAX_HEALTH] * 0.75f && + Q_irand(FORCE_LEVEL_0, NPCS.NPC->client->ps.fd.forcePowerLevel[FP_DRAIN]) > FORCE_LEVEL_1 && + WP_ForcePowerUsable(NPCS.NPC, FP_DRAIN) && + ((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) && Q_stricmp("cultist_drain", NPCS.NPC->NPC_type))) || + Q_irand(0, 1)) { + ForceDrain(NPCS.NPC); + NPCS.NPC->client->ps.weaponTime = Q_irand(1000, 3000 + (g_npcspskill.integer * 500)); + TIMER_Set(NPCS.NPC, "draining", NPCS.NPC->client->ps.weaponTime); + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPC->client->ps.weaponTime); + } else if (WP_ForcePowerUsable(NPCS.NPC, FP_GRIP) && NPCS.NPC->enemy && InFOV(NPCS.NPC->enemy, NPCS.NPC, 20, 30)) { + // taunt + if (TIMER_Done(NPCS.NPC, "chatter") && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && + NPCS.NPCInfo->blockedSpeechDebounceTime < level.time) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_TAUNT1, EV_TAUNT3), 3000); + jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; + TIMER_Set(NPCS.NPC, "chatter", 3000); } - else if ( WP_ForcePowerUsable( NPCS.NPC, FP_GRIP ) - && NPCS.NPC->enemy && InFOV( NPCS.NPC->enemy, NPCS.NPC, 20, 30 ) ) - { - //taunt - if ( TIMER_Done( NPCS.NPC, "chatter" ) && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_TAUNT1, EV_TAUNT3 ), 3000 ); - jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; - TIMER_Set( NPCS.NPC, "chatter", 3000 ); - } - //grip - TIMER_Set( NPCS.NPC, "gripping", 3000 ); - TIMER_Set( NPCS.NPC, "attackDelay", 3000 ); - } - else - { - if ( WP_ForcePowerUsable( NPCS.NPC, FP_SABERTHROW ) - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1 << FP_SPEED)) - && !(NPCS.NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + // grip + TIMER_Set(NPCS.NPC, "gripping", 3000); + TIMER_Set(NPCS.NPC, "attackDelay", 3000); + } else { + if (WP_ForcePowerUsable(NPCS.NPC, FP_SABERTHROW) && !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) && + !(NPCS.NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; } } - } - else - { - if ( NPCS.NPCInfo->rank >= RANK_LT_JG - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1 << FP_SPEED)) - && !(NPCS.NPC->client->ps.saberEventFlags&SEF_INWATER) )//saber not in water - {//throw saber + } else { + if (NPCS.NPCInfo->rank >= RANK_LT_JG && !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) && + !(NPCS.NPC->client->ps.saberEventFlags & SEF_INWATER)) // saber not in water + { // throw saber NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; } } } - //see if we should advance now - else if ( NPCS.NPCInfo->stats.aggression > 5 ) - {//approach enemy - if ( TIMER_Done( NPCS.NPC, "parryTime" ) || NPCS.NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPCS.NPC->enemy->client || NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance - if ( enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//far away or allowed to use saber + // see if we should advance now + else if (NPCS.NPCInfo->stats.aggression > 5) { // approach enemy + if (TIMER_Done(NPCS.NPC, "parryTime") || NPCS.NPCInfo->rank > RANK_LT) { // not parrying + if (!NPCS.NPC->enemy->client || NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance + if (enemy_dist > 200 || !(NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // far away or allowed to use saber Jedi_Advance(); } } } - } - else - {//maintain this distance? - //walk? + } else { // maintain this distance? + // walk? } } - } - else - {//we're not close enough to attack, but not far enough away to be safe - if ( NPCS.NPCInfo->stats.aggression < 4 ) - {//back off and defend + } else { // we're not close enough to attack, but not far enough away to be safe + if (NPCS.NPCInfo->stats.aggression < 4) { // back off and defend Jedi_Retreat(); - } - else if ( NPCS.NPCInfo->stats.aggression > 5 ) - {//try to get closer - if ( enemy_dist > 0 && !(NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE)) - {//we're allowed to use our lightsaber, get closer - if ( TIMER_Done( NPCS.NPC, "parryTime" ) || NPCS.NPCInfo->rank > RANK_LT ) - {//not parrying - if ( !NPCS.NPC->enemy->client || NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//they're on the ground, so advance + } else if (NPCS.NPCInfo->stats.aggression > 5) { // try to get closer + if (enemy_dist > 0 && !(NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // we're allowed to use our lightsaber, get closer + if (TIMER_Done(NPCS.NPC, "parryTime") || NPCS.NPCInfo->rank > RANK_LT) { // not parrying + if (!NPCS.NPC->enemy->client || NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // they're on the ground, so advance Jedi_Advance(); } } } - } - else - {//agression is 4 or 5... somewhere in the middle - //what do we do here? Nothing? - //Move forward and back? + } else { // agression is 4 or 5... somewhere in the middle + // what do we do here? Nothing? + // Move forward and back? } } - //if really really mad, rage! - if ( NPCS.NPCInfo->stats.aggression > Q_irand( 5, 15 ) - && NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth*0.75f - && !Q_irand( 0, 2 ) ) - { - if ( (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<stats.aggression > Q_irand(5, 15) && NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth * 0.75f && !Q_irand(0, 2)) { + if ((NPCS.NPC->client->ps.fd.forcePowersKnown & (1 << FP_RAGE)) != 0 && (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) == 0) { Jedi_Rage(); } } } -static qboolean Jedi_Strafe( int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking ) -{ - if( Jedi_CultistDestroyer( NPCS.NPC ) ) - { +static qboolean Jedi_Strafe(int strafeTimeMin, int strafeTimeMax, int nextStrafeTimeMin, int nextStrafeTimeMax, qboolean walking) { + if (Jedi_CultistDestroyer(NPCS.NPC)) { return qfalse; } - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_LOCK_WON && NPCS.NPC->enemy && NPCS.NPC->enemy->painDebounceTime > level.time ) - {//don't strafe if pressing the advantage of winning a saberLock + if (NPCS.NPC->client->ps.saberEventFlags & SEF_LOCK_WON && NPCS.NPC->enemy && + NPCS.NPC->enemy->painDebounceTime > level.time) { // don't strafe if pressing the advantage of winning a saberLock return qfalse; } - if ( TIMER_Done( NPCS.NPC, "strafeLeft" ) && TIMER_Done( NPCS.NPC, "strafeRight" ) ) - { + if (TIMER_Done(NPCS.NPC, "strafeLeft") && TIMER_Done(NPCS.NPC, "strafeRight")) { qboolean strafed = qfalse; - //TODO: make left/right choice a tactical decision rather than random: + // TODO: make left/right choice a tactical decision rather than random: // try to keep own back away from walls and ledges, // try to keep enemy's back to a ledge or wall // Maybe try to strafe toward designer-placed "safe spots" or "goals"? - int strafeTime = Q_irand( strafeTimeMin, strafeTimeMax ); + int strafeTime = Q_irand(strafeTimeMin, strafeTimeMax); - if ( Q_irand( 0, 1 ) ) - { - if ( NPC_MoveDirClear( NPCS.ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPCS.NPC, "strafeLeft", strafeTime ); + if (Q_irand(0, 1)) { + if (NPC_MoveDirClear(NPCS.ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPCS.NPC, "strafeLeft", strafeTime); + strafed = qtrue; + } else if (NPC_MoveDirClear(NPCS.ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPCS.NPC, "strafeRight", strafeTime); strafed = qtrue; } - else if ( NPC_MoveDirClear( NPCS.ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPCS.NPC, "strafeRight", strafeTime ); - strafed = qtrue; - } - } - else - { - if ( NPC_MoveDirClear( NPCS.ucmd.forwardmove, 127, qfalse ) ) - { - TIMER_Set( NPCS.NPC, "strafeRight", strafeTime ); + } else { + if (NPC_MoveDirClear(NPCS.ucmd.forwardmove, 127, qfalse)) { + TIMER_Set(NPCS.NPC, "strafeRight", strafeTime); strafed = qtrue; - } - else if ( NPC_MoveDirClear( NPCS.ucmd.forwardmove, -127, qfalse ) ) - { - TIMER_Set( NPCS.NPC, "strafeLeft", strafeTime ); + } else if (NPC_MoveDirClear(NPCS.ucmd.forwardmove, -127, qfalse)) { + TIMER_Set(NPCS.NPC, "strafeLeft", strafeTime); strafed = qtrue; } } - if ( strafed ) - { - TIMER_Set( NPCS.NPC, "noStrafe", strafeTime + Q_irand( nextStrafeTimeMin, nextStrafeTimeMax ) ); - if ( walking ) - {//should be a slow strafe - TIMER_Set( NPCS.NPC, "walking", strafeTime ); + if (strafed) { + TIMER_Set(NPCS.NPC, "noStrafe", strafeTime + Q_irand(nextStrafeTimeMin, nextStrafeTimeMax)); + if (walking) { // should be a slow strafe + TIMER_Set(NPCS.NPC, "walking", strafeTime); } return qtrue; } @@ -1946,382 +1580,280 @@ Right now used to dodge instant-hit weapons. FIXME: possibly call this for saber melee evasion and/or missile evasion? FIXME: possibly let player do this too? */ -//rwwFIXMEFIXME: Going to use qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ) from -//w_saber.c.. maybe use seperate one for NPCs or add cases to that one? +// rwwFIXMEFIXME: Going to use qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ) from +// w_saber.c.. maybe use seperate one for NPCs or add cases to that one? -evasionType_t Jedi_CheckFlipEvasions( gentity_t *self, float rightdot, float zdiff ) -{ - if ( self->NPC && (self->NPC->scriptFlags&SCF_NO_ACROBATICS) ) - { +evasionType_t Jedi_CheckFlipEvasions(gentity_t *self, float rightdot, float zdiff) { + if (self->NPC && (self->NPC->scriptFlags & SCF_NO_ACROBATICS)) { return EVASION_NONE; } - if ( self->client - && (self->client->ps.fd.forceRageRecoveryTime > level.time || (self->client->ps.fd.forcePowersActive&(1<client && + (self->client->ps.fd.forceRageRecoveryTime > level.time || (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)))) { // no fancy dodges when raging return EVASION_NONE; } - //Check for: - //ARIALS/CARTWHEELS - //WALL-RUNS - //WALL-FLIPS - //FIXME: if facing a wall, do forward wall-walk-backflip - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT ) - {//already running on a wall + // Check for: + // ARIALS/CARTWHEELS + // WALL-RUNS + // WALL-FLIPS + // FIXME: if facing a wall, do forward wall-walk-backflip + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT || self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT) { // already running on a wall vec3_t right, fwdAngles; - int anim = -1; + int anim = -1; float animLength; VectorSet(fwdAngles, 0, self->client->ps.viewangles[YAW], 0); - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); - animLength = BG_AnimLength( self->localAnimIndex, (animNumber_t)self->client->ps.legsAnim ); - if ( self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0 ) - {//I'm running on a wall to my left and the attack is on the left - if ( animLength - self->client->ps.legsTimer > 400 - && self->client->ps.legsTimer > 400 ) - {//not at the beginning or end of the anim + animLength = BG_AnimLength(self->localAnimIndex, (animNumber_t)self->client->ps.legsAnim); + if (self->client->ps.legsAnim == BOTH_WALL_RUN_LEFT && rightdot < 0) { // I'm running on a wall to my left and the attack is on the left + if (animLength - self->client->ps.legsTimer > 400 && self->client->ps.legsTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_LEFT_FLIP; } - } - else if ( self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0 ) - {//I'm running on a wall to my right and the attack is on the right - if ( animLength - self->client->ps.legsTimer > 400 - && self->client->ps.legsTimer > 400 ) - {//not at the beginning or end of the anim + } else if (self->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT && rightdot > 0) { // I'm running on a wall to my right and the attack is on the right + if (animLength - self->client->ps.legsTimer > 400 && self->client->ps.legsTimer > 400) { // not at the beginning or end of the anim anim = BOTH_WALL_RUN_RIGHT_FLIP; } } - if ( anim != -1 ) - {//flip off the wall! + if (anim != -1) { // flip off the wall! int parts; - //FIXME: check the direction we will flip towards for do-not-enter/walls/drops? - //NOTE: we presume there is still a wall there! - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + // FIXME: check the direction we will flip towards for do-not-enter/walls/drops? + // NOTE: we presume there is still a wall there! + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { self->client->ps.velocity[0] *= 0.5f; self->client->ps.velocity[1] *= 0.5f; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - //rwwFIXMEFIXME: Add these pm flags? - G_AddEvent( self, EV_JUMP, 0 ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); + // rwwFIXMEFIXME: Add these pm flags? + G_AddEvent(self, EV_JUMP, 0); return EVASION_OTHER; } - } - else if ( self->client->NPC_class != CLASS_DESANN //desann doesn't do these kind of frilly acrobatics - && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) - && Q_irand( 0, 1 ) - && !BG_InRoll( &self->client->ps, self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) - && !BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - { + } else if (self->client->NPC_class != CLASS_DESANN // desann doesn't do these kind of frilly acrobatics + && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT) && Q_irand(0, 1) && + !BG_InRoll(&self->client->ps, self->client->ps.legsAnim) && !PM_InKnockDown(&self->client->ps) && + !BG_SaberInSpecialAttack(self->client->ps.torsoAnim)) { vec3_t fwd, right, traceto, mins, maxs, fwdAngles; - trace_t trace; + trace_t trace; int parts, anim; - float speed, checkDist; + float speed, checkDist; qboolean allowCartWheels = qtrue; qboolean allowWallFlips = qtrue; - if ( self->client->ps.weapon == WP_SABER ) - { - if ( self->client->saber[0].model[0] - && (self->client->saber[0].saberFlags&SFL_NO_CARTWHEELS) ) - { + if (self->client->ps.weapon == WP_SABER) { + if (self->client->saber[0].model[0] && (self->client->saber[0].saberFlags & SFL_NO_CARTWHEELS)) { allowCartWheels = qfalse; - } - else if ( self->client->saber[1].model[0] - && (self->client->saber[1].saberFlags&SFL_NO_CARTWHEELS) ) - { + } else if (self->client->saber[1].model[0] && (self->client->saber[1].saberFlags & SFL_NO_CARTWHEELS)) { allowCartWheels = qfalse; } - if ( self->client->saber[0].model[0] - && (self->client->saber[0].saberFlags&SFL_NO_WALL_FLIPS) ) - { + if (self->client->saber[0].model[0] && (self->client->saber[0].saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; - } - else if ( self->client->saber[1].model[0] - && (self->client->saber[1].saberFlags&SFL_NO_WALL_FLIPS) ) - { + } else if (self->client->saber[1].model[0] && (self->client->saber[1].saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; } } - VectorSet(mins, self->r.mins[0],self->r.mins[1],0); - VectorSet(maxs, self->r.maxs[0],self->r.maxs[1],24); + VectorSet(mins, self->r.mins[0], self->r.mins[1], 0); + VectorSet(maxs, self->r.maxs[0], self->r.maxs[1], 24); VectorSet(fwdAngles, 0, self->client->ps.viewangles[YAW], 0); - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); parts = SETANIM_BOTH; - if ( BG_SaberInAttack( self->client->ps.saberMove ) - || PM_SaberInStart( self->client->ps.saberMove ) ) - { + if (BG_SaberInAttack(self->client->ps.saberMove) || PM_SaberInStart(self->client->ps.saberMove)) { parts = SETANIM_LEGS; } - if ( rightdot >= 0 ) - { - if ( Q_irand( 0, 1 ) ) - { + if (rightdot >= 0) { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_LEFT; - } - else - { + } else { anim = BOTH_CARTWHEEL_LEFT; } checkDist = -128; speed = -200; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { anim = BOTH_ARIAL_RIGHT; - } - else - { + } else { anim = BOTH_CARTWHEEL_RIGHT; } checkDist = 128; speed = 200; } - //trace in the dir that we want to go - VectorMA( self->r.currentOrigin, checkDist, right, traceto ); - trap->Trace( &trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - if ( trace.fraction >= 1.0f && allowCartWheels ) - {//it's clear, let's do it - //FIXME: check for drops? + // trace in the dir that we want to go + VectorMA(self->r.currentOrigin, checkDist, right, traceto); + trap->Trace(&trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (trace.fraction >= 1.0f && allowCartWheels) { // it's clear, let's do it + // FIXME: check for drops? vec3_t jumpRt; - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.weaponTime = self->client->ps.legsTimer;//don't attack again until this anim is done - VectorCopy( self->client->ps.viewangles, fwdAngles ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.weaponTime = self->client->ps.legsTimer; // don't attack again until this anim is done + VectorCopy(self->client->ps.viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the flip - AngleVectors( fwdAngles, NULL, jumpRt, NULL ); - VectorScale( jumpRt, speed, self->client->ps.velocity ); - self->client->ps.fd.forceJumpCharge = 0;//so we don't play the force flip anim + // do the flip + AngleVectors(fwdAngles, NULL, jumpRt, NULL); + VectorScale(jumpRt, speed, self->client->ps.velocity); + self->client->ps.fd.forceJumpCharge = 0; // so we don't play the force flip anim self->client->ps.velocity[2] = 200; - self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2];//so we don't take damage if we land at same height - //self->client->ps.pm_flags |= PMF_JUMPING; - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - //ucmd.upmove = 0; + self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2]; // so we don't take damage if we land at same height + // self->client->ps.pm_flags |= PMF_JUMPING; + if (self->client->NPC_class == CLASS_BOBAFETT) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); + } + // ucmd.upmove = 0; return EVASION_CARTWHEEL; - } - else if ( !(trace.contents&CONTENTS_BOTCLIP) ) - {//hit a wall, not a do-not-enter brush - //FIXME: before we check any of these jump-type evasions, we should check for headroom, right? - //Okay, see if we can flip *off* the wall and go the other way - vec3_t idealNormal; + } else if (!(trace.contents & CONTENTS_BOTCLIP)) { // hit a wall, not a do-not-enter brush + // FIXME: before we check any of these jump-type evasions, we should check for headroom, right? + // Okay, see if we can flip *off* the wall and go the other way + vec3_t idealNormal; gentity_t *traceEnt; - VectorSubtract( self->r.currentOrigin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + VectorSubtract(self->r.currentOrigin, traceto, idealNormal); + VectorNormalize(idealNormal); traceEnt = &g_entities[trace.entityNum]; - if ( (trace.entityNums.solid!=SOLID_BMODEL) || DotProduct( trace.plane.normal, idealNormal ) > 0.7f ) - {//it's a ent of some sort or it's a wall roughly facing us + if ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7f) { // it's a ent of some sort or it's a wall roughly facing us float bestCheckDist = 0; - //hmm, see if we're moving forward - if ( DotProduct( self->client->ps.velocity, fwd ) < 200 ) - {//not running forward very fast - //check to see if it's okay to move the other way - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on that side is close enough to wall-flip off of or wall-run on + // hmm, see if we're moving forward + if (DotProduct(self->client->ps.velocity, fwd) < 200) { // not running forward very fast + // check to see if it's okay to move the other way + if ((trace.fraction * checkDist) <= 32) { // wall on that side is close enough to wall-flip off of or wall-run on bestCheckDist = checkDist; checkDist *= -1.0f; - VectorMA( self->r.currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - trap->Trace( &trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - if ( trace.fraction >= 1.0f ) - {//it's clear, let's do it - if ( allowWallFlips ) - {//okay to do wall-flips with this saber - //FIXME: check for drops? - //turn the cartwheel into a wallflip in the other dir - if ( rightdot > 0 ) - { + VectorMA(self->r.currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + trap->Trace(&trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, + CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (trace.fraction >= 1.0f) { // it's clear, let's do it + if (allowWallFlips) { // okay to do wall-flips with this saber + // FIXME: check for drops? + // turn the cartwheel into a wallflip in the other dir + if (rightdot > 0) { anim = BOTH_WALL_FLIP_LEFT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, 150, right, self->client->ps.velocity ); - } - else - { + VectorMA(self->client->ps.velocity, 150, right, self->client->ps.velocity); + } else { anim = BOTH_WALL_FLIP_RIGHT; self->client->ps.velocity[0] = self->client->ps.velocity[1] = 0; - VectorMA( self->client->ps.velocity, -150, right, self->client->ps.velocity ); + VectorMA(self->client->ps.velocity, -150, right, self->client->ps.velocity); } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2];//so we don't take damage if we land at same height - //self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2]; // so we don't take damage if we land at same height + // self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); + if (self->client->NPC_class == CLASS_BOBAFETT) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } return EVASION_OTHER; - } - } - else - {//boxed in on both sides - if ( DotProduct( self->client->ps.velocity, fwd ) < 0 ) - {//moving backwards + } + } else { // boxed in on both sides + if (DotProduct(self->client->ps.velocity, fwd) < 0) { // moving backwards return EVASION_NONE; } - if ( (trace.fraction*checkDist) <= 32 && (trace.fraction*checkDist) < bestCheckDist ) - { + if ((trace.fraction * checkDist) <= 32 && (trace.fraction * checkDist) < bestCheckDist) { bestCheckDist = checkDist; } } - } - else - {//too far from that wall to flip or run off it, check other side + } else { // too far from that wall to flip or run off it, check other side checkDist *= -1.0f; - VectorMA( self->r.currentOrigin, checkDist, right, traceto ); - //trace in the dir that we want to go - trap->Trace( &trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - if ( (trace.fraction*checkDist) <= 32 ) - {//wall on this side is close enough + VectorMA(self->r.currentOrigin, checkDist, right, traceto); + // trace in the dir that we want to go + trap->Trace(&trace, self->r.currentOrigin, mins, maxs, traceto, self->s.number, + CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, 0); + if ((trace.fraction * checkDist) <= 32) { // wall on this side is close enough bestCheckDist = checkDist; - } - else - {//neither side has a wall within 32 + } else { // neither side has a wall within 32 return EVASION_NONE; } } } - //Try wall run? - if ( bestCheckDist ) - {//one of the walls was close enough to wall-run on + // Try wall run? + if (bestCheckDist) { // one of the walls was close enough to wall-run on qboolean allowWallRuns = qtrue; - if ( self->client->ps.weapon == WP_SABER ) - { - if ( self->client->saber[0].model[0] - && (self->client->saber[0].saberFlags&SFL_NO_WALL_RUNS) ) - { + if (self->client->ps.weapon == WP_SABER) { + if (self->client->saber[0].model[0] && (self->client->saber[0].saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; - } - else if ( self->client->saber[1].model[0] - && (self->client->saber[1].saberFlags&SFL_NO_WALL_RUNS) ) - { + } else if (self->client->saber[1].model[0] && (self->client->saber[1].saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; } } - if ( allowWallRuns ) - {//okay to do wallruns with this saber - //FIXME: check for long enough wall and a drop at the end? - if ( bestCheckDist > 0 ) - {//it was to the right + if (allowWallRuns) { // okay to do wallruns with this saber + // FIXME: check for long enough wall and a drop at the end? + if (bestCheckDist > 0) { // it was to the right anim = BOTH_WALL_RUN_RIGHT; - } - else - {//it was to the left + } else { // it was to the left anim = BOTH_WALL_RUN_LEFT; } - self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2]/2.25f; - //animate me + self->client->ps.velocity[2] = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; + // animate me parts = SETANIM_LEGS; - if ( !self->client->ps.weaponTime ) - { + if (!self->client->ps.weaponTime) { parts = SETANIM_BOTH; } - NPC_SetAnim( self, parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2];//so we don't take damage if we land at same height - //self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_SoundOnEnt( self, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPC_SetAnim(self, parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2]; // so we don't take damage if we land at same height + // self->client->ps.pm_flags |= (PMF_JUMPING|PMF_SLOW_MO_FALL); + if (self->client->NPC_class == CLASS_BOBAFETT) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_SoundOnEnt(self, CHAN_BODY, "sound/weapons/force/jump.wav"); } return EVASION_OTHER; } } - //else check for wall in front, do backflip off wall + // else check for wall in front, do backflip off wall } } } return EVASION_NONE; } -int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) -{ - if ( !self->client ) - { +int Jedi_ReCalcParryTime(gentity_t *self, evasionType_t evasionType) { + if (!self->client) { return 0; } - if ( self->s.number >= 0 && self->s.number < MAX_CLIENTS ) - {//player + if (self->s.number >= 0 && self->s.number < MAX_CLIENTS) { // player return bg_parryDebounce[self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]]; - } - else if ( self->NPC ) - { - if ( !g_saberRealisticCombat.integer - && ( g_npcspskill.integer == 2 || (g_npcspskill.integer == 1 && self->client->NPC_class == CLASS_TAVION) ) ) - { - if ( self->client->NPC_class == CLASS_TAVION ) - { + } else if (self->NPC) { + if (!g_saberRealisticCombat.integer && (g_npcspskill.integer == 2 || (g_npcspskill.integer == 1 && self->client->NPC_class == CLASS_TAVION))) { + if (self->client->NPC_class == CLASS_TAVION) { return 0; + } else { + return Q_irand(0, 150); } - else - { - return Q_irand( 0, 150 ); - } - } - else - { - int baseTime; - if ( evasionType == EVASION_DODGE ) - { + } else { + int baseTime; + if (evasionType == EVASION_DODGE) { baseTime = self->client->ps.torsoTimer; - } - else if ( evasionType == EVASION_CARTWHEEL ) - { + } else if (evasionType == EVASION_CARTWHEEL) { baseTime = self->client->ps.torsoTimer; - } - else if ( self->client->ps.saberInFlight ) - { - baseTime = Q_irand( 1, 3 ) * 50; - } - else - { - if ( g_saberRealisticCombat.integer ) - { + } else if (self->client->ps.saberInFlight) { + baseTime = Q_irand(1, 3) * 50; + } else { + if (g_saberRealisticCombat.integer) { baseTime = 500; - switch ( g_npcspskill.integer ) - { + switch (g_npcspskill.integer) { case 0: baseTime = 500; break; @@ -2333,72 +1865,47 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) baseTime = 100; break; } - } - else - { - baseTime = 150;//500; + } else { + baseTime = 150; // 500; - switch ( g_npcspskill.integer ) - { + switch (g_npcspskill.integer) { case 0: - baseTime = 200;//500; + baseTime = 200; // 500; break; case 1: - baseTime = 100;//300; + baseTime = 100; // 300; break; case 2: default: - baseTime = 50;//100; + baseTime = 50; // 100; break; } } - if ( self->client->NPC_class == CLASS_TAVION ) - {//Tavion is faster - baseTime = ceil(baseTime/2.0f); - } - else if ( self->NPC->rank >= RANK_LT_JG ) - {//fencers, bosses, shadowtroopers, luke, desann, et al use the norm - if ( !Q_irand( 0, 2 ) ) - {//with the occasional fast parry - baseTime = ceil(baseTime/2.0f); + if (self->client->NPC_class == CLASS_TAVION) { // Tavion is faster + baseTime = ceil(baseTime / 2.0f); + } else if (self->NPC->rank >= RANK_LT_JG) { // fencers, bosses, shadowtroopers, luke, desann, et al use the norm + if (!Q_irand(0, 2)) { // with the occasional fast parry + baseTime = ceil(baseTime / 2.0f); } - } - else if ( self->NPC->rank == RANK_CIVILIAN ) - {//grunts are slowest - baseTime = baseTime*Q_irand(1,3); - } - else if ( self->NPC->rank == RANK_CREWMAN ) - {//acrobats aren't so bad - if ( evasionType == EVASION_PARRY - || evasionType == EVASION_DUCK_PARRY - || evasionType == EVASION_JUMP_PARRY ) - {//slower with parries - baseTime = baseTime*Q_irand(1,2); - } - else - {//faster with acrobatics - //baseTime = baseTime; + } else if (self->NPC->rank == RANK_CIVILIAN) { // grunts are slowest + baseTime = baseTime * Q_irand(1, 3); + } else if (self->NPC->rank == RANK_CREWMAN) { // acrobats aren't so bad + if (evasionType == EVASION_PARRY || evasionType == EVASION_DUCK_PARRY || evasionType == EVASION_JUMP_PARRY) { // slower with parries + baseTime = baseTime * Q_irand(1, 2); + } else { // faster with acrobatics + // baseTime = baseTime; } + } else { // force users are kinda slow + baseTime = baseTime * Q_irand(1, 2); } - else - {//force users are kinda slow - baseTime = baseTime*Q_irand(1,2); - } - if ( evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY ) - { + if (evasionType == EVASION_DUCK || evasionType == EVASION_DUCK_PARRY) { baseTime += 100; - } - else if ( evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY ) - { + } else if (evasionType == EVASION_JUMP || evasionType == EVASION_JUMP_PARRY) { baseTime += 50; - } - else if ( evasionType == EVASION_OTHER ) - { + } else if (evasionType == EVASION_OTHER) { baseTime += 100; - } - else if ( evasionType == EVASION_FJUMP ) - { + } else if (evasionType == EVASION_FJUMP) { baseTime += 100; } } @@ -2409,30 +1916,24 @@ int Jedi_ReCalcParryTime( gentity_t *self, evasionType_t evasionType ) return 0; } -qboolean Jedi_QuickReactions( gentity_t *self ) -{ - if ( ( self->client->NPC_class == CLASS_JEDI && NPCS.NPCInfo->rank == RANK_COMMANDER ) || - self->client->NPC_class == CLASS_TAVION || - (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_1&&g_npcspskill.integer>1) || - (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]>FORCE_LEVEL_2&&g_npcspskill.integer>0) ) - { +qboolean Jedi_QuickReactions(gentity_t *self) { + if ((self->client->NPC_class == CLASS_JEDI && NPCS.NPCInfo->rank == RANK_COMMANDER) || self->client->NPC_class == CLASS_TAVION || + (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_1 && g_npcspskill.integer > 1) || + (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] > FORCE_LEVEL_2 && g_npcspskill.integer > 0)) { return qtrue; } return qfalse; } -qboolean Jedi_SaberBusy( gentity_t *self ) -{ - if ( self->client->ps.torsoTimer > 300 - && ( (BG_SaberInAttack( self->client->ps.saberMove )&&self->client->ps.fd.saberAnimLevel==FORCE_LEVEL_3) - || BG_SpinningSaberAnim( self->client->ps.torsoAnim ) - || BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) - //|| PM_SaberInBounce( self->client->ps.saberMove ) - || PM_SaberInBrokenParry( self->client->ps.saberMove ) - //|| PM_SaberInDeflect( self->client->ps.saberMove ) - || BG_FlippingAnim( self->client->ps.torsoAnim ) - || PM_RollingAnim( self->client->ps.torsoAnim ) ) ) - {//my saber is not in a parrying position +qboolean Jedi_SaberBusy(gentity_t *self) { + if (self->client->ps.torsoTimer > 300 && + ((BG_SaberInAttack(self->client->ps.saberMove) && self->client->ps.fd.saberAnimLevel == FORCE_LEVEL_3) || + BG_SpinningSaberAnim(self->client->ps.torsoAnim) || + BG_SaberInSpecialAttack(self->client->ps.torsoAnim) + //|| PM_SaberInBounce( self->client->ps.saberMove ) + || PM_SaberInBrokenParry(self->client->ps.saberMove) + //|| PM_SaberInDeflect( self->client->ps.saberMove ) + || BG_FlippingAnim(self->client->ps.torsoAnim) || PM_RollingAnim(self->client->ps.torsoAnim))) { // my saber is not in a parrying position return qtrue; } return qfalse; @@ -2450,456 +1951,320 @@ NOTE: always blocking projectiles in this func! ------------------------- */ -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist ) //dist = 0.0f +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist) // dist = 0.0f { - vec3_t hitloc, hitdir, diff, fwdangles={0,0,0}, right; + vec3_t hitloc, hitdir, diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; - int duckChance = 0; - int dodgeAnim = -1; - qboolean saberBusy = qfalse, doDodge = qfalse; - evasionType_t evasionType = EVASION_NONE; - - //FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! - //FIXME: reborn don't block enough anymore - if ( !incoming ) - { - VectorCopy( pHitloc, hitloc ); - VectorCopy( phitDir, hitdir ); - //FIXME: maybe base this on rank some? And/or g_npcspskill? - if ( self->client->ps.saberInFlight ) - {//DOH! do non-saber evasion! + int duckChance = 0; + int dodgeAnim = -1; + qboolean saberBusy = qfalse, doDodge = qfalse; + evasionType_t evasionType = EVASION_NONE; + + // FIXME: if we don't have our saber in hand, pick the force throw option or a jump or strafe! + // FIXME: reborn don't block enough anymore + if (!incoming) { + VectorCopy(pHitloc, hitloc); + VectorCopy(phitDir, hitdir); + // FIXME: maybe base this on rank some? And/or g_npcspskill? + if (self->client->ps.saberInFlight) { // DOH! do non-saber evasion! saberBusy = qtrue; + } else if (Jedi_QuickReactions( + self)) { // jedi trainer and tavion are must faster at parrying and can do it whenever they like + // Also, on medium, all level 3 people can parry any time and on hard, all level 2 or 3 people can parry any time + } else { + saberBusy = Jedi_SaberBusy(self); } - else if ( Jedi_QuickReactions( self ) ) - {//jedi trainer and tavion are must faster at parrying and can do it whenever they like - //Also, on medium, all level 3 people can parry any time and on hard, all level 2 or 3 people can parry any time - } - else - { - saberBusy = Jedi_SaberBusy( self ); - } - } - else - { - if ( incoming->s.weapon == WP_SABER ) - {//flying lightsaber, face it! - //FIXME: for this to actually work, we'd need to call update angles too? - //Jedi_FaceEntity( self, incoming, qtrue ); + } else { + if (incoming->s.weapon == WP_SABER) { // flying lightsaber, face it! + // FIXME: for this to actually work, we'd need to call update angles too? + // Jedi_FaceEntity( self, incoming, qtrue ); } - VectorCopy( incoming->r.currentOrigin, hitloc ); - VectorNormalize2( incoming->s.pos.trDelta, hitdir ); + VectorCopy(incoming->r.currentOrigin, hitloc); + VectorNormalize2(incoming->s.pos.trDelta, hitdir); } - if ( self->client && self->client->NPC_class == CLASS_BOBAFETT ) - { + if (self->client && self->client->NPC_class == CLASS_BOBAFETT) { saberBusy = qtrue; } - VectorSubtract( hitloc, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(hitloc, self->client->renderInfo.eyePoint, diff); diff[2] = 0; - //VectorNormalize( diff ); + // VectorNormalize( diff ); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); - - rightdot = DotProduct(right, diff);// + flrand(-0.10f,0.10f); - //totalHeight = self->client->renderInfo.eyePoint[2] - self->r.absmin[2]; - zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2];// + Q_irand(-6,6); - - //see if we can dodge if need-be - if ( (dist>16&&(Q_irand( 0, 2 )||saberBusy)) - || self->client->ps.saberInFlight - || BG_SabersOff( &self->client->ps ) - || self->client->NPC_class == CLASS_BOBAFETT ) - {//either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG) ) - {//acrobat or fencer or above - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE &&//on the ground - !(self->client->ps.pm_flags&PMF_DUCKED)&&cmd->upmove>=0&&TIMER_Done( self, "duck" )//not ducking - && !BG_InRoll( &self->client->ps, self->client->ps.legsAnim )//not rolling - && !PM_InKnockDown( &self->client->ps )//not knocked down - && ( self->client->ps.saberInFlight || - self->client->NPC_class == CLASS_BOBAFETT || - (!BG_SaberInAttack( self->client->ps.saberMove )//not attacking - && !PM_SaberInStart( self->client->ps.saberMove )//not starting an attack - && !BG_SpinningSaberAnim( self->client->ps.torsoAnim )//not in a saber spin - && !BG_SaberInSpecialAttack( self->client->ps.torsoAnim ))//not in a special attack - ) - ) - {//need to check all these because it overrides both torso and legs with the dodge + AngleVectors(fwdangles, NULL, right, NULL); + + rightdot = DotProduct(right, diff); // + flrand(-0.10f,0.10f); + // totalHeight = self->client->renderInfo.eyePoint[2] - self->r.absmin[2]; + zdiff = hitloc[2] - self->client->renderInfo.eyePoint[2]; // + Q_irand(-6,6); + + // see if we can dodge if need-be + if ((dist > 16 && (Q_irand(0, 2) || saberBusy)) || self->client->ps.saberInFlight || BG_SabersOff(&self->client->ps) || + self->client->NPC_class == CLASS_BOBAFETT) { // either it will miss by a bit (and 25% chance) OR our saber is not in-hand OR saber is off + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank >= RANK_LT_JG)) { // acrobat or fencer or above + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && // on the ground + !(self->client->ps.pm_flags & PMF_DUCKED) && cmd->upmove >= 0 && TIMER_Done(self, "duck") // not ducking + && !BG_InRoll(&self->client->ps, self->client->ps.legsAnim) // not rolling + && !PM_InKnockDown(&self->client->ps) // not knocked down + && (self->client->ps.saberInFlight || self->client->NPC_class == CLASS_BOBAFETT || + (!BG_SaberInAttack(self->client->ps.saberMove) // not attacking + && !PM_SaberInStart(self->client->ps.saberMove) // not starting an attack + && !BG_SpinningSaberAnim(self->client->ps.torsoAnim) // not in a saber spin + && !BG_SaberInSpecialAttack(self->client->ps.torsoAnim)) // not in a special attack + )) { // need to check all these because it overrides both torso and legs with the dodge doDodge = qtrue; } } } // Figure out what quadrant the block was in. - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2]-self->r.absmin[2],zdiff,rightdot); - } - - //UL = > -1//-6 - //UR = > -6//-9 - //TOP = > +6//+4 - //FIXME: take FP_SABER_DEFENSE into account here somehow? - if ( zdiff >= -5 )//was 0 - { - if ( incoming || !saberBusy ) - { - if ( rightdot > 12 - || (rightdot > 3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, 0.3 - {//coming from right - if ( doDodge ) - { - if ( self->client->NPC_class == CLASS_BOBAFETT && !Q_irand( 0, 2 ) ) - {//roll! - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); + if (d_JediAI.integer) { + Com_Printf("(%d) evading attack from height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, hitloc[2] - self->r.absmin[2], zdiff, rightdot); + } + + // UL = > -1//-6 + // UR = > -6//-9 + // TOP = > +6//+4 + // FIXME: take FP_SABER_DEFENSE into account here somehow? + if (zdiff >= -5) // was 0 + { + if (incoming || !saberBusy) { + if (rightdot > 12 || (rightdot > 3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, 0.3 + { // coming from right + if (doDodge) { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 2)) { // roll! + TIMER_Start(self, "duck", Q_irand(500, 1500)); + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); evasionType = EVASION_DUCK; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FL; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BL; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "duck " ); + if (d_JediAI.integer) { + Com_Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI.integer ) - { - Com_Printf( "UR block\n" ); + if (d_JediAI.integer) { + Com_Printf("UR block\n"); } - } - else if ( rightdot < -12 - || (rightdot < -3 && zdiff < 5) - || (!incoming&&fabs(hitdir[2])<0.25f) )//was normalized, -0.3 - {//coming from left - if ( doDodge ) - { - if ( self->client->NPC_class == CLASS_BOBAFETT && !Q_irand( 0, 2 ) ) - {//roll! - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - TIMER_Start( self, "strafeRight", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeLeft", 0 ); + } else if (rightdot < -12 || (rightdot < -3 && zdiff < 5) || (!incoming && fabs(hitdir[2]) < 0.25f)) // was normalized, -0.3 + { // coming from left + if (doDodge) { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 2)) { // roll! + TIMER_Start(self, "duck", Q_irand(500, 1500)); + TIMER_Start(self, "strafeRight", Q_irand(500, 1500)); + TIMER_Set(self, "strafeLeft", 0); evasionType = EVASION_DUCK; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { dodgeAnim = BOTH_DODGE_FR; - } - else - { + } else { dodgeAnim = BOTH_DODGE_BR; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - if ( zdiff > 5 ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + if (zdiff > 5) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "duck " ); + if (d_JediAI.integer) { + Com_Printf("duck "); } - } - else - { + } else { duckChance = 6; } } } - if ( d_JediAI.integer ) - { - Com_Printf( "UL block\n" ); + if (d_JediAI.integer) { + Com_Printf("UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; evasionType = EVASION_PARRY; - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { duckChance = 4; } - if ( d_JediAI.integer ) - { - Com_Printf( "TOP block\n" ); + if (d_JediAI.integer) { + Com_Printf("TOP block\n"); } } - } - else - { - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + } else { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - if ( d_JediAI.integer ) - { - Com_Printf( "duck " ); + if (d_JediAI.integer) { + Com_Printf("duck "); } } } } - //LL = -22//= -18 to -39 - //LR = -23//= -20 to -41 - else if ( zdiff > -22 )//was-15 ) + // LL = -22//= -18 to -39 + // LR = -23//= -20 to -41 + else if (zdiff > -22) // was-15 ) { - if ( 1 )//zdiff < -10 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { - //duckChance = 2; - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + if (1) // zdiff < -10 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { + // duckChance = 2; + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - if ( d_JediAI.integer ) - { - Com_Printf( "duck " ); + if (d_JediAI.integer) { + Com_Printf("duck "); } - } - else - {//in air! Ducking does no good + } else { // in air! Ducking does no good } } - if ( incoming || !saberBusy ) - { - if ( rightdot > 8 || (rightdot > 3 && zdiff < -11) )//was normalized, 0.2 + if (incoming || !saberBusy) { + if (rightdot > 8 || (rightdot > 3 && zdiff < -11)) // was normalized, 0.2 { - if ( doDodge ) - { - if ( self->client->NPC_class == CLASS_BOBAFETT && !Q_irand( 0, 2 ) ) - {//roll! - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - } - else - { + if (doDodge) { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 2)) { // roll! + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + } else { dodgeAnim = BOTH_DODGE_L; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI.integer ) - { - Com_Printf( "mid-UR block\n" ); + if (d_JediAI.integer) { + Com_Printf("mid-UR block\n"); } - } - else if ( rightdot < -8 || (rightdot < -3 && zdiff < -11) )//was normalized, -0.2 + } else if (rightdot < -8 || (rightdot < -3 && zdiff < -11)) // was normalized, -0.2 { - if ( doDodge ) - { - if ( self->client->NPC_class == CLASS_BOBAFETT && !Q_irand( 0, 2 ) ) - {//roll! - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - } - else - { + if (doDodge) { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 2)) { // roll! + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + } else { dodgeAnim = BOTH_DODGE_R; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } } - if ( d_JediAI.integer ) - { - Com_Printf( "mid-UL block\n" ); + if (d_JediAI.integer) { + Com_Printf("mid-UL block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; - if ( evasionType == EVASION_DUCK ) - { + if (evasionType == EVASION_DUCK) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_PARRY; } - if ( d_JediAI.integer ) - { - Com_Printf( "mid-TOP block\n" ); + if (d_JediAI.integer) { + Com_Printf("mid-TOP block\n"); } } } - } - else if ( saberBusy || (zdiff < -36 && ( zdiff < -44 || !Q_irand( 0, 2 ) ) ) )//was -30 and -40//2nd one was -46 - {//jump! - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//already in air, duck to pull up legs - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); + } else if (saberBusy || (zdiff < -36 && (zdiff < -44 || !Q_irand(0, 2)))) // was -30 and -40//2nd one was -46 + { // jump! + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // already in air, duck to pull up legs + TIMER_Start(self, "duck", Q_irand(500, 1500)); evasionType = EVASION_DUCK; - if ( d_JediAI.integer ) - { - Com_Printf( "legs up\n" ); + if (d_JediAI.integer) { + Com_Printf("legs up\n"); } - if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "LR block\n" ); + if (d_JediAI.integer) { + Com_Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_DUCK_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "LL block\n" ); + if (d_JediAI.integer) { + Com_Printf("LL block\n"); } } } - } - else - {//gotta jump! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.fd.forceRageRecoveryTime < level.time - && !(self->client->ps.fd.forcePowersActive&(1<client->ps ) ) - { - self->client->ps.fd.forceJumpCharge = 320;//FIXME: calc this intelligently + } else { // gotta jump! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.fd.forceRageRecoveryTime < level.time && + !(self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.fd.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - if ( d_JediAI.integer ) - { - Com_Printf( "force jump + " ); + if (d_JediAI.integer) { + Com_Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.fd.forceRageRecoveryTime < level.time - && !(self->client->ps.fd.forcePowersActive&(1<client->NPC_class == CLASS_BOBAFETT && !Q_irand( 0, 1 ) ) - {//roll! - if ( rightdot > 0 ) - { - TIMER_Start( self, "strafeLeft", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeRight", 0 ); - TIMER_Set( self, "walking", 0 ); - } - else - { - TIMER_Start( self, "strafeRight", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "strafeLeft", 0 ); - TIMER_Set( self, "walking", 0 ); + } else { // normal jump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.fd.forceRageRecoveryTime < level.time && + !(self->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) { + if (self->client->NPC_class == CLASS_BOBAFETT && !Q_irand(0, 1)) { // roll! + if (rightdot > 0) { + TIMER_Start(self, "strafeLeft", Q_irand(500, 1500)); + TIMER_Set(self, "strafeRight", 0); + TIMER_Set(self, "walking", 0); + } else { + TIMER_Start(self, "strafeRight", Q_irand(500, 1500)); + TIMER_Set(self, "strafeLeft", 0); + TIMER_Set(self, "walking", 0); } - } - else - { - if ( self == NPCS.NPC ) - { + } else { + if (self == NPCS.NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } } evasionType = EVASION_JUMP; - if ( d_JediAI.integer ) - { - Com_Printf( "jump + " ); + if (d_JediAI.integer) { + Com_Printf("jump + "); } } - if ( self->client->NPC_class == CLASS_TAVION ) - { - if ( !incoming - && self->client->ps.groundEntityNum < ENTITYNUM_NONE - && !Q_irand( 0, 2 ) ) - { - if ( !BG_SaberInAttack( self->client->ps.saberMove ) - && !PM_SaberInStart( self->client->ps.saberMove ) - && !BG_InRoll( &self->client->ps, self->client->ps.legsAnim ) - && !PM_InKnockDown( &self->client->ps ) - && !BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) ) - {//do the butterfly! + if (self->client->NPC_class == CLASS_TAVION) { + if (!incoming && self->client->ps.groundEntityNum < ENTITYNUM_NONE && !Q_irand(0, 2)) { + if (!BG_SaberInAttack(self->client->ps.saberMove) && !PM_SaberInStart(self->client->ps.saberMove) && + !BG_InRoll(&self->client->ps, self->client->ps.legsAnim) && !PM_InKnockDown(&self->client->ps) && + !BG_SaberInSpecialAttack(self->client->ps.torsoAnim)) { // do the butterfly! int butterflyAnim; - if ( Q_irand( 0, 1 ) ) - { + if (Q_irand(0, 1)) { butterflyAnim = BOTH_BUTTERFLY_LEFT; - } - else - { + } else { butterflyAnim = BOTH_BUTTERFLY_RIGHT; } evasionType = EVASION_CARTWHEEL; - NPC_SetAnim( self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, butterflyAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.velocity[2] = 225; - self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2];//so we don't take damage if we land at same height - // self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - // self->client->ps.SaberActivateTrail( 300 );//FIXME: reset this when done! - //Ah well. No hacking from the server for now. - if ( self->client->NPC_class == CLASS_BOBAFETT ) - { - G_AddEvent( self, EV_JUMP, 0 ); - } - else - { - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/force/jump.wav") ); + self->client->ps.fd.forceJumpZStart = self->r.currentOrigin[2]; // so we don't take damage if we land at same height + // self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + // self->client->ps.SaberActivateTrail( 300 );//FIXME: reset this when done! + // Ah well. No hacking from the server for now. + if (self->client->NPC_class == CLASS_BOBAFETT) { + G_AddEvent(self, EV_JUMP, 0); + } else { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/jump.wav")); } cmd->upmove = 0; saberBusy = qtrue; @@ -2907,110 +2272,72 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } } - if ( ((evasionType = Jedi_CheckFlipEvasions( self, rightdot, zdiff ))!=EVASION_NONE) ) - { + if (((evasionType = Jedi_CheckFlipEvasions(self, rightdot, zdiff)) != EVASION_NONE)) { saberBusy = qtrue; - } - else if ( incoming || !saberBusy ) - { - //since the jump may be cleared if not safe, set a lower block too - if ( rightdot >= 0 ) - { + } else if (incoming || !saberBusy) { + // since the jump may be cleared if not safe, set a lower block too + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI.integer ) - { - Com_Printf( "LR block\n" ); + if (d_JediAI.integer) { + Com_Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; - if ( evasionType == EVASION_JUMP ) - { + if (evasionType == EVASION_JUMP) { evasionType = EVASION_JUMP_PARRY; - } - else if ( evasionType == EVASION_NONE ) - { + } else if (evasionType == EVASION_NONE) { evasionType = EVASION_PARRY; } - if ( d_JediAI.integer ) - { - Com_Printf( "LL block\n" ); + if (d_JediAI.integer) { + Com_Printf("LL block\n"); } } } } - } - else - { - if ( incoming || !saberBusy ) - { - if ( rightdot >= 0 ) - { + } else { + if (incoming || !saberBusy) { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; evasionType = EVASION_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "LR block\n" ); + if (d_JediAI.integer) { + Com_Printf("LR block\n"); } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; evasionType = EVASION_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "LL block\n" ); + if (d_JediAI.integer) { + Com_Printf("LL block\n"); } } - if ( incoming && incoming->s.weapon == WP_SABER ) - {//thrown saber! - if ( self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG ) && - (!Q_irand( 0, 10 ) || (!Q_irand( 0, 2 ) && (cmd->forwardmove || cmd->rightmove))) ) - {//superjump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.fd.forceRageRecoveryTime < level.time - && !(self->client->ps.fd.forcePowersActive&(1<client->ps ) ) - { - self->client->ps.fd.forceJumpCharge = 320;//FIXME: calc this intelligently + if (incoming && incoming->s.weapon == WP_SABER) { // thrown saber! + if (self->NPC && (self->NPC->rank == RANK_CREWMAN || self->NPC->rank > RANK_LT_JG) && + (!Q_irand(0, 10) || (!Q_irand(0, 2) && (cmd->forwardmove || cmd->rightmove)))) { // superjump + // FIXME: check the jump, if can't, then block + if (self->NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.fd.forceRageRecoveryTime < level.time && + !(self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && !PM_InKnockDown(&self->client->ps)) { + self->client->ps.fd.forceJumpCharge = 320; // FIXME: calc this intelligently evasionType = EVASION_FJUMP; - if ( d_JediAI.integer ) - { - Com_Printf( "force jump + " ); + if (d_JediAI.integer) { + Com_Printf("force jump + "); } } - } - else - {//normal jump - //FIXME: check the jump, if can't, then block - if ( self->NPC - && !(self->NPC->scriptFlags&SCF_NO_ACROBATICS) - && self->client->ps.fd.forceRageRecoveryTime < level.time - && !(self->client->ps.fd.forcePowersActive&(1<NPC && !(self->NPC->scriptFlags & SCF_NO_ACROBATICS) && self->client->ps.fd.forceRageRecoveryTime < level.time && + !(self->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) { + if (self == NPCS.NPC) { cmd->upmove = 127; - } - else - { + } else { self->client->ps.velocity[2] = JUMP_VELOCITY; } evasionType = EVASION_JUMP_PARRY; - if ( d_JediAI.integer ) - { - Com_Printf( "jump + " ); + if (d_JediAI.integer) { + Com_Printf("jump + "); } } } @@ -3018,43 +2345,34 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } - if ( evasionType == EVASION_NONE ) - { + if (evasionType == EVASION_NONE) { return EVASION_NONE; } - //stop taunting - TIMER_Set( self, "taunting", 0 ); - //stop gripping - TIMER_Set( self, "gripping", -level.time ); - WP_ForcePowerStop( self, FP_GRIP ); - //stop draining - TIMER_Set( self, "draining", -level.time ); - WP_ForcePowerStop( self, FP_DRAIN ); - - if ( dodgeAnim != -1 ) - {//dodged + // stop taunting + TIMER_Set(self, "taunting", 0); + // stop gripping + TIMER_Set(self, "gripping", -level.time); + WP_ForcePowerStop(self, FP_GRIP); + // stop draining + TIMER_Set(self, "draining", -level.time); + WP_ForcePowerStop(self, FP_DRAIN); + + if (dodgeAnim != -1) { // dodged evasionType = EVASION_DODGE; - NPC_SetAnim( self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, dodgeAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); self->client->ps.weaponTime = self->client->ps.torsoTimer; - //force them to stop moving in this case + // force them to stop moving in this case self->client->ps.pm_time = self->client->ps.torsoTimer; - //FIXME: maybe make a sound? Like a grunt? EV_JUMP? + // FIXME: maybe make a sound? Like a grunt? EV_JUMP? self->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //dodged, not block - } - else - { - if ( duckChance ) - { - if ( !Q_irand( 0, duckChance ) ) - { - TIMER_Start( self, "duck", Q_irand( 500, 1500 ) ); - if ( evasionType == EVASION_PARRY ) - { + // dodged, not block + } else { + if (duckChance) { + if (!Q_irand(0, duckChance)) { + TIMER_Start(self, "duck", Q_irand(500, 1500)); + if (evasionType == EVASION_PARRY) { evasionType = EVASION_DUCK_PARRY; - } - else - { + } else { evasionType = EVASION_DUCK; } /* @@ -3066,35 +2384,32 @@ evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc } } - if ( incoming ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (incoming) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } - } - //if ( self->client->ps.saberBlocked != BLOCKED_NONE ) + // if ( self->client->ps.saberBlocked != BLOCKED_NONE ) { - int parryReCalcTime = Jedi_ReCalcParryTime( self, evasionType ); - if ( self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime ) - { + int parryReCalcTime = Jedi_ReCalcParryTime(self, evasionType); + if (self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] < level.time + parryReCalcTime) { self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + parryReCalcTime; } } return evasionType; } -extern float ShortestLineSegBewteen2LineSegs( vec3_t start1, vec3_t end1, vec3_t start2, vec3_t end2, vec3_t close_pnt1, vec3_t close_pnt2 ); -extern int WPDEBUG_SaberColor( saber_colors_t saberColor ); -static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bladeNum = 0 +extern float ShortestLineSegBewteen2LineSegs(vec3_t start1, vec3_t end1, vec3_t start2, vec3_t end2, vec3_t close_pnt1, vec3_t close_pnt2); +extern int WPDEBUG_SaberColor(saber_colors_t saberColor); +static qboolean Jedi_SaberBlock(int saberNum, int bladeNum) // saberNum = 0, bladeNum = 0 { - vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir;//saberBase, + vec3_t hitloc, saberTipOld, saberTip, top, bottom, axisPoint, saberPoint, dir; // saberBase, vec3_t pointDir, baseDir, tipDir, saberHitPoint, saberMins, saberMaxs; - float pointDist, baseDirPerc, dist; - float bladeLen = 0; - trace_t tr; - evasionType_t evasionType; + float pointDist, baseDirPerc, dist; + float bladeLen = 0; + trace_t tr; + evasionType_t evasionType; - //FIXME: reborn don't block enough anymore + // FIXME: reborn don't block enough anymore /* //maybe do this on easy only... or only on grunt-level reborn if ( NPC->client->ps.weaponTime ) @@ -3103,13 +2418,11 @@ static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bl } */ - if ( !TIMER_Done( NPCS.NPC, "parryReCalcTime" ) ) - {//can't do our own re-think of which parry to use yet + if (!TIMER_Done(NPCS.NPC, "parryReCalcTime")) { // can't do our own re-think of which parry to use yet return qfalse; } - if ( NPCS.NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't move the saber to another position yet + if (NPCS.NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] > level.time) { // can't move the saber to another position yet return qfalse; } @@ -3121,14 +2434,13 @@ static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bl } */ - if ( NPCS.NPC->enemy->health <= 0 || !NPCS.NPC->enemy->client ) - {//don't keep blocking him once he's dead (or if not a client) + if (NPCS.NPC->enemy->health <= 0 || !NPCS.NPC->enemy->client) { // don't keep blocking him once he's dead (or if not a client) return qfalse; } /* //VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); - //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext ); - VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); + //VectorMA( NPC->enemy->client->renderInfo.muzzlePointNext, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirNext, saberTipNext + ); VectorMA( NPC->enemy->client->renderInfo.muzzlePointOld, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDirOld, saberTipOld ); VectorMA( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->ps.saberLength, NPC->enemy->client->renderInfo.muzzleDir, saberTip ); VectorSubtract( NPC->enemy->client->renderInfo.muzzlePoint, NPC->enemy->client->renderInfo.muzzlePointOld, dir );//get the dir @@ -3167,26 +2479,27 @@ static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bl VectorCopy( tr.endpos, hitloc ); } */ - VectorSet(saberMins,-4,-4,-4); - VectorSet(saberMaxs,4,4,4); - - VectorMA( NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzlePointOld, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].length, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzleDirOld, saberTipOld ); - VectorMA( NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzlePoint, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].length, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzleDir, saberTip ); -// VectorCopy(NPC->enemy->client->lastSaberBase_Always, muzzlePoint); -// VectorMA(muzzlePoint, GAME_SABER_LENGTH, NPC->enemy->client->lastSaberDir_Always, saberTip); -// VectorCopy(saberTip, saberTipOld); - - VectorCopy( NPCS.NPC->r.currentOrigin, top ); + VectorSet(saberMins, -4, -4, -4); + VectorSet(saberMaxs, 4, 4, 4); + + VectorMA(NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzlePointOld, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].length, + NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzleDirOld, saberTipOld); + VectorMA(NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzlePoint, NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].length, + NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].muzzleDir, saberTip); + // VectorCopy(NPC->enemy->client->lastSaberBase_Always, muzzlePoint); + // VectorMA(muzzlePoint, GAME_SABER_LENGTH, NPC->enemy->client->lastSaberDir_Always, saberTip); + // VectorCopy(saberTip, saberTipOld); + + VectorCopy(NPCS.NPC->r.currentOrigin, top); top[2] = NPCS.NPC->r.absmax[2]; - VectorCopy( NPCS.NPC->r.currentOrigin, bottom ); + VectorCopy(NPCS.NPC->r.currentOrigin, bottom); bottom[2] = NPCS.NPC->r.absmin[2]; - dist = ShortestLineSegBewteen2LineSegs( NPCS.NPC->enemy->client->renderInfo.muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint ); - if ( dist > NPCS.NPC->r.maxs[0]*5 )//was *3 - {//FIXME: sometimes he reacts when you're too far away to actually hit him - if ( d_JediAI.integer ) - { - Com_Printf( S_COLOR_RED"enemy saber dist: %4.2f\n", dist ); + dist = ShortestLineSegBewteen2LineSegs(NPCS.NPC->enemy->client->renderInfo.muzzlePoint, saberTip, bottom, top, saberPoint, axisPoint); + if (dist > NPCS.NPC->r.maxs[0] * 5) // was *3 + { // FIXME: sometimes he reacts when you're too far away to actually hit him + if (d_JediAI.integer) { + Com_Printf(S_COLOR_RED "enemy saber dist: %4.2f\n", dist); } /* if ( dist < 300 //close @@ -3197,44 +2510,36 @@ static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bl } else */ - { - TIMER_Set( NPCS.NPC, "parryTime", -1 ); - } + { TIMER_Set(NPCS.NPC, "parryTime", -1); } return qfalse; } - if ( d_JediAI.integer ) - { - Com_Printf( S_COLOR_GREEN"enemy saber dist: %4.2f\n", dist ); + if (d_JediAI.integer) { + Com_Printf(S_COLOR_GREEN "enemy saber dist: %4.2f\n", dist); } - VectorSubtract( saberPoint, NPCS.NPC->enemy->client->renderInfo.muzzlePoint, pointDir ); - pointDist = VectorLength( pointDir ); + VectorSubtract(saberPoint, NPCS.NPC->enemy->client->renderInfo.muzzlePoint, pointDir); + pointDist = VectorLength(pointDir); bladeLen = NPCS.NPC->enemy->client->saber[saberNum].blade[bladeNum].length; - if ( bladeLen <= 0 ) - { + if (bladeLen <= 0) { baseDirPerc = 0.5f; - } - else - { - baseDirPerc = pointDist/bladeLen; - } - VectorSubtract( NPCS.NPC->enemy->client->renderInfo.muzzlePoint, NPCS.NPC->enemy->client->renderInfo.muzzlePointOld, baseDir ); - VectorSubtract( saberTip, saberTipOld, tipDir ); - VectorScale( baseDir, baseDirPerc, baseDir ); - VectorMA( baseDir, 1.0f-baseDirPerc, tipDir, dir ); - VectorMA( saberPoint, 200, dir, hitloc ); - - //get the actual point of impact - trap->Trace( &tr, saberPoint, saberMins, saberMaxs, hitloc, NPCS.NPC->enemy->s.number, CONTENTS_BODY, qfalse, 0, 0 );//, G2_RETURNONHIT, 10 ); - if ( tr.allsolid || tr.startsolid || tr.fraction >= 1.0f ) - {//estimate - vec3_t dir2Me; - VectorSubtract( axisPoint, saberPoint, dir2Me ); - dist = VectorNormalize( dir2Me ); - if ( DotProduct( dir, dir2Me ) < 0.2f ) - {//saber is not swinging in my direction + } else { + baseDirPerc = pointDist / bladeLen; + } + VectorSubtract(NPCS.NPC->enemy->client->renderInfo.muzzlePoint, NPCS.NPC->enemy->client->renderInfo.muzzlePointOld, baseDir); + VectorSubtract(saberTip, saberTipOld, tipDir); + VectorScale(baseDir, baseDirPerc, baseDir); + VectorMA(baseDir, 1.0f - baseDirPerc, tipDir, dir); + VectorMA(saberPoint, 200, dir, hitloc); + + // get the actual point of impact + trap->Trace(&tr, saberPoint, saberMins, saberMaxs, hitloc, NPCS.NPC->enemy->s.number, CONTENTS_BODY, qfalse, 0, 0); //, G2_RETURNONHIT, 10 ); + if (tr.allsolid || tr.startsolid || tr.fraction >= 1.0f) { // estimate + vec3_t dir2Me; + VectorSubtract(axisPoint, saberPoint, dir2Me); + dist = VectorNormalize(dir2Me); + if (DotProduct(dir, dir2Me) < 0.2f) { // saber is not swinging in my direction /* if ( dist < 300 //close && !Jedi_QuickReactions( NPC )//quick reaction people can interrupt themselves @@ -3244,74 +2549,57 @@ static qboolean Jedi_SaberBlock( int saberNum, int bladeNum ) //saberNum = 0, bl } else */ - { - TIMER_Set( NPCS.NPC, "parryTime", -1 ); - } + { TIMER_Set(NPCS.NPC, "parryTime", -1); } return qfalse; } - ShortestLineSegBewteen2LineSegs( saberPoint, hitloc, bottom, top, saberHitPoint, hitloc ); + ShortestLineSegBewteen2LineSegs(saberPoint, hitloc, bottom, top, saberHitPoint, hitloc); /* VectorSubtract( saberPoint, axisPoint, dir ); VectorNormalize( dir ); VectorMA( axisPoint, NPC->r.maxs[0]*1.22, dir, hitloc ); */ - } - else - { - VectorCopy( tr.endpos, hitloc ); + } else { + VectorCopy(tr.endpos, hitloc); } - if ( d_JediAI.integer ) - { - //G_DebugLine( saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor( NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].color ), qtrue ); + if (d_JediAI.integer) { + // G_DebugLine( saberPoint, hitloc, FRAMETIME, WPDEBUG_SaberColor( NPC->enemy->client->ps.saber[saberNum].blade[bladeNum].color ), qtrue ); G_TestLine(saberPoint, hitloc, 0x0000ff, FRAMETIME); } - //FIXME: if saber is off and/or we have force speed and want to be really cocky, + // FIXME: if saber is off and/or we have force speed and want to be really cocky, // and the swing misses by some amount, we can use the dodges here... :) - if ( (evasionType=Jedi_SaberBlockGo( NPCS.NPC, &NPCS.ucmd, hitloc, dir, NULL, dist )) != EVASION_DODGE ) - {//we did block (not dodge) + if ((evasionType = Jedi_SaberBlockGo(NPCS.NPC, &NPCS.ucmd, hitloc, dir, NULL, dist)) != EVASION_DODGE) { // we did block (not dodge) int parryReCalcTime; - if ( !NPCS.NPC->client->ps.saberInFlight ) - {//make sure saber is on + if (!NPCS.NPC->client->ps.saberInFlight) { // make sure saber is on WP_ActivateSaber(NPCS.NPC); } - //debounce our parry recalc time - parryReCalcTime = Jedi_ReCalcParryTime( NPCS.NPC, evasionType ); - TIMER_Set( NPCS.NPC, "parryReCalcTime", Q_irand( 0, parryReCalcTime ) ); - if ( d_JediAI.integer ) - { - Com_Printf( "Keep parry choice until: %d\n", level.time + parryReCalcTime ); + // debounce our parry recalc time + parryReCalcTime = Jedi_ReCalcParryTime(NPCS.NPC, evasionType); + TIMER_Set(NPCS.NPC, "parryReCalcTime", Q_irand(0, parryReCalcTime)); + if (d_JediAI.integer) { + Com_Printf("Keep parry choice until: %d\n", level.time + parryReCalcTime); } - //determine how long to hold this anim - if ( TIMER_Done( NPCS.NPC, "parryTime" ) ) - { - if ( NPCS.NPC->client->NPC_class == CLASS_TAVION ) - { - TIMER_Set( NPCS.NPC, "parryTime", Q_irand( parryReCalcTime/2, parryReCalcTime*1.5 ) ); - } - else if ( NPCS.NPCInfo->rank >= RANK_LT_JG ) - {//fencers and higher hold a parry less - TIMER_Set( NPCS.NPC, "parryTime", parryReCalcTime ); - } - else - {//others hold it longer - TIMER_Set( NPCS.NPC, "parryTime", Q_irand( 1, 2 )*parryReCalcTime ); + // determine how long to hold this anim + if (TIMER_Done(NPCS.NPC, "parryTime")) { + if (NPCS.NPC->client->NPC_class == CLASS_TAVION) { + TIMER_Set(NPCS.NPC, "parryTime", Q_irand(parryReCalcTime / 2, parryReCalcTime * 1.5)); + } else if (NPCS.NPCInfo->rank >= RANK_LT_JG) { // fencers and higher hold a parry less + TIMER_Set(NPCS.NPC, "parryTime", parryReCalcTime); + } else { // others hold it longer + TIMER_Set(NPCS.NPC, "parryTime", Q_irand(1, 2) * parryReCalcTime); } } - } - else - { + } else { int dodgeTime = NPCS.NPC->client->ps.torsoTimer; - if ( NPCS.NPCInfo->rank > RANK_LT_COMM && NPCS.NPC->client->NPC_class != CLASS_DESANN ) - {//higher-level guys can dodge faster + if (NPCS.NPCInfo->rank > RANK_LT_COMM && NPCS.NPC->client->NPC_class != CLASS_DESANN) { // higher-level guys can dodge faster dodgeTime -= 200; } - TIMER_Set( NPCS.NPC, "parryReCalcTime", dodgeTime ); - TIMER_Set( NPCS.NPC, "parryTime", dodgeTime ); + TIMER_Set(NPCS.NPC, "parryReCalcTime", dodgeTime); + TIMER_Set(NPCS.NPC, "parryTime", dodgeTime); } return qtrue; } @@ -3322,191 +2610,146 @@ Jedi_EvasionSaber defend if other is using saber and attacking me! ------------------------- */ -static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir ) -{ - vec3_t dirEnemy2Me; - int evasionChance = 30;//only step aside 30% if he's moving at me but not attacking - qboolean enemy_attacking = qfalse; - qboolean throwing_saber = qfalse; - qboolean shooting_lightning = qfalse; - - if ( !NPCS.NPC->enemy->client ) - { +static void Jedi_EvasionSaber(vec3_t enemy_movedir, float enemy_dist, vec3_t enemy_dir) { + vec3_t dirEnemy2Me; + int evasionChance = 30; // only step aside 30% if he's moving at me but not attacking + qboolean enemy_attacking = qfalse; + qboolean throwing_saber = qfalse; + qboolean shooting_lightning = qfalse; + + if (!NPCS.NPC->enemy->client) { return; - } - else if ( NPCS.NPC->enemy->client - && NPCS.NPC->enemy->s.weapon == WP_SABER - && NPCS.NPC->enemy->client->ps.saberLockTime > level.time ) - {//don't try to block/evade an enemy who is in a saberLock + } else if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->s.weapon == WP_SABER && + NPCS.NPC->enemy->client->ps.saberLockTime > level.time) { // don't try to block/evade an enemy who is in a saberLock return; - } - else if ( NPCS.NPC->client->ps.saberEventFlags&SEF_LOCK_WON && NPCS.NPC->enemy->painDebounceTime > level.time ) - {//pressing the advantage of winning a saber lock + } else if (NPCS.NPC->client->ps.saberEventFlags & SEF_LOCK_WON && + NPCS.NPC->enemy->painDebounceTime > level.time) { // pressing the advantage of winning a saber lock return; } - if ( NPCS.NPC->enemy->client->ps.saberInFlight && !TIMER_Done( NPCS.NPC, "taunting" ) ) - {//if he's throwing his saber, stop taunting - TIMER_Set( NPCS.NPC, "taunting", -level.time ); - if ( !NPCS.NPC->client->ps.saberInFlight ) - { + if (NPCS.NPC->enemy->client->ps.saberInFlight && !TIMER_Done(NPCS.NPC, "taunting")) { // if he's throwing his saber, stop taunting + TIMER_Set(NPCS.NPC, "taunting", -level.time); + if (!NPCS.NPC->client->ps.saberInFlight) { WP_ActivateSaber(NPCS.NPC); } } - if ( TIMER_Done( NPCS.NPC, "parryTime" ) ) - { - if ( NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + if (TIMER_Done(NPCS.NPC, "parryTime")) { + if (NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPCS.NPC->enemy->client->ps.weaponTime && NPCS.NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - { - if ( !NPCS.NPC->client->ps.saberInFlight && Jedi_SaberBlock(0, 0) ) - { + if (NPCS.NPC->enemy->client->ps.weaponTime && NPCS.NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { + if (!NPCS.NPC->client->ps.saberInFlight && Jedi_SaberBlock(0, 0)) { return; } } - VectorSubtract( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, dirEnemy2Me ); - VectorNormalize( dirEnemy2Me ); + VectorSubtract(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, dirEnemy2Me); + VectorNormalize(dirEnemy2Me); - if ( NPCS.NPC->enemy->client->ps.weaponTime && NPCS.NPC->enemy->client->ps.weaponstate == WEAPON_FIRING ) - {//enemy is attacking + if (NPCS.NPC->enemy->client->ps.weaponTime && NPCS.NPC->enemy->client->ps.weaponstate == WEAPON_FIRING) { // enemy is attacking enemy_attacking = qtrue; evasionChance = 90; } - if ( (NPCS.NPC->enemy->client->ps.fd.forcePowersActive&(1<enemy->client->ps.fd.forcePowersActive & (1 << FP_LIGHTNING))) { // enemy is shooting lightning enemy_attacking = qtrue; shooting_lightning = qtrue; evasionChance = 50; } - if ( NPCS.NPC->enemy->client->ps.saberInFlight && NPCS.NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE && NPCS.NPC->enemy->client->ps.saberEntityState != SES_RETURNING ) - {//enemy is shooting lightning + if (NPCS.NPC->enemy->client->ps.saberInFlight && NPCS.NPC->enemy->client->ps.saberEntityNum != ENTITYNUM_NONE && + NPCS.NPC->enemy->client->ps.saberEntityState != SES_RETURNING) { // enemy is shooting lightning enemy_attacking = qtrue; throwing_saber = qtrue; } - //FIXME: this needs to take skill and rank(reborn type) into account much more - if ( Q_irand( 0, 100 ) < evasionChance ) - {//check to see if he's coming at me + // FIXME: this needs to take skill and rank(reborn type) into account much more + if (Q_irand(0, 100) < evasionChance) { // check to see if he's coming at me float facingAmt; - if ( VectorCompare( enemy_movedir, vec3_origin ) || shooting_lightning || throwing_saber ) - {//he's not moving (or he's using a ranged attack), see if he's facing me - vec3_t enemy_fwd; - AngleVectors( NPCS.NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL ); - facingAmt = DotProduct( enemy_fwd, dirEnemy2Me ); - } - else - {//he's moving - facingAmt = DotProduct( enemy_movedir, dirEnemy2Me ); + if (VectorCompare(enemy_movedir, vec3_origin) || shooting_lightning || + throwing_saber) { // he's not moving (or he's using a ranged attack), see if he's facing me + vec3_t enemy_fwd; + AngleVectors(NPCS.NPC->enemy->client->ps.viewangles, enemy_fwd, NULL, NULL); + facingAmt = DotProduct(enemy_fwd, dirEnemy2Me); + } else { // he's moving + facingAmt = DotProduct(enemy_movedir, dirEnemy2Me); } - if ( flrand( 0.25, 1 ) < facingAmt ) - {//coming at/facing me! + if (flrand(0.25, 1) < facingAmt) { // coming at/facing me! int whichDefense = 0; - if ( NPCS.NPC->client->ps.weaponTime || NPCS.NPC->client->ps.saberInFlight || NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - {//I'm attacking or recovering from a parry, can only try to strafe/jump right now - if ( Q_irand( 0, 10 ) < NPCS.NPCInfo->stats.aggression ) - { + if (NPCS.NPC->client->ps.weaponTime || NPCS.NPC->client->ps.saberInFlight || + NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { // I'm attacking or recovering from a parry, can only try to strafe/jump right now + if (Q_irand(0, 10) < NPCS.NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - { - if ( shooting_lightning ) - {//check for lightning attack - //only valid defense is strafe and/or jump + } else { + if (shooting_lightning) { // check for lightning attack + // only valid defense is strafe and/or jump whichDefense = 100; - } - else if ( throwing_saber ) - {//he's thrown his saber! See if it's coming at me - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (throwing_saber) { // he's thrown his saber! See if it's coming at me + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[NPCS.NPC->enemy->client->ps.saberEntityNum]; - VectorSubtract( NPCS.NPC->r.currentOrigin, saber->r.currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( !Q_irand( 0, 3 ) ) - { - //Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); - Jedi_Aggression( NPCS.NPC, 1 ); + VectorSubtract(NPCS.NPC->r.currentOrigin, saber->r.currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (!Q_irand(0, 3)) { + // Com_Printf( "(%d) raise agg - enemy threw saber\n", level.time ); + Jedi_Aggression(NPCS.NPC, 1); } - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 100 ) - {//it's close - whichDefense = Q_irand( 3, 6 ); - } - else if ( saberDist < 200 ) - {//got some time, yet, try pushing - whichDefense = Q_irand( 0, 8 ); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 100) { // it's close + whichDefense = Q_irand(3, 6); + } else if (saberDist < 200) { // got some time, yet, try pushing + whichDefense = Q_irand(0, 8); } } } - if ( whichDefense ) - {//already chose one - } - else if ( enemy_dist > 80 || !enemy_attacking ) - {//he's pretty far, or not swinging, just strafe - if ( VectorCompare( enemy_movedir, vec3_origin ) ) - {//if he's not moving, not swinging and far enough away, no evasion necc. + if (whichDefense) { // already chose one + } else if (enemy_dist > 80 || !enemy_attacking) { // he's pretty far, or not swinging, just strafe + if (VectorCompare(enemy_movedir, vec3_origin)) { // if he's not moving, not swinging and far enough away, no evasion necc. return; } - if ( Q_irand( 0, 10 ) < NPCS.NPCInfo->stats.aggression ) - { + if (Q_irand(0, 10) < NPCS.NPCInfo->stats.aggression) { return; } whichDefense = 100; - } - else - {//he's getting close and swinging at me - vec3_t fwd; - //see if I'm facing him - AngleVectors( NPCS.NPC->client->ps.viewangles, fwd, NULL, NULL ); - if ( DotProduct( enemy_dir, fwd ) < 0.5 ) - {//I'm not really facing him, best option is to strafe - whichDefense = Q_irand( 5, 16 ); - } - else if ( enemy_dist < 56 ) - {//he's very close, maybe we should be more inclined to block or throw - whichDefense = Q_irand( NPCS.NPCInfo->stats.aggression, 12 ); - } - else - { - whichDefense = Q_irand( 2, 16 ); + } else { // he's getting close and swinging at me + vec3_t fwd; + // see if I'm facing him + AngleVectors(NPCS.NPC->client->ps.viewangles, fwd, NULL, NULL); + if (DotProduct(enemy_dir, fwd) < 0.5) { // I'm not really facing him, best option is to strafe + whichDefense = Q_irand(5, 16); + } else if (enemy_dist < 56) { // he's very close, maybe we should be more inclined to block or throw + whichDefense = Q_irand(NPCS.NPCInfo->stats.aggression, 12); + } else { + whichDefense = Q_irand(2, 16); } } } - if ( whichDefense >= 4 && whichDefense <= 12 ) - {//would try to block - if ( NPCS.NPC->client->ps.saberInFlight ) - {//can't, saber in not in hand, so fall back to strafe/jump + if (whichDefense >= 4 && whichDefense <= 12) { // would try to block + if (NPCS.NPC->client->ps.saberInFlight) { // can't, saber in not in hand, so fall back to strafe/jump whichDefense = 100; } } - switch( whichDefense ) - { + switch (whichDefense) { case 0: case 1: case 2: case 3: - //use jedi force push? - //FIXME: try to do this if health low or enemy back to a cliff? - if ( (NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && TIMER_Done( NPCS.NPC, "parryTime" ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] - ForceThrow( NPCS.NPC, qfalse ); + // use jedi force push? + // FIXME: try to do this if health low or enemy back to a cliff? + if ((NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && + TIMER_Done(NPCS.NPC, "parryTime")) { // FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] + ForceThrow(NPCS.NPC, qfalse); } break; case 4: @@ -3518,94 +2761,72 @@ static void Jedi_EvasionSaber( vec3_t enemy_movedir, float enemy_dist, vec3_t en case 10: case 11: case 12: - //try to parry the blow - //Com_Printf( "blocking\n" ); + // try to parry the blow + // Com_Printf( "blocking\n" ); Jedi_SaberBlock(0, 0); break; default: - //Evade! - //start a strafe left/right if not already - if ( !Q_irand( 0, 5 ) || !Jedi_Strafe( 300, 1000, 0, 1000, qfalse ) ) - {//certain chance they will pick an alternative evasion - //if couldn't strafe, try a different kind of evasion... - if ( shooting_lightning || throwing_saber || enemy_dist < 80 ) - { - //FIXME: force-jump+forward - jump over the guy! - if ( shooting_lightning || (!Q_irand( 0, 2 ) && NPCS.NPCInfo->stats.aggression < 4 && TIMER_Done( NPCS.NPC, "parryTime" ) ) ) - { - if ( (NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && Q_irand( 0, 2 ) ) - {//FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] - ForceThrow( NPCS.NPC, qfalse ); - } - else if ( (NPCS.NPCInfo->rank==RANK_CREWMAN||NPCS.NPCInfo->rank>RANK_LT_JG) - && !(NPCS.NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && NPCS.NPC->client->ps.fd.forceRageRecoveryTime < level.time - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? + // Evade! + // start a strafe left/right if not already + if (!Q_irand(0, 5) || !Jedi_Strafe(300, 1000, 0, 1000, qfalse)) { // certain chance they will pick an alternative evasion + // if couldn't strafe, try a different kind of evasion... + if (shooting_lightning || throwing_saber || enemy_dist < 80) { + // FIXME: force-jump+forward - jump over the guy! + if (shooting_lightning || (!Q_irand(0, 2) && NPCS.NPCInfo->stats.aggression < 4 && TIMER_Done(NPCS.NPC, "parryTime"))) { + if ((NPCS.NPCInfo->rank == RANK_ENSIGN || NPCS.NPCInfo->rank > RANK_LT_JG) && !shooting_lightning && + Q_irand(0, 2)) { // FIXME: check forcePushRadius[NPC->client->ps.fd.forcePowerLevel[FP_PUSH]] + ForceThrow(NPCS.NPC, qfalse); + } else if ((NPCS.NPCInfo->rank == RANK_CREWMAN || NPCS.NPCInfo->rank > RANK_LT_JG) && + !(NPCS.NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && NPCS.NPC->client->ps.fd.forceRageRecoveryTime < level.time && + !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && + !PM_InKnockDown(&NPCS.NPC->client->ps)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? NPCS.NPC->client->ps.fd.forceJumpCharge = 480; - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPCS.NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); - if ( Q_irand( 0, 2 ) ) - { + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPCS.NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); + if (Q_irand(0, 2)) { NPCS.ucmd.forwardmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); - } - else - { + VectorClear(NPCS.NPC->client->ps.moveDir); + } else { NPCS.ucmd.forwardmove = -127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } - //FIXME: if this jump is cleared, we can't block... so pick a random lower block? - if ( Q_irand( 0, 1 ) )//FIXME: make intelligent + // FIXME: if this jump is cleared, we can't block... so pick a random lower block? + if (Q_irand(0, 1)) // FIXME: make intelligent { NPCS.NPC->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { NPCS.NPC->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - } - else if ( enemy_attacking ) - { + } else if (enemy_attacking) { Jedi_SaberBlock(0, 0); } } - } - else - {//strafed - if ( d_JediAI.integer ) - { - Com_Printf( "def strafe\n" ); + } else { // strafed + if (d_JediAI.integer) { + Com_Printf("def strafe\n"); } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_NO_ACROBATICS) - && NPCS.NPC->client->ps.fd.forceRageRecoveryTime < level.time - && !(NPCS.NPC->client->ps.fd.forcePowersActive&(1<rank == RANK_CREWMAN || NPCS.NPCInfo->rank > RANK_LT_JG ) - && !PM_InKnockDown( &NPCS.NPC->client->ps ) - && !Q_irand( 0, 5 ) ) - {//FIXME: make this a function call? - //FIXME: check for clearance, safety of landing spot? - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - NPCS.NPC->client->ps.fd.forceJumpCharge = 280;//FIXME: calc this intelligently? - } - else - { + if (!(NPCS.NPCInfo->scriptFlags & SCF_NO_ACROBATICS) && NPCS.NPC->client->ps.fd.forceRageRecoveryTime < level.time && + !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && + (NPCS.NPCInfo->rank == RANK_CREWMAN || NPCS.NPCInfo->rank > RANK_LT_JG) && !PM_InKnockDown(&NPCS.NPC->client->ps) && + !Q_irand(0, 5)) { // FIXME: make this a function call? + // FIXME: check for clearance, safety of landing spot? + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + NPCS.NPC->client->ps.fd.forceJumpCharge = 280; // FIXME: calc this intelligently? + } else { NPCS.NPC->client->ps.fd.forceJumpCharge = 320; } - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPCS.NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPCS.NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); } } break; } - //turn off slow walking no matter what - TIMER_Set( NPCS.NPC, "walking", -level.time ); - TIMER_Set( NPCS.NPC, "taunting", -level.time ); + // turn off slow walking no matter what + TIMER_Set(NPCS.NPC, "walking", -level.time); + TIMER_Set(NPCS.NPC, "taunting", -level.time); } } } @@ -3622,82 +2843,68 @@ static qboolean Jedi_Flee( void ) } */ - /* ========================================================================================== INTERNAL AI ROUTINES ========================================================================================== */ -gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float minDot ) -{ +gentity_t *Jedi_FindEnemyInCone(gentity_t *self, gentity_t *fallback, float minDot) { vec3_t forward, mins, maxs, dir; - float dist, bestDist = Q3_INFINITE; - gentity_t *enemy = fallback; - gentity_t *check = NULL; - int entityList[MAX_GENTITIES]; - int e, numListedEntities; - trace_t tr; - - if ( !self->client ) - { + float dist, bestDist = Q3_INFINITE; + gentity_t *enemy = fallback; + gentity_t *check = NULL; + int entityList[MAX_GENTITIES]; + int e, numListedEntities; + trace_t tr; + + if (!self->client) { return enemy; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); - for ( e = 0 ; e < 3 ; e++ ) - { + for (e = 0; e < 3; e++) { mins[e] = self->r.currentOrigin[e] - 1024; maxs[e] = self->r.currentOrigin[e] + 1024; } - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { check = &g_entities[entityList[e]]; - if ( check == self ) - {//me + if (check == self) { // me continue; } - if ( !(check->inuse) ) - {//freed + if (!(check->inuse)) { // freed continue; } - if ( !check->client ) - {//not a client - FIXME: what about turrets? + if (!check->client) { // not a client - FIXME: what about turrets? continue; } - if ( check->client->playerTeam != self->client->enemyTeam ) - {//not an enemy - FIXME: what about turrets? + if (check->client->playerTeam != self->client->enemyTeam) { // not an enemy - FIXME: what about turrets? continue; } - if ( check->health <= 0 ) - {//dead + if (check->health <= 0) { // dead continue; } - if ( !trap->InPVS( check->r.currentOrigin, self->r.currentOrigin ) ) - {//can't potentially see them + if (!trap->InPVS(check->r.currentOrigin, self->r.currentOrigin)) { // can't potentially see them continue; } - VectorSubtract( check->r.currentOrigin, self->r.currentOrigin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(check->r.currentOrigin, self->r.currentOrigin, dir); + dist = VectorNormalize(dir); - if ( DotProduct( dir, forward ) < minDot ) - {//not in front + if (DotProduct(dir, forward) < minDot) { // not in front continue; } - //really should have a clear LOS to this thing... - trap->Trace( &tr, self->r.currentOrigin, vec3_origin, vec3_origin, check->r.currentOrigin, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != check->s.number ) - {//must have clear shot + // really should have a clear LOS to this thing... + trap->Trace(&tr, self->r.currentOrigin, vec3_origin, vec3_origin, check->r.currentOrigin, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction < 1.0f && tr.entityNum != check->s.number) { // must have clear shot continue; } - if ( dist < bestDist ) - {//closer than our last best one + if (dist < bestDist) { // closer than our last best one dist = bestDist; enemy = check; } @@ -3705,33 +2912,29 @@ gentity_t *Jedi_FindEnemyInCone( gentity_t *self, gentity_t *fallback, float min return enemy; } -static void Jedi_SetEnemyInfo( vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction ) -{ - if ( !NPCS.NPC || !NPCS.NPC->enemy ) - {//no valid enemy +static void Jedi_SetEnemyInfo(vec3_t enemy_dest, vec3_t enemy_dir, float *enemy_dist, vec3_t enemy_movedir, float *enemy_movespeed, int prediction) { + if (!NPCS.NPC || !NPCS.NPC->enemy) { // no valid enemy return; } - if ( !NPCS.NPC->enemy->client ) - { - VectorClear( enemy_movedir ); + if (!NPCS.NPC->enemy->client) { + VectorClear(enemy_movedir); *enemy_movespeed = 0; - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, enemy_dest ); - enemy_dest[2] += NPCS.NPC->enemy->r.mins[2] + 24;//get it's origin to a height I can work with - VectorSubtract( enemy_dest, NPCS.NPC->r.currentOrigin, enemy_dir ); - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - *enemy_dist = VectorNormalize( enemy_dir );// - (NPC->client->ps.saberLengthMax + NPC->r.maxs[0]*1.5 + 16); - } - else - {//see where enemy is headed - VectorCopy( NPCS.NPC->enemy->client->ps.velocity, enemy_movedir ); - *enemy_movespeed = VectorNormalize( enemy_movedir ); - //figure out where he'll be, say, 3 frames from now - VectorMA( NPCS.NPC->enemy->r.currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest ); - //figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is - VectorSubtract( enemy_dest, NPCS.NPC->r.currentOrigin, enemy_dir );//NPC->client->renderInfo.muzzlePoint - //FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... - *enemy_dist = VectorNormalize( enemy_dir ) - (NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0]*1.5 + 16); //just use the blade 0 len I guess - //FIXME: keep a group of enemies around me and use that info to make decisions... + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, enemy_dest); + enemy_dest[2] += NPCS.NPC->enemy->r.mins[2] + 24; // get it's origin to a height I can work with + VectorSubtract(enemy_dest, NPCS.NPC->r.currentOrigin, enemy_dir); + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + *enemy_dist = VectorNormalize(enemy_dir); // - (NPC->client->ps.saberLengthMax + NPC->r.maxs[0]*1.5 + 16); + } else { // see where enemy is headed + VectorCopy(NPCS.NPC->enemy->client->ps.velocity, enemy_movedir); + *enemy_movespeed = VectorNormalize(enemy_movedir); + // figure out where he'll be, say, 3 frames from now + VectorMA(NPCS.NPC->enemy->r.currentOrigin, *enemy_movespeed * 0.001 * prediction, enemy_movedir, enemy_dest); + // figure out what dir the enemy's estimated position is from me and how far from the tip of my saber he is + VectorSubtract(enemy_dest, NPCS.NPC->r.currentOrigin, enemy_dir); // NPC->client->renderInfo.muzzlePoint + // FIXME: enemy_dist calc needs to include all blade lengths, and include distance from hand to start of blade.... + *enemy_dist = + VectorNormalize(enemy_dir) - (NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0] * 1.5 + 16); // just use the blade 0 len I guess + // FIXME: keep a group of enemies around me and use that info to make decisions... // For instance, if there are multiple enemies, evade more, push them away // and use medium attacks. If enemies are using blasters, switch to fast. // If one jedi enemy, use strong attacks. Use grip when fighting one or @@ -3740,66 +2943,48 @@ static void Jedi_SetEnemyInfo( vec3_t enemy_dest, vec3_t enemy_dir, float *enemy } } -extern float WP_SpeedOfMissileForWeapon( int wp, qboolean alt_fire ); -static void Jedi_FaceEnemy( qboolean doPitch ) -{ - vec3_t enemy_eyes, eyes, angles; +extern float WP_SpeedOfMissileForWeapon(int wp, qboolean alt_fire); +static void Jedi_FaceEnemy(qboolean doPitch) { + vec3_t enemy_eyes, eyes, angles; - if ( NPCS.NPC == NULL ) + if (NPCS.NPC == NULL) return; - if ( NPCS.NPC->enemy == NULL ) + if (NPCS.NPC->enemy == NULL) return; - if ( NPCS.NPC->client->ps.fd.forcePowersActive & (1<client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 ) - {//don't update? + if (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_GRIP) && NPCS.NPC->client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1) { // don't update? NPCS.NPCInfo->desiredPitch = NPCS.NPC->client->ps.viewangles[PITCH]; NPCS.NPCInfo->desiredYaw = NPCS.NPC->client->ps.viewangles[YAW]; return; } - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, eyes ); - - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_eyes ); - - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT - && TIMER_Done( NPCS.NPC, "flameTime" ) - && NPCS.NPC->s.weapon != WP_NONE - && NPCS.NPC->s.weapon != WP_DISRUPTOR - && (NPCS.NPC->s.weapon != WP_ROCKET_LAUNCHER||!(NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE)) - && NPCS.NPC->s.weapon != WP_THERMAL - && NPCS.NPC->s.weapon != WP_TRIP_MINE - && NPCS.NPC->s.weapon != WP_DET_PACK - && NPCS.NPC->s.weapon != WP_STUN_BATON - /*&& NPC->s.weapon != WP_MELEE*/ ) - {//boba leads his enemy - if ( NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth*0.5f ) - {//lead - float missileSpeed = WP_SpeedOfMissileForWeapon( NPCS.NPC->s.weapon, ((qboolean)(NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE)) ); - if ( missileSpeed ) - { - float eDist = Distance( eyes, enemy_eyes ); - eDist /= missileSpeed;//How many seconds it will take to get to the enemy - VectorMA( enemy_eyes, eDist*flrand(0.95f,1.25f), NPCS.NPC->enemy->client->ps.velocity, enemy_eyes ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, eyes); + + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_eyes); + + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT && TIMER_Done(NPCS.NPC, "flameTime") && NPCS.NPC->s.weapon != WP_NONE && + NPCS.NPC->s.weapon != WP_DISRUPTOR && (NPCS.NPC->s.weapon != WP_ROCKET_LAUNCHER || !(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) && + NPCS.NPC->s.weapon != WP_THERMAL && NPCS.NPC->s.weapon != WP_TRIP_MINE && NPCS.NPC->s.weapon != WP_DET_PACK && NPCS.NPC->s.weapon != WP_STUN_BATON + /*&& NPC->s.weapon != WP_MELEE*/) { // boba leads his enemy + if (NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth * 0.5f) { // lead + float missileSpeed = WP_SpeedOfMissileForWeapon(NPCS.NPC->s.weapon, ((qboolean)(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE))); + if (missileSpeed) { + float eDist = Distance(eyes, enemy_eyes); + eDist /= missileSpeed; // How many seconds it will take to get to the enemy + VectorMA(enemy_eyes, eDist * flrand(0.95f, 1.25f), NPCS.NPC->enemy->client->ps.velocity, enemy_eyes); } } } - //Find the desired angles - if ( !NPCS.NPC->client->ps.saberInFlight - && (NPCS.NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 - || NPCS.NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 - || NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK_BACK) - ) - {//point *away* - GetAnglesForDirection( enemy_eyes, eyes, angles ); - } - else - {//point towards him - GetAnglesForDirection( eyes, enemy_eyes, angles ); + // Find the desired angles + if (!NPCS.NPC->client->ps.saberInFlight && (NPCS.NPC->client->ps.legsAnim == BOTH_A2_STABBACK1 || NPCS.NPC->client->ps.legsAnim == BOTH_CROUCHATTACKBACK1 || + NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK_BACK)) { // point *away* + GetAnglesForDirection(enemy_eyes, eyes, angles); + } else { // point towards him + GetAnglesForDirection(eyes, enemy_eyes, angles); } - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); /* if ( NPC->client->ps.saberBlocked == BLOCKED_UPPER_LEFT ) {//temp hack- to make up for poor coverage on left side @@ -3807,242 +2992,170 @@ static void Jedi_FaceEnemy( qboolean doPitch ) } */ - if ( doPitch ) - { - NPCS.NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); - if ( NPCS.NPC->client->ps.saberInFlight ) - {//tilt down a little + if (doPitch) { + NPCS.NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); + if (NPCS.NPC->client->ps.saberInFlight) { // tilt down a little NPCS.NPCInfo->desiredPitch += 10; } } - //FIXME: else desiredPitch = 0? Or keep previous? + // FIXME: else desiredPitch = 0? Or keep previous? } -static void Jedi_DebounceDirectionChanges( void ) -{ - //FIXME: check these before making fwd/back & right/left decisions? - //Time-debounce changes in forward/back dir - if ( NPCS.ucmd.forwardmove > 0 ) - { - if ( !TIMER_Done( NPCS.NPC, "moveback" ) || !TIMER_Done( NPCS.NPC, "movenone" ) ) - { +static void Jedi_DebounceDirectionChanges(void) { + // FIXME: check these before making fwd/back & right/left decisions? + // Time-debounce changes in forward/back dir + if (NPCS.ucmd.forwardmove > 0) { + if (!TIMER_Done(NPCS.NPC, "moveback") || !TIMER_Done(NPCS.NPC, "movenone")) { NPCS.ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( NPCS.ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (NPCS.ucmd.rightmove > 0) { NPCS.ucmd.rightmove = 127; - } - else if ( NPCS.ucmd.rightmove < 0 ) - { + } else if (NPCS.ucmd.rightmove < 0) { NPCS.ucmd.rightmove = -127; } - VectorClear( NPCS.NPC->client->ps.moveDir ); - TIMER_Set( NPCS.NPC, "moveback", -level.time ); - if ( TIMER_Done( NPCS.NPC, "movenone" ) ) - { - TIMER_Set( NPCS.NPC, "movenone", Q_irand( 1000, 2000 ) ); + VectorClear(NPCS.NPC->client->ps.moveDir); + TIMER_Set(NPCS.NPC, "moveback", -level.time); + if (TIMER_Done(NPCS.NPC, "movenone")) { + TIMER_Set(NPCS.NPC, "movenone", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPCS.NPC, "moveforward")) { // FIXME: should be if it's zero? + TIMER_Set(NPCS.NPC, "moveforward", Q_irand(500, 2000)); } - else if ( TIMER_Done( NPCS.NPC, "moveforward" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPCS.NPC, "moveforward", Q_irand( 500, 2000 ) ); - } - } - else if ( NPCS.ucmd.forwardmove < 0 ) - { - if ( !TIMER_Done( NPCS.NPC, "moveforward" ) || !TIMER_Done( NPCS.NPC, "movenone" ) ) - { + } else if (NPCS.ucmd.forwardmove < 0) { + if (!TIMER_Done(NPCS.NPC, "moveforward") || !TIMER_Done(NPCS.NPC, "movenone")) { NPCS.ucmd.forwardmove = 0; - //now we have to normalize the total movement again - if ( NPCS.ucmd.rightmove > 0 ) - { + // now we have to normalize the total movement again + if (NPCS.ucmd.rightmove > 0) { NPCS.ucmd.rightmove = 127; - } - else if ( NPCS.ucmd.rightmove < 0 ) - { + } else if (NPCS.ucmd.rightmove < 0) { NPCS.ucmd.rightmove = -127; } - VectorClear( NPCS.NPC->client->ps.moveDir ); - TIMER_Set( NPCS.NPC, "moveforward", -level.time ); - if ( TIMER_Done( NPCS.NPC, "movenone" ) ) - { - TIMER_Set( NPCS.NPC, "movenone", Q_irand( 1000, 2000 ) ); + VectorClear(NPCS.NPC->client->ps.moveDir); + TIMER_Set(NPCS.NPC, "moveforward", -level.time); + if (TIMER_Done(NPCS.NPC, "movenone")) { + TIMER_Set(NPCS.NPC, "movenone", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPCS.NPC, "moveback")) { // FIXME: should be if it's zero? + TIMER_Set(NPCS.NPC, "moveback", Q_irand(250, 1000)); } - else if ( TIMER_Done( NPCS.NPC, "moveback" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPCS.NPC, "moveback", Q_irand( 250, 1000 ) ); - } - } - else if ( !TIMER_Done( NPCS.NPC, "moveforward" ) ) - {//NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? + } else if (!TIMER_Done(NPCS.NPC, "moveforward")) { // NOTE: edge checking should stop me if this is bad... but what if it sends us colliding into the enemy? NPCS.ucmd.forwardmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPCS.NPC, "moveback" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPCS.NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPCS.NPC, "moveback")) { // NOTE: edge checking should stop me if this is bad... NPCS.ucmd.forwardmove = -127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } - //Time-debounce changes in right/left dir - if ( NPCS.ucmd.rightmove > 0 ) - { - if ( !TIMER_Done( NPCS.NPC, "moveleft" ) || !TIMER_Done( NPCS.NPC, "movecenter" ) ) - { + // Time-debounce changes in right/left dir + if (NPCS.ucmd.rightmove > 0) { + if (!TIMER_Done(NPCS.NPC, "moveleft") || !TIMER_Done(NPCS.NPC, "movecenter")) { NPCS.ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( NPCS.ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (NPCS.ucmd.forwardmove > 0) { NPCS.ucmd.forwardmove = 127; - } - else if ( NPCS.ucmd.forwardmove < 0 ) - { + } else if (NPCS.ucmd.forwardmove < 0) { NPCS.ucmd.forwardmove = -127; } - VectorClear( NPCS.NPC->client->ps.moveDir ); - TIMER_Set( NPCS.NPC, "moveleft", -level.time ); - if ( TIMER_Done( NPCS.NPC, "movecenter" ) ) - { - TIMER_Set( NPCS.NPC, "movecenter", Q_irand( 1000, 2000 ) ); + VectorClear(NPCS.NPC->client->ps.moveDir); + TIMER_Set(NPCS.NPC, "moveleft", -level.time); + if (TIMER_Done(NPCS.NPC, "movecenter")) { + TIMER_Set(NPCS.NPC, "movecenter", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPCS.NPC, "moveright")) { // FIXME: should be if it's zero? + TIMER_Set(NPCS.NPC, "moveright", Q_irand(250, 1500)); } - else if ( TIMER_Done( NPCS.NPC, "moveright" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPCS.NPC, "moveright", Q_irand( 250, 1500 ) ); - } - } - else if ( NPCS.ucmd.rightmove < 0 ) - { - if ( !TIMER_Done( NPCS.NPC, "moveright" ) || !TIMER_Done( NPCS.NPC, "movecenter" ) ) - { + } else if (NPCS.ucmd.rightmove < 0) { + if (!TIMER_Done(NPCS.NPC, "moveright") || !TIMER_Done(NPCS.NPC, "movecenter")) { NPCS.ucmd.rightmove = 0; - //now we have to normalize the total movement again - if ( NPCS.ucmd.forwardmove > 0 ) - { + // now we have to normalize the total movement again + if (NPCS.ucmd.forwardmove > 0) { NPCS.ucmd.forwardmove = 127; - } - else if ( NPCS.ucmd.forwardmove < 0 ) - { + } else if (NPCS.ucmd.forwardmove < 0) { NPCS.ucmd.forwardmove = -127; } - VectorClear( NPCS.NPC->client->ps.moveDir ); - TIMER_Set( NPCS.NPC, "moveright", -level.time ); - if ( TIMER_Done( NPCS.NPC, "movecenter" ) ) - { - TIMER_Set( NPCS.NPC, "movecenter", Q_irand( 1000, 2000 ) ); + VectorClear(NPCS.NPC->client->ps.moveDir); + TIMER_Set(NPCS.NPC, "moveright", -level.time); + if (TIMER_Done(NPCS.NPC, "movecenter")) { + TIMER_Set(NPCS.NPC, "movecenter", Q_irand(1000, 2000)); } + } else if (TIMER_Done(NPCS.NPC, "moveleft")) { // FIXME: should be if it's zero? + TIMER_Set(NPCS.NPC, "moveleft", Q_irand(250, 1500)); } - else if ( TIMER_Done( NPCS.NPC, "moveleft" ) ) - {//FIXME: should be if it's zero? - TIMER_Set( NPCS.NPC, "moveleft", Q_irand( 250, 1500 ) ); - } - } - else if ( !TIMER_Done( NPCS.NPC, "moveright" ) ) - {//NOTE: edge checking should stop me if this is bad... + } else if (!TIMER_Done(NPCS.NPC, "moveright")) { // NOTE: edge checking should stop me if this is bad... NPCS.ucmd.rightmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); - } - else if ( !TIMER_Done( NPCS.NPC, "moveleft" ) ) - {//NOTE: edge checking should stop me if this is bad... + VectorClear(NPCS.NPC->client->ps.moveDir); + } else if (!TIMER_Done(NPCS.NPC, "moveleft")) { // NOTE: edge checking should stop me if this is bad... NPCS.ucmd.rightmove = -127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } } -static void Jedi_TimersApply( void ) -{ - if ( !NPCS.ucmd.rightmove ) - {//only if not already strafing - //FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too - if ( !TIMER_Done( NPCS.NPC, "strafeLeft" ) ) - { - if ( NPCS.NPCInfo->desiredYaw > NPCS.NPC->client->ps.viewangles[YAW] + 60 ) - {//we want to turn left, don't apply the strafing - } - else - {//go ahead and strafe left +static void Jedi_TimersApply(void) { + if (!NPCS.ucmd.rightmove) { // only if not already strafing + // FIXME: if enemy behind me and turning to face enemy, don't strafe in that direction, too + if (!TIMER_Done(NPCS.NPC, "strafeLeft")) { + if (NPCS.NPCInfo->desiredYaw > NPCS.NPC->client->ps.viewangles[YAW] + 60) { // we want to turn left, don't apply the strafing + } else { // go ahead and strafe left NPCS.ucmd.rightmove = -127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } - } - else if ( !TIMER_Done( NPCS.NPC, "strafeRight" ) ) - { - if ( NPCS.NPCInfo->desiredYaw < NPCS.NPC->client->ps.viewangles[YAW] - 60 ) - {//we want to turn right, don't apply the strafing - } - else - {//go ahead and strafe left + } else if (!TIMER_Done(NPCS.NPC, "strafeRight")) { + if (NPCS.NPCInfo->desiredYaw < NPCS.NPC->client->ps.viewangles[YAW] - 60) { // we want to turn right, don't apply the strafing + } else { // go ahead and strafe left NPCS.ucmd.rightmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } } } Jedi_DebounceDirectionChanges(); - //use careful anim/slower movement if not already moving - if ( !NPCS.ucmd.forwardmove && !TIMER_Done( NPCS.NPC, "walking" ) ) - { + // use careful anim/slower movement if not already moving + if (!NPCS.ucmd.forwardmove && !TIMER_Done(NPCS.NPC, "walking")) { NPCS.ucmd.buttons |= (BUTTON_WALKING); } - if ( !TIMER_Done( NPCS.NPC, "taunting" ) ) - { + if (!TIMER_Done(NPCS.NPC, "taunting")) { NPCS.ucmd.buttons |= (BUTTON_WALKING); } - if ( !TIMER_Done( NPCS.NPC, "gripping" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (!TIMER_Done(NPCS.NPC, "gripping")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around NPCS.ucmd.buttons |= BUTTON_FORCEGRIP; } - if ( !TIMER_Done( NPCS.NPC, "draining" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (!TIMER_Done(NPCS.NPC, "draining")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around NPCS.ucmd.buttons |= BUTTON_FORCE_DRAIN; } - if ( !TIMER_Done( NPCS.NPC, "holdLightning" ) ) - {//hold down the lightning key + if (!TIMER_Done(NPCS.NPC, "holdLightning")) { // hold down the lightning key NPCS.ucmd.buttons |= BUTTON_FORCE_LIGHTNING; } } -static void Jedi_CombatTimersUpdate( int enemy_dist ) -{ - if( Jedi_CultistDestroyer( NPCS.NPC ) ) - { - Jedi_Aggression( NPCS.NPC, 5 ); +static void Jedi_CombatTimersUpdate(int enemy_dist) { + if (Jedi_CultistDestroyer(NPCS.NPC)) { + Jedi_Aggression(NPCS.NPC, 5); return; } - if ( TIMER_Done( NPCS.NPC, "roamTime" ) ) - { - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 2000, 5000 ) ); - //okay, now mess with agression - if ( NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forceRageRecoveryTime > level.time ) - {//recovering - Jedi_Aggression( NPCS.NPC, Q_irand( -2, 0 ) ); + if (TIMER_Done(NPCS.NPC, "roamTime")) { + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(2000, 5000)); + // okay, now mess with agression + if (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) { // raging + Jedi_Aggression(NPCS.NPC, Q_irand(0, 3)); + } else if (NPCS.NPC->client->ps.fd.forceRageRecoveryTime > level.time) { // recovering + Jedi_Aggression(NPCS.NPC, Q_irand(-2, 0)); } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client ) - { - switch( NPCS.NPC->enemy->client->ps.weapon ) - { + if (NPCS.NPC->enemy && NPCS.NPC->enemy->client) { + switch (NPCS.NPC->enemy->client->ps.weapon) { case WP_SABER: - //If enemy has a lightsaber, always close in - if ( BG_SabersOff( &NPCS.NPC->enemy->client->ps ) ) - {//fool! Standing around unarmed, charge! - //Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); - Jedi_Aggression( NPCS.NPC, 2 ); - } - else - { - //Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); - Jedi_Aggression( NPCS.NPC, 1 ); + // If enemy has a lightsaber, always close in + if (BG_SabersOff(&NPCS.NPC->enemy->client->ps)) { // fool! Standing around unarmed, charge! + // Com_Printf( "(%d) raise agg - enemy saber off\n", level.time ); + Jedi_Aggression(NPCS.NPC, 2); + } else { + // Com_Printf( "(%d) raise agg - enemy saber\n", level.time ); + Jedi_Aggression(NPCS.NPC, 1); } break; case WP_BLASTER: @@ -4053,18 +3166,16 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) case WP_DEMP2: case WP_FLECHETTE: case WP_ROCKET_LAUNCHER: - //if he has a blaster, move in when: - //They're not shooting at me - if ( NPCS.NPC->enemy->attackDebounceTime < level.time ) - {//does this apply to players? - //Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); - Jedi_Aggression( NPCS.NPC, 1 ); + // if he has a blaster, move in when: + // They're not shooting at me + if (NPCS.NPC->enemy->attackDebounceTime < level.time) { // does this apply to players? + // Com_Printf( "(%d) raise agg - enemy not shooting ranged weap\n", level.time ); + Jedi_Aggression(NPCS.NPC, 1); } - //He's closer than a dist that gives us time to deflect - if ( enemy_dist < 256 ) - { - //Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); - Jedi_Aggression( NPCS.NPC, 1 ); + // He's closer than a dist that gives us time to deflect + if (enemy_dist < 256) { + // Com_Printf( "(%d) raise agg - enemy ranged weap- too close\n", level.time ); + Jedi_Aggression(NPCS.NPC, 1); } break; default: @@ -4073,31 +3184,23 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } - if ( TIMER_Done( NPCS.NPC, "noStrafe" ) && TIMER_Done( NPCS.NPC, "strafeLeft" ) && TIMER_Done( NPCS.NPC, "strafeRight" ) ) - { - //FIXME: Maybe more likely to do this if aggression higher? Or some other stat? - if ( !Q_irand( 0, 4 ) ) - {//start a strafe - if ( Jedi_Strafe( 1000, 3000, 0, 4000, qtrue ) ) - { - if ( d_JediAI.integer ) - { - Com_Printf( "off strafe\n" ); + if (TIMER_Done(NPCS.NPC, "noStrafe") && TIMER_Done(NPCS.NPC, "strafeLeft") && TIMER_Done(NPCS.NPC, "strafeRight")) { + // FIXME: Maybe more likely to do this if aggression higher? Or some other stat? + if (!Q_irand(0, 4)) { // start a strafe + if (Jedi_Strafe(1000, 3000, 0, 4000, qtrue)) { + if (d_JediAI.integer) { + Com_Printf("off strafe\n"); } } - } - else - {//postpone any strafing for a while - TIMER_Set( NPCS.NPC, "noStrafe", Q_irand( 1000, 3000 ) ); + } else { // postpone any strafing for a while + TIMER_Set(NPCS.NPC, "noStrafe", Q_irand(1000, 3000)); } } - if ( NPCS.NPC->client->ps.saberEventFlags ) - {//some kind of saber combat event is still pending + if (NPCS.NPC->client->ps.saberEventFlags) { // some kind of saber combat event is still pending int newFlags = NPCS.NPC->client->ps.saberEventFlags; - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_PARRIED ) - {//parried - TIMER_Set( NPCS.NPC, "parryTime", -1 ); + if (NPCS.NPC->client->ps.saberEventFlags & SEF_PARRIED) { // parried + TIMER_Set(NPCS.NPC, "parryTime", -1); /* if ( NPCInfo->rank >= RANK_LT_JG ) { @@ -4108,113 +3211,87 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } */ - if ( NPCS.NPC->enemy && PM_SaberInKnockaway( NPCS.NPC->enemy->client->ps.saberMove ) ) - {//advance! - Jedi_Aggression( NPCS.NPC, 1 );//get closer - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel-1) );//use a faster attack - } - else - { - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (NPCS.NPC->enemy && PM_SaberInKnockaway(NPCS.NPC->enemy->client->ps.saberMove)) { // advance! + Jedi_Aggression(NPCS.NPC, 1); // get closer + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel - 1)); // use a faster attack + } else { + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we parried\n", level.time ); - Jedi_Aggression( NPCS.NPC, -1 ); + // Com_Printf( "(%d) drop agg - we parried\n", level.time ); + Jedi_Aggression(NPCS.NPC, -1); } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel-1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel - 1)); } } - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCS.NPCInfo->stats.aggression, level.time + 100 ); + if (d_JediAI.integer) { + Com_Printf("(%d) PARRY: agg %d, no parry until %d\n", level.time, NPCS.NPCInfo->stats.aggression, level.time + 100); } newFlags &= ~SEF_PARRIED; } - if ( !NPCS.NPC->client->ps.weaponTime && (NPCS.NPC->client->ps.saberEventFlags&SEF_HITENEMY) )//hit enemy - {//we hit our enemy last time we swung, drop our aggression - if ( !Q_irand( 0, 1 ) )//FIXME: dependant on rank/diff? + if (!NPCS.NPC->client->ps.weaponTime && (NPCS.NPC->client->ps.saberEventFlags & SEF_HITENEMY)) // hit enemy + { // we hit our enemy last time we swung, drop our aggression + if (!Q_irand(0, 1)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); - Jedi_Aggression( NPCS.NPC, -1 ); - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) HIT: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression ); + // Com_Printf( "(%d) drop agg - we hit enemy\n", level.time ); + Jedi_Aggression(NPCS.NPC, -1); + if (d_JediAI.integer) { + Com_Printf("(%d) HIT: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression); } - if ( !Q_irand( 0, 3 ) - && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time - && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time - && NPCS.NPC->painDebounceTime < level.time - 1000 ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_GLOAT1, EV_GLOAT3 ), 3000 ); + if (!Q_irand(0, 3) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && NPCS.NPC->painDebounceTime < level.time - 1000) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_GLOAT1, EV_GLOAT3), 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } } - if ( !Q_irand( 0, 2 ) ) - { - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel+1) ); + if (!Q_irand(0, 2)) { + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel + 1)); } newFlags &= ~SEF_HITENEMY; } - if ( (NPCS.NPC->client->ps.saberEventFlags&SEF_BLOCKED) ) - {//was blocked whilst attacking - if ( PM_SaberInBrokenParry( NPCS.NPC->client->ps.saberMove ) - || NPCS.NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - { - //Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); - if ( NPCS.NPC->client->ps.saberInFlight ) - {//lost our saber, too!!! - Jedi_Aggression( NPCS.NPC, -5 );//really really really should back off!!! - } - else - { - Jedi_Aggression( NPCS.NPC, -2 );//really should back off! + if ((NPCS.NPC->client->ps.saberEventFlags & SEF_BLOCKED)) { // was blocked whilst attacking + if (PM_SaberInBrokenParry(NPCS.NPC->client->ps.saberMove) || NPCS.NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { + // Com_Printf( "(%d) drop agg - we were knock-blocked\n", level.time ); + if (NPCS.NPC->client->ps.saberInFlight) { // lost our saber, too!!! + Jedi_Aggression(NPCS.NPC, -5); // really really really should back off!!! + } else { + Jedi_Aggression(NPCS.NPC, -2); // really should back off! } - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel+1) );//use a stronger attack - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression ); + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel + 1)); // use a stronger attack + if (d_JediAI.integer) { + Com_Printf("(%d) KNOCK-BLOCKED: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression); } - } - else - { - if ( !Q_irand( 0, 2 ) )//FIXME: dependant on rank/diff? + } else { + if (!Q_irand(0, 2)) // FIXME: dependant on rank/diff? { - //Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); - Jedi_Aggression( NPCS.NPC, -1 ); - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) BLOCKED: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression ); + // Com_Printf( "(%d) drop agg - we were blocked\n", level.time ); + Jedi_Aggression(NPCS.NPC, -1); + if (d_JediAI.integer) { + Com_Printf("(%d) BLOCKED: agg %d\n", level.time, NPCS.NPCInfo->stats.aggression); } } - if ( !Q_irand( 0, 1 ) ) - { - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel+1) ); + if (!Q_irand(0, 1)) { + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel + 1)); } } newFlags &= ~SEF_BLOCKED; - //FIXME: based on the type of parry the enemy is doing and my skill, + // FIXME: based on the type of parry the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. } - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_DEFLECTED ) - {//deflected a shot + if (NPCS.NPC->client->ps.saberEventFlags & SEF_DEFLECTED) { // deflected a shot newFlags &= ~SEF_DEFLECTED; - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel-1) ); + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel - 1)); } } - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_HITWALL ) - {//hit a wall + if (NPCS.NPC->client->ps.saberEventFlags & SEF_HITWALL) { // hit a wall newFlags &= ~SEF_HITWALL; } - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_HITOBJECT ) - {//hit some other damagable object - if ( !Q_irand( 0, 3 ) ) - { - Jedi_AdjustSaberAnimLevel( NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel-1) ); + if (NPCS.NPC->client->ps.saberEventFlags & SEF_HITOBJECT) { // hit some other damagable object + if (!Q_irand(0, 3)) { + Jedi_AdjustSaberAnimLevel(NPCS.NPC, (NPCS.NPC->client->ps.fd.saberAnimLevel - 1)); } newFlags &= ~SEF_HITOBJECT; } @@ -4222,181 +3299,144 @@ static void Jedi_CombatTimersUpdate( int enemy_dist ) } } -static void Jedi_CombatIdle( int enemy_dist ) -{ - if ( !TIMER_Done( NPCS.NPC, "parryTime" ) ) - { +static void Jedi_CombatIdle(int enemy_dist) { + if (!TIMER_Done(NPCS.NPC, "parryTime")) { return; } - if ( NPCS.NPC->client->ps.saberInFlight ) - {//don't do this idle stuff if throwing saber + if (NPCS.NPC->client->ps.saberInFlight) { // don't do this idle stuff if throwing saber return; } - if ( NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forceRageRecoveryTime > level.time ) - {//never taunt while raging or recovering from rage + if (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_RAGE) || + NPCS.NPC->client->ps.fd.forceRageRecoveryTime > level.time) { // never taunt while raging or recovering from rage return; } - //FIXME: make these distance numbers defines? - if ( enemy_dist >= 64 ) - {//FIXME: only do this if standing still? - //based on aggression, flaunt/taunt + // FIXME: make these distance numbers defines? + if (enemy_dist >= 64) { // FIXME: only do this if standing still? + // based on aggression, flaunt/taunt int chance = 20; - if ( NPCS.NPC->client->NPC_class == CLASS_SHADOWTROOPER ) - { + if (NPCS.NPC->client->NPC_class == CLASS_SHADOWTROOPER) { chance = 10; } - //FIXME: possibly throw local objects at enemy? - if ( Q_irand( 2, chance ) < NPCS.NPCInfo->stats.aggression ) - { - if ( TIMER_Done( NPCS.NPC, "chatter" ) && NPCS.NPC->client->ps.forceHandExtend == HANDEXTEND_NONE ) - {//FIXME: add more taunt behaviors - //FIXME: sometimes he turns it off, then turns it right back on again??? - if ( enemy_dist > 200 - && NPCS.NPC->client->NPC_class != CLASS_BOBAFETT - && !NPCS.NPC->client->ps.saberHolstered - && !Q_irand( 0, 5 ) ) - {//taunt even more, turn off the saber - //FIXME: don't do this if health low? - WP_DeactivateSaber( NPCS.NPC, qfalse ); - //Don't attack for a bit + // FIXME: possibly throw local objects at enemy? + if (Q_irand(2, chance) < NPCS.NPCInfo->stats.aggression) { + if (TIMER_Done(NPCS.NPC, "chatter") && NPCS.NPC->client->ps.forceHandExtend == HANDEXTEND_NONE) { // FIXME: add more taunt behaviors + // FIXME: sometimes he turns it off, then turns it right back on again??? + if (enemy_dist > 200 && NPCS.NPC->client->NPC_class != CLASS_BOBAFETT && !NPCS.NPC->client->ps.saberHolstered && + !Q_irand(0, 5)) { // taunt even more, turn off the saber + // FIXME: don't do this if health low? + WP_DeactivateSaber(NPCS.NPC, qfalse); + // Don't attack for a bit NPCS.NPCInfo->stats.aggression = 3; - //FIXME: maybe start strafing? - //debounce this - if ( NPCS.NPC->client->playerTeam != NPCTEAM_PLAYER && !Q_irand( 0, 1 )) - { - //NPC->client->ps.taunting = level.time + 100; + // FIXME: maybe start strafing? + // debounce this + if (NPCS.NPC->client->playerTeam != NPCTEAM_PLAYER && !Q_irand(0, 1)) { + // NPC->client->ps.taunting = level.time + 100; NPCS.NPC->client->ps.forceHandExtend = HANDEXTEND_JEDITAUNT; NPCS.NPC->client->ps.forceHandExtendTime = level.time + 5000; - TIMER_Set( NPCS.NPC, "chatter", Q_irand( 5000, 10000 ) ); - TIMER_Set( NPCS.NPC, "taunting", 5500 ); - } - else - { + TIMER_Set(NPCS.NPC, "chatter", Q_irand(5000, 10000)); + TIMER_Set(NPCS.NPC, "taunting", 5500); + } else { Jedi_BattleTaunt(); - TIMER_Set( NPCS.NPC, "taunting", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPCS.NPC, "taunting", Q_irand(5000, 10000)); } - } - else if ( Jedi_BattleTaunt() ) - {//FIXME: pick some anims + } else if (Jedi_BattleTaunt()) { // FIXME: pick some anims } } } } } -static qboolean Jedi_AttackDecide( int enemy_dist ) -{ +static qboolean Jedi_AttackDecide(int enemy_dist) { // Begin fixed cultist_destroyer AI - if ( Jedi_CultistDestroyer( NPCS.NPC ) ) - { // destroyer - if ( enemy_dist <= 32 ) - {//go boom! - //float? - //VectorClear( NPC->client->ps.velocity ); - //NPC->client->ps.gravity = 0; - //NPC->svFlags |= SVF_CUSTOM_GRAVITY; - //NPC->client->moveType = MT_FLYSWIM; - //NPC->flags |= FL_NO_KNOCKBACK; + if (Jedi_CultistDestroyer(NPCS.NPC)) { // destroyer + if (enemy_dist <= 32) { // go boom! + // float? + // VectorClear( NPC->client->ps.velocity ); + // NPC->client->ps.gravity = 0; + // NPC->svFlags |= SVF_CUSTOM_GRAVITY; + // NPC->client->moveType = MT_FLYSWIM; + // NPC->flags |= FL_NO_KNOCKBACK; NPCS.NPC->flags |= FL_GODMODE; NPCS.NPC->takedamage = qfalse; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - NPCS.NPC->client->ps.fd.forcePowersActive |= ( 1 << FP_RAGE ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_FORCE_RAGE, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + NPCS.NPC->client->ps.fd.forcePowersActive |= (1 << FP_RAGE); NPCS.NPC->painDebounceTime = NPCS.NPC->useDebounceTime = level.time + NPCS.NPC->client->ps.torsoTimer; return qtrue; } return qfalse; } - if ( NPCS.NPC->enemy->client - && NPCS.NPC->enemy->s.weapon == WP_SABER - && NPCS.NPC->enemy->client->ps.saberLockTime > level.time - && NPCS.NPC->client->ps.saberLockTime < level.time ) - {//enemy is in a saberLock and we are not + if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->client->ps.saberLockTime > level.time && + NPCS.NPC->client->ps.saberLockTime < level.time) { // enemy is in a saberLock and we are not return qfalse; } - if ( NPCS.NPC->client->ps.saberEventFlags&SEF_LOCK_WON ) - {//we won a saber lock, press the advantage with an attack! - int chance = 0; - if ( NPCS.NPC->client->NPC_class == CLASS_DESANN || NPCS.NPC->client->NPC_class == CLASS_LUKE || !Q_stricmp("Yoda",NPCS.NPC->NPC_type) ) - {//desann and luke + if (NPCS.NPC->client->ps.saberEventFlags & SEF_LOCK_WON) { // we won a saber lock, press the advantage with an attack! + int chance = 0; + if (NPCS.NPC->client->NPC_class == CLASS_DESANN || NPCS.NPC->client->NPC_class == CLASS_LUKE || + !Q_stricmp("Yoda", NPCS.NPC->NPC_type)) { // desann and luke chance = 20; - } - else if ( NPCS.NPC->client->NPC_class == CLASS_TAVION ) - {//tavion + } else if (NPCS.NPC->client->NPC_class == CLASS_TAVION) { // tavion chance = 10; - } - else if ( NPCS.NPC->client->NPC_class == CLASS_REBORN && NPCS.NPCInfo->rank == RANK_LT_JG ) - {//fencer + } else if (NPCS.NPC->client->NPC_class == CLASS_REBORN && NPCS.NPCInfo->rank == RANK_LT_JG) { // fencer chance = 5; - } - else - { + } else { chance = NPCS.NPCInfo->rank; } - if ( Q_irand( 0, 30 ) < chance ) - {//based on skill with some randomness - NPCS.NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON;//clear this now that we are using the opportunity - TIMER_Set( NPCS.NPC, "noRetreat", Q_irand( 500, 2000 ) ); - //FIXME: check enemy_dist? + if (Q_irand(0, 30) < chance) { // based on skill with some randomness + NPCS.NPC->client->ps.saberEventFlags &= ~SEF_LOCK_WON; // clear this now that we are using the opportunity + TIMER_Set(NPCS.NPC, "noRetreat", Q_irand(500, 2000)); + // FIXME: check enemy_dist? NPCS.NPC->client->ps.weaponTime = NPCS.NPCInfo->shotTime = NPCS.NPC->attackDebounceTime = 0; - //NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - WeaponThink( qtrue ); + WeaponThink(qtrue); return qtrue; } } - if ( NPCS.NPC->client->NPC_class == CLASS_TAVION || - ( NPCS.NPC->client->NPC_class == CLASS_REBORN && NPCS.NPCInfo->rank == RANK_LT_JG ) || - ( NPCS.NPC->client->NPC_class == CLASS_JEDI && NPCS.NPCInfo->rank == RANK_COMMANDER ) ) - {//tavion, fencers, jedi trainer are all good at following up a parry with an attack - if ( ( PM_SaberInParry( NPCS.NPC->client->ps.saberMove ) || PM_SaberInKnockaway( NPCS.NPC->client->ps.saberMove ) ) - && NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//try to attack straight from a parry + if (NPCS.NPC->client->NPC_class == CLASS_TAVION || (NPCS.NPC->client->NPC_class == CLASS_REBORN && NPCS.NPCInfo->rank == RANK_LT_JG) || + (NPCS.NPC->client->NPC_class == CLASS_JEDI && + NPCS.NPCInfo->rank == RANK_COMMANDER)) { // tavion, fencers, jedi trainer are all good at following up a parry with an attack + if ((PM_SaberInParry(NPCS.NPC->client->ps.saberMove) || PM_SaberInKnockaway(NPCS.NPC->client->ps.saberMove)) && + NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // try to attack straight from a parry NPCS.NPC->client->ps.weaponTime = NPCS.NPCInfo->shotTime = NPCS.NPC->attackDebounceTime = 0; - //NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; + // NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - Jedi_AdjustSaberAnimLevel( NPCS.NPC, FORCE_LEVEL_1 );//try to follow-up with a quick attack - WeaponThink( qtrue ); + Jedi_AdjustSaberAnimLevel(NPCS.NPC, FORCE_LEVEL_1); // try to follow-up with a quick attack + WeaponThink(qtrue); return qtrue; } } - //try to hit them if we can - if ( enemy_dist >= 64 ) - { + // try to hit them if we can + if (enemy_dist >= 64) { return qfalse; } - if ( !TIMER_Done( NPCS.NPC, "parryTime" ) ) - { + if (!TIMER_Done(NPCS.NPC, "parryTime")) { return qfalse; } - if ( (NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) ) - {//not allowed to attack + if ((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE)) { // not allowed to attack return qfalse; } - if ( !(NPCS.ucmd.buttons&BUTTON_ATTACK) && !(NPCS.ucmd.buttons&BUTTON_ALT_ATTACK) ) - {//not already attacking - //Try to attack - WeaponThink( qtrue ); + if (!(NPCS.ucmd.buttons & BUTTON_ATTACK) && !(NPCS.ucmd.buttons & BUTTON_ALT_ATTACK)) { // not already attacking + // Try to attack + WeaponThink(qtrue); } - //FIXME: Maybe try to push enemy off a ledge? + // FIXME: Maybe try to push enemy off a ledge? - //close enough to step forward + // close enough to step forward - //FIXME: an attack debounce timer other than the phaser debounce time? + // FIXME: an attack debounce timer other than the phaser debounce time? // or base it on aggression? - if ( NPCS.ucmd.buttons&BUTTON_ATTACK ) - {//attacking + if (NPCS.ucmd.buttons & BUTTON_ATTACK) { // attacking /* if ( enemy_dist > 32 && NPCInfo->stats.aggression >= 4 ) {//move forward if we're too far away and we're chasing him @@ -4407,28 +3447,23 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) ucmd.forwardmove = -127; } */ - //FIXME: based on the type of parry/attack the enemy is doing and my skill, + // FIXME: based on the type of parry/attack the enemy is doing and my skill, // choose an attack that is likely to get around the parry? // right now that's generic in the saber animation code, auto-picks // a next anim for me, but really should be AI-controlled. - //FIXME: have this interact with/override above strafing code? - if ( !NPCS.ucmd.rightmove ) - {//not already strafing - if ( !Q_irand( 0, 3 ) ) - {//25% chance of doing this - vec3_t right, dir2enemy; - - AngleVectors( NPCS.NPC->r.currentAngles, NULL, right, NULL ); - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentAngles, dir2enemy ); - if ( DotProduct( right, dir2enemy ) > 0 ) - {//he's to my right, strafe left + // FIXME: have this interact with/override above strafing code? + if (!NPCS.ucmd.rightmove) { // not already strafing + if (!Q_irand(0, 3)) { // 25% chance of doing this + vec3_t right, dir2enemy; + + AngleVectors(NPCS.NPC->r.currentAngles, NULL, right, NULL); + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentAngles, dir2enemy); + if (DotProduct(right, dir2enemy) > 0) { // he's to my right, strafe left NPCS.ucmd.rightmove = -127; - VectorClear( NPCS.NPC->client->ps.moveDir ); - } - else - {//he's to my left, strafe right + VectorClear(NPCS.NPC->client->ps.moveDir); + } else { // he's to my left, strafe right NPCS.ucmd.rightmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } } } @@ -4438,12 +3473,11 @@ static qboolean Jedi_AttackDecide( int enemy_dist ) return qfalse; } -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f -static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) -{//FIXME: if land on enemy, knock him down & jump off again +static qboolean Jedi_Jump(vec3_t dest, int goalEntNum) { // FIXME: if land on enemy, knock him down & jump off again /* if ( dest[2] - NPC->r.currentOrigin[2] < 64 && DistanceHorizontal( NPC->r.currentOrigin, dest ) > 256 ) {//a pretty horizontal jump, easy to fake: @@ -4466,176 +3500,144 @@ static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) } else */ - if ( 1 ) - { - float targetDist, shotSpeed = 300, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, - vec3_t targetDir, shotVel, failCase; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, timeStep = 500, hitCount = 0, maxHits = 7; - vec3_t lastPos, testPos, bottom; - - while ( hitCount < maxHits ) - { - VectorSubtract( dest, NPCS.NPC->r.currentOrigin, targetDir ); - targetDist = VectorNormalize( targetDir ); - - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + if (1) { + float targetDist, shotSpeed = 300, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, + vec3_t targetDir, shotVel, failCase; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, timeStep = 500, hitCount = 0, maxHits = 7; + vec3_t lastPos, testPos, bottom; + + while (hitCount < maxHits) { + VectorSubtract(dest, NPCS.NPC->r.currentOrigin, targetDir); + targetDist = VectorNormalize(targetDir); + + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * NPCS.NPC->client->ps.gravity; - if ( !hitCount ) - {//save the first one as the worst case scenario - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first one as the worst case scenario + VectorCopy(shotVel, failCase); } - if ( 1 )//tracePath ) - {//do a rough trace of the path + if (1) // tracePath ) + { // do a rough trace of the path blocked = qfalse; - VectorCopy( NPCS.NPC->r.currentOrigin, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(NPCS.NPC->r.currentOrigin, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( NPCS.NPC->r.currentOrigin, lastPos ); + VectorCopy(NPCS.NPC->r.currentOrigin, lastPos); - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); - } - BG_EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - if ( testPos[2] < lastPos[2] ) - {//going down, ignore botclip - trap->Trace( &trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? + // Trace just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - else - {//going up, check for botclip - trap->Trace( &trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); + BG_EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + if (testPos[2] < lastPos[2]) { // going down, ignore botclip + trap->Trace(&trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); + } else { // going up, check for botclip + trap->Trace(&trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask | CONTENTS_BOTCLIP, + qfalse, 0, 0); } - if ( trace.allsolid || trace.startsolid ) - { + if (trace.allsolid || trace.startsolid) { blocked = qtrue; break; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.entityNum == goalEntNum ) - {//hit the enemy, that's perfect! - //Hmm, don't want to land on him, though... + if (trace.fraction < 1.0f) { // hit something + if (trace.entityNum == goalEntNum) { // hit the enemy, that's perfect! + // Hmm, don't want to land on him, though... break; - } - else - { - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + } else { + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush blocked = qtrue; break; } - if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, dest ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, dest) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, dest ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, dest); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; break; } } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear - if ( trace.fraction >= 1.0f ) - {//hmm, make sure we'll land on the ground... - //FIXME: do we care how far below ourselves or our dest we'll land? - VectorCopy( trace.endpos, bottom ); + if (elapsedTime == floor(travelTime)) { // reached end, all clear + if (trace.fraction >= 1.0f) { // hmm, make sure we'll land on the ground... + // FIXME: do we care how far below ourselves or our dest we'll land? + VectorCopy(trace.endpos, bottom); bottom[2] -= 128; - trap->Trace( &trace, trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.fraction >= 1.0f ) - {//would fall too far + trap->Trace(&trace, trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.fraction >= 1.0f) { // would fall too far blocked = qtrue; } } break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - shotSpeed = 300 + ((hitCount-2) * 100);//from 100 to 900 (skipping 300) - if ( hitCount >= 2 ) - {//skip 300 since that was the first value we tested + shotSpeed = 300 + ((hitCount - 2) * 100); // from 100 to 900 (skipping 300) + if (hitCount >= 2) { // skip 300 since that was the first value we tested shotSpeed += 100; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) - //NOTE: or try failcase? - VectorCopy( failCase, NPCS.NPC->client->ps.velocity ); + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + // NOTE: or try failcase? + VectorCopy(failCase, NPCS.NPC->client->ps.velocity); } - VectorCopy( shotVel, NPCS.NPC->client->ps.velocity ); - } - else - {//a more complicated jump - vec3_t dir, p1, p2, apex; - float time, height, forward, z, xy, dist, apexHeight; + VectorCopy(shotVel, NPCS.NPC->client->ps.velocity); + } else { // a more complicated jump + vec3_t dir, p1, p2, apex; + float time, height, forward, z, xy, dist, apexHeight; - if ( NPCS.NPC->r.currentOrigin[2] > dest[2] )//NPCInfo->goalEntity->r.currentOrigin + if (NPCS.NPC->r.currentOrigin[2] > dest[2]) // NPCInfo->goalEntity->r.currentOrigin { - VectorCopy( NPCS.NPC->r.currentOrigin, p1 ); - VectorCopy( dest, p2 );//NPCInfo->goalEntity->r.currentOrigin - } - else if ( NPCS.NPC->r.currentOrigin[2] < dest[2] )//NPCInfo->goalEntity->r.currentOrigin - { - VectorCopy( dest, p1 );//NPCInfo->goalEntity->r.currentOrigin - VectorCopy( NPCS.NPC->r.currentOrigin, p2 ); - } - else + VectorCopy(NPCS.NPC->r.currentOrigin, p1); + VectorCopy(dest, p2); // NPCInfo->goalEntity->r.currentOrigin + } else if (NPCS.NPC->r.currentOrigin[2] < dest[2]) // NPCInfo->goalEntity->r.currentOrigin { - VectorCopy( NPCS.NPC->r.currentOrigin, p1 ); - VectorCopy( dest, p2 );//NPCInfo->goalEntity->r.currentOrigin + VectorCopy(dest, p1); // NPCInfo->goalEntity->r.currentOrigin + VectorCopy(NPCS.NPC->r.currentOrigin, p2); + } else { + VectorCopy(NPCS.NPC->r.currentOrigin, p1); + VectorCopy(dest, p2); // NPCInfo->goalEntity->r.currentOrigin } - //z = xy*xy - VectorSubtract( p2, p1, dir ); + // z = xy*xy + VectorSubtract(p2, p1, dir); dir[2] = 0; - //Get xy and z diffs - xy = VectorNormalize( dir ); + // Get xy and z diffs + xy = VectorNormalize(dir); z = p1[2] - p2[2]; - apexHeight = APEX_HEIGHT/2; + apexHeight = APEX_HEIGHT / 2; - //Determine most desirable apex height - //FIXME: length of xy will change curve of parabola, need to account for this - //somewhere... PARA_WIDTH + // Determine most desirable apex height + // FIXME: length of xy will change curve of parabola, need to account for this + // somewhere... PARA_WIDTH /* apexHeight = (APEX_HEIGHT * PARA_WIDTH/xy) + (APEX_HEIGHT * z/128); if ( apexHeight < APEX_HEIGHT * 0.5 ) @@ -4652,76 +3654,67 @@ static qboolean Jedi_Jump( vec3_t dest, int goalEntNum ) assert(z >= 0); -// Com_Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); + // Com_Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); xy -= z; xy *= 0.5; assert(xy > 0); - VectorMA( p1, xy, dir, apex ); + VectorMA(p1, xy, dir, apex); apex[2] += apexHeight; VectorCopy(apex, NPCS.NPC->pos1); - //Now we have the apex, aim for it + // Now we have the apex, aim for it height = apex[2] - NPCS.NPC->r.currentOrigin[2]; - time = sqrt( height / ( .5 * NPCS.NPC->client->ps.gravity ) );//was 0.5, but didn't work well for very long jumps - if ( !time ) - { - //Com_Printf( S_COLOR_RED"ERROR: no time in jump\n" ); + time = sqrt(height / (.5 * NPCS.NPC->client->ps.gravity)); // was 0.5, but didn't work well for very long jumps + if (!time) { + // Com_Printf( S_COLOR_RED"ERROR: no time in jump\n" ); return qfalse; } - VectorSubtract ( apex, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.velocity ); + VectorSubtract(apex, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.velocity); NPCS.NPC->client->ps.velocity[2] = 0; - dist = VectorNormalize( NPCS.NPC->client->ps.velocity ); + dist = VectorNormalize(NPCS.NPC->client->ps.velocity); - forward = dist / time * 1.25;//er... probably bad, but... - VectorScale( NPCS.NPC->client->ps.velocity, forward, NPCS.NPC->client->ps.velocity ); + forward = dist / time * 1.25; // er... probably bad, but... + VectorScale(NPCS.NPC->client->ps.velocity, forward, NPCS.NPC->client->ps.velocity); - //FIXME: Uh.... should we trace/EvaluateTrajectory this to make sure we have clearance and we land where we want? + // FIXME: Uh.... should we trace/EvaluateTrajectory this to make sure we have clearance and we land where we want? NPCS.NPC->client->ps.velocity[2] = time * NPCS.NPC->client->ps.gravity; - //Com_Printf("Jump Velocity: %4.2f, %4.2f, %4.2f\n", NPC->client->ps.velocity[0], NPC->client->ps.velocity[1], NPC->client->ps.velocity[2] ); + // Com_Printf("Jump Velocity: %4.2f, %4.2f, %4.2f\n", NPC->client->ps.velocity[0], NPC->client->ps.velocity[1], NPC->client->ps.velocity[2] ); } return qtrue; } -static qboolean Jedi_TryJump( gentity_t *goal ) -{//FIXME: never does a simple short, regular jump... - //FIXME: I need to be on ground too! - if ( (NPCS.NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { +static qboolean Jedi_TryJump(gentity_t *goal) { // FIXME: never does a simple short, regular jump... + // FIXME: I need to be on ground too! + if ((NPCS.NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { return qfalse; } - if ( TIMER_Done( NPCS.NPC, "jumpChaseDebounce" ) ) - { - if ( (!goal->client || goal->client->ps.groundEntityNum != ENTITYNUM_NONE) ) - { - if ( !PM_InKnockDown( &NPCS.NPC->client->ps ) && !BG_InRoll( &NPCS.NPC->client->ps, NPCS.NPC->client->ps.legsAnim ) ) - {//enemy is on terra firma + if (TIMER_Done(NPCS.NPC, "jumpChaseDebounce")) { + if ((!goal->client || goal->client->ps.groundEntityNum != ENTITYNUM_NONE)) { + if (!PM_InKnockDown(&NPCS.NPC->client->ps) && !BG_InRoll(&NPCS.NPC->client->ps, NPCS.NPC->client->ps.legsAnim)) { // enemy is on terra firma vec3_t goal_diff; float goal_z_diff; float goal_xy_dist; - VectorSubtract( goal->r.currentOrigin, NPCS.NPC->r.currentOrigin, goal_diff ); + VectorSubtract(goal->r.currentOrigin, NPCS.NPC->r.currentOrigin, goal_diff); goal_z_diff = goal_diff[2]; goal_diff[2] = 0; - goal_xy_dist = VectorNormalize( goal_diff ); - if ( goal_xy_dist < 550 && goal_z_diff > -400/*was -256*/ )//for now, jedi don't take falling damage && (NPC->health > 20 || goal_z_diff > 0 ) && (NPC->health >= 100 || goal_z_diff > -128 ))//closer than @512 + goal_xy_dist = VectorNormalize(goal_diff); + if (goal_xy_dist < 550 && goal_z_diff > -400 /*was -256*/) // for now, jedi don't take falling damage && (NPC->health > 20 || goal_z_diff > 0 ) + // && (NPC->health >= 100 || goal_z_diff > -128 ))//closer than @512 { qboolean debounce = qfalse; - if ( NPCS.NPC->health < 150 && ((NPCS.NPC->health < 30 && goal_z_diff < 0) || goal_z_diff < -128 ) ) - {//don't jump, just walk off... doesn't help with ledges, though + if (NPCS.NPC->health < 150 && + ((NPCS.NPC->health < 30 && goal_z_diff < 0) || goal_z_diff < -128)) { // don't jump, just walk off... doesn't help with ledges, though debounce = qtrue; - } - else if ( goal_z_diff < 32 && goal_xy_dist < 200 ) - {//what is their ideal jump height? + } else if (goal_z_diff < 32 && goal_xy_dist < 200) { // what is their ideal jump height? NPCS.ucmd.upmove = 127; debounce = qtrue; - } - else - { + } else { /* //NO! All Jedi can jump-navigate now... if ( NPCInfo->rank != RANK_CREWMAN && NPCInfo->rank <= RANK_LT_JG ) @@ -4729,54 +3722,42 @@ static qboolean Jedi_TryJump( gentity_t *goal ) return qfalse; } */ - if ( goal_z_diff > 0 || goal_xy_dist > 128 ) - {//Fake a force-jump - //Screw it, just do my own calc & throw + if (goal_z_diff > 0 || goal_xy_dist > 128) { // Fake a force-jump + // Screw it, just do my own calc & throw vec3_t dest; - VectorCopy( goal->r.currentOrigin, dest ); - if ( goal == NPCS.NPC->enemy ) - { - int sideTry = 0; - while( sideTry < 10 ) - {//FIXME: make it so it doesn't try the same spot again? - trace_t trace; - vec3_t bottom; - - if ( Q_irand( 0, 1 ) ) - { - dest[0] += NPCS.NPC->enemy->r.maxs[0]*1.25; - } - else - { - dest[0] += NPCS.NPC->enemy->r.mins[0]*1.25; + VectorCopy(goal->r.currentOrigin, dest); + if (goal == NPCS.NPC->enemy) { + int sideTry = 0; + while (sideTry < 10) { // FIXME: make it so it doesn't try the same spot again? + trace_t trace; + vec3_t bottom; + + if (Q_irand(0, 1)) { + dest[0] += NPCS.NPC->enemy->r.maxs[0] * 1.25; + } else { + dest[0] += NPCS.NPC->enemy->r.mins[0] * 1.25; } - if ( Q_irand( 0, 1 ) ) - { - dest[1] += NPCS.NPC->enemy->r.maxs[1]*1.25; + if (Q_irand(0, 1)) { + dest[1] += NPCS.NPC->enemy->r.maxs[1] * 1.25; + } else { + dest[1] += NPCS.NPC->enemy->r.mins[1] * 1.25; } - else - { - dest[1] += NPCS.NPC->enemy->r.mins[1]*1.25; - } - VectorCopy( dest, bottom ); + VectorCopy(dest, bottom); bottom[2] -= 128; - trap->Trace( &trace, dest, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, goal->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.fraction < 1.0f ) - {//hit floor, okay to land here + trap->Trace(&trace, dest, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, goal->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.fraction < 1.0f) { // hit floor, okay to land here break; } sideTry++; } - if ( sideTry >= 10 ) - {//screw it, just jump right at him? - VectorCopy( goal->r.currentOrigin, dest ); + if (sideTry >= 10) { // screw it, just jump right at him? + VectorCopy(goal->r.currentOrigin, dest); } } - if ( Jedi_Jump( dest, goal->s.number ) ) - { - //Com_Printf( "(%d) pre-checked force jump\n", level.time ); + if (Jedi_Jump(dest, goal->s.number)) { + // Com_Printf( "(%d) pre-checked force jump\n", level.time ); - //FIXME: store the dir we;re going in in case something gets in the way of the jump? + // FIXME: store the dir we;re going in in case something gets in the way of the jump? //? = vectoyaw( NPC->client->ps.velocity ); /* if ( NPC->client->ps.velocity[2] < 320 ) @@ -4785,48 +3766,41 @@ static qboolean Jedi_TryJump( gentity_t *goal ) } else */ - {//FIXME: make this a function call + { // FIXME: make this a function call int jumpAnim; - //FIXME: this should be more intelligent, like the normal force jump anim logic - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT - ||( NPCS.NPCInfo->rank != RANK_CREWMAN && NPCS.NPCInfo->rank <= RANK_LT_JG ) ) - {//can't do acrobatics + // FIXME: this should be more intelligent, like the normal force jump anim logic + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT || + (NPCS.NPCInfo->rank != RANK_CREWMAN && NPCS.NPCInfo->rank <= RANK_LT_JG)) { // can't do acrobatics jumpAnim = BOTH_FORCEJUMP1; - } - else - { + } else { jumpAnim = BOTH_FLIP_F; } - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, jumpAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } NPCS.NPC->client->ps.fd.forceJumpZStart = NPCS.NPC->r.currentOrigin[2]; - //NPC->client->ps.pm_flags |= PMF_JUMPING; + // NPC->client->ps.pm_flags |= PMF_JUMPING; NPCS.NPC->client->ps.weaponTime = NPCS.NPC->client->ps.torsoTimer; - NPCS.NPC->client->ps.fd.forcePowersActive |= ( 1 << FP_LEVITATION ); - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - G_SoundOnEnt( NPCS.NPC, CHAN_ITEM, "sound/boba/jeton.wav" ); - NPCS.NPC->client->jetPackTime = level.time + Q_irand( 1000, 3000 ); - } - else - { - G_SoundOnEnt( NPCS.NPC, CHAN_BODY, "sound/weapons/force/jump.wav" ); + NPCS.NPC->client->ps.fd.forcePowersActive |= (1 << FP_LEVITATION); + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + G_SoundOnEnt(NPCS.NPC, CHAN_ITEM, "sound/boba/jeton.wav"); + NPCS.NPC->client->jetPackTime = level.time + Q_irand(1000, 3000); + } else { + G_SoundOnEnt(NPCS.NPC, CHAN_BODY, "sound/weapons/force/jump.wav"); } - TIMER_Set( NPCS.NPC, "forceJumpChasing", Q_irand( 2000, 3000 ) ); + TIMER_Set(NPCS.NPC, "forceJumpChasing", Q_irand(2000, 3000)); debounce = qtrue; } } } - if ( debounce ) - { - //Don't jump again for another 2 to 5 seconds - TIMER_Set( NPCS.NPC, "jumpChaseDebounce", Q_irand( 2000, 5000 ) ); + if (debounce) { + // Don't jump again for another 2 to 5 seconds + TIMER_Set(NPCS.NPC, "jumpChaseDebounce", Q_irand(2000, 5000)); NPCS.ucmd.forwardmove = 127; - VectorClear( NPCS.NPC->client->ps.moveDir ); - TIMER_Set( NPCS.NPC, "duck", -level.time ); + VectorClear(NPCS.NPC->client->ps.moveDir); + TIMER_Set(NPCS.NPC, "duck", -level.time); return qtrue; } } @@ -4836,21 +3810,17 @@ static qboolean Jedi_TryJump( gentity_t *goal ) return qfalse; } -static qboolean Jedi_Jumping( gentity_t *goal ) -{ - if ( !TIMER_Done( NPCS.NPC, "forceJumpChasing" ) && goal ) - {//force-jumping at the enemy -// if ( !(NPC->client->ps.pm_flags & PMF_JUMPING )//forceJumpZStart ) -// && !(NPC->client->ps.pm_flags&PMF_TRIGGER_PUSHED)) - if (NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) //rwwFIXMEFIXME: Not sure if this is gonna work, use the PM flags ideally. - {//landed - TIMER_Set( NPCS.NPC, "forceJumpChasing", 0 ); - } - else - { - NPC_FaceEntity( goal, qtrue ); - //FIXME: push me torward where I was heading - //FIXME: if hit a ledge as soon as we jumped, we need to push toward our goal... must remember original jump dir and/or original jump dest +static qboolean Jedi_Jumping(gentity_t *goal) { + if (!TIMER_Done(NPCS.NPC, "forceJumpChasing") && goal) { // force-jumping at the enemy + // if ( !(NPC->client->ps.pm_flags & PMF_JUMPING )//forceJumpZStart ) + // && !(NPC->client->ps.pm_flags&PMF_TRIGGER_PUSHED)) + if (NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE) // rwwFIXMEFIXME: Not sure if this is gonna work, use the PM flags ideally. + { // landed + TIMER_Set(NPCS.NPC, "forceJumpChasing", 0); + } else { + NPC_FaceEntity(goal, qtrue); + // FIXME: push me torward where I was heading + // FIXME: if hit a ledge as soon as we jumped, we need to push toward our goal... must remember original jump dir and/or original jump dest /* vec3_t viewangles_xy={0,0,0}, goal_dir, goal_xy_dir, forward, right; float goal_dist; @@ -4885,48 +3855,33 @@ static qboolean Jedi_Jumping( gentity_t *goal ) return qfalse; } -extern void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ); -static void Jedi_CheckEnemyMovement( float enemy_dist ) -{ - if ( !NPCS.NPC->enemy || !NPCS.NPC->enemy->client ) - { +extern void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir); +static void Jedi_CheckEnemyMovement(float enemy_dist) { + if (!NPCS.NPC->enemy || !NPCS.NPC->enemy->client) { return; } - if ( NPCS.NPC->client->NPC_class != CLASS_TAVION - && NPCS.NPC->client->NPC_class != CLASS_DESANN - && NPCS.NPC->client->NPC_class != CLASS_LUKE - && Q_stricmp("Yoda",NPCS.NPC->NPC_type) ) - { - if ( NPCS.NPC->enemy->enemy && NPCS.NPC->enemy->enemy == NPCS.NPC ) - {//enemy is mad at *me* - if ( NPCS.NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 || - NPCS.NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN ) - {//enemy is flipping over me - if ( Q_irand( 0, NPCS.NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + if (NPCS.NPC->client->NPC_class != CLASS_TAVION && NPCS.NPC->client->NPC_class != CLASS_DESANN && NPCS.NPC->client->NPC_class != CLASS_LUKE && + Q_stricmp("Yoda", NPCS.NPC->NPC_type)) { + if (NPCS.NPC->enemy->enemy && NPCS.NPC->enemy->enemy == NPCS.NPC) { // enemy is mad at *me* + if (NPCS.NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSLASHDOWN1 || + NPCS.NPC->enemy->client->ps.legsAnim == BOTH_JUMPFLIPSTABDOWN) { // enemy is flipping over me + if (Q_irand(0, NPCS.NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... NPCS.ucmd.forwardmove = NPCS.ucmd.rightmove = NPCS.ucmd.upmove = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); NPCS.NPC->client->ps.fd.forceJumpCharge = 0; - TIMER_Set( NPCS.NPC, "strafeLeft", -1 ); - TIMER_Set( NPCS.NPC, "strafeRight", -1 ); - TIMER_Set( NPCS.NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPCS.NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPCS.NPC, "movecenter", Q_irand( 500, 1000 ) ); + TIMER_Set(NPCS.NPC, "strafeLeft", -1); + TIMER_Set(NPCS.NPC, "strafeRight", -1); + TIMER_Set(NPCS.NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPCS.NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPCS.NPC, "movecenter", Q_irand(500, 1000)); } - } - else if ( NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 - || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT - || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT - || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP - || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP ) - {//he's flipping off a wall - if ( NPCS.NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//still in air - if ( enemy_dist < 256 ) - {//close - if ( Q_irand( 0, NPCS.NPCInfo->rank ) < RANK_LT ) - {//be nice and stand still for him... + } else if (NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_BACK1 || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_RIGHT || + NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_FLIP_LEFT || NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_LEFT_FLIP || + NPCS.NPC->enemy->client->ps.legsAnim == BOTH_WALL_RUN_RIGHT_FLIP) { // he's flipping off a wall + if (NPCS.NPC->enemy->client->ps.groundEntityNum == ENTITYNUM_NONE) { // still in air + if (enemy_dist < 256) { // close + if (Q_irand(0, NPCS.NPCInfo->rank) < RANK_LT) { // be nice and stand still for him... vec3_t enemyFwd, dest, dir; /* @@ -4940,61 +3895,50 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) TIMER_Set( NPC, "movecenter", Q_irand( 500, 1000 ) ); TIMER_Set( NPC, "noturn", Q_irand( 200, 500 ) ); */ - //stop current movement + // stop current movement NPCS.ucmd.forwardmove = NPCS.ucmd.rightmove = NPCS.ucmd.upmove = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); NPCS.NPC->client->ps.fd.forceJumpCharge = 0; - TIMER_Set( NPCS.NPC, "strafeLeft", -1 ); - TIMER_Set( NPCS.NPC, "strafeRight", -1 ); - TIMER_Set( NPCS.NPC, "noStrafe", Q_irand( 500, 1000 ) ); - TIMER_Set( NPCS.NPC, "noturn", Q_irand( 250, 500 )*(3-g_npcspskill.integer) ); - - VectorCopy( NPCS.NPC->enemy->client->ps.velocity, enemyFwd ); - VectorNormalize( enemyFwd ); - VectorMA( NPCS.NPC->enemy->r.currentOrigin, -64, enemyFwd, dest ); - VectorSubtract( dest, NPCS.NPC->r.currentOrigin, dir ); - if ( VectorNormalize( dir ) > 32 ) - { - G_UcmdMoveForDir( NPCS.NPC, &NPCS.ucmd, dir ); - } - else - { - TIMER_Set( NPCS.NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPCS.NPC, "movecenter", Q_irand( 500, 1000 ) ); + TIMER_Set(NPCS.NPC, "strafeLeft", -1); + TIMER_Set(NPCS.NPC, "strafeRight", -1); + TIMER_Set(NPCS.NPC, "noStrafe", Q_irand(500, 1000)); + TIMER_Set(NPCS.NPC, "noturn", Q_irand(250, 500) * (3 - g_npcspskill.integer)); + + VectorCopy(NPCS.NPC->enemy->client->ps.velocity, enemyFwd); + VectorNormalize(enemyFwd); + VectorMA(NPCS.NPC->enemy->r.currentOrigin, -64, enemyFwd, dest); + VectorSubtract(dest, NPCS.NPC->r.currentOrigin, dir); + if (VectorNormalize(dir) > 32) { + G_UcmdMoveForDir(NPCS.NPC, &NPCS.ucmd, dir); + } else { + TIMER_Set(NPCS.NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPCS.NPC, "movecenter", Q_irand(500, 1000)); } } } } - } - else if ( NPCS.NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1 ) - {//he's stabbing backwards - if ( enemy_dist < 256 && enemy_dist > 64 ) - {//close - if ( !InFront( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->enemy->r.currentAngles, 0.0f ) ) - {//behind him - if ( !Q_irand( 0, NPCS.NPCInfo->rank ) ) - {//be nice and stand still for him... + } else if (NPCS.NPC->enemy->client->ps.legsAnim == BOTH_A2_STABBACK1) { // he's stabbing backwards + if (enemy_dist < 256 && enemy_dist > 64) { // close + if (!InFront(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->enemy->r.currentAngles, 0.0f)) { // behind him + if (!Q_irand(0, NPCS.NPCInfo->rank)) { // be nice and stand still for him... vec3_t enemyFwd, dest, dir; - //stop current movement + // stop current movement NPCS.ucmd.forwardmove = NPCS.ucmd.rightmove = NPCS.ucmd.upmove = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); NPCS.NPC->client->ps.fd.forceJumpCharge = 0; - TIMER_Set( NPCS.NPC, "strafeLeft", -1 ); - TIMER_Set( NPCS.NPC, "strafeRight", -1 ); - TIMER_Set( NPCS.NPC, "noStrafe", Q_irand( 500, 1000 ) ); - - AngleVectors( NPCS.NPC->enemy->r.currentAngles, enemyFwd, NULL, NULL ); - VectorMA( NPCS.NPC->enemy->r.currentOrigin, -32, enemyFwd, dest ); - VectorSubtract( dest, NPCS.NPC->r.currentOrigin, dir ); - if ( VectorNormalize( dir ) > 64 ) - { - G_UcmdMoveForDir( NPCS.NPC, &NPCS.ucmd, dir ); - } - else - { - TIMER_Set( NPCS.NPC, "movenone", Q_irand( 500, 1000 ) ); - TIMER_Set( NPCS.NPC, "movecenter", Q_irand( 500, 1000 ) ); + TIMER_Set(NPCS.NPC, "strafeLeft", -1); + TIMER_Set(NPCS.NPC, "strafeRight", -1); + TIMER_Set(NPCS.NPC, "noStrafe", Q_irand(500, 1000)); + + AngleVectors(NPCS.NPC->enemy->r.currentAngles, enemyFwd, NULL, NULL); + VectorMA(NPCS.NPC->enemy->r.currentOrigin, -32, enemyFwd, dest); + VectorSubtract(dest, NPCS.NPC->r.currentOrigin, dir); + if (VectorNormalize(dir) > 64) { + G_UcmdMoveForDir(NPCS.NPC, &NPCS.ucmd, dir); + } else { + TIMER_Set(NPCS.NPC, "movenone", Q_irand(500, 1000)); + TIMER_Set(NPCS.NPC, "movecenter", Q_irand(500, 1000)); } } } @@ -5002,148 +3946,127 @@ static void Jedi_CheckEnemyMovement( float enemy_dist ) } } } - //FIXME: also: + // FIXME: also: // If enemy doing wall flip, keep running forward // If enemy doing back-attack and we're behind him keep running forward toward his back, don't strafe } -static void Jedi_CheckJumps( void ) -{ - vec3_t jumpVel; - trace_t trace; - trajectory_t tr; - vec3_t lastPos, testPos, bottom; - int elapsedTime; +static void Jedi_CheckJumps(void) { + vec3_t jumpVel; + trace_t trace; + trajectory_t tr; + vec3_t lastPos, testPos, bottom; + int elapsedTime; - if ( (NPCS.NPCInfo->scriptFlags&SCF_NO_ACROBATICS) ) - { + if ((NPCS.NPCInfo->scriptFlags & SCF_NO_ACROBATICS)) { NPCS.NPC->client->ps.fd.forceJumpCharge = 0; NPCS.ucmd.upmove = 0; return; } - //FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb - //FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? + // FIXME: should probably check this before AI decides that best move is to jump? Otherwise, they may end up just standing there and looking dumb + // FIXME: all this work and he still jumps off ledges... *sigh*... need CONTENTS_BOTCLIP do-not-enter brushes...? VectorClear(jumpVel); - if ( NPCS.NPC->client->ps.fd.forceJumpCharge ) - { - //Com_Printf( "(%d) force jump\n", level.time ); - WP_GetVelocityForForceJump( NPCS.NPC, jumpVel, &NPCS.ucmd ); - } - else if ( NPCS.ucmd.upmove > 0 ) - { - //Com_Printf( "(%d) regular jump\n", level.time ); - VectorCopy( NPCS.NPC->client->ps.velocity, jumpVel ); + if (NPCS.NPC->client->ps.fd.forceJumpCharge) { + // Com_Printf( "(%d) force jump\n", level.time ); + WP_GetVelocityForForceJump(NPCS.NPC, jumpVel, &NPCS.ucmd); + } else if (NPCS.ucmd.upmove > 0) { + // Com_Printf( "(%d) regular jump\n", level.time ); + VectorCopy(NPCS.NPC->client->ps.velocity, jumpVel); jumpVel[2] = JUMP_VELOCITY; - } - else - { + } else { return; } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( !jumpVel[0] && !jumpVel[1] )//FIXME: && !ucmd.forwardmove && !ucmd.rightmove? - {//we assume a jump straight up is safe - //Com_Printf( "(%d) jump straight up is safe\n", level.time ); + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (!jumpVel[0] && !jumpVel[1]) // FIXME: && !ucmd.forwardmove && !ucmd.rightmove? + { // we assume a jump straight up is safe + // Com_Printf( "(%d) jump straight up is safe\n", level.time ); return; } - //Now predict where this is going - //in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there + // Now predict where this is going + // in steps, keep evaluating the trajectory until the new z pos is <= than current z pos, trace down from there - VectorCopy( NPCS.NPC->r.currentOrigin, tr.trBase ); - VectorCopy( jumpVel, tr.trDelta ); + VectorCopy(NPCS.NPC->r.currentOrigin, tr.trBase); + VectorCopy(jumpVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; - VectorCopy( NPCS.NPC->r.currentOrigin, lastPos ); - - VectorClear(trace.endpos); //shut the compiler up - - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500 ) - { - BG_EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - //FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... - if ( testPos[2] < lastPos[2] ) - {//going down, don't check for BOTCLIP - trap->Trace( &trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 );//FIXME: include CONTENTS_BOTCLIP? - } - else - {//going up, check for BOTCLIP - trap->Trace( &trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - } - if ( trace.allsolid || trace.startsolid ) - {//WTF? - //FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? + VectorCopy(NPCS.NPC->r.currentOrigin, lastPos); + + VectorClear(trace.endpos); // shut the compiler up + + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to + // apex and down? + for (elapsedTime = 500; elapsedTime <= 4000; elapsedTime += 500) { + BG_EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + // FIXME: account for PM_AirMove if ucmd.forwardmove and/or ucmd.rightmove is non-zero... + if (testPos[2] < lastPos[2]) { // going down, don't check for BOTCLIP + trap->Trace(&trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, + 0); // FIXME: include CONTENTS_BOTCLIP? + } else { // going up, check for BOTCLIP + trap->Trace(&trace, lastPos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, testPos, NPCS.NPC->s.number, NPCS.NPC->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); + } + if (trace.allsolid || trace.startsolid) { // WTF? + // FIXME: what do we do when we start INSIDE the CONTENTS_BOTCLIP? Do the trace again without that clipmask? goto jump_unsafe; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.contents & CONTENTS_BOTCLIP ) - {//hit a do-not-enter brush + if (trace.fraction < 1.0f) { // hit something + if (trace.contents & CONTENTS_BOTCLIP) { // hit a do-not-enter brush goto jump_unsafe; } - //FIXME: trace through func_glass? + // FIXME: trace through func_glass? break; } - VectorCopy( testPos, lastPos ); + VectorCopy(testPos, lastPos); } - //okay, reached end of jump, now trace down from here for a floor - VectorCopy( trace.endpos, bottom ); - if ( bottom[2] > NPCS.NPC->r.currentOrigin[2] ) - {//only care about dist down from current height or lower + // okay, reached end of jump, now trace down from here for a floor + VectorCopy(trace.endpos, bottom); + if (bottom[2] > NPCS.NPC->r.currentOrigin[2]) { // only care about dist down from current height or lower bottom[2] = NPCS.NPC->r.currentOrigin[2]; - } - else if ( NPCS.NPC->r.currentOrigin[2] - bottom[2] > 400 ) - {//whoa, long drop, don't do it! - //probably no floor at end of jump, so don't jump + } else if (NPCS.NPC->r.currentOrigin[2] - bottom[2] > 400) { // whoa, long drop, don't do it! + // probably no floor at end of jump, so don't jump goto jump_unsafe; } bottom[2] -= 128; - trap->Trace( &trace, trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid || trace.startsolid || trace.fraction < 1.0f ) - {//hit ground! - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//landed on an ent + trap->Trace(&trace, trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, bottom, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0); + if (trace.allsolid || trace.startsolid || trace.fraction < 1.0f) { // hit ground! + if (trace.entityNum < ENTITYNUM_WORLD) { // landed on an ent gentity_t *groundEnt = &g_entities[trace.entityNum]; - if ( groundEnt->r.svFlags&SVF_GLASS_BRUSH ) - {//don't land on breakable glass! + if (groundEnt->r.svFlags & SVF_GLASS_BRUSH) { // don't land on breakable glass! goto jump_unsafe; } } - //Com_Printf( "(%d) jump is safe\n", level.time ); + // Com_Printf( "(%d) jump is safe\n", level.time ); return; } jump_unsafe: - //probably no floor at end of jump, so don't jump - //Com_Printf( "(%d) unsafe jump cleared\n", level.time ); + // probably no floor at end of jump, so don't jump + // Com_Printf( "(%d) unsafe jump cleared\n", level.time ); NPCS.NPC->client->ps.fd.forceJumpCharge = 0; NPCS.ucmd.upmove = 0; } -static void Jedi_Combat( void ) -{ - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - qboolean enemy_lost = qfalse; +static void Jedi_Combat(void) { + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + qboolean enemy_lost = qfalse; - //See where enemy will be 300 ms from now - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); + // See where enemy will be 300 ms from now + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); - if ( Jedi_Jumping( NPCS.NPC->enemy ) ) - {//I'm in the middle of a jump, so just see if I should attack - Jedi_AttackDecide( enemy_dist ); + if (Jedi_Jumping(NPCS.NPC->enemy)) { // I'm in the middle of a jump, so just see if I should attack + Jedi_AttackDecide(enemy_dist); return; } - if ( !(NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2 ) - {//not gripping - //If we can't get straight at him - if ( !Jedi_ClearPathToSpot( enemy_dest, NPCS.NPC->enemy->s.number ) ) - {//hunt him down - //Com_Printf( "No Clear Path\n" ); - if ( (NPC_ClearLOS4( NPCS.NPC->enemy )||NPCS.NPCInfo->enemyLastSeenTime>level.time-500) && NPC_FaceEnemy( qtrue ) )//( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && + if (!(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) || NPCS.NPC->client->ps.fd.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) { // not gripping + // If we can't get straight at him + if (!Jedi_ClearPathToSpot(enemy_dest, NPCS.NPC->enemy->s.number)) { // hunt him down + // Com_Printf( "No Clear Path\n" ); + if ((NPC_ClearLOS4(NPCS.NPC->enemy) || NPCS.NPCInfo->enemyLastSeenTime > level.time - 500) && + NPC_FaceEnemy(qtrue)) //( NPCInfo->rank == RANK_CREWMAN || NPCInfo->rank > RANK_LT_JG ) && { - //try to jump to him? + // try to jump to him? /* vec3_t end; VectorCopy( NPC->r.currentOrigin, end ); @@ -5168,146 +4091,125 @@ static void Jedi_Combat( void ) } } */ - //FIXME: about every 1 second calc a velocity, - //run a loop of traces with evaluate trajectory - //for gravity with my size, see if it makes it... - //this will also catch misacalculations that send you off ledges! - //Com_Printf( "Considering Jump\n" ); - if ( Jedi_TryJump( NPCS.NPC->enemy ) ) - {//FIXME: what about jumping to his enemyLastSeenLocation? + // FIXME: about every 1 second calc a velocity, + // run a loop of traces with evaluate trajectory + // for gravity with my size, see if it makes it... + // this will also catch misacalculations that send you off ledges! + // Com_Printf( "Considering Jump\n" ); + if (Jedi_TryJump(NPCS.NPC->enemy)) { // FIXME: what about jumping to his enemyLastSeenLocation? return; } } - //Check for evasion - if ( TIMER_Done( NPCS.NPC, "parryTime" ) ) - {//finished parrying - if ( NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPCS.NPC, "parryTime")) { // finished parrying + if (NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && + NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( Jedi_Hunt() && !(NPCS.NPCInfo->aiFlags&NPCAI_BLOCKED) )//FIXME: have to do this because they can ping-pong forever - {//can macro-navigate to him - if ( enemy_dist < 384 && !Q_irand( 0, 10 ) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && !NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_JLOST1, EV_JLOST3 ), 3000 ); + if (Jedi_Hunt() && !(NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED)) // FIXME: have to do this because they can ping-pong forever + { // can macro-navigate to him + if (enemy_dist < 384 && !Q_irand(0, 10) && NPCS.NPCInfo->blockedSpeechDebounceTime < level.time && + jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] < level.time && !NPC_ClearLOS4(NPCS.NPC->enemy)) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_JLOST1, EV_JLOST3), 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } return; } - //well, try to head for his last seen location - /* - else if ( Jedi_Track() ) - { - return; - } - */ else - {//FIXME: try to find a waypoint that can see enemy, jump from there - if ( NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//try to jump to the blockedDest - gentity_t *tempGoal = G_Spawn();//ugh, this is NOT good...? - G_SetOrigin( tempGoal, NPCS.NPCInfo->blockedDest ); - trap->LinkEntity( (sharedEntity_t *)tempGoal ); - if ( Jedi_TryJump( tempGoal ) ) - {//going to jump to the dest - G_FreeEntity( tempGoal ); + // well, try to head for his last seen location + /* + else if ( Jedi_Track() ) + { + return; + } + */ + else { // FIXME: try to find a waypoint that can see enemy, jump from there + if (NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED) { // try to jump to the blockedDest + gentity_t *tempGoal = G_Spawn(); // ugh, this is NOT good...? + G_SetOrigin(tempGoal, NPCS.NPCInfo->blockedDest); + trap->LinkEntity((sharedEntity_t *)tempGoal); + if (Jedi_TryJump(tempGoal)) { // going to jump to the dest + G_FreeEntity(tempGoal); return; } - G_FreeEntity( tempGoal ); + G_FreeEntity(tempGoal); } enemy_lost = qtrue; } } } - //else, we can see him or we can't track him at all + // else, we can see him or we can't track him at all - //every few seconds, decide if we should we advance or retreat? - Jedi_CombatTimersUpdate( enemy_dist ); + // every few seconds, decide if we should we advance or retreat? + Jedi_CombatTimersUpdate(enemy_dist); - //We call this even if lost enemy to keep him moving and to update the taunting behavior - //maintain a distance from enemy appropriate for our aggression level - Jedi_CombatDistance( enemy_dist ); + // We call this even if lost enemy to keep him moving and to update the taunting behavior + // maintain a distance from enemy appropriate for our aggression level + Jedi_CombatDistance(enemy_dist); - if ( !enemy_lost ) - { - //Update our seen enemy position - if ( !NPCS.NPC->enemy->client || ( NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE ) ) - { - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); + if (!enemy_lost) { + // Update our seen enemy position + if (!NPCS.NPC->enemy->client || + (NPCS.NPC->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE && NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE)) { + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); } NPCS.NPCInfo->enemyLastSeenTime = level.time; } - //Turn to face the enemy - if ( TIMER_Done( NPCS.NPC, "noturn" ) ) - { - Jedi_FaceEnemy( qtrue ); + // Turn to face the enemy + if (TIMER_Done(NPCS.NPC, "noturn")) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - //Check for evasion - if ( TIMER_Done( NPCS.NPC, "parryTime" ) ) - {//finished parrying - if ( NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && - NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN ) - {//wasn't blocked myself + // Check for evasion + if (TIMER_Done(NPCS.NPC, "parryTime")) { // finished parrying + if (NPCS.NPC->client->ps.saberBlocked != BLOCKED_ATK_BOUNCE && NPCS.NPC->client->ps.saberBlocked != BLOCKED_PARRY_BROKEN) { // wasn't blocked myself NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; } } - if ( NPCS.NPC->enemy->s.weapon == WP_SABER ) - { - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); - } - else - {//do we need to do any evasion for other kinds of enemies? + if (NPCS.NPC->enemy->s.weapon == WP_SABER) { + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); + } else { // do we need to do any evasion for other kinds of enemies? } - //apply strafing/walking timers, etc. + // apply strafing/walking timers, etc. Jedi_TimersApply(); - if ( !NPCS.NPC->client->ps.saberInFlight && (!(NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2) ) - {//not throwing saber or using force grip - //see if we can attack - if ( !Jedi_AttackDecide( enemy_dist ) ) - {//we're not attacking, decide what else to do - Jedi_CombatIdle( enemy_dist ); - //FIXME: lower aggression when actually strike offensively? Or just when do damage? - } - else - {//we are attacking - //stop taunting - TIMER_Set( NPCS.NPC, "taunting", -level.time ); + if (!NPCS.NPC->client->ps.saberInFlight && (!(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) || + NPCS.NPC->client->ps.fd.forcePowerLevel[FP_GRIP] < FORCE_LEVEL_2)) { // not throwing saber or using force grip + // see if we can attack + if (!Jedi_AttackDecide(enemy_dist)) { // we're not attacking, decide what else to do + Jedi_CombatIdle(enemy_dist); + // FIXME: lower aggression when actually strike offensively? Or just when do damage? + } else { // we are attacking + // stop taunting + TIMER_Set(NPCS.NPC, "taunting", -level.time); } + } else { } - else - { - } - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); } - //Check for certain enemy special moves - Jedi_CheckEnemyMovement( enemy_dist ); - //Make sure that we don't jump off ledges over long drops + // Check for certain enemy special moves + Jedi_CheckEnemyMovement(enemy_dist); + // Make sure that we don't jump off ledges over long drops Jedi_CheckJumps(); - //Just make sure we don't strafe into walls or off cliffs - if ( !NPC_MoveDirClear( NPCS.ucmd.forwardmove, NPCS.ucmd.rightmove, qtrue ) ) - {//uh-oh, we are going to fall or hit something - navInfo_t info; - //Get the move info - NAV_GetLastMove( &info ); - if ( !(info.flags & NIF_MACRO_NAV) ) - {//micro-navigation told us to step off a ledge, try using macronav for now - NPC_MoveToGoal( qfalse ); - } - //reset the timers. - TIMER_Set( NPCS.NPC, "strafeLeft", 0 ); - TIMER_Set( NPCS.NPC, "strafeRight", 0 ); + // Just make sure we don't strafe into walls or off cliffs + if (!NPC_MoveDirClear(NPCS.ucmd.forwardmove, NPCS.ucmd.rightmove, qtrue)) { // uh-oh, we are going to fall or hit something + navInfo_t info; + // Get the move info + NAV_GetLastMove(&info); + if (!(info.flags & NIF_MACRO_NAV)) { // micro-navigation told us to step off a ledge, try using macronav for now + NPC_MoveToGoal(qfalse); + } + // reset the timers. + TIMER_Set(NPCS.NPC, "strafeLeft", 0); + TIMER_Set(NPCS.NPC, "strafeRight", 0); } } @@ -5323,214 +4225,175 @@ NPC_Jedi_Pain ------------------------- */ -void NPC_Jedi_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Jedi_Pain(gentity_t *self, gentity_t *attacker, int damage) { gentity_t *other = attacker; vec3_t point; VectorCopy(gPainPoint, point); - //FIXME: base the actual aggression add/subtract on health? - //FIXME: don't do this more than once per frame? - //FIXME: when take pain, stop force gripping....? - if ( other->s.weapon == WP_SABER ) - {//back off - TIMER_Set( self, "parryTime", -1 ); - if ( self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",self->NPC_type) ) - {//less for Desann - self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_npcspskill.integer)*50; - } - else if ( self->NPC->rank >= RANK_LT_JG ) - { - self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_npcspskill.integer)*100;//300 - } - else + // FIXME: base the actual aggression add/subtract on health? + // FIXME: don't do this more than once per frame? + // FIXME: when take pain, stop force gripping....? + if (other->s.weapon == WP_SABER) { // back off + TIMER_Set(self, "parryTime", -1); + if (self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", self->NPC_type)) { // less for Desann + self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_npcspskill.integer) * 50; + } else if (self->NPC->rank >= RANK_LT_JG) { + self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_npcspskill.integer) * 100; // 300 + } else { + self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3 - g_npcspskill.integer) * 200; // 500 + } + if (!Q_irand(0, 3)) { // ouch... maybe switch up which saber power level we're using + Jedi_AdjustSaberAnimLevel(self, Q_irand(FORCE_LEVEL_1, FORCE_LEVEL_3)); + } + if (!Q_irand(0, 1)) // damage > 20 || self->health < 40 || { - self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + (3-g_npcspskill.integer)*200;//500 + // Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); + Jedi_Aggression(self, -1); } - if ( !Q_irand( 0, 3 ) ) - {//ouch... maybe switch up which saber power level we're using - Jedi_AdjustSaberAnimLevel( self, Q_irand( FORCE_LEVEL_1, FORCE_LEVEL_3 ) ); - } - if ( !Q_irand( 0, 1 ) )//damage > 20 || self->health < 40 || - { - //Com_Printf( "(%d) drop agg - hit by saber\n", level.time ); - Jedi_Aggression( self, -1 ); - } - if ( d_JediAI.integer ) - { - Com_Printf( "(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time+500 ); + if (d_JediAI.integer) { + Com_Printf("(%d) PAIN: agg %d, no parry until %d\n", level.time, self->NPC->stats.aggression, level.time + 500); } - //for testing only - // Figure out what quadrant the hit was in. - if ( d_JediAI.integer ) - { - vec3_t diff, fwdangles, right; + // for testing only + // Figure out what quadrant the hit was in. + if (d_JediAI.integer) { + vec3_t diff, fwdangles, right; float rightdot, zdiff; - VectorSubtract( point, self->client->renderInfo.eyePoint, diff ); + VectorSubtract(point, self->client->renderInfo.eyePoint, diff); diff[2] = 0; fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); rightdot = DotProduct(right, diff); zdiff = point[2] - self->client->renderInfo.eyePoint[2]; - Com_Printf( "(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2]-self->r.absmin[2],zdiff,rightdot); + Com_Printf("(%d) saber hit at height %4.2f, zdiff: %4.2f, rightdot: %4.2f\n", level.time, point[2] - self->r.absmin[2], zdiff, rightdot); } - } - else - {//attack - //Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); - Jedi_Aggression( self, 1 ); + } else { // attack + // Com_Printf( "(%d) raise agg - hit by ranged\n", level.time ); + Jedi_Aggression(self, 1); } self->NPC->enemyCheckDebounceTime = 0; - WP_ForcePowerStop( self, FP_GRIP ); + WP_ForcePowerStop(self, FP_GRIP); - //NPC_Pain( self, inflictor, other, point, damage, mod ); + // NPC_Pain( self, inflictor, other, point, damage, mod ); NPC_Pain(self, attacker, damage); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } - //drop me from the ceiling if I'm on it - if ( Jedi_WaitingAmbush( self ) ) - { + // drop me from the ceiling if I'm on it + if (Jedi_WaitingAmbush(self)) { self->client->noclip = qfalse; } - if ( self->client->ps.legsAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.legsAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_LEGS, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - if ( self->client->ps.torsoAnim == BOTH_CEILING_CLING ) - { - NPC_SetAnim( self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (self->client->ps.torsoAnim == BOTH_CEILING_CLING) { + NPC_SetAnim(self, SETANIM_TORSO, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } -qboolean Jedi_CheckDanger( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_MINOR ); - - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner - || !level.alertEvents[alertEvent].owner->client - || (level.alertEvents[alertEvent].owner!=NPCS.NPC&&level.alertEvents[alertEvent].owner->client->playerTeam!=NPCS.NPC->client->playerTeam) ) - {//no owner +qboolean Jedi_CheckDanger(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_MINOR); + + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != NPCS.NPC && + level.alertEvents[alertEvent].owner->client->playerTeam != NPCS.NPC->client->playerTeam)) { // no owner return qfalse; } - G_SetEnemy( NPCS.NPC, level.alertEvents[alertEvent].owner ); + G_SetEnemy(NPCS.NPC, level.alertEvents[alertEvent].owner); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } return qfalse; } -qboolean Jedi_CheckAmbushPlayer( void ) -{ +qboolean Jedi_CheckAmbushPlayer(void) { int i = 0; gentity_t *player; float target_dist; float zDiff; - for ( i = 0; i < MAX_CLIENTS; i++ ) - { + for (i = 0; i < MAX_CLIENTS; i++) { player = &g_entities[i]; - if ( !player || !player->client ) - { + if (!player || !player->client) { continue; } - if ( !NPC_ValidEnemy( player ) ) - { + if (!NPC_ValidEnemy(player)) { continue; } -// if ( NPC->client->ps.powerups[PW_CLOAKED] || g_crosshairEntNum != NPC->s.number ) - if (NPCS.NPC->client->ps.powerups[PW_CLOAKED] || !NPC_SomeoneLookingAtMe(NPCS.NPC)) //rwwFIXMEFIXME: Need to pay attention to who is under crosshair for each player or something. - {//if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... - if ( !trap->InPVS( player->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - {//must be in same room + // if ( NPC->client->ps.powerups[PW_CLOAKED] || g_crosshairEntNum != NPC->s.number ) + if (NPCS.NPC->client->ps.powerups[PW_CLOAKED] || + !NPC_SomeoneLookingAtMe(NPCS.NPC)) // rwwFIXMEFIXME: Need to pay attention to who is under crosshair for each player or something. + { // if I'm not cloaked and the player's crosshair is on me, I will wake up, otherwise do this stuff down here... + if (!trap->InPVS(player->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { // must be in same room continue; - } - else - { - if ( !NPCS.NPC->client->ps.powerups[PW_CLOAKED] ) - { - NPC_SetLookTarget( NPCS.NPC, 0, 0 ); + } else { + if (!NPCS.NPC->client->ps.powerups[PW_CLOAKED]) { + NPC_SetLookTarget(NPCS.NPC, 0, 0); } } - zDiff = NPCS.NPC->r.currentOrigin[2]-player->r.currentOrigin[2]; - if ( zDiff <= 0 || zDiff > 512 ) - {//never ambush if they're above me or way way below me + zDiff = NPCS.NPC->r.currentOrigin[2] - player->r.currentOrigin[2]; + if (zDiff <= 0 || zDiff > 512) { // never ambush if they're above me or way way below me continue; } - //If the target is this close, then wake up regardless - if ( (target_dist = DistanceHorizontalSquared( player->r.currentOrigin, NPCS.NPC->r.currentOrigin )) > 4096 ) - {//closer than 64 - always ambush - if ( target_dist > 147456 ) - {//> 384, not close enough to ambush + // If the target is this close, then wake up regardless + if ((target_dist = DistanceHorizontalSquared(player->r.currentOrigin, NPCS.NPC->r.currentOrigin)) > 4096) { // closer than 64 - always ambush + if (target_dist > 147456) { //> 384, not close enough to ambush continue; } - //Check FOV first - if ( NPCS.NPC->client->ps.powerups[PW_CLOAKED] ) - { - if ( InFOV( player, NPCS.NPC, 30, 90 ) == qfalse ) - { + // Check FOV first + if (NPCS.NPC->client->ps.powerups[PW_CLOAKED]) { + if (InFOV(player, NPCS.NPC, 30, 90) == qfalse) { continue; } - } - else - { - if ( InFOV( player, NPCS.NPC, 45, 90 ) == qfalse ) - { + } else { + if (InFOV(player, NPCS.NPC, 45, 90) == qfalse) { continue; } } } - if ( !NPC_ClearLOS4( player ) ) - { + if (!NPC_ClearLOS4(player)) { continue; } } - //Got him, return true; - G_SetEnemy( NPCS.NPC, player ); + // Got him, return true; + G_SetEnemy(NPCS.NPC, player); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //Didn't get anyone. + // Didn't get anyone. return qfalse; } -void Jedi_Ambush( gentity_t *self ) -{ +void Jedi_Ambush(gentity_t *self) { self->client->noclip = qfalse; -// self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - self->client->ps.weaponTime = self->client->ps.torsoTimer; //NPC->client->ps.torsoTimer; //what the? - if ( self->client->NPC_class != CLASS_BOBAFETT ) - { + // self->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_CEILING_DROP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + self->client->ps.weaponTime = self->client->ps.torsoTimer; // NPC->client->ps.torsoTimer; //what the? + if (self->client->NPC_class != CLASS_BOBAFETT) { WP_ActivateSaber(self); } - Jedi_Decloak( self ); - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 1000 ); + Jedi_Decloak(self); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 1000); } -qboolean Jedi_WaitingAmbush( gentity_t *self ) -{ - if ( (self->spawnflags&JSF_AMBUSH) && self->client->noclip ) - { +qboolean Jedi_WaitingAmbush(gentity_t *self) { + if ((self->spawnflags & JSF_AMBUSH) && self->client->noclip) { return qtrue; } return qfalse; @@ -5541,64 +4404,51 @@ Jedi_Patrol ------------------------- */ -static void Jedi_Patrol( void ) -{ +static void Jedi_Patrol(void) { NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( Jedi_WaitingAmbush( NPCS.NPC ) ) - {//hiding on the ceiling - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - {//look for enemies - if ( Jedi_CheckAmbushPlayer() || Jedi_CheckDanger() ) - {//found him! - Jedi_Ambush( NPCS.NPC ); - NPC_UpdateAngles( qtrue, qtrue ); + if (Jedi_WaitingAmbush(NPCS.NPC)) { // hiding on the ceiling + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_CEILING_CLING, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { // look for enemies + if (Jedi_CheckAmbushPlayer() || Jedi_CheckDanger()) { // found him! + Jedi_Ambush(NPCS.NPC); + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES )//NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - {//look for enemies + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) // NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) + { // look for enemies gentity_t *best_enemy = NULL; - float best_enemy_dist = Q3_INFINITE; + float best_enemy_dist = Q3_INFINITE; int i; - for ( i = 0; i < ENTITYNUM_WORLD; i++ ) - { + for (i = 0; i < ENTITYNUM_WORLD; i++) { gentity_t *enemy = &g_entities[i]; - float enemy_dist; - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPCS.NPC->client->enemyTeam ) - { - if ( trap->InPVS( NPCS.NPC->r.currentOrigin, enemy->r.currentOrigin ) ) - {//we could potentially see him - enemy_dist = DistanceSquared( NPCS.NPC->r.currentOrigin, enemy->r.currentOrigin ); - if ( enemy->s.eType == ET_PLAYER || enemy_dist < best_enemy_dist ) - { - //if the enemy is close enough, or threw his saber, take him as the enemy - //FIXME: what if he throws a thermal detonator? - if ( enemy_dist < (220*220) || ( NPCS.NPCInfo->investigateCount>= 3 && !NPCS.NPC->client->ps.saberHolstered ) ) - { - G_SetEnemy( NPCS.NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + float enemy_dist; + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && enemy->client->playerTeam == NPCS.NPC->client->enemyTeam) { + if (trap->InPVS(NPCS.NPC->r.currentOrigin, enemy->r.currentOrigin)) { // we could potentially see him + enemy_dist = DistanceSquared(NPCS.NPC->r.currentOrigin, enemy->r.currentOrigin); + if (enemy->s.eType == ET_PLAYER || enemy_dist < best_enemy_dist) { + // if the enemy is close enough, or threw his saber, take him as the enemy + // FIXME: what if he throws a thermal detonator? + if (enemy_dist < (220 * 220) || (NPCS.NPCInfo->investigateCount >= 3 && !NPCS.NPC->client->ps.saberHolstered)) { + G_SetEnemy(NPCS.NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCS.NPCInfo->stats.aggression = 3; break; - } - else if ( enemy->client->ps.saberInFlight && !enemy->client->ps.saberHolstered ) - {//threw his saber, see if it's heading toward me and close enough to consider a threat - float saberDist; - vec3_t saberDir2Me; - vec3_t saberMoveDir; + } else if (enemy->client->ps.saberInFlight && + !enemy->client->ps.saberHolstered) { // threw his saber, see if it's heading toward me and close enough to consider a threat + float saberDist; + vec3_t saberDir2Me; + vec3_t saberMoveDir; gentity_t *saber = &g_entities[enemy->client->ps.saberEntityNum]; - VectorSubtract( NPCS.NPC->r.currentOrigin, saber->r.currentOrigin, saberDir2Me ); - saberDist = VectorNormalize( saberDir2Me ); - VectorCopy( saber->s.pos.trDelta, saberMoveDir ); - VectorNormalize( saberMoveDir ); - if ( DotProduct( saberMoveDir, saberDir2Me ) > 0.5 ) - {//it's heading towards me - if ( saberDist < 200 ) - {//incoming! - G_SetEnemy( NPCS.NPC, enemy ); - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + VectorSubtract(NPCS.NPC->r.currentOrigin, saber->r.currentOrigin, saberDir2Me); + saberDist = VectorNormalize(saberDir2Me); + VectorCopy(saber->s.pos.trDelta, saberMoveDir); + VectorNormalize(saberMoveDir); + if (DotProduct(saberMoveDir, saberDir2Me) > 0.5) { // it's heading towards me + if (saberDist < 200) { // incoming! + G_SetEnemy(NPCS.NPC, enemy); + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now NPCS.NPCInfo->stats.aggression = 3; break; } @@ -5610,109 +4460,78 @@ static void Jedi_Patrol( void ) } } } - if ( !NPCS.NPC->enemy ) - {//still not mad - if ( !best_enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); + if (!NPCS.NPC->enemy) { // still not mad + if (!best_enemy) { + // Com_Printf( "(%d) drop agg - no enemy (patrol)\n", level.time ); Jedi_AggressionErosion(-1); - //FIXME: what about alerts? But not if ignore alerts - } - else - {//have one to consider - if ( NPC_ClearLOS4( best_enemy ) ) - {//we have a clear (of architecture) LOS to him - if ( best_enemy->s.number ) - {//just attack - G_SetEnemy( NPCS.NPC, best_enemy ); + // FIXME: what about alerts? But not if ignore alerts + } else { // have one to consider + if (NPC_ClearLOS4(best_enemy)) { // we have a clear (of architecture) LOS to him + if (best_enemy->s.number) { // just attack + G_SetEnemy(NPCS.NPC, best_enemy); NPCS.NPCInfo->stats.aggression = 3; - } - else if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - {//the player, toy with him - //get progressively more interested over time - if ( TIMER_Done( NPCS.NPC, "watchTime" ) ) - {//we want to pick him up in stages - if ( TIMER_Get( NPCS.NPC, "watchTime" ) == -1 ) - {//this is the first time, we'll ignore him for a couple seconds - TIMER_Set( NPCS.NPC, "watchTime", Q_irand( 3000, 5000 ) ); + } else if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { // the player, toy with him + // get progressively more interested over time + if (TIMER_Done(NPCS.NPC, "watchTime")) { // we want to pick him up in stages + if (TIMER_Get(NPCS.NPC, "watchTime") == -1) { // this is the first time, we'll ignore him for a couple seconds + TIMER_Set(NPCS.NPC, "watchTime", Q_irand(3000, 5000)); goto finish; - } - else - {//okay, we've ignored him, now start to notice him - if ( !NPCS.NPCInfo->investigateCount ) - { - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_JDETECTED1, EV_JDETECTED3 ), 3000 ); + } else { // okay, we've ignored him, now start to notice him + if (!NPCS.NPCInfo->investigateCount) { + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_JDETECTED1, EV_JDETECTED3), 3000); } NPCS.NPCInfo->investigateCount++; - TIMER_Set( NPCS.NPC, "watchTime", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPCS.NPC, "watchTime", Q_irand(4000, 10000)); } } - //while we're waiting, do what we need to do - if ( best_enemy_dist < (440*440) || NPCS.NPCInfo->investigateCount >= 2 ) - {//stage three: keep facing him - NPC_FaceEntity( best_enemy, qtrue ); - if ( best_enemy_dist < (330*330) ) - {//stage four: turn on the saber - if ( !NPCS.NPC->client->ps.saberInFlight ) - { + // while we're waiting, do what we need to do + if (best_enemy_dist < (440 * 440) || NPCS.NPCInfo->investigateCount >= 2) { // stage three: keep facing him + NPC_FaceEntity(best_enemy, qtrue); + if (best_enemy_dist < (330 * 330)) { // stage four: turn on the saber + if (!NPCS.NPC->client->ps.saberInFlight) { WP_ActivateSaber(NPCS.NPC); } } - } - else if ( best_enemy_dist < (550*550) || NPCS.NPCInfo->investigateCount == 1 ) - {//stage two: stop and face him every now and then - if ( TIMER_Done( NPCS.NPC, "watchTime" ) ) - { - NPC_FaceEntity( best_enemy, qtrue ); + } else if (best_enemy_dist < (550 * 550) || NPCS.NPCInfo->investigateCount == 1) { // stage two: stop and face him every now and then + if (TIMER_Done(NPCS.NPC, "watchTime")) { + NPC_FaceEntity(best_enemy, qtrue); } - } - else - {//stage one: look at him. - NPC_SetLookTarget( NPCS.NPC, best_enemy->s.number, 0 ); + } else { // stage one: look at him. + NPC_SetLookTarget(NPCS.NPC, best_enemy->s.number, 0); } } - } - else if ( TIMER_Done( NPCS.NPC, "watchTime" ) ) - {//haven't seen him in a bit, clear the lookTarget - NPC_ClearLookTarget( NPCS.NPC ); + } else if (TIMER_Done(NPCS.NPC, "watchTime")) { // haven't seen him in a bit, clear the lookTarget + NPC_ClearLookTarget(NPCS.NPC); } } } } finish: - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - //Jedi_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); + // Jedi_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPCS.NPC->enemy ) - {//just picked one up - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (NPCS.NPC->enemy) { // just picked one up + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); } } -qboolean Jedi_CanPullBackSaber( gentity_t *self ) -{ - if ( self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done( self, "parryTime" ) ) - { +qboolean Jedi_CanPullBackSaber(gentity_t *self) { + if (self->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN && !TIMER_Done(self, "parryTime")) { return qfalse; } - if ( self->client->NPC_class == CLASS_SHADOWTROOPER - || self->client->NPC_class == CLASS_TAVION - || self->client->NPC_class == CLASS_LUKE - || self->client->NPC_class == CLASS_DESANN - || !Q_stricmp( "Yoda", self->NPC_type ) ) - { + if (self->client->NPC_class == CLASS_SHADOWTROOPER || self->client->NPC_class == CLASS_TAVION || self->client->NPC_class == CLASS_LUKE || + self->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", self->NPC_type)) { return qtrue; } - if ( self->painDebounceTime > level.time )//|| self->client->ps.weaponTime > 0 ) + if (self->painDebounceTime > level.time) //|| self->client->ps.weaponTime > 0 ) { return qfalse; } @@ -5724,39 +4543,33 @@ qboolean Jedi_CanPullBackSaber( gentity_t *self ) NPC_BSJedi_FollowLeader ------------------------- */ -void NPC_BSJedi_FollowLeader( void ) -{ +void NPC_BSJedi_FollowLeader(void) { NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( !NPCS.NPC->enemy ) - { - //Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); + if (!NPCS.NPC->enemy) { + // Com_Printf( "(%d) drop agg - no enemy (follow)\n", level.time ); Jedi_AggressionErosion(-1); } - //did we drop our saber? If so, go after it! - if ( NPCS.NPC->client->ps.saberInFlight ) - {//saber is not in hand - if ( NPCS.NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPCS.NPC->client->ps.saberEntityNum > 0 )//player is 0 - {// - if ( g_entities[NPCS.NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - {//fell to the ground, try to pick it up... - if ( Jedi_CanPullBackSaber( NPCS.NPC ) ) - { - //FIXME: if it's on the ground and we just pulled it back to us, should we + // did we drop our saber? If so, go after it! + if (NPCS.NPC->client->ps.saberInFlight) { // saber is not in hand + if (NPCS.NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPCS.NPC->client->ps.saberEntityNum > 0) // player is 0 + { // + if (g_entities[NPCS.NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY) { // fell to the ground, try to pick it up... + if (Jedi_CanPullBackSaber(NPCS.NPC)) { + // FIXME: if it's on the ground and we just pulled it back to us, should we // stand still for a bit to make sure it gets to us...? // otherwise we could end up running away from it while it's on its // way back to us and we could lose it again. NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCS.NPCInfo->goalEntity = &g_entities[NPCS.NPC->client->ps.saberEntityNum]; NPCS.ucmd.buttons |= BUTTON_ATTACK; - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0 ) - {//get our saber back NOW! - if ( !NPC_MoveToGoal( qtrue ) )//Jedi_Move( NPCInfo->goalEntity, qfalse ); - {//can't nav to it, try jumping to it - NPC_FaceEntity( NPCS.NPCInfo->goalEntity, qtrue ); - Jedi_TryJump( NPCS.NPCInfo->goalEntity ); + if (NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0) { // get our saber back NOW! + if (!NPC_MoveToGoal(qtrue)) // Jedi_Move( NPCInfo->goalEntity, qfalse ); + { // can't nav to it, try jumping to it + NPC_FaceEntity(NPCS.NPCInfo->goalEntity, qtrue); + Jedi_TryJump(NPCS.NPCInfo->goalEntity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } @@ -5764,149 +4577,117 @@ void NPC_BSJedi_FollowLeader( void ) } } - if ( NPCS.NPCInfo->goalEntity ) - { - trace_t trace; + if (NPCS.NPCInfo->goalEntity) { + trace_t trace; - if ( Jedi_Jumping( NPCS.NPCInfo->goalEntity ) ) - {//in mid-jump + if (Jedi_Jumping(NPCS.NPCInfo->goalEntity)) { // in mid-jump return; } - if ( !NAV_CheckAhead( NPCS.NPC, NPCS.NPCInfo->goalEntity->r.currentOrigin, &trace, ( NPCS.NPC->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - {//can't get straight to him - if ( NPC_ClearLOS4( NPCS.NPCInfo->goalEntity ) && NPC_FaceEntity( NPCS.NPCInfo->goalEntity, qtrue ) ) - {//no line of sight - if ( Jedi_TryJump( NPCS.NPCInfo->goalEntity ) ) - {//started a jump + if (!NAV_CheckAhead(NPCS.NPC, NPCS.NPCInfo->goalEntity->r.currentOrigin, &trace, + (NPCS.NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { // can't get straight to him + if (NPC_ClearLOS4(NPCS.NPCInfo->goalEntity) && NPC_FaceEntity(NPCS.NPCInfo->goalEntity, qtrue)) { // no line of sight + if (Jedi_TryJump(NPCS.NPCInfo->goalEntity)) { // started a jump return; } } } - if ( NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//try to jump to the blockedDest - if ( fabs(NPCS.NPCInfo->blockedDest[2]-NPCS.NPC->r.currentOrigin[2]) > 64 ) - { - gentity_t *tempGoal = G_Spawn();//ugh, this is NOT good...? - G_SetOrigin( tempGoal, NPCS.NPCInfo->blockedDest ); - trap->LinkEntity( (sharedEntity_t *)tempGoal ); - TIMER_Set( NPCS.NPC, "jumpChaseDebounce", -1 ); - if ( Jedi_TryJump( tempGoal ) ) - {//going to jump to the dest - G_FreeEntity( tempGoal ); + if (NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED) { // try to jump to the blockedDest + if (fabs(NPCS.NPCInfo->blockedDest[2] - NPCS.NPC->r.currentOrigin[2]) > 64) { + gentity_t *tempGoal = G_Spawn(); // ugh, this is NOT good...? + G_SetOrigin(tempGoal, NPCS.NPCInfo->blockedDest); + trap->LinkEntity((sharedEntity_t *)tempGoal); + TIMER_Set(NPCS.NPC, "jumpChaseDebounce", -1); + if (Jedi_TryJump(tempGoal)) { // going to jump to the dest + G_FreeEntity(tempGoal); return; } - G_FreeEntity( tempGoal ); + G_FreeEntity(tempGoal); } } } - //try normal movement + // try normal movement NPC_BSFollowLeader(); } - /* ------------------------- Jedi_Attack ------------------------- */ -static void Jedi_Attack( void ) -{ - //Don't do anything if we're in a pain anim - if ( NPCS.NPC->painDebounceTime > level.time ) - { - if ( Q_irand( 0, 1 ) ) - { - Jedi_FaceEnemy( qtrue ); +static void Jedi_Attack(void) { + // Don't do anything if we're in a pain anim + if (NPCS.NPC->painDebounceTime > level.time) { + if (Q_irand(0, 1)) { + Jedi_FaceEnemy(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( NPCS.NPC->client->ps.saberLockTime > level.time ) - { - //FIXME: maybe if I'm losing I should try to force-push out of it? Very rarely, though... - if ( NPCS.NPC->client->ps.fd.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 - && NPCS.NPC->client->ps.saberLockTime < level.time + 5000 - && !Q_irand( 0, 10 )) - { - ForceThrow( NPCS.NPC, qfalse ); + if (NPCS.NPC->client->ps.saberLockTime > level.time) { + // FIXME: maybe if I'm losing I should try to force-push out of it? Very rarely, though... + if (NPCS.NPC->client->ps.fd.forcePowerLevel[FP_PUSH] > FORCE_LEVEL_2 && NPCS.NPC->client->ps.saberLockTime < level.time + 5000 && !Q_irand(0, 10)) { + ForceThrow(NPCS.NPC, qfalse); } - //based on my skill, hit attack button every other to every several frames in order to push enemy back - else - { + // based on my skill, hit attack button every other to every several frames in order to push enemy back + else { float chance; - if ( NPCS.NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda",NPCS.NPC->NPC_type) ) - { - if ( g_npcspskill.integer ) - { - chance = 4.0f;//he pushes *hard* - } - else - { - chance = 3.0f;//he pushes *hard* - } - } - else if ( NPCS.NPC->client->NPC_class == CLASS_TAVION ) - { - chance = 2.0f+g_npcspskill.value;//from 2 to 4 - } - else - {//the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard - float maxChance = (float)(RANK_LT)/2.0f+3.0f;//5? - if ( !g_npcspskill.value ) - { - chance = (float)(NPCS.NPCInfo->rank)/2.0f; + if (NPCS.NPC->client->NPC_class == CLASS_DESANN || !Q_stricmp("Yoda", NPCS.NPC->NPC_type)) { + if (g_npcspskill.integer) { + chance = 4.0f; // he pushes *hard* + } else { + chance = 3.0f; // he pushes *hard* } - else - { - chance = (float)(NPCS.NPCInfo->rank)/2.0f+1.0f; + } else if (NPCS.NPC->client->NPC_class == CLASS_TAVION) { + chance = 2.0f + g_npcspskill.value; // from 2 to 4 + } else { // the escalation in difficulty is nice, here, but cap it so it doesn't get *impossible* on hard + float maxChance = (float)(RANK_LT) / 2.0f + 3.0f; // 5? + if (!g_npcspskill.value) { + chance = (float)(NPCS.NPCInfo->rank) / 2.0f; + } else { + chance = (float)(NPCS.NPCInfo->rank) / 2.0f + 1.0f; } - if ( chance > maxChance ) - { + if (chance > maxChance) { chance = maxChance; } } - // if ( flrand( -4.0f, chance ) >= 0.0f && !(NPC->client->ps.pm_flags&PMF_ATTACK_HELD) ) - // { - // ucmd.buttons |= BUTTON_ATTACK; - // } - if ( flrand( -4.0f, chance ) >= 0.0f ) - { + // if ( flrand( -4.0f, chance ) >= 0.0f && !(NPC->client->ps.pm_flags&PMF_ATTACK_HELD) ) + // { + // ucmd.buttons |= BUTTON_ATTACK; + // } + if (flrand(-4.0f, chance) >= 0.0f) { NPCS.ucmd.buttons |= BUTTON_ATTACK; } - //rwwFIXMEFIXME: support for PMF_ATTACK_HELD + // rwwFIXMEFIXME: support for PMF_ATTACK_HELD } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - //did we drop our saber? If so, go after it! - if ( NPCS.NPC->client->ps.saberInFlight ) - {//saber is not in hand - // if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 - if (!NPCS.NPC->client->ps.saberEntityNum && NPCS.NPC->client->saberStoredIndex) //this is valid, it's 0 when our saber is gone -rww (mp-specific) - {// - //if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) - if (1) //no matter - {//fell to the ground, try to pick it up - // if ( Jedi_CanPullBackSaber( NPC ) ) - if (1) //no matter + // did we drop our saber? If so, go after it! + if (NPCS.NPC->client->ps.saberInFlight) { // saber is not in hand + // if ( NPC->client->ps.saberEntityNum < ENTITYNUM_NONE && NPC->client->ps.saberEntityNum > 0 )//player is 0 + if (!NPCS.NPC->client->ps.saberEntityNum && NPCS.NPC->client->saberStoredIndex) // this is valid, it's 0 when our saber is gone -rww (mp-specific) + { // + // if ( g_entities[NPC->client->ps.saberEntityNum].s.pos.trType == TR_STATIONARY ) + if (1) // no matter + { // fell to the ground, try to pick it up + // if ( Jedi_CanPullBackSaber( NPC ) ) + if (1) // no matter { NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; NPCS.NPCInfo->goalEntity = &g_entities[NPCS.NPC->client->saberStoredIndex]; NPCS.ucmd.buttons |= BUTTON_ATTACK; - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0 ) - {//get our saber back NOW! - Jedi_Move( NPCS.NPCInfo->goalEntity, qfalse ); - NPC_UpdateAngles( qtrue, qtrue ); - if ( NPCS.NPC->enemy->s.weapon == WP_SABER ) - {//be sure to continue evasion - vec3_t enemy_dir, enemy_movedir, enemy_dest; - float enemy_dist, enemy_movespeed; - Jedi_SetEnemyInfo( enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300 ); - Jedi_EvasionSaber( enemy_movedir, enemy_dist, enemy_dir ); + if (NPCS.NPC->enemy && NPCS.NPC->enemy->health > 0) { // get our saber back NOW! + Jedi_Move(NPCS.NPCInfo->goalEntity, qfalse); + NPC_UpdateAngles(qtrue, qtrue); + if (NPCS.NPC->enemy->s.weapon == WP_SABER) { // be sure to continue evasion + vec3_t enemy_dir, enemy_movedir, enemy_dest; + float enemy_dist, enemy_movespeed; + Jedi_SetEnemyInfo(enemy_dest, enemy_dir, &enemy_dist, enemy_movedir, &enemy_movespeed, 300); + Jedi_EvasionSaber(enemy_movedir, enemy_dist, enemy_dir); } return; } @@ -5914,209 +4695,172 @@ static void Jedi_Attack( void ) } } } - //see if our enemy was killed by us, gloat and turn off saber after cool down. - //FIXME: don't do this if we have other enemies to fight...? - if ( NPCS.NPC->enemy ) - { - if ( NPCS.NPC->enemy->health <= 0 && NPCS.NPC->enemy->enemy == NPCS.NPC && NPCS.NPC->client->playerTeam != NPCTEAM_PLAYER )//good guys don't gloat - {//my enemy is dead and I killed him - NPCS.NPCInfo->enemyCheckDebounceTime = 0;//keep looking for others + // see if our enemy was killed by us, gloat and turn off saber after cool down. + // FIXME: don't do this if we have other enemies to fight...? + if (NPCS.NPC->enemy) { + if (NPCS.NPC->enemy->health <= 0 && NPCS.NPC->enemy->enemy == NPCS.NPC && NPCS.NPC->client->playerTeam != NPCTEAM_PLAYER) // good guys don't gloat + { // my enemy is dead and I killed him + NPCS.NPCInfo->enemyCheckDebounceTime = 0; // keep looking for others - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( NPCS.NPCInfo->walkDebounceTime < level.time && NPCS.NPCInfo->walkDebounceTime >= 0 ) - { - TIMER_Set( NPCS.NPC, "gloatTime", 10000 ); + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + if (NPCS.NPCInfo->walkDebounceTime < level.time && NPCS.NPCInfo->walkDebounceTime >= 0) { + TIMER_Set(NPCS.NPC, "gloatTime", 10000); NPCS.NPCInfo->walkDebounceTime = -1; } - if ( !TIMER_Done( NPCS.NPC, "gloatTime" ) ) - { - if ( DistanceHorizontalSquared( NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->enemy->r.currentOrigin ) > 4096 && (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + if (!TIMER_Done(NPCS.NPC, "gloatTime")) { + if (DistanceHorizontalSquared(NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->enemy->r.currentOrigin) > 4096 && + (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - Jedi_Move( NPCS.NPC->enemy, qfalse ); + Jedi_Move(NPCS.NPC->enemy, qfalse); NPCS.ucmd.buttons |= BUTTON_WALKING; + } else { + TIMER_Set(NPCS.NPC, "gloatTime", 0); } - else - { - TIMER_Set( NPCS.NPC, "gloatTime", 0 ); - } - } - else if ( NPCS.NPCInfo->walkDebounceTime == -1 ) - { + } else if (NPCS.NPCInfo->walkDebounceTime == -1) { NPCS.NPCInfo->walkDebounceTime = -2; - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = level.time + 3000; NPCS.NPCInfo->desiredPitch = 0; NPCS.NPCInfo->goalEntity = NULL; } - Jedi_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + Jedi_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - { - if ( !TIMER_Done( NPCS.NPC, "parryTime" ) ) - { - TIMER_Set( NPCS.NPC, "parryTime", -1 ); + } else { + if (!TIMER_Done(NPCS.NPC, "parryTime")) { + TIMER_Set(NPCS.NPC, "parryTime", -1); NPCS.NPC->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + 500; } NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( !NPCS.NPC->client->ps.saberHolstered && NPCS.NPC->client->ps.saberInFlight ) - {//saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy - //FIXME: need to stop this from happening over and over again when they're blocking their victim's saber - //FIXME: turn off saber sooner so we get cool walk anim? - //Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); + if (!NPCS.NPC->client->ps.saberHolstered && + NPCS.NPC->client->ps.saberInFlight) { // saber is still on (or we're trying to pull it back), count down erosion and keep facing the enemy + // FIXME: need to stop this from happening over and over again when they're blocking their victim's saber + // FIXME: turn off saber sooner so we get cool walk anim? + // Com_Printf( "(%d) drop agg - enemy dead\n", level.time ); Jedi_AggressionErosion(-3); - if ( BG_SabersOff( &NPCS.NPC->client->ps ) && !NPCS.NPC->client->ps.saberInFlight ) - {//turned off saber (in hand), gloat - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_VICTORY1, EV_VICTORY3 ), 3000 ); + if (BG_SabersOff(&NPCS.NPC->client->ps) && !NPCS.NPC->client->ps.saberInFlight) { // turned off saber (in hand), gloat + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_VICTORY1, EV_VICTORY3), 3000); jediSpeechDebounceTime[NPCS.NPC->client->playerTeam] = level.time + 3000; NPCS.NPCInfo->desiredPitch = 0; NPCS.NPCInfo->goalEntity = NULL; } - TIMER_Set( NPCS.NPC, "gloatTime", 10000 ); + TIMER_Set(NPCS.NPC, "gloatTime", 10000); } - if ( !NPCS.NPC->client->ps.saberHolstered || NPCS.NPC->client->ps.saberInFlight || !TIMER_Done( NPCS.NPC, "gloatTime" ) ) - {//keep walking - if ( DistanceHorizontalSquared( NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->enemy->r.currentOrigin ) > 4096 && (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) )//64 squared + if (!NPCS.NPC->client->ps.saberHolstered || NPCS.NPC->client->ps.saberInFlight || !TIMER_Done(NPCS.NPC, "gloatTime")) { // keep walking + if (DistanceHorizontalSquared(NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->enemy->r.currentOrigin) > 4096 && + (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // 64 squared { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - Jedi_Move( NPCS.NPC->enemy, qfalse ); + Jedi_Move(NPCS.NPC->enemy, qfalse); NPCS.ucmd.buttons |= BUTTON_WALKING; - } - else - {//got there - if ( NPCS.NPC->health < NPCS.NPC->client->pers.maxHealth - && (NPCS.NPC->client->ps.fd.forcePowersKnown&(1<client->ps.fd.forcePowersActive&(1<health < NPCS.NPC->client->pers.maxHealth && (NPCS.NPC->client->ps.fd.forcePowersKnown & (1 << FP_HEAL)) != 0 && + (NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_HEAL)) == 0) { + ForceHeal(NPCS.NPC); } } - Jedi_FaceEnemy( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + Jedi_FaceEnemy(qtrue); + NPC_UpdateAngles(qtrue, qtrue); return; } } } } - //If we don't have an enemy, just idle - if ( NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp( "PAS", NPCS.NPC->enemy->classname ) ) - { - if ( NPCS.NPC->enemy->count <= 0 ) - {//it's out of ammo - if ( NPCS.NPC->enemy->activator && NPC_ValidEnemy( NPCS.NPC->enemy->activator ) ) - { + // If we don't have an enemy, just idle + if (NPCS.NPC->enemy->s.weapon == WP_TURRET && !Q_stricmp("PAS", NPCS.NPC->enemy->classname)) { + if (NPCS.NPC->enemy->count <= 0) { // it's out of ammo + if (NPCS.NPC->enemy->activator && NPC_ValidEnemy(NPCS.NPC->enemy->activator)) { gentity_t *turretOwner = NPCS.NPC->enemy->activator; - G_ClearEnemy( NPCS.NPC ); - G_SetEnemy( NPCS.NPC, turretOwner ); - } - else - { - G_ClearEnemy( NPCS.NPC ); + G_ClearEnemy(NPCS.NPC); + G_SetEnemy(NPCS.NPC, turretOwner); + } else { + G_ClearEnemy(NPCS.NPC); } } } - NPC_CheckEnemy( qtrue, qtrue, qtrue ); + NPC_CheckEnemy(qtrue, qtrue, qtrue); - if ( !NPCS.NPC->enemy ) - { + if (!NPCS.NPC->enemy) { NPCS.NPC->client->ps.saberBlocked = BLOCKED_NONE; - if ( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - {//lost him, go back to what we were doing before + if (NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { // lost him, go back to what we were doing before NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - Jedi_Patrol();//was calling Idle... why? + Jedi_Patrol(); // was calling Idle... why? return; } - //always face enemy if have one + // always face enemy if have one NPCS.NPCInfo->combatMove = qtrue; - //Track the player and kill them if possible + // Track the player and kill them if possible Jedi_Combat(); - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) - || ((NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_HEAL]scriptFlags & SCF_CHASE_ENEMIES) || + ((NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_HEAL)) && + NPCS.NPC->client->ps.fd.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_2)) { // this is really stupid, but okay... NPCS.ucmd.forwardmove = 0; NPCS.ucmd.rightmove = 0; - if ( NPCS.ucmd.upmove > 0 ) - { + if (NPCS.ucmd.upmove > 0) { NPCS.ucmd.upmove = 0; } NPCS.NPC->client->ps.fd.forceJumpCharge = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } - //NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... - if ( NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//don't push while in air, throws off jumps! - //FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? + // NOTE: for now, we clear ucmd.forwardmove & ucmd.rightmove while in air to avoid jumps going awry... + if (NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE) { // don't push while in air, throws off jumps! + // FIXME: if we are in the air over a drop near a ledge, should we try to push back towards the ledge? NPCS.ucmd.forwardmove = 0; NPCS.ucmd.rightmove = 0; - VectorClear( NPCS.NPC->client->ps.moveDir ); + VectorClear(NPCS.NPC->client->ps.moveDir); } - if ( !TIMER_Done( NPCS.NPC, "duck" ) ) - { + if (!TIMER_Done(NPCS.NPC, "duck")) { NPCS.ucmd.upmove = -127; } - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( PM_SaberInBrokenParry( NPCS.NPC->client->ps.saberMove ) || NPCS.NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN ) - {//just make sure they don't pull their saber to them if they're being blocked + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { + if (PM_SaberInBrokenParry(NPCS.NPC->client->ps.saberMove) || + NPCS.NPC->client->ps.saberBlocked == BLOCKED_PARRY_BROKEN) { // just make sure they don't pull their saber to them if they're being blocked NPCS.ucmd.buttons &= ~BUTTON_ATTACK; } } - if( (NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE) //not allowed to attack - || ((NPCS.NPC->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_HEAL]client->ps.saberEventFlags&SEF_INWATER)&&!NPCS.NPC->client->ps.saberInFlight) )//saber in water + if ((NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) // not allowed to attack + || ((NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_HEAL)) && NPCS.NPC->client->ps.fd.forcePowerLevel[FP_HEAL] < FORCE_LEVEL_3) || + ((NPCS.NPC->client->ps.saberEventFlags & SEF_INWATER) && !NPCS.NPC->client->ps.saberInFlight)) // saber in water { - NPCS.ucmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + NPCS.ucmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); } - if ( NPCS.NPCInfo->scriptFlags&SCF_NO_ACROBATICS ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_NO_ACROBATICS) { NPCS.ucmd.upmove = 0; NPCS.NPC->client->ps.fd.forceJumpCharge = 0; } - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { Jedi_CheckDecreaseSaberAnimLevel(); } - if ( NPCS.ucmd.buttons & BUTTON_ATTACK && NPCS.NPC->client->playerTeam == NPCTEAM_ENEMY ) - { - if ( Q_irand( 0, NPCS.NPC->client->ps.fd.saberAnimLevel ) > 0 - && Q_irand( 0, NPCS.NPC->client->pers.maxHealth+10 ) > NPCS.NPC->health - && !Q_irand( 0, 3 )) - {//the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_COMBAT1, EV_COMBAT3 ), 1000 ); + if (NPCS.ucmd.buttons & BUTTON_ATTACK && NPCS.NPC->client->playerTeam == NPCTEAM_ENEMY) { + if (Q_irand(0, NPCS.NPC->client->ps.fd.saberAnimLevel) > 0 && Q_irand(0, NPCS.NPC->client->pers.maxHealth + 10) > NPCS.NPC->health && + !Q_irand(0, 3)) { // the more we're hurt and the stronger the attack we're using, the more likely we are to make a anger noise when we swing + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_COMBAT1, EV_COMBAT3), 1000); } } - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( NPCS.NPC->client->NPC_class == CLASS_TAVION - || (g_npcspskill.integer && ( NPCS.NPC->client->NPC_class == CLASS_DESANN || NPCS.NPCInfo->rank >= Q_irand( RANK_CREWMAN, RANK_CAPTAIN )))) - {//Tavion will kick in force speed if the player does... - if ( NPCS.NPC->enemy - && NPCS.NPC->enemy->s.number >= 0 && NPCS.NPC->enemy->s.number < MAX_CLIENTS - && NPCS.NPC->enemy->client - && (NPCS.NPC->enemy->client->ps.fd.forcePowersActive & (1<client->ps.fd.forcePowersActive & (1<client->NPC_class != CLASS_BOBAFETT) { + if (NPCS.NPC->client->NPC_class == CLASS_TAVION || + (g_npcspskill.integer && (NPCS.NPC->client->NPC_class == CLASS_DESANN || + NPCS.NPCInfo->rank >= Q_irand(RANK_CREWMAN, RANK_CAPTAIN)))) { // Tavion will kick in force speed if the player does... + if (NPCS.NPC->enemy && NPCS.NPC->enemy->s.number >= 0 && NPCS.NPC->enemy->s.number < MAX_CLIENTS && NPCS.NPC->enemy->client && + (NPCS.NPC->enemy->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) && !(NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED))) { int chance = 0; - switch ( g_npcspskill.integer ) - { + switch (g_npcspskill.integer) { case 0: chance = 9; break; @@ -6127,28 +4871,21 @@ static void Jedi_Attack( void ) chance = 1; break; } - if ( !Q_irand( 0, chance ) ) - { - ForceSpeed( NPCS.NPC, 0 ); + if (!Q_irand(0, chance)) { + ForceSpeed(NPCS.NPC, 0); } } } } } -extern void WP_Explode( gentity_t *self ); -qboolean Jedi_InSpecialMove( void ) -{ - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_1 - || NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_2 - || NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_3 - || NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_1 - || NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_2 - || NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_3 - || NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END - || NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRABBED ) - { - NPC_UpdateAngles( qtrue, qtrue ); +extern void WP_Explode(gentity_t *self); +qboolean Jedi_InSpecialMove(void) { + if (NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_1 || NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_2 || + NPCS.NPC->client->ps.torsoAnim == BOTH_KYLE_PA_3 || NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_1 || + NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_2 || NPCS.NPC->client->ps.torsoAnim == BOTH_PLAYER_PA_3 || + NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_END || NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRABBED) { + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } @@ -6165,26 +4902,21 @@ qboolean Jedi_InSpecialMove( void ) return qtrue; }*/ - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START - || NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD ) - { - if ( !TIMER_Done( NPCS.NPC, "draining" ) ) - {//FIXME: what do we do if we ran out of power? NPC's can't? - //FIXME: don't keep turning to face enemy or we'll end up spinning around + if (NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_START || NPCS.NPC->client->ps.torsoAnim == BOTH_FORCE_DRAIN_GRAB_HOLD) { + if (!TIMER_Done(NPCS.NPC, "draining")) { // FIXME: what do we do if we ran out of power? NPC's can't? + // FIXME: don't keep turning to face enemy or we'll end up spinning around NPCS.ucmd.buttons |= BUTTON_FORCE_DRAIN; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_TAVION_SWORDPOWER ) - { - NPCS.NPC->health += Q_irand( 1, 2 ); - if ( NPCS.NPC->health > NPCS.NPC->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (NPCS.NPC->client->ps.torsoAnim == BOTH_TAVION_SWORDPOWER) { + NPCS.NPC->health += Q_irand(1, 2); + if (NPCS.NPC->health > NPCS.NPC->client->ps.stats[STAT_MAX_HEALTH]) { NPCS.NPC->health = NPCS.NPC->client->ps.stats[STAT_MAX_HEALTH]; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return qtrue; } /*else if ( NPC->client->ps.torsoAnim == BOTH_SCEPTER_HOLD ) @@ -6239,22 +4971,18 @@ qboolean Jedi_InSpecialMove( void ) return qtrue; }*/ - if ( Jedi_CultistDestroyer( NPCS.NPC ) ) - { - if ( !NPCS.NPC->takedamage ) - {//ready to explode - if ( NPCS.NPC->useDebounceTime <= level.time ) - { - //this should damage everyone - FIXME: except other destroyers? - NPCS.NPC->client->playerTeam = NPCTEAM_FREE;//FIXME: will this destroy wampas, tusken & rancors? - NPCS.NPC->splashDamage = 200; // rough match to SP - NPCS.NPC->splashRadius = 512; // see above - WP_Explode( NPCS.NPC ); + if (Jedi_CultistDestroyer(NPCS.NPC)) { + if (!NPCS.NPC->takedamage) { // ready to explode + if (NPCS.NPC->useDebounceTime <= level.time) { + // this should damage everyone - FIXME: except other destroyers? + NPCS.NPC->client->playerTeam = NPCTEAM_FREE; // FIXME: will this destroy wampas, tusken & rancors? + NPCS.NPC->splashDamage = 200; // rough match to SP + NPCS.NPC->splashRadius = 512; // see above + WP_Explode(NPCS.NPC); return qtrue; } - if ( NPCS.NPC->enemy ) - { - NPC_FaceEnemy( qfalse ); + if (NPCS.NPC->enemy) { + NPC_FaceEnemy(qfalse); } return qtrue; } @@ -6262,74 +4990,66 @@ qboolean Jedi_InSpecialMove( void ) return qfalse; } -extern void NPC_BSST_Patrol( void ); -extern void NPC_BSSniper_Default( void ); -void NPC_BSJedi_Default( void ) -{ - if ( Jedi_InSpecialMove() ) - { +extern void NPC_BSST_Patrol(void); +extern void NPC_BSSniper_Default(void); +void NPC_BSJedi_Default(void) { + if (Jedi_InSpecialMove()) { return; } Jedi_CheckCloak(); - if( !NPCS.NPC->enemy ) - {//don't have an enemy, look for one - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (!NPCS.NPC->enemy) { // don't have an enemy, look for one + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { NPC_BSST_Patrol(); - } - else - { + } else { Jedi_Patrol(); } - } - else//if ( NPC->enemy ) - {//have an enemy - if ( Jedi_WaitingAmbush( NPCS.NPC ) ) - {//we were still waiting to drop down - must have had enemy set on me outside my AI - Jedi_Ambush( NPCS.NPC ); + } else // if ( NPC->enemy ) + { // have an enemy + if (Jedi_WaitingAmbush(NPCS.NPC)) { // we were still waiting to drop down - must have had enemy set on me outside my AI + Jedi_Ambush(NPCS.NPC); } - if ( Jedi_CultistDestroyer( NPCS.NPC ) - && !NPCS.NPCInfo->charmedTime ) - {//destroyer - //permanent effect + if (Jedi_CultistDestroyer(NPCS.NPC) && !NPCS.NPCInfo->charmedTime) { // destroyer + // permanent effect NPCS.NPCInfo->charmedTime = Q3_INFINITE; - NPCS.NPC->client->ps.fd.forcePowersActive |= ( 1 << FP_RAGE ); + NPCS.NPC->client->ps.fd.forcePowersActive |= (1 << FP_RAGE); NPCS.NPC->client->ps.fd.forcePowerDuration[FP_RAGE] = Q3_INFINITE; - //NPC->client->ps.eFlags |= EF_FORCE_DRAINED; - //FIXME: precache me! - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/movers/objects/green_beam_lp2.wav" );//test/charm.wav" ); + // NPC->client->ps.eFlags |= EF_FORCE_DRAINED; + // FIXME: precache me! + NPCS.NPC->s.loopSound = G_SoundIndex("sound/movers/objects/green_beam_lp2.wav"); // test/charm.wav" ); } - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( NPCS.NPC->enemy->enemy != NPCS.NPC && NPCS.NPC->health == NPCS.NPC->client->pers.maxHealth && DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin )>(800*800) ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + if (NPCS.NPC->enemy->enemy != NPCS.NPC && NPCS.NPC->health == NPCS.NPC->client->pers.maxHealth && + DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin) > (800 * 800)) { NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; - Boba_ChangeWeapon( WP_DISRUPTOR ); + Boba_ChangeWeapon(WP_DISRUPTOR); NPC_BSSniper_Default(); return; } } Jedi_Attack(); - //if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch if needbe... - if ( ((!NPCS.ucmd.buttons&&!NPCS.NPC->client->ps.fd.forcePowersActive)||(NPCS.NPC->enemy&&NPCS.NPC->enemy->health<=0)) && NPCS.NPCInfo->enemyCheckDebounceTime < level.time ) - {//not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), not using force powers and it's time to look again - //FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain their own list and we just access it? - gentity_t *sav_enemy = NPCS.NPC->enemy;//FIXME: what about NPC->lastEnemy? + // if we have multiple-jedi combat, probably need to keep checking (at certain debounce intervals) for a better (closer, more active) enemy and switch + // if needbe... + if (((!NPCS.ucmd.buttons && !NPCS.NPC->client->ps.fd.forcePowersActive) || (NPCS.NPC->enemy && NPCS.NPC->enemy->health <= 0)) && + NPCS.NPCInfo->enemyCheckDebounceTime < level.time) { // not doing anything (or walking toward a vanquished enemy - fixme: always taunt the player?), + // not using force powers and it's time to look again + // FIXME: build a list of all local enemies (since we have to find best anyway) for other AI factors- like when to use group attacks, determine when + // to change tactics, when surrounded, when blocked by another in the enemy group, etc. Should we build this group list or let the enemies maintain + // their own list and we just access it? + gentity_t *sav_enemy = NPCS.NPC->enemy; // FIXME: what about NPC->lastEnemy? gentity_t *newEnemy; NPCS.NPC->enemy = NULL; - newEnemy = NPC_CheckEnemy( (qboolean)(NPCS.NPCInfo->confusionTime < level.time), qfalse, qfalse ); + newEnemy = NPC_CheckEnemy((qboolean)(NPCS.NPCInfo->confusionTime < level.time), qfalse, qfalse); NPCS.NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPCS.NPC->lastEnemy = NPCS.NPC->enemy; - G_SetEnemy( NPCS.NPC, newEnemy ); + G_SetEnemy(NPCS.NPC, newEnemy); } - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 3000 ); + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 3000); } } } diff --git a/codemp/game/NPC_AI_Mark1.c b/codemp/game/NPC_AI_Mark1.c index 75909593af..c0b7e4ff4d 100644 --- a/codemp/game/NPC_AI_Mark1.c +++ b/codemp/game/NPC_AI_Mark1.c @@ -23,29 +23,28 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define TURN_OFF 0x00000100 +#define TURN_OFF 0x00000100 -#define LEFT_ARM_HEALTH 40 -#define RIGHT_ARM_HEALTH 40 -#define AMMO_POD_HEALTH 40 +#define LEFT_ARM_HEALTH 40 +#define RIGHT_ARM_HEALTH 40 +#define AMMO_POD_HEALTH 40 -#define BOWCASTER_VELOCITY 1300 -#define BOWCASTER_NPC_DAMAGE_EASY 12 -#define BOWCASTER_NPC_DAMAGE_NORMAL 24 -#define BOWCASTER_NPC_DAMAGE_HARD 36 -#define BOWCASTER_SIZE 2 -#define BOWCASTER_SPLASH_DAMAGE 0 -#define BOWCASTER_SPLASH_RADIUS 0 +#define BOWCASTER_VELOCITY 1300 +#define BOWCASTER_NPC_DAMAGE_EASY 12 +#define BOWCASTER_NPC_DAMAGE_NORMAL 24 +#define BOWCASTER_NPC_DAMAGE_HARD 36 +#define BOWCASTER_SIZE 2 +#define BOWCASTER_SPLASH_DAMAGE 0 +#define BOWCASTER_SPLASH_RADIUS 0 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -56,41 +55,40 @@ enum LSTATE_FIRED4, }; -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); void Mark1_BlasterAttack(qboolean advance); -void DeathFX( gentity_t *ent ); +void DeathFX(gentity_t *ent); -extern gitem_t *BG_FindItemForAmmo( ammo_t ammo ); +extern gitem_t *BG_FindItemForAmmo(ammo_t ammo); /* ------------------------- NPC_Mark1_Precache ------------------------- */ -void NPC_Mark1_Precache(void) -{ - G_SoundIndex( "sound/chars/mark1/misc/mark1_wakeup"); - G_SoundIndex( "sound/chars/mark1/misc/shutdown"); - G_SoundIndex( "sound/chars/mark1/misc/walk"); - G_SoundIndex( "sound/chars/mark1/misc/run"); - G_SoundIndex( "sound/chars/mark1/misc/death1"); - G_SoundIndex( "sound/chars/mark1/misc/death2"); - G_SoundIndex( "sound/chars/mark1/misc/anger"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_fire"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_pain"); - G_SoundIndex( "sound/chars/mark1/misc/mark1_explo"); - -// G_EffectIndex( "small_chunks"); - G_EffectIndex( "env/med_explode2"); - G_EffectIndex( "explosions/probeexplosion1"); - G_EffectIndex( "blaster/smoke_bolton"); - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "explosions/droidexplosion1" ); - - RegisterItem( BG_FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( BG_FindItemForAmmo( AMMO_BLASTER )); - RegisterItem( BG_FindItemForWeapon( WP_BOWCASTER )); - RegisterItem( BG_FindItemForWeapon( WP_BRYAR_PISTOL )); +void NPC_Mark1_Precache(void) { + G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup"); + G_SoundIndex("sound/chars/mark1/misc/shutdown"); + G_SoundIndex("sound/chars/mark1/misc/walk"); + G_SoundIndex("sound/chars/mark1/misc/run"); + G_SoundIndex("sound/chars/mark1/misc/death1"); + G_SoundIndex("sound/chars/mark1/misc/death2"); + G_SoundIndex("sound/chars/mark1/misc/anger"); + G_SoundIndex("sound/chars/mark1/misc/mark1_fire"); + G_SoundIndex("sound/chars/mark1/misc/mark1_pain"); + G_SoundIndex("sound/chars/mark1/misc/mark1_explo"); + + // G_EffectIndex( "small_chunks"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("explosions/probeexplosion1"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("explosions/droidexplosion1"); + + RegisterItem(BG_FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(BG_FindItemForAmmo(AMMO_BLASTER)); + RegisterItem(BG_FindItemForWeapon(WP_BOWCASTER)); + RegisterItem(BG_FindItemForWeapon(WP_BRYAR_PISTOL)); } /* @@ -98,27 +96,22 @@ void NPC_Mark1_Precache(void) NPC_Mark1_Part_Explode ------------------------- */ -void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark1_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - trap->G2API_GetBoltMatrix( self->ghoul2, 0, - bolt, - &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, - NULL, self->modelScale ); + trap->G2API_GetBoltMatrix(self->ghoul2, 0, bolt, &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, self->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); - G_PlayEffectID( G_EffectIndex("env/med_explode2"), org, dir ); + G_PlayEffectID(G_EffectIndex("env/med_explode2"), org, dir); - G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), org, dir ); + G_PlayEffectID(G_EffectIndex("blaster/smoke_bolton"), org, dir); } - //G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number ); + // G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number ); } /* @@ -126,11 +119,10 @@ void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) Mark1_Idle ------------------------- */ -void Mark1_Idle( void ) -{ +void Mark1_Idle(void) { NPC_BSIdle(); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL); } /* @@ -139,37 +131,34 @@ Mark1Dead_FireRocket - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireRocket (void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,muzzle_dir; +void Mark1Dead_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, muzzle_dir; gentity_t *missile; - int damage = 50; + int damage = 50; int bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash5"); - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, muzzle_dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - missile = CreateMissile( muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPCS.NPC, qfalse); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - //missile->methodOfDeath = MOD_ENERGY; + // missile->methodOfDeath = MOD_ENERGY; missile->methodOfDeath = MOD_ROCKET; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = BOWCASTER_SPLASH_DAMAGE; @@ -177,7 +166,6 @@ void Mark1Dead_FireRocket (void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -186,28 +174,25 @@ Mark1Dead_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1Dead_FireBlaster (void) -{ - vec3_t muzzle1,muzzle_dir; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1Dead_FireBlaster(void) { + vec3_t muzzle1, muzzle_dir; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash1"); - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, muzzle_dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, muzzle_dir); - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir); - missile = CreateMissile( muzzle1, muzzle_dir, 1600, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, muzzle_dir, 1600, 10000, NPCS.NPC, qfalse); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -216,7 +201,6 @@ void Mark1Dead_FireBlaster (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -224,8 +208,7 @@ void Mark1Dead_FireBlaster (void) Mark1_die ------------------------- */ -void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) -{ +void Mark1_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc) { /* int anim; @@ -247,16 +230,13 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } */ - G_Sound( self, CHAN_AUTO, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav",Q_irand( 1, 2)))); + G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav", Q_irand(1, 2)))); // Choose a death anim - if (Q_irand( 1, 10) > 5) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (Q_irand(1, 10) > 5) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } @@ -265,68 +245,58 @@ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int Mark1_dying ------------------------- */ -void Mark1_dying( gentity_t *self ) -{ - int num,newBolt; +void Mark1_dying(gentity_t *self) { + int num, newBolt; - if (self->client->ps.torsoTimer>0) - { - if (TIMER_Done(self,"dyingExplosion")) - { - num = Q_irand( 1, 3); + if (self->client->ps.torsoTimer > 0) { + if (TIMER_Done(self, "dyingExplosion")) { + num = Q_irand(1, 3); // Find place to generate explosion - if (num == 1) - { - num = Q_irand( 8, 10); - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, va("*flash%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - } - else - { - num = Q_irand( 1, 6); - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, va("*torso_tube%d",num) ); - NPC_Mark1_Part_Explode(self,newBolt); - NPC_SetSurfaceOnOff( self, va("torso_tube%d",num), TURN_OFF ); + if (num == 1) { + num = Q_irand(8, 10); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, va("*flash%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + } else { + num = Q_irand(1, 6); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, va("*torso_tube%d", num)); + NPC_Mark1_Part_Explode(self, newBolt); + NPC_SetSurfaceOnOff(self, va("torso_tube%d", num), TURN_OFF); } - TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1000 ) ); + TIMER_Set(self, "dyingExplosion", Q_irand(300, 1000)); } - -// int dir; -// vec3_t right; + // int dir; + // vec3_t right; // Shove to the side -// AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); -// VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); + // AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); + // VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); // See which weapons are there // Randomly fire blaster - if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm" )) // Is the blaster still on the model? + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_arm")) // Is the blaster still on the model? { - if (Q_irand( 1, 5) == 1) - { + if (Q_irand(1, 5) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireBlaster(); RestoreNPCGlobals(); } } // Randomly fire rocket - if (!trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_arm" )) // Is the rocket still on the model? + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "r_arm")) // Is the rocket still on the model? { - if (Q_irand( 1, 10) == 1) - { + if (Q_irand(1, 10) == 1) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Mark1Dead_FireRocket(); RestoreNPCGlobals(); } } } - } /* @@ -335,70 +305,59 @@ NPC_Mark1_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark1_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - int newBolt,i,chance; +void NPC_Mark1_Pain(gentity_t *self, gentity_t *attacker, int damage) { + int newBolt, i, chance; int hitLoc = gPainHitLoc; - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); // Hit in the CHEST??? - if (hitLoc==HL_CHEST) - { - chance = Q_irand( 1, 4); + if (hitLoc == HL_CHEST) { + chance = Q_irand(1, 4); - if ((chance == 1) && (damage > 5)) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((chance == 1) && (damage > 5)) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } // Hit in the left arm? - else if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) - { - if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? + else if ((hitLoc == HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { + if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*flash3" ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*flash3"); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - NPC_SetSurfaceOnOff( self, "l_arm", TURN_OFF ); + NPC_SetSurfaceOnOff(self, "l_arm", TURN_OFF); } } // Hit in the right arm? - else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? + else if ((hitLoc == HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) - { - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*flash4" ); - if ( newBolt != -1 ) - { -// G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); - NPC_Mark1_Part_Explode( self, newBolt ); + if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*flash4"); + if (newBolt != -1) { + // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); + NPC_Mark1_Part_Explode(self, newBolt); } - NPC_SetSurfaceOnOff( self, "r_arm", TURN_OFF ); + NPC_SetSurfaceOnOff(self, "r_arm", TURN_OFF); } } // Check ammo pods - else - { - for (i=0;i<6;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + else { + for (i = 0; i < 6; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, va("*torso_tube%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark1_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, va("*torso_tube%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark1_Part_Explode(self, newBolt); } - NPC_SetSurfaceOnOff( self, va("torso_tube%d",(i+1)), TURN_OFF ); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetSurfaceOnOff(self, va("torso_tube%d", (i + 1)), TURN_OFF); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); break; } } @@ -406,10 +365,8 @@ void NPC_Mark1_Pain(gentity_t *self, gentity_t *attacker, int damage) } // Are both guns shot off? - if ((trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm" )>0) && - (trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_arm" )>0)) - { - G_Damage(self,NULL,NULL,NULL,NULL,self->health,0,MOD_UNKNOWN); + if ((trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "l_arm") > 0) && (trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "r_arm") > 0)) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, 0, MOD_UNKNOWN); } } @@ -419,18 +376,16 @@ Mark1_Hunt - look for enemy. -------------------------` */ -void Mark1_Hunt(void) -{ +void Mark1_Hunt(void) { - if ( NPCS.NPCInfo->goalEntity == NULL ) - { + if (NPCS.NPCInfo->goalEntity == NULL) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCS.NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -439,61 +394,48 @@ Mark1_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ -void Mark1_FireBlaster(void) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; -// static vec3_t muzzle; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt; +void Mark1_FireBlaster(void) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + // static vec3_t muzzle; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt; // Which muzzle to fire from? - if ((NPCS.NPCInfo->localState <= LSTATE_FIRED0) || (NPCS.NPCInfo->localState == LSTATE_FIRED4)) - { + if ((NPCS.NPCInfo->localState <= LSTATE_FIRED0) || (NPCS.NPCInfo->localState == LSTATE_FIRED4)) { NPCS.NPCInfo->localState = LSTATE_FIRED1; bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash1"); - } - else if (NPCS.NPCInfo->localState == LSTATE_FIRED1) - { + } else if (NPCS.NPCInfo->localState == LSTATE_FIRED1) { NPCS.NPCInfo->localState = LSTATE_FIRED2; bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash2"); - } - else if (NPCS.NPCInfo->localState == LSTATE_FIRED2) - { + } else if (NPCS.NPCInfo->localState == LSTATE_FIRED2) { NPCS.NPCInfo->localState = LSTATE_FIRED3; bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash3"); - } - else - { + } else { NPCS.NPCInfo->localState = LSTATE_FIRED4; bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash4"); } - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); - if (NPCS.NPC->health) - { - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPCS.NPC->r.currentAngles, forward, vright, up); + if (NPCS.NPC->health) { + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPCS.NPC->r.currentAngles, forward, vright, up); } - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, forward ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle1, forward); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -502,7 +444,6 @@ void Mark1_FireBlaster(void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -510,57 +451,47 @@ void Mark1_FireBlaster(void) Mark1_BlasterAttack ------------------------- */ -void Mark1_BlasterAttack(qboolean advance ) -{ +void Mark1_BlasterAttack(qboolean advance) { int chance; - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - chance = Q_irand( 1, 5); + chance = Q_irand(1, 5); NPCS.NPCInfo->burstCount++; - if (NPCS.NPCInfo->burstCount<3) // Too few shots this burst? + if (NPCS.NPCInfo->burstCount < 3) // Too few shots this burst? { - chance = 2; // Force it to keep firing. - } - else if (NPCS.NPCInfo->burstCount>12) // Too many shots fired this burst? + chance = 2; // Force it to keep firing. + } else if (NPCS.NPCInfo->burstCount > 12) // Too many shots fired this burst? { NPCS.NPCInfo->burstCount = 0; - chance = 1; // Force it to stop firing. + chance = 1; // Force it to stop firing. } // Stop firing. - if (chance == 1) - { + if (chance == 1) { NPCS.NPCInfo->burstCount = 0; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPCS.NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. - } - else - { - if (TIMER_Done( NPCS.NPC, "attackDelay2" )) // Can't be shooting every frame. + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(1000, 3000)); + NPCS.NPC->client->ps.torsoTimer = 0; // Just in case the firing anim is running. + } else { + if (TIMER_Done(NPCS.NPC, "attackDelay2")) // Can't be shooting every frame. { - TIMER_Set( NPCS.NPC, "attackDelay2", Q_irand( 50, 50) ); + TIMER_Set(NPCS.NPC, "attackDelay2", Q_irand(50, 50)); Mark1_FireBlaster(); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } return; } - } - else if (advance) - { - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPCS.NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. + } else if (advance) { + if (NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPCS.NPC->client->ps.torsoTimer = 0; // Just in case the firing anim is running. } Mark1_Hunt(); - } - else // Make sure he's not firing. + } else // Make sure he's not firing. { - if ( NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) - { - NPCS.NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. + if (NPCS.NPC->client->ps.torsoAnim == BOTH_ATTACK1) { + NPCS.NPC->client->ps.torsoTimer = 0; // Just in case the firing anim is running. } } } @@ -570,39 +501,36 @@ void Mark1_BlasterAttack(qboolean advance ) Mark1_FireRocket ------------------------- */ -void Mark1_FireRocket(void) -{ - mdxaBone_t boltMatrix; - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; +void Mark1_FireRocket(void) { + mdxaBone_t boltMatrix; + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; int bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash5"); gentity_t *missile; - int damage = 50; + int damage = 50; - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); -// G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); + // G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire" )); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); - missile = CreateMissile( muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPCS.NPC, qfalse); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -613,7 +541,6 @@ void Mark1_FireRocket(void) // we don't want it to bounce missile->bounceCount = 0; - } /* @@ -621,16 +548,13 @@ void Mark1_FireRocket(void) Mark1_RocketAttack ------------------------- */ -void Mark1_RocketAttack( qboolean advance ) -{ - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? +void Mark1_RocketAttack(qboolean advance) { + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 1000, 3000) ); - NPC_SetAnim( NPCS.NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(1000, 3000)); + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); Mark1_FireRocket(); - } - else if (advance) - { + } else if (advance) { Mark1_Hunt(); } } @@ -640,83 +564,66 @@ void Mark1_RocketAttack( qboolean advance ) Mark1_AttackDecision ------------------------- */ -void Mark1_AttackDecision( void ) -{ - int blasterTest,rocketTest; - float distance; - distance_e distRate; - qboolean visible; - qboolean advance; - - //randomly talk - if ( TIMER_Done(NPCS.NPC,"patrolNoise") ) - { - if (TIMER_Done(NPCS.NPC,"angerNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); +void Mark1_AttackDecision(void) { + int blasterTest, rocketTest; + float distance; + distance_e distRate; + qboolean visible; + qboolean advance; + + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + if (TIMER_Done(NPCS.NPC, "angerNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(4000, 10000)); } } // Enemy is dead or he has no enemy. - if ((NPCS.NPC->enemy->health<1) || ( NPC_CheckEnemyExt(qfalse) == qfalse )) - { + if ((NPCS.NPC->enemy->health < 1) || (NPC_CheckEnemyExt(qfalse) == qfalse)) { NPCS.NPC->enemy = NULL; return; } // Rate our distance to the target and visibility - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + distRate = (distance > MIN_MELEE_RANGE_SQR) ? DIST_LONG : DIST_MELEE; + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { Mark1_Hunt(); return; } // See if the side weapons are there - blasterTest = trap->G2API_GetSurfaceRenderStatus( NPCS.NPC->ghoul2, 0, "l_arm" ); - rocketTest = trap->G2API_GetSurfaceRenderStatus( NPCS.NPC->ghoul2, 0, "r_arm" ); + blasterTest = trap->G2API_GetSurfaceRenderStatus(NPCS.NPC->ghoul2, 0, "l_arm"); + rocketTest = trap->G2API_GetSurfaceRenderStatus(NPCS.NPC->ghoul2, 0, "r_arm"); // It has both side weapons - if (!blasterTest && !rocketTest) - { - ; // So do nothing. - } - else if (blasterTest!=-1 - &&blasterTest) - { + if (!blasterTest && !rocketTest) { + ; // So do nothing. + } else if (blasterTest != -1 && blasterTest) { distRate = DIST_LONG; - } - else if (rocketTest!=-1 - &&rocketTest) - { + } else if (rocketTest != -1 && rocketTest) { distRate = DIST_MELEE; - } - else // It should never get here, but just in case + } else // It should never get here, but just in case { NPCS.NPC->health = 0; NPCS.NPC->client->ps.stats[STAT_HEALTH] = 0; - //GEntity_DieFunc(NPC, NPC, NPC, 100, MOD_UNKNOWN); - if (NPCS.NPC->die) - { + // GEntity_DieFunc(NPC, NPC, NPC, 100, MOD_UNKNOWN); + if (NPCS.NPC->die) { NPCS.NPC->die(NPCS.NPC, NPCS.NPC, NPCS.NPC, 100, MOD_UNKNOWN); } } // We can see enemy so shoot him if timers let you. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - if (distRate == DIST_MELEE) - { + if (distRate == DIST_MELEE) { Mark1_BlasterAttack(advance); - } - else if (distRate == DIST_LONG) - { + } else if (distRate == DIST_LONG) { Mark1_RocketAttack(advance); } } @@ -726,57 +633,45 @@ void Mark1_AttackDecision( void ) Mark1_Patrol ------------------------- */ -void Mark1_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark1_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk -// if (TIMER_Done(NPC,"patrolNoise")) -// { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); -// -// TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); -// } + // randomly talk + // if (TIMER_Done(NPC,"patrolNoise")) + // { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // + // TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + // } } - } - /* ------------------------- NPC_BSMark1_Default ------------------------- */ -void NPC_BSMark1_Default( void ) -{ - //NPC->e_DieFunc = dieF_Mark1_die; +void NPC_BSMark1_Default(void) { + // NPC->e_DieFunc = dieF_Mark1_die; - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; Mark1_AttackDecision(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark1_Patrol(); - } - else - { + } else { Mark1_Idle(); } } diff --git a/codemp/game/NPC_AI_Mark2.c b/codemp/game/NPC_AI_Mark2.c index 90da001b6b..231b94f23c 100644 --- a/codemp/game/NPC_AI_Mark2.c +++ b/codemp/game/NPC_AI_Mark2.c @@ -23,42 +23,40 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -#define AMMO_POD_HEALTH 1 -#define TURN_OFF 0x00000100 +#define AMMO_POD_HEALTH 1 +#define TURN_OFF 0x00000100 -#define VELOCITY_DECAY 0.25 -#define MAX_DISTANCE 256 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) -#define MIN_DISTANCE 24 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define VELOCITY_DECAY 0.25 +#define MAX_DISTANCE 256 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) +#define MIN_DISTANCE 24 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -extern gitem_t *BG_FindItemForAmmo( ammo_t ammo ); +extern gitem_t *BG_FindItemForAmmo(ammo_t ammo); -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_DROPPINGDOWN, LSTATE_DOWN, LSTATE_RISINGUP, }; -void NPC_Mark2_Precache( void ) -{ - G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" );// blows up on death - G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_fire" ); - G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); - - G_EffectIndex( "explosions/droidexplosion1" ); - G_EffectIndex( "env/med_explode2" ); - G_EffectIndex( "blaster/smoke_bolton" ); - G_EffectIndex( "bryar/muzzle_flash" ); - - RegisterItem( BG_FindItemForWeapon( WP_BRYAR_PISTOL )); - RegisterItem( BG_FindItemForAmmo( AMMO_METAL_BOLTS)); - RegisterItem( BG_FindItemForAmmo( AMMO_POWERCELL )); - RegisterItem( BG_FindItemForAmmo( AMMO_BLASTER )); +void NPC_Mark2_Precache(void) { + G_SoundIndex("sound/chars/mark2/misc/mark2_explo"); // blows up on death + G_SoundIndex("sound/chars/mark2/misc/mark2_pain"); + G_SoundIndex("sound/chars/mark2/misc/mark2_fire"); + G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); + + G_EffectIndex("explosions/droidexplosion1"); + G_EffectIndex("env/med_explode2"); + G_EffectIndex("blaster/smoke_bolton"); + G_EffectIndex("bryar/muzzle_flash"); + + RegisterItem(BG_FindItemForWeapon(WP_BRYAR_PISTOL)); + RegisterItem(BG_FindItemForAmmo(AMMO_METAL_BOLTS)); + RegisterItem(BG_FindItemForAmmo(AMMO_POWERCELL)); + RegisterItem(BG_FindItemForAmmo(AMMO_BLASTER)); } /* @@ -66,28 +64,23 @@ void NPC_Mark2_Precache( void ) NPC_Mark2_Part_Explode ------------------------- */ -void NPC_Mark2_Part_Explode( gentity_t *self, int bolt ) -{ - if ( bolt >=0 ) - { - mdxaBone_t boltMatrix; - vec3_t org, dir; +void NPC_Mark2_Part_Explode(gentity_t *self, int bolt) { + if (bolt >= 0) { + mdxaBone_t boltMatrix; + vec3_t org, dir; - trap->G2API_GetBoltMatrix( self->ghoul2, 0, - bolt, - &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, - NULL, self->modelScale ); + trap->G2API_GetBoltMatrix(self->ghoul2, 0, bolt, &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, self->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, dir); - G_PlayEffectID( G_EffectIndex("env/med_explode2"), org, dir ); - G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), org, dir ); + G_PlayEffectID(G_EffectIndex("env/med_explode2"), org, dir); + G_PlayEffectID(G_EffectIndex("blaster/smoke_bolton"), org, dir); } - //G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number); + // G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number); - self->count++; // Count of pods blown off + self->count++; // Count of pods blown off } /* @@ -96,36 +89,31 @@ NPC_Mark2_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ -void NPC_Mark2_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - int newBolt,i; +void NPC_Mark2_Pain(gentity_t *self, gentity_t *attacker, int damage) { + int newBolt, i; int hitLoc = gPainHitLoc; - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - for (i=0;i<3;i++) - { - if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? + for (i = 0; i < 3; i++) { + if ((hitLoc == HL_GENERIC1 + i) && (self->locationDamage[HL_GENERIC1 + i] > AMMO_POD_HEALTH)) // Blow it up? { - if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) - { - newBolt = trap->G2API_AddBolt( self->ghoul2, 0, va("torso_canister%d",(i+1)) ); - if ( newBolt != -1 ) - { - NPC_Mark2_Part_Explode(self,newBolt); + if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { + newBolt = trap->G2API_AddBolt(self->ghoul2, 0, va("torso_canister%d", (i + 1))); + if (newBolt != -1) { + NPC_Mark2_Part_Explode(self, newBolt); } - NPC_SetSurfaceOnOff( self, va("torso_canister%d",(i+1)), TURN_OFF ); + NPC_SetSurfaceOnOff(self, va("torso_canister%d", (i + 1)), TURN_OFF); break; } } } - G_Sound( self, CHAN_AUTO, G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" )); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_pain")); // If any pods were blown off, kill him - if (self->count > 0) - { - G_Damage( self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN ); + if (self->count > 0) { + G_Damage(self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN); } } @@ -134,18 +122,16 @@ void NPC_Mark2_Pain(gentity_t *self, gentity_t *attacker, int damage) Mark2_Hunt ------------------------- */ -void Mark2_Hunt(void) -{ - if ( NPCS.NPCInfo->goalEntity == NULL ) - { +void Mark2_Hunt(void) { + if (NPCS.NPCInfo->goalEntity == NULL) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; } // Turn toward him before moving towards him. - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); NPCS.NPCInfo->combatMove = qtrue; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } /* @@ -153,39 +139,33 @@ void Mark2_Hunt(void) Mark2_FireBlaster ------------------------- */ -void Mark2_FireBlaster(qboolean advance) -{ - vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; - static vec3_t forward, vright, up; -// static vec3_t muzzle; - gentity_t *missile; - mdxaBone_t boltMatrix; +void Mark2_FireBlaster(qboolean advance) { + vec3_t muzzle1, enemy_org1, delta1, angleToEnemy1; + static vec3_t forward, vright, up; + // static vec3_t muzzle; + gentity_t *missile; + mdxaBone_t boltMatrix; int bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash"); - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle1); - if (NPCS.NPC->health) - { - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorSubtract (enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); - } - else - { - AngleVectors (NPCS.NPC->r.currentAngles, forward, vright, up); + if (NPCS.NPC->health) { + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org1); + VectorSubtract(enemy_org1, muzzle1, delta1); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); + } else { + AngleVectors(NPCS.NPC->r.currentAngles, forward, vright, up); } - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, forward ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle1, forward); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); - missile = CreateMissile( muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle1, forward, 1600, 10000, NPCS.NPC, qfalse); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -194,7 +174,6 @@ void Mark2_FireBlaster(qboolean advance) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -202,23 +181,18 @@ void Mark2_FireBlaster(qboolean advance) Mark2_BlasterAttack ------------------------- */ -void Mark2_BlasterAttack(qboolean advance) -{ - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? +void Mark2_BlasterAttack(qboolean advance) { + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - if (NPCS.NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. + if (NPCS.NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. { - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2000) ); - } - else - { - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 100, 500) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2000)); + } else { + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(100, 500)); } Mark2_FireBlaster(advance); return; - } - else if (advance) - { + } else if (advance) { Mark2_Hunt(); } } @@ -228,122 +202,101 @@ void Mark2_BlasterAttack(qboolean advance) Mark2_AttackDecision ------------------------- */ -void Mark2_AttackDecision( void ) -{ - float distance; - qboolean visible; - qboolean advance; +void Mark2_AttackDecision(void) { + float distance; + qboolean visible; + qboolean advance; - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); // He's been ordered to get up - if (NPCS.NPCInfo->localState == LSTATE_RISINGUP) - { + if (NPCS.NPCInfo->localState == LSTATE_RISINGUP) { NPCS.NPC->flags &= ~FL_SHIELDED; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - if ((NPCS.NPC->client->ps.legsTimer<=0) && - NPCS.NPC->client->ps.torsoAnim == BOTH_RUN1START ) - { - NPCS.NPCInfo->localState = LSTATE_NONE; // He's up again. + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + if ((NPCS.NPC->client->ps.legsTimer <= 0) && NPCS.NPC->client->ps.torsoAnim == BOTH_RUN1START) { + NPCS.NPCInfo->localState = LSTATE_NONE; // He's up again. } return; } // If we cannot see our target, move to see it - if ((!visible) || (!NPC_FaceEnemy(qtrue))) - { + if ((!visible) || (!NPC_FaceEnemy(qtrue))) { // If he's going down or is down, make him get up - if ((NPCS.NPCInfo->localState == LSTATE_DOWN) || (NPCS.NPCInfo->localState == LSTATE_DROPPINGDOWN)) - { - if ( TIMER_Done( NPCS.NPC, "downTime" ) ) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) + if ((NPCS.NPCInfo->localState == LSTATE_DOWN) || (NPCS.NPCInfo->localState == LSTATE_DROPPINGDOWN)) { + if (TIMER_Done(NPCS.NPC, "downTime")) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) { NPCS.NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPCS.NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPCS.NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - } - else - { + } else { Mark2_Hunt(); } return; } // He's down but he could advance if he wants to. - if ((advance) && (TIMER_Done( NPCS.NPC, "downTime" )) && (NPCS.NPCInfo->localState == LSTATE_DOWN)) - { + if ((advance) && (TIMER_Done(NPCS.NPC, "downTime")) && (NPCS.NPCInfo->localState == LSTATE_DOWN)) { NPCS.NPCInfo->localState = LSTATE_RISINGUP; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPCS.NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPCS.NPC, "runTime", Q_irand(3000, 8000)); // So he runs for a while before testing to see if he should drop down. } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // Dropping down to shoot - if (NPCS.NPCInfo->localState == LSTATE_DROPPINGDOWN) - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); - TIMER_Set( NPCS.NPC, "downTime", Q_irand( 3000, 9000) ); + if (NPCS.NPCInfo->localState == LSTATE_DROPPINGDOWN) { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE); + TIMER_Set(NPCS.NPC, "downTime", Q_irand(3000, 9000)); - if ((NPCS.NPC->client->ps.legsTimer<=0) && NPCS.NPC->client->ps.torsoAnim == BOTH_RUN1STOP ) - { + if ((NPCS.NPC->client->ps.legsTimer <= 0) && NPCS.NPC->client->ps.torsoAnim == BOTH_RUN1STOP) { NPCS.NPC->flags |= FL_SHIELDED; NPCS.NPCInfo->localState = LSTATE_DOWN; } } // He's down and shooting - else if (NPCS.NPCInfo->localState == LSTATE_DOWN) - { - NPCS.NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles + else if (NPCS.NPCInfo->localState == LSTATE_DOWN) { + NPCS.NPC->flags |= FL_SHIELDED; // only damagable by lightsabers and missiles Mark2_BlasterAttack(qfalse); - } - else if (TIMER_Done( NPCS.NPC, "runTime" )) // Lowering down to attack. But only if he's done running at you. + } else if (TIMER_Done(NPCS.NPC, "runTime")) // Lowering down to attack. But only if he's done running at you. { NPCS.NPCInfo->localState = LSTATE_DROPPINGDOWN; - } - else if (advance) - { + } else if (advance) { // We can see enemy so shoot him if timer lets you. Mark2_BlasterAttack(advance); } } - /* ------------------------- Mark2_Patrol ------------------------- */ -void Mark2_Patrol( void ) -{ - if ( NPC_CheckPlayerTeamStealth() ) - { -// G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); - NPC_UpdateAngles( qtrue, qtrue ); +void Mark2_Patrol(void) { + if (NPC_CheckPlayerTeamStealth()) { + // G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_MoveToGoal(qtrue); + NPC_UpdateAngles(qtrue, qtrue); } - //randomly talk - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { -// G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } } } @@ -353,29 +306,20 @@ void Mark2_Patrol( void ) Mark2_Idle ------------------------- */ -void Mark2_Idle( void ) -{ - NPC_BSIdle(); -} +void Mark2_Idle(void) { NPC_BSIdle(); } /* ------------------------- NPC_BSMark2_Default ------------------------- */ -void NPC_BSMark2_Default( void ) -{ - if ( NPCS.NPC->enemy ) - { +void NPC_BSMark2_Default(void) { + if (NPCS.NPC->enemy) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; Mark2_AttackDecision(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Mark2_Patrol(); - } - else - { + } else { Mark2_Idle(); } } diff --git a/codemp/game/NPC_AI_MineMonster.c b/codemp/game/NPC_AI_MineMonster.c index 3c801728d1..4ec8dd5b17 100644 --- a/codemp/game/NPC_AI_MineMonster.c +++ b/codemp/game/NPC_AI_MineMonster.c @@ -23,83 +23,70 @@ along with this program; if not, see . #include "b_local.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 54 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 54 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 128 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 128 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 /* ------------------------- NPC_MineMonster_Precache ------------------------- */ -void NPC_MineMonster_Precache( void ) -{ +void NPC_MineMonster_Precache(void) { int i; - for ( i = 0; i < 4; i++ ) - { - G_SoundIndex( va("sound/chars/mine/misc/bite%i.wav", i+1 )); - G_SoundIndex( va("sound/chars/mine/misc/miss%i.wav", i+1 )); + for (i = 0; i < 4; i++) { + G_SoundIndex(va("sound/chars/mine/misc/bite%i.wav", i + 1)); + G_SoundIndex(va("sound/chars/mine/misc/miss%i.wav", i + 1)); } } - /* ------------------------- MineMonster_Idle ------------------------- */ -void MineMonster_Idle( void ) -{ - if ( UpdateGoal() ) - { +void MineMonster_Idle(void) { + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - /* ------------------------- MineMonster_Patrol ------------------------- */ -void MineMonster_Patrol( void ) -{ +void MineMonster_Patrol(void) { vec3_t dif; NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPCS.NPC, "patrolTime" )) - { - TIMER_Set( NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPCS.NPC, "patrolTime")) { + TIMER_Set(NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } - //rwwFIXMEFIXME: Care about all clients, not just client 0 - //OJKFIXME: clietnum 0 - VectorSubtract( g_entities[0].r.currentOrigin, NPCS.NPC->r.currentOrigin, dif ); + // rwwFIXMEFIXME: Care about all clients, not just client 0 + // OJKFIXME: clietnum 0 + VectorSubtract(g_entities[0].r.currentOrigin, NPCS.NPC->r.currentOrigin, dif); - if ( VectorLengthSquared( dif ) < 256 * 256 ) - { - G_SetEnemy( NPCS.NPC, &g_entities[0] ); + if (VectorLengthSquared(dif) < 256 * 256) { + G_SetEnemy(NPCS.NPC, &g_entities[0]); } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { MineMonster_Idle(); return; } @@ -110,141 +97,112 @@ void MineMonster_Patrol( void ) MineMonster_Move ------------------------- */ -void MineMonster_Move( qboolean visible ) -{ - if ( NPCS.NPCInfo->localState != LSTATE_WAITING ) - { +void MineMonster_Move(qboolean visible) { + if (NPCS.NPCInfo->localState != LSTATE_WAITING) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPC_MoveToGoal( qtrue ); - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -void MineMonster_TryDamage( gentity_t *enemy, int damage ) -{ - vec3_t end, dir; - trace_t tr; +void MineMonster_TryDamage(gentity_t *enemy, int damage) { + vec3_t end, dir; + trace_t tr; - if ( !enemy ) - { + if (!enemy) { return; } - AngleVectors( NPCS.NPC->client->ps.viewangles, dir, NULL, NULL ); - VectorMA( NPCS.NPC->r.currentOrigin, MIN_DISTANCE, dir, end ); + AngleVectors(NPCS.NPC->client->ps.viewangles, dir, NULL, NULL); + VectorMA(NPCS.NPC->r.currentOrigin, MIN_DISTANCE, dir, end); // Should probably trace from the mouth, but, ah well. - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE ) - { - G_Damage( &g_entities[tr.entityNum], NPCS.NPC, NPCS.NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - G_Sound( NPCS.NPC, CHAN_AUTO, G_EffectIndex(va("sound/chars/mine/misc/bite%i.wav", Q_irand(1,4)))); - } - else - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_EffectIndex(va("sound/chars/mine/misc/miss%i.wav", Q_irand(1,4)))); + if (tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE) { + G_Damage(&g_entities[tr.entityNum], NPCS.NPC, NPCS.NPC, dir, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + G_Sound(NPCS.NPC, CHAN_AUTO, G_EffectIndex(va("sound/chars/mine/misc/bite%i.wav", Q_irand(1, 4)))); + } else { + G_Sound(NPCS.NPC, CHAN_AUTO, G_EffectIndex(va("sound/chars/mine/misc/miss%i.wav", Q_irand(1, 4)))); } } //------------------------------ -void MineMonster_Attack( void ) -{ - if ( !TIMER_Exists( NPCS.NPC, "attacking" )) - { +void MineMonster_Attack(void) { + if (!TIMER_Exists(NPCS.NPC, "attacking")) { // usually try and play a jump attack if the player somehow got above them....or just really rarely - if ( NPCS.NPC->enemy && ((NPCS.NPC->enemy->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f ) - || Q_flrand(0.0f, 1.0f) > 0.8f )) - { + if (NPCS.NPC->enemy && + ((NPCS.NPC->enemy->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2] > 10 && Q_flrand(0.0f, 1.0f) > 0.1f) || Q_flrand(0.0f, 1.0f) > 0.8f)) { // Going to do ATTACK4 - TIMER_Set( NPCS.NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attacking", 1750 + Q_flrand(0.0f, 1.0f) * 200); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPCS.NPC, "attack2_dmg", 950 ); // level two damage - } - else if ( Q_flrand(0.0f, 1.0f) > 0.5f ) - { - if ( Q_flrand(0.0f, 1.0f) > 0.8f ) - { + TIMER_Set(NPCS.NPC, "attack2_dmg", 950); // level two damage + } else if (Q_flrand(0.0f, 1.0f) > 0.5f) { + if (Q_flrand(0.0f, 1.0f) > 0.8f) { // Going to do ATTACK3, (rare) - TIMER_Set( NPCS.NPC, "attacking", 850 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attacking", 850); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPCS.NPC, "attack2_dmg", 400 ); // level two damage - } - else - { + TIMER_Set(NPCS.NPC, "attack2_dmg", 400); // level two damage + } else { // Going to do ATTACK1 - TIMER_Set( NPCS.NPC, "attacking", 850 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attacking", 850); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPCS.NPC, "attack1_dmg", 450 ); // level one damage + TIMER_Set(NPCS.NPC, "attack1_dmg", 450); // level one damage } - } - else - { + } else { // Going to do ATTACK2 - TIMER_Set( NPCS.NPC, "attacking", 1250 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + TIMER_Set(NPCS.NPC, "attacking", 1250); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - TIMER_Set( NPCS.NPC, "attack1_dmg", 700 ); // level one damage + TIMER_Set(NPCS.NPC, "attack1_dmg", 700); // level one damage } - } - else - { + } else { // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPCS.NPC, "attack1_dmg", qtrue )) - { - MineMonster_TryDamage( NPCS.NPC->enemy, 5 ); - } - else if ( TIMER_Done2( NPCS.NPC, "attack2_dmg", qtrue )) - { - MineMonster_TryDamage( NPCS.NPC->enemy, 10 ); + if (TIMER_Done2(NPCS.NPC, "attack1_dmg", qtrue)) { + MineMonster_TryDamage(NPCS.NPC->enemy, 5); + } else if (TIMER_Done2(NPCS.NPC, "attack2_dmg", qtrue)) { + MineMonster_TryDamage(NPCS.NPC->enemy, 10); } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPCS.NPC, "attacking", qtrue ); + TIMER_Done2(NPCS.NPC, "attacking", qtrue); } //---------------------------------- -void MineMonster_Combat( void ) -{ +void MineMonster_Combat(void) { float distance; qboolean advance; // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS4( NPCS.NPC->enemy ) || UpdateGoal( )) - { + if (!NPC_ClearLOS4(NPCS.NPC->enemy) || UpdateGoal()) { NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - distance = DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); + distance = DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); - advance = (qboolean)( distance > MIN_DISTANCE_SQR ? qtrue : qfalse ); + advance = (qboolean)(distance > MIN_DISTANCE_SQR ? qtrue : qfalse); - if (( advance || NPCS.NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPCS.NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCS.NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPCS.NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPCS.NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPCS.NPC, "takingPain", qtrue)) { NPCS.NPCInfo->localState = LSTATE_CLEAR; + } else { + MineMonster_Move(qtrue); } - else - { - MineMonster_Move( qtrue ); - } - } - else - { + } else { MineMonster_Attack(); } } @@ -254,48 +212,38 @@ void MineMonster_Combat( void ) NPC_MineMonster_Pain ------------------------- */ -void NPC_MineMonster_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->client->pers.maxHealth*100.0f) ); +void NPC_MineMonster_Pain(gentity_t *self, gentity_t *attacker, int damage) { + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->client->pers.maxHealth * 100.0f)); - if ( damage >= 10 ) - { - TIMER_Remove( self, "attacking" ); - TIMER_Remove( self, "attacking1_dmg" ); - TIMER_Remove( self, "attacking2_dmg" ); - TIMER_Set( self, "takingPain", 1350 ); + if (damage >= 10) { + TIMER_Remove(self, "attacking"); + TIMER_Remove(self, "attacking1_dmg"); + TIMER_Remove(self, "attacking2_dmg"); + TIMER_Set(self, "takingPain", 1350); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } - /* ------------------------- NPC_BSMineMonster_Default ------------------------- */ -void NPC_BSMineMonster_Default( void ) -{ - if ( NPCS.NPC->enemy ) - { +void NPC_BSMineMonster_Default(void) { + if (NPCS.NPC->enemy) { MineMonster_Combat(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { MineMonster_Patrol(); - } - else - { + } else { MineMonster_Idle(); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codemp/game/NPC_AI_Rancor.c b/codemp/game/NPC_AI_Rancor.c index 0fb5834bf9..43723a7b80 100644 --- a/codemp/game/NPC_AI_Rancor.c +++ b/codemp/game/NPC_AI_Rancor.c @@ -22,27 +22,25 @@ along with this program; if not, see . #include "b_local.h" -extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex ); +extern void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex); // These define the working combat range for these suckers -#define MIN_DISTANCE 128 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 128 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 1024 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 1024 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 -void Rancor_SetBolts( gentity_t *self ) -{ - if ( self && self->client ) - { +void Rancor_SetBolts(gentity_t *self) { + if (self && self->client) { renderInfo_t *ri = &self->client->renderInfo; - ri->handRBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*r_hand" ); - ri->handLBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*l_hand" ); - ri->headBolt = trap->G2API_AddBolt( self->ghoul2, 0, "*head_eyes" ); - ri->torsoBolt = trap->G2API_AddBolt( self->ghoul2, 0, "jaw_bone" ); + ri->handRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_hand"); + ri->handLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_hand"); + ri->headBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*head_eyes"); + ri->torsoBolt = trap->G2API_AddBolt(self->ghoul2, 0, "jaw_bone"); } } @@ -51,44 +49,36 @@ void Rancor_SetBolts( gentity_t *self ) NPC_Rancor_Precache ------------------------- */ -void NPC_Rancor_Precache( void ) -{ +void NPC_Rancor_Precache(void) { int i; - for ( i = 1; i < 3; i ++ ) - { - G_SoundIndex( va("sound/chars/rancor/snort_%d.wav", i) ); + for (i = 1; i < 3; i++) { + G_SoundIndex(va("sound/chars/rancor/snort_%d.wav", i)); } - G_SoundIndex( "sound/chars/rancor/swipehit.wav" ); - G_SoundIndex( "sound/chars/rancor/chomp.wav" ); + G_SoundIndex("sound/chars/rancor/swipehit.wav"); + G_SoundIndex("sound/chars/rancor/chomp.wav"); } - /* ------------------------- Rancor_Idle ------------------------- */ -void Rancor_Idle( void ) -{ +void Rancor_Idle(void) { NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - -qboolean Rancor_CheckRoar( gentity_t *self ) -{ - if ( !self->wait ) - {//haven't ever gotten mad yet - self->wait = 1;//do this only once +qboolean Rancor_CheckRoar(gentity_t *self) { + if (!self->wait) { // haven't ever gotten mad yet + self->wait = 1; // do this only once self->client->ps.eFlags2 |= EF2_ALERTED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( self, "rageTime", self->client->ps.legsTimer ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(self, "rageTime", self->client->ps.legsTimer); return qtrue; } return qfalse; @@ -98,31 +88,25 @@ qboolean Rancor_CheckRoar( gentity_t *self ) Rancor_Patrol ------------------------- */ -void Rancor_Patrol( void ) -{ +void Rancor_Patrol(void) { NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPCS.NPC, "patrolTime" )) - { - TIMER_Set( NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPCS.NPC, "patrolTime")) { + TIMER_Set(NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Rancor_Idle(); return; } - Rancor_CheckRoar( NPCS.NPC ); - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); + Rancor_CheckRoar(NPCS.NPC); + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(5000, 15000)); } /* @@ -130,190 +114,147 @@ void Rancor_Patrol( void ) Rancor_Move ------------------------- */ -void Rancor_Move( qboolean visible ) -{ - if ( NPCS.NPCInfo->localState != LSTATE_WAITING ) - { +void Rancor_Move(qboolean visible) { + if (NPCS.NPCInfo->localState != LSTATE_WAITING) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - if ( !NPC_MoveToGoal( qtrue ) ) - { + if (!NPC_MoveToGoal(qtrue)) { NPCS.NPCInfo->consecutiveBlockedMoves++; - } - else - { + } else { NPCS.NPCInfo->consecutiveBlockedMoves = 0; } - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -extern void G_Knockdown( gentity_t *victim ); -extern void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, qboolean postDeath ); -extern float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ); -extern int NPC_GetEntsNearBolt( int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); - -void Rancor_DropVictim( gentity_t *self ) -{ - //FIXME: if Rancor dies, it should drop its victim. - //FIXME: if Rancor is removed, it must remove its victim. - if ( self->activator ) - { - if ( self->activator->client ) - { +extern void G_Knockdown(gentity_t *victim); +extern void G_Dismember(gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, + qboolean postDeath); +extern float NPC_EntRangeFromBolt(gentity_t *targEnt, int boltIndex); +extern int NPC_GetEntsNearBolt(int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg); + +void Rancor_DropVictim(gentity_t *self) { + // FIXME: if Rancor dies, it should drop its victim. + // FIXME: if Rancor is removed, it must remove its victim. + if (self->activator) { + if (self->activator->client) { self->activator->client->ps.eFlags2 &= ~EF2_HELD_BY_MONSTER; self->activator->client->ps.hasLookTarget = qfalse; self->activator->client->ps.lookTarget = ENTITYNUM_NONE; self->activator->client->ps.viewangles[ROLL] = 0; - SetClientViewAngle( self->activator, self->activator->client->ps.viewangles ); + SetClientViewAngle(self->activator, self->activator->client->ps.viewangles); self->activator->r.currentAngles[PITCH] = self->activator->r.currentAngles[ROLL] = 0; - G_SetAngles( self->activator, self->activator->r.currentAngles ); + G_SetAngles(self->activator, self->activator->r.currentAngles); } - if ( self->activator->health <= 0 ) - { - //if ( self->activator->s.number ) - {//never free player - if ( self->count == 1 ) - {//in my hand, just drop them - if ( self->activator->client ) - { + if (self->activator->health <= 0) { + // if ( self->activator->s.number ) + { // never free player + if (self->count == 1) { // in my hand, just drop them + if (self->activator->client) { self->activator->client->ps.legsTimer = self->activator->client->ps.torsoTimer = 0; - //FIXME: ragdoll? + // FIXME: ragdoll? } - } - else - { - if ( self->activator->client ) - { - self->activator->client->ps.eFlags |= EF_NODRAW;//so his corpse doesn't drop out of me... + } else { + if (self->activator->client) { + self->activator->client->ps.eFlags |= EF_NODRAW; // so his corpse doesn't drop out of me... } - //G_FreeEntity( self->activator ); + // G_FreeEntity( self->activator ); } } - } - else - { - if ( self->activator->NPC ) - {//start thinking again + } else { + if (self->activator->NPC) { // start thinking again self->activator->NPC->nextBStateThink = level.time; } - //clear their anim and let them fall + // clear their anim and let them fall self->activator->client->ps.legsTimer = self->activator->client->ps.torsoTimer = 0; } - if ( self->enemy == self->activator ) - { + if (self->enemy == self->activator) { self->enemy = NULL; } self->activator = NULL; } - self->count = 0;//drop him + self->count = 0; // drop him } -void Rancor_Swing( qboolean tryGrab ) -{ - int radiusEntNums[128]; - int numEnts; - const float radius = 88; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; +void Rancor_Swing(qboolean tryGrab) { + int radiusEntNums[128]; + int numEnts; + const float radius = 88; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; - numEnts = NPC_GetEntsNearBolt( radiusEntNums, radius, NPCS.NPC->client->renderInfo.handRBolt, boltOrg ); + numEnts = NPC_GetEntsNearBolt(radiusEntNums, radius, NPCS.NPC->client->renderInfo.handRBolt, boltOrg); - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { gentity_t *radiusEnt = &g_entities[radiusEntNums[i]]; - if ( !radiusEnt->inuse ) - { + if (!radiusEnt->inuse) { continue; } - if ( radiusEnt == NPCS.NPC ) - {//Skip the rancor ent + if (radiusEnt == NPCS.NPC) { // Skip the rancor ent continue; } - if ( radiusEnt->client == NULL ) - {//must be a client + if (radiusEnt->client == NULL) { // must be a client continue; } - if ( (radiusEnt->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//can't be one already being held + if ((radiusEnt->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // can't be one already being held continue; } - if ( DistanceSquared( radiusEnt->r.currentOrigin, boltOrg ) <= radiusSquared ) - { - if ( tryGrab - && NPCS.NPC->count != 1 //don't have one in hand or in mouth already - FIXME: allow one in hand and any number in mouth! - && radiusEnt->client->NPC_class != CLASS_RANCOR - && radiusEnt->client->NPC_class != CLASS_GALAKMECH - && radiusEnt->client->NPC_class != CLASS_ATST - && radiusEnt->client->NPC_class != CLASS_GONK - && radiusEnt->client->NPC_class != CLASS_R2D2 - && radiusEnt->client->NPC_class != CLASS_R5D2 - && radiusEnt->client->NPC_class != CLASS_MARK1 - && radiusEnt->client->NPC_class != CLASS_MARK2 - && radiusEnt->client->NPC_class != CLASS_MOUSE - && radiusEnt->client->NPC_class != CLASS_PROBE - && radiusEnt->client->NPC_class != CLASS_SEEKER - && radiusEnt->client->NPC_class != CLASS_REMOTE - && radiusEnt->client->NPC_class != CLASS_SENTRY - && radiusEnt->client->NPC_class != CLASS_INTERROGATOR - && radiusEnt->client->NPC_class != CLASS_VEHICLE ) - {//grab - if ( NPCS.NPC->count == 2 ) - {//have one in my mouth, remove him - TIMER_Remove( NPCS.NPC, "clearGrabbed" ); - Rancor_DropVictim( NPCS.NPC ); + if (DistanceSquared(radiusEnt->r.currentOrigin, boltOrg) <= radiusSquared) { + if (tryGrab && NPCS.NPC->count != 1 // don't have one in hand or in mouth already - FIXME: allow one in hand and any number in mouth! + && radiusEnt->client->NPC_class != CLASS_RANCOR && radiusEnt->client->NPC_class != CLASS_GALAKMECH && + radiusEnt->client->NPC_class != CLASS_ATST && radiusEnt->client->NPC_class != CLASS_GONK && radiusEnt->client->NPC_class != CLASS_R2D2 && + radiusEnt->client->NPC_class != CLASS_R5D2 && radiusEnt->client->NPC_class != CLASS_MARK1 && radiusEnt->client->NPC_class != CLASS_MARK2 && + radiusEnt->client->NPC_class != CLASS_MOUSE && radiusEnt->client->NPC_class != CLASS_PROBE && radiusEnt->client->NPC_class != CLASS_SEEKER && + radiusEnt->client->NPC_class != CLASS_REMOTE && radiusEnt->client->NPC_class != CLASS_SENTRY && + radiusEnt->client->NPC_class != CLASS_INTERROGATOR && radiusEnt->client->NPC_class != CLASS_VEHICLE) { // grab + if (NPCS.NPC->count == 2) { // have one in my mouth, remove him + TIMER_Remove(NPCS.NPC, "clearGrabbed"); + Rancor_DropVictim(NPCS.NPC); } - NPCS.NPC->enemy = radiusEnt;//make him my new best friend + NPCS.NPC->enemy = radiusEnt; // make him my new best friend radiusEnt->client->ps.eFlags2 |= EF2_HELD_BY_MONSTER; - //FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something + // FIXME: this makes it so that the victim can't hit us with shots! Just use activator or something radiusEnt->client->ps.hasLookTarget = qtrue; radiusEnt->client->ps.lookTarget = NPCS.NPC->s.number; - NPCS.NPC->activator = radiusEnt;//remember him - NPCS.NPC->count = 1;//in my hand - //wait to attack - TIMER_Set( NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_irand(500, 2500) ); - if ( radiusEnt->health > 0 && radiusEnt->pain ) - {//do pain on enemy - radiusEnt->pain( radiusEnt, NPCS.NPC, 100 ); - //GEntity_PainFunc( radiusEnt, NPC, NPC, radiusEnt->r.currentOrigin, 0, MOD_CRUSH ); - } - else if ( radiusEnt->client ) - { + NPCS.NPC->activator = radiusEnt; // remember him + NPCS.NPC->count = 1; // in my hand + // wait to attack + TIMER_Set(NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_irand(500, 2500)); + if (radiusEnt->health > 0 && radiusEnt->pain) { // do pain on enemy + radiusEnt->pain(radiusEnt, NPCS.NPC, 100); + // GEntity_PainFunc( radiusEnt, NPC, NPC, radiusEnt->r.currentOrigin, 0, MOD_CRUSH ); + } else if (radiusEnt->client) { radiusEnt->client->ps.forceHandExtend = HANDEXTEND_NONE; radiusEnt->client->ps.forceHandExtendTime = 0; - NPC_SetAnim( radiusEnt, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(radiusEnt, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - } - else - {//smack + } else { // smack vec3_t pushDir; vec3_t angs; - G_Sound( radiusEnt, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - //actually push the enemy + G_Sound(radiusEnt, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + // actually push the enemy /* //VectorSubtract( radiusEnt->r.currentOrigin, boltOrg, pushDir ); VectorSubtract( radiusEnt->r.currentOrigin, NPC->r.currentOrigin, pushDir ); pushDir[2] = Q_flrand( 100, 200 ); VectorNormalize( pushDir ); */ - VectorCopy( NPCS.NPC->client->ps.viewangles, angs ); - angs[YAW] += flrand( 25, 50 ); - angs[PITCH] = flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - if ( radiusEnt->client->NPC_class != CLASS_RANCOR - && radiusEnt->client->NPC_class != CLASS_ATST ) - { - G_Damage( radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand( 25, 40 ), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - G_Throw( radiusEnt, pushDir, 250 ); - if ( radiusEnt->health > 0 ) - {//do pain on enemy - G_Knockdown( radiusEnt );//, NPC, pushDir, 100, qtrue ); + VectorCopy(NPCS.NPC->client->ps.viewangles, angs); + angs[YAW] += flrand(25, 50); + angs[PITCH] = flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + if (radiusEnt->client->NPC_class != CLASS_RANCOR && radiusEnt->client->NPC_class != CLASS_ATST) { + G_Damage(radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand(25, 40), DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, + MOD_MELEE); + G_Throw(radiusEnt, pushDir, 250); + if (radiusEnt->health > 0) { // do pain on enemy + G_Knockdown(radiusEnt); //, NPC, pushDir, 100, qtrue ); } } } @@ -321,254 +262,208 @@ void Rancor_Swing( qboolean tryGrab ) } } -void Rancor_Smash( void ) -{ - int radiusEntNums[128]; - int numEnts; - const float radius = 128; - const float halfRadSquared = ((radius/2)*(radius/2)); - const float radiusSquared = (radius*radius); - float distSq; - int i; - vec3_t boltOrg; +void Rancor_Smash(void) { + int radiusEntNums[128]; + int numEnts; + const float radius = 128; + const float halfRadSquared = ((radius / 2) * (radius / 2)); + const float radiusSquared = (radius * radius); + float distSq; + int i; + vec3_t boltOrg; - AddSoundEvent( NPCS.NPC, NPCS.NPC->r.currentOrigin, 512, AEL_DANGER, qfalse );//, qtrue ); + AddSoundEvent(NPCS.NPC, NPCS.NPC->r.currentOrigin, 512, AEL_DANGER, qfalse); //, qtrue ); - numEnts = NPC_GetEntsNearBolt( radiusEntNums, radius, NPCS.NPC->client->renderInfo.handLBolt, boltOrg ); + numEnts = NPC_GetEntsNearBolt(radiusEntNums, radius, NPCS.NPC->client->renderInfo.handLBolt, boltOrg); - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { gentity_t *radiusEnt = &g_entities[radiusEntNums[i]]; - if ( !radiusEnt->inuse ) - { + if (!radiusEnt->inuse) { continue; } - if ( radiusEnt == NPCS.NPC ) - {//Skip the rancor ent + if (radiusEnt == NPCS.NPC) { // Skip the rancor ent continue; } - if ( radiusEnt->client == NULL ) - {//must be a client + if (radiusEnt->client == NULL) { // must be a client continue; } - if ( (radiusEnt->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//can't be one being held + if ((radiusEnt->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // can't be one being held continue; } - distSq = DistanceSquared( radiusEnt->r.currentOrigin, boltOrg ); - if ( distSq <= radiusSquared ) - { - G_Sound( radiusEnt, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - if ( distSq < halfRadSquared ) - {//close enough to do damage, too - G_Damage( radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand( 10, 25 ), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + distSq = DistanceSquared(radiusEnt->r.currentOrigin, boltOrg); + if (distSq <= radiusSquared) { + G_Sound(radiusEnt, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + if (distSq < halfRadSquared) { // close enough to do damage, too + G_Damage(radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand(10, 25), DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, + MOD_MELEE); } - if ( radiusEnt->health > 0 - && radiusEnt->client - && radiusEnt->client->NPC_class != CLASS_RANCOR - && radiusEnt->client->NPC_class != CLASS_ATST ) - { - if ( distSq < halfRadSquared - || radiusEnt->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//within range of my fist or withing ground-shaking range and not in the air - G_Knockdown( radiusEnt );//, NPC, vec3_origin, 100, qtrue ); + if (radiusEnt->health > 0 && radiusEnt->client && radiusEnt->client->NPC_class != CLASS_RANCOR && radiusEnt->client->NPC_class != CLASS_ATST) { + if (distSq < halfRadSquared || + radiusEnt->client->ps.groundEntityNum != ENTITYNUM_NONE) { // within range of my fist or withing ground-shaking range and not in the air + G_Knockdown(radiusEnt); //, NPC, vec3_origin, 100, qtrue ); } } } } } -void Rancor_Bite( void ) -{ - int radiusEntNums[128]; - int numEnts; - const float radius = 100; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; +void Rancor_Bite(void) { + int radiusEntNums[128]; + int numEnts; + const float radius = 100; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; - numEnts = NPC_GetEntsNearBolt( radiusEntNums, radius, NPCS.NPC->client->renderInfo.crotchBolt, boltOrg );//was gutBolt? + numEnts = NPC_GetEntsNearBolt(radiusEntNums, radius, NPCS.NPC->client->renderInfo.crotchBolt, boltOrg); // was gutBolt? - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { gentity_t *radiusEnt = &g_entities[radiusEntNums[i]]; - if ( !radiusEnt->inuse ) - { + if (!radiusEnt->inuse) { continue; } - if ( radiusEnt == NPCS.NPC ) - {//Skip the rancor ent + if (radiusEnt == NPCS.NPC) { // Skip the rancor ent continue; } - if ( radiusEnt->client == NULL ) - {//must be a client + if (radiusEnt->client == NULL) { // must be a client continue; } - if ( (radiusEnt->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//can't be one already being held + if ((radiusEnt->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // can't be one already being held continue; } - if ( DistanceSquared( radiusEnt->r.currentOrigin, boltOrg ) <= radiusSquared ) - { - G_Damage( radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand( 15, 30 ), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - if ( radiusEnt->health <= 0 && radiusEnt->client ) - {//killed them, chance of dismembering - if ( !Q_irand( 0, 1 ) ) - {//bite something off - int hitLoc = Q_irand( G2_MODELPART_HEAD, G2_MODELPART_RLEG ); - if ( hitLoc == G2_MODELPART_HEAD ) - { - NPC_SetAnim( radiusEnt, SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else if ( hitLoc == G2_MODELPART_WAIST ) - { - NPC_SetAnim( radiusEnt, SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (DistanceSquared(radiusEnt->r.currentOrigin, boltOrg) <= radiusSquared) { + G_Damage(radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, Q_irand(15, 30), DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, MOD_MELEE); + if (radiusEnt->health <= 0 && radiusEnt->client) { // killed them, chance of dismembering + if (!Q_irand(0, 1)) { // bite something off + int hitLoc = Q_irand(G2_MODELPART_HEAD, G2_MODELPART_RLEG); + if (hitLoc == G2_MODELPART_HEAD) { + NPC_SetAnim(radiusEnt, SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (hitLoc == G2_MODELPART_WAIST) { + NPC_SetAnim(radiusEnt, SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //radiusEnt->client->dismembered = qfalse; - //FIXME: the limb should just disappear, cuz I ate it - G_Dismember( radiusEnt, NPCS.NPC, radiusEnt->r.currentOrigin, hitLoc, 90, 0, radiusEnt->client->ps.torsoAnim, qtrue); - //G_DoDismemberment( radiusEnt, radiusEnt->r.currentOrigin, MOD_SABER, 1000, hitLoc, qtrue ); + // radiusEnt->client->dismembered = qfalse; + // FIXME: the limb should just disappear, cuz I ate it + G_Dismember(radiusEnt, NPCS.NPC, radiusEnt->r.currentOrigin, hitLoc, 90, 0, radiusEnt->client->ps.torsoAnim, qtrue); + // G_DoDismemberment( radiusEnt, radiusEnt->r.currentOrigin, MOD_SABER, 1000, hitLoc, qtrue ); } } - G_Sound( radiusEnt, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); + G_Sound(radiusEnt, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/chomp.wav")); } } } //------------------------------ -extern void TossClientItems( gentity_t *self ); -void Rancor_Attack( float distance, qboolean doCharge ) -{ - - if ( !TIMER_Exists( NPCS.NPC, "attacking" ) ) - { - if ( NPCS.NPC->count == 2 && NPCS.NPC->activator ) - { - } - else if ( NPCS.NPC->count == 1 && NPCS.NPC->activator ) - {//holding enemy - if ( NPCS.NPC->activator->health > 0 && Q_irand( 0, 1 ) ) - {//quick bite - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 450 ); - } - else - {//full eat - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 900 ); - //Make victim scream in fright - if ( NPCS.NPC->activator->health > 0 && NPCS.NPC->activator->client ) - { - G_AddEvent( NPCS.NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0 ); - NPC_SetAnim( NPCS.NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - if ( NPCS.NPC->activator->NPC ) - {//no more thinking for you - TossClientItems( NPCS.NPC ); +extern void TossClientItems(gentity_t *self); +void Rancor_Attack(float distance, qboolean doCharge) { + + if (!TIMER_Exists(NPCS.NPC, "attacking")) { + if (NPCS.NPC->count == 2 && NPCS.NPC->activator) { + } else if (NPCS.NPC->count == 1 && NPCS.NPC->activator) { // holding enemy + if (NPCS.NPC->activator->health > 0 && Q_irand(0, 1)) { // quick bite + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 450); + } else { // full eat + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 900); + // Make victim scream in fright + if (NPCS.NPC->activator->health > 0 && NPCS.NPC->activator->client) { + G_AddEvent(NPCS.NPC->activator, Q_irand(EV_DEATH1, EV_DEATH3), 0); + NPC_SetAnim(NPCS.NPC->activator, SETANIM_TORSO, BOTH_FALLDEATH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (NPCS.NPC->activator->NPC) { // no more thinking for you + TossClientItems(NPCS.NPC); NPCS.NPC->activator->NPC->nextBStateThink = Q3_INFINITE; } } } - } - else if ( NPCS.NPC->enemy->health > 0 && doCharge ) - {//charge - vec3_t fwd, yawAng; - VectorSet( yawAng, 0, NPCS.NPC->client->ps.viewangles[YAW], 0 ); - AngleVectors( yawAng, fwd, NULL, NULL ); - VectorScale( fwd, distance*1.5f, NPCS.NPC->client->ps.velocity ); + } else if (NPCS.NPC->enemy->health > 0 && doCharge) { // charge + vec3_t fwd, yawAng; + VectorSet(yawAng, 0, NPCS.NPC->client->ps.viewangles[YAW], 0); + AngleVectors(yawAng, fwd, NULL, NULL); + VectorScale(fwd, distance * 1.5f, NPCS.NPC->client->ps.velocity); NPCS.NPC->client->ps.velocity[2] = 150; NPCS.NPC->client->ps.groundEntityNum = ENTITYNUM_NONE; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 1250 ); - } - else if ( !Q_irand(0, 1) ) - {//smash - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 1000 ); - } - else - {//try to grab - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 1000 ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_MELEE2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 1250); + } else if (!Q_irand(0, 1)) { // smash + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_MELEE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 1000); + } else { // try to grab + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 1000); } - TIMER_Set( NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_flrand(0.0f, 1.0f) * 200 ); + TIMER_Set(NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_flrand(0.0f, 1.0f) * 200); } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPCS.NPC, "attack_dmg", qtrue ) ) - { + if (TIMER_Done2(NPCS.NPC, "attack_dmg", qtrue)) { vec3_t shakePos; - switch ( NPCS.NPC->client->ps.legsAnim ) - { + switch (NPCS.NPC->client->ps.legsAnim) { case BOTH_MELEE1: Rancor_Smash(); - G_GetBoltPosition( NPCS.NPC, NPCS.NPC->client->renderInfo.handLBolt, shakePos, 0 ); - G_ScreenShake( shakePos, NULL, 4.0f, 1000, qfalse ); - //CGCam_Shake( 1.0f*playerDist/128.0f, 1000 ); + G_GetBoltPosition(NPCS.NPC, NPCS.NPC->client->renderInfo.handLBolt, shakePos, 0); + G_ScreenShake(shakePos, NULL, 4.0f, 1000, qfalse); + // CGCam_Shake( 1.0f*playerDist/128.0f, 1000 ); break; case BOTH_MELEE2: Rancor_Bite(); - TIMER_Set( NPCS.NPC, "attack_dmg2", 450 ); + TIMER_Set(NPCS.NPC, "attack_dmg2", 450); break; case BOTH_ATTACK1: - if ( NPCS.NPC->count == 1 && NPCS.NPC->activator ) - { - G_Damage( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, Q_irand( 25, 40 ), DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - if ( NPCS.NPC->activator->health <= 0 ) - {//killed him - //make it look like we bit his head off - //NPC->activator->client->dismembered = qfalse; - G_Dismember( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_HEAD, 90, 0, NPCS.NPC->activator->client->ps.torsoAnim, qtrue); - //G_DoDismemberment( NPC->activator, NPC->activator->r.currentOrigin, MOD_SABER, 1000, HL_HEAD, qtrue ); + if (NPCS.NPC->count == 1 && NPCS.NPC->activator) { + G_Damage(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, Q_irand(25, 40), + DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK, MOD_MELEE); + if (NPCS.NPC->activator->health <= 0) { // killed him + // make it look like we bit his head off + // NPC->activator->client->dismembered = qfalse; + G_Dismember(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_HEAD, 90, 0, + NPCS.NPC->activator->client->ps.torsoAnim, qtrue); + // G_DoDismemberment( NPC->activator, NPC->activator->r.currentOrigin, MOD_SABER, 1000, HL_HEAD, qtrue ); NPCS.NPC->activator->client->ps.forceHandExtend = HANDEXTEND_NONE; NPCS.NPC->activator->client->ps.forceHandExtendTime = 0; - NPC_SetAnim( NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - G_Sound( NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); + G_Sound(NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/chomp.wav")); } break; case BOTH_ATTACK2: - //try to grab - Rancor_Swing( qtrue ); + // try to grab + Rancor_Swing(qtrue); break; case BOTH_ATTACK3: - if ( NPCS.NPC->count == 1 && NPCS.NPC->activator ) - { - //cut in half - if ( NPCS.NPC->activator->client ) - { - //NPC->activator->client->dismembered = qfalse; - G_Dismember( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_WAIST, 90, 0, NPCS.NPC->activator->client->ps.torsoAnim, qtrue); - //G_DoDismemberment( NPC->activator, NPC->enemy->r.currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); + if (NPCS.NPC->count == 1 && NPCS.NPC->activator) { + // cut in half + if (NPCS.NPC->activator->client) { + // NPC->activator->client->dismembered = qfalse; + G_Dismember(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_WAIST, 90, 0, + NPCS.NPC->activator->client->ps.torsoAnim, qtrue); + // G_DoDismemberment( NPC->activator, NPC->enemy->r.currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); } - //KILL - G_Damage( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, NPCS.NPC->enemy->health+10, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_MELEE );//, HL_NONE );// - if ( NPCS.NPC->activator->client ) - { + // KILL + G_Damage(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, NPCS.NPC->enemy->health + 10, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_MELEE); //, HL_NONE );// + if (NPCS.NPC->activator->client) { NPCS.NPC->activator->client->ps.forceHandExtend = HANDEXTEND_NONE; NPCS.NPC->activator->client->ps.forceHandExtendTime = 0; - NPC_SetAnim( NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( NPCS.NPC, "attack_dmg2", 1350 ); - G_Sound( NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); - G_AddEvent( NPCS.NPC->activator, EV_JUMP, NPCS.NPC->activator->health ); + TIMER_Set(NPCS.NPC, "attack_dmg2", 1350); + G_Sound(NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/swipehit.wav")); + G_AddEvent(NPCS.NPC->activator, EV_JUMP, NPCS.NPC->activator->health); } break; } - } - else if ( TIMER_Done2( NPCS.NPC, "attack_dmg2", qtrue ) ) - { - switch ( NPCS.NPC->client->ps.legsAnim ) - { + } else if (TIMER_Done2(NPCS.NPC, "attack_dmg2", qtrue)) { + switch (NPCS.NPC->client->ps.legsAnim) { case BOTH_MELEE1: break; case BOTH_MELEE2: @@ -579,134 +474,108 @@ void Rancor_Attack( float distance, qboolean doCharge ) case BOTH_ATTACK2: break; case BOTH_ATTACK3: - if ( NPCS.NPC->count == 1 && NPCS.NPC->activator ) - {//swallow victim - G_Sound( NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex( "sound/chars/rancor/chomp.wav" ) ); - //FIXME: sometimes end up with a live one in our mouths? - //just make sure they're dead - if ( NPCS.NPC->activator->health > 0 ) - { - //cut in half - //NPC->activator->client->dismembered = qfalse; - G_Dismember( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_WAIST, 90, 0, NPCS.NPC->activator->client->ps.torsoAnim, qtrue); - //G_DoDismemberment( NPC->activator, NPC->enemy->r.currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); - //KILL - G_Damage( NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, NPCS.NPC->enemy->health+10, DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_MELEE );//, HL_NONE ); + if (NPCS.NPC->count == 1 && NPCS.NPC->activator) { // swallow victim + G_Sound(NPCS.NPC->activator, CHAN_AUTO, G_SoundIndex("sound/chars/rancor/chomp.wav")); + // FIXME: sometimes end up with a live one in our mouths? + // just make sure they're dead + if (NPCS.NPC->activator->health > 0) { + // cut in half + // NPC->activator->client->dismembered = qfalse; + G_Dismember(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC->activator->r.currentOrigin, G2_MODELPART_WAIST, 90, 0, + NPCS.NPC->activator->client->ps.torsoAnim, qtrue); + // G_DoDismemberment( NPC->activator, NPC->enemy->r.currentOrigin, MOD_SABER, 1000, HL_WAIST, qtrue ); + // KILL + G_Damage(NPCS.NPC->activator, NPCS.NPC, NPCS.NPC, vec3_origin, NPCS.NPC->activator->r.currentOrigin, NPCS.NPC->enemy->health + 10, + DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_MELEE); //, HL_NONE ); NPCS.NPC->activator->client->ps.forceHandExtend = HANDEXTEND_NONE; NPCS.NPC->activator->client->ps.forceHandExtendTime = 0; - NPC_SetAnim( NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - G_AddEvent( NPCS.NPC->activator, EV_JUMP, NPCS.NPC->activator->health ); + NPC_SetAnim(NPCS.NPC->activator, SETANIM_BOTH, BOTH_SWIM_IDLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_AddEvent(NPCS.NPC->activator, EV_JUMP, NPCS.NPC->activator->health); } - if ( NPCS.NPC->activator->client ) - {//*sigh*, can't get tags right, just remove them? + if (NPCS.NPC->activator->client) { //*sigh*, can't get tags right, just remove them? NPCS.NPC->activator->client->ps.eFlags |= EF_NODRAW; } NPCS.NPC->count = 2; - TIMER_Set( NPCS.NPC, "clearGrabbed", 2600 ); + TIMER_Set(NPCS.NPC, "clearGrabbed", 2600); } break; } - } - else if ( NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK2 ) - { - if ( NPCS.NPC->client->ps.legsTimer >= 1200 && NPCS.NPC->client->ps.legsTimer <= 1350 ) - { - if ( Q_irand( 0, 2 ) ) - { - Rancor_Swing( qfalse ); - } - else - { - Rancor_Swing( qtrue ); + } else if (NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK2) { + if (NPCS.NPC->client->ps.legsTimer >= 1200 && NPCS.NPC->client->ps.legsTimer <= 1350) { + if (Q_irand(0, 2)) { + Rancor_Swing(qfalse); + } else { + Rancor_Swing(qtrue); } - } - else if ( NPCS.NPC->client->ps.legsTimer >= 1100 && NPCS.NPC->client->ps.legsTimer <= 1550 ) - { - Rancor_Swing( qtrue ); + } else if (NPCS.NPC->client->ps.legsTimer >= 1100 && NPCS.NPC->client->ps.legsTimer <= 1550) { + Rancor_Swing(qtrue); } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPCS.NPC, "attacking", qtrue ); + TIMER_Done2(NPCS.NPC, "attacking", qtrue); } //---------------------------------- -void Rancor_Combat( void ) -{ - if ( NPCS.NPC->count ) - {//holding my enemy - if ( TIMER_Done2( NPCS.NPC, "takingPain", qtrue )) - { +void Rancor_Combat(void) { + if (NPCS.NPC->count) { // holding my enemy + if (TIMER_Done2(NPCS.NPC, "takingPain", qtrue)) { NPCS.NPCInfo->localState = LSTATE_CLEAR; + } else { + Rancor_Attack(0, qfalse); } - else - { - Rancor_Attack( 0, qfalse ); - } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS4( NPCS.NPC->enemy ) )//|| UpdateGoal( )) + if (!NPC_ClearLOS4(NPCS.NPC->enemy)) //|| UpdateGoal( )) { NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPCS.NPCInfo->goalRadius = MIN_DISTANCE;//MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MIN_DISTANCE; // MAX_DISTANCE; // just get us within combat range - if ( !NPC_MoveToGoal( qtrue ) ) - {//couldn't go after him? Look for a new one - TIMER_Set( NPCS.NPC, "lookForNewEnemy", 0 ); + if (!NPC_MoveToGoal(qtrue)) { // couldn't go after him? Look for a new one + TIMER_Set(NPCS.NPC, "lookForNewEnemy", 0); NPCS.NPCInfo->consecutiveBlockedMoves++; - } - else - { + } else { NPCS.NPCInfo->consecutiveBlockedMoves = 0; } return; } // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); { - float distance; - qboolean advance; - qboolean doCharge; + float distance; + qboolean advance; + qboolean doCharge; - distance = Distance( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - advance = (qboolean)( distance > (NPCS.NPC->r.maxs[0]+MIN_DISTANCE) ? qtrue : qfalse ); + distance = Distance(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + advance = (qboolean)(distance > (NPCS.NPC->r.maxs[0] + MIN_DISTANCE) ? qtrue : qfalse); doCharge = qfalse; - if ( advance ) - {//have to get closer - vec3_t yawOnlyAngles; - VectorSet( yawOnlyAngles, 0, NPCS.NPC->r.currentAngles[YAW], 0 ); - if ( NPCS.NPC->enemy->health > 0 - && fabs(distance-250) <= 80 - && InFOV3( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, yawOnlyAngles, 30, 30 ) ) - { - if ( !Q_irand( 0, 9 ) ) - {//go for the charge + if (advance) { // have to get closer + vec3_t yawOnlyAngles; + VectorSet(yawOnlyAngles, 0, NPCS.NPC->r.currentAngles[YAW], 0); + if (NPCS.NPC->enemy->health > 0 && fabs(distance - 250) <= 80 && + InFOV3(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, yawOnlyAngles, 30, 30)) { + if (!Q_irand(0, 9)) { // go for the charge doCharge = qtrue; advance = qfalse; } } } - if (( advance /*|| NPCInfo->localState == LSTATE_WAITING*/ ) && TIMER_Done( NPCS.NPC, "attacking" )) // waiting monsters can't attack + if ((advance /*|| NPCInfo->localState == LSTATE_WAITING*/) && TIMER_Done(NPCS.NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPCS.NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPCS.NPC, "takingPain", qtrue)) { NPCS.NPCInfo->localState = LSTATE_CLEAR; + } else { + Rancor_Move(qtrue); } - else - { - Rancor_Move( qtrue ); - } - } - else - { - Rancor_Attack( distance, doCharge ); + } else { + Rancor_Attack(distance, doCharge); } } } @@ -716,78 +585,60 @@ void Rancor_Combat( void ) NPC_Rancor_Pain ------------------------- */ -void NPC_Rancor_Pain( gentity_t *self, gentity_t *attacker, int damage ) -{ +void NPC_Rancor_Pain(gentity_t *self, gentity_t *attacker, int damage) { qboolean hitByRancor = qfalse; - if ( attacker&&attacker->client&&attacker->client->NPC_class==CLASS_RANCOR ) - { + if (attacker && attacker->client && attacker->client->NPC_class == CLASS_RANCOR) { hitByRancor = qtrue; } - if ( attacker - && attacker->inuse - && attacker != self->enemy - && !(attacker->flags&FL_NOTARGET) ) - { - if ( !self->count ) - { - if ( (!attacker->s.number&&!Q_irand(0,3)) - || !self->enemy - || self->enemy->health == 0 - || (self->enemy->client&&self->enemy->client->NPC_class == CLASS_RANCOR) - || (self->NPC && self->NPC->consecutiveBlockedMoves>=10 && DistanceSquared( attacker->r.currentOrigin, self->r.currentOrigin ) < DistanceSquared( self->enemy->r.currentOrigin, self->r.currentOrigin )) ) - {//if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker - //FIXME: if can't nav to my enemy, take this guy if I can nav to him - G_SetEnemy( self, attacker ); - TIMER_Set( self, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - if ( hitByRancor ) - {//stay mad at this Rancor for 2-5 secs before looking for attacker enemies - TIMER_Set( self, "rancorInfight", Q_irand( 2000, 5000 ) ); + if (attacker && attacker->inuse && attacker != self->enemy && !(attacker->flags & FL_NOTARGET)) { + if (!self->count) { + if ((!attacker->s.number && !Q_irand(0, 3)) || !self->enemy || self->enemy->health == 0 || + (self->enemy->client && self->enemy->client->NPC_class == CLASS_RANCOR) || + (self->NPC && self->NPC->consecutiveBlockedMoves >= 10 && + DistanceSquared(attacker->r.currentOrigin, self->r.currentOrigin) < + DistanceSquared(self->enemy->r.currentOrigin, self->r.currentOrigin))) { // if my enemy is dead (or attacked by player) and I'm not still + // holding/eating someone, turn on the attacker + // FIXME: if can't nav to my enemy, take this guy if I can nav to him + G_SetEnemy(self, attacker); + TIMER_Set(self, "lookForNewEnemy", Q_irand(5000, 15000)); + if (hitByRancor) { // stay mad at this Rancor for 2-5 secs before looking for attacker enemies + TIMER_Set(self, "rancorInfight", Q_irand(2000, 5000)); } - } } } - if ( (hitByRancor|| (self->count==1&&self->activator&&!Q_irand(0,4)) || Q_irand( 0, 200 ) < damage )//hit by rancor, hit while holding live victim, or took a lot of damage - && self->client->ps.legsAnim != BOTH_STAND1TO2 - && TIMER_Done( self, "takingPain" ) ) - { - if ( !Rancor_CheckRoar( self ) ) - { - if ( self->client->ps.legsAnim != BOTH_MELEE1 - && self->client->ps.legsAnim != BOTH_MELEE2 - && self->client->ps.legsAnim != BOTH_ATTACK2 ) - {//cant interrupt one of the big attack anims + if ((hitByRancor || (self->count == 1 && self->activator && !Q_irand(0, 4)) || + Q_irand(0, 200) < damage) // hit by rancor, hit while holding live victim, or took a lot of damage + && self->client->ps.legsAnim != BOTH_STAND1TO2 && TIMER_Done(self, "takingPain")) { + if (!Rancor_CheckRoar(self)) { + if (self->client->ps.legsAnim != BOTH_MELEE1 && self->client->ps.legsAnim != BOTH_MELEE2 && + self->client->ps.legsAnim != BOTH_ATTACK2) { // cant interrupt one of the big attack anims /* if ( self->count != 1 || attacker == self->activator || (self->client->ps.legsAnim != BOTH_ATTACK1&&self->client->ps.legsAnim != BOTH_ATTACK3) ) */ - {//if going to bite our victim, only victim can interrupt that anim - if ( self->health > 100 || hitByRancor ) - { - TIMER_Remove( self, "attacking" ); + { // if going to bite our victim, only victim can interrupt that anim + if (self->health > 100 || hitByRancor) { + TIMER_Remove(self, "attacking"); - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); + VectorCopy(self->NPC->lastPathAngles, self->s.angles); - if ( self->count == 1 ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if (self->count == 1) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( self, "takingPain", self->client->ps.legsTimer+Q_irand(0, 500) ); + TIMER_Set(self, "takingPain", self->client->ps.legsTimer + Q_irand(0, 500)); - if ( self->NPC ) - { + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } } } } - //let go + // let go /* if ( !Q_irand( 0, 3 ) && self->count == 1 ) { @@ -797,39 +648,32 @@ void NPC_Rancor_Pain( gentity_t *self, gentity_t *attacker, int damage ) } } -void Rancor_CheckDropVictim( void ) -{ +void Rancor_CheckDropVictim(void) { vec3_t mins, maxs; vec3_t start, end; - trace_t trace; + trace_t trace; - VectorSet( mins, NPCS.NPC->activator->r.mins[0]-1, NPCS.NPC->activator->r.mins[1]-1, 0 ); - VectorSet( maxs, NPCS.NPC->activator->r.maxs[0]+1, NPCS.NPC->activator->r.maxs[1]+1, 1 ); - VectorSet( start, NPCS.NPC->activator->r.currentOrigin[0], NPCS.NPC->activator->r.currentOrigin[1], NPCS.NPC->activator->r.absmin[2] ); - VectorSet( end, NPCS.NPC->activator->r.currentOrigin[0], NPCS.NPC->activator->r.currentOrigin[1], NPCS.NPC->activator->r.absmax[2]-1 ); + VectorSet(mins, NPCS.NPC->activator->r.mins[0] - 1, NPCS.NPC->activator->r.mins[1] - 1, 0); + VectorSet(maxs, NPCS.NPC->activator->r.maxs[0] + 1, NPCS.NPC->activator->r.maxs[1] + 1, 1); + VectorSet(start, NPCS.NPC->activator->r.currentOrigin[0], NPCS.NPC->activator->r.currentOrigin[1], NPCS.NPC->activator->r.absmin[2]); + VectorSet(end, NPCS.NPC->activator->r.currentOrigin[0], NPCS.NPC->activator->r.currentOrigin[1], NPCS.NPC->activator->r.absmax[2] - 1); - trap->Trace( &trace, start, mins, maxs, end, NPCS.NPC->activator->s.number, NPCS.NPC->activator->clipmask, qfalse, 0, 0 ); - if ( !trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f ) - { - Rancor_DropVictim( NPCS.NPC ); + trap->Trace(&trace, start, mins, maxs, end, NPCS.NPC->activator->s.number, NPCS.NPC->activator->clipmask, qfalse, 0, 0); + if (!trace.allsolid && !trace.startsolid && trace.fraction >= 1.0f) { + Rancor_DropVictim(NPCS.NPC); } } -//if he's stepping on things then crush them -rww -void Rancor_Crush(void) -{ +// if he's stepping on things then crush them -rww +void Rancor_Crush(void) { gentity_t *crush; - if (!NPCS.NPC || - !NPCS.NPC->client || - NPCS.NPC->client->ps.groundEntityNum >= ENTITYNUM_WORLD) - { //nothing to crush + if (!NPCS.NPC || !NPCS.NPC->client || NPCS.NPC->client->ps.groundEntityNum >= ENTITYNUM_WORLD) { // nothing to crush return; } crush = &g_entities[NPCS.NPC->client->ps.groundEntityNum]; - if (crush->inuse && crush->client && !crush->localAnimIndex) - { //a humanoid, smash them good. + if (crush->inuse && crush->client && !crush->localAnimIndex) { // a humanoid, smash them good. G_Damage(crush, NPCS.NPC, NPCS.NPC, NULL, NPCS.NPC->r.currentOrigin, 200, 0, MOD_CRUSH); } } @@ -839,131 +683,101 @@ void Rancor_Crush(void) NPC_BSRancor_Default ------------------------- */ -void NPC_BSRancor_Default( void ) -{ - AddSightEvent( NPCS.NPC, NPCS.NPC->r.currentOrigin, 1024, AEL_DANGER_GREAT, 50 ); +void NPC_BSRancor_Default(void) { + AddSightEvent(NPCS.NPC, NPCS.NPC->r.currentOrigin, 1024, AEL_DANGER_GREAT, 50); Rancor_Crush(); - NPCS.NPC->client->ps.eFlags2 &= ~(EF2_USE_ALT_ANIM|EF2_GENERIC_NPC_FLAG); - if ( NPCS.NPC->count ) - {//holding someone + NPCS.NPC->client->ps.eFlags2 &= ~(EF2_USE_ALT_ANIM | EF2_GENERIC_NPC_FLAG); + if (NPCS.NPC->count) { // holding someone NPCS.NPC->client->ps.eFlags2 |= EF2_USE_ALT_ANIM; - if ( NPCS.NPC->count == 2 ) - {//in my mouth + if (NPCS.NPC->count == 2) { // in my mouth NPCS.NPC->client->ps.eFlags2 |= EF2_GENERIC_NPC_FLAG; } - } - else - { - NPCS.NPC->client->ps.eFlags2 &= ~(EF2_USE_ALT_ANIM|EF2_GENERIC_NPC_FLAG); + } else { + NPCS.NPC->client->ps.eFlags2 &= ~(EF2_USE_ALT_ANIM | EF2_GENERIC_NPC_FLAG); } - if ( TIMER_Done2( NPCS.NPC, "clearGrabbed", qtrue ) ) - { - Rancor_DropVictim( NPCS.NPC ); - } - else if ( NPCS.NPC->client->ps.legsAnim == BOTH_PAIN2 - && NPCS.NPC->count == 1 - && NPCS.NPC->activator ) - { - if ( !Q_irand( 0, 3 ) ) - { + if (TIMER_Done2(NPCS.NPC, "clearGrabbed", qtrue)) { + Rancor_DropVictim(NPCS.NPC); + } else if (NPCS.NPC->client->ps.legsAnim == BOTH_PAIN2 && NPCS.NPC->count == 1 && NPCS.NPC->activator) { + if (!Q_irand(0, 3)) { Rancor_CheckDropVictim(); } } - if ( !TIMER_Done( NPCS.NPC, "rageTime" ) ) - {//do nothing but roar first time we see an enemy - AddSoundEvent( NPCS.NPC, NPCS.NPC->r.currentOrigin, 1024, AEL_DANGER_GREAT, qfalse );//, qfalse ); - NPC_FaceEnemy( qtrue ); + if (!TIMER_Done(NPCS.NPC, "rageTime")) { // do nothing but roar first time we see an enemy + AddSoundEvent(NPCS.NPC, NPCS.NPC->r.currentOrigin, 1024, AEL_DANGER_GREAT, qfalse); //, qfalse ); + NPC_FaceEnemy(qtrue); return; } - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { /* if ( NPC->enemy->client //enemy is a client && (NPC->enemy->client->NPC_class == CLASS_UGNAUGHT || NPC->enemy->client->NPC_class == CLASS_JAWA )//enemy is a lowly jawa or ugnaught && NPC->enemy->enemy != NPC//enemy's enemy is not me - && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || NPC->enemy->enemy->client->NPC_class!=CLASS_RANCOR) )//enemy's enemy is not a client or is not a rancor (which is as scary as me anyway) + && (!NPC->enemy->enemy || !NPC->enemy->enemy->client || NPC->enemy->enemy->client->NPC_class!=CLASS_RANCOR) )//enemy's enemy is not a client or is + not a rancor (which is as scary as me anyway) {//they should be scared of ME and no-one else G_SetEnemy( NPC->enemy, NPC ); } */ - if ( TIMER_Done(NPCS.NPC,"angrynoise") ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( va("sound/chars/rancor/misc/anger%d.wav", Q_irand(1, 3))) ); + if (TIMER_Done(NPCS.NPC, "angrynoise")) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex(va("sound/chars/rancor/misc/anger%d.wav", Q_irand(1, 3)))); - TIMER_Set( NPCS.NPC, "angrynoise", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPCS.NPC, "angrynoise", Q_irand(5000, 10000)); + } else { + AddSoundEvent(NPCS.NPC, NPCS.NPC->r.currentOrigin, 512, AEL_DANGER_GREAT, qfalse); //, qfalse ); } - else - { - AddSoundEvent( NPCS.NPC, NPCS.NPC->r.currentOrigin, 512, AEL_DANGER_GREAT, qfalse );//, qfalse ); - } - if ( NPCS.NPC->count == 2 && NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK3 ) - {//we're still chewing our enemy up - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCS.NPC->count == 2 && NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK3) { // we're still chewing our enemy up + NPC_UpdateAngles(qtrue, qtrue); return; } - //else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while - if( NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_RANCOR ) - {//got mad at another Rancor, look for a valid enemy - if ( TIMER_Done( NPCS.NPC, "rancorInfight" ) ) - { - NPC_CheckEnemyExt( qtrue ); + // else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while + if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_RANCOR) { // got mad at another Rancor, look for a valid enemy + if (TIMER_Done(NPCS.NPC, "rancorInfight")) { + NPC_CheckEnemyExt(qtrue); } - } - else if ( !NPCS.NPC->count ) - { - if ( ValidEnemy( NPCS.NPC->enemy ) == qfalse ) - { - TIMER_Remove( NPCS.NPC, "lookForNewEnemy" );//make them look again right now - if ( !NPCS.NPC->enemy->inuse || level.time - NPCS.NPC->enemy->s.time > Q_irand( 10000, 15000 ) ) - {//it's been a while since the enemy died, or enemy is completely gone, get bored with him + } else if (!NPCS.NPC->count) { + if (ValidEnemy(NPCS.NPC->enemy) == qfalse) { + TIMER_Remove(NPCS.NPC, "lookForNewEnemy"); // make them look again right now + if (!NPCS.NPC->enemy->inuse || + level.time - NPCS.NPC->enemy->s.time > + Q_irand(10000, 15000)) { // it's been a while since the enemy died, or enemy is completely gone, get bored with him NPCS.NPC->enemy = NULL; Rancor_Patrol(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( TIMER_Done( NPCS.NPC, "lookForNewEnemy" ) ) - { - gentity_t *newEnemy, *sav_enemy = NPCS.NPC->enemy;//FIXME: what about NPC->lastEnemy? + if (TIMER_Done(NPCS.NPC, "lookForNewEnemy")) { + gentity_t *newEnemy, *sav_enemy = NPCS.NPC->enemy; // FIXME: what about NPC->lastEnemy? NPCS.NPC->enemy = NULL; - newEnemy = NPC_CheckEnemy( NPCS.NPCInfo->confusionTime < level.time, qfalse, qfalse ); + newEnemy = NPC_CheckEnemy(NPCS.NPCInfo->confusionTime < level.time, qfalse, qfalse); NPCS.NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPCS.NPC->lastEnemy = NPCS.NPC->enemy; - G_SetEnemy( NPCS.NPC, newEnemy ); - //hold this one for at least 5-15 seconds - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - } - else - {//look again in 2-5 secs - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + G_SetEnemy(NPCS.NPC, newEnemy); + // hold this one for at least 5-15 seconds + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(5000, 15000)); + } else { // look again in 2-5 secs + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(2000, 5000)); } } } Rancor_Combat(); - } - else - { - if ( TIMER_Done(NPCS.NPC,"idlenoise") ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( va("sound/chars/rancor/snort_%d.wav", Q_irand(1, 2))) ); + } else { + if (TIMER_Done(NPCS.NPC, "idlenoise")) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex(va("sound/chars/rancor/snort_%d.wav", Q_irand(1, 2)))); - TIMER_Set( NPCS.NPC, "idlenoise", Q_irand( 2000, 4000 ) ); - AddSoundEvent( NPCS.NPC, NPCS.NPC->r.currentOrigin, 384, AEL_DANGER, qfalse );//, qfalse ); + TIMER_Set(NPCS.NPC, "idlenoise", Q_irand(2000, 4000)); + AddSoundEvent(NPCS.NPC, NPCS.NPC->r.currentOrigin, 384, AEL_DANGER, qfalse); //, qfalse ); } - if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Rancor_Patrol(); - } - else - { + } else { Rancor_Idle(); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codemp/game/NPC_AI_Remote.c b/codemp/game/NPC_AI_Remote.c index c4fb53f1aa..2b092de67a 100644 --- a/codemp/game/NPC_AI_Remote.c +++ b/codemp/game/NPC_AI_Remote.c @@ -23,24 +23,21 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -void Remote_Strafe( void ); +void Remote_Strafe(void); -#define VELOCITY_DECAY 0.85f +#define VELOCITY_DECAY 0.85f - -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, }; -void Remote_Idle( void ); +void Remote_Idle(void); -void NPC_Remote_Precache(void) -{ +void NPC_Remote_Precache(void) { G_SoundIndex("sound/chars/remote/misc/fire.wav"); - G_SoundIndex( "sound/chars/remote/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/remote/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } /* @@ -48,14 +45,13 @@ void NPC_Remote_Precache(void) NPC_Remote_Pain ------------------------- */ -void NPC_Remote_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Remote_Pain(gentity_t *self, gentity_t *attacker, int damage) { SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Remote_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); } /* @@ -63,210 +59,182 @@ void NPC_Remote_Pain(gentity_t *self, gentity_t *attacker, int damage) Remote_MaintainHeight ------------------------- */ -void Remote_MaintainHeight( void ) -{ - float dif; +void Remote_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); - if ( NPCS.NPC->client->ps.velocity[2] ) - { + if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 2) { NPCS.NPC->client->ps.velocity[2] = 0; } } // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPCS.NPC->enemy ) - { - if (TIMER_Done( NPCS.NPC, "heightChange")) - { - TIMER_Set( NPCS.NPC,"heightChange",Q_irand( 1000, 3000 )); + if (NPCS.NPC->enemy) { + if (TIMER_Done(NPCS.NPC, "heightChange")) { + TIMER_Set(NPCS.NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPCS.NPC->enemy->r.currentOrigin[2] + Q_irand( 0, NPCS.NPC->enemy->r.maxs[2]+8 )) - NPCS.NPC->r.currentOrigin[2]; + dif = (NPCS.NPC->enemy->r.currentOrigin[2] + Q_irand(0, NPCS.NPC->enemy->r.maxs[2] + 8)) - NPCS.NPC->r.currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2 ) - { - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 2) { + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); } dif *= 10; - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; - // NPC->fx_time = level.time; - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; + // NPC->fx_time = level.time; + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCS.NPCInfo->goalEntity ) // Is there a goal? + if (NPCS.NPCInfo->goalEntity) // Is there a goal? { goal = NPCS.NPCInfo->goalEntity; - } - else - { + } else { goal = NPCS.NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - dif = ( dif < 0 ? -24 : 24 ); - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; + if (fabs(dif) > 24) { + dif = (dif < 0 ? -24 : 24); + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; } } } // Apply friction - if ( NPCS.NPC->client->ps.velocity[0] ) - { + if (NPCS.NPC->client->ps.velocity[0]) { NPCS.NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[0]) < 1) { NPCS.NPC->client->ps.velocity[0] = 0; } } - if ( NPCS.NPC->client->ps.velocity[1] ) - { + if (NPCS.NPC->client->ps.velocity[1]) { NPCS.NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[1]) < 1) { NPCS.NPC->client->ps.velocity[1] = 0; } } } -#define REMOTE_STRAFE_VEL 256 -#define REMOTE_STRAFE_DIS 200 -#define REMOTE_UPWARD_PUSH 32 +#define REMOTE_STRAFE_VEL 256 +#define REMOTE_STRAFE_DIS 200 +#define REMOTE_UPWARD_PUSH 32 /* ------------------------- Remote_Strafe ------------------------- */ -void Remote_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Remote_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPCS.NPC->r.currentOrigin, REMOTE_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPCS.NPC->r.currentOrigin, REMOTE_STRAFE_DIS * dir, right, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPCS.NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPCS.NPC->client->ps.velocity, REMOTE_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/remote/misc/hiss.wav")); // Add a slight upward push NPCS.NPC->client->ps.velocity[2] += REMOTE_UPWARD_PUSH; // Set the strafe start time so we can do a controlled roll - // NPC->fx_time = level.time; + // NPC->fx_time = level.time; NPCS.NPCInfo->standTime = level.time + 3000 + Q_flrand(0.0f, 1.0f) * 500; } } -#define REMOTE_FORWARD_BASE_SPEED 10 -#define REMOTE_FORWARD_MULTIPLIER 5 +#define REMOTE_FORWARD_BASE_SPEED 10 +#define REMOTE_FORWARD_MULTIPLIER 5 /* ------------------------- Remote_Hunt ------------------------- */ -void Remote_Hunt( qboolean visible, qboolean advance, qboolean retreat ) -{ - float distance, speed; - vec3_t forward; +void Remote_Hunt(qboolean visible, qboolean advance, qboolean retreat) { + float distance, speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCS.NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCS.NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Remote_Strafe(); return; } } - //If we don't want to advance, stop here - if ( advance == qfalse && visible == qtrue ) + // If we don't want to advance, stop here + if (advance == qfalse && visible == qtrue) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = REMOTE_FORWARD_BASE_SPEED + REMOTE_FORWARD_MULTIPLIER * g_npcspskill.integer; - if ( retreat == qtrue ) - { + if (retreat == qtrue) { speed *= -1; } - VectorMA( NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity); } - /* ------------------------- Remote_Fire ------------------------- */ -void Remote_Fire (void) -{ - vec3_t delta1, enemy_org1, muzzle1; - vec3_t angleToEnemy1; - static vec3_t forward, vright, up; -// static vec3_t muzzle; - gentity_t *missile; +void Remote_Fire(void) { + vec3_t delta1, enemy_org1, muzzle1; + vec3_t angleToEnemy1; + static vec3_t forward, vright, up; + // static vec3_t muzzle; + gentity_t *missile; - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org1 ); - VectorCopy( NPCS.NPC->r.currentOrigin, muzzle1 ); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org1); + VectorCopy(NPCS.NPC->r.currentOrigin, muzzle1); - VectorSubtract (enemy_org1, muzzle1, delta1); + VectorSubtract(enemy_org1, muzzle1, delta1); - vectoangles ( delta1, angleToEnemy1 ); - AngleVectors (angleToEnemy1, forward, vright, up); + vectoangles(delta1, angleToEnemy1); + AngleVectors(angleToEnemy1, forward, vright, up); - missile = CreateMissile( NPCS.NPC->r.currentOrigin, forward, 1000, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(NPCS.NPC->r.currentOrigin, forward, 1000, 10000, NPCS.NPC, qfalse); - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), NPCS.NPC->r.currentOrigin, forward ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), NPCS.NPC->r.currentOrigin, forward); missile->classname = "briar"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -275,7 +243,6 @@ void Remote_Fire (void) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - } /* @@ -283,72 +250,64 @@ void Remote_Fire (void) Remote_Ranged ------------------------- */ -void Remote_Ranged( qboolean visible, qboolean advance, qboolean retreat ) -{ - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) // Attack? +void Remote_Ranged(qboolean visible, qboolean advance, qboolean retreat) { + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 3000 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 3000)); Remote_Fire(); } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); } } -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) /* ------------------------- Remote_Attack ------------------------- */ -void Remote_Attack( void ) -{ - float distance; - qboolean visible; - float idealDist; - qboolean advance, retreat; - - if ( TIMER_Done(NPCS.NPC,"spin") ) - { - TIMER_Set( NPCS.NPC, "spin", Q_irand( 250, 1500 ) ); - NPCS.NPCInfo->desiredYaw += Q_irand( -200, 200 ); +void Remote_Attack(void) { + float distance; + qboolean visible; + float idealDist; + qboolean advance, retreat; + + if (TIMER_Done(NPCS.NPC, "spin")) { + TIMER_Set(NPCS.NPC, "spin", Q_irand(250, 1500)); + NPCS.NPCInfo->desiredYaw += Q_irand(-200, 200); } // Always keep a good height off the ground Remote_MaintainHeight(); // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse ) - { + if (NPC_CheckEnemyExt(qfalse) == qfalse) { Remote_Idle(); return; } // Rate our distance to the target, and our visibilty - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - idealDist = MIN_DISTANCE_SQR+(MIN_DISTANCE_SQR*flrand( 0, 1 )); - advance = (qboolean)(distance > idealDist*1.25); - retreat = (qboolean)(distance < idealDist*0.75); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + idealDist = MIN_DISTANCE_SQR + (MIN_DISTANCE_SQR * flrand(0, 1)); + advance = (qboolean)(distance > idealDist * 1.25); + retreat = (qboolean)(distance < idealDist * 0.75); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Remote_Hunt( visible, advance, retreat ); + if (visible == qfalse) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Remote_Hunt(visible, advance, retreat); return; } } - Remote_Ranged( visible, advance, retreat ); - + Remote_Ranged(visible, advance, retreat); } /* @@ -356,8 +315,7 @@ void Remote_Attack( void ) Remote_Idle ------------------------- */ -void Remote_Idle( void ) -{ +void Remote_Idle(void) { Remote_MaintainHeight(); NPC_BSIdle(); @@ -368,35 +326,30 @@ void Remote_Idle( void ) Remote_Patrol ------------------------- */ -void Remote_Patrol( void ) -{ +void Remote_Patrol(void) { Remote_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - if ( UpdateGoal() ) - { - //start loop sound once we move + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + if (UpdateGoal()) { + // start loop sound once we move NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } - /* ------------------------- NPC_BSRemote_Default ------------------------- */ -void NPC_BSRemote_Default( void ) -{ - if ( NPCS.NPC->enemy ) +void NPC_BSRemote_Default(void) { + if (NPCS.NPC->enemy) Remote_Attack(); - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) + else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) Remote_Patrol(); else Remote_Idle(); diff --git a/codemp/game/NPC_AI_Seeker.c b/codemp/game/NPC_AI_Seeker.c index 47864259aa..2298f90a6d 100644 --- a/codemp/game/NPC_AI_Seeker.c +++ b/codemp/game/NPC_AI_Seeker.c @@ -23,123 +23,102 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -extern void Boba_FireDecide( void ); +extern void Boba_FireDecide(void); -void Seeker_Strafe( void ); +void Seeker_Strafe(void); -#define VELOCITY_DECAY 0.7f +#define VELOCITY_DECAY 0.7f -#define MIN_MELEE_RANGE 320 -#define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) +#define MIN_MELEE_RANGE 320 +#define MIN_MELEE_RANGE_SQR (MIN_MELEE_RANGE * MIN_MELEE_RANGE) -#define MIN_DISTANCE 80 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 80 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SEEKER_STRAFE_VEL 100 -#define SEEKER_STRAFE_DIS 200 -#define SEEKER_UPWARD_PUSH 32 +#define SEEKER_STRAFE_VEL 100 +#define SEEKER_STRAFE_DIS 200 +#define SEEKER_UPWARD_PUSH 32 -#define SEEKER_FORWARD_BASE_SPEED 10 -#define SEEKER_FORWARD_MULTIPLIER 2 +#define SEEKER_FORWARD_BASE_SPEED 10 +#define SEEKER_FORWARD_MULTIPLIER 2 -#define SEEKER_SEEK_RADIUS 1024 +#define SEEKER_SEEK_RADIUS 1024 //------------------------------------ -void NPC_Seeker_Precache(void) -{ +void NPC_Seeker_Precache(void) { G_SoundIndex("sound/chars/seeker/misc/fire.wav"); - G_SoundIndex( "sound/chars/seeker/misc/hiss.wav"); - G_EffectIndex( "env/small_explode"); + G_SoundIndex("sound/chars/seeker/misc/hiss.wav"); + G_EffectIndex("env/small_explode"); } //------------------------------------ -void NPC_Seeker_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ - if ( !(self->NPC->aiFlags&NPCAI_CUSTOM_GRAVITY )) - { - G_Damage( self, NULL, NULL, (float*)vec3_origin, (float*)vec3_origin, 999, 0, MOD_FALLING ); +void NPC_Seeker_Pain(gentity_t *self, gentity_t *attacker, int damage) { + if (!(self->NPC->aiFlags & NPCAI_CUSTOM_GRAVITY)) { + G_Damage(self, NULL, NULL, (float *)vec3_origin, (float *)vec3_origin, 999, 0, MOD_FALLING); } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); Seeker_Strafe(); RestoreNPCGlobals(); - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); } //------------------------------------ -void Seeker_MaintainHeight( void ) -{ - float dif; +void Seeker_MaintainHeight(void) { + float dif; // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at or a little below enemy eye level - if ( NPCS.NPC->enemy ) - { - if (TIMER_Done( NPCS.NPC, "heightChange" )) - { + if (NPCS.NPC->enemy) { + if (TIMER_Done(NPCS.NPC, "heightChange")) { float difFactor; - TIMER_Set( NPCS.NPC,"heightChange",Q_irand( 1000, 3000 )); + TIMER_Set(NPCS.NPC, "heightChange", Q_irand(1000, 3000)); // Find the height difference - dif = (NPCS.NPC->enemy->r.currentOrigin[2] + flrand( NPCS.NPC->enemy->r.maxs[2]/2, NPCS.NPC->enemy->r.maxs[2]+8 )) - NPCS.NPC->r.currentOrigin[2]; + dif = (NPCS.NPC->enemy->r.currentOrigin[2] + flrand(NPCS.NPC->enemy->r.maxs[2] / 2, NPCS.NPC->enemy->r.maxs[2] + 8)) - NPCS.NPC->r.currentOrigin[2]; difFactor = 1.0f; - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPCS.NPC, "flameTime" ) ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + if (TIMER_Done(NPCS.NPC, "flameTime")) { difFactor = 10.0f; } } // cap to prevent dramatic height shifts - if ( fabs( dif ) > 2*difFactor ) - { - if ( fabs( dif ) > 24*difFactor ) - { - dif = ( dif < 0 ? -24*difFactor : 24*difFactor ); + if (fabs(dif) > 2 * difFactor) { + if (fabs(dif) > 24 * difFactor) { + dif = (dif < 0 ? -24 * difFactor : 24 * difFactor); } - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; } - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - NPCS.NPC->client->ps.velocity[2] *= flrand( 0.85f, 3.0f ); + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + NPCS.NPC->client->ps.velocity[2] *= flrand(0.85f, 3.0f); } } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCS.NPCInfo->goalEntity ) // Is there a goal? + if (NPCS.NPCInfo->goalEntity) // Is there a goal? { goal = NPCS.NPCInfo->goalEntity; - } - else - { + } else { goal = NPCS.NPCInfo->lastGoalEntity; } - if ( goal ) - { + if (goal) { dif = goal->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; - if ( fabs( dif ) > 24 ) - { - NPCS.ucmd.upmove = ( NPCS.ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPCS.NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > 24) { + NPCS.ucmd.upmove = (NPCS.ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 2) { NPCS.NPC->client->ps.velocity[2] = 0; } } @@ -148,107 +127,90 @@ void Seeker_MaintainHeight( void ) } // Apply friction - if ( NPCS.NPC->client->ps.velocity[0] ) - { + if (NPCS.NPC->client->ps.velocity[0]) { NPCS.NPC->client->ps.velocity[0] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[0]) < 1) { NPCS.NPC->client->ps.velocity[0] = 0; } } - if ( NPCS.NPC->client->ps.velocity[1] ) - { + if (NPCS.NPC->client->ps.velocity[1]) { NPCS.NPC->client->ps.velocity[1] *= VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[1]) < 1) { NPCS.NPC->client->ps.velocity[1] = 0; } } } //------------------------------------ -void Seeker_Strafe( void ) -{ - int side; - vec3_t end, right, dir; - trace_t tr; +void Seeker_Strafe(void) { + int side; + vec3_t end, right, dir; + trace_t tr; - if ( Q_flrand(0.0f, 1.0f) > 0.7f || !NPCS.NPC->enemy || !NPCS.NPC->enemy->client ) - { + if (Q_flrand(0.0f, 1.0f) > 0.7f || !NPCS.NPC->enemy || !NPCS.NPC->enemy->client) { // Do a regular style strafe - AngleVectors( NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonably valid - side = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPCS.NPC->r.currentOrigin, SEEKER_STRAFE_DIS * side, right, end ); + side = (rand() & 1) ? -1 : 1; + VectorMA(NPCS.NPC->r.currentOrigin, SEEKER_STRAFE_DIS * side, right, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { + if (tr.fraction > 0.9f) { float vel = SEEKER_STRAFE_VEL; float upPush = SEEKER_UPWARD_PUSH; - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); - } - else - { + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/seeker/misc/hiss")); + } else { vel *= 3.0f; upPush *= 4.0f; } - VectorMA( NPCS.NPC->client->ps.velocity, vel*side, right, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, vel * side, right, NPCS.NPC->client->ps.velocity); // Add a slight upward push NPCS.NPC->client->ps.velocity[2] += upPush; NPCS.NPCInfo->standTime = level.time + 1000 + Q_flrand(0.0f, 1.0f) * 500; } - } - else - { + } else { float stDis; // Do a strafe to try and keep on the side of their enemy - AngleVectors( NPCS.NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL ); + AngleVectors(NPCS.NPC->enemy->client->renderInfo.eyeAngles, dir, right, NULL); // Pick a random side - side = ( rand() & 1 ) ? -1 : 1; + side = (rand() & 1) ? -1 : 1; stDis = SEEKER_STRAFE_DIS; - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { stDis *= 2.0f; } - VectorMA( NPCS.NPC->enemy->r.currentOrigin, stDis * side, right, end ); + VectorMA(NPCS.NPC->enemy->r.currentOrigin, stDis * side, right, end); // then add a very small bit of random in front of/behind the player action - VectorMA( end, Q_flrand(-1.0f, 1.0f) * 25, dir, end ); + VectorMA(end, Q_flrand(-1.0f, 1.0f) * 25, dir, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { + if (tr.fraction > 0.9f) { float dis, upPush; - VectorSubtract( tr.endpos, NPCS.NPC->r.currentOrigin, dir ); + VectorSubtract(tr.endpos, NPCS.NPC->r.currentOrigin, dir); dir[2] *= 0.25; // do less upward change - dis = VectorNormalize( dir ); + dis = VectorNormalize(dir); // Try to move the desired enemy side - VectorMA( NPCS.NPC->client->ps.velocity, dis, dir, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, dis, dir, NPCS.NPC->client->ps.velocity); upPush = SEEKER_UPWARD_PUSH; - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); - } - else - { + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/seeker/misc/hiss")); + } else { upPush *= 4.0f; } @@ -261,69 +223,60 @@ void Seeker_Strafe( void ) } //------------------------------------ -void Seeker_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Seeker_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); // If we're not supposed to stand still, pursue the player - if ( NPCS.NPCInfo->standTime < level.time ) - { + if (NPCS.NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Seeker_Strafe(); return; } } // If we don't want to advance, stop here - if ( advance == qfalse ) - { + if (advance == qfalse) { return; } // Only try and navigate if the player is visible - if ( visible == qfalse ) - { + if (visible == qfalse) { // Move towards our goal NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 24; // Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) - { + if (NPC_GetMoveDirection(forward, &distance) == qfalse) { return; } - } - else - { - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SEEKER_FORWARD_BASE_SPEED + SEEKER_FORWARD_MULTIPLIER * g_npcspskill.integer; - VectorMA( NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity); } //------------------------------------ -void Seeker_Fire( void ) -{ - vec3_t dir, enemy_org, muzzle; - gentity_t *missile; +void Seeker_Fire(void) { + vec3_t dir, enemy_org, muzzle; + gentity_t *missile; - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org ); - VectorSubtract( enemy_org, NPCS.NPC->r.currentOrigin, dir ); - VectorNormalize( dir ); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org); + VectorSubtract(enemy_org, NPCS.NPC->r.currentOrigin, dir); + VectorNormalize(dir); // move a bit forward in the direction we shall shoot in so that the bolt doesn't poke out the other side of the seeker - VectorMA( NPCS.NPC->r.currentOrigin, 15, dir, muzzle ); + VectorMA(NPCS.NPC->r.currentOrigin, 15, dir, muzzle); - missile = CreateMissile( muzzle, dir, 1000, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle, dir, 1000, 10000, NPCS.NPC, qfalse); - G_PlayEffectID( G_EffectIndex("blaster/muzzle_flash"), NPCS.NPC->r.currentOrigin, dir ); + G_PlayEffectID(G_EffectIndex("blaster/muzzle_flash"), NPCS.NPC->r.currentOrigin, dir); missile->classname = "blaster"; missile->s.weapon = WP_BLASTER; @@ -332,123 +285,104 @@ void Seeker_Fire( void ) missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BLASTER; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - if ( NPCS.NPC->r.ownerNum < ENTITYNUM_NONE ) - { + if (NPCS.NPC->r.ownerNum < ENTITYNUM_NONE) { missile->r.ownerNum = NPCS.NPC->r.ownerNum; } } //------------------------------------ -void Seeker_Ranged( qboolean visible, qboolean advance ) -{ - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( NPCS.NPC->count > 0 ) - { - if ( TIMER_Done( NPCS.NPC, "attackDelay" )) // Attack? +void Seeker_Ranged(qboolean visible, qboolean advance) { + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { + if (NPCS.NPC->count > 0) { + if (TIMER_Done(NPCS.NPC, "attackDelay")) // Attack? { - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 250, 2500 )); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(250, 2500)); Seeker_Fire(); NPCS.NPC->count--; } - } - else - { + } else { // out of ammo, so let it die...give it a push up so it can fall more and blow up on impact - // NPC->client->ps.gravity = 900; - // NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; - // NPC->client->ps.velocity[2] += 16; - G_Damage( NPCS.NPC, NPCS.NPC, NPCS.NPC, NULL, NULL, 999, 0, MOD_UNKNOWN ); + // NPC->client->ps.gravity = 900; + // NPC->svFlags &= ~SVF_CUSTOM_GRAVITY; + // NPC->client->ps.velocity[2] += 16; + G_Damage(NPCS.NPC, NPCS.NPC, NPCS.NPC, NULL, NULL, 999, 0, MOD_UNKNOWN); } } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); } } //------------------------------------ -void Seeker_Attack( void ) -{ - float distance; - qboolean visible, advance; +void Seeker_Attack(void) { + float distance; + qboolean visible, advance; // Always keep a good height off the ground Seeker_MaintainHeight(); // Rate our distance to the target, and our visibilty - distance = DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - advance = (qboolean)(distance>(200.0f*200.0f)); + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + advance = (qboolean)(distance > (200.0f * 200.0f)); } // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Seeker_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Seeker_Hunt(visible, advance); return; } } - Seeker_Ranged( visible, advance ); + Seeker_Ranged(visible, advance); } //------------------------------------ -void Seeker_FindEnemy( void ) -{ - int numFound; - float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; - vec3_t mins, maxs; - int entityList[MAX_GENTITIES]; - gentity_t *ent, *best = NULL; - int i; +void Seeker_FindEnemy(void) { + int numFound; + float dis, bestDis = SEEKER_SEEK_RADIUS * SEEKER_SEEK_RADIUS + 1; + vec3_t mins, maxs; + int entityList[MAX_GENTITIES]; + gentity_t *ent, *best = NULL; + int i; - VectorSet( maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS, SEEKER_SEEK_RADIUS); + VectorScale(maxs, -1, mins); - numFound = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numFound = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( i = 0 ; i < numFound ; i++ ) - { + for (i = 0; i < numFound; i++) { ent = &g_entities[entityList[i]]; - if ( ent->s.number == NPCS.NPC->s.number - || !ent->client //&& || !ent->NPC - || ent->health <= 0 - || !ent->inuse ) - { + if (ent->s.number == NPCS.NPC->s.number || !ent->client //&& || !ent->NPC + || ent->health <= 0 || !ent->inuse) { continue; } - if ( ent->client->playerTeam == NPCS.NPC->client->playerTeam || ent->client->playerTeam == NPCTEAM_NEUTRAL ) // don't attack same team or bots + if (ent->client->playerTeam == NPCS.NPC->client->playerTeam || ent->client->playerTeam == NPCTEAM_NEUTRAL) // don't attack same team or bots { continue; } // try to find the closest visible one - if ( !NPC_ClearLOS4( ent )) - { + if (!NPC_ClearLOS4(ent)) { continue; } - dis = DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, ent->r.currentOrigin ); + dis = DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, ent->r.currentOrigin); - if ( dis <= bestDis ) - { + if (dis <= bestDis) { bestDis = dis; best = ent; } } - if ( best ) - { + if (best) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPCS.NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi @@ -457,92 +391,74 @@ void Seeker_FindEnemy( void ) } //------------------------------------ -void Seeker_FollowOwner( void ) -{ - float dis, minDistSqr; - vec3_t pt, dir; - gentity_t *owner = &g_entities[NPCS.NPC->s.owner]; +void Seeker_FollowOwner(void) { + float dis, minDistSqr; + vec3_t pt, dir; + gentity_t *owner = &g_entities[NPCS.NPC->s.owner]; Seeker_MaintainHeight(); - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { owner = NPCS.NPC->enemy; } - if ( !owner || owner == NPCS.NPC || !owner->client ) - { + if (!owner || owner == NPCS.NPC || !owner->client) { return; } - //rwwFIXMEFIXME: Care about all clients not just 0 - dis = DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, owner->r.currentOrigin ); + // rwwFIXMEFIXME: Care about all clients not just 0 + dis = DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, owner->r.currentOrigin); minDistSqr = MIN_DISTANCE_SQR; - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPCS.NPC, "flameTime" ) ) - { - minDistSqr = 200*200; + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + if (TIMER_Done(NPCS.NPC, "flameTime")) { + minDistSqr = 200 * 200; } } - if ( dis < minDistSqr ) - { + if (dis < minDistSqr) { // generally circle the player closely till we take an enemy..this is our target point - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { - pt[0] = owner->r.currentOrigin[0] + cos( level.time * 0.001f + NPCS.NPC->random ) * 250; - pt[1] = owner->r.currentOrigin[1] + sin( level.time * 0.001f + NPCS.NPC->random ) * 250; - if ( NPCS.NPC->client->jetPackTime < level.time ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { + pt[0] = owner->r.currentOrigin[0] + cos(level.time * 0.001f + NPCS.NPC->random) * 250; + pt[1] = owner->r.currentOrigin[1] + sin(level.time * 0.001f + NPCS.NPC->random) * 250; + if (NPCS.NPC->client->jetPackTime < level.time) { pt[2] = NPCS.NPC->r.currentOrigin[2] - 64; - } - else - { + } else { pt[2] = owner->r.currentOrigin[2] + 200; } - } - else - { - pt[0] = owner->r.currentOrigin[0] + cos( level.time * 0.001f + NPCS.NPC->random ) * 56; - pt[1] = owner->r.currentOrigin[1] + sin( level.time * 0.001f + NPCS.NPC->random ) * 56; + } else { + pt[0] = owner->r.currentOrigin[0] + cos(level.time * 0.001f + NPCS.NPC->random) * 56; + pt[1] = owner->r.currentOrigin[1] + sin(level.time * 0.001f + NPCS.NPC->random) * 56; pt[2] = owner->r.currentOrigin[2] + 40; } - VectorSubtract( pt, NPCS.NPC->r.currentOrigin, dir ); - VectorMA( NPCS.NPC->client->ps.velocity, 0.8f, dir, NPCS.NPC->client->ps.velocity ); - } - else - { - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT ) - { - if ( TIMER_Done( NPCS.NPC, "seekerhiss" )) - { - TIMER_Set( NPCS.NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000 ); - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/seeker/misc/hiss" )); + VectorSubtract(pt, NPCS.NPC->r.currentOrigin, dir); + VectorMA(NPCS.NPC->client->ps.velocity, 0.8f, dir, NPCS.NPC->client->ps.velocity); + } else { + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT) { + if (TIMER_Done(NPCS.NPC, "seekerhiss")) { + TIMER_Set(NPCS.NPC, "seekerhiss", 1000 + Q_flrand(0.0f, 1.0f) * 1000); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/seeker/misc/hiss")); } } // Hey come back! NPCS.NPCInfo->goalEntity = owner; NPCS.NPCInfo->goalRadius = 32; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); NPCS.NPC->parent = owner; } - if ( NPCS.NPCInfo->enemyCheckDebounceTime < level.time ) - { + if (NPCS.NPCInfo->enemyCheckDebounceTime < level.time) { // check twice a second to find a new enemy Seeker_FindEnemy(); NPCS.NPCInfo->enemyCheckDebounceTime = level.time + 500; } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } //------------------------------------ -void NPC_BSSeeker_Default( void ) -{ +void NPC_BSSeeker_Default(void) { /* if ( in_camera ) { @@ -553,39 +469,31 @@ void NPC_BSSeeker_Default( void ) } } */ - //N/A for MP. - if ( NPCS.NPC->r.ownerNum < ENTITYNUM_NONE ) - { - //OJKFIXME: clientnum 0 + // N/A for MP. + if (NPCS.NPC->r.ownerNum < ENTITYNUM_NONE) { + // OJKFIXME: clientnum 0 gentity_t *owner = &g_entities[0]; - if ( owner->health <= 0 - || (owner->client && owner->client->pers.connected == CON_DISCONNECTED) ) - {//owner is dead or gone - //remove me - G_Damage( NPCS.NPC, NULL, NULL, NULL, NULL, 10000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG ); + if (owner->health <= 0 || (owner->client && owner->client->pers.connected == CON_DISCONNECTED)) { // owner is dead or gone + // remove me + G_Damage(NPCS.NPC, NULL, NULL, NULL, NULL, 10000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); return; } } - if ( NPCS.NPC->random == 0.0f ) - { + if (NPCS.NPC->random == 0.0f) { // used to offset seekers around a circle so they don't occupy the same spot. This is not a fool-proof method. NPCS.NPC->random = Q_flrand(0.0f, 1.0f) * 6.3f; // roughly 2pi } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->health && NPCS.NPC->enemy->inuse ) - { - //OJKFIXME: clientnum 0 - if ( NPCS.NPC->client->NPC_class != CLASS_BOBAFETT && ( NPCS.NPC->enemy->s.number == 0 || ( NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_SEEKER )) ) - { - //hacked to never take the player as an enemy, even if the player shoots at it + if (NPCS.NPC->enemy && NPCS.NPC->enemy->health && NPCS.NPC->enemy->inuse) { + // OJKFIXME: clientnum 0 + if (NPCS.NPC->client->NPC_class != CLASS_BOBAFETT && + (NPCS.NPC->enemy->s.number == 0 || (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_SEEKER))) { + // hacked to never take the player as an enemy, even if the player shoots at it NPCS.NPC->enemy = NULL; - } - else - { + } else { Seeker_Attack(); - if ( NPCS.NPC->client->NPC_class == CLASS_BOBAFETT ) - { + if (NPCS.NPC->client->NPC_class == CLASS_BOBAFETT) { Boba_FireDecide(); } return; diff --git a/codemp/game/NPC_AI_Sentry.c b/codemp/game/NPC_AI_Sentry.c index f0ff05cac9..f7135e9858 100644 --- a/codemp/game/NPC_AI_Sentry.c +++ b/codemp/game/NPC_AI_Sentry.c @@ -23,24 +23,23 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -extern gitem_t *BG_FindItemForAmmo( ammo_t ammo ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); +extern gitem_t *BG_FindItemForAmmo(ammo_t ammo); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); -#define MIN_DISTANCE 256 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 256 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define SENTRY_FORWARD_BASE_SPEED 10 -#define SENTRY_FORWARD_MULTIPLIER 5 +#define SENTRY_FORWARD_BASE_SPEED 10 +#define SENTRY_FORWARD_MULTIPLIER 5 -#define SENTRY_VELOCITY_DECAY 0.85f -#define SENTRY_STRAFE_VEL 256 -#define SENTRY_STRAFE_DIS 200 -#define SENTRY_UPWARD_PUSH 32 -#define SENTRY_HOVER_HEIGHT 24 +#define SENTRY_VELOCITY_DECAY 0.85f +#define SENTRY_STRAFE_VEL 256 +#define SENTRY_STRAFE_DIS 200 +#define SENTRY_UPWARD_PUSH 32 +#define SENTRY_HOVER_HEIGHT 24 -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, @@ -54,26 +53,24 @@ enum NPC_Sentry_Precache ------------------------- */ -void NPC_Sentry_Precache(void) -{ +void NPC_Sentry_Precache(void) { int i; - G_SoundIndex( "sound/chars/sentry/misc/sentry_explo" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_pain" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_open" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_shield_close" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); - G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); + G_SoundIndex("sound/chars/sentry/misc/sentry_explo"); + G_SoundIndex("sound/chars/sentry/misc/sentry_pain"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_open"); + G_SoundIndex("sound/chars/sentry/misc/sentry_shield_close"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); + G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); - for ( i = 1; i < 4; i++) - { - G_SoundIndex( va( "sound/chars/sentry/misc/talk%d", i ) ); + for (i = 1; i < 4; i++) { + G_SoundIndex(va("sound/chars/sentry/misc/talk%d", i)); } - G_EffectIndex( "bryar/muzzle_flash"); - G_EffectIndex( "env/med_explode"); + G_EffectIndex("bryar/muzzle_flash"); + G_EffectIndex("env/med_explode"); - RegisterItem( BG_FindItemForAmmo( AMMO_BLASTER )); + RegisterItem(BG_FindItemForAmmo(AMMO_BLASTER)); } /* @@ -81,13 +78,12 @@ void NPC_Sentry_Precache(void) sentry_use ================ */ -void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void sentry_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); self->flags &= ~FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; + NPC_SetAnim(self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // self->NPC->localState = LSTATE_WAKEUP; self->NPC->localState = LSTATE_ACTIVE; } @@ -96,32 +92,30 @@ void sentry_use( gentity_t *self, gentity_t *other, gentity_t *activator) NPC_Sentry_Pain ------------------------- */ -void NPC_Sentry_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Sentry_Pain(gentity_t *self, gentity_t *attacker, int damage) { int mod = gPainMOD; - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { self->NPC->burstCount = 0; - TIMER_Set( self, "attackDelay", Q_irand( 9000, 12000) ); + TIMER_Set(self, "attackDelay", Q_irand(9000, 12000)); self->flags |= FL_SHIELDED; - NPC_SetAnim( self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_pain") ); + NPC_SetAnim(self, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_pain")); self->NPC->localState = LSTATE_ACTIVE; } // You got hit, go after the enemy -// if (self->NPC->localState == LSTATE_ASLEEP) -// { -// G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); -// -// self->flags &= ~FL_SHIELDED; -// NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); -// self->NPC->localState = LSTATE_WAKEUP; -// } + // if (self->NPC->localState == LSTATE_ASLEEP) + // { + // G_Sound( self, G_SoundIndex("sound/chars/sentry/misc/shieldsopen.wav")); + // + // self->flags &= ~FL_SHIELDED; + // NPC_SetAnim( self, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // self->NPC->localState = LSTATE_WAKEUP; + // } } /* @@ -129,40 +123,31 @@ void NPC_Sentry_Pain(gentity_t *self, gentity_t *attacker, int damage) Sentry_Fire ------------------------- */ -void Sentry_Fire (void) -{ - vec3_t muzzle; - static vec3_t forward, vright, up; - gentity_t *missile; - mdxaBone_t boltMatrix; - int bolt, which; +void Sentry_Fire(void) { + vec3_t muzzle; + static vec3_t forward, vright, up; + gentity_t *missile; + mdxaBone_t boltMatrix; + int bolt, which; NPCS.NPC->flags &= ~FL_SHIELDED; - if ( NPCS.NPCInfo->localState == LSTATE_POWERING_UP ) - { - if ( TIMER_Done( NPCS.NPC, "powerup" )) - { + if (NPCS.NPCInfo->localState == LSTATE_POWERING_UP) { + if (TIMER_Done(NPCS.NPC, "powerup")) { NPCS.NPCInfo->localState = LSTATE_ATTACKING; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // can't do anything right now return; } - } - else if ( NPCS.NPCInfo->localState == LSTATE_ACTIVE ) - { + } else if (NPCS.NPCInfo->localState == LSTATE_ACTIVE) { NPCS.NPCInfo->localState = LSTATE_POWERING_UP; - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_shield_open") ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "powerup", 250 ); + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_shield_open")); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_POWERUP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "powerup", 250); return; - } - else if ( NPCS.NPCInfo->localState != LSTATE_ATTACKING ) - { + } else if (NPCS.NPCInfo->localState != LSTATE_ATTACKING) { // bad because we are uninitialized NPCS.NPCInfo->localState = LSTATE_ACTIVE; return; @@ -170,8 +155,7 @@ void Sentry_Fire (void) // Which muzzle to fire from? which = NPCS.NPCInfo->burstCount % 3; - switch( which ) - { + switch (which) { case 0: bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash1"); break; @@ -183,19 +167,17 @@ void Sentry_Fire (void) bolt = trap->G2API_AddBolt(NPCS.NPC->ghoul2, 0, "*flash03"); } - trap->G2API_GetBoltMatrix( NPCS.NPC->ghoul2, 0, - bolt, - &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, - NULL, NPCS.NPC->modelScale ); + trap->G2API_GetBoltMatrix(NPCS.NPC->ghoul2, 0, bolt, &boltMatrix, NPCS.NPC->r.currentAngles, NPCS.NPC->r.currentOrigin, level.time, NULL, + NPCS.NPC->modelScale); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, muzzle); - AngleVectors( NPCS.NPC->r.currentAngles, forward, vright, up ); -// G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); + AngleVectors(NPCS.NPC->r.currentAngles, forward, vright, up); + // G_Sound( NPC, G_SoundIndex("sound/chars/sentry/misc/shoot.wav")); - G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle, forward ); + G_PlayEffectID(G_EffectIndex("bryar/muzzle_flash"), muzzle, forward); - missile = CreateMissile( muzzle, forward, 1600, 10000, NPCS.NPC, qfalse ); + missile = CreateMissile(muzzle, forward, 1600, 10000, NPCS.NPC, qfalse); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -209,13 +191,10 @@ void Sentry_Fire (void) missile->damage = 5; // now scale for difficulty - if ( g_npcspskill.integer == 0 ) - { + if (g_npcspskill.integer == 0) { NPCS.NPC->attackDebounceTime += 200; missile->damage = 1; - } - else if ( g_npcspskill.integer == 1 ) - { + } else if (g_npcspskill.integer == 1) { NPCS.NPC->attackDebounceTime += 100; missile->damage = 3; } @@ -226,100 +205,80 @@ void Sentry_Fire (void) Sentry_MaintainHeight ------------------------- */ -void Sentry_MaintainHeight( void ) -{ - float dif; +void Sentry_MaintainHeight(void) { + float dif; - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_1_lp" ); + NPCS.NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_1_lp"); // Update our angles regardless - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); // If we have an enemy, we should try to hover at about enemy eye level - if ( NPCS.NPC->enemy ) - { + if (NPCS.NPC->enemy) { // Find the height difference - dif = (NPCS.NPC->enemy->r.currentOrigin[2]+NPCS.NPC->enemy->r.maxs[2]) - NPCS.NPC->r.currentOrigin[2]; + dif = (NPCS.NPC->enemy->r.currentOrigin[2] + NPCS.NPC->enemy->r.maxs[2]) - NPCS.NPC->r.currentOrigin[2]; // cap to prevent dramatic height shifts - if ( fabs( dif ) > 8 ) - { - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - dif = ( dif < 0 ? -24 : 24 ); + if (fabs(dif) > 8) { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + dif = (dif < 0 ? -24 : 24); } - NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2]+dif)/2; + NPCS.NPC->client->ps.velocity[2] = (NPCS.NPC->client->ps.velocity[2] + dif) / 2; } - } - else - { + } else { gentity_t *goal = NULL; - if ( NPCS.NPCInfo->goalEntity ) // Is there a goal? + if (NPCS.NPCInfo->goalEntity) // Is there a goal? { goal = NPCS.NPCInfo->goalEntity; - } - else - { + } else { goal = NPCS.NPCInfo->lastGoalEntity; } - if (goal) - { + if (goal) { dif = goal->r.currentOrigin[2] - NPCS.NPC->r.currentOrigin[2]; - if ( fabs( dif ) > SENTRY_HOVER_HEIGHT ) - { - NPCS.ucmd.upmove = ( NPCS.ucmd.upmove < 0 ? -4 : 4 ); - } - else - { - if ( NPCS.NPC->client->ps.velocity[2] ) - { + if (fabs(dif) > SENTRY_HOVER_HEIGHT) { + NPCS.ucmd.upmove = (NPCS.ucmd.upmove < 0 ? -4 : 4); + } else { + if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 2 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 2) { NPCS.NPC->client->ps.velocity[2] = 0; } } } } // Apply friction to Z - else if ( NPCS.NPC->client->ps.velocity[2] ) - { + else if (NPCS.NPC->client->ps.velocity[2]) { NPCS.NPC->client->ps.velocity[2] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[2] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[2]) < 1) { NPCS.NPC->client->ps.velocity[2] = 0; } } } // Apply friction - if ( NPCS.NPC->client->ps.velocity[0] ) - { + if (NPCS.NPC->client->ps.velocity[0]) { NPCS.NPC->client->ps.velocity[0] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[0] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[0]) < 1) { NPCS.NPC->client->ps.velocity[0] = 0; } } - if ( NPCS.NPC->client->ps.velocity[1] ) - { + if (NPCS.NPC->client->ps.velocity[1]) { NPCS.NPC->client->ps.velocity[1] *= SENTRY_VELOCITY_DECAY; - if ( fabs( NPCS.NPC->client->ps.velocity[1] ) < 1 ) - { + if (fabs(NPCS.NPC->client->ps.velocity[1]) < 1) { NPCS.NPC->client->ps.velocity[1] = 0; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); } /* @@ -327,22 +286,17 @@ void Sentry_MaintainHeight( void ) Sentry_Idle ------------------------- */ -void Sentry_Idle( void ) -{ +void Sentry_Idle(void) { Sentry_MaintainHeight(); // Is he waking up? - if (NPCS.NPCInfo->localState == LSTATE_WAKEUP) - { - if (NPCS.NPC->client->ps.torsoTimer<=0) - { + if (NPCS.NPCInfo->localState == LSTATE_WAKEUP) { + if (NPCS.NPC->client->ps.torsoTimer <= 0) { NPCS.NPCInfo->scriptFlags |= SCF_LOOK_FOR_ENEMIES; NPCS.NPCInfo->burstCount = 0; } - } - else - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + } else { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPC->flags |= FL_SHIELDED; NPC_BSIdle(); @@ -354,31 +308,29 @@ void Sentry_Idle( void ) Sentry_Strafe ------------------------- */ -void Sentry_Strafe( void ) -{ - int dir; - vec3_t end, right; - trace_t tr; +void Sentry_Strafe(void) { + int dir; + vec3_t end, right; + trace_t tr; - AngleVectors( NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL ); + AngleVectors(NPCS.NPC->client->renderInfo.eyeAngles, NULL, right, NULL); // Pick a random strafe direction, then check to see if doing a strafe would be // reasonable valid - dir = ( rand() & 1 ) ? -1 : 1; - VectorMA( NPCS.NPC->r.currentOrigin, SENTRY_STRAFE_DIS * dir, right, end ); + dir = (rand() & 1) ? -1 : 1; + VectorMA(NPCS.NPC->r.currentOrigin, SENTRY_STRAFE_DIS * dir, right, end); - trap->Trace( &tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, NPCS.NPC->r.currentOrigin, NULL, NULL, end, NPCS.NPC->s.number, MASK_SOLID, qfalse, 0, 0); // Close enough - if ( tr.fraction > 0.9f ) - { - VectorMA( NPCS.NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity ); + if (tr.fraction > 0.9f) { + VectorMA(NPCS.NPC->client->ps.velocity, SENTRY_STRAFE_VEL * dir, right, NPCS.NPC->client->ps.velocity); // Add a slight upward push NPCS.NPC->client->ps.velocity[2] += SENTRY_UPWARD_PUSH; // Set the strafe start time so we can do a controlled roll - // NPC->fx_time = level.time; + // NPC->fx_time = level.time; NPCS.NPCInfo->standTime = level.time + 3000 + Q_flrand(0.0f, 1.0f) * 500; } } @@ -388,45 +340,39 @@ void Sentry_Strafe( void ) Sentry_Hunt ------------------------- */ -void Sentry_Hunt( qboolean visible, qboolean advance ) -{ - float distance, speed; - vec3_t forward; +void Sentry_Hunt(qboolean visible, qboolean advance) { + float distance, speed; + vec3_t forward; - //If we're not supposed to stand still, pursue the player - if ( NPCS.NPCInfo->standTime < level.time ) - { + // If we're not supposed to stand still, pursue the player + if (NPCS.NPCInfo->standTime < level.time) { // Only strafe when we can see the player - if ( visible ) - { + if (visible) { Sentry_Strafe(); return; } } - //If we don't want to advance, stop here - if ( !advance && visible ) + // If we don't want to advance, stop here + if (!advance && visible) return; - //Only try and navigate if the player is visible - if ( visible == qfalse ) - { + // Only try and navigate if the player is visible + if (visible == qfalse) { // Move towards our goal NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; - //Get our direction from the navigator if we can't see our target - if ( NPC_GetMoveDirection( forward, &distance ) == qfalse ) + // Get our direction from the navigator if we can't see our target + if (NPC_GetMoveDirection(forward, &distance) == qfalse) return; - } - else - { - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward ); - /*distance = */VectorNormalize( forward ); + } else { + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, forward); + /*distance = */ VectorNormalize(forward); } speed = SENTRY_FORWARD_BASE_SPEED + SENTRY_FORWARD_MULTIPLIER * g_npcspskill.integer; - VectorMA( NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity ); + VectorMA(NPCS.NPC->client->ps.velocity, speed, forward, NPCS.NPC->client->ps.velocity); } /* @@ -434,35 +380,27 @@ void Sentry_Hunt( qboolean visible, qboolean advance ) Sentry_RangedAttack ------------------------- */ -void Sentry_RangedAttack( qboolean visible, qboolean advance ) -{ - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) && NPCS.NPC->attackDebounceTime < level.time && visible ) // Attack? +void Sentry_RangedAttack(qboolean visible, qboolean advance) { + if (TIMER_Done(NPCS.NPC, "attackDelay") && NPCS.NPC->attackDebounceTime < level.time && visible) // Attack? { - if ( NPCS.NPCInfo->burstCount > 6 ) - { - if ( !NPCS.NPC->fly_sound_debounce_time ) - {//delay closing down to give the player an opening - NPCS.NPC->fly_sound_debounce_time = level.time + Q_irand( 500, 2000 ); - } - else if ( NPCS.NPC->fly_sound_debounce_time < level.time ) - { + if (NPCS.NPCInfo->burstCount > 6) { + if (!NPCS.NPC->fly_sound_debounce_time) { // delay closing down to give the player an opening + NPCS.NPC->fly_sound_debounce_time = level.time + Q_irand(500, 2000); + } else if (NPCS.NPC->fly_sound_debounce_time < level.time) { NPCS.NPCInfo->localState = LSTATE_ACTIVE; NPCS.NPC->fly_sound_debounce_time = NPCS.NPCInfo->burstCount = 0; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 2000, 3500) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(2000, 3500)); NPCS.NPC->flags |= FL_SHIELDED; - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close" ); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_FLY_SHIELDED, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, "sound/chars/sentry/misc/sentry_shield_close"); } - } - else - { + } else { Sentry_Fire(); } } - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); } } @@ -471,100 +409,88 @@ void Sentry_RangedAttack( qboolean visible, qboolean advance ) Sentry_AttackDecision ------------------------- */ -void Sentry_AttackDecision( void ) -{ - float distance; - qboolean visible, advance; +void Sentry_AttackDecision(void) { + float distance; + qboolean visible, advance; // Always keep a good height off the ground Sentry_MaintainHeight(); - NPCS.NPC->s.loopSound = G_SoundIndex( "sound/chars/sentry/misc/sentry_hover_2_lp" ); + NPCS.NPC->s.loopSound = G_SoundIndex("sound/chars/sentry/misc/sentry_hover_2_lp"); - //randomly talk - if ( TIMER_Done(NPCS.NPC,"patrolNoise") ) - { - if (TIMER_Done(NPCS.NPC,"angerNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + if (TIMER_Done(NPCS.NPC, "angerNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(4000, 10000)); } } // He's dead. - if (NPCS.NPC->enemy->health<1) - { + if (NPCS.NPC->enemy->health < 1) { NPCS.NPC->enemy = NULL; Sentry_Idle(); return; } // If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse ) - { + if (NPC_CheckEnemyExt(qfalse) == qfalse) { Sentry_Idle(); return; } // Rate our distance to the target and visibilty - distance = (int) DistanceHorizontalSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - visible = NPC_ClearLOS4( NPCS.NPC->enemy ); - advance = (qboolean)(distance > MIN_DISTANCE_SQR); + distance = (int)DistanceHorizontalSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + visible = NPC_ClearLOS4(NPCS.NPC->enemy); + advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it - if ( visible == qfalse ) - { - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { - Sentry_Hunt( visible, advance ); + if (visible == qfalse) { + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { + Sentry_Hunt(visible, advance); return; } } - NPC_FaceEnemy( qtrue ); + NPC_FaceEnemy(qtrue); - Sentry_RangedAttack( visible, advance ); + Sentry_RangedAttack(visible, advance); } -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); /* ------------------------- NPC_Sentry_Patrol ------------------------- */ -void NPC_Sentry_Patrol( void ) -{ +void NPC_Sentry_Patrol(void) { Sentry_MaintainHeight(); - //If we have somewhere to go, then do that - if (!NPCS.NPC->enemy) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + // If we have somewhere to go, then do that + if (!NPCS.NPC->enemy) { + if (NPC_CheckPlayerTeamStealth()) { + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( UpdateGoal() ) - { - //start loop sound once we move + if (UpdateGoal()) { + // start loop sound once we move NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - //randomly talk - if (TIMER_Done(NPCS.NPC,"patrolNoise")) - { - G_SoundOnEnt( NPCS.NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3)) ); + // randomly talk + if (TIMER_Done(NPCS.NPC, "patrolNoise")) { + G_SoundOnEnt(NPCS.NPC, CHAN_AUTO, va("sound/chars/sentry/misc/talk%d", Q_irand(1, 3))); - TIMER_Set( NPCS.NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "patrolNoise", Q_irand(2000, 4000)); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -572,24 +498,17 @@ void NPC_Sentry_Patrol( void ) NPC_BSSentry_Default ------------------------- */ -void NPC_BSSentry_Default( void ) -{ - if ( NPCS.NPC->targetname ) - { +void NPC_BSSentry_Default(void) { + if (NPCS.NPC->targetname) { NPCS.NPC->use = sentry_use; } - if (( NPCS.NPC->enemy ) && (NPCS.NPCInfo->localState != LSTATE_WAKEUP)) - { + if ((NPCS.NPC->enemy) && (NPCS.NPCInfo->localState != LSTATE_WAKEUP)) { // Don't attack if waking up or if no enemy Sentry_AttackDecision(); - } - else if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { NPC_Sentry_Patrol(); - } - else - { + } else { Sentry_Idle(); } } diff --git a/codemp/game/NPC_AI_Sniper.c b/codemp/game/NPC_AI_Sniper.c index 1701a65056..e3e4389114 100644 --- a/codemp/game/NPC_AI_Sniper.c +++ b/codemp/game/NPC_AI_Sniper.c @@ -24,98 +24,91 @@ along with this program; if not, see . #include "g_nav.h" #include "anims.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern qboolean FlyingCreature( gentity_t *ent ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern qboolean FlyingCreature(gentity_t *ent); -#define SPF_NO_HIDE 2 +#define SPF_NO_HIDE 2 -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 -#define DISTANCE_SCALE 0.25f -#define DISTANCE_THRESHOLD 0.075f -#define SPEED_SCALE 0.25f -#define FOV_SCALE 0.5f -#define LIGHT_SCALE 0.25f +#define DISTANCE_SCALE 0.25f +#define DISTANCE_THRESHOLD 0.075f +#define SPEED_SCALE 0.25f +#define FOV_SCALE 0.5f +#define LIGHT_SCALE 0.25f -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) -qboolean NPC_CheckPlayerTeamStealth( void ); +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS2; static qboolean enemyCS2; static qboolean faceEnemy2; static qboolean move2; static qboolean shoot2; -static float enemyDist2; +static float enemyDist2; -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void Sniper_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); +void Sniper_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); } -void NPC_Sniper_PlayConfusionSound( gentity_t *self ) -{//FIXME: make this a custom sound in sound set - if ( self->health > 0 ) - { - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); +void NPC_Sniper_PlayConfusionSound(gentity_t *self) { // FIXME: make this a custom sound in sound set + if (self->health > 0) { + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); - TIMER_Set( self, "flee", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); + TIMER_Set(self, "flee", 0); self->NPC->squadState = SQUAD_IDLE; self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } - /* ------------------------- NPC_ST_Pain ------------------------- */ -void NPC_Sniper_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Sniper_Pain(gentity_t *self, gentity_t *attacker, int damage) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -125,9 +118,8 @@ ST_HoldPosition ------------------------- */ -static void Sniper_HoldPosition( void ) -{ - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qtrue ); +static void Sniper_HoldPosition(void) { + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qtrue); NPCS.NPCInfo->goalEntity = NULL; /*if ( TIMER_Done( NPC, "stand" ) ) @@ -143,55 +135,49 @@ ST_Move ------------------------- */ -static qboolean Sniper_Move( void ) -{ - qboolean moved; - navInfo_t info; +static qboolean Sniper_Move(void) { + qboolean moved; + navInfo_t info; - NPCS.NPCInfo->combatMove = qtrue;//always move straight toward our goal + NPCS.NPCInfo->combatMove = qtrue; // always move straight toward our goal - moved = NPC_MoveToGoal( qtrue ); + moved = NPC_MoveToGoal(qtrue); - //Get the move info - NAV_GetLastMove( &info ); + // Get the move info + NAV_GetLastMove(&info); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPCS.NPC->enemy ) - { + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPCS.NPC->enemy) { Sniper_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//couldn't get to enemy - if ( (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); + // If our move failed, then reset + if (moved == qfalse) { // couldn't get to enemy + if ((NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && NPCS.NPCInfo->goalEntity && + NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); int cp; - if ( NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1 ); - if ( cp == -1 && !(NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32, -1 ); + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1); + if (cp == -1 && !(NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, + CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32, -1); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL); return moved; } } - //just hang here + // just hang here Sniper_HoldPosition(); } @@ -204,80 +190,64 @@ NPC_BSSniper_Patrol ------------------------- */ -void NPC_BSSniper_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? +void NPC_BSSniper_Patrol(void) { // FIXME: pick up on bodies of dead buddies? NPCS.NPC->count = 0; - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCS.NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//Should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - //Is there danger nearby - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS ); - if ( NPC_CheckForDanger( alertEvent ) ) - { - NPC_UpdateAngles( qtrue, qtrue ); + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + // Is there danger nearby + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_SUSPICIOUS); + if (NPC_CheckForDanger(alertEvent)) { + NPC_UpdateAngles(qtrue, qtrue); return; - } - else - {//check for other alert events - //There is an event to look at - if ( alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID ) - { + } else { // check for other alert events + // There is an event to look at + if (alertEvent >= 0 && level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID) { NPCS.NPCInfo->lastAlertID = level.alertEvents[alertEvent].ID; - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED ) - { - if ( level.alertEvents[alertEvent].owner && - level.alertEvents[alertEvent].owner->client && + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED) { + if (level.alertEvents[alertEvent].owner && level.alertEvents[alertEvent].owner->client && level.alertEvents[alertEvent].owner->health >= 0 && - level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam ) - {//an enemy - G_SetEnemy( NPCS.NPC, level.alertEvents[alertEvent].owner ); - //NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( (6-NPCS.NPCInfo->stats.aim)*100, (6-NPCS.NPCInfo->stats.aim)*500 ) ); + level.alertEvents[alertEvent].owner->client->playerTeam == NPCS.NPC->client->enemyTeam) { // an enemy + G_SetEnemy(NPCS.NPC, level.alertEvents[alertEvent].owner); + // NPCInfo->enemyLastSeenTime = level.time; + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand((6 - NPCS.NPCInfo->stats.aim) * 100, (6 - NPCS.NPCInfo->stats.aim) * 500)); } - } - else - {//FIXME: get more suspicious over time? - //Save the position for movement (if necessary) - //FIXME: sound? - VectorCopy( level.alertEvents[alertEvent].position, NPCS.NPCInfo->investigateGoal ); - NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand( 500, 1000 ); - if ( level.alertEvents[alertEvent].level == AEL_SUSPICIOUS ) - {//suspicious looks longer - NPCS.NPCInfo->investigateDebounceTime += Q_irand( 500, 2500 ); + } else { // FIXME: get more suspicious over time? + // Save the position for movement (if necessary) + // FIXME: sound? + VectorCopy(level.alertEvents[alertEvent].position, NPCS.NPCInfo->investigateGoal); + NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand(500, 1000); + if (level.alertEvents[alertEvent].level == AEL_SUSPICIOUS) { // suspicious looks longer + NPCS.NPCInfo->investigateDebounceTime += Q_irand(500, 2500); } } } } - if ( NPCS.NPCInfo->investigateDebounceTime > level.time ) - {//FIXME: walk over to it, maybe? Not if not chase enemies flag - //NOTE: stops walking or doing anything else below - vec3_t dir, angles; - float o_yaw, o_pitch; + if (NPCS.NPCInfo->investigateDebounceTime > level.time) { // FIXME: walk over to it, maybe? Not if not chase enemies flag + // NOTE: stops walking or doing anything else below + vec3_t dir, angles; + float o_yaw, o_pitch; - VectorSubtract( NPCS.NPCInfo->investigateGoal, NPCS.NPC->client->renderInfo.eyePoint, dir ); - vectoangles( dir, angles ); + VectorSubtract(NPCS.NPCInfo->investigateGoal, NPCS.NPC->client->renderInfo.eyePoint, dir); + vectoangles(dir, angles); o_yaw = NPCS.NPCInfo->desiredYaw; o_pitch = NPCS.NPCInfo->desiredPitch; NPCS.NPCInfo->desiredYaw = angles[YAW]; NPCS.NPCInfo->desiredPitch = angles[PITCH]; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPCS.NPCInfo->desiredYaw = o_yaw; NPCS.NPCInfo->desiredPitch = o_pitch; @@ -286,14 +256,13 @@ void NPC_BSSniper_Patrol( void ) } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -327,112 +296,96 @@ ST_CheckMoveState ------------------------- */ -static void Sniper_CheckMoveState( void ) -{ +static void Sniper_CheckMoveState(void) { - //See if we're a scout - if ( !(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) )//NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) + // See if we're a scout + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) // NPCInfo->behaviorState == BS_STAND_AND_SHOOT ) { - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - { + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { move2 = qfalse; return; } } - //See if we're running away - else if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( TIMER_Done( NPCS.NPC, "flee" ) ) - { + // See if we're running away + else if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + if (TIMER_Done(NPCS.NPC, "flee")) { NPCS.NPCInfo->squadState = SQUAD_IDLE; - } - else - { + } else { faceEnemy2 = qfalse; } - } - else if ( NPCS.NPCInfo->squadState == SQUAD_IDLE ) - { - if ( !NPCS.NPCInfo->goalEntity ) - { + } else if (NPCS.NPCInfo->squadState == SQUAD_IDLE) { + if (!NPCS.NPCInfo->goalEntity) { move2 = qfalse; return; } } - //See if we're moving towards a goal, not the enemy - if ( ( NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy ) && ( NPCS.NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, FlyingCreature( NPCS.NPC ) ) || - ( NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS2 && enemyDist2 <= 10000 ) ) - { - // int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCS.NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - TIMER_Set( NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100 ); - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 3000, 7000 ) ); - // newSquadState = SQUAD_COVER; + // See if we're moving towards a goal, not the enemy + if ((NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy) && (NPCS.NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, + FlyingCreature(NPCS.NPC)) || + (NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS2 && enemyDist2 <= 10000)) { + // int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCS.NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + TIMER_Set(NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100); + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(3000, 7000)); + // newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( (6-NPCS.NPCInfo->stats.aim)*50, (6-NPCS.NPCInfo->stats.aim)*100 ) ); //FIXME: Slant for difficulty levels, too? - //don't do something else just yet - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 1000, 4000 ) ); - //stop fleeing - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPCS.NPC, "flee", -level.time ); + // don't attack right away + TIMER_Set(NPCS.NPC, "attackDelay", + Q_irand((6 - NPCS.NPCInfo->stats.aim) * 50, (6 - NPCS.NPCInfo->stats.aim) * 100)); // FIXME: Slant for difficulty levels, too? + // don't do something else just yet + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(1000, 4000)); + // stop fleeing + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPCS.NPC, "flee", -level.time); NPCS.NPCInfo->squadState = SQUAD_IDLE; } return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(4000, 8000)); } } -static void Sniper_ResolveBlockedShot( void ) -{ - if ( TIMER_Done( NPCS.NPC, "duck" ) ) - {//we're not ducking - if ( TIMER_Done( NPCS.NPC, "roamTime" ) ) - {//not roaming - //FIXME: try to find another spot from which to hit the enemy - if ( (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) && (!NPCS.NPCInfo->goalEntity || NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) ) - {//we were running after enemy - //Try to find a combat point that can hit the enemy - int cpFlags = (CP_CLEAR|CP_HAS_ROUTE); +static void Sniper_ResolveBlockedShot(void) { + if (TIMER_Done(NPCS.NPC, "duck")) { // we're not ducking + if (TIMER_Done(NPCS.NPC, "roamTime")) { // not roaming + // FIXME: try to find another spot from which to hit the enemy + if ((NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) && + (!NPCS.NPCInfo->goalEntity || NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy)) { // we were running after enemy + // Try to find a combat point that can hit the enemy + int cpFlags = (CP_CLEAR | CP_HAS_ROUTE); int cp; - if ( NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1 ); - if ( cp == -1 && !(NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - {//okay, try one by the enemy - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, CP_CLEAR|CP_HAS_ROUTE|CP_HORZ_DIST_COLL, 32, -1 ); + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, cpFlags, 32, -1); + if (cp == -1 && !(NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { // okay, try one by the enemy + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin, + CP_CLEAR | CP_HAS_ROUTE | CP_HORZ_DIST_COLL, 32, -1); } - //NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... - if ( cp != -1 ) - {//found a combat point that has a clear shot to enemy - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL ); - TIMER_Set( NPCS.NPC, "duck", -1 ); - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 1000, 3000 ) ); + // NOTE: there may be a perfectly valid one, just not one within CP_COLLECT_RADIUS of either me or him... + if (cp != -1) { // found a combat point that has a clear shot to enemy + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL); + TIMER_Set(NPCS.NPC, "duck", -1); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(1000, 3000)); return; } } @@ -462,185 +415,148 @@ ST_CheckFireState ------------------------- */ -static void Sniper_CheckFireState( void ) -{ - if ( enemyCS2 ) - {//if have a clear shot, always try +static void Sniper_CheckFireState(void) { + if (enemyCS2) { // if have a clear shot, always try return; } - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || NPCS.NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || + NPCS.NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPCS.NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPCS.NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //continue to fire on their last position - if ( !Q_irand( 0, 1 ) && NPCS.NPCInfo->enemyLastSeenTime && level.time - NPCS.NPCInfo->enemyLastSeenTime < ((5-NPCS.NPCInfo->stats.aim)*1000) )//FIXME: incorporate skill too? + // continue to fire on their last position + if (!Q_irand(0, 1) && NPCS.NPCInfo->enemyLastSeenTime && + level.time - NPCS.NPCInfo->enemyLastSeenTime < ((5 - NPCS.NPCInfo->stats.aim) * 1000)) // FIXME: incorporate skill too? { - if ( !VectorCompare( vec3_origin, NPCS.NPCInfo->enemyLastSeenLocation ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!VectorCompare(vec3_origin, NPCS.NPCInfo->enemyLastSeenLocation)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); - VectorSubtract( NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); + VectorSubtract(NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir); - VectorNormalize( dir ); + VectorNormalize(dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); - NPCS.NPCInfo->desiredYaw = angles[YAW]; - NPCS.NPCInfo->desiredPitch = angles[PITCH]; + NPCS.NPCInfo->desiredYaw = angles[YAW]; + NPCS.NPCInfo->desiredPitch = angles[PITCH]; shoot2 = qtrue; - //faceEnemy2 = qfalse; + // faceEnemy2 = qfalse; } return; - } - else if ( level.time - NPCS.NPCInfo->enemyLastSeenTime > 10000 ) - {//next time we see him, we'll miss few times first + } else if (level.time - NPCS.NPCInfo->enemyLastSeenTime > 10000) { // next time we see him, we'll miss few times first NPCS.NPC->count = 0; } } -qboolean Sniper_EvaluateShot( int hit ) -{ +qboolean Sniper_EvaluateShot(int hit) { gentity_t *hitEnt; - if ( !NPCS.NPC->enemy ) - { + if (!NPCS.NPC->enemy) { return qfalse; } hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->r.svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPCS.NPC->s.weapon == WP_EMPLACED_GUN) ) - || ( hitEnt && (hitEnt->r.svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && ((hitEnt->r.svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || NPCS.NPC->s.weapon == WP_EMPLACED_GUN)) || + (hitEnt && (hitEnt->r.svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; } -void Sniper_FaceEnemy( void ) -{ - //FIXME: the ones behind kill holes are facing some arbitrary direction and not firing - //FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? - //FIXME: need to give designers option to make them not miss first few shots - if ( NPCS.NPC->enemy ) - { - vec3_t muzzle, target, angles, forward, right, up; - //Get the positions - AngleVectors( NPCS.NPC->client->ps.viewangles, forward, right, up ); - CalcMuzzlePoint( NPCS.NPC, forward, right, up, muzzle ); - //CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); - CalcEntitySpot( NPCS.NPC->enemy, SPOT_ORIGIN, target ); - - if ( enemyDist2 > 65536 && NPCS.NPCInfo->stats.aim < 5 )//is 256 squared, was 16384 (128*128) +void Sniper_FaceEnemy(void) { + // FIXME: the ones behind kill holes are facing some arbitrary direction and not firing + // FIXME: If actually trying to hit enemy, don't fire unless enemy is at least in front of me? + // FIXME: need to give designers option to make them not miss first few shots + if (NPCS.NPC->enemy) { + vec3_t muzzle, target, angles, forward, right, up; + // Get the positions + AngleVectors(NPCS.NPC->client->ps.viewangles, forward, right, up); + CalcMuzzlePoint(NPCS.NPC, forward, right, up, muzzle); + // CalcEntitySpot( NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_ORIGIN, target); + + if (enemyDist2 > 65536 && NPCS.NPCInfo->stats.aim < 5) // is 256 squared, was 16384 (128*128) { - if ( NPCS.NPC->count < (5-NPCS.NPCInfo->stats.aim) ) - {//miss a few times first - if ( shoot2 && TIMER_Done( NPCS.NPC, "attackDelay" ) && level.time >= NPCS.NPCInfo->shotTime ) - {//ready to fire again - qboolean aimError = qfalse; - qboolean hit = qtrue; - int tryMissCount = 0; - trace_t trace; - - GetAnglesForDirection( muzzle, target, angles ); - AngleVectors( angles, forward, right, up ); - - while ( hit && tryMissCount < 10 ) - { + if (NPCS.NPC->count < (5 - NPCS.NPCInfo->stats.aim)) { // miss a few times first + if (shoot2 && TIMER_Done(NPCS.NPC, "attackDelay") && level.time >= NPCS.NPCInfo->shotTime) { // ready to fire again + qboolean aimError = qfalse; + qboolean hit = qtrue; + int tryMissCount = 0; + trace_t trace; + + GetAnglesForDirection(muzzle, target, angles); + AngleVectors(angles, forward, right, up); + + while (hit && tryMissCount < 10) { tryMissCount++; - if ( !Q_irand( 0, 1 ) ) - { + if (!Q_irand(0, 1)) { aimError = qtrue; - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPCS.NPC->enemy->r.maxs[2]*flrand(1.5, 4), right, target ); - } - else - { - VectorMA( target, NPCS.NPC->enemy->r.mins[2]*flrand(1.5, 4), right, target ); + if (!Q_irand(0, 1)) { + VectorMA(target, NPCS.NPC->enemy->r.maxs[2] * flrand(1.5, 4), right, target); + } else { + VectorMA(target, NPCS.NPC->enemy->r.mins[2] * flrand(1.5, 4), right, target); } } - if ( !aimError || !Q_irand( 0, 1 ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - VectorMA( target, NPCS.NPC->enemy->r.maxs[2]*flrand(1.5, 4), up, target ); - } - else - { - VectorMA( target, NPCS.NPC->enemy->r.mins[2]*flrand(1.5, 4), up, target ); + if (!aimError || !Q_irand(0, 1)) { + if (!Q_irand(0, 1)) { + VectorMA(target, NPCS.NPC->enemy->r.maxs[2] * flrand(1.5, 4), up, target); + } else { + VectorMA(target, NPCS.NPC->enemy->r.mins[2] * flrand(1.5, 4), up, target); } } - trap->Trace( &trace, muzzle, vec3_origin, vec3_origin, target, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - hit = Sniper_EvaluateShot( trace.entityNum ); + trap->Trace(&trace, muzzle, vec3_origin, vec3_origin, target, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + hit = Sniper_EvaluateShot(trace.entityNum); } NPCS.NPC->count++; - } - else - { - if ( !enemyLOS2 ) - { - NPC_UpdateAngles( qtrue, qtrue ); + } else { + if (!enemyLOS2) { + NPC_UpdateAngles(qtrue, qtrue); return; } } - } - else - {//based on distance, aim value, difficulty and enemy movement, miss - //FIXME: incorporate distance as a factor? - int missFactor = 8-(NPCS.NPCInfo->stats.aim+g_npcspskill.integer) * 3; - if ( missFactor > ENEMY_POS_LAG_STEPS ) - { + } else { // based on distance, aim value, difficulty and enemy movement, miss + // FIXME: incorporate distance as a factor? + int missFactor = 8 - (NPCS.NPCInfo->stats.aim + g_npcspskill.integer) * 3; + if (missFactor > ENEMY_POS_LAG_STEPS) { missFactor = ENEMY_POS_LAG_STEPS; + } else if (missFactor < 0) { //??? + missFactor = 0; } - else if ( missFactor < 0 ) - {//??? - missFactor = 0 ; - } - VectorCopy( NPCS.NPCInfo->enemyLaggedPos[missFactor], target ); + VectorCopy(NPCS.NPCInfo->enemyLaggedPos[missFactor], target); } - GetAnglesForDirection( muzzle, target, angles ); - } - else - { - target[2] += flrand( 0, NPCS.NPC->enemy->r.maxs[2] ); - //CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); - GetAnglesForDirection( muzzle, target, angles ); + GetAnglesForDirection(muzzle, target, angles); + } else { + target[2] += flrand(0, NPCS.NPC->enemy->r.maxs[2]); + // CalcEntitySpot( NPC->enemy, SPOT_HEAD_LEAN, target ); + GetAnglesForDirection(muzzle, target, angles); } - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCS.NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCS.NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void Sniper_UpdateEnemyPos( void ) -{ +void Sniper_UpdateEnemyPos(void) { int index; int i; - for ( i = MAX_ENEMY_POS_LAG-ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL ) - { - index = i/ENEMY_POS_LAG_INTERVAL; - if ( !index ) - { - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD_LEAN, NPCS.NPCInfo->enemyLaggedPos[index] ); - NPCS.NPCInfo->enemyLaggedPos[index][2] -= flrand( 2, 16 ); - } - else - { - VectorCopy( NPCS.NPCInfo->enemyLaggedPos[index-1], NPCS.NPCInfo->enemyLaggedPos[index] ); + for (i = MAX_ENEMY_POS_LAG - ENEMY_POS_LAG_INTERVAL; i >= 0; i -= ENEMY_POS_LAG_INTERVAL) { + index = i / ENEMY_POS_LAG_INTERVAL; + if (!index) { + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD_LEAN, NPCS.NPCInfo->enemyLaggedPos[index]); + NPCS.NPCInfo->enemyLaggedPos[index][2] -= flrand(2, 16); + } else { + VectorCopy(NPCS.NPCInfo->enemyLaggedPos[index - 1], NPCS.NPCInfo->enemyLaggedPos[index]); } } } @@ -651,42 +567,37 @@ NPC_BSSniper_Attack ------------------------- */ -void Sniper_StartHide( void ) -{ - int duckTime = Q_irand( 2000, 5000 ); +void Sniper_StartHide(void) { + int duckTime = Q_irand(2000, 5000); - TIMER_Set( NPCS.NPC, "duck", duckTime ); - TIMER_Set( NPCS.NPC, "watch", 500 ); - TIMER_Set( NPCS.NPC, "attackDelay", duckTime + Q_irand( 500, 2000 ) ); + TIMER_Set(NPCS.NPC, "duck", duckTime); + TIMER_Set(NPCS.NPC, "watch", 500); + TIMER_Set(NPCS.NPC, "attackDelay", duckTime + Q_irand(500, 2000)); } -void NPC_BSSniper_Attack( void ) -{ - //Don't do anything if we're hurt - if ( NPCS.NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); +void NPC_BSSniper_Attack(void) { + // Don't do anything if we're hurt + if (NPCS.NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt(qfalse) == qfalse) //! NPC->enemy )// { NPCS.NPC->enemy = NULL; - NPC_BSSniper_Patrol();//FIXME: or patrol? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } - if ( TIMER_Done( NPCS.NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - NPC_UpdateAngles( qtrue, qtrue ); + if (TIMER_Done(NPCS.NPC, "flee") && NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPCS.NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSSniper_Patrol();//FIXME: or patrol? + if (!NPCS.NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSSniper_Patrol(); // FIXME: or patrol? return; } @@ -694,67 +605,60 @@ void NPC_BSSniper_Attack( void ) move2 = qtrue; faceEnemy2 = qfalse; shoot2 = qfalse; - enemyDist2 = DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - if ( enemyDist2 < 16384 )//128 squared - {//too close, so switch to primary fire - if ( NPCS.NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE ) - {//use primary fire - trace_t trace; - trap->Trace ( &trace, NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->enemy->r.mins, NPCS.NPC->enemy->r.maxs, NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->s.number, NPCS.NPC->enemy->clipmask, qfalse, 0, 0 ); - if ( !trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPCS.NPC->s.number ) ) - {//he can get right to me + enemyDist2 = DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + if (enemyDist2 < 16384) // 128 squared + { // too close, so switch to primary fire + if (NPCS.NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { // use primary fire + trace_t trace; + trap->Trace(&trace, NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->enemy->r.mins, NPCS.NPC->enemy->r.maxs, NPCS.NPC->r.currentOrigin, + NPCS.NPC->enemy->s.number, NPCS.NPC->enemy->clipmask, qfalse, 0, 0); + if (!trace.allsolid && !trace.startsolid && (trace.fraction == 1.0 || trace.entityNum == NPCS.NPC->s.number)) { // he can get right to me NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //FIXME: switch back if he gets far away again? + // FIXME: switch back if he gets far away again? } - } - else if ( enemyDist2 > 65536 )//256 squared + } else if (enemyDist2 > 65536) // 256 squared { - if ( NPCS.NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( !(NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPCS.NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (!(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } } Sniper_UpdateEnemyPos(); - //can we see our target? - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) )//|| (NPCInfo->stats.aim >= 5 && trap->inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) + // can we see our target? + if (NPC_ClearLOS4(NPCS.NPC->enemy)) //|| (NPCInfo->stats.aim >= 5 && trap->inPVS( NPC->client->renderInfo.eyePoint, NPC->enemy->currentOrigin )) ) { float maxShootDist; NPCS.NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); enemyLOS2 = qtrue; maxShootDist = NPC_MaxDistSquaredForWeapon(); - if ( enemyDist2 < maxShootDist ) - { + if (enemyDist2 < maxShootDist) { vec3_t fwd, right, up, muzzle, end; - trace_t tr; + trace_t tr; int hit; - AngleVectors( NPCS.NPC->client->ps.viewangles, fwd, right, up ); - CalcMuzzlePoint( NPCS.NPC, fwd, right, up, muzzle ); - VectorMA( muzzle, 8192, fwd, end ); - trap->Trace ( &tr, muzzle, NULL, NULL, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + AngleVectors(NPCS.NPC->client->ps.viewangles, fwd, right, up); + CalcMuzzlePoint(NPCS.NPC, fwd, right, up, muzzle); + VectorMA(muzzle, 8192, fwd, end); + trap->Trace(&tr, muzzle, NULL, NULL, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); hit = tr.entityNum; - //can we shoot our target? - if ( Sniper_EvaluateShot( hit ) ) - { + // can we shoot our target? + if (Sniper_EvaluateShot(hit)) { enemyCS2 = qtrue; } } @@ -767,121 +671,92 @@ void NPC_BSSniper_Attack( void ) } */ - if ( enemyLOS2 ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS2) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy2 = qtrue; } - if ( enemyCS2 ) - { + if (enemyCS2) { shoot2 = qtrue; - } - else if ( level.time - NPCS.NPCInfo->enemyLastSeenTime > 3000 ) - {//Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds up when ducked seems to make them want to run when they uncrouch + } else if (level.time - NPCS.NPCInfo->enemyLastSeenTime > 3000) { // Hmm, have to get around this bastard... FIXME: this NPCInfo->enemyLastSeenTime builds + // up when ducked seems to make them want to run when they uncrouch Sniper_ResolveBlockedShot(); } - //Check for movement to take care of + // Check for movement to take care of Sniper_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations Sniper_CheckFireState(); - if ( move2 ) - {//move toward goal - if ( NPCS.NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist2 > 10000 ) )//100 squared + if (move2) { // move toward goal + if (NPCS.NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist2 > 10000 ) )//100 squared { move2 = Sniper_Move(); - } - else - { + } else { move2 = qfalse; } } - if ( !move2 ) - { - if ( !TIMER_Done( NPCS.NPC, "duck" ) ) - { - if ( TIMER_Done( NPCS.NPC, "watch" ) ) - {//not while watching + if (!move2) { + if (!TIMER_Done(NPCS.NPC, "duck")) { + if (TIMER_Done(NPCS.NPC, "watch")) { // not while watching NPCS.ucmd.upmove = -127; } } - //FIXME: what about leaning? - //FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again - } - else - {//stop ducking! - TIMER_Set( NPCS.NPC, "duck", -1 ); + // FIXME: what about leaning? + // FIXME: also, when stop ducking, start looking, if enemy can see me, chance of ducking back down again + } else { // stop ducking! + TIMER_Set(NPCS.NPC, "duck", -1); } - if ( TIMER_Done( NPCS.NPC, "duck" ) - && TIMER_Done( NPCS.NPC, "watch" ) - && (TIMER_Get( NPCS.NPC, "attackDelay" )-level.time) > 1000 - && NPCS.NPC->attackDebounceTime < level.time ) - { - if ( enemyLOS2 && (NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - { - if ( NPCS.NPC->fly_sound_debounce_time < level.time ) - { + if (TIMER_Done(NPCS.NPC, "duck") && TIMER_Done(NPCS.NPC, "watch") && (TIMER_Get(NPCS.NPC, "attackDelay") - level.time) > 1000 && + NPCS.NPC->attackDebounceTime < level.time) { + if (enemyLOS2 && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { + if (NPCS.NPC->fly_sound_debounce_time < level.time) { NPCS.NPC->fly_sound_debounce_time = level.time + 2000; } } } - if ( !faceEnemy2 ) - {//we want to face in the dir we're running - if ( move2 ) - {//don't run away and shoot + if (!faceEnemy2) { // we want to face in the dir we're running + if (move2) { // don't run away and shoot NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lastPathAngles[YAW]; NPCS.NPCInfo->desiredPitch = 0; shoot2 = qfalse; } - NPC_UpdateAngles( qtrue, qtrue ); - } - else// if ( faceEnemy2 ) - {//face the enemy + NPC_UpdateAngles(qtrue, qtrue); + } else // if ( faceEnemy2 ) + { // face the enemy Sniper_FaceEnemy(); } - if ( NPCS.NPCInfo->scriptFlags&SCF_DONT_FIRE ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot2 = qfalse; } - //FIXME: don't shoot right away! - if ( shoot2 ) - {//try to shoot if it's time - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - WeaponThink( qtrue ); - if ( NPCS.ucmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK) ) - { - G_SoundOnEnt( NPCS.NPC, CHAN_WEAPON, "sound/null.wav" ); + // FIXME: don't shoot right away! + if (shoot2) { // try to shoot if it's time + if (TIMER_Done(NPCS.NPC, "attackDelay")) { + WeaponThink(qtrue); + if (NPCS.ucmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) { + G_SoundOnEnt(NPCS.NPC, CHAN_WEAPON, "sound/null.wav"); } - //took a shot, now hide - if ( !(NPCS.NPC->spawnflags&SPF_NO_HIDE) && !Q_irand( 0, 1 ) ) - { - //FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover + // took a shot, now hide + if (!(NPCS.NPC->spawnflags & SPF_NO_HIDE) && !Q_irand(0, 1)) { + // FIXME: do this if in combat point and combat point has duck-type cover... also handle lean-type cover Sniper_StartHide(); - } - else - { - TIMER_Set( NPCS.NPC, "attackDelay", NPCS.NPCInfo->shotTime-level.time ); + } else { + TIMER_Set(NPCS.NPC, "attackDelay", NPCS.NPCInfo->shotTime - level.time); } } } } -void NPC_BSSniper_Default( void ) -{ - if( !NPCS.NPC->enemy ) - {//don't have an enemy, look for one +void NPC_BSSniper_Default(void) { + if (!NPCS.NPC->enemy) { // don't have an enemy, look for one NPC_BSSniper_Patrol(); - } - else//if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_BSSniper_Attack(); } } diff --git a/codemp/game/NPC_AI_Stormtrooper.c b/codemp/game/NPC_AI_Stormtrooper.c index 131077e28e..23b2e694fe 100644 --- a/codemp/game/NPC_AI_Stormtrooper.c +++ b/codemp/game/NPC_AI_Stormtrooper.c @@ -24,38 +24,38 @@ along with this program; if not, see . #include "g_nav.h" #include "anims.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ); -extern qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ); -extern void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ); -extern void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ); -extern void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); -extern qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -extern void NPC_CheckGetNewWeapon( void ); -extern int GetTime ( int lastTime ); -extern void NPC_AimAdjust( int change ); -extern qboolean FlyingCreature( gentity_t *ent ); - -#define MAX_VIEW_DIST 1024 -#define MAX_VIEW_SPEED 250 -#define MAX_LIGHT_INTENSITY 255 -#define MIN_LIGHT_THRESHOLD 0.1 -#define ST_MIN_LIGHT_THRESHOLD 30 -#define ST_MAX_LIGHT_THRESHOLD 180 -#define DISTANCE_THRESHOLD 0.075f - -#define DISTANCE_SCALE 0.35f //These first three get your base detection rating, ideally add up to 1 -#define FOV_SCALE 0.40f // -#define LIGHT_SCALE 0.25f // - -#define SPEED_SCALE 0.25f //These next two are bonuses -#define TURNING_SCALE 0.25f // - -#define REALIZE_THRESHOLD 0.6f -#define CAUTIOUS_THRESHOLD ( REALIZE_THRESHOLD * 0.75 ) - -qboolean NPC_CheckPlayerTeamStealth( void ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState); +extern qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum); +extern void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot); +extern void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group); +extern void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime); +extern qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern void NPC_CheckGetNewWeapon(void); +extern int GetTime(int lastTime); +extern void NPC_AimAdjust(int change); +extern qboolean FlyingCreature(gentity_t *ent); + +#define MAX_VIEW_DIST 1024 +#define MAX_VIEW_SPEED 250 +#define MAX_LIGHT_INTENSITY 255 +#define MIN_LIGHT_THRESHOLD 0.1 +#define ST_MIN_LIGHT_THRESHOLD 30 +#define ST_MAX_LIGHT_THRESHOLD 180 +#define DISTANCE_THRESHOLD 0.075f + +#define DISTANCE_SCALE 0.35f // These first three get your base detection rating, ideally add up to 1 +#define FOV_SCALE 0.40f // +#define LIGHT_SCALE 0.25f // + +#define SPEED_SCALE 0.25f // These next two are bonuses +#define TURNING_SCALE 0.25f // + +#define REALIZE_THRESHOLD 0.6f +#define CAUTIOUS_THRESHOLD (REALIZE_THRESHOLD * 0.75) + +qboolean NPC_CheckPlayerTeamStealth(void); static qboolean enemyLOS; static qboolean enemyCS; @@ -64,67 +64,57 @@ static qboolean hitAlly; static qboolean faceEnemy; static qboolean move; static qboolean shoot; -static float enemyDist; -static vec3_t impactPos; +static float enemyDist; +static vec3_t impactPos; -int groupSpeechDebounceTime[TEAM_NUM_TEAMS];//used to stop several group AI from speaking all at once +int groupSpeechDebounceTime[TEAM_NUM_TEAMS]; // used to stop several group AI from speaking all at once -//Local state enums -enum -{ +// Local state enums +enum { LSTATE_NONE = 0, LSTATE_UNDERFIRE, LSTATE_INVESTIGATE, }; -void ST_AggressionAdjust( gentity_t *self, int change ) -{ - int upper_threshold, lower_threshold; +void ST_AggressionAdjust(gentity_t *self, int change) { + int upper_threshold, lower_threshold; self->NPC->stats.aggression += change; - //FIXME: base this on initial NPC stats - if ( self->client->playerTeam == NPCTEAM_PLAYER ) - {//good guys are less aggressive + // FIXME: base this on initial NPC stats + if (self->client->playerTeam == NPCTEAM_PLAYER) { // good guys are less aggressive upper_threshold = 7; lower_threshold = 1; - } - else - {//bad guys are more aggressive + } else { // bad guys are more aggressive upper_threshold = 10; lower_threshold = 3; } - if ( self->NPC->stats.aggression > upper_threshold ) - { + if (self->NPC->stats.aggression > upper_threshold) { self->NPC->stats.aggression = upper_threshold; - } - else if ( self->NPC->stats.aggression < lower_threshold ) - { + } else if (self->NPC->stats.aggression < lower_threshold) { self->NPC->stats.aggression = lower_threshold; } } -void ST_ClearTimers( gentity_t *ent ) -{ - TIMER_Set( ent, "chatter", 0 ); - TIMER_Set( ent, "duck", 0 ); - TIMER_Set( ent, "stand", 0 ); - TIMER_Set( ent, "shuffleTime", 0 ); - TIMER_Set( ent, "sleepTime", 0 ); - TIMER_Set( ent, "enemyLastVisible", 0 ); - TIMER_Set( ent, "roamTime", 0 ); - TIMER_Set( ent, "hideTime", 0 ); - TIMER_Set( ent, "attackDelay", 0 ); //FIXME: Slant for difficulty levels - TIMER_Set( ent, "stick", 0 ); - TIMER_Set( ent, "scoutTime", 0 ); - TIMER_Set( ent, "flee", 0 ); - TIMER_Set( ent, "interrogating", 0 ); - TIMER_Set( ent, "verifyCP", 0 ); +void ST_ClearTimers(gentity_t *ent) { + TIMER_Set(ent, "chatter", 0); + TIMER_Set(ent, "duck", 0); + TIMER_Set(ent, "stand", 0); + TIMER_Set(ent, "shuffleTime", 0); + TIMER_Set(ent, "sleepTime", 0); + TIMER_Set(ent, "enemyLastVisible", 0); + TIMER_Set(ent, "roamTime", 0); + TIMER_Set(ent, "hideTime", 0); + TIMER_Set(ent, "attackDelay", 0); // FIXME: Slant for difficulty levels + TIMER_Set(ent, "stick", 0); + TIMER_Set(ent, "scoutTime", 0); + TIMER_Set(ent, "flee", 0); + TIMER_Set(ent, "interrogating", 0); + TIMER_Set(ent, "verifyCP", 0); } -enum -{ +enum { SPEECH_CHASE, SPEECH_CONFUSED, SPEECH_COVER, @@ -141,19 +131,14 @@ enum SPEECH_PUSHED }; -static void ST_Speech( gentity_t *self, int speechType, float failChance ) -{ - if ( Q_flrand(0.0f, 1.0f) < failChance ) - { +static void ST_Speech(gentity_t *self, int speechType, float failChance) { + if (Q_flrand(0.0f, 1.0f) < failChance) { return; } - if ( failChance >= 0 ) - {//a negative failChance makes it always talk - if ( self->NPC->group ) - {//group AI speech debounce timer - if ( self->NPC->group->speechDebounceTime > level.time ) - { + if (failChance >= 0) { // a negative failChance makes it always talk + if (self->NPC->group) { // group AI speech debounce timer + if (self->NPC->group->speechDebounceTime > level.time) { return; } /* @@ -165,77 +150,68 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) } } */ - } - else if ( !TIMER_Done( self, "chatter" ) ) - {//personal timer + } else if (!TIMER_Done(self, "chatter")) { // personal timer return; - } - else if ( groupSpeechDebounceTime[self->client->playerTeam] > level.time ) - {//for those not in group AI - //FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? + } else if (groupSpeechDebounceTime[self->client->playerTeam] > level.time) { // for those not in group AI + // FIXME: let certain speech types interrupt others? Let closer NPCs interrupt farther away ones? return; } } - if ( self->NPC->group ) - {//So they don't all speak at once... - //FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! - self->NPC->group->speechDebounceTime = level.time + Q_irand( 2000, 4000 ); + if (self->NPC->group) { // So they don't all speak at once... + // FIXME: if they're not yet mad, they have no group, so distracting a group of them makes them all speak! + self->NPC->group->speechDebounceTime = level.time + Q_irand(2000, 4000); + } else { + TIMER_Set(self, "chatter", Q_irand(2000, 4000)); } - else - { - TIMER_Set( self, "chatter", Q_irand( 2000, 4000 ) ); - } - groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand( 2000, 4000 ); + groupSpeechDebounceTime[self->client->playerTeam] = level.time + Q_irand(2000, 4000); - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - switch( speechType ) - { + switch (speechType) { case SPEECH_CHASE: - G_AddVoiceEvent( self, Q_irand(EV_CHASE1, EV_CHASE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CHASE1, EV_CHASE3), 2000); break; case SPEECH_CONFUSED: - G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); break; case SPEECH_COVER: - G_AddVoiceEvent( self, Q_irand(EV_COVER1, EV_COVER5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_COVER1, EV_COVER5), 2000); break; case SPEECH_DETECTED: - G_AddVoiceEvent( self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_DETECTED1, EV_DETECTED5), 2000); break; case SPEECH_GIVEUP: - G_AddVoiceEvent( self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_GIVEUP1, EV_GIVEUP4), 2000); break; case SPEECH_LOOK: - G_AddVoiceEvent( self, Q_irand(EV_LOOK1, EV_LOOK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_LOOK1, EV_LOOK2), 2000); break; case SPEECH_LOST: - G_AddVoiceEvent( self, EV_LOST1, 2000 ); + G_AddVoiceEvent(self, EV_LOST1, 2000); break; case SPEECH_OUTFLANK: - G_AddVoiceEvent( self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_OUTFLANK1, EV_OUTFLANK2), 2000); break; case SPEECH_ESCAPING: - G_AddVoiceEvent( self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ESCAPING1, EV_ESCAPING3), 2000); break; case SPEECH_SIGHT: - G_AddVoiceEvent( self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SIGHT1, EV_SIGHT3), 2000); break; case SPEECH_SOUND: - G_AddVoiceEvent( self, Q_irand(EV_SOUND1, EV_SOUND3), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SOUND1, EV_SOUND3), 2000); break; case SPEECH_SUSPICIOUS: - G_AddVoiceEvent( self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_SUSPICIOUS1, EV_SUSPICIOUS5), 2000); break; case SPEECH_YELL: - G_AddVoiceEvent( self, Q_irand( EV_ANGER1, EV_ANGER3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_ANGER1, EV_ANGER3), 2000); break; case SPEECH_PUSHED: - G_AddVoiceEvent( self, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 2000 ); + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); break; default: break; @@ -244,31 +220,25 @@ static void ST_Speech( gentity_t *self, int speechType, float failChance ) self->NPC->blockedSpeechDebounceTime = level.time + 2000; } -void ST_MarkToCover( gentity_t *self ) -{ - if ( !self || !self->NPC ) - { +void ST_MarkToCover(gentity_t *self) { + if (!self || !self->NPC) { return; } self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "attackDelay", Q_irand( 500, 2500 ) ); - ST_AggressionAdjust( self, -3 ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + TIMER_Set(self, "attackDelay", Q_irand(500, 2500)); + ST_AggressionAdjust(self, -3); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } -void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ) -{ - if ( !self || !self->NPC ) - { +void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime) { + if (!self || !self->NPC) { return; } - G_StartFlee( self, enemy, dangerPoint, dangerLevel, minTime, maxTime ); - if ( self->NPC->group && self->NPC->group->numGroup > 1 ) - { - ST_Speech( self, SPEECH_COVER, 0 );//FIXME: flee sound? + G_StartFlee(self, enemy, dangerPoint, dangerLevel, minTime, maxTime); + if (self->NPC->group && self->NPC->group->numGroup > 1) { + ST_Speech(self, SPEECH_COVER, 0); // FIXME: flee sound? } } /* @@ -277,19 +247,17 @@ NPC_ST_Pain ------------------------- */ -void NPC_ST_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_ST_Pain(gentity_t *self, gentity_t *attacker, int damage) { self->NPC->localState = LSTATE_UNDERFIRE; - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "hideTime", -1 ); - TIMER_Set( self, "stand", 2000 ); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "hideTime", -1); + TIMER_Set(self, "stand", 2000); - NPC_Pain( self, attacker, damage ); + NPC_Pain(self, attacker, damage); - if ( !damage && self->health > 0 ) - {//FIXME: better way to know I was pushed - G_AddVoiceEvent( self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000 ); + if (!damage && self->health > 0) { // FIXME: better way to know I was pushed + G_AddVoiceEvent(self, Q_irand(EV_PUSHED1, EV_PUSHED3), 2000); } } @@ -299,19 +267,17 @@ ST_HoldPosition ------------------------- */ -static void ST_HoldPosition( void ) -{ +static void ST_HoldPosition(void) { - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - TIMER_Set( NPCS.NPC, "flee", -level.time ); - } - TIMER_Set( NPCS.NPC, "verifyCP", Q_irand( 1000, 3000 ) );//don't look for another one for a few seconds - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qtrue ); - //NPCInfo->combatPoint = -1;//??? - if ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//don't have a script waiting for me to get to my point, okay to stop trying and stand - AI_GroupUpdateSquadstates( NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT ); + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + TIMER_Set(NPCS.NPC, "flee", -level.time); + } + TIMER_Set(NPCS.NPC, "verifyCP", Q_irand(1000, 3000)); // don't look for another one for a few seconds + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qtrue); + // NPCInfo->combatPoint = -1;//??? + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // don't have a script waiting for me to get to my point, okay to stop trying and stand + AI_GroupUpdateSquadstates(NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT); NPCS.NPCInfo->goalEntity = NULL; } @@ -322,32 +288,23 @@ static void ST_HoldPosition( void ) */ } -void NPC_ST_SayMovementSpeech( void ) -{ +void NPC_ST_SayMovementSpeech(void) { - if ( !NPCS.NPCInfo->movementSpeech ) - { + if (!NPCS.NPCInfo->movementSpeech) { return; } - if ( NPCS.NPCInfo->group && - NPCS.NPCInfo->group->commander && - NPCS.NPCInfo->group->commander->client && - NPCS.NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - {//imperial (commander) gives the order - ST_Speech( NPCS.NPCInfo->group->commander, NPCS.NPCInfo->movementSpeech, NPCS.NPCInfo->movementSpeechChance ); - } - else - {//really don't want to say this unless we can actually get there... - ST_Speech( NPCS.NPC, NPCS.NPCInfo->movementSpeech, NPCS.NPCInfo->movementSpeechChance ); + if (NPCS.NPCInfo->group && NPCS.NPCInfo->group->commander && NPCS.NPCInfo->group->commander->client && + NPCS.NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && !Q_irand(0, 3)) { // imperial (commander) gives the order + ST_Speech(NPCS.NPCInfo->group->commander, NPCS.NPCInfo->movementSpeech, NPCS.NPCInfo->movementSpeechChance); + } else { // really don't want to say this unless we can actually get there... + ST_Speech(NPCS.NPC, NPCS.NPCInfo->movementSpeech, NPCS.NPCInfo->movementSpeechChance); } NPCS.NPCInfo->movementSpeech = 0; NPCS.NPCInfo->movementSpeechChance = 0.0f; } -void NPC_ST_StoreMovementSpeech( int speech, float chance ) -{ +void NPC_ST_StoreMovementSpeech(int speech, float chance) { NPCS.NPCInfo->movementSpeech = speech; NPCS.NPCInfo->movementSpeechChance = chance; } @@ -356,44 +313,40 @@ void NPC_ST_StoreMovementSpeech( int speech, float chance ) ST_Move ------------------------- */ -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ); -static qboolean ST_Move( void ) -{ - qboolean moved; - navInfo_t info; +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other); +static qboolean ST_Move(void) { + qboolean moved; + navInfo_t info; - NPCS.NPCInfo->combatMove = qtrue;//always move straight toward our goal + NPCS.NPCInfo->combatMove = qtrue; // always move straight toward our goal - moved = NPC_MoveToGoal( qtrue ); + moved = NPC_MoveToGoal(qtrue); - //Get the move info - NAV_GetLastMove( &info ); + // Get the move info + NAV_GetLastMove(&info); - //FIXME: if we bump into another one of our guys and can't get around him, just stop! - //If we hit our target, then stop and fire! - if ( info.flags & NIF_COLLISION ) - { - if ( info.blocker == NPCS.NPC->enemy ) - { + // FIXME: if we bump into another one of our guys and can't get around him, just stop! + // If we hit our target, then stop and fire! + if (info.flags & NIF_COLLISION) { + if (info.blocker == NPCS.NPC->enemy) { ST_HoldPosition(); } } - //If our move failed, then reset - if ( moved == qfalse ) - {//FIXME: if we're going to a combat point, need to pick a different one - if ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//can't transfer movegoal or stop when a script we're running is waiting to complete - if ( info.blocker && info.blocker->NPC && NPCS.NPCInfo->group != NULL && info.blocker->NPC->group == NPCS.NPCInfo->group )//(NPCInfo->aiFlags&NPCAI_BLOCKED) && NPCInfo->group != NULL ) - {//dammit, something is in our way - //see if it's one of ours + // If our move failed, then reset + if (moved == qfalse) { // FIXME: if we're going to a combat point, need to pick a different one + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // can't transfer movegoal or stop when a script we're running is waiting to complete + if (info.blocker && info.blocker->NPC && NPCS.NPCInfo->group != NULL && + info.blocker->NPC->group == NPCS.NPCInfo->group) //(NPCInfo->aiFlags&NPCAI_BLOCKED) && NPCInfo->group != NULL ) + { // dammit, something is in our way + // see if it's one of ours int j; - for ( j = 0; j < NPCS.NPCInfo->group->numGroup; j++ ) - { - if ( NPCS.NPCInfo->group->member[j].number == NPCS.NPCInfo->blockingEntNum ) - {//we're being blocked by one of our own, pass our goal onto them and I'll stand still - ST_TransferMoveGoal( NPCS.NPC, &g_entities[NPCS.NPCInfo->group->member[j].number] ); + for (j = 0; j < NPCS.NPCInfo->group->numGroup; j++) { + if (NPCS.NPCInfo->group->member[j].number == + NPCS.NPCInfo->blockingEntNum) { // we're being blocked by one of our own, pass our goal onto them and I'll stand still + ST_TransferMoveGoal(NPCS.NPC, &g_entities[NPCS.NPCInfo->group->member[j].number]); break; } } @@ -401,38 +354,32 @@ static qboolean ST_Move( void ) ST_HoldPosition(); } - } - else - { - //First time you successfully move, say what it is you're doing + } else { + // First time you successfully move, say what it is you're doing NPC_ST_SayMovementSpeech(); } return moved; } - /* ------------------------- NPC_ST_SleepShuffle ------------------------- */ -static void NPC_ST_SleepShuffle( void ) -{ - //Play an awake script if we have one - if ( G_ActivateBehavior( NPCS.NPC, BSET_AWAKE) ) - { +static void NPC_ST_SleepShuffle(void) { + // Play an awake script if we have one + if (G_ActivateBehavior(NPCS.NPC, BSET_AWAKE)) { return; } - //Automate some movement and noise - if ( TIMER_Done( NPCS.NPC, "shuffleTime" ) ) - { + // Automate some movement and noise + if (TIMER_Done(NPCS.NPC, "shuffleTime")) { - //TODO: Play sleeping shuffle animation + // TODO: Play sleeping shuffle animation - //int soundIndex = Q_irand( 0, 1 ); + // int soundIndex = Q_irand( 0, 1 ); /* switch ( soundIndex ) @@ -447,16 +394,15 @@ static void NPC_ST_SleepShuffle( void ) } */ - TIMER_Set( NPCS.NPC, "shuffleTime", 4000 ); - TIMER_Set( NPCS.NPC, "sleepTime", 2000 ); + TIMER_Set(NPCS.NPC, "shuffleTime", 4000); + TIMER_Set(NPCS.NPC, "sleepTime", 2000); return; } - //They made another noise while we were stirring, see if we can see them - if ( TIMER_Done( NPCS.NPC, "sleepTime" ) ) - { + // They made another noise while we were stirring, see if we can see them + if (TIMER_Done(NPCS.NPC, "sleepTime")) { NPC_CheckPlayerTeamStealth(); - TIMER_Set( NPCS.NPC, "sleepTime", 2000 ); + TIMER_Set(NPCS.NPC, "sleepTime", 2000); } } @@ -466,43 +412,36 @@ NPC_ST_Sleep ------------------------- */ -void NPC_BSST_Sleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qfalse, qtrue, -1, qfalse, AEL_MINOR );//only check sounds since we're alseep! +void NPC_BSST_Sleep(void) { + int alertEvent = NPC_CheckAlertEvents(qfalse, qtrue, -1, qfalse, AEL_MINOR); // only check sounds since we're alseep! - //There is an event we heard - if ( alertEvent >= 0 ) - { - //See if it was enough to wake us up - if ( level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - int i; - float dist; - float bestDist = 16384.0f; - gentity_t *bestCl = NULL; - gentity_t *ent = NULL; + // There is an event we heard + if (alertEvent >= 0) { + // See if it was enough to wake us up + if (level.alertEvents[alertEvent].level == AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + int i; + float dist; + float bestDist = 16384.0f; + gentity_t *bestCl = NULL; + gentity_t *ent = NULL; - for ( i=0; iinuse && ent->health > 0 && !(ent->client->ps.eFlags & EF_DEAD) && - G_ClearLOS( NPCS.NPC, NPCS.NPC->s.origin, ent->s.origin ) ) - { - if ( ( dist = Distance( NPCS.NPC->s.origin, ent->s.origin ) ) < bestDist ) - { - bestCl = ent; - bestDist = dist; + if (ent->inuse && ent->health > 0 && !(ent->client->ps.eFlags & EF_DEAD) && G_ClearLOS(NPCS.NPC, NPCS.NPC->s.origin, ent->s.origin)) { + if ((dist = Distance(NPCS.NPC->s.origin, ent->s.origin)) < bestDist) { + bestCl = ent; + bestDist = dist; } } } - if ( bestCl ) - { - G_SetEnemy( NPCS.NPC, bestCl ); + if (bestCl) { + G_SetEnemy(NPCS.NPC, bestCl); return; } } - //Otherwise just stir a bit + // Otherwise just stir a bit NPC_ST_SleepShuffle(); return; } @@ -514,170 +453,147 @@ NPC_CheckEnemyStealth ------------------------- */ -qboolean NPC_CheckEnemyStealth( gentity_t *target ) -{ - float target_dist, minDist = 40;//any closer than 40 and we definitely notice - float maxViewDist; - qboolean clearLOS; +qboolean NPC_CheckEnemyStealth(gentity_t *target) { + float target_dist, minDist = 40; // any closer than 40 and we definitely notice + float maxViewDist; + qboolean clearLOS; - //In case we aquired one some other way - if ( NPCS.NPC->enemy != NULL ) + // In case we aquired one some other way + if (NPCS.NPC->enemy != NULL) return qtrue; - //Ignore notarget - if ( target->flags & FL_NOTARGET ) + // Ignore notarget + if (target->flags & FL_NOTARGET) return qfalse; - if ( target->health <= 0 ) - { + if (target->health <= 0) { return qfalse; } - if ( target->client->ps.weapon == WP_SABER && !target->client->ps.saberHolstered && !target->client->ps.saberInFlight ) - {//if target has saber in hand and activated, we wake up even sooner even if not facing him + if (target->client->ps.weapon == WP_SABER && !target->client->ps.saberHolstered && + !target->client->ps.saberInFlight) { // if target has saber in hand and activated, we wake up even sooner even if not facing him minDist = 100; } - target_dist = DistanceSquared( target->r.currentOrigin, NPCS.NPC->r.currentOrigin ); + target_dist = DistanceSquared(target->r.currentOrigin, NPCS.NPC->r.currentOrigin); - //If the target is this close, then wake up regardless - if ( !(target->client->ps.pm_flags&PMF_DUCKED) - && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) - && (target_dist) < (minDist*minDist) ) - { - G_SetEnemy( NPCS.NPC, target ); + // If the target is this close, then wake up regardless + if (!(target->client->ps.pm_flags & PMF_DUCKED) && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) && (target_dist) < (minDist * minDist)) { + G_SetEnemy(NPCS.NPC, target); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - maxViewDist = MAX_VIEW_DIST; + maxViewDist = MAX_VIEW_DIST; - if ( NPCS.NPCInfo->stats.visrange > maxViewDist ) - {//FIXME: should we always just set maxViewDist to this? + if (NPCS.NPCInfo->stats.visrange > maxViewDist) { // FIXME: should we always just set maxViewDist to this? maxViewDist = NPCS.NPCInfo->stats.visrange; } - if ( target_dist > (maxViewDist*maxViewDist) ) - {//out of possible visRange + if (target_dist > (maxViewDist * maxViewDist)) { // out of possible visRange return qfalse; } - //Check FOV first - if ( InFOV( target, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov ) == qfalse ) + // Check FOV first + if (InFOV(target, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov) == qfalse) return qfalse; - //clearLOS = ( target->client->ps.leanofs ) ? NPC_ClearLOS5( target->client->renderInfo.eyePoint ) : NPC_ClearLOS4( target ); - clearLOS = NPC_ClearLOS4( target ); - - //Now check for clear line of vision - if ( clearLOS ) - { - vec3_t targ_org; - int target_crouching; - float hAngle_perc, vAngle_perc, FOV_perc; - float target_speed; - float dist_rating, speed_rating, turning_rating; - float light_level; - float vis_rating, target_rating; - float dist_influence, fov_influence, light_influence; - float realize, cautious; - int contents; - - if ( target->client->NPC_class == CLASS_ATST ) - {//can't miss 'em! - G_SetEnemy( NPCS.NPC, target ); - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // clearLOS = ( target->client->ps.leanofs ) ? NPC_ClearLOS5( target->client->renderInfo.eyePoint ) : NPC_ClearLOS4( target ); + clearLOS = NPC_ClearLOS4(target); + + // Now check for clear line of vision + if (clearLOS) { + vec3_t targ_org; + int target_crouching; + float hAngle_perc, vAngle_perc, FOV_perc; + float target_speed; + float dist_rating, speed_rating, turning_rating; + float light_level; + float vis_rating, target_rating; + float dist_influence, fov_influence, light_influence; + float realize, cautious; + int contents; + + if (target->client->NPC_class == CLASS_ATST) { // can't miss 'em! + G_SetEnemy(NPCS.NPC, target); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - VectorSet(targ_org, target->r.currentOrigin[0],target->r.currentOrigin[1],target->r.currentOrigin[2]+target->r.maxs[2]-4); - hAngle_perc = NPC_GetHFOVPercentage( targ_org, NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->client->renderInfo.eyeAngles, NPCS.NPCInfo->stats.hfov ); - vAngle_perc = NPC_GetVFOVPercentage( targ_org, NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->client->renderInfo.eyeAngles, NPCS.NPCInfo->stats.vfov ); + VectorSet(targ_org, target->r.currentOrigin[0], target->r.currentOrigin[1], target->r.currentOrigin[2] + target->r.maxs[2] - 4); + hAngle_perc = NPC_GetHFOVPercentage(targ_org, NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->client->renderInfo.eyeAngles, NPCS.NPCInfo->stats.hfov); + vAngle_perc = NPC_GetVFOVPercentage(targ_org, NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->client->renderInfo.eyeAngles, NPCS.NPCInfo->stats.vfov); - //Scale them vertically some, and horizontally pretty harshly - vAngle_perc *= vAngle_perc;//( vAngle_perc * vAngle_perc ); - hAngle_perc *= ( hAngle_perc * hAngle_perc ); + // Scale them vertically some, and horizontally pretty harshly + vAngle_perc *= vAngle_perc; //( vAngle_perc * vAngle_perc ); + hAngle_perc *= (hAngle_perc * hAngle_perc); - //Cap our vertical vision severely - //if ( vAngle_perc <= 0.3f ) // was 0.5f + // Cap our vertical vision severely + // if ( vAngle_perc <= 0.3f ) // was 0.5f // return qfalse; - //Assess the player's current status - target_dist = Distance( target->r.currentOrigin, NPCS.NPC->r.currentOrigin ); - - target_speed = VectorLength( target->client->ps.velocity ); - target_crouching = ( target->client->pers.cmd.upmove < 0 ); - dist_rating = ( target_dist / maxViewDist ); - speed_rating = ( target_speed / MAX_VIEW_SPEED ); - turning_rating = 5.0f;//AngleDelta( target->client->ps.viewangles[PITCH], target->lastAngles[PITCH] )/180.0f + AngleDelta( target->client->ps.viewangles[YAW], target->lastAngles[YAW] )/180.0f; - light_level = (255/MAX_LIGHT_INTENSITY); //( target->lightLevel / MAX_LIGHT_INTENSITY ); - FOV_perc = 1.0f - ( hAngle_perc + vAngle_perc ) * 0.5f; //FIXME: Dunno about the average... - vis_rating = 0.0f; - - //Too dark - if ( light_level < MIN_LIGHT_THRESHOLD ) + // Assess the player's current status + target_dist = Distance(target->r.currentOrigin, NPCS.NPC->r.currentOrigin); + + target_speed = VectorLength(target->client->ps.velocity); + target_crouching = (target->client->pers.cmd.upmove < 0); + dist_rating = (target_dist / maxViewDist); + speed_rating = (target_speed / MAX_VIEW_SPEED); + turning_rating = 5.0f; // AngleDelta( target->client->ps.viewangles[PITCH], target->lastAngles[PITCH] )/180.0f + AngleDelta( + // target->client->ps.viewangles[YAW], target->lastAngles[YAW] )/180.0f; + light_level = (255 / MAX_LIGHT_INTENSITY); //( target->lightLevel / MAX_LIGHT_INTENSITY ); + FOV_perc = 1.0f - (hAngle_perc + vAngle_perc) * 0.5f; // FIXME: Dunno about the average... + vis_rating = 0.0f; + + // Too dark + if (light_level < MIN_LIGHT_THRESHOLD) return qfalse; - //Too close? - if ( dist_rating < DISTANCE_THRESHOLD ) - { - G_SetEnemy( NPCS.NPC, target ); - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + // Too close? + if (dist_rating < DISTANCE_THRESHOLD) { + G_SetEnemy(NPCS.NPC, target); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //Out of range - if ( dist_rating > 1.0f ) + // Out of range + if (dist_rating > 1.0f) return qfalse; - //Cap our speed checks - if ( speed_rating > 1.0f ) + // Cap our speed checks + if (speed_rating > 1.0f) speed_rating = 1.0f; - - //Calculate the distance, fov and light influences + // Calculate the distance, fov and light influences //...Visibilty linearly wanes over distance - dist_influence = DISTANCE_SCALE * ( ( 1.0f - dist_rating ) ); + dist_influence = DISTANCE_SCALE * ((1.0f - dist_rating)); //...As the percentage out of the FOV increases, straight perception suffers on an exponential scale - fov_influence = FOV_SCALE * ( 1.0f - FOV_perc ); + fov_influence = FOV_SCALE * (1.0f - FOV_perc); //...Lack of light hides, abundance of light exposes - light_influence = ( light_level - 0.5f ) * LIGHT_SCALE; - - //Calculate our base rating - target_rating = dist_influence + fov_influence + light_influence; - - //Now award any final bonuses to this number - contents = trap->PointContents( targ_org, target->s.number ); - if ( contents&CONTENTS_WATER ) - { - int myContents = trap->PointContents( NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->s.number ); - if ( !(myContents&CONTENTS_WATER) ) - {//I'm not in water - if ( NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//these guys can see in in/through water pretty well - vis_rating = 0.10f;//10% bonus + light_influence = (light_level - 0.5f) * LIGHT_SCALE; + + // Calculate our base rating + target_rating = dist_influence + fov_influence + light_influence; + + // Now award any final bonuses to this number + contents = trap->PointContents(targ_org, target->s.number); + if (contents & CONTENTS_WATER) { + int myContents = trap->PointContents(NPCS.NPC->client->renderInfo.eyePoint, NPCS.NPC->s.number); + if (!(myContents & CONTENTS_WATER)) { // I'm not in water + if (NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // these guys can see in in/through water pretty well + vis_rating = 0.10f; // 10% bonus + } else { + vis_rating = 0.35f; // 35% bonus } - else - { - vis_rating = 0.35f;//35% bonus - } - } - else - {//else, if we're both in water - if ( NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//I can see him just fine - } - else - { - vis_rating = 0.15f;//15% bonus + } else { // else, if we're both in water + if (NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // I can see him just fine + } else { + vis_rating = 0.15f; // 15% bonus } } - } - else - {//not in water - if ( contents&CONTENTS_FOG ) - { - vis_rating = 0.15f;//15% bonus + } else { // not in water + if (contents & CONTENTS_FOG) { + vis_rating = 0.15f; // 15% bonus } } @@ -686,67 +602,57 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) //...Motion draws the eye quickly target_rating += speed_rating * SPEED_SCALE; target_rating += turning_rating * TURNING_SCALE; - //FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? + // FIXME: check to see if they're animating, too? But can we do something as simple as frame != oldframe? //...Smaller targets are harder to indentify - if ( target_crouching ) - { - target_rating *= 0.9f; //10% bonus + if (target_crouching) { + target_rating *= 0.9f; // 10% bonus } - //If he's violated the threshold, then realize him - //float difficulty_scale = 1.0f + (2.0f-g_npcspskill.value);//if playing on easy, 20% harder to be seen...? - if ( NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER ) - {//swamptroopers can see much better - realize = (float)CAUTIOUS_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; - } - else - { - realize = (float)REALIZE_THRESHOLD/**difficulty_scale*/; - cautious = (float)CAUTIOUS_THRESHOLD * 0.75f/**difficulty_scale*/; + // If he's violated the threshold, then realize him + // float difficulty_scale = 1.0f + (2.0f-g_npcspskill.value);//if playing on easy, 20% harder to be seen...? + if (NPCS.NPC->client->NPC_class == CLASS_SWAMPTROOPER) { // swamptroopers can see much better + realize = (float)CAUTIOUS_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; + } else { + realize = (float)REALIZE_THRESHOLD /**difficulty_scale*/; + cautious = (float)CAUTIOUS_THRESHOLD * 0.75f /**difficulty_scale*/; } - if ( target_rating > realize && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { - G_SetEnemy( NPCS.NPC, target ); + if (target_rating > realize && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { + G_SetEnemy(NPCS.NPC, target); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); return qtrue; } - //If he's above the caution threshold, then realize him in a few seconds unless he moves to cover - if ( target_rating > cautious && !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - {//FIXME: ambushing guys should never talk - if ( TIMER_Done( NPCS.NPC, "enemyLastVisible" ) ) - {//If we haven't already, start the counter - int lookTime = Q_irand( 4500, 8500 ); - //NPCInfo->timeEnemyLastVisible = level.time + 2000; - TIMER_Set( NPCS.NPC, "enemyLastVisible", lookTime ); - //TODO: Play a sound along the lines of, "Huh? What was that?" - ST_Speech( NPCS.NPC, SPEECH_SIGHT, 0 ); - NPC_TempLookTarget( NPCS.NPC, target->s.number, lookTime, lookTime ); - //FIXME: set desired yaw and pitch towards this guy? - } - else if ( TIMER_Get( NPCS.NPC, "enemyLastVisible" ) <= level.time + 500 && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) //FIXME: Is this reliable? + // If he's above the caution threshold, then realize him in a few seconds unless he moves to cover + if (target_rating > cautious && !(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { // FIXME: ambushing guys should never talk + if (TIMER_Done(NPCS.NPC, "enemyLastVisible")) { // If we haven't already, start the counter + int lookTime = Q_irand(4500, 8500); + // NPCInfo->timeEnemyLastVisible = level.time + 2000; + TIMER_Set(NPCS.NPC, "enemyLastVisible", lookTime); + // TODO: Play a sound along the lines of, "Huh? What was that?" + ST_Speech(NPCS.NPC, SPEECH_SIGHT, 0); + NPC_TempLookTarget(NPCS.NPC, target->s.number, lookTime, lookTime); + // FIXME: set desired yaw and pitch towards this guy? + } else if (TIMER_Get(NPCS.NPC, "enemyLastVisible") <= level.time + 500 && + (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) // FIXME: Is this reliable? { - if ( NPCS.NPCInfo->rank < RANK_LT && !Q_irand( 0, 2 ) ) - { - int interrogateTime = Q_irand( 2000, 4000 ); - ST_Speech( NPCS.NPC, SPEECH_SUSPICIOUS, 0 ); - TIMER_Set( NPCS.NPC, "interrogating", interrogateTime ); - G_SetEnemy( NPCS.NPC, target ); + if (NPCS.NPCInfo->rank < RANK_LT && !Q_irand(0, 2)) { + int interrogateTime = Q_irand(2000, 4000); + ST_Speech(NPCS.NPC, SPEECH_SUSPICIOUS, 0); + TIMER_Set(NPCS.NPC, "interrogating", interrogateTime); + G_SetEnemy(NPCS.NPC, target); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", interrogateTime ); - TIMER_Set( NPCS.NPC, "stand", interrogateTime ); - } - else - { - G_SetEnemy( NPCS.NPC, target ); + TIMER_Set(NPCS.NPC, "attackDelay", interrogateTime); + TIMER_Set(NPCS.NPC, "stand", interrogateTime); + } else { + G_SetEnemy(NPCS.NPC, target); NPCS.NPCInfo->enemyLastSeenTime = level.time; - //FIXME: ambush guys (like those popping out of water) shouldn't delay... - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); - TIMER_Set( NPCS.NPC, "stand", Q_irand( 500, 2500 ) ); + // FIXME: ambush guys (like those popping out of water) shouldn't delay... + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); + TIMER_Set(NPCS.NPC, "stand", Q_irand(500, 2500)); } return qtrue; } @@ -758,8 +664,7 @@ qboolean NPC_CheckEnemyStealth( gentity_t *target ) return qfalse; } -qboolean NPC_CheckPlayerTeamStealth( void ) -{ +qboolean NPC_CheckPlayerTeamStealth(void) { /* //NOTENOTE: For now, all stealh checks go against the player, since // he is the main focus. Squad members and rivals do not @@ -770,18 +675,15 @@ qboolean NPC_CheckPlayerTeamStealth( void ) gentity_t *enemy; int i; - for ( i = 0; i < ENTITYNUM_WORLD; i++ ) - { + for (i = 0; i < ENTITYNUM_WORLD; i++) { enemy = &g_entities[i]; - if (!enemy->inuse) - { + if (!enemy->inuse) { continue; } - if ( enemy && enemy->client && NPC_ValidEnemy( enemy ) && enemy->client->playerTeam == NPCS.NPC->client->enemyTeam ) - { - if ( NPC_CheckEnemyStealth( enemy ) ) //Change this pointer to assess other entities + if (enemy && enemy->client && NPC_ValidEnemy(enemy) && enemy->client->playerTeam == NPCS.NPC->client->enemyTeam) { + if (NPC_CheckEnemyStealth(enemy)) // Change this pointer to assess other entities { return qtrue; } @@ -795,44 +697,36 @@ NPC_ST_InvestigateEvent ------------------------- */ -#define MAX_CHECK_THRESHOLD 1 +#define MAX_CHECK_THRESHOLD 1 -static qboolean NPC_ST_InvestigateEvent( int eventID, qboolean extraSuspicious ) -{ - //If they've given themselves away, just take them as an enemy - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - if ( level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { +static qboolean NPC_ST_InvestigateEvent(int eventID, qboolean extraSuspicious) { + // If they've given themselves away, just take them as an enemy + if (NPCS.NPCInfo->confusionTime < level.time) { + if (level.alertEvents[eventID].level == AEL_DISCOVERED && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { NPCS.NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPCS.NPC->client->enemyTeam ) - {//not an enemy + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPCS.NPC->client->enemyTeam) { // not an enemy return qfalse; } - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - //ST_Speech( NPC, SPEECH_CHARGE, 0 ); - G_SetEnemy( NPCS.NPC, level.alertEvents[eventID].owner ); + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just + // let combat AI handle this... (act as if you lost him) ST_Speech( NPC, SPEECH_CHARGE, 0 ); + G_SetEnemy(NPCS.NPC, level.alertEvents[eventID].owner); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); - if ( level.alertEvents[eventID].type == AET_SOUND ) - {//heard him, didn't see him, stick for a bit - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 500, 2500 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); + if (level.alertEvents[eventID].type == AET_SOUND) { // heard him, didn't see him, stick for a bit + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(500, 2500)); } return qtrue; } } - //don't look at the same alert twice - if ( level.alertEvents[eventID].ID == NPCS.NPCInfo->lastAlertID ) - { + // don't look at the same alert twice + if (level.alertEvents[eventID].ID == NPCS.NPCInfo->lastAlertID) { return qfalse; } NPCS.NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - //Must be ready to take another sound event + // Must be ready to take another sound event /* if ( NPCInfo->investigateSoundDebounceTime > level.time ) { @@ -840,114 +734,90 @@ static qboolean NPC_ST_InvestigateEvent( int eventID, qboolean extraSuspicious ) } */ - if ( level.alertEvents[eventID].type == AET_SIGHT ) - {//sight alert, check the light level - if ( level.alertEvents[eventID].light < Q_irand( ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD ) ) - {//below my threshhold of potentially seeing + if (level.alertEvents[eventID].type == AET_SIGHT) { // sight alert, check the light level + if (level.alertEvents[eventID].light < Q_irand(ST_MIN_LIGHT_THRESHOLD, ST_MAX_LIGHT_THRESHOLD)) { // below my threshhold of potentially seeing return qfalse; } } - //Save the position for movement (if necessary) - VectorCopy( level.alertEvents[eventID].position, NPCS.NPCInfo->investigateGoal ); + // Save the position for movement (if necessary) + VectorCopy(level.alertEvents[eventID].position, NPCS.NPCInfo->investigateGoal); - //First awareness of it - NPCS.NPCInfo->investigateCount += ( extraSuspicious ) ? 2 : 1; + // First awareness of it + NPCS.NPCInfo->investigateCount += (extraSuspicious) ? 2 : 1; - //Clamp the value - if ( NPCS.NPCInfo->investigateCount > 4 ) + // Clamp the value + if (NPCS.NPCInfo->investigateCount > 4) NPCS.NPCInfo->investigateCount = 4; - //See if we should walk over and investigate - if ( level.alertEvents[eventID].level > AEL_MINOR && NPCS.NPCInfo->investigateCount > 1 && (NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - { - //make it so they can walk right to this point and look at it rather than having to use combatPoints - if ( G_ExpandPointToBBox( NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->s.number, ((NPCS.NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP) ) ) - {//we were able to move the investigateGoal to a point in which our bbox would fit - //drop the goal to the ground so we can get at it - vec3_t end; - trace_t trace; - VectorCopy( NPCS.NPCInfo->investigateGoal, end ); - end[2] -= 512;//FIXME: not always right? What if it's even higher, somehow? - trap->Trace( &trace, NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, end, ENTITYNUM_NONE, ((NPCS.NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP), qfalse, 0, 0 ); - if ( trace.fraction >= 1.0f ) - {//too high to even bother - //FIXME: look at them??? - } - else - { - VectorCopy( trace.endpos, NPCS.NPCInfo->investigateGoal ); - NPC_SetMoveGoal( NPCS.NPC, NPCS.NPCInfo->investigateGoal, 16, qtrue, -1, NULL ); + // See if we should walk over and investigate + if (level.alertEvents[eventID].level > AEL_MINOR && NPCS.NPCInfo->investigateCount > 1 && (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { + // make it so they can walk right to this point and look at it rather than having to use combatPoints + if (G_ExpandPointToBBox(NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPC->s.number, + ((NPCS.NPC->clipmask & ~CONTENTS_BODY) | + CONTENTS_BOTCLIP))) { // we were able to move the investigateGoal to a point in which our bbox would fit + // drop the goal to the ground so we can get at it + vec3_t end; + trace_t trace; + VectorCopy(NPCS.NPCInfo->investigateGoal, end); + end[2] -= 512; // FIXME: not always right? What if it's even higher, somehow? + trap->Trace(&trace, NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, end, ENTITYNUM_NONE, + ((NPCS.NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP), qfalse, 0, 0); + if (trace.fraction >= 1.0f) { // too high to even bother + // FIXME: look at them??? + } else { + VectorCopy(trace.endpos, NPCS.NPCInfo->investigateGoal); + NPC_SetMoveGoal(NPCS.NPC, NPCS.NPCInfo->investigateGoal, 16, qtrue, -1, NULL); NPCS.NPCInfo->localState = LSTATE_INVESTIGATE; } - } - else - { - int id = NPC_FindCombatPoint( NPCS.NPCInfo->investigateGoal, NPCS.NPCInfo->investigateGoal, NPCS.NPCInfo->investigateGoal, CP_INVESTIGATE|CP_HAS_ROUTE, 0, -1 ); + } else { + int id = NPC_FindCombatPoint(NPCS.NPCInfo->investigateGoal, NPCS.NPCInfo->investigateGoal, NPCS.NPCInfo->investigateGoal, + CP_INVESTIGATE | CP_HAS_ROUTE, 0, -1); - if ( id != -1 ) - { - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[id].origin, 16, qtrue, id, NULL ); + if (id != -1) { + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[id].origin, 16, qtrue, id, NULL); NPCS.NPCInfo->localState = LSTATE_INVESTIGATE; } } - //Say something - //FIXME: only if have others in group... these should be responses? - if ( NPCS.NPCInfo->investigateDebounceTime+NPCS.NPCInfo->pauseTime > level.time ) - {//was already investigating - if ( NPCS.NPCInfo->group && - NPCS.NPCInfo->group->commander && - NPCS.NPCInfo->group->commander->client && - NPCS.NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && - !Q_irand( 0, 3 ) ) - { - ST_Speech( NPCS.NPCInfo->group->commander, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds - } - else - { - ST_Speech( NPCS.NPC, SPEECH_LOOK, 0 );//FIXME: "I'll go check it out" type sounds - } - } - else - { - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPCS.NPC, SPEECH_SIGHT, 0 ); + // Say something + // FIXME: only if have others in group... these should be responses? + if (NPCS.NPCInfo->investigateDebounceTime + NPCS.NPCInfo->pauseTime > level.time) { // was already investigating + if (NPCS.NPCInfo->group && NPCS.NPCInfo->group->commander && NPCS.NPCInfo->group->commander->client && + NPCS.NPCInfo->group->commander->client->NPC_class == CLASS_IMPERIAL && !Q_irand(0, 3)) { + ST_Speech(NPCS.NPCInfo->group->commander, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds + } else { + ST_Speech(NPCS.NPC, SPEECH_LOOK, 0); // FIXME: "I'll go check it out" type sounds } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPCS.NPC, SPEECH_SOUND, 0 ); + } else { + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPCS.NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPCS.NPC, SPEECH_SOUND, 0); } } - //Setup the debounce info - NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 5000; - NPCS.NPCInfo->investigateSoundDebounceTime = level.time + 2000; - NPCS.NPCInfo->pauseTime = level.time; - } - else - {//just look? - //Say something - if ( level.alertEvents[eventID].type == AET_SIGHT ) - { - ST_Speech( NPCS.NPC, SPEECH_SIGHT, 0 ); - } - else if ( level.alertEvents[eventID].type == AET_SOUND ) - { - ST_Speech( NPCS.NPC, SPEECH_SOUND, 0 ); + // Setup the debounce info + NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 5000; + NPCS.NPCInfo->investigateSoundDebounceTime = level.time + 2000; + NPCS.NPCInfo->pauseTime = level.time; + } else { // just look? + // Say something + if (level.alertEvents[eventID].type == AET_SIGHT) { + ST_Speech(NPCS.NPC, SPEECH_SIGHT, 0); + } else if (level.alertEvents[eventID].type == AET_SOUND) { + ST_Speech(NPCS.NPC, SPEECH_SOUND, 0); } - //Setup the debounce info - NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 1000; - NPCS.NPCInfo->investigateSoundDebounceTime = level.time + 1000; - NPCS.NPCInfo->pauseTime = level.time; - VectorCopy( level.alertEvents[eventID].position, NPCS.NPCInfo->investigateGoal ); + // Setup the debounce info + NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 1000; + NPCS.NPCInfo->investigateSoundDebounceTime = level.time + 1000; + NPCS.NPCInfo->pauseTime = level.time; + VectorCopy(level.alertEvents[eventID].position, NPCS.NPCInfo->investigateGoal); } - if ( level.alertEvents[eventID].level >= AEL_DANGER ) - { - NPCS.NPCInfo->investigateDebounceTime = Q_irand( 500, 2500 ); + if (level.alertEvents[eventID].level >= AEL_DANGER) { + NPCS.NPCInfo->investigateDebounceTime = Q_irand(500, 2500); } - //Start investigating + // Start investigating NPCS.NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; } @@ -958,16 +828,15 @@ ST_OffsetLook ------------------------- */ -static void ST_OffsetLook( float offset, vec3_t out ) -{ - vec3_t angles, forward, temp; +static void ST_OffsetLook(float offset, vec3_t out) { + vec3_t angles, forward, temp; - GetAnglesForDirection( NPCS.NPC->r.currentOrigin, NPCS.NPCInfo->investigateGoal, angles ); + GetAnglesForDirection(NPCS.NPC->r.currentOrigin, NPCS.NPCInfo->investigateGoal, angles); angles[YAW] += offset; - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( NPCS.NPC->r.currentOrigin, 64, forward, out ); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(NPCS.NPC->r.currentOrigin, 64, forward, out); - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, temp ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, temp); out[2] = temp[2]; } @@ -977,30 +846,25 @@ ST_LookAround ------------------------- */ -static void ST_LookAround( void ) -{ - vec3_t lookPos; - float perc = (float) ( level.time - NPCS.NPCInfo->pauseTime ) / (float) NPCS.NPCInfo->investigateDebounceTime; +static void ST_LookAround(void) { + vec3_t lookPos; + float perc = (float)(level.time - NPCS.NPCInfo->pauseTime) / (float)NPCS.NPCInfo->investigateDebounceTime; - //Keep looking at the spot - if ( perc < 0.25 ) - { - VectorCopy( NPCS.NPCInfo->investigateGoal, lookPos ); - } - else if ( perc < 0.5f ) //Look up but straight ahead + // Keep looking at the spot + if (perc < 0.25) { + VectorCopy(NPCS.NPCInfo->investigateGoal, lookPos); + } else if (perc < 0.5f) // Look up but straight ahead { - ST_OffsetLook( 0.0f, lookPos ); - } - else if ( perc < 0.75f ) //Look right + ST_OffsetLook(0.0f, lookPos); + } else if (perc < 0.75f) // Look right { - ST_OffsetLook( 45.0f, lookPos ); - } - else //Look left + ST_OffsetLook(45.0f, lookPos); + } else // Look left { - ST_OffsetLook( -45.0f, lookPos ); + ST_OffsetLook(-45.0f, lookPos); } - NPC_FacePosition( lookPos, qtrue ); + NPC_FacePosition(lookPos, qtrue); } /* @@ -1009,96 +873,83 @@ NPC_BSST_Investigate ------------------------- */ -void NPC_BSST_Investigate( void ) -{ - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPCS.NPC ); +void NPC_BSST_Investigate(void) { + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPCS.NPC); - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - //Look for an enemy - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - ST_Speech( NPCS.NPC, SPEECH_DETECTED, 0 ); - NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCS.NPCInfo->confusionTime < level.time) { + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + // Look for an enemy + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + ST_Speech(NPCS.NPC, SPEECH_DETECTED, 0); + NPCS.NPCInfo->tempBehavior = BS_DEFAULT; + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, NPCS.NPCInfo->lastAlertID, qfalse, AEL_MINOR ); + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, NPCS.NPCInfo->lastAlertID, qfalse, AEL_MINOR); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - if ( NPC_CheckForDanger( alertEvent ) ) - {//running like hell - ST_Speech( NPCS.NPC, SPEECH_COVER, 0 );//FIXME: flee sound? + // There is an event to look at + if (alertEvent >= 0) { + if (NPCS.NPCInfo->confusionTime < level.time) { + if (NPC_CheckForDanger(alertEvent)) { // running like hell + ST_Speech(NPCS.NPC, SPEECH_COVER, 0); // FIXME: flee sound? return; } } - if ( level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID ) - { - NPC_ST_InvestigateEvent( alertEvent, qtrue ); + if (level.alertEvents[alertEvent].ID != NPCS.NPCInfo->lastAlertID) { + NPC_ST_InvestigateEvent(alertEvent, qtrue); } } } - //If we're done looking, then just return to what we were doing - if ( ( NPCS.NPCInfo->investigateDebounceTime + NPCS.NPCInfo->pauseTime ) < level.time ) - { + // If we're done looking, then just return to what we were doing + if ((NPCS.NPCInfo->investigateDebounceTime + NPCS.NPCInfo->pauseTime) < level.time) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; NPCS.NPCInfo->goalEntity = UpdateGoal(); - NPC_UpdateAngles( qtrue, qtrue ); - //Say something - ST_Speech( NPCS.NPC, SPEECH_GIVEUP, 0 ); + NPC_UpdateAngles(qtrue, qtrue); + // Say something + ST_Speech(NPCS.NPC, SPEECH_GIVEUP, 0); return; } - //FIXME: else, look for new alerts + // FIXME: else, look for new alerts - //See if we're searching for the noise's origin - if ( NPCS.NPCInfo->localState == LSTATE_INVESTIGATE && (NPCS.NPCInfo->goalEntity!=NULL) ) - { - //See if we're there - if ( NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 32, FlyingCreature( NPCS.NPC ) ) == qfalse ) - { + // See if we're searching for the noise's origin + if (NPCS.NPCInfo->localState == LSTATE_INVESTIGATE && (NPCS.NPCInfo->goalEntity != NULL)) { + // See if we're there + if (NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 32, + FlyingCreature(NPCS.NPC)) == qfalse) { NPCS.ucmd.buttons |= BUTTON_WALKING; - //Try and move there - if ( NPC_MoveToGoal( qtrue ) ) - { - //Bump our times - NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 5000; - NPCS.NPCInfo->pauseTime = level.time; + // Try and move there + if (NPC_MoveToGoal(qtrue)) { + // Bump our times + NPCS.NPCInfo->investigateDebounceTime = NPCS.NPCInfo->investigateCount * 5000; + NPCS.NPCInfo->pauseTime = level.time; - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } } - //Otherwise we're done or have given up - //Say something - //ST_Speech( NPC, SPEECH_LOOK, 0.33f ); + // Otherwise we're done or have given up + // Say something + // ST_Speech( NPC, SPEECH_LOOK, 0.33f ); NPCS.NPCInfo->localState = LSTATE_NONE; } - //Look around + // Look around ST_LookAround(); } @@ -1108,98 +959,77 @@ NPC_BSST_Patrol ------------------------- */ -void NPC_BSST_Patrol( void ) -{//FIXME: pick up on bodies of dead buddies? +void NPC_BSST_Patrol(void) { // FIXME: pick up on bodies of dead buddies? - //get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too - AI_GetGroup( NPCS.NPC ); + // get group- mainly for group speech debouncing, but may use for group scouting/investigating AI, too + AI_GetGroup(NPCS.NPC); - if ( NPCS.NPCInfo->confusionTime < level.time ) - { - //Look for any enemies - if ( NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckPlayerTeamStealth() ) - { - //NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now - //NPC_AngerSound(); - NPC_UpdateAngles( qtrue, qtrue ); + if (NPCS.NPCInfo->confusionTime < level.time) { + // Look for any enemies + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckPlayerTeamStealth()) { + // NPCInfo->behaviorState = BS_HUNT_AND_KILL;//should be auto now + // NPC_AngerSound(); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_MINOR ); + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_MINOR); - //There is an event to look at - if ( alertEvent >= 0 ) - { - if ( NPC_ST_InvestigateEvent( alertEvent, qfalse ) ) - {//actually going to investigate it - NPC_UpdateAngles( qtrue, qtrue ); + // There is an event to look at + if (alertEvent >= 0) { + if (NPC_ST_InvestigateEvent(alertEvent, qfalse)) { // actually going to investigate it + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - //ST_Move( NPCInfo->goalEntity ); - NPC_MoveToGoal( qtrue ); - } - else// if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - if ( NPCS.NPC->client->NPC_class != CLASS_IMPERIAL && NPCS.NPC->client->NPC_class != CLASS_IMPWORKER ) - {//imperials do not look around - if ( TIMER_Done( NPCS.NPC, "enemyLastVisible" ) ) - {//nothing suspicious, look around - if ( !Q_irand( 0, 30 ) ) - { - NPCS.NPCInfo->desiredYaw = NPCS.NPC->s.angles[1] + Q_irand( -90, 90 ); + // ST_Move( NPCInfo->goalEntity ); + NPC_MoveToGoal(qtrue); + } else // if ( !(NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) + { + if (NPCS.NPC->client->NPC_class != CLASS_IMPERIAL && NPCS.NPC->client->NPC_class != CLASS_IMPWORKER) { // imperials do not look around + if (TIMER_Done(NPCS.NPC, "enemyLastVisible")) { // nothing suspicious, look around + if (!Q_irand(0, 30)) { + NPCS.NPCInfo->desiredYaw = NPCS.NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCS.NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCS.NPCInfo->desiredPitch = Q_irand(-20, 20); } } } } - NPC_UpdateAngles( qtrue, qtrue ); - //TEMP hack for Imperial stand anim - if ( NPCS.NPC->client->NPC_class == CLASS_IMPERIAL || NPCS.NPC->client->NPC_class == CLASS_IMPWORKER ) - {//hack - if ( NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove || NPCS.ucmd.upmove ) - {//moving + NPC_UpdateAngles(qtrue, qtrue); + // TEMP hack for Imperial stand anim + if (NPCS.NPC->client->NPC_class == CLASS_IMPERIAL || NPCS.NPC->client->NPC_class == CLASS_IMPWORKER) { // hack + if (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove || NPCS.ucmd.upmove) { // moving - if( (NPCS.NPC->client->ps.torsoTimer <= 0) || (NPCS.NPC->client->ps.torsoAnim == BOTH_STAND4) ) - { - if ( (NPCS.ucmd.buttons&BUTTON_WALKING) && !(NPCS.NPCInfo->scriptFlags&SCF_RUNNING) ) - {//not running, only set upper anim + if ((NPCS.NPC->client->ps.torsoTimer <= 0) || (NPCS.NPC->client->ps.torsoAnim == BOTH_STAND4)) { + if ((NPCS.ucmd.buttons & BUTTON_WALKING) && !(NPCS.NPCInfo->scriptFlags & SCF_RUNNING)) { // not running, only set upper anim // No longer overrides scripted anims - NPC_SetAnim( NPCS.NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + NPC_SetAnim(NPCS.NPC, SETANIM_TORSO, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPC->client->ps.torsoTimer = 200; } } - } - else - {//standing still, set both torso and legs anim + } else { // standing still, set both torso and legs anim // No longer overrides scripted anims - if( ( NPCS.NPC->client->ps.torsoTimer <= 0 || (NPCS.NPC->client->ps.torsoAnim == BOTH_STAND4) ) && - ( NPCS.NPC->client->ps.legsTimer <= 0 || (NPCS.NPC->client->ps.legsAnim == BOTH_STAND4) ) ) - { - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if ((NPCS.NPC->client->ps.torsoTimer <= 0 || (NPCS.NPC->client->ps.torsoAnim == BOTH_STAND4)) && + (NPCS.NPC->client->ps.legsTimer <= 0 || (NPCS.NPC->client->ps.legsAnim == BOTH_STAND4))) { + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_STAND4, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPC->client->ps.torsoTimer = NPCS.NPC->client->ps.legsTimer = 200; } } - //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way - if ( NPCS.NPC->client->ps.weapon != WP_NONE ) - { - ChangeWeapon( NPCS.NPC, WP_NONE ); + // FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way + if (NPCS.NPC->client->ps.weapon != WP_NONE) { + ChangeWeapon(NPCS.NPC, WP_NONE); NPCS.NPC->client->ps.weapon = WP_NONE; NPCS.NPC->client->ps.weaponstate = WEAPON_READY; /* @@ -1209,7 +1039,7 @@ void NPC_BSST_Patrol( void ) NPC->weaponModel[0] = -1; } */ - //rwwFIXMEFIXME: Do this? + // rwwFIXMEFIXME: Do this? } } } @@ -1243,40 +1073,31 @@ ST_CheckMoveState ------------------------- */ -static void ST_CheckMoveState( void ) -{ +static void ST_CheckMoveState(void) { - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//moving toward a goal that a script is waiting on, so don't stop for anything! + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { // moving toward a goal that a script is waiting on, so don't stop for anything! move = qtrue; } - //See if we're a scout - else if ( NPCS.NPCInfo->squadState == SQUAD_SCOUT ) - { - //If we're supposed to stay put, then stand there and fire - if ( TIMER_Done( NPCS.NPC, "stick" ) == qfalse ) - { + // See if we're a scout + else if (NPCS.NPCInfo->squadState == SQUAD_SCOUT) { + // If we're supposed to stay put, then stand there and fire + if (TIMER_Done(NPCS.NPC, "stick") == qfalse) { move = qfalse; return; } - //Otherwise, if we can see our target, just shoot - if ( enemyLOS ) - { - if ( enemyCS ) - { - //if we're going after our enemy, we can stop now - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - { - AI_GroupUpdateSquadstates( NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT ); + // Otherwise, if we can see our target, just shoot + if (enemyLOS) { + if (enemyCS) { + // if we're going after our enemy, we can stop now + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { + AI_GroupUpdateSquadstates(NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT); move = qfalse; return; } } - } - else - { - //Move to find our target + } else { + // Move to find our target faceEnemy = qfalse; } @@ -1290,152 +1111,128 @@ static void ST_CheckMoveState( void ) } */ - //ucmd.buttons |= BUTTON_CAREFUL; + // ucmd.buttons |= BUTTON_CAREFUL; } - //See if we're running away - else if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT ) - { - if ( NPCS.NPCInfo->goalEntity ) - { + // See if we're running away + else if (NPCS.NPCInfo->squadState == SQUAD_RETREAT) { + if (NPCS.NPCInfo->goalEntity) { faceEnemy = qfalse; - } - else - {//um, lost our goal? Just stand and shoot, then + } else { // um, lost our goal? Just stand and shoot, then NPCS.NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; } } - //see if we're heading to some other combatPoint - else if ( NPCS.NPCInfo->squadState == SQUAD_TRANSITION ) - { - //ucmd.buttons |= BUTTON_CAREFUL; - if ( !NPCS.NPCInfo->goalEntity ) - {//um, lost our goal? Just stand and shoot, then + // see if we're heading to some other combatPoint + else if (NPCS.NPCInfo->squadState == SQUAD_TRANSITION) { + // ucmd.buttons |= BUTTON_CAREFUL; + if (!NPCS.NPCInfo->goalEntity) { // um, lost our goal? Just stand and shoot, then NPCS.NPCInfo->squadState = SQUAD_STAND_AND_SHOOT; } } - //see if we're at point, duck and fire - else if ( NPCS.NPCInfo->squadState == SQUAD_POINT ) - { - if ( TIMER_Done( NPCS.NPC, "stick" ) ) - { - AI_GroupUpdateSquadstates( NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT ); + // see if we're at point, duck and fire + else if (NPCS.NPCInfo->squadState == SQUAD_POINT) { + if (TIMER_Done(NPCS.NPC, "stick")) { + AI_GroupUpdateSquadstates(NPCS.NPCInfo->group, NPCS.NPC, SQUAD_STAND_AND_SHOOT); return; } move = qfalse; return; } - //see if we're just standing around - else if ( NPCS.NPCInfo->squadState == SQUAD_STAND_AND_SHOOT ) - {//from this squadState we can transition to others? + // see if we're just standing around + else if (NPCS.NPCInfo->squadState == SQUAD_STAND_AND_SHOOT) { // from this squadState we can transition to others? move = qfalse; return; } - //see if we're hiding - else if ( NPCS.NPCInfo->squadState == SQUAD_COVER ) - { - //Should we duck? + // see if we're hiding + else if (NPCS.NPCInfo->squadState == SQUAD_COVER) { + // Should we duck? move = qfalse; return; } - //see if we're just standing around - else if ( NPCS.NPCInfo->squadState == SQUAD_IDLE ) - { - if ( !NPCS.NPCInfo->goalEntity ) - { + // see if we're just standing around + else if (NPCS.NPCInfo->squadState == SQUAD_IDLE) { + if (!NPCS.NPCInfo->goalEntity) { move = qfalse; return; } } //?? - else - {//invalid squadState! - } - - //See if we're moving towards a goal, not the enemy - if ( ( NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy ) && ( NPCS.NPCInfo->goalEntity != NULL ) ) - { - //Did we make it? - if ( NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, FlyingCreature( NPCS.NPC ) ) || - ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) && NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && enemyDist <= 10000 ) ) - {//either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and found our enemy - int newSquadState = SQUAD_STAND_AND_SHOOT; - //we got where we wanted to go, set timers based on why we were running - switch ( NPCS.NPCInfo->squadState ) - { - case SQUAD_RETREAT://was running away - //done fleeing, obviously - TIMER_Set( NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100 ); - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 3000, 7000 ) ); - TIMER_Set( NPCS.NPC, "flee", -level.time ); + else { // invalid squadState! + } + + // See if we're moving towards a goal, not the enemy + if ((NPCS.NPCInfo->goalEntity != NPCS.NPC->enemy) && (NPCS.NPCInfo->goalEntity != NULL)) { + // Did we make it? + if (NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, NPCS.NPCInfo->goalEntity->r.currentOrigin, 16, + FlyingCreature(NPCS.NPC)) || + (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV) && NPCS.NPCInfo->squadState == SQUAD_SCOUT && enemyLOS && + enemyDist <= 10000)) { // either hit our navgoal or our navgoal was not a crucial (scripted) one (maybe a combat point) and we're scouting and + // found our enemy + int newSquadState = SQUAD_STAND_AND_SHOOT; + // we got where we wanted to go, set timers based on why we were running + switch (NPCS.NPCInfo->squadState) { + case SQUAD_RETREAT: // was running away + // done fleeing, obviously + TIMER_Set(NPCS.NPC, "duck", (NPCS.NPC->client->pers.maxHealth - NPCS.NPC->health) * 100); + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(3000, 7000)); + TIMER_Set(NPCS.NPC, "flee", -level.time); newSquadState = SQUAD_COVER; break; - case SQUAD_TRANSITION://was heading for a combat point - TIMER_Set( NPCS.NPC, "hideTime", Q_irand( 2000, 4000 ) ); + case SQUAD_TRANSITION: // was heading for a combat point + TIMER_Set(NPCS.NPC, "hideTime", Q_irand(2000, 4000)); break; - case SQUAD_SCOUT://was running after player + case SQUAD_SCOUT: // was running after player break; default: break; } - AI_GroupUpdateSquadstates( NPCS.NPCInfo->group, NPCS.NPC, newSquadState ); + AI_GroupUpdateSquadstates(NPCS.NPCInfo->group, NPCS.NPC, newSquadState); NPC_ReachedGoal(); - //don't attack right away - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 250, 500 ) ); //FIXME: Slant for difficulty levels - //don't do something else just yet - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 1000, 4000 ) ); + // don't attack right away + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(250, 500)); // FIXME: Slant for difficulty levels + // don't do something else just yet + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(1000, 4000)); return; } - //keep going, hold of roamTimer until we get there - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 4000, 8000 ) ); + // keep going, hold of roamTimer until we get there + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(4000, 8000)); } } -void ST_ResolveBlockedShot( int hit ) -{ - int stuckTime; +void ST_ResolveBlockedShot(int hit) { + int stuckTime; - //figure out how long we intend to stand here, max - if ( TIMER_Get( NPCS.NPC, "roamTime" ) > TIMER_Get( NPCS.NPC, "stick" ) ) - { - stuckTime = TIMER_Get( NPCS.NPC, "roamTime" )-level.time; - } - else - { - stuckTime = TIMER_Get( NPCS.NPC, "stick" )-level.time; + // figure out how long we intend to stand here, max + if (TIMER_Get(NPCS.NPC, "roamTime") > TIMER_Get(NPCS.NPC, "stick")) { + stuckTime = TIMER_Get(NPCS.NPC, "roamTime") - level.time; + } else { + stuckTime = TIMER_Get(NPCS.NPC, "stick") - level.time; } - if ( TIMER_Done( NPCS.NPC, "duck" ) ) - {//we're not ducking - if ( AI_GroupContainsEntNum( NPCS.NPCInfo->group, hit ) ) - { + if (TIMER_Done(NPCS.NPC, "duck")) { // we're not ducking + if (AI_GroupContainsEntNum(NPCS.NPCInfo->group, hit)) { gentity_t *member = &g_entities[hit]; - if ( TIMER_Done( member, "duck" ) ) - {//they aren't ducking - if ( TIMER_Done( member, "stand" ) ) - {//they're not being forced to stand - //tell them to duck at least as long as I'm not moving - TIMER_Set( member, "duck", stuckTime ); + if (TIMER_Done(member, "duck")) { // they aren't ducking + if (TIMER_Done(member, "stand")) { // they're not being forced to stand + // tell them to duck at least as long as I'm not moving + TIMER_Set(member, "duck", stuckTime); return; } } } - } - else - {//maybe we should stand - if ( TIMER_Done( NPCS.NPC, "stand" ) ) - {//stand for as long as we'll be here - TIMER_Set( NPCS.NPC, "stand", stuckTime ); + } else { // maybe we should stand + if (TIMER_Done(NPCS.NPC, "stand")) { // stand for as long as we'll be here + TIMER_Set(NPCS.NPC, "stand", stuckTime); return; } } - //Hmm, can't resolve this by telling them to duck or telling me to stand - //We need to move! - TIMER_Set( NPCS.NPC, "roamTime", -1 ); - TIMER_Set( NPCS.NPC, "stick", -1 ); - TIMER_Set( NPCS.NPC, "duck", -1 ); - TIMER_Set( NPCS.NPC, "attakDelay", Q_irand( 1000, 3000 ) ); + // Hmm, can't resolve this by telling them to duck or telling me to stand + // We need to move! + TIMER_Set(NPCS.NPC, "roamTime", -1); + TIMER_Set(NPCS.NPC, "stick", -1); + TIMER_Set(NPCS.NPC, "duck", -1); + TIMER_Set(NPCS.NPC, "attakDelay", Q_irand(1000, 3000)); } /* @@ -1444,124 +1241,113 @@ ST_CheckFireState ------------------------- */ -static void ST_CheckFireState( void ) -{ - if ( enemyCS ) - {//if have a clear shot, always try +static void ST_CheckFireState(void) { + if (enemyCS) { // if have a clear shot, always try return; } - if ( NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || NPCS.NPCInfo->squadState == SQUAD_SCOUT ) - {//runners never try to fire at the last pos + if (NPCS.NPCInfo->squadState == SQUAD_RETREAT || NPCS.NPCInfo->squadState == SQUAD_TRANSITION || + NPCS.NPCInfo->squadState == SQUAD_SCOUT) { // runners never try to fire at the last pos return; } - if ( !VectorCompare( NPCS.NPC->client->ps.velocity, vec3_origin ) ) - {//if moving at all, don't do this + if (!VectorCompare(NPCS.NPC->client->ps.velocity, vec3_origin)) { // if moving at all, don't do this return; } - //See if we should continue to fire on their last position - //!TIMER_Done( NPC, "stick" ) || - if ( !hitAlly //we're not going to hit an ally - && enemyInFOV //enemy is in our FOV //FIXME: or we don't have a clear LOS? - && NPCS.NPCInfo->enemyLastSeenTime > 0 //we've seen the enemy - && NPCS.NPCInfo->group //have a group - && (NPCS.NPCInfo->group->numState[SQUAD_RETREAT]>0||NPCS.NPCInfo->group->numState[SQUAD_TRANSITION]>0||NPCS.NPCInfo->group->numState[SQUAD_SCOUT]>0) )//laying down covering fire + // See if we should continue to fire on their last position + //! TIMER_Done( NPC, "stick" ) || + if (!hitAlly // we're not going to hit an ally + && enemyInFOV // enemy is in our FOV //FIXME: or we don't have a clear LOS? + && NPCS.NPCInfo->enemyLastSeenTime > 0 // we've seen the enemy + && NPCS.NPCInfo->group // have a group + && (NPCS.NPCInfo->group->numState[SQUAD_RETREAT] > 0 || NPCS.NPCInfo->group->numState[SQUAD_TRANSITION] > 0 || + NPCS.NPCInfo->group->numState[SQUAD_SCOUT] > 0)) // laying down covering fire { - if ( level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000 &&//we have seem the enemy in the last 10 seconds - (!NPCS.NPCInfo->group || level.time - NPCS.NPCInfo->group->lastSeenEnemyTime < 10000 ))//we are not in a group or the group has seen the enemy in the last 10 seconds + if (level.time - NPCS.NPCInfo->enemyLastSeenTime < 10000 && // we have seem the enemy in the last 10 seconds + (!NPCS.NPCInfo->group || + level.time - NPCS.NPCInfo->group->lastSeenEnemyTime < 10000)) // we are not in a group or the group has seen the enemy in the last 10 seconds { - if ( !Q_irand( 0, 10 ) ) - { - //Fire on the last known position - vec3_t muzzle, dir, angles; + if (!Q_irand(0, 10)) { + // Fire on the last known position + vec3_t muzzle, dir, angles; qboolean tooClose = qfalse; qboolean tooFar = qfalse; float distThreshold; float dist; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, muzzle ); - if ( VectorCompare( impactPos, vec3_origin ) ) - {//never checked ShotEntity this frame, so must do a trace... + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, muzzle); + if (VectorCompare(impactPos, vec3_origin)) { // never checked ShotEntity this frame, so must do a trace... trace_t tr; - //vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; - vec3_t forward, end; - AngleVectors( NPCS.NPC->client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, 8192, forward, end ); - trap->Trace( &tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - VectorCopy( tr.endpos, impactPos ); + // vec3_t mins = {-2,-2,-2}, maxs = {2,2,2}; + vec3_t forward, end; + AngleVectors(NPCS.NPC->client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, 8192, forward, end); + trap->Trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + VectorCopy(tr.endpos, impactPos); } - //see if impact would be too close to me - distThreshold = 16384/*128*128*/;//default - switch ( NPCS.NPC->s.weapon ) - { + // see if impact would be too close to me + distThreshold = 16384 /*128*128*/; // default + switch (NPCS.NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 65536/*256*256*/; + distThreshold = 65536 /*256*256*/; break; case WP_REPEATER: - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 65536/*256*256*/; + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 65536 /*256*256*/; } break; default: break; } - dist = DistanceSquared( impactPos, muzzle ); + dist = DistanceSquared(impactPos, muzzle); - if ( dist < distThreshold ) - {//impact would be too close to me + if (dist < distThreshold) { // impact would be too close to me tooClose = qtrue; - } - else if ( level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000 || - (NPCS.NPCInfo->group && level.time - NPCS.NPCInfo->group->lastSeenEnemyTime > 5000 )) - {//we've haven't seen them in the last 5 seconds - //see if it's too far from where he is - distThreshold = 65536/*256*256*/;//default - switch ( NPCS.NPC->s.weapon ) - { + } else if (level.time - NPCS.NPCInfo->enemyLastSeenTime > 5000 || + (NPCS.NPCInfo->group && + level.time - NPCS.NPCInfo->group->lastSeenEnemyTime > 5000)) { // we've haven't seen them in the last 5 seconds + // see if it's too far from where he is + distThreshold = 65536 /*256*256*/; // default + switch (NPCS.NPC->s.weapon) { case WP_ROCKET_LAUNCHER: case WP_FLECHETTE: case WP_THERMAL: case WP_TRIP_MINE: case WP_DET_PACK: - distThreshold = 262144/*512*512*/; + distThreshold = 262144 /*512*512*/; break; case WP_REPEATER: - if ( NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE ) - { - distThreshold = 262144/*512*512*/; + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + distThreshold = 262144 /*512*512*/; } break; default: break; } - dist = DistanceSquared( impactPos, NPCS.NPCInfo->enemyLastSeenLocation ); - if ( dist > distThreshold ) - {//impact would be too far from enemy + dist = DistanceSquared(impactPos, NPCS.NPCInfo->enemyLastSeenLocation); + if (dist > distThreshold) { // impact would be too far from enemy tooFar = qtrue; } } - if ( !tooClose && !tooFar ) - {//okay too shoot at last pos - VectorSubtract( NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir ); - VectorNormalize( dir ); - vectoangles( dir, angles ); + if (!tooClose && !tooFar) { // okay too shoot at last pos + VectorSubtract(NPCS.NPCInfo->enemyLastSeenLocation, muzzle, dir); + VectorNormalize(dir); + vectoangles(dir, angles); - NPCS.NPCInfo->desiredYaw = angles[YAW]; - NPCS.NPCInfo->desiredPitch = angles[PITCH]; + NPCS.NPCInfo->desiredYaw = angles[YAW]; + NPCS.NPCInfo->desiredPitch = angles[PITCH]; shoot = qtrue; faceEnemy = qfalse; - //AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); + // AI_GroupUpdateSquadstates( NPCInfo->group, NPC, SQUAD_STAND_AND_SHOOT ); return; } } @@ -1569,177 +1355,139 @@ static void ST_CheckFireState( void ) } } -void ST_TrackEnemy( gentity_t *self, vec3_t enemyPos ) -{ - //clear timers - TIMER_Set( self, "attackDelay", Q_irand( 1000, 2000 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 500, 1500 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint, qfalse ); - //go after his last seen pos - NPC_SetMoveGoal( self, enemyPos, 16, qfalse, -1, NULL ); +void ST_TrackEnemy(gentity_t *self, vec3_t enemyPos) { + // clear timers + TIMER_Set(self, "attackDelay", Q_irand(1000, 2000)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(500, 1500)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint, qfalse); + // go after his last seen pos + NPC_SetMoveGoal(self, enemyPos, 16, qfalse, -1, NULL); } -int ST_ApproachEnemy( gentity_t *self ) -{ - TIMER_Set( self, "attackDelay", Q_irand( 250, 500 ) ); - //TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 1000, 2000 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( self->NPC->combatPoint, qfalse ); - //return the relevant combat point flags - return (CP_CLEAR|CP_CLOSEST); +int ST_ApproachEnemy(gentity_t *self) { + TIMER_Set(self, "attackDelay", Q_irand(250, 500)); + // TIMER_Set( self, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(1000, 2000)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(self->NPC->combatPoint, qfalse); + // return the relevant combat point flags + return (CP_CLEAR | CP_CLOSEST); } -void ST_HuntEnemy( gentity_t *self ) -{ - //TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack - //TIMER_Set( NPC, "duck", -1 ); - TIMER_Set( self, "stick", Q_irand( 250, 1000 ) ); - TIMER_Set( self, "stand", -1 ); - TIMER_Set( self, "scoutTime", TIMER_Get( self, "stick" )-level.time+Q_irand(5000, 10000) ); - //leave my combat point - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qfalse ); - //go directly after the enemy - if ( NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES ) - { +void ST_HuntEnemy(gentity_t *self) { + // TIMER_Set( NPC, "attackDelay", Q_irand( 250, 500 ) );//Disabled this for now, guys who couldn't hunt would never attack + // TIMER_Set( NPC, "duck", -1 ); + TIMER_Set(self, "stick", Q_irand(250, 1000)); + TIMER_Set(self, "stand", -1); + TIMER_Set(self, "scoutTime", TIMER_Get(self, "stick") - level.time + Q_irand(5000, 10000)); + // leave my combat point + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qfalse); + // go directly after the enemy + if (NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES) { self->NPC->goalEntity = NPCS.NPC->enemy; } } -void ST_TransferTimers( gentity_t *self, gentity_t *other ) -{ - TIMER_Set( other, "attackDelay", TIMER_Get( self, "attackDelay" )-level.time ); - TIMER_Set( other, "duck", TIMER_Get( self, "duck" )-level.time ); - TIMER_Set( other, "stick", TIMER_Get( self, "stick" )-level.time ); - TIMER_Set( other, "scoutTime", TIMER_Get( self, "scout" )-level.time ); - TIMER_Set( other, "roamTime", TIMER_Get( self, "roamTime" )-level.time ); - TIMER_Set( other, "stand", TIMER_Get( self, "stand" )-level.time ); - TIMER_Set( self, "attackDelay", -1 ); - TIMER_Set( self, "duck", -1 ); - TIMER_Set( self, "stick", -1 ); - TIMER_Set( self, "scoutTime", -1 ); - TIMER_Set( self, "roamTime", -1 ); - TIMER_Set( self, "stand", -1 ); +void ST_TransferTimers(gentity_t *self, gentity_t *other) { + TIMER_Set(other, "attackDelay", TIMER_Get(self, "attackDelay") - level.time); + TIMER_Set(other, "duck", TIMER_Get(self, "duck") - level.time); + TIMER_Set(other, "stick", TIMER_Get(self, "stick") - level.time); + TIMER_Set(other, "scoutTime", TIMER_Get(self, "scout") - level.time); + TIMER_Set(other, "roamTime", TIMER_Get(self, "roamTime") - level.time); + TIMER_Set(other, "stand", TIMER_Get(self, "stand") - level.time); + TIMER_Set(self, "attackDelay", -1); + TIMER_Set(self, "duck", -1); + TIMER_Set(self, "stick", -1); + TIMER_Set(self, "scoutTime", -1); + TIMER_Set(self, "roamTime", -1); + TIMER_Set(self, "stand", -1); } -void ST_TransferMoveGoal( gentity_t *self, gentity_t *other ) -{ - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)self, TID_MOVE_NAV ) ) - {//can't transfer movegoal when a script we're running is waiting to complete +void ST_TransferMoveGoal(gentity_t *self, gentity_t *other) { + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)self, TID_MOVE_NAV)) { // can't transfer movegoal when a script we're running is waiting to complete return; } - if ( self->NPC->combatPoint != -1 ) - {//I've got a combatPoint I'm going to, give it to him + if (self->NPC->combatPoint != -1) { // I've got a combatPoint I'm going to, give it to him self->NPC->lastFailedCombatPoint = other->NPC->combatPoint = self->NPC->combatPoint; self->NPC->combatPoint = -1; - } - else - {//I must be going for a goal, give that to him instead - if ( self->NPC->goalEntity == self->NPC->tempGoal ) - { - NPC_SetMoveGoal( other, self->NPC->tempGoal->r.currentOrigin, self->NPC->goalRadius, ((self->NPC->tempGoal->flags&FL_NAVGOAL)?qtrue:qfalse), -1, NULL ); - } - else - { + } else { // I must be going for a goal, give that to him instead + if (self->NPC->goalEntity == self->NPC->tempGoal) { + NPC_SetMoveGoal(other, self->NPC->tempGoal->r.currentOrigin, self->NPC->goalRadius, ((self->NPC->tempGoal->flags & FL_NAVGOAL) ? qtrue : qfalse), + -1, NULL); + } else { other->NPC->goalEntity = self->NPC->goalEntity; } } - //give him my squadstate - AI_GroupUpdateSquadstates( self->NPC->group, other, NPCS.NPCInfo->squadState ); + // give him my squadstate + AI_GroupUpdateSquadstates(self->NPC->group, other, NPCS.NPCInfo->squadState); - //give him my timers and clear mine - ST_TransferTimers( self, other ); + // give him my timers and clear mine + ST_TransferTimers(self, other); - //now make me stand around for a second or two at least - AI_GroupUpdateSquadstates( self->NPC->group, self, SQUAD_STAND_AND_SHOOT ); - TIMER_Set( self, "stand", Q_irand( 1000, 3000 ) ); + // now make me stand around for a second or two at least + AI_GroupUpdateSquadstates(self->NPC->group, self, SQUAD_STAND_AND_SHOOT); + TIMER_Set(self, "stand", Q_irand(1000, 3000)); } -int ST_GetCPFlags( void ) -{ +int ST_GetCPFlags(void) { int cpFlags = 0; - if ( NPCS.NPC && NPCS.NPCInfo->group ) - { - if ( NPCS.NPC == NPCS.NPCInfo->group->commander && NPCS.NPC->client->NPC_class == CLASS_IMPERIAL ) - {//imperials hang back and give orders - if ( NPCS.NPCInfo->group->numGroup > 1 && Q_irand( -3, NPCS.NPCInfo->group->numGroup ) > 1 ) - {//FIXME: make sure he;s giving orders with these lines - if ( Q_irand( 0, 1 ) ) - { - ST_Speech( NPCS.NPC, SPEECH_CHASE, 0.5 ); - } - else - { - ST_Speech( NPCS.NPC, SPEECH_YELL, 0.5 ); + if (NPCS.NPC && NPCS.NPCInfo->group) { + if (NPCS.NPC == NPCS.NPCInfo->group->commander && NPCS.NPC->client->NPC_class == CLASS_IMPERIAL) { // imperials hang back and give orders + if (NPCS.NPCInfo->group->numGroup > 1 && Q_irand(-3, NPCS.NPCInfo->group->numGroup) > 1) { // FIXME: make sure he;s giving orders with these lines + if (Q_irand(0, 1)) { + ST_Speech(NPCS.NPC, SPEECH_CHASE, 0.5); + } else { + ST_Speech(NPCS.NPC, SPEECH_YELL, 0.5); } } - cpFlags = (CP_CLEAR|CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); - } - else if ( NPCS.NPCInfo->group->morale < 0 ) - {//hide - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE|CP_RETREAT); - } - else if ( NPCS.NPCInfo->group->morale < NPCS.NPCInfo->group->numGroup ) - {//morale is low for our size + cpFlags = (CP_CLEAR | CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); + } else if (NPCS.NPCInfo->group->morale < 0) { // hide + cpFlags = (CP_COVER | CP_AVOID | CP_SAFE | CP_RETREAT); + } else if (NPCS.NPCInfo->group->morale < NPCS.NPCInfo->group->numGroup) { // morale is low for our size int moraleDrop = NPCS.NPCInfo->group->numGroup - NPCS.NPCInfo->group->morale; - if ( moraleDrop < -6 ) - {//flee (no clear shot needed) - cpFlags = (CP_FLEE|CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < -3 ) - {//retreat (no clear shot needed) - cpFlags = (CP_RETREAT|CP_COVER|CP_AVOID|CP_SAFE); - } - else if ( moraleDrop < 0 ) - {//cover (no clear shot needed) - cpFlags = (CP_COVER|CP_AVOID|CP_SAFE); - } - } - else - { + if (moraleDrop < -6) { // flee (no clear shot needed) + cpFlags = (CP_FLEE | CP_RETREAT | CP_COVER | CP_AVOID | CP_SAFE); + } else if (moraleDrop < -3) { // retreat (no clear shot needed) + cpFlags = (CP_RETREAT | CP_COVER | CP_AVOID | CP_SAFE); + } else if (moraleDrop < 0) { // cover (no clear shot needed) + cpFlags = (CP_COVER | CP_AVOID | CP_SAFE); + } + } else { int moraleBoost = NPCS.NPCInfo->group->morale - NPCS.NPCInfo->group->numGroup; - if ( moraleBoost > 20 ) - {//charge to any one and outflank (no cover needed) - cpFlags = (CP_CLEAR|CP_FLANK|CP_APPROACH_ENEMY); - } - else if ( moraleBoost > 15 ) - {//charge to closest one (no cover needed) - cpFlags = (CP_CLEAR|CP_CLOSEST|CP_APPROACH_ENEMY); - } - else if ( moraleBoost > 10 ) - {//charge closer (no cover needed) - cpFlags = (CP_CLEAR|CP_APPROACH_ENEMY); + if (moraleBoost > 20) { // charge to any one and outflank (no cover needed) + cpFlags = (CP_CLEAR | CP_FLANK | CP_APPROACH_ENEMY); + } else if (moraleBoost > 15) { // charge to closest one (no cover needed) + cpFlags = (CP_CLEAR | CP_CLOSEST | CP_APPROACH_ENEMY); + } else if (moraleBoost > 10) { // charge closer (no cover needed) + cpFlags = (CP_CLEAR | CP_APPROACH_ENEMY); } } } - if ( !cpFlags ) - { - //at some medium level of morale - switch( Q_irand( 0, 3 ) ) - { - case 0://just take the nearest one - cpFlags = (CP_CLEAR|CP_COVER|CP_NEAREST); + if (!cpFlags) { + // at some medium level of morale + switch (Q_irand(0, 3)) { + case 0: // just take the nearest one + cpFlags = (CP_CLEAR | CP_COVER | CP_NEAREST); break; - case 1://take one closer to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_APPROACH_ENEMY); + case 1: // take one closer to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_APPROACH_ENEMY); break; - case 2://take the one closest to the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_CLOSEST|CP_APPROACH_ENEMY); + case 2: // take the one closest to the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_CLOSEST | CP_APPROACH_ENEMY); break; - case 3://take the one on the other side of the enemy - cpFlags = (CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); + case 3: // take the one on the other side of the enemy + cpFlags = (CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); break; } } - if ( NPCS.NPC && (NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST) ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCS.NPC && (NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST)) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } return cpFlags; @@ -1757,65 +1505,55 @@ FIXME: work in pairs? ------------------------- */ -void ST_Commander( void ) -{ - int i, j; - int cp, cpFlags_org, cpFlags; - AIGroupInfo_t *group = NPCS.NPCInfo->group; - gentity_t *member;//, *buddy; - qboolean runner = qfalse; - qboolean enemyLost = qfalse; - qboolean enemyProtected = qfalse; -// qboolean scouting = qfalse; - int squadState; - int curMemberNum, lastMemberNum; - float avoidDist; +void ST_Commander(void) { + int i, j; + int cp, cpFlags_org, cpFlags; + AIGroupInfo_t *group = NPCS.NPCInfo->group; + gentity_t *member; //, *buddy; + qboolean runner = qfalse; + qboolean enemyLost = qfalse; + qboolean enemyProtected = qfalse; + // qboolean scouting = qfalse; + int squadState; + int curMemberNum, lastMemberNum; + float avoidDist; group->processed = qtrue; - if ( group->enemy == NULL || group->enemy->client == NULL ) - {//hmm, no enemy...?! + if (group->enemy == NULL || group->enemy->client == NULL) { // hmm, no enemy...?! return; } - //FIXME: have this group commander check the enemy group (if any) and see if they have + // FIXME: have this group commander check the enemy group (if any) and see if they have // superior numbers. If they do, fall back rather than advance. If you have // superior numbers, advance on them. - //FIXME: find the group commander and have him occasionally give orders when there is speech - //FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left + // FIXME: find the group commander and have him occasionally give orders when there is speech + // FIXME: start fleeing when only a couple of you vs. a lightsaber, possibly give up if the only one left SaveNPCGlobals(); - if ( group->lastSeenEnemyTime < level.time - 180000 ) - {//dissolve the group - ST_Speech( NPCS.NPC, SPEECH_LOST, 0.0f ); - group->enemy->waypoint = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - for ( i = 0; i < group->numGroup; i++ ) - { + if (group->lastSeenEnemyTime < level.time - 180000) { // dissolve the group + ST_Speech(NPCS.NPC, SPEECH_LOST, 0.0f); + group->enemy->waypoint = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - SetNPCGlobals( member ); - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't break from that + SetNPCGlobals(member); + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, + TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't break from that continue; } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to move on my own + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to move on my own continue; } - //Lost enemy for three minutes? go into search mode? - G_ClearEnemy( NPCS.NPC ); - NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt( NPCS.NPC, group->enemy->waypoint ); - if ( NPCS.NPC->waypoint == WAYPOINT_NONE ) - { - NPCS.NPCInfo->behaviorState = BS_DEFAULT;//BS_PATROL; - } - else if ( group->enemy->waypoint == WAYPOINT_NONE || (trap->Nav_GetPathCost( NPCS.NPC->waypoint, group->enemy->waypoint ) >= Q3_INFINITE) ) - { - NPC_BSSearchStart( NPCS.NPC->waypoint, BS_SEARCH ); - } - else - { - NPC_BSSearchStart( group->enemy->waypoint, BS_SEARCH ); + // Lost enemy for three minutes? go into search mode? + G_ClearEnemy(NPCS.NPC); + NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt(NPCS.NPC, group->enemy->waypoint); + if (NPCS.NPC->waypoint == WAYPOINT_NONE) { + NPCS.NPCInfo->behaviorState = BS_DEFAULT; // BS_PATROL; + } else if (group->enemy->waypoint == WAYPOINT_NONE || (trap->Nav_GetPathCost(NPCS.NPC->waypoint, group->enemy->waypoint) >= Q3_INFINITE)) { + NPC_BSSearchStart(NPCS.NPC->waypoint, BS_SEARCH); + } else { + NPC_BSSearchStart(group->enemy->waypoint, BS_SEARCH); } } group->enemy = NULL; @@ -1823,8 +1561,7 @@ void ST_Commander( void ) return; } - - //See if anyone in our group is not alerted and alert them + // See if anyone in our group is not alerted and alert them /* for ( i = 0; i < group->numGroup; i++ ) { @@ -1846,139 +1583,110 @@ void ST_Commander( void ) } } */ - //Okay, everyone is mad + // Okay, everyone is mad - //see if anyone is running - if ( group->numState[SQUAD_SCOUT] > 0 || - group->numState[SQUAD_TRANSITION] > 0 || - group->numState[SQUAD_RETREAT] > 0 ) - {//someone is running + // see if anyone is running + if (group->numState[SQUAD_SCOUT] > 0 || group->numState[SQUAD_TRANSITION] > 0 || group->numState[SQUAD_RETREAT] > 0) { // someone is running runner = qtrue; } - if ( /*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && group->lastSeenEnemyTime < level.time - 30000 ) - {//no-one has seen the enemy for 30 seconds// and no-one is running after him - if ( group->commander && !Q_irand( 0, 1 ) ) - { - ST_Speech( group->commander, SPEECH_ESCAPING, 0.0f ); + if (/*!runner &&*/ group->lastSeenEnemyTime > level.time - 32000 && + group->lastSeenEnemyTime < level.time - 30000) { // no-one has seen the enemy for 30 seconds// and no-one is running after him + if (group->commander && !Q_irand(0, 1)) { + ST_Speech(group->commander, SPEECH_ESCAPING, 0.0f); + } else { + ST_Speech(NPCS.NPC, SPEECH_ESCAPING, 0.0f); } - else - { - ST_Speech( NPCS.NPC, SPEECH_ESCAPING, 0.0f ); - } - //don't say this again + // don't say this again NPCS.NPCInfo->blockedSpeechDebounceTime = level.time + 3000; } - if ( group->lastSeenEnemyTime < level.time - 10000 ) - {//no-one has seen the enemy for at least 10 seconds! Should send a scout + if (group->lastSeenEnemyTime < level.time - 10000) { // no-one has seen the enemy for at least 10 seconds! Should send a scout enemyLost = qtrue; } - if ( group->lastClearShotTime < level.time - 5000 ) - {//no-one has had a clear shot for 5 seconds! + if (group->lastClearShotTime < level.time - 5000) { // no-one has had a clear shot for 5 seconds! enemyProtected = qtrue; } - //Go through the list: + // Go through the list: - //Everyone should try to get to a combat point if possible - if ( d_asynchronousGroupAI.integer ) - {//do one member a turn + // Everyone should try to get to a combat point if possible + if (d_asynchronousGroupAI.integer) { // do one member a turn group->activeMemberNum++; - if ( group->activeMemberNum >= group->numGroup ) - { + if (group->activeMemberNum >= group->numGroup) { group->activeMemberNum = 0; } curMemberNum = group->activeMemberNum; lastMemberNum = curMemberNum + 1; - } - else - { + } else { curMemberNum = 0; lastMemberNum = group->numGroup; } - for ( i = curMemberNum; i < lastMemberNum; i++ ) - { - //reset combat point flags + for (i = curMemberNum; i < lastMemberNum; i++) { + // reset combat point flags cp = -1; cpFlags = 0; squadState = SQUAD_IDLE; avoidDist = 0; - // scouting = qfalse; + // scouting = qfalse; - //get the next guy + // get the next guy member = &g_entities[group->member[i].number]; - if ( !member->enemy ) - {//don't include guys that aren't angry + if (!member->enemy) { // don't include guys that aren't angry continue; } - SetNPCGlobals( member ); + SetNPCGlobals(member); - if ( !TIMER_Done( NPCS.NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPCS.NPC, "flee")) { // running away continue; } - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go continue; } - if ( NPCS.NPC->s.weapon == WP_NONE - && NPCS.NPCInfo->goalEntity - && NPCS.NPCInfo->goalEntity == NPCS.NPCInfo->tempGoal - && NPCS.NPCInfo->goalEntity->enemy - && NPCS.NPCInfo->goalEntity->enemy->s.eType == ET_ITEM ) - {//running to pick up a gun, don't do other logic + if (NPCS.NPC->s.weapon == WP_NONE && NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPCInfo->tempGoal && + NPCS.NPCInfo->goalEntity->enemy && NPCS.NPCInfo->goalEntity->enemy->s.eType == ET_ITEM) { // running to pick up a gun, don't do other logic continue; } - //see if this member should start running (only if have no officer... FIXME: should always run from AEL_DANGER_GREAT?) - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { - if ( NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//going to run - ST_Speech( NPCS.NPC, SPEECH_COVER, 0 ); + // see if this member should start running (only if have no officer... FIXME: should always run from AEL_DANGER_GREAT?) + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { + if (NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // going to run + ST_Speech(NPCS.NPC, SPEECH_COVER, 0); continue; } } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not allowed to do combat-movement + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not allowed to do combat-movement continue; } - //check the local state - if ( NPCS.NPCInfo->squadState != SQUAD_RETREAT ) - {//not already retreating - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - {//weaponless, should be hiding - if ( NPCS.NPCInfo->goalEntity == NULL || NPCS.NPCInfo->goalEntity->enemy == NULL || NPCS.NPCInfo->goalEntity->enemy->s.eType != ET_ITEM ) - {//not running after a pickup - if ( TIMER_Done( NPCS.NPC, "hideTime" ) || (DistanceSquared( group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) < 65536 && NPC_ClearLOS4( NPCS.NPC->enemy )) ) - {//done hiding or enemy near and can see us - //er, start another flee I guess? - NPC_StartFlee( NPCS.NPC->enemy, NPCS.NPC->enemy->r.currentOrigin, AEL_DANGER_GREAT, 5000, 10000 ); - }//else, just hang here + // check the local state + if (NPCS.NPCInfo->squadState != SQUAD_RETREAT) { // not already retreating + if (NPCS.NPC->client->ps.weapon == WP_NONE) { // weaponless, should be hiding + if (NPCS.NPCInfo->goalEntity == NULL || NPCS.NPCInfo->goalEntity->enemy == NULL || + NPCS.NPCInfo->goalEntity->enemy->s.eType != ET_ITEM) { // not running after a pickup + if (TIMER_Done(NPCS.NPC, "hideTime") || (DistanceSquared(group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin) < 65536 && + NPC_ClearLOS4(NPCS.NPC->enemy))) { // done hiding or enemy near and can see us + // er, start another flee I guess? + NPC_StartFlee(NPCS.NPC->enemy, NPCS.NPC->enemy->r.currentOrigin, AEL_DANGER_GREAT, 5000, 10000); + } // else, just hang here } continue; } - if ( TIMER_Done( NPCS.NPC, "roamTime" ) && TIMER_Done( NPCS.NPC, "hideTime" ) && NPCS.NPC->health > 10 && !trap->InPVS( group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - {//cant even see enemy - //better go after him - cpFlags |= (CP_CLEAR|CP_COVER); - } - else if ( NPCS.NPCInfo->localState == LSTATE_UNDERFIRE ) - {//we've been shot - switch( group->enemy->client->ps.weapon ) - { + if (TIMER_Done(NPCS.NPC, "roamTime") && TIMER_Done(NPCS.NPC, "hideTime") && NPCS.NPC->health > 10 && + !trap->InPVS(group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { // cant even see enemy + // better go after him + cpFlags |= (CP_CLEAR | CP_COVER); + } else if (NPCS.NPCInfo->localState == LSTATE_UNDERFIRE) { // we've been shot + switch (group->enemy->client->ps.weapon) { case WP_SABER: - if ( DistanceSquared( group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) < 65536 )//256 squared + if (DistanceSquared(group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin) < 65536) // 256 squared { - cpFlags |= (CP_AVOID_ENEMY|CP_COVER|CP_AVOID|CP_RETREAT); - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { + cpFlags |= (CP_AVOID_ENEMY | CP_COVER | CP_AVOID | CP_RETREAT); + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { squadState = SQUAD_RETREAT; } avoidDist = 256; @@ -1989,41 +1697,29 @@ void ST_Commander( void ) cpFlags |= (CP_COVER); break; } - if ( NPCS.NPC->health <= 10 ) - { - if ( !group->commander || group->commander->NPC->rank < RANK_ENSIGN ) - { - cpFlags |= (CP_FLEE|CP_AVOID|CP_RETREAT); + if (NPCS.NPC->health <= 10) { + if (!group->commander || group->commander->NPC->rank < RANK_ENSIGN) { + cpFlags |= (CP_FLEE | CP_AVOID | CP_RETREAT); squadState = SQUAD_RETREAT; } } - } - else - {//not hit, see if there are other reasons we should run - if ( trap->InPVS( NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin ) ) - {//in the same room as enemy - if ( NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER && - DistanceSquared( group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) < MIN_ROCKET_DIST_SQUARED && - NPCS.NPCInfo->squadState != SQUAD_TRANSITION ) - {//too close for me to fire my weapon and I'm not already on the move - cpFlags |= (CP_AVOID_ENEMY|CP_CLEAR|CP_AVOID); + } else { // not hit, see if there are other reasons we should run + if (trap->InPVS(NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin)) { // in the same room as enemy + if (NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER && + DistanceSquared(group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin) < MIN_ROCKET_DIST_SQUARED && + NPCS.NPCInfo->squadState != SQUAD_TRANSITION) { // too close for me to fire my weapon and I'm not already on the move + cpFlags |= (CP_AVOID_ENEMY | CP_CLEAR | CP_AVOID); avoidDist = 256; - } - else - { - switch( group->enemy->client->ps.weapon ) - { + } else { + switch (group->enemy->client->ps.weapon) { case WP_SABER: - //if ( group->enemy->client->ps.SaberLength() > 0 ) - if (!group->enemy->client->ps.saberHolstered) - { - if ( DistanceSquared( group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) < 65536 ) - { - if ( TIMER_Done( NPCS.NPC, "hideTime" ) ) - { - if ( NPCS.NPCInfo->squadState != SQUAD_TRANSITION ) - {//not already moving: FIXME: we need to see if where we're going is good now? - cpFlags |= (CP_AVOID_ENEMY|CP_CLEAR|CP_AVOID); + // if ( group->enemy->client->ps.SaberLength() > 0 ) + if (!group->enemy->client->ps.saberHolstered) { + if (DistanceSquared(group->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin) < 65536) { + if (TIMER_Done(NPCS.NPC, "hideTime")) { + if (NPCS.NPCInfo->squadState != + SQUAD_TRANSITION) { // not already moving: FIXME: we need to see if where we're going is good now? + cpFlags |= (CP_AVOID_ENEMY | CP_CLEAR | CP_AVOID); avoidDist = 256; } } @@ -2037,168 +1733,123 @@ void ST_Commander( void ) } } - if ( !cpFlags ) - {//okay, we have no new enemy-driven reason to run... let's use tactics now - if ( runner && NPCS.NPCInfo->combatPoint != -1 ) - {//someone is running and we have a combat point already - if ( NPCS.NPCInfo->squadState != SQUAD_SCOUT && - NPCS.NPCInfo->squadState != SQUAD_TRANSITION && - NPCS.NPCInfo->squadState != SQUAD_RETREAT ) - {//it's not us - if ( TIMER_Done( NPCS.NPC, "verifyCP" ) && DistanceSquared( NPCS.NPC->r.currentOrigin, level.combatPoints[NPCS.NPCInfo->combatPoint].origin ) > 64*64 ) - {//1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... - //uh, WTF, we're not on our combat point? - //er, try again, I guess? + if (!cpFlags) { // okay, we have no new enemy-driven reason to run... let's use tactics now + if (runner && NPCS.NPCInfo->combatPoint != -1) { // someone is running and we have a combat point already + if (NPCS.NPCInfo->squadState != SQUAD_SCOUT && NPCS.NPCInfo->squadState != SQUAD_TRANSITION && + NPCS.NPCInfo->squadState != SQUAD_RETREAT) { // it's not us + if (TIMER_Done(NPCS.NPC, "verifyCP") && + DistanceSquared(NPCS.NPC->r.currentOrigin, level.combatPoints[NPCS.NPCInfo->combatPoint].origin) > + 64 * 64) { // 1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... + // uh, WTF, we're not on our combat point? + // er, try again, I guess? cp = NPCS.NPCInfo->combatPoint; cpFlags |= ST_GetCPFlags(); + } else { // cover them + // stop ducking + TIMER_Set(NPCS.NPC, "duck", -1); + // start shooting + TIMER_Set(NPCS.NPC, "attackDelay", -1); + // AI should take care of the rest - fire at enemy } - else - {//cover them - //stop ducking - TIMER_Set( NPCS.NPC, "duck", -1 ); - //start shooting - TIMER_Set( NPCS.NPC, "attackDelay", -1 ); - //AI should take care of the rest - fire at enemy - } - } - else - {//we're running - //see if we're blocked - if ( NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED ) - {//dammit, something is in our way - //see if it's one of ours - for ( j = 0; j < group->numGroup; j++ ) - { - if ( group->member[j].number == NPCS.NPCInfo->blockingEntNum ) - {//we're being blocked by one of our own, pass our goal onto them and I'll stand still - ST_TransferMoveGoal( NPCS.NPC, &g_entities[group->member[j].number] ); + } else { // we're running + // see if we're blocked + if (NPCS.NPCInfo->aiFlags & NPCAI_BLOCKED) { // dammit, something is in our way + // see if it's one of ours + for (j = 0; j < group->numGroup; j++) { + if (group->member[j].number == + NPCS.NPCInfo->blockingEntNum) { // we're being blocked by one of our own, pass our goal onto them and I'll stand still + ST_TransferMoveGoal(NPCS.NPC, &g_entities[group->member[j].number]); break; } } } - //we don't need to do anything else + // we don't need to do anything else continue; } - } - else - {//okay no-one is running, use some tactics - if ( NPCS.NPCInfo->combatPoint != -1 ) - {//we have a combat point we're supposed to be running to - if ( NPCS.NPCInfo->squadState != SQUAD_SCOUT && - NPCS.NPCInfo->squadState != SQUAD_TRANSITION && - NPCS.NPCInfo->squadState != SQUAD_RETREAT ) - {//but we're not running - if ( TIMER_Done( NPCS.NPC, "verifyCP" ) ) - {//1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, you've stopped running... - if ( DistanceSquared( NPCS.NPC->r.currentOrigin, level.combatPoints[NPCS.NPCInfo->combatPoint].origin ) > 64*64 ) - {//uh, WTF, we're not on our combat point? - //er, try again, I guess? + } else { // okay no-one is running, use some tactics + if (NPCS.NPCInfo->combatPoint != -1) { // we have a combat point we're supposed to be running to + if (NPCS.NPCInfo->squadState != SQUAD_SCOUT && NPCS.NPCInfo->squadState != SQUAD_TRANSITION && + NPCS.NPCInfo->squadState != SQUAD_RETREAT) { // but we're not running + if (TIMER_Done(NPCS.NPC, "verifyCP")) { // 1 - 3 seconds have passed since you chose a CP, see if you're there since, for some reason, + // you've stopped running... + if (DistanceSquared(NPCS.NPC->r.currentOrigin, level.combatPoints[NPCS.NPCInfo->combatPoint].origin) > + 64 * 64) { // uh, WTF, we're not on our combat point? + // er, try again, I guess? cp = NPCS.NPCInfo->combatPoint; cpFlags |= ST_GetCPFlags(); } } } } - if ( enemyLost ) - {//if no-one has seen the enemy for a while, send a scout - //ask where he went - if ( group->numState[SQUAD_SCOUT] <= 0 ) - { - // scouting = qtrue; - NPC_ST_StoreMovementSpeech( SPEECH_CHASE, 0.0f ); + if (enemyLost) { // if no-one has seen the enemy for a while, send a scout + // ask where he went + if (group->numState[SQUAD_SCOUT] <= 0) { + // scouting = qtrue; + NPC_ST_StoreMovementSpeech(SPEECH_CHASE, 0.0f); } - //Since no-one else has done this, I should be the closest one, so go after him... - ST_TrackEnemy( NPCS.NPC, group->enemyLastSeenPos ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_SCOUT ); - //we're not using a cp, so we need to set runner to true right here + // Since no-one else has done this, I should be the closest one, so go after him... + ST_TrackEnemy(NPCS.NPC, group->enemyLastSeenPos); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_SCOUT); + // we're not using a cp, so we need to set runner to true right here runner = qtrue; - } - else if ( enemyProtected ) - {//if no-one has a clear shot at the enemy, someone should go after him - //FIXME: if I'm in an area where no safe combat points have a clear shot at me, they don't come after me... they should anyway, though after some extra hesitation. - //ALSO: seem to give up when behind an area portal? - //since no-one else here has done this, I should be the closest one - if ( TIMER_Done( NPCS.NPC, "roamTime" ) && !Q_irand( 0, group->numGroup) ) - {//only do this if we're ready to move again and we feel like it - cpFlags |= ST_ApproachEnemy( NPCS.NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_SCOUT ); + } else if (enemyProtected) { // if no-one has a clear shot at the enemy, someone should go after him + // FIXME: if I'm in an area where no safe combat points have a clear shot at me, they don't come after me... they should anyway, though + // after some extra hesitation. ALSO: seem to give up when behind an area portal? since no-one else here has done this, I should be the + // closest one + if (TIMER_Done(NPCS.NPC, "roamTime") && !Q_irand(0, group->numGroup)) { // only do this if we're ready to move again and we feel like it + cpFlags |= ST_ApproachEnemy(NPCS.NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_SCOUT); } - } - else - {//group can see and has been shooting at the enemy - //see if we should do something fancy? - - {//we're ready to move - if ( NPCS.NPCInfo->combatPoint == -1 ) - {//we're not on a combat point - if ( 1 )//!Q_irand( 0, 2 ) ) - {//we should go for a combat point + } else { // group can see and has been shooting at the enemy + // see if we should do something fancy? + + { // we're ready to move + if (NPCS.NPCInfo->combatPoint == -1) { // we're not on a combat point + if (1) //! Q_irand( 0, 2 ) ) + { // we should go for a combat point cpFlags |= ST_GetCPFlags(); + } else { + TIMER_Set(NPCS.NPC, "stick", Q_irand(2000, 4000)); + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(1000, 3000)); } - else - { - TIMER_Set( NPCS.NPC, "stick", Q_irand( 2000, 4000 ) ); - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 1000, 3000 ) ); - } - } - else if ( TIMER_Done( NPCS.NPC, "roamTime" ) ) - {//we are already on a combat point - if ( i == 0 ) - {//we're the closest - if ( (group->morale-group->numGroup>0) && !Q_irand( 0, 4 ) ) - {//try to outflank him - cpFlags |= (CP_CLEAR|CP_COVER|CP_FLANK|CP_APPROACH_ENEMY); - } - else if ( (group->morale-group->numGroup<0) ) - {//better move! + } else if (TIMER_Done(NPCS.NPC, "roamTime")) { // we are already on a combat point + if (i == 0) { // we're the closest + if ((group->morale - group->numGroup > 0) && !Q_irand(0, 4)) { // try to outflank him + cpFlags |= (CP_CLEAR | CP_COVER | CP_FLANK | CP_APPROACH_ENEMY); + } else if ((group->morale - group->numGroup < 0)) { // better move! cpFlags |= ST_GetCPFlags(); + } else { // If we're point, then get down + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(2000, 5000)); + TIMER_Set(NPCS.NPC, "stick", Q_irand(2000, 5000)); + // FIXME: what if we can't shoot from a ducked pos? + TIMER_Set(NPCS.NPC, "duck", Q_irand(3000, 4000)); + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_POINT); } - else - {//If we're point, then get down - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 2000, 5000 ) ); - TIMER_Set( NPCS.NPC, "stick", Q_irand( 2000, 5000 ) ); - //FIXME: what if we can't shoot from a ducked pos? - TIMER_Set( NPCS.NPC, "duck", Q_irand( 3000, 4000 ) ); - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_POINT ); - } - } - else if ( i == group->numGroup - 1 ) - {//farthest from the enemy - if ( (group->morale-group->numGroup<0) ) - {//low morale, just hang here - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 2000, 5000 ) ); - TIMER_Set( NPCS.NPC, "stick", Q_irand( 2000, 5000 ) ); - } - else if ( (group->morale-group->numGroup>0) ) - {//try to move in on the enemy - cpFlags |= ST_ApproachEnemy( NPCS.NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_SCOUT ); - } - else - {//use normal decision making process + } else if (i == group->numGroup - 1) { // farthest from the enemy + if ((group->morale - group->numGroup < 0)) { // low morale, just hang here + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(2000, 5000)); + TIMER_Set(NPCS.NPC, "stick", Q_irand(2000, 5000)); + } else if ((group->morale - group->numGroup > 0)) { // try to move in on the enemy + cpFlags |= ST_ApproachEnemy(NPCS.NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_SCOUT); + } else { // use normal decision making process cpFlags |= ST_GetCPFlags(); } - } - else - {//someone in-between - if ( (group->morale-group->numGroup<0) || !Q_irand( 0, 4 ) ) - {//do something + } else { // someone in-between + if ((group->morale - group->numGroup < 0) || !Q_irand(0, 4)) { // do something cpFlags |= ST_GetCPFlags(); - } - else - { - TIMER_Set( NPCS.NPC, "stick", Q_irand( 2000, 4000 ) ); - TIMER_Set( NPCS.NPC, "roamTime", Q_irand( 2000, 4000 ) ); + } else { + TIMER_Set(NPCS.NPC, "stick", Q_irand(2000, 4000)); + TIMER_Set(NPCS.NPC, "roamTime", Q_irand(2000, 4000)); } } } } - if ( !cpFlags ) - {//still not moving - //see if we should say something? + if (!cpFlags) { // still not moving + // see if we should say something? /* if ( NPC->attackDebounceTime < level.time - 2000 ) {//we, personally, haven't shot for 2 seconds @@ -2207,38 +1858,32 @@ void ST_Commander( void ) } */ - //see if we should do other fun stuff - //toy with ducking - if ( TIMER_Done( NPCS.NPC, "duck" ) ) - {//not ducking - if ( TIMER_Done( NPCS.NPC, "stand" ) ) - {//don't have to keep standing - if ( NPCS.NPCInfo->combatPoint == -1 || (level.combatPoints[NPCS.NPCInfo->combatPoint].flags&CPF_DUCK) ) - {//okay to duck here - if ( !Q_irand( 0, 3 ) ) - { - TIMER_Set( NPCS.NPC, "duck", Q_irand( 1000, 3000 ) ); + // see if we should do other fun stuff + // toy with ducking + if (TIMER_Done(NPCS.NPC, "duck")) { // not ducking + if (TIMER_Done(NPCS.NPC, "stand")) { // don't have to keep standing + if (NPCS.NPCInfo->combatPoint == -1 || (level.combatPoints[NPCS.NPCInfo->combatPoint].flags & CPF_DUCK)) { // okay to duck here + if (!Q_irand(0, 3)) { + TIMER_Set(NPCS.NPC, "duck", Q_irand(1000, 3000)); } } } } - //FIXME: what about CPF_LEAN? + // FIXME: what about CPF_LEAN? } } } } - //clear the local state + // clear the local state NPCS.NPCInfo->localState = LSTATE_NONE; - if ( NPCS.NPCInfo->scriptFlags&SCF_USE_CP_NEAREST ) - { - cpFlags &= ~(CP_FLANK|CP_APPROACH_ENEMY|CP_CLOSEST); + if (NPCS.NPCInfo->scriptFlags & SCF_USE_CP_NEAREST) { + cpFlags &= ~(CP_FLANK | CP_APPROACH_ENEMY | CP_CLOSEST); cpFlags |= CP_NEAREST; } - //Assign combat points - if ( cpFlags ) - {//we want to run to a combat point + // Assign combat points + if (cpFlags) { // we want to run to a combat point /* if ( NPCInfo->combatPoint != -1 ) {//if we're on a combat point, we obviously don't want the one we're closest to @@ -2246,126 +1891,90 @@ void ST_Commander( void ) } */ - if ( group->enemy->client->ps.weapon == WP_SABER && /*group->enemy->client->ps.SaberLength() > 0*/!group->enemy->client->ps.saberHolstered ) - {//we obviously want to avoid the enemy if he has a saber + if (group->enemy->client->ps.weapon == WP_SABER && /*group->enemy->client->ps.SaberLength() > 0*/ !group->enemy->client->ps + .saberHolstered) { // we obviously want to avoid the enemy if he has a saber cpFlags |= CP_AVOID_ENEMY; avoidDist = 256; } - //remember what we *wanted* to do... + // remember what we *wanted* to do... cpFlags_org = cpFlags; - //now get a combat point - if ( cp == -1 ) - {//may have had sone set above - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, cpFlags|CP_HAS_ROUTE, avoidDist, NPCS.NPCInfo->lastFailedCombatPoint ); + // now get a combat point + if (cp == -1) { // may have had sone set above + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, cpFlags | CP_HAS_ROUTE, avoidDist, + NPCS.NPCInfo->lastFailedCombatPoint); } - while ( cp == -1 && cpFlags != CP_ANY ) - {//start "OR"ing out certain flags to see if we can find *any* point - if ( cpFlags & CP_INVESTIGATE ) - {//don't need to investigate + while (cp == -1 && cpFlags != CP_ANY) { // start "OR"ing out certain flags to see if we can find *any* point + if (cpFlags & CP_INVESTIGATE) { // don't need to investigate cpFlags &= ~CP_INVESTIGATE; - } - else if ( cpFlags & CP_SQUAD ) - {//don't need to stick to squads + } else if (cpFlags & CP_SQUAD) { // don't need to stick to squads cpFlags &= ~CP_SQUAD; - } - else if ( cpFlags & CP_DUCK ) - {//don't need to duck + } else if (cpFlags & CP_DUCK) { // don't need to duck cpFlags &= ~CP_DUCK; - } - else if ( cpFlags & CP_NEAREST ) - {//don't need closest one to me + } else if (cpFlags & CP_NEAREST) { // don't need closest one to me cpFlags &= ~CP_NEAREST; - } - else if ( cpFlags & CP_FLANK ) - {//don't need to flank enemy + } else if (cpFlags & CP_FLANK) { // don't need to flank enemy cpFlags &= ~CP_FLANK; - } - else if ( cpFlags & CP_SAFE ) - {//don't need one that hasn't been shot at recently + } else if (cpFlags & CP_SAFE) { // don't need one that hasn't been shot at recently cpFlags &= ~CP_SAFE; - } - else if ( cpFlags & CP_CLOSEST ) - {//don't need to get closest to enemy + } else if (cpFlags & CP_CLOSEST) { // don't need to get closest to enemy cpFlags &= ~CP_CLOSEST; - //but let's try to approach at least + // but let's try to approach at least cpFlags |= CP_APPROACH_ENEMY; - } - else if ( cpFlags & CP_APPROACH_ENEMY ) - {//don't need to approach enemy + } else if (cpFlags & CP_APPROACH_ENEMY) { // don't need to approach enemy cpFlags &= ~CP_APPROACH_ENEMY; - } - else if ( cpFlags & CP_COVER ) - {//don't need cover + } else if (cpFlags & CP_COVER) { // don't need cover cpFlags &= ~CP_COVER; - //but let's pick one that makes us duck + // but let's pick one that makes us duck cpFlags |= CP_DUCK; - } - else if ( cpFlags & CP_CLEAR ) - {//don't need a clear shot to enemy + } else if (cpFlags & CP_CLEAR) { // don't need a clear shot to enemy cpFlags &= ~CP_CLEAR; - } - else if ( cpFlags & CP_AVOID_ENEMY ) - {//don't need to avoid enemy + } else if (cpFlags & CP_AVOID_ENEMY) { // don't need to avoid enemy cpFlags &= ~CP_AVOID_ENEMY; - } - else if ( cpFlags & CP_RETREAT ) - {//don't need to retreat + } else if (cpFlags & CP_RETREAT) { // don't need to retreat cpFlags &= ~CP_RETREAT; - } - else if ( cpFlags &CP_FLEE ) - {//don't need to flee + } else if (cpFlags & CP_FLEE) { // don't need to flee cpFlags &= ~CP_FLEE; - //but at least avoid enemy and pick one that gives cover - cpFlags |= (CP_COVER|CP_AVOID_ENEMY); - } - else if ( cpFlags & CP_AVOID ) - {//okay, even pick one right by me + // but at least avoid enemy and pick one that gives cover + cpFlags |= (CP_COVER | CP_AVOID_ENEMY); + } else if (cpFlags & CP_AVOID) { // okay, even pick one right by me cpFlags &= ~CP_AVOID; - } - else - { + } else { cpFlags = CP_ANY; } - //now try again - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, cpFlags|CP_HAS_ROUTE, avoidDist, -1 ); + // now try again + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, cpFlags | CP_HAS_ROUTE, avoidDist, + -1); } - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - //let others know that someone is now running + // see if we got a valid one + if (cp != -1) { // found a combat point + // let others know that someone is now running runner = qtrue; - //don't change course again until we get to where we're going - TIMER_Set( NPCS.NPC, "roamTime", Q3_INFINITE ); - TIMER_Set( NPCS.NPC, "verifyCP", Q_irand( 1000, 3000 ) );//don't make sure you're in your CP for 1 - 3 seconds - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL ); - //okay, try a move right now to see if we can even get there - - //if ( ST_Move() ) - {//we actually can get to it, so okay to say you're going there. - //FIXME: Hmm... any way we can store this move info so we don't have to do it again + // don't change course again until we get to where we're going + TIMER_Set(NPCS.NPC, "roamTime", Q3_INFINITE); + TIMER_Set(NPCS.NPC, "verifyCP", Q_irand(1000, 3000)); // don't make sure you're in your CP for 1 - 3 seconds + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL); + // okay, try a move right now to see if we can even get there + + // if ( ST_Move() ) + { // we actually can get to it, so okay to say you're going there. + // FIXME: Hmm... any way we can store this move info so we don't have to do it again // when our turn to think comes up? - //set us up so others know we're on the move - if ( squadState != SQUAD_IDLE ) - { - AI_GroupUpdateSquadstates( group, NPCS.NPC, squadState ); - } - else if ( cpFlags&CP_FLEE ) - {//outright running for your life - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_RETREAT ); - } - else - {//any other kind of transition between combat points - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_TRANSITION ); + // set us up so others know we're on the move + if (squadState != SQUAD_IDLE) { + AI_GroupUpdateSquadstates(group, NPCS.NPC, squadState); + } else if (cpFlags & CP_FLEE) { // outright running for your life + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_RETREAT); + } else { // any other kind of transition between combat points + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_TRANSITION); } - //unless we're trying to flee, walk slowly - if ( !(cpFlags_org&CP_FLEE) ) - { - //ucmd.buttons |= BUTTON_CAREFUL; + // unless we're trying to flee, walk slowly + if (!(cpFlags_org & CP_FLEE)) { + // ucmd.buttons |= BUTTON_CAREFUL; } /* @@ -2376,38 +1985,30 @@ void ST_Commander( void ) //group->speechDebounceTime = level.time + 5000; } //flanking: - else */if ( cpFlags & CP_FLANK ) - { - if ( group->numGroup > 1 ) - { - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); + else */ + if (cpFlags & CP_FLANK) { + if (group->numGroup > 1) { + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); } - } - else - {//okay, let's cheat - if ( group->numGroup > 1 ) - { - float dot = 1.0f; - if ( !Q_irand( 0, 3 ) ) - {//25% of the time, see if we're flanking the enemy - vec3_t eDir2Me, eDir2CP; + } else { // okay, let's cheat + if (group->numGroup > 1) { + float dot = 1.0f; + if (!Q_irand(0, 3)) { // 25% of the time, see if we're flanking the enemy + vec3_t eDir2Me, eDir2CP; - VectorSubtract( NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, eDir2Me ); - VectorNormalize( eDir2Me ); + VectorSubtract(NPCS.NPC->r.currentOrigin, group->enemy->r.currentOrigin, eDir2Me); + VectorNormalize(eDir2Me); - VectorSubtract( level.combatPoints[NPCS.NPCInfo->combatPoint].origin, group->enemy->r.currentOrigin, eDir2CP ); - VectorNormalize( eDir2CP ); + VectorSubtract(level.combatPoints[NPCS.NPCInfo->combatPoint].origin, group->enemy->r.currentOrigin, eDir2CP); + VectorNormalize(eDir2CP); - dot = DotProduct( eDir2Me, eDir2CP ); + dot = DotProduct(eDir2Me, eDir2CP); } - if ( dot < 0.4 ) - {//flanking! - NPC_ST_StoreMovementSpeech( SPEECH_OUTFLANK, -1 ); - } - else if ( !Q_irand( 0, 10 ) ) - {//regular movement - NPC_ST_StoreMovementSpeech( SPEECH_YELL, 0.2f );//was SPEECH_COVER + if (dot < 0.4) { // flanking! + NPC_ST_StoreMovementSpeech(SPEECH_OUTFLANK, -1); + } else if (!Q_irand(0, 10)) { // regular movement + NPC_ST_StoreMovementSpeech(SPEECH_YELL, 0.2f); // was SPEECH_COVER } } } @@ -2420,14 +2021,12 @@ void ST_Commander( void ) } } */ - }//else: nothing, a failed move should clear the combatPoint and you can try again next frame - } - else if ( NPCS.NPCInfo->squadState == SQUAD_SCOUT ) - {//we couldn't find a combatPoint by the player, so just go after him directly - ST_HuntEnemy( NPCS.NPC ); - //set me into scout mode - AI_GroupUpdateSquadstates( group, NPCS.NPC, SQUAD_SCOUT ); - //AI should take care of rest + } // else: nothing, a failed move should clear the combatPoint and you can try again next frame + } else if (NPCS.NPCInfo->squadState == SQUAD_SCOUT) { // we couldn't find a combatPoint by the player, so just go after him directly + ST_HuntEnemy(NPCS.NPC); + // set me into scout mode + AI_GroupUpdateSquadstates(group, NPCS.NPC, SQUAD_SCOUT); + // AI should take care of rest } } } @@ -2442,81 +2041,64 @@ NPC_BSST_Attack ------------------------- */ -void NPC_BSST_Attack( void ) -{ - vec3_t enemyDir, shootDir; +void NPC_BSST_Attack(void) { + vec3_t enemyDir, shootDir; float dot; - //Don't do anything if we're hurt - if ( NPCS.NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // Don't do anything if we're hurt + if (NPCS.NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - //NPC_CheckEnemy( qtrue, qfalse ); - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse )//!NPC->enemy )// + // NPC_CheckEnemy( qtrue, qfalse ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt(qfalse) == qfalse) //! NPC->enemy )// { NPCS.NPC->enemy = NULL; - if( NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER ) - { + if (NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER) { NPC_BSPatrol(); - } - else - { - NPC_BSST_Patrol();//FIXME: or patrol? + } else { + NPC_BSST_Patrol(); // FIXME: or patrol? } return; } - //FIXME: put some sort of delay into the guys depending on how they saw you...? + // FIXME: put some sort of delay into the guys depending on how they saw you...? - //Get our group info - if ( TIMER_Done( NPCS.NPC, "interrogating" ) ) - { - AI_GetGroup( NPCS.NPC );//, 45, 512, NPC->enemy ); - } - else - { - //FIXME: when done interrogating, I should send out a team alert! + // Get our group info + if (TIMER_Done(NPCS.NPC, "interrogating")) { + AI_GetGroup(NPCS.NPC); //, 45, 512, NPC->enemy ); + } else { + // FIXME: when done interrogating, I should send out a team alert! } - if ( NPCS.NPCInfo->group ) - {//I belong to a squad of guys - we should *always* have a group - if ( !NPCS.NPCInfo->group->processed ) - {//I'm the first ent in my group, I'll make the command decisions -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS + if (NPCS.NPCInfo->group) { // I belong to a squad of guys - we should *always* have a group + if (!NPCS.NPCInfo->group->processed) { // I'm the first ent in my group, I'll make the command decisions +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS ST_Commander(); -#if AI_TIMERS - int commTime = GetTime ( startTime ); - if ( commTime > 20 ) - { - trap->Printf( S_COLOR_RED"ERROR: Commander time: %d\n", commTime ); - } - else if ( commTime > 10 ) - { - trap->Printf( S_COLOR_YELLOW"WARNING: Commander time: %d\n", commTime ); - } - else if ( commTime > 2 ) - { - trap->Printf( S_COLOR_GREEN"Commander time: %d\n", commTime ); - } -#endif// AI_TIMERS - } - } - else if ( TIMER_Done( NPCS.NPC, "flee" ) && NPC_CheckForDanger( NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_DANGER ) ) ) - {//not already fleeing, and going to run - ST_Speech( NPCS.NPC, SPEECH_COVER, 0 ); - NPC_UpdateAngles( qtrue, qtrue ); +#if AI_TIMERS + int commTime = GetTime(startTime); + if (commTime > 20) { + trap->Printf(S_COLOR_RED "ERROR: Commander time: %d\n", commTime); + } else if (commTime > 10) { + trap->Printf(S_COLOR_YELLOW "WARNING: Commander time: %d\n", commTime); + } else if (commTime > 2) { + trap->Printf(S_COLOR_GREEN "Commander time: %d\n", commTime); + } +#endif // AI_TIMERS + } + } else if (TIMER_Done(NPCS.NPC, "flee") && + NPC_CheckForDanger(NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_DANGER))) { // not already fleeing, and going to run + ST_Speech(NPCS.NPC, SPEECH_COVER, 0); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( !NPCS.NPC->enemy ) - {//WTF? somehow we lost our enemy? - NPC_BSST_Patrol();//FIXME: or patrol? + if (!NPCS.NPC->enemy) { // WTF? somehow we lost our enemy? + NPC_BSST_Patrol(); // FIXME: or patrol? return; } @@ -2525,254 +2107,199 @@ void NPC_BSST_Attack( void ) faceEnemy = qfalse; shoot = qfalse; hitAlly = qfalse; - VectorClear( impactPos ); - enemyDist = DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - - VectorSubtract( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, enemyDir ); - VectorNormalize( enemyDir ); - AngleVectors( NPCS.NPC->client->ps.viewangles, shootDir, NULL, NULL ); - dot = DotProduct( enemyDir, shootDir ); - if ( dot > 0.5f ||( enemyDist * (1.0f-dot)) < 10000 ) - {//enemy is in front of me or they're very close and not behind me + VectorClear(impactPos); + enemyDist = DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + + VectorSubtract(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, enemyDir); + VectorNormalize(enemyDir); + AngleVectors(NPCS.NPC->client->ps.viewangles, shootDir, NULL, NULL); + dot = DotProduct(enemyDir, shootDir); + if (dot > 0.5f || (enemyDist * (1.0f - dot)) < 10000) { // enemy is in front of me or they're very close and not behind me enemyInFOV = qtrue; } - if ( enemyDist < MIN_ROCKET_DIST_SQUARED )//128 - {//enemy within 128 - if ( (NPCS.NPC->client->ps.weapon == WP_FLECHETTE || NPCS.NPC->client->ps.weapon == WP_REPEATER) && - (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) ) - {//shooting an explosive, but enemy too close, switch to primary fire + if (enemyDist < MIN_ROCKET_DIST_SQUARED) // 128 + { // enemy within 128 + if ((NPCS.NPC->client->ps.weapon == WP_FLECHETTE || NPCS.NPC->client->ps.weapon == WP_REPEATER) && + (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // shooting an explosive, but enemy too close, switch to primary fire NPCS.NPCInfo->scriptFlags &= ~SCF_ALT_FIRE; - //FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... + // FIXME: we can never go back to alt-fire this way since, after this, we don't know if we were initially supposed to use alt-fire or not... } - } - else if ( enemyDist > 65536 )//256 squared + } else if (enemyDist > 65536) // 256 squared { - if ( NPCS.NPC->client->ps.weapon == WP_DISRUPTOR ) - {//sniping... should be assumed - if ( !(NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE) ) - {//use primary fire + if (NPCS.NPC->client->ps.weapon == WP_DISRUPTOR) { // sniping... should be assumed + if (!(NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE)) { // use primary fire NPCS.NPCInfo->scriptFlags |= SCF_ALT_FIRE; - //reset fire-timing variables - NPC_ChangeWeapon( WP_DISRUPTOR ); - NPC_UpdateAngles( qtrue, qtrue ); + // reset fire-timing variables + NPC_ChangeWeapon(WP_DISRUPTOR); + NPC_UpdateAngles(qtrue, qtrue); return; } } } - //can we see our target? - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { - AI_GroupUpdateEnemyLastSeen( NPCS.NPCInfo->group, NPCS.NPC->enemy->r.currentOrigin ); + // can we see our target? + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { + AI_GroupUpdateEnemyLastSeen(NPCS.NPCInfo->group, NPCS.NPC->enemy->r.currentOrigin); NPCS.NPCInfo->enemyLastSeenTime = level.time; enemyLOS = qtrue; - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - { - enemyCS = qfalse;//not true, but should stop us from firing - NPC_AimAdjust( -1 );//adjust aim worse longer we have no weapon - } - else - {//can we shoot our target? - if ( (NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || (NPCS.NPC->client->ps.weapon == WP_FLECHETTE && (NPCS.NPCInfo->scriptFlags&SCF_ALT_FIRE))) && enemyDist < MIN_ROCKET_DIST_SQUARED )//128*128 + if (NPCS.NPC->client->ps.weapon == WP_NONE) { + enemyCS = qfalse; // not true, but should stop us from firing + NPC_AimAdjust(-1); // adjust aim worse longer we have no weapon + } else { // can we shoot our target? + if ((NPCS.NPC->client->ps.weapon == WP_ROCKET_LAUNCHER || + (NPCS.NPC->client->ps.weapon == WP_FLECHETTE && (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE))) && + enemyDist < MIN_ROCKET_DIST_SQUARED) // 128*128 { - enemyCS = qfalse;//not true, but should stop us from firing - hitAlly = qtrue;//us! - //FIXME: if too close, run away! - } - else if ( enemyInFOV ) - {//if enemy is FOV, go ahead and check for shooting - int hit = NPC_ShotEntity( NPCS.NPC->enemy, impactPos ); + enemyCS = qfalse; // not true, but should stop us from firing + hitAlly = qtrue; // us! + // FIXME: if too close, run away! + } else if (enemyInFOV) { // if enemy is FOV, go ahead and check for shooting + int hit = NPC_ShotEntity(NPCS.NPC->enemy, impactPos); gentity_t *hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number - || ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam ) - || ( hitEnt && hitEnt->takedamage && ((hitEnt->r.svFlags&SVF_GLASS_BRUSH)||hitEnt->health < 40||NPCS.NPC->s.weapon == WP_EMPLACED_GUN) ) ) - {//can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway - AI_GroupUpdateClearShotTime( NPCS.NPCInfo->group ); + if (hit == NPCS.NPC->enemy->s.number || (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (hitEnt && hitEnt->takedamage && + ((hitEnt->r.svFlags & SVF_GLASS_BRUSH) || hitEnt->health < 40 || + NPCS.NPC->s.weapon == + WP_EMPLACED_GUN))) { // can hit enemy or enemy ally or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + AI_GroupUpdateClearShotTime(NPCS.NPCInfo->group); enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); - } - else - {//Hmm, have to get around this bastard - NPC_AimAdjust( 1 );//adjust aim better longer we can see enemy - ST_ResolveBlockedShot( hit ); - if ( hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam ) - {//would hit an ally, don't fire!!! + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); + } else { // Hmm, have to get around this bastard + NPC_AimAdjust(1); // adjust aim better longer we can see enemy + ST_ResolveBlockedShot(hit); + if (hitEnt && hitEnt->client && hitEnt->client->playerTeam == NPCS.NPC->client->playerTeam) { // would hit an ally, don't fire!!! hitAlly = qtrue; - } - else - {//Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire + } else { // Check and see where our shot *would* hit... if it's not close to the enemy (within 256?), then don't fire } } - } - else - { - enemyCS = qfalse;//not true, but should stop us from firing + } else { + enemyCS = qfalse; // not true, but should stop us from firing } } - } - else if ( trap->InPVS( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - { + } else if (trap->InPVS(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { NPCS.NPCInfo->enemyLastSeenTime = level.time; faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + NPC_AimAdjust(-1); // adjust aim worse longer we cannot see enemy } - if ( NPCS.NPC->client->ps.weapon == WP_NONE ) - { + if (NPCS.NPC->client->ps.weapon == WP_NONE) { faceEnemy = qfalse; shoot = qfalse; - } - else - { - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + } else { + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } } - //Check for movement to take care of + // Check for movement to take care of ST_CheckMoveState(); - //See if we should override shooting decision with any special considerations + // See if we should override shooting decision with any special considerations ST_CheckFireState(); - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); } - if ( !(NPCS.NPCInfo->scriptFlags&SCF_CHASE_ENEMIES) ) - {//not supposed to chase my enemies - if ( NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) - {//goal is my entity, so don't move + if (!(NPCS.NPCInfo->scriptFlags & SCF_CHASE_ENEMIES)) { // not supposed to chase my enemies + if (NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) { // goal is my entity, so don't move move = qfalse; } } - if ( NPCS.NPC->client->ps.weaponTime > 0 && NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { + if (NPCS.NPC->client->ps.weaponTime > 0 && NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER) { move = qfalse; } - if ( move ) - {//move toward goal - if ( NPCS.NPCInfo->goalEntity )//&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared + if (move) { // move toward goal + if (NPCS.NPCInfo->goalEntity) //&& ( NPCInfo->goalEntity != NPC->enemy || enemyDist > 10000 ) )//100 squared { move = ST_Move(); - } - else - { + } else { move = qfalse; } } - if ( !move ) - { - if ( !TIMER_Done( NPCS.NPC, "duck" ) ) - { + if (!move) { + if (!TIMER_Done(NPCS.NPC, "duck")) { NPCS.ucmd.upmove = -127; } - //FIXME: what about leaning? - } - else - {//stop ducking! - TIMER_Set( NPCS.NPC, "duck", -1 ); + // FIXME: what about leaning? + } else { // stop ducking! + TIMER_Set(NPCS.NPC, "duck", -1); } - if ( !TIMER_Done( NPCS.NPC, "flee" ) ) - {//running away + if (!TIMER_Done(NPCS.NPC, "flee")) { // running away faceEnemy = qfalse; } - //FIXME: check scf_face_move_dir here? + // FIXME: check scf_face_move_dir here? - if ( !faceEnemy ) - {//we want to face in the dir we're running - if ( !move ) - {//if we haven't moved, we should look in the direction we last looked? - VectorCopy( NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->lastPathAngles ); + if (!faceEnemy) { // we want to face in the dir we're running + if (!move) { // if we haven't moved, we should look in the direction we last looked? + VectorCopy(NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->lastPathAngles); } NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lastPathAngles[YAW]; NPCS.NPCInfo->desiredPitch = 0; - NPC_UpdateAngles( qtrue, qtrue ); - if ( move ) - {//don't run away and shoot + NPC_UpdateAngles(qtrue, qtrue); + if (move) { // don't run away and shoot shoot = qfalse; } } - if ( NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->enemy ) - { - if ( NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPCS.NPC->enemy && NPCS.NPC->enemy->enemy) { + if (NPCS.NPC->enemy->s.weapon == WP_SABER && + NPCS.NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing + // rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - //FIXME: don't shoot right away! - if ( NPCS.NPC->client->ps.weaponTime > 0 ) - { - if ( NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER ) - { - if ( !enemyLOS || !enemyCS ) - {//cancel it + // FIXME: don't shoot right away! + if (NPCS.NPC->client->ps.weaponTime > 0) { + if (NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER) { + if (!enemyLOS || !enemyCS) { // cancel it NPCS.NPC->client->ps.weaponTime = 0; - } - else - {//delay our next attempt - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 3000, 5000 ) ); + } else { // delay our next attempt + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(3000, 5000)); } } - } - else if ( shoot ) - {//try to shoot if it's time - if ( TIMER_Done( NPCS.NPC, "attackDelay" ) ) - { - if( !(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + } else if (shoot) { // try to shoot if it's time + if (TIMER_Done(NPCS.NPC, "attackDelay")) { + if (!(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } - //NASTY - if ( NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER - && (NPCS.ucmd.buttons&BUTTON_ATTACK) - && !move - && g_npcspskill.integer > 1 - && !Q_irand( 0, 3 ) ) - {//every now and then, shoot a homing rocket + // NASTY + if (NPCS.NPC->s.weapon == WP_ROCKET_LAUNCHER && (NPCS.ucmd.buttons & BUTTON_ATTACK) && !move && g_npcspskill.integer > 1 && + !Q_irand(0, 3)) { // every now and then, shoot a homing rocket NPCS.ucmd.buttons &= ~BUTTON_ATTACK; NPCS.ucmd.buttons |= BUTTON_ALT_ATTACK; - NPCS.NPC->client->ps.weaponTime = Q_irand( 1000, 2500 ); + NPCS.NPC->client->ps.weaponTime = Q_irand(1000, 2500); } } } } - -void NPC_BSST_Default( void ) -{ - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); +void NPC_BSST_Default(void) { + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if( !NPCS.NPC->enemy ) - {//don't have an enemy, look for one + if (!NPCS.NPC->enemy) { // don't have an enemy, look for one NPC_BSST_Patrol(); - } - else //if ( NPC->enemy ) - {//have an enemy + } else // if ( NPC->enemy ) + { // have an enemy NPC_CheckGetNewWeapon(); NPC_BSST_Attack(); } diff --git a/codemp/game/NPC_AI_Utils.c b/codemp/game/NPC_AI_Utils.c index 23d73c2134..624ef83a5a 100644 --- a/codemp/game/NPC_AI_Utils.c +++ b/codemp/game/NPC_AI_Utils.c @@ -28,10 +28,10 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -#define MAX_RADIUS_ENTS 128 -#define DEFAULT_RADIUS 45 +#define MAX_RADIUS_ENTS 128 +#define DEFAULT_RADIUS 45 -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ); +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member); extern void G_TestLine(vec3_t start, vec3_t end, int color, int time); @@ -41,44 +41,41 @@ AI_GetGroupSize ------------------------- */ -int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid ) -{ - int radiusEnts[ MAX_RADIUS_ENTS ]; - gentity_t *check; - vec3_t mins, maxs; - int numEnts, realCount = 0; - int i; - int j; - - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { +int AI_GetGroupSize(vec3_t origin, int radius, team_t playerTeam, gentity_t *avoid) { + int radiusEnts[MAX_RADIUS_ENTS]; + gentity_t *check; + vec3_t mins, maxs; + int numEnts, realCount = 0; + int i; + int j; + + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - //Get the number of entities in a given space - numEnts = trap->EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get the number of entities in a given space + numEnts = trap->EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( j = 0; j < numEnts; j++ ) - { + // Cull this list + for (j = 0; j < numEnts; j++) { check = &g_entities[radiusEnts[j]]; - //Validate clients - if ( check->client == NULL ) + // Validate clients + if (check->client == NULL) continue; - //Skip the requested avoid ent if present - if ( ( avoid != NULL ) && ( check == avoid ) ) + // Skip the requested avoid ent if present + if ((avoid != NULL) && (check == avoid)) continue; - //Must be on the same team - if ( check->client->playerTeam != (npcteam_t)playerTeam ) + // Must be on the same team + if (check->client->playerTeam != (npcteam_t)playerTeam) continue; - //Must be alive - if ( check->health <= 0 ) + // Must be alive + if (check->health <= 0) continue; realCount++; @@ -87,31 +84,26 @@ int AI_GetGroupSize( vec3_t origin, int radius, team_t playerTeam, gentity_t *av return realCount; } -//Overload +// Overload -int AI_GetGroupSize2( gentity_t *ent, int radius ) -{ - if ( ( ent == NULL ) || ( ent->client == NULL ) ) +int AI_GetGroupSize2(gentity_t *ent, int radius) { + if ((ent == NULL) || (ent->client == NULL)) return -1; - return AI_GetGroupSize( ent->r.currentOrigin, radius, (team_t)ent->client->playerTeam, ent ); + return AI_GetGroupSize(ent->r.currentOrigin, radius, (team_t)ent->client->playerTeam, ent); } -void AI_SetClosestBuddy( AIGroupInfo_t *group ) -{ - int i, j; - int dist, bestDist; +void AI_SetClosestBuddy(AIGroupInfo_t *group) { + int i, j; + int dist, bestDist; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { group->member[i].closestBuddy = ENTITYNUM_NONE; bestDist = Q3_INFINITE; - for ( j = 0; j < group->numGroup; j++ ) - { - dist = DistanceSquared( g_entities[group->member[i].number].r.currentOrigin, g_entities[group->member[j].number].r.currentOrigin ); - if ( dist < bestDist ) - { + for (j = 0; j < group->numGroup; j++) { + dist = DistanceSquared(g_entities[group->member[i].number].r.currentOrigin, g_entities[group->member[j].number].r.currentOrigin); + if (dist < bestDist) { bestDist = dist; group->member[i].closestBuddy = group->member[j].number; } @@ -119,95 +111,71 @@ void AI_SetClosestBuddy( AIGroupInfo_t *group ) } } -void AI_SortGroupByPathCostToEnemy( AIGroupInfo_t *group ) -{ +void AI_SortGroupByPathCostToEnemy(AIGroupInfo_t *group) { AIGroupMember_t bestMembers[MAX_GROUP_MEMBERS]; - int i, j, k; - qboolean sort = qfalse; + int i, j, k; + qboolean sort = qfalse; - if ( group->enemy != NULL ) - {//FIXME: just use enemy->waypoint? - group->enemyWP = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - } - else - { + if (group->enemy != NULL) { // FIXME: just use enemy->waypoint? + group->enemyWP = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + } else { group->enemyWP = WAYPOINT_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->enemyWP == WAYPOINT_NONE ) - {//FIXME: just use member->waypoint? + for (i = 0; i < group->numGroup; i++) { + if (group->enemyWP == WAYPOINT_NONE) { // FIXME: just use member->waypoint? group->member[i].waypoint = WAYPOINT_NONE; group->member[i].pathCostToEnemy = Q3_INFINITE; - } - else - {//FIXME: just use member->waypoint? - group->member[i].waypoint = NAV_FindClosestWaypointForEnt( group->enemy, WAYPOINT_NONE ); - if ( group->member[i].waypoint != WAYPOINT_NONE ) - { - group->member[i].pathCostToEnemy = trap->Nav_GetPathCost( group->member[i].waypoint, group->enemyWP ); - //at least one of us has a path, so do sorting + } else { // FIXME: just use member->waypoint? + group->member[i].waypoint = NAV_FindClosestWaypointForEnt(group->enemy, WAYPOINT_NONE); + if (group->member[i].waypoint != WAYPOINT_NONE) { + group->member[i].pathCostToEnemy = trap->Nav_GetPathCost(group->member[i].waypoint, group->enemyWP); + // at least one of us has a path, so do sorting sort = qtrue; - } - else - { + } else { group->member[i].pathCostToEnemy = Q3_INFINITE; } } } - //Now sort - if ( sort ) - { - //initialize bestMembers data - for ( j = 0; j < group->numGroup; j++ ) - { + // Now sort + if (sort) { + // initialize bestMembers data + for (j = 0; j < group->numGroup; j++) { bestMembers[j].number = ENTITYNUM_NONE; } - for ( i = 0; i < group->numGroup; i++ ) - { - for ( j = 0; j < group->numGroup; j++ ) - { - if ( bestMembers[j].number != ENTITYNUM_NONE ) - {//slot occupied - if ( group->member[i].pathCostToEnemy < bestMembers[j].pathCostToEnemy ) - {//this guy has a shorter path than the one currenly in this spot, bump him and put myself in here - for ( k = group->numGroup; k < j; k++ ) - { - memcpy( &bestMembers[k], &bestMembers[k-1], sizeof( bestMembers[k] ) ); + for (i = 0; i < group->numGroup; i++) { + for (j = 0; j < group->numGroup; j++) { + if (bestMembers[j].number != ENTITYNUM_NONE) { // slot occupied + if (group->member[i].pathCostToEnemy < + bestMembers[j].pathCostToEnemy) { // this guy has a shorter path than the one currenly in this spot, bump him and put myself in here + for (k = group->numGroup; k < j; k++) { + memcpy(&bestMembers[k], &bestMembers[k - 1], sizeof(bestMembers[k])); } - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } - } - else - {//slot unoccupied, reached end of list, throw self in here - memcpy( &bestMembers[j], &group->member[i], sizeof( bestMembers[j] ) ); + } else { // slot unoccupied, reached end of list, throw self in here + memcpy(&bestMembers[j], &group->member[i], sizeof(bestMembers[j])); break; } } } - //Okay, now bestMembers is a sorted list, just copy it into group->members - for ( i = 0; i < group->numGroup; i++ ) - { - memcpy( &group->member[i], &bestMembers[i], sizeof( group->member[i] ) ); + // Okay, now bestMembers is a sorted list, just copy it into group->members + for (i = 0; i < group->numGroup; i++) { + memcpy(&group->member[i], &bestMembers[i], sizeof(group->member[i])); } } } -qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those contain me already - int i, j; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup )//&& level.groups[i].enemy != NULL ) - {//check this one - for ( j = 0; j < level.groups[i].numGroup; j++ ) - { - if ( level.groups[i].member[j].number == self->s.number ) - { +qboolean AI_FindSelfInPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those contain me already + int i, j; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup) //&& level.groups[i].enemy != NULL ) + { // check this one + for (j = 0; j < level.groups[i].numGroup; j++) { + if (level.groups[i].member[j].number == self->s.number) { self->NPC->group = &level.groups[i]; return qtrue; } @@ -217,46 +185,36 @@ qboolean AI_FindSelfInPreviousGroup( gentity_t *self ) return qfalse; } -void AI_InsertGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ +void AI_InsertGroupMember(AIGroupInfo_t *group, gentity_t *member) { int i; - //okay, you know what? Check this damn group and make sure we're not already in here! - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - {//already in here + // okay, you know what? Check this damn group and make sure we're not already in here! + for (i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { // already in here break; } } - if ( i < group->numGroup ) - {//found him in group already - } - else - {//add him in + if (i < group->numGroup) { // found him in group already + } else { // add him in group->member[group->numGroup++].number = member->s.number; group->numState[member->NPC->squadState]++; } - if ( !group->commander || (member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || (member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } member->NPC->group = group; } -qboolean AI_TryJoinPreviousGroup( gentity_t *self ) -{//go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! - int i; - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( level.groups[i].numGroup - && level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) +qboolean +AI_TryJoinPreviousGroup(gentity_t *self) { // go through other groups made this frame and see if any of those have the same enemy as me... if so, add me in! + int i; + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (level.groups[i].numGroup && + level.groups[i].numGroup < (MAX_GROUP_MEMBERS - 1) //&& level.groups[i].enemy != NULL - && level.groups[i].enemy == self->enemy ) - {//has members, not full and has my enemy - if ( AI_ValidateGroupMember( &level.groups[i], self ) ) - {//I am a valid member for this group - AI_InsertGroupMember( &level.groups[i], self ); + && level.groups[i].enemy == self->enemy) { // has members, not full and has my enemy + if (AI_ValidateGroupMember(&level.groups[i], self)) { // I am a valid member for this group + AI_InsertGroupMember(&level.groups[i], self); return qtrue; } } @@ -264,108 +222,93 @@ qboolean AI_TryJoinPreviousGroup( gentity_t *self ) return qfalse; } -qboolean AI_GetNextEmptyGroup( gentity_t *self ) -{ +qboolean AI_GetNextEmptyGroup(gentity_t *self) { int i; - if ( AI_FindSelfInPreviousGroup( self ) ) - {//already in one, no need to make a new one + if (AI_FindSelfInPreviousGroup(self)) { // already in one, no need to make a new one return qfalse; } - if ( AI_TryJoinPreviousGroup( self ) ) - {//try to just put us in one that already exists + if (AI_TryJoinPreviousGroup(self)) { // try to just put us in one that already exists return qfalse; } - //okay, make a whole new one, then - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup ) - {//make a new one + // okay, make a whole new one, then + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup) { // make a new one self->NPC->group = &level.groups[i]; return qtrue; } } - //if ( i >= MAX_FRAME_GROUPS ) - {//WTF? Out of groups! + // if ( i >= MAX_FRAME_GROUPS ) + { // WTF? Out of groups! self->NPC->group = NULL; return qfalse; } } -qboolean AI_ValidateNoEnemyGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ +qboolean AI_ValidateNoEnemyGroupMember(AIGroupInfo_t *group, gentity_t *member) { vec3_t center; - if ( !group ) - { + if (!group) { return qfalse; } - if ( group->commander ) - { - VectorCopy( group->commander->r.currentOrigin, center ); - } - else - {//hmm, just pick the first member - if ( group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD ) - { + if (group->commander) { + VectorCopy(group->commander->r.currentOrigin, center); + } else { // hmm, just pick the first member + if (group->member[0].number < 0 || group->member[0].number >= ENTITYNUM_WORLD) { return qfalse; } - VectorCopy( g_entities[group->member[0].number].r.currentOrigin, center ); + VectorCopy(g_entities[group->member[0].number].r.currentOrigin, center); } - //FIXME: maybe it should be based on the center of the mass of the group, not the commander? - if ( DistanceSquared( center, member->r.currentOrigin ) > 147456/*384*384*/ ) - { + // FIXME: maybe it should be based on the center of the mass of the group, not the commander? + if (DistanceSquared(center, member->r.currentOrigin) > 147456 /*384*384*/) { return qfalse; } - if ( !trap->InPVS( member->r.currentOrigin, center ) ) - {//not within PVS of the group enemy + if (!trap->InPVS(member->r.currentOrigin, center)) { // not within PVS of the group enemy return qfalse; } return qtrue; } -qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) -{ - //Validate ents - if ( member == NULL ) +qboolean AI_ValidateGroupMember(AIGroupInfo_t *group, gentity_t *member) { + // Validate ents + if (member == NULL) return qfalse; - //Validate clients - if ( member->client == NULL ) + // Validate clients + if (member->client == NULL) return qfalse; - //Validate NPCs - if ( member->NPC == NULL ) + // Validate NPCs + if (member->NPC == NULL) return qfalse; - //must be aware - if ( member->NPC->confusionTime > level.time ) + // must be aware + if (member->NPC->confusionTime > level.time) return qfalse; - //must be allowed to join groups - if ( member->NPC->scriptFlags&SCF_NO_GROUPS ) + // must be allowed to join groups + if (member->NPC->scriptFlags & SCF_NO_GROUPS) return qfalse; - //Must not be in another group - if ( member->NPC->group != NULL && member->NPC->group != group ) - {//FIXME: if that group's enemy is mine, why not absorb that group into mine? + // Must not be in another group + if (member->NPC->group != NULL && member->NPC->group != group) { // FIXME: if that group's enemy is mine, why not absorb that group into mine? return qfalse; } - //Must be alive - if ( member->health <= 0 ) + // Must be alive + if (member->health <= 0) return qfalse; - //can't be in an emplaced gun -// if( member->s.eFlags & EF_LOCKED_TO_WEAPON ) -// return qfalse; - //rwwFIXMEFIXME: support this flag + // can't be in an emplaced gun + // if( member->s.eFlags & EF_LOCKED_TO_WEAPON ) + // return qfalse; + // rwwFIXMEFIXME: support this flag - //Must be on the same team - if ( member->client->playerTeam != (npcteam_t)group->team ) + // Must be on the same team + if (member->client->playerTeam != (npcteam_t)group->team) return qfalse; if ( member->client->ps.weapon == WP_SABER ||//!= self->s.weapon ) @@ -382,43 +325,30 @@ qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) return qfalse; } - if ( member->client->NPC_class == CLASS_ATST || - member->client->NPC_class == CLASS_PROBE || - member->client->NPC_class == CLASS_SEEKER || - member->client->NPC_class == CLASS_REMOTE || - member->client->NPC_class == CLASS_SENTRY || - member->client->NPC_class == CLASS_INTERROGATOR || - member->client->NPC_class == CLASS_MINEMONSTER || - member->client->NPC_class == CLASS_HOWLER || - member->client->NPC_class == CLASS_MARK1 || - member->client->NPC_class == CLASS_MARK2 ) - {//these kinds of enemies don't actually use this group AI + if (member->client->NPC_class == CLASS_ATST || member->client->NPC_class == CLASS_PROBE || member->client->NPC_class == CLASS_SEEKER || + member->client->NPC_class == CLASS_REMOTE || member->client->NPC_class == CLASS_SENTRY || member->client->NPC_class == CLASS_INTERROGATOR || + member->client->NPC_class == CLASS_MINEMONSTER || member->client->NPC_class == CLASS_HOWLER || member->client->NPC_class == CLASS_MARK1 || + member->client->NPC_class == CLASS_MARK2) { // these kinds of enemies don't actually use this group AI return qfalse; } - //should have same enemy - if ( member->enemy != group->enemy ) - { - if ( member->enemy != NULL ) - {//he's fighting someone else, leave him out + // should have same enemy + if (member->enemy != group->enemy) { + if (member->enemy != NULL) { // he's fighting someone else, leave him out return qfalse; } - if ( !trap->InPVS( member->r.currentOrigin, group->enemy->r.currentOrigin ) ) - {//not within PVS of the group enemy + if (!trap->InPVS(member->r.currentOrigin, group->enemy->r.currentOrigin)) { // not within PVS of the group enemy return qfalse; } - } - else if ( group->enemy == NULL ) - {//if the group is a patrol group, only take those within the room and radius - if ( !AI_ValidateNoEnemyGroupMember( group, member ) ) - { + } else if (group->enemy == NULL) { // if the group is a patrol group, only take those within the room and radius + if (!AI_ValidateNoEnemyGroupMember(group, member)) { return qfalse; } } - //must be actually in combat mode - if ( !TIMER_Done( member, "interrogating" ) ) + // must be actually in combat mode + if (!TIMER_Done(member, "interrogating")) return qfalse; - //FIXME: need to have a route to enemy and/or clear shot? + // FIXME: need to have a route to enemy and/or clear shot? return qtrue; } @@ -427,48 +357,41 @@ qboolean AI_ValidateGroupMember( AIGroupInfo_t *group, gentity_t *member ) AI_GetGroup ------------------------- */ -void AI_GetGroup( gentity_t *self ) -{ - int i; - gentity_t *member;//, *waiter; - //int waiters[MAX_WAITERS]; +void AI_GetGroup(gentity_t *self) { + int i; + gentity_t *member; //, *waiter; + // int waiters[MAX_WAITERS]; - if ( !self || !self->NPC ) - { + if (!self || !self->NPC) { return; } - if ( d_noGroupAI.integer ) - { + if (d_noGroupAI.integer) { self->NPC->group = NULL; return; } - if ( !self->client ) - { + if (!self->client) { self->NPC->group = NULL; return; } - if ( self->NPC->scriptFlags&SCF_NO_GROUPS ) - { + if (self->NPC->scriptFlags & SCF_NO_GROUPS) { self->NPC->group = NULL; return; } - if ( self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000 ))) - { + if (self->enemy && (!self->enemy->client || (level.time - self->NPC->enemyLastSeenTime > 7000))) { self->NPC->group = NULL; return; } - if ( !AI_GetNextEmptyGroup( self ) ) - {//either no more groups left or we're already in a group built earlier + if (!AI_GetNextEmptyGroup(self)) { // either no more groups left or we're already in a group built earlier return; } - //create a new one - memset( self->NPC->group, 0, sizeof( AIGroupInfo_t ) ); + // create a new one + memset(self->NPC->group, 0, sizeof(AIGroupInfo_t)); self->NPC->group->enemy = self->enemy; self->NPC->group->team = (team_t)self->client->playerTeam; @@ -477,33 +400,29 @@ void AI_GetGroup( gentity_t *self ) self->NPC->group->memberValidateTime = level.time + 2000; self->NPC->group->activeMemberNum = 0; - if ( self->NPC->group->enemy ) - { + if (self->NPC->group->enemy) { self->NPC->group->lastSeenEnemyTime = level.time; self->NPC->group->lastClearShotTime = level.time; - VectorCopy( self->NPC->group->enemy->r.currentOrigin, self->NPC->group->enemyLastSeenPos ); + VectorCopy(self->NPC->group->enemy->r.currentOrigin, self->NPC->group->enemyLastSeenPos); } -// for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) - for ( i = 0; i < level.num_entities ; i++) - { + // for ( i = 0, member = &g_entities[0]; i < globals.num_entities ; i++, member++) + for (i = 0; i < level.num_entities; i++) { member = &g_entities[i]; - if (!member->inuse) - { + if (!member->inuse) { continue; } - if ( !AI_ValidateGroupMember( self->NPC->group, member ) ) - {//FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group + if (!AI_ValidateGroupMember( + self->NPC->group, member)) { // FIXME: keep track of those who aren't angry yet and see if we should wake them after we assemble the core group continue; } - //store it - AI_InsertGroupMember( self->NPC->group, member ); + // store it + AI_InsertGroupMember(self->NPC->group, member); - if ( self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1) ) - {//full + if (self->NPC->group->numGroup >= (MAX_GROUP_MEMBERS - 1)) { // full break; } } @@ -527,195 +446,154 @@ void AI_GetGroup( gentity_t *self ) } */ - if ( self->NPC->group->numGroup <= 0 ) - {//none in group + if (self->NPC->group->numGroup <= 0) { // none in group self->NPC->group = NULL; return; } - AI_SortGroupByPathCostToEnemy( self->NPC->group ); - AI_SetClosestBuddy( self->NPC->group ); + AI_SortGroupByPathCostToEnemy(self->NPC->group); + AI_SetClosestBuddy(self->NPC->group); } -void AI_SetNewGroupCommander( AIGroupInfo_t *group ) -{ +void AI_SetNewGroupCommander(AIGroupInfo_t *group) { gentity_t *member = NULL; int i; group->commander = NULL; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( !group->commander || (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank) ) - {//keep track of highest rank + if (!group->commander || + (member && member->NPC && group->commander->NPC && member->NPC->rank > group->commander->NPC->rank)) { // keep track of highest rank group->commander = member; } } } -void AI_DeleteGroupMember( AIGroupInfo_t *group, int memberNum ) -{ +void AI_DeleteGroupMember(AIGroupInfo_t *group, int memberNum) { int i; - if ( group->commander && group->commander->s.number == group->member[memberNum].number ) - { + if (group->commander && group->commander->s.number == group->member[memberNum].number) { group->commander = NULL; } - if ( g_entities[group->member[memberNum].number].NPC ) - { + if (g_entities[group->member[memberNum].number].NPC) { g_entities[group->member[memberNum].number].NPC->group = NULL; } - for ( i = memberNum; i < (group->numGroup-1); i++ ) - { - memcpy( &group->member[i], &group->member[i+1], sizeof( group->member[i] ) ); + for (i = memberNum; i < (group->numGroup - 1); i++) { + memcpy(&group->member[i], &group->member[i + 1], sizeof(group->member[i])); } - if ( memberNum < group->activeMemberNum ) - { + if (memberNum < group->activeMemberNum) { group->activeMemberNum--; - if ( group->activeMemberNum < 0 ) - { + if (group->activeMemberNum < 0) { group->activeMemberNum = 0; } } group->numGroup--; - if ( group->numGroup < 0 ) - { + if (group->numGroup < 0) { group->numGroup = 0; } - AI_SetNewGroupCommander( group ); + AI_SetNewGroupCommander(group); } -void AI_DeleteSelfFromGroup( gentity_t *self ) -{ +void AI_DeleteSelfFromGroup(gentity_t *self) { int i; - //FIXME: if killed, keep track of how many in group killed? To affect morale? - for ( i = 0; i < self->NPC->group->numGroup; i++ ) - { - if ( self->NPC->group->member[i].number == self->s.number ) - { - AI_DeleteGroupMember( self->NPC->group, i ); + // FIXME: if killed, keep track of how many in group killed? To affect morale? + for (i = 0; i < self->NPC->group->numGroup; i++) { + if (self->NPC->group->member[i].number == self->s.number) { + AI_DeleteGroupMember(self->NPC->group, i); return; } } } -extern void ST_AggressionAdjust( gentity_t *self, int change ); -extern void ST_MarkToCover( gentity_t *self ); -extern void ST_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime ); -void AI_GroupMemberKilled( gentity_t *self ) -{ +extern void ST_AggressionAdjust(gentity_t *self, int change); +extern void ST_MarkToCover(gentity_t *self); +extern void ST_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int minTime, int maxTime); +void AI_GroupMemberKilled(gentity_t *self) { AIGroupInfo_t *group = self->NPC->group; - gentity_t *member; - qboolean noflee = qfalse; - int i; + gentity_t *member; + qboolean noflee = qfalse; + int i; - if ( !group ) - {//what group? + if (!group) { // what group? return; } - if ( !self || !self->NPC || self->NPC->rank < RANK_ENSIGN ) - {//I'm not an officer, let's not really care for now + if (!self || !self->NPC || self->NPC->rank < RANK_ENSIGN) { // I'm not an officer, let's not really care for now return; } - //temporarily drop group morale for a few seconds + // temporarily drop group morale for a few seconds group->moraleAdjust -= self->NPC->rank; - //go through and drop aggression on my teammates (more cover, worse aim) - for ( i = 0; i < group->numGroup; i++ ) - { + // go through and drop aggression on my teammates (more cover, worse aim) + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member == self ) - { + if (member == self) { continue; } - if ( member->NPC->rank > RANK_ENSIGN ) - {//officers do not panic + if (member->NPC->rank > RANK_ENSIGN) { // officers do not panic noflee = qtrue; - } - else - { - ST_AggressionAdjust( member, -1 ); - member->NPC->currentAim -= Q_irand( 0, 10 );//Q_irand( 0, 2);//drop their aim accuracy + } else { + ST_AggressionAdjust(member, -1); + member->NPC->currentAim -= Q_irand(0, 10); // Q_irand( 0, 2);//drop their aim accuracy } } - //okay, if I'm the group commander, make everyone else flee - if ( group->commander != self ) - {//I'm not the commander... hmm, should maybe a couple flee... maybe those near me? + // okay, if I'm the group commander, make everyone else flee + if (group->commander != self) { // I'm not the commander... hmm, should maybe a couple flee... maybe those near me? return; } - //now see if there is another of sufficient rank to keep them from fleeing - if ( !noflee ) - { + // now see if there is another of sufficient rank to keep them from fleeing + if (!noflee) { self->NPC->group->speechDebounceTime = 0; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member == self ) - { + if (member == self) { continue; } - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunt - if ( group->enemy && DistanceSquared( member->r.currentOrigin, group->enemy->r.currentOrigin ) < 65536/*256*256*/ ) - {//those close to enemy run away! - ST_StartFlee( member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else if ( DistanceSquared( member->r.currentOrigin, self->r.currentOrigin ) < 65536/*256*256*/ ) - {//those close to me run away! - ST_StartFlee( member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else - {//else, maybe just a random chance - if ( Q_irand( 0, self->NPC->rank ) > member->NPC->rank ) - {//lower rank they are, higher rank I am, more likely they are to flee - ST_StartFlee( member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000 ); - } - else - { - ST_MarkToCover( member ); + if (member->NPC->rank < RANK_ENSIGN) { // grunt + if (group->enemy && + DistanceSquared(member->r.currentOrigin, group->enemy->r.currentOrigin) < 65536 /*256*256*/) { // those close to enemy run away! + ST_StartFlee(member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else if (DistanceSquared(member->r.currentOrigin, self->r.currentOrigin) < 65536 /*256*256*/) { // those close to me run away! + ST_StartFlee(member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else { // else, maybe just a random chance + if (Q_irand(0, self->NPC->rank) > member->NPC->rank) { // lower rank they are, higher rank I am, more likely they are to flee + ST_StartFlee(member, group->enemy, member->r.currentOrigin, AEL_DANGER_GREAT, 3000, 5000); + } else { + ST_MarkToCover(member); } } - member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more + member->NPC->currentAim -= Q_irand(1, 15); // Q_irand( 1, 3 );//drop their aim accuracy even more } - member->NPC->currentAim -= Q_irand( 1, 15 ); //Q_irand( 1, 3 );//drop their aim accuracy even more + member->NPC->currentAim -= Q_irand(1, 15); // Q_irand( 1, 3 );//drop their aim accuracy even more } } } -void AI_GroupUpdateEnemyLastSeen( AIGroupInfo_t *group, vec3_t spot ) -{ - if ( !group ) - { +void AI_GroupUpdateEnemyLastSeen(AIGroupInfo_t *group, vec3_t spot) { + if (!group) { return; } group->lastSeenEnemyTime = level.time; - VectorCopy( spot, group->enemyLastSeenPos ); + VectorCopy(spot, group->enemyLastSeenPos); } -void AI_GroupUpdateClearShotTime( AIGroupInfo_t *group ) -{ - if ( !group ) - { +void AI_GroupUpdateClearShotTime(AIGroupInfo_t *group) { + if (!group) { return; } group->lastClearShotTime = level.time; } -void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int newSquadState ) -{ +void AI_GroupUpdateSquadstates(AIGroupInfo_t *group, gentity_t *member, int newSquadState) { int i; - if ( !group ) - { + if (!group) { member->NPC->squadState = newSquadState; return; } - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == member->s.number ) - { + for (i = 0; i < group->numGroup; i++) { + if (group->member[i].number == member->s.number) { group->numState[member->NPC->squadState]--; member->NPC->squadState = newSquadState; group->numState[member->NPC->squadState]++; @@ -724,65 +602,52 @@ void AI_GroupUpdateSquadstates( AIGroupInfo_t *group, gentity_t *member, int new } } -qboolean AI_RefreshGroup( AIGroupInfo_t *group ) -{ - gentity_t *member; - int i;//, j; +qboolean AI_RefreshGroup(AIGroupInfo_t *group) { + gentity_t *member; + int i; //, j; - //see if we should merge with another group - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( &level.groups[i] == group ) - { + // see if we should merge with another group + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (&level.groups[i] == group) { break; - } - else - { - if ( level.groups[i].enemy == group->enemy ) - {//2 groups with same enemy - if ( level.groups[i].numGroup+group->numGroup < (MAX_GROUP_MEMBERS - 1) ) - {//combining the members would fit in one group + } else { + if (level.groups[i].enemy == group->enemy) { // 2 groups with same enemy + if (level.groups[i].numGroup + group->numGroup < (MAX_GROUP_MEMBERS - 1)) { // combining the members would fit in one group qboolean deleteWhenDone = qtrue; int j; - //combine the members of mine into theirs - for ( j = 0; j < group->numGroup; j++ ) - { + // combine the members of mine into theirs + for (j = 0; j < group->numGroup; j++) { member = &g_entities[group->member[j].number]; - if ( level.groups[i].enemy == NULL ) - {//special case for groups without enemies, must be in range - if ( !AI_ValidateNoEnemyGroupMember( &level.groups[i], member ) ) - { + if (level.groups[i].enemy == NULL) { // special case for groups without enemies, must be in range + if (!AI_ValidateNoEnemyGroupMember(&level.groups[i], member)) { deleteWhenDone = qfalse; continue; } } - //remove this member from this group - AI_DeleteGroupMember( group, j ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // remove this member from this group + AI_DeleteGroupMember(group, j); + // keep marker at same place since we deleted this guy and shifted everyone up one j--; - //add them to the earlier group - AI_InsertGroupMember( &level.groups[i], member ); + // add them to the earlier group + AI_InsertGroupMember(&level.groups[i], member); } - //return and delete this group - if ( deleteWhenDone ) - { + // return and delete this group + if (deleteWhenDone) { return qfalse; } } } } } - //clear numStates - for ( i = 0; i < NUM_SQUAD_STATES; i++ ) - { + // clear numStates + for (i = 0; i < NUM_SQUAD_STATES; i++) { group->numState[i] = 0; } - //go through group and validate each membership + // go through group and validate each membership group->commander = NULL; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { /* //this checks for duplicate copies of one member in a group for ( j = 0; j < group->numGroup; j++ ) @@ -797,43 +662,34 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } if ( j < group->numGroup ) {//found a dupe! - trap->Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, group->member[i].number ); - AI_DeleteGroupMember( group, i ); - i--; - continue; + trap->Printf( S_COLOR_RED"ERROR: member %s(%d) a duplicate group member!!!\n", g_entities[group->member[i].number].targetname, + group->member[i].number ); AI_DeleteGroupMember( group, i ); i--; continue; } */ member = &g_entities[group->member[i].number]; - //Must be alive - if ( member->health <= 0 ) - { - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + // Must be alive + if (member->health <= 0) { + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else if ( group->memberValidateTime < level.time && !AI_ValidateGroupMember( group, member ) ) - { - //remove this one from the group - AI_DeleteGroupMember( group, i ); - //keep marker at same place since we deleted this guy and shifted everyone up one + } else if (group->memberValidateTime < level.time && !AI_ValidateGroupMember(group, member)) { + // remove this one from the group + AI_DeleteGroupMember(group, i); + // keep marker at same place since we deleted this guy and shifted everyone up one i--; - } - else - {//membership is valid - //keep track of squadStates + } else { // membership is valid + // keep track of squadStates group->numState[member->NPC->squadState]++; - if ( !group->commander || member->NPC->rank > group->commander->NPC->rank ) - {//keep track of highest rank + if (!group->commander || member->NPC->rank > group->commander->NPC->rank) { // keep track of highest rank group->commander = member; } } } - if ( group->memberValidateTime < level.time ) - { - group->memberValidateTime = level.time + Q_irand( 500, 2500 ); + if (group->memberValidateTime < level.time) { + group->memberValidateTime = level.time + Q_irand(500, 2500); } - //Now add any new guys as long as we're not full + // Now add any new guys as long as we're not full /* for ( i = 0, member = &g_entities[0]; i < globals.num_entities && group->numGroup < (MAX_GROUP_MEMBERS - 1); i++, member++) { @@ -851,41 +707,29 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) } */ - //calc the morale of this group + // calc the morale of this group group->morale = group->moraleAdjust; - for ( i = 0; i < group->numGroup; i++ ) - { + for (i = 0; i < group->numGroup; i++) { member = &g_entities[group->member[i].number]; - if ( member->NPC->rank < RANK_ENSIGN ) - {//grunts + if (member->NPC->rank < RANK_ENSIGN) { // grunts group->morale++; - } - else - { + } else { group->morale += member->NPC->rank; } - if ( group->commander && d_npcai.integer ) - { - //G_DebugLine( group->commander->r.currentOrigin, member->r.currentOrigin, FRAMETIME, 0x00ff00ff, qtrue ); + if (group->commander && d_npcai.integer) { + // G_DebugLine( group->commander->r.currentOrigin, member->r.currentOrigin, FRAMETIME, 0x00ff00ff, qtrue ); G_TestLine(group->commander->r.currentOrigin, member->r.currentOrigin, 0x00000ff, FRAMETIME); } } - if ( group->enemy ) - {//modify morale based on enemy health and weapon - if ( group->enemy->health < 10 ) - { + if (group->enemy) { // modify morale based on enemy health and weapon + if (group->enemy->health < 10) { group->morale += 10; - } - else if ( group->enemy->health < 25 ) - { + } else if (group->enemy->health < 25) { group->morale += 5; - } - else if ( group->enemy->health < 50 ) - { + } else if (group->enemy->health < 50) { group->morale += 2; } - switch( group->enemy->s.weapon ) - { + switch (group->enemy->s.weapon) { case WP_SABER: group->morale -= 5; break; @@ -913,77 +757,66 @@ qboolean AI_RefreshGroup( AIGroupInfo_t *group ) case WP_DET_PACK: group->morale -= 10; break; -// case WP_MELEE: // Any ol' melee attack -// group->morale += 20; -// break; + // case WP_MELEE: // Any ol' melee attack + // group->morale += 20; + // break; case WP_STUN_BATON: group->morale += 10; break; case WP_EMPLACED_GUN: group->morale -= 8; break; -// case WP_ATST_MAIN: -// group->morale -= 8; -// break; -// case WP_ATST_SIDE: -// group->morale -= 20; -// break; + // case WP_ATST_MAIN: + // group->morale -= 8; + // break; + // case WP_ATST_SIDE: + // group->morale -= 20; + // break; } } - if ( group->moraleDebounce < level.time ) - {//slowly degrade whatever moraleAdjusters we may have - if ( group->moraleAdjust > 0 ) - { + if (group->moraleDebounce < level.time) { // slowly degrade whatever moraleAdjusters we may have + if (group->moraleAdjust > 0) { group->moraleAdjust--; - } - else if ( group->moraleAdjust < 0 ) - { + } else if (group->moraleAdjust < 0) { group->moraleAdjust++; } - group->moraleDebounce = level.time + 1000;//FIXME: define? + group->moraleDebounce = level.time + 1000; // FIXME: define? } - //mark this group as not having been run this frame + // mark this group as not having been run this frame group->processed = qfalse; - return (group->numGroup>0); + return (group->numGroup > 0); } -void AI_UpdateGroups( void ) -{ +void AI_UpdateGroups(void) { int i; - if ( d_noGroupAI.integer ) - { + if (d_noGroupAI.integer) { return; } - //Clear all Groups - for ( i = 0; i < MAX_FRAME_GROUPS; i++ ) - { - if ( !level.groups[i].numGroup || AI_RefreshGroup( &level.groups[i] ) == qfalse )//level.groups[i].enemy == NULL || + // Clear all Groups + for (i = 0; i < MAX_FRAME_GROUPS; i++) { + if (!level.groups[i].numGroup || AI_RefreshGroup(&level.groups[i]) == qfalse) // level.groups[i].enemy == NULL || { - memset( &level.groups[i], 0, sizeof( level.groups[i] ) ); + memset(&level.groups[i], 0, sizeof(level.groups[i])); } } } -qboolean AI_GroupContainsEntNum( AIGroupInfo_t *group, int entNum ) -{ +qboolean AI_GroupContainsEntNum(AIGroupInfo_t *group, int entNum) { int i; - if ( !group ) - { + if (!group) { return qfalse; } - for ( i = 0; i < group->numGroup; i++ ) - { - if ( group->member[i].number == entNum ) - { + for (i = 0; i < group->numGroup; i++) { + if (group->member[i].number == entNum) { return qtrue; } } return qfalse; } -//Overload +// Overload /* void AI_GetGroup( AIGroupInfo_t &group, gentity_t *ent, int radius ) @@ -1014,25 +847,22 @@ AI_CheckEnemyCollision ------------------------- */ -qboolean AI_CheckEnemyCollision( gentity_t *ent, qboolean takeEnemy ) -{ - navInfo_t info; +qboolean AI_CheckEnemyCollision(gentity_t *ent, qboolean takeEnemy) { + navInfo_t info; - if ( ent == NULL ) + if (ent == NULL) return qfalse; -// if ( ent->svFlags & SVF_LOCKEDENEMY ) -// return qfalse; + // if ( ent->svFlags & SVF_LOCKEDENEMY ) + // return qfalse; - NAV_GetLastMove( &info ); + NAV_GetLastMove(&info); - //See if we've hit something - if ( ( info.blocker ) && ( info.blocker != ent->enemy ) ) - { - if ( ( info.blocker->client ) && ( info.blocker->client->playerTeam == ent->client->enemyTeam ) ) - { - if ( takeEnemy ) - G_SetEnemy( ent, info.blocker ); + // See if we've hit something + if ((info.blocker) && (info.blocker != ent->enemy)) { + if ((info.blocker->client) && (info.blocker->client->playerTeam == ent->client->enemyTeam)) { + if (takeEnemy) + G_SetEnemy(ent, info.blocker); return qtrue; } @@ -1047,76 +877,71 @@ AI_DistributeAttack ------------------------- */ -#define MAX_RADIUS_ENTS 128 +#define MAX_RADIUS_ENTS 128 -gentity_t *AI_DistributeAttack( gentity_t *attacker, gentity_t *enemy, team_t team, int threshold ) -{ - int radiusEnts[ MAX_RADIUS_ENTS ]; - gentity_t *check; - int numEnts; - int numSurrounding; - int i; - int j; - vec3_t mins, maxs; - - //Don't take new targets -// if ( NPC->svFlags & SVF_LOCKEDENEMY ) -// return enemy; - - numSurrounding = AI_GetGroupSize( enemy->r.currentOrigin, 48, team, attacker ); - - //First, see if we should look for the player - if ( enemy != &g_entities[0] ) - { - //rwwFIXMEFIXME: care about all clients not just 0 - int aroundPlayer = AI_GetGroupSize( g_entities[0].r.currentOrigin, 48, team, attacker ); +gentity_t *AI_DistributeAttack(gentity_t *attacker, gentity_t *enemy, team_t team, int threshold) { + int radiusEnts[MAX_RADIUS_ENTS]; + gentity_t *check; + int numEnts; + int numSurrounding; + int i; + int j; + vec3_t mins, maxs; - //See if we're above our threshold - if ( aroundPlayer < threshold ) - { + // Don't take new targets + // if ( NPC->svFlags & SVF_LOCKEDENEMY ) + // return enemy; + + numSurrounding = AI_GetGroupSize(enemy->r.currentOrigin, 48, team, attacker); + + // First, see if we should look for the player + if (enemy != &g_entities[0]) { + // rwwFIXMEFIXME: care about all clients not just 0 + int aroundPlayer = AI_GetGroupSize(g_entities[0].r.currentOrigin, 48, team, attacker); + + // See if we're above our threshold + if (aroundPlayer < threshold) { return &g_entities[0]; } } - //See if our current enemy is still ok - if ( numSurrounding < threshold ) + // See if our current enemy is still ok + if (numSurrounding < threshold) return enemy; - //Otherwise we need to take a new enemy if possible + // Otherwise we need to take a new enemy if possible - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = enemy->r.currentOrigin[i] - 512; maxs[i] = enemy->r.currentOrigin[i] + 512; } - //Get the number of entities in a given space - numEnts = trap->EntitiesInBox( mins, maxs, radiusEnts, MAX_RADIUS_ENTS ); + // Get the number of entities in a given space + numEnts = trap->EntitiesInBox(mins, maxs, radiusEnts, MAX_RADIUS_ENTS); - //Cull this list - for ( j = 0; j < numEnts; j++ ) - { + // Cull this list + for (j = 0; j < numEnts; j++) { check = &g_entities[radiusEnts[j]]; - //Validate clients - if ( check->client == NULL ) + // Validate clients + if (check->client == NULL) continue; - //Skip the requested avoid ent if present - if ( check == enemy ) + // Skip the requested avoid ent if present + if (check == enemy) continue; - //Must be on the same team - if ( check->client->playerTeam != enemy->client->playerTeam ) + // Must be on the same team + if (check->client->playerTeam != enemy->client->playerTeam) continue; - //Must be alive - if ( check->health <= 0 ) + // Must be alive + if (check->health <= 0) continue; - //Must not be overwhelmed - if ( AI_GetGroupSize( check->r.currentOrigin, 48, team, attacker ) > threshold ) + // Must not be overwhelmed + if (AI_GetGroupSize(check->r.currentOrigin, 48, team, attacker) > threshold) continue; return check; diff --git a/codemp/game/NPC_AI_Wampa.c b/codemp/game/NPC_AI_Wampa.c index 34f4afb3ca..6c075f0afe 100644 --- a/codemp/game/NPC_AI_Wampa.c +++ b/codemp/game/NPC_AI_Wampa.c @@ -24,34 +24,32 @@ along with this program; if not, see . #include "g_nav.h" // These define the working combat range for these suckers -#define MIN_DISTANCE 48 -#define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) +#define MIN_DISTANCE 48 +#define MIN_DISTANCE_SQR (MIN_DISTANCE * MIN_DISTANCE) -#define MAX_DISTANCE 1024 -#define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) +#define MAX_DISTANCE 1024 +#define MAX_DISTANCE_SQR (MAX_DISTANCE * MAX_DISTANCE) -#define LSTATE_CLEAR 0 -#define LSTATE_WAITING 1 +#define LSTATE_CLEAR 0 +#define LSTATE_WAITING 1 float enemyDist = 0; -void Wampa_SetBolts( gentity_t *self ) -{ - if ( self && self->client ) - { +void Wampa_SetBolts(gentity_t *self) { + if (self && self->client) { renderInfo_t *ri = &self->client->renderInfo; ri->headBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*head_eyes"); - //ri->cervicalBolt = trap->G2API_AddBolt(self->ghoul2, 0, "neck_bone" ); - //ri->chestBolt = trap->G2API_AddBolt(self->ghoul2, 0, "upper_spine"); - //ri->gutBolt = trap->G2API_AddBolt(self->ghoul2, 0, "mid_spine"); + // ri->cervicalBolt = trap->G2API_AddBolt(self->ghoul2, 0, "neck_bone" ); + // ri->chestBolt = trap->G2API_AddBolt(self->ghoul2, 0, "upper_spine"); + // ri->gutBolt = trap->G2API_AddBolt(self->ghoul2, 0, "mid_spine"); ri->torsoBolt = trap->G2API_AddBolt(self->ghoul2, 0, "lower_spine"); ri->crotchBolt = trap->G2API_AddBolt(self->ghoul2, 0, "rear_bone"); - //ri->elbowLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_arm_elbow"); - //ri->elbowRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_arm_elbow"); + // ri->elbowLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_arm_elbow"); + // ri->elbowRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_arm_elbow"); ri->handLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_hand"); ri->handRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_hand"); - //ri->kneeLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*hips_l_knee"); - //ri->kneeRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*hips_r_knee"); + // ri->kneeLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*hips_l_knee"); + // ri->kneeRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*hips_r_knee"); ri->footLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_leg_foot"); ri->footRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_leg_foot"); } @@ -62,8 +60,7 @@ void Wampa_SetBolts( gentity_t *self ) NPC_Wampa_Precache ------------------------- */ -void NPC_Wampa_Precache( void ) -{ +void NPC_Wampa_Precache(void) { /* int i; for ( i = 1; i < 4; i ++ ) @@ -75,35 +72,30 @@ void NPC_Wampa_Precache( void ) G_SoundIndex( va("sound/chars/wampa/snort%d.wav", i) ); } */ - G_SoundIndex( "sound/chars/rancor/swipehit.wav" ); - //G_SoundIndex( "sound/chars/wampa/chomp.wav" ); + G_SoundIndex("sound/chars/rancor/swipehit.wav"); + // G_SoundIndex( "sound/chars/wampa/chomp.wav" ); } - /* ------------------------- Wampa_Idle ------------------------- */ -void Wampa_Idle( void ) -{ +void Wampa_Idle(void) { NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons &= ~BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } -qboolean Wampa_CheckRoar( gentity_t *self ) -{ - if ( self->wait < level.time ) - { - self->wait = level.time + Q_irand( 5000, 20000 ); - NPC_SetAnim( self, SETANIM_BOTH, Q_irand(BOTH_GESTURE1,BOTH_GESTURE2), (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD) ); - TIMER_Set( self, "rageTime", self->client->ps.legsTimer ); +qboolean Wampa_CheckRoar(gentity_t *self) { + if (self->wait < level.time) { + self->wait = level.time + Q_irand(5000, 20000); + NPC_SetAnim(self, SETANIM_BOTH, Q_irand(BOTH_GESTURE1, BOTH_GESTURE2), (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD)); + TIMER_Set(self, "rageTime", self->client->ps.legsTimer); return qtrue; } return qfalse; @@ -113,31 +105,25 @@ qboolean Wampa_CheckRoar( gentity_t *self ) Wampa_Patrol ------------------------- */ -void Wampa_Patrol( void ) -{ +void Wampa_Patrol(void) { NPCS.NPCInfo->localState = LSTATE_CLEAR; - //If we have somewhere to go, then do that - if ( UpdateGoal() ) - { + // If we have somewhere to go, then do that + if (UpdateGoal()) { NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_MoveToGoal( qtrue ); - } - else - { - if ( TIMER_Done( NPCS.NPC, "patrolTime" )) - { - TIMER_Set( NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000 ); + NPC_MoveToGoal(qtrue); + } else { + if (TIMER_Done(NPCS.NPC, "patrolTime")) { + TIMER_Set(NPCS.NPC, "patrolTime", Q_flrand(-1.0f, 1.0f) * 5000 + 5000); } } - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Wampa_Idle(); return; } - Wampa_CheckRoar( NPCS.NPC ); - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); + Wampa_CheckRoar(NPCS.NPC); + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(5000, 15000)); } /* @@ -145,301 +131,237 @@ void Wampa_Patrol( void ) Wampa_Move ------------------------- */ -void Wampa_Move( qboolean visible ) -{ - if ( NPCS.NPCInfo->localState != LSTATE_WAITING ) - { +void Wampa_Move(qboolean visible) { + if (NPCS.NPCInfo->localState != LSTATE_WAITING) { NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - if ( NPCS.NPC->enemy ) - {//pick correct movement speed and anim - //run by default + if (NPCS.NPC->enemy) { // pick correct movement speed and anim + // run by default NPCS.ucmd.buttons &= ~BUTTON_WALKING; - if ( !TIMER_Done( NPCS.NPC, "runfar" ) - || !TIMER_Done( NPCS.NPC, "runclose" ) ) - {//keep running with this anim & speed for a bit - } - else if ( !TIMER_Done( NPCS.NPC, "walk" ) ) - {//keep walking for a bit + if (!TIMER_Done(NPCS.NPC, "runfar") || !TIMER_Done(NPCS.NPC, "runclose")) { // keep running with this anim & speed for a bit + } else if (!TIMER_Done(NPCS.NPC, "walk")) { // keep walking for a bit NPCS.ucmd.buttons |= BUTTON_WALKING; - } - else if ( visible && enemyDist > 384 && NPCS.NPCInfo->stats.runSpeed == 180 ) - {//fast run, all fours + } else if (visible && enemyDist > 384 && NPCS.NPCInfo->stats.runSpeed == 180) { // fast run, all fours NPCS.NPCInfo->stats.runSpeed = 300; - TIMER_Set( NPCS.NPC, "runfar", Q_irand( 2000, 4000 ) ); - } - else if ( enemyDist > 256 && NPCS.NPCInfo->stats.runSpeed == 300 ) - {//slow run, upright + TIMER_Set(NPCS.NPC, "runfar", Q_irand(2000, 4000)); + } else if (enemyDist > 256 && NPCS.NPCInfo->stats.runSpeed == 300) { // slow run, upright NPCS.NPCInfo->stats.runSpeed = 180; - TIMER_Set( NPCS.NPC, "runclose", Q_irand( 3000, 5000 ) ); - } - else if ( enemyDist < 128 ) - {//walk + TIMER_Set(NPCS.NPC, "runclose", Q_irand(3000, 5000)); + } else if (enemyDist < 128) { // walk NPCS.NPCInfo->stats.runSpeed = 180; NPCS.ucmd.buttons |= BUTTON_WALKING; - TIMER_Set( NPCS.NPC, "walk", Q_irand( 4000, 6000 ) ); + TIMER_Set(NPCS.NPC, "walk", Q_irand(4000, 6000)); } } - if ( NPCS.NPCInfo->stats.runSpeed == 300 ) - {//need to use the alternate run - hunched over on all fours + if (NPCS.NPCInfo->stats.runSpeed == 300) { // need to use the alternate run - hunched over on all fours NPCS.NPC->client->ps.eFlags2 |= EF2_USE_ALT_ANIM; } - NPC_MoveToGoal( qtrue ); - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPC_MoveToGoal(qtrue); + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range } } //--------------------------------------------------------- -extern void G_Knockdown( gentity_t *victim ); -extern void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, qboolean postDeath ); -extern int NPC_GetEntsNearBolt( int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg ); - -void Wampa_Slash( int boltIndex, qboolean backhand ) -{ - int radiusEntNums[128]; - int numEnts; - const float radius = 88; - const float radiusSquared = (radius*radius); - int i; - vec3_t boltOrg; - int damage = (backhand)?Q_irand(10,15):Q_irand(20,30); - - numEnts = NPC_GetEntsNearBolt( radiusEntNums, radius, boltIndex, boltOrg ); - - for ( i = 0; i < numEnts; i++ ) - { +extern void G_Knockdown(gentity_t *victim); +extern void G_Dismember(gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, + qboolean postDeath); +extern int NPC_GetEntsNearBolt(int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg); + +void Wampa_Slash(int boltIndex, qboolean backhand) { + int radiusEntNums[128]; + int numEnts; + const float radius = 88; + const float radiusSquared = (radius * radius); + int i; + vec3_t boltOrg; + int damage = (backhand) ? Q_irand(10, 15) : Q_irand(20, 30); + + numEnts = NPC_GetEntsNearBolt(radiusEntNums, radius, boltIndex, boltOrg); + + for (i = 0; i < numEnts; i++) { gentity_t *radiusEnt = &g_entities[radiusEntNums[i]]; - if ( !radiusEnt->inuse ) - { + if (!radiusEnt->inuse) { continue; } - if ( radiusEnt == NPCS.NPC ) - {//Skip the wampa ent + if (radiusEnt == NPCS.NPC) { // Skip the wampa ent continue; } - if ( radiusEnt->client == NULL ) - {//must be a client + if (radiusEnt->client == NULL) { // must be a client continue; } - if ( DistanceSquared( radiusEnt->r.currentOrigin, boltOrg ) <= radiusSquared ) - { - //smack - G_Damage( radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, damage, ((backhand)?DAMAGE_NO_ARMOR:(DAMAGE_NO_ARMOR|DAMAGE_NO_KNOCKBACK)), MOD_MELEE ); - if ( backhand ) - { - //actually push the enemy + if (DistanceSquared(radiusEnt->r.currentOrigin, boltOrg) <= radiusSquared) { + // smack + G_Damage(radiusEnt, NPCS.NPC, NPCS.NPC, vec3_origin, radiusEnt->r.currentOrigin, damage, + ((backhand) ? DAMAGE_NO_ARMOR : (DAMAGE_NO_ARMOR | DAMAGE_NO_KNOCKBACK)), MOD_MELEE); + if (backhand) { + // actually push the enemy vec3_t pushDir; vec3_t angs; - VectorCopy( NPCS.NPC->client->ps.viewangles, angs ); - angs[YAW] += flrand( 25, 50 ); - angs[PITCH] = flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - if ( radiusEnt->client->NPC_class != CLASS_WAMPA - && radiusEnt->client->NPC_class != CLASS_RANCOR - && radiusEnt->client->NPC_class != CLASS_ATST ) - { - G_Throw( radiusEnt, pushDir, 65 ); - if ( BG_KnockDownable(&radiusEnt->client->ps) && - radiusEnt->health > 0 && Q_irand( 0, 1 ) ) - {//do pain on enemy + VectorCopy(NPCS.NPC->client->ps.viewangles, angs); + angs[YAW] += flrand(25, 50); + angs[PITCH] = flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + if (radiusEnt->client->NPC_class != CLASS_WAMPA && radiusEnt->client->NPC_class != CLASS_RANCOR && radiusEnt->client->NPC_class != CLASS_ATST) { + G_Throw(radiusEnt, pushDir, 65); + if (BG_KnockDownable(&radiusEnt->client->ps) && radiusEnt->health > 0 && Q_irand(0, 1)) { // do pain on enemy radiusEnt->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; radiusEnt->client->ps.forceDodgeAnim = 0; radiusEnt->client->ps.forceHandExtendTime = level.time + 1100; radiusEnt->client->ps.quickerGetup = qfalse; } } - } - else if ( radiusEnt->health <= 0 && radiusEnt->client ) - {//killed them, chance of dismembering - if ( !Q_irand( 0, 1 ) ) - {//bite something off - int hitLoc = Q_irand( G2_MODELPART_HEAD, G2_MODELPART_RLEG ); - if ( hitLoc == G2_MODELPART_HEAD ) - { - NPC_SetAnim( radiusEnt, SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + } else if (radiusEnt->health <= 0 && radiusEnt->client) { // killed them, chance of dismembering + if (!Q_irand(0, 1)) { // bite something off + int hitLoc = Q_irand(G2_MODELPART_HEAD, G2_MODELPART_RLEG); + if (hitLoc == G2_MODELPART_HEAD) { + NPC_SetAnim(radiusEnt, SETANIM_BOTH, BOTH_DEATH17, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (hitLoc == G2_MODELPART_WAIST) { + NPC_SetAnim(radiusEnt, SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - else if ( hitLoc == G2_MODELPART_WAIST ) - { - NPC_SetAnim( radiusEnt, SETANIM_BOTH, BOTH_DEATHBACKWARD2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - G_Dismember( radiusEnt, NPCS.NPC, radiusEnt->r.currentOrigin, hitLoc, 90, 0, radiusEnt->client->ps.torsoAnim, qtrue); + G_Dismember(radiusEnt, NPCS.NPC, radiusEnt->r.currentOrigin, hitLoc, 90, 0, radiusEnt->client->ps.torsoAnim, qtrue); } - } - else if ( !Q_irand( 0, 3 ) && radiusEnt->health > 0 ) - {//one out of every 4 normal hits does a knockdown, too + } else if (!Q_irand(0, 3) && radiusEnt->health > 0) { // one out of every 4 normal hits does a knockdown, too vec3_t pushDir; vec3_t angs; - VectorCopy( NPCS.NPC->client->ps.viewangles, angs ); - angs[YAW] += flrand( 25, 50 ); - angs[PITCH] = flrand( -25, -15 ); - AngleVectors( angs, pushDir, NULL, NULL ); - G_Knockdown( radiusEnt ); + VectorCopy(NPCS.NPC->client->ps.viewangles, angs); + angs[YAW] += flrand(25, 50); + angs[PITCH] = flrand(-25, -15); + AngleVectors(angs, pushDir, NULL, NULL); + G_Knockdown(radiusEnt); } - G_Sound( radiusEnt, CHAN_WEAPON, G_SoundIndex( "sound/chars/rancor/swipehit.wav" ) ); + G_Sound(radiusEnt, CHAN_WEAPON, G_SoundIndex("sound/chars/rancor/swipehit.wav")); } } } //------------------------------ -void Wampa_Attack( float distance, qboolean doCharge ) -{ - if ( !TIMER_Exists( NPCS.NPC, "attacking" ) ) - { - if ( Q_irand(0, 2) && !doCharge ) - {//double slash - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 750 ); - } - else if ( doCharge || (distance > 270 && distance < 430 && !Q_irand(0, 1)) ) - {//leap - vec3_t fwd, yawAng; - VectorSet( yawAng, 0, NPCS.NPC->client->ps.viewangles[YAW], 0 ); - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 500 ); - AngleVectors( yawAng, fwd, NULL, NULL ); - VectorScale( fwd, distance*1.5f, NPCS.NPC->client->ps.velocity ); +void Wampa_Attack(float distance, qboolean doCharge) { + if (!TIMER_Exists(NPCS.NPC, "attacking")) { + if (Q_irand(0, 2) && !doCharge) { // double slash + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 750); + } else if (doCharge || (distance > 270 && distance < 430 && !Q_irand(0, 1))) { // leap + vec3_t fwd, yawAng; + VectorSet(yawAng, 0, NPCS.NPC->client->ps.viewangles[YAW], 0); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 500); + AngleVectors(yawAng, fwd, NULL, NULL); + VectorScale(fwd, distance * 1.5f, NPCS.NPC->client->ps.velocity); NPCS.NPC->client->ps.velocity[2] = 150; NPCS.NPC->client->ps.groundEntityNum = ENTITYNUM_NONE; - } - else - {//backhand - NPC_SetAnim( NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - TIMER_Set( NPCS.NPC, "attack_dmg", 250 ); + } else { // backhand + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_ATTACK3, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + TIMER_Set(NPCS.NPC, "attack_dmg", 250); } - TIMER_Set( NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_flrand(0.0f, 1.0f) * 200 ); - //allow us to re-evaluate our running speed/anim - TIMER_Set( NPCS.NPC, "runfar", -1 ); - TIMER_Set( NPCS.NPC, "runclose", -1 ); - TIMER_Set( NPCS.NPC, "walk", -1 ); + TIMER_Set(NPCS.NPC, "attacking", NPCS.NPC->client->ps.legsTimer + Q_flrand(0.0f, 1.0f) * 200); + // allow us to re-evaluate our running speed/anim + TIMER_Set(NPCS.NPC, "runfar", -1); + TIMER_Set(NPCS.NPC, "runclose", -1); + TIMER_Set(NPCS.NPC, "walk", -1); } // Need to do delayed damage since the attack animations encapsulate multiple mini-attacks - if ( TIMER_Done2( NPCS.NPC, "attack_dmg", qtrue ) ) - { - switch ( NPCS.NPC->client->ps.legsAnim ) - { + if (TIMER_Done2(NPCS.NPC, "attack_dmg", qtrue)) { + switch (NPCS.NPC->client->ps.legsAnim) { case BOTH_ATTACK1: - Wampa_Slash( NPCS.NPC->client->renderInfo.handRBolt, qfalse ); - //do second hit - TIMER_Set( NPCS.NPC, "attack_dmg2", 100 ); + Wampa_Slash(NPCS.NPC->client->renderInfo.handRBolt, qfalse); + // do second hit + TIMER_Set(NPCS.NPC, "attack_dmg2", 100); break; case BOTH_ATTACK2: - Wampa_Slash( NPCS.NPC->client->renderInfo.handRBolt, qfalse ); - TIMER_Set( NPCS.NPC, "attack_dmg2", 100 ); + Wampa_Slash(NPCS.NPC->client->renderInfo.handRBolt, qfalse); + TIMER_Set(NPCS.NPC, "attack_dmg2", 100); break; case BOTH_ATTACK3: - Wampa_Slash( NPCS.NPC->client->renderInfo.handLBolt, qtrue ); + Wampa_Slash(NPCS.NPC->client->renderInfo.handLBolt, qtrue); break; } - } - else if ( TIMER_Done2( NPCS.NPC, "attack_dmg2", qtrue ) ) - { - switch ( NPCS.NPC->client->ps.legsAnim ) - { + } else if (TIMER_Done2(NPCS.NPC, "attack_dmg2", qtrue)) { + switch (NPCS.NPC->client->ps.legsAnim) { case BOTH_ATTACK1: - Wampa_Slash( NPCS.NPC->client->renderInfo.handLBolt, qfalse ); + Wampa_Slash(NPCS.NPC->client->renderInfo.handLBolt, qfalse); break; case BOTH_ATTACK2: - Wampa_Slash( NPCS.NPC->client->renderInfo.handLBolt, qfalse ); + Wampa_Slash(NPCS.NPC->client->renderInfo.handLBolt, qfalse); break; } } // Just using this to remove the attacking flag at the right time - TIMER_Done2( NPCS.NPC, "attacking", qtrue ); + TIMER_Done2(NPCS.NPC, "attacking", qtrue); - if ( NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK1 && distance > (NPCS.NPC->r.maxs[0]+MIN_DISTANCE) ) - {//okay to keep moving + if (NPCS.NPC->client->ps.legsAnim == BOTH_ATTACK1 && distance > (NPCS.NPC->r.maxs[0] + MIN_DISTANCE)) { // okay to keep moving NPCS.ucmd.buttons |= BUTTON_WALKING; - Wampa_Move( qtrue ); + Wampa_Move(qtrue); } } //---------------------------------- -void Wampa_Combat( void ) -{ +void Wampa_Combat(void) { // If we cannot see our target or we have somewhere to go, then do that - if ( !NPC_ClearLOS( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ) ) - { - if ( !Q_irand( 0, 10 ) ) - { - if ( Wampa_CheckRoar( NPCS.NPC ) ) - { + if (!NPC_ClearLOS(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin)) { + if (!Q_irand(0, 10)) { + if (Wampa_CheckRoar(NPCS.NPC)) { return; } } NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - Wampa_Move( qfalse ); + Wampa_Move(qfalse); return; - } - else if ( UpdateGoal() ) - { + } else if (UpdateGoal()) { NPCS.NPCInfo->combatMove = qtrue; NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; - NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range + NPCS.NPCInfo->goalRadius = MAX_DISTANCE; // just get us within combat range - Wampa_Move( qtrue ); + Wampa_Move(qtrue); return; - } - else - { - float distance = enemyDist = Distance( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - qboolean advance = (qboolean)( distance > (NPCS.NPC->r.maxs[0]+MIN_DISTANCE) ? qtrue : qfalse ); - qboolean doCharge = qfalse; + } else { + float distance = enemyDist = Distance(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + qboolean advance = (qboolean)(distance > (NPCS.NPC->r.maxs[0] + MIN_DISTANCE) ? qtrue : qfalse); + qboolean doCharge = qfalse; // Sometimes I have problems with facing the enemy I'm attacking, so force the issue so I don't look dumb - //FIXME: always seems to face off to the left or right?!!!! - NPC_FaceEnemy( qtrue ); - - - if ( advance ) - {//have to get closer - vec3_t yawOnlyAngles; - VectorSet( yawOnlyAngles, 0, NPCS.NPC->r.currentAngles[YAW], 0 ); - if ( NPCS.NPC->enemy->health > 0//enemy still alive - && fabs(distance-350) <= 80 //enemy anywhere from 270 to 430 away - && InFOV3( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, yawOnlyAngles, 20, 20 ) )//enemy generally in front - {//10% chance of doing charge anim - if ( !Q_irand( 0, 9 ) ) - {//go for the charge + // FIXME: always seems to face off to the left or right?!!!! + NPC_FaceEnemy(qtrue); + + if (advance) { // have to get closer + vec3_t yawOnlyAngles; + VectorSet(yawOnlyAngles, 0, NPCS.NPC->r.currentAngles[YAW], 0); + if (NPCS.NPC->enemy->health > 0 // enemy still alive + && fabs(distance - 350) <= 80 // enemy anywhere from 270 to 430 away + && InFOV3(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, yawOnlyAngles, 20, 20)) // enemy generally in front + { // 10% chance of doing charge anim + if (!Q_irand(0, 9)) { // go for the charge doCharge = qtrue; advance = qfalse; } } } - if (( advance || NPCS.NPCInfo->localState == LSTATE_WAITING ) && TIMER_Done( NPCS.NPC, "attacking" )) // waiting monsters can't attack + if ((advance || NPCS.NPCInfo->localState == LSTATE_WAITING) && TIMER_Done(NPCS.NPC, "attacking")) // waiting monsters can't attack { - if ( TIMER_Done2( NPCS.NPC, "takingPain", qtrue )) - { + if (TIMER_Done2(NPCS.NPC, "takingPain", qtrue)) { NPCS.NPCInfo->localState = LSTATE_CLEAR; + } else { + Wampa_Move(qtrue); } - else - { - Wampa_Move( qtrue ); - } - } - else - { - if ( !Q_irand( 0, 20 ) ) - {//FIXME: only do this if we just damaged them or vice-versa? - if ( Wampa_CheckRoar( NPCS.NPC ) ) - { + } else { + if (!Q_irand(0, 20)) { // FIXME: only do this if we just damaged them or vice-versa? + if (Wampa_CheckRoar(NPCS.NPC)) { return; } } - if ( !Q_irand( 0, 1 ) ) - {//FIXME: base on skill - Wampa_Attack( distance, doCharge ); + if (!Q_irand(0, 1)) { // FIXME: base on skill + Wampa_Attack(distance, doCharge); } } } @@ -450,66 +372,49 @@ void Wampa_Combat( void ) NPC_Wampa_Pain ------------------------- */ -void NPC_Wampa_Pain( gentity_t *self, gentity_t *attacker, int damage ) -{ +void NPC_Wampa_Pain(gentity_t *self, gentity_t *attacker, int damage) { qboolean hitByWampa = qfalse; - if ( attacker&&attacker->client&&attacker->client->NPC_class==CLASS_WAMPA ) - { + if (attacker && attacker->client && attacker->client->NPC_class == CLASS_WAMPA) { hitByWampa = qtrue; } - if ( attacker - && attacker->inuse - && attacker != self->enemy - && !(attacker->flags&FL_NOTARGET) ) - { - if ( (!attacker->s.number&&!Q_irand(0,3)) - || !self->enemy - || self->enemy->health == 0 - || (self->enemy->client&&self->enemy->client->NPC_class == CLASS_WAMPA) - || (!Q_irand(0, 4 ) && DistanceSquared( attacker->r.currentOrigin, self->r.currentOrigin ) < DistanceSquared( self->enemy->r.currentOrigin, self->r.currentOrigin )) ) - {//if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker - //FIXME: if can't nav to my enemy, take this guy if I can nav to him - G_SetEnemy( self, attacker ); - TIMER_Set( self, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - if ( hitByWampa ) - {//stay mad at this Wampa for 2-5 secs before looking for attacker enemies - TIMER_Set( self, "wampaInfight", Q_irand( 2000, 5000 ) ); + if (attacker && attacker->inuse && attacker != self->enemy && !(attacker->flags & FL_NOTARGET)) { + if ((!attacker->s.number && !Q_irand(0, 3)) || !self->enemy || self->enemy->health == 0 || + (self->enemy->client && self->enemy->client->NPC_class == CLASS_WAMPA) || + (!Q_irand(0, 4) && + DistanceSquared(attacker->r.currentOrigin, self->r.currentOrigin) < + DistanceSquared( + self->enemy->r.currentOrigin, + self->r.currentOrigin))) { // if my enemy is dead (or attacked by player) and I'm not still holding/eating someone, turn on the attacker + // FIXME: if can't nav to my enemy, take this guy if I can nav to him + G_SetEnemy(self, attacker); + TIMER_Set(self, "lookForNewEnemy", Q_irand(5000, 15000)); + if (hitByWampa) { // stay mad at this Wampa for 2-5 secs before looking for attacker enemies + TIMER_Set(self, "wampaInfight", Q_irand(2000, 5000)); } } } - if ( (hitByWampa|| Q_irand( 0, 100 ) < damage )//hit by wampa, hit while holding live victim, or took a lot of damage - && self->client->ps.legsAnim != BOTH_GESTURE1 - && self->client->ps.legsAnim != BOTH_GESTURE2 - && TIMER_Done( self, "takingPain" ) ) - { - if ( !Wampa_CheckRoar( self ) ) - { - if ( self->client->ps.legsAnim != BOTH_ATTACK1 - && self->client->ps.legsAnim != BOTH_ATTACK2 - && self->client->ps.legsAnim != BOTH_ATTACK3 ) - {//cant interrupt one of the big attack anims - if ( self->health > 100 || hitByWampa ) - { - TIMER_Remove( self, "attacking" ); - - VectorCopy( self->NPC->lastPathAngles, self->s.angles ); - - if ( !Q_irand( 0, 1 ) ) - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); - } - else - { - NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD ); + if ((hitByWampa || Q_irand(0, 100) < damage) // hit by wampa, hit while holding live victim, or took a lot of damage + && self->client->ps.legsAnim != BOTH_GESTURE1 && self->client->ps.legsAnim != BOTH_GESTURE2 && TIMER_Done(self, "takingPain")) { + if (!Wampa_CheckRoar(self)) { + if (self->client->ps.legsAnim != BOTH_ATTACK1 && self->client->ps.legsAnim != BOTH_ATTACK2 && + self->client->ps.legsAnim != BOTH_ATTACK3) { // cant interrupt one of the big attack anims + if (self->health > 100 || hitByWampa) { + TIMER_Remove(self, "attacking"); + + VectorCopy(self->NPC->lastPathAngles, self->s.angles); + + if (!Q_irand(0, 1)) { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + NPC_SetAnim(self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - TIMER_Set( self, "takingPain", self->client->ps.legsTimer+Q_irand(0, 500) ); - //allow us to re-evaluate our running speed/anim - TIMER_Set( self, "runfar", -1 ); - TIMER_Set( self, "runclose", -1 ); - TIMER_Set( self, "walk", -1 ); - - if ( self->NPC ) - { + TIMER_Set(self, "takingPain", self->client->ps.legsTimer + Q_irand(0, 500)); + // allow us to re-evaluate our running speed/anim + TIMER_Set(self, "runfar", -1); + TIMER_Set(self, "runclose", -1); + TIMER_Set(self, "walk", -1); + + if (self->NPC) { self->NPC->localState = LSTATE_WAITING; } } @@ -523,153 +428,118 @@ void NPC_Wampa_Pain( gentity_t *self, gentity_t *attacker, int damage ) NPC_BSWampa_Default ------------------------- */ -void NPC_BSWampa_Default( void ) -{ +void NPC_BSWampa_Default(void) { NPCS.NPC->client->ps.eFlags2 &= ~EF2_USE_ALT_ANIM; - //NORMAL ANIMS + // NORMAL ANIMS // stand1 = normal stand // walk1 = normal, non-angry walk // walk2 = injured // run1 = far away run // run2 = close run - //VICTIM ANIMS + // VICTIM ANIMS // grabswipe = melee1 - sweep out and grab // stand2 attack = attack4 - while holding victim, swipe at him // walk3_drag = walk5 - walk with drag // stand2 = hold victim // stand2to1 = drop victim - if ( !TIMER_Done( NPCS.NPC, "rageTime" ) ) - {//do nothing but roar first time we see an enemy - NPC_FaceEnemy( qtrue ); + if (!TIMER_Done(NPCS.NPC, "rageTime")) { // do nothing but roar first time we see an enemy + NPC_FaceEnemy(qtrue); return; } - if ( NPCS.NPC->enemy ) - { - if ( !TIMER_Done(NPCS.NPC,"attacking") ) - {//in middle of attack - //face enemy - NPC_FaceEnemy( qtrue ); - //continue attack logic - enemyDist = Distance( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ); - Wampa_Attack( enemyDist, qfalse ); + if (NPCS.NPC->enemy) { + if (!TIMER_Done(NPCS.NPC, "attacking")) { // in middle of attack + // face enemy + NPC_FaceEnemy(qtrue); + // continue attack logic + enemyDist = Distance(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin); + Wampa_Attack(enemyDist, qfalse); return; - } - else - { - if ( TIMER_Done(NPCS.NPC,"angrynoise") ) - { - G_Sound( NPCS.NPC, CHAN_VOICE, G_SoundIndex( va("sound/chars/wampa/misc/anger%d.wav", Q_irand(1, 2)) ) ); + } else { + if (TIMER_Done(NPCS.NPC, "angrynoise")) { + G_Sound(NPCS.NPC, CHAN_VOICE, G_SoundIndex(va("sound/chars/wampa/misc/anger%d.wav", Q_irand(1, 2)))); - TIMER_Set( NPCS.NPC, "angrynoise", Q_irand( 5000, 10000 ) ); + TIMER_Set(NPCS.NPC, "angrynoise", Q_irand(5000, 10000)); } - //else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while - if( NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_WAMPA ) - {//got mad at another Wampa, look for a valid enemy - if ( TIMER_Done( NPCS.NPC, "wampaInfight" ) ) - { - NPC_CheckEnemyExt( qtrue ); + // else, if he's in our hand, we eat, else if he's on the ground, we keep attacking his dead body for a while + if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_WAMPA) { // got mad at another Wampa, look for a valid enemy + if (TIMER_Done(NPCS.NPC, "wampaInfight")) { + NPC_CheckEnemyExt(qtrue); } - } - else - { - if ( ValidEnemy( NPCS.NPC->enemy ) == qfalse ) - { - TIMER_Remove( NPCS.NPC, "lookForNewEnemy" );//make them look again right now - if ( !NPCS.NPC->enemy->inuse || level.time - NPCS.NPC->enemy->s.time > Q_irand( 10000, 15000 ) ) - {//it's been a while since the enemy died, or enemy is completely gone, get bored with him + } else { + if (ValidEnemy(NPCS.NPC->enemy) == qfalse) { + TIMER_Remove(NPCS.NPC, "lookForNewEnemy"); // make them look again right now + if (!NPCS.NPC->enemy->inuse || + level.time - NPCS.NPC->enemy->s.time > + Q_irand(10000, 15000)) { // it's been a while since the enemy died, or enemy is completely gone, get bored with him NPCS.NPC->enemy = NULL; Wampa_Patrol(); - NPC_UpdateAngles( qtrue, qtrue ); - //just lost my enemy - if ( (NPCS.NPC->spawnflags&2) ) - {//search around me if I don't have an enemy - NPC_BSSearchStart( NPCS.NPC->waypoint, BS_SEARCH ); + NPC_UpdateAngles(qtrue, qtrue); + // just lost my enemy + if ((NPCS.NPC->spawnflags & 2)) { // search around me if I don't have an enemy + NPC_BSSearchStart(NPCS.NPC->waypoint, BS_SEARCH); NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else if ( (NPCS.NPC->spawnflags&1) ) - {//wander if I don't have an enemy - NPC_BSSearchStart( NPCS.NPC->waypoint, BS_WANDER ); + } else if ((NPCS.NPC->spawnflags & 1)) { // wander if I don't have an enemy + NPC_BSSearchStart(NPCS.NPC->waypoint, BS_WANDER); NPCS.NPCInfo->tempBehavior = BS_DEFAULT; } return; } } - if ( TIMER_Done( NPCS.NPC, "lookForNewEnemy" ) ) - { - gentity_t *newEnemy, *sav_enemy = NPCS.NPC->enemy;//FIXME: what about NPC->lastEnemy? + if (TIMER_Done(NPCS.NPC, "lookForNewEnemy")) { + gentity_t *newEnemy, *sav_enemy = NPCS.NPC->enemy; // FIXME: what about NPC->lastEnemy? NPCS.NPC->enemy = NULL; - newEnemy = NPC_CheckEnemy( NPCS.NPCInfo->confusionTime < level.time, qfalse, qfalse ); + newEnemy = NPC_CheckEnemy(NPCS.NPCInfo->confusionTime < level.time, qfalse, qfalse); NPCS.NPC->enemy = sav_enemy; - if ( newEnemy && newEnemy != sav_enemy ) - {//picked up a new enemy! + if (newEnemy && newEnemy != sav_enemy) { // picked up a new enemy! NPCS.NPC->lastEnemy = NPCS.NPC->enemy; - G_SetEnemy( NPCS.NPC, newEnemy ); - //hold this one for at least 5-15 seconds - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); - } - else - {//look again in 2-5 secs - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 2000, 5000 ) ); + G_SetEnemy(NPCS.NPC, newEnemy); + // hold this one for at least 5-15 seconds + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(5000, 15000)); + } else { // look again in 2-5 secs + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(2000, 5000)); } } } Wampa_Combat(); return; } - } - else - { - if ( TIMER_Done(NPCS.NPC,"idlenoise") ) - { - G_Sound( NPCS.NPC, CHAN_AUTO, G_SoundIndex( "sound/chars/wampa/misc/anger3.wav" ) ); + } else { + if (TIMER_Done(NPCS.NPC, "idlenoise")) { + G_Sound(NPCS.NPC, CHAN_AUTO, G_SoundIndex("sound/chars/wampa/misc/anger3.wav")); - TIMER_Set( NPCS.NPC, "idlenoise", Q_irand( 2000, 4000 ) ); + TIMER_Set(NPCS.NPC, "idlenoise", Q_irand(2000, 4000)); } - if ( (NPCS.NPC->spawnflags&2) ) - {//search around me if I don't have an enemy - if ( NPCS.NPCInfo->homeWp == WAYPOINT_NONE ) - {//no homewap, initialize the search behavior - NPC_BSSearchStart( WAYPOINT_NONE, BS_SEARCH ); + if ((NPCS.NPC->spawnflags & 2)) { // search around me if I don't have an enemy + if (NPCS.NPCInfo->homeWp == WAYPOINT_NONE) { // no homewap, initialize the search behavior + NPC_BSSearchStart(WAYPOINT_NONE, BS_SEARCH); NPCS.NPCInfo->tempBehavior = BS_DEFAULT; } NPCS.ucmd.buttons |= BUTTON_WALKING; - NPC_BSSearch();//this automatically looks for enemies - } - else if ( (NPCS.NPC->spawnflags&1) ) - {//wander if I don't have an enemy - if ( NPCS.NPCInfo->homeWp == WAYPOINT_NONE ) - {//no homewap, initialize the wander behavior - NPC_BSSearchStart( WAYPOINT_NONE, BS_WANDER ); + NPC_BSSearch(); // this automatically looks for enemies + } else if ((NPCS.NPC->spawnflags & 1)) { // wander if I don't have an enemy + if (NPCS.NPCInfo->homeWp == WAYPOINT_NONE) { // no homewap, initialize the wander behavior + NPC_BSSearchStart(WAYPOINT_NONE, BS_WANDER); NPCS.NPCInfo->tempBehavior = BS_DEFAULT; } NPCS.ucmd.buttons |= BUTTON_WALKING; NPC_BSWander(); - if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { - if ( NPC_CheckEnemyExt( qtrue ) == qfalse ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { + if (NPC_CheckEnemyExt(qtrue) == qfalse) { Wampa_Idle(); - } - else - { - Wampa_CheckRoar( NPCS.NPC ); - TIMER_Set( NPCS.NPC, "lookForNewEnemy", Q_irand( 5000, 15000 ) ); + } else { + Wampa_CheckRoar(NPCS.NPC); + TIMER_Set(NPCS.NPC, "lookForNewEnemy", Q_irand(5000, 15000)); } } - } - else - { - if ( NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) - { + } else { + if (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES) { Wampa_Patrol(); - } - else - { + } else { Wampa_Idle(); } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } diff --git a/codemp/game/NPC_behavior.c b/codemp/game/NPC_behavior.c index cc08a64040..00e2a7c27a 100644 --- a/codemp/game/NPC_behavior.c +++ b/codemp/game/NPC_behavior.c @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_behavior.cpp +// NPC_behavior.cpp /* FIXME - MCG: These all need to make use of the snapshots. Write something that can look for only specific @@ -32,109 +32,96 @@ we need it... #include "g_nav.h" #include "icarus/Q3_Interface.h" -extern qboolean showBBoxes; +extern qboolean showBBoxes; extern vec3_t NPCDEBUG_BLUE; -extern void G_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -extern void NPC_CheckGetNewWeapon( void ); +extern void G_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +extern void NPC_CheckGetNewWeapon(void); -extern qboolean PM_InKnockDown( playerState_t *ps ); +extern qboolean PM_InKnockDown(playerState_t *ps); -extern void NPC_AimAdjust( int change ); +extern void NPC_AimAdjust(int change); extern qboolean NPC_SomeoneLookingAtMe(gentity_t *ent); /* void NPC_BSAdvanceFight (void) Advance towards your captureGoal and shoot anyone you can along the way. */ -void NPC_BSAdvanceFight (void) -{//FIXME: IMPLEMENT - //Head to Goal if I can +void NPC_BSAdvanceFight(void) { // FIXME: IMPLEMENT + // Head to Goal if I can - //Make sure we're still headed where we want to capture - if ( NPCS.NPCInfo->captureGoal ) - {//FIXME: if no captureGoal, what do we do? - //VectorCopy( NPCInfo->captureGoal->r.currentOrigin, NPCInfo->tempGoal->r.currentOrigin ); - //NPCInfo->goalEntity = NPCInfo->tempGoal; + // Make sure we're still headed where we want to capture + if (NPCS.NPCInfo->captureGoal) { // FIXME: if no captureGoal, what do we do? + // VectorCopy( NPCInfo->captureGoal->r.currentOrigin, NPCInfo->tempGoal->r.currentOrigin ); + // NPCInfo->goalEntity = NPCInfo->tempGoal; - NPC_SetMoveGoal( NPCS.NPC, NPCS.NPCInfo->captureGoal->r.currentOrigin, 16, qtrue, -1, NULL ); + NPC_SetMoveGoal(NPCS.NPC, NPCS.NPCInfo->captureGoal->r.currentOrigin, 16, qtrue, -1, NULL); -// NAV_ClearLastRoute(NPC); + // NAV_ClearLastRoute(NPC); NPCS.NPCInfo->goalTime = level.time + 100000; } -// NPC_BSRun(); + // NPC_BSRun(); NPC_CheckEnemy(qtrue, qfalse, qtrue); - //FIXME: Need melee code - if( NPCS.NPC->enemy ) - {//See if we can shoot him - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; - qboolean dead_on = qfalse; - float attack_scale = 1.0; - float aim_off; - float max_aim_off = 64; - - //Yaw to enemy + // FIXME: Need melee code + if (NPCS.NPC->enemy) { // See if we can shoot him + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + qboolean dead_on = qfalse; + float attack_scale = 1.0; + float aim_off; + float max_aim_off = 64; + + // Yaw to enemy VectorMA(NPCS.NPC->enemy->r.absmin, 0.5, NPCS.NPC->enemy->r.maxs, enemy_org); - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); - if(!NPC_EnemyTooFar(NPCS.NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue)) - { + if (!NPC_EnemyTooFar(NPCS.NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { attack_ok = qtrue; } - if(attack_ok) - { + if (attack_ok) { NPC_UpdateShootAngles(angleToEnemy, qfalse, qtrue); NPCS.NPCInfo->enemyLastVisibility = NPCS.enemyVisibility; - NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_FOV);//CHECK_360|//CHECK_PVS| + NPCS.enemyVisibility = NPC_CheckVisibility(NPCS.NPC->enemy, CHECK_FOV); // CHECK_360|//CHECK_PVS| - if(NPCS.enemyVisibility == VIS_FOV) - {//He's in our FOV + if (NPCS.enemyVisibility == VIS_FOV) { // He's in our FOV attack_ok = qtrue; - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_head); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_head); - if(attack_ok) - { - trace_t tr; - gentity_t *traceEnt; - //are we gonna hit him if we shoot at his center? - trap->Trace ( &tr, muzzle, NULL, NULL, enemy_org, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + if (attack_ok) { + trace_t tr; + gentity_t *traceEnt; + // are we gonna hit him if we shoot at his center? + trap->Trace(&tr, muzzle, NULL, NULL, enemy_org, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); traceEnt = &g_entities[tr.entityNum]; - if( traceEnt != NPCS.NPC->enemy && - (!traceEnt || !traceEnt->client || !NPCS.NPC->client->enemyTeam || NPCS.NPC->client->enemyTeam != traceEnt->client->playerTeam) ) - {//no, so shoot for the head + if (traceEnt != NPCS.NPC->enemy && (!traceEnt || !traceEnt->client || !NPCS.NPC->client->enemyTeam || + NPCS.NPC->client->enemyTeam != traceEnt->client->playerTeam)) { // no, so shoot for the head attack_scale *= 0.75; - trap->Trace ( &tr, muzzle, NULL, NULL, enemy_head, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, muzzle, NULL, NULL, enemy_head, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); traceEnt = &g_entities[tr.entityNum]; } - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPCS.NPC->enemy || (traceEnt->client && NPCS.NPC->client->enemyTeam && NPCS.NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPCS.NPC->enemy || + (traceEnt->client && NPCS.NPC->client->enemyTeam && NPCS.NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPCS.NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPCS.NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPCS.NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPCS.NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -142,348 +129,317 @@ void NPC_BSAdvanceFight (void) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPCS.NPCInfo->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateShootAngles(angleToEnemy, qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - AngleVectors (NPCS.NPCInfo->shootAngles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + AngleVectors(NPCS.NPCInfo->shootAngles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_head, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot NPCS.enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); } } -//Don't do this- only for when stationary and trying to shoot an enemy -// else -// NPC->cantHitEnemyCounter++; - } - else - {//FIXME: + // Don't do this- only for when stationary and trying to shoot an enemy + // else + // NPC->cantHitEnemyCounter++; + } else { // FIXME: NPC_UpdateShootAngles(NPCS.NPC->client->ps.viewangles, qtrue, qtrue); } - if(!NPCS.ucmd.forwardmove && !NPCS.ucmd.rightmove) - {//We reached our captureGoal - if(trap->ICARUS_IsInitialized(NPCS.NPC->s.number)) - { - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_BSTATE ); + if (!NPCS.ucmd.forwardmove && !NPCS.ucmd.rightmove) { // We reached our captureGoal + if (trap->ICARUS_IsInitialized(NPCS.NPC->s.number)) { + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_BSTATE); } } } -void Disappear(gentity_t *self) -{ -// ClientDisconnect(self); +void Disappear(gentity_t *self) { + // ClientDisconnect(self); self->s.eFlags |= EF_NODRAW; self->think = 0; self->nextthink = -1; } -void MakeOwnerInvis (gentity_t *self); -void BeamOut (gentity_t *self) -{ -// gentity_t *tent = G_Spawn(); +void MakeOwnerInvis(gentity_t *self); +void BeamOut(gentity_t *self) { + // gentity_t *tent = G_Spawn(); -/* - tent->owner = self; - tent->think = MakeOwnerInvis; - tent->nextthink = level.time + 1800; - //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); - tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); -*/ - //fixme: doesn't actually go away! + /* + tent->owner = self; + tent->think = MakeOwnerInvis; + tent->nextthink = level.time + 1800; + //G_AddEvent( ent, EV_PLAYER_TELEPORT, 0 ); + tent = G_TempEntity( self->client->pcurrentOrigin, EV_PLAYER_TELEPORT ); + */ + // fixme: doesn't actually go away! self->nextthink = level.time + 1500; self->think = Disappear; self->client->squadname = NULL; self->client->playerTeam = self->s.teamowner = TEAM_FREE; - //self->r.svFlags |= SVF_BEAMING; //this appears unused in SP as well + // self->r.svFlags |= SVF_BEAMING; //this appears unused in SP as well } -void NPC_BSCinematic( void ) -{ +void NPC_BSCinematic(void) { - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - if ( UpdateGoal() ) - {//have a goalEntity - //move toward goal, should also face that goal - NPC_MoveToGoal( qtrue ); + if (UpdateGoal()) { // have a goalEntity + // move toward goal, should also face that goal + NPC_MoveToGoal(qtrue); } - if ( NPCS.NPCInfo->watchTarget ) - {//have an entity which we want to keep facing - //NOTE: this will override any angles set by NPC_MoveToGoal + if (NPCS.NPCInfo->watchTarget) { // have an entity which we want to keep facing + // NOTE: this will override any angles set by NPC_MoveToGoal vec3_t eyes, viewSpot, viewvec, viewangles; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD_LEAN, eyes ); - CalcEntitySpot( NPCS.NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD_LEAN, eyes); + CalcEntitySpot(NPCS.NPCInfo->watchTarget, SPOT_HEAD_LEAN, viewSpot); - VectorSubtract( viewSpot, eyes, viewvec ); + VectorSubtract(viewSpot, eyes, viewvec); - vectoangles( viewvec, viewangles ); + vectoangles(viewvec, viewangles); NPCS.NPCInfo->lockedDesiredYaw = NPCS.NPCInfo->desiredYaw = viewangles[YAW]; NPCS.NPCInfo->lockedDesiredPitch = NPCS.NPCInfo->desiredPitch = viewangles[PITCH]; } - NPC_UpdateAngles( qtrue, qtrue ); -} - -void NPC_BSWait( void ) -{ - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } +void NPC_BSWait(void) { NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSInvestigate (void) -{ -/* - //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the - //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) - vec3_t invDir, invAngles, spot; - gentity_t *saveGoal; - //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, - //look for enemies, then turn away after your investigate counter was down- - //investigate counter goes up every time you set it... - - if(level.time > NPCInfo->enemyCheckDebounceTime) - { - NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); - NPC_CheckEnemy(qtrue, qfalse); - if(NPC->enemy) - {//FIXME: do anger script - NPCInfo->goalEntity = NPC->enemy; -// NAV_ClearLastRoute(NPC); - NPCInfo->behaviorState = BS_RUN_AND_SHOOT; - NPCInfo->tempBehavior = BS_DEFAULT; - NPC_AngerSound(); - return; +void NPC_BSInvestigate(void) { + /* + //FIXME: maybe allow this to be set as a tempBState in a script? Just specify the + //investigateGoal, investigateDebounceTime and investigateCount? (Needs a macro) + vec3_t invDir, invAngles, spot; + gentity_t *saveGoal; + //BS_INVESTIGATE would turn toward goal, maybe take a couple steps towards it, + //look for enemies, then turn away after your investigate counter was down- + //investigate counter goes up every time you set it... + + if(level.time > NPCInfo->enemyCheckDebounceTime) + { + NPCInfo->enemyCheckDebounceTime = level.time + (NPCInfo->stats.vigilance * 1000); + NPC_CheckEnemy(qtrue, qfalse); + if(NPC->enemy) + {//FIXME: do anger script + NPCInfo->goalEntity = NPC->enemy; + // NAV_ClearLastRoute(NPC); + NPCInfo->behaviorState = BS_RUN_AND_SHOOT; + NPCInfo->tempBehavior = BS_DEFAULT; + NPC_AngerSound(); + return; + } } - } - NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); + NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_WEAPONREADY3, SETANIM_FLAG_NORMAL ); - if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) - { - VectorCopy(NPCInfo->eventOwner->r.currentOrigin, NPCInfo->investigateGoal); - } - - saveGoal = NPCInfo->goalEntity; - if( level.time > NPCInfo->walkDebounceTime ) - { - vec3_t vec; + if(NPCInfo->stats.vigilance <= 1.0 && NPCInfo->eventOwner) + { + VectorCopy(NPCInfo->eventOwner->r.currentOrigin, NPCInfo->investigateGoal); + } - VectorSubtract(NPCInfo->investigateGoal, NPC->r.currentOrigin, vec); - vec[2] = 0; - if(VectorLength(vec) > 64) + saveGoal = NPCInfo->goalEntity; + if( level.time > NPCInfo->walkDebounceTime ) { - if(Q_irand(0, 100) < NPCInfo->investigateCount) - {//take a full step - //NPCInfo->walkDebounceTime = level.time + 1400; - //actually finds length of my BOTH_WALK anim - NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + vec3_t vec; + + VectorSubtract(NPCInfo->investigateGoal, NPC->r.currentOrigin, vec); + vec[2] = 0; + if(VectorLength(vec) > 64) + { + if(Q_irand(0, 100) < NPCInfo->investigateCount) + {//take a full step + //NPCInfo->walkDebounceTime = level.time + 1400; + //actually finds length of my BOTH_WALK anim + NPCInfo->walkDebounceTime = PM_AnimLength( NPC->client->clientInfo.animFileIndex, BOTH_WALK1 ); + } } } - } - if( level.time < NPCInfo->walkDebounceTime ) - {//walk toward investigateGoal + if( level.time < NPCInfo->walkDebounceTime ) + {//walk toward investigateGoal - /* - NPCInfo->goalEntity = NPCInfo->tempGoal; -// NAV_ClearLastRoute(NPC); - VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->r.currentOrigin); - */ + /* + NPCInfo->goalEntity = NPCInfo->tempGoal; + // NAV_ClearLastRoute(NPC); + VectorCopy(NPCInfo->investigateGoal, NPCInfo->tempGoal->r.currentOrigin); + */ -/* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); + /* NPC_SetMoveGoal( NPC, NPCInfo->investigateGoal, 16, qtrue ); - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal( qtrue ); - //FIXME: walk2? - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); + //FIXME: walk2? + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_WALK1,SETANIM_FLAG_NORMAL); - ucmd.buttons |= BUTTON_WALKING; - } - else - { + ucmd.buttons |= BUTTON_WALKING; + } + else + { - NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + NPC_SetAnim(NPC,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - if(NPCInfo->hlookCount > 30) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->hlookCount > 30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount < -30) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->hlookCount < -30) { - NPCInfo->hlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->hlookCount = 0; + } } - } - else if(NPCInfo->hlookCount == 0) - { - NPCInfo->hlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 7) - { - if(NPCInfo->hlookCount > 0) + else if(NPCInfo->hlookCount == 0) { - NPCInfo->hlookCount++; + NPCInfo->hlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 7) { - NPCInfo->hlookCount--; + if(NPCInfo->hlookCount > 0) + { + NPCInfo->hlookCount++; + } + else//lookCount < 0 + { + NPCInfo->hlookCount--; + } } - } - if(NPCInfo->vlookCount >= 15) - { - if(Q_irand(0, 10) > 7) + if(NPCInfo->vlookCount >= 15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount <= -15) - { - if(Q_irand(0, 10) > 7) + else if(NPCInfo->vlookCount <= -15) { - NPCInfo->vlookCount = 0; + if(Q_irand(0, 10) > 7) + { + NPCInfo->vlookCount = 0; + } } - } - else if(NPCInfo->vlookCount == 0) - { - NPCInfo->vlookCount = Q_irand(-1, 1); - } - else if(Q_irand(0, 10) > 8) - { - if(NPCInfo->vlookCount > 0) + else if(NPCInfo->vlookCount == 0) { - NPCInfo->vlookCount++; + NPCInfo->vlookCount = Q_irand(-1, 1); } - else//lookCount < 0 + else if(Q_irand(0, 10) > 8) { - NPCInfo->vlookCount--; + if(NPCInfo->vlookCount > 0) + { + NPCInfo->vlookCount++; + } + else//lookCount < 0 + { + NPCInfo->vlookCount--; + } } - } - //turn toward investigateGoal - CalcEntitySpot( NPC, SPOT_HEAD, spot ); - VectorSubtract(NPCInfo->investigateGoal, spot, invDir); - VectorNormalize(invDir); - vectoangles(invDir, invAngles); - NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); - NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); - } + //turn toward investigateGoal + CalcEntitySpot( NPC, SPOT_HEAD, spot ); + VectorSubtract(NPCInfo->investigateGoal, spot, invDir); + VectorNormalize(invDir); + vectoangles(invDir, invAngles); + NPCInfo->desiredYaw = AngleNormalize360(invAngles[YAW] + NPCInfo->hlookCount); + NPCInfo->desiredPitch = AngleNormalize360(invAngles[PITCH] + NPCInfo->hlookCount); + } - NPC_UpdateAngles(qtrue, qtrue); + NPC_UpdateAngles(qtrue, qtrue); - NPCInfo->goalEntity = saveGoal; -// NAV_ClearLastRoute(NPC); + NPCInfo->goalEntity = saveGoal; + // NAV_ClearLastRoute(NPC); - if(level.time > NPCInfo->investigateDebounceTime) - { - NPCInfo->tempBehavior = BS_DEFAULT; - } + if(level.time > NPCInfo->investigateDebounceTime) + { + NPCInfo->tempBehavior = BS_DEFAULT; + } - NPC_CheckSoundEvents(); - */ + NPC_CheckSoundEvents(); + */ } -qboolean NPC_CheckInvestigate( int alertEventNum ) -{ - gentity_t *owner = level.alertEvents[alertEventNum].owner; - int invAdd = level.alertEvents[alertEventNum].level; - vec3_t soundPos; - float soundRad = level.alertEvents[alertEventNum].radius; - float earshot = NPCS.NPCInfo->stats.earshot; +qboolean NPC_CheckInvestigate(int alertEventNum) { + gentity_t *owner = level.alertEvents[alertEventNum].owner; + int invAdd = level.alertEvents[alertEventNum].level; + vec3_t soundPos; + float soundRad = level.alertEvents[alertEventNum].radius; + float earshot = NPCS.NPCInfo->stats.earshot; - VectorCopy( level.alertEvents[alertEventNum].position, soundPos ); + VectorCopy(level.alertEvents[alertEventNum].position, soundPos); - //NOTE: Trying to preserve previous investigation behavior - if ( !owner ) - { + // NOTE: Trying to preserve previous investigation behavior + if (!owner) { return qfalse; } - if ( owner->s.eType != ET_PLAYER && owner->s.eType != ET_NPC && owner == NPCS.NPCInfo->goalEntity ) - { + if (owner->s.eType != ET_PLAYER && owner->s.eType != ET_NPC && owner == NPCS.NPCInfo->goalEntity) { return qfalse; } - if ( owner->s.eFlags & EF_NODRAW ) - { + if (owner->s.eFlags & EF_NODRAW) { return qfalse; } - if ( owner->flags & FL_NOTARGET ) - { + if (owner->flags & FL_NOTARGET) { return qfalse; } - if ( soundRad < earshot ) - { + if (soundRad < earshot) { return qfalse; } - //if(!trap->InPVSIgnorePortals(ent->r.currentOrigin, NPC->r.currentOrigin))//should we be able to hear through areaportals? - if ( !trap->InPVS( soundPos, NPCS.NPC->r.currentOrigin ) ) - {//can hear through doors? + // if(!trap->InPVSIgnorePortals(ent->r.currentOrigin, NPC->r.currentOrigin))//should we be able to hear through areaportals? + if (!trap->InPVS(soundPos, NPCS.NPC->r.currentOrigin)) { // can hear through doors? return qfalse; } - if ( owner->client && owner->client->playerTeam && NPCS.NPC->client->playerTeam && owner->client->playerTeam != NPCS.NPC->client->playerTeam ) - { - if( (float)NPCS.NPCInfo->investigateCount >= (NPCS.NPCInfo->stats.vigilance*200) && owner ) - {//If investigateCount == 10, just take it as enemy and go - if ( ValidEnemy( owner ) ) - {//FIXME: run angerscript - G_SetEnemy( NPCS.NPC, owner ); + if (owner->client && owner->client->playerTeam && NPCS.NPC->client->playerTeam && owner->client->playerTeam != NPCS.NPC->client->playerTeam) { + if ((float)NPCS.NPCInfo->investigateCount >= (NPCS.NPCInfo->stats.vigilance * 200) && owner) { // If investigateCount == 10, just take it as enemy and + // go + if (ValidEnemy(owner)) { // FIXME: run angerscript + G_SetEnemy(NPCS.NPC, owner); NPCS.NPCInfo->goalEntity = NPCS.NPC->enemy; NPCS.NPCInfo->goalRadius = 12; NPCS.NPCInfo->behaviorState = BS_HUNT_AND_KILL; return qtrue; } - } - else - { + } else { NPCS.NPCInfo->investigateCount += invAdd; } - //run awakescript + // run awakescript G_ActivateBehavior(NPCS.NPC, BSET_AWAKE); /* @@ -493,16 +449,13 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) } */ - //NPCInfo->hlookCount = NPCInfo->vlookCount = 0; + // NPCInfo->hlookCount = NPCInfo->vlookCount = 0; NPCS.NPCInfo->eventOwner = owner; - VectorCopy( soundPos, NPCS.NPCInfo->investigateGoal ); - if ( NPCS.NPCInfo->investigateCount > 20 ) - { + VectorCopy(soundPos, NPCS.NPCInfo->investigateGoal); + if (NPCS.NPCInfo->investigateCount > 20) { NPCS.NPCInfo->investigateDebounceTime = level.time + 10000; - } - else - { - NPCS.NPCInfo->investigateDebounceTime = level.time + (NPCS.NPCInfo->investigateCount*500); + } else { + NPCS.NPCInfo->investigateDebounceTime = level.time + (NPCS.NPCInfo->investigateCount * 500); } NPCS.NPCInfo->tempBehavior = BS_INVESTIGATE; return qtrue; @@ -511,17 +464,14 @@ qboolean NPC_CheckInvestigate( int alertEventNum ) return qfalse; } - /* void NPC_BSSleep( void ) */ -void NPC_BSSleep( void ) -{ - int alertEvent = NPC_CheckAlertEvents( qtrue, qfalse, -1, qfalse, AEL_MINOR ); +void NPC_BSSleep(void) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qfalse, -1, qfalse, AEL_MINOR); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { G_ActivateBehavior(NPCS.NPC, BSET_AWAKE); return; } @@ -538,151 +488,118 @@ void NPC_BSSleep( void ) */ } -extern qboolean NPC_MoveDirClear( int forwardmove, int rightmove, qboolean reset ); -void NPC_BSFollowLeader (void) -{ - vec3_t vec; - float leaderDist; - visibility_t leaderVis; - int curAnim; - - if ( !NPCS.NPC->client->leader ) - {//ok, stand guard until we find an enemy - if( NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL ) - { +extern qboolean NPC_MoveDirClear(int forwardmove, int rightmove, qboolean reset); +void NPC_BSFollowLeader(void) { + vec3_t vec; + float leaderDist; + visibility_t leaderVis; + int curAnim; + + if (!NPCS.NPC->client->leader) { // ok, stand guard until we find an enemy + if (NPCS.NPCInfo->tempBehavior == BS_HUNT_AND_KILL) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else - { + } else { NPCS.NPCInfo->tempBehavior = BS_STAND_GUARD; NPC_BSStandGuard(); } return; } - if ( !NPCS.NPC->enemy ) - {//no enemy, find one - NPC_CheckEnemy( NPCS.NPCInfo->confusionTimeenemy ) - {//just found one - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); - } - else - { - if ( !(NPCS.NPCInfo->scriptFlags&SCF_IGNORE_ALERTS) ) - { - int eventID = NPC_CheckAlertEvents( qtrue, qtrue, -1, qfalse, AEL_MINOR ); - if ( level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCS.NPCInfo->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) - { + if (!NPCS.NPC->enemy) { // no enemy, find one + NPC_CheckEnemy(NPCS.NPCInfo->confusionTime < level.time, qfalse, qtrue); // don't find new enemy if this is tempbehav + if (NPCS.NPC->enemy) { // just found one + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); + } else { + if (!(NPCS.NPCInfo->scriptFlags & SCF_IGNORE_ALERTS)) { + int eventID = NPC_CheckAlertEvents(qtrue, qtrue, -1, qfalse, AEL_MINOR); + if (level.alertEvents[eventID].level >= AEL_SUSPICIOUS && (NPCS.NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES)) { NPCS.NPCInfo->lastAlertID = level.alertEvents[eventID].ID; - if ( !level.alertEvents[eventID].owner || - !level.alertEvents[eventID].owner->client || - level.alertEvents[eventID].owner->health <= 0 || - level.alertEvents[eventID].owner->client->playerTeam != NPCS.NPC->client->enemyTeam ) - {//not an enemy - } - else - { - //FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for him? Or just let combat AI handle this... (act as if you lost him) - G_SetEnemy( NPCS.NPC, level.alertEvents[eventID].owner ); - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (!level.alertEvents[eventID].owner || !level.alertEvents[eventID].owner->client || level.alertEvents[eventID].owner->health <= 0 || + level.alertEvents[eventID].owner->client->playerTeam != NPCS.NPC->client->enemyTeam) { // not an enemy + } else { + // FIXME: what if can't actually see enemy, don't know where he is... should we make them just become very alert and start looking for + // him? Or just let combat AI handle this... (act as if you lost him) + G_SetEnemy(NPCS.NPC, level.alertEvents[eventID].owner); + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCS.NPCInfo->enemyLastSeenTime = level.time; - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 1000 ) ); + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 1000)); } } - } } - if ( !NPCS.NPC->enemy ) - { - if ( NPCS.NPC->client->leader - && NPCS.NPC->client->leader->enemy - && NPCS.NPC->client->leader->enemy != NPCS.NPC - && ( (NPCS.NPC->client->leader->enemy->client&&NPCS.NPC->client->leader->enemy->client->playerTeam==NPCS.NPC->client->enemyTeam) - ||(/*NPC->client->leader->enemy->r.svFlags&SVF_NONNPC_ENEMY*/0&&NPCS.NPC->client->leader->enemy->alliedTeam==NPCS.NPC->client->enemyTeam) ) - && NPCS.NPC->client->leader->enemy->health > 0 ) - { //rwwFIXMEFIXME: use SVF_NONNPC_ENEMY? - G_SetEnemy( NPCS.NPC, NPCS.NPC->client->leader->enemy ); - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 3000, 10000 ); + if (!NPCS.NPC->enemy) { + if (NPCS.NPC->client->leader && NPCS.NPC->client->leader->enemy && NPCS.NPC->client->leader->enemy != NPCS.NPC && + ((NPCS.NPC->client->leader->enemy->client && NPCS.NPC->client->leader->enemy->client->playerTeam == NPCS.NPC->client->enemyTeam) || + (/*NPC->client->leader->enemy->r.svFlags&SVF_NONNPC_ENEMY*/ 0 && + NPCS.NPC->client->leader->enemy->alliedTeam == NPCS.NPC->client->enemyTeam)) && + NPCS.NPC->client->leader->enemy->health > 0) { // rwwFIXMEFIXME: use SVF_NONNPC_ENEMY? + G_SetEnemy(NPCS.NPC, NPCS.NPC->client->leader->enemy); + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(3000, 10000); NPCS.NPCInfo->enemyLastSeenTime = level.time; } } - } - else - { - if ( NPCS.NPC->enemy->health <= 0 || (NPCS.NPC->enemy->flags&FL_NOTARGET) ) - { - G_ClearEnemy( NPCS.NPC ); - if ( NPCS.NPCInfo->enemyCheckDebounceTime > level.time + 1000 ) - { - NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand( 1000, 2000 ); + } else { + if (NPCS.NPC->enemy->health <= 0 || (NPCS.NPC->enemy->flags & FL_NOTARGET)) { + G_ClearEnemy(NPCS.NPC); + if (NPCS.NPCInfo->enemyCheckDebounceTime > level.time + 1000) { + NPCS.NPCInfo->enemyCheckDebounceTime = level.time + Q_irand(1000, 2000); } - } - else if ( NPCS.NPC->client->ps.weapon && NPCS.NPCInfo->enemyCheckDebounceTime < level.time ) - { - NPC_CheckEnemy( (NPCS.NPCInfo->confusionTimetempBehavior!=BS_FOLLOW_LEADER), qfalse, qtrue );//don't find new enemy if this is tempbehav + } else if (NPCS.NPC->client->ps.weapon && NPCS.NPCInfo->enemyCheckDebounceTime < level.time) { + NPC_CheckEnemy((NPCS.NPCInfo->confusionTime < level.time || NPCS.NPCInfo->tempBehavior != BS_FOLLOW_LEADER), qfalse, + qtrue); // don't find new enemy if this is tempbehav } } - if ( NPCS.NPC->enemy && NPCS.NPC->client->ps.weapon ) - {//If have an enemy, face him and fire - if ( NPCS.NPC->client->ps.weapon == WP_SABER )//|| NPCInfo->confusionTime>level.time ) - {//lightsaber user or charmed enemy - if ( NPCS.NPCInfo->tempBehavior != BS_FOLLOW_LEADER ) - {//not already in a temp bState - //go after the guy + if (NPCS.NPC->enemy && NPCS.NPC->client->ps.weapon) { // If have an enemy, face him and fire + if (NPCS.NPC->client->ps.weapon == WP_SABER) //|| NPCInfo->confusionTime>level.time ) + { // lightsaber user or charmed enemy + if (NPCS.NPCInfo->tempBehavior != BS_FOLLOW_LEADER) { // not already in a temp bState + // go after the guy NPCS.NPCInfo->tempBehavior = BS_HUNT_AND_KILL; NPC_UpdateAngles(qtrue, qtrue); return; } } - NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_FOV|CHECK_SHOOT );//CHECK_360|CHECK_PVS| - if ( NPCS.enemyVisibility > VIS_PVS ) - {//face - vec3_t enemy_org, muzzle, delta, angleToEnemy; + NPCS.enemyVisibility = NPC_CheckVisibility(NPCS.NPC->enemy, CHECK_FOV | CHECK_SHOOT); // CHECK_360|CHECK_PVS| + if (NPCS.enemyVisibility > VIS_PVS) { // face + vec3_t enemy_org, muzzle, delta, angleToEnemy; - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); - VectorSubtract( enemy_org, muzzle, delta); - vectoangles( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); NPCS.NPCInfo->desiredYaw = angleToEnemy[YAW]; NPCS.NPCInfo->desiredPitch = angleToEnemy[PITCH]; - NPC_UpdateFiringAngles( qtrue, qtrue ); - - if ( NPCS.enemyVisibility >= VIS_SHOOT ) - {//shoot - NPC_AimAdjust( 2 ); - if ( NPC_GetHFOVPercentage( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->stats.hfov ) > 0.6f - && NPC_GetHFOVPercentage( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, NPCS.NPCInfo->stats.vfov ) > 0.5f ) - {//actually withing our front cone - WeaponThink( qtrue ); + NPC_UpdateFiringAngles(qtrue, qtrue); + + if (NPCS.enemyVisibility >= VIS_SHOOT) { // shoot + NPC_AimAdjust(2); + if (NPC_GetHFOVPercentage(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, + NPCS.NPCInfo->stats.hfov) > 0.6f && + NPC_GetHFOVPercentage(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.viewangles, + NPCS.NPCInfo->stats.vfov) > 0.5f) { // actually withing our front cone + WeaponThink(qtrue); } - } - else - { - NPC_AimAdjust( 1 ); + } else { + NPC_AimAdjust(1); } - //NPC_CheckCanAttack(1.0, qfalse); - } - else - { - NPC_AimAdjust( -1 ); + // NPC_CheckCanAttack(1.0, qfalse); + } else { + NPC_AimAdjust(-1); } - } - else - {//FIXME: combine with vector calc below - vec3_t head, leaderHead, delta, angleToLeader; - - CalcEntitySpot( NPCS.NPC->client->leader, SPOT_HEAD, leaderHead ); - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, head ); - VectorSubtract (leaderHead, head, delta); - vectoangles ( delta, angleToLeader ); + } else { // FIXME: combine with vector calc below + vec3_t head, leaderHead, delta, angleToLeader; + + CalcEntitySpot(NPCS.NPC->client->leader, SPOT_HEAD, leaderHead); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, head); + VectorSubtract(leaderHead, head, delta); + vectoangles(delta, angleToLeader); VectorNormalize(delta); NPCS.NPC->NPC->desiredYaw = angleToLeader[YAW]; NPCS.NPC->NPC->desiredPitch = angleToLeader[PITCH]; @@ -690,127 +607,109 @@ void NPC_BSFollowLeader (void) NPC_UpdateAngles(qtrue, qtrue); } - //leader visible? - leaderVis = NPC_CheckVisibility( NPCS.NPC->client->leader, CHECK_PVS|CHECK_360|CHECK_SHOOT );// ent->e_UseFunc = useF_NULL; - + // leader visible? + leaderVis = NPC_CheckVisibility(NPCS.NPC->client->leader, CHECK_PVS | CHECK_360 | CHECK_SHOOT); // ent->e_UseFunc = useF_NULL; - //Follow leader, stay within visibility and a certain distance, maintain a distance from. + // Follow leader, stay within visibility and a certain distance, maintain a distance from. curAnim = NPCS.NPC->client->ps.legsAnim; - if ( curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && curAnim != BOTH_MELEE2 ) - {//Don't move toward leader if we're in a full-body attack anim - //FIXME, use IdealDistance to determine if we need to close distance - float followDist = 96.0f;//FIXME: If there are enmies, make this larger? - float backupdist, walkdist, minrundist; - float leaderHDist; - - if ( NPCS.NPCInfo->followDist ) - { + if (curAnim != BOTH_ATTACK1 && curAnim != BOTH_ATTACK2 && curAnim != BOTH_ATTACK3 && curAnim != BOTH_MELEE1 && + curAnim != BOTH_MELEE2) { // Don't move toward leader if we're in a full-body attack anim + // FIXME, use IdealDistance to determine if we need to close distance + float followDist = 96.0f; // FIXME: If there are enmies, make this larger? + float backupdist, walkdist, minrundist; + float leaderHDist; + + if (NPCS.NPCInfo->followDist) { followDist = NPCS.NPCInfo->followDist; } - backupdist = followDist/2.0f; - walkdist = followDist*0.83; - minrundist = followDist*1.33; + backupdist = followDist / 2.0f; + walkdist = followDist * 0.83; + minrundist = followDist * 1.33; VectorSubtract(NPCS.NPC->client->leader->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); - leaderDist = VectorLength( vec );//FIXME: make this just nav distance? - //never get within their radius horizontally + leaderDist = VectorLength(vec); // FIXME: make this just nav distance? + // never get within their radius horizontally vec[2] = 0; - leaderHDist = VectorLength( vec ); - if( leaderHDist > backupdist && (leaderVis != VIS_SHOOT || leaderDist > walkdist) ) - {//We should close in? + leaderHDist = VectorLength(vec); + if (leaderHDist > backupdist && (leaderVis != VIS_SHOOT || leaderDist > walkdist)) { // We should close in? NPCS.NPCInfo->goalEntity = NPCS.NPC->client->leader; NPC_SlideMoveToGoal(); - if ( leaderVis == VIS_SHOOT && leaderDist < minrundist ) - { + if (leaderVis == VIS_SHOOT && leaderDist < minrundist) { NPCS.ucmd.buttons |= BUTTON_WALKING; } - } - else if ( leaderDist < backupdist ) - {//We should back off? + } else if (leaderDist < backupdist) { // We should back off? NPCS.NPCInfo->goalEntity = NPCS.NPC->client->leader; NPC_SlideMoveToGoal(); - //reversing direction + // reversing direction NPCS.ucmd.forwardmove = -NPCS.ucmd.forwardmove; - NPCS.ucmd.rightmove = -NPCS.ucmd.rightmove; - VectorScale( NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir ); - }//otherwise, stay where we are - //check for do not enter and stop if there's one there... - if ( NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove || VectorCompare( vec3_origin, NPCS.NPC->client->ps.moveDir ) ) - { - NPC_MoveDirClear( NPCS.ucmd.forwardmove, NPCS.ucmd.rightmove, qtrue ); + NPCS.ucmd.rightmove = -NPCS.ucmd.rightmove; + VectorScale(NPCS.NPC->client->ps.moveDir, -1, NPCS.NPC->client->ps.moveDir); + } // otherwise, stay where we are + // check for do not enter and stop if there's one there... + if (NPCS.ucmd.forwardmove || NPCS.ucmd.rightmove || VectorCompare(vec3_origin, NPCS.NPC->client->ps.moveDir)) { + NPC_MoveDirClear(NPCS.ucmd.forwardmove, NPCS.ucmd.rightmove, qtrue); } } } -#define APEX_HEIGHT 200.0f -#define PARA_WIDTH (sqrt(APEX_HEIGHT)+sqrt(APEX_HEIGHT)) -#define JUMP_SPEED 200.0f -void NPC_BSJump (void) -{ - vec3_t dir, angles, p1, p2, apex; - float time, height, forward, z, xy, dist, yawError, apexHeight; - - if( !NPCS.NPCInfo->goalEntity ) - {//Should have task completed the navgoal +#define APEX_HEIGHT 200.0f +#define PARA_WIDTH (sqrt(APEX_HEIGHT) + sqrt(APEX_HEIGHT)) +#define JUMP_SPEED 200.0f +void NPC_BSJump(void) { + vec3_t dir, angles, p1, p2, apex; + float time, height, forward, z, xy, dist, yawError, apexHeight; + + if (!NPCS.NPCInfo->goalEntity) { // Should have task completed the navgoal return; } - if ( NPCS.NPCInfo->jumpState != JS_JUMPING && NPCS.NPCInfo->jumpState != JS_LANDING ) - { - //Face navgoal + if (NPCS.NPCInfo->jumpState != JS_JUMPING && NPCS.NPCInfo->jumpState != JS_LANDING) { + // Face navgoal VectorSubtract(NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir); vectoangles(dir, angles); NPCS.NPCInfo->desiredPitch = NPCS.NPCInfo->lockedDesiredPitch = AngleNormalize360(angles[PITCH]); NPCS.NPCInfo->desiredYaw = NPCS.NPCInfo->lockedDesiredYaw = AngleNormalize360(angles[YAW]); } - NPC_UpdateAngles ( qtrue, qtrue ); - yawError = AngleDelta ( NPCS.NPC->client->ps.viewangles[YAW], NPCS.NPCInfo->desiredYaw ); - //We don't really care about pitch here + NPC_UpdateAngles(qtrue, qtrue); + yawError = AngleDelta(NPCS.NPC->client->ps.viewangles[YAW], NPCS.NPCInfo->desiredYaw); + // We don't really care about pitch here - switch ( NPCS.NPCInfo->jumpState ) - { + switch (NPCS.NPCInfo->jumpState) { case JS_FACING: - if ( yawError < MIN_ANGLE_ERROR ) - {//Facing it, Start crouching - NPC_SetAnim(NPCS.NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (yawError < MIN_ANGLE_ERROR) { // Facing it, Start crouching + NPC_SetAnim(NPCS.NPC, SETANIM_LEGS, BOTH_CROUCH1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPCInfo->jumpState = JS_CROUCHING; } break; case JS_CROUCHING: - if ( NPCS.NPC->client->ps.legsTimer > 0 ) - {//Still playing crouching anim + if (NPCS.NPC->client->ps.legsTimer > 0) { // Still playing crouching anim return; } - //Create a parabola + // Create a parabola - if ( NPCS.NPC->r.currentOrigin[2] > NPCS.NPCInfo->goalEntity->r.currentOrigin[2] ) - { - VectorCopy( NPCS.NPC->r.currentOrigin, p1 ); - VectorCopy( NPCS.NPCInfo->goalEntity->r.currentOrigin, p2 ); - } - else if ( NPCS.NPC->r.currentOrigin[2] < NPCS.NPCInfo->goalEntity->r.currentOrigin[2] ) - { - VectorCopy( NPCS.NPCInfo->goalEntity->r.currentOrigin, p1 ); - VectorCopy( NPCS.NPC->r.currentOrigin, p2 ); - } - else - { - VectorCopy( NPCS.NPC->r.currentOrigin, p1 ); - VectorCopy( NPCS.NPCInfo->goalEntity->r.currentOrigin, p2 ); + if (NPCS.NPC->r.currentOrigin[2] > NPCS.NPCInfo->goalEntity->r.currentOrigin[2]) { + VectorCopy(NPCS.NPC->r.currentOrigin, p1); + VectorCopy(NPCS.NPCInfo->goalEntity->r.currentOrigin, p2); + } else if (NPCS.NPC->r.currentOrigin[2] < NPCS.NPCInfo->goalEntity->r.currentOrigin[2]) { + VectorCopy(NPCS.NPCInfo->goalEntity->r.currentOrigin, p1); + VectorCopy(NPCS.NPC->r.currentOrigin, p2); + } else { + VectorCopy(NPCS.NPC->r.currentOrigin, p1); + VectorCopy(NPCS.NPCInfo->goalEntity->r.currentOrigin, p2); } - //z = xy*xy - VectorSubtract( p2, p1, dir ); + // z = xy*xy + VectorSubtract(p2, p1, dir); dir[2] = 0; - //Get xy and z diffs - xy = VectorNormalize( dir ); + // Get xy and z diffs + xy = VectorNormalize(dir); z = p1[2] - p2[2]; - apexHeight = APEX_HEIGHT/2; + apexHeight = APEX_HEIGHT / 2; /* //Determine most desirable apex height apexHeight = (APEX_HEIGHT * PARA_WIDTH/xy) + (APEX_HEIGHT * z/128); @@ -824,101 +723,89 @@ void NPC_BSJump (void) } */ - //FIXME: length of xy will change curve of parabola, need to account for this - //somewhere... PARA_WIDTH + // FIXME: length of xy will change curve of parabola, need to account for this + // somewhere... PARA_WIDTH z = (sqrt(apexHeight + z) - sqrt(apexHeight)); assert(z >= 0); -// Com_Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); + // Com_Printf("apex is %4.2f percent from p1: ", (xy-z)*0.5/xy*100.0f); // Don't need to set apex xy if NPC is jumping directly up. - if ( xy > 0.0f ) - { + if (xy > 0.0f) { xy -= z; xy *= 0.5; assert(xy > 0); } - VectorMA (p1, xy, dir, apex); + VectorMA(p1, xy, dir, apex); apex[2] += apexHeight; VectorCopy(apex, NPCS.NPC->pos1); - //Now we have the apex, aim for it + // Now we have the apex, aim for it height = apex[2] - NPCS.NPC->r.currentOrigin[2]; - time = sqrt( height / ( .5 * NPCS.NPC->client->ps.gravity ) ); - if ( !time ) - { -// Com_Printf("ERROR no time in jump\n"); + time = sqrt(height / (.5 * NPCS.NPC->client->ps.gravity)); + if (!time) { + // Com_Printf("ERROR no time in jump\n"); return; } // set s.origin2 to the push velocity - VectorSubtract ( apex, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.velocity ); + VectorSubtract(apex, NPCS.NPC->r.currentOrigin, NPCS.NPC->client->ps.velocity); NPCS.NPC->client->ps.velocity[2] = 0; - dist = VectorNormalize( NPCS.NPC->client->ps.velocity ); + dist = VectorNormalize(NPCS.NPC->client->ps.velocity); forward = dist / time; - VectorScale( NPCS.NPC->client->ps.velocity, forward, NPCS.NPC->client->ps.velocity ); + VectorScale(NPCS.NPC->client->ps.velocity, forward, NPCS.NPC->client->ps.velocity); NPCS.NPC->client->ps.velocity[2] = time * NPCS.NPC->client->ps.gravity; -// Com_Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); + // Com_Printf( "%s jumping %s, gravity at %4.0f percent\n", NPC->targetname, vtos(NPC->client->ps.velocity), NPC->client->ps.gravity/8.0f ); NPCS.NPC->flags |= FL_NO_KNOCKBACK; NPCS.NPCInfo->jumpState = JS_JUMPING; - //FIXME: jumpsound? + // FIXME: jumpsound? break; case JS_JUMPING: - if ( showBBoxes ) - { + if (showBBoxes) { VectorAdd(NPCS.NPC->r.mins, NPCS.NPC->pos1, p1); VectorAdd(NPCS.NPC->r.maxs, NPCS.NPC->pos1, p2); - G_Cube( p1, p2, NPCDEBUG_BLUE, 0.5 ); + G_Cube(p1, p2, NPCDEBUG_BLUE, 0.5); } - if ( NPCS.NPC->s.groundEntityNum != ENTITYNUM_NONE) - {//Landed, start landing anim - //FIXME: if the + if (NPCS.NPC->s.groundEntityNum != ENTITYNUM_NONE) { // Landed, start landing anim + // FIXME: if the VectorClear(NPCS.NPC->client->ps.velocity); - NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); NPCS.NPCInfo->jumpState = JS_LANDING; - //FIXME: landsound? - } - else if ( NPCS.NPC->client->ps.legsTimer > 0 ) - {//Still playing jumping anim - //FIXME: apply jump velocity here, a couple frames after start, not right away + // FIXME: landsound? + } else if (NPCS.NPC->client->ps.legsTimer > 0) { // Still playing jumping anim + // FIXME: apply jump velocity here, a couple frames after start, not right away return; - } - else - {//still in air, but done with jump anim, play inair anim + } else { // still in air, but done with jump anim, play inair anim NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_OVERRIDE); } break; case JS_LANDING: - if ( NPCS.NPC->client->ps.legsTimer > 0 ) - {//Still playing landing anim + if (NPCS.NPC->client->ps.legsTimer > 0) { // Still playing landing anim return; - } - else - { + } else { NPCS.NPCInfo->jumpState = JS_WAITING; - - //task complete no matter what... + // task complete no matter what... NPC_ClearGoal(); NPCS.NPCInfo->goalTime = level.time; NPCS.NPCInfo->aiFlags &= ~NPCAI_MOVING; NPCS.ucmd.forwardmove = 0; NPCS.NPC->flags &= ~FL_NO_KNOCKBACK; - //Return that the goal was reached - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ); + // Return that the goal was reached + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV); - //Or should we keep jumping until reached goal? + // Or should we keep jumping until reached goal? /* NPCInfo->goalEntity = UpdateGoal(); @@ -928,7 +815,6 @@ void NPC_BSJump (void) Q3_TaskIDComplete( NPC, TID_MOVE_NAV ); } */ - } break; case JS_WAITING: @@ -938,65 +824,56 @@ void NPC_BSJump (void) } } -void NPC_BSRemove (void) -{ - NPC_UpdateAngles ( qtrue, qtrue ); - //OJKFIXME: clientnum 0 - if( !trap->InPVS( NPCS.NPC->r.currentOrigin, g_entities[0].r.currentOrigin ) )//FIXME: use cg.vieworg? - { //rwwFIXMEFIXME: Care about all clients instead of just 0? - G_UseTargets2( NPCS.NPC, NPCS.NPC, NPCS.NPC->target3 ); +void NPC_BSRemove(void) { + NPC_UpdateAngles(qtrue, qtrue); + // OJKFIXME: clientnum 0 + if (!trap->InPVS(NPCS.NPC->r.currentOrigin, g_entities[0].r.currentOrigin)) // FIXME: use cg.vieworg? + { // rwwFIXMEFIXME: Care about all clients instead of just 0? + G_UseTargets2(NPCS.NPC, NPCS.NPC, NPCS.NPC->target3); NPCS.NPC->s.eFlags |= EF_NODRAW; NPCS.NPC->s.eType = ET_INVISIBLE; NPCS.NPC->r.contents = 0; NPCS.NPC->health = 0; NPCS.NPC->targetname = NULL; - //Disappear in half a second + // Disappear in half a second NPCS.NPC->think = G_FreeEntity; NPCS.NPC->nextthink = level.time + FRAMETIME; - }//FIXME: else allow for out of FOV??? + } // FIXME: else allow for out of FOV??? } -void NPC_BSSearch (void) -{ +void NPC_BSSearch(void) { NPC_CheckEnemy(qtrue, qfalse, qtrue); - //Look for enemies, if find one: - if ( NPCS.NPC->enemy ) - { - if( NPCS.NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + // Look for enemies, if find one: + if (NPCS.NPC->enemy) { + if (NPCS.NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to run and shoot + } else { // if bState, change to run and shoot NPCS.NPCInfo->behaviorState = BS_HUNT_AND_KILL; NPC_BSRunAndShoot(); } return; } - //FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must - //want us to do something else? If tempBehavior, just default, else set - //to run and shoot...? + // FIXME: what if our goalEntity is not NULL and NOT our tempGoal - they must + // want us to do something else? If tempBehavior, just default, else set + // to run and shoot...? - //FIXME: Reimplement + // FIXME: Reimplement - if ( !NPCS.NPCInfo->investigateDebounceTime ) - {//On our way to a tempGoal - float minGoalReachedDistSquared = 32*32; - vec3_t vec; + if (!NPCS.NPCInfo->investigateDebounceTime) { // On our way to a tempGoal + float minGoalReachedDistSquared = 32 * 32; + vec3_t vec; - //Keep moving toward our tempGoal + // Keep moving toward our tempGoal NPCS.NPCInfo->goalEntity = NPCS.NPCInfo->tempGoal; - VectorSubtract ( NPCS.NPCInfo->tempGoal->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); - if ( vec[2] < 24 ) - { + VectorSubtract(NPCS.NPCInfo->tempGoal->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); + if (vec[2] < 24) { vec[2] = 0; } - if ( NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { + if (NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { /* //FIXME: can't get the radius... float wpRadSq = waypoints[NPCInfo->tempGoal->waypoint].radius * waypoints[NPCInfo->tempGoal->waypoint].radius; @@ -1006,110 +883,87 @@ void NPC_BSSearch (void) } */ - minGoalReachedDistSquared = 32*32;//12*12; + minGoalReachedDistSquared = 32 * 32; // 12*12; } - if ( VectorLengthSquared( vec ) < minGoalReachedDistSquared ) - { - //Close enough, just got there - NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt( NPCS.NPC, WAYPOINT_NONE ); + if (VectorLengthSquared(vec) < minGoalReachedDistSquared) { + // Close enough, just got there + NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt(NPCS.NPC, WAYPOINT_NONE); - if ( ( NPCS.NPCInfo->homeWp == WAYPOINT_NONE ) || ( NPCS.NPC->waypoint == WAYPOINT_NONE ) ) - { - //Heading for or at an invalid waypoint, get out of this bState - if( NPCS.NPCInfo->tempBehavior == BS_SEARCH ) - {//if tempbehavior, set tempbehavior to default + if ((NPCS.NPCInfo->homeWp == WAYPOINT_NONE) || (NPCS.NPC->waypoint == WAYPOINT_NONE)) { + // Heading for or at an invalid waypoint, get out of this bState + if (NPCS.NPCInfo->tempBehavior == BS_SEARCH) { // if tempbehavior, set tempbehavior to default NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//if bState, change to stand guard + } else { // if bState, change to stand guard NPCS.NPCInfo->behaviorState = BS_STAND_GUARD; NPC_BSRunAndShoot(); } return; } - if ( NPCS.NPC->waypoint == NPCS.NPCInfo->homeWp ) - { - //Just Reached our homeWp, if this is the first time, run your lostenemyscript - if ( NPCS.NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP ) - { + if (NPCS.NPC->waypoint == NPCS.NPCInfo->homeWp) { + // Just Reached our homeWp, if this is the first time, run your lostenemyscript + if (NPCS.NPCInfo->aiFlags & NPCAI_ENROUTE_TO_HOMEWP) { NPCS.NPCInfo->aiFlags &= ~NPCAI_ENROUTE_TO_HOMEWP; - G_ActivateBehavior( NPCS.NPC, BSET_LOSTENEMY ); + G_ActivateBehavior(NPCS.NPC, BSET_LOSTENEMY); } - } - //Com_Printf("Got there.\n"); - //Com_Printf("Looking..."); - if( !Q_irand(0, 1) ) - { + // Com_Printf("Got there.\n"); + // Com_Printf("Looking..."); + if (!Q_irand(0, 1)) { NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); - } - else - { + } else { NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); } NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); + } else { + NPC_MoveToGoal(qtrue); } - else - { - NPC_MoveToGoal( qtrue ); - } - } - else - { - //We're there - if ( NPCS.NPCInfo->investigateDebounceTime > level.time ) - { - //Still waiting around for a bit - //Turn angles every now and then to look around - if ( NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { - if ( !Q_irand( 0, 30 ) ) - { - int numEdges = trap->Nav_GetNodeNumEdges( NPCS.NPCInfo->tempGoal->waypoint ); + } else { + // We're there + if (NPCS.NPCInfo->investigateDebounceTime > level.time) { + // Still waiting around for a bit + // Turn angles every now and then to look around + if (NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { + if (!Q_irand(0, 30)) { + int numEdges = trap->Nav_GetNodeNumEdges(NPCS.NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - vec3_t branchPos, lookDir; + vec3_t branchPos, lookDir; - int nextWp = trap->Nav_GetNodeEdge( NPCS.NPCInfo->tempGoal->waypoint, branchNum ); - trap->Nav_GetNodePosition( nextWp, branchPos ); + int nextWp = trap->Nav_GetNodeEdge(NPCS.NPCInfo->tempGoal->waypoint, branchNum); + trap->Nav_GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPCS.NPCInfo->tempGoal->r.currentOrigin, lookDir ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + flrand( -45, 45 ) ); + VectorSubtract(branchPos, NPCS.NPCInfo->tempGoal->r.currentOrigin, lookDir); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(vectoyaw(lookDir) + flrand(-45, 45)); } - //pick an angle +-45 degrees off of the dir of a random branch - //from NPCInfo->tempGoal->waypoint - //int branch = Q_irand( 0, (waypoints[NPCInfo->tempGoal->waypoint].numNeighbors - 1) ); - //int nextWp = waypoints[NPCInfo->tempGoal->waypoint].nextWaypoint[branch][NPC->client->moveType]; - //vec3_t lookDir; + // pick an angle +-45 degrees off of the dir of a random branch + // from NPCInfo->tempGoal->waypoint + // int branch = Q_irand( 0, (waypoints[NPCInfo->tempGoal->waypoint].numNeighbors - 1) ); + // int nextWp = waypoints[NPCInfo->tempGoal->waypoint].nextWaypoint[branch][NPC->client->moveType]; + // vec3_t lookDir; - //VectorSubtract( waypoints[nextWp].origin, NPCInfo->tempGoal->r.currentOrigin, lookDir ); - //Look in that direction +- 45 degrees - //NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); + // VectorSubtract( waypoints[nextWp].origin, NPCInfo->tempGoal->r.currentOrigin, lookDir ); + // Look in that direction +- 45 degrees + // NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + Q_flrand( -45, 45 ) ); } } - //Com_Printf("."); - } - else - {//Just finished waiting - NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt( NPCS.NPC, WAYPOINT_NONE ); + // Com_Printf("."); + } else { // Just finished waiting + NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt(NPCS.NPC, WAYPOINT_NONE); - if ( NPCS.NPC->waypoint == NPCS.NPCInfo->homeWp ) - { - int numEdges = trap->Nav_GetNodeNumEdges( NPCS.NPCInfo->tempGoal->waypoint ); + if (NPCS.NPC->waypoint == NPCS.NPCInfo->homeWp) { + int numEdges = trap->Nav_GetNodeNumEdges(NPCS.NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - int nextWp = trap->Nav_GetNodeEdge( NPCS.NPCInfo->homeWp, branchNum ); - trap->Nav_GetNodePosition( nextWp, NPCS.NPCInfo->tempGoal->r.currentOrigin ); + int nextWp = trap->Nav_GetNodeEdge(NPCS.NPCInfo->homeWp, branchNum); + trap->Nav_GetNodePosition(nextWp, NPCS.NPCInfo->tempGoal->r.currentOrigin); NPCS.NPCInfo->tempGoal->waypoint = nextWp; } @@ -1122,10 +976,8 @@ void NPC_BSSearch (void) NPCInfo->tempGoal->waypoint = nextWp; //Com_Printf("\nHeading for wp %d...\n", waypoints[NPCInfo->homeWp].nextWaypoint[branch][NPC->client->moveType]); */ - } - else - {//At a branch, so return home - trap->Nav_GetNodePosition( NPCS.NPCInfo->homeWp, NPCS.NPCInfo->tempGoal->r.currentOrigin ); + } else { // At a branch, so return home + trap->Nav_GetNodePosition(NPCS.NPCInfo->homeWp, NPCS.NPCInfo->tempGoal->r.currentOrigin); NPCS.NPCInfo->tempGoal->waypoint = NPCS.NPCInfo->homeWp; /* VectorCopy( waypoints[NPCInfo->homeWp].origin, NPCInfo->tempGoal->r.currentOrigin ); @@ -1135,13 +987,13 @@ void NPC_BSSearch (void) } NPCS.NPCInfo->investigateDebounceTime = 0; - //Start moving toward our tempGoal + // Start moving toward our tempGoal NPCS.NPCInfo->goalEntity = NPCS.NPCInfo->tempGoal; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -1150,14 +1002,11 @@ NPC_BSSearchStart ------------------------- */ -void NPC_BSSearchStart( int homeWp, bState_t bState ) -{ - //FIXME: Reimplement - if ( homeWp == WAYPOINT_NONE ) - { - homeWp = NAV_FindClosestWaypointForEnt( NPCS.NPC, WAYPOINT_NONE ); - if( NPCS.NPC->waypoint == WAYPOINT_NONE ) - { +void NPC_BSSearchStart(int homeWp, bState_t bState) { + // FIXME: Reimplement + if (homeWp == WAYPOINT_NONE) { + homeWp = NAV_FindClosestWaypointForEnt(NPCS.NPC, WAYPOINT_NONE); + if (NPCS.NPC->waypoint == WAYPOINT_NONE) { NPCS.NPC->waypoint = homeWp; } } @@ -1165,9 +1014,9 @@ void NPC_BSSearchStart( int homeWp, bState_t bState ) NPCS.NPCInfo->tempBehavior = bState; NPCS.NPCInfo->aiFlags |= NPCAI_ENROUTE_TO_HOMEWP; NPCS.NPCInfo->investigateDebounceTime = 0; - trap->Nav_GetNodePosition( homeWp, NPCS.NPCInfo->tempGoal->r.currentOrigin ); + trap->Nav_GetNodePosition(homeWp, NPCS.NPCInfo->tempGoal->r.currentOrigin); NPCS.NPCInfo->tempGoal->waypoint = homeWp; - //Com_Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); + // Com_Printf("\nHeading for wp %d...\n", NPCInfo->homeWp); } /* @@ -1178,22 +1027,20 @@ NPC_BSNoClip ------------------------- */ -void NPC_BSNoClip ( void ) -{ +void NPC_BSNoClip(void) { - if ( UpdateGoal() ) - { - vec3_t dir, forward, right, angles, up = {0, 0, 1}; - float fDot, rDot, uDot; + if (UpdateGoal()) { + vec3_t dir, forward, right, angles, up = {0, 0, 1}; + float fDot, rDot, uDot; - VectorSubtract( NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir ); + VectorSubtract(NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir); - vectoangles( dir, angles ); + vectoangles(dir, angles); NPCS.NPCInfo->desiredYaw = angles[YAW]; - AngleVectors( NPCS.NPC->r.currentAngles, forward, right, NULL ); + AngleVectors(NPCS.NPC->r.currentAngles, forward, right, NULL); - VectorNormalize( dir ); + VectorNormalize(dir); fDot = DotProduct(forward, dir) * 127; rDot = DotProduct(right, dir) * 127; @@ -1202,109 +1049,88 @@ void NPC_BSNoClip ( void ) NPCS.ucmd.forwardmove = floor(fDot); NPCS.ucmd.rightmove = floor(rDot); NPCS.ucmd.upmove = floor(uDot); - } - else - { - //Cut velocity? - VectorClear( NPCS.NPC->client->ps.velocity ); + } else { + // Cut velocity? + VectorClear(NPCS.NPC->client->ps.velocity); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } -void NPC_BSWander (void) -{//FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? - if ( !NPCS.NPCInfo->investigateDebounceTime ) - {//Starting out - float minGoalReachedDistSquared = 64;//32*32; - vec3_t vec; +void NPC_BSWander(void) { // FIXME: don't actually go all the way to the next waypoint, just move in fits and jerks...? + if (!NPCS.NPCInfo->investigateDebounceTime) { // Starting out + float minGoalReachedDistSquared = 64; // 32*32; + vec3_t vec; - //Keep moving toward our tempGoal + // Keep moving toward our tempGoal NPCS.NPCInfo->goalEntity = NPCS.NPCInfo->tempGoal; - VectorSubtract ( NPCS.NPCInfo->tempGoal->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); + VectorSubtract(NPCS.NPCInfo->tempGoal->r.currentOrigin, NPCS.NPC->r.currentOrigin, vec); - if ( NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { + if (NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { minGoalReachedDistSquared = 64; } - if ( VectorLengthSquared( vec ) < minGoalReachedDistSquared ) - { - //Close enough, just got there - NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt( NPCS.NPC, WAYPOINT_NONE ); + if (VectorLengthSquared(vec) < minGoalReachedDistSquared) { + // Close enough, just got there + NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt(NPCS.NPC, WAYPOINT_NONE); - if( !Q_irand(0, 1) ) - { + if (!Q_irand(0, 1)) { NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_GUARD_LOOKAROUND1, SETANIM_FLAG_NORMAL); - } - else - { + } else { NPC_SetAnim(NPCS.NPC, SETANIM_BOTH, BOTH_GUARD_IDLE1, SETANIM_FLAG_NORMAL); } - //Just got here, so Look around for a while + // Just got here, so Look around for a while NPCS.NPCInfo->investigateDebounceTime = level.time + Q_irand(3000, 10000); + } else { + // Keep moving toward goal + NPC_MoveToGoal(qtrue); } - else - { - //Keep moving toward goal - NPC_MoveToGoal( qtrue ); - } - } - else - { - //We're there - if ( NPCS.NPCInfo->investigateDebounceTime > level.time ) - { - //Still waiting around for a bit - //Turn angles every now and then to look around - if ( NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE ) - { - if ( !Q_irand( 0, 30 ) ) - { - int numEdges = trap->Nav_GetNodeNumEdges( NPCS.NPCInfo->tempGoal->waypoint ); + } else { + // We're there + if (NPCS.NPCInfo->investigateDebounceTime > level.time) { + // Still waiting around for a bit + // Turn angles every now and then to look around + if (NPCS.NPCInfo->tempGoal->waypoint != WAYPOINT_NONE) { + if (!Q_irand(0, 30)) { + int numEdges = trap->Nav_GetNodeNumEdges(NPCS.NPCInfo->tempGoal->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - vec3_t branchPos, lookDir; + vec3_t branchPos, lookDir; - int nextWp = trap->Nav_GetNodeEdge( NPCS.NPCInfo->tempGoal->waypoint, branchNum ); - trap->Nav_GetNodePosition( nextWp, branchPos ); + int nextWp = trap->Nav_GetNodeEdge(NPCS.NPCInfo->tempGoal->waypoint, branchNum); + trap->Nav_GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPCS.NPCInfo->tempGoal->r.currentOrigin, lookDir ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( vectoyaw( lookDir ) + flrand( -45, 45 ) ); + VectorSubtract(branchPos, NPCS.NPCInfo->tempGoal->r.currentOrigin, lookDir); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(vectoyaw(lookDir) + flrand(-45, 45)); } } } - } - else - {//Just finished waiting - NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt( NPCS.NPC, WAYPOINT_NONE ); + } else { // Just finished waiting + NPCS.NPC->waypoint = NAV_FindClosestWaypointForEnt(NPCS.NPC, WAYPOINT_NONE); - if ( NPCS.NPC->waypoint != WAYPOINT_NONE ) - { - int numEdges = trap->Nav_GetNodeNumEdges( NPCS.NPC->waypoint ); + if (NPCS.NPC->waypoint != WAYPOINT_NONE) { + int numEdges = trap->Nav_GetNodeNumEdges(NPCS.NPC->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - int branchNum = Q_irand( 0, numEdges - 1 ); + if (numEdges != WAYPOINT_NONE) { + int branchNum = Q_irand(0, numEdges - 1); - int nextWp = trap->Nav_GetNodeEdge( NPCS.NPC->waypoint, branchNum ); - trap->Nav_GetNodePosition( nextWp, NPCS.NPCInfo->tempGoal->r.currentOrigin ); + int nextWp = trap->Nav_GetNodeEdge(NPCS.NPC->waypoint, branchNum); + trap->Nav_GetNodePosition(nextWp, NPCS.NPCInfo->tempGoal->r.currentOrigin); NPCS.NPCInfo->tempGoal->waypoint = nextWp; } NPCS.NPCInfo->investigateDebounceTime = 0; - //Start moving toward our tempGoal + // Start moving toward our tempGoal NPCS.NPCInfo->goalEntity = NPCS.NPCInfo->tempGoal; - NPC_MoveToGoal( qtrue ); + NPC_MoveToGoal(qtrue); } } } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); } /* @@ -1333,77 +1159,58 @@ void NPC_BSFaceLeader (void) NPC_BSFlee ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void WP_DropWeapon( gentity_t *dropper, vec3_t velocity ); -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -void NPC_Surrender( void ) -{//FIXME: say "don't shoot!" if we weren't already surrendering - if ( NPCS.NPC->client->ps.weaponTime || PM_InKnockDown( &NPCS.NPC->client->ps ) ) - { +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void WP_DropWeapon(gentity_t *dropper, vec3_t velocity); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +void NPC_Surrender(void) { // FIXME: say "don't shoot!" if we weren't already surrendering + if (NPCS.NPC->client->ps.weaponTime || PM_InKnockDown(&NPCS.NPC->client->ps)) { return; } - if ( NPCS.NPC->s.weapon != WP_NONE && - NPCS.NPC->s.weapon != WP_STUN_BATON && - NPCS.NPC->s.weapon != WP_SABER ) - { - //WP_DropWeapon( NPC, NULL ); //rwwFIXMEFIXME: Do this (gonna need a system for notifying client of removal) + if (NPCS.NPC->s.weapon != WP_NONE && NPCS.NPC->s.weapon != WP_STUN_BATON && NPCS.NPC->s.weapon != WP_SABER) { + // WP_DropWeapon( NPC, NULL ); //rwwFIXMEFIXME: Do this (gonna need a system for notifying client of removal) } - if ( NPCS.NPCInfo->surrenderTime < level.time - 5000 ) - {//haven't surrendered for at least 6 seconds, tell them what you're doing - //FIXME: need real dialogue EV_SURRENDER - NPCS.NPCInfo->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( NPCS.NPC, Q_irand( EV_PUSHED1, EV_PUSHED3 ), 3000 ); + if (NPCS.NPCInfo->surrenderTime < level.time - 5000) { // haven't surrendered for at least 6 seconds, tell them what you're doing + // FIXME: need real dialogue EV_SURRENDER + NPCS.NPCInfo->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_PUSHED1, EV_PUSHED3), 3000); } -// NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); -// NPC->client->ps.torsoTimer = 1000; - NPCS.NPCInfo->surrenderTime = level.time + 1000;//stay surrendered for at least 1 second - //FIXME: while surrendering, make a big sight/sound alert? Or G_AlertTeam? + // NPC_SetAnim( NPC, SETANIM_TORSO, TORSO_SURRENDER_START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); + // NPC->client->ps.torsoTimer = 1000; + NPCS.NPCInfo->surrenderTime = level.time + 1000; // stay surrendered for at least 1 second + // FIXME: while surrendering, make a big sight/sound alert? Or G_AlertTeam? } -qboolean NPC_CheckSurrender( void ) -{ - if ( !trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) - && NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE - && !NPCS.NPC->client->ps.weaponTime && !PM_InKnockDown( &NPCS.NPC->client->ps ) - && NPCS.NPC->enemy && NPCS.NPC->enemy->client && NPCS.NPC->enemy->enemy == NPCS.NPC && NPCS.NPC->enemy->s.weapon != WP_NONE && NPCS.NPC->enemy->s.weapon != WP_STUN_BATON - && NPCS.NPC->enemy->health > 20 && NPCS.NPC->enemy->painDebounceTime < level.time - 3000 && NPCS.NPC->enemy->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] < level.time - 1000 ) - {//don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the enemy is not mad at me or is hurt or not a threat or busy being attacked - //FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? - if ( NPCS.NPC->s.weapon != WP_ROCKET_LAUNCHER - && NPCS.NPC->s.weapon != WP_REPEATER - && NPCS.NPC->s.weapon != WP_FLECHETTE - && NPCS.NPC->s.weapon != WP_SABER ) - {//jedi and heavy weapons guys never surrender - //FIXME: rework all this logic into some orderly fashion!!! - if ( NPCS.NPC->s.weapon != WP_NONE ) - {//they have a weapon so they'd have to drop it to surrender - //don't give up unless low on health - if ( NPCS.NPC->health > 25 /*|| NPC->health >= NPC->max_health*/ ) - { //rwwFIXMEFIXME: Keep max health not a ps state? +qboolean NPC_CheckSurrender(void) { + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV) && NPCS.NPC->client->ps.groundEntityNum != ENTITYNUM_NONE && + !NPCS.NPC->client->ps.weaponTime && !PM_InKnockDown(&NPCS.NPC->client->ps) && NPCS.NPC->enemy && NPCS.NPC->enemy->client && + NPCS.NPC->enemy->enemy == NPCS.NPC && NPCS.NPC->enemy->s.weapon != WP_NONE && NPCS.NPC->enemy->s.weapon != WP_STUN_BATON && + NPCS.NPC->enemy->health > 20 && NPCS.NPC->enemy->painDebounceTime < level.time - 3000 && + NPCS.NPC->enemy->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] < + level.time - 1000) { // don't surrender if scripted to run somewhere or if we're in the air or if we're busy or if we don't have an enemy or if the + // enemy is not mad at me or is hurt or not a threat or busy being attacked + // FIXME: even if not in a group, don't surrender if there are other enemies in the PVS and within a certain range? + if (NPCS.NPC->s.weapon != WP_ROCKET_LAUNCHER && NPCS.NPC->s.weapon != WP_REPEATER && NPCS.NPC->s.weapon != WP_FLECHETTE && + NPCS.NPC->s.weapon != WP_SABER) { // jedi and heavy weapons guys never surrender + // FIXME: rework all this logic into some orderly fashion!!! + if (NPCS.NPC->s.weapon != WP_NONE) { // they have a weapon so they'd have to drop it to surrender + // don't give up unless low on health + if (NPCS.NPC->health > 25 /*|| NPC->health >= NPC->max_health*/) { // rwwFIXMEFIXME: Keep max health not a ps state? return qfalse; } - //if ( g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time ) - if (NPC_SomeoneLookingAtMe(NPCS.NPC) && NPCS.NPC->painDebounceTime > level.time) - {//if he just shot me, always give up - //fall through - } - else - {//don't give up unless facing enemy and he's very close - if ( !InFOV( NPCS.NPC->enemy, NPCS.NPC, 60, 30 ) ) - {//I'm not looking at them + // if ( g_crosshairEntNum == NPC->s.number && NPC->painDebounceTime > level.time ) + if (NPC_SomeoneLookingAtMe(NPCS.NPC) && NPCS.NPC->painDebounceTime > level.time) { // if he just shot me, always give up + // fall through + } else { // don't give up unless facing enemy and he's very close + if (!InFOV(NPCS.NPC->enemy, NPCS.NPC, 60, 30)) { // I'm not looking at them return qfalse; - } - else if ( DistanceSquared( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ) < 65536/*256*256*/ ) - {//they're not close + } else if (DistanceSquared(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin) < 65536 /*256*256*/) { // they're not close return qfalse; - } - else if ( !trap->InPVS( NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ) ) - {//they're not in the same room + } else if (!trap->InPVS(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin)) { // they're not in the same room return qfalse; } } } - //fixme: this logic keeps making npc's randomly surrender + // fixme: this logic keeps making npc's randomly surrender /* if ( NPCInfo->group && NPCInfo->group->numGroup <= 1 ) {//I'm alone but I was in a group//FIXME: surrender anyway if just melee or no weap? @@ -1463,307 +1270,260 @@ qboolean NPC_CheckSurrender( void ) return qfalse; } -void NPC_BSFlee( void ) -{//FIXME: keep checking for danger +void NPC_BSFlee(void) { // FIXME: keep checking for danger gentity_t *goal; - if ( TIMER_Done( NPCS.NPC, "flee" ) && NPCS.NPCInfo->tempBehavior == BS_FLEE ) - { + if (TIMER_Done(NPCS.NPC, "flee") && NPCS.NPCInfo->tempBehavior == BS_FLEE) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; NPCS.NPCInfo->squadState = SQUAD_IDLE; - //FIXME: should we set some timer to make him stay in this spot for a bit, - //so he doesn't just suddenly turn around and come back at the enemy? - //OR, just stop running toward goal for last second or so of flee? + // FIXME: should we set some timer to make him stay in this spot for a bit, + // so he doesn't just suddenly turn around and come back at the enemy? + // OR, just stop running toward goal for last second or so of flee? } - if ( NPC_CheckSurrender() ) - { + if (NPC_CheckSurrender()) { return; } goal = NPCS.NPCInfo->goalEntity; - if ( !goal ) - { + if (!goal) { goal = NPCS.NPCInfo->lastGoalEntity; - if ( !goal ) - {//???!!! + if (!goal) { //???!!! goal = NPCS.NPCInfo->tempGoal; } } - if ( goal ) - { + if (goal) { qboolean moved; qboolean reverseCourse = qtrue; - //FIXME: if no weapon, find one and run to pick it up? + // FIXME: if no weapon, find one and run to pick it up? - //Let's try to find a waypoint that gets me away from this thing - if ( NPCS.NPC->waypoint == WAYPOINT_NONE ) - { - NPCS.NPC->waypoint = NAV_GetNearestNode( NPCS.NPC, NPCS.NPC->lastWaypoint ); + // Let's try to find a waypoint that gets me away from this thing + if (NPCS.NPC->waypoint == WAYPOINT_NONE) { + NPCS.NPC->waypoint = NAV_GetNearestNode(NPCS.NPC, NPCS.NPC->lastWaypoint); } - if ( NPCS.NPC->waypoint != WAYPOINT_NONE ) - { - int numEdges = trap->Nav_GetNodeNumEdges( NPCS.NPC->waypoint ); + if (NPCS.NPC->waypoint != WAYPOINT_NONE) { + int numEdges = trap->Nav_GetNodeNumEdges(NPCS.NPC->waypoint); - if ( numEdges != WAYPOINT_NONE ) - { - vec3_t dangerDir; - int nextWp; - int branchNum; + if (numEdges != WAYPOINT_NONE) { + vec3_t dangerDir; + int nextWp; + int branchNum; - VectorSubtract( NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.currentOrigin, dangerDir ); - VectorNormalize( dangerDir ); + VectorSubtract(NPCS.NPCInfo->investigateGoal, NPCS.NPC->r.currentOrigin, dangerDir); + VectorNormalize(dangerDir); - for ( branchNum = 0; branchNum < numEdges; branchNum++ ) - { - vec3_t branchPos, runDir; + for (branchNum = 0; branchNum < numEdges; branchNum++) { + vec3_t branchPos, runDir; - nextWp = trap->Nav_GetNodeEdge( NPCS.NPC->waypoint, branchNum ); - trap->Nav_GetNodePosition( nextWp, branchPos ); + nextWp = trap->Nav_GetNodeEdge(NPCS.NPC->waypoint, branchNum); + trap->Nav_GetNodePosition(nextWp, branchPos); - VectorSubtract( branchPos, NPCS.NPC->r.currentOrigin, runDir ); - VectorNormalize( runDir ); - if ( DotProduct( runDir, dangerDir ) > flrand( 0, 0.5 ) ) - {//don't run toward danger + VectorSubtract(branchPos, NPCS.NPC->r.currentOrigin, runDir); + VectorNormalize(runDir); + if (DotProduct(runDir, dangerDir) > flrand(0, 0.5)) { // don't run toward danger continue; } - //FIXME: don't want to ping-pong back and forth - NPC_SetMoveGoal( NPCS.NPC, branchPos, 0, qtrue, -1, NULL ); + // FIXME: don't want to ping-pong back and forth + NPC_SetMoveGoal(NPCS.NPC, branchPos, 0, qtrue, -1, NULL); reverseCourse = qfalse; break; } } } - moved = NPC_MoveToGoal( qfalse );//qtrue? (do try to move straight to (away from) goal) + moved = NPC_MoveToGoal(qfalse); // qtrue? (do try to move straight to (away from) goal) - if ( NPCS.NPC->s.weapon == WP_NONE && (moved == qfalse || reverseCourse) ) - {//No weapon and no escape route... Just cower? Need anim. + if (NPCS.NPC->s.weapon == WP_NONE && (moved == qfalse || reverseCourse)) { // No weapon and no escape route... Just cower? Need anim. NPC_Surrender(); - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - //If our move failed, then just run straight away from our goal - //FIXME: We really shouldn't do this. - if ( moved == qfalse ) - { - vec3_t dir; - if ( reverseCourse ) - { - VectorSubtract( NPCS.NPC->r.currentOrigin, goal->r.currentOrigin, dir ); - } - else - { - VectorSubtract( goal->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir ); + // If our move failed, then just run straight away from our goal + // FIXME: We really shouldn't do this. + if (moved == qfalse) { + vec3_t dir; + if (reverseCourse) { + VectorSubtract(NPCS.NPC->r.currentOrigin, goal->r.currentOrigin, dir); + } else { + VectorSubtract(goal->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir); } - NPCS.NPCInfo->distToGoal = VectorNormalize( dir ); - NPCS.NPCInfo->desiredYaw = vectoyaw( dir ); + NPCS.NPCInfo->distToGoal = VectorNormalize(dir); + NPCS.NPCInfo->desiredYaw = vectoyaw(dir); NPCS.NPCInfo->desiredPitch = 0; NPCS.ucmd.forwardmove = 127; - } - else if ( reverseCourse ) - { - //ucmd.forwardmove *= -1; - //ucmd.rightmove *= -1; - //VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); + } else if (reverseCourse) { + // ucmd.forwardmove *= -1; + // ucmd.rightmove *= -1; + // VectorScale( NPC->client->ps.moveDir, -1, NPC->client->ps.moveDir ); NPCS.NPCInfo->desiredYaw *= -1; } - //FIXME: can stop after a safe distance? - //ucmd.upmove = 0; + // FIXME: can stop after a safe distance? + // ucmd.upmove = 0; NPCS.ucmd.buttons &= ~BUTTON_WALKING; - //FIXME: what do we do once we've gotten to our goal? + // FIXME: what do we do once we've gotten to our goal? } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); NPC_CheckGetNewWeapon(); } -void NPC_StartFlee( gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ +void NPC_StartFlee(gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { int cp = -1; - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ) ) - {//running somewhere that a script requires us to go, don't interrupt that! + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV)) { // running somewhere that a script requires us to go, don't interrupt that! return; } - //if have a fleescript, run that instead - if ( G_ActivateBehavior( NPCS.NPC, BSET_FLEE ) ) - { + // if have a fleescript, run that instead + if (G_ActivateBehavior(NPCS.NPC, BSET_FLEE)) { return; } - //FIXME: play a flee sound? Appropriate to situation? - if ( enemy ) - { - G_SetEnemy( NPCS.NPC, enemy ); + // FIXME: play a flee sound? Appropriate to situation? + if (enemy) { + G_SetEnemy(NPCS.NPC, enemy); } - //FIXME: if don't have a weapon, find nearest one we have a route to and run for it? - if ( dangerLevel > AEL_DANGER || NPCS.NPC->s.weapon == WP_NONE || ((!NPCS.NPCInfo->group || NPCS.NPCInfo->group->numGroup <= 1) && NPCS.NPC->health <= 10 ) ) - {//IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER|CP_AVOID|CP_HAS_ROUTE|CP_NO_PVS, 128, -1 ); + // FIXME: if don't have a weapon, find nearest one we have a route to and run for it? + if (dangerLevel > AEL_DANGER || NPCS.NPC->s.weapon == WP_NONE || + ((!NPCS.NPCInfo->group || NPCS.NPCInfo->group->numGroup <= 1) && + NPCS.NPC->health <= 10)) { // IF either great danger OR I have no weapon OR I'm alone and low on health, THEN try to find a combat point out of PVS + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER | CP_AVOID | CP_HAS_ROUTE | CP_NO_PVS, 128, -1); } - //FIXME: still happens too often... - if ( cp == -1 ) - {//okay give up on the no PVS thing - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER|CP_AVOID|CP_HAS_ROUTE, 128, -1 ); - if ( cp == -1 ) - {//okay give up on the avoid - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER|CP_HAS_ROUTE, 128, -1 ); - if ( cp == -1 ) - {//okay give up on the cover - cp = NPC_FindCombatPoint( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_HAS_ROUTE, 128, -1 ); + // FIXME: still happens too often... + if (cp == -1) { // okay give up on the no PVS thing + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER | CP_AVOID | CP_HAS_ROUTE, 128, -1); + if (cp == -1) { // okay give up on the avoid + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_COVER | CP_HAS_ROUTE, 128, -1); + if (cp == -1) { // okay give up on the cover + cp = NPC_FindCombatPoint(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.currentOrigin, dangerPoint, CP_HAS_ROUTE, 128, -1); } } } - //see if we got a valid one - if ( cp != -1 ) - {//found a combat point - NPC_SetCombatPoint( cp ); - NPC_SetMoveGoal( NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL ); + // see if we got a valid one + if (cp != -1) { // found a combat point + NPC_SetCombatPoint(cp); + NPC_SetMoveGoal(NPCS.NPC, level.combatPoints[cp].origin, 8, qtrue, cp, NULL); NPCS.NPCInfo->behaviorState = BS_HUNT_AND_KILL; NPCS.NPCInfo->tempBehavior = BS_DEFAULT; - } - else - {//need to just run like hell! - if ( NPCS.NPC->s.weapon != WP_NONE ) - { - return;//let's just not flee? - } - else - { - //FIXME: other evasion AI? Duck? Strafe? Dodge? + } else { // need to just run like hell! + if (NPCS.NPC->s.weapon != WP_NONE) { + return; // let's just not flee? + } else { + // FIXME: other evasion AI? Duck? Strafe? Dodge? NPCS.NPCInfo->tempBehavior = BS_FLEE; - //Run straight away from here... FIXME: really want to find farthest waypoint/navgoal from this pos... maybe based on alert event radius? - NPC_SetMoveGoal( NPCS.NPC, dangerPoint, 0, qtrue, -1, NULL ); - //store the danger point - VectorCopy( dangerPoint, NPCS.NPCInfo->investigateGoal );//FIXME: make a new field for this? + // Run straight away from here... FIXME: really want to find farthest waypoint/navgoal from this pos... maybe based on alert event radius? + NPC_SetMoveGoal(NPCS.NPC, dangerPoint, 0, qtrue, -1, NULL); + // store the danger point + VectorCopy(dangerPoint, NPCS.NPCInfo->investigateGoal); // FIXME: make a new field for this? } } - //FIXME: localize this Timer? - TIMER_Set( NPCS.NPC, "attackDelay", Q_irand( 500, 2500 ) ); - //FIXME: is this always applicable? + // FIXME: localize this Timer? + TIMER_Set(NPCS.NPC, "attackDelay", Q_irand(500, 2500)); + // FIXME: is this always applicable? NPCS.NPCInfo->squadState = SQUAD_RETREAT; - TIMER_Set( NPCS.NPC, "flee", Q_irand( fleeTimeMin, fleeTimeMax ) ); - TIMER_Set( NPCS.NPC, "panic", Q_irand( 1000, 4000 ) );//how long to wait before trying to nav to a dropped weapon + TIMER_Set(NPCS.NPC, "flee", Q_irand(fleeTimeMin, fleeTimeMax)); + TIMER_Set(NPCS.NPC, "panic", Q_irand(1000, 4000)); // how long to wait before trying to nav to a dropped weapon - if (NPCS.NPC->client->NPC_class != CLASS_PROTOCOL) - { - TIMER_Set( NPCS.NPC, "duck", 0 ); + if (NPCS.NPC->client->NPC_class != CLASS_PROTOCOL) { + TIMER_Set(NPCS.NPC, "duck", 0); } } -void G_StartFlee( gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax ) -{ - if ( !self->NPC ) - {//player +void G_StartFlee(gentity_t *self, gentity_t *enemy, vec3_t dangerPoint, int dangerLevel, int fleeTimeMin, int fleeTimeMax) { + if (!self->NPC) { // player return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - NPC_StartFlee( enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax ); + NPC_StartFlee(enemy, dangerPoint, dangerLevel, fleeTimeMin, fleeTimeMax); RestoreNPCGlobals(); } -void NPC_BSEmplaced( void ) -{ +void NPC_BSEmplaced(void) { qboolean enemyLOS = qfalse; qboolean enemyCS = qfalse; qboolean faceEnemy = qfalse; qboolean shoot = qfalse; - vec3_t impactPos; + vec3_t impactPos; - //Don't do anything if we're hurt - if ( NPCS.NPC->painDebounceTime > level.time ) - { - NPC_UpdateAngles( qtrue, qtrue ); + // Don't do anything if we're hurt + if (NPCS.NPC->painDebounceTime > level.time) { + NPC_UpdateAngles(qtrue, qtrue); return; } - if( NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON ) - { - WeaponThink( qtrue ); + if (NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) { + WeaponThink(qtrue); } - //If we don't have an enemy, just idle - if ( NPC_CheckEnemyExt(qfalse) == qfalse ) - { - if ( !Q_irand( 0, 30 ) ) - { - NPCS.NPCInfo->desiredYaw = NPCS.NPC->s.angles[1] + Q_irand( -90, 90 ); + // If we don't have an enemy, just idle + if (NPC_CheckEnemyExt(qfalse) == qfalse) { + if (!Q_irand(0, 30)) { + NPCS.NPCInfo->desiredYaw = NPCS.NPC->s.angles[1] + Q_irand(-90, 90); } - if ( !Q_irand( 0, 30 ) ) - { - NPCS.NPCInfo->desiredPitch = Q_irand( -20, 20 ); + if (!Q_irand(0, 30)) { + NPCS.NPCInfo->desiredPitch = Q_irand(-20, 20); } - NPC_UpdateAngles( qtrue, qtrue ); + NPC_UpdateAngles(qtrue, qtrue); return; } - if ( NPC_ClearLOS4( NPCS.NPC->enemy ) ) - { + if (NPC_ClearLOS4(NPCS.NPC->enemy)) { int hit; gentity_t *hitEnt; enemyLOS = qtrue; - hit = NPC_ShotEntity( NPCS.NPC->enemy, impactPos ); + hit = NPC_ShotEntity(NPCS.NPC->enemy, impactPos); hitEnt = &g_entities[hit]; - if ( hit == NPCS.NPC->enemy->s.number || ( hitEnt && hitEnt->takedamage ) ) - {//can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || + (hitEnt && hitEnt->takedamage)) { // can hit enemy or will hit glass or other minor breakable (or in emplaced gun), so shoot anyway enemyCS = qtrue; - NPC_AimAdjust( 2 );//adjust aim better longer we have clear shot at enemy - VectorCopy( NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); + NPC_AimAdjust(2); // adjust aim better longer we have clear shot at enemy + VectorCopy(NPCS.NPC->enemy->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); } } -/* - else if ( trap->InPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin ) ) - { - NPCInfo->enemyLastSeenTime = level.time; - faceEnemy = qtrue; - NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy - } -*/ + /* + else if ( trap->InPVS( NPC->enemy->r.currentOrigin, NPC->r.currentOrigin ) ) + { + NPCInfo->enemyLastSeenTime = level.time; + faceEnemy = qtrue; + NPC_AimAdjust( -1 );//adjust aim worse longer we cannot see enemy + } + */ - if ( enemyLOS ) - {//FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? + if (enemyLOS) { // FIXME: no need to face enemy if we're moving to some other goal and he's too far away to shoot? faceEnemy = qtrue; } - if ( enemyCS ) - { + if (enemyCS) { shoot = qtrue; } - if ( faceEnemy ) - {//face the enemy - NPC_FaceEnemy( qtrue ); - } - else - {//we want to face in the dir we're running - NPC_UpdateAngles( qtrue, qtrue ); + if (faceEnemy) { // face the enemy + NPC_FaceEnemy(qtrue); + } else { // we want to face in the dir we're running + NPC_UpdateAngles(qtrue, qtrue); } - if ( NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE ) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { shoot = qfalse; } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->enemy ) - { - if ( NPCS.NPC->enemy->s.weapon == WP_SABER && NPCS.NPC->enemy->enemy->s.weapon == WP_SABER ) - {//don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) + if (NPCS.NPC->enemy && NPCS.NPC->enemy->enemy) { + if (NPCS.NPC->enemy->s.weapon == WP_SABER && + NPCS.NPC->enemy->enemy->s.weapon == WP_SABER) { // don't shoot at an enemy jedi who is fighting another jedi, for fear of injuring one or causing + // rogue blaster deflections (a la Obi Wan/Vader duel at end of ANH) shoot = qfalse; } } - if ( shoot ) - {//try to shoot if it's time - if( !(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON) ) // we've already fired, no need to do it again here + if (shoot) { // try to shoot if it's time + if (!(NPCS.NPCInfo->scriptFlags & SCF_FIRE_WEAPON)) // we've already fired, no need to do it again here { - WeaponThink( qtrue ); + WeaponThink(qtrue); } } } diff --git a/codemp/game/NPC_combat.c b/codemp/game/NPC_combat.c index 7b855edc0c..3dcc1212f3 100644 --- a/codemp/game/NPC_combat.c +++ b/codemp/game/NPC_combat.c @@ -20,38 +20,34 @@ along with this program; if not, see . =========================================================================== */ -//NPC_combat.cpp +// NPC_combat.cpp #include "b_local.h" #include "g_nav.h" -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_ClearLookTarget( gentity_t *self ); -extern void NPC_Jedi_RateNewEnemy( gentity_t *self, gentity_t *enemy ); -extern int NAV_FindClosestWaypointForPoint2( vec3_t point ); -extern int NAV_GetNearestNode( gentity_t *self, int lastNode ); -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); -extern qboolean PM_DroidMelee( int npc_class ); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_ClearLookTarget(gentity_t *self); +extern void NPC_Jedi_RateNewEnemy(gentity_t *self, gentity_t *enemy); +extern int NAV_FindClosestWaypointForPoint2(vec3_t point); +extern int NAV_GetNearestNode(gentity_t *self, int lastNode); +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); +extern qboolean PM_DroidMelee(int npc_class); -void ChangeWeapon( gentity_t *ent, int newWeapon ); +void ChangeWeapon(gentity_t *ent, int newWeapon); -void G_ClearEnemy (gentity_t *self) -{ - NPC_CheckLookTarget( self ); +void G_ClearEnemy(gentity_t *self) { + NPC_CheckLookTarget(self); - if ( self->enemy ) - { - if( self->client && self->client->renderInfo.lookTarget == self->enemy->s.number ) - { - NPC_ClearLookTarget( self ); + if (self->enemy) { + if (self->client && self->client->renderInfo.lookTarget == self->enemy->s.number) { + NPC_ClearLookTarget(self); } - if ( self->NPC && self->enemy == self->NPC->goalEntity ) - { + if (self->NPC && self->enemy == self->NPC->goalEntity) { self->NPC->goalEntity = NULL; } - //FIXME: set last enemy? + // FIXME: set last enemy? } self->enemy = NULL; @@ -63,21 +59,18 @@ NPC_AngerAlert ------------------------- */ -#define ANGER_ALERT_RADIUS 512 -#define ANGER_ALERT_SOUND_RADIUS 256 +#define ANGER_ALERT_RADIUS 512 +#define ANGER_ALERT_SOUND_RADIUS 256 -void G_AngerAlert( gentity_t *self ) -{ - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... +void G_AngerAlert(gentity_t *self) { + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return; } - if ( !TIMER_Done( self, "interrogating" ) ) - {//I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! + if (!TIMER_Done(self, "interrogating")) { // I'm interrogating, don't wake everyone else up yet... FIXME: this may never wake everyone else up, though! return; } - //FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? - G_AlertTeam( self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS ); + // FIXME: hmm.... with all the other new alerts now, is this still neccesary or even a good idea...? + G_AlertTeam(self, self->enemy, ANGER_ALERT_RADIUS, ANGER_ALERT_SOUND_RADIUS); } /* @@ -86,48 +79,39 @@ G_TeamEnemy ------------------------- */ -qboolean G_TeamEnemy( gentity_t *self ) -{//FIXME: Probably a better way to do this, is a linked list of your teammates already available? - int i; - gentity_t *ent; +qboolean G_TeamEnemy(gentity_t *self) { // FIXME: Probably a better way to do this, is a linked list of your teammates already available? + int i; + gentity_t *ent; - if ( !self->client || self->client->playerTeam == NPCTEAM_FREE ) - { + if (!self->client || self->client->playerTeam == NPCTEAM_FREE) { return qfalse; } - if ( self && self->NPC && (self->NPC->scriptFlags&SCF_NO_GROUPS) ) - {//I'm not a team playa... + if (self && self->NPC && (self->NPC->scriptFlags & SCF_NO_GROUPS)) { // I'm not a team playa... return qfalse; } - for( i = 1; i < level.num_entities; i++ ) - { + for (i = 1; i < level.num_entities; i++) { ent = &g_entities[i]; - if ( ent == self ) - { + if (ent == self) { continue; } - if ( ent->health <= 0 ) - { + if (ent->health <= 0) { continue; } - if ( !ent->client ) - { + if (!ent->client) { continue; } - if ( ent->client->playerTeam != self->client->playerTeam ) - {//ent is not on my team + if (ent->client->playerTeam != self->client->playerTeam) { // ent is not on my team continue; } - if ( ent->enemy ) - {//they have an enemy - if ( !ent->enemy->client || ent->enemy->client->playerTeam != self->client->playerTeam ) - {//the ent's enemy is either a normal ent or is a player/NPC that is not on my team + if (ent->enemy) { // they have an enemy + if (!ent->enemy->client || ent->enemy->client->playerTeam != + self->client->playerTeam) { // the ent's enemy is either a normal ent or is a player/NPC that is not on my team return qtrue; } } @@ -136,62 +120,55 @@ qboolean G_TeamEnemy( gentity_t *self ) return qfalse; } -void G_AttackDelay( gentity_t *self, gentity_t *enemy ) -{ - if ( enemy && self->client && self->NPC ) - {//delay their attack based on how far away they're facing from enemy - vec3_t fwd, dir; - int attDelay; +void G_AttackDelay(gentity_t *self, gentity_t *enemy) { + if (enemy && self->client && self->NPC) { // delay their attack based on how far away they're facing from enemy + vec3_t fwd, dir; + int attDelay; - VectorSubtract( self->client->renderInfo.eyePoint, enemy->r.currentOrigin, dir );//purposely backwards - VectorNormalize( dir ); - AngleVectors( self->client->renderInfo.eyeAngles, fwd, NULL, NULL ); - //dir[2] = fwd[2] = 0;//ignore z diff? + VectorSubtract(self->client->renderInfo.eyePoint, enemy->r.currentOrigin, dir); // purposely backwards + VectorNormalize(dir); + AngleVectors(self->client->renderInfo.eyeAngles, fwd, NULL, NULL); + // dir[2] = fwd[2] = 0;//ignore z diff? - attDelay = (4-g_npcspskill.integer)*500;//initial: from 1000ms delay on hard to 2000ms delay on easy - if ( self->client->playerTeam == NPCTEAM_PLAYER ) - {//invert - attDelay = 2000-attDelay; + attDelay = (4 - g_npcspskill.integer) * 500; // initial: from 1000ms delay on hard to 2000ms delay on easy + if (self->client->playerTeam == NPCTEAM_PLAYER) { // invert + attDelay = 2000 - attDelay; } - attDelay += floor( (DotProduct( fwd, dir )+1.0f) * 2000.0f );//add up to 4000ms delay if they're facing away + attDelay += floor((DotProduct(fwd, dir) + 1.0f) * 2000.0f); // add up to 4000ms delay if they're facing away - //FIXME: should distance matter, too? + // FIXME: should distance matter, too? - //Now modify the delay based on NPC_class, weapon, and team - //NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds - switch ( self->client->NPC_class ) - { - case CLASS_IMPERIAL://they give orders and hang back - attDelay += Q_irand( 500, 1500 ); + // Now modify the delay based on NPC_class, weapon, and team + // NOTE: attDelay should be somewhere between 1000 to 6000 milliseconds + switch (self->client->NPC_class) { + case CLASS_IMPERIAL: // they give orders and hang back + attDelay += Q_irand(500, 1500); break; - case CLASS_STORMTROOPER://stormtroopers shoot sooner - if ( self->NPC->rank >= RANK_LT ) - {//officers shoot even sooner - attDelay -= Q_irand( 500, 1500 ); - } - else - {//normal stormtroopers don't have as fast reflexes as officers - attDelay -= Q_irand( 0, 1000 ); + case CLASS_STORMTROOPER: // stormtroopers shoot sooner + if (self->NPC->rank >= RANK_LT) { // officers shoot even sooner + attDelay -= Q_irand(500, 1500); + } else { // normal stormtroopers don't have as fast reflexes as officers + attDelay -= Q_irand(0, 1000); } break; - case CLASS_SWAMPTROOPER://shoot very quickly? What about guys in water? - attDelay -= Q_irand( 1000, 2000 ); + case CLASS_SWAMPTROOPER: // shoot very quickly? What about guys in water? + attDelay -= Q_irand(1000, 2000); break; - case CLASS_IMPWORKER://they panic, don't fire right away - attDelay += Q_irand( 1000, 2500 ); + case CLASS_IMPWORKER: // they panic, don't fire right away + attDelay += Q_irand(1000, 2500); break; case CLASS_TRANDOSHAN: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; case CLASS_JAN: case CLASS_LANDO: case CLASS_PRISONER: case CLASS_REBEL: - attDelay -= Q_irand( 500, 1500 ); + attDelay -= Q_irand(500, 1500); break; case CLASS_GALAKMECH: case CLASS_ATST: - attDelay -= Q_irand( 1000, 2000 ); + attDelay -= Q_irand(1000, 2000); break; case CLASS_REELO: case CLASS_UGNAUGHT: @@ -230,8 +207,7 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) break; } - switch ( self->s.weapon ) - { + switch (self->s.weapon) { case WP_NONE: case WP_SABER: return; @@ -239,278 +215,237 @@ void G_AttackDelay( gentity_t *self, gentity_t *enemy ) case WP_BRYAR_PISTOL: break; case WP_BLASTER: - if ( self->NPC->scriptFlags & SCF_ALT_FIRE ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); - } - else - {//regular blaster - attDelay -= Q_irand( 0, 500 ); + if (self->NPC->scriptFlags & SCF_ALT_FIRE) { // rapid-fire blasters + attDelay += Q_irand(0, 500); + } else { // regular blaster + attDelay -= Q_irand(0, 500); } break; case WP_BOWCASTER: - attDelay += Q_irand( 0, 500 ); + attDelay += Q_irand(0, 500); break; case WP_REPEATER: - if ( !(self->NPC->scriptFlags&SCF_ALT_FIRE) ) - {//rapid-fire blasters - attDelay += Q_irand( 0, 500 ); + if (!(self->NPC->scriptFlags & SCF_ALT_FIRE)) { // rapid-fire blasters + attDelay += Q_irand(0, 500); } break; case WP_FLECHETTE: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; case WP_ROCKET_LAUNCHER: - attDelay += Q_irand( 500, 1500 ); + attDelay += Q_irand(500, 1500); break; -// case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster -// attDelay -= Q_irand( 500, 1500 ); -// break; - //rwwFIXMEFIXME: Have this weapon for NPCs? - case WP_DISRUPTOR://sniper's don't delay? + // case WP_BLASTER_PISTOL: // apparently some enemy only version of the blaster + // attDelay -= Q_irand( 500, 1500 ); + // break; + // rwwFIXMEFIXME: Have this weapon for NPCs? + case WP_DISRUPTOR: // sniper's don't delay? return; break; - case WP_THERMAL://grenade-throwing has a built-in delay + case WP_THERMAL: // grenade-throwing has a built-in delay return; break; - case WP_STUN_BATON: // Any ol' melee attack + case WP_STUN_BATON: // Any ol' melee attack return; break; case WP_EMPLACED_GUN: return; break; - case WP_TURRET: // turret guns + case WP_TURRET: // turret guns return; break; -// case WP_BOT_LASER: // Probe droid - Laser blast -// return; //rwwFIXMEFIXME: Have this weapon for NPCs? - break; - /* - case WP_DEMP2: - break; - case WP_TRIP_MINE: - break; - case WP_DET_PACK: - break; - case WP_STUN_BATON: - break; - case WP_ATST_MAIN: - break; - case WP_ATST_SIDE: - break; - case WP_TIE_FIGHTER: - break; - case WP_RAPID_FIRE_CONC: + // case WP_BOT_LASER: // Probe droid - Laser blast + // return; //rwwFIXMEFIXME: Have this weapon for NPCs? break; - */ + /* + case WP_DEMP2: + break; + case WP_TRIP_MINE: + break; + case WP_DET_PACK: + break; + case WP_STUN_BATON: + break; + case WP_ATST_MAIN: + break; + case WP_ATST_SIDE: + break; + case WP_TIE_FIGHTER: + break; + case WP_RAPID_FIRE_CONC: + break; + */ } - if ( self->client->playerTeam == NPCTEAM_PLAYER ) - {//clamp it - if ( attDelay > 2000 ) - { + if (self->client->playerTeam == NPCTEAM_PLAYER) { // clamp it + if (attDelay > 2000) { attDelay = 2000; } } - //don't shoot right away - if ( attDelay > 4000+((2-g_npcspskill.integer)*3000) ) - { - attDelay = 4000+((2-g_npcspskill.integer)*3000); + // don't shoot right away + if (attDelay > 4000 + ((2 - g_npcspskill.integer) * 3000)) { + attDelay = 4000 + ((2 - g_npcspskill.integer) * 3000); } - TIMER_Set( self, "attackDelay", attDelay );//Q_irand( 1500, 4500 ) ); - //don't move right away either - if ( attDelay > 4000 ) - { + TIMER_Set(self, "attackDelay", attDelay); // Q_irand( 1500, 4500 ) ); + // don't move right away either + if (attDelay > 4000) { attDelay = 4000 - Q_irand(500, 1500); - } - else - { + } else { attDelay -= Q_irand(500, 1500); } - TIMER_Set( self, "roamTime", attDelay );//was Q_irand( 1000, 3500 ); + TIMER_Set(self, "roamTime", attDelay); // was Q_irand( 1000, 3500 ); } } -void G_ForceSaberOn(gentity_t *ent) -{ - if (ent->client->ps.saberInFlight) - { //alright, can't turn it on now in any case, so forget it. +void G_ForceSaberOn(gentity_t *ent) { + if (ent->client->ps.saberInFlight) { // alright, can't turn it on now in any case, so forget it. return; } - if (!ent->client->ps.saberHolstered) - { //it's already on! + if (!ent->client->ps.saberHolstered) { // it's already on! return; } - if (ent->client->ps.weapon != WP_SABER) - { //This probably should never happen. But if it does we'll just return without complaining. + if (ent->client->ps.weapon != WP_SABER) { // This probably should never happen. But if it does we'll just return without complaining. return; } - //Well then, turn it on. + // Well then, turn it on. ent->client->ps.saberHolstered = 0; - if (ent->client->saber[0].soundOn) - { + if (ent->client->saber[0].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOn); } - if (ent->client->saber[1].soundOn) - { + if (ent->client->saber[1].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOn); } } - /* ------------------------- G_SetEnemy ------------------------- */ -void G_AimSet( gentity_t *self, int aim ); -void G_SetEnemy( gentity_t *self, gentity_t *enemy ) -{ - int event = 0; +void G_AimSet(gentity_t *self, int aim); +void G_SetEnemy(gentity_t *self, gentity_t *enemy) { + int event = 0; - //Must be valid - if ( enemy == NULL ) + // Must be valid + if (enemy == NULL) return; - //Must be valid - if ( enemy->inuse == 0 ) - { + // Must be valid + if (enemy->inuse == 0) { return; } - //Don't take the enemy if in notarget - if ( enemy->flags & FL_NOTARGET ) + // Don't take the enemy if in notarget + if (enemy->flags & FL_NOTARGET) return; - if ( !self->NPC ) - { + if (!self->NPC) { self->enemy = enemy; return; } - if ( self->NPC->confusionTime > level.time ) - {//can't pick up enemies if confused + if (self->NPC->confusionTime > level.time) { // can't pick up enemies if confused return; } #ifdef _DEBUG - if ( self->s.number >= MAX_CLIENTS ) - { - assert( enemy != self ); + if (self->s.number >= MAX_CLIENTS) { + assert(enemy != self); } -#endif// _DEBUG +#endif // _DEBUG -// if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) -// {//unmask the player -// enemy->client->playerTeam = TEAM_PLAYER; -// } + // if ( enemy->client && enemy->client->playerTeam == TEAM_DISGUISE ) + // {//unmask the player + // enemy->client->playerTeam = TEAM_PLAYER; + // } - if ( self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam ) - {//Probably a damn script! - if ( self->NPC->charmedTime > level.time ) - {//Probably a damn script! + if (self->client && self->NPC && enemy->client && enemy->client->playerTeam == self->client->playerTeam) { // Probably a damn script! + if (self->NPC->charmedTime > level.time) { // Probably a damn script! return; } } - if ( self->NPC && self->client && self->client->ps.weapon == WP_SABER ) - { - //when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. - NPC_Jedi_RateNewEnemy( self, enemy ); + if (self->NPC && self->client && self->client->ps.weapon == WP_SABER) { + // when get new enemy, set a base aggression based on what that enemy is using, how far they are, etc. + NPC_Jedi_RateNewEnemy(self, enemy); } - //NOTE: this is not necessarily true! - //self->NPC->enemyLastSeenTime = level.time; + // NOTE: this is not necessarily true! + // self->NPC->enemyLastSeenTime = level.time; - if ( self->enemy == NULL ) - { - //TEMP HACK: turn on our saber - if ( self->health > 0 ) - { + if (self->enemy == NULL) { + // TEMP HACK: turn on our saber + if (self->health > 0) { G_ForceSaberOn(self); } - //FIXME: Have to do this to prevent alert cascading - G_ClearEnemy( self ); + // FIXME: Have to do this to prevent alert cascading + G_ClearEnemy(self); self->enemy = enemy; - //Special case- if player is being hunted by his own people, set their enemy team correctly - if ( self->client->playerTeam == NPCTEAM_PLAYER && enemy->s.number >= 0 && enemy->s.number < MAX_CLIENTS ) - { + // Special case- if player is being hunted by his own people, set their enemy team correctly + if (self->client->playerTeam == NPCTEAM_PLAYER && enemy->s.number >= 0 && enemy->s.number < MAX_CLIENTS) { self->client->enemyTeam = NPCTEAM_PLAYER; } - //If have an anger script, run that instead of yelling - if( G_ActivateBehavior( self, BSET_ANGER ) ) - { - } - else if ( self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam ) - { - //FIXME: Use anger when entire team has no enemy. + // If have an anger script, run that instead of yelling + if (G_ActivateBehavior(self, BSET_ANGER)) { + } else if (self->client && enemy->client && self->client->playerTeam != enemy->client->playerTeam) { + // FIXME: Use anger when entire team has no enemy. // Basically, you're first one to notice enemies - //if ( self->forcePushTime < level.time ) // not currently being pushed - if (1) //rwwFIXMEFIXME: Set forcePushTime + // if ( self->forcePushTime < level.time ) // not currently being pushed + if (1) // rwwFIXMEFIXME: Set forcePushTime { - if ( !G_TeamEnemy( self ) ) - {//team did not have an enemy previously + if (!G_TeamEnemy(self)) { // team did not have an enemy previously event = Q_irand(EV_ANGER1, EV_ANGER3); } } - if ( event ) - {//yell - G_AddVoiceEvent( self, event, 2000 ); + if (event) { // yell + G_AddVoiceEvent(self, event, 2000); } } - if ( self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || - self->s.weapon == WP_THERMAL /*|| self->s.weapon == WP_BLASTER_PISTOL */ //rwwFIXMEFIXME: Blaster pistol useable by npcs? - || self->s.weapon == WP_BOWCASTER ) - {//Hmm, how about sniper and bowcaster? - //When first get mad, aim is bad - //Hmm, base on game difficulty, too? Rank? - if ( self->client->playerTeam == NPCTEAM_PLAYER ) - { - G_AimSet( self, Q_irand( self->NPC->stats.aim - (5*(g_npcspskill.integer)), self->NPC->stats.aim - g_npcspskill.integer ) ); - } - else - { + if (self->s.weapon == WP_BLASTER || self->s.weapon == WP_REPEATER || + self->s.weapon == WP_THERMAL /*|| self->s.weapon == WP_BLASTER_PISTOL */ // rwwFIXMEFIXME: Blaster pistol useable by npcs? + || self->s.weapon == WP_BOWCASTER) { // Hmm, how about sniper and bowcaster? + // When first get mad, aim is bad + // Hmm, base on game difficulty, too? Rank? + if (self->client->playerTeam == NPCTEAM_PLAYER) { + G_AimSet(self, Q_irand(self->NPC->stats.aim - (5 * (g_npcspskill.integer)), self->NPC->stats.aim - g_npcspskill.integer)); + } else { int minErr = 3; int maxErr = 12; - if ( self->client->NPC_class == CLASS_IMPWORKER ) - { + if (self->client->NPC_class == CLASS_IMPWORKER) { minErr = 15; maxErr = 30; - } - else if ( self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN ) - { + } else if (self->client->NPC_class == CLASS_STORMTROOPER && self->NPC && self->NPC->rank <= RANK_CREWMAN) { minErr = 5; maxErr = 15; } - G_AimSet( self, Q_irand( self->NPC->stats.aim - (maxErr*(3-g_npcspskill.integer)), self->NPC->stats.aim - (minErr*(3-g_npcspskill.integer)) ) ); + G_AimSet(self, + Q_irand(self->NPC->stats.aim - (maxErr * (3 - g_npcspskill.integer)), self->NPC->stats.aim - (minErr * (3 - g_npcspskill.integer)))); } } - //Alert anyone else in the area - if ( Q_stricmp( "desperado", self->NPC_type ) != 0 && Q_stricmp( "paladin", self->NPC_type ) != 0 ) - {//special holodeck enemies exception - if ( self->client->ps.fd.forceGripBeingGripped < level.time ) - {//gripped people can't call for help - G_AngerAlert( self ); + // Alert anyone else in the area + if (Q_stricmp("desperado", self->NPC_type) != 0 && Q_stricmp("paladin", self->NPC_type) != 0) { // special holodeck enemies exception + if (self->client->ps.fd.forceGripBeingGripped < level.time) { // gripped people can't call for help + G_AngerAlert(self); } } - //Stormtroopers don't fire right away! - G_AttackDelay( self, enemy ); + // Stormtroopers don't fire right away! + G_AttackDelay(self, enemy); - //rwwFIXMEFIXME: Deal with this some other way. + // rwwFIXMEFIXME: Deal with this some other way. /* //FIXME: this is a disgusting hack that is supposed to make the Imperials start with their weapon holstered- need a better way if ( self->client->ps.weapon == WP_NONE && !Q_strncmp( self->NPC_type, "imp", 3 ) && !(self->NPC->scriptFlags & SCF_FORCED_MARCH) ) @@ -534,14 +469,13 @@ void G_SetEnemy( gentity_t *self, gentity_t *enemy ) return; } - //Otherwise, just picking up another enemy + // Otherwise, just picking up another enemy - if ( event ) - { - G_AddVoiceEvent( self, event, 2000 ); + if (event) { + G_AddVoiceEvent(self, event, 2000); } - //Take the enemy + // Take the enemy G_ClearEnemy(self); self->enemy = enemy; } @@ -591,10 +525,8 @@ int ChooseBestWeapon( void ) } */ -void ChangeWeapon( gentity_t *ent, int newWeapon ) -{ - if ( !ent || !ent->client || !ent->NPC ) - { +void ChangeWeapon(gentity_t *ent, int newWeapon) { + if (!ent || !ent->client || !ent->NPC) { return; } @@ -605,11 +537,10 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) ent->NPC->attackHold = 0; ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[newWeapon].ammoIndex]; - switch ( newWeapon ) - { - case WP_BRYAR_PISTOL://prifle + switch (newWeapon) { + case WP_BRYAR_PISTOL: // prifle ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; /* @@ -624,7 +555,7 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) ent->NPC->burstSpacing = 500;//attack debounce break; */ - //rwwFIXMEFIXME: support WP_BLASTER_PISTOL and WP_BOT_LASER + // rwwFIXMEFIXME: support WP_BLASTER_PISTOL and WP_BOT_LASER /* case WP_BOT_LASER://probe attack @@ -641,144 +572,131 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) case WP_SABER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 0;//attackdebounce + ent->NPC->burstSpacing = 0; // attackdebounce break; case WP_DISRUPTOR: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - switch( g_npcspskill.integer ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + switch (g_npcspskill.integer) { case 0: - ent->NPC->burstSpacing = 2500;//attackdebounce + ent->NPC->burstSpacing = 2500; // attackdebounce break; case 1: - ent->NPC->burstSpacing = 2000;//attackdebounce + ent->NPC->burstSpacing = 2000; // attackdebounce break; case 2: - ent->NPC->burstSpacing = 1500;//attackdebounce + ent->NPC->burstSpacing = 1500; // attackdebounce break; } - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_BOWCASTER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 1000;//attackdebounce - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce + ent->NPC->burstSpacing = 500; // attack debounce break; case WP_REPEATER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; ent->NPC->burstMean = 6; ent->NPC->burstMax = 10; - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce + ent->NPC->burstSpacing = 500; // attack debounce } break; case WP_DEMP2: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; case WP_FLECHETTE: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { - ent->NPC->burstSpacing = 2000;//attackdebounce - } - else - { - ent->NPC->burstSpacing = 1000;//attackdebounce + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { + ent->NPC->burstSpacing = 2000; // attackdebounce + } else { + ent->NPC->burstSpacing = 1000; // attackdebounce } break; case WP_ROCKET_LAUNCHER: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 2500;//attackdebounce - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 2500;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 2000;//attack debounce + // ent->NPC->burstSpacing = 2500;//attackdebounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 2500; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 2000; // attack debounce else - ent->NPC->burstSpacing = 1500;//attack debounce + ent->NPC->burstSpacing = 1500; // attack debounce break; case WP_THERMAL: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - // ent->NPC->burstSpacing = 3000;//attackdebounce - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 3000;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 2500;//attack debounce + // ent->NPC->burstSpacing = 3000;//attackdebounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 3000; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 2500; // attack debounce else - ent->NPC->burstSpacing = 2000;//attack debounce + ent->NPC->burstSpacing = 2000; // attack debounce break; - /* - case WP_SABER: - ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; - ent->NPC->burstMin = 5;//0.5 sec - ent->NPC->burstMean = 10;//1 second - ent->NPC->burstMax = 20;//3 seconds - ent->NPC->burstSpacing = 2000;//2 seconds - ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst - break; - */ + /* + case WP_SABER: + ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; + ent->NPC->burstMin = 5;//0.5 sec + ent->NPC->burstMean = 10;//1 second + ent->NPC->burstMax = 20;//3 seconds + ent->NPC->burstSpacing = 2000;//2 seconds + ent->NPC->attackHold = 1000;//Hold attack button for a 1-second burst + break; + */ case WP_BLASTER: - if ( ent->NPC->scriptFlags & SCF_ALT_FIRE ) - { + if (ent->NPC->scriptFlags & SCF_ALT_FIRE) { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 3; ent->NPC->burstMean = 3; ent->NPC->burstMax = 3; - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 1500;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 1000;//attack debounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 1500; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 1000; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce - } - else - { + ent->NPC->burstSpacing = 500; // attack debounce + } else { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - if ( g_npcspskill.integer == 0 ) - ent->NPC->burstSpacing = 1000;//attack debounce - else if ( g_npcspskill.integer == 1 ) - ent->NPC->burstSpacing = 750;//attack debounce + if (g_npcspskill.integer == 0) + ent->NPC->burstSpacing = 1000; // attack debounce + else if (g_npcspskill.integer == 1) + ent->NPC->burstSpacing = 750; // attack debounce else - ent->NPC->burstSpacing = 500;//attack debounce - // ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 500; // attack debounce + // ent->NPC->burstSpacing = 1000;//attackdebounce } break; case WP_STUN_BATON: ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attackdebounce + ent->NPC->burstSpacing = 1000; // attackdebounce break; /* @@ -794,58 +712,43 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) ent->NPC->burstSpacing = 500;//attack debounce break; */ - //rwwFIXMEFIXME: support for atst weaps + // rwwFIXMEFIXME: support for atst weaps case WP_EMPLACED_GUN: - //FIXME: give some designer-control over this? - if ( ent->client && ent->client->NPC_class == CLASS_REELO ) - { + // FIXME: give some designer-control over this? + if (ent->client && ent->client->NPC_class == CLASS_REELO) { ent->NPC->aiFlags &= ~NPCAI_BURST_WEAPON; - ent->NPC->burstSpacing = 1000;//attack debounce - // if ( g_npcspskill.integer == 0 ) - // ent->NPC->burstSpacing = 300;//attack debounce - // else if ( g_npcspskill.integer == 1 ) - // ent->NPC->burstSpacing = 200;//attack debounce - // else - // ent->NPC->burstSpacing = 100;//attack debounce - } - else - { + ent->NPC->burstSpacing = 1000; // attack debounce + // if ( g_npcspskill.integer == 0 ) + // ent->NPC->burstSpacing = 300;//attack debounce + // else if ( g_npcspskill.integer == 1 ) + // ent->NPC->burstSpacing = 200;//attack debounce + // else + // ent->NPC->burstSpacing = 100;//attack debounce + } else { ent->NPC->aiFlags |= NPCAI_BURST_WEAPON; ent->NPC->burstMin = 2; // 3 shots, really ent->NPC->burstMean = 2; ent->NPC->burstMax = 2; - if ( ent->parent ) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. + if (ent->parent) // if we have an owner, it should be the chair at this point...so query the chair for its shot debounce times, etc. { - if ( g_npcspskill.integer == 0 ) - { - ent->NPC->burstSpacing = ent->parent->wait + 400;//attack debounce - ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots + if (g_npcspskill.integer == 0) { + ent->NPC->burstSpacing = ent->parent->wait + 400; // attack debounce + ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots + } else if (g_npcspskill.integer == 1) { + ent->NPC->burstSpacing = ent->parent->wait + 200; // attack debounce + } else { + ent->NPC->burstSpacing = ent->parent->wait; // attack debounce } - else if ( g_npcspskill.integer == 1 ) - { - ent->NPC->burstSpacing = ent->parent->wait + 200;//attack debounce - } - else - { - ent->NPC->burstSpacing = ent->parent->wait;//attack debounce - } - } - else - { - if ( g_npcspskill.integer == 0 ) - { - ent->NPC->burstSpacing = 1200;//attack debounce + } else { + if (g_npcspskill.integer == 0) { + ent->NPC->burstSpacing = 1200; // attack debounce ent->NPC->burstMin = ent->NPC->burstMax = 1; // two shots - } - else if ( g_npcspskill.integer == 1 ) - { - ent->NPC->burstSpacing = 1000;//attack debounce - } - else - { - ent->NPC->burstSpacing = 800;//attack debounce + } else if (g_npcspskill.integer == 1) { + ent->NPC->burstSpacing = 1000; // attack debounce + } else { + ent->NPC->burstSpacing = 800; // attack debounce } } } @@ -857,8 +760,7 @@ void ChangeWeapon( gentity_t *ent, int newWeapon ) } } -void NPC_ChangeWeapon( int newWeapon ) -{ +void NPC_ChangeWeapon(int newWeapon) { /* qboolean changing = qfalse; if ( newWeapon != NPC->client->ps.weapon ) @@ -885,22 +787,19 @@ void NPC_ChangeWeapon( int newWeapon ) G_CreateG2AttachedWeaponModel( NPC, weaponData[NPC->client->ps.weapon].weaponMdl, NPC->handRBolt, 0 ); } }*/ - //rwwFIXMEFIXME: Change the same way as players, all this stuff is just crazy. + // rwwFIXMEFIXME: Change the same way as players, all this stuff is just crazy. } /* void NPC_ApplyWeaponFireDelay(void) How long, if at all, in msec the actual fire should delay from the time the attack was started */ -void NPC_ApplyWeaponFireDelay(void) -{ - if ( NPCS.NPC->attackDebounceTime > level.time ) - {//Just fired, if attacking again, must be a burst fire, so don't add delay - //NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! +void NPC_ApplyWeaponFireDelay(void) { + if (NPCS.NPC->attackDebounceTime > level.time) { // Just fired, if attacking again, must be a burst fire, so don't add delay + // NOTE: Borg AI uses attackDebounceTime "incorrectly", so this will always return for them! return; } - switch(NPCS.client->ps.weapon) - { + switch (NPCS.client->ps.weapon) { /* case WP_BOT_LASER: NPCInfo->burstCount = 0; @@ -909,9 +808,8 @@ void NPC_ApplyWeaponFireDelay(void) */ //rwwFIXMEFIXME: support for this case WP_THERMAL: - if ( NPCS.client->ps.clientNum ) - {//NPCs delay... - //FIXME: player should, too, but would feel weird in 1st person, even though it + if (NPCS.client->ps.clientNum) { // NPCs delay... + // FIXME: player should, too, but would feel weird in 1st person, even though it // would look right in 3rd person. Really should have a wind-up anim // for player as he holds down the fire button to throw, then play // the actual throw when he lets go... @@ -920,9 +818,9 @@ void NPC_ApplyWeaponFireDelay(void) break; case WP_STUN_BATON: - //if ( !PM_DroidMelee( client->NPC_class ) ) - if (1) //rwwFIXMEFIXME: ... - {//FIXME: should be unique per melee anim + // if ( !PM_DroidMelee( client->NPC_class ) ) + if (1) // rwwFIXMEFIXME: ... + { // FIXME: should be unique per melee anim NPCS.client->ps.weaponTime = 300; } break; @@ -938,38 +836,34 @@ void NPC_ApplyWeaponFireDelay(void) ShootThink ------------------------- */ -void ShootThink( void ) -{ - int delay; +void ShootThink(void) { + int delay; NPCS.ucmd.buttons &= ~BUTTON_ATTACK; -/* - if ( enemyVisibility != VIS_SHOOT) - return; -*/ + /* + if ( enemyVisibility != VIS_SHOOT) + return; + */ - if ( NPCS.client->ps.weapon == WP_NONE ) + if (NPCS.client->ps.weapon == WP_NONE) return; - if ( NPCS.client->ps.weaponstate != WEAPON_READY && NPCS.client->ps.weaponstate != WEAPON_FIRING && NPCS.client->ps.weaponstate != WEAPON_IDLE) + if (NPCS.client->ps.weaponstate != WEAPON_READY && NPCS.client->ps.weaponstate != WEAPON_FIRING && NPCS.client->ps.weaponstate != WEAPON_IDLE) return; - if ( level.time < NPCS.NPCInfo->shotTime ) - { + if (level.time < NPCS.NPCInfo->shotTime) { return; } NPCS.ucmd.buttons |= BUTTON_ATTACK; - NPCS.NPCInfo->currentAmmo = NPCS.client->ps.ammo[weaponData[NPCS.client->ps.weapon].ammoIndex]; // checkme + NPCS.NPCInfo->currentAmmo = NPCS.client->ps.ammo[weaponData[NPCS.client->ps.weapon].ammoIndex]; // checkme NPC_ApplyWeaponFireDelay(); - if ( NPCS.NPCInfo->aiFlags & NPCAI_BURST_WEAPON ) - { - if ( !NPCS.NPCInfo->burstCount ) - { - NPCS.NPCInfo->burstCount = Q_irand( NPCS.NPCInfo->burstMin, NPCS.NPCInfo->burstMax ); + if (NPCS.NPCInfo->aiFlags & NPCAI_BURST_WEAPON) { + if (!NPCS.NPCInfo->burstCount) { + NPCS.NPCInfo->burstCount = Q_irand(NPCS.NPCInfo->burstMin, NPCS.NPCInfo->burstMax); /* NPCInfo->burstCount = erandom( NPCInfo->burstMean ); if ( NPCInfo->burstCount < NPCInfo->burstMin ) @@ -982,60 +876,39 @@ void ShootThink( void ) } */ delay = 0; - } - else - { + } else { NPCS.NPCInfo->burstCount--; - if ( NPCS.NPCInfo->burstCount == 0 ) - { + if (NPCS.NPCInfo->burstCount == 0) { delay = NPCS.NPCInfo->burstSpacing; - } - else - { + } else { delay = 0; } } - if ( !delay ) - { + if (!delay) { // HACK: dirty little emplaced bits, but is done because it would otherwise require some sort of new variable... - if ( NPCS.client->ps.weapon == WP_EMPLACED_GUN ) - { - if ( NPCS.NPC->parent ) // try and get the debounce values from the chair if we can + if (NPCS.client->ps.weapon == WP_EMPLACED_GUN) { + if (NPCS.NPC->parent) // try and get the debounce values from the chair if we can { - if ( g_npcspskill.integer == 0 ) - { + if (g_npcspskill.integer == 0) { delay = NPCS.NPC->parent->random + 150; - } - else if ( g_npcspskill.integer == 1 ) - { + } else if (g_npcspskill.integer == 1) { delay = NPCS.NPC->parent->random + 100; - } - else - { + } else { delay = NPCS.NPC->parent->random; } - } - else - { - if ( g_npcspskill.integer == 0 ) - { + } else { + if (g_npcspskill.integer == 0) { delay = 350; - } - else if ( g_npcspskill.integer == 1 ) - { + } else if (g_npcspskill.integer == 1) { delay = 300; - } - else - { + } else { delay = 200; } } } } - } - else - { + } else { delay = NPCS.NPCInfo->burstSpacing; } @@ -1049,22 +922,20 @@ FIXME makes this so there's a delay from event that caused us to check to actual Added: hacks for Borg */ -void WeaponThink( qboolean inCombat ) -{ +void WeaponThink(qboolean inCombat) { - if ( NPCS.client->ps.weaponstate == WEAPON_RAISING || NPCS.client->ps.weaponstate == WEAPON_DROPPING ) - { + if (NPCS.client->ps.weaponstate == WEAPON_RAISING || NPCS.client->ps.weaponstate == WEAPON_DROPPING) { NPCS.ucmd.weapon = NPCS.client->ps.weapon; NPCS.ucmd.buttons &= ~BUTTON_ATTACK; return; } -//MCG - Begin - //For now, no-one runs out of ammo - if(NPCS.NPC->client->ps.ammo[ weaponData[NPCS.client->ps.weapon].ammoIndex ] < 10) // checkme -// if(NPC->client->ps.ammo[ client->ps.weapon ] < 10) + // MCG - Begin + // For now, no-one runs out of ammo + if (NPCS.NPC->client->ps.ammo[weaponData[NPCS.client->ps.weapon].ammoIndex] < 10) // checkme + // if(NPC->client->ps.ammo[ client->ps.weapon ] < 10) { - Add_Ammo (NPCS.NPC, NPCS.client->ps.weapon, 100); + Add_Ammo(NPCS.NPC, NPCS.client->ps.weapon, 100); } NPCS.ucmd.weapon = NPCS.client->ps.weapon; @@ -1075,33 +946,24 @@ void WeaponThink( qboolean inCombat ) HaveWeapon */ -qboolean HaveWeapon( int weapon ) -{ - return ( NPCS.client->ps.stats[STAT_WEAPONS] & ( 1 << weapon ) ); -} +qboolean HaveWeapon(int weapon) { return (NPCS.client->ps.stats[STAT_WEAPONS] & (1 << weapon)); } -qboolean EntIsGlass (gentity_t *check) -{ - if(check->classname && - !Q_stricmp("func_breakable", check->classname) && - check->count == 1 && check->health <= 100) - { +qboolean EntIsGlass(gentity_t *check) { + if (check->classname && !Q_stricmp("func_breakable", check->classname) && check->count == 1 && check->health <= 100) { return qtrue; } return qfalse; } -qboolean ShotThroughGlass (trace_t *tr, gentity_t *target, vec3_t spot, int mask) -{ - gentity_t *hit = &g_entities[ tr->entityNum ]; - if(hit != target && EntIsGlass(hit)) - {//ok to shoot through breakable glass - int skip = hit->s.number; - vec3_t muzzle; +qboolean ShotThroughGlass(trace_t *tr, gentity_t *target, vec3_t spot, int mask) { + gentity_t *hit = &g_entities[tr->entityNum]; + if (hit != target && EntIsGlass(hit)) { // ok to shoot through breakable glass + int skip = hit->s.number; + vec3_t muzzle; VectorCopy(tr->endpos, muzzle); - trap->Trace (tr, muzzle, NULL, NULL, spot, skip, mask, qfalse, 0, 0 ); + trap->Trace(tr, muzzle, NULL, NULL, spot, skip, mask, qfalse, 0, 0); return qtrue; } @@ -1116,72 +978,62 @@ this function does not check teams, invulnerability, notarget, etc.... Added: If can't shoot center, try head, if not, see if it's close enough to try anyway. */ -qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) -{ - trace_t tr; - vec3_t muzzle; - vec3_t spot, diff; - gentity_t *traceEnt; +qboolean CanShoot(gentity_t *ent, gentity_t *shooter) { + trace_t tr; + vec3_t muzzle; + vec3_t spot, diff; + gentity_t *traceEnt; - CalcEntitySpot( shooter, SPOT_WEAPON, muzzle ); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); //FIXME preferred target locations for some weapons (feet for R/L) + CalcEntitySpot(shooter, SPOT_WEAPON, muzzle); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); // FIXME preferred target locations for some weapons (feet for R/L) - trap->Trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, qfalse, 0, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; + trap->Trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, qfalse, 0, 0); + traceEnt = &g_entities[tr.entityNum]; // point blank, baby! - if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer) ) - { + if (tr.startsolid && (shooter->NPC) && (shooter->NPC->touchedByPlayer)) { traceEnt = shooter->NPC->touchedByPlayer; } - if ( ShotThroughGlass( &tr, ent, spot, MASK_SHOT ) ) - { - traceEnt = &g_entities[ tr.entityNum ]; + if (ShotThroughGlass(&tr, ent, spot, MASK_SHOT)) { + traceEnt = &g_entities[tr.entityNum]; } // shot is dead on - if ( traceEnt == ent ) - { + if (traceEnt == ent) { return qtrue; } -//MCG - Begin - else - {//ok, can't hit them in center, try their head - CalcEntitySpot( ent, SPOT_HEAD, spot ); - trap->Trace ( &tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, qfalse, 0, 0 ); - traceEnt = &g_entities[ tr.entityNum ]; - if ( traceEnt == ent) - { + // MCG - Begin + else { // ok, can't hit them in center, try their head + CalcEntitySpot(ent, SPOT_HEAD, spot); + trap->Trace(&tr, muzzle, NULL, NULL, spot, shooter->s.number, MASK_SHOT, qfalse, 0, 0); + traceEnt = &g_entities[tr.entityNum]; + if (traceEnt == ent) { return qtrue; } } - //Actually, we should just check to fire in dir we're facing and if it's close enough, - //and we didn't hit someone on our own team, shoot + // Actually, we should just check to fire in dir we're facing and if it's close enough, + // and we didn't hit someone on our own team, shoot VectorSubtract(spot, tr.endpos, diff); - if(VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) - { + if (VectorLength(diff) < Q_flrand(0.0f, 1.0f) * 32) { return qtrue; } -//MCG - End - // shot would hit a non-client - if ( !traceEnt->client ) - { + // MCG - End + // shot would hit a non-client + if (!traceEnt->client) { return qfalse; } // shot is blocked by another player // he's already dead, so go ahead - if ( traceEnt->health <= 0 ) - { + if (traceEnt->health <= 0) { return qtrue; } // don't deliberately shoot a teammate - if ( traceEnt->client && ( traceEnt->client->playerTeam == shooter->client->playerTeam ) ) - { + if (traceEnt->client && (traceEnt->client->playerTeam == shooter->client->playerTeam)) { return qfalse; } @@ -1189,63 +1041,52 @@ qboolean CanShoot ( gentity_t *ent, gentity_t *shooter ) return qtrue; } - /* void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) Added: hacks for scripted NPCs */ -void NPC_CheckPossibleEnemy( gentity_t *other, visibility_t vis ) -{ +void NPC_CheckPossibleEnemy(gentity_t *other, visibility_t vis) { // is he is already our enemy? - if ( other == NPCS.NPC->enemy ) + if (other == NPCS.NPC->enemy) return; - if ( other->flags & FL_NOTARGET ) + if (other->flags & FL_NOTARGET) return; // we already have an enemy and this guy is in our FOV, see if this guy would be better - if ( NPCS.NPC->enemy && vis == VIS_FOV ) - { - if ( NPCS.NPCInfo->enemyLastSeenTime - level.time < 2000 ) - { + if (NPCS.NPC->enemy && vis == VIS_FOV) { + if (NPCS.NPCInfo->enemyLastSeenTime - level.time < 2000) { return; } - if ( NPCS.enemyVisibility == VIS_UNKNOWN ) - { - NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_360|CHECK_FOV ); + if (NPCS.enemyVisibility == VIS_UNKNOWN) { + NPCS.enemyVisibility = NPC_CheckVisibility(NPCS.NPC->enemy, CHECK_360 | CHECK_FOV); } - if ( NPCS.enemyVisibility == VIS_FOV ) - { + if (NPCS.enemyVisibility == VIS_FOV) { return; } } - if ( !NPCS.NPC->enemy ) - {//only take an enemy if you don't have one yet - G_SetEnemy( NPCS.NPC, other ); + if (!NPCS.NPC->enemy) { // only take an enemy if you don't have one yet + G_SetEnemy(NPCS.NPC, other); } - if ( vis == VIS_FOV ) - { + if (vis == VIS_FOV) { NPCS.NPCInfo->enemyLastSeenTime = level.time; - VectorCopy( other->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation ); + VectorCopy(other->r.currentOrigin, NPCS.NPCInfo->enemyLastSeenLocation); NPCS.NPCInfo->enemyLastHeardTime = 0; - VectorClear( NPCS.NPCInfo->enemyLastHeardLocation ); - } - else - { + VectorClear(NPCS.NPCInfo->enemyLastHeardLocation); + } else { NPCS.NPCInfo->enemyLastSeenTime = 0; - VectorClear( NPCS.NPCInfo->enemyLastSeenLocation ); + VectorClear(NPCS.NPCInfo->enemyLastSeenLocation); NPCS.NPCInfo->enemyLastHeardTime = level.time; - VectorCopy( other->r.currentOrigin, NPCS.NPCInfo->enemyLastHeardLocation ); + VectorCopy(other->r.currentOrigin, NPCS.NPCInfo->enemyLastHeardLocation); } } - //========================================== -//MCG Added functions: +// MCG Added functions: //========================================== /* @@ -1255,23 +1096,21 @@ DOES NOT control how fast you can fire Only makes you keep your weapon up after you fire */ -int NPC_AttackDebounceForWeapon (void) -{ - switch ( NPCS.NPC->client->ps.weapon ) - { -/* - case WP_BLASTER://scav rifle - return 1000; - break; +int NPC_AttackDebounceForWeapon(void) { + switch (NPCS.NPC->client->ps.weapon) { + /* + case WP_BLASTER://scav rifle + return 1000; + break; - case WP_BRYAR_PISTOL://prifle - return 3000; - break; + case WP_BRYAR_PISTOL://prifle + return 3000; + break; - case WP_SABER: - return 100; - break; -*/ + case WP_SABER: + return 100; + break; + */ case WP_SABER: return 0; break; @@ -1288,28 +1127,25 @@ int NPC_AttackDebounceForWeapon (void) return 1000; break; */ - //rwwFIXMEFIXME: support + // rwwFIXMEFIXME: support default: - return NPCS.NPCInfo->burstSpacing;//was 100 by default + return NPCS.NPCInfo->burstSpacing; // was 100 by default break; } } -//FIXME: need a mindist for explosive weapons -float NPC_MaxDistSquaredForWeapon (void) -{ - if(NPCS.NPCInfo->stats.shootDistance > 0) - {//overrides default weapon dist +// FIXME: need a mindist for explosive weapons +float NPC_MaxDistSquaredForWeapon(void) { + if (NPCS.NPCInfo->stats.shootDistance > 0) { // overrides default weapon dist return NPCS.NPCInfo->stats.shootDistance * NPCS.NPCInfo->stats.shootDistance; } - switch ( NPCS.NPC->s.weapon ) - { - case WP_BLASTER://scav rifle - return 1024 * 1024;//should be shorter? + switch (NPCS.NPC->s.weapon) { + case WP_BLASTER: // scav rifle + return 1024 * 1024; // should be shorter? break; - case WP_BRYAR_PISTOL://prifle + case WP_BRYAR_PISTOL: // prifle return 1024 * 1024; break; @@ -1319,34 +1155,29 @@ float NPC_MaxDistSquaredForWeapon (void) break; */ - case WP_DISRUPTOR://disruptor - if ( NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE ) - { - return ( 4096 * 4096 ); - } - else - { + case WP_DISRUPTOR: // disruptor + if (NPCS.NPCInfo->scriptFlags & SCF_ALT_FIRE) { + return (4096 * 4096); + } else { return 1024 * 1024; } break; -/* - case WP_SABER: - return 1024 * 1024; - break; -*/ + /* + case WP_SABER: + return 1024 * 1024; + break; + */ case WP_SABER: - if ( NPCS.NPC->client && NPCS.NPC->client->saber[0].blade[0].lengthMax ) - {//FIXME: account for whether enemy and I are heading towards each other! - return (NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0]*1.5)*(NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0]*1.5); - } - else - { - return 48*48; + if (NPCS.NPC->client && NPCS.NPC->client->saber[0].blade[0].lengthMax) { // FIXME: account for whether enemy and I are heading towards each other! + return (NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0] * 1.5) * + (NPCS.NPC->client->saber[0].blade[0].lengthMax + NPCS.NPC->r.maxs[0] * 1.5); + } else { + return 48 * 48; } break; default: - return 1024 * 1024;//was 0 + return 1024 * 1024; // was 0 break; } } @@ -1357,63 +1188,41 @@ ValidEnemy ------------------------- */ -qboolean ValidEnemy(gentity_t *ent) -{ +qboolean ValidEnemy(gentity_t *ent) { - if ( ent == NULL ) + if (ent == NULL) return qfalse; - if ( ent == NPCS.NPC ) + if (ent == NPCS.NPC) return qfalse; - //if team_free, maybe everyone is an enemy? - //if ( !NPC->client->enemyTeam ) + // if team_free, maybe everyone is an enemy? + // if ( !NPC->client->enemyTeam ) // return qfalse; - if ( !(ent->flags & FL_NOTARGET) ) - { - if( ent->health > 0 ) - { - if( !ent->client ) - { + if (!(ent->flags & FL_NOTARGET)) { + if (ent->health > 0) { + if (!ent->client) { return qtrue; - } - else if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) - {//don't go after spectators + } else if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { // don't go after spectators return qfalse; - } - else if ( ent->client->tempSpectate >= level.time ) - {//don't go after spectators + } else if (ent->client->tempSpectate >= level.time) { // don't go after spectators return qfalse; - } - else - { + } else { int entTeam = TEAM_FREE; - if ( ent->NPC && ent->client ) - { + if (ent->NPC && ent->client) { entTeam = ent->client->playerTeam; - } - else if ( ent->client ) - { - if ( ent->client->sess.sessionTeam == TEAM_BLUE ) - { + } else if (ent->client) { + if (ent->client->sess.sessionTeam == TEAM_BLUE) { entTeam = NPCTEAM_PLAYER; - } - else if ( ent->client->sess.sessionTeam == TEAM_RED ) - { + } else if (ent->client->sess.sessionTeam == TEAM_RED) { entTeam = NPCTEAM_ENEMY; - } - else - { + } else { entTeam = NPCTEAM_NEUTRAL; } } - if( entTeam == NPCTEAM_FREE - || NPCS.NPC->client->enemyTeam == NPCTEAM_FREE - || entTeam == NPCS.NPC->client->enemyTeam ) - { - if ( entTeam != NPCS.NPC->client->playerTeam ) - { + if (entTeam == NPCTEAM_FREE || NPCS.NPC->client->enemyTeam == NPCTEAM_FREE || entTeam == NPCS.NPC->client->enemyTeam) { + if (entTeam != NPCS.NPC->client->playerTeam) { return qtrue; } } @@ -1424,26 +1233,21 @@ qboolean ValidEnemy(gentity_t *ent) return qfalse; } -qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) -{ - vec3_t vec; +qboolean NPC_EnemyTooFar(gentity_t *enemy, float dist, qboolean toShoot) { + vec3_t vec; - if ( !toShoot ) - {//Not trying to actually press fire button with this check - if ( NPCS.NPC->client->ps.weapon == WP_SABER ) - {//Just have to get to him + if (!toShoot) { // Not trying to actually press fire button with this check + if (NPCS.NPC->client->ps.weapon == WP_SABER) { // Just have to get to him return qfalse; } } - - if(!dist) - { + if (!dist) { VectorSubtract(NPCS.NPC->r.currentOrigin, enemy->r.currentOrigin, vec); dist = VectorLengthSquared(vec); } - if(dist > NPC_MaxDistSquaredForWeapon()) + if (dist > NPC_MaxDistSquaredForWeapon()) return qtrue; return qfalse; @@ -1466,133 +1270,97 @@ You can mix and match any of those options (example: find closest visible player FIXME: this should go through the snapshot and find the closest enemy */ -gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest ) -{ - int num_choices = 0; - int choice[128];//FIXME: need a different way to determine how many choices? - gentity_t *newenemy = NULL; - gentity_t *closestEnemy = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = Q3_INFINITE; - qboolean failed = qfalse; - int visChecks = (CHECK_360|CHECK_FOV|CHECK_VISRANGE); - int minVis = VIS_FOV; - - if ( enemyTeam == NPCTEAM_NEUTRAL ) - { +gentity_t *NPC_PickEnemy(gentity_t *closestTo, int enemyTeam, qboolean checkVis, qboolean findPlayersFirst, qboolean findClosest) { + int num_choices = 0; + int choice[128]; // FIXME: need a different way to determine how many choices? + gentity_t *newenemy = NULL; + gentity_t *closestEnemy = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = Q3_INFINITE; + qboolean failed = qfalse; + int visChecks = (CHECK_360 | CHECK_FOV | CHECK_VISRANGE); + int minVis = VIS_FOV; + + if (enemyTeam == NPCTEAM_NEUTRAL) { return NULL; } - if ( NPCS.NPCInfo->behaviorState == BS_STAND_AND_SHOOT || - NPCS.NPCInfo->behaviorState == BS_HUNT_AND_KILL ) - {//Formations guys don't require inFov to pick up a target - //These other behavior states are active battle states and should not - //use FOV. FOV checks are for enemies who are patrolling, guarding, etc. + if (NPCS.NPCInfo->behaviorState == BS_STAND_AND_SHOOT || + NPCS.NPCInfo->behaviorState == BS_HUNT_AND_KILL) { // Formations guys don't require inFov to pick up a target + // These other behavior states are active battle states and should not + // use FOV. FOV checks are for enemies who are patrolling, guarding, etc. visChecks &= ~CHECK_FOV; minVis = VIS_360; } - //OJKFIXME: care about clients other than 0 - //OJKFIXME: choice[] is not size checked? - if( findPlayersFirst ) - {//try to find a player first + // OJKFIXME: care about clients other than 0 + // OJKFIXME: choice[] is not size checked? + if (findPlayersFirst) { // try to find a player first newenemy = &g_entities[0]; - if( newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if( newenemy->health > 0 ) - { - if( NPC_ValidEnemy( newenemy) )//enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || ( enemyTeam == TEAM_PLAYER ) ) - {//FIXME: check for range and FOV or vis? - if( newenemy != NPCS.NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if ( trap->InPVS(newenemy->r.currentOrigin, NPCS.NPC->r.currentOrigin) ) - { - if(NPCS.NPCInfo->behaviorState == BS_INVESTIGATE || NPCS.NPCInfo->behaviorState == BS_PATROL) - { - if(!NPCS.NPC->enemy) - { - if(!InVisrange(newenemy)) - { + if (newenemy->client && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if (NPC_ValidEnemy(newenemy)) // enemyTeam == TEAM_PLAYER || newenemy->client->playerTeam == enemyTeam || ( enemyTeam == TEAM_PLAYER ) ) + { // FIXME: check for range and FOV or vis? + if (newenemy != NPCS.NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (trap->InPVS(newenemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { + if (NPCS.NPCInfo->behaviorState == BS_INVESTIGATE || NPCS.NPCInfo->behaviorState == BS_PATROL) { + if (!NPCS.NPC->enemy) { + if (!InVisrange(newenemy)) { failed = qtrue; - } - else if(NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { failed = qtrue; } } } - if ( !failed ) - { - VectorSubtract( closestTo->r.currentOrigin, newenemy->r.currentOrigin, diff ); + if (!failed) { + VectorSubtract(closestTo->r.currentOrigin, newenemy->r.currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them failed = qtrue; + } else { + Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPCS.NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPCS.NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { failed = qtrue; } - } - else - { - Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPCS.NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPCS.NPC->targetname, + newenemy->targetname, newenemy->client->hiddenDist); } } - if(!failed) - { - if(findClosest) - { - if(relDist < bestDist) - { - if(!NPC_EnemyTooFar(newenemy, relDist, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (!failed) { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if(!NPC_EnemyTooFar(newenemy, 0, qfalse)) - { - if(checkVis) - { - if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) == VIS_FOV) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1605,14 +1373,12 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - if (findClosest && closestEnemy) - { + if (findClosest && closestEnemy) { return closestEnemy; } - if (num_choices) - { - return &g_entities[ choice[rand() % num_choices] ]; + if (num_choices) { + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1627,117 +1393,84 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis bestDist = Q3_INFINITE; closestEnemy = NULL; - for ( entNum = 0; entNum < level.num_entities; entNum++ ) - { + for (entNum = 0; entNum < level.num_entities; entNum++) { newenemy = &g_entities[entNum]; - if ( newenemy != NPCS.NPC && (newenemy->client /*|| newenemy->svFlags & SVF_NONNPC_ENEMY*/) && !(newenemy->flags & FL_NOTARGET) && !(newenemy->s.eFlags & EF_NODRAW)) - { - if ( newenemy->health > 0 ) - { - if ( (newenemy->client && NPC_ValidEnemy( newenemy)) - || (!newenemy->client && newenemy->alliedTeam == enemyTeam) ) - {//FIXME: check for range and FOV or vis? - if ( NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER && enemyTeam == NPCTEAM_PLAYER ) - {//player allies turning on ourselves? How? - if ( newenemy->s.number >= MAX_CLIENTS ) - {//only turn on the player, not other player allies + if (newenemy != NPCS.NPC && (newenemy->client /*|| newenemy->svFlags & SVF_NONNPC_ENEMY*/) && !(newenemy->flags & FL_NOTARGET) && + !(newenemy->s.eFlags & EF_NODRAW)) { + if (newenemy->health > 0) { + if ((newenemy->client && NPC_ValidEnemy(newenemy)) || + (!newenemy->client && newenemy->alliedTeam == enemyTeam)) { // FIXME: check for range and FOV or vis? + if (NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER && enemyTeam == NPCTEAM_PLAYER) { // player allies turning on ourselves? How? + if (newenemy->s.number >= MAX_CLIENTS) { // only turn on the player, not other player allies continue; } } - if ( newenemy != NPCS.NPC->lastEnemy ) - {//Make sure we're not just going back and forth here - if(!trap->InPVS(newenemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) - { + if (newenemy != NPCS.NPC->lastEnemy) { // Make sure we're not just going back and forth here + if (!trap->InPVS(newenemy->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { continue; } - if ( NPCS.NPCInfo->behaviorState == BS_INVESTIGATE || NPCS.NPCInfo->behaviorState == BS_PATROL ) - { - if ( !NPCS.NPC->enemy ) - { - if ( !InVisrange( newenemy ) ) - { + if (NPCS.NPCInfo->behaviorState == BS_INVESTIGATE || NPCS.NPCInfo->behaviorState == BS_PATROL) { + if (!NPCS.NPC->enemy) { + if (!InVisrange(newenemy)) { continue; - } - else if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) != VIS_FOV ) - { + } else if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_FOV | CHECK_VISRANGE) != VIS_FOV) { continue; } } } - VectorSubtract( closestTo->r.currentOrigin, newenemy->r.currentOrigin, diff ); + VectorSubtract(closestTo->r.currentOrigin, newenemy->r.currentOrigin, diff); relDist = VectorLengthSquared(diff); - if ( newenemy->client && newenemy->client->hiddenDist > 0 ) - { - if( relDist > newenemy->client->hiddenDist*newenemy->client->hiddenDist ) - { - //out of hidden range - if ( VectorLengthSquared( newenemy->client->hiddenDir ) ) - {//They're only hidden from a certain direction, check - float dot; - - VectorNormalize( diff ); - dot = DotProduct( newenemy->client->hiddenDir, diff ); - if ( dot > 0.5 ) - {//I'm not looking in the right dir toward them to see them + if (newenemy->client && newenemy->client->hiddenDist > 0) { + if (relDist > newenemy->client->hiddenDist * newenemy->client->hiddenDist) { + // out of hidden range + if (VectorLengthSquared(newenemy->client->hiddenDir)) { // They're only hidden from a certain direction, check + float dot; + + VectorNormalize(diff); + dot = DotProduct(newenemy->client->hiddenDir, diff); + if (dot > 0.5) { // I'm not looking in the right dir toward them to see them continue; + } else { + Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", + NPCS.NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot); } - else - { - Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDir %s targetDir %s dot %f\n", NPCS.NPC->targetname, newenemy->targetname, vtos(newenemy->client->hiddenDir), vtos(diff), dot ); - } - } - else - { + } else { continue; } - } - else - { - Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPCS.NPC->targetname, newenemy->targetname, newenemy->client->hiddenDist ); + } else { + Debug_Printf(&d_npcai, DEBUG_LEVEL_INFO, "%s saw %s trying to hide - hiddenDist %f\n", NPCS.NPC->targetname, + newenemy->targetname, newenemy->client->hiddenDist); } } - if ( findClosest ) - { - if ( relDist < bestDist ) - { - if ( !NPC_EnemyTooFar( newenemy, relDist, qfalse ) ) - { - if ( checkVis ) - { - //FIXME: NPCs need to be able to pick up other NPCs behind them, - //but for now, commented out because it was picking up enemies it shouldn't - //if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - if ( NPC_CheckVisibility ( newenemy, visChecks ) == minVis ) - { + if (findClosest) { + if (relDist < bestDist) { + if (!NPC_EnemyTooFar(newenemy, relDist, qfalse)) { + if (checkVis) { + // FIXME: NPCs need to be able to pick up other NPCs behind them, + // but for now, commented out because it was picking up enemies it shouldn't + // if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) + if (NPC_CheckVisibility(newenemy, visChecks) == minVis) { bestDist = relDist; closestEnemy = newenemy; } - } - else - { + } else { bestDist = relDist; closestEnemy = newenemy; } } } - } - else if ( !NPC_EnemyTooFar( newenemy, 0, qfalse ) ) - { - if ( checkVis ) - { - //if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) - if ( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + } else if (!NPC_EnemyTooFar(newenemy, 0, qfalse)) { + if (checkVis) { + // if( NPC_CheckVisibility ( newenemy, CHECK_360|CHECK_FOV|CHECK_VISRANGE ) == VIS_FOV ) + if (NPC_CheckVisibility(newenemy, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { choice[num_choices++] = newenemy->s.number; } - } - else - { + } else { choice[num_choices++] = newenemy->s.number; } } @@ -1747,18 +1480,15 @@ gentity_t *NPC_PickEnemy( gentity_t *closestTo, int enemyTeam, qboolean checkVis } } - - if (findClosest) - {//FIXME: you can pick up an enemy around a corner this way. + if (findClosest) { // FIXME: you can pick up an enemy around a corner this way. return closestEnemy; } - if (!num_choices) - { + if (!num_choices) { return NULL; } - return &g_entities[ choice[rand() % num_choices] ]; + return &g_entities[choice[rand() % num_choices]]; } /* @@ -1767,84 +1497,69 @@ gentity_t *NPC_PickAlly ( void ) Simply returns closest visible ally */ -gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly ) -{ - gentity_t *ally = NULL; - gentity_t *closestAlly = NULL; - int entNum; - vec3_t diff; - float relDist; - float bestDist = range; - - for ( entNum = 0; entNum < level.num_entities; entNum++ ) - { +gentity_t *NPC_PickAlly(qboolean facingEachOther, float range, qboolean ignoreGroup, qboolean movingOnly) { + gentity_t *ally = NULL; + gentity_t *closestAlly = NULL; + int entNum; + vec3_t diff; + float relDist; + float bestDist = range; + + for (entNum = 0; entNum < level.num_entities; entNum++) { ally = &g_entities[entNum]; - if ( ally->client ) - { - if ( ally->health > 0 ) - { - if ( ally->client && ( ally->client->playerTeam == NPCS.NPC->client->playerTeam || - NPCS.NPC->client->playerTeam == NPCTEAM_ENEMY ) )// && ally->client->playerTeam == TEAM_DISGUISE ) ) ) - {//if on same team or if player is disguised as your team - if ( ignoreGroup ) - { - if ( ally == NPCS.NPC->client->leader ) - { - //reject + if (ally->client) { + if (ally->health > 0) { + if (ally->client && (ally->client->playerTeam == NPCS.NPC->client->playerTeam || + NPCS.NPC->client->playerTeam == NPCTEAM_ENEMY)) // && ally->client->playerTeam == TEAM_DISGUISE ) ) ) + { // if on same team or if player is disguised as your team + if (ignoreGroup) { + if (ally == NPCS.NPC->client->leader) { + // reject continue; } - if ( ally->client && ally->client->leader && ally->client->leader == NPCS.NPC ) - { - //reject + if (ally->client && ally->client->leader && ally->client->leader == NPCS.NPC) { + // reject continue; } } - if(!trap->InPVS(ally->r.currentOrigin, NPCS.NPC->r.currentOrigin)) - { + if (!trap->InPVS(ally->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { continue; } - if ( movingOnly && ally->client && NPCS.NPC->client ) - {//They have to be moving relative to each other - if ( !DistanceSquared( ally->client->ps.velocity, NPCS.NPC->client->ps.velocity ) ) - { + if (movingOnly && ally->client && NPCS.NPC->client) { // They have to be moving relative to each other + if (!DistanceSquared(ally->client->ps.velocity, NPCS.NPC->client->ps.velocity)) { continue; } } - VectorSubtract( NPCS.NPC->r.currentOrigin, ally->r.currentOrigin, diff ); - relDist = VectorNormalize( diff ); - if ( relDist < bestDist ) - { - if ( facingEachOther ) - { - vec3_t vf; - float dot; + VectorSubtract(NPCS.NPC->r.currentOrigin, ally->r.currentOrigin, diff); + relDist = VectorNormalize(diff); + if (relDist < bestDist) { + if (facingEachOther) { + vec3_t vf; + float dot; - AngleVectors( ally->client->ps.viewangles, vf, NULL, NULL ); + AngleVectors(ally->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot < 0.5 ) - {//Not facing in dir to me + if (dot < 0.5) { // Not facing in dir to me continue; } - //He's facing me, am I facing him? - AngleVectors( NPCS.NPC->client->ps.viewangles, vf, NULL, NULL ); + // He's facing me, am I facing him? + AngleVectors(NPCS.NPC->client->ps.viewangles, vf, NULL, NULL); VectorNormalize(vf); dot = DotProduct(diff, vf); - if ( dot > -0.5 ) - {//I'm not facing opposite of dir to me + if (dot > -0.5) { // I'm not facing opposite of dir to me continue; } - //I am facing him + // I am facing him } - if ( NPC_CheckVisibility ( ally, CHECK_360|CHECK_VISRANGE ) >= VIS_360 ) - { + if (NPC_CheckVisibility(ally, CHECK_360 | CHECK_VISRANGE) >= VIS_360) { bestDist = relDist; closestAlly = ally; } @@ -1854,48 +1569,43 @@ gentity_t *NPC_PickAlly ( qboolean facingEachOther, float range, qboolean ignore } } - return closestAlly; } -gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnemy ) -{ - qboolean forcefindNew = qfalse; - gentity_t *closestTo; - gentity_t *newEnemy = NULL; - //FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot - //someone we can't hit? Rather than hard-coded 10? +gentity_t *NPC_CheckEnemy(qboolean findNew, qboolean tooFarOk, qboolean setEnemy) { + qboolean forcefindNew = qfalse; + gentity_t *closestTo; + gentity_t *newEnemy = NULL; + // FIXME: have a "NPCInfo->persistance" we can set to determine how long to try to shoot + // someone we can't hit? Rather than hard-coded 10? - //FIXME they shouldn't recognize enemy's death instantly + // FIXME they shouldn't recognize enemy's death instantly - //TEMP FIX: - //if(NPC->enemy->client) + // TEMP FIX: + // if(NPC->enemy->client) //{ // NPC->enemy->health = NPC->enemy->client->ps.stats[STAT_HEALTH]; - //} + // } - if ( NPCS.NPC->enemy ) - { - if ( !NPCS.NPC->enemy->inuse )//|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! + if (NPCS.NPC->enemy) { + if (!NPCS.NPC->enemy->inuse) //|| NPC->enemy == NPC )//wtf? NPCs should never get mad at themselves! { - if ( setEnemy ) - { - G_ClearEnemy( NPCS.NPC ); + if (setEnemy) { + G_ClearEnemy(NPCS.NPC); } } } - //if ( NPC->svFlags & SVF_IGNORE_ENEMIES ) - if (0) //rwwFIXMEFIXME: support for this flag - {//We're ignoring all enemies for now - if ( setEnemy ) - { - G_ClearEnemy( NPCS.NPC ); + // if ( NPC->svFlags & SVF_IGNORE_ENEMIES ) + if (0) // rwwFIXMEFIXME: support for this flag + { // We're ignoring all enemies for now + if (setEnemy) { + G_ClearEnemy(NPCS.NPC); } return NULL; } - //rwwFIXMEFIXME: support for this flag + // rwwFIXMEFIXME: support for this flag /* if ( NPC->svFlags & SVF_LOCKEDENEMY ) {//keep this enemy until dead @@ -1910,36 +1620,26 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem } */ - if ( NPCS.NPC->enemy ) - { - if ( NPC_EnemyTooFar(NPCS.NPC->enemy, 0, qfalse) ) - { - if(findNew) - {//See if there is a close one and take it if so, else keep this one + if (NPCS.NPC->enemy) { + if (NPC_EnemyTooFar(NPCS.NPC->enemy, 0, qfalse)) { + if (findNew) { // See if there is a close one and take it if so, else keep this one forcefindNew = qtrue; - } - else if(!tooFarOk)//FIXME: don't need this extra bool any more + } else if (!tooFarOk) // FIXME: don't need this extra bool any more { - if ( setEnemy ) - { - G_ClearEnemy( NPCS.NPC ); + if (setEnemy) { + G_ClearEnemy(NPCS.NPC); } } - } - else if ( !trap->InPVS(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin ) ) - {//FIXME: should this be a line-of site check? - //FIXME: a lot of things check PVS AGAIN when deciding whether - //or not to shoot, redundant! - //Should we lose the enemy? - //FIXME: if lose enemy, run lostenemyscript - if ( NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->hiddenDist ) - {//He ducked into shadow while we weren't looking - //Drop enemy and see if we should search for him + } else if (!trap->InPVS(NPCS.NPC->r.currentOrigin, NPCS.NPC->enemy->r.currentOrigin)) { // FIXME: should this be a line-of site check? + // FIXME: a lot of things check PVS AGAIN when deciding whether + // or not to shoot, redundant! + // Should we lose the enemy? + // FIXME: if lose enemy, run lostenemyscript + if (NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->hiddenDist) { // He ducked into shadow while we weren't looking + // Drop enemy and see if we should search for him NPC_LostEnemyDecideChase(); - } - else - {//If we're not chasing him, we need to lose him - //NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up + } else { // If we're not chasing him, we need to lose him + // NOTE: since we no longer have bStates, really, this logic doesn't work, so never give him up /* switch( NPCInfo->behaviorState ) @@ -1965,84 +1665,67 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem } } - if ( NPCS.NPC->enemy ) - { - if ( NPCS.NPC->enemy->health <= 0 || NPCS.NPC->enemy->flags & FL_NOTARGET ) - { - if ( setEnemy ) - { - G_ClearEnemy( NPCS.NPC ); + if (NPCS.NPC->enemy) { + if (NPCS.NPC->enemy->health <= 0 || NPCS.NPC->enemy->flags & FL_NOTARGET) { + if (setEnemy) { + G_ClearEnemy(NPCS.NPC); } } } closestTo = NPCS.NPC; - //FIXME: check your defendEnt, if you have one, see if their enemy is different - //than yours, or, if they don't have one, pick the closest enemy to THEM? - if ( NPCS.NPCInfo->defendEnt ) - {//Trying to protect someone - if ( NPCS.NPCInfo->defendEnt->health > 0 ) - {//Still alive, We presume we're close to them, navigation should handle this? - if ( NPCS.NPCInfo->defendEnt->enemy ) - {//They were shot or acquired an enemy - if ( NPCS.NPC->enemy != NPCS.NPCInfo->defendEnt->enemy ) - {//They have a different enemy, take it! + // FIXME: check your defendEnt, if you have one, see if their enemy is different + // than yours, or, if they don't have one, pick the closest enemy to THEM? + if (NPCS.NPCInfo->defendEnt) { // Trying to protect someone + if (NPCS.NPCInfo->defendEnt->health > 0) { // Still alive, We presume we're close to them, navigation should handle this? + if (NPCS.NPCInfo->defendEnt->enemy) { // They were shot or acquired an enemy + if (NPCS.NPC->enemy != NPCS.NPCInfo->defendEnt->enemy) { // They have a different enemy, take it! newEnemy = NPCS.NPCInfo->defendEnt->enemy; - if ( setEnemy ) - { - G_SetEnemy( NPCS.NPC, NPCS.NPCInfo->defendEnt->enemy ); + if (setEnemy) { + G_SetEnemy(NPCS.NPC, NPCS.NPCInfo->defendEnt->enemy); } } - } - else if ( NPCS.NPC->enemy == NULL ) - {//We don't have an enemy, so find closest to defendEnt + } else if (NPCS.NPC->enemy == NULL) { // We don't have an enemy, so find closest to defendEnt closestTo = NPCS.NPCInfo->defendEnt; } } } - if (!NPCS.NPC->enemy || ( NPCS.NPC->enemy && NPCS.NPC->enemy->health <= 0 ) || forcefindNew ) - {//FIXME: NPCs that are moving after an enemy should ignore the can't hit enemy counter- that should only be for NPCs that are standing still - //NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full + if (!NPCS.NPC->enemy || (NPCS.NPC->enemy && NPCS.NPC->enemy->health <= 0) || + forcefindNew) { // FIXME: NPCs that are moving after an enemy should ignore the can't hit enemy counter- that should only be for NPCs that are standing + // still + // NOTE: cantHitEnemyCounter >= 100 means we couldn't hit enemy for a full // 10 seconds, so give up. This means even if we're chasing him, we would // try to find another enemy after 10 seconds (assuming the cantHitEnemyCounter // is allowed to increment in a chasing bState) - qboolean foundenemy = qfalse; + qboolean foundenemy = qfalse; - if(!findNew) - { - if ( setEnemy ) - { + if (!findNew) { + if (setEnemy) { NPCS.NPC->lastEnemy = NPCS.NPC->enemy; G_ClearEnemy(NPCS.NPC); } return NULL; } - //If enemy dead or unshootable, look for others on out enemy's team - if ( NPCS.NPC->client->enemyTeam != NPCTEAM_NEUTRAL ) - { - //NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose + // If enemy dead or unshootable, look for others on out enemy's team + if (NPCS.NPC->client->enemyTeam != NPCTEAM_NEUTRAL) { + // NOTE: this only checks vis if can't hit enemy for 10 tries, which I suppose // means they need to find one that in more than just PVS - //newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - //For now, made it so you ALWAYS have to check VIS - newEnemy = NPC_PickEnemy( closestTo, NPCS.NPC->client->enemyTeam, qtrue, qfalse, qtrue );//3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) - if ( newEnemy ) - { + // newenemy = NPC_PickEnemy( closestTo, NPC->client->enemyTeam, (NPC->cantHitEnemyCounter > 10), qfalse, qtrue );//3rd parm was (NPC->enemyTeam == + // TEAM_STARFLEET) For now, made it so you ALWAYS have to check VIS + newEnemy = NPC_PickEnemy(closestTo, NPCS.NPC->client->enemyTeam, qtrue, qfalse, qtrue); // 3rd parm was (NPC->enemyTeam == TEAM_STARFLEET) + if (newEnemy) { foundenemy = qtrue; - if ( setEnemy ) - { - G_SetEnemy( NPCS.NPC, newEnemy ); + if (setEnemy) { + G_SetEnemy(NPCS.NPC, newEnemy); } } } - if ( !forcefindNew ) - { - if ( !foundenemy ) - { - if ( setEnemy ) - { + if (!forcefindNew) { + if (!foundenemy) { + if (setEnemy) { NPCS.NPC->lastEnemy = NPCS.NPC->enemy; G_ClearEnemy(NPCS.NPC); } @@ -2050,16 +1733,13 @@ gentity_t *NPC_CheckEnemy( qboolean findNew, qboolean tooFarOk, qboolean setEnem NPCS.NPC->cantHitEnemyCounter = 0; } - //FIXME: if we can't find any at all, go into independent NPC AI, pursue and kill + // FIXME: if we can't find any at all, go into independent NPC AI, pursue and kill } - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client ) - { - if(NPCS.NPC->enemy->client->playerTeam) - { -// assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); - if( NPCS.NPC->client->playerTeam != NPCS.NPC->enemy->client->playerTeam ) - { + if (NPCS.NPC->enemy && NPCS.NPC->enemy->client) { + if (NPCS.NPC->enemy->client->playerTeam) { + // assert( NPC->client->playerTeam != NPC->enemy->client->playerTeam); + if (NPCS.NPC->client->playerTeam != NPCS.NPC->enemy->client->playerTeam) { NPCS.NPC->client->enemyTeam = NPCS.NPC->enemy->client->playerTeam; } } @@ -2073,37 +1753,33 @@ NPC_ClearShot ------------------------- */ -qboolean NPC_ClearShot( gentity_t *ent ) -{ - vec3_t muzzle; - trace_t tr; +qboolean NPC_ClearShot(gentity_t *ent) { + vec3_t muzzle; + trace_t tr; - if ( ( NPCS.NPC == NULL ) || ( ent == NULL ) ) + if ((NPCS.NPC == NULL) || (ent == NULL)) return qfalse; - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPCS.NPC->s.weapon == WP_BLASTER /*|| NPC->s.weapon == WP_BLASTER_PISTOL*/ ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPCS.NPC->s.weapon == WP_BLASTER /*|| NPC->s.weapon == WP_BLASTER_PISTOL*/) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - trap->Trace ( &tr, muzzle, mins, maxs, ent->r.currentOrigin, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - } - else - { - trap->Trace ( &tr, muzzle, NULL, NULL, ent->r.currentOrigin, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, muzzle, mins, maxs, ent->r.currentOrigin, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + } else { + trap->Trace(&tr, muzzle, NULL, NULL, ent->r.currentOrigin, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); } - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { return qfalse; } - if ( tr.entityNum == ent->s.number ) + if (tr.entityNum == ent->s.number) return qtrue; return qfalse; @@ -2115,71 +1791,62 @@ NPC_ShotEntity ------------------------- */ -int NPC_ShotEntity( gentity_t *ent, vec3_t impactPos ) -{ - vec3_t muzzle; +int NPC_ShotEntity(gentity_t *ent, vec3_t impactPos) { + vec3_t muzzle; vec3_t targ; - trace_t tr; + trace_t tr; - if ( !NPCS.NPC || !ent ) + if (!NPCS.NPC || !ent) return qfalse; - if ( NPCS.NPC->s.weapon == WP_THERMAL ) - {//thermal aims from slightly above head - //FIXME: what about low-angle shots, rolling the thermal under something? - vec3_t angles, forward, end; + if (NPCS.NPC->s.weapon == WP_THERMAL) { // thermal aims from slightly above head + // FIXME: what about low-angle shots, rolling the thermal under something? + vec3_t angles, forward, end; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD, muzzle ); - VectorSet( angles, 0, NPCS.NPC->client->ps.viewangles[1], 0 ); - AngleVectors( angles, forward, NULL, NULL ); - VectorMA( muzzle, 8, forward, end ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD, muzzle); + VectorSet(angles, 0, NPCS.NPC->client->ps.viewangles[1], 0); + AngleVectors(angles, forward, NULL, NULL); + VectorMA(muzzle, 8, forward, end); end[2] += 24; - trap->Trace ( &tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - VectorCopy( tr.endpos, muzzle ); + trap->Trace(&tr, muzzle, vec3_origin, vec3_origin, end, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + VectorCopy(tr.endpos, muzzle); + } else { + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); } - else - { - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); - } - CalcEntitySpot( ent, SPOT_CHEST, targ ); + CalcEntitySpot(ent, SPOT_CHEST, targ); // add aim error // use weapon instead of specific npc types, although you could add certain npc classes if you wanted -// if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) - if( NPCS.NPC->s.weapon == WP_BLASTER /*|| NPC->s.weapon == WP_BLASTER_PISTOL*/ ) // any other guns to check for? + // if ( NPC->client->playerTeam == TEAM_SCAVENGERS ) + if (NPCS.NPC->s.weapon == WP_BLASTER /*|| NPC->s.weapon == WP_BLASTER_PISTOL*/) // any other guns to check for? { - vec3_t mins = { -2, -2, -2 }; - vec3_t maxs = { 2, 2, 2 }; + vec3_t mins = {-2, -2, -2}; + vec3_t maxs = {2, 2, 2}; - trap->Trace ( &tr, muzzle, mins, maxs, targ, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - } - else - { - trap->Trace ( &tr, muzzle, NULL, NULL, targ, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, muzzle, mins, maxs, targ, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + } else { + trap->Trace(&tr, muzzle, NULL, NULL, targ, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); } - //FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? - if ( impactPos ) - {//they want to know *where* the hit would be, too - VectorCopy( tr.endpos, impactPos ); + // FIXME: if using a bouncing weapon like the bowcaster, should we check the reflection of the wall, too? + if (impactPos) { // they want to know *where* the hit would be, too + VectorCopy(tr.endpos, impactPos); } -/* // NPCs should be able to shoot even if the muzzle would be inside their target - if ( tr.startsolid || tr.allsolid ) - { - return ENTITYNUM_NONE; - } -*/ + /* // NPCs should be able to shoot even if the muzzle would be inside their target + if ( tr.startsolid || tr.allsolid ) + { + return ENTITYNUM_NONE; + } + */ return tr.entityNum; } -qboolean NPC_EvaluateShot( int hit, qboolean glassOK ) -{ - if ( !NPCS.NPC->enemy ) - { +qboolean NPC_EvaluateShot(int hit, qboolean glassOK) { + if (!NPCS.NPC->enemy) { return qfalse; } - if ( hit == NPCS.NPC->enemy->s.number || (&g_entities[hit] != NULL && (g_entities[hit].r.svFlags&SVF_GLASS_BRUSH)) ) - {//can hit enemy or will hit glass, so shoot anyway + if (hit == NPCS.NPC->enemy->s.number || + (&g_entities[hit] != NULL && (g_entities[hit].r.svFlags & SVF_GLASS_BRUSH))) { // can hit enemy or will hit glass, so shoot anyway return qtrue; } return qfalse; @@ -2191,17 +1858,15 @@ NPC_CheckAttack Simply checks aggression and returns true or false */ -qboolean NPC_CheckAttack (float scale) -{ - if(!scale) +qboolean NPC_CheckAttack(float scale) { + if (!scale) scale = 1.0; - if(((float)NPCS.NPCInfo->stats.aggression) * scale < flrand(0, 4)) - { + if (((float)NPCS.NPCInfo->stats.aggression) * scale < flrand(0, 4)) { return qfalse; } - if(NPCS.NPCInfo->shotTime > level.time) + if (NPCS.NPCInfo->shotTime > level.time) return qfalse; return qtrue; @@ -2213,93 +1878,81 @@ NPC_CheckDefend Simply checks evasion and returns true or false */ -qboolean NPC_CheckDefend (float scale) -{ - if(!scale) +qboolean NPC_CheckDefend(float scale) { + if (!scale) scale = 1.0; - if((float)(NPCS.NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) + if ((float)(NPCS.NPCInfo->stats.evasion) > Q_flrand(0.0f, 1.0f) * 4 * scale) return qtrue; return qfalse; } - -//NOTE: BE SURE TO CHECK PVS BEFORE THIS! -qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) -{ - vec3_t delta, forward; - vec3_t angleToEnemy; - vec3_t hitspot, muzzle, diff, enemy_org;//, enemy_head; - float distanceToEnemy; - qboolean attack_ok = qfalse; -// qboolean duck_ok = qfalse; - qboolean dead_on = qfalse; - float aim_off; - float max_aim_off = 128 - (16 * (float)NPCS.NPCInfo->stats.aim); - trace_t tr; - gentity_t *traceEnt = NULL; - - if(NPCS.NPC->enemy->flags & FL_NOTARGET) - { +// NOTE: BE SURE TO CHECK PVS BEFORE THIS! +qboolean NPC_CheckCanAttack(float attack_scale, qboolean stationary) { + vec3_t delta, forward; + vec3_t angleToEnemy; + vec3_t hitspot, muzzle, diff, enemy_org; //, enemy_head; + float distanceToEnemy; + qboolean attack_ok = qfalse; + // qboolean duck_ok = qfalse; + qboolean dead_on = qfalse; + float aim_off; + float max_aim_off = 128 - (16 * (float)NPCS.NPCInfo->stats.aim); + trace_t tr; + gentity_t *traceEnt = NULL; + + if (NPCS.NPC->enemy->flags & FL_NOTARGET) { return qfalse; } - //FIXME: only check to see if should duck if that provides cover from the - //enemy!!! - if(!attack_scale) - { + // FIXME: only check to see if should duck if that provides cover from the + // enemy!!! + if (!attack_scale) { attack_scale = 1.0; } - //Yaw to enemy - CalcEntitySpot( NPCS.NPC->enemy, SPOT_HEAD, enemy_org ); - NPC_AimWiggle( enemy_org ); + // Yaw to enemy + CalcEntitySpot(NPCS.NPC->enemy, SPOT_HEAD, enemy_org); + NPC_AimWiggle(enemy_org); - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); - VectorSubtract (enemy_org, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + VectorSubtract(enemy_org, muzzle, delta); + vectoangles(delta, angleToEnemy); distanceToEnemy = VectorNormalize(delta); NPCS.NPC->NPC->desiredYaw = angleToEnemy[YAW]; NPC_UpdateFiringAngles(qfalse, qtrue); - if( NPC_EnemyTooFar(NPCS.NPC->enemy, distanceToEnemy*distanceToEnemy, qtrue) ) - {//Too far away? Do not attack + if (NPC_EnemyTooFar(NPCS.NPC->enemy, distanceToEnemy * distanceToEnemy, qtrue)) { // Too far away? Do not attack return qfalse; } - if(NPCS.client->ps.weaponTime > 0) - {//already waiting for a shot to fire + if (NPCS.client->ps.weaponTime > 0) { // already waiting for a shot to fire NPCS.NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); return qfalse; } - if(NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) - { + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) { return qfalse; } NPCS.NPCInfo->enemyLastVisibility = NPCS.enemyVisibility; - //See if they're in our FOV and we have a clear shot to them - NPCS.enemyVisibility = NPC_CheckVisibility ( NPCS.NPC->enemy, CHECK_360|CHECK_FOV);////CHECK_PVS| + // See if they're in our FOV and we have a clear shot to them + NPCS.enemyVisibility = NPC_CheckVisibility(NPCS.NPC->enemy, CHECK_360 | CHECK_FOV); ////CHECK_PVS| - if(NPCS.enemyVisibility >= VIS_FOV) - {//He's in our FOV + if (NPCS.enemyVisibility >= VIS_FOV) { // He's in our FOV attack_ok = qtrue; - //CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); - - //Check to duck - if ( NPCS.NPC->enemy->client ) - { - if ( NPCS.NPC->enemy->enemy == NPCS.NPC ) - { - if ( NPCS.NPC->enemy->client->buttons & BUTTON_ATTACK ) - {//FIXME: determine if enemy fire angles would hit me or get close - if ( NPC_CheckDefend( 1.0 ) )//FIXME: Check self-preservation? Health? - {//duck and don't shoot + // CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_head); + + // Check to duck + if (NPCS.NPC->enemy->client) { + if (NPCS.NPC->enemy->enemy == NPCS.NPC) { + if (NPCS.NPC->enemy->client->buttons & BUTTON_ATTACK) { // FIXME: determine if enemy fire angles would hit me or get close + if (NPC_CheckDefend(1.0)) // FIXME: Check self-preservation? Health? + { // duck and don't shoot attack_ok = qfalse; NPCS.ucmd.upmove = -127; } @@ -2307,14 +1960,13 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if(attack_ok) - { - //are we gonna hit him - //NEW: use actual forward facing - AngleVectors( NPCS.client->ps.viewangles, forward, NULL, NULL ); - VectorMA( muzzle, distanceToEnemy, forward, hitspot ); - trap->Trace( &tr, muzzle, NULL, NULL, hitspot, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0 ); - ShotThroughGlass( &tr, NPCS.NPC->enemy, hitspot, MASK_SHOT ); + if (attack_ok) { + // are we gonna hit him + // NEW: use actual forward facing + AngleVectors(NPCS.client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); + trap->Trace(&tr, muzzle, NULL, NULL, hitspot, NPCS.NPC->s.number, MASK_SHOT, qfalse, 0, 0); + ShotThroughGlass(&tr, NPCS.NPC->enemy, hitspot, MASK_SHOT); /* //OLD: trace regardless of facing trap->Trace ( &tr, muzzle, NULL, NULL, enemy_org, NPC->s.number, MASK_SHOT ); @@ -2339,21 +1991,16 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } */ - VectorCopy( tr.endpos, hitspot ); + VectorCopy(tr.endpos, hitspot); - if( traceEnt == NPCS.NPC->enemy || (traceEnt->client && NPCS.NPC->client->enemyTeam && NPCS.NPC->client->enemyTeam == traceEnt->client->playerTeam) ) - { + if (traceEnt == NPCS.NPC->enemy || + (traceEnt->client && NPCS.NPC->client->enemyTeam && NPCS.NPC->client->enemyTeam == traceEnt->client->playerTeam)) { dead_on = qtrue; - } - else - { + } else { attack_scale *= 0.5; - if(NPCS.NPC->client->playerTeam) - { - if(traceEnt && traceEnt->client && traceEnt->client->playerTeam) - { - if(NPCS.NPC->client->playerTeam == traceEnt->client->playerTeam) - {//Don't shoot our own team + if (NPCS.NPC->client->playerTeam) { + if (traceEnt && traceEnt->client && traceEnt->client->playerTeam) { + if (NPCS.NPC->client->playerTeam == traceEnt->client->playerTeam) { // Don't shoot our own team attack_ok = qfalse; } } @@ -2361,76 +2008,62 @@ qboolean NPC_CheckCanAttack (float attack_scale, qboolean stationary) } } - if( attack_ok ) - { - //ok, now adjust pitch aim - VectorSubtract (hitspot, muzzle, delta); - vectoangles ( delta, angleToEnemy ); + if (attack_ok) { + // ok, now adjust pitch aim + VectorSubtract(hitspot, muzzle, delta); + vectoangles(delta, angleToEnemy); NPCS.NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); - if( !dead_on ) - {//We're not going to hit him directly, try a suppressing fire - //see if where we're going to shoot is too far from his origin - if(traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) - {//easy to kill - go for it - //if(traceEnt->die == ExplodeDeath_Wait && traceEnt->splashDamage) - if (0) //rwwFIXMEFIXME: ExplodeDeath_Wait? - {//going to explode, don't shoot if close to self + if (!dead_on) { // We're not going to hit him directly, try a suppressing fire + // see if where we're going to shoot is too far from his origin + if (traceEnt && (traceEnt->health <= 30 || EntIsGlass(traceEnt))) { // easy to kill - go for it + // if(traceEnt->die == ExplodeDeath_Wait && traceEnt->splashDamage) + if (0) // rwwFIXMEFIXME: ExplodeDeath_Wait? + { // going to explode, don't shoot if close to self VectorSubtract(NPCS.NPC->r.currentOrigin, traceEnt->r.currentOrigin, diff); - if(VectorLengthSquared(diff) < traceEnt->splashRadius*traceEnt->splashRadius) - {//Too close to shoot! + if (VectorLengthSquared(diff) < traceEnt->splashRadius * traceEnt->splashRadius) { // Too close to shoot! attack_ok = qfalse; - } - else - {//Hey, it might kill him, do it! - attack_scale *= 2;// + } else { // Hey, it might kill him, do it! + attack_scale *= 2; // } } - } - else - { - AngleVectors (NPCS.client->ps.viewangles, forward, NULL, NULL); - VectorMA ( muzzle, distanceToEnemy, forward, hitspot); + } else { + AngleVectors(NPCS.client->ps.viewangles, forward, NULL, NULL); + VectorMA(muzzle, distanceToEnemy, forward, hitspot); VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off)//FIXME: use aim value to allow poor aim? + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) // FIXME: use aim value to allow poor aim? { attack_scale *= 0.75; - //see if where we're going to shoot is too far from his head + // see if where we're going to shoot is too far from his head VectorSubtract(hitspot, enemy_org, diff); aim_off = VectorLength(diff); - if(aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) - { + if (aim_off > Q_flrand(0.0f, 1.0f) * max_aim_off) { attack_ok = qfalse; } } - attack_scale *= (max_aim_off - aim_off + 1)/max_aim_off; + attack_scale *= (max_aim_off - aim_off + 1) / max_aim_off; } } } - } - else - {//Update pitch anyway + } else { // Update pitch anyway NPCS.NPC->NPC->desiredPitch = angleToEnemy[PITCH]; NPC_UpdateFiringAngles(qtrue, qfalse); } - if( attack_ok ) - { - if( NPC_CheckAttack( attack_scale )) - {//check aggression to decide if we should shoot + if (attack_ok) { + if (NPC_CheckAttack(attack_scale)) { // check aggression to decide if we should shoot NPCS.enemyVisibility = VIS_SHOOT; WeaponThink(qtrue); - } - else + } else attack_ok = qfalse; } return attack_ok; } //======================================================================================== -//OLD id-style hunt and kill +// OLD id-style hunt and kill //======================================================================================== /* IdealDistance @@ -2438,13 +2071,11 @@ IdealDistance determines what the NPC's ideal distance from it's enemy should be in the current situation */ -float IdealDistance ( gentity_t *self ) -{ - float ideal; +float IdealDistance(gentity_t *self) { + float ideal; ideal = 225 - 20 * NPCS.NPCInfo->stats.aggression; - switch ( NPCS.NPC->s.weapon ) - { + switch (NPCS.NPC->s.weapon) { case WP_ROCKET_LAUNCHER: ideal += 200; break; @@ -2452,10 +2083,10 @@ float IdealDistance ( gentity_t *self ) case WP_THERMAL: ideal += 50; break; - + case WP_SABER: case WP_BRYAR_PISTOL: -// case WP_BLASTER_PISTOL: + // case WP_BLASTER_PISTOL: case WP_BLASTER: default: break; @@ -2475,12 +2106,10 @@ LEAN - Lean-type cover, NOT IMPLEMENTED SNIPE - Snipers look for these first, NOT IMPLEMENTED */ -void SP_point_combat( gentity_t *self ) -{ - if(level.numCombatPoints >= MAX_COMBAT_POINTS) - { +void SP_point_combat(gentity_t *self) { + if (level.numCombatPoints >= MAX_COMBAT_POINTS) { #ifndef FINAL_BUILD - Com_Printf(S_COLOR_RED"ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); + Com_Printf(S_COLOR_RED "ERROR: Too many combat points, limit is %d\n", MAX_COMBAT_POINTS); #endif G_FreeEntity(self); return; @@ -2490,14 +2119,13 @@ void SP_point_combat( gentity_t *self ) G_SetOrigin(self, self->s.origin); trap->LinkEntity((sharedEntity_t *)self); - if ( G_CheckInSolid( self, qtrue ) ) - { + if (G_CheckInSolid(self, qtrue)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: combat point at %s in solid!\n", vtos(self->r.currentOrigin) ); + Com_Printf(S_COLOR_RED "ERROR: combat point at %s in solid!\n", vtos(self->r.currentOrigin)); #endif } - VectorCopy( self->r.currentOrigin, level.combatPoints[level.numCombatPoints].origin ); + VectorCopy(self->r.currentOrigin, level.combatPoints[level.numCombatPoints].origin); level.combatPoints[level.numCombatPoints].flags = self->spawnflags; level.combatPoints[level.numCombatPoints].occupied = qfalse; @@ -2507,23 +2135,19 @@ void SP_point_combat( gentity_t *self ) G_FreeEntity(self); } -void CP_FindCombatPointWaypoints( void ) -{ +void CP_FindCombatPointWaypoints(void) { int i; - for ( i = 0; i < level.numCombatPoints; i++ ) - { - level.combatPoints[i].waypoint = NAV_FindClosestWaypointForPoint2( level.combatPoints[i].origin ); + for (i = 0; i < level.numCombatPoints; i++) { + level.combatPoints[i].waypoint = NAV_FindClosestWaypointForPoint2(level.combatPoints[i].origin); #ifndef FINAL_BUILD - if ( level.combatPoints[i].waypoint == WAYPOINT_NONE ) - { - Com_Printf( S_COLOR_RED"ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin) ); + if (level.combatPoints[i].waypoint == WAYPOINT_NONE) { + Com_Printf(S_COLOR_RED "ERROR: Combat Point at %s has no waypoint!\n", vtos(level.combatPoints[i].origin)); } #endif } } - /* ------------------------- NPC_CollectCombatPoints @@ -2533,63 +2157,53 @@ typedef struct combatPt_s { float dist; int index; } combatPt_t; -static int NPC_CollectCombatPoints( const vec3_t origin, const float radius, combatPt_t *points, const int flags ) -{ - float radiusSqr = (radius*radius); - float distance; - float bestDistance = Q3_INFINITE; - int numPoints = 0; - int i; - - //Collect all nearest - for ( i = 0; i < level.numCombatPoints; i++ ) - { - if (numPoints >= MAX_COMBAT_POINTS) - { +static int NPC_CollectCombatPoints(const vec3_t origin, const float radius, combatPt_t *points, const int flags) { + float radiusSqr = (radius * radius); + float distance; + float bestDistance = Q3_INFINITE; + int numPoints = 0; + int i; + + // Collect all nearest + for (i = 0; i < level.numCombatPoints; i++) { + if (numPoints >= MAX_COMBAT_POINTS) { break; } - //Must be vacant - if ( level.combatPoints[i].occupied == (int) qtrue ) + // Must be vacant + if (level.combatPoints[i].occupied == (int)qtrue) continue; - //If we want a duck space, make sure this is one - if ( ( flags & CP_DUCK ) && ( level.combatPoints[i].flags & CPF_DUCK ) ) + // If we want a duck space, make sure this is one + if ((flags & CP_DUCK) && (level.combatPoints[i].flags & CPF_DUCK)) continue; - //If we want a duck space, make sure this is one - if ( ( flags & CP_FLEE ) && ( level.combatPoints[i].flags & CPF_FLEE ) ) + // If we want a duck space, make sure this is one + if ((flags & CP_FLEE) && (level.combatPoints[i].flags & CPF_FLEE)) continue; - ///Make sure this is an investigate combat point - if ( ( flags & CP_INVESTIGATE ) && ( level.combatPoints[i].flags & CPF_INVESTIGATE ) ) + /// Make sure this is an investigate combat point + if ((flags & CP_INVESTIGATE) && (level.combatPoints[i].flags & CPF_INVESTIGATE)) continue; - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) && ( ( flags & CP_SQUAD ) == qfalse ) ) + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) && ((flags & CP_SQUAD) == qfalse)) continue; - if ( flags&CP_NO_PVS ) - {//must not be within PVS of mu current origin - if ( trap->InPVS( origin, level.combatPoints[i].origin ) ) - { + if (flags & CP_NO_PVS) { // must not be within PVS of mu current origin + if (trap->InPVS(origin, level.combatPoints[i].origin)) { continue; } } - if ( flags&CP_HORZ_DIST_COLL ) - { - distance = DistanceHorizontalSquared( origin, level.combatPoints[i].origin ); - } - else - { - distance = DistanceSquared( origin, level.combatPoints[i].origin ); + if (flags & CP_HORZ_DIST_COLL) { + distance = DistanceHorizontalSquared(origin, level.combatPoints[i].origin); + } else { + distance = DistanceSquared(origin, level.combatPoints[i].origin); } - if ( distance < radiusSqr ) - { - if (distance < bestDistance) - { + if (distance < radiusSqr) { + if (distance < bestDistance) { bestDistance = distance; } @@ -2608,157 +2222,128 @@ NPC_FindCombatPoint ------------------------- */ -#define MIN_AVOID_DOT 0.75f -#define MIN_AVOID_DISTANCE 128 -#define MIN_AVOID_DISTANCE_SQUARED ( MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE ) -#define CP_COLLECT_RADIUS 512.0f +#define MIN_AVOID_DOT 0.75f +#define MIN_AVOID_DISTANCE 128 +#define MIN_AVOID_DISTANCE_SQUARED (MIN_AVOID_DISTANCE * MIN_AVOID_DISTANCE) +#define CP_COLLECT_RADIUS 512.0f -int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3_t enemyPosition, const int flags, const float avoidDist, const int ignorePoint ) -{ - combatPt_t points[MAX_COMBAT_POINTS]; - int best = -1, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE; - float dist; - trace_t tr; - float collRad = CP_COLLECT_RADIUS; - int numPoints; - int j = 0; - float modifiedAvoidDist = avoidDist; - - if ( modifiedAvoidDist <= 0 ) - { +int NPC_FindCombatPoint(const vec3_t position, const vec3_t avoidPosition, vec3_t enemyPosition, const int flags, const float avoidDist, + const int ignorePoint) { + combatPt_t points[MAX_COMBAT_POINTS]; + int best = -1, cost, bestCost = Q3_INFINITE, waypoint = WAYPOINT_NONE; + float dist; + trace_t tr; + float collRad = CP_COLLECT_RADIUS; + int numPoints; + int j = 0; + float modifiedAvoidDist = avoidDist; + + if (modifiedAvoidDist <= 0) { modifiedAvoidDist = MIN_AVOID_DISTANCE_SQUARED; - } - else - { + } else { modifiedAvoidDist *= modifiedAvoidDist; } - if ( (flags & CP_HAS_ROUTE) || (flags & CP_NEAREST) ) - {//going to be doing macro nav tests - if ( NPCS.NPC->waypoint == WAYPOINT_NONE ) - { - waypoint = NAV_GetNearestNode( NPCS.NPC, NPCS.NPC->lastWaypoint ); - } - else - { + if ((flags & CP_HAS_ROUTE) || (flags & CP_NEAREST)) { // going to be doing macro nav tests + if (NPCS.NPC->waypoint == WAYPOINT_NONE) { + waypoint = NAV_GetNearestNode(NPCS.NPC, NPCS.NPC->lastWaypoint); + } else { waypoint = NPCS.NPC->waypoint; } } - //Collect our nearest points - if ( flags & CP_NO_PVS ) - {//much larger radius since most will be dropped? - collRad = CP_COLLECT_RADIUS*4; + // Collect our nearest points + if (flags & CP_NO_PVS) { // much larger radius since most will be dropped? + collRad = CP_COLLECT_RADIUS * 4; } - numPoints = NPC_CollectCombatPoints( enemyPosition, collRad, points, flags );//position + numPoints = NPC_CollectCombatPoints(enemyPosition, collRad, points, flags); // position - - for ( j = 0; j < numPoints; j++ ) - { - //const int i = (*cpi).second; + for (j = 0; j < numPoints; j++) { + // const int i = (*cpi).second; const int i = points[j].index; const float pdist = points[j].dist; - //Must not be one we want to ignore - if ( i == ignorePoint ) + // Must not be one we want to ignore + if (i == ignorePoint) continue; - //FIXME: able to mark certain ones as too dangerous to go to for now? Like a tripmine/thermal/detpack is near or something? - //If we need a cover point, check this point - if ( ( flags & CP_COVER ) && ( NPC_ClearLOS( level.combatPoints[i].origin, enemyPosition ) == qtrue ) )//Used to use NPC->enemy + // FIXME: able to mark certain ones as too dangerous to go to for now? Like a tripmine/thermal/detpack is near or something? + // If we need a cover point, check this point + if ((flags & CP_COVER) && (NPC_ClearLOS(level.combatPoints[i].origin, enemyPosition) == qtrue)) // Used to use NPC->enemy continue; - //Need a clear LOS to our target... and be within shot range to enemy position (FIXME: make this a separate CS_ flag? and pass in a range?) - if ( flags & CP_CLEAR ) - { - if ( NPC_ClearLOS3( level.combatPoints[i].origin, NPCS.NPC->enemy ) == qfalse ) - { + // Need a clear LOS to our target... and be within shot range to enemy position (FIXME: make this a separate CS_ flag? and pass in a range?) + if (flags & CP_CLEAR) { + if (NPC_ClearLOS3(level.combatPoints[i].origin, NPCS.NPC->enemy) == qfalse) { continue; } - if ( NPCS.NPC->s.weapon == WP_THERMAL ) - {//horizontal - dist = DistanceHorizontalSquared( level.combatPoints[i].origin, NPCS.NPC->enemy->r.currentOrigin ); - } - else - {//actual - dist = DistanceSquared( level.combatPoints[i].origin, NPCS.NPC->enemy->r.currentOrigin ); + if (NPCS.NPC->s.weapon == WP_THERMAL) { // horizontal + dist = DistanceHorizontalSquared(level.combatPoints[i].origin, NPCS.NPC->enemy->r.currentOrigin); + } else { // actual + dist = DistanceSquared(level.combatPoints[i].origin, NPCS.NPC->enemy->r.currentOrigin); } - if ( dist > (NPCS.NPCInfo->stats.visrange*NPCS.NPCInfo->stats.visrange) ) - { + if (dist > (NPCS.NPCInfo->stats.visrange * NPCS.NPCInfo->stats.visrange)) { continue; } } - //Avoid this position? - if ( ( flags & CP_AVOID ) && ( DistanceSquared( level.combatPoints[i].origin, position ) < modifiedAvoidDist ) )//was using MIN_AVOID_DISTANCE_SQUARED, not passed in modifiedAvoidDist + // Avoid this position? + if ((flags & CP_AVOID) && (DistanceSquared(level.combatPoints[i].origin, position) < + modifiedAvoidDist)) // was using MIN_AVOID_DISTANCE_SQUARED, not passed in modifiedAvoidDist continue; - //Try to find a point closer to the enemy than where we are - if ( flags & CP_APPROACH_ENEMY ) - { - if ( flags&CP_HORZ_DIST_COLL ) - { - if ( pdist > DistanceHorizontalSquared( position, enemyPosition ) ) - { + // Try to find a point closer to the enemy than where we are + if (flags & CP_APPROACH_ENEMY) { + if (flags & CP_HORZ_DIST_COLL) { + if (pdist > DistanceHorizontalSquared(position, enemyPosition)) { continue; } - } - else - { - if ( pdist > DistanceSquared( position, enemyPosition ) ) - { + } else { + if (pdist > DistanceSquared(position, enemyPosition)) { continue; } } } - //Try to find a point farther from the enemy than where we are - if ( flags & CP_RETREAT ) - { - if ( flags&CP_HORZ_DIST_COLL ) - { - if ( pdist < DistanceHorizontalSquared( position, enemyPosition ) ) - {//it's closer, don't use it + // Try to find a point farther from the enemy than where we are + if (flags & CP_RETREAT) { + if (flags & CP_HORZ_DIST_COLL) { + if (pdist < DistanceHorizontalSquared(position, enemyPosition)) { // it's closer, don't use it continue; } - } - else - { - if ( pdist < DistanceSquared( position, enemyPosition ) ) - {//it's closer, don't use it + } else { + if (pdist < DistanceSquared(position, enemyPosition)) { // it's closer, don't use it continue; } } } - //We want a point on other side of the enemy from current pos - if ( flags & CP_FLANK ) - { - vec3_t eDir2Me, eDir2CP; + // We want a point on other side of the enemy from current pos + if (flags & CP_FLANK) { + vec3_t eDir2Me, eDir2CP; float dot; - VectorSubtract( position, enemyPosition, eDir2Me ); - VectorNormalize( eDir2Me ); + VectorSubtract(position, enemyPosition, eDir2Me); + VectorNormalize(eDir2Me); - VectorSubtract( level.combatPoints[i].origin, enemyPosition, eDir2CP ); - VectorNormalize( eDir2CP ); + VectorSubtract(level.combatPoints[i].origin, enemyPosition, eDir2CP); + VectorNormalize(eDir2CP); - dot = DotProduct( eDir2Me, eDir2CP ); + dot = DotProduct(eDir2Me, eDir2CP); - //Not far enough behind enemy from current pos - if ( dot >= 0.4 ) + // Not far enough behind enemy from current pos + if (dot >= 0.4) continue; } - //See if we're trying to avoid our enemy - //FIXME: this needs to check for the waypoint you'll be taking to get to that combat point - if ( flags & CP_AVOID_ENEMY ) - { - vec3_t eDir, gDir; - vec3_t wpOrg; + // See if we're trying to avoid our enemy + // FIXME: this needs to check for the waypoint you'll be taking to get to that combat point + if (flags & CP_AVOID_ENEMY) { + vec3_t eDir, gDir; + vec3_t wpOrg; float dot; - VectorSubtract( position, enemyPosition, eDir ); - VectorNormalize( eDir ); + VectorSubtract(position, enemyPosition, eDir); + VectorNormalize(eDir); /* NAV_FindClosestWaypointForEnt( NPC, level.combatPoints[i].waypoint ); @@ -2768,33 +2353,30 @@ int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3 } else */ - { - VectorCopy( level.combatPoints[i].origin, wpOrg ); - } - VectorSubtract( position, wpOrg, gDir ); - VectorNormalize( gDir ); + { VectorCopy(level.combatPoints[i].origin, wpOrg); } + VectorSubtract(position, wpOrg, gDir); + VectorNormalize(gDir); - dot = DotProduct( gDir, eDir ); + dot = DotProduct(gDir, eDir); - //Don't want to run at enemy - if ( dot >= MIN_AVOID_DOT ) + // Don't want to run at enemy + if (dot >= MIN_AVOID_DOT) continue; - //Can't be too close to the enemy - if ( DistanceSquared( wpOrg, enemyPosition ) < modifiedAvoidDist ) + // Can't be too close to the enemy + if (DistanceSquared(wpOrg, enemyPosition) < modifiedAvoidDist) continue; } - //Okay, now make sure it's not blocked - trap->Trace( &tr, level.combatPoints[i].origin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, level.combatPoints[i].origin, NPCS.NPC->s.number, NPCS.NPC->clipmask, qfalse, 0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + // Okay, now make sure it's not blocked + trap->Trace(&tr, level.combatPoints[i].origin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, level.combatPoints[i].origin, NPCS.NPC->s.number, NPCS.NPC->clipmask, + qfalse, 0, 0); + if (tr.allsolid || tr.startsolid) { continue; } - //we must have a route to the combat point - if ( flags & CP_HAS_ROUTE ) - { + // we must have a route to the combat point + if (flags & CP_HAS_ROUTE) { /* if ( level.combatPoints[i].waypoint == WAYPOINT_NONE ) { @@ -2802,30 +2384,29 @@ int NPC_FindCombatPoint( const vec3_t position, const vec3_t avoidPosition, vec3 } */ - if ( waypoint == WAYPOINT_NONE || level.combatPoints[i].waypoint == WAYPOINT_NONE || trap->Nav_GetBestNodeAltRoute2( waypoint, level.combatPoints[i].waypoint, NODE_NONE ) == WAYPOINT_NONE ) - {//can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one - if ( !NAV_ClearPathToPoint( NPCS.NPC, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, level.combatPoints[i].origin, NPCS.NPC->clipmask, ENTITYNUM_NONE ) ) - {//don't even have a clear straight path to this one + if (waypoint == WAYPOINT_NONE || level.combatPoints[i].waypoint == WAYPOINT_NONE || + trap->Nav_GetBestNodeAltRoute2(waypoint, level.combatPoints[i].waypoint, NODE_NONE) == + WAYPOINT_NONE) { // can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one + if (!NAV_ClearPathToPoint(NPCS.NPC, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, level.combatPoints[i].origin, NPCS.NPC->clipmask, + ENTITYNUM_NONE)) { // don't even have a clear straight path to this one continue; } } } - //We want the one with the shortest path from current pos - if ( flags & CP_NEAREST && waypoint != WAYPOINT_NONE && level.combatPoints[i].waypoint != WAYPOINT_NONE ) - { - cost = trap->Nav_GetPathCost( waypoint, level.combatPoints[i].waypoint ); - if ( cost < bestCost ) - { + // We want the one with the shortest path from current pos + if (flags & CP_NEAREST && waypoint != WAYPOINT_NONE && level.combatPoints[i].waypoint != WAYPOINT_NONE) { + cost = trap->Nav_GetPathCost(waypoint, level.combatPoints[i].waypoint); + if (cost < bestCost) { bestCost = cost; best = i; } continue; } - //we want the combat point closest to the enemy - //if ( flags & CP_CLOSEST ) - //they are sorted by this distance, so the first one to get this far is the closest + // we want the combat point closest to the enemy + // if ( flags & CP_CLOSEST ) + // they are sorted by this distance, so the first one to get this far is the closest return i; } @@ -2838,33 +2419,30 @@ NPC_FindSquadPoint ------------------------- */ -int NPC_FindSquadPoint( vec3_t position ) -{ - float dist, nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - int nearestPoint = -1; - int i; +int NPC_FindSquadPoint(vec3_t position) { + float dist, nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + int nearestPoint = -1; + int i; - //float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->r.currentOrigin ); + // float playerDist = DistanceSquared( g_entities[0].currentOrigin, NPC->r.currentOrigin ); - for ( i = 0; i < level.numCombatPoints; i++ ) - { - //Squad points are only valid if we're looking for them - if ( ( level.combatPoints[i].flags & CPF_SQUAD ) == qfalse ) + for (i = 0; i < level.numCombatPoints; i++) { + // Squad points are only valid if we're looking for them + if ((level.combatPoints[i].flags & CPF_SQUAD) == qfalse) continue; - //Must be vacant - if ( level.combatPoints[i].occupied == qtrue ) + // Must be vacant + if (level.combatPoints[i].occupied == qtrue) continue; - dist = DistanceSquared( position, level.combatPoints[i].origin ); + dist = DistanceSquared(position, level.combatPoints[i].origin); - //The point cannot take us past the player - //if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this + // The point cannot take us past the player + // if ( dist > ( playerDist * DotProduct( dirToPlayer, playerDir ) ) ) //FIXME: Retain this // continue; - //See if this is closer than the others - if ( dist < nearestDist ) - { + // See if this is closer than the others + if (dist < nearestDist) { nearestPoint = i; nearestDist = dist; } @@ -2879,17 +2457,16 @@ NPC_ReserveCombatPoint ------------------------- */ -qboolean NPC_ReserveCombatPoint( int combatPointID ) -{ - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) +qboolean NPC_ReserveCombatPoint(int combatPointID) { + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's not already occupied - if ( level.combatPoints[combatPointID].occupied ) + // Make sure it's not already occupied + if (level.combatPoints[combatPointID].occupied) return qfalse; - //Reserve it + // Reserve it level.combatPoints[combatPointID].occupied = qtrue; return qtrue; @@ -2901,21 +2478,19 @@ NPC_FreeCombatPoint ------------------------- */ -qboolean NPC_FreeCombatPoint( int combatPointID, qboolean failed ) -{ - if ( failed ) - {//remember that this one failed for us +qboolean NPC_FreeCombatPoint(int combatPointID, qboolean failed) { + if (failed) { // remember that this one failed for us NPCS.NPCInfo->lastFailedCombatPoint = combatPointID; } - //Make sure it's valid - if ( combatPointID > level.numCombatPoints ) + // Make sure it's valid + if (combatPointID > level.numCombatPoints) return qfalse; - //Make sure it's currently occupied - if ( level.combatPoints[combatPointID].occupied == qfalse ) + // Make sure it's currently occupied + if (level.combatPoints[combatPointID].occupied == qfalse) return qfalse; - //Free it + // Free it level.combatPoints[combatPointID].occupied = qfalse; return qtrue; @@ -2927,15 +2502,13 @@ NPC_SetCombatPoint ------------------------- */ -qboolean NPC_SetCombatPoint( int combatPointID ) -{ - //Free a combat point if we already have one - if ( NPCS.NPCInfo->combatPoint != -1 ) - { - NPC_FreeCombatPoint( NPCS.NPCInfo->combatPoint, qfalse ); +qboolean NPC_SetCombatPoint(int combatPointID) { + // Free a combat point if we already have one + if (NPCS.NPCInfo->combatPoint != -1) { + NPC_FreeCombatPoint(NPCS.NPCInfo->combatPoint, qfalse); } - if ( NPC_ReserveCombatPoint( combatPointID ) == qfalse ) + if (NPC_ReserveCombatPoint(combatPointID) == qfalse) return qfalse; NPCS.NPCInfo->combatPoint = combatPointID; @@ -2943,56 +2516,46 @@ qboolean NPC_SetCombatPoint( int combatPointID ) return qtrue; } -extern qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ); -gentity_t *NPC_SearchForWeapons( void ) -{ +extern qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper); +gentity_t *NPC_SearchForWeapons(void) { gentity_t *found = g_entities, *bestFound = NULL; - float dist, bestDist = Q3_INFINITE; + float dist, bestDist = Q3_INFINITE; int i; -// for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) - for ( i = 0; iinuse ) -// { -// continue; -// } - if(!g_entities[i].inuse) + // for ( found = g_entities; found < &g_entities[globals.num_entities] ; found++) + for (i = 0; i < level.num_entities; i++) { + // if ( !found->inuse ) + // { + // continue; + // } + if (!g_entities[i].inuse) continue; - found=&g_entities[i]; + found = &g_entities[i]; - //FIXME: Also look for ammo_racks that have weapons on them? - if ( found->s.eType != ET_ITEM ) - { + // FIXME: Also look for ammo_racks that have weapons on them? + if (found->s.eType != ET_ITEM) { continue; } - if ( found->item->giType != IT_WEAPON ) - { + if (found->item->giType != IT_WEAPON) { continue; } - if ( found->s.eFlags & EF_NODRAW ) - { + if (found->s.eFlags & EF_NODRAW) { continue; } - if ( CheckItemCanBePickedUpByNPC( found, NPCS.NPC ) ) - { - if ( trap->InPVS( found->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - { - dist = DistanceSquared( found->r.currentOrigin, NPCS.NPC->r.currentOrigin ); - if ( dist < bestDist ) - { - if ( !trap->Nav_GetBestPathBetweenEnts( (sharedEntity_t *)NPCS.NPC, (sharedEntity_t *)found, NF_CLEAR_PATH ) - || trap->Nav_GetBestNodeAltRoute2( NPCS.NPC->waypoint, found->waypoint, NODE_NONE ) == WAYPOINT_NONE ) - {//can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one - if ( NAV_ClearPathToPoint( NPCS.NPC, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, found->r.currentOrigin, NPCS.NPC->clipmask, ENTITYNUM_NONE ) ) - {//have a clear straight path to this one + if (CheckItemCanBePickedUpByNPC(found, NPCS.NPC)) { + if (trap->InPVS(found->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { + dist = DistanceSquared(found->r.currentOrigin, NPCS.NPC->r.currentOrigin); + if (dist < bestDist) { + if (!trap->Nav_GetBestPathBetweenEnts((sharedEntity_t *)NPCS.NPC, (sharedEntity_t *)found, NF_CLEAR_PATH) || + trap->Nav_GetBestNodeAltRoute2(NPCS.NPC->waypoint, found->waypoint, NODE_NONE) == + WAYPOINT_NONE) { // can't possibly have a route to any OR can't possibly have a route to this one OR don't have a route to this one + if (NAV_ClearPathToPoint(NPCS.NPC, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, found->r.currentOrigin, NPCS.NPC->clipmask, + ENTITYNUM_NONE)) { // have a clear straight path to this one bestDist = dist; bestFound = found; } - } - else - {//can nav to it + } else { // can nav to it bestDist = dist; bestFound = found; } @@ -3004,35 +2567,27 @@ gentity_t *NPC_SearchForWeapons( void ) return bestFound; } -void NPC_SetPickUpGoal( gentity_t *foundWeap ) -{ +void NPC_SetPickUpGoal(gentity_t *foundWeap) { vec3_t org; - //NPCInfo->goalEntity = foundWeap; - VectorCopy( foundWeap->r.currentOrigin, org ); - org[2] += 24 - (foundWeap->r.mins[2]*-1);//adjust the origin so that I am on the ground - NPC_SetMoveGoal( NPCS.NPC, org, foundWeap->r.maxs[0]*0.75, qfalse, -1, foundWeap ); + // NPCInfo->goalEntity = foundWeap; + VectorCopy(foundWeap->r.currentOrigin, org); + org[2] += 24 - (foundWeap->r.mins[2] * -1); // adjust the origin so that I am on the ground + NPC_SetMoveGoal(NPCS.NPC, org, foundWeap->r.maxs[0] * 0.75, qfalse, -1, foundWeap); NPCS.NPCInfo->tempGoal->waypoint = foundWeap->waypoint; NPCS.NPCInfo->tempBehavior = BS_DEFAULT; NPCS.NPCInfo->squadState = SQUAD_TRANSITION; } -void NPC_CheckGetNewWeapon( void ) -{ - if ( NPCS.NPC->s.weapon == WP_NONE && NPCS.NPC->enemy ) - {//if running away because dropped weapon... - if ( NPCS.NPCInfo->goalEntity - && NPCS.NPCInfo->goalEntity == NPCS.NPCInfo->tempGoal - && NPCS.NPCInfo->goalEntity->enemy - && !NPCS.NPCInfo->goalEntity->enemy->inuse ) - {//maybe was running at a weapon that was picked up +void NPC_CheckGetNewWeapon(void) { + if (NPCS.NPC->s.weapon == WP_NONE && NPCS.NPC->enemy) { // if running away because dropped weapon... + if (NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->goalEntity == NPCS.NPCInfo->tempGoal && NPCS.NPCInfo->goalEntity->enemy && + !NPCS.NPCInfo->goalEntity->enemy->inuse) { // maybe was running at a weapon that was picked up NPCS.NPCInfo->goalEntity = NULL; } - if ( TIMER_Done( NPCS.NPC, "panic" ) && NPCS.NPCInfo->goalEntity == NULL ) - {//need a weapon, any lying around? + if (TIMER_Done(NPCS.NPC, "panic") && NPCS.NPCInfo->goalEntity == NULL) { // need a weapon, any lying around? gentity_t *foundWeap = NPC_SearchForWeapons(); - if ( foundWeap ) - {//try to nav to it + if (foundWeap) { // try to nav to it /* if ( !trap->Nav_GetBestPathBetweenEnts( NPC, foundWeap, NF_CLEAR_PATH ) || trap->Nav_GetBestNodeAltRoute( NPC->waypoint, foundWeap->waypoint ) == WAYPOINT_NONE ) @@ -3047,59 +2602,49 @@ void NPC_CheckGetNewWeapon( void ) } else */ - { - NPC_SetPickUpGoal( foundWeap ); - } + { NPC_SetPickUpGoal(foundWeap); } } } } } -void NPC_AimAdjust( int change ) -{ - if ( !TIMER_Exists( NPCS.NPC, "aimDebounce" ) ) - { - int debounce = 500+(3-g_npcspskill.integer)*100; - TIMER_Set( NPCS.NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_npcspskill.integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); +void NPC_AimAdjust(int change) { + if (!TIMER_Exists(NPCS.NPC, "aimDebounce")) { + int debounce = 500 + (3 - g_npcspskill.integer) * 100; + TIMER_Set(NPCS.NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_npcspskill.integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); return; } - if ( TIMER_Done( NPCS.NPC, "aimDebounce" ) ) - { + if (TIMER_Done(NPCS.NPC, "aimDebounce")) { int debounce; NPCS.NPCInfo->currentAim += change; - if ( NPCS.NPCInfo->currentAim > NPCS.NPCInfo->stats.aim ) - {//can never be better than max aim + if (NPCS.NPCInfo->currentAim > NPCS.NPCInfo->stats.aim) { // can never be better than max aim NPCS.NPCInfo->currentAim = NPCS.NPCInfo->stats.aim; - } - else if ( NPCS.NPCInfo->currentAim < -30 ) - {//can never be worse than this + } else if (NPCS.NPCInfo->currentAim < -30) { // can never be worse than this NPCS.NPCInfo->currentAim = -30; } - //Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); + // Com_Printf( "%s new aim = %d\n", NPC->NPC_type, NPCInfo->currentAim ); - debounce = 500+(3-g_npcspskill.integer)*100; - TIMER_Set( NPCS.NPC, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - //int debounce = 1000+(3-g_npcspskill.integer)*500; - //TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); + debounce = 500 + (3 - g_npcspskill.integer) * 100; + TIMER_Set(NPCS.NPC, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_npcspskill.integer)*500; + // TIMER_Set( NPC, "aimDebounce", Q_irand( debounce, debounce+2000 ) ); } } -void G_AimSet( gentity_t *self, int aim ) -{ - if ( self->NPC ) - { +void G_AimSet(gentity_t *self, int aim) { + if (self->NPC) { int debounce; self->NPC->currentAim = aim; - //Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); + // Com_Printf( "%s new aim = %d\n", self->NPC_type, self->NPC->currentAim ); - debounce = 500+(3-g_npcspskill.integer)*100; - TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+1000 ) ); - // int debounce = 1000+(3-g_npcspskill.integer)*500; - // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); + debounce = 500 + (3 - g_npcspskill.integer) * 100; + TIMER_Set(self, "aimDebounce", Q_irand(debounce, debounce + 1000)); + // int debounce = 1000+(3-g_npcspskill.integer)*500; + // TIMER_Set( self, "aimDebounce", Q_irand( debounce,debounce+2000 ) ); } } diff --git a/codemp/game/NPC_goal.c b/codemp/game/NPC_goal.c index 499710f487..23e0b5eb4f 100644 --- a/codemp/game/NPC_goal.c +++ b/codemp/game/NPC_goal.c @@ -20,91 +20,77 @@ along with this program; if not, see . =========================================================================== */ -//b_goal.cpp +// b_goal.cpp #include "b_local.h" #include "icarus/Q3_Interface.h" -extern qboolean FlyingCreature( gentity_t *ent ); +extern qboolean FlyingCreature(gentity_t *ent); /* SetGoal */ -void SetGoal( gentity_t *goal, float rating ) -{ +void SetGoal(gentity_t *goal, float rating) { NPCS.NPCInfo->goalEntity = goal; -// NPCInfo->goalEntityNeed = rating; + // NPCInfo->goalEntityNeed = rating; NPCS.NPCInfo->goalTime = level.time; -// NAV_ClearLastRoute(NPC); - if ( goal ) - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); - } - else - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); + // NAV_ClearLastRoute(NPC); + if (goal) { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: %s @ %s (%f)\n", goal->classname, vtos( goal->currentOrigin), rating ); + } else { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: NONE\n" ); } } - /* NPC_SetGoal */ -void NPC_SetGoal( gentity_t *goal, float rating ) -{ - if ( goal == NPCS.NPCInfo->goalEntity ) - { +void NPC_SetGoal(gentity_t *goal, float rating) { + if (goal == NPCS.NPCInfo->goalEntity) { return; } - if ( !goal ) - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); + if (!goal) { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_ERROR, "NPC_SetGoal: NULL goal\n" ); return; } - if ( goal->client ) - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); + if (goal->client) { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_ERROR, "NPC_SetGoal: goal is a client\n" ); return; } - if ( NPCS.NPCInfo->goalEntity ) - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); + if (NPCS.NPCInfo->goalEntity) { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_SetGoal: push %s\n", NPCInfo->goalEntity->classname ); NPCS.NPCInfo->lastGoalEntity = NPCS.NPCInfo->goalEntity; -// NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; + // NPCInfo->lastGoalEntityNeed = NPCInfo->goalEntityNeed; } - SetGoal( goal, rating ); + SetGoal(goal, rating); } - /* NPC_ClearGoal */ -void NPC_ClearGoal( void ) -{ - gentity_t *goal; +void NPC_ClearGoal(void) { + gentity_t *goal; - if ( !NPCS.NPCInfo->lastGoalEntity ) - { - SetGoal( NULL, 0.0 ); + if (!NPCS.NPCInfo->lastGoalEntity) { + SetGoal(NULL, 0.0); return; } goal = NPCS.NPCInfo->lastGoalEntity; NPCS.NPCInfo->lastGoalEntity = NULL; -// NAV_ClearLastRoute(NPC); - if ( goal->inuse && !(goal->s.eFlags & EF_NODRAW) ) - { -// Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); - SetGoal( goal, 0 );//, NPCInfo->lastGoalEntityNeed + // NAV_ClearLastRoute(NPC); + if (goal->inuse && !(goal->s.eFlags & EF_NODRAW)) { + // Debug_NPCPrintf( NPC, d_npcai, DEBUG_LEVEL_INFO, "NPC_ClearGoal: pop %s\n", goal->classname ); + SetGoal(goal, 0); //, NPCInfo->lastGoalEntityNeed return; } - SetGoal( NULL, 0.0 ); + SetGoal(NULL, 0.0); } /* @@ -113,143 +99,140 @@ G_BoundsOverlap ------------------------- */ -qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) -{//NOTE: flush up against counts as overlapping - if(mins1[0]>maxs2[0]) +qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2) { // NOTE: flush up against counts as overlapping + if (mins1[0] > maxs2[0]) return qfalse; - if(mins1[1]>maxs2[1]) + if (mins1[1] > maxs2[1]) return qfalse; - if(mins1[2]>maxs2[2]) + if (mins1[2] > maxs2[2]) return qfalse; - if(maxs1[0]goalTime = level.time; -//MCG - Begin + // MCG - Begin NPCS.NPCInfo->aiFlags &= ~NPCAI_MOVING; NPCS.ucmd.forwardmove = 0; - //Return that the goal was reached - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV ); -//MCG - End + // Return that the goal was reached + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_MOVE_NAV); + // MCG - End } /* ReachedGoal id removed checks against waypoints and is now checking surfaces */ -//qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, gentity_t *goal, qboolean flying ); -qboolean ReachedGoal( gentity_t *goal ) -{ - //FIXME: For script waypoints, need a special check -/* - int goalWpNum; - vec3_t vec; - //vec3_t angles; - float delta; - - if ( goal->flags & FL_NAVGOAL ) - {//waypoint_navgoal - return NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, goal, FlyingCreature( NPC ) ); - } +// qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, gentity_t *goal, qboolean flying ); +qboolean ReachedGoal(gentity_t *goal) { + // FIXME: For script waypoints, need a special check + /* + int goalWpNum; + vec3_t vec; + //vec3_t angles; + float delta; + + if ( goal->flags & FL_NAVGOAL ) + {//waypoint_navgoal + return NAV_HitNavGoal( NPC->currentOrigin, NPC->mins, NPC->maxs, goal, FlyingCreature( NPC ) ); + } - if ( goal == NPCInfo->tempGoal && !(goal->flags & FL_NAVGOAL)) - {//MUST touch waypoints, even if moving to it - //This is odd, it just checks to see if they are on the same - //surface and the tempGoal in in the FOV - does NOT check distance! - // are we on same surface? + if ( goal == NPCInfo->tempGoal && !(goal->flags & FL_NAVGOAL)) + {//MUST touch waypoints, even if moving to it + //This is odd, it just checks to see if they are on the same + //surface and the tempGoal in in the FOV - does NOT check distance! + // are we on same surface? - //FIXME: NPC->waypoint reset every frame, need to find it first - //Should we do that here? (Still will do it only once per frame) - if ( NPC->waypoint >= 0 && NPC->waypoint < num_waypoints ) - { - goalWpNum = NAV_FindWaypointAt ( goal->currentOrigin ); - if ( NPC->waypoint != goalWpNum ) + //FIXME: NPC->waypoint reset every frame, need to find it first + //Should we do that here? (Still will do it only once per frame) + if ( NPC->waypoint >= 0 && NPC->waypoint < num_waypoints ) + { + goalWpNum = NAV_FindWaypointAt ( goal->currentOrigin ); + if ( NPC->waypoint != goalWpNum ) + { + return qfalse; + } + } + + VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); + //Who cares if it's in our FOV?! + /* + // is it in our FOV + vectoangles ( vec, angles ); + delta = AngleDelta ( NPC->client->ps.viewangles[YAW], angles[YAW] ); + if ( fabs ( delta ) > NPCInfo->stats.hfov ) { return qfalse; } - } + */ - VectorSubtract ( NPCInfo->tempGoal->currentOrigin, NPC->currentOrigin, vec); - //Who cares if it's in our FOV?! - /* - // is it in our FOV - vectoangles ( vec, angles ); - delta = AngleDelta ( NPC->client->ps.viewangles[YAW], angles[YAW] ); - if ( fabs ( delta ) > NPCInfo->stats.hfov ) + /* + //If in the same waypoint as tempGoal, we're there, right? + if ( goal->waypoint >= 0 && goal->waypoint < num_waypoints ) + { + if ( NPC->waypoint == goal->waypoint ) { - return qfalse; + return qtrue; } - */ + } + */ - /* - //If in the same waypoint as tempGoal, we're there, right? - if ( goal->waypoint >= 0 && goal->waypoint < num_waypoints ) - { - if ( NPC->waypoint == goal->waypoint ) - { + /* + if ( VectorLengthSquared( vec ) < (64*64) ) + {//Close enough return qtrue; } - } - */ -/* - if ( VectorLengthSquared( vec ) < (64*64) ) - {//Close enough - return qtrue; + return qfalse; } - - return qfalse; - } -*/ - if ( NPCS.NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL ) - { + */ + if (NPCS.NPCInfo->aiFlags & NPCAI_TOUCHED_GOAL) { NPCS.NPCInfo->aiFlags &= ~NPCAI_TOUCHED_GOAL; return qtrue; } -/* - if ( goal->s.eFlags & EF_NODRAW ) - { - goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); - if ( NPC->waypoint == goalWpNum ) + /* + if ( goal->s.eFlags & EF_NODRAW ) { - return qtrue; + goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); + if ( NPC->waypoint == goalWpNum ) + { + return qtrue; + } + return qfalse; } - return qfalse; - } - if(goal->client && goal->health <= 0) - {//trying to get to dead guy - goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); - if ( NPC->waypoint == goalWpNum ) - { - VectorSubtract(NPC->currentOrigin, goal->currentOrigin, vec); - vec[2] = 0; - delta = VectorLengthSquared(vec); - if(delta <= 800) - {//with 20-30 of other guy's origin - return qtrue; + if(goal->client && goal->health <= 0) + {//trying to get to dead guy + goalWpNum = NAV_FindWaypointAt( goal->currentOrigin ); + if ( NPC->waypoint == goalWpNum ) + { + VectorSubtract(NPC->currentOrigin, goal->currentOrigin, vec); + vec[2] = 0; + delta = VectorLengthSquared(vec); + if(delta <= 800) + {//with 20-30 of other guy's origin + return qtrue; + } } } - } -*/ - return NAV_HitNavGoal( NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, goal->r.currentOrigin, NPCS.NPCInfo->goalRadius, FlyingCreature( NPCS.NPC ) ); + */ + return NAV_HitNavGoal(NPCS.NPC->r.currentOrigin, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, goal->r.currentOrigin, NPCS.NPCInfo->goalRadius, + FlyingCreature(NPCS.NPC)); } /* @@ -262,28 +245,24 @@ In fact, doesn't seem to be any waypoint info on entities at all any more? MCG - Since goal is ALWAYS goalEntity, took out a lot of sending goal entity pointers around for no reason */ -gentity_t *UpdateGoal( void ) -{ - gentity_t *goal; +gentity_t *UpdateGoal(void) { + gentity_t *goal; - if ( !NPCS.NPCInfo->goalEntity ) - { + if (!NPCS.NPCInfo->goalEntity) { return NULL; } - if ( !NPCS.NPCInfo->goalEntity->inuse ) - {//Somehow freed it, but didn't clear it + if (!NPCS.NPCInfo->goalEntity->inuse) { // Somehow freed it, but didn't clear it NPC_ClearGoal(); return NULL; } goal = NPCS.NPCInfo->goalEntity; - if ( ReachedGoal( goal ) ) - { + if (ReachedGoal(goal)) { NPC_ReachedGoal(); - goal = NULL;//so they don't keep trying to move to it - }//else if fail, need to tell script so? + goal = NULL; // so they don't keep trying to move to it + } // else if fail, need to tell script so? return goal; } diff --git a/codemp/game/NPC_misc.c b/codemp/game/NPC_misc.c index 9a06391a90..b9c641c161 100644 --- a/codemp/game/NPC_misc.c +++ b/codemp/game/NPC_misc.c @@ -29,11 +29,10 @@ along with this program; if not, see . /* Debug_Printf */ -void Debug_Printf (vmCvar_t *cv, int debugLevel, char *fmt, ...) -{ - char *color; - va_list argptr; - char msg[1024]; +void Debug_Printf(vmCvar_t *cv, int debugLevel, char *fmt, ...) { + char *color; + va_list argptr; + char msg[1024]; if (cv->value < debugLevel) return; @@ -47,32 +46,29 @@ void Debug_Printf (vmCvar_t *cv, int debugLevel, char *fmt, ...) else // if (debugLevel == DEBUG_LEVEL_ERROR) color = S_COLOR_RED; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf(msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_end(argptr); Com_Printf("%s%5i:%s", color, level.time, msg); } - /* Debug_NPCPrintf */ -void Debug_NPCPrintf (gentity_t *printNPC, vmCvar_t *cv, int debugLevel, char *fmt, ...) -{ - int color; - va_list argptr; - char msg[1024]; +void Debug_NPCPrintf(gentity_t *printNPC, vmCvar_t *cv, int debugLevel, char *fmt, ...) { + int color; + va_list argptr; + char msg[1024]; - if (cv->value < debugLevel) - { + if (cv->value < debugLevel) { return; } -// if ( debugNPCName.string[0] && Q_stricmp( debugNPCName.string, printNPC->targetname) != 0 ) -// { -// return; -// } + // if ( debugNPCName.string[0] && Q_stricmp( debugNPCName.string, printNPC->targetname) != 0 ) + // { + // return; + // } if (debugLevel == DEBUG_LEVEL_DETAIL) color = COLOR_WHITE; @@ -83,9 +79,9 @@ void Debug_NPCPrintf (gentity_t *printNPC, vmCvar_t *cv, int debugLevel, char *f else // if (debugLevel == DEBUG_LEVEL_ERROR) color = COLOR_RED; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf(msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_end(argptr); - Com_Printf ("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); + Com_Printf("%c%c%5i (%s) %s", Q_COLOR_ESCAPE, color, level.time, printNPC->targetname, msg); } diff --git a/codemp/game/NPC_move.c b/codemp/game/NPC_move.c index 5809909167..aa6f5b1601 100644 --- a/codemp/game/NPC_move.c +++ b/codemp/game/NPC_move.c @@ -27,16 +27,16 @@ along with this program; if not, see . #include "g_nav.h" #include "anims.h" -void G_Cylinder( vec3_t start, vec3_t end, float radius, vec3_t color ); +void G_Cylinder(vec3_t start, vec3_t end, float radius, vec3_t color); qboolean G_BoundsOverlap(const vec3_t mins1, const vec3_t maxs1, const vec3_t mins2, const vec3_t maxs2); -int NAV_Steer( gentity_t *self, vec3_t dir, float distance ); -extern int GetTime ( int lastTime ); +int NAV_Steer(gentity_t *self, vec3_t dir, float distance); +extern int GetTime(int lastTime); -navInfo_t frameNavInfo; -extern qboolean FlyingCreature( gentity_t *ent ); +navInfo_t frameNavInfo; +extern qboolean FlyingCreature(gentity_t *ent); -extern qboolean PM_InKnockDown( playerState_t *ps ); +extern qboolean PM_InKnockDown(playerState_t *ps); /* ------------------------- @@ -44,44 +44,39 @@ NPC_ClearPathToGoal ------------------------- */ -qboolean NPC_ClearPathToGoal( vec3_t dir, gentity_t *goal ) -{ - trace_t trace; +qboolean NPC_ClearPathToGoal(vec3_t dir, gentity_t *goal) { + trace_t trace; float radius, dist, tFrac; - //FIXME: What does do about area portals? THIS IS BROKEN - //if ( trap->inPVS( NPC->r.currentOrigin, goal->r.currentOrigin ) == qfalse ) + // FIXME: What does do about area portals? THIS IS BROKEN + // if ( trap->inPVS( NPC->r.currentOrigin, goal->r.currentOrigin ) == qfalse ) // return qfalse; - //Look ahead and see if we're clear to move to our goal position - if ( NAV_CheckAhead( NPCS.NPC, goal->r.currentOrigin, &trace, ( NPCS.NPC->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - //VectorSubtract( goal->r.currentOrigin, NPC->r.currentOrigin, dir ); + // Look ahead and see if we're clear to move to our goal position + if (NAV_CheckAhead(NPCS.NPC, goal->r.currentOrigin, &trace, (NPCS.NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + // VectorSubtract( goal->r.currentOrigin, NPC->r.currentOrigin, dir ); return qtrue; } - if (!FlyingCreature(NPCS.NPC)) - { - //See if we're too far above - if ( fabs( NPCS.NPC->r.currentOrigin[2] - goal->r.currentOrigin[2] ) > 48 ) + if (!FlyingCreature(NPCS.NPC)) { + // See if we're too far above + if (fabs(NPCS.NPC->r.currentOrigin[2] - goal->r.currentOrigin[2]) > 48) return qfalse; } - //This is a work around - radius = ( NPCS.NPC->r.maxs[0] > NPCS.NPC->r.maxs[1] ) ? NPCS.NPC->r.maxs[0] : NPCS.NPC->r.maxs[1]; - dist = Distance( NPCS.NPC->r.currentOrigin, goal->r.currentOrigin ); - tFrac = 1.0f - ( radius / dist ); + // This is a work around + radius = (NPCS.NPC->r.maxs[0] > NPCS.NPC->r.maxs[1]) ? NPCS.NPC->r.maxs[0] : NPCS.NPC->r.maxs[1]; + dist = Distance(NPCS.NPC->r.currentOrigin, goal->r.currentOrigin); + tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) + if (trace.fraction >= tFrac) return qtrue; - //See if we're looking for a navgoal - if ( goal->flags & FL_NAVGOAL ) - { - //Okay, didn't get all the way there, let's see if we got close enough: - if ( NAV_HitNavGoal( trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, goal->r.currentOrigin, NPCS.NPCInfo->goalRadius, FlyingCreature( NPCS.NPC ) ) ) - { - //VectorSubtract(goal->r.currentOrigin, NPC->r.currentOrigin, dir); + // See if we're looking for a navgoal + if (goal->flags & FL_NAVGOAL) { + // Okay, didn't get all the way there, let's see if we got close enough: + if (NAV_HitNavGoal(trace.endpos, NPCS.NPC->r.mins, NPCS.NPC->r.maxs, goal->r.currentOrigin, NPCS.NPCInfo->goalRadius, FlyingCreature(NPCS.NPC))) { + // VectorSubtract(goal->r.currentOrigin, NPC->r.currentOrigin, dir); return qtrue; } } @@ -95,18 +90,14 @@ NPC_CheckCombatMove ------------------------- */ -static QINLINE qboolean NPC_CheckCombatMove( void ) -{ - //return NPCInfo->combatMove; - if ( ( NPCS.NPCInfo->goalEntity && NPCS.NPC->enemy && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy ) || ( NPCS.NPCInfo->combatMove ) ) - { +static QINLINE qboolean NPC_CheckCombatMove(void) { + // return NPCInfo->combatMove; + if ((NPCS.NPCInfo->goalEntity && NPCS.NPC->enemy && NPCS.NPCInfo->goalEntity == NPCS.NPC->enemy) || (NPCS.NPCInfo->combatMove)) { return qtrue; } - if ( NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->watchTarget ) - { - if ( NPCS.NPCInfo->goalEntity != NPCS.NPCInfo->watchTarget ) - { + if (NPCS.NPCInfo->goalEntity && NPCS.NPCInfo->watchTarget) { + if (NPCS.NPCInfo->goalEntity != NPCS.NPCInfo->watchTarget) { return qtrue; } } @@ -120,19 +111,17 @@ NPC_LadderMove ------------------------- */ -static void NPC_LadderMove( vec3_t dir ) -{ - //FIXME: this doesn't guarantee we're facing ladder - //ALSO: Need to be able to get off at top - //ALSO: Need to play an anim - //ALSO: Need transitionary anims? +static void NPC_LadderMove(vec3_t dir) { + // FIXME: this doesn't guarantee we're facing ladder + // ALSO: Need to be able to get off at top + // ALSO: Need to play an anim + // ALSO: Need transitionary anims? - if ( ( dir[2] > 0 ) || ( dir[2] < 0 && NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE ) ) - { - //Set our movement direction + if ((dir[2] > 0) || (dir[2] < 0 && NPCS.NPC->client->ps.groundEntityNum == ENTITYNUM_NONE)) { + // Set our movement direction NPCS.ucmd.upmove = (dir[2] > 0) ? 127 : -127; - //Don't move around on XY + // Don't move around on XY NPCS.ucmd.forwardmove = NPCS.ucmd.rightmove = 0; } } @@ -143,19 +132,18 @@ NPC_GetMoveInformation ------------------------- */ -static QINLINE qboolean NPC_GetMoveInformation( vec3_t dir, float *distance ) -{ - //NOTENOTE: Use path stacks! +static QINLINE qboolean NPC_GetMoveInformation(vec3_t dir, float *distance) { + // NOTENOTE: Use path stacks! - //Make sure we have somewhere to go - if ( NPCS.NPCInfo->goalEntity == NULL ) + // Make sure we have somewhere to go + if (NPCS.NPCInfo->goalEntity == NULL) return qfalse; - //Get our move info - VectorSubtract( NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir ); - *distance = VectorNormalize( dir ); + // Get our move info + VectorSubtract(NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPC->r.currentOrigin, dir); + *distance = VectorNormalize(dir); - VectorCopy( NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPCInfo->blockedDest ); + VectorCopy(NPCS.NPCInfo->goalEntity->r.currentOrigin, NPCS.NPCInfo->blockedDest); return qtrue; } @@ -166,10 +154,7 @@ NAV_GetLastMove ------------------------- */ -void NAV_GetLastMove( navInfo_t *info ) -{ - *info = frameNavInfo; -} +void NAV_GetLastMove(navInfo_t *info) { *info = frameNavInfo; } /* ------------------------- @@ -177,40 +162,36 @@ NPC_GetMoveDirection ------------------------- */ -qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) -{ - vec3_t angles; +qboolean NPC_GetMoveDirection(vec3_t out, float *distance) { + vec3_t angles; - //Clear the struct - memset( &frameNavInfo, 0, sizeof( frameNavInfo ) ); + // Clear the struct + memset(&frameNavInfo, 0, sizeof(frameNavInfo)); - //Get our movement, if any - if ( NPC_GetMoveInformation( frameNavInfo.direction, &frameNavInfo.distance ) == qfalse ) + // Get our movement, if any + if (NPC_GetMoveInformation(frameNavInfo.direction, &frameNavInfo.distance) == qfalse) return qfalse; - //Setup the return value + // Setup the return value *distance = frameNavInfo.distance; - //For starters - VectorCopy( frameNavInfo.direction, frameNavInfo.pathDirection ); + // For starters + VectorCopy(frameNavInfo.direction, frameNavInfo.pathDirection); - //If on a ladder, move appropriately - if ( NPCS.NPC->watertype & CONTENTS_LADDER ) - { - NPC_LadderMove( frameNavInfo.direction ); + // If on a ladder, move appropriately + if (NPCS.NPC->watertype & CONTENTS_LADDER) { + NPC_LadderMove(frameNavInfo.direction); return qtrue; } - //Attempt a straight move to goal - if ( NPC_ClearPathToGoal( frameNavInfo.direction, NPCS.NPCInfo->goalEntity ) == qfalse ) - { - //See if we're just stuck - if ( NAV_MoveToGoal( NPCS.NPC, &frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + // Attempt a straight move to goal + if (NPC_ClearPathToGoal(frameNavInfo.direction, NPCS.NPCInfo->goalEntity) == qfalse) { + // See if we're just stuck + if (NAV_MoveToGoal(NPCS.NPC, &frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } @@ -218,22 +199,19 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) frameNavInfo.flags |= NIF_MACRO_NAV; } - //Avoid any collisions on the way - if ( NAV_AvoidCollision( NPCS.NPC, NPCS.NPCInfo->goalEntity, &frameNavInfo ) == qfalse ) - { - //FIXME: Emit a warning, this is a worst case scenario - //FIXME: if we have a clear path to our goal (exluding bodies), but then this + // Avoid any collisions on the way + if (NAV_AvoidCollision(NPCS.NPC, NPCS.NPCInfo->goalEntity, &frameNavInfo) == qfalse) { + // FIXME: Emit a warning, this is a worst case scenario + // FIXME: if we have a clear path to our goal (exluding bodies), but then this // check (against bodies only) fails, shouldn't we fall back // to macro navigation? Like so: - if ( !(frameNavInfo.flags&NIF_MACRO_NAV) ) - {//we had a clear path to goal and didn't try macro nav, but can't avoid collision so try macro nav here - //See if we're just stuck - if ( NAV_MoveToGoal( NPCS.NPC, &frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + if (!(frameNavInfo.flags & NIF_MACRO_NAV)) { // we had a clear path to goal and didn't try macro nav, but can't avoid collision so try macro nav here + // See if we're just stuck + if (NAV_MoveToGoal(NPCS.NPC, &frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } @@ -242,8 +220,8 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) } } - //Setup the return values - VectorCopy( frameNavInfo.direction, out ); + // Setup the return values + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qtrue; @@ -254,122 +232,103 @@ qboolean NPC_GetMoveDirection( vec3_t out, float *distance ) NPC_GetMoveDirectionAltRoute ------------------------- */ -extern int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t *info ); -extern qboolean NAVNEW_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t *info, qboolean setBlockedInfo, int blockedMovesLimit ); -qboolean NPC_GetMoveDirectionAltRoute( vec3_t out, float *distance, qboolean tryStraight ) -{ - vec3_t angles; +extern int NAVNEW_MoveToGoal(gentity_t *self, navInfo_t *info); +extern qboolean NAVNEW_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t *info, qboolean setBlockedInfo, int blockedMovesLimit); +qboolean NPC_GetMoveDirectionAltRoute(vec3_t out, float *distance, qboolean tryStraight) { + vec3_t angles; NPCS.NPCInfo->aiFlags &= ~NPCAI_BLOCKED; - //Clear the struct - memset( &frameNavInfo, 0, sizeof( frameNavInfo ) ); + // Clear the struct + memset(&frameNavInfo, 0, sizeof(frameNavInfo)); - //Get our movement, if any - if ( NPC_GetMoveInformation( frameNavInfo.direction, &frameNavInfo.distance ) == qfalse ) + // Get our movement, if any + if (NPC_GetMoveInformation(frameNavInfo.direction, &frameNavInfo.distance) == qfalse) return qfalse; - //Setup the return value + // Setup the return value *distance = frameNavInfo.distance; - //For starters - VectorCopy( frameNavInfo.direction, frameNavInfo.pathDirection ); + // For starters + VectorCopy(frameNavInfo.direction, frameNavInfo.pathDirection); - //If on a ladder, move appropriately - if ( NPCS.NPC->watertype & CONTENTS_LADDER ) - { - NPC_LadderMove( frameNavInfo.direction ); + // If on a ladder, move appropriately + if (NPCS.NPC->watertype & CONTENTS_LADDER) { + NPC_LadderMove(frameNavInfo.direction); return qtrue; } - //Attempt a straight move to goal - if ( !tryStraight || NPC_ClearPathToGoal( frameNavInfo.direction, NPCS.NPCInfo->goalEntity ) == qfalse ) - {//blocked - //Can't get straight to goal, use macro nav - if ( NAVNEW_MoveToGoal( NPCS.NPC, &frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + // Attempt a straight move to goal + if (!tryStraight || NPC_ClearPathToGoal(frameNavInfo.direction, NPCS.NPCInfo->goalEntity) == qfalse) { // blocked + // Can't get straight to goal, use macro nav + if (NAVNEW_MoveToGoal(NPCS.NPC, &frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } - //else we are on our way + // else we are on our way frameNavInfo.flags |= NIF_MACRO_NAV; - } - else - {//we have no architectural problems, see if there are ents inthe way and try to go around them - //not blocked - if ( d_altRoutes.integer ) - {//try macro nav - navInfo_t tempInfo; - memcpy( &tempInfo, &frameNavInfo, sizeof( tempInfo ) ); - if ( NAVNEW_AvoidCollision( NPCS.NPC, NPCS.NPCInfo->goalEntity, &tempInfo, qtrue, 5 ) == qfalse ) - {//revert to macro nav - //Can't get straight to goal, dump tempInfo and use macro nav - if ( NAVNEW_MoveToGoal( NPCS.NPC, &frameNavInfo ) == WAYPOINT_NONE ) - { - //Can't reach goal, just face - vectoangles( frameNavInfo.direction, angles ); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - VectorCopy( frameNavInfo.direction, out ); + } else { // we have no architectural problems, see if there are ents inthe way and try to go around them + // not blocked + if (d_altRoutes.integer) { // try macro nav + navInfo_t tempInfo; + memcpy(&tempInfo, &frameNavInfo, sizeof(tempInfo)); + if (NAVNEW_AvoidCollision(NPCS.NPC, NPCS.NPCInfo->goalEntity, &tempInfo, qtrue, 5) == qfalse) { // revert to macro nav + // Can't get straight to goal, dump tempInfo and use macro nav + if (NAVNEW_MoveToGoal(NPCS.NPC, &frameNavInfo) == WAYPOINT_NONE) { + // Can't reach goal, just face + vectoangles(frameNavInfo.direction, angles); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qfalse; } - //else we are on our way + // else we are on our way frameNavInfo.flags |= NIF_MACRO_NAV; + } else { // otherwise, either clear or can avoid + memcpy(&frameNavInfo, &tempInfo, sizeof(frameNavInfo)); } - else - {//otherwise, either clear or can avoid - memcpy( &frameNavInfo, &tempInfo, sizeof( frameNavInfo ) ); - } - } - else - {//OR: just give up - if ( NAVNEW_AvoidCollision( NPCS.NPC, NPCS.NPCInfo->goalEntity, &frameNavInfo, qtrue, 30 ) == qfalse ) - {//give up + } else { // OR: just give up + if (NAVNEW_AvoidCollision(NPCS.NPC, NPCS.NPCInfo->goalEntity, &frameNavInfo, qtrue, 30) == qfalse) { // give up return qfalse; } } } - //Setup the return values - VectorCopy( frameNavInfo.direction, out ); + // Setup the return values + VectorCopy(frameNavInfo.direction, out); *distance = frameNavInfo.distance; return qtrue; } -void G_UcmdMoveForDir( gentity_t *self, usercmd_t *cmd, vec3_t dir ) -{ - vec3_t forward, right; - float fDot, rDot; +void G_UcmdMoveForDir(gentity_t *self, usercmd_t *cmd, vec3_t dir) { + vec3_t forward, right; + float fDot, rDot; - AngleVectors( self->r.currentAngles, forward, right, NULL ); + AngleVectors(self->r.currentAngles, forward, right, NULL); dir[2] = 0; - VectorNormalize( dir ); - //NPCs cheat and store this directly because converting movement into a ucmd loses precision - VectorCopy( dir, self->client->ps.moveDir ); - - fDot = DotProduct( forward, dir ) * 127.0f; - rDot = DotProduct( right, dir ) * 127.0f; - //Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte - if ( fDot > 127.0f ) - { + VectorNormalize(dir); + // NPCs cheat and store this directly because converting movement into a ucmd loses precision + VectorCopy(dir, self->client->ps.moveDir); + + fDot = DotProduct(forward, dir) * 127.0f; + rDot = DotProduct(right, dir) * 127.0f; + // Must clamp this because DotProduct is not guaranteed to return a number within -1 to 1, and that would be bad when we're shoving this into a signed byte + if (fDot > 127.0f) { fDot = 127.0f; } - if ( fDot < -127.0f ) - { + if (fDot < -127.0f) { fDot = -127.0f; } - if ( rDot > 127.0f ) - { + if (rDot > 127.0f) { rDot = 127.0f; } - if ( rDot < -127.0f ) - { + if (rDot < -127.0f) { rDot = -127.0f; } cmd->forwardmove = floor(fDot); @@ -396,20 +355,18 @@ NPC_MoveToGoal Now assumes goal is goalEntity, was no reason for it to be otherwise ------------------------- */ -#if AI_TIMERS +#if AI_TIMERS extern int navTime; -#endif// AI_TIMERS -qboolean NPC_MoveToGoal( qboolean tryStraight ) -{ - float distance; - vec3_t dir; - -#if AI_TIMERS - int startTime = GetTime(0); -#endif// AI_TIMERS - //If taking full body pain, don't move - if ( PM_InKnockDown( &NPCS.NPC->client->ps ) || ( ( NPCS.NPC->s.legsAnim >= BOTH_PAIN1 ) && ( NPCS.NPC->s.legsAnim <= BOTH_PAIN18 ) ) ) - { +#endif // AI_TIMERS +qboolean NPC_MoveToGoal(qboolean tryStraight) { + float distance; + vec3_t dir; + +#if AI_TIMERS + int startTime = GetTime(0); +#endif // AI_TIMERS + // If taking full body pain, don't move + if (PM_InKnockDown(&NPCS.NPC->client->ps) || ((NPCS.NPC->s.legsAnim >= BOTH_PAIN1) && (NPCS.NPC->s.legsAnim <= BOTH_PAIN18))) { return qtrue; } @@ -419,70 +376,60 @@ qboolean NPC_MoveToGoal( qboolean tryStraight ) return qtrue; } */ - //rwwFIXMEFIXME: emplaced support + // rwwFIXMEFIXME: emplaced support - //FIXME: if can't get to goal & goal is a target (enemy), try to find a waypoint that has line of sight to target, at least? - //Get our movement direction + // FIXME: if can't get to goal & goal is a target (enemy), try to find a waypoint that has line of sight to target, at least? + // Get our movement direction #if 1 - if ( NPC_GetMoveDirectionAltRoute( dir, &distance, tryStraight ) == qfalse ) + if (NPC_GetMoveDirectionAltRoute(dir, &distance, tryStraight) == qfalse) #else - if ( NPC_GetMoveDirection( dir, &distance ) == qfalse ) + if (NPC_GetMoveDirection(dir, &distance) == qfalse) #endif return qfalse; - NPCS.NPCInfo->distToGoal = distance; + NPCS.NPCInfo->distToGoal = distance; - //Convert the move to angles - vectoangles( dir, NPCS.NPCInfo->lastPathAngles ); - if ( (NPCS.ucmd.buttons&BUTTON_WALKING) ) - { + // Convert the move to angles + vectoangles(dir, NPCS.NPCInfo->lastPathAngles); + if ((NPCS.ucmd.buttons & BUTTON_WALKING)) { NPCS.NPC->client->ps.speed = NPCS.NPCInfo->stats.walkSpeed; - } - else - { + } else { NPCS.NPC->client->ps.speed = NPCS.NPCInfo->stats.runSpeed; } - //FIXME: still getting ping-ponging in certain cases... !!! Nav/avoidance error? WTF???!!! - //If in combat move, then move directly towards our goal - if ( NPC_CheckCombatMove() ) - {//keep current facing - G_UcmdMoveForDir( NPCS.NPC, &NPCS.ucmd, dir ); - } - else - {//face our goal - //FIXME: strafe instead of turn if change in dir is small and temporary - NPCS.NPCInfo->desiredPitch = 0.0f; - NPCS.NPCInfo->desiredYaw = AngleNormalize360( NPCS.NPCInfo->lastPathAngles[YAW] ); - - //Pitch towards the goal and also update if flying or swimming - if ( (NPCS.NPC->client->ps.eFlags2&EF2_FLYING) )//moveType == MT_FLYSWIM ) + // FIXME: still getting ping-ponging in certain cases... !!! Nav/avoidance error? WTF???!!! + // If in combat move, then move directly towards our goal + if (NPC_CheckCombatMove()) { // keep current facing + G_UcmdMoveForDir(NPCS.NPC, &NPCS.ucmd, dir); + } else { // face our goal + // FIXME: strafe instead of turn if change in dir is small and temporary + NPCS.NPCInfo->desiredPitch = 0.0f; + NPCS.NPCInfo->desiredYaw = AngleNormalize360(NPCS.NPCInfo->lastPathAngles[YAW]); + + // Pitch towards the goal and also update if flying or swimming + if ((NPCS.NPC->client->ps.eFlags2 & EF2_FLYING)) // moveType == MT_FLYSWIM ) { - NPCS.NPCInfo->desiredPitch = AngleNormalize360( NPCS.NPCInfo->lastPathAngles[PITCH] ); + NPCS.NPCInfo->desiredPitch = AngleNormalize360(NPCS.NPCInfo->lastPathAngles[PITCH]); - if ( dir[2] ) - { + if (dir[2]) { float scale = (dir[2] * distance); - if ( scale > 64 ) - { + if (scale > 64) { scale = 64; - } - else if ( scale < -64 ) - { + } else if (scale < -64) { scale = -64; } NPCS.NPC->client->ps.velocity[2] = scale; - //NPC->client->ps.velocity[2] = (dir[2] > 0) ? 64 : -64; + // NPC->client->ps.velocity[2] = (dir[2] > 0) ? 64 : -64; } } - //Set any final info + // Set any final info NPCS.ucmd.forwardmove = 127; } -#if AI_TIMERS - navTime += GetTime( startTime ); -#endif// AI_TIMERS +#if AI_TIMERS + navTime += GetTime(startTime); +#endif // AI_TIMERS return qtrue; } @@ -493,32 +440,29 @@ void NPC_SlideMoveToGoal( void ) Now assumes goal is goalEntity, if want to use tempGoal, you set that before calling the func ------------------------- */ -qboolean NPC_SlideMoveToGoal( void ) -{ - float saveYaw = NPCS.NPC->client->ps.viewangles[YAW]; +qboolean NPC_SlideMoveToGoal(void) { + float saveYaw = NPCS.NPC->client->ps.viewangles[YAW]; qboolean ret; NPCS.NPCInfo->combatMove = qtrue; - ret = NPC_MoveToGoal( qtrue ); + ret = NPC_MoveToGoal(qtrue); - NPCS.NPCInfo->desiredYaw = saveYaw; + NPCS.NPCInfo->desiredYaw = saveYaw; return ret; } - /* ------------------------- NPC_ApplyRoff ------------------------- */ -void NPC_ApplyRoff(void) -{ - BG_PlayerStateToEntityState( &NPCS.NPC->client->ps, &NPCS.NPC->s, qfalse ); - //VectorCopy ( NPC->r.currentOrigin, NPC->lastOrigin ); - //rwwFIXMEFIXME: Any significance to this? +void NPC_ApplyRoff(void) { + BG_PlayerStateToEntityState(&NPCS.NPC->client->ps, &NPCS.NPC->s, qfalse); + // VectorCopy ( NPC->r.currentOrigin, NPC->lastOrigin ); + // rwwFIXMEFIXME: Any significance to this? // use the precise origin for linking trap->LinkEntity((sharedEntity_t *)NPCS.NPC); diff --git a/codemp/game/NPC_reactions.c b/codemp/game/NPC_reactions.c index 48c60b411d..49b1782615 100644 --- a/codemp/game/NPC_reactions.c +++ b/codemp/game/NPC_reactions.c @@ -20,38 +20,38 @@ along with this program; if not, see . =========================================================================== */ -//NPC_reactions.cpp +// NPC_reactions.cpp #include "b_local.h" #include "anims.h" #include "w_saber.h" -extern qboolean G_CheckForStrongAttackMomentum( gentity_t *self ); -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath ); -extern void cgi_S_StartSound( vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx ); -extern qboolean Q3_TaskIDPending( gentity_t *ent, taskID_t taskType ); -extern qboolean NPC_CheckLookTarget( gentity_t *self ); -extern void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -extern void Jedi_Ambush( gentity_t *self ); +extern qboolean G_CheckForStrongAttackMomentum(gentity_t *self); +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +extern void G_SoundOnEnt(gentity_t *ent, soundChannel_t channel, const char *soundPath); +extern void cgi_S_StartSound(vec3_t origin, int entityNum, int entchannel, sfxHandle_t sfx); +extern qboolean Q3_TaskIDPending(gentity_t *ent, taskID_t taskType); +extern qboolean NPC_CheckLookTarget(gentity_t *self); +extern void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +extern void Jedi_Ambush(gentity_t *self); extern qboolean NPC_SomeoneLookingAtMe(gentity_t *ent); -extern qboolean BG_SaberInSpecialAttack( int anim ); -extern qboolean PM_SpinningSaberAnim( int anim ); -extern qboolean PM_SpinningAnim( int anim ); -extern qboolean PM_InKnockDown( playerState_t *ps ); -extern qboolean BG_FlippingAnim( int anim ); -extern qboolean PM_RollingAnim( int anim ); -extern qboolean PM_InCartwheel( int anim ); -extern qboolean BG_CrouchAnim( int anim ); +extern qboolean BG_SaberInSpecialAttack(int anim); +extern qboolean PM_SpinningSaberAnim(int anim); +extern qboolean PM_SpinningAnim(int anim); +extern qboolean PM_InKnockDown(playerState_t *ps); +extern qboolean BG_FlippingAnim(int anim); +extern qboolean PM_RollingAnim(int anim); +extern qboolean PM_InCartwheel(int anim); +extern qboolean BG_CrouchAnim(int anim); -extern int teamLastEnemyTime[]; +extern int teamLastEnemyTime[]; extern int killPlayerTimer; -//float g_crosshairEntDist = Q3_INFINITE; -//int g_crosshairSameEntTime = 0; -//int g_crosshairEntNum = ENTITYNUM_NONE; -//int g_crosshairEntTime = 0; +// float g_crosshairEntDist = Q3_INFINITE; +// int g_crosshairSameEntTime = 0; +// int g_crosshairEntNum = ENTITYNUM_NONE; +// int g_crosshairEntTime = 0; /* ------------------------- @@ -59,88 +59,81 @@ NPC_CheckAttacker ------------------------- */ -static void NPC_CheckAttacker( gentity_t *other, int mod ) -{ - //FIXME: I don't see anything in here that would stop teammates from taking a teammate +static void NPC_CheckAttacker(gentity_t *other, int mod) { + // FIXME: I don't see anything in here that would stop teammates from taking a teammate // as an enemy. Ideally, there would be code before this to prevent that from // happening, but that is presumptuous. - if ( !VALIDENT( other ) ) + if (!VALIDENT(other)) return; - if ( other == NPCS.NPC ) + if (other == NPCS.NPC) return; - //Don't take a target that doesn't want to be - if ( other->flags & FL_NOTARGET ) + // Don't take a target that doesn't want to be + if (other->flags & FL_NOTARGET) return; -// if ( NPC->svFlags & SVF_LOCKEDENEMY ) -// {//IF LOCKED, CANNOT CHANGE ENEMY!!!!! -// return; -// } - //rwwFIXMEFIXME: support this + // if ( NPC->svFlags & SVF_LOCKEDENEMY ) + // {//IF LOCKED, CANNOT CHANGE ENEMY!!!!! + // return; + // } + // rwwFIXMEFIXME: support this - //If we haven't taken a target, just get mad - if ( NPCS.NPC->enemy == NULL )//was using "other", fixed to NPC + // If we haven't taken a target, just get mad + if (NPCS.NPC->enemy == NULL) // was using "other", fixed to NPC { - G_SetEnemy( NPCS.NPC, other ); + G_SetEnemy(NPCS.NPC, other); return; } - //we have an enemy, see if he's dead - if ( NPCS.NPC->enemy->health <= 0 ) - { - G_ClearEnemy( NPCS.NPC ); - G_SetEnemy( NPCS.NPC, other ); + // we have an enemy, see if he's dead + if (NPCS.NPC->enemy->health <= 0) { + G_ClearEnemy(NPCS.NPC); + G_SetEnemy(NPCS.NPC, other); return; } - //Don't take the same enemy again - if ( other == NPCS.NPC->enemy ) + // Don't take the same enemy again + if (other == NPCS.NPC->enemy) return; - if ( NPCS.NPC->client->ps.weapon == WP_SABER ) - {//I'm a jedi - if ( mod == MOD_SABER ) - {//I was hit by a saber FIXME: what if this was a thrown saber? - //always switch to this enemy if I'm a jedi and hit by another saber - G_ClearEnemy( NPCS.NPC ); - G_SetEnemy( NPCS.NPC, other ); + if (NPCS.NPC->client->ps.weapon == WP_SABER) { // I'm a jedi + if (mod == MOD_SABER) { // I was hit by a saber FIXME: what if this was a thrown saber? + // always switch to this enemy if I'm a jedi and hit by another saber + G_ClearEnemy(NPCS.NPC); + G_SetEnemy(NPCS.NPC, other); return; } } - //OJKFIXME: clientnum 0 - //Special case player interactions - if ( other == &g_entities[0] ) - { - //Account for the skill level to skew the results - float luckThreshold; + // OJKFIXME: clientnum 0 + // Special case player interactions + if (other == &g_entities[0]) { + // Account for the skill level to skew the results + float luckThreshold; - switch ( g_npcspskill.integer ) - { - //Easiest difficulty, mild chance of picking up the player + switch (g_npcspskill.integer) { + // Easiest difficulty, mild chance of picking up the player case 0: luckThreshold = 0.9f; break; - //Medium difficulty, half-half chance of picking up the player + // Medium difficulty, half-half chance of picking up the player case 1: luckThreshold = 0.5f; break; - //Hardest difficulty, always turn on attacking player + // Hardest difficulty, always turn on attacking player case 2: default: luckThreshold = 0.0f; break; } - //Randomly pick up the target - if ( Q_flrand(0.0f, 1.0f) > luckThreshold ) - { - G_ClearEnemy( other ); + // Randomly pick up the target + if (Q_flrand(0.0f, 1.0f) > luckThreshold) { + G_ClearEnemy(other); other->enemy = NPCS.NPC; } @@ -148,16 +141,13 @@ static void NPC_CheckAttacker( gentity_t *other, int mod ) } } -void NPC_SetPainEvent( gentity_t *self ) -{ - if ( !self->NPC || !(self->NPC->aiFlags&NPCAI_DIE_ON_IMPACT) ) - { - //if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) - if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)self, TID_CHAN_VOICE) && self->client) - { - //G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); - G_AddEvent( self, EV_PAIN, floor((float)self->health/self->client->ps.stats[STAT_MAX_HEALTH]*100.0f) ); - //rwwFIXMEFIXME: Do this properly? +void NPC_SetPainEvent(gentity_t *self) { + if (!self->NPC || !(self->NPC->aiFlags & NPCAI_DIE_ON_IMPACT)) { + // if ( !Q3_TaskIDPending( self, TID_CHAN_VOICE ) ) + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)self, TID_CHAN_VOICE) && self->client) { + // G_AddEvent( self, EV_PAIN, floor((float)self->health/self->max_health*100.0f) ); + G_AddEvent(self, EV_PAIN, floor((float)self->health / self->client->ps.stats[STAT_MAX_HEALTH] * 100.0f)); + // rwwFIXMEFIXME: Do this properly? } } } @@ -168,44 +158,40 @@ NPC_GetPainChance ------------------------- */ -float NPC_GetPainChance( gentity_t *self, int damage ) -{ +float NPC_GetPainChance(gentity_t *self, int damage) { float pain_chance; - if ( !self->enemy ) - {//surprised, always take pain + if (!self->enemy) { // surprised, always take pain return 1.0f; } - if (!self->client) - { + if (!self->client) { return 1.0f; } - //if ( damage > self->max_health/2.0f ) - if (damage > self->client->ps.stats[STAT_MAX_HEALTH]/2.0f) - { + // if ( damage > self->max_health/2.0f ) + if (damage > self->client->ps.stats[STAT_MAX_HEALTH] / 2.0f) { return 1.0f; } - pain_chance = (float)(self->client->ps.stats[STAT_MAX_HEALTH]-self->health)/(self->client->ps.stats[STAT_MAX_HEALTH]*2.0f) + (float)damage/(self->client->ps.stats[STAT_MAX_HEALTH]/2.0f); - switch ( g_npcspskill.integer ) - { - case 0: //easy - //return 0.75f; + pain_chance = (float)(self->client->ps.stats[STAT_MAX_HEALTH] - self->health) / (self->client->ps.stats[STAT_MAX_HEALTH] * 2.0f) + + (float)damage / (self->client->ps.stats[STAT_MAX_HEALTH] / 2.0f); + switch (g_npcspskill.integer) { + case 0: // easy + // return 0.75f; break; - case 1://med + case 1: // med pain_chance *= 0.5f; - //return 0.35f; + // return 0.35f; break; - case 2://hard + case 2: // hard default: pain_chance *= 0.1f; - //return 0.05f; + // return 0.05f; break; } - //Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); + // Com_Printf( "%s: %4.2f\n", self->NPC_type, pain_chance ); return pain_chance; } @@ -215,108 +201,78 @@ NPC_ChoosePainAnimation ------------------------- */ -#define MIN_PAIN_TIME 200 +#define MIN_PAIN_TIME 200 -extern int G_PickPainAnim( gentity_t *self, vec3_t point, int damage, int hitLoc ); -void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc, int voiceEvent ) -{ - int pain_anim = -1; - float pain_chance; +extern int G_PickPainAnim(gentity_t *self, vec3_t point, int damage, int hitLoc); +void NPC_ChoosePainAnimation(gentity_t *self, gentity_t *other, vec3_t point, int damage, int mod, int hitLoc, int voiceEvent) { + int pain_anim = -1; + float pain_chance; - //If we've already taken pain, then don't take it again - if ( level.time < self->painDebounceTime && /*mod != MOD_ELECTROCUTE &&*/ mod != MOD_MELEE ) //rwwFIXMEFIXME: MOD_ELECTROCUTE - {//FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? + // If we've already taken pain, then don't take it again + if (level.time < self->painDebounceTime && /*mod != MOD_ELECTROCUTE &&*/ mod != MOD_MELEE) // rwwFIXMEFIXME: MOD_ELECTROCUTE + { // FIXME: if hit while recoving from losing a saber lock, we should still play a pain anim? return; } - if ( self->s.weapon == WP_THERMAL && self->client->ps.weaponTime > 0 ) - {//don't interrupt thermal throwing anim + if (self->s.weapon == WP_THERMAL && self->client->ps.weaponTime > 0) { // don't interrupt thermal throwing anim return; - } - else if ( self->client->NPC_class == CLASS_GALAKMECH ) - { - if ( hitLoc == HL_GENERIC1 ) - {//hit the antenna! + } else if (self->client->NPC_class == CLASS_GALAKMECH) { + if (hitLoc == HL_GENERIC1) { // hit the antenna! pain_chance = 1.0f; - // self->s.powerups |= ( 1 << PW_SHOCKED ); - // self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); - //rwwFIXMEFIXME: support for this - } - // else if ( self->client->ps.powerups[PW_GALAK_SHIELD] ) - // {//shield up - // return; - // } - //rwwFIXMEFIXME: and this - else if ( self->health > 200 && damage < 100 ) - {//have a *lot* of health + // self->s.powerups |= ( 1 << PW_SHOCKED ); + // self->client->ps.powerups[PW_SHOCKED] = level.time + Q_irand( 500, 2500 ); + // rwwFIXMEFIXME: support for this + } + // else if ( self->client->ps.powerups[PW_GALAK_SHIELD] ) + // {//shield up + // return; + // } + // rwwFIXMEFIXME: and this + else if (self->health > 200 && damage < 100) { // have a *lot* of health pain_chance = 0.05f; + } else { // the lower my health and greater the damage, the more likely I am to play a pain anim + pain_chance = (200.0f - self->health) / 100.0f + damage / 50.0f; } - else - {//the lower my health and greater the damage, the more likely I am to play a pain anim - pain_chance = (200.0f-self->health)/100.0f + damage/50.0f; - } - } - else if ( self->client && self->client->playerTeam == NPCTEAM_PLAYER && other && !other->s.number ) - {//ally shot by player always complains + } else if (self->client && self->client->playerTeam == NPCTEAM_PLAYER && other && !other->s.number) { // ally shot by player always complains pain_chance = 1.1f; - } - else - { - if ( other && (other->s.weapon == WP_SABER || /*mod == MOD_ELECTROCUTE ||*/ mod == MOD_CRUSH/*FIXME:MOD_FORCE_GRIP*/ ) ) - { - pain_chance = 1.0f;//always take pain from saber - } - else if ( mod == MOD_MELEE ) - {//higher in rank (skill) we are, less likely we are to be fazed by a punch - pain_chance = 1.0f - ((RANK_CAPTAIN-self->NPC->rank)/(float)RANK_CAPTAIN); - } - else if ( self->client->NPC_class == CLASS_PROTOCOL ) - { + } else { + if (other && (other->s.weapon == WP_SABER || /*mod == MOD_ELECTROCUTE ||*/ mod == MOD_CRUSH /*FIXME:MOD_FORCE_GRIP*/)) { + pain_chance = 1.0f; // always take pain from saber + } else if (mod == MOD_MELEE) { // higher in rank (skill) we are, less likely we are to be fazed by a punch + pain_chance = 1.0f - ((RANK_CAPTAIN - self->NPC->rank) / (float)RANK_CAPTAIN); + } else if (self->client->NPC_class == CLASS_PROTOCOL) { pain_chance = 1.0f; + } else { + pain_chance = NPC_GetPainChance(self, damage); } - else - { - pain_chance = NPC_GetPainChance( self, damage ); - } - if ( self->client->NPC_class == CLASS_DESANN ) - { + if (self->client->NPC_class == CLASS_DESANN) { pain_chance *= 0.5f; } } - //See if we're going to flinch - if ( Q_flrand(0.0f, 1.0f) < pain_chance ) - { + // See if we're going to flinch + if (Q_flrand(0.0f, 1.0f) < pain_chance) { int animLength; - //Pick and play our animation - if ( self->client->ps.fd.forceGripBeingGripped < level.time ) - {//not being force-gripped or force-drained - if ( /*G_CheckForStrongAttackMomentum( self ) //rwwFIXMEFIXME: Is this needed? - ||*/ PM_SpinningAnim( self->client->ps.legsAnim ) - || BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || PM_InKnockDown( &self->client->ps ) - || PM_RollingAnim( self->client->ps.legsAnim ) - || (BG_FlippingAnim( self->client->ps.legsAnim )&&!PM_InCartwheel( self->client->ps.legsAnim )) ) - {//strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain + // Pick and play our animation + if (self->client->ps.fd.forceGripBeingGripped < level.time) { // not being force-gripped or force-drained + if ( /*G_CheckForStrongAttackMomentum( self ) //rwwFIXMEFIXME: Is this needed? + ||*/ + PM_SpinningAnim(self->client->ps.legsAnim) || BG_SaberInSpecialAttack(self->client->ps.torsoAnim) || PM_InKnockDown(&self->client->ps) || + PM_RollingAnim(self->client->ps.legsAnim) || + (BG_FlippingAnim(self->client->ps.legsAnim) && + !PM_InCartwheel(self->client->ps.legsAnim))) { // strong attacks, rolls, knockdowns, flips and spins cannot be interrupted by pain return; - } - else - {//play an anim + } else { // play an anim int parts; - if ( self->client->NPC_class == CLASS_GALAKMECH ) - {//only has 1 for now - //FIXME: never plays this, it seems... + if (self->client->NPC_class == CLASS_GALAKMECH) { // only has 1 for now + // FIXME: never plays this, it seems... pain_anim = BOTH_PAIN1; - } - else if ( mod == MOD_MELEE ) - { - pain_anim = BG_PickAnim( self->localAnimIndex, BOTH_PAIN2, BOTH_PAIN3 ); - } - else if ( self->s.weapon == WP_SABER ) - {//temp HACK: these are the only 2 pain anims that look good when holding a saber - pain_anim = BG_PickAnim( self->localAnimIndex, BOTH_PAIN2, BOTH_PAIN3 ); + } else if (mod == MOD_MELEE) { + pain_anim = BG_PickAnim(self->localAnimIndex, BOTH_PAIN2, BOTH_PAIN3); + } else if (self->s.weapon == WP_SABER) { // temp HACK: these are the only 2 pain anims that look good when holding a saber + pain_anim = BG_PickAnim(self->localAnimIndex, BOTH_PAIN2, BOTH_PAIN3); } /* else if ( mod != MOD_ELECTROCUTE ) @@ -325,38 +281,30 @@ void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, vec3_t point, i } */ - if ( pain_anim == -1 ) - { - pain_anim = BG_PickAnim( self->localAnimIndex, BOTH_PAIN1, BOTH_PAIN18 ); + if (pain_anim == -1) { + pain_anim = BG_PickAnim(self->localAnimIndex, BOTH_PAIN1, BOTH_PAIN18); } - self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1;//next attack must be a quick attack - self->client->ps.saberMove = LS_READY;//don't finish whatever saber move you may have been in + self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; // next attack must be a quick attack + self->client->ps.saberMove = LS_READY; // don't finish whatever saber move you may have been in parts = SETANIM_BOTH; - if ( BG_CrouchAnim( self->client->ps.legsAnim ) || PM_InCartwheel( self->client->ps.legsAnim ) ) - { + if (BG_CrouchAnim(self->client->ps.legsAnim) || PM_InCartwheel(self->client->ps.legsAnim)) { parts = SETANIM_LEGS; } - if (pain_anim != -1) - { - NPC_SetAnim( self, parts, pain_anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (pain_anim != -1) { + NPC_SetAnim(self, parts, pain_anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - if ( voiceEvent != -1 ) - { - G_AddVoiceEvent( self, voiceEvent, Q_irand( 2000, 4000 ) ); - } - else - { - NPC_SetPainEvent( self ); + if (voiceEvent != -1) { + G_AddVoiceEvent(self, voiceEvent, Q_irand(2000, 4000)); + } else { + NPC_SetPainEvent(self); } - } - else - { - G_AddVoiceEvent( self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0 ); + } else { + G_AddVoiceEvent(self, Q_irand(EV_CHOKE1, EV_CHOKE3), 0); } - //Setup the timing for it + // Setup the timing for it /* if ( mod == MOD_ELECTROCUTE ) { @@ -375,10 +323,9 @@ void NPC_ChoosePainAnimation( gentity_t *self, gentity_t *other, vec3_t point, i NPC_Pain =============== */ -void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage) -{ +void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage) { npcteam_t otherTeam = NPCTEAM_FREE; - int voiceEvent = -1; + int voiceEvent = -1; gentity_t *other = attacker; int mod = gPainMOD; int hitLoc = gPainHitLoc; @@ -386,115 +333,93 @@ void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage) VectorCopy(gPainPoint, point); - if ( self->NPC == NULL ) + if (self->NPC == NULL) return; - if ( other == NULL ) + if (other == NULL) return; - //or just remove ->pain in player_die? - if ( self->client->ps.pm_type == PM_DEAD ) + // or just remove ->pain in player_die? + if (self->client->ps.pm_type == PM_DEAD) return; - if ( other == self ) + if (other == self) return; - //MCG: Ignore damage from your own team for now - if ( other->client ) - { + // MCG: Ignore damage from your own team for now + if (other->client) { otherTeam = other->client->playerTeam; - // if ( otherTeam == TEAM_DISGUISE ) - // { - // otherTeam = TEAM_PLAYER; - // } + // if ( otherTeam == TEAM_DISGUISE ) + // { + // otherTeam = TEAM_PLAYER; + // } } - if ( self->client->playerTeam - && other->client - && otherTeam == self->client->playerTeam - /* && (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)*/) - //rwwFIXMEFIXME: Will need modification when player controllable npcs are done - {//hit by a teammate - if ( other != self->enemy && self != other->enemy ) - {//we weren't already enemies - if ( self->enemy || other->enemy + if (self->client->playerTeam && other->client && otherTeam == self->client->playerTeam + /* && (!player->client->ps.viewEntity || other->s.number != player->client->ps.viewEntity)*/) + // rwwFIXMEFIXME: Will need modification when player controllable npcs are done + { // hit by a teammate + if (other != self->enemy && self != other->enemy) { // we weren't already enemies + if (self->enemy || other->enemy //|| (other->s.number&&other->s.number!=player->client->ps.viewEntity) - //rwwFIXMEFIXME: same - - /*|| (!other->s.number&&Q_irand( 0, 3 ))*/ ) - {//if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad (FIXME:accumulate anger+base on diff?) - //FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad - //Still run pain and flee scripts - if ( self->client && self->NPC ) - {//Run any pain instructions - if ( self->health <= (self->client->ps.stats[STAT_MAX_HEALTH]/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { + // rwwFIXMEFIXME: same - } - else// if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + /*|| (!other->s.number&&Q_irand( 0, 3 ))*/) { // if one of us actually has an enemy already, it's okay, just an accident OR wasn't hit by player + // or someone controlled by player OR player hit ally and didn't get 25% chance of getting mad + // (FIXME:accumulate anger+base on diff?) + // FIXME: player should have to do a certain amount of damage to ally or hit them several times to make them mad + // Still run pain and flee scripts + if (self->client && self->NPC) { // Run any pain instructions + if (self->health <= (self->client->ps.stats[STAT_MAX_HEALTH] / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, -1 ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, -1); } } return; - } - else if ( self->NPC && !other->s.number )//should be assumed, but... - {//dammit, stop that! - if ( self->NPC->charmedTime ) - {//mindtricked + } else if (self->NPC && !other->s.number) // should be assumed, but... + { // dammit, stop that! + if (self->NPC->charmedTime) { // mindtricked return; - } - else if ( self->NPC->ffireCount < 3+((2-g_npcspskill.integer)*2) ) - {//not mad enough yet - //Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_npcspskill.integer)*2) ); - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - if ( Q_irand( 0, 1 ) ) - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, EV_FFWARN ); - } - else - { - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, -1 ); + } else if (self->NPC->ffireCount < 3 + ((2 - g_npcspskill.integer) * 2)) { // not mad enough yet + // Com_Printf( "chck: %d < %d\n", self->NPC->ffireCount, 3+((2-g_npcspskill.integer)*2) ); + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + if (Q_irand(0, 1)) { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, EV_FFWARN); + } else { + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, -1); } } return; - } - else if ( G_ActivateBehavior( self, BSET_FFIRE ) ) - {//we have a specific script to run, so do that instead + } else if (G_ActivateBehavior(self, BSET_FFIRE)) { // we have a specific script to run, so do that instead return; - } - else - {//okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and clear any flags that would stop us) + } else { // okay, we're going to turn on our ally, we need to set and lock our enemy and put ourselves in a bstate that lets us attack him (and + // clear any flags that would stop us) self->NPC->blockedSpeechDebounceTime = 0; voiceEvent = EV_FFTURN; self->NPC->behaviorState = self->NPC->tempBehavior = self->NPC->defaultBehavior = BS_DEFAULT; other->flags &= ~FL_NOTARGET; - //self->svFlags &= ~(SVF_IGNORE_ENEMIES|SVF_ICARUS_FREEZE|SVF_NO_COMBAT_SOUNDS); + // self->svFlags &= ~(SVF_IGNORE_ENEMIES|SVF_ICARUS_FREEZE|SVF_NO_COMBAT_SOUNDS); self->r.svFlags &= ~SVF_ICARUS_FREEZE; - G_SetEnemy( self, other ); - //self->svFlags |= SVF_LOCKEDENEMY; //rwwFIXMEFIXME: proper support for these flags. - self->NPC->scriptFlags &= ~(SCF_DONT_FIRE|SCF_CROUCHED|SCF_WALKING|SCF_NO_COMBAT_TALK|SCF_FORCED_MARCH); - self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES|SCF_NO_MIND_TRICK); - //NOTE: we also stop ICARUS altogether - //stop_icarus = qtrue; - //rwwFIXMEFIXME: stop icarus? - if ( !killPlayerTimer ) - { + G_SetEnemy(self, other); + // self->svFlags |= SVF_LOCKEDENEMY; //rwwFIXMEFIXME: proper support for these flags. + self->NPC->scriptFlags &= ~(SCF_DONT_FIRE | SCF_CROUCHED | SCF_WALKING | SCF_NO_COMBAT_TALK | SCF_FORCED_MARCH); + self->NPC->scriptFlags |= (SCF_CHASE_ENEMIES | SCF_NO_MIND_TRICK); + // NOTE: we also stop ICARUS altogether + // stop_icarus = qtrue; + // rwwFIXMEFIXME: stop icarus? + if (!killPlayerTimer) { killPlayerTimer = level.time + 10000; } } @@ -503,40 +428,33 @@ void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage) } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - //Do extra bits - if ( NPCS.NPCInfo->ignorePain == qfalse ) - { - NPCS.NPCInfo->confusionTime = 0;//clear any charm or confusion, regardless - if ( damage != -1 ) - {//-1 == don't play pain anim - //Set our proper pain animation - NPC_ChoosePainAnimation( self, other, point, damage, mod, hitLoc, voiceEvent ); + // Do extra bits + if (NPCS.NPCInfo->ignorePain == qfalse) { + NPCS.NPCInfo->confusionTime = 0; // clear any charm or confusion, regardless + if (damage != -1) { //-1 == don't play pain anim + // Set our proper pain animation + NPC_ChoosePainAnimation(self, other, point, damage, mod, hitLoc, voiceEvent); } - //Check to take a new enemy - if ( NPCS.NPC->enemy != other && NPCS.NPC != other ) - {//not already mad at them - NPC_CheckAttacker( other, mod ); + // Check to take a new enemy + if (NPCS.NPC->enemy != other && NPCS.NPC != other) { // not already mad at them + NPC_CheckAttacker(other, mod); } } - //Attempt to run any pain instructions - if ( self->client && self->NPC ) - { - //FIXME: This needs better heuristics perhaps - if(self->health <= (self->client->ps.stats[STAT_MAX_HEALTH]/3) && G_ActivateBehavior(self, BSET_FLEE) ) - { - } - else //if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) + // Attempt to run any pain instructions + if (self->client && self->NPC) { + // FIXME: This needs better heuristics perhaps + if (self->health <= (self->client->ps.stats[STAT_MAX_HEALTH] / 3) && G_ActivateBehavior(self, BSET_FLEE)) { + } else // if( VALIDSTRING( self->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior(self, BSET_PAIN); } } - //Attempt to fire any paintargets we might have - if( self->paintarget && self->paintarget[0] ) - { + // Attempt to fire any paintargets we might have + if (self->paintarget && self->paintarget[0]) { G_UseTargets2(self, other, self->paintarget); } @@ -548,21 +466,18 @@ void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage) NPC_Touch ------------------------- */ -extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); -void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) -{ +extern qboolean INV_SecurityKeyGive(gentity_t *target, const char *keyname); +void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) { - if(!self->NPC) + if (!self->NPC) return; SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if ( self->message && self->health <= 0 ) - {//I am dead and carrying a key - //if ( other && player && player->health > 0 && other == player ) - if (other && other->client && other->s.number < MAX_CLIENTS) - {//player touched me + if (self->message && self->health <= 0) { // I am dead and carrying a key + // if ( other && player && player->health > 0 && other == player ) + if (other && other->client && other->s.number < MAX_CLIENTS) { // player touched me /* char *text; qboolean keyTaken; @@ -592,7 +507,7 @@ void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) } } */ - //rwwFIXMEFIXME: support for goodie/security keys? + // rwwFIXMEFIXME: support for goodie/security keys? /* if ( keyTaken ) {//remove my key @@ -608,59 +523,48 @@ void NPC_Touch(gentity_t *self, gentity_t *other, trace_t *trace) } } - if ( other->client ) - {//FIXME: if pushing against another bot, both ucmd.rightmove = 127??? - //Except if not facing one another... - if ( other->health > 0 ) - { + if (other->client) { // FIXME: if pushing against another bot, both ucmd.rightmove = 127??? + // Except if not facing one another... + if (other->health > 0) { NPCS.NPCInfo->touchedByPlayer = other; } - if ( other == NPCS.NPCInfo->goalEntity ) - { + if (other == NPCS.NPCInfo->goalEntity) { NPCS.NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } - if( /*!(self->svFlags&SVF_LOCKEDENEMY) && !(self->svFlags&SVF_IGNORE_ENEMIES) &&*/ !(other->flags & FL_NOTARGET) ) - { - if ( self->client->enemyTeam ) - {//See if we bumped into an enemy - if ( other->client->playerTeam == self->client->enemyTeam ) - {//bumped into an enemy - if( NPCS.NPCInfo->behaviorState != BS_HUNT_AND_KILL && !NPCS.NPCInfo->tempBehavior ) - {//MCG - Begin: checking specific BS mode here, this is bad, a HACK - //FIXME: not medics? - if ( NPCS.NPC->enemy != other ) - {//not already mad at them - G_SetEnemy( NPCS.NPC, other ); + if (/*!(self->svFlags&SVF_LOCKEDENEMY) && !(self->svFlags&SVF_IGNORE_ENEMIES) &&*/ !(other->flags & FL_NOTARGET)) { + if (self->client->enemyTeam) { // See if we bumped into an enemy + if (other->client->playerTeam == self->client->enemyTeam) { // bumped into an enemy + if (NPCS.NPCInfo->behaviorState != BS_HUNT_AND_KILL && + !NPCS.NPCInfo->tempBehavior) { // MCG - Begin: checking specific BS mode here, this is bad, a HACK + // FIXME: not medics? + if (NPCS.NPC->enemy != other) { // not already mad at them + G_SetEnemy(NPCS.NPC, other); } - // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; + // NPCInfo->tempBehavior = BS_HUNT_AND_KILL; } } } } - //FIXME: do this if player is moving toward me and with a certain dist? + // FIXME: do this if player is moving toward me and with a certain dist? /* if ( other->s.number == 0 && self->client->playerTeam == other->client->playerTeam ) { VectorAdd( self->client->pushVec, other->client->ps.velocity, self->client->pushVec ); } */ - } - else - {//FIXME: check for SVF_NONNPC_ENEMY flag here? - if ( other->health > 0 ) - { - //if ( NPC->enemy == other && (other->svFlags&SVF_NONNPC_ENEMY) ) - if (0) //rwwFIXMEFIXME: Can probably just check if num < MAX_CLIENTS for non-npc enemy stuff + } else { // FIXME: check for SVF_NONNPC_ENEMY flag here? + if (other->health > 0) { + // if ( NPC->enemy == other && (other->svFlags&SVF_NONNPC_ENEMY) ) + if (0) // rwwFIXMEFIXME: Can probably just check if num < MAX_CLIENTS for non-npc enemy stuff { NPCS.NPCInfo->touchedByPlayer = other; } } - if ( other == NPCS.NPCInfo->goalEntity ) - { + if (other == NPCS.NPCInfo->goalEntity) { NPCS.NPCInfo->aiFlags |= NPCAI_TOUCHED_GOAL; } } @@ -674,37 +578,30 @@ NPC_TempLookTarget ------------------------- */ -void NPC_TempLookTarget( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ) -{ - if ( !self->client ) - { +void NPC_TempLookTarget(gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime) { + if (!self->client) { return; } - if ( (self->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//lookTarget is set by and to the monster that's holding you, no other operations can change that + if ((self->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // lookTarget is set by and to the monster that's holding you, no other operations can change that return; } - if ( !minLookTime ) - { + if (!minLookTime) { minLookTime = 1000; } - if ( !maxLookTime ) - { + if (!maxLookTime) { maxLookTime = 1000; } - if ( !NPC_CheckLookTarget( self ) ) - {//Not already looking at something else - //Look at him for 1 to 3 seconds - NPC_SetLookTarget( self, lookEntNum, level.time + Q_irand( minLookTime, maxLookTime ) ); + if (!NPC_CheckLookTarget(self)) { // Not already looking at something else + // Look at him for 1 to 3 seconds + NPC_SetLookTarget(self, lookEntNum, level.time + Q_irand(minLookTime, maxLookTime)); } } -void NPC_Respond( gentity_t *self, int userNum ) -{ +void NPC_Respond(gentity_t *self, int userNum) { int event = -1; /* @@ -718,242 +615,159 @@ void NPC_Respond( gentity_t *self, int userNum ) } */ - if ( !Q_irand( 0, 1 ) ) - {//set looktarget to them for a second or two - NPC_TempLookTarget( self, userNum, 1000, 3000 ); + if (!Q_irand(0, 1)) { // set looktarget to them for a second or two + NPC_TempLookTarget(self, userNum, 1000, 3000); } - //some last-minute hacked in responses - switch ( self->client->NPC_class ) - { + // some last-minute hacked in responses + switch (self->client->NPC_class) { case CLASS_JAN: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 2 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 2)) { event = EV_SUSPICIOUS4; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_SOUND1; - } - else - { + } else { event = EV_CONFUSE1; } break; case CLASS_LANDO: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 6 ) ) - { + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 1)) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); + } + } else if (!Q_irand(0, 6)) { event = EV_SIGHT2; - } - else if ( !Q_irand( 0, 5 ) ) - { + } else if (!Q_irand(0, 5)) { event = EV_GIVEUP4; - } - else if ( Q_irand( 0, 4 ) > 1 ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else - { - event = Q_irand( EV_JDETECTED1, EV_JDETECTED2 ); + } else if (Q_irand(0, 4) > 1) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else { + event = Q_irand(EV_JDETECTED1, EV_JDETECTED2); } break; case CLASS_LUKE: - if ( self->enemy ) - { + if (self->enemy) { event = EV_COVER1; - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_JEDI: - if ( !self->enemy ) - { + if (!self->enemy) { /* if ( !(self->svFlags&SVF_IGNORE_ENEMIES) && (self->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) && self->client->enemyTeam == TEAM_ENEMY ) */ - if (0) //rwwFIXMEFIXME: support flags! + if (0) // rwwFIXMEFIXME: support flags! { - event = Q_irand( EV_ANGER1, EV_ANGER3 ); - } - else - { - event = Q_irand( EV_TAUNT1, EV_TAUNT2 ); + event = Q_irand(EV_ANGER1, EV_ANGER3); + } else { + event = Q_irand(EV_TAUNT1, EV_TAUNT2); } } break; case CLASS_PRISONER: - if ( self->enemy ) - { - if ( Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); + if (self->enemy) { + if (Q_irand(0, 1)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_REBEL: - if ( self->enemy ) - { - if ( !Q_irand( 0, 2 ) ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); + if (self->enemy) { + if (!Q_irand(0, 2)) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else { + event = Q_irand(EV_DETECTED1, EV_DETECTED5); } - else - { - event = Q_irand( EV_DETECTED1, EV_DETECTED5 ); - } - } - else - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); + } else { + event = Q_irand(EV_SOUND1, EV_SOUND3); } break; case CLASS_BESPIN_COP: - if ( !Q_stricmp( "bespincop", self->NPC_type ) ) - {//variant 1 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); + if (!Q_stricmp("bespincop", self->NPC_type)) { // variant 1 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); - } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT2, EV_SIGHT3 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT2, EV_SIGHT3); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_ESCAPING2; - } - else - { + } else { event = EV_GIVEUP4; } - } - else - {//variant2 - if ( self->enemy ) - { - if ( Q_irand( 0, 9 ) > 6 ) - { - event = Q_irand( EV_CHASE1, EV_CHASE3 ); - } - else if ( Q_irand( 0, 6 ) > 4 ) - { - event = Q_irand( EV_OUTFLANK1, EV_OUTFLANK2 ); - } - else - { - event = Q_irand( EV_COVER1, EV_COVER5 ); + } else { // variant2 + if (self->enemy) { + if (Q_irand(0, 9) > 6) { + event = Q_irand(EV_CHASE1, EV_CHASE3); + } else if (Q_irand(0, 6) > 4) { + event = Q_irand(EV_OUTFLANK1, EV_OUTFLANK2); + } else { + event = Q_irand(EV_COVER1, EV_COVER5); } - } - else if ( !Q_irand( 0, 3 ) ) - { - event = Q_irand( EV_SIGHT1, EV_SIGHT2 ); - } - else if ( !Q_irand( 0, 1 ) ) - { - event = Q_irand( EV_SOUND1, EV_SOUND3 ); - } - else if ( !Q_irand( 0, 2 ) ) - { + } else if (!Q_irand(0, 3)) { + event = Q_irand(EV_SIGHT1, EV_SIGHT2); + } else if (!Q_irand(0, 1)) { + event = Q_irand(EV_SOUND1, EV_SOUND3); + } else if (!Q_irand(0, 2)) { event = EV_LOST1; - } - else if ( !Q_irand( 0, 1 ) ) - { + } else if (!Q_irand(0, 1)) { event = EV_GIVEUP3; - } - else - { + } else { event = EV_CONFUSE1; } } break; - case CLASS_R2D2: // droid - G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav",Q_irand(1, 3)))); + case CLASS_R2D2: // droid + G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/r2d2/misc/r2d2talk0%d.wav", Q_irand(1, 3)))); break; - case CLASS_R5D2: // droid - G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav",Q_irand(1, 4)))); + case CLASS_R5D2: // droid + G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/r5d2/misc/r5talk%d.wav", Q_irand(1, 4)))); break; - case CLASS_MOUSE: // droid - G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav",Q_irand(1, 3)))); + case CLASS_MOUSE: // droid + G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/mouse/misc/mousego%d.wav", Q_irand(1, 3)))); break; - case CLASS_GONK: // droid - G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav",Q_irand(1, 2)))); + case CLASS_GONK: // droid + G_Sound(self, CHAN_AUTO, G_SoundIndex(va("sound/chars/gonk/misc/gonktalk%d.wav", Q_irand(1, 2)))); break; default: break; } - if ( event != -1 ) - { - //hack here because we reuse some "combat" and "extra" sounds - qboolean addFlag = (self->NPC->scriptFlags&SCF_NO_COMBAT_TALK); + if (event != -1) { + // hack here because we reuse some "combat" and "extra" sounds + qboolean addFlag = (self->NPC->scriptFlags & SCF_NO_COMBAT_TALK); self->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; - G_AddVoiceEvent( self, event, 3000 ); + G_AddVoiceEvent(self, event, 3000); - if ( addFlag ) - { + if (addFlag) { self->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; } } @@ -965,33 +779,27 @@ NPC_UseResponse ------------------------- */ -void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) -{ - if ( !self->NPC || !self->client ) - { +void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone) { + if (!self->NPC || !self->client) { return; } - if ( user->s.number >= MAX_CLIENTS ) - {//not used by the player - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->s.number >= MAX_CLIENTS) { // not used by the player + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( user->client && self->client->playerTeam != user->client->playerTeam && self->client->playerTeam != NPCTEAM_NEUTRAL ) - {//only those on the same team react - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); + if (user->client && self->client->playerTeam != user->client->playerTeam && + self->client->playerTeam != NPCTEAM_NEUTRAL) { // only those on the same team react + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); } return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - {//I'm not responding right now + if (self->NPC->blockedSpeechDebounceTime > level.time) { // I'm not responding right now return; } @@ -1004,15 +812,12 @@ void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) } } */ - //rwwFIXMEFIXME: Support for this? + // rwwFIXMEFIXME: Support for this? - if ( useWhenDone ) - { - G_ActivateBehavior( self, BSET_USE ); - } - else - { - NPC_Respond( self, user->s.number ); + if (useWhenDone) { + G_ActivateBehavior(self, BSET_USE); + } else { + NPC_Respond(self, user->s.number); } } @@ -1021,98 +826,83 @@ void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ) NPC_Use ------------------------- */ -extern void Add_Batteries( gentity_t *ent, int *count ); +extern void Add_Batteries(gentity_t *ent, int *count); -void NPC_Use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if (self->client->ps.pm_type == PM_DEAD) - {//or just remove ->pain in player_die? +void NPC_Use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->client->ps.pm_type == PM_DEAD) { // or just remove ->pain in player_die? return; } SaveNPCGlobals(); - SetNPCGlobals( self ); + SetNPCGlobals(self); - if(self->client && self->NPC) - { + if (self->client && self->NPC) { // If this is a vehicle, let the other guy board it. Added 12/14/02 by AReis. - if ( self->client->NPC_class == CLASS_VEHICLE ) - { + if (self->client->NPC_class == CLASS_VEHICLE) { Vehicle_t *pVeh = self->m_pVehicle; - if ( pVeh && pVeh->m_pVehicleInfo ) - { - //if I used myself, eject everyone on me - if ( other == self ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); + if (pVeh && pVeh->m_pVehicleInfo) { + // if I used myself, eject everyone on me + if (other == self) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); } // If other is already riding this vehicle (self), eject him. - else if ( other->s.owner == self->s.number ) - { - pVeh->m_pVehicleInfo->Eject( pVeh, (bgEntity_t *)other, qfalse ); + else if (other->s.owner == self->s.number) { + pVeh->m_pVehicleInfo->Eject(pVeh, (bgEntity_t *)other, qfalse); } // Otherwise board this vehicle. - else - { - pVeh->m_pVehicleInfo->Board( pVeh, (bgEntity_t *)other ); + else { + pVeh->m_pVehicleInfo->Board(pVeh, (bgEntity_t *)other); } } + } else if (Jedi_WaitingAmbush(NPCS.NPC)) { + Jedi_Ambush(NPCS.NPC); } - else if ( Jedi_WaitingAmbush( NPCS.NPC ) ) - { - Jedi_Ambush( NPCS.NPC ); - } - //Run any use instructions - if ( activator && activator->s.number >= 0 && activator->s.number < MAX_CLIENTS && self->client->NPC_class == CLASS_GONK ) - { + // Run any use instructions + if (activator && activator->s.number >= 0 && activator->s.number < MAX_CLIENTS && self->client->NPC_class == CLASS_GONK) { // must be using the gonk, so attempt to give battery power. // NOTE: this will steal up to MAX_BATTERIES for the activator, leaving the residual on the gonk for potential later use. -// Add_Batteries( activator, &self->client->ps.batteryCharge ); - //rwwFIXMEFIXME: support for this? + // Add_Batteries( activator, &self->client->ps.batteryCharge ); + // rwwFIXMEFIXME: support for this? } // Not using MEDICs anymore -/* - if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) - {//Heal me NOW, dammit! - if ( activator->health < activator->client->ps.stats[STAT_MAX_HEALTH] ) - {//person needs help - if ( self->NPC->eventualGoal != activator ) - {//not my current patient already - NPC_TakePatient( activator ); - G_ActivateBehavior( self, BSET_USE ); + /* + if ( self->NPC->behaviorState == BS_MEDIC_HIDE && activator->client ) + {//Heal me NOW, dammit! + if ( activator->health < activator->client->ps.stats[STAT_MAX_HEALTH] ) + {//person needs help + if ( self->NPC->eventualGoal != activator ) + {//not my current patient already + NPC_TakePatient( activator ); + G_ActivateBehavior( self, BSET_USE ); + } + } + else if ( !self->enemy && activator->s.number == 0 && !trap->VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) + {//I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse( self, other, qfalse ); + } } - } - else if ( !self->enemy && activator->s.number == 0 && !trap->VoiceVolume[self->s.number] && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); - } - } -*/ -// else if ( self->behaviorSet[BSET_USE] ) - if ( self->behaviorSet[BSET_USE] ) - { - NPC_UseResponse( self, other, qtrue ); + */ + // else if ( self->behaviorSet[BSET_USE] ) + if (self->behaviorSet[BSET_USE]) { + NPC_UseResponse(self, other, qtrue); } -// else if ( isMedic( self ) ) -// {//Heal me NOW, dammit! -// NPC_TakePatient( activator ); -// } - else if ( activator && !self->enemy - && activator->s.number >= 0 && activator->s.number < MAX_CLIENTS - && !(self->NPC->scriptFlags&SCF_NO_RESPONSE) ) - //rwwFIXMEFIXME: voice volume support? - {//I don't have an enemy and I'm not talking and I was used by the player - NPC_UseResponse( self, other, qfalse ); + // else if ( isMedic( self ) ) + // {//Heal me NOW, dammit! + // NPC_TakePatient( activator ); + // } + else if (activator && !self->enemy && activator->s.number >= 0 && activator->s.number < MAX_CLIENTS && !(self->NPC->scriptFlags & SCF_NO_RESPONSE)) + // rwwFIXMEFIXME: voice volume support? + { // I don't have an enemy and I'm not talking and I was used by the player + NPC_UseResponse(self, other, qfalse); } } RestoreNPCGlobals(); } -void NPC_CheckPlayerAim( void ) -{ - //FIXME: need appropriate dialogue +void NPC_CheckPlayerAim(void) { + // FIXME: need appropriate dialogue /* gentity_t *player = &g_entities[0]; @@ -1128,9 +918,8 @@ void NPC_CheckPlayerAim( void ) */ } -void NPC_CheckAllClear( void ) -{ - //FIXME: need to make this happen only once after losing enemies, not over and over again +void NPC_CheckAllClear(void) { + // FIXME: need to make this happen only once after losing enemies, not over and over again /* if ( NPC->client && !NPC->enemy && level.time - teamLastEnemyTime[NPC->client->playerTeam] > 10000 ) {//Team hasn't seen an enemy in 10 seconds diff --git a/codemp/game/NPC_senses.c b/codemp/game/NPC_senses.c index 1eff5a4192..38894eb334 100644 --- a/codemp/game/NPC_senses.c +++ b/codemp/game/NPC_senses.c @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_senses.cpp +// NPC_senses.cpp #include "b_local.h" @@ -30,26 +30,22 @@ qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore returns true if can see from point 1 to 2, even through glass (1 pane)- doesn't work with portals */ -qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) -{ - trace_t tr; - gentity_t *hit; +qboolean G_ClearLineOfSight(const vec3_t point1, const vec3_t point2, int ignore, int clipmask) { + trace_t tr; + gentity_t *hit; - trap->Trace ( &tr, point1, NULL, NULL, point2, ignore, clipmask, qfalse, 0, 0 ); - if ( tr.fraction == 1.0 ) - { + trap->Trace(&tr, point1, NULL, NULL, point2, ignore, clipmask, qfalse, 0, 0); + if (tr.fraction == 1.0) { return qtrue; } - hit = &g_entities[ tr.entityNum ]; - if(EntIsGlass(hit)) - { - vec3_t newpoint1; + hit = &g_entities[tr.entityNum]; + if (EntIsGlass(hit)) { + vec3_t newpoint1; VectorCopy(tr.endpos, newpoint1); - trap->Trace (&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, qfalse, 0, 0 ); + trap->Trace(&tr, newpoint1, NULL, NULL, point2, hit->s.number, clipmask, qfalse, 0, 0); - if ( tr.fraction == 1.0 ) - { + if (tr.fraction == 1.0) { return qtrue; } } @@ -66,54 +62,49 @@ or take any AI related factors (for example, the NPC's reaction time) into accou FIXME do we need fat and thin version of this? */ -qboolean CanSee ( gentity_t *ent ) -{ - trace_t tr; - vec3_t eyes, spot; +qboolean CanSee(gentity_t *ent) { + trace_t tr; + vec3_t eyes, spot; - CalcEntitySpot( NPCS.NPC, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - trap->Trace ( &tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + trap->Trace(&tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - trap->Trace ( &tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + trap->Trace(&tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - trap->Trace ( &tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0 ); - ShotThroughGlass (&tr, ent, spot, MASK_OPAQUE); - if ( tr.fraction == 1.0 ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + trap->Trace(&tr, eyes, NULL, NULL, spot, NPCS.NPC->s.number, MASK_OPAQUE, qfalse, 0, 0); + ShotThroughGlass(&tr, ent, spot, MASK_OPAQUE); + if (tr.fraction == 1.0) { return qtrue; } return qfalse; } -qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold ) -{ - vec3_t dir, forward, angles; - float dot; +qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold) { + vec3_t dir, forward, angles; + float dot; - VectorSubtract( spot, from, dir ); + VectorSubtract(spot, from, dir); dir[2] = 0; - VectorNormalize( dir ); + VectorNormalize(dir); - VectorCopy( fromAngles, angles ); + VectorCopy(fromAngles, angles); angles[0] = 0; - AngleVectors( angles, forward, NULL, NULL ); + AngleVectors(angles, forward, NULL, NULL); - dot = DotProduct( dir, forward ); + dot = DotProduct(dir, forward); return (dot > threshHold); } @@ -125,121 +116,104 @@ IDEA: further off to side of FOV range, higher chance of failing even if technic keep core of 50% to sides as always succeeding */ -//Position compares +// Position compares -qboolean InFOV3( vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV ) -{ - vec3_t deltaVector, angles, deltaAngles; +qboolean InFOV3(vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV) { + vec3_t deltaVector, angles, deltaAngles; - VectorSubtract ( spot, from, deltaVector ); - vectoangles ( deltaVector, angles ); + VectorSubtract(spot, from, deltaVector); + vectoangles(deltaVector, angles); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -//NPC to position +// NPC to position -qboolean InFOV2( vec3_t origin, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t fromAngles, eyes; +qboolean InFOV2(vec3_t origin, gentity_t *from, int hFOV, int vFOV) { + vec3_t fromAngles, eyes; - if( from->client ) - { + if (from->client) { VectorCopy(from->client->ps.viewangles, fromAngles); - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD, eyes ); + CalcEntitySpot(from, SPOT_HEAD, eyes); - return InFOV3( origin, eyes, fromAngles, hFOV, vFOV ); + return InFOV3(origin, eyes, fromAngles, hFOV, vFOV); } -//Entity to entity - -qboolean InFOV ( gentity_t *ent, gentity_t *from, int hFOV, int vFOV ) -{ - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - vec3_t angles, fromAngles; - vec3_t deltaAngles; - - if( from->client ) - { - if( !VectorCompare( from->client->renderInfo.eyeAngles, vec3_origin ) ) - {//Actual facing of tag_head! - //NOTE: Stasis aliens may have a problem with this? - VectorCopy( from->client->renderInfo.eyeAngles, fromAngles ); +// Entity to entity + +qboolean InFOV(gentity_t *ent, gentity_t *from, int hFOV, int vFOV) { + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + vec3_t angles, fromAngles; + vec3_t deltaAngles; + + if (from->client) { + if (!VectorCompare(from->client->renderInfo.eyeAngles, vec3_origin)) { // Actual facing of tag_head! + // NOTE: Stasis aliens may have a problem with this? + VectorCopy(from->client->renderInfo.eyeAngles, fromAngles); + } else { + VectorCopy(from->client->ps.viewangles, fromAngles); } - else - { - VectorCopy( from->client->ps.viewangles, fromAngles ); - } - } - else - { + } else { VectorCopy(from->s.angles, fromAngles); } - CalcEntitySpot( from, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(from, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_HEAD, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_HEAD, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } - CalcEntitySpot( ent, SPOT_LEGS, spot ); - VectorSubtract ( spot, eyes, deltaVector); - vectoangles ( deltaVector, angles ); - deltaAngles[PITCH] = AngleDelta ( fromAngles[PITCH], angles[PITCH] ); - deltaAngles[YAW] = AngleDelta ( fromAngles[YAW], angles[YAW] ); - if ( fabs ( deltaAngles[PITCH] ) <= vFOV && fabs ( deltaAngles[YAW] ) <= hFOV ) - { + CalcEntitySpot(ent, SPOT_LEGS, spot); + VectorSubtract(spot, eyes, deltaVector); + vectoangles(deltaVector, angles); + deltaAngles[PITCH] = AngleDelta(fromAngles[PITCH], angles[PITCH]); + deltaAngles[YAW] = AngleDelta(fromAngles[YAW], angles[YAW]); + if (fabs(deltaAngles[PITCH]) <= vFOV && fabs(deltaAngles[YAW]) <= hFOV) { return qtrue; } return qfalse; } -qboolean InVisrange ( gentity_t *ent ) -{//FIXME: make a calculate visibility for ents that takes into account - //lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. - vec3_t eyes; - vec3_t spot; - vec3_t deltaVector; - float visrange = (NPCS.NPCInfo->stats.visrange * NPCS.NPCInfo->stats.visrange); +qboolean InVisrange(gentity_t *ent) { // FIXME: make a calculate visibility for ents that takes into account + // lighting, movement, turning, crouch/stand up, other anims, hide brushes, etc. + vec3_t eyes; + vec3_t spot; + vec3_t deltaVector; + float visrange = (NPCS.NPCInfo->stats.visrange * NPCS.NPCInfo->stats.visrange); - CalcEntitySpot( NPCS.NPC, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(NPCS.NPC, SPOT_HEAD_LEAN, eyes); - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); - VectorSubtract ( spot, eyes, deltaVector); + CalcEntitySpot(ent, SPOT_ORIGIN, spot); + VectorSubtract(spot, eyes, deltaVector); /*if(ent->client) { @@ -263,8 +237,7 @@ qboolean InVisrange ( gentity_t *ent ) } }*/ - if(VectorLengthSquared(deltaVector) > visrange) - { + if (VectorLengthSquared(deltaVector) > visrange) { return qfalse; } @@ -275,69 +248,54 @@ qboolean InVisrange ( gentity_t *ent ) NPC_CheckVisibility */ -visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) -{ +visibility_t NPC_CheckVisibility(gentity_t *ent, int flags) { // flags should never be 0 - if ( !flags ) - { + if (!flags) { return VIS_NOT; } // check PVS - if ( flags & CHECK_PVS ) - { - if ( !trap->InPVS ( ent->r.currentOrigin, NPCS.NPC->r.currentOrigin ) ) - { + if (flags & CHECK_PVS) { + if (!trap->InPVS(ent->r.currentOrigin, NPCS.NPC->r.currentOrigin)) { return VIS_NOT; } } - if ( !(flags & (CHECK_360|CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_360 | CHECK_FOV | CHECK_SHOOT))) { return VIS_PVS; } // check within visrange - if (flags & CHECK_VISRANGE) - { - if( !InVisrange ( ent ) ) - { + if (flags & CHECK_VISRANGE) { + if (!InVisrange(ent)) { return VIS_PVS; } } // check 360 degree visibility - //Meaning has to be a direct line of site - if ( flags & CHECK_360 ) - { - if ( !CanSee ( ent ) ) - { + // Meaning has to be a direct line of site + if (flags & CHECK_360) { + if (!CanSee(ent)) { return VIS_PVS; } } - if ( !(flags & (CHECK_FOV|CHECK_SHOOT)) ) - { + if (!(flags & (CHECK_FOV | CHECK_SHOOT))) { return VIS_360; } // check FOV - if ( flags & CHECK_FOV ) - { - if ( !InFOV ( ent, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov) ) - { + if (flags & CHECK_FOV) { + if (!InFOV(ent, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov)) { return VIS_360; } } - if ( !(flags & CHECK_SHOOT) ) - { + if (!(flags & CHECK_SHOOT)) { return VIS_FOV; } // check shootability - if ( flags & CHECK_SHOOT ) - { - if ( !CanShoot ( ent, NPCS.NPC ) ) - { + if (flags & CHECK_SHOOT) { + if (!CanShoot(ent, NPCS.NPC)) { return VIS_FOV; } } @@ -350,53 +308,49 @@ visibility_t NPC_CheckVisibility ( gentity_t *ent, int flags ) NPC_CheckSoundEvents ------------------------- */ -static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - int bestEvent = -1; +static int G_CheckSoundEvents(gentity_t *self, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; + int bestTime = -1; int i; float dist, radius; maxHearDist *= maxHearDist; - for ( i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( i == ignoreAlert ) + for (i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (i == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SOUND ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SOUND) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->r.currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->r.currentOrigin); - //can't hear it - if ( dist > maxHearDist ) + // can't hear it + if (dist > maxHearDist) continue; radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - if ( level.alertEvents[i].addLight ) - {//a quiet sound, must have LOS to hear it - if ( G_ClearLOS5( self, level.alertEvents[i].position ) == qfalse ) - {//no LOS, didn't hear it + if (level.alertEvents[i].addLight) { // a quiet sound, must have LOS to hear it + if (G_ClearLOS5(self, level.alertEvents[i].position) == qfalse) { // no LOS, didn't hear it continue; } } - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -406,17 +360,16 @@ static int G_CheckSoundEvents( gentity_t *self, float maxHearDist, int ignoreAle return bestEvent; } -float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) -{ +float G_GetLightLevel(vec3_t pos, vec3_t fromDir) { /* vec3_t ambient={0}, directed, lightDir; cgi_R_GetLighting( pos, ambient, directed, lightDir ); lightLevel = VectorLength( ambient ) + (VectorLength( directed )*DotProduct( lightDir, fromDir )); */ - float lightLevel; - //rwwFIXMEFIXME: ...this is evil. We can possibly read from the server BSP data, or load the lightmap along - //with collision data and whatnot, but is it worth it? + float lightLevel; + // rwwFIXMEFIXME: ...this is evil. We can possibly read from the server BSP data, or load the lightmap along + // with collision data and whatnot, but is it worth it? lightLevel = 255; return lightLevel; @@ -426,59 +379,57 @@ float G_GetLightLevel( vec3_t pos, vec3_t fromDir ) NPC_CheckSightEvents ------------------------- */ -static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - int bestEvent = -1; +static int G_CheckSightEvents(gentity_t *self, int hFOV, int vFOV, float maxSeeDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + int bestEvent = -1; int bestAlert = -1; - int bestTime = -1; + int bestTime = -1; int i; - float dist, radius; + float dist, radius; maxSeeDist *= maxSeeDist; - for ( i = 0; i < level.numAlertEvents; i++ ) - { - //are we purposely ignoring this alert? - if ( i == ignoreAlert ) + for (i = 0; i < level.numAlertEvents; i++) { + // are we purposely ignoring this alert? + if (i == ignoreAlert) continue; - //We're only concerned about sounds - if ( level.alertEvents[i].type != AET_SIGHT ) + // We're only concerned about sounds + if (level.alertEvents[i].type != AET_SIGHT) continue; - //must be at least this noticable - if ( level.alertEvents[i].level < minAlertLevel ) + // must be at least this noticable + if (level.alertEvents[i].level < minAlertLevel) continue; - //must have an owner? - if ( mustHaveOwner && !level.alertEvents[i].owner ) + // must have an owner? + if (mustHaveOwner && !level.alertEvents[i].owner) continue; - //Must be within range - dist = DistanceSquared( level.alertEvents[i].position, self->r.currentOrigin ); + // Must be within range + dist = DistanceSquared(level.alertEvents[i].position, self->r.currentOrigin); - //can't see it - if ( dist > maxSeeDist ) + // can't see it + if (dist > maxSeeDist) continue; radius = level.alertEvents[i].radius * level.alertEvents[i].radius; - if ( dist > radius ) + if (dist > radius) continue; - //Must be visible - if ( InFOV2( level.alertEvents[i].position, self, hFOV, vFOV ) == qfalse ) + // Must be visible + if (InFOV2(level.alertEvents[i].position, self, hFOV, vFOV) == qfalse) continue; - if ( G_ClearLOS5( self, level.alertEvents[i].position ) == qfalse ) + if (G_ClearLOS5(self, level.alertEvents[i].position) == qfalse) continue; - //FIXME: possibly have the light level at this point affect the + // FIXME: possibly have the light level at this point affect the // visibility/alert level of this event? Would also // need to take into account how bright the event // itself is. A lightsaber would stand out more // in the dark... maybe pass in a light level that // is added to the actual light level at this position? - //See if this one takes precedence over the previous one - if ( level.alertEvents[i].level >= bestAlert //higher alert level - || (level.alertEvents[i].level==bestAlert&&level.alertEvents[i].timestamp >= bestTime) )//same alert level, but this one is newer - {//NOTE: equal is better because it's later in the array + // See if this one takes precedence over the previous one + if (level.alertEvents[i].level >= bestAlert // higher alert level + || (level.alertEvents[i].level == bestAlert && level.alertEvents[i].timestamp >= bestTime)) // same alert level, but this one is newer + { // NOTE: equal is better because it's later in the array bestEvent = i; bestAlert = level.alertEvents[i].level; bestTime = level.alertEvents[i].timestamp; @@ -492,104 +443,89 @@ static int G_CheckSightEvents( gentity_t *self, int hFOV, int vFOV, float maxSee ------------------------- NPC_CheckAlertEvents - NOTE: Should all NPCs create alertEvents too so they can detect each other? + NOTE: Should all NPCs create alertEvents too so they can detect each other? ------------------------- */ -int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ +int G_CheckAlertEvents(gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert, qboolean mustHaveOwner, + int minAlertLevel) { int bestSoundEvent = -1; int bestSightEvent = -1; int bestSoundAlert = -1; int bestSightAlert = -1; - //OJKFIXME: clientnum 0 - if ( &g_entities[0] == NULL || g_entities[0].health <= 0 ) - { - //player is dead + // OJKFIXME: clientnum 0 + if (&g_entities[0] == NULL || g_entities[0].health <= 0) { + // player is dead return -1; } - //get sound event - bestSoundEvent = G_CheckSoundEvents( self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel ); - //get sound event alert level - if ( bestSoundEvent >= 0 ) - { + // get sound event + bestSoundEvent = G_CheckSoundEvents(self, maxHearDist, ignoreAlert, mustHaveOwner, minAlertLevel); + // get sound event alert level + if (bestSoundEvent >= 0) { bestSoundAlert = level.alertEvents[bestSoundEvent].level; } - //get sight event - if ( self->NPC ) - { - bestSightEvent = G_CheckSightEvents( self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel ); - } - else - { - bestSightEvent = G_CheckSightEvents( self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel );//FIXME: look at cg_view to get more accurate numbers? + // get sight event + if (self->NPC) { + bestSightEvent = G_CheckSightEvents(self, self->NPC->stats.hfov, self->NPC->stats.vfov, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); + } else { + bestSightEvent = + G_CheckSightEvents(self, 80, 80, maxSeeDist, ignoreAlert, mustHaveOwner, minAlertLevel); // FIXME: look at cg_view to get more accurate numbers? } - //get sight event alert level - if ( bestSightEvent >= 0 ) - { + // get sight event alert level + if (bestSightEvent >= 0) { bestSightAlert = level.alertEvents[bestSightEvent].level; } - //return the one that has a higher alert (or sound if equal) - //FIXME: This doesn't take the distance of the event into account + // return the one that has a higher alert (or sound if equal) + // FIXME: This doesn't take the distance of the event into account - if ( bestSightEvent >= 0 && bestSightAlert > bestSoundAlert ) - {//valid best sight event, more important than the sound event - //get the light level of the alert event for this checker - vec3_t eyePoint, sightDir; - //get eye point - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyePoint ); - VectorSubtract( level.alertEvents[bestSightEvent].position, eyePoint, sightDir ); - level.alertEvents[bestSightEvent].light = level.alertEvents[bestSightEvent].addLight + G_GetLightLevel( level.alertEvents[bestSightEvent].position, sightDir ); - //return the sight event + if (bestSightEvent >= 0 && bestSightAlert > bestSoundAlert) { // valid best sight event, more important than the sound event + // get the light level of the alert event for this checker + vec3_t eyePoint, sightDir; + // get eye point + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyePoint); + VectorSubtract(level.alertEvents[bestSightEvent].position, eyePoint, sightDir); + level.alertEvents[bestSightEvent].light = + level.alertEvents[bestSightEvent].addLight + G_GetLightLevel(level.alertEvents[bestSightEvent].position, sightDir); + // return the sight event return bestSightEvent; } - //return the sound event + // return the sound event return bestSoundEvent; } -int NPC_CheckAlertEvents( qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel ) -{ - return G_CheckAlertEvents( NPCS.NPC, checkSight, checkSound, NPCS.NPCInfo->stats.visrange, NPCS.NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, minAlertLevel ); +int NPC_CheckAlertEvents(qboolean checkSight, qboolean checkSound, int ignoreAlert, qboolean mustHaveOwner, int minAlertLevel) { + return G_CheckAlertEvents(NPCS.NPC, checkSight, checkSound, NPCS.NPCInfo->stats.visrange, NPCS.NPCInfo->stats.earshot, ignoreAlert, mustHaveOwner, + minAlertLevel); } -qboolean G_CheckForDanger( gentity_t *self, int alertEvent ) -{//FIXME: more bStates need to call this? - if ( alertEvent == -1 ) - { +qboolean G_CheckForDanger(gentity_t *self, int alertEvent) { // FIXME: more bStates need to call this? + if (alertEvent == -1) { return qfalse; } - if ( level.alertEvents[alertEvent].level >= AEL_DANGER ) - {//run away! - if ( !level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || (level.alertEvents[alertEvent].owner!=self&&level.alertEvents[alertEvent].owner->client->playerTeam!=self->client->playerTeam) ) - { - if ( self->NPC ) - { - if ( self->NPC->scriptFlags & SCF_DONT_FLEE ) - {//can't flee + if (level.alertEvents[alertEvent].level >= AEL_DANGER) { // run away! + if (!level.alertEvents[alertEvent].owner || !level.alertEvents[alertEvent].owner->client || + (level.alertEvents[alertEvent].owner != self && level.alertEvents[alertEvent].owner->client->playerTeam != self->client->playerTeam)) { + if (self->NPC) { + if (self->NPC->scriptFlags & SCF_DONT_FLEE) { // can't flee return qfalse; - } - else - { - NPC_StartFlee( level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, 6000 ); + } else { + NPC_StartFlee(level.alertEvents[alertEvent].owner, level.alertEvents[alertEvent].position, level.alertEvents[alertEvent].level, 3000, 6000); return qtrue; } - } - else - { + } else { return qtrue; } } } return qfalse; } -qboolean NPC_CheckForDanger( int alertEvent ) -{//FIXME: more bStates need to call this? - return G_CheckForDanger( NPCS.NPC, alertEvent ); +qboolean NPC_CheckForDanger(int alertEvent) { // FIXME: more bStates need to call this? + return G_CheckForDanger(NPCS.NPC, alertEvent); } /* @@ -597,41 +533,35 @@ qboolean NPC_CheckForDanger( int alertEvent ) AddSoundEvent ------------------------- */ -qboolean RemoveOldestAlert( void ); -void AddSoundEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +qboolean RemoveOldestAlert(void); +void AddSoundEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: if owner is not a player or player ally, and there are no player allies present, + // FIXME: if owner is not a player or player ally, and there are no player allies present, // perhaps we don't need to store the alert... unless we want the player to // react to enemy alert events in some way? - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SOUND; - level.alertEvents[ level.numAlertEvents ].owner = owner; - if ( needLOS ) - {//a very low-level sound, when check this sound event, check for LOS - level.alertEvents[ level.numAlertEvents ].addLight = 1; //will force an LOS trace on this sound + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SOUND; + level.alertEvents[level.numAlertEvents].owner = owner; + if (needLOS) { // a very low-level sound, when check this sound event, check for LOS + level.alertEvents[level.numAlertEvents].addLight = 1; // will force an LOS trace on this sound + } else { + level.alertEvents[level.numAlertEvents].addLight = 0; // will force an LOS trace on this sound } - else - { - level.alertEvents[ level.numAlertEvents ].addLight = 0; //will force an LOS trace on this sound - } - level.alertEvents[ level.numAlertEvents ].ID = level.curAlertID++; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].ID = level.curAlertID++; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -642,33 +572,30 @@ AddSightEvent ------------------------- */ -void AddSightEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight ) -{ - //FIXME: Handle this in another manner? - if ( level.numAlertEvents >= MAX_ALERT_EVENTS ) - { - if ( !RemoveOldestAlert() ) - {//how could that fail? +void AddSightEvent(gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight) { + // FIXME: Handle this in another manner? + if (level.numAlertEvents >= MAX_ALERT_EVENTS) { + if (!RemoveOldestAlert()) { // how could that fail? return; } } - if ( owner == NULL && alertLevel < AEL_DANGER ) //allows un-owned danger alerts + if (owner == NULL && alertLevel < AEL_DANGER) // allows un-owned danger alerts return; - //FIXME: if owner is not a player or player ally, and there are no player allies present, + // FIXME: if owner is not a player or player ally, and there are no player allies present, // perhaps we don't need to store the alert... unless we want the player to // react to enemy alert events in some way? - VectorCopy( position, level.alertEvents[ level.numAlertEvents ].position ); + VectorCopy(position, level.alertEvents[level.numAlertEvents].position); - level.alertEvents[ level.numAlertEvents ].radius = radius; - level.alertEvents[ level.numAlertEvents ].level = alertLevel; - level.alertEvents[ level.numAlertEvents ].type = AET_SIGHT; - level.alertEvents[ level.numAlertEvents ].owner = owner; - level.alertEvents[ level.numAlertEvents ].addLight = addLight; //will get added to actual light at that point when it's checked - level.alertEvents[ level.numAlertEvents ].ID = level.curAlertID++; - level.alertEvents[ level.numAlertEvents ].timestamp = level.time; + level.alertEvents[level.numAlertEvents].radius = radius; + level.alertEvents[level.numAlertEvents].level = alertLevel; + level.alertEvents[level.numAlertEvents].type = AET_SIGHT; + level.alertEvents[level.numAlertEvents].owner = owner; + level.alertEvents[level.numAlertEvents].addLight = addLight; // will get added to actual light at that point when it's checked + level.alertEvents[level.numAlertEvents].ID = level.curAlertID++; + level.alertEvents[level.numAlertEvents].timestamp = level.time; level.numAlertEvents++; } @@ -679,76 +606,61 @@ ClearPlayerAlertEvents ------------------------- */ -void ClearPlayerAlertEvents( void ) -{ +void ClearPlayerAlertEvents(void) { int curNumAlerts = level.numAlertEvents; int i; - //loop through them all (max 32) - for ( i = 0; i < curNumAlerts; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time ) - {//this event has timed out - //drop the count + // loop through them all (max 32) + for (i = 0; i < curNumAlerts; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp && level.alertEvents[i].timestamp + ALERT_CLEAR_TIME < level.time) { // this event has timed out + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (i+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[i], &level.alertEvents[i+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(i+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((i + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[i], &level.alertEvents[i + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (i + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[i], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[i], 0, sizeof(alertEvent_t)); } } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); + // make sure this never drops below zero... if it does, something very very bad happened + assert(level.numAlertEvents >= 0); - if ( eventClearTime < level.time ) - {//this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms + if (eventClearTime < + level.time) { // this is just a 200ms debouncer so things that generate constant alerts (like corpses and missiles) add an alert every 200 ms eventClearTime = level.time + ALERT_CLEAR_TIME; } } -qboolean RemoveOldestAlert( void ) -{ - int oldestEvent = -1, oldestTime = Q3_INFINITE; +qboolean RemoveOldestAlert(void) { + int oldestEvent = -1, oldestTime = Q3_INFINITE; int i; - //loop through them all (max 32) - for ( i = 0; i < level.numAlertEvents; i++ ) - { - //see if the event is old enough to delete - if ( level.alertEvents[i].timestamp < oldestTime ) - { + // loop through them all (max 32) + for (i = 0; i < level.numAlertEvents; i++) { + // see if the event is old enough to delete + if (level.alertEvents[i].timestamp < oldestTime) { oldestEvent = i; oldestTime = level.alertEvents[i].timestamp; } } - if ( oldestEvent != -1 ) - { - //drop the count + if (oldestEvent != -1) { + // drop the count level.numAlertEvents--; - //shift the rest down - if ( level.numAlertEvents > 0 ) - {//still have more in the array - if ( (oldestEvent+1) < MAX_ALERT_EVENTS ) - { - memmove( &level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent+1], sizeof(alertEvent_t)*(MAX_ALERT_EVENTS-(oldestEvent+1) ) ); + // shift the rest down + if (level.numAlertEvents > 0) { // still have more in the array + if ((oldestEvent + 1) < MAX_ALERT_EVENTS) { + memmove(&level.alertEvents[oldestEvent], &level.alertEvents[oldestEvent + 1], sizeof(alertEvent_t) * (MAX_ALERT_EVENTS - (oldestEvent + 1))); } - } - else - {//just clear this one... or should we clear the whole array? - memset( &level.alertEvents[oldestEvent], 0, sizeof( alertEvent_t ) ); + } else { // just clear this one... or should we clear the whole array? + memset(&level.alertEvents[oldestEvent], 0, sizeof(alertEvent_t)); } } - //make sure this never drops below zero... if it does, something very very bad happened - assert( level.numAlertEvents >= 0 ); - //return true is have room for one now - return (level.numAlertEvents= 0); + // return true is have room for one now + return (level.numAlertEvents < MAX_ALERT_EVENTS); } /* @@ -758,20 +670,17 @@ G_ClearLOS */ // Position to position -qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) -{ - trace_t tr; - int traceCount = 0; - - //FIXME: ENTITYNUM_NONE ok? - trap->Trace ( &tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE/*CONTENTS_SOLID*//*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, qfalse, 0, 0 ); - while ( tr.fraction < 1.0 && traceCount < 3 ) - {//can see through 3 panes of glass - if ( tr.entityNum < ENTITYNUM_WORLD ) - { - if ( &g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].r.svFlags&SVF_GLASS_BRUSH) ) - {//can see through glass, trace again, ignoring me - trap->Trace ( &tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, qfalse, 0, 0 ); +qboolean G_ClearLOS(gentity_t *self, const vec3_t start, const vec3_t end) { + trace_t tr; + int traceCount = 0; + + // FIXME: ENTITYNUM_NONE ok? + trap->Trace(&tr, start, NULL, NULL, end, ENTITYNUM_NONE, CONTENTS_OPAQUE /*CONTENTS_SOLID*/ /*(CONTENTS_SOLID|CONTENTS_MONSTERCLIP)*/, qfalse, 0, 0); + while (tr.fraction < 1.0 && traceCount < 3) { // can see through 3 panes of glass + if (tr.entityNum < ENTITYNUM_WORLD) { + if (&g_entities[tr.entityNum] != NULL && (g_entities[tr.entityNum].r.svFlags & SVF_GLASS_BRUSH)) { // can see through glass, trace again, ignoring + // me + trap->Trace(&tr, tr.endpos, NULL, NULL, end, tr.entityNum, MASK_OPAQUE, qfalse, 0, 0); traceCount++; continue; } @@ -779,62 +688,58 @@ qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ) return qfalse; } - if ( tr.fraction == 1.0 ) + if (tr.fraction == 1.0) return qtrue; return qfalse; } -//Entity to position -qboolean G_ClearLOS2( gentity_t *self, gentity_t *ent, const vec3_t end ) -{ - vec3_t eyes; +// Entity to position +qboolean G_ClearLOS2(gentity_t *self, gentity_t *ent, const vec3_t end) { + vec3_t eyes; - CalcEntitySpot( ent, SPOT_HEAD_LEAN, eyes ); + CalcEntitySpot(ent, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } -//Position to entity -qboolean G_ClearLOS3( gentity_t *self, const vec3_t start, gentity_t *ent ) -{ - vec3_t spot; +// Position to entity +qboolean G_ClearLOS3(gentity_t *self, const vec3_t start, gentity_t *ent) { + vec3_t spot; - //Look for the chest first - CalcEntitySpot( ent, SPOT_ORIGIN, spot ); + // Look for the chest first + CalcEntitySpot(ent, SPOT_ORIGIN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; - //Look for the head next - CalcEntitySpot( ent, SPOT_HEAD_LEAN, spot ); + // Look for the head next + CalcEntitySpot(ent, SPOT_HEAD_LEAN, spot); - if ( G_ClearLOS( self, start, spot ) ) + if (G_ClearLOS(self, start, spot)) return qtrue; return qfalse; } -//NPC's eyes to entity -qboolean G_ClearLOS4( gentity_t *self, gentity_t *ent ) -{ - vec3_t eyes; +// NPC's eyes to entity +qboolean G_ClearLOS4(gentity_t *self, gentity_t *ent) { + vec3_t eyes; - //Calculate my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); + // Calculate my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS3( self, eyes, ent ); + return G_ClearLOS3(self, eyes, ent); } -//NPC's eyes to position -qboolean G_ClearLOS5( gentity_t *self, const vec3_t end ) -{ - vec3_t eyes; +// NPC's eyes to position +qboolean G_ClearLOS5(gentity_t *self, const vec3_t end) { + vec3_t eyes; - //Calculate the my position - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); + // Calculate the my position + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); - return G_ClearLOS( self, eyes, end ); + return G_ClearLOS(self, eyes, end); } /* @@ -843,21 +748,20 @@ NPC_GetFOVPercentage ------------------------- */ -float NPC_GetHFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float hFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetHFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float hFOV) { + vec3_t deltaVector, angles; + float delta; - VectorSubtract ( spot, from, deltaVector ); + VectorSubtract(spot, from, deltaVector); - vectoangles ( deltaVector, angles ); + vectoangles(deltaVector, angles); - delta = fabs( AngleDelta ( facing[YAW], angles[YAW] ) ); + delta = fabs(AngleDelta(facing[YAW], angles[YAW])); - if ( delta > hFOV ) + if (delta > hFOV) return 0.0f; - return ( ( hFOV - delta ) / hFOV ); + return ((hFOV - delta) / hFOV); } /* @@ -866,64 +770,56 @@ NPC_GetVFOVPercentage ------------------------- */ -float NPC_GetVFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float vFOV ) -{ - vec3_t deltaVector, angles; - float delta; +float NPC_GetVFOVPercentage(vec3_t spot, vec3_t from, vec3_t facing, float vFOV) { + vec3_t deltaVector, angles; + float delta; - VectorSubtract ( spot, from, deltaVector ); + VectorSubtract(spot, from, deltaVector); - vectoangles ( deltaVector, angles ); + vectoangles(deltaVector, angles); - delta = fabs( AngleDelta ( facing[PITCH], angles[PITCH] ) ); + delta = fabs(AngleDelta(facing[PITCH], angles[PITCH])); - if ( delta > vFOV ) + if (delta > vFOV) return 0.0f; - return ( ( vFOV - delta ) / vFOV ); + return ((vFOV - delta) / vFOV); } -#define MAX_INTEREST_DIST ( 256 * 256 ) +#define MAX_INTEREST_DIST (256 * 256) /* ------------------------- NPC_FindLocalInterestPoint ------------------------- */ -int G_FindLocalInterestPoint( gentity_t *self ) -{ - int i, bestPoint = ENTITYNUM_NONE; - float dist, bestDist = Q3_INFINITE; - vec3_t diffVec, eyes; - - CalcEntitySpot( self, SPOT_HEAD_LEAN, eyes ); - for ( i = 0; i < level.numInterestPoints; i++ ) - { - //Don't ignore portals? If through a portal, need to look at portal! - if ( trap->InPVS( level.interestPoints[i].origin, eyes ) ) - { - VectorSubtract( level.interestPoints[i].origin, eyes, diffVec ); - if ( (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && - fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2 ) - {//Too close to look so far up or down +int G_FindLocalInterestPoint(gentity_t *self) { + int i, bestPoint = ENTITYNUM_NONE; + float dist, bestDist = Q3_INFINITE; + vec3_t diffVec, eyes; + + CalcEntitySpot(self, SPOT_HEAD_LEAN, eyes); + for (i = 0; i < level.numInterestPoints; i++) { + // Don't ignore portals? If through a portal, need to look at portal! + if (trap->InPVS(level.interestPoints[i].origin, eyes)) { + VectorSubtract(level.interestPoints[i].origin, eyes, diffVec); + if ((fabs(diffVec[0]) + fabs(diffVec[1])) / 2 < 48 && + fabs(diffVec[2]) > (fabs(diffVec[0]) + fabs(diffVec[1])) / 2) { // Too close to look so far up or down continue; } - dist = VectorLengthSquared( diffVec ); - //Some priority to more interesting points - //dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); - if ( dist < MAX_INTEREST_DIST && dist < bestDist ) - { - if ( G_ClearLineOfSight( eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE ) ) - { + dist = VectorLengthSquared(diffVec); + // Some priority to more interesting points + // dist -= ((int)level.interestPoints[i].lookMode * 5) * ((int)level.interestPoints[i].lookMode * 5); + if (dist < MAX_INTEREST_DIST && dist < bestDist) { + if (G_ClearLineOfSight(eyes, level.interestPoints[i].origin, self->s.number, MASK_OPAQUE)) { bestDist = dist; bestPoint = i; } } } } - if ( bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target ) - { - G_UseTargets2( self, self, level.interestPoints[bestPoint].target ); + if (bestPoint != ENTITYNUM_NONE && level.interestPoints[bestPoint].target) { + G_UseTargets2(self, self, level.interestPoints[bestPoint].target); } return bestPoint; } @@ -934,10 +830,8 @@ A point that a squadmate will look at if standing still target - thing to fire when someone looks at this thing */ -void SP_target_interest( gentity_t *self ) -{//FIXME: rename point_interest - if(level.numInterestPoints >= MAX_INTEREST_POINTS) - { +void SP_target_interest(gentity_t *self) { // FIXME: rename point_interest + if (level.numInterestPoints >= MAX_INTEREST_POINTS) { Com_Printf("ERROR: Too many interest points, limit is %d\n", MAX_INTEREST_POINTS); G_FreeEntity(self); return; @@ -945,9 +839,8 @@ void SP_target_interest( gentity_t *self ) VectorCopy(self->r.currentOrigin, level.interestPoints[level.numInterestPoints].origin); - if(self->target && self->target[0]) - { - level.interestPoints[level.numInterestPoints].target = G_NewString( self->target ); + if (self->target && self->target[0]) { + level.interestPoints[level.numInterestPoints].target = G_NewString(self->target); } level.numInterestPoints++; diff --git a/codemp/game/NPC_sounds.c b/codemp/game/NPC_sounds.c index be0a571bf2..609ed40962 100644 --- a/codemp/game/NPC_sounds.c +++ b/codemp/game/NPC_sounds.c @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_sounds.cpp +// NPC_sounds.cpp #include "b_local.h" #include "icarus/Q3_Interface.h" @@ -41,75 +41,66 @@ void NPC_AngerSound (void) } */ -extern void G_SpeechEvent( gentity_t *self, int event ); -void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ) -{ - if ( !self->NPC ) - { +extern void G_SpeechEvent(gentity_t *self, int event); +void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime) { + if (!self->NPC) { return; } - if ( !self->client || self->client->ps.pm_type >= PM_DEAD ) - { + if (!self->client || self->client->ps.pm_type >= PM_DEAD) { return; } - if ( self->NPC->blockedSpeechDebounceTime > level.time ) - { + if (self->NPC->blockedSpeechDebounceTime > level.time) { return; } - if ( trap->ICARUS_TaskIDPending( (sharedEntity_t *)self, TID_CHAN_VOICE ) ) - { + if (trap->ICARUS_TaskIDPending((sharedEntity_t *)self, TID_CHAN_VOICE)) { return; } - - if ( (self->NPC->scriptFlags&SCF_NO_COMBAT_TALK) && ( (event >= EV_ANGER1 && event <= EV_VICTORY3) || (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5) ) )//(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) + if ((self->NPC->scriptFlags & SCF_NO_COMBAT_TALK) && + ((event >= EV_ANGER1 && event <= EV_VICTORY3) || + (event >= EV_CHASE1 && event <= EV_SUSPICIOUS5))) //(event < EV_FF_1A || event > EV_FF_3C) && (event < EV_RESPOND1 || event > EV_MISSION3) ) { return; } - if ( (self->NPC->scriptFlags&SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5) ) - { + if ((self->NPC->scriptFlags & SCF_NO_ALERT_TALK) && (event >= EV_GIVEUP1 && event <= EV_SUSPICIOUS5)) { return; } - //FIXME: Also needs to check for teammates. Don't want + // FIXME: Also needs to check for teammates. Don't want // everyone babbling at once - //NOTE: was losing too many speech events, so we do it directly now, screw networking! - //G_AddEvent( self, event, 0 ); - G_SpeechEvent( self, event ); + // NOTE: was losing too many speech events, so we do it directly now, screw networking! + // G_AddEvent( self, event, 0 ); + G_SpeechEvent(self, event); - //won't speak again for 5 seconds (unless otherwise specified) - self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime==0) ? 5000 : speakDebounceTime); + // won't speak again for 5 seconds (unless otherwise specified) + self->NPC->blockedSpeechDebounceTime = level.time + ((speakDebounceTime == 0) ? 5000 : speakDebounceTime); } -void NPC_PlayConfusionSound( gentity_t *self ) -{ - if ( self->health > 0 ) - { - if ( self->enemy ||//was mad - !TIMER_Done( self, "enemyLastVisible" ) ||//saw something suspicious - self->client->renderInfo.lookTarget == 0//was looking at player - ) - { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, Q_irand( EV_CONFUSE2, EV_CONFUSE3 ), 2000 ); - } - else if ( self->NPC && self->NPC->investigateDebounceTime+self->NPC->pauseTime > level.time )//was checking something out +void NPC_PlayConfusionSound(gentity_t *self) { + if (self->health > 0) { + if (self->enemy || // was mad + !TIMER_Done(self, "enemyLastVisible") || // saw something suspicious + self->client->renderInfo.lookTarget == 0 // was looking at player + ) { + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, Q_irand(EV_CONFUSE2, EV_CONFUSE3), 2000); + } else if (self->NPC && self->NPC->investigateDebounceTime + self->NPC->pauseTime > level.time) // was checking something out { - self->NPC->blockedSpeechDebounceTime = 0;//make sure we say this - G_AddVoiceEvent( self, EV_CONFUSE1, 2000 ); + self->NPC->blockedSpeechDebounceTime = 0; // make sure we say this + G_AddVoiceEvent(self, EV_CONFUSE1, 2000); } - //G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + // G_AddVoiceEvent( self, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); } - //reset him to be totally unaware again - TIMER_Set( self, "enemyLastVisible", 0 ); + // reset him to be totally unaware again + TIMER_Set(self, "enemyLastVisible", 0); self->NPC->tempBehavior = BS_DEFAULT; - //self->NPC->behaviorState = BS_PATROL; - G_ClearEnemy( self );//FIXME: or just self->enemy = NULL;? + // self->NPC->behaviorState = BS_PATROL; + G_ClearEnemy(self); // FIXME: or just self->enemy = NULL;? self->NPC->investigateCount = 0; } diff --git a/codemp/game/NPC_spawn.c b/codemp/game/NPC_spawn.c index a9761a9be4..ee768b9f00 100644 --- a/codemp/game/NPC_spawn.c +++ b/codemp/game/NPC_spawn.c @@ -20,8 +20,8 @@ along with this program; if not, see . =========================================================================== */ -//b_spawn.cpp -//added by MCG +// b_spawn.cpp +// added by MCG #include "b_local.h" #include "anims.h" #include "w_saber.h" @@ -29,80 +29,79 @@ along with this program; if not, see . #include "bg_vehicles.h" #include "g_nav.h" -extern void G_DebugPrint( int level, const char *format, ... ); - -extern qboolean G_CheckInSolid (gentity_t *self, qboolean fix); -extern qboolean ClientUserinfoChanged( int clientNum ); -extern qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -extern void Jedi_Cloak( gentity_t *self ); - -extern void Q3_SetParm (int entID, int parmNum, const char *parmValue); -extern team_t TranslateTeamName( const char *name ); -extern char *TeamNames[TEAM_NUM_TEAMS]; - -extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); -extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); - -extern void ST_ClearTimers( gentity_t *ent ); -extern void Jedi_ClearTimers( gentity_t *ent ); -extern void NPC_ShadowTrooper_Precache( void ); -extern void NPC_Gonk_Precache( void ); -extern void NPC_Mouse_Precache( void ); -extern void NPC_Seeker_Precache( void ); -extern void NPC_Remote_Precache( void ); -extern void NPC_R2D2_Precache(void); -extern void NPC_R5D2_Precache(void); +extern void G_DebugPrint(int level, const char *format, ...); + +extern qboolean G_CheckInSolid(gentity_t *self, qboolean fix); +extern qboolean ClientUserinfoChanged(int clientNum); +extern qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +extern void Jedi_Cloak(gentity_t *self); + +extern void Q3_SetParm(int entID, int parmNum, const char *parmValue); +extern team_t TranslateTeamName(const char *name); +extern char *TeamNames[TEAM_NUM_TEAMS]; + +extern void PM_SetTorsoAnimTimer(gentity_t *ent, int *torsoAnimTimer, int time); +extern void PM_SetLegsAnimTimer(gentity_t *ent, int *legsAnimTimer, int time); + +extern void ST_ClearTimers(gentity_t *ent); +extern void Jedi_ClearTimers(gentity_t *ent); +extern void NPC_ShadowTrooper_Precache(void); +extern void NPC_Gonk_Precache(void); +extern void NPC_Mouse_Precache(void); +extern void NPC_Seeker_Precache(void); +extern void NPC_Remote_Precache(void); +extern void NPC_R2D2_Precache(void); +extern void NPC_R5D2_Precache(void); extern void NPC_Probe_Precache(void); extern void NPC_Interrogator_Precache(gentity_t *self); -extern void NPC_MineMonster_Precache( void ); -extern void NPC_Howler_Precache( void ); +extern void NPC_MineMonster_Precache(void); +extern void NPC_Howler_Precache(void); extern void NPC_ATST_Precache(void); extern void NPC_Sentry_Precache(void); extern void NPC_Mark1_Precache(void); extern void NPC_Mark2_Precache(void); -extern void NPC_GalakMech_Precache( void ); -extern void NPC_GalakMech_Init( gentity_t *ent ); -extern void NPC_Protocol_Precache( void ); -extern void Boba_Precache( void ); -extern void NPC_Wampa_Precache( void ); -gentity_t *NPC_SpawnType( gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle ); +extern void NPC_GalakMech_Precache(void); +extern void NPC_GalakMech_Init(gentity_t *ent); +extern void NPC_Protocol_Precache(void); +extern void Boba_Precache(void); +extern void NPC_Wampa_Precache(void); +gentity_t *NPC_SpawnType(gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle); -extern void Rancor_SetBolts( gentity_t *self ); -extern void Wampa_SetBolts( gentity_t *self ); +extern void Rancor_SetBolts(gentity_t *self); +extern void Wampa_SetBolts(gentity_t *self); -#define NSF_DROP_TO_FLOOR 16 +#define NSF_DROP_TO_FLOOR 16 // PAIN functions... // -extern void funcBBrushPain (gentity_t *self, gentity_t *attacker, int damage); -extern void misc_model_breakable_pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void station_pain (gentity_t *self, gentity_t *attacker, int damage); -extern void func_usable_pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_ATST_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_ST_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Jedi_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Droid_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Probe_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_MineMonster_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Howler_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Seeker_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Remote_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void emplaced_gun_pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Mark1_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_GM_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Sentry_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Mark2_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void PlayerPain (gentity_t *self, gentity_t *attacker, int damage); -extern void GasBurst (gentity_t *self, gentity_t *attacker, int damage); -extern void CrystalCratePain (gentity_t *self, gentity_t *attacker, int damage); -extern void TurretPain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Wampa_Pain (gentity_t *self, gentity_t *attacker, int damage); -extern void NPC_Rancor_Pain (gentity_t *self, gentity_t *attacker, int damage); - -int WP_SetSaberModel( gclient_t *client, class_t npcClass ) -{ - //rwwFIXMEFIXME: Do something here, need to let the client know. +extern void funcBBrushPain(gentity_t *self, gentity_t *attacker, int damage); +extern void misc_model_breakable_pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void station_pain(gentity_t *self, gentity_t *attacker, int damage); +extern void func_usable_pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_ATST_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_ST_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Jedi_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Droid_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Probe_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_MineMonster_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Howler_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Seeker_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Remote_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void emplaced_gun_pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Mark1_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_GM_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Sentry_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Mark2_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void PlayerPain(gentity_t *self, gentity_t *attacker, int damage); +extern void GasBurst(gentity_t *self, gentity_t *attacker, int damage); +extern void CrystalCratePain(gentity_t *self, gentity_t *attacker, int damage); +extern void TurretPain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Wampa_Pain(gentity_t *self, gentity_t *attacker, int damage); +extern void NPC_Rancor_Pain(gentity_t *self, gentity_t *attacker, int damage); + +int WP_SetSaberModel(gclient_t *client, class_t npcClass) { + // rwwFIXMEFIXME: Do something here, need to let the client know. return 1; } @@ -111,18 +110,14 @@ int WP_SetSaberModel( gclient_t *client, class_t npcClass ) NPC_PainFunc ------------------------- */ -typedef void (PAIN_FUNC) (gentity_t *self, gentity_t *attacker, int damage); +typedef void(PAIN_FUNC)(gentity_t *self, gentity_t *attacker, int damage); -PAIN_FUNC *NPC_PainFunc( gentity_t *ent ) -{ - void (*func)(gentity_t *self, gentity_t *attacker, int damage); +PAIN_FUNC *NPC_PainFunc(gentity_t *ent) { + void (*func)(gentity_t * self, gentity_t * attacker, int damage); - if ( ent->client->ps.weapon == WP_SABER ) - { + if (ent->client->ps.weapon == WP_SABER) { func = NPC_Jedi_Pain; - } - else - { + } else { // team no longer indicates race/species, use NPC_class to determine different npc types /* switch ( ent->client->playerTeam ) @@ -132,8 +127,7 @@ PAIN_FUNC *NPC_PainFunc( gentity_t *ent ) break; } */ - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { // troopers get special pain case CLASS_STORMTROOPER: case CLASS_SWAMPTROOPER: @@ -195,23 +189,20 @@ PAIN_FUNC *NPC_PainFunc( gentity_t *ent ) func = NPC_Pain; break; } - } return func; } - /* ------------------------- NPC_TouchFunc ------------------------- */ -typedef void (TOUCH_FUNC) (gentity_t *self, gentity_t *other, trace_t *trace); +typedef void(TOUCH_FUNC)(gentity_t *self, gentity_t *other, trace_t *trace); -TOUCH_FUNC *NPC_TouchFunc( gentity_t *ent ) -{ - void (*func)(gentity_t *self, gentity_t *other, trace_t *trace); +TOUCH_FUNC *NPC_TouchFunc(gentity_t *ent) { + void (*func)(gentity_t * self, gentity_t * other, trace_t * trace); func = NPC_Touch; @@ -224,85 +215,72 @@ NPC_SetMiscDefaultData ------------------------- */ -extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum ); -void NPC_SetMiscDefaultData( gentity_t *ent ) -{ - if ( ent->spawnflags & SFB_CINEMATIC ) - {//if a cinematic guy, default us to wait bState +extern void G_CreateG2AttachedWeaponModel(gentity_t *ent, const char *weaponModel, int boltNum, int weaponNum); +void NPC_SetMiscDefaultData(gentity_t *ent) { + if (ent->spawnflags & SFB_CINEMATIC) { // if a cinematic guy, default us to wait bState ent->NPC->behaviorState = BS_CINEMATIC; } - if ( ent->client->NPC_class == CLASS_BOBAFETT ) - {//set some stuff, precache + if (ent->client->NPC_class == CLASS_BOBAFETT) { // set some stuff, precache Boba_Precache(); - ent->client->ps.fd.forcePowersKnown |= ( 1 << FP_LEVITATION ); + ent->client->ps.fd.forcePowersKnown |= (1 << FP_LEVITATION); ent->client->ps.fd.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_3; ent->client->ps.fd.forcePower = 100; - ent->NPC->scriptFlags |= (SCF_ALT_FIRE|SCF_NO_GROUPS); + ent->NPC->scriptFlags |= (SCF_ALT_FIRE | SCF_NO_GROUPS); } - //if ( !Q_stricmp( "atst_vehicle", ent->NPC_type ) )//FIXME: has to be a better, easier way to tell this, no? - if (ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle) - { - ent->s.g2radius = 255;//MAX for this value, was (ent->r.maxs[2]-ent->r.mins[2]), which is 272 or something + // if ( !Q_stricmp( "atst_vehicle", ent->NPC_type ) )//FIXME: has to be a better, easier way to tell this, no? + if (ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle) { + ent->s.g2radius = 255; // MAX for this value, was (ent->r.maxs[2]-ent->r.mins[2]), which is 272 or something - if (ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) - { - ent->mass = 2000;//??? - ent->flags |= (FL_SHIELDED|FL_NO_KNOCKBACK); + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { + ent->mass = 2000; //??? + ent->flags |= (FL_SHIELDED | FL_NO_KNOCKBACK); ent->pain = NPC_ATST_Pain; } - //turn the damn hatch cover on and LEAVE it on - trap->G2API_SetSurfaceOnOff( ent->ghoul2, "head_hatchcover", 0/*TURN_ON*/ ); - } - if ( !Q_stricmp( "wampa", ent->NPC_type ) ) - {//FIXME: extern this into NPC.cfg? - Wampa_SetBolts( ent ); - ent->s.g2radius = 80;//??? - ent->mass = 300;//??? + // turn the damn hatch cover on and LEAVE it on + trap->G2API_SetSurfaceOnOff(ent->ghoul2, "head_hatchcover", 0 /*TURN_ON*/); + } + if (!Q_stricmp("wampa", ent->NPC_type)) { // FIXME: extern this into NPC.cfg? + Wampa_SetBolts(ent); + ent->s.g2radius = 80; //??? + ent->mass = 300; //??? ent->flags |= FL_NO_KNOCKBACK; ent->pain = NPC_Wampa_Pain; } - if ( ent->client->NPC_class == CLASS_RANCOR ) - { - Rancor_SetBolts( ent ); - ent->s.g2radius = 255;//MAX for this value, was (ent->r.maxs[2]-ent->r.mins[2]), which is 272 or something - ent->mass = 1000;//??? + if (ent->client->NPC_class == CLASS_RANCOR) { + Rancor_SetBolts(ent); + ent->s.g2radius = 255; // MAX for this value, was (ent->r.maxs[2]-ent->r.mins[2]), which is 272 or something + ent->mass = 1000; //??? ent->flags |= FL_NO_KNOCKBACK; ent->pain = NPC_Rancor_Pain; ent->health *= 4; } - if ( !Q_stricmp( "Yoda", ent->NPC_type ) ) - {//FIXME: extern this into NPC.cfg? - ent->NPC->scriptFlags |= SCF_NO_FORCE;//force powers don't work on him + if (!Q_stricmp("Yoda", ent->NPC_type)) { // FIXME: extern this into NPC.cfg? + ent->NPC->scriptFlags |= SCF_NO_FORCE; // force powers don't work on him } - if ( !Q_stricmp( "emperor", ent->NPC_type ) - || !Q_stricmp( "cultist_grip", ent->NPC_type ) - || !Q_stricmp( "cultist_drain", ent->NPC_type ) - || !Q_stricmp( "cultist_lightning", ent->NPC_type )) - {//FIXME: extern this into NPC.cfg? - ent->NPC->scriptFlags |= SCF_DONT_FIRE;//so he uses only force powers + if (!Q_stricmp("emperor", ent->NPC_type) || !Q_stricmp("cultist_grip", ent->NPC_type) || !Q_stricmp("cultist_drain", ent->NPC_type) || + !Q_stricmp("cultist_lightning", ent->NPC_type)) { // FIXME: extern this into NPC.cfg? + ent->NPC->scriptFlags |= SCF_DONT_FIRE; // so he uses only force powers } //================== -// if ( ent->client->ps.saber[0].type != SABER_NONE ) - if (ent->client->ps.weapon == WP_SABER) //rwwFIXMEFIXME: is this going to work? - {//if I'm equipped with a saber, initialize it (them) - // ent->client->ps.SaberDeactivate(); - // ent->client->ps.SetSaberLength( 0 ); - WP_SaberInitBladeData( ent ); + // if ( ent->client->ps.saber[0].type != SABER_NONE ) + if (ent->client->ps.weapon == WP_SABER) // rwwFIXMEFIXME: is this going to work? + { // if I'm equipped with a saber, initialize it (them) + // ent->client->ps.SaberDeactivate(); + // ent->client->ps.SetSaberLength( 0 ); + WP_SaberInitBladeData(ent); ent->client->ps.saberHolstered = 2; - // G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[0].model, ent->handRBolt, 0 ); - // if ( ent->client->ps.dualSabers ) - // { - // G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[1].model, ent->handLBolt, 1 ); - // } - Jedi_ClearTimers( ent ); - } - if ( ent->client->ps.fd.forcePowersKnown != 0 ) - { - WP_InitForcePowers( ent ); - WP_SpawnInitForcePowers(ent); //rww - } - if ( ent->client->NPC_class == CLASS_SEEKER ) - { + // G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[0].model, ent->handRBolt, 0 ); + // if ( ent->client->ps.dualSabers ) + // { + // G_CreateG2AttachedWeaponModel( ent, ent->client->ps.saber[1].model, ent->handLBolt, 1 ); + // } + Jedi_ClearTimers(ent); + } + if (ent->client->ps.fd.forcePowersKnown != 0) { + WP_InitForcePowers(ent); + WP_SpawnInitForcePowers(ent); // rww + } + if (ent->client->NPC_class == CLASS_SEEKER) { ent->NPC->defaultBehavior = BS_DEFAULT; ent->client->ps.gravity = 0; ent->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; @@ -310,31 +288,25 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) ent->count = 30; // SEEKER shot ammo count } //***I'm not sure whether I should leave this as a TEAM_ switch, I think NPC_class may be more appropriate - dmv - switch(ent->client->playerTeam) - { + switch (ent->client->playerTeam) { case NPCTEAM_PLAYER: - //ent->flags |= FL_NO_KNOCKBACK; - if ( ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_LUKE ) - {//good jedi + // ent->flags |= FL_NO_KNOCKBACK; + if (ent->client->NPC_class == CLASS_JEDI || ent->client->NPC_class == CLASS_LUKE) { // good jedi ent->client->enemyTeam = NPCTEAM_ENEMY; - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher + if (ent->spawnflags & JSF_AMBUSH) { // ambusher ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = qtrue;//hang + ent->client->noclip = qtrue; // hang } - } - else - { + } else { /* if (ent->client->ps.weapon != WP_NONE) { G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); } */ - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL://FIXME: new weapon: imp blaster pistol - // case WP_BLASTER_PISTOL: + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: // FIXME: new weapon: imp blaster pistol + // case WP_BLASTER_PISTOL: case WP_DISRUPTOR: case WP_BOWCASTER: case WP_REPEATER: @@ -345,24 +317,20 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) break; case WP_THERMAL: case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //ent->health = 25; - //FIXME: not necc. a ST - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL ) - {//officers, grenade-throwers use alt-fire - //ent->health = 50; - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // ent->health = 25; + // FIXME: not necc. a ST + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_LT || ent->client->ps.weapon == WP_THERMAL) { // officers, grenade-throwers use alt-fire + // ent->health = 50; + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } break; } } - if ( ent->client->NPC_class == CLASS_KYLE || ent->client->NPC_class == CLASS_VEHICLE || (ent->spawnflags & SFB_CINEMATIC) ) - { + if (ent->client->NPC_class == CLASS_KYLE || ent->client->NPC_class == CLASS_VEHICLE || (ent->spawnflags & SFB_CINEMATIC)) { ent->NPC->defaultBehavior = BS_CINEMATIC; - } - else - { + } else { /* ent->NPC->defaultBehavior = BS_FOLLOW_LEADER; ent->client->leader = &g_entities[0]; @@ -372,8 +340,7 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) case NPCTEAM_NEUTRAL: - if ( Q_stricmp( ent->NPC_type, "gonk" ) == 0 ) - { + if (Q_stricmp(ent->NPC_type, "gonk") == 0) { // I guess we generically make them player usable ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -392,127 +359,100 @@ void NPC_SetMiscDefaultData( gentity_t *ent ) ent->client->ps.batteryCharge = MAX_BATTERIES * 0.5f; break; }*/ - //rwwFIXMEFIXME: Make use of this. + // rwwFIXMEFIXME: Make use of this. } break; - case NPCTEAM_ENEMY: - { - ent->NPC->defaultBehavior = BS_DEFAULT; - if ( ent->client->NPC_class == CLASS_SHADOWTROOPER ) - {//FIXME: a spawnflag? - Jedi_Cloak( ent ); + case NPCTEAM_ENEMY: { + ent->NPC->defaultBehavior = BS_DEFAULT; + if (ent->client->NPC_class == CLASS_SHADOWTROOPER) { // FIXME: a spawnflag? + Jedi_Cloak(ent); + } + if (ent->client->NPC_class == CLASS_TAVION || ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_DESANN || + ent->client->NPC_class == CLASS_SHADOWTROOPER) { + ent->client->enemyTeam = NPCTEAM_PLAYER; + if (ent->spawnflags & JSF_AMBUSH) { // ambusher + ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; + ent->client->noclip = qtrue; // hang } - if( ent->client->NPC_class == CLASS_TAVION || - ent->client->NPC_class == CLASS_REBORN || - ent->client->NPC_class == CLASS_DESANN || - ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - ent->client->enemyTeam = NPCTEAM_PLAYER; - if ( ent->spawnflags & JSF_AMBUSH ) - {//ambusher - ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - ent->client->noclip = qtrue;//hang + } else if (ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_SENTRY) { + ent->NPC->defaultBehavior = BS_DEFAULT; + ent->client->ps.gravity = 0; + ent->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; + ent->client->ps.eFlags2 |= EF2_FLYING; + } else { + // G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); + switch (ent->client->ps.weapon) { + case WP_BRYAR_PISTOL: + break; + // case WP_BLASTER_PISTOL: + // break; + case WP_DISRUPTOR: + // Sniper + // ent->NPC->scriptFlags |= SCF_ALT_FIRE;//FIXME: use primary fire sometimes? Up close? Different class of NPC? + break; + case WP_BOWCASTER: + break; + case WP_REPEATER: + // machine-gunner + break; + case WP_DEMP2: + break; + case WP_FLECHETTE: + // shotgunner + if (!Q_stricmp("stofficeralt", ent->NPC_type)) { + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } - } - else if( ent->client->NPC_class == CLASS_PROBE || ent->client->NPC_class == CLASS_REMOTE || - ent->client->NPC_class == CLASS_INTERROGATOR || ent->client->NPC_class == CLASS_SENTRY) - { - ent->NPC->defaultBehavior = BS_DEFAULT; - ent->client->ps.gravity = 0; - ent->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; - ent->client->ps.eFlags2 |= EF2_FLYING; - } - else - { - // G_CreateG2AttachedWeaponModel( ent, weaponData[ent->client->ps.weapon].weaponMdl, ent->handRBolt, 0 ); - switch ( ent->client->ps.weapon ) - { - case WP_BRYAR_PISTOL: - break; - // case WP_BLASTER_PISTOL: - // break; - case WP_DISRUPTOR: - //Sniper - //ent->NPC->scriptFlags |= SCF_ALT_FIRE;//FIXME: use primary fire sometimes? Up close? Different class of NPC? - break; - case WP_BOWCASTER: - break; - case WP_REPEATER: - //machine-gunner - break; - case WP_DEMP2: - break; - case WP_FLECHETTE: - //shotgunner - if ( !Q_stricmp( "stofficeralt", ent->NPC_type ) ) - { - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; - case WP_ROCKET_LAUNCHER: - break; - case WP_THERMAL: - //Gran, use main, bouncy fire -// ent->NPC->scriptFlags |= SCF_ALT_FIRE; - break; - case WP_STUN_BATON: - break; - default: - case WP_BLASTER: - //FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers - //FIXME: not necc. a ST - ST_ClearTimers( ent ); - if ( ent->NPC->rank >= RANK_COMMANDER ) - {//commanders use alt-fire - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - if ( !Q_stricmp( "rodian2", ent->NPC_type ) ) - { - //ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - break; + break; + case WP_ROCKET_LAUNCHER: + break; + case WP_THERMAL: + // Gran, use main, bouncy fire + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; + break; + case WP_STUN_BATON: + break; + default: + case WP_BLASTER: + // FIXME: health in NPCs.cfg, and not all blaster users are stormtroopers + // FIXME: not necc. a ST + ST_ClearTimers(ent); + if (ent->NPC->rank >= RANK_COMMANDER) { // commanders use alt-fire + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } - if ( !Q_stricmp( "galak_mech", ent->NPC_type ) ) - {//starts with armor - NPC_GalakMech_Init( ent ); + if (!Q_stricmp("rodian2", ent->NPC_type)) { + // ent->NPC->scriptFlags |= SCF_ALT_FIRE; } + break; + } + if (!Q_stricmp("galak_mech", ent->NPC_type)) { // starts with armor + NPC_GalakMech_Init(ent); } } - break; + } break; default: break; } - - if ( ent->client->NPC_class == CLASS_SEEKER - && ent->activator ) - {//assume my teams are already set correctly - } - else - { - //for siege, want "bad" npc's allied with the "bad" team - if (level.gametype == GT_SIEGE && ent->s.NPC_class != CLASS_VEHICLE) - { - if (ent->client->enemyTeam == NPCTEAM_PLAYER) - { + if (ent->client->NPC_class == CLASS_SEEKER && ent->activator) { // assume my teams are already set correctly + } else { + // for siege, want "bad" npc's allied with the "bad" team + if (level.gametype == GT_SIEGE && ent->s.NPC_class != CLASS_VEHICLE) { + if (ent->client->enemyTeam == NPCTEAM_PLAYER) { ent->client->sess.sessionTeam = SIEGETEAM_TEAM1; - } - else if (ent->client->enemyTeam == NPCTEAM_ENEMY) - { + } else if (ent->client->enemyTeam == NPCTEAM_ENEMY) { ent->client->sess.sessionTeam = SIEGETEAM_TEAM2; - } - else - { + } else { ent->client->sess.sessionTeam = TEAM_FREE; } } } - if ( ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1 ) // chris/steve/kevin requested that the mark1 be shielded also + if (ent->client->NPC_class == CLASS_ATST || ent->client->NPC_class == CLASS_MARK1) // chris/steve/kevin requested that the mark1 be shielded also { - ent->flags |= (FL_SHIELDED|FL_NO_KNOCKBACK); + ent->flags |= (FL_SHIELDED | FL_NO_KNOCKBACK); } } @@ -522,224 +462,183 @@ NPC_WeaponsForTeam ------------------------- */ -int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ) -{ +int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type) { //*** not sure how to handle this, should I pass in class instead of team and go from there? - dmv - switch(team) - { -// case TEAM_IMPERIAL: + switch (team) { + // case TEAM_IMPERIAL: case NPCTEAM_ENEMY: - if ( Q_stricmp( "tavion", NPC_type ) == 0 || - Q_strncmp( "reborn", NPC_type, 6 ) == 0 || - Q_stricmp( "desann", NPC_type ) == 0 || - Q_strncmp( "shadowtrooper", NPC_type, 13 ) == 0 ) - return ( 1 << WP_SABER); -// return ( 1 << WP_IMPERIAL_BLADE); - //NOTENOTE: Falls through if not a knife user - -// case TEAM_SCAVENGERS: -// case TEAM_MALON: - //FIXME: default weapon in npc config? - if ( Q_strncmp( "stofficer", NPC_type, 9 ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("tavion", NPC_type) == 0 || Q_strncmp("reborn", NPC_type, 6) == 0 || Q_stricmp("desann", NPC_type) == 0 || + Q_strncmp("shadowtrooper", NPC_type, 13) == 0) + return (1 << WP_SABER); + // return ( 1 << WP_IMPERIAL_BLADE); + // NOTENOTE: Falls through if not a knife user + + // case TEAM_SCAVENGERS: + // case TEAM_MALON: + // FIXME: default weapon in npc config? + if (Q_strncmp("stofficer", NPC_type, 9) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "stcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("stcommander", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "swamptrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_FLECHETTE); + if (Q_stricmp("swamptrooper", NPC_type) == 0) { + return (1 << WP_FLECHETTE); } - if ( Q_stricmp( "swamptrooper2", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("swamptrooper2", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_stricmp( "rockettrooper", NPC_type ) == 0 ) - { - return ( 1 << WP_ROCKET_LAUNCHER); + if (Q_stricmp("rockettrooper", NPC_type) == 0) { + return (1 << WP_ROCKET_LAUNCHER); } - if ( Q_strncmp( "shadowtrooper", NPC_type, 13 ) == 0 ) - { - return ( 1 << WP_SABER);//|( 1 << WP_RAPID_CONCUSSION)? + if (Q_strncmp("shadowtrooper", NPC_type, 13) == 0) { + return (1 << WP_SABER); //|( 1 << WP_RAPID_CONCUSSION)? } - if ( Q_stricmp( "imperial", NPC_type ) == 0 ) - { - //return ( 1 << WP_BLASTER_PISTOL); - return ( 1 << WP_BLASTER); + if (Q_stricmp("imperial", NPC_type) == 0) { + // return ( 1 << WP_BLASTER_PISTOL); + return (1 << WP_BLASTER); } - if ( Q_strncmp( "impworker", NPC_type, 9 ) == 0 ) - { - //return ( 1 << WP_BLASTER_PISTOL); - return ( 1 << WP_BLASTER); + if (Q_strncmp("impworker", NPC_type, 9) == 0) { + // return ( 1 << WP_BLASTER_PISTOL); + return (1 << WP_BLASTER); } - if ( Q_stricmp( "stormpilot", NPC_type ) == 0 ) - { - //return ( 1 << WP_BLASTER_PISTOL); - return ( 1 << WP_BLASTER); + if (Q_stricmp("stormpilot", NPC_type) == 0) { + // return ( 1 << WP_BLASTER_PISTOL); + return (1 << WP_BLASTER); } - if ( Q_stricmp( "galak", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("galak", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "galak_mech", NPC_type ) == 0 ) - { - return ( 1 << WP_REPEATER); + if (Q_stricmp("galak_mech", NPC_type) == 0) { + return (1 << WP_REPEATER); } - if ( Q_strncmp( "ugnaught", NPC_type, 8 ) == 0 ) - { + if (Q_strncmp("ugnaught", NPC_type, 8) == 0) { return WP_NONE; } - if ( Q_stricmp( "granshooter", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("granshooter", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "granboxer", NPC_type ) == 0 ) - { - return ( 1 << WP_STUN_BATON); + if (Q_stricmp("granboxer", NPC_type) == 0) { + return (1 << WP_STUN_BATON); } - if ( Q_strncmp( "gran", NPC_type, 4 ) == 0 ) - { - return (( 1 << WP_THERMAL)|( 1 << WP_STUN_BATON)); + if (Q_strncmp("gran", NPC_type, 4) == 0) { + return ((1 << WP_THERMAL) | (1 << WP_STUN_BATON)); } - if ( Q_stricmp( "rodian", NPC_type ) == 0 ) - { - return ( 1 << WP_DISRUPTOR); + if (Q_stricmp("rodian", NPC_type) == 0) { + return (1 << WP_DISRUPTOR); } - if ( Q_stricmp( "rodian2", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("rodian2", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "interrogator",NPC_type) == 0) || ( Q_stricmp( "sentry",NPC_type) == 0) || (Q_strncmp( "protocol",NPC_type,8) == 0) ) - { + if ((Q_stricmp("interrogator", NPC_type) == 0) || (Q_stricmp("sentry", NPC_type) == 0) || (Q_strncmp("protocol", NPC_type, 8) == 0)) { return WP_NONE; } - if ( Q_strncmp( "weequay", NPC_type, 7 ) == 0 ) - { - return ( 1 << WP_BOWCASTER);//|( 1 << WP_STAFF )(FIXME: new weap?) + if (Q_strncmp("weequay", NPC_type, 7) == 0) { + return (1 << WP_BOWCASTER); //|( 1 << WP_STAFF )(FIXME: new weap?) } - if ( Q_stricmp( "impofficer", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impofficer", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if ( Q_stricmp( "impcommander", NPC_type ) == 0 ) - { - return ( 1 << WP_BLASTER); + if (Q_stricmp("impcommander", NPC_type) == 0) { + return (1 << WP_BLASTER); } - if (( Q_stricmp( "probe", NPC_type ) == 0 ) || ( Q_stricmp( "seeker", NPC_type ) == 0 )) - { - //return ( 1 << WP_BOT_LASER); + if ((Q_stricmp("probe", NPC_type) == 0) || (Q_stricmp("seeker", NPC_type) == 0)) { + // return ( 1 << WP_BOT_LASER); return 0; } - if ( Q_stricmp( "remote", NPC_type ) == 0 ) - { - //return ( 1 << WP_BOT_LASER ); + if (Q_stricmp("remote", NPC_type) == 0) { + // return ( 1 << WP_BOT_LASER ); return 0; } - if ( Q_stricmp( "trandoshan", NPC_type ) == 0 ) - { - return (1<client->playerTeam, ent->spawnflags, ent->NPC_type ); +void NPC_SetWeapons(gentity_t *ent) { + int bestWeap = WP_NONE; + int curWeap; + int weapons = NPC_WeaponsForTeam((team_t)ent->client->playerTeam, ent->spawnflags, ent->NPC_type); ent->client->ps.stats[STAT_WEAPONS] = 0; - for ( curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if ( (weapons & ( 1 << curWeap )) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << curWeap ); -// RegisterItem( FindItemForWeapon( (weapon_t)(curWeap) ) ); //precache the weapon - //rwwFIXMEFIXME: Precache - ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100;//FIXME: max ammo - - if ( bestWeap == WP_SABER ) - { + for (curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if ((weapons & (1 << curWeap))) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << curWeap); + // RegisterItem( FindItemForWeapon( (weapon_t)(curWeap) ) ); //precache the weapon + // rwwFIXMEFIXME: Precache + ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[curWeap].ammoIndex] = 100; // FIXME: max ammo + + if (bestWeap == WP_SABER) { // still want to register other weapons -- force saber to be best weap continue; } - if ( curWeap == WP_STUN_BATON ) - { - if ( bestWeap == WP_NONE ) - {// We'll only consider giving Melee since we haven't found anything better yet. + if (curWeap == WP_STUN_BATON) { + if (bestWeap == WP_NONE) { // We'll only consider giving Melee since we haven't found anything better yet. bestWeap = curWeap; } - } - else if ( curWeap > bestWeap || bestWeap == WP_STUN_BATON ) - { + } else if (curWeap > bestWeap || bestWeap == WP_STUN_BATON) { // This will never override saber as best weap. Also will override WP_STUN_BATON if something better comes later in the list bestWeap = curWeap; } @@ -805,19 +696,15 @@ NPC_SpawnEffect ------------------------- */ -void NPC_SpawnEffect (gentity_t *ent) -{ -} +void NPC_SpawnEffect(gentity_t *ent) {} //-------------------------------------------------------------- // NPC_SetFX_SpawnStates // // Set up any special parms for spawn effects //-------------------------------------------------------------- -void NPC_SetFX_SpawnStates( gentity_t *ent ) -{ - if ( !(ent->NPC->aiFlags&NPCAI_CUSTOM_GRAVITY) ) - { +void NPC_SetFX_SpawnStates(gentity_t *ent) { + if (!(ent->NPC->aiFlags & NPCAI_CUSTOM_GRAVITY)) { ent->client->ps.gravity = g_gravity.value; } } @@ -828,74 +715,60 @@ NPC_SpotWouldTelefrag ================ */ -qboolean NPC_SpotWouldTelefrag( gentity_t *npc ) -{ - int i, num; - int touch[MAX_GENTITIES]; - gentity_t *hit; - vec3_t mins, maxs; +qboolean NPC_SpotWouldTelefrag(gentity_t *npc) { + int i, num; + int touch[MAX_GENTITIES]; + gentity_t *hit; + vec3_t mins, maxs; - VectorAdd( npc->r.currentOrigin, npc->r.mins, mins ); - VectorAdd( npc->r.currentOrigin, npc->r.maxs, maxs ); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(npc->r.currentOrigin, npc->r.mins, mins); + VectorAdd(npc->r.currentOrigin, npc->r.maxs, maxs); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient && hit->client->ps.stats[STAT_HEALTH] > 0 ) { - if (hit->inuse - && hit->client - && hit->s.number != npc->s.number - && (hit->r.contents&MASK_NPCSOLID) - && hit->s.number != npc->r.ownerNum - && hit->r.ownerNum != npc->s.number) - { + // if ( hit->client && hit->client->ps.stats[STAT_HEALTH] > 0 ) { + if (hit->inuse && hit->client && hit->s.number != npc->s.number && (hit->r.contents & MASK_NPCSOLID) && hit->s.number != npc->r.ownerNum && + hit->r.ownerNum != npc->s.number) { return qtrue; } - } return qfalse; } //-------------------------------------------------------------- -void NPC_Begin (gentity_t *ent) -{ - vec3_t spawn_origin, spawn_angles; - gclient_t *client; - usercmd_t ucmd; - gentity_t *spawnPoint = NULL; - - memset( &ucmd, 0, sizeof( ucmd ) ); - - if ( !(ent->spawnflags & SFB_NOTSOLID) ) - {//No NPCs should telefrag - if (NPC_SpotWouldTelefrag(ent)) - { - if ( ent->wait < 0 ) - {//remove yourself - G_DebugPrint( WL_DEBUG, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, ent->target3 ); - //Fire off our target3 - G_UseTargets2( ent, ent, ent->target3 ); - - //Kill us +void NPC_Begin(gentity_t *ent) { + vec3_t spawn_origin, spawn_angles; + gclient_t *client; + usercmd_t ucmd; + gentity_t *spawnPoint = NULL; + + memset(&ucmd, 0, sizeof(ucmd)); + + if (!(ent->spawnflags & SFB_NOTSOLID)) { // No NPCs should telefrag + if (NPC_SpotWouldTelefrag(ent)) { + if (ent->wait < 0) { // remove yourself + G_DebugPrint(WL_DEBUG, "NPC %s could not spawn, firing target3 (%s) and removing self\n", ent->targetname, ent->target3); + // Fire off our target3 + G_UseTargets2(ent, ent, ent->target3); + + // Kill us ent->think = G_FreeEntity; ent->nextthink = level.time + 100; - } - else - { - G_DebugPrint( WL_DEBUG, "NPC %s could not spawn, waiting %4.2 secs to try again\n", ent->targetname, ent->wait/1000.0f ); + } else { + G_DebugPrint(WL_DEBUG, "NPC %s could not spawn, waiting %4.2 secs to try again\n", ent->targetname, ent->wait / 1000.0f); ent->think = NPC_Begin; - ent->nextthink = level.time + ent->wait;//try again in half a second + ent->nextthink = level.time + ent->wait; // try again in half a second } return; } } - //Spawn effect - NPC_SpawnEffect( ent ); + // Spawn effect + NPC_SpawnEffect(ent); - VectorCopy( ent->client->ps.origin, spawn_origin); - VectorCopy( ent->s.angles, spawn_angles); + VectorCopy(ent->client->ps.origin, spawn_origin); + VectorCopy(ent->s.angles, spawn_angles); spawn_angles[YAW] = ent->NPC->desiredYaw; client = ent->client; @@ -908,79 +781,61 @@ void NPC_Begin (gentity_t *ent) client->ps.clientNum = ent->s.number; // clear entity values - if ( ent->health ) // Was health supplied in map + if (ent->health) // Was health supplied in map { client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->health; - } - else if ( ent->NPC->stats.health ) // Was health supplied in NPC.cfg? + } else if (ent->NPC->stats.health) // Was health supplied in NPC.cfg? { - if ( ent->client->NPC_class != CLASS_REBORN - && ent->client->NPC_class != CLASS_SHADOWTROOPER + if (ent->client->NPC_class != CLASS_REBORN && + ent->client->NPC_class != CLASS_SHADOWTROOPER //&& ent->client->NPC_class != CLASS_TAVION //&& ent->client->NPC_class != CLASS_DESANN - && ent->client->NPC_class != CLASS_JEDI ) - {// up everyone except jedi - ent->NPC->stats.health += ent->NPC->stats.health/4 * g_npcspskill.integer; // 100% on easy, 125% on medium, 150% on hard + && ent->client->NPC_class != CLASS_JEDI) { // up everyone except jedi + ent->NPC->stats.health += ent->NPC->stats.health / 4 * g_npcspskill.integer; // 100% on easy, 125% on medium, 150% on hard } client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = ent->NPC->stats.health; - } - else - { + } else { client->pers.maxHealth = client->ps.stats[STAT_MAX_HEALTH] = 100; } - if ( !Q_stricmp( "rodian", ent->NPC_type ) ) - {//sniper - //NOTE: this will get overridden by any aim settings in their spawnscripts - switch ( g_npcspskill.integer ) - { + if (!Q_stricmp("rodian", ent->NPC_type)) { // sniper + // NOTE: this will get overridden by any aim settings in their spawnscripts + switch (g_npcspskill.integer) { case 0: ent->NPC->stats.aim = 1; break; case 1: - ent->NPC->stats.aim = Q_irand( 2, 3 ); + ent->NPC->stats.aim = Q_irand(2, 3); break; case 2: - ent->NPC->stats.aim = Q_irand( 3, 4 ); + ent->NPC->stats.aim = Q_irand(3, 4); break; } - } - else if ( ent->client->NPC_class == CLASS_STORMTROOPER - || ent->client->NPC_class == CLASS_SWAMPTROOPER - || ent->client->NPC_class == CLASS_IMPWORKER - || !Q_stricmp( "rodian2", ent->NPC_type ) ) - {//tweak yawspeed for these NPCs based on difficulty - switch ( g_npcspskill.integer ) - { + } else if (ent->client->NPC_class == CLASS_STORMTROOPER || ent->client->NPC_class == CLASS_SWAMPTROOPER || ent->client->NPC_class == CLASS_IMPWORKER || + !Q_stricmp("rodian2", ent->NPC_type)) { // tweak yawspeed for these NPCs based on difficulty + switch (g_npcspskill.integer) { case 0: ent->NPC->stats.yawSpeed *= 0.75f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 3, 6 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(3, 6); } break; case 1: - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 2, 4 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(2, 4); } break; case 2: ent->NPC->stats.yawSpeed *= 1.5f; - if ( ent->client->NPC_class == CLASS_IMPWORKER ) - { - ent->NPC->stats.aim -= Q_irand( 0, 2 ); + if (ent->client->NPC_class == CLASS_IMPWORKER) { + ent->NPC->stats.aim -= Q_irand(0, 2); } break; } - } - else if ( ent->client->NPC_class == CLASS_REBORN - || ent->client->NPC_class == CLASS_SHADOWTROOPER ) - { - switch ( g_npcspskill.integer ) - { + } else if (ent->client->NPC_class == CLASS_REBORN || ent->client->NPC_class == CLASS_SHADOWTROOPER) { + switch (g_npcspskill.integer) { case 1: ent->NPC->stats.yawSpeed *= 1.25f; break; @@ -990,26 +845,22 @@ void NPC_Begin (gentity_t *ent) } } - ent->s.groundEntityNum = ENTITYNUM_NONE; ent->mass = 10; ent->takedamage = qtrue; ent->inuse = qtrue; ent->classname = "NPC"; -// if ( ent->client->race == RACE_HOLOGRAM ) -// {//can shoot through holograms, but not walk through them -// ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces -// ent->clipmask = MASK_NPCSOLID; -// } else - if(!(ent->spawnflags & SFB_NOTSOLID)) - { + // if ( ent->client->race == RACE_HOLOGRAM ) + // {//can shoot through holograms, but not walk through them + // ent->contents = CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_ITEM;//contents_corspe to make them show up in ID and use traces + // ent->clipmask = MASK_NPCSOLID; + // } else + if (!(ent->spawnflags & SFB_NOTSOLID)) { ent->r.contents = CONTENTS_BODY; ent->clipmask = MASK_NPCSOLID; - } - else - { + } else { ent->r.contents = 0; - ent->clipmask = MASK_NPCSOLID&~CONTENTS_BODY; + ent->clipmask = MASK_NPCSOLID & ~CONTENTS_BODY; } /* if(!ent->client->moveType)//Static? @@ -1017,7 +868,7 @@ void NPC_Begin (gentity_t *ent) ent->client->moveType = MT_RUNJUMP; } */ - //rwwFIXMEFIXME: movetype support + // rwwFIXMEFIXME: movetype support ent->die = player_die; ent->waterlevel = 0; @@ -1025,51 +876,45 @@ void NPC_Begin (gentity_t *ent) ent->client->ps.rocketLockIndex = ENTITYNUM_NONE; ent->client->ps.rocketLockTime = 0; - //visible to player and NPCs - if ( ent->client->NPC_class != CLASS_R2D2 && - ent->client->NPC_class != CLASS_R5D2 && - ent->client->NPC_class != CLASS_MOUSE && - ent->client->NPC_class != CLASS_GONK && - ent->client->NPC_class != CLASS_PROTOCOL ) - { + // visible to player and NPCs + if (ent->client->NPC_class != CLASS_R2D2 && ent->client->NPC_class != CLASS_R5D2 && ent->client->NPC_class != CLASS_MOUSE && + ent->client->NPC_class != CLASS_GONK && ent->client->NPC_class != CLASS_PROTOCOL) { ent->flags &= ~FL_NOTARGET; } ent->s.eFlags &= ~EF_NODRAW; - NPC_SetFX_SpawnStates( ent ); + NPC_SetFX_SpawnStates(ent); - //client->ps.friction = 6; - //rwwFIXMEFIXME: per ent friction? + // client->ps.friction = 6; + // rwwFIXMEFIXME: per ent friction? - if ( ent->client->ps.weapon == WP_NONE ) - {//not set by the NPCs.cfg + if (ent->client->ps.weapon == WP_NONE) { // not set by the NPCs.cfg NPC_SetWeapons(ent); } - //select the weapon + // select the weapon ent->NPC->currentAmmo = ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex]; ent->client->ps.weaponstate = WEAPON_IDLE; - ChangeWeapon( ent, ent->client->ps.weapon ); + ChangeWeapon(ent, ent->client->ps.weapon); - VectorCopy( spawn_origin, client->ps.origin ); + VectorCopy(spawn_origin, client->ps.origin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; // clear entity state values - //ent->s.eType = ET_PLAYER; + // ent->s.eType = ET_PLAYER; ent->s.eType = ET_NPC; -// ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models + // ent->s.skinNum = ent - g_entities - 1; // used as index to get custom models - VectorCopy (spawn_origin, ent->s.origin); -// ent->s.origin[2] += 1; // make sure off ground + VectorCopy(spawn_origin, ent->s.origin); + // ent->s.origin[2] += 1; // make sure off ground - SetClientViewAngle( ent, spawn_angles ); + SetClientViewAngle(ent, spawn_angles); client->renderInfo.lookTarget = ENTITYNUM_NONE; - if(!(ent->spawnflags & 64)) - { - G_KillBox( ent ); - trap->LinkEntity ((sharedEntity_t *)ent); + if (!(ent->spawnflags & 64)) { + G_KillBox(ent); + trap->LinkEntity((sharedEntity_t *)ent); } // don't allow full run speed for a bit @@ -1079,187 +924,149 @@ void NPC_Begin (gentity_t *ent) client->respawnTime = level.time; client->inactivityTime = level.time + g_inactivity.value * 1000; client->latched_buttons = 0; - if ( ent->s.m_iVehicleNum ) - {//I'm an NPC in a vehicle (or a vehicle), I already have owner set - } - else if ( client->NPC_class == CLASS_SEEKER && ent->activator != NULL ) - {//somebody else "owns" me + if (ent->s.m_iVehicleNum) { // I'm an NPC in a vehicle (or a vehicle), I already have owner set + } else if (client->NPC_class == CLASS_SEEKER && ent->activator != NULL) { // somebody else "owns" me ent->s.owner = ent->r.ownerNum = ent->activator->s.number; - } - else - { + } else { ent->s.owner = ENTITYNUM_NONE; } // set default animations - if ( ent->client->NPC_class != CLASS_VEHICLE ) - { - NPC_SetAnim( ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL ); + if (ent->client->NPC_class != CLASS_VEHICLE) { + NPC_SetAnim(ent, SETANIM_BOTH, BOTH_STAND1, SETANIM_FLAG_NORMAL); } - if( spawnPoint ) - { + if (spawnPoint) { // fire the targets of the spawn point - G_UseTargets( spawnPoint, ent ); + G_UseTargets(spawnPoint, ent); } - //ICARUS include - trap->ICARUS_InitEnt( (sharedEntity_t *)ent ); + // ICARUS include + trap->ICARUS_InitEnt((sharedEntity_t *)ent); -//==NPC initialization - SetNPCGlobals( ent ); + //==NPC initialization + SetNPCGlobals(ent); ent->enemy = NULL; NPCS.NPCInfo->timeOfDeath = 0; NPCS.NPCInfo->shotTime = 0; NPC_ClearGoal(); - NPC_ChangeWeapon( ent->client->ps.weapon ); + NPC_ChangeWeapon(ent->client->ps.weapon); -//==Final NPC initialization - ent->pain = NPC_PainFunc( ent ); //painF_NPC_Pain; - ent->touch = NPC_TouchFunc( ent ); //touchF_NPC_Touch; -// ent->NPC->side = 1; + //==Final NPC initialization + ent->pain = NPC_PainFunc(ent); // painF_NPC_Pain; + ent->touch = NPC_TouchFunc(ent); // touchF_NPC_Touch; + // ent->NPC->side = 1; ent->client->ps.ping = ent->NPC->stats.reactions * 50; - //MCG - Begin: NPC hacks - //FIXME: Set the team correctly - if (ent->s.NPC_class != CLASS_VEHICLE || level.gametype != GT_SIEGE) - { + // MCG - Begin: NPC hacks + // FIXME: Set the team correctly + if (ent->s.NPC_class != CLASS_VEHICLE || level.gametype != GT_SIEGE) { ent->client->ps.persistant[PERS_TEAM] = ent->client->playerTeam; } - ent->use = NPC_Use; + ent->use = NPC_Use; ent->think = NPC_Think; ent->nextthink = level.time + FRAMETIME + Q_irand(0, 100); - NPC_SetMiscDefaultData( ent ); - if ( ent->health <= 0 ) - { - //ORIGINAL ID: health will count down towards max_health + NPC_SetMiscDefaultData(ent); + if (ent->health <= 0) { + // ORIGINAL ID: health will count down towards max_health ent->health = client->ps.stats[STAT_HEALTH] = ent->client->pers.maxHealth; - } - else - { + } else { client->ps.stats[STAT_HEALTH] = ent->health; } - if (ent->s.shouldtarget) - { + if (ent->s.shouldtarget) { ent->maxHealth = ent->health; G_ScaleNetHealth(ent); } - ChangeWeapon( ent, ent->client->ps.weapon );//yes, again... sigh + ChangeWeapon(ent, ent->client->ps.weapon); // yes, again... sigh - if ( !(ent->spawnflags & SFB_STARTINSOLID) ) - {//Not okay to start in solid - G_CheckInSolid( ent, qtrue ); + if (!(ent->spawnflags & SFB_STARTINSOLID)) { // Not okay to start in solid + G_CheckInSolid(ent, qtrue); } - VectorClear( ent->NPC->lastClearOrigin ); + VectorClear(ent->NPC->lastClearOrigin); - //Run a script if you have one assigned to you - if ( G_ActivateBehavior( ent, BSET_SPAWN ) ) - { + // Run a script if you have one assigned to you + if (G_ActivateBehavior(ent, BSET_SPAWN)) { trap->ICARUS_MaintainTaskManager(ent->s.number); } - VectorCopy( ent->r.currentOrigin, ent->client->renderInfo.eyePoint ); + VectorCopy(ent->r.currentOrigin, ent->client->renderInfo.eyePoint); // run a client frame to drop exactly to the floor, // initialize animations and other things - memset( &ucmd, 0, sizeof( ucmd ) ); + memset(&ucmd, 0, sizeof(ucmd)); //_VectorCopy( client->pers.cmd_angles, ucmd.angles ); VectorCopyM(client->pers.cmd.angles, ucmd.angles); ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON ) - { - //G_MatchPlayerWeapon( ent ); - //rwwFIXMEFIXME: Use this? Probably doesn't really matter for MP. + if (ent->NPC->aiFlags & NPCAI_MATCHPLAYERWEAPON) { + // G_MatchPlayerWeapon( ent ); + // rwwFIXMEFIXME: Use this? Probably doesn't really matter for MP. } - ClientThink( ent->s.number, &ucmd ); + ClientThink(ent->s.number, &ucmd); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); - if ( ent->client->playerTeam == NPCTEAM_ENEMY ) - {//valid enemy spawned - if ( !(ent->spawnflags&SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC ) - {//not a cinematic enemy - if ( g_entities[0].client ) - { - //g_entities[0].client->sess.missionStats.enemiesSpawned++; - //rwwFIXMEFIXME: Do something here? And this is a rather strange place to be storing - //this sort of data. + if (ent->client->playerTeam == NPCTEAM_ENEMY) { // valid enemy spawned + if (!(ent->spawnflags & SFB_CINEMATIC) && ent->NPC->behaviorState != BS_CINEMATIC) { // not a cinematic enemy + if (g_entities[0].client) { + // g_entities[0].client->sess.missionStats.enemiesSpawned++; + // rwwFIXMEFIXME: Do something here? And this is a rather strange place to be storing + // this sort of data. } } } ent->waypoint = ent->NPC->homeWp = WAYPOINT_NONE; - if ( ent->m_pVehicle ) - {//a vehicle - //check for droidunit - if ( ent->m_pVehicle->m_iDroidUnitTag != -1 ) - { - char *droidNPCType = NULL; + if (ent->m_pVehicle) { // a vehicle + // check for droidunit + if (ent->m_pVehicle->m_iDroidUnitTag != -1) { + char *droidNPCType = NULL; gentity_t *droidEnt = NULL; - if ( ent->model2 - && ent->model2[0] ) - {//specified on the NPC_Vehicle spawner ent + if (ent->model2 && ent->model2[0]) { // specified on the NPC_Vehicle spawner ent droidNPCType = ent->model2; - } - else if ( ent->m_pVehicle->m_pVehicleInfo->droidNPC - && ent->m_pVehicle->m_pVehicleInfo->droidNPC[0] ) - {//specified in the vehicle's .veh file + } else if (ent->m_pVehicle->m_pVehicleInfo->droidNPC && ent->m_pVehicle->m_pVehicleInfo->droidNPC[0]) { // specified in the vehicle's .veh file droidNPCType = ent->m_pVehicle->m_pVehicleInfo->droidNPC; } - if ( droidNPCType != NULL ) - { - if ( Q_stricmp( "random", droidNPCType ) == 0 - || Q_stricmp( "default", droidNPCType ) == 0 ) - {//use default - R2D2 or R5D2 - if ( Q_irand( 0, 1 ) ) - { + if (droidNPCType != NULL) { + if (Q_stricmp("random", droidNPCType) == 0 || Q_stricmp("default", droidNPCType) == 0) { // use default - R2D2 or R5D2 + if (Q_irand(0, 1)) { droidNPCType = "r2d2"; - } - else - { + } else { droidNPCType = "r5d2"; } } - droidEnt = NPC_SpawnType( ent, droidNPCType, NULL, qfalse ); - if ( droidEnt != NULL ) - { - if ( droidEnt->client ) - { - droidEnt->client->ps.m_iVehicleNum = - droidEnt->s.m_iVehicleNum = - //droidEnt->s.otherEntityNum2 = - droidEnt->s.owner = - droidEnt->r.ownerNum = ent->s.number; + droidEnt = NPC_SpawnType(ent, droidNPCType, NULL, qfalse); + if (droidEnt != NULL) { + if (droidEnt->client) { + droidEnt->client->ps.m_iVehicleNum = droidEnt->s.m_iVehicleNum = + // droidEnt->s.otherEntityNum2 = + droidEnt->s.owner = droidEnt->r.ownerNum = ent->s.number; ent->m_pVehicle->m_pDroidUnit = (bgEntity_t *)droidEnt; - //SP way: - //droidEnt->s.m_iVehicleNum = ent->s.number; - //droidEnt->owner = ent; - VectorCopy( ent->r.currentOrigin, droidEnt->s.origin ); - VectorCopy( ent->r.currentOrigin, droidEnt->client->ps.origin ); - G_SetOrigin( droidEnt, droidEnt->s.origin ); - trap->LinkEntity( (sharedEntity_t *)droidEnt ); - VectorCopy( ent->r.currentAngles, droidEnt->s.angles ); - G_SetAngles( droidEnt, droidEnt->s.angles ); - if ( droidEnt->NPC ) - { + // SP way: + // droidEnt->s.m_iVehicleNum = ent->s.number; + // droidEnt->owner = ent; + VectorCopy(ent->r.currentOrigin, droidEnt->s.origin); + VectorCopy(ent->r.currentOrigin, droidEnt->client->ps.origin); + G_SetOrigin(droidEnt, droidEnt->s.origin); + trap->LinkEntity((sharedEntity_t *)droidEnt); + VectorCopy(ent->r.currentAngles, droidEnt->s.angles); + G_SetAngles(droidEnt, droidEnt->s.angles); + if (droidEnt->NPC) { droidEnt->NPC->desiredYaw = droidEnt->s.angles[YAW]; droidEnt->NPC->desiredPitch = droidEnt->s.angles[PITCH]; } droidEnt->flags |= FL_UNDYING; - } - else - {//wtf? - G_FreeEntity( droidEnt ); + } else { // wtf? + G_FreeEntity(droidEnt); } } } @@ -1269,22 +1076,19 @@ void NPC_Begin (gentity_t *ent) gNPC_t *gNPCPtrs[MAX_GENTITIES]; -gNPC_t *New_NPC_t(int entNum) -{ +gNPC_t *New_NPC_t(int entNum) { gNPC_t *ptr; - if (!gNPCPtrs[entNum]) - { - gNPCPtrs[entNum] = (gNPC_t *)BG_Alloc (sizeof(gNPC_t)); + if (!gNPCPtrs[entNum]) { + gNPCPtrs[entNum] = (gNPC_t *)BG_Alloc(sizeof(gNPC_t)); } ptr = gNPCPtrs[entNum]; - if (ptr) - { + if (ptr) { // clear it... // - memset(ptr, 0, sizeof( *ptr ) ); + memset(ptr, 0, sizeof(*ptr)); } return ptr; @@ -1338,264 +1142,232 @@ qboolean NPC_StasisSpawn_Go( gentity_t *ent ) return qtrue; } */ -void NPC_DefaultScriptFlags( gentity_t *ent ) -{ - if ( !ent || !ent->NPC ) - { +void NPC_DefaultScriptFlags(gentity_t *ent) { + if (!ent || !ent->NPC) { return; } - //Set up default script flags - ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES|SCF_LOOK_FOR_ENEMIES); + // Set up default script flags + ent->NPC->scriptFlags = (SCF_CHASE_ENEMIES | SCF_LOOK_FOR_ENEMIES); } /* ------------------------- NPC_Spawn_Go ------------------------- */ -extern void G_CreateAnimalNPC( Vehicle_t **pVeh, const char *strAnimalType ); -extern void G_CreateSpeederNPC( Vehicle_t **pVeh, const char *strType ); -extern void G_CreateWalkerNPC( Vehicle_t **pVeh, const char *strAnimalType ); -extern void G_CreateFighterNPC( Vehicle_t **pVeh, const char *strType ); +extern void G_CreateAnimalNPC(Vehicle_t **pVeh, const char *strAnimalType); +extern void G_CreateSpeederNPC(Vehicle_t **pVeh, const char *strType); +extern void G_CreateWalkerNPC(Vehicle_t **pVeh, const char *strAnimalType); +extern void G_CreateFighterNPC(Vehicle_t **pVeh, const char *strType); -gentity_t *NPC_Spawn_Do( gentity_t *ent ) -{ - gentity_t *newent = NULL; - int index; - vec3_t saveOrg; +gentity_t *NPC_Spawn_Do(gentity_t *ent) { + gentity_t *newent = NULL; + int index; + vec3_t saveOrg; -/* //Do extra code for stasis spawners - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ + /* //Do extra code for stasis spawners + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ - //Test for drop to floor - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - trace_t tr; - vec3_t bottom; + // Test for drop to floor + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + trace_t tr; + vec3_t bottom; - VectorCopy( ent->r.currentOrigin, saveOrg ); - VectorCopy( ent->r.currentOrigin, bottom ); + VectorCopy(ent->r.currentOrigin, saveOrg); + VectorCopy(ent->r.currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, bottom, ent->s.number, MASK_NPCSOLID, qfalse, 0, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, bottom, ent->s.number, MASK_NPCSOLID, qfalse, 0, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); } } - //Check the spawner's count - if( ent->count != -1 ) - { + // Check the spawner's count + if (ent->count != -1) { ent->count--; - if( ent->count <= 0 ) - { - ent->use = 0;//never again - //FIXME: why not remove me...? Because of all the string pointers? Just do G_NewStrings? + if (ent->count <= 0) { + ent->use = 0; // never again + // FIXME: why not remove me...? Because of all the string pointers? Just do G_NewStrings? } } newent = G_Spawn(); - if ( newent == NULL ) - { - Com_Printf ( S_COLOR_RED "ERROR: NPC G_Spawn failed\n" ); + if (newent == NULL) { + Com_Printf(S_COLOR_RED "ERROR: NPC G_Spawn failed\n"); return NULL; } newent->fullName = ent->fullName; newent->NPC = New_NPC_t(newent->s.number); - if ( newent->NPC == NULL ) - { - Com_Printf ( S_COLOR_RED "ERROR: NPC G_Alloc NPC failed\n" ); + if (newent->NPC == NULL) { + Com_Printf(S_COLOR_RED "ERROR: NPC G_Alloc NPC failed\n"); goto finish; - // return NULL; + // return NULL; } - //newent->client = (gclient_s *)G_Alloc (sizeof(gclient_s)); + // newent->client = (gclient_s *)G_Alloc (sizeof(gclient_s)); G_CreateFakeClient(newent->s.number, &newent->client); newent->NPC->tempGoal = G_Spawn(); - if ( newent->NPC->tempGoal == NULL ) - { + if (newent->NPC->tempGoal == NULL) { newent->NPC = NULL; goto finish; - // return NULL; + // return NULL; } newent->NPC->tempGoal->classname = "NPC_goal"; newent->NPC->tempGoal->parent = newent; newent->NPC->tempGoal->r.svFlags |= SVF_NOCLIENT; - if ( newent->client == NULL ) - { - Com_Printf ( S_COLOR_RED "ERROR: NPC BG_Alloc client failed\n" ); + if (newent->client == NULL) { + Com_Printf(S_COLOR_RED "ERROR: NPC BG_Alloc client failed\n"); goto finish; - // return NULL; + // return NULL; } - memset ( newent->client, 0, sizeof(*newent->client) ); + memset(newent->client, 0, sizeof(*newent->client)); - //Assign the pointer for bg entity access + // Assign the pointer for bg entity access newent->playerState = &newent->client->ps; -//==NPC_Connect( newent, net_name );=================================== + //==NPC_Connect( newent, net_name );=================================== - if ( ent->NPC_type == NULL ) - { + if (ent->NPC_type == NULL) { ent->NPC_type = "random"; - } - else - { - ent->NPC_type = Q_strlwr( G_NewString( ent->NPC_type ) ); + } else { + ent->NPC_type = Q_strlwr(G_NewString(ent->NPC_type)); } - if ( ent->r.svFlags & SVF_NO_BASIC_SOUNDS ) - { + if (ent->r.svFlags & SVF_NO_BASIC_SOUNDS) { newent->r.svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( ent->r.svFlags & SVF_NO_COMBAT_SOUNDS ) - { + if (ent->r.svFlags & SVF_NO_COMBAT_SOUNDS) { newent->r.svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( ent->r.svFlags & SVF_NO_EXTRA_SOUNDS ) - { + if (ent->r.svFlags & SVF_NO_EXTRA_SOUNDS) { newent->r.svFlags |= SVF_NO_EXTRA_SOUNDS; } - if ( ent->message ) - {//has a key - newent->message = ent->message;//transfer the key name - newent->flags |= FL_NO_KNOCKBACK;//don't fall off ledges + if (ent->message) { // has a key + newent->message = ent->message; // transfer the key name + newent->flags |= FL_NO_KNOCKBACK; // don't fall off ledges } // If this is a vehicle we need to see what kind it is so we properlly allocate it. - if ( Q_stricmp( ent->classname, "NPC_Vehicle" ) == 0 ) - { + if (Q_stricmp(ent->classname, "NPC_Vehicle") == 0) { // Get the vehicle entry index. - int iVehIndex = BG_VehicleGetIndex( ent->NPC_type ); + int iVehIndex = BG_VehicleGetIndex(ent->NPC_type); - if ( iVehIndex == VEHICLE_NONE ) - { - G_FreeEntity( newent ); - //get rid of the spawner, too, I guess - G_FreeEntity( ent ); + if (iVehIndex == VEHICLE_NONE) { + G_FreeEntity(newent); + // get rid of the spawner, too, I guess + G_FreeEntity(ent); return NULL; } // NOTE: If you change/add any of these, update NPC_Spawn_f for the new vehicle you // want to be able to spawn in manually. // See what kind of vehicle this is and allocate it properly. - switch( g_vehicleInfo[iVehIndex].type ) - { - case VH_ANIMAL: - // Create the animal (making sure all it's data is initialized). - G_CreateAnimalNPC( &newent->m_pVehicle, ent->NPC_type ); - break; - case VH_SPEEDER: - // Create the speeder (making sure all it's data is initialized). - G_CreateSpeederNPC( &newent->m_pVehicle, ent->NPC_type ); - break; - case VH_FIGHTER: - // Create the fighter (making sure all it's data is initialized). - G_CreateFighterNPC( &newent->m_pVehicle, ent->NPC_type ); - break; - case VH_WALKER: - // Create the walker (making sure all it's data is initialized). - G_CreateWalkerNPC( &newent->m_pVehicle, ent->NPC_type ); - break; + switch (g_vehicleInfo[iVehIndex].type) { + case VH_ANIMAL: + // Create the animal (making sure all it's data is initialized). + G_CreateAnimalNPC(&newent->m_pVehicle, ent->NPC_type); + break; + case VH_SPEEDER: + // Create the speeder (making sure all it's data is initialized). + G_CreateSpeederNPC(&newent->m_pVehicle, ent->NPC_type); + break; + case VH_FIGHTER: + // Create the fighter (making sure all it's data is initialized). + G_CreateFighterNPC(&newent->m_pVehicle, ent->NPC_type); + break; + case VH_WALKER: + // Create the walker (making sure all it's data is initialized). + G_CreateWalkerNPC(&newent->m_pVehicle, ent->NPC_type); + break; - default: - Com_Printf ( S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type ); - G_FreeEntity( newent ); - //get rid of the spawner, too, I guess - G_FreeEntity( ent ); - return NULL; + default: + Com_Printf(S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type); + G_FreeEntity(newent); + // get rid of the spawner, too, I guess + G_FreeEntity(ent); + return NULL; } - assert(newent->m_pVehicle && - newent->m_pVehicle->m_pVehicleInfo && - newent->m_pVehicle->m_pVehicleInfo->Initialize); + assert(newent->m_pVehicle && newent->m_pVehicle->m_pVehicleInfo && newent->m_pVehicle->m_pVehicleInfo->Initialize); - //set up my happy prediction hack + // set up my happy prediction hack newent->m_pVehicle->m_vOrientation = &newent->client->ps.vehOrientation[0]; // Setup the vehicle. newent->m_pVehicle->m_pParentEntity = (bgEntity_t *)newent; - newent->m_pVehicle->m_pVehicleInfo->Initialize( newent->m_pVehicle ); + newent->m_pVehicle->m_pVehicleInfo->Initialize(newent->m_pVehicle); - //cache all the assets - newent->m_pVehicle->m_pVehicleInfo->RegisterAssets( newent->m_pVehicle ); - //set the class + // cache all the assets + newent->m_pVehicle->m_pVehicleInfo->RegisterAssets(newent->m_pVehicle); + // set the class newent->client->NPC_class = CLASS_VEHICLE; - if ( g_vehicleInfo[iVehIndex].type == VH_FIGHTER ) - {//FIXME: EXTERN!!! - newent->flags |= (FL_NO_KNOCKBACK|FL_SHIELDED|FL_DMG_BY_HEAVY_WEAP_ONLY);//don't get pushed around, blasters bounce off, only damage from heavy weaps + if (g_vehicleInfo[iVehIndex].type == VH_FIGHTER) { // FIXME: EXTERN!!! + newent->flags |= + (FL_NO_KNOCKBACK | FL_SHIELDED | FL_DMG_BY_HEAVY_WEAP_ONLY); // don't get pushed around, blasters bounce off, only damage from heavy weaps } - //WTF?!!! Ships spawning in pointing straight down! - //set them up to start landed + // WTF?!!! Ships spawning in pointing straight down! + // set them up to start landed newent->m_pVehicle->m_vOrientation[YAW] = ent->s.angles[YAW]; newent->m_pVehicle->m_vOrientation[PITCH] = newent->m_pVehicle->m_vOrientation[ROLL] = 0.0f; - G_SetAngles( newent, newent->m_pVehicle->m_vOrientation ); - SetClientViewAngle( newent, newent->m_pVehicle->m_vOrientation ); + G_SetAngles(newent, newent->m_pVehicle->m_vOrientation); + SetClientViewAngle(newent, newent->m_pVehicle->m_vOrientation); - //newent->m_pVehicle->m_ulFlags |= VEH_GEARSOPEN; - //why? this would just make it so the initial anim never got played... -rww - //There was no initial anim, it would just open the gear even though it's already on the ground (fixed now, made an initial anim) + // newent->m_pVehicle->m_ulFlags |= VEH_GEARSOPEN; + // why? this would just make it so the initial anim never got played... -rww + // There was no initial anim, it would just open the gear even though it's already on the ground (fixed now, made an initial anim) - //For SUSPEND spawnflag, the amount of time to drop like a rock after SUSPEND turns off + // For SUSPEND spawnflag, the amount of time to drop like a rock after SUSPEND turns off newent->fly_sound_debounce_time = ent->fly_sound_debounce_time; - //for no-pilot-death delay + // for no-pilot-death delay newent->damage = ent->damage; - //no-pilot-death distance + // no-pilot-death distance newent->speed = ent->speed; - //for veh transfer all healy stuff + // for veh transfer all healy stuff newent->healingclass = ent->healingclass; newent->healingsound = ent->healingsound; newent->healingrate = ent->healingrate; - newent->model2 = ent->model2;//for droidNPC - } - else - { - newent->client->ps.weapon = WP_NONE;//init for later check in NPC_Begin + newent->model2 = ent->model2; // for droidNPC + } else { + newent->client->ps.weapon = WP_NONE; // init for later check in NPC_Begin } VectorCopy(ent->s.origin, newent->s.origin); VectorCopy(ent->s.origin, newent->client->ps.origin); VectorCopy(ent->s.origin, newent->r.currentOrigin); - G_SetOrigin(newent, ent->s.origin);//just to be sure! - //NOTE: on vehicles, anything in the .npc file will STOMP data on the NPC that's set by the vehicle - if ( !NPC_ParseParms( ent->NPC_type, newent ) ) - { - Com_Printf ( S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type ); - G_FreeEntity( newent ); - //get rid of the spawner, too, I guess - G_FreeEntity( ent ); + G_SetOrigin(newent, ent->s.origin); // just to be sure! + // NOTE: on vehicles, anything in the .npc file will STOMP data on the NPC that's set by the vehicle + if (!NPC_ParseParms(ent->NPC_type, newent)) { + Com_Printf(S_COLOR_RED "ERROR: Couldn't spawn NPC %s\n", ent->NPC_type); + G_FreeEntity(newent); + // get rid of the spawner, too, I guess + G_FreeEntity(ent); return NULL; } - if ( ent->NPC_type ) - { - if ( !Q_stricmp( ent->NPC_type, "kyle" ) ) - {//FIXME: "player", not Kyle? Or check NPC_type against player's NPC_type? + if (ent->NPC_type) { + if (!Q_stricmp(ent->NPC_type, "kyle")) { // FIXME: "player", not Kyle? Or check NPC_type against player's NPC_type? newent->NPC->aiFlags |= NPCAI_MATCHPLAYERWEAPON; - } - else if ( !Q_stricmp( ent->NPC_type, "test" ) ) - { - int n; - for ( n = 0; n < 1 ; n++) - { - if ( g_entities[n].s.eType != ET_NPC && g_entities[n].client) - { + } else if (!Q_stricmp(ent->NPC_type, "test")) { + int n; + for (n = 0; n < 1; n++) { + if (g_entities[n].s.eType != ET_NPC && g_entities[n].client) { VectorCopy(g_entities[n].s.origin, newent->s.origin); newent->client->playerTeam = newent->s.teamowner = g_entities[n].client->playerTeam; break; @@ -1603,27 +1375,24 @@ gentity_t *NPC_Spawn_Do( gentity_t *ent ) } newent->NPC->defaultBehavior = newent->NPC->behaviorState = BS_WAIT; newent->classname = "NPC"; - // newent->r.svFlags |= SVF_NOPUSH; + // newent->r.svFlags |= SVF_NOPUSH; } } -//===================================================================== - //set the info we want - if ( !newent->health ) - { + //===================================================================== + // set the info we want + if (!newent->health) { newent->health = ent->health; } newent->script_targetname = ent->NPC_targetname; newent->targetname = ent->NPC_targetname; - newent->target = ent->NPC_target;//death - newent->target2 = ent->target2;//knocked out death - newent->target3 = ent->target3;//??? - newent->target4 = ent->target4;//ffire death + newent->target = ent->NPC_target; // death + newent->target2 = ent->target2; // knocked out death + newent->target3 = ent->target3; //??? + newent->target4 = ent->target4; // ffire death newent->wait = ent->wait; - for( index = BSET_FIRST; index < NUM_BSETS; index++) - { - if ( ent->behaviorSet[index] ) - { + for (index = BSET_FIRST; index < NUM_BSETS; index++) { + if (ent->behaviorSet[index]) { newent->behaviorSet[index] = ent->behaviorSet[index]; } } @@ -1635,120 +1404,99 @@ gentity_t *NPC_Spawn_Do( gentity_t *ent ) VectorCopy(ent->s.angles, newent->s.angles); VectorCopy(ent->s.angles, newent->r.currentAngles); VectorCopy(ent->s.angles, newent->client->ps.viewangles); - newent->NPC->desiredYaw =ent->s.angles[YAW]; + newent->NPC->desiredYaw = ent->s.angles[YAW]; trap->LinkEntity((sharedEntity_t *)newent); newent->spawnflags = ent->spawnflags; - if(ent->paintarget) - { //safe to point at owner's string since memory is never freed during game + if (ent->paintarget) { // safe to point at owner's string since memory is never freed during game newent->paintarget = ent->paintarget; } - if(ent->opentarget) - { + if (ent->opentarget) { newent->opentarget = ent->opentarget; } -//==New stuff===================================================================== - newent->s.eType = ET_NPC;//ET_PLAYER; + //==New stuff===================================================================== + newent->s.eType = ET_NPC; // ET_PLAYER; - //FIXME: Call CopyParms - if ( ent->parms ) - { + // FIXME: Call CopyParms + if (ent->parms) { int parmNum; - for ( parmNum = 0; parmNum < MAX_PARMS; parmNum++ ) - { - if ( ent->parms->parm[parmNum][0] ) - { - Q3_SetParm( newent->s.number, parmNum, ent->parms->parm[parmNum] ); + for (parmNum = 0; parmNum < MAX_PARMS; parmNum++) { + if (ent->parms->parm[parmNum][0]) { + Q3_SetParm(newent->s.number, parmNum, ent->parms->parm[parmNum]); } } } - //FIXME: copy cameraGroup, store mine in message or other string field + // FIXME: copy cameraGroup, store mine in message or other string field - //set origin + // set origin newent->s.pos.trType = TR_INTERPOLATE; newent->s.pos.trTime = level.time; - VectorCopy( newent->r.currentOrigin, newent->s.pos.trBase ); - VectorClear( newent->s.pos.trDelta ); + VectorCopy(newent->r.currentOrigin, newent->s.pos.trBase); + VectorClear(newent->s.pos.trDelta); newent->s.pos.trDuration = 0; - //set angles + // set angles newent->s.apos.trType = TR_INTERPOLATE; newent->s.apos.trTime = level.time; - //VectorCopy( newent->r.currentOrigin, newent->s.apos.trBase ); - //Why was the origin being used as angles? Typo I'm assuming -rww - VectorCopy( newent->s.angles, newent->s.apos.trBase ); + // VectorCopy( newent->r.currentOrigin, newent->s.apos.trBase ); + // Why was the origin being used as angles? Typo I'm assuming -rww + VectorCopy(newent->s.angles, newent->s.apos.trBase); - VectorClear( newent->s.apos.trDelta ); + VectorClear(newent->s.apos.trDelta); newent->s.apos.trDuration = 0; newent->NPC->combatPoint = -1; - newent->flags |= FL_NOTARGET;//So he's ignored until he's fully spawned - newent->s.eFlags |= EF_NODRAW;//So he's ignored until he's fully spawned + newent->flags |= FL_NOTARGET; // So he's ignored until he's fully spawned + newent->s.eFlags |= EF_NODRAW; // So he's ignored until he's fully spawned newent->think = NPC_Begin; newent->nextthink = level.time + FRAMETIME; - NPC_DefaultScriptFlags( newent ); + NPC_DefaultScriptFlags(newent); - //copy over team variables, too + // copy over team variables, too newent->s.shouldtarget = ent->s.shouldtarget; newent->s.teamowner = ent->s.teamowner; newent->alliedTeam = ent->alliedTeam; newent->teamnodmg = ent->teamnodmg; - if ( ent->team && ent->team[0] ) - {//specified team directly? + if (ent->team && ent->team[0]) { // specified team directly? newent->client->sess.sessionTeam = atoi(ent->team); - } - else if ( newent->s.teamowner != TEAM_FREE ) - { + } else if (newent->s.teamowner != TEAM_FREE) { newent->client->sess.sessionTeam = newent->s.teamowner; - } - else if ( newent->alliedTeam != TEAM_FREE ) - { + } else if (newent->alliedTeam != TEAM_FREE) { newent->client->sess.sessionTeam = newent->alliedTeam; - } - else if ( newent->teamnodmg != TEAM_FREE ) - { + } else if (newent->teamnodmg != TEAM_FREE) { newent->client->sess.sessionTeam = newent->teamnodmg; - } - else - { + } else { newent->client->sess.sessionTeam = TEAM_FREE; } newent->client->ps.persistant[PERS_TEAM] = newent->client->sess.sessionTeam; - trap->LinkEntity ((sharedEntity_t *)newent); + trap->LinkEntity((sharedEntity_t *)newent); - if(!ent->use) - { - if( ent->target ) - {//use any target we're pointed at - G_UseTargets ( ent, ent ); + if (!ent->use) { + if (ent->target) { // use any target we're pointed at + G_UseTargets(ent, ent); } - if(ent->closetarget) - {//last guy should fire this target when he dies + if (ent->closetarget) { // last guy should fire this target when he dies newent->target = ent->closetarget; } ent->targetname = NULL; - //why not remove me...? Because of all the string pointers? Just do G_NewStrings? - G_FreeEntity( ent );//bye! + // why not remove me...? Because of all the string pointers? Just do G_NewStrings? + G_FreeEntity(ent); // bye! } finish: - if ( ent->spawnflags & NSF_DROP_TO_FLOOR ) - { - G_SetOrigin( ent, saveOrg ); + if (ent->spawnflags & NSF_DROP_TO_FLOOR) { + G_SetOrigin(ent, saveOrg); } return newent; } -void NPC_Spawn_Go(gentity_t *ent) -{ - NPC_Spawn_Do(ent); -} +void NPC_Spawn_Go(gentity_t *ent) { NPC_Spawn_Do(ent); } /* ------------------------- @@ -1790,27 +1538,26 @@ NPC_ShySpawn ------------------------- */ -#define SHY_THINK_TIME 1000 -#define SHY_SPAWN_DISTANCE 128 -#define SHY_SPAWN_DISTANCE_SQR ( SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE ) +#define SHY_THINK_TIME 1000 +#define SHY_SPAWN_DISTANCE 128 +#define SHY_SPAWN_DISTANCE_SQR (SHY_SPAWN_DISTANCE * SHY_SPAWN_DISTANCE) -void NPC_ShySpawn( gentity_t *ent ) -{ +void NPC_ShySpawn(gentity_t *ent) { ent->nextthink = level.time + SHY_THINK_TIME; ent->think = NPC_ShySpawn; - //rwwFIXMEFIXME: Care about other clients not just 0? - if ( DistanceSquared( g_entities[0].r.currentOrigin, ent->r.currentOrigin ) <= SHY_SPAWN_DISTANCE_SQR ) + // rwwFIXMEFIXME: Care about other clients not just 0? + if (DistanceSquared(g_entities[0].r.currentOrigin, ent->r.currentOrigin) <= SHY_SPAWN_DISTANCE_SQR) return; - if ( (InFOV( ent, &g_entities[0], 80, 64 )) ) // FIXME: hardcoded fov - if ( (NPC_ClearLOS2( &g_entities[0], ent->r.currentOrigin )) ) + if ((InFOV(ent, &g_entities[0], 80, 64))) // FIXME: hardcoded fov + if ((NPC_ClearLOS2(&g_entities[0], ent->r.currentOrigin))) return; ent->think = 0; ent->nextthink = 0; - NPC_Spawn_Go( ent ); + NPC_Spawn_Go(ent); } /* @@ -1819,38 +1566,30 @@ NPC_Spawn ------------------------- */ -void NPC_Spawn ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - //delay before spawning NPC - if( ent->delay ) - { -/* //Stasis does an extra step - if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) - { - if ( NPC_StasisSpawn_Go( ent ) == qfalse ) - return; - } -*/ - if ( ent->spawnflags & 2048 ) // SHY +void NPC_Spawn(gentity_t *ent, gentity_t *other, gentity_t *activator) { + // delay before spawning NPC + if (ent->delay) { + /* //Stasis does an extra step + if ( Q_stricmp( ent->classname, "NPC_Stasis" ) == 0 ) + { + if ( NPC_StasisSpawn_Go( ent ) == qfalse ) + return; + } + */ + if (ent->spawnflags & 2048) // SHY { ent->think = NPC_ShySpawn; - } - else - { + } else { ent->think = NPC_Spawn_Go; } ent->nextthink = level.time + ent->delay; - } - else - { - if ( ent->spawnflags & 2048 ) // SHY - { - NPC_ShySpawn( ent ); - } - else + } else { + if (ent->spawnflags & 2048) // SHY { - NPC_Spawn_Do( ent ); + NPC_ShySpawn(ent); + } else { + NPC_Spawn_Do(ent); } } } @@ -1891,7 +1630,7 @@ fleescript - default script to run when hit and below 50% health (none by defaul deathscript - default script to run when killed (none by default) These strings can be used to activate behaviors instead of scripts - these are checked first and so no scripts should be names with these names: - default - 0: whatever + default - 0: whatever idle - 1: Stand around, do abolutely nothing roam - 2: Roam around, collect stuff walk - 3: Crouch-Walk toward their goals @@ -1938,75 +1677,62 @@ teamnodmg - team that NPC does not take damage from (turrets and other auto-defe "noCombatSounds" - set to 1 to prevent loading and usage of combat sounds (anger, victory, etc.) "noExtraSounds" - set to 1 to prevent loading and usage of "extra" sounds (chasing the enemy - detecting them, flanking them... also jedi combat sounds) */ -extern void NPC_PrecacheAnimationCFG( const char *NPC_type ); -void NPC_Precache ( gentity_t *spawner ); -void NPC_PrecacheType( char *NPC_type ) -{ +extern void NPC_PrecacheAnimationCFG(const char *NPC_type); +void NPC_Precache(gentity_t *spawner); +void NPC_PrecacheType(char *NPC_type) { gentity_t *fakespawner = G_Spawn(); - if ( fakespawner ) - { + if (fakespawner) { fakespawner->NPC_type = NPC_type; - NPC_Precache( fakespawner ); - //NOTE: does the spawner have to stay around to send any precached info to the clients...? - G_FreeEntity( fakespawner ); + NPC_Precache(fakespawner); + // NOTE: does the spawner have to stay around to send any precached info to the clients...? + G_FreeEntity(fakespawner); } } -void SP_NPC_spawner( gentity_t *self) -{ +void SP_NPC_spawner(gentity_t *self) { int t; - if (!g_allowNPC.integer) - { + if (!g_allowNPC.integer) { self->think = G_FreeEntity; self->nextthink = level.time; return; } - if ( !self->fullName || !self->fullName[0] ) - { - //FIXME: make an index into an external string table for localization + if (!self->fullName || !self->fullName[0]) { + // FIXME: make an index into an external string table for localization self->fullName = "Humanoid Lifeform"; } - //register/precache the models needed for this NPC, not anymore - //self->classname = "NPC_spawner"; + // register/precache the models needed for this NPC, not anymore + // self->classname = "NPC_spawner"; - if(!self->count) - { + if (!self->count) { self->count = 1; } - {//Stop loading of certain extra sounds - static int garbage; + { // Stop loading of certain extra sounds + static int garbage; - if ( G_SpawnInt( "noBasicSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noBasicSounds", "0", &garbage)) { self->r.svFlags |= SVF_NO_BASIC_SOUNDS; } - if ( G_SpawnInt( "noCombatSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noCombatSounds", "0", &garbage)) { self->r.svFlags |= SVF_NO_COMBAT_SOUNDS; } - if ( G_SpawnInt( "noExtraSounds", "0", &garbage ) ) - { + if (G_SpawnInt("noExtraSounds", "0", &garbage)) { self->r.svFlags |= SVF_NO_EXTRA_SOUNDS; } } - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; - } - else - { - self->wait *= 1000;//1 = 1 msec, 1000 = 1 sec + } else { + self->wait *= 1000; // 1 = 1 msec, 1000 = 1 sec } - self->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + self->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - G_SpawnInt( "showhealth", "0", &t ); - if (t) - { + G_SpawnInt("showhealth", "0", &t); + if (t) { self->s.shouldtarget = qtrue; } /* @@ -2015,55 +1741,49 @@ void SP_NPC_spawner( gentity_t *self) self->r.svFlags |= SVF_NPC_PRECACHE; } */ - //rwwFIXMEFIXME: support for this flag? + // rwwFIXMEFIXME: support for this flag? - //We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid - NPC_PrecacheAnimationCFG( self->NPC_type ); + // We have to load the animation.cfg now because spawnscripts are going to want to set anims and we need to know their length and if they're valid + NPC_PrecacheAnimationCFG(self->NPC_type); - //rww - can't cheat and do this on the client like in SP, so I'm doing this. + // rww - can't cheat and do this on the client like in SP, so I'm doing this. NPC_Precache(self); - if ( self->targetname ) - {//Wait for triggering + if (self->targetname) { // Wait for triggering self->use = NPC_Spawn; - // self->r.svFlags |= SVF_NPC_PRECACHE;//FIXME: precache my weapons somehow? - - //NPC_PrecacheModels( self->NPC_type ); - } - else - { - //NOTE: auto-spawners never check for shy spawning - //if ( spawning ) - if (1) //just gonna always do this I suppose. - {//in entity spawn stage - map starting up + // self->r.svFlags |= SVF_NPC_PRECACHE;//FIXME: precache my weapons somehow? + + // NPC_PrecacheModels( self->NPC_type ); + } else { + // NOTE: auto-spawners never check for shy spawning + // if ( spawning ) + if (1) // just gonna always do this I suppose. + { // in entity spawn stage - map starting up self->think = NPC_Spawn_Go; self->nextthink = level.time + START_TIME_REMOVE_ENTS + 50; - } - else - {//else spawn right now - NPC_Spawn( self, self, self ); + } else { // else spawn right now + NPC_Spawn(self, self, self); } } - //FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup - //Or just don't include NPC_spawners in cameraGroupings + // FIXME: store cameraGroup somewhere else and apply to spawned NPCs' cameraGroup + // Or just don't include NPC_spawners in cameraGroupings } -extern void G_VehicleSpawn( gentity_t *self ); +extern void G_VehicleSpawn(gentity_t *self); /*QUAKED NPC_Vehicle (1 0 0) (-16 -16 -24) (16 16 32) NO_PILOT_DIE SUSPENDED x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY NO_PILOT_DIE - die after certain amount of time of not having a pilot -SUSPENDED - Fighters: Don't drop until someone gets in it (this only works as long as no-nw has *ever* ridden the vehicle, to simulate ships that are suspended-docked) - note: ships inside trigger_spaces do not drop when unoccupied -CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) -NOTSOLID - Starts not solid -STARTINSOLID - Don't try to fix if spawn in solid -SHY - Spawner is shy +SUSPENDED - Fighters: Don't drop until someone gets in it (this only works as long as no-nw has *ever* ridden the vehicle, to simulate ships that are +suspended-docked) - note: ships inside trigger_spaces do not drop when unoccupied CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) NOTSOLID - Starts not +solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy set NPC_type to vehicle name in vehicles.dat "dropTime" use with SUSPENDED - if set, the vehicle will drop straight down for this number of seconds before flying forward "dmg" use with NO_PILOT_DIE - delay in milliseconds for ship to explode if no pilot (default 10000) "speed" use with NO_PILOT_DIE - distance for pilot to get away from ship after dismounting before it starts counting down the death timer -"model2" - if the vehicle can have a droid (has "*droidunit" tag), this NPC will be spawned and placed there - note: game will automatically use the one specified in the .veh file (if any) or, absent that, it will use an R2D2 or R5D2 NPC) +"model2" - if the vehicle can have a droid (has "*droidunit" tag), this NPC will be spawned and placed there - note: game will automatically use the one +specified in the .veh file (if any) or, absent that, it will use an R2D2 or R5D2 NPC) showhealth - set to 1 to show health bar on this entity when crosshair is over it @@ -2082,41 +1802,34 @@ teamnodmg - team that NPC does not take damage from (turrets and other auto-defe 1 - red 2 - blue */ -qboolean NPC_VehiclePrecache( gentity_t *spawner ) -{ +qboolean NPC_VehiclePrecache(gentity_t *spawner) { char *droidNPCType = NULL; - //This will precache the vehicle + // This will precache the vehicle vehicleInfo_t *pVehInfo; - int iVehIndex = BG_VehicleGetIndex( spawner->NPC_type ); - if ( iVehIndex == VEHICLE_NONE ) - {//fixme: error msg? + int iVehIndex = BG_VehicleGetIndex(spawner->NPC_type); + if (iVehIndex == VEHICLE_NONE) { // fixme: error msg? return qfalse; } - G_ModelIndex(va("$%s", spawner->NPC_type)); //make sure the thing is frickin precached - //now cache his model/skin/anim config + G_ModelIndex(va("$%s", spawner->NPC_type)); // make sure the thing is frickin precached + // now cache his model/skin/anim config pVehInfo = &g_vehicleInfo[iVehIndex]; - if (pVehInfo->model && pVehInfo->model[0]) - { + if (pVehInfo->model && pVehInfo->model[0]) { void *tempG2 = NULL; int skin = 0; - if (pVehInfo->skin && pVehInfo->skin[0]) - { + if (pVehInfo->skin && pVehInfo->skin[0]) { skin = trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", pVehInfo->model, pVehInfo->skin)); } trap->G2API_InitGhoul2Model(&tempG2, va("models/players/%s/model.glm", pVehInfo->model), 0, skin, 0, 0, 0); - if (tempG2) - { //now, cache the anim config. + if (tempG2) { // now, cache the anim config. char GLAName[1024]; GLAName[0] = 0; trap->G2API_GetGLAName(tempG2, 0, GLAName); - if (GLAName[0]) - { - char *slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { + if (GLAName[0]) { + char *slash = Q_strrchr(GLAName, '/'); + if (slash) { strcpy(slash, "/animation.cfg"); BG_ParseAnimationFile(GLAName, NULL, qfalse); @@ -2126,117 +1839,87 @@ qboolean NPC_VehiclePrecache( gentity_t *spawner ) } } - //also precache the droid NPC if there is one - if ( spawner->model2 - && spawner->model2[0] ) - { + // also precache the droid NPC if there is one + if (spawner->model2 && spawner->model2[0]) { droidNPCType = spawner->model2; - } - else if ( g_vehicleInfo[iVehIndex].droidNPC - && g_vehicleInfo[iVehIndex].droidNPC[0] ) - { + } else if (g_vehicleInfo[iVehIndex].droidNPC && g_vehicleInfo[iVehIndex].droidNPC[0]) { droidNPCType = g_vehicleInfo[iVehIndex].droidNPC; } - if ( droidNPCType ) - { - if ( Q_stricmp( "random", droidNPCType ) == 0 - || Q_stricmp( "default", droidNPCType ) == 0 ) - {//precache both r2 and r5, as defaults - NPC_PrecacheType( "r2d2" ); - NPC_PrecacheType( "r5d2" ); - } - else - { - NPC_PrecacheType( droidNPCType ); + if (droidNPCType) { + if (Q_stricmp("random", droidNPCType) == 0 || Q_stricmp("default", droidNPCType) == 0) { // precache both r2 and r5, as defaults + NPC_PrecacheType("r2d2"); + NPC_PrecacheType("r5d2"); + } else { + NPC_PrecacheType(droidNPCType); } } return qtrue; } -void NPC_VehicleSpawnUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->delay ) - { +void NPC_VehicleSpawnUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->delay) { self->think = G_VehicleSpawn; self->nextthink = level.time + self->delay; - } - else - { - G_VehicleSpawn( self ); + } else { + G_VehicleSpawn(self); } } -void SP_NPC_Vehicle( gentity_t *self) -{ +void SP_NPC_Vehicle(gentity_t *self) { float dropTime; - int t; - if ( !self->NPC_type ) - { + int t; + if (!self->NPC_type) { self->NPC_type = "swoop"; } - if ( !self->classname ) - { + if (!self->classname) { self->classname = "NPC_Vehicle"; } - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; + } else { + self->wait *= 1000; // 1 = 1 msec, 1000 = 1 sec } - else - { - self->wait *= 1000;//1 = 1 msec, 1000 = 1 sec - } - self->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + self->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - G_SetOrigin( self, self->s.origin ); - G_SetAngles( self, self->s.angles ); - G_SpawnFloat( "dropTime", "0", &dropTime ); - if ( dropTime ) - { - self->fly_sound_debounce_time = ceil(dropTime*1000.0); + G_SetOrigin(self, self->s.origin); + G_SetAngles(self, self->s.angles); + G_SpawnFloat("dropTime", "0", &dropTime); + if (dropTime) { + self->fly_sound_debounce_time = ceil(dropTime * 1000.0); } - G_SpawnInt( "showhealth", "0", &t ); - if (t) - { + G_SpawnInt("showhealth", "0", &t); + if (t) { self->s.shouldtarget = qtrue; } - //FIXME: PRECACHE!!! + // FIXME: PRECACHE!!! - if ( self->targetname ) - { - if ( !NPC_VehiclePrecache( self ) ) - {//FIXME: err msg? - G_FreeEntity( self ); + if (self->targetname) { + if (!NPC_VehiclePrecache(self)) { // FIXME: err msg? + G_FreeEntity(self); return; } self->use = NPC_VehicleSpawnUse; - } - else - { - if ( self->delay ) - { - if ( !NPC_VehiclePrecache( self ) ) - {//FIXME: err msg? - G_FreeEntity( self ); + } else { + if (self->delay) { + if (!NPC_VehiclePrecache(self)) { // FIXME: err msg? + G_FreeEntity(self); return; } self->think = G_VehicleSpawn; self->nextthink = level.time + self->delay; - } - else - { - G_VehicleSpawn( self ); + } else { + G_VehicleSpawn(self); } } } -//Characters +// Characters -//STAR WARS NPCs============================================================================ +// STAR WARS NPCs============================================================================ /*QUAKED NPC_spawner (1 0 0) (-16 -16 -24) (16 16 32) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2280,7 +1963,7 @@ deathscript - default script to run when killed (none by default) These strings can be used to activate behaviors instead of scripts - these are checked first and so no scripts should be names with these names: - default - 0: whatever + default - 0: whatever idle - 1: Stand around, do abolutely nothing roam - 2: Roam around, collect stuff walk - 3: Crouch-Walk toward their goals @@ -2308,7 +1991,7 @@ delay - after spawned or triggered, how many seconds to wait to spawn the NPC */ //============================================================================================= -//CHARACTERS +// CHARACTERS //============================================================================================= /*QUAKED NPC_Kyle (1 0 0) (-16 -16 -24) (16 16 32) x RIFLEMAN PHASER TRICORDER DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2317,13 +2000,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Kyle( gentity_t *self) -{ +void SP_NPC_Kyle(gentity_t *self) { self->NPC_type = "Kyle"; - WP_SetSaberModel( NULL, CLASS_KYLE ); + WP_SetSaberModel(NULL, CLASS_KYLE); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Lando(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2333,11 +2015,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Lando( gentity_t *self) -{ +void SP_NPC_Lando(gentity_t *self) { self->NPC_type = "Lando"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Jan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2347,11 +2028,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Jan( gentity_t *self) -{ +void SP_NPC_Jan(gentity_t *self) { self->NPC_type = "Jan"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Luke(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2361,13 +2041,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Luke( gentity_t *self) -{ +void SP_NPC_Luke(gentity_t *self) { self->NPC_type = "Luke"; - WP_SetSaberModel( NULL, CLASS_LUKE ); + WP_SetSaberModel(NULL, CLASS_LUKE); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MonMothma(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2377,11 +2056,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MonMothma( gentity_t *self) -{ +void SP_NPC_MonMothma(gentity_t *self) { self->NPC_type = "MonMothma"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tavion (1 0 0) (-16 -16 -24) (16 16 32) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2391,13 +2069,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tavion( gentity_t *self) -{ +void SP_NPC_Tavion(gentity_t *self) { self->NPC_type = "Tavion"; - WP_SetSaberModel( NULL, CLASS_TAVION ); + WP_SetSaberModel(NULL, CLASS_TAVION); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tavion_New (1 0 0) (-16 -16 -24) (16 16 32) SCEPTER SITH_SWORD x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2411,22 +2088,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tavion_New( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Tavion_New(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "tavion_scepter"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "tavion_sith_sword"; - } - else - { + } else { self->NPC_type = "tavion_new"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Alora (1 0 0) (-16 -16 -24) (16 16 32) DUAL x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2439,18 +2110,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Alora( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Alora(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "alora_dual"; - } - else - { + } else { self->NPC_type = "alora"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reborn_New(1 0 0) (-16 -16 -24) (16 16 40) DUAL STAFF WEAK x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2466,43 +2133,28 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reborn_New( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&4) ) - {//weaker guys - if ( (self->spawnflags&1) ) - { +void SP_NPC_Reborn_New(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 4)) { // weaker guys + if ((self->spawnflags & 1)) { self->NPC_type = "reborn_dual2"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "reborn_staff2"; - } - else - { + } else { self->NPC_type = "reborn_new2"; } - } - else - { - if ( (self->spawnflags&1) ) - { + } else { + if ((self->spawnflags & 1)) { self->NPC_type = "reborn_dual"; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "reborn_staff"; - } - else - { + } else { self->NPC_type = "reborn_new"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Saber(1 0 0) (-16 -16 -24) (16 16 40) MED STRONG ALL THROW CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2513,7 +2165,8 @@ default fencer uses fast style - weak, but can attack rapidly. Good defense. MED - Uses medium style - average speed and attack strength, average defense. STRONG - Uses strong style, slower than others, but can do a lot of damage with one blow. Weak defense. ALL - Knows all 3 styles, switches between them, good defense. -THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 spawnflags) +THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 +spawnflags) CEILING - Sticks to the ceiling until he sees an enemy or takes pain CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2521,57 +2174,36 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist_Saber( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { - if ( (self->spawnflags&8) ) - { +void SP_NPC_Cultist_Saber(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_med_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_med"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_strong_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_strong"; } - } - else if ( (self->spawnflags&4) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 4)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_all_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber_all"; } - } - else - { - if ( (self->spawnflags&8) ) - { + } else { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Saber_Powers(1 0 0) (-16 -16 -24) (16 16 40) MED STRONG ALL THROW CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2582,7 +2214,8 @@ default fencer uses fast style - weak, but can attack rapidly. Good defense. MED - Uses medium style - average speed and attack strength, average defense. STRONG - Uses strong style, slower than others, but can do a lot of damage with one blow. Weak defense. ALL - Knows all 3 styles, switches between them, good defense. -THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 spawnflags) +THROW - can throw their saber (level 2) - reduces their defense some (can use this spawnflag alone or in combination with any *one* of the previous 3 +spawnflags) CEILING - Sticks to the ceiling until he sees an enemy or takes pain CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2590,57 +2223,36 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist_Saber_Powers( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { - if ( (self->spawnflags&8) ) - { +void SP_NPC_Cultist_Saber_Powers(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_med_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_med2"; } - } - else if ( (self->spawnflags&2) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 2)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_strong_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_strong2"; } - } - else if ( (self->spawnflags&4) ) - { - if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 4)) { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_all_throw2"; - } - else - { + } else { self->NPC_type = "cultist_saber_all2"; } - } - else - { - if ( (self->spawnflags&8) ) - { + } else { + if ((self->spawnflags & 8)) { self->NPC_type = "cultist_saber_throw"; - } - else - { + } else { self->NPC_type = "cultist_saber2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist(1 0 0) (-16 -16 -24) (16 16 40) SABER GRIP LIGHTNING DRAIN CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2658,52 +2270,39 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Cultist(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = NULL; - self->spawnflags = 0;//fast, no throw - switch ( Q_irand( 0, 2 ) ) - { - case 0://medium + self->spawnflags = 0; // fast, no throw + switch (Q_irand(0, 2)) { + case 0: // medium self->spawnflags |= 1; break; - case 1://strong + case 1: // strong self->spawnflags |= 2; break; - case 2://all + case 2: // all self->spawnflags |= 4; break; } - if ( Q_irand( 0, 1 ) ) - {//throw + if (Q_irand(0, 1)) { // throw self->spawnflags |= 8; } - SP_NPC_Cultist_Saber( self ); + SP_NPC_Cultist_Saber(self); return; - } - else if ( (self->spawnflags&2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "cultist_grip"; - } - else if ( (self->spawnflags&4) ) - { + } else if ((self->spawnflags & 4)) { self->NPC_type = "cultist_lightning"; - } - else if ( (self->spawnflags&8) ) - { + } else if ((self->spawnflags & 8)) { self->NPC_type = "cultist_drain"; - } - else - { + } else { self->NPC_type = "cultist"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Commando(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2716,13 +2315,11 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist_Commando( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Cultist_Commando(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "cultistcommando"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Cultist_Destroyer(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2734,10 +2331,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Cultist_Destroyer( gentity_t *self) -{ - self->NPC_type = "cultist";//"cultist_explode"; - SP_NPC_spawner( self ); +void SP_NPC_Cultist_Destroyer(gentity_t *self) { + self->NPC_type = "cultist"; //"cultist_explode"; + SP_NPC_spawner(self); } /*QUAKED NPC_Reelo(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2747,11 +2343,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reelo( gentity_t *self) -{ +void SP_NPC_Reelo(gentity_t *self) { self->NPC_type = "Reelo"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Galak(1 0 0) (-16 -16 -24) (16 16 40) MECH x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2763,19 +2358,15 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Galak( gentity_t *self) -{ - if ( self->spawnflags & 1 ) - { +void SP_NPC_Galak(gentity_t *self) { + if (self->spawnflags & 1) { self->NPC_type = "Galak_Mech"; NPC_GalakMech_Precache(); - } - else - { + } else { self->NPC_type = "Galak"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Desann(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2785,13 +2376,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Desann( gentity_t *self) -{ +void SP_NPC_Desann(gentity_t *self) { self->NPC_type = "Desann"; - WP_SetSaberModel( NULL, CLASS_DESANN ); + WP_SetSaberModel(NULL, CLASS_DESANN); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Bartender(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2801,11 +2391,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Bartender( gentity_t *self) -{ +void SP_NPC_Bartender(gentity_t *self) { self->NPC_type = "Bartender"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MorganKatarn(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2815,15 +2404,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MorganKatarn( gentity_t *self) -{ +void SP_NPC_MorganKatarn(gentity_t *self) { self->NPC_type = "MorganKatarn"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ALLIES +// ALLIES //============================================================================================= /*QUAKED NPC_Jedi(1 0 0) (-16 -16 -24) (16 16 40) TRAINER MASTER RANDOM x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2838,14 +2426,10 @@ SHY - Spawner is shy Ally Jedi NPC Buddy - tags along with player */ -void SP_NPC_Jedi( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( self->spawnflags & 4 ) - {//random! - switch ( Q_irand( 0, 11 ) ) - { +void SP_NPC_Jedi(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 4) { // random! + switch (Q_irand(0, 11)) { case 0: self->NPC_type = "jedi_hf1"; break; @@ -2880,41 +2464,33 @@ void SP_NPC_Jedi( gentity_t *self) self->NPC_type = "jedi_zf1"; break; case 11: - default://just in case + default: // just in case self->NPC_type = "jedi_zf2"; break; } - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "jedimaster"; - } - else if ( self->spawnflags & 1 ) - { + } else if (self->spawnflags & 1) { self->NPC_type = "jeditrainer"; - } - else - { + } else { /* if ( !Q_irand( 0, 2 ) ) { self->NPC_type = "JediF"; } else - */if ( Q_irand( 0, 1 ) ) - { + */ + if (Q_irand(0, 1)) { self->NPC_type = "Jedi"; - } - else - { + } else { self->NPC_type = "Jedi2"; } } } - WP_SetSaberModel( NULL, CLASS_JEDI ); + WP_SetSaberModel(NULL, CLASS_JEDI); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Prisoner(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2922,23 +2498,18 @@ DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface bel CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid -SHY - Spawner is shy -*/ -void SP_NPC_Prisoner( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( Q_irand( 0, 1 ) ) - { +SHY - Spawner is shy +*/ +void SP_NPC_Prisoner(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Prisoner"; - } - else - { + } else { self->NPC_type = "Prisoner2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rebel(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2948,25 +2519,20 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rebel( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Rebel(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Rebel"; - } - else - { + } else { self->NPC_type = "Rebel2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//ENEMIES +// ENEMIES //============================================================================================= /*QUAKED NPC_Human_Merc(1 0 0) (-16 -16 -24) (16 16 40) BOWCASTER REPEATER FLECHETTE CONCUSSION DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -2979,7 +2545,9 @@ CONCUSSION - Starts with a Concussion Rifle If you want them to start with any other kind of weapon, make a spawnscript for them that sets their weapon. -"message" - turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. NOTE: this overrides all the weapon spawnflags +"message" - turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the +func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. +NOTE: this overrides all the weapon spawnflags DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -2987,36 +2555,26 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Human_Merc( gentity_t *self ) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Human_Merc(gentity_t *self) { + if (!self->NPC_type) { /*if ( self->message ) { self->NPC_type = "human_merc_key"; } - else */if ( (self->spawnflags & 1) ) - { + else */ + if ((self->spawnflags & 1)) { self->NPC_type = "human_merc_bow"; - } - else if ( (self->spawnflags & 2) ) - { + } else if ((self->spawnflags & 2)) { self->NPC_type = "human_merc_rep"; - } - else if ( (self->spawnflags & 4) ) - { + } else if ((self->spawnflags & 4)) { self->NPC_type = "human_merc_flc"; - } - else if ( (self->spawnflags & 8) ) - { + } else if ((self->spawnflags & 8)) { self->NPC_type = "human_merc_cnc"; - } - else - { + } else { self->NPC_type = "human_merc"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Stormtrooper(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER ALTOFFICER ROCKET DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3033,42 +2591,28 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Stormtrooper( gentity_t *self) -{ - if ( self->spawnflags & 8 ) - {//rocketer +void SP_NPC_Stormtrooper(gentity_t *self) { + if (self->spawnflags & 8) { // rocketer self->NPC_type = "rockettrooper"; - } - else if ( self->spawnflags & 4 ) - {//alt-officer + } else if (self->spawnflags & 4) { // alt-officer self->NPC_type = "stofficeralt"; - } - else if ( self->spawnflags & 2 ) - {//commander + } else if (self->spawnflags & 2) { // commander self->NPC_type = "stcommander"; - } - else if ( self->spawnflags & 1 ) - {//officer + } else if (self->spawnflags & 1) { // officer self->NPC_type = "stofficer"; - } - else - {//regular trooper - if ( Q_irand( 0, 1 ) ) - { + } else { // regular trooper + if (Q_irand(0, 1)) { self->NPC_type = "StormTrooper"; - } - else - { + } else { self->NPC_type = "StormTrooper2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } -void SP_NPC_StormtrooperOfficer( gentity_t *self) -{ +void SP_NPC_StormtrooperOfficer(gentity_t *self) { self->spawnflags |= 1; - SP_NPC_Stormtrooper( self ); + SP_NPC_Stormtrooper(self); } /*QUAKED NPC_Snowtrooper(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY 30 health, blaster @@ -3079,11 +2623,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Snowtrooper( gentity_t *self) -{ +void SP_NPC_Snowtrooper(gentity_t *self) { self->NPC_type = "snowtrooper"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tie_Pilot(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY 30 health, blaster @@ -3094,11 +2637,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tie_Pilot( gentity_t *self) -{ +void SP_NPC_Tie_Pilot(gentity_t *self) { self->NPC_type = "stormpilot"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Ugnaught(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3108,21 +2650,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Ugnaught( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( Q_irand( 0, 1 ) ) - { +void SP_NPC_Ugnaught(gentity_t *self) { + if (!self->NPC_type) { + if (Q_irand(0, 1)) { self->NPC_type = "Ugnaught"; - } - else - { + } else { self->NPC_type = "Ugnaught2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Jawa(1 0 0) (-16 -16 -24) (16 16 40) ARMED x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3134,21 +2671,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Jawa( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Jawa(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "jawa_armed"; - } - else - { + } else { self->NPC_type = "jawa"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Gran(1 0 0) (-16 -16 -24) (16 16 40) SHOOTER BOXER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3162,32 +2694,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Gran( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Gran(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "granshooter"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "granboxer"; - } - else - { - if ( Q_irand( 0, 1 ) ) - { + } else { + if (Q_irand(0, 1)) { self->NPC_type = "gran"; - } - else - { + } else { self->NPC_type = "gran2"; } } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Rodian(1 0 0) (-16 -16 -24) (16 16 40) BLASTER NO_HIDE x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3199,21 +2721,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Rodian( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags&1 ) - { +void SP_NPC_Rodian(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rodian2"; - } - else - { + } else { self->NPC_type = "rodian"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Weequay(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3223,12 +2740,9 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Weequay( gentity_t *self) -{ - if ( !self->NPC_type ) - { - switch ( Q_irand( 0, 3 ) ) - { +void SP_NPC_Weequay(gentity_t *self) { + if (!self->NPC_type) { + switch (Q_irand(0, 3)) { case 0: self->NPC_type = "Weequay"; break; @@ -3244,7 +2758,7 @@ void SP_NPC_Weequay( gentity_t *self) } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Trandoshan(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3254,14 +2768,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Trandoshan( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Trandoshan(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "Trandoshan"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Tusken(1 0 0) (-16 -16 -24) (16 16 40) SNIPER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3271,21 +2783,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Tusken( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( (self->spawnflags&1) ) - { +void SP_NPC_Tusken(gentity_t *self) { + if (!self->NPC_type) { + if ((self->spawnflags & 1)) { self->NPC_type = "tuskensniper"; - } - else - { + } else { self->NPC_type = "tusken"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Noghri(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3295,14 +2802,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Noghri( gentity_t *self) -{ - if ( !self->NPC_type ) - { +void SP_NPC_Noghri(gentity_t *self) { + if (!self->NPC_type) { self->NPC_type = "noghri"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_SwampTrooper(1 0 0) (-16 -16 -24) (16 16 40) REPEATER x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3313,21 +2818,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_SwampTrooper( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_SwampTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "SwampTrooper2"; - } - else - { + } else { self->NPC_type = "SwampTrooper"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Imperial(1 0 0) (-16 -16 -24) (16 16 40) OFFICER COMMANDER x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3337,7 +2837,9 @@ Greyshirt grunt, uses blaster pistol, 20 health. OFFICER - Brownshirt Officer, uses blaster rifle, 40 health COMMANDER - Blackshirt Commander, uses rapid-fire blaster rifle, 80 healt -"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" spawnflag. +"message" - if a COMMANDER, turns on his key surface. This is the name of the key you get when you walk over his body. This must match the "message" field of +the func_security_panel you want this key to open. Set to "goodie" to have him carrying a goodie key that player can use to operate doors with "GOODIE" +spawnflag. DROPTOFLOOR - NPC can be in air, but will spawn on the closest floor surface below it CINEMATIC - Will spawn with no default AI (BS_CINEMATIC) @@ -3345,20 +2847,13 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Imperial( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Imperial(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "ImpOfficer"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "ImpCommander"; - } - else - { + } else { self->NPC_type = "Imperial"; } } @@ -3377,8 +2872,8 @@ void SP_NPC_Imperial( gentity_t *self) } } */ - //rwwFIXMEFIXME: Allow goodie keys - SP_NPC_spawner( self ); + // rwwFIXMEFIXME: Allow goodie keys + SP_NPC_spawner(self); } /*QUAKED NPC_ImpWorker(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3388,25 +2883,18 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_ImpWorker( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( !Q_irand( 0, 2 ) ) - { +void SP_NPC_ImpWorker(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 2)) { self->NPC_type = "ImpWorker"; - } - else if ( Q_irand( 0, 1 ) ) - { + } else if (Q_irand(0, 1)) { self->NPC_type = "ImpWorker2"; - } - else - { + } else { self->NPC_type = "ImpWorker3"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_BespinCop(1 0 0) (-16 -16 -24) (16 16 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3416,21 +2904,16 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_BespinCop( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_BespinCop(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "BespinCop"; - } - else - { + } else { self->NPC_type = "BespinCop2"; } } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Reborn(1 0 0) (-16 -16 -24) (16 16 40) FORCE FENCER ACROBAT BOSS CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3450,34 +2933,23 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Reborn( gentity_t *self) -{ - if ( !self->NPC_type ) - { - if ( self->spawnflags & 1 ) - { +void SP_NPC_Reborn(gentity_t *self) { + if (!self->NPC_type) { + if (self->spawnflags & 1) { self->NPC_type = "rebornforceuser"; - } - else if ( self->spawnflags & 2 ) - { + } else if (self->spawnflags & 2) { self->NPC_type = "rebornfencer"; - } - else if ( self->spawnflags & 4 ) - { + } else if (self->spawnflags & 4) { self->NPC_type = "rebornacrobat"; - } - else if ( self->spawnflags & 8 ) - { + } else if (self->spawnflags & 8) { self->NPC_type = "rebornboss"; - } - else - { + } else { self->NPC_type = "reborn"; } } - WP_SetSaberModel( NULL, CLASS_REBORN ); - SP_NPC_spawner( self ); + WP_SetSaberModel(NULL, CLASS_REBORN); + SP_NPC_spawner(self); } /*QUAKED NPC_ShadowTrooper(1 0 0) (-16 -16 -24) (16 16 40) x x x x CEILING CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3487,27 +2959,22 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_ShadowTrooper( gentity_t *self) -{ - if(!self->NPC_type) - { - if ( !Q_irand( 0, 1 ) ) - { +void SP_NPC_ShadowTrooper(gentity_t *self) { + if (!self->NPC_type) { + if (!Q_irand(0, 1)) { self->NPC_type = "ShadowTrooper"; - } - else - { + } else { self->NPC_type = "ShadowTrooper2"; } } NPC_ShadowTrooper_Precache(); - WP_SetSaberModel( NULL, CLASS_SHADOWTROOPER ); + WP_SetSaberModel(NULL, CLASS_SHADOWTROOPER); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//MONSTERS +// MONSTERS //============================================================================================= /*QUAKED NPC_Monster_Murjj (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3517,11 +2984,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Murjj( gentity_t *self) -{ +void SP_NPC_Monster_Murjj(gentity_t *self) { self->NPC_type = "Murjj"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Swamp (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3531,11 +2997,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Swamp( gentity_t *self) -{ +void SP_NPC_Monster_Swamp(gentity_t *self) { self->NPC_type = "Swamp"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Howler (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3545,11 +3010,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Howler( gentity_t *self) -{ +void SP_NPC_Monster_Howler(gentity_t *self) { self->NPC_type = "howler"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_MineMonster (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3559,11 +3023,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_MineMonster( gentity_t *self) -{ +void SP_NPC_MineMonster(gentity_t *self) { self->NPC_type = "minemonster"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_MineMonster_Precache(); } @@ -3574,11 +3037,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Claw( gentity_t *self) -{ +void SP_NPC_Monster_Claw(gentity_t *self) { self->NPC_type = "Claw"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Glider (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3588,11 +3050,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Glider( gentity_t *self) -{ +void SP_NPC_Monster_Glider(gentity_t *self) { self->NPC_type = "Glider"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Flier2 (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3602,11 +3063,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Flier2( gentity_t *self) -{ +void SP_NPC_Monster_Flier2(gentity_t *self) { self->NPC_type = "Flier2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Lizard (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3616,11 +3076,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Lizard( gentity_t *self) -{ +void SP_NPC_Monster_Lizard(gentity_t *self) { self->NPC_type = "Lizard"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Fish (1 0 0) (-12 -12 -24) (12 12 40) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3630,11 +3089,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Fish( gentity_t *self) -{ +void SP_NPC_Monster_Fish(gentity_t *self) { self->NPC_type = "Fish"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Wampa (1 0 0) (-12 -12 -24) (12 12 40) WANDER SEARCH x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3646,13 +3104,12 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Wampa( gentity_t *self) -{ +void SP_NPC_Monster_Wampa(gentity_t *self) { self->NPC_type = "wampa"; NPC_Wampa_Precache(); - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } /*QUAKED NPC_Monster_Rancor (1 0 0) (-30 -30 -24) (30 30 104) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3662,15 +3119,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Monster_Rancor( gentity_t *self) -{ +void SP_NPC_Monster_Rancor(gentity_t *self) { self->NPC_type = "rancor"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); } //============================================================================================= -//DROIDS +// DROIDS //============================================================================================= /*QUAKED NPC_Droid_Interrogator (1 0 0) (-12 -12 -24) (12 12 0) x x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3680,11 +3136,10 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_Interrogator( gentity_t *self) -{ +void SP_NPC_Droid_Interrogator(gentity_t *self) { self->NPC_type = "interrogator"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Interrogator_Precache(self); } @@ -3698,11 +3153,10 @@ SHY - Spawner is shy Imperial Probe Droid - the multilegged floating droid that Han and Chewie shot on the ice planet Hoth */ -void SP_NPC_Droid_Probe( gentity_t *self) -{ +void SP_NPC_Droid_Probe(gentity_t *self) { self->NPC_type = "probe"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Probe_Precache(); } @@ -3717,11 +3171,10 @@ SHY - Spawner is shy Big walking droid */ -void SP_NPC_Droid_Mark1( gentity_t *self) -{ +void SP_NPC_Droid_Mark1(gentity_t *self) { self->NPC_type = "mark1"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Mark1_Precache(); } @@ -3736,11 +3189,10 @@ SHY - Spawner is shy Small rolling droid with one gun. */ -void SP_NPC_Droid_Mark2( gentity_t *self) -{ +void SP_NPC_Droid_Mark2(gentity_t *self) { self->NPC_type = "mark2"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Mark2_Precache(); } @@ -3752,18 +3204,14 @@ NOTSOLID - Starts not solid STARTINSOLID - Don't try to fix if spawn in solid SHY - Spawner is shy */ -void SP_NPC_Droid_ATST( gentity_t *self) -{ - if ( (self->spawnflags&1) ) - { +void SP_NPC_Droid_ATST(gentity_t *self) { + if ((self->spawnflags & 1)) { self->NPC_type = "atst_vehicle"; - } - else - { + } else { self->NPC_type = "atst"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_ATST_Precache(); } @@ -3777,11 +3225,10 @@ SHY - Spawner is shy Remote Droid - the floating round droid used by Obi Wan to train Luke about the force while on the Millenium Falcon. */ -void SP_NPC_Droid_Remote( gentity_t *self) -{ +void SP_NPC_Droid_Remote(gentity_t *self) { self->NPC_type = "remote"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Remote_Precache(); } @@ -3795,11 +3242,10 @@ SHY - Spawner is shy Seeker Droid - floating round droids that shadow troopers spawn */ -void SP_NPC_Droid_Seeker( gentity_t *self) -{ +void SP_NPC_Droid_Seeker(gentity_t *self) { self->NPC_type = "seeker"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Seeker_Precache(); } @@ -3813,11 +3259,10 @@ SHY - Spawner is shy Sentry Droid - Large, armored floating Imperial droids with 3 forward-facing gun turrets */ -void SP_NPC_Droid_Sentry( gentity_t *self) -{ +void SP_NPC_Droid_Sentry(gentity_t *self) { self->NPC_type = "sentry"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Sentry_Precache(); } @@ -3833,13 +3278,12 @@ Gonk Droid - the droid that looks like a walking ice machine. Was in the Jawa la NOTARGET by default */ -void SP_NPC_Droid_Gonk( gentity_t *self) -{ +void SP_NPC_Droid_Gonk(gentity_t *self) { self->NPC_type = "gonk"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); - //precache the Gonk sounds + // precache the Gonk sounds NPC_Gonk_Precache(); } @@ -3854,15 +3298,13 @@ Mouse Droid - small, box shaped droid, first seen on the Death Star. Chewie yell NOTARGET by default */ -void SP_NPC_Droid_Mouse( gentity_t *self) -{ +void SP_NPC_Droid_Mouse(gentity_t *self) { self->NPC_type = "mouse"; - SP_NPC_spawner( self ); + SP_NPC_spawner(self); - //precache the Mouse sounds + // precache the Mouse sounds NPC_Mouse_Precache(); - } /*QUAKED NPC_Droid_R2D2 (1 0 0) (-12 -12 -24) (12 12 40) IMPERIAL x x x DROPTOFLOOR CINEMATIC NOTSOLID STARTINSOLID SHY @@ -3876,18 +3318,14 @@ R2D2 Droid - you probably know this one already. NOTARGET by default */ -void SP_NPC_Droid_R2D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R2D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r2d2_imp"; - } - else - { + } else { self->NPC_type = "r2d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_R2D2_Precache(); } @@ -3904,18 +3342,14 @@ R5D2 Droid - the droid originally chosen by Uncle Owen until it blew a bad motiv NOTARGET by default */ -void SP_NPC_Droid_R5D2( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_R5D2(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "r5d2_imp"; - } - else - { + } else { self->NPC_type = "r5d2"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_R5D2_Precache(); } @@ -3929,61 +3363,52 @@ SHY - Spawner is shy NOTARGET by default */ -void SP_NPC_Droid_Protocol( gentity_t *self) -{ - if ( self->spawnflags&1 ) - {//imperial skin +void SP_NPC_Droid_Protocol(gentity_t *self) { + if (self->spawnflags & 1) { // imperial skin self->NPC_type = "protocol_imp"; - } - else - { + } else { self->NPC_type = "protocol"; } - SP_NPC_spawner( self ); + SP_NPC_spawner(self); NPC_Protocol_Precache(); } - -//NPC console commands +// NPC console commands /* NPC_Spawn_f */ -gentity_t *NPC_SpawnType( gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle ) -{ - gentity_t *NPCspawner = G_Spawn(); - vec3_t forward, end; - trace_t trace; +gentity_t *NPC_SpawnType(gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle) { + gentity_t *NPCspawner = G_Spawn(); + vec3_t forward, end; + trace_t trace; - if(!NPCspawner) - { - Com_Printf( S_COLOR_RED"NPC_Spawn Error: Out of entities!\n" ); + if (!NPCspawner) { + Com_Printf(S_COLOR_RED "NPC_Spawn Error: Out of entities!\n"); return NULL; } NPCspawner->think = G_FreeEntity; NPCspawner->nextthink = level.time + FRAMETIME; - if ( !npc_type ) - { + if (!npc_type) { return NULL; } - if (!npc_type[0]) - { - Com_Printf( S_COLOR_RED"Error, expected one of:\n"S_COLOR_WHITE" NPC spawn [NPC type (from ext_data/NPCs)]\n NPC spawn vehicle [VEH type (from ext_data/vehicles)]\n" ); + if (!npc_type[0]) { + Com_Printf(S_COLOR_RED "Error, expected one of:\n" S_COLOR_WHITE + " NPC spawn [NPC type (from ext_data/NPCs)]\n NPC spawn vehicle [VEH type (from ext_data/vehicles)]\n"); return NULL; } - if ( !ent || !ent->client ) - {//screw you, go away + if (!ent || !ent->client) { // screw you, go away return NULL; } - //rwwFIXMEFIXME: Care about who is issuing this command/other clients besides 0? - //Spawn it at spot of first player - //FIXME: will gib them! + // rwwFIXMEFIXME: Care about who is issuing this command/other clients besides 0? + // Spawn it at spot of first player + // FIXME: will gib them! AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL); VectorNormalize(forward); VectorMA(ent->r.currentOrigin, 64, forward, end); @@ -3995,15 +3420,14 @@ gentity_t *NPC_SpawnType( gentity_t *ent, char *npc_type, char *targetname, qboo end[2] += 24; G_SetOrigin(NPCspawner, end); VectorCopy(NPCspawner->r.currentOrigin, NPCspawner->s.origin); - //set the yaw so that they face away from player + // set the yaw so that they face away from player NPCspawner->s.angles[1] = ent->client->ps.viewangles[1]; trap->LinkEntity((sharedEntity_t *)NPCspawner); - NPCspawner->NPC_type = G_NewString( npc_type ); + NPCspawner->NPC_type = G_NewString(npc_type); - if ( targetname ) - { + if (targetname) { NPCspawner->NPC_targetname = G_NewString(targetname); } @@ -4011,230 +3435,164 @@ gentity_t *NPC_SpawnType( gentity_t *ent, char *npc_type, char *targetname, qboo NPCspawner->delay = 0; - //NPCspawner->spawnflags |= SFB_NOTSOLID; + // NPCspawner->spawnflags |= SFB_NOTSOLID; - //NPCspawner->playerTeam = TEAM_FREE; - //NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; + // NPCspawner->playerTeam = TEAM_FREE; + // NPCspawner->behaviorSet[BSET_SPAWN] = "common/guard"; - if ( isVehicle ) - { + if (isVehicle) { NPCspawner->classname = "NPC_Vehicle"; } - //call precache funcs for James' builds - if ( !Q_stricmp( "gonk", NPCspawner->NPC_type)) - { + // call precache funcs for James' builds + if (!Q_stricmp("gonk", NPCspawner->NPC_type)) { NPC_Gonk_Precache(); - } - else if ( !Q_stricmp( "mouse", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mouse", NPCspawner->NPC_type)) { NPC_Mouse_Precache(); - } - else if ( !Q_strncmp( "r2d2", NPCspawner->NPC_type, 4)) - { + } else if (!Q_strncmp("r2d2", NPCspawner->NPC_type, 4)) { NPC_R2D2_Precache(); - } - else if ( !Q_stricmp( "atst", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("atst", NPCspawner->NPC_type)) { NPC_ATST_Precache(); - } - else if ( !Q_strncmp( "r5d2", NPCspawner->NPC_type, 4)) - { + } else if (!Q_strncmp("r5d2", NPCspawner->NPC_type, 4)) { NPC_R5D2_Precache(); - } - else if ( !Q_stricmp( "mark1", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mark1", NPCspawner->NPC_type)) { NPC_Mark1_Precache(); - } - else if ( !Q_stricmp( "mark2", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("mark2", NPCspawner->NPC_type)) { NPC_Mark2_Precache(); - } - else if ( !Q_stricmp( "interrogator", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("interrogator", NPCspawner->NPC_type)) { NPC_Interrogator_Precache(NULL); - } - else if ( !Q_stricmp( "probe", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("probe", NPCspawner->NPC_type)) { NPC_Probe_Precache(); - } - else if ( !Q_stricmp( "seeker", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("seeker", NPCspawner->NPC_type)) { NPC_Seeker_Precache(); - } - else if ( !Q_stricmp( "remote", NPCspawner->NPC_type)) - { + } else if (!Q_stricmp("remote", NPCspawner->NPC_type)) { NPC_Remote_Precache(); - } - else if ( !Q_strncmp( "shadowtrooper", NPCspawner->NPC_type, 13 ) ) - { + } else if (!Q_strncmp("shadowtrooper", NPCspawner->NPC_type, 13)) { NPC_ShadowTrooper_Precache(); - } - else if ( !Q_stricmp( "minemonster", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("minemonster", NPCspawner->NPC_type)) { NPC_MineMonster_Precache(); - } - else if ( !Q_stricmp( "howler", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("howler", NPCspawner->NPC_type)) { NPC_Howler_Precache(); - } - else if ( !Q_stricmp( "sentry", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("sentry", NPCspawner->NPC_type)) { NPC_Sentry_Precache(); - } - else if ( !Q_stricmp( "protocol", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("protocol", NPCspawner->NPC_type)) { NPC_Protocol_Precache(); - } - else if ( !Q_stricmp( "galak_mech", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("galak_mech", NPCspawner->NPC_type)) { NPC_GalakMech_Precache(); - } - else if ( !Q_stricmp( "wampa", NPCspawner->NPC_type )) - { + } else if (!Q_stricmp("wampa", NPCspawner->NPC_type)) { NPC_Wampa_Precache(); } - return (NPC_Spawn_Do( NPCspawner )); + return (NPC_Spawn_Do(NPCspawner)); } -void NPC_Spawn_f( gentity_t *ent ) -{ - char npc_type[1024]; - char targetname[1024]; - qboolean isVehicle = qfalse; +void NPC_Spawn_f(gentity_t *ent) { + char npc_type[1024]; + char targetname[1024]; + qboolean isVehicle = qfalse; trap->Argv(2, npc_type, 1024); - if ( Q_stricmp( "vehicle", npc_type ) == 0 ) - { + if (Q_stricmp("vehicle", npc_type) == 0) { isVehicle = qtrue; trap->Argv(3, npc_type, 1024); trap->Argv(4, targetname, 1024); - } - else - { + } else { trap->Argv(3, targetname, 1024); } - NPC_SpawnType( ent, npc_type, targetname, isVehicle ); + NPC_SpawnType(ent, npc_type, targetname, isVehicle); } /* NPC_Kill_f */ extern stringID_table_t TeamTable[]; -void NPC_Kill_f( void ) -{ - int n; - gentity_t *player; - char name[1024]; - npcteam_t killTeam = NPCTEAM_FREE; - qboolean killNonSF = qfalse; +void NPC_Kill_f(void) { + int n; + gentity_t *player; + char name[1024]; + npcteam_t killTeam = NPCTEAM_FREE; + qboolean killNonSF = qfalse; trap->Argv(2, name, 1024); - if ( !name[0] ) - { - Com_Printf( S_COLOR_RED"Error, Expected:\n"); - Com_Printf( S_COLOR_RED"NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n" ); - Com_Printf( S_COLOR_RED"or\n" ); - Com_Printf( S_COLOR_RED"NPC kill 'all' - kills all NPCs\n" ); - Com_Printf( S_COLOR_RED"or\n" ); - Com_Printf( S_COLOR_RED"NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n" ); + if (!name[0]) { + Com_Printf(S_COLOR_RED "Error, Expected:\n"); + Com_Printf(S_COLOR_RED "NPC kill '[NPC targetname]' - kills NPCs with certain targetname\n"); + Com_Printf(S_COLOR_RED "or\n"); + Com_Printf(S_COLOR_RED "NPC kill 'all' - kills all NPCs\n"); + Com_Printf(S_COLOR_RED "or\n"); + Com_Printf(S_COLOR_RED "NPC team '[teamname]' - kills all NPCs of a certain team ('nonally' is all but your allies)\n"); return; } - if ( Q_stricmp( "team", name ) == 0 ) - { + if (Q_stricmp("team", name) == 0) { trap->Argv(3, name, 1024); - if ( !name[0] ) - { - Com_Printf( S_COLOR_RED"NPC_Kill Error: 'npc kill team' requires a team name!\n" ); - Com_Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - Com_Printf( S_COLOR_RED"%s\n", TeamNames[n] ); + if (!name[0]) { + Com_Printf(S_COLOR_RED "NPC_Kill Error: 'npc kill team' requires a team name!\n"); + Com_Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + Com_Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - Com_Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + Com_Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } - if ( Q_stricmp( "nonally", name ) == 0 ) - { + if (Q_stricmp("nonally", name) == 0) { killNonSF = qtrue; - } - else - { - killTeam = GetIDForString( TeamTable, name ); - - if ( killTeam == NPCTEAM_FREE ) - { - Com_Printf( S_COLOR_RED"NPC_Kill Error: team '%s' not recognized\n", name ); - Com_Printf( S_COLOR_RED"Valid team names are:\n"); - for ( n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++ ) - { - Com_Printf( S_COLOR_RED"%s\n", TeamNames[n] ); + } else { + killTeam = GetIDForString(TeamTable, name); + + if (killTeam == NPCTEAM_FREE) { + Com_Printf(S_COLOR_RED "NPC_Kill Error: team '%s' not recognized\n", name); + Com_Printf(S_COLOR_RED "Valid team names are:\n"); + for (n = (TEAM_FREE + 1); n < TEAM_NUM_TEAMS; n++) { + Com_Printf(S_COLOR_RED "%s\n", TeamNames[n]); } - Com_Printf( S_COLOR_RED"nonally - kills all but your teammates\n" ); + Com_Printf(S_COLOR_RED "nonally - kills all but your teammates\n"); return; } } } - for ( n = 1; n < ENTITYNUM_MAX_NORMAL; n++) - { + for (n = 1; n < ENTITYNUM_MAX_NORMAL; n++) { player = &g_entities[n]; if (!player->inuse) { continue; } - if ( killNonSF ) - { - if ( player ) - { - if ( player->client ) - { - if ( player->client->playerTeam != NPCTEAM_PLAYER ) - { - Com_Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + if (killNonSF) { + if (player) { + if (player->client) { + if (player->client->playerTeam != NPCTEAM_PLAYER) { + Com_Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; - if (player->die && player->client) - { + if (player->die && player->client) { player->die(player, player, player, player->client->pers.maxHealth, MOD_UNKNOWN); } } - } - else if ( player->NPC_type && player->classname && player->classname[0] && Q_stricmp( "NPC_starfleet", player->classname ) != 0 ) - {//A spawner, remove it - Com_Printf( S_COLOR_GREEN"Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname ); - G_FreeEntity( player ); - //FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? + } else if (player->NPC_type && player->classname && player->classname[0] && + Q_stricmp("NPC_starfleet", player->classname) != 0) { // A spawner, remove it + Com_Printf(S_COLOR_GREEN "Removing NPC spawner %s with NPC named %s\n", player->NPC_type, player->NPC_targetname); + G_FreeEntity(player); + // FIXME: G_UseTargets2(player, player, player->NPC_target & player->target);? } } - } - else if ( player && player->NPC && player->client ) - { - if ( killTeam != NPCTEAM_FREE ) - { - if ( player->client->playerTeam == killTeam ) - { - Com_Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if (player && player->NPC && player->client) { + if (killTeam != NPCTEAM_FREE) { + if (player->client->playerTeam == killTeam) { + Com_Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; - if (player->die) - { + if (player->die) { player->die(player, player, player, player->client->pers.maxHealth, MOD_UNKNOWN); } } - } - else if( (player->targetname && Q_stricmp( name, player->targetname ) == 0) - || Q_stricmp( name, "all" ) == 0 ) - { - Com_Printf( S_COLOR_GREEN"Killing NPC %s named %s\n", player->NPC_type, player->targetname ); + } else if ((player->targetname && Q_stricmp(name, player->targetname) == 0) || Q_stricmp(name, "all") == 0) { + Com_Printf(S_COLOR_GREEN "Killing NPC %s named %s\n", player->NPC_type, player->targetname); player->health = 0; player->client->ps.stats[STAT_HEALTH] = 0; - if (player->die) - { + if (player->die) { player->die(player, player, player, 100, MOD_UNKNOWN); } } @@ -4246,78 +3604,57 @@ void NPC_Kill_f( void ) G_FreeEntity( player ); } */ - //rwwFIXMEFIXME: should really do something here. + // rwwFIXMEFIXME: should really do something here. } } -void NPC_PrintScore( gentity_t *ent ) -{ - Com_Printf( "%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE] ); -} +void NPC_PrintScore(gentity_t *ent) { Com_Printf("%s: %d\n", ent->targetname, ent->client->ps.persistant[PERS_SCORE]); } /* Svcmd_NPC_f parse and dispatch bot commands */ -qboolean showBBoxes = qfalse; -void Cmd_NPC_f( gentity_t *ent ) -{ - char cmd[1024]; - - trap->Argv( 1, cmd, 1024 ); - - if ( !cmd[0] ) - { - Com_Printf( "Valid NPC commands are:\n" ); - Com_Printf( " spawn [NPC type (from NPCs.cfg)]\n" ); - Com_Printf( " kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n" ); - Com_Printf( " showbounds (draws exact bounding boxes of NPCs)\n" ); - Com_Printf( " score [NPC targetname] (prints number of kills per NPC)\n" ); - } - else if ( Q_stricmp( cmd, "spawn" ) == 0 ) - { - NPC_Spawn_f( ent ); - } - else if ( Q_stricmp( cmd, "kill" ) == 0 ) - { +qboolean showBBoxes = qfalse; +void Cmd_NPC_f(gentity_t *ent) { + char cmd[1024]; + + trap->Argv(1, cmd, 1024); + + if (!cmd[0]) { + Com_Printf("Valid NPC commands are:\n"); + Com_Printf(" spawn [NPC type (from NPCs.cfg)]\n"); + Com_Printf(" kill [NPC targetname] or [all(kills all NPCs)] or 'team [teamname]'\n"); + Com_Printf(" showbounds (draws exact bounding boxes of NPCs)\n"); + Com_Printf(" score [NPC targetname] (prints number of kills per NPC)\n"); + } else if (Q_stricmp(cmd, "spawn") == 0) { + NPC_Spawn_f(ent); + } else if (Q_stricmp(cmd, "kill") == 0) { NPC_Kill_f(); - } - else if ( Q_stricmp( cmd, "showbounds" ) == 0 ) - {//Toggle on and off + } else if (Q_stricmp(cmd, "showbounds") == 0) { // Toggle on and off showBBoxes = showBBoxes ? qfalse : qtrue; - } - else if ( Q_stricmp ( cmd, "score" ) == 0 ) - { - char cmd2[1024]; + } else if (Q_stricmp(cmd, "score") == 0) { + char cmd2[1024]; gentity_t *thisent = NULL; - trap->Argv( 2, cmd2, sizeof( cmd2 ) ); + trap->Argv(2, cmd2, sizeof(cmd2)); - if ( !cmd2[0] ) - {//Show the score for all NPCs + if (!cmd2[0]) { // Show the score for all NPCs int i; - Com_Printf( "SCORE LIST:\n" ); - for ( i = 0; i < ENTITYNUM_WORLD; i++ ) - { + Com_Printf("SCORE LIST:\n"); + for (i = 0; i < ENTITYNUM_WORLD; i++) { thisent = &g_entities[i]; - if ( !thisent || !thisent->client ) - { + if (!thisent || !thisent->client) { continue; } - NPC_PrintScore( thisent ); - } - } - else - { - if ( (thisent = G_Find( NULL, FOFS(targetname), cmd2 )) != NULL && thisent->client ) - { - NPC_PrintScore( thisent ); + NPC_PrintScore(thisent); } - else - { - Com_Printf( "ERROR: NPC score - no such NPC %s\n", cmd2 ); + } else { + if ((thisent = G_Find(NULL, FOFS(targetname), cmd2)) != NULL && thisent->client) { + NPC_PrintScore(thisent); + } else { + Com_Printf("ERROR: NPC score - no such NPC %s\n", cmd2); } } } diff --git a/codemp/game/NPC_stats.c b/codemp/game/NPC_stats.c index 4920ad8a68..d90b852957 100644 --- a/codemp/game/NPC_stats.c +++ b/codemp/game/NPC_stats.c @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//NPC_stats.cpp +// NPC_stats.cpp #include "b_local.h" #include "b_public.h" #include "anims.h" @@ -28,215 +28,148 @@ along with this program; if not, see . extern qboolean NPCsPrecached; -extern qboolean WP_SaberParseParms( const char *SaberName, saberInfo_t *saber ); -extern void WP_RemoveSaber( saberInfo_t *sabers, int saberNum ); +extern qboolean WP_SaberParseParms(const char *SaberName, saberInfo_t *saber); +extern void WP_RemoveSaber(saberInfo_t *sabers, int saberNum); -stringID_table_t TeamTable[] = -{ - ENUM2STRING(NPCTEAM_FREE), // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc +stringID_table_t TeamTable[] = { + ENUM2STRING(NPCTEAM_FREE), // caution, some code checks a team_t via "if (!team_t_varname)" so I guess this should stay as entry 0, great or what? -slc ENUM2STRING(NPCTEAM_PLAYER), ENUM2STRING(NPCTEAM_ENEMY), - ENUM2STRING(NPCTEAM_NEUTRAL), // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator - {"", -1} -}; + ENUM2STRING(NPCTEAM_NEUTRAL), // most droids are team_neutral, there are some exceptions like Probe,Seeker,Interrogator + {"", -1}}; // this list was made using the model directories, this MUST be in the same order as the CLASS_ enum in teams.h -stringID_table_t ClassTable[] = -{ - ENUM2STRING(CLASS_NONE), // hopefully this will never be used by an npc), just covering all bases - ENUM2STRING(CLASS_ATST), // technically droid... - ENUM2STRING(CLASS_BARTENDER), - ENUM2STRING(CLASS_BESPIN_COP), - ENUM2STRING(CLASS_CLAW), - ENUM2STRING(CLASS_COMMANDO), - ENUM2STRING(CLASS_DESANN), - ENUM2STRING(CLASS_FISH), - ENUM2STRING(CLASS_FLIER2), - ENUM2STRING(CLASS_GALAK), - ENUM2STRING(CLASS_GLIDER), - ENUM2STRING(CLASS_GONK), // droid - ENUM2STRING(CLASS_GRAN), - ENUM2STRING(CLASS_HOWLER), -// ENUM2STRING(CLASS_RANCOR), - ENUM2STRING(CLASS_IMPERIAL), - ENUM2STRING(CLASS_IMPWORKER), - ENUM2STRING(CLASS_INTERROGATOR), // droid - ENUM2STRING(CLASS_JAN), - ENUM2STRING(CLASS_JEDI), - ENUM2STRING(CLASS_KYLE), - ENUM2STRING(CLASS_LANDO), - ENUM2STRING(CLASS_LIZARD), - ENUM2STRING(CLASS_LUKE), - ENUM2STRING(CLASS_MARK1), // droid - ENUM2STRING(CLASS_MARK2), // droid - ENUM2STRING(CLASS_GALAKMECH), // droid - ENUM2STRING(CLASS_MINEMONSTER), - ENUM2STRING(CLASS_MONMOTHA), - ENUM2STRING(CLASS_MORGANKATARN), - ENUM2STRING(CLASS_MOUSE), // droid - ENUM2STRING(CLASS_MURJJ), - ENUM2STRING(CLASS_PRISONER), - ENUM2STRING(CLASS_PROBE), // droid - ENUM2STRING(CLASS_PROTOCOL), // droid - ENUM2STRING(CLASS_R2D2), // droid - ENUM2STRING(CLASS_R5D2), // droid - ENUM2STRING(CLASS_REBEL), - ENUM2STRING(CLASS_REBORN), - ENUM2STRING(CLASS_REELO), - ENUM2STRING(CLASS_REMOTE), - ENUM2STRING(CLASS_RODIAN), - ENUM2STRING(CLASS_SEEKER), // droid - ENUM2STRING(CLASS_SENTRY), - ENUM2STRING(CLASS_SHADOWTROOPER), - ENUM2STRING(CLASS_STORMTROOPER), - ENUM2STRING(CLASS_SWAMP), - ENUM2STRING(CLASS_SWAMPTROOPER), - ENUM2STRING(CLASS_TAVION), - ENUM2STRING(CLASS_TRANDOSHAN), - ENUM2STRING(CLASS_UGNAUGHT), - ENUM2STRING(CLASS_JAWA), - ENUM2STRING(CLASS_WEEQUAY), - ENUM2STRING(CLASS_BOBAFETT), - //ENUM2STRING(CLASS_ROCKETTROOPER), - //ENUM2STRING(CLASS_PLAYER), - ENUM2STRING(CLASS_VEHICLE), - ENUM2STRING(CLASS_RANCOR), - ENUM2STRING(CLASS_WAMPA), - {"", -1} -}; - -stringID_table_t BSTable[] = -{ - ENUM2STRING(BS_DEFAULT),//# default behavior for that NPC - ENUM2STRING(BS_ADVANCE_FIGHT),//# Advance to captureGoal and shoot enemies if you can - ENUM2STRING(BS_SLEEP),//# Play awake script when startled by sound - ENUM2STRING(BS_FOLLOW_LEADER),//# Follow your leader and shoot any enemies you come across - ENUM2STRING(BS_JUMP),//# Face navgoal and jump to it. - ENUM2STRING(BS_SEARCH),//# Using current waypoint as a base), search the immediate branches of waypoints for enemies - ENUM2STRING(BS_WANDER),//# Wander down random waypoint paths - ENUM2STRING(BS_NOCLIP),//# Moves through walls), etc. - ENUM2STRING(BS_REMOVE),//# Waits for player to leave PVS then removes itself - ENUM2STRING(BS_CINEMATIC),//# Does nothing but face it's angles and move to a goal if it has one - //the rest are internal only - {"", -1}, +stringID_table_t ClassTable[] = {ENUM2STRING(CLASS_NONE), // hopefully this will never be used by an npc), just covering all bases + ENUM2STRING(CLASS_ATST), // technically droid... + ENUM2STRING(CLASS_BARTENDER), + ENUM2STRING(CLASS_BESPIN_COP), + ENUM2STRING(CLASS_CLAW), + ENUM2STRING(CLASS_COMMANDO), + ENUM2STRING(CLASS_DESANN), + ENUM2STRING(CLASS_FISH), + ENUM2STRING(CLASS_FLIER2), + ENUM2STRING(CLASS_GALAK), + ENUM2STRING(CLASS_GLIDER), + ENUM2STRING(CLASS_GONK), // droid + ENUM2STRING(CLASS_GRAN), + ENUM2STRING(CLASS_HOWLER), + // ENUM2STRING(CLASS_RANCOR), + ENUM2STRING(CLASS_IMPERIAL), + ENUM2STRING(CLASS_IMPWORKER), + ENUM2STRING(CLASS_INTERROGATOR), // droid + ENUM2STRING(CLASS_JAN), + ENUM2STRING(CLASS_JEDI), + ENUM2STRING(CLASS_KYLE), + ENUM2STRING(CLASS_LANDO), + ENUM2STRING(CLASS_LIZARD), + ENUM2STRING(CLASS_LUKE), + ENUM2STRING(CLASS_MARK1), // droid + ENUM2STRING(CLASS_MARK2), // droid + ENUM2STRING(CLASS_GALAKMECH), // droid + ENUM2STRING(CLASS_MINEMONSTER), + ENUM2STRING(CLASS_MONMOTHA), + ENUM2STRING(CLASS_MORGANKATARN), + ENUM2STRING(CLASS_MOUSE), // droid + ENUM2STRING(CLASS_MURJJ), + ENUM2STRING(CLASS_PRISONER), + ENUM2STRING(CLASS_PROBE), // droid + ENUM2STRING(CLASS_PROTOCOL), // droid + ENUM2STRING(CLASS_R2D2), // droid + ENUM2STRING(CLASS_R5D2), // droid + ENUM2STRING(CLASS_REBEL), + ENUM2STRING(CLASS_REBORN), + ENUM2STRING(CLASS_REELO), + ENUM2STRING(CLASS_REMOTE), + ENUM2STRING(CLASS_RODIAN), + ENUM2STRING(CLASS_SEEKER), // droid + ENUM2STRING(CLASS_SENTRY), + ENUM2STRING(CLASS_SHADOWTROOPER), + ENUM2STRING(CLASS_STORMTROOPER), + ENUM2STRING(CLASS_SWAMP), + ENUM2STRING(CLASS_SWAMPTROOPER), + ENUM2STRING(CLASS_TAVION), + ENUM2STRING(CLASS_TRANDOSHAN), + ENUM2STRING(CLASS_UGNAUGHT), + ENUM2STRING(CLASS_JAWA), + ENUM2STRING(CLASS_WEEQUAY), + ENUM2STRING(CLASS_BOBAFETT), + // ENUM2STRING(CLASS_ROCKETTROOPER), + // ENUM2STRING(CLASS_PLAYER), + ENUM2STRING(CLASS_VEHICLE), + ENUM2STRING(CLASS_RANCOR), + ENUM2STRING(CLASS_WAMPA), + {"", -1}}; + +stringID_table_t BSTable[] = { + ENUM2STRING(BS_DEFAULT), //# default behavior for that NPC + ENUM2STRING(BS_ADVANCE_FIGHT), //# Advance to captureGoal and shoot enemies if you can + ENUM2STRING(BS_SLEEP), //# Play awake script when startled by sound + ENUM2STRING(BS_FOLLOW_LEADER), //# Follow your leader and shoot any enemies you come across + ENUM2STRING(BS_JUMP), //# Face navgoal and jump to it. + ENUM2STRING(BS_SEARCH), //# Using current waypoint as a base), search the immediate branches of waypoints for enemies + ENUM2STRING(BS_WANDER), //# Wander down random waypoint paths + ENUM2STRING(BS_NOCLIP), //# Moves through walls), etc. + ENUM2STRING(BS_REMOVE), //# Waits for player to leave PVS then removes itself + ENUM2STRING(BS_CINEMATIC), //# Does nothing but face it's angles and move to a goal if it has one + // the rest are internal only + {"", -1}, }; -#define stringIDExpand(str, strEnum) {str, strEnum}, ENUM2STRING(strEnum) - -stringID_table_t BSETTable[] = -{ - ENUM2STRING(BSET_SPAWN),//# script to use when first spawned - ENUM2STRING(BSET_USE),//# script to use when used - ENUM2STRING(BSET_AWAKE),//# script to use when awoken/startled - ENUM2STRING(BSET_ANGER),//# script to use when aquire an enemy - ENUM2STRING(BSET_ATTACK),//# script to run when you attack - ENUM2STRING(BSET_VICTORY),//# script to run when you kill someone - ENUM2STRING(BSET_LOSTENEMY),//# script to run when you can't find your enemy - ENUM2STRING(BSET_PAIN),//# script to use when take pain - ENUM2STRING(BSET_FLEE),//# script to use when take pain below 50% of health - ENUM2STRING(BSET_DEATH),//# script to use when killed - ENUM2STRING(BSET_DELAYED),//# script to run when self->delayScriptTime is reached - ENUM2STRING(BSET_BLOCKED),//# script to run when blocked by a friendly NPC or player - ENUM2STRING(BSET_BUMPED),//# script to run when bumped into a friendly NPC or player (can set bumpRadius) - ENUM2STRING(BSET_STUCK),//# script to run when blocked by a wall - ENUM2STRING(BSET_FFIRE),//# script to run when player shoots their own teammates - ENUM2STRING(BSET_FFDEATH),//# script to run when player kills a teammate +#define stringIDExpand(str, strEnum) {str, strEnum}, ENUM2STRING(strEnum) + +stringID_table_t BSETTable[] = { + ENUM2STRING(BSET_SPAWN), //# script to use when first spawned + ENUM2STRING(BSET_USE), //# script to use when used + ENUM2STRING(BSET_AWAKE), //# script to use when awoken/startled + ENUM2STRING(BSET_ANGER), //# script to use when aquire an enemy + ENUM2STRING(BSET_ATTACK), //# script to run when you attack + ENUM2STRING(BSET_VICTORY), //# script to run when you kill someone + ENUM2STRING(BSET_LOSTENEMY), //# script to run when you can't find your enemy + ENUM2STRING(BSET_PAIN), //# script to use when take pain + ENUM2STRING(BSET_FLEE), //# script to use when take pain below 50% of health + ENUM2STRING(BSET_DEATH), //# script to use when killed + ENUM2STRING(BSET_DELAYED), //# script to run when self->delayScriptTime is reached + ENUM2STRING(BSET_BLOCKED), //# script to run when blocked by a friendly NPC or player + ENUM2STRING(BSET_BUMPED), //# script to run when bumped into a friendly NPC or player (can set bumpRadius) + ENUM2STRING(BSET_STUCK), //# script to run when blocked by a wall + ENUM2STRING(BSET_FFIRE), //# script to run when player shoots their own teammates + ENUM2STRING(BSET_FFDEATH), //# script to run when player kills a teammate stringIDExpand("", BSET_INVALID), - {"", -1}, + {"", -1}, }; extern stringID_table_t WPTable[]; extern stringID_table_t FPTable[]; -char *TeamNames[TEAM_NUM_TEAMS] = -{ - "", - "player", - "enemy", - "neutral" -}; +char *TeamNames[TEAM_NUM_TEAMS] = {"", "player", "enemy", "neutral"}; // this list was made using the model directories, this MUST be in the same order as the CLASS_ enum in teams.h -char *ClassNames[CLASS_NUM_CLASSES] = -{ - "", // class none - "atst", - "bartender", - "bespin_cop", - "claw", - "commando", - "desann", - "fish", - "flier2", - "galak", - "glider", - "gonk", - "gran", - "howler", - "imperial", - "impworker", - "interrogator", - "jan", - "jedi", - "kyle", - "lando", - "lizard", - "luke", - "mark1", - "mark2", - "galak_mech", - "minemonster", - "monmotha", - "morgankatarn", - "mouse", - "murjj", - "prisoner", - "probe", - "protocol", - "r2d2", - "r5d2", - "rebel", - "reborn", - "reelo", - "remote", - "rodian", - "seeker", - "sentry", - "shadowtrooper", - "stormtrooper", - "swamp", - "swamptrooper", - "tavion", - "trandoshan", - "ugnaught", - "weequay", - "bobafett", - "vehicle", - "rancor", - "wampa", +char *ClassNames[CLASS_NUM_CLASSES] = { + "", // class none + "atst", "bartender", "bespin_cop", "claw", "commando", "desann", "fish", "flier2", "galak", "glider", "gonk", + "gran", "howler", "imperial", "impworker", "interrogator", "jan", "jedi", "kyle", "lando", "lizard", "luke", + "mark1", "mark2", "galak_mech", "minemonster", "monmotha", "morgankatarn", "mouse", "murjj", "prisoner", "probe", "protocol", + "r2d2", "r5d2", "rebel", "reborn", "reelo", "remote", "rodian", "seeker", "sentry", "shadowtrooper", "stormtrooper", + "swamp", "swamptrooper", "tavion", "trandoshan", "ugnaught", "weequay", "bobafett", "vehicle", "rancor", "wampa", }; - /* NPC_ReactionTime */ -//FIXME use grandom in here -int NPC_ReactionTime ( void ) -{ - return 200 * ( 6 - NPCS.NPCInfo->stats.reactions ); -} +// FIXME use grandom in here +int NPC_ReactionTime(void) { return 200 * (6 - NPCS.NPCInfo->stats.reactions); } // // parse support routines // -extern qboolean BG_ParseLiteral( const char **data, const char *string ); +extern qboolean BG_ParseLiteral(const char **data, const char *string); // // NPC parameters file : scripts/NPCs.cfg // #define MAX_NPC_DATA_SIZE 0x40000 -char NPCParms[MAX_NPC_DATA_SIZE]; +char NPCParms[MAX_NPC_DATA_SIZE]; /* team_t TranslateTeamName( const char *name ) @@ -275,53 +208,43 @@ static rank_t TranslateRankName( const char *name ) Should be used to determine pip bolt-ons */ -static rank_t TranslateRankName( const char *name ) -{ - if ( !Q_stricmp( name, "civilian" ) ) - { +static rank_t TranslateRankName(const char *name) { + if (!Q_stricmp(name, "civilian")) { return RANK_CIVILIAN; } - if ( !Q_stricmp( name, "crewman" ) ) - { + if (!Q_stricmp(name, "crewman")) { return RANK_CREWMAN; } - if ( !Q_stricmp( name, "ensign" ) ) - { + if (!Q_stricmp(name, "ensign")) { return RANK_ENSIGN; } - if ( !Q_stricmp( name, "ltjg" ) ) - { + if (!Q_stricmp(name, "ltjg")) { return RANK_LT_JG; } - if ( !Q_stricmp( name, "lt" ) ) - { + if (!Q_stricmp(name, "lt")) { return RANK_LT; } - if ( !Q_stricmp( name, "ltcomm" ) ) - { + if (!Q_stricmp(name, "ltcomm")) { return RANK_LT_COMM; } - if ( !Q_stricmp( name, "commander" ) ) - { + if (!Q_stricmp(name, "commander")) { return RANK_COMMANDER; } - if ( !Q_stricmp( name, "captain" ) ) - { + if (!Q_stricmp(name, "captain")) { return RANK_CAPTAIN; } return RANK_CIVILIAN; - } -extern saber_colors_t TranslateSaberColor( const char *name ); +extern saber_colors_t TranslateSaberColor(const char *name); /* static int MethodNameToNumber( const char *name ) { if ( !Q_stricmp( name, "EXPONENTIAL" ) ) { @@ -357,7 +280,7 @@ static int ItemNameToNumber( const char *name, int itemType ) { } */ -//rwwFIXMEFIXME: movetypes +// rwwFIXMEFIXME: movetypes /* static int MoveTypeNameToEnum( const char *name ) { @@ -385,23 +308,20 @@ static int MoveTypeNameToEnum( const char *name ) //#define CONVENIENT_ANIMATION_FILE_DEBUG_THING #ifdef CONVENIENT_ANIMATION_FILE_DEBUG_THING -void SpewDebugStuffToFile(animation_t *anims) -{ +void SpewDebugStuffToFile(animation_t *anims) { char BGPAFtext[40000]; fileHandle_t f; int i = 0; trap->FS_Open("file_of_debug_stuff_SP.txt", &f, FS_WRITE); - if (!f) - { + if (!f) { return; } BGPAFtext[0] = 0; - while (i < MAX_ANIMATIONS) - { + while (i < MAX_ANIMATIONS) { strcat(BGPAFtext, va("%i %i\n", i, anims[i].frameLerp)); i++; } @@ -411,24 +331,21 @@ void SpewDebugStuffToFile(animation_t *anims) } #endif -qboolean G_ParseAnimFileSet( const char *filename, const char *animCFG, int *animFileIndex ) -{ +qboolean G_ParseAnimFileSet(const char *filename, const char *animCFG, int *animFileIndex) { *animFileIndex = BG_ParseAnimationFile(filename, NULL, qfalse); - //if it's humanoid we should have it cached and return it, if it is not it will be loaded (unless it's also cached already) + // if it's humanoid we should have it cached and return it, if it is not it will be loaded (unless it's also cached already) - if (*animFileIndex == -1) - { + if (*animFileIndex == -1) { return qfalse; } - //I guess this isn't really even needed game-side. - //BG_ParseAnimationSndFile(filename, *animFileIndex); + // I guess this isn't really even needed game-side. + // BG_ParseAnimationSndFile(filename, *animFileIndex); return qtrue; } -void NPC_PrecacheAnimationCFG( const char *NPC_type ) -{ -#if 0 //rwwFIXMEFIXME: Actually precache stuff here. +void NPC_PrecacheAnimationCFG(const char *NPC_type) { +#if 0 // rwwFIXMEFIXME: Actually precache stuff here. char filename[MAX_QPATH]; const char *token; const char *value; @@ -537,21 +454,18 @@ void NPC_PrecacheAnimationCFG( const char *NPC_type ) #endif } -extern int NPC_WeaponsForTeam( team_t team, int spawnflags, const char *NPC_type ); -void NPC_PrecacheWeapons( team_t playerTeam, int spawnflags, char *NPCtype ) -{ - int weapons = NPC_WeaponsForTeam( playerTeam, spawnflags, NPCtype ); +extern int NPC_WeaponsForTeam(team_t team, int spawnflags, const char *NPC_type); +void NPC_PrecacheWeapons(team_t playerTeam, int spawnflags, char *NPCtype) { + int weapons = NPC_WeaponsForTeam(playerTeam, spawnflags, NPCtype); int curWeap; - for ( curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) - { - if (weapons & (1 << curWeap)) - { + for (curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++) { + if (weapons & (1 << curWeap)) { RegisterItem(BG_FindItemForWeapon((weapon_t)curWeap)); } } -#if 0 //rwwFIXMEFIXME: actually precache weapons here +#if 0 // rwwFIXMEFIXME: actually precache weapons here int weapons = NPC_WeaponsForTeam( playerTeam, spawnflags, NPCtype ); gitem_t *item; for ( int curWeap = WP_SABER; curWeap < WP_NUM_WEAPONS; curWeap++ ) @@ -586,247 +500,208 @@ void NPC_Precache ( char *NPCName ) Precaches NPC skins, tgas and md3s. */ -void NPC_Precache ( gentity_t *spawner ) -{ - npcteam_t playerTeam = NPCTEAM_FREE; - const char *token; - const char *value; - const char *p; - char *patch; - char sound[MAX_QPATH]; - qboolean md3Model = qfalse; - char playerModel[MAX_QPATH]; - char customSkin[MAX_QPATH]; - char sessionName[MAX_QPATH+15]; - - if ( !Q_stricmp( "random", spawner->NPC_type ) ) - {//sorry, can't precache a random just yet +void NPC_Precache(gentity_t *spawner) { + npcteam_t playerTeam = NPCTEAM_FREE; + const char *token; + const char *value; + const char *p; + char *patch; + char sound[MAX_QPATH]; + qboolean md3Model = qfalse; + char playerModel[MAX_QPATH]; + char customSkin[MAX_QPATH]; + char sessionName[MAX_QPATH + 15]; + + if (!Q_stricmp("random", spawner->NPC_type)) { // sorry, can't precache a random just yet return; } - strcpy(customSkin,"default"); + strcpy(customSkin, "default"); p = NPCParms; - Com_sprintf( sessionName, sizeof(sessionName), "NPC_Precache(%s)", spawner->NPC_type ); + Com_sprintf(sessionName, sizeof(sessionName), "NPC_Precache(%s)", spawner->NPC_type); COM_BeginParseSession(sessionName); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) return; - if ( !Q_stricmp( token, spawner->NPC_type ) ) - { + if (!Q_stricmp(token, spawner->NPC_type)) { break; } - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } - if ( !p ) - { + if (!p) { return; } - if ( BG_ParseLiteral( &p, "{" ) ) - { + if (BG_ParseLiteral(&p, "{")) { return; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", spawner->NPC_type); return; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { - //Q_strncpyz( ri.headModelName, value, sizeof(ri.headModelName), qtrue); + if (!Q_stricmp("none", value)) { + } else { + // Q_strncpyz( ri.headModelName, value, sizeof(ri.headModelName), qtrue); } md3Model = qtrue; continue; } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - } - else - { - //Q_strncpyz( ri.torsoModelName, value, sizeof(ri.torsoModelName), qtrue); + if (!Q_stricmp("none", value)) { + } else { + // Q_strncpyz( ri.torsoModelName, value, sizeof(ri.torsoModelName), qtrue); } md3Model = qtrue; continue; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - //Q_strncpyz( ri.legsModelName, value, sizeof(ri.legsModelName), qtrue); + // Q_strncpyz( ri.legsModelName, value, sizeof(ri.legsModelName), qtrue); md3Model = qtrue; continue; } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( playerModel, value, sizeof(playerModel)); + Q_strncpyz(playerModel, value, sizeof(playerModel)); md3Model = qfalse; continue; } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( customSkin, value, sizeof(customSkin)); + Q_strncpyz(customSkin, value, sizeof(customSkin)); continue; } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - char tk[4096]; //rww - hackilicious! + if (!Q_stricmp(token, "playerTeam")) { + char tk[4096]; // rww - hackilicious! - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - //playerTeam = TranslateTeamName(value); + // playerTeam = TranslateTeamName(value); Com_sprintf(tk, sizeof(tk), "NPC%s", token); - playerTeam = GetIDForString( TeamTable, tk ); + playerTeam = GetIDForString(TeamTable, tk); continue; } - // snd - if ( !Q_stricmp( token, "snd" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->r.svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->r.svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - spawner->s.csSounds_Std = G_SoundIndex( va("*$%s", sound) ); + spawner->s.csSounds_Std = G_SoundIndex(va("*$%s", sound)); } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->r.svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->r.svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - spawner->s.csSounds_Combat = G_SoundIndex( va("*$%s", sound) ); + spawner->s.csSounds_Combat = G_SoundIndex(va("*$%s", sound)); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->r.svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->r.svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - spawner->s.csSounds_Extra = G_SoundIndex( va("*$%s", sound) ); + spawner->s.csSounds_Extra = G_SoundIndex(va("*$%s", sound)); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) { - if ( COM_ParseString( &p, &value ) ) { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(spawner->r.svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(spawner->r.svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - spawner->s.csSounds_Jedi = G_SoundIndex( va("*$%s", sound) ); + spawner->s.csSounds_Jedi = G_SoundIndex(va("*$%s", sound)); } continue; } - if (!Q_stricmp(token, "weapon")) - { + if (!Q_stricmp(token, "weapon")) { int curWeap; - if (COM_ParseString(&p, &value)) - { + if (COM_ParseString(&p, &value)) { continue; } - curWeap = GetIDForString( WPTable, value ); + curWeap = GetIDForString(WPTable, value); - if (curWeap > WP_NONE && curWeap < WP_NUM_WEAPONS) - { + if (curWeap > WP_NONE && curWeap < WP_NUM_WEAPONS) { RegisterItem(BG_FindItemForWeapon((weapon_t)curWeap)); } continue; @@ -834,34 +709,29 @@ void NPC_Precache ( gentity_t *spawner ) } // If we're not a vehicle, then an error here would be valid... - if ( !spawner->client || spawner->client->NPC_class != CLASS_VEHICLE ) - { - if ( md3Model ) - { + if (!spawner->client || spawner->client->NPC_class != CLASS_VEHICLE) { + if (md3Model) { Com_Printf("MD3 model using NPCs are not supported in MP\n"); - } - else - { //if we have a model/skin then index them so they'll be registered immediately - //when the client gets a configstring update. + } else { // if we have a model/skin then index them so they'll be registered immediately + // when the client gets a configstring update. char modelName[MAX_QPATH]; Com_sprintf(modelName, sizeof(modelName), "models/players/%s/model.glm", playerModel); - if (customSkin[0]) - { //append it after a * - strcat( modelName, va("*%s", customSkin) ); + if (customSkin[0]) { // append it after a * + strcat(modelName, va("*%s", customSkin)); } G_ModelIndex(modelName); } } - //precache this NPC's possible weapons - NPC_PrecacheWeapons( (team_t)playerTeam, spawner->spawnflags, spawner->NPC_type ); + // precache this NPC's possible weapons + NPC_PrecacheWeapons((team_t)playerTeam, spawner->spawnflags, spawner->NPC_type); -// CG_RegisterNPCCustomSounds( &ci ); -// CG_RegisterNPCEffects( playerTeam ); - //rwwFIXMEFIXME: same - //FIXME: Look for a "sounds" directory and precache death, pain, alert sounds + // CG_RegisterNPCCustomSounds( &ci ); + // CG_RegisterNPCEffects( playerTeam ); + // rwwFIXMEFIXME: same + // FIXME: Look for a "sounds" directory and precache death, pain, alert sounds } #if 0 @@ -963,23 +833,22 @@ void NPC_BuildRandom( gentity_t *NPC ) #endif extern void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName); -qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) -{ - const char *token; - const char *value; - const char *p; - int n; - float f; - char *patch; - char sound[MAX_QPATH]; - char playerModel[MAX_QPATH]; - char customSkin[MAX_QPATH]; - char sessionName[MAX_QPATH+17]; - renderInfo_t *ri = &NPC->client->renderInfo; - gNPCstats_t *stats = NULL; - qboolean md3Model = qtrue; - char surfOff[1024]; - char surfOn[1024]; +qboolean NPC_ParseParms(const char *NPCName, gentity_t *NPC) { + const char *token; + const char *value; + const char *p; + int n; + float f; + char *patch; + char sound[MAX_QPATH]; + char playerModel[MAX_QPATH]; + char customSkin[MAX_QPATH]; + char sessionName[MAX_QPATH + 17]; + renderInfo_t *ri = &NPC->client->renderInfo; + gNPCstats_t *stats = NULL; + qboolean md3Model = qtrue; + char surfOff[1024]; + char surfOn[1024]; qboolean parsingPlayer = qfalse; vec3_t playerMins; vec3_t playerMaxs; @@ -989,64 +858,59 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) VectorSet(playerMins, -15, -15, DEFAULT_MINS_2); VectorSet(playerMaxs, 15, 15, DEFAULT_MAXS_2); - strcpy(customSkin,"default"); - if ( !NPCName || !NPCName[0]) - { + strcpy(customSkin, "default"); + if (!NPCName || !NPCName[0]) { NPCName = "Player"; } - if ( !NPC->s.number && NPC->client != NULL ) - {//player, only want certain data + if (!NPC->s.number && NPC->client != NULL) { // player, only want certain data parsingPlayer = qtrue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats = &NPC->NPC->stats; -/* - NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; - NPC->NPC->allWeaponOrder[1] = WP_SABER; - NPC->NPC->allWeaponOrder[2] = WP_IMOD; - NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; - NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[6] = WP_NONE; - NPC->NPC->allWeaponOrder[7] = WP_NONE; -*/ + /* + NPC->NPC->allWeaponOrder[0] = WP_BRYAR_PISTOL; + NPC->NPC->allWeaponOrder[1] = WP_SABER; + NPC->NPC->allWeaponOrder[2] = WP_IMOD; + NPC->NPC->allWeaponOrder[3] = WP_SCAVENGER_RIFLE; + NPC->NPC->allWeaponOrder[4] = WP_TRICORDER; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[6] = WP_NONE; + NPC->NPC->allWeaponOrder[7] = WP_NONE; + */ // fill in defaults - stats->aggression = 3; - stats->aim = 3; - stats->earshot = 1024; - stats->evasion = 3; - stats->hfov = 90; - stats->intelligence = 3; - stats->move = 3; - stats->reactions = 3; - stats->vfov = 60; - stats->vigilance = 0.1f; - stats->visrange = 1024; - - stats->health = 0; - - stats->yawSpeed = 90; - stats->walkSpeed = 90; - stats->runSpeed = 300; - stats->acceleration = 15;//Increase/descrease speed this much per frame (20fps) - } - else - { + stats->aggression = 3; + stats->aim = 3; + stats->earshot = 1024; + stats->evasion = 3; + stats->hfov = 90; + stats->intelligence = 3; + stats->move = 3; + stats->reactions = 3; + stats->vfov = 60; + stats->vigilance = 0.1f; + stats->visrange = 1024; + + stats->health = 0; + + stats->yawSpeed = 90; + stats->walkSpeed = 90; + stats->runSpeed = 300; + stats->acceleration = 15; // Increase/descrease speed this much per frame (20fps) + } else { stats = NULL; } - //Set defaults - //FIXME: should probably put default torso and head models, but what about enemies - //that don't have any- like Stasis? - //Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName), qtrue); - //Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName), qtrue); - //Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName), qtrue); - //FIXME: should we have one for weapon too? - memset( (char *)surfOff, 0, sizeof(surfOff) ); - memset( (char *)surfOn, 0, sizeof(surfOn) ); + // Set defaults + // FIXME: should probably put default torso and head models, but what about enemies + // that don't have any- like Stasis? + // Q_strncpyz( ri->headModelName, DEFAULT_HEADMODEL, sizeof(ri->headModelName), qtrue); + // Q_strncpyz( ri->torsoModelName, DEFAULT_TORSOMODEL, sizeof(ri->torsoModelName), qtrue); + // Q_strncpyz( ri->legsModelName, DEFAULT_LEGSMODEL, sizeof(ri->legsModelName), qtrue); + // FIXME: should we have one for weapon too? + memset((char *)surfOff, 0, sizeof(surfOff)); + memset((char *)surfOn, 0, sizeof(surfOn)); /* ri->headYawRangeLeft = 50; @@ -1073,7 +937,7 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) NPC->client->ps.crouchheight = CROUCH_MAXS_2; NPC->client->ps.standheight = DEFAULT_MAXS_2; - //rwwFIXMEFIXME: ... + // rwwFIXMEFIXME: ... /* NPC->client->moveType = MT_RUNJUMP; @@ -1086,85 +950,68 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) NPC->s.modelScale[0] = NPC->s.modelScale[1] = NPC->s.modelScale[2] = 1.0f; */ - NPC->client->ps.customRGBA[0]=255; - NPC->client->ps.customRGBA[1]=255; - NPC->client->ps.customRGBA[2]=255; - NPC->client->ps.customRGBA[3]=255; + NPC->client->ps.customRGBA[0] = 255; + NPC->client->ps.customRGBA[1] = 255; + NPC->client->ps.customRGBA[2] = 255; + NPC->client->ps.customRGBA[3] = 255; - if ( !Q_stricmp( "random", NPCName ) ) - {//Randomly assemble a starfleet guy - //NPC_BuildRandom( NPC ); + if (!Q_stricmp("random", NPCName)) { // Randomly assemble a starfleet guy + // NPC_BuildRandom( NPC ); Com_Printf("RANDOM NPC NOT SUPPORTED IN MP\n"); return qfalse; - } - else - { + } else { int fp; p = NPCParms; - Com_sprintf( sessionName, sizeof(sessionName), "NPC_ParseParms(%s)", NPCName ); + Com_sprintf(sessionName, sizeof(sessionName), "NPC_ParseParms(%s)", NPCName); COM_BeginParseSession(sessionName); // look for the right NPC - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { return qfalse; } - if ( !Q_stricmp( token, NPCName ) ) - { + if (!Q_stricmp(token, NPCName)) { break; } - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } - if ( !p ) - { + if (!p) { return qfalse; } - if ( BG_ParseLiteral( &p, "{" ) ) - { + if (BG_ParseLiteral(&p, "{")) { return qfalse; } // parse the NPC info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", NPCName ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", NPCName); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - //===MODEL PROPERTIES=========================================================== + //===MODEL PROPERTIES=========================================================== // custom color - if ( !Q_stricmp( token, "customRGBA" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customRGBA")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !Q_stricmp( value, "random") ) - { - NPC->client->ps.customRGBA[0]=Q_irand(0,255); - NPC->client->ps.customRGBA[1]=Q_irand(0,255); - NPC->client->ps.customRGBA[2]=Q_irand(0,255); - NPC->client->ps.customRGBA[3]=255; - } - else if ( !Q_stricmp( value, "random1" ) ) - { + if (!Q_stricmp(value, "random")) { + NPC->client->ps.customRGBA[0] = Q_irand(0, 255); + NPC->client->ps.customRGBA[1] = Q_irand(0, 255); + NPC->client->ps.customRGBA[2] = Q_irand(0, 255); NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 5 ) ) - { + } else if (!Q_stricmp(value, "random1")) { + NPC->client->ps.customRGBA[3] = 255; + switch (Q_irand(0, 5)) { default: case 0: NPC->client->ps.customRGBA[0] = 127; @@ -1197,363 +1044,326 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) NPC->client->ps.customRGBA[2] = 14; break; } - } - else if ( !Q_stricmp( value, "jedi_hf" ) ) - { + } else if (!Q_stricmp(value, "jedi_hf")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 7 ) ) - { + switch (Q_irand(0, 7)) { default: - case 0://red1 + case 0: // red1 NPC->client->ps.customRGBA[0] = 165; NPC->client->ps.customRGBA[1] = 48; NPC->client->ps.customRGBA[2] = 21; break; - case 1://yellow1 + case 1: // yellow1 NPC->client->ps.customRGBA[0] = 254; NPC->client->ps.customRGBA[1] = 230; NPC->client->ps.customRGBA[2] = 132; break; - case 2://bluegray + case 2: // bluegray NPC->client->ps.customRGBA[0] = 181; NPC->client->ps.customRGBA[1] = 207; NPC->client->ps.customRGBA[2] = 255; break; - case 3://pink + case 3: // pink NPC->client->ps.customRGBA[0] = 233; NPC->client->ps.customRGBA[1] = 183; NPC->client->ps.customRGBA[2] = 208; break; - case 4://lt blue + case 4: // lt blue NPC->client->ps.customRGBA[0] = 161; NPC->client->ps.customRGBA[1] = 226; NPC->client->ps.customRGBA[2] = 240; break; - case 5://blue + case 5: // blue NPC->client->ps.customRGBA[0] = 101; NPC->client->ps.customRGBA[1] = 159; NPC->client->ps.customRGBA[2] = 255; break; - case 6://orange + case 6: // orange NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 157; NPC->client->ps.customRGBA[2] = 114; break; - case 7://violet + case 7: // violet NPC->client->ps.customRGBA[0] = 216; NPC->client->ps.customRGBA[1] = 160; NPC->client->ps.customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_hm" ) ) - { + } else if (!Q_stricmp(value, "jedi_hm")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 7 ) ) - { + switch (Q_irand(0, 7)) { default: - case 0://yellow + case 0: // yellow NPC->client->ps.customRGBA[0] = 252; NPC->client->ps.customRGBA[1] = 243; NPC->client->ps.customRGBA[2] = 180; break; - case 1://blue + case 1: // blue NPC->client->ps.customRGBA[0] = 69; NPC->client->ps.customRGBA[1] = 109; NPC->client->ps.customRGBA[2] = 255; break; - case 2://gold + case 2: // gold NPC->client->ps.customRGBA[0] = 254; NPC->client->ps.customRGBA[1] = 197; NPC->client->ps.customRGBA[2] = 73; break; - case 3://orange + case 3: // orange NPC->client->ps.customRGBA[0] = 178; NPC->client->ps.customRGBA[1] = 78; NPC->client->ps.customRGBA[2] = 18; break; - case 4://bluegreen + case 4: // bluegreen NPC->client->ps.customRGBA[0] = 112; NPC->client->ps.customRGBA[1] = 153; NPC->client->ps.customRGBA[2] = 161; break; - case 5://blue2 + case 5: // blue2 NPC->client->ps.customRGBA[0] = 123; NPC->client->ps.customRGBA[1] = 182; NPC->client->ps.customRGBA[2] = 255; break; - case 6://green2 + case 6: // green2 NPC->client->ps.customRGBA[0] = 0; NPC->client->ps.customRGBA[1] = 88; NPC->client->ps.customRGBA[2] = 105; break; - case 7://violet + case 7: // violet NPC->client->ps.customRGBA[0] = 138; NPC->client->ps.customRGBA[1] = 0; NPC->client->ps.customRGBA[2] = 0; break; } - } - else if ( !Q_stricmp( value, "jedi_kdm" ) ) - { + } else if (!Q_stricmp(value, "jedi_kdm")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 8 ) ) - { + switch (Q_irand(0, 8)) { default: - case 0://blue + case 0: // blue NPC->client->ps.customRGBA[0] = 85; NPC->client->ps.customRGBA[1] = 120; NPC->client->ps.customRGBA[2] = 255; break; - case 1://violet + case 1: // violet NPC->client->ps.customRGBA[0] = 173; NPC->client->ps.customRGBA[1] = 142; NPC->client->ps.customRGBA[2] = 219; break; - case 2://brown1 + case 2: // brown1 NPC->client->ps.customRGBA[0] = 254; NPC->client->ps.customRGBA[1] = 197; NPC->client->ps.customRGBA[2] = 73; break; - case 3://orange + case 3: // orange NPC->client->ps.customRGBA[0] = 138; NPC->client->ps.customRGBA[1] = 83; NPC->client->ps.customRGBA[2] = 0; break; - case 4://gold + case 4: // gold NPC->client->ps.customRGBA[0] = 254; NPC->client->ps.customRGBA[1] = 199; NPC->client->ps.customRGBA[2] = 14; break; - case 5://blue2 + case 5: // blue2 NPC->client->ps.customRGBA[0] = 68; NPC->client->ps.customRGBA[1] = 194; NPC->client->ps.customRGBA[2] = 217; break; - case 6://red1 + case 6: // red1 NPC->client->ps.customRGBA[0] = 170; NPC->client->ps.customRGBA[1] = 3; NPC->client->ps.customRGBA[2] = 30; break; - case 7://yellow1 + case 7: // yellow1 NPC->client->ps.customRGBA[0] = 225; NPC->client->ps.customRGBA[1] = 226; NPC->client->ps.customRGBA[2] = 144; break; - case 8://violet2 + case 8: // violet2 NPC->client->ps.customRGBA[0] = 167; NPC->client->ps.customRGBA[1] = 202; NPC->client->ps.customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_rm" ) ) - { + } else if (!Q_stricmp(value, "jedi_rm")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 8 ) ) - { + switch (Q_irand(0, 8)) { default: - case 0://blue + case 0: // blue NPC->client->ps.customRGBA[0] = 127; NPC->client->ps.customRGBA[1] = 153; NPC->client->ps.customRGBA[2] = 255; break; - case 1://green1 + case 1: // green1 NPC->client->ps.customRGBA[0] = 208; NPC->client->ps.customRGBA[1] = 249; NPC->client->ps.customRGBA[2] = 85; break; - case 2://blue2 + case 2: // blue2 NPC->client->ps.customRGBA[0] = 181; NPC->client->ps.customRGBA[1] = 207; NPC->client->ps.customRGBA[2] = 255; break; - case 3://gold + case 3: // gold NPC->client->ps.customRGBA[0] = 138; NPC->client->ps.customRGBA[1] = 83; NPC->client->ps.customRGBA[2] = 0; break; - case 4://gold + case 4: // gold NPC->client->ps.customRGBA[0] = 224; NPC->client->ps.customRGBA[1] = 171; NPC->client->ps.customRGBA[2] = 44; break; - case 5://green2 + case 5: // green2 NPC->client->ps.customRGBA[0] = 49; NPC->client->ps.customRGBA[1] = 155; NPC->client->ps.customRGBA[2] = 131; break; - case 6://red1 + case 6: // red1 NPC->client->ps.customRGBA[0] = 163; NPC->client->ps.customRGBA[1] = 79; NPC->client->ps.customRGBA[2] = 17; break; - case 7://violet2 + case 7: // violet2 NPC->client->ps.customRGBA[0] = 148; NPC->client->ps.customRGBA[1] = 104; NPC->client->ps.customRGBA[2] = 228; break; - case 8://green3 + case 8: // green3 NPC->client->ps.customRGBA[0] = 138; NPC->client->ps.customRGBA[1] = 136; NPC->client->ps.customRGBA[2] = 0; break; } - } - else if ( !Q_stricmp( value, "jedi_tf" ) ) - { + } else if (!Q_stricmp(value, "jedi_tf")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 5 ) ) - { + switch (Q_irand(0, 5)) { default: - case 0://green1 + case 0: // green1 NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 235; NPC->client->ps.customRGBA[2] = 100; break; - case 1://blue1 + case 1: // blue1 NPC->client->ps.customRGBA[0] = 62; NPC->client->ps.customRGBA[1] = 155; NPC->client->ps.customRGBA[2] = 255; break; - case 2://red1 + case 2: // red1 NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 110; NPC->client->ps.customRGBA[2] = 120; break; - case 3://purple + case 3: // purple NPC->client->ps.customRGBA[0] = 180; NPC->client->ps.customRGBA[1] = 150; NPC->client->ps.customRGBA[2] = 255; break; - case 4://flesh + case 4: // flesh NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 200; NPC->client->ps.customRGBA[2] = 212; break; - case 5://base + case 5: // base NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 255; NPC->client->ps.customRGBA[2] = 255; break; } - } - else if ( !Q_stricmp( value, "jedi_zf" ) ) - { + } else if (!Q_stricmp(value, "jedi_zf")) { NPC->client->ps.customRGBA[3] = 255; - switch ( Q_irand( 0, 7 ) ) - { + switch (Q_irand(0, 7)) { default: - case 0://red1 + case 0: // red1 NPC->client->ps.customRGBA[0] = 204; NPC->client->ps.customRGBA[1] = 19; NPC->client->ps.customRGBA[2] = 21; break; - case 1://orange1 + case 1: // orange1 NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 107; NPC->client->ps.customRGBA[2] = 40; break; - case 2://pink1 + case 2: // pink1 NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 148; NPC->client->ps.customRGBA[2] = 155; break; - case 3://gold + case 3: // gold NPC->client->ps.customRGBA[0] = 255; NPC->client->ps.customRGBA[1] = 164; NPC->client->ps.customRGBA[2] = 59; break; - case 4://violet1 + case 4: // violet1 NPC->client->ps.customRGBA[0] = 216; NPC->client->ps.customRGBA[1] = 160; NPC->client->ps.customRGBA[2] = 255; break; - case 5://blue1 + case 5: // blue1 NPC->client->ps.customRGBA[0] = 101; NPC->client->ps.customRGBA[1] = 159; NPC->client->ps.customRGBA[2] = 255; break; - case 6://blue2 + case 6: // blue2 NPC->client->ps.customRGBA[0] = 161; NPC->client->ps.customRGBA[1] = 226; NPC->client->ps.customRGBA[2] = 240; break; - case 7://blue3 + case 7: // blue3 NPC->client->ps.customRGBA[0] = 37; NPC->client->ps.customRGBA[1] = 155; NPC->client->ps.customRGBA[2] = 181; break; } - } - else - { - NPC->client->ps.customRGBA[0]=atoi(value); + } else { + NPC->client->ps.customRGBA[0] = atoi(value); - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - NPC->client->ps.customRGBA[1]=n; + NPC->client->ps.customRGBA[1] = n; - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - NPC->client->ps.customRGBA[2]=n; + NPC->client->ps.customRGBA[2] = n; - if ( COM_ParseInt( &p, &n ) ) - { + if (COM_ParseInt(&p, &n)) { continue; } - NPC->client->ps.customRGBA[3]=n; + NPC->client->ps.customRGBA[3] = n; } continue; } // headmodel - if ( !Q_stricmp( token, "headmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "headmodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - //Zero the head clamp range so the torso & legs don't lag behind - ri->headYawRangeLeft = - ri->headYawRangeRight = - ri->headPitchRangeUp = - ri->headPitchRangeDown = 0; + if (!Q_stricmp("none", value)) { + // Zero the head clamp range so the torso & legs don't lag behind + ri->headYawRangeLeft = ri->headYawRangeRight = ri->headPitchRangeUp = ri->headPitchRangeDown = 0; } continue; } // torsomodel - if ( !Q_stricmp( token, "torsomodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "torsomodel")) { + if (COM_ParseString(&p, &value)) { continue; } - if(!Q_stricmp("none", value)) - { - //Zero the torso clamp range so the legs don't lag behind - ri->torsoYawRangeLeft = - ri->torsoYawRangeRight = - ri->torsoPitchRangeUp = - ri->torsoPitchRangeDown = 0; + if (!Q_stricmp("none", value)) { + // Zero the torso clamp range so the legs don't lag behind + ri->torsoYawRangeLeft = ri->torsoYawRangeRight = ri->torsoPitchRangeUp = ri->torsoPitchRangeDown = 0; } continue; } // legsmodel - if ( !Q_stricmp( token, "legsmodel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "legsmodel")) { + if (COM_ParseString(&p, &value)) { continue; } /* @@ -1565,196 +1375,158 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // playerModel - if ( !Q_stricmp( token, "playerModel" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "playerModel")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( playerModel, value, sizeof(playerModel)); + Q_strncpyz(playerModel, value, sizeof(playerModel)); md3Model = qfalse; continue; } // customSkin - if ( !Q_stricmp( token, "customSkin" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "customSkin")) { + if (COM_ParseString(&p, &value)) { continue; } - Q_strncpyz( customSkin, value, sizeof(customSkin)); + Q_strncpyz(customSkin, value, sizeof(customSkin)); continue; } // surfOff - if ( !Q_stricmp( token, "surfOff" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOff")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOff[0] ) - { - Q_strcat( (char *)surfOff, sizeof(surfOff), "," ); - Q_strcat( (char *)surfOff, sizeof(surfOff), value ); - } - else - { - Q_strncpyz( surfOff, value, sizeof(surfOff)); + if (surfOff[0]) { + Q_strcat((char *)surfOff, sizeof(surfOff), ","); + Q_strcat((char *)surfOff, sizeof(surfOff), value); + } else { + Q_strncpyz(surfOff, value, sizeof(surfOff)); } continue; } // surfOn - if ( !Q_stricmp( token, "surfOn" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "surfOn")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( surfOn[0] ) - { - Q_strcat( (char *)surfOn, sizeof(surfOn), "," ); - Q_strcat( (char *)surfOn, sizeof(surfOn), value ); - } - else - { - Q_strncpyz( surfOn, value, sizeof(surfOn)); + if (surfOn[0]) { + Q_strcat((char *)surfOn, sizeof(surfOn), ","); + Q_strcat((char *)surfOn, sizeof(surfOn), value); + } else { + Q_strncpyz(surfOn, value, sizeof(surfOn)); } continue; } - //headYawRangeLeft - if ( !Q_stricmp( token, "headYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeLeft + if (!Q_stricmp(token, "headYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeLeft = n; continue; } - //headYawRangeRight - if ( !Q_stricmp( token, "headYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headYawRangeRight + if (!Q_stricmp(token, "headYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headYawRangeRight = n; continue; } - //headPitchRangeUp - if ( !Q_stricmp( token, "headPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeUp + if (!Q_stricmp(token, "headPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeUp = n; continue; } - //headPitchRangeDown - if ( !Q_stricmp( token, "headPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // headPitchRangeDown + if (!Q_stricmp(token, "headPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->headPitchRangeDown = n; continue; } - //torsoYawRangeLeft - if ( !Q_stricmp( token, "torsoYawRangeLeft" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeLeft + if (!Q_stricmp(token, "torsoYawRangeLeft")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeLeft = n; continue; } - //torsoYawRangeRight - if ( !Q_stricmp( token, "torsoYawRangeRight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoYawRangeRight + if (!Q_stricmp(token, "torsoYawRangeRight")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoYawRangeRight = n; continue; } - //torsoPitchRangeUp - if ( !Q_stricmp( token, "torsoPitchRangeUp" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeUp + if (!Q_stricmp(token, "torsoPitchRangeUp")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeUp = n; continue; } - //torsoPitchRangeDown - if ( !Q_stricmp( token, "torsoPitchRangeDown" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // torsoPitchRangeDown + if (!Q_stricmp(token, "torsoPitchRangeDown")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } ri->torsoPitchRangeDown = n; @@ -1762,329 +1534,289 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // Uniform XYZ scale - if ( !Q_stricmp( token, "scale" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "scale")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { - NPC->client->ps.iModelScale = n; //so the client knows - if (n >= 1024) - { + if (n != 100) { + NPC->client->ps.iModelScale = n; // so the client knows + if (n >= 1024) { Com_Printf("WARNING: MP does not support scaling up to or over 1024%\n"); n = 1023; } - NPC->modelScale[0] = NPC->modelScale[1] = NPC->modelScale[2] = n/100.0f; + NPC->modelScale[0] = NPC->modelScale[1] = NPC->modelScale[2] = n / 100.0f; } continue; } - //X scale - if ( !Q_stricmp( token, "scaleX" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // X scale + if (!Q_stricmp(token, "scaleX")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { + if (n != 100) { Com_Printf("MP doesn't support xyz scaling, use 'scale'.\n"); - //NPC->s.modelScale[0] = n/100.0f; + // NPC->s.modelScale[0] = n/100.0f; } continue; } - //Y scale - if ( !Q_stricmp( token, "scaleY" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Y scale + if (!Q_stricmp(token, "scaleY")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { + if (n != 100) { Com_Printf("MP doesn't support xyz scaling, use 'scale'.\n"); - //NPC->s.modelScale[1] = n/100.0f; + // NPC->s.modelScale[1] = n/100.0f; } continue; } - //Z scale - if ( !Q_stricmp( token, "scaleZ" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // Z scale + if (!Q_stricmp(token, "scaleZ")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if (n != 100) - { + if (n != 100) { Com_Printf("MP doesn't support xyz scaling, use 'scale'.\n"); - // NPC->s.modelScale[2] = n/100.0f; + // NPC->s.modelScale[2] = n/100.0f; } continue; } - //===AI STATS===================================================================== - if ( !parsingPlayer ) - { + //===AI STATS===================================================================== + if (!parsingPlayer) { // aggression - if ( !Q_stricmp( token, "aggression" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aggression")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aggression = n; } continue; } // aim - if ( !Q_stricmp( token, "aim" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "aim")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->aim = n; } continue; } // earshot - if ( !Q_stricmp( token, "earshot" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "earshot")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->earshot = f; } continue; } // evasion - if ( !Q_stricmp( token, "evasion" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "evasion")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->evasion = n; } continue; } // hfov - if ( !Q_stricmp( token, "hfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "hfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 30 || n > 180 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 30 || n > 180) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - stats->hfov = n;// / 2; //FIXME: Why was this being done?! + if (NPC->NPC) { + stats->hfov = n; // / 2; //FIXME: Why was this being done?! } continue; } // intelligence - if ( !Q_stricmp( token, "intelligence" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "intelligence")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->intelligence = n; } continue; } // move - if ( !Q_stricmp( token, "move" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "move")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->move = n; } continue; } // reactions - if ( !Q_stricmp( token, "reactions" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "reactions")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 1 || n > 5 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 1 || n > 5) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->reactions = n; } continue; } // shootDistance - if ( !Q_stricmp( token, "shootDistance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "shootDistance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->shootDistance = f; } continue; } // vfov - if ( !Q_stricmp( token, "vfov" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vfov")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 30 || n > 180 ) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 30 || n > 180) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vfov = n / 2; } continue; } // vigilance - if ( !Q_stricmp( token, "vigilance" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "vigilance")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->vigilance = f; } continue; } // visrange - if ( !Q_stricmp( token, "visrange" ) ) { - if ( COM_ParseFloat( &p, &f ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "visrange")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - if ( f < 0.0f ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (f < 0.0f) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->visrange = f; } continue; } // race - // if ( !Q_stricmp( token, "race" ) ) - // { - // if ( COM_ParseString( &p, &value ) ) - // { - // continue; - // } - // NPC->client->race = TranslateRaceName(value); - // continue; - // } + // if ( !Q_stricmp( token, "race" ) ) + // { + // if ( COM_ParseString( &p, &value ) ) + // { + // continue; + // } + // NPC->client->race = TranslateRaceName(value); + // continue; + // } // rank - if ( !Q_stricmp( token, "rank" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "rank")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->rank = TranslateRankName(value); } continue; @@ -2092,34 +1824,26 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // health - if ( !Q_stricmp( token, "health" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "health")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->health = n; - } - else if ( parsingPlayer ) - { + } else if (parsingPlayer) { NPC->client->ps.stats[STAT_MAX_HEALTH] = NPC->client->pers.maxHealth = n; } continue; } // fullName - if ( !Q_stricmp( token, "fullName" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "fullName")) { + if (COM_ParseString(&p, &value)) { continue; } NPC->fullName = G_NewString(value); @@ -2127,49 +1851,44 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // playerTeam - if ( !Q_stricmp( token, "playerTeam" ) ) - { - char tk[4096]; //rww - hackilicious! + if (!Q_stricmp(token, "playerTeam")) { + char tk[4096]; // rww - hackilicious! - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } Com_sprintf(tk, sizeof(tk), "NPC%s", token); - NPC->client->playerTeam = NPC->s.teamowner = (team_t)GetIDForString( TeamTable, tk );//TranslateTeamName(value); + NPC->client->playerTeam = NPC->s.teamowner = (team_t)GetIDForString(TeamTable, tk); // TranslateTeamName(value); continue; } // enemyTeam - if ( !Q_stricmp( token, "enemyTeam" ) ) - { - char tk[4096]; //rww - hackilicious! + if (!Q_stricmp(token, "enemyTeam")) { + char tk[4096]; // rww - hackilicious! - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } Com_sprintf(tk, sizeof(tk), "NPC%s", token); - NPC->client->enemyTeam = GetIDForString( TeamTable, tk );//TranslateTeamName(value); + NPC->client->enemyTeam = GetIDForString(TeamTable, tk); // TranslateTeamName(value); continue; } // class - if ( !Q_stricmp( token, "class" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "class")) { + if (COM_ParseString(&p, &value)) { continue; } - NPC->client->NPC_class = (class_t)GetIDForString( ClassTable, value ); - NPC->s.NPC_class = NPC->client->NPC_class; //we actually only need this value now, but at the moment I don't feel like changing the 200+ references to client->NPC_class. + NPC->client->NPC_class = (class_t)GetIDForString(ClassTable, value); + NPC->s.NPC_class = NPC->client->NPC_class; // we actually only need this value now, but at the moment I don't feel like changing the 200+ + // references to client->NPC_class. // No md3's for vehicles. - if ( NPC->client->NPC_class == CLASS_VEHICLE ) - { - if ( !NPC->m_pVehicle ) - {//you didn't spawn this guy right! - Com_Printf ( S_COLOR_RED "ERROR: Tried to spawn a vehicle NPC (%s) without using NPC_Vehicle or 'NPC spawn vehicle '!!! Bad, bad, bad! Shame on you!\n", NPCName ); + if (NPC->client->NPC_class == CLASS_VEHICLE) { + if (!NPC->m_pVehicle) { // you didn't spawn this guy right! + Com_Printf(S_COLOR_RED "ERROR: Tried to spawn a vehicle NPC (%s) without using NPC_Vehicle or 'NPC spawn vehicle '!!! " + "Bad, bad, bad! Shame on you!\n", + NPCName); return qfalse; } md3Model = qfalse; @@ -2179,102 +1898,90 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // dismemberment probability for head - if ( !Q_stricmp( token, "dismemberProbHead" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHead")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - // NPC->client->dismemberProbHead = n; - //rwwFIXMEFIXME: support for this? + if (NPC->NPC) { + // NPC->client->dismemberProbHead = n; + // rwwFIXMEFIXME: support for this? } continue; } // dismemberment probability for arms - if ( !Q_stricmp( token, "dismemberProbArms" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbArms")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - // NPC->client->dismemberProbArms = n; + if (NPC->NPC) { + // NPC->client->dismemberProbArms = n; } continue; } // dismemberment probability for hands - if ( !Q_stricmp( token, "dismemberProbHands" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbHands")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - // NPC->client->dismemberProbHands = n; + if (NPC->NPC) { + // NPC->client->dismemberProbHands = n; } continue; } // dismemberment probability for waist - if ( !Q_stricmp( token, "dismemberProbWaist" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbWaist")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - // NPC->client->dismemberProbWaist = n; + if (NPC->NPC) { + // NPC->client->dismemberProbWaist = n; } continue; } // dismemberment probability for legs - if ( !Q_stricmp( token, "dismemberProbLegs" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "dismemberProbLegs")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { - // NPC->client->dismemberProbLegs = n; + if (NPC->NPC) { + // NPC->client->dismemberProbLegs = n; } continue; } - //===MOVEMENT STATS============================================================ + //===MOVEMENT STATS============================================================ - if ( !Q_stricmp( token, "width" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "width")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -2283,28 +1990,24 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !Q_stricmp( token, "height" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "height")) { + if (COM_ParseInt(&p, &n)) { continue; } - if ( NPC->client->NPC_class == CLASS_VEHICLE - && NPC->m_pVehicle - && NPC->m_pVehicle->m_pVehicleInfo - && NPC->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//a flying vehicle's origin must be centered in bbox and it should spawn on the ground - //trace_t tr; - //vec3_t bottom; - //float adjust = 32.0f; - NPC->r.maxs[2] = NPC->client->ps.standheight = (n/2.0f); + if (NPC->client->NPC_class == CLASS_VEHICLE && NPC->m_pVehicle && NPC->m_pVehicle->m_pVehicleInfo && + NPC->m_pVehicle->m_pVehicleInfo->type == + VH_FIGHTER) { // a flying vehicle's origin must be centered in bbox and it should spawn on the ground + // trace_t tr; + // vec3_t bottom; + // float adjust = 32.0f; + NPC->r.maxs[2] = NPC->client->ps.standheight = (n / 2.0f); NPC->r.mins[2] = -NPC->r.maxs[2]; - NPC->s.origin[2] += (DEFAULT_MINS_2-NPC->r.mins[2])+0.125f; + NPC->s.origin[2] += (DEFAULT_MINS_2 - NPC->r.mins[2]) + 0.125f; VectorCopy(NPC->s.origin, NPC->client->ps.origin); VectorCopy(NPC->s.origin, NPC->r.currentOrigin); - G_SetOrigin( NPC, NPC->s.origin ); + G_SetOrigin(NPC, NPC->s.origin); trap->LinkEntity((sharedEntity_t *)NPC); - //now trace down + // now trace down /* VectorCopy( NPC->s.origin, bottom ); bottom[2] -= adjust; @@ -2315,20 +2018,16 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) trap->LinkEntity((sharedEntity_t *)NPC); } */ - } - else - { - NPC->r.mins[2] = DEFAULT_MINS_2;//Cannot change + } else { + NPC->r.mins[2] = DEFAULT_MINS_2; // Cannot change NPC->r.maxs[2] = NPC->client->ps.standheight = n + DEFAULT_MINS_2; } NPC->radius = n; continue; } - if ( !Q_stricmp( token, "crouchheight" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { + if (!Q_stricmp(token, "crouchheight")) { + if (COM_ParseInt(&p, &n)) { continue; } @@ -2336,121 +2035,99 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !parsingPlayer ) - { - if ( !Q_stricmp( token, "movetype" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!parsingPlayer) { + if (!Q_stricmp(token, "movetype")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( Q_stricmp( "flyswim", value ) == 0 ) - { + if (Q_stricmp("flyswim", value) == 0) { NPC->client->ps.eFlags2 |= EF2_FLYING; } - //NPC->client->moveType = (movetype_t)MoveTypeNameToEnum(value); - //rwwFIXMEFIXME: support for movetypes + // NPC->client->moveType = (movetype_t)MoveTypeNameToEnum(value); + // rwwFIXMEFIXME: support for movetypes continue; } // yawSpeed - if ( !Q_stricmp( token, "yawSpeed" ) ) { - if ( COM_ParseInt( &p, &n ) ) { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "yawSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n <= 0) { - Com_Printf( "bad %s in NPC '%s'\n", token, NPCName ); + if (n <= 0) { + Com_Printf("bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->yawSpeed = ((float)(n)); } continue; } // walkSpeed - if ( !Q_stricmp( token, "walkSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "walkSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->walkSpeed = n; } continue; } - //runSpeed - if ( !Q_stricmp( token, "runSpeed" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // runSpeed + if (!Q_stricmp(token, "runSpeed")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->runSpeed = n; } continue; } - //acceleration - if ( !Q_stricmp( token, "acceleration" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // acceleration + if (!Q_stricmp(token, "acceleration")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < 0 ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { stats->acceleration = n; } continue; } - //sex - skip in MP - if ( !Q_stricmp( token, "sex" ) ) - { - SkipRestOfLine( &p ); + // sex - skip in MP + if (!Q_stricmp(token, "sex")) { + SkipRestOfLine(&p); continue; } -//===MISC=============================================================================== + //===MISC=============================================================================== // default behavior - if ( !Q_stricmp( token, "behavior" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "behavior")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( n < BS_DEFAULT || n >= NUM_BSTATES ) - { - Com_Printf( S_COLOR_YELLOW"WARNING: bad %s in NPC '%s'\n", token, NPCName ); + if (n < BS_DEFAULT || n >= NUM_BSTATES) { + Com_Printf(S_COLOR_YELLOW "WARNING: bad %s in NPC '%s'\n", token, NPCName); continue; } - if ( NPC->NPC ) - { + if (NPC->NPC) { NPC->NPC->defaultBehavior = (bState_t)(n); } continue; @@ -2458,248 +2135,202 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // snd - if ( !Q_stricmp( token, "snd" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "snd")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->r.svFlags&SVF_NO_BASIC_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->r.svFlags & SVF_NO_BASIC_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - // ci->customBasicSoundDir = G_NewString( sound ); - //rwwFIXMEFIXME: Hooray for violating client server rules + // ci->customBasicSoundDir = G_NewString( sound ); + // rwwFIXMEFIXME: Hooray for violating client server rules } continue; } // sndcombat - if ( !Q_stricmp( token, "sndcombat" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndcombat")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->r.svFlags&SVF_NO_COMBAT_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->r.svFlags & SVF_NO_COMBAT_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - // ci->customCombatSoundDir = G_NewString( sound ); + // ci->customCombatSoundDir = G_NewString( sound ); } continue; } // sndextra - if ( !Q_stricmp( token, "sndextra" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndextra")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->r.svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->r.svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - // ci->customExtraSoundDir = G_NewString( sound ); + // ci->customExtraSoundDir = G_NewString( sound ); } continue; } // sndjedi - if ( !Q_stricmp( token, "sndjedi" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "sndjedi")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->r.svFlags&SVF_NO_EXTRA_SOUNDS) ) - { - //FIXME: store this in some sound field or parse in the soundTable like the animTable... - Q_strncpyz( sound, value, sizeof( sound ) ); - patch = strstr( sound, "/" ); - if ( patch ) - { + if (!(NPC->r.svFlags & SVF_NO_EXTRA_SOUNDS)) { + // FIXME: store this in some sound field or parse in the soundTable like the animTable... + Q_strncpyz(sound, value, sizeof(sound)); + patch = strstr(sound, "/"); + if (patch) { *patch = 0; } - //ci->customJediSoundDir = G_NewString( sound ); + // ci->customJediSoundDir = G_NewString( sound ); } continue; } - //New NPC/jedi stats: - //starting weapon - if ( !Q_stricmp( token, "weapon" ) ) - { + // New NPC/jedi stats: + // starting weapon + if (!Q_stricmp(token, "weapon")) { int weap; - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - //FIXME: need to precache the weapon, too? (in above func) - weap = GetIDForString( WPTable, value ); - if ( weap >= WP_NONE && weap <= WP_NUM_WEAPONS )///*WP_BLASTER_PISTOL*/WP_SABER ) //?! + // FIXME: need to precache the weapon, too? (in above func) + weap = GetIDForString(WPTable, value); + if (weap >= WP_NONE && weap <= WP_NUM_WEAPONS) ///*WP_BLASTER_PISTOL*/WP_SABER ) //?! { NPC->client->ps.weapon = weap; - NPC->client->ps.stats[STAT_WEAPONS] |= ( 1 << NPC->client->ps.weapon ); - if ( weap > WP_NONE ) - { - // RegisterItem( FindItemForWeapon( (weapon_t)(NPC->client->ps.weapon) ) ); //precache the weapon - NPC->client->ps.ammo[weaponData[NPC->client->ps.weapon].ammoIndex] = 100;//FIXME: max ammo! + NPC->client->ps.stats[STAT_WEAPONS] |= (1 << NPC->client->ps.weapon); + if (weap > WP_NONE) { + // RegisterItem( FindItemForWeapon( (weapon_t)(NPC->client->ps.weapon) ) ); //precache the weapon + NPC->client->ps.ammo[weaponData[NPC->client->ps.weapon].ammoIndex] = 100; // FIXME: max ammo! } } continue; } - if ( !parsingPlayer ) - { - //altFire - if ( !Q_stricmp( token, "altFire" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + if (!parsingPlayer) { + // altFire + if (!Q_stricmp(token, "altFire")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - if ( NPC->NPC ) - { - if ( n != 0 ) - { + if (NPC->NPC) { + if (n != 0) { NPC->NPC->scriptFlags |= SCF_ALT_FIRE; } } continue; } - //Other unique behaviors/numbers that are currently hardcoded? + // Other unique behaviors/numbers that are currently hardcoded? } - //force powers - fp = GetIDForString( FPTable, token ); - if ( fp >= FP_FIRST && fp < NUM_FORCE_POWERS ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force powers + fp = GetIDForString(FPTable, token); + if (fp >= FP_FIRST && fp < NUM_FORCE_POWERS) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //FIXME: need to precache the fx, too? (in above func) - //cap - if ( n > 5 ) - { + // FIXME: need to precache the fx, too? (in above func) + // cap + if (n > 5) { n = 5; - } - else if ( n < 0 ) - { + } else if (n < 0) { n = 0; } - if ( n ) - {//set - NPC->client->ps.fd.forcePowersKnown |= ( 1 << fp ); - } - else - {//clear - NPC->client->ps.fd.forcePowersKnown &= ~( 1 << fp ); + if (n) { // set + NPC->client->ps.fd.forcePowersKnown |= (1 << fp); + } else { // clear + NPC->client->ps.fd.forcePowersKnown &= ~(1 << fp); } NPC->client->ps.fd.forcePowerLevel[fp] = n; continue; } - //max force power - if ( !Q_stricmp( token, "forcePowerMax" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // max force power + if (!Q_stricmp(token, "forcePowerMax")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } NPC->client->ps.fd.forcePowerMax = n; continue; } - //force regen rate - default is 100ms - if ( !Q_stricmp( token, "forceRegenRate" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force regen rate - default is 100ms + if (!Q_stricmp(token, "forceRegenRate")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //NPC->client->ps.forcePowerRegenRate = n; - //rwwFIXMEFIXME: support this? + // NPC->client->ps.forcePowerRegenRate = n; + // rwwFIXMEFIXME: support this? continue; } - //force regen amount - default is 1 (points per second) - if ( !Q_stricmp( token, "forceRegenAmount" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // force regen amount - default is 1 (points per second) + if (!Q_stricmp(token, "forceRegenAmount")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //NPC->client->ps.forcePowerRegenAmount = n; - //rwwFIXMEFIXME: support this? + // NPC->client->ps.forcePowerRegenAmount = n; + // rwwFIXMEFIXME: support this? continue; } - //have a sabers.cfg and just name your saber in your NPCs.cfg/ICARUS script - //saber name - if ( !Q_stricmp( token, "saber" ) ) - { + // have a sabers.cfg and just name your saber in your NPCs.cfg/ICARUS script + // saber name + if (!Q_stricmp(token, "saber")) { char *saberName; - if ( COM_ParseString( &p, &value ) ) - { + if (COM_ParseString(&p, &value)) { continue; } - saberName = (char *)BG_TempAlloc(4096);//G_NewString( value ); + saberName = (char *)BG_TempAlloc(4096); // G_NewString( value ); strcpy(saberName, value); - WP_SaberParseParms( saberName, &NPC->client->saber[0] ); + WP_SaberParseParms(saberName, &NPC->client->saber[0]); npcSaber1 = G_ModelIndex(va("@%s", saberName)); BG_TempFree(4096); continue; } - //second saber name - if ( !Q_stricmp( token, "saber2" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + // second saber name + if (!Q_stricmp(token, "saber2")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( !(NPC->client->saber[0].saberFlags&SFL_TWO_HANDED) ) - {//can't use a second saber if first one is a two-handed saber...? - char *saberName = (char *)BG_TempAlloc(4096);//G_NewString( value ); + if (!(NPC->client->saber[0].saberFlags & SFL_TWO_HANDED)) { // can't use a second saber if first one is a two-handed saber...? + char *saberName = (char *)BG_TempAlloc(4096); // G_NewString( value ); strcpy(saberName, value); - WP_SaberParseParms( saberName, &NPC->client->saber[1] ); - if ( (NPC->client->saber[1].saberFlags&SFL_TWO_HANDED) ) - {//tsk tsk, can't use a twoHanded saber as second saber - WP_RemoveSaber( NPC->client->saber, 1 ); - } - else - { - //NPC->client->ps.dualSabers = qtrue; + WP_SaberParseParms(saberName, &NPC->client->saber[1]); + if ((NPC->client->saber[1].saberFlags & SFL_TWO_HANDED)) { // tsk tsk, can't use a twoHanded saber as second saber + WP_RemoveSaber(NPC->client->saber, 1); + } else { + // NPC->client->ps.dualSabers = qtrue; npcSaber2 = G_ModelIndex(va("@%s", saberName)); } BG_TempFree(4096); @@ -2708,772 +2339,617 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) } // saberColor - if ( !Q_stricmp( token, "saberColor" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - saber_colors_t color = TranslateSaberColor( value ); - for ( n = 0; n < MAX_BLADES; n++ ) - { + if (NPC->client) { + saber_colors_t color = TranslateSaberColor(value); + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[0].blade[n].color = color; - NPC->s.boltToPlayer = NPC->s.boltToPlayer & 0x38;//(111000) + NPC->s.boltToPlayer = NPC->s.boltToPlayer & 0x38; //(111000) NPC->s.boltToPlayer += (color + 1); } } continue; } - if ( !Q_stricmp( token, "saberColor2" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor2")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[1].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[1].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor3" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor3")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[2].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[2].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor4" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor4")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[3].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[3].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor5" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor5")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[4].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[4].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor6" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor6")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[5].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[5].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor7" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor7")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[6].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[6].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saberColor8" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saberColor8")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[0].blade[7].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[0].blade[7].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - saber_colors_t color = TranslateSaberColor( value ); - for ( n = 0; n < MAX_BLADES; n++ ) - { + if (NPC->client) { + saber_colors_t color = TranslateSaberColor(value); + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[1].blade[n].color = color; - NPC->s.boltToPlayer = NPC->s.boltToPlayer & 0x7;//(000111) + NPC->s.boltToPlayer = NPC->s.boltToPlayer & 0x7; //(000111) NPC->s.boltToPlayer += ((color + 1) << 3); } } continue; } - if ( !Q_stricmp( token, "saber2Color2" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color2")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[1].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[1].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color3" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color3")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[2].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[2].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color4" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color4")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[3].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[3].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color5" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color5")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[4].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[4].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color6" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color6")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[5].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[5].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color7" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color7")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[6].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[6].color = TranslateSaberColor(value); } continue; } - if ( !Q_stricmp( token, "saber2Color8" ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, "saber2Color8")) { + if (COM_ParseString(&p, &value)) { continue; } - if ( NPC->client ) - { - NPC->client->saber[1].blade[7].color = TranslateSaberColor( value ); + if (NPC->client) { + NPC->client->saber[1].blade[7].color = TranslateSaberColor(value); } continue; } - //saber length - if ( !Q_stricmp( token, "saberLength" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + // saber length + if (!Q_stricmp(token, "saberLength")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[0].blade[n].lengthMax = f; } continue; } - if ( !Q_stricmp( token, "saberLength2" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength2")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[1].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength3" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength3")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[2].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength4" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength4")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[3].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength5" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength5")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[4].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength6" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength6")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[5].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength7" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength7")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[6].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saberLength8" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberLength8")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[0].blade[7].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[1].blade[n].lengthMax = f; } continue; } - if ( !Q_stricmp( token, "saber2Length2" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length2")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[1].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length3" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length3")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[2].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length4" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length4")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[3].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length5" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length5")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[4].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length6" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length6")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[5].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length7" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length7")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[6].lengthMax = f; continue; } - if ( !Q_stricmp( token, "saber2Length8" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Length8")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 4.0f ) - { + // cap + if (f < 4.0f) { f = 4.0f; } NPC->client->saber[1].blade[7].lengthMax = f; continue; } - //saber radius - if ( !Q_stricmp( token, "saberRadius" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + // saber radius + if (!Q_stricmp(token, "saberRadius")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[0].blade[n].radius = f; } continue; } - if ( !Q_stricmp( token, "saberRadius2" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius2")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[1].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius3" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius3")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[2].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius4" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius4")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[3].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius5" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius5")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[4].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius6" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius6")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[5].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius7" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius7")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[6].radius = f; continue; } - if ( !Q_stricmp( token, "saberRadius8" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saberRadius8")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[0].blade[7].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } - for ( n = 0; n < MAX_BLADES; n++ ) - { + for (n = 0; n < MAX_BLADES; n++) { NPC->client->saber[1].blade[n].radius = f; } continue; } - if ( !Q_stricmp( token, "saber2Radius2" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius2")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[1].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius3" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius3")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[2].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius4" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius4")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[3].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius5" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius5")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[4].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius6" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius6")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[5].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius7" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius7")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[6].radius = f; continue; } - if ( !Q_stricmp( token, "saber2Radius8" ) ) - { - if ( COM_ParseFloat( &p, &f ) ) - { - SkipRestOfLine( &p ); + if (!Q_stricmp(token, "saber2Radius8")) { + if (COM_ParseFloat(&p, &f)) { + SkipRestOfLine(&p); continue; } - //cap - if ( f < 0.25f ) - { + // cap + if (f < 0.25f) { f = 0.25f; } NPC->client->saber[1].blade[7].radius = f; continue; } - //ADD: - //saber sounds (on, off, loop) - //loop sound (like Vader's breathing or droid bleeps, etc.) + // ADD: + // saber sounds (on, off, loop) + // loop sound (like Vader's breathing or droid bleeps, etc.) - //starting saber style - if ( !Q_stricmp( token, "saberStyle" ) ) - { - if ( COM_ParseInt( &p, &n ) ) - { - SkipRestOfLine( &p ); + // starting saber style + if (!Q_stricmp(token, "saberStyle")) { + if (COM_ParseInt(&p, &n)) { + SkipRestOfLine(&p); continue; } - //cap - if ( n < 0 ) - { + // cap + if (n < 0) { n = 0; - } - else if ( n > 5 ) - { + } else if (n > 5) { n = 5; } NPC->client->ps.fd.saberAnimLevel = n; @@ -3486,63 +2962,54 @@ qboolean NPC_ParseParms( const char *NPCName, gentity_t *NPC ) continue; } - if ( !parsingPlayer ) - { - Com_Printf( "WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName ); + if (!parsingPlayer) { + Com_Printf("WARNING: unknown keyword '%s' while parsing '%s'\n", token, NPCName); } - SkipRestOfLine( &p ); + SkipRestOfLine(&p); } } -/* -Ghoul2 Insert Start -*/ - if ( !md3Model ) - { + /* + Ghoul2 Insert Start + */ + if (!md3Model) { qboolean setTypeBack = qfalse; - if (npcSaber1 == 0) - { //use "kyle" for a default then + if (npcSaber1 == 0) { // use "kyle" for a default then npcSaber1 = G_ModelIndex("@Kyle"); - WP_SaberParseParms( DEFAULT_SABER, &NPC->client->saber[0] ); + WP_SaberParseParms(DEFAULT_SABER, &NPC->client->saber[0]); } NPC->s.npcSaber1 = npcSaber1; NPC->s.npcSaber2 = npcSaber2; - if (!customSkin[0]) - { + if (!customSkin[0]) { strcpy(customSkin, "default"); } - if ( NPC->client && NPC->client->NPC_class == CLASS_VEHICLE ) - { //vehicles want their names fed in as models - //we put the $ in front to indicate a name and not a model + if (NPC->client && NPC->client->NPC_class == CLASS_VEHICLE) { // vehicles want their names fed in as models + // we put the $ in front to indicate a name and not a model strcpy(playerModel, va("$%s", NPCName)); } SetupGameGhoul2Model(NPC, playerModel, customSkin); - if (!NPC->NPC_type) - { //just do this for now so NPC_Precache can see the name. + if (!NPC->NPC_type) { // just do this for now so NPC_Precache can see the name. NPC->NPC_type = (char *)NPCName; setTypeBack = qtrue; } - NPC_Precache(NPC); //this will just soundindex some values for sounds on the client, + NPC_Precache(NPC); // this will just soundindex some values for sounds on the client, - if (setTypeBack) - { //don't want this being set if we aren't ready yet. + if (setTypeBack) { // don't want this being set if we aren't ready yet. NPC->NPC_type = NULL; } - } - else - { + } else { Com_Printf("MD3 MODEL NPC'S ARE NOT SUPPORTED IN MP!\n"); return qfalse; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ /* if( NPCsPrecached ) {//Spawning in after initial precache, our models are precached, we just need to set our clientInfo @@ -3551,63 +3018,58 @@ Ghoul2 Insert End CG_RegisterNPCEffects( NPC->client->playerTeam ); } */ - //rwwFIXMEFIXME: Do something here I guess to properly precache stuff. + // rwwFIXMEFIXME: Do something here I guess to properly precache stuff. return qtrue; } char npcParseBuffer[MAX_NPC_DATA_SIZE]; -void NPC_LoadParms( void ) -{ - int len, totallen, npcExtFNLen, fileCnt, i; -// const char *filename = "ext_data/NPC2.cfg"; - char /**buffer,*/ *holdChar, *marker; - char npcExtensionListBuf[2048]; // The list of file names read in +void NPC_LoadParms(void) { + int len, totallen, npcExtFNLen, fileCnt, i; + // const char *filename = "ext_data/NPC2.cfg"; + char /**buffer,*/ *holdChar, *marker; + char npcExtensionListBuf[2048]; // The list of file names read in fileHandle_t f; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = len; - marker = NPCParms+totallen; + marker = NPCParms + totallen; *marker = 0; - //now load in the extra .npc extensions - fileCnt = trap->FS_GetFileList("ext_data/NPCs", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf) ); + // now load in the extra .npc extensions + fileCnt = trap->FS_GetFileList("ext_data/NPCs", ".npc", npcExtensionListBuf, sizeof(npcExtensionListBuf)); holdChar = npcExtensionListBuf; - for ( i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1 ) - { - npcExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += npcExtFNLen + 1) { + npcExtFNLen = strlen(holdChar); -// Com_Printf( "Parsing %s\n", holdChar ); + // Com_Printf( "Parsing %s\n", holdChar ); - len = trap->FS_Open(va( "ext_data/NPCs/%s", holdChar), &f, FS_READ); + len = trap->FS_Open(va("ext_data/NPCs/%s", holdChar), &f, FS_READ); - if ( len == -1 ) - { - Com_Printf( "error reading file\n" ); - } - else - { - if ( totallen + len >= MAX_NPC_DATA_SIZE ) { - trap->FS_Close( f ); - trap->Error( ERR_DROP, "NPC extensions (*.npc) are too large" ); + if (len == -1) { + Com_Printf("error reading file\n"); + } else { + if (totallen + len >= MAX_NPC_DATA_SIZE) { + trap->FS_Close(f); + trap->Error(ERR_DROP, "NPC extensions (*.npc) are too large"); } trap->FS_Read(npcParseBuffer, len, f); npcParseBuffer[len] = 0; - len = COM_Compress( npcParseBuffer ); + len = COM_Compress(npcParseBuffer); - strcat( marker, npcParseBuffer ); + strcat(marker, npcParseBuffer); strcat(marker, "\n"); len++; trap->FS_Close(f); totallen += len; - marker = NPCParms+totallen; + marker = NPCParms + totallen; //*marker = 0; //rww - make sure this is null or strcat will not append to the correct place - //rww 12/19/02-actually the probelm was npcParseBuffer not being nul-term'd, which could cause issues in the strcat too + // rww 12/19/02-actually the probelm was npcParseBuffer not being nul-term'd, which could cause issues in the strcat too } } } diff --git a/codemp/game/NPC_utils.c b/codemp/game/NPC_utils.c index f811e75894..7908165ce1 100644 --- a/codemp/game/NPC_utils.c +++ b/codemp/game/NPC_utils.c @@ -20,18 +20,18 @@ along with this program; if not, see . =========================================================================== */ -//NPC_utils.cpp +// NPC_utils.cpp #include "b_local.h" #include "icarus/Q3_Interface.h" #include "ghoul2/G2.h" -int teamNumbers[TEAM_NUM_TEAMS]; -int teamStrength[TEAM_NUM_TEAMS]; -int teamCounter[TEAM_NUM_TEAMS]; +int teamNumbers[TEAM_NUM_TEAMS]; +int teamStrength[TEAM_NUM_TEAMS]; +int teamCounter[TEAM_NUM_TEAMS]; -#define VALID_ATTACK_CONE 2.0f //Degrees -extern void G_DebugPrint( int level, const char *format, ... ); +#define VALID_ATTACK_CONE 2.0f // Degrees +extern void G_DebugPrint(int level, const char *format, ...); /* void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) @@ -39,42 +39,36 @@ void CalcEntitySpot ( gentity_t *ent, spot_t spot, vec3_t point ) Added: Uses shootAngles if a NPC has them */ -void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) -{ - vec3_t forward, up, right; - vec3_t start, end; - trace_t tr; +void CalcEntitySpot(const gentity_t *ent, const spot_t spot, vec3_t point) { + vec3_t forward, up, right; + vec3_t start, end; + trace_t tr; - if ( !ent ) - { + if (!ent) { return; } - switch ( spot ) - { + switch (spot) { case SPOT_ORIGIN: - if(VectorCompare(ent->r.currentOrigin, vec3_origin)) - {//brush - VectorSubtract(ent->r.absmax, ent->r.absmin, point);//size + if (VectorCompare(ent->r.currentOrigin, vec3_origin)) { // brush + VectorSubtract(ent->r.absmax, ent->r.absmin, point); // size VectorMA(ent->r.absmin, 0.5, point, point); - } - else - { - VectorCopy ( ent->r.currentOrigin, point ); + } else { + VectorCopy(ent->r.currentOrigin, point); } break; case SPOT_CHEST: case SPOT_HEAD: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) /*&& (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)*/ ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && + VectorLengthSquared( + ent->client->renderInfo + .eyePoint) /*&& (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD)*/) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->r.currentOrigin[0]; point[1] = ent->r.currentOrigin[1]; } @@ -84,35 +78,30 @@ void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) SubtractLeanOfs( ent, point ); } */ - } - else - { - VectorCopy ( ent->r.currentOrigin, point ); - if ( ent->client ) - { + } else { + VectorCopy(ent->r.currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } } - if ( spot == SPOT_CHEST && ent->client ) - { - if ( ent->client->NPC_class != CLASS_ATST ) - {//adjust up some - point[2] -= ent->r.maxs[2]*0.2f; + if (spot == SPOT_CHEST && ent->client) { + if (ent->client->NPC_class != CLASS_ATST) { // adjust up some + point[2] -= ent->r.maxs[2] * 0.2f; } } break; case SPOT_HEAD_LEAN: - if ( ent->client && VectorLengthSquared( ent->client->renderInfo.eyePoint ) /*&& (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD*/ ) - {//Actual tag_head eyespot! - //FIXME: Stasis aliens may have a problem here... - VectorCopy( ent->client->renderInfo.eyePoint, point ); - if ( ent->client->NPC_class == CLASS_ATST ) - {//adjust up some - point[2] += 28;//magic number :) + if (ent->client && + VectorLengthSquared( + ent->client->renderInfo + .eyePoint) /*&& (ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD*/) { // Actual tag_head eyespot! + // FIXME: Stasis aliens may have a problem here... + VectorCopy(ent->client->renderInfo.eyePoint, point); + if (ent->client->NPC_class == CLASS_ATST) { // adjust up some + point[2] += 28; // magic number :) } - if ( ent->NPC ) - {//always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards + if (ent->NPC) { // always aim from the center of my bbox, so we don't wiggle when we lean forward or backwards point[0] = ent->r.currentOrigin[0]; point[1] = ent->r.currentOrigin[1]; } @@ -122,74 +111,65 @@ void CalcEntitySpot ( const gentity_t *ent, const spot_t spot, vec3_t point ) SubtractLeanOfs( ent, point ); } */ - //NOTE: automatically takes leaning into account! - } - else - { - VectorCopy ( ent->r.currentOrigin, point ); - if ( ent->client ) - { + // NOTE: automatically takes leaning into account! + } else { + VectorCopy(ent->r.currentOrigin, point); + if (ent->client) { point[2] += ent->client->ps.viewheight; } - //AddLeanOfs ( ent, point ); + // AddLeanOfs ( ent, point ); } break; - //FIXME: implement... - //case SPOT_CHEST: - //Returns point 3/4 from tag_torso to tag_head? - //break; + // FIXME: implement... + // case SPOT_CHEST: + // Returns point 3/4 from tag_torso to tag_head? + // break; case SPOT_LEGS: - VectorCopy ( ent->r.currentOrigin, point ); + VectorCopy(ent->r.currentOrigin, point); point[2] += (ent->r.mins[2] * 0.5); break; case SPOT_WEAPON: - if( ent->NPC && !VectorCompare( ent->NPC->shootAngles, vec3_origin ) && !VectorCompare( ent->NPC->shootAngles, ent->client->ps.viewangles )) - { - AngleVectors( ent->NPC->shootAngles, forward, right, up ); - } - else - { - AngleVectors( ent->client->ps.viewangles, forward, right, up ); + if (ent->NPC && !VectorCompare(ent->NPC->shootAngles, vec3_origin) && !VectorCompare(ent->NPC->shootAngles, ent->client->ps.viewangles)) { + AngleVectors(ent->NPC->shootAngles, forward, right, up); + } else { + AngleVectors(ent->client->ps.viewangles, forward, right, up); } - CalcMuzzlePoint( (gentity_t*)ent, forward, right, up, point ); - //NOTE: automatically takes leaning into account! + CalcMuzzlePoint((gentity_t *)ent, forward, right, up, point); + // NOTE: automatically takes leaning into account! break; case SPOT_GROUND: // if entity is on the ground, just use it's absmin - if ( ent->s.groundEntityNum != ENTITYNUM_NONE ) - { - VectorCopy( ent->r.currentOrigin, point ); + if (ent->s.groundEntityNum != ENTITYNUM_NONE) { + VectorCopy(ent->r.currentOrigin, point); point[2] = ent->r.absmin[2]; break; } // if it is reasonably close to the ground, give the point underneath of it - VectorCopy( ent->r.currentOrigin, start ); + VectorCopy(ent->r.currentOrigin, start); start[2] = ent->r.absmin[2]; - VectorCopy( start, end ); + VectorCopy(start, end); end[2] -= 64; - trap->Trace( &tr, start, ent->r.mins, ent->r.maxs, end, ent->s.number, MASK_PLAYERSOLID, qfalse, 0, 0 ); - if ( tr.fraction < 1.0 ) - { - VectorCopy( tr.endpos, point); + trap->Trace(&tr, start, ent->r.mins, ent->r.maxs, end, ent->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); + if (tr.fraction < 1.0) { + VectorCopy(tr.endpos, point); break; } // otherwise just use the origin - VectorCopy( ent->r.currentOrigin, point ); + VectorCopy(ent->r.currentOrigin, point); break; default: - VectorCopy ( ent->r.currentOrigin, point ); + VectorCopy(ent->r.currentOrigin, point); break; } } - //=================================================================================== /* @@ -201,57 +181,48 @@ Does not include "aim" in it's calculations FIXME: stop compressing angles into shorts!!!! */ -qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) -{ +qboolean NPC_UpdateAngles(qboolean doPitch, qboolean doYaw) { #if 1 - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - qboolean exact = qtrue; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the existing render flag... - dmv - if ( !NPCS.NPC->enemy && ( (level.time < NPCS.NPCInfo->aimTime) /*|| NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE*/) ) - { - if(doPitch) + // aimTime isn't even set anymore... so this code was never reached, but I need a way to lock NPC's yaw, so instead of making a new SCF_ flag, just use the + // existing render flag... - dmv + if (!NPCS.NPC->enemy && ((level.time < NPCS.NPCInfo->aimTime) /*|| NPC->client->renderInfo.renderFlags & RF_LOCKEDANGLE*/)) { + if (doPitch) targetPitch = NPCS.NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCS.NPCInfo->lockedDesiredYaw; - } - else - { + } else { // we're changing the lockedDesired Pitch/Yaw below so it's lost it's original meaning, get rid of the lock flag - // NPC->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; + // NPC->client->renderInfo.renderFlags &= ~RF_LOCKEDANGLE; - if(doPitch) - { + if (doPitch) { targetPitch = NPCS.NPCInfo->desiredPitch; NPCS.NPCInfo->lockedDesiredPitch = NPCS.NPCInfo->desiredPitch; } - if(doYaw) - { + if (doYaw) { targetYaw = NPCS.NPCInfo->desiredYaw; NPCS.NPCInfo->lockedDesiredYaw = NPCS.NPCInfo->desiredYaw; } } - if ( NPCS.NPC->s.weapon == WP_EMPLACED_GUN ) - { + if (NPCS.NPC->s.weapon == WP_EMPLACED_GUN) { // FIXME: this seems to do nothing, actually... yawSpeed = 20; - } - else - { + } else { yawSpeed = NPCS.NPCInfo->stats.yawSpeed; } - if ( NPCS.NPC->s.weapon == WP_SABER && NPCS.NPC->client->ps.fd.forcePowersActive&(1<s.weapon == WP_SABER && NPCS.NPC->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) { char buf[128]; float tFVal = 0; @@ -259,129 +230,107 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) tFVal = atof(buf); - yawSpeed *= 1.0f/tFVal; + yawSpeed *= 1.0f / tFVal; } - if( doYaw ) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPCS.NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPCS.NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - NPCS.ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - NPCS.client->ps.delta_angles[YAW]; + NPCS.ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - NPCS.client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if( doPitch ) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPCS.NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { - if ( error ) - { + error = AngleDelta(NPCS.NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0f / 1000.0f;//msec + decay *= 50.0f / 1000.0f; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - NPCS.ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - NPCS.client->ps.delta_angles[PITCH]; + NPCS.ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - NPCS.client->ps.delta_angles[PITCH]; } - NPCS.ucmd.angles[ROLL] = ANGLE2SHORT ( NPCS.NPC->client->ps.viewangles[ROLL] ) - NPCS.client->ps.delta_angles[ROLL]; + NPCS.ucmd.angles[ROLL] = ANGLE2SHORT(NPCS.NPC->client->ps.viewangles[ROLL]) - NPCS.client->ps.delta_angles[ROLL]; - if ( exact && trap->ICARUS_TaskIDPending( (sharedEntity_t *)NPCS.NPC, TID_ANGLE_FACE ) ) - { - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)NPCS.NPC, TID_ANGLE_FACE ); + if (exact && trap->ICARUS_TaskIDPending((sharedEntity_t *)NPCS.NPC, TID_ANGLE_FACE)) { + trap->ICARUS_TaskIDComplete((sharedEntity_t *)NPCS.NPC, TID_ANGLE_FACE); } return exact; #else - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; - float yawSpeed; - //float runningMod = NPCInfo->currentSpeed/100.0f; - qboolean exact = qtrue; - qboolean doSound = qfalse; + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; + float yawSpeed; + // float runningMod = NPCInfo->currentSpeed/100.0f; + qboolean exact = qtrue; + qboolean doSound = qfalse; // if angle changes are locked; just keep the current angles - if ( level.time < NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCInfo->lockedDesiredPitch = NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCInfo->lockedDesiredYaw = NPCInfo->desiredYaw; } yawSpeed = NPCInfo->stats.yawSpeed; - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPC->client->ps.viewangles[YAW], targetYaw ); - if( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[YAW], targetYaw); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) @@ -421,41 +370,33 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } else*/ - if ( error ) - { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + error ) - client->ps.delta_angles[YAW]; + ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + error) - client->ps.delta_angles[YAW]; } - //FIXME: have a pitchSpeed? - if(doPitch) - { + // FIXME: have a pitchSpeed? + if (doPitch) { // decay pitch error - error = AngleDelta ( NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( fabs(error) > MIN_ANGLE_ERROR ) - { + error = AngleDelta(NPC->client->ps.viewangles[PITCH], targetPitch); + if (fabs(error) > MIN_ANGLE_ERROR) { /* if(NPC->client->playerTeam == TEAM_BORG&& NPCInfo->behaviorState != BS_FACE&&NPCInfo->tempBehavior!= BS_FACE) @@ -495,35 +436,29 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) } else*/ - if ( error ) - { + if (error) { exact = qfalse; decay = 60.0 + yawSpeed * 3; - decay *= 50.0 / 1000.0;//msec + decay *= 50.0 / 1000.0; // msec - if ( error < 0.0 ) - { + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } } } - ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + error ) - client->ps.delta_angles[PITCH]; + ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + error) - client->ps.delta_angles[PITCH]; } - ucmd.angles[ROLL] = ANGLE2SHORT ( NPC->client->ps.viewangles[ROLL] ) - client->ps.delta_angles[ROLL]; + ucmd.angles[ROLL] = ANGLE2SHORT(NPC->client->ps.viewangles[ROLL]) - client->ps.delta_angles[ROLL]; /* if(doSound) @@ -535,23 +470,19 @@ qboolean NPC_UpdateAngles ( qboolean doPitch, qboolean doYaw ) return exact; #endif - } -void NPC_AimWiggle( vec3_t enemy_org ) -{ - //shoot for somewhere between the head and torso - //NOTE: yes, I know this looks weird, but it works - if ( NPCS.NPCInfo->aimErrorDebounceTime < level.time ) - { - NPCS.NPCInfo->aimOfs[0] = 0.3*flrand(NPCS.NPC->enemy->r.mins[0], NPCS.NPC->enemy->r.maxs[0]); - NPCS.NPCInfo->aimOfs[1] = 0.3*flrand(NPCS.NPC->enemy->r.mins[1], NPCS.NPC->enemy->r.maxs[1]); - if ( NPCS.NPC->enemy->r.maxs[2] > 0 ) - { - NPCS.NPCInfo->aimOfs[2] = NPCS.NPC->enemy->r.maxs[2]*flrand(0.0f, -1.0f); +void NPC_AimWiggle(vec3_t enemy_org) { + // shoot for somewhere between the head and torso + // NOTE: yes, I know this looks weird, but it works + if (NPCS.NPCInfo->aimErrorDebounceTime < level.time) { + NPCS.NPCInfo->aimOfs[0] = 0.3 * flrand(NPCS.NPC->enemy->r.mins[0], NPCS.NPC->enemy->r.maxs[0]); + NPCS.NPCInfo->aimOfs[1] = 0.3 * flrand(NPCS.NPC->enemy->r.mins[1], NPCS.NPC->enemy->r.maxs[1]); + if (NPCS.NPC->enemy->r.maxs[2] > 0) { + NPCS.NPCInfo->aimOfs[2] = NPCS.NPC->enemy->r.maxs[2] * flrand(0.0f, -1.0f); } } - VectorAdd( enemy_org, NPCS.NPCInfo->aimOfs, enemy_org ); + VectorAdd(enemy_org, NPCS.NPCInfo->aimOfs, enemy_org); } /* @@ -559,8 +490,7 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) Includes aim when determining angles - so they don't always hit... */ -qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) -{ +qboolean NPC_UpdateFiringAngles(qboolean doPitch, qboolean doYaw) { #if 0 float diff; @@ -627,71 +557,58 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) #else - float error, diff; - float decay; - float targetPitch = 0; - float targetYaw = 0; - qboolean exact = qtrue; + float error, diff; + float decay; + float targetPitch = 0; + float targetYaw = 0; + qboolean exact = qtrue; // if angle changes are locked; just keep the current angles - if ( level.time < NPCS.NPCInfo->aimTime ) - { - if(doPitch) + if (level.time < NPCS.NPCInfo->aimTime) { + if (doPitch) targetPitch = NPCS.NPCInfo->lockedDesiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCS.NPCInfo->lockedDesiredYaw; - } - else - { - if(doPitch) + } else { + if (doPitch) targetPitch = NPCS.NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) targetYaw = NPCS.NPCInfo->desiredYaw; -// NPCInfo->aimTime = level.time + 250; - if(doPitch) + // NPCInfo->aimTime = level.time + 250; + if (doPitch) NPCS.NPCInfo->lockedDesiredPitch = NPCS.NPCInfo->desiredPitch; - if(doYaw) + if (doYaw) NPCS.NPCInfo->lockedDesiredYaw = NPCS.NPCInfo->desiredYaw; } - if ( NPCS.NPCInfo->aimErrorDebounceTime < level.time ) - { - if ( Q_irand(0, 1 ) ) - { + if (NPCS.NPCInfo->aimErrorDebounceTime < level.time) { + if (Q_irand(0, 1)) { NPCS.NPCInfo->lastAimErrorYaw = ((float)(6 - NPCS.NPCInfo->stats.aim)) * flrand(-1, 1); } - if ( Q_irand(0, 1 ) ) - { + if (Q_irand(0, 1)) { NPCS.NPCInfo->lastAimErrorPitch = ((float)(6 - NPCS.NPCInfo->stats.aim)) * flrand(-1, 1); } NPCS.NPCInfo->aimErrorDebounceTime = level.time + Q_irand(250, 2000); } - if(doYaw) - { + if (doYaw) { // decay yaw diff - diff = AngleDelta ( NPCS.NPC->client->ps.viewangles[YAW], targetYaw ); + diff = AngleDelta(NPCS.NPC->client->ps.viewangles[YAW], targetYaw); - if ( diff) - { + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } @@ -707,32 +624,25 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) } */ - NPCS.ucmd.angles[YAW] = ANGLE2SHORT( targetYaw + diff + error ) - NPCS.client->ps.delta_angles[YAW]; + NPCS.ucmd.angles[YAW] = ANGLE2SHORT(targetYaw + diff + error) - NPCS.client->ps.delta_angles[YAW]; } - if(doPitch) - { + if (doPitch) { // decay pitch diff - diff = AngleDelta ( NPCS.NPC->client->ps.viewangles[PITCH], targetPitch ); - if ( diff) - { + diff = AngleDelta(NPCS.NPC->client->ps.viewangles[PITCH], targetPitch); + if (diff) { exact = qfalse; decay = 60.0 + 80.0; - decay *= 50.0f / 1000.0f;//msec - if ( diff < 0.0 ) - { + decay *= 50.0f / 1000.0f; // msec + if (diff < 0.0) { diff += decay; - if ( diff > 0.0 ) - { + if (diff > 0.0) { diff = 0.0; } - } - else - { + } else { diff -= decay; - if ( diff < 0.0 ) - { + if (diff < 0.0) { diff = 0.0; } } @@ -740,15 +650,14 @@ qboolean NPC_UpdateFiringAngles ( qboolean doPitch, qboolean doYaw ) error = NPCS.NPCInfo->lastAimErrorPitch; - NPCS.ucmd.angles[PITCH] = ANGLE2SHORT( targetPitch + diff + error ) - NPCS.client->ps.delta_angles[PITCH]; + NPCS.ucmd.angles[PITCH] = ANGLE2SHORT(targetPitch + diff + error) - NPCS.client->ps.delta_angles[PITCH]; } - NPCS.ucmd.angles[ROLL] = ANGLE2SHORT ( NPCS.NPC->client->ps.viewangles[ROLL] ) - NPCS.client->ps.delta_angles[ROLL]; + NPCS.ucmd.angles[ROLL] = ANGLE2SHORT(NPCS.NPC->client->ps.viewangles[ROLL]) - NPCS.client->ps.delta_angles[ROLL]; return exact; #endif - } //=================================================================================== @@ -758,40 +667,31 @@ static void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doY Does update angles on shootAngles */ -void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) -{//FIXME: shoot angles either not set right or not used! - float error; - float decay; - float targetPitch = 0; - float targetYaw = 0; +void NPC_UpdateShootAngles(vec3_t angles, qboolean doPitch, qboolean doYaw) { // FIXME: shoot angles either not set right or not used! + float error; + float decay; + float targetPitch = 0; + float targetYaw = 0; - if(doPitch) + if (doPitch) targetPitch = angles[PITCH]; - if(doYaw) + if (doYaw) targetYaw = angles[YAW]; - - if(doYaw) - { + if (doYaw) { // decay yaw error - error = AngleDelta ( NPCS.NPCInfo->shootAngles[YAW], targetYaw ); - if ( error ) - { + error = AngleDelta(NPCS.NPCInfo->shootAngles[YAW], targetYaw); + if (error) { decay = 60.0 + 80.0 * NPCS.NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -799,27 +699,20 @@ void NPC_UpdateShootAngles (vec3_t angles, qboolean doPitch, qboolean doYaw ) NPCS.NPCInfo->shootAngles[YAW] = targetYaw + error; } - if(doPitch) - { + if (doPitch) { // decay pitch error - error = AngleDelta ( NPCS.NPCInfo->shootAngles[PITCH], targetPitch ); - if ( error ) - { + error = AngleDelta(NPCS.NPCInfo->shootAngles[PITCH], targetPitch); + if (error) { decay = 60.0 + 80.0 * NPCS.NPCInfo->stats.aim; - decay *= 100.0f / 1000.0f;//msec - if ( error < 0.0 ) - { + decay *= 100.0f / 1000.0f; // msec + if (error < 0.0) { error += decay; - if ( error > 0.0 ) - { + if (error > 0.0) { error = 0.0; } - } - else - { + } else { error -= decay; - if ( error < 0.0 ) - { + if (error < 0.0) { error = 0.0; } } @@ -836,25 +729,21 @@ Sets the number of living clients on each team FIXME: Does not account for non-respawned players! FIXME: Don't include medics? */ -void SetTeamNumbers (void) -{ - gentity_t *found; - int i; +void SetTeamNumbers(void) { + gentity_t *found; + int i; - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - { + for (i = 0; i < TEAM_NUM_TEAMS; i++) { teamNumbers[i] = 0; teamStrength[i] = 0; } - //OJKFIXME: clientnum 0 - for( i = 0; i < 1 ; i++ ) - { + // OJKFIXME: clientnum 0 + for (i = 0; i < 1; i++) { found = &g_entities[i]; - if( found->client ) - { - if( found->health > 0 )//FIXME: or if a player! + if (found->client) { + if (found->health > 0) // FIXME: or if a player! { teamNumbers[found->client->playerTeam]++; teamStrength[found->client->playerTeam] += found->health; @@ -862,60 +751,50 @@ void SetTeamNumbers (void) } } - for( i = 0; i < TEAM_NUM_TEAMS; i++ ) - {//Get the average health - teamStrength[i] = floor( ((float)(teamStrength[i])) / ((float)(teamNumbers[i])) ); + for (i = 0; i < TEAM_NUM_TEAMS; i++) { // Get the average health + teamStrength[i] = floor(((float)(teamStrength[i])) / ((float)(teamNumbers[i]))); } } extern stringID_table_t BSTable[]; extern stringID_table_t BSETTable[]; -qboolean G_ActivateBehavior (gentity_t *self, int bset ) -{ - bState_t bSID = (bState_t)-1; +qboolean G_ActivateBehavior(gentity_t *self, int bset) { + bState_t bSID = (bState_t)-1; char *bs_name = NULL; - if ( !self ) - { + if (!self) { return qfalse; } bs_name = self->behaviorSet[bset]; - if( !(VALIDSTRING( bs_name )) ) - { + if (!(VALIDSTRING(bs_name))) { return qfalse; } - if ( self->NPC ) - { - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); + if (self->NPC) { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); } - if(bSID != (bState_t)-1) - { + if (bSID != (bState_t)-1) { self->NPC->tempBehavior = BS_DEFAULT; self->NPC->behaviorState = bSID; - } - else - { + } else { /* char newname[MAX_FILENAME_LENGTH]; sprintf((char *) &newname, "%s/%s", Q3_SCRIPT_DIR, bs_name ); */ - //FIXME: between here and actually getting into the ICARUS_RunScript function, the stack gets blown! - //if ( ( ICARUS_entFilter == -1 ) || ( ICARUS_entFilter == self->s.number ) ) - if (0) - { - G_DebugPrint( WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID( BSETTable, bset ), bs_name ); + // FIXME: between here and actually getting into the ICARUS_RunScript function, the stack gets blown! + // if ( ( ICARUS_entFilter == -1 ) || ( ICARUS_entFilter == self->s.number ) ) + if (0) { + G_DebugPrint(WL_VERBOSE, "%s attempting to run bSet %s (%s)\n", self->targetname, GetStringForID(BSETTable, bset), bs_name); } - trap->ICARUS_RunScript( (sharedEntity_t *)self, va( "%s/%s", Q3_SCRIPT_DIR, bs_name ) ); + trap->ICARUS_RunScript((sharedEntity_t *)self, va("%s/%s", Q3_SCRIPT_DIR, bs_name)); } return qtrue; } - /* ============================================================================= @@ -924,9 +803,8 @@ qboolean G_ActivateBehavior (gentity_t *self, int bset ) ============================================================================= */ -//rww - special system for sync'ing bone angles between client and server. -void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) -{ +// rww - special system for sync'ing bone angles between client and server. +void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) { int *thebone = &ent->s.boneIndex1; int *firstFree = NULL; int i = 0; @@ -935,23 +813,17 @@ void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) vec3_t *boneVector = &ent->s.boneAngles1; vec3_t *freeBoneVec = NULL; - while (thebone) - { - if (!*thebone && !firstFree) - { //if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. + while (thebone) { + if (!*thebone && !firstFree) { // if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. firstFree = thebone; freeBoneVec = boneVector; - } - else if (*thebone) - { - if (*thebone == boneIndex) - { //this is it + } else if (*thebone) { + if (*thebone == boneIndex) { // this is it break; } } - switch (i) - { + switch (i) { case 0: thebone = &ent->s.boneIndex2; boneVector = &ent->s.boneAngles2; @@ -973,10 +845,8 @@ void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) i++; } - if (!thebone) - { //didn't find it, create it - if (!firstFree) - { //no free bones.. can't do a thing then. + if (!thebone) { // didn't find it, create it + if (!firstFree) { // no free bones.. can't do a thing then. Com_Printf("WARNING: NPC has no free bone indexes\n"); return; } @@ -987,16 +857,15 @@ void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) boneVector = freeBoneVec; } - //If we got here then we have a vector and an index. + // If we got here then we have a vector and an index. - //Copy the angles over the vector in the entitystate, so we can use the corresponding index - //to set the bone angles on the client. + // Copy the angles over the vector in the entitystate, so we can use the corresponding index + // to set the bone angles on the client. VectorCopy(angles, *boneVector); - //Now set the angles on our server instance if we have one. + // Now set the angles on our server instance if we have one. - if (!ent->ghoul2) - { + if (!ent->ghoul2) { return; } @@ -1005,73 +874,60 @@ void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) right = NEGATIVE_Y; forward = NEGATIVE_Z; - //first 3 bits is forward, second 3 bits is right, third 3 bits is up - ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); + // first 3 bits is forward, second 3 bits is right, third 3 bits is up + ent->s.boneOrient = ((forward) | (right << 3) | (up << 6)); trap->G2API_SetBoneAngles(ent->ghoul2, 0, bone, angles, flags, up, right, forward, NULL, 100, level.time); } -//rww - and another method of automatically managing surface status for the client and server at once -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 +// rww - and another method of automatically managing surface status for the client and server at once +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 -void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags) -{ +void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags) { int i = 0; qboolean foundIt = qfalse; - while (i < BG_NUM_TOGGLEABLE_SURFACES && bgToggleableSurfaces[i]) - { - if (!Q_stricmp(surfaceName, bgToggleableSurfaces[i])) - { //got it + while (i < BG_NUM_TOGGLEABLE_SURFACES && bgToggleableSurfaces[i]) { + if (!Q_stricmp(surfaceName, bgToggleableSurfaces[i])) { // got it foundIt = qtrue; break; } i++; } - if (!foundIt) - { + if (!foundIt) { Com_Printf("WARNING: Tried to toggle NPC surface that isn't in toggleable surface list (%s)\n", surfaceName); return; } - if (surfaceFlags == TURN_ON) - { //Make sure the entitystate values reflect this surface as on now. + if (surfaceFlags == TURN_ON) { // Make sure the entitystate values reflect this surface as on now. ent->s.surfacesOn |= (1 << i); ent->s.surfacesOff &= ~(1 << i); - } - else - { //Otherwise make sure they're off. + } else { // Otherwise make sure they're off. ent->s.surfacesOn &= ~(1 << i); ent->s.surfacesOff |= (1 << i); } - if (!ent->ghoul2) - { + if (!ent->ghoul2) { return; } trap->G2API_SetSurfaceOnOff(ent->ghoul2, surfaceName, surfaceFlags); } -//rww - cheap check to see if an armed client is looking in our general direction -qboolean NPC_SomeoneLookingAtMe(gentity_t *ent) -{ +// rww - cheap check to see if an armed client is looking in our general direction +qboolean NPC_SomeoneLookingAtMe(gentity_t *ent) { int i = 0; gentity_t *pEnt; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { pEnt = &g_entities[i]; - if (pEnt && pEnt->inuse && pEnt->client && pEnt->client->sess.sessionTeam != TEAM_SPECTATOR && - pEnt->client->tempSpectate < level.time && !(pEnt->client->ps.pm_flags & PMF_FOLLOW) && pEnt->s.weapon != WP_NONE) - { - if (trap->InPVS(ent->r.currentOrigin, pEnt->r.currentOrigin)) - { - if (InFOV( ent, pEnt, 30, 30 )) - { //I'm in a 30 fov or so cone from this player.. that's enough I guess. + if (pEnt && pEnt->inuse && pEnt->client && pEnt->client->sess.sessionTeam != TEAM_SPECTATOR && pEnt->client->tempSpectate < level.time && + !(pEnt->client->ps.pm_flags & PMF_FOLLOW) && pEnt->s.weapon != WP_NONE) { + if (trap->InPVS(ent->r.currentOrigin, pEnt->r.currentOrigin)) { + if (InFOV(ent, pEnt, 30, 30)) { // I'm in a 30 fov or so cone from this player.. that's enough I guess. return qtrue; } } @@ -1083,26 +939,11 @@ qboolean NPC_SomeoneLookingAtMe(gentity_t *ent) return qfalse; } -qboolean NPC_ClearLOS( const vec3_t start, const vec3_t end ) -{ - return G_ClearLOS( NPCS.NPC, start, end ); -} -qboolean NPC_ClearLOS5( const vec3_t end ) -{ - return G_ClearLOS5( NPCS.NPC, end ); -} -qboolean NPC_ClearLOS4( gentity_t *ent ) -{ - return G_ClearLOS4( NPCS.NPC, ent ); -} -qboolean NPC_ClearLOS3( const vec3_t start, gentity_t *ent ) -{ - return G_ClearLOS3( NPCS.NPC, start, ent ); -} -qboolean NPC_ClearLOS2( gentity_t *ent, const vec3_t end ) -{ - return G_ClearLOS2( NPCS.NPC, ent, end ); -} +qboolean NPC_ClearLOS(const vec3_t start, const vec3_t end) { return G_ClearLOS(NPCS.NPC, start, end); } +qboolean NPC_ClearLOS5(const vec3_t end) { return G_ClearLOS5(NPCS.NPC, end); } +qboolean NPC_ClearLOS4(gentity_t *ent) { return G_ClearLOS4(NPCS.NPC, ent); } +qboolean NPC_ClearLOS3(const vec3_t start, gentity_t *ent) { return G_ClearLOS3(NPCS.NPC, start, ent); } +qboolean NPC_ClearLOS2(gentity_t *ent, const vec3_t end) { return G_ClearLOS2(NPCS.NPC, ent, end); } /* ------------------------- @@ -1110,98 +951,79 @@ NPC_ValidEnemy ------------------------- */ -qboolean NPC_ValidEnemy( gentity_t *ent ) -{ +qboolean NPC_ValidEnemy(gentity_t *ent) { int entTeam = TEAM_FREE; - //Must be a valid pointer - if ( ent == NULL ) + // Must be a valid pointer + if (ent == NULL) return qfalse; - //Must not be me - if ( ent == NPCS.NPC ) + // Must not be me + if (ent == NPCS.NPC) return qfalse; - //Must not be deleted - if ( ent->inuse == qfalse ) + // Must not be deleted + if (ent->inuse == qfalse) return qfalse; - //Must be alive - if ( ent->health <= 0 ) + // Must be alive + if (ent->health <= 0) return qfalse; - //In case they're in notarget mode - if ( ent->flags & FL_NOTARGET ) + // In case they're in notarget mode + if (ent->flags & FL_NOTARGET) return qfalse; - //Must be an NPC - if ( ent->client == NULL ) - { - // if ( ent->svFlags&SVF_NONNPC_ENEMY ) - if (ent->s.eType != ET_NPC) - {//still potentially valid - if ( ent->alliedTeam == NPCS.NPC->client->playerTeam ) - { + // Must be an NPC + if (ent->client == NULL) { + // if ( ent->svFlags&SVF_NONNPC_ENEMY ) + if (ent->s.eType != ET_NPC) { // still potentially valid + if (ent->alliedTeam == NPCS.NPC->client->playerTeam) { return qfalse; - } - else - { + } else { return qtrue; } - } - else - { + } else { return qfalse; } - } - else if ( ent->client && ent->client->sess.sessionTeam == TEAM_SPECTATOR ) - {//don't go after spectators + } else if (ent->client && ent->client->sess.sessionTeam == TEAM_SPECTATOR) { // don't go after spectators return qfalse; - } - else if ( ent->client && ent->client->tempSpectate >= level.time ) - {//don't go after spectators + } else if (ent->client && ent->client->tempSpectate >= level.time) { // don't go after spectators return qfalse; } - if ( ent->NPC && ent->client ) - { + if (ent->NPC && ent->client) { entTeam = ent->client->playerTeam; - } - else if ( ent->client ) - { - if (level.gametype < GT_TEAM) - { + } else if (ent->client) { + if (level.gametype < GT_TEAM) { entTeam = NPCTEAM_PLAYER; - } - else - { - if ( ent->client->sess.sessionTeam == TEAM_BLUE ) - { + } else { + if (ent->client->sess.sessionTeam == TEAM_BLUE) { entTeam = NPCTEAM_PLAYER; - } - else if ( ent->client->sess.sessionTeam == TEAM_RED ) - { + } else if (ent->client->sess.sessionTeam == TEAM_RED) { entTeam = NPCTEAM_ENEMY; - } - else - { + } else { entTeam = NPCTEAM_NEUTRAL; } } } - //Can't be on the same team - if ( ent->client->playerTeam == NPCS.NPC->client->playerTeam ) + // Can't be on the same team + if (ent->client->playerTeam == NPCS.NPC->client->playerTeam) return qfalse; - //if haven't seen him in a while, give up - //if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? + // if haven't seen him in a while, give up + // if ( NPCInfo->enemyLastSeenTime != 0 && level.time - NPCInfo->enemyLastSeenTime > 7000 )//FIXME: make a stat? // return qfalse; - if ( entTeam == NPCS.NPC->client->enemyTeam //simplest case: they're on my enemy team - || (NPCS.NPC->client->enemyTeam == NPCTEAM_FREE && ent->client->NPC_class != NPCS.NPC->client->NPC_class )//I get mad at anyone and this guy isn't the same class as me - || (ent->client->NPC_class == CLASS_WAMPA && ent->enemy )//a rampaging wampa - || (ent->client->NPC_class == CLASS_RANCOR && ent->enemy )//a rampaging rancor - || (entTeam == NPCTEAM_FREE && ent->client->enemyTeam == NPCTEAM_FREE && ent->enemy && ent->enemy->client && (ent->enemy->client->playerTeam == NPCS.NPC->client->playerTeam||(ent->enemy->client->playerTeam != NPCTEAM_ENEMY&&NPCS.NPC->client->playerTeam==NPCTEAM_PLAYER))) //enemy is a rampaging non-aligned creature who is attacking someone on our team or a non-enemy (this last condition is used only if we're a good guy - in effect, we protect the innocent) - ) - { + if (entTeam == NPCS.NPC->client->enemyTeam // simplest case: they're on my enemy team + || (NPCS.NPC->client->enemyTeam == NPCTEAM_FREE && + ent->client->NPC_class != NPCS.NPC->client->NPC_class) // I get mad at anyone and this guy isn't the same class as me + || (ent->client->NPC_class == CLASS_WAMPA && ent->enemy) // a rampaging wampa + || (ent->client->NPC_class == CLASS_RANCOR && ent->enemy) // a rampaging rancor + || (entTeam == NPCTEAM_FREE && ent->client->enemyTeam == NPCTEAM_FREE && ent->enemy && ent->enemy->client && + (ent->enemy->client->playerTeam == NPCS.NPC->client->playerTeam || + (ent->enemy->client->playerTeam != NPCTEAM_ENEMY && + NPCS.NPC->client->playerTeam == NPCTEAM_PLAYER))) // enemy is a rampaging non-aligned creature who is attacking someone on our team or a non-enemy + // (this last condition is used only if we're a good guy - in effect, we protect the innocent) + ) { return qtrue; } @@ -1214,19 +1036,18 @@ NPC_TargetVisible ------------------------- */ -qboolean NPC_TargetVisible( gentity_t *ent ) -{ +qboolean NPC_TargetVisible(gentity_t *ent) { - //Make sure we're in a valid range - if ( DistanceSquared( ent->r.currentOrigin, NPCS.NPC->r.currentOrigin ) > ( NPCS.NPCInfo->stats.visrange * NPCS.NPCInfo->stats.visrange ) ) + // Make sure we're in a valid range + if (DistanceSquared(ent->r.currentOrigin, NPCS.NPC->r.currentOrigin) > (NPCS.NPCInfo->stats.visrange * NPCS.NPCInfo->stats.visrange)) return qfalse; - //Check our FOV - if ( InFOV( ent, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov ) == qfalse ) + // Check our FOV + if (InFOV(ent, NPCS.NPC, NPCS.NPCInfo->stats.hfov, NPCS.NPCInfo->stats.vfov) == qfalse) return qfalse; - //Check for sight - if ( NPC_ClearLOS4( ent ) == qfalse ) + // Check for sight + if (NPC_ClearLOS4(ent) == qfalse) return qfalse; return qtrue; @@ -1263,51 +1084,47 @@ NPC_FindNearestEnemy ------------------------- */ -#define MAX_RADIUS_ENTS 256 //NOTE: This can cause entities to be lost -#define NEAR_DEFAULT_RADIUS 256 +#define MAX_RADIUS_ENTS 256 // NOTE: This can cause entities to be lost +#define NEAR_DEFAULT_RADIUS 256 -int NPC_FindNearestEnemy( gentity_t *ent ) -{ - int iradiusEnts[ MAX_RADIUS_ENTS ]; - gentity_t *radEnt; - vec3_t mins, maxs; - int nearestEntID = -1; - float nearestDist = (float)WORLD_SIZE*(float)WORLD_SIZE; - float distance; - int numEnts, numChecks = 0; - int i; - - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { +int NPC_FindNearestEnemy(gentity_t *ent) { + int iradiusEnts[MAX_RADIUS_ENTS]; + gentity_t *radEnt; + vec3_t mins, maxs; + int nearestEntID = -1; + float nearestDist = (float)WORLD_SIZE * (float)WORLD_SIZE; + float distance; + int numEnts, numChecks = 0; + int i; + + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = ent->r.currentOrigin[i] - NPCS.NPCInfo->stats.visrange; maxs[i] = ent->r.currentOrigin[i] + NPCS.NPCInfo->stats.visrange; } - //Get a number of entities in a given space - numEnts = trap->EntitiesInBox( mins, maxs, iradiusEnts, MAX_RADIUS_ENTS ); + // Get a number of entities in a given space + numEnts = trap->EntitiesInBox(mins, maxs, iradiusEnts, MAX_RADIUS_ENTS); - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { radEnt = &g_entities[iradiusEnts[i]]; - //Don't consider self - if ( radEnt == ent ) + // Don't consider self + if (radEnt == ent) continue; - //Must be valid - if ( NPC_ValidEnemy( radEnt ) == qfalse ) + // Must be valid + if (NPC_ValidEnemy(radEnt) == qfalse) continue; numChecks++; - //Must be visible - if ( NPC_TargetVisible( radEnt ) == qfalse ) + // Must be visible + if (NPC_TargetVisible(radEnt) == qfalse) continue; - distance = DistanceSquared( ent->r.currentOrigin, radEnt->r.currentOrigin ); + distance = DistanceSquared(ent->r.currentOrigin, radEnt->r.currentOrigin); - //Found one closer to us - if ( distance < nearestDist ) - { + // Found one closer to us + if (distance < nearestDist) { nearestEntID = radEnt->s.number; nearestDist = distance; } @@ -1322,37 +1139,33 @@ NPC_PickEnemyExt ------------------------- */ -gentity_t *NPC_PickEnemyExt( qboolean checkAlerts ) -{ - //If we've asked for the closest enemy - int entID = NPC_FindNearestEnemy( NPCS.NPC ); +gentity_t *NPC_PickEnemyExt(qboolean checkAlerts) { + // If we've asked for the closest enemy + int entID = NPC_FindNearestEnemy(NPCS.NPC); - //If we have a valid enemy, use it - if ( entID >= 0 ) + // If we have a valid enemy, use it + if (entID >= 0) return &g_entities[entID]; - if ( checkAlerts ) - { - int alertEvent = NPC_CheckAlertEvents( qtrue, qtrue, -1, qtrue, AEL_DISCOVERED ); + if (checkAlerts) { + int alertEvent = NPC_CheckAlertEvents(qtrue, qtrue, -1, qtrue, AEL_DISCOVERED); - //There is an event to look at - if ( alertEvent >= 0 ) - { + // There is an event to look at + if (alertEvent >= 0) { alertEvent_t *event = &level.alertEvents[alertEvent]; - //Don't pay attention to our own alerts - if ( event->owner == NPCS.NPC ) + // Don't pay attention to our own alerts + if (event->owner == NPCS.NPC) return NULL; - if ( event->level >= AEL_DISCOVERED ) - { - //If it's the player, attack him - //OJKFIXME: clientnum 0 - if ( event->owner == &g_entities[0] ) + if (event->level >= AEL_DISCOVERED) { + // If it's the player, attack him + // OJKFIXME: clientnum 0 + if (event->owner == &g_entities[0]) return event->owner; - //If it's on our team, then take its enemy as well - if ( ( event->owner->client ) && ( event->owner->client->playerTeam == NPCS.NPC->client->playerTeam ) ) + // If it's on our team, then take its enemy as well + if ((event->owner->client) && (event->owner->client->playerTeam == NPCS.NPC->client->playerTeam)) return event->owner->enemy; } } @@ -1367,10 +1180,9 @@ NPC_FindPlayer ------------------------- */ -qboolean NPC_FindPlayer( void ) -{ - //OJKFIXME: clientnum 0 - return NPC_TargetVisible( &g_entities[0] ); +qboolean NPC_FindPlayer(void) { + // OJKFIXME: clientnum 0 + return NPC_TargetVisible(&g_entities[0]); } /* @@ -1379,9 +1191,8 @@ NPC_CheckPlayerDistance ------------------------- */ -static qboolean NPC_CheckPlayerDistance( void ) -{ - return qfalse;//MOOT in MP +static qboolean NPC_CheckPlayerDistance(void) { + return qfalse; // MOOT in MP /* float distance; @@ -1419,56 +1230,51 @@ NPC_FindEnemy ------------------------- */ -qboolean NPC_FindEnemy( qboolean checkAlerts ) -{ +qboolean NPC_FindEnemy(qboolean checkAlerts) { gentity_t *newenemy; - //We're ignoring all enemies for now - //if( NPC->svFlags & SVF_IGNORE_ENEMIES ) - if (0) //rwwFIXMEFIXME: support for flag + // We're ignoring all enemies for now + // if( NPC->svFlags & SVF_IGNORE_ENEMIES ) + if (0) // rwwFIXMEFIXME: support for flag { - G_ClearEnemy( NPCS.NPC ); + G_ClearEnemy(NPCS.NPC); return qfalse; } - //we can't pick up any enemies for now - if( NPCS.NPCInfo->confusionTime > level.time ) - { + // we can't pick up any enemies for now + if (NPCS.NPCInfo->confusionTime > level.time) { return qfalse; } - //Don't want a new enemy - //rwwFIXMEFIXME: support for locked enemy - //if ( ( ValidEnemy( NPC->enemy ) ) && ( NPC->svFlags & SVF_LOCKEDENEMY ) ) + // Don't want a new enemy + // rwwFIXMEFIXME: support for locked enemy + // if ( ( ValidEnemy( NPC->enemy ) ) && ( NPC->svFlags & SVF_LOCKEDENEMY ) ) // return qtrue; - //See if the player is closer than our current enemy - if ( NPC_CheckPlayerDistance() ) - { + // See if the player is closer than our current enemy + if (NPC_CheckPlayerDistance()) { return qtrue; } - //Otherwise, turn off the flag -// NPC->svFlags &= ~SVF_LOCKEDENEMY; - //See if the player is closer than our current enemy - if ( NPCS.NPC->client->NPC_class != CLASS_RANCOR - && NPCS.NPC->client->NPC_class != CLASS_WAMPA + // Otherwise, turn off the flag + // NPC->svFlags &= ~SVF_LOCKEDENEMY; + // See if the player is closer than our current enemy + if (NPCS.NPC->client->NPC_class != CLASS_RANCOR && + NPCS.NPC->client->NPC_class != CLASS_WAMPA //&& NPC->client->NPC_class != CLASS_SAND_CREATURE - && NPC_CheckPlayerDistance() ) - {//rancors, wampas & sand creatures don't care if player is closer, they always go with closest + && NPC_CheckPlayerDistance()) { // rancors, wampas & sand creatures don't care if player is closer, they always go with closest return qtrue; } - //If we've gotten here alright, then our target it still valid - if ( NPC_ValidEnemy( NPCS.NPC->enemy ) ) + // If we've gotten here alright, then our target it still valid + if (NPC_ValidEnemy(NPCS.NPC->enemy)) return qtrue; - newenemy = NPC_PickEnemyExt( checkAlerts ); + newenemy = NPC_PickEnemyExt(checkAlerts); - //if we found one, take it as the enemy - if( NPC_ValidEnemy( newenemy ) ) - { - G_SetEnemy( NPCS.NPC, newenemy ); + // if we found one, take it as the enemy + if (NPC_ValidEnemy(newenemy)) { + G_SetEnemy(NPCS.NPC, newenemy); return qtrue; } @@ -1481,20 +1287,19 @@ NPC_CheckEnemyExt ------------------------- */ -qboolean NPC_CheckEnemyExt( qboolean checkAlerts ) -{ - //Make sure we're ready to think again -/* - if ( NPCInfo->enemyCheckDebounceTime > level.time ) - return qfalse; +qboolean NPC_CheckEnemyExt(qboolean checkAlerts) { + // Make sure we're ready to think again + /* + if ( NPCInfo->enemyCheckDebounceTime > level.time ) + return qfalse; - //Get our next think time - NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); + //Get our next think time + NPCInfo->enemyCheckDebounceTime = level.time + NPC_GetCheckDelta(); - //Attempt to find an enemy - return NPC_FindEnemy(); -*/ - return NPC_FindEnemy( checkAlerts ); + //Attempt to find an enemy + return NPC_FindEnemy(); + */ + return NPC_FindEnemy(checkAlerts); } /* @@ -1503,58 +1308,52 @@ NPC_FacePosition ------------------------- */ -qboolean NPC_FacePosition( vec3_t position, qboolean doPitch ) -{ - vec3_t muzzle; - vec3_t angles; - float yawDelta; - qboolean facing = qtrue; +qboolean NPC_FacePosition(vec3_t position, qboolean doPitch) { + vec3_t muzzle; + vec3_t angles; + float yawDelta; + qboolean facing = qtrue; - //Get the positions - if ( NPCS.NPC->client && (NPCS.NPC->client->NPC_class == CLASS_RANCOR || NPCS.NPC->client->NPC_class == CLASS_WAMPA) )// || NPC->client->NPC_class == CLASS_SAND_CREATURE) ) + // Get the positions + if (NPCS.NPC->client && + (NPCS.NPC->client->NPC_class == CLASS_RANCOR || NPCS.NPC->client->NPC_class == CLASS_WAMPA)) // || NPC->client->NPC_class == CLASS_SAND_CREATURE) ) { - CalcEntitySpot( NPCS.NPC, SPOT_ORIGIN, muzzle ); + CalcEntitySpot(NPCS.NPC, SPOT_ORIGIN, muzzle); muzzle[2] += NPCS.NPC->r.maxs[2] * 0.75f; - } - else if ( NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_GALAKMECH ) - { - CalcEntitySpot( NPCS.NPC, SPOT_WEAPON, muzzle ); - } - else - { - CalcEntitySpot( NPCS.NPC, SPOT_HEAD_LEAN, muzzle );//SPOT_HEAD + } else if (NPCS.NPC->client && NPCS.NPC->client->NPC_class == CLASS_GALAKMECH) { + CalcEntitySpot(NPCS.NPC, SPOT_WEAPON, muzzle); + } else { + CalcEntitySpot(NPCS.NPC, SPOT_HEAD_LEAN, muzzle); // SPOT_HEAD } - //Find the desired angles - GetAnglesForDirection( muzzle, position, angles ); + // Find the desired angles + GetAnglesForDirection(muzzle, position, angles); - NPCS.NPCInfo->desiredYaw = AngleNormalize360( angles[YAW] ); - NPCS.NPCInfo->desiredPitch = AngleNormalize360( angles[PITCH] ); + NPCS.NPCInfo->desiredYaw = AngleNormalize360(angles[YAW]); + NPCS.NPCInfo->desiredPitch = AngleNormalize360(angles[PITCH]); - if ( NPCS.NPC->enemy && NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_ATST ) - { + if (NPCS.NPC->enemy && NPCS.NPC->enemy->client && NPCS.NPC->enemy->client->NPC_class == CLASS_ATST) { // FIXME: this is kind of dumb, but it was the easiest way to get it to look sort of ok - NPCS.NPCInfo->desiredYaw += flrand( -5, 5 ) + sin( level.time * 0.004f ) * 7; - NPCS.NPCInfo->desiredPitch += flrand( -2, 2 ); + NPCS.NPCInfo->desiredYaw += flrand(-5, 5) + sin(level.time * 0.004f) * 7; + NPCS.NPCInfo->desiredPitch += flrand(-2, 2); } - //Face that yaw - NPC_UpdateAngles( qtrue, qtrue ); + // Face that yaw + NPC_UpdateAngles(qtrue, qtrue); - //Find the delta between our goal and our current facing - yawDelta = AngleNormalize360( NPCS.NPCInfo->desiredYaw - ( SHORT2ANGLE( NPCS.ucmd.angles[YAW] + NPCS.client->ps.delta_angles[YAW] ) ) ); + // Find the delta between our goal and our current facing + yawDelta = AngleNormalize360(NPCS.NPCInfo->desiredYaw - (SHORT2ANGLE(NPCS.ucmd.angles[YAW] + NPCS.client->ps.delta_angles[YAW]))); - //See if we are facing properly - if ( fabs( yawDelta ) > VALID_ATTACK_CONE ) + // See if we are facing properly + if (fabs(yawDelta) > VALID_ATTACK_CONE) facing = qfalse; - if ( doPitch ) - { - //Find the delta between our goal and our current facing - float currentAngles = ( SHORT2ANGLE( NPCS.ucmd.angles[PITCH] + NPCS.client->ps.delta_angles[PITCH] ) ); + if (doPitch) { + // Find the delta between our goal and our current facing + float currentAngles = (SHORT2ANGLE(NPCS.ucmd.angles[PITCH] + NPCS.client->ps.delta_angles[PITCH])); float pitchDelta = NPCS.NPCInfo->desiredPitch - currentAngles; - //See if we are facing properly - if ( fabs( pitchDelta ) > VALID_ATTACK_CONE ) + // See if we are facing properly + if (fabs(pitchDelta) > VALID_ATTACK_CONE) facing = qfalse; } @@ -1567,14 +1366,13 @@ NPC_FaceEntity ------------------------- */ -qboolean NPC_FaceEntity( gentity_t *ent, qboolean doPitch ) -{ - vec3_t entPos; +qboolean NPC_FaceEntity(gentity_t *ent, qboolean doPitch) { + vec3_t entPos; - //Get the positions - CalcEntitySpot( ent, SPOT_HEAD_LEAN, entPos ); + // Get the positions + CalcEntitySpot(ent, SPOT_HEAD_LEAN, entPos); - return NPC_FacePosition( entPos, doPitch ); + return NPC_FacePosition(entPos, doPitch); } /* @@ -1583,15 +1381,14 @@ NPC_FaceEnemy ------------------------- */ -qboolean NPC_FaceEnemy( qboolean doPitch ) -{ - if ( NPCS.NPC == NULL ) +qboolean NPC_FaceEnemy(qboolean doPitch) { + if (NPCS.NPC == NULL) return qfalse; - if ( NPCS.NPC->enemy == NULL ) + if (NPCS.NPC->enemy == NULL) return qfalse; - return NPC_FaceEntity( NPCS.NPC->enemy, doPitch ); + return NPC_FaceEntity(NPCS.NPC->enemy, doPitch); } /* @@ -1600,18 +1397,17 @@ NPC_CheckCanAttackExt ------------------------- */ -qboolean NPC_CheckCanAttackExt( void ) -{ - //We don't want them to shoot - if( NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE ) +qboolean NPC_CheckCanAttackExt(void) { + // We don't want them to shoot + if (NPCS.NPCInfo->scriptFlags & SCF_DONT_FIRE) return qfalse; - //Turn to face - if ( NPC_FaceEnemy( qtrue ) == qfalse ) + // Turn to face + if (NPC_FaceEnemy(qtrue) == qfalse) return qfalse; - //Must have a clear line of sight to the target - if ( NPC_ClearShot( NPCS.NPC->enemy ) == qfalse ) + // Must have a clear line of sight to the target + if (NPC_ClearShot(NPCS.NPC->enemy) == qfalse) return qfalse; return qtrue; @@ -1623,19 +1419,16 @@ NPC_ClearLookTarget ------------------------- */ -void NPC_ClearLookTarget( gentity_t *self ) -{ - if ( !self->client ) - { +void NPC_ClearLookTarget(gentity_t *self) { + if (!self->client) { return; } - if ( (self->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//lookTarget is set by and to the monster that's holding you, no other operations can change that + if ((self->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // lookTarget is set by and to the monster that's holding you, no other operations can change that return; } - self->client->renderInfo.lookTarget = ENTITYNUM_NONE;//ENTITYNUM_WORLD; + self->client->renderInfo.lookTarget = ENTITYNUM_NONE; // ENTITYNUM_WORLD; self->client->renderInfo.lookTargetClearTime = 0; } @@ -1644,15 +1437,12 @@ void NPC_ClearLookTarget( gentity_t *self ) NPC_SetLookTarget ------------------------- */ -void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) -{ - if ( !self->client ) - { +void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime) { + if (!self->client) { return; } - if ( (self->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//lookTarget is set by and to the monster that's holding you, no other operations can change that + if ((self->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // lookTarget is set by and to the monster that's holding you, no other operations can change that return; } @@ -1665,26 +1455,19 @@ void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ) NPC_CheckLookTarget ------------------------- */ -qboolean NPC_CheckLookTarget( gentity_t *self ) -{ - if ( self->client ) - { - if ( self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - {//within valid range - if ( (&g_entities[self->client->renderInfo.lookTarget] == NULL) || !g_entities[self->client->renderInfo.lookTarget].inuse ) - {//lookTarget not inuse or not valid anymore - NPC_ClearLookTarget( self ); - } - else if ( self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time ) - {//Time to clear lookTarget - NPC_ClearLookTarget( self ); - } - else if ( g_entities[self->client->renderInfo.lookTarget].client && self->enemy && (&g_entities[self->client->renderInfo.lookTarget] != self->enemy) ) - {//should always look at current enemy if engaged in battle... FIXME: this could override certain scripted lookTargets...??? - NPC_ClearLookTarget( self ); - } - else - { +qboolean NPC_CheckLookTarget(gentity_t *self) { + if (self->client) { + if (self->client->renderInfo.lookTarget >= 0 && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { // within valid range + if ((&g_entities[self->client->renderInfo.lookTarget] == NULL) || + !g_entities[self->client->renderInfo.lookTarget].inuse) { // lookTarget not inuse or not valid anymore + NPC_ClearLookTarget(self); + } else if (self->client->renderInfo.lookTargetClearTime && self->client->renderInfo.lookTargetClearTime < level.time) { // Time to clear lookTarget + NPC_ClearLookTarget(self); + } else if (g_entities[self->client->renderInfo.lookTarget].client && self->enemy && + (&g_entities[self->client->renderInfo.lookTarget] != self->enemy)) { // should always look at current enemy if engaged in battle... + // FIXME: this could override certain scripted lookTargets...??? + NPC_ClearLookTarget(self); + } else { return qtrue; } } @@ -1698,101 +1481,81 @@ qboolean NPC_CheckLookTarget( gentity_t *self ) NPC_CheckCharmed ------------------------- */ -extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); -void NPC_CheckCharmed( void ) -{ +extern void G_AddVoiceEvent(gentity_t *self, int event, int speakDebounceTime); +void NPC_CheckCharmed(void) { - if ( NPCS.NPCInfo->charmedTime && NPCS.NPCInfo->charmedTime < level.time && NPCS.NPC->client ) - {//we were charmed, set us back! - NPCS.NPC->client->playerTeam = NPCS.NPC->genericValue1; - NPCS.NPC->client->enemyTeam = NPCS.NPC->genericValue2; - NPCS.NPC->s.teamowner = NPCS.NPC->genericValue3; + if (NPCS.NPCInfo->charmedTime && NPCS.NPCInfo->charmedTime < level.time && NPCS.NPC->client) { // we were charmed, set us back! + NPCS.NPC->client->playerTeam = NPCS.NPC->genericValue1; + NPCS.NPC->client->enemyTeam = NPCS.NPC->genericValue2; + NPCS.NPC->s.teamowner = NPCS.NPC->genericValue3; NPCS.NPC->client->leader = NULL; - if ( NPCS.NPCInfo->tempBehavior == BS_FOLLOW_LEADER ) - { + if (NPCS.NPCInfo->tempBehavior == BS_FOLLOW_LEADER) { NPCS.NPCInfo->tempBehavior = BS_DEFAULT; } - G_ClearEnemy( NPCS.NPC ); + G_ClearEnemy(NPCS.NPC); NPCS.NPCInfo->charmedTime = 0; - //say something to let player know you've snapped out of it - G_AddVoiceEvent( NPCS.NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000 ); + // say something to let player know you've snapped out of it + G_AddVoiceEvent(NPCS.NPC, Q_irand(EV_CONFUSE1, EV_CONFUSE3), 2000); } } -void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex ) -{ - mdxaBone_t boltMatrix; - vec3_t result, angles; +void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex) { + mdxaBone_t boltMatrix; + vec3_t result, angles; - if (!self || !self->inuse) - { + if (!self || !self->inuse) { return; } - if (self->client) - { //clients don't actually even keep r.currentAngles maintained + if (self->client) { // clients don't actually even keep r.currentAngles maintained VectorSet(angles, 0, self->client->ps.viewangles[YAW], 0); - } - else - { + } else { VectorSet(angles, 0, self->r.currentAngles[YAW], 0); } - if ( /*!self || ...haha (sorry, i'm tired)*/ !self->ghoul2 ) - { + if (/*!self || ...haha (sorry, i'm tired)*/ !self->ghoul2) { return; } - trap->G2API_GetBoltMatrix( self->ghoul2, modelIndex, - boltIndex, - &boltMatrix, angles, self->r.currentOrigin, level.time, - NULL, self->modelScale ); - if ( pos ) - { - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, result ); - VectorCopy( result, pos ); + trap->G2API_GetBoltMatrix(self->ghoul2, modelIndex, boltIndex, &boltMatrix, angles, self->r.currentOrigin, level.time, NULL, self->modelScale); + if (pos) { + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, result); + VectorCopy(result, pos); } } -float NPC_EntRangeFromBolt( gentity_t *targEnt, int boltIndex ) -{ - vec3_t org; +float NPC_EntRangeFromBolt(gentity_t *targEnt, int boltIndex) { + vec3_t org; - if ( !targEnt ) - { + if (!targEnt) { return Q3_INFINITE; } - G_GetBoltPosition( NPCS.NPC, boltIndex, org, 0 ); + G_GetBoltPosition(NPCS.NPC, boltIndex, org, 0); - return (Distance( targEnt->r.currentOrigin, org )); + return (Distance(targEnt->r.currentOrigin, org)); } -float NPC_EnemyRangeFromBolt( int boltIndex ) -{ - return (NPC_EntRangeFromBolt( NPCS.NPC->enemy, boltIndex )); -} +float NPC_EnemyRangeFromBolt(int boltIndex) { return (NPC_EntRangeFromBolt(NPCS.NPC->enemy, boltIndex)); } -int NPC_GetEntsNearBolt( int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg ) -{ - vec3_t mins, maxs; - int i; +int NPC_GetEntsNearBolt(int *radiusEnts, float radius, int boltIndex, vec3_t boltOrg) { + vec3_t mins, maxs; + int i; - //get my handRBolt's position - vec3_t org; + // get my handRBolt's position + vec3_t org; - G_GetBoltPosition( NPCS.NPC, boltIndex, org, 0 ); + G_GetBoltPosition(NPCS.NPC, boltIndex, org, 0); - VectorCopy( org, boltOrg ); + VectorCopy(org, boltOrg); - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = boltOrg[i] - radius; maxs[i] = boltOrg[i] + radius; } - //Get the number of entities in a given space - return (trap->EntitiesInBox( mins, maxs, radiusEnts, 128 )); + // Get the number of entities in a given space + return (trap->EntitiesInBox(mins, maxs, radiusEnts, 128)); } diff --git a/codemp/game/SpeederNPC.c b/codemp/game/SpeederNPC.c index dc66ef3c61..c0a8df188b 100644 --- a/codemp/game/SpeederNPC.c +++ b/codemp/game/SpeederNPC.c @@ -20,50 +20,44 @@ along with this program; if not, see . =========================================================================== */ -#ifdef _GAME //including game headers on cgame is FORBIDDEN ^_^ - #include "g_local.h" +#ifdef _GAME // including game headers on cgame is FORBIDDEN ^_^ +#include "g_local.h" #endif #include "bg_public.h" #include "bg_vehicles.h" -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); -#ifdef _GAME //SP or gameside MP - extern vec3_t playerMins; - extern vec3_t playerMaxs; - extern void ChangeWeapon( gentity_t *ent, int newWeapon ); - extern int PM_AnimLength( int index, animNumber_t anim ); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); +#ifdef _GAME // SP or gameside MP +extern vec3_t playerMins; +extern vec3_t playerMaxs; +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +extern int PM_AnimLength(int index, animNumber_t anim); #endif -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags); extern int BG_GetTime(void); -extern qboolean BG_SabersOff( playerState_t *ps ); +extern qboolean BG_SabersOff(playerState_t *ps); -//Alright, actually, most of this file is shared between game and cgame for MP. -//I would like to keep it this way, so when modifying for SP please keep in -//mind the bgEntity restrictions imposed. -rww +// Alright, actually, most of this file is shared between game and cgame for MP. +// I would like to keep it this way, so when modifying for SP please keep in +// mind the bgEntity restrictions imposed. -rww -#define STRAFERAM_DURATION 8 -#define STRAFERAM_ANGLE 8 +#define STRAFERAM_DURATION 8 +#define STRAFERAM_ANGLE 8 -qboolean VEH_StartStrafeRam(Vehicle_t *pVeh, qboolean Right, int Duration) -{ - return qfalse; -} +qboolean VEH_StartStrafeRam(Vehicle_t *pVeh, qboolean Right, int Duration) { return qfalse; } -#ifdef _GAME //game-only.. for now +#ifdef _GAME // game-only.. for now // Like a think or move command, this updates various vehicle properties. -qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Update( pVeh, pUcmd ) ) - { +qboolean Update(Vehicle_t *pVeh, const usercmd_t *pUcmd) { + if (!g_vehicleInfo[VEHICLE_BASE].Update(pVeh, pUcmd)) { return qfalse; } // See whether this vehicle should be exploding. - if ( pVeh->m_iDieTime != 0 ) - { - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + if (pVeh->m_iDieTime != 0) { + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); } // Update move direction. @@ -72,43 +66,36 @@ qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) } #endif //_GAME -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations + // Client sets ucmds and such for speed alterations float speedInc, speedIdleDec, speedIdle, speedMin, speedMax; playerState_t *parentPS; -// playerState_t *pilotPS = NULL; - int curTime; + // playerState_t *pilotPS = NULL; + int curTime; parentPS = pVeh->m_pParentEntity->playerState; - if (pVeh->m_pPilot) - { - // pilotPS = pVeh->m_pPilot->playerState; + if (pVeh->m_pPilot) { + // pilotPS = pVeh->m_pPilot->playerState; } // If we're flying, make us accelerate at 40% (about half) acceleration rate, and restore the pitch // to origin (straight) position (at 5% increments). - if ( pVeh->m_ulFlags & VEH_FLYING ) - { + if (pVeh->m_ulFlags & VEH_FLYING) { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier * 0.4f; - } - else if ( !parentPS->m_iVehicleNum ) - {//drifts to a stop + } else if (!parentPS->m_iVehicleNum) { // drifts to a stop speedInc = 0; - //pVeh->m_ucmd.forwardmove = 127; - } - else - { + // pVeh->m_ucmd.forwardmove = 127; + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } speedIdleDec = pVeh->m_pVehicleInfo->decelIdle * pVeh->m_fTimeModifier; @@ -116,42 +103,35 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) #ifdef _GAME curTime = level.time; #elif _CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif - - if ( (pVeh->m_pPilot /*&& (pilotPS->weapon == WP_NONE || pilotPS->weapon == WP_MELEE )*/ && (pVeh->m_ucmd.buttons & BUTTON_ALT_ATTACK) && pVeh->m_pVehicleInfo->turboSpeed) /*|| (parentPS && parentPS->electrifyTime > curTime && pVeh->m_pVehicleInfo->turboSpeed)*/ //make them go! ) { - if ( (parentPS && parentPS->electrifyTime > curTime) || - (pVeh->m_pPilot->playerState && - (pVeh->m_pPilot->playerState->weapon == WP_MELEE || - (pVeh->m_pPilot->playerState->weapon == WP_SABER && BG_SabersOff( pVeh->m_pPilot->playerState ) ))) ) - { - if ((curTime - pVeh->m_iTurboTime)>pVeh->m_pVehicleInfo->turboRecharge) - { + if ((parentPS && parentPS->electrifyTime > curTime) || + (pVeh->m_pPilot->playerState && (pVeh->m_pPilot->playerState->weapon == WP_MELEE || + (pVeh->m_pPilot->playerState->weapon == WP_SABER && BG_SabersOff(pVeh->m_pPilot->playerState))))) { + if ((curTime - pVeh->m_iTurboTime) > pVeh->m_pVehicleInfo->turboRecharge) { pVeh->m_iTurboTime = (curTime + pVeh->m_pVehicleInfo->turboDuration); - if (pVeh->m_pVehicleInfo->iTurboStartFX) - { + if (pVeh->m_pVehicleInfo->iTurboStartFX) { int i; - for (i=0; (im_iExhaustTag[i]!=-1); i++) - { + for (i = 0; (i < MAX_VEHICLE_EXHAUSTS && pVeh->m_iExhaustTag[i] != -1); i++) { #ifdef _GAME - if (pVeh->m_pParentEntity && - pVeh->m_pParentEntity->ghoul2 && - pVeh->m_pParentEntity->playerState) - { //fine, I'll use a tempent for this, but only because it's played only once at the start of a turbo. + if (pVeh->m_pParentEntity && pVeh->m_pParentEntity->ghoul2 && + pVeh->m_pParentEntity + ->playerState) { // fine, I'll use a tempent for this, but only because it's played only once at the start of a turbo. vec3_t boltOrg, boltDir; mdxaBone_t boltMatrix; VectorSet(boltDir, 0.0f, pVeh->m_pParentEntity->playerState->viewangles[YAW], 0.0f); - trap->G2API_GetBoltMatrix(pVeh->m_pParentEntity->ghoul2, 0, pVeh->m_iExhaustTag[i], &boltMatrix, boltDir, pVeh->m_pParentEntity->playerState->origin, level.time, NULL, pVeh->m_pParentEntity->modelScale); + trap->G2API_GetBoltMatrix(pVeh->m_pParentEntity->ghoul2, 0, pVeh->m_iExhaustTag[i], &boltMatrix, boltDir, + pVeh->m_pParentEntity->playerState->origin, level.time, NULL, pVeh->m_pParentEntity->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrg); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltDir); G_PlayEffectID(pVeh->m_pVehicleInfo->iTurboStartFX, boltOrg, boltDir); @@ -159,128 +139,92 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) #endif } } - parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed + parentPS->speed = pVeh->m_pVehicleInfo->turboSpeed; // Instantly Jump To Turbo Speed } } } // Slide Breaking - if (pVeh->m_ulFlags&VEH_SLIDEBREAKING) - { - if (pVeh->m_ucmd.forwardmove>=0 ) - { + if (pVeh->m_ulFlags & VEH_SLIDEBREAKING) { + if (pVeh->m_ucmd.forwardmove >= 0) { pVeh->m_ulFlags &= ~VEH_SLIDEBREAKING; } parentPS->speed = 0; - } - else if ( - (curTime > pVeh->m_iTurboTime) && - !(pVeh->m_ulFlags&VEH_FLYING) && - pVeh->m_ucmd.forwardmove<0 && - fabs(pVeh->m_vOrientation[ROLL])>25.0f) - { + } else if ((curTime > pVeh->m_iTurboTime) && !(pVeh->m_ulFlags & VEH_FLYING) && pVeh->m_ucmd.forwardmove < 0 && fabs(pVeh->m_vOrientation[ROLL]) > 25.0f) { pVeh->m_ulFlags |= VEH_SLIDEBREAKING; } - - if ( curTime < pVeh->m_iTurboTime ) - { + if (curTime < pVeh->m_iTurboTime) { speedMax = pVeh->m_pVehicleInfo->turboSpeed; - if (parentPS) - { + if (parentPS) { parentPS->eFlags |= EF_JETPACK_ACTIVE; } - } - else - { + } else { speedMax = pVeh->m_pVehicleInfo->speedMax; - if (parentPS) - { + if (parentPS) { parentPS->eFlags &= ~EF_JETPACK_ACTIVE; } } - speedIdle = pVeh->m_pVehicleInfo->speedIdle; speedMin = pVeh->m_pVehicleInfo->speedMin; - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( !pVeh->m_pVehicleInfo->strafePerc || (0 && pVeh->m_pParentEntity->s.number < MAX_CLIENTS) ) - {//if in a strafe-capable vehicle, clear strafing unless using alternate control scheme - //pVeh->m_ucmd.rightmove = 0; + } else { + if (!pVeh->m_pVehicleInfo->strafePerc || + (0 && pVeh->m_pParentEntity->s.number < MAX_CLIENTS)) { // if in a strafe-capable vehicle, clear strafing unless using alternate control scheme + // pVeh->m_ucmd.rightmove = 0; } } - if ( parentPS->speed > speedMax ) - { + if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } - if (parentPS && parentPS->electrifyTime > curTime) - { - parentPS->speed *= (pVeh->m_fTimeModifier/60.0f); + if (parentPS && parentPS->electrifyTime > curTime) { + parentPS->speed *= (pVeh->m_fTimeModifier / 60.0f); } - /********************************************************************************/ /* END Here is where we move the vehicle (forward or back or whatever). END */ /********************************************************************************/ } -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -//Oh, and please, use "< MAX_CLIENTS" to check for "player" and not +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// Oh, and please, use "< MAX_CLIENTS" to check for "player" and not //"!s.number", this is a universal check that will work for both SP -//and MP. -rww -// ProcessOrientCommands the Vehicle. +// and MP. -rww +// ProcessOrientCommands the Vehicle. extern void AnimalProcessOri(Vehicle_t *pVeh); -void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -289,40 +233,31 @@ void ProcessOrientCommands( Vehicle_t *pVeh ) float angDif; - if (pVeh->m_pPilot) - { + if (pVeh->m_pPilot) { riderPS = pVeh->m_pPilot->playerState; - } - else - { + } else { riderPS = pVeh->m_pParentEntity->playerState; } parentPS = pVeh->m_pParentEntity->playerState; - //pVeh->m_vOrientation[YAW] = 0.0f;//riderPS->viewangles[YAW]; + // pVeh->m_vOrientation[YAW] = 0.0f;//riderPS->viewangles[YAW]; angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*4.0f; //magic number hackery - if (s < 0.0f) - { + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 4.0f; // magic number hackery + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); - if (parentPS->electrifyTime > pm->cmd.serverTime) - { //do some crazy stuff - pVeh->m_vOrientation[YAW] += (sin(pm->cmd.serverTime/1000.0f)*3.0f)*pVeh->m_fTimeModifier; + if (parentPS->electrifyTime > pm->cmd.serverTime) { // do some crazy stuff + pVeh->m_vOrientation[YAW] += (sin(pm->cmd.serverTime / 1000.0f) * 3.0f) * pVeh->m_fTimeModifier; } } @@ -333,69 +268,53 @@ void ProcessOrientCommands( Vehicle_t *pVeh ) #ifdef _GAME -extern int PM_AnimLength( int index, animNumber_t anim ); +extern int PM_AnimLength(int index, animNumber_t anim); // This function makes sure that the vehicle is properly animated. -void AnimateVehicle( Vehicle_t *pVeh ) -{ -} +void AnimateVehicle(Vehicle_t *pVeh) {} #endif //_GAME -//rest of file is shared +// rest of file is shared -//NOTE NOTE NOTE NOTE NOTE NOTE -//I want to keep this function BG too, because it's fairly generic already, and it -//would be nice to have proper prediction of animations. -rww -// This function makes sure that the rider's in this vehicle are properly animated. -void AnimateRiders( Vehicle_t *pVeh ) -{ +// NOTE NOTE NOTE NOTE NOTE NOTE +// I want to keep this function BG too, because it's fairly generic already, and it +// would be nice to have proper prediction of animations. -rww +// This function makes sure that the rider's in this vehicle are properly animated. +void AnimateRiders(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_VS_IDLE; int iFlags = SETANIM_FLAG_NORMAL; playerState_t *pilotPS; int curTime; - // Boarding animation. - if ( pVeh->m_iBoarding != 0 ) - { + if (pVeh->m_iBoarding != 0) { // We've just started moarding, set the amount of time it will take to finish moarding. - if ( pVeh->m_iBoarding < 0 ) - { + if (pVeh->m_iBoarding < 0) { int iAnimLen; // Boarding from left... - if ( pVeh->m_iBoarding == -1 ) - { + if (pVeh->m_iBoarding == -1) { Anim = BOTH_VS_MOUNT_L; - } - else if ( pVeh->m_iBoarding == -2 ) - { + } else if (pVeh->m_iBoarding == -2) { Anim = BOTH_VS_MOUNT_R; - } - else if ( pVeh->m_iBoarding == -3 ) - { + } else if (pVeh->m_iBoarding == -3) { Anim = BOTH_VS_MOUNTJUMP_L; - } - else if ( pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT) - { + } else if (pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT) { Anim = BOTH_VS_MOUNTTHROW_R; - } - else if ( pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT) - { + } else if (pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT) { Anim = BOTH_VS_MOUNTTHROW_L; } // Set the delay time (which happens to be the time it takes for the animation to complete). // NOTE: Here I made it so the delay is actually 40% (0.4f) of the animation time. - iAnimLen = BG_AnimLength( pVeh->m_pPilot->localAnimIndex, Anim ) * 0.4f; + iAnimLen = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim) * 0.4f; pVeh->m_iBoarding = BG_GetTime() + iAnimLen; // Set the animation, which won't be interrupted until it's completed. // TODO: But what if he's killed? Should the animation remain persistant??? iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, - SETANIM_BOTH, Anim, iFlags); + BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags); } return; @@ -409,248 +328,269 @@ void AnimateRiders( Vehicle_t *pVeh ) #ifdef _GAME curTime = level.time; #elif _CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif // Going in reverse... - if ( pVeh->m_ucmd.forwardmove < 0 && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) - { + if (pVeh->m_ucmd.forwardmove < 0 && !(pVeh->m_ulFlags & VEH_SLIDEBREAKING)) { Anim = BOTH_VS_REV; - } - else - { - qboolean HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); - qboolean Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons&BUTTON_ATTACK)); - qboolean Flying = qfalse; - qboolean Crashing = qfalse; - qboolean Right = (pVeh->m_ucmd.rightmove>0); - qboolean Left = (pVeh->m_ucmd.rightmove<0); - qboolean Turbo = (curTimem_iTurboTime); - EWeaponPose WeaponPose = WPOSE_NONE; - + } else { + qboolean HasWeapon = ((pilotPS->weapon != WP_NONE) && (pilotPS->weapon != WP_MELEE)); + qboolean Attacking = (HasWeapon && !!(pVeh->m_ucmd.buttons & BUTTON_ATTACK)); + qboolean Flying = qfalse; + qboolean Crashing = qfalse; + qboolean Right = (pVeh->m_ucmd.rightmove > 0); + qboolean Left = (pVeh->m_ucmd.rightmove < 0); + qboolean Turbo = (curTime < pVeh->m_iTurboTime); + EWeaponPose WeaponPose = WPOSE_NONE; // Remove Crashing Flag //---------------------- pVeh->m_ulFlags &= ~VEH_CRASHING; - // Put Away Saber When It Is Not Active //-------------------------------------- // Don't Interrupt Attack Anims //------------------------------ - if (pilotPS->weaponTime>0) - { + if (pilotPS->weaponTime > 0) { return; } // Compute The Weapon Pose //-------------------------- - if (pilotPS->weapon==WP_BLASTER) - { + if (pilotPS->weapon == WP_BLASTER) { WeaponPose = WPOSE_BLASTER; - } - else if (pilotPS->weapon==WP_SABER) - { - if ( (pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VS_ATL_TO_R_S) - { - pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; + } else if (pilotPS->weapon == WP_SABER) { + if ((pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VS_ATL_TO_R_S) { + pVeh->m_ulFlags &= ~VEH_SABERINLEFTHAND; } - if (!(pVeh->m_ulFlags&VEH_SABERINLEFTHAND) && pilotPS->torsoAnim==BOTH_VS_ATR_TO_L_S) - { - pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; + if (!(pVeh->m_ulFlags & VEH_SABERINLEFTHAND) && pilotPS->torsoAnim == BOTH_VS_ATR_TO_L_S) { + pVeh->m_ulFlags |= VEH_SABERINLEFTHAND; } - WeaponPose = (pVeh->m_ulFlags&VEH_SABERINLEFTHAND)?(WPOSE_SABERLEFT):(WPOSE_SABERRIGHT); + WeaponPose = (pVeh->m_ulFlags & VEH_SABERINLEFTHAND) ? (WPOSE_SABERLEFT) : (WPOSE_SABERRIGHT); } - - if (Attacking && WeaponPose) - {// Attack! - iFlags = SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART; + if (Attacking && WeaponPose) { // Attack! + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART; // Auto Aiming //=============================================== - if (!Left && !Right) // Allow player strafe keys to override + if (!Left && !Right) // Allow player strafe keys to override { - if (pilotPS->weapon==WP_SABER && !Left && !Right) - { - Left = (WeaponPose==WPOSE_SABERLEFT); - Right = !Left; + if (pilotPS->weapon == WP_SABER && !Left && !Right) { + Left = (WeaponPose == WPOSE_SABERLEFT); + Right = !Left; } } - - if (Left) - {// Attack Left - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_ATL_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_ATR_TO_L_S; break; - default: assert(0); + if (Left) { // Attack Left + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_ATL_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_ATR_TO_L_S; + break; + default: + assert(0); } - } - else if (Right) - {// Attack Right - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_ATL_TO_R_S; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_ATR_S; break; - default: assert(0); + } else if (Right) { // Attack Right + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_ATL_TO_R_S; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_ATR_S; + break; + default: + assert(0); } - } - else - {// Attack Ahead - switch(WeaponPose) - { - case WPOSE_BLASTER: Anim = BOTH_VS_ATF_G; break; - default: assert(0); + } else { // Attack Ahead + switch (WeaponPose) { + case WPOSE_BLASTER: + Anim = BOTH_VS_ATF_G; + break; + default: + assert(0); } } - } - else if (Left && pVeh->m_ucmd.buttons&BUTTON_USE) - {// Look To The Left Behind - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: Anim = BOTH_VS_LOOKLEFT; + } else if (Left && pVeh->m_ucmd.buttons & BUTTON_USE) { // Look To The Left Behind + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + switch (WeaponPose) { + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + Anim = BOTH_VS_LOOKLEFT; } - } - else if (Right && pVeh->m_ucmd.buttons&BUTTON_USE) - {// Look To The Right Behind - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: Anim = BOTH_VS_LOOKRIGHT; + } else if (Right && pVeh->m_ucmd.buttons & BUTTON_USE) { // Look To The Right Behind + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + switch (WeaponPose) { + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + Anim = BOTH_VS_LOOKRIGHT; } - } - else if (Turbo) - {// Kicked In Turbo - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - Anim = BOTH_VS_TURBO; - } - else if (Flying) - {// Off the ground in a jump - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + } else if (Turbo) { // Kicked In Turbo + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + Anim = BOTH_VS_TURBO; + } else if (Flying) { // Off the ground in a jump + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_AIR; break; - case WPOSE_BLASTER: Anim = BOTH_VS_AIR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_AIR_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_AIR_SR; break; - default: assert(0); + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_AIR; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_AIR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_AIR_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_AIR_SR; + break; + default: + assert(0); } - } - else if (Crashing) - {// Hit the ground! - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LAND; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LAND_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LAND_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LAND_SR; break; - default: assert(0); + } else if (Crashing) { // Hit the ground! + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LAND; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LAND_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LAND_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LAND_SR; + break; + default: + assert(0); } - } - else - {// No Special Moves - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; - - if (pVeh->m_vOrientation[ROLL] <= -20) - {// Lean Left - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LEANL; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LEANL_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LEANL_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LEANL_SR; break; - default: assert(0); + } else { // No Special Moves + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLDLESS; + + if (pVeh->m_vOrientation[ROLL] <= -20) { // Lean Left + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LEANL; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LEANL_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LEANL_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LEANL_SR; + break; + default: + assert(0); } - } - else if (pVeh->m_vOrientation[ROLL] >= 20) - {// Lean Right - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_LEANR; break; - case WPOSE_BLASTER: Anim = BOTH_VS_LEANR_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_LEANR_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_LEANR_SR; break; - default: assert(0); + } else if (pVeh->m_vOrientation[ROLL] >= 20) { // Lean Right + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_LEANR; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_LEANR_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_LEANR_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_LEANR_SR; + break; + default: + assert(0); } - } - else - {// No Lean - switch(WeaponPose) - { - case WPOSE_NONE: Anim = BOTH_VS_IDLE; break; - case WPOSE_BLASTER: Anim = BOTH_VS_IDLE_G; break; - case WPOSE_SABERLEFT: Anim = BOTH_VS_IDLE_SL; break; - case WPOSE_SABERRIGHT: Anim = BOTH_VS_IDLE_SR; break; - default: assert(0); + } else { // No Lean + switch (WeaponPose) { + case WPOSE_NONE: + Anim = BOTH_VS_IDLE; + break; + case WPOSE_BLASTER: + Anim = BOTH_VS_IDLE_G; + break; + case WPOSE_SABERLEFT: + Anim = BOTH_VS_IDLE_SL; + break; + case WPOSE_SABERRIGHT: + Anim = BOTH_VS_IDLE_SR; + break; + default: + assert(0); } } - }// No Special Moves - }// Going backwards? + } // No Special Moves + } // Going backwards? iFlags &= ~SETANIM_FLAG_OVERRIDE; - if (pVeh->m_pPilot->playerState->torsoAnim == Anim) - { + if (pVeh->m_pPilot->playerState->torsoAnim == Anim) { pVeh->m_pPilot->playerState->torsoTimer = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim); } - if (pVeh->m_pPilot->playerState->legsAnim == Anim) - { + if (pVeh->m_pPilot->playerState->legsAnim == Anim) { pVeh->m_pPilot->playerState->legsTimer = BG_AnimLength(pVeh->m_pPilot->localAnimIndex, Anim); } - BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, - SETANIM_BOTH, Anim, iFlags|SETANIM_FLAG_HOLD); + BG_SetAnim(pVeh->m_pPilot->playerState, bgAllAnims[pVeh->m_pPilot->localAnimIndex].anims, SETANIM_BOTH, Anim, iFlags | SETANIM_FLAG_HOLD); } #ifndef _GAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -void G_SetSpeederVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +void G_SetSpeederVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef _GAME - pVehInfo->AnimateVehicle = AnimateVehicle; - pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; -// pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; -// pVehInfo->RegisterAssets = RegisterAssets; -// pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; + pVehInfo->AnimateVehicle = AnimateVehicle; + pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + // pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + // pVehInfo->RegisterAssets = RegisterAssets; + // pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; #endif - //shared - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + // shared + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef _GAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef _GAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -659,21 +599,18 @@ void G_SetSpeederVehicleFunctions( vehicleInfo_t *pVehInfo ) extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif - // Create/Allocate a new Animal Vehicle (initializing it as well). -void G_CreateSpeederNPC( Vehicle_t **pVeh, const char *strType ) -{ +void G_CreateSpeederNPC(Vehicle_t **pVeh, const char *strType) { #ifdef _GAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strType)]; } diff --git a/codemp/game/WalkerNPC.c b/codemp/game/WalkerNPC.c index a611718b0f..73741c8a66 100644 --- a/codemp/game/WalkerNPC.c +++ b/codemp/game/WalkerNPC.c @@ -20,30 +20,29 @@ along with this program; if not, see . =========================================================================== */ -#ifdef _GAME //including game headers on cgame is FORBIDDEN ^_^ +#ifdef _GAME // including game headers on cgame is FORBIDDEN ^_^ #include "g_local.h" #endif #include "bg_public.h" #include "bg_vehicles.h" -#ifdef _GAME //we only want a few of these functions for BG +#ifdef _GAME // we only want a few of these functions for BG -extern float DotToSpot( vec3_t spot, vec3_t from, vec3_t fromAngles ); +extern float DotToSpot(vec3_t spot, vec3_t from, vec3_t fromAngles); extern vec3_t playerMins; extern vec3_t playerMaxs; -extern int PM_AnimLength( int index, animNumber_t anim ); -extern void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend); -extern void G_Knockdown( gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock ); -extern void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ); +extern int PM_AnimLength(int index, animNumber_t anim); +extern void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend); +extern void G_Knockdown(gentity_t *self, gentity_t *attacker, const vec3_t pushDir, float strength, qboolean breakSaberLock); +extern void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask); -static void RegisterAssets( Vehicle_t *pVeh ) -{ - //atst uses turret weapon +static void RegisterAssets(Vehicle_t *pVeh) { + // atst uses turret weapon RegisterItem(BG_FindItemForWeapon(WP_TURRET)); - //call the standard RegisterAssets now - g_vehicleInfo[VEHICLE_BASE].RegisterAssets( pVeh ); + // call the standard RegisterAssets now + g_vehicleInfo[VEHICLE_BASE].RegisterAssets(pVeh); } // Like a think or move command, this updates various vehicle properties. @@ -55,9 +54,8 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUcmd ) */ // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -static qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ - if ( !g_vehicleInfo[VEHICLE_BASE].Board( pVeh, pEnt ) ) +static qboolean Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { + if (!g_vehicleInfo[VEHICLE_BASE].Board(pVeh, pEnt)) return qfalse; // Set the board wait time (they won't be able to do anything, including getting off, for this amount of time). @@ -67,21 +65,19 @@ static qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) } #endif //_GAME - -//MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessMoveCommands the Vehicle. -static void ProcessMoveCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSMOVECOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessMoveCommands the Vehicle. +static void ProcessMoveCommands(Vehicle_t *pVeh) { /************************************************************************************/ /* BEGIN Here is where we move the vehicle (forward or back or whatever). BEGIN */ /************************************************************************************/ - //Client sets ucmds and such for speed alterations + // Client sets ucmds and such for speed alterations float speedInc, speedIdleDec, speedIdle, speedMin, speedMax; float fWalkSpeedMax; bgEntity_t *parent = pVeh->m_pParentEntity; @@ -93,62 +89,42 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) speedIdle = pVeh->m_pVehicleInfo->speedIdle; speedMin = pVeh->m_pVehicleInfo->speedMin; - if ( !parentPS->m_iVehicleNum ) - {//drifts to a stop + if (!parentPS->m_iVehicleNum) { // drifts to a stop speedInc = speedIdle * pVeh->m_fTimeModifier; - VectorClear( parentPS->moveDir ); - //m_ucmd.forwardmove = 127; + VectorClear(parentPS->moveDir); + // m_ucmd.forwardmove = 127; parentPS->speed = 0; - } - else - { + } else { speedInc = pVeh->m_pVehicleInfo->acceleration * pVeh->m_fTimeModifier; } - if ( parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || - pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0 ) - { - if ( pVeh->m_ucmd.forwardmove > 0 && speedInc ) - { + if (parentPS->speed || parentPS->groundEntityNum == ENTITYNUM_NONE || pVeh->m_ucmd.forwardmove || pVeh->m_ucmd.upmove > 0) { + if (pVeh->m_ucmd.forwardmove > 0 && speedInc) { parentPS->speed += speedInc; - } - else if ( pVeh->m_ucmd.forwardmove < 0 ) - { - if ( parentPS->speed > speedIdle ) - { + } else if (pVeh->m_ucmd.forwardmove < 0) { + if (parentPS->speed > speedIdle) { parentPS->speed -= speedInc; - } - else if ( parentPS->speed > speedMin ) - { + } else if (parentPS->speed > speedMin) { parentPS->speed -= speedIdleDec; } } // No input, so coast to stop. - else if ( parentPS->speed > 0.0f ) - { + else if (parentPS->speed > 0.0f) { parentPS->speed -= speedIdleDec; - if ( parentPS->speed < 0.0f ) - { + if (parentPS->speed < 0.0f) { parentPS->speed = 0.0f; } - } - else if ( parentPS->speed < 0.0f ) - { + } else if (parentPS->speed < 0.0f) { parentPS->speed += speedIdleDec; - if ( parentPS->speed > 0.0f ) - { + if (parentPS->speed > 0.0f) { parentPS->speed = 0.0f; } } - } - else - { - if ( pVeh->m_ucmd.forwardmove < 0 ) - { + } else { + if (pVeh->m_ucmd.forwardmove < 0) { pVeh->m_ucmd.forwardmove = 0; } - if ( pVeh->m_ucmd.upmove < 0 ) - { + if (pVeh->m_ucmd.upmove < 0) { pVeh->m_ucmd.upmove = 0; } @@ -161,27 +137,20 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) }*/ } - if (parentPS && parentPS->electrifyTime > pm->cmd.serverTime) - { + if (parentPS && parentPS->electrifyTime > pm->cmd.serverTime) { speedMax *= 0.5f; } fWalkSpeedMax = speedMax * 0.275f; - if ( pVeh->m_ucmd.buttons & BUTTON_WALKING && parentPS->speed > fWalkSpeedMax ) - { + if (pVeh->m_ucmd.buttons & BUTTON_WALKING && parentPS->speed > fWalkSpeedMax) { parentPS->speed = fWalkSpeedMax; - } - else if ( parentPS->speed > speedMax ) - { + } else if (parentPS->speed > speedMax) { parentPS->speed = speedMax; - } - else if ( parentPS->speed < speedMin ) - { + } else if (parentPS->speed < speedMin) { parentPS->speed = speedMin; } - if (parentPS->stats[STAT_HEALTH] <= 0) - { //don't keep moving while you're dying! + if (parentPS->stats[STAT_HEALTH] <= 0) { // don't keep moving while you're dying! parentPS->speed = 0; } @@ -190,29 +159,23 @@ static void ProcessMoveCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -void WalkerYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) -{ +void WalkerYawAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *parentPS) { float angDif = AngleSubtract(pVeh->m_vOrientation[YAW], riderPS->viewangles[YAW]); - if (parentPS && parentPS->speed) - { + if (parentPS && parentPS->speed) { float s = parentPS->speed; - float maxDif = pVeh->m_pVehicleInfo->turningSpeed*1.5f; //magic number hackery + float maxDif = pVeh->m_pVehicleInfo->turningSpeed * 1.5f; // magic number hackery - if (s < 0.0f) - { + if (s < 0.0f) { s = -s; } - angDif *= s/pVeh->m_pVehicleInfo->speedMax; - if (angDif > maxDif) - { + angDif *= s / pVeh->m_pVehicleInfo->speedMax; + if (angDif > maxDif) { angDif = maxDif; - } - else if (angDif < -maxDif) - { + } else if (angDif < -maxDif) { angDif = -maxDif; } - pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif*(pVeh->m_fTimeModifier*0.2f)); + pVeh->m_vOrientation[YAW] = AngleNormalize180(pVeh->m_vOrientation[YAW] - angDif * (pVeh->m_fTimeModifier * 0.2f)); } } @@ -244,15 +207,14 @@ void WalkerPitchAdjust(Vehicle_t *pVeh, playerState_t *riderPS, playerState_t *p } */ -//MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! -//If you really need to violate this rule for SP, then use ifdefs. -//By BG-compatible, I mean no use of game-specific data - ONLY use -//stuff available in the MP bgEntity (in SP, the bgEntity is #defined -//as a gentity, but the MP-compatible access restrictions are based -//on the bgEntity structure in the MP codebase) -rww -// ProcessOrientCommands the Vehicle. -static void ProcessOrientCommands( Vehicle_t *pVeh ) -{ +// MP RULE - ALL PROCESSORIENTCOMMANDS FUNCTIONS MUST BE BG-COMPATIBLE!!! +// If you really need to violate this rule for SP, then use ifdefs. +// By BG-compatible, I mean no use of game-specific data - ONLY use +// stuff available in the MP bgEntity (in SP, the bgEntity is #defined +// as a gentity, but the MP-compatible access restrictions are based +// on the bgEntity structure in the MP codebase) -rww +// ProcessOrientCommands the Vehicle. +static void ProcessOrientCommands(Vehicle_t *pVeh) { /********************************************************************************/ /* BEGIN Here is where make sure the vehicle is properly oriented. BEGIN */ /********************************************************************************/ @@ -260,13 +222,11 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) playerState_t *parentPS, *riderPS; bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } - if ( !rider ) - { + if (!rider) { rider = parent; } @@ -274,43 +234,33 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) riderPS = rider->playerState; // If the player is the rider... - if ( rider->s.number < MAX_CLIENTS ) - {//FIXME: use the vehicle's turning stat in this calc + if (rider->s.number < MAX_CLIENTS) { // FIXME: use the vehicle's turning stat in this calc WalkerYawAdjust(pVeh, riderPS, parentPS); - //FighterPitchAdjust(pVeh, riderPS, parentPS); + // FighterPitchAdjust(pVeh, riderPS, parentPS); pVeh->m_vOrientation[PITCH] = riderPS->viewangles[PITCH]; - } - else - { + } else { float turnSpeed = pVeh->m_pVehicleInfo->turningSpeed; - if ( !pVeh->m_pVehicleInfo->turnWhenStopped - && !parentPS->speed )//FIXME: or !pVeh->m_ucmd.forwardmove? - {//can't turn when not moving - //FIXME: or ramp up to max turnSpeed? + if (!pVeh->m_pVehicleInfo->turnWhenStopped && !parentPS->speed) // FIXME: or !pVeh->m_ucmd.forwardmove? + { // can't turn when not moving + // FIXME: or ramp up to max turnSpeed? turnSpeed = 0.0f; } - if (rider->s.eType == ET_NPC) - {//help NPCs out some + if (rider->s.eType == ET_NPC) { // help NPCs out some turnSpeed *= 2.0f; - if (parentPS->speed > 200.0f) - { - turnSpeed += turnSpeed * parentPS->speed/200.0f*0.05f; + if (parentPS->speed > 200.0f) { + turnSpeed += turnSpeed * parentPS->speed / 200.0f * 0.05f; } } turnSpeed *= pVeh->m_fTimeModifier; - //default control scheme: strafing turns, mouselook aims - if ( pVeh->m_ucmd.rightmove < 0 ) - { + // default control scheme: strafing turns, mouselook aims + if (pVeh->m_ucmd.rightmove < 0) { pVeh->m_vOrientation[YAW] += turnSpeed; - } - else if ( pVeh->m_ucmd.rightmove > 0 ) - { + } else if (pVeh->m_ucmd.rightmove > 0) { pVeh->m_vOrientation[YAW] -= turnSpeed; } - if ( pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel ) - {//damaged badly + if (pVeh->m_pVehicleInfo->malfunctionArmorLevel && pVeh->m_iArmor <= pVeh->m_pVehicleInfo->malfunctionArmorLevel) { // damaged badly } } @@ -319,18 +269,16 @@ static void ProcessOrientCommands( Vehicle_t *pVeh ) /********************************************************************************/ } -#ifdef _GAME //back to our game-only functions +#ifdef _GAME // back to our game-only functions // This function makes sure that the vehicle is properly animated. -static void AnimateVehicle( Vehicle_t *pVeh ) -{ +static void AnimateVehicle(Vehicle_t *pVeh) { animNumber_t Anim = BOTH_STAND1; int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; float fSpeedPercToMax; // We're dead (boarding is reused here so I don't have to make another variable :-). - if ( parent->health <= 0 ) - { + if (parent->health <= 0) { /* if ( pVeh->m_iBoarding != -999 ) // Animate the death just once! { @@ -344,40 +292,39 @@ static void AnimateVehicle( Vehicle_t *pVeh ) return; } -// Following is redundant to g_vehicles.c -// if ( pVeh->m_iBoarding ) -// { -// //we have no boarding anim -// if (pVeh->m_iBoarding < level.time) -// { //we are on now -// pVeh->m_iBoarding = 0; -// } -// else -// { -// return; -// } -// } + // Following is redundant to g_vehicles.c + // if ( pVeh->m_iBoarding ) + // { + // //we have no boarding anim + // if (pVeh->m_iBoarding < level.time) + // { //we are on now + // pVeh->m_iBoarding = 0; + // } + // else + // { + // return; + // } + // } // Percentage of maximum speed relative to current speed. - //float fSpeed = VectorLength( client->ps.velocity ); + // float fSpeed = VectorLength( client->ps.velocity ); fSpeedPercToMax = parent->client->ps.speed / pVeh->m_pVehicleInfo->speedMax; // If we're moving... - if ( fSpeedPercToMax > 0.0f ) //fSpeedPercToMax >= 0.85f ) + if (fSpeedPercToMax > 0.0f) // fSpeedPercToMax >= 0.85f ) { - // float fYawDelta; + // float fYawDelta; iBlend = 300; iFlags = SETANIM_FLAG_OVERRIDE; - // fYawDelta = pVeh->m_vPrevOrientation[YAW] - pVeh->m_vOrientation[YAW]; + // fYawDelta = pVeh->m_vPrevOrientation[YAW] - pVeh->m_vOrientation[YAW]; // NOTE: Mikes suggestion for fixing the stuttering walk (left/right) is to maintain the // current frame between animations. I have no clue how to do this and have to work on other // stuff so good luck to him :-p AReis // If we're walking (or our speed is less than .275%)... - if ( ( pVeh->m_ucmd.buttons & BUTTON_WALKING ) || fSpeedPercToMax < 0.275f ) - { + if ((pVeh->m_ucmd.buttons & BUTTON_WALKING) || fSpeedPercToMax < 0.275f) { // Make them lean if we're turning. /*if ( fYawDelta < -0.0001f ) { @@ -388,13 +335,10 @@ static void AnimateVehicle( Vehicle_t *pVeh ) Anim = BOTH_VT_WALK_FWD_R; } else*/ - { - Anim = BOTH_WALK1; - } + { Anim = BOTH_WALK1; } } // otherwise we're running. - else - { + else { // Make them lean if we're turning. /*if ( fYawDelta < -0.0001f ) { @@ -405,80 +349,69 @@ static void AnimateVehicle( Vehicle_t *pVeh ) Anim = BOTH_VT_RUN_FWD_R; } else*/ - { - Anim = BOTH_RUN1; - } + { Anim = BOTH_RUN1; } } - } - else - { + } else { // Going in reverse... - if ( fSpeedPercToMax < -0.018f ) - { + if (fSpeedPercToMax < -0.018f) { iFlags = SETANIM_FLAG_NORMAL; Anim = BOTH_WALKBACK1; iBlend = 500; - } - else - { - //int iChance = Q_irand( 0, 20000 ); + } else { + // int iChance = Q_irand( 0, 20000 ); // Every once in a while buck or do a different idle... iFlags = SETANIM_FLAG_NORMAL | SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD; iBlend = 600; - if (parent->client->ps.m_iVehicleNum) - {//occupado + if (parent->client->ps.m_iVehicleNum) { // occupado Anim = BOTH_STAND1; - } - else - {//wide open for you, baby + } else { // wide open for you, baby Anim = BOTH_STAND2; } } } - Vehicle_SetAnim( parent, SETANIM_LEGS, Anim, iFlags, iBlend ); + Vehicle_SetAnim(parent, SETANIM_LEGS, Anim, iFlags, iBlend); } -//rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful -//and lagged +// rwwFIXMEFIXME: This is all going to have to be predicted I think, or it will feel awful +// and lagged #endif //_GAME #ifndef _GAME -void AttachRidersGeneric( Vehicle_t *pVeh ); +void AttachRidersGeneric(Vehicle_t *pVeh); #endif -//on the client this function will only set up the process command funcs -void G_SetWalkerVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +// on the client this function will only set up the process command funcs +void G_SetWalkerVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef _GAME - pVehInfo->AnimateVehicle = AnimateVehicle; -// pVehInfo->AnimateRiders = AnimateRiders; -// pVehInfo->ValidateBoard = ValidateBoard; -// pVehInfo->SetParent = SetParent; -// pVehInfo->SetPilot = SetPilot; -// pVehInfo->AddPassenger = AddPassenger; -// pVehInfo->Animate = Animate; - pVehInfo->Board = Board; -// pVehInfo->Eject = Eject; -// pVehInfo->EjectAll = EjectAll; -// pVehInfo->StartDeathDelay = StartDeathDelay; -// pVehInfo->DeathUpdate = DeathUpdate; - pVehInfo->RegisterAssets = RegisterAssets; + pVehInfo->AnimateVehicle = AnimateVehicle; + // pVehInfo->AnimateRiders = AnimateRiders; + // pVehInfo->ValidateBoard = ValidateBoard; + // pVehInfo->SetParent = SetParent; + // pVehInfo->SetPilot = SetPilot; + // pVehInfo->AddPassenger = AddPassenger; + // pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + // pVehInfo->Eject = Eject; + // pVehInfo->EjectAll = EjectAll; + // pVehInfo->StartDeathDelay = StartDeathDelay; + // pVehInfo->DeathUpdate = DeathUpdate; + pVehInfo->RegisterAssets = RegisterAssets; // pVehInfo->Initialize = Initialize; // pVehInfo->Update = Update; // pVehInfo->UpdateRider = UpdateRider; #endif //_GAME - pVehInfo->ProcessMoveCommands = ProcessMoveCommands; - pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + pVehInfo->ProcessOrientCommands = ProcessOrientCommands; -#ifndef _GAME //cgame prediction attachment func - pVehInfo->AttachRiders = AttachRidersGeneric; +#ifndef _GAME // cgame prediction attachment func + pVehInfo->AttachRiders = AttachRidersGeneric; #endif -// pVehInfo->AttachRiders = AttachRiders; -// pVehInfo->Ghost = Ghost; -// pVehInfo->UnGhost = UnGhost; -// pVehInfo->Inhabited = Inhabited; + // pVehInfo->AttachRiders = AttachRiders; + // pVehInfo->Ghost = Ghost; + // pVehInfo->UnGhost = UnGhost; + // pVehInfo->Inhabited = Inhabited; } // Following is only in game, not in namespace @@ -487,23 +420,20 @@ void G_SetWalkerVehicleFunctions( vehicleInfo_t *pVehInfo ) extern void G_AllocateVehicleObject(Vehicle_t **pVeh); #endif - // Create/Allocate a new Animal Vehicle (initializing it as well). -//this is a BG function too in MP so don't un-bg-compatibilify it -rww -void G_CreateWalkerNPC( Vehicle_t **pVeh, const char *strAnimalType ) -{ +// this is a BG function too in MP so don't un-bg-compatibilify it -rww +void G_CreateWalkerNPC(Vehicle_t **pVeh, const char *strAnimalType) { // Allocate the Vehicle. #ifdef _GAME - //these will remain on entities on the client once allocated because the pointer is - //never stomped. on the server, however, when an ent is freed, the entity struct is - //memset to 0, so this memory would be lost.. - G_AllocateVehicleObject(pVeh); + // these will remain on entities on the client once allocated because the pointer is + // never stomped. on the server, however, when an ent is freed, the entity struct is + // memset to 0, so this memory would be lost.. + G_AllocateVehicleObject(pVeh); #else - if (!*pVeh) - { //only allocate a new one if we really have to - (*pVeh) = (Vehicle_t *) BG_Alloc( sizeof(Vehicle_t) ); + if (!*pVeh) { // only allocate a new one if we really have to + (*pVeh) = (Vehicle_t *)BG_Alloc(sizeof(Vehicle_t)); } #endif memset(*pVeh, 0, sizeof(Vehicle_t)); - (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex( strAnimalType )]; + (*pVeh)->m_pVehicleInfo = &g_vehicleInfo[BG_VehicleGetIndex(strAnimalType)]; } diff --git a/codemp/game/ai_main.c b/codemp/game/ai_main.c index 3908e2c119..1e067ca169 100644 --- a/codemp/game/ai_main.c +++ b/codemp/game/ai_main.c @@ -34,10 +34,9 @@ along with this program; if not, see . * *****************************************************************************/ - #include "g_local.h" #include "qcommon/q_shared.h" -#include "botlib/botlib.h" //bot lib interface +#include "botlib/botlib.h" //bot lib interface #include "botlib/be_aas.h" #include "botlib/be_ea.h" #include "botlib/be_ai_char.h" @@ -57,25 +56,25 @@ along with this program; if not, see . #define BOT_CTF_DEBUG 1 */ -#define BOT_THINK_TIME 0 +#define BOT_THINK_TIME 0 -//bot states -bot_state_t *botstates[MAX_CLIENTS]; -//number of bots +// bot states +bot_state_t *botstates[MAX_CLIENTS]; +// number of bots int numbots; -//floating point time +// floating point time float floattime; -//time to do a regular update +// time to do a regular update float regularupdate_time; // -//for siege: +// for siege: extern int rebel_attackers; extern int imperial_attackers; boteventtracker_t gBotEventTracker[MAX_CLIENTS]; -//rww - new bot cvars.. +// rww - new bot cvars.. vmCvar_t bot_forcepowers; vmCvar_t bot_forgimmick; vmCvar_t bot_honorableduelacceptance; @@ -98,7 +97,7 @@ vmCvar_t bot_wp_edit; vmCvar_t bot_wp_clearweight; vmCvar_t bot_wp_distconnect; vmCvar_t bot_wp_visconnect; -//end rww +// end rww wpobject_t *flagRed; wpobject_t *oFlagRed; @@ -110,45 +109,22 @@ gentity_t *droppedRedFlag; gentity_t *eFlagBlue; gentity_t *droppedBlueFlag; -char *ctfStateNames[] = { - "CTFSTATE_NONE", - "CTFSTATE_ATTACKER", - "CTFSTATE_DEFENDER", - "CTFSTATE_RETRIEVAL", - "CTFSTATE_GUARDCARRIER", - "CTFSTATE_GETFLAGHOME", - "CTFSTATE_MAXCTFSTATES" -}; - -char *ctfStateDescriptions[] = { - "I'm not occupied", - "I'm attacking the enemy's base", - "I'm defending our base", - "I'm getting our flag back", - "I'm escorting our flag carrier", - "I've got the enemy's flag" -}; - -char *siegeStateDescriptions[] = { - "I'm not occupied", - "I'm attempting to complete the current objective", - "I'm preventing the enemy from completing their objective" -}; - -char *teamplayStateDescriptions[] = { - "I'm not occupied", - "I'm following my squad commander", - "I'm assisting my commanding", - "I'm attempting to regroup and form a new squad" -}; - -void BotStraightTPOrderCheck(gentity_t *ent, int ordernum, bot_state_t *bs) -{ - switch (ordernum) - { +char *ctfStateNames[] = {"CTFSTATE_NONE", "CTFSTATE_ATTACKER", "CTFSTATE_DEFENDER", "CTFSTATE_RETRIEVAL", + "CTFSTATE_GUARDCARRIER", "CTFSTATE_GETFLAGHOME", "CTFSTATE_MAXCTFSTATES"}; + +char *ctfStateDescriptions[] = {"I'm not occupied", "I'm attacking the enemy's base", "I'm defending our base", + "I'm getting our flag back", "I'm escorting our flag carrier", "I've got the enemy's flag"}; + +char *siegeStateDescriptions[] = {"I'm not occupied", "I'm attempting to complete the current objective", + "I'm preventing the enemy from completing their objective"}; + +char *teamplayStateDescriptions[] = {"I'm not occupied", "I'm following my squad commander", "I'm assisting my commanding", + "I'm attempting to regroup and form a new squad"}; + +void BotStraightTPOrderCheck(gentity_t *ent, int ordernum, bot_state_t *bs) { + switch (ordernum) { case 0: - if (bs->squadLeader == ent) - { + if (bs->squadLeader == ent) { bs->teamplayState = 0; bs->squadLeader = NULL; } @@ -171,116 +147,84 @@ void BotStraightTPOrderCheck(gentity_t *ent, int ordernum, bot_state_t *bs) } } -void BotSelectWeapon(int client, int weapon) -{ - if (weapon <= WP_NONE) - { -// assert(0); +void BotSelectWeapon(int client, int weapon) { + if (weapon <= WP_NONE) { + // assert(0); return; } trap->EA_SelectWeapon(client, weapon); } -void BotReportStatus(bot_state_t *bs) -{ - if (level.gametype == GT_TEAM) - { +void BotReportStatus(bot_state_t *bs) { + if (level.gametype == GT_TEAM) { trap->EA_SayTeam(bs->client, teamplayStateDescriptions[bs->teamplayState]); - } - else if (level.gametype == GT_SIEGE) - { + } else if (level.gametype == GT_SIEGE) { trap->EA_SayTeam(bs->client, siegeStateDescriptions[bs->siegeState]); - } - else if (level.gametype == GT_CTF || level.gametype == GT_CTY) - { + } else if (level.gametype == GT_CTF || level.gametype == GT_CTY) { trap->EA_SayTeam(bs->client, ctfStateDescriptions[bs->ctfState]); } } -//accept a team order from a player -void BotOrder(gentity_t *ent, int clientnum, int ordernum) -{ +// accept a team order from a player +void BotOrder(gentity_t *ent, int clientnum, int ordernum) { int stateMin = 0; int stateMax = 0; int i = 0; - if (!ent || !ent->client || !ent->client->sess.teamLeader) - { + if (!ent || !ent->client || !ent->client->sess.teamLeader) { return; } - if (clientnum != -1 && !botstates[clientnum]) - { + if (clientnum != -1 && !botstates[clientnum]) { return; } - if (clientnum != -1 && !OnSameTeam(ent, &g_entities[clientnum])) - { + if (clientnum != -1 && !OnSameTeam(ent, &g_entities[clientnum])) { return; } - if (level.gametype != GT_CTF && level.gametype != GT_CTY && level.gametype != GT_SIEGE && level.gametype != GT_TEAM) - { + if (level.gametype != GT_CTF && level.gametype != GT_CTY && level.gametype != GT_SIEGE && level.gametype != GT_TEAM) { return; } - if (level.gametype == GT_CTF || level.gametype == GT_CTY) - { + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { stateMin = CTFSTATE_NONE; stateMax = CTFSTATE_MAXCTFSTATES; - } - else if (level.gametype == GT_SIEGE) - { + } else if (level.gametype == GT_SIEGE) { stateMin = SIEGESTATE_NONE; stateMax = SIEGESTATE_MAXSIEGESTATES; - } - else if (level.gametype == GT_TEAM) - { + } else if (level.gametype == GT_TEAM) { stateMin = TEAMPLAYSTATE_NONE; stateMax = TEAMPLAYSTATE_MAXTPSTATES; } - if ((ordernum < stateMin && ordernum != -1) || ordernum >= stateMax) - { + if ((ordernum < stateMin && ordernum != -1) || ordernum >= stateMax) { return; } - if (clientnum != -1) - { - if (ordernum == -1) - { + if (clientnum != -1) { + if (ordernum == -1) { BotReportStatus(botstates[clientnum]); - } - else - { + } else { BotStraightTPOrderCheck(ent, ordernum, botstates[clientnum]); botstates[clientnum]->state_Forced = ordernum; botstates[clientnum]->chatObject = ent; botstates[clientnum]->chatAltObject = NULL; - if (BotDoChat(botstates[clientnum], "OrderAccepted", 1)) - { + if (BotDoChat(botstates[clientnum], "OrderAccepted", 1)) { botstates[clientnum]->chatTeam = 1; } } - } - else - { - while (i < MAX_CLIENTS) - { - if (botstates[i] && OnSameTeam(ent, &g_entities[i])) - { - if (ordernum == -1) - { + } else { + while (i < MAX_CLIENTS) { + if (botstates[i] && OnSameTeam(ent, &g_entities[i])) { + if (ordernum == -1) { BotReportStatus(botstates[i]); - } - else - { + } else { BotStraightTPOrderCheck(ent, ordernum, botstates[i]); botstates[i]->state_Forced = ordernum; botstates[i]->chatObject = ent; botstates[i]->chatAltObject = NULL; - if (BotDoChat(botstates[i], "OrderAccepted", 0)) - { + if (BotDoChat(botstates[i], "OrderAccepted", 0)) { botstates[i]->chatTeam = 1; } } @@ -291,48 +235,34 @@ void BotOrder(gentity_t *ent, int clientnum, int ordernum) } } -//See if bot is mindtricked by the client in question -int BotMindTricked(int botClient, int enemyClient) -{ +// See if bot is mindtricked by the client in question +int BotMindTricked(int botClient, int enemyClient) { forcedata_t *fd; - if (!g_entities[enemyClient].client) - { + if (!g_entities[enemyClient].client) { return 0; } fd = &g_entities[enemyClient].client->ps.fd; - if (!fd) - { + if (!fd) { return 0; } - if (botClient > 47) - { - if (fd->forceMindtrickTargetIndex4 & (1 << (botClient-48))) - { + if (botClient > 47) { + if (fd->forceMindtrickTargetIndex4 & (1 << (botClient - 48))) { return 1; } - } - else if (botClient > 31) - { - if (fd->forceMindtrickTargetIndex3 & (1 << (botClient-32))) - { + } else if (botClient > 31) { + if (fd->forceMindtrickTargetIndex3 & (1 << (botClient - 32))) { return 1; } - } - else if (botClient > 15) - { - if (fd->forceMindtrickTargetIndex2 & (1 << (botClient-16))) - { + } else if (botClient > 15) { + if (fd->forceMindtrickTargetIndex2 & (1 << (botClient - 16))) { return 1; } - } - else - { - if (fd->forceMindtrickTargetIndex & (1 << botClient)) - { + } else { + if (fd->forceMindtrickTargetIndex & (1 << botClient)) { return 1; } } @@ -343,16 +273,14 @@ int BotMindTricked(int botClient, int enemyClient) int BotGetWeaponRange(bot_state_t *bs); int PassLovedOneCheck(bot_state_t *bs, gentity_t *ent); -void ExitLevel( void ); +void ExitLevel(void); void QDECL BotAI_Print(int type, char *fmt, ...) { return; } -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ); +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower); -int IsTeamplay(void) -{ - if ( level.gametype < GT_TEAM ) - { +int IsTeamplay(void) { + if (level.gametype < GT_TEAM) { return 0; } @@ -364,18 +292,18 @@ int IsTeamplay(void) BotAI_GetClientState ================== */ -int BotAI_GetClientState( int clientNum, playerState_t *state ) { - gentity_t *ent; +int BotAI_GetClientState(int clientNum, playerState_t *state) { + gentity_t *ent; ent = &g_entities[clientNum]; - if ( !ent->inuse ) { + if (!ent->inuse) { return qfalse; } - if ( !ent->client ) { + if (!ent->client) { return qfalse; } - memcpy( state, &ent->client->ps, sizeof(playerState_t) ); + memcpy(state, &ent->client->ps, sizeof(playerState_t)); return qtrue; } @@ -384,15 +312,18 @@ int BotAI_GetClientState( int clientNum, playerState_t *state ) { BotAI_GetEntityState ================== */ -int BotAI_GetEntityState( int entityNum, entityState_t *state ) { - gentity_t *ent; +int BotAI_GetEntityState(int entityNum, entityState_t *state) { + gentity_t *ent; ent = &g_entities[entityNum]; - memset( state, 0, sizeof(entityState_t) ); - if (!ent->inuse) return qfalse; - if (!ent->r.linked) return qfalse; - if (ent->r.svFlags & SVF_NOCLIENT) return qfalse; - memcpy( state, &ent->s, sizeof(entityState_t) ); + memset(state, 0, sizeof(entityState_t)); + if (!ent->inuse) + return qfalse; + if (!ent->r.linked) + return qfalse; + if (ent->r.svFlags & SVF_NOCLIENT) + return qfalse; + memcpy(state, &ent->s, sizeof(entityState_t)); return qtrue; } @@ -401,16 +332,16 @@ int BotAI_GetEntityState( int entityNum, entityState_t *state ) { BotAI_GetSnapshotEntity ================== */ -int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state ) { - int entNum; +int BotAI_GetSnapshotEntity(int clientNum, int sequence, entityState_t *state) { + int entNum; - entNum = trap->BotGetSnapshotEntity( clientNum, sequence ); - if ( entNum == -1 ) { + entNum = trap->BotGetSnapshotEntity(clientNum, sequence); + if (entNum == -1) { memset(state, 0, sizeof(entityState_t)); return -1; } - BotAI_GetEntityState( entNum, state ); + BotAI_GetEntityState(entNum, state); return sequence + 1; } @@ -420,18 +351,14 @@ int BotAI_GetSnapshotEntity( int clientNum, int sequence, entityState_t *state ) BotEntityInfo ============== */ -void BotEntityInfo(int entnum, aas_entityinfo_t *info) { - trap->AAS_EntityInfo(entnum, info); -} +void BotEntityInfo(int entnum, aas_entityinfo_t *info) { trap->AAS_EntityInfo(entnum, info); } /* ============== NumBots ============== */ -int NumBots(void) { - return numbots; -} +int NumBots(void) { return numbots; } /* ============== @@ -443,10 +370,11 @@ float AngleDifference(float ang1, float ang2) { diff = ang1 - ang2; if (ang1 > ang2) { - if (diff > 180.0) diff -= 360.0; - } - else { - if (diff < -180.0) diff += 360.0; + if (diff > 180.0) + diff -= 360.0; + } else { + if (diff < -180.0) + diff += 360.0; } return diff; } @@ -461,19 +389,22 @@ float BotChangeViewAngle(float angle, float ideal_angle, float speed) { angle = AngleMod(angle); ideal_angle = AngleMod(ideal_angle); - if (angle == ideal_angle) return angle; + if (angle == ideal_angle) + return angle; move = ideal_angle - angle; if (ideal_angle > angle) { - if (move > 180.0) move -= 360.0; - } - else { - if (move < -180.0) move += 360.0; + if (move > 180.0) + move -= 360.0; + } else { + if (move < -180.0) + move += 360.0; } if (move > 0) { - if (move > speed) move = speed; - } - else { - if (move < -speed) move = -speed; + if (move > speed) + move = speed; + } else { + if (move < -speed) + move = -speed; } return AngleMod(angle + move); } @@ -487,44 +418,33 @@ void BotChangeViewAngles(bot_state_t *bs, float thinktime) { float diff, factor, maxchange, anglespeed, disired_speed; int i; - if (bs->ideal_viewangles[PITCH] > 180) bs->ideal_viewangles[PITCH] -= 360; + if (bs->ideal_viewangles[PITCH] > 180) + bs->ideal_viewangles[PITCH] -= 360; - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { - if (bs->settings.skill <= 1) - { - factor = (bs->skills.turnspeed_combat*0.4f)*bs->settings.skill; + if (bs->currentEnemy && bs->frame_Enemy_Vis) { + if (bs->settings.skill <= 1) { + factor = (bs->skills.turnspeed_combat * 0.4f) * bs->settings.skill; + } else if (bs->settings.skill <= 2) { + factor = (bs->skills.turnspeed_combat * 0.6f) * bs->settings.skill; + } else if (bs->settings.skill <= 3) { + factor = (bs->skills.turnspeed_combat * 0.8f) * bs->settings.skill; + } else { + factor = bs->skills.turnspeed_combat * bs->settings.skill; } - else if (bs->settings.skill <= 2) - { - factor = (bs->skills.turnspeed_combat*0.6f)*bs->settings.skill; - } - else if (bs->settings.skill <= 3) - { - factor = (bs->skills.turnspeed_combat*0.8f)*bs->settings.skill; - } - else - { - factor = bs->skills.turnspeed_combat*bs->settings.skill; - } - } - else - { + } else { factor = bs->skills.turnspeed; } - if (factor > 1) - { + if (factor > 1) { factor = 1; } - if (factor < 0.001) - { + if (factor < 0.001) { factor = 0.001f; } maxchange = bs->skills.maxturn; - //if (maxchange < 240) maxchange = 240; + // if (maxchange < 240) maxchange = 240; maxchange *= thinktime; for (i = 0; i < 2; i++) { bs->viewangles[i] = AngleMod(bs->viewangles[i]); @@ -532,16 +452,21 @@ void BotChangeViewAngles(bot_state_t *bs, float thinktime) { diff = AngleDifference(bs->viewangles[i], bs->ideal_viewangles[i]); disired_speed = diff * factor; bs->viewanglespeed[i] += (bs->viewanglespeed[i] - disired_speed); - if (bs->viewanglespeed[i] > 180) bs->viewanglespeed[i] = maxchange; - if (bs->viewanglespeed[i] < -180) bs->viewanglespeed[i] = -maxchange; + if (bs->viewanglespeed[i] > 180) + bs->viewanglespeed[i] = maxchange; + if (bs->viewanglespeed[i] < -180) + bs->viewanglespeed[i] = -maxchange; anglespeed = bs->viewanglespeed[i]; - if (anglespeed > maxchange) anglespeed = maxchange; - if (anglespeed < -maxchange) anglespeed = -maxchange; + if (anglespeed > maxchange) + anglespeed = maxchange; + if (anglespeed < -maxchange) + anglespeed = -maxchange; bs->viewangles[i] += anglespeed; bs->viewangles[i] = AngleMod(bs->viewangles[i]); bs->viewanglespeed[i] *= 0.45 * (1 - factor); } - if (bs->viewangles[PITCH] > 180) bs->viewangles[PITCH] -= 360; + if (bs->viewangles[PITCH] > 180) + bs->viewangles[PITCH] -= 360; trap->EA_View(bs->client, bs->viewangles); } @@ -556,28 +481,34 @@ void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3] int j; float f, r, u, m; - //clear the whole structure + // clear the whole structure memset(ucmd, 0, sizeof(usercmd_t)); - //the duration for the user command in milli seconds + // the duration for the user command in milli seconds ucmd->serverTime = time; // if (bi->actionflags & ACTION_DELAYEDJUMP) { bi->actionflags |= ACTION_JUMP; bi->actionflags &= ~ACTION_DELAYEDJUMP; } - //set the buttons - if (bi->actionflags & ACTION_RESPAWN) ucmd->buttons = BUTTON_ATTACK; - if (bi->actionflags & ACTION_ATTACK) ucmd->buttons |= BUTTON_ATTACK; - if (bi->actionflags & ACTION_ALT_ATTACK) ucmd->buttons |= BUTTON_ALT_ATTACK; -// if (bi->actionflags & ACTION_TALK) ucmd->buttons |= BUTTON_TALK; - if (bi->actionflags & ACTION_GESTURE) ucmd->buttons |= BUTTON_GESTURE; - if (bi->actionflags & ACTION_USE) ucmd->buttons |= BUTTON_USE_HOLDABLE; - if (bi->actionflags & ACTION_WALK) ucmd->buttons |= BUTTON_WALKING; - - if (bi->actionflags & ACTION_FORCEPOWER) ucmd->buttons |= BUTTON_FORCEPOWER; - - if (useTime < level.time && Q_irand(1, 10) < 5) - { //for now just hit use randomly in case there's something useable around + // set the buttons + if (bi->actionflags & ACTION_RESPAWN) + ucmd->buttons = BUTTON_ATTACK; + if (bi->actionflags & ACTION_ATTACK) + ucmd->buttons |= BUTTON_ATTACK; + if (bi->actionflags & ACTION_ALT_ATTACK) + ucmd->buttons |= BUTTON_ALT_ATTACK; + // if (bi->actionflags & ACTION_TALK) ucmd->buttons |= BUTTON_TALK; + if (bi->actionflags & ACTION_GESTURE) + ucmd->buttons |= BUTTON_GESTURE; + if (bi->actionflags & ACTION_USE) + ucmd->buttons |= BUTTON_USE_HOLDABLE; + if (bi->actionflags & ACTION_WALK) + ucmd->buttons |= BUTTON_WALKING; + + if (bi->actionflags & ACTION_FORCEPOWER) + ucmd->buttons |= BUTTON_FORCEPOWER; + + if (useTime < level.time && Q_irand(1, 10) < 5) { // for now just hit use randomly in case there's something useable around ucmd->buttons |= BUTTON_USE; } #if 0 @@ -590,10 +521,9 @@ void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3] if (bi->actionflags & ACTION_GUARDBASE) ucmd->buttons |= BUTTON_GUARDBASE; if (bi->actionflags & ACTION_PATROL) ucmd->buttons |= BUTTON_PATROL; if (bi->actionflags & ACTION_FOLLOWME) ucmd->buttons |= BUTTON_FOLLOWME; -#endif //0 +#endif // 0 - if (bi->weapon == WP_NONE) - { + if (bi->weapon == WP_NONE) { #ifdef _DEBUG // Com_Printf("WARNING: Bot tried to use WP_NONE!\n"); #endif @@ -602,27 +532,29 @@ void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3] // ucmd->weapon = bi->weapon; - //set the view angles - //NOTE: the ucmd->angles are the angles WITHOUT the delta angles + // set the view angles + // NOTE: the ucmd->angles are the angles WITHOUT the delta angles ucmd->angles[PITCH] = ANGLE2SHORT(bi->viewangles[PITCH]); ucmd->angles[YAW] = ANGLE2SHORT(bi->viewangles[YAW]); ucmd->angles[ROLL] = ANGLE2SHORT(bi->viewangles[ROLL]); - //subtract the delta angles + // subtract the delta angles for (j = 0; j < 3; j++) { temp = ucmd->angles[j] - delta_angles[j]; ucmd->angles[j] = temp; } - //NOTE: movement is relative to the REAL view angles - //get the horizontal forward and right vector - //get the pitch in the range [-180, 180] - if (bi->dir[2]) angles[PITCH] = bi->viewangles[PITCH]; - else angles[PITCH] = 0; + // NOTE: movement is relative to the REAL view angles + // get the horizontal forward and right vector + // get the pitch in the range [-180, 180] + if (bi->dir[2]) + angles[PITCH] = bi->viewangles[PITCH]; + else + angles[PITCH] = 0; angles[YAW] = bi->viewangles[YAW]; angles[ROLL] = 0; AngleVectors(angles, forward, right, NULL); - //bot input speed is in the range [0, 400] + // bot input speed is in the range [0, 400] bi->speed = bi->speed * 127 / 400; - //set the view independent movement + // set the view independent movement f = DotProduct(forward, bi->dir); r = DotProduct(right, bi->dir); u = fabs(forward[2]) * bi->dir[2]; @@ -645,15 +577,21 @@ void BotInputToUserCommand(bot_input_t *bi, usercmd_t *ucmd, int delta_angles[3] ucmd->forwardmove = f; ucmd->rightmove = r; ucmd->upmove = u; - //normal keyboard movement - if (bi->actionflags & ACTION_MOVEFORWARD) ucmd->forwardmove = 127; - if (bi->actionflags & ACTION_MOVEBACK) ucmd->forwardmove = -127; - if (bi->actionflags & ACTION_MOVELEFT) ucmd->rightmove = -127; - if (bi->actionflags & ACTION_MOVERIGHT) ucmd->rightmove = 127; - //jump/moveup - if (bi->actionflags & ACTION_JUMP) ucmd->upmove = 127; - //crouch/movedown - if (bi->actionflags & ACTION_CROUCH) ucmd->upmove = -127; + // normal keyboard movement + if (bi->actionflags & ACTION_MOVEFORWARD) + ucmd->forwardmove = 127; + if (bi->actionflags & ACTION_MOVEBACK) + ucmd->forwardmove = -127; + if (bi->actionflags & ACTION_MOVELEFT) + ucmd->rightmove = -127; + if (bi->actionflags & ACTION_MOVERIGHT) + ucmd->rightmove = 127; + // jump/moveup + if (bi->actionflags & ACTION_JUMP) + ucmd->upmove = 127; + // crouch/movedown + if (bi->actionflags & ACTION_CROUCH) + ucmd->upmove = -127; } /* @@ -665,21 +603,22 @@ void BotUpdateInput(bot_state_t *bs, int time, int elapsed_time) { bot_input_t bi; int j; - //add the delta angles to the bot's current view angles + // add the delta angles to the bot's current view angles for (j = 0; j < 3; j++) { bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j])); } - //change the bot view angles - BotChangeViewAngles(bs, (float) elapsed_time / 1000); - //retrieve the bot input - trap->EA_GetInput(bs->client, (float) time / 1000, &bi); - //respawn hack + // change the bot view angles + BotChangeViewAngles(bs, (float)elapsed_time / 1000); + // retrieve the bot input + trap->EA_GetInput(bs->client, (float)time / 1000, &bi); + // respawn hack if (bi.actionflags & ACTION_RESPAWN) { - if (bs->lastucmd.buttons & BUTTON_ATTACK) bi.actionflags &= ~(ACTION_RESPAWN|ACTION_ATTACK); + if (bs->lastucmd.buttons & BUTTON_ATTACK) + bi.actionflags &= ~(ACTION_RESPAWN | ACTION_ATTACK); } - //convert the bot input to a usercmd + // convert the bot input to a usercmd BotInputToUserCommand(&bi, &bs->lastucmd, bs->cur_ps.delta_angles, time, bs->noUseTime); - //subtract the delta angles + // subtract the delta angles for (j = 0; j < 3; j++) { bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j])); } @@ -702,11 +641,11 @@ void BotAIRegularUpdate(void) { RemoveColorEscapeSequences ============== */ -void RemoveColorEscapeSequences( char *text ) { +void RemoveColorEscapeSequences(char *text) { int i, l; l = 0; - for ( i = 0; text[i]; i++ ) { + for (i = 0; text[i]; i++) { if (Q_IsColorStringExt(&text[i])) { i++; continue; @@ -718,7 +657,6 @@ void RemoveColorEscapeSequences( char *text ) { text[l] = '\0'; } - /* ============== BotAI @@ -741,42 +679,40 @@ int BotAI(int client, float thinktime) { return qfalse; } - //retrieve the current client state - BotAI_GetClientState( client, &bs->cur_ps ); + // retrieve the current client state + BotAI_GetClientState(client, &bs->cur_ps); - //retrieve any waiting server commands - while( trap->BotGetServerCommand(client, buf, sizeof(buf)) ) { - //have buf point to the command and args to the command arguments - args = strchr( buf, ' '); - if (!args) continue; + // retrieve any waiting server commands + while (trap->BotGetServerCommand(client, buf, sizeof(buf))) { + // have buf point to the command and args to the command arguments + args = strchr(buf, ' '); + if (!args) + continue; *args++ = '\0'; - //remove color espace sequences from the arguments - RemoveColorEscapeSequences( args ); + // remove color espace sequences from the arguments + RemoveColorEscapeSequences(args); - if (!Q_stricmp(buf, "cp ")) - { /*CenterPrintf*/ } - else if (!Q_stricmp(buf, "cs")) - { /*ConfigStringModified*/ } - else if (!Q_stricmp(buf, "scores")) - { /*FIXME: parse scores?*/ } - else if (!Q_stricmp(buf, "clientLevelShot")) - { /*ignore*/ } + if (!Q_stricmp(buf, "cp ")) { /*CenterPrintf*/ + } else if (!Q_stricmp(buf, "cs")) { /*ConfigStringModified*/ + } else if (!Q_stricmp(buf, "scores")) { /*FIXME: parse scores?*/ + } else if (!Q_stricmp(buf, "clientLevelShot")) { /*ignore*/ + } } - //add the delta angles to the bot's current view angles + // add the delta angles to the bot's current view angles for (j = 0; j < 3; j++) { bs->viewangles[j] = AngleMod(bs->viewangles[j] + SHORT2ANGLE(bs->cur_ps.delta_angles[j])); } - //increase the local time of the bot + // increase the local time of the bot bs->ltime += thinktime; // bs->thinktime = thinktime; - //origin of the bot + // origin of the bot VectorCopy(bs->cur_ps.origin, bs->origin); - //eye coordinates of the bot + // eye coordinates of the bot VectorCopy(bs->cur_ps.origin, bs->eye); bs->eye[2] += bs->cur_ps.viewheight; - //get the area the bot is in + // get the area the bot is in #ifdef _DEBUG start = trap->Milliseconds(); @@ -787,17 +723,16 @@ int BotAI(int client, float thinktime) { trap->Cvar_Update(&bot_debugmessages); - if (bot_debugmessages.integer) - { + if (bot_debugmessages.integer) { Com_Printf("Single AI frametime: %i\n", (end - start)); } #endif - //subtract the delta angles + // subtract the delta angles for (j = 0; j < 3; j++) { bs->viewangles[j] = AngleMod(bs->viewangles[j] - SHORT2ANGLE(bs->cur_ps.delta_angles[j])); } - //everything was ok + // everything was ok return qtrue; } @@ -811,28 +746,25 @@ void BotScheduleBotThink(void) { botnum = 0; - for( i = 0; i < MAX_CLIENTS; i++ ) { - if( !botstates[i] || !botstates[i]->inuse ) { + for (i = 0; i < MAX_CLIENTS; i++) { + if (!botstates[i] || !botstates[i]->inuse) { continue; } - //initialize the bot think residual time + // initialize the bot think residual time botstates[i]->botthink_residual = BOT_THINK_TIME * botnum / numbots; botnum++; } } -int PlayersInGame(void) -{ +int PlayersInGame(void) { int i = 0; gentity_t *ent; int pl = 0; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->pers.connected == CON_CONNECTED) - { + if (ent && ent->client && ent->client->pers.connected == CON_CONNECTED) { pl++; } @@ -850,8 +782,9 @@ BotAISetupClient int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean restart) { bot_state_t *bs; - if (!botstates[client]) botstates[client] = (bot_state_t *) B_Alloc(sizeof(bot_state_t)); //G_Alloc(sizeof(bot_state_t)); - //rww - G_Alloc bad! B_Alloc good. + if (!botstates[client]) + botstates[client] = (bot_state_t *)B_Alloc(sizeof(bot_state_t)); // G_Alloc(sizeof(bot_state_t)); + // rww - G_Alloc bad! B_Alloc good. memset(botstates[client], 0, sizeof(bot_state_t)); @@ -864,9 +797,9 @@ int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean resta memcpy(&bs->settings, settings, sizeof(bot_settings_t)); - bs->client = client; //need to know the client number before doing personality stuff + bs->client = client; // need to know the client number before doing personality stuff - //initialize weapon weight defaults.. + // initialize weapon weight defaults.. bs->botWeaponWeights[WP_NONE] = 0; bs->botWeaponWeights[WP_STUN_BATON] = 1; bs->botWeaponWeights[WP_SABER] = 10; @@ -885,15 +818,14 @@ int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean resta BotUtilizePersonality(bs); - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { bs->botWeaponWeights[WP_SABER] = 13; } - //allocate a goal state + // allocate a goal state bs->gs = trap->BotAllocGoalState(client); - //allocate a weapon state + // allocate a weapon state bs->ws = trap->BotAllocWeaponState(); bs->inuse = qtrue; @@ -903,11 +835,10 @@ int BotAISetupClient(int client, struct bot_settings_s *settings, qboolean resta bs->ms = trap->BotAllocMoveState(); numbots++; - //NOTE: reschedule the bot thinking + // NOTE: reschedule the bot thinking BotScheduleBotThink(); - if (PlayersInGame()) - { //don't talk to yourself + if (PlayersInGame()) { // don't talk to yourself BotDoChat(bs, "GeneralGreetings", 0); } @@ -924,23 +855,23 @@ int BotAIShutdownClient(int client, qboolean restart) { bs = botstates[client]; if (!bs || !bs->inuse) { - //BotAI_Print(PRT_ERROR, "BotAIShutdownClient: client %d already shutdown\n", client); + // BotAI_Print(PRT_ERROR, "BotAIShutdownClient: client %d already shutdown\n", client); return qfalse; } trap->BotFreeMoveState(bs->ms); - //free the goal state` + // free the goal state` trap->BotFreeGoalState(bs->gs); - //free the weapon weights + // free the weapon weights trap->BotFreeWeaponState(bs->ws); // - //clear the bot state + // clear the bot state memset(bs, 0, sizeof(bot_state_t)); - //set the inuse flag to qfalse + // set the inuse flag to qfalse bs->inuse = qfalse; - //there's one bot less + // there's one bot less numbots--; - //everything went ok + // everything went ok return qtrue; } @@ -956,10 +887,10 @@ void BotResetState(bot_state_t *bs) { int client, entitynum, inuse; int movestate, goalstate, weaponstate; bot_settings_t settings; - playerState_t ps; //current player state + playerState_t ps; // current player state float entergame_time; - //save some things that should not be reset here + // save some things that should not be reset here memcpy(&settings, &bs->settings, sizeof(bot_settings_t)); memcpy(&ps, &bs->cur_ps, sizeof(playerState_t)); inuse = bs->inuse; @@ -969,9 +900,9 @@ void BotResetState(bot_state_t *bs) { goalstate = bs->gs; weaponstate = bs->ws; entergame_time = bs->entergame_time; - //reset the whole state + // reset the whole state memset(bs, 0, sizeof(bot_state_t)); - //copy back some state stuff that should not be reset + // copy back some state stuff that should not be reset bs->ms = movestate; bs->gs = goalstate; bs->ws = weaponstate; @@ -981,12 +912,17 @@ void BotResetState(bot_state_t *bs) { bs->client = client; bs->entitynum = entitynum; bs->entergame_time = entergame_time; - //reset several states - if (bs->ms) trap->BotResetMoveState(bs->ms); - if (bs->gs) trap->BotResetGoalState(bs->gs); - if (bs->ws) trap->BotResetWeaponState(bs->ws); - if (bs->gs) trap->BotResetAvoidGoals(bs->gs); - if (bs->ms) trap->BotResetAvoidReach(bs->ms); + // reset several states + if (bs->ms) + trap->BotResetMoveState(bs->ms); + if (bs->gs) + trap->BotResetGoalState(bs->gs); + if (bs->ws) + trap->BotResetWeaponState(bs->ws); + if (bs->gs) + trap->BotResetAvoidGoals(bs->gs); + if (bs->ms) + trap->BotResetAvoidReach(bs->ms); } /* @@ -994,12 +930,12 @@ void BotResetState(bot_state_t *bs) { BotAILoadMap ============== */ -int BotAILoadMap( int restart ) { - int i; +int BotAILoadMap(int restart) { + int i; for (i = 0; i < MAX_CLIENTS; i++) { if (botstates[i] && botstates[i]->inuse) { - BotResetState( botstates[i] ); + BotResetState(botstates[i]); botstates[i]->setupcount = 4; } } @@ -1007,43 +943,36 @@ int BotAILoadMap( int restart ) { return qtrue; } -//rww - bot ai +// rww - bot ai -//standard visibility check -int OrgVisible(vec3_t org1, vec3_t org2, int ignore) -{ +// standard visibility check +int OrgVisible(vec3_t org1, vec3_t org2, int ignore) { trace_t tr; - trap->Trace(&tr, org1, NULL, NULL, org2, ignore, MASK_SOLID, qfalse, 0, 0 ); + trap->Trace(&tr, org1, NULL, NULL, org2, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 1; } return 0; } -//special waypoint visibility check -int WPOrgVisible(gentity_t *bot, vec3_t org1, vec3_t org2, int ignore) -{ +// special waypoint visibility check +int WPOrgVisible(gentity_t *bot, vec3_t org1, vec3_t org2, int ignore) { trace_t tr; gentity_t *ownent; trap->Trace(&tr, org1, NULL, NULL, org2, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { trap->Trace(&tr, org1, NULL, NULL, org2, ignore, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum != ENTITYNUM_NONE && g_entities[tr.entityNum].s.eType == ET_SPECIAL) - { - if (g_entities[tr.entityNum].parent && g_entities[tr.entityNum].parent->client) - { + if (tr.fraction != 1 && tr.entityNum != ENTITYNUM_NONE && g_entities[tr.entityNum].s.eType == ET_SPECIAL) { + if (g_entities[tr.entityNum].parent && g_entities[tr.entityNum].parent->client) { ownent = g_entities[tr.entityNum].parent; - if (OnSameTeam(bot, ownent) || bot->s.number == ownent->s.number) - { + if (OnSameTeam(bot, ownent) || bot->s.number == ownent->s.number) { return 1; } } @@ -1056,33 +985,27 @@ int WPOrgVisible(gentity_t *bot, vec3_t org1, vec3_t org2, int ignore) return 0; } -//visibility check with hull trace -int OrgVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) -{ +// visibility check with hull trace +int OrgVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) { trace_t tr; - if (RMG.integer) - { + if (RMG.integer) { trap->Trace(&tr, org1, NULL, NULL, org2, ignore, MASK_SOLID, qfalse, 0, 0); - } - else - { + } else { trap->Trace(&tr, org1, mins, maxs, org2, ignore, MASK_SOLID, qfalse, 0, 0); } - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { return 1; } return 0; } -//see if there's a func_* ent under the given pos. -//kind of badly done, but this shouldn't happen -//often. -int CheckForFunc(vec3_t org, int ignore) -{ +// see if there's a func_* ent under the given pos. +// kind of badly done, but this shouldn't happen +// often. +int CheckForFunc(vec3_t org, int ignore) { gentity_t *fent; vec3_t under; trace_t tr; @@ -1093,36 +1016,30 @@ int CheckForFunc(vec3_t org, int ignore) trap->Trace(&tr, org, NULL, NULL, under, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 0; } fent = &g_entities[tr.entityNum]; - if (!fent) - { + if (!fent) { return 0; } - if (strstr(fent->classname, "func_")) - { - return 1; //there's a func brush here + if (strstr(fent->classname, "func_")) { + return 1; // there's a func brush here } return 0; } -//perform pvs check based on rmg or not -qboolean BotPVSCheck( const vec3_t p1, const vec3_t p2 ) -{ - if (RMG.integer && bot_pvstype.integer) - { +// perform pvs check based on rmg or not +qboolean BotPVSCheck(const vec3_t p1, const vec3_t p2) { + if (RMG.integer && bot_pvstype.integer) { vec3_t subPoint; VectorSubtract(p1, p2, subPoint); - if (VectorLength(subPoint) > 5000) - { + if (VectorLength(subPoint) > 5000) { return qfalse; } return qtrue; @@ -1131,9 +1048,8 @@ qboolean BotPVSCheck( const vec3_t p1, const vec3_t p2 ) return trap->InPVS(p1, p2); } -//get the index to the nearest visible waypoint in the global trail -int GetNearestVisibleWP(vec3_t org, int ignore) -{ +// get the index to the nearest visible waypoint in the global trail +int GetNearestVisibleWP(vec3_t org, int ignore) { int i; float bestdist; float flLen; @@ -1141,14 +1057,11 @@ int GetNearestVisibleWP(vec3_t org, int ignore) vec3_t a, mins, maxs; i = 0; - if (RMG.integer) - { + if (RMG.integer) { bestdist = 300; - } - else - { - bestdist = 800;//99999; - //don't trace over 800 units away to avoid GIANT HORRIBLE SPEED HITS ^_^ + } else { + bestdist = 800; // 99999; + // don't trace over 800 units away to avoid GIANT HORRIBLE SPEED HITS ^_^ } bestindex = -1; @@ -1159,15 +1072,12 @@ int GetNearestVisibleWP(vec3_t org, int ignore) maxs[1] = 15; maxs[2] = 1; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { VectorSubtract(org, gWPArray[i]->origin, a); flLen = VectorLength(a); - if (flLen < bestdist && (RMG.integer || BotPVSCheck(org, gWPArray[i]->origin)) && OrgVisibleBox(org, mins, maxs, gWPArray[i]->origin, ignore)) - { + if (flLen < bestdist && (RMG.integer || BotPVSCheck(org, gWPArray[i]->origin)) && OrgVisibleBox(org, mins, maxs, gWPArray[i]->origin, ignore)) { bestdist = flLen; bestindex = i; } @@ -1179,84 +1089,69 @@ int GetNearestVisibleWP(vec3_t org, int ignore) return bestindex; } -//wpDirection -//0 == FORWARD -//1 == BACKWARD +// wpDirection +// 0 == FORWARD +// 1 == BACKWARD -//see if this is a valid waypoint to pick up in our -//current state (whatever that may be) -int PassWayCheck(bot_state_t *bs, int windex) -{ - if (!gWPArray[windex] || !gWPArray[windex]->inuse) - { //bad point index +// see if this is a valid waypoint to pick up in our +// current state (whatever that may be) +int PassWayCheck(bot_state_t *bs, int windex) { + if (!gWPArray[windex] || !gWPArray[windex]->inuse) { // bad point index return 0; } - if (RMG.integer) - { - if ((gWPArray[windex]->flags & WPFLAG_RED_FLAG) || - (gWPArray[windex]->flags & WPFLAG_BLUE_FLAG)) - { //red or blue flag, we'd like to get here + if (RMG.integer) { + if ((gWPArray[windex]->flags & WPFLAG_RED_FLAG) || (gWPArray[windex]->flags & WPFLAG_BLUE_FLAG)) { // red or blue flag, we'd like to get here return 1; } } - if (bs->wpDirection && (gWPArray[windex]->flags & WPFLAG_ONEWAY_FWD)) - { //we're not travelling in a direction on the trail that will allow us to pass this point + if (bs->wpDirection && + (gWPArray[windex]->flags & WPFLAG_ONEWAY_FWD)) { // we're not travelling in a direction on the trail that will allow us to pass this point return 0; - } - else if (!bs->wpDirection && (gWPArray[windex]->flags & WPFLAG_ONEWAY_BACK)) - { //we're not travelling in a direction on the trail that will allow us to pass this point + } else if (!bs->wpDirection && + (gWPArray[windex]->flags & WPFLAG_ONEWAY_BACK)) { // we're not travelling in a direction on the trail that will allow us to pass this point return 0; } - if (bs->wpCurrent && gWPArray[windex]->forceJumpTo && - gWPArray[windex]->origin[2] > (bs->wpCurrent->origin[2]+64) && - bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION] < gWPArray[windex]->forceJumpTo) - { //waypoint requires force jump level greater than our current one to pass + if (bs->wpCurrent && gWPArray[windex]->forceJumpTo && gWPArray[windex]->origin[2] > (bs->wpCurrent->origin[2] + 64) && + bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION] < + gWPArray[windex]->forceJumpTo) { // waypoint requires force jump level greater than our current one to pass return 0; } return 1; } -//tally up the distance between two waypoints -float TotalTrailDistance(int start, int end, bot_state_t *bs) -{ +// tally up the distance between two waypoints +float TotalTrailDistance(int start, int end, bot_state_t *bs) { int beginat; int endat; float distancetotal; distancetotal = 0; - if (start > end) - { + if (start > end) { beginat = end; endat = start; - } - else - { + } else { beginat = start; endat = end; } - while (beginat < endat) - { - if (beginat >= gWPNum || !gWPArray[beginat] || !gWPArray[beginat]->inuse) - { //invalid waypoint index + while (beginat < endat) { + if (beginat >= gWPNum || !gWPArray[beginat] || !gWPArray[beginat]->inuse) { // invalid waypoint index return -1; } - if (!RMG.integer) - { + if (!RMG.integer) { if ((end > start && gWPArray[beginat]->flags & WPFLAG_ONEWAY_BACK) || - (start > end && gWPArray[beginat]->flags & WPFLAG_ONEWAY_FWD)) - { //a one-way point, this means this path cannot be travelled to the final point + (start > end && gWPArray[beginat]->flags & WPFLAG_ONEWAY_FWD)) { // a one-way point, this means this path cannot be travelled to the final point return -1; } } -#if 0 //disabled force jump checks for now +#if 0 // disabled force jump checks for now if (gWPArray[beginat]->forceJumpTo) { if (gWPArray[beginat-1] && gWPArray[beginat-1]->origin[2]+64 < gWPArray[beginat]->origin[2]) @@ -1289,10 +1184,9 @@ float TotalTrailDistance(int start, int end, bot_state_t *bs) return distancetotal; } -//see if there's a route shorter than our current one to get -//to the final destination we currently desire -void CheckForShorterRoutes(bot_state_t *bs, int newwpindex) -{ +// see if there's a route shorter than our current one to get +// to the final destination we currently desire +void CheckForShorterRoutes(bot_state_t *bs, int newwpindex) { float bestlen; float checklen; int bestindex; @@ -1302,54 +1196,42 @@ void CheckForShorterRoutes(bot_state_t *bs, int newwpindex) i = 0; fj = 0; - if (!bs->wpDestination) - { + if (!bs->wpDestination) { return; } - //set our traversal direction based on the index of the point - if (newwpindex < bs->wpDestination->index) - { + // set our traversal direction based on the index of the point + if (newwpindex < bs->wpDestination->index) { bs->wpDirection = 0; - } - else if (newwpindex > bs->wpDestination->index) - { + } else if (newwpindex > bs->wpDestination->index) { bs->wpDirection = 1; } - //can't switch again yet - if (bs->wpSwitchTime > level.time) - { + // can't switch again yet + if (bs->wpSwitchTime > level.time) { return; } - //no neighboring points to check off of - if (!gWPArray[newwpindex]->neighbornum) - { + // no neighboring points to check off of + if (!gWPArray[newwpindex]->neighbornum) { return; } - //get the trail distance for our wp + // get the trail distance for our wp bestindex = newwpindex; bestlen = TotalTrailDistance(newwpindex, bs->wpDestination->index, bs); - while (i < gWPArray[newwpindex]->neighbornum) - { //now go through the neighbors and check the distance to the desired point from each neighbor + while (i < gWPArray[newwpindex]->neighbornum) { // now go through the neighbors and check the distance to the desired point from each neighbor checklen = TotalTrailDistance(gWPArray[newwpindex]->neighbors[i].num, bs->wpDestination->index, bs); - if (checklen < bestlen-64 || bestlen == -1) - { //this path covers less distance, let's take it instead - if (bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION] >= gWPArray[newwpindex]->neighbors[i].forceJumpTo) - { + if (checklen < bestlen - 64 || bestlen == -1) { // this path covers less distance, let's take it instead + if (bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION] >= gWPArray[newwpindex]->neighbors[i].forceJumpTo) { bestlen = checklen; bestindex = gWPArray[newwpindex]->neighbors[i].num; - if (gWPArray[newwpindex]->neighbors[i].forceJumpTo) - { + if (gWPArray[newwpindex]->neighbors[i].forceJumpTo) { fj = gWPArray[newwpindex]->neighbors[i].forceJumpTo; - } - else - { + } else { fj = 0; } } @@ -1358,20 +1240,18 @@ void CheckForShorterRoutes(bot_state_t *bs, int newwpindex) i++; } - if (bestindex != newwpindex && bestindex != -1) - { //we found a path we want to switch to, let's do it + if (bestindex != newwpindex && bestindex != -1) { // we found a path we want to switch to, let's do it bs->wpCurrent = gWPArray[bestindex]; bs->wpSwitchTime = level.time + 3000; - if (fj) - { //do we have to force jump to get to this neighbor? + if (fj) { // do we have to force jump to get to this neighbor? #ifndef FORCEJUMP_INSTANTMETHOD bs->forceJumpChargeTime = level.time + 1000; bs->beStill = level.time + 1000; bs->forceJumping = bs->forceJumpChargeTime; #else bs->beStill = level.time + 500; - bs->jumpTime = level.time + fj*1200; + bs->jumpTime = level.time + fj * 1200; bs->jDelay = level.time + 200; bs->forceJumping = bs->jumpTime; #endif @@ -1379,55 +1259,44 @@ void CheckForShorterRoutes(bot_state_t *bs, int newwpindex) } } -//check for flags on the waypoint we're currently travelling to -//and perform the desired behavior based on the flag -void WPConstantRoutine(bot_state_t *bs) -{ - if (!bs->wpCurrent) - { +// check for flags on the waypoint we're currently travelling to +// and perform the desired behavior based on the flag +void WPConstantRoutine(bot_state_t *bs) { + if (!bs->wpCurrent) { return; } - if (bs->wpCurrent->flags & WPFLAG_DUCK) - { //duck while travelling to this point + if (bs->wpCurrent->flags & WPFLAG_DUCK) { // duck while travelling to this point bs->duckTime = level.time + 100; } #ifndef FORCEJUMP_INSTANTMETHOD - if (bs->wpCurrent->flags & WPFLAG_JUMP) - { //jump while travelling to this point - float heightDif = (bs->wpCurrent->origin[2] - bs->origin[2]+16); + if (bs->wpCurrent->flags & WPFLAG_JUMP) { // jump while travelling to this point + float heightDif = (bs->wpCurrent->origin[2] - bs->origin[2] + 16); - if (bs->origin[2]+16 >= bs->wpCurrent->origin[2]) - { //don't need to jump, we're already higher than this point + if (bs->origin[2] + 16 >= bs->wpCurrent->origin[2]) { // don't need to jump, we're already higher than this point heightDif = 0; } - if (heightDif > 40 && (bs->cur_ps.fd.forcePowersKnown & (1 << FP_LEVITATION)) && (bs->cur_ps.fd.forceJumpCharge < (forceJumpStrength[bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION]]-100) || bs->cur_ps.groundEntityNum == ENTITYNUM_NONE)) - { //alright, let's jump + if (heightDif > 40 && (bs->cur_ps.fd.forcePowersKnown & (1 << FP_LEVITATION)) && + (bs->cur_ps.fd.forceJumpCharge < (forceJumpStrength[bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION]] - 100) || + bs->cur_ps.groundEntityNum == ENTITYNUM_NONE)) { // alright, let's jump bs->forceJumpChargeTime = level.time + 1000; - if (bs->cur_ps.groundEntityNum != ENTITYNUM_NONE && bs->jumpPrep < (level.time-300)) - { + if (bs->cur_ps.groundEntityNum != ENTITYNUM_NONE && bs->jumpPrep < (level.time - 300)) { bs->jumpPrep = level.time + 700; } bs->beStill = level.time + 300; bs->jumpTime = 0; - if (bs->wpSeenTime < (level.time + 600)) - { + if (bs->wpSeenTime < (level.time + 600)) { bs->wpSeenTime = level.time + 600; } - } - else if (heightDif > 64 && !(bs->cur_ps.fd.forcePowersKnown & (1 << FP_LEVITATION))) - { //this point needs force jump to reach and we don't have it - //Kill the current point and turn around + } else if (heightDif > 64 && !(bs->cur_ps.fd.forcePowersKnown & (1 << FP_LEVITATION))) { // this point needs force jump to reach and we don't have it + // Kill the current point and turn around bs->wpCurrent = NULL; - if (bs->wpDirection) - { + if (bs->wpDirection) { bs->wpDirection = 0; - } - else - { + } else { bs->wpDirection = 1; } @@ -1436,158 +1305,126 @@ void WPConstantRoutine(bot_state_t *bs) } #endif - if (bs->wpCurrent->forceJumpTo) - { + if (bs->wpCurrent->forceJumpTo) { #ifdef FORCEJUMP_INSTANTMETHOD - if (bs->origin[2]+16 < bs->wpCurrent->origin[2]) - { + if (bs->origin[2] + 16 < bs->wpCurrent->origin[2]) { bs->jumpTime = level.time + 100; } #else - if (bs->cur_ps.fd.forceJumpCharge < (forceJumpStrength[bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION]]-100)) - { + if (bs->cur_ps.fd.forceJumpCharge < (forceJumpStrength[bs->cur_ps.fd.forcePowerLevel[FP_LEVITATION]] - 100)) { bs->forceJumpChargeTime = level.time + 200; } #endif } } -//check if our ctf state is to guard the base -qboolean BotCTFGuardDuty(bot_state_t *bs) -{ - if (level.gametype != GT_CTF && level.gametype != GT_CTY) - { +// check if our ctf state is to guard the base +qboolean BotCTFGuardDuty(bot_state_t *bs) { + if (level.gametype != GT_CTF && level.gametype != GT_CTY) { return qfalse; } - if (bs->ctfState == CTFSTATE_DEFENDER) - { + if (bs->ctfState == CTFSTATE_DEFENDER) { return qtrue; } return qfalse; } -//when we reach the waypoint we are travelling to, -//this function will be called. We will perform any -//checks for flags on the current wp and activate -//any "touch" events based on that. -void WPTouchRoutine(bot_state_t *bs) -{ +// when we reach the waypoint we are travelling to, +// this function will be called. We will perform any +// checks for flags on the current wp and activate +// any "touch" events based on that. +void WPTouchRoutine(bot_state_t *bs) { int lastNum; - if (!bs->wpCurrent) - { + if (!bs->wpCurrent) { return; } bs->wpTravelTime = level.time + 10000; - if (bs->wpCurrent->flags & WPFLAG_NOMOVEFUNC) - { //don't try to use any nearby map objects for a little while + if (bs->wpCurrent->flags & WPFLAG_NOMOVEFUNC) { // don't try to use any nearby map objects for a little while bs->noUseTime = level.time + 4000; } #ifdef FORCEJUMP_INSTANTMETHOD - if ((bs->wpCurrent->flags & WPFLAG_JUMP) && bs->wpCurrent->forceJumpTo) - { //jump if we're flagged to but not if this indicates a force jump point. Force jumping is - //handled elsewhere. + if ((bs->wpCurrent->flags & WPFLAG_JUMP) && bs->wpCurrent->forceJumpTo) { // jump if we're flagged to but not if this indicates a force jump point. Force + // jumping is handled elsewhere. bs->jumpTime = level.time + 100; } #else - if ((bs->wpCurrent->flags & WPFLAG_JUMP) && !bs->wpCurrent->forceJumpTo) - { //jump if we're flagged to but not if this indicates a force jump point. Force jumping is - //handled elsewhere. + if ((bs->wpCurrent->flags & WPFLAG_JUMP) && !bs->wpCurrent->forceJumpTo) { // jump if we're flagged to but not if this indicates a force jump point. Force + // jumping is handled elsewhere. bs->jumpTime = level.time + 100; } #endif - if (bs->isCamper && bot_camp.integer && (BotIsAChickenWuss(bs) || BotCTFGuardDuty(bs) || bs->isCamper == 2) && ((bs->wpCurrent->flags & WPFLAG_SNIPEORCAMP) || (bs->wpCurrent->flags & WPFLAG_SNIPEORCAMPSTAND)) && - bs->cur_ps.weapon != WP_SABER && bs->cur_ps.weapon != WP_MELEE && bs->cur_ps.weapon != WP_STUN_BATON) - { //if we're a camper and a chicken then camp - if (bs->wpDirection) - { - lastNum = bs->wpCurrent->index+1; - } - else - { - lastNum = bs->wpCurrent->index-1; + if (bs->isCamper && bot_camp.integer && (BotIsAChickenWuss(bs) || BotCTFGuardDuty(bs) || bs->isCamper == 2) && + ((bs->wpCurrent->flags & WPFLAG_SNIPEORCAMP) || (bs->wpCurrent->flags & WPFLAG_SNIPEORCAMPSTAND)) && bs->cur_ps.weapon != WP_SABER && + bs->cur_ps.weapon != WP_MELEE && bs->cur_ps.weapon != WP_STUN_BATON) { // if we're a camper and a chicken then camp + if (bs->wpDirection) { + lastNum = bs->wpCurrent->index + 1; + } else { + lastNum = bs->wpCurrent->index - 1; } - if (gWPArray[lastNum] && gWPArray[lastNum]->inuse && gWPArray[lastNum]->index && bs->isCamping < level.time) - { - bs->isCamping = level.time + rand()%15000 + 30000; + if (gWPArray[lastNum] && gWPArray[lastNum]->inuse && gWPArray[lastNum]->index && bs->isCamping < level.time) { + bs->isCamping = level.time + rand() % 15000 + 30000; bs->wpCamping = bs->wpCurrent; bs->wpCampingTo = gWPArray[lastNum]; - if (bs->wpCurrent->flags & WPFLAG_SNIPEORCAMPSTAND) - { + if (bs->wpCurrent->flags & WPFLAG_SNIPEORCAMPSTAND) { bs->campStanding = qtrue; - } - else - { + } else { bs->campStanding = qfalse; } } - } - else if ((bs->cur_ps.weapon == WP_SABER || bs->cur_ps.weapon == WP_STUN_BATON || bs->cur_ps.weapon == WP_MELEE) && - bs->isCamping > level.time) - { //don't snipe/camp with a melee weapon, that would be silly + } else if ((bs->cur_ps.weapon == WP_SABER || bs->cur_ps.weapon == WP_STUN_BATON || bs->cur_ps.weapon == WP_MELEE) && + bs->isCamping > level.time) { // don't snipe/camp with a melee weapon, that would be silly bs->isCamping = 0; bs->wpCampingTo = NULL; bs->wpCamping = NULL; } - if (bs->wpDestination) - { - if (bs->wpCurrent->index == bs->wpDestination->index) - { + if (bs->wpDestination) { + if (bs->wpCurrent->index == bs->wpDestination->index) { bs->wpDestination = NULL; - if (bs->runningLikeASissy) - { //this obviously means we're scared and running, so we'll want to keep our navigational priorities less delayed + if (bs->runningLikeASissy) { // this obviously means we're scared and running, so we'll want to keep our navigational priorities less delayed bs->destinationGrabTime = level.time + 500; - } - else - { + } else { bs->destinationGrabTime = level.time + 3500; } - } - else - { + } else { CheckForShorterRoutes(bs, bs->wpCurrent->index); } } } -//could also slowly lerp toward, but for now -//just copying straight over. -void MoveTowardIdealAngles(bot_state_t *bs) -{ - VectorCopy(bs->goalAngles, bs->ideal_viewangles); -} +// could also slowly lerp toward, but for now +// just copying straight over. +void MoveTowardIdealAngles(bot_state_t *bs) { VectorCopy(bs->goalAngles, bs->ideal_viewangles); } #define BOT_STRAFE_AVOIDANCE #ifdef BOT_STRAFE_AVOIDANCE -#define STRAFEAROUND_RIGHT 1 -#define STRAFEAROUND_LEFT 2 - -//do some trace checks for strafing to get an idea of where we -//are and if we should move to avoid obstacles. -int BotTrace_Strafe(bot_state_t *bs, vec3_t traceto) -{ - vec3_t playerMins = {-15, -15, /*DEFAULT_MINS_2*/-8}; +#define STRAFEAROUND_RIGHT 1 +#define STRAFEAROUND_LEFT 2 + +// do some trace checks for strafing to get an idea of where we +// are and if we should move to avoid obstacles. +int BotTrace_Strafe(bot_state_t *bs, vec3_t traceto) { + vec3_t playerMins = {-15, -15, /*DEFAULT_MINS_2*/ -8}; vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; vec3_t from, to; vec3_t dirAng, dirDif; vec3_t forward, right; trace_t tr; - if (bs->cur_ps.groundEntityNum == ENTITYNUM_NONE) - { //don't do this in the air, it can be.. dangerous. + if (bs->cur_ps.groundEntityNum == ENTITYNUM_NONE) { // don't do this in the air, it can be.. dangerous. return 0; } @@ -1596,8 +1433,8 @@ int BotTrace_Strafe(bot_state_t *bs, vec3_t traceto) vectoangles(dirAng, dirAng); if (AngleDifference(bs->viewangles[YAW], dirAng[YAW]) > 60 || - AngleDifference(bs->viewangles[YAW], dirAng[YAW]) < -60) - { //If we aren't facing the direction we're going here, then we've got enough excuse to be too stupid to strafe around anyway + AngleDifference(bs->viewangles[YAW], dirAng[YAW]) < + -60) { // If we aren't facing the direction we're going here, then we've got enough excuse to be too stupid to strafe around anyway return 0; } @@ -1610,46 +1447,43 @@ int BotTrace_Strafe(bot_state_t *bs, vec3_t traceto) AngleVectors(dirDif, forward, 0, 0); - to[0] = from[0] + forward[0]*32; - to[1] = from[1] + forward[1]*32; - to[2] = from[2] + forward[2]*32; + to[0] = from[0] + forward[0] * 32; + to[1] = from[1] + forward[1] * 32; + to[2] = from[2] + forward[2] * 32; trap->Trace(&tr, from, playerMins, playerMaxs, to, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 0; } AngleVectors(dirAng, 0, right, 0); - from[0] += right[0]*32; - from[1] += right[1]*32; - from[2] += right[2]*16; + from[0] += right[0] * 32; + from[1] += right[1] * 32; + from[2] += right[2] * 16; - to[0] += right[0]*32; - to[1] += right[1]*32; - to[2] += right[2]*32; + to[0] += right[0] * 32; + to[1] += right[1] * 32; + to[2] += right[2] * 32; trap->Trace(&tr, from, playerMins, playerMaxs, to, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return STRAFEAROUND_RIGHT; } - from[0] -= right[0]*64; - from[1] -= right[1]*64; - from[2] -= right[2]*64; + from[0] -= right[0] * 64; + from[1] -= right[1] * 64; + from[2] -= right[2] * 64; - to[0] -= right[0]*64; - to[1] -= right[1]*64; - to[2] -= right[2]*64; + to[0] -= right[0] * 64; + to[1] -= right[1] * 64; + to[2] -= right[2] * 64; trap->Trace(&tr, from, playerMins, playerMaxs, to, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return STRAFEAROUND_LEFT; } @@ -1657,10 +1491,9 @@ int BotTrace_Strafe(bot_state_t *bs, vec3_t traceto) } #endif -//Similar to the trace check, but we want to trace to see -//if there's anything we can jump over. -int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) -{ +// Similar to the trace check, but we want to trace to see +// if there's anything we can jump over. +int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) { vec3_t mins, maxs, a, fwd, traceto_mod, tracefrom_mod; trace_t tr; int orTr; @@ -1670,9 +1503,9 @@ int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) AngleVectors(a, fwd, NULL, NULL); - traceto_mod[0] = bs->origin[0] + fwd[0]*4; - traceto_mod[1] = bs->origin[1] + fwd[1]*4; - traceto_mod[2] = bs->origin[2] + fwd[2]*4; + traceto_mod[0] = bs->origin[0] + fwd[0] * 4; + traceto_mod[1] = bs->origin[1] + fwd[1] * 4; + traceto_mod[2] = bs->origin[2] + fwd[2] * 4; mins[0] = -15; mins[1] = -15; @@ -1683,8 +1516,7 @@ int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) trap->Trace(&tr, bs->origin, mins, maxs, traceto_mod, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 0; } @@ -1704,15 +1536,13 @@ int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) trap->Trace(&tr, tracefrom_mod, mins, maxs, traceto_mod, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { - if (orTr >= 0 && orTr < MAX_CLIENTS && botstates[orTr] && botstates[orTr]->jumpTime > level.time) - { - return 0; //so bots don't try to jump over each other at the same time + if (tr.fraction == 1) { + if (orTr >= 0 && orTr < MAX_CLIENTS && botstates[orTr] && botstates[orTr]->jumpTime > level.time) { + return 0; // so bots don't try to jump over each other at the same time } - if (bs->currentEnemy && bs->currentEnemy->s.number == orTr && (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER || BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE)) - { + if (bs->currentEnemy && bs->currentEnemy->s.number == orTr && + (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER || BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE)) { return 0; } @@ -1722,9 +1552,8 @@ int BotTrace_Jump(bot_state_t *bs, vec3_t traceto) return 0; } -//And yet another check to duck under any obstacles. -int BotTrace_Duck(bot_state_t *bs, vec3_t traceto) -{ +// And yet another check to duck under any obstacles. +int BotTrace_Duck(bot_state_t *bs, vec3_t traceto) { vec3_t mins, maxs, a, fwd, traceto_mod, tracefrom_mod; trace_t tr; @@ -1733,9 +1562,9 @@ int BotTrace_Duck(bot_state_t *bs, vec3_t traceto) AngleVectors(a, fwd, NULL, NULL); - traceto_mod[0] = bs->origin[0] + fwd[0]*4; - traceto_mod[1] = bs->origin[1] + fwd[1]*4; - traceto_mod[2] = bs->origin[2] + fwd[2]*4; + traceto_mod[0] = bs->origin[0] + fwd[0] * 4; + traceto_mod[1] = bs->origin[1] + fwd[1] * 4; + traceto_mod[2] = bs->origin[2] + fwd[2] * 4; mins[0] = -15; mins[1] = -15; @@ -1746,15 +1575,14 @@ int BotTrace_Duck(bot_state_t *bs, vec3_t traceto) trap->Trace(&tr, bs->origin, mins, maxs, traceto_mod, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1) - { + if (tr.fraction != 1) { return 0; } VectorCopy(bs->origin, tracefrom_mod); - tracefrom_mod[2] += 31;//33; - traceto_mod[2] += 31;//33; + tracefrom_mod[2] += 31; // 33; + traceto_mod[2] += 31; // 33; mins[0] = -15; mins[1] = -15; @@ -1765,115 +1593,94 @@ int BotTrace_Duck(bot_state_t *bs, vec3_t traceto) trap->Trace(&tr, tracefrom_mod, mins, maxs, traceto_mod, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1) - { + if (tr.fraction != 1) { return 1; } return 0; } -//check of the potential enemy is a valid one -int PassStandardEnemyChecks(bot_state_t *bs, gentity_t *en) -{ - if (!bs || !en) - { //shouldn't happen +// check of the potential enemy is a valid one +int PassStandardEnemyChecks(bot_state_t *bs, gentity_t *en) { + if (!bs || !en) { // shouldn't happen return 0; } - if (!en->client) - { //not a client, don't care about him + if (!en->client) { // not a client, don't care about him return 0; } - if (en->health < 1) - { //he's already dead + if (en->health < 1) { // he's already dead return 0; } - if (!en->takedamage) - { //a client that can't take damage? + if (!en->takedamage) { // a client that can't take damage? return 0; } if (bs->doingFallback && - (gLevelFlags & LEVELFLAG_IGNOREINFALLBACK)) - { //we screwed up in our nav routines somewhere and we've reverted to a fallback state to - //try to get back on the trail. If the level specifies to ignore enemies in this state, - //then ignore them. + (gLevelFlags & LEVELFLAG_IGNOREINFALLBACK)) { // we screwed up in our nav routines somewhere and we've reverted to a fallback state to + // try to get back on the trail. If the level specifies to ignore enemies in this state, + // then ignore them. return 0; } - if (en->client->ps.pm_type == PM_INTERMISSION || - en->client->ps.pm_type == PM_SPECTATOR || - en->client->sess.sessionTeam == TEAM_SPECTATOR) - { //don't attack spectators + if (en->client->ps.pm_type == PM_INTERMISSION || en->client->ps.pm_type == PM_SPECTATOR || + en->client->sess.sessionTeam == TEAM_SPECTATOR) { // don't attack spectators return 0; } - if (!en->client->pers.connected) - { //a "zombie" client? + if (!en->client->pers.connected) { // a "zombie" client? return 0; } - if (!en->s.solid) - { //shouldn't happen + if (!en->s.solid) { // shouldn't happen return 0; } - if (bs->client == en->s.number) - { //don't attack yourself + if (bs->client == en->s.number) { // don't attack yourself return 0; } - if (OnSameTeam(&g_entities[bs->client], en)) - { //don't attack teammates + if (OnSameTeam(&g_entities[bs->client], en)) { // don't attack teammates return 0; } - if (BotMindTricked(bs->client, en->s.number)) - { - if (bs->currentEnemy && bs->currentEnemy->s.number == en->s.number) - { //if mindtricked by this enemy, then be less "aware" of them, even though - //we know they're there. + if (BotMindTricked(bs->client, en->s.number)) { + if (bs->currentEnemy && bs->currentEnemy->s.number == en->s.number) { // if mindtricked by this enemy, then be less "aware" of them, even though + // we know they're there. vec3_t vs; float vLen = 0; VectorSubtract(bs->origin, en->client->ps.origin, vs); vLen = VectorLength(vs); - if (vLen > 64 /*&& (level.time - en->client->dangerTime) > 150*/) - { + if (vLen > 64 /*&& (level.time - en->client->dangerTime) > 150*/) { return 0; } } } - if (en->client->ps.duelInProgress && en->client->ps.duelIndex != bs->client) - { //don't attack duelists unless you're dueling them + if (en->client->ps.duelInProgress && en->client->ps.duelIndex != bs->client) { // don't attack duelists unless you're dueling them return 0; } - if (bs->cur_ps.duelInProgress && en->s.number != bs->cur_ps.duelIndex) - { //ditto, the other way around + if (bs->cur_ps.duelInProgress && en->s.number != bs->cur_ps.duelIndex) { // ditto, the other way around return 0; } - if (level.gametype == GT_JEDIMASTER && !en->client->ps.isJediMaster && !bs->cur_ps.isJediMaster) - { //rules for attacking non-JM in JM mode + if (level.gametype == GT_JEDIMASTER && !en->client->ps.isJediMaster && !bs->cur_ps.isJediMaster) { // rules for attacking non-JM in JM mode vec3_t vs; float vLen = 0; - if (!g_friendlyFire.integer) - { //can't harm non-JM in JM mode if FF is off + if (!g_friendlyFire.integer) { // can't harm non-JM in JM mode if FF is off return 0; } VectorSubtract(bs->origin, en->client->ps.origin, vs); vLen = VectorLength(vs); - if (vLen > 350) - { + if (vLen > 350) { return 0; } } @@ -1881,56 +1688,43 @@ int PassStandardEnemyChecks(bot_state_t *bs, gentity_t *en) return 1; } -//Notifies the bot that he has taken damage from "attacker". -void BotDamageNotification(gclient_t *bot, gentity_t *attacker) -{ +// Notifies the bot that he has taken damage from "attacker". +void BotDamageNotification(gclient_t *bot, gentity_t *attacker) { bot_state_t *bs; bot_state_t *bs_a; int i; - if (!bot || !attacker || !attacker->client) - { + if (!bot || !attacker || !attacker->client) { return; } - if (bot->ps.clientNum >= MAX_CLIENTS) - { //an NPC.. do nothing for them. + if (bot->ps.clientNum >= MAX_CLIENTS) { // an NPC.. do nothing for them. return; } - if (attacker->s.number >= MAX_CLIENTS) - { //if attacker is an npc also don't care I suppose. + if (attacker->s.number >= MAX_CLIENTS) { // if attacker is an npc also don't care I suppose. return; } bs_a = botstates[attacker->s.number]; - if (bs_a) - { //if the client attacking us is a bot as well + if (bs_a) { // if the client attacking us is a bot as well bs_a->lastAttacked = &g_entities[bot->ps.clientNum]; i = 0; - while (i < MAX_CLIENTS) - { - if (botstates[i] && - i != bs_a->client && - botstates[i]->lastAttacked == &g_entities[bot->ps.clientNum]) - { + while (i < MAX_CLIENTS) { + if (botstates[i] && i != bs_a->client && botstates[i]->lastAttacked == &g_entities[bot->ps.clientNum]) { botstates[i]->lastAttacked = NULL; } i++; } - } - else //got attacked by a real client, so no one gets rights to lastAttacked + } else // got attacked by a real client, so no one gets rights to lastAttacked { i = 0; - while (i < MAX_CLIENTS) - { - if (botstates[i] && - botstates[i]->lastAttacked == &g_entities[bot->ps.clientNum]) - { + while (i < MAX_CLIENTS) { + if (botstates[i] && botstates[i]->lastAttacked == &g_entities[bot->ps.clientNum]) { botstates[i]->lastAttacked = NULL; } @@ -1940,60 +1734,50 @@ void BotDamageNotification(gclient_t *bot, gentity_t *attacker) bs = botstates[bot->ps.clientNum]; - if (!bs) - { + if (!bs) { return; } bs->lastHurt = attacker; - if (bs->currentEnemy) - { //we don't care about the guy attacking us if we have an enemy already + if (bs->currentEnemy) { // we don't care about the guy attacking us if we have an enemy already return; } - if (!PassStandardEnemyChecks(bs, attacker)) - { //the person that hurt us is not a valid enemy + if (!PassStandardEnemyChecks(bs, attacker)) { // the person that hurt us is not a valid enemy return; } - if (PassLovedOneCheck(bs, attacker)) - { //the person that hurt us is the one we love! + if (PassLovedOneCheck(bs, attacker)) { // the person that hurt us is the one we love! bs->currentEnemy = attacker; bs->enemySeenTime = level.time + ENEMY_FORGET_MS; } } -//perform cheap "hearing" checks based on the event catching -//system -int BotCanHear(bot_state_t *bs, gentity_t *en, float endist) -{ +// perform cheap "hearing" checks based on the event catching +// system +int BotCanHear(bot_state_t *bs, gentity_t *en, float endist) { float minlen; - if (!en || !en->client) - { + if (!en || !en->client) { return 0; } - if (en && en->client && en->client->ps.otherSoundTime > level.time) - { //they made a noise in recent time + if (en && en->client && en->client->ps.otherSoundTime > level.time) { // they made a noise in recent time minlen = en->client->ps.otherSoundLen; goto checkStep; } - if (en && en->client && en->client->ps.footstepTime > level.time) - { //they made a footstep + if (en && en->client && en->client->ps.footstepTime > level.time) { // they made a footstep minlen = 256; goto checkStep; } - if (gBotEventTracker[en->s.number].eventTime < level.time) - { //no recent events to check + if (gBotEventTracker[en->s.number].eventTime < level.time) { // no recent events to check return 0; } - switch(gBotEventTracker[en->s.number].events[gBotEventTracker[en->s.number].eventSequence & (MAX_PS_EVENTS-1)]) - { //did the last event contain a sound? + switch (gBotEventTracker[en->s.number].events[gBotEventTracker[en->s.number].eventSequence & (MAX_PS_EVENTS - 1)]) { // did the last event contain a sound? case EV_GLOBAL_SOUND: minlen = 256; break; @@ -2020,30 +1804,25 @@ int BotCanHear(bot_state_t *bs, gentity_t *en, float endist) break; } checkStep: - if (BotMindTricked(bs->client, en->s.number)) - { //if mindtricked by this person, cut down on the minlen so they can't "hear" as well + if (BotMindTricked(bs->client, en->s.number)) { // if mindtricked by this person, cut down on the minlen so they can't "hear" as well minlen /= 4; } - if (endist <= minlen) - { //we heard it + if (endist <= minlen) { // we heard it return 1; } return 0; } -//check for new events -void UpdateEventTracker(void) -{ +// check for new events +void UpdateEventTracker(void) { int i; i = 0; - while (i < MAX_CLIENTS) - { - if (gBotEventTracker[i].eventSequence != level.clients[i].ps.eventSequence) - { //updated event + while (i < MAX_CLIENTS) { + if (gBotEventTracker[i].eventSequence != level.clients[i].ps.eventSequence) { // updated event gBotEventTracker[i].eventSequence = level.clients[i].ps.eventSequence; gBotEventTracker[i].events[0] = level.clients[i].ps.events[0]; gBotEventTracker[i].events[1] = level.clients[i].ps.events[1]; @@ -2054,42 +1833,30 @@ void UpdateEventTracker(void) } } -//check if said angles are within our fov -int InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles) -{ +// check if said angles are within our fov +int InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles) { int i; float diff, angle; - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { angle = AngleMod(viewangles[i]); angles[i] = AngleMod(angles[i]); diff = angles[i] - angle; - if (angles[i] > angle) - { - if (diff > 180.0) - { + if (angles[i] > angle) { + if (diff > 180.0) { diff -= 360.0; } - } - else - { - if (diff < -180.0) - { + } else { + if (diff < -180.0) { diff += 360.0; } } - if (diff > 0) - { - if (diff > fov * 0.5) - { + if (diff > 0) { + if (diff > fov * 0.5) { return 0; } - } - else - { - if (diff < -fov * 0.5) - { + } else { + if (diff < -fov * 0.5) { return 0; } } @@ -2097,51 +1864,40 @@ int InFieldOfVision(vec3_t viewangles, float fov, vec3_t angles) return 1; } -//We cannot hurt the ones we love. Unless of course this -//function says we can. -int PassLovedOneCheck(bot_state_t *bs, gentity_t *ent) -{ +// We cannot hurt the ones we love. Unless of course this +// function says we can. +int PassLovedOneCheck(bot_state_t *bs, gentity_t *ent) { int i; bot_state_t *loved; - if (!bs->lovednum) - { + if (!bs->lovednum) { return 1; } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { //There is no love in 1-on-1 + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // There is no love in 1-on-1 return 1; } i = 0; - if (!botstates[ent->s.number]) - { //not a bot + if (!botstates[ent->s.number]) { // not a bot return 1; } - if (!bot_attachments.integer) - { + if (!bot_attachments.integer) { return 1; } loved = botstates[ent->s.number]; - while (i < bs->lovednum) - { - if (strcmp(level.clients[loved->client].pers.netname, bs->loved[i].name) == 0) - { - if (!IsTeamplay() && bs->loved[i].level < 2) - { //if FFA and level of love is not greater than 1, just don't care + while (i < bs->lovednum) { + if (strcmp(level.clients[loved->client].pers.netname, bs->loved[i].name) == 0) { + if (!IsTeamplay() && bs->loved[i].level < 2) { // if FFA and level of love is not greater than 1, just don't care return 1; - } - else if (IsTeamplay() && !OnSameTeam(&g_entities[bs->client], &g_entities[loved->client]) && bs->loved[i].level < 2) - { //is teamplay, but not on same team and level < 2 + } else if (IsTeamplay() && !OnSameTeam(&g_entities[bs->client], &g_entities[loved->client]) && + bs->loved[i].level < 2) { // is teamplay, but not on same team and level < 2 return 1; - } - else - { + } else { return 0; } } @@ -2154,9 +1910,8 @@ int PassLovedOneCheck(bot_state_t *bs, gentity_t *ent) qboolean G_ThereIsAMaster(void); -//standard check to find a new enemy. -int ScanForEnemies(bot_state_t *bs) -{ +// standard check to find a new enemy. +int ScanForEnemies(bot_state_t *bs) { vec3_t a; float distcheck; float closest; @@ -2169,67 +1924,52 @@ int ScanForEnemies(bot_state_t *bs) i = 0; bestindex = -1; - if (bs->currentEnemy) - { //only switch to a new enemy if he's significantly closer + if (bs->currentEnemy) { // only switch to a new enemy if he's significantly closer hasEnemyDist = bs->frame_Enemy_Len; } - if (bs->currentEnemy && bs->currentEnemy->client && - bs->currentEnemy->client->ps.isJediMaster) - { //The Jedi Master must die. + if (bs->currentEnemy && bs->currentEnemy->client && bs->currentEnemy->client->ps.isJediMaster) { // The Jedi Master must die. return -1; } - if (level.gametype == GT_JEDIMASTER) - { - if (G_ThereIsAMaster() && !bs->cur_ps.isJediMaster) - { //if friendly fire is on in jedi master we can attack people that bug us - if (!g_friendlyFire.integer) - { + if (level.gametype == GT_JEDIMASTER) { + if (G_ThereIsAMaster() && !bs->cur_ps.isJediMaster) { // if friendly fire is on in jedi master we can attack people that bug us + if (!g_friendlyFire.integer) { noAttackNonJM = qtrue; - } - else - { - closest = 128; //only get mad at people if they get close enough to you to anger you, or hurt you + } else { + closest = 128; // only get mad at people if they get close enough to you to anger you, or hurt you } } } - while (i <= MAX_CLIENTS) - { - if (i != bs->client && g_entities[i].client && !OnSameTeam(&g_entities[bs->client], &g_entities[i]) && PassStandardEnemyChecks(bs, &g_entities[i]) && BotPVSCheck(g_entities[i].client->ps.origin, bs->eye) && PassLovedOneCheck(bs, &g_entities[i])) - { + while (i <= MAX_CLIENTS) { + if (i != bs->client && g_entities[i].client && !OnSameTeam(&g_entities[bs->client], &g_entities[i]) && PassStandardEnemyChecks(bs, &g_entities[i]) && + BotPVSCheck(g_entities[i].client->ps.origin, bs->eye) && PassLovedOneCheck(bs, &g_entities[i])) { VectorSubtract(g_entities[i].client->ps.origin, bs->eye, a); distcheck = VectorLength(a); vectoangles(a, a); - if (g_entities[i].client->ps.isJediMaster) - { //make us think the Jedi Master is close so we'll attack him above all + if (g_entities[i].client->ps.isJediMaster) { // make us think the Jedi Master is close so we'll attack him above all distcheck = 1; } - if (distcheck < closest && ((InFieldOfVision(bs->viewangles, 90, a) && !BotMindTricked(bs->client, i)) || BotCanHear(bs, &g_entities[i], distcheck)) && OrgVisible(bs->eye, g_entities[i].client->ps.origin, -1)) - { - if (BotMindTricked(bs->client, i)) - { - if (distcheck < 256 || (level.time - g_entities[i].client->dangerTime) < 100) - { - if (!hasEnemyDist || distcheck < (hasEnemyDist - 128)) - { //if we have an enemy, only switch to closer if he is 128+ closer to avoid flipping out - if (!noAttackNonJM || g_entities[i].client->ps.isJediMaster) - { + if (distcheck < closest && + ((InFieldOfVision(bs->viewangles, 90, a) && !BotMindTricked(bs->client, i)) || BotCanHear(bs, &g_entities[i], distcheck)) && + OrgVisible(bs->eye, g_entities[i].client->ps.origin, -1)) { + if (BotMindTricked(bs->client, i)) { + if (distcheck < 256 || (level.time - g_entities[i].client->dangerTime) < 100) { + if (!hasEnemyDist || + distcheck < (hasEnemyDist - 128)) { // if we have an enemy, only switch to closer if he is 128+ closer to avoid flipping out + if (!noAttackNonJM || g_entities[i].client->ps.isJediMaster) { closest = distcheck; bestindex = i; } } } - } - else - { - if (!hasEnemyDist || distcheck < (hasEnemyDist - 128)) - { //if we have an enemy, only switch to closer if he is 128+ closer to avoid flipping out - if (!noAttackNonJM || g_entities[i].client->ps.isJediMaster) - { + } else { + if (!hasEnemyDist || + distcheck < (hasEnemyDist - 128)) { // if we have an enemy, only switch to closer if he is 128+ closer to avoid flipping out + if (!noAttackNonJM || g_entities[i].client->ps.isJediMaster) { closest = distcheck; bestindex = i; } @@ -2243,19 +1983,15 @@ int ScanForEnemies(bot_state_t *bs) return bestindex; } -int WaitingForNow(bot_state_t *bs, vec3_t goalpos) -{ //checks if the bot is doing something along the lines of waiting for an elevator to raise up +int WaitingForNow(bot_state_t *bs, vec3_t goalpos) { // checks if the bot is doing something along the lines of waiting for an elevator to raise up vec3_t xybot, xywp, a; - if (!bs->wpCurrent) - { + if (!bs->wpCurrent) { return 0; } - if ((int)goalpos[0] != (int)bs->wpCurrent->origin[0] || - (int)goalpos[1] != (int)bs->wpCurrent->origin[1] || - (int)goalpos[2] != (int)bs->wpCurrent->origin[2]) - { + if ((int)goalpos[0] != (int)bs->wpCurrent->origin[0] || (int)goalpos[1] != (int)bs->wpCurrent->origin[1] || + (int)goalpos[2] != (int)bs->wpCurrent->origin[2]) { return 0; } @@ -2267,28 +2003,21 @@ int WaitingForNow(bot_state_t *bs, vec3_t goalpos) VectorSubtract(xybot, xywp, a); - if (VectorLength(a) < 16 && bs->frame_Waypoint_Len > 100) - { - if (CheckForFunc(bs->origin, bs->client)) - { - return 1; //we're probably standing on an elevator and riding up/down. Or at least we hope so. + if (VectorLength(a) < 16 && bs->frame_Waypoint_Len > 100) { + if (CheckForFunc(bs->origin, bs->client)) { + return 1; // we're probably standing on an elevator and riding up/down. Or at least we hope so. } - } - else if (VectorLength(a) < 64 && bs->frame_Waypoint_Len > 64 && - CheckForFunc(bs->origin, bs->client)) - { + } else if (VectorLength(a) < 64 && bs->frame_Waypoint_Len > 64 && CheckForFunc(bs->origin, bs->client)) { bs->noUseTime = level.time + 2000; } return 0; } -//get an ideal distance for us to be at in relation to our opponent -//based on our weapon. -int BotGetWeaponRange(bot_state_t *bs) -{ - switch (bs->cur_ps.weapon) - { +// get an ideal distance for us to be at in relation to our opponent +// based on our weapon. +int BotGetWeaponRange(bot_state_t *bs) { + switch (bs->cur_ps.weapon) { case WP_STUN_BATON: case WP_MELEE: return BWEAPONRANGE_MELEE; @@ -2321,189 +2050,149 @@ int BotGetWeaponRange(bot_state_t *bs) } } -//see if we want to run away from the opponent for whatever reason -int BotIsAChickenWuss(bot_state_t *bs) -{ +// see if we want to run away from the opponent for whatever reason +int BotIsAChickenWuss(bot_state_t *bs) { int bWRange; - if (gLevelFlags & LEVELFLAG_IMUSTNTRUNAWAY) - { //The level says we mustn't run away! + if (gLevelFlags & LEVELFLAG_IMUSTNTRUNAWAY) { // The level says we mustn't run away! return 0; } - if (level.gametype == GT_SINGLE_PLAYER) - { //"coop" (not really) + if (level.gametype == GT_SINGLE_PLAYER) { //"coop" (not really) return 0; } - if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster) - { //Then you may know no fear. - //Well, unless he's strong. - if (bs->currentEnemy && bs->currentEnemy->client && - bs->currentEnemy->client->ps.isJediMaster && - bs->currentEnemy->health > 40 && - bs->cur_ps.weapon < WP_ROCKET_LAUNCHER) - { //explosive weapons are most effective against the Jedi Master + if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster) { // Then you may know no fear. + // Well, unless he's strong. + if (bs->currentEnemy && bs->currentEnemy->client && bs->currentEnemy->client->ps.isJediMaster && bs->currentEnemy->health > 40 && + bs->cur_ps.weapon < WP_ROCKET_LAUNCHER) { // explosive weapons are most effective against the Jedi Master goto jmPass; } return 0; } - if (level.gametype == GT_CTF && bs->currentEnemy && bs->currentEnemy->client) - { + if (level.gametype == GT_CTF && bs->currentEnemy && bs->currentEnemy->client) { if (bs->currentEnemy->client->ps.powerups[PW_REDFLAG] || - bs->currentEnemy->client->ps.powerups[PW_BLUEFLAG]) - { //don't be afraid of flag carriers, they must die! + bs->currentEnemy->client->ps.powerups[PW_BLUEFLAG]) { // don't be afraid of flag carriers, they must die! return 0; } } jmPass: - if (bs->chickenWussCalculationTime > level.time) - { - return 2; //don't want to keep going between two points... + if (bs->chickenWussCalculationTime > level.time) { + return 2; // don't want to keep going between two points... } - if (bs->cur_ps.fd.forcePowersActive & (1 << FP_RAGE)) - { //don't run while raging + if (bs->cur_ps.fd.forcePowersActive & (1 << FP_RAGE)) { // don't run while raging return 0; } - if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster) - { //be frightened of the jedi master? I guess in this case. + if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster) { // be frightened of the jedi master? I guess in this case. return 1; } bs->chickenWussCalculationTime = level.time + MAX_CHICKENWUSS_TIME; - if (g_entities[bs->client].health < BOT_RUN_HEALTH) - { //we're low on health, let's get away + if (g_entities[bs->client].health < BOT_RUN_HEALTH) { // we're low on health, let's get away return 1; } bWRange = BotGetWeaponRange(bs); - if (bWRange == BWEAPONRANGE_MELEE || bWRange == BWEAPONRANGE_SABER) - { - if (bWRange != BWEAPONRANGE_SABER || !bs->saberSpecialist) - { //run away if we're using melee, or if we're using a saber and not a "saber specialist" + if (bWRange == BWEAPONRANGE_MELEE || bWRange == BWEAPONRANGE_SABER) { + if (bWRange != BWEAPONRANGE_SABER || !bs->saberSpecialist) { // run away if we're using melee, or if we're using a saber and not a "saber specialist" return 1; } } - if (bs->cur_ps.weapon == WP_BRYAR_PISTOL) - { //the bryar is a weak weapon, so just try to find a new one if it's what you're having to use + if (bs->cur_ps.weapon == WP_BRYAR_PISTOL) { // the bryar is a weak weapon, so just try to find a new one if it's what you're having to use return 1; } - if (bs->currentEnemy && bs->currentEnemy->client && - bs->currentEnemy->client->ps.weapon == WP_SABER && - bs->frame_Enemy_Len < 512 && bs->cur_ps.weapon != WP_SABER) - { //if close to an enemy with a saber and not using a saber, then try to back off + if (bs->currentEnemy && bs->currentEnemy->client && bs->currentEnemy->client->ps.weapon == WP_SABER && bs->frame_Enemy_Len < 512 && + bs->cur_ps.weapon != WP_SABER) { // if close to an enemy with a saber and not using a saber, then try to back off return 1; } - if ((level.time-bs->cur_ps.electrifyTime) < 16000) - { //lightning is dangerous. + if ((level.time - bs->cur_ps.electrifyTime) < 16000) { // lightning is dangerous. return 1; } - //didn't run, reset the timer + // didn't run, reset the timer bs->chickenWussCalculationTime = 0; return 0; } -//look for "bad things". bad things include detpacks, thermal detonators, -//and other dangerous explodey items. -gentity_t *GetNearestBadThing(bot_state_t *bs) -{ +// look for "bad things". bad things include detpacks, thermal detonators, +// and other dangerous explodey items. +gentity_t *GetNearestBadThing(bot_state_t *bs) { int i = 0; float glen; vec3_t hold; int bestindex = 0; - float bestdist = 800; //if not within a radius of 800, it's no threat anyway + float bestdist = 800; // if not within a radius of 800, it's no threat anyway int foundindex = 0; float factor = 0; gentity_t *ent; trace_t tr; - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; - if ( (ent && - !ent->client && - ent->inuse && - ent->damage && - /*(ent->s.weapon == WP_THERMAL || ent->s.weapon == WP_FLECHETTE)*/ - ent->s.weapon && - ent->splashDamage) || - (ent && - ent->genericValue5 == 1000 && - ent->inuse && - ent->health > 0 && - ent->genericValue3 != bs->client && - g_entities[ent->genericValue3].client && !OnSameTeam(&g_entities[bs->client], &g_entities[ent->genericValue3])) ) - { //try to escape from anything with a non-0 s.weapon and non-0 damage. This hopefully only means dangerous projectiles. - //Or a sentry gun if bolt_Head == 1000. This is a terrible hack, yes. + if ((ent && !ent->client && ent->inuse && ent->damage && + /*(ent->s.weapon == WP_THERMAL || ent->s.weapon == WP_FLECHETTE)*/ + ent->s.weapon && ent->splashDamage) || + (ent && ent->genericValue5 == 1000 && ent->inuse && ent->health > 0 && ent->genericValue3 != bs->client && g_entities[ent->genericValue3].client && + !OnSameTeam(&g_entities[bs->client], + &g_entities[ent->genericValue3]))) { // try to escape from anything with a non-0 s.weapon and non-0 damage. This hopefully only means + // dangerous projectiles. Or a sentry gun if bolt_Head == 1000. This is a terrible hack, yes. VectorSubtract(bs->origin, ent->r.currentOrigin, hold); glen = VectorLength(hold); - if (ent->s.weapon != WP_THERMAL && ent->s.weapon != WP_FLECHETTE && - ent->s.weapon != WP_DET_PACK && ent->s.weapon != WP_TRIP_MINE) - { + if (ent->s.weapon != WP_THERMAL && ent->s.weapon != WP_FLECHETTE && ent->s.weapon != WP_DET_PACK && ent->s.weapon != WP_TRIP_MINE) { factor = 0.5; - if (ent->s.weapon && glen <= 256 && bs->settings.skill > 2) - { //it's a projectile so push it away + if (ent->s.weapon && glen <= 256 && bs->settings.skill > 2) { // it's a projectile so push it away bs->doForcePush = level.time + 700; - //trap->Print("PUSH PROJECTILE\n"); + // trap->Print("PUSH PROJECTILE\n"); } - } - else - { + } else { factor = 1; } if (ent->s.weapon == WP_ROCKET_LAUNCHER && (ent->r.ownerNum == bs->client || - (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && - g_entities[ent->r.ownerNum].client && OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum]))) ) - { //don't be afraid of your own rockets or your teammates' rockets + (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && g_entities[ent->r.ownerNum].client && + OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum])))) { // don't be afraid of your own rockets or your teammates' rockets factor = 0; } if (ent->s.weapon == WP_DET_PACK && (ent->r.ownerNum == bs->client || - (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && - g_entities[ent->r.ownerNum].client && OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum]))) ) - { //don't be afraid of your own detpacks or your teammates' detpacks + (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && g_entities[ent->r.ownerNum].client && + OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum])))) { // don't be afraid of your own detpacks or your teammates' detpacks factor = 0; } if (ent->s.weapon == WP_TRIP_MINE && (ent->r.ownerNum == bs->client || - (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && - g_entities[ent->r.ownerNum].client && OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum]))) ) - { //don't be afraid of your own trip mines or your teammates' trip mines + (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && g_entities[ent->r.ownerNum].client && + OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum])))) { // don't be afraid of your own trip mines or your teammates' trip mines factor = 0; } if (ent->s.weapon == WP_THERMAL && (ent->r.ownerNum == bs->client || - (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && - g_entities[ent->r.ownerNum].client && OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum]))) ) - { //don't be afraid of your own thermals or your teammates' thermals + (ent->r.ownerNum > 0 && ent->r.ownerNum < MAX_CLIENTS && g_entities[ent->r.ownerNum].client && + OnSameTeam(&g_entities[bs->client], &g_entities[ent->r.ownerNum])))) { // don't be afraid of your own thermals or your teammates' thermals factor = 0; } - if (glen < bestdist*factor && BotPVSCheck(bs->origin, ent->s.pos.trBase)) - { + if (glen < bestdist * factor && BotPVSCheck(bs->origin, ent->s.pos.trBase)) { trap->Trace(&tr, bs->origin, NULL, NULL, ent->s.pos.trBase, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == ent->s.number) - { + if (tr.fraction == 1 || tr.entityNum == ent->s.number) { bestindex = i; bestdist = glen; foundindex = 1; @@ -2511,23 +2200,18 @@ gentity_t *GetNearestBadThing(bot_state_t *bs) } } - if (ent && !ent->client && ent->inuse && ent->damage && ent->s.weapon && ent->r.ownerNum < MAX_CLIENTS && ent->r.ownerNum >= 0) - { //if we're in danger of a projectile belonging to someone and don't have an enemy, set the enemy to them + if (ent && !ent->client && ent->inuse && ent->damage && ent->s.weapon && ent->r.ownerNum < MAX_CLIENTS && + ent->r.ownerNum >= 0) { // if we're in danger of a projectile belonging to someone and don't have an enemy, set the enemy to them gentity_t *projOwner = &g_entities[ent->r.ownerNum]; - if (projOwner && projOwner->inuse && projOwner->client) - { - if (!bs->currentEnemy) - { - if (PassStandardEnemyChecks(bs, projOwner)) - { - if (PassLovedOneCheck(bs, projOwner)) - { + if (projOwner && projOwner->inuse && projOwner->client) { + if (!bs->currentEnemy) { + if (PassStandardEnemyChecks(bs, projOwner)) { + if (PassLovedOneCheck(bs, projOwner)) { VectorSubtract(bs->origin, ent->r.currentOrigin, hold); glen = VectorLength(hold); - if (glen < 512) - { + if (glen < 512) { bs->currentEnemy = projOwner; bs->enemySeenTime = level.time + ENEMY_FORGET_MS; } @@ -2540,88 +2224,68 @@ gentity_t *GetNearestBadThing(bot_state_t *bs) i++; } - if (foundindex) - { + if (foundindex) { bs->dontGoBack = level.time + 1500; return &g_entities[bestindex]; - } - else - { + } else { return NULL; } } -//Keep our CTF priorities on defending our team's flag -int BotDefendFlag(bot_state_t *bs) -{ +// Keep our CTF priorities on defending our team's flag +int BotDefendFlag(bot_state_t *bs) { wpobject_t *flagPoint; vec3_t a; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { flagPoint = flagRed; - } - else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) - { + } else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) { flagPoint = flagBlue; - } - else - { + } else { return 0; } - if (!flagPoint) - { + if (!flagPoint) { return 0; } VectorSubtract(bs->origin, flagPoint->origin, a); - if (VectorLength(a) > BASE_GUARD_DISTANCE) - { + if (VectorLength(a) > BASE_GUARD_DISTANCE) { bs->wpDestination = flagPoint; } return 1; } -//Keep our CTF priorities on getting the other team's flag -int BotGetEnemyFlag(bot_state_t *bs) -{ +// Keep our CTF priorities on getting the other team's flag +int BotGetEnemyFlag(bot_state_t *bs) { wpobject_t *flagPoint; vec3_t a; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { flagPoint = flagBlue; - } - else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) - { + } else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) { flagPoint = flagRed; - } - else - { + } else { return 0; } - if (!flagPoint) - { + if (!flagPoint) { return 0; } VectorSubtract(bs->origin, flagPoint->origin, a); - if (VectorLength(a) > BASE_GETENEMYFLAG_DISTANCE) - { + if (VectorLength(a) > BASE_GETENEMYFLAG_DISTANCE) { bs->wpDestination = flagPoint; } return 1; } -//Our team's flag is gone, so try to get it back -int BotGetFlagBack(bot_state_t *bs) -{ +// Our team's flag is gone, so try to get it back +int BotGetFlagBack(bot_state_t *bs) { int i = 0; int myFlag = 0; int foundCarrier = 0; @@ -2629,21 +2293,16 @@ int BotGetFlagBack(bot_state_t *bs) gentity_t *ent = NULL; vec3_t usethisvec; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { myFlag = PW_REDFLAG; - } - else - { + } else { myFlag = PW_BLUEFLAG; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client && ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) { foundCarrier = 1; break; } @@ -2651,31 +2310,24 @@ int BotGetFlagBack(bot_state_t *bs) i++; } - if (!foundCarrier) - { + if (!foundCarrier) { return 0; } - if (!ent) - { + if (!ent) { return 0; } - if (bs->wpDestSwitchTime < level.time) - { - if (ent->client) - { + if (bs->wpDestSwitchTime < level.time) { + if (ent->client) { VectorCopy(ent->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(ent->s.origin, usethisvec); } tempInt = GetNearestVisibleWP(usethisvec, 0); - if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) - { + if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) { bs->wpDestination = gWPArray[tempInt]; bs->wpDestSwitchTime = level.time + Q_irand(1000, 5000); } @@ -2684,10 +2336,9 @@ int BotGetFlagBack(bot_state_t *bs) return 1; } -//Someone else on our team has the enemy flag, so try to get -//to their assistance -int BotGuardFlagCarrier(bot_state_t *bs) -{ +// Someone else on our team has the enemy flag, so try to get +// to their assistance +int BotGuardFlagCarrier(bot_state_t *bs) { int i = 0; int enemyFlag = 0; int foundCarrier = 0; @@ -2695,21 +2346,16 @@ int BotGuardFlagCarrier(bot_state_t *bs) gentity_t *ent = NULL; vec3_t usethisvec; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { enemyFlag = PW_BLUEFLAG; - } - else - { + } else { enemyFlag = PW_REDFLAG; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->ps.powerups[enemyFlag] && OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client && ent->client->ps.powerups[enemyFlag] && OnSameTeam(&g_entities[bs->client], ent)) { foundCarrier = 1; break; } @@ -2717,31 +2363,24 @@ int BotGuardFlagCarrier(bot_state_t *bs) i++; } - if (!foundCarrier) - { + if (!foundCarrier) { return 0; } - if (!ent) - { + if (!ent) { return 0; } - if (bs->wpDestSwitchTime < level.time) - { - if (ent->client) - { + if (bs->wpDestSwitchTime < level.time) { + if (ent->client) { VectorCopy(ent->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(ent->s.origin, usethisvec); } tempInt = GetNearestVisibleWP(usethisvec, 0); - if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) - { + if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) { bs->wpDestination = gWPArray[tempInt]; bs->wpDestSwitchTime = level.time + Q_irand(1000, 5000); } @@ -2750,42 +2389,33 @@ int BotGuardFlagCarrier(bot_state_t *bs) return 1; } -//We have the flag, let's get it home. -int BotGetFlagHome(bot_state_t *bs) -{ +// We have the flag, let's get it home. +int BotGetFlagHome(bot_state_t *bs) { wpobject_t *flagPoint; vec3_t a; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { flagPoint = flagRed; - } - else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) - { + } else if (level.clients[bs->client].sess.sessionTeam == TEAM_BLUE) { flagPoint = flagBlue; - } - else - { + } else { return 0; } - if (!flagPoint) - { + if (!flagPoint) { return 0; } VectorSubtract(bs->origin, flagPoint->origin, a); - if (VectorLength(a) > BASE_FLAGWAIT_DISTANCE) - { + if (VectorLength(a) > BASE_FLAGWAIT_DISTANCE) { bs->wpDestination = flagPoint; } return 1; } -void GetNewFlagPoint(wpobject_t *wp, gentity_t *flagEnt, int team) -{ //get the nearest possible waypoint to the flag since it's not in its original position +void GetNewFlagPoint(wpobject_t *wp, gentity_t *flagEnt, int team) { // get the nearest possible waypoint to the flag since it's not in its original position int i = 0; vec3_t a, mins, maxs; float bestdist; @@ -2805,27 +2435,22 @@ void GetNewFlagPoint(wpobject_t *wp, gentity_t *flagEnt, int team) bestdist = VectorLength(a); - if (bestdist <= WP_KEEP_FLAG_DIST) - { + if (bestdist <= WP_KEEP_FLAG_DIST) { trap->Trace(&tr, wp->origin, mins, maxs, flagEnt->s.pos.trBase, flagEnt->s.number, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { //this point is good + if (tr.fraction == 1) { // this point is good return; } } - while (i < gWPNum) - { + while (i < gWPNum) { VectorSubtract(gWPArray[i]->origin, flagEnt->s.pos.trBase, a); testdist = VectorLength(a); - if (testdist < bestdist) - { + if (testdist < bestdist) { trap->Trace(&tr, gWPArray[i]->origin, mins, maxs, flagEnt->s.pos.trBase, flagEnt->s.number, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { foundindex = 1; bestindex = i; bestdist = testdist; @@ -2835,27 +2460,22 @@ void GetNewFlagPoint(wpobject_t *wp, gentity_t *flagEnt, int team) i++; } - if (foundindex) - { - if (team == TEAM_RED) - { + if (foundindex) { + if (team == TEAM_RED) { flagRed = gWPArray[bestindex]; - } - else - { + } else { flagBlue = gWPArray[bestindex]; } } } -//See if our CTF state should take priority in our nav routines -int CTFTakesPriority(bot_state_t *bs) -{ +// See if our CTF state should take priority in our nav routines +int CTFTakesPriority(bot_state_t *bs) { gentity_t *ent = NULL; int enemyFlag = 0; int myFlag = 0; int enemyHasOurFlag = 0; - //int weHaveEnemyFlag = 0; + // int weHaveEnemyFlag = 0; int numOnMyTeam = 0; int numOnEnemyTeam = 0; int numAttackers = 0; @@ -2870,55 +2490,39 @@ int CTFTakesPriority(bot_state_t *bs) trap->Print("CTFSTATE: %s\n", ctfStateNames[bs->ctfState]); #endif - if (level.gametype != GT_CTF && level.gametype != GT_CTY) - { + if (level.gametype != GT_CTF && level.gametype != GT_CTY) { return 0; } if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && - (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_GATHER_TIME) - { //get the nearest weapon laying around base before heading off for battle + (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_GATHER_TIME) { // get the nearest weapon laying around base before heading off for battle idleWP = GetBestIdleGoal(bs); - if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) - { - if (bs->wpDestSwitchTime < level.time) - { + if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) { + if (bs->wpDestSwitchTime < level.time) { bs->wpDestination = gWPArray[idleWP]; } return 1; } - } - else if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && - (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_CHASE_CTF && - bs->wpDestination && bs->wpDestination->weight) - { + } else if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_CHASE_CTF && bs->wpDestination && + bs->wpDestination->weight) { dest_sw = bs->wpDestination; dosw = 1; } - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { myFlag = PW_REDFLAG; - } - else - { + } else { myFlag = PW_BLUEFLAG; } - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { enemyFlag = PW_BLUEFLAG; - } - else - { + } else { enemyFlag = PW_REDFLAG; } - if (!flagRed || !flagBlue || - !flagRed->inuse || !flagBlue->inuse || - !eFlagRed || !eFlagBlue) - { + if (!flagRed || !flagBlue || !flagRed->inuse || !flagBlue->inuse || !eFlagRed || !eFlagBlue) { return 0; } @@ -2932,140 +2536,100 @@ int CTFTakesPriority(bot_state_t *bs) G_TestLine(flagBlue->origin, t, 0x0000ff, 500); #endif - if (droppedRedFlag && (droppedRedFlag->flags & FL_DROPPED_ITEM)) - { + if (droppedRedFlag && (droppedRedFlag->flags & FL_DROPPED_ITEM)) { GetNewFlagPoint(flagRed, droppedRedFlag, TEAM_RED); - } - else - { + } else { flagRed = oFlagRed; } - if (droppedBlueFlag && (droppedBlueFlag->flags & FL_DROPPED_ITEM)) - { + if (droppedBlueFlag && (droppedBlueFlag->flags & FL_DROPPED_ITEM)) { GetNewFlagPoint(flagBlue, droppedBlueFlag, TEAM_BLUE); - } - else - { + } else { flagBlue = oFlagBlue; } - if (!bs->ctfState) - { + if (!bs->ctfState) { return 0; } i = 0; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client) - { + if (ent && ent->client) { /*if (ent->client->ps.powerups[enemyFlag] && OnSameTeam(&g_entities[bs->client], ent)) { weHaveEnemyFlag = 1; } - else */if (ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) - { + else */ + if (ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) { enemyHasOurFlag = 1; } - if (OnSameTeam(&g_entities[bs->client], ent)) - { + if (OnSameTeam(&g_entities[bs->client], ent)) { numOnMyTeam++; - } - else - { + } else { numOnEnemyTeam++; } - if (botstates[ent->s.number]) - { - if (botstates[ent->s.number]->ctfState == CTFSTATE_ATTACKER || - botstates[ent->s.number]->ctfState == CTFSTATE_RETRIEVAL) - { + if (botstates[ent->s.number]) { + if (botstates[ent->s.number]->ctfState == CTFSTATE_ATTACKER || botstates[ent->s.number]->ctfState == CTFSTATE_RETRIEVAL) { numAttackers++; - } - else - { + } else { numDefenders++; } - } - else - { //assume real players to be attackers in our logic + } else { // assume real players to be attackers in our logic numAttackers++; } } i++; } - if (bs->cur_ps.powerups[enemyFlag]) - { - if ((numOnMyTeam < 2 || !numAttackers) && enemyHasOurFlag) - { + if (bs->cur_ps.powerups[enemyFlag]) { + if ((numOnMyTeam < 2 || !numAttackers) && enemyHasOurFlag) { bs->ctfState = CTFSTATE_RETRIEVAL; - } - else - { + } else { bs->ctfState = CTFSTATE_GETFLAGHOME; } - } - else if (bs->ctfState == CTFSTATE_GETFLAGHOME) - { + } else if (bs->ctfState == CTFSTATE_GETFLAGHOME) { bs->ctfState = 0; } - if (bs->state_Forced) - { + if (bs->state_Forced) { bs->ctfState = bs->state_Forced; } - if (bs->ctfState == CTFSTATE_DEFENDER) - { - if (BotDefendFlag(bs)) - { + if (bs->ctfState == CTFSTATE_DEFENDER) { + if (BotDefendFlag(bs)) { goto success; } } - if (bs->ctfState == CTFSTATE_ATTACKER) - { - if (BotGetEnemyFlag(bs)) - { + if (bs->ctfState == CTFSTATE_ATTACKER) { + if (BotGetEnemyFlag(bs)) { goto success; } } - if (bs->ctfState == CTFSTATE_RETRIEVAL) - { - if (BotGetFlagBack(bs)) - { + if (bs->ctfState == CTFSTATE_RETRIEVAL) { + if (BotGetFlagBack(bs)) { goto success; - } - else - { //can't find anyone on another team being a carrier, so ignore this priority + } else { // can't find anyone on another team being a carrier, so ignore this priority bs->ctfState = 0; } } - if (bs->ctfState == CTFSTATE_GUARDCARRIER) - { - if (BotGuardFlagCarrier(bs)) - { + if (bs->ctfState == CTFSTATE_GUARDCARRIER) { + if (BotGuardFlagCarrier(bs)) { goto success; - } - else - { //can't find anyone on our team being a carrier, so ignore this priority + } else { // can't find anyone on our team being a carrier, so ignore this priority bs->ctfState = 0; } } - if (bs->ctfState == CTFSTATE_GETFLAGHOME) - { - if (BotGetFlagHome(bs)) - { + if (bs->ctfState == CTFSTATE_GETFLAGHOME) { + if (BotGetFlagHome(bs)) { goto success; } } @@ -3073,35 +2637,29 @@ int CTFTakesPriority(bot_state_t *bs) return 0; success: - if (dosw) - { //allow ctf code to run, but if after a particular item then keep going after it + if (dosw) { // allow ctf code to run, but if after a particular item then keep going after it bs->wpDestination = dest_sw; } return 1; } -int EntityVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore, int ignore2) -{ +int EntityVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore, int ignore2) { trace_t tr; trap->Trace(&tr, org1, mins, maxs, org2, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { return 1; - } - else if (tr.entityNum != ENTITYNUM_NONE && tr.entityNum == ignore2) - { + } else if (tr.entityNum != ENTITYNUM_NONE && tr.entityNum == ignore2) { return 1; } return 0; } -//Get the closest objective for siege and go after it -int Siege_TargetClosestObjective(bot_state_t *bs, int flag) -{ +// Get the closest objective for siege and go after it +int Siege_TargetClosestObjective(bot_state_t *bs, int flag) { int i = 0; int bestindex = -1; float testdistance = 0; @@ -3118,22 +2676,18 @@ int Siege_TargetClosestObjective(bot_state_t *bs, int flag) maxs[1] = 1; maxs[2] = 1; - if ( bs->wpDestination && (bs->wpDestination->flags & flag) && bs->wpDestination->associated_entity != ENTITYNUM_NONE && - g_entities[bs->wpDestination->associated_entity].inuse && g_entities[bs->wpDestination->associated_entity].use ) - { + if (bs->wpDestination && (bs->wpDestination->flags & flag) && bs->wpDestination->associated_entity != ENTITYNUM_NONE && + g_entities[bs->wpDestination->associated_entity].inuse && g_entities[bs->wpDestination->associated_entity].use) { goto hasPoint; } - while (i < gWPNum) - { - if ( gWPArray[i] && gWPArray[i]->inuse && (gWPArray[i]->flags & flag) && gWPArray[i]->associated_entity != ENTITYNUM_NONE && - g_entities[gWPArray[i]->associated_entity].inuse && g_entities[gWPArray[i]->associated_entity].use ) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && (gWPArray[i]->flags & flag) && gWPArray[i]->associated_entity != ENTITYNUM_NONE && + g_entities[gWPArray[i]->associated_entity].inuse && g_entities[gWPArray[i]->associated_entity].use) { VectorSubtract(gWPArray[i]->origin, bs->origin, a); testdistance = VectorLength(a); - if (testdistance < bestdistance) - { + if (testdistance < bestdistance) { bestdistance = testdistance; bestindex = i; } @@ -3142,19 +2696,15 @@ int Siege_TargetClosestObjective(bot_state_t *bs, int flag) i++; } - if (bestindex != -1) - { + if (bestindex != -1) { bs->wpDestination = gWPArray[bestindex]; - } - else - { + } else { return 0; } hasPoint: goalent = &g_entities[bs->wpDestination->associated_entity]; - if (!goalent) - { + if (!goalent) { return 0; } @@ -3162,47 +2712,37 @@ int Siege_TargetClosestObjective(bot_state_t *bs, int flag) testdistance = VectorLength(a); - dif[0] = (goalent->r.absmax[0]+goalent->r.absmin[0])/2; - dif[1] = (goalent->r.absmax[1]+goalent->r.absmin[1])/2; - dif[2] = (goalent->r.absmax[2]+goalent->r.absmin[2])/2; - //brush models can have tricky origins, so this is our hacky method of getting the center point + dif[0] = (goalent->r.absmax[0] + goalent->r.absmin[0]) / 2; + dif[1] = (goalent->r.absmax[1] + goalent->r.absmin[1]) / 2; + dif[2] = (goalent->r.absmax[2] + goalent->r.absmin[2]) / 2; + // brush models can have tricky origins, so this is our hacky method of getting the center point - if (goalent->takedamage && testdistance < BOT_MIN_SIEGE_GOAL_SHOOT && - EntityVisibleBox(bs->origin, mins, maxs, dif, bs->client, goalent->s.number)) - { + if (goalent->takedamage && testdistance < BOT_MIN_SIEGE_GOAL_SHOOT && EntityVisibleBox(bs->origin, mins, maxs, dif, bs->client, goalent->s.number)) { bs->shootGoal = goalent; bs->touchGoal = NULL; - } - else if (goalent->use && testdistance < BOT_MIN_SIEGE_GOAL_TRAVEL) - { + } else if (goalent->use && testdistance < BOT_MIN_SIEGE_GOAL_TRAVEL) { bs->shootGoal = NULL; bs->touchGoal = goalent; - } - else - { //don't know how to handle this goal object! + } else { // don't know how to handle this goal object! bs->shootGoal = NULL; bs->touchGoal = NULL; } - if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE || - BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) - { - bs->shootGoal = NULL; //too risky + if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE || BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) { + bs->shootGoal = NULL; // too risky } - if (bs->touchGoal) - { - //trap->Print("Please, master, let me touch it!\n"); + if (bs->touchGoal) { + // trap->Print("Please, master, let me touch it!\n"); VectorCopy(dif, bs->goalPosition); } return 1; } -void Siege_DefendFromAttackers(bot_state_t *bs) -{ //this may be a little cheap, but the best way to find our defending point is probably - //to just find the nearest person on the opposing team since they'll most likely - //be on offense in this situation +void Siege_DefendFromAttackers(bot_state_t *bs) { // this may be a little cheap, but the best way to find our defending point is probably + // to just find the nearest person on the opposing team since they'll most likely + // be on offense in this situation int wpClose = -1; int i = 0; float testdist = 999999; @@ -3211,19 +2751,16 @@ void Siege_DefendFromAttackers(bot_state_t *bs) gentity_t *ent; vec3_t a; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->sess.sessionTeam != g_entities[bs->client].client->sess.sessionTeam && - ent->health > 0 && ent->client->sess.sessionTeam != TEAM_SPECTATOR) - { + if (ent && ent->client && ent->client->sess.sessionTeam != g_entities[bs->client].client->sess.sessionTeam && ent->health > 0 && + ent->client->sess.sessionTeam != TEAM_SPECTATOR) { VectorSubtract(ent->client->ps.origin, bs->origin, a); testdist = VectorLength(a); - if (testdist < bestdist) - { + if (testdist < bestdist) { bestindex = i; bestdist = testdist; } @@ -3232,38 +2769,31 @@ void Siege_DefendFromAttackers(bot_state_t *bs) i++; } - if (bestindex == -1) - { + if (bestindex == -1) { return; } wpClose = GetNearestVisibleWP(g_entities[bestindex].client->ps.origin, -1); - if (wpClose != -1 && gWPArray[wpClose] && gWPArray[wpClose]->inuse) - { + if (wpClose != -1 && gWPArray[wpClose] && gWPArray[wpClose]->inuse) { bs->wpDestination = gWPArray[wpClose]; bs->destinationGrabTime = level.time + 10000; } } -//how many defenders on our team? -int Siege_CountDefenders(bot_state_t *bs) -{ +// how many defenders on our team? +int Siege_CountDefenders(bot_state_t *bs) { int i = 0; int num = 0; gentity_t *ent; bot_state_t *bot; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; bot = botstates[i]; - if (ent && ent->client && bot) - { - if (bot->siegeState == SIEGESTATE_DEFENDER && - ent->client->sess.sessionTeam == g_entities[bs->client].client->sess.sessionTeam) - { + if (ent && ent->client && bot) { + if (bot->siegeState == SIEGESTATE_DEFENDER && ent->client->sess.sessionTeam == g_entities[bs->client].client->sess.sessionTeam) { num++; } } @@ -3274,21 +2804,17 @@ int Siege_CountDefenders(bot_state_t *bs) return num; } -//how many other players on our team? -int Siege_CountTeammates(bot_state_t *bs) -{ +// how many other players on our team? +int Siege_CountTeammates(bot_state_t *bs) { int i = 0; int num = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client) - { - if (ent->client->sess.sessionTeam == g_entities[bs->client].client->sess.sessionTeam) - { + if (ent && ent->client) { + if (ent->client->sess.sessionTeam == g_entities[bs->client].client->sess.sessionTeam) { num++; } } @@ -3299,12 +2825,11 @@ int Siege_CountTeammates(bot_state_t *bs) return num; } -//see if siege objective completion should take priority in our -//nav routines. -int SiegeTakesPriority(bot_state_t *bs) -{ +// see if siege objective completion should take priority in our +// nav routines. +int SiegeTakesPriority(bot_state_t *bs) { int attacker; - //int flagForDefendableObjective; + // int flagForDefendableObjective; int flagForAttackableObjective; int defenders, teammates; int idleWP; @@ -3314,186 +2839,143 @@ int SiegeTakesPriority(bot_state_t *bs) vec3_t dif; trace_t tr; - if (level.gametype != GT_SIEGE) - { + if (level.gametype != GT_SIEGE) { return 0; } bcl = g_entities[bs->client].client; - if (!bcl) - { + if (!bcl) { return 0; } if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && - (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_GATHER_TIME) - { //get the nearest weapon laying around base before heading off for battle + (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_GATHER_TIME) { // get the nearest weapon laying around base before heading off for battle idleWP = GetBestIdleGoal(bs); - if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) - { - if (bs->wpDestSwitchTime < level.time) - { + if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) { + if (bs->wpDestSwitchTime < level.time) { bs->wpDestination = gWPArray[idleWP]; } return 1; } - } - else if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && - (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_CHASE_TIME && - bs->wpDestination && bs->wpDestination->weight) - { + } else if (bs->cur_ps.weapon == WP_BRYAR_PISTOL && (level.time - bs->lastDeadTime) < BOT_MAX_WEAPON_CHASE_TIME && bs->wpDestination && + bs->wpDestination->weight) { dest_sw = bs->wpDestination; dosw = 1; } - if (bcl->sess.sessionTeam == SIEGETEAM_TEAM1) - { + if (bcl->sess.sessionTeam == SIEGETEAM_TEAM1) { attacker = imperial_attackers; - //flagForDefendableObjective = WPFLAG_SIEGE_REBELOBJ; + // flagForDefendableObjective = WPFLAG_SIEGE_REBELOBJ; flagForAttackableObjective = WPFLAG_SIEGE_IMPERIALOBJ; - } - else - { + } else { attacker = rebel_attackers; - //flagForDefendableObjective = WPFLAG_SIEGE_IMPERIALOBJ; + // flagForDefendableObjective = WPFLAG_SIEGE_IMPERIALOBJ; flagForAttackableObjective = WPFLAG_SIEGE_REBELOBJ; } - if (attacker) - { + if (attacker) { bs->siegeState = SIEGESTATE_ATTACKER; - } - else - { + } else { bs->siegeState = SIEGESTATE_DEFENDER; defenders = Siege_CountDefenders(bs); teammates = Siege_CountTeammates(bs); - if (defenders > teammates/3 && teammates > 1) - { //devote around 1/4 of our team to completing our own side goals even if we're a defender. - //If we have no side goals we will realize that later on and join the defenders + if (defenders > teammates / 3 && teammates > 1) { // devote around 1/4 of our team to completing our own side goals even if we're a defender. + // If we have no side goals we will realize that later on and join the defenders bs->siegeState = SIEGESTATE_ATTACKER; } } - if (bs->state_Forced) - { + if (bs->state_Forced) { bs->siegeState = bs->state_Forced; } - if (bs->siegeState == SIEGESTATE_ATTACKER) - { - if (!Siege_TargetClosestObjective(bs, flagForAttackableObjective)) - { //looks like we have no goals other than to keep the other team from completing objectives + if (bs->siegeState == SIEGESTATE_ATTACKER) { + if (!Siege_TargetClosestObjective( + bs, flagForAttackableObjective)) { // looks like we have no goals other than to keep the other team from completing objectives Siege_DefendFromAttackers(bs); - if (bs->shootGoal) - { - dif[0] = (bs->shootGoal->r.absmax[0]+bs->shootGoal->r.absmin[0])/2; - dif[1] = (bs->shootGoal->r.absmax[1]+bs->shootGoal->r.absmin[1])/2; - dif[2] = (bs->shootGoal->r.absmax[2]+bs->shootGoal->r.absmin[2])/2; + if (bs->shootGoal) { + dif[0] = (bs->shootGoal->r.absmax[0] + bs->shootGoal->r.absmin[0]) / 2; + dif[1] = (bs->shootGoal->r.absmax[1] + bs->shootGoal->r.absmin[1]) / 2; + dif[2] = (bs->shootGoal->r.absmax[2] + bs->shootGoal->r.absmin[2]) / 2; - if (!BotPVSCheck(bs->origin, dif)) - { + if (!BotPVSCheck(bs->origin, dif)) { bs->shootGoal = NULL; - } - else - { + } else { trap->Trace(&tr, bs->origin, NULL, NULL, dif, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) - { + if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) { bs->shootGoal = NULL; } } } } - } - else if (bs->siegeState == SIEGESTATE_DEFENDER) - { + } else if (bs->siegeState == SIEGESTATE_DEFENDER) { Siege_DefendFromAttackers(bs); - if (bs->shootGoal) - { - dif[0] = (bs->shootGoal->r.absmax[0]+bs->shootGoal->r.absmin[0])/2; - dif[1] = (bs->shootGoal->r.absmax[1]+bs->shootGoal->r.absmin[1])/2; - dif[2] = (bs->shootGoal->r.absmax[2]+bs->shootGoal->r.absmin[2])/2; + if (bs->shootGoal) { + dif[0] = (bs->shootGoal->r.absmax[0] + bs->shootGoal->r.absmin[0]) / 2; + dif[1] = (bs->shootGoal->r.absmax[1] + bs->shootGoal->r.absmin[1]) / 2; + dif[2] = (bs->shootGoal->r.absmax[2] + bs->shootGoal->r.absmin[2]) / 2; - if (!BotPVSCheck(bs->origin, dif)) - { + if (!BotPVSCheck(bs->origin, dif)) { bs->shootGoal = NULL; - } - else - { + } else { trap->Trace(&tr, bs->origin, NULL, NULL, dif, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) - { + if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) { bs->shootGoal = NULL; } } } - } - else - { //get busy! + } else { // get busy! Siege_TargetClosestObjective(bs, flagForAttackableObjective); - if (bs->shootGoal) - { - dif[0] = (bs->shootGoal->r.absmax[0]+bs->shootGoal->r.absmin[0])/2; - dif[1] = (bs->shootGoal->r.absmax[1]+bs->shootGoal->r.absmin[1])/2; - dif[2] = (bs->shootGoal->r.absmax[2]+bs->shootGoal->r.absmin[2])/2; + if (bs->shootGoal) { + dif[0] = (bs->shootGoal->r.absmax[0] + bs->shootGoal->r.absmin[0]) / 2; + dif[1] = (bs->shootGoal->r.absmax[1] + bs->shootGoal->r.absmin[1]) / 2; + dif[2] = (bs->shootGoal->r.absmax[2] + bs->shootGoal->r.absmin[2]) / 2; - if (!BotPVSCheck(bs->origin, dif)) - { + if (!BotPVSCheck(bs->origin, dif)) { bs->shootGoal = NULL; - } - else - { + } else { trap->Trace(&tr, bs->origin, NULL, NULL, dif, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) - { + if (tr.fraction != 1 && tr.entityNum != bs->shootGoal->s.number) { bs->shootGoal = NULL; } } } } - if (dosw) - { //allow siege objective code to run, but if after a particular item then keep going after it + if (dosw) { // allow siege objective code to run, but if after a particular item then keep going after it bs->wpDestination = dest_sw; } return 1; } -//see if jedi master priorities should take priority in our nav -//routines. -int JMTakesPriority(bot_state_t *bs) -{ +// see if jedi master priorities should take priority in our nav +// routines. +int JMTakesPriority(bot_state_t *bs) { int i = 0; int wpClose = -1; gentity_t *theImportantEntity = NULL; - if (level.gametype != GT_JEDIMASTER) - { + if (level.gametype != GT_JEDIMASTER) { return 0; } - if (bs->cur_ps.isJediMaster) - { + if (bs->cur_ps.isJediMaster) { return 0; } - //jmState becomes the index for the one who carries the saber. If jmState is -1 then the saber is currently - //without an owner + // jmState becomes the index for the one who carries the saber. If jmState is -1 then the saber is currently + // without an owner bs->jmState = -1; - while (i < MAX_CLIENTS) - { - if (g_entities[i].client && g_entities[i].inuse && - g_entities[i].client->ps.isJediMaster) - { + while (i < MAX_CLIENTS) { + if (g_entities[i].client && g_entities[i].inuse && g_entities[i].client->ps.isJediMaster) { bs->jmState = i; break; } @@ -3501,28 +2983,20 @@ int JMTakesPriority(bot_state_t *bs) i++; } - if (bs->jmState != -1) - { + if (bs->jmState != -1) { theImportantEntity = &g_entities[bs->jmState]; - } - else - { + } else { theImportantEntity = gJMSaberEnt; } - if (theImportantEntity && theImportantEntity->inuse && bs->destinationGrabTime < level.time) - { - if (theImportantEntity->client) - { + if (theImportantEntity && theImportantEntity->inuse && bs->destinationGrabTime < level.time) { + if (theImportantEntity->client) { wpClose = GetNearestVisibleWP(theImportantEntity->client->ps.origin, theImportantEntity->s.number); - } - else - { + } else { wpClose = GetNearestVisibleWP(theImportantEntity->r.currentOrigin, theImportantEntity->s.number); } - if (wpClose != -1 && gWPArray[wpClose] && gWPArray[wpClose]->inuse) - { + if (wpClose != -1 && gWPArray[wpClose] && gWPArray[wpClose]->inuse) { /* Com_Printf("BOT GRABBED IDEAL JM LOCATION\n"); if (bs->wpDestination != gWPArray[wpClose]) @@ -3543,54 +3017,41 @@ int JMTakesPriority(bot_state_t *bs) return 1; } -//see if we already have an item/powerup/etc. that is associated -//with this waypoint. -int BotHasAssociated(bot_state_t *bs, wpobject_t *wp) -{ +// see if we already have an item/powerup/etc. that is associated +// with this waypoint. +int BotHasAssociated(bot_state_t *bs, wpobject_t *wp) { gentity_t *as; - if (wp->associated_entity == ENTITYNUM_NONE) - { //make it think this is an item we have so we don't go after nothing + if (wp->associated_entity == ENTITYNUM_NONE) { // make it think this is an item we have so we don't go after nothing return 1; } as = &g_entities[wp->associated_entity]; - if (!as || !as->item) - { + if (!as || !as->item) { return 0; } - if (as->item->giType == IT_WEAPON) - { - if (bs->cur_ps.stats[STAT_WEAPONS] & (1 << as->item->giTag)) - { + if (as->item->giType == IT_WEAPON) { + if (bs->cur_ps.stats[STAT_WEAPONS] & (1 << as->item->giTag)) { return 1; } return 0; - } - else if (as->item->giType == IT_HOLDABLE) - { - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << as->item->giTag)) - { + } else if (as->item->giType == IT_HOLDABLE) { + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << as->item->giTag)) { return 1; } return 0; - } - else if (as->item->giType == IT_POWERUP) - { - if (bs->cur_ps.powerups[as->item->giTag]) - { + } else if (as->item->giType == IT_POWERUP) { + if (bs->cur_ps.powerups[as->item->giTag]) { return 1; } return 0; - } - else if (as->item->giType == IT_AMMO) - { - if (bs->cur_ps.ammo[as->item->giTag] > 10) //hack + } else if (as->item->giType == IT_AMMO) { + if (bs->cur_ps.ammo[as->item->giTag] > 10) // hack { return 1; } @@ -3601,32 +3062,25 @@ int BotHasAssociated(bot_state_t *bs, wpobject_t *wp) return 0; } -//we don't really have anything we want to do right now, -//let's just find the best thing to do given the current -//situation. -int GetBestIdleGoal(bot_state_t *bs) -{ +// we don't really have anything we want to do right now, +// let's just find the best thing to do given the current +// situation. +int GetBestIdleGoal(bot_state_t *bs) { int i = 0; int highestweight = 0; int desiredindex = -1; int dist_to_weight = 0; int traildist; - if (!bs->wpCurrent) - { + if (!bs->wpCurrent) { return -1; } - if (bs->isCamper != 2) - { - if (bs->randomNavTime < level.time) - { - if (Q_irand(1, 10) < 5) - { + if (bs->isCamper != 2) { + if (bs->randomNavTime < level.time) { + if (Q_irand(1, 10) < 5) { bs->randomNav = 1; - } - else - { + } else { bs->randomNav = 0; } @@ -3634,28 +3088,20 @@ int GetBestIdleGoal(bot_state_t *bs) } } - if (bs->randomNav) - { //stop looking for items and/or camping on them + if (bs->randomNav) { // stop looking for items and/or camping on them return -1; } - while (i < gWPNum) - { - if (gWPArray[i] && - gWPArray[i]->inuse && - (gWPArray[i]->flags & WPFLAG_GOALPOINT) && - gWPArray[i]->weight > highestweight && - !BotHasAssociated(bs, gWPArray[i])) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && (gWPArray[i]->flags & WPFLAG_GOALPOINT) && gWPArray[i]->weight > highestweight && + !BotHasAssociated(bs, gWPArray[i])) { traildist = TotalTrailDistance(bs->wpCurrent->index, i, bs); - if (traildist != -1) - { - dist_to_weight = (int)traildist/10000; - dist_to_weight = (gWPArray[i]->weight)-dist_to_weight; + if (traildist != -1) { + dist_to_weight = (int)traildist / 10000; + dist_to_weight = (gWPArray[i]->weight) - dist_to_weight; - if (dist_to_weight > highestweight) - { + if (dist_to_weight > highestweight) { highestweight = dist_to_weight; desiredindex = i; } @@ -3668,10 +3114,9 @@ int GetBestIdleGoal(bot_state_t *bs) return desiredindex; } -//go through the list of possible priorities for navigating -//and work out the best destination point. -void GetIdealDestination(bot_state_t *bs) -{ +// go through the list of possible priorities for navigating +// and work out the best destination point. +void GetIdealDestination(bot_state_t *bs) { int tempInt, cWPIndex, bChicken, idleWP; float distChange, plusLen, minusLen; vec3_t usethisvec, a; @@ -3680,291 +3125,214 @@ void GetIdealDestination(bot_state_t *bs) #ifdef _DEBUG trap->Cvar_Update(&bot_nogoals); - if (bot_nogoals.integer) - { + if (bot_nogoals.integer) { return; } #endif - if (!bs->wpCurrent) - { + if (!bs->wpCurrent) { return; } - if ((level.time - bs->escapeDirTime) > 4000) - { + if ((level.time - bs->escapeDirTime) > 4000) { badthing = GetNearestBadThing(bs); - } - else - { + } else { badthing = NULL; } - if (badthing && badthing->inuse && - badthing->health > 0 && badthing->takedamage) - { + if (badthing && badthing->inuse && badthing->health > 0 && badthing->takedamage) { bs->dangerousObject = badthing; - } - else - { + } else { bs->dangerousObject = NULL; } - if (!badthing && bs->wpDestIgnoreTime > level.time) - { + if (!badthing && bs->wpDestIgnoreTime > level.time) { return; } - if (!badthing && bs->dontGoBack > level.time) - { - if (bs->wpDestination) - { + if (!badthing && bs->dontGoBack > level.time) { + if (bs->wpDestination) { bs->wpStoreDest = bs->wpDestination; } bs->wpDestination = NULL; return; - } - else if (!badthing && bs->wpStoreDest) - { //after we finish running away, switch back to our original destination + } else if (!badthing && bs->wpStoreDest) { // after we finish running away, switch back to our original destination bs->wpDestination = bs->wpStoreDest; bs->wpStoreDest = NULL; } - if (badthing && bs->wpCamping) - { + if (badthing && bs->wpCamping) { bs->wpCamping = NULL; } - if (bs->wpCamping) - { + if (bs->wpCamping) { bs->wpDestination = bs->wpCamping; return; } - if (!badthing && CTFTakesPriority(bs)) - { - if (bs->ctfState) - { + if (!badthing && CTFTakesPriority(bs)) { + if (bs->ctfState) { bs->runningToEscapeThreat = 1; } return; - } - else if (!badthing && SiegeTakesPriority(bs)) - { - if (bs->siegeState) - { + } else if (!badthing && SiegeTakesPriority(bs)) { + if (bs->siegeState) { bs->runningToEscapeThreat = 1; } return; - } - else if (!badthing && JMTakesPriority(bs)) - { + } else if (!badthing && JMTakesPriority(bs)) { bs->runningToEscapeThreat = 1; } - if (badthing) - { + if (badthing) { bs->runningLikeASissy = level.time + 100; - if (bs->wpDestination) - { + if (bs->wpDestination) { bs->wpStoreDest = bs->wpDestination; } bs->wpDestination = NULL; - if (bs->wpDirection) - { - tempInt = bs->wpCurrent->index+1; - } - else - { - tempInt = bs->wpCurrent->index-1; + if (bs->wpDirection) { + tempInt = bs->wpCurrent->index + 1; + } else { + tempInt = bs->wpCurrent->index - 1; } - if (gWPArray[tempInt] && gWPArray[tempInt]->inuse && bs->escapeDirTime < level.time) - { + if (gWPArray[tempInt] && gWPArray[tempInt]->inuse && bs->escapeDirTime < level.time) { VectorSubtract(badthing->s.pos.trBase, bs->wpCurrent->origin, a); plusLen = VectorLength(a); VectorSubtract(badthing->s.pos.trBase, gWPArray[tempInt]->origin, a); minusLen = VectorLength(a); - if (plusLen < minusLen) - { - if (bs->wpDirection) - { + if (plusLen < minusLen) { + if (bs->wpDirection) { bs->wpDirection = 0; - } - else - { + } else { bs->wpDirection = 1; } bs->wpCurrent = gWPArray[tempInt]; - bs->escapeDirTime = level.time + Q_irand(500, 1000);//Q_irand(1000, 1400); + bs->escapeDirTime = level.time + Q_irand(500, 1000); // Q_irand(1000, 1400); - //trap->Print("Escaping from scary bad thing [%s]\n", badthing->classname); + // trap->Print("Escaping from scary bad thing [%s]\n", badthing->classname); } } - //trap->Print("Run away run away run away!\n"); + // trap->Print("Run away run away run away!\n"); return; } - distChange = 0; //keep the compiler from complaining + distChange = 0; // keep the compiler from complaining tempInt = BotGetWeaponRange(bs); - if (tempInt == BWEAPONRANGE_MELEE) - { + if (tempInt == BWEAPONRANGE_MELEE) { distChange = 1; - } - else if (tempInt == BWEAPONRANGE_SABER) - { + } else if (tempInt == BWEAPONRANGE_SABER) { distChange = 1; - } - else if (tempInt == BWEAPONRANGE_MID) - { + } else if (tempInt == BWEAPONRANGE_MID) { distChange = 128; - } - else if (tempInt == BWEAPONRANGE_LONG) - { + } else if (tempInt == BWEAPONRANGE_LONG) { distChange = 300; } - if (bs->revengeEnemy && bs->revengeEnemy->health > 0 && - bs->revengeEnemy->client && bs->revengeEnemy->client->pers.connected == CON_CONNECTED) - { //if we hate someone, always try to get to them - if (bs->wpDestSwitchTime < level.time) - { - if (bs->revengeEnemy->client) - { + if (bs->revengeEnemy && bs->revengeEnemy->health > 0 && bs->revengeEnemy->client && + bs->revengeEnemy->client->pers.connected == CON_CONNECTED) { // if we hate someone, always try to get to them + if (bs->wpDestSwitchTime < level.time) { + if (bs->revengeEnemy->client) { VectorCopy(bs->revengeEnemy->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(bs->revengeEnemy->s.origin, usethisvec); } tempInt = GetNearestVisibleWP(usethisvec, 0); - if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) - { + if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) { bs->wpDestination = gWPArray[tempInt]; bs->wpDestSwitchTime = level.time + Q_irand(5000, 10000); } } - } - else if (bs->squadLeader && bs->squadLeader->health > 0 && - bs->squadLeader->client && bs->squadLeader->client->pers.connected == CON_CONNECTED) - { - if (bs->wpDestSwitchTime < level.time) - { - if (bs->squadLeader->client) - { + } else if (bs->squadLeader && bs->squadLeader->health > 0 && bs->squadLeader->client && bs->squadLeader->client->pers.connected == CON_CONNECTED) { + if (bs->wpDestSwitchTime < level.time) { + if (bs->squadLeader->client) { VectorCopy(bs->squadLeader->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(bs->squadLeader->s.origin, usethisvec); } tempInt = GetNearestVisibleWP(usethisvec, 0); - if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) - { + if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) { bs->wpDestination = gWPArray[tempInt]; bs->wpDestSwitchTime = level.time + Q_irand(5000, 10000); } } - } - else if (bs->currentEnemy) - { - if (bs->currentEnemy->client) - { + } else if (bs->currentEnemy) { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(bs->currentEnemy->s.origin, usethisvec); } bChicken = BotIsAChickenWuss(bs); bs->runningToEscapeThreat = bChicken; - if (bs->frame_Enemy_Len < distChange || (bChicken && bChicken != 2)) - { + if (bs->frame_Enemy_Len < distChange || (bChicken && bChicken != 2)) { cWPIndex = bs->wpCurrent->index; - if (bs->frame_Enemy_Len > 400) - { //good distance away, start running toward a good place for an item or powerup or whatever + if (bs->frame_Enemy_Len > 400) { // good distance away, start running toward a good place for an item or powerup or whatever idleWP = GetBestIdleGoal(bs); - if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) - { + if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) { bs->wpDestination = gWPArray[idleWP]; } - } - else if (gWPArray[cWPIndex-1] && gWPArray[cWPIndex-1]->inuse && - gWPArray[cWPIndex+1] && gWPArray[cWPIndex+1]->inuse) - { - VectorSubtract(gWPArray[cWPIndex+1]->origin, usethisvec, a); + } else if (gWPArray[cWPIndex - 1] && gWPArray[cWPIndex - 1]->inuse && gWPArray[cWPIndex + 1] && gWPArray[cWPIndex + 1]->inuse) { + VectorSubtract(gWPArray[cWPIndex + 1]->origin, usethisvec, a); plusLen = VectorLength(a); - VectorSubtract(gWPArray[cWPIndex-1]->origin, usethisvec, a); + VectorSubtract(gWPArray[cWPIndex - 1]->origin, usethisvec, a); minusLen = VectorLength(a); - if (minusLen > plusLen) - { - bs->wpDestination = gWPArray[cWPIndex-1]; - } - else - { - bs->wpDestination = gWPArray[cWPIndex+1]; + if (minusLen > plusLen) { + bs->wpDestination = gWPArray[cWPIndex - 1]; + } else { + bs->wpDestination = gWPArray[cWPIndex + 1]; } } - } - else if (bChicken != 2 && bs->wpDestSwitchTime < level.time) - { + } else if (bChicken != 2 && bs->wpDestSwitchTime < level.time) { tempInt = GetNearestVisibleWP(usethisvec, 0); - if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) - { + if (tempInt != -1 && TotalTrailDistance(bs->wpCurrent->index, tempInt, bs) != -1) { bs->wpDestination = gWPArray[tempInt]; - if (level.gametype == GT_SINGLE_PLAYER) - { //be more aggressive + if (level.gametype == GT_SINGLE_PLAYER) { // be more aggressive bs->wpDestSwitchTime = level.time + Q_irand(300, 1000); - } - else - { + } else { bs->wpDestSwitchTime = level.time + Q_irand(1000, 5000); } } } } - if (!bs->wpDestination && bs->wpDestSwitchTime < level.time) - { - //trap->Print("I need something to do\n"); + if (!bs->wpDestination && bs->wpDestSwitchTime < level.time) { + // trap->Print("I need something to do\n"); idleWP = GetBestIdleGoal(bs); - if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) - { + if (idleWP != -1 && gWPArray[idleWP] && gWPArray[idleWP]->inuse) { bs->wpDestination = gWPArray[idleWP]; } } } -//commander CTF AI - tell other bots in the so-called +// commander CTF AI - tell other bots in the so-called //"squad" what to do. -void CommanderBotCTFAI(bot_state_t *bs) -{ +void CommanderBotCTFAI(bot_state_t *bs) { int i = 0; gentity_t *ent; int squadmates = 0; gentity_t *squad[MAX_CLIENTS]; - int defendAttackPriority = 0; //0 == attack, 1 == defend - int guardDefendPriority = 0; //0 == defend, 1 == guard - int attackRetrievePriority = 0; //0 == retrieve, 1 == attack + int defendAttackPriority = 0; // 0 == attack, 1 == defend + int guardDefendPriority = 0; // 0 == defend, 1 == guard + int attackRetrievePriority = 0; // 0 == retrieve, 1 == attack int myFlag = 0; int enemyFlag = 0; int enemyHasOurFlag = 0; @@ -3974,62 +3342,41 @@ void CommanderBotCTFAI(bot_state_t *bs) int numAttackers = 0; int numDefenders = 0; - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { myFlag = PW_REDFLAG; - } - else - { + } else { myFlag = PW_BLUEFLAG; } - if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) - { + if (level.clients[bs->client].sess.sessionTeam == TEAM_RED) { enemyFlag = PW_BLUEFLAG; - } - else - { + } else { enemyFlag = PW_REDFLAG; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client) - { - if (ent->client->ps.powerups[enemyFlag] && OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client) { + if (ent->client->ps.powerups[enemyFlag] && OnSameTeam(&g_entities[bs->client], ent)) { weHaveEnemyFlag = 1; - } - else if (ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) - { + } else if (ent->client->ps.powerups[myFlag] && !OnSameTeam(&g_entities[bs->client], ent)) { enemyHasOurFlag = 1; } - if (OnSameTeam(&g_entities[bs->client], ent)) - { + if (OnSameTeam(&g_entities[bs->client], ent)) { numOnMyTeam++; - } - else - { + } else { numOnEnemyTeam++; } - if (botstates[ent->s.number]) - { - if (botstates[ent->s.number]->ctfState == CTFSTATE_ATTACKER || - botstates[ent->s.number]->ctfState == CTFSTATE_RETRIEVAL) - { + if (botstates[ent->s.number]) { + if (botstates[ent->s.number]->ctfState == CTFSTATE_ATTACKER || botstates[ent->s.number]->ctfState == CTFSTATE_RETRIEVAL) { numAttackers++; - } - else - { + } else { numDefenders++; } - } - else - { //assume real players to be attackers in our logic + } else { // assume real players to be attackers in our logic numAttackers++; } } @@ -4038,12 +3385,10 @@ void CommanderBotCTFAI(bot_state_t *bs) i = 0; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && botstates[i] && botstates[i]->squadLeader && botstates[i]->squadLeader->s.number == bs->client && i != bs->client) - { + if (ent && ent->client && botstates[i] && botstates[i]->squadLeader && botstates[i]->squadLeader->s.number == bs->client && i != bs->client) { squad[squadmates] = ent; squadmates++; } @@ -4056,63 +3401,43 @@ void CommanderBotCTFAI(bot_state_t *bs) i = 0; - if (enemyHasOurFlag && !weHaveEnemyFlag) - { //start off with an attacker instead of a retriever if we don't have the enemy flag yet so that they can't capture it first. - //after that we focus on getting our flag back. + if (enemyHasOurFlag && !weHaveEnemyFlag) { // start off with an attacker instead of a retriever if we don't have the enemy flag yet so that they can't + // capture it first. after that we focus on getting our flag back. attackRetrievePriority = 1; } - while (i < squadmates) - { - if (squad[i] && squad[i]->client && botstates[squad[i]->s.number]) - { - if (botstates[squad[i]->s.number]->ctfState != CTFSTATE_GETFLAGHOME) - { //never tell a bot to stop trying to bring the flag to the base - if (defendAttackPriority) - { - if (weHaveEnemyFlag) - { - if (guardDefendPriority) - { + while (i < squadmates) { + if (squad[i] && squad[i]->client && botstates[squad[i]->s.number]) { + if (botstates[squad[i]->s.number]->ctfState != CTFSTATE_GETFLAGHOME) { // never tell a bot to stop trying to bring the flag to the base + if (defendAttackPriority) { + if (weHaveEnemyFlag) { + if (guardDefendPriority) { botstates[squad[i]->s.number]->ctfState = CTFSTATE_GUARDCARRIER; guardDefendPriority = 0; - } - else - { + } else { botstates[squad[i]->s.number]->ctfState = CTFSTATE_DEFENDER; guardDefendPriority = 1; } - } - else - { + } else { botstates[squad[i]->s.number]->ctfState = CTFSTATE_DEFENDER; } defendAttackPriority = 0; - } - else - { - if (enemyHasOurFlag) - { - if (attackRetrievePriority) - { + } else { + if (enemyHasOurFlag) { + if (attackRetrievePriority) { botstates[squad[i]->s.number]->ctfState = CTFSTATE_ATTACKER; attackRetrievePriority = 0; - } - else - { + } else { botstates[squad[i]->s.number]->ctfState = CTFSTATE_RETRIEVAL; attackRetrievePriority = 1; } - } - else - { + } else { botstates[squad[i]->s.number]->ctfState = CTFSTATE_ATTACKER; } defendAttackPriority = 1; } - } - else if ((numOnMyTeam < 2 || !numAttackers) && enemyHasOurFlag) - { //I'm the only one on my team who will attack and the enemy has my flag, I have to go after him + } else if ((numOnMyTeam < 2 || !numAttackers) && + enemyHasOurFlag) { // I'm the only one on my team who will attack and the enemy has my flag, I have to go after him botstates[squad[i]->s.number]->ctfState = CTFSTATE_RETRIEVAL; } } @@ -4121,9 +3446,8 @@ void CommanderBotCTFAI(bot_state_t *bs) } } -//similar to ctf ai, for siege -void CommanderBotSiegeAI(bot_state_t *bs) -{ +// similar to ctf ai, for siege +void CommanderBotSiegeAI(bot_state_t *bs) { int i = 0; int squadmates = 0; int commanded = 0; @@ -4132,52 +3456,42 @@ void CommanderBotSiegeAI(bot_state_t *bs) gentity_t *ent; bot_state_t *bst; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent) && botstates[ent->s.number]) - { + if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent) && botstates[ent->s.number]) { bst = botstates[ent->s.number]; - if (bst && !bst->isSquadLeader && !bst->state_Forced) - { + if (bst && !bst->isSquadLeader && !bst->state_Forced) { squad[squadmates] = ent; squadmates++; - } - else if (bst && !bst->isSquadLeader && bst->state_Forced) - { //count them as commanded + } else if (bst && !bst->isSquadLeader && bst->state_Forced) { // count them as commanded commanded++; } } - if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent)) { teammates++; } i++; } - if (!squadmates) - { + if (!squadmates) { return; } - //tell squad mates to do what I'm doing, up to half of team, let the other half make their own decisions + // tell squad mates to do what I'm doing, up to half of team, let the other half make their own decisions i = 0; - while (i < squadmates && squad[i]) - { + while (i < squadmates && squad[i]) { bst = botstates[squad[i]->s.number]; - if (commanded > teammates/2) - { + if (commanded > teammates / 2) { break; } - if (bst) - { + if (bst) { bst->state_Forced = bs->siegeState; bst->siegeState = bs->siegeState; commanded++; @@ -4187,24 +3501,20 @@ void CommanderBotSiegeAI(bot_state_t *bs) } } -//teamplay ffa squad ai -void BotDoTeamplayAI(bot_state_t *bs) -{ - if (bs->state_Forced) - { +// teamplay ffa squad ai +void BotDoTeamplayAI(bot_state_t *bs) { + if (bs->state_Forced) { bs->teamplayState = bs->state_Forced; } - if (bs->teamplayState == TEAMPLAYSTATE_REGROUP) - { //force to find a new leader + if (bs->teamplayState == TEAMPLAYSTATE_REGROUP) { // force to find a new leader bs->squadLeader = NULL; bs->isSquadLeader = 0; } } -//like ctf and siege commander ai, instruct the squad -void CommanderBotTeamplayAI(bot_state_t *bs) -{ +// like ctf and siege commander ai, instruct the squad +void CommanderBotTeamplayAI(bot_state_t *bs) { int i = 0; int squadmates = 0; int teammates = 0; @@ -4216,36 +3526,28 @@ void CommanderBotTeamplayAI(bot_state_t *bs) gentity_t *ent; bot_state_t *bst; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent) && botstates[ent->s.number]) - { + if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent) && botstates[ent->s.number]) { bst = botstates[ent->s.number]; - if (foundsquadleader && bst && bst->isSquadLeader) - { //never more than one squad leader + if (foundsquadleader && bst && bst->isSquadLeader) { // never more than one squad leader bst->isSquadLeader = 0; } - if (bst && !bst->isSquadLeader) - { + if (bst && !bst->isSquadLeader) { squad[squadmates] = ent; squadmates++; - } - else if (bst) - { + } else if (bst) { foundsquadleader = 1; } } - if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client && OnSameTeam(&g_entities[bs->client], ent)) { teammates++; - if (ent->health < worsthealth) - { + if (ent->health < worsthealth) { teammate_indanger = ent->s.number; worsthealth = ent->health; } @@ -4254,35 +3556,28 @@ void CommanderBotTeamplayAI(bot_state_t *bs) i++; } - if (!squadmates) - { + if (!squadmates) { return; } i = 0; - while (i < squadmates && squad[i]) - { + while (i < squadmates && squad[i]) { bst = botstates[squad[i]->s.number]; - if (bst && !bst->state_Forced) - { //only order if this guy is not being ordered directly by the real player team leader - if (teammate_indanger >= 0 && !teammate_helped) - { //send someone out to help whoever needs help most at the moment + if (bst && !bst->state_Forced) { // only order if this guy is not being ordered directly by the real player team leader + if (teammate_indanger >= 0 && !teammate_helped) { // send someone out to help whoever needs help most at the moment bst->teamplayState = TEAMPLAYSTATE_ASSISTING; bst->squadLeader = &g_entities[teammate_indanger]; teammate_helped = 1; - } - else if ((teammate_indanger == -1 || teammate_helped) && bst->teamplayState == TEAMPLAYSTATE_ASSISTING) - { //no teammates need help badly, but this guy is trying to help them anyway, so stop + } else if ((teammate_indanger == -1 || teammate_helped) && + bst->teamplayState == TEAMPLAYSTATE_ASSISTING) { // no teammates need help badly, but this guy is trying to help them anyway, so stop bst->teamplayState = TEAMPLAYSTATE_FOLLOWING; bst->squadLeader = &g_entities[bs->client]; } - if (bs->squadRegroupInterval < level.time && Q_irand(1, 10) < 5) - { //every so often tell the squad to regroup for the sake of variation - if (bst->teamplayState == TEAMPLAYSTATE_FOLLOWING) - { + if (bs->squadRegroupInterval < level.time && Q_irand(1, 10) < 5) { // every so often tell the squad to regroup for the sake of variation + if (bst->teamplayState == TEAMPLAYSTATE_FOLLOWING) { bst->teamplayState = TEAMPLAYSTATE_REGROUP; } @@ -4296,26 +3591,19 @@ void CommanderBotTeamplayAI(bot_state_t *bs) } } -//pick which commander ai to use based on gametype -void CommanderBotAI(bot_state_t *bs) -{ - if (level.gametype == GT_CTF || level.gametype == GT_CTY) - { +// pick which commander ai to use based on gametype +void CommanderBotAI(bot_state_t *bs) { + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { CommanderBotCTFAI(bs); - } - else if (level.gametype == GT_SIEGE) - { + } else if (level.gametype == GT_SIEGE) { CommanderBotSiegeAI(bs); - } - else if (level.gametype == GT_TEAM) - { + } else if (level.gametype == GT_TEAM) { CommanderBotTeamplayAI(bs); } } -//close range combat routines -void MeleeCombatHandling(bot_state_t *bs) -{ +// close range combat routines +void MeleeCombatHandling(bot_state_t *bs) { vec3_t usethisvec; vec3_t downvec; vec3_t midorg; @@ -4327,28 +3615,20 @@ void MeleeCombatHandling(bot_state_t *bs) int me_down; int mid_down; - if (!bs->currentEnemy) - { + if (!bs->currentEnemy) { return; } - if (bs->currentEnemy->client) - { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(bs->currentEnemy->s.origin, usethisvec); } - if (bs->meleeStrafeTime < level.time) - { - if (bs->meleeStrafeDir) - { + if (bs->meleeStrafeTime < level.time) { + if (bs->meleeStrafeDir) { bs->meleeStrafeDir = 0; - } - else - { + } else { bs->meleeStrafeDir = 1; } @@ -4380,9 +3660,9 @@ void MeleeCombatHandling(bot_state_t *bs) vectoangles(a, a); AngleVectors(a, fwd, NULL, NULL); - midorg[0] = bs->origin[0] + fwd[0]*bs->frame_Enemy_Len/2; - midorg[1] = bs->origin[1] + fwd[1]*bs->frame_Enemy_Len/2; - midorg[2] = bs->origin[2] + fwd[2]*bs->frame_Enemy_Len/2; + midorg[0] = bs->origin[0] + fwd[0] * bs->frame_Enemy_Len / 2; + midorg[1] = bs->origin[1] + fwd[1] * bs->frame_Enemy_Len / 2; + midorg[2] = bs->origin[2] + fwd[2] * bs->frame_Enemy_Len / 2; VectorCopy(midorg, downvec); downvec[2] -= 4096; @@ -4391,16 +3671,13 @@ void MeleeCombatHandling(bot_state_t *bs) mid_down = (int)tr.endpos[2]; - if (me_down == en_down && - en_down == mid_down) - { + if (me_down == en_down && en_down == mid_down) { VectorCopy(usethisvec, bs->goalPosition); } } -//saber combat routines (it's simple, but it works) -void SaberCombatHandling(bot_state_t *bs) -{ +// saber combat routines (it's simple, but it works) +void SaberCombatHandling(bot_state_t *bs) { vec3_t usethisvec; vec3_t downvec; vec3_t midorg; @@ -4412,28 +3689,20 @@ void SaberCombatHandling(bot_state_t *bs) int me_down; int mid_down; - if (!bs->currentEnemy) - { + if (!bs->currentEnemy) { return; } - if (bs->currentEnemy->client) - { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, usethisvec); - } - else - { + } else { VectorCopy(bs->currentEnemy->s.origin, usethisvec); } - if (bs->meleeStrafeTime < level.time) - { - if (bs->meleeStrafeDir) - { + if (bs->meleeStrafeTime < level.time) { + if (bs->meleeStrafeDir) { bs->meleeStrafeDir = 0; - } - else - { + } else { bs->meleeStrafeDir = 1; } @@ -4454,13 +3723,10 @@ void SaberCombatHandling(bot_state_t *bs) en_down = (int)tr.endpos[2]; - if (tr.startsolid || tr.allsolid) - { + if (tr.startsolid || tr.allsolid) { en_down = 1; me_down = 2; - } - else - { + } else { VectorCopy(bs->origin, downvec); downvec[2] -= 4096; @@ -4468,8 +3734,7 @@ void SaberCombatHandling(bot_state_t *bs) me_down = (int)tr.endpos[2]; - if (tr.startsolid || tr.allsolid) - { + if (tr.startsolid || tr.allsolid) { en_down = 1; me_down = 2; } @@ -4479,9 +3744,9 @@ void SaberCombatHandling(bot_state_t *bs) vectoangles(a, a); AngleVectors(a, fwd, NULL, NULL); - midorg[0] = bs->origin[0] + fwd[0]*bs->frame_Enemy_Len/2; - midorg[1] = bs->origin[1] + fwd[1]*bs->frame_Enemy_Len/2; - midorg[2] = bs->origin[2] + fwd[2]*bs->frame_Enemy_Len/2; + midorg[0] = bs->origin[0] + fwd[0] * bs->frame_Enemy_Len / 2; + midorg[1] = bs->origin[1] + fwd[1] * bs->frame_Enemy_Len / 2; + midorg[2] = bs->origin[2] + fwd[2] * bs->frame_Enemy_Len / 2; VectorCopy(midorg, downvec); downvec[2] -= 4096; @@ -4490,31 +3755,19 @@ void SaberCombatHandling(bot_state_t *bs) mid_down = (int)tr.endpos[2]; - if (me_down == en_down && - en_down == mid_down) - { - if (usethisvec[2] > (bs->origin[2]+32) && - bs->currentEnemy->client && - bs->currentEnemy->client->ps.groundEntityNum == ENTITYNUM_NONE) - { + if (me_down == en_down && en_down == mid_down) { + if (usethisvec[2] > (bs->origin[2] + 32) && bs->currentEnemy->client && bs->currentEnemy->client->ps.groundEntityNum == ENTITYNUM_NONE) { bs->jumpTime = level.time + 100; } - if (bs->frame_Enemy_Len > 128) - { //be ready to attack + if (bs->frame_Enemy_Len > 128) { // be ready to attack bs->saberDefending = 0; bs->saberDefendDecideTime = level.time + Q_irand(1000, 2000); - } - else - { - if (bs->saberDefendDecideTime < level.time) - { - if (bs->saberDefending) - { + } else { + if (bs->saberDefendDecideTime < level.time) { + if (bs->saberDefending) { bs->saberDefending = 0; - } - else - { + } else { bs->saberDefending = 1; } @@ -4522,25 +3775,22 @@ void SaberCombatHandling(bot_state_t *bs) } } - if (bs->frame_Enemy_Len < 54) - { + if (bs->frame_Enemy_Len < 54) { VectorCopy(bs->origin, bs->goalPosition); bs->saberBFTime = 0; - } - else - { + } else { VectorCopy(usethisvec, bs->goalPosition); } - if (bs->currentEnemy && bs->currentEnemy->client) - { - if (!BG_SaberInSpecial(bs->currentEnemy->client->ps.saberMove) && bs->frame_Enemy_Len > 90 && bs->saberBFTime > level.time && bs->saberBTime > level.time && bs->beStill < level.time && bs->saberSTime < level.time) - { + if (bs->currentEnemy && bs->currentEnemy->client) { + if (!BG_SaberInSpecial(bs->currentEnemy->client->ps.saberMove) && bs->frame_Enemy_Len > 90 && bs->saberBFTime > level.time && + bs->saberBTime > level.time && bs->beStill < level.time && bs->saberSTime < level.time) { bs->beStill = level.time + Q_irand(500, 1000); bs->saberSTime = level.time + Q_irand(1200, 1800); - } - else if (bs->currentEnemy->client->ps.weapon == WP_SABER && bs->frame_Enemy_Len < 80 && ((Q_irand(1, 10) < 8 && bs->saberBFTime < level.time) || bs->saberBTime > level.time || BG_SaberInKata(bs->currentEnemy->client->ps.saberMove) || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK_DUAL)) - { + } else if (bs->currentEnemy->client->ps.weapon == WP_SABER && bs->frame_Enemy_Len < 80 && + ((Q_irand(1, 10) < 8 && bs->saberBFTime < level.time) || bs->saberBTime > level.time || + BG_SaberInKata(bs->currentEnemy->client->ps.saberMove) || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK || + bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK_DUAL)) { vec3_t vs; vec3_t groundcheck; int idealDist; @@ -4549,23 +3799,19 @@ void SaberCombatHandling(bot_state_t *bs) VectorSubtract(bs->origin, usethisvec, vs); VectorNormalize(vs); - if (BG_SaberInKata(bs->currentEnemy->client->ps.saberMove) || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK_DUAL) - { + if (BG_SaberInKata(bs->currentEnemy->client->ps.saberMove) || bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK || + bs->currentEnemy->client->ps.saberMove == LS_SPINATTACK_DUAL) { idealDist = 256; - } - else - { + } else { idealDist = 64; } - while (checkIncr < idealDist) - { - bs->goalPosition[0] = bs->origin[0] + vs[0]*checkIncr; - bs->goalPosition[1] = bs->origin[1] + vs[1]*checkIncr; - bs->goalPosition[2] = bs->origin[2] + vs[2]*checkIncr; + while (checkIncr < idealDist) { + bs->goalPosition[0] = bs->origin[0] + vs[0] * checkIncr; + bs->goalPosition[1] = bs->origin[1] + vs[1] * checkIncr; + bs->goalPosition[2] = bs->origin[2] + vs[2] * checkIncr; - if (bs->saberBTime < level.time) - { + if (bs->saberBTime < level.time) { bs->saberBFTime = level.time + Q_irand(900, 1300); bs->saberBTime = level.time + Q_irand(300, 700); } @@ -4576,16 +3822,13 @@ void SaberCombatHandling(bot_state_t *bs) trap->Trace(&tr, bs->goalPosition, NULL, NULL, groundcheck, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1.0f) - { //don't back off of a ledge + if (tr.fraction == 1.0f) { // don't back off of a ledge VectorCopy(usethisvec, bs->goalPosition); break; } checkIncr += 64; } - } - else if (bs->currentEnemy->client->ps.weapon == WP_SABER && bs->frame_Enemy_Len >= 75) - { + } else if (bs->currentEnemy->client->ps.weapon == WP_SABER && bs->frame_Enemy_Len >= 75) { bs->saberBFTime = level.time + Q_irand(700, 1300); bs->saberBTime = 0; } @@ -4605,20 +3848,16 @@ void SaberCombatHandling(bot_state_t *bs) bs->goalPosition[1] -= fwd[1]*16; bs->goalPosition[2] -= fwd[2]*16; }*/ - } - else if (bs->frame_Enemy_Len <= 56) - { + } else if (bs->frame_Enemy_Len <= 56) { bs->doAttack = 1; bs->saberDefending = 0; } } -//should we be "leading" our aim with this weapon? And if -//so, by how much? -float BotWeaponCanLead(bot_state_t *bs) -{ - switch ( bs->cur_ps.weapon ) - { +// should we be "leading" our aim with this weapon? And if +// so, by how much? +float BotWeaponCanLead(bot_state_t *bs) { + switch (bs->cur_ps.weapon) { case WP_BRYAR_PISTOL: return 0.5f; case WP_BLASTER: @@ -4638,119 +3877,94 @@ float BotWeaponCanLead(bot_state_t *bs) } } -//offset the desired view angles with aim leading in mind -void BotAimLeading(bot_state_t *bs, vec3_t headlevel, float leadAmount) -{ +// offset the desired view angles with aim leading in mind +void BotAimLeading(bot_state_t *bs, vec3_t headlevel, float leadAmount) { int x; vec3_t predictedSpot; vec3_t movementVector; vec3_t a, ang; float vtotal; - if (!bs->currentEnemy || - !bs->currentEnemy->client) - { + if (!bs->currentEnemy || !bs->currentEnemy->client) { return; } - if (!bs->frame_Enemy_Len) - { + if (!bs->frame_Enemy_Len) { return; } vtotal = 0; - if (bs->currentEnemy->client->ps.velocity[0] < 0) - { + if (bs->currentEnemy->client->ps.velocity[0] < 0) { vtotal += -bs->currentEnemy->client->ps.velocity[0]; - } - else - { + } else { vtotal += bs->currentEnemy->client->ps.velocity[0]; } - if (bs->currentEnemy->client->ps.velocity[1] < 0) - { + if (bs->currentEnemy->client->ps.velocity[1] < 0) { vtotal += -bs->currentEnemy->client->ps.velocity[1]; - } - else - { + } else { vtotal += bs->currentEnemy->client->ps.velocity[1]; } - if (bs->currentEnemy->client->ps.velocity[2] < 0) - { + if (bs->currentEnemy->client->ps.velocity[2] < 0) { vtotal += -bs->currentEnemy->client->ps.velocity[2]; - } - else - { + } else { vtotal += bs->currentEnemy->client->ps.velocity[2]; } - //trap->Print("Leadin target with a velocity total of %f\n", vtotal); + // trap->Print("Leadin target with a velocity total of %f\n", vtotal); VectorCopy(bs->currentEnemy->client->ps.velocity, movementVector); VectorNormalize(movementVector); - x = bs->frame_Enemy_Len*leadAmount; //hardly calculated with an exact science, but it works + x = bs->frame_Enemy_Len * leadAmount; // hardly calculated with an exact science, but it works - if (vtotal > 400) - { + if (vtotal > 400) { vtotal = 400; } - if (vtotal) - { - x = (bs->frame_Enemy_Len*0.9)*leadAmount*(vtotal*0.0012); //hardly calculated with an exact science, but it works - } - else - { - x = (bs->frame_Enemy_Len*0.9)*leadAmount; //hardly calculated with an exact science, but it works + if (vtotal) { + x = (bs->frame_Enemy_Len * 0.9) * leadAmount * (vtotal * 0.0012); // hardly calculated with an exact science, but it works + } else { + x = (bs->frame_Enemy_Len * 0.9) * leadAmount; // hardly calculated with an exact science, but it works } - predictedSpot[0] = headlevel[0] + (movementVector[0]*x); - predictedSpot[1] = headlevel[1] + (movementVector[1]*x); - predictedSpot[2] = headlevel[2] + (movementVector[2]*x); + predictedSpot[0] = headlevel[0] + (movementVector[0] * x); + predictedSpot[1] = headlevel[1] + (movementVector[1] * x); + predictedSpot[2] = headlevel[2] + (movementVector[2] * x); VectorSubtract(predictedSpot, bs->eye, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); } -//wobble our aim around based on our sk1llz -void BotAimOffsetGoalAngles(bot_state_t *bs) -{ +// wobble our aim around based on our sk1llz +void BotAimOffsetGoalAngles(bot_state_t *bs) { int i; float accVal; i = 0; - if (bs->skills.perfectaim) - { + if (bs->skills.perfectaim) { return; } - if (bs->aimOffsetTime > level.time) - { - if (bs->aimOffsetAmtYaw) - { + if (bs->aimOffsetTime > level.time) { + if (bs->aimOffsetAmtYaw) { bs->goalAngles[YAW] += bs->aimOffsetAmtYaw; } - if (bs->aimOffsetAmtPitch) - { + if (bs->aimOffsetAmtPitch) { bs->goalAngles[PITCH] += bs->aimOffsetAmtPitch; } - while (i <= 2) - { - if (bs->goalAngles[i] > 360) - { + while (i <= 2) { + if (bs->goalAngles[i] > 360) { bs->goalAngles[i] -= 360; } - if (bs->goalAngles[i] < 0) - { + if (bs->goalAngles[i] < 0) { bs->goalAngles[i] += 360; } @@ -4759,295 +3973,206 @@ void BotAimOffsetGoalAngles(bot_state_t *bs) return; } - accVal = bs->skills.accuracy/bs->settings.skill; + accVal = bs->skills.accuracy / bs->settings.skill; - if (bs->currentEnemy && BotMindTricked(bs->client, bs->currentEnemy->s.number)) - { //having to judge where they are by hearing them, so we should be quite inaccurate here + if (bs->currentEnemy && + BotMindTricked(bs->client, bs->currentEnemy->s.number)) { // having to judge where they are by hearing them, so we should be quite inaccurate here accVal *= 7; - if (accVal < 30) - { + if (accVal < 30) { accVal = 30; } } - if (bs->revengeEnemy && bs->revengeHateLevel && - bs->currentEnemy == bs->revengeEnemy) - { //bot becomes more skilled as anger level raises - accVal = accVal/bs->revengeHateLevel; + if (bs->revengeEnemy && bs->revengeHateLevel && bs->currentEnemy == bs->revengeEnemy) { // bot becomes more skilled as anger level raises + accVal = accVal / bs->revengeHateLevel; } - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { //assume our goal is aiming at the enemy, seeing as he's visible and all - if (!bs->currentEnemy->s.pos.trDelta[0] && - !bs->currentEnemy->s.pos.trDelta[1] && - !bs->currentEnemy->s.pos.trDelta[2]) - { - accVal = 0; //he's not even moving, so he shouldn't really be hard to hit. - } - else - { - accVal += accVal*0.25; //if he's moving he's this much harder to hit + if (bs->currentEnemy && bs->frame_Enemy_Vis) { // assume our goal is aiming at the enemy, seeing as he's visible and all + if (!bs->currentEnemy->s.pos.trDelta[0] && !bs->currentEnemy->s.pos.trDelta[1] && !bs->currentEnemy->s.pos.trDelta[2]) { + accVal = 0; // he's not even moving, so he shouldn't really be hard to hit. + } else { + accVal += accVal * 0.25; // if he's moving he's this much harder to hit } - if (g_entities[bs->client].s.pos.trDelta[0] || - g_entities[bs->client].s.pos.trDelta[1] || - g_entities[bs->client].s.pos.trDelta[2]) - { - accVal += accVal*0.15; //make it somewhat harder to aim if we're moving also + if (g_entities[bs->client].s.pos.trDelta[0] || g_entities[bs->client].s.pos.trDelta[1] || g_entities[bs->client].s.pos.trDelta[2]) { + accVal += accVal * 0.15; // make it somewhat harder to aim if we're moving also } } - if (accVal > 90) - { + if (accVal > 90) { accVal = 90; } - if (accVal < 1) - { + if (accVal < 1) { accVal = 0; } - if (!accVal) - { + if (!accVal) { bs->aimOffsetAmtYaw = 0; bs->aimOffsetAmtPitch = 0; return; } - if (rand()%10 <= 5) - { - bs->aimOffsetAmtYaw = rand()%(int)accVal; - } - else - { - bs->aimOffsetAmtYaw = -(rand()%(int)accVal); + if (rand() % 10 <= 5) { + bs->aimOffsetAmtYaw = rand() % (int)accVal; + } else { + bs->aimOffsetAmtYaw = -(rand() % (int)accVal); } - if (rand()%10 <= 5) - { - bs->aimOffsetAmtPitch = rand()%(int)accVal; - } - else - { - bs->aimOffsetAmtPitch = -(rand()%(int)accVal); + if (rand() % 10 <= 5) { + bs->aimOffsetAmtPitch = rand() % (int)accVal; + } else { + bs->aimOffsetAmtPitch = -(rand() % (int)accVal); } - bs->aimOffsetTime = level.time + rand()%500 + 200; + bs->aimOffsetTime = level.time + rand() % 500 + 200; } -//do we want to alt fire with this weapon? -int ShouldSecondaryFire(bot_state_t *bs) -{ +// do we want to alt fire with this weapon? +int ShouldSecondaryFire(bot_state_t *bs) { int weap; int dif; float rTime; weap = bs->cur_ps.weapon; - if (bs->cur_ps.ammo[weaponData[weap].ammoIndex] < weaponData[weap].altEnergyPerShot) - { + if (bs->cur_ps.ammo[weaponData[weap].ammoIndex] < weaponData[weap].altEnergyPerShot) { return 0; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) { float heldTime = (level.time - bs->cur_ps.weaponChargeTime); rTime = bs->cur_ps.rocketLockTime; - if (rTime < 1) - { + if (rTime < 1) { rTime = bs->cur_ps.rocketLastValidTime; } - if (heldTime > 5000) - { //just give up and release it if we can't manage a lock in 5 seconds + if (heldTime > 5000) { // just give up and release it if we can't manage a lock in 5 seconds return 2; } - if (rTime > 0) - { - dif = ( level.time - rTime ) / ( 1200.0f / 16.0f ); + if (rTime > 0) { + dif = (level.time - rTime) / (1200.0f / 16.0f); - if (dif >= 10) - { + if (dif >= 10) { return 2; - } - else if (bs->frame_Enemy_Len > 250) - { + } else if (bs->frame_Enemy_Len > 250) { return 1; } - } - else if (bs->frame_Enemy_Len > 250) - { + } else if (bs->frame_Enemy_Len > 250) { return 1; } - } - else if ((bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) && (level.time - bs->cur_ps.weaponChargeTime) > bs->altChargeTime) - { + } else if ((bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) && (level.time - bs->cur_ps.weaponChargeTime) > bs->altChargeTime) { return 2; - } - else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) - { + } else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) { return 1; } - if (weap == WP_BRYAR_PISTOL && bs->frame_Enemy_Len < 300) - { + if (weap == WP_BRYAR_PISTOL && bs->frame_Enemy_Len < 300) { return 1; - } - else if (weap == WP_BOWCASTER && bs->frame_Enemy_Len > 300) - { + } else if (weap == WP_BOWCASTER && bs->frame_Enemy_Len > 300) { return 1; - } - else if (weap == WP_REPEATER && bs->frame_Enemy_Len < 600 && bs->frame_Enemy_Len > 250) - { + } else if (weap == WP_REPEATER && bs->frame_Enemy_Len < 600 && bs->frame_Enemy_Len > 250) { return 1; - } - else if (weap == WP_BLASTER && bs->frame_Enemy_Len < 300) - { + } else if (weap == WP_BLASTER && bs->frame_Enemy_Len < 300) { return 1; - } - else if (weap == WP_ROCKET_LAUNCHER && bs->frame_Enemy_Len > 250) - { + } else if (weap == WP_ROCKET_LAUNCHER && bs->frame_Enemy_Len > 250) { return 1; } return 0; } -//standard weapon combat routines -int CombatBotAI(bot_state_t *bs, float thinktime) -{ +// standard weapon combat routines +int CombatBotAI(bot_state_t *bs, float thinktime) { vec3_t eorg, a; int secFire; float fovcheck; - if (!bs->currentEnemy) - { + if (!bs->currentEnemy) { return 0; } - if (bs->currentEnemy->client) - { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, eorg); - } - else - { + } else { VectorCopy(bs->currentEnemy->s.origin, eorg); } VectorSubtract(eorg, bs->eye, a); vectoangles(a, a); - if (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) - { - if (bs->frame_Enemy_Len <= SABER_ATTACK_RANGE) - { + if (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) { + if (bs->frame_Enemy_Len <= SABER_ATTACK_RANGE) { bs->doAttack = 1; } - } - else if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE) - { - if (bs->frame_Enemy_Len <= MELEE_ATTACK_RANGE) - { + } else if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE) { + if (bs->frame_Enemy_Len <= MELEE_ATTACK_RANGE) { bs->doAttack = 1; } - } - else - { - if (bs->cur_ps.weapon == WP_THERMAL || bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) - { //be careful with the hurty weapons + } else { + if (bs->cur_ps.weapon == WP_THERMAL || bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) { // be careful with the hurty weapons fovcheck = 40; if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && - bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) - { //if we're charging the weapon up then we can hold fire down within a normal fov + bs->cur_ps.weapon == WP_ROCKET_LAUNCHER) { // if we're charging the weapon up then we can hold fire down within a normal fov fovcheck = 60; } - } - else - { + } else { fovcheck = 60; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING || - bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING || bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) { fovcheck = 160; } - if (bs->frame_Enemy_Len < 128) - { + if (bs->frame_Enemy_Len < 128) { fovcheck *= 2; } - if (InFieldOfVision(bs->viewangles, fovcheck, a)) - { - if (bs->cur_ps.weapon == WP_THERMAL) - { - if (((level.time - bs->cur_ps.weaponChargeTime) < (bs->frame_Enemy_Len*2) && - (level.time - bs->cur_ps.weaponChargeTime) < 4000 && - bs->frame_Enemy_Len > 64) || - (bs->cur_ps.weaponstate != WEAPON_CHARGING && - bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT)) - { - if (bs->cur_ps.weaponstate != WEAPON_CHARGING && bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT) - { - if (bs->frame_Enemy_Len > 512 && bs->frame_Enemy_Len < 800) - { + if (InFieldOfVision(bs->viewangles, fovcheck, a)) { + if (bs->cur_ps.weapon == WP_THERMAL) { + if (((level.time - bs->cur_ps.weaponChargeTime) < (bs->frame_Enemy_Len * 2) && (level.time - bs->cur_ps.weaponChargeTime) < 4000 && + bs->frame_Enemy_Len > 64) || + (bs->cur_ps.weaponstate != WEAPON_CHARGING && bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT)) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING && bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT) { + if (bs->frame_Enemy_Len > 512 && bs->frame_Enemy_Len < 800) { bs->doAltAttack = 1; - //bs->doAttack = 1; - } - else - { + // bs->doAttack = 1; + } else { bs->doAttack = 1; - //bs->doAltAttack = 1; + // bs->doAltAttack = 1; } } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING) { bs->doAttack = 1; - } - else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) - { + } else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) { bs->doAltAttack = 1; } } - } - else - { + } else { secFire = ShouldSecondaryFire(bs); - if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && - bs->cur_ps.weaponstate != WEAPON_CHARGING) - { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && bs->cur_ps.weaponstate != WEAPON_CHARGING) { bs->altChargeTime = Q_irand(500, 1000); } - if (secFire == 1) - { + if (secFire == 1) { bs->doAltAttack = 1; - } - else if (!secFire) - { - if (bs->cur_ps.weapon != WP_THERMAL) - { - if (bs->cur_ps.weaponstate != WEAPON_CHARGING || - bs->altChargeTime > (level.time - bs->cur_ps.weaponChargeTime)) - { + } else if (!secFire) { + if (bs->cur_ps.weapon != WP_THERMAL) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING || bs->altChargeTime > (level.time - bs->cur_ps.weaponChargeTime)) { bs->doAttack = 1; } - } - else - { + } else { bs->doAttack = 1; } } - if (secFire == 2) - { //released a charge + if (secFire == 2) { // released a charge return 1; } } @@ -5057,18 +4182,16 @@ int CombatBotAI(bot_state_t *bs, float thinktime) return 0; } -//we messed up and got off the normal path, let's fall -//back to jumping around and turning in random -//directions off walls to see if we can get back to a -//good place. -int BotFallbackNavigation(bot_state_t *bs) -{ +// we messed up and got off the normal path, let's fall +// back to jumping around and turning in random +// directions off walls to see if we can get back to a +// good place. +int BotFallbackNavigation(bot_state_t *bs) { vec3_t b_angle, fwd, trto, mins, maxs; trace_t tr; - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { - return 2; //we're busy + if (bs->currentEnemy && bs->frame_Enemy_Vis) { + return 2; // we're busy } mins[0] = -15; @@ -5085,100 +4208,80 @@ int BotFallbackNavigation(bot_state_t *bs) AngleVectors(b_angle, fwd, NULL, NULL); - trto[0] = bs->origin[0] + fwd[0]*16; - trto[1] = bs->origin[1] + fwd[1]*16; - trto[2] = bs->origin[2] + fwd[2]*16; + trto[0] = bs->origin[0] + fwd[0] * 16; + trto[1] = bs->origin[1] + fwd[1] * 16; + trto[2] = bs->origin[2] + fwd[2] * 16; trap->Trace(&tr, bs->origin, mins, maxs, trto, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { VectorCopy(trto, bs->goalPosition); - return 1; //success! - } - else - { - bs->goalAngles[YAW] = rand()%360; + return 1; // success! + } else { + bs->goalAngles[YAW] = rand() % 360; } return 0; } -int BotTryAnotherWeapon(bot_state_t *bs) -{ //out of ammo, resort to the first weapon we come across that has ammo +int BotTryAnotherWeapon(bot_state_t *bs) { // out of ammo, resort to the first weapon we come across that has ammo int i; i = 1; - while (i < WP_NUM_WEAPONS) - { - if (bs->cur_ps.ammo[weaponData[i].ammoIndex] >= weaponData[i].energyPerShot && - (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) - { + while (i < WP_NUM_WEAPONS) { + if (bs->cur_ps.ammo[weaponData[i].ammoIndex] >= weaponData[i].energyPerShot && (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) { bs->virtualWeapon = i; BotSelectWeapon(bs->client, i); - //bs->cur_ps.weapon = i; - //level.clients[bs->client].ps.weapon = i; + // bs->cur_ps.weapon = i; + // level.clients[bs->client].ps.weapon = i; return 1; } i++; } - if (bs->cur_ps.weapon != 1 && bs->virtualWeapon != 1) - { //should always have this.. shouldn't we? + if (bs->cur_ps.weapon != 1 && bs->virtualWeapon != 1) { // should always have this.. shouldn't we? bs->virtualWeapon = 1; BotSelectWeapon(bs->client, 1); - //bs->cur_ps.weapon = 1; - //level.clients[bs->client].ps.weapon = 1; + // bs->cur_ps.weapon = 1; + // level.clients[bs->client].ps.weapon = 1; return 1; } return 0; } -//is this weapon available to us? -qboolean BotWeaponSelectable(bot_state_t *bs, int weapon) -{ - if (weapon == WP_NONE) - { +// is this weapon available to us? +qboolean BotWeaponSelectable(bot_state_t *bs, int weapon) { + if (weapon == WP_NONE) { return qfalse; } - if (bs->cur_ps.ammo[weaponData[weapon].ammoIndex] >= weaponData[weapon].energyPerShot && - (bs->cur_ps.stats[STAT_WEAPONS] & (1 << weapon))) - { + if (bs->cur_ps.ammo[weaponData[weapon].ammoIndex] >= weaponData[weapon].energyPerShot && (bs->cur_ps.stats[STAT_WEAPONS] & (1 << weapon))) { return qtrue; } return qfalse; } -//select the best weapon we can -int BotSelectIdealWeapon(bot_state_t *bs) -{ +// select the best weapon we can +int BotSelectIdealWeapon(bot_state_t *bs) { int i; int bestweight = -1; int bestweapon = 0; i = 0; - while (i < WP_NUM_WEAPONS) - { - if (bs->cur_ps.ammo[weaponData[i].ammoIndex] >= weaponData[i].energyPerShot && - bs->botWeaponWeights[i] > bestweight && - (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) - { - if (i == WP_THERMAL) - { //special case.. - if (bs->currentEnemy && bs->frame_Enemy_Len < 700) - { + while (i < WP_NUM_WEAPONS) { + if (bs->cur_ps.ammo[weaponData[i].ammoIndex] >= weaponData[i].energyPerShot && bs->botWeaponWeights[i] > bestweight && + (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) { + if (i == WP_THERMAL) { // special case.. + if (bs->currentEnemy && bs->frame_Enemy_Len < 700) { bestweight = bs->botWeaponWeights[i]; bestweapon = i; } - } - else - { + } else { bestweight = bs->botWeaponWeights[i]; bestweapon = i; } @@ -5187,80 +4290,60 @@ int BotSelectIdealWeapon(bot_state_t *bs) i++; } - if ( bs->currentEnemy && bs->frame_Enemy_Len < 300 && - (bestweapon == WP_BRYAR_PISTOL || bestweapon == WP_BLASTER || bestweapon == WP_BOWCASTER) && - (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) ) - { + if (bs->currentEnemy && bs->frame_Enemy_Len < 300 && (bestweapon == WP_BRYAR_PISTOL || bestweapon == WP_BLASTER || bestweapon == WP_BOWCASTER) && + (bs->cur_ps.stats[STAT_WEAPONS] & (1 << WP_SABER))) { bestweapon = WP_SABER; bestweight = 1; } - if ( bs->currentEnemy && bs->frame_Enemy_Len > 300 && - bs->currentEnemy->client && bs->currentEnemy->client->ps.weapon != WP_SABER && - (bestweapon == WP_SABER) ) - { //if the enemy is far away, and we have our saber selected, see if we have any good distance weapons instead - if (BotWeaponSelectable(bs, WP_DISRUPTOR)) - { + if (bs->currentEnemy && bs->frame_Enemy_Len > 300 && bs->currentEnemy->client && bs->currentEnemy->client->ps.weapon != WP_SABER && + (bestweapon == WP_SABER)) { // if the enemy is far away, and we have our saber selected, see if we have any good distance weapons instead + if (BotWeaponSelectable(bs, WP_DISRUPTOR)) { bestweapon = WP_DISRUPTOR; bestweight = 1; - } - else if (BotWeaponSelectable(bs, WP_ROCKET_LAUNCHER)) - { + } else if (BotWeaponSelectable(bs, WP_ROCKET_LAUNCHER)) { bestweapon = WP_ROCKET_LAUNCHER; bestweight = 1; - } - else if (BotWeaponSelectable(bs, WP_BOWCASTER)) - { + } else if (BotWeaponSelectable(bs, WP_BOWCASTER)) { bestweapon = WP_BOWCASTER; bestweight = 1; - } - else if (BotWeaponSelectable(bs, WP_BLASTER)) - { + } else if (BotWeaponSelectable(bs, WP_BLASTER)) { bestweapon = WP_BLASTER; bestweight = 1; - } - else if (BotWeaponSelectable(bs, WP_REPEATER)) - { + } else if (BotWeaponSelectable(bs, WP_REPEATER)) { bestweapon = WP_REPEATER; bestweight = 1; - } - else if (BotWeaponSelectable(bs, WP_DEMP2)) - { + } else if (BotWeaponSelectable(bs, WP_DEMP2)) { bestweapon = WP_DEMP2; bestweight = 1; } } - //assert(bs->cur_ps.weapon > 0 && bestweapon > 0); + // assert(bs->cur_ps.weapon > 0 && bestweapon > 0); - if (bestweight != -1 && bs->cur_ps.weapon != bestweapon && bs->virtualWeapon != bestweapon) - { + if (bestweight != -1 && bs->cur_ps.weapon != bestweapon && bs->virtualWeapon != bestweapon) { bs->virtualWeapon = bestweapon; BotSelectWeapon(bs->client, bestweapon); - //bs->cur_ps.weapon = bestweapon; - //level.clients[bs->client].ps.weapon = bestweapon; + // bs->cur_ps.weapon = bestweapon; + // level.clients[bs->client].ps.weapon = bestweapon; return 1; } - //assert(bs->cur_ps.weapon > 0); + // assert(bs->cur_ps.weapon > 0); return 0; } -//check/select the chosen weapon -int BotSelectChoiceWeapon(bot_state_t *bs, int weapon, int doselection) -{ //if !doselection then bot will only check if he has the specified weapon and return 1 (yes) or 0 (no) +// check/select the chosen weapon +int BotSelectChoiceWeapon(bot_state_t *bs, int weapon, + int doselection) { // if !doselection then bot will only check if he has the specified weapon and return 1 (yes) or 0 (no) int i; int hasit = 0; i = 0; - while (i < WP_NUM_WEAPONS) - { - if (bs->cur_ps.ammo[weaponData[i].ammoIndex] > weaponData[i].energyPerShot && - i == weapon && - (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) - { + while (i < WP_NUM_WEAPONS) { + if (bs->cur_ps.ammo[weaponData[i].ammoIndex] > weaponData[i].energyPerShot && i == weapon && (bs->cur_ps.stats[STAT_WEAPONS] & (1 << i))) { hasit = 1; break; } @@ -5268,75 +4351,63 @@ int BotSelectChoiceWeapon(bot_state_t *bs, int weapon, int doselection) i++; } - if (hasit && bs->cur_ps.weapon != weapon && doselection && bs->virtualWeapon != weapon) - { + if (hasit && bs->cur_ps.weapon != weapon && doselection && bs->virtualWeapon != weapon) { bs->virtualWeapon = weapon; BotSelectWeapon(bs->client, weapon); - //bs->cur_ps.weapon = weapon; - //level.clients[bs->client].ps.weapon = weapon; + // bs->cur_ps.weapon = weapon; + // level.clients[bs->client].ps.weapon = weapon; return 2; } - if (hasit) - { + if (hasit) { return 1; } return 0; } -//override our standard weapon choice with a melee weapon -int BotSelectMelee(bot_state_t *bs) -{ - if (bs->cur_ps.weapon != 1 && bs->virtualWeapon != 1) - { +// override our standard weapon choice with a melee weapon +int BotSelectMelee(bot_state_t *bs) { + if (bs->cur_ps.weapon != 1 && bs->virtualWeapon != 1) { bs->virtualWeapon = 1; BotSelectWeapon(bs->client, 1); - //bs->cur_ps.weapon = 1; - //level.clients[bs->client].ps.weapon = 1; + // bs->cur_ps.weapon = 1; + // level.clients[bs->client].ps.weapon = 1; return 1; } return 0; } -//See if we our in love with the potential bot. -int GetLoveLevel(bot_state_t *bs, bot_state_t *love) -{ +// See if we our in love with the potential bot. +int GetLoveLevel(bot_state_t *bs, bot_state_t *love) { int i = 0; const char *lname = NULL; - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { //There is no love in 1-on-1 + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // There is no love in 1-on-1 return 0; } - if (!bs || !love || !g_entities[love->client].client) - { + if (!bs || !love || !g_entities[love->client].client) { return 0; } - if (!bs->lovednum) - { + if (!bs->lovednum) { return 0; } - if (!bot_attachments.integer) - { + if (!bot_attachments.integer) { return 1; } lname = g_entities[love->client].client->pers.netname; - if (!lname) - { + if (!lname) { return 0; } - while (i < bs->lovednum) - { - if (strcmp(bs->loved[i].name, lname) == 0) - { + while (i < bs->lovednum) { + if (strcmp(bs->loved[i].name, lname) == 0) { return bs->loved[i].level; } @@ -5346,74 +4417,57 @@ int GetLoveLevel(bot_state_t *bs, bot_state_t *love) return 0; } -//Our loved one was killed. We must become infuriated! -void BotLovedOneDied(bot_state_t *bs, bot_state_t *loved, int lovelevel) -{ - if (!loved->lastHurt || !loved->lastHurt->client || - loved->lastHurt->s.number == loved->client) - { +// Our loved one was killed. We must become infuriated! +void BotLovedOneDied(bot_state_t *bs, bot_state_t *loved, int lovelevel) { + if (!loved->lastHurt || !loved->lastHurt->client || loved->lastHurt->s.number == loved->client) { return; } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { //There is no love in 1-on-1 + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // There is no love in 1-on-1 return; } - if (!IsTeamplay()) - { - if (lovelevel < 2) - { + if (!IsTeamplay()) { + if (lovelevel < 2) { return; } - } - else if (OnSameTeam(&g_entities[bs->client], loved->lastHurt)) - { //don't hate teammates no matter what + } else if (OnSameTeam(&g_entities[bs->client], loved->lastHurt)) { // don't hate teammates no matter what return; } - if (loved->client == loved->lastHurt->s.number) - { + if (loved->client == loved->lastHurt->s.number) { return; } - if (bs->client == loved->lastHurt->s.number) - { //oops! + if (bs->client == loved->lastHurt->s.number) { // oops! return; } - if (!bot_attachments.integer) - { + if (!bot_attachments.integer) { return; } - if (!PassLovedOneCheck(bs, loved->lastHurt)) - { //a loved one killed a loved one.. you cannot hate them + if (!PassLovedOneCheck(bs, loved->lastHurt)) { // a loved one killed a loved one.. you cannot hate them bs->chatObject = loved->lastHurt; bs->chatAltObject = &g_entities[loved->client]; BotDoChat(bs, "LovedOneKilledLovedOne", 0); return; } - if (bs->revengeEnemy == loved->lastHurt) - { - if (bs->revengeHateLevel < bs->loved_death_thresh) - { + if (bs->revengeEnemy == loved->lastHurt) { + if (bs->revengeHateLevel < bs->loved_death_thresh) { bs->revengeHateLevel++; - if (bs->revengeHateLevel == bs->loved_death_thresh) - { - //broke into the highest anger level - //CHAT: Hatred section + if (bs->revengeHateLevel == bs->loved_death_thresh) { + // broke into the highest anger level + // CHAT: Hatred section bs->chatObject = loved->lastHurt; bs->chatAltObject = NULL; BotDoChat(bs, "Hatred", 1); } } - } - else if (bs->revengeHateLevel < bs->loved_death_thresh-1) - { //only switch hatred if we don't hate the existing revenge-enemy too much - //CHAT: BelovedKilled section + } else if (bs->revengeHateLevel < bs->loved_death_thresh - 1) { // only switch hatred if we don't hate the existing revenge-enemy too much + // CHAT: BelovedKilled section bs->chatObject = &g_entities[loved->client]; bs->chatAltObject = loved->lastHurt; BotDoChat(bs, "BelovedKilled", 0); @@ -5422,20 +4476,15 @@ void BotLovedOneDied(bot_state_t *bs, bot_state_t *loved, int lovelevel) } } -void BotDeathNotify(bot_state_t *bs) -{ //in case someone has an emotional attachment to us, we'll notify them +void BotDeathNotify(bot_state_t *bs) { // in case someone has an emotional attachment to us, we'll notify them int i = 0; int ltest = 0; - while (i < MAX_CLIENTS) - { - if (botstates[i] && botstates[i]->lovednum) - { + while (i < MAX_CLIENTS) { + if (botstates[i] && botstates[i]->lovednum) { ltest = 0; - while (ltest < botstates[i]->lovednum) - { - if (strcmp(level.clients[bs->client].pers.netname, botstates[i]->loved[ltest].name) == 0) - { + while (ltest < botstates[i]->lovednum) { + if (strcmp(level.clients[bs->client].pers.netname, botstates[i]->loved[ltest].name) == 0) { BotLovedOneDied(botstates[i], bs, botstates[i]->loved[ltest].level); break; } @@ -5448,16 +4497,15 @@ void BotDeathNotify(bot_state_t *bs) } } -//perform strafe trace checks -void StrafeTracing(bot_state_t *bs) -{ +// perform strafe trace checks +void StrafeTracing(bot_state_t *bs) { vec3_t mins, maxs; vec3_t right, rorg, drorg; trace_t tr; mins[0] = -15; mins[1] = -15; - //mins[2] = -24; + // mins[2] = -24; mins[2] = -22; maxs[0] = 15; maxs[1] = 15; @@ -5465,23 +4513,19 @@ void StrafeTracing(bot_state_t *bs) AngleVectors(bs->viewangles, NULL, right, NULL); - if (bs->meleeStrafeDir) - { - rorg[0] = bs->origin[0] - right[0]*32; - rorg[1] = bs->origin[1] - right[1]*32; - rorg[2] = bs->origin[2] - right[2]*32; - } - else - { - rorg[0] = bs->origin[0] + right[0]*32; - rorg[1] = bs->origin[1] + right[1]*32; - rorg[2] = bs->origin[2] + right[2]*32; + if (bs->meleeStrafeDir) { + rorg[0] = bs->origin[0] - right[0] * 32; + rorg[1] = bs->origin[1] - right[1] * 32; + rorg[2] = bs->origin[2] - right[2] * 32; + } else { + rorg[0] = bs->origin[0] + right[0] * 32; + rorg[1] = bs->origin[1] + right[1] * 32; + rorg[2] = bs->origin[2] + right[2] * 32; } trap->Trace(&tr, bs->origin, mins, maxs, rorg, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1) - { + if (tr.fraction != 1) { bs->meleeStrafeDisable = level.time + Q_irand(500, 1500); } @@ -5491,87 +4535,65 @@ void StrafeTracing(bot_state_t *bs) trap->Trace(&tr, rorg, NULL, NULL, drorg, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { //this may be a dangerous ledge, so don't strafe over it just in case + if (tr.fraction == 1) { // this may be a dangerous ledge, so don't strafe over it just in case bs->meleeStrafeDisable = level.time + Q_irand(500, 1500); } } -//doing primary weapon fire -int PrimFiring(bot_state_t *bs) -{ - if (bs->cur_ps.weaponstate != WEAPON_CHARGING && - bs->doAttack) - { +// doing primary weapon fire +int PrimFiring(bot_state_t *bs) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING && bs->doAttack) { return 1; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING && - !bs->doAttack) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING && !bs->doAttack) { return 1; } return 0; } -//should we keep our primary weapon from firing? -int KeepPrimFromFiring(bot_state_t *bs) -{ - if (bs->cur_ps.weaponstate != WEAPON_CHARGING && - bs->doAttack) - { +// should we keep our primary weapon from firing? +int KeepPrimFromFiring(bot_state_t *bs) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING && bs->doAttack) { bs->doAttack = 0; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING && - !bs->doAttack) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING && !bs->doAttack) { bs->doAttack = 1; } return 0; } -//doing secondary weapon fire -int AltFiring(bot_state_t *bs) -{ - if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && - bs->doAltAttack) - { +// doing secondary weapon fire +int AltFiring(bot_state_t *bs) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && bs->doAltAttack) { return 1; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && - !bs->doAltAttack) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && !bs->doAltAttack) { return 1; } return 0; } -//should we keep our alt from firing? -int KeepAltFromFiring(bot_state_t *bs) -{ - if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && - bs->doAltAttack) - { +// should we keep our alt from firing? +int KeepAltFromFiring(bot_state_t *bs) { + if (bs->cur_ps.weaponstate != WEAPON_CHARGING_ALT && bs->doAltAttack) { bs->doAltAttack = 0; } - if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && - !bs->doAltAttack) - { + if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT && !bs->doAltAttack) { bs->doAltAttack = 1; } return 0; } -//Try not to shoot our friends in the back. Or in the face. Or anywhere, really. -gentity_t *CheckForFriendInLOF(bot_state_t *bs) -{ +// Try not to shoot our friends in the back. Or in the face. Or anywhere, really. +gentity_t *CheckForFriendInLOF(bot_state_t *bs) { vec3_t fwd; vec3_t trfrom, trto; vec3_t mins, maxs; @@ -5590,25 +4612,21 @@ gentity_t *CheckForFriendInLOF(bot_state_t *bs) VectorCopy(bs->eye, trfrom); - trto[0] = trfrom[0] + fwd[0]*2048; - trto[1] = trfrom[1] + fwd[1]*2048; - trto[2] = trfrom[2] + fwd[2]*2048; + trto[0] = trfrom[0] + fwd[0] * 2048; + trto[1] = trfrom[1] + fwd[1] * 2048; + trto[2] = trfrom[2] + fwd[2] * 2048; trap->Trace(&tr, trfrom, mins, maxs, trto, bs->client, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum <= MAX_CLIENTS) - { + if (tr.fraction != 1 && tr.entityNum <= MAX_CLIENTS) { trent = &g_entities[tr.entityNum]; - if (trent && trent->client) - { - if (IsTeamplay() && OnSameTeam(&g_entities[bs->client], trent)) - { + if (trent && trent->client) { + if (IsTeamplay() && OnSameTeam(&g_entities[bs->client], trent)) { return trent; } - if (botstates[trent->s.number] && GetLoveLevel(bs, botstates[trent->s.number]) > 1) - { + if (botstates[trent->s.number] && GetLoveLevel(bs, botstates[trent->s.number]) > 1) { return trent; } } @@ -5617,29 +4635,23 @@ gentity_t *CheckForFriendInLOF(bot_state_t *bs) return NULL; } -void BotScanForLeader(bot_state_t *bs) -{ //bots will only automatically obtain a leader if it's another bot using this method. +void BotScanForLeader(bot_state_t *bs) { // bots will only automatically obtain a leader if it's another bot using this method. int i = 0; gentity_t *ent; - if (bs->isSquadLeader) - { + if (bs->isSquadLeader) { return; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && botstates[i] && botstates[i]->isSquadLeader && bs->client != i) - { - if (OnSameTeam(&g_entities[bs->client], ent)) - { + if (ent && ent->client && botstates[i] && botstates[i]->isSquadLeader && bs->client != i) { + if (OnSameTeam(&g_entities[bs->client], ent)) { bs->squadLeader = ent; break; } - if (GetLoveLevel(bs, botstates[i]) > 1 && !IsTeamplay()) - { //ignore love status regarding squad leaders if we're in teamplay + if (GetLoveLevel(bs, botstates[i]) > 1 && !IsTeamplay()) { // ignore love status regarding squad leaders if we're in teamplay bs->squadLeader = ent; break; } @@ -5649,28 +4661,21 @@ void BotScanForLeader(bot_state_t *bs) } } -//w3rd to the p33pz. -void BotReplyGreetings(bot_state_t *bs) -{ +// w3rd to the p33pz. +void BotReplyGreetings(bot_state_t *bs) { int i = 0; int numhello = 0; - while (i < MAX_CLIENTS) - { - if (botstates[i] && - botstates[i]->canChat && - i != bs->client) - { + while (i < MAX_CLIENTS) { + if (botstates[i] && botstates[i]->canChat && i != bs->client) { botstates[i]->chatObject = &g_entities[bs->client]; botstates[i]->chatAltObject = NULL; - if (BotDoChat(botstates[i], "ResponseGreetings", 0)) - { + if (BotDoChat(botstates[i], "ResponseGreetings", 0)) { numhello++; } } - if (numhello > 3) - { //don't let more than 4 bots say hello at once + if (numhello > 3) { // don't let more than 4 bots say hello at once return; } @@ -5678,9 +4683,8 @@ void BotReplyGreetings(bot_state_t *bs) } } -//try to move in to grab a nearby flag -void CTFFlagMovement(bot_state_t *bs) -{ +// try to move in to grab a nearby flag +void CTFFlagMovement(bot_state_t *bs) { int diddrop = 0; gentity_t *desiredDrop = NULL; vec3_t a, mins, maxs; @@ -5693,60 +4697,44 @@ void CTFFlagMovement(bot_state_t *bs) maxs[1] = 15; maxs[2] = 7; - if (bs->wantFlag && (bs->wantFlag->flags & FL_DROPPED_ITEM)) - { - if (bs->staticFlagSpot[0] == bs->wantFlag->s.pos.trBase[0] && - bs->staticFlagSpot[1] == bs->wantFlag->s.pos.trBase[1] && - bs->staticFlagSpot[2] == bs->wantFlag->s.pos.trBase[2]) - { + if (bs->wantFlag && (bs->wantFlag->flags & FL_DROPPED_ITEM)) { + if (bs->staticFlagSpot[0] == bs->wantFlag->s.pos.trBase[0] && bs->staticFlagSpot[1] == bs->wantFlag->s.pos.trBase[1] && + bs->staticFlagSpot[2] == bs->wantFlag->s.pos.trBase[2]) { VectorSubtract(bs->origin, bs->wantFlag->s.pos.trBase, a); - if (VectorLength(a) <= BOT_FLAG_GET_DISTANCE) - { + if (VectorLength(a) <= BOT_FLAG_GET_DISTANCE) { VectorCopy(bs->wantFlag->s.pos.trBase, bs->goalPosition); return; - } - else - { + } else { bs->wantFlag = NULL; } - } - else - { + } else { bs->wantFlag = NULL; } - } - else if (bs->wantFlag) - { + } else if (bs->wantFlag) { bs->wantFlag = NULL; } - if (flagRed && flagBlue) - { - if (bs->wpDestination == flagRed || - bs->wpDestination == flagBlue) - { - if (bs->wpDestination == flagRed && droppedRedFlag && (droppedRedFlag->flags & FL_DROPPED_ITEM) && droppedRedFlag->classname && strcmp(droppedRedFlag->classname, "freed") != 0) - { + if (flagRed && flagBlue) { + if (bs->wpDestination == flagRed || bs->wpDestination == flagBlue) { + if (bs->wpDestination == flagRed && droppedRedFlag && (droppedRedFlag->flags & FL_DROPPED_ITEM) && droppedRedFlag->classname && + strcmp(droppedRedFlag->classname, "freed") != 0) { desiredDrop = droppedRedFlag; diddrop = 1; } - if (bs->wpDestination == flagBlue && droppedBlueFlag && (droppedBlueFlag->flags & FL_DROPPED_ITEM) && droppedBlueFlag->classname && strcmp(droppedBlueFlag->classname, "freed") != 0) - { + if (bs->wpDestination == flagBlue && droppedBlueFlag && (droppedBlueFlag->flags & FL_DROPPED_ITEM) && droppedBlueFlag->classname && + strcmp(droppedBlueFlag->classname, "freed") != 0) { desiredDrop = droppedBlueFlag; diddrop = 1; } - if (diddrop && desiredDrop) - { + if (diddrop && desiredDrop) { VectorSubtract(bs->origin, desiredDrop->s.pos.trBase, a); - if (VectorLength(a) <= BOT_FLAG_GET_DISTANCE) - { + if (VectorLength(a) <= BOT_FLAG_GET_DISTANCE) { trap->Trace(&tr, bs->origin, mins, maxs, desiredDrop->s.pos.trBase, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == desiredDrop->s.number) - { + if (tr.fraction == 1 || tr.entityNum == desiredDrop->s.number) { VectorCopy(desiredDrop->s.pos.trBase, bs->goalPosition); VectorCopy(desiredDrop->s.pos.trBase, bs->staticFlagSpot); return; @@ -5757,36 +4745,30 @@ void CTFFlagMovement(bot_state_t *bs) } } -//see if we want to make our detpacks blow up -void BotCheckDetPacks(bot_state_t *bs) -{ +// see if we want to make our detpacks blow up +void BotCheckDetPacks(bot_state_t *bs) { gentity_t *dp = NULL; gentity_t *myDet = NULL; vec3_t a; float enLen; float myLen; - while ( (dp = G_Find( dp, FOFS(classname), "detpack") ) != NULL ) - { - if (dp && dp->parent && dp->parent->s.number == bs->client) - { + while ((dp = G_Find(dp, FOFS(classname), "detpack")) != NULL) { + if (dp && dp->parent && dp->parent->s.number == bs->client) { myDet = dp; break; } } - if (!myDet) - { + if (!myDet) { return; } - if (!bs->currentEnemy || !bs->currentEnemy->client || !bs->frame_Enemy_Vis) - { //require the enemy to be visilbe just to be fair.. + if (!bs->currentEnemy || !bs->currentEnemy->client || !bs->frame_Enemy_Vis) { // require the enemy to be visilbe just to be fair.. - //unless.. + // unless.. if (bs->currentEnemy && bs->currentEnemy->client && - (level.time - bs->plantContinue) < 5000) - { //it's a fresh plant (within 5 seconds) so we should be able to guess + (level.time - bs->plantContinue) < 5000) { // it's a fresh plant (within 5 seconds) so we should be able to guess goto stillmadeit; } return; @@ -5800,57 +4782,46 @@ void BotCheckDetPacks(bot_state_t *bs) VectorSubtract(bs->origin, myDet->s.pos.trBase, a); myLen = VectorLength(a); - if (enLen > myLen) - { + if (enLen > myLen) { return; } - if (enLen < BOT_PLANT_BLOW_DISTANCE && OrgVisible(bs->currentEnemy->client->ps.origin, myDet->s.pos.trBase, bs->currentEnemy->s.number)) - { //we could just call the "blow all my detpacks" function here, but I guess that's cheating. + if (enLen < BOT_PLANT_BLOW_DISTANCE && + OrgVisible(bs->currentEnemy->client->ps.origin, myDet->s.pos.trBase, + bs->currentEnemy->s.number)) { // we could just call the "blow all my detpacks" function here, but I guess that's cheating. bs->plantKillEmAll = level.time + 500; } } -//see if it would be beneficial at this time to use one of our inv items -int BotUseInventoryItem(bot_state_t *bs) -{ - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) - { - if (g_entities[bs->client].health <= 75) - { +// see if it would be beneficial at this time to use one of our inv items +int BotUseInventoryItem(bot_state_t *bs) { + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) { + if (g_entities[bs->client].health <= 75) { bs->cur_ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(HI_MEDPAC, IT_HOLDABLE); goto wantuseitem; } } - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) - { - if (g_entities[bs->client].health <= 50) - { + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) { + if (g_entities[bs->client].health <= 50) { bs->cur_ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(HI_MEDPAC_BIG, IT_HOLDABLE); goto wantuseitem; } } - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) - { - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) { + if (bs->currentEnemy && bs->frame_Enemy_Vis) { bs->cur_ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(HI_SEEKER, IT_HOLDABLE); goto wantuseitem; } } - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) - { - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) { + if (bs->currentEnemy && bs->frame_Enemy_Vis) { bs->cur_ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(HI_SENTRY_GUN, IT_HOLDABLE); goto wantuseitem; } } - if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) - { - if (bs->currentEnemy && bs->frame_Enemy_Vis && bs->runningToEscapeThreat) - { //this will (hopefully) result in the bot placing the shield down while facing - //the enemy and running away + if (bs->cur_ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) { + if (bs->currentEnemy && bs->frame_Enemy_Vis && bs->runningToEscapeThreat) { // this will (hopefully) result in the bot placing the shield down while + // facing the enemy and running away bs->cur_ps.stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(HI_SHIELD, IT_HOLDABLE); goto wantuseitem; } @@ -5864,33 +4835,29 @@ int BotUseInventoryItem(bot_state_t *bs) return 1; } -//trace forward to see if we can plant a detpack or something -int BotSurfaceNear(bot_state_t *bs) -{ +// trace forward to see if we can plant a detpack or something +int BotSurfaceNear(bot_state_t *bs) { trace_t tr; vec3_t fwd; AngleVectors(bs->viewangles, fwd, NULL, NULL); - fwd[0] = bs->origin[0]+(fwd[0]*64); - fwd[1] = bs->origin[1]+(fwd[1]*64); - fwd[2] = bs->origin[2]+(fwd[2]*64); + fwd[0] = bs->origin[0] + (fwd[0] * 64); + fwd[1] = bs->origin[1] + (fwd[1] * 64); + fwd[2] = bs->origin[2] + (fwd[2] * 64); trap->Trace(&tr, bs->origin, NULL, NULL, fwd, bs->client, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1) - { + if (tr.fraction != 1) { return 1; } return 0; } -//could we block projectiles from the weapon potentially with a light saber? -int BotWeaponBlockable(int weapon) -{ - switch (weapon) - { +// could we block projectiles from the weapon potentially with a light saber? +int BotWeaponBlockable(int weapon) { + switch (weapon) { case WP_STUN_BATON: case WP_MELEE: return 0; @@ -5914,57 +4881,42 @@ int BotWeaponBlockable(int weapon) void Cmd_EngageDuel_f(gentity_t *ent); void Cmd_ToggleSaber_f(gentity_t *ent); -//movement overrides -void Bot_SetForcedMovement(int bot, int forward, int right, int up) -{ +// movement overrides +void Bot_SetForcedMovement(int bot, int forward, int right, int up) { bot_state_t *bs; bs = botstates[bot]; - if (!bs) - { //not a bot + if (!bs) { // not a bot return; } - if (forward != -1) - { - if (bs->forceMove_Forward) - { + if (forward != -1) { + if (bs->forceMove_Forward) { bs->forceMove_Forward = 0; - } - else - { + } else { bs->forceMove_Forward = forward; } } - if (right != -1) - { - if (bs->forceMove_Right) - { + if (right != -1) { + if (bs->forceMove_Right) { bs->forceMove_Right = 0; - } - else - { + } else { bs->forceMove_Right = right; } } - if (up != -1) - { - if (bs->forceMove_Up) - { + if (up != -1) { + if (bs->forceMove_Up) { bs->forceMove_Up = 0; - } - else - { + } else { bs->forceMove_Up = up; } } } -//the main AI loop. -//please don't be too frightened. -void StandardBotAI(bot_state_t *bs, float thinktime) -{ +// the main AI loop. +// please don't be too frightened. +void StandardBotAI(bot_state_t *bs, float thinktime) { int wp, enemy; int desiredIndex; int goalWPIndex; @@ -5984,8 +4936,7 @@ void StandardBotAI(bot_state_t *bs, float thinktime) int detSelect = 0; vec3_t preFrameGAngles; - if (gDeactivated) - { + if (gDeactivated) { bs->wpCurrent = NULL; bs->currentEnemy = NULL; bs->wpDestination = NULL; @@ -5993,10 +4944,7 @@ void StandardBotAI(bot_state_t *bs, float thinktime) return; } - if (g_entities[bs->client].inuse && - g_entities[bs->client].client && - g_entities[bs->client].client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (g_entities[bs->client].inuse && g_entities[bs->client].client && g_entities[bs->client].client->sess.sessionTeam == TEAM_SPECTATOR) { bs->wpCurrent = NULL; bs->currentEnemy = NULL; bs->wpDestination = NULL; @@ -6004,45 +4952,34 @@ void StandardBotAI(bot_state_t *bs, float thinktime) return; } - #ifndef FINAL_BUILD - if (bot_getinthecarrr.integer) - { //stupid vehicle debug, I tire of having to connect another client to test passengers. + if (bot_getinthecarrr.integer) { // stupid vehicle debug, I tire of having to connect another client to test passengers. gentity_t *botEnt = &g_entities[bs->client]; - if (botEnt->inuse && botEnt->client && botEnt->client->ps.m_iVehicleNum) - { //in a vehicle, so... + if (botEnt->inuse && botEnt->client && botEnt->client->ps.m_iVehicleNum) { // in a vehicle, so... bs->noUseTime = level.time + 5000; - if (bot_getinthecarrr.integer != 2) - { + if (bot_getinthecarrr.integer != 2) { trap->EA_MoveForward(bs->client); - if (bot_getinthecarrr.integer == 3) - { //use alt fire + if (bot_getinthecarrr.integer == 3) { // use alt fire trap->EA_Alt_Attack(bs->client); } } - } - else - { //find one, get in + } else { // find one, get in int i = 0; gentity_t *vehicle = NULL; - //find the nearest, manned vehicle - while (i < MAX_GENTITIES) - { + // find the nearest, manned vehicle + while (i < MAX_GENTITIES) { vehicle = &g_entities[i]; - if (vehicle->inuse && vehicle->client && vehicle->s.eType == ET_NPC && - vehicle->s.NPC_class == CLASS_VEHICLE && vehicle->m_pVehicle && - (vehicle->client->ps.m_iVehicleNum || bot_getinthecarrr.integer == 2)) - { //ok, this is a vehicle, and it has a pilot/passengers + if (vehicle->inuse && vehicle->client && vehicle->s.eType == ET_NPC && vehicle->s.NPC_class == CLASS_VEHICLE && vehicle->m_pVehicle && + (vehicle->client->ps.m_iVehicleNum || bot_getinthecarrr.integer == 2)) { // ok, this is a vehicle, and it has a pilot/passengers break; } i++; } - if (i != MAX_GENTITIES && vehicle) - { //broke before end so we must've found something + if (i != MAX_GENTITIES && vehicle) { // broke before end so we must've found something vec3_t v; VectorSubtract(vehicle->client->ps.origin, bs->origin, v); @@ -6051,8 +4988,7 @@ void StandardBotAI(bot_state_t *bs, float thinktime) MoveTowardIdealAngles(bs); trap->EA_Move(bs->client, v, 5000.0f); - if (bs->noUseTime < (level.time-400)) - { + if (bs->noUseTime < (level.time - 400)) { bs->noUseTime = level.time + 500; } } @@ -6062,20 +4998,17 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } #endif - if (bot_forgimmick.integer) - { + if (bot_forgimmick.integer) { bs->wpCurrent = NULL; bs->currentEnemy = NULL; bs->wpDestination = NULL; bs->wpDirection = 0; - if (bot_forgimmick.integer == 2) - { //for debugging saber stuff, this is handy + if (bot_forgimmick.integer == 2) { // for debugging saber stuff, this is handy trap->EA_Attack(bs->client); } - if (bot_forgimmick.integer == 3) - { //for testing cpu usage moving around rmg terrain without AI + if (bot_forgimmick.integer == 3) { // for testing cpu usage moving around rmg terrain without AI vec3_t mdir; VectorSubtract(bs->origin, vec3_origin, mdir); @@ -6084,10 +5017,8 @@ void StandardBotAI(bot_state_t *bs, float thinktime) trap->EA_Move(bs->client, mdir, 5000); } - if (bot_forgimmick.integer == 4) - { //constantly move toward client 0 - if (g_entities[0].client && g_entities[0].inuse) - { + if (bot_forgimmick.integer == 4) { // constantly move toward client 0 + if (g_entities[0].client && g_entities[0].inuse) { vec3_t mdir; VectorSubtract(g_entities[0].client->ps.origin, bs->origin, mdir); @@ -6096,58 +5027,43 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } - if (bs->forceMove_Forward) - { - if (bs->forceMove_Forward > 0) - { + if (bs->forceMove_Forward) { + if (bs->forceMove_Forward > 0) { trap->EA_MoveForward(bs->client); - } - else - { + } else { trap->EA_MoveBack(bs->client); } } - if (bs->forceMove_Right) - { - if (bs->forceMove_Right > 0) - { + if (bs->forceMove_Right) { + if (bs->forceMove_Right > 0) { trap->EA_MoveRight(bs->client); - } - else - { + } else { trap->EA_MoveLeft(bs->client); } } - if (bs->forceMove_Up) - { + if (bs->forceMove_Up) { trap->EA_Jump(bs->client); } return; } - if (!bs->lastDeadTime) - { //just spawned in? + if (!bs->lastDeadTime) { // just spawned in? bs->lastDeadTime = level.time; } - if (g_entities[bs->client].health < 1) - { + if (g_entities[bs->client].health < 1) { bs->lastDeadTime = level.time; - if (!bs->deathActivitiesDone && bs->lastHurt && bs->lastHurt->client && bs->lastHurt->s.number != bs->client) - { + if (!bs->deathActivitiesDone && bs->lastHurt && bs->lastHurt->client && bs->lastHurt->s.number != bs->client) { BotDeathNotify(bs); - if (PassLovedOneCheck(bs, bs->lastHurt)) - { - //CHAT: Died + if (PassLovedOneCheck(bs, bs->lastHurt)) { + // CHAT: Died bs->chatObject = bs->lastHurt; bs->chatAltObject = NULL; BotDoChat(bs, "Died", 0); - } - else if (!PassLovedOneCheck(bs, bs->lastHurt) && - botstates[bs->lastHurt->s.number] && - PassLovedOneCheck(botstates[bs->lastHurt->s.number], &g_entities[bs->client])) - { //killed by a bot that I love, but that does not love me + } else if (!PassLovedOneCheck(bs, bs->lastHurt) && botstates[bs->lastHurt->s.number] && + PassLovedOneCheck(botstates[bs->lastHurt->s.number], + &g_entities[bs->client])) { // killed by a bot that I love, but that does not love me bs->chatObject = bs->lastHurt; bs->chatAltObject = NULL; BotDoChat(bs, "KilledOnPurposeByLove", 0); @@ -6167,9 +5083,7 @@ void StandardBotAI(bot_state_t *bs, float thinktime) bs->wpSeenTime = 0; bs->wpDirection = 0; - if (rand()%10 < 5 && - (!bs->doChat || bs->chatTime < level.time)) - { + if (rand() % 10 < 5 && (!bs->doChat || bs->chatTime < level.time)) { trap->EA_Attack(bs->client); } @@ -6180,40 +5094,33 @@ void StandardBotAI(bot_state_t *bs, float thinktime) bs->doAttack = 0; bs->doAltAttack = 0; - //reset the attack states + // reset the attack states - if (bs->isSquadLeader) - { + if (bs->isSquadLeader) { CommanderBotAI(bs); - } - else - { + } else { BotDoTeamplayAI(bs); } - if (!bs->currentEnemy) - { + if (!bs->currentEnemy) { bs->frame_Enemy_Vis = 0; } - if (bs->revengeEnemy && bs->revengeEnemy->client && - bs->revengeEnemy->client->pers.connected != CON_CONNECTED && bs->revengeEnemy->client->pers.connected != CON_CONNECTING) - { + if (bs->revengeEnemy && bs->revengeEnemy->client && bs->revengeEnemy->client->pers.connected != CON_CONNECTED && + bs->revengeEnemy->client->pers.connected != CON_CONNECTING) { bs->revengeEnemy = NULL; bs->revengeHateLevel = 0; } - if (bs->currentEnemy && bs->currentEnemy->client && - bs->currentEnemy->client->pers.connected != CON_CONNECTED && bs->currentEnemy->client->pers.connected != CON_CONNECTING) - { + if (bs->currentEnemy && bs->currentEnemy->client && bs->currentEnemy->client->pers.connected != CON_CONNECTED && + bs->currentEnemy->client->pers.connected != CON_CONNECTING) { bs->currentEnemy = NULL; } fjHalt = 0; #ifndef FORCEJUMP_INSTANTMETHOD - if (bs->forceJumpChargeTime > level.time) - { + if (bs->forceJumpChargeTime > level.time) { useTheForce = 1; forceHostile = 0; } @@ -6226,105 +5133,96 @@ void StandardBotAI(bot_state_t *bs, float thinktime) VectorSubtract(bs->currentEnemy->client->ps.origin, bs->eye, a_fo); vectoangles(a_fo, a_fo); - //do this above all things - if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PUSH)) && (bs->doForcePush > level.time || bs->cur_ps.fd.forceGripBeingGripped > level.time) && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PUSH]][FP_PUSH] /*&& InFieldOfVision(bs->viewangles, 50, a_fo)*/) - { + // do this above all things + if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PUSH)) && (bs->doForcePush > level.time || bs->cur_ps.fd.forceGripBeingGripped > level.time) && + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PUSH]][FP_PUSH] /*&& InFieldOfVision(bs->viewangles, 50, a_fo)*/) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_PUSH; useTheForce = 1; forceHostile = 1; - } - else if (bs->cur_ps.fd.forceSide == FORCE_DARKSIDE) - { //try dark side powers - //in order of priority top to bottom - if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_GRIP)) && (bs->cur_ps.fd.forcePowersActive & (1 << FP_GRIP)) && InFieldOfVision(bs->viewangles, 50, a_fo)) - { //already gripping someone, so hold it + } else if (bs->cur_ps.fd.forceSide == FORCE_DARKSIDE) { // try dark side powers + // in order of priority top to bottom + if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_GRIP)) && (bs->cur_ps.fd.forcePowersActive & (1 << FP_GRIP)) && + InFieldOfVision(bs->viewangles, 50, a_fo)) { // already gripping someone, so hold it level.clients[bs->client].ps.fd.forcePowerSelected = FP_GRIP; useTheForce = 1; forceHostile = 1; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_LIGHTNING)) && bs->frame_Enemy_Len < FORCE_LIGHTNING_RADIUS && level.clients[bs->client].ps.fd.forcePower > 50 && InFieldOfVision(bs->viewangles, 50, a_fo)) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_LIGHTNING)) && bs->frame_Enemy_Len < FORCE_LIGHTNING_RADIUS && + level.clients[bs->client].ps.fd.forcePower > 50 && InFieldOfVision(bs->viewangles, 50, a_fo)) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_LIGHTNING; useTheForce = 1; forceHostile = 1; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_GRIP)) && bs->frame_Enemy_Len < MAX_GRIP_DISTANCE && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_GRIP]][FP_GRIP] && InFieldOfVision(bs->viewangles, 50, a_fo)) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_GRIP)) && bs->frame_Enemy_Len < MAX_GRIP_DISTANCE && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_GRIP]][FP_GRIP] && + InFieldOfVision(bs->viewangles, 50, a_fo)) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_GRIP; useTheForce = 1; forceHostile = 1; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_RAGE)) && g_entities[bs->client].health < 25 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_RAGE]][FP_RAGE]) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_RAGE)) && g_entities[bs->client].health < 25 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_RAGE]][FP_RAGE]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_RAGE; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_DRAIN)) && bs->frame_Enemy_Len < MAX_DRAIN_DISTANCE && level.clients[bs->client].ps.fd.forcePower > 50 && InFieldOfVision(bs->viewangles, 50, a_fo) && bs->currentEnemy->client->ps.fd.forcePower > 10 && bs->currentEnemy->client->ps.fd.forceSide == FORCE_LIGHTSIDE) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_DRAIN)) && bs->frame_Enemy_Len < MAX_DRAIN_DISTANCE && + level.clients[bs->client].ps.fd.forcePower > 50 && InFieldOfVision(bs->viewangles, 50, a_fo) && + bs->currentEnemy->client->ps.fd.forcePower > 10 && bs->currentEnemy->client->ps.fd.forceSide == FORCE_LIGHTSIDE) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_DRAIN; useTheForce = 1; forceHostile = 1; } - } - else if (bs->cur_ps.fd.forceSide == FORCE_LIGHTSIDE) - { //try light side powers + } else if (bs->cur_ps.fd.forceSide == FORCE_LIGHTSIDE) { // try light side powers if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_ABSORB)) && bs->cur_ps.fd.forceGripCripple && - level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) - { //absorb to get out + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) { // absorb to get out level.clients[bs->client].ps.fd.forcePowerSelected = FP_ABSORB; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_ABSORB)) && bs->cur_ps.electrifyTime >= level.time && - level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) - { //absorb lightning + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_ABSORB)) && bs->cur_ps.electrifyTime >= level.time && + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) { // absorb lightning level.clients[bs->client].ps.fd.forcePowerSelected = FP_ABSORB; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_TELEPATHY)) && bs->frame_Enemy_Len < MAX_TRICK_DISTANCE && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TELEPATHY]][FP_TELEPATHY] && InFieldOfVision(bs->viewangles, 50, a_fo) && !(bs->currentEnemy->client->ps.fd.forcePowersActive & (1 << FP_SEE))) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_TELEPATHY)) && bs->frame_Enemy_Len < MAX_TRICK_DISTANCE && + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TELEPATHY]][FP_TELEPATHY] && + InFieldOfVision(bs->viewangles, 50, a_fo) && !(bs->currentEnemy->client->ps.fd.forcePowersActive & (1 << FP_SEE))) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_TELEPATHY; useTheForce = 1; forceHostile = 1; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_ABSORB)) && g_entities[bs->client].health < 75 && bs->currentEnemy->client->ps.fd.forceSide == FORCE_DARKSIDE && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_ABSORB)) && g_entities[bs->client].health < 75 && + bs->currentEnemy->client->ps.fd.forceSide == FORCE_DARKSIDE && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_ABSORB]][FP_ABSORB]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_ABSORB; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PROTECT)) && g_entities[bs->client].health < 35 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PROTECT]][FP_PROTECT]) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PROTECT)) && g_entities[bs->client].health < 35 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PROTECT]][FP_PROTECT]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_PROTECT; useTheForce = 1; forceHostile = 0; } } - if (!useTheForce) - { //try neutral powers - if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PUSH)) && bs->cur_ps.fd.forceGripBeingGripped > level.time && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PUSH]][FP_PUSH] && InFieldOfVision(bs->viewangles, 50, a_fo)) - { + if (!useTheForce) { // try neutral powers + if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PUSH)) && bs->cur_ps.fd.forceGripBeingGripped > level.time && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_PUSH]][FP_PUSH] && + InFieldOfVision(bs->viewangles, 50, a_fo)) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_PUSH; useTheForce = 1; forceHostile = 1; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_SPEED)) && g_entities[bs->client].health < 25 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_SPEED]][FP_SPEED]) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_SPEED)) && g_entities[bs->client].health < 25 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_SPEED]][FP_SPEED]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_SPEED; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_SEE)) && BotMindTricked(bs->client, bs->currentEnemy->s.number) && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_SEE]][FP_SEE]) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_SEE)) && BotMindTricked(bs->client, bs->currentEnemy->s.number) && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_SEE]][FP_SEE]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_SEE; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PULL)) && bs->frame_Enemy_Len < 256 && level.clients[bs->client].ps.fd.forcePower > 75 && InFieldOfVision(bs->viewangles, 50, a_fo)) - { + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_PULL)) && bs->frame_Enemy_Len < 256 && level.clients[bs->client].ps.fd.forcePower > 75 && + InFieldOfVision(bs->viewangles, 50, a_fo)) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_PULL; useTheForce = 1; forceHostile = 1; @@ -6332,27 +5230,25 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } - if (!useTheForce) - { //try powers that we don't care if we have an enemy for - if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_HEAL)) && g_entities[bs->client].health < 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_HEAL]][FP_HEAL] && bs->cur_ps.fd.forcePowerLevel[FP_HEAL] > FORCE_LEVEL_1) - { + if (!useTheForce) { // try powers that we don't care if we have an enemy for + if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_HEAL)) && g_entities[bs->client].health < 50 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_HEAL]][FP_HEAL] && + bs->cur_ps.fd.forcePowerLevel[FP_HEAL] > FORCE_LEVEL_1) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_HEAL; useTheForce = 1; forceHostile = 0; - } - else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_HEAL)) && g_entities[bs->client].health < 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_HEAL]][FP_HEAL] && !bs->currentEnemy && bs->isCamping > level.time) - { //only meditate and heal if we're camping + } else if ((bs->cur_ps.fd.forcePowersKnown & (1 << FP_HEAL)) && g_entities[bs->client].health < 50 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_HEAL]][FP_HEAL] && + !bs->currentEnemy && bs->isCamping > level.time) { // only meditate and heal if we're camping level.clients[bs->client].ps.fd.forcePowerSelected = FP_HEAL; useTheForce = 1; forceHostile = 0; } } - if (useTheForce && forceHostile) - { + if (useTheForce && forceHostile) { if (bs->currentEnemy && bs->currentEnemy->client && - !ForcePowerUsableOn(&g_entities[bs->client], bs->currentEnemy, level.clients[bs->client].ps.fd.forcePowerSelected)) - { + !ForcePowerUsableOn(&g_entities[bs->client], bs->currentEnemy, level.clients[bs->client].ps.fd.forcePowerSelected)) { useTheForce = 0; forceHostile = 0; } @@ -6362,54 +5258,40 @@ void StandardBotAI(bot_state_t *bs, float thinktime) bs->deathActivitiesDone = 0; - if (BotUseInventoryItem(bs)) - { - if (rand()%10 < 5) - { + if (BotUseInventoryItem(bs)) { + if (rand() % 10 < 5) { trap->EA_Use(bs->client); } } - if (bs->cur_ps.ammo[weaponData[bs->cur_ps.weapon].ammoIndex] < weaponData[bs->cur_ps.weapon].energyPerShot) - { - if (BotTryAnotherWeapon(bs)) - { + if (bs->cur_ps.ammo[weaponData[bs->cur_ps.weapon].ammoIndex] < weaponData[bs->cur_ps.weapon].energyPerShot) { + if (BotTryAnotherWeapon(bs)) { return; } - } - else - { - if (bs->currentEnemy && bs->lastVisibleEnemyIndex == bs->currentEnemy->s.number && - bs->frame_Enemy_Vis && bs->forceWeaponSelect /*&& bs->plantContinue < level.time*/) - { + } else { + if (bs->currentEnemy && bs->lastVisibleEnemyIndex == bs->currentEnemy->s.number && bs->frame_Enemy_Vis && + bs->forceWeaponSelect /*&& bs->plantContinue < level.time*/) { bs->forceWeaponSelect = 0; } - if (bs->plantContinue > level.time) - { + if (bs->plantContinue > level.time) { bs->doAttack = 1; bs->destinationGrabTime = 0; } - if (!bs->forceWeaponSelect && bs->cur_ps.hasDetPackPlanted && bs->plantKillEmAll > level.time) - { + if (!bs->forceWeaponSelect && bs->cur_ps.hasDetPackPlanted && bs->plantKillEmAll > level.time) { bs->forceWeaponSelect = WP_DET_PACK; } - if (bs->forceWeaponSelect) - { + if (bs->forceWeaponSelect) { selResult = BotSelectChoiceWeapon(bs, bs->forceWeaponSelect, 1); } - if (selResult) - { - if (selResult == 2) - { //newly selected + if (selResult) { + if (selResult == 2) { // newly selected return; } - } - else if (BotSelectIdealWeapon(bs)) - { + } else if (BotSelectIdealWeapon(bs)) { return; } } @@ -6418,68 +5300,50 @@ void StandardBotAI(bot_state_t *bs, float thinktime) return; }*/ - reaction = bs->skills.reflex/bs->settings.skill; + reaction = bs->skills.reflex / bs->settings.skill; - if (reaction < 0) - { + if (reaction < 0) { reaction = 0; } - if (reaction > 2000) - { + if (reaction > 2000) { reaction = 2000; } - if (!bs->currentEnemy) - { + if (!bs->currentEnemy) { bs->timeToReact = level.time + reaction; } - if (bs->cur_ps.weapon == WP_DET_PACK && bs->cur_ps.hasDetPackPlanted && bs->plantKillEmAll > level.time) - { + if (bs->cur_ps.weapon == WP_DET_PACK && bs->cur_ps.hasDetPackPlanted && bs->plantKillEmAll > level.time) { bs->doAltAttack = 1; } - if (bs->wpCamping) - { - if (bs->isCamping < level.time) - { + if (bs->wpCamping) { + if (bs->isCamping < level.time) { bs->wpCamping = NULL; bs->isCamping = 0; } - if (bs->currentEnemy && bs->frame_Enemy_Vis) - { + if (bs->currentEnemy && bs->frame_Enemy_Vis) { bs->wpCamping = NULL; bs->isCamping = 0; } } - if (bs->wpCurrent && - (bs->wpSeenTime < level.time || bs->wpTravelTime < level.time)) - { + if (bs->wpCurrent && (bs->wpSeenTime < level.time || bs->wpTravelTime < level.time)) { bs->wpCurrent = NULL; } - if (bs->currentEnemy) - { - if (bs->enemySeenTime < level.time || - !PassStandardEnemyChecks(bs, bs->currentEnemy)) - { - if (bs->revengeEnemy == bs->currentEnemy && - bs->currentEnemy->health < 1 && - bs->lastAttacked && bs->lastAttacked == bs->currentEnemy) - { - //CHAT: Destroyed hated one [KilledHatedOne section] + if (bs->currentEnemy) { + if (bs->enemySeenTime < level.time || !PassStandardEnemyChecks(bs, bs->currentEnemy)) { + if (bs->revengeEnemy == bs->currentEnemy && bs->currentEnemy->health < 1 && bs->lastAttacked && bs->lastAttacked == bs->currentEnemy) { + // CHAT: Destroyed hated one [KilledHatedOne section] bs->chatObject = bs->revengeEnemy; bs->chatAltObject = NULL; BotDoChat(bs, "KilledHatedOne", 1); bs->revengeEnemy = NULL; bs->revengeHateLevel = 0; - } - else if (bs->currentEnemy->health < 1 && PassLovedOneCheck(bs, bs->currentEnemy) && - bs->lastAttacked && bs->lastAttacked == bs->currentEnemy) - { - //CHAT: Killed + } else if (bs->currentEnemy->health < 1 && PassLovedOneCheck(bs, bs->currentEnemy) && bs->lastAttacked && bs->lastAttacked == bs->currentEnemy) { + // CHAT: Killed bs->chatObject = bs->currentEnemy; bs->chatAltObject = NULL; BotDoChat(bs, "Killed", 0); @@ -6489,32 +5353,19 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } - if (bot_honorableduelacceptance.integer) - { - if (bs->currentEnemy && bs->currentEnemy->client && - bs->cur_ps.weapon == WP_SABER && - g_privateDuel.integer && - bs->frame_Enemy_Vis && - bs->frame_Enemy_Len < 400 && - bs->currentEnemy->client->ps.weapon == WP_SABER && - bs->currentEnemy->client->ps.saberHolstered) - { + if (bot_honorableduelacceptance.integer) { + if (bs->currentEnemy && bs->currentEnemy->client && bs->cur_ps.weapon == WP_SABER && g_privateDuel.integer && bs->frame_Enemy_Vis && + bs->frame_Enemy_Len < 400 && bs->currentEnemy->client->ps.weapon == WP_SABER && bs->currentEnemy->client->ps.saberHolstered) { vec3_t e_ang_vec; VectorSubtract(bs->currentEnemy->client->ps.origin, bs->eye, e_ang_vec); - if (InFieldOfVision(bs->viewangles, 100, e_ang_vec)) - { //Our enemy has his saber holstered and has challenged us to a duel, so challenge him back - if (!bs->cur_ps.saberHolstered) - { + if (InFieldOfVision(bs->viewangles, 100, e_ang_vec)) { // Our enemy has his saber holstered and has challenged us to a duel, so challenge him back + if (!bs->cur_ps.saberHolstered) { Cmd_ToggleSaber_f(&g_entities[bs->client]); - } - else - { - if (bs->currentEnemy->client->ps.duelIndex == bs->client && - bs->currentEnemy->client->ps.duelTime > level.time && - !bs->cur_ps.duelInProgress) - { + } else { + if (bs->currentEnemy->client->ps.duelIndex == bs->client && bs->currentEnemy->client->ps.duelTime > level.time && + !bs->cur_ps.duelInProgress) { Cmd_EngageDuel_f(&g_entities[bs->client]); } } @@ -6526,53 +5377,45 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } } - //Apparently this "allows you to cheese" when fighting against bots. I'm not sure why you'd want to con bots - //into an easy kill, since they're bots and all. But whatever. + // Apparently this "allows you to cheese" when fighting against bots. I'm not sure why you'd want to con bots + // into an easy kill, since they're bots and all. But whatever. - if (!bs->wpCurrent) - { + if (!bs->wpCurrent) { wp = GetNearestVisibleWP(bs->origin, bs->client); - if (wp != -1) - { + if (wp != -1) { bs->wpCurrent = gWPArray[wp]; bs->wpSeenTime = level.time + 1500; - bs->wpTravelTime = level.time + 10000; //never take more than 10 seconds to travel to a waypoint + bs->wpTravelTime = level.time + 10000; // never take more than 10 seconds to travel to a waypoint } } if (bs->enemySeenTime < level.time || !bs->frame_Enemy_Vis || !bs->currentEnemy || - (bs->currentEnemy /*&& bs->cur_ps.weapon == WP_SABER && bs->frame_Enemy_Len > 300*/)) - { + (bs->currentEnemy /*&& bs->cur_ps.weapon == WP_SABER && bs->frame_Enemy_Len > 300*/)) { enemy = ScanForEnemies(bs); - if (enemy != -1) - { + if (enemy != -1) { bs->currentEnemy = &g_entities[enemy]; bs->enemySeenTime = level.time + ENEMY_FORGET_MS; } } - if (!bs->squadLeader && !bs->isSquadLeader) - { + if (!bs->squadLeader && !bs->isSquadLeader) { BotScanForLeader(bs); } - if (!bs->squadLeader && bs->squadCannotLead < level.time) - { //if still no leader after scanning, then become a squad leader + if (!bs->squadLeader && bs->squadCannotLead < level.time) { // if still no leader after scanning, then become a squad leader bs->isSquadLeader = 1; } - if (bs->isSquadLeader && bs->squadLeader) - { //we don't follow anyone if we are a leader + if (bs->isSquadLeader && bs->squadLeader) { // we don't follow anyone if we are a leader bs->squadLeader = NULL; } - //ESTABLISH VISIBILITIES AND DISTANCES FOR THE WHOLE FRAME HERE - if (bs->wpCurrent) - { - if (RMG.integer) - { //this is somewhat hacky, but in RMG we don't really care about vertical placement because points are scattered across only the terrain. + // ESTABLISH VISIBILITIES AND DISTANCES FOR THE WHOLE FRAME HERE + if (bs->wpCurrent) { + if (RMG.integer) { // this is somewhat hacky, but in RMG we don't really care about vertical placement because points are scattered across only the + // terrain. vec3_t vecB, vecC; vecB[0] = bs->origin[0]; @@ -6583,230 +5426,166 @@ void StandardBotAI(bot_state_t *bs, float thinktime) vecC[1] = bs->wpCurrent->origin[1]; vecC[2] = vecB[2]; - VectorSubtract(vecC, vecB, a); - } - else - { + } else { VectorSubtract(bs->wpCurrent->origin, bs->origin, a); } bs->frame_Waypoint_Len = VectorLength(a); visResult = WPOrgVisible(&g_entities[bs->client], bs->origin, bs->wpCurrent->origin, bs->client); - if (visResult == 2) - { + if (visResult == 2) { bs->frame_Waypoint_Vis = 0; bs->wpSeenTime = 0; bs->wpDestination = NULL; bs->wpDestIgnoreTime = level.time + 5000; - if (bs->wpDirection) - { + if (bs->wpDirection) { bs->wpDirection = 0; - } - else - { + } else { bs->wpDirection = 1; } - } - else if (visResult) - { + } else if (visResult) { bs->frame_Waypoint_Vis = 1; - } - else - { + } else { bs->frame_Waypoint_Vis = 0; } } - if (bs->currentEnemy) - { - if (bs->currentEnemy->client) - { + if (bs->currentEnemy) { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, eorg); eorg[2] += bs->currentEnemy->client->ps.viewheight; - } - else - { + } else { VectorCopy(bs->currentEnemy->s.origin, eorg); } VectorSubtract(eorg, bs->eye, a); bs->frame_Enemy_Len = VectorLength(a); - if (OrgVisible(bs->eye, eorg, bs->client)) - { + if (OrgVisible(bs->eye, eorg, bs->client)) { bs->frame_Enemy_Vis = 1; VectorCopy(eorg, bs->lastEnemySpotted); VectorCopy(bs->origin, bs->hereWhenSpotted); bs->lastVisibleEnemyIndex = bs->currentEnemy->s.number; - //VectorCopy(bs->eye, bs->lastEnemySpotted); + // VectorCopy(bs->eye, bs->lastEnemySpotted); bs->hitSpotted = 0; - } - else - { + } else { bs->frame_Enemy_Vis = 0; } - } - else - { + } else { bs->lastVisibleEnemyIndex = ENTITYNUM_NONE; } - //END + // END - if (bs->frame_Enemy_Vis) - { + if (bs->frame_Enemy_Vis) { bs->enemySeenTime = level.time + ENEMY_FORGET_MS; } - if (bs->wpCurrent) - { + if (bs->wpCurrent) { int wpTouchDist = BOT_WPTOUCH_DISTANCE; WPConstantRoutine(bs); - if (!bs->wpCurrent) - { //WPConstantRoutine has the ability to nullify the waypoint if it fails certain checks, so.. + if (!bs->wpCurrent) { // WPConstantRoutine has the ability to nullify the waypoint if it fails certain checks, so.. return; } - if (bs->wpCurrent->flags & WPFLAG_WAITFORFUNC) - { - if (!CheckForFunc(bs->wpCurrent->origin, -1)) - { - bs->beStill = level.time + 500; //no func brush under.. wait + if (bs->wpCurrent->flags & WPFLAG_WAITFORFUNC) { + if (!CheckForFunc(bs->wpCurrent->origin, -1)) { + bs->beStill = level.time + 500; // no func brush under.. wait } } - if (bs->wpCurrent->flags & WPFLAG_NOMOVEFUNC) - { - if (CheckForFunc(bs->wpCurrent->origin, -1)) - { - bs->beStill = level.time + 500; //func brush under.. wait + if (bs->wpCurrent->flags & WPFLAG_NOMOVEFUNC) { + if (CheckForFunc(bs->wpCurrent->origin, -1)) { + bs->beStill = level.time + 500; // func brush under.. wait } } - if (bs->frame_Waypoint_Vis || (bs->wpCurrent->flags & WPFLAG_NOVIS)) - { - if (RMG.integer) - { - bs->wpSeenTime = level.time + 5000; //if we lose sight of the point, we have 1.5 seconds to regain it before we drop it - } - else - { - bs->wpSeenTime = level.time + 1500; //if we lose sight of the point, we have 1.5 seconds to regain it before we drop it + if (bs->frame_Waypoint_Vis || (bs->wpCurrent->flags & WPFLAG_NOVIS)) { + if (RMG.integer) { + bs->wpSeenTime = level.time + 5000; // if we lose sight of the point, we have 1.5 seconds to regain it before we drop it + } else { + bs->wpSeenTime = level.time + 1500; // if we lose sight of the point, we have 1.5 seconds to regain it before we drop it } } VectorCopy(bs->wpCurrent->origin, bs->goalPosition); - if (bs->wpDirection) - { - goalWPIndex = bs->wpCurrent->index-1; - } - else - { - goalWPIndex = bs->wpCurrent->index+1; + if (bs->wpDirection) { + goalWPIndex = bs->wpCurrent->index - 1; + } else { + goalWPIndex = bs->wpCurrent->index + 1; } - if (bs->wpCamping) - { + if (bs->wpCamping) { VectorSubtract(bs->wpCampingTo->origin, bs->origin, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); VectorSubtract(bs->origin, bs->wpCamping->origin, a); - if (VectorLength(a) < 64) - { + if (VectorLength(a) < 64) { VectorCopy(bs->wpCamping->origin, bs->goalPosition); bs->beStill = level.time + 1000; - if (!bs->campStanding) - { + if (!bs->campStanding) { bs->duckTime = level.time + 1000; } } - } - else if (gWPArray[goalWPIndex] && gWPArray[goalWPIndex]->inuse && - !(gLevelFlags & LEVELFLAG_NOPOINTPREDICTION)) - { + } else if (gWPArray[goalWPIndex] && gWPArray[goalWPIndex]->inuse && !(gLevelFlags & LEVELFLAG_NOPOINTPREDICTION)) { VectorSubtract(gWPArray[goalWPIndex]->origin, bs->origin, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); - } - else - { + } else { VectorSubtract(bs->wpCurrent->origin, bs->origin, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); } - if (bs->destinationGrabTime < level.time /*&& (!bs->wpDestination || (bs->currentEnemy && bs->frame_Enemy_Vis))*/) - { + if (bs->destinationGrabTime < level.time /*&& (!bs->wpDestination || (bs->currentEnemy && bs->frame_Enemy_Vis))*/) { GetIdealDestination(bs); } - if (bs->wpCurrent && bs->wpDestination) - { - if (TotalTrailDistance(bs->wpCurrent->index, bs->wpDestination->index, bs) == -1) - { + if (bs->wpCurrent && bs->wpDestination) { + if (TotalTrailDistance(bs->wpCurrent->index, bs->wpDestination->index, bs) == -1) { bs->wpDestination = NULL; bs->destinationGrabTime = level.time + 10000; } } - if (RMG.integer) - { - if (bs->frame_Waypoint_Vis) - { - if (bs->wpCurrent && !bs->wpCurrent->flags) - { + if (RMG.integer) { + if (bs->frame_Waypoint_Vis) { + if (bs->wpCurrent && !bs->wpCurrent->flags) { wpTouchDist *= 3; } } } - if (bs->frame_Waypoint_Len < wpTouchDist || (RMG.integer && bs->frame_Waypoint_Len < wpTouchDist*2)) - { + if (bs->frame_Waypoint_Len < wpTouchDist || (RMG.integer && bs->frame_Waypoint_Len < wpTouchDist * 2)) { WPTouchRoutine(bs); - if (!bs->wpDirection) - { - desiredIndex = bs->wpCurrent->index+1; - } - else - { - desiredIndex = bs->wpCurrent->index-1; + if (!bs->wpDirection) { + desiredIndex = bs->wpCurrent->index + 1; + } else { + desiredIndex = bs->wpCurrent->index - 1; } - if (gWPArray[desiredIndex] && - gWPArray[desiredIndex]->inuse && - desiredIndex < gWPNum && - desiredIndex >= 0 && - PassWayCheck(bs, desiredIndex)) - { + if (gWPArray[desiredIndex] && gWPArray[desiredIndex]->inuse && desiredIndex < gWPNum && desiredIndex >= 0 && PassWayCheck(bs, desiredIndex)) { bs->wpCurrent = gWPArray[desiredIndex]; - } - else - { - if (bs->wpDestination) - { + } else { + if (bs->wpDestination) { bs->wpDestination = NULL; bs->destinationGrabTime = level.time + 10000; } - if (bs->wpDirection) - { + if (bs->wpDirection) { bs->wpDirection = 0; - } - else - { + } else { bs->wpDirection = 1; } } } - } - else //We can't find a waypoint, going to need a fallback routine. + } else // We can't find a waypoint, going to need a fallback routine. { /*if (level.gametype == GT_DUEL)*/ - { //helps them get out of messy situations + { // helps them get out of messy situations /*if ((level.time - bs->forceJumpChargeTime) > 3500) { bs->forceJumpChargeTime = level.time + 2000; @@ -6820,25 +5599,21 @@ void StandardBotAI(bot_state_t *bs, float thinktime) doingFallback = BotFallbackNavigation(bs); } - if (RMG.integer) - { //for RMG if the bot sticks around an area too long, jump around randomly some to spread to a new area (horrible hacky method) + if (RMG.integer) { // for RMG if the bot sticks around an area too long, jump around randomly some to spread to a new area (horrible hacky method) vec3_t vSubDif; VectorSubtract(bs->origin, bs->lastSignificantAreaChange, vSubDif); - if (VectorLength(vSubDif) > 1500) - { + if (VectorLength(vSubDif) > 1500) { VectorCopy(bs->origin, bs->lastSignificantAreaChange); bs->lastSignificantChangeTime = level.time + 20000; } - if (bs->lastSignificantChangeTime < level.time) - { + if (bs->lastSignificantChangeTime < level.time) { bs->iHaveNoIdeaWhereIAmGoing = level.time + 17000; } } - if (bs->iHaveNoIdeaWhereIAmGoing > level.time && !bs->currentEnemy) - { + if (bs->iHaveNoIdeaWhereIAmGoing > level.time && !bs->currentEnemy) { VectorCopy(preFrameGAngles, bs->goalAngles); bs->wpCurrent = NULL; bs->wpSwitchTime = level.time + 150; @@ -6849,45 +5624,29 @@ void StandardBotAI(bot_state_t *bs, float thinktime) bs->lastSignificantChangeTime = level.time + 25000; } - if (bs->wpCurrent && RMG.integer) - { + if (bs->wpCurrent && RMG.integer) { qboolean doJ = qfalse; - if (bs->wpCurrent->origin[2]-192 > bs->origin[2]) - { + if (bs->wpCurrent->origin[2] - 192 > bs->origin[2]) { doJ = qtrue; - } - else if ((bs->wpTravelTime - level.time) < 5000 && bs->wpCurrent->origin[2]-64 > bs->origin[2]) - { + } else if ((bs->wpTravelTime - level.time) < 5000 && bs->wpCurrent->origin[2] - 64 > bs->origin[2]) { doJ = qtrue; - } - else if ((bs->wpTravelTime - level.time) < 7000 && (bs->wpCurrent->flags & WPFLAG_RED_FLAG)) - { - if ((level.time - bs->jumpTime) > 200) - { + } else if ((bs->wpTravelTime - level.time) < 7000 && (bs->wpCurrent->flags & WPFLAG_RED_FLAG)) { + if ((level.time - bs->jumpTime) > 200) { bs->jumpTime = level.time + 100; bs->jumpHoldTime = level.time + 100; bs->jDelay = 0; } - } - else if ((bs->wpTravelTime - level.time) < 7000 && (bs->wpCurrent->flags & WPFLAG_BLUE_FLAG)) - { - if ((level.time - bs->jumpTime) > 200) - { + } else if ((bs->wpTravelTime - level.time) < 7000 && (bs->wpCurrent->flags & WPFLAG_BLUE_FLAG)) { + if ((level.time - bs->jumpTime) > 200) { bs->jumpTime = level.time + 100; bs->jumpHoldTime = level.time + 100; bs->jDelay = 0; } - } - else if (bs->wpCurrent->index > 0) - { - if ((bs->wpTravelTime - level.time) < 7000) - { - if ((gWPArray[bs->wpCurrent->index-1]->flags & WPFLAG_RED_FLAG) || - (gWPArray[bs->wpCurrent->index-1]->flags & WPFLAG_BLUE_FLAG)) - { - if ((level.time - bs->jumpTime) > 200) - { + } else if (bs->wpCurrent->index > 0) { + if ((bs->wpTravelTime - level.time) < 7000) { + if ((gWPArray[bs->wpCurrent->index - 1]->flags & WPFLAG_RED_FLAG) || (gWPArray[bs->wpCurrent->index - 1]->flags & WPFLAG_BLUE_FLAG)) { + if ((level.time - bs->jumpTime) > 200) { bs->jumpTime = level.time + 100; bs->jumpHoldTime = level.time + 100; bs->jDelay = 0; @@ -6896,90 +5655,64 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } - if (doJ) - { + if (doJ) { bs->jumpTime = level.time + 1500; bs->jumpHoldTime = level.time + 1500; bs->jDelay = 0; } } - if (doingFallback) - { + if (doingFallback) { bs->doingFallback = qtrue; - } - else - { + } else { bs->doingFallback = qfalse; } - if (bs->timeToReact < level.time && bs->currentEnemy && bs->enemySeenTime > level.time + (ENEMY_FORGET_MS - (ENEMY_FORGET_MS*0.2))) - { - if (bs->frame_Enemy_Vis) - { + if (bs->timeToReact < level.time && bs->currentEnemy && bs->enemySeenTime > level.time + (ENEMY_FORGET_MS - (ENEMY_FORGET_MS * 0.2))) { + if (bs->frame_Enemy_Vis) { CombatBotAI(bs, thinktime); - } - else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) - { //keep charging in case we see him again before we lose track of him + } else if (bs->cur_ps.weaponstate == WEAPON_CHARGING_ALT) { // keep charging in case we see him again before we lose track of him bs->doAltAttack = 1; - } - else if (bs->cur_ps.weaponstate == WEAPON_CHARGING) - { //keep charging in case we see him again before we lose track of him + } else if (bs->cur_ps.weaponstate == WEAPON_CHARGING) { // keep charging in case we see him again before we lose track of him bs->doAttack = 1; } - if (bs->destinationGrabTime > level.time + 100) - { - bs->destinationGrabTime = level.time + 100; //assures that we will continue staying within a general area of where we want to be in a combat situation + if (bs->destinationGrabTime > level.time + 100) { + bs->destinationGrabTime = + level.time + 100; // assures that we will continue staying within a general area of where we want to be in a combat situation } - if (bs->currentEnemy->client) - { + if (bs->currentEnemy->client) { VectorCopy(bs->currentEnemy->client->ps.origin, headlevel); headlevel[2] += bs->currentEnemy->client->ps.viewheight; - } - else - { + } else { VectorCopy(bs->currentEnemy->client->ps.origin, headlevel); } - if (!bs->frame_Enemy_Vis) - { - //if (!bs->hitSpotted && VectorLength(a) > 256) - if (OrgVisible(bs->eye, bs->lastEnemySpotted, -1)) - { + if (!bs->frame_Enemy_Vis) { + // if (!bs->hitSpotted && VectorLength(a) > 256) + if (OrgVisible(bs->eye, bs->lastEnemySpotted, -1)) { VectorCopy(bs->lastEnemySpotted, headlevel); VectorSubtract(headlevel, bs->eye, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); - if (bs->cur_ps.weapon == WP_FLECHETTE && - bs->cur_ps.weaponstate == WEAPON_READY && - bs->currentEnemy && bs->currentEnemy->client) - { + if (bs->cur_ps.weapon == WP_FLECHETTE && bs->cur_ps.weaponstate == WEAPON_READY && bs->currentEnemy && bs->currentEnemy->client) { mLen = VectorLength(a) > 128; - if (mLen > 128 && mLen < 1024) - { + if (mLen > 128 && mLen < 1024) { VectorSubtract(bs->currentEnemy->client->ps.origin, bs->lastEnemySpotted, a); - if (VectorLength(a) < 300) - { + if (VectorLength(a) < 300) { bs->doAltAttack = 1; } } } } - } - else - { + } else { bLeadAmount = BotWeaponCanLead(bs); - if ((bs->skills.accuracy/bs->settings.skill) <= 8 && - bLeadAmount) - { + if ((bs->skills.accuracy / bs->settings.skill) <= 8 && bLeadAmount) { BotAimLeading(bs, headlevel, bLeadAmount); - } - else - { + } else { VectorSubtract(headlevel, bs->eye, a); vectoangles(a, ang); VectorCopy(ang, bs->goalAngles); @@ -6989,109 +5722,76 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } } - if (bs->cur_ps.saberInFlight) - { + if (bs->cur_ps.saberInFlight) { bs->saberThrowTime = level.time + Q_irand(4000, 10000); } - if (bs->currentEnemy) - { - if (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) - { + if (bs->currentEnemy) { + if (BotGetWeaponRange(bs) == BWEAPONRANGE_SABER) { int saberRange = SABER_ATTACK_RANGE; VectorSubtract(bs->currentEnemy->client->ps.origin, bs->eye, a_fo); vectoangles(a_fo, a_fo); - if (bs->saberPowerTime < level.time) - { //Don't just use strong attacks constantly, switch around a bit - if (Q_irand(1, 10) <= 5) - { + if (bs->saberPowerTime < level.time) { // Don't just use strong attacks constantly, switch around a bit + if (Q_irand(1, 10) <= 5) { bs->saberPower = qtrue; - } - else - { + } else { bs->saberPower = qfalse; } bs->saberPowerTime = level.time + Q_irand(3000, 15000); } - if ( g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_STAFF - && g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_DUAL ) - { - if (bs->currentEnemy->health > 75 - && g_entities[bs->client].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > 2) - { - if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_STRONG - && bs->saberPower) - { //if we are up against someone with a lot of health and we have a strong attack available, then h4q them + if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_STAFF && g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_DUAL) { + if (bs->currentEnemy->health > 75 && g_entities[bs->client].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > 2) { + if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_STRONG && + bs->saberPower) { // if we are up against someone with a lot of health and we have a strong attack available, then h4q them Cmd_SaberAttackCycle_f(&g_entities[bs->client]); } - } - else if (bs->currentEnemy->health > 40 - && g_entities[bs->client].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > 1) - { - if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_MEDIUM) - { //they're down on health a little, use level 2 if we can + } else if (bs->currentEnemy->health > 40 && g_entities[bs->client].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > 1) { + if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_MEDIUM) { // they're down on health a little, use level 2 if we can Cmd_SaberAttackCycle_f(&g_entities[bs->client]); } - } - else - { - if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_FAST) - { //they've gone below 40 health, go at them with quick attacks + } else { + if (g_entities[bs->client].client->ps.fd.saberAnimLevel != SS_FAST) { // they've gone below 40 health, go at them with quick attacks Cmd_SaberAttackCycle_f(&g_entities[bs->client]); } } } - if (level.gametype == GT_SINGLE_PLAYER) - { + if (level.gametype == GT_SINGLE_PLAYER) { saberRange *= 3; } - if (bs->frame_Enemy_Len <= saberRange) - { + if (bs->frame_Enemy_Len <= saberRange) { SaberCombatHandling(bs); - if (bs->frame_Enemy_Len < 80) - { + if (bs->frame_Enemy_Len < 80) { meleestrafe = 1; } - } - else if (bs->saberThrowTime < level.time && !bs->cur_ps.saberInFlight && - (bs->cur_ps.fd.forcePowersKnown & (1 << FP_SABERTHROW)) && - InFieldOfVision(bs->viewangles, 30, a_fo) && - bs->frame_Enemy_Len < BOT_SABER_THROW_RANGE && - bs->cur_ps.fd.saberAnimLevel != SS_STAFF) - { + } else if (bs->saberThrowTime < level.time && !bs->cur_ps.saberInFlight && (bs->cur_ps.fd.forcePowersKnown & (1 << FP_SABERTHROW)) && + InFieldOfVision(bs->viewangles, 30, a_fo) && bs->frame_Enemy_Len < BOT_SABER_THROW_RANGE && bs->cur_ps.fd.saberAnimLevel != SS_STAFF) { bs->doAltAttack = 1; bs->doAttack = 0; - } - else if (bs->cur_ps.saberInFlight && bs->frame_Enemy_Len > 300 && bs->frame_Enemy_Len < BOT_SABER_THROW_RANGE) - { + } else if (bs->cur_ps.saberInFlight && bs->frame_Enemy_Len > 300 && bs->frame_Enemy_Len < BOT_SABER_THROW_RANGE) { bs->doAltAttack = 1; bs->doAttack = 0; } - } - else if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE) - { - if (bs->frame_Enemy_Len <= MELEE_ATTACK_RANGE) - { + } else if (BotGetWeaponRange(bs) == BWEAPONRANGE_MELEE) { + if (bs->frame_Enemy_Len <= MELEE_ATTACK_RANGE) { MeleeCombatHandling(bs); meleestrafe = 1; } } } - if (doingFallback && bs->currentEnemy) //just stand and fire if we have no idea where we are + if (doingFallback && bs->currentEnemy) // just stand and fire if we have no idea where we are { VectorCopy(bs->origin, bs->goalPosition); } - if (bs->forceJumping > level.time) - { + if (bs->forceJumping > level.time) { VectorCopy(bs->origin, noz_x); VectorCopy(bs->goalPosition, noz_y); @@ -7099,35 +5799,25 @@ void StandardBotAI(bot_state_t *bs, float thinktime) VectorSubtract(noz_x, noz_y, noz_x); - if (VectorLength(noz_x) < 32) - { + if (VectorLength(noz_x) < 32) { fjHalt = 1; } } - if (bs->doChat && bs->chatTime > level.time && (!bs->currentEnemy || !bs->frame_Enemy_Vis)) - { + if (bs->doChat && bs->chatTime > level.time && (!bs->currentEnemy || !bs->frame_Enemy_Vis)) { return; - } - else if (bs->doChat && bs->currentEnemy && bs->frame_Enemy_Vis) - { - //bs->chatTime = level.time + bs->chatTime_stored; - bs->doChat = 0; //do we want to keep the bot waiting to chat until after the enemy is gone? + } else if (bs->doChat && bs->currentEnemy && bs->frame_Enemy_Vis) { + // bs->chatTime = level.time + bs->chatTime_stored; + bs->doChat = 0; // do we want to keep the bot waiting to chat until after the enemy is gone? bs->chatTeam = 0; - } - else if (bs->doChat && bs->chatTime <= level.time) - { - if (bs->chatTeam) - { + } else if (bs->doChat && bs->chatTime <= level.time) { + if (bs->chatTeam) { trap->EA_SayTeam(bs->client, bs->currentChat); bs->chatTeam = 0; - } - else - { + } else { trap->EA_Say(bs->client, bs->currentChat); } - if (bs->doChat == 2) - { + if (bs->doChat == 2) { BotReplyGreetings(bs); } bs->doChat = 0; @@ -7137,154 +5827,113 @@ void StandardBotAI(bot_state_t *bs, float thinktime) if (/*bs->wpDestination &&*/ bs->shootGoal && /*bs->wpDestination->associated_entity == bs->shootGoal->s.number &&*/ - bs->shootGoal->health > 0 && bs->shootGoal->takedamage) - { - dif[0] = (bs->shootGoal->r.absmax[0]+bs->shootGoal->r.absmin[0])/2; - dif[1] = (bs->shootGoal->r.absmax[1]+bs->shootGoal->r.absmin[1])/2; - dif[2] = (bs->shootGoal->r.absmax[2]+bs->shootGoal->r.absmin[2])/2; + bs->shootGoal->health > 0 && bs->shootGoal->takedamage) { + dif[0] = (bs->shootGoal->r.absmax[0] + bs->shootGoal->r.absmin[0]) / 2; + dif[1] = (bs->shootGoal->r.absmax[1] + bs->shootGoal->r.absmin[1]) / 2; + dif[2] = (bs->shootGoal->r.absmax[2] + bs->shootGoal->r.absmin[2]) / 2; - if (!bs->currentEnemy || bs->frame_Enemy_Len > 256) - { //if someone is close then don't stop shooting them for this + if (!bs->currentEnemy || bs->frame_Enemy_Len > 256) { // if someone is close then don't stop shooting them for this VectorSubtract(dif, bs->eye, a); vectoangles(a, a); VectorCopy(a, bs->goalAngles); - if (InFieldOfVision(bs->viewangles, 30, a) && - EntityVisibleBox(bs->origin, NULL, NULL, dif, bs->client, bs->shootGoal->s.number)) - { + if (InFieldOfVision(bs->viewangles, 30, a) && EntityVisibleBox(bs->origin, NULL, NULL, dif, bs->client, bs->shootGoal->s.number)) { bs->doAttack = 1; } } } - if (bs->cur_ps.hasDetPackPlanted) - { //check if our enemy gets near it and detonate if he does + if (bs->cur_ps.hasDetPackPlanted) { // check if our enemy gets near it and detonate if he does BotCheckDetPacks(bs); - } - else if (bs->currentEnemy && bs->lastVisibleEnemyIndex == bs->currentEnemy->s.number && !bs->frame_Enemy_Vis && bs->plantTime < level.time && - !bs->doAttack && !bs->doAltAttack) - { + } else if (bs->currentEnemy && bs->lastVisibleEnemyIndex == bs->currentEnemy->s.number && !bs->frame_Enemy_Vis && bs->plantTime < level.time && + !bs->doAttack && !bs->doAltAttack) { VectorSubtract(bs->origin, bs->hereWhenSpotted, a); - if (bs->plantDecided > level.time || (bs->frame_Enemy_Len < BOT_PLANT_DISTANCE*2 && VectorLength(a) < BOT_PLANT_DISTANCE)) - { + if (bs->plantDecided > level.time || (bs->frame_Enemy_Len < BOT_PLANT_DISTANCE * 2 && VectorLength(a) < BOT_PLANT_DISTANCE)) { mineSelect = BotSelectChoiceWeapon(bs, WP_TRIP_MINE, 0); detSelect = BotSelectChoiceWeapon(bs, WP_DET_PACK, 0); - if (bs->cur_ps.hasDetPackPlanted) - { + if (bs->cur_ps.hasDetPackPlanted) { detSelect = 0; } - if (bs->plantDecided > level.time && bs->forceWeaponSelect && - bs->cur_ps.weapon == bs->forceWeaponSelect) - { + if (bs->plantDecided > level.time && bs->forceWeaponSelect && bs->cur_ps.weapon == bs->forceWeaponSelect) { bs->doAttack = 1; bs->plantDecided = 0; bs->plantTime = level.time + BOT_PLANT_INTERVAL; bs->plantContinue = level.time + 500; bs->beStill = level.time + 500; - } - else if (mineSelect || detSelect) - { - if (BotSurfaceNear(bs)) - { - if (!mineSelect) - { //if no mines use detpacks, otherwise use mines + } else if (mineSelect || detSelect) { + if (BotSurfaceNear(bs)) { + if (!mineSelect) { // if no mines use detpacks, otherwise use mines mineSelect = WP_DET_PACK; - } - else - { + } else { mineSelect = WP_TRIP_MINE; } detSelect = BotSelectChoiceWeapon(bs, mineSelect, 1); - if (detSelect && detSelect != 2) - { //We have it and it is now our weapon + if (detSelect && detSelect != 2) { // We have it and it is now our weapon bs->plantDecided = level.time + 1000; bs->forceWeaponSelect = mineSelect; return; - } - else if (detSelect == 2) - { + } else if (detSelect == 2) { bs->forceWeaponSelect = mineSelect; return; } } } } - } - else if (bs->plantContinue < level.time) - { + } else if (bs->plantContinue < level.time) { bs->forceWeaponSelect = 0; } - if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster && bs->jmState == -1 && gJMSaberEnt && gJMSaberEnt->inuse) - { + if (level.gametype == GT_JEDIMASTER && !bs->cur_ps.isJediMaster && bs->jmState == -1 && gJMSaberEnt && gJMSaberEnt->inuse) { vec3_t saberLen; float fSaberLen = 0; VectorSubtract(bs->origin, gJMSaberEnt->r.currentOrigin, saberLen); fSaberLen = VectorLength(saberLen); - if (fSaberLen < 256) - { - if (OrgVisible(bs->origin, gJMSaberEnt->r.currentOrigin, bs->client)) - { + if (fSaberLen < 256) { + if (OrgVisible(bs->origin, gJMSaberEnt->r.currentOrigin, bs->client)) { VectorCopy(gJMSaberEnt->r.currentOrigin, bs->goalPosition); } } } - if (bs->beStill < level.time && !WaitingForNow(bs, bs->goalPosition) && !fjHalt) - { + if (bs->beStill < level.time && !WaitingForNow(bs, bs->goalPosition) && !fjHalt) { VectorSubtract(bs->goalPosition, bs->origin, bs->goalMovedir); VectorNormalize(bs->goalMovedir); - if (bs->jumpTime > level.time && bs->jDelay < level.time && - level.clients[bs->client].pers.cmd.upmove > 0) - { - // trap->EA_Move(bs->client, bs->origin, 5000); + if (bs->jumpTime > level.time && bs->jDelay < level.time && level.clients[bs->client].pers.cmd.upmove > 0) { + // trap->EA_Move(bs->client, bs->origin, 5000); bs->beStill = level.time + 200; - } - else - { + } else { trap->EA_Move(bs->client, bs->goalMovedir, 5000); } - if (meleestrafe) - { + if (meleestrafe) { StrafeTracing(bs); } - if (bs->meleeStrafeDir && meleestrafe && bs->meleeStrafeDisable < level.time) - { + if (bs->meleeStrafeDir && meleestrafe && bs->meleeStrafeDisable < level.time) { trap->EA_MoveRight(bs->client); - } - else if (meleestrafe && bs->meleeStrafeDisable < level.time) - { + } else if (meleestrafe && bs->meleeStrafeDisable < level.time) { trap->EA_MoveLeft(bs->client); } - if (BotTrace_Jump(bs, bs->goalPosition)) - { + if (BotTrace_Jump(bs, bs->goalPosition)) { bs->jumpTime = level.time + 100; - } - else if (BotTrace_Duck(bs, bs->goalPosition)) - { + } else if (BotTrace_Duck(bs, bs->goalPosition)) { bs->duckTime = level.time + 100; } #ifdef BOT_STRAFE_AVOIDANCE - else - { + else { int strafeAround = BotTrace_Strafe(bs, bs->goalPosition); - if (strafeAround == STRAFEAROUND_RIGHT) - { + if (strafeAround == STRAFEAROUND_RIGHT) { trap->EA_MoveRight(bs->client); - } - else if (strafeAround == STRAFEAROUND_LEFT) - { + } else if (strafeAround == STRAFEAROUND_LEFT) { trap->EA_MoveLeft(bs->client); } } @@ -7292,147 +5941,115 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } #ifndef FORCEJUMP_INSTANTMETHOD - if (bs->forceJumpChargeTime > level.time) - { + if (bs->forceJumpChargeTime > level.time) { bs->jumpTime = 0; } #endif - if (bs->jumpPrep > level.time) - { + if (bs->jumpPrep > level.time) { bs->forceJumpChargeTime = 0; } - if (bs->forceJumpChargeTime > level.time) - { - bs->jumpHoldTime = ((bs->forceJumpChargeTime - level.time)/2) + level.time; + if (bs->forceJumpChargeTime > level.time) { + bs->jumpHoldTime = ((bs->forceJumpChargeTime - level.time) / 2) + level.time; bs->forceJumpChargeTime = 0; } - if (bs->jumpHoldTime > level.time) - { + if (bs->jumpHoldTime > level.time) { bs->jumpTime = bs->jumpHoldTime; } - if (bs->jumpTime > level.time && bs->jDelay < level.time) - { - if (bs->jumpHoldTime > level.time) - { + if (bs->jumpTime > level.time && bs->jDelay < level.time) { + if (bs->jumpHoldTime > level.time) { trap->EA_Jump(bs->client); - if (bs->wpCurrent) - { - if ((bs->wpCurrent->origin[2] - bs->origin[2]) < 64) - { + if (bs->wpCurrent) { + if ((bs->wpCurrent->origin[2] - bs->origin[2]) < 64) { trap->EA_MoveForward(bs->client); } - } - else - { + } else { trap->EA_MoveForward(bs->client); } - if (g_entities[bs->client].client->ps.groundEntityNum == ENTITYNUM_NONE) - { + if (g_entities[bs->client].client->ps.groundEntityNum == ENTITYNUM_NONE) { g_entities[bs->client].client->ps.pm_flags |= PMF_JUMP_HELD; } - } - else if (!(bs->cur_ps.pm_flags & PMF_JUMP_HELD)) - { + } else if (!(bs->cur_ps.pm_flags & PMF_JUMP_HELD)) { trap->EA_Jump(bs->client); } } - if (bs->duckTime > level.time) - { + if (bs->duckTime > level.time) { trap->EA_Crouch(bs->client); } - if ( bs->dangerousObject && bs->dangerousObject->inuse && bs->dangerousObject->health > 0 && - bs->dangerousObject->takedamage && (!bs->frame_Enemy_Vis || !bs->currentEnemy) && - (BotGetWeaponRange(bs) == BWEAPONRANGE_MID || BotGetWeaponRange(bs) == BWEAPONRANGE_LONG) && - bs->cur_ps.weapon != WP_DET_PACK && bs->cur_ps.weapon != WP_TRIP_MINE && - !bs->shootGoal ) - { + if (bs->dangerousObject && bs->dangerousObject->inuse && bs->dangerousObject->health > 0 && bs->dangerousObject->takedamage && + (!bs->frame_Enemy_Vis || !bs->currentEnemy) && (BotGetWeaponRange(bs) == BWEAPONRANGE_MID || BotGetWeaponRange(bs) == BWEAPONRANGE_LONG) && + bs->cur_ps.weapon != WP_DET_PACK && bs->cur_ps.weapon != WP_TRIP_MINE && !bs->shootGoal) { float danLen; VectorSubtract(bs->dangerousObject->r.currentOrigin, bs->eye, a); danLen = VectorLength(a); - if (danLen > 256) - { + if (danLen > 256) { vectoangles(a, a); VectorCopy(a, bs->goalAngles); - if (Q_irand(1, 10) < 5) - { + if (Q_irand(1, 10) < 5) { bs->goalAngles[YAW] += Q_irand(0, 3); bs->goalAngles[PITCH] += Q_irand(0, 3); - } - else - { + } else { bs->goalAngles[YAW] -= Q_irand(0, 3); bs->goalAngles[PITCH] -= Q_irand(0, 3); } if (InFieldOfVision(bs->viewangles, 30, a) && - EntityVisibleBox(bs->origin, NULL, NULL, bs->dangerousObject->r.currentOrigin, bs->client, bs->dangerousObject->s.number)) - { + EntityVisibleBox(bs->origin, NULL, NULL, bs->dangerousObject->r.currentOrigin, bs->client, bs->dangerousObject->s.number)) { bs->doAttack = 1; } } } - if (PrimFiring(bs) || - AltFiring(bs)) - { + if (PrimFiring(bs) || AltFiring(bs)) { friendInLOF = CheckForFriendInLOF(bs); - if (friendInLOF) - { - if (PrimFiring(bs)) - { + if (friendInLOF) { + if (PrimFiring(bs)) { KeepPrimFromFiring(bs); } - if (AltFiring(bs)) - { + if (AltFiring(bs)) { KeepAltFromFiring(bs); } - if (useTheForce && forceHostile) - { + if (useTheForce && forceHostile) { useTheForce = 0; } - if (!useTheForce && friendInLOF->client) - { //we have a friend here and are not currently using force powers, see if we can help them out - if (friendInLOF->health <= 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL]) - { + if (!useTheForce && friendInLOF->client) { // we have a friend here and are not currently using force powers, see if we can help them out + if (friendInLOF->health <= 50 && level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_TEAM_HEAL; useTheForce = 1; forceHostile = 0; - } - else if (friendInLOF->client->ps.fd.forcePower <= 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE]) - { + } else if (friendInLOF->client->ps.fd.forcePower <= 50 && + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_TEAM_FORCE; useTheForce = 1; forceHostile = 0; } } } - } - else if (level.gametype >= GT_TEAM) - { //still check for anyone to help.. + } else if (level.gametype >= GT_TEAM) { // still check for anyone to help.. friendInLOF = CheckForFriendInLOF(bs); - if (!useTheForce && friendInLOF) - { - if (friendInLOF->health <= 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL]) - { + if (!useTheForce && friendInLOF) { + if (friendInLOF->health <= 50 && + level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_TEAM_HEAL; useTheForce = 1; forceHostile = 0; - } - else if (friendInLOF->client->ps.fd.forcePower <= 50 && level.clients[bs->client].ps.fd.forcePower > forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE]) - { + } else if (friendInLOF->client->ps.fd.forcePower <= 50 && + level.clients[bs->client].ps.fd.forcePower > + forcePowerNeeded[level.clients[bs->client].ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE]) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_TEAM_FORCE; useTheForce = 1; forceHostile = 0; @@ -7441,71 +6058,51 @@ void StandardBotAI(bot_state_t *bs, float thinktime) } if (bs->doAttack && bs->cur_ps.weapon == WP_DET_PACK && - bs->cur_ps.hasDetPackPlanted) - { //maybe a bit hackish, but bots only want to plant one of these at any given time to avoid complications + bs->cur_ps.hasDetPackPlanted) { // maybe a bit hackish, but bots only want to plant one of these at any given time to avoid complications bs->doAttack = 0; } - if (bs->doAttack && bs->cur_ps.weapon == WP_SABER && - bs->saberDefending && bs->currentEnemy && bs->currentEnemy->client && - BotWeaponBlockable(bs->currentEnemy->client->ps.weapon) ) - { + if (bs->doAttack && bs->cur_ps.weapon == WP_SABER && bs->saberDefending && bs->currentEnemy && bs->currentEnemy->client && + BotWeaponBlockable(bs->currentEnemy->client->ps.weapon)) { bs->doAttack = 0; } - if (bs->cur_ps.saberLockTime > level.time) - { - if (rand()%10 < 5) - { + if (bs->cur_ps.saberLockTime > level.time) { + if (rand() % 10 < 5) { bs->doAttack = 1; - } - else - { + } else { bs->doAttack = 0; } } - if (bs->botChallengingTime > level.time) - { + if (bs->botChallengingTime > level.time) { bs->doAttack = 0; bs->doAltAttack = 0; } - if (bs->cur_ps.weapon == WP_SABER && - bs->cur_ps.saberInFlight && - !bs->cur_ps.saberEntityNum) - { //saber knocked away, keep trying to get it back + if (bs->cur_ps.weapon == WP_SABER && bs->cur_ps.saberInFlight && !bs->cur_ps.saberEntityNum) { // saber knocked away, keep trying to get it back bs->doAttack = 1; bs->doAltAttack = 0; } - if (bs->doAttack) - { + if (bs->doAttack) { trap->EA_Attack(bs->client); - } - else if (bs->doAltAttack) - { + } else if (bs->doAltAttack) { trap->EA_Alt_Attack(bs->client); } - if (useTheForce && forceHostile && bs->botChallengingTime > level.time) - { + if (useTheForce && forceHostile && bs->botChallengingTime > level.time) { useTheForce = qfalse; } - if (useTheForce) - { + if (useTheForce) { #ifndef FORCEJUMP_INSTANTMETHOD - if (bs->forceJumpChargeTime > level.time) - { + if (bs->forceJumpChargeTime > level.time) { level.clients[bs->client].ps.fd.forcePowerSelected = FP_LEVITATION; trap->EA_ForcePower(bs->client); - } - else - { + } else { #endif - if (bot_forcepowers.integer && !g_forcePowerDisable.integer) - { + if (bot_forcepowers.integer && !g_forcePowerDisable.integer) { trap->EA_ForcePower(bs->client); } #ifndef FORCEJUMP_INSTANTMETHOD @@ -7527,11 +6124,10 @@ int BotAIStartFrame(int time) { int i; int elapsed_time, thinktime; static int local_time; -// static int botlib_residual; + // static int botlib_residual; static int lastbotthink_time; - if (gUpdateVars < level.time) - { + if (gUpdateVars < level.time) { trap->Cvar_Update(&bot_pvstype); trap->Cvar_Update(&bot_camp); trap->Cvar_Update(&bot_attachments); @@ -7545,18 +6141,17 @@ int BotAIStartFrame(int time) { G_CheckBotSpawn(); - //rww - addl bot frame functions - if (gBotEdit) - { + // rww - addl bot frame functions + if (gBotEdit) { trap->Cvar_Update(&bot_wp_info); BotWaypointRender(); } UpdateEventTracker(); - //end rww + // end rww - //cap the bot think time - //if the bot think time changed we should reschedule the bots + // cap the bot think time + // if the bot think time changed we should reschedule the bots if (BOT_THINK_TIME != lastbotthink_time) { lastbotthink_time = BOT_THINK_TIME; BotScheduleBotThink(); @@ -7565,32 +6160,34 @@ int BotAIStartFrame(int time) { elapsed_time = time - local_time; local_time = time; - if (elapsed_time > BOT_THINK_TIME) thinktime = elapsed_time; - else thinktime = BOT_THINK_TIME; + if (elapsed_time > BOT_THINK_TIME) + thinktime = elapsed_time; + else + thinktime = BOT_THINK_TIME; // execute scheduled bot AI - for( i = 0; i < MAX_CLIENTS; i++ ) { - if( !botstates[i] || !botstates[i]->inuse ) { + for (i = 0; i < MAX_CLIENTS; i++) { + if (!botstates[i] || !botstates[i]->inuse) { continue; } // botstates[i]->botthink_residual += elapsed_time; // - if ( botstates[i]->botthink_residual >= thinktime ) { + if (botstates[i]->botthink_residual >= thinktime) { botstates[i]->botthink_residual -= thinktime; if (g_entities[i].client->pers.connected == CON_CONNECTED) { - BotAI(i, (float) thinktime / 1000); + BotAI(i, (float)thinktime / 1000); } } } // execute bot user commands every frame - for( i = 0; i < MAX_CLIENTS; i++ ) { - if( !botstates[i] || !botstates[i]->inuse ) { + for (i = 0; i < MAX_CLIENTS; i++) { + if (!botstates[i] || !botstates[i]->inuse) { continue; } - if( g_entities[i].client->pers.connected != CON_CONNECTED ) { + if (g_entities[i].client->pers.connected != CON_CONNECTED) { continue; } @@ -7606,8 +6203,8 @@ int BotAIStartFrame(int time) { BotAISetup ============== */ -int BotAISetup( int restart ) { - //rww - new bot cvars.. +int BotAISetup(int restart) { + // rww - new bot cvars.. trap->Cvar_Register(&bot_forcepowers, "bot_forcepowers", "1", CVAR_CHEAT); trap->Cvar_Register(&bot_forgimmick, "bot_forgimmick", "0", CVAR_CHEAT); trap->Cvar_Register(&bot_honorableduelacceptance, "bot_honorableduelacceptance", "0", CVAR_CHEAT); @@ -7631,19 +6228,18 @@ int BotAISetup( int restart ) { trap->Cvar_Register(&bot_wp_visconnect, "bot_wp_visconnect", "1", 0); trap->Cvar_Update(&bot_forcepowers); - //end rww + // end rww - //if the game is restarted for a tournament + // if the game is restarted for a tournament if (restart) { return qtrue; } - //initialize the bot states - memset( botstates, 0, sizeof(botstates) ); + // initialize the bot states + memset(botstates, 0, sizeof(botstates)); - if (!trap->BotLibSetup()) - { - return qfalse; //wts?! + if (!trap->BotLibSetup()) { + return qfalse; // wts?! } return qtrue; @@ -7654,21 +6250,20 @@ int BotAISetup( int restart ) { BotAIShutdown ============== */ -int BotAIShutdown( int restart ) { +int BotAIShutdown(int restart) { int i; - //if the game is restarted for a tournament - if ( restart ) { - //shutdown all the bots in the botlib + // if the game is restarted for a tournament + if (restart) { + // shutdown all the bots in the botlib for (i = 0; i < MAX_CLIENTS; i++) { if (botstates[i] && botstates[i]->inuse) { BotAIShutdownClient(botstates[i]->client, restart); } } - //don't shutdown the bot library - } - else { + // don't shutdown the bot library + } else { trap->BotLibShutdown(); } return qtrue; diff --git a/codemp/game/ai_util.c b/codemp/game/ai_util.c index 03dc9bb30a..0b2bf3df33 100644 --- a/codemp/game/ai_util.c +++ b/codemp/game/ai_util.c @@ -34,19 +34,11 @@ void *BAllocList[MAX_BALLOC]; char gBotChatBuffer[MAX_CLIENTS][MAX_CHAT_BUFFER_SIZE]; -void *B_TempAlloc(int size) -{ - return BG_TempAlloc(size); -} - -void B_TempFree(int size) -{ - BG_TempFree(size); -} +void *B_TempAlloc(int size) { return BG_TempAlloc(size); } +void B_TempFree(int size) { BG_TempFree(size); } -void *B_Alloc(int size) -{ +void *B_Alloc(int size) { #ifdef BOT_ZMALLOC void *ptr = NULL; int i = 0; @@ -55,14 +47,10 @@ void *B_Alloc(int size) int free = 0; int used = 0; - while (i < MAX_BALLOC) - { - if (!BAllocList[i]) - { + while (i < MAX_BALLOC) { + if (!BAllocList[i]) { free++; - } - else - { + } else { used++; } @@ -76,19 +64,16 @@ void *B_Alloc(int size) ptr = trap->BotGetMemoryGame(size); - while (i < MAX_BALLOC) - { - if (!BAllocList[i]) - { + while (i < MAX_BALLOC) { + if (!BAllocList[i]) { BAllocList[i] = ptr; break; } i++; } - if (i == MAX_BALLOC) - { - //If this happens we'll have to rely on this chunk being freed manually with B_Free, which it hopefully will be + if (i == MAX_BALLOC) { + // If this happens we'll have to rely on this chunk being freed manually with B_Free, which it hopefully will be #ifdef DEBUG trap->Print("WARNING: MAXIMUM B_ALLOC ALLOCATIONS EXCEEDED\n"); #endif @@ -102,8 +87,7 @@ void *B_Alloc(int size) #endif } -void B_Free(void *ptr) -{ +void B_Free(void *ptr) { #ifdef BOT_ZMALLOC int i = 0; @@ -111,14 +95,10 @@ void B_Free(void *ptr) int free = 0; int used = 0; - while (i < MAX_BALLOC) - { - if (!BAllocList[i]) - { + while (i < MAX_BALLOC) { + if (!BAllocList[i]) { free++; - } - else - { + } else { used++; } @@ -130,10 +110,8 @@ void B_Free(void *ptr) i = 0; #endif - while (i < MAX_BALLOC) - { - if (BAllocList[i] == ptr) - { + while (i < MAX_BALLOC) { + if (BAllocList[i] == ptr) { BAllocList[i] = NULL; break; } @@ -141,9 +119,8 @@ void B_Free(void *ptr) i++; } - if (i == MAX_BALLOC) - { - //Likely because the limit was exceeded and we're now freeing the chunk manually as we hoped would happen + if (i == MAX_BALLOC) { + // Likely because the limit was exceeded and we're now freeing the chunk manually as we hoped would happen #ifdef DEBUG trap->Print("WARNING: Freeing allocation which is not in the allocation structure\n"); #endif @@ -153,8 +130,7 @@ void B_Free(void *ptr) #endif } -void B_InitAlloc(void) -{ +void B_InitAlloc(void) { #ifdef BOT_ZMALLOC memset(BAllocList, 0, sizeof(BAllocList)); #endif @@ -162,15 +138,12 @@ void B_InitAlloc(void) memset(gWPArray, 0, sizeof(gWPArray)); } -void B_CleanupAlloc(void) -{ +void B_CleanupAlloc(void) { #ifdef BOT_ZMALLOC int i = 0; - while (i < MAX_BALLOC) - { - if (BAllocList[i]) - { + while (i < MAX_BALLOC) { + if (BAllocList[i]) { trap->BotFreeMemoryGame(BAllocList[i]); BAllocList[i] = NULL; } @@ -180,8 +153,7 @@ void B_CleanupAlloc(void) #endif } -int GetValueGroup(char *buf, char *group, char *outbuf) -{ +int GetValueGroup(char *buf, char *group, char *outbuf) { char *place, *placesecond; int failure; int i; @@ -192,8 +164,7 @@ int GetValueGroup(char *buf, char *group, char *outbuf) place = strstr(buf, group); - if (!place) - { + if (!place) { return 0; } @@ -202,46 +173,36 @@ int GetValueGroup(char *buf, char *group, char *outbuf) failure = 0; - while (buf[startpoint+1] != '{' || buf[startletter] != '\n') - { - placesecond = strstr(place+1, group); + while (buf[startpoint + 1] != '{' || buf[startletter] != '\n') { + placesecond = strstr(place + 1, group); - if (placesecond) - { + if (placesecond) { startpoint += (placesecond - place); startletter += (placesecond - place); place = placesecond; - } - else - { + } else { failure = 1; break; } } - if (failure) - { + if (failure) { return 0; } - //we have found the proper group name if we made it here, so find the opening brace and read into the outbuf - //until hitting the end brace + // we have found the proper group name if we made it here, so find the opening brace and read into the outbuf + // until hitting the end brace - while (buf[startpoint] != '{') - { + while (buf[startpoint] != '{') { startpoint++; } startpoint++; - while (buf[startpoint] != '}' || subg) - { - if (buf[startpoint] == '{') - { + while (buf[startpoint] != '}' || subg) { + if (buf[startpoint] == '{') { subg++; - } - else if (buf[startpoint] == '}') - { + } else if (buf[startpoint] == '}') { subg--; } outbuf[i] = buf[startpoint]; @@ -253,27 +214,21 @@ int GetValueGroup(char *buf, char *group, char *outbuf) return 1; } -int GetPairedValue(char *buf, char *key, char *outbuf) -{ +int GetPairedValue(char *buf, char *key, char *outbuf) { char *place, *placesecond; int startpoint, startletter; int i, found; - if (!buf || !key || !outbuf) - { + if (!buf || !key || !outbuf) { return 0; } i = 0; - while (buf[i] && buf[i] != '\0') - { - if (buf[i] == '/') - { - if (buf[i+1] && buf[i+1] != '\0' && buf[i+1] == '/') - { - while (buf[i] != '\n') - { + while (buf[i] && buf[i] != '\0') { + if (buf[i] == '/') { + if (buf[i + 1] && buf[i + 1] != '\0' && buf[i + 1] == '/') { + while (buf[i] != '\n') { buf[i] = '/'; i++; } @@ -284,57 +239,46 @@ int GetPairedValue(char *buf, char *key, char *outbuf) place = strstr(buf, key); - if (!place) - { + if (!place) { return 0; } - //tab == 9 + // tab == 9 startpoint = place - buf + strlen(key); startletter = (place - buf) - 1; found = 0; - while (!found) - { - if (startletter == 0 || !buf[startletter] || buf[startletter] == '\0' || buf[startletter] == 9 || buf[startletter] == ' ' || buf[startletter] == '\n') - { - if (buf[startpoint] == '\0' || buf[startpoint] == 9 || buf[startpoint] == ' ' || buf[startpoint] == '\n') - { + while (!found) { + if (startletter == 0 || !buf[startletter] || buf[startletter] == '\0' || buf[startletter] == 9 || buf[startletter] == ' ' || buf[startletter] == '\n') { + if (buf[startpoint] == '\0' || buf[startpoint] == 9 || buf[startpoint] == ' ' || buf[startpoint] == '\n') { found = 1; break; } } - placesecond = strstr(place+1, key); + placesecond = strstr(place + 1, key); - if (placesecond) - { + if (placesecond) { startpoint += placesecond - place; startletter += placesecond - place; place = placesecond; - } - else - { + } else { place = NULL; break; } - } - if (!found || !place || !buf[startpoint] || buf[startpoint] == '\0') - { + if (!found || !place || !buf[startpoint] || buf[startpoint] == '\0') { return 0; } - while (buf[startpoint] == ' ' || buf[startpoint] == 9 || buf[startpoint] == '\n') - { + while (buf[startpoint] == ' ' || buf[startpoint] == 9 || buf[startpoint] == '\n') { startpoint++; } i = 0; - while (buf[startpoint] && buf[startpoint] != '\0' && buf[startpoint] != '\n') - { + while (buf[startpoint] && buf[startpoint] != '\0' && buf[startpoint] != '\n') { outbuf[i] = buf[startpoint]; i++; startpoint++; @@ -345,8 +289,7 @@ int GetPairedValue(char *buf, char *key, char *outbuf) return 1; } -int BotDoChat(bot_state_t *bs, char *section, int always) -{ +int BotDoChat(bot_state_t *bs, char *section, int always) { char *chatgroup; int rVal; int inc_1; @@ -357,23 +300,19 @@ int BotDoChat(bot_state_t *bs, char *section, int always) int getthisline; gentity_t *cobject; - if (!bs->canChat) - { + if (!bs->canChat) { return 0; } - if (bs->doChat) - { //already have a chat scheduled + if (bs->doChat) { // already have a chat scheduled return 0; } - if (trap->Cvar_VariableIntegerValue("se_language")) - { //no chatting unless English. + if (trap->Cvar_VariableIntegerValue("se_language")) { // no chatting unless English. return 0; } - if (Q_irand(1, 10) > bs->chatFrequency && !always) - { + if (Q_irand(1, 10) > bs->chatFrequency && !always) { return 0; } @@ -383,19 +322,17 @@ int BotDoChat(bot_state_t *bs, char *section, int always) rVal = GetValueGroup(gBotChatBuffer[bs->client], section, chatgroup); - if (!rVal) //the bot has no group defined for the specified chat event + if (!rVal) // the bot has no group defined for the specified chat event { - B_TempFree(MAX_CHAT_BUFFER_SIZE); //chatgroup + B_TempFree(MAX_CHAT_BUFFER_SIZE); // chatgroup return 0; } inc_1 = 0; inc_2 = 2; - while (chatgroup[inc_2] && chatgroup[inc_2] != '\0') - { - if (chatgroup[inc_2] != 13 && chatgroup[inc_2] != 9) - { + while (chatgroup[inc_2] && chatgroup[inc_2] != '\0') { + if (chatgroup[inc_2] != 13 && chatgroup[inc_2] != 9) { chatgroup[inc_1] = chatgroup[inc_2]; inc_1++; } @@ -407,29 +344,24 @@ int BotDoChat(bot_state_t *bs, char *section, int always) lines = 0; - while (chatgroup[inc_1] && chatgroup[inc_1] != '\0') - { - if (chatgroup[inc_1] == '\n') - { + while (chatgroup[inc_1] && chatgroup[inc_1] != '\0') { + if (chatgroup[inc_1] == '\n') { lines++; } inc_1++; } - if (!lines) - { - B_TempFree(MAX_CHAT_BUFFER_SIZE); //chatgroup + if (!lines) { + B_TempFree(MAX_CHAT_BUFFER_SIZE); // chatgroup return 0; } - getthisline = Q_irand(0, (lines+1)); + getthisline = Q_irand(0, (lines + 1)); - if (getthisline < 1) - { + if (getthisline < 1) { getthisline = 1; } - if (getthisline > lines) - { + if (getthisline > lines) { getthisline = lines; } @@ -437,80 +369,63 @@ int BotDoChat(bot_state_t *bs, char *section, int always) inc_1 = 0; - while (checkedline != getthisline) - { - if (chatgroup[inc_1] && chatgroup[inc_1] != '\0') - { - if (chatgroup[inc_1] == '\n') - { + while (checkedline != getthisline) { + if (chatgroup[inc_1] && chatgroup[inc_1] != '\0') { + if (chatgroup[inc_1] == '\n') { inc_1++; checkedline++; } } - if (checkedline == getthisline) - { + if (checkedline == getthisline) { break; } inc_1++; } - //we're at the starting position of the desired line here + // we're at the starting position of the desired line here inc_2 = 0; - while (chatgroup[inc_1] != '\n') - { + while (chatgroup[inc_1] != '\n') { chatgroup[inc_2] = chatgroup[inc_1]; inc_2++; inc_1++; } chatgroup[inc_2] = '\0'; - //trap->EA_Say(bs->client, chatgroup); + // trap->EA_Say(bs->client, chatgroup); inc_1 = 0; inc_2 = 0; - if (strlen(chatgroup) > MAX_CHAT_LINE_SIZE) - { - B_TempFree(MAX_CHAT_BUFFER_SIZE); //chatgroup + if (strlen(chatgroup) > MAX_CHAT_LINE_SIZE) { + B_TempFree(MAX_CHAT_BUFFER_SIZE); // chatgroup return 0; } - while (chatgroup[inc_1]) - { - if (chatgroup[inc_1] == '%' && chatgroup[inc_1+1] != '%') - { + while (chatgroup[inc_1]) { + if (chatgroup[inc_1] == '%' && chatgroup[inc_1 + 1] != '%') { inc_1++; - if (chatgroup[inc_1] == 's' && bs->chatObject) - { + if (chatgroup[inc_1] == 's' && bs->chatObject) { cobject = bs->chatObject; - } - else if (chatgroup[inc_1] == 'a' && bs->chatAltObject) - { + } else if (chatgroup[inc_1] == 'a' && bs->chatAltObject) { cobject = bs->chatAltObject; - } - else - { + } else { cobject = NULL; } - if (cobject && cobject->client) - { + if (cobject && cobject->client) { inc_n = 0; - while (cobject->client->pers.netname[inc_n]) - { + while (cobject->client->pers.netname[inc_n]) { bs->currentChat[inc_2] = cobject->client->pers.netname[inc_n]; inc_2++; inc_n++; } - inc_2--; //to make up for the auto-increment below + inc_2--; // to make up for the auto-increment below } - } - else - { + } else { bs->currentChat[inc_2] = chatgroup[inc_1]; } inc_2++; @@ -518,55 +433,45 @@ int BotDoChat(bot_state_t *bs, char *section, int always) } bs->currentChat[inc_2] = '\0'; - if (strcmp(section, "GeneralGreetings") == 0) - { + if (strcmp(section, "GeneralGreetings") == 0) { bs->doChat = 2; - } - else - { + } else { bs->doChat = 1; } - bs->chatTime_stored = (strlen(bs->currentChat)*45)+Q_irand(1300, 1500); + bs->chatTime_stored = (strlen(bs->currentChat) * 45) + Q_irand(1300, 1500); bs->chatTime = level.time + bs->chatTime_stored; - B_TempFree(MAX_CHAT_BUFFER_SIZE); //chatgroup + B_TempFree(MAX_CHAT_BUFFER_SIZE); // chatgroup return 1; } -void ParseEmotionalAttachments(bot_state_t *bs, char *buf) -{ +void ParseEmotionalAttachments(bot_state_t *bs, char *buf) { int i = 0; int i_c = 0; char tbuf[16]; - while (buf[i] && buf[i] != '}') - { - while (buf[i] == ' ' || buf[i] == '{' || buf[i] == 9 || buf[i] == 13 || buf[i] == '\n') - { + while (buf[i] && buf[i] != '}') { + while (buf[i] == ' ' || buf[i] == '{' || buf[i] == 9 || buf[i] == 13 || buf[i] == '\n') { i++; } - if (buf[i] && buf[i] != '}') - { + if (buf[i] && buf[i] != '}') { i_c = 0; - while (buf[i] != '{' && buf[i] != 9 && buf[i] != 13 && buf[i] != '\n') - { + while (buf[i] != '{' && buf[i] != 9 && buf[i] != 13 && buf[i] != '\n') { bs->loved[bs->lovednum].name[i_c] = buf[i]; i_c++; i++; } bs->loved[bs->lovednum].name[i_c] = '\0'; - while (buf[i] == ' ' || buf[i] == '{' || buf[i] == 9 || buf[i] == 13 || buf[i] == '\n') - { + while (buf[i] == ' ' || buf[i] == '{' || buf[i] == 9 || buf[i] == 13 || buf[i] == '\n') { i++; } i_c = 0; - while (buf[i] != '{' && buf[i] != 9 && buf[i] != 13 && buf[i] != '\n') - { + while (buf[i] != '{' && buf[i] != 9 && buf[i] != 13 && buf[i] != '\n') { tbuf[i_c] = buf[i]; i_c++; i++; @@ -576,14 +481,11 @@ void ParseEmotionalAttachments(bot_state_t *bs, char *buf) bs->loved[bs->lovednum].level = atoi(tbuf); bs->lovednum++; - } - else - { + } else { break; } - if (bs->lovednum >= MAX_LOVED_ONES) - { + if (bs->lovednum >= MAX_LOVED_ONES) { return; } @@ -591,36 +493,31 @@ void ParseEmotionalAttachments(bot_state_t *bs, char *buf) } } -int ReadChatGroups(bot_state_t *bs, char *buf) -{ +int ReadChatGroups(bot_state_t *bs, char *buf) { char *cgroupbegin; int cgbplace; int i; cgroupbegin = strstr(buf, "BEGIN_CHAT_GROUPS"); - if (!cgroupbegin) - { + if (!cgroupbegin) { return 0; } - if (strlen(cgroupbegin) >= MAX_CHAT_BUFFER_SIZE) - { + if (strlen(cgroupbegin) >= MAX_CHAT_BUFFER_SIZE) { trap->Print(S_COLOR_RED "Error: Personality chat section exceeds max size\n"); return 0; } - cgbplace = cgroupbegin - buf+1; + cgbplace = cgroupbegin - buf + 1; - while (buf[cgbplace] != '\n') - { + while (buf[cgbplace] != '\n') { cgbplace++; } i = 0; - while (buf[cgbplace] && buf[cgbplace] != '\0') - { + while (buf[cgbplace] && buf[cgbplace] != '\0') { gBotChatBuffer[bs->client][i] = buf[cgbplace]; i++; cgbplace++; @@ -631,13 +528,12 @@ int ReadChatGroups(bot_state_t *bs, char *buf) return 1; } -void BotUtilizePersonality(bot_state_t *bs) -{ +void BotUtilizePersonality(bot_state_t *bs) { fileHandle_t f; int len, rlen; int failed; int i; - //char buf[131072]; + // char buf[131072]; char *buf = (char *)B_TempAlloc(131072); char *readbuf, *group; @@ -645,18 +541,16 @@ void BotUtilizePersonality(bot_state_t *bs) failed = 0; - if (!f) - { + if (!f) { trap->Print(S_COLOR_RED "Error: Specified personality not found\n"); - B_TempFree(131072); //buf + B_TempFree(131072); // buf return; } - if (len >= 131072) - { + if (len >= 131072) { trap->Print(S_COLOR_RED "Personality file exceeds maximum length\n"); - B_TempFree(131072); //buf - trap->FS_Close( f ); + B_TempFree(131072); // buf + trap->FS_Close(f); return; } @@ -664,8 +558,7 @@ void BotUtilizePersonality(bot_state_t *bs) rlen = len; - while (len < 131072) - { //kill all characters after the file length, since sometimes FS_Read doesn't do that entirely (or so it seems) + while (len < 131072) { // kill all characters after the file length, since sometimes FS_Read doesn't do that entirely (or so it seems) buf[len] = '\0'; len++; } @@ -675,214 +568,159 @@ void BotUtilizePersonality(bot_state_t *bs) readbuf = (char *)B_TempAlloc(1024); group = (char *)B_TempAlloc(65536); - if (!GetValueGroup(buf, "GeneralBotInfo", group)) - { + if (!GetValueGroup(buf, "GeneralBotInfo", group)) { trap->Print(S_COLOR_RED "Personality file contains no GeneralBotInfo group\n"); - failed = 1; //set failed so we know to set everything to default values + failed = 1; // set failed so we know to set everything to default values } - if (!failed && GetPairedValue(group, "reflex", readbuf)) - { + if (!failed && GetPairedValue(group, "reflex", readbuf)) { bs->skills.reflex = atoi(readbuf); - } - else - { - bs->skills.reflex = 100; //default + } else { + bs->skills.reflex = 100; // default } - if (!failed && GetPairedValue(group, "accuracy", readbuf)) - { + if (!failed && GetPairedValue(group, "accuracy", readbuf)) { bs->skills.accuracy = atof(readbuf); - } - else - { - bs->skills.accuracy = 10; //default + } else { + bs->skills.accuracy = 10; // default } - if (!failed && GetPairedValue(group, "turnspeed", readbuf)) - { + if (!failed && GetPairedValue(group, "turnspeed", readbuf)) { bs->skills.turnspeed = atof(readbuf); - } - else - { - bs->skills.turnspeed = 0.01f; //default + } else { + bs->skills.turnspeed = 0.01f; // default } - if (!failed && GetPairedValue(group, "turnspeed_combat", readbuf)) - { + if (!failed && GetPairedValue(group, "turnspeed_combat", readbuf)) { bs->skills.turnspeed_combat = atof(readbuf); - } - else - { - bs->skills.turnspeed_combat = 0.05f; //default + } else { + bs->skills.turnspeed_combat = 0.05f; // default } - if (!failed && GetPairedValue(group, "maxturn", readbuf)) - { + if (!failed && GetPairedValue(group, "maxturn", readbuf)) { bs->skills.maxturn = atof(readbuf); - } - else - { - bs->skills.maxturn = 360; //default + } else { + bs->skills.maxturn = 360; // default } - if (!failed && GetPairedValue(group, "perfectaim", readbuf)) - { + if (!failed && GetPairedValue(group, "perfectaim", readbuf)) { bs->skills.perfectaim = atoi(readbuf); - } - else - { - bs->skills.perfectaim = 0; //default + } else { + bs->skills.perfectaim = 0; // default } - if (!failed && GetPairedValue(group, "chatability", readbuf)) - { + if (!failed && GetPairedValue(group, "chatability", readbuf)) { bs->canChat = atoi(readbuf); - } - else - { - bs->canChat = 0; //default + } else { + bs->canChat = 0; // default } - if (!failed && GetPairedValue(group, "chatfrequency", readbuf)) - { + if (!failed && GetPairedValue(group, "chatfrequency", readbuf)) { bs->chatFrequency = atoi(readbuf); - } - else - { - bs->chatFrequency = 5; //default + } else { + bs->chatFrequency = 5; // default } - if (!failed && GetPairedValue(group, "hatelevel", readbuf)) - { + if (!failed && GetPairedValue(group, "hatelevel", readbuf)) { bs->loved_death_thresh = atoi(readbuf); - } - else - { - bs->loved_death_thresh = 3; //default + } else { + bs->loved_death_thresh = 3; // default } - if (!failed && GetPairedValue(group, "camper", readbuf)) - { + if (!failed && GetPairedValue(group, "camper", readbuf)) { bs->isCamper = atoi(readbuf); - } - else - { - bs->isCamper = 0; //default + } else { + bs->isCamper = 0; // default } - if (!failed && GetPairedValue(group, "saberspecialist", readbuf)) - { + if (!failed && GetPairedValue(group, "saberspecialist", readbuf)) { bs->saberSpecialist = atoi(readbuf); - } - else - { - bs->saberSpecialist = 0; //default + } else { + bs->saberSpecialist = 0; // default } - if (!failed && GetPairedValue(group, "forceinfo", readbuf)) - { + if (!failed && GetPairedValue(group, "forceinfo", readbuf)) { Com_sprintf(bs->forceinfo, sizeof(bs->forceinfo), "%s\0", readbuf); - } - else - { + } else { Com_sprintf(bs->forceinfo, sizeof(bs->forceinfo), "%s\0", DEFAULT_FORCEPOWERS); } i = 0; - while (i < MAX_CHAT_BUFFER_SIZE) - { //clear out the chat buffer for this bot + while (i < MAX_CHAT_BUFFER_SIZE) { // clear out the chat buffer for this bot gBotChatBuffer[bs->client][i] = '\0'; i++; } - if (bs->canChat) - { - if (!ReadChatGroups(bs, buf)) - { + if (bs->canChat) { + if (!ReadChatGroups(bs, buf)) { bs->canChat = 0; } } - if (GetValueGroup(buf, "BotWeaponWeights", group)) - { - if (GetPairedValue(group, "WP_STUN_BATON", readbuf)) - { + if (GetValueGroup(buf, "BotWeaponWeights", group)) { + if (GetPairedValue(group, "WP_STUN_BATON", readbuf)) { bs->botWeaponWeights[WP_STUN_BATON] = atoi(readbuf); bs->botWeaponWeights[WP_MELEE] = bs->botWeaponWeights[WP_STUN_BATON]; } - if (GetPairedValue(group, "WP_SABER", readbuf)) - { + if (GetPairedValue(group, "WP_SABER", readbuf)) { bs->botWeaponWeights[WP_SABER] = atoi(readbuf); } - if (GetPairedValue(group, "WP_BRYAR_PISTOL", readbuf)) - { + if (GetPairedValue(group, "WP_BRYAR_PISTOL", readbuf)) { bs->botWeaponWeights[WP_BRYAR_PISTOL] = atoi(readbuf); } - if (GetPairedValue(group, "WP_BLASTER", readbuf)) - { + if (GetPairedValue(group, "WP_BLASTER", readbuf)) { bs->botWeaponWeights[WP_BLASTER] = atoi(readbuf); } - if (GetPairedValue(group, "WP_DISRUPTOR", readbuf)) - { + if (GetPairedValue(group, "WP_DISRUPTOR", readbuf)) { bs->botWeaponWeights[WP_DISRUPTOR] = atoi(readbuf); } - if (GetPairedValue(group, "WP_BOWCASTER", readbuf)) - { + if (GetPairedValue(group, "WP_BOWCASTER", readbuf)) { bs->botWeaponWeights[WP_BOWCASTER] = atoi(readbuf); } - if (GetPairedValue(group, "WP_REPEATER", readbuf)) - { + if (GetPairedValue(group, "WP_REPEATER", readbuf)) { bs->botWeaponWeights[WP_REPEATER] = atoi(readbuf); } - if (GetPairedValue(group, "WP_DEMP2", readbuf)) - { + if (GetPairedValue(group, "WP_DEMP2", readbuf)) { bs->botWeaponWeights[WP_DEMP2] = atoi(readbuf); } - if (GetPairedValue(group, "WP_FLECHETTE", readbuf)) - { + if (GetPairedValue(group, "WP_FLECHETTE", readbuf)) { bs->botWeaponWeights[WP_FLECHETTE] = atoi(readbuf); } - if (GetPairedValue(group, "WP_ROCKET_LAUNCHER", readbuf)) - { + if (GetPairedValue(group, "WP_ROCKET_LAUNCHER", readbuf)) { bs->botWeaponWeights[WP_ROCKET_LAUNCHER] = atoi(readbuf); } - if (GetPairedValue(group, "WP_THERMAL", readbuf)) - { + if (GetPairedValue(group, "WP_THERMAL", readbuf)) { bs->botWeaponWeights[WP_THERMAL] = atoi(readbuf); } - if (GetPairedValue(group, "WP_TRIP_MINE", readbuf)) - { + if (GetPairedValue(group, "WP_TRIP_MINE", readbuf)) { bs->botWeaponWeights[WP_TRIP_MINE] = atoi(readbuf); } - if (GetPairedValue(group, "WP_DET_PACK", readbuf)) - { + if (GetPairedValue(group, "WP_DET_PACK", readbuf)) { bs->botWeaponWeights[WP_DET_PACK] = atoi(readbuf); } } bs->lovednum = 0; - if (GetValueGroup(buf, "EmotionalAttachments", group)) - { + if (GetValueGroup(buf, "EmotionalAttachments", group)) { ParseEmotionalAttachments(bs, group); } - B_TempFree(131072); //buf - B_TempFree(1024); //readbuf - B_TempFree(65536); //group + B_TempFree(131072); // buf + B_TempFree(1024); // readbuf + B_TempFree(65536); // group trap->FS_Close(f); } diff --git a/codemp/game/ai_wpnav.c b/codemp/game/ai_wpnav.c index 562fe75ffd..72f545085b 100644 --- a/codemp/game/ai_wpnav.c +++ b/codemp/game/ai_wpnav.c @@ -37,88 +37,74 @@ int gWPNum = 0; int gLastPrintedIndex = -1; nodeobject_t nodetable[MAX_NODETABLE_SIZE]; -int nodenum; //so we can connect broken trails +int nodenum; // so we can connect broken trails int gLevelFlags = 0; -char *GetFlagStr( int flags ) -{ +char *GetFlagStr(int flags) { char *flagstr; int i; flagstr = (char *)B_TempAlloc(128); i = 0; - if (!flags) - { + if (!flags) { strcpy(flagstr, "none\0"); goto fend; } - if (flags & WPFLAG_JUMP) - { + if (flags & WPFLAG_JUMP) { flagstr[i] = 'j'; i++; } - if (flags & WPFLAG_DUCK) - { + if (flags & WPFLAG_DUCK) { flagstr[i] = 'd'; i++; } - if (flags & WPFLAG_SNIPEORCAMPSTAND) - { + if (flags & WPFLAG_SNIPEORCAMPSTAND) { flagstr[i] = 'c'; i++; } - if (flags & WPFLAG_WAITFORFUNC) - { + if (flags & WPFLAG_WAITFORFUNC) { flagstr[i] = 'f'; i++; } - if (flags & WPFLAG_SNIPEORCAMP) - { + if (flags & WPFLAG_SNIPEORCAMP) { flagstr[i] = 's'; i++; } - if (flags & WPFLAG_ONEWAY_FWD) - { + if (flags & WPFLAG_ONEWAY_FWD) { flagstr[i] = 'x'; i++; } - if (flags & WPFLAG_ONEWAY_BACK) - { + if (flags & WPFLAG_ONEWAY_BACK) { flagstr[i] = 'y'; i++; } - if (flags & WPFLAG_GOALPOINT) - { + if (flags & WPFLAG_GOALPOINT) { flagstr[i] = 'g'; i++; } - if (flags & WPFLAG_NOVIS) - { + if (flags & WPFLAG_NOVIS) { flagstr[i] = 'n'; i++; } - if (flags & WPFLAG_NOMOVEFUNC) - { + if (flags & WPFLAG_NOMOVEFUNC) { flagstr[i] = 'm'; i++; } - if (flags & WPFLAG_RED_FLAG) - { - if (i) - { + if (flags & WPFLAG_RED_FLAG) { + if (i) { flagstr[i] = ' '; i++; } @@ -140,10 +126,8 @@ char *GetFlagStr( int flags ) i++; } - if (flags & WPFLAG_BLUE_FLAG) - { - if (i) - { + if (flags & WPFLAG_BLUE_FLAG) { + if (i) { flagstr[i] = ' '; i++; } @@ -167,10 +151,8 @@ char *GetFlagStr( int flags ) i++; } - if (flags & WPFLAG_SIEGE_IMPERIALOBJ) - { - if (i) - { + if (flags & WPFLAG_SIEGE_IMPERIALOBJ) { + if (i) { flagstr[i] = ' '; i++; } @@ -192,10 +174,8 @@ char *GetFlagStr( int flags ) i++; } - if (flags & WPFLAG_SIEGE_REBELOBJ) - { - if (i) - { + if (flags & WPFLAG_SIEGE_REBELOBJ) { + if (i) { flagstr[i] = ' '; i++; } @@ -219,8 +199,7 @@ char *GetFlagStr( int flags ) flagstr[i] = '\0'; - if (i == 0) - { + if (i == 0) { strcpy(flagstr, "unknown\0"); } @@ -228,11 +207,10 @@ char *GetFlagStr( int flags ) return flagstr; } -void G_TestLine(vec3_t start, vec3_t end, int color, int time) -{ +void G_TestLine(vec3_t start, vec3_t end, int color, int time) { gentity_t *te; - te = G_TempEntity( start, EV_TESTLINE ); + te = G_TempEntity(start, EV_TESTLINE); VectorCopy(start, te->s.origin); VectorCopy(end, te->s.origin2); te->s.time2 = time; @@ -240,8 +218,7 @@ void G_TestLine(vec3_t start, vec3_t end, int color, int time) te->r.svFlags |= SVF_BROADCAST; } -void BotWaypointRender(void) -{ +void BotWaypointRender(void) { int i, n; int inc_checker; int bestindex; @@ -253,15 +230,13 @@ void BotWaypointRender(void) char *flagstr; vec3_t a; - if (!gBotEdit) - { + if (!gBotEdit) { return; } bestindex = 0; - if (gWPRenderTime > level.time) - { + if (gWPRenderTime > level.time) { goto checkprint; } @@ -270,75 +245,62 @@ void BotWaypointRender(void) i = gWPRenderedFrame; inc_checker = gWPRenderedFrame; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { - plum = G_TempEntity( gWPArray[i]->origin, EV_SCOREPLUM ); + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { + plum = G_TempEntity(gWPArray[i]->origin, EV_SCOREPLUM); plum->r.svFlags |= SVF_BROADCAST; plum->s.time = i; n = 0; - while (n < gWPArray[i]->neighbornum) - { - if (gWPArray[i]->neighbors[n].forceJumpTo && gWPArray[gWPArray[i]->neighbors[n].num]) - { + while (n < gWPArray[i]->neighbornum) { + if (gWPArray[i]->neighbors[n].forceJumpTo && gWPArray[gWPArray[i]->neighbors[n].num]) { G_TestLine(gWPArray[i]->origin, gWPArray[gWPArray[i]->neighbors[n].num]->origin, 0x0000ff, 5000); } n++; } gWPRenderedFrame++; - } - else - { + } else { gWPRenderedFrame = 0; break; } - if ((i - inc_checker) > 4) - { - break; //don't render too many at once + if ((i - inc_checker) > 4) { + break; // don't render too many at once } i++; } - if (i >= gWPNum) - { - gWPRenderTime = level.time + 1500; //wait a bit after we finish doing the whole trail + if (i >= gWPNum) { + gWPRenderTime = level.time + 1500; // wait a bit after we finish doing the whole trail gWPRenderedFrame = 0; } checkprint: - if (!bot_wp_info.value) - { + if (!bot_wp_info.value) { return; } - viewent = &g_entities[0]; //only show info to the first client + viewent = &g_entities[0]; // only show info to the first client - if (!viewent || !viewent->client) - { //client isn't in the game yet? + if (!viewent || !viewent->client) { // client isn't in the game yet? return; } - bestdist = 256; //max distance for showing point info + bestdist = 256; // max distance for showing point info gotbestindex = 0; i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { VectorSubtract(viewent->client->ps.origin, gWPArray[i]->origin, a); checkdist = VectorLength(a); - if (checkdist < bestdist) - { + if (checkdist < bestdist) { bestdist = checkdist; bestindex = i; gotbestindex = 1; @@ -347,33 +309,29 @@ void BotWaypointRender(void) i++; } - if (gotbestindex && bestindex != gLastPrintedIndex) - { + if (gotbestindex && bestindex != gLastPrintedIndex) { flagstr = GetFlagStr(gWPArray[bestindex]->flags); gLastPrintedIndex = bestindex; - trap->Print(S_COLOR_YELLOW "Waypoint %i\nFlags - %i (%s) (w%f)\nOrigin - (%i %i %i)\n", (int)(gWPArray[bestindex]->index), (int)(gWPArray[bestindex]->flags), flagstr, gWPArray[bestindex]->weight, (int)(gWPArray[bestindex]->origin[0]), (int)(gWPArray[bestindex]->origin[1]), (int)(gWPArray[bestindex]->origin[2])); - //GetFlagStr allocates 128 bytes for this, if it's changed then obviously this must be as well - B_TempFree(128); //flagstr + trap->Print(S_COLOR_YELLOW "Waypoint %i\nFlags - %i (%s) (w%f)\nOrigin - (%i %i %i)\n", (int)(gWPArray[bestindex]->index), + (int)(gWPArray[bestindex]->flags), flagstr, gWPArray[bestindex]->weight, (int)(gWPArray[bestindex]->origin[0]), + (int)(gWPArray[bestindex]->origin[1]), (int)(gWPArray[bestindex]->origin[2])); + // GetFlagStr allocates 128 bytes for this, if it's changed then obviously this must be as well + B_TempFree(128); // flagstr - plum = G_TempEntity( gWPArray[bestindex]->origin, EV_SCOREPLUM ); + plum = G_TempEntity(gWPArray[bestindex]->origin, EV_SCOREPLUM); plum->r.svFlags |= SVF_BROADCAST; - plum->s.time = bestindex; //render it once - } - else if (!gotbestindex) - { + plum->s.time = bestindex; // render it once + } else if (!gotbestindex) { gLastPrintedIndex = -1; } } -void TransferWPData(int from, int to) -{ - if (!gWPArray[to]) - { +void TransferWPData(int from, int to) { + if (!gWPArray[to]) { gWPArray[to] = (wpobject_t *)B_Alloc(sizeof(wpobject_t)); } - if (!gWPArray[to]) - { + if (!gWPArray[to]) { trap->Print(S_COLOR_RED "FATAL ERROR: Could not allocated memory for waypoint\n"); } @@ -387,54 +345,45 @@ void TransferWPData(int from, int to) VectorCopy(gWPArray[from]->origin, gWPArray[to]->origin); } -void CreateNewWP(vec3_t origin, int flags) -{ - if (gWPNum >= MAX_WPARRAY_SIZE) - { - if (!RMG.integer) - { +void CreateNewWP(vec3_t origin, int flags) { + if (gWPNum >= MAX_WPARRAY_SIZE) { + if (!RMG.integer) { trap->Print(S_COLOR_YELLOW "Warning: Waypoint limit hit (%i)\n", MAX_WPARRAY_SIZE); } return; } - if (!gWPArray[gWPNum]) - { + if (!gWPArray[gWPNum]) { gWPArray[gWPNum] = (wpobject_t *)B_Alloc(sizeof(wpobject_t)); } - if (!gWPArray[gWPNum]) - { + if (!gWPArray[gWPNum]) { trap->Print(S_COLOR_RED "ERROR: Could not allocated memory for waypoint\n"); } gWPArray[gWPNum]->flags = flags; - gWPArray[gWPNum]->weight = 0; //calculated elsewhere - gWPArray[gWPNum]->associated_entity = ENTITYNUM_NONE; //set elsewhere + gWPArray[gWPNum]->weight = 0; // calculated elsewhere + gWPArray[gWPNum]->associated_entity = ENTITYNUM_NONE; // set elsewhere gWPArray[gWPNum]->forceJumpTo = 0; - gWPArray[gWPNum]->disttonext = 0; //calculated elsewhere + gWPArray[gWPNum]->disttonext = 0; // calculated elsewhere gWPArray[gWPNum]->index = gWPNum; gWPArray[gWPNum]->inuse = 1; VectorCopy(origin, gWPArray[gWPNum]->origin); gWPNum++; } -void CreateNewWP_FromObject(wpobject_t *wp) -{ +void CreateNewWP_FromObject(wpobject_t *wp) { int i; - if (gWPNum >= MAX_WPARRAY_SIZE) - { + if (gWPNum >= MAX_WPARRAY_SIZE) { return; } - if (!gWPArray[gWPNum]) - { + if (!gWPArray[gWPNum]) { gWPArray[gWPNum] = (wpobject_t *)B_Alloc(sizeof(wpobject_t)); } - if (!gWPArray[gWPNum]) - { + if (!gWPArray[gWPNum]) { trap->Print(S_COLOR_RED "ERROR: Could not allocated memory for waypoint\n"); } @@ -450,21 +399,17 @@ void CreateNewWP_FromObject(wpobject_t *wp) i = wp->neighbornum; - while (i >= 0) - { + while (i >= 0) { gWPArray[gWPNum]->neighbors[i].num = wp->neighbors[i].num; gWPArray[gWPNum]->neighbors[i].forceJumpTo = wp->neighbors[i].forceJumpTo; i--; } - if (gWPArray[gWPNum]->flags & WPFLAG_RED_FLAG) - { + if (gWPArray[gWPNum]->flags & WPFLAG_RED_FLAG) { flagRed = gWPArray[gWPNum]; oFlagRed = flagRed; - } - else if (gWPArray[gWPNum]->flags & WPFLAG_BLUE_FLAG) - { + } else if (gWPArray[gWPNum]->flags & WPFLAG_BLUE_FLAG) { flagBlue = gWPArray[gWPNum]; oFlagBlue = flagBlue; } @@ -472,43 +417,36 @@ void CreateNewWP_FromObject(wpobject_t *wp) gWPNum++; } -void RemoveWP(void) -{ - if (gWPNum <= 0) - { +void RemoveWP(void) { + if (gWPNum <= 0) { return; } gWPNum--; - if (!gWPArray[gWPNum] || !gWPArray[gWPNum]->inuse) - { + if (!gWPArray[gWPNum] || !gWPArray[gWPNum]->inuse) { return; } - //B_Free((wpobject_t *)gWPArray[gWPNum]); - if (gWPArray[gWPNum]) - { - memset( gWPArray[gWPNum], 0, sizeof(*gWPArray[gWPNum]) ); + // B_Free((wpobject_t *)gWPArray[gWPNum]); + if (gWPArray[gWPNum]) { + memset(gWPArray[gWPNum], 0, sizeof(*gWPArray[gWPNum])); } - //gWPArray[gWPNum] = NULL; + // gWPArray[gWPNum] = NULL; - if (gWPArray[gWPNum]) - { + if (gWPArray[gWPNum]) { gWPArray[gWPNum]->inuse = 0; } } -void RemoveAllWP(void) -{ - while(gWPNum) { +void RemoveAllWP(void) { + while (gWPNum) { RemoveWP(); } } -void RemoveWP_InTrail(int afterindex) -{ +void RemoveWP_InTrail(int afterindex) { int foundindex; int foundanindex; int didchange; @@ -519,16 +457,13 @@ void RemoveWP_InTrail(int afterindex) didchange = 0; i = 0; - if (afterindex < 0 || afterindex >= gWPNum) - { + if (afterindex < 0 || afterindex >= gWPNum) { trap->Print(S_COLOR_YELLOW "Waypoint number %i does not exist\n", afterindex); return; } - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) { foundindex = i; foundanindex = 1; break; @@ -537,36 +472,31 @@ void RemoveWP_InTrail(int afterindex) i++; } - if (!foundanindex) - { + if (!foundanindex) { trap->Print(S_COLOR_YELLOW "Waypoint index %i should exist, but does not (?)\n", afterindex); return; } i = 0; - while (i <= gWPNum) - { - if (gWPArray[i] && gWPArray[i]->index == foundindex) - { - //B_Free(gWPArray[i]); + while (i <= gWPNum) { + if (gWPArray[i] && gWPArray[i]->index == foundindex) { + // B_Free(gWPArray[i]); - //Keep reusing the memory - memset( gWPArray[i], 0, sizeof(*gWPArray[i]) ); + // Keep reusing the memory + memset(gWPArray[i], 0, sizeof(*gWPArray[i])); - //gWPArray[i] = NULL; + // gWPArray[i] = NULL; gWPArray[i]->inuse = 0; didchange = 1; - } - else if (gWPArray[i] && didchange) - { - TransferWPData(i, i-1); - //B_Free(gWPArray[i]); + } else if (gWPArray[i] && didchange) { + TransferWPData(i, i - 1); + // B_Free(gWPArray[i]); - //Keep reusing the memory - memset( gWPArray[i], 0, sizeof(*gWPArray[i]) ); + // Keep reusing the memory + memset(gWPArray[i], 0, sizeof(*gWPArray[i])); - //gWPArray[i] = NULL; + // gWPArray[i] = NULL; gWPArray[i]->inuse = 0; } @@ -575,8 +505,7 @@ void RemoveWP_InTrail(int afterindex) gWPNum--; } -int CreateNewWP_InTrail(vec3_t origin, int flags, int afterindex) -{ +int CreateNewWP_InTrail(vec3_t origin, int flags, int afterindex) { int foundindex; int foundanindex; int i; @@ -585,25 +514,20 @@ int CreateNewWP_InTrail(vec3_t origin, int flags, int afterindex) foundanindex = 0; i = 0; - if (gWPNum >= MAX_WPARRAY_SIZE) - { - if (!RMG.integer) - { + if (gWPNum >= MAX_WPARRAY_SIZE) { + if (!RMG.integer) { trap->Print(S_COLOR_YELLOW "Warning: Waypoint limit hit (%i)\n", MAX_WPARRAY_SIZE); } return 0; } - if (afterindex < 0 || afterindex >= gWPNum) - { + if (afterindex < 0 || afterindex >= gWPNum) { trap->Print(S_COLOR_YELLOW "Waypoint number %i does not exist\n", afterindex); return 0; } - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) { foundindex = i; foundanindex = 1; break; @@ -612,33 +536,27 @@ int CreateNewWP_InTrail(vec3_t origin, int flags, int afterindex) i++; } - if (!foundanindex) - { + if (!foundanindex) { trap->Print(S_COLOR_YELLOW "Waypoint index %i should exist, but does not (?)\n", afterindex); return 0; } i = gWPNum; - while (i >= 0) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index != foundindex) - { - TransferWPData(i, i+1); - } - else if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == foundindex) - { + while (i >= 0) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index != foundindex) { + TransferWPData(i, i + 1); + } else if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == foundindex) { i++; - if (!gWPArray[i]) - { + if (!gWPArray[i]) { gWPArray[i] = (wpobject_t *)B_Alloc(sizeof(wpobject_t)); } gWPArray[i]->flags = flags; - gWPArray[i]->weight = 0; //calculated elsewhere - gWPArray[i]->associated_entity = ENTITYNUM_NONE; //set elsewhere - gWPArray[i]->disttonext = 0; //calculated elsewhere + gWPArray[i]->weight = 0; // calculated elsewhere + gWPArray[i]->associated_entity = ENTITYNUM_NONE; // set elsewhere + gWPArray[i]->disttonext = 0; // calculated elsewhere gWPArray[i]->forceJumpTo = 0; gWPArray[i]->index = i; gWPArray[i]->inuse = 1; @@ -653,8 +571,7 @@ int CreateNewWP_InTrail(vec3_t origin, int flags, int afterindex) return 1; } -int CreateNewWP_InsertUnder(vec3_t origin, int flags, int afterindex) -{ +int CreateNewWP_InsertUnder(vec3_t origin, int flags, int afterindex) { int foundindex; int foundanindex; int i; @@ -663,25 +580,20 @@ int CreateNewWP_InsertUnder(vec3_t origin, int flags, int afterindex) foundanindex = 0; i = 0; - if (gWPNum >= MAX_WPARRAY_SIZE) - { - if (!RMG.integer) - { + if (gWPNum >= MAX_WPARRAY_SIZE) { + if (!RMG.integer) { trap->Print(S_COLOR_YELLOW "Warning: Waypoint limit hit (%i)\n", MAX_WPARRAY_SIZE); } return 0; } - if (afterindex < 0 || afterindex >= gWPNum) - { + if (afterindex < 0 || afterindex >= gWPNum) { trap->Print(S_COLOR_YELLOW "Waypoint number %i does not exist\n", afterindex); return 0; } - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) { foundindex = i; foundanindex = 1; break; @@ -690,34 +602,28 @@ int CreateNewWP_InsertUnder(vec3_t origin, int flags, int afterindex) i++; } - if (!foundanindex) - { + if (!foundanindex) { trap->Print(S_COLOR_YELLOW "Waypoint index %i should exist, but does not (?)\n", afterindex); return 0; } i = gWPNum; - while (i >= 0) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index != foundindex) - { - TransferWPData(i, i+1); - } - else if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == foundindex) - { - //i++; - TransferWPData(i, i+1); + while (i >= 0) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index != foundindex) { + TransferWPData(i, i + 1); + } else if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == foundindex) { + // i++; + TransferWPData(i, i + 1); - if (!gWPArray[i]) - { + if (!gWPArray[i]) { gWPArray[i] = (wpobject_t *)B_Alloc(sizeof(wpobject_t)); } gWPArray[i]->flags = flags; - gWPArray[i]->weight = 0; //calculated elsewhere - gWPArray[i]->associated_entity = ENTITYNUM_NONE; //set elsewhere - gWPArray[i]->disttonext = 0; //calculated elsewhere + gWPArray[i]->weight = 0; // calculated elsewhere + gWPArray[i]->associated_entity = ENTITYNUM_NONE; // set elsewhere + gWPArray[i]->disttonext = 0; // calculated elsewhere gWPArray[i]->forceJumpTo = 0; gWPArray[i]->index = i; gWPArray[i]->inuse = 1; @@ -732,14 +638,12 @@ int CreateNewWP_InsertUnder(vec3_t origin, int flags, int afterindex) return 1; } -void TeleportToWP(gentity_t *pl, int afterindex) -{ +void TeleportToWP(gentity_t *pl, int afterindex) { int foundindex; int foundanindex; int i; - if (!pl || !pl->client) - { + if (!pl || !pl->client) { return; } @@ -747,16 +651,13 @@ void TeleportToWP(gentity_t *pl, int afterindex) foundanindex = 0; i = 0; - if (afterindex < 0 || afterindex >= gWPNum) - { + if (afterindex < 0 || afterindex >= gWPNum) { trap->Print(S_COLOR_YELLOW "Waypoint number %i does not exist\n", afterindex); return; } - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->index == afterindex) { foundindex = i; foundanindex = 1; break; @@ -765,8 +666,7 @@ void TeleportToWP(gentity_t *pl, int afterindex) i++; } - if (!foundanindex) - { + if (!foundanindex) { trap->Print(S_COLOR_YELLOW "Waypoint index %i should exist, but does not (?)\n", afterindex); return; } @@ -776,10 +676,8 @@ void TeleportToWP(gentity_t *pl, int afterindex) return; } -void WPFlagsModify(int wpnum, int flags) -{ - if (wpnum < 0 || wpnum >= gWPNum || !gWPArray[wpnum] || !gWPArray[wpnum]->inuse) - { +void WPFlagsModify(int wpnum, int flags) { + if (wpnum < 0 || wpnum >= gWPNum || !gWPArray[wpnum] || !gWPArray[wpnum]->inuse) { trap->Print(S_COLOR_YELLOW "WPFlagsModify: Waypoint %i does not exist\n", wpnum); return; } @@ -787,36 +685,27 @@ void WPFlagsModify(int wpnum, int flags) gWPArray[wpnum]->flags = flags; } -static int NotWithinRange(int base, int extent) -{ - if (extent > base && base+5 >= extent) - { +static int NotWithinRange(int base, int extent) { + if (extent > base && base + 5 >= extent) { return 0; } - if (extent < base && base-5 <= extent) - { + if (extent < base && base - 5 <= extent) { return 0; } return 1; } -int NodeHere(vec3_t spot) -{ +int NodeHere(vec3_t spot) { int i; i = 0; - while (i < nodenum) - { - if ((int)nodetable[i].origin[0] == (int)spot[0] && - (int)nodetable[i].origin[1] == (int)spot[1]) - { - if ((int)nodetable[i].origin[2] == (int)spot[2] || - ((int)nodetable[i].origin[2] < (int)spot[2] && (int)nodetable[i].origin[2]+5 > (int)spot[2]) || - ((int)nodetable[i].origin[2] > (int)spot[2] && (int)nodetable[i].origin[2]-5 < (int)spot[2])) - { + while (i < nodenum) { + if ((int)nodetable[i].origin[0] == (int)spot[0] && (int)nodetable[i].origin[1] == (int)spot[1]) { + if ((int)nodetable[i].origin[2] == (int)spot[2] || ((int)nodetable[i].origin[2] < (int)spot[2] && (int)nodetable[i].origin[2] + 5 > (int)spot[2]) || + ((int)nodetable[i].origin[2] > (int)spot[2] && (int)nodetable[i].origin[2] - 5 < (int)spot[2])) { return 1; } } @@ -826,14 +715,12 @@ int NodeHere(vec3_t spot) return 0; } -int CanGetToVector(vec3_t org1, vec3_t org2, vec3_t mins, vec3_t maxs) -{ +int CanGetToVector(vec3_t org1, vec3_t org2, vec3_t mins, vec3_t maxs) { trace_t tr; trap->Trace(&tr, org1, mins, maxs, org2, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { return 1; } @@ -898,7 +785,7 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t org2, vec3_t mins, vec3_t maxs) } #else int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) -//int ExampleAnimEntMove(gentity_t *self, vec3_t moveTo, float stepSize) +// int ExampleAnimEntMove(gentity_t *self, vec3_t moveTo, float stepSize) { trace_t tr; vec3_t stepTo; @@ -920,37 +807,33 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) stepTo[2] = workingOrg[2]; VectorSubtract(stepTo, workingOrg, stepSub); - stepSize = VectorLength(stepSub); //make the step size the length of the original positions without Z + stepSize = VectorLength(stepSub); // make the step size the length of the original positions without Z VectorNormalize(stepSub); - while (!initialDone || didMove) - { + while (!initialDone || didMove) { initialDone = qtrue; didMove = 0; - stepGoal[0] = workingOrg[0] + stepSub[0]*stepSize; - stepGoal[1] = workingOrg[1] + stepSub[1]*stepSize; - stepGoal[2] = workingOrg[2] + stepSub[2]*stepSize; + stepGoal[0] = workingOrg[0] + stepSub[0] * stepSize; + stepGoal[1] = workingOrg[1] + stepSub[1] * stepSize; + stepGoal[2] = workingOrg[2] + stepSub[2] * stepSize; trap->Trace(&tr, workingOrg, mins, maxs, stepGoal, ENTITYNUM_NONE, traceMask, qfalse, 0, 0); - if (!tr.startsolid && !tr.allsolid && tr.fraction) - { + if (!tr.startsolid && !tr.allsolid && tr.fraction) { vec3_t vecSub; VectorSubtract(workingOrg, tr.endpos, vecSub); - if (VectorLength(vecSub) > (stepSize/2)) - { + if (VectorLength(vecSub) > (stepSize / 2)) { workingOrg[0] = tr.endpos[0]; workingOrg[1] = tr.endpos[1]; - //trap->LinkEntity(self); + // trap->LinkEntity(self); didMove = 1; } } - if (didMove != 1) - { //stair check + if (didMove != 1) { // stair check vec3_t trFrom; vec3_t trTo; vec3_t trDir; @@ -959,21 +842,19 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) VectorCopy(tr.endpos, trFrom); trFrom[2] += 16; - VectorSubtract(/*tr.endpos*/stepGoal, workingOrg, trDir); + VectorSubtract(/*tr.endpos*/ stepGoal, workingOrg, trDir); VectorNormalize(trDir); - trTo[0] = tr.endpos[0] + trDir[0]*2; - trTo[1] = tr.endpos[1] + trDir[1]*2; - trTo[2] = tr.endpos[2] + trDir[2]*2; + trTo[0] = tr.endpos[0] + trDir[0] * 2; + trTo[1] = tr.endpos[1] + trDir[1] * 2; + trTo[2] = tr.endpos[2] + trDir[2] * 2; trTo[2] += 16; VectorSubtract(trFrom, trTo, vecMeasure); - if (VectorLength(vecMeasure) > 1) - { + if (VectorLength(vecMeasure) > 1) { trap->Trace(&tr, trFrom, mins, maxs, trTo, ENTITYNUM_NONE, traceMask, qfalse, 0, 0); - if (!tr.startsolid && !tr.allsolid && tr.fraction == 1) - { //clear trace here, probably up a step + if (!tr.startsolid && !tr.allsolid && tr.fraction == 1) { // clear trace here, probably up a step vec3_t trDown; vec3_t trUp; VectorCopy(tr.endpos, trUp); @@ -982,10 +863,9 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) trap->Trace(&tr, trFrom, mins, maxs, trTo, ENTITYNUM_NONE, traceMask, qfalse, 0, 0); - if (!tr.startsolid && !tr.allsolid) - { //plop us down on the step after moving up + if (!tr.startsolid && !tr.allsolid) { // plop us down on the step after moving up VectorCopy(tr.endpos, workingOrg); - //trap->LinkEntity(self); + // trap->LinkEntity(self); didMove = 1; } } @@ -995,14 +875,12 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) VectorSubtract(lastIncrement, workingOrg, finalMeasure); measureLength = VectorLength(finalMeasure); - if (!measureLength) - { //no progress, break out. If last movement was a sucess didMove will equal 1. + if (!measureLength) { // no progress, break out. If last movement was a sucess didMove will equal 1. break; } - stepSize -= measureLength; //subtract the progress distance from the step size so we don't overshoot the mark. - if (stepSize <= 0) - { + stepSize -= measureLength; // subtract the progress distance from the step size so we don't overshoot the mark. + if (stepSize <= 0) { break; } @@ -1013,8 +891,7 @@ int CanGetToVectorTravel(vec3_t org1, vec3_t moveTo, vec3_t mins, vec3_t maxs) } #endif -int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) -{ +int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) { int foundit; int cancontinue; int i; @@ -1022,7 +899,7 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) int successnodeindex; int insertindex; int prenodestart; - static byte extendednodes[MAX_NODETABLE_SIZE]; //for storing checked nodes and not trying to extend them each a bazillion times + static byte extendednodes[MAX_NODETABLE_SIZE]; // for storing checked nodes and not trying to extend them each a bazillion times float fvecmeas; float baseheight; float branchDistance; @@ -1034,30 +911,23 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) vec3_t validspotpos; trace_t tr; - memset( extendednodes, 0, sizeof( extendednodes ) ); + memset(extendednodes, 0, sizeof(extendednodes)); - if (RMG.integer) - { //this might be temporary. Or not. - if (!(gWPArray[startindex]->flags & WPFLAG_NEVERONEWAY) && - !(gWPArray[endindex]->flags & WPFLAG_NEVERONEWAY)) - { + if (RMG.integer) { // this might be temporary. Or not. + if (!(gWPArray[startindex]->flags & WPFLAG_NEVERONEWAY) && !(gWPArray[endindex]->flags & WPFLAG_NEVERONEWAY)) { gWPArray[startindex]->flags |= WPFLAG_ONEWAY_FWD; gWPArray[endindex]->flags |= WPFLAG_ONEWAY_BACK; } return 0; } - if (!RMG.integer) - { + if (!RMG.integer) { branchDistance = TABLE_BRANCH_DISTANCE; - } - else - { - branchDistance = 512; //be less precise here, terrain is fairly broad, and we don't want to take an hour precalculating + } else { + branchDistance = 512; // be less precise here, terrain is fairly broad, and we don't want to take an hour precalculating } - if (RMG.integer) - { + if (RMG.integer) { maxDistFactor = 700; } @@ -1075,10 +945,10 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) successnodeindex = 0; - while (i < MAX_NODETABLE_SIZE) //clear it out before using it + while (i < MAX_NODETABLE_SIZE) // clear it out before using it { nodetable[i].flags = 0; -// nodetable[i].index = 0; + // nodetable[i].index = 0; nodetable[i].inuse = 0; nodetable[i].neighbornum = 0; nodetable[i].origin[0] = 0; @@ -1093,8 +963,7 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) i = 0; - if (!behindTheScenes) - { + if (!behindTheScenes) { trap->Print(S_COLOR_YELLOW "Point %i is not connected to %i - Repairing...\n", startindex, endindex); } @@ -1113,42 +982,31 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) VectorCopy(startplace, nodetable[nodenum].origin); nodetable[nodenum].weight = 1; nodetable[nodenum].inuse = 1; -// nodetable[nodenum].index = nodenum; + // nodetable[nodenum].index = nodenum; nodenum++; - while (nodenum < MAX_NODETABLE_SIZE && !foundit && cancontinue) - { - if (RMG.integer) - { //adjust the branch distance dynamically depending on the distance from the start and end points. + while (nodenum < MAX_NODETABLE_SIZE && !foundit && cancontinue) { + if (RMG.integer) { // adjust the branch distance dynamically depending on the distance from the start and end points. vec3_t startDist; vec3_t endDist; float startDistf; float endDistf; - VectorSubtract(nodetable[nodenum-1].origin, gWPArray[startindex]->origin, startDist); - VectorSubtract(nodetable[nodenum-1].origin, gWPArray[endindex]->origin, endDist); + VectorSubtract(nodetable[nodenum - 1].origin, gWPArray[startindex]->origin, startDist); + VectorSubtract(nodetable[nodenum - 1].origin, gWPArray[endindex]->origin, endDist); startDistf = VectorLength(startDist); endDistf = VectorLength(endDist); - if (startDistf < 64 || endDistf < 64) - { + if (startDistf < 64 || endDistf < 64) { branchDistance = 64; - } - else if (startDistf < 128 || endDistf < 128) - { + } else if (startDistf < 128 || endDistf < 128) { branchDistance = 128; - } - else if (startDistf < 256 || endDistf < 256) - { + } else if (startDistf < 256 || endDistf < 256) { branchDistance = 256; - } - else if (startDistf < 512 || endDistf < 512) - { + } else if (startDistf < 512 || endDistf < 512) { branchDistance = 512; - } - else - { + } else { branchDistance = 800; } } @@ -1156,15 +1014,12 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) i = 0; prenodestart = nodenum; - while (i < prenodestart) - { - if (extendednodes[i] != 1) - { + while (i < prenodestart) { + if (extendednodes[i] != 1) { VectorSubtract(gWPArray[endindex]->origin, nodetable[i].origin, a); fvecmeas = VectorLength(a); - if (fvecmeas < 128 && CanGetToVector(gWPArray[endindex]->origin, nodetable[i].origin, mins, maxs)) - { + if (fvecmeas < 128 && CanGetToVector(gWPArray[endindex]->origin, nodetable[i].origin, mins, maxs)) { foundit = 1; successnodeindex = i; break; @@ -1179,26 +1034,24 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) trap->Trace(&tr, testspot, NULL, NULL, starttrace, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - testspot[2] = tr.endpos[2]+baseheight; + testspot[2] = tr.endpos[2] + baseheight; - if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) - { + if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) { VectorCopy(testspot, nodetable[nodenum].origin); nodetable[nodenum].inuse = 1; -// nodetable[nodenum].index = nodenum; - nodetable[nodenum].weight = nodetable[i].weight+1; + // nodetable[nodenum].index = nodenum; + nodetable[nodenum].weight = nodetable[i].weight + 1; nodetable[nodenum].neighbornum = i; - if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > 50) - { //if there's a big drop, make sure we know we can't just magically fly back up + if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > + 50) { // if there's a big drop, make sure we know we can't just magically fly back up nodetable[nodenum].flags = WPFLAG_ONEWAY_FWD; } nodenum++; cancontinue = 1; } - if (nodenum >= MAX_NODETABLE_SIZE) - { - break; //failure + if (nodenum >= MAX_NODETABLE_SIZE) { + break; // failure } VectorCopy(nodetable[i].origin, testspot); @@ -1210,26 +1063,24 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) trap->Trace(&tr, testspot, NULL, NULL, starttrace, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - testspot[2] = tr.endpos[2]+baseheight; + testspot[2] = tr.endpos[2] + baseheight; - if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) - { + if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) { VectorCopy(testspot, nodetable[nodenum].origin); nodetable[nodenum].inuse = 1; -// nodetable[nodenum].index = nodenum; - nodetable[nodenum].weight = nodetable[i].weight+1; + // nodetable[nodenum].index = nodenum; + nodetable[nodenum].weight = nodetable[i].weight + 1; nodetable[nodenum].neighbornum = i; - if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > 50) - { //if there's a big drop, make sure we know we can't just magically fly back up + if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > + 50) { // if there's a big drop, make sure we know we can't just magically fly back up nodetable[nodenum].flags = WPFLAG_ONEWAY_FWD; } nodenum++; cancontinue = 1; } - if (nodenum >= MAX_NODETABLE_SIZE) - { - break; //failure + if (nodenum >= MAX_NODETABLE_SIZE) { + break; // failure } VectorCopy(nodetable[i].origin, testspot); @@ -1241,26 +1092,24 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) trap->Trace(&tr, testspot, NULL, NULL, starttrace, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - testspot[2] = tr.endpos[2]+baseheight; + testspot[2] = tr.endpos[2] + baseheight; - if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) - { + if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) { VectorCopy(testspot, nodetable[nodenum].origin); nodetable[nodenum].inuse = 1; -// nodetable[nodenum].index = nodenum; - nodetable[nodenum].weight = nodetable[i].weight+1; + // nodetable[nodenum].index = nodenum; + nodetable[nodenum].weight = nodetable[i].weight + 1; nodetable[nodenum].neighbornum = i; - if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > 50) - { //if there's a big drop, make sure we know we can't just magically fly back up + if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > + 50) { // if there's a big drop, make sure we know we can't just magically fly back up nodetable[nodenum].flags = WPFLAG_ONEWAY_FWD; } nodenum++; cancontinue = 1; } - if (nodenum >= MAX_NODETABLE_SIZE) - { - break; //failure + if (nodenum >= MAX_NODETABLE_SIZE) { + break; // failure } VectorCopy(nodetable[i].origin, testspot); @@ -1272,26 +1121,24 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) trap->Trace(&tr, testspot, NULL, NULL, starttrace, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - testspot[2] = tr.endpos[2]+baseheight; + testspot[2] = tr.endpos[2] + baseheight; - if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) - { + if (!NodeHere(testspot) && !tr.startsolid && !tr.allsolid && CanGetToVector(nodetable[i].origin, testspot, mins, maxs)) { VectorCopy(testspot, nodetable[nodenum].origin); nodetable[nodenum].inuse = 1; -// nodetable[nodenum].index = nodenum; - nodetable[nodenum].weight = nodetable[i].weight+1; + // nodetable[nodenum].index = nodenum; + nodetable[nodenum].weight = nodetable[i].weight + 1; nodetable[nodenum].neighbornum = i; - if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > 50) - { //if there's a big drop, make sure we know we can't just magically fly back up + if ((nodetable[i].origin[2] - nodetable[nodenum].origin[2]) > + 50) { // if there's a big drop, make sure we know we can't just magically fly back up nodetable[nodenum].flags = WPFLAG_ONEWAY_FWD; } nodenum++; cancontinue = 1; } - if (nodenum >= MAX_NODETABLE_SIZE) - { - break; //failure + if (nodenum >= MAX_NODETABLE_SIZE) { + break; // failure } extendednodes[i] = 1; @@ -1301,9 +1148,8 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) } } - if (!foundit) - { -#ifndef _DEBUG //if debug just always print this. + if (!foundit) { +#ifndef _DEBUG // if debug just always print this. if (!behindTheScenes) #endif { @@ -1311,9 +1157,10 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) } gWPArray[startindex]->flags |= WPFLAG_ONEWAY_FWD; gWPArray[endindex]->flags |= WPFLAG_ONEWAY_BACK; - if (!behindTheScenes) - { - trap->Print(S_COLOR_YELLOW "Since points cannot be connected, point %i has been flagged as only-forward and point %i has been flagged as only-backward.\n", startindex, endindex); + if (!behindTheScenes) { + trap->Print(S_COLOR_YELLOW + "Since points cannot be connected, point %i has been flagged as only-forward and point %i has been flagged as only-backward.\n", + startindex, endindex); } /*while (nodenum >= 0) @@ -1325,40 +1172,33 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) nodenum--; }*/ - //The above code transfers nodes into the "rendered" waypoint array. Strictly for debugging. + // The above code transfers nodes into the "rendered" waypoint array. Strictly for debugging. - if (!behindTheScenes) - { //just use what we have if we're auto-pathing the level + if (!behindTheScenes) { // just use what we have if we're auto-pathing the level return 0; - } - else - { + } else { vec3_t endDist; int nCount = 0; int idealNode = -1; float bestDist = 0; float testDist; - if (nodenum <= 10) - { //not enough to even really bother. + if (nodenum <= 10) { // not enough to even really bother. return 0; } - //Since it failed, find whichever node is closest to the desired end. - while (nCount < nodenum) - { + // Since it failed, find whichever node is closest to the desired end. + while (nCount < nodenum) { VectorSubtract(nodetable[nCount].origin, gWPArray[endindex]->origin, endDist); testDist = VectorLength(endDist); - if (idealNode == -1) - { + if (idealNode == -1) { idealNode = nCount; bestDist = testDist; nCount++; continue; } - if (testDist < bestDist) - { + if (testDist < bestDist) { idealNode = nCount; bestDist = testDist; } @@ -1366,8 +1206,7 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) nCount++; } - if (idealNode == -1) - { + if (idealNode == -1) { return 0; } @@ -1380,16 +1219,16 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) failsafe = 0; VectorCopy(gWPArray[startindex]->origin, validspotpos); - while (failsafe < MAX_NODETABLE_SIZE && i < MAX_NODETABLE_SIZE && i >= 0) - { + while (failsafe < MAX_NODETABLE_SIZE && i < MAX_NODETABLE_SIZE && i >= 0) { VectorSubtract(validspotpos, nodetable[i].origin, a); - if (!nodetable[nodetable[i].neighbornum].inuse || !CanGetToVectorTravel(validspotpos, /*nodetable[nodetable[i].neighbornum].origin*/nodetable[i].origin, mins, maxs) || VectorLength(a) > maxDistFactor || (!CanGetToVectorTravel(validspotpos, gWPArray[endindex]->origin, mins, maxs) && CanGetToVectorTravel(nodetable[i].origin, gWPArray[endindex]->origin, mins, maxs)) ) - { + if (!nodetable[nodetable[i].neighbornum].inuse || + !CanGetToVectorTravel(validspotpos, /*nodetable[nodetable[i].neighbornum].origin*/ nodetable[i].origin, mins, maxs) || + VectorLength(a) > maxDistFactor || + (!CanGetToVectorTravel(validspotpos, gWPArray[endindex]->origin, mins, maxs) && + CanGetToVectorTravel(nodetable[i].origin, gWPArray[endindex]->origin, mins, maxs))) { nodetable[i].flags |= WPFLAG_CALCULATED; - if (!CreateNewWP_InTrail(nodetable[i].origin, nodetable[i].flags, insertindex)) - { - if (!behindTheScenes) - { + if (!CreateNewWP_InTrail(nodetable[i].origin, nodetable[i].flags, insertindex)) { + if (!behindTheScenes) { trap->Print(S_COLOR_RED "Could not link %i to %i, waypoint limit hit.\n", startindex, endindex); } return 0; @@ -1398,8 +1237,7 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) VectorCopy(nodetable[i].origin, validspotpos); } - if (i == 0) - { + if (i == 0) { break; } @@ -1408,57 +1246,47 @@ int ConnectTrail(int startindex, int endindex, qboolean behindTheScenes) failsafe++; } - if (!behindTheScenes) - { + if (!behindTheScenes) { trap->Print(S_COLOR_YELLOW "Finished connecting %i to %i.\n", startindex, endindex); } return 1; } -int OpposingEnds(int start, int end) -{ - if (!gWPArray[start] || !gWPArray[start]->inuse || !gWPArray[end] || !gWPArray[end]->inuse) - { +int OpposingEnds(int start, int end) { + if (!gWPArray[start] || !gWPArray[start]->inuse || !gWPArray[end] || !gWPArray[end]->inuse) { return 0; } - if ((gWPArray[start]->flags & WPFLAG_ONEWAY_FWD) && - (gWPArray[end]->flags & WPFLAG_ONEWAY_BACK)) - { + if ((gWPArray[start]->flags & WPFLAG_ONEWAY_FWD) && (gWPArray[end]->flags & WPFLAG_ONEWAY_BACK)) { return 1; } return 0; } -int DoorBlockingSection(int start, int end) -{ //if a door blocks the trail, we'll just have to assume the points on each side are in visibility when it's open +int DoorBlockingSection(int start, int end) { // if a door blocks the trail, we'll just have to assume the points on each side are in visibility when it's open trace_t tr; gentity_t *testdoor; int start_trace_index; - if (!gWPArray[start] || !gWPArray[start]->inuse || !gWPArray[end] || !gWPArray[end]->inuse) - { + if (!gWPArray[start] || !gWPArray[start]->inuse || !gWPArray[end] || !gWPArray[end]->inuse) { return 0; } trap->Trace(&tr, gWPArray[start]->origin, NULL, NULL, gWPArray[end]->origin, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 0; } testdoor = &g_entities[tr.entityNum]; - if (!testdoor) - { + if (!testdoor) { return 0; } - if (!strstr(testdoor->classname, "func_")) - { + if (!strstr(testdoor->classname, "func_")) { return 0; } @@ -1466,34 +1294,29 @@ int DoorBlockingSection(int start, int end) trap->Trace(&tr, gWPArray[end]->origin, NULL, NULL, gWPArray[start]->origin, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1) - { + if (tr.fraction == 1) { return 0; } - if (start_trace_index == tr.entityNum) - { + if (start_trace_index == tr.entityNum) { return 1; } return 0; } -int RepairPaths(qboolean behindTheScenes) -{ +int RepairPaths(qboolean behindTheScenes) { int i; -// int ctRet; + // int ctRet; vec3_t a; float maxDistFactor = 400; - if (!gWPNum) - { + if (!gWPNum) { return 0; } - if (RMG.integer) - { - maxDistFactor = 800; //higher tolerance here. + if (RMG.integer) { + maxDistFactor = 800; // higher tolerance here. } i = 0; @@ -1501,23 +1324,21 @@ int RepairPaths(qboolean behindTheScenes) trap->Cvar_Update(&bot_wp_distconnect); trap->Cvar_Update(&bot_wp_visconnect); - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i+1] && gWPArray[i+1]->inuse) - { - VectorSubtract(gWPArray[i]->origin, gWPArray[i+1]->origin, a); - - if (!(gWPArray[i+1]->flags & WPFLAG_NOVIS) && - !(gWPArray[i+1]->flags & WPFLAG_JUMP) && //don't calculate on jump points because they might not always want to be visible (in cases of force jumping) - !(gWPArray[i]->flags & WPFLAG_CALCULATED) && //don't calculate it again - !OpposingEnds(i, i+1) && - ((bot_wp_distconnect.value && VectorLength(a) > maxDistFactor) || (!OrgVisible(gWPArray[i]->origin, gWPArray[i+1]->origin, ENTITYNUM_NONE) && bot_wp_visconnect.value) ) && - !DoorBlockingSection(i, i+1)) - { - /*ctRet = */ConnectTrail(i, i+1, behindTheScenes); - - if (gWPNum >= MAX_WPARRAY_SIZE) - { //Bad! + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i + 1] && gWPArray[i + 1]->inuse) { + VectorSubtract(gWPArray[i]->origin, gWPArray[i + 1]->origin, a); + + if (!(gWPArray[i + 1]->flags & WPFLAG_NOVIS) && + !(gWPArray[i + 1]->flags & + WPFLAG_JUMP) && // don't calculate on jump points because they might not always want to be visible (in cases of force jumping) + !(gWPArray[i]->flags & WPFLAG_CALCULATED) && // don't calculate it again + !OpposingEnds(i, i + 1) && + ((bot_wp_distconnect.value && VectorLength(a) > maxDistFactor) || + (!OrgVisible(gWPArray[i]->origin, gWPArray[i + 1]->origin, ENTITYNUM_NONE) && bot_wp_visconnect.value)) && + !DoorBlockingSection(i, i + 1)) { + /*ctRet = */ ConnectTrail(i, i + 1, behindTheScenes); + + if (gWPNum >= MAX_WPARRAY_SIZE) { // Bad! gWPNum = MAX_WPARRAY_SIZE; break; } @@ -1535,8 +1356,7 @@ int RepairPaths(qboolean behindTheScenes) return 1; } -int OrgVisibleCurve(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) -{ +int OrgVisibleCurve(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) { trace_t tr; vec3_t evenorg1; @@ -1545,12 +1365,10 @@ int OrgVisibleCurve(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int igno trap->Trace(&tr, evenorg1, mins, maxs, org2, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { trap->Trace(&tr, evenorg1, mins, maxs, org1, ignore, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { return 1; } } @@ -1558,8 +1376,7 @@ int OrgVisibleCurve(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int igno return 0; } -int CanForceJumpTo(int baseindex, int testingindex, float distance) -{ +int CanForceJumpTo(int baseindex, int testingindex, float distance) { float heightdif; vec3_t xy_base, xy_test, v, mins, maxs; wpobject_t *wpBase = gWPArray[baseindex]; @@ -1570,15 +1387,13 @@ int CanForceJumpTo(int baseindex, int testingindex, float distance) mins[2] = -15; //-1 maxs[0] = 15; maxs[1] = 15; - maxs[2] = 15; //1 + maxs[2] = 15; // 1 - if (!wpBase || !wpBase->inuse || !wpTest || !wpTest->inuse) - { + if (!wpBase || !wpBase->inuse || !wpTest || !wpTest->inuse) { return 0; } - if (distance > 400) - { + if (distance > 400) { return 0; } @@ -1589,51 +1404,38 @@ int CanForceJumpTo(int baseindex, int testingindex, float distance) VectorSubtract(xy_base, xy_test, v); - if (VectorLength(v) > MAX_NEIGHBOR_LINK_DISTANCE) - { + if (VectorLength(v) > MAX_NEIGHBOR_LINK_DISTANCE) { return 0; } - if ((int)wpBase->origin[2] < (int)wpTest->origin[2]) - { + if ((int)wpBase->origin[2] < (int)wpTest->origin[2]) { heightdif = wpTest->origin[2] - wpBase->origin[2]; - } - else - { - return 0; //err.. + } else { + return 0; // err.. } - if (heightdif < 128) - { //don't bother.. + if (heightdif < 128) { // don't bother.. return 0; } - if (heightdif > 512) - { //too high + if (heightdif > 512) { // too high return 0; } - if (!OrgVisibleCurve(wpBase->origin, mins, maxs, wpTest->origin, ENTITYNUM_NONE)) - { + if (!OrgVisibleCurve(wpBase->origin, mins, maxs, wpTest->origin, ENTITYNUM_NONE)) { return 0; } - if (heightdif > 400) - { + if (heightdif > 400) { return 3; - } - else if (heightdif > 256) - { + } else if (heightdif > 256) { return 2; - } - else - { + } else { return 1; } } -void CalculatePaths(void) -{ +void CalculatePaths(void) { int i; int c; int forceJumpable; @@ -1642,14 +1444,12 @@ void CalculatePaths(void) vec3_t a; vec3_t mins, maxs; - if (!gWPNum) - { + if (!gWPNum) { return; } - if (RMG.integer) - { - maxNeighborDist = DEFAULT_GRID_SPACING + (DEFAULT_GRID_SPACING*0.5); + if (RMG.integer) { + maxNeighborDist = DEFAULT_GRID_SPACING + (DEFAULT_GRID_SPACING * 0.5); } mins[0] = -15; @@ -1657,17 +1457,14 @@ void CalculatePaths(void) mins[2] = -15; //-1 maxs[0] = 15; maxs[1] = 15; - maxs[2] = 15; //1 + maxs[2] = 15; // 1 - //now clear out all the neighbor data before we recalculate + // now clear out all the neighbor data before we recalculate i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->neighbornum) - { - while (gWPArray[i]->neighbornum >= 0) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->neighbornum) { + while (gWPArray[i]->neighbornum >= 0) { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].num = 0; gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 0; gWPArray[i]->neighbornum--; @@ -1680,40 +1477,29 @@ void CalculatePaths(void) i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { c = 0; - while (c < gWPNum) - { - if (gWPArray[c] && gWPArray[c]->inuse && i != c && - NotWithinRange(i, c)) - { + while (c < gWPNum) { + if (gWPArray[c] && gWPArray[c]->inuse && i != c && NotWithinRange(i, c)) { VectorSubtract(gWPArray[i]->origin, gWPArray[c]->origin, a); nLDist = VectorLength(a); forceJumpable = CanForceJumpTo(i, c, nLDist); - if ((nLDist < maxNeighborDist || forceJumpable) && - ((int)gWPArray[i]->origin[2] == (int)gWPArray[c]->origin[2] || forceJumpable) && - (OrgVisibleBox(gWPArray[i]->origin, mins, maxs, gWPArray[c]->origin, ENTITYNUM_NONE) || forceJumpable)) - { + if ((nLDist < maxNeighborDist || forceJumpable) && ((int)gWPArray[i]->origin[2] == (int)gWPArray[c]->origin[2] || forceJumpable) && + (OrgVisibleBox(gWPArray[i]->origin, mins, maxs, gWPArray[c]->origin, ENTITYNUM_NONE) || forceJumpable)) { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].num = c; - if (forceJumpable && ((int)gWPArray[i]->origin[2] != (int)gWPArray[c]->origin[2] || nLDist < maxNeighborDist)) - { - gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 999;//forceJumpable; //FJSR - } - else - { + if (forceJumpable && ((int)gWPArray[i]->origin[2] != (int)gWPArray[c]->origin[2] || nLDist < maxNeighborDist)) { + gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 999; // forceJumpable; //FJSR + } else { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 0; } gWPArray[i]->neighbornum++; } - if (gWPArray[i]->neighbornum >= MAX_NEIGHBOR_SIZE) - { + if (gWPArray[i]->neighbornum >= MAX_NEIGHBOR_SIZE) { break; } } @@ -1724,27 +1510,23 @@ void CalculatePaths(void) } } -gentity_t *GetObjectThatTargets(gentity_t *ent) -{ +gentity_t *GetObjectThatTargets(gentity_t *ent) { gentity_t *next = NULL; - if (!ent->targetname) - { + if (!ent->targetname) { return NULL; } - next = G_Find( next, FOFS(target), ent->targetname ); + next = G_Find(next, FOFS(target), ent->targetname); - if (next) - { + if (next) { return next; } return NULL; } -void CalculateSiegeGoals(void) -{ +void CalculateSiegeGoals(void) { int i = 0; int looptracker = 0; int wpindex = 0; @@ -1752,48 +1534,39 @@ void CalculateSiegeGoals(void) gentity_t *ent; gentity_t *tent = NULL, *t2ent = NULL; - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; tent = NULL; - if (ent && ent->classname && strcmp(ent->classname, "info_siege_objective") == 0) - { + if (ent && ent->classname && strcmp(ent->classname, "info_siege_objective") == 0) { tent = ent; t2ent = GetObjectThatTargets(tent); looptracker = 0; - while (t2ent && looptracker < 2048) - { //looptracker keeps us from getting stuck in case something is set up weird on this map + while (t2ent && looptracker < 2048) { // looptracker keeps us from getting stuck in case something is set up weird on this map tent = t2ent; t2ent = GetObjectThatTargets(tent); looptracker++; } - if (looptracker >= 2048) - { //something unpleasent has happened + if (looptracker >= 2048) { // something unpleasent has happened tent = NULL; break; } } - if (tent && ent && tent != ent) - { //tent should now be the object attached to the mission objective - dif[0] = (tent->r.absmax[0]+tent->r.absmin[0])/2; - dif[1] = (tent->r.absmax[1]+tent->r.absmin[1])/2; - dif[2] = (tent->r.absmax[2]+tent->r.absmin[2])/2; + if (tent && ent && tent != ent) { // tent should now be the object attached to the mission objective + dif[0] = (tent->r.absmax[0] + tent->r.absmin[0]) / 2; + dif[1] = (tent->r.absmax[1] + tent->r.absmin[1]) / 2; + dif[2] = (tent->r.absmax[2] + tent->r.absmin[2]) / 2; wpindex = GetNearestVisibleWP(dif, tent->s.number); - if (wpindex != -1 && gWPArray[wpindex] && gWPArray[wpindex]->inuse) - { //found the waypoint nearest the center of this objective-related object - if (ent->side == SIEGETEAM_TEAM1) - { + if (wpindex != -1 && gWPArray[wpindex] && gWPArray[wpindex]->inuse) { // found the waypoint nearest the center of this objective-related object + if (ent->side == SIEGETEAM_TEAM1) { gWPArray[wpindex]->flags |= WPFLAG_SIEGE_IMPERIALOBJ; - } - else - { + } else { gWPArray[wpindex]->flags |= WPFLAG_SIEGE_REBELOBJ; } @@ -1805,29 +1578,27 @@ void CalculateSiegeGoals(void) } } -float botGlobalNavWeaponWeights[WP_NUM_WEAPONS] = -{ - 0,//WP_NONE, - - 0,//WP_STUN_BATON, - 0,//WP_MELEE - 0,//WP_SABER, // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. - 0,//WP_BRYAR_PISTOL, - 3,//WP_BLASTER, - 5,//WP_DISRUPTOR, - 4,//WP_BOWCASTER, - 6,//WP_REPEATER, - 7,//WP_DEMP2, - 8,//WP_FLECHETTE, - 9,//WP_ROCKET_LAUNCHER, - 3,//WP_THERMAL, - 3,//WP_TRIP_MINE, - 3,//WP_DET_PACK, - 0//WP_EMPLACED_GUN, +float botGlobalNavWeaponWeights[WP_NUM_WEAPONS] = { + 0, // WP_NONE, + + 0, // WP_STUN_BATON, + 0, // WP_MELEE + 0, // WP_SABER, // NOTE: lots of code assumes this is the first weapon (... which is crap) so be careful -Ste. + 0, // WP_BRYAR_PISTOL, + 3, // WP_BLASTER, + 5, // WP_DISRUPTOR, + 4, // WP_BOWCASTER, + 6, // WP_REPEATER, + 7, // WP_DEMP2, + 8, // WP_FLECHETTE, + 9, // WP_ROCKET_LAUNCHER, + 3, // WP_THERMAL, + 3, // WP_TRIP_MINE, + 3, // WP_DET_PACK, + 0 // WP_EMPLACED_GUN, }; -int GetNearestVisibleWPToItem(vec3_t org, int ignore) -{ +int GetNearestVisibleWPToItem(vec3_t org, int ignore) { int i; float bestdist; float flLen; @@ -1835,7 +1606,7 @@ int GetNearestVisibleWPToItem(vec3_t org, int ignore) vec3_t a, mins, maxs; i = 0; - bestdist = 64; //has to be less than 64 units to the item or it isn't safe enough + bestdist = 64; // has to be less than 64 units to the item or it isn't safe enough bestindex = -1; mins[0] = -15; @@ -1845,17 +1616,12 @@ int GetNearestVisibleWPToItem(vec3_t org, int ignore) maxs[1] = 15; maxs[2] = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && - gWPArray[i]->origin[2]-15 < org[2] && - gWPArray[i]->origin[2]+15 > org[2]) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->origin[2] - 15 < org[2] && gWPArray[i]->origin[2] + 15 > org[2]) { VectorSubtract(org, gWPArray[i]->origin, a); flLen = VectorLength(a); - if (flLen < bestdist && trap->InPVS(org, gWPArray[i]->origin) && OrgVisibleBox(org, mins, maxs, gWPArray[i]->origin, ignore)) - { + if (flLen < bestdist && trap->InPVS(org, gWPArray[i]->origin) && OrgVisibleBox(org, mins, maxs, gWPArray[i]->origin, ignore)) { bestdist = flLen; bestindex = i; } @@ -1867,8 +1633,7 @@ int GetNearestVisibleWPToItem(vec3_t org, int ignore) return bestindex; } -void CalculateWeightGoals(void) -{ //set waypoint weights depending on weapon and item placement +void CalculateWeightGoals(void) { // set waypoint weights depending on weapon and item placement int i = 0; int wpindex = 0; gentity_t *ent; @@ -1876,16 +1641,12 @@ void CalculateWeightGoals(void) trap->Cvar_Update(&bot_wp_clearweight); - if (bot_wp_clearweight.integer) - { //if set then flush out all weight/goal values before calculating them again - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + if (bot_wp_clearweight.integer) { // if set then flush out all weight/goal values before calculating them again + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { gWPArray[i]->weight = 0; - if (gWPArray[i]->flags & WPFLAG_GOALPOINT) - { + if (gWPArray[i]->flags & WPFLAG_GOALPOINT) { gWPArray[i]->flags &= ~WPFLAG_GOALPOINT; } } @@ -1896,62 +1657,39 @@ void CalculateWeightGoals(void) i = 0; - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; weight = 0; - if (ent && ent->classname) - { - if (strcmp(ent->classname, "item_seeker") == 0) - { + if (ent && ent->classname) { + if (strcmp(ent->classname, "item_seeker") == 0) { weight = 2; - } - else if (strcmp(ent->classname, "item_shield") == 0) - { + } else if (strcmp(ent->classname, "item_shield") == 0) { weight = 2; - } - else if (strcmp(ent->classname, "item_medpac") == 0) - { + } else if (strcmp(ent->classname, "item_medpac") == 0) { weight = 2; - } - else if (strcmp(ent->classname, "item_sentry_gun") == 0) - { + } else if (strcmp(ent->classname, "item_sentry_gun") == 0) { weight = 2; - } - else if (strcmp(ent->classname, "item_force_enlighten_dark") == 0) - { + } else if (strcmp(ent->classname, "item_force_enlighten_dark") == 0) { weight = 5; - } - else if (strcmp(ent->classname, "item_force_enlighten_light") == 0) - { + } else if (strcmp(ent->classname, "item_force_enlighten_light") == 0) { weight = 5; - } - else if (strcmp(ent->classname, "item_force_boon") == 0) - { + } else if (strcmp(ent->classname, "item_force_boon") == 0) { weight = 5; - } - else if (strcmp(ent->classname, "item_ysalimari") == 0) - { + } else if (strcmp(ent->classname, "item_ysalimari") == 0) { weight = 2; - } - else if (strstr(ent->classname, "weapon_") && ent->item) - { + } else if (strstr(ent->classname, "weapon_") && ent->item) { weight = botGlobalNavWeaponWeights[ent->item->giTag]; - } - else if (ent->item && ent->item->giType == IT_AMMO) - { + } else if (ent->item && ent->item->giType == IT_AMMO) { weight = 3; } } - if (ent && weight) - { + if (ent && weight) { wpindex = GetNearestVisibleWPToItem(ent->s.pos.trBase, ent->s.number); - if (wpindex != -1 && gWPArray[wpindex] && gWPArray[wpindex]->inuse) - { //found the waypoint nearest the center of this object + if (wpindex != -1 && gWPArray[wpindex] && gWPArray[wpindex]->inuse) { // found the waypoint nearest the center of this object gWPArray[wpindex]->weight = weight; gWPArray[wpindex]->flags |= WPFLAG_GOALPOINT; gWPArray[wpindex]->associated_entity = ent->s.number; @@ -1962,51 +1700,38 @@ void CalculateWeightGoals(void) } } -void CalculateJumpRoutes(void) -{ +void CalculateJumpRoutes(void) { int i = 0; float nheightdif = 0; float pheightdif = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { - if (gWPArray[i]->flags & WPFLAG_JUMP) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { + if (gWPArray[i]->flags & WPFLAG_JUMP) { nheightdif = 0; pheightdif = 0; gWPArray[i]->forceJumpTo = 0; - if (gWPArray[i-1] && gWPArray[i-1]->inuse && (gWPArray[i-1]->origin[2]+16) < gWPArray[i]->origin[2]) - { - nheightdif = (gWPArray[i]->origin[2] - gWPArray[i-1]->origin[2]); + if (gWPArray[i - 1] && gWPArray[i - 1]->inuse && (gWPArray[i - 1]->origin[2] + 16) < gWPArray[i]->origin[2]) { + nheightdif = (gWPArray[i]->origin[2] - gWPArray[i - 1]->origin[2]); } - if (gWPArray[i+1] && gWPArray[i+1]->inuse && (gWPArray[i+1]->origin[2]+16) < gWPArray[i]->origin[2]) - { - pheightdif = (gWPArray[i]->origin[2] - gWPArray[i+1]->origin[2]); + if (gWPArray[i + 1] && gWPArray[i + 1]->inuse && (gWPArray[i + 1]->origin[2] + 16) < gWPArray[i]->origin[2]) { + pheightdif = (gWPArray[i]->origin[2] - gWPArray[i + 1]->origin[2]); } - if (nheightdif > pheightdif) - { + if (nheightdif > pheightdif) { pheightdif = nheightdif; } - if (pheightdif) - { - if (pheightdif > 500) - { - gWPArray[i]->forceJumpTo = 999; //FORCE_LEVEL_3; //FJSR - } - else if (pheightdif > 256) - { - gWPArray[i]->forceJumpTo = 999; //FORCE_LEVEL_2; //FJSR - } - else if (pheightdif > 128) - { - gWPArray[i]->forceJumpTo = 999; //FORCE_LEVEL_1; //FJSR + if (pheightdif) { + if (pheightdif > 500) { + gWPArray[i]->forceJumpTo = 999; // FORCE_LEVEL_3; //FJSR + } else if (pheightdif > 256) { + gWPArray[i]->forceJumpTo = 999; // FORCE_LEVEL_2; //FJSR + } else if (pheightdif > 128) { + gWPArray[i]->forceJumpTo = 999; // FORCE_LEVEL_1; //FJSR } } } @@ -2016,8 +1741,7 @@ void CalculateJumpRoutes(void) } } -int LoadPathData(const char *filename) -{ +int LoadPathData(const char *filename) { fileHandle_t f; char *fileString; char *currentVar; @@ -2036,18 +1760,16 @@ int LoadPathData(const char *filename) len = trap->FS_Open(routePath, &f, FS_READ); - B_TempFree(1024); //routePath + B_TempFree(1024); // routePath - if (!f) - { + if (!f) { trap->Print(S_COLOR_YELLOW "Bot route data not found for %s\n", filename); return 2; } - if (len >= 524288) - { + if (len >= 524288) { trap->Print(S_COLOR_RED "Route file exceeds maximum length\n"); - trap->FS_Close( f ); + trap->FS_Close(f); return 0; } @@ -2056,18 +1778,15 @@ int LoadPathData(const char *filename) trap->FS_Read(fileString, len, f); - if (fileString[i] == 'l') - { //contains a "levelflags" entry.. + if (fileString[i] == 'l') { // contains a "levelflags" entry.. char readLFlags[64]; i_cv = 0; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { i++; } i++; - while (fileString[i] != '\n') - { + while (fileString[i] != '\n') { readLFlags[i_cv] = fileString[i]; i_cv++; i++; @@ -2076,14 +1795,11 @@ int LoadPathData(const char *filename) i++; gLevelFlags = atoi(readLFlags); - } - else - { + } else { gLevelFlags = 0; } - while (i < len) - { + while (i < len) { i_cv = 0; thiswp.index = 0; @@ -2099,16 +1815,14 @@ int LoadPathData(const char *filename) thiswp.disttonext = 0; nei_num = 0; - while (nei_num < MAX_NEIGHBOR_SIZE) - { + while (nei_num < MAX_NEIGHBOR_SIZE) { thiswp.neighbors[nei_num].num = 0; thiswp.neighbors[nei_num].forceJumpTo = 0; nei_num++; } - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2120,8 +1834,7 @@ int LoadPathData(const char *filename) i_cv = 0; i++; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2133,8 +1846,7 @@ int LoadPathData(const char *filename) i_cv = 0; i++; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2147,8 +1859,7 @@ int LoadPathData(const char *filename) i++; i++; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2160,8 +1871,7 @@ int LoadPathData(const char *filename) i_cv = 0; i++; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2173,8 +1883,7 @@ int LoadPathData(const char *filename) i_cv = 0; i++; - while (fileString[i] != ')') - { + while (fileString[i] != ')') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2185,11 +1894,9 @@ int LoadPathData(const char *filename) i += 4; - while (fileString[i] != '}') - { + while (fileString[i] != '}') { i_cv = 0; - while (fileString[i] != ' ' && fileString[i] != '-') - { + while (fileString[i] != ' ' && fileString[i] != '-') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2198,23 +1905,19 @@ int LoadPathData(const char *filename) thiswp.neighbors[thiswp.neighbornum].num = atoi(currentVar); - if (fileString[i] == '-') - { + if (fileString[i] == '-') { i_cv = 0; i++; - while (fileString[i] != ' ') - { + while (fileString[i] != ' ') { currentVar[i_cv] = fileString[i]; i_cv++; i++; } currentVar[i_cv] = '\0'; - thiswp.neighbors[thiswp.neighbornum].forceJumpTo = 999; //atoi(currentVar); //FJSR - } - else - { + thiswp.neighbors[thiswp.neighbornum].forceJumpTo = 999; // atoi(currentVar); //FJSR + } else { thiswp.neighbors[thiswp.neighbornum].forceJumpTo = 0; } @@ -2227,8 +1930,7 @@ int LoadPathData(const char *filename) i++; i++; - while (fileString[i] != '\n') - { + while (fileString[i] != '\n') { currentVar[i_cv] = fileString[i]; i_cv++; i++; @@ -2241,29 +1943,27 @@ int LoadPathData(const char *filename) i++; } - B_TempFree(524288); //fileString - B_TempFree(2048); //currentVar + B_TempFree(524288); // fileString + B_TempFree(2048); // currentVar trap->FS_Close(f); - if (level.gametype == GT_SIEGE) - { + if (level.gametype == GT_SIEGE) { CalculateSiegeGoals(); } CalculateWeightGoals(); - //calculate weights for idle activity goals when - //the bot has absolutely nothing else to do + // calculate weights for idle activity goals when + // the bot has absolutely nothing else to do CalculateJumpRoutes(); - //Look at jump points and mark them as requiring - //force jumping as needed + // Look at jump points and mark them as requiring + // force jumping as needed return 1; } -void FlagObjects(void) -{ +void FlagObjects(void) { int i = 0, bestindex = 0, found = 0; float bestdist = 999999, tlen = 0; gentity_t *flag_red, *flag_blue, *ent; @@ -2280,23 +1980,17 @@ void FlagObjects(void) maxs[1] = 15; maxs[2] = 5; - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->classname) - { - if (!flag_red && strcmp(ent->classname, "team_CTF_redflag") == 0) - { + if (ent && ent->inuse && ent->classname) { + if (!flag_red && strcmp(ent->classname, "team_CTF_redflag") == 0) { flag_red = ent; - } - else if (!flag_blue && strcmp(ent->classname, "team_CTF_blueflag") == 0) - { + } else if (!flag_blue && strcmp(ent->classname, "team_CTF_blueflag") == 0) { flag_blue = ent; } - if (flag_red && flag_blue) - { + if (flag_red && flag_blue) { break; } } @@ -2306,37 +2000,30 @@ void FlagObjects(void) i = 0; - if (!flag_red || !flag_blue) - { + if (!flag_red || !flag_blue) { return; } - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { VectorSubtract(flag_red->s.pos.trBase, gWPArray[i]->origin, a); tlen = VectorLength(a); - if (tlen < bestdist) - { + if (tlen < bestdist) { trap->Trace(&tr, flag_red->s.pos.trBase, mins, maxs, gWPArray[i]->origin, flag_red->s.number, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == flag_red->s.number) - { + if (tr.fraction == 1 || tr.entityNum == flag_red->s.number) { bestdist = tlen; bestindex = i; found = 1; } } - } i++; } - if (found) - { + if (found) { gWPArray[bestindex]->flags |= WPFLAG_RED_FLAG; flagRed = gWPArray[bestindex]; oFlagRed = flagRed; @@ -2348,32 +2035,26 @@ void FlagObjects(void) found = 0; i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { VectorSubtract(flag_blue->s.pos.trBase, gWPArray[i]->origin, a); tlen = VectorLength(a); - if (tlen < bestdist) - { + if (tlen < bestdist) { trap->Trace(&tr, flag_blue->s.pos.trBase, mins, maxs, gWPArray[i]->origin, flag_blue->s.number, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == flag_blue->s.number) - { + if (tr.fraction == 1 || tr.entityNum == flag_blue->s.number) { bestdist = tlen; bestindex = i; found = 1; } } - } i++; } - if (found) - { + if (found) { gWPArray[bestindex]->flags |= WPFLAG_BLUE_FLAG; flagBlue = gWPArray[bestindex]; oFlagBlue = flagBlue; @@ -2381,8 +2062,7 @@ void FlagObjects(void) } } -int SavePathData(const char *filename) -{ +int SavePathData(const char *filename) { fileHandle_t f; char *fileString; char *storeString; @@ -2394,8 +2074,7 @@ int SavePathData(const char *filename) fileString = NULL; i = 0; - if (!gWPNum) - { + if (!gWPNum) { return 0; } @@ -2405,51 +2084,44 @@ int SavePathData(const char *filename) trap->FS_Open(routePath, &f, FS_WRITE); - B_TempFree(1024); //routePath + B_TempFree(1024); // routePath - if (!f) - { + if (!f) { trap->Print(S_COLOR_RED "ERROR: Could not open file to write path data\n"); return 0; } - if (!RepairPaths(qfalse)) //check if we can see all waypoints from the last. If not, try to branch over. + if (!RepairPaths(qfalse)) // check if we can see all waypoints from the last. If not, try to branch over. { trap->FS_Close(f); return 0; } - CalculatePaths(); //make everything nice and connected before saving + CalculatePaths(); // make everything nice and connected before saving - FlagObjects(); //currently only used for flagging waypoints nearest CTF flags + FlagObjects(); // currently only used for flagging waypoints nearest CTF flags fileString = (char *)B_TempAlloc(524288); storeString = (char *)B_TempAlloc(4096); - Com_sprintf(fileString, 524288, "%i %i %f (%f %f %f) { ", gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], gWPArray[i]->origin[1], gWPArray[i]->origin[2]); + Com_sprintf(fileString, 524288, "%i %i %f (%f %f %f) { ", gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], + gWPArray[i]->origin[1], gWPArray[i]->origin[2]); n = 0; - while (n < gWPArray[i]->neighbornum) - { - if (gWPArray[i]->neighbors[n].forceJumpTo) - { + while (n < gWPArray[i]->neighbornum) { + if (gWPArray[i]->neighbors[n].forceJumpTo) { Com_sprintf(storeString, 4096, "%s%i-%i ", storeString, gWPArray[i]->neighbors[n].num, gWPArray[i]->neighbors[n].forceJumpTo); - } - else - { + } else { Com_sprintf(storeString, 4096, "%s%i ", storeString, gWPArray[i]->neighbors[n].num); } n++; } - if (gWPArray[i+1] && gWPArray[i+1]->inuse && gWPArray[i+1]->index) - { - VectorSubtract(gWPArray[i]->origin, gWPArray[i+1]->origin, a); + if (gWPArray[i + 1] && gWPArray[i + 1]->inuse && gWPArray[i + 1]->index) { + VectorSubtract(gWPArray[i]->origin, gWPArray[i + 1]->origin, a); flLen = VectorLength(a); - } - else - { + } else { flLen = 0; } @@ -2459,33 +2131,27 @@ int SavePathData(const char *filename) i++; - while (i < gWPNum) - { - //sprintf(fileString, "%s%i %i %f (%f %f %f) { ", fileString, gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], gWPArray[i]->origin[1], gWPArray[i]->origin[2]); - Com_sprintf(storeString, 4096, "%i %i %f (%f %f %f) { ", gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], gWPArray[i]->origin[1], gWPArray[i]->origin[2]); + while (i < gWPNum) { + // sprintf(fileString, "%s%i %i %f (%f %f %f) { ", fileString, gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], + // gWPArray[i]->origin[1], gWPArray[i]->origin[2]); + Com_sprintf(storeString, 4096, "%i %i %f (%f %f %f) { ", gWPArray[i]->index, gWPArray[i]->flags, gWPArray[i]->weight, gWPArray[i]->origin[0], + gWPArray[i]->origin[1], gWPArray[i]->origin[2]); n = 0; - while (n < gWPArray[i]->neighbornum) - { - if (gWPArray[i]->neighbors[n].forceJumpTo) - { + while (n < gWPArray[i]->neighbornum) { + if (gWPArray[i]->neighbors[n].forceJumpTo) { Com_sprintf(storeString, 4096, "%s%i-%i ", storeString, gWPArray[i]->neighbors[n].num, gWPArray[i]->neighbors[n].forceJumpTo); - } - else - { + } else { Com_sprintf(storeString, 4096, "%s%i ", storeString, gWPArray[i]->neighbors[n].num); } n++; } - if (gWPArray[i+1] && gWPArray[i+1]->inuse && gWPArray[i+1]->index) - { - VectorSubtract(gWPArray[i]->origin, gWPArray[i+1]->origin, a); + if (gWPArray[i + 1] && gWPArray[i + 1]->inuse && gWPArray[i + 1]->index) { + VectorSubtract(gWPArray[i]->origin, gWPArray[i + 1]->origin, a); flLen = VectorLength(a); - } - else - { + } else { flLen = 0; } @@ -2500,8 +2166,8 @@ int SavePathData(const char *filename) trap->FS_Write(fileString, strlen(fileString), f); - B_TempFree(524288); //fileString - B_TempFree(4096); //storeString + B_TempFree(524288); // fileString + B_TempFree(4096); // storeString trap->FS_Close(f); @@ -2514,21 +2180,18 @@ int SavePathData(const char *filename) int gSpawnPointNum = 0; gentity_t *gSpawnPoints[MAX_SPAWNPOINT_ARRAY]; -int G_NearestNodeToPoint(vec3_t point) -{ //gets the node on the entire grid which is nearest to the specified coordinates. +int G_NearestNodeToPoint(vec3_t point) { // gets the node on the entire grid which is nearest to the specified coordinates. vec3_t vSub; int bestIndex = -1; int i = 0; float bestDist = 0; float testDist = 0; - while (i < nodenum) - { + while (i < nodenum) { VectorSubtract(nodetable[i].origin, point, vSub); testDist = VectorLength(vSub); - if (bestIndex == -1) - { + if (bestIndex == -1) { bestIndex = i; bestDist = testDist; @@ -2536,8 +2199,7 @@ int G_NearestNodeToPoint(vec3_t point) continue; } - if (testDist < bestDist) - { + if (testDist < bestDist) { bestIndex = i; bestDist = testDist; } @@ -2547,12 +2209,10 @@ int G_NearestNodeToPoint(vec3_t point) return bestIndex; } -void G_NodeClearForNext(void) -{ //reset nodes for the next trail connection. +void G_NodeClearForNext(void) { // reset nodes for the next trail connection. int i = 0; - while (i < nodenum) - { + while (i < nodenum) { nodetable[i].flags = 0; nodetable[i].weight = 99999; @@ -2560,28 +2220,21 @@ void G_NodeClearForNext(void) } } -void G_NodeClearFlags(void) -{ //only clear out flags so nodes can be reused. +void G_NodeClearFlags(void) { // only clear out flags so nodes can be reused. int i = 0; - while (i < nodenum) - { + while (i < nodenum) { nodetable[i].flags = 0; i++; } } -int G_NodeMatchingXY(float x, float y) -{ //just get the first unflagged node with the matching x,y coordinates. +int G_NodeMatchingXY(float x, float y) { // just get the first unflagged node with the matching x,y coordinates. int i = 0; - while (i < nodenum) - { - if (nodetable[i].origin[0] == x && - nodetable[i].origin[1] == y && - !nodetable[i].flags) - { + while (i < nodenum) { + if (nodetable[i].origin[0] == x && nodetable[i].origin[1] == y && !nodetable[i].flags) { return i; } @@ -2591,21 +2244,15 @@ int G_NodeMatchingXY(float x, float y) return -1; } -int G_NodeMatchingXY_BA(int x, int y, int final) -{ //return the node with the lowest weight that matches the specified x,y coordinates. +int G_NodeMatchingXY_BA(int x, int y, int final) { // return the node with the lowest weight that matches the specified x,y coordinates. int i = 0; int bestindex = -1; float bestWeight = 9999; - while (i < nodenum) - { - if ((int)nodetable[i].origin[0] == x && - (int)nodetable[i].origin[1] == y && - !nodetable[i].flags && - ((nodetable[i].weight < bestWeight) || (i == final))) - { - if (i == final) - { + while (i < nodenum) { + if ((int)nodetable[i].origin[0] == x && (int)nodetable[i].origin[1] == y && !nodetable[i].flags && + ((nodetable[i].weight < bestWeight) || (i == final))) { + if (i == final) { return i; } bestindex = i; @@ -2618,9 +2265,8 @@ int G_NodeMatchingXY_BA(int x, int y, int final) return bestindex; } -int G_RecursiveConnection(int start, int end, int weight, qboolean traceCheck, float baseHeight) -{ - int indexDirections[4]; //0 == down, 1 == up, 2 == left, 3 == right +int G_RecursiveConnection(int start, int end, int weight, qboolean traceCheck, float baseHeight) { + int indexDirections[4]; // 0 == down, 1 == up, 2 == left, 3 == right int recursiveIndex = -1; int i = 0; int passWeight = weight; @@ -2651,39 +2297,31 @@ int G_RecursiveConnection(int start, int end, int weight, qboolean traceCheck, f indexDirections[3] = G_NodeMatchingXY(givenXY[0], givenXY[1]); i = 0; - while (i < 4) - { - if (indexDirections[i] == end) - { //we've connected all the way to the destination. + while (i < 4) { + if (indexDirections[i] == end) { // we've connected all the way to the destination. return indexDirections[i]; } - if (indexDirections[i] != -1 && nodetable[indexDirections[i]].flags) - { //this point is already used, so it's not valid. + if (indexDirections[i] != -1 && nodetable[indexDirections[i]].flags) { // this point is already used, so it's not valid. indexDirections[i] = -1; - } - else if (indexDirections[i] != -1) - { //otherwise mark it as used. + } else if (indexDirections[i] != -1) { // otherwise mark it as used. nodetable[indexDirections[i]].flags = 1; } - if (indexDirections[i] != -1 && traceCheck) - { //if we care about trace visibility between nodes, perform the check and mark as not valid if the trace isn't clear. + if (indexDirections[i] != -1 && + traceCheck) { // if we care about trace visibility between nodes, perform the check and mark as not valid if the trace isn't clear. trap->Trace(&tr, nodetable[start].origin, NULL, NULL, nodetable[indexDirections[i]].origin, ENTITYNUM_NONE, CONTENTS_SOLID, qfalse, 0, 0); - if (tr.fraction != 1) - { + if (tr.fraction != 1) { indexDirections[i] = -1; } } - if (indexDirections[i] != -1) - { //it's still valid, so keep connecting via this point. + if (indexDirections[i] != -1) { // it's still valid, so keep connecting via this point. recursiveIndex = G_RecursiveConnection(indexDirections[i], end, passWeight, traceCheck, baseHeight); } - if (recursiveIndex != -1) - { //the result of the recursive check was valid, so return it. + if (recursiveIndex != -1) { // the result of the recursive check was valid, so return it. return recursiveIndex; } @@ -2694,25 +2332,22 @@ int G_RecursiveConnection(int start, int end, int weight, qboolean traceCheck, f } #ifdef DEBUG_NODE_FILE -void G_DebugNodeFile() -{ +void G_DebugNodeFile() { fileHandle_t f; int i = 0; float placeX; char fileString[131072]; - gentity_t *terrain = G_Find( NULL, FOFS(classname), "terrain" ); + gentity_t *terrain = G_Find(NULL, FOFS(classname), "terrain"); fileString[0] = 0; placeX = terrain->r.absmin[0]; - while (i < nodenum) - { + while (i < nodenum) { strcat(fileString, va("%i-%f ", i, nodetable[i].weight)); placeX += DEFAULT_GRID_SPACING; - if (placeX >= terrain->r.absmax[0]) - { + if (placeX >= terrain->r.absmax[0]) { strcat(fileString, "\n"); placeX = terrain->r.absmin[0]; } @@ -2732,8 +2367,7 @@ void G_DebugNodeFile() #define ALLOWABLE_DEBUG_FILE_SIZE 1048576 -void CreateAsciiTableRepresentation() -{ //Draw a text grid of the entire waypoint array (useful for debugging final waypoint placement) +void CreateAsciiTableRepresentation() { // Draw a text grid of the entire waypoint array (useful for debugging final waypoint placement) fileHandle_t f; int i = 0; int sP = 0; @@ -2743,92 +2377,72 @@ void CreateAsciiTableRepresentation() int oldY; char fileString[ALLOWABLE_DEBUG_FILE_SIZE]; char bChr = '+'; - gentity_t *terrain = G_Find( NULL, FOFS(classname), "terrain" ); + gentity_t *terrain = G_Find(NULL, FOFS(classname), "terrain"); placeX = terrain->r.absmin[0]; placeY = terrain->r.absmin[1]; - oldX = placeX-1; - oldY = placeY-1; + oldX = placeX - 1; + oldY = placeY - 1; - while (placeY < terrain->r.absmax[1]) - { - while (placeX < terrain->r.absmax[0]) - { + while (placeY < terrain->r.absmax[1]) { + while (placeX < terrain->r.absmax[0]) { qboolean gotit = qfalse; i = 0; - while (i < gWPNum) - { + while (i < gWPNum) { if (((int)gWPArray[i]->origin[0] <= placeX && (int)gWPArray[i]->origin[0] > oldX) && - ((int)gWPArray[i]->origin[1] <= placeY && (int)gWPArray[i]->origin[1] > oldY)) - { + ((int)gWPArray[i]->origin[1] <= placeY && (int)gWPArray[i]->origin[1] > oldY)) { gotit = qtrue; break; } i++; } - if (gotit) - { - if (gWPArray[i]->flags & WPFLAG_ONEWAY_FWD) - { + if (gotit) { + if (gWPArray[i]->flags & WPFLAG_ONEWAY_FWD) { bChr = 'F'; - } - else if (gWPArray[i]->flags & WPFLAG_ONEWAY_BACK) - { + } else if (gWPArray[i]->flags & WPFLAG_ONEWAY_BACK) { bChr = 'B'; - } - else - { + } else { bChr = '+'; } - if (gWPArray[i]->index < 10) - { + if (gWPArray[i]->index < 10) { fileString[sP] = bChr; - fileString[sP+1] = '0'; - fileString[sP+2] = '0'; - fileString[sP+3] = va("%i", gWPArray[i]->index)[0]; - } - else if (gWPArray[i]->index < 100) - { + fileString[sP + 1] = '0'; + fileString[sP + 2] = '0'; + fileString[sP + 3] = va("%i", gWPArray[i]->index)[0]; + } else if (gWPArray[i]->index < 100) { char *vastore = va("%i", gWPArray[i]->index); fileString[sP] = bChr; - fileString[sP+1] = '0'; - fileString[sP+2] = vastore[0]; - fileString[sP+3] = vastore[1]; - } - else if (gWPArray[i]->index < 1000) - { + fileString[sP + 1] = '0'; + fileString[sP + 2] = vastore[0]; + fileString[sP + 3] = vastore[1]; + } else if (gWPArray[i]->index < 1000) { char *vastore = va("%i", gWPArray[i]->index); fileString[sP] = bChr; - fileString[sP+1] = vastore[0]; - fileString[sP+2] = vastore[1]; - fileString[sP+3] = vastore[2]; - } - else - { + fileString[sP + 1] = vastore[0]; + fileString[sP + 2] = vastore[1]; + fileString[sP + 3] = vastore[2]; + } else { fileString[sP] = 'X'; - fileString[sP+1] = 'X'; - fileString[sP+2] = 'X'; - fileString[sP+3] = 'X'; + fileString[sP + 1] = 'X'; + fileString[sP + 2] = 'X'; + fileString[sP + 3] = 'X'; } - } - else - { + } else { fileString[sP] = '-'; - fileString[sP+1] = '-'; - fileString[sP+2] = '-'; - fileString[sP+3] = '-'; + fileString[sP + 1] = '-'; + fileString[sP + 2] = '-'; + fileString[sP + 3] = '-'; } sP += 4; - if (sP >= ALLOWABLE_DEBUG_FILE_SIZE-16) - { + if (sP >= ALLOWABLE_DEBUG_FILE_SIZE - 16) { break; } oldX = placeX; @@ -2836,12 +2450,11 @@ void CreateAsciiTableRepresentation() } placeX = terrain->r.absmin[0]; - oldX = placeX-1; + oldX = placeX - 1; fileString[sP] = '\n'; sP++; - if (sP >= ALLOWABLE_DEBUG_FILE_SIZE-16) - { + if (sP >= ALLOWABLE_DEBUG_FILE_SIZE - 16) { break; } @@ -2856,8 +2469,7 @@ void CreateAsciiTableRepresentation() trap->FS_Close(f); } -void CreateAsciiNodeTableRepresentation(int start, int end) -{ //draw a text grid of a single node path, from point A to Z. +void CreateAsciiNodeTableRepresentation(int start, int end) { // draw a text grid of a single node path, from point A to Z. fileHandle_t f; int i = 0; int sP = 0; @@ -2866,93 +2478,74 @@ void CreateAsciiNodeTableRepresentation(int start, int end) int oldX; int oldY; char fileString[ALLOWABLE_DEBUG_FILE_SIZE]; - gentity_t *terrain = G_Find( NULL, FOFS(classname), "terrain" ); + gentity_t *terrain = G_Find(NULL, FOFS(classname), "terrain"); placeX = terrain->r.absmin[0]; placeY = terrain->r.absmin[1]; - oldX = placeX-1; - oldY = placeY-1; + oldX = placeX - 1; + oldY = placeY - 1; - while (placeY < terrain->r.absmax[1]) - { - while (placeX < terrain->r.absmax[0]) - { + while (placeY < terrain->r.absmax[1]) { + while (placeX < terrain->r.absmax[0]) { qboolean gotit = qfalse; i = 0; - while (i < nodenum) - { + while (i < nodenum) { if (((int)nodetable[i].origin[0] <= placeX && (int)nodetable[i].origin[0] > oldX) && - ((int)nodetable[i].origin[1] <= placeY && (int)nodetable[i].origin[1] > oldY)) - { + ((int)nodetable[i].origin[1] <= placeY && (int)nodetable[i].origin[1] > oldY)) { gotit = qtrue; break; } i++; } - if (gotit) - { - if (i == start) - { //beginning of the node trail + if (gotit) { + if (i == start) { // beginning of the node trail fileString[sP] = 'A'; - fileString[sP+1] = 'A'; - fileString[sP+2] = 'A'; - fileString[sP+3] = 'A'; - } - else if (i == end) - { //destination of the node trail + fileString[sP + 1] = 'A'; + fileString[sP + 2] = 'A'; + fileString[sP + 3] = 'A'; + } else if (i == end) { // destination of the node trail fileString[sP] = 'Z'; - fileString[sP+1] = 'Z'; - fileString[sP+2] = 'Z'; - fileString[sP+3] = 'Z'; - } - else if (nodetable[i].weight < 10) - { + fileString[sP + 1] = 'Z'; + fileString[sP + 2] = 'Z'; + fileString[sP + 3] = 'Z'; + } else if (nodetable[i].weight < 10) { fileString[sP] = '+'; - fileString[sP+1] = '0'; - fileString[sP+2] = '0'; - fileString[sP+3] = va("%f", nodetable[i].weight)[0]; - } - else if (nodetable[i].weight < 100) - { + fileString[sP + 1] = '0'; + fileString[sP + 2] = '0'; + fileString[sP + 3] = va("%f", nodetable[i].weight)[0]; + } else if (nodetable[i].weight < 100) { char *vastore = va("%f", nodetable[i].weight); fileString[sP] = '+'; - fileString[sP+1] = '0'; - fileString[sP+2] = vastore[0]; - fileString[sP+3] = vastore[1]; - } - else if (nodetable[i].weight < 1000) - { + fileString[sP + 1] = '0'; + fileString[sP + 2] = vastore[0]; + fileString[sP + 3] = vastore[1]; + } else if (nodetable[i].weight < 1000) { char *vastore = va("%f", nodetable[i].weight); fileString[sP] = '+'; - fileString[sP+1] = vastore[0]; - fileString[sP+2] = vastore[1]; - fileString[sP+3] = vastore[2]; - } - else - { + fileString[sP + 1] = vastore[0]; + fileString[sP + 2] = vastore[1]; + fileString[sP + 3] = vastore[2]; + } else { fileString[sP] = 'X'; - fileString[sP+1] = 'X'; - fileString[sP+2] = 'X'; - fileString[sP+3] = 'X'; + fileString[sP + 1] = 'X'; + fileString[sP + 2] = 'X'; + fileString[sP + 3] = 'X'; } - } - else - { + } else { fileString[sP] = '-'; - fileString[sP+1] = '-'; - fileString[sP+2] = '-'; - fileString[sP+3] = '-'; + fileString[sP + 1] = '-'; + fileString[sP + 2] = '-'; + fileString[sP + 3] = '-'; } sP += 4; - if (sP >= ALLOWABLE_DEBUG_FILE_SIZE-16) - { + if (sP >= ALLOWABLE_DEBUG_FILE_SIZE - 16) { break; } oldX = placeX; @@ -2960,12 +2553,11 @@ void CreateAsciiNodeTableRepresentation(int start, int end) } placeX = terrain->r.absmin[0]; - oldX = placeX-1; + oldX = placeX - 1; fileString[sP] = '\n'; sP++; - if (sP >= ALLOWABLE_DEBUG_FILE_SIZE-16) - { + if (sP >= ALLOWABLE_DEBUG_FILE_SIZE - 16) { break; } @@ -2981,9 +2573,9 @@ void CreateAsciiNodeTableRepresentation(int start, int end) } #endif -qboolean G_BackwardAttachment(int start, int finalDestination, int insertAfter) -{ //After creating a node path between 2 points, this function links the 2 points with actual waypoint data. - int indexDirections[4]; //0 == down, 1 == up, 2 == left, 3 == right +qboolean G_BackwardAttachment(int start, int finalDestination, + int insertAfter) { // After creating a node path between 2 points, this function links the 2 points with actual waypoint data. + int indexDirections[4]; // 0 == down, 1 == up, 2 == left, 3 == right int i = 0; int lowestWeight = 9999; int desiredIndex = -1; @@ -3009,19 +2601,16 @@ qboolean G_BackwardAttachment(int start, int finalDestination, int insertAfter) givenXY[1] += DEFAULT_GRID_SPACING; indexDirections[3] = G_NodeMatchingXY_BA(givenXY[0], givenXY[1], finalDestination); - while (i < 4) - { - if (indexDirections[i] != -1) - { - if (indexDirections[i] == finalDestination) - { //hooray, we've found the original point and linked all the way back to it. + while (i < 4) { + if (indexDirections[i] != -1) { + if (indexDirections[i] == finalDestination) { // hooray, we've found the original point and linked all the way back to it. CreateNewWP_InsertUnder(nodetable[start].origin, 0, insertAfter); CreateNewWP_InsertUnder(nodetable[indexDirections[i]].origin, 0, insertAfter); return qtrue; } - if (nodetable[indexDirections[i]].weight < lowestWeight && nodetable[indexDirections[i]].weight && !nodetable[indexDirections[i]].flags /*&& (nodetable[indexDirections[i]].origin[2]-64 < nodetable[start].origin[2])*/) - { + if (nodetable[indexDirections[i]].weight < lowestWeight && nodetable[indexDirections[i]].weight && + !nodetable[indexDirections[i]].flags /*&& (nodetable[indexDirections[i]].origin[2]-64 < nodetable[start].origin[2])*/) { desiredIndex = indexDirections[i]; lowestWeight = nodetable[indexDirections[i]].weight; } @@ -3029,14 +2618,10 @@ qboolean G_BackwardAttachment(int start, int finalDestination, int insertAfter) i++; } - if (desiredIndex != -1) - { //Create a waypoint here, and then recursively call this function for the next neighbor with the lowest weight. - if (gWPNum < 3900) - { + if (desiredIndex != -1) { // Create a waypoint here, and then recursively call this function for the next neighbor with the lowest weight. + if (gWPNum < 3900) { CreateNewWP_InsertUnder(nodetable[start].origin, 0, insertAfter); - } - else - { + } else { return qfalse; } @@ -3047,13 +2632,11 @@ qboolean G_BackwardAttachment(int start, int finalDestination, int insertAfter) return qfalse; } - #ifdef _DEBUG #define PATH_TIME_DEBUG #endif -void G_RMGPathing(void) -{ //Generate waypoint information on-the-fly for the random mission. +void G_RMGPathing(void) { // Generate waypoint information on-the-fly for the random mission. float placeX, placeY, placeZ; int i = 0; int gridSpacing = DEFAULT_GRID_SPACING; @@ -3065,10 +2648,9 @@ void G_RMGPathing(void) #endif vec3_t downVec, trMins, trMaxs; trace_t tr; - gentity_t *terrain = G_Find( NULL, FOFS(classname), "terrain" ); + gentity_t *terrain = G_Find(NULL, FOFS(classname), "terrain"); - if (!terrain || !terrain->inuse || terrain->s.eType != ET_TERRAIN) - { + if (!terrain || !terrain->inuse || terrain->s.eType != ET_TERRAIN) { trap->Print("Error: RMG with no terrain!\n"); return; } @@ -3085,21 +2667,17 @@ void G_RMGPathing(void) placeX = terrain->r.absmin[0]; placeY = terrain->r.absmin[1]; - placeZ = terrain->r.absmax[2]-400; + placeZ = terrain->r.absmax[2] - 400; - //skim through the entirety of the terrain limits and drop nodes, removing - //nodes that start in solid or fall too high on the terrain. - while (placeY < terrain->r.absmax[1]) - { - if (nodenum >= MAX_NODETABLE_SIZE) - { + // skim through the entirety of the terrain limits and drop nodes, removing + // nodes that start in solid or fall too high on the terrain. + while (placeY < terrain->r.absmax[1]) { + if (nodenum >= MAX_NODETABLE_SIZE) { break; } - while (placeX < terrain->r.absmax[0]) - { - if (nodenum >= MAX_NODETABLE_SIZE) - { + while (placeX < terrain->r.absmax[0]) { + if (nodenum >= MAX_NODETABLE_SIZE) { break; } @@ -3111,13 +2689,11 @@ void G_RMGPathing(void) downVec[2] -= 3000; trap->Trace(&tr, nodetable[nodenum].origin, trMins, trMaxs, downVec, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); - if ((tr.entityNum >= ENTITYNUM_WORLD || g_entities[tr.entityNum].s.eType == ET_TERRAIN) && tr.endpos[2] < terrain->r.absmin[2]+750) - { //only drop nodes on terrain directly + if ((tr.entityNum >= ENTITYNUM_WORLD || g_entities[tr.entityNum].s.eType == ET_TERRAIN) && + tr.endpos[2] < terrain->r.absmin[2] + 750) { // only drop nodes on terrain directly VectorCopy(tr.endpos, nodetable[nodenum].origin); nodenum++; - } - else - { + } else { VectorClear(nodetable[nodenum].origin); } @@ -3130,49 +2706,45 @@ void G_RMGPathing(void) G_NodeClearForNext(); - //The grid has been placed down, now use it to connect the points in the level. - while (i < gSpawnPointNum-1) - { - if (!gSpawnPoints[i] || !gSpawnPoints[i]->inuse || !gSpawnPoints[i+1] || !gSpawnPoints[i+1]->inuse) - { + // The grid has been placed down, now use it to connect the points in the level. + while (i < gSpawnPointNum - 1) { + if (!gSpawnPoints[i] || !gSpawnPoints[i]->inuse || !gSpawnPoints[i + 1] || !gSpawnPoints[i + 1]->inuse) { i++; continue; } nearestIndex = G_NearestNodeToPoint(gSpawnPoints[i]->s.origin); - nearestIndexForNext = G_NearestNodeToPoint(gSpawnPoints[i+1]->s.origin); + nearestIndexForNext = G_NearestNodeToPoint(gSpawnPoints[i + 1]->s.origin); - if (nearestIndex == -1 || nearestIndexForNext == -1) - { //Looks like there is no grid data near one of the points. Ideally, this will never happen. + if (nearestIndex == -1 || nearestIndexForNext == -1) { // Looks like there is no grid data near one of the points. Ideally, this will never happen. i++; continue; } - if (nearestIndex == nearestIndexForNext) - { //Two spawn points on top of each other? We don't need to do both points, keep going until the next differs. + if (nearestIndex == nearestIndexForNext) { // Two spawn points on top of each other? We don't need to do both points, keep going until the next differs. i++; continue; } - //So, nearestIndex is now the node for the spawn point we're on, and nearestIndexForNext is the - //node we want to get to from here. + // So, nearestIndex is now the node for the spawn point we're on, and nearestIndexForNext is the + // node we want to get to from here. - //For now I am going to branch out mindlessly, but I will probably want to use some sort of A* algorithm - //here to lessen the time taken. - if (G_RecursiveConnection(nearestIndex, nearestIndexForNext, 0, qtrue, terrain->r.absmin[2]) != nearestIndexForNext) - { //failed to branch to where we want. Oh well, try it without trace checks. + // For now I am going to branch out mindlessly, but I will probably want to use some sort of A* algorithm + // here to lessen the time taken. + if (G_RecursiveConnection(nearestIndex, nearestIndexForNext, 0, qtrue, terrain->r.absmin[2]) != + nearestIndexForNext) { // failed to branch to where we want. Oh well, try it without trace checks. G_NodeClearForNext(); - if (G_RecursiveConnection(nearestIndex, nearestIndexForNext, 0, qfalse, terrain->r.absmin[2]) != nearestIndexForNext) - { //still failed somehow. Just disregard this point. + if (G_RecursiveConnection(nearestIndex, nearestIndexForNext, 0, qfalse, terrain->r.absmin[2]) != + nearestIndexForNext) { // still failed somehow. Just disregard this point. G_NodeClearForNext(); i++; continue; } } - //Now our node array is set up so that highest reasonable weight is the destination node, and 2 is next to the original index, - //so trace back to that point. + // Now our node array is set up so that highest reasonable weight is the destination node, and 2 is next to the original index, + // so trace back to that point. G_NodeClearFlags(); #ifdef ASCII_ART_DEBUG @@ -3180,20 +2752,16 @@ void G_RMGPathing(void) CreateAsciiNodeTableRepresentation(nearestIndex, nearestIndexForNext); #endif #endif - if (G_BackwardAttachment(nearestIndexForNext, nearestIndex, gWPNum-1)) - { //successfully connected the trail from nearestIndex to nearestIndexForNext - if (gSpawnPoints[i+1]->inuse && gSpawnPoints[i+1]->item && - gSpawnPoints[i+1]->item->giType == IT_TEAM) - { //This point is actually a CTF flag. - if (gSpawnPoints[i+1]->item->giTag == PW_REDFLAG || gSpawnPoints[i+1]->item->giTag == PW_BLUEFLAG) - { //Place a waypoint on the flag next in the trail, so the nearest grid point will link to it. - CreateNewWP_InsertUnder(gSpawnPoints[i+1]->s.origin, WPFLAG_NEVERONEWAY, gWPNum-1); + if (G_BackwardAttachment(nearestIndexForNext, nearestIndex, gWPNum - 1)) { // successfully connected the trail from nearestIndex to nearestIndexForNext + if (gSpawnPoints[i + 1]->inuse && gSpawnPoints[i + 1]->item && gSpawnPoints[i + 1]->item->giType == IT_TEAM) { // This point is actually a CTF flag. + if (gSpawnPoints[i + 1]->item->giTag == PW_REDFLAG || + gSpawnPoints[i + 1]->item->giTag == + PW_BLUEFLAG) { // Place a waypoint on the flag next in the trail, so the nearest grid point will link to it. + CreateNewWP_InsertUnder(gSpawnPoints[i + 1]->s.origin, WPFLAG_NEVERONEWAY, gWPNum - 1); } } - } - else - { + } else { break; } @@ -3205,7 +2773,7 @@ void G_RMGPathing(void) i++; } - RepairPaths(qtrue); //this has different behaviour for RMG and will just flag all points one way that don't trace to each other. + RepairPaths(qtrue); // this has different behaviour for RMG and will just flag all points one way that don't trace to each other. #ifdef PATH_TIME_DEBUG endTime = trap->Milliseconds(); @@ -3218,31 +2786,25 @@ void G_RMGPathing(void) #endif } -void BeginAutoPathRoutine(void) -{ //Called for RMG levels. +void BeginAutoPathRoutine(void) { // Called for RMG levels. int i = 0; gentity_t *ent = NULL; vec3_t v; gSpawnPointNum = 0; - CreateNewWP(vec3_origin, 0); //create a dummy waypoint to insert under + CreateNewWP(vec3_origin, 0); // create a dummy waypoint to insert under - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->classname && ent->classname[0] && !Q_stricmp(ent->classname, "info_player_deathmatch")) - { - if (ent->s.origin[2] < 1280) - { //h4x + if (ent && ent->inuse && ent->classname && ent->classname[0] && !Q_stricmp(ent->classname, "info_player_deathmatch")) { + if (ent->s.origin[2] < 1280) { // h4x gSpawnPoints[gSpawnPointNum] = ent; gSpawnPointNum++; } - } - else if (ent && ent->inuse && ent->item && ent->item->giType == IT_TEAM && - (ent->item->giTag == PW_REDFLAG || ent->item->giTag == PW_BLUEFLAG)) - { //also make it path to flags in CTF. + } else if (ent && ent->inuse && ent->item && ent->item->giType == IT_TEAM && + (ent->item->giTag == PW_REDFLAG || ent->item->giTag == PW_BLUEFLAG)) { // also make it path to flags in CTF. gSpawnPoints[gSpawnPointNum] = ent; gSpawnPointNum++; } @@ -3250,97 +2812,77 @@ void BeginAutoPathRoutine(void) i++; } - if (gSpawnPointNum < 1) - { + if (gSpawnPointNum < 1) { return; } G_RMGPathing(); - //rww - Using a faster in-engine version because we're having to wait for this stuff to get done as opposed to just saving it once. + // rww - Using a faster in-engine version because we're having to wait for this stuff to get done as opposed to just saving it once. trap->BotUpdateWaypoints(gWPNum, gWPArray); trap->BotCalculatePaths(RMG.integer); - //CalculatePaths(); //make everything nice and connected - + // CalculatePaths(); //make everything nice and connected - FlagObjects(); //currently only used for flagging waypoints nearest CTF flags + FlagObjects(); // currently only used for flagging waypoints nearest CTF flags i = 0; - while (i < gWPNum-1) - { //disttonext is normally set on save, and when a file is loaded. For RMG we must do it after calc'ing. - VectorSubtract(gWPArray[i]->origin, gWPArray[i+1]->origin, v); + while (i < gWPNum - 1) { // disttonext is normally set on save, and when a file is loaded. For RMG we must do it after calc'ing. + VectorSubtract(gWPArray[i]->origin, gWPArray[i + 1]->origin, v); gWPArray[i]->disttonext = VectorLength(v); i++; } - RemoveWP(); //remove the dummy point at the end of the trail + RemoveWP(); // remove the dummy point at the end of the trail } extern vmCvar_t bot_normgpath; -void LoadPath_ThisLevel(void) -{ - vmCvar_t mapname; - int i = 0; - gentity_t *ent = NULL; +void LoadPath_ThisLevel(void) { + vmCvar_t mapname; + int i = 0; + gentity_t *ent = NULL; - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); - if (RMG.integer) - { //If RMG, generate the path on-the-fly + if (RMG.integer) { // If RMG, generate the path on-the-fly trap->Cvar_Register(&bot_normgpath, "bot_normgpath", "1", CVAR_CHEAT); - //note: This is disabled for now as I'm using standard bot nav - //on premade terrain levels. + // note: This is disabled for now as I'm using standard bot nav + // on premade terrain levels. - if (!bot_normgpath.integer) - { //autopath the random map + if (!bot_normgpath.integer) { // autopath the random map BeginAutoPathRoutine(); - } - else - { //try loading standard nav data + } else { // try loading standard nav data LoadPathData(mapname.string); } gLevelFlags |= LEVELFLAG_NOPOINTPREDICTION; - } - else - { - if (LoadPathData(mapname.string) == 2) - { - //enter "edit" mode if cheats enabled? + } else { + if (LoadPathData(mapname.string) == 2) { + // enter "edit" mode if cheats enabled? } } trap->Cvar_Update(&bot_wp_edit); - if (bot_wp_edit.value) - { + if (bot_wp_edit.value) { gBotEdit = 1; - } - else - { + } else { gBotEdit = 0; } - //set the flag entities - while (i < level.num_entities) - { + // set the flag entities + while (i < level.num_entities) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->classname) - { - if (!eFlagRed && strcmp(ent->classname, "team_CTF_redflag") == 0) - { + if (ent && ent->inuse && ent->classname) { + if (!eFlagRed && strcmp(ent->classname, "team_CTF_redflag") == 0) { eFlagRed = ent; - } - else if (!eFlagBlue && strcmp(ent->classname, "team_CTF_blueflag") == 0) - { + } else if (!eFlagBlue && strcmp(ent->classname, "team_CTF_blueflag") == 0) { eFlagBlue = ent; } - if (eFlagRed && eFlagBlue) - { + if (eFlagRed && eFlagBlue) { break; } } @@ -3349,29 +2891,25 @@ void LoadPath_ThisLevel(void) } } -gentity_t *GetClosestSpawn(gentity_t *ent) -{ - gentity_t *spawn; - gentity_t *closestSpawn = NULL; - float closestDist = -1; - int i = MAX_CLIENTS; +gentity_t *GetClosestSpawn(gentity_t *ent) { + gentity_t *spawn; + gentity_t *closestSpawn = NULL; + float closestDist = -1; + int i = MAX_CLIENTS; spawn = NULL; - while (i < level.num_entities) - { + while (i < level.num_entities) { spawn = &g_entities[i]; - if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch")) ) - { + if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch"))) { float checkDist; vec3_t vSub; VectorSubtract(ent->client->ps.origin, spawn->r.currentOrigin, vSub); checkDist = VectorLength(vSub); - if (closestDist == -1 || checkDist < closestDist) - { + if (closestDist == -1 || checkDist < closestDist) { closestSpawn = spawn; closestDist = checkDist; } @@ -3383,20 +2921,17 @@ gentity_t *GetClosestSpawn(gentity_t *ent) return closestSpawn; } -gentity_t *GetNextSpawnInIndex(gentity_t *currentSpawn) -{ - gentity_t *spawn; - gentity_t *nextSpawn = NULL; - int i = currentSpawn->s.number+1; +gentity_t *GetNextSpawnInIndex(gentity_t *currentSpawn) { + gentity_t *spawn; + gentity_t *nextSpawn = NULL; + int i = currentSpawn->s.number + 1; spawn = NULL; - while (i < level.num_entities) - { + while (i < level.num_entities) { spawn = &g_entities[i]; - if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch")) ) - { + if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch"))) { nextSpawn = spawn; break; } @@ -3404,16 +2939,13 @@ gentity_t *GetNextSpawnInIndex(gentity_t *currentSpawn) i++; } - if (!nextSpawn) - { //loop back around to 0 + if (!nextSpawn) { // loop back around to 0 i = MAX_CLIENTS; - while (i < level.num_entities) - { + while (i < level.num_entities) { spawn = &g_entities[i]; - if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch")) ) - { + if (spawn && spawn->inuse && (!Q_stricmp(spawn->classname, "info_player_start") || !Q_stricmp(spawn->classname, "info_player_deathmatch"))) { nextSpawn = spawn; break; } @@ -3425,15 +2957,13 @@ gentity_t *GetNextSpawnInIndex(gentity_t *currentSpawn) return nextSpawn; } -int AcceptBotCommand(char *cmd, gentity_t *pl) -{ +int AcceptBotCommand(char *cmd, gentity_t *pl) { int OptionalArgument, i; int FlagsFromArgument; char *OptionalSArgument, *RequiredSArgument; vmCvar_t mapname; - if (!gBotEdit) - { + if (!gBotEdit) { return 0; } @@ -3443,17 +2973,17 @@ int AcceptBotCommand(char *cmd, gentity_t *pl) OptionalSArgument = NULL; RequiredSArgument = NULL; - //if a waypoint editing related command is issued, bots will deactivate. - //once bot_wp_save is issued and the trail is recalculated, bots will activate again. + // if a waypoint editing related command is issued, bots will deactivate. + // once bot_wp_save is issued and the trail is recalculated, bots will activate again. - if (!pl || !pl->client) - { + if (!pl || !pl->client) { return 0; } - if (Q_stricmp (cmd, "bot_wp_cmdlist") == 0) //lists all the bot waypoint commands. + if (Q_stricmp(cmd, "bot_wp_cmdlist") == 0) // lists all the bot waypoint commands. { - trap->Print(S_COLOR_YELLOW "bot_wp_add" S_COLOR_WHITE " - Add a waypoint (optional int parameter will insert the point after the specified waypoint index in a trail)\n\n"); + trap->Print(S_COLOR_YELLOW "bot_wp_add" S_COLOR_WHITE + " - Add a waypoint (optional int parameter will insert the point after the specified waypoint index in a trail)\n\n"); trap->Print(S_COLOR_YELLOW "bot_wp_rem" S_COLOR_WHITE " - Remove a waypoint (removes last unless waypoint index is specified as a parameter)\n\n"); trap->Print(S_COLOR_YELLOW "bot_wp_addflagged" S_COLOR_WHITE " - Same as wp_add, but adds a flagged point (type bot_wp_addflagged for help)\n\n"); trap->Print(S_COLOR_YELLOW "bot_wp_switchflags" S_COLOR_WHITE " - Switches flags on an existing waypoint (type bot_wp_switchflags for help)\n\n"); @@ -3464,256 +2994,185 @@ int AcceptBotCommand(char *cmd, gentity_t *pl) return 1; } - if (Q_stricmp (cmd, "bot_wp_add") == 0) - { + if (Q_stricmp(cmd, "bot_wp_add") == 0) { gDeactivated = 1; - OptionalSArgument = ConcatArgs( 1 ); + OptionalSArgument = ConcatArgs(1); - if (OptionalSArgument) - { + if (OptionalSArgument) { OptionalArgument = atoi(OptionalSArgument); } - if (OptionalSArgument && OptionalSArgument[0]) - { + if (OptionalSArgument && OptionalSArgument[0]) { CreateNewWP_InTrail(pl->client->ps.origin, 0, OptionalArgument); - } - else - { + } else { CreateNewWP(pl->client->ps.origin, 0); } return 1; } - if (Q_stricmp (cmd, "bot_wp_rem") == 0) - { + if (Q_stricmp(cmd, "bot_wp_rem") == 0) { gDeactivated = 1; - OptionalSArgument = ConcatArgs( 1 ); + OptionalSArgument = ConcatArgs(1); - if (OptionalSArgument) - { + if (OptionalSArgument) { OptionalArgument = atoi(OptionalSArgument); } - if (OptionalSArgument && OptionalSArgument[0]) - { + if (OptionalSArgument && OptionalSArgument[0]) { RemoveWP_InTrail(OptionalArgument); - } - else - { + } else { RemoveWP(); } return 1; } - if (Q_stricmp (cmd, "bot_wp_tele") == 0) - { + if (Q_stricmp(cmd, "bot_wp_tele") == 0) { gDeactivated = 1; - OptionalSArgument = ConcatArgs( 1 ); + OptionalSArgument = ConcatArgs(1); - if (OptionalSArgument) - { + if (OptionalSArgument) { OptionalArgument = atoi(OptionalSArgument); } - if (OptionalSArgument && OptionalSArgument[0]) - { + if (OptionalSArgument && OptionalSArgument[0]) { TeleportToWP(pl, OptionalArgument); - } - else - { + } else { trap->Print(S_COLOR_YELLOW "You didn't specify an index. Assuming last.\n"); - TeleportToWP(pl, gWPNum-1); + TeleportToWP(pl, gWPNum - 1); } return 1; } - if (Q_stricmp (cmd, "bot_wp_spawntele") == 0) - { + if (Q_stricmp(cmd, "bot_wp_spawntele") == 0) { gentity_t *closestSpawn = GetClosestSpawn(pl); - if (!closestSpawn) - { //There should always be a spawn point.. + if (!closestSpawn) { // There should always be a spawn point.. return 1; } closestSpawn = GetNextSpawnInIndex(closestSpawn); - if (closestSpawn) - { + if (closestSpawn) { VectorCopy(closestSpawn->r.currentOrigin, pl->client->ps.origin); } return 1; } - if (Q_stricmp (cmd, "bot_wp_addflagged") == 0) - { + if (Q_stricmp(cmd, "bot_wp_addflagged") == 0) { gDeactivated = 1; - RequiredSArgument = ConcatArgs( 1 ); + RequiredSArgument = ConcatArgs(1); - if (!RequiredSArgument || !RequiredSArgument[0]) - { - trap->Print(S_COLOR_YELLOW "Flag string needed for bot_wp_addflagged\nj - Jump point\nd - Duck point\nc - Snipe or camp standing\nf - Wait for func\nm - Do not move to when func is under\ns - Snipe or camp\nx - Oneway, forward\ny - Oneway, back\ng - Mission goal\nn - No visibility\nExample (for a point the bot would jump at, and reverse on when traveling a trail backwards):\nbot_wp_addflagged jx\n"); + if (!RequiredSArgument || !RequiredSArgument[0]) { + trap->Print(S_COLOR_YELLOW + "Flag string needed for bot_wp_addflagged\nj - Jump point\nd - Duck point\nc - Snipe or camp standing\nf - Wait for func\nm - Do not " + "move to when func is under\ns - Snipe or camp\nx - Oneway, forward\ny - Oneway, back\ng - Mission goal\nn - No visibility\nExample " + "(for a point the bot would jump at, and reverse on when traveling a trail backwards):\nbot_wp_addflagged jx\n"); return 1; } - while (RequiredSArgument[i]) - { - if (RequiredSArgument[i] == 'j') - { + while (RequiredSArgument[i]) { + if (RequiredSArgument[i] == 'j') { FlagsFromArgument |= WPFLAG_JUMP; - } - else if (RequiredSArgument[i] == 'd') - { + } else if (RequiredSArgument[i] == 'd') { FlagsFromArgument |= WPFLAG_DUCK; - } - else if (RequiredSArgument[i] == 'c') - { + } else if (RequiredSArgument[i] == 'c') { FlagsFromArgument |= WPFLAG_SNIPEORCAMPSTAND; - } - else if (RequiredSArgument[i] == 'f') - { + } else if (RequiredSArgument[i] == 'f') { FlagsFromArgument |= WPFLAG_WAITFORFUNC; - } - else if (RequiredSArgument[i] == 's') - { + } else if (RequiredSArgument[i] == 's') { FlagsFromArgument |= WPFLAG_SNIPEORCAMP; - } - else if (RequiredSArgument[i] == 'x') - { + } else if (RequiredSArgument[i] == 'x') { FlagsFromArgument |= WPFLAG_ONEWAY_FWD; - } - else if (RequiredSArgument[i] == 'y') - { + } else if (RequiredSArgument[i] == 'y') { FlagsFromArgument |= WPFLAG_ONEWAY_BACK; - } - else if (RequiredSArgument[i] == 'g') - { + } else if (RequiredSArgument[i] == 'g') { FlagsFromArgument |= WPFLAG_GOALPOINT; - } - else if (RequiredSArgument[i] == 'n') - { + } else if (RequiredSArgument[i] == 'n') { FlagsFromArgument |= WPFLAG_NOVIS; - } - else if (RequiredSArgument[i] == 'm') - { + } else if (RequiredSArgument[i] == 'm') { FlagsFromArgument |= WPFLAG_NOMOVEFUNC; } i++; } - OptionalSArgument = ConcatArgs( 2 ); + OptionalSArgument = ConcatArgs(2); - if (OptionalSArgument) - { + if (OptionalSArgument) { OptionalArgument = atoi(OptionalSArgument); } - if (OptionalSArgument && OptionalSArgument[0]) - { + if (OptionalSArgument && OptionalSArgument[0]) { CreateNewWP_InTrail(pl->client->ps.origin, FlagsFromArgument, OptionalArgument); - } - else - { + } else { CreateNewWP(pl->client->ps.origin, FlagsFromArgument); } return 1; } - if (Q_stricmp (cmd, "bot_wp_switchflags") == 0) - { + if (Q_stricmp(cmd, "bot_wp_switchflags") == 0) { gDeactivated = 1; - RequiredSArgument = ConcatArgs( 1 ); + RequiredSArgument = ConcatArgs(1); - if (!RequiredSArgument || !RequiredSArgument[0]) - { - trap->Print(S_COLOR_YELLOW "Flag string needed for bot_wp_switchflags\nType bot_wp_addflagged for a list of flags and their corresponding characters, or use 0 for no flags.\nSyntax: bot_wp_switchflags \n"); + if (!RequiredSArgument || !RequiredSArgument[0]) { + trap->Print(S_COLOR_YELLOW "Flag string needed for bot_wp_switchflags\nType bot_wp_addflagged for a list of flags and their corresponding " + "characters, or use 0 for no flags.\nSyntax: bot_wp_switchflags \n"); return 1; } - while (RequiredSArgument[i]) - { - if (RequiredSArgument[i] == 'j') - { + while (RequiredSArgument[i]) { + if (RequiredSArgument[i] == 'j') { FlagsFromArgument |= WPFLAG_JUMP; - } - else if (RequiredSArgument[i] == 'd') - { + } else if (RequiredSArgument[i] == 'd') { FlagsFromArgument |= WPFLAG_DUCK; - } - else if (RequiredSArgument[i] == 'c') - { + } else if (RequiredSArgument[i] == 'c') { FlagsFromArgument |= WPFLAG_SNIPEORCAMPSTAND; - } - else if (RequiredSArgument[i] == 'f') - { + } else if (RequiredSArgument[i] == 'f') { FlagsFromArgument |= WPFLAG_WAITFORFUNC; - } - else if (RequiredSArgument[i] == 's') - { + } else if (RequiredSArgument[i] == 's') { FlagsFromArgument |= WPFLAG_SNIPEORCAMP; - } - else if (RequiredSArgument[i] == 'x') - { + } else if (RequiredSArgument[i] == 'x') { FlagsFromArgument |= WPFLAG_ONEWAY_FWD; - } - else if (RequiredSArgument[i] == 'y') - { + } else if (RequiredSArgument[i] == 'y') { FlagsFromArgument |= WPFLAG_ONEWAY_BACK; - } - else if (RequiredSArgument[i] == 'g') - { + } else if (RequiredSArgument[i] == 'g') { FlagsFromArgument |= WPFLAG_GOALPOINT; - } - else if (RequiredSArgument[i] == 'n') - { + } else if (RequiredSArgument[i] == 'n') { FlagsFromArgument |= WPFLAG_NOVIS; - } - else if (RequiredSArgument[i] == 'm') - { + } else if (RequiredSArgument[i] == 'm') { FlagsFromArgument |= WPFLAG_NOMOVEFUNC; } i++; } - OptionalSArgument = ConcatArgs( 2 ); + OptionalSArgument = ConcatArgs(2); - if (OptionalSArgument) - { + if (OptionalSArgument) { OptionalArgument = atoi(OptionalSArgument); } - if (OptionalSArgument && OptionalSArgument[0]) - { + if (OptionalSArgument && OptionalSArgument[0]) { WPFlagsModify(OptionalArgument, FlagsFromArgument); - } - else - { + } else { trap->Print(S_COLOR_YELLOW "Waypoint number (to modify) needed for bot_wp_switchflags\nSyntax: bot_wp_switchflags \n"); } return 1; } - if (Q_stricmp (cmd, "bot_wp_killoneways") == 0) - { + if (Q_stricmp(cmd, "bot_wp_killoneways") == 0) { i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { - if (gWPArray[i]->flags & WPFLAG_ONEWAY_FWD) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { + if (gWPArray[i]->flags & WPFLAG_ONEWAY_FWD) { gWPArray[i]->flags &= ~WPFLAG_ONEWAY_FWD; } - if (gWPArray[i]->flags & WPFLAG_ONEWAY_BACK) - { + if (gWPArray[i]->flags & WPFLAG_ONEWAY_BACK) { gWPArray[i]->flags &= ~WPFLAG_ONEWAY_BACK; } } @@ -3724,10 +3183,9 @@ int AcceptBotCommand(char *cmd, gentity_t *pl) return 1; } - if (Q_stricmp (cmd, "bot_wp_save") == 0) - { + if (Q_stricmp(cmd, "bot_wp_save") == 0) { gDeactivated = 0; - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); SavePathData(mapname.string); return 1; } diff --git a/codemp/game/bg_g2_utils.c b/codemp/game/bg_g2_utils.c index f8e6739a95..ca1a48eaca 100644 --- a/codemp/game/bg_g2_utils.c +++ b/codemp/game/bg_g2_utils.c @@ -28,116 +28,97 @@ along with this program; if not, see . #include "bg_public.h" #if defined(_GAME) - #include "g_local.h" +#include "g_local.h" #elif defined(_CGAME) - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #endif -void BG_AttachToRancor( void *ghoul2, float rancYaw, vec3_t rancOrigin, int time, qhandle_t *modelList, vec3_t modelScale, qboolean inMouth, vec3_t out_origin, vec3_t out_angles, matrix3_t out_axis ) -{ - mdxaBone_t boltMatrix; +void BG_AttachToRancor(void *ghoul2, float rancYaw, vec3_t rancOrigin, int time, qhandle_t *modelList, vec3_t modelScale, qboolean inMouth, vec3_t out_origin, + vec3_t out_angles, matrix3_t out_axis) { + mdxaBone_t boltMatrix; int boltIndex; vec3_t rancAngles; vec3_t temp_angles; // Getting the bolt here - if ( inMouth ) - {//in mouth - #if defined(_GAME) + if (inMouth) { // in mouth +#if defined(_GAME) boltIndex = trap->G2API_AddBolt(ghoul2, 0, "jaw_bone"); - #elif defined(_CGAME) +#elif defined(_CGAME) boltIndex = trap->G2API_AddBolt(ghoul2, 0, "jaw_bone"); - #endif - } - else - {//in right hand - #if defined(_GAME) +#endif + } else { // in right hand +#if defined(_GAME) boltIndex = trap->G2API_AddBolt(ghoul2, 0, "*r_hand"); - #elif defined(_CGAME) +#elif defined(_CGAME) boltIndex = trap->G2API_AddBolt(ghoul2, 0, "*r_hand"); - #endif +#endif } - VectorSet( rancAngles, 0, rancYaw, 0 ); + VectorSet(rancAngles, 0, rancYaw, 0); #if defined(_GAME) - trap->G2API_GetBoltMatrix( ghoul2, 0, boltIndex, &boltMatrix, rancAngles, rancOrigin, time, modelList, modelScale ); + trap->G2API_GetBoltMatrix(ghoul2, 0, boltIndex, &boltMatrix, rancAngles, rancOrigin, time, modelList, modelScale); #elif defined(_CGAME) - trap->G2API_GetBoltMatrix( ghoul2, 0, boltIndex, &boltMatrix, rancAngles, rancOrigin, time, modelList, modelScale ); + trap->G2API_GetBoltMatrix(ghoul2, 0, boltIndex, &boltMatrix, rancAngles, rancOrigin, time, modelList, modelScale); #endif // Storing ent position, bolt position, and bolt axis - if ( out_origin ) - { - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, out_origin ); + if (out_origin) { + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, out_origin); } - if ( out_axis ) - { - if ( inMouth ) - {//in mouth - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Z, out_axis[0] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, out_axis[1] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, out_axis[2] ); - } - else - {//in hand - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, out_axis[0] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_X, out_axis[1] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Z, out_axis[2] ); + if (out_axis) { + if (inMouth) { // in mouth + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, out_axis[0]); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, out_axis[1]); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, out_axis[2]); + } else { // in hand + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, out_axis[0]); + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, out_axis[1]); + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, out_axis[2]); } - //FIXME: this is messing up our axis and turning us inside-out? - if ( out_angles ) - { - vectoangles( out_axis[0], out_angles ); - vectoangles( out_axis[2], temp_angles ); + // FIXME: this is messing up our axis and turning us inside-out? + if (out_angles) { + vectoangles(out_axis[0], out_angles); + vectoangles(out_axis[2], temp_angles); out_angles[ROLL] = -temp_angles[PITCH]; } - } - else if ( out_angles ) - { + } else if (out_angles) { matrix3_t temp_axis; - if ( inMouth ) - {//in mouth - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Z, temp_axis[0] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, temp_axis[2] ); - } - else - {//in hand - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, temp_axis[0] ); - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Z, temp_axis[2] ); + if (inMouth) { // in mouth + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, temp_axis[0]); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, temp_axis[2]); + } else { // in hand + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, temp_axis[0]); + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, temp_axis[2]); } - //FIXME: this is messing up our axis and turning us inside-out? - vectoangles( temp_axis[0], out_angles ); - vectoangles( temp_axis[2], temp_angles ); + // FIXME: this is messing up our axis and turning us inside-out? + vectoangles(temp_axis[0], out_angles); + vectoangles(temp_axis[2], temp_angles); out_angles[ROLL] = -temp_angles[PITCH]; } } -#define MAX_VARIANTS 8 -qboolean BG_GetRootSurfNameWithVariant( void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize ) -{ +#define MAX_VARIANTS 8 +qboolean BG_GetRootSurfNameWithVariant(void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize) { #if defined(_GAME) - if ( !ghoul2 || !trap->G2API_GetSurfaceRenderStatus( ghoul2, 0, rootSurfName ) ) + if (!ghoul2 || !trap->G2API_GetSurfaceRenderStatus(ghoul2, 0, rootSurfName)) #elif defined(_CGAME) - if ( !ghoul2 || !trap->G2API_GetSurfaceRenderStatus( ghoul2, 0, rootSurfName ) ) + if (!ghoul2 || !trap->G2API_GetSurfaceRenderStatus(ghoul2, 0, rootSurfName)) #endif - {//see if the basic name without variants is on - Q_strncpyz( returnSurfName, rootSurfName, returnSize ); + { // see if the basic name without variants is on + Q_strncpyz(returnSurfName, rootSurfName, returnSize); return qtrue; - } - else - {//check variants + } else { // check variants int i; - for ( i = 0; i < MAX_VARIANTS; i++ ) - { - Com_sprintf( returnSurfName, returnSize, "%s%c", rootSurfName, 'a'+i ); - #if defined(_GAME) - if ( !trap->G2API_GetSurfaceRenderStatus( ghoul2, 0, returnSurfName ) ) - #elif defined(_CGAME) - if ( !trap->G2API_GetSurfaceRenderStatus( ghoul2, 0, returnSurfName ) ) - #endif + for (i = 0; i < MAX_VARIANTS; i++) { + Com_sprintf(returnSurfName, returnSize, "%s%c", rootSurfName, 'a' + i); +#if defined(_GAME) + if (!trap->G2API_GetSurfaceRenderStatus(ghoul2, 0, returnSurfName)) +#elif defined(_CGAME) + if (!trap->G2API_GetSurfaceRenderStatus(ghoul2, 0, returnSurfName)) +#endif { return qtrue; } } } - Q_strncpyz( returnSurfName, rootSurfName, returnSize ); + Q_strncpyz(returnSurfName, rootSurfName, returnSize); return qfalse; } - diff --git a/codemp/game/bg_misc.c b/codemp/game/bg_misc.c index b7fc7ba955..843663ad4f 100644 --- a/codemp/game/bg_misc.c +++ b/codemp/game/bg_misc.c @@ -27,307 +27,226 @@ along with this program; if not, see . #include "bg_public.h" #if defined(_GAME) - #include "g_local.h" +#include "g_local.h" #elif defined(_CGAME) - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif defined(UI_BUILD) - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif -const char *bgToggleableSurfaces[BG_NUM_TOGGLEABLE_SURFACES] = -{ - "l_arm_key", //0 - "torso_canister1", - "torso_canister2", - "torso_canister3", - "torso_tube1", - "torso_tube2", //5 - "torso_tube3", - "torso_tube4", - "torso_tube5", - "torso_tube6", - "r_arm", //10 - "l_arm", - "torso_shield", - "torso_galaktorso", - "torso_collar", -// "torso_eyes_mouth", //15 -// "torso_galakhead", -// "torso_galakface", -// "torso_antenna_base_cap", -// "torso_antenna", -// "l_arm_augment", //20 -// "l_arm_middle", -// "l_arm_wrist", -// "r_arm_middle", //yeah.. galak's surf stuff is no longer auto, sorry! need the space for vehicle surfs. - "r_wing1", //15 - "r_wing2", - "l_wing1", - "l_wing2", - "r_gear", - "l_gear", //20 - "nose", - "blah4", - "blah5", - "l_hand", - "r_hand", //25 - "helmet", - "head", - "head_concussion_charger", - "head_light_blaster_cann", //29 - NULL +const char *bgToggleableSurfaces[BG_NUM_TOGGLEABLE_SURFACES] = { + "l_arm_key", // 0 + "torso_canister1", "torso_canister2", "torso_canister3", "torso_tube1", + "torso_tube2", // 5 + "torso_tube3", "torso_tube4", "torso_tube5", "torso_tube6", + "r_arm", // 10 + "l_arm", "torso_shield", "torso_galaktorso", "torso_collar", + // "torso_eyes_mouth", //15 + // "torso_galakhead", + // "torso_galakface", + // "torso_antenna_base_cap", + // "torso_antenna", + // "l_arm_augment", //20 + // "l_arm_middle", + // "l_arm_wrist", + // "r_arm_middle", //yeah.. galak's surf stuff is no longer auto, sorry! need the space for vehicle surfs. + "r_wing1", // 15 + "r_wing2", "l_wing1", "l_wing2", "r_gear", + "l_gear", // 20 + "nose", "blah4", "blah5", "l_hand", + "r_hand", // 25 + "helmet", "head", "head_concussion_charger", + "head_light_blaster_cann", // 29 + NULL}; + +const int bgToggleableSurfaceDebris[BG_NUM_TOGGLEABLE_SURFACES] = {0, // 0 + 0, 0, 0, 0, + 0, // 5 + 0, 0, 0, 0, + 0, // 10 + 0, 0, 0, + 0, //>= 2 means it should create a flame trail when destroyed (for vehicles) + 3, // 15 + 5, // rwing2 + 4, + 6, // lwing2 + 0, // rgear + 0, // lgear //20 + 7, // nose + 0, // blah + 0, // blah + 0, + 0, // 25 + 0, 0, 0, + 0, // 29 + -1}; + +const char *bg_customSiegeSoundNames[MAX_CUSTOM_SIEGE_SOUNDS] = {"*att_attack", "*att_primary", "*att_second", "*def_guns", "*def_position", + "*def_primary", "*def_second", "*reply_coming", "*reply_go", "*reply_no", + "*reply_stay", "*reply_yes", "*req_assist", "*req_demo", "*req_hvy", + "*req_medic", "*req_sup", "*req_tech", "*spot_air", "*spot_defenses", + "*spot_emplaced", "*spot_sniper", "*spot_troops", "*tac_cover", "*tac_fallback", + "*tac_follow", "*tac_hold", "*tac_split", "*tac_together", NULL}; + +// rww - not putting @ in front of these because +// we don't need them in a cgame StringEd lookup. +// Let me know if this causes problems, pat. +char *forceMasteryLevels[NUM_FORCE_MASTERY_LEVELS] = { + "MASTERY0", //"Uninitiated", // FORCE_MASTERY_UNINITIATED, + "MASTERY1", //"Initiate", // FORCE_MASTERY_INITIATE, + "MASTERY2", //"Padawan", // FORCE_MASTERY_PADAWAN, + "MASTERY3", //"Jedi", // FORCE_MASTERY_JEDI, + "MASTERY4", //"Jedi Adept", // FORCE_MASTERY_JEDI_GUARDIAN, + "MASTERY5", //"Jedi Guardian", // FORCE_MASTERY_JEDI_ADEPT, + "MASTERY6", //"Jedi Knight", // FORCE_MASTERY_JEDI_KNIGHT, + "MASTERY7", //"Jedi Master" // FORCE_MASTERY_JEDI_MASTER, }; -const int bgToggleableSurfaceDebris[BG_NUM_TOGGLEABLE_SURFACES] = -{ - 0, //0 - 0, - 0, - 0, - 0, - 0, //5 - 0, - 0, - 0, - 0, - 0, //10 - 0, - 0, - 0, - 0, //>= 2 means it should create a flame trail when destroyed (for vehicles) - 3, //15 - 5, //rwing2 - 4, - 6, //lwing2 - 0, //rgear - 0, //lgear //20 - 7, //nose - 0, //blah - 0, //blah - 0, - 0, //25 - 0, - 0, - 0, - 0, //29 - -1 +int forceMasteryPoints[NUM_FORCE_MASTERY_LEVELS] = { + 0, // FORCE_MASTERY_UNINITIATED, + 5, // FORCE_MASTERY_INITIATE, + 10, // FORCE_MASTERY_PADAWAN, + 20, // FORCE_MASTERY_JEDI, + 30, // FORCE_MASTERY_JEDI_GUARDIAN, + 50, // FORCE_MASTERY_JEDI_ADEPT, + 75, // FORCE_MASTERY_JEDI_KNIGHT, + 100 // FORCE_MASTERY_JEDI_MASTER, }; -const char *bg_customSiegeSoundNames[MAX_CUSTOM_SIEGE_SOUNDS] = -{ - "*att_attack", - "*att_primary", - "*att_second", - "*def_guns", - "*def_position", - "*def_primary", - "*def_second", - "*reply_coming", - "*reply_go", - "*reply_no", - "*reply_stay", - "*reply_yes", - "*req_assist", - "*req_demo", - "*req_hvy", - "*req_medic", - "*req_sup", - "*req_tech", - "*spot_air", - "*spot_defenses", - "*spot_emplaced", - "*spot_sniper", - "*spot_troops", - "*tac_cover", - "*tac_fallback", - "*tac_follow", - "*tac_hold", - "*tac_split", - "*tac_together", - NULL +int bgForcePowerCost[NUM_FORCE_POWERS][NUM_FORCE_POWER_LEVELS] = // 0 == neutral + { + {0, 2, 4, 6}, // Heal // FP_HEAL + {0, 0, 2, 6}, // Jump //FP_LEVITATION,//hold/duration + {0, 2, 4, 6}, // Speed //FP_SPEED,//duration + {0, 1, 3, 6}, // Push //FP_PUSH,//hold/duration + {0, 1, 3, 6}, // Pull //FP_PULL,//hold/duration + {0, 4, 6, 8}, // Mind Trick //FP_TELEPATHY,//instant + {0, 1, 3, 6}, // Grip //FP_GRIP,//hold/duration + {0, 2, 5, 8}, // Lightning //FP_LIGHTNING,//hold/duration + {0, 4, 6, 8}, // Dark Rage //FP_RAGE,//duration + {0, 2, 5, 8}, // Protection //FP_PROTECT,//duration + {0, 1, 3, 6}, // Absorb //FP_ABSORB,//duration + {0, 1, 3, 6}, // Team Heal //FP_TEAM_HEAL,//instant + {0, 1, 3, 6}, // Team Force //FP_TEAM_FORCE,//instant + {0, 2, 4, 6}, // Drain //FP_DRAIN,//hold/duration + {0, 2, 5, 8}, // Sight //FP_SEE,//duration + {0, 1, 5, 8}, // Saber Attack //FP_SABER_OFFENSE, + {0, 1, 5, 8}, // Saber Defend //FP_SABER_DEFENSE, + {0, 4, 6, 8} // Saber Throw //FP_SABERTHROW, + // NUM_FORCE_POWERS }; -//rww - not putting @ in front of these because -//we don't need them in a cgame StringEd lookup. -//Let me know if this causes problems, pat. -char *forceMasteryLevels[NUM_FORCE_MASTERY_LEVELS] = -{ - "MASTERY0", //"Uninitiated", // FORCE_MASTERY_UNINITIATED, - "MASTERY1", //"Initiate", // FORCE_MASTERY_INITIATE, - "MASTERY2", //"Padawan", // FORCE_MASTERY_PADAWAN, - "MASTERY3", //"Jedi", // FORCE_MASTERY_JEDI, - "MASTERY4", //"Jedi Adept", // FORCE_MASTERY_JEDI_GUARDIAN, - "MASTERY5", //"Jedi Guardian", // FORCE_MASTERY_JEDI_ADEPT, - "MASTERY6", //"Jedi Knight", // FORCE_MASTERY_JEDI_KNIGHT, - "MASTERY7", //"Jedi Master" // FORCE_MASTERY_JEDI_MASTER, +int forcePowerSorted[NUM_FORCE_POWERS] = { // rww - always use this order when drawing force powers for any reason + FP_TELEPATHY, FP_HEAL, FP_ABSORB, FP_PROTECT, FP_TEAM_HEAL, FP_LEVITATION, FP_SPEED, FP_PUSH, FP_PULL, + FP_SEE, FP_LIGHTNING, FP_DRAIN, FP_RAGE, FP_GRIP, FP_TEAM_FORCE, FP_SABER_OFFENSE, FP_SABER_DEFENSE, FP_SABERTHROW}; + +int forcePowerDarkLight[NUM_FORCE_POWERS] = // 0 == neutral + { + // nothing should be usable at rank 0.. + FORCE_LIGHTSIDE, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + FORCE_LIGHTSIDE, // FP_TELEPATHY,//instant + FORCE_DARKSIDE, // FP_GRIP,//hold/duration + FORCE_DARKSIDE, // FP_LIGHTNING,//hold/duration + FORCE_DARKSIDE, // FP_RAGE,//duration + FORCE_LIGHTSIDE, // FP_PROTECT,//duration + FORCE_LIGHTSIDE, // FP_ABSORB,//duration + FORCE_LIGHTSIDE, // FP_TEAM_HEAL,//instant + FORCE_DARKSIDE, // FP_TEAM_FORCE,//instant + FORCE_DARKSIDE, // FP_DRAIN,//hold/duration + 0, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 0, // FP_SABER_DEFENSE, + 0 // FP_SABERTHROW, + // NUM_FORCE_POWERS }; -int forceMasteryPoints[NUM_FORCE_MASTERY_LEVELS] = -{ - 0, // FORCE_MASTERY_UNINITIATED, - 5, // FORCE_MASTERY_INITIATE, - 10, // FORCE_MASTERY_PADAWAN, - 20, // FORCE_MASTERY_JEDI, - 30, // FORCE_MASTERY_JEDI_GUARDIAN, - 50, // FORCE_MASTERY_JEDI_ADEPT, - 75, // FORCE_MASTERY_JEDI_KNIGHT, - 100 // FORCE_MASTERY_JEDI_MASTER, +int WeaponReadyAnim[WP_NUM_WEAPONS] = { + TORSO_DROPWEAP1, // WP_NONE, + + TORSO_WEAPONREADY3, // WP_STUN_BATON, + TORSO_WEAPONREADY3, // WP_MELEE, + BOTH_STAND2, // WP_SABER, + TORSO_WEAPONREADY2, // WP_BRYAR_PISTOL, + TORSO_WEAPONREADY3, // WP_BLASTER, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY4,//WP_DISRUPTOR, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY5,//WP_BOWCASTER, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY6,//WP_REPEATER, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY7,//WP_DEMP2, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY8,//WP_FLECHETTE, + TORSO_WEAPONREADY3, // TORSO_WEAPONREADY9,//WP_ROCKET_LAUNCHER, + TORSO_WEAPONREADY10, // WP_THERMAL, + TORSO_WEAPONREADY10, // TORSO_WEAPONREADY11,//WP_TRIP_MINE, + TORSO_WEAPONREADY10, // TORSO_WEAPONREADY12,//WP_DET_PACK, + TORSO_WEAPONREADY3, // WP_CONCUSSION + TORSO_WEAPONREADY2, // WP_BRYAR_OLD, + + // NOT VALID (e.g. should never really be used): + BOTH_STAND1, // WP_EMPLACED_GUN, + TORSO_WEAPONREADY1 // WP_TURRET, }; -int bgForcePowerCost[NUM_FORCE_POWERS][NUM_FORCE_POWER_LEVELS] = //0 == neutral -{ - { 0, 2, 4, 6 }, // Heal // FP_HEAL - { 0, 0, 2, 6 }, // Jump //FP_LEVITATION,//hold/duration - { 0, 2, 4, 6 }, // Speed //FP_SPEED,//duration - { 0, 1, 3, 6 }, // Push //FP_PUSH,//hold/duration - { 0, 1, 3, 6 }, // Pull //FP_PULL,//hold/duration - { 0, 4, 6, 8 }, // Mind Trick //FP_TELEPATHY,//instant - { 0, 1, 3, 6 }, // Grip //FP_GRIP,//hold/duration - { 0, 2, 5, 8 }, // Lightning //FP_LIGHTNING,//hold/duration - { 0, 4, 6, 8 }, // Dark Rage //FP_RAGE,//duration - { 0, 2, 5, 8 }, // Protection //FP_PROTECT,//duration - { 0, 1, 3, 6 }, // Absorb //FP_ABSORB,//duration - { 0, 1, 3, 6 }, // Team Heal //FP_TEAM_HEAL,//instant - { 0, 1, 3, 6 }, // Team Force //FP_TEAM_FORCE,//instant - { 0, 2, 4, 6 }, // Drain //FP_DRAIN,//hold/duration - { 0, 2, 5, 8 }, // Sight //FP_SEE,//duration - { 0, 1, 5, 8 }, // Saber Attack //FP_SABER_OFFENSE, - { 0, 1, 5, 8 }, // Saber Defend //FP_SABER_DEFENSE, - { 0, 4, 6, 8 } // Saber Throw //FP_SABERTHROW, - //NUM_FORCE_POWERS +int WeaponReadyLegsAnim[WP_NUM_WEAPONS] = { + BOTH_STAND1, // WP_NONE, + + BOTH_STAND1, // WP_STUN_BATON, + BOTH_STAND1, // WP_MELEE, + BOTH_STAND2, // WP_SABER, + BOTH_STAND1, // WP_BRYAR_PISTOL, + BOTH_STAND1, // WP_BLASTER, + BOTH_STAND1, // TORSO_WEAPONREADY4,//WP_DISRUPTOR, + BOTH_STAND1, // TORSO_WEAPONREADY5,//WP_BOWCASTER, + BOTH_STAND1, // TORSO_WEAPONREADY6,//WP_REPEATER, + BOTH_STAND1, // TORSO_WEAPONREADY7,//WP_DEMP2, + BOTH_STAND1, // TORSO_WEAPONREADY8,//WP_FLECHETTE, + BOTH_STAND1, // TORSO_WEAPONREADY9,//WP_ROCKET_LAUNCHER, + BOTH_STAND1, // WP_THERMAL, + BOTH_STAND1, // TORSO_WEAPONREADY11,//WP_TRIP_MINE, + BOTH_STAND1, // TORSO_WEAPONREADY12,//WP_DET_PACK, + BOTH_STAND1, // WP_CONCUSSION + BOTH_STAND1, // WP_BRYAR_OLD, + + // NOT VALID (e.g. should never really be used): + BOTH_STAND1, // WP_EMPLACED_GUN, + BOTH_STAND1 // WP_TURRET, }; -int forcePowerSorted[NUM_FORCE_POWERS] = -{ //rww - always use this order when drawing force powers for any reason - FP_TELEPATHY, - FP_HEAL, - FP_ABSORB, - FP_PROTECT, - FP_TEAM_HEAL, - FP_LEVITATION, - FP_SPEED, - FP_PUSH, - FP_PULL, - FP_SEE, - FP_LIGHTNING, - FP_DRAIN, - FP_RAGE, - FP_GRIP, - FP_TEAM_FORCE, - FP_SABER_OFFENSE, - FP_SABER_DEFENSE, - FP_SABERTHROW +int WeaponAttackAnim[WP_NUM_WEAPONS] = { + BOTH_ATTACK1, // WP_NONE, //(shouldn't happen) + + BOTH_ATTACK3, // WP_STUN_BATON, + BOTH_ATTACK3, // WP_MELEE, + BOTH_STAND2, // WP_SABER, //(has its own handling) + BOTH_ATTACK2, // WP_BRYAR_PISTOL, + BOTH_ATTACK3, // WP_BLASTER, + BOTH_ATTACK3, // BOTH_ATTACK4,//WP_DISRUPTOR, + BOTH_ATTACK3, // BOTH_ATTACK5,//WP_BOWCASTER, + BOTH_ATTACK3, // BOTH_ATTACK6,//WP_REPEATER, + BOTH_ATTACK3, // BOTH_ATTACK7,//WP_DEMP2, + BOTH_ATTACK3, // BOTH_ATTACK8,//WP_FLECHETTE, + BOTH_ATTACK3, // BOTH_ATTACK9,//WP_ROCKET_LAUNCHER, + BOTH_THERMAL_THROW, // WP_THERMAL, + BOTH_ATTACK3, // BOTH_ATTACK11,//WP_TRIP_MINE, + BOTH_ATTACK3, // BOTH_ATTACK12,//WP_DET_PACK, +#ifndef BASE_COMPAT + BOTH_ATTACK3, // WP_CONCUSSION, +#endif // BASE_COMPAT + BOTH_ATTACK2, // WP_BRYAR_OLD, + + // NOT VALID (e.g. should never really be used): + BOTH_STAND1, // WP_EMPLACED_GUN, + BOTH_ATTACK1 // WP_TURRET, }; -int forcePowerDarkLight[NUM_FORCE_POWERS] = //0 == neutral -{ //nothing should be usable at rank 0.. - FORCE_LIGHTSIDE,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - FORCE_LIGHTSIDE,//FP_TELEPATHY,//instant - FORCE_DARKSIDE,//FP_GRIP,//hold/duration - FORCE_DARKSIDE,//FP_LIGHTNING,//hold/duration - FORCE_DARKSIDE,//FP_RAGE,//duration - FORCE_LIGHTSIDE,//FP_PROTECT,//duration - FORCE_LIGHTSIDE,//FP_ABSORB,//duration - FORCE_LIGHTSIDE,//FP_TEAM_HEAL,//instant - FORCE_DARKSIDE,//FP_TEAM_FORCE,//instant - FORCE_DARKSIDE,//FP_DRAIN,//hold/duration - 0,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 0,//FP_SABER_DEFENSE, - 0//FP_SABERTHROW, - //NUM_FORCE_POWERS -}; - -int WeaponReadyAnim[WP_NUM_WEAPONS] = -{ - TORSO_DROPWEAP1,//WP_NONE, - - TORSO_WEAPONREADY3,//WP_STUN_BATON, - TORSO_WEAPONREADY3,//WP_MELEE, - BOTH_STAND2,//WP_SABER, - TORSO_WEAPONREADY2,//WP_BRYAR_PISTOL, - TORSO_WEAPONREADY3,//WP_BLASTER, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY4,//WP_DISRUPTOR, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY5,//WP_BOWCASTER, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY6,//WP_REPEATER, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY7,//WP_DEMP2, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY8,//WP_FLECHETTE, - TORSO_WEAPONREADY3,//TORSO_WEAPONREADY9,//WP_ROCKET_LAUNCHER, - TORSO_WEAPONREADY10,//WP_THERMAL, - TORSO_WEAPONREADY10,//TORSO_WEAPONREADY11,//WP_TRIP_MINE, - TORSO_WEAPONREADY10,//TORSO_WEAPONREADY12,//WP_DET_PACK, - TORSO_WEAPONREADY3,//WP_CONCUSSION - TORSO_WEAPONREADY2,//WP_BRYAR_OLD, - - //NOT VALID (e.g. should never really be used): - BOTH_STAND1,//WP_EMPLACED_GUN, - TORSO_WEAPONREADY1//WP_TURRET, -}; - -int WeaponReadyLegsAnim[WP_NUM_WEAPONS] = -{ - BOTH_STAND1,//WP_NONE, - - BOTH_STAND1,//WP_STUN_BATON, - BOTH_STAND1,//WP_MELEE, - BOTH_STAND2,//WP_SABER, - BOTH_STAND1,//WP_BRYAR_PISTOL, - BOTH_STAND1,//WP_BLASTER, - BOTH_STAND1,//TORSO_WEAPONREADY4,//WP_DISRUPTOR, - BOTH_STAND1,//TORSO_WEAPONREADY5,//WP_BOWCASTER, - BOTH_STAND1,//TORSO_WEAPONREADY6,//WP_REPEATER, - BOTH_STAND1,//TORSO_WEAPONREADY7,//WP_DEMP2, - BOTH_STAND1,//TORSO_WEAPONREADY8,//WP_FLECHETTE, - BOTH_STAND1,//TORSO_WEAPONREADY9,//WP_ROCKET_LAUNCHER, - BOTH_STAND1,//WP_THERMAL, - BOTH_STAND1,//TORSO_WEAPONREADY11,//WP_TRIP_MINE, - BOTH_STAND1,//TORSO_WEAPONREADY12,//WP_DET_PACK, - BOTH_STAND1,//WP_CONCUSSION - BOTH_STAND1,//WP_BRYAR_OLD, - - //NOT VALID (e.g. should never really be used): - BOTH_STAND1,//WP_EMPLACED_GUN, - BOTH_STAND1//WP_TURRET, -}; - -int WeaponAttackAnim[WP_NUM_WEAPONS] = -{ - BOTH_ATTACK1,//WP_NONE, //(shouldn't happen) - - BOTH_ATTACK3,//WP_STUN_BATON, - BOTH_ATTACK3,//WP_MELEE, - BOTH_STAND2,//WP_SABER, //(has its own handling) - BOTH_ATTACK2,//WP_BRYAR_PISTOL, - BOTH_ATTACK3,//WP_BLASTER, - BOTH_ATTACK3,//BOTH_ATTACK4,//WP_DISRUPTOR, - BOTH_ATTACK3,//BOTH_ATTACK5,//WP_BOWCASTER, - BOTH_ATTACK3,//BOTH_ATTACK6,//WP_REPEATER, - BOTH_ATTACK3,//BOTH_ATTACK7,//WP_DEMP2, - BOTH_ATTACK3,//BOTH_ATTACK8,//WP_FLECHETTE, - BOTH_ATTACK3,//BOTH_ATTACK9,//WP_ROCKET_LAUNCHER, - BOTH_THERMAL_THROW,//WP_THERMAL, - BOTH_ATTACK3,//BOTH_ATTACK11,//WP_TRIP_MINE, - BOTH_ATTACK3,//BOTH_ATTACK12,//WP_DET_PACK, - #ifndef BASE_COMPAT - BOTH_ATTACK3,//WP_CONCUSSION, - #endif // BASE_COMPAT - BOTH_ATTACK2,//WP_BRYAR_OLD, - - //NOT VALID (e.g. should never really be used): - BOTH_STAND1,//WP_EMPLACED_GUN, - BOTH_ATTACK1//WP_TURRET, -}; - -qboolean BG_FileExists( const char *fileName ) { - if ( fileName && fileName[0] ) { +qboolean BG_FileExists(const char *fileName) { + if (fileName && fileName[0]) { fileHandle_t f = NULL_FILE; - trap->FS_Open( fileName, &f, FS_READ ); - if ( f > 0 ) { - trap->FS_Close( f ); + trap->FS_Open(fileName, &f, FS_READ); + if (f > 0) { + trap->FS_Close(f); return qtrue; } } @@ -335,10 +254,8 @@ qboolean BG_FileExists( const char *fileName ) { } // given a boltmatrix, return in vec a normalised vector for the axis requested in flags -void BG_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, int flags, vec3_t vec) -{ - switch (flags) - { +void BG_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, int flags, vec3_t vec) { + switch (flags) { case ORIGIN: vec[0] = boltMatrix->matrix[0][3]; vec[1] = boltMatrix->matrix[1][3]; @@ -348,7 +265,7 @@ void BG_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, int flags, vec3_t vec) vec[0] = boltMatrix->matrix[0][1]; vec[1] = boltMatrix->matrix[1][1]; vec[2] = boltMatrix->matrix[2][1]; - break; + break; case POSITIVE_X: vec[0] = boltMatrix->matrix[0][0]; vec[1] = boltMatrix->matrix[1][0]; @@ -389,8 +306,7 @@ fpDisabled is actually only expected (needed) from the server, because the ui di force power selection anyway when force powers are disabled on the server. ================ */ -qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRank, qboolean freeSaber, int teamForce, int gametype, int fpDisabled) -{ +qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRank, qboolean freeSaber, int teamForce, int gametype, int fpDisabled) { char powerBuf[128]; char readBuf[128]; qboolean maintainsValidity = qtrue; @@ -404,57 +320,49 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan int final_Side; int final_Powers[NUM_FORCE_POWERS] = {0}; - if ( powerLen >= 128 ) - { //This should not happen. If it does, this is obviously a bogus string. - //They can have this string. Because I said so. - Q_strncpyz( powerBuf, DEFAULT_FORCEPOWERS, sizeof( powerBuf ) ); + if (powerLen >= 128) { // This should not happen. If it does, this is obviously a bogus string. + // They can have this string. Because I said so. + Q_strncpyz(powerBuf, DEFAULT_FORCEPOWERS, sizeof(powerBuf)); maintainsValidity = qfalse; - } - else - Q_strncpyz( powerBuf, powerOut, sizeof( powerBuf ) ); //copy it as the original + } else + Q_strncpyz(powerBuf, powerOut, sizeof(powerBuf)); // copy it as the original - //first of all, print the max rank into the string as the rank - Q_strncpyz( powerOut, va( "%i-", maxRank ), powerOutSize ); + // first of all, print the max rank into the string as the rank + Q_strncpyz(powerOut, va("%i-", maxRank), powerOutSize); - while (i < sizeof( powerBuf ) && powerBuf[i] && powerBuf[i] != '-') - { + while (i < sizeof(powerBuf) && powerBuf[i] && powerBuf[i] != '-') { i++; } i++; - while (i < sizeof( powerBuf ) && powerBuf[i] && powerBuf[i] != '-') - { + while (i < sizeof(powerBuf) && powerBuf[i] && powerBuf[i] != '-') { readBuf[c] = powerBuf[i]; c++; i++; } readBuf[c] = 0; i++; - //at this point, readBuf contains the intended side + // at this point, readBuf contains the intended side final_Side = atoi(readBuf); - if (final_Side != FORCE_LIGHTSIDE && - final_Side != FORCE_DARKSIDE) - { //Not a valid side. You will be dark. Because I said so. (this is something that should never actually happen unless you purposely feed in an invalid config) + if (final_Side != FORCE_LIGHTSIDE && final_Side != FORCE_DARKSIDE) { // Not a valid side. You will be dark. Because I said so. (this is something that + // should never actually happen unless you purposely feed in an invalid config) final_Side = FORCE_DARKSIDE; maintainsValidity = qfalse; } - if (teamForce) - { //If we are under force-aligned teams, make sure we're on the right side. - if (final_Side != teamForce) - { + if (teamForce) { // If we are under force-aligned teams, make sure we're on the right side. + if (final_Side != teamForce) { final_Side = teamForce; - //maintainsValidity = qfalse; - //Not doing this, for now. Let them join the team with their filtered powers. + // maintainsValidity = qfalse; + // Not doing this, for now. Let them join the team with their filtered powers. } } - //Now we have established a valid rank, and a valid side. - //Read the force powers in, and cut them down based on the various rules supplied. + // Now we have established a valid rank, and a valid side. + // Read the force powers in, and cut them down based on the various rules supplied. c = 0; - while (i < sizeof( powerBuf ) && powerBuf[i] && powerBuf[i] != '\n' && powerBuf[i] != '\r' - && powerBuf[i] >= '0' && powerBuf[i] <= '3' && c < NUM_FORCE_POWERS) - { + while (i < sizeof(powerBuf) && powerBuf[i] && powerBuf[i] != '\n' && powerBuf[i] != '\r' && powerBuf[i] >= '0' && powerBuf[i] <= '3' && + c < NUM_FORCE_POWERS) { readBuf[0] = powerBuf[i]; readBuf[1] = 0; final_Powers[c] = atoi(readBuf); @@ -462,51 +370,38 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan i++; } - //final_Powers now contains all the stuff from the string - //Set the maximum allowed points used based on the max rank level, and count the points actually used. + // final_Powers now contains all the stuff from the string + // Set the maximum allowed points used based on the max rank level, and count the points actually used. allowedPoints = forceMasteryPoints[maxRank]; i = 0; - while (i < NUM_FORCE_POWERS) - { //if this power doesn't match the side we're on, then 0 it now. - if (final_Powers[i] && - forcePowerDarkLight[i] && - forcePowerDarkLight[i] != final_Side) - { + while (i < NUM_FORCE_POWERS) { // if this power doesn't match the side we're on, then 0 it now. + if (final_Powers[i] && forcePowerDarkLight[i] && forcePowerDarkLight[i] != final_Side) { final_Powers[i] = 0; - //This is only likely to happen with g_forceBasedTeams. Let it slide. + // This is only likely to happen with g_forceBasedTeams. Let it slide. } - if ( final_Powers[i] && - (fpDisabled & (1 << i)) ) - { //if this power is disabled on the server via said server option, then we don't get it. + if (final_Powers[i] && (fpDisabled & (1 << i))) { // if this power is disabled on the server via said server option, then we don't get it. final_Powers[i] = 0; } i++; } - if (gametype < GT_TEAM) - { //don't bother with team powers then + if (gametype < GT_TEAM) { // don't bother with team powers then final_Powers[FP_TEAM_HEAL] = 0; final_Powers[FP_TEAM_FORCE] = 0; } usedPoints = 0; i = 0; - while (i < NUM_FORCE_POWERS) - { - countDown = Com_Clampi( 0, NUM_FORCE_POWER_LEVELS, final_Powers[i] ); + while (i < NUM_FORCE_POWERS) { + countDown = Com_Clampi(0, NUM_FORCE_POWER_LEVELS, final_Powers[i]); - while (countDown > 0) - { + while (countDown > 0) { usedPoints += bgForcePowerCost[i][countDown]; //[fp index][fp level] - //if this is jump, or we have a free saber and it's offense or defense, take the level back down on level 1 - if ( countDown == 1 && - ((i == FP_LEVITATION) || - (i == FP_SABER_OFFENSE && freeSaber) || - (i == FP_SABER_DEFENSE && freeSaber)) ) - { + // if this is jump, or we have a free saber and it's offense or defense, take the level back down on level 1 + if (countDown == 1 && ((i == FP_LEVITATION) || (i == FP_SABER_OFFENSE && freeSaber) || (i == FP_SABER_DEFENSE && freeSaber))) { usedPoints -= bgForcePowerCost[i][countDown]; } countDown--; @@ -515,66 +410,49 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan i++; } - if (usedPoints > allowedPoints) - { //Time to do the fancy stuff. (meaning, slowly cut parts off while taking a guess at what is most or least important in the config) + if (usedPoints > + allowedPoints) { // Time to do the fancy stuff. (meaning, slowly cut parts off while taking a guess at what is most or least important in the config) int attemptedCycles = 0; int powerCycle = 2; int minPow = 0; - if (freeSaber) - { + if (freeSaber) { minPow = 1; } maintainsValidity = qfalse; - while (usedPoints > allowedPoints) - { + while (usedPoints > allowedPoints) { c = 0; - while (c < NUM_FORCE_POWERS && usedPoints > allowedPoints) - { - if (final_Powers[c] && final_Powers[c] < powerCycle) - { //kill in order of lowest powers, because the higher powers are probably more important + while (c < NUM_FORCE_POWERS && usedPoints > allowedPoints) { + if (final_Powers[c] && final_Powers[c] < powerCycle) { // kill in order of lowest powers, because the higher powers are probably more important if (c == FP_SABER_OFFENSE && - (final_Powers[FP_SABER_DEFENSE] > minPow || final_Powers[FP_SABERTHROW] > 0)) - { //if we're on saber attack, only suck it down if we have no def or throw either - int whichOne = FP_SABERTHROW; //first try throw + (final_Powers[FP_SABER_DEFENSE] > minPow || + final_Powers[FP_SABERTHROW] > 0)) { // if we're on saber attack, only suck it down if we have no def or throw either + int whichOne = FP_SABERTHROW; // first try throw - if (!final_Powers[whichOne]) - { - whichOne = FP_SABER_DEFENSE; //if no throw, drain defense + if (!final_Powers[whichOne]) { + whichOne = FP_SABER_DEFENSE; // if no throw, drain defense } - while (final_Powers[whichOne] > 0 && usedPoints > allowedPoints) - { - if ( final_Powers[whichOne] > 1 || - ( (whichOne != FP_SABER_OFFENSE || !freeSaber) && - (whichOne != FP_SABER_DEFENSE || !freeSaber) ) ) - { //don't take attack or defend down on level 1 still, if it's free + while (final_Powers[whichOne] > 0 && usedPoints > allowedPoints) { + if (final_Powers[whichOne] > 1 || + ((whichOne != FP_SABER_OFFENSE || !freeSaber) && + (whichOne != FP_SABER_DEFENSE || !freeSaber))) { // don't take attack or defend down on level 1 still, if it's free usedPoints -= bgForcePowerCost[whichOne][final_Powers[whichOne]]; final_Powers[whichOne]--; - } - else - { + } else { break; } } - } - else - { - while (final_Powers[c] > 0 && usedPoints > allowedPoints) - { - if ( final_Powers[c] > 1 || - ((c != FP_LEVITATION) && - (c != FP_SABER_OFFENSE || !freeSaber) && - (c != FP_SABER_DEFENSE || !freeSaber)) ) - { + } else { + while (final_Powers[c] > 0 && usedPoints > allowedPoints) { + if (final_Powers[c] > 1 || + ((c != FP_LEVITATION) && (c != FP_SABER_OFFENSE || !freeSaber) && (c != FP_SABER_DEFENSE || !freeSaber))) { usedPoints -= bgForcePowerCost[c][final_Powers[c]]; final_Powers[c]--; - } - else - { + } else { break; } } @@ -587,23 +465,17 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan powerCycle++; attemptedCycles++; - if (attemptedCycles > NUM_FORCE_POWERS) - { //I think this should be impossible. But just in case. + if (attemptedCycles > NUM_FORCE_POWERS) { // I think this should be impossible. But just in case. break; } } - if (usedPoints > allowedPoints) - { //Still? Fine then.. we will kill all of your powers, except the freebies. + if (usedPoints > allowedPoints) { // Still? Fine then.. we will kill all of your powers, except the freebies. i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { final_Powers[i] = 0; - if (i == FP_LEVITATION || - (i == FP_SABER_OFFENSE && freeSaber) || - (i == FP_SABER_DEFENSE && freeSaber)) - { + if (i == FP_LEVITATION || (i == FP_SABER_OFFENSE && freeSaber) || (i == FP_SABER_DEFENSE && freeSaber)) { final_Powers[i] = 1; } i++; @@ -612,8 +484,7 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan } } - if (freeSaber) - { + if (freeSaber) { if (final_Powers[FP_SABER_OFFENSE] < 1) final_Powers[FP_SABER_OFFENSE] = 1; if (final_Powers[FP_SABER_DEFENSE] < 1) @@ -623,17 +494,15 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan final_Powers[FP_LEVITATION] = 1; i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { if (final_Powers[i] > FORCE_LEVEL_3) final_Powers[i] = FORCE_LEVEL_3; i++; } - if (fpDisabled) - { //If we specifically have attack or def disabled, force them up to level 3. It's the way - //things work for the case of all powers disabled. - //If jump is disabled, down-cap it to level 1. Otherwise don't do a thing. + if (fpDisabled) { // If we specifically have attack or def disabled, force them up to level 3. It's the way + // things work for the case of all powers disabled. + // If jump is disabled, down-cap it to level 1. Otherwise don't do a thing. if (fpDisabled & (1 << FP_LEVITATION)) final_Powers[FP_LEVITATION] = 1; if (fpDisabled & (1 << FP_SABER_OFFENSE)) @@ -642,22 +511,20 @@ qboolean BG_LegalizedForcePowers(char *powerOut, size_t powerOutSize, int maxRan final_Powers[FP_SABER_DEFENSE] = 3; } - if (final_Powers[FP_SABER_OFFENSE] < 1) - { + if (final_Powers[FP_SABER_OFFENSE] < 1) { final_Powers[FP_SABER_DEFENSE] = 0; final_Powers[FP_SABERTHROW] = 0; } - //We finally have all the force powers legalized and stored locally. - //Put them all into the string and return the result. We already have - //the rank there, so print the side and the powers now. + // We finally have all the force powers legalized and stored locally. + // Put them all into the string and return the result. We already have + // the rank there, so print the side and the powers now. Q_strcat(powerOut, powerOutSize, va("%i-", final_Side)); i = strlen(powerOut); c = 0; - while (c < NUM_FORCE_POWERS) - { - Q_strncpyz(readBuf, va( "%i", final_Powers[c] ), sizeof( readBuf ) ); + while (c < NUM_FORCE_POWERS) { + Q_strncpyz(readBuf, va("%i", final_Powers[c]), sizeof(readBuf)); powerOut[i] = readBuf[0]; c++; i++; @@ -683,921 +550,882 @@ An item fires all of its targets when it is picked up. If the toucher can't car "count" override quantity or duration on most items. */ -gitem_t bg_itemlist[] = -{ - { - NULL, // classname - NULL, // pickup_sound - { NULL, // world_model[0] - NULL, // world_model[1] - 0, 0} , // world_model[2],[3] - NULL, // view_model -/* icon */ NULL, // icon -/* pickup */ //NULL, // pickup_name - 0, // quantity - IT_BAD, // giType (IT_*) - 0, // giTag -/* precache */ "", // precaches -/* sounds */ "", // sounds - "" // description - }, // leave index 0 alone +gitem_t bg_itemlist[] = { + { + NULL, // classname + NULL, // pickup_sound + {NULL, // world_model[0] + NULL, // world_model[1] + 0, 0}, // world_model[2],[3] + NULL, // view_model + /* icon */ NULL, // icon + /* pickup */ // NULL, // pickup_name + 0, // quantity + IT_BAD, // giType (IT_*) + 0, // giTag + /* precache */ "", // precaches + /* sounds */ "", // sounds + "" // description + }, // leave index 0 alone // // Pickups // -/*QUAKED item_shield_sm_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Instant shield pickup, restores 25 -*/ + /*QUAKED item_shield_sm_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Instant shield pickup, restores 25 + */ { "item_shield_sm_instant", "sound/player/pickupshield.wav", - { "models/map_objects/mp/psd_sm.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/small_shield", -/* pickup */// "Shield Small", + {"models/map_objects/mp/psd_sm.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/small_shield", + /* pickup */ // "Shield Small", 25, IT_ARMOR, - 1, //special for shield - max on pickup is maxhealth*tag, thus small shield goes up to 100 shield -/* precache */ "", -/* sounds */ "" - "" // description + 1, // special for shield - max on pickup is maxhealth*tag, thus small shield goes up to 100 shield + /* precache */ "", + /* sounds */ + "" + "" // description }, -/*QUAKED item_shield_lrg_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Instant shield pickup, restores 100 -*/ + /*QUAKED item_shield_lrg_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Instant shield pickup, restores 100 + */ { "item_shield_lrg_instant", "sound/player/pickupshield.wav", - { "models/map_objects/mp/psd.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/large_shield", -/* pickup */// "Shield Large", + {"models/map_objects/mp/psd.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/large_shield", + /* pickup */ // "Shield Large", 100, IT_ARMOR, - 2, //special for shield - max on pickup is maxhealth*tag, thus large shield goes up to 200 shield -/* precache */ "", -/* sounds */ "", - "" // description + 2, // special for shield - max on pickup is maxhealth*tag, thus large shield goes up to 200 shield + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_medpak_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Instant medpack pickup, heals 25 -*/ + /*QUAKED item_medpak_instant (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Instant medpack pickup, heals 25 + */ { "item_medpak_instant", "sound/player/pickuphealth.wav", - { "models/map_objects/mp/medpac.md3", - 0, 0, 0 }, -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_medkit", -/* pickup */// "Medpack", + {"models/map_objects/mp/medpac.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_medkit", + /* pickup */ // "Medpack", 25, IT_HEALTH, 0, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, - // // ITEMS // -/*QUAKED item_seeker (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -30 seconds of seeker drone -*/ + /*QUAKED item_seeker (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + 30 seconds of seeker drone + */ { "item_seeker", "sound/weapons/w_pkup.wav", - { "models/items/remote.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_seeker", -/* pickup */// "Seeker Drone", + {"models/items/remote.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_seeker", + /* pickup */ // "Seeker Drone", 120, IT_HOLDABLE, HI_SEEKER, -/* precache */ "", -/* sounds */ "", - "@MENUS_AN_ATTACK_DRONE_SIMILAR" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_AN_ATTACK_DRONE_SIMILAR" // description }, -/*QUAKED item_shield (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Portable shield -*/ + /*QUAKED item_shield (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Portable shield + */ { "item_shield", "sound/weapons/w_pkup.wav", - { "models/map_objects/mp/shield.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_shieldwall", -/* pickup */// "Forcefield", + {"models/map_objects/mp/shield.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_shieldwall", + /* pickup */ // "Forcefield", 120, IT_HOLDABLE, HI_SHIELD, -/* precache */ "", -/* sounds */ "sound/weapons/detpack/stick.wav sound/movers/doors/forcefield_on.wav sound/movers/doors/forcefield_off.wav sound/movers/doors/forcefield_lp.wav sound/effects/bumpfield.wav", - "@MENUS_THIS_STATIONARY_ENERGY" // description + /* precache */ "", + /* sounds */ + "sound/weapons/detpack/stick.wav sound/movers/doors/forcefield_on.wav sound/movers/doors/forcefield_off.wav sound/movers/doors/forcefield_lp.wav " + "sound/effects/bumpfield.wav", + "@MENUS_THIS_STATIONARY_ENERGY" // description }, -/*QUAKED item_medpac (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Bacta canister pickup, heals 25 on use -*/ + /*QUAKED item_medpac (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Bacta canister pickup, heals 25 on use + */ { - "item_medpac", //should be item_bacta + "item_medpac", // should be item_bacta "sound/weapons/w_pkup.wav", - { "models/map_objects/mp/bacta.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_bacta", -/* pickup */// "Bacta Canister", + {"models/map_objects/mp/bacta.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_bacta", + /* pickup */ // "Bacta Canister", 25, IT_HOLDABLE, HI_MEDPAC, -/* precache */ "", -/* sounds */ "", - "@SP_INGAME_BACTA_DESC" // description + /* precache */ "", + /* sounds */ "", + "@SP_INGAME_BACTA_DESC" // description }, -/*QUAKED item_medpac_big (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Big bacta canister pickup, heals 50 on use -*/ + /*QUAKED item_medpac_big (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Big bacta canister pickup, heals 50 on use + */ { - "item_medpac_big", //should be item_bacta + "item_medpac_big", // should be item_bacta "sound/weapons/w_pkup.wav", - { "models/items/big_bacta.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_big_bacta", -/* pickup */// "Bacta Canister", + {"models/items/big_bacta.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_big_bacta", + /* pickup */ // "Bacta Canister", 25, IT_HOLDABLE, HI_MEDPAC_BIG, -/* precache */ "", -/* sounds */ "", - "@SP_INGAME_BACTA_DESC" // description + /* precache */ "", + /* sounds */ "", + "@SP_INGAME_BACTA_DESC" // description }, -/*QUAKED item_binoculars (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -These will be standard equipment on the player - DO NOT PLACE -*/ + /*QUAKED item_binoculars (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + These will be standard equipment on the player - DO NOT PLACE + */ { "item_binoculars", "sound/weapons/w_pkup.wav", - { "models/items/binoculars.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_zoom", -/* pickup */// "Binoculars", + {"models/items/binoculars.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_zoom", + /* pickup */ // "Binoculars", 60, IT_HOLDABLE, HI_BINOCULARS, -/* precache */ "", -/* sounds */ "", - "@SP_INGAME_LA_GOGGLES_DESC" // description + /* precache */ "", + /* sounds */ "", + "@SP_INGAME_LA_GOGGLES_DESC" // description }, -/*QUAKED item_sentry_gun (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Sentry gun inventory pickup. -*/ + /*QUAKED item_sentry_gun (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Sentry gun inventory pickup. + */ { "item_sentry_gun", "sound/weapons/w_pkup.wav", - { "models/items/psgun.glm", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_sentrygun", -/* pickup */// "Sentry Gun", + {"models/items/psgun.glm", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_sentrygun", + /* pickup */ // "Sentry Gun", 120, IT_HOLDABLE, HI_SENTRY_GUN, -/* precache */ "", -/* sounds */ "", - "@MENUS_THIS_DEADLY_WEAPON_IS" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THIS_DEADLY_WEAPON_IS" // description }, -/*QUAKED item_jetpack (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Do not place. -*/ + /*QUAKED item_jetpack (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Do not place. + */ { "item_jetpack", "sound/weapons/w_pkup.wav", - { "models/items/psgun.glm", //FIXME: no model - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_jetpack", -/* pickup */// "Sentry Gun", + {"models/items/psgun.glm", // FIXME: no model + 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_jetpack", + /* pickup */ // "Sentry Gun", 120, IT_HOLDABLE, HI_JETPACK, -/* precache */ "effects/boba/jet.efx", -/* sounds */ "sound/chars/boba/JETON.wav sound/chars/boba/JETHOVER.wav sound/effects/fire_lp.wav", - "@MENUS_JETPACK_DESC" // description + /* precache */ "effects/boba/jet.efx", + /* sounds */ "sound/chars/boba/JETON.wav sound/chars/boba/JETHOVER.wav sound/effects/fire_lp.wav", + "@MENUS_JETPACK_DESC" // description }, -/*QUAKED item_healthdisp (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Do not place. For siege classes ONLY. -*/ + /*QUAKED item_healthdisp (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Do not place. For siege classes ONLY. + */ { "item_healthdisp", "sound/weapons/w_pkup.wav", - { "models/map_objects/mp/bacta.md3", //replace me - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_healthdisp", -/* pickup */// "Sentry Gun", + {"models/map_objects/mp/bacta.md3", // replace me + 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_healthdisp", + /* pickup */ // "Sentry Gun", 120, IT_HOLDABLE, HI_HEALTHDISP, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_ammodisp (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Do not place. For siege classes ONLY. -*/ + /*QUAKED item_ammodisp (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Do not place. For siege classes ONLY. + */ { "item_ammodisp", "sound/weapons/w_pkup.wav", - { "models/map_objects/mp/bacta.md3", //replace me - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_ammodisp", -/* pickup */// "Sentry Gun", + {"models/map_objects/mp/bacta.md3", // replace me + 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_ammodisp", + /* pickup */ // "Sentry Gun", 120, IT_HOLDABLE, HI_AMMODISP, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_eweb_holdable (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -Do not place. For siege classes ONLY. -*/ + /*QUAKED item_eweb_holdable (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + Do not place. For siege classes ONLY. + */ { "item_eweb_holdable", "sound/interface/shieldcon_empty", - { "models/map_objects/hoth/eweb_model.glm", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_eweb", -/* pickup */// "Sentry Gun", + {"models/map_objects/hoth/eweb_model.glm", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_eweb", + /* pickup */ // "Sentry Gun", 120, IT_HOLDABLE, HI_EWEB, -/* precache */ "", -/* sounds */ "", - "@MENUS_EWEB_DESC" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_EWEB_DESC" // description }, -/*QUAKED item_seeker (.3 .3 1) (-8 -8 -0) (8 8 16) suspended -30 seconds of seeker drone -*/ + /*QUAKED item_seeker (.3 .3 1) (-8 -8 -0) (8 8 16) suspended + 30 seconds of seeker drone + */ { "item_cloak", "sound/weapons/w_pkup.wav", - { "models/items/psgun.glm", //FIXME: no model - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_cloak", -/* pickup */// "Seeker Drone", + {"models/items/psgun.glm", // FIXME: no model + 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_cloak", + /* pickup */ // "Seeker Drone", 120, IT_HOLDABLE, HI_CLOAK, -/* precache */ "", -/* sounds */ "", - "@MENUS_CLOAK_DESC" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_CLOAK_DESC" // description }, -/*QUAKED item_force_enlighten_light (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Adds one rank to all Force powers temporarily. Only light jedi can use. -*/ + /*QUAKED item_force_enlighten_light (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Adds one rank to all Force powers temporarily. Only light jedi can use. + */ { "item_force_enlighten_light", "sound/player/enlightenment.wav", - { "models/map_objects/mp/jedi_enlightenment.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/mpi_jlight", -/* pickup */// "Light Force Enlightenment", + {"models/map_objects/mp/jedi_enlightenment.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_jlight", + /* pickup */ // "Light Force Enlightenment", 25, IT_POWERUP, PW_FORCE_ENLIGHTENED_LIGHT, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_force_enlighten_dark (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Adds one rank to all Force powers temporarily. Only dark jedi can use. -*/ + /*QUAKED item_force_enlighten_dark (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Adds one rank to all Force powers temporarily. Only dark jedi can use. + */ { "item_force_enlighten_dark", "sound/player/enlightenment.wav", - { "models/map_objects/mp/dk_enlightenment.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/mpi_dklight", -/* pickup */// "Dark Force Enlightenment", + {"models/map_objects/mp/dk_enlightenment.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_dklight", + /* pickup */ // "Dark Force Enlightenment", 25, IT_POWERUP, PW_FORCE_ENLIGHTENED_DARK, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_force_boon (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Unlimited Force Pool for a short time. -*/ + /*QUAKED item_force_boon (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Unlimited Force Pool for a short time. + */ { "item_force_boon", "sound/player/boon.wav", - { "models/map_objects/mp/force_boon.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/mpi_fboon", -/* pickup */// "Force Boon", + {"models/map_objects/mp/force_boon.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_fboon", + /* pickup */ // "Force Boon", 25, IT_POWERUP, PW_FORCE_BOON, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED item_ysalimari (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -A small lizard carried on the player, which prevents the possessor from using any Force power. However, he is unaffected by any Force power. -*/ + /*QUAKED item_ysalimari (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + A small lizard carried on the player, which prevents the possessor from using any Force power. However, he is unaffected by any Force power. + */ { "item_ysalimari", "sound/player/ysalimari.wav", - { "models/map_objects/mp/ysalimari.md3", - 0, 0, 0} , -/* view */ NULL, -/* icon */ "gfx/hud/mpi_ysamari", -/* pickup */// "Ysalamiri", + {"models/map_objects/mp/ysalimari.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_ysamari", + /* pickup */ // "Ysalamiri", 25, IT_POWERUP, PW_YSALAMIRI, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, // // WEAPONS // -/*QUAKED weapon_stun_baton (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED weapon_stun_baton (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { "weapon_stun_baton", "sound/weapons/w_pkup.wav", - { "models/weapons2/stun_baton/baton_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/stun_baton/baton.md3", -/* icon */ "gfx/hud/w_icon_stunbaton", -/* pickup */// "Stun Baton", + {"models/weapons2/stun_baton/baton_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/stun_baton/baton.md3", + /* icon */ "gfx/hud/w_icon_stunbaton", + /* pickup */ // "Stun Baton", 100, IT_WEAPON, WP_STUN_BATON, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED weapon_melee (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED weapon_melee (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { "weapon_melee", "sound/weapons/w_pkup.wav", - { "models/weapons2/stun_baton/baton_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/stun_baton/baton.md3", -/* icon */ "gfx/hud/w_icon_melee", -/* pickup */// "Stun Baton", + {"models/weapons2/stun_baton/baton_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/stun_baton/baton.md3", + /* icon */ "gfx/hud/w_icon_melee", + /* pickup */ // "Stun Baton", 100, IT_WEAPON, WP_MELEE, -/* precache */ "", -/* sounds */ "", - "@MENUS_MELEE_DESC" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_MELEE_DESC" // description }, -/*QUAKED weapon_saber (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED weapon_saber (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { "weapon_saber", "sound/weapons/w_pkup.wav", - { DEFAULT_SABER_MODEL, - 0, 0, 0}, -/* view */ "models/weapons2/saber/saber_w.md3", -/* icon */ "gfx/hud/w_icon_lightsaber", -/* pickup */// "Lightsaber", + {DEFAULT_SABER_MODEL, 0, 0, 0}, + /* view */ "models/weapons2/saber/saber_w.md3", + /* icon */ "gfx/hud/w_icon_lightsaber", + /* pickup */ // "Lightsaber", 100, IT_WEAPON, WP_SABER, -/* precache */ "", -/* sounds */ "", - "@MENUS_AN_ELEGANT_WEAPON_FOR" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_AN_ELEGANT_WEAPON_FOR" // description }, -/*QUAKED weapon_bryar_pistol (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED weapon_bryar_pistol (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { //"weapon_bryar_pistol", "weapon_blaster_pistol", "sound/weapons/w_pkup.wav", - { "models/weapons2/blaster_pistol/blaster_pistol_w.glm",//"models/weapons2/briar_pistol/briar_pistol_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/blaster_pistol/blaster_pistol.md3",//"models/weapons2/briar_pistol/briar_pistol.md3", -/* icon */ "gfx/hud/w_icon_blaster_pistol",//"gfx/hud/w_icon_rifle", -/* pickup */// "Bryar Pistol", + {"models/weapons2/blaster_pistol/blaster_pistol_w.glm", //"models/weapons2/briar_pistol/briar_pistol_w.glm", + 0, 0, 0}, + /* view */ "models/weapons2/blaster_pistol/blaster_pistol.md3", //"models/weapons2/briar_pistol/briar_pistol.md3", + /* icon */ "gfx/hud/w_icon_blaster_pistol", //"gfx/hud/w_icon_rifle", + /* pickup */ // "Bryar Pistol", 100, IT_WEAPON, WP_BRYAR_PISTOL, -/* precache */ "", -/* sounds */ "", - "@MENUS_BLASTER_PISTOL_DESC" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_BLASTER_PISTOL_DESC" // description }, -/*QUAKED weapon_concussion_rifle (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_concussion_rifle (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_concussion_rifle", "sound/weapons/w_pkup.wav", - { "models/weapons2/concussion/c_rifle_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/concussion/c_rifle.md3", -/* icon */ "gfx/hud/w_icon_c_rifle",//"gfx/hud/w_icon_rifle", -/* pickup */// "Concussion Rifle", + {"models/weapons2/concussion/c_rifle_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/concussion/c_rifle.md3", + /* icon */ "gfx/hud/w_icon_c_rifle", //"gfx/hud/w_icon_rifle", + /* pickup */ // "Concussion Rifle", 50, IT_WEAPON, WP_CONCUSSION, -/* precache */ "", -/* sounds */ "", - "@MENUS_CONC_RIFLE_DESC" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_CONC_RIFLE_DESC" // description }, -/*QUAKED weapon_bryar_pistol_old (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED weapon_bryar_pistol_old (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { "weapon_bryar_pistol", "sound/weapons/w_pkup.wav", - { "models/weapons2/briar_pistol/briar_pistol_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/briar_pistol/briar_pistol.md3", -/* icon */ "gfx/hud/w_icon_briar",//"gfx/hud/w_icon_rifle", -/* pickup */// "Bryar Pistol", + {"models/weapons2/briar_pistol/briar_pistol_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/briar_pistol/briar_pistol.md3", + /* icon */ "gfx/hud/w_icon_briar", //"gfx/hud/w_icon_rifle", + /* pickup */ // "Bryar Pistol", 100, IT_WEAPON, WP_BRYAR_OLD, -/* precache */ "", -/* sounds */ "", - "@SP_INGAME_BLASTER_PISTOL" // description + /* precache */ "", + /* sounds */ "", + "@SP_INGAME_BLASTER_PISTOL" // description }, -/*QUAKED weapon_blaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_blaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_blaster", "sound/weapons/w_pkup.wav", - { "models/weapons2/blaster_r/blaster_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/blaster_r/blaster.md3", -/* icon */ "gfx/hud/w_icon_blaster", -/* pickup */// "E11 Blaster Rifle", + {"models/weapons2/blaster_r/blaster_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/blaster_r/blaster.md3", + /* icon */ "gfx/hud/w_icon_blaster", + /* pickup */ // "E11 Blaster Rifle", 100, IT_WEAPON, WP_BLASTER, -/* precache */ "", -/* sounds */ "", - "@MENUS_THE_PRIMARY_WEAPON_OF" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THE_PRIMARY_WEAPON_OF" // description }, -/*QUAKED weapon_disruptor (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_disruptor (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_disruptor", "sound/weapons/w_pkup.wav", - { "models/weapons2/disruptor/disruptor_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/disruptor/disruptor.md3", -/* icon */ "gfx/hud/w_icon_disruptor", -/* pickup */// "Tenloss Disruptor Rifle", + {"models/weapons2/disruptor/disruptor_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/disruptor/disruptor.md3", + /* icon */ "gfx/hud/w_icon_disruptor", + /* pickup */ // "Tenloss Disruptor Rifle", 100, IT_WEAPON, WP_DISRUPTOR, -/* precache */ "", -/* sounds */ "", - "@MENUS_THIS_NEFARIOUS_WEAPON" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THIS_NEFARIOUS_WEAPON" // description }, -/*QUAKED weapon_bowcaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_bowcaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_bowcaster", "sound/weapons/w_pkup.wav", - { "models/weapons2/bowcaster/bowcaster_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/bowcaster/bowcaster.md3", -/* icon */ "gfx/hud/w_icon_bowcaster", -/* pickup */// "Wookiee Bowcaster", + {"models/weapons2/bowcaster/bowcaster_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/bowcaster/bowcaster.md3", + /* icon */ "gfx/hud/w_icon_bowcaster", + /* pickup */ // "Wookiee Bowcaster", 100, IT_WEAPON, WP_BOWCASTER, -/* precache */ "", -/* sounds */ "", - "@MENUS_THIS_ARCHAIC_LOOKING" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THIS_ARCHAIC_LOOKING" // description }, -/*QUAKED weapon_repeater (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_repeater (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_repeater", "sound/weapons/w_pkup.wav", - { "models/weapons2/heavy_repeater/heavy_repeater_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/heavy_repeater/heavy_repeater.md3", -/* icon */ "gfx/hud/w_icon_repeater", -/* pickup */// "Imperial Heavy Repeater", + {"models/weapons2/heavy_repeater/heavy_repeater_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/heavy_repeater/heavy_repeater.md3", + /* icon */ "gfx/hud/w_icon_repeater", + /* pickup */ // "Imperial Heavy Repeater", 100, IT_WEAPON, WP_REPEATER, -/* precache */ "", -/* sounds */ "", - "@MENUS_THIS_DESTRUCTIVE_PROJECTILE" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THIS_DESTRUCTIVE_PROJECTILE" // description }, -/*QUAKED weapon_demp2 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -NOTENOTE This weapon is not yet complete. Don't place it. -*/ + /*QUAKED weapon_demp2 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + NOTENOTE This weapon is not yet complete. Don't place it. + */ { "weapon_demp2", "sound/weapons/w_pkup.wav", - { "models/weapons2/demp2/demp2_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/demp2/demp2.md3", -/* icon */ "gfx/hud/w_icon_demp2", -/* pickup */// "DEMP2", + {"models/weapons2/demp2/demp2_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/demp2/demp2.md3", + /* icon */ "gfx/hud/w_icon_demp2", + /* pickup */ // "DEMP2", 100, IT_WEAPON, WP_DEMP2, -/* precache */ "", -/* sounds */ "", - "@MENUS_COMMONLY_REFERRED_TO" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_COMMONLY_REFERRED_TO" // description }, -/*QUAKED weapon_flechette (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_flechette (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_flechette", "sound/weapons/w_pkup.wav", - { "models/weapons2/golan_arms/golan_arms_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/golan_arms/golan_arms.md3", -/* icon */ "gfx/hud/w_icon_flechette", -/* pickup */// "Golan Arms Flechette", + {"models/weapons2/golan_arms/golan_arms_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/golan_arms/golan_arms.md3", + /* icon */ "gfx/hud/w_icon_flechette", + /* pickup */ // "Golan Arms Flechette", 100, IT_WEAPON, WP_FLECHETTE, -/* precache */ "", -/* sounds */ "", - "@MENUS_WIDELY_USED_BY_THE_CORPORATE" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_WIDELY_USED_BY_THE_CORPORATE" // description }, -/*QUAKED weapon_rocket_launcher (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_rocket_launcher (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_rocket_launcher", "sound/weapons/w_pkup.wav", - { "models/weapons2/merr_sonn/merr_sonn_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/merr_sonn/merr_sonn.md3", -/* icon */ "gfx/hud/w_icon_merrsonn", -/* pickup */// "Merr-Sonn Missile System", + {"models/weapons2/merr_sonn/merr_sonn_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/merr_sonn/merr_sonn.md3", + /* icon */ "gfx/hud/w_icon_merrsonn", + /* pickup */ // "Merr-Sonn Missile System", 3, IT_WEAPON, WP_ROCKET_LAUNCHER, -/* precache */ "", -/* sounds */ "", - "@MENUS_THE_PLX_2M_IS_AN_EXTREMELY" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THE_PLX_2M_IS_AN_EXTREMELY" // description }, -/*QUAKED ammo_thermal (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED ammo_thermal (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "ammo_thermal", "sound/weapons/w_pkup.wav", - { "models/weapons2/thermal/thermal_pu.md3", - "models/weapons2/thermal/thermal_w.glm", 0, 0}, -/* view */ "models/weapons2/thermal/thermal.md3", -/* icon */ "gfx/hud/w_icon_thermal", -/* pickup */// "Thermal Detonators", + {"models/weapons2/thermal/thermal_pu.md3", "models/weapons2/thermal/thermal_w.glm", 0, 0}, + /* view */ "models/weapons2/thermal/thermal.md3", + /* icon */ "gfx/hud/w_icon_thermal", + /* pickup */ // "Thermal Detonators", 4, IT_AMMO, AMMO_THERMAL, -/* precache */ "", -/* sounds */ "", - "@MENUS_THE_THERMAL_DETONATOR" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THE_THERMAL_DETONATOR" // description }, -/*QUAKED ammo_tripmine (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED ammo_tripmine (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "ammo_tripmine", "sound/weapons/w_pkup.wav", - { "models/weapons2/laser_trap/laser_trap_pu.md3", - "models/weapons2/laser_trap/laser_trap_w.glm", 0, 0}, -/* view */ "models/weapons2/laser_trap/laser_trap.md3", -/* icon */ "gfx/hud/w_icon_tripmine", -/* pickup */// "Trip Mines", + {"models/weapons2/laser_trap/laser_trap_pu.md3", "models/weapons2/laser_trap/laser_trap_w.glm", 0, 0}, + /* view */ "models/weapons2/laser_trap/laser_trap.md3", + /* icon */ "gfx/hud/w_icon_tripmine", + /* pickup */ // "Trip Mines", 3, IT_AMMO, AMMO_TRIPMINE, -/* precache */ "", -/* sounds */ "", - "@MENUS_TRIP_MINES_CONSIST_OF" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_TRIP_MINES_CONSIST_OF" // description }, -/*QUAKED ammo_detpack (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED ammo_detpack (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "ammo_detpack", "sound/weapons/w_pkup.wav", - { "models/weapons2/detpack/det_pack_pu.md3", "models/weapons2/detpack/det_pack_proj.glm", "models/weapons2/detpack/det_pack_w.glm", 0}, -/* view */ "models/weapons2/detpack/det_pack.md3", -/* icon */ "gfx/hud/w_icon_detpack", -/* pickup */// "Det Packs", + {"models/weapons2/detpack/det_pack_pu.md3", "models/weapons2/detpack/det_pack_proj.glm", "models/weapons2/detpack/det_pack_w.glm", 0}, + /* view */ "models/weapons2/detpack/det_pack.md3", + /* icon */ "gfx/hud/w_icon_detpack", + /* pickup */ // "Det Packs", 3, IT_AMMO, AMMO_DETPACK, -/* precache */ "", -/* sounds */ "", - "@MENUS_A_DETONATION_PACK_IS" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_A_DETONATION_PACK_IS" // description }, -/*QUAKED weapon_thermal (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_thermal (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_thermal", "sound/weapons/w_pkup.wav", - { "models/weapons2/thermal/thermal_w.glm", "models/weapons2/thermal/thermal_pu.md3", - 0, 0 }, -/* view */ "models/weapons2/thermal/thermal.md3", -/* icon */ "gfx/hud/w_icon_thermal", -/* pickup */// "Thermal Detonator", + {"models/weapons2/thermal/thermal_w.glm", "models/weapons2/thermal/thermal_pu.md3", 0, 0}, + /* view */ "models/weapons2/thermal/thermal.md3", + /* icon */ "gfx/hud/w_icon_thermal", + /* pickup */ // "Thermal Detonator", 4, IT_WEAPON, WP_THERMAL, -/* precache */ "", -/* sounds */ "", - "@MENUS_THE_THERMAL_DETONATOR" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_THE_THERMAL_DETONATOR" // description }, -/*QUAKED weapon_trip_mine (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_trip_mine (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_trip_mine", "sound/weapons/w_pkup.wav", - { "models/weapons2/laser_trap/laser_trap_w.glm", "models/weapons2/laser_trap/laser_trap_pu.md3", - 0, 0}, -/* view */ "models/weapons2/laser_trap/laser_trap.md3", -/* icon */ "gfx/hud/w_icon_tripmine", -/* pickup */// "Trip Mine", + {"models/weapons2/laser_trap/laser_trap_w.glm", "models/weapons2/laser_trap/laser_trap_pu.md3", 0, 0}, + /* view */ "models/weapons2/laser_trap/laser_trap.md3", + /* icon */ "gfx/hud/w_icon_tripmine", + /* pickup */ // "Trip Mine", 3, IT_WEAPON, WP_TRIP_MINE, -/* precache */ "", -/* sounds */ "", - "@MENUS_TRIP_MINES_CONSIST_OF" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_TRIP_MINES_CONSIST_OF" // description }, -/*QUAKED weapon_det_pack (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_det_pack (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_det_pack", "sound/weapons/w_pkup.wav", - { "models/weapons2/detpack/det_pack_proj.glm", "models/weapons2/detpack/det_pack_pu.md3", "models/weapons2/detpack/det_pack_w.glm", 0}, -/* view */ "models/weapons2/detpack/det_pack.md3", -/* icon */ "gfx/hud/w_icon_detpack", -/* pickup */// "Det Pack", + {"models/weapons2/detpack/det_pack_proj.glm", "models/weapons2/detpack/det_pack_pu.md3", "models/weapons2/detpack/det_pack_w.glm", 0}, + /* view */ "models/weapons2/detpack/det_pack.md3", + /* icon */ "gfx/hud/w_icon_detpack", + /* pickup */ // "Det Pack", 3, IT_WEAPON, WP_DET_PACK, -/* precache */ "", -/* sounds */ "", - "@MENUS_A_DETONATION_PACK_IS" // description + /* precache */ "", + /* sounds */ "", + "@MENUS_A_DETONATION_PACK_IS" // description }, -/*QUAKED weapon_emplaced (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -*/ + /*QUAKED weapon_emplaced (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + */ { "weapon_emplaced", "sound/weapons/w_pkup.wav", - { "models/weapons2/blaster_r/blaster_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/blaster_r/blaster.md3", -/* icon */ "gfx/hud/w_icon_blaster", -/* pickup */// "Emplaced Gun", + {"models/weapons2/blaster_r/blaster_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/blaster_r/blaster.md3", + /* icon */ "gfx/hud/w_icon_blaster", + /* pickup */ // "Emplaced Gun", 50, IT_WEAPON, WP_EMPLACED_GUN, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, - -//NOTE: This is to keep things from messing up because the turret weapon type isn't real + // NOTE: This is to keep things from messing up because the turret weapon type isn't real { "weapon_turretwp", "sound/weapons/w_pkup.wav", - { "models/weapons2/blaster_r/blaster_w.glm", - 0, 0, 0}, -/* view */ "models/weapons2/blaster_r/blaster.md3", -/* icon */ "gfx/hud/w_icon_blaster", -/* pickup */// "Turret Gun", + {"models/weapons2/blaster_r/blaster_w.glm", 0, 0, 0}, + /* view */ "models/weapons2/blaster_r/blaster.md3", + /* icon */ "gfx/hud/w_icon_blaster", + /* pickup */ // "Turret Gun", 50, IT_WEAPON, WP_TURRET, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, // // AMMO ITEMS // -/*QUAKED ammo_force (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Don't place this -*/ + /*QUAKED ammo_force (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Don't place this + */ { "ammo_force", "sound/player/pickupenergy.wav", - { "models/items/energy_cell.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/hud/w_icon_blaster", -/* pickup */// "Force??", + {"models/items/energy_cell.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/w_icon_blaster", + /* pickup */ // "Force??", 100, IT_AMMO, AMMO_FORCE, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED ammo_blaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Ammo for the Bryar and Blaster pistols. -*/ + /*QUAKED ammo_blaster (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Ammo for the Bryar and Blaster pistols. + */ { "ammo_blaster", "sound/player/pickupenergy.wav", - { "models/items/energy_cell.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/hud/i_icon_battery", -/* pickup */// "Blaster Pack", + {"models/items/energy_cell.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/i_icon_battery", + /* pickup */ // "Blaster Pack", 100, IT_AMMO, AMMO_BLASTER, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED ammo_powercell (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Ammo for Tenloss Disruptor, Wookie Bowcaster, and the Destructive Electro Magnetic Pulse (demp2 ) guns -*/ + /*QUAKED ammo_powercell (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Ammo for Tenloss Disruptor, Wookie Bowcaster, and the Destructive Electro Magnetic Pulse (demp2 ) guns + */ { "ammo_powercell", "sound/player/pickupenergy.wav", - { "models/items/power_cell.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/ammo_power_cell", -/* pickup */// "Power Cell", + {"models/items/power_cell.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/ammo_power_cell", + /* pickup */ // "Power Cell", 100, IT_AMMO, AMMO_POWERCELL, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED ammo_metallic_bolts (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Ammo for Imperial Heavy Repeater and the Golan Arms Flechette -*/ + /*QUAKED ammo_metallic_bolts (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Ammo for Imperial Heavy Repeater and the Golan Arms Flechette + */ { "ammo_metallic_bolts", "sound/player/pickupenergy.wav", - { "models/items/metallic_bolts.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/ammo_metallic_bolts", -/* pickup */// "Metallic Bolts", + {"models/items/metallic_bolts.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/ammo_metallic_bolts", + /* pickup */ // "Metallic Bolts", 100, IT_AMMO, AMMO_METAL_BOLTS, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED ammo_rockets (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -Ammo for Merr-Sonn portable missile launcher -*/ + /*QUAKED ammo_rockets (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + Ammo for Merr-Sonn portable missile launcher + */ { "ammo_rockets", "sound/player/pickupenergy.wav", - { "models/items/rockets.md3", - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/ammo_rockets", -/* pickup */// "Rockets", + {"models/items/rockets.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/ammo_rockets", + /* pickup */ // "Rockets", 3, IT_AMMO, AMMO_ROCKETS, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED ammo_all (.3 .3 1) (-16 -16 -16) (16 16 16) suspended -DO NOT PLACE in a map, this is only for siege classes that have ammo -dispensing ability -*/ + /*QUAKED ammo_all (.3 .3 1) (-16 -16 -16) (16 16 16) suspended + DO NOT PLACE in a map, this is only for siege classes that have ammo + dispensing ability + */ { "ammo_all", "sound/player/pickupenergy.wav", - { "models/items/battery.md3", //replace me - 0, 0, 0}, -/* view */ NULL, -/* icon */ "gfx/mp/ammo_rockets", //replace me -/* pickup */// "Rockets", + {"models/items/battery.md3", // replace me + 0, 0, 0}, + /* view */ NULL, + /* icon */ "gfx/mp/ammo_rockets", // replace me + /* pickup */ // "Rockets", 0, IT_AMMO, -1, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, // // POWERUP ITEMS // -/*QUAKED team_CTF_redflag (1 0 0) (-16 -16 -16) (16 16 16) -Only in CTF games -*/ + /*QUAKED team_CTF_redflag (1 0 0) (-16 -16 -16) (16 16 16) + Only in CTF games + */ { "team_CTF_redflag", NULL, - { "models/flags/r_flag.md3", - "models/flags/r_flag_ysal.md3", 0, 0 }, -/* view */ NULL, -/* icon */ "gfx/hud/mpi_rflag", -/* pickup */// "Red Flag", + {"models/flags/r_flag.md3", "models/flags/r_flag_ysal.md3", 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_rflag", + /* pickup */ // "Red Flag", 0, IT_TEAM, PW_REDFLAG, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, -/*QUAKED team_CTF_blueflag (0 0 1) (-16 -16 -16) (16 16 16) -Only in CTF games -*/ + /*QUAKED team_CTF_blueflag (0 0 1) (-16 -16 -16) (16 16 16) + Only in CTF games + */ { "team_CTF_blueflag", NULL, - { "models/flags/b_flag.md3", - "models/flags/b_flag_ysal.md3", 0, 0 }, -/* view */ NULL, -/* icon */ "gfx/hud/mpi_bflag", -/* pickup */// "Blue Flag", + {"models/flags/b_flag.md3", "models/flags/b_flag_ysal.md3", 0, 0}, + /* view */ NULL, + /* icon */ "gfx/hud/mpi_bflag", + /* pickup */ // "Blue Flag", 0, IT_TEAM, PW_BLUEFLAG, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, // @@ -1610,65 +1438,61 @@ Only in One Flag CTF games { "team_CTF_neutralflag", NULL, - { "models/flags/n_flag.md3", - 0, 0, 0 }, -/* view */ NULL, -/* icon */ "icons/iconf_neutral1", -/* pickup */// "Neutral Flag", + {"models/flags/n_flag.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "icons/iconf_neutral1", + /* pickup */ // "Neutral Flag", 0, IT_TEAM, PW_NEUTRALFLAG, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, { "item_redcube", "sound/player/pickupenergy.wav", - { "models/powerups/orb/r_orb.md3", - 0, 0, 0 }, -/* view */ NULL, -/* icon */ "icons/iconh_rorb", -/* pickup */// "Red Cube", + {"models/powerups/orb/r_orb.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "icons/iconh_rorb", + /* pickup */ // "Red Cube", 0, IT_TEAM, 0, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, { "item_bluecube", "sound/player/pickupenergy.wav", - { "models/powerups/orb/b_orb.md3", - 0, 0, 0 }, -/* view */ NULL, -/* icon */ "icons/iconh_borb", -/* pickup */// "Blue Cube", + {"models/powerups/orb/b_orb.md3", 0, 0, 0}, + /* view */ NULL, + /* icon */ "icons/iconh_borb", + /* pickup */ // "Blue Cube", 0, IT_TEAM, 0, -/* precache */ "", -/* sounds */ "", - "" // description + /* precache */ "", + /* sounds */ "", + "" // description }, // end of list marker - {NULL} -}; + {NULL}}; -int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) - 1; +int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) - 1; -float vectoyaw( const vec3_t vec ) { - float yaw; +float vectoyaw(const vec3_t vec) { + float yaw; if (vec[YAW] == 0 && vec[PITCH] == 0) { yaw = 0; } else { if (vec[PITCH]) { - yaw = ( atan2( vec[YAW], vec[PITCH]) * 180 / M_PI ); + yaw = (atan2(vec[YAW], vec[PITCH]) * 180 / M_PI); } else if (vec[YAW] > 0) { yaw = 90; } else { @@ -1682,74 +1506,56 @@ float vectoyaw( const vec3_t vec ) { return yaw; } -qboolean BG_HasYsalamiri(int gametype, playerState_t *ps) -{ - if (gametype == GT_CTY && - (ps->powerups[PW_REDFLAG] || ps->powerups[PW_BLUEFLAG])) - { +qboolean BG_HasYsalamiri(int gametype, playerState_t *ps) { + if (gametype == GT_CTY && (ps->powerups[PW_REDFLAG] || ps->powerups[PW_BLUEFLAG])) { return qtrue; } - if (ps->powerups[PW_YSALAMIRI]) - { + if (ps->powerups[PW_YSALAMIRI]) { return qtrue; } return qfalse; } -qboolean BG_CanUseFPNow(int gametype, playerState_t *ps, int time, forcePowers_t power) -{ - if (BG_HasYsalamiri(gametype, ps)) - { +qboolean BG_CanUseFPNow(int gametype, playerState_t *ps, int time, forcePowers_t power) { + if (BG_HasYsalamiri(gametype, ps)) { return qfalse; } - if ( ps->forceRestricted || ps->trueNonJedi ) - { + if (ps->forceRestricted || ps->trueNonJedi) { return qfalse; } - if (ps->weapon == WP_EMPLACED_GUN) - { //can't use any of your powers while on an emplaced weapon + if (ps->weapon == WP_EMPLACED_GUN) { // can't use any of your powers while on an emplaced weapon return qfalse; } - if (ps->m_iVehicleNum) - { //can't use powers while riding a vehicle (this may change, I don't know) + if (ps->m_iVehicleNum) { // can't use powers while riding a vehicle (this may change, I don't know) return qfalse; } - if (ps->duelInProgress) - { + if (ps->duelInProgress) { if (power != FP_SABER_OFFENSE && power != FP_SABER_DEFENSE && /*power != FP_SABERTHROW &&*/ - power != FP_LEVITATION) - { - if (!ps->saberLockFrame || power != FP_PUSH) - { + power != FP_LEVITATION) { + if (!ps->saberLockFrame || power != FP_PUSH) { return qfalse; } } } - if (ps->saberLockFrame || ps->saberLockTime > time) - { - if (power != FP_PUSH) - { + if (ps->saberLockFrame || ps->saberLockTime > time) { + if (power != FP_PUSH) { return qfalse; } } - if (ps->fallingToDeath) - { + if (ps->fallingToDeath) { return qfalse; } - if ((ps->brokenLimbs & (1 << BROKENLIMB_RARM)) || - (ps->brokenLimbs & (1 << BROKENLIMB_LARM))) - { //powers we can't use with a broken arm - switch (power) - { + if ((ps->brokenLimbs & (1 << BROKENLIMB_RARM)) || (ps->brokenLimbs & (1 << BROKENLIMB_LARM))) { // powers we can't use with a broken arm + switch (power) { case FP_PUSH: case FP_PULL: case FP_GRIP: @@ -1769,13 +1575,11 @@ qboolean BG_CanUseFPNow(int gametype, playerState_t *ps, int time, forcePowers_t BG_FindItemForPowerup ============== */ -gitem_t *BG_FindItemForPowerup( powerup_t pw ) { - int i; +gitem_t *BG_FindItemForPowerup(powerup_t pw) { + int i; - for ( i = 0 ; i < bg_numItems ; i++ ) { - if ( (bg_itemlist[i].giType == IT_POWERUP || - bg_itemlist[i].giType == IT_TEAM) && - bg_itemlist[i].giTag == pw ) { + for (i = 0; i < bg_numItems; i++) { + if ((bg_itemlist[i].giType == IT_POWERUP || bg_itemlist[i].giType == IT_TEAM) && bg_itemlist[i].giTag == pw) { return &bg_itemlist[i]; } } @@ -1783,43 +1587,41 @@ gitem_t *BG_FindItemForPowerup( powerup_t pw ) { return NULL; } - /* ============== BG_FindItemForHoldable ============== */ -gitem_t *BG_FindItemForHoldable( holdable_t pw ) { - int i; +gitem_t *BG_FindItemForHoldable(holdable_t pw) { + int i; - for ( i = 0 ; i < bg_numItems ; i++ ) { - if ( bg_itemlist[i].giType == IT_HOLDABLE && bg_itemlist[i].giTag == pw ) { + for (i = 0; i < bg_numItems; i++) { + if (bg_itemlist[i].giType == IT_HOLDABLE && bg_itemlist[i].giTag == pw) { return &bg_itemlist[i]; } } - Com_Error( ERR_DROP, "HoldableItem not found" ); + Com_Error(ERR_DROP, "HoldableItem not found"); return NULL; } - /* =============== BG_FindItemForWeapon =============== */ -gitem_t *BG_FindItemForWeapon( weapon_t weapon ) { - gitem_t *it; +gitem_t *BG_FindItemForWeapon(weapon_t weapon) { + gitem_t *it; - for ( it = bg_itemlist + 1 ; it->classname ; it++) { - if ( it->giType == IT_WEAPON && it->giTag == weapon ) { + for (it = bg_itemlist + 1; it->classname; it++) { + if (it->giType == IT_WEAPON && it->giTag == weapon) { return it; } } - Com_Error( ERR_DROP, "Couldn't find item for weapon %i", weapon); + Com_Error(ERR_DROP, "Couldn't find item for weapon %i", weapon); return NULL; } @@ -1829,16 +1631,16 @@ BG_FindItemForAmmo =============== */ -gitem_t *BG_FindItemForAmmo( ammo_t ammo ) { - gitem_t *it; +gitem_t *BG_FindItemForAmmo(ammo_t ammo) { + gitem_t *it; - for ( it = bg_itemlist + 1 ; it->classname ; it++) { - if ( it->giType == IT_AMMO && it->giTag == ammo ) { + for (it = bg_itemlist + 1; it->classname; it++) { + if (it->giType == IT_AMMO && it->giTag == ammo) { return it; } } - Com_Error( ERR_DROP, "Couldn't find item for ammo %i", ammo); + Com_Error(ERR_DROP, "Couldn't find item for ammo %i", ammo); return NULL; } @@ -1848,11 +1650,11 @@ BG_FindItem =============== */ -gitem_t *BG_FindItem( const char *classname ) { - gitem_t *it; +gitem_t *BG_FindItem(const char *classname) { + gitem_t *it; - for ( it = bg_itemlist + 1 ; it->classname ; it++ ) { - if ( !Q_stricmp( it->classname, classname) ) + for (it = bg_itemlist + 1; it->classname; it++) { + if (!Q_stricmp(it->classname, classname)) return it; } @@ -1867,60 +1669,60 @@ Items can be picked up without actually touching their physical bounds to make grabbing them easier ============ */ -qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime ) { - vec3_t origin; +qboolean BG_PlayerTouchesItem(playerState_t *ps, entityState_t *item, int atTime) { + vec3_t origin; - BG_EvaluateTrajectory( &item->pos, atTime, origin ); + BG_EvaluateTrajectory(&item->pos, atTime, origin); // we are ignoring ducked differences here - if ( ps->origin[0] - origin[0] > 44 - || ps->origin[0] - origin[0] < -50 - || ps->origin[1] - origin[1] > 36 - || ps->origin[1] - origin[1] < -36 - || ps->origin[2] - origin[2] > 36 - || ps->origin[2] - origin[2] < -36 ) { + if (ps->origin[0] - origin[0] > 44 || ps->origin[0] - origin[0] < -50 || ps->origin[1] - origin[1] > 36 || ps->origin[1] - origin[1] < -36 || + ps->origin[2] - origin[2] > 36 || ps->origin[2] - origin[2] < -36) { return qfalse; } return qtrue; } -int BG_ProperForceIndex( int power ) { +int BG_ProperForceIndex(int power) { int i; - for ( i=0; ifd.forcePowerSelected; // no valid force powers - if ( x >= NUM_FORCE_POWERS || x == -1 ) + if (x >= NUM_FORCE_POWERS || x == -1) return; - presel = x = BG_ProperForceIndex( x ); + presel = x = BG_ProperForceIndex(x); // get the next/prev power and handle overflow - if ( direction == 1 ) x++; - else x--; - if ( x >= NUM_FORCE_POWERS ) x = 0; - if ( x < 0 ) x = NUM_FORCE_POWERS-1; + if (direction == 1) + x++; + else + x--; + if (x >= NUM_FORCE_POWERS) + x = 0; + if (x < 0) + x = NUM_FORCE_POWERS - 1; - i = forcePowerSorted[x]; //the "sorted" value of this power + i = forcePowerSorted[x]; // the "sorted" value of this power - while ( x != presel ) { + while (x != presel) { // loop around to the current force power - if ( ps->fd.forcePowersKnown & (1 << i) && i != (signed)ps->fd.forcePowerSelected ) { + if (ps->fd.forcePowersKnown & (1 << i) && i != (signed)ps->fd.forcePowerSelected) { // we have this power - if ( i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE && i != FP_SABERTHROW ) { + if (i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE && i != FP_SABERTHROW) { // it's selectable foundnext = i; break; @@ -1928,28 +1730,28 @@ void BG_CycleForce( playerState_t *ps, int direction ) { } // get the next/prev power and handle overflow - if ( direction == 1 ) x++; - else x--; - if ( x >= NUM_FORCE_POWERS ) x = 0; - if ( x < 0 ) x = NUM_FORCE_POWERS-1; + if (direction == 1) + x++; + else + x--; + if (x >= NUM_FORCE_POWERS) + x = 0; + if (x < 0) + x = NUM_FORCE_POWERS - 1; - i = forcePowerSorted[x]; //set to the sorted value again + i = forcePowerSorted[x]; // set to the sorted value again } // if we found one, select it - if ( foundnext != -1 ) + if (foundnext != -1) ps->fd.forcePowerSelected = foundnext; } -int BG_GetItemIndexByTag(int tag, int type) -{ //Get the itemlist index from the tag and type +int BG_GetItemIndexByTag(int tag, int type) { // Get the itemlist index from the tag and type int i = 0; - while (i < bg_numItems) - { - if (bg_itemlist[i].giTag == tag && - bg_itemlist[i].giType == type) - { + while (i < bg_numItems) { + if (bg_itemlist[i].giTag == tag && bg_itemlist[i].giType == type) { return i; } @@ -1959,19 +1761,15 @@ int BG_GetItemIndexByTag(int tag, int type) return 0; } -//yeah.. -qboolean BG_IsItemSelectable(playerState_t *ps, int item) -{ - if (item == HI_HEALTHDISP || item == HI_AMMODISP || - item == HI_JETPACK) - { +// yeah.. +qboolean BG_IsItemSelectable(playerState_t *ps, int item) { + if (item == HI_HEALTHDISP || item == HI_AMMODISP || item == HI_JETPACK) { return qfalse; } return qtrue; } -void BG_CycleInven(playerState_t *ps, int direction) -{ +void BG_CycleInven(playerState_t *ps, int direction) { int i; int dontFreeze = 0; int original; @@ -1979,55 +1777,40 @@ void BG_CycleInven(playerState_t *ps, int direction) i = bg_itemlist[ps->stats[STAT_HOLDABLE_ITEM]].giTag; original = i; - if (direction == 1) - { //next + if (direction == 1) { // next i++; - if (i == HI_NUM_HOLDABLE) - { + if (i == HI_NUM_HOLDABLE) { i = 1; } - } - else - { //previous + } else { // previous i--; - if (i == 0) - { - i = HI_NUM_HOLDABLE-1; + if (i == 0) { + i = HI_NUM_HOLDABLE - 1; } } - while (i != original) - { //go in a full loop until hitting something, if hit nothing then select nothing - if (ps->stats[STAT_HOLDABLE_ITEMS] & (1 << i)) - { //we have it, select it. - if (BG_IsItemSelectable(ps, i)) - { + while (i != original) { // go in a full loop until hitting something, if hit nothing then select nothing + if (ps->stats[STAT_HOLDABLE_ITEMS] & (1 << i)) { // we have it, select it. + if (BG_IsItemSelectable(ps, i)) { ps->stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(i, IT_HOLDABLE); break; } } - if (direction == 1) - { //next + if (direction == 1) { // next i++; - } - else - { //previous + } else { // previous i--; } - if (i <= 0) - { //wrap around to the last - i = HI_NUM_HOLDABLE-1; - } - else if (i >= HI_NUM_HOLDABLE) - { //wrap around to the first + if (i <= 0) { // wrap around to the last + i = HI_NUM_HOLDABLE - 1; + } else if (i >= HI_NUM_HOLDABLE) { // wrap around to the first i = 1; } dontFreeze++; - if (dontFreeze >= 32) - { //yeah, sure, whatever (it's 2 am and I'm paranoid and can't frickin think) + if (dontFreeze >= 32) { // yeah, sure, whatever (it's 2 am and I'm paranoid and can't frickin think) break; } } @@ -2041,85 +1824,71 @@ Returns false if the item should not be picked up. This needs to be the same for client side prediction and server use. ================ */ -qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const playerState_t *ps ) { - gitem_t *item; +qboolean BG_CanItemBeGrabbed(int gametype, const entityState_t *ent, const playerState_t *ps) { + gitem_t *item; - if ( ent->modelindex < 1 || ent->modelindex >= bg_numItems ) { - Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" ); + if (ent->modelindex < 1 || ent->modelindex >= bg_numItems) { + Com_Error(ERR_DROP, "BG_CanItemBeGrabbed: index out of range"); } item = &bg_itemlist[ent->modelindex]; - if ( ps ) - { - if ( ps->trueJedi ) - {//force powers and saber only - if ( item->giType != IT_TEAM //not a flag - && item->giType != IT_ARMOR//not shields - && (item->giType != IT_WEAPON - || item->giTag != WP_SABER)//not a saber - && (item->giType != IT_HOLDABLE || item->giTag != HI_SEEKER)//not a seeker - && (item->giType != IT_POWERUP || item->giTag == PW_YSALAMIRI) )//not a force pick-up + if (ps) { + if (ps->trueJedi) { // force powers and saber only + if (item->giType != IT_TEAM // not a flag + && item->giType != IT_ARMOR // not shields + && (item->giType != IT_WEAPON || item->giTag != WP_SABER) // not a saber + && (item->giType != IT_HOLDABLE || item->giTag != HI_SEEKER) // not a seeker + && (item->giType != IT_POWERUP || item->giTag == PW_YSALAMIRI)) // not a force pick-up { return qfalse; } - } - else if ( ps->trueNonJedi ) - {//can't pick up force powerups - if ( (item->giType == IT_POWERUP && item->giTag != PW_YSALAMIRI) //if a powerup, can only can pick up ysalamiri - || (item->giType == IT_HOLDABLE && item->giTag == HI_SEEKER)//if holdable, cannot pick up seeker - || (item->giType == IT_WEAPON && item->giTag == WP_SABER ) )//or if it's a saber + } else if (ps->trueNonJedi) { // can't pick up force powerups + if ((item->giType == IT_POWERUP && item->giTag != PW_YSALAMIRI) // if a powerup, can only can pick up ysalamiri + || (item->giType == IT_HOLDABLE && item->giTag == HI_SEEKER) // if holdable, cannot pick up seeker + || (item->giType == IT_WEAPON && item->giTag == WP_SABER)) // or if it's a saber { return qfalse; } } - if ( ps->isJediMaster && item && (item->giType == IT_WEAPON || item->giType == IT_AMMO)) - {//jedi master cannot pick up weapons + if (ps->isJediMaster && item && (item->giType == IT_WEAPON || item->giType == IT_AMMO)) { // jedi master cannot pick up weapons return qfalse; } - if ( ps->duelInProgress ) - { //no picking stuff up while in a duel, no matter what the type is + if (ps->duelInProgress) { // no picking stuff up while in a duel, no matter what the type is return qfalse; } - } - else - {//safety return since below code assumes a non-null ps + } else { // safety return since below code assumes a non-null ps return qfalse; } - switch( item->giType ) { + switch (item->giType) { case IT_WEAPON: - if (ent->generic1 == ps->clientNum && ent->powerups) - { + if (ent->generic1 == ps->clientNum && ent->powerups) { return qfalse; } - if (!(ent->eFlags & EF_DROPPEDWEAPON) && (ps->stats[STAT_WEAPONS] & (1 << item->giTag)) && - item->giTag != WP_THERMAL && item->giTag != WP_TRIP_MINE && item->giTag != WP_DET_PACK) - { //weaponstay stuff.. if this isn't dropped, and you already have it, you don't get it. + if (!(ent->eFlags & EF_DROPPEDWEAPON) && (ps->stats[STAT_WEAPONS] & (1 << item->giTag)) && item->giTag != WP_THERMAL && item->giTag != WP_TRIP_MINE && + item->giTag != WP_DET_PACK) { // weaponstay stuff.. if this isn't dropped, and you already have it, you don't get it. return qfalse; } - if (item->giTag == WP_THERMAL || item->giTag == WP_TRIP_MINE || item->giTag == WP_DET_PACK) - { //check to see if full on ammo for this, if so, then.. + if (item->giTag == WP_THERMAL || item->giTag == WP_TRIP_MINE || item->giTag == WP_DET_PACK) { // check to see if full on ammo for this, if so, then.. int ammoIndex = weaponData[item->giTag].ammoIndex; - if (ps->ammo[ammoIndex] >= ammoData[ammoIndex].max) - { //don't need it + if (ps->ammo[ammoIndex] >= ammoData[ammoIndex].max) { // don't need it return qfalse; } } - return qtrue; // weapons are always picked up + return qtrue; // weapons are always picked up case IT_AMMO: - if (item->giTag == -1) - { //special case for "all ammo" packs + if (item->giTag == -1) { // special case for "all ammo" packs return qtrue; } - if ( ps->ammo[item->giTag] >= ammoData[item->giTag].max) { - return qfalse; // can't hold any more + if (ps->ammo[item->giTag] >= ammoData[item->giTag].max) { + return qfalse; // can't hold any more } return qtrue; case IT_ARMOR: - if ( ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH]/* * item->giTag*/ ) { + if (ps->stats[STAT_ARMOR] >= ps->stats[STAT_MAX_HEALTH] /* * item->giTag*/) { return qfalse; } return qtrue; @@ -2127,47 +1896,40 @@ qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const play case IT_HEALTH: // small and mega healths will go over the max, otherwise // don't pick up if already at max - if ((ps->fd.forcePowersActive & (1 << FP_RAGE))) - { + if ((ps->fd.forcePowersActive & (1 << FP_RAGE))) { return qfalse; } - if ( item->quantity == 5 || item->quantity == 100 ) { - if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] * 2 ) { + if (item->quantity == 5 || item->quantity == 100) { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] * 2) { return qfalse; } return qtrue; } - if ( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] ) { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) { return qfalse; } return qtrue; case IT_POWERUP: - if (ps && (ps->powerups[PW_YSALAMIRI])) - { - if (item->giTag != PW_YSALAMIRI) - { + if (ps && (ps->powerups[PW_YSALAMIRI])) { + if (item->giTag != PW_YSALAMIRI) { return qfalse; } } - return qtrue; // powerups are always picked up + return qtrue; // powerups are always picked up case IT_TEAM: // team items, such as flags - if( gametype == GT_CTF || gametype == GT_CTY ) { + if (gametype == GT_CTF || gametype == GT_CTY) { // ent->modelindex2 is non-zero on items if they are dropped // we need to know this because we can pick up our dropped flag (and return it) // but we can't pick up our flag at base if (ps->persistant[PERS_TEAM] == TEAM_RED) { - if (item->giTag == PW_BLUEFLAG || - (item->giTag == PW_REDFLAG && ent->modelindex2) || - (item->giTag == PW_REDFLAG && ps->powerups[PW_BLUEFLAG]) ) + if (item->giTag == PW_BLUEFLAG || (item->giTag == PW_REDFLAG && ent->modelindex2) || (item->giTag == PW_REDFLAG && ps->powerups[PW_BLUEFLAG])) return qtrue; } else if (ps->persistant[PERS_TEAM] == TEAM_BLUE) { - if (item->giTag == PW_REDFLAG || - (item->giTag == PW_BLUEFLAG && ent->modelindex2) || - (item->giTag == PW_BLUEFLAG && ps->powerups[PW_REDFLAG]) ) + if (item->giTag == PW_REDFLAG || (item->giTag == PW_BLUEFLAG && ent->modelindex2) || (item->giTag == PW_BLUEFLAG && ps->powerups[PW_REDFLAG])) return qtrue; } } @@ -2175,19 +1937,18 @@ qboolean BG_CanItemBeGrabbed( int gametype, const entityState_t *ent, const play return qfalse; case IT_HOLDABLE: - if ( ps->stats[STAT_HOLDABLE_ITEMS] & (1 << item->giTag)) - { + if (ps->stats[STAT_HOLDABLE_ITEMS] & (1 << item->giTag)) { return qfalse; } return qtrue; - case IT_BAD: - Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: IT_BAD" ); - default: + case IT_BAD: + Com_Error(ERR_DROP, "BG_CanItemBeGrabbed: IT_BAD"); + default: #ifndef NDEBUG // bk0001204 - Com_Printf("BG_CanItemBeGrabbed: unknown enum %d\n", item->giType ); + Com_Printf("BG_CanItemBeGrabbed: unknown enum %d\n", item->giType); #endif - break; + break; } return qfalse; @@ -2201,60 +1962,56 @@ BG_EvaluateTrajectory ================ */ -void BG_EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void BG_EvaluateTrajectory(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorCopy( tr->trBase, result ); + VectorCopy(tr->trBase, result); break; case TR_LINEAR: - deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) * 0.001; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = sin( deltaTime * M_PI * 2 ); - VectorMA( tr->trBase, phase, tr->trDelta, result ); + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = sin(deltaTime * M_PI * 2); + VectorMA(tr->trBase, phase, tr->trDelta, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds - if ( deltaTime < 0 ) { + deltaTime = (atTime - tr->trTime) * 0.001; // milliseconds to seconds + if (deltaTime < 0) { deltaTime = 0; } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) - { + if (atTime > tr->trTime + tr->trDuration) { atTime = tr->trTime + tr->trDuration; } - //new slow-down at end - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { + // new slow-down at end + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { deltaTime = 0; + } else { // FIXME: maybe scale this somehow? So that it starts out faster and stops faster? + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)(atTime - tr->trTime)) / (float)tr->trDuration)))); } - else - {//FIXME: maybe scale this somehow? So that it starts out faster and stops faster? - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)(atTime-tr->trTime))/(float)tr->trDuration)) )); - } - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds - VectorMA( tr->trBase, deltaTime, tr->trDelta, result ); - result[2] -= 0.5 * DEFAULT_GRAVITY * deltaTime * deltaTime; // FIXME: local gravity... + deltaTime = (atTime - tr->trTime) * 0.001; // milliseconds to seconds + VectorMA(tr->trBase, deltaTime, tr->trDelta, result); + result[2] -= 0.5 * DEFAULT_GRAVITY * deltaTime * deltaTime; // FIXME: local gravity... break; default: #ifdef _GAME - Com_Error( ERR_DROP, "BG_EvaluateTrajectory: [ GAME] unknown trType: %i", tr->trType ); + Com_Error(ERR_DROP, "BG_EvaluateTrajectory: [ GAME] unknown trType: %i", tr->trType); #else - Com_Error( ERR_DROP, "BG_EvaluateTrajectory: [CGAME] unknown trType: %i", tr->trType ); + Com_Error(ERR_DROP, "BG_EvaluateTrajectory: [CGAME] unknown trType: %i", tr->trType); #endif break; } @@ -2267,50 +2024,49 @@ BG_EvaluateTrajectoryDelta For determining velocity at a given time ================ */ -void BG_EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result ) { - float deltaTime; - float phase; +void BG_EvaluateTrajectoryDelta(const trajectory_t *tr, int atTime, vec3_t result) { + float deltaTime; + float phase; - switch( tr->trType ) { + switch (tr->trType) { case TR_STATIONARY: case TR_INTERPOLATE: - VectorClear( result ); + VectorClear(result); break; case TR_LINEAR: - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_SINE: - deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration; - phase = cos( deltaTime * M_PI * 2 ); // derivative of sin = cos + deltaTime = (atTime - tr->trTime) / (float)tr->trDuration; + phase = cos(deltaTime * M_PI * 2); // derivative of sin = cos phase *= 0.5; - VectorScale( tr->trDelta, phase, result ); + VectorScale(tr->trDelta, phase, result); break; case TR_LINEAR_STOP: - if ( atTime > tr->trTime + tr->trDuration ) { - VectorClear( result ); + if (atTime > tr->trTime + tr->trDuration) { + VectorClear(result); return; } - VectorCopy( tr->trDelta, result ); + VectorCopy(tr->trDelta, result); break; case TR_NONLINEAR_STOP: - if ( atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0 ) - { - VectorClear( result ); + if (atTime - tr->trTime > tr->trDuration || atTime - tr->trTime <= 0) { + VectorClear(result); return; } - deltaTime = tr->trDuration*0.001f*((float)cos( DEG2RAD(90.0f - (90.0f*((float)(atTime-tr->trTime))/(float)tr->trDuration)) )); - VectorScale( tr->trDelta, deltaTime, result ); + deltaTime = tr->trDuration * 0.001f * ((float)cos(DEG2RAD(90.0f - (90.0f * ((float)(atTime - tr->trTime)) / (float)tr->trDuration)))); + VectorScale(tr->trDelta, deltaTime, result); break; case TR_GRAVITY: - deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds - VectorCopy( tr->trDelta, result ); - result[2] -= DEFAULT_GRAVITY * deltaTime; // FIXME: local gravity... + deltaTime = (atTime - tr->trTime) * 0.001; // milliseconds to seconds + VectorCopy(tr->trDelta, result); + result[2] -= DEFAULT_GRAVITY * deltaTime; // FIXME: local gravity... break; default: #ifdef _GAME - Com_Error( ERR_DROP, "BG_EvaluateTrajectoryDelta: [ GAME] unknown trType: %i", tr->trType ); + Com_Error(ERR_DROP, "BG_EvaluateTrajectoryDelta: [ GAME] unknown trType: %i", tr->trType); #else - Com_Error( ERR_DROP, "BG_EvaluateTrajectoryDelta: [CGAME] unknown trType: %i", tr->trType ); + Com_Error(ERR_DROP, "BG_EvaluateTrajectoryDelta: [CGAME] unknown trType: %i", tr->trType); #endif break; } @@ -2321,52 +2077,31 @@ const char *eventnames[EV_NUM_ENTITY_EVENTS] = { "EV_CLIENTJOIN", - "EV_FOOTSTEP", - "EV_FOOTSTEP_METAL", - "EV_FOOTSPLASH", - "EV_FOOTWADE", - "EV_SWIM", + "EV_FOOTSTEP", "EV_FOOTSTEP_METAL", "EV_FOOTSPLASH", "EV_FOOTWADE", "EV_SWIM", - "EV_STEP_4", - "EV_STEP_8", - "EV_STEP_12", - "EV_STEP_16", + "EV_STEP_4", "EV_STEP_8", "EV_STEP_12", "EV_STEP_16", "EV_FALL", - "EV_JUMP_PAD", // boing sound at origin", jump sound on player + "EV_JUMP_PAD", // boing sound at origin", jump sound on player - "EV_GHOUL2_MARK", //create a projectile impact mark on something with a client-side g2 instance. + "EV_GHOUL2_MARK", // create a projectile impact mark on something with a client-side g2 instance. - "EV_GLOBAL_DUEL", - "EV_PRIVATE_DUEL", + "EV_GLOBAL_DUEL", "EV_PRIVATE_DUEL", - "EV_JUMP", - "EV_ROLL", - "EV_WATER_TOUCH", // foot touches - "EV_WATER_LEAVE", // foot leaves - "EV_WATER_UNDER", // head touches - "EV_WATER_CLEAR", // head leaves + "EV_JUMP", "EV_ROLL", + "EV_WATER_TOUCH", // foot touches + "EV_WATER_LEAVE", // foot leaves + "EV_WATER_UNDER", // head touches + "EV_WATER_CLEAR", // head leaves - "EV_ITEM_PICKUP", // normal item pickups are predictable - "EV_GLOBAL_ITEM_PICKUP", // powerup / team sounds are broadcast to everyone + "EV_ITEM_PICKUP", // normal item pickups are predictable + "EV_GLOBAL_ITEM_PICKUP", // powerup / team sounds are broadcast to everyone "EV_VEH_FIRE", - "EV_NOAMMO", - "EV_CHANGE_WEAPON", - "EV_FIRE_WEAPON", - "EV_ALT_FIRE", - "EV_SABER_ATTACK", - "EV_SABER_HIT", - "EV_SABER_BLOCK", - "EV_SABER_CLASHFLARE", - "EV_SABER_UNHOLSTER", - "EV_BECOME_JEDIMASTER", - "EV_DISRUPTOR_MAIN_SHOT", - "EV_DISRUPTOR_SNIPER_SHOT", - "EV_DISRUPTOR_SNIPER_MISS", - "EV_DISRUPTOR_HIT", + "EV_NOAMMO", "EV_CHANGE_WEAPON", "EV_FIRE_WEAPON", "EV_ALT_FIRE", "EV_SABER_ATTACK", "EV_SABER_HIT", "EV_SABER_BLOCK", "EV_SABER_CLASHFLARE", + "EV_SABER_UNHOLSTER", "EV_BECOME_JEDIMASTER", "EV_DISRUPTOR_MAIN_SHOT", "EV_DISRUPTOR_SNIPER_SHOT", "EV_DISRUPTOR_SNIPER_MISS", "EV_DISRUPTOR_HIT", "EV_DISRUPTOR_ZOOMSOUND", "EV_PREDEFSOUND", @@ -2377,106 +2112,67 @@ const char *eventnames[EV_NUM_ENTITY_EVENTS] = { "EV_LOCALTIMER", - "EV_USE", // +Use key - - "EV_USE_ITEM0", - "EV_USE_ITEM1", - "EV_USE_ITEM2", - "EV_USE_ITEM3", - "EV_USE_ITEM4", - "EV_USE_ITEM5", - "EV_USE_ITEM6", - "EV_USE_ITEM7", - "EV_USE_ITEM8", - "EV_USE_ITEM9", - "EV_USE_ITEM10", - "EV_USE_ITEM11", - "EV_USE_ITEM12", - "EV_USE_ITEM13", - "EV_USE_ITEM14", - "EV_USE_ITEM15", + "EV_USE", // +Use key + + "EV_USE_ITEM0", "EV_USE_ITEM1", "EV_USE_ITEM2", "EV_USE_ITEM3", "EV_USE_ITEM4", "EV_USE_ITEM5", "EV_USE_ITEM6", "EV_USE_ITEM7", "EV_USE_ITEM8", + "EV_USE_ITEM9", "EV_USE_ITEM10", "EV_USE_ITEM11", "EV_USE_ITEM12", "EV_USE_ITEM13", "EV_USE_ITEM14", "EV_USE_ITEM15", "EV_ITEMUSEFAIL", - "EV_ITEM_RESPAWN", - "EV_ITEM_POP", - "EV_PLAYER_TELEPORT_IN", - "EV_PLAYER_TELEPORT_OUT", + "EV_ITEM_RESPAWN", "EV_ITEM_POP", "EV_PLAYER_TELEPORT_IN", "EV_PLAYER_TELEPORT_OUT", - "EV_GRENADE_BOUNCE", // eventParm will be the soundindex + "EV_GRENADE_BOUNCE", // eventParm will be the soundindex "EV_MISSILE_STICK", "EV_PLAY_EFFECT", - "EV_PLAY_EFFECT_ID", //finally gave in and added it.. + "EV_PLAY_EFFECT_ID", // finally gave in and added it.. "EV_PLAY_PORTAL_EFFECT_ID", - "EV_PLAYDOORSOUND", - "EV_PLAYDOORLOOPSOUND", - "EV_BMODEL_SOUND", + "EV_PLAYDOORSOUND", "EV_PLAYDOORLOOPSOUND", "EV_BMODEL_SOUND", - "EV_MUTE_SOUND", - "EV_VOICECMD_SOUND", - "EV_GENERAL_SOUND", - "EV_GLOBAL_SOUND", // no attenuation - "EV_GLOBAL_TEAM_SOUND", - "EV_ENTITY_SOUND", + "EV_MUTE_SOUND", "EV_VOICECMD_SOUND", "EV_GENERAL_SOUND", + "EV_GLOBAL_SOUND", // no attenuation + "EV_GLOBAL_TEAM_SOUND", "EV_ENTITY_SOUND", "EV_PLAY_ROFF", - "EV_GLASS_SHATTER", - "EV_DEBRIS", - "EV_MISC_MODEL_EXP", + "EV_GLASS_SHATTER", "EV_DEBRIS", "EV_MISC_MODEL_EXP", "EV_CONC_ALT_IMPACT", - "EV_MISSILE_HIT", - "EV_MISSILE_MISS", - "EV_MISSILE_MISS_METAL", - "EV_BULLET", // otherEntity is the shooter - - "EV_PAIN", - "EV_DEATH1", - "EV_DEATH2", - "EV_DEATH3", - "EV_OBITUARY", - - #ifdef BASE_COMPAT - "EV_POWERUP_QUAD", - "EV_POWERUP_BATTLESUIT", - #endif // BASE_COMPAT + "EV_MISSILE_HIT", "EV_MISSILE_MISS", "EV_MISSILE_MISS_METAL", + "EV_BULLET", // otherEntity is the shooter + + "EV_PAIN", "EV_DEATH1", "EV_DEATH2", "EV_DEATH3", "EV_OBITUARY", + +#ifdef BASE_COMPAT + "EV_POWERUP_QUAD", "EV_POWERUP_BATTLESUIT", +#endif // BASE_COMPAT //"EV_POWERUP_REGEN", "EV_FORCE_DRAINED", - "EV_GIB_PLAYER", // gib a previously living player - "EV_SCOREPLUM", // score plum + "EV_GIB_PLAYER", // gib a previously living player + "EV_SCOREPLUM", // score plum "EV_CTFMESSAGE", "EV_BODYFADE", - "EV_SIEGE_ROUNDOVER", - "EV_SIEGE_OBJECTIVECOMPLETE", + "EV_SIEGE_ROUNDOVER", "EV_SIEGE_OBJECTIVECOMPLETE", "EV_DESTROY_GHOUL2_INSTANCE", "EV_DESTROY_WEAPON_MODEL", - "EV_GIVE_NEW_RANK", - "EV_SET_FREE_SABER", - "EV_SET_FORCE_DISABLE", + "EV_GIVE_NEW_RANK", "EV_SET_FREE_SABER", "EV_SET_FORCE_DISABLE", - "EV_WEAPON_CHARGE", - "EV_WEAPON_CHARGE_ALT", + "EV_WEAPON_CHARGE", "EV_WEAPON_CHARGE_ALT", "EV_SHIELD_HIT", - "EV_DEBUG_LINE", - "EV_TESTLINE", - "EV_STOPLOOPINGSOUND", - "EV_STARTLOOPINGSOUND", - "EV_TAUNT", -//fixme, added a bunch that aren't here! + "EV_DEBUG_LINE", "EV_TESTLINE", "EV_STOPLOOPINGSOUND", "EV_STARTLOOPINGSOUND", "EV_TAUNT", + // fixme, added a bunch that aren't here! }; /* @@ -2487,30 +2183,31 @@ Handles the sequence numbers =============== */ -void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps ) { +void BG_AddPredictableEventToPlayerstate(int newEvent, int eventParm, playerState_t *ps) { #ifdef _DEBUG { - static vmCvar_t showEvents; - static qboolean isRegistered = qfalse; + static vmCvar_t showEvents; + static qboolean isRegistered = qfalse; - if (!isRegistered) - { + if (!isRegistered) { trap->Cvar_Register(&showEvents, "showevents", "0", 0); isRegistered = qtrue; } - if ( showEvents.integer != 0 ) { + if (showEvents.integer != 0) { #ifdef _GAME - Com_Printf(" game event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm); + Com_Printf(" game event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount /*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], + eventParm); #else - Com_Printf("Cgame event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm); + Com_Printf("Cgame event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount /*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], + eventParm); #endif } } #endif - ps->events[ps->eventSequence & (MAX_PS_EVENTS-1)] = newEvent; - ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS-1)] = eventParm; + ps->events[ps->eventSequence & (MAX_PS_EVENTS - 1)] = newEvent; + ps->eventParms[ps->eventSequence & (MAX_PS_EVENTS - 1)] = eventParm; ps->eventSequence++; } @@ -2519,9 +2216,9 @@ void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerSta BG_TouchJumpPad ======================== */ -void BG_TouchJumpPad( playerState_t *ps, entityState_t *jumppad ) { +void BG_TouchJumpPad(playerState_t *ps, entityState_t *jumppad) { // spectators don't use jump pads - if ( ps->pm_type != PM_NORMAL && ps->pm_type != PM_JETPACK && ps->pm_type != PM_FLOAT ) { + if (ps->pm_type != PM_NORMAL && ps->pm_type != PM_JETPACK && ps->pm_type != PM_FLOAT) { return; } @@ -2542,9 +2239,9 @@ void BG_TouchJumpPad( playerState_t *ps, entityState_t *jumppad ) { ps->jumppad_ent = jumppad->number; ps->jumppad_frame = ps->pmove_framecount; // give the player the velocity from the jumppad - VectorCopy( jumppad->origin2, ps->velocity ); + VectorCopy(jumppad->origin2, ps->velocity); // fix: no more force draining after bouncing the jumppad - ps->fd.forcePowersActive &= ~(1<fd.forcePowersActive &= ~(1 << FP_LEVITATION); } /* @@ -2554,38 +2251,27 @@ BG_EmplacedView Shared code for emplaced angle gun constriction ================= */ -int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint) -{ +int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint) { float dif = AngleSubtract(baseAngles[YAW], angles[YAW]); - if (dif > constraint || - dif < -constraint) - { + if (dif > constraint || dif < -constraint) { float amt; - if (dif > constraint) - { - amt = (dif-constraint); + if (dif > constraint) { + amt = (dif - constraint); dif = constraint; - } - else if (dif < -constraint) - { - amt = (dif+constraint); + } else if (dif < -constraint) { + amt = (dif + constraint); dif = -constraint; - } - else - { + } else { amt = 0.0f; } *newYaw = AngleSubtract(angles[YAW], -dif); - if (amt > 1.0f || amt < -1.0f) - { //significant, force the view + if (amt > 1.0f || amt < -1.0f) { // significant, force the view return 2; - } - else - { //just a little out of range + } else { // just a little out of range return 1; } } @@ -2593,44 +2279,30 @@ int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float const return 0; } -//To see if the client is trying to use one of the included skins not meant for MP. -//I don't much care for hardcoded strings, but this seems the best way to go. -qboolean BG_IsValidCharacterModel(const char *modelName, const char *skinName) -{ - if (!Q_stricmp(skinName, "menu")) - { +// To see if the client is trying to use one of the included skins not meant for MP. +// I don't much care for hardcoded strings, but this seems the best way to go. +qboolean BG_IsValidCharacterModel(const char *modelName, const char *skinName) { + if (!Q_stricmp(skinName, "menu")) { return qfalse; - } - else if (!Q_stricmp(modelName, "kyle")) - { - if (!Q_stricmp(skinName, "fpls")) - { + } else if (!Q_stricmp(modelName, "kyle")) { + if (!Q_stricmp(skinName, "fpls")) { return qfalse; - } - else if (!Q_stricmp(skinName, "fpls2")) - { + } else if (!Q_stricmp(skinName, "fpls2")) { return qfalse; - } - else if (!Q_stricmp(skinName, "fpls3")) - { + } else if (!Q_stricmp(skinName, "fpls3")) { return qfalse; } } return qtrue; } -qboolean BG_ValidateSkinForTeam( const char *modelName, char *skinName, int team, float *colors ) -{ - if (strlen (modelName) > 5 && Q_stricmpn (modelName, "jedi_", 5) == 0) - { //argh, it's a custom player skin! - if (team == TEAM_RED && colors) - { +qboolean BG_ValidateSkinForTeam(const char *modelName, char *skinName, int team, float *colors) { + if (strlen(modelName) > 5 && Q_stricmpn(modelName, "jedi_", 5) == 0) { // argh, it's a custom player skin! + if (team == TEAM_RED && colors) { colors[0] = 1.0f; colors[1] = 0.0f; colors[2] = 0.0f; - } - else if (team == TEAM_BLUE && colors) - { + } else if (team == TEAM_BLUE && colors) { colors[0] = 0.0f; colors[1] = 0.0f; colors[2] = 1.0f; @@ -2638,89 +2310,58 @@ qboolean BG_ValidateSkinForTeam( const char *modelName, char *skinName, int team return qtrue; } - if (team == TEAM_RED) - { - if ( Q_stricmp( "red", skinName ) != 0 ) - {//not "red" - if ( Q_stricmp( "blue", skinName ) == 0 - || Q_stricmp( "default", skinName ) == 0 - || strchr(skinName, '|')//a multi-skin playerModel - || !BG_IsValidCharacterModel(modelName, skinName) ) - { + if (team == TEAM_RED) { + if (Q_stricmp("red", skinName) != 0) { // not "red" + if (Q_stricmp("blue", skinName) == 0 || Q_stricmp("default", skinName) == 0 || strchr(skinName, '|') // a multi-skin playerModel + || !BG_IsValidCharacterModel(modelName, skinName)) { Q_strncpyz(skinName, "red", MAX_QPATH); return qfalse; - } - else - {//need to set it to red - int len = strlen( skinName ); - if ( len < 3 ) - {//too short to be "red" + } else { // need to set it to red + int len = strlen(skinName); + if (len < 3) { // too short to be "red" Q_strcat(skinName, MAX_QPATH, "_red"); - } - else - { - char *start = &skinName[len-3]; - if ( Q_strncmp( "red", start, 3 ) != 0 ) - {//doesn't already end in "red" - if ( len+4 >= MAX_QPATH ) - {//too big to append "_red" + } else { + char *start = &skinName[len - 3]; + if (Q_strncmp("red", start, 3) != 0) { // doesn't already end in "red" + if (len + 4 >= MAX_QPATH) { // too big to append "_red" Q_strncpyz(skinName, "red", MAX_QPATH); return qfalse; - } - else - { + } else { Q_strcat(skinName, MAX_QPATH, "_red"); } } } - //if file does not exist, set to "red" - if ( !BG_FileExists( va( "models/players/%s/model_%s.skin", modelName, skinName ) ) ) - { + // if file does not exist, set to "red" + if (!BG_FileExists(va("models/players/%s/model_%s.skin", modelName, skinName))) { Q_strncpyz(skinName, "red", MAX_QPATH); } return qfalse; } } - } - else if (team == TEAM_BLUE) - { - if ( Q_stricmp( "blue", skinName ) != 0 ) - { - if ( Q_stricmp( "red", skinName ) == 0 - || Q_stricmp( "default", skinName ) == 0 - || strchr(skinName, '|')//a multi-skin playerModel - || !BG_IsValidCharacterModel(modelName, skinName) ) - { + } else if (team == TEAM_BLUE) { + if (Q_stricmp("blue", skinName) != 0) { + if (Q_stricmp("red", skinName) == 0 || Q_stricmp("default", skinName) == 0 || strchr(skinName, '|') // a multi-skin playerModel + || !BG_IsValidCharacterModel(modelName, skinName)) { Q_strncpyz(skinName, "blue", MAX_QPATH); return qfalse; - } - else - {//need to set it to blue - int len = strlen( skinName ); - if ( len < 4 ) - {//too short to be "blue" + } else { // need to set it to blue + int len = strlen(skinName); + if (len < 4) { // too short to be "blue" Q_strcat(skinName, MAX_QPATH, "_blue"); - } - else - { - char *start = &skinName[len-4]; - if ( Q_strncmp( "blue", start, 4 ) != 0 ) - {//doesn't already end in "blue" - if ( len+5 >= MAX_QPATH ) - {//too big to append "_blue" + } else { + char *start = &skinName[len - 4]; + if (Q_strncmp("blue", start, 4) != 0) { // doesn't already end in "blue" + if (len + 5 >= MAX_QPATH) { // too big to append "_blue" Q_strncpyz(skinName, "blue", MAX_QPATH); return qfalse; - } - else - { + } else { Q_strcat(skinName, MAX_QPATH, "_blue"); } } } - //if file does not exist, set to "blue" - if ( !BG_FileExists( va( "models/players/%s/model_%s.skin", modelName, skinName ) ) ) - { + // if file does not exist, set to "blue" + if (!BG_FileExists(va("models/players/%s/model_%s.skin", modelName, skinName))) { Q_strncpyz(skinName, "blue", MAX_QPATH); } return qfalse; @@ -2738,12 +2379,12 @@ This is done after each set of usercmd_t on the server, and after local prediction on the client ======================== */ -void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean snap ) { - int i; +void BG_PlayerStateToEntityState(playerState_t *ps, entityState_t *s, qboolean snap) { + int i; - if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) { + if (ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) { s->eType = ET_INVISIBLE; - } else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) { + } else if (ps->stats[STAT_HEALTH] <= GIB_HEALTH) { s->eType = ET_INVISIBLE; } else { s->eType = ET_PLAYER; @@ -2752,17 +2393,17 @@ void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean s->number = ps->clientNum; s->pos.trType = TR_INTERPOLATE; - VectorCopy( ps->origin, s->pos.trBase ); - if ( snap ) { - SnapVector( s->pos.trBase ); + VectorCopy(ps->origin, s->pos.trBase); + if (snap) { + SnapVector(s->pos.trBase); } // set the trDelta for flag direction - VectorCopy( ps->velocity, s->pos.trDelta ); + VectorCopy(ps->velocity, s->pos.trDelta); s->apos.trType = TR_INTERPOLATE; - VectorCopy( ps->viewangles, s->apos.trBase ); - if ( snap ) { - SnapVector( s->apos.trBase ); + VectorCopy(ps->viewangles, s->apos.trBase); + if (snap) { + SnapVector(s->apos.trBase); } s->trickedentindex = ps->fd.forceMindtrickTargetIndex; @@ -2787,8 +2428,8 @@ void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean s->legsFlip = ps->legsFlip; s->torsoFlip = ps->torsoFlip; - s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number - // so corpses can also reference the proper config + s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number + // so corpses can also reference the proper config s->eFlags = ps->eFlags; s->eFlags2 = ps->eFlags2; @@ -2797,12 +2438,9 @@ void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean s->saberMove = ps->saberMove; s->forcePowersActive = ps->fd.forcePowersActive; - if (ps->duelInProgress) - { + if (ps->duelInProgress) { s->bolt1 = 1; - } - else - { + } else { s->bolt1 = 0; } @@ -2810,39 +2448,37 @@ void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean s->saberHolstered = ps->saberHolstered; - if (ps->genericEnemyIndex != -1) - { + if (ps->genericEnemyIndex != -1) { s->eFlags |= EF_SEEKERDRONE; } - if ( ps->stats[STAT_HEALTH] <= 0 ) { + if (ps->stats[STAT_HEALTH] <= 0) { s->eFlags |= EF_DEAD; } else { s->eFlags &= ~EF_DEAD; } - if ( ps->externalEvent ) { + if (ps->externalEvent) { s->event = ps->externalEvent; s->eventParm = ps->externalEventParm; - } else if ( ps->entityEventSequence < ps->eventSequence ) { - int seq; + } else if (ps->entityEventSequence < ps->eventSequence) { + int seq; - if ( ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) { + if (ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) { ps->entityEventSequence = ps->eventSequence - MAX_PS_EVENTS; } - seq = ps->entityEventSequence & (MAX_PS_EVENTS-1); - s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 ); - s->eventParm = ps->eventParms[ seq ]; + seq = ps->entityEventSequence & (MAX_PS_EVENTS - 1); + s->event = ps->events[seq] | ((ps->entityEventSequence & 3) << 8); + s->eventParm = ps->eventParms[seq]; ps->entityEventSequence++; } - s->weapon = ps->weapon; s->groundEntityNum = ps->groundEntityNum; s->powerups = 0; - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { - if ( ps->powerups[ i ] ) { + for (i = 0; i < MAX_POWERUPS; i++) { + if (ps->powerups[i]) { s->powerups |= 1 << i; } } @@ -2850,7 +2486,7 @@ void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, qboolean s->loopSound = ps->loopSound; s->generic1 = ps->generic1; - //NOT INCLUDED IN ENTITYSTATETOPLAYERSTATE: + // NOT INCLUDED IN ENTITYSTATETOPLAYERSTATE: s->modelindex2 = ps->weaponstate; s->constantLight = ps->weaponChargeTime; @@ -2888,12 +2524,12 @@ This is done after each set of usercmd_t on the server, and after local prediction on the client ======================== */ -void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s, int time, qboolean snap ) { - int i; +void BG_PlayerStateToEntityStateExtraPolate(playerState_t *ps, entityState_t *s, int time, qboolean snap) { + int i; - if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR ) { + if (ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) { s->eType = ET_INVISIBLE; - } else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) { + } else if (ps->stats[STAT_HEALTH] <= GIB_HEALTH) { s->eType = ET_INVISIBLE; } else { s->eType = ET_PLAYER; @@ -2902,21 +2538,21 @@ void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s s->number = ps->clientNum; s->pos.trType = TR_LINEAR_STOP; - VectorCopy( ps->origin, s->pos.trBase ); - if ( snap ) { - SnapVector( s->pos.trBase ); + VectorCopy(ps->origin, s->pos.trBase); + if (snap) { + SnapVector(s->pos.trBase); } // set the trDelta for flag direction and linear prediction - VectorCopy( ps->velocity, s->pos.trDelta ); + VectorCopy(ps->velocity, s->pos.trDelta); // set the time for linear prediction s->pos.trTime = time; // set maximum extra polation time s->pos.trDuration = 50; // 1000 / sv_fps (default = 20) s->apos.trType = TR_INTERPOLATE; - VectorCopy( ps->viewangles, s->apos.trBase ); - if ( snap ) { - SnapVector( s->apos.trBase ); + VectorCopy(ps->viewangles, s->apos.trBase); + if (snap) { + SnapVector(s->apos.trBase); } s->trickedentindex = ps->fd.forceMindtrickTargetIndex; @@ -2941,8 +2577,8 @@ void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s s->legsFlip = ps->legsFlip; s->torsoFlip = ps->torsoFlip; - s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number - // so corpses can also reference the proper config + s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number + // so corpses can also reference the proper config s->eFlags = ps->eFlags; s->eFlags2 = ps->eFlags2; @@ -2951,12 +2587,9 @@ void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s s->saberMove = ps->saberMove; s->forcePowersActive = ps->fd.forcePowersActive; - if (ps->duelInProgress) - { + if (ps->duelInProgress) { s->bolt1 = 1; - } - else - { + } else { s->bolt1 = 0; } @@ -2964,37 +2597,36 @@ void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s s->saberHolstered = ps->saberHolstered; - if (ps->genericEnemyIndex != -1) - { + if (ps->genericEnemyIndex != -1) { s->eFlags |= EF_SEEKERDRONE; } - if ( ps->stats[STAT_HEALTH] <= 0 ) { + if (ps->stats[STAT_HEALTH] <= 0) { s->eFlags |= EF_DEAD; } else { s->eFlags &= ~EF_DEAD; } - if ( ps->externalEvent ) { + if (ps->externalEvent) { s->event = ps->externalEvent; s->eventParm = ps->externalEventParm; - } else if ( ps->entityEventSequence < ps->eventSequence ) { - int seq; + } else if (ps->entityEventSequence < ps->eventSequence) { + int seq; - if ( ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) { + if (ps->entityEventSequence < ps->eventSequence - MAX_PS_EVENTS) { ps->entityEventSequence = ps->eventSequence - MAX_PS_EVENTS; } - seq = ps->entityEventSequence & (MAX_PS_EVENTS-1); - s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 ); - s->eventParm = ps->eventParms[ seq ]; + seq = ps->entityEventSequence & (MAX_PS_EVENTS - 1); + s->event = ps->events[seq] | ((ps->entityEventSequence & 3) << 8); + s->eventParm = ps->eventParms[seq]; ps->entityEventSequence++; } s->weapon = ps->weapon; s->groundEntityNum = ps->groundEntityNum; s->powerups = 0; - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { - if ( ps->powerups[ i ] ) { + for (i = 0; i < MAX_POWERUPS; i++) { + if (ps->powerups[i]) { s->powerups |= 1 << i; } } @@ -3002,7 +2634,7 @@ void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s s->loopSound = ps->loopSound; s->generic1 = ps->generic1; - //NOT INCLUDED IN ENTITYSTATETOPLAYERSTATE: + // NOT INCLUDED IN ENTITYSTATETOPLAYERSTATE: s->modelindex2 = ps->weaponstate; s->constantLight = ps->weaponChargeTime; @@ -3040,90 +2672,81 @@ PLAYER ANGLES ============================================================================= */ -int BG_ModelCache(const char *modelName, const char *skinName) -{ - #ifdef _GAME - void *g2 = NULL; +int BG_ModelCache(const char *modelName, const char *skinName) { +#ifdef _GAME + void *g2 = NULL; - if ( VALIDSTRING( skinName ) ) - trap->R_RegisterSkin( skinName ); + if (VALIDSTRING(skinName)) + trap->R_RegisterSkin(skinName); - //I could hook up a precache ghoul2 function, but oh well, this works - trap->G2API_InitGhoul2Model( &g2, modelName, 0, 0, 0, 0, 0 ); - //now get rid of it - if ( g2 ) - trap->G2API_CleanGhoul2Models( &g2 ); + // I could hook up a precache ghoul2 function, but oh well, this works + trap->G2API_InitGhoul2Model(&g2, modelName, 0, 0, 0, 0, 0); + // now get rid of it + if (g2) + trap->G2API_CleanGhoul2Models(&g2); - return 0; - #else // !_GAME - if ( VALIDSTRING( skinName ) ) - { - #ifdef _CGAME - trap->R_RegisterSkin( skinName ); - #else // !_CGAME - trap->R_RegisterSkin( skinName ); - #endif // _CGAME - } - #ifdef _CGAME - return trap->R_RegisterModel( modelName ); - #else // !_CGAME - return trap->R_RegisterModel( modelName ); - #endif // _CGAME - #endif // _GAME + return 0; +#else // !_GAME + if (VALIDSTRING(skinName)) { +#ifdef _CGAME + trap->R_RegisterSkin(skinName); +#else // !_CGAME + trap->R_RegisterSkin(skinName); +#endif // _CGAME + } +#ifdef _CGAME + return trap->R_RegisterModel(modelName); +#else // !_CGAME + return trap->R_RegisterModel(modelName); +#endif // _CGAME +#endif // _GAME } #if defined(_GAME) - #define MAX_POOL_SIZE 3000000 //1024000 -#elif defined(_CGAME) //don't need as much for cgame stuff. 2mb will be fine. - #define MAX_POOL_SIZE 2048000 -#elif defined(UI_BUILD) //And for the ui the only thing we'll be using this for anyway is allocating anim data for g2 menu models - #define MAX_POOL_SIZE 512000 +#define MAX_POOL_SIZE 3000000 // 1024000 +#elif defined(_CGAME) // don't need as much for cgame stuff. 2mb will be fine. +#define MAX_POOL_SIZE 2048000 +#elif defined(UI_BUILD) // And for the ui the only thing we'll be using this for anyway is allocating anim data for g2 menu models +#define MAX_POOL_SIZE 512000 #endif -//I am using this for all the stuff like NPC client structures on server/client and -//non-humanoid animations as well until/if I can get dynamic memory working properly -//with casted datatypes, which is why it is so large. +// I am using this for all the stuff like NPC client structures on server/client and +// non-humanoid animations as well until/if I can get dynamic memory working properly +// with casted datatypes, which is why it is so large. +static char bg_pool[MAX_POOL_SIZE]; +static int bg_poolSize = 0; +static int bg_poolTail = MAX_POOL_SIZE; -static char bg_pool[MAX_POOL_SIZE]; -static int bg_poolSize = 0; -static int bg_poolTail = MAX_POOL_SIZE; - -void *BG_Alloc ( int size ) -{ +void *BG_Alloc(int size) { bg_poolSize = ((bg_poolSize + 0x00000003) & 0xfffffffc); - if (bg_poolSize + size > bg_poolTail) - { - Com_Error( ERR_DROP, "BG_Alloc: buffer exceeded tail (%d > %d)", bg_poolSize + size, bg_poolTail); + if (bg_poolSize + size > bg_poolTail) { + Com_Error(ERR_DROP, "BG_Alloc: buffer exceeded tail (%d > %d)", bg_poolSize + size, bg_poolTail); return 0; } bg_poolSize += size; - return &bg_pool[bg_poolSize-size]; + return &bg_pool[bg_poolSize - size]; } -void *BG_AllocUnaligned ( int size ) -{ - if (bg_poolSize + size > bg_poolTail) - { - Com_Error( ERR_DROP, "BG_AllocUnaligned: buffer exceeded tail (%d > %d)", bg_poolSize + size, bg_poolTail); +void *BG_AllocUnaligned(int size) { + if (bg_poolSize + size > bg_poolTail) { + Com_Error(ERR_DROP, "BG_AllocUnaligned: buffer exceeded tail (%d > %d)", bg_poolSize + size, bg_poolTail); return 0; } bg_poolSize += size; - return &bg_pool[bg_poolSize-size]; + return &bg_pool[bg_poolSize - size]; } -void *BG_TempAlloc( int size ) -{ +void *BG_TempAlloc(int size) { size = ((size + 0x00000003) & 0xfffffffc); - if (bg_poolTail - size < bg_poolSize) - { - Com_Error( ERR_DROP, "BG_TempAlloc: buffer exceeded head (%d > %d)", bg_poolTail - size, bg_poolSize); + if (bg_poolTail - size < bg_poolSize) { + Com_Error(ERR_DROP, "BG_TempAlloc: buffer exceeded head (%d > %d)", bg_poolTail - size, bg_poolSize); return 0; } @@ -3132,47 +2755,28 @@ void *BG_TempAlloc( int size ) return &bg_pool[bg_poolTail]; } -void BG_TempFree( int size ) -{ +void BG_TempFree(int size) { size = ((size + 0x00000003) & 0xfffffffc); - if (bg_poolTail+size > MAX_POOL_SIZE) - { - Com_Error( ERR_DROP, "BG_TempFree: tail greater than size (%d > %d)", bg_poolTail+size, MAX_POOL_SIZE ); + if (bg_poolTail + size > MAX_POOL_SIZE) { + Com_Error(ERR_DROP, "BG_TempFree: tail greater than size (%d > %d)", bg_poolTail + size, MAX_POOL_SIZE); } bg_poolTail += size; } -char *BG_StringAlloc ( const char *source ) -{ - char *dest = (char*)BG_Alloc( strlen ( source ) + 1 ); - strcpy( dest, source ); +char *BG_StringAlloc(const char *source) { + char *dest = (char *)BG_Alloc(strlen(source) + 1); + strcpy(dest, source); return dest; } -qboolean BG_OutOfMemory ( void ) -{ - return bg_poolSize >= MAX_POOL_SIZE; -} +qboolean BG_OutOfMemory(void) { return bg_poolSize >= MAX_POOL_SIZE; } -const char *gametypeStringShort[GT_MAX_GAME_TYPE] = { - "FFA", - "HOLO", - "JM", - "1v1", - "2v1", - "SP", - "TDM", - "SAGA", - "CTF", - "CTY" -}; +const char *gametypeStringShort[GT_MAX_GAME_TYPE] = {"FFA", "HOLO", "JM", "1v1", "2v1", "SP", "TDM", "SAGA", "CTF", "CTY"}; -const char *BG_GetGametypeString( int gametype ) -{ - switch ( gametype ) - { +const char *BG_GetGametypeString(int gametype) { + switch (gametype) { case GT_FFA: return "Free For All"; case GT_HOLOCRON: @@ -3200,21 +2804,27 @@ const char *BG_GetGametypeString( int gametype ) } } -int BG_GetGametypeForString( const char *gametype ) -{ - if ( !Q_stricmp( gametype, "ffa" ) - ||!Q_stricmp( gametype, "dm" ) ) return GT_FFA; - else if ( !Q_stricmp( gametype, "holocron" ) ) return GT_HOLOCRON; - else if ( !Q_stricmp( gametype, "jm" ) ) return GT_JEDIMASTER; - else if ( !Q_stricmp( gametype, "duel" ) ) return GT_DUEL; - else if ( !Q_stricmp( gametype, "powerduel" ) ) return GT_POWERDUEL; - else if ( !Q_stricmp( gametype, "sp" ) - ||!Q_stricmp( gametype, "coop" ) ) return GT_SINGLE_PLAYER; - else if ( !Q_stricmp( gametype, "tdm" ) - ||!Q_stricmp( gametype, "tffa" ) - ||!Q_stricmp( gametype, "team" ) ) return GT_TEAM; - else if ( !Q_stricmp( gametype, "siege" ) ) return GT_SIEGE; - else if ( !Q_stricmp( gametype, "ctf" ) ) return GT_CTF; - else if ( !Q_stricmp( gametype, "cty" ) ) return GT_CTY; - else return -1; +int BG_GetGametypeForString(const char *gametype) { + if (!Q_stricmp(gametype, "ffa") || !Q_stricmp(gametype, "dm")) + return GT_FFA; + else if (!Q_stricmp(gametype, "holocron")) + return GT_HOLOCRON; + else if (!Q_stricmp(gametype, "jm")) + return GT_JEDIMASTER; + else if (!Q_stricmp(gametype, "duel")) + return GT_DUEL; + else if (!Q_stricmp(gametype, "powerduel")) + return GT_POWERDUEL; + else if (!Q_stricmp(gametype, "sp") || !Q_stricmp(gametype, "coop")) + return GT_SINGLE_PLAYER; + else if (!Q_stricmp(gametype, "tdm") || !Q_stricmp(gametype, "tffa") || !Q_stricmp(gametype, "team")) + return GT_TEAM; + else if (!Q_stricmp(gametype, "siege")) + return GT_SIEGE; + else if (!Q_stricmp(gametype, "ctf")) + return GT_CTF; + else if (!Q_stricmp(gametype, "cty")) + return GT_CTY; + else + return -1; } diff --git a/codemp/game/bg_panimate.c b/codemp/game/bg_panimate.c index fa65f9d724..9683078c15 100644 --- a/codemp/game/bg_panimate.c +++ b/codemp/game/bg_panimate.c @@ -30,56 +30,52 @@ along with this program; if not, see . #include "cgame/animtable.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif -extern saberInfo_t *BG_MySaber( int clientNum, int saberNum ); +extern saberInfo_t *BG_MySaber(int clientNum, int saberNum); /* ============================================================================== BEGIN: Animation utility functions (sequence checking) ============================================================================== */ -//Called regardless of pm validity: +// Called regardless of pm validity: // VVFIXME - Most of these functions are totally stateless and stupid. Don't // need multiple copies of this, but it's much easier (and less likely to // break in the future) if I keep separate namespace versions now. -qboolean BG_SaberStanceAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_STAND1://not really a saberstance anim, actually... "saber off" stance - case BOTH_STAND2://single-saber, medium style - case BOTH_SABERFAST_STANCE://single-saber, fast style - case BOTH_SABERSLOW_STANCE://single-saber, strong style - case BOTH_SABERSTAFF_STANCE://saber staff style - case BOTH_SABERDUAL_STANCE://dual saber style +qboolean BG_SaberStanceAnim(int anim) { + switch (anim) { + case BOTH_STAND1: // not really a saberstance anim, actually... "saber off" stance + case BOTH_STAND2: // single-saber, medium style + case BOTH_SABERFAST_STANCE: // single-saber, fast style + case BOTH_SABERSLOW_STANCE: // single-saber, strong style + case BOTH_SABERSTAFF_STANCE: // saber staff style + case BOTH_SABERDUAL_STANCE: // dual saber style return qtrue; break; } return qfalse; } -qboolean BG_CrouchAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SIT1: //# Normal chair sit. - case BOTH_SIT2: //# Lotus position. - case BOTH_SIT3: //# Sitting in tired position: elbows on knees - case BOTH_CROUCH1: //# Transition from standing to crouch - case BOTH_CROUCH1IDLE: //# Crouching idle - case BOTH_CROUCH1WALK: //# Walking while crouched - case BOTH_CROUCH1WALKBACK: //# Walking while crouched - case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 - case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) - case BOTH_KNEES1: //# Tavion on her knees - case BOTH_CROUCHATTACKBACK1://FIXME: not if in middle of anim? +qboolean BG_CrouchAnim(int anim) { + switch (anim) { + case BOTH_SIT1: //# Normal chair sit. + case BOTH_SIT2: //# Lotus position. + case BOTH_SIT3: //# Sitting in tired position: elbows on knees + case BOTH_CROUCH1: //# Transition from standing to crouch + case BOTH_CROUCH1IDLE: //# Crouching idle + case BOTH_CROUCH1WALK: //# Walking while crouched + case BOTH_CROUCH1WALKBACK: //# Walking while crouched + case BOTH_CROUCH2TOSTAND1: //# going from crouch2 to stand1 + case BOTH_CROUCH3: //# Desann crouching down to Kyle (cin 9) + case BOTH_KNEES1: //# Tavion on her knees + case BOTH_CROUCHATTACKBACK1: // FIXME: not if in middle of anim? case BOTH_ROLL_STAB: return qtrue; break; @@ -87,10 +83,8 @@ qboolean BG_CrouchAnim( int anim ) return qfalse; } -qboolean BG_InSpecialJump( int anim ) -{ - switch ( (anim) ) - { +qboolean BG_InSpecialJump(int anim) { + switch ((anim)) { case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_RIGHT_STOP: case BOTH_WALL_RUN_RIGHT_FLIP: @@ -110,8 +104,8 @@ qboolean BG_InSpecialJump( int anim ) case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_ARIAL_LEFT: @@ -131,29 +125,23 @@ qboolean BG_InSpecialJump( int anim ) case BOTH_A7_SOULCAL: return qtrue; } - if ( BG_InReboundJump( anim ) ) - { + if (BG_InReboundJump(anim)) { return qtrue; } - if ( BG_InReboundHold( anim ) ) - { + if (BG_InReboundHold(anim)) { return qtrue; } - if ( BG_InReboundRelease( anim ) ) - { + if (BG_InReboundRelease(anim)) { return qtrue; } - if ( BG_InBackFlip( anim ) ) - { + if (BG_InBackFlip(anim)) { return qtrue; } return qfalse; } -qboolean BG_InSaberStandAnim( int anim ) -{ - switch ( (anim) ) - { +qboolean BG_InSaberStandAnim(int anim) { + switch ((anim)) { case BOTH_SABERFAST_STANCE: case BOTH_STAND2: case BOTH_SABERSLOW_STANCE: @@ -165,10 +153,8 @@ qboolean BG_InSaberStandAnim( int anim ) } } -qboolean BG_InReboundJump( int anim ) -{ - switch ( anim ) - { +qboolean BG_InReboundJump(int anim) { + switch (anim) { case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEWALLREBOUND_LEFT: case BOTH_FORCEWALLREBOUND_BACK: @@ -179,10 +165,8 @@ qboolean BG_InReboundJump( int anim ) return qfalse; } -qboolean BG_InReboundHold( int anim ) -{ - switch ( anim ) - { +qboolean BG_InReboundHold(int anim) { + switch (anim) { case BOTH_FORCEWALLHOLD_FORWARD: case BOTH_FORCEWALLHOLD_LEFT: case BOTH_FORCEWALLHOLD_BACK: @@ -193,10 +177,8 @@ qboolean BG_InReboundHold( int anim ) return qfalse; } -qboolean BG_InReboundRelease( int anim ) -{ - switch ( anim ) - { +qboolean BG_InReboundRelease(int anim) { + switch (anim) { case BOTH_FORCEWALLRELEASE_FORWARD: case BOTH_FORCEWALLRELEASE_LEFT: case BOTH_FORCEWALLRELEASE_BACK: @@ -207,10 +189,8 @@ qboolean BG_InReboundRelease( int anim ) return qfalse; } -qboolean BG_InBackFlip( int anim ) -{ - switch ( anim ) - { +qboolean BG_InBackFlip(int anim) { + switch (anim) { case BOTH_FLIP_BACK1: case BOTH_FLIP_BACK2: case BOTH_FLIP_BACK3: @@ -220,14 +200,12 @@ qboolean BG_InBackFlip( int anim ) return qfalse; } -qboolean BG_DirectFlippingAnim( int anim ) -{ - switch ( (anim) ) - { - case BOTH_FLIP_F: //# Flip forward - case BOTH_FLIP_B: //# Flip backwards - case BOTH_FLIP_L: //# Flip left - case BOTH_FLIP_R: //# Flip right +qboolean BG_DirectFlippingAnim(int anim) { + switch ((anim)) { + case BOTH_FLIP_F: //# Flip forward + case BOTH_FLIP_B: //# Flip backwards + case BOTH_FLIP_L: //# Flip left + case BOTH_FLIP_R: //# Flip right return qtrue; break; } @@ -235,22 +213,17 @@ qboolean BG_DirectFlippingAnim( int anim ) return qfalse; } -qboolean BG_SaberInAttackPure( int move ) -{ - if ( move >= LS_A_TL2BR && move <= LS_A_T2B ) - { +qboolean BG_SaberInAttackPure(int move) { + if (move >= LS_A_TL2BR && move <= LS_A_T2B) { return qtrue; } return qfalse; } -qboolean BG_SaberInAttack( int move ) -{ - if ( move >= LS_A_TL2BR && move <= LS_A_T2B ) - { +qboolean BG_SaberInAttack(int move) { + if (move >= LS_A_TL2BR && move <= LS_A_T2B) { return qtrue; } - switch ( move ) - { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -308,10 +281,8 @@ qboolean BG_SaberInAttack( int move ) return qfalse; } -qboolean BG_SaberInKata( int saberMove ) -{ - switch ( saberMove ) - { +qboolean BG_SaberInKata(int saberMove) { + switch (saberMove) { case LS_A1_SPECIAL: case LS_A2_SPECIAL: case LS_A3_SPECIAL: @@ -322,10 +293,8 @@ qboolean BG_SaberInKata( int saberMove ) return qfalse; } -qboolean BG_InKataAnim(int anim) -{ - switch (anim) - { +qboolean BG_InKataAnim(int anim) { + switch (anim) { case BOTH_A6_SABERPROTECT: case BOTH_A7_SOULCAL: case BOTH_A1_SPECIAL: @@ -336,10 +305,8 @@ qboolean BG_InKataAnim(int anim) return qfalse; } -qboolean BG_SaberInSpecial( int move ) -{ - switch( move ) - { +qboolean BG_SaberInSpecial(int move) { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -396,10 +363,8 @@ qboolean BG_SaberInSpecial( int move ) return qfalse; } -qboolean BG_KickMove( int move ) -{ - switch( move ) - { +qboolean BG_KickMove(int move) { + switch (move) { case LS_KICK_F: case LS_KICK_B: case LS_KICK_R: @@ -417,10 +382,8 @@ qboolean BG_KickMove( int move ) return qfalse; } -qboolean BG_SaberInIdle( int move ) -{ - switch ( move ) - { +qboolean BG_SaberInIdle(int move) { + switch (move) { case LS_NONE: case LS_READY: case LS_DRAW: @@ -431,10 +394,8 @@ qboolean BG_SaberInIdle( int move ) return qfalse; } -qboolean BG_InExtraDefenseSaberMove( int move ) -{ - switch ( move ) - { +qboolean BG_InExtraDefenseSaberMove(int move) { + switch (move) { case LS_SPINATTACK_DUAL: case LS_SPINATTACK: case LS_DUAL_SPIN_PROTECT: @@ -449,14 +410,12 @@ qboolean BG_InExtraDefenseSaberMove( int move ) return qfalse; } -qboolean BG_FlippingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_FLIP_F: //# Flip forward - case BOTH_FLIP_B: //# Flip backwards - case BOTH_FLIP_L: //# Flip left - case BOTH_FLIP_R: //# Flip right +qboolean BG_FlippingAnim(int anim) { + switch (anim) { + case BOTH_FLIP_F: //# Flip forward + case BOTH_FLIP_B: //# Flip backwards + case BOTH_FLIP_L: //# Flip left + case BOTH_FLIP_R: //# Flip right case BOTH_WALL_RUN_RIGHT_FLIP: case BOTH_WALL_RUN_LEFT_FLIP: case BOTH_WALL_FLIP_RIGHT: @@ -465,7 +424,7 @@ qboolean BG_FlippingAnim( int anim ) case BOTH_FLIP_BACK2: case BOTH_FLIP_BACK3: case BOTH_WALL_FLIP_BACK1: - //Not really flips, but... + // Not really flips, but... case BOTH_WALL_RUN_RIGHT: case BOTH_WALL_RUN_LEFT: case BOTH_WALL_RUN_RIGHT_STOP: @@ -484,7 +443,7 @@ qboolean BG_FlippingAnim( int anim ) case BOTH_JUMPFLIPSTABDOWN: case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: - //JKA + // JKA case BOTH_FORCEWALLRUNFLIP_END: case BOTH_FORCEWALLRUNFLIP_ALT: case BOTH_FLIP_ATTACK7: @@ -495,11 +454,9 @@ qboolean BG_FlippingAnim( int anim ) return qfalse; } -qboolean BG_SpinningSaberAnim( int anim ) -{ - switch ( anim ) - { - //level 1 - FIXME: level 1 will have *no* spins +qboolean BG_SpinningSaberAnim(int anim) { + switch (anim) { + // level 1 - FIXME: level 1 will have *no* spins case BOTH_T1_BR_BL: case BOTH_T1__R__L: case BOTH_T1__R_BL: @@ -512,28 +469,28 @@ qboolean BG_SpinningSaberAnim( int anim ) case BOTH_T1_BL_BR: case BOTH_T1_BL__R: case BOTH_T1_BL_TR: - //level 2 + // level 2 case BOTH_T2_BR__L: case BOTH_T2_BR_BL: case BOTH_T2__R_BL: case BOTH_T2__L_BR: case BOTH_T2_BL_BR: case BOTH_T2_BL__R: - //level 3 + // level 3 case BOTH_T3_BR__L: case BOTH_T3_BR_BL: case BOTH_T3__R_BL: case BOTH_T3__L_BR: case BOTH_T3_BL_BR: case BOTH_T3_BL__R: - //level 4 + // level 4 case BOTH_T4_BR__L: case BOTH_T4_BR_BL: case BOTH_T4__R_BL: case BOTH_T4__L_BR: case BOTH_T4_BL_BR: case BOTH_T4_BL__R: - //level 5 + // level 5 case BOTH_T5_BR_BL: case BOTH_T5__R__L: case BOTH_T5__R_BL: @@ -546,7 +503,7 @@ qboolean BG_SpinningSaberAnim( int anim ) case BOTH_T5_BL_BR: case BOTH_T5_BL__R: case BOTH_T5_BL_TR: - //level 6 + // level 6 case BOTH_T6_BR_TL: case BOTH_T6__R_TL: case BOTH_T6__R__L: @@ -569,7 +526,7 @@ qboolean BG_SpinningSaberAnim( int anim ) case BOTH_T6_BL_BR: case BOTH_T6_BL__R: case BOTH_T6_BL_TR: - //level 7 + // level 7 case BOTH_T7_BR_TL: case BOTH_T7_BR__L: case BOTH_T7_BR_BL: @@ -587,8 +544,8 @@ qboolean BG_SpinningSaberAnim( int anim ) case BOTH_T7_T__BR: case BOTH_T7__L_TR: case BOTH_V7_BL_S7: - //special - //case BOTH_A2_STABBACK1: + // special + // case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: case BOTH_BUTTERFLY_LEFT: @@ -603,10 +560,8 @@ qboolean BG_SpinningSaberAnim( int anim ) return qfalse; } -qboolean BG_SaberInSpecialAttack( int anim ) -{ - switch ( anim ) - { +qboolean BG_SaberInSpecialAttack(int anim) { + switch (anim) { case BOTH_A2_STABBACK1: case BOTH_ATTACK_BACK: case BOTH_CROUCHATTACKBACK1: @@ -619,8 +574,8 @@ qboolean BG_SaberInSpecialAttack( int anim ) case BOTH_FJSS_TL_BR: case BOTH_LUNGE2_B__T_: case BOTH_FORCELEAP2_T__B_: - case BOTH_JUMPFLIPSLASHDOWN1://# - case BOTH_JUMPFLIPSTABDOWN://# + case BOTH_JUMPFLIPSLASHDOWN1: //# + case BOTH_JUMPFLIPSTABDOWN: //# case BOTH_JUMPATTACK6: case BOTH_JUMPATTACK7: case BOTH_SPINATTACK6: @@ -661,10 +616,8 @@ qboolean BG_SaberInSpecialAttack( int anim ) return qfalse; } -qboolean BG_KickingAnim( int anim ) -{ - switch ( anim ) - { +qboolean BG_KickingAnim(int anim) { + switch (anim) { case BOTH_A7_KICK_F: case BOTH_A7_KICK_B: case BOTH_A7_KICK_R: @@ -677,7 +630,7 @@ qboolean BG_KickingAnim( int anim ) case BOTH_A7_KICK_R_AIR: case BOTH_A7_KICK_L_AIR: case BOTH_A7_HILT: - //NOT kicks, but do kick traces anyway + // NOT kicks, but do kick traces anyway case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: @@ -688,33 +641,29 @@ qboolean BG_KickingAnim( int anim ) return qfalse; } -int BG_InGrappleMove(int anim) -{ - switch (anim) - { +int BG_InGrappleMove(int anim) { + switch (anim) { case BOTH_KYLE_GRAB: case BOTH_KYLE_MISS: - return 1; //grabbing at someone + return 1; // grabbing at someone case BOTH_KYLE_PA_1: case BOTH_KYLE_PA_2: - return 2; //beating the shit out of someone + return 2; // beating the shit out of someone case BOTH_PLAYER_PA_1: case BOTH_PLAYER_PA_2: case BOTH_PLAYER_PA_FLY: - return 3; //getting the shit beaten out of you + return 3; // getting the shit beaten out of you break; } return 0; } -int BG_BrokenParryForAttack( int move ) -{ - //Our attack was knocked away by a knockaway parry - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( saberMoveData[move].startQuad ) - { +int BG_BrokenParryForAttack(int move) { + // Our attack was knocked away by a knockaway parry + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (saberMoveData[move].startQuad) { case Q_B: return LS_V1_B_; break; @@ -743,20 +692,15 @@ int BG_BrokenParryForAttack( int move ) return LS_NONE; } -int BG_BrokenParryForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { +int BG_BrokenParryForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { case LS_PARRY_UP: - //Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back - if ( Q_irand( 0, 1 ) ) - { + // Hmm... since we don't know what dir the hit came from, randomly pick knock down or knock back + if (Q_irand(0, 1)) { return LS_H1_B_; - } - else - { + } else { return LS_H1_T_; } break; @@ -773,42 +717,38 @@ int BG_BrokenParryForParry( int move ) return LS_H1_BL; break; case LS_READY: - return LS_H1_B_;//??? + return LS_H1_B_; //??? break; } return LS_NONE; } -int BG_KnockawayForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { - case BLOCKED_TOP://LS_PARRY_UP: - return LS_K1_T_;//push up +int BG_KnockawayForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { + case BLOCKED_TOP: // LS_PARRY_UP: + return LS_K1_T_; // push up break; - case BLOCKED_UPPER_RIGHT://LS_PARRY_UR: - default://case LS_READY: - return LS_K1_TR;//push up, slightly to right + case BLOCKED_UPPER_RIGHT: // LS_PARRY_UR: + default: // case LS_READY: + return LS_K1_TR; // push up, slightly to right break; - case BLOCKED_UPPER_LEFT://LS_PARRY_UL: - return LS_K1_TL;//push up and to left + case BLOCKED_UPPER_LEFT: // LS_PARRY_UL: + return LS_K1_TL; // push up and to left break; - case BLOCKED_LOWER_RIGHT://LS_PARRY_LR: - return LS_K1_BR;//push down and to left + case BLOCKED_LOWER_RIGHT: // LS_PARRY_LR: + return LS_K1_BR; // push down and to left break; - case BLOCKED_LOWER_LEFT://LS_PARRY_LL: - return LS_K1_BL;//push down and to right + case BLOCKED_LOWER_LEFT: // LS_PARRY_LL: + return LS_K1_BL; // push down and to right break; } - //return LS_NONE; + // return LS_NONE; } -qboolean BG_InRoll( playerState_t *ps, int anim ) -{ - switch ( (anim) ) - { +qboolean BG_InRoll(playerState_t *ps, int anim) { + switch ((anim)) { case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_BROLL_L: @@ -821,8 +761,7 @@ qboolean BG_InRoll( playerState_t *ps, int anim ) case BOTH_ROLL_B: case BOTH_ROLL_R: case BOTH_ROLL_L: - if ( ps->legsTimer > 0 ) - { + if (ps->legsTimer > 0) { return qtrue; } break; @@ -830,10 +769,8 @@ qboolean BG_InRoll( playerState_t *ps, int anim ) return qfalse; } -qboolean BG_InSpecialDeathAnim( int anim ) -{ - switch( anim ) - { +qboolean BG_InSpecialDeathAnim(int anim) { + switch (anim) { case BOTH_DEATH_ROLL: //# Death anim from a roll case BOTH_DEATH_FLIP: //# Death anim from a flip case BOTH_DEATH_SPIN_90_R: //# Death anim when facing 90 degrees right @@ -841,8 +778,8 @@ qboolean BG_InSpecialDeathAnim( int anim ) case BOTH_DEATH_SPIN_180: //# Death anim when facing backwards case BOTH_DEATH_LYING_UP: //# Death anim when lying on back case BOTH_DEATH_LYING_DN: //# Death anim when lying on front - case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face - case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back + case BOTH_DEATH_FALLING_DN: //# Death anim when falling on face + case BOTH_DEATH_FALLING_UP: //# Death anim when falling on back case BOTH_DEATH_CROUCHED: //# Death anim when crouched return qtrue; break; @@ -852,88 +789,86 @@ qboolean BG_InSpecialDeathAnim( int anim ) } } -qboolean BG_InDeathAnim ( int anim ) -{//Purposely does not cover stumbledeath and falldeath... - switch( anim ) - { - case BOTH_DEATH1: //# First Death anim - case BOTH_DEATH2: //# Second Death anim - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH8: //# - case BOTH_DEATH9: //# - case BOTH_DEATH10: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH13: //# - case BOTH_DEATH14: //# - case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) - case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) - case BOTH_DEATH15: //# - case BOTH_DEATH16: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATH20: //# - case BOTH_DEATH21: //# - case BOTH_DEATH22: //# - case BOTH_DEATH23: //# - case BOTH_DEATH24: //# - case BOTH_DEATH25: //# - - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom +qboolean BG_InDeathAnim(int anim) { // Purposely does not cover stumbledeath and falldeath... + switch (anim) { + case BOTH_DEATH1: //# First Death anim + case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH8: //# + case BOTH_DEATH9: //# + case BOTH_DEATH10: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH13: //# + case BOTH_DEATH14: //# + case BOTH_DEATH14_UNGRIP: //# Desann's end death (cin #35) + case BOTH_DEATH14_SITUP: //# Tavion sitting up after having been thrown (cin #23) + case BOTH_DEATH15: //# + case BOTH_DEATH16: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATH20: //# + case BOTH_DEATH21: //# + case BOTH_DEATH22: //# + case BOTH_DEATH23: //# + case BOTH_DEATH24: //# + case BOTH_DEATH25: //# + + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHFORWARD3: //# Tavion's falling in cin# 23 + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom //# #sep case BOTH_ DEAD POSES # Should be last frame of corresponding previous anims - case BOTH_DEAD1: //# First Death finished pose - case BOTH_DEAD2: //# Second Death finished pose - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD8: //# - case BOTH_DEAD9: //# - case BOTH_DEAD10: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD13: //# - case BOTH_DEAD14: //# - case BOTH_DEAD15: //# - case BOTH_DEAD16: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_DEAD20: //# - case BOTH_DEAD21: //# - case BOTH_DEAD22: //# - case BOTH_DEAD23: //# - case BOTH_DEAD24: //# - case BOTH_DEAD25: //# - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEAD1: //# First Death finished pose + case BOTH_DEAD2: //# Second Death finished pose + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD8: //# + case BOTH_DEAD9: //# + case BOTH_DEAD10: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD13: //# + case BOTH_DEAD14: //# + case BOTH_DEAD15: //# + case BOTH_DEAD16: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_DEAD20: //# + case BOTH_DEAD21: //# + case BOTH_DEAD22: //# + case BOTH_DEAD23: //# + case BOTH_DEAD24: //# + case BOTH_DEAD25: //# + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose //# #sep case BOTH_ DEAD TWITCH/FLOP # React to being shot from death poses case BOTH_DEADFLOP1: //# React to being shot from First Death finished pose case BOTH_DEADFLOP2: //# React to being shot from Second Death finished pose case BOTH_DISMEMBER_HEAD1: //# - case BOTH_DISMEMBER_TORSO1: //# + case BOTH_DISMEMBER_TORSO1: //# case BOTH_DISMEMBER_LLEG: //# case BOTH_DISMEMBER_RLEG: //# case BOTH_DISMEMBER_RARM: //# @@ -941,15 +876,13 @@ qboolean BG_InDeathAnim ( int anim ) return qtrue; break; default: - return BG_InSpecialDeathAnim( anim ); + return BG_InSpecialDeathAnim(anim); break; } } -qboolean BG_InKnockDownOnly( int anim ) -{ - switch ( anim ) - { +qboolean BG_InKnockDownOnly(int anim) { + switch (anim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: @@ -960,10 +893,8 @@ qboolean BG_InKnockDownOnly( int anim ) return qfalse; } -qboolean BG_InSaberLockOld( int anim ) -{ - switch ( anim ) - { +qboolean BG_InSaberLockOld(int anim) { + switch (anim) { case BOTH_BF2LOCK: case BOTH_BF1LOCK: case BOTH_CWCIRCLELOCK: @@ -973,28 +904,26 @@ qboolean BG_InSaberLockOld( int anim ) return qfalse; } -qboolean BG_InSaberLock( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_DL_T_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_ST_S_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_ST_T_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_S_S_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_S_T_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_DL_DL_S_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_T_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_ST_S_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_ST_T_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_S_S_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_S_T_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_ST_DL_S_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_DL_T_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_ST_S_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_T_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_S_S_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_S_T_L_1: //lock if I'm using staff vs. a single +qboolean BG_InSaberLock(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_DL_T_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_ST_S_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_ST_T_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_S_S_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_S_T_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_DL_DL_S_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_T_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_ST_S_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_ST_T_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_S_S_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_S_T_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_ST_DL_S_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_DL_T_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_ST_S_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_T_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_S_S_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_S_T_L_1: // lock if I'm using staff vs. a single case BOTH_LK_S_S_S_L_2: case BOTH_LK_S_S_T_L_2: case BOTH_LK_DL_DL_S_L_2: @@ -1004,17 +933,15 @@ qboolean BG_InSaberLock( int anim ) return qtrue; break; default: - return BG_InSaberLockOld( anim ); + return BG_InSaberLockOld(anim); break; } - //return qfalse; + // return qfalse; } -//Called only where pm is valid (not all require pm, but some do): -qboolean PM_InCartwheel( int anim ) -{ - switch ( anim ) - { +// Called only where pm is valid (not all require pm, but some do): +qboolean PM_InCartwheel(int anim) { + switch (anim) { case BOTH_ARIAL_LEFT: case BOTH_ARIAL_RIGHT: case BOTH_ARIAL_F1: @@ -1026,18 +953,16 @@ qboolean PM_InCartwheel( int anim ) return qfalse; } -qboolean BG_InKnockDownOnGround( playerState_t *ps ) -{ - switch ( ps->legsAnim ) - { +qboolean BG_InKnockDownOnGround(playerState_t *ps) { + switch (ps->legsAnim) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: case BOTH_KNOCKDOWN4: case BOTH_KNOCKDOWN5: case BOTH_RELEASED: - //if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) - {//at end of fall down anim + // if ( PM_AnimLength( g_entities[ps->clientNum].client->clientInfo.animFileIndex, (animNumber_t)ps->legsAnim ) - ps->legsAnimTimer > 300 ) + { // at end of fall down anim return qtrue; } break; @@ -1056,8 +981,7 @@ qboolean BG_InKnockDownOnGround( playerState_t *ps ) case BOTH_FORCE_GETUP_B4: case BOTH_FORCE_GETUP_B5: case BOTH_FORCE_GETUP_B6: - if ( BG_AnimLength( 0, (animNumber_t)ps->legsAnim ) - ps->legsTimer < 500 ) - {//at beginning of getup anim + if (BG_AnimLength(0, (animNumber_t)ps->legsAnim) - ps->legsTimer < 500) { // at beginning of getup anim return qtrue; } break; @@ -1069,20 +993,17 @@ qboolean BG_InKnockDownOnGround( playerState_t *ps ) case BOTH_GETUP_FROLL_F: case BOTH_GETUP_FROLL_L: case BOTH_GETUP_FROLL_R: - if ( BG_AnimLength( 0, (animNumber_t)ps->legsAnim ) - ps->legsTimer < 500 ) - {//at beginning of getup anim + if (BG_AnimLength(0, (animNumber_t)ps->legsAnim) - ps->legsTimer < 500) { // at beginning of getup anim return qtrue; } break; case BOTH_LK_DL_ST_T_SB_1_L: - if ( ps->legsTimer < 1000 ) - { + if (ps->legsTimer < 1000) { return qtrue; } break; case BOTH_PLAYER_PA_3_FLY: - if ( ps->legsTimer < 300 ) - { + if (ps->legsTimer < 300) { return qtrue; } break; @@ -1090,10 +1011,8 @@ qboolean BG_InKnockDownOnGround( playerState_t *ps ) return qfalse; } -qboolean BG_StabDownAnim( int anim ) -{ - switch ( anim ) - { +qboolean BG_StabDownAnim(int anim) { + switch (anim) { case BOTH_STABDOWN: case BOTH_STABDOWN_STAFF: case BOTH_STABDOWN_DUAL: @@ -1102,10 +1021,8 @@ qboolean BG_StabDownAnim( int anim ) return qfalse; } -int PM_SaberBounceForAttack( int move ) -{ - switch ( saberMoveData[move].startQuad ) - { +int PM_SaberBounceForAttack(int move) { + switch (saberMoveData[move].startQuad) { case Q_B: case Q_BR: return LS_B1_BR; @@ -1132,10 +1049,8 @@ int PM_SaberBounceForAttack( int move ) return LS_NONE; } -int PM_SaberDeflectionForQuad( int quad ) -{ - switch ( quad ) - { +int PM_SaberDeflectionForQuad(int quad) { + switch (quad) { case Q_B: return LS_D1_B_; break; @@ -1164,78 +1079,59 @@ int PM_SaberDeflectionForQuad( int quad ) return LS_NONE; } -qboolean PM_SaberInDeflect( int move ) -{ - if ( move >= LS_D1_BR && move <= LS_D1_B_ ) - { +qboolean PM_SaberInDeflect(int move) { + if (move >= LS_D1_BR && move <= LS_D1_B_) { return qtrue; } return qfalse; } -qboolean PM_SaberInParry( int move ) -{ - if ( move >= LS_PARRY_UP && move <= LS_PARRY_LL ) - { +qboolean PM_SaberInParry(int move) { + if (move >= LS_PARRY_UP && move <= LS_PARRY_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInKnockaway( int move ) -{ - if ( move >= LS_K1_T_ && move <= LS_K1_BL ) - { +qboolean PM_SaberInKnockaway(int move) { + if (move >= LS_K1_T_ && move <= LS_K1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInReflect( int move ) -{ - if ( move >= LS_REFLECT_UP && move <= LS_REFLECT_LL ) - { +qboolean PM_SaberInReflect(int move) { + if (move >= LS_REFLECT_UP && move <= LS_REFLECT_LL) { return qtrue; } return qfalse; } -qboolean PM_SaberInStart( int move ) -{ - if ( move >= LS_S_TL2BR && move <= LS_S_T2B ) - { +qboolean PM_SaberInStart(int move) { + if (move >= LS_S_TL2BR && move <= LS_S_T2B) { return qtrue; } return qfalse; } -qboolean PM_SaberInReturn( int move ) -{ - if ( move >= LS_R_TL2BR && move <= LS_R_T2B ) - { +qboolean PM_SaberInReturn(int move) { + if (move >= LS_R_TL2BR && move <= LS_R_T2B) { return qtrue; } return qfalse; } -qboolean BG_SaberInReturn( int move ) -{ - return PM_SaberInReturn( move ); -} +qboolean BG_SaberInReturn(int move) { return PM_SaberInReturn(move); } -qboolean PM_InSaberAnim( int anim ) -{ - if ( (anim) >= BOTH_A1_T__B_ && (anim) <= BOTH_H1_S1_BR ) - { +qboolean PM_InSaberAnim(int anim) { + if ((anim) >= BOTH_A1_T__B_ && (anim) <= BOTH_H1_S1_BR) { return qtrue; } return qfalse; } -qboolean PM_InKnockDown( playerState_t *ps ) -{ - switch ( (ps->legsAnim) ) - { +qboolean PM_InKnockDown(playerState_t *ps) { + switch ((ps->legsAnim)) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: @@ -1263,8 +1159,7 @@ qboolean PM_InKnockDown( playerState_t *ps ) case BOTH_GETUP_FROLL_F: case BOTH_GETUP_FROLL_L: case BOTH_GETUP_FROLL_R: - if ( ps->legsTimer ) - { + if (ps->legsTimer) { return qtrue; } break; @@ -1272,90 +1167,83 @@ qboolean PM_InKnockDown( playerState_t *ps ) return qfalse; } -qboolean PM_PainAnim( int anim ) -{ - switch ( (anim) ) - { - case BOTH_PAIN1: //# First take pain anim - case BOTH_PAIN2: //# Second take pain anim - case BOTH_PAIN3: //# Third take pain anim - case BOTH_PAIN4: //# Fourth take pain anim - case BOTH_PAIN5: //# Fifth take pain anim - from behind - case BOTH_PAIN6: //# Sixth take pain anim - from behind - case BOTH_PAIN7: //# Seventh take pain anim - from behind - case BOTH_PAIN8: //# Eigth take pain anim - from behind - case BOTH_PAIN9: //# - case BOTH_PAIN10: //# - case BOTH_PAIN11: //# - case BOTH_PAIN12: //# - case BOTH_PAIN13: //# - case BOTH_PAIN14: //# - case BOTH_PAIN15: //# - case BOTH_PAIN16: //# - case BOTH_PAIN17: //# - case BOTH_PAIN18: //# +qboolean PM_PainAnim(int anim) { + switch ((anim)) { + case BOTH_PAIN1: //# First take pain anim + case BOTH_PAIN2: //# Second take pain anim + case BOTH_PAIN3: //# Third take pain anim + case BOTH_PAIN4: //# Fourth take pain anim + case BOTH_PAIN5: //# Fifth take pain anim - from behind + case BOTH_PAIN6: //# Sixth take pain anim - from behind + case BOTH_PAIN7: //# Seventh take pain anim - from behind + case BOTH_PAIN8: //# Eigth take pain anim - from behind + case BOTH_PAIN9: //# + case BOTH_PAIN10: //# + case BOTH_PAIN11: //# + case BOTH_PAIN12: //# + case BOTH_PAIN13: //# + case BOTH_PAIN14: //# + case BOTH_PAIN15: //# + case BOTH_PAIN16: //# + case BOTH_PAIN17: //# + case BOTH_PAIN18: //# return qtrue; break; } return qfalse; } -qboolean PM_JumpingAnim( int anim ) -{ - switch ( (anim) ) - { - case BOTH_JUMP1: //# Jump - wind-up and leave ground - case BOTH_INAIR1: //# In air loop (from jump) - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_INAIRBACK1: //# In air loop (from jump back) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_INAIRLEFT1: //# In air loop (from jump left) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_INAIRRIGHT1: //# In air loop (from jump right) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground - case BOTH_FORCEINAIR1: //# In air loop (from jump) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground - case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground - case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground - case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_JumpingAnim(int anim) { + switch ((anim)) { + case BOTH_JUMP1: //# Jump - wind-up and leave ground + case BOTH_INAIR1: //# In air loop (from jump) + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_JUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_INAIRBACK1: //# In air loop (from jump back) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_JUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_INAIRLEFT1: //# In air loop (from jump left) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_JUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_INAIRRIGHT1: //# In air loop (from jump right) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + case BOTH_FORCEJUMP1: //# Jump - wind-up and leave ground + case BOTH_FORCEINAIR1: //# In air loop (from jump) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCEJUMPBACK1: //# Jump backwards - wind-up and leave ground + case BOTH_FORCEINAIRBACK1: //# In air loop (from jump back) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCEJUMPLEFT1: //# Jump left - wind-up and leave ground + case BOTH_FORCEINAIRLEFT1: //# In air loop (from jump left) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCEJUMPRIGHT1: //# Jump right - wind-up and leave ground + case BOTH_FORCEINAIRRIGHT1: //# In air loop (from jump right) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_LandingAnim( int anim ) -{ - switch ( (anim) ) - { - case BOTH_LAND1: //# Landing (from in air loop) - case BOTH_LAND2: //# Landing Hard (from a great height) - case BOTH_LANDBACK1: //# Landing backwards(from in air loop) - case BOTH_LANDLEFT1: //# Landing left(from in air loop) - case BOTH_LANDRIGHT1: //# Landing right(from in air loop) - case BOTH_FORCELAND1: //# Landing (from in air loop) - case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) - case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) - case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) +qboolean PM_LandingAnim(int anim) { + switch ((anim)) { + case BOTH_LAND1: //# Landing (from in air loop) + case BOTH_LAND2: //# Landing Hard (from a great height) + case BOTH_LANDBACK1: //# Landing backwards(from in air loop) + case BOTH_LANDLEFT1: //# Landing left(from in air loop) + case BOTH_LANDRIGHT1: //# Landing right(from in air loop) + case BOTH_FORCELAND1: //# Landing (from in air loop) + case BOTH_FORCELANDBACK1: //# Landing backwards(from in air loop) + case BOTH_FORCELANDLEFT1: //# Landing left(from in air loop) + case BOTH_FORCELANDRIGHT1: //# Landing right(from in air loop) return qtrue; break; } return qfalse; } -qboolean PM_SpinningAnim( int anim ) -{ +qboolean PM_SpinningAnim(int anim) { /* switch ( anim ) { @@ -1364,13 +1252,11 @@ qboolean PM_SpinningAnim( int anim ) break; } */ - return BG_SpinningSaberAnim( anim ); + return BG_SpinningSaberAnim(anim); } -qboolean PM_InOnGroundAnim ( int anim ) -{ - switch( anim ) - { +qboolean PM_InOnGroundAnim(int anim) { + switch (anim) { case BOTH_DEAD1: case BOTH_DEAD2: case BOTH_DEAD3: @@ -1382,12 +1268,12 @@ qboolean PM_InOnGroundAnim ( int anim ) case BOTH_DEADBACKWARD2: case BOTH_LYINGDEATH1: case BOTH_LYINGDEAD1: - case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso - case BOTH_KNOCKDOWN1: //# - case BOTH_KNOCKDOWN2: //# - case BOTH_KNOCKDOWN3: //# - case BOTH_KNOCKDOWN4: //# - case BOTH_KNOCKDOWN5: //# + case BOTH_SLEEP1: //# laying on back-rknee up-rhand on torso + case BOTH_KNOCKDOWN1: //# + case BOTH_KNOCKDOWN2: //# + case BOTH_KNOCKDOWN3: //# + case BOTH_KNOCKDOWN4: //# + case BOTH_KNOCKDOWN5: //# case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -1418,16 +1304,13 @@ qboolean PM_InOnGroundAnim ( int anim ) return qfalse; } -qboolean PM_InRollComplete( playerState_t *ps, int anim ) -{ - switch ( (anim) ) - { +qboolean PM_InRollComplete(playerState_t *ps, int anim) { + switch ((anim)) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: case BOTH_ROLL_L: - if ( ps->legsTimer < 1 ) - { + if (ps->legsTimer < 1) { return qtrue; } break; @@ -1435,129 +1318,115 @@ qboolean PM_InRollComplete( playerState_t *ps, int anim ) return qfalse; } -qboolean PM_CanRollFromSoulCal( playerState_t *ps ) -{ - if ( ps->legsAnim == BOTH_A7_SOULCAL - && ps->legsTimer < 700 - && ps->legsTimer > 250 ) - { +qboolean PM_CanRollFromSoulCal(playerState_t *ps) { + if (ps->legsAnim == BOTH_A7_SOULCAL && ps->legsTimer < 700 && ps->legsTimer > 250) { return qtrue; } return qfalse; } -qboolean BG_SuperBreakLoseAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_SB_1_L: //super break I lost - case BOTH_LK_S_DL_T_SB_1_L: //super break I lost - case BOTH_LK_S_ST_S_SB_1_L: //super break I lost - case BOTH_LK_S_ST_T_SB_1_L: //super break I lost - case BOTH_LK_S_S_S_SB_1_L: //super break I lost - case BOTH_LK_S_S_T_SB_1_L: //super break I lost - case BOTH_LK_DL_DL_S_SB_1_L: //super break I lost - case BOTH_LK_DL_DL_T_SB_1_L: //super break I lost - case BOTH_LK_DL_ST_S_SB_1_L: //super break I lost - case BOTH_LK_DL_ST_T_SB_1_L: //super break I lost - case BOTH_LK_DL_S_S_SB_1_L: //super break I lost - case BOTH_LK_DL_S_T_SB_1_L: //super break I lost - case BOTH_LK_ST_DL_S_SB_1_L: //super break I lost - case BOTH_LK_ST_DL_T_SB_1_L: //super break I lost - case BOTH_LK_ST_ST_S_SB_1_L: //super break I lost - case BOTH_LK_ST_ST_T_SB_1_L: //super break I lost - case BOTH_LK_ST_S_S_SB_1_L: //super break I lost - case BOTH_LK_ST_S_T_SB_1_L: //super break I lost +qboolean BG_SuperBreakLoseAnim(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_SB_1_L: // super break I lost + case BOTH_LK_S_DL_T_SB_1_L: // super break I lost + case BOTH_LK_S_ST_S_SB_1_L: // super break I lost + case BOTH_LK_S_ST_T_SB_1_L: // super break I lost + case BOTH_LK_S_S_S_SB_1_L: // super break I lost + case BOTH_LK_S_S_T_SB_1_L: // super break I lost + case BOTH_LK_DL_DL_S_SB_1_L: // super break I lost + case BOTH_LK_DL_DL_T_SB_1_L: // super break I lost + case BOTH_LK_DL_ST_S_SB_1_L: // super break I lost + case BOTH_LK_DL_ST_T_SB_1_L: // super break I lost + case BOTH_LK_DL_S_S_SB_1_L: // super break I lost + case BOTH_LK_DL_S_T_SB_1_L: // super break I lost + case BOTH_LK_ST_DL_S_SB_1_L: // super break I lost + case BOTH_LK_ST_DL_T_SB_1_L: // super break I lost + case BOTH_LK_ST_ST_S_SB_1_L: // super break I lost + case BOTH_LK_ST_ST_T_SB_1_L: // super break I lost + case BOTH_LK_ST_S_S_SB_1_L: // super break I lost + case BOTH_LK_ST_S_T_SB_1_L: // super break I lost return qtrue; break; } return qfalse; } -qboolean BG_SuperBreakWinAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_LK_S_DL_S_SB_1_W: //super break I won - case BOTH_LK_S_DL_T_SB_1_W: //super break I won - case BOTH_LK_S_ST_S_SB_1_W: //super break I won - case BOTH_LK_S_ST_T_SB_1_W: //super break I won - case BOTH_LK_S_S_S_SB_1_W: //super break I won - case BOTH_LK_S_S_T_SB_1_W: //super break I won - case BOTH_LK_DL_DL_S_SB_1_W: //super break I won - case BOTH_LK_DL_DL_T_SB_1_W: //super break I won - case BOTH_LK_DL_ST_S_SB_1_W: //super break I won - case BOTH_LK_DL_ST_T_SB_1_W: //super break I won - case BOTH_LK_DL_S_S_SB_1_W: //super break I won - case BOTH_LK_DL_S_T_SB_1_W: //super break I won - case BOTH_LK_ST_DL_S_SB_1_W: //super break I won - case BOTH_LK_ST_DL_T_SB_1_W: //super break I won - case BOTH_LK_ST_ST_S_SB_1_W: //super break I won - case BOTH_LK_ST_ST_T_SB_1_W: //super break I won - case BOTH_LK_ST_S_S_SB_1_W: //super break I won - case BOTH_LK_ST_S_T_SB_1_W: //super break I won +qboolean BG_SuperBreakWinAnim(int anim) { + switch (anim) { + case BOTH_LK_S_DL_S_SB_1_W: // super break I won + case BOTH_LK_S_DL_T_SB_1_W: // super break I won + case BOTH_LK_S_ST_S_SB_1_W: // super break I won + case BOTH_LK_S_ST_T_SB_1_W: // super break I won + case BOTH_LK_S_S_S_SB_1_W: // super break I won + case BOTH_LK_S_S_T_SB_1_W: // super break I won + case BOTH_LK_DL_DL_S_SB_1_W: // super break I won + case BOTH_LK_DL_DL_T_SB_1_W: // super break I won + case BOTH_LK_DL_ST_S_SB_1_W: // super break I won + case BOTH_LK_DL_ST_T_SB_1_W: // super break I won + case BOTH_LK_DL_S_S_SB_1_W: // super break I won + case BOTH_LK_DL_S_T_SB_1_W: // super break I won + case BOTH_LK_ST_DL_S_SB_1_W: // super break I won + case BOTH_LK_ST_DL_T_SB_1_W: // super break I won + case BOTH_LK_ST_ST_S_SB_1_W: // super break I won + case BOTH_LK_ST_ST_T_SB_1_W: // super break I won + case BOTH_LK_ST_S_S_SB_1_W: // super break I won + case BOTH_LK_ST_S_T_SB_1_W: // super break I won return qtrue; break; } return qfalse; } - -qboolean BG_SaberLockBreakAnim( int anim ) -{ - switch ( anim ) - { +qboolean BG_SaberLockBreakAnim(int anim) { + switch (anim) { case BOTH_BF1BREAK: case BOTH_BF2BREAK: case BOTH_CWCIRCLEBREAK: case BOTH_CCWCIRCLEBREAK: - case BOTH_LK_S_DL_S_B_1_L: //normal break I lost - case BOTH_LK_S_DL_S_B_1_W: //normal break I won - case BOTH_LK_S_DL_T_B_1_L: //normal break I lost - case BOTH_LK_S_DL_T_B_1_W: //normal break I won - case BOTH_LK_S_ST_S_B_1_L: //normal break I lost - case BOTH_LK_S_ST_S_B_1_W: //normal break I won - case BOTH_LK_S_ST_T_B_1_L: //normal break I lost - case BOTH_LK_S_ST_T_B_1_W: //normal break I won - case BOTH_LK_S_S_S_B_1_L: //normal break I lost - case BOTH_LK_S_S_S_B_1_W: //normal break I won - case BOTH_LK_S_S_T_B_1_L: //normal break I lost - case BOTH_LK_S_S_T_B_1_W: //normal break I won - case BOTH_LK_DL_DL_S_B_1_L: //normal break I lost - case BOTH_LK_DL_DL_S_B_1_W: //normal break I won - case BOTH_LK_DL_DL_T_B_1_L: //normal break I lost - case BOTH_LK_DL_DL_T_B_1_W: //normal break I won - case BOTH_LK_DL_ST_S_B_1_L: //normal break I lost - case BOTH_LK_DL_ST_S_B_1_W: //normal break I won - case BOTH_LK_DL_ST_T_B_1_L: //normal break I lost - case BOTH_LK_DL_ST_T_B_1_W: //normal break I won - case BOTH_LK_DL_S_S_B_1_L: //normal break I lost - case BOTH_LK_DL_S_S_B_1_W: //normal break I won - case BOTH_LK_DL_S_T_B_1_L: //normal break I lost - case BOTH_LK_DL_S_T_B_1_W: //normal break I won - case BOTH_LK_ST_DL_S_B_1_L: //normal break I lost - case BOTH_LK_ST_DL_S_B_1_W: //normal break I won - case BOTH_LK_ST_DL_T_B_1_L: //normal break I lost - case BOTH_LK_ST_DL_T_B_1_W: //normal break I won - case BOTH_LK_ST_ST_S_B_1_L: //normal break I lost - case BOTH_LK_ST_ST_S_B_1_W: //normal break I won - case BOTH_LK_ST_ST_T_B_1_L: //normal break I lost - case BOTH_LK_ST_ST_T_B_1_W: //normal break I won - case BOTH_LK_ST_S_S_B_1_L: //normal break I lost - case BOTH_LK_ST_S_S_B_1_W: //normal break I won - case BOTH_LK_ST_S_T_B_1_L: //normal break I lost - case BOTH_LK_ST_S_T_B_1_W: //normal break I won + case BOTH_LK_S_DL_S_B_1_L: // normal break I lost + case BOTH_LK_S_DL_S_B_1_W: // normal break I won + case BOTH_LK_S_DL_T_B_1_L: // normal break I lost + case BOTH_LK_S_DL_T_B_1_W: // normal break I won + case BOTH_LK_S_ST_S_B_1_L: // normal break I lost + case BOTH_LK_S_ST_S_B_1_W: // normal break I won + case BOTH_LK_S_ST_T_B_1_L: // normal break I lost + case BOTH_LK_S_ST_T_B_1_W: // normal break I won + case BOTH_LK_S_S_S_B_1_L: // normal break I lost + case BOTH_LK_S_S_S_B_1_W: // normal break I won + case BOTH_LK_S_S_T_B_1_L: // normal break I lost + case BOTH_LK_S_S_T_B_1_W: // normal break I won + case BOTH_LK_DL_DL_S_B_1_L: // normal break I lost + case BOTH_LK_DL_DL_S_B_1_W: // normal break I won + case BOTH_LK_DL_DL_T_B_1_L: // normal break I lost + case BOTH_LK_DL_DL_T_B_1_W: // normal break I won + case BOTH_LK_DL_ST_S_B_1_L: // normal break I lost + case BOTH_LK_DL_ST_S_B_1_W: // normal break I won + case BOTH_LK_DL_ST_T_B_1_L: // normal break I lost + case BOTH_LK_DL_ST_T_B_1_W: // normal break I won + case BOTH_LK_DL_S_S_B_1_L: // normal break I lost + case BOTH_LK_DL_S_S_B_1_W: // normal break I won + case BOTH_LK_DL_S_T_B_1_L: // normal break I lost + case BOTH_LK_DL_S_T_B_1_W: // normal break I won + case BOTH_LK_ST_DL_S_B_1_L: // normal break I lost + case BOTH_LK_ST_DL_S_B_1_W: // normal break I won + case BOTH_LK_ST_DL_T_B_1_L: // normal break I lost + case BOTH_LK_ST_DL_T_B_1_W: // normal break I won + case BOTH_LK_ST_ST_S_B_1_L: // normal break I lost + case BOTH_LK_ST_ST_S_B_1_W: // normal break I won + case BOTH_LK_ST_ST_T_B_1_L: // normal break I lost + case BOTH_LK_ST_ST_T_B_1_W: // normal break I won + case BOTH_LK_ST_S_S_B_1_L: // normal break I lost + case BOTH_LK_ST_S_S_B_1_W: // normal break I won + case BOTH_LK_ST_S_T_B_1_L: // normal break I lost + case BOTH_LK_ST_S_T_B_1_W: // normal break I won return qtrue; break; } - return (BG_SuperBreakLoseAnim(anim)||BG_SuperBreakWinAnim(anim)); + return (BG_SuperBreakLoseAnim(anim) || BG_SuperBreakWinAnim(anim)); } - -qboolean BG_FullBodyTauntAnim( int anim ) -{ - switch ( anim ) - { +qboolean BG_FullBodyTauntAnim(int anim) { + switch (anim) { case BOTH_GESTURE1: case BOTH_DUAL_TAUNT: case BOTH_STAFF_TAUNT: @@ -1579,7 +1448,6 @@ qboolean BG_FullBodyTauntAnim( int anim ) return qfalse; } - /* ============= BG_AnimLength @@ -1589,57 +1457,46 @@ and anim number. Obviously does not take things like the length of the anim while force speeding (as an example) and whatnot into account. ============= */ -int BG_AnimLength( int index, animNumber_t anim ) { - if ( (int)anim < 0 || anim >= MAX_ANIMATIONS ) { +int BG_AnimLength(int index, animNumber_t anim) { + if ((int)anim < 0 || anim >= MAX_ANIMATIONS) { return 0; } - return bgAllAnims[index].anims[anim].numFrames * fabs( (float)(bgAllAnims[index].anims[anim].frameLerp) ); + return bgAllAnims[index].anims[anim].numFrames * fabs((float)(bgAllAnims[index].anims[anim].frameLerp)); } -//just use whatever pm->animations is -int PM_AnimLength( int index, animNumber_t anim ) { - if ( !pm->animations || (int)anim < 0 || anim >= MAX_ANIMATIONS ) { +// just use whatever pm->animations is +int PM_AnimLength(int index, animNumber_t anim) { + if (!pm->animations || (int)anim < 0 || anim >= MAX_ANIMATIONS) { return 0; } - return pm->animations[anim].numFrames * fabs( (float)(pm->animations[anim].frameLerp) ); + return pm->animations[anim].numFrames * fabs((float)(pm->animations[anim].frameLerp)); } -void PM_DebugLegsAnim(int anim) -{ +void PM_DebugLegsAnim(int anim) { int oldAnim = (pm->ps->legsAnim); int newAnim = (anim); - if (oldAnim < MAX_TOTALANIMATIONS && oldAnim >= BOTH_DEATH1 && - newAnim < MAX_TOTALANIMATIONS && newAnim >= BOTH_DEATH1) - { + if (oldAnim < MAX_TOTALANIMATIONS && oldAnim >= BOTH_DEATH1 && newAnim < MAX_TOTALANIMATIONS && newAnim >= BOTH_DEATH1) { Com_Printf("OLD: %s\n", animTable[oldAnim]); Com_Printf("NEW: %s\n", animTable[newAnim]); } } -qboolean PM_SaberInTransition( int move ) -{ - if ( move >= LS_T1_BR__R && move <= LS_T1_BL__L ) - { +qboolean PM_SaberInTransition(int move) { + if (move >= LS_T1_BR__R && move <= LS_T1_BL__L) { return qtrue; } return qfalse; } -qboolean BG_SaberInTransitionAny( int move ) -{ - if ( PM_SaberInStart( move ) ) - { +qboolean BG_SaberInTransitionAny(int move) { + if (PM_SaberInStart(move)) { return qtrue; - } - else if ( PM_SaberInTransition( move ) ) - { + } else if (PM_SaberInTransition(move)) { return qtrue; - } - else if ( PM_SaberInReturn( move ) ) - { + } else if (PM_SaberInReturn(move)) { return qtrue; } return qfalse; @@ -1651,48 +1508,36 @@ END: Animation utility functions (sequence checking) ============================================================================== */ -void BG_FlipPart(playerState_t *ps, int part) -{ - if (part == SETANIM_TORSO) - { - if (ps->torsoFlip) - { +void BG_FlipPart(playerState_t *ps, int part) { + if (part == SETANIM_TORSO) { + if (ps->torsoFlip) { ps->torsoFlip = qfalse; - } - else - { + } else { ps->torsoFlip = qtrue; } - } - else if (part == SETANIM_LEGS) - { - if (ps->legsFlip) - { + } else if (part == SETANIM_LEGS) { + if (ps->legsFlip) { ps->legsFlip = qfalse; - } - else - { + } else { ps->legsFlip = qtrue; } } } -qboolean BGPAFtextLoaded = qfalse; -animation_t bgHumanoidAnimations[MAX_TOTALANIMATIONS]; //humanoid animations are the only ones that are statically allocated. +qboolean BGPAFtextLoaded = qfalse; +animation_t bgHumanoidAnimations[MAX_TOTALANIMATIONS]; // humanoid animations are the only ones that are statically allocated. bgLoadedAnim_t bgAllAnims[MAX_ANIM_FILES]; -int bgNumAllAnims = 2; //start off at 2, because 0 will always be assigned to humanoid, and 1 will always be rockettrooper +int bgNumAllAnims = 2; // start off at 2, because 0 will always be assigned to humanoid, and 1 will always be rockettrooper -//ALWAYS call on game/cgame init -void BG_InitAnimsets(void) -{ +// ALWAYS call on game/cgame init +void BG_InitAnimsets(void) { memset(&bgAllAnims, 0, sizeof(bgAllAnims)); - BGPAFtextLoaded = qfalse; // VVFIXME - The PC doesn't seem to need this, but why? + BGPAFtextLoaded = qfalse; // VVFIXME - The PC doesn't seem to need this, but why? } -//ALWAYS call on game/cgame shutdown -void BG_ClearAnimsets(void) -{ +// ALWAYS call on game/cgame shutdown +void BG_ClearAnimsets(void) { /* int i = 1; @@ -1707,16 +1552,14 @@ void BG_ClearAnimsets(void) */ } -animation_t *BG_AnimsetAlloc(void) -{ - assert (bgNumAllAnims < MAX_ANIM_FILES); - bgAllAnims[bgNumAllAnims].anims = (animation_t *) BG_Alloc(sizeof(animation_t)*MAX_TOTALANIMATIONS); +animation_t *BG_AnimsetAlloc(void) { + assert(bgNumAllAnims < MAX_ANIM_FILES); + bgAllAnims[bgNumAllAnims].anims = (animation_t *)BG_Alloc(sizeof(animation_t) * MAX_TOTALANIMATIONS); return bgAllAnims[bgNumAllAnims].anims; } -void BG_AnimsetFree(animation_t *animset) -{ +void BG_AnimsetFree(animation_t *animset) { /* if (!animset) { @@ -1734,385 +1577,318 @@ void BG_AnimsetFree(animation_t *animset) */ } -#ifdef _CGAME //none of this is actually needed serverside. Could just be moved to cgame code but it's here since it used to tie in a lot with the anim loading stuff. -stringID_table_t animEventTypeTable[MAX_ANIM_EVENTS+1] = -{ - ENUM2STRING(AEV_SOUND), //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay - ENUM2STRING(AEV_FOOTSTEP), //# animID AEV_FOOTSTEP framenum footstepType - ENUM2STRING(AEV_EFFECT), //# animID AEV_EFFECT framenum effectpath boltName - ENUM2STRING(AEV_FIRE), //# animID AEV_FIRE framenum altfire chancetofire - ENUM2STRING(AEV_MOVE), //# animID AEV_MOVE framenum forwardpush rightpush uppush - ENUM2STRING(AEV_SOUNDCHAN), //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay - ENUM2STRING(AEV_SABER_SWING), //# animID AEV_SABER_SWING framenum CHANNEL randomlow randomhi chancetoplay - ENUM2STRING(AEV_SABER_SPIN), //# animID AEV_SABER_SPIN framenum CHANNEL chancetoplay - //must be terminated - { NULL,-1 } -}; - -stringID_table_t footstepTypeTable[NUM_FOOTSTEP_TYPES+1] = -{ - ENUM2STRING(FOOTSTEP_R), - ENUM2STRING(FOOTSTEP_L), - ENUM2STRING(FOOTSTEP_HEAVY_R), - ENUM2STRING(FOOTSTEP_HEAVY_L), - //must be terminated - { NULL,-1 } -}; - -int CheckAnimFrameForEventType( animevent_t *animEvents, int keyFrame, animEventType_t eventType ) -{ +#ifdef _CGAME // none of this is actually needed serverside. Could just be moved to cgame code but it's here since it used to tie in a lot with the anim loading + // stuff. +stringID_table_t animEventTypeTable[MAX_ANIM_EVENTS + 1] = { + ENUM2STRING(AEV_SOUND), //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay + ENUM2STRING(AEV_FOOTSTEP), //# animID AEV_FOOTSTEP framenum footstepType + ENUM2STRING(AEV_EFFECT), //# animID AEV_EFFECT framenum effectpath boltName + ENUM2STRING(AEV_FIRE), //# animID AEV_FIRE framenum altfire chancetofire + ENUM2STRING(AEV_MOVE), //# animID AEV_MOVE framenum forwardpush rightpush uppush + ENUM2STRING(AEV_SOUNDCHAN), //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay + ENUM2STRING(AEV_SABER_SWING), //# animID AEV_SABER_SWING framenum CHANNEL randomlow randomhi chancetoplay + ENUM2STRING(AEV_SABER_SPIN), //# animID AEV_SABER_SPIN framenum CHANNEL chancetoplay + // must be terminated + {NULL, -1}}; + +stringID_table_t footstepTypeTable[NUM_FOOTSTEP_TYPES + 1] = {ENUM2STRING(FOOTSTEP_R), + ENUM2STRING(FOOTSTEP_L), + ENUM2STRING(FOOTSTEP_HEAVY_R), + ENUM2STRING(FOOTSTEP_HEAVY_L), + // must be terminated + {NULL, -1}}; + +int CheckAnimFrameForEventType(animevent_t *animEvents, int keyFrame, animEventType_t eventType) { int i; - for ( i = 0; i < MAX_ANIM_EVENTS; i++ ) - { - if ( animEvents[i].keyFrame == keyFrame ) - {//there is an animevent on this frame already - if ( animEvents[i].eventType == eventType ) - {//and it is of the same type + for (i = 0; i < MAX_ANIM_EVENTS; i++) { + if (animEvents[i].keyFrame == keyFrame) { // there is an animevent on this frame already + if (animEvents[i].eventType == eventType) { // and it is of the same type return i; } } } - //nope + // nope return -1; } -void ParseAnimationEvtBlock(const char *aeb_filename, animevent_t *animEvents, animation_t *animations, int *i,const char **text_p) -{ - const char *token; - int num, n, animNum, keyFrame, lowestVal, highestVal, curAnimEvent, lastAnimEvent = 0; - animEventType_t eventType; - char stringData[MAX_QPATH]; +void ParseAnimationEvtBlock(const char *aeb_filename, animevent_t *animEvents, animation_t *animations, int *i, const char **text_p) { + const char *token; + int num, n, animNum, keyFrame, lowestVal, highestVal, curAnimEvent, lastAnimEvent = 0; + animEventType_t eventType; + char stringData[MAX_QPATH]; // get past starting bracket - while(1) - { - token = COM_Parse( text_p ); - if ( !Q_stricmp( token, "{" ) ) - { + while (1) { + token = COM_Parse(text_p); + if (!Q_stricmp(token, "{")) { break; } } - //NOTE: instead of a blind increment, increase the index + // NOTE: instead of a blind increment, increase the index // this way if we have an event on an anim that already // has an event of that type, it stomps it // read information for each frame - while ( 1 ) - { - if ( lastAnimEvent >= MAX_ANIM_EVENTS ) - { - Com_Error( ERR_DROP, "ParseAnimationEvtBlock: number events in animEvent file %s > MAX_ANIM_EVENTS(%i)", aeb_filename, MAX_ANIM_EVENTS ); + while (1) { + if (lastAnimEvent >= MAX_ANIM_EVENTS) { + Com_Error(ERR_DROP, "ParseAnimationEvtBlock: number events in animEvent file %s > MAX_ANIM_EVENTS(%i)", aeb_filename, MAX_ANIM_EVENTS); return; } // Get base frame of sequence - token = COM_Parse( text_p ); - if ( !token || !token[0]) - { + token = COM_Parse(text_p); + if (!token || !token[0]) { break; } - if ( !Q_stricmp( token, "}" ) ) // At end of block + if (!Q_stricmp(token, "}")) // At end of block { break; } - //Compare to same table as animations used + // Compare to same table as animations used // so we don't have to use actual numbers for animation first frames, // just need offsets. - //This way when animation numbers change, this table won't have to be updated, + // This way when animation numbers change, this table won't have to be updated, // at least not much. animNum = GetIDForString(animTable, token); - if(animNum == -1) - {//Unrecognized ANIM ENUM name, or we're skipping this line, keep going till you get a good one - Com_Printf(S_COLOR_YELLOW"WARNING: Unknown token %s in animEvent file %s\n", token, aeb_filename ); - while (token[0]) - { - token = COM_ParseExt( text_p, qfalse ); //returns empty string when next token is EOL + if (animNum == -1) { // Unrecognized ANIM ENUM name, or we're skipping this line, keep going till you get a good one + Com_Printf(S_COLOR_YELLOW "WARNING: Unknown token %s in animEvent file %s\n", token, aeb_filename); + while (token[0]) { + token = COM_ParseExt(text_p, qfalse); // returns empty string when next token is EOL } continue; } - if ( animations[animNum].numFrames == 0 ) - {//we don't use this anim - Com_Printf(S_COLOR_YELLOW"WARNING: %s animevents.cfg: anim %s not used by this model\n", aeb_filename, token); - //skip this entry - SkipRestOfLine( text_p ); + if (animations[animNum].numFrames == 0) { // we don't use this anim + Com_Printf(S_COLOR_YELLOW "WARNING: %s animevents.cfg: anim %s not used by this model\n", aeb_filename, token); + // skip this entry + SkipRestOfLine(text_p); continue; } - token = COM_Parse( text_p ); + token = COM_Parse(text_p); eventType = (animEventType_t)GetIDForString(animEventTypeTable, token); - if ( eventType == AEV_NONE || eventType == (animEventType_t)-1 ) - {//Unrecognized ANIM EVENT TYOE, or we're skipping this line, keep going till you get a good one - //Com_Printf(S_COLOR_YELLOW"WARNING: Unknown token %s in animEvent file %s\n", token, aeb_filename ); + if (eventType == AEV_NONE || + eventType == (animEventType_t)-1) { // Unrecognized ANIM EVENT TYOE, or we're skipping this line, keep going till you get a good one + // Com_Printf(S_COLOR_YELLOW"WARNING: Unknown token %s in animEvent file %s\n", token, aeb_filename ); continue; } - //set our start frame + // set our start frame keyFrame = animations[animNum].firstFrame; // Get offset to frame within sequence - token = COM_Parse( text_p ); - if ( !token ) - { + token = COM_Parse(text_p); + if (!token) { break; } - keyFrame += atoi( token ); + keyFrame += atoi(token); - //see if this frame already has an event of this type on it, if so, overwrite it - curAnimEvent = CheckAnimFrameForEventType( animEvents, keyFrame, eventType ); - if ( curAnimEvent == -1 ) - {//this anim frame doesn't already have an event of this type on it + // see if this frame already has an event of this type on it, if so, overwrite it + curAnimEvent = CheckAnimFrameForEventType(animEvents, keyFrame, eventType); + if (curAnimEvent == -1) { // this anim frame doesn't already have an event of this type on it curAnimEvent = lastAnimEvent; } - //now that we know which event index we're going to plug the data into, start doing it + // now that we know which event index we're going to plug the data into, start doing it animEvents[curAnimEvent].eventType = eventType; animEvents[curAnimEvent].keyFrame = keyFrame; - //now read out the proper data based on the type - switch ( animEvents[curAnimEvent].eventType ) - { - case AEV_SOUNDCHAN: //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay - token = COM_Parse( text_p ); - if ( !token ) + // now read out the proper data based on the type + switch (animEvents[curAnimEvent].eventType) { + case AEV_SOUNDCHAN: //# animID AEV_SOUNDCHAN framenum CHANNEL soundpath randomlow randomhi chancetoplay + token = COM_Parse(text_p); + if (!token) break; - if ( !Q_stricmp( token, "CHAN_VOICE_ATTEN" ) ) + if (!Q_stricmp(token, "CHAN_VOICE_ATTEN")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE_ATTEN; - else if ( !Q_stricmp( token, "CHAN_VOICE_GLOBAL" ) ) + else if (!Q_stricmp(token, "CHAN_VOICE_GLOBAL")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE_GLOBAL; - else if ( !Q_stricmp( token, "CHAN_ANNOUNCER" ) ) + else if (!Q_stricmp(token, "CHAN_ANNOUNCER")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_ANNOUNCER; - else if ( !Q_stricmp( token, "CHAN_BODY" ) ) + else if (!Q_stricmp(token, "CHAN_BODY")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_BODY; - else if ( !Q_stricmp( token, "CHAN_WEAPON" ) ) + else if (!Q_stricmp(token, "CHAN_WEAPON")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_WEAPON; - else if ( !Q_stricmp( token, "CHAN_VOICE" ) ) + else if (!Q_stricmp(token, "CHAN_VOICE")) animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_VOICE; else animEvents[curAnimEvent].eventData[AED_SOUNDCHANNEL] = CHAN_AUTO; - //fall through to normal sound - case AEV_SOUND: //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay - //get soundstring - token = COM_Parse( text_p ); - if ( !token ) - { + // fall through to normal sound + case AEV_SOUND: //# animID AEV_SOUND framenum soundpath randomlow randomhi chancetoplay + // get soundstring + token = COM_Parse(text_p); + if (!token) { break; } strcpy(stringData, token); - //get lowest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get lowest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - lowestVal = atoi( token ); - //get highest value - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + lowestVal = atoi(token); + // get highest value + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - highestVal = atoi( token ); - //Now precache all the sounds - //NOTE: If we can be assured sequential handles, we can store sound indices + highestVal = atoi(token); + // Now precache all the sounds + // NOTE: If we can be assured sequential handles, we can store sound indices // instead of strings, unfortunately, if these sounds were previously // registered, we cannot be guaranteed sequential indices. Thus an array - if(lowestVal && highestVal) - { - //assert(highestVal - lowestVal < MAX_RANDOM_ANIM_SOUNDS); - if ((highestVal-lowestVal) >= MAX_RANDOM_ANIM_SOUNDS) - { - highestVal = lowestVal + (MAX_RANDOM_ANIM_SOUNDS-1); + if (lowestVal && highestVal) { + // assert(highestVal - lowestVal < MAX_RANDOM_ANIM_SOUNDS); + if ((highestVal - lowestVal) >= MAX_RANDOM_ANIM_SOUNDS) { + highestVal = lowestVal + (MAX_RANDOM_ANIM_SOUNDS - 1); } - for ( n = lowestVal, num = AED_SOUNDINDEX_START; n <= highestVal && num <= AED_SOUNDINDEX_END; n++, num++ ) - { - if (stringData[0] == '*') - { //FIXME? Would be nice to make custom sounds work with animEvents. + for (n = lowestVal, num = AED_SOUNDINDEX_START; n <= highestVal && num <= AED_SOUNDINDEX_END; n++, num++) { + if (stringData[0] == '*') { // FIXME? Would be nice to make custom sounds work with animEvents. animEvents[curAnimEvent].eventData[num] = 0; - } - else - { - animEvents[curAnimEvent].eventData[num] = trap->S_RegisterSound( va( stringData, n ) ); + } else { + animEvents[curAnimEvent].eventData[num] = trap->S_RegisterSound(va(stringData, n)); } } animEvents[curAnimEvent].eventData[AED_SOUND_NUMRANDOMSNDS] = num - 1; - } - else - { - if (stringData[0] == '*') - { //FIXME? Would be nice to make custom sounds work with animEvents. + } else { + if (stringData[0] == '*') { // FIXME? Would be nice to make custom sounds work with animEvents. animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] = 0; - } - else - { - animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] = trap->S_RegisterSound( stringData ); + } else { + animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] = trap->S_RegisterSound(stringData); } #ifndef FINAL_BUILD - if ( !animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] && - stringData[0] != '*') - {//couldn't register it - file not found - Com_Printf( S_COLOR_RED "ParseAnimationSndBlock: sound %s does not exist (animevents.cfg %s)!\n", stringData, aeb_filename ); + if (!animEvents[curAnimEvent].eventData[AED_SOUNDINDEX_START] && stringData[0] != '*') { // couldn't register it - file not found + Com_Printf(S_COLOR_RED "ParseAnimationSndBlock: sound %s does not exist (animevents.cfg %s)!\n", stringData, aeb_filename); } #endif animEvents[curAnimEvent].eventData[AED_SOUND_NUMRANDOMSNDS] = 0; } - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY] = atoi(token); - //last part - cheat and check and see if it's a special overridable saber sound we know of... - if ( !Q_stricmpn( "sound/weapons/saber/saberhup", stringData, 28 ) ) - {//a saber swing + // last part - cheat and check and see if it's a special overridable saber sound we know of... + if (!Q_stricmpn("sound/weapons/saber/saberhup", stringData, 28)) { // a saber swing animEvents[curAnimEvent].eventType = AEV_SABER_SWING; - animEvents[curAnimEvent].eventData[AED_SABER_SWING_SABERNUM] = 0;//since we don't know which one they meant if we're hacking this, always use first saber + animEvents[curAnimEvent].eventData[AED_SABER_SWING_SABERNUM] = + 0; // since we don't know which one they meant if we're hacking this, always use first saber animEvents[curAnimEvent].eventData[AED_SABER_SWING_PROBABILITY] = animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY]; - if ( lowestVal < 4 ) - {//fast swing - animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 0;//SWING_FAST; + if (lowestVal < 4) { // fast swing + animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 0; // SWING_FAST; + } else if (lowestVal < 7) { // medium swing + animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 1; // SWING_MEDIUM; + } else { // strong swing + animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 2; // SWING_STRONG; } - else if ( lowestVal < 7 ) - {//medium swing - animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 1;//SWING_MEDIUM; - } - else - {//strong swing - animEvents[curAnimEvent].eventData[AED_SABER_SWING_TYPE] = 2;//SWING_STRONG; - } - } - else if ( !Q_stricmpn( "sound/weapons/saber/saberspin", stringData, 29 ) ) - {//a saber spin + } else if (!Q_stricmpn("sound/weapons/saber/saberspin", stringData, 29)) { // a saber spin animEvents[curAnimEvent].eventType = AEV_SABER_SPIN; - animEvents[curAnimEvent].eventData[AED_SABER_SPIN_SABERNUM] = 0;//since we don't know which one they meant if we're hacking this, always use first saber + animEvents[curAnimEvent].eventData[AED_SABER_SPIN_SABERNUM] = + 0; // since we don't know which one they meant if we're hacking this, always use first saber animEvents[curAnimEvent].eventData[AED_SABER_SPIN_PROBABILITY] = animEvents[curAnimEvent].eventData[AED_SOUND_PROBABILITY]; - if ( stringData[29] == 'o' ) - {//saberspinoff + if (stringData[29] == 'o') { // saberspinoff animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 0; - } - else if ( stringData[29] == '1' ) - {//saberspin1 + } else if (stringData[29] == '1') { // saberspin1 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 2; - } - else if ( stringData[29] == '2' ) - {//saberspin2 + } else if (stringData[29] == '2') { // saberspin2 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 3; - } - else if ( stringData[29] == '3' ) - {//saberspin3 + } else if (stringData[29] == '3') { // saberspin3 animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 4; - } - else if ( stringData[29] == '%' ) - {//saberspin%d + } else if (stringData[29] == '%') { // saberspin%d animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 5; - } - else - {//just plain saberspin + } else { // just plain saberspin animEvents[curAnimEvent].eventData[AED_SABER_SPIN_TYPE] = 1; } } break; - case AEV_FOOTSTEP: //# animID AEV_FOOTSTEP framenum footstepType - //get footstep type - token = COM_Parse( text_p ); - if ( !token ) - { + case AEV_FOOTSTEP: //# animID AEV_FOOTSTEP framenum footstepType + // get footstep type + token = COM_Parse(text_p); + if (!token) { break; } animEvents[curAnimEvent].eventData[AED_FOOTSTEP_TYPE] = GetIDForString(footstepTypeTable, token); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FOOTSTEP_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_FOOTSTEP_PROBABILITY] = atoi(token); break; - case AEV_EFFECT: //# animID AEV_EFFECT framenum effectpath boltName - //get effect index - token = COM_Parse( text_p ); - if ( !token ) - { + case AEV_EFFECT: //# animID AEV_EFFECT framenum effectpath boltName + // get effect index + token = COM_Parse(text_p); + if (!token) { break; } - animEvents[curAnimEvent].eventData[AED_EFFECTINDEX] = trap->FX_RegisterEffect( token ); - //get bolt index - token = COM_Parse( text_p ); - if ( !token ) - { + animEvents[curAnimEvent].eventData[AED_EFFECTINDEX] = trap->FX_RegisterEffect(token); + // get bolt index + token = COM_Parse(text_p); + if (!token) { break; } - if ( Q_stricmp( "none", token ) != 0 && Q_stricmp( "NULL", token ) != 0 ) - {//actually are specifying a bolt to use - if (!animEvents[curAnimEvent].stringData) - { //eh, whatever. no dynamic stuff, so this will do. - animEvents[curAnimEvent].stringData = (char *) BG_Alloc(2048); + if (Q_stricmp("none", token) != 0 && Q_stricmp("NULL", token) != 0) { // actually are specifying a bolt to use + if (!animEvents[curAnimEvent].stringData) { // eh, whatever. no dynamic stuff, so this will do. + animEvents[curAnimEvent].stringData = (char *)BG_Alloc(2048); } strcpy(animEvents[curAnimEvent].stringData, token); } - //NOTE: this string will later be used to add a bolt and store the index, as below: - //animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + // NOTE: this string will later be used to add a bolt and store the index, as below: + // animEvent->eventData[AED_BOLTINDEX] = trap->G2API_AddBolt( ¢->gent->ghoul2[cent->gent->playerModel], animEvent->stringData ); + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_EFFECT_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_EFFECT_PROBABILITY] = atoi(token); break; - case AEV_FIRE: //# animID AEV_FIRE framenum altfire chancetofire - //get altfire - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + case AEV_FIRE: //# animID AEV_FIRE framenum altfire chancetofire + // get altfire + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FIRE_ALT] = atoi( token ); - //get probability - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + animEvents[curAnimEvent].eventData[AED_FIRE_ALT] = atoi(token); + // get probability + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_FIRE_PROBABILITY] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_FIRE_PROBABILITY] = atoi(token); break; - case AEV_MOVE: //# animID AEV_MOVE framenum forwardpush rightpush uppush - //get forward push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + case AEV_MOVE: //# animID AEV_MOVE framenum forwardpush rightpush uppush + // get forward push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_MOVE_FWD] = atoi( token ); - //get right push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + animEvents[curAnimEvent].eventData[AED_MOVE_FWD] = atoi(token); + // get right push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_MOVE_RT] = atoi( token ); - //get upwards push - token = COM_Parse( text_p ); - if ( !token ) - {//WARNING! BAD TABLE! + animEvents[curAnimEvent].eventData[AED_MOVE_RT] = atoi(token); + // get upwards push + token = COM_Parse(text_p); + if (!token) { // WARNING! BAD TABLE! break; } - animEvents[curAnimEvent].eventData[AED_MOVE_UP] = atoi( token ); + animEvents[curAnimEvent].eventData[AED_MOVE_UP] = atoi(token); break; - default: //unknown? - SkipRestOfLine( text_p ); + default: // unknown? + SkipRestOfLine(text_p); continue; break; } - if ( curAnimEvent == lastAnimEvent ) - { + if (curAnimEvent == lastAnimEvent) { lastAnimEvent++; } } @@ -2132,37 +1908,31 @@ This file's presence is not required bgLoadedEvents_t bgAllEvents[MAX_ANIM_FILES]; int bgNumAnimEvents = 1; static int bg_animParseIncluding = 0; -int BG_ParseAnimationEvtFile( const char *as_filename, int animFileIndex, int eventFileIndex ) -{ - const char *text_p; - int len; - const char *token; - char text[80000]; - char sfilename[MAX_QPATH]; - fileHandle_t f; - int i, j, upper_i, lower_i; - int usedIndex = -1; - animevent_t *legsAnimEvents; - animevent_t *torsoAnimEvents; - animation_t *animations; - int forcedIndex; +int BG_ParseAnimationEvtFile(const char *as_filename, int animFileIndex, int eventFileIndex) { + const char *text_p; + int len; + const char *token; + char text[80000]; + char sfilename[MAX_QPATH]; + fileHandle_t f; + int i, j, upper_i, lower_i; + int usedIndex = -1; + animevent_t *legsAnimEvents; + animevent_t *torsoAnimEvents; + animation_t *animations; + int forcedIndex; assert(animFileIndex < MAX_ANIM_FILES); assert(eventFileIndex < MAX_ANIM_FILES); - if (eventFileIndex == -1) - { + if (eventFileIndex == -1) { forcedIndex = 0; - } - else - { + } else { forcedIndex = eventFileIndex; } - if (bg_animParseIncluding <= 0) - { //if we should be parsing an included file, skip this part - if ( bgAllEvents[forcedIndex].eventsParsed ) - {//already cached this one + if (bg_animParseIncluding <= 0) { // if we should be parsing an included file, skip this part + if (bgAllEvents[forcedIndex].eventsParsed) { // already cached this one return forcedIndex; } } @@ -2171,14 +1941,11 @@ int BG_ParseAnimationEvtFile( const char *as_filename, int animFileIndex, int ev torsoAnimEvents = bgAllEvents[forcedIndex].torsoAnimEvents; animations = bgAllAnims[animFileIndex].anims; - if (bg_animParseIncluding <= 0) - { //if we should be parsing an included file, skip this part - //Go through and see if this filename is already in the table. + if (bg_animParseIncluding <= 0) { // if we should be parsing an included file, skip this part + // Go through and see if this filename is already in the table. i = 0; - while (i < bgNumAnimEvents && forcedIndex != 0) - { - if (!Q_stricmp(as_filename, bgAllEvents[i].filename)) - { //looks like we have it already. + while (i < bgNumAnimEvents && forcedIndex != 0) { + if (!Q_stricmp(as_filename, bgAllEvents[i].filename)) { // looks like we have it already. return i; } i++; @@ -2186,25 +1953,23 @@ int BG_ParseAnimationEvtFile( const char *as_filename, int animFileIndex, int ev } // Load and parse animevents.cfg file - Com_sprintf( sfilename, sizeof( sfilename ), "%sanimevents.cfg", as_filename ); + Com_sprintf(sfilename, sizeof(sfilename), "%sanimevents.cfg", as_filename); - if (bg_animParseIncluding <= 0) - { //should already be done if we're including - //initialize anim event array - for( i = 0; i < MAX_ANIM_EVENTS; i++ ) - { - //Type of event + if (bg_animParseIncluding <= 0) { // should already be done if we're including + // initialize anim event array + for (i = 0; i < MAX_ANIM_EVENTS; i++) { + // Type of event torsoAnimEvents[i].eventType = AEV_NONE; legsAnimEvents[i].eventType = AEV_NONE; - //Frame to play event on + // Frame to play event on torsoAnimEvents[i].keyFrame = -1; legsAnimEvents[i].keyFrame = -1; - //we allow storage of one string, temporarily (in case we have to look up an index later, then make sure to set stringData to NULL so we only do the look-up once) + // we allow storage of one string, temporarily (in case we have to look up an index later, then make sure to set stringData to NULL so we only do + // the look-up once) torsoAnimEvents[i].stringData = NULL; legsAnimEvents[i].stringData = NULL; - //Unique IDs, can be soundIndex of sound file to play OR effect index or footstep type, etc. - for ( j = 0; j < AED_ARRAY_SIZE; j++ ) - { + // Unique IDs, can be soundIndex of sound file to play OR effect index or footstep type, etc. + for (j = 0; j < AED_ARRAY_SIZE; j++) { torsoAnimEvents[i].eventData[j] = -1; legsAnimEvents[i].eventData[j] = -1; } @@ -2212,76 +1977,69 @@ int BG_ParseAnimationEvtFile( const char *as_filename, int animFileIndex, int ev } // load the file - len = trap->FS_Open( sfilename, &f, FS_READ ); - if ( len <= 0 ) - {//no file + len = trap->FS_Open(sfilename, &f, FS_READ); + if (len <= 0) { // no file goto fin; } - if ( len >= sizeof( text ) - 1 ) - { + if (len >= sizeof(text) - 1) { trap->FS_Close(f); #ifndef FINAL_BUILD - Com_Error(ERR_DROP, "File %s too long\n", sfilename ); + Com_Error(ERR_DROP, "File %s too long\n", sfilename); #else - Com_Printf( "File %s too long\n", sfilename ); + Com_Printf("File %s too long\n", sfilename); #endif goto fin; } - trap->FS_Read( text, len, f ); + trap->FS_Read(text, len, f); text[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); // parse the text text_p = text; - upper_i =0; - lower_i =0; + upper_i = 0; + lower_i = 0; - COM_BeginParseSession ("BG_ParseAnimationEvtFile"); + COM_BeginParseSession("BG_ParseAnimationEvtFile"); // read information for batches of sounds (UPPER or LOWER) - while ( 1 ) - { + while (1) { // Get base frame of sequence - token = COM_Parse( &text_p ); - if ( !token || !token[0] ) - { + token = COM_Parse(&text_p); + if (!token || !token[0]) { break; } - if ( !Q_stricmp(token,"include") ) // grab from another animevents.cfg - {//NOTE: you REALLY should NOT do this after the main block of UPPERSOUNDS and LOWERSOUNDS - const char *include_filename = COM_Parse( &text_p ); - if ( include_filename != NULL ) - { + if (!Q_stricmp(token, "include")) // grab from another animevents.cfg + { // NOTE: you REALLY should NOT do this after the main block of UPPERSOUNDS and LOWERSOUNDS + const char *include_filename = COM_Parse(&text_p); + if (include_filename != NULL) { char fullIPath[MAX_QPATH]; strcpy(fullIPath, va("models/players/%s/", include_filename)); bg_animParseIncluding++; - BG_ParseAnimationEvtFile( fullIPath, animFileIndex, forcedIndex ); + BG_ParseAnimationEvtFile(fullIPath, animFileIndex, forcedIndex); bg_animParseIncluding--; } } - if ( !Q_stricmp(token,"UPPEREVENTS") ) // A batch of upper sounds + if (!Q_stricmp(token, "UPPEREVENTS")) // A batch of upper sounds { - ParseAnimationEvtBlock( as_filename, torsoAnimEvents, animations, &upper_i, &text_p ); + ParseAnimationEvtBlock(as_filename, torsoAnimEvents, animations, &upper_i, &text_p); } - else if ( !Q_stricmp(token,"LOWEREVENTS") ) // A batch of lower sounds + else if (!Q_stricmp(token, "LOWEREVENTS")) // A batch of lower sounds { - ParseAnimationEvtBlock( as_filename, legsAnimEvents, animations, &lower_i, &text_p ); + ParseAnimationEvtBlock(as_filename, legsAnimEvents, animations, &lower_i, &text_p); } } usedIndex = forcedIndex; fin: - //Mark this anim set so that we know we tried to load he sounds, don't care if the load failed - if (bg_animParseIncluding <= 0) - { //if we should be parsing an included file, skip this part + // Mark this anim set so that we know we tried to load he sounds, don't care if the load failed + if (bg_animParseIncluding <= 0) { // if we should be parsing an included file, skip this part bgAllEvents[forcedIndex].eventsParsed = qtrue; strcpy(bgAllEvents[forcedIndex].filename, as_filename); - if (forcedIndex) - { + if (forcedIndex) { bgNumAnimEvents++; } } @@ -2299,63 +2057,51 @@ models/players/visor/animation.cfg, etc ====================== */ -int BG_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) -{ - char *text_p; - int len; - int i; - char *token; - float fps; - int usedIndex = -1; - int nextIndex = bgNumAllAnims; - qboolean dynAlloc = qfalse; - ///qboolean wasLoaded = qfalse; +int BG_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) { + char *text_p; + int len; + int i; + char *token; + float fps; + int usedIndex = -1; + int nextIndex = bgNumAllAnims; + qboolean dynAlloc = qfalse; + /// qboolean wasLoaded = qfalse; static char BGPAFtext[60000]; - fileHandle_t f; - int animNum; + fileHandle_t f; + int animNum; BGPAFtext[0] = '\0'; - if (!isHumanoid) - { + if (!isHumanoid) { i = 0; - while (i < bgNumAllAnims) - { //see if it's been loaded already - if (!Q_stricmp(bgAllAnims[i].filename, filename)) - { + while (i < bgNumAllAnims) { // see if it's been loaded already + if (!Q_stricmp(bgAllAnims[i].filename, filename)) { animset = bgAllAnims[i].anims; - return i; //alright, we already have it. + return i; // alright, we already have it. } i++; } - //Looks like it has not yet been loaded. Allocate space for the anim set if we need to, and continue along. - if (!animset) - { - if (strstr(filename, "players/_humanoid/")) - { //then use the static humanoid set. + // Looks like it has not yet been loaded. Allocate space for the anim set if we need to, and continue along. + if (!animset) { + if (strstr(filename, "players/_humanoid/")) { // then use the static humanoid set. animset = bgHumanoidAnimations; nextIndex = 0; - } - else if (strstr(filename, "players/rockettrooper/")) - { //rockettrooper always index 1 + } else if (strstr(filename, "players/rockettrooper/")) { // rockettrooper always index 1 nextIndex = 1; animset = BG_AnimsetAlloc(); - dynAlloc = qtrue; //so we know to free this memory in case we have to return early. Don't want any leaks. + dynAlloc = qtrue; // so we know to free this memory in case we have to return early. Don't want any leaks. - if (!animset) - { + if (!animset) { assert(!"Anim set alloc failed!"); return -1; } - } - else - { + } else { animset = BG_AnimsetAlloc(); - dynAlloc = qtrue; //so we know to free this memory in case we have to return early. Don't want any leaks. + dynAlloc = qtrue; // so we know to free this memory in case we have to return early. Don't want any leaks. - if (!animset) - { + if (!animset) { assert(!"Anim set alloc failed!"); return -1; } @@ -2363,53 +2109,44 @@ int BG_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i } } #ifdef _DEBUG - else - { + else { assert(animset); } #endif // load the file - if (!BGPAFtextLoaded || !isHumanoid) - { //rww - We are always using the same animation config now. So only load it once. - len = trap->FS_Open( filename, &f, FS_READ ); - if ( (len <= 0) || (len >= sizeof( BGPAFtext ) - 1) ) - { - trap->FS_Close( f ); - if (dynAlloc) - { + if (!BGPAFtextLoaded || !isHumanoid) { // rww - We are always using the same animation config now. So only load it once. + len = trap->FS_Open(filename, &f, FS_READ); + if ((len <= 0) || (len >= sizeof(BGPAFtext) - 1)) { + trap->FS_Close(f); + if (dynAlloc) { BG_AnimsetFree(animset); } - if (len > 0) - { + if (len > 0) { Com_Error(ERR_DROP, "%s exceeds the allowed game-side animation buffer!", filename); } return -1; } - trap->FS_Read( BGPAFtext, len, f ); + trap->FS_Read(BGPAFtext, len, f); BGPAFtext[len] = 0; - trap->FS_Close( f ); - } - else - { - if (dynAlloc) - { + trap->FS_Close(f); + } else { + if (dynAlloc) { assert(!"Should not have allocated dynamically for humanoid"); BG_AnimsetFree(animset); } - return 0; //humanoid index + return 0; // humanoid index } // parse the text text_p = BGPAFtext; - //FIXME: have some way of playing anims backwards... negative numFrames? + // FIXME: have some way of playing anims backwards... negative numFrames? - //initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 - for(i = 0; i < MAX_ANIMATIONS; i++) - { + // initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 + for (i = 0; i < MAX_ANIMATIONS; i++) { animset[i].firstFrame = 0; animset[i].numFrames = 0; animset[i].loopFrames = -1; @@ -2417,69 +2154,56 @@ int BG_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i } // read information for each frame - while(1) - { - token = COM_Parse( (const char **)(&text_p) ); + while (1) { + token = COM_Parse((const char **)(&text_p)); - if ( !token || !token[0]) - { + if (!token || !token[0]) { break; } animNum = GetIDForString(animTable, token); - if(animNum == -1) - { + if (animNum == -1) { //#ifndef FINAL_BUILD #ifdef _DEBUG - if (strcmp(token,"ROOT")) - { - Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, filename); + if (strcmp(token, "ROOT")) { + Com_Printf(S_COLOR_RED "WARNING: Unknown token %s in %s\n", token, filename); } - while (token[0]) - { - token = COM_ParseExt( (const char **) &text_p, qfalse ); //returns empty string when next token is EOL + while (token[0]) { + token = COM_ParseExt((const char **)&text_p, qfalse); // returns empty string when next token is EOL } #endif continue; } - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].firstFrame = atoi( token ); + animset[animNum].firstFrame = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].numFrames = atoi( token ); + animset[animNum].numFrames = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].loopFrames = atoi( token ); + animset[animNum].loopFrames = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - fps = atof( token ); - if ( fps == 0 ) - { - fps = 1;//Don't allow divide by zero error + fps = atof(token); + if (fps == 0) { + fps = 1; // Don't allow divide by zero error } - if ( fps < 0 ) - {//backwards + if (fps < 0) { // backwards animset[animNum].frameLerp = floor(1000.0f / fps); - } - else - { + } else { animset[animNum].frameLerp = ceil(1000.0f / fps); } } @@ -2502,29 +2226,23 @@ int BG_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i SpewDebugStuffToFile(); #endif -// wasLoaded = BGPAFtextLoaded; + // wasLoaded = BGPAFtextLoaded; - if (isHumanoid) - { + if (isHumanoid) { bgAllAnims[0].anims = animset; strcpy(bgAllAnims[0].filename, filename); BGPAFtextLoaded = qtrue; usedIndex = 0; - } - else - { + } else { bgAllAnims[nextIndex].anims = animset; strcpy(bgAllAnims[nextIndex].filename, filename); usedIndex = bgNumAllAnims; - if (nextIndex > 1) - { //don't bother increasing the number if this ended up as a humanoid/rockettrooper load. + if (nextIndex > 1) { // don't bother increasing the number if this ended up as a humanoid/rockettrooper load. bgNumAllAnims++; - } - else - { + } else { BGPAFtextLoaded = qtrue; usedIndex = nextIndex; } @@ -2550,29 +2268,23 @@ LEGS Animations Base animation for overall body =================== */ -static void BG_StartLegsAnim( playerState_t *ps, int anim ) -{ - if ( ps->pm_type >= PM_DEAD ) - { - //vehicles are allowed to do this.. IF it's a vehicle death anim - if (ps->clientNum < MAX_CLIENTS || anim != BOTH_VT_DEATH1) - { +static void BG_StartLegsAnim(playerState_t *ps, int anim) { + if (ps->pm_type >= PM_DEAD) { + // vehicles are allowed to do this.. IF it's a vehicle death anim + if (ps->clientNum < MAX_CLIENTS || anim != BOTH_VT_DEATH1) { return; } } - if ( ps->legsTimer > 0 ) - { - return; // a high priority animation is running + if (ps->legsTimer > 0) { + return; // a high priority animation is running } - if (ps->legsAnim == anim) - { + if (ps->legsAnim == anim) { BG_FlipPart(ps, SETANIM_LEGS); } #ifdef _GAME - else if (g_entities[ps->clientNum].s.legsAnim == anim) - { //toggled anim to one anim then back to the one we were at previously in - //one frame, indicating that anim should be restarted. + else if (g_entities[ps->clientNum].s.legsAnim == anim) { // toggled anim to one anim then back to the one we were at previously in + // one frame, indicating that anim should be restarted. BG_FlipPart(ps, SETANIM_LEGS); } #endif @@ -2585,165 +2297,118 @@ static void BG_StartLegsAnim( playerState_t *ps, int anim ) */ } -void PM_ContinueLegsAnim( int anim ) { - if ( ( pm->ps->legsAnim ) == anim ) { +void PM_ContinueLegsAnim(int anim) { + if ((pm->ps->legsAnim) == anim) { return; } - if ( pm->ps->legsTimer > 0 ) { - return; // a high priority animation is running + if (pm->ps->legsTimer > 0) { + return; // a high priority animation is running } - BG_StartLegsAnim( pm->ps, anim ); + BG_StartLegsAnim(pm->ps, anim); } -void PM_ForceLegsAnim( int anim) { - if (BG_InSpecialJump(pm->ps->legsAnim) && - pm->ps->legsTimer > 0 && - !BG_InSpecialJump(anim)) - { +void PM_ForceLegsAnim(int anim) { + if (BG_InSpecialJump(pm->ps->legsAnim) && pm->ps->legsTimer > 0 && !BG_InSpecialJump(anim)) { return; } - if (BG_InRoll(pm->ps, pm->ps->legsAnim) && - pm->ps->legsTimer > 0 && - !BG_InRoll(pm->ps, anim)) - { + if (BG_InRoll(pm->ps, pm->ps->legsAnim) && pm->ps->legsTimer > 0 && !BG_InRoll(pm->ps, anim)) { return; } pm->ps->legsTimer = 0; - BG_StartLegsAnim( pm->ps, anim ); + BG_StartLegsAnim(pm->ps, anim); } - - /* =================== TORSO Animations Override animations for upper body =================== */ -void BG_StartTorsoAnim( playerState_t *ps, int anim ) -{ - if ( ps->pm_type >= PM_DEAD ) - { +void BG_StartTorsoAnim(playerState_t *ps, int anim) { + if (ps->pm_type >= PM_DEAD) { return; } - if (ps->torsoAnim == anim) - { + if (ps->torsoAnim == anim) { BG_FlipPart(ps, SETANIM_TORSO); } #ifdef _GAME - else if (g_entities[ps->clientNum].s.torsoAnim == anim) - { //toggled anim to one anim then back to the one we were at previously in - //one frame, indicating that anim should be restarted. + else if (g_entities[ps->clientNum].s.torsoAnim == anim) { // toggled anim to one anim then back to the one we were at previously in + // one frame, indicating that anim should be restarted. BG_FlipPart(ps, SETANIM_TORSO); } #endif ps->torsoAnim = anim; } -void PM_StartTorsoAnim( int anim ) -{ - BG_StartTorsoAnim(pm->ps, anim); -} - +void PM_StartTorsoAnim(int anim) { BG_StartTorsoAnim(pm->ps, anim); } /* ------------------------- PM_SetLegsAnimTimer ------------------------- */ -void BG_SetLegsAnimTimer(playerState_t *ps, int time) -{ +void BG_SetLegsAnimTimer(playerState_t *ps, int time) { ps->legsTimer = time; - if (ps->legsTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional. NOTENOTE Yeah this seems dumb, but it mirrors SP. + if (ps->legsTimer < 0 && + time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional. NOTENOTE Yeah this seems dumb, but it mirrors SP. ps->legsTimer = 0; } } -void PM_SetLegsAnimTimer(int time) -{ - BG_SetLegsAnimTimer(pm->ps, time); -} +void PM_SetLegsAnimTimer(int time) { BG_SetLegsAnimTimer(pm->ps, time); } /* ------------------------- PM_SetTorsoAnimTimer ------------------------- */ -void BG_SetTorsoAnimTimer(playerState_t *ps, int time ) -{ +void BG_SetTorsoAnimTimer(playerState_t *ps, int time) { ps->torsoTimer = time; - if (ps->torsoTimer < 0 && time != -1 ) - {//Cap timer to 0 if was counting down, but let it be -1 if that was intentional. NOTENOTE Yeah this seems dumb, but it mirrors SP. + if (ps->torsoTimer < 0 && + time != -1) { // Cap timer to 0 if was counting down, but let it be -1 if that was intentional. NOTENOTE Yeah this seems dumb, but it mirrors SP. ps->torsoTimer = 0; } } -void PM_SetTorsoAnimTimer(int time ) -{ - BG_SetTorsoAnimTimer(pm->ps, time); -} +void PM_SetTorsoAnimTimer(int time) { BG_SetTorsoAnimTimer(pm->ps, time); } -void BG_SaberStartTransAnim( int clientNum, int saberAnimLevel, int weapon, int anim, float *animSpeed, int broken ) -{ - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_ROLL_STAB ) - { - if ( weapon == WP_SABER ) - { - saberInfo_t *saber = BG_MySaber( clientNum, 0 ); - if ( saber - && saber->animSpeedScale != 1.0f ) - { +void BG_SaberStartTransAnim(int clientNum, int saberAnimLevel, int weapon, int anim, float *animSpeed, int broken) { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_ROLL_STAB) { + if (weapon == WP_SABER) { + saberInfo_t *saber = BG_MySaber(clientNum, 0); + if (saber && saber->animSpeedScale != 1.0f) { *animSpeed *= saber->animSpeedScale; } - saber = BG_MySaber( clientNum, 1 ); - if ( saber - && saber->animSpeedScale != 1.0f ) - { + saber = BG_MySaber(clientNum, 1); + if (saber && saber->animSpeedScale != 1.0f) { *animSpeed *= saber->animSpeedScale; } } } - if ( ( (anim) >= BOTH_T1_BR__R && - (anim) <= BOTH_T1_BL_TL ) || - ( (anim) >= BOTH_T2_BR__R && - (anim) <= BOTH_T2_BL_TL ) || - ( (anim) >= BOTH_T3_BR__R && - (anim) <= BOTH_T3_BL_TL ) ) - { - if ( saberAnimLevel == FORCE_LEVEL_1 ) - { + if (((anim) >= BOTH_T1_BR__R && (anim) <= BOTH_T1_BL_TL) || ((anim) >= BOTH_T2_BR__R && (anim) <= BOTH_T2_BL_TL) || + ((anim) >= BOTH_T3_BR__R && (anim) <= BOTH_T3_BL_TL)) { + if (saberAnimLevel == FORCE_LEVEL_1) { *animSpeed *= 1.5f; - } - else if ( saberAnimLevel == FORCE_LEVEL_3 ) - { + } else if (saberAnimLevel == FORCE_LEVEL_3) { *animSpeed *= 0.75f; } - if (broken & (1<clientNum, ps->fd.saberAnimLevel, ps->weapon, anim, &editAnimSpeed, ps->brokenLimbs); // Set torso anim - if (setAnimParts & SETANIM_TORSO) - { + if (setAnimParts & SETANIM_TORSO) { // Don't reset if it's already running the anim - if( !(setAnimFlags & SETANIM_FLAG_RESTART) && (ps->torsoAnim) == anim ) - { + if (!(setAnimFlags & SETANIM_FLAG_RESTART) && (ps->torsoAnim) == anim) { goto setAnimLegs; } // or if a more important anim is running - if( !(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((ps->torsoTimer > 0)||(ps->torsoTimer == -1)) ) - { + if (!(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((ps->torsoTimer > 0) || (ps->torsoTimer == -1))) { goto setAnimLegs; } BG_StartTorsoAnim(ps, anim); - if (setAnimFlags & SETANIM_FLAG_HOLD) - { - if (setAnimFlags & SETANIM_FLAG_HOLDLESS) - { // Make sure to only wait in full 1/20 sec server frame intervals. + if (setAnimFlags & SETANIM_FLAG_HOLD) { + if (setAnimFlags & SETANIM_FLAG_HOLDLESS) { // Make sure to only wait in full 1/20 sec server frame intervals. int dur; int speedDif; - dur = (animations[anim].numFrames-1) * fabs((float)(animations[anim].frameLerp)); + dur = (animations[anim].numFrames - 1) * fabs((float)(animations[anim].frameLerp)); speedDif = dur - (dur * editAnimSpeed); dur += speedDif; - if (dur > 1) - { - ps->torsoTimer = dur-1; - } - else - { + if (dur > 1) { + ps->torsoTimer = dur - 1; + } else { ps->torsoTimer = fabs((float)(animations[anim].frameLerp)); } - } - else - { - ps->torsoTimer = ((animations[anim].numFrames ) * fabs((float)(animations[anim].frameLerp))); + } else { + ps->torsoTimer = ((animations[anim].numFrames) * fabs((float)(animations[anim].frameLerp))); } - if (ps->fd.forcePowersActive & (1 << FP_RAGE)) - { + if (ps->fd.forcePowersActive & (1 << FP_RAGE)) { ps->torsoTimer /= 1.7; } } @@ -2821,54 +2472,40 @@ void BG_SetAnimFinal(playerState_t *ps, animation_t *animations, setAnimLegs: // Set legs anim - if (setAnimParts & SETANIM_LEGS) - { + if (setAnimParts & SETANIM_LEGS) { // Don't reset if it's already running the anim - if( !(setAnimFlags & SETANIM_FLAG_RESTART) && (ps->legsAnim) == anim ) - { + if (!(setAnimFlags & SETANIM_FLAG_RESTART) && (ps->legsAnim) == anim) { goto setAnimDone; } // or if a more important anim is running - if( !(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((ps->legsTimer > 0)||(ps->legsTimer == -1)) ) - { + if (!(setAnimFlags & SETANIM_FLAG_OVERRIDE) && ((ps->legsTimer > 0) || (ps->legsTimer == -1))) { goto setAnimDone; } BG_StartLegsAnim(ps, anim); - if (setAnimFlags & SETANIM_FLAG_HOLD) - { - if (setAnimFlags & SETANIM_FLAG_HOLDLESS) - { // Make sure to only wait in full 1/20 sec server frame intervals. + if (setAnimFlags & SETANIM_FLAG_HOLD) { + if (setAnimFlags & SETANIM_FLAG_HOLDLESS) { // Make sure to only wait in full 1/20 sec server frame intervals. int dur; int speedDif; - dur = (animations[anim].numFrames-1) * fabs((float)(animations[anim].frameLerp)); + dur = (animations[anim].numFrames - 1) * fabs((float)(animations[anim].frameLerp)); speedDif = dur - (dur * editAnimSpeed); dur += speedDif; - if (dur > 1) - { - ps->legsTimer = dur-1; - } - else - { + if (dur > 1) { + ps->legsTimer = dur - 1; + } else { ps->legsTimer = fabs((float)(animations[anim].frameLerp)); } - } - else - { - ps->legsTimer = ((animations[anim].numFrames ) * fabs((float)(animations[anim].frameLerp))); + } else { + ps->legsTimer = ((animations[anim].numFrames) * fabs((float)(animations[anim].frameLerp))); } - if (PM_RunningAnim(anim) || - PM_WalkingAnim(anim)) //these guys are ok, they don't actually reference pm + if (PM_RunningAnim(anim) || PM_WalkingAnim(anim)) // these guys are ok, they don't actually reference pm { - if (ps->fd.forcePowersActive & (1 << FP_RAGE)) - { + if (ps->fd.forcePowersActive & (1 << FP_RAGE)) { ps->legsTimer /= 1.3; - } - else if (ps->fd.forcePowersActive & (1 << FP_SPEED)) - { + } else if (ps->fd.forcePowersActive & (1 << FP_SPEED)) { ps->legsTimer /= 1.7; } } @@ -2879,78 +2516,61 @@ void BG_SetAnimFinal(playerState_t *ps, animation_t *animations, return; } -void PM_SetAnimFinal(int setAnimParts,int anim,int setAnimFlags) -{ - BG_SetAnimFinal(pm->ps, pm->animations, setAnimParts, anim, setAnimFlags); -} - +void PM_SetAnimFinal(int setAnimParts, int anim, int setAnimFlags) { BG_SetAnimFinal(pm->ps, pm->animations, setAnimParts, anim, setAnimFlags); } -qboolean BG_HasAnimation(int animIndex, int animation) -{ +qboolean BG_HasAnimation(int animIndex, int animation) { animation_t *animations; - //must be a valid anim number - if ( animation < 0 || animation >= MAX_ANIMATIONS ) - { + // must be a valid anim number + if (animation < 0 || animation >= MAX_ANIMATIONS) { return qfalse; } - //Must have a file index entry - if( animIndex < 0 || animIndex > bgNumAllAnims ) + // Must have a file index entry + if (animIndex < 0 || animIndex > bgNumAllAnims) return qfalse; animations = bgAllAnims[animIndex].anims; - //No frames, no anim - if ( animations[animation].numFrames == 0 ) + // No frames, no anim + if (animations[animation].numFrames == 0) return qfalse; - //Has the sequence + // Has the sequence return qtrue; } -int BG_PickAnim( int animIndex, int minAnim, int maxAnim ) -{ +int BG_PickAnim(int animIndex, int minAnim, int maxAnim) { int anim; int count = 0; - do - { + do { anim = Q_irand(minAnim, maxAnim); count++; - } - while ( !BG_HasAnimation( animIndex, anim ) && count < 1000 ); + } while (!BG_HasAnimation(animIndex, anim) && count < 1000); - if (count == 1000) - { //guess we just don't have a death anim then. + if (count == 1000) { // guess we just don't have a death anim then. return -1; } return anim; } -//I want to be able to use this on a playerstate even when we are not the focus -//of a pmove too so I have ported it to true BGishness. -//Please do not reference pm in this function or any functions that it calls, -//or I will cry. -rww -void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags) -{ - if (!animations) - { +// I want to be able to use this on a playerstate even when we are not the focus +// of a pmove too so I have ported it to true BGishness. +// Please do not reference pm in this function or any functions that it calls, +// or I will cry. -rww +void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags) { + if (!animations) { animations = bgAllAnims[0].anims; } - if (animations[anim].firstFrame == 0 && animations[anim].numFrames == 0) - { - if (anim == BOTH_RUNBACK1 || - anim == BOTH_WALKBACK1 || - anim == BOTH_RUN1) - { //hack for droids + if (animations[anim].firstFrame == 0 && animations[anim].numFrames == 0) { + if (anim == BOTH_RUNBACK1 || anim == BOTH_WALKBACK1 || anim == BOTH_RUN1) { // hack for droids anim = BOTH_WALK2; } - if (animations[anim].firstFrame == 0 && animations[anim].numFrames == 0) - { //still? Just return then I guess. + if (animations[anim].firstFrame == 0 && animations[anim].numFrames == 0) { // still? Just return then I guess. return; } } @@ -2961,26 +2581,21 @@ void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int setAnimFlags |= SETANIM_FLAG_RESTART; } */ - //Don't know why I put this here originally but it's messing stuff up now and it isn't needed. + // Don't know why I put this here originally but it's messing stuff up now and it isn't needed. -// if (BG_InRoll(ps, ps->legsAnim)) -// { //never interrupt a roll -// return; -// } + // if (BG_InRoll(ps, ps->legsAnim)) + // { //never interrupt a roll + // return; + // } - if (setAnimFlags&SETANIM_FLAG_OVERRIDE) - { - if (setAnimParts & SETANIM_TORSO) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || (ps->torsoAnim) != anim ) - { + if (setAnimFlags & SETANIM_FLAG_OVERRIDE) { + if (setAnimParts & SETANIM_TORSO) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || (ps->torsoAnim) != anim) { BG_SetTorsoAnimTimer(ps, 0); } } - if (setAnimParts & SETANIM_LEGS) - { - if( (setAnimFlags & SETANIM_FLAG_RESTART) || (ps->legsAnim) != anim ) - { + if (setAnimParts & SETANIM_LEGS) { + if ((setAnimFlags & SETANIM_FLAG_RESTART) || (ps->legsAnim) != anim) { BG_SetLegsAnimTimer(ps, 0); } } @@ -2989,8 +2604,4 @@ void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int BG_SetAnimFinal(ps, animations, setAnimParts, anim, setAnimFlags); } -void PM_SetAnim(int setAnimParts,int anim,int setAnimFlags) -{ - BG_SetAnim(pm->ps, pm->animations, setAnimParts, anim, setAnimFlags); -} - +void PM_SetAnim(int setAnimParts, int anim, int setAnimFlags) { BG_SetAnim(pm->ps, pm->animations, setAnimParts, anim, setAnimFlags); } diff --git a/codemp/game/bg_pmove.c b/codemp/game/bg_pmove.c index 62ac9c8772..8e5acc64d2 100644 --- a/codemp/game/bg_pmove.c +++ b/codemp/game/bg_pmove.c @@ -30,27 +30,27 @@ along with this program; if not, see . #include "ghoul2/G2.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif #define MAX_WEAPON_CHARGE_TIME 5000 #ifdef _GAME - extern void G_CheapWeaponFire(int entNum, int ev); - extern qboolean TryGrapple(gentity_t *ent); //g_cmds.c -#endif // _GAME +extern void G_CheapWeaponFire(int entNum, int ev); +extern qboolean TryGrapple(gentity_t *ent); // g_cmds.c +#endif // _GAME -extern qboolean BG_FullBodyTauntAnim( int anim ); +extern qboolean BG_FullBodyTauntAnim(int anim); extern float PM_WalkableGroundDistance(void); -extern qboolean PM_GroundSlideOkay( float zNormal ); -extern saberInfo_t *BG_MySaber( int clientNum, int saberNum ); +extern qboolean PM_GroundSlideOkay(float zNormal); +extern saberInfo_t *BG_MySaber(int clientNum, int saberNum); -pmove_t *pm; -pml_t pml; +pmove_t *pm; +pml_t pml; bgEntity_t *pm_entSelf = NULL; bgEntity_t *pm_entVeh = NULL; @@ -60,207 +60,180 @@ qboolean gPMDoSlowFall = qfalse; qboolean pm_cancelOutZoom = qfalse; // movement parameters -float pm_stopspeed = 100.0f; -float pm_duckScale = 0.50f; -float pm_swimScale = 0.50f; -float pm_wadeScale = 0.70f; - -float pm_vehicleaccelerate = 36.0f; -float pm_accelerate = 10.0f; -float pm_airaccelerate = 1.0f; -float pm_wateraccelerate = 4.0f; -float pm_flyaccelerate = 8.0f; - -float pm_friction = 6.0f; -float pm_waterfriction = 1.0f; -float pm_flightfriction = 3.0f; -float pm_spectatorfriction = 5.0f; - -int c_pmove = 0; - -float forceSpeedLevels[4] = -{ - 1, //rank 0? - 1.25, - 1.5, - 1.75 -}; - -int forcePowerNeeded[NUM_FORCE_POWER_LEVELS][NUM_FORCE_POWERS] = -{ - { //nothing should be usable at rank 0.. - 999,//FP_HEAL,//instant - 999,//FP_LEVITATION,//hold/duration - 999,//FP_SPEED,//duration - 999,//FP_PUSH,//hold/duration - 999,//FP_PULL,//hold/duration - 999,//FP_TELEPATHY,//instant - 999,//FP_GRIP,//hold/duration - 999,//FP_LIGHTNING,//hold/duration - 999,//FP_RAGE,//duration - 999,//FP_PROTECT,//duration - 999,//FP_ABSORB,//duration - 999,//FP_TEAM_HEAL,//instant - 999,//FP_TEAM_FORCE,//instant - 999,//FP_DRAIN,//hold/duration - 999,//FP_SEE,//duration - 999,//FP_SABER_OFFENSE, - 999,//FP_SABER_DEFENSE, - 999//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 65,//FP_HEAL,//instant //was 25, but that was way too little - 10,//FP_LEVITATION,//hold/duration - 50,//FP_SPEED,//duration - 20,//FP_PUSH,//hold/duration - 20,//FP_PULL,//hold/duration - 20,//FP_TELEPATHY,//instant - 30,//FP_GRIP,//hold/duration - 1,//FP_LIGHTNING,//hold/duration - 50,//FP_RAGE,//duration - 50,//FP_PROTECT,//duration - 50,//FP_ABSORB,//duration - 50,//FP_TEAM_HEAL,//instant - 50,//FP_TEAM_FORCE,//instant - 20,//FP_DRAIN,//hold/duration - 20,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 2,//FP_SABER_DEFENSE, - 20//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 60,//FP_HEAL,//instant - 10,//FP_LEVITATION,//hold/duration - 50,//FP_SPEED,//duration - 20,//FP_PUSH,//hold/duration - 20,//FP_PULL,//hold/duration - 20,//FP_TELEPATHY,//instant - 30,//FP_GRIP,//hold/duration - 1,//FP_LIGHTNING,//hold/duration - 50,//FP_RAGE,//duration - 25,//FP_PROTECT,//duration - 25,//FP_ABSORB,//duration - 33,//FP_TEAM_HEAL,//instant - 33,//FP_TEAM_FORCE,//instant - 20,//FP_DRAIN,//hold/duration - 20,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 1,//FP_SABER_DEFENSE, - 20//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 50,//FP_HEAL,//instant //You get 5 points of health.. for 50 force points! - 10,//FP_LEVITATION,//hold/duration - 50,//FP_SPEED,//duration - 20,//FP_PUSH,//hold/duration - 20,//FP_PULL,//hold/duration - 20,//FP_TELEPATHY,//instant - 60,//FP_GRIP,//hold/duration - 1,//FP_LIGHTNING,//hold/duration - 50,//FP_RAGE,//duration - 10,//FP_PROTECT,//duration - 10,//FP_ABSORB,//duration - 25,//FP_TEAM_HEAL,//instant - 25,//FP_TEAM_FORCE,//instant - 20,//FP_DRAIN,//hold/duration - 20,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 0,//FP_SABER_DEFENSE, - 20//FP_SABERTHROW, - //NUM_FORCE_POWERS - } +float pm_stopspeed = 100.0f; +float pm_duckScale = 0.50f; +float pm_swimScale = 0.50f; +float pm_wadeScale = 0.70f; + +float pm_vehicleaccelerate = 36.0f; +float pm_accelerate = 10.0f; +float pm_airaccelerate = 1.0f; +float pm_wateraccelerate = 4.0f; +float pm_flyaccelerate = 8.0f; + +float pm_friction = 6.0f; +float pm_waterfriction = 1.0f; +float pm_flightfriction = 3.0f; +float pm_spectatorfriction = 5.0f; + +int c_pmove = 0; + +float forceSpeedLevels[4] = {1, // rank 0? + 1.25, 1.5, 1.75}; + +int forcePowerNeeded[NUM_FORCE_POWER_LEVELS][NUM_FORCE_POWERS] = {{ + // nothing should be usable at rank 0.. + 999, // FP_HEAL,//instant + 999, // FP_LEVITATION,//hold/duration + 999, // FP_SPEED,//duration + 999, // FP_PUSH,//hold/duration + 999, // FP_PULL,//hold/duration + 999, // FP_TELEPATHY,//instant + 999, // FP_GRIP,//hold/duration + 999, // FP_LIGHTNING,//hold/duration + 999, // FP_RAGE,//duration + 999, // FP_PROTECT,//duration + 999, // FP_ABSORB,//duration + 999, // FP_TEAM_HEAL,//instant + 999, // FP_TEAM_FORCE,//instant + 999, // FP_DRAIN,//hold/duration + 999, // FP_SEE,//duration + 999, // FP_SABER_OFFENSE, + 999, // FP_SABER_DEFENSE, + 999 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 65, // FP_HEAL,//instant //was 25, but that was way too little + 10, // FP_LEVITATION,//hold/duration + 50, // FP_SPEED,//duration + 20, // FP_PUSH,//hold/duration + 20, // FP_PULL,//hold/duration + 20, // FP_TELEPATHY,//instant + 30, // FP_GRIP,//hold/duration + 1, // FP_LIGHTNING,//hold/duration + 50, // FP_RAGE,//duration + 50, // FP_PROTECT,//duration + 50, // FP_ABSORB,//duration + 50, // FP_TEAM_HEAL,//instant + 50, // FP_TEAM_FORCE,//instant + 20, // FP_DRAIN,//hold/duration + 20, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 2, // FP_SABER_DEFENSE, + 20 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 60, // FP_HEAL,//instant + 10, // FP_LEVITATION,//hold/duration + 50, // FP_SPEED,//duration + 20, // FP_PUSH,//hold/duration + 20, // FP_PULL,//hold/duration + 20, // FP_TELEPATHY,//instant + 30, // FP_GRIP,//hold/duration + 1, // FP_LIGHTNING,//hold/duration + 50, // FP_RAGE,//duration + 25, // FP_PROTECT,//duration + 25, // FP_ABSORB,//duration + 33, // FP_TEAM_HEAL,//instant + 33, // FP_TEAM_FORCE,//instant + 20, // FP_DRAIN,//hold/duration + 20, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 1, // FP_SABER_DEFENSE, + 20 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 50, // FP_HEAL,//instant //You get 5 points of health.. for 50 force points! + 10, // FP_LEVITATION,//hold/duration + 50, // FP_SPEED,//duration + 20, // FP_PUSH,//hold/duration + 20, // FP_PULL,//hold/duration + 20, // FP_TELEPATHY,//instant + 60, // FP_GRIP,//hold/duration + 1, // FP_LIGHTNING,//hold/duration + 50, // FP_RAGE,//duration + 10, // FP_PROTECT,//duration + 10, // FP_ABSORB,//duration + 25, // FP_TEAM_HEAL,//instant + 25, // FP_TEAM_FORCE,//instant + 20, // FP_DRAIN,//hold/duration + 20, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 0, // FP_SABER_DEFENSE, + 20 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }}; + +float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = { + 32, // normal jump (+stepheight+crouchdiff = 66) + 96, //(+stepheight+crouchdiff = 130) + 192, //(+stepheight+crouchdiff = 226) + 384 //(+stepheight+crouchdiff = 418) }; -float forceJumpHeight[NUM_FORCE_POWER_LEVELS] = -{ - 32,//normal jump (+stepheight+crouchdiff = 66) - 96,//(+stepheight+crouchdiff = 130) - 192,//(+stepheight+crouchdiff = 226) - 384//(+stepheight+crouchdiff = 418) -}; - -float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = -{ - JUMP_VELOCITY,//normal jump - 420, - 590, - 840 -}; +float forceJumpStrength[NUM_FORCE_POWER_LEVELS] = {JUMP_VELOCITY, // normal jump + 420, 590, 840}; -//rww - Get a pointer to the bgEntity by the index -bgEntity_t *PM_BGEntForNum( int num ) -{ +// rww - Get a pointer to the bgEntity by the index +bgEntity_t *PM_BGEntForNum(int num) { bgEntity_t *ent; - if (!pm) - { + if (!pm) { assert(!"You cannot call PM_BGEntForNum outside of pm functions!"); return NULL; } - if (!pm->baseEnt) - { + if (!pm->baseEnt) { assert(!"Base entity address not set"); return NULL; } - if (!pm->entSize) - { + if (!pm->entSize) { assert(!"sizeof(ent) is 0, impossible (not set?)"); return NULL; } assert(num >= 0 && num < MAX_GENTITIES); - ent = (bgEntity_t *)((byte *)pm->baseEnt + pm->entSize*(num)); + ent = (bgEntity_t *)((byte *)pm->baseEnt + pm->entSize * (num)); return ent; } -qboolean BG_SabersOff( playerState_t *ps ) -{ - if ( !ps->saberHolstered ) - { +qboolean BG_SabersOff(playerState_t *ps) { + if (!ps->saberHolstered) { return qfalse; } - if ( ps->fd.saberAnimLevelBase == SS_DUAL - || ps->fd.saberAnimLevelBase == SS_STAFF ) - { - if ( ps->saberHolstered < 2 ) - { + if (ps->fd.saberAnimLevelBase == SS_DUAL || ps->fd.saberAnimLevelBase == SS_STAFF) { + if (ps->saberHolstered < 2) { return qfalse; } } return qtrue; } -qboolean BG_KnockDownable(playerState_t *ps) -{ - if (!ps) - { //just for safety +qboolean BG_KnockDownable(playerState_t *ps) { + if (!ps) { // just for safety return qfalse; } - if (ps->m_iVehicleNum) - { //riding a vehicle, don't knock me down + if (ps->m_iVehicleNum) { // riding a vehicle, don't knock me down return qfalse; } - if (ps->emplacedIndex) - { //using emplaced gun or eweb, can't be knocked down + if (ps->emplacedIndex) { // using emplaced gun or eweb, can't be knocked down return qfalse; } - //ok, I guess? + // ok, I guess? return qtrue; } -//hacky assumption check, assume any client non-humanoid is a rocket trooper -static QINLINE qboolean PM_IsRocketTrooper(void) -{ +// hacky assumption check, assume any client non-humanoid is a rocket trooper +static QINLINE qboolean PM_IsRocketTrooper(void) { /* if (pm->ps->clientNum < MAX_CLIENTS && pm->gametype == GT_SIEGE && @@ -273,43 +246,32 @@ static QINLINE qboolean PM_IsRocketTrooper(void) return qfalse; } -int PM_GetSaberStance(void) -{ +int PM_GetSaberStance(void) { int anim = BOTH_STAND2; - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); - if (!pm->ps->saberEntityNum) - { //lost it + if (!pm->ps->saberEntityNum) { // lost it return BOTH_STAND1; } - if ( BG_SabersOff( pm->ps ) ) - { + if (BG_SabersOff(pm->ps)) { return BOTH_STAND1; } - if ( saber1 - && saber1->readyAnim != -1 ) - { + if (saber1 && saber1->readyAnim != -1) { return saber1->readyAnim; } - if ( saber2 - && saber2->readyAnim != -1 ) - { + if (saber2 && saber2->readyAnim != -1) { return saber2->readyAnim; } - if ( saber1 - && saber2 - && !pm->ps->saberHolstered ) - {//dual sabers, both on + if (saber1 && saber2 && !pm->ps->saberHolstered) { // dual sabers, both on return BOTH_SABERDUAL_STANCE; } - switch ( pm->ps->fd.saberAnimLevel ) - { + switch (pm->ps->fd.saberAnimLevel) { case SS_DUAL: anim = BOTH_SABERDUAL_STANCE; break; @@ -333,17 +295,15 @@ int PM_GetSaberStance(void) return anim; } -qboolean PM_DoSlowFall(void) -{ - if ( ( (pm->ps->legsAnim) == BOTH_WALL_RUN_RIGHT || (pm->ps->legsAnim) == BOTH_WALL_RUN_LEFT ) && pm->ps->legsTimer > 500 ) - { +qboolean PM_DoSlowFall(void) { + if (((pm->ps->legsAnim) == BOTH_WALL_RUN_RIGHT || (pm->ps->legsAnim) == BOTH_WALL_RUN_LEFT) && pm->ps->legsTimer > 500) { return qtrue; } return qfalse; } -//begin vehicle functions crudely ported from sp -rww +// begin vehicle functions crudely ported from sp -rww /* ==================================================================== void pitch_roll_for_slope (edict_t *forwhom, vec3_t *slope, vec3_t storeAngles ) @@ -358,87 +318,77 @@ and returns. ==================================================================== */ -void PM_pitch_roll_for_slope( bgEntity_t *forwhom, vec3_t pass_slope, vec3_t storeAngles ) -{ - vec3_t slope; - vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = { 0, 0, 0 }; - float pitch, mod, dot; +void PM_pitch_roll_for_slope(bgEntity_t *forwhom, vec3_t pass_slope, vec3_t storeAngles) { + vec3_t slope; + vec3_t nvf, ovf, ovr, startspot, endspot, new_angles = {0, 0, 0}; + float pitch, mod, dot; - //if we don't have a slope, get one - if( !pass_slope || VectorCompare( vec3_origin, pass_slope ) ) - { + // if we don't have a slope, get one + if (!pass_slope || VectorCompare(vec3_origin, pass_slope)) { trace_t trace; - VectorCopy( pm->ps->origin, startspot ); + VectorCopy(pm->ps->origin, startspot); startspot[2] += pm->mins[2] + 4; - VectorCopy( startspot, endspot ); + VectorCopy(startspot, endspot); endspot[2] -= 300; - pm->trace( &trace, pm->ps->origin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID ); -// if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) -// forwhom.flags(-)FL_ONGROUND; + pm->trace(&trace, pm->ps->origin, vec3_origin, vec3_origin, endspot, forwhom->s.number, MASK_SOLID); + // if(trace_fraction>0.05&&forwhom.movetype==MOVETYPE_STEP) + // forwhom.flags(-)FL_ONGROUND; - if ( trace.fraction >= 1.0 ) + if (trace.fraction >= 1.0) return; - if ( VectorCompare( vec3_origin, trace.plane.normal ) ) + if (VectorCompare(vec3_origin, trace.plane.normal)) return; - VectorCopy( trace.plane.normal, slope ); - } - else - { - VectorCopy( pass_slope, slope ); + VectorCopy(trace.plane.normal, slope); + } else { + VectorCopy(pass_slope, slope); } - if ( forwhom->s.NPC_class == CLASS_VEHICLE ) - {//special code for vehicles + if (forwhom->s.NPC_class == CLASS_VEHICLE) { // special code for vehicles Vehicle_t *pVeh = forwhom->m_pVehicle; vec3_t tempAngles; tempAngles[PITCH] = tempAngles[ROLL] = 0; tempAngles[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( tempAngles, ovf, ovr, NULL ); - } - else - { - AngleVectors( pm->ps->viewangles, ovf, ovr, NULL ); + AngleVectors(tempAngles, ovf, ovr, NULL); + } else { + AngleVectors(pm->ps->viewangles, ovf, ovr, NULL); } - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod<0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); - if ( storeAngles ) - { + if (storeAngles) { storeAngles[PITCH] = dot * pitch; - storeAngles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); - } - else //if ( forwhom->client ) + storeAngles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); + } else // if ( forwhom->client ) { float oldmins2; pm->ps->viewangles[PITCH] = dot * pitch; - pm->ps->viewangles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + pm->ps->viewangles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); oldmins2 = pm->mins[2]; - pm->mins[2] = -24 + 12 * fabs(pm->ps->viewangles[PITCH])/180.0f; - //FIXME: if it gets bigger, move up - if ( oldmins2 > pm->mins[2] ) - {//our mins is now lower, need to move up - //FIXME: trace? + pm->mins[2] = -24 + 12 * fabs(pm->ps->viewangles[PITCH]) / 180.0f; + // FIXME: if it gets bigger, move up + if (oldmins2 > pm->mins[2]) { // our mins is now lower, need to move up + // FIXME: trace? pm->ps->origin[2] += (oldmins2 - pm->mins[2]); - //forwhom->currentOrigin[2] = forwhom->client->ps.origin[2]; - //trap->linkentity( forwhom ); + // forwhom->currentOrigin[2] = forwhom->client->ps.origin[2]; + // trap->linkentity( forwhom ); } } /* @@ -450,256 +400,209 @@ void PM_pitch_roll_for_slope( bgEntity_t *forwhom, vec3_t pass_slope, vec3_t sto */ } -#define FLY_NONE 0 -#define FLY_NORMAL 1 -#define FLY_VEHICLE 2 -#define FLY_HOVER 3 +#define FLY_NONE 0 +#define FLY_NORMAL 1 +#define FLY_VEHICLE 2 +#define FLY_HOVER 3 static int pm_flying = FLY_NONE; -void PM_SetSpecialMoveValues (void) -{ +void PM_SetSpecialMoveValues(void) { bgEntity_t *pEnt; - if (pm->ps->clientNum < MAX_CLIENTS) - { //we know that real players aren't vehs + if (pm->ps->clientNum < MAX_CLIENTS) { // we know that real players aren't vehs pm_flying = FLY_NONE; return; } - //default until we decide otherwise + // default until we decide otherwise pm_flying = FLY_NONE; pEnt = pm_entSelf; - if ( pEnt ) - { - if ( (pm->ps->eFlags2&EF2_FLYING) )// pm->gent->client->moveType == MT_FLYSWIM ) + if (pEnt) { + if ((pm->ps->eFlags2 & EF2_FLYING)) // pm->gent->client->moveType == MT_FLYSWIM ) { pm_flying = FLY_NORMAL; - } - else if ( pEnt->s.NPC_class == CLASS_VEHICLE ) - { - if ( pEnt->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - { + } else if (pEnt->s.NPC_class == CLASS_VEHICLE) { + if (pEnt->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { pm_flying = FLY_VEHICLE; - } - else if ( pEnt->m_pVehicle->m_pVehicleInfo->hoverHeight > 0 ) - { + } else if (pEnt->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) { pm_flying = FLY_HOVER; } } } } -static void PM_SetVehicleAngles( vec3_t normal ) -{ +static void PM_SetVehicleAngles(vec3_t normal) { bgEntity_t *pEnt = pm_entSelf; Vehicle_t *pVeh; - vec3_t vAngles; + vec3_t vAngles; float vehicleBankingSpeed; float pitchBias; int i; - if ( !pEnt || pEnt->s.NPC_class != CLASS_VEHICLE ) - { + if (!pEnt || pEnt->s.NPC_class != CLASS_VEHICLE) { return; } pVeh = pEnt->m_pVehicle; - //float curVehicleBankingSpeed; - vehicleBankingSpeed = (pVeh->m_pVehicleInfo->bankingSpeed*32.0f)*pml.frametime;//0.25f + // float curVehicleBankingSpeed; + vehicleBankingSpeed = (pVeh->m_pVehicleInfo->bankingSpeed * 32.0f) * pml.frametime; // 0.25f - if ( vehicleBankingSpeed <= 0 - || ( pVeh->m_pVehicleInfo->pitchLimit == 0 && pVeh->m_pVehicleInfo->rollLimit == 0 ) ) - {//don't bother, this vehicle doesn't bank + if (vehicleBankingSpeed <= 0 || (pVeh->m_pVehicleInfo->pitchLimit == 0 && pVeh->m_pVehicleInfo->rollLimit == 0)) { // don't bother, this vehicle doesn't + // bank return; } - //FIXME: do 3 traces to define a plane and use that... smoothes it out some, too... - //pitch_roll_for_slope( pm->gent, normal, vAngles ); - //FIXME: maybe have some pitch control in water and/or air? + // FIXME: do 3 traces to define a plane and use that... smoothes it out some, too... + // pitch_roll_for_slope( pm->gent, normal, vAngles ); + // FIXME: maybe have some pitch control in water and/or air? - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { pitchBias = 0.0f; - } - else - { - //FIXME: gravity does not matter in SPACE!!! - //center of gravity affects pitch in air/water (FIXME: what about roll?) - pitchBias = 90.0f*pVeh->m_pVehicleInfo->centerOfGravity[0];//if centerOfGravity is all the way back (-1.0f), vehicle pitches up 90 degrees when in air - } - - VectorClear( vAngles ); - if ( pm->waterlevel > 0 ) - {//in water - //view pitch has some influence when in water - //FIXME: take center of gravity into account? - vAngles[PITCH] += (pm->ps->viewangles[PITCH]-vAngles[PITCH])*0.75f + (pitchBias*0.5); - } - else if ( normal ) - {//have a valid surface below me - PM_pitch_roll_for_slope( pEnt, normal, vAngles ); - if ( (pml.groundTrace.contents&(CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)) ) - {//on water - //view pitch has some influence when on a fluid surface - //FIXME: take center of gravity into account - vAngles[PITCH] += (pm->ps->viewangles[PITCH]-vAngles[PITCH])*0.5f + (pitchBias*0.5f); - } - } - else - {//in air, let pitch match view...? - //FIXME: take center of gravity into account - vAngles[PITCH] = pm->ps->viewangles[PITCH]*0.5f + pitchBias; - //don't bank so fast when in the air - vehicleBankingSpeed *= (0.125f*pml.frametime); - } - //NOTE: if angles are flat and we're moving through air (not on ground), + } else { + // FIXME: gravity does not matter in SPACE!!! + // center of gravity affects pitch in air/water (FIXME: what about roll?) + pitchBias = + 90.0f * pVeh->m_pVehicleInfo->centerOfGravity[0]; // if centerOfGravity is all the way back (-1.0f), vehicle pitches up 90 degrees when in air + } + + VectorClear(vAngles); + if (pm->waterlevel > 0) { // in water + // view pitch has some influence when in water + // FIXME: take center of gravity into account? + vAngles[PITCH] += (pm->ps->viewangles[PITCH] - vAngles[PITCH]) * 0.75f + (pitchBias * 0.5); + } else if (normal) { // have a valid surface below me + PM_pitch_roll_for_slope(pEnt, normal, vAngles); + if ((pml.groundTrace.contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { // on water + // view pitch has some influence when on a fluid surface + // FIXME: take center of gravity into account + vAngles[PITCH] += (pm->ps->viewangles[PITCH] - vAngles[PITCH]) * 0.5f + (pitchBias * 0.5f); + } + } else { // in air, let pitch match view...? + // FIXME: take center of gravity into account + vAngles[PITCH] = pm->ps->viewangles[PITCH] * 0.5f + pitchBias; + // don't bank so fast when in the air + vehicleBankingSpeed *= (0.125f * pml.frametime); + } + // NOTE: if angles are flat and we're moving through air (not on ground), // then pitch/bank? - if ( pVeh->m_pVehicleInfo->rollLimit > 0 ) - { - //roll when banking - vec3_t velocity; - float speed; - VectorCopy( pm->ps->velocity, velocity ); + if (pVeh->m_pVehicleInfo->rollLimit > 0) { + // roll when banking + vec3_t velocity; + float speed; + VectorCopy(pm->ps->velocity, velocity); velocity[2] = 0.0f; - speed = VectorNormalize( velocity ); - if ( speed > 32.0f || speed < -32.0f ) - { - vec3_t rt, tempVAngles; - float side; - float dp; + speed = VectorNormalize(velocity); + if (speed > 32.0f || speed < -32.0f) { + vec3_t rt, tempVAngles; + float side; + float dp; // Magic number fun! Speed is used for banking, so modulate the speed by a sine wave - //FIXME: this banks too early - speed *= sin( (150 + pml.frametime) * 0.003 ); + // FIXME: this banks too early + speed *= sin((150 + pml.frametime) * 0.003); // Clamp to prevent harsh rolling - if ( speed > 60 ) + if (speed > 60) speed = 60; - VectorCopy( pVeh->m_vOrientation, tempVAngles ); + VectorCopy(pVeh->m_vOrientation, tempVAngles); tempVAngles[ROLL] = 0; - AngleVectors( tempVAngles, NULL, rt, NULL ); - dp = DotProduct( velocity, rt ); + AngleVectors(tempVAngles, NULL, rt, NULL); + dp = DotProduct(velocity, rt); side = speed * dp; vAngles[ROLL] -= side; } } - //cap - if ( pVeh->m_pVehicleInfo->pitchLimit != -1 ) - { - if ( vAngles[PITCH] > pVeh->m_pVehicleInfo->pitchLimit ) - { + // cap + if (pVeh->m_pVehicleInfo->pitchLimit != -1) { + if (vAngles[PITCH] > pVeh->m_pVehicleInfo->pitchLimit) { vAngles[PITCH] = pVeh->m_pVehicleInfo->pitchLimit; - } - else if ( vAngles[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit ) - { + } else if (vAngles[PITCH] < -pVeh->m_pVehicleInfo->pitchLimit) { vAngles[PITCH] = -pVeh->m_pVehicleInfo->pitchLimit; } } - if ( vAngles[ROLL] > pVeh->m_pVehicleInfo->rollLimit ) - { + if (vAngles[ROLL] > pVeh->m_pVehicleInfo->rollLimit) { vAngles[ROLL] = pVeh->m_pVehicleInfo->rollLimit; - } - else if ( vAngles[ROLL] < -pVeh->m_pVehicleInfo->rollLimit ) - { + } else if (vAngles[ROLL] < -pVeh->m_pVehicleInfo->rollLimit) { vAngles[ROLL] = -pVeh->m_pVehicleInfo->rollLimit; } - //do it - for ( i = 0; i < 3; i++ ) - { - if ( i == YAW ) - {//yawing done elsewhere + // do it + for (i = 0; i < 3; i++) { + if (i == YAW) { // yawing done elsewhere continue; } - //bank faster the higher the difference is + // bank faster the higher the difference is /* else if ( i == PITCH ) { - curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[PITCH], pVeh->m_vOrientation[PITCH] )))/(g_vehicleInfo[pm->ps->vehicleIndex].pitchLimit/2.0f); + curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[PITCH], pVeh->m_vOrientation[PITCH] + )))/(g_vehicleInfo[pm->ps->vehicleIndex].pitchLimit/2.0f); } else if ( i == ROLL ) { - curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[ROLL], pVeh->m_vOrientation[ROLL] )))/(g_vehicleInfo[pm->ps->vehicleIndex].rollLimit/2.0f); + curVehicleBankingSpeed = vehicleBankingSpeed*fabs(AngleNormalize180(AngleSubtract( vAngles[ROLL], pVeh->m_vOrientation[ROLL] + )))/(g_vehicleInfo[pm->ps->vehicleIndex].rollLimit/2.0f); } if ( curVehicleBankingSpeed ) */ { - if ( pVeh->m_vOrientation[i] >= vAngles[i] + vehicleBankingSpeed ) - { + if (pVeh->m_vOrientation[i] >= vAngles[i] + vehicleBankingSpeed) { pVeh->m_vOrientation[i] -= vehicleBankingSpeed; - } - else if ( pVeh->m_vOrientation[i] <= vAngles[i] - vehicleBankingSpeed ) - { + } else if (pVeh->m_vOrientation[i] <= vAngles[i] - vehicleBankingSpeed) { pVeh->m_vOrientation[i] += vehicleBankingSpeed; - } - else - { + } else { pVeh->m_vOrientation[i] = vAngles[i]; } } } } -void BG_VehicleTurnRateForSpeed( Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride ) -{ - if ( pVeh && pVeh->m_pVehicleInfo ) - { +void BG_VehicleTurnRateForSpeed(Vehicle_t *pVeh, float speed, float *mPitchOverride, float *mYawOverride) { + if (pVeh && pVeh->m_pVehicleInfo) { float speedFrac = 1.0f; - if ( pVeh->m_pVehicleInfo->speedDependantTurning ) - { - if ( pVeh->m_LandTrace.fraction >= 1.0f - || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE ) - { - speedFrac = (speed/(pVeh->m_pVehicleInfo->speedMax*0.75f)); - if ( speedFrac < 0.25f ) - { + if (pVeh->m_pVehicleInfo->speedDependantTurning) { + if (pVeh->m_LandTrace.fraction >= 1.0f || pVeh->m_LandTrace.plane.normal[2] < MIN_LANDING_SLOPE) { + speedFrac = (speed / (pVeh->m_pVehicleInfo->speedMax * 0.75f)); + if (speedFrac < 0.25f) { speedFrac = 0.25f; - } - else if ( speedFrac > 1.0f ) - { + } else if (speedFrac > 1.0f) { speedFrac = 1.0f; } } } - if ( pVeh->m_pVehicleInfo->mousePitch ) - { - *mPitchOverride = pVeh->m_pVehicleInfo->mousePitch*speedFrac; + if (pVeh->m_pVehicleInfo->mousePitch) { + *mPitchOverride = pVeh->m_pVehicleInfo->mousePitch * speedFrac; } - if ( pVeh->m_pVehicleInfo->mouseYaw ) - { - *mYawOverride = pVeh->m_pVehicleInfo->mouseYaw*speedFrac; + if (pVeh->m_pVehicleInfo->mouseYaw) { + *mYawOverride = pVeh->m_pVehicleInfo->mouseYaw * speedFrac; } } } - // Following couple things don't belong in the DLL namespace! #ifdef _GAME - #if !defined(MACOS_X) && !defined(__GCC__) && !defined(__GNUC__) - typedef struct gentity_s gentity_t; - #endif - gentity_t *G_PlayEffectID( const int fxID, vec3_t org, vec3_t ang ); +#if !defined(MACOS_X) && !defined(__GCC__) && !defined(__GNUC__) +typedef struct gentity_s gentity_t; +#endif +gentity_t *G_PlayEffectID(const int fxID, vec3_t org, vec3_t ang); #endif - -static void PM_GroundTraceMissed( void ); -void PM_HoverTrace( void ) -{ +static void PM_GroundTraceMissed(void); +void PM_HoverTrace(void) { Vehicle_t *pVeh; float hoverHeight; - vec3_t point, vAng, fxAxis[3]; - trace_t *trace; + vec3_t point, vAng, fxAxis[3]; + trace_t *trace; float relativeWaterLevel; bgEntity_t *pEnt = pm_entSelf; - if ( !pEnt || pEnt->s.NPC_class != CLASS_VEHICLE ) - { + if (!pEnt || pEnt->s.NPC_class != CLASS_VEHICLE) { return; } @@ -709,57 +612,44 @@ void PM_HoverTrace( void ) pml.groundPlane = qfalse; - //relativeWaterLevel = (pm->ps->waterheight - (pm->ps->origin[2]+pm->mins[2])); - relativeWaterLevel = pm->waterlevel; //I.. guess this works - if ( pm->waterlevel && relativeWaterLevel >= 0 ) - {//in water - if ( pVeh->m_pVehicleInfo->bouyancy <= 0.0f ) - {//sink like a rock - } - else - {//rise up - float floatHeight = (pVeh->m_pVehicleInfo->bouyancy * ((pm->maxs[2]-pm->mins[2])*0.5f)) - (hoverHeight*0.5f);//1.0f should make you float half-in, half-out of water - if ( relativeWaterLevel > floatHeight ) - {//too low, should rise up + // relativeWaterLevel = (pm->ps->waterheight - (pm->ps->origin[2]+pm->mins[2])); + relativeWaterLevel = pm->waterlevel; // I.. guess this works + if (pm->waterlevel && relativeWaterLevel >= 0) { // in water + if (pVeh->m_pVehicleInfo->bouyancy <= 0.0f) { // sink like a rock + } else { // rise up + float floatHeight = (pVeh->m_pVehicleInfo->bouyancy * ((pm->maxs[2] - pm->mins[2]) * 0.5f)) - + (hoverHeight * 0.5f); // 1.0f should make you float half-in, half-out of water + if (relativeWaterLevel > floatHeight) { // too low, should rise up pm->ps->velocity[2] += (relativeWaterLevel - floatHeight) * pVeh->m_fTimeModifier; } } - //if ( pm->ps->waterheight < pm->ps->origin[2]+pm->maxs[2] ) - if (pm->waterlevel <= 1) - {//part of us is sticking out of water - if ( fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100 ) - {//moving at a decent speed - if ( Q_irand( pml.frametime, 100 ) >= 50 ) - {//splash + // if ( pm->ps->waterheight < pm->ps->origin[2]+pm->maxs[2] ) + if (pm->waterlevel <= 1) { // part of us is sticking out of water + if (fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100) { // moving at a decent speed + if (Q_irand(pml.frametime, 100) >= 50) { // splash vec3_t wakeOrg; vAng[PITCH] = vAng[ROLL] = 0; vAng[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( vAng, fxAxis[2], fxAxis[1], fxAxis[0] ); - VectorCopy( pm->ps->origin, wakeOrg ); - //wakeOrg[2] = pm->ps->waterheight; - if (pm->waterlevel >= 2) - { - wakeOrg[2] = pm->ps->origin[2]+16; - } - else - { + AngleVectors(vAng, fxAxis[2], fxAxis[1], fxAxis[0]); + VectorCopy(pm->ps->origin, wakeOrg); + // wakeOrg[2] = pm->ps->waterheight; + if (pm->waterlevel >= 2) { + wakeOrg[2] = pm->ps->origin[2] + 16; + } else { wakeOrg[2] = pm->ps->origin[2]; } - #ifdef _GAME //yeah, this is kind of crappy and makes no use of prediction whatsoever - if ( pVeh->m_pVehicleInfo->iWakeFX ) - { - //G_PlayEffectID( pVeh->m_pVehicleInfo->iWakeFX, wakeOrg, fxAxis[0] ); - //tempent use bad! - G_AddEvent((gentity_t *)pEnt, EV_PLAY_EFFECT_ID, pVeh->m_pVehicleInfo->iWakeFX); - } - #endif +#ifdef _GAME // yeah, this is kind of crappy and makes no use of prediction whatsoever + if (pVeh->m_pVehicleInfo->iWakeFX) { + // G_PlayEffectID( pVeh->m_pVehicleInfo->iWakeFX, wakeOrg, fxAxis[0] ); + // tempent use bad! + G_AddEvent((gentity_t *)pEnt, EV_PLAY_EFFECT_ID, pVeh->m_pVehicleInfo->iWakeFX); + } +#endif } } } - } - else - { + } else { int traceContents; float minNormal = pVeh->m_pVehicleInfo->maxSlope; @@ -767,54 +657,41 @@ void PM_HoverTrace( void ) point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] - hoverHeight; - //FIXME: check for water, too? If over water, go slower and make wave effect + // FIXME: check for water, too? If over water, go slower and make wave effect // If *in* water, go really slow and use bouyancy stat to determine how far below surface to float - //NOTE: if bouyancy is 2.0f or higher, you float over water like it's solid ground. + // NOTE: if bouyancy is 2.0f or higher, you float over water like it's solid ground. // if it's 1.0f, you sink halfway into water. If it's 0, you sink... traceContents = pm->tracemask; - if ( pVeh->m_pVehicleInfo->bouyancy >= 2.0f ) - {//sit on water - traceContents |= (CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA); - } - pm->trace( trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, traceContents ); - if (trace->plane.normal[0] > 0.5f || trace->plane.normal[0] < -0.5f || - trace->plane.normal[1] > 0.5f || trace->plane.normal[1] < -0.5f) - { //steep slanted hill, don't go up it. + if (pVeh->m_pVehicleInfo->bouyancy >= 2.0f) { // sit on water + traceContents |= (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA); + } + pm->trace(trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, traceContents); + if (trace->plane.normal[0] > 0.5f || trace->plane.normal[0] < -0.5f || trace->plane.normal[1] > 0.5f || + trace->plane.normal[1] < -0.5f) { // steep slanted hill, don't go up it. float d = fabs(trace->plane.normal[0]); float e = fabs(trace->plane.normal[1]); - if (e > d) - { + if (e > d) { d = e; } - pm->ps->velocity[2] = -300.0f*d; - } - else if ( trace->plane.normal[2] >= minNormal ) - {//not a steep slope, so push us up - if ( trace->fraction < 1.0f ) - {//push up off ground + pm->ps->velocity[2] = -300.0f * d; + } else if (trace->plane.normal[2] >= minNormal) { // not a steep slope, so push us up + if (trace->fraction < 1.0f) { // push up off ground float hoverForce = pVeh->m_pVehicleInfo->hoverStrength; - if ( trace->fraction > 0.5f ) - { - pm->ps->velocity[2] += (1.0f-trace->fraction)*hoverForce*pVeh->m_fTimeModifier; - } - else - { - pm->ps->velocity[2] += (0.5f-(trace->fraction*trace->fraction))*hoverForce*2.0f*pVeh->m_fTimeModifier; - } - if ( (trace->contents&(CONTENTS_WATER|CONTENTS_SLIME|CONTENTS_LAVA)) ) - {//hovering on water, make a spash if moving - if ( fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100 ) - {//moving at a decent speed - if ( Q_irand( pml.frametime, 100 ) >= 50 ) - {//splash + if (trace->fraction > 0.5f) { + pm->ps->velocity[2] += (1.0f - trace->fraction) * hoverForce * pVeh->m_fTimeModifier; + } else { + pm->ps->velocity[2] += (0.5f - (trace->fraction * trace->fraction)) * hoverForce * 2.0f * pVeh->m_fTimeModifier; + } + if ((trace->contents & (CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA))) { // hovering on water, make a spash if moving + if (fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1]) > 100) { // moving at a decent speed + if (Q_irand(pml.frametime, 100) >= 50) { // splash vAng[PITCH] = vAng[ROLL] = 0; vAng[YAW] = pVeh->m_vOrientation[YAW]; - AngleVectors( vAng, fxAxis[2], fxAxis[1], fxAxis[0] ); + AngleVectors(vAng, fxAxis[2], fxAxis[1], fxAxis[0]); #ifdef _GAME - if ( pVeh->m_pVehicleInfo->iWakeFX ) - { - G_PlayEffectID( pVeh->m_pVehicleInfo->iWakeFX, trace->endpos, fxAxis[0] ); + if (pVeh->m_pVehicleInfo->iWakeFX) { + G_PlayEffectID(pVeh->m_pVehicleInfo->iWakeFX, trace->endpos, fxAxis[0]); } #endif } @@ -824,54 +701,43 @@ void PM_HoverTrace( void ) } } } - if ( pml.groundPlane ) - { - PM_SetVehicleAngles( pml.groundTrace.plane.normal ); + if (pml.groundPlane) { + PM_SetVehicleAngles(pml.groundTrace.plane.normal); // We're on the ground. pVeh->m_ulFlags &= ~VEH_FLYING; pVeh->m_vAngularVelocity = 0.0f; - } - else - { - PM_SetVehicleAngles( NULL ); + } else { + PM_SetVehicleAngles(NULL); // We're flying in the air. pVeh->m_ulFlags |= VEH_FLYING; - //groundTrace + // groundTrace - if (pVeh->m_vAngularVelocity==0.0f) - { + if (pVeh->m_vAngularVelocity == 0.0f) { pVeh->m_vAngularVelocity = pVeh->m_vOrientation[YAW] - pVeh->m_vPrevOrientation[YAW]; - if (pVeh->m_vAngularVelocity<-15.0f) - { + if (pVeh->m_vAngularVelocity < -15.0f) { pVeh->m_vAngularVelocity = -15.0f; } - if (pVeh->m_vAngularVelocity> 15.0f) - { - pVeh->m_vAngularVelocity = 15.0f; + if (pVeh->m_vAngularVelocity > 15.0f) { + pVeh->m_vAngularVelocity = 15.0f; } } - //pVeh->m_vAngularVelocity *= 0.95f; // Angular Velocity Decays Over Time - if (pVeh->m_vAngularVelocity > 0.0f) - { + // pVeh->m_vAngularVelocity *= 0.95f; // Angular Velocity Decays Over Time + if (pVeh->m_vAngularVelocity > 0.0f) { pVeh->m_vAngularVelocity -= pml.frametime; - if (pVeh->m_vAngularVelocity < 0.0f) - { + if (pVeh->m_vAngularVelocity < 0.0f) { pVeh->m_vAngularVelocity = 0.0f; } - } - else if (pVeh->m_vAngularVelocity < 0.0f) - { + } else if (pVeh->m_vAngularVelocity < 0.0f) { pVeh->m_vAngularVelocity += pml.frametime; - if (pVeh->m_vAngularVelocity > 0.0f) - { + if (pVeh->m_vAngularVelocity > 0.0f) { pVeh->m_vAngularVelocity = 0.0f; } } } PM_GroundTraceMissed(); } -//end vehicle functions crudely ported from sp -rww +// end vehicle functions crudely ported from sp -rww /* =============== @@ -879,33 +745,28 @@ PM_AddEvent =============== */ -void PM_AddEvent( int newEvent ) { - BG_AddPredictableEventToPlayerstate( newEvent, 0, pm->ps ); -} +void PM_AddEvent(int newEvent) { BG_AddPredictableEventToPlayerstate(newEvent, 0, pm->ps); } -void PM_AddEventWithParm( int newEvent, int parm ) -{ - BG_AddPredictableEventToPlayerstate( newEvent, parm, pm->ps ); -} +void PM_AddEventWithParm(int newEvent, int parm) { BG_AddPredictableEventToPlayerstate(newEvent, parm, pm->ps); } /* =============== PM_AddTouchEnt =============== */ -void PM_AddTouchEnt( int entityNum ) { - int i; +void PM_AddTouchEnt(int entityNum) { + int i; - if ( entityNum == ENTITYNUM_WORLD ) { + if (entityNum == ENTITYNUM_WORLD) { return; } - if ( pm->numtouch >= MAXTOUCH ) { + if (pm->numtouch >= MAXTOUCH) { return; } // see if it is already added - for ( i = 0 ; i < pm->numtouch ; i++ ) { - if ( pm->touchents[ i ] == entityNum ) { + for (i = 0; i < pm->numtouch; i++) { + if (pm->touchents[i] == entityNum) { return; } } @@ -914,7 +775,6 @@ void PM_AddTouchEnt( int entityNum ) { pm->touchents[pm->numtouch++] = entityNum; } - /* ================== PM_ClipVelocity @@ -922,43 +782,40 @@ PM_ClipVelocity Slide off of the impacting surface ================== */ -void PM_ClipVelocity( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) { - float backoff; - float change; - float oldInZ; - int i; +void PM_ClipVelocity(vec3_t in, vec3_t normal, vec3_t out, float overbounce) { + float backoff; + float change; + float oldInZ; + int i; - if ( (pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//no sliding! - VectorCopy( in, out ); + if ((pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // no sliding! + VectorCopy(in, out); return; } oldInZ = in[2]; - backoff = DotProduct (in, normal); + backoff = DotProduct(in, normal); - if ( backoff < 0 ) { + if (backoff < 0) { backoff *= overbounce; } else { backoff /= overbounce; } - for ( i=0 ; i<3 ; i++ ) { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; out[i] = in[i] - change; } - if ( pm->stepSlideFix ) - { - if ( pm->ps->clientNum < MAX_CLIENTS//normal player - && pm->ps->groundEntityNum != ENTITYNUM_NONE//on the ground - && normal[2] < MIN_WALK_NORMAL )//sliding against a steep slope - {//if walking on the ground, don't slide up slopes that are too steep to walk on + if (pm->stepSlideFix) { + if (pm->ps->clientNum < MAX_CLIENTS // normal player + && pm->ps->groundEntityNum != ENTITYNUM_NONE // on the ground + && normal[2] < MIN_WALK_NORMAL) // sliding against a steep slope + { // if walking on the ground, don't slide up slopes that are too steep to walk on out[2] = oldInZ; } } } - /* ================== PM_Friction @@ -966,26 +823,25 @@ PM_Friction Handles both ground friction and water friction ================== */ -static void PM_Friction( void ) { - vec3_t vec; - float *vel; - float speed, newspeed, control; - float drop; +static void PM_Friction(void) { + vec3_t vec; + float *vel; + float speed, newspeed, control; + float drop; bgEntity_t *pEnt = NULL; vel = pm->ps->velocity; - VectorCopy( vel, vec ); - if ( pml.walking ) { - vec[2] = 0; // ignore slope movement + VectorCopy(vel, vec); + if (pml.walking) { + vec[2] = 0; // ignore slope movement } speed = VectorLength(vec); if (speed < 1) { vel[0] = 0; - vel[1] = 0; // allow sinking underwater - if (pm->ps->pm_type == PM_SPECTATOR) - { + vel[1] = 0; // allow sinking underwater + if (pm->ps->pm_type == PM_SPECTATOR) { vel[2] = 0; } // FIXME: still have z friction underwater? @@ -994,25 +850,17 @@ static void PM_Friction( void ) { drop = 0; - if (pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { pEnt = pm_entSelf; } // apply ground friction, even if on ladder - if (pm_flying != FLY_VEHICLE && - pEnt && - pEnt->s.NPC_class == CLASS_VEHICLE && - pEnt->m_pVehicle && - pEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL && - pEnt->m_pVehicle->m_pVehicleInfo->type != VH_WALKER && - pEnt->m_pVehicle->m_pVehicleInfo->friction ) - { + if (pm_flying != FLY_VEHICLE && pEnt && pEnt->s.NPC_class == CLASS_VEHICLE && pEnt->m_pVehicle && pEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL && + pEnt->m_pVehicle->m_pVehicleInfo->type != VH_WALKER && pEnt->m_pVehicle->m_pVehicleInfo->friction) { float friction = pEnt->m_pVehicle->m_pVehicleInfo->friction; - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) /*&& !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)*/ ) - { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) /*&& !(pm->ps->pm_flags & PMF_TIME_NOFRICTION)*/) { control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; /* if ( Flying == FLY_HOVER ) { @@ -1035,49 +883,40 @@ static void PM_Friction( void ) { } */ } - } - else if ( pm_flying != FLY_NORMAL && pm_flying != FLY_VEHICLE ) - { + } else if (pm_flying != FLY_NORMAL && pm_flying != FLY_VEHICLE) { // apply ground friction - if ( pm->waterlevel <= 1 ) { - if ( pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK) ) { + if (pm->waterlevel <= 1) { + if (pml.walking && !(pml.groundTrace.surfaceFlags & SURF_SLICK)) { // if getting knocked back, no friction - if ( ! (pm->ps->pm_flags & PMF_TIME_KNOCKBACK) ) { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK)) { control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*pm_friction*pml.frametime; + drop += control * pm_friction * pml.frametime; } } } } - if ( pm_flying == FLY_VEHICLE ) - { - if ( !(pm->ps->pm_flags & PMF_TIME_KNOCKBACK) ) - { - control = speed;// < pm_stopspeed ? pm_stopspeed : speed; - drop += control*pm_friction*pml.frametime; + if (pm_flying == FLY_VEHICLE) { + if (!(pm->ps->pm_flags & PMF_TIME_KNOCKBACK)) { + control = speed; // < pm_stopspeed ? pm_stopspeed : speed; + drop += control * pm_friction * pml.frametime; } } // apply water friction even if just wading - if ( pm->waterlevel ) { - drop += speed*pm_waterfriction*pm->waterlevel*pml.frametime; + if (pm->waterlevel) { + drop += speed * pm_waterfriction * pm->waterlevel * pml.frametime; } // If on a client then there is no friction - else if ( pm->ps->groundEntityNum < MAX_CLIENTS ) - { + else if (pm->ps->groundEntityNum < MAX_CLIENTS) { drop = 0; } - if ( pm->ps->pm_type == PM_SPECTATOR || pm->ps->pm_type == PM_FLOAT ) - { - if (pm->ps->pm_type == PM_FLOAT) - { //almost no friction while floating - drop += speed*0.1*pml.frametime; - } - else - { - drop += speed*pm_spectatorfriction*pml.frametime; + if (pm->ps->pm_type == PM_SPECTATOR || pm->ps->pm_type == PM_FLOAT) { + if (pm->ps->pm_type == PM_FLOAT) { // almost no friction while floating + drop += speed * 0.1 * pml.frametime; + } else { + drop += speed * pm_spectatorfriction * pml.frametime; } } @@ -1088,10 +927,9 @@ static void PM_Friction( void ) { } newspeed /= speed; - VectorScale( vel, newspeed, vel ); + VectorScale(vel, newspeed, vel); } - /* ============== PM_Accelerate @@ -1099,63 +937,52 @@ PM_Accelerate Handles user intended acceleration ============== */ -static void PM_Accelerate( vec3_t wishdir, float wishspeed, float accel ) -{ - if (pm->gametype != GT_SIEGE - || pm->ps->m_iVehicleNum - || pm->ps->clientNum >= MAX_CLIENTS - || pm->ps->pm_type != PM_NORMAL) - { //standard method, allows "bunnyhopping" and whatnot - int i; - float addspeed, accelspeed, currentspeed; - - currentspeed = DotProduct (pm->ps->velocity, wishdir); +static void PM_Accelerate(vec3_t wishdir, float wishspeed, float accel) { + if (pm->gametype != GT_SIEGE || pm->ps->m_iVehicleNum || pm->ps->clientNum >= MAX_CLIENTS || + pm->ps->pm_type != PM_NORMAL) { // standard method, allows "bunnyhopping" and whatnot + int i; + float addspeed, accelspeed, currentspeed; + + currentspeed = DotProduct(pm->ps->velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0 && pm->ps->clientNum < MAX_CLIENTS) { return; } - if (addspeed < 0) - { - accelspeed = (-accel)*pml.frametime*wishspeed; + if (addspeed < 0) { + accelspeed = (-accel) * pml.frametime * wishspeed; if (accelspeed < addspeed) { accelspeed = addspeed; } - } - else - { - accelspeed = accel*pml.frametime*wishspeed; + } else { + accelspeed = accel * pml.frametime * wishspeed; if (accelspeed > addspeed) { accelspeed = addspeed; } } - for (i=0 ; i<3 ; i++) { - pm->ps->velocity[i] += accelspeed*wishdir[i]; + for (i = 0; i < 3; i++) { + pm->ps->velocity[i] += accelspeed * wishdir[i]; } - } - else - { //use the proper way for siege - vec3_t wishVelocity; - vec3_t pushDir; - float pushLen; - float canPush; + } else { // use the proper way for siege + vec3_t wishVelocity; + vec3_t pushDir; + float pushLen; + float canPush; - VectorScale( wishdir, wishspeed, wishVelocity ); - VectorSubtract( wishVelocity, pm->ps->velocity, pushDir ); - pushLen = VectorNormalize( pushDir ); + VectorScale(wishdir, wishspeed, wishVelocity); + VectorSubtract(wishVelocity, pm->ps->velocity, pushDir); + pushLen = VectorNormalize(pushDir); - canPush = accel*pml.frametime*wishspeed; + canPush = accel * pml.frametime * wishspeed; if (canPush > pushLen) { canPush = pushLen; } - VectorMA( pm->ps->velocity, canPush, pushDir, pm->ps->velocity ); + VectorMA(pm->ps->velocity, canPush, pushDir, pm->ps->velocity); } } - - /* ============ PM_CmdScale @@ -1165,32 +992,30 @@ This allows the clients to use axial -127 to 127 values for all directions without getting a sqrt(2) distortion in speed. ============ */ -static float PM_CmdScale( usercmd_t *cmd ) { - int max; - float total; - float scale; - int umove = 0; //cmd->upmove; - //don't factor upmove into scaling speed +static float PM_CmdScale(usercmd_t *cmd) { + int max; + float total; + float scale; + int umove = 0; // cmd->upmove; + // don't factor upmove into scaling speed - max = abs( cmd->forwardmove ); - if ( abs( cmd->rightmove ) > max ) { - max = abs( cmd->rightmove ); + max = abs(cmd->forwardmove); + if (abs(cmd->rightmove) > max) { + max = abs(cmd->rightmove); } - if ( abs( umove ) > max ) { - max = abs( umove ); + if (abs(umove) > max) { + max = abs(umove); } - if ( !max ) { + if (!max) { return 0; } - total = sqrt( (float)(cmd->forwardmove * cmd->forwardmove - + cmd->rightmove * cmd->rightmove + umove * umove) ); - scale = (float)pm->ps->speed * max / ( 127.0 * total ); + total = sqrt((float)(cmd->forwardmove * cmd->forwardmove + cmd->rightmove * cmd->rightmove + umove * umove)); + scale = (float)pm->ps->speed * max / (127.0 * total); return scale; } - /* ================ PM_SetMovementDir @@ -1199,32 +1024,32 @@ Determine the rotation of the legs reletive to the facing dir ================ */ -static void PM_SetMovementDir( void ) { - if ( pm->cmd.forwardmove || pm->cmd.rightmove ) { - if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0 ) { +static void PM_SetMovementDir(void) { + if (pm->cmd.forwardmove || pm->cmd.rightmove) { + if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 0; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 1; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 2; - } else if ( pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove < 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 3; - } else if ( pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove == 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 4; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove < 0) { pm->ps->movementDir = 5; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove == 0) { pm->ps->movementDir = 6; - } else if ( pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0 ) { + } else if (pm->cmd.rightmove > 0 && pm->cmd.forwardmove > 0) { pm->ps->movementDir = 7; } } else { // if they aren't actively going directly sideways, // change the animation to the diagonal so they // don't stop too crooked - if ( pm->ps->movementDir == 2 ) { + if (pm->ps->movementDir == 2) { pm->ps->movementDir = 1; - } else if ( pm->ps->movementDir == 6 ) { + } else if (pm->ps->movementDir == 6) { pm->ps->movementDir = 7; } } @@ -1232,197 +1057,154 @@ static void PM_SetMovementDir( void ) { #define METROID_JUMP 1 -qboolean PM_ForceJumpingUp(void) -{ - if ( !(pm->ps->fd.forcePowersActive&(1<ps->fd.forceJumpCharge ) - {//already jumped and let go +qboolean PM_ForceJumpingUp(void) { + if (!(pm->ps->fd.forcePowersActive & (1 << FP_LEVITATION)) && pm->ps->fd.forceJumpCharge) { // already jumped and let go return qfalse; } - if ( BG_InSpecialJump( pm->ps->legsAnim ) ) - { + if (BG_InSpecialJump(pm->ps->legsAnim)) { return qfalse; } - if (BG_SaberInSpecial(pm->ps->saberMove)) - { + if (BG_SaberInSpecial(pm->ps->saberMove)) { return qfalse; } - if (BG_SaberInSpecialAttack(pm->ps->legsAnim)) - { + if (BG_SaberInSpecialAttack(pm->ps->legsAnim)) { return qfalse; } - if (BG_HasYsalamiri(pm->gametype, pm->ps)) - { + if (BG_HasYsalamiri(pm->gametype, pm->ps)) { return qfalse; } - if (!BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION)) - { + if (!BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION)) { return qfalse; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE && //in air - (pm->ps->pm_flags & PMF_JUMP_HELD) && //jumped - pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && //force-jump capable - pm->ps->velocity[2] > 0 )//going up + if (pm->ps->groundEntityNum == ENTITYNUM_NONE && // in air + (pm->ps->pm_flags & PMF_JUMP_HELD) && // jumped + pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && // force-jump capable + pm->ps->velocity[2] > 0) // going up { return qtrue; } return qfalse; } -static void PM_JumpForDir( void ) -{ +static void PM_JumpForDir(void) { int anim = BOTH_JUMP1; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_JUMPBACK1; pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_JUMPRIGHT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_JUMPLEFT1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else - { + } else { anim = BOTH_JUMP1; pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; } - if(!BG_InDeathAnim(pm->ps->legsAnim)) - { - PM_SetAnim(SETANIM_LEGS,anim,SETANIM_FLAG_OVERRIDE); + if (!BG_InDeathAnim(pm->ps->legsAnim)) { + PM_SetAnim(SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE); } } -void PM_SetPMViewAngle(playerState_t *ps, vec3_t angle, usercmd_t *ucmd) -{ - int i; +void PM_SetPMViewAngle(playerState_t *ps, vec3_t angle, usercmd_t *ucmd) { + int i; - for (i=0 ; i<3 ; i++) - { // set the delta angle - int cmdAngle; + for (i = 0; i < 3; i++) { // set the delta angle + int cmdAngle; cmdAngle = ANGLE2SHORT(angle[i]); ps->delta_angles[i] = cmdAngle - ucmd->angles[i]; } - VectorCopy (angle, ps->viewangles); + VectorCopy(angle, ps->viewangles); } -qboolean PM_AdjustAngleForWallRun( playerState_t *ps, usercmd_t *ucmd, qboolean doMove ) -{ - if (( (ps->legsAnim) == BOTH_WALL_RUN_RIGHT || (ps->legsAnim) == BOTH_WALL_RUN_LEFT ) && ps->legsTimer > 500 ) - {//wall-running and not at end of anim - //stick to wall, if there is one - vec3_t fwd, rt, traceTo, mins, maxs, fwdAngles; - trace_t trace; - float dist, yawAdjust; +qboolean PM_AdjustAngleForWallRun(playerState_t *ps, usercmd_t *ucmd, qboolean doMove) { + if (((ps->legsAnim) == BOTH_WALL_RUN_RIGHT || (ps->legsAnim) == BOTH_WALL_RUN_LEFT) && ps->legsTimer > 500) { // wall-running and not at end of anim + // stick to wall, if there is one + vec3_t fwd, rt, traceTo, mins, maxs, fwdAngles; + trace_t trace; + float dist, yawAdjust; VectorSet(mins, -15, -15, 0); VectorSet(maxs, 15, 15, 24); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( fwdAngles, fwd, rt, NULL ); - if ( (ps->legsAnim) == BOTH_WALL_RUN_RIGHT ) - { + AngleVectors(fwdAngles, fwd, rt, NULL); + if ((ps->legsAnim) == BOTH_WALL_RUN_RIGHT) { dist = 128; yawAdjust = -90; - } - else - { + } else { dist = -128; yawAdjust = 90; } - VectorMA( ps->origin, dist, rt, traceTo ); + VectorMA(ps->origin, dist, rt, traceTo); - pm->trace( &trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID ); + pm->trace(&trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID); - if ( trace.fraction < 1.0f - && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f) )//&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) + if (trace.fraction < 1.0f && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f)) //&& ent->client->ps.groundEntityNum == ENTITYNUM_NONE ) { - trace_t trace2; + trace_t trace2; vec3_t traceTo2; - vec3_t wallRunFwd, wallRunAngles; + vec3_t wallRunFwd, wallRunAngles; - VectorClear( wallRunAngles ); - wallRunAngles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; - AngleVectors( wallRunAngles, wallRunFwd, NULL, NULL ); + VectorClear(wallRunAngles); + wallRunAngles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; + AngleVectors(wallRunAngles, wallRunFwd, NULL, NULL); - VectorMA( pm->ps->origin, 32, wallRunFwd, traceTo2 ); - pm->trace( &trace2, pm->ps->origin, mins, maxs, traceTo2, pm->ps->clientNum, MASK_PLAYERSOLID ); - if ( trace2.fraction < 1.0f && DotProduct( trace2.plane.normal, wallRunFwd ) <= -0.999f ) - {//wall we can't run on in front of us - trace.fraction = 1.0f;//just a way to get it to kick us off the wall below + VectorMA(pm->ps->origin, 32, wallRunFwd, traceTo2); + pm->trace(&trace2, pm->ps->origin, mins, maxs, traceTo2, pm->ps->clientNum, MASK_PLAYERSOLID); + if (trace2.fraction < 1.0f && DotProduct(trace2.plane.normal, wallRunFwd) <= -0.999f) { // wall we can't run on in front of us + trace.fraction = 1.0f; // just a way to get it to kick us off the wall below } } - if ( trace.fraction < 1.0f - && (trace.plane.normal[2] >= 0.0f&&trace.plane.normal[2] <= 0.4f/*MAX_WALL_RUN_Z_NORMAL*/) ) - {//still a wall there - if ( (ps->legsAnim) == BOTH_WALL_RUN_RIGHT ) - { + if (trace.fraction < 1.0f && (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f /*MAX_WALL_RUN_Z_NORMAL*/)) { // still a wall there + if ((ps->legsAnim) == BOTH_WALL_RUN_RIGHT) { ucmd->rightmove = 127; - } - else - { + } else { ucmd->rightmove = -127; } - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - //make me face perpendicular to the wall - ps->viewangles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; + // make me face perpendicular to the wall + ps->viewangles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; PM_SetPMViewAngle(ps, ps->viewangles, ucmd); - ucmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] ) - ps->delta_angles[YAW]; - if ( doMove ) - { - //push me forward - float zVel = ps->velocity[2]; - if ( ps->legsTimer > 500 ) - {//not at end of anim yet + ucmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW]) - ps->delta_angles[YAW]; + if (doMove) { + // push me forward + float zVel = ps->velocity[2]; + if (ps->legsTimer > 500) { // not at end of anim yet float speed = 175; - if ( ucmd->forwardmove < 0 ) - {//slower + if (ucmd->forwardmove < 0) { // slower speed = 100; + } else if (ucmd->forwardmove > 0) { + speed = 250; // running speed } - else if ( ucmd->forwardmove > 0 ) - { - speed = 250;//running speed - } - VectorScale( fwd, speed, ps->velocity ); + VectorScale(fwd, speed, ps->velocity); } - ps->velocity[2] = zVel;//preserve z velocity - //pull me toward the wall, too - VectorMA( ps->velocity, dist, rt, ps->velocity ); + ps->velocity[2] = zVel; // preserve z velocity + // pull me toward the wall, too + VectorMA(ps->velocity, dist, rt, ps->velocity); } ucmd->forwardmove = 0; return qtrue; - } - else if ( doMove ) - {//stop it - if ( (ps->legsAnim) == BOTH_WALL_RUN_RIGHT ) - { - PM_SetAnim(SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else if ( (ps->legsAnim) == BOTH_WALL_RUN_LEFT ) - { - PM_SetAnim(SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + } else if (doMove) { // stop it + if ((ps->legsAnim) == BOTH_WALL_RUN_RIGHT) { + PM_SetAnim(SETANIM_BOTH, BOTH_WALL_RUN_RIGHT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if ((ps->legsAnim) == BOTH_WALL_RUN_LEFT) { + PM_SetAnim(SETANIM_BOTH, BOTH_WALL_RUN_LEFT_STOP, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } @@ -1430,84 +1212,70 @@ qboolean PM_AdjustAngleForWallRun( playerState_t *ps, usercmd_t *ucmd, qboolean return qfalse; } -qboolean PM_AdjustAnglesForWallRunUpFlipAlt( usercmd_t *ucmd ) -{ -// ucmd->angles[PITCH] = ANGLE2SHORT( pm->ps->viewangles[PITCH] ) - pm->ps->delta_angles[PITCH]; -// ucmd->angles[YAW] = ANGLE2SHORT( pm->ps->viewangles[YAW] ) - pm->ps->delta_angles[YAW]; +qboolean PM_AdjustAnglesForWallRunUpFlipAlt(usercmd_t *ucmd) { + // ucmd->angles[PITCH] = ANGLE2SHORT( pm->ps->viewangles[PITCH] ) - pm->ps->delta_angles[PITCH]; + // ucmd->angles[YAW] = ANGLE2SHORT( pm->ps->viewangles[YAW] ) - pm->ps->delta_angles[YAW]; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, ucmd); return qtrue; } -qboolean PM_AdjustAngleForWallRunUp( playerState_t *ps, usercmd_t *ucmd, qboolean doMove ) -{ - if ( ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START ) - {//wall-running up - //stick to wall, if there is one - vec3_t fwd, traceTo, mins, maxs, fwdAngles; - trace_t trace; - float dist = 128; - - VectorSet(mins, -15,-15,0); - VectorSet(maxs, 15,15,24); +qboolean PM_AdjustAngleForWallRunUp(playerState_t *ps, usercmd_t *ucmd, qboolean doMove) { + if (ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START) { // wall-running up + // stick to wall, if there is one + vec3_t fwd, traceTo, mins, maxs, fwdAngles; + trace_t trace; + float dist = 128; + + VectorSet(mins, -15, -15, 0); + VectorSet(maxs, 15, 15, 24); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( ps->origin, dist, fwd, traceTo ); - pm->trace( &trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID ); - if ( trace.fraction > 0.5f ) - {//hmm, some room, see if there's a floor right here - trace_t trace2; - vec3_t top, bottom; - - VectorCopy( trace.endpos, top ); - top[2] += (pm->mins[2]*-1) + 4.0f; - VectorCopy( top, bottom ); + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(ps->origin, dist, fwd, traceTo); + pm->trace(&trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID); + if (trace.fraction > 0.5f) { // hmm, some room, see if there's a floor right here + trace_t trace2; + vec3_t top, bottom; + + VectorCopy(trace.endpos, top); + top[2] += (pm->mins[2] * -1) + 4.0f; + VectorCopy(top, bottom); bottom[2] -= 64.0f; - pm->trace( &trace2, top, pm->mins, pm->maxs, bottom, ps->clientNum, MASK_PLAYERSOLID ); - if ( !trace2.allsolid - && !trace2.startsolid - && trace2.fraction < 1.0f - && trace2.plane.normal[2] > 0.7f )//slope we can stand on - {//cool, do the alt-flip and land on whetever it is we just scaled up - VectorScale( fwd, 100, pm->ps->velocity ); + pm->trace(&trace2, top, pm->mins, pm->maxs, bottom, ps->clientNum, MASK_PLAYERSOLID); + if (!trace2.allsolid && !trace2.startsolid && trace2.fraction < 1.0f && trace2.plane.normal[2] > 0.7f) // slope we can stand on + { // cool, do the alt-flip and land on whetever it is we just scaled up + VectorScale(fwd, 100, pm->ps->velocity); pm->ps->velocity[2] += 400; - PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_ALT, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_ALT, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->pm_flags |= PMF_JUMP_HELD; - //ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - //ent->client->ps.forcePowersActive |= (1<client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + // ent->client->ps.forcePowersActive |= (1<upmove = 0; return qfalse; } } - if ( //ucmd->upmove <= 0 && - ps->legsTimer > 0 && - ucmd->forwardmove > 0 && - trace.fraction < 1.0f && - (trace.plane.normal[2] >= 0.0f&&trace.plane.normal[2]<=0.4f/*MAX_WALL_RUN_Z_NORMAL*/) ) - {//still a vertical wall there - //make sure there's not a ceiling above us! - trace_t trace2; - VectorCopy( ps->origin, traceTo ); + if ( // ucmd->upmove <= 0 && + ps->legsTimer > 0 && ucmd->forwardmove > 0 && trace.fraction < 1.0f && + (trace.plane.normal[2] >= 0.0f && trace.plane.normal[2] <= 0.4f /*MAX_WALL_RUN_Z_NORMAL*/)) { // still a vertical wall there + // make sure there's not a ceiling above us! + trace_t trace2; + VectorCopy(ps->origin, traceTo); traceTo[2] += 64; - pm->trace( &trace2, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID ); - if ( trace2.fraction < 1.0f ) - {//will hit a ceiling, so force jump-off right now - //NOTE: hits any entity or clip brush in the way, too, not just architecture! - } - else - {//all clear, keep going - //FIXME: don't pull around 90 turns - //FIXME: simulate stepping up steps here, somehow? + pm->trace(&trace2, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID); + if (trace2.fraction < 1.0f) { // will hit a ceiling, so force jump-off right now + // NOTE: hits any entity or clip brush in the way, too, not just architecture! + } else { // all clear, keep going + // FIXME: don't pull around 90 turns + // FIXME: simulate stepping up steps here, somehow? ucmd->forwardmove = 127; - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - //make me face the wall - ps->viewangles[YAW] = vectoyaw( trace.plane.normal )+180; + // make me face the wall + ps->viewangles[YAW] = vectoyaw(trace.plane.normal) + 180; PM_SetPMViewAngle(ps, ps->viewangles, ucmd); /* if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) @@ -1515,17 +1283,15 @@ qboolean PM_AdjustAngleForWallRunUp( playerState_t *ps, usercmd_t *ucmd, qboolea SetClientViewAngle( ent, ent->client->ps.viewangles ); } */ - ucmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] ) - ps->delta_angles[YAW]; - //if ( ent->s.number || !player_locked ) - if (1) //aslkfhsakf + ucmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW]) - ps->delta_angles[YAW]; + // if ( ent->s.number || !player_locked ) + if (1) // aslkfhsakf { - if ( doMove ) - { - //pull me toward the wall - VectorScale( trace.plane.normal, -dist*trace.fraction, ps->velocity ); - //push me up - if ( ps->legsTimer > 200 ) - {//not at end of anim yet + if (doMove) { + // pull me toward the wall + VectorScale(trace.plane.normal, -dist * trace.fraction, ps->velocity); + // push me up + if (ps->legsTimer > 200) { // not at end of anim yet float speed = 300; /* if ( ucmd->forwardmove < 0 ) @@ -1537,7 +1303,7 @@ qboolean PM_AdjustAngleForWallRunUp( playerState_t *ps, usercmd_t *ucmd, qboolea speed = 250;//running speed } */ - ps->velocity[2] = speed;//preserve z velocity + ps->velocity[2] = speed; // preserve z velocity } } } @@ -1545,121 +1311,103 @@ qboolean PM_AdjustAngleForWallRunUp( playerState_t *ps, usercmd_t *ucmd, qboolea return qtrue; } } - //failed! - if ( doMove ) - {//stop it - VectorScale( fwd, -300.0f, ps->velocity ); + // failed! + if (doMove) { // stop it + VectorScale(fwd, -300.0f, ps->velocity); ps->velocity[2] += 200; - //NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //why?!?#?#@!%$R@$KR#F:Hdl;asfm - PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + // NPC_SetAnim( ent, SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // why?!?#?#@!%$R@$KR#F:Hdl;asfm + PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRUNFLIP_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ps->pm_flags |= PMF_JUMP_HELD; - //ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + // ent->client->ps.pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - //FIXME do I need this in mp? - //ent->client->ps.forcePowersActive |= (1<client->ps.forcePowersActive |= (1<upmove = 0; - //return qtrue; + // return qtrue; } } return qfalse; } -#define JUMP_OFF_WALL_SPEED 200.0f -//nice... -static float BG_ForceWallJumpStrength( void ) -{ - return (forceJumpStrength[FORCE_LEVEL_3]/2.5f); -} +#define JUMP_OFF_WALL_SPEED 200.0f +// nice... +static float BG_ForceWallJumpStrength(void) { return (forceJumpStrength[FORCE_LEVEL_3] / 2.5f); } -qboolean PM_AdjustAngleForWallJump( playerState_t *ps, usercmd_t *ucmd, qboolean doMove ) -{ - if ( ( ( BG_InReboundJump( ps->legsAnim ) || BG_InReboundHold( ps->legsAnim ) ) - && ( BG_InReboundJump( ps->torsoAnim ) || BG_InReboundHold( ps->torsoAnim ) ) ) - || (pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//hugging wall, getting ready to jump off - //stick to wall, if there is one - vec3_t checkDir, traceTo, mins, maxs, fwdAngles; - trace_t trace; - float dist = 128.0f, yawAdjust; - - VectorSet(mins, pm->mins[0],pm->mins[1],0); - VectorSet(maxs, pm->maxs[0],pm->maxs[1],24); +qboolean PM_AdjustAngleForWallJump(playerState_t *ps, usercmd_t *ucmd, qboolean doMove) { + if (((BG_InReboundJump(ps->legsAnim) || BG_InReboundHold(ps->legsAnim)) && (BG_InReboundJump(ps->torsoAnim) || BG_InReboundHold(ps->torsoAnim))) || + (pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // hugging wall, getting ready to jump off + // stick to wall, if there is one + vec3_t checkDir, traceTo, mins, maxs, fwdAngles; + trace_t trace; + float dist = 128.0f, yawAdjust; + + VectorSet(mins, pm->mins[0], pm->mins[1], 0); + VectorSet(maxs, pm->maxs[0], pm->maxs[1], 24); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - switch ( ps->legsAnim ) - { + switch (ps->legsAnim) { case BOTH_FORCEWALLREBOUND_RIGHT: case BOTH_FORCEWALLHOLD_RIGHT: - AngleVectors( fwdAngles, NULL, checkDir, NULL ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); yawAdjust = -90; break; case BOTH_FORCEWALLREBOUND_LEFT: case BOTH_FORCEWALLHOLD_LEFT: - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); yawAdjust = 90; break; case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEWALLHOLD_FORWARD: - AngleVectors( fwdAngles, checkDir, NULL, NULL ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); yawAdjust = 180; break; case BOTH_FORCEWALLREBOUND_BACK: case BOTH_FORCEWALLHOLD_BACK: - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); yawAdjust = 0; break; default: - //WTF??? + // WTF??? pm->ps->pm_flags &= ~PMF_STUCK_TO_WALL; return qfalse; break; } - if ( pm->debugMelee ) - {//uber-skillz - if ( ucmd->upmove > 0 ) - {//hold on until you let go manually - if ( BG_InReboundHold( ps->legsAnim ) ) - {//keep holding - if ( ps->legsTimer < 150 ) - { + if (pm->debugMelee) { // uber-skillz + if (ucmd->upmove > 0) { // hold on until you let go manually + if (BG_InReboundHold(ps->legsAnim)) { // keep holding + if (ps->legsTimer < 150) { ps->legsTimer = 150; } - } - else - {//if got to hold part of anim, play hold anim - if ( ps->legsTimer <= 300 ) - { + } else { // if got to hold part of anim, play hold anim + if (ps->legsTimer <= 300) { ps->saberHolstered = 2; - PM_SetAnim( SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD+(ps->legsAnim-BOTH_FORCEWALLHOLD_FORWARD), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD + (ps->legsAnim - BOTH_FORCEWALLHOLD_FORWARD), + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); ps->legsTimer = ps->torsoTimer = 150; } } } } - VectorMA( ps->origin, dist, checkDir, traceTo ); - pm->trace( &trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID ); - if ( //ucmd->upmove <= 0 && - ps->legsTimer > 100 && - trace.fraction < 1.0f && - fabs(trace.plane.normal[2]) <= 0.2f/*MAX_WALL_GRAB_SLOPE*/ ) - {//still a vertical wall there - //FIXME: don't pull around 90 turns + VectorMA(ps->origin, dist, checkDir, traceTo); + pm->trace(&trace, ps->origin, mins, maxs, traceTo, ps->clientNum, MASK_PLAYERSOLID); + if ( // ucmd->upmove <= 0 && + ps->legsTimer > 100 && trace.fraction < 1.0f && fabs(trace.plane.normal[2]) <= 0.2f /*MAX_WALL_GRAB_SLOPE*/) { // still a vertical wall there + // FIXME: don't pull around 90 turns /* if ( ent->s.number || !player_locked ) { ucmd->forwardmove = 127; } */ - if ( ucmd->upmove < 0 ) - { + if (ucmd->upmove < 0) { ucmd->upmove = 0; } - //align me to the wall - ps->viewangles[YAW] = vectoyaw( trace.plane.normal )+yawAdjust; + // align me to the wall + ps->viewangles[YAW] = vectoyaw(trace.plane.normal) + yawAdjust; PM_SetPMViewAngle(ps, ps->viewangles, ucmd); /* if ( ent->client->ps.viewEntity <= 0 || ent->client->ps.viewEntity >= ENTITYNUM_WORLD ) @@ -1667,85 +1415,73 @@ qboolean PM_AdjustAngleForWallJump( playerState_t *ps, usercmd_t *ucmd, qboolean SetClientViewAngle( ent, ent->client->ps.viewangles ); } */ - ucmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] ) - ps->delta_angles[YAW]; - //if ( ent->s.number || !player_locked ) - if (1) - { - if ( doMove ) - { - //pull me toward the wall - VectorScale( trace.plane.normal, -128.0f, ps->velocity ); + ucmd->angles[YAW] = ANGLE2SHORT(ps->viewangles[YAW]) - ps->delta_angles[YAW]; + // if ( ent->s.number || !player_locked ) + if (1) { + if (doMove) { + // pull me toward the wall + VectorScale(trace.plane.normal, -128.0f, ps->velocity); } } ucmd->upmove = 0; ps->pm_flags |= PMF_STUCK_TO_WALL; return qtrue; - } - else if ( doMove - && (ps->pm_flags&PMF_STUCK_TO_WALL)) - {//jump off - //push off of it! + } else if (doMove && (ps->pm_flags & PMF_STUCK_TO_WALL)) { // jump off + // push off of it! ps->pm_flags &= ~PMF_STUCK_TO_WALL; ps->velocity[0] = ps->velocity[1] = 0; - VectorScale( checkDir, -JUMP_OFF_WALL_SPEED, ps->velocity ); + VectorScale(checkDir, -JUMP_OFF_WALL_SPEED, ps->velocity); ps->velocity[2] = BG_ForceWallJumpStrength(); - ps->pm_flags |= PMF_JUMP_HELD;//PMF_JUMPING|PMF_JUMP_HELD; - //G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - ps->fd.forceJumpSound = 1; //this is a stupid thing, i should fix it. - //ent->client->ps.forcePowersActive |= (1<origin[2] < ps->fd.forceJumpZStart) - { + ps->pm_flags |= PMF_JUMP_HELD; // PMF_JUMPING|PMF_JUMP_HELD; + // G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + ps->fd.forceJumpSound = 1; // this is a stupid thing, i should fix it. + // ent->client->ps.forcePowersActive |= (1<origin[2] < ps->fd.forceJumpZStart) { ps->fd.forceJumpZStart = ps->origin[2]; } - //FIXME do I need this? + // FIXME do I need this? - BG_ForcePowerDrain( ps, FP_LEVITATION, 10 ); - //no control for half a second + BG_ForcePowerDrain(ps, FP_LEVITATION, 10); + // no control for half a second ps->pm_flags |= PMF_TIME_KNOCKBACK; ps->pm_time = 500; ucmd->forwardmove = 0; ucmd->rightmove = 0; ucmd->upmove = 127; - if ( BG_InReboundHold( ps->legsAnim ) ) - {//if was in hold pose, release now - PM_SetAnim( SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD+(ps->legsAnim-BOTH_FORCEWALLHOLD_FORWARD), SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { - //PM_JumpForDir(); - PM_SetAnim(SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); + if (BG_InReboundHold(ps->legsAnim)) { // if was in hold pose, release now + PM_SetAnim(SETANIM_BOTH, BOTH_FORCEWALLRELEASE_FORWARD + (ps->legsAnim - BOTH_FORCEWALLHOLD_FORWARD), + SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + // PM_JumpForDir(); + PM_SetAnim(SETANIM_LEGS, BOTH_FORCEJUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); } - //return qtrue; + // return qtrue; } } ps->pm_flags &= ~PMF_STUCK_TO_WALL; return qfalse; } -//Set the height for when a force jump was started. If it's 0, nuge it up (slight hack to prevent holding jump over slopes) -void PM_SetForceJumpZStart(float value) -{ +// Set the height for when a force jump was started. If it's 0, nuge it up (slight hack to prevent holding jump over slopes) +void PM_SetForceJumpZStart(float value) { pm->ps->fd.forceJumpZStart = value; - if (!pm->ps->fd.forceJumpZStart) - { + if (!pm->ps->fd.forceJumpZStart) { pm->ps->fd.forceJumpZStart -= 0.1f; } } -float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = -{ - 66,//normal jump (32+stepheight(18)+crouchdiff(24) = 74) - 130,//(96+stepheight(18)+crouchdiff(24) = 138) - 226,//(192+stepheight(18)+crouchdiff(24) = 234) - 418//(384+stepheight(18)+crouchdiff(24) = 426) +float forceJumpHeightMax[NUM_FORCE_POWER_LEVELS] = { + 66, // normal jump (32+stepheight(18)+crouchdiff(24) = 74) + 130, //(96+stepheight(18)+crouchdiff(24) = 138) + 226, //(192+stepheight(18)+crouchdiff(24) = 234) + 418 //(384+stepheight(18)+crouchdiff(24) = 426) }; -void PM_GrabWallForJump( int anim ) -{//NOTE!!! assumes an appropriate anim is being passed in!!! - PM_SetAnim( SETANIM_BOTH, anim, SETANIM_FLAG_RESTART|SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - PM_AddEvent( EV_JUMP );//make sound for grab +void PM_GrabWallForJump(int anim) { // NOTE!!! assumes an appropriate anim is being passed in!!! + PM_SetAnim(SETANIM_BOTH, anim, SETANIM_FLAG_RESTART | SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + PM_AddEvent(EV_JUMP); // make sound for grab pm->ps->pm_flags |= PMF_STUCK_TO_WALL; } @@ -1754,295 +1490,215 @@ void PM_GrabWallForJump( int anim ) PM_CheckJump ============= */ -static qboolean PM_CheckJump( void ) -{ +static qboolean PM_CheckJump(void) { qboolean allowFlips = qtrue; - if (pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { bgEntity_t *pEnt = pm_entSelf; - if (pEnt->s.eType == ET_NPC && - pEnt->s.NPC_class == CLASS_VEHICLE) - { //no! + if (pEnt->s.eType == ET_NPC && pEnt->s.NPC_class == CLASS_VEHICLE) { // no! return qfalse; } } - if (pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || - pm->ps->forceHandExtend == HANDEXTEND_PRETHROWN || - pm->ps->forceHandExtend == HANDEXTEND_POSTTHROWN) - { + if (pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || pm->ps->forceHandExtend == HANDEXTEND_PRETHROWN || + pm->ps->forceHandExtend == HANDEXTEND_POSTTHROWN) { return qfalse; } - if (pm->ps->pm_type == PM_JETPACK) - { //there's no actual jumping while we jetpack + if (pm->ps->pm_type == PM_JETPACK) { // there's no actual jumping while we jetpack return qfalse; } - //Don't allow jump until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + // Don't allow jump until all buttons are up + if (pm->ps->pm_flags & PMF_RESPAWNED) { return qfalse; } - if ( PM_InKnockDown( pm->ps ) || BG_InRoll( pm->ps, pm->ps->legsAnim ) ) - {//in knockdown + if (PM_InKnockDown(pm->ps) || BG_InRoll(pm->ps, pm->ps->legsAnim)) { // in knockdown return qfalse; } - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber1 - && (saber1->saberFlags&SFL_NO_FLIPS) ) - { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + if (saber1 && (saber1->saberFlags & SFL_NO_FLIPS)) { allowFlips = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_FLIPS) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_FLIPS)) { allowFlips = qfalse; } } - if (pm->ps->groundEntityNum != ENTITYNUM_NONE || pm->ps->origin[2] < pm->ps->fd.forceJumpZStart) - { - pm->ps->fd.forcePowersActive &= ~(1<ps->groundEntityNum != ENTITYNUM_NONE || pm->ps->origin[2] < pm->ps->fd.forceJumpZStart) { + pm->ps->fd.forcePowersActive &= ~(1 << FP_LEVITATION); } - if (pm->ps->fd.forcePowersActive & (1 << FP_LEVITATION)) - { //Force jump is already active.. continue draining power appropriately until we land. - if (pm->ps->fd.forcePowerDebounce[FP_LEVITATION] < pm->cmd.serverTime) - { - if ( pm->gametype == GT_DUEL - || pm->gametype == GT_POWERDUEL ) - {//jump takes less power - BG_ForcePowerDrain( pm->ps, FP_LEVITATION, 1 ); - } - else - { - BG_ForcePowerDrain( pm->ps, FP_LEVITATION, 5 ); + if (pm->ps->fd.forcePowersActive & (1 << FP_LEVITATION)) { // Force jump is already active.. continue draining power appropriately until we land. + if (pm->ps->fd.forcePowerDebounce[FP_LEVITATION] < pm->cmd.serverTime) { + if (pm->gametype == GT_DUEL || pm->gametype == GT_POWERDUEL) { // jump takes less power + BG_ForcePowerDrain(pm->ps, FP_LEVITATION, 1); + } else { + BG_ForcePowerDrain(pm->ps, FP_LEVITATION, 5); } - if (pm->ps->fd.forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_2) - { + if (pm->ps->fd.forcePowerLevel[FP_LEVITATION] >= FORCE_LEVEL_2) { pm->ps->fd.forcePowerDebounce[FP_LEVITATION] = pm->cmd.serverTime + 300; - } - else - { + } else { pm->ps->fd.forcePowerDebounce[FP_LEVITATION] = pm->cmd.serverTime + 200; } } } - if (pm->ps->forceJumpFlip) - { //Forced jump anim + if (pm->ps->forceJumpFlip) { // Forced jump anim int anim = BOTH_FORCEINAIR1; - int parts = SETANIM_BOTH; - if ( allowFlips ) - { - if ( pm->cmd.forwardmove > 0 ) - { + int parts = SETANIM_BOTH; + if (allowFlips) { + if (pm->cmd.forwardmove > 0) { anim = BOTH_FLIP_F; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FLIP_B; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_FLIP_R; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FLIP_L; } - } - else - { - if ( pm->cmd.forwardmove > 0 ) - { + } else { + if (pm->cmd.forwardmove > 0) { anim = BOTH_FORCEINAIR1; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FORCEINAIRBACK1; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_FORCEINAIRRIGHT1; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FORCEINAIRLEFT1; } } - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->forceJumpFlip = qfalse; return qtrue; } #if METROID_JUMP - if ( pm->waterlevel < 2 ) - { - if ( pm->ps->gravity > 0 ) - {//can't do this in zero-G - if ( PM_ForceJumpingUp() ) - {//holding jump in air + if (pm->waterlevel < 2) { + if (pm->ps->gravity > 0) { // can't do this in zero-G + if (PM_ForceJumpingUp()) { // holding jump in air float curHeight = pm->ps->origin[2] - pm->ps->fd.forceJumpZStart; - //check for max force jump level and cap off & cut z vel - if ( ( curHeight<=forceJumpHeight[0] ||//still below minimum jump height - (pm->ps->fd.forcePower&&pm->cmd.upmove>=10) ) &&////still have force power available and still trying to jump up + // check for max force jump level and cap off & cut z vel + if ((curHeight <= forceJumpHeight[0] || // still below minimum jump height + (pm->ps->fd.forcePower && pm->cmd.upmove >= 10)) && ////still have force power available and still trying to jump up curHeight < forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] && - pm->ps->fd.forceJumpZStart)//still below maximum jump height - {//can still go up - if ( curHeight > forceJumpHeight[0] ) - {//passed normal jump height *2? - if ( !(pm->ps->fd.forcePowersActive&(1<ps->fd.forceJumpZStart) // still below maximum jump height + { // can still go up + if (curHeight > forceJumpHeight[0]) { // passed normal jump height *2? + if (!(pm->ps->fd.forcePowersActive & (1 << FP_LEVITATION))) // haven't started forcejump yet { - //start force jump - pm->ps->fd.forcePowersActive |= (1<ps->fd.forcePowersActive |= (1 << FP_LEVITATION); pm->ps->fd.forceJumpSound = 1; - //play flip - if ((pm->cmd.forwardmove || pm->cmd.rightmove) && //pushing in a dir - (pm->ps->legsAnim) != BOTH_FLIP_F &&//not already flipping - (pm->ps->legsAnim) != BOTH_FLIP_B && - (pm->ps->legsAnim) != BOTH_FLIP_R && - (pm->ps->legsAnim) != BOTH_FLIP_L - && allowFlips ) - { + // play flip + if ((pm->cmd.forwardmove || pm->cmd.rightmove) && // pushing in a dir + (pm->ps->legsAnim) != BOTH_FLIP_F && // not already flipping + (pm->ps->legsAnim) != BOTH_FLIP_B && (pm->ps->legsAnim) != BOTH_FLIP_R && (pm->ps->legsAnim) != BOTH_FLIP_L && allowFlips) { int anim = BOTH_FORCEINAIR1; - int parts = SETANIM_BOTH; + int parts = SETANIM_BOTH; - if ( pm->cmd.forwardmove > 0 ) - { + if (pm->cmd.forwardmove > 0) { anim = BOTH_FLIP_F; - } - else if ( pm->cmd.forwardmove < 0 ) - { + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FLIP_B; - } - else if ( pm->cmd.rightmove > 0 ) - { + } else if (pm->cmd.rightmove > 0) { anim = BOTH_FLIP_R; - } - else if ( pm->cmd.rightmove < 0 ) - { + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FLIP_L; } - if ( pm->ps->weaponTime ) - { + if (pm->ps->weaponTime) { parts = SETANIM_LEGS; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else if ( pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - { + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else if (pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { vec3_t facingFwd, facingRight, facingAngles; - int anim = -1; + int anim = -1; float dotR, dotF; VectorSet(facingAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( facingAngles, facingFwd, facingRight, NULL ); - dotR = DotProduct( facingRight, pm->ps->velocity ); - dotF = DotProduct( facingFwd, pm->ps->velocity ); + AngleVectors(facingAngles, facingFwd, facingRight, NULL); + dotR = DotProduct(facingRight, pm->ps->velocity); + dotF = DotProduct(facingFwd, pm->ps->velocity); - if ( fabs(dotR) > fabs(dotF) * 1.5 ) - { - if ( dotR > 150 ) - { + if (fabs(dotR) > fabs(dotF) * 1.5) { + if (dotR > 150) { anim = BOTH_FORCEJUMPRIGHT1; - } - else if ( dotR < -150 ) - { + } else if (dotR < -150) { anim = BOTH_FORCEJUMPLEFT1; } - } - else - { - if ( dotF > 150 ) - { + } else { + if (dotF > 150) { anim = BOTH_FORCEJUMP1; - } - else if ( dotF < -150 ) - { + } else if (dotF < -150) { anim = BOTH_FORCEJUMPBACK1; } } - if ( anim != -1 ) - { + if (anim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - {//FIXME: really only care if we're in a saber attack anim... + if (pm->ps->weaponTime) { // FIXME: really only care if we're in a saber attack anim... parts = SETANIM_LEGS; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else - { //jump is already active (the anim has started) - if ( pm->ps->legsTimer < 1 ) - {//not in the middle of a legsAnim + } else { // jump is already active (the anim has started) + if (pm->ps->legsTimer < 1) { // not in the middle of a legsAnim int anim = (pm->ps->legsAnim); int newAnim = -1; - switch ( anim ) - { + switch (anim) { case BOTH_FORCEJUMP1: - newAnim = BOTH_FORCELAND1;//BOTH_FORCEINAIR1; + newAnim = BOTH_FORCELAND1; // BOTH_FORCEINAIR1; break; case BOTH_FORCEJUMPBACK1: - newAnim = BOTH_FORCELANDBACK1;//BOTH_FORCEINAIRBACK1; + newAnim = BOTH_FORCELANDBACK1; // BOTH_FORCEINAIRBACK1; break; case BOTH_FORCEJUMPLEFT1: - newAnim = BOTH_FORCELANDLEFT1;//BOTH_FORCEINAIRLEFT1; + newAnim = BOTH_FORCELANDLEFT1; // BOTH_FORCEINAIRLEFT1; break; case BOTH_FORCEJUMPRIGHT1: - newAnim = BOTH_FORCELANDRIGHT1;//BOTH_FORCEINAIRRIGHT1; + newAnim = BOTH_FORCELANDRIGHT1; // BOTH_FORCEINAIRRIGHT1; break; } - if ( newAnim != -1 ) - { + if (newAnim != -1) { int parts = SETANIM_BOTH; - if ( pm->ps->weaponTime ) - { + if (pm->ps->weaponTime) { parts = SETANIM_LEGS; } - PM_SetAnim( parts, newAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(parts, newAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } } - //need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel - pm->ps->velocity[2] = (forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]]-curHeight)/forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]]*forceJumpStrength[pm->ps->fd.forcePowerLevel[FP_LEVITATION]];//JUMP_VELOCITY; + // need to scale this down, start with height velocity (based on max force jump height) and scale down to regular jump vel + pm->ps->velocity[2] = (forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] - curHeight) / + forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] * + forceJumpStrength[pm->ps->fd.forcePowerLevel[FP_LEVITATION]]; // JUMP_VELOCITY; pm->ps->velocity[2] /= 10; pm->ps->velocity[2] += JUMP_VELOCITY; pm->ps->pm_flags |= PMF_JUMP_HELD; - } - else if ( curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] - forceJumpHeight[0] ) - {//still have some headroom, don't totally stop it - if ( pm->ps->velocity[2] > JUMP_VELOCITY ) - { + } else if (curHeight > forceJumpHeight[0] && curHeight < forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] - + forceJumpHeight[0]) { // still have some headroom, don't totally stop it + if (pm->ps->velocity[2] > JUMP_VELOCITY) { pm->ps->velocity[2] = JUMP_VELOCITY; } - } - else - { - //pm->ps->velocity[2] = 0; - //rww - changed for the sake of balance in multiplayer + } else { + // pm->ps->velocity[2] = 0; + // rww - changed for the sake of balance in multiplayer - if ( pm->ps->velocity[2] > JUMP_VELOCITY ) - { + if (pm->ps->velocity[2] > JUMP_VELOCITY) { pm->ps->velocity[2] = JUMP_VELOCITY; } } @@ -2054,221 +1710,164 @@ static qboolean PM_CheckJump( void ) #endif - //Not jumping - if ( pm->cmd.upmove < 10 && pm->ps->groundEntityNum != ENTITYNUM_NONE) { + // Not jumping + if (pm->cmd.upmove < 10 && pm->ps->groundEntityNum != ENTITYNUM_NONE) { return qfalse; } // must wait for jump to be released - if ( pm->ps->pm_flags & PMF_JUMP_HELD ) - { + if (pm->ps->pm_flags & PMF_JUMP_HELD) { // clear upmove so cmdscale doesn't lower running speed pm->cmd.upmove = 0; return qfalse; } - if ( pm->ps->gravity <= 0 ) - {//in low grav, you push in the dir you're facing as long as there is something behind you to shove off of - vec3_t forward, back; - trace_t trace; + if (pm->ps->gravity <= 0) { // in low grav, you push in the dir you're facing as long as there is something behind you to shove off of + vec3_t forward, back; + trace_t trace; - AngleVectors( pm->ps->viewangles, forward, NULL, NULL ); - VectorMA( pm->ps->origin, -8, forward, back ); - pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask ); + AngleVectors(pm->ps->viewangles, forward, NULL, NULL); + VectorMA(pm->ps->origin, -8, forward, back); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, back, pm->ps->clientNum, pm->tracemask); - if ( trace.fraction <= 1.0f ) - { - VectorMA( pm->ps->velocity, JUMP_VELOCITY*2, forward, pm->ps->velocity ); - PM_SetAnim(SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART); - }//else no surf close enough to push off of + if (trace.fraction <= 1.0f) { + VectorMA(pm->ps->velocity, JUMP_VELOCITY * 2, forward, pm->ps->velocity); + PM_SetAnim(SETANIM_LEGS, BOTH_FORCEJUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART); + } // else no surf close enough to push off of pm->cmd.upmove = 0; - } - else if ( pm->cmd.upmove > 0 && pm->waterlevel < 2 && - pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && - !(pm->ps->pm_flags&PMF_JUMP_HELD) && - (pm->ps->weapon == WP_SABER || pm->ps->weapon == WP_MELEE) && - !PM_IsRocketTrooper() && - !BG_HasYsalamiri(pm->gametype, pm->ps) && - BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION) ) - { + } else if (pm->cmd.upmove > 0 && pm->waterlevel < 2 && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_0 && !(pm->ps->pm_flags & PMF_JUMP_HELD) && + (pm->ps->weapon == WP_SABER || pm->ps->weapon == WP_MELEE) && !PM_IsRocketTrooper() && !BG_HasYsalamiri(pm->gametype, pm->ps) && + BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION)) { qboolean allowWallRuns = qtrue; qboolean allowWallFlips = qtrue; - // qboolean allowFlips = qtrue; + // qboolean allowFlips = qtrue; qboolean allowWallGrabs = qtrue; - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber1 - && (saber1->saberFlags&SFL_NO_WALL_RUNS) ) - { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + if (saber1 && (saber1->saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_WALL_RUNS) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_WALL_RUNS)) { allowWallRuns = qfalse; } - if ( saber1 - && (saber1->saberFlags&SFL_NO_WALL_FLIPS) ) - { + if (saber1 && (saber1->saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_WALL_FLIPS) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_WALL_FLIPS)) { allowWallFlips = qfalse; } - if ( saber1 - && (saber1->saberFlags&SFL_NO_FLIPS) ) - { + if (saber1 && (saber1->saberFlags & SFL_NO_FLIPS)) { allowFlips = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_FLIPS) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_FLIPS)) { allowFlips = qfalse; } - if ( saber1 - && (saber1->saberFlags&SFL_NO_WALL_GRAB) ) - { + if (saber1 && (saber1->saberFlags & SFL_NO_WALL_GRAB)) { allowWallGrabs = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_WALL_GRAB) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_WALL_GRAB)) { allowWallGrabs = qfalse; } } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on the ground - //check for left-wall and right-wall special jumps + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on the ground + // check for left-wall and right-wall special jumps int anim = -1; - float vertPush = 0; - if ( pm->cmd.rightmove > 0 && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing right - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - if ( allowWallRuns ) - { - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + float vertPush = 0; + if (pm->cmd.rightmove > 0 && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing right + if (pm->cmd.forwardmove > 0) { // wall-run + if (allowWallRuns) { + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_RIGHT; } - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - if ( allowWallFlips ) - { - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + if (allowWallFlips) { + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_RIGHT; } } - } - else if ( pm->cmd.rightmove < 0 && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 ) - {//strafing left - if ( pm->cmd.forwardmove > 0 ) - {//wall-run - if ( allowWallRuns ) - { - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.0f; + } else if (pm->cmd.rightmove < 0 && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // strafing left + if (pm->cmd.forwardmove > 0) { // wall-run + if (allowWallRuns) { + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.0f; anim = BOTH_WALL_RUN_LEFT; } - } - else if ( pm->cmd.forwardmove == 0 ) - {//wall-flip - if ( allowWallFlips ) - { - vertPush = forceJumpStrength[FORCE_LEVEL_2]/2.25f; + } else if (pm->cmd.forwardmove == 0) { // wall-flip + if (allowWallFlips) { + vertPush = forceJumpStrength[FORCE_LEVEL_2] / 2.25f; anim = BOTH_WALL_FLIP_LEFT; } } - } - else if ( pm->cmd.forwardmove < 0 && !(pm->cmd.buttons&BUTTON_ATTACK) ) - {//backflip - if ( allowFlips ) - { + } else if (pm->cmd.forwardmove < 0 && !(pm->cmd.buttons & BUTTON_ATTACK)) { // backflip + if (allowFlips) { vertPush = JUMP_VELOCITY; - anim = BOTH_FLIP_BACK1;//BG_PickAnim( BOTH_FLIP_BACK1, BOTH_FLIP_BACK3 ); + anim = BOTH_FLIP_BACK1; // BG_PickAnim( BOTH_FLIP_BACK1, BOTH_FLIP_BACK3 ); } } - vertPush += 128; //give them an extra shove + vertPush += 128; // give them an extra shove - if ( anim != -1 ) - { + if (anim != -1) { vec3_t fwd, right, traceto, mins, maxs, fwdAngles; - vec3_t idealNormal={0}, wallNormal={0}; - trace_t trace; + vec3_t idealNormal = {0}, wallNormal = {0}; + trace_t trace; qboolean doTrace = qfalse; - int contents = MASK_SOLID;//MASK_PLAYERSOLID; + int contents = MASK_SOLID; // MASK_PLAYERSOLID; - VectorSet(mins, pm->mins[0],pm->mins[1],0); - VectorSet(maxs, pm->maxs[0],pm->maxs[1],24); + VectorSet(mins, pm->mins[0], pm->mins[1], 0); + VectorSet(maxs, pm->maxs[0], pm->maxs[1], 24); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - memset(&trace, 0, sizeof(trace)); //to shut the compiler up + memset(&trace, 0, sizeof(trace)); // to shut the compiler up - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); - //trace-check for a wall, if necc. - switch ( anim ) - { + // trace-check for a wall, if necc. + switch (anim) { case BOTH_WALL_FLIP_LEFT: - //NOTE: purposely falls through to next case! + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_LEFT: doTrace = qtrue; - VectorMA( pm->ps->origin, -16, right, traceto ); + VectorMA(pm->ps->origin, -16, right, traceto); break; case BOTH_WALL_FLIP_RIGHT: - //NOTE: purposely falls through to next case! + // NOTE: purposely falls through to next case! case BOTH_WALL_RUN_RIGHT: doTrace = qtrue; - VectorMA( pm->ps->origin, 16, right, traceto ); + VectorMA(pm->ps->origin, 16, right, traceto); break; case BOTH_WALL_FLIP_BACK1: doTrace = qtrue; - VectorMA( pm->ps->origin, 16, fwd, traceto ); + VectorMA(pm->ps->origin, 16, fwd, traceto); break; } - if ( doTrace ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents ); - VectorCopy( trace.plane.normal, wallNormal ); - VectorNormalize( wallNormal ); - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + if (doTrace) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents); + VectorCopy(trace.plane.normal, wallNormal); + VectorNormalize(wallNormal); + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); } - if ( !doTrace || (trace.fraction < 1.0f && (trace.entityNum < MAX_CLIENTS || DotProduct(wallNormal,idealNormal) > 0.7)) ) - {//there is a wall there.. or hit a client - if ( (anim != BOTH_WALL_RUN_LEFT - && anim != BOTH_WALL_RUN_RIGHT - && anim != BOTH_FORCEWALLRUNFLIP_START) - || (wallNormal[2] >= 0.0f&&wallNormal[2]<=0.4f/*MAX_WALL_RUN_Z_NORMAL*/) ) - {//wall-runs can only run on perfectly flat walls, sorry. + if (!doTrace || (trace.fraction < 1.0f && + (trace.entityNum < MAX_CLIENTS || DotProduct(wallNormal, idealNormal) > 0.7))) { // there is a wall there.. or hit a client + if ((anim != BOTH_WALL_RUN_LEFT && anim != BOTH_WALL_RUN_RIGHT && anim != BOTH_FORCEWALLRUNFLIP_START) || + (wallNormal[2] >= 0.0f && wallNormal[2] <= 0.4f /*MAX_WALL_RUN_Z_NORMAL*/)) { // wall-runs can only run on perfectly flat walls, sorry. int parts; - //move me to side - if ( anim == BOTH_WALL_FLIP_LEFT ) - { + // move me to side + if (anim == BOTH_WALL_FLIP_LEFT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_FLIP_RIGHT ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_FLIP_RIGHT) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_FLIP_BACK1 - || anim == BOTH_FLIP_BACK2 - || anim == BOTH_FLIP_BACK3 - || anim == BOTH_WALL_FLIP_BACK1 ) - { + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); + } else if (anim == BOTH_FLIP_BACK1 || anim == BOTH_FLIP_BACK2 || anim == BOTH_FLIP_BACK3 || anim == BOTH_WALL_FLIP_BACK1) { pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - VectorMA( pm->ps->velocity, -150, fwd, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -150, fwd, pm->ps->velocity); } /* @@ -2281,156 +1880,128 @@ static qboolean PM_CheckJump( void ) } */ - //up - if ( vertPush ) - { + // up + if (vertPush) { pm->ps->velocity[2] = vertPush; pm->ps->fd.forcePowersActive |= (1 << FP_LEVITATION); } - //animate me + // animate me parts = SETANIM_LEGS; - if ( anim == BOTH_BUTTERFLY_LEFT ) - { + if (anim == BOTH_BUTTERFLY_LEFT) { parts = SETANIM_BOTH; - pm->cmd.buttons&=~BUTTON_ATTACK; + pm->cmd.buttons &= ~BUTTON_ATTACK; pm->ps->saberMove = LS_NONE; - } - else if ( !pm->ps->weaponTime ) - { + } else if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - if ( anim == BOTH_BUTTERFLY_LEFT ) - { + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (anim == BOTH_BUTTERFLY_LEFT) { pm->ps->weaponTime = pm->ps->torsoTimer; } - PM_SetForceJumpZStart(pm->ps->origin[2]);//so we don't take damage if we land at same height + PM_SetForceJumpZStart(pm->ps->origin[2]); // so we don't take damage if we land at same height pm->ps->pm_flags |= PMF_JUMP_HELD; pm->cmd.upmove = 0; pm->ps->fd.forceJumpSound = 1; } } } - } - else - {//in the air + } else { // in the air int legsAnim = pm->ps->legsAnim; - if ( legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT ) - {//running on a wall + if (legsAnim == BOTH_WALL_RUN_LEFT || legsAnim == BOTH_WALL_RUN_RIGHT) { // running on a wall vec3_t right, traceto, mins, maxs, fwdAngles; - trace_t trace; - int anim = -1; + trace_t trace; + int anim = -1; VectorSet(mins, pm->mins[0], pm->mins[0], 0); VectorSet(maxs, pm->maxs[0], pm->maxs[0], 24); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); - if ( legsAnim == BOTH_WALL_RUN_LEFT ) - { - if ( pm->ps->legsTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( 0, (animNumber_t)BOTH_WALL_RUN_LEFT ); - if ( pm->ps->legsTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, -16, right, traceto ); + if (legsAnim == BOTH_WALL_RUN_LEFT) { + if (pm->ps->legsTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(0, (animNumber_t)BOTH_WALL_RUN_LEFT); + if (pm->ps->legsTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, -16, right, traceto); anim = BOTH_WALL_RUN_LEFT_FLIP; } } - } - else if ( legsAnim == BOTH_WALL_RUN_RIGHT ) - { - if ( pm->ps->legsTimer > 400 ) - {//not at the end of the anim - float animLen = PM_AnimLength( 0, (animNumber_t)BOTH_WALL_RUN_RIGHT ); - if ( pm->ps->legsTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, 16, right, traceto ); + } else if (legsAnim == BOTH_WALL_RUN_RIGHT) { + if (pm->ps->legsTimer > 400) { // not at the end of the anim + float animLen = PM_AnimLength(0, (animNumber_t)BOTH_WALL_RUN_RIGHT); + if (pm->ps->legsTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, 16, right, traceto); anim = BOTH_WALL_RUN_RIGHT_FLIP; } } } - if ( anim != -1 ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY ); - if ( trace.fraction < 1.0f ) - {//flip off wall + if (anim != -1) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY); + if (trace.fraction < 1.0f) { // flip off wall int parts = 0; - if ( anim == BOTH_WALL_RUN_LEFT_FLIP ) - { + if (anim == BOTH_WALL_RUN_LEFT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, 150, right, pm->ps->velocity ); - } - else if ( anim == BOTH_WALL_RUN_RIGHT_FLIP ) - { + VectorMA(pm->ps->velocity, 150, right, pm->ps->velocity); + } else if (anim == BOTH_WALL_RUN_RIGHT_FLIP) { pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, -150, right, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -150, right, pm->ps->velocity); } parts = SETANIM_LEGS; - if ( !pm->ps->weaponTime ) - { + if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->cmd.upmove = 0; } } - if ( pm->cmd.upmove != 0 ) - {//jump failed, so don't try to do normal jump code, just return + if (pm->cmd.upmove != 0) { // jump failed, so don't try to do normal jump code, just return return qfalse; } } - //NEW JKA - else if ( pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START ) - { + // NEW JKA + else if (pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START) { vec3_t fwd, traceto, mins, maxs, fwdAngles; - trace_t trace; - int anim = -1; + trace_t trace; + int anim = -1; float animLen; VectorSet(mins, pm->mins[0], pm->mins[0], 0.0f); VectorSet(maxs, pm->maxs[0], pm->maxs[0], 24.0f); - //hmm, did you mean [1] and [1]? + // hmm, did you mean [1] and [1]? VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0.0f); - AngleVectors( fwdAngles, fwd, NULL, NULL ); + AngleVectors(fwdAngles, fwd, NULL, NULL); - assert(pm_entSelf); //null pm_entSelf would be a Bad Thing - animLen = BG_AnimLength( pm_entSelf->localAnimIndex, BOTH_FORCEWALLRUNFLIP_START ); - if ( pm->ps->legsTimer < animLen - 400 ) - {//not at start of anim - VectorMA( pm->ps->origin, 16, fwd, traceto ); + assert(pm_entSelf); // null pm_entSelf would be a Bad Thing + animLen = BG_AnimLength(pm_entSelf->localAnimIndex, BOTH_FORCEWALLRUNFLIP_START); + if (pm->ps->legsTimer < animLen - 400) { // not at start of anim + VectorMA(pm->ps->origin, 16, fwd, traceto); anim = BOTH_FORCEWALLRUNFLIP_END; } - if ( anim != -1 ) - { - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID|CONTENTS_BODY ); - if ( trace.fraction < 1.0f ) - {//flip off wall + if (anim != -1) { + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID | CONTENTS_BODY); + if (trace.fraction < 1.0f) { // flip off wall int parts = SETANIM_LEGS; pm->ps->velocity[0] *= 0.5f; pm->ps->velocity[1] *= 0.5f; - VectorMA( pm->ps->velocity, -300, fwd, pm->ps->velocity ); + VectorMA(pm->ps->velocity, -300, fwd, pm->ps->velocity); pm->ps->velocity[2] += 200; - if ( !pm->ps->weaponTime ) - {//not attacking, set anim on both + if (!pm->ps->weaponTime) { // not attacking, set anim on both parts = SETANIM_BOTH; } - PM_SetAnim( parts, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - //FIXME: do damage to traceEnt, like above? - //pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - //ha ha, so silly with your silly jumpy fally flags. + PM_SetAnim(parts, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // FIXME: do damage to traceEnt, like above? + // pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + // ha ha, so silly with your silly jumpy fally flags. pm->cmd.upmove = 0; - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); } } - if ( pm->cmd.upmove != 0 ) - {//jump failed, so don't try to do normal jump code, just return + if (pm->cmd.upmove != 0) { // jump failed, so don't try to do normal jump code, just return return qfalse; } } @@ -2438,7 +2009,8 @@ static qboolean PM_CheckJump( void ) else if ( pm->cmd.forwardmove > 0 //pushing forward && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && pm->ps->velocity[2] > 200 - && PM_GroundDistance() <= 80 //unfortunately we do not have a happy ground timer like SP (this would use up more bandwidth if we wanted prediction workign right), so we'll just use the actual ground distance. + && PM_GroundDistance() <= 80 //unfortunately we do not have a happy ground timer like SP (this would use up more bandwidth if we wanted + prediction workign right), so we'll just use the actual ground distance. && !BG_InSpecialJump(pm->ps->legsAnim)) {//run up wall, flip backwards vec3_t fwd, traceto, mins, maxs, fwdAngles; @@ -2485,172 +2057,150 @@ static qboolean PM_CheckJump( void ) } } */ - else if ( pm->cmd.forwardmove > 0 //pushing forward - && pm->ps->fd.forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 - && PM_WalkableGroundDistance() <= 80 //unfortunately we do not have a happy ground timer like SP (this would use up more bandwidth if we wanted prediction workign right), so we'll just use the actual ground distance. - && (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything - {//run up wall, flip backwards - if ( allowWallRuns ) - { - //FIXME: have to be moving... make sure it's opposite the wall... or at least forward? + else if (pm->cmd.forwardmove > 0 // pushing forward + && pm->ps->fd.forceRageRecoveryTime < pm->cmd.serverTime // not in a force Rage recovery period + && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && + PM_WalkableGroundDistance() <= 80 // unfortunately we do not have a happy ground timer like SP (this would use up more bandwidth if we + // wanted prediction workign right), so we'll just use the actual ground distance. + && (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1)) // not in a flip or spin or anything + { // run up wall, flip backwards + if (allowWallRuns) { + // FIXME: have to be moving... make sure it's opposite the wall... or at least forward? int wallWalkAnim = BOTH_WALL_FLIP_BACK1; int parts = SETANIM_LEGS; - int contents = MASK_SOLID;//MASK_PLAYERSOLID;//CONTENTS_SOLID; - //qboolean kick = qtrue; - if ( pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 ) - { + int contents = MASK_SOLID; // MASK_PLAYERSOLID;//CONTENTS_SOLID; + // qboolean kick = qtrue; + if (pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2) { wallWalkAnim = BOTH_FORCEWALLRUNFLIP_START; parts = SETANIM_BOTH; - //kick = qfalse; - } - else - { - if ( !pm->ps->weaponTime ) - { + // kick = qfalse; + } else { + if (!pm->ps->weaponTime) { parts = SETANIM_BOTH; } } - //if ( PM_HasAnimation( pm->gent, wallWalkAnim ) ) - if (1) //sure, we have it! Because I SAID SO. + // if ( PM_HasAnimation( pm->gent, wallWalkAnim ) ) + if (1) // sure, we have it! Because I SAID SO. { vec3_t fwd, traceto, mins, maxs, fwdAngles; - trace_t trace; - vec3_t idealNormal; + trace_t trace; + vec3_t idealNormal; bgEntity_t *traceEnt; VectorSet(mins, pm->mins[0], pm->mins[1], 0.0f); VectorSet(maxs, pm->maxs[0], pm->maxs[1], 24.0f); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0.0f); - AngleVectors( fwdAngles, fwd, NULL, NULL ); - VectorMA( pm->ps->origin, 32, fwd, traceto ); + AngleVectors(fwdAngles, fwd, NULL, NULL); + VectorMA(pm->ps->origin, 32, fwd, traceto); - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents );//FIXME: clip brushes too? - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, contents); // FIXME: clip brushes too? + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); traceEnt = PM_BGEntForNum(trace.entityNum); - if ( trace.fraction < 1.0f - &&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(trace.plane.normal,idealNormal)>0.7) ) - {//there is a wall there + if (trace.fraction < 1.0f && ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7)) { // there is a wall there pm->ps->velocity[0] = pm->ps->velocity[1] = 0; - if ( wallWalkAnim == BOTH_FORCEWALLRUNFLIP_START ) - { - pm->ps->velocity[2] = forceJumpStrength[FORCE_LEVEL_3]/2.0f; - } - else - { - VectorMA( pm->ps->velocity, -150, fwd, pm->ps->velocity ); + if (wallWalkAnim == BOTH_FORCEWALLRUNFLIP_START) { + pm->ps->velocity[2] = forceJumpStrength[FORCE_LEVEL_3] / 2.0f; + } else { + VectorMA(pm->ps->velocity, -150, fwd, pm->ps->velocity); pm->ps->velocity[2] += 150.0f; } - //animate me - PM_SetAnim( parts, wallWalkAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - // pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; - //again with the flags! - //G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - //yucky! - PM_SetForceJumpZStart(pm->ps->origin[2]);//so we don't take damage if we land at same height + // animate me + PM_SetAnim(parts, wallWalkAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + // pm->ps->pm_flags |= PMF_JUMPING|PMF_SLOW_MO_FALL; + // again with the flags! + // G_SoundOnEnt( pm->gent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // yucky! + PM_SetForceJumpZStart(pm->ps->origin[2]); // so we don't take damage if we land at same height pm->cmd.upmove = 0; pm->ps->fd.forceJumpSound = 1; - BG_ForcePowerDrain( pm->ps, FP_LEVITATION, 5 ); + BG_ForcePowerDrain(pm->ps, FP_LEVITATION, 5); - //kick if jumping off an ent + // kick if jumping off an ent /* if ( kick && traceEnt && (traceEnt->s.eType == ET_PLAYER || traceEnt->s.eType == ET_NPC) ) { //kick that thang! pm->ps->forceKickFlip = traceEnt->s.number+1; } */ - pm->cmd.rightmove = pm->cmd.forwardmove= 0; + pm->cmd.rightmove = pm->cmd.forwardmove = 0; } } } - } - else if ( (!BG_InSpecialJump( legsAnim )//not in a special jump anim - ||BG_InReboundJump( legsAnim )//we're already in a rebound - ||BG_InBackFlip( legsAnim ) )//a backflip (needed so you can jump off a wall behind you) - //&& pm->ps->velocity[2] <= 0 - && pm->ps->velocity[2] > -1200 //not falling down very fast - && !(pm->ps->pm_flags&PMF_JUMP_HELD)//have to have released jump since last press - && (pm->cmd.forwardmove||pm->cmd.rightmove)//pushing in a direction - //&& pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period - && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2//level 3 jump or better - //&& WP_ForcePowerAvailable( pm->gent, FP_LEVITATION, 10 )//have enough force power to do another one - && BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION) - && (pm->ps->origin[2]-pm->ps->fd.forceJumpZStart) < (forceJumpHeightMax[FORCE_LEVEL_3]-(BG_ForceWallJumpStrength()/2.0f)) //can fit at least one more wall jump in (yes, using "magic numbers"... for now) - //&& (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything - ) - {//see if we're pushing at a wall and jump off it if so - if ( allowWallGrabs ) - { - //FIXME: make sure we have enough force power - //FIXME: check to see if we can go any higher - //FIXME: limit to a certain number of these in a row? - //FIXME: maybe don't require a ucmd direction, just check all 4? - //FIXME: should stick to the wall for a second, then push off... + } else if ((!BG_InSpecialJump(legsAnim) // not in a special jump anim + || BG_InReboundJump(legsAnim) // we're already in a rebound + || BG_InBackFlip(legsAnim)) // a backflip (needed so you can jump off a wall behind you) + //&& pm->ps->velocity[2] <= 0 + && pm->ps->velocity[2] > -1200 // not falling down very fast + && !(pm->ps->pm_flags & PMF_JUMP_HELD) // have to have released jump since last press + && (pm->cmd.forwardmove || pm->cmd.rightmove) // pushing in a direction + //&& pm->ps->forceRageRecoveryTime < pm->cmd.serverTime //not in a force Rage recovery period + && pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_2 // level 3 jump or better + //&& WP_ForcePowerAvailable( pm->gent, FP_LEVITATION, 10 )//have enough force power to do another one + && BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION) && + (pm->ps->origin[2] - pm->ps->fd.forceJumpZStart) < + (forceJumpHeightMax[FORCE_LEVEL_3] - + (BG_ForceWallJumpStrength() / 2.0f)) // can fit at least one more wall jump in (yes, using "magic numbers"... for now) + //&& (pm->ps->legsAnim == BOTH_JUMP1 || pm->ps->legsAnim == BOTH_INAIR1 ) )//not in a flip or spin or anything + ) { // see if we're pushing at a wall and jump off it if so + if (allowWallGrabs) { + // FIXME: make sure we have enough force power + // FIXME: check to see if we can go any higher + // FIXME: limit to a certain number of these in a row? + // FIXME: maybe don't require a ucmd direction, just check all 4? + // FIXME: should stick to the wall for a second, then push off... vec3_t checkDir, traceto, mins, maxs, fwdAngles; - trace_t trace; - vec3_t idealNormal; - int anim = -1; + trace_t trace; + vec3_t idealNormal; + int anim = -1; VectorSet(mins, pm->mins[0], pm->mins[1], 0.0f); VectorSet(maxs, pm->maxs[0], pm->maxs[1], 24.0f); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0.0f); - if ( pm->cmd.rightmove ) - { - if ( pm->cmd.rightmove > 0 ) - { + if (pm->cmd.rightmove) { + if (pm->cmd.rightmove > 0) { anim = BOTH_FORCEWALLREBOUND_RIGHT; - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - } - else if ( pm->cmd.rightmove < 0 ) - { + AngleVectors(fwdAngles, NULL, checkDir, NULL); + } else if (pm->cmd.rightmove < 0) { anim = BOTH_FORCEWALLREBOUND_LEFT; - AngleVectors( fwdAngles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); } - } - else if ( pm->cmd.forwardmove > 0 ) - { + } else if (pm->cmd.forwardmove > 0) { anim = BOTH_FORCEWALLREBOUND_FORWARD; - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - } - else if ( pm->cmd.forwardmove < 0 ) - { + AngleVectors(fwdAngles, checkDir, NULL, NULL); + } else if (pm->cmd.forwardmove < 0) { anim = BOTH_FORCEWALLREBOUND_BACK; - AngleVectors( fwdAngles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(fwdAngles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); } - if ( anim != -1 ) - {//trace in the dir we're pushing in and see if there's a vertical wall there + if (anim != -1) { // trace in the dir we're pushing in and see if there's a vertical wall there bgEntity_t *traceEnt; - VectorMA( pm->ps->origin, 8, checkDir, traceto ); - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID );//FIXME: clip brushes too? - VectorSubtract( pm->ps->origin, traceto, idealNormal ); - VectorNormalize( idealNormal ); + VectorMA(pm->ps->origin, 8, checkDir, traceto); + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID); // FIXME: clip brushes too? + VectorSubtract(pm->ps->origin, traceto, idealNormal); + VectorNormalize(idealNormal); traceEnt = PM_BGEntForNum(trace.entityNum); - if ( trace.fraction < 1.0f - &&fabs(trace.plane.normal[2]) <= 0.2f/*MAX_WALL_GRAB_SLOPE*/ - &&((trace.entityNums.solid!=SOLID_BMODEL)||DotProduct(trace.plane.normal,idealNormal)>0.7) ) - {//there is a wall there - float dot = DotProduct( pm->ps->velocity, trace.plane.normal ); - if ( dot < 1.0f ) - {//can't be heading *away* from the wall! - //grab it! - PM_GrabWallForJump( anim ); + if (trace.fraction < 1.0f && fabs(trace.plane.normal[2]) <= 0.2f /*MAX_WALL_GRAB_SLOPE*/ + && ((trace.entityNum < ENTITYNUM_WORLD && traceEnt && traceEnt->s.solid != SOLID_BMODEL) || + DotProduct(trace.plane.normal, idealNormal) > 0.7)) { // there is a wall there + float dot = DotProduct(pm->ps->velocity, trace.plane.normal); + if (dot < 1.0f) { // can't be heading *away* from the wall! + // grab it! + PM_GrabWallForJump(anim); } } } } + } else { + // FIXME: if in a butterfly, kick people away? } - else - { - //FIXME: if in a butterfly, kick people away? - } - //END NEW JKA + // END NEW JKA } } @@ -2714,29 +2264,26 @@ static qboolean PM_CheckJump( void ) } } */ - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - if ( pm->cmd.upmove > 0 ) - {//no special jumps + if (pm->cmd.upmove > 0) { // no special jumps pm->ps->velocity[2] = JUMP_VELOCITY; - PM_SetForceJumpZStart(pm->ps->origin[2]);//so we don't take damage if we land at same height + PM_SetForceJumpZStart(pm->ps->origin[2]); // so we don't take damage if we land at same height pm->ps->pm_flags |= PMF_JUMP_HELD; } - //Jumping + // Jumping pml.groundPlane = qfalse; pml.walking = qfalse; pm->ps->pm_flags |= PMF_JUMP_HELD; pm->ps->groundEntityNum = ENTITYNUM_NONE; PM_SetForceJumpZStart(pm->ps->origin[2]); - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); - //Set the animations - if ( pm->ps->gravity > 0 && !BG_InSpecialJump( pm->ps->legsAnim ) ) - { + // Set the animations + if (pm->ps->gravity > 0 && !BG_InSpecialJump(pm->ps->legsAnim)) { PM_JumpForDir(); } @@ -2747,40 +2294,40 @@ static qboolean PM_CheckJump( void ) PM_CheckWaterJump ============= */ -static qboolean PM_CheckWaterJump( void ) { - vec3_t spot; - int cont; - vec3_t flatforward; +static qboolean PM_CheckWaterJump(void) { + vec3_t spot; + int cont; + vec3_t flatforward; if (pm->ps->pm_time) { return qfalse; } // check for water jump - if ( pm->waterlevel != 2 ) { + if (pm->waterlevel != 2) { return qfalse; } flatforward[0] = pml.forward[0]; flatforward[1] = pml.forward[1]; flatforward[2] = 0; - VectorNormalize (flatforward); + VectorNormalize(flatforward); - VectorMA (pm->ps->origin, 30, flatforward, spot); + VectorMA(pm->ps->origin, 30, flatforward, spot); spot[2] += 4; - cont = pm->pointcontents (spot, pm->ps->clientNum ); - if ( !(cont & CONTENTS_SOLID) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (!(cont & CONTENTS_SOLID)) { return qfalse; } spot[2] += 16; - cont = pm->pointcontents (spot, pm->ps->clientNum ); - if ( cont & (CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY) ) { + cont = pm->pointcontents(spot, pm->ps->clientNum); + if (cont & (CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_BODY)) { return qfalse; } // jump out of water - VectorScale (pml.forward, 200, pm->ps->velocity); + VectorScale(pml.forward, 200, pm->ps->velocity); pm->ps->velocity[2] = 350; pm->ps->pm_flags |= PMF_TIME_WATERJUMP; @@ -2791,7 +2338,6 @@ static qboolean PM_CheckWaterJump( void ) { //============================================================================ - /* =================== PM_WaterJumpMove @@ -2799,10 +2345,10 @@ PM_WaterJumpMove Flying out of the water =================== */ -static void PM_WaterJumpMove( void ) { +static void PM_WaterJumpMove(void) { // waterjump has no control, but falls - PM_StepSlideMove( qtrue ); + PM_StepSlideMove(qtrue); pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; if (pm->ps->velocity[2] < 0) { @@ -2818,15 +2364,15 @@ PM_WaterMove =================== */ -static void PM_WaterMove( void ) { - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float vel; +static void PM_WaterMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float vel; - if ( PM_CheckWaterJump() ) { + if (PM_CheckWaterJump()) { PM_WaterJumpMove(); return; } @@ -2844,44 +2390,43 @@ static void PM_WaterMove( void ) { } } #endif - PM_Friction (); + PM_Friction(); - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // // user intentions // - if ( !scale ) { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; - wishvel[2] = -60; // sink towards bottom + wishvel[2] = -60; // sink towards bottom } else { - for (i=0 ; i<3 ; i++) - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + for (i = 0; i < 3; i++) + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; wishvel[2] += scale * pm->cmd.upmove; } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); - if ( wishspeed > pm->ps->speed * pm_swimScale ) { + if (wishspeed > pm->ps->speed * pm_swimScale) { wishspeed = pm->ps->speed * pm_swimScale; } - PM_Accelerate (wishdir, wishspeed, pm_wateraccelerate); + PM_Accelerate(wishdir, wishspeed, pm_wateraccelerate); // make sure we can go up slopes easily under water - if ( pml.groundPlane && DotProduct( pm->ps->velocity, pml.groundTrace.plane.normal ) < 0 ) { + if (pml.groundPlane && DotProduct(pm->ps->velocity, pml.groundTrace.plane.normal) < 0) { vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); VectorNormalize(pm->ps->velocity); VectorScale(pm->ps->velocity, vel, pm->ps->velocity); } - PM_SlideMove( qfalse ); + PM_SlideMove(qfalse); } /* @@ -2890,94 +2435,82 @@ PM_FlyVehicleMove =================== */ -static void PM_FlyVehicleMove( void ) -{ - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; - float zVel; - float fmove = 0.0f, smove = 0.0f; +static void PM_FlyVehicleMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; + float zVel; + float fmove = 0.0f, smove = 0.0f; // We don't use these here because we pre-calculate the movedir in the vehicle update anyways, and if // you leave this, you get strange motion during boarding (the player can move the vehicle). - //fmove = pm->cmd.forwardmove; - //smove = pm->cmd.rightmove; + // fmove = pm->cmd.forwardmove; + // smove = pm->cmd.rightmove; // normal slowdown - if ( pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//falling + if (pm->ps->gravity && pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum == ENTITYNUM_NONE) { // falling zVel = pm->ps->velocity[2]; - PM_Friction (); + PM_Friction(); pm->ps->velocity[2] = zVel; - } - else - { - PM_Friction (); - if ( pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { - pm->ps->velocity[2] = 0; // ignore slope movement + } else { + PM_Friction(); + if (pm->ps->velocity[2] < 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE) { + pm->ps->velocity[2] = 0; // ignore slope movement } } - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); // Get The WishVel And WishSpeed //------------------------------- - if ( pm->ps->clientNum >= MAX_CLIENTS ) - {//NPC + if (pm->ps->clientNum >= MAX_CLIENTS) { // NPC // If The UCmds Were Set, But Never Converted Into A MoveDir, Then Make The WishDir From UCmds //-------------------------------------------------------------------------------------------- - if ((fmove!=0.0f || smove!=0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) - { - //trap->Printf("Generating MoveDir\n"); - for ( i = 0 ; i < 3 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if ((fmove != 0.0f || smove != 0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) { + // trap->Printf("Generating MoveDir\n"); + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } - VectorCopy( wishvel, wishdir ); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Otherwise, Use The Move Dir //----------------------------- - else - { + else { wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); } - } - else - { - for ( i = 0 ; i < 3 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else { + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } // when going up or down slopes the wish velocity should Not be zero - // wishvel[2] = 0; + // wishvel[2] = 0; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Handle negative speed. - if ( wishspeed < 0 ) - { + if (wishspeed < 0) { wishspeed = wishspeed * -1.0f; - VectorScale( wishvel, -1.0f, wishvel ); - VectorScale( wishdir, -1.0f, wishdir ); + VectorScale(wishvel, -1.0f, wishvel); + VectorScale(wishdir, -1.0f, wishdir); } - VectorCopy( wishvel, wishdir ); - wishspeed = VectorNormalize( wishdir ); + VectorCopy(wishvel, wishdir); + wishspeed = VectorNormalize(wishdir); - PM_Accelerate( wishdir, wishspeed, 100 ); + PM_Accelerate(wishdir, wishspeed, 100); - PM_StepSlideMove( 1 ); + PM_StepSlideMove(1); } /* @@ -2987,82 +2520,76 @@ PM_FlyMove Only with the flight powerup =================== */ -static void PM_FlyMove( void ) { - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - float scale; +static void PM_FlyMove(void) { + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + float scale; // normal slowdown - PM_Friction (); + PM_Friction(); - scale = PM_CmdScale( &pm->cmd ); + scale = PM_CmdScale(&pm->cmd); - if ( pm->ps->pm_type == PM_SPECTATOR && pm->cmd.buttons & BUTTON_ALT_ATTACK) { - //turbo boost + if (pm->ps->pm_type == PM_SPECTATOR && pm->cmd.buttons & BUTTON_ALT_ATTACK) { + // turbo boost scale *= 10; } // // user intentions // - if ( !scale ) { + if (!scale) { wishvel[0] = 0; wishvel[1] = 0; - wishvel[2] = pm->ps->speed * (pm->cmd.upmove/127.0f); + wishvel[2] = pm->ps->speed * (pm->cmd.upmove / 127.0f); } else { - for (i=0 ; i<3 ; i++) { - wishvel[i] = scale * pml.forward[i]*pm->cmd.forwardmove + scale * pml.right[i]*pm->cmd.rightmove; + for (i = 0; i < 3; i++) { + wishvel[i] = scale * pml.forward[i] * pm->cmd.forwardmove + scale * pml.right[i] * pm->cmd.rightmove; } wishvel[2] += scale * pm->cmd.upmove; } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); - PM_Accelerate (wishdir, wishspeed, pm_flyaccelerate); + PM_Accelerate(wishdir, wishspeed, pm_flyaccelerate); - PM_StepSlideMove( qfalse ); + PM_StepSlideMove(qfalse); } - /* =================== PM_AirMove =================== */ -static void PM_AirMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; - float accelerate; - usercmd_t cmd; - Vehicle_t *pVeh = NULL; - - if (pm->ps->clientNum >= MAX_CLIENTS) - { - bgEntity_t *pEnt = pm_entSelf; +static void PM_AirMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; + float accelerate; + usercmd_t cmd; + Vehicle_t *pVeh = NULL; + + if (pm->ps->clientNum >= MAX_CLIENTS) { + bgEntity_t *pEnt = pm_entSelf; - if ( pEnt && pEnt->s.NPC_class == CLASS_VEHICLE ) - { + if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE) { pVeh = pEnt->m_pVehicle; } } - if (pm->ps->pm_type != PM_SPECTATOR) - { + if (pm->ps->pm_type != PM_SPECTATOR) { #if METROID_JUMP PM_CheckJump(); #else - if (pm->ps->fd.forceJumpZStart && - pm->ps->forceJumpFlip) - { + if (pm->ps->fd.forceJumpZStart && pm->ps->forceJumpFlip) { PM_CheckJump(); } #endif @@ -3073,7 +2600,7 @@ static void PM_AirMove( void ) { smove = pm->cmd.rightmove; cmd = pm->cmd; - scale = PM_CmdScale( &cmd ); + scale = PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -3081,16 +2608,14 @@ static void PM_AirMove( void ) { // project moves down to flat plane pml.forward[2] = 0; pml.right[2] = 0; - VectorNormalize (pml.forward); - VectorNormalize (pml.right); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); - if ( pVeh && pVeh->m_pVehicleInfo->hoverHeight > 0 ) - {//in a hovering vehicle, have air control - if ( 1 ) - { + if (pVeh && pVeh->m_pVehicleInfo->hoverHeight > 0) { // in a hovering vehicle, have air control + if (1) { wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy( pm->ps->moveDir, wishdir ); + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(pm->ps->moveDir, wishdir); scale = 1.0f; } #if 0 @@ -3192,76 +2717,56 @@ static void PM_AirMove( void ) { } } #endif - } - else if ( gPMDoSlowFall ) - {//no air-control - VectorClear( wishvel ); - } - else if (pm->ps->pm_type == PM_JETPACK) - { //reduced air control while not jetting - for ( i = 0 ; i < 2 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else if (gPMDoSlowFall) { // no air-control + VectorClear(wishvel); + } else if (pm->ps->pm_type == PM_JETPACK) { // reduced air control while not jetting + for (i = 0; i < 2; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } wishvel[2] = 0; - if (pm->cmd.upmove <= 0) - { - VectorScale(wishvel, 0.8f, wishvel); - } - else - { //if we are jetting then we have more control than usual - VectorScale(wishvel, 2.0f, wishvel); + if (pm->cmd.upmove <= 0) { + VectorScale(wishvel, 0.8f, wishvel); + } else { // if we are jetting then we have more control than usual + VectorScale(wishvel, 2.0f, wishvel); } - } - else - { - for ( i = 0 ; i < 2 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + } else { + for (i = 0; i < 2; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } wishvel[2] = 0; } - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; accelerate = pm_airaccelerate; - if ( pVeh && pVeh->m_pVehicleInfo->type == VH_SPEEDER ) - {//speeders have more control in air - //in mid-air + if (pVeh && pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // speeders have more control in air + // in mid-air accelerate = pVeh->m_pVehicleInfo->traction; - if ( pml.groundPlane ) - {//on a slope of some kind, shouldn't have much control and should slide a lot + if (pml.groundPlane) { // on a slope of some kind, shouldn't have much control and should slide a lot accelerate *= 0.5f; } } // not on ground, so little effect on velocity - PM_Accelerate (wishdir, wishspeed, accelerate); + PM_Accelerate(wishdir, wishspeed, accelerate); // we may have a ground plane that is very steep, even // though we don't have a groundentity // slide along the steep plane - if ( pml.groundPlane ) - { - if ( !(pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//don't slide when stuck to a wall - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - { - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (!(pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // don't slide when stuck to a wall + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } } - if ( (pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//no grav when stuck to wall - PM_StepSlideMove( qfalse ); - } - else - { - PM_StepSlideMove( qtrue ); + if ((pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // no grav when stuck to wall + PM_StepSlideMove(qfalse); + } else { + PM_StepSlideMove(qtrue); } } @@ -3271,30 +2776,28 @@ PM_WalkMove =================== */ -static void PM_WalkMove( void ) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed = 0.0f; - float scale; - usercmd_t cmd; - float accelerate; - float vel; - qboolean npcMovement = qfalse; - - if ( pm->waterlevel > 2 && DotProduct( pml.forward, pml.groundTrace.plane.normal ) > 0 ) { +static void PM_WalkMove(void) { + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed = 0.0f; + float scale; + usercmd_t cmd; + float accelerate; + float vel; + qboolean npcMovement = qfalse; + + if (pm->waterlevel > 2 && DotProduct(pml.forward, pml.groundTrace.plane.normal) > 0) { // begin swimming PM_WaterMove(); return; } - - if (pm->ps->pm_type != PM_SPECTATOR) - { - if ( PM_CheckJump () ) { + if (pm->ps->pm_type != PM_SPECTATOR) { + if (PM_CheckJump()) { // jumped away - if ( pm->waterlevel > 1 ) { + if (pm->waterlevel > 1) { PM_WaterMove(); } else { PM_AirMove(); @@ -3303,13 +2806,13 @@ static void PM_WalkMove( void ) { } } - PM_Friction (); + PM_Friction(); fmove = pm->cmd.forwardmove; smove = pm->cmd.rightmove; cmd = pm->cmd; - scale = PM_CmdScale( &cmd ); + scale = PM_CmdScale(&cmd); // set the movementDir so clients can rotate the legs for strafing PM_SetMovementDir(); @@ -3319,41 +2822,36 @@ static void PM_WalkMove( void ) { pml.right[2] = 0; // project the forward and right directions onto the ground plane - PM_ClipVelocity (pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP ); - PM_ClipVelocity (pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP ); + PM_ClipVelocity(pml.forward, pml.groundTrace.plane.normal, pml.forward, OVERCLIP); + PM_ClipVelocity(pml.right, pml.groundTrace.plane.normal, pml.right, OVERCLIP); // - VectorNormalize (pml.forward); - VectorNormalize (pml.right); + VectorNormalize(pml.forward); + VectorNormalize(pml.right); // Get The WishVel And WishSpeed //------------------------------- - if ( pm->ps->clientNum >= MAX_CLIENTS && !VectorCompare( pm->ps->moveDir, vec3_origin ) ) - {//NPC + if (pm->ps->clientNum >= MAX_CLIENTS && !VectorCompare(pm->ps->moveDir, vec3_origin)) { // NPC bgEntity_t *pEnt = pm_entSelf; - if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE) - { + if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE) { // If The UCmds Were Set, But Never Converted Into A MoveDir, Then Make The WishDir From UCmds //-------------------------------------------------------------------------------------------- - if ((fmove!=0.0f || smove!=0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) - { - //trap->Printf("Generating MoveDir\n"); - for ( i = 0 ; i < 3 ; i++ ) - { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if ((fmove != 0.0f || smove != 0.0f) && VectorCompare(pm->ps->moveDir, vec3_origin)) { + // trap->Printf("Generating MoveDir\n"); + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } - VectorCopy( wishvel, wishdir ); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // Otherwise, Use The Move Dir //----------------------------- - else - { - //wishspeed = pm->ps->speed; - VectorScale( pm->ps->moveDir, pm->ps->speed, wishvel ); - VectorCopy (wishvel, wishdir); + else { + // wishspeed = pm->ps->speed; + VectorScale(pm->ps->moveDir, pm->ps->speed, wishvel); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); } @@ -3361,59 +2859,50 @@ static void PM_WalkMove( void ) { } } - if (!npcMovement) - { - for ( i = 0 ; i < 3 ; i++ ) { - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + if (!npcMovement) { + for (i = 0; i < 3; i++) { + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; } // when going up or down slopes the wish velocity should Not be zero - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; } // clamp the speed lower if ducking - if ( pm->ps->pm_flags & PMF_DUCKED ) { - if ( wishspeed > pm->ps->speed * pm_duckScale ) { + if (pm->ps->pm_flags & PMF_DUCKED) { + if (wishspeed > pm->ps->speed * pm_duckScale) { wishspeed = pm->ps->speed * pm_duckScale; } - } - else if ( (pm->ps->pm_flags & PMF_ROLLING) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && - !PM_InRollComplete(pm->ps, pm->ps->legsAnim)) - { - if ( wishspeed > pm->ps->speed * pm_duckScale ) { + } else if ((pm->ps->pm_flags & PMF_ROLLING) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && !PM_InRollComplete(pm->ps, pm->ps->legsAnim)) { + if (wishspeed > pm->ps->speed * pm_duckScale) { wishspeed = pm->ps->speed * pm_duckScale; } } // clamp the speed lower if wading or walking on the bottom - if ( pm->waterlevel ) { - float waterScale; + if (pm->waterlevel) { + float waterScale; waterScale = pm->waterlevel / 3.0; - waterScale = 1.0 - ( 1.0 - pm_swimScale ) * waterScale; - if ( wishspeed > pm->ps->speed * waterScale ) { + waterScale = 1.0 - (1.0 - pm_swimScale) * waterScale; + if (wishspeed > pm->ps->speed * waterScale) { wishspeed = pm->ps->speed * waterScale; } } // when a player gets hit, they temporarily lose // full control, which allows them to be moved a bit - if ( pm_flying == FLY_HOVER ) - { + if (pm_flying == FLY_HOVER) { accelerate = pm_vehicleaccelerate; - } - else if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK ) - { + } else if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK) { accelerate = pm_airaccelerate; - } - else - { + } else { accelerate = pm_accelerate; } - PM_Accelerate (wishdir, wishspeed, accelerate); + PM_Accelerate(wishdir, wishspeed, accelerate); /* if (pm->ps->clientNum >= MAX_CLIENTS) { @@ -3425,19 +2914,17 @@ static void PM_WalkMove( void ) { } */ - //Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); - //Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); + // Com_Printf("velocity = %1.1f %1.1f %1.1f\n", pm->ps->velocity[0], pm->ps->velocity[1], pm->ps->velocity[2]); + // Com_Printf("velocity1 = %1.1f\n", VectorLength(pm->ps->velocity)); - if ( ( pml.groundTrace.surfaceFlags & SURF_SLICK ) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK ) - { + if ((pml.groundTrace.surfaceFlags & SURF_SLICK) || pm->ps->pm_flags & PMF_TIME_KNOCKBACK) { pm->ps->velocity[2] -= pm->ps->gravity * pml.frametime; } vel = VectorLength(pm->ps->velocity); // slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); // don't decrease velocity when going up or down a slope VectorNormalize(pm->ps->velocity); @@ -3448,67 +2935,62 @@ static void PM_WalkMove( void ) { return; } - PM_StepSlideMove( qfalse ); + PM_StepSlideMove(qfalse); - //Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); + // Com_Printf("velocity2 = %1.1f\n", VectorLength(pm->ps->velocity)); } - /* ============== PM_DeadMove ============== */ -static void PM_DeadMove( void ) { - float forward; +static void PM_DeadMove(void) { + float forward; - if ( !pml.walking ) { + if (!pml.walking) { return; } // extra friction - forward = VectorLength (pm->ps->velocity); + forward = VectorLength(pm->ps->velocity); forward -= 20; - if ( forward <= 0 ) { - VectorClear (pm->ps->velocity); + if (forward <= 0) { + VectorClear(pm->ps->velocity); } else { - VectorNormalize (pm->ps->velocity); - VectorScale (pm->ps->velocity, forward, pm->ps->velocity); + VectorNormalize(pm->ps->velocity); + VectorScale(pm->ps->velocity, forward, pm->ps->velocity); } } - /* =============== PM_NoclipMove =============== */ -static void PM_NoclipMove( void ) { - float speed, drop, friction, control, newspeed; - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - float scale; +static void PM_NoclipMove(void) { + float speed, drop, friction, control, newspeed; + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + float scale; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; // friction - speed = VectorLength (pm->ps->velocity); - if (speed < 1) - { - VectorCopy (vec3_origin, pm->ps->velocity); - } - else - { + speed = VectorLength(pm->ps->velocity); + if (speed < 1) { + VectorCopy(vec3_origin, pm->ps->velocity); + } else { drop = 0; - friction = pm_friction*1.5; // extra friction + friction = pm_friction * 1.5; // extra friction control = speed < pm_stopspeed ? pm_stopspeed : speed; - drop += control*friction*pml.frametime; + drop += control * friction * pml.frametime; // scale the velocity newspeed = speed - drop; @@ -3516,33 +2998,33 @@ static void PM_NoclipMove( void ) { newspeed = 0; newspeed /= speed; - VectorScale (pm->ps->velocity, newspeed, pm->ps->velocity); + VectorScale(pm->ps->velocity, newspeed, pm->ps->velocity); } // accelerate - scale = PM_CmdScale( &pm->cmd ); - if (pm->cmd.buttons & BUTTON_ATTACK) { //turbo boost + scale = PM_CmdScale(&pm->cmd); + if (pm->cmd.buttons & BUTTON_ATTACK) { // turbo boost scale *= 10; } - if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { //turbo boost + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // turbo boost scale *= 10; } fmove = pm->cmd.forwardmove; smove = pm->cmd.rightmove; - for (i=0 ; i<3 ; i++) - wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove; + for (i = 0; i < 3; i++) + wishvel[i] = pml.forward[i] * fmove + pml.right[i] * smove; wishvel[2] += pm->cmd.upmove; - VectorCopy (wishvel, wishdir); + VectorCopy(wishvel, wishdir); wishspeed = VectorNormalize(wishdir); wishspeed *= scale; - PM_Accelerate( wishdir, wishspeed, pm_accelerate ); + PM_Accelerate(wishdir, wishspeed, pm_accelerate); // move - VectorMA (pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); + VectorMA(pm->ps->origin, pml.frametime, pm->ps->velocity, pm->ps->origin); } //============================================================================ @@ -3554,95 +3036,69 @@ PM_FootstepForSurface Returns an event number appropriate for the groundsurface ================ */ -static int PM_FootstepForSurface( void ) -{ - if ( pml.groundTrace.surfaceFlags & SURF_NOSTEPS ) - { +static int PM_FootstepForSurface(void) { + if (pml.groundTrace.surfaceFlags & SURF_NOSTEPS) { return 0; } - return ( pml.groundTrace.surfaceFlags & MATERIAL_MASK ); + return (pml.groundTrace.surfaceFlags & MATERIAL_MASK); } -extern qboolean PM_CanRollFromSoulCal( playerState_t *ps ); -static int PM_TryRoll( void ) -{ - trace_t trace; - int anim = -1; +extern qboolean PM_CanRollFromSoulCal(playerState_t *ps); +static int PM_TryRoll(void) { + trace_t trace; + int anim = -1; vec3_t fwd, right, traceto, mins, maxs, fwdAngles; - if ( BG_SaberInAttack( pm->ps->saberMove ) || BG_SaberInSpecialAttack( pm->ps->torsoAnim ) - || BG_SpinningSaberAnim( pm->ps->legsAnim ) - || PM_SaberInStart( pm->ps->saberMove ) ) - {//attacking or spinning (or, if player, starting an attack) - if ( PM_CanRollFromSoulCal( pm->ps ) ) - {//hehe - } - else - { + if (BG_SaberInAttack(pm->ps->saberMove) || BG_SaberInSpecialAttack(pm->ps->torsoAnim) || BG_SpinningSaberAnim(pm->ps->legsAnim) || + PM_SaberInStart(pm->ps->saberMove)) { // attacking or spinning (or, if player, starting an attack) + if (PM_CanRollFromSoulCal(pm->ps)) { // hehe + } else { return 0; } } - if ((pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE) || - PM_IsRocketTrooper() || - BG_HasYsalamiri(pm->gametype, pm->ps) || - !BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION)) - { //Not using saber, or can't use jump + if ((pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE) || PM_IsRocketTrooper() || BG_HasYsalamiri(pm->gametype, pm->ps) || + !BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_LEVITATION)) { // Not using saber, or can't use jump return 0; } - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber = BG_MySaber( pm->ps->clientNum, 0 ); - if ( saber - && (saber->saberFlags&SFL_NO_ROLLS) ) - { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber = BG_MySaber(pm->ps->clientNum, 0); + if (saber && (saber->saberFlags & SFL_NO_ROLLS)) { return 0; } - saber = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber - && (saber->saberFlags&SFL_NO_ROLLS) ) - { + saber = BG_MySaber(pm->ps->clientNum, 1); + if (saber && (saber->saberFlags & SFL_NO_ROLLS)) { return 0; } } - VectorSet(mins, pm->mins[0],pm->mins[1],pm->mins[2]+STEPSIZE); - VectorSet(maxs, pm->maxs[0],pm->maxs[1],pm->ps->crouchheight); + VectorSet(mins, pm->mins[0], pm->mins[1], pm->mins[2] + STEPSIZE); + VectorSet(maxs, pm->maxs[0], pm->maxs[1], pm->ps->crouchheight); VectorSet(fwdAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( fwdAngles, fwd, right, NULL ); + AngleVectors(fwdAngles, fwd, right, NULL); - if ( pm->cmd.forwardmove ) - { //check forward/backward rolls - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { + if (pm->cmd.forwardmove) { // check forward/backward rolls + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { anim = BOTH_ROLL_B; - VectorMA( pm->ps->origin, -64, fwd, traceto ); - } - else - { + VectorMA(pm->ps->origin, -64, fwd, traceto); + } else { anim = BOTH_ROLL_F; - VectorMA( pm->ps->origin, 64, fwd, traceto ); + VectorMA(pm->ps->origin, 64, fwd, traceto); } - } - else if ( pm->cmd.rightmove > 0 ) - { //right + } else if (pm->cmd.rightmove > 0) { // right anim = BOTH_ROLL_R; - VectorMA( pm->ps->origin, 64, right, traceto ); - } - else if ( pm->cmd.rightmove < 0 ) - { //left + VectorMA(pm->ps->origin, 64, right, traceto); + } else if (pm->cmd.rightmove < 0) { // left anim = BOTH_ROLL_L; - VectorMA( pm->ps->origin, -64, right, traceto ); + VectorMA(pm->ps->origin, -64, right, traceto); } - if ( anim != -1 ) - { //We want to roll. Perform a trace to see if we can, and if so, send us into one. - pm->trace( &trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID ); - if ( trace.fraction >= 1.0f ) - { + if (anim != -1) { // We want to roll. Perform a trace to see if we can, and if so, send us into one. + pm->trace(&trace, pm->ps->origin, mins, maxs, traceto, pm->ps->clientNum, CONTENTS_SOLID); + if (trace.fraction >= 1.0f) { pm->ps->saberMove = LS_NONE; return anim; } @@ -3651,22 +3107,18 @@ static int PM_TryRoll( void ) } #ifdef _GAME -static void PM_CrashLandEffect( void ) -{ +static void PM_CrashLandEffect(void) { float delta; - if ( pm->waterlevel ) - { + if (pm->waterlevel) { return; } - delta = fabs(pml.previous_velocity[2])/10;//VectorLength( pml.previous_velocity );? - if ( delta >= 30 ) - { + delta = fabs(pml.previous_velocity[2]) / 10; // VectorLength( pml.previous_velocity );? + if (delta >= 30) { vec3_t bottom; - int effectID = -1; - int material = (pml.groundTrace.surfaceFlags&MATERIAL_MASK); - VectorSet( bottom, pm->ps->origin[0],pm->ps->origin[1],pm->ps->origin[2]+pm->mins[2]+1 ); - switch ( material ) - { + int effectID = -1; + int material = (pml.groundTrace.surfaceFlags & MATERIAL_MASK); + VectorSet(bottom, pm->ps->origin[0], pm->ps->origin[1], pm->ps->origin[2] + pm->mins[2] + 1); + switch (material) { case MATERIAL_MUD: effectID = EFFECT_LANDING_MUD; break; @@ -3684,9 +3136,8 @@ static void PM_CrashLandEffect( void ) break; } - if ( effectID != -1 ) - { - G_PlayEffect( effectID, bottom, pml.groundTrace.plane.normal ); + if (effectID != -1) { + G_PlayEffect(effectID, bottom, pml.groundTrace.plane.normal); } } } @@ -3698,13 +3149,13 @@ PM_CrashLand Check for hard landings that generate sound events ================= */ -static void PM_CrashLand( void ) { - float delta; - float dist; - float vel, acc; - float t; - float a, b, c, den; - qboolean didRoll = qfalse; +static void PM_CrashLand(void) { + float delta; + float dist; + float vel, acc; + float t; + float a, b, c, den; + qboolean didRoll = qfalse; // calculate the exact velocity on landing dist = pm->ps->origin[2] - pml.previous_origin[2]; @@ -3715,32 +3166,28 @@ static void PM_CrashLand( void ) { b = vel; c = -dist; - den = b * b - 4 * a * c; - if ( den < 0 ) { + den = b * b - 4 * a * c; + if (den < 0) { pm->ps->inAirAnim = qfalse; return; } - t = (-b - sqrt( den ) ) / ( 2 * a ); + t = (-b - sqrt(den)) / (2 * a); delta = vel + t * acc; - delta = delta*delta * 0.0001; + delta = delta * delta * 0.0001; #ifdef _GAME PM_CrashLandEffect(); #endif // ducking while falling doubles damage - if ( pm->ps->pm_flags & PMF_DUCKED ) { + if (pm->ps->pm_flags & PMF_DUCKED) { delta *= 2; } - if (pm->ps->legsAnim == BOTH_A7_KICK_F_AIR || - pm->ps->legsAnim == BOTH_A7_KICK_B_AIR || - pm->ps->legsAnim == BOTH_A7_KICK_R_AIR || - pm->ps->legsAnim == BOTH_A7_KICK_L_AIR) - { + if (pm->ps->legsAnim == BOTH_A7_KICK_F_AIR || pm->ps->legsAnim == BOTH_A7_KICK_B_AIR || pm->ps->legsAnim == BOTH_A7_KICK_R_AIR || + pm->ps->legsAnim == BOTH_A7_KICK_L_AIR) { int landAnim = -1; - switch ( pm->ps->legsAnim ) - { + switch (pm->ps->legsAnim) { case BOTH_A7_KICK_F_AIR: landAnim = BOTH_FORCELAND1; break; @@ -3754,26 +3201,17 @@ static void PM_CrashLand( void ) { landAnim = BOTH_FORCELANDLEFT1; break; } - if ( landAnim != -1 ) - { - if ( pm->ps->torsoAnim == pm->ps->legsAnim ) - { - PM_SetAnim(SETANIM_BOTH, landAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - } - else - { - PM_SetAnim(SETANIM_LEGS, landAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (landAnim != -1) { + if (pm->ps->torsoAnim == pm->ps->legsAnim) { + PM_SetAnim(SETANIM_BOTH, landAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(SETANIM_LEGS, landAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } - } - else if (pm->ps->legsAnim == BOTH_FORCEJUMPLEFT1 || - pm->ps->legsAnim == BOTH_FORCEJUMPRIGHT1 || - pm->ps->legsAnim == BOTH_FORCEJUMPBACK1 || - pm->ps->legsAnim == BOTH_FORCEJUMP1) - { + } else if (pm->ps->legsAnim == BOTH_FORCEJUMPLEFT1 || pm->ps->legsAnim == BOTH_FORCEJUMPRIGHT1 || pm->ps->legsAnim == BOTH_FORCEJUMPBACK1 || + pm->ps->legsAnim == BOTH_FORCEJUMP1) { int fjAnim; - switch (pm->ps->legsAnim) - { + switch (pm->ps->legsAnim) { case BOTH_FORCEJUMPLEFT1: fjAnim = BOTH_LANDLEFT1; break; @@ -3787,53 +3225,39 @@ static void PM_CrashLand( void ) { fjAnim = BOTH_LAND1; break; } - PM_SetAnim(SETANIM_BOTH, fjAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + PM_SetAnim(SETANIM_BOTH, fjAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } // decide which landing animation to use - else if (!BG_InRoll(pm->ps, pm->ps->legsAnim) && pm->ps->inAirAnim && !pm->ps->m_iVehicleNum) - { //only play a land animation if we transitioned into an in-air animation while off the ground - if (!BG_SaberInSpecial(pm->ps->saberMove)) - { - if ( pm->ps->pm_flags & PMF_BACKWARDS_JUMP ) { - PM_ForceLegsAnim( BOTH_LANDBACK1 ); + else if (!BG_InRoll(pm->ps, pm->ps->legsAnim) && pm->ps->inAirAnim && + !pm->ps->m_iVehicleNum) { // only play a land animation if we transitioned into an in-air animation while off the ground + if (!BG_SaberInSpecial(pm->ps->saberMove)) { + if (pm->ps->pm_flags & PMF_BACKWARDS_JUMP) { + PM_ForceLegsAnim(BOTH_LANDBACK1); } else { - PM_ForceLegsAnim( BOTH_LAND1 ); + PM_ForceLegsAnim(BOTH_LAND1); } } } - if (pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE && !PM_IsRocketTrooper()) - { //saber handles its own anims - //This will push us back into our weaponready stance from the land anim. - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { - PM_StartTorsoAnim( TORSO_WEAPONREADY4 ); - } - else - { - if (pm->ps->weapon == WP_EMPLACED_GUN) - { - PM_StartTorsoAnim( BOTH_GUNSIT1 ); - } - else - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); - } + if (pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE && !PM_IsRocketTrooper()) { // saber handles its own anims + // This will push us back into our weaponready stance from the land anim. + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + PM_StartTorsoAnim(TORSO_WEAPONREADY4); + } else { + if (pm->ps->weapon == WP_EMPLACED_GUN) { + PM_StartTorsoAnim(BOTH_GUNSIT1); + } else { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); + } } } - if (!BG_InSpecialJump(pm->ps->legsAnim) || - pm->ps->legsTimer < 1 || - (pm->ps->legsAnim) == BOTH_WALL_RUN_LEFT || - (pm->ps->legsAnim) == BOTH_WALL_RUN_RIGHT) - { //Only set the timer if we're in an anim that can be interrupted (this would not be, say, a flip) - if (!BG_InRoll(pm->ps, pm->ps->legsAnim) && pm->ps->inAirAnim) - { - if (!BG_SaberInSpecial(pm->ps->saberMove) || pm->ps->weapon != WP_SABER) - { - if (pm->ps->legsAnim != BOTH_FORCELAND1 && pm->ps->legsAnim != BOTH_FORCELANDBACK1 && - pm->ps->legsAnim != BOTH_FORCELANDRIGHT1 && pm->ps->legsAnim != BOTH_FORCELANDLEFT1) - { //don't override if we have started a force land + if (!BG_InSpecialJump(pm->ps->legsAnim) || pm->ps->legsTimer < 1 || (pm->ps->legsAnim) == BOTH_WALL_RUN_LEFT || + (pm->ps->legsAnim) == BOTH_WALL_RUN_RIGHT) { // Only set the timer if we're in an anim that can be interrupted (this would not be, say, a flip) + if (!BG_InRoll(pm->ps, pm->ps->legsAnim) && pm->ps->inAirAnim) { + if (!BG_SaberInSpecial(pm->ps->saberMove) || pm->ps->weapon != WP_SABER) { + if (pm->ps->legsAnim != BOTH_FORCELAND1 && pm->ps->legsAnim != BOTH_FORCELANDBACK1 && pm->ps->legsAnim != BOTH_FORCELANDRIGHT1 && + pm->ps->legsAnim != BOTH_FORCELANDLEFT1) { // don't override if we have started a force land pm->ps->legsTimer = TIMER_LAND; } } @@ -3842,54 +3266,48 @@ static void PM_CrashLand( void ) { pm->ps->inAirAnim = qfalse; - if (pm->ps->m_iVehicleNum) - { //don't do fall stuff while on a vehicle + if (pm->ps->m_iVehicleNum) { // don't do fall stuff while on a vehicle return; } // never take falling damage if completely underwater - if ( pm->waterlevel == 3 ) { + if (pm->waterlevel == 3) { return; } // reduce falling damage if there is standing water - if ( pm->waterlevel == 2 ) { + if (pm->waterlevel == 2) { delta *= 0.25; } - if ( pm->waterlevel == 1 ) { + if (pm->waterlevel == 1) { delta *= 0.5; } - if ( delta < 1 ) { + if (delta < 1) { return; } - if ( pm->ps->pm_flags & PMF_DUCKED ) - { - if( delta >= 2 && !PM_InOnGroundAnim( pm->ps->legsAnim ) && !PM_InKnockDown( pm->ps ) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && - pm->ps->forceHandExtend == HANDEXTEND_NONE ) - {//roll! + if (pm->ps->pm_flags & PMF_DUCKED) { + if (delta >= 2 && !PM_InOnGroundAnim(pm->ps->legsAnim) && !PM_InKnockDown(pm->ps) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && + pm->ps->forceHandExtend == HANDEXTEND_NONE) { // roll! int anim = PM_TryRoll(); - if (PM_InRollComplete(pm->ps, pm->ps->legsAnim)) - { + if (PM_InRollComplete(pm->ps, pm->ps->legsAnim)) { anim = 0; pm->ps->legsTimer = 0; pm->ps->legsAnim = 0; - PM_SetAnim(SETANIM_BOTH,BOTH_LAND1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + PM_SetAnim(SETANIM_BOTH, BOTH_LAND1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->legsTimer = TIMER_LAND; } - if ( anim ) - {//absorb some impact + if (anim) { // absorb some impact pm->ps->legsTimer = 0; delta /= 3; // /= 2 just cancels out the above delta *= 2 when landing while crouched, the roll itself should absorb a little damage pm->ps->legsAnim = 0; - if (pm->ps->torsoAnim == BOTH_A7_SOULCAL) - { //get out of it on torso + if (pm->ps->torsoAnim == BOTH_A7_SOULCAL) { // get out of it on torso pm->ps->torsoTimer = 0; } - PM_SetAnim(SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + PM_SetAnim(SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); didRoll = qtrue; } } @@ -3897,67 +3315,50 @@ static void PM_CrashLand( void ) { // SURF_NODAMAGE is used for bounce pads where you don't ever // want to take damage or play a crunch sound - if ( !(pml.groundTrace.surfaceFlags & SURF_NODAMAGE) ) { - if (delta > 7) - { + if (!(pml.groundTrace.surfaceFlags & SURF_NODAMAGE)) { + if (delta > 7) { int delta_send = (int)delta; - if (delta_send > 600) - { //will never need to know any value above this + if (delta_send > 600) { // will never need to know any value above this delta_send = 600; } - if (pm->ps->fd.forceJumpZStart) - { - if ((int)pm->ps->origin[2] >= (int)pm->ps->fd.forceJumpZStart) - { //was force jumping, landed on higher or same level as when force jump was started - if (delta_send > 8) - { + if (pm->ps->fd.forceJumpZStart) { + if ((int)pm->ps->origin[2] >= + (int)pm->ps->fd.forceJumpZStart) { // was force jumping, landed on higher or same level as when force jump was started + if (delta_send > 8) { delta_send = 8; } - } - else - { - if (delta_send > 8) - { + } else { + if (delta_send > 8) { int dif = ((int)pm->ps->fd.forceJumpZStart - (int)pm->ps->origin[2]); int dmgLess = (forceJumpHeight[pm->ps->fd.forcePowerLevel[FP_LEVITATION]] - dif); - if (dmgLess < 0) - { + if (dmgLess < 0) { dmgLess = 0; } - delta_send -= (dmgLess*0.3); + delta_send -= (dmgLess * 0.3); - if (delta_send < 8) - { + if (delta_send < 8) { delta_send = 8; } - //Com_Printf("Damage sub: %i\n", (int)((dmgLess*0.1))); + // Com_Printf("Damage sub: %i\n", (int)((dmgLess*0.1))); } } } - if (didRoll) - { //Add the appropriate event.. - PM_AddEventWithParm( EV_ROLL, delta_send ); - } - else - { - PM_AddEventWithParm( EV_FALL, delta_send ); - } - } - else - { - if (didRoll) - { - PM_AddEventWithParm( EV_ROLL, 0 ); + if (didRoll) { // Add the appropriate event.. + PM_AddEventWithParm(EV_ROLL, delta_send); + } else { + PM_AddEventWithParm(EV_FALL, delta_send); } - else - { - PM_AddEventWithParm( EV_FOOTSTEP, PM_FootstepForSurface() ); + } else { + if (didRoll) { + PM_AddEventWithParm(EV_ROLL, 0); + } else { + PM_AddEventWithParm(EV_FOOTSTEP, PM_FootstepForSurface()); } } } @@ -3974,11 +3375,11 @@ static void PM_CrashLand( void ) { PM_CorrectAllSolid ============= */ -static int PM_CorrectAllSolid( trace_t *trace ) { - int i, j, k; - vec3_t point; +static int PM_CorrectAllSolid(trace_t *trace) { + int i, j, k; + vec3_t point; - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:allsolid\n", c_pmove); } @@ -3987,16 +3388,16 @@ static int PM_CorrectAllSolid( trace_t *trace ) { for (j = -1; j <= 1; j++) { for (k = -1; k <= 1; k++) { VectorCopy(pm->ps->origin, point); - point[0] += (float) i; - point[1] += (float) j; - point[2] += (float) k; - pm->trace (trace, point, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); - if ( !trace->allsolid ) { + point[0] += (float)i; + point[1] += (float)j; + point[2] += (float)k; + pm->trace(trace, point, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); + if (!trace->allsolid) { point[0] = pm->ps->origin[0]; point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] - 0.25; - pm->trace (trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); + pm->trace(trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); pml.groundTrace = *trace; return qtrue; } @@ -4018,80 +3419,69 @@ PM_GroundTraceMissed The ground trace didn't hit a surface, so we are in freefall ============= */ -static void PM_GroundTraceMissed( void ) { - trace_t trace; - vec3_t point; - - //rww - don't want to do this when handextend_choke, because you can be standing on the ground - //while still holding your throat. - if ( pm->ps->pm_type == PM_FLOAT ) - { - //we're assuming this is because you're being choked +static void PM_GroundTraceMissed(void) { + trace_t trace; + vec3_t point; + + // rww - don't want to do this when handextend_choke, because you can be standing on the ground + // while still holding your throat. + if (pm->ps->pm_type == PM_FLOAT) { + // we're assuming this is because you're being choked int parts = SETANIM_LEGS; - //rww - also don't use SETANIM_FLAG_HOLD, it will cause the legs to float around a bit before going into - //a proper anim even when on the ground. + // rww - also don't use SETANIM_FLAG_HOLD, it will cause the legs to float around a bit before going into + // a proper anim even when on the ground. PM_SetAnim(parts, BOTH_CHOKE3, SETANIM_FLAG_OVERRIDE); + } else if (pm->ps->pm_type == PM_JETPACK) { // jetpacking + // rww - also don't use SETANIM_FLAG_HOLD, it will cause the legs to float around a bit before going into + // a proper anim even when on the ground. + // PM_SetAnim(SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE); } - else if ( pm->ps->pm_type == PM_JETPACK ) - {//jetpacking - //rww - also don't use SETANIM_FLAG_HOLD, it will cause the legs to float around a bit before going into - //a proper anim even when on the ground. - //PM_SetAnim(SETANIM_LEGS,BOTH_FORCEJUMP1,SETANIM_FLAG_OVERRIDE); - } - //If the anim is choke3, act like we just went into the air because we aren't in a float - else if ( pm->ps->groundEntityNum != ENTITYNUM_NONE || (pm->ps->legsAnim) == BOTH_CHOKE3 ) - { + // If the anim is choke3, act like we just went into the air because we aren't in a float + else if (pm->ps->groundEntityNum != ENTITYNUM_NONE || (pm->ps->legsAnim) == BOTH_CHOKE3) { // we just transitioned into freefall - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:lift\n", c_pmove); } // if they aren't in a jumping animation and the ground is a ways away, force into it // if we didn't do the trace, the player would be backflipping down staircases - VectorCopy( pm->ps->origin, point ); + VectorCopy(pm->ps->origin, point); point[2] -= 64; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); - if ( trace.fraction == 1.0 || pm->ps->pm_type == PM_FLOAT ) { - if ( pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags&PMF_JUMP_HELD)) - { - //PM_SetAnim(SETANIM_LEGS,BOTH_INAIR1,SETANIM_FLAG_OVERRIDE); - PM_SetAnim(SETANIM_LEGS,BOTH_INAIR1,0); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); + if (trace.fraction == 1.0 || pm->ps->pm_type == PM_FLOAT) { + if (pm->ps->velocity[2] <= 0 && !(pm->ps->pm_flags & PMF_JUMP_HELD)) { + // PM_SetAnim(SETANIM_LEGS,BOTH_INAIR1,SETANIM_FLAG_OVERRIDE); + PM_SetAnim(SETANIM_LEGS, BOTH_INAIR1, 0); pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else if ( pm->cmd.forwardmove >= 0 ) - { - PM_SetAnim(SETANIM_LEGS,BOTH_JUMP1,SETANIM_FLAG_OVERRIDE); + } else if (pm->cmd.forwardmove >= 0) { + PM_SetAnim(SETANIM_LEGS, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE); pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; - } - else - { - PM_SetAnim(SETANIM_LEGS,BOTH_JUMPBACK1,SETANIM_FLAG_OVERRIDE); + } else { + PM_SetAnim(SETANIM_LEGS, BOTH_JUMPBACK1, SETANIM_FLAG_OVERRIDE); pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; } pm->ps->inAirAnim = qtrue; } - } - else if (!pm->ps->inAirAnim) - { + } else if (!pm->ps->inAirAnim) { // if they aren't in a jumping animation and the ground is a ways away, force into it // if we didn't do the trace, the player would be backflipping down staircases - VectorCopy( pm->ps->origin, point ); + VectorCopy(pm->ps->origin, point); point[2] -= 64; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); - if ( trace.fraction == 1.0 || pm->ps->pm_type == PM_FLOAT ) - { + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); + if (trace.fraction == 1.0 || pm->ps->pm_type == PM_FLOAT) { pm->ps->inAirAnim = qtrue; } } - if (PM_InRollComplete(pm->ps, pm->ps->legsAnim)) - { //Client won't catch an animation restart because it only checks frame against incoming frame, so if you roll when you land after rolling - //off of something it won't replay the roll anim unless we switch it off in the air. This fixes that. - PM_SetAnim(SETANIM_BOTH,BOTH_INAIR1,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (PM_InRollComplete( + pm->ps, + pm->ps->legsAnim)) { // Client won't catch an animation restart because it only checks frame against incoming frame, so if you roll when you land + // after rolling off of something it won't replay the roll anim unless we switch it off in the air. This fixes that. + PM_SetAnim(SETANIM_BOTH, BOTH_INAIR1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->inAirAnim = qtrue; } @@ -4100,23 +3490,20 @@ static void PM_GroundTraceMissed( void ) { pml.walking = qfalse; } - /* ============= PM_GroundTrace ============= */ -static void PM_GroundTrace( void ) { - vec3_t point; - trace_t trace; +static void PM_GroundTrace(void) { + vec3_t point; + trace_t trace; float minNormal = (float)MIN_WALK_NORMAL; - if ( pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { bgEntity_t *pEnt = pm_entSelf; - if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE) - { + if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE) { minNormal = pEnt->m_pVehicle->m_pVehicleInfo->maxSlope; } } @@ -4125,17 +3512,16 @@ static void PM_GroundTrace( void ) { point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] - 0.25; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, point, pm->ps->clientNum, pm->tracemask); pml.groundTrace = trace; // do something corrective if the trace starts in a solid... - if ( trace.allsolid ) { - if ( !PM_CorrectAllSolid(&trace) ) + if (trace.allsolid) { + if (!PM_CorrectAllSolid(&trace)) return; } - if (pm->ps->pm_type == PM_FLOAT || pm->ps->pm_type == PM_JETPACK) - { + if (pm->ps->pm_type == PM_FLOAT || pm->ps->pm_type == PM_JETPACK) { PM_GroundTraceMissed(); pml.groundPlane = qfalse; pml.walking = qfalse; @@ -4143,7 +3529,7 @@ static void PM_GroundTrace( void ) { } // if the trace didn't hit anything, we are in free fall - if ( trace.fraction == 1.0 ) { + if (trace.fraction == 1.0) { PM_GroundTraceMissed(); pml.groundPlane = qfalse; pml.walking = qfalse; @@ -4151,16 +3537,16 @@ static void PM_GroundTrace( void ) { } // check if getting thrown off the ground - if ( pm->ps->velocity[2] > 0 && DotProduct( pm->ps->velocity, trace.plane.normal ) > 10 ) { - if ( pm->debugLevel ) { + if (pm->ps->velocity[2] > 0 && DotProduct(pm->ps->velocity, trace.plane.normal) > 10) { + if (pm->debugLevel) { Com_Printf("%i:kickoff\n", c_pmove); } // go into jump animation - if ( pm->cmd.forwardmove >= 0 ) { - PM_ForceLegsAnim( BOTH_JUMP1 ); + if (pm->cmd.forwardmove >= 0) { + PM_ForceLegsAnim(BOTH_JUMP1); pm->ps->pm_flags &= ~PMF_BACKWARDS_JUMP; } else { - PM_ForceLegsAnim( BOTH_JUMPBACK1 ); + PM_ForceLegsAnim(BOTH_JUMPBACK1); pm->ps->pm_flags |= PMF_BACKWARDS_JUMP; } @@ -4171,8 +3557,8 @@ static void PM_GroundTrace( void ) { } // slopes that are too steep will not be considered onground - if ( trace.plane.normal[2] < minNormal ) { - if ( pm->debugLevel ) { + if (trace.plane.normal[2] < minNormal) { + if (pm->debugLevel) { Com_Printf("%i:steep\n", c_pmove); } pm->ps->groundEntityNum = ENTITYNUM_NONE; @@ -4185,44 +3571,30 @@ static void PM_GroundTrace( void ) { pml.walking = qtrue; // hitting solid ground will end a waterjump - if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) - { + if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { pm->ps->pm_flags &= ~(PMF_TIME_WATERJUMP | PMF_TIME_LAND); pm->ps->pm_time = 0; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // just hit the ground - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:Land\n", c_pmove); } PM_CrashLand(); #ifdef _GAME - if (pm->ps->clientNum < MAX_CLIENTS && - !pm->ps->m_iVehicleNum && - trace.entityNum < ENTITYNUM_WORLD && - trace.entityNum >= MAX_CLIENTS && - !pm->ps->zoomMode && - pm_entSelf) - { //check if we landed on a vehicle + if (pm->ps->clientNum < MAX_CLIENTS && !pm->ps->m_iVehicleNum && trace.entityNum < ENTITYNUM_WORLD && trace.entityNum >= MAX_CLIENTS && + !pm->ps->zoomMode && pm_entSelf) { // check if we landed on a vehicle gentity_t *trEnt = &g_entities[trace.entityNum]; - if (trEnt->inuse && trEnt->client && trEnt->s.eType == ET_NPC && trEnt->s.NPC_class == CLASS_VEHICLE && - !trEnt->client->ps.m_iVehicleNum && - trEnt->m_pVehicle && - trEnt->m_pVehicle->m_pVehicleInfo->type != VH_WALKER && - trEnt->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) - { //it's a vehicle alright, let's board it.. if it's not an atst or ship - if (!BG_SaberInSpecial(pm->ps->saberMove) && - pm->ps->forceHandExtend == HANDEXTEND_NONE && - pm->ps->weaponTime <= 0) - { + if (trEnt->inuse && trEnt->client && trEnt->s.eType == ET_NPC && trEnt->s.NPC_class == CLASS_VEHICLE && !trEnt->client->ps.m_iVehicleNum && + trEnt->m_pVehicle && trEnt->m_pVehicle->m_pVehicleInfo->type != VH_WALKER && + trEnt->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) { // it's a vehicle alright, let's board it.. if it's not an atst or ship + if (!BG_SaberInSpecial(pm->ps->saberMove) && pm->ps->forceHandExtend == HANDEXTEND_NONE && pm->ps->weaponTime <= 0) { gentity_t *servEnt = (gentity_t *)pm_entSelf; - if (level.gametype < GT_TEAM || - !trEnt->alliedTeam || - (trEnt->alliedTeam == servEnt->client->sess.sessionTeam)) - { //not belonging to a team, or client is on same team + if (level.gametype < GT_TEAM || !trEnt->alliedTeam || + (trEnt->alliedTeam == servEnt->client->sess.sessionTeam)) { // not belonging to a team, or client is on same team trEnt->m_pVehicle->m_pVehicleInfo->Board(trEnt->m_pVehicle, pm_entSelf); } } @@ -4231,7 +3603,7 @@ static void PM_GroundTrace( void ) { #endif // don't do landing time if we were just going down a slope - if ( pml.previous_velocity[2] < -200 ) { + if (pml.previous_velocity[2] < -200) { // don't allow another jump for a little while pm->ps->pm_flags |= PMF_TIME_LAND; pm->ps->pm_time = 250; @@ -4241,20 +3613,19 @@ static void PM_GroundTrace( void ) { pm->ps->groundEntityNum = trace.entityNum; pm->ps->lastOnGround = pm->cmd.serverTime; - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); } - /* ============= PM_SetWaterLevel ============= */ -static void PM_SetWaterLevel( void ) { - vec3_t point; - int cont; - int sample1; - int sample2; +static void PM_SetWaterLevel(void) { + vec3_t point; + int cont; + int sample1; + int sample2; // // get waterlevel, accounting for ducking @@ -4265,39 +3636,34 @@ static void PM_SetWaterLevel( void ) { point[0] = pm->ps->origin[0]; point[1] = pm->ps->origin[1]; point[2] = pm->ps->origin[2] + MINS_Z + 1; - cont = pm->pointcontents( point, pm->ps->clientNum ); + cont = pm->pointcontents(point, pm->ps->clientNum); - if ( cont & MASK_WATER ) { + if (cont & MASK_WATER) { sample2 = pm->ps->viewheight - MINS_Z; sample1 = sample2 / 2; pm->watertype = cont; pm->waterlevel = 1; point[2] = pm->ps->origin[2] + MINS_Z + sample1; - cont = pm->pointcontents (point, pm->ps->clientNum ); - if ( cont & MASK_WATER ) { + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & MASK_WATER) { pm->waterlevel = 2; point[2] = pm->ps->origin[2] + MINS_Z + sample2; - cont = pm->pointcontents (point, pm->ps->clientNum ); - if ( cont & MASK_WATER ){ + cont = pm->pointcontents(point, pm->ps->clientNum); + if (cont & MASK_WATER) { pm->waterlevel = 3; } } } - } -qboolean PM_CheckDualForwardJumpDuck( void ) -{ +qboolean PM_CheckDualForwardJumpDuck(void) { qboolean resized = qfalse; - if ( pm->ps->legsAnim == BOTH_JUMPATTACK6 ) - { - //dynamically reduce bounding box to let character sail over heads of enemies - if ( ( pm->ps->legsTimer >= 1450 - && PM_AnimLength( 0, BOTH_JUMPATTACK6 ) - pm->ps->legsTimer >= 400 ) - ||(pm->ps->legsTimer >= 400 - && PM_AnimLength( 0, BOTH_JUMPATTACK6 ) - pm->ps->legsTimer >= 1100 ) ) - {//in a part of the anim that we're pretty much sideways in, raise up the mins + if (pm->ps->legsAnim == BOTH_JUMPATTACK6) { + // dynamically reduce bounding box to let character sail over heads of enemies + if ((pm->ps->legsTimer >= 1450 && PM_AnimLength(0, BOTH_JUMPATTACK6) - pm->ps->legsTimer >= 400) || + (pm->ps->legsTimer >= 400 && + PM_AnimLength(0, BOTH_JUMPATTACK6) - pm->ps->legsTimer >= 1100)) { // in a part of the anim that we're pretty much sideways in, raise up the mins pm->mins[2] = 0; pm->ps->pm_flags |= PMF_FIX_MINS; resized = qtrue; @@ -4306,98 +3672,83 @@ qboolean PM_CheckDualForwardJumpDuck( void ) return resized; } -void PM_CheckFixMins( void ) -{ - if ( (pm->ps->pm_flags&PMF_FIX_MINS) )// pm->mins[2] > DEFAULT_MINS_2 ) - {//drop the mins back down - //do a trace to make sure it's okay - trace_t trace; +void PM_CheckFixMins(void) { + if ((pm->ps->pm_flags & PMF_FIX_MINS)) // pm->mins[2] > DEFAULT_MINS_2 ) + { // drop the mins back down + // do a trace to make sure it's okay + trace_t trace; vec3_t end, curMins, curMaxs; - VectorSet( end, pm->ps->origin[0], pm->ps->origin[1], pm->ps->origin[2]+MINS_Z ); - VectorSet( curMins, pm->mins[0], pm->mins[1], 0 ); - VectorSet( curMaxs, pm->maxs[0], pm->maxs[1], pm->ps->standheight ); + VectorSet(end, pm->ps->origin[0], pm->ps->origin[1], pm->ps->origin[2] + MINS_Z); + VectorSet(curMins, pm->mins[0], pm->mins[1], 0); + VectorSet(curMaxs, pm->maxs[0], pm->maxs[1], pm->ps->standheight); - pm->trace( &trace, pm->ps->origin, curMins, curMaxs, end, pm->ps->clientNum, pm->tracemask ); - if ( !trace.allsolid && !trace.startsolid ) - {//should never start in solid - if ( trace.fraction >= 1.0f ) - {//all clear - //drop the bottom of my bbox back down + pm->trace(&trace, pm->ps->origin, curMins, curMaxs, end, pm->ps->clientNum, pm->tracemask); + if (!trace.allsolid && !trace.startsolid) { // should never start in solid + if (trace.fraction >= 1.0f) { // all clear + // drop the bottom of my bbox back down pm->mins[2] = MINS_Z; pm->ps->pm_flags &= ~PMF_FIX_MINS; - } - else - {//move me up so the bottom of my bbox will be where the trace ended, at least - //need to trace up, too - float updist = ((1.0f-trace.fraction) * -MINS_Z); - end[2] = pm->ps->origin[2]+updist; - pm->trace( &trace, pm->ps->origin, curMins, curMaxs, end, pm->ps->clientNum, pm->tracemask ); - if ( !trace.allsolid && !trace.startsolid ) - {//should never start in solid - if ( trace.fraction >= 1.0f ) - {//all clear - //move me up + } else { // move me up so the bottom of my bbox will be where the trace ended, at least + // need to trace up, too + float updist = ((1.0f - trace.fraction) * -MINS_Z); + end[2] = pm->ps->origin[2] + updist; + pm->trace(&trace, pm->ps->origin, curMins, curMaxs, end, pm->ps->clientNum, pm->tracemask); + if (!trace.allsolid && !trace.startsolid) { // should never start in solid + if (trace.fraction >= 1.0f) { // all clear + // move me up pm->ps->origin[2] += updist; - //drop the bottom of my bbox back down + // drop the bottom of my bbox back down pm->mins[2] = MINS_Z; pm->ps->pm_flags &= ~PMF_FIX_MINS; - } - else - {//crap, no room to expand, so just crouch us - if ( pm->ps->legsAnim != BOTH_JUMPATTACK6 - || pm->ps->legsTimer <= 200 ) - {//at the end of the anim, and we can't leave ourselves like this - //so drop the maxs, put the mins back and move us up + } else { // crap, no room to expand, so just crouch us + if (pm->ps->legsAnim != BOTH_JUMPATTACK6 || pm->ps->legsTimer <= 200) { // at the end of the anim, and we can't leave ourselves like + // this + // so drop the maxs, put the mins back and move us up pm->maxs[2] += MINS_Z; pm->ps->origin[2] -= MINS_Z; pm->mins[2] = MINS_Z; - //this way we'll be in a crouch when we're done - if ( pm->ps->legsAnim == BOTH_JUMPATTACK6 ) - { + // this way we'll be in a crouch when we're done + if (pm->ps->legsAnim == BOTH_JUMPATTACK6) { pm->ps->legsTimer = pm->ps->torsoTimer = 0; } pm->ps->pm_flags |= PMF_DUCKED; - //FIXME: do we need to set a crouch anim here? + // FIXME: do we need to set a crouch anim here? pm->ps->pm_flags &= ~PMF_FIX_MINS; } } - }//crap, stuck + } // crap, stuck } - }//crap, stuck! + } // crap, stuck! } } -static qboolean PM_CanStand ( void ) -{ - qboolean canStand = qtrue; - float x, y; - trace_t trace; - - const vec3_t lineMins = { -5.0f, -5.0f, -2.5f }; - const vec3_t lineMaxs = { 5.0f, 5.0f, 0.0f }; - - for ( x = pm->mins[0] + 5.0f; canStand && x <= (pm->maxs[0] - 5.0f); x += 10.0f ) - { - for ( y = pm->mins[1] + 5.0f; y <= (pm->maxs[1] - 5.0f); y += 10.0f ) - { - vec3_t start, end;// - VectorSet( start, x, y, pm->maxs[2] ); - VectorSet( end, x, y, pm->ps->standheight ); - - VectorAdd (start, pm->ps->origin, start); - VectorAdd (end, pm->ps->origin, end); - - pm->trace (&trace, start, lineMins, lineMaxs, end, pm->ps->clientNum, pm->tracemask); - if ( trace.allsolid || trace.fraction < 1.0f ) - { +static qboolean PM_CanStand(void) { + qboolean canStand = qtrue; + float x, y; + trace_t trace; + + const vec3_t lineMins = {-5.0f, -5.0f, -2.5f}; + const vec3_t lineMaxs = {5.0f, 5.0f, 0.0f}; + + for (x = pm->mins[0] + 5.0f; canStand && x <= (pm->maxs[0] - 5.0f); x += 10.0f) { + for (y = pm->mins[1] + 5.0f; y <= (pm->maxs[1] - 5.0f); y += 10.0f) { + vec3_t start, end; // + VectorSet(start, x, y, pm->maxs[2]); + VectorSet(end, x, y, pm->ps->standheight); + + VectorAdd(start, pm->ps->origin, start); + VectorAdd(end, pm->ps->origin, end); + + pm->trace(&trace, start, lineMins, lineMaxs, end, pm->ps->clientNum, pm->tracemask); + if (trace.allsolid || trace.fraction < 1.0f) { canStand = qfalse; break; } } } - return canStand; + return canStand; } /* @@ -4407,28 +3758,23 @@ PM_CheckDuck Sets mins, maxs, and pm->ps->viewheight ============== */ -static void PM_CheckDuck (void) -{ -// trace_t trace; +static void PM_CheckDuck(void) { + // trace_t trace; - if ( pm->ps->m_iVehicleNum > 0 && pm->ps->m_iVehicleNum < ENTITYNUM_NONE ) - {//riding a vehicle or are a vehicle - //no ducking or rolling when on a vehicle - //right? not even on ones that you just ride on top of? + if (pm->ps->m_iVehicleNum > 0 && pm->ps->m_iVehicleNum < ENTITYNUM_NONE) { // riding a vehicle or are a vehicle + // no ducking or rolling when on a vehicle + // right? not even on ones that you just ride on top of? pm->ps->pm_flags &= ~PMF_DUCKED; pm->ps->pm_flags &= ~PMF_ROLLING; - //NOTE: we don't clear the pm->cmd.upmove here because - //the vehicle code may need it later... but, for riders, - //it should have already been copied over to the vehicle, right? + // NOTE: we don't clear the pm->cmd.upmove here because + // the vehicle code may need it later... but, for riders, + // it should have already been copied over to the vehicle, right? - if (pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { return; } if (pm_entVeh && pm_entVeh->m_pVehicle && - (pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || - pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)) - { + (pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)) { trace_t solidTr; pm->mins[0] = -16; @@ -4437,30 +3783,25 @@ static void PM_CheckDuck (void) pm->maxs[0] = 16; pm->maxs[1] = 16; - pm->maxs[2] = pm->ps->standheight;//DEFAULT_MAXS_2; + pm->maxs[2] = pm->ps->standheight; // DEFAULT_MAXS_2; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; - pm->trace (&solidTr, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->m_iVehicleNum, pm->tracemask); - if (solidTr.startsolid || solidTr.allsolid || solidTr.fraction != 1.0f) - { //whoops, can't fit here. Down to 0! + pm->trace(&solidTr, pm->ps->origin, pm->mins, pm->maxs, pm->ps->origin, pm->ps->m_iVehicleNum, pm->tracemask); + if (solidTr.startsolid || solidTr.allsolid || solidTr.fraction != 1.0f) { // whoops, can't fit here. Down to 0! VectorClear(pm->mins); VectorClear(pm->maxs); #ifdef _GAME { gentity_t *me = &g_entities[pm->ps->clientNum]; - if (me->inuse && me->client) - { //yeah, this is a really terrible hack. + if (me->inuse && me->client) { // yeah, this is a really terrible hack. me->client->solidHack = level.time + 200; } } #endif } } - } - else - { - if (pm->ps->clientNum < MAX_CLIENTS) - { + } else { + if (pm->ps->clientNum < MAX_CLIENTS) { pm->mins[0] = -15; pm->mins[1] = -15; @@ -4468,53 +3809,38 @@ static void PM_CheckDuck (void) pm->maxs[1] = 15; } - if ( PM_CheckDualForwardJumpDuck() ) - {//special anim resizing us - } - else - { + if (PM_CheckDualForwardJumpDuck()) { // special anim resizing us + } else { PM_CheckFixMins(); - if ( !pm->mins[2] ) - { + if (!pm->mins[2]) { pm->mins[2] = MINS_Z; } } - if (pm->ps->pm_type == PM_DEAD && pm->ps->clientNum < MAX_CLIENTS) - { + if (pm->ps->pm_type == PM_DEAD && pm->ps->clientNum < MAX_CLIENTS) { pm->maxs[2] = -8; pm->ps->viewheight = DEAD_VIEWHEIGHT; return; } - if (BG_InRoll(pm->ps, pm->ps->legsAnim) && !BG_KickingAnim(pm->ps->legsAnim)) - { - pm->maxs[2] = pm->ps->crouchheight; //CROUCH_MAXS_2; + if (BG_InRoll(pm->ps, pm->ps->legsAnim) && !BG_KickingAnim(pm->ps->legsAnim)) { + pm->maxs[2] = pm->ps->crouchheight; // CROUCH_MAXS_2; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; pm->ps->pm_flags &= ~PMF_DUCKED; pm->ps->pm_flags |= PMF_ROLLING; return; - } - else if (pm->ps->pm_flags & PMF_ROLLING) - { - if ( PM_CanStand() ) { + } else if (pm->ps->pm_flags & PMF_ROLLING) { + if (PM_CanStand()) { pm->maxs[2] = pm->ps->standheight; pm->ps->pm_flags &= ~PMF_ROLLING; } - } - else if (pm->cmd.upmove < 0 || - pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || - pm->ps->forceHandExtend == HANDEXTEND_PRETHROWN || - pm->ps->forceHandExtend == HANDEXTEND_POSTTHROWN) - { // duck + } else if (pm->cmd.upmove < 0 || pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || pm->ps->forceHandExtend == HANDEXTEND_PRETHROWN || + pm->ps->forceHandExtend == HANDEXTEND_POSTTHROWN) { // duck pm->ps->pm_flags |= PMF_DUCKED; - } - else - { // stand up if possible - if (pm->ps->pm_flags & PMF_DUCKED) - { - if ( PM_CanStand() ) { + } else { // stand up if possible + if (pm->ps->pm_flags & PMF_DUCKED) { + if (PM_CanStand()) { pm->maxs[2] = pm->ps->standheight; pm->ps->pm_flags &= ~PMF_DUCKED; } @@ -4522,29 +3848,20 @@ static void PM_CheckDuck (void) } } - if (pm->ps->pm_flags & PMF_DUCKED) - { - pm->maxs[2] = pm->ps->crouchheight;//CROUCH_MAXS_2; + if (pm->ps->pm_flags & PMF_DUCKED) { + pm->maxs[2] = pm->ps->crouchheight; // CROUCH_MAXS_2; pm->ps->viewheight = CROUCH_VIEWHEIGHT; - } - else if (pm->ps->pm_flags & PMF_ROLLING) - { - pm->maxs[2] = pm->ps->crouchheight;//CROUCH_MAXS_2; + } else if (pm->ps->pm_flags & PMF_ROLLING) { + pm->maxs[2] = pm->ps->crouchheight; // CROUCH_MAXS_2; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; - } - else - { - pm->maxs[2] = pm->ps->standheight;//DEFAULT_MAXS_2; + } else { + pm->maxs[2] = pm->ps->standheight; // DEFAULT_MAXS_2; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; } } - - //=================================================================== - - /* ============== PM_Use @@ -4554,17 +3871,15 @@ Generates a use event */ #define USE_DELAY 2000 -void PM_Use( void ) -{ - if ( pm->ps->useTime > 0 ) - pm->ps->useTime -= 100;//pm->cmd.msec; +void PM_Use(void) { + if (pm->ps->useTime > 0) + pm->ps->useTime -= 100; // pm->cmd.msec; - if ( pm->ps->useTime > 0 ) { + if (pm->ps->useTime > 0) { return; } - if ( ! (pm->cmd.buttons & BUTTON_USE ) ) - { + if (!(pm->cmd.buttons & BUTTON_USE)) { pm->useEvent = 0; pm->ps->useTime = 0; return; @@ -4574,31 +3889,27 @@ void PM_Use( void ) pm->ps->useTime = USE_DELAY; } -qboolean PM_WalkingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_WALK1: //# Normal walk - case BOTH_WALK2: //# Normal walk with saber - case BOTH_WALK_STAFF: //# Normal walk with staff - case BOTH_WALK_DUAL: //# Normal walk with staff - case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) - case BOTH_WALK6: //# Slow walk for Luke (cin 12) - case BOTH_WALK7: //# Fast walk - case BOTH_WALKBACK1: //# Walk1 backwards - case BOTH_WALKBACK2: //# Walk2 backwards - case BOTH_WALKBACK_STAFF: //# Walk backwards with staff - case BOTH_WALKBACK_DUAL: //# Walk backwards with dual +qboolean PM_WalkingAnim(int anim) { + switch (anim) { + case BOTH_WALK1: //# Normal walk + case BOTH_WALK2: //# Normal walk with saber + case BOTH_WALK_STAFF: //# Normal walk with staff + case BOTH_WALK_DUAL: //# Normal walk with staff + case BOTH_WALK5: //# Tavion taunting Kyle (cin 22) + case BOTH_WALK6: //# Slow walk for Luke (cin 12) + case BOTH_WALK7: //# Fast walk + case BOTH_WALKBACK1: //# Walk1 backwards + case BOTH_WALKBACK2: //# Walk2 backwards + case BOTH_WALKBACK_STAFF: //# Walk backwards with staff + case BOTH_WALKBACK_DUAL: //# Walk backwards with dual return qtrue; break; } return qfalse; } -qboolean PM_RunningAnim( int anim ) -{ - switch ( (anim) ) - { +qboolean PM_RunningAnim(int anim) { + switch ((anim)) { case BOTH_RUN1: case BOTH_RUN2: case BOTH_RUN_STAFF: @@ -4607,146 +3918,136 @@ qboolean PM_RunningAnim( int anim ) case BOTH_RUNBACK2: case BOTH_RUNBACK_STAFF: case BOTH_RUNBACK_DUAL: - case BOTH_RUN1START: //# Start into full run1 + case BOTH_RUN1START: //# Start into full run1 case BOTH_RUN1STOP: //# Stop from full run1 case BOTH_RUNSTRAFE_LEFT1: //# Sidestep left: should loop - case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop + case BOTH_RUNSTRAFE_RIGHT1: //# Sidestep right: should loop return qtrue; break; } return qfalse; } -qboolean PM_SwimmingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_SWIM_IDLE1: //# Swimming Idle 1 - case BOTH_SWIMFORWARD: //# Swim forward loop - case BOTH_SWIMBACKWARD: //# Swim backward loop +qboolean PM_SwimmingAnim(int anim) { + switch (anim) { + case BOTH_SWIM_IDLE1: //# Swimming Idle 1 + case BOTH_SWIMFORWARD: //# Swim forward loop + case BOTH_SWIMBACKWARD: //# Swim backward loop return qtrue; break; } return qfalse; } -qboolean PM_RollingAnim( int anim ) -{ - switch ( anim ) - { - case BOTH_ROLL_F: //# Roll forward - case BOTH_ROLL_B: //# Roll backward - case BOTH_ROLL_L: //# Roll left - case BOTH_ROLL_R: //# Roll right +qboolean PM_RollingAnim(int anim) { + switch (anim) { + case BOTH_ROLL_F: //# Roll forward + case BOTH_ROLL_B: //# Roll backward + case BOTH_ROLL_L: //# Roll left + case BOTH_ROLL_R: //# Roll right return qtrue; break; } return qfalse; } -void PM_AnglesForSlope( const float yaw, const vec3_t slope, vec3_t angles ) -{ - vec3_t nvf, ovf, ovr, new_angles; - float pitch, mod, dot; +void PM_AnglesForSlope(const float yaw, const vec3_t slope, vec3_t angles) { + vec3_t nvf, ovf, ovr, new_angles; + float pitch, mod, dot; - VectorSet( angles, 0, yaw, 0 ); - AngleVectors( angles, ovf, ovr, NULL ); + VectorSet(angles, 0, yaw, 0); + AngleVectors(angles, ovf, ovr, NULL); - vectoangles( slope, new_angles ); + vectoangles(slope, new_angles); pitch = new_angles[PITCH] + 90; new_angles[ROLL] = new_angles[PITCH] = 0; - AngleVectors( new_angles, nvf, NULL, NULL ); + AngleVectors(new_angles, nvf, NULL, NULL); - mod = DotProduct( nvf, ovr ); + mod = DotProduct(nvf, ovr); - if ( mod < 0 ) + if (mod < 0) mod = -1; else mod = 1; - dot = DotProduct( nvf, ovf ); + dot = DotProduct(nvf, ovf); angles[YAW] = 0; angles[PITCH] = dot * pitch; - angles[ROLL] = ((1-Q_fabs(dot)) * pitch * mod); + angles[ROLL] = ((1 - Q_fabs(dot)) * pitch * mod); } -void PM_FootSlopeTrace( float *pDiff, float *pInterval ) -{ - vec3_t footLOrg, footROrg, footLBot, footRBot; +void PM_FootSlopeTrace(float *pDiff, float *pInterval) { + vec3_t footLOrg, footROrg, footLBot, footRBot; vec3_t footLPoint, footRPoint; vec3_t footMins, footMaxs; vec3_t footLSlope, footRSlope; - trace_t trace; - float diff, interval; + trace_t trace; + float diff, interval; - mdxaBone_t boltMatrix; - vec3_t G2Angles; + mdxaBone_t boltMatrix; + vec3_t G2Angles; VectorSet(G2Angles, 0, pm->ps->viewangles[YAW], 0); - interval = 4;//? + interval = 4; //? - trap->G2API_GetBoltMatrix( pm->ghoul2, 0, pm->g2Bolts_LFoot, &boltMatrix, G2Angles, pm->ps->origin, pm->cmd.serverTime, NULL, pm->modelScale ); + trap->G2API_GetBoltMatrix(pm->ghoul2, 0, pm->g2Bolts_LFoot, &boltMatrix, G2Angles, pm->ps->origin, pm->cmd.serverTime, NULL, pm->modelScale); footLPoint[0] = boltMatrix.matrix[0][3]; footLPoint[1] = boltMatrix.matrix[1][3]; footLPoint[2] = boltMatrix.matrix[2][3]; - trap->G2API_GetBoltMatrix( pm->ghoul2, 0, pm->g2Bolts_RFoot, &boltMatrix, G2Angles, pm->ps->origin, pm->cmd.serverTime, NULL, pm->modelScale ); + trap->G2API_GetBoltMatrix(pm->ghoul2, 0, pm->g2Bolts_RFoot, &boltMatrix, G2Angles, pm->ps->origin, pm->cmd.serverTime, NULL, pm->modelScale); footRPoint[0] = boltMatrix.matrix[0][3]; footRPoint[1] = boltMatrix.matrix[1][3]; footRPoint[2] = boltMatrix.matrix[2][3]; - //get these on the cgame and store it, save ourselves a ghoul2 construct skel call - VectorCopy( footLPoint, footLOrg ); - VectorCopy( footRPoint, footROrg ); + // get these on the cgame and store it, save ourselves a ghoul2 construct skel call + VectorCopy(footLPoint, footLOrg); + VectorCopy(footRPoint, footROrg); - //step 2: adjust foot tag z height to bottom of bbox+1 + // step 2: adjust foot tag z height to bottom of bbox+1 footLOrg[2] = pm->ps->origin[2] + pm->mins[2] + 1; footROrg[2] = pm->ps->origin[2] + pm->mins[2] + 1; - VectorSet( footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval*10 ); - VectorSet( footRBot, footROrg[0], footROrg[1], footROrg[2] - interval*10 ); + VectorSet(footLBot, footLOrg[0], footLOrg[1], footLOrg[2] - interval * 10); + VectorSet(footRBot, footROrg[0], footROrg[1], footROrg[2] - interval * 10); - //step 3: trace down from each, find difference - VectorSet( footMins, -3, -3, 0 ); - VectorSet( footMaxs, 3, 3, 1 ); + // step 3: trace down from each, find difference + VectorSet(footMins, -3, -3, 0); + VectorSet(footMaxs, 3, 3, 1); - pm->trace( &trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask ); - VectorCopy( trace.endpos, footLBot ); - VectorCopy( trace.plane.normal, footLSlope ); + pm->trace(&trace, footLOrg, footMins, footMaxs, footLBot, pm->ps->clientNum, pm->tracemask); + VectorCopy(trace.endpos, footLBot); + VectorCopy(trace.plane.normal, footLSlope); - pm->trace( &trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask ); - VectorCopy( trace.endpos, footRBot ); - VectorCopy( trace.plane.normal, footRSlope ); + pm->trace(&trace, footROrg, footMins, footMaxs, footRBot, pm->ps->clientNum, pm->tracemask); + VectorCopy(trace.endpos, footRBot); + VectorCopy(trace.plane.normal, footRSlope); diff = footLBot[2] - footRBot[2]; - if ( pDiff != NULL ) - { + if (pDiff != NULL) { *pDiff = diff; } - if ( pInterval != NULL ) - { + if (pInterval != NULL) { *pInterval = interval; } } -qboolean BG_InSlopeAnim( int anim ) -{ - switch ( anim ) - { - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left +qboolean BG_InSlopeAnim(int anim) { + switch (anim) { + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left case LEGS_S1_LUP1: case LEGS_S1_LUP2: case LEGS_S1_LUP3: @@ -4793,79 +4094,54 @@ qboolean BG_InSlopeAnim( int anim ) return qfalse; } -#define SLOPE_RECALC_INT 100 +#define SLOPE_RECALC_INT 100 -qboolean PM_AdjustStandAnimForSlope( void ) -{ - float diff; - float interval; - int destAnim; - int legsAnim; - #define SLOPERECALCVAR pm->ps->slopeRecalcTime //this is purely convenience - - if (!pm->ghoul2) - { //probably just changed models and not quite in sync yet +qboolean PM_AdjustStandAnimForSlope(void) { + float diff; + float interval; + int destAnim; + int legsAnim; +#define SLOPERECALCVAR pm->ps->slopeRecalcTime // this is purely convenience + + if (!pm->ghoul2) { // probably just changed models and not quite in sync yet return qfalse; } - if ( pm->g2Bolts_LFoot == -1 || pm->g2Bolts_RFoot == -1 ) - {//need these bolts! + if (pm->g2Bolts_LFoot == -1 || pm->g2Bolts_RFoot == -1) { // need these bolts! return qfalse; } - //step 1: find the 2 foot tags - PM_FootSlopeTrace( &diff, &interval ); + // step 1: find the 2 foot tags + PM_FootSlopeTrace(&diff, &interval); - //step 4: based on difference, choose one of the left/right slope-match intervals - if ( diff >= interval*5 ) - { + // step 4: based on difference, choose one of the left/right slope-match intervals + if (diff >= interval * 5) { destAnim = LEGS_LEFTUP5; - } - else if ( diff >= interval*4 ) - { + } else if (diff >= interval * 4) { destAnim = LEGS_LEFTUP4; - } - else if ( diff >= interval*3 ) - { + } else if (diff >= interval * 3) { destAnim = LEGS_LEFTUP3; - } - else if ( diff >= interval*2 ) - { + } else if (diff >= interval * 2) { destAnim = LEGS_LEFTUP2; - } - else if ( diff >= interval ) - { + } else if (diff >= interval) { destAnim = LEGS_LEFTUP1; - } - else if ( diff <= interval*-5 ) - { + } else if (diff <= interval * -5) { destAnim = LEGS_RIGHTUP5; - } - else if ( diff <= interval*-4 ) - { + } else if (diff <= interval * -4) { destAnim = LEGS_RIGHTUP4; - } - else if ( diff <= interval*-3 ) - { + } else if (diff <= interval * -3) { destAnim = LEGS_RIGHTUP3; - } - else if ( diff <= interval*-2 ) - { + } else if (diff <= interval * -2) { destAnim = LEGS_RIGHTUP2; - } - else if ( diff <= interval*-1 ) - { + } else if (diff <= interval * -1) { destAnim = LEGS_RIGHTUP1; - } - else - { + } else { return qfalse; } legsAnim = pm->ps->legsAnim; - //adjust for current legs anim - switch ( legsAnim ) - { + // adjust for current legs anim + switch (legsAnim) { case BOTH_STAND1: case LEGS_S1_LUP1: @@ -4878,24 +4154,24 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S1_RUP3: case LEGS_S1_RUP4: case LEGS_S1_RUP5: - destAnim = LEGS_S1_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S1_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND2: case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: case BOTH_CROUCH1: - case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left - //fine + case LEGS_LEFTUP1: //# On a slope with left foot 4 higher than right + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP1: //# On a slope with RIGHT foot 4 higher than left + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left + // fine break; case BOTH_STAND3: case LEGS_S3_LUP1: @@ -4908,7 +4184,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S3_RUP3: case LEGS_S3_RUP4: case LEGS_S3_RUP5: - destAnim = LEGS_S3_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S3_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND4: case LEGS_S4_LUP1: @@ -4921,7 +4197,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S4_RUP3: case LEGS_S4_RUP4: case LEGS_S4_RUP5: - destAnim = LEGS_S4_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S4_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND5: case LEGS_S5_LUP1: @@ -4934,7 +4210,7 @@ qboolean PM_AdjustStandAnimForSlope( void ) case LEGS_S5_RUP3: case LEGS_S5_RUP4: case LEGS_S5_RUP5: - destAnim = LEGS_S5_LUP1 + (destAnim-LEGS_LEFTUP1); + destAnim = LEGS_S5_LUP1 + (destAnim - LEGS_LEFTUP1); break; case BOTH_STAND6: default: @@ -4942,76 +4218,53 @@ qboolean PM_AdjustStandAnimForSlope( void ) break; } - //step 5: based on the chosen interval and the current legsAnim, pick the correct anim - //step 6: increment/decrement to the dest anim, not instant - if ( (legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) - || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) - || (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) - || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) - || (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5) ) - {//already in left-side up - if ( destAnim > legsAnim && SLOPERECALCVAR < pm->cmd.serverTime ) - { + // step 5: based on the chosen interval and the current legsAnim, pick the correct anim + // step 6: increment/decrement to the dest anim, not instant + if ((legsAnim >= LEGS_LEFTUP1 && legsAnim <= LEGS_LEFTUP5) || (legsAnim >= LEGS_S1_LUP1 && legsAnim <= LEGS_S1_LUP5) || + (legsAnim >= LEGS_S3_LUP1 && legsAnim <= LEGS_S3_LUP5) || (legsAnim >= LEGS_S4_LUP1 && legsAnim <= LEGS_S4_LUP5) || + (legsAnim >= LEGS_S5_LUP1 && legsAnim <= LEGS_S5_LUP5)) { // already in left-side up + if (destAnim > legsAnim && SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim++; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && SLOPERECALCVAR < pm->cmd.serverTime ) - { + } else if (destAnim < legsAnim && SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim--; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else //if (SLOPERECALCVAR < pm->cmd.serverTime) + } else // if (SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim = destAnim; } destAnim = legsAnim; - } - else if ( (legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) - || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) - || (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) - || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) - || (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5) ) - {//already in right-side up - if ( destAnim > legsAnim && SLOPERECALCVAR < pm->cmd.serverTime ) - { + } else if ((legsAnim >= LEGS_RIGHTUP1 && legsAnim <= LEGS_RIGHTUP5) || (legsAnim >= LEGS_S1_RUP1 && legsAnim <= LEGS_S1_RUP5) || + (legsAnim >= LEGS_S3_RUP1 && legsAnim <= LEGS_S3_RUP5) || (legsAnim >= LEGS_S4_RUP1 && legsAnim <= LEGS_S4_RUP5) || + (legsAnim >= LEGS_S5_RUP1 && legsAnim <= LEGS_S5_RUP5)) { // already in right-side up + if (destAnim > legsAnim && SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim++; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim < legsAnim && SLOPERECALCVAR < pm->cmd.serverTime ) - { + } else if (destAnim < legsAnim && SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim--; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else //if (SLOPERECALCVAR < pm->cmd.serverTime) + } else // if (SLOPERECALCVAR < pm->cmd.serverTime) { legsAnim = destAnim; } destAnim = legsAnim; - } - else - {//in a stand of some sort? - switch ( legsAnim ) - { + } else { // in a stand of some sort? + switch (legsAnim) { case BOTH_STAND1: case TORSO_WEAPONREADY1: case TORSO_WEAPONREADY2: case TORSO_WEAPONREADY3: case TORSO_WEAPONREADY10: - if ( destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S1_LUP1 && destAnim <= LEGS_S1_LUP5) { // going into left side up destAnim = LEGS_S1_LUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S1_RUP1 && destAnim <= LEGS_S1_RUP5) { // going into right side up destAnim = LEGS_S1_RUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -5019,66 +4272,46 @@ qboolean PM_AdjustStandAnimForSlope( void ) case BOTH_SABERFAST_STANCE: case BOTH_SABERSLOW_STANCE: case BOTH_CROUCH1IDLE: - if ( destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5 ) - {//going into left side up + if (destAnim >= LEGS_LEFTUP1 && destAnim <= LEGS_LEFTUP5) { // going into left side up destAnim = LEGS_LEFTUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_RIGHTUP1 && destAnim <= LEGS_RIGHTUP5) { // going into right side up destAnim = LEGS_RIGHTUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND3: - if ( destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S3_LUP1 && destAnim <= LEGS_S3_LUP5) { // going into left side up destAnim = LEGS_S3_LUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S3_RUP1 && destAnim <= LEGS_S3_RUP5) { // going into right side up destAnim = LEGS_S3_RUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND4: - if ( destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S4_LUP1 && destAnim <= LEGS_S4_LUP5) { // going into left side up destAnim = LEGS_S4_LUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S4_RUP1 && destAnim <= LEGS_S4_RUP5) { // going into right side up destAnim = LEGS_S4_RUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; case BOTH_STAND5: - if ( destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5 ) - {//going into left side up + if (destAnim >= LEGS_S5_LUP1 && destAnim <= LEGS_S5_LUP5) { // going into left side up destAnim = LEGS_S5_LUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else if ( destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5 ) - {//going into right side up + } else if (destAnim >= LEGS_S5_RUP1 && destAnim <= LEGS_S5_RUP5) { // going into right side up destAnim = LEGS_S5_RUP1; SLOPERECALCVAR = pm->cmd.serverTime + SLOPE_RECALC_INT; - } - else - {//will never get here + } else { // will never get here return qfalse; } break; @@ -5088,8 +4321,8 @@ qboolean PM_AdjustStandAnimForSlope( void ) break; } } - //step 7: set the anim - //PM_SetAnim( SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL ); + // step 7: set the anim + // PM_SetAnim( SETANIM_LEGS, destAnim, SETANIM_FLAG_NORMAL ); PM_ContinueLegsAnim(destAnim); return qtrue; @@ -5097,22 +4330,20 @@ qboolean PM_AdjustStandAnimForSlope( void ) extern int WeaponReadyLegsAnim[WP_NUM_WEAPONS]; -//rww - slowly back out of slope leg anims, to prevent skipping between slope anims and general jittering -int PM_LegsSlopeBackTransition(int desiredAnim) -{ +// rww - slowly back out of slope leg anims, to prevent skipping between slope anims and general jittering +int PM_LegsSlopeBackTransition(int desiredAnim) { int anim = pm->ps->legsAnim; int resultingAnim = desiredAnim; - switch ( anim ) - { - case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right - case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right - case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right - case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right - case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left - case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left - case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left - case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left + switch (anim) { + case LEGS_LEFTUP2: //# On a slope with left foot 8 higher than right + case LEGS_LEFTUP3: //# On a slope with left foot 12 higher than right + case LEGS_LEFTUP4: //# On a slope with left foot 16 higher than right + case LEGS_LEFTUP5: //# On a slope with left foot 20 higher than right + case LEGS_RIGHTUP2: //# On a slope with RIGHT foot 8 higher than left + case LEGS_RIGHTUP3: //# On a slope with RIGHT foot 12 higher than left + case LEGS_RIGHTUP4: //# On a slope with RIGHT foot 16 higher than left + case LEGS_RIGHTUP5: //# On a slope with RIGHT foot 20 higher than left case LEGS_S1_LUP2: case LEGS_S1_LUP3: case LEGS_S1_LUP4: @@ -5145,13 +4376,10 @@ int PM_LegsSlopeBackTransition(int desiredAnim) case LEGS_S5_RUP3: case LEGS_S5_RUP4: case LEGS_S5_RUP5: - if (pm->ps->slopeRecalcTime < pm->cmd.serverTime) - { - resultingAnim = anim-1; - pm->ps->slopeRecalcTime = pm->cmd.serverTime + 8;//SLOPE_RECALC_INT; - } - else - { + if (pm->ps->slopeRecalcTime < pm->cmd.serverTime) { + resultingAnim = anim - 1; + pm->ps->slopeRecalcTime = pm->cmd.serverTime + 8; // SLOPE_RECALC_INT; + } else { resultingAnim = anim; } VectorClear(pm->ps->velocity); @@ -5166,23 +4394,16 @@ int PM_LegsSlopeBackTransition(int desiredAnim) PM_Footsteps =============== */ -static void PM_Footsteps( void ) { - float bobmove; - int old; - int setAnimFlags = 0; - - if ( (PM_InSaberAnim( (pm->ps->legsAnim) ) && !BG_SpinningSaberAnim( (pm->ps->legsAnim) )) - || (pm->ps->legsAnim) == BOTH_STAND1 - || (pm->ps->legsAnim) == BOTH_STAND1TO2 - || (pm->ps->legsAnim) == BOTH_STAND2TO1 - || (pm->ps->legsAnim) == BOTH_STAND2 - || (pm->ps->legsAnim) == BOTH_SABERFAST_STANCE - || (pm->ps->legsAnim) == BOTH_SABERSLOW_STANCE - || (pm->ps->legsAnim) == BOTH_BUTTON_HOLD - || (pm->ps->legsAnim) == BOTH_BUTTON_RELEASE - || PM_LandingAnim( (pm->ps->legsAnim) ) - || PM_PainAnim( (pm->ps->legsAnim) )) - {//legs are in a saber anim, and not spinning, be sure to override it +static void PM_Footsteps(void) { + float bobmove; + int old; + int setAnimFlags = 0; + + if ((PM_InSaberAnim((pm->ps->legsAnim)) && !BG_SpinningSaberAnim((pm->ps->legsAnim))) || (pm->ps->legsAnim) == BOTH_STAND1 || + (pm->ps->legsAnim) == BOTH_STAND1TO2 || (pm->ps->legsAnim) == BOTH_STAND2TO1 || (pm->ps->legsAnim) == BOTH_STAND2 || + (pm->ps->legsAnim) == BOTH_SABERFAST_STANCE || (pm->ps->legsAnim) == BOTH_SABERSLOW_STANCE || (pm->ps->legsAnim) == BOTH_BUTTON_HOLD || + (pm->ps->legsAnim) == BOTH_BUTTON_RELEASE || PM_LandingAnim((pm->ps->legsAnim)) || + PM_PainAnim((pm->ps->legsAnim))) { // legs are in a saber anim, and not spinning, be sure to override it setAnimFlags |= SETANIM_FLAG_OVERRIDE; } @@ -5190,104 +4411,67 @@ static void PM_Footsteps( void ) { // calculate speed and cycle to be used for // all cyclic walking effects // - pm->xyspeed = sqrt( pm->ps->velocity[0] * pm->ps->velocity[0] - + pm->ps->velocity[1] * pm->ps->velocity[1] ); + pm->xyspeed = sqrt(pm->ps->velocity[0] * pm->ps->velocity[0] + pm->ps->velocity[1] * pm->ps->velocity[1]); - if (pm->ps->saberMove == LS_SPINATTACK) - { - PM_ContinueLegsAnim( pm->ps->torsoAnim ); - } - else if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) { + if (pm->ps->saberMove == LS_SPINATTACK) { + PM_ContinueLegsAnim(pm->ps->torsoAnim); + } else if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // airborne leaves position in cycle intact, but doesn't advance - if ( pm->waterlevel > 1 ) - { - if (pm->xyspeed > 60) - { - PM_ContinueLegsAnim( BOTH_SWIMFORWARD ); - } - else - { - PM_ContinueLegsAnim( BOTH_SWIM_IDLE1 ); + if (pm->waterlevel > 1) { + if (pm->xyspeed > 60) { + PM_ContinueLegsAnim(BOTH_SWIMFORWARD); + } else { + PM_ContinueLegsAnim(BOTH_SWIM_IDLE1); } } return; } // if not trying to move - else if ( !pm->cmd.forwardmove && !pm->cmd.rightmove ) { - if ( pm->xyspeed < 5 ) { - pm->ps->bobCycle = 0; // start at beginning of cycle again - if ( pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_RANCOR ) - { - if ( (pm->ps->eFlags2&EF2_USE_ALT_ANIM) ) - {//holding someone - PM_ContinueLegsAnim( BOTH_STAND4 ); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND4,SETANIM_FLAG_NORMAL); - } - else if ( (pm->ps->eFlags2&EF2_ALERTED) ) - {//have an enemy or have had one since we spawned - PM_ContinueLegsAnim( BOTH_STAND2 ); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND2,SETANIM_FLAG_NORMAL); - } - else - {//just stand there - PM_ContinueLegsAnim( BOTH_STAND1 ); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else if ( pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_WAMPA ) - { - if ( (pm->ps->eFlags2&EF2_USE_ALT_ANIM) ) - {//holding a victim - PM_ContinueLegsAnim( BOTH_STAND2 ); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND2,SETANIM_FLAG_NORMAL); - } - else - {//not holding a victim - PM_ContinueLegsAnim( BOTH_STAND1 ); - //PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); - } - } - else if ( (pm->ps->pm_flags & PMF_DUCKED) || (pm->ps->pm_flags & PMF_ROLLING) ) { - if ((pm->ps->legsAnim) != BOTH_CROUCH1IDLE) - { + else if (!pm->cmd.forwardmove && !pm->cmd.rightmove) { + if (pm->xyspeed < 5) { + pm->ps->bobCycle = 0; // start at beginning of cycle again + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_RANCOR) { + if ((pm->ps->eFlags2 & EF2_USE_ALT_ANIM)) { // holding someone + PM_ContinueLegsAnim(BOTH_STAND4); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND4,SETANIM_FLAG_NORMAL); + } else if ((pm->ps->eFlags2 & EF2_ALERTED)) { // have an enemy or have had one since we spawned + PM_ContinueLegsAnim(BOTH_STAND2); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND2,SETANIM_FLAG_NORMAL); + } else { // just stand there + PM_ContinueLegsAnim(BOTH_STAND1); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + } + } else if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_WAMPA) { + if ((pm->ps->eFlags2 & EF2_USE_ALT_ANIM)) { // holding a victim + PM_ContinueLegsAnim(BOTH_STAND2); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND2,SETANIM_FLAG_NORMAL); + } else { // not holding a victim + PM_ContinueLegsAnim(BOTH_STAND1); + // PM_SetAnim(pm,SETANIM_LEGS,BOTH_STAND1,SETANIM_FLAG_NORMAL); + } + } else if ((pm->ps->pm_flags & PMF_DUCKED) || (pm->ps->pm_flags & PMF_ROLLING)) { + if ((pm->ps->legsAnim) != BOTH_CROUCH1IDLE) { PM_SetAnim(SETANIM_LEGS, BOTH_CROUCH1IDLE, setAnimFlags); - } - else - { - PM_ContinueLegsAnim( BOTH_CROUCH1IDLE ); + } else { + PM_ContinueLegsAnim(BOTH_CROUCH1IDLE); } } else { - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { ///???? continue legs anim on a torso anim...??!!! - //yeah.. the anim has a valid pose for the legs, it uses it (you can't move while using disruptor) - PM_ContinueLegsAnim( TORSO_WEAPONREADY4 ); - } - else - { - if (pm->ps->weapon == WP_SABER && BG_SabersOff( pm->ps ) ) - { - if (!PM_AdjustStandAnimForSlope()) - { - //PM_ContinueLegsAnim( BOTH_STAND1 ); + // yeah.. the anim has a valid pose for the legs, it uses it (you can't move while using disruptor) + PM_ContinueLegsAnim(TORSO_WEAPONREADY4); + } else { + if (pm->ps->weapon == WP_SABER && BG_SabersOff(pm->ps)) { + if (!PM_AdjustStandAnimForSlope()) { + // PM_ContinueLegsAnim( BOTH_STAND1 ); PM_ContinueLegsAnim(PM_LegsSlopeBackTransition(BOTH_STAND1)); } - } - else - { - if (pm->ps->weapon != WP_SABER || !PM_AdjustStandAnimForSlope()) - { - if (pm->ps->weapon == WP_SABER) - { + } else { + if (pm->ps->weapon != WP_SABER || !PM_AdjustStandAnimForSlope()) { + if (pm->ps->weapon == WP_SABER) { PM_ContinueLegsAnim(PM_LegsSlopeBackTransition(PM_GetSaberStance())); - } - else - { + } else { PM_ContinueLegsAnim(PM_LegsSlopeBackTransition(WeaponReadyLegsAnim[pm->ps->weapon])); } } @@ -5298,363 +4482,237 @@ static void PM_Footsteps( void ) { return; } - if (pm->ps->saberMove == LS_SPINATTACK) - { + if (pm->ps->saberMove == LS_SPINATTACK) { bobmove = 0.2f; - PM_ContinueLegsAnim( pm->ps->torsoAnim ); - } - else if ( pm->ps->pm_flags & PMF_DUCKED ) - { + PM_ContinueLegsAnim(pm->ps->torsoAnim); + } else if (pm->ps->pm_flags & PMF_DUCKED) { int rolled = 0; - bobmove = 0.5; // ducked characters bob much faster + bobmove = 0.5; // ducked characters bob much faster - if ( ( (PM_RunningAnim( pm->ps->legsAnim )&&VectorLengthSquared(pm->ps->velocity)>=40000/*200*200*/) || PM_CanRollFromSoulCal( pm->ps ) ) && - !BG_InRoll(pm->ps, pm->ps->legsAnim) ) - {//roll! + if (((PM_RunningAnim(pm->ps->legsAnim) && VectorLengthSquared(pm->ps->velocity) >= 40000 /*200*200*/) || PM_CanRollFromSoulCal(pm->ps)) && + !BG_InRoll(pm->ps, pm->ps->legsAnim)) { // roll! rolled = PM_TryRoll(); } - if ( !rolled ) - { //if the roll failed or didn't attempt, do standard crouching anim stuff. - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) { - if ((pm->ps->legsAnim) != BOTH_CROUCH1WALKBACK) - { + if (!rolled) { // if the roll failed or didn't attempt, do standard crouching anim stuff. + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + if ((pm->ps->legsAnim) != BOTH_CROUCH1WALKBACK) { PM_SetAnim(SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_ContinueLegsAnim(BOTH_CROUCH1WALKBACK); } - else - { - PM_ContinueLegsAnim( BOTH_CROUCH1WALKBACK ); - } - } - else { - if ((pm->ps->legsAnim) != BOTH_CROUCH1WALK) - { + } else { + if ((pm->ps->legsAnim) != BOTH_CROUCH1WALK) { PM_SetAnim(SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); - } - else - { - PM_ContinueLegsAnim( BOTH_CROUCH1WALK ); + } else { + PM_ContinueLegsAnim(BOTH_CROUCH1WALK); } } - } - else - { //otherwise send us into the roll + } else { // otherwise send us into the roll pm->ps->legsTimer = 0; pm->ps->legsAnim = 0; - PM_SetAnim(SETANIM_BOTH,rolled,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - PM_AddEventWithParm( EV_ROLL, 0 ); - pm->maxs[2] = pm->ps->crouchheight;//CROUCH_MAXS_2; + PM_SetAnim(SETANIM_BOTH, rolled, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + PM_AddEventWithParm(EV_ROLL, 0); + pm->maxs[2] = pm->ps->crouchheight; // CROUCH_MAXS_2; pm->ps->viewheight = DEFAULT_VIEWHEIGHT; pm->ps->pm_flags &= ~PMF_DUCKED; pm->ps->pm_flags |= PMF_ROLLING; } - } - else if ((pm->ps->pm_flags & PMF_ROLLING) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && - !PM_InRollComplete(pm->ps, pm->ps->legsAnim)) - { - bobmove = 0.5; // ducked characters bob much faster + } else if ((pm->ps->pm_flags & PMF_ROLLING) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && !PM_InRollComplete(pm->ps, pm->ps->legsAnim)) { + bobmove = 0.5; // ducked characters bob much faster - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { - if ((pm->ps->legsAnim) != BOTH_CROUCH1WALKBACK) - { + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { + if ((pm->ps->legsAnim) != BOTH_CROUCH1WALKBACK) { PM_SetAnim(SETANIM_LEGS, BOTH_CROUCH1WALKBACK, setAnimFlags); + } else { + PM_ContinueLegsAnim(BOTH_CROUCH1WALKBACK); } - else - { - PM_ContinueLegsAnim( BOTH_CROUCH1WALKBACK ); - } - } - else - { - if ((pm->ps->legsAnim) != BOTH_CROUCH1WALK) - { + } else { + if ((pm->ps->legsAnim) != BOTH_CROUCH1WALK) { PM_SetAnim(SETANIM_LEGS, BOTH_CROUCH1WALK, setAnimFlags); - } - else - { - PM_ContinueLegsAnim( BOTH_CROUCH1WALK ); + } else { + PM_ContinueLegsAnim(BOTH_CROUCH1WALK); } } - } - else - { + } else { int desiredAnim = -1; - if ((pm->ps->legsAnim == BOTH_FORCELAND1 || - pm->ps->legsAnim == BOTH_FORCELANDBACK1 || - pm->ps->legsAnim == BOTH_FORCELANDRIGHT1 || - pm->ps->legsAnim == BOTH_FORCELANDLEFT1) && - pm->ps->legsTimer > 0) - { //let it finish first + if ((pm->ps->legsAnim == BOTH_FORCELAND1 || pm->ps->legsAnim == BOTH_FORCELANDBACK1 || pm->ps->legsAnim == BOTH_FORCELANDRIGHT1 || + pm->ps->legsAnim == BOTH_FORCELANDLEFT1) && + pm->ps->legsTimer > 0) { // let it finish first bobmove = 0.2f; - } - else if ( !( pm->cmd.buttons & BUTTON_WALKING ) ) - {//running - bobmove = 0.4f; // faster speeds bob faster - if ( pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_WAMPA ) - { - if ( (pm->ps->eFlags2&EF2_USE_ALT_ANIM) ) - {//full on run, on all fours + } else if (!(pm->cmd.buttons & BUTTON_WALKING)) { // running + bobmove = 0.4f; // faster speeds bob faster + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_WAMPA) { + if ((pm->ps->eFlags2 & EF2_USE_ALT_ANIM)) { // full on run, on all fours desiredAnim = BOTH_RUN1; + } else { // regular, upright run + desiredAnim = BOTH_RUN2; } - else - {//regular, upright run - desiredAnim = BOTH_RUN2; - } - } - else if ( pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_RANCOR ) - {//no run anims - if ( (pm->ps->pm_flags&PMF_BACKWARDS_RUN) ) - { + } else if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_RANCOR) { // no run anims + if ((pm->ps->pm_flags & PMF_BACKWARDS_RUN)) { desiredAnim = BOTH_WALKBACK1; - } - else - { + } else { desiredAnim = BOTH_WALK1; } } #ifdef _GAME - else if ( pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_JAWA) - { + else if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_JAWA) { // Jawa has a special run animation :D desiredAnim = BOTH_RUN4; bobmove = 0.2f; } #endif - else if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { + else if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { #ifndef BASE_COMPAT - if( pm->ps->weapon != WP_SABER ) - { + if (pm->ps->weapon != WP_SABER) { desiredAnim = BOTH_RUNBACK1; - } - else - { + } else { #endif - switch (pm->ps->fd.saberAnimLevel) - { - case SS_STAFF: - if ( pm->ps->saberHolstered > 1 ) - {//saber off - desiredAnim = BOTH_RUNBACK1; - } - else - { - //desiredAnim = BOTH_RUNBACK_STAFF; - //hmm.. stuff runback anim is pretty messed up for some reason. - desiredAnim = BOTH_RUNBACK2; - } - break; - case SS_DUAL: - if ( pm->ps->saberHolstered > 1 ) - {//sabers off - desiredAnim = BOTH_RUNBACK1; - } - else - { - //desiredAnim = BOTH_RUNBACK_DUAL; - //and so is the dual - desiredAnim = BOTH_RUNBACK2; - } - break; - default: - if ( pm->ps->saberHolstered ) - {//saber off - desiredAnim = BOTH_RUNBACK1; - } - else - { - desiredAnim = BOTH_RUNBACK2; + switch (pm->ps->fd.saberAnimLevel) { + case SS_STAFF: + if (pm->ps->saberHolstered > 1) { // saber off + desiredAnim = BOTH_RUNBACK1; + } else { + // desiredAnim = BOTH_RUNBACK_STAFF; + // hmm.. stuff runback anim is pretty messed up for some reason. + desiredAnim = BOTH_RUNBACK2; + } + break; + case SS_DUAL: + if (pm->ps->saberHolstered > 1) { // sabers off + desiredAnim = BOTH_RUNBACK1; + } else { + // desiredAnim = BOTH_RUNBACK_DUAL; + // and so is the dual + desiredAnim = BOTH_RUNBACK2; + } + break; + default: + if (pm->ps->saberHolstered) { // saber off + desiredAnim = BOTH_RUNBACK1; + } else { + desiredAnim = BOTH_RUNBACK2; + } + break; } - break; - } #ifndef BASE_COMPAT } #endif - } - else - { -#ifndef BASE_COMPAT // FIXME: this doesn't break base compatibility at all, remove #ifndef - if ( pm->ps->weapon != WP_SABER ) - { + } else { +#ifndef BASE_COMPAT // FIXME: this doesn't break base compatibility at all, remove #ifndef + if (pm->ps->weapon != WP_SABER) { desiredAnim = BOTH_RUN1; - } - else - { + } else { #endif - switch (pm->ps->fd.saberAnimLevel) - { - case SS_STAFF: - if ( pm->ps->saberHolstered > 1 ) - {//blades off - desiredAnim = BOTH_RUN1; - } - else if ( pm->ps->saberHolstered == 1 ) - {//1 blade on - desiredAnim = BOTH_RUN2; - } - else - { - if (pm->ps->fd.forcePowersActive & (1<ps->fd.saberAnimLevel) { + case SS_STAFF: + if (pm->ps->saberHolstered > 1) { // blades off desiredAnim = BOTH_RUN1; + } else if (pm->ps->saberHolstered == 1) { // 1 blade on + desiredAnim = BOTH_RUN2; + } else { + if (pm->ps->fd.forcePowersActive & (1 << FP_SPEED)) { + desiredAnim = BOTH_RUN1; + } else { + desiredAnim = BOTH_RUN_STAFF; + } } - else - { - desiredAnim = BOTH_RUN_STAFF; + break; + case SS_DUAL: + if (pm->ps->saberHolstered > 1) { // blades off + desiredAnim = BOTH_RUN1; + } else if (pm->ps->saberHolstered == 1) { // 1 saber on + desiredAnim = BOTH_RUN2; + } else { + desiredAnim = BOTH_RUN_DUAL; } + break; + default: + if (pm->ps->saberHolstered) { // saber off + desiredAnim = BOTH_RUN1; + } else { + desiredAnim = BOTH_RUN2; + } + break; } - break; - case SS_DUAL: - if ( pm->ps->saberHolstered > 1 ) - {//blades off - desiredAnim = BOTH_RUN1; - } - else if ( pm->ps->saberHolstered == 1 ) - {//1 saber on - desiredAnim = BOTH_RUN2; - } - else - { - desiredAnim = BOTH_RUN_DUAL; - } - break; - default: - if ( pm->ps->saberHolstered ) - {//saber off - desiredAnim = BOTH_RUN1; - } - else - { - desiredAnim = BOTH_RUN2; - } - break; - } #ifndef BASE_COMPAT } #endif } - } - else - { - bobmove = 0.2f; // walking bobs slow - if ( pm->ps->pm_flags & PMF_BACKWARDS_RUN ) - { + } else { + bobmove = 0.2f; // walking bobs slow + if (pm->ps->pm_flags & PMF_BACKWARDS_RUN) { #ifndef BASE_COMPAT // fixme, doesn't break base compat if enabled (I tested this to be sure) - if( pm->ps->weapon != WP_SABER ) - { + if (pm->ps->weapon != WP_SABER) { desiredAnim = BOTH_WALKBACK1; - } - else - { + } else { #endif - switch (pm->ps->fd.saberAnimLevel) - { - case SS_STAFF: - if ( pm->ps->saberHolstered > 1 ) - { - desiredAnim = BOTH_WALKBACK1; - } - else if ( pm->ps->saberHolstered ) - { - desiredAnim = BOTH_WALKBACK2; - } - else - { - desiredAnim = BOTH_WALKBACK_STAFF; - } - break; - case SS_DUAL: - if ( pm->ps->saberHolstered > 1 ) - { - desiredAnim = BOTH_WALKBACK1; - } - else if ( pm->ps->saberHolstered ) - { - desiredAnim = BOTH_WALKBACK2; - } - else - { - desiredAnim = BOTH_WALKBACK_DUAL; - } - break; - default: - if ( pm->ps->saberHolstered ) - { - desiredAnim = BOTH_WALKBACK1; - } - else - { - desiredAnim = BOTH_WALKBACK2; + switch (pm->ps->fd.saberAnimLevel) { + case SS_STAFF: + if (pm->ps->saberHolstered > 1) { + desiredAnim = BOTH_WALKBACK1; + } else if (pm->ps->saberHolstered) { + desiredAnim = BOTH_WALKBACK2; + } else { + desiredAnim = BOTH_WALKBACK_STAFF; + } + break; + case SS_DUAL: + if (pm->ps->saberHolstered > 1) { + desiredAnim = BOTH_WALKBACK1; + } else if (pm->ps->saberHolstered) { + desiredAnim = BOTH_WALKBACK2; + } else { + desiredAnim = BOTH_WALKBACK_DUAL; + } + break; + default: + if (pm->ps->saberHolstered) { + desiredAnim = BOTH_WALKBACK1; + } else { + desiredAnim = BOTH_WALKBACK2; + } + break; } - break; - } #ifndef BASE_COMPAT } #endif - } - else - { - if ( pm->ps->weapon == WP_MELEE ) - { + } else { + if (pm->ps->weapon == WP_MELEE) { desiredAnim = BOTH_WALK1; - } - else if ( BG_SabersOff( pm->ps ) ) - { + } else if (BG_SabersOff(pm->ps)) { desiredAnim = BOTH_WALK1; } #ifndef BASE_COMPAT - else if ( pm->ps->weapon != WP_SABER ) - { + else if (pm->ps->weapon != WP_SABER) { desiredAnim = BOTH_WALK1; } #endif - else - { - switch (pm->ps->fd.saberAnimLevel) - { + else { + switch (pm->ps->fd.saberAnimLevel) { case SS_STAFF: - if ( pm->ps->saberHolstered > 1 ) - { + if (pm->ps->saberHolstered > 1) { desiredAnim = BOTH_WALK1; - } - else if ( pm->ps->saberHolstered ) - { + } else if (pm->ps->saberHolstered) { desiredAnim = BOTH_WALK2; - } - else - { + } else { desiredAnim = BOTH_WALK_STAFF; } break; case SS_DUAL: - if ( pm->ps->saberHolstered > 1 ) - { + if (pm->ps->saberHolstered > 1) { desiredAnim = BOTH_WALK1; - } - else if ( pm->ps->saberHolstered ) - { + } else if (pm->ps->saberHolstered) { desiredAnim = BOTH_WALK2; - } - else - { + } else { desiredAnim = BOTH_WALK_DUAL; } break; default: - if ( pm->ps->saberHolstered ) - { + if (pm->ps->saberHolstered) { desiredAnim = BOTH_WALK1; - } - else - { + } else { desiredAnim = BOTH_WALK2; } break; @@ -5663,16 +4721,12 @@ static void PM_Footsteps( void ) { } } - if (desiredAnim != -1) - { + if (desiredAnim != -1) { int ires = PM_LegsSlopeBackTransition(desiredAnim); - if ((pm->ps->legsAnim) != desiredAnim && ires == desiredAnim) - { + if ((pm->ps->legsAnim) != desiredAnim && ires == desiredAnim) { PM_SetAnim(SETANIM_LEGS, desiredAnim, setAnimFlags); - } - else - { + } else { PM_ContinueLegsAnim(ires); } } @@ -5680,19 +4734,18 @@ static void PM_Footsteps( void ) { // check for footstep / splash sounds old = pm->ps->bobCycle; - pm->ps->bobCycle = (int)( old + bobmove * pml.msec ) & 255; + pm->ps->bobCycle = (int)(old + bobmove * pml.msec) & 255; // if we just crossed a cycle boundary, play an appropriate footstep event - if ( ( ( old + 64 ) ^ ( pm->ps->bobCycle + 64 ) ) & 128 ) - { + if (((old + 64) ^ (pm->ps->bobCycle + 64)) & 128) { pm->ps->footstepTime = pm->cmd.serverTime + 300; - if ( pm->waterlevel == 1 ) { + if (pm->waterlevel == 1) { // splashing - PM_AddEvent( EV_FOOTSPLASH ); - } else if ( pm->waterlevel == 2 ) { + PM_AddEvent(EV_FOOTSPLASH); + } else if (pm->waterlevel == 2) { // wading / swimming at surface - PM_AddEvent( EV_SWIM ); - } else if ( pm->waterlevel == 3 ) { + PM_AddEvent(EV_SWIM); + } else if (pm->waterlevel == 3) { // no sound when completely underwater } } @@ -5705,7 +4758,7 @@ PM_WaterEvents Generate sound events for entering and leaving water ============== */ -static void PM_WaterEvents( void ) { // FIXME? +static void PM_WaterEvents(void) { // FIXME? #ifdef _GAME qboolean impact_splash = qfalse; #endif @@ -5714,12 +4767,11 @@ static void PM_WaterEvents( void ) { // FIXME? // if (!pml.previous_waterlevel && pm->waterlevel) { #ifdef _GAME - if ( VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + if (VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } #endif - PM_AddEvent( EV_WATER_TOUCH ); + PM_AddEvent(EV_WATER_TOUCH); } // @@ -5727,44 +4779,36 @@ static void PM_WaterEvents( void ) { // FIXME? // if (pml.previous_waterlevel && !pm->waterlevel) { #ifdef _GAME - if ( VectorLengthSquared( pm->ps->velocity ) > 40000 ) - { + if (VectorLengthSquared(pm->ps->velocity) > 40000) { impact_splash = qtrue; } #endif - PM_AddEvent( EV_WATER_LEAVE ); + PM_AddEvent(EV_WATER_LEAVE); } #ifdef _GAME - if ( impact_splash ) - { - //play the splash effect - trace_t tr; - vec3_t start, end; - + if (impact_splash) { + // play the splash effect + trace_t tr; + vec3_t start, end; - VectorCopy( pm->ps->origin, start ); - VectorCopy( pm->ps->origin, end ); + VectorCopy(pm->ps->origin, start); + VectorCopy(pm->ps->origin, end); // FIXME: set start and end better start[2] += 10; end[2] -= 40; - pm->trace( &tr, start, vec3_origin, vec3_origin, end, pm->ps->clientNum, MASK_WATER ); + pm->trace(&tr, start, vec3_origin, vec3_origin, end, pm->ps->clientNum, MASK_WATER); - if ( tr.fraction < 1.0f ) - { - if ( (tr.contents&CONTENTS_LAVA) ) - { - G_PlayEffect( EFFECT_LAVA_SPLASH, tr.endpos, tr.plane.normal ); - } - else if ( (tr.contents&CONTENTS_SLIME) ) + if (tr.fraction < 1.0f) { + if ((tr.contents & CONTENTS_LAVA)) { + G_PlayEffect(EFFECT_LAVA_SPLASH, tr.endpos, tr.plane.normal); + } else if ((tr.contents & CONTENTS_SLIME)) { + G_PlayEffect(EFFECT_ACID_SPLASH, tr.endpos, tr.plane.normal); + } else // must be water { - G_PlayEffect( EFFECT_ACID_SPLASH, tr.endpos, tr.plane.normal ); - } - else //must be water - { - G_PlayEffect( EFFECT_WATER_SPLASH, tr.endpos, tr.plane.normal ); + G_PlayEffect(EFFECT_WATER_SPLASH, tr.endpos, tr.plane.normal); } } } @@ -5774,21 +4818,19 @@ static void PM_WaterEvents( void ) { // FIXME? // check for head just going under water // if (pml.previous_waterlevel != 3 && pm->waterlevel == 3) { - PM_AddEvent( EV_WATER_UNDER ); + PM_AddEvent(EV_WATER_UNDER); } // // check for head just coming out of water // if (pml.previous_waterlevel == 3 && pm->waterlevel != 3) { - PM_AddEvent( EV_WATER_CLEAR ); + PM_AddEvent(EV_WATER_CLEAR); } } -void BG_ClearRocketLock( playerState_t *ps ) -{ - if ( ps ) - { +void BG_ClearRocketLock(playerState_t *ps) { + if (ps) { ps->rocketLockIndex = ENTITYNUM_NONE; ps->rocketLastValidTime = 0; ps->rocketLockTime = -1; @@ -5801,60 +4843,55 @@ void BG_ClearRocketLock( playerState_t *ps ) PM_BeginWeaponChange =============== */ -void PM_BeginWeaponChange( int weapon ) { - if ( weapon <= WP_NONE || weapon >= WP_NUM_WEAPONS ) { +void PM_BeginWeaponChange(int weapon) { + if (weapon <= WP_NONE || weapon >= WP_NUM_WEAPONS) { return; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { return; } - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { return; } // turn of any kind of zooming when weapon switching. - if (pm->ps->zoomMode) - { + if (pm->ps->zoomMode) { pm->ps->zoomMode = 0; pm->ps->zoomTime = pm->ps->commandTime; } - PM_AddEventWithParm( EV_CHANGE_WEAPON, weapon ); + PM_AddEventWithParm(EV_CHANGE_WEAPON, weapon); pm->ps->weaponstate = WEAPON_DROPPING; pm->ps->weaponTime += 200; - //PM_StartTorsoAnim( TORSO_DROPWEAP1 ); + // PM_StartTorsoAnim( TORSO_DROPWEAP1 ); PM_SetAnim(SETANIM_TORSO, TORSO_DROPWEAP1, SETANIM_FLAG_OVERRIDE); - BG_ClearRocketLock( pm->ps ); + BG_ClearRocketLock(pm->ps); } - /* =============== PM_FinishWeaponChange =============== */ -void PM_FinishWeaponChange( void ) { - int weapon; +void PM_FinishWeaponChange(void) { + int weapon; weapon = pm->cmd.weapon; - if ( weapon < WP_NONE || weapon >= WP_NUM_WEAPONS ) { + if (weapon < WP_NONE || weapon >= WP_NUM_WEAPONS) { weapon = WP_NONE; } - if ( !( pm->ps->stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(pm->ps->stats[STAT_WEAPONS] & (1 << weapon))) { weapon = WP_NONE; } - if (weapon == WP_SABER) - { + if (weapon == WP_SABER) { PM_SetSaberMove(LS_DRAW); - } - else - { - //PM_StartTorsoAnim( TORSO_RAISEWEAP1); + } else { + // PM_StartTorsoAnim( TORSO_RAISEWEAP1); PM_SetAnim(SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_OVERRIDE); } pm->ps->weapon = weapon; @@ -5863,145 +4900,116 @@ void PM_FinishWeaponChange( void ) { } #ifdef _GAME -extern void WP_GetVehicleCamPos( gentity_t *ent, gentity_t *pilot, vec3_t camPos ); +extern void WP_GetVehicleCamPos(gentity_t *ent, gentity_t *pilot, vec3_t camPos); #else -extern void CG_GetVehicleCamPos( vec3_t camPos ); +extern void CG_GetVehicleCamPos(vec3_t camPos); #endif -#define MAX_XHAIR_DIST_ACCURACY 20000.0f -int BG_VehTraceFromCamPos( trace_t *camTrace, bgEntity_t *bgEnt, const vec3_t entOrg, const vec3_t shotStart, const vec3_t end, vec3_t newEnd, vec3_t shotDir, float bestDist ) -{ - //NOTE: this MUST stay up to date with the method used in CG_ScanForCrosshairEntity (where it checks the doExtraVehTraceFromViewPos bool) - vec3_t viewDir2End, extraEnd, camPos; - float minAutoAimDist; +#define MAX_XHAIR_DIST_ACCURACY 20000.0f +int BG_VehTraceFromCamPos(trace_t *camTrace, bgEntity_t *bgEnt, const vec3_t entOrg, const vec3_t shotStart, const vec3_t end, vec3_t newEnd, vec3_t shotDir, + float bestDist) { + // NOTE: this MUST stay up to date with the method used in CG_ScanForCrosshairEntity (where it checks the doExtraVehTraceFromViewPos bool) + vec3_t viewDir2End, extraEnd, camPos; + float minAutoAimDist; #ifdef _GAME - WP_GetVehicleCamPos( (gentity_t *)bgEnt, (gentity_t *)bgEnt->m_pVehicle->m_pPilot, camPos ); + WP_GetVehicleCamPos((gentity_t *)bgEnt, (gentity_t *)bgEnt->m_pVehicle->m_pPilot, camPos); #else - CG_GetVehicleCamPos( camPos ); + CG_GetVehicleCamPos(camPos); #endif - minAutoAimDist = Distance( entOrg, camPos ) + (bgEnt->m_pVehicle->m_pVehicleInfo->length/2.0f) + 200.0f; + minAutoAimDist = Distance(entOrg, camPos) + (bgEnt->m_pVehicle->m_pVehicleInfo->length / 2.0f) + 200.0f; - VectorCopy( end, newEnd ); - VectorSubtract( end, camPos, viewDir2End ); - VectorNormalize( viewDir2End ); - VectorMA( camPos, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd ); + VectorCopy(end, newEnd); + VectorSubtract(end, camPos, viewDir2End); + VectorNormalize(viewDir2End); + VectorMA(camPos, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd); - pm->trace( camTrace, camPos, vec3_origin, vec3_origin, extraEnd, bgEnt->s.number, CONTENTS_SOLID|CONTENTS_BODY ); + pm->trace(camTrace, camPos, vec3_origin, vec3_origin, extraEnd, bgEnt->s.number, CONTENTS_SOLID | CONTENTS_BODY); - if ( !camTrace->allsolid - && !camTrace->startsolid - && camTrace->fraction < 1.0f - && (camTrace->fraction*MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist - && ((camTrace->fraction*MAX_XHAIR_DIST_ACCURACY)-Distance( entOrg, camPos )) < bestDist ) - {//this trace hit *something* that's closer than the thing the main trace hit, so use this result instead - VectorCopy( camTrace->endpos, newEnd ); - VectorSubtract( newEnd, shotStart, shotDir ); - VectorNormalize( shotDir ); - return (camTrace->entityNum+1); + if (!camTrace->allsolid && !camTrace->startsolid && camTrace->fraction < 1.0f && (camTrace->fraction * MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist && + ((camTrace->fraction * MAX_XHAIR_DIST_ACCURACY) - Distance(entOrg, camPos)) < + bestDist) { // this trace hit *something* that's closer than the thing the main trace hit, so use this result instead + VectorCopy(camTrace->endpos, newEnd); + VectorSubtract(newEnd, shotStart, shotDir); + VectorNormalize(shotDir); + return (camTrace->entityNum + 1); } return 0; } -void PM_RocketLock( float lockDist, qboolean vehicleLock ) -{ +void PM_RocketLock(float lockDist, qboolean vehicleLock) { // Not really a charge weapon, but we still want to delay fire until the button comes up so that we can // implement our alt-fire locking stuff - vec3_t ang; - trace_t tr; + vec3_t ang; + trace_t tr; vec3_t muzzleOffPoint, muzzlePoint, forward, right, up; - if ( vehicleLock ) - { - AngleVectors( pm->ps->viewangles, forward, right, up ); - VectorCopy( pm->ps->origin, muzzlePoint ); - VectorMA( muzzlePoint, lockDist, forward, ang ); - } - else - { - AngleVectors( pm->ps->viewangles, forward, right, up ); + if (vehicleLock) { + AngleVectors(pm->ps->viewangles, forward, right, up); + VectorCopy(pm->ps->origin, muzzlePoint); + VectorMA(muzzlePoint, lockDist, forward, ang); + } else { + AngleVectors(pm->ps->viewangles, forward, right, up); AngleVectors(pm->ps->viewangles, ang, NULL, NULL); - VectorCopy( pm->ps->origin, muzzlePoint ); + VectorCopy(pm->ps->origin, muzzlePoint); VectorCopy(WP_MuzzlePoint[WP_ROCKET_LAUNCHER], muzzleOffPoint); VectorMA(muzzlePoint, muzzleOffPoint[0], forward, muzzlePoint); VectorMA(muzzlePoint, muzzleOffPoint[1], right, muzzlePoint); muzzlePoint[2] += pm->ps->viewheight + muzzleOffPoint[2]; - ang[0] = muzzlePoint[0] + ang[0]*lockDist; - ang[1] = muzzlePoint[1] + ang[1]*lockDist; - ang[2] = muzzlePoint[2] + ang[2]*lockDist; + ang[0] = muzzlePoint[0] + ang[0] * lockDist; + ang[1] = muzzlePoint[1] + ang[1] * lockDist; + ang[2] = muzzlePoint[2] + ang[2] * lockDist; } - pm->trace(&tr, muzzlePoint, NULL, NULL, ang, pm->ps->clientNum, MASK_PLAYERSOLID); - if ( vehicleLock ) - {//vehicles also do a trace from the camera point if the main one misses - if ( tr.fraction >= 1.0f ) - { + if (vehicleLock) { // vehicles also do a trace from the camera point if the main one misses + if (tr.fraction >= 1.0f) { trace_t camTrace; vec3_t newEnd, shotDir; - if ( BG_VehTraceFromCamPos( &camTrace, PM_BGEntForNum(pm->ps->clientNum), pm->ps->origin, muzzlePoint, tr.endpos, newEnd, shotDir, (tr.fraction*lockDist) ) ) - { - memcpy( &tr, &camTrace, sizeof(tr) ); + if (BG_VehTraceFromCamPos(&camTrace, PM_BGEntForNum(pm->ps->clientNum), pm->ps->origin, muzzlePoint, tr.endpos, newEnd, shotDir, + (tr.fraction * lockDist))) { + memcpy(&tr, &camTrace, sizeof(tr)); } } } - if (tr.fraction != 1 && tr.entityNum < ENTITYNUM_NONE && tr.entityNum != pm->ps->clientNum) - { + if (tr.fraction != 1 && tr.entityNum < ENTITYNUM_NONE && tr.entityNum != pm->ps->clientNum) { bgEntity_t *bgEnt = PM_BGEntForNum(tr.entityNum); - if ( bgEnt && (bgEnt->s.powerups&PW_CLOAKED) ) - { + if (bgEnt && (bgEnt->s.powerups & PW_CLOAKED)) { pm->ps->rocketLockIndex = ENTITYNUM_NONE; pm->ps->rocketLockTime = 0; - } - else if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) - { - if (pm->ps->rocketLockIndex == ENTITYNUM_NONE) - { + } else if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) { + if (pm->ps->rocketLockIndex == ENTITYNUM_NONE) { pm->ps->rocketLockIndex = tr.entityNum; pm->ps->rocketLockTime = pm->cmd.serverTime; - } - else if (pm->ps->rocketLockIndex != tr.entityNum && pm->ps->rocketTargetTime < pm->cmd.serverTime) - { + } else if (pm->ps->rocketLockIndex != tr.entityNum && pm->ps->rocketTargetTime < pm->cmd.serverTime) { pm->ps->rocketLockIndex = tr.entityNum; pm->ps->rocketLockTime = pm->cmd.serverTime; - } - else if (pm->ps->rocketLockIndex == tr.entityNum) - { - if (pm->ps->rocketLockTime == -1) - { + } else if (pm->ps->rocketLockIndex == tr.entityNum) { + if (pm->ps->rocketLockTime == -1) { pm->ps->rocketLockTime = pm->ps->rocketLastValidTime; } } - if (pm->ps->rocketLockIndex == tr.entityNum) - { + if (pm->ps->rocketLockIndex == tr.entityNum) { pm->ps->rocketTargetTime = pm->cmd.serverTime + 500; } - } - else if (!vehicleLock) - { - if (pm->ps->rocketTargetTime < pm->cmd.serverTime) - { + } else if (!vehicleLock) { + if (pm->ps->rocketTargetTime < pm->cmd.serverTime) { pm->ps->rocketLockIndex = ENTITYNUM_NONE; pm->ps->rocketLockTime = 0; } } - } - else if (pm->ps->rocketTargetTime < pm->cmd.serverTime) - { + } else if (pm->ps->rocketTargetTime < pm->cmd.serverTime) { pm->ps->rocketLockIndex = ENTITYNUM_NONE; pm->ps->rocketLockTime = 0; - } - else - { - if (pm->ps->rocketLockTime != -1) - { + } else { + if (pm->ps->rocketLockTime != -1) { pm->ps->rocketLastValidTime = pm->ps->rocketLockTime; } pm->ps->rocketLockTime = -1; @@ -6009,52 +5017,38 @@ void PM_RocketLock( float lockDist, qboolean vehicleLock ) } //--------------------------------------- -static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh ) +static qboolean PM_DoChargedWeapons(qboolean vehicleRocketLock, bgEntity_t *veh) //--------------------------------------- { - qboolean charging = qfalse, - altFire = qfalse; - - if ( vehicleRocketLock ) - { - if ( (pm->cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//actually charging - if ( veh - && veh->m_pVehicle ) - {//just make sure we have this veh info - if ( ( (pm->cmd.buttons&BUTTON_ATTACK) - &&g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming - &&pm->ps->ammo[0]>=g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].iAmmoPerShot ) - || - ( (pm->cmd.buttons&BUTTON_ALT_ATTACK) - &&g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming - &&pm->ps->ammo[1]>=g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].iAmmoPerShot ) ) - {//pressing the appropriate fire button for the lock-on/charging weapon + qboolean charging = qfalse, altFire = qfalse; + + if (vehicleRocketLock) { + if ((pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // actually charging + if (veh && veh->m_pVehicle) { // just make sure we have this veh info + if (((pm->cmd.buttons & BUTTON_ATTACK) && g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming && + pm->ps->ammo[0] >= g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].iAmmoPerShot) || + ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming && + pm->ps->ammo[1] >= g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID] + .iAmmoPerShot)) { // pressing the appropriate fire button for the lock-on/charging weapon PM_RocketLock(16384, qtrue); charging = qtrue; } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; } } } - //else, let go and should fire now - } - else - { + // else, let go and should fire now + } else { // If you want your weapon to be a charging weapon, just set this bit up - switch( pm->ps->weapon ) - { + switch (pm->ps->weapon) { //------------------ case WP_BRYAR_PISTOL: // alt-fire charges the weapon - //if ( pm->gametype == GT_SIEGE ) - if (1) - { - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + // if ( pm->gametype == GT_SIEGE ) + if (1) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -6062,8 +5056,7 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh break; case WP_CONCUSSION: - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; } break; @@ -6071,8 +5064,7 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh case WP_BRYAR_OLD: // alt-fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { charging = qtrue; altFire = qtrue; } @@ -6082,18 +5074,15 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh case WP_BOWCASTER: // primary fire charges the weapon - if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; //------------------ case WP_ROCKET_LAUNCHER: - if ( (pm->cmd.buttons & BUTTON_ALT_ATTACK) - && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] >= weaponData[pm->ps->weapon].altEnergyPerShot ) - { - PM_RocketLock(2048,qfalse); + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] >= weaponData[pm->ps->weapon].altEnergyPerShot) { + PM_RocketLock(2048, qfalse); charging = qtrue; altFire = qtrue; } @@ -6102,47 +5091,33 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh //------------------ case WP_THERMAL: - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; // override default of not being an alt-fire charging = qtrue; - } - else if ( pm->cmd.buttons & BUTTON_ATTACK ) - { + } else if (pm->cmd.buttons & BUTTON_ATTACK) { charging = qtrue; } break; case WP_DEMP2: - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { altFire = qtrue; // override default of not being an alt-fire charging = qtrue; } break; case WP_DISRUPTOR: - if ((pm->cmd.buttons & BUTTON_ATTACK) && - pm->ps->zoomMode == 1 && - pm->ps->zoomLocked) - { - if (!pm->cmd.forwardmove && - !pm->cmd.rightmove && - pm->cmd.upmove <= 0) - { + if ((pm->cmd.buttons & BUTTON_ATTACK) && pm->ps->zoomMode == 1 && pm->ps->zoomLocked) { + if (!pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove <= 0) { charging = qtrue; altFire = qtrue; - } - else - { + } else { charging = qfalse; altFire = qfalse; } } - if (pm->ps->zoomMode != 1 && - pm->ps->weaponstate == WEAPON_CHARGING_ALT) - { + if (pm->ps->zoomMode != 1 && pm->ps->weaponstate == WEAPON_CHARGING_ALT) { pm->ps->weaponstate = WEAPON_READY; charging = qfalse; altFire = qfalse; @@ -6153,80 +5128,61 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh // set up the appropriate weapon state based on the button that's down. // Note that we ALWAYS return if charging is set ( meaning the buttons are still down ) - if ( charging ) - { - if ( altFire ) - { - if ( pm->ps->weaponstate != WEAPON_CHARGING_ALT ) - { + if (charging) { + if (altFire) { + if (pm->ps->weaponstate != WEAPON_CHARGING_ALT) { // charge isn't started, so do it now pm->ps->weaponstate = WEAPON_CHARGING_ALT; pm->ps->weaponChargeTime = pm->cmd.serverTime; pm->ps->weaponChargeSubtractTime = pm->cmd.serverTime + weaponData[pm->ps->weapon].altChargeSubTime; #ifdef _DEBUG - // Com_Printf("Starting charge\n"); + // Com_Printf("Starting charge\n"); #endif assert(pm->ps->weapon > WP_NONE); BG_AddPredictableEventToPlayerstate(EV_WEAPON_CHARGE_ALT, pm->ps->weapon, pm->ps); } - if ( vehicleRocketLock ) - {//check vehicle ammo - if ( veh && pm->ps->ammo[1] < g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].iAmmoPerShot ) - { + if (vehicleRocketLock) { // check vehicle ammo + if (veh && pm->ps->ammo[1] < g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].iAmmoPerShot) { pm->ps->weaponstate = WEAPON_CHARGING_ALT; goto rest; } - } - else if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < (weaponData[pm->ps->weapon].altChargeSub+weaponData[pm->ps->weapon].altEnergyPerShot)) - { + } else if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < + (weaponData[pm->ps->weapon].altChargeSub + weaponData[pm->ps->weapon].altEnergyPerShot)) { pm->ps->weaponstate = WEAPON_CHARGING_ALT; goto rest; - } - else if ((pm->cmd.serverTime - pm->ps->weaponChargeTime) < weaponData[pm->ps->weapon].altMaxCharge) - { - if (pm->ps->weaponChargeSubtractTime < pm->cmd.serverTime) - { + } else if ((pm->cmd.serverTime - pm->ps->weaponChargeTime) < weaponData[pm->ps->weapon].altMaxCharge) { + if (pm->ps->weaponChargeSubtractTime < pm->cmd.serverTime) { pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] -= weaponData[pm->ps->weapon].altChargeSub; pm->ps->weaponChargeSubtractTime = pm->cmd.serverTime + weaponData[pm->ps->weapon].altChargeSubTime; } } - } - else - { - if ( pm->ps->weaponstate != WEAPON_CHARGING ) - { + } else { + if (pm->ps->weaponstate != WEAPON_CHARGING) { // charge isn't started, so do it now pm->ps->weaponstate = WEAPON_CHARGING; pm->ps->weaponChargeTime = pm->cmd.serverTime; pm->ps->weaponChargeSubtractTime = pm->cmd.serverTime + weaponData[pm->ps->weapon].chargeSubTime; #ifdef _DEBUG - // Com_Printf("Starting charge\n"); + // Com_Printf("Starting charge\n"); #endif BG_AddPredictableEventToPlayerstate(EV_WEAPON_CHARGE, pm->ps->weapon, pm->ps); } - if ( vehicleRocketLock ) - { - if ( veh && pm->ps->ammo[0] < g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].iAmmoPerShot ) - {//check vehicle ammo + if (vehicleRocketLock) { + if (veh && pm->ps->ammo[0] < g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].iAmmoPerShot) { // check vehicle ammo pm->ps->weaponstate = WEAPON_CHARGING; goto rest; } - } - else if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < (weaponData[pm->ps->weapon].chargeSub+weaponData[pm->ps->weapon].energyPerShot)) - { + } else if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < (weaponData[pm->ps->weapon].chargeSub + weaponData[pm->ps->weapon].energyPerShot)) { pm->ps->weaponstate = WEAPON_CHARGING; goto rest; - } - else if ((pm->cmd.serverTime - pm->ps->weaponChargeTime) < weaponData[pm->ps->weapon].maxCharge) - { - if (pm->ps->weaponChargeSubtractTime < pm->cmd.serverTime) - { + } else if ((pm->cmd.serverTime - pm->ps->weaponChargeTime) < weaponData[pm->ps->weapon].maxCharge) { + if (pm->ps->weaponChargeSubtractTime < pm->cmd.serverTime) { pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] -= weaponData[pm->ps->weapon].chargeSub; pm->ps->weaponChargeSubtractTime = pm->cmd.serverTime + weaponData[pm->ps->weapon].chargeSubTime; } @@ -6238,95 +5194,79 @@ static qboolean PM_DoChargedWeapons( qboolean vehicleRocketLock, bgEntity_t *veh rest: // Only charging weapons should be able to set these states...so.... // let's see which fire mode we need to set up now that the buttons are up - if ( pm->ps->weaponstate == WEAPON_CHARGING ) - { + if (pm->ps->weaponstate == WEAPON_CHARGING) { // weapon has a charge, so let us do an attack #ifdef _DEBUG - // Com_Printf("Firing. Charge time=%d\n", pm->cmd.serverTime - pm->ps->weaponChargeTime); + // Com_Printf("Firing. Charge time=%d\n", pm->cmd.serverTime - pm->ps->weaponChargeTime); #endif // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ATTACK; pm->ps->eFlags |= EF_FIRING; - } - else if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + } else if (pm->ps->weaponstate == WEAPON_CHARGING_ALT) { // weapon has a charge, so let us do an alt-attack #ifdef _DEBUG - // Com_Printf("Firing. Charge time=%d\n", pm->cmd.serverTime - pm->ps->weaponChargeTime); + // Com_Printf("Firing. Charge time=%d\n", pm->cmd.serverTime - pm->ps->weaponChargeTime); #endif // dumb, but since we shoot a charged weapon on button-up, we need to repress this button for now pm->cmd.buttons |= BUTTON_ALT_ATTACK; - pm->ps->eFlags |= (EF_FIRING|EF_ALT_FIRING); + pm->ps->eFlags |= (EF_FIRING | EF_ALT_FIRING); } return qfalse; // continue with the rest of the weapon code } +#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon +#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon -#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in g_weapon - -int PM_ItemUsable(playerState_t *ps, int forcedUse) -{ +int PM_ItemUsable(playerState_t *ps, int forcedUse) { vec3_t fwd, fwdorg, dest, pos; vec3_t yawonly; vec3_t mins, maxs; vec3_t trtest; trace_t tr; - if (ps->m_iVehicleNum) - { + if (ps->m_iVehicleNum) { return 0; } - if (ps->pm_flags & PMF_USE_ITEM_HELD) - { //force to let go first + if (ps->pm_flags & PMF_USE_ITEM_HELD) { // force to let go first return 0; } - if (ps->duelInProgress) - { //not allowed to use holdables while in a private duel. + if (ps->duelInProgress) { // not allowed to use holdables while in a private duel. return 0; } - if (!forcedUse) - { + if (!forcedUse) { forcedUse = bg_itemlist[ps->stats[STAT_HOLDABLE_ITEM]].giTag; } - if (!BG_IsItemSelectable(ps, forcedUse)) - { + if (!BG_IsItemSelectable(ps, forcedUse)) { return 0; } - switch (forcedUse) - { + switch (forcedUse) { case HI_MEDPAC: case HI_MEDPAC_BIG: - if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) - { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) { return 0; } - if (ps->stats[STAT_HEALTH] <= 0 || - (ps->eFlags & EF_DEAD)) - { + if (ps->stats[STAT_HEALTH] <= 0 || (ps->eFlags & EF_DEAD)) { return 0; } return 1; case HI_SEEKER: - if (ps->eFlags & EF_SEEKERDRONE) - { + if (ps->eFlags & EF_SEEKERDRONE) { PM_AddEventWithParm(EV_ITEMUSEFAIL, SEEKER_ALREADYDEPLOYED); return 0; } return 1; case HI_SENTRY_GUN: - if (ps->fd.sentryDeployed) - { + if (ps->fd.sentryDeployed) { PM_AddEventWithParm(EV_ITEMUSEFAIL, SENTRY_ALREADYPLACED); return 0; } @@ -6335,23 +5275,22 @@ int PM_ItemUsable(playerState_t *ps, int forcedUse) yawonly[PITCH] = 0; yawonly[YAW] = ps->viewangles[YAW]; - VectorSet( mins, -8, -8, 0 ); - VectorSet( maxs, 8, 8, 24 ); + VectorSet(mins, -8, -8, 0); + VectorSet(maxs, 8, 8, 24); AngleVectors(yawonly, fwd, NULL, NULL); - fwdorg[0] = ps->origin[0] + fwd[0]*64; - fwdorg[1] = ps->origin[1] + fwd[1]*64; - fwdorg[2] = ps->origin[2] + fwd[2]*64; + fwdorg[0] = ps->origin[0] + fwd[0] * 64; + fwdorg[1] = ps->origin[1] + fwd[1] * 64; + fwdorg[2] = ps->origin[2] + fwd[2] * 64; - trtest[0] = fwdorg[0] + fwd[0]*16; - trtest[1] = fwdorg[1] + fwd[1]*16; - trtest[2] = fwdorg[2] + fwd[2]*16; + trtest[0] = fwdorg[0] + fwd[0] * 16; + trtest[1] = fwdorg[1] + fwd[1] * 16; + trtest[2] = fwdorg[2] + fwd[2] * 16; pm->trace(&tr, ps->origin, mins, maxs, trtest, ps->clientNum, MASK_PLAYERSOLID); - if ((tr.fraction != 1 && tr.entityNum != ps->clientNum) || tr.startsolid || tr.allsolid) - { + if ((tr.fraction != 1 && tr.entityNum != ps->clientNum) || tr.startsolid || tr.allsolid) { PM_AddEventWithParm(EV_ITEMUSEFAIL, SENTRY_NOROOM); return 0; } @@ -6366,23 +5305,21 @@ int PM_ItemUsable(playerState_t *ps, int forcedUse) maxs[1] = 8; maxs[2] = 8; - AngleVectors (ps->viewangles, fwd, NULL, NULL); + AngleVectors(ps->viewangles, fwd, NULL, NULL); fwd[2] = 0; VectorMA(ps->origin, 64, fwd, dest); - pm->trace(&tr, ps->origin, mins, maxs, dest, ps->clientNum, MASK_SHOT ); - if (tr.fraction > 0.9 && !tr.startsolid && !tr.allsolid) - { + pm->trace(&tr, ps->origin, mins, maxs, dest, ps->clientNum, MASK_SHOT); + if (tr.fraction > 0.9 && !tr.startsolid && !tr.allsolid) { VectorCopy(tr.endpos, pos); - VectorSet( dest, pos[0], pos[1], pos[2] - 4096 ); - pm->trace( &tr, pos, mins, maxs, dest, ps->clientNum, MASK_SOLID ); - if ( !tr.startsolid && !tr.allsolid ) - { + VectorSet(dest, pos[0], pos[1], pos[2] - 4096); + pm->trace(&tr, pos, mins, maxs, dest, ps->clientNum, MASK_SOLID); + if (!tr.startsolid && !tr.allsolid) { return 1; } } PM_AddEventWithParm(EV_ITEMUSEFAIL, SHIELD_NOROOM); return 0; - case HI_JETPACK: //check for stuff here? + case HI_JETPACK: // check for stuff here? return 1; case HI_HEALTHDISP: return 1; @@ -6390,228 +5327,178 @@ int PM_ItemUsable(playerState_t *ps, int forcedUse) return 1; case HI_EWEB: return 1; - case HI_CLOAK: //check for stuff here? + case HI_CLOAK: // check for stuff here? return 1; default: return 1; } } -//cheesy vehicle weapon hackery -qboolean PM_CanSetWeaponAnims(void) -{ - if (pm->ps->m_iVehicleNum) - { +// cheesy vehicle weapon hackery +qboolean PM_CanSetWeaponAnims(void) { + if (pm->ps->m_iVehicleNum) { return qfalse; } return qtrue; } -//perform player anim overrides while on vehicle. +// perform player anim overrides while on vehicle. extern int PM_irand_timesync(int val1, int val2); -void PM_VehicleWeaponAnimate(void) -{ +void PM_VehicleWeaponAnimate(void) { bgEntity_t *veh = pm_entVeh; Vehicle_t *pVeh; int iFlags = 0, Anim = -1; - if (!veh || - !veh->m_pVehicle || - !veh->m_pVehicle->m_pPilot || - !veh->m_pVehicle->m_pPilot->playerState || - pm->ps->clientNum != veh->m_pVehicle->m_pPilot->playerState->clientNum) - { //make sure the vehicle exists, and its pilot is this player + if (!veh || !veh->m_pVehicle || !veh->m_pVehicle->m_pPilot || !veh->m_pVehicle->m_pPilot->playerState || + pm->ps->clientNum != veh->m_pVehicle->m_pPilot->playerState->clientNum) { // make sure the vehicle exists, and its pilot is this player return; } pVeh = veh->m_pVehicle; - if (pVeh->m_pVehicleInfo->type == VH_WALKER || - pVeh->m_pVehicleInfo->type == VH_FIGHTER) - { //slightly hacky I guess, but whatever. + if (pVeh->m_pVehicleInfo->type == VH_WALKER || pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // slightly hacky I guess, but whatever. return; } backAgain: // If they're firing, play the right fire animation. - if ( pm->cmd.buttons & ( BUTTON_ATTACK | BUTTON_ALT_ATTACK ) ) - { + if (pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) { iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - switch ( pm->ps->weapon ) - { - case WP_SABER: - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { //don't do anything.. I guess. - pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; - goto backAgain; - } - // If we're already in an attack animation, leave (let it continue). - if (pm->ps->torsoTimer <= 0) - { //we'll be starting a new attack - PM_AddEvent(EV_SABER_ATTACK); - } + switch (pm->ps->weapon) { + case WP_SABER: + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // don't do anything.. I guess. + pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; + goto backAgain; + } + // If we're already in an attack animation, leave (let it continue). + if (pm->ps->torsoTimer <= 0) { // we'll be starting a new attack + PM_AddEvent(EV_SABER_ATTACK); + } - //just set it to something so we have a proper trail. This is a stupid - //hack (much like the rest of this function) - pm->ps->saberMove = LS_R_TL2BR; + // just set it to something so we have a proper trail. This is a stupid + // hack (much like the rest of this function) + pm->ps->saberMove = LS_R_TL2BR; - if ( pm->ps->torsoTimer > 0 && (pm->ps->torsoAnim == BOTH_VS_ATR_S || - pm->ps->torsoAnim == BOTH_VS_ATL_S) ) - { - /* - //FIXME: no need to even call the PM_SetAnim at all in this case - Anim = (animNumber_t)pm->ps->torsoAnim; - iFlags = SETANIM_FLAG_NORMAL; - break; - */ - return; - } + if (pm->ps->torsoTimer > 0 && (pm->ps->torsoAnim == BOTH_VS_ATR_S || pm->ps->torsoAnim == BOTH_VS_ATL_S)) { + /* + //FIXME: no need to even call the PM_SetAnim at all in this case + Anim = (animNumber_t)pm->ps->torsoAnim; + iFlags = SETANIM_FLAG_NORMAL; + break; + */ + return; + } - // Start the attack. - if ( pm->cmd.rightmove > 0 ) //right side attack - { + // Start the attack. + if (pm->cmd.rightmove > 0) // right side attack + { + Anim = BOTH_VS_ATR_S; + } else if (pm->cmd.rightmove < 0) // left-side attack + { + Anim = BOTH_VS_ATL_S; + } else // random + { + // FIXME: alternate back and forth or auto-aim? + // if ( !Q_irand( 0, 1 ) ) + if (!PM_irand_timesync(0, 1)) { Anim = BOTH_VS_ATR_S; - } - else if ( pm->cmd.rightmove < 0 ) //left-side attack - { + } else { Anim = BOTH_VS_ATL_S; } - else //random - { - //FIXME: alternate back and forth or auto-aim? - //if ( !Q_irand( 0, 1 ) ) - if (!PM_irand_timesync(0, 1)) - { - Anim = BOTH_VS_ATR_S; - } - else - { - Anim = BOTH_VS_ATL_S; - } - } + } - if (pm->ps->torsoTimer <= 0) - { //restart the anim if we are already in it (and finished) - iFlags |= SETANIM_FLAG_RESTART; - } - break; + if (pm->ps->torsoTimer <= 0) { // restart the anim if we are already in it (and finished) + iFlags |= SETANIM_FLAG_RESTART; + } + break; - case WP_BLASTER: - // Override the shoot anim. - if ( pm->ps->torsoAnim == BOTH_ATTACK3 ) + case WP_BLASTER: + // Override the shoot anim. + if (pm->ps->torsoAnim == BOTH_ATTACK3) { + if (pm->cmd.rightmove > 0) // right side attack { - if ( pm->cmd.rightmove > 0 ) //right side attack - { - Anim = BOTH_VS_ATR_G; - } - else if ( pm->cmd.rightmove < 0 ) //left side - { - Anim = BOTH_VS_ATL_G; - } - else //frontal - { - Anim = BOTH_VS_ATF_G; - } + Anim = BOTH_VS_ATR_G; + } else if (pm->cmd.rightmove < 0) // left side + { + Anim = BOTH_VS_ATL_G; + } else // frontal + { + Anim = BOTH_VS_ATF_G; } - break; + } + break; - default: - Anim = BOTH_VS_IDLE; - break; + default: + Anim = BOTH_VS_IDLE; + break; } - } - else if (veh->playerState && veh->playerState->speed < 0 && - pVeh->m_pVehicleInfo->type == VH_ANIMAL) - { //tauntaun is going backwards + } else if (veh->playerState && veh->playerState->speed < 0 && pVeh->m_pVehicleInfo->type == VH_ANIMAL) { // tauntaun is going backwards Anim = BOTH_VT_WALK_REV; - } - else if (veh->playerState && veh->playerState->speed < 0 && - pVeh->m_pVehicleInfo->type == VH_SPEEDER) - { //speeder is going backwards + } else if (veh->playerState && veh->playerState->speed < 0 && pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // speeder is going backwards Anim = BOTH_VS_REV; } // They're not firing so play the Idle for the weapon. - else - { + else { iFlags = SETANIM_FLAG_NORMAL; - switch ( pm->ps->weapon ) - { - case WP_SABER: - if ( BG_SabersOff( pm->ps ) ) - { //saber holstered, normal idle - Anim = BOTH_VS_IDLE; - } - // In the Air. - //else if ( pVeh->m_ulFlags & VEH_FLYING ) - else if (0) - { - Anim = BOTH_VS_AIR_G; - iFlags = SETANIM_FLAG_OVERRIDE; - } - // Crashing. - //else if ( pVeh->m_ulFlags & VEH_CRASHING ) - else if (0) - { - pVeh->m_ulFlags &= ~VEH_CRASHING; // Remove the flag, we are doing the animation. - Anim = BOTH_VS_LAND_SR; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - } - else - { - Anim = BOTH_VS_IDLE_SR; - } - break; + switch (pm->ps->weapon) { + case WP_SABER: + if (BG_SabersOff(pm->ps)) { // saber holstered, normal idle + Anim = BOTH_VS_IDLE; + } + // In the Air. + // else if ( pVeh->m_ulFlags & VEH_FLYING ) + else if (0) { + Anim = BOTH_VS_AIR_G; + iFlags = SETANIM_FLAG_OVERRIDE; + } + // Crashing. + // else if ( pVeh->m_ulFlags & VEH_CRASHING ) + else if (0) { + pVeh->m_ulFlags &= ~VEH_CRASHING; // Remove the flag, we are doing the animation. + Anim = BOTH_VS_LAND_SR; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + } else { + Anim = BOTH_VS_IDLE_SR; + } + break; - case WP_BLASTER: - // In the Air. - //if ( pVeh->m_ulFlags & VEH_FLYING ) - if (0) - { - Anim = BOTH_VS_AIR_G; - iFlags = SETANIM_FLAG_OVERRIDE; - } - // Crashing. - //else if ( pVeh->m_ulFlags & VEH_CRASHING ) - else if (0) - { - pVeh->m_ulFlags &= ~VEH_CRASHING; // Remove the flag, we are doing the animation. - Anim = BOTH_VS_LAND_G; - iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; - } - else - { - Anim = BOTH_VS_IDLE_G; - } - break; + case WP_BLASTER: + // In the Air. + // if ( pVeh->m_ulFlags & VEH_FLYING ) + if (0) { + Anim = BOTH_VS_AIR_G; + iFlags = SETANIM_FLAG_OVERRIDE; + } + // Crashing. + // else if ( pVeh->m_ulFlags & VEH_CRASHING ) + else if (0) { + pVeh->m_ulFlags &= ~VEH_CRASHING; // Remove the flag, we are doing the animation. + Anim = BOTH_VS_LAND_G; + iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD; + } else { + Anim = BOTH_VS_IDLE_G; + } + break; - default: - Anim = BOTH_VS_IDLE; - break; + default: + Anim = BOTH_VS_IDLE; + break; } } - if (Anim != -1) - { //override it - if (pVeh->m_pVehicleInfo->type == VH_ANIMAL) - { //agh.. remap anims for the tauntaun - switch (Anim) - { + if (Anim != -1) { // override it + if (pVeh->m_pVehicleInfo->type == VH_ANIMAL) { // agh.. remap anims for the tauntaun + switch (Anim) { case BOTH_VS_IDLE: - if (veh->playerState && veh->playerState->speed > 0) - { - if (veh->playerState->speed > pVeh->m_pVehicleInfo->speedMax) - { //turbo + if (veh->playerState && veh->playerState->speed > 0) { + if (veh->playerState->speed > pVeh->m_pVehicleInfo->speedMax) { // turbo Anim = BOTH_VT_TURBO; - } - else - { + } else { Anim = BOTH_VT_RUN_FWD; } - } - else - { + } else { Anim = BOTH_VT_IDLE; } break; @@ -6622,7 +5509,7 @@ void PM_VehicleWeaponAnimate(void) Anim = BOTH_VT_ATL_S; break; case BOTH_VS_ATR_G: - Anim = BOTH_VT_ATR_G; + Anim = BOTH_VT_ATR_G; break; case BOTH_VS_ATL_G: Anim = BOTH_VT_ATL_G; @@ -6640,7 +5527,7 @@ void PM_VehicleWeaponAnimate(void) Anim = BOTH_VT_IDLE_G; break; - //should not happen for tauntaun: + // should not happen for tauntaun: case BOTH_VS_AIR_G: case BOTH_VS_LAND_SL: case BOTH_VS_LAND_SR: @@ -6663,24 +5550,17 @@ Generates weapon events and modifes the weapon counter ============== */ extern int PM_KickMoveForConditions(void); -static void PM_Weapon( void ) -{ - int addTime; +static void PM_Weapon(void) { + int addTime; int amount; - int killAfterItem = 0; + int killAfterItem = 0; bgEntity_t *veh = NULL; qboolean vehicleRocketLock = qfalse; #ifdef _GAME - if (pm->ps->clientNum >= MAX_CLIENTS && - pm->ps->weapon == WP_NONE && - pm->cmd.weapon == WP_NONE && - pm_entSelf) - { //npc with no weapon + if (pm->ps->clientNum >= MAX_CLIENTS && pm->ps->weapon == WP_NONE && pm->cmd.weapon == WP_NONE && pm_entSelf) { // npc with no weapon gentity_t *gent = (gentity_t *)pm_entSelf; - if (gent->inuse && gent->client && - !gent->localAnimIndex) - { //humanoid + if (gent->inuse && gent->client && !gent->localAnimIndex) { // humanoid pm->ps->torsoAnim = pm->ps->legsAnim; pm->ps->torsoTimer = pm->ps->legsTimer; return; @@ -6688,121 +5568,94 @@ static void PM_Weapon( void ) } #endif - if (!pm->ps->emplacedIndex && - pm->ps->weapon == WP_EMPLACED_GUN) - { //oh no! + if (!pm->ps->emplacedIndex && pm->ps->weapon == WP_EMPLACED_GUN) { // oh no! int i = 0; int weap = -1; - while (i < WP_NUM_WEAPONS) - { - if ((pm->ps->stats[STAT_WEAPONS] & (1 << i)) && i != WP_NONE) - { //this one's good + while (i < WP_NUM_WEAPONS) { + if ((pm->ps->stats[STAT_WEAPONS] & (1 << i)) && i != WP_NONE) { // this one's good weap = i; break; } i++; } - if (weap != -1) - { + if (weap != -1) { pm->cmd.weapon = weap; pm->ps->weapon = weap; return; } } - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pm->ps->m_iVehicleNum) - { //riding a vehicle - if ( (veh = pm_entVeh) && - (veh->m_pVehicle && (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) ) ) - {//riding a walker/fighter - //keep saber off, do no weapon stuff at all! + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->m_iVehicleNum) { // riding a vehicle + if ((veh = pm_entVeh) && (veh->m_pVehicle && (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || + veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER))) { // riding a walker/fighter + // keep saber off, do no weapon stuff at all! pm->ps->saberHolstered = 2; #ifdef _GAME - pm->cmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + pm->cmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); #else - if ( g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming - || g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming ) - {//our vehicle uses a rocket launcher, so do the normal checks + if (g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming || + g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming) { // our vehicle uses a rocket launcher, so do the normal checks vehicleRocketLock = qtrue; pm->cmd.buttons &= ~BUTTON_ATTACK; - } - else - { - pm->cmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); + } else { + pm->cmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); } #endif } } - if (pm->ps->weapon != WP_DISRUPTOR //not using disruptor - && pm->ps->weapon != WP_ROCKET_LAUNCHER//not using rocket launcher - && pm->ps->weapon != WP_THERMAL//not using thermals - && !pm->ps->m_iVehicleNum )//not a vehicle or in a vehicle - { //check for exceeding max charge time if not using disruptor or rocket launcher or thermals - if ( pm->ps->weaponstate == WEAPON_CHARGING_ALT ) - { + if (pm->ps->weapon != WP_DISRUPTOR // not using disruptor + && pm->ps->weapon != WP_ROCKET_LAUNCHER // not using rocket launcher + && pm->ps->weapon != WP_THERMAL // not using thermals + && !pm->ps->m_iVehicleNum) // not a vehicle or in a vehicle + { // check for exceeding max charge time if not using disruptor or rocket launcher or thermals + if (pm->ps->weaponstate == WEAPON_CHARGING_ALT) { int timeDif = (pm->cmd.serverTime - pm->ps->weaponChargeTime); - if (timeDif > MAX_WEAPON_CHARGE_TIME) - { + if (timeDif > MAX_WEAPON_CHARGE_TIME) { pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } } - if ( pm->ps->weaponstate == WEAPON_CHARGING ) - { + if (pm->ps->weaponstate == WEAPON_CHARGING) { int timeDif = (pm->cmd.serverTime - pm->ps->weaponChargeTime); - if (timeDif > MAX_WEAPON_CHARGE_TIME) - { + if (timeDif > MAX_WEAPON_CHARGE_TIME) { pm->cmd.buttons &= ~BUTTON_ATTACK; } } } - if (pm->ps->forceHandExtend == HANDEXTEND_WEAPONREADY && - PM_CanSetWeaponAnims()) - { //reset into weapon stance - if (pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE && !PM_IsRocketTrooper()) - { //saber handles its own anims - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { - //PM_StartTorsoAnim( TORSO_WEAPONREADY4 ); - PM_StartTorsoAnim( TORSO_RAISEWEAP1); - } - else - { - if (pm->ps->weapon == WP_EMPLACED_GUN) - { - PM_StartTorsoAnim( BOTH_GUNSIT1 ); - } - else - { - //PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); - PM_StartTorsoAnim( TORSO_RAISEWEAP1); + if (pm->ps->forceHandExtend == HANDEXTEND_WEAPONREADY && PM_CanSetWeaponAnims()) { // reset into weapon stance + if (pm->ps->weapon != WP_SABER && pm->ps->weapon != WP_MELEE && !PM_IsRocketTrooper()) { // saber handles its own anims + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + // PM_StartTorsoAnim( TORSO_WEAPONREADY4 ); + PM_StartTorsoAnim(TORSO_RAISEWEAP1); + } else { + if (pm->ps->weapon == WP_EMPLACED_GUN) { + PM_StartTorsoAnim(BOTH_GUNSIT1); + } else { + // PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); + PM_StartTorsoAnim(TORSO_RAISEWEAP1); } } } - //we now go into a weapon raise anim after every force hand extend. - //this is so that my holster-view-weapon-when-hand-extend stuff works. + // we now go into a weapon raise anim after every force hand extend. + // this is so that my holster-view-weapon-when-hand-extend stuff works. pm->ps->weaponstate = WEAPON_RAISING; pm->ps->weaponTime += 250; pm->ps->forceHandExtend = HANDEXTEND_NONE; - } - else if (pm->ps->forceHandExtend != HANDEXTEND_NONE) - { //nothing else should be allowed to happen during this time, including weapon fire + } else if (pm->ps->forceHandExtend != HANDEXTEND_NONE) { // nothing else should be allowed to happen during this time, including weapon fire int desiredAnim = 0; qboolean seperateOnTorso = qfalse; qboolean playFullBody = qfalse; int desiredOnTorso = 0; - switch(pm->ps->forceHandExtend) - { + switch (pm->ps->forceHandExtend) { case HANDEXTEND_FORCEPUSH: desiredAnim = BOTH_FORCEPUSH; break; @@ -6810,28 +5663,17 @@ static void PM_Weapon( void ) desiredAnim = BOTH_FORCEPULL; break; case HANDEXTEND_FORCE_HOLD: - if ( (pm->ps->fd.forcePowersActive&(1<ps->fd.forcePowersActive & (1 << FP_GRIP))) { // gripping desiredAnim = BOTH_FORCEGRIP_HOLD; - } - else if ( (pm->ps->fd.forcePowersActive&(1<ps->weapon == WP_MELEE - && pm->ps->activeForcePass > FORCE_LEVEL_2 ) - {//2-handed lightning + } else if ((pm->ps->fd.forcePowersActive & (1 << FP_LIGHTNING))) { // lightning + if (pm->ps->weapon == WP_MELEE && pm->ps->activeForcePass > FORCE_LEVEL_2) { // 2-handed lightning desiredAnim = BOTH_FORCE_2HANDEDLIGHTNING_HOLD; - } - else - { + } else { desiredAnim = BOTH_FORCELIGHTNING_HOLD; } - } - else if ( (pm->ps->fd.forcePowersActive&(1<ps->fd.forcePowersActive & (1 << FP_DRAIN))) { // draining desiredAnim = BOTH_FORCEGRIP_HOLD; - } - else - {//??? + } else { //??? desiredAnim = BOTH_FORCEGRIP_HOLD; } break; @@ -6839,49 +5681,34 @@ static void PM_Weapon( void ) desiredAnim = BOTH_SABERPULL; break; case HANDEXTEND_CHOKE: - desiredAnim = BOTH_CHOKE3; //left-handed choke + desiredAnim = BOTH_CHOKE3; // left-handed choke break; case HANDEXTEND_DODGE: desiredAnim = pm->ps->forceDodgeAnim; break; case HANDEXTEND_KNOCKDOWN: - if (pm->ps->forceDodgeAnim) - { - if (pm->ps->forceDodgeAnim > 4) - { //this means that we want to play a sepereate anim on the torso - int originalDAnim = pm->ps->forceDodgeAnim-8; //-8 is the original legs anim - if (originalDAnim == 2) - { + if (pm->ps->forceDodgeAnim) { + if (pm->ps->forceDodgeAnim > 4) { // this means that we want to play a sepereate anim on the torso + int originalDAnim = pm->ps->forceDodgeAnim - 8; //-8 is the original legs anim + if (originalDAnim == 2) { desiredAnim = BOTH_FORCE_GETUP_B1; - } - else if (originalDAnim == 3) - { - desiredAnim = BOTH_FORCE_GETUP_B3; - } - else - { + } else if (originalDAnim == 3) { + desiredAnim = BOTH_FORCE_GETUP_B3; + } else { desiredAnim = BOTH_GETUP1; } - //now specify the torso anim + // now specify the torso anim seperateOnTorso = qtrue; desiredOnTorso = BOTH_FORCEPUSH; - } - else if (pm->ps->forceDodgeAnim == 2) - { + } else if (pm->ps->forceDodgeAnim == 2) { desiredAnim = BOTH_FORCE_GETUP_B1; - } - else if (pm->ps->forceDodgeAnim == 3) - { + } else if (pm->ps->forceDodgeAnim == 3) { desiredAnim = BOTH_FORCE_GETUP_B3; - } - else - { + } else { desiredAnim = BOTH_GETUP1; } - } - else - { + } else { desiredAnim = BOTH_KNOCKDOWN1; } break; @@ -6890,10 +5717,7 @@ static void PM_Weapon( void ) break; case HANDEXTEND_TAUNT: desiredAnim = pm->ps->forceDodgeAnim; - if ( desiredAnim != BOTH_ENGAGETAUNT - && VectorCompare( pm->ps->velocity, vec3_origin ) - && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { + if (desiredAnim != BOTH_ENGAGETAUNT && VectorCompare(pm->ps->velocity, vec3_origin) && pm->ps->groundEntityNum != ENTITYNUM_NONE) { playFullBody = qtrue; } break; @@ -6910,12 +5734,9 @@ static void PM_Weapon( void ) playFullBody = qtrue; break; case HANDEXTEND_POSTTHROWN: - if (pm->ps->forceDodgeAnim) - { + if (pm->ps->forceDodgeAnim) { desiredAnim = BOTH_FORCE_GETUP_F2; - } - else - { + } else { desiredAnim = BOTH_KNOCKDOWN5; } playFullBody = qtrue; @@ -6925,49 +5746,43 @@ static void PM_Weapon( void ) break; case HANDEXTEND_JEDITAUNT: desiredAnim = BOTH_GESTURE1; - //playFullBody = qtrue; + // playFullBody = qtrue; break; - //Hmm... maybe use these, too? - //BOTH_FORCEHEAL_QUICK //quick heal (SP level 2 & 3) - //BOTH_MINDTRICK1 // wave (maybe for mind trick 2 & 3 - whole area, and for force seeing) - //BOTH_MINDTRICK2 // tap (maybe for mind trick 1 - one person) - //BOTH_FORCEGRIP_START //start grip - //BOTH_FORCEGRIP_HOLD //hold grip - //BOTH_FORCEGRIP_RELEASE //release grip - //BOTH_FORCELIGHTNING //quick lightning burst (level 1) - //BOTH_FORCELIGHTNING_START //start lightning - //BOTH_FORCELIGHTNING_HOLD //hold lightning - //BOTH_FORCELIGHTNING_RELEASE //release lightning + // Hmm... maybe use these, too? + // BOTH_FORCEHEAL_QUICK //quick heal (SP level 2 & 3) + // BOTH_MINDTRICK1 // wave (maybe for mind trick 2 & 3 - whole area, and for force seeing) + // BOTH_MINDTRICK2 // tap (maybe for mind trick 1 - one person) + // BOTH_FORCEGRIP_START //start grip + // BOTH_FORCEGRIP_HOLD //hold grip + // BOTH_FORCEGRIP_RELEASE //release grip + // BOTH_FORCELIGHTNING //quick lightning burst (level 1) + // BOTH_FORCELIGHTNING_START //start lightning + // BOTH_FORCELIGHTNING_HOLD //hold lightning + // BOTH_FORCELIGHTNING_RELEASE //release lightning default: desiredAnim = BOTH_FORCEPUSH; break; } - if (!seperateOnTorso) - { //of seperateOnTorso, handle it after setting the legs - PM_SetAnim(SETANIM_TORSO, desiredAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (!seperateOnTorso) { // of seperateOnTorso, handle it after setting the legs + PM_SetAnim(SETANIM_TORSO, desiredAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->torsoTimer = 1; } - if (playFullBody) - { //sorry if all these exceptions are getting confusing. This one just means play on both legs and torso. - PM_SetAnim(SETANIM_BOTH, desiredAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (playFullBody) { // sorry if all these exceptions are getting confusing. This one just means play on both legs and torso. + PM_SetAnim(SETANIM_BOTH, desiredAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->legsTimer = pm->ps->torsoTimer = 1; - } - else if (pm->ps->forceHandExtend == HANDEXTEND_DODGE || pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || - (pm->ps->forceHandExtend == HANDEXTEND_CHOKE && pm->ps->groundEntityNum == ENTITYNUM_NONE) ) - { //special case, play dodge anim on whole body, choke anim too if off ground - if (seperateOnTorso) - { - PM_SetAnim(SETANIM_LEGS, desiredAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + } else if (pm->ps->forceHandExtend == HANDEXTEND_DODGE || pm->ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || + (pm->ps->forceHandExtend == HANDEXTEND_CHOKE && + pm->ps->groundEntityNum == ENTITYNUM_NONE)) { // special case, play dodge anim on whole body, choke anim too if off ground + if (seperateOnTorso) { + PM_SetAnim(SETANIM_LEGS, desiredAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->legsTimer = 1; - PM_SetAnim(SETANIM_TORSO, desiredOnTorso, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + PM_SetAnim(SETANIM_TORSO, desiredOnTorso, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->torsoTimer = 1; - } - else - { - PM_SetAnim(SETANIM_LEGS, desiredAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + } else { + PM_SetAnim(SETANIM_LEGS, desiredAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->legsTimer = 1; } } @@ -6975,10 +5790,7 @@ static void PM_Weapon( void ) return; } - if (BG_InSpecialJump(pm->ps->legsAnim) || - BG_InRoll(pm->ps, pm->ps->legsAnim) || - PM_InRollComplete(pm->ps, pm->ps->legsAnim)) - { + if (BG_InSpecialJump(pm->ps->legsAnim) || BG_InRoll(pm->ps, pm->ps->legsAnim) || PM_InRollComplete(pm->ps, pm->ps->legsAnim)) { /* if (pm->cmd.weapon != WP_MELEE && pm->ps->weapon != WP_MELEE && @@ -6988,134 +5800,106 @@ static void PM_Weapon( void ) pm->ps->weapon = WP_SABER; } */ - if (pm->ps->weaponTime < pm->ps->legsTimer) - { + if (pm->ps->weaponTime < pm->ps->legsTimer) { pm->ps->weaponTime = pm->ps->legsTimer; } } - if (pm->ps->duelInProgress) - { + if (pm->ps->duelInProgress) { pm->cmd.weapon = WP_SABER; pm->ps->weapon = WP_SABER; - if (pm->ps->duelTime >= pm->cmd.serverTime) - { + if (pm->ps->duelTime >= pm->cmd.serverTime) { pm->cmd.upmove = 0; pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; } } - if (pm->ps->weapon == WP_SABER && pm->ps->saberMove != LS_READY && pm->ps->saberMove != LS_NONE) - { - pm->cmd.weapon = WP_SABER; //don't allow switching out mid-attack + if (pm->ps->weapon == WP_SABER && pm->ps->saberMove != LS_READY && pm->ps->saberMove != LS_NONE) { + pm->cmd.weapon = WP_SABER; // don't allow switching out mid-attack } - if (pm->ps->weapon == WP_SABER) - { - //rww - we still need the item stuff, so we won't return immediately + if (pm->ps->weapon == WP_SABER) { + // rww - we still need the item stuff, so we won't return immediately PM_WeaponLightsaber(); killAfterItem = 1; - } - else if (pm->ps->weapon != WP_EMPLACED_GUN) - { + } else if (pm->ps->weapon != WP_EMPLACED_GUN) { pm->ps->saberHolstered = 0; } - if (PM_CanSetWeaponAnims()) - { - if (pm->ps->weapon == WP_THERMAL || - pm->ps->weapon == WP_TRIP_MINE || - pm->ps->weapon == WP_DET_PACK) - { - if (pm->ps->weapon == WP_THERMAL) - { - if ((pm->ps->torsoAnim) == WeaponAttackAnim[pm->ps->weapon] && - (pm->ps->weaponTime-200) <= 0) - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); + if (PM_CanSetWeaponAnims()) { + if (pm->ps->weapon == WP_THERMAL || pm->ps->weapon == WP_TRIP_MINE || pm->ps->weapon == WP_DET_PACK) { + if (pm->ps->weapon == WP_THERMAL) { + if ((pm->ps->torsoAnim) == WeaponAttackAnim[pm->ps->weapon] && (pm->ps->weaponTime - 200) <= 0) { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); } - } - else - { - if ((pm->ps->torsoAnim) == WeaponAttackAnim[pm->ps->weapon] && - (pm->ps->weaponTime-700) <= 0) - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); + } else { + if ((pm->ps->torsoAnim) == WeaponAttackAnim[pm->ps->weapon] && (pm->ps->weaponTime - 700) <= 0) { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); } } } } // don't allow attack until all buttons are up - if ( pm->ps->pm_flags & PMF_RESPAWNED ) { + if (pm->ps->pm_flags & PMF_RESPAWNED) { return; } // ignore if spectator - if ( pm->ps->clientNum < MAX_CLIENTS && pm->ps->persistant[PERS_TEAM] == TEAM_SPECTATOR ) { - return; + if (pm->ps->clientNum < MAX_CLIENTS && pm->ps->persistant[PERS_TEAM] == TEAM_SPECTATOR) { + return; } // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) { + if (pm->ps->stats[STAT_HEALTH] <= 0) { pm->ps->weapon = WP_NONE; return; } // check for item using - if ( pm->cmd.buttons & BUTTON_USE_HOLDABLE ) { + if (pm->cmd.buttons & BUTTON_USE_HOLDABLE) { // fix: rocket lock bug, one of many... - BG_ClearRocketLock( pm->ps ); + BG_ClearRocketLock(pm->ps); - if ( ! ( pm->ps->pm_flags & PMF_USE_ITEM_HELD ) ) { + if (!(pm->ps->pm_flags & PMF_USE_ITEM_HELD)) { - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - && pm->ps->m_iVehicleNum) - {//riding a vehicle, can't use holdable items, this button operates as the weapon link/unlink toggle + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && + pm->ps->m_iVehicleNum) { // riding a vehicle, can't use holdable items, this button operates as the weapon link/unlink toggle return; } - if (!pm->ps->stats[STAT_HOLDABLE_ITEM]) - { + if (!pm->ps->stats[STAT_HOLDABLE_ITEM]) { return; } - if (!PM_ItemUsable(pm->ps, 0)) - { + if (!PM_ItemUsable(pm->ps, 0)) { pm->ps->pm_flags |= PMF_USE_ITEM_HELD; return; - } - else - { - if (pm->ps->stats[STAT_HOLDABLE_ITEMS] & (1 << bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag)) - { + } else { + if (pm->ps->stats[STAT_HOLDABLE_ITEMS] & (1 << bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag)) { if (bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_BINOCULARS && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_JETPACK && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_HEALTHDISP && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_AMMODISP && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_CLOAK && - bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_EWEB) - { //never use up the binoculars or jetpack or dispensers or cloak or ... + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != + HI_EWEB) { // never use up the binoculars or jetpack or dispensers or cloak or ... pm->ps->stats[STAT_HOLDABLE_ITEMS] -= (1 << bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag); } - } - else - { - return; //this should not happen... + } else { + return; // this should not happen... } pm->ps->pm_flags |= PMF_USE_ITEM_HELD; - PM_AddEvent( EV_USE_ITEM0 + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag ); + PM_AddEvent(EV_USE_ITEM0 + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag); if (bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_BINOCULARS && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_JETPACK && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_HEALTHDISP && - bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_AMMODISP && - bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_CLOAK && - bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_EWEB) - { + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_AMMODISP && bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_CLOAK && + bg_itemlist[pm->ps->stats[STAT_HOLDABLE_ITEM]].giTag != HI_EWEB) { pm->ps->stats[STAT_HOLDABLE_ITEM] = 0; BG_CycleInven(pm->ps, 1); } @@ -7136,41 +5920,35 @@ static void PM_Weapon( void ) } */ - if (killAfterItem) - { + if (killAfterItem) { return; } // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; } - if (pm->ps->isJediMaster && pm->ps->emplacedIndex) - { + if (pm->ps->isJediMaster && pm->ps->emplacedIndex) { pm->ps->emplacedIndex = 0; pm->ps->saberHolstered = 0; } - if (pm->ps->duelInProgress && pm->ps->emplacedIndex) - { + if (pm->ps->duelInProgress && pm->ps->emplacedIndex) { pm->ps->emplacedIndex = 0; pm->ps->saberHolstered = 0; } - if (pm->ps->weapon == WP_EMPLACED_GUN && pm->ps->emplacedIndex) - { - pm->cmd.weapon = WP_EMPLACED_GUN; //No switch for you! - PM_StartTorsoAnim( BOTH_GUNSIT1 ); + if (pm->ps->weapon == WP_EMPLACED_GUN && pm->ps->emplacedIndex) { + pm->cmd.weapon = WP_EMPLACED_GUN; // No switch for you! + PM_StartTorsoAnim(BOTH_GUNSIT1); } - if (pm->ps->isJediMaster || pm->ps->duelInProgress || pm->ps->trueJedi) - { + if (pm->ps->isJediMaster || pm->ps->duelInProgress || pm->ps->trueJedi) { pm->cmd.weapon = WP_SABER; pm->ps->weapon = WP_SABER; - if (pm->ps->isJediMaster || pm->ps->trueJedi) - { + if (pm->ps->isJediMaster || pm->ps->trueJedi) { pm->ps->stats[STAT_WEAPONS] = (1 << WP_SABER); } } @@ -7178,32 +5956,25 @@ static void PM_Weapon( void ) amount = weaponData[pm->ps->weapon].energyPerShot; // take an ammo away if not infinite - if ( pm->ps->weapon != WP_NONE && - pm->ps->weapon == pm->cmd.weapon && - (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) ) - { - if ( pm->ps->clientNum < MAX_CLIENTS && pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->weapon != WP_NONE && pm->ps->weapon == pm->cmd.weapon && (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING)) { + if (pm->ps->clientNum < MAX_CLIENTS && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { // enough energy to fire this weapon? if (pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < weaponData[pm->ps->weapon].energyPerShot && - pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < weaponData[pm->ps->weapon].altEnergyPerShot) - { //the weapon is out of ammo essentially because it cannot fire primary or secondary, so do the switch - //regardless of if the player is attacking or not - PM_AddEventWithParm( EV_NOAMMO, WP_NUM_WEAPONS+pm->ps->weapon ); + pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < + weaponData[pm->ps->weapon].altEnergyPerShot) { // the weapon is out of ammo essentially because it cannot fire primary or secondary, so do + // the switch regardless of if the player is attacking or not + PM_AddEventWithParm(EV_NOAMMO, WP_NUM_WEAPONS + pm->ps->weapon); - if (pm->ps->weaponTime < 500) - { + if (pm->ps->weaponTime < 500) { pm->ps->weaponTime += 500; } return; } - if (pm->ps->weapon == WP_DET_PACK && !pm->ps->hasDetPackPlanted && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < 1) - { - PM_AddEventWithParm( EV_NOAMMO, WP_NUM_WEAPONS+pm->ps->weapon ); + if (pm->ps->weapon == WP_DET_PACK && !pm->ps->hasDetPackPlanted && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] < 1) { + PM_AddEventWithParm(EV_NOAMMO, WP_NUM_WEAPONS + pm->ps->weapon); - if (pm->ps->weaponTime < 500) - { + if (pm->ps->weaponTime < 500) { pm->ps->weaponTime += 500; } return; @@ -7214,70 +5985,52 @@ static void PM_Weapon( void ) // check for weapon change // can't change if weapon is firing, but can change // again if lowering or raising - if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) { - if ( pm->ps->weapon != pm->cmd.weapon ) { - PM_BeginWeaponChange( pm->cmd.weapon ); + if (pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } } - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { return; } - if (pm->ps->weapon == WP_DISRUPTOR && - pm->ps->zoomMode == 1) - { - if (pm_cancelOutZoom) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + if (pm_cancelOutZoom) { pm->ps->zoomMode = 0; pm->ps->zoomFov = 0; pm->ps->zoomLocked = qfalse; pm->ps->zoomLockTime = 0; - PM_AddEvent( EV_DISRUPTOR_ZOOMSOUND ); + PM_AddEvent(EV_DISRUPTOR_ZOOMSOUND); return; } - if (pm->cmd.forwardmove || - pm->cmd.rightmove || - pm->cmd.upmove > 0) - { + if (pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove > 0) { return; } } // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } - if ( pm->ps->weaponstate == WEAPON_RAISING ) { + if (pm->ps->weaponstate == WEAPON_RAISING) { pm->ps->weaponstate = WEAPON_READY; - if (PM_CanSetWeaponAnims()) - { - if ( pm->ps->weapon == WP_SABER ) - { - PM_StartTorsoAnim( PM_GetSaberStance() ); - } - else if (pm->ps->weapon == WP_MELEE || PM_IsRocketTrooper()) - { - PM_StartTorsoAnim( pm->ps->legsAnim ); - } - else - { - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { - PM_StartTorsoAnim( TORSO_WEAPONREADY4 ); - } - else - { - if (pm->ps->weapon == WP_EMPLACED_GUN) - { - PM_StartTorsoAnim( BOTH_GUNSIT1 ); - } - else - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); + if (PM_CanSetWeaponAnims()) { + if (pm->ps->weapon == WP_SABER) { + PM_StartTorsoAnim(PM_GetSaberStance()); + } else if (pm->ps->weapon == WP_MELEE || PM_IsRocketTrooper()) { + PM_StartTorsoAnim(pm->ps->legsAnim); + } else { + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + PM_StartTorsoAnim(TORSO_WEAPONREADY4); + } else { + if (pm->ps->weapon == WP_EMPLACED_GUN) { + PM_StartTorsoAnim(BOTH_GUNSIT1); + } else { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); } } } @@ -7285,100 +6038,59 @@ static void PM_Weapon( void ) return; } - if (PM_CanSetWeaponAnims() && - !PM_IsRocketTrooper() && - pm->ps->weaponstate == WEAPON_READY && pm->ps->weaponTime <= 0 && - (pm->ps->weapon >= WP_BRYAR_PISTOL || pm->ps->weapon == WP_STUN_BATON) && - pm->ps->torsoTimer <= 0 && - (pm->ps->torsoAnim) != WeaponReadyAnim[pm->ps->weapon] && - pm->ps->torsoAnim != TORSO_WEAPONIDLE3 && - pm->ps->weapon != WP_EMPLACED_GUN) - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); - } - else if (PM_CanSetWeaponAnims() && - pm->ps->weapon == WP_MELEE) - { - if (pm->ps->weaponTime <= 0 && - pm->ps->forceHandExtend == HANDEXTEND_NONE) - { + if (PM_CanSetWeaponAnims() && !PM_IsRocketTrooper() && pm->ps->weaponstate == WEAPON_READY && pm->ps->weaponTime <= 0 && + (pm->ps->weapon >= WP_BRYAR_PISTOL || pm->ps->weapon == WP_STUN_BATON) && pm->ps->torsoTimer <= 0 && + (pm->ps->torsoAnim) != WeaponReadyAnim[pm->ps->weapon] && pm->ps->torsoAnim != TORSO_WEAPONIDLE3 && pm->ps->weapon != WP_EMPLACED_GUN) { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); + } else if (PM_CanSetWeaponAnims() && pm->ps->weapon == WP_MELEE) { + if (pm->ps->weaponTime <= 0 && pm->ps->forceHandExtend == HANDEXTEND_NONE) { int desTAnim = pm->ps->legsAnim; - if (desTAnim == BOTH_STAND1 || - desTAnim == BOTH_STAND2) - { //remap the standard standing anims for melee stance + if (desTAnim == BOTH_STAND1 || desTAnim == BOTH_STAND2) { // remap the standard standing anims for melee stance desTAnim = BOTH_STAND6; } - if (!(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK))) - { //don't do this while holding attack - if (pm->ps->torsoAnim != desTAnim) - { - PM_StartTorsoAnim( desTAnim ); + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // don't do this while holding attack + if (pm->ps->torsoAnim != desTAnim) { + PM_StartTorsoAnim(desTAnim); } } } - } - else if (PM_CanSetWeaponAnims() && PM_IsRocketTrooper()) - { + } else if (PM_CanSetWeaponAnims() && PM_IsRocketTrooper()) { int desTAnim = pm->ps->legsAnim; - if (!(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK))) - { //don't do this while holding attack - if (pm->ps->torsoAnim != desTAnim) - { - PM_StartTorsoAnim( desTAnim ); + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // don't do this while holding attack + if (pm->ps->torsoAnim != desTAnim) { + PM_StartTorsoAnim(desTAnim); } } } - if (((pm->ps->torsoAnim) == TORSO_WEAPONREADY4 || - (pm->ps->torsoAnim) == BOTH_ATTACK4) && - (pm->ps->weapon != WP_DISRUPTOR || pm->ps->zoomMode != 1)) - { - if (pm->ps->weapon == WP_EMPLACED_GUN) - { - PM_StartTorsoAnim( BOTH_GUNSIT1 ); - } - else if (PM_CanSetWeaponAnims()) - { - PM_StartTorsoAnim( WeaponReadyAnim[pm->ps->weapon] ); + if (((pm->ps->torsoAnim) == TORSO_WEAPONREADY4 || (pm->ps->torsoAnim) == BOTH_ATTACK4) && (pm->ps->weapon != WP_DISRUPTOR || pm->ps->zoomMode != 1)) { + if (pm->ps->weapon == WP_EMPLACED_GUN) { + PM_StartTorsoAnim(BOTH_GUNSIT1); + } else if (PM_CanSetWeaponAnims()) { + PM_StartTorsoAnim(WeaponReadyAnim[pm->ps->weapon]); } - } - else if (((pm->ps->torsoAnim) != TORSO_WEAPONREADY4 && - (pm->ps->torsoAnim) != BOTH_ATTACK4) && - PM_CanSetWeaponAnims() && - (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1)) - { - PM_StartTorsoAnim( TORSO_WEAPONREADY4 ); + } else if (((pm->ps->torsoAnim) != TORSO_WEAPONREADY4 && (pm->ps->torsoAnim) != BOTH_ATTACK4) && PM_CanSetWeaponAnims() && + (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1)) { + PM_StartTorsoAnim(TORSO_WEAPONREADY4); } - if (pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_VEHICLE) - {//we are a vehicle + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_VEHICLE) { // we are a vehicle veh = pm_entSelf; } - if ( veh - && veh->m_pVehicle ) - { - if ( g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming - || g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming ) - {//don't clear the rocket locking ever? + if (veh && veh->m_pVehicle) { + if (g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID].fHoming || + g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID].fHoming) { // don't clear the rocket locking ever? vehicleRocketLock = qtrue; } } - if ( !vehicleRocketLock ) - { - if (pm->ps->weapon != WP_ROCKET_LAUNCHER) - { - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pm->ps->m_iVehicleNum) - {//riding a vehicle, the vehicle will tell me my rocketlock stuff... - } - else - { + if (!vehicleRocketLock) { + if (pm->ps->weapon != WP_ROCKET_LAUNCHER) { + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->m_iVehicleNum) { // riding a vehicle, the vehicle will tell me my rocketlock stuff... + } else { pm->ps->rocketLockIndex = ENTITYNUM_NONE; pm->ps->rocketLockTime = 0; pm->ps->rocketTargetTime = 0; @@ -7386,46 +6098,34 @@ static void PM_Weapon( void ) } } - if ( PM_DoChargedWeapons(vehicleRocketLock, veh)) - { + if (PM_DoChargedWeapons(vehicleRocketLock, veh)) { // In some cases the charged weapon code may want us to short circuit the rest of the firing code return; } // check for fire - if ( ! (pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK))) - { + if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { pm->ps->weaponTime = 0; pm->ps->weaponstate = WEAPON_READY; return; } - if (pm->ps->weapon == WP_EMPLACED_GUN) - { + if (pm->ps->weapon == WP_EMPLACED_GUN) { addTime = weaponData[pm->ps->weapon].fireTime; pm->ps->weaponTime += addTime; - if ( (pm->cmd.buttons & BUTTON_ALT_ATTACK) ) - { - PM_AddEvent( EV_ALT_FIRE ); - } - else - { - PM_AddEvent( EV_FIRE_WEAPON ); + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK)) { + PM_AddEvent(EV_ALT_FIRE); + } else { + PM_AddEvent(EV_FIRE_WEAPON); } return; - } - else if (pm->ps->m_iVehicleNum - && pm_entSelf->s.NPC_class==CLASS_VEHICLE) - { //a vehicle NPC that has a pilot + } else if (pm->ps->m_iVehicleNum && pm_entSelf->s.NPC_class == CLASS_VEHICLE) { // a vehicle NPC that has a pilot pm->ps->weaponstate = WEAPON_FIRING; pm->ps->weaponTime += 100; -#ifdef _GAME //hack, only do it game-side. vehicle weapons don't really need predicting I suppose. - if ( (pm->cmd.buttons & BUTTON_ALT_ATTACK) ) - { +#ifdef _GAME // hack, only do it game-side. vehicle weapons don't really need predicting I suppose. + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK)) { G_CheapWeaponFire(pm->ps->clientNum, EV_ALT_FIRE); - } - else - { + } else { G_CheapWeaponFire(pm->ps->clientNum, EV_FIRE_WEAPON); } #endif @@ -7444,34 +6144,22 @@ static void PM_Weapon( void ) return; } - if (pm->ps->weapon == WP_DISRUPTOR && - (pm->cmd.buttons & BUTTON_ALT_ATTACK) && - !pm->ps->zoomLocked) - { + if (pm->ps->weapon == WP_DISRUPTOR && (pm->cmd.buttons & BUTTON_ALT_ATTACK) && !pm->ps->zoomLocked) { return; } - if (pm->ps->weapon == WP_DISRUPTOR && - (pm->cmd.buttons & BUTTON_ALT_ATTACK) && - pm->ps->zoomMode == 2) - { //can't use disruptor secondary while zoomed binoculars + if (pm->ps->weapon == WP_DISRUPTOR && (pm->cmd.buttons & BUTTON_ALT_ATTACK) && + pm->ps->zoomMode == 2) { // can't use disruptor secondary while zoomed binoculars return; } - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { - PM_StartTorsoAnim( BOTH_ATTACK4 ); - } - else if (pm->ps->weapon == WP_MELEE) - { //special anims for standard melee attacks - //Alternate between punches and use the anim length as weapon time. - if (!pm->ps->m_iVehicleNum) - { //if riding a vehicle don't do this stuff at all - if (pm->debugMelee && - (pm->cmd.buttons & BUTTON_ATTACK) && - (pm->cmd.buttons & BUTTON_ALT_ATTACK)) - { //ok, grapple time -#if 0 //eh, I want to try turning the saber off, but can't do that reliably for prediction.. + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + PM_StartTorsoAnim(BOTH_ATTACK4); + } else if (pm->ps->weapon == WP_MELEE) { // special anims for standard melee attacks + // Alternate between punches and use the anim length as weapon time. + if (!pm->ps->m_iVehicleNum) { // if riding a vehicle don't do this stuff at all + if (pm->debugMelee && (pm->cmd.buttons & BUTTON_ATTACK) && (pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // ok, grapple time +#if 0 // eh, I want to try turning the saber off, but can't do that reliably for prediction.. qboolean icandoit = qtrue; if (pm->ps->weaponTime > 0) { //weapon busy @@ -7502,46 +6190,33 @@ static void PM_Weapon( void ) } } #else - #ifdef _GAME - if (pm_entSelf) - { - if (TryGrapple((gentity_t *)pm_entSelf)) - { +#ifdef _GAME + if (pm_entSelf) { + if (TryGrapple((gentity_t *)pm_entSelf)) { return; } } - #else +#else return; - #endif #endif - } - else if (pm->debugMelee && - (pm->cmd.buttons & BUTTON_ALT_ATTACK)) - { //kicks - if (!BG_KickingAnim(pm->ps->torsoAnim) && - !BG_KickingAnim(pm->ps->legsAnim)) - { +#endif + } else if (pm->debugMelee && (pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // kicks + if (!BG_KickingAnim(pm->ps->torsoAnim) && !BG_KickingAnim(pm->ps->legsAnim)) { int kickMove = PM_KickMoveForConditions(); - if (kickMove == LS_HILT_BASH) - { //yeah.. no hilt to bash with! + if (kickMove == LS_HILT_BASH) { // yeah.. no hilt to bash with! kickMove = LS_KICK_F; } - if (kickMove != -1) - { - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//if in air, convert kick to an in-air kick + if (kickMove != -1) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // if in air, convert kick to an in-air kick float gDist = PM_GroundDistance(); - //let's only allow air kicks if a certain distance from the ground - //it's silly to be able to do them right as you land. - //also looks wrong to transition from a non-complete flip anim... - if ((!BG_FlippingAnim( pm->ps->legsAnim ) || pm->ps->legsTimer <= 0) && - gDist > 64.0f && //strict minimum - gDist > (-pm->ps->velocity[2])-64.0f //make sure we are high to ground relative to downward velocity as well - ) - { - switch ( kickMove ) - { + // let's only allow air kicks if a certain distance from the ground + // it's silly to be able to do them right as you land. + // also looks wrong to transition from a non-complete flip anim... + if ((!BG_FlippingAnim(pm->ps->legsAnim) || pm->ps->legsTimer <= 0) && gDist > 64.0f && // strict minimum + gDist > (-pm->ps->velocity[2]) - 64.0f // make sure we are high to ground relative to downward velocity as well + ) { + switch (kickMove) { case LS_KICK_F: kickMove = LS_KICK_F_AIR; break; @@ -7554,27 +6229,22 @@ static void PM_Weapon( void ) case LS_KICK_L: kickMove = LS_KICK_L_AIR; break; - default: //oh well, can't do any other kick move while in-air + default: // oh well, can't do any other kick move while in-air kickMove = -1; break; } - } - else - { //off ground, but too close to ground + } else { // off ground, but too close to ground kickMove = -1; } } } - if (kickMove != -1) - { + if (kickMove != -1) { int kickAnim = saberMoveData[kickMove].animToUse; - if (kickAnim != -1) - { - PM_SetAnim(SETANIM_BOTH, kickAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); - if (pm->ps->legsAnim == kickAnim) - { + if (kickAnim != -1) { + PM_SetAnim(SETANIM_BOTH, kickAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + if (pm->ps->legsAnim == kickAnim) { pm->ps->weaponTime = pm->ps->legsTimer; return; } @@ -7582,62 +6252,47 @@ static void PM_Weapon( void ) } } - //if got here then no move to do so put torso into leg idle or whatever - if (pm->ps->torsoAnim != pm->ps->legsAnim) - { - PM_SetAnim(SETANIM_BOTH, pm->ps->legsAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + // if got here then no move to do so put torso into leg idle or whatever + if (pm->ps->torsoAnim != pm->ps->legsAnim) { + PM_SetAnim(SETANIM_BOTH, pm->ps->legsAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } pm->ps->weaponTime = 0; return; - } - else - { //just punch + } else { // just punch int desTAnim = BOTH_MELEE1; - if (pm->ps->torsoAnim == BOTH_MELEE1) - { + if (pm->ps->torsoAnim == BOTH_MELEE1) { desTAnim = BOTH_MELEE2; } - PM_StartTorsoAnim( desTAnim ); + PM_StartTorsoAnim(desTAnim); - if (pm->ps->torsoAnim == desTAnim) - { + if (pm->ps->torsoAnim == desTAnim) { pm->ps->weaponTime = pm->ps->torsoTimer; } } } - } - else - { - PM_StartTorsoAnim( WeaponAttackAnim[pm->ps->weapon] ); + } else { + PM_StartTorsoAnim(WeaponAttackAnim[pm->ps->weapon]); } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { amount = weaponData[pm->ps->weapon].altEnergyPerShot; - } - else - { + } else { amount = weaponData[pm->ps->weapon].energyPerShot; } pm->ps->weaponstate = WEAPON_FIRING; // take an ammo away if not infinite - if ( pm->ps->clientNum < MAX_CLIENTS && pm->ps->ammo[ weaponData[pm->ps->weapon].ammoIndex ] != -1 ) - { + if (pm->ps->clientNum < MAX_CLIENTS && pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] != -1) { // enough energy to fire this weapon? - if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) - { + if ((pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] - amount) >= 0) { pm->ps->ammo[weaponData[pm->ps->weapon].ammoIndex] -= amount; - } - else // Not enough energy + } else // Not enough energy { // Switch weapons - if (pm->ps->weapon != WP_DET_PACK || !pm->ps->hasDetPackPlanted) - { - PM_AddEventWithParm( EV_NOAMMO, WP_NUM_WEAPONS+pm->ps->weapon ); - if (pm->ps->weaponTime < 500) - { + if (pm->ps->weapon != WP_DET_PACK || !pm->ps->hasDetPackPlanted) { + PM_AddEventWithParm(EV_NOAMMO, WP_NUM_WEAPONS + pm->ps->weapon); + if (pm->ps->weaponTime < 500) { pm->ps->weaponTime += 500; } } @@ -7645,37 +6300,26 @@ static void PM_Weapon( void ) } } - if ( pm->cmd.buttons & BUTTON_ALT_ATTACK ) { - //if ( pm->ps->weapon == WP_BRYAR_PISTOL && pm->gametype != GT_SIEGE ) - if (0) - { //kind of a hack for now - PM_AddEvent( EV_FIRE_WEAPON ); + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { + // if ( pm->ps->weapon == WP_BRYAR_PISTOL && pm->gametype != GT_SIEGE ) + if (0) { // kind of a hack for now + PM_AddEvent(EV_FIRE_WEAPON); addTime = weaponData[pm->ps->weapon].fireTime; - } - else if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode != 1) - { - PM_AddEvent( EV_FIRE_WEAPON ); + } else if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode != 1) { + PM_AddEvent(EV_FIRE_WEAPON); addTime = weaponData[pm->ps->weapon].fireTime; - } - else - { - if (pm->ps->weapon != WP_MELEE || - !pm->ps->m_iVehicleNum) - { //do not fire melee events at all when on vehicle - PM_AddEvent( EV_ALT_FIRE ); + } else { + if (pm->ps->weapon != WP_MELEE || !pm->ps->m_iVehicleNum) { // do not fire melee events at all when on vehicle + PM_AddEvent(EV_ALT_FIRE); } addTime = weaponData[pm->ps->weapon].altFireTime; } - } - else { - if (pm->ps->weapon != WP_MELEE || - !pm->ps->m_iVehicleNum) - { //do not fire melee events at all when on vehicle - PM_AddEvent( EV_FIRE_WEAPON ); + } else { + if (pm->ps->weapon != WP_MELEE || !pm->ps->m_iVehicleNum) { // do not fire melee events at all when on vehicle + PM_AddEvent(EV_FIRE_WEAPON); } addTime = weaponData[pm->ps->weapon].fireTime; - if ( pm->gametype == GT_SIEGE && pm->ps->weapon == WP_DET_PACK ) - { // were far too spammy before? So says Rick. + if (pm->gametype == GT_SIEGE && pm->ps->weapon == WP_DET_PACK) { // were far too spammy before? So says Rick. addTime *= 2; } } @@ -7686,12 +6330,9 @@ static void PM_Weapon( void ) } */ - if (pm->ps->fd.forcePowersActive & (1 << FP_RAGE)) - { + if (pm->ps->fd.forcePowersActive & (1 << FP_RAGE)) { addTime *= 0.75; - } - else if (pm->ps->fd.forceRageRecoveryTime > pm->cmd.serverTime) - { + } else if (pm->ps->fd.forceRageRecoveryTime > pm->cmd.serverTime) { addTime *= 1.5; } @@ -7704,29 +6345,27 @@ PM_Animate ================ */ -static void PM_Animate( void ) { - if ( pm->cmd.buttons & BUTTON_GESTURE ) { - if (pm->ps->m_iVehicleNum) - { //eh, fine, clear it - if (pm->ps->forceHandExtendTime < pm->cmd.serverTime) - { +static void PM_Animate(void) { + if (pm->cmd.buttons & BUTTON_GESTURE) { + if (pm->ps->m_iVehicleNum) { // eh, fine, clear it + if (pm->ps->forceHandExtendTime < pm->cmd.serverTime) { pm->ps->forceHandExtend = HANDEXTEND_NONE; } } - if ( pm->ps->torsoTimer < 1 && pm->ps->forceHandExtend == HANDEXTEND_NONE && - pm->ps->legsTimer < 1 && pm->ps->weaponTime < 1 && pm->ps->saberLockTime < pm->cmd.serverTime) { + if (pm->ps->torsoTimer < 1 && pm->ps->forceHandExtend == HANDEXTEND_NONE && pm->ps->legsTimer < 1 && pm->ps->weaponTime < 1 && + pm->ps->saberLockTime < pm->cmd.serverTime) { pm->ps->forceHandExtend = HANDEXTEND_TAUNT; - //FIXME: random taunt anims? + // FIXME: random taunt anims? pm->ps->forceDodgeAnim = BOTH_ENGAGETAUNT; pm->ps->forceHandExtendTime = pm->cmd.serverTime + 1000; - //pm->ps->weaponTime = 100; + // pm->ps->weaponTime = 100; - PM_AddEvent( EV_TAUNT ); + PM_AddEvent(EV_TAUNT); } #if 0 // Here's an interesting bit. The bots in TA used buttons to do additional gestures. @@ -7766,16 +6405,15 @@ static void PM_Animate( void ) { } } - /* ================ PM_DropTimers ================ */ -static void PM_DropTimers( void ) { +static void PM_DropTimers(void) { // drop misc timing counter - if ( pm->ps->pm_time ) { - if ( pml.msec >= pm->ps->pm_time ) { + if (pm->ps->pm_time) { + if (pml.msec >= pm->ps->pm_time) { pm->ps->pm_flags &= ~PMF_ALL_TIMES; pm->ps->pm_time = 0; } else { @@ -7784,16 +6422,16 @@ static void PM_DropTimers( void ) { } // drop animation counter - if ( pm->ps->legsTimer > 0 ) { + if (pm->ps->legsTimer > 0) { pm->ps->legsTimer -= pml.msec; - if ( pm->ps->legsTimer < 0 ) { + if (pm->ps->legsTimer < 0) { pm->ps->legsTimer = 0; } } - if ( pm->ps->torsoTimer > 0 ) { + if (pm->ps->torsoTimer > 0) { pm->ps->torsoTimer -= pml.msec; - if ( pm->ps->torsoTimer < 0 ) { + if (pm->ps->torsoTimer < 0) { pm->ps->torsoTimer = 0; } } @@ -7804,24 +6442,21 @@ static void PM_DropTimers( void ) { // which includes files that are also compiled in SP. We do need to make // sure we only get one copy in the linker, though. -extern vmCvar_t bg_fighterAltControl; -qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ) -{ - if ( bg_fighterAltControl.integer - && ps->clientNum < MAX_CLIENTS //real client - && ps->m_iVehicleNum//in a vehicle - && pVeh //valid vehicle data pointer - && pVeh->m_pVehicleInfo//valid vehicle info - && pVeh->m_pVehicleInfo->type == VH_FIGHTER )//fighter - //FIXME: specify per vehicle instead of assuming true for all fighters - //FIXME: map/server setting? - {//can roll and pitch without limitation! +extern vmCvar_t bg_fighterAltControl; +qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh) { + if (bg_fighterAltControl.integer && ps->clientNum < MAX_CLIENTS // real client + && ps->m_iVehicleNum // in a vehicle + && pVeh // valid vehicle data pointer + && pVeh->m_pVehicleInfo // valid vehicle info + && pVeh->m_pVehicleInfo->type == VH_FIGHTER) // fighter + // FIXME: specify per vehicle instead of assuming true for all fighters + // FIXME: map/server setting? + { // can roll and pitch without limitation! return qtrue; } return qfalse; } - /* ================ PM_UpdateViewAngles @@ -7830,62 +6465,49 @@ This can be used as another entry point when only the viewangles are being updated isntead of a full move ================ */ -void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd ) { - short temp; - int i; +void PM_UpdateViewAngles(playerState_t *ps, const usercmd_t *cmd) { + short temp; + int i; - if ( ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPINTERMISSION) { - return; // no view changes at all + if (ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPINTERMISSION) { + return; // no view changes at all } - if ( ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0 ) { - return; // no view changes at all + if (ps->pm_type != PM_SPECTATOR && ps->stats[STAT_HEALTH] <= 0) { + return; // no view changes at all } // circularly clamp the angles with deltas - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { temp = cmd->angles[i] + ps->delta_angles[i]; #ifdef VEH_CONTROL_SCHEME_4 - if ( pm_entVeh - && pm_entVeh->m_pVehicle - && pm_entVeh->m_pVehicle->m_pVehicleInfo - && pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER - && (cmd->serverTime-pm_entVeh->playerState->hyperSpaceTime) >= HYPERSPACE_TIME ) - {//in a vehicle and not hyperspacing - if ( i == PITCH ) - { - int pitchClamp = ANGLE2SHORT(AngleNormalize180(pm_entVeh->m_pVehicle->m_vPrevRiderViewAngles[PITCH]+10.0f)); + if (pm_entVeh && pm_entVeh->m_pVehicle && pm_entVeh->m_pVehicle->m_pVehicleInfo && pm_entVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && + (cmd->serverTime - pm_entVeh->playerState->hyperSpaceTime) >= HYPERSPACE_TIME) { // in a vehicle and not hyperspacing + if (i == PITCH) { + int pitchClamp = ANGLE2SHORT(AngleNormalize180(pm_entVeh->m_pVehicle->m_vPrevRiderViewAngles[PITCH] + 10.0f)); // don't let the player look up or down more than 22.5 degrees - if ( temp > pitchClamp ) - { + if (temp > pitchClamp) { ps->delta_angles[i] = pitchClamp - cmd->angles[i]; temp = pitchClamp; - } - else if ( temp < -pitchClamp ) - { + } else if (temp < -pitchClamp) { ps->delta_angles[i] = -pitchClamp - cmd->angles[i]; temp = -pitchClamp; } } - if ( i == YAW ) - { - int yawClamp = ANGLE2SHORT(AngleNormalize180(pm_entVeh->m_pVehicle->m_vPrevRiderViewAngles[YAW]+10.0f)); + if (i == YAW) { + int yawClamp = ANGLE2SHORT(AngleNormalize180(pm_entVeh->m_pVehicle->m_vPrevRiderViewAngles[YAW] + 10.0f)); // don't let the player look left or right more than 22.5 degrees - if ( temp > yawClamp ) - { + if (temp > yawClamp) { ps->delta_angles[i] = yawClamp - cmd->angles[i]; temp = yawClamp; - } - else if ( temp < -yawClamp ) - { + } else if (temp < -yawClamp) { ps->delta_angles[i] = -yawClamp - cmd->angles[i]; temp = -yawClamp; } } } -#else //VEH_CONTROL_SCHEME_4 - if ( pm_entVeh && BG_UnrestrainedPitchRoll( ps, pm_entVeh->m_pVehicle ) ) - {//in a fighter +#else // VEH_CONTROL_SCHEME_4 + if (pm_entVeh && BG_UnrestrainedPitchRoll(ps, pm_entVeh->m_pVehicle)) { // in a fighter /* if ( i == ROLL ) {//get roll from vehicle @@ -7896,14 +6518,13 @@ void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd ) { */ } #endif // VEH_CONTROL_SCHEME_4 - else - { - if ( i == PITCH ) { + else { + if (i == PITCH) { // don't let the player look up or down more than 90 degrees - if ( temp > 16000 ) { + if (temp > 16000) { ps->delta_angles[i] = 16000 - cmd->angles[i]; temp = 16000; - } else if ( temp < -16000 ) { + } else if (temp < -16000) { ps->delta_angles[i] = -16000 - cmd->angles[i]; temp = -16000; } @@ -8048,51 +6669,42 @@ void PM_UpdateViewAngles( playerState_t *ps, const usercmd_t *cmd ) { */ //------------------------------------------- -void PM_AdjustAttackStates( pmove_t *pmove ) +void PM_AdjustAttackStates(pmove_t *pmove) //------------------------------------------- { int amount; - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pmove->ps->m_iVehicleNum) - { //riding a vehicle + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pmove->ps->m_iVehicleNum) { // riding a vehicle bgEntity_t *veh = pm_entVeh; - if ( veh && - (veh->m_pVehicle && (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER)) ) - {//riding a walker/fighter - //not firing, ever - pmove->ps->eFlags &= ~(EF_FIRING|EF_ALT_FIRING); + if (veh && (veh->m_pVehicle && + (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER))) { // riding a walker/fighter + // not firing, ever + pmove->ps->eFlags &= ~(EF_FIRING | EF_ALT_FIRING); return; } } // get ammo usage - if ( pmove->cmd.buttons & BUTTON_ALT_ATTACK ) - { - amount = pmove->ps->ammo[weaponData[ pmove->ps->weapon ].ammoIndex] - weaponData[pmove->ps->weapon].altEnergyPerShot; - } - else - { - amount = pmove->ps->ammo[weaponData[ pmove->ps->weapon ].ammoIndex] - weaponData[pmove->ps->weapon].energyPerShot; + if (pmove->cmd.buttons & BUTTON_ALT_ATTACK) { + amount = pmove->ps->ammo[weaponData[pmove->ps->weapon].ammoIndex] - weaponData[pmove->ps->weapon].altEnergyPerShot; + } else { + amount = pmove->ps->ammo[weaponData[pmove->ps->weapon].ammoIndex] - weaponData[pmove->ps->weapon].energyPerShot; } // disruptor alt-fire should toggle the zoom mode, but only bother doing this for the player? - if ( pmove->ps->weapon == WP_DISRUPTOR && pmove->ps->weaponstate == WEAPON_READY ) - { + if (pmove->ps->weapon == WP_DISRUPTOR && pmove->ps->weaponstate == WEAPON_READY) { if ( !(pmove->ps->eFlags & EF_ALT_FIRING) && (pmove->cmd.buttons & BUTTON_ALT_ATTACK) /*&& pmove->cmd.upmove <= 0 && !pmove->cmd.forwardmove && !pmove->cmd.rightmove*/) { // We just pressed the alt-fire key - if ( !pmove->ps->zoomMode && pmove->ps->pm_type != PM_DEAD ) - { + if (!pmove->ps->zoomMode && pmove->ps->pm_type != PM_DEAD) { // not already zooming, so do it now pmove->ps->zoomMode = 1; pmove->ps->zoomLocked = qfalse; - pmove->ps->zoomFov = 80.0f;//cg_fov.value; + pmove->ps->zoomFov = 80.0f; // cg_fov.value; pmove->ps->zoomLockTime = pmove->cmd.serverTime + 50; PM_AddEvent(EV_DISRUPTOR_ZOOMSOUND); - } - else if (pmove->ps->zoomMode == 1 && pmove->ps->zoomLockTime < pmove->cmd.serverTime) - { //check for == 1 so we can't turn binoculars off with disruptor alt fire + } else if (pmove->ps->zoomMode == 1 && + pmove->ps->zoomLockTime < pmove->cmd.serverTime) { // check for == 1 so we can't turn binoculars off with disruptor alt fire // already zooming, so must be wanting to turn it off pmove->ps->zoomMode = 0; pmove->ps->zoomTime = pmove->ps->commandTime; @@ -8100,21 +6712,16 @@ void PM_AdjustAttackStates( pmove_t *pmove ) PM_AddEvent(EV_DISRUPTOR_ZOOMSOUND); pmove->ps->weaponTime = 1000; } - } - else if ( !(pmove->cmd.buttons & BUTTON_ALT_ATTACK ) && pmove->ps->zoomLockTime < pmove->cmd.serverTime) - { + } else if (!(pmove->cmd.buttons & BUTTON_ALT_ATTACK) && pmove->ps->zoomLockTime < pmove->cmd.serverTime) { // Not pressing zoom any more - if ( pmove->ps->zoomMode ) - { - if (pmove->ps->zoomMode == 1 && !pmove->ps->zoomLocked) - { //approximate what level the client should be zoomed at based on how long zoom was held - pmove->ps->zoomFov = ((pmove->cmd.serverTime+50) - pmove->ps->zoomLockTime) * 0.035f; - if (pmove->ps->zoomFov > 50) - { + if (pmove->ps->zoomMode) { + if (pmove->ps->zoomMode == 1 && + !pmove->ps->zoomLocked) { // approximate what level the client should be zoomed at based on how long zoom was held + pmove->ps->zoomFov = ((pmove->cmd.serverTime + 50) - pmove->ps->zoomLockTime) * 0.035f; + if (pmove->ps->zoomFov > 50) { pmove->ps->zoomFov = 50; } - if (pmove->ps->zoomFov < 1) - { + if (pmove->ps->zoomFov < 1) { pmove->ps->zoomFov = 1; } } @@ -8122,7 +6729,7 @@ void PM_AdjustAttackStates( pmove_t *pmove ) pmove->ps->zoomLocked = qtrue; } } - //This seemed like a good idea, but apparently it confuses people. So disabled for now. + // This seemed like a good idea, but apparently it confuses people. So disabled for now. /* else if (!(pmove->ps->eFlags & EF_ALT_FIRING) && (pmove->cmd.buttons & BUTTON_ALT_ATTACK) && (pmove->cmd.upmove > 0 || pmove->cmd.forwardmove || pmove->cmd.rightmove)) @@ -8145,18 +6752,13 @@ void PM_AdjustAttackStates( pmove_t *pmove ) } */ - if ( pmove->cmd.buttons & BUTTON_ATTACK ) - { + if (pmove->cmd.buttons & BUTTON_ATTACK) { // If we are zoomed, we should switch the ammo usage to the alt-fire, otherwise, we'll // just use whatever ammo was selected from above - if ( pmove->ps->zoomMode ) - { - amount = pmove->ps->ammo[weaponData[ pmove->ps->weapon ].ammoIndex] - - weaponData[pmove->ps->weapon].altEnergyPerShot; + if (pmove->ps->zoomMode) { + amount = pmove->ps->ammo[weaponData[pmove->ps->weapon].ammoIndex] - weaponData[pmove->ps->weapon].altEnergyPerShot; } - } - else - { + } else { // alt-fire button pressing doesn't use any ammo amount = 0; } @@ -8178,51 +6780,36 @@ void PM_AdjustAttackStates( pmove_t *pmove ) */ // set the firing flag for continuous beam weapons, saber will fire even if out of ammo - if ( !(pmove->ps->pm_flags & PMF_RESPAWNED) && - pmove->ps->pm_type != PM_INTERMISSION && - pmove->ps->pm_type != PM_NOCLIP && - ( pmove->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) && - ( amount >= 0 || pmove->ps->weapon == WP_SABER )) - { - if ( pmove->cmd.buttons & BUTTON_ALT_ATTACK ) - { + if (!(pmove->ps->pm_flags & PMF_RESPAWNED) && pmove->ps->pm_type != PM_INTERMISSION && pmove->ps->pm_type != PM_NOCLIP && + (pmove->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)) && (amount >= 0 || pmove->ps->weapon == WP_SABER)) { + if (pmove->cmd.buttons & BUTTON_ALT_ATTACK) { pmove->ps->eFlags |= EF_ALT_FIRING; - } - else - { + } else { pmove->ps->eFlags &= ~EF_ALT_FIRING; } // This flag should always get set, even when alt-firing pmove->ps->eFlags |= EF_FIRING; - } - else - { + } else { // Clear 'em out - pmove->ps->eFlags &= ~(EF_FIRING|EF_ALT_FIRING); + pmove->ps->eFlags &= ~(EF_FIRING | EF_ALT_FIRING); } // disruptor should convert a main fire to an alt-fire if the gun is currently zoomed - if ( pmove->ps->weapon == WP_DISRUPTOR) - { - if ( pmove->cmd.buttons & BUTTON_ATTACK && pmove->ps->zoomMode == 1 && pmove->ps->zoomLocked) - { + if (pmove->ps->weapon == WP_DISRUPTOR) { + if (pmove->cmd.buttons & BUTTON_ATTACK && pmove->ps->zoomMode == 1 && pmove->ps->zoomLocked) { // converting the main fire to an alt-fire pmove->cmd.buttons |= BUTTON_ALT_ATTACK; pmove->ps->eFlags |= EF_ALT_FIRING; - } - else if ( pmove->cmd.buttons & BUTTON_ALT_ATTACK && pmove->ps->zoomMode == 1 && pmove->ps->zoomLocked) - { + } else if (pmove->cmd.buttons & BUTTON_ALT_ATTACK && pmove->ps->zoomMode == 1 && pmove->ps->zoomLocked) { pmove->cmd.buttons &= ~BUTTON_ALT_ATTACK; pmove->ps->eFlags &= ~EF_ALT_FIRING; } } } -void BG_CmdForRoll( playerState_t *ps, int anim, usercmd_t *pCmd ) -{ - switch ( (anim) ) - { +void BG_CmdForRoll(playerState_t *ps, int anim, usercmd_t *pCmd) { + switch ((anim)) { case BOTH_ROLL_F: pCmd->forwardmove = 127; pCmd->rightmove = 0; @@ -8242,187 +6829,145 @@ void BG_CmdForRoll( playerState_t *ps, int anim, usercmd_t *pCmd ) case BOTH_GETUP_BROLL_R: pCmd->forwardmove = 0; pCmd->rightmove = 48; - //NOTE: speed is 400 + // NOTE: speed is 400 break; case BOTH_GETUP_FROLL_R: - if ( ps->legsTimer <= 250 ) - {//end of anim + if (ps->legsTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 0; pCmd->rightmove = 48; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_L: pCmd->forwardmove = 0; pCmd->rightmove = -48; - //NOTE: speed is 400 + // NOTE: speed is 400 break; case BOTH_GETUP_FROLL_L: - if ( ps->legsTimer <= 250 ) - {//end of anim + if (ps->legsTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 0; pCmd->rightmove = -48; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_B: - if ( ps->torsoTimer <= 250 ) - {//end of anim + if (ps->torsoTimer <= 250) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( 0, (animNumber_t)ps->legsAnim ) - ps->torsoTimer < 350 ) - {//beginning of anim + } else if (PM_AnimLength(0, (animNumber_t)ps->legsAnim) - ps->torsoTimer < 350) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = -64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_FROLL_B: - if ( ps->torsoTimer <= 100 ) - {//end of anim + if (ps->torsoTimer <= 100) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( 0, (animNumber_t)ps->legsAnim ) - ps->torsoTimer < 200 ) - {//beginning of anim + } else if (PM_AnimLength(0, (animNumber_t)ps->legsAnim) - ps->torsoTimer < 200) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = -64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_BROLL_F: - if ( ps->torsoTimer <= 550 ) - {//end of anim + if (ps->torsoTimer <= 550) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else if ( PM_AnimLength( 0, (animNumber_t)ps->legsAnim ) - ps->torsoTimer < 150 ) - {//beginning of anim + } else if (PM_AnimLength(0, (animNumber_t)ps->legsAnim) - ps->torsoTimer < 150) { // beginning of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { + } else { pCmd->forwardmove = 64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; case BOTH_GETUP_FROLL_F: - if ( ps->torsoTimer <= 100 ) - {//end of anim + if (ps->torsoTimer <= 100) { // end of anim pCmd->forwardmove = pCmd->rightmove = 0; - } - else - { - //FIXME: ramp down over length of anim + } else { + // FIXME: ramp down over length of anim pCmd->forwardmove = 64; pCmd->rightmove = 0; - //NOTE: speed is 400 + // NOTE: speed is 400 } break; } pCmd->upmove = 0; } -qboolean PM_SaberInTransition( int move ); +qboolean PM_SaberInTransition(int move); -void BG_AdjustClientSpeed(playerState_t *ps, usercmd_t *cmd, int svTime) -{ - saberInfo_t *saber; +void BG_AdjustClientSpeed(playerState_t *ps, usercmd_t *cmd, int svTime) { + saberInfo_t *saber; - if (ps->clientNum >= MAX_CLIENTS) - { + if (ps->clientNum >= MAX_CLIENTS) { bgEntity_t *bgEnt = pm_entSelf; - if (bgEnt && bgEnt->s.NPC_class == CLASS_VEHICLE) - { //vehicles manage their own speed + if (bgEnt && bgEnt->s.NPC_class == CLASS_VEHICLE) { // vehicles manage their own speed return; } } - //For prediction, always reset speed back to the last known server base speed - //If we didn't do this, under lag we'd eventually dwindle speed down to 0 even though - //that would not be the correct predicted value. + // For prediction, always reset speed back to the last known server base speed + // If we didn't do this, under lag we'd eventually dwindle speed down to 0 even though + // that would not be the correct predicted value. ps->speed = ps->basespeed; - if (ps->forceHandExtend == HANDEXTEND_DODGE) - { + if (ps->forceHandExtend == HANDEXTEND_DODGE) { ps->speed = 0; } - if (ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || - ps->forceHandExtend == HANDEXTEND_PRETHROWN || - ps->forceHandExtend == HANDEXTEND_POSTTHROWN) - { + if (ps->forceHandExtend == HANDEXTEND_KNOCKDOWN || ps->forceHandExtend == HANDEXTEND_PRETHROWN || ps->forceHandExtend == HANDEXTEND_POSTTHROWN) { ps->speed = 0; } - - if ( cmd->forwardmove < 0 && !(cmd->buttons&BUTTON_WALKING) && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//running backwards is slower than running forwards (like SP) + if (cmd->forwardmove < 0 && !(cmd->buttons & BUTTON_WALKING) && + pm->ps->groundEntityNum != ENTITYNUM_NONE) { // running backwards is slower than running forwards (like SP) ps->speed *= 0.75f; } - if (ps->fd.forcePowersActive & (1 << FP_GRIP)) - { + if (ps->fd.forcePowersActive & (1 << FP_GRIP)) { ps->speed *= 0.4f; } - if (ps->fd.forcePowersActive & (1 << FP_SPEED)) - { + if (ps->fd.forcePowersActive & (1 << FP_SPEED)) { ps->speed *= 1.7f; - } - else if (ps->fd.forcePowersActive & (1 << FP_RAGE)) - { + } else if (ps->fd.forcePowersActive & (1 << FP_RAGE)) { ps->speed *= 1.3f; - } - else if (ps->fd.forceRageRecoveryTime > svTime) - { + } else if (ps->fd.forceRageRecoveryTime > svTime) { ps->speed *= 0.75f; } - if (pm->ps->weapon == WP_DISRUPTOR && - pm->ps->zoomMode == 1 && pm->ps->zoomLockTime < pm->cmd.serverTime) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1 && pm->ps->zoomLockTime < pm->cmd.serverTime) { ps->speed *= 0.5f; } - if ( ps->fd.forceGripCripple && pm->ps->persistant[PERS_TEAM] != TEAM_SPECTATOR ) { - if ( ps->fd.forcePowersActive & (1 << FP_RAGE) ) + if (ps->fd.forceGripCripple && pm->ps->persistant[PERS_TEAM] != TEAM_SPECTATOR) { + if (ps->fd.forcePowersActive & (1 << FP_RAGE)) ps->speed *= 0.9f; - else if ( ps->fd.forcePowersActive & (1 << FP_SPEED) ) + else if (ps->fd.forcePowersActive & (1 << FP_SPEED)) ps->speed *= 0.8f; else ps->speed *= 0.2f; } - if ( BG_SaberInAttack( ps->saberMove ) && cmd->forwardmove < 0 ) - {//if running backwards while attacking, don't run as fast. - switch( ps->fd.saberAnimLevel ) - { + if (BG_SaberInAttack(ps->saberMove) && cmd->forwardmove < 0) { // if running backwards while attacking, don't run as fast. + switch (ps->fd.saberAnimLevel) { case FORCE_LEVEL_1: ps->speed *= 0.75f; break; @@ -8437,22 +6982,14 @@ void BG_AdjustClientSpeed(playerState_t *ps, usercmd_t *cmd, int svTime) default: break; } - } - else if ( BG_SpinningSaberAnim( ps->legsAnim ) ) - { - if (ps->fd.saberAnimLevel == FORCE_LEVEL_3) - { + } else if (BG_SpinningSaberAnim(ps->legsAnim)) { + if (ps->fd.saberAnimLevel == FORCE_LEVEL_3) { ps->speed *= 0.3f; - } - else - { + } else { ps->speed *= 0.5f; } - } - else if ( ps->weapon == WP_SABER && BG_SaberInAttack( ps->saberMove ) ) - {//if attacking with saber while running, drop your speed - switch( ps->fd.saberAnimLevel ) - { + } else if (ps->weapon == WP_SABER && BG_SaberInAttack(ps->saberMove)) { // if attacking with saber while running, drop your speed + switch (ps->fd.saberAnimLevel) { case FORCE_LEVEL_2: case SS_DUAL: case SS_STAFF: @@ -8464,69 +7001,47 @@ void BG_AdjustClientSpeed(playerState_t *ps, usercmd_t *cmd, int svTime) default: break; } - } - else if (ps->weapon == WP_SABER && ps->fd.saberAnimLevel == FORCE_LEVEL_3 && - PM_SaberInTransition(ps->saberMove)) - { //Now, we want to even slow down in transitions for level 3 (since it has chains and stuff now) - if (cmd->forwardmove < 0) - { + } else if (ps->weapon == WP_SABER && ps->fd.saberAnimLevel == FORCE_LEVEL_3 && + PM_SaberInTransition(ps->saberMove)) { // Now, we want to even slow down in transitions for level 3 (since it has chains and stuff now) + if (cmd->forwardmove < 0) { ps->speed *= 0.4f; - } - else - { + } else { ps->speed *= 0.6f; } } - if ( BG_InRoll( ps, ps->legsAnim ) && ps->speed > 50 ) - { //can't roll unless you're able to move normally - if ((ps->legsAnim) == BOTH_ROLL_B) - { //backwards roll is pretty fast, should also be slower - if (ps->legsTimer > 800) - { - ps->speed = ps->legsTimer/2.5; - } - else - { - ps->speed = ps->legsTimer/6.0;//450; - } - } - else - { - if (ps->legsTimer > 800) - { - ps->speed = ps->legsTimer/1.5;//450; + if (BG_InRoll(ps, ps->legsAnim) && ps->speed > 50) { // can't roll unless you're able to move normally + if ((ps->legsAnim) == BOTH_ROLL_B) { // backwards roll is pretty fast, should also be slower + if (ps->legsTimer > 800) { + ps->speed = ps->legsTimer / 2.5; + } else { + ps->speed = ps->legsTimer / 6.0; // 450; } - else - { - ps->speed = ps->legsTimer/5.0;//450; + } else { + if (ps->legsTimer > 800) { + ps->speed = ps->legsTimer / 1.5; // 450; + } else { + ps->speed = ps->legsTimer / 5.0; // 450; } } - if (ps->speed > 600) - { + if (ps->speed > 600) { ps->speed = 600; } - //Automatically slow down as the roll ends. + // Automatically slow down as the roll ends. } - saber = BG_MySaber( ps->clientNum, 0 ); - if ( saber - && saber->moveSpeedScale != 1.0f ) - { + saber = BG_MySaber(ps->clientNum, 0); + if (saber && saber->moveSpeedScale != 1.0f) { ps->speed *= saber->moveSpeedScale; } - saber = BG_MySaber( ps->clientNum, 1 ); - if ( saber - && saber->moveSpeedScale != 1.0f ) - { + saber = BG_MySaber(ps->clientNum, 1); + if (saber && saber->moveSpeedScale != 1.0f) { ps->speed *= saber->moveSpeedScale; } } -qboolean BG_InRollAnim( entityState_t *cent ) -{ - switch ( (cent->legsAnim) ) - { +qboolean BG_InRollAnim(entityState_t *cent) { + switch ((cent->legsAnim)) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: @@ -8536,10 +7051,8 @@ qboolean BG_InRollAnim( entityState_t *cent ) return qfalse; } -qboolean BG_InKnockDown( int anim ) -{ - switch ( (anim) ) - { +qboolean BG_InKnockDown(int anim) { + switch ((anim)) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: @@ -8573,10 +7086,8 @@ qboolean BG_InKnockDown( int anim ) return qfalse; } -qboolean BG_InRollES( entityState_t *ps, int anim ) -{ - switch ( (anim) ) - { +qboolean BG_InRollES(entityState_t *ps, int anim) { + switch ((anim)) { case BOTH_ROLL_F: case BOTH_ROLL_B: case BOTH_ROLL_R: @@ -8587,37 +7098,34 @@ qboolean BG_InRollES( entityState_t *ps, int anim ) return qfalse; } -void BG_IK_MoveArm(void *ghoul2, int lHandBolt, int time, entityState_t *ent, int basePose, vec3_t desiredPos, qboolean *ikInProgress, - vec3_t origin, vec3_t angles, vec3_t scale, int blendTime, qboolean forceHalt) -{ +void BG_IK_MoveArm(void *ghoul2, int lHandBolt, int time, entityState_t *ent, int basePose, vec3_t desiredPos, qboolean *ikInProgress, vec3_t origin, + vec3_t angles, vec3_t scale, int blendTime, qboolean forceHalt) { mdxaBone_t lHandMatrix; vec3_t lHand; vec3_t torg; float distToDest; - if (!ghoul2) - { + if (!ghoul2) { return; } assert(bgHumanoidAnimations[basePose].firstFrame > 0); - if (!*ikInProgress && !forceHalt) - { + if (!*ikInProgress && !forceHalt) { int baseposeAnim = basePose; sharedSetBoneIKStateParams_t ikP; - //restrict the shoulder joint - //VectorSet(ikP.pcjMins,-50.0f,-80.0f,-15.0f); - //VectorSet(ikP.pcjMaxs,15.0f,40.0f,15.0f); + // restrict the shoulder joint + // VectorSet(ikP.pcjMins,-50.0f,-80.0f,-15.0f); + // VectorSet(ikP.pcjMaxs,15.0f,40.0f,15.0f); - //for now, leaving it unrestricted, but restricting elbow joint. - //This lets us break the arm however we want in order to fling people - //in throws, and doesn't look bad. - VectorSet(ikP.pcjMins,0,0,0); - VectorSet(ikP.pcjMaxs,0,0,0); + // for now, leaving it unrestricted, but restricting elbow joint. + // This lets us break the arm however we want in order to fling people + // in throws, and doesn't look bad. + VectorSet(ikP.pcjMins, 0, 0, 0); + VectorSet(ikP.pcjMaxs, 0, 0, 0); - //give the info on our entity. + // give the info on our entity. ikP.blendTime = blendTime; VectorCopy(origin, ikP.origin); VectorCopy(angles, ikP.angles); @@ -8626,49 +7134,45 @@ void BG_IK_MoveArm(void *ghoul2, int lHandBolt, int time, entityState_t *ent, in ikP.radius = 10.0f; VectorCopy(scale, ikP.scale); - //base pose frames for the limb + // base pose frames for the limb ikP.startFrame = bgHumanoidAnimations[baseposeAnim].firstFrame + bgHumanoidAnimations[baseposeAnim].numFrames; ikP.endFrame = bgHumanoidAnimations[baseposeAnim].firstFrame + bgHumanoidAnimations[baseposeAnim].numFrames; - ikP.forceAnimOnBone = qfalse; //let it use existing anim if it's the same as this one. + ikP.forceAnimOnBone = qfalse; // let it use existing anim if it's the same as this one. - //we want to call with a null bone name first. This will init all of the - //ik system stuff on the g2 instance, because we need ragdoll effectors - //in order for our pcj's to know how to angle properly. - if (!trap->G2API_SetBoneIKState(ghoul2, time, NULL, IKS_DYNAMIC, &ikP)) - { + // we want to call with a null bone name first. This will init all of the + // ik system stuff on the g2 instance, because we need ragdoll effectors + // in order for our pcj's to know how to angle properly. + if (!trap->G2API_SetBoneIKState(ghoul2, time, NULL, IKS_DYNAMIC, &ikP)) { assert(!"Failed to init IK system for g2 instance!"); } - //Now, create our IK bone state. - if (trap->G2API_SetBoneIKState(ghoul2, time, "lhumerus", IKS_DYNAMIC, &ikP)) - { - //restrict the elbow joint - VectorSet(ikP.pcjMins,-90.0f,-20.0f,-20.0f); - VectorSet(ikP.pcjMaxs,30.0f,20.0f,-20.0f); + // Now, create our IK bone state. + if (trap->G2API_SetBoneIKState(ghoul2, time, "lhumerus", IKS_DYNAMIC, &ikP)) { + // restrict the elbow joint + VectorSet(ikP.pcjMins, -90.0f, -20.0f, -20.0f); + VectorSet(ikP.pcjMaxs, 30.0f, 20.0f, -20.0f); - if (trap->G2API_SetBoneIKState(ghoul2, time, "lradius", IKS_DYNAMIC, &ikP)) - { //everything went alright. + if (trap->G2API_SetBoneIKState(ghoul2, time, "lradius", IKS_DYNAMIC, &ikP)) { // everything went alright. *ikInProgress = qtrue; } } } - if (*ikInProgress && !forceHalt) - { //actively update our ik state. + if (*ikInProgress && !forceHalt) { // actively update our ik state. sharedIKMoveParams_t ikM; sharedRagDollUpdateParams_t tuParms; vec3_t tAngles; - //set the argument struct up - VectorCopy(desiredPos, ikM.desiredOrigin); //we want the bone to move here.. if possible + // set the argument struct up + VectorCopy(desiredPos, ikM.desiredOrigin); // we want the bone to move here.. if possible VectorCopy(angles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; trap->G2API_GetBoltMatrix(ghoul2, 0, lHandBolt, &lHandMatrix, tAngles, origin, time, 0, scale); - //Get the point position from the matrix. + // Get the point position from the matrix. lHand[0] = lHandMatrix.matrix[0][3]; lHand[1] = lHandMatrix.matrix[1][3]; lHand[2] = lHandMatrix.matrix[2][3]; @@ -8676,34 +7180,24 @@ void BG_IK_MoveArm(void *ghoul2, int lHandBolt, int time, entityState_t *ent, in VectorSubtract(lHand, desiredPos, torg); distToDest = VectorLength(torg); - //closer we are, more we want to keep updated. - //if we're far away we don't want to be too fast or we'll start twitching all over. - if (distToDest < 2) - { //however if we're this close we want very precise movement + // closer we are, more we want to keep updated. + // if we're far away we don't want to be too fast or we'll start twitching all over. + if (distToDest < 2) { // however if we're this close we want very precise movement ikM.movementSpeed = 0.4f; - } - else if (distToDest < 16) - { - ikM.movementSpeed = 0.9f;//8.0f; - } - else if (distToDest < 32) - { - ikM.movementSpeed = 0.8f;//4.0f; - } - else if (distToDest < 64) - { - ikM.movementSpeed = 0.7f;//2.0f; - } - else - { + } else if (distToDest < 16) { + ikM.movementSpeed = 0.9f; // 8.0f; + } else if (distToDest < 32) { + ikM.movementSpeed = 0.8f; // 4.0f; + } else if (distToDest < 64) { + ikM.movementSpeed = 0.7f; // 2.0f; + } else { ikM.movementSpeed = 0.6f; } - VectorCopy(origin, ikM.origin); //our position in the world. + VectorCopy(origin, ikM.origin); // our position in the world. ikM.boneName[0] = 0; - if (trap->G2API_IKMove(ghoul2, time, &ikM)) - { - //now do the standard model animate stuff with ragdoll update params. + if (trap->G2API_IKMove(ghoul2, time, &ikM)) { + // now do the standard model animate stuff with ragdoll update params. VectorCopy(angles, tuParms.angles); tuParms.angles[PITCH] = 0; @@ -8714,149 +7208,115 @@ void BG_IK_MoveArm(void *ghoul2, int lHandBolt, int time, entityState_t *ent, in VectorClear(tuParms.velocity); trap->G2API_AnimateG2Models(ghoul2, time, &tuParms); - } - else - { + } else { *ikInProgress = qfalse; } - } - else if (*ikInProgress) - { //kill it + } else if (*ikInProgress) { // kill it float cFrame, animSpeed; int sFrame, eFrame, flags; trap->G2API_SetBoneIKState(ghoul2, time, "lhumerus", IKS_NONE, NULL); trap->G2API_SetBoneIKState(ghoul2, time, "lradius", IKS_NONE, NULL); - //then reset the angles/anims on these PCJs + // then reset the angles/anims on these PCJs trap->G2API_SetBoneAngles(ghoul2, 0, "lhumerus", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "lradius", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, time); - //Get the anim/frames that the pelvis is on exactly, and match the left arm back up with them again. + // Get the anim/frames that the pelvis is on exactly, and match the left arm back up with them again. trap->G2API_GetBoneAnim(ghoul2, "pelvis", (const int)time, &cFrame, &sFrame, &eFrame, &flags, &animSpeed, 0, 0); trap->G2API_SetBoneAnim(ghoul2, 0, "lhumerus", sFrame, eFrame, flags, animSpeed, time, sFrame, 300); trap->G2API_SetBoneAnim(ghoul2, 0, "lradius", sFrame, eFrame, flags, animSpeed, time, sFrame, 300); - //And finally, get rid of all the ik state effector data by calling with null bone name (similar to how we init it). + // And finally, get rid of all the ik state effector data by calling with null bone name (similar to how we init it). trap->G2API_SetBoneIKState(ghoul2, time, NULL, IKS_NONE, NULL); *ikInProgress = qfalse; } } -//Adjust the head/neck desired angles -void BG_UpdateLookAngles( int lookingDebounceTime, vec3_t lastHeadAngles, int time, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, float minYaw, float maxYaw, float minRoll, float maxRoll ) -{ +// Adjust the head/neck desired angles +void BG_UpdateLookAngles(int lookingDebounceTime, vec3_t lastHeadAngles, int time, vec3_t lookAngles, float lookSpeed, float minPitch, float maxPitch, + float minYaw, float maxYaw, float minRoll, float maxRoll) { static const float fFrameInter = 0.1f; static vec3_t oldLookAngles; static vec3_t lookAnglesDiff; static int ang; - if ( lookingDebounceTime > time ) - { - //clamp so don't get "Exorcist" effect - if ( lookAngles[PITCH] > maxPitch ) - { + if (lookingDebounceTime > time) { + // clamp so don't get "Exorcist" effect + if (lookAngles[PITCH] > maxPitch) { lookAngles[PITCH] = maxPitch; - } - else if ( lookAngles[PITCH] < minPitch ) - { + } else if (lookAngles[PITCH] < minPitch) { lookAngles[PITCH] = minPitch; } - if ( lookAngles[YAW] > maxYaw ) - { + if (lookAngles[YAW] > maxYaw) { lookAngles[YAW] = maxYaw; - } - else if ( lookAngles[YAW] < minYaw ) - { + } else if (lookAngles[YAW] < minYaw) { lookAngles[YAW] = minYaw; } - if ( lookAngles[ROLL] > maxRoll ) - { + if (lookAngles[ROLL] > maxRoll) { lookAngles[ROLL] = maxRoll; - } - else if ( lookAngles[ROLL] < minRoll ) - { + } else if (lookAngles[ROLL] < minRoll) { lookAngles[ROLL] = minRoll; } - //slowly lerp to this new value - //Remember last headAngles - VectorCopy( lastHeadAngles, oldLookAngles ); - VectorSubtract( lookAngles, oldLookAngles, lookAnglesDiff ); + // slowly lerp to this new value + // Remember last headAngles + VectorCopy(lastHeadAngles, oldLookAngles); + VectorSubtract(lookAngles, oldLookAngles, lookAnglesDiff); - for ( ang = 0; ang < 3; ang++ ) - { - lookAnglesDiff[ang] = AngleNormalize180( lookAnglesDiff[ang] ); + for (ang = 0; ang < 3; ang++) { + lookAnglesDiff[ang] = AngleNormalize180(lookAnglesDiff[ang]); } - if( VectorLengthSquared( lookAnglesDiff ) ) - { - lookAngles[PITCH] = AngleNormalize180( oldLookAngles[PITCH]+(lookAnglesDiff[PITCH]*fFrameInter*lookSpeed) ); - lookAngles[YAW] = AngleNormalize180( oldLookAngles[YAW]+(lookAnglesDiff[YAW]*fFrameInter*lookSpeed) ); - lookAngles[ROLL] = AngleNormalize180( oldLookAngles[ROLL]+(lookAnglesDiff[ROLL]*fFrameInter*lookSpeed) ); + if (VectorLengthSquared(lookAnglesDiff)) { + lookAngles[PITCH] = AngleNormalize180(oldLookAngles[PITCH] + (lookAnglesDiff[PITCH] * fFrameInter * lookSpeed)); + lookAngles[YAW] = AngleNormalize180(oldLookAngles[YAW] + (lookAnglesDiff[YAW] * fFrameInter * lookSpeed)); + lookAngles[ROLL] = AngleNormalize180(oldLookAngles[ROLL] + (lookAnglesDiff[ROLL] * fFrameInter * lookSpeed)); } } - //Remember current lookAngles next time - VectorCopy( lookAngles, lastHeadAngles ); + // Remember current lookAngles next time + VectorCopy(lookAngles, lastHeadAngles); } -//for setting visual look (headturn) angles -static void BG_G2ClientNeckAngles( void *ghoul2, int time, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, vec3_t headClampMinAngles, vec3_t headClampMaxAngles ) -{ - vec3_t lA; - VectorCopy( lookAngles, lA ); - //clamp the headangles (which should now be relative to the cervical (neck) angles - if ( lA[PITCH] < headClampMinAngles[PITCH] ) - { +// for setting visual look (headturn) angles +static void BG_G2ClientNeckAngles(void *ghoul2, int time, const vec3_t lookAngles, vec3_t headAngles, vec3_t neckAngles, vec3_t thoracicAngles, + vec3_t headClampMinAngles, vec3_t headClampMaxAngles) { + vec3_t lA; + VectorCopy(lookAngles, lA); + // clamp the headangles (which should now be relative to the cervical (neck) angles + if (lA[PITCH] < headClampMinAngles[PITCH]) { lA[PITCH] = headClampMinAngles[PITCH]; - } - else if ( lA[PITCH] > headClampMaxAngles[PITCH] ) - { + } else if (lA[PITCH] > headClampMaxAngles[PITCH]) { lA[PITCH] = headClampMaxAngles[PITCH]; } - if ( lA[YAW] < headClampMinAngles[YAW] ) - { + if (lA[YAW] < headClampMinAngles[YAW]) { lA[YAW] = headClampMinAngles[YAW]; - } - else if ( lA[YAW] > headClampMaxAngles[YAW] ) - { + } else if (lA[YAW] > headClampMaxAngles[YAW]) { lA[YAW] = headClampMaxAngles[YAW]; } - if ( lA[ROLL] < headClampMinAngles[ROLL] ) - { + if (lA[ROLL] < headClampMinAngles[ROLL]) { lA[ROLL] = headClampMinAngles[ROLL]; - } - else if ( lA[ROLL] > headClampMaxAngles[ROLL] ) - { + } else if (lA[ROLL] > headClampMaxAngles[ROLL]) { lA[ROLL] = headClampMaxAngles[ROLL]; } - //split it up between the neck and cranium - if ( thoracicAngles[PITCH] ) - {//already been set above, blend them + // split it up between the neck and cranium + if (thoracicAngles[PITCH]) { // already been set above, blend them thoracicAngles[PITCH] = (thoracicAngles[PITCH] + (lA[PITCH] * 0.4)) * 0.5f; - } - else - { + } else { thoracicAngles[PITCH] = lA[PITCH] * 0.4; } - if ( thoracicAngles[YAW] ) - {//already been set above, blend them + if (thoracicAngles[YAW]) { // already been set above, blend them thoracicAngles[YAW] = (thoracicAngles[YAW] + (lA[YAW] * 0.1)) * 0.5f; - } - else - { + } else { thoracicAngles[YAW] = lA[YAW] * 0.1; } - if ( thoracicAngles[ROLL] ) - {//already been set above, blend them + if (thoracicAngles[ROLL]) { // already been set above, blend them thoracicAngles[ROLL] = (thoracicAngles[ROLL] + (lA[ROLL] * 0.1)) * 0.5f; - } - else - { + } else { thoracicAngles[ROLL] = lA[ROLL] * 0.1; } @@ -8880,128 +7340,90 @@ static void BG_G2ClientNeckAngles( void *ghoul2, int time, const vec3_t lookAngl trap->G2API_SetBoneAngles(ghoul2, 0, "thoracic", thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); } -//rww - Finally decided to convert all this stuff to BG form. -static void BG_G2ClientSpineAngles( void *ghoul2, int motionBolt, vec3_t cent_lerpOrigin, vec3_t cent_lerpAngles, entityState_t *cent, - int time, vec3_t viewAngles, int ciLegs, int ciTorso, const vec3_t angles, vec3_t thoracicAngles, - vec3_t ulAngles, vec3_t llAngles, vec3_t modelScale, float *tPitchAngle, float *tYawAngle, int *corrTime ) -{ +// rww - Finally decided to convert all this stuff to BG form. +static void BG_G2ClientSpineAngles(void *ghoul2, int motionBolt, vec3_t cent_lerpOrigin, vec3_t cent_lerpAngles, entityState_t *cent, int time, + vec3_t viewAngles, int ciLegs, int ciTorso, const vec3_t angles, vec3_t thoracicAngles, vec3_t ulAngles, vec3_t llAngles, + vec3_t modelScale, float *tPitchAngle, float *tYawAngle, int *corrTime) { qboolean doCorr = qfalse; //*tPitchAngle = viewAngles[PITCH]; - viewAngles[YAW] = AngleDelta( cent_lerpAngles[YAW], angles[YAW] ); + viewAngles[YAW] = AngleDelta(cent_lerpAngles[YAW], angles[YAW]); //*tYawAngle = viewAngles[YAW]; #if 1 - if ( !BG_FlippingAnim( cent->legsAnim ) && - !BG_SpinningSaberAnim( cent->legsAnim ) && - !BG_SpinningSaberAnim( cent->torsoAnim ) && - !BG_InSpecialJump( cent->legsAnim ) && - !BG_InSpecialJump( cent->torsoAnim ) && - !BG_InDeathAnim(cent->legsAnim) && - !BG_InDeathAnim(cent->torsoAnim) && - !BG_InRollES(cent, cent->legsAnim) && - !BG_InRollAnim(cent) && - !BG_SaberInSpecial(cent->saberMove) && - !BG_SaberInSpecialAttack(cent->torsoAnim) && + if (!BG_FlippingAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->torsoAnim) && + !BG_InSpecialJump(cent->legsAnim) && !BG_InSpecialJump(cent->torsoAnim) && !BG_InDeathAnim(cent->legsAnim) && !BG_InDeathAnim(cent->torsoAnim) && + !BG_InRollES(cent, cent->legsAnim) && !BG_InRollAnim(cent) && !BG_SaberInSpecial(cent->saberMove) && !BG_SaberInSpecialAttack(cent->torsoAnim) && !BG_SaberInSpecialAttack(cent->legsAnim) && - !BG_InKnockDown(cent->torsoAnim) && - !BG_InKnockDown(cent->legsAnim) && - !BG_InKnockDown(ciTorso) && - !BG_InKnockDown(ciLegs) && - - !BG_FlippingAnim( ciLegs ) && - !BG_SpinningSaberAnim( ciLegs ) && - !BG_SpinningSaberAnim( ciTorso ) && - !BG_InSpecialJump( ciLegs ) && - !BG_InSpecialJump( ciTorso ) && - !BG_InDeathAnim(ciLegs) && - !BG_InDeathAnim(ciTorso) && - !BG_SaberInSpecialAttack(ciTorso) && + !BG_InKnockDown(cent->torsoAnim) && !BG_InKnockDown(cent->legsAnim) && !BG_InKnockDown(ciTorso) && !BG_InKnockDown(ciLegs) && + + !BG_FlippingAnim(ciLegs) && !BG_SpinningSaberAnim(ciLegs) && !BG_SpinningSaberAnim(ciTorso) && !BG_InSpecialJump(ciLegs) && + !BG_InSpecialJump(ciTorso) && !BG_InDeathAnim(ciLegs) && !BG_InDeathAnim(ciTorso) && !BG_SaberInSpecialAttack(ciTorso) && !BG_SaberInSpecialAttack(ciLegs) && - !(cent->eFlags & EF_DEAD) && - (cent->legsAnim) != (cent->torsoAnim) && - (ciLegs) != (ciTorso) && - !cent->m_iVehicleNum) - { + !(cent->eFlags & EF_DEAD) && (cent->legsAnim) != (cent->torsoAnim) && (ciLegs) != (ciTorso) && !cent->m_iVehicleNum) { doCorr = qtrue; } #else - if ( ((!BG_FlippingAnim( cent->legsAnim ) - && !BG_SpinningSaberAnim( cent->legsAnim ) - && !BG_SpinningSaberAnim( cent->torsoAnim ) - && (cent->legsAnim) != (cent->torsoAnim)) //NOTE: presumes your legs & torso are on the same frame, though they *should* be because PM_SetAnimFinal tries to keep them in synch - || - (!BG_FlippingAnim( ciLegs ) - && !BG_SpinningSaberAnim( ciLegs ) - && !BG_SpinningSaberAnim( ciTorso ) - && (ciLegs) != (ciTorso))) - || - ciLegs != cent->legsAnim - || - ciTorso != cent->torsoAnim) - { + if (((!BG_FlippingAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->torsoAnim) && + (cent->legsAnim) != (cent->torsoAnim)) // NOTE: presumes your legs & torso are on the same frame, though they *should* be because PM_SetAnimFinal + // tries to keep them in synch + || (!BG_FlippingAnim(ciLegs) && !BG_SpinningSaberAnim(ciLegs) && !BG_SpinningSaberAnim(ciTorso) && (ciLegs) != (ciTorso))) || + ciLegs != cent->legsAnim || ciTorso != cent->torsoAnim) { doCorr = qtrue; - *corrTime = time + 1000; //continue correcting for a second after to smooth things out. SP doesn't need this for whatever reason but I can't find a way around it. - } - else if (*corrTime >= time) - { - if (!BG_FlippingAnim( cent->legsAnim ) - && !BG_SpinningSaberAnim( cent->legsAnim ) - && !BG_SpinningSaberAnim( cent->torsoAnim ) - && !BG_FlippingAnim( ciLegs ) - && !BG_SpinningSaberAnim( ciLegs ) - && !BG_SpinningSaberAnim( ciTorso )) - { + *corrTime = + time + + 1000; // continue correcting for a second after to smooth things out. SP doesn't need this for whatever reason but I can't find a way around it. + } else if (*corrTime >= time) { + if (!BG_FlippingAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->legsAnim) && !BG_SpinningSaberAnim(cent->torsoAnim) && !BG_FlippingAnim(ciLegs) && + !BG_SpinningSaberAnim(ciLegs) && !BG_SpinningSaberAnim(ciTorso)) { doCorr = qtrue; } } #endif - if (doCorr) - {//FIXME: no need to do this if legs and torso on are same frame - //adjust for motion offset - mdxaBone_t boltMatrix; - vec3_t motionFwd, motionAngles; - vec3_t motionRt, tempAng; - int ang; + if (doCorr) { // FIXME: no need to do this if legs and torso on are same frame + // adjust for motion offset + mdxaBone_t boltMatrix; + vec3_t motionFwd, motionAngles; + vec3_t motionRt, tempAng; + int ang; - trap->G2API_GetBoltMatrix_NoRecNoRot( ghoul2, 0, motionBolt, &boltMatrix, vec3_origin, cent_lerpOrigin, time, 0, modelScale); - //BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, motionFwd ); + trap->G2API_GetBoltMatrix_NoRecNoRot(ghoul2, 0, motionBolt, &boltMatrix, vec3_origin, cent_lerpOrigin, time, 0, modelScale); + // BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, motionFwd ); motionFwd[0] = -boltMatrix.matrix[0][1]; motionFwd[1] = -boltMatrix.matrix[1][1]; motionFwd[2] = -boltMatrix.matrix[2][1]; - vectoangles( motionFwd, motionAngles ); + vectoangles(motionFwd, motionAngles); - //BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, motionRt ); + // BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, motionRt ); motionRt[0] = -boltMatrix.matrix[0][0]; motionRt[1] = -boltMatrix.matrix[1][0]; motionRt[2] = -boltMatrix.matrix[2][0]; - vectoangles( motionRt, tempAng ); + vectoangles(motionRt, tempAng); motionAngles[ROLL] = -tempAng[PITCH]; - for ( ang = 0; ang < 3; ang++ ) - { - viewAngles[ang] = AngleNormalize180( viewAngles[ang] - AngleNormalize180( motionAngles[ang] ) ); + for (ang = 0; ang < 3; ang++) { + viewAngles[ang] = AngleNormalize180(viewAngles[ang] - AngleNormalize180(motionAngles[ang])); } } - //distribute the angles differently up the spine - //NOTE: each of these distributions must add up to 1.0f - thoracicAngles[PITCH] = viewAngles[PITCH]*0.20f; - llAngles[PITCH] = viewAngles[PITCH]*0.40f; - ulAngles[PITCH] = viewAngles[PITCH]*0.40f; + // distribute the angles differently up the spine + // NOTE: each of these distributions must add up to 1.0f + thoracicAngles[PITCH] = viewAngles[PITCH] * 0.20f; + llAngles[PITCH] = viewAngles[PITCH] * 0.40f; + ulAngles[PITCH] = viewAngles[PITCH] * 0.40f; - thoracicAngles[YAW] = viewAngles[YAW]*0.20f; - ulAngles[YAW] = viewAngles[YAW]*0.35f; - llAngles[YAW] = viewAngles[YAW]*0.45f; + thoracicAngles[YAW] = viewAngles[YAW] * 0.20f; + ulAngles[YAW] = viewAngles[YAW] * 0.35f; + llAngles[YAW] = viewAngles[YAW] * 0.45f; - thoracicAngles[ROLL] = viewAngles[ROLL]*0.20f; - ulAngles[ROLL] = viewAngles[ROLL]*0.35f; - llAngles[ROLL] = viewAngles[ROLL]*0.45f; + thoracicAngles[ROLL] = viewAngles[ROLL] * 0.20f; + ulAngles[ROLL] = viewAngles[ROLL] * 0.35f; + llAngles[ROLL] = viewAngles[ROLL] * 0.45f; } /* @@ -9009,59 +7431,58 @@ static void BG_G2ClientSpineAngles( void *ghoul2, int motionBolt, vec3_t cent_le CG_SwingAngles ================== */ -static float BG_SwingAngles( float destination, float swingTolerance, float clampTolerance, - float speed, float *angle, qboolean *swinging, int frametime ) { - float swing; - float move; - float scale; +static float BG_SwingAngles(float destination, float swingTolerance, float clampTolerance, float speed, float *angle, qboolean *swinging, int frametime) { + float swing; + float move; + float scale; - if ( !*swinging ) { + if (!*swinging) { // see if a swing should be started - swing = AngleSubtract( *angle, destination ); - if ( swing > swingTolerance || swing < -swingTolerance ) { + swing = AngleSubtract(*angle, destination); + if (swing > swingTolerance || swing < -swingTolerance) { *swinging = qtrue; } } - if ( !*swinging ) { + if (!*swinging) { return 0; } // modify the speed depending on the delta // so it doesn't seem so linear - swing = AngleSubtract( destination, *angle ); - scale = fabs( swing ); - if ( scale < swingTolerance * 0.5 ) { + swing = AngleSubtract(destination, *angle); + scale = fabs(swing); + if (scale < swingTolerance * 0.5) { scale = 0.5; - } else if ( scale < swingTolerance ) { + } else if (scale < swingTolerance) { scale = 1.0; } else { scale = 2.0; } // swing towards the destination angle - if ( swing >= 0 ) { + if (swing >= 0) { move = frametime * scale * speed; - if ( move >= swing ) { + if (move >= swing) { move = swing; *swinging = qfalse; } - *angle = AngleMod( *angle + move ); - } else if ( swing < 0 ) { + *angle = AngleMod(*angle + move); + } else if (swing < 0) { move = frametime * scale * -speed; - if ( move <= swing ) { + if (move <= swing) { move = swing; *swinging = qfalse; } - *angle = AngleMod( *angle + move ); + *angle = AngleMod(*angle + move); } // clamp to no more than tolerance - swing = AngleSubtract( destination, *angle ); - if ( swing > clampTolerance ) { - *angle = AngleMod( destination - (clampTolerance - 1) ); - } else if ( swing < -clampTolerance ) { - *angle = AngleMod( destination + (clampTolerance - 1) ); + swing = AngleSubtract(destination, *angle); + if (swing > clampTolerance) { + *angle = AngleMod(destination - (clampTolerance - 1)); + } else if (swing < -clampTolerance) { + *angle = AngleMod(destination + (clampTolerance - 1)); } return swing; @@ -9069,11 +7490,9 @@ static float BG_SwingAngles( float destination, float swingTolerance, float clam //#define BONE_BASED_LEG_ANGLES -//I apologize for this function -qboolean BG_InRoll2( entityState_t *es ) -{ - switch ( (es->legsAnim) ) - { +// I apologize for this function +qboolean BG_InRoll2(entityState_t *es) { + switch ((es->legsAnim)) { case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_BROLL_L: @@ -9092,49 +7511,44 @@ qboolean BG_InRoll2( entityState_t *es ) return qfalse; } - -extern qboolean BG_SaberLockBreakAnim( int anim ); //bg_panimate.c -void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int time, vec3_t cent_lerpOrigin, - vec3_t cent_lerpAngles, matrix3_t legs, vec3_t legsAngles, qboolean *tYawing, - qboolean *tPitching, qboolean *lYawing, float *tYawAngle, float *tPitchAngle, - float *lYawAngle, int frametime, vec3_t turAngles, vec3_t modelScale, int ciLegs, - int ciTorso, int *corrTime, vec3_t lookAngles, vec3_t lastHeadAngles, int lookTime, - entityState_t *emplaced, int *crazySmoothFactor) -{ - int adddir = 0; - static int dir; - static int i; -// static int movementOffsets[8] = { 0, 22, 45, -22, 0, 22, -45, -22 }; - float degrees_negative = 0; - float degrees_positive = 0; - static float dif; - static float dest; - static float speed; //, speed_dif, speed_desired; - static const float lookSpeed = 1.5f; +extern qboolean BG_SaberLockBreakAnim(int anim); // bg_panimate.c +void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int time, vec3_t cent_lerpOrigin, vec3_t cent_lerpAngles, matrix3_t legs, + vec3_t legsAngles, qboolean *tYawing, qboolean *tPitching, qboolean *lYawing, float *tYawAngle, float *tPitchAngle, float *lYawAngle, + int frametime, vec3_t turAngles, vec3_t modelScale, int ciLegs, int ciTorso, int *corrTime, vec3_t lookAngles, vec3_t lastHeadAngles, + int lookTime, entityState_t *emplaced, int *crazySmoothFactor) { + int adddir = 0; + static int dir; + static int i; + // static int movementOffsets[8] = { 0, 22, 45, -22, 0, 22, -45, -22 }; + float degrees_negative = 0; + float degrees_positive = 0; + static float dif; + static float dest; + static float speed; //, speed_dif, speed_desired; + static const float lookSpeed = 1.5f; #ifdef BONE_BASED_LEG_ANGLES - static float legBoneYaw; + static float legBoneYaw; #endif - static vec3_t eyeAngles; - static vec3_t neckAngles; - static vec3_t velocity; - static vec3_t torsoAngles, headAngles; - static vec3_t velPos, velAng; - static vec3_t ulAngles, llAngles, viewAngles, angles, thoracicAngles = {0,0,0}; - static vec3_t headClampMinAngles = {-25,-55,-10}, headClampMaxAngles = {50,50,10}; - - if ( cent->m_iVehicleNum || cent->forceFrame || BG_SaberLockBreakAnim(cent->legsAnim) || BG_SaberLockBreakAnim(cent->torsoAnim) ) - { //a vehicle or riding a vehicle - in either case we don't need to be in here + static vec3_t eyeAngles; + static vec3_t neckAngles; + static vec3_t velocity; + static vec3_t torsoAngles, headAngles; + static vec3_t velPos, velAng; + static vec3_t ulAngles, llAngles, viewAngles, angles, thoracicAngles = {0, 0, 0}; + static vec3_t headClampMinAngles = {-25, -55, -10}, headClampMaxAngles = {50, 50, 10}; + + if (cent->m_iVehicleNum || cent->forceFrame || BG_SaberLockBreakAnim(cent->legsAnim) || + BG_SaberLockBreakAnim(cent->torsoAnim)) { // a vehicle or riding a vehicle - in either case we don't need to be in here vec3_t forcedAngles; VectorClear(forcedAngles); forcedAngles[YAW] = cent_lerpAngles[YAW]; forcedAngles[ROLL] = cent_lerpAngles[ROLL]; - AnglesToAxis( forcedAngles, legs ); + AnglesToAxis(forcedAngles, legs); VectorCopy(forcedAngles, legsAngles); VectorCopy(legsAngles, turAngles); - if (cent->number < MAX_CLIENTS) - { + if (cent->number < MAX_CLIENTS) { trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); @@ -9144,176 +7558,147 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti return; } - if ((time+2000) < *corrTime) - { + if ((time + 2000) < *corrTime) { *corrTime = 0; } - VectorCopy( cent_lerpAngles, headAngles ); - headAngles[YAW] = AngleMod( headAngles[YAW] ); - VectorClear( legsAngles ); - VectorClear( torsoAngles ); + VectorCopy(cent_lerpAngles, headAngles); + headAngles[YAW] = AngleMod(headAngles[YAW]); + VectorClear(legsAngles); + VectorClear(torsoAngles); // --------- yaw ------------- // allow yaw to drift a bit - if ((( cent->legsAnim ) != BOTH_STAND1) || - ( cent->torsoAnim ) != WeaponReadyAnim[cent->weapon] ) - { + if (((cent->legsAnim) != BOTH_STAND1) || (cent->torsoAnim) != WeaponReadyAnim[cent->weapon]) { // if not standing still, always point all in the same direction - //cent->pe.torso.yawing = qtrue; // always center + // cent->pe.torso.yawing = qtrue; // always center *tYawing = qtrue; - //cent->pe.torso.pitching = qtrue; // always center + // cent->pe.torso.pitching = qtrue; // always center *tPitching = qtrue; - //cent->pe.legs.yawing = qtrue; // always center + // cent->pe.legs.yawing = qtrue; // always center *lYawing = qtrue; } // adjust legs for movement dir - if ( cent->eFlags & EF_DEAD ) { + if (cent->eFlags & EF_DEAD) { // don't let dead bodies twitch dir = 0; } else { dir = cent->angles2[YAW]; - if ( dir < 0 || dir > 7 ) { - Com_Error( ERR_DROP, "Bad player movement angle (%i)", dir ); + if (dir < 0 || dir > 7) { + Com_Error(ERR_DROP, "Bad player movement angle (%i)", dir); } } torsoAngles[YAW] = headAngles[YAW]; - //for now, turn torso instantly and let the legs swing to follow + // for now, turn torso instantly and let the legs swing to follow *tYawAngle = torsoAngles[YAW]; // --------- pitch ------------- - VectorCopy( cent->pos.trDelta, velocity ); + VectorCopy(cent->pos.trDelta, velocity); - if (BG_InRoll2(cent)) - { //don't affect angles based on vel then + if (BG_InRoll2(cent)) { // don't affect angles based on vel then VectorClear(velocity); - } - else if (cent->weapon == WP_SABER && - BG_SaberInSpecial(cent->saberMove)) - { + } else if (cent->weapon == WP_SABER && BG_SaberInSpecial(cent->saberMove)) { VectorClear(velocity); } - speed = VectorNormalize( velocity ); + speed = VectorNormalize(velocity); - if (!speed) - { + if (!speed) { torsoAngles[YAW] = headAngles[YAW]; } // only show a fraction of the pitch angle in the torso - if ( headAngles[PITCH] > 180 ) { + if (headAngles[PITCH] > 180) { dest = (-360 + headAngles[PITCH]) * 0.75; } else { dest = headAngles[PITCH] * 0.75; } - if (cent->m_iVehicleNum) - { //swing instantly on vehicles + if (cent->m_iVehicleNum) { // swing instantly on vehicles *tPitchAngle = dest; - } - else - { - BG_SwingAngles( dest, 15, 30, 0.1f, tPitchAngle, tPitching, frametime ); + } else { + BG_SwingAngles(dest, 15, 30, 0.1f, tPitchAngle, tPitching, frametime); } torsoAngles[PITCH] = *tPitchAngle; // --------- roll ------------- - if ( speed ) { - matrix3_t axis; - float side; + if (speed) { + matrix3_t axis; + float side; speed *= 0.05f; - AnglesToAxis( legsAngles, axis ); - side = speed * DotProduct( velocity, axis[1] ); + AnglesToAxis(legsAngles, axis); + side = speed * DotProduct(velocity, axis[1]); legsAngles[ROLL] -= side; - side = speed * DotProduct( velocity, axis[0] ); + side = speed * DotProduct(velocity, axis[0]); legsAngles[PITCH] += side; } - //legsAngles[YAW] = headAngles[YAW] + (movementOffsets[ dir ]*speed_dif); + // legsAngles[YAW] = headAngles[YAW] + (movementOffsets[ dir ]*speed_dif); - //rww - crazy velocity-based leg angle calculation + // rww - crazy velocity-based leg angle calculation legsAngles[YAW] = headAngles[YAW]; velPos[0] = cent_lerpOrigin[0] + velocity[0]; velPos[1] = cent_lerpOrigin[1] + velocity[1]; - velPos[2] = cent_lerpOrigin[2];// + velocity[2]; + velPos[2] = cent_lerpOrigin[2]; // + velocity[2]; - if ( cent->groundEntityNum == ENTITYNUM_NONE || - cent->forceFrame || - (cent->weapon == WP_EMPLACED_GUN && emplaced) ) - { //off the ground, no direction-based leg angles (same if in saberlock) + if (cent->groundEntityNum == ENTITYNUM_NONE || cent->forceFrame || + (cent->weapon == WP_EMPLACED_GUN && emplaced)) { // off the ground, no direction-based leg angles (same if in saberlock) VectorCopy(cent_lerpOrigin, velPos); } VectorSubtract(cent_lerpOrigin, velPos, velAng); - if (!VectorCompare(velAng, vec3_origin)) - { + if (!VectorCompare(velAng, vec3_origin)) { vectoangles(velAng, velAng); - if (velAng[YAW] <= legsAngles[YAW]) - { + if (velAng[YAW] <= legsAngles[YAW]) { degrees_negative = (legsAngles[YAW] - velAng[YAW]); degrees_positive = (360 - legsAngles[YAW]) + velAng[YAW]; - } - else - { + } else { degrees_negative = legsAngles[YAW] + (360 - velAng[YAW]); degrees_positive = (velAng[YAW] - legsAngles[YAW]); } - if ( degrees_negative < degrees_positive ) - { + if (degrees_negative < degrees_positive) { dif = degrees_negative; adddir = 0; - } - else - { + } else { dif = degrees_positive; adddir = 1; } - if (dif > 90) - { + if (dif > 90) { dif = (180 - dif); } - if (dif > 60) - { + if (dif > 60) { dif = 60; } - //Slight hack for when playing is running backward - if (dir == 3 || dir == 5) - { + // Slight hack for when playing is running backward + if (dir == 3 || dir == 5) { dif = -dif; } - if (adddir) - { + if (adddir) { legsAngles[YAW] -= dif; - } - else - { + } else { legsAngles[YAW] += dif; } } - if (cent->m_iVehicleNum) - { //swing instantly on vehicles + if (cent->m_iVehicleNum) { // swing instantly on vehicles *lYawAngle = legsAngles[YAW]; - } - else - { - BG_SwingAngles( legsAngles[YAW], /*40*/0, 90, 0.65f, lYawAngle, lYawing, frametime ); + } else { + BG_SwingAngles(legsAngles[YAW], /*40*/ 0, 90, 0.65f, lYawAngle, lYawing, frametime); } legsAngles[YAW] = *lYawAngle; @@ -9325,17 +7710,16 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti legsAngles[ROLL] = 0; torsoAngles[ROLL] = 0; -// VectorCopy(legsAngles, turAngles); + // VectorCopy(legsAngles, turAngles); // pull the angles back out of the hierarchial chain - AnglesSubtract( headAngles, torsoAngles, headAngles ); - AnglesSubtract( torsoAngles, legsAngles, torsoAngles ); + AnglesSubtract(headAngles, torsoAngles, headAngles); + AnglesSubtract(torsoAngles, legsAngles, torsoAngles); legsAngles[PITCH] = 0; - if (cent->heldByClient) - { //keep the base angles clear when doing the IK stuff, it doesn't compensate for it. - //rwwFIXMEFIXME: Store leg angles off and add them to all the fed in angles for G2 functions? + if (cent->heldByClient) { // keep the base angles clear when doing the IK stuff, it doesn't compensate for it. + // rwwFIXMEFIXME: Store leg angles off and add them to all the fed in angles for G2 functions? VectorClear(legsAngles); legsAngles[YAW] = cent_lerpAngles[YAW]; } @@ -9348,39 +7732,31 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti VectorCopy(legsAngles, turAngles); - AnglesToAxis( legsAngles, legs ); + AnglesToAxis(legsAngles, legs); - VectorCopy( cent_lerpAngles, viewAngles ); + VectorCopy(cent_lerpAngles, viewAngles); viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - VectorSet( angles, 0, legsAngles[1], 0 ); + VectorSet(angles, 0, legsAngles[1], 0); angles[0] = legsAngles[0]; - if ( angles[0] > 30 ) - { + if (angles[0] > 30) { angles[0] = 30; - } - else if ( angles[0] < -30 ) - { + } else if (angles[0] < -30) { angles[0] = -30; } - if (cent->weapon == WP_EMPLACED_GUN && - emplaced) - { //if using an emplaced gun, then we want to make sure we're angled to "hold" it right + if (cent->weapon == WP_EMPLACED_GUN && emplaced) { // if using an emplaced gun, then we want to make sure we're angled to "hold" it right vec3_t facingAngles; VectorSubtract(emplaced->pos.trBase, cent_lerpOrigin, facingAngles); vectoangles(facingAngles, facingAngles); - if (emplaced->weapon == WP_NONE) - { //e-web + if (emplaced->weapon == WP_NONE) { // e-web VectorCopy(facingAngles, legsAngles); - AnglesToAxis( legsAngles, legs ); - } - else - { //misc emplaced + AnglesToAxis(legsAngles, legs); + } else { // misc emplaced float emplacedDif = AngleSubtract(cent_lerpAngles[YAW], facingAngles[YAW]); /* @@ -9392,57 +7768,54 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti VectorSet(facingAngles, -16.0f, -emplacedDif, 0.0f); - if (cent->legsAnim == BOTH_STRAFE_LEFT1 || cent->legsAnim == BOTH_STRAFE_RIGHT1) - { //try to adjust so it doesn't look wrong - if (crazySmoothFactor) - { //want to smooth a lot during this because it chops around and looks like ass + if (cent->legsAnim == BOTH_STRAFE_LEFT1 || cent->legsAnim == BOTH_STRAFE_RIGHT1) { // try to adjust so it doesn't look wrong + if (crazySmoothFactor) { // want to smooth a lot during this because it chops around and looks like ass *crazySmoothFactor = time + 1000; } - BG_G2ClientSpineAngles(ghoul2, motionBolt, cent_lerpOrigin, cent_lerpAngles, cent, time, viewAngles, ciLegs, ciTorso, angles, thoracicAngles, ulAngles, llAngles, modelScale, tPitchAngle, tYawAngle, corrTime); + BG_G2ClientSpineAngles(ghoul2, motionBolt, cent_lerpOrigin, cent_lerpAngles, cent, time, viewAngles, ciLegs, ciTorso, angles, thoracicAngles, + ulAngles, llAngles, modelScale, tPitchAngle, tYawAngle, corrTime); trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); VectorAdd(facingAngles, thoracicAngles, facingAngles); - if (cent->legsAnim == BOTH_STRAFE_LEFT1) - { //this one needs some further correction + if (cent->legsAnim == BOTH_STRAFE_LEFT1) { // this one needs some further correction facingAngles[YAW] -= 32.0f; } - } - else - { - // trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - // trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + } else { + // trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + // trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "cranium", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); } - VectorScale(facingAngles, 0.6f, facingAngles); trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - VectorScale(facingAngles, 0.8f, facingAngles); trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", facingAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - VectorScale(facingAngles, 0.8f, facingAngles); trap->G2API_SetBoneAngles(ghoul2, 0, "thoracic", facingAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + VectorScale(facingAngles, 0.6f, facingAngles); + trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + VectorScale(facingAngles, 0.8f, facingAngles); + trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", facingAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + VectorScale(facingAngles, 0.8f, facingAngles); + trap->G2API_SetBoneAngles(ghoul2, 0, "thoracic", facingAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - //Now we want the head angled toward where we are facing + // Now we want the head angled toward where we are facing VectorSet(facingAngles, 0.0f, dif, 0.0f); VectorScale(facingAngles, 0.6f, facingAngles); trap->G2API_SetBoneAngles(ghoul2, 0, "cervical", facingAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - return; //don't have to bother with the rest then + return; // don't have to bother with the rest then } } - BG_G2ClientSpineAngles(ghoul2, motionBolt, cent_lerpOrigin, cent_lerpAngles, cent, time, - viewAngles, ciLegs, ciTorso, angles, thoracicAngles, ulAngles, llAngles, modelScale, - tPitchAngle, tYawAngle, corrTime); + BG_G2ClientSpineAngles(ghoul2, motionBolt, cent_lerpOrigin, cent_lerpAngles, cent, time, viewAngles, ciLegs, ciTorso, angles, thoracicAngles, ulAngles, + llAngles, modelScale, tPitchAngle, tYawAngle, corrTime); VectorCopy(cent_lerpAngles, eyeAngles); - for ( i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize180( lookAngles[i] ); - eyeAngles[i] = AngleNormalize180( eyeAngles[i] ); + for (i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize180(lookAngles[i]); + eyeAngles[i] = AngleNormalize180(eyeAngles[i]); } - AnglesSubtract( lookAngles, eyeAngles, lookAngles ); + AnglesSubtract(lookAngles, eyeAngles, lookAngles); BG_UpdateLookAngles(lookTime, lastHeadAngles, time, lookAngles, lookSpeed, -50.0f, 50.0f, -70.0f, 70.0f, -30.0f, 30.0f); @@ -9455,8 +7828,7 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti bLAngles[ROLL] = AngleNormalize180((legBoneYaw - cent_lerpAngles[YAW])); strap_G2API_SetBoneAngles(ghoul2, 0, "model_root", bLAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); - if (!llAngles[YAW]) - { + if (!llAngles[YAW]) { llAngles[YAW] -= bLAngles[ROLL]; } } @@ -9465,215 +7837,177 @@ void BG_G2PlayerAngles(void *ghoul2, int motionBolt, entityState_t *cent, int ti trap->G2API_SetBoneAngles(ghoul2, 0, "lower_lumbar", llAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "upper_lumbar", ulAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); trap->G2API_SetBoneAngles(ghoul2, 0, "thoracic", thoracicAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); -// trap->G2API_SetBoneAngles(ghoul2, 0, "cervical", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); + // trap->G2API_SetBoneAngles(ghoul2, 0, "cervical", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); } -void BG_G2ATSTAngles(void *ghoul2, int time, vec3_t cent_lerpAngles ) -{// up right fwd - trap->G2API_SetBoneAngles( ghoul2, 0, "thoracic", cent_lerpAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time ); +void BG_G2ATSTAngles( + void *ghoul2, int time, + vec3_t cent_lerpAngles) { // up right fwd + trap->G2API_SetBoneAngles(ghoul2, 0, "thoracic", cent_lerpAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, 0, 0, time); } -static qboolean PM_AdjustAnglesForDualJumpAttack( playerState_t *ps, usercmd_t *ucmd ) -{ - //ucmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] ) - ps->delta_angles[PITCH]; - //ucmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] ) - ps->delta_angles[YAW]; +static qboolean PM_AdjustAnglesForDualJumpAttack(playerState_t *ps, usercmd_t *ucmd) { + // ucmd->angles[PITCH] = ANGLE2SHORT( ps->viewangles[PITCH] ) - ps->delta_angles[PITCH]; + // ucmd->angles[YAW] = ANGLE2SHORT( ps->viewangles[YAW] ) - ps->delta_angles[YAW]; return qtrue; } -static QINLINE void PM_CmdForSaberMoves(usercmd_t *ucmd) -{ - //DUAL FORWARD+JUMP+ATTACK - if ( (pm->ps->legsAnim == BOTH_JUMPATTACK6 && pm->ps->saberMove == LS_JUMPATTACK_DUAL) || - (pm->ps->legsAnim == BOTH_BUTTERFLY_FL1 && pm->ps->saberMove == LS_JUMPATTACK_STAFF_LEFT) || - (pm->ps->legsAnim == BOTH_BUTTERFLY_FR1 && pm->ps->saberMove == LS_JUMPATTACK_STAFF_RIGHT) || - (pm->ps->legsAnim == BOTH_BUTTERFLY_RIGHT && pm->ps->saberMove == LS_BUTTERFLY_RIGHT) || - (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT && pm->ps->saberMove == LS_BUTTERFLY_LEFT) ) - { +static QINLINE void PM_CmdForSaberMoves(usercmd_t *ucmd) { + // DUAL FORWARD+JUMP+ATTACK + if ((pm->ps->legsAnim == BOTH_JUMPATTACK6 && pm->ps->saberMove == LS_JUMPATTACK_DUAL) || + (pm->ps->legsAnim == BOTH_BUTTERFLY_FL1 && pm->ps->saberMove == LS_JUMPATTACK_STAFF_LEFT) || + (pm->ps->legsAnim == BOTH_BUTTERFLY_FR1 && pm->ps->saberMove == LS_JUMPATTACK_STAFF_RIGHT) || + (pm->ps->legsAnim == BOTH_BUTTERFLY_RIGHT && pm->ps->saberMove == LS_BUTTERFLY_RIGHT) || + (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT && pm->ps->saberMove == LS_BUTTERFLY_LEFT)) { int aLen = PM_AnimLength(0, BOTH_JUMPATTACK6); ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - if ( pm->ps->legsAnim == BOTH_JUMPATTACK6 ) - { //dual stance attack - if ( pm->ps->legsTimer >= 100 //not at end - && (aLen - pm->ps->legsTimer) >= 250 ) //not in beginning - { //middle of anim - //push forward + if (pm->ps->legsAnim == BOTH_JUMPATTACK6) { // dual stance attack + if (pm->ps->legsTimer >= 100 // not at end + && (aLen - pm->ps->legsTimer) >= 250) // not in beginning + { // middle of anim + // push forward ucmd->forwardmove = 127; } - if ( (pm->ps->legsTimer >= 900 //not at end - && aLen - pm->ps->legsTimer >= 950 ) //not in beginning - || ( pm->ps->legsTimer >= 1600 - && aLen - pm->ps->legsTimer >= 400 ) ) //not in beginning - { //one of the two jumps - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - { //still on ground? - if ( pm->ps->groundEntityNum >= MAX_CLIENTS ) - { - //jump! - pm->ps->velocity[2] = 250;//400; - pm->ps->fd.forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - //pm->ps->pm_flags |= PMF_JUMPING; - //FIXME: NPCs yell? + if ((pm->ps->legsTimer >= 900 // not at end + && aLen - pm->ps->legsTimer >= 950) // not in beginning + || (pm->ps->legsTimer >= 1600 && aLen - pm->ps->legsTimer >= 400)) // not in beginning + { // one of the two jumps + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // still on ground? + if (pm->ps->groundEntityNum >= MAX_CLIENTS) { + // jump! + pm->ps->velocity[2] = 250; // 400; + pm->ps->fd.forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + // pm->ps->pm_flags |= PMF_JUMPING; + // FIXME: NPCs yell? PM_AddEvent(EV_JUMP); - //G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + // G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); } - } - else - { //FIXME: if this is the second jump, maybe we should just stop the anim? + } else { // FIXME: if this is the second jump, maybe we should just stop the anim? } } - } - else - { //saberstaff attacks + } else { // saberstaff attacks float lenMin = 1700.0f; float lenMax = 1800.0f; aLen = PM_AnimLength(0, (animNumber_t)pm->ps->legsAnim); - if (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT) - { + if (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT) { lenMin = 1200.0f; lenMax = 1400.0f; } - //FIXME: don't slide off people/obstacles? - if ( pm->ps->legsAnim == BOTH_BUTTERFLY_RIGHT - || pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT ) - { - if ( pm->ps->legsTimer > 450 ) - { - switch ( pm->ps->legsAnim ) - { - case BOTH_BUTTERFLY_LEFT: - ucmd->rightmove = -127; - break; - case BOTH_BUTTERFLY_RIGHT: - ucmd->rightmove = 127; - break; - default: - break; + // FIXME: don't slide off people/obstacles? + if (pm->ps->legsAnim == BOTH_BUTTERFLY_RIGHT || pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT) { + if (pm->ps->legsTimer > 450) { + switch (pm->ps->legsAnim) { + case BOTH_BUTTERFLY_LEFT: + ucmd->rightmove = -127; + break; + case BOTH_BUTTERFLY_RIGHT: + ucmd->rightmove = 127; + break; + default: + break; } } - } - else - { - if ( pm->ps->legsTimer >= 100 //not at end - && aLen - pm->ps->legsTimer >= 250 )//not in beginning - {//middle of anim - //push forward + } else { + if (pm->ps->legsTimer >= 100 // not at end + && aLen - pm->ps->legsTimer >= 250) // not in beginning + { // middle of anim + // push forward ucmd->forwardmove = 127; } } - if ( pm->ps->legsTimer >= lenMin && pm->ps->legsTimer < lenMax ) - {//one of the two jumps - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? - //jump! - if (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT) - { + if (pm->ps->legsTimer >= lenMin && pm->ps->legsTimer < lenMax) { // one of the two jumps + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // still on ground? + // jump! + if (pm->ps->legsAnim == BOTH_BUTTERFLY_LEFT) { pm->ps->velocity[2] = 350; - } - else - { + } else { pm->ps->velocity[2] = 250; } - pm->ps->fd.forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - //pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? + pm->ps->fd.forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + // pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; + // FIXME: NPCs yell? PM_AddEvent(EV_JUMP); - //G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - } - else - {//FIXME: if this is the second jump, maybe we should just stop the anim? + // G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + } else { // FIXME: if this is the second jump, maybe we should just stop the anim? } } } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//can only turn when your feet hit the ground - if (PM_AdjustAnglesForDualJumpAttack(pm->ps, ucmd)) - { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // can only turn when your feet hit the ground + if (PM_AdjustAnglesForDualJumpAttack(pm->ps, ucmd)) { PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, ucmd); } } - //rwwFIXMEFIXME: Bother with bbox resizing like sp? + // rwwFIXMEFIXME: Bother with bbox resizing like sp? } - //STAFF BACK+JUMP+ATTACK - else if (pm->ps->saberMove == LS_A_BACKFLIP_ATK && - pm->ps->legsAnim == BOTH_JUMPATTACK7) - { + // STAFF BACK+JUMP+ATTACK + else if (pm->ps->saberMove == LS_A_BACKFLIP_ATK && pm->ps->legsAnim == BOTH_JUMPATTACK7) { int aLen = PM_AnimLength(0, BOTH_JUMPATTACK7); - if ( pm->ps->legsTimer > 800 //not at end - && aLen - pm->ps->legsTimer >= 400 )//not in beginning - {//middle of anim - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? + if (pm->ps->legsTimer > 800 // not at end + && aLen - pm->ps->legsTimer >= 400) // not in beginning + { // middle of anim + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // still on ground? vec3_t yawAngles, backDir; - //push backwards some? - VectorSet( yawAngles, 0, pm->ps->viewangles[YAW]+180, 0 ); - AngleVectors( yawAngles, backDir, 0, 0 ); - VectorScale( backDir, 100, pm->ps->velocity ); + // push backwards some? + VectorSet(yawAngles, 0, pm->ps->viewangles[YAW] + 180, 0); + AngleVectors(yawAngles, backDir, 0, 0); + VectorScale(backDir, 100, pm->ps->velocity); - //jump! + // jump! pm->ps->velocity[2] = 300; - pm->ps->fd.forceJumpZStart = pm->ps->origin[2]; //so we don't take damage if we land at same height - //pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; + pm->ps->fd.forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + // pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? + // FIXME: NPCs yell? PM_AddEvent(EV_JUMP); - //G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); - ucmd->upmove = 0; //clear any actual jump command + // G_SoundOnEnt( ent, CHAN_BODY, "sound/weapons/force/jump.wav" ); + ucmd->upmove = 0; // clear any actual jump command } } ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; } - //STAFF/DUAL SPIN ATTACK - else if (pm->ps->saberMove == LS_SPINATTACK || - pm->ps->saberMove == LS_SPINATTACK_DUAL) - { + // STAFF/DUAL SPIN ATTACK + else if (pm->ps->saberMove == LS_SPINATTACK || pm->ps->saberMove == LS_SPINATTACK_DUAL) { ucmd->forwardmove = ucmd->rightmove = ucmd->upmove = 0; - //lock their viewangles during these attacks. + // lock their viewangles during these attacks. PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, ucmd); } } -//constrain him based on the angles of his vehicle and the caps -void PM_VehicleViewAngles(playerState_t *ps, bgEntity_t *veh, usercmd_t *ucmd) -{ +// constrain him based on the angles of his vehicle and the caps +void PM_VehicleViewAngles(playerState_t *ps, bgEntity_t *veh, usercmd_t *ucmd) { Vehicle_t *pVeh = veh->m_pVehicle; qboolean setAngles = qfalse; vec3_t clampMin; vec3_t clampMax; int i; - if ( veh->m_pVehicle->m_pPilot - && veh->m_pVehicle->m_pPilot->s.number == ps->clientNum ) - {//set the pilot's viewangles to the vehicle's viewangles + if (veh->m_pVehicle->m_pPilot && veh->m_pVehicle->m_pPilot->s.number == ps->clientNum) { // set the pilot's viewangles to the vehicle's viewangles #ifdef VEH_CONTROL_SCHEME_4 - if ( 1 ) -#else //VEH_CONTROL_SCHEME_4 - if ( !BG_UnrestrainedPitchRoll( ps, veh->m_pVehicle ) ) -#endif //VEH_CONTROL_SCHEME_4 - {//only if not if doing special free-roll/pitch control + if (1) +#else // VEH_CONTROL_SCHEME_4 + if (!BG_UnrestrainedPitchRoll(ps, veh->m_pVehicle)) +#endif // VEH_CONTROL_SCHEME_4 + { // only if not if doing special free-roll/pitch control setAngles = qtrue; clampMin[PITCH] = -pVeh->m_pVehicleInfo->lookPitch; clampMax[PITCH] = pVeh->m_pVehicleInfo->lookPitch; clampMin[YAW] = clampMax[YAW] = 0; clampMin[ROLL] = clampMax[ROLL] = -1; } - } - else - { - //NOTE: passengers can look around freely, UNLESS they're controlling a turret! - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - if ( veh->m_pVehicle->m_pVehicleInfo->turret[i].passengerNum == ps->generic1 ) - {//this turret is my station + } else { + // NOTE: passengers can look around freely, UNLESS they're controlling a turret! + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + if (veh->m_pVehicle->m_pVehicleInfo->turret[i].passengerNum == ps->generic1) { // this turret is my station setAngles = qtrue; clampMin[PITCH] = veh->m_pVehicle->m_pVehicleInfo->turret[i].pitchClampUp; clampMax[PITCH] = veh->m_pVehicle->m_pVehicleInfo->turret[i].pitchClampDown; @@ -9684,25 +8018,15 @@ void PM_VehicleViewAngles(playerState_t *ps, bgEntity_t *veh, usercmd_t *ucmd) } } } - if ( setAngles ) - { - for ( i = 0; i < 3; i++ ) - {//clamp viewangles - if ( clampMin[i] == -1 || clampMax[i] == -1 ) - {//no clamp - } - else if ( !clampMin[i] && !clampMax[i] ) - {//no allowance - //ps->viewangles[i] = veh->playerState->viewangles[i]; - } - else - {//allowance - if (ps->viewangles[i] > clampMax[i]) - { + if (setAngles) { + for (i = 0; i < 3; i++) { // clamp viewangles + if (clampMin[i] == -1 || clampMax[i] == -1) { // no clamp + } else if (!clampMin[i] && !clampMax[i]) { // no allowance + // ps->viewangles[i] = veh->playerState->viewangles[i]; + } else { // allowance + if (ps->viewangles[i] > clampMax[i]) { ps->viewangles[i] = clampMax[i]; - } - else if (ps->viewangles[i] < clampMin[i]) - { + } else if (ps->viewangles[i] < clampMin[i]) { ps->viewangles[i] = clampMin[i]; } } @@ -9741,58 +8065,49 @@ void PM_VehicleViewAngles(playerState_t *ps, bgEntity_t *veh, usercmd_t *ucmd) PM_SetPMViewAngle(ps, ps->viewangles, ucmd); } */ -//see if a weapon is ok to use on a vehicle -qboolean PM_WeaponOkOnVehicle( int weapon ) -{ - //FIXME: check g_vehicleInfo for our vehicle? - switch ( weapon ) - { - //case WP_NONE: +// see if a weapon is ok to use on a vehicle +qboolean PM_WeaponOkOnVehicle(int weapon) { + // FIXME: check g_vehicleInfo for our vehicle? + switch (weapon) { + // case WP_NONE: case WP_MELEE: case WP_SABER: case WP_BLASTER: - //case WP_THERMAL: + // case WP_THERMAL: return qtrue; break; } return qfalse; } -//do we have a weapon that's ok for using on the vehicle? -int PM_GetOkWeaponForVehicle(void) -{ +// do we have a weapon that's ok for using on the vehicle? +int PM_GetOkWeaponForVehicle(void) { int i = 0; - while (i < WP_NUM_WEAPONS) - { - if ((pm->ps->stats[STAT_WEAPONS] & (1 << i)) && - PM_WeaponOkOnVehicle(i)) - { //this one's good + while (i < WP_NUM_WEAPONS) { + if ((pm->ps->stats[STAT_WEAPONS] & (1 << i)) && PM_WeaponOkOnVehicle(i)) { // this one's good return i; } i++; } - //oh dear! - //assert(!"No valid veh weaps"); + // oh dear! + // assert(!"No valid veh weaps"); return -1; } -//force the vehicle to turn and travel to its forced destination point -void PM_VehForcedTurning(bgEntity_t *veh) -{ +// force the vehicle to turn and travel to its forced destination point +void PM_VehForcedTurning(bgEntity_t *veh) { bgEntity_t *dst = PM_BGEntForNum(veh->playerState->vehTurnaroundIndex); float pitchD, yawD; vec3_t dir; - if (!veh || !veh->m_pVehicle) - { + if (!veh || !veh->m_pVehicle) { return; } - if (!dst) - { //can't find dest ent? + if (!dst) { // can't find dest ent? return; } @@ -9806,8 +8121,8 @@ void PM_VehForcedTurning(bgEntity_t *veh) yawD = AngleSubtract(pm->ps->viewangles[YAW], dir[YAW]); pitchD = AngleSubtract(pm->ps->viewangles[PITCH], dir[PITCH]); - yawD *= 0.6f*pml.frametime; - pitchD *= 0.6f*pml.frametime; + yawD *= 0.6f * pml.frametime; + pitchD *= 0.6f * pml.frametime; #ifdef VEH_CONTROL_SCHEME_4 veh->playerState->viewangles[YAW] = AngleSubtract(veh->playerState->viewangles[YAW], yawD); @@ -9817,72 +8132,53 @@ void PM_VehForcedTurning(bgEntity_t *veh) PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); PM_SetPMViewAngle(veh->playerState, veh->playerState->viewangles, &pm->cmd); - VectorClear( veh->m_pVehicle->m_vPrevRiderViewAngles ); + VectorClear(veh->m_pVehicle->m_vPrevRiderViewAngles); veh->m_pVehicle->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(pm->ps->viewangles[YAW]); -#else //VEH_CONTROL_SCHEME_4 +#else // VEH_CONTROL_SCHEME_4 pm->ps->viewangles[YAW] = AngleSubtract(pm->ps->viewangles[YAW], yawD); pm->ps->viewangles[PITCH] = AngleSubtract(pm->ps->viewangles[PITCH], pitchD); PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); -#endif //VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 } #ifdef VEH_CONTROL_SCHEME_4 -void PM_VehFaceHyperspacePoint(bgEntity_t *veh) -{ +void PM_VehFaceHyperspacePoint(bgEntity_t *veh) { - if (!veh || !veh->m_pVehicle) - { + if (!veh || !veh->m_pVehicle) { return; - } - else - { - float timeFrac = ((float)(pm->cmd.serverTime-veh->playerState->hyperSpaceTime))/HYPERSPACE_TIME; - float turnRate, aDelta; - int i, matchedAxes = 0; + } else { + float timeFrac = ((float)(pm->cmd.serverTime - veh->playerState->hyperSpaceTime)) / HYPERSPACE_TIME; + float turnRate, aDelta; + int i, matchedAxes = 0; pm->cmd.upmove = veh->m_pVehicle->m_ucmd.upmove = 127; pm->cmd.forwardmove = veh->m_pVehicle->m_ucmd.forwardmove = 0; - pm->cmd.rightmove = veh->m_pVehicle->m_ucmd.rightmove = 0; - - turnRate = (90.0f*pml.frametime); - for ( i = 0; i < 3; i++ ) - { - aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], veh->m_pVehicle->m_vOrientation[i]); - if ( fabs( aDelta ) < turnRate ) - {//all is good - veh->playerState->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; - matchedAxes++; - } - else - { - aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], veh->playerState->viewangles[i]); - if ( fabs( aDelta ) < turnRate ) - { - veh->playerState->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; - } - else if ( aDelta > 0 ) - { - if ( i == YAW ) - { - veh->playerState->viewangles[i] = AngleNormalize360( veh->playerState->viewangles[i]+turnRate ); - } - else - { - veh->playerState->viewangles[i] = AngleNormalize180( veh->playerState->viewangles[i]+turnRate ); - } - } - else - { - if ( i == YAW ) - { - veh->playerState->viewangles[i] = AngleNormalize360( veh->playerState->viewangles[i]-turnRate ); + pm->cmd.rightmove = veh->m_pVehicle->m_ucmd.rightmove = 0; + + turnRate = (90.0f * pml.frametime); + for (i = 0; i < 3; i++) { + aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], veh->m_pVehicle->m_vOrientation[i]); + if (fabs(aDelta) < turnRate) { // all is good + veh->playerState->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; + matchedAxes++; + } else { + aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], veh->playerState->viewangles[i]); + if (fabs(aDelta) < turnRate) { + veh->playerState->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; + } else if (aDelta > 0) { + if (i == YAW) { + veh->playerState->viewangles[i] = AngleNormalize360(veh->playerState->viewangles[i] + turnRate); + } else { + veh->playerState->viewangles[i] = AngleNormalize180(veh->playerState->viewangles[i] + turnRate); } - else - { - veh->playerState->viewangles[i] = AngleNormalize180( veh->playerState->viewangles[i]-turnRate ); + } else { + if (i == YAW) { + veh->playerState->viewangles[i] = AngleNormalize360(veh->playerState->viewangles[i] - turnRate); + } else { + veh->playerState->viewangles[i] = AngleNormalize180(veh->playerState->viewangles[i] - turnRate); } } } @@ -9893,79 +8189,56 @@ void PM_VehFaceHyperspacePoint(bgEntity_t *veh) PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); PM_SetPMViewAngle(veh->playerState, veh->playerState->viewangles, &pm->cmd); - VectorClear( veh->m_pVehicle->m_vPrevRiderViewAngles ); + VectorClear(veh->m_pVehicle->m_vPrevRiderViewAngles); veh->m_pVehicle->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(pm->ps->viewangles[YAW]); - if ( timeFrac < HYPERSPACE_TELEPORT_FRAC ) - {//haven't gone through yet - if ( matchedAxes < 3 ) - {//not facing the right dir yet - //keep hyperspace time up to date + if (timeFrac < HYPERSPACE_TELEPORT_FRAC) { // haven't gone through yet + if (matchedAxes < 3) { // not facing the right dir yet + // keep hyperspace time up to date veh->playerState->hyperSpaceTime += pml.msec; - } - else if ( !(veh->playerState->eFlags2&EF2_HYPERSPACE)) - {//flag us as ready to hyperspace! + } else if (!(veh->playerState->eFlags2 & EF2_HYPERSPACE)) { // flag us as ready to hyperspace! veh->playerState->eFlags2 |= EF2_HYPERSPACE; } } } } -#else //VEH_CONTROL_SCHEME_4 +#else // VEH_CONTROL_SCHEME_4 -void PM_VehFaceHyperspacePoint(bgEntity_t *veh) -{ +void PM_VehFaceHyperspacePoint(bgEntity_t *veh) { - if (!veh || !veh->m_pVehicle) - { + if (!veh || !veh->m_pVehicle) { return; - } - else - { - float timeFrac = ((float)(pm->cmd.serverTime-veh->playerState->hyperSpaceTime))/HYPERSPACE_TIME; - float turnRate, aDelta; - int i, matchedAxes = 0; + } else { + float timeFrac = ((float)(pm->cmd.serverTime - veh->playerState->hyperSpaceTime)) / HYPERSPACE_TIME; + float turnRate, aDelta; + int i, matchedAxes = 0; pm->cmd.upmove = veh->m_pVehicle->m_ucmd.upmove = 127; pm->cmd.forwardmove = veh->m_pVehicle->m_ucmd.forwardmove = 0; pm->cmd.rightmove = veh->m_pVehicle->m_ucmd.rightmove = 0; - turnRate = (90.0f*pml.frametime); - for ( i = 0; i < 3; i++ ) - { + turnRate = (90.0f * pml.frametime); + for (i = 0; i < 3; i++) { aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], veh->m_pVehicle->m_vOrientation[i]); - if ( fabs( aDelta ) < turnRate ) - {//all is good + if (fabs(aDelta) < turnRate) { // all is good pm->ps->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; matchedAxes++; - } - else - { + } else { aDelta = AngleSubtract(veh->playerState->hyperSpaceAngles[i], pm->ps->viewangles[i]); - if ( fabs( aDelta ) < turnRate ) - { + if (fabs(aDelta) < turnRate) { pm->ps->viewangles[i] = veh->playerState->hyperSpaceAngles[i]; - } - else if ( aDelta > 0 ) - { - if ( i == YAW ) - { - pm->ps->viewangles[i] = AngleNormalize360( pm->ps->viewangles[i]+turnRate ); - } - else - { - pm->ps->viewangles[i] = AngleNormalize180( pm->ps->viewangles[i]+turnRate ); - } - } - else - { - if ( i == YAW ) - { - pm->ps->viewangles[i] = AngleNormalize360( pm->ps->viewangles[i]-turnRate ); + } else if (aDelta > 0) { + if (i == YAW) { + pm->ps->viewangles[i] = AngleNormalize360(pm->ps->viewangles[i] + turnRate); + } else { + pm->ps->viewangles[i] = AngleNormalize180(pm->ps->viewangles[i] + turnRate); } - else - { - pm->ps->viewangles[i] = AngleNormalize180( pm->ps->viewangles[i]-turnRate ); + } else { + if (i == YAW) { + pm->ps->viewangles[i] = AngleNormalize360(pm->ps->viewangles[i] - turnRate); + } else { + pm->ps->viewangles[i] = AngleNormalize180(pm->ps->viewangles[i] - turnRate); } } } @@ -9973,105 +8246,84 @@ void PM_VehFaceHyperspacePoint(bgEntity_t *veh) PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - if ( timeFrac < HYPERSPACE_TELEPORT_FRAC ) - {//haven't gone through yet - if ( matchedAxes < 3 ) - {//not facing the right dir yet - //keep hyperspace time up to date + if (timeFrac < HYPERSPACE_TELEPORT_FRAC) { // haven't gone through yet + if (matchedAxes < 3) { // not facing the right dir yet + // keep hyperspace time up to date veh->playerState->hyperSpaceTime += pml.msec; - } - else if ( !(veh->playerState->eFlags2&EF2_HYPERSPACE)) - {//flag us as ready to hyperspace! + } else if (!(veh->playerState->eFlags2 & EF2_HYPERSPACE)) { // flag us as ready to hyperspace! veh->playerState->eFlags2 |= EF2_HYPERSPACE; } } } } -#endif //VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 -void BG_VehicleAdjustBBoxForOrientation( Vehicle_t *veh, vec3_t origin, vec3_t mins, vec3_t maxs, - int clientNum, int tracemask, - void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask)) -{ - if ( !veh - || !veh->m_pVehicleInfo->length - || !veh->m_pVehicleInfo->width - || !veh->m_pVehicleInfo->height ) - //|| veh->m_LandTrace.fraction < 1.0f ) +void BG_VehicleAdjustBBoxForOrientation(Vehicle_t *veh, vec3_t origin, vec3_t mins, vec3_t maxs, int clientNum, int tracemask, + void (*localTrace)(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, + int passEntityNum, int contentMask)) { + if (!veh || !veh->m_pVehicleInfo->length || !veh->m_pVehicleInfo->width || !veh->m_pVehicleInfo->height) + //|| veh->m_LandTrace.fraction < 1.0f ) { return; - } - else if ( veh->m_pVehicleInfo->type != VH_FIGHTER - //&& veh->m_pVehicleInfo->type != VH_SPEEDER - && veh->m_pVehicleInfo->type != VH_FLIER ) - {//only those types of vehicles have dynamic bboxes, the rest just use a static bbox - VectorSet( maxs, veh->m_pVehicleInfo->width/2.0f, veh->m_pVehicleInfo->width/2.0f, veh->m_pVehicleInfo->height+DEFAULT_MINS_2 ); - VectorSet( mins, veh->m_pVehicleInfo->width/-2.0f, veh->m_pVehicleInfo->width/-2.0f, DEFAULT_MINS_2 ); + } else if (veh->m_pVehicleInfo->type != VH_FIGHTER + //&& veh->m_pVehicleInfo->type != VH_SPEEDER + && veh->m_pVehicleInfo->type != VH_FLIER) { // only those types of vehicles have dynamic bboxes, the rest just use a static bbox + VectorSet(maxs, veh->m_pVehicleInfo->width / 2.0f, veh->m_pVehicleInfo->width / 2.0f, veh->m_pVehicleInfo->height + DEFAULT_MINS_2); + VectorSet(mins, veh->m_pVehicleInfo->width / -2.0f, veh->m_pVehicleInfo->width / -2.0f, DEFAULT_MINS_2); return; - } - else - { - matrix3_t axis; - vec3_t point[8], newMins, newMaxs; - int curAxis = 0, i; - trace_t trace; - - AnglesToAxis( veh->m_vOrientation, axis ); - VectorMA( origin, veh->m_pVehicleInfo->length/2.0f, axis[0], point[0] ); - VectorMA( origin, -veh->m_pVehicleInfo->length/2.0f, axis[0], point[1] ); - //extrapolate each side up and down - VectorMA( point[0], veh->m_pVehicleInfo->height/2.0f, axis[2], point[0] ); - VectorMA( point[0], -veh->m_pVehicleInfo->height, axis[2], point[2] ); - VectorMA( point[1], veh->m_pVehicleInfo->height/2.0f, axis[2], point[1] ); - VectorMA( point[1], -veh->m_pVehicleInfo->height, axis[2], point[3] ); - - VectorMA( origin, veh->m_pVehicleInfo->width/2.0f, axis[1], point[4] ); - VectorMA( origin, -veh->m_pVehicleInfo->width/2.0f, axis[1], point[5] ); - //extrapolate each side up and down - VectorMA( point[4], veh->m_pVehicleInfo->height/2.0f, axis[2], point[4] ); - VectorMA( point[4], -veh->m_pVehicleInfo->height, axis[2], point[6] ); - VectorMA( point[5], veh->m_pVehicleInfo->height/2.0f, axis[2], point[5] ); - VectorMA( point[5], -veh->m_pVehicleInfo->height, axis[2], point[7] ); + } else { + matrix3_t axis; + vec3_t point[8], newMins, newMaxs; + int curAxis = 0, i; + trace_t trace; + + AnglesToAxis(veh->m_vOrientation, axis); + VectorMA(origin, veh->m_pVehicleInfo->length / 2.0f, axis[0], point[0]); + VectorMA(origin, -veh->m_pVehicleInfo->length / 2.0f, axis[0], point[1]); + // extrapolate each side up and down + VectorMA(point[0], veh->m_pVehicleInfo->height / 2.0f, axis[2], point[0]); + VectorMA(point[0], -veh->m_pVehicleInfo->height, axis[2], point[2]); + VectorMA(point[1], veh->m_pVehicleInfo->height / 2.0f, axis[2], point[1]); + VectorMA(point[1], -veh->m_pVehicleInfo->height, axis[2], point[3]); + + VectorMA(origin, veh->m_pVehicleInfo->width / 2.0f, axis[1], point[4]); + VectorMA(origin, -veh->m_pVehicleInfo->width / 2.0f, axis[1], point[5]); + // extrapolate each side up and down + VectorMA(point[4], veh->m_pVehicleInfo->height / 2.0f, axis[2], point[4]); + VectorMA(point[4], -veh->m_pVehicleInfo->height, axis[2], point[6]); + VectorMA(point[5], veh->m_pVehicleInfo->height / 2.0f, axis[2], point[5]); + VectorMA(point[5], -veh->m_pVehicleInfo->height, axis[2], point[7]); /* VectorMA( origin, veh->m_pVehicleInfo->height/2.0f, axis[2], point[4] ); VectorMA( origin, -veh->m_pVehicleInfo->height/2.0f, axis[2], point[5] ); */ - //Now inflate a bbox around these points - VectorCopy( origin, newMins ); - VectorCopy( origin, newMaxs ); - for ( curAxis = 0; curAxis < 3; curAxis++ ) - { - for ( i = 0; i < 8; i++ ) - { - if ( point[i][curAxis] > newMaxs[curAxis] ) - { + // Now inflate a bbox around these points + VectorCopy(origin, newMins); + VectorCopy(origin, newMaxs); + for (curAxis = 0; curAxis < 3; curAxis++) { + for (i = 0; i < 8; i++) { + if (point[i][curAxis] > newMaxs[curAxis]) { newMaxs[curAxis] = point[i][curAxis]; - } - else if ( point[i][curAxis] < newMins[curAxis] ) - { + } else if (point[i][curAxis] < newMins[curAxis]) { newMins[curAxis] = point[i][curAxis]; } } } - VectorSubtract( newMins, origin, newMins ); - VectorSubtract( newMaxs, origin, newMaxs ); - //now see if that's a valid way to be - if (localTrace) - { - localTrace( &trace, origin, newMins, newMaxs, origin, clientNum, tracemask ); - } - else - { //don't care about solid stuff then + VectorSubtract(newMins, origin, newMins); + VectorSubtract(newMaxs, origin, newMaxs); + // now see if that's a valid way to be + if (localTrace) { + localTrace(&trace, origin, newMins, newMaxs, origin, clientNum, tracemask); + } else { // don't care about solid stuff then trace.startsolid = trace.allsolid = 0; } - if ( !trace.startsolid && !trace.allsolid ) - {//let's use it! - VectorCopy( newMins, mins ); - VectorCopy( newMaxs, maxs ); + if (!trace.startsolid && !trace.allsolid) { // let's use it! + VectorCopy(newMins, mins); + VectorCopy(newMaxs, maxs); } - //else: just use the last one, I guess...? - //FIXME: make it as close as possible? Or actually prevent the change in m_vOrientation? Or push away from anything we hit? + // else: just use the last one, I guess...? + // FIXME: make it as close as possible? Or actually prevent the change in m_vOrientation? Or push away from anything we hit? } } /* @@ -10082,95 +8334,69 @@ PmoveSingle */ extern int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); extern qboolean BG_FighterUpdate(Vehicle_t *pVeh, const usercmd_t *pUcmd, vec3_t trMins, vec3_t trMaxs, float gravity, - void (*traceFunc)( trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, int passEntityNum, int contentMask )); //FighterNPC.c + void (*traceFunc)(trace_t *results, const vec3_t start, const vec3_t lmins, const vec3_t lmaxs, const vec3_t end, + int passEntityNum, int contentMask)); // FighterNPC.c -#define JETPACK_HOVER_HEIGHT 64 +#define JETPACK_HOVER_HEIGHT 64 //#define _TESTING_VEH_PREDICTION -void PM_MoveForKata(usercmd_t *ucmd) -{ - if ( pm->ps->legsAnim == BOTH_A7_SOULCAL - && pm->ps->saberMove == LS_STAFF_SOULCAL ) - {//forward spinning staff attack +void PM_MoveForKata(usercmd_t *ucmd) { + if (pm->ps->legsAnim == BOTH_A7_SOULCAL && pm->ps->saberMove == LS_STAFF_SOULCAL) { // forward spinning staff attack ucmd->upmove = 0; - if ( PM_CanRollFromSoulCal( pm->ps ) ) - { + if (PM_CanRollFromSoulCal(pm->ps)) { ucmd->upmove = -127; ucmd->rightmove = 0; - if (ucmd->forwardmove < 0) - { + if (ucmd->forwardmove < 0) { ucmd->forwardmove = 0; } - } - else - { + } else { ucmd->rightmove = 0; - //FIXME: don't slide off people/obstacles? - if ( pm->ps->legsTimer >= 2750 ) - {//not at end - //push forward + // FIXME: don't slide off people/obstacles? + if (pm->ps->legsTimer >= 2750) { // not at end + // push forward ucmd->forwardmove = 64; - } - else - { + } else { ucmd->forwardmove = 0; } } - if ( pm->ps->legsTimer >= 2650 - && pm->ps->legsTimer < 2850 ) - {//the jump - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//still on ground? - //jump! + if (pm->ps->legsTimer >= 2650 && pm->ps->legsTimer < 2850) { // the jump + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // still on ground? + // jump! pm->ps->velocity[2] = 250; - pm->ps->fd.forceJumpZStart = pm->ps->origin[2];//so we don't take damage if we land at same height - // pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; - //FIXME: NPCs yell? + pm->ps->fd.forceJumpZStart = pm->ps->origin[2]; // so we don't take damage if we land at same height + // pm->ps->pm_flags |= PMF_JUMPING;//|PMF_SLOW_MO_FALL; + // FIXME: NPCs yell? PM_AddEvent(EV_JUMP); } } - } - else if (pm->ps->legsAnim == BOTH_A2_SPECIAL) - { //medium kata + } else if (pm->ps->legsAnim == BOTH_A2_SPECIAL) { // medium kata pm->cmd.rightmove = 0; pm->cmd.upmove = 0; - if (pm->ps->legsTimer < 2700 && pm->ps->legsTimer > 2300) - { + if (pm->ps->legsTimer < 2700 && pm->ps->legsTimer > 2300) { pm->cmd.forwardmove = 127; - } - else if (pm->ps->legsTimer < 900 && pm->ps->legsTimer > 500) - { + } else if (pm->ps->legsTimer < 900 && pm->ps->legsTimer > 500) { pm->cmd.forwardmove = 127; - } - else - { + } else { pm->cmd.forwardmove = 0; } - } - else if (pm->ps->legsAnim == BOTH_A3_SPECIAL) - { //strong kata + } else if (pm->ps->legsAnim == BOTH_A3_SPECIAL) { // strong kata pm->cmd.rightmove = 0; pm->cmd.upmove = 0; - if (pm->ps->legsTimer < 1700 && pm->ps->legsTimer > 1000) - { + if (pm->ps->legsTimer < 1700 && pm->ps->legsTimer > 1000) { pm->cmd.forwardmove = 127; - } - else - { + } else { pm->cmd.forwardmove = 0; } - } - else - { + } else { pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; pm->cmd.upmove = 0; } } -void PmoveSingle (pmove_t *pmove) { +void PmoveSingle(pmove_t *pmove) { qboolean stiffenedUp = qfalse; float gDist = 0; qboolean noAnimate = qfalse; @@ -10178,41 +8404,31 @@ void PmoveSingle (pmove_t *pmove) { pm = pmove; - if (pm->cmd.buttons & BUTTON_ATTACK && pm->cmd.buttons & BUTTON_USE_HOLDABLE) - { + if (pm->cmd.buttons & BUTTON_ATTACK && pm->cmd.buttons & BUTTON_USE_HOLDABLE) { pm->cmd.buttons &= ~BUTTON_ATTACK; pm->cmd.buttons &= ~BUTTON_USE_HOLDABLE; } - if (pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->cmd.buttons & BUTTON_USE_HOLDABLE) - { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK && pm->cmd.buttons & BUTTON_USE_HOLDABLE) { pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; pm->cmd.buttons &= ~BUTTON_USE_HOLDABLE; } - if (pm->ps->emplacedIndex) - { - if (pm->cmd.buttons & BUTTON_ALT_ATTACK) - { //hackerrific. + if (pm->ps->emplacedIndex) { + if (pm->cmd.buttons & BUTTON_ALT_ATTACK) { // hackerrific. pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; pm->cmd.buttons |= BUTTON_ATTACK; } } - //set up these "global" bg ents + // set up these "global" bg ents pm_entSelf = PM_BGEntForNum(pm->ps->clientNum); - if (pm->ps->m_iVehicleNum) - { - if (pm->ps->clientNum < MAX_CLIENTS) - { //player riding vehicle + if (pm->ps->m_iVehicleNum) { + if (pm->ps->clientNum < MAX_CLIENTS) { // player riding vehicle pm_entVeh = PM_BGEntForNum(pm->ps->m_iVehicleNum); + } else { // vehicle with player pilot + pm_entVeh = PM_BGEntForNum(pm->ps->m_iVehicleNum - 1); } - else - { //vehicle with player pilot - pm_entVeh = PM_BGEntForNum(pm->ps->m_iVehicleNum-1); - } - } - else - { //no vehicle ent + } else { // no vehicle ent pm_entVeh = NULL; } @@ -10227,144 +8443,84 @@ void PmoveSingle (pmove_t *pmove) { pm->watertype = 0; pm->waterlevel = 0; - if (PM_IsRocketTrooper()) - { //kind of nasty, don't let them crouch or anything if nonhumanoid (probably a rockettrooper) - if (pm->cmd.upmove < 0) - { + if (PM_IsRocketTrooper()) { // kind of nasty, don't let them crouch or anything if nonhumanoid (probably a rockettrooper) + if (pm->cmd.upmove < 0) { pm->cmd.upmove = 0; } } - if (pm->ps->pm_type == PM_FLOAT) - { //You get no control over where you go in grip movement + if (pm->ps->pm_type == PM_FLOAT) { // You get no control over where you go in grip movement stiffenedUp = qtrue; - } - else if (pm->ps->eFlags & EF_DISINTEGRATION) - { + } else if (pm->ps->eFlags & EF_DISINTEGRATION) { stiffenedUp = qtrue; - } - else if ( BG_SaberLockBreakAnim( pm->ps->legsAnim ) - || BG_SaberLockBreakAnim( pm->ps->torsoAnim ) - || pm->ps->saberLockTime >= pm->cmd.serverTime ) - {//can't move or turn + } else if (BG_SaberLockBreakAnim(pm->ps->legsAnim) || BG_SaberLockBreakAnim(pm->ps->torsoAnim) || + pm->ps->saberLockTime >= pm->cmd.serverTime) { // can't move or turn stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - } - else if ( pm->ps->saberMove == LS_A_BACK || pm->ps->saberMove == LS_A_BACK_CR || - pm->ps->saberMove == LS_A_BACKSTAB || pm->ps->saberMove == LS_A_FLIP_STAB || - pm->ps->saberMove == LS_A_FLIP_SLASH || pm->ps->saberMove == LS_A_JUMP_T__B_ || - pm->ps->saberMove == LS_DUAL_LR || pm->ps->saberMove == LS_DUAL_FB) - { - if (pm->ps->legsAnim == BOTH_JUMPFLIPSTABDOWN || - pm->ps->legsAnim == BOTH_JUMPFLIPSLASHDOWN1) - { //flipover medium stance attack - if (pm->ps->legsTimer < 1600 && pm->ps->legsTimer > 900) - { - pm->ps->viewangles[YAW] += pml.frametime*240.0f; + } else if (pm->ps->saberMove == LS_A_BACK || pm->ps->saberMove == LS_A_BACK_CR || pm->ps->saberMove == LS_A_BACKSTAB || + pm->ps->saberMove == LS_A_FLIP_STAB || pm->ps->saberMove == LS_A_FLIP_SLASH || pm->ps->saberMove == LS_A_JUMP_T__B_ || + pm->ps->saberMove == LS_DUAL_LR || pm->ps->saberMove == LS_DUAL_FB) { + if (pm->ps->legsAnim == BOTH_JUMPFLIPSTABDOWN || pm->ps->legsAnim == BOTH_JUMPFLIPSLASHDOWN1) { // flipover medium stance attack + if (pm->ps->legsTimer < 1600 && pm->ps->legsTimer > 900) { + pm->ps->viewangles[YAW] += pml.frametime * 240.0f; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); } } stiffenedUp = qtrue; - } - else if ((pm->ps->legsAnim) == (BOTH_A2_STABBACK1) || - (pm->ps->legsAnim) == (BOTH_ATTACK_BACK) || - (pm->ps->legsAnim) == (BOTH_CROUCHATTACKBACK1) || - (pm->ps->legsAnim) == (BOTH_FORCELEAP2_T__B_) || - (pm->ps->legsAnim) == (BOTH_JUMPFLIPSTABDOWN) || - (pm->ps->legsAnim) == (BOTH_JUMPFLIPSLASHDOWN1)) - { + } else if ((pm->ps->legsAnim) == (BOTH_A2_STABBACK1) || (pm->ps->legsAnim) == (BOTH_ATTACK_BACK) || (pm->ps->legsAnim) == (BOTH_CROUCHATTACKBACK1) || + (pm->ps->legsAnim) == (BOTH_FORCELEAP2_T__B_) || (pm->ps->legsAnim) == (BOTH_JUMPFLIPSTABDOWN) || + (pm->ps->legsAnim) == (BOTH_JUMPFLIPSLASHDOWN1)) { stiffenedUp = qtrue; - } - else if (pm->ps->legsAnim == BOTH_ROLL_STAB) - { + } else if (pm->ps->legsAnim == BOTH_ROLL_STAB) { stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - } - else if (pm->ps->heldByClient) - { + } else if (pm->ps->heldByClient) { stiffenedUp = qtrue; - } - else if (BG_KickMove(pm->ps->saberMove) || BG_KickingAnim(pm->ps->legsAnim)) - { + } else if (BG_KickMove(pm->ps->saberMove) || BG_KickingAnim(pm->ps->legsAnim)) { stiffenedUp = qtrue; - } - else if (BG_InGrappleMove(pm->ps->torsoAnim)) - { + } else if (BG_InGrappleMove(pm->ps->torsoAnim)) { stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - } - else if ( pm->ps->saberMove == LS_STABDOWN_DUAL || - pm->ps->saberMove == LS_STABDOWN_STAFF || - pm->ps->saberMove == LS_STABDOWN) - {//FIXME: need to only move forward until we bump into our target...? - if (pm->ps->legsTimer < 800) - { //freeze movement near end of anim + } else if (pm->ps->saberMove == LS_STABDOWN_DUAL || pm->ps->saberMove == LS_STABDOWN_STAFF || + pm->ps->saberMove == LS_STABDOWN) { // FIXME: need to only move forward until we bump into our target...? + if (pm->ps->legsTimer < 800) { // freeze movement near end of anim stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - } - else - { //force forward til then - pm->cmd.rightmove = 0; + } else { // force forward til then + pm->cmd.rightmove = 0; pm->cmd.upmove = 0; pm->cmd.forwardmove = 64; } - } - else if (pm->ps->saberMove == LS_PULL_ATTACK_STAB || - pm->ps->saberMove == LS_PULL_ATTACK_SWING) - { + } else if (pm->ps->saberMove == LS_PULL_ATTACK_STAB || pm->ps->saberMove == LS_PULL_ATTACK_SWING) { stiffenedUp = qtrue; - } - else if (BG_SaberInKata(pm->ps->saberMove) || - BG_InKataAnim(pm->ps->torsoAnim) || - BG_InKataAnim(pm->ps->legsAnim)) - { + } else if (BG_SaberInKata(pm->ps->saberMove) || BG_InKataAnim(pm->ps->torsoAnim) || BG_InKataAnim(pm->ps->legsAnim)) { PM_MoveForKata(&pm->cmd); - } - else if ( BG_FullBodyTauntAnim( pm->ps->legsAnim ) - && BG_FullBodyTauntAnim( pm->ps->torsoAnim ) ) - { - if ( (pm->cmd.buttons&BUTTON_ATTACK) - || (pm->cmd.buttons&BUTTON_ALT_ATTACK) - || (pm->cmd.buttons&BUTTON_FORCEPOWER) - || (pm->cmd.buttons&BUTTON_FORCEGRIP) - || (pm->cmd.buttons&BUTTON_FORCE_LIGHTNING) - || (pm->cmd.buttons&BUTTON_FORCE_DRAIN) - || pm->cmd.upmove ) - {//stop the anim - if ( pm->ps->legsAnim == BOTH_MEDITATE - && pm->ps->torsoAnim == BOTH_MEDITATE ) - { - PM_SetAnim( SETANIM_BOTH, BOTH_MEDITATE_END, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - { + } else if (BG_FullBodyTauntAnim(pm->ps->legsAnim) && BG_FullBodyTauntAnim(pm->ps->torsoAnim)) { + if ((pm->cmd.buttons & BUTTON_ATTACK) || (pm->cmd.buttons & BUTTON_ALT_ATTACK) || (pm->cmd.buttons & BUTTON_FORCEPOWER) || + (pm->cmd.buttons & BUTTON_FORCEGRIP) || (pm->cmd.buttons & BUTTON_FORCE_LIGHTNING) || (pm->cmd.buttons & BUTTON_FORCE_DRAIN) || + pm->cmd.upmove) { // stop the anim + if (pm->ps->legsAnim == BOTH_MEDITATE && pm->ps->torsoAnim == BOTH_MEDITATE) { + PM_SetAnim(SETANIM_BOTH, BOTH_MEDITATE_END, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { pm->ps->legsTimer = pm->ps->torsoTimer = 0; } - if ( pm->ps->forceHandExtend == HANDEXTEND_TAUNT ) - { + if (pm->ps->forceHandExtend == HANDEXTEND_TAUNT) { pm->ps->forceHandExtend = 0; } - } - else - { - if ( pm->ps->legsAnim == BOTH_MEDITATE ) - { - if ( pm->ps->legsTimer < 100 ) - { + } else { + if (pm->ps->legsAnim == BOTH_MEDITATE) { + if (pm->ps->legsTimer < 100) { pm->ps->legsTimer = 100; } } - if ( pm->ps->torsoAnim == BOTH_MEDITATE ) - { - if ( pm->ps->torsoTimer < 100 ) - { + if (pm->ps->torsoAnim == BOTH_MEDITATE) { + if (pm->ps->torsoTimer < 100) { pm->ps->legsTimer = 100; } pm->ps->forceHandExtend = HANDEXTEND_TAUNT; pm->ps->forceHandExtendTime = pm->cmd.serverTime + 100; } - if ( pm->ps->legsTimer > 0 || pm->ps->torsoTimer > 0 ) - { + if (pm->ps->legsTimer > 0 || pm->ps->torsoTimer > 0) { stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); pm->cmd.rightmove = 0; @@ -10373,42 +8529,29 @@ void PmoveSingle (pmove_t *pmove) { pm->cmd.buttons = 0; } } - } - else if ( pm->ps->legsAnim == BOTH_MEDITATE_END - && pm->ps->legsTimer > 0 ) - { + } else if (pm->ps->legsAnim == BOTH_MEDITATE_END && pm->ps->legsTimer > 0) { stiffenedUp = qtrue; PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); - pm->cmd.rightmove = 0; + pm->cmd.rightmove = 0; pm->cmd.upmove = 0; pm->cmd.forwardmove = 0; pm->cmd.buttons = 0; - } - else if (pm->ps->legsAnim == BOTH_FORCELAND1 || - pm->ps->legsAnim == BOTH_FORCELANDBACK1 || - pm->ps->legsAnim == BOTH_FORCELANDRIGHT1 || - pm->ps->legsAnim == BOTH_FORCELANDLEFT1) - { //can't move while in a force land + } else if (pm->ps->legsAnim == BOTH_FORCELAND1 || pm->ps->legsAnim == BOTH_FORCELANDBACK1 || pm->ps->legsAnim == BOTH_FORCELANDRIGHT1 || + pm->ps->legsAnim == BOTH_FORCELANDLEFT1) { // can't move while in a force land stiffenedUp = qtrue; } - if ( pm->ps->saberMove == LS_A_LUNGE ) - {//can't move during lunge + if (pm->ps->saberMove == LS_A_LUNGE) { // can't move during lunge pm->cmd.rightmove = pm->cmd.upmove = 0; - if ( pm->ps->legsTimer > 500 ) - { + if (pm->ps->legsTimer > 500) { pm->cmd.forwardmove = 127; - } - else - { + } else { pm->cmd.forwardmove = 0; } } - if ( pm->ps->saberMove == LS_A_JUMP_T__B_ ) - {//can't move during leap - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//hit the ground + if (pm->ps->saberMove == LS_A_JUMP_T__B_) { // can't move during leap + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // hit the ground pm->cmd.forwardmove = 0; } pm->cmd.rightmove = pm->cmd.upmove = 0; @@ -10422,15 +8565,11 @@ void PmoveSingle (pmove_t *pmove) { } #endif - if (pm->ps->emplacedIndex) - { - if (pm->cmd.forwardmove < 0 || PM_GroundDistance() > 32.0f) - { + if (pm->ps->emplacedIndex) { + if (pm->cmd.forwardmove < 0 || PM_GroundDistance() > 32.0f) { pm->ps->emplacedIndex = 0; pm->ps->saberHolstered = 0; - } - else - { + } else { stiffenedUp = qtrue; } } @@ -10447,90 +8586,74 @@ void PmoveSingle (pmove_t *pmove) { } */ - if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->weaponstate == WEAPON_CHARGING_ALT) - { //not allowed to move while charging the disruptor - if (pm->cmd.forwardmove || - pm->cmd.rightmove || - pm->cmd.upmove > 0) - { //get out + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->weaponstate == WEAPON_CHARGING_ALT) { // not allowed to move while charging the disruptor + if (pm->cmd.forwardmove || pm->cmd.rightmove || pm->cmd.upmove > 0) { // get out pm->ps->weaponstate = WEAPON_READY; pm->ps->weaponTime = 1000; - PM_AddEventWithParm(EV_WEAPON_CHARGE, WP_DISRUPTOR); //cut the weapon charge sound + PM_AddEventWithParm(EV_WEAPON_CHARGE, WP_DISRUPTOR); // cut the weapon charge sound pm->cmd.upmove = 0; } - } - else if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) - { //can't jump - if (pm->cmd.upmove > 0) - { + } else if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { // can't jump + if (pm->cmd.upmove > 0) { pm->cmd.upmove = 0; } } - if (stiffenedUp) - { + if (stiffenedUp) { pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; pm->cmd.upmove = 0; } - if (pm->ps->fd.forceGripCripple) - { //don't let attack or alt attack if being gripped I guess + if (pm->ps->fd.forceGripCripple) { // don't let attack or alt attack if being gripped I guess pm->cmd.buttons &= ~BUTTON_ATTACK; pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } - if ( BG_InRoll( pm->ps, pm->ps->legsAnim ) ) - { //can't roll unless you're able to move normally - BG_CmdForRoll( pm->ps, pm->ps->legsAnim, &pm->cmd ); + if (BG_InRoll(pm->ps, pm->ps->legsAnim)) { // can't roll unless you're able to move normally + BG_CmdForRoll(pm->ps, pm->ps->legsAnim, &pm->cmd); } PM_CmdForSaberMoves(&pm->cmd); BG_AdjustClientSpeed(pm->ps, &pm->cmd, pm->cmd.serverTime); - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) { - pm->tracemask &= ~CONTENTS_BODY; // corpses can fly through bodies + if (pm->ps->stats[STAT_HEALTH] <= 0) { + pm->tracemask &= ~CONTENTS_BODY; // corpses can fly through bodies } // make sure walking button is clear if they are running, to avoid // proxy no-footsteps cheats - if ( abs( pm->cmd.forwardmove ) > 64 || abs( pm->cmd.rightmove ) > 64 ) { + if (abs(pm->cmd.forwardmove) > 64 || abs(pm->cmd.rightmove) > 64) { pm->cmd.buttons &= ~BUTTON_WALKING; } // set the talk balloon flag - if ( pm->cmd.buttons & BUTTON_TALK ) { + if (pm->cmd.buttons & BUTTON_TALK) { pm->ps->eFlags |= EF_TALK; } else { pm->ps->eFlags &= ~EF_TALK; } pm_cancelOutZoom = qfalse; - if (pm->ps->weapon == WP_DISRUPTOR && - pm->ps->zoomMode == 1) - { - if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && - !(pm->cmd.buttons & BUTTON_ATTACK) && - pm->ps->zoomLocked) - { + if (pm->ps->weapon == WP_DISRUPTOR && pm->ps->zoomMode == 1) { + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) && !(pm->cmd.buttons & BUTTON_ATTACK) && pm->ps->zoomLocked) { pm_cancelOutZoom = qtrue; } } // In certain situations, we may want to control which attack buttons are pressed and what kind of functionality // is attached to them - PM_AdjustAttackStates( pm ); + PM_AdjustAttackStates(pm); // clear the respawned flag if attack and use are cleared - if ( pm->ps->stats[STAT_HEALTH] > 0 && - !( pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_USE_HOLDABLE) ) ) { + if (pm->ps->stats[STAT_HEALTH] > 0 && !(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_USE_HOLDABLE))) { pm->ps->pm_flags &= ~PMF_RESPAWNED; } // if talk button is down, dissallow all other input // this is to prevent any possible intercept proxy from // adding fake talk balloons - if ( pmove->cmd.buttons & BUTTON_TALK ) { + if (pmove->cmd.buttons & BUTTON_TALK) { // keep the talk button set tho for when the cmd.serverTime > 66 msec // and the same cmd is used multiple times in Pmove pmove->cmd.buttons = BUTTON_TALK; @@ -10540,13 +8663,13 @@ void PmoveSingle (pmove_t *pmove) { } // clear all pmove local vars - memset (&pml, 0, sizeof(pml)); + memset(&pml, 0, sizeof(pml)); // determine the time pml.msec = pmove->cmd.serverTime - pm->ps->commandTime; - if ( pml.msec < 1 ) { + if (pml.msec < 1) { pml.msec = 1; - } else if ( pml.msec > 200 ) { + } else if (pml.msec > 200) { pml.msec = 200; } @@ -10564,69 +8687,53 @@ void PmoveSingle (pmove_t *pmove) { pm->ps->commandTime = pmove->cmd.serverTime; // save old org in case we get stuck - VectorCopy (pm->ps->origin, pml.previous_origin); + VectorCopy(pm->ps->origin, pml.previous_origin); // save old velocity for crashlanding - VectorCopy (pm->ps->velocity, pml.previous_velocity); + VectorCopy(pm->ps->velocity, pml.previous_velocity); pml.frametime = pml.msec * 0.001; - if (pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_VEHICLE) - { //we are a vehicle + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_VEHICLE) { // we are a vehicle bgEntity_t *veh = pm_entSelf; - assert( veh && veh->m_pVehicle); - if ( veh && veh->m_pVehicle ) - { - veh->m_pVehicle->m_fTimeModifier = pml.frametime*60.0f; + assert(veh && veh->m_pVehicle); + if (veh && veh->m_pVehicle) { + veh->m_pVehicle->m_fTimeModifier = pml.frametime * 60.0f; } - } - else if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pm->ps->m_iVehicleNum) - { + } else if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->m_iVehicleNum) { bgEntity_t *veh = pm_entVeh; if (veh && veh->playerState && - (pm->cmd.serverTime-veh->playerState->hyperSpaceTime) < HYPERSPACE_TIME) - { //going into hyperspace, turn to face the right angles - PM_VehFaceHyperspacePoint(veh); - } - else if (veh && veh->playerState && - veh->playerState->vehTurnaroundIndex && - veh->playerState->vehTurnaroundTime > pm->cmd.serverTime) - { //riding this vehicle, turn my view too - PM_VehForcedTurning(veh); + (pm->cmd.serverTime - veh->playerState->hyperSpaceTime) < HYPERSPACE_TIME) { // going into hyperspace, turn to face the right angles + PM_VehFaceHyperspacePoint(veh); + } else if (veh && veh->playerState && veh->playerState->vehTurnaroundIndex && + veh->playerState->vehTurnaroundTime > pm->cmd.serverTime) { // riding this vehicle, turn my view too + PM_VehForcedTurning(veh); } } - if ( pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_ALT && - pm->ps->legsTimer > 0 ) - { + if (pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_ALT && pm->ps->legsTimer > 0) { vec3_t vFwd, fwdAng; VectorSet(fwdAng, 0.0f, pm->ps->viewangles[YAW], 0.0f); - AngleVectors( fwdAng, vFwd, NULL, NULL ); - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - { + AngleVectors(fwdAng, vFwd, NULL, NULL); + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { float savZ = pm->ps->velocity[2]; - VectorScale( vFwd, 100, pm->ps->velocity ); + VectorScale(vFwd, 100, pm->ps->velocity); pm->ps->velocity[2] = savZ; } pm->cmd.forwardmove = pm->cmd.rightmove = pm->cmd.upmove = 0; - PM_AdjustAnglesForWallRunUpFlipAlt( &pm->cmd ); + PM_AdjustAnglesForWallRunUpFlipAlt(&pm->cmd); } -// PM_AdjustAngleForWallRun(pm->ps, &pm->cmd, qtrue); -// PM_AdjustAnglesForStabDown( pm->ps, &pm->cmd ); - PM_AdjustAngleForWallJump( pm->ps, &pm->cmd, qtrue ); - PM_AdjustAngleForWallRunUp( pm->ps, &pm->cmd, qtrue ); - PM_AdjustAngleForWallRun( pm->ps, &pm->cmd, qtrue ); + // PM_AdjustAngleForWallRun(pm->ps, &pm->cmd, qtrue); + // PM_AdjustAnglesForStabDown( pm->ps, &pm->cmd ); + PM_AdjustAngleForWallJump(pm->ps, &pm->cmd, qtrue); + PM_AdjustAngleForWallRunUp(pm->ps, &pm->cmd, qtrue); + PM_AdjustAngleForWallRun(pm->ps, &pm->cmd, qtrue); - if (pm->ps->saberMove == LS_A_JUMP_T__B_ || pm->ps->saberMove == LS_A_LUNGE || - pm->ps->saberMove == LS_A_BACK_CR || pm->ps->saberMove == LS_A_BACK || - pm->ps->saberMove == LS_A_BACKSTAB) - { + if (pm->ps->saberMove == LS_A_JUMP_T__B_ || pm->ps->saberMove == LS_A_LUNGE || pm->ps->saberMove == LS_A_BACK_CR || pm->ps->saberMove == LS_A_BACK || + pm->ps->saberMove == LS_A_BACKSTAB) { PM_SetPMViewAngle(pm->ps, pm->ps->viewangles, &pm->cmd); } @@ -10642,23 +8749,23 @@ void PmoveSingle (pmove_t *pmove) { PM_SetSpecialMoveValues(); // update the viewangles - PM_UpdateViewAngles( pm->ps, &pm->cmd ); + PM_UpdateViewAngles(pm->ps, &pm->cmd); - AngleVectors (pm->ps->viewangles, pml.forward, pml.right, pml.up); + AngleVectors(pm->ps->viewangles, pml.forward, pml.right, pml.up); - if ( pm->cmd.upmove < 10 && !(pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { + if (pm->cmd.upmove < 10 && !(pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // not holding jump pm->ps->pm_flags &= ~PMF_JUMP_HELD; } // decide if backpedaling animations should be used - if ( pm->cmd.forwardmove < 0 ) { + if (pm->cmd.forwardmove < 0) { pm->ps->pm_flags |= PMF_BACKWARDS_RUN; - } else if ( pm->cmd.forwardmove > 0 || ( pm->cmd.forwardmove == 0 && pm->cmd.rightmove ) ) { + } else if (pm->cmd.forwardmove > 0 || (pm->cmd.forwardmove == 0 && pm->cmd.rightmove)) { pm->ps->pm_flags &= ~PMF_BACKWARDS_RUN; } - if ( pm->ps->pm_type >= PM_DEAD ) { + if (pm->ps->pm_type >= PM_DEAD) { pm->cmd.forwardmove = 0; pm->cmd.rightmove = 0; pm->cmd.upmove = 0; @@ -10674,38 +8781,35 @@ void PmoveSingle (pmove_t *pmove) { } */ - if (pm->ps->saberLockTime >= pm->cmd.serverTime) - { + if (pm->ps->saberLockTime >= pm->cmd.serverTime) { pm->cmd.upmove = 0; - pm->cmd.forwardmove = 0;//50; - pm->cmd.rightmove = 0;//*= 0.1; + pm->cmd.forwardmove = 0; // 50; + pm->cmd.rightmove = 0; //*= 0.1; } - if ( pm->ps->pm_type == PM_SPECTATOR ) { - PM_CheckDuck (); - if (!pm->noSpecMove) - { - PM_FlyMove (); + if (pm->ps->pm_type == PM_SPECTATOR) { + PM_CheckDuck(); + if (!pm->noSpecMove) { + PM_FlyMove(); } - PM_DropTimers (); + PM_DropTimers(); return; } - if ( pm->ps->pm_type == PM_NOCLIP ) { - if (pm->ps->clientNum < MAX_CLIENTS) - { - PM_NoclipMove (); - PM_DropTimers (); + if (pm->ps->pm_type == PM_NOCLIP) { + if (pm->ps->clientNum < MAX_CLIENTS) { + PM_NoclipMove(); + PM_DropTimers(); return; } } if (pm->ps->pm_type == PM_FREEZE) { - return; // no movement at all + return; // no movement at all } - if ( pm->ps->pm_type == PM_INTERMISSION || pm->ps->pm_type == PM_SPINTERMISSION) { - return; // no movement at all + if (pm->ps->pm_type == PM_INTERMISSION || pm->ps->pm_type == PM_SPINTERMISSION) { + return; // no movement at all } // set watertype, and waterlevel @@ -10713,138 +8817,105 @@ void PmoveSingle (pmove_t *pmove) { pml.previous_waterlevel = pmove->waterlevel; // set mins, maxs, and viewheight - PM_CheckDuck (); + PM_CheckDuck(); - if (pm->ps->pm_type == PM_JETPACK) - { + if (pm->ps->pm_type == PM_JETPACK) { gDist = PM_GroundDistance(); savedGravity = pm->ps->gravity; - if (gDist < JETPACK_HOVER_HEIGHT+64) - { + if (gDist < JETPACK_HOVER_HEIGHT + 64) { pm->ps->gravity *= 0.1f; - } - else - { + } else { pm->ps->gravity *= 0.25f; } - } - else if (gPMDoSlowFall) - { + } else if (gPMDoSlowFall) { savedGravity = pm->ps->gravity; pm->ps->gravity *= 0.5; } - //if we're in jetpack mode then see if we should be jetting around - if (pm->ps->pm_type == PM_JETPACK) - { - if (pm->cmd.rightmove > 0) - { + // if we're in jetpack mode then see if we should be jetting around + if (pm->ps->pm_type == PM_JETPACK) { + if (pm->cmd.rightmove > 0) { PM_ContinueLegsAnim(BOTH_INAIRRIGHT1); - } - else if (pm->cmd.rightmove < 0) - { - PM_ContinueLegsAnim(BOTH_INAIRLEFT1); - } - else if (pm->cmd.forwardmove > 0) - { + } else if (pm->cmd.rightmove < 0) { + PM_ContinueLegsAnim(BOTH_INAIRLEFT1); + } else if (pm->cmd.forwardmove > 0) { PM_ContinueLegsAnim(BOTH_INAIR1); - } - else if (pm->cmd.forwardmove < 0) - { + } else if (pm->cmd.forwardmove < 0) { PM_ContinueLegsAnim(BOTH_INAIRBACK1); - } - else - { + } else { PM_ContinueLegsAnim(BOTH_INAIR1); } if (pm->ps->weapon == WP_SABER && - BG_SpinningSaberAnim( pm->ps->legsAnim )) - { //make him stir around since he shouldn't have any real control when spinning + BG_SpinningSaberAnim(pm->ps->legsAnim)) { // make him stir around since he shouldn't have any real control when spinning pm->ps->velocity[0] += Q_irand(-100, 100); pm->ps->velocity[1] += Q_irand(-100, 100); } - if (pm->cmd.upmove > 0 && pm->ps->velocity[2] < 256) - { //cap upward velocity off at 256. Seems reasonable. + if (pm->cmd.upmove > 0 && pm->ps->velocity[2] < 256) { // cap upward velocity off at 256. Seems reasonable. float addIn = 12.0f; -/* - //Add based on our distance to the ground if we're already travelling upward - if (pm->ps->velocity[2] > 0) - { - while (gDist > 64) - { //subtract 1 for every 64 units off the ground we get - addIn--; + /* + //Add based on our distance to the ground if we're already travelling upward + if (pm->ps->velocity[2] > 0) + { + while (gDist > 64) + { //subtract 1 for every 64 units off the ground we get + addIn--; - gDist -= 64; + gDist -= 64; - if (addIn <= 0) - { //break out if we're not even going to add anything - break; - } - } - } -*/ - if (pm->ps->velocity[2] > 0) - { + if (addIn <= 0) + { //break out if we're not even going to add anything + break; + } + } + } + */ + if (pm->ps->velocity[2] > 0) { addIn = 12.0f - (gDist / 64.0f); } - if (addIn > 0.0f) - { + if (addIn > 0.0f) { pm->ps->velocity[2] += addIn; } - pm->ps->eFlags |= EF_JETPACK_FLAMING; //going up - } - else - { - pm->ps->eFlags &= ~EF_JETPACK_FLAMING; //idling + pm->ps->eFlags |= EF_JETPACK_FLAMING; // going up + } else { + pm->ps->eFlags &= ~EF_JETPACK_FLAMING; // idling - if (pm->ps->velocity[2] < 256) - { - if (pm->ps->velocity[2] < -100) - { + if (pm->ps->velocity[2] < 256) { + if (pm->ps->velocity[2] < -100) { pm->ps->velocity[2] = -100; } - if (gDist < JETPACK_HOVER_HEIGHT) - { //make sure we're always hovering off the ground somewhat while jetpack is active + if (gDist < JETPACK_HOVER_HEIGHT) { // make sure we're always hovering off the ground somewhat while jetpack is active pm->ps->velocity[2] += 2; } } } } - if (pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && pm_entSelf->m_pVehicle) - { //Now update our mins/maxs to match our m_vOrientation based on our length, width & height - BG_VehicleAdjustBBoxForOrientation( pm_entSelf->m_pVehicle, pm->ps->origin, pm->mins, pm->maxs, pm->ps->clientNum, pm->tracemask, pm->trace ); + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && + pm_entSelf->m_pVehicle) { // Now update our mins/maxs to match our m_vOrientation based on our length, width & height + BG_VehicleAdjustBBoxForOrientation(pm_entSelf->m_pVehicle, pm->ps->origin, pm->mins, pm->maxs, pm->ps->clientNum, pm->tracemask, pm->trace); } // set groundentity PM_GroundTrace(); - if ( pm_flying == FLY_HOVER ) - {//never stick to the ground + if (pm_flying == FLY_HOVER) { // never stick to the ground PM_HoverTrace(); } - if ( pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//on ground + if (pm->ps->groundEntityNum != ENTITYNUM_NONE) { // on ground pm->ps->fd.forceJumpZStart = 0; } - if ( pm->ps->pm_type == PM_DEAD ) { - if (pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_VEHICLE && - pm_entSelf->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) - {//vehicles don't use deadmove - } - else - { - PM_DeadMove (); + if (pm->ps->pm_type == PM_DEAD) { + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_VEHICLE && + pm_entSelf->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { // vehicles don't use deadmove + } else { + PM_DeadMove(); } } @@ -10863,76 +8934,60 @@ void PmoveSingle (pmove_t *pmove) { #endif #endif - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pm->ps->m_iVehicleNum) - { //a player riding a vehicle + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->m_iVehicleNum) { // a player riding a vehicle bgEntity_t *veh = pm_entVeh; - if ( veh && veh->m_pVehicle && - (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) ) - {//*sigh*, until we get forced weapon-switching working? - pm->cmd.buttons &= ~(BUTTON_ATTACK|BUTTON_ALT_ATTACK); - pm->ps->eFlags &= ~(EF_FIRING|EF_ALT_FIRING); - //pm->cmd.weapon = pm->ps->weapon; + if (veh && veh->m_pVehicle && + (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || + veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER)) { //*sigh*, until we get forced weapon-switching working? + pm->cmd.buttons &= ~(BUTTON_ATTACK | BUTTON_ALT_ATTACK); + pm->ps->eFlags &= ~(EF_FIRING | EF_ALT_FIRING); + // pm->cmd.weapon = pm->ps->weapon; } } - if (!pm->ps->m_iVehicleNum && - pm_entSelf->s.NPC_class!=CLASS_VEHICLE&& - pm_entSelf->s.NPC_class!=CLASS_RANCOR&& + if (!pm->ps->m_iVehicleNum && pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm_entSelf->s.NPC_class != CLASS_RANCOR && pm->ps->groundEntityNum < ENTITYNUM_WORLD && - pm->ps->groundEntityNum >= MAX_CLIENTS) - { //I am a player client, not riding on a vehicle, and potentially standing on an NPC + pm->ps->groundEntityNum >= MAX_CLIENTS) { // I am a player client, not riding on a vehicle, and potentially standing on an NPC bgEntity_t *pEnt = PM_BGEntForNum(pm->ps->groundEntityNum); - if (pEnt && pEnt->s.eType == ET_NPC && - pEnt->s.NPC_class != CLASS_VEHICLE) //don't bounce on vehicles - { //this is actually an NPC, let's try to bounce of its head to make sure we can't just stand around on top of it. - if (pm->ps->velocity[2] < 270) - { //try forcing velocity up and also force him to jump - pm->ps->velocity[2] = 270; //seems reasonable + if (pEnt && pEnt->s.eType == ET_NPC && pEnt->s.NPC_class != CLASS_VEHICLE) // don't bounce on vehicles + { // this is actually an NPC, let's try to bounce of its head to make sure we can't just stand around on top of it. + if (pm->ps->velocity[2] < 270) { // try forcing velocity up and also force him to jump + pm->ps->velocity[2] = 270; // seems reasonable pm->cmd.upmove = 127; } } #ifdef _GAME - else if ( !pm->ps->zoomMode && - pm_entSelf //I exist - && pEnt->m_pVehicle )//ent has a vehicle + else if (!pm->ps->zoomMode && pm_entSelf // I exist + && pEnt->m_pVehicle) // ent has a vehicle { - gentity_t *gEnt = (gentity_t*)pEnt; - if ( gEnt->client - && !gEnt->client->ps.m_iVehicleNum //vehicle is empty - && (gEnt->spawnflags&2) )//SUSPENDED - {//it's a vehicle, see if we should get in it - //if land on an empty, suspended vehicle, get in it - pEnt->m_pVehicle->m_pVehicleInfo->Board( pEnt->m_pVehicle, (bgEntity_t *)pm_entSelf ); + gentity_t *gEnt = (gentity_t *)pEnt; + if (gEnt->client && !gEnt->client->ps.m_iVehicleNum // vehicle is empty + && (gEnt->spawnflags & 2)) // SUSPENDED + { // it's a vehicle, see if we should get in it + // if land on an empty, suspended vehicle, get in it + pEnt->m_pVehicle->m_pVehicleInfo->Board(pEnt->m_pVehicle, (bgEntity_t *)pm_entSelf); } } #endif } - if (pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_VEHICLE) - { //we are a vehicle + if (pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_VEHICLE) { // we are a vehicle bgEntity_t *veh = pm_entSelf; assert(veh && veh->playerState && veh->m_pVehicle && veh->s.number >= MAX_CLIENTS); - if (veh->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) - { //kind of hacky, don't want to do this for flying vehicles + if (veh->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) { // kind of hacky, don't want to do this for flying vehicles veh->m_pVehicle->m_vOrientation[PITCH] = pm->ps->viewangles[PITCH]; } - if (!pm->ps->m_iVehicleNum) - { //no one is driving, just update and get out + if (!pm->ps->m_iVehicleNum) { // no one is driving, just update and get out #ifdef _GAME veh->m_pVehicle->m_pVehicleInfo->Update(veh->m_pVehicle, &pm->cmd); - veh->m_pVehicle->m_pVehicleInfo->Animate(veh->m_pVehicle); + veh->m_pVehicle->m_pVehicleInfo->Animate(veh->m_pVehicle); #endif - } - else - { + } else { bgEntity_t *self = pm_entVeh; #ifdef _GAME int i = 0; @@ -10940,14 +8995,11 @@ void PmoveSingle (pmove_t *pmove) { assert(self && self->playerState && self->s.number < MAX_CLIENTS); - if (pm->ps->pm_type == PM_DEAD && - (veh->m_pVehicle->m_ulFlags & VEH_CRASHING)) - { + if (pm->ps->pm_type == PM_DEAD && (veh->m_pVehicle->m_ulFlags & VEH_CRASHING)) { veh->m_pVehicle->m_ulFlags &= ~VEH_CRASHING; } - if (self->playerState->m_iVehicleNum) - { //only do it if they still have a vehicle (didn't get ejected this update or something) + if (self->playerState->m_iVehicleNum) { // only do it if they still have a vehicle (didn't get ejected this update or something) PM_VehicleViewAngles(self->playerState, veh, &veh->m_pVehicle->m_ucmd); } @@ -10956,36 +9008,31 @@ void PmoveSingle (pmove_t *pmove) { veh->m_pVehicle->m_pVehicleInfo->Animate(veh->m_pVehicle); veh->m_pVehicle->m_pVehicleInfo->UpdateRider(veh->m_pVehicle, self, &veh->m_pVehicle->m_ucmd); - //update the passengers - while (i < veh->m_pVehicle->m_iNumPassengers) - { - if (veh->m_pVehicle->m_ppPassengers[i]) - { - gentity_t *thePassenger = (gentity_t *)veh->m_pVehicle->m_ppPassengers[i]; //yes, this is, in fact, ass. - if (thePassenger->inuse && thePassenger->client) - { + // update the passengers + while (i < veh->m_pVehicle->m_iNumPassengers) { + if (veh->m_pVehicle->m_ppPassengers[i]) { + gentity_t *thePassenger = (gentity_t *)veh->m_pVehicle->m_ppPassengers[i]; // yes, this is, in fact, ass. + if (thePassenger->inuse && thePassenger->client) { veh->m_pVehicle->m_pVehicleInfo->UpdateRider(veh->m_pVehicle, veh->m_pVehicle->m_ppPassengers[i], &thePassenger->client->pers.cmd); } } i++; } #else - if (!veh->playerState->vehBoarding )//|| veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) + if (!veh->playerState->vehBoarding) //|| veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { - if (veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //client must explicitly call this for prediction + if (veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // client must explicitly call this for prediction BG_FighterUpdate(veh->m_pVehicle, &veh->m_pVehicle->m_ucmd, pm->mins, pm->maxs, self->playerState->gravity, pm->trace); } - if (veh->m_pVehicle->m_iBoarding == 0) - { + if (veh->m_pVehicle->m_iBoarding == 0) { vec3_t vRollAng; - //make sure we are set as its pilot cgame side + // make sure we are set as its pilot cgame side veh->m_pVehicle->m_pPilot = self; // Keep track of the old orientation. - VectorCopy( veh->m_pVehicle->m_vOrientation, veh->m_pVehicle->m_vPrevOrientation ); + VectorCopy(veh->m_pVehicle->m_vOrientation, veh->m_pVehicle->m_vPrevOrientation); veh->m_pVehicle->m_pVehicleInfo->ProcessOrientCommands(veh->m_pVehicle); PM_SetPMViewAngle(veh->playerState, veh->m_pVehicle->m_vOrientation, &veh->m_pVehicle->m_ucmd); @@ -10997,16 +9044,13 @@ void PmoveSingle (pmove_t *pmove) { PM_SetPMViewAngle(self->playerState, vRollAng, &pm->cmd); // Setup the move direction. - if ( veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - { - AngleVectors( veh->m_pVehicle->m_vOrientation, veh->playerState->moveDir, NULL, NULL ); - } - else - { + if (veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { + AngleVectors(veh->m_pVehicle->m_vOrientation, veh->playerState->moveDir, NULL, NULL); + } else { vec3_t vVehAngles; VectorSet(vVehAngles, 0, veh->m_pVehicle->m_vOrientation[YAW], 0); - AngleVectors( vVehAngles, veh->playerState->moveDir, NULL, NULL ); + AngleVectors(vVehAngles, veh->playerState->moveDir, NULL, NULL); } } } @@ -11017,11 +9061,9 @@ void PmoveSingle (pmove_t *pmove) { PM_SetPMViewAngle(self->playerState, veh->playerState->viewangles, &veh->m_pVehicle->m_ucmd); } */ - else if (veh->playerState) - { + else if (veh->playerState) { veh->playerState->speed = 0.0f; - if (veh->m_pVehicle) - { + if (veh->m_pVehicle) { PM_SetPMViewAngle(self->playerState, veh->m_pVehicle->m_vOrientation, &pm->cmd); PM_SetPMViewAngle(veh->playerState, veh->m_pVehicle->m_vOrientation, &pm->cmd); } @@ -11031,29 +9073,20 @@ void PmoveSingle (pmove_t *pmove) { noAnimate = qtrue; } - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - &&pm->ps->m_iVehicleNum) - {//don't even run physics on a player if he's on a vehicle - he goes where the vehicle goes - } - else - { //don't even run physics on a player if he's on a vehicle - he goes where the vehicle goes - if (pm->ps->pm_type == PM_FLOAT - ||pm_flying == FLY_NORMAL) - { - PM_FlyMove (); - } - else if ( pm_flying == FLY_VEHICLE ) - { + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && + pm->ps->m_iVehicleNum) { // don't even run physics on a player if he's on a vehicle - he goes where the vehicle goes + } else { // don't even run physics on a player if he's on a vehicle - he goes where the vehicle goes + if (pm->ps->pm_type == PM_FLOAT || pm_flying == FLY_NORMAL) { + PM_FlyMove(); + } else if (pm_flying == FLY_VEHICLE) { PM_FlyVehicleMove(); - } - else - { + } else { if (pm->ps->pm_flags & PMF_TIME_WATERJUMP) { PM_WaterJumpMove(); - } else if ( pm->waterlevel > 1 ) { + } else if (pm->waterlevel > 1) { // swimming PM_WaterMove(); - } else if ( pml.walking ) { + } else if (pml.walking) { // walking on ground PM_WalkMove(); } else { @@ -11063,57 +9096,47 @@ void PmoveSingle (pmove_t *pmove) { } } - if (!noAnimate) - { + if (!noAnimate) { PM_Animate(); } // set groundentity, watertype, and waterlevel PM_GroundTrace(); - if ( pm_flying == FLY_HOVER ) - {//never stick to the ground + if (pm_flying == FLY_HOVER) { // never stick to the ground PM_HoverTrace(); } PM_SetWaterLevel(); - if (pm->cmd.forcesel != (byte)-1 && (pm->ps->fd.forcePowersKnown & (1 << pm->cmd.forcesel))) - { + if (pm->cmd.forcesel != (byte)-1 && (pm->ps->fd.forcePowersKnown & (1 << pm->cmd.forcesel))) { pm->ps->fd.forcePowerSelected = pm->cmd.forcesel; } - if (pm->cmd.invensel != (byte)-1 && (pm->ps->stats[STAT_HOLDABLE_ITEMS] & (1 << pm->cmd.invensel))) - { + if (pm->cmd.invensel != (byte)-1 && (pm->ps->stats[STAT_HOLDABLE_ITEMS] & (1 << pm->cmd.invensel))) { pm->ps->stats[STAT_HOLDABLE_ITEM] = BG_GetItemIndexByTag(pm->cmd.invensel, IT_HOLDABLE); } if (pm->ps->m_iVehicleNum /*&&pm_entSelf->s.NPC_class!=CLASS_VEHICLE*/ - && pm->ps->clientNum < MAX_CLIENTS) - {//a client riding a vehicle - if ( (pm->ps->eFlags&EF_NODRAW) ) - {//inside the vehicle, do nothing - } - else if (!PM_WeaponOkOnVehicle(pm->cmd.weapon) || !PM_WeaponOkOnVehicle(pm->ps->weapon)) - { //this weapon is not legal for the vehicle, force to our current one - if (!PM_WeaponOkOnVehicle(pm->ps->weapon)) - { //uh-oh! + && pm->ps->clientNum < MAX_CLIENTS) { // a client riding a vehicle + if ((pm->ps->eFlags & EF_NODRAW)) { // inside the vehicle, do nothing + } else if (!PM_WeaponOkOnVehicle(pm->cmd.weapon) || + !PM_WeaponOkOnVehicle(pm->ps->weapon)) { // this weapon is not legal for the vehicle, force to our current one + if (!PM_WeaponOkOnVehicle(pm->ps->weapon)) { // uh-oh! int weap = PM_GetOkWeaponForVehicle(); - if (weap != -1) - { + if (weap != -1) { pm->cmd.weapon = weap; pm->ps->weapon = weap; } - } - else - { + } else { pm->cmd.weapon = pm->ps->weapon; } } } - if (!pm->ps->m_iVehicleNum //not a vehicle and not riding one - || pm_entSelf->s.NPC_class==CLASS_VEHICLE //you are a vehicle NPC - || (!(pm->ps->eFlags&EF_NODRAW)&&PM_WeaponOkOnVehicle(pm->cmd.weapon)) )//you're not inside the vehicle and the weapon you're holding can be used when riding this vehicle - { //only run weapons if a valid weapon is selected + if (!pm->ps->m_iVehicleNum // not a vehicle and not riding one + || pm_entSelf->s.NPC_class == CLASS_VEHICLE // you are a vehicle NPC + || (!(pm->ps->eFlags & EF_NODRAW) && + PM_WeaponOkOnVehicle(pm->cmd.weapon))) // you're not inside the vehicle and the weapon you're holding can be used when riding this vehicle + { // only run weapons if a valid weapon is selected // weapons PM_Weapon(); } @@ -11121,10 +9144,7 @@ void PmoveSingle (pmove_t *pmove) { PM_Use(); if (!pm->ps->m_iVehicleNum && - (pm->ps->clientNum < MAX_CLIENTS || - !pm_entSelf || - pm_entSelf->s.NPC_class != CLASS_VEHICLE)) - { //don't do this if we're on a vehicle, or we are one + (pm->ps->clientNum < MAX_CLIENTS || !pm_entSelf || pm_entSelf->s.NPC_class != CLASS_VEHICLE)) { // don't do this if we're on a vehicle, or we are one // footstep events / legs animations PM_Footsteps(); } @@ -11133,41 +9153,33 @@ void PmoveSingle (pmove_t *pmove) { PM_WaterEvents(); // snap velocity to integer coordinates to save network bandwidth - if ( !pm->pmove_float ) - trap->SnapVector( pm->ps->velocity ); + if (!pm->pmove_float) + trap->SnapVector(pm->ps->velocity); - if (pm->ps->pm_type == PM_JETPACK || gPMDoSlowFall ) - { + if (pm->ps->pm_type == PM_JETPACK || gPMDoSlowFall) { pm->ps->gravity = savedGravity; } - if (//pm->ps->m_iVehicleNum && - pm->ps->clientNum >= MAX_CLIENTS && - pm_entSelf && - pm_entSelf->s.NPC_class == CLASS_VEHICLE) - { //a vehicle with passengers + if ( // pm->ps->m_iVehicleNum && + pm->ps->clientNum >= MAX_CLIENTS && pm_entSelf && pm_entSelf->s.NPC_class == CLASS_VEHICLE) { // a vehicle with passengers bgEntity_t *veh; veh = pm_entSelf; assert(veh->m_pVehicle); - //this could be kind of "inefficient" because it's called after every passenger pmove too. - //Maybe instead of AttachRiders we should have each rider call attach for himself? - if (veh->m_pVehicle && veh->ghoul2) - { - veh->m_pVehicle->m_pVehicleInfo->AttachRiders( veh->m_pVehicle ); + // this could be kind of "inefficient" because it's called after every passenger pmove too. + // Maybe instead of AttachRiders we should have each rider call attach for himself? + if (veh->m_pVehicle && veh->ghoul2) { + veh->m_pVehicle->m_pVehicleInfo->AttachRiders(veh->m_pVehicle); } } - if (pm_entSelf->s.NPC_class!=CLASS_VEHICLE - && pm->ps->m_iVehicleNum) - { //riding a vehicle, see if we should do some anim overrides + if (pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->m_iVehicleNum) { // riding a vehicle, see if we should do some anim overrides PM_VehicleWeaponAnimate(); } } - /* ================ Pmove @@ -11175,53 +9187,50 @@ Pmove Can be called by either the server or the client ================ */ -void Pmove (pmove_t *pmove) { - int finalTime; +void Pmove(pmove_t *pmove) { + int finalTime; finalTime = pmove->cmd.serverTime; - if ( finalTime < pmove->ps->commandTime ) { - return; // should not happen + if (finalTime < pmove->ps->commandTime) { + return; // should not happen } - if ( finalTime > pmove->ps->commandTime + 1000 ) { + if (finalTime > pmove->ps->commandTime + 1000) { pmove->ps->commandTime = finalTime - 1000; } - if (pmove->ps->fallingToDeath) - { + if (pmove->ps->fallingToDeath) { pmove->cmd.forwardmove = 0; pmove->cmd.rightmove = 0; pmove->cmd.upmove = 0; pmove->cmd.buttons = 0; } - pmove->ps->pmove_framecount = (pmove->ps->pmove_framecount+1) & ((1<ps->pmove_framecount = (pmove->ps->pmove_framecount + 1) & ((1 << PS_PMOVEFRAMECOUNTBITS) - 1); // chop the move up if it is too long, to prevent framerate // dependent behavior - while ( pmove->ps->commandTime != finalTime ) { - int msec; + while (pmove->ps->commandTime != finalTime) { + int msec; msec = finalTime - pmove->ps->commandTime; - if ( pmove->pmove_fixed ) { - if ( msec > pmove->pmove_msec ) { + if (pmove->pmove_fixed) { + if (msec > pmove->pmove_msec) { msec = pmove->pmove_msec; } - } - else { - if ( msec > 66 ) { + } else { + if (msec > 66) { msec = 66; } } pmove->cmd.serverTime = pmove->ps->commandTime + msec; - PmoveSingle( pmove ); + PmoveSingle(pmove); - if ( pmove->ps->pm_flags & PMF_JUMP_HELD ) { + if (pmove->ps->pm_flags & PMF_JUMP_HELD) { pmove->cmd.upmove = 20; } } } - diff --git a/codemp/game/bg_saber.c b/codemp/game/bg_saber.c index e59413515b..2bf617e235 100644 --- a/codemp/game/bg_saber.c +++ b/codemp/game/bg_saber.c @@ -26,30 +26,26 @@ along with this program; if not, see . #include "bg_local.h" #include "w_saber.h" -extern qboolean BG_SabersOff( playerState_t *ps ); -saberInfo_t *BG_MySaber( int clientNum, int saberNum ); +extern qboolean BG_SabersOff(playerState_t *ps); +saberInfo_t *BG_MySaber(int clientNum, int saberNum); -int PM_irand_timesync(int val1, int val2) -{ +int PM_irand_timesync(int val1, int val2) { int i; - i = (val1-1) + (Q_random( &pm->cmd.serverTime )*(val2 - val1)) + 1; - if (i < val1) - { + i = (val1 - 1) + (Q_random(&pm->cmd.serverTime) * (val2 - val1)) + 1; + if (i < val1) { i = val1; } - if (i > val2) - { + if (i > val2) { i = val2; } return i; } -void BG_ForcePowerDrain( playerState_t *ps, forcePowers_t forcePower, int overrideAmt ) -{ - //take away the power - int drain = overrideAmt; +void BG_ForcePowerDrain(playerState_t *ps, forcePowers_t forcePower, int overrideAmt) { + // take away the power + int drain = overrideAmt; /* if (ps->powerups[PW_FORCE_BOON]) @@ -57,57 +53,40 @@ void BG_ForcePowerDrain( playerState_t *ps, forcePowers_t forcePower, int overri return; } */ - //No longer grant infinite force with boon. + // No longer grant infinite force with boon. - if ( !drain ) - { + if (!drain) { drain = forcePowerNeeded[ps->fd.forcePowerLevel[forcePower]][forcePower]; } - if ( !drain ) - { + if (!drain) { return; } - if (forcePower == FP_LEVITATION) - { //special case + if (forcePower == FP_LEVITATION) { // special case int jumpDrain = 0; - if (ps->velocity[2] > 250) - { + if (ps->velocity[2] > 250) { jumpDrain = 20; - } - else if (ps->velocity[2] > 200) - { + } else if (ps->velocity[2] > 200) { jumpDrain = 16; - } - else if (ps->velocity[2] > 150) - { + } else if (ps->velocity[2] > 150) { jumpDrain = 12; - } - else if (ps->velocity[2] > 100) - { + } else if (ps->velocity[2] > 100) { jumpDrain = 8; - } - else if (ps->velocity[2] > 50) - { + } else if (ps->velocity[2] > 50) { jumpDrain = 6; - } - else if (ps->velocity[2] > 0) - { + } else if (ps->velocity[2] > 0) { jumpDrain = 4; } - if (jumpDrain) - { - if (ps->fd.forcePowerLevel[FP_LEVITATION]) - { //don't divide by 0! + if (jumpDrain) { + if (ps->fd.forcePowerLevel[FP_LEVITATION]) { // don't divide by 0! jumpDrain /= ps->fd.forcePowerLevel[FP_LEVITATION]; } } ps->fd.forcePower -= jumpDrain; - if ( ps->fd.forcePower < 0 ) - { + if (ps->fd.forcePower < 0) { ps->fd.forcePower = 0; } @@ -115,17 +94,14 @@ void BG_ForcePowerDrain( playerState_t *ps, forcePowers_t forcePower, int overri } ps->fd.forcePower -= drain; - if ( ps->fd.forcePower < 0 ) - { + if (ps->fd.forcePower < 0) { ps->fd.forcePower = 0; } } -qboolean BG_EnoughForcePowerForMove( int cost ) -{ - if ( pm->ps->fd.forcePower < cost ) - { - PM_AddEvent( EV_NOAMMO ); +qboolean BG_EnoughForcePowerForMove(int cost) { + if (pm->ps->fd.forcePower < cost) { + PM_AddEvent(EV_NOAMMO); return qfalse; } @@ -133,238 +109,245 @@ qboolean BG_EnoughForcePowerForMove( int cost ) } // Silly, but I'm replacing these macros so they are shorter! -#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) -#define AFLAG_ACTIVE (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) +#define AFLAG_IDLE (SETANIM_FLAG_NORMAL) +#define AFLAG_ACTIVE (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_WAIT (SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS) #define AFLAG_FINISH (SETANIM_FLAG_HOLD) -//FIXME: add the alternate anims for each style? -saberMoveData_t saberMoveData[LS_MOVE_MAX] = {// NB:randomized +// FIXME: add the alternate anims for each style? +saberMoveData_t saberMoveData[LS_MOVE_MAX] = { + // NB:randomized // name anim(do all styles?)startQ endQ setanimflag blend, blocking chain_idle chain_attack trailLen - {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0 }, // LS_NONE = 0, + {"None", BOTH_STAND1, Q_R, Q_R, AFLAG_IDLE, 350, BLK_NO, LS_NONE, LS_NONE, 0}, // LS_NONE = 0, // General movements with saber - {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0 }, // LS_READY, - {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_DRAW, - {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0 }, // LS_PUTAWAY, + {"Ready", BOTH_STAND2, Q_R, Q_R, AFLAG_IDLE, 350, BLK_WIDE, LS_READY, LS_S_R2L, 0}, // LS_READY, + {"Draw", BOTH_STAND1TO2, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_DRAW, + {"Putaway", BOTH_STAND2TO1, Q_R, Q_R, AFLAG_FINISH, 350, BLK_NO, LS_READY, LS_S_R2L, 0}, // LS_PUTAWAY, // Attacks - //UL2LR - {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200 }, // LS_A_TL2BR - //SLASH LEFT - {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200 }, // LS_A_L2R - //LL2UR - {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200 }, // LS_A_BL2TR - //LR2UL - {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200 }, // LS_A_BR2TL - //SLASH RIGHT - {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200 },// LS_A_R2L - //UR2LL - {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200 }, // LS_A_TR2BL - //SLASH DOWN - {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200 }, // LS_A_T2B - //special attacks - {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACKSTAB - {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK - {"CR Back Att", BOTH_CROUCHATTACKBACK1,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_BACK_CR - {"RollStab", BOTH_ROLL_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_ROLL_STAB - {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_LUNGE - {"Jump Att", BOTH_FORCELEAP2_T__B_,Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_A_JUMP_T__B_ - {"Flip Stab", BOTH_JUMPFLIPSTABDOWN,Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200 }, // LS_A_FLIP_STAB - {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1,Q_L,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200 }, // LS_A_FLIP_SLASH - {"DualJump Atk",BOTH_JUMPATTACK6, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_BL_TR, 200 }, // LS_JUMPATTACK_DUAL - - {"DualJumpAtkL_A",BOTH_ARIAL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TL2BR, 200 }, // LS_JUMPATTACK_ARIAL_LEFT - {"DualJumpAtkR_A",BOTH_ARIAL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TR2BL, 200 }, // LS_JUMPATTACK_ARIAL_RIGHT - - {"DualJumpAtkL_A",BOTH_CARTWHEEL_LEFT, Q_R,Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TL_BR, 200 }, // LS_JUMPATTACK_CART_LEFT - {"DualJumpAtkR_A",BOTH_CARTWHEEL_RIGHT, Q_R,Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TR_BL, 200 }, // LS_JUMPATTACK_CART_RIGHT - - {"DualJumpAtkLStaff", BOTH_BUTTERFLY_FL1,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200 }, // LS_JUMPATTACK_STAFF_LEFT - {"DualJumpAtkRStaff", BOTH_BUTTERFLY_FR1,Q_R,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200 }, // LS_JUMPATTACK_STAFF_RIGHT - - {"ButterflyLeft", BOTH_BUTTERFLY_LEFT,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200 }, // LS_BUTTERFLY_LEFT - {"ButterflyRight", BOTH_BUTTERFLY_RIGHT,Q_R,Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200 }, // LS_BUTTERFLY_RIGHT - - {"BkFlip Atk", BOTH_JUMPATTACK7, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200 }, // LS_A_BACKFLIP_ATK - {"DualSpinAtk", BOTH_SPINATTACK6, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK_DUAL - {"StfSpinAtk", BOTH_SPINATTACK7, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK - {"LngLeapAtk", BOTH_FORCELONGLEAP_ATTACK,Q_R,Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_LEAP_ATTACK - {"SwoopAtkR", BOTH_VS_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SWOOP_ATTACK_RIGHT - {"SwoopAtkL", BOTH_VS_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SWOOP_ATTACK_LEFT - {"TauntaunAtkR",BOTH_VT_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_TAUNTAUN_ATTACK_RIGHT - {"TauntaunAtkL",BOTH_VT_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_TAUNTAUN_ATTACK_LEFT - {"StfKickFwd", BOTH_A7_KICK_F, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_F - {"StfKickBack", BOTH_A7_KICK_B, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_B - {"StfKickRight",BOTH_A7_KICK_R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_R - {"StfKickLeft", BOTH_A7_KICK_L, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_L - {"StfKickSpin", BOTH_A7_KICK_S, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_S - {"StfKickBkFwd",BOTH_A7_KICK_BF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_BF - {"StfKickSplit",BOTH_A7_KICK_RL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200 }, // LS_KICK_RL - {"StfKickFwdAir",BOTH_A7_KICK_F_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_F_AIR - {"StfKickBackAir",BOTH_A7_KICK_B_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_B_AIR - {"StfKickRightAir",BOTH_A7_KICK_R_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_R_AIR - {"StfKickLeftAir",BOTH_A7_KICK_L_AIR,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_KICK_L_AIR - {"StabDown", BOTH_STABDOWN, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN - {"StabDownStf", BOTH_STABDOWN_STAFF,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN_STAFF - {"StabDownDual",BOTH_STABDOWN_DUAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200 }, // LS_STABDOWN_DUAL - {"dualspinprot",BOTH_A6_SABERPROTECT,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500 }, // LS_DUAL_SPIN_PROTECT - {"StfSoulCal", BOTH_A7_SOULCAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500 }, // LS_STAFF_SOULCAL - {"specialfast", BOTH_A1_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A1_SPECIAL - {"specialmed", BOTH_A2_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A2_SPECIAL - {"specialstr", BOTH_A3_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A3_SPECIAL - {"upsidedwnatk",BOTH_FLIP_ATTACK7, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_UPSIDE_DOWN_ATTACK - {"pullatkstab", BOTH_PULL_IMPALE_STAB,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_STAB - {"pullatkswing",BOTH_PULL_IMPALE_SWING,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_SWING - {"AloraSpinAtk",BOTH_ALORA_SPIN_SLASH,Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_SPINATTACK_ALORA - {"Dual FB Atk", BOTH_A6_FB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_DUAL_FB - {"Dual LR Atk", BOTH_A6_LR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_DUAL_LR - {"StfHiltBash", BOTH_A7_HILT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_HILT_BASH - - //starts - {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200 }, // LS_S_TL2BR - {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200 }, // LS_S_L2R - {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200 }, // LS_S_BL2TR - {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200 }, // LS_S_BR2TL - {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200 }, // LS_S_R2L - {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200 }, // LS_S_TR2BL - {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200 }, // LS_S_T2B - - //returns - {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TL2BR - {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_L2R - {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BL2TR - {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_BR2TL - {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_R2L - {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_TR2BL - {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200 }, // LS_R_T2B - - //Transitions - {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc bottom right to right - {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) - {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) - {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast weak spin bottom right to top left - {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin bottom right to left - {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin bottom right to bottom left - {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) - {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc right to top right - {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast ar right to top (use: BOTH_T1_T___R) - {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc right to top left - {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast weak spin right to left - {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin right to bottom left - {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top right to bottom right - {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top right to right (use: BOTH_T1__R_TR) - {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top right to top (use: BOTH_T1_T__TR) - {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top right to top left - {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top right to left - {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast weak spin top right to bottom left - {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast arc top to bottom right - {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top to right - {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top to top right - {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc top to top left - {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top to left - {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top to bottom left - {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin top left to bottom right - {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast arc top left to right (use: BOTH_T1__R_TL) - {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) - {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc top left to top (use: BOTH_T1_T__TL) - {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc top left to left (use: BOTH_T1__L_TL) - {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc top left to bottom left - {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin left to bottom right - {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin left to right - {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast arc left to top right (use: BOTH_T1_TR__L) - {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc left to top (use: BOTH_T1_T___L) - {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc left to top left - {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150 }, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) - {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150 }, //# Fast weak spin bottom left to bottom right - {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150 }, //# Fast weak spin bottom left to right - {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150 }, //# Fast weak spin bottom left to top right - {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150 }, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) - {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150 }, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) - {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150 }, //# Fast arc bottom left to left - - //Bounces - {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - - //Deflected attacks (like bounces, but slide off enemy saber, not straight back) - {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150 }, - {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150 }, - {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150 }, - {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150 }, - {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150 }, - {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150 }, - {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150 }, - - //Reflected attacks - {"Reflected BR",BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BR - {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__R - {"Reflected TR",BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TR - {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_T_ - {"Reflected TL",BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_TL - {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1__L - {"Reflected BL",BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_BL - {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150 },// LS_V1_B_ + // UL2LR + {"TL2BR Att", BOTH_A1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TL2BR, LS_R_TL2BR, 200}, // LS_A_TL2BR + // SLASH LEFT + {"L2R Att", BOTH_A1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_L2R, LS_R_L2R, 200}, // LS_A_L2R + // LL2UR + {"BL2TR Att", BOTH_A1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_TIGHT, LS_R_BL2TR, LS_R_BL2TR, 200}, // LS_A_BL2TR + // LR2UL + {"BR2TL Att", BOTH_A1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_BR2TL, LS_R_BR2TL, 200}, // LS_A_BR2TL + // SLASH RIGHT + {"R2L Att", BOTH_A1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_R2L, LS_R_R2L, 200}, // LS_A_R2L + // UR2LL + {"TR2BL Att", BOTH_A1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_TR2BL, LS_R_TR2BL, 200}, // LS_A_TR2BL + // SLASH DOWN + {"T2B Att", BOTH_A1_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_R_T2B, LS_R_T2B, 200}, // LS_A_T2B + // special attacks + {"Back Stab", BOTH_A2_STABBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACKSTAB + {"Back Att", BOTH_ATTACK_BACK, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK + {"CR Back Att", BOTH_CROUCHATTACKBACK1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_BACK_CR + {"RollStab", BOTH_ROLL_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_ROLL_STAB + {"Lunge Att", BOTH_LUNGE2_B__T_, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_LUNGE + {"Jump Att", BOTH_FORCELEAP2_T__B_, Q_T, Q_B, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_A_JUMP_T__B_ + {"Flip Stab", BOTH_JUMPFLIPSTABDOWN, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200}, // LS_A_FLIP_STAB + {"Flip Slash", BOTH_JUMPFLIPSLASHDOWN1, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R_T_, 200}, // LS_A_FLIP_SLASH + {"DualJump Atk", BOTH_JUMPATTACK6, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_BL_TR, 200}, // LS_JUMPATTACK_DUAL + + {"DualJumpAtkL_A", BOTH_ARIAL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TL2BR, 200}, // LS_JUMPATTACK_ARIAL_LEFT + {"DualJumpAtkR_A", BOTH_ARIAL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_A_TR2BL, 200}, // LS_JUMPATTACK_ARIAL_RIGHT + + {"DualJumpAtkL_A", BOTH_CARTWHEEL_LEFT, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TL_BR, 200}, // LS_JUMPATTACK_CART_LEFT + {"DualJumpAtkR_A", BOTH_CARTWHEEL_RIGHT, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_TR_BL, 200}, // LS_JUMPATTACK_CART_RIGHT + + {"DualJumpAtkLStaff", BOTH_BUTTERFLY_FL1, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200}, // LS_JUMPATTACK_STAFF_LEFT + {"DualJumpAtkRStaff", BOTH_BUTTERFLY_FR1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200}, // LS_JUMPATTACK_STAFF_RIGHT + + {"ButterflyLeft", BOTH_BUTTERFLY_LEFT, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__L__R, 200}, // LS_BUTTERFLY_LEFT + {"ButterflyRight", BOTH_BUTTERFLY_RIGHT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1__R__L, 200}, // LS_BUTTERFLY_RIGHT + + {"BkFlip Atk", BOTH_JUMPATTACK7, Q_B, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_T1_T___R, 200}, // LS_A_BACKFLIP_ATK + {"DualSpinAtk", BOTH_SPINATTACK6, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK_DUAL + {"StfSpinAtk", BOTH_SPINATTACK7, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK + {"LngLeapAtk", BOTH_FORCELONGLEAP_ATTACK, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_LEAP_ATTACK + {"SwoopAtkR", BOTH_VS_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SWOOP_ATTACK_RIGHT + {"SwoopAtkL", BOTH_VS_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SWOOP_ATTACK_LEFT + {"TauntaunAtkR", BOTH_VT_ATR_S, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_TAUNTAUN_ATTACK_RIGHT + {"TauntaunAtkL", BOTH_VT_ATL_S, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_TAUNTAUN_ATTACK_LEFT + {"StfKickFwd", BOTH_A7_KICK_F, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_F + {"StfKickBack", BOTH_A7_KICK_B, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_B + {"StfKickRight", BOTH_A7_KICK_R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_R + {"StfKickLeft", BOTH_A7_KICK_L, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_L + {"StfKickSpin", BOTH_A7_KICK_S, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_S + {"StfKickBkFwd", BOTH_A7_KICK_BF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_BF + {"StfKickSplit", BOTH_A7_KICK_RL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_S_R2L, 200}, // LS_KICK_RL + {"StfKickFwdAir", BOTH_A7_KICK_F_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_F_AIR + {"StfKickBackAir", BOTH_A7_KICK_B_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_B_AIR + {"StfKickRightAir", BOTH_A7_KICK_R_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_R_AIR + {"StfKickLeftAir", BOTH_A7_KICK_L_AIR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_KICK_L_AIR + {"StabDown", BOTH_STABDOWN, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN + {"StabDownStf", BOTH_STABDOWN_STAFF, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN_STAFF + {"StabDownDual", BOTH_STABDOWN_DUAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_S_R2L, 200}, // LS_STABDOWN_DUAL + {"dualspinprot", BOTH_A6_SABERPROTECT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500}, // LS_DUAL_SPIN_PROTECT + {"StfSoulCal", BOTH_A7_SOULCAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 500}, // LS_STAFF_SOULCAL + {"specialfast", BOTH_A1_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A1_SPECIAL + {"specialmed", BOTH_A2_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A2_SPECIAL + {"specialstr", BOTH_A3_SPECIAL, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 2000}, // LS_A3_SPECIAL + {"upsidedwnatk", BOTH_FLIP_ATTACK7, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_UPSIDE_DOWN_ATTACK + {"pullatkstab", BOTH_PULL_IMPALE_STAB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_STAB + {"pullatkswing", BOTH_PULL_IMPALE_SWING, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_PULL_ATTACK_SWING + {"AloraSpinAtk", BOTH_ALORA_SPIN_SLASH, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_SPINATTACK_ALORA + {"Dual FB Atk", BOTH_A6_FB, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_DUAL_FB + {"Dual LR Atk", BOTH_A6_LR, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_DUAL_LR + {"StfHiltBash", BOTH_A7_HILT, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_HILT_BASH + + // starts + {"TL2BR St", BOTH_S1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TL2BR, LS_A_TL2BR, 200}, // LS_S_TL2BR + {"L2R St", BOTH_S1_S1__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_L2R, LS_A_L2R, 200}, // LS_S_L2R + {"BL2TR St", BOTH_S1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BL2TR, LS_A_BL2TR, 200}, // LS_S_BL2TR + {"BR2TL St", BOTH_S1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_BR2TL, LS_A_BR2TL, 200}, // LS_S_BR2TL + {"R2L St", BOTH_S1_S1__R, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_R2L, LS_A_R2L, 200}, // LS_S_R2L + {"TR2BL St", BOTH_S1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_TR2BL, LS_A_TR2BL, 200}, // LS_S_TR2BL + {"T2B St", BOTH_S1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_TIGHT, LS_A_T2B, LS_A_T2B, 200}, // LS_S_T2B + + // returns + {"TL2BR Ret", BOTH_R1_BR_S1, Q_BR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TL2BR + {"L2R Ret", BOTH_R1__R_S1, Q_R, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_L2R + {"BL2TR Ret", BOTH_R1_TR_S1, Q_TR, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BL2TR + {"BR2TL Ret", BOTH_R1_TL_S1, Q_TL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_BR2TL + {"R2L Ret", BOTH_R1__L_S1, Q_L, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_R2L + {"TR2BL Ret", BOTH_R1_BL_S1, Q_BL, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_TR2BL + {"T2B Ret", BOTH_R1_B__S1, Q_B, Q_R, AFLAG_FINISH, 100, BLK_TIGHT, LS_READY, LS_READY, 200}, // LS_R_T2B + + // Transitions + {"BR2R Trans", BOTH_T1_BR__R, Q_BR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc bottom right to right + {"BR2TR Trans", BOTH_T1_BR_TR, Q_BR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc bottom right to top right (use: BOTH_T1_TR_BR) + {"BR2T Trans", BOTH_T1_BR_T_, Q_BR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc bottom right to top (use: BOTH_T1_T__BR) + {"BR2TL Trans", BOTH_T1_BR_TL, Q_BR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast weak spin bottom right to top left + {"BR2L Trans", BOTH_T1_BR__L, Q_BR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin bottom right to left + {"BR2BL Trans", BOTH_T1_BR_BL, Q_BR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin bottom right to bottom left + {"R2BR Trans", BOTH_T1__R_BR, Q_R, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, + 150}, //# Fast arc right to bottom right (use: BOTH_T1_BR__R) + {"R2TR Trans", BOTH_T1__R_TR, Q_R, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc right to top right + {"R2T Trans", BOTH_T1__R_T_, Q_R, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast ar right to top (use: BOTH_T1_T___R) + {"R2TL Trans", BOTH_T1__R_TL, Q_R, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc right to top left + {"R2L Trans", BOTH_T1__R__L, Q_R, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast weak spin right to left + {"R2BL Trans", BOTH_T1__R_BL, Q_R, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin right to bottom left + {"TR2BR Trans", BOTH_T1_TR_BR, Q_TR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top right to bottom right + {"TR2R Trans", BOTH_T1_TR__R, Q_TR, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top right to right (use: BOTH_T1__R_TR) + {"TR2T Trans", BOTH_T1_TR_T_, Q_TR, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top right to top (use: BOTH_T1_T__TR) + {"TR2TL Trans", BOTH_T1_TR_TL, Q_TR, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top right to top left + {"TR2L Trans", BOTH_T1_TR__L, Q_TR, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top right to left + {"TR2BL Trans", BOTH_T1_TR_BL, Q_TR, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast weak spin top right to bottom left + {"T2BR Trans", BOTH_T1_T__BR, Q_T, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast arc top to bottom right + {"T2R Trans", BOTH_T1_T___R, Q_T, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top to right + {"T2TR Trans", BOTH_T1_T__TR, Q_T, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast arc top to top right + {"T2TL Trans", BOTH_T1_T__TL, Q_T, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc top to top left + {"T2L Trans", BOTH_T1_T___L, Q_T, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top to left + {"T2BL Trans", BOTH_T1_T__BL, Q_T, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top to bottom left + {"TL2BR Trans", BOTH_T1_TL_BR, Q_TL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin top left to bottom right + {"TL2R Trans", BOTH_T1_TL__R, Q_TL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast arc top left to right (use: BOTH_T1__R_TL) + {"TL2TR Trans", BOTH_T1_TL_TR, Q_TL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc top left to top right (use: BOTH_T1_TR_TL) + {"TL2T Trans", BOTH_T1_TL_T_, Q_TL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, + 150}, //# Fast arc top left to top (use: BOTH_T1_T__TL) + {"TL2L Trans", BOTH_T1_TL__L, Q_TL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc top left to left (use: BOTH_T1__L_TL) + {"TL2BL Trans", BOTH_T1_TL_BL, Q_TL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, 150}, //# Fast arc top left to bottom left + {"L2BR Trans", BOTH_T1__L_BR, Q_L, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin left to bottom right + {"L2R Trans", BOTH_T1__L__R, Q_L, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin left to right + {"L2TR Trans", BOTH_T1__L_TR, Q_L, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, + 150}, //# Fast arc left to top right (use: BOTH_T1_TR__L) + {"L2T Trans", BOTH_T1__L_T_, Q_L, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc left to top (use: BOTH_T1_T___L) + {"L2TL Trans", BOTH_T1__L_TL, Q_L, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, 150}, //# Fast arc left to top left + {"L2BL Trans", BOTH_T1__L_BL, Q_L, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_A_BL2TR, + 150}, //# Fast arc left to bottom left (use: BOTH_T1_BL__L) + {"BL2BR Trans", BOTH_T1_BL_BR, Q_BL, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_A_BR2TL, 150}, //# Fast weak spin bottom left to bottom right + {"BL2R Trans", BOTH_T1_BL__R, Q_BL, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_A_R2L, 150}, //# Fast weak spin bottom left to right + {"BL2TR Trans", BOTH_T1_BL_TR, Q_BL, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_TR2BL, 150}, //# Fast weak spin bottom left to top right + {"BL2T Trans", BOTH_T1_BL_T_, Q_BL, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_A_T2B, 150}, //# Fast arc bottom left to top (use: BOTH_T1_T__BL) + {"BL2TL Trans", BOTH_T1_BL_TL, Q_BL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_A_TL2BR, + 150}, //# Fast arc bottom left to top left (use: BOTH_T1_TL_BL) + {"BL2L Trans", BOTH_T1_BL__L, Q_BL, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_A_L2R, 150}, //# Fast arc bottom left to left + + // Bounces + {"Bounce BR", BOTH_B1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Bounce R", BOTH_B1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Bounce TR", BOTH_B1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Bounce T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Bounce TL", BOTH_B1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Bounce L", BOTH_B1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Bounce BL", BOTH_B1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + + // Deflected attacks (like bounces, but slide off enemy saber, not straight back) + {"Deflect BR", BOTH_D1_BR___, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TL2BR, LS_T1_BR_TR, 150}, + {"Deflect R", BOTH_D1__R___, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_R_L2R, LS_T1__R__L, 150}, + {"Deflect TR", BOTH_D1_TR___, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_TR_TL, 150}, + {"Deflect T", BOTH_B1_T____, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + {"Deflect TL", BOTH_D1_TL___, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BR2TL, LS_T1_TL_TR, 150}, + {"Deflect L", BOTH_D1__L___, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_R_R2L, LS_T1__L__R, 150}, + {"Deflect BL", BOTH_D1_BL___, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_R_TR2BL, LS_T1_BL_TR, 150}, + {"Deflect B", BOTH_D1_B____, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_R_BL2TR, LS_T1_T__BL, 150}, + + // Reflected attacks + {"Reflected BR", BOTH_V1_BR_S1, Q_BR, Q_BR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BR + {"Reflected R", BOTH_V1__R_S1, Q_R, Q_R, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__R + {"Reflected TR", BOTH_V1_TR_S1, Q_TR, Q_TR, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TR + {"Reflected T", BOTH_V1_T__S1, Q_T, Q_T, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_T_ + {"Reflected TL", BOTH_V1_TL_S1, Q_TL, Q_TL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_TL + {"Reflected L", BOTH_V1__L_S1, Q_L, Q_L, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1__L + {"Reflected BL", BOTH_V1_BL_S1, Q_BL, Q_BL, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_BL + {"Reflected B", BOTH_V1_B__S1, Q_B, Q_B, AFLAG_ACTIVE, 100, BLK_NO, LS_READY, LS_READY, 150}, // LS_V1_B_ // Broken parries - {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UP, - {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UR, - {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_UL, - {"BParry LR", BOTH_H1_S1_BR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LR, - {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LR - {"BParry LL", BOTH_H1_S1_BL, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL + {"BParry Top", BOTH_H1_S1_T_, Q_T, Q_B, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UP, + {"BParry UR", BOTH_H1_S1_TR, Q_TR, Q_BL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UR, + {"BParry UL", BOTH_H1_S1_TL, Q_TL, Q_BR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_UL, + {"BParry LR", BOTH_H1_S1_BR, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LR, + {"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LR + {"BParry LL", BOTH_H1_S1_BL, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150}, // LS_PARRY_LL //{"BParry LR", BOTH_H1_S1_BL, Q_BL, Q_TR, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LR, //{"BParry Bot", BOTH_H1_S1_B_, Q_B, Q_T, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL //{"BParry LL", BOTH_H1_S1_BR, Q_BR, Q_TL, AFLAG_ACTIVE, 50, BLK_NO, LS_READY, LS_READY, 150 }, // LS_PARRY_LL // Knockaways - {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150 }, // LS_PARRY_UP, - {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150 }, // LS_PARRY_UR, - {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150 }, // LS_PARRY_UL, - {"Knock LR", BOTH_K1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150 }, // LS_PARRY_LR, - {"Knock LL", BOTH_K1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150 }, // LS_PARRY_LL + {"Knock Top", BOTH_K1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_T__BR, 150}, // LS_PARRY_UP, + {"Knock UR", BOTH_K1_S1_TR, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_T1_TR__R, 150}, // LS_PARRY_UR, + {"Knock UL", BOTH_K1_S1_TL, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_T1_TL__L, 150}, // LS_PARRY_UL, + {"Knock LR", BOTH_K1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150}, // LS_PARRY_LR, + {"Knock LL", BOTH_K1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150}, // LS_PARRY_LL //{"Knock LR", BOTH_K1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_T1_BL_TL, 150 }, // LS_PARRY_LR, //{"Knock LL", BOTH_K1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_T1_BR_TR, 150 }, // LS_PARRY_LL // Parry - {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150 }, // LS_PARRY_UP, - {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150 }, // LS_PARRY_UR, - {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150 }, // LS_PARRY_UL, - {"Parry LR", BOTH_P1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150 }, // LS_PARRY_LR, - {"Parry LL", BOTH_P1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150 }, // LS_PARRY_LL + {"Parry Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 150}, // LS_PARRY_UP, + {"Parry UR", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 150}, // LS_PARRY_UR, + {"Parry UL", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 150}, // LS_PARRY_UL, + {"Parry LR", BOTH_P1_S1_BR, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150}, // LS_PARRY_LR, + {"Parry LL", BOTH_P1_S1_BL, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150}, // LS_PARRY_LL //{"Parry LR", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 150 }, // LS_PARRY_LR, //{"Parry LL", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 150 }, // LS_PARRY_LL // Reflecting a missile - {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300 }, // LS_PARRY_UP, - {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300 }, // LS_PARRY_UR, - {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300 }, // LS_PARRY_UL, - {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300 }, // LS_PARRY_LR - {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300 }, // LS_PARRY_LL, + {"Reflect Top", BOTH_P1_S1_T_, Q_R, Q_T, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_T2B, 300}, // LS_PARRY_UP, + {"Reflect UR", BOTH_P1_S1_TL, Q_R, Q_TR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BR2TL, LS_A_TL2BR, 300}, // LS_PARRY_UR, + {"Reflect UL", BOTH_P1_S1_TR, Q_R, Q_TL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_BL2TR, LS_A_TR2BL, 300}, // LS_PARRY_UL, + {"Reflect LR", BOTH_P1_S1_BR, Q_R, Q_BL, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TR2BL, LS_A_BL2TR, 300}, // LS_PARRY_LR + {"Reflect LL", BOTH_P1_S1_BL, Q_R, Q_BR, AFLAG_ACTIVE, 50, BLK_WIDE, LS_R_TL2BR, LS_A_BR2TL, 300}, // LS_PARRY_LL, }; -int transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = -{ - { LS_NONE, LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, LS_NONE }, - { LS_T1__R_BR, LS_NONE, LS_T1__R_TR, LS_T1__R_T_, LS_T1__R_TL, LS_T1__R__L, LS_T1__R_BL, LS_NONE }, - { LS_T1_TR_BR, LS_T1_TR__R, LS_NONE, LS_T1_TR_T_, LS_T1_TR_TL, LS_T1_TR__L, LS_T1_TR_BL, LS_NONE }, - { LS_T1_T__BR, LS_T1_T___R, LS_T1_T__TR, LS_NONE, LS_T1_T__TL, LS_T1_T___L, LS_T1_T__BL, LS_NONE }, - { LS_T1_TL_BR, LS_T1_TL__R, LS_T1_TL_TR, LS_T1_TL_T_, LS_NONE, LS_T1_TL__L, LS_T1_TL_BL, LS_NONE }, - { LS_T1__L_BR, LS_T1__L__R, LS_T1__L_TR, LS_T1__L_T_, LS_T1__L_TL, LS_NONE, LS_T1__L_BL, LS_NONE }, - { LS_T1_BL_BR, LS_T1_BL__R, LS_T1_BL_TR, LS_T1_BL_T_, LS_T1_BL_TL, LS_T1_BL__L, LS_NONE, LS_NONE }, - { LS_T1_BL_BR, LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, LS_NONE }, +int transitionMove[Q_NUM_QUADS][Q_NUM_QUADS] = { + {LS_NONE, LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, LS_NONE}, + {LS_T1__R_BR, LS_NONE, LS_T1__R_TR, LS_T1__R_T_, LS_T1__R_TL, LS_T1__R__L, LS_T1__R_BL, LS_NONE}, + {LS_T1_TR_BR, LS_T1_TR__R, LS_NONE, LS_T1_TR_T_, LS_T1_TR_TL, LS_T1_TR__L, LS_T1_TR_BL, LS_NONE}, + {LS_T1_T__BR, LS_T1_T___R, LS_T1_T__TR, LS_NONE, LS_T1_T__TL, LS_T1_T___L, LS_T1_T__BL, LS_NONE}, + {LS_T1_TL_BR, LS_T1_TL__R, LS_T1_TL_TR, LS_T1_TL_T_, LS_NONE, LS_T1_TL__L, LS_T1_TL_BL, LS_NONE}, + {LS_T1__L_BR, LS_T1__L__R, LS_T1__L_TR, LS_T1__L_T_, LS_T1__L_TL, LS_NONE, LS_T1__L_BL, LS_NONE}, + {LS_T1_BL_BR, LS_T1_BL__R, LS_T1_BL_TR, LS_T1_BL_T_, LS_T1_BL_TL, LS_T1_BL__L, LS_NONE, LS_NONE}, + {LS_T1_BL_BR, LS_T1_BR__R, LS_T1_BR_TR, LS_T1_BR_T_, LS_T1_BR_TL, LS_T1_BR__L, LS_T1_BR_BL, LS_NONE}, }; -saberMoveName_t PM_AttackMoveForQuad( int quad ) -{ - switch ( quad ) - { +saberMoveName_t PM_AttackMoveForQuad(int quad) { + switch (quad) { case Q_B: case Q_BR: return LS_A_BR2TL; @@ -393,13 +376,10 @@ saberMoveName_t PM_AttackMoveForQuad( int quad ) qboolean PM_SaberKataDone(int curmove, int newmove); -int PM_SaberAnimTransitionAnim( int curmove, int newmove ) -{ +int PM_SaberAnimTransitionAnim(int curmove, int newmove) { int retmove = newmove; - if ( curmove == LS_READY ) - {//just standing there - switch ( newmove ) - { + if (curmove == LS_READY) { // just standing there + switch (newmove) { case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -407,20 +387,16 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the start - retmove = LS_S_TL2BR + (newmove-LS_A_TL2BR); + // transition is the start + retmove = LS_S_TL2BR + (newmove - LS_A_TL2BR); break; } - } - else - { - switch ( newmove ) - { - //transitioning to ready pose + } else { + switch (newmove) { + // transitioning to ready pose case LS_READY: - switch ( curmove ) - { - //transitioning from an attack + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -428,12 +404,12 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - //transition is the return - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); + // transition is the return + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); break; } break; - //transitioning to an attack + // transitioning to an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -441,27 +417,18 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_A_R2L: case LS_A_TR2BL: case LS_A_T2B: - if ( newmove == curmove ) - { - //going into an attack - if ( PM_SaberKataDone( curmove, newmove ) ) - {//done with this kata, must return to ready before attack again - retmove = LS_R_TL2BR + (newmove-LS_A_TL2BR); - } - else - {//okay to chain to another attack + if (newmove == curmove) { + // going into an attack + if (PM_SaberKataDone(curmove, newmove)) { // done with this kata, must return to ready before attack again + retmove = LS_R_TL2BR + (newmove - LS_A_TL2BR); + } else { // okay to chain to another attack retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; } - } - else if ( saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad ) - {//new move starts from same quadrant + } else if (saberMoveData[curmove].endQuad == saberMoveData[newmove].startQuad) { // new move starts from same quadrant retmove = newmove; - } - else - { - switch ( curmove ) - { - //transitioning from an attack + } else { + switch (curmove) { + // transitioning from an attack case LS_A_TL2BR: case LS_A_L2R: case LS_A_BL2TR: @@ -479,7 +446,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_D1_B_: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //transitioning from a return + // transitioning from a return case LS_R_TL2BR: case LS_R_L2R: case LS_R_BL2TR: @@ -487,7 +454,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_R_R2L: case LS_R_TR2BL: case LS_R_T2B: - //transitioning from a bounce + // transitioning from a bounce /* case LS_BOUNCE_UL2LL: case LS_BOUNCE_LL2UL: @@ -505,7 +472,7 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_BOUNCE_LR: case LS_BOUNCE_LL: */ - //transitioning from a parry/reflection/knockaway/broken parry + // transitioning from a parry/reflection/knockaway/broken parry case LS_PARRY_UP: case LS_PARRY_UR: case LS_PARRY_UL: @@ -536,362 +503,259 @@ int PM_SaberAnimTransitionAnim( int curmove, int newmove ) case LS_H1_BL: retmove = transitionMove[saberMoveData[curmove].endQuad][saberMoveData[newmove].startQuad]; break; - //NB: transitioning from transitions is fine + // NB: transitioning from transitions is fine } } break; - //transitioning to any other anim is not supported + // transitioning to any other anim is not supported } } - if ( retmove == LS_NONE ) - { + if (retmove == LS_NONE) { return newmove; } return retmove; } -extern qboolean BG_InKnockDown( int anim ); -saberMoveName_t PM_CheckStabDown( void ) -{ +extern qboolean BG_InKnockDown(int anim); +saberMoveName_t PM_CheckStabDown(void) { vec3_t faceFwd, facingAngles; vec3_t fwd; bgEntity_t *ent = NULL; trace_t tr; - //yeah, vm's may complain, but.. who cares! + // yeah, vm's may complain, but.. who cares! vec3_t trmins = {-15, -15, -15}; vec3_t trmaxs = {15, 15, 15}; - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber1 - && (saber1->saberFlags&SFL_NO_STABDOWN) ) - { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + if (saber1 && (saber1->saberFlags & SFL_NO_STABDOWN)) { return LS_NONE; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_STABDOWN) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_STABDOWN)) { return LS_NONE; } - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//sorry must be on ground! + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // sorry must be on ground! return LS_NONE; } - if ( pm->ps->clientNum < MAX_CLIENTS ) - {//player + if (pm->ps->clientNum < MAX_CLIENTS) { // player pm->ps->velocity[2] = 0; pm->cmd.upmove = 0; } VectorSet(facingAngles, 0, pm->ps->viewangles[YAW], 0); - AngleVectors( facingAngles, faceFwd, NULL, NULL ); + AngleVectors(facingAngles, faceFwd, NULL, NULL); - //FIXME: need to only move forward until we bump into our target...? + // FIXME: need to only move forward until we bump into our target...? VectorMA(pm->ps->origin, 164.0f, faceFwd, fwd); pm->trace(&tr, pm->ps->origin, trmins, trmaxs, fwd, pm->ps->clientNum, MASK_PLAYERSOLID); - if (tr.entityNum < ENTITYNUM_WORLD) - { + if (tr.entityNum < ENTITYNUM_WORLD) { ent = PM_BGEntForNum(tr.entityNum); } - if ( ent && - (ent->s.eType == ET_PLAYER || ent->s.eType == ET_NPC) && - BG_InKnockDown( ent->s.legsAnim ) ) - {//guy is on the ground below me, do a top-down attack - if ( pm->ps->fd.saberAnimLevel == SS_DUAL ) - { + if (ent && (ent->s.eType == ET_PLAYER || ent->s.eType == ET_NPC) && BG_InKnockDown(ent->s.legsAnim)) { // guy is on the ground below me, do a top-down + // attack + if (pm->ps->fd.saberAnimLevel == SS_DUAL) { return LS_STABDOWN_DUAL; - } - else if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { + } else if (pm->ps->fd.saberAnimLevel == SS_STAFF) { return LS_STABDOWN_STAFF; - } - else - { + } else { return LS_STABDOWN; } } return LS_NONE; } -int PM_SaberMoveQuadrantForMovement( usercmd_t *ucmd ) -{ - if ( ucmd->rightmove > 0 ) - {//moving right - if ( ucmd->forwardmove > 0 ) - {//forward right = TL2BR slash +int PM_SaberMoveQuadrantForMovement(usercmd_t *ucmd) { + if (ucmd->rightmove > 0) { // moving right + if (ucmd->forwardmove > 0) { // forward right = TL2BR slash return Q_TL; - } - else if ( ucmd->forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (ucmd->forwardmove < 0) { // backward right = BL2TR uppercut return Q_BL; - } - else - {//just right is a left slice + } else { // just right is a left slice return Q_L; } - } - else if ( ucmd->rightmove < 0 ) - {//moving left - if ( ucmd->forwardmove > 0 ) - {//forward left = TR2BL slash + } else if (ucmd->rightmove < 0) { // moving left + if (ucmd->forwardmove > 0) { // forward left = TR2BL slash return Q_TR; - } - else if ( ucmd->forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (ucmd->forwardmove < 0) { // backward left = BR2TL uppercut return Q_BR; - } - else - {//just left is a right slice + } else { // just left is a right slice return Q_R; } - } - else - {//not moving left or right - if ( ucmd->forwardmove > 0 ) - {//forward= T2B slash + } else { // not moving left or right + if (ucmd->forwardmove > 0) { // forward= T2B slash return Q_T; - } - else if ( ucmd->forwardmove < 0 ) - {//backward= T2B slash //or B2T uppercut? + } else if (ucmd->forwardmove < 0) { // backward= T2B slash //or B2T uppercut? return Q_T; - } - else - {//Not moving at all + } else { // Not moving at all return Q_R; } } } //=================================================================== -qboolean PM_SaberInBounce( int move ) -{ - if ( move >= LS_B1_BR && move <= LS_B1_BL ) - { +qboolean PM_SaberInBounce(int move) { + if (move >= LS_B1_BR && move <= LS_B1_BL) { return qtrue; } - if ( move >= LS_D1_BR && move <= LS_D1_BL ) - { + if (move >= LS_D1_BR && move <= LS_D1_BL) { return qtrue; } return qfalse; } -qboolean PM_SaberInTransition( int move ); - -int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = -{ -// Q_BR,Q_BR, Q_BR,Q_R, Q_BR,Q_TR, Q_BR,Q_T, Q_BR,Q_TL, Q_BR,Q_L, Q_BR,Q_BL, Q_BR,Q_B, - { 0, 45, 90, 135, 180, 215, 270, 45 }, -// Q_R,Q_BR, Q_R,Q_R, Q_R,Q_TR, Q_R,Q_T, Q_R,Q_TL, Q_R,Q_L, Q_R,Q_BL, Q_R,Q_B, - { 45, 0, 45, 90, 135, 180, 215, 90 }, -// Q_TR,Q_BR, Q_TR,Q_R, Q_TR,Q_TR, Q_TR,Q_T, Q_TR,Q_TL, Q_TR,Q_L, Q_TR,Q_BL, Q_TR,Q_B, - { 90, 45, 0, 45, 90, 135, 180, 135 }, -// Q_T,Q_BR, Q_T,Q_R, Q_T,Q_TR, Q_T,Q_T, Q_T,Q_TL, Q_T,Q_L, Q_T,Q_BL, Q_T,Q_B, - { 135, 90, 45, 0, 45, 90, 135, 180 }, -// Q_TL,Q_BR, Q_TL,Q_R, Q_TL,Q_TR, Q_TL,Q_T, Q_TL,Q_TL, Q_TL,Q_L, Q_TL,Q_BL, Q_TL,Q_B, - { 180, 135, 90, 45, 0, 45, 90, 135 }, -// Q_L,Q_BR, Q_L,Q_R, Q_L,Q_TR, Q_L,Q_T, Q_L,Q_TL, Q_L,Q_L, Q_L,Q_BL, Q_L,Q_B, - { 215, 180, 135, 90, 45, 0, 45, 90 }, -// Q_BL,Q_BR, Q_BL,Q_R, Q_BL,Q_TR, Q_BL,Q_T, Q_BL,Q_TL, Q_BL,Q_L, Q_BL,Q_BL, Q_BL,Q_B, - { 270, 215, 180, 135, 90, 45, 0, 45 }, -// Q_B,Q_BR, Q_B,Q_R, Q_B,Q_TR, Q_B,Q_T, Q_B,Q_TL, Q_B,Q_L, Q_B,Q_BL, Q_B,Q_B, - { 45, 90, 135, 180, 135, 90, 45, 0 }, +qboolean PM_SaberInTransition(int move); + +int saberMoveTransitionAngle[Q_NUM_QUADS][Q_NUM_QUADS] = { + // Q_BR,Q_BR, Q_BR,Q_R, Q_BR,Q_TR, Q_BR,Q_T, Q_BR,Q_TL, Q_BR,Q_L, Q_BR,Q_BL, Q_BR,Q_B, + {0, 45, 90, 135, 180, 215, 270, 45}, + // Q_R,Q_BR, Q_R,Q_R, Q_R,Q_TR, Q_R,Q_T, Q_R,Q_TL, Q_R,Q_L, Q_R,Q_BL, Q_R,Q_B, + {45, 0, 45, 90, 135, 180, 215, 90}, + // Q_TR,Q_BR, Q_TR,Q_R, Q_TR,Q_TR, Q_TR,Q_T, Q_TR,Q_TL, Q_TR,Q_L, Q_TR,Q_BL, Q_TR,Q_B, + {90, 45, 0, 45, 90, 135, 180, 135}, + // Q_T,Q_BR, Q_T,Q_R, Q_T,Q_TR, Q_T,Q_T, Q_T,Q_TL, Q_T,Q_L, Q_T,Q_BL, Q_T,Q_B, + {135, 90, 45, 0, 45, 90, 135, 180}, + // Q_TL,Q_BR, Q_TL,Q_R, Q_TL,Q_TR, Q_TL,Q_T, Q_TL,Q_TL, Q_TL,Q_L, Q_TL,Q_BL, Q_TL,Q_B, + {180, 135, 90, 45, 0, 45, 90, 135}, + // Q_L,Q_BR, Q_L,Q_R, Q_L,Q_TR, Q_L,Q_T, Q_L,Q_TL, Q_L,Q_L, Q_L,Q_BL, Q_L,Q_B, + {215, 180, 135, 90, 45, 0, 45, 90}, + // Q_BL,Q_BR, Q_BL,Q_R, Q_BL,Q_TR, Q_BL,Q_T, Q_BL,Q_TL, Q_BL,Q_L, Q_BL,Q_BL, Q_BL,Q_B, + {270, 215, 180, 135, 90, 45, 0, 45}, + // Q_B,Q_BR, Q_B,Q_R, Q_B,Q_TR, Q_B,Q_T, Q_B,Q_TL, Q_B,Q_L, Q_B,Q_BL, Q_B,Q_B, + {45, 90, 135, 180, 135, 90, 45, 0}, }; -int PM_SaberAttackChainAngle( int move1, int move2 ) -{ - if ( move1 == -1 || move2 == -1 ) - { +int PM_SaberAttackChainAngle(int move1, int move2) { + if (move1 == -1 || move2 == -1) { return -1; } return saberMoveTransitionAngle[saberMoveData[move1].endQuad][saberMoveData[move2].startQuad]; } -qboolean PM_SaberKataDone(int curmove, int newmove) -{ - if (pm->ps->m_iVehicleNum) - { //never continue kata on vehicle - if (pm->ps->saberAttackChainCount > 0) - { +qboolean PM_SaberKataDone(int curmove, int newmove) { + if (pm->ps->m_iVehicleNum) { // never continue kata on vehicle + if (pm->ps->saberAttackChainCount > 0) { return qtrue; } } - if ( pm->ps->fd.saberAnimLevel == SS_DESANN || pm->ps->fd.saberAnimLevel == SS_TAVION ) - {//desann and tavion can link up as many attacks as they want + if (pm->ps->fd.saberAnimLevel == SS_DESANN || pm->ps->fd.saberAnimLevel == SS_TAVION) { // desann and tavion can link up as many attacks as they want return qfalse; } - if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { - //TEMP: for now, let staff attacks infinitely chain + if (pm->ps->fd.saberAnimLevel == SS_STAFF) { + // TEMP: for now, let staff attacks infinitely chain return qfalse; - } - else if ( pm->ps->fd.saberAnimLevel == SS_DUAL ) - { - //TEMP: for now, let staff attacks infinitely chain + } else if (pm->ps->fd.saberAnimLevel == SS_DUAL) { + // TEMP: for now, let staff attacks infinitely chain return qfalse; - } - else if ( pm->ps->fd.saberAnimLevel == FORCE_LEVEL_3 ) - { - if ( curmove == LS_NONE || newmove == LS_NONE ) - { - if ( pm->ps->fd.saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > PM_irand_timesync( 0, 1 ) ) - { + } else if (pm->ps->fd.saberAnimLevel == FORCE_LEVEL_3) { + if (curmove == LS_NONE || newmove == LS_NONE) { + if (pm->ps->fd.saberAnimLevel >= FORCE_LEVEL_3 && pm->ps->saberAttackChainCount > PM_irand_timesync(0, 1)) { return qtrue; } - } - else if ( pm->ps->saberAttackChainCount > PM_irand_timesync( 2, 3 ) ) - { + } else if (pm->ps->saberAttackChainCount > PM_irand_timesync(2, 3)) { return qtrue; - } - else if ( pm->ps->saberAttackChainCount > 0 ) - { - int chainAngle = PM_SaberAttackChainAngle( curmove, newmove ); - if ( chainAngle < 135 || chainAngle > 215 ) - {//if trying to chain to a move that doesn't continue the momentum + } else if (pm->ps->saberAttackChainCount > 0) { + int chainAngle = PM_SaberAttackChainAngle(curmove, newmove); + if (chainAngle < 135 || chainAngle > 215) { // if trying to chain to a move that doesn't continue the momentum return qtrue; - } - else if ( chainAngle == 180 ) - {//continues the momentum perfectly, allow it to chain 66% of the time - if ( pm->ps->saberAttackChainCount > 1 ) - { + } else if (chainAngle == 180) { // continues the momentum perfectly, allow it to chain 66% of the time + if (pm->ps->saberAttackChainCount > 1) { return qtrue; } - } - else - {//would continue the movement somewhat, 50% chance of continuing - if ( pm->ps->saberAttackChainCount > 2 ) - { + } else { // would continue the movement somewhat, 50% chance of continuing + if (pm->ps->saberAttackChainCount > 2) { return qtrue; } } } - } - else - {//Perhaps have chainAngle influence fast and medium chains as well? For now, just do level 3. - if (newmove == LS_A_TL2BR || - newmove == LS_A_L2R || - newmove == LS_A_BL2TR || - newmove == LS_A_BR2TL || - newmove == LS_A_R2L || - newmove == LS_A_TR2BL ) - { //lower chaining tolerance for spinning saber anims + } else { // Perhaps have chainAngle influence fast and medium chains as well? For now, just do level 3. + if (newmove == LS_A_TL2BR || newmove == LS_A_L2R || newmove == LS_A_BL2TR || newmove == LS_A_BR2TL || newmove == LS_A_R2L || + newmove == LS_A_TR2BL) { // lower chaining tolerance for spinning saber anims int chainTolerance; - if (pm->ps->fd.saberAnimLevel == FORCE_LEVEL_1) - { + if (pm->ps->fd.saberAnimLevel == FORCE_LEVEL_1) { chainTolerance = 5; - } - else - { + } else { chainTolerance = 3; } - if (pm->ps->saberAttackChainCount >= chainTolerance && PM_irand_timesync(1, pm->ps->saberAttackChainCount) > chainTolerance) - { + if (pm->ps->saberAttackChainCount >= chainTolerance && PM_irand_timesync(1, pm->ps->saberAttackChainCount) > chainTolerance) { return qtrue; } } - if ( pm->ps->fd.saberAnimLevel == FORCE_LEVEL_2 && pm->ps->saberAttackChainCount > PM_irand_timesync( 2, 5 ) ) - { + if (pm->ps->fd.saberAnimLevel == FORCE_LEVEL_2 && pm->ps->saberAttackChainCount > PM_irand_timesync(2, 5)) { return qtrue; } } return qfalse; } -void PM_SetAnimFrame( playerState_t *gent, int frame, qboolean torso, qboolean legs ) -{ - gent->saberLockFrame = frame; -} +void PM_SetAnimFrame(playerState_t *gent, int frame, qboolean torso, qboolean legs) { gent->saberLockFrame = frame; } -int PM_SaberLockWinAnim( qboolean victory, qboolean superBreak ) -{ +int PM_SaberLockWinAnim(qboolean victory, qboolean superBreak) { int winAnim = -1; - switch ( pm->ps->torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, animTable[pm->ps->torsoAnim].name ); -#endif -*/ + switch (pm->ps->torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", pm->gent->NPC_type, pm->ps->torsoAnim, + animTable[pm->ps->torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( superBreak ) - { + if (superBreak) { winAnim = BOTH_LK_S_S_T_SB_1_W; - } - else if ( !victory ) - { + } else if (!victory) { winAnim = BOTH_BF1BREAK; - } - else - { + } else { pm->ps->saberMove = LS_A_T2B; winAnim = BOTH_A3_T__B_; } break; case BOTH_BF1LOCK: - if ( superBreak ) - { + if (superBreak) { winAnim = BOTH_LK_S_S_T_SB_1_W; - } - else if ( !victory ) - { + } else if (!victory) { winAnim = BOTH_KNOCKDOWN4; - } - else - { + } else { pm->ps->saberMove = LS_K1_T_; winAnim = BOTH_K1_S1_T_; } break; case BOTH_CWCIRCLELOCK: - if ( superBreak ) - { + if (superBreak) { winAnim = BOTH_LK_S_S_S_SB_1_W; - } - else if ( !victory ) - { - pm->ps->saberMove = LS_V1_BL;//pm->ps->saberBounceMove = + } else if (!victory) { + pm->ps->saberMove = LS_V1_BL; // pm->ps->saberBounceMove = pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BL_S1; - } - else - { + } else { winAnim = BOTH_CWCIRCLEBREAK; } break; case BOTH_CCWCIRCLELOCK: - if ( superBreak ) - { + if (superBreak) { winAnim = BOTH_LK_S_S_S_SB_1_W; - } - else if ( !victory ) - { - pm->ps->saberMove = LS_V1_BR;//pm->ps->saberBounceMove = + } else if (!victory) { + pm->ps->saberMove = LS_V1_BR; // pm->ps->saberBounceMove = pm->ps->saberBlocked = BLOCKED_PARRY_BROKEN; winAnim = BOTH_V1_BR_S1; - } - else - { + } else { winAnim = BOTH_CCWCIRCLEBREAK; } break; default: - //must be using new system: + // must be using new system: break; } - if ( winAnim != -1 ) - { - PM_SetAnim( SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (winAnim != -1) { + PM_SetAnim(SETANIM_BOTH, winAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->weaponTime = pm->ps->torsoTimer; pm->ps->saberBlocked = BLOCKED_NONE; pm->ps->weaponstate = WEAPON_FIRING; @@ -907,89 +771,63 @@ int PM_SaberLockWinAnim( qboolean victory, qboolean superBreak ) } // Need to avoid nesting namespaces! -#ifdef _GAME //including game headers on cgame is FORBIDDEN ^_^ - #include "g_local.h" - extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags); - extern gentity_t g_entities[]; +#ifdef _GAME // including game headers on cgame is FORBIDDEN ^_^ +#include "g_local.h" +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags); +extern gentity_t g_entities[]; #elif defined(_CGAME) - #include "cgame/cg_local.h" //ahahahahhahahaha@$!$! +#include "cgame/cg_local.h" //ahahahahhahahaha@$!$! #endif -int PM_SaberLockLoseAnim( playerState_t *genemy, qboolean victory, qboolean superBreak ) -{ +int PM_SaberLockLoseAnim(playerState_t *genemy, qboolean victory, qboolean superBreak) { int loseAnim = -1; - switch ( genemy->torsoAnim ) - { -/* - default: -#ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, animTable[genemy->client->ps.torsoAnim].name ); -#endif -*/ + switch (genemy->torsoAnim) { + /* + default: + #ifndef FINAL_BUILD + Com_Printf( S_COLOR_RED"ERROR-PM_SaberLockBreak: %s not in saberlock anim, anim = (%d)%s\n", genemy->NPC_type, genemy->client->ps.torsoAnim, + animTable[genemy->client->ps.torsoAnim].name ); #endif + */ case BOTH_BF2LOCK: - if ( superBreak ) - { + if (superBreak) { loseAnim = BOTH_LK_S_S_T_SB_1_L; - } - else if ( !victory ) - { + } else if (!victory) { loseAnim = BOTH_BF1BREAK; - } - else - { - if ( !victory ) - {//no-one won + } else { + if (!victory) { // no-one won genemy->saberMove = LS_K1_T_; loseAnim = BOTH_K1_S1_T_; - } - else - {//FIXME: this anim needs to transition back to ready when done + } else { // FIXME: this anim needs to transition back to ready when done loseAnim = BOTH_BF1BREAK; } } break; case BOTH_BF1LOCK: - if ( superBreak ) - { + if (superBreak) { loseAnim = BOTH_LK_S_S_T_SB_1_L; - } - else if ( !victory ) - { + } else if (!victory) { loseAnim = BOTH_KNOCKDOWN4; - } - else - { - if ( !victory ) - {//no-one won + } else { + if (!victory) { // no-one won genemy->saberMove = LS_A_T2B; loseAnim = BOTH_A3_T__B_; - } - else - { + } else { loseAnim = BOTH_KNOCKDOWN4; } } break; case BOTH_CWCIRCLELOCK: - if ( superBreak ) - { + if (superBreak) { loseAnim = BOTH_LK_S_S_S_SB_1_L; - } - else if ( !victory ) - { - genemy->saberMove = LS_V1_BL;//genemy->saberBounceMove = + } else if (!victory) { + genemy->saberMove = LS_V1_BL; // genemy->saberBounceMove = genemy->saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; - } - else - { - if ( !victory ) - {//no-one won + } else { + if (!victory) { // no-one won loseAnim = BOTH_CCWCIRCLEBREAK; - } - else - { - genemy->saberMove = LS_V1_BL;//genemy->saberBounceMove = + } else { + genemy->saberMove = LS_V1_BL; // genemy->saberBounceMove = genemy->saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BL_S1; /* @@ -1001,25 +839,17 @@ int PM_SaberLockLoseAnim( playerState_t *genemy, qboolean victory, qboolean supe } break; case BOTH_CCWCIRCLELOCK: - if ( superBreak ) - { + if (superBreak) { loseAnim = BOTH_LK_S_S_S_SB_1_L; - } - else if ( !victory ) - { - genemy->saberMove = LS_V1_BR;//genemy->saberBounceMove = + } else if (!victory) { + genemy->saberMove = LS_V1_BR; // genemy->saberBounceMove = genemy->saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; - } - else - { - if ( !victory ) - {//no-one won + } else { + if (!victory) { // no-one won loseAnim = BOTH_CWCIRCLEBREAK; - } - else - { - genemy->saberMove = LS_V1_BR;//genemy->saberBounceMove = + } else { + genemy->saberMove = LS_V1_BR; // genemy->saberBounceMove = genemy->saberBlocked = BLOCKED_PARRY_BROKEN; loseAnim = BOTH_V1_BR_S1; /* @@ -1031,11 +861,10 @@ int PM_SaberLockLoseAnim( playerState_t *genemy, qboolean victory, qboolean supe } break; } - if ( loseAnim != -1 ) - { + if (loseAnim != -1) { #ifdef _GAME - NPC_SetAnim( &g_entities[genemy->clientNum], SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - genemy->weaponTime = genemy->torsoTimer;// + 250; + NPC_SetAnim(&g_entities[genemy->clientNum], SETANIM_BOTH, loseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + genemy->weaponTime = genemy->torsoTimer; // + 250; #endif genemy->saberBlocked = BLOCKED_NONE; genemy->weaponstate = WEAPON_READY; @@ -1043,67 +872,54 @@ int PM_SaberLockLoseAnim( playerState_t *genemy, qboolean victory, qboolean supe return loseAnim; } -int PM_SaberLockResultAnim( playerState_t *duelist, qboolean superBreak, qboolean won ) -{ +int PM_SaberLockResultAnim(playerState_t *duelist, qboolean superBreak, qboolean won) { int baseAnim = duelist->torsoAnim; - switch ( baseAnim ) - { - case BOTH_LK_S_S_S_L_2: //lock if I'm using single vs. a single and other intitiated + switch (baseAnim) { + case BOTH_LK_S_S_S_L_2: // lock if I'm using single vs. a single and other intitiated baseAnim = BOTH_LK_S_S_S_L_1; break; - case BOTH_LK_S_S_T_L_2: //lock if I'm using single vs. a single and other initiated + case BOTH_LK_S_S_T_L_2: // lock if I'm using single vs. a single and other initiated baseAnim = BOTH_LK_S_S_T_L_1; break; - case BOTH_LK_DL_DL_S_L_2: //lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_S_L_2: // lock if I'm using dual vs. dual and other initiated baseAnim = BOTH_LK_DL_DL_S_L_1; break; - case BOTH_LK_DL_DL_T_L_2: //lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_T_L_2: // lock if I'm using dual vs. dual and other initiated baseAnim = BOTH_LK_DL_DL_T_L_1; break; - case BOTH_LK_ST_ST_S_L_2: //lock if I'm using staff vs. a staff and other initiated + case BOTH_LK_ST_ST_S_L_2: // lock if I'm using staff vs. a staff and other initiated baseAnim = BOTH_LK_ST_ST_S_L_1; break; - case BOTH_LK_ST_ST_T_L_2: //lock if I'm using staff vs. a staff and other initiated + case BOTH_LK_ST_ST_T_L_2: // lock if I'm using staff vs. a staff and other initiated baseAnim = BOTH_LK_ST_ST_T_L_1; break; } - //what kind of break? - if ( !superBreak ) - { + // what kind of break? + if (!superBreak) { baseAnim -= 2; - } - else if ( superBreak ) - { + } else if (superBreak) { baseAnim += 1; - } - else - {//WTF? Not a valid result + } else { // WTF? Not a valid result return -1; } - //win or lose? - if ( won ) - { + // win or lose? + if (won) { baseAnim += 1; } - //play the anim and hold it + // play the anim and hold it #ifdef _GAME - //server-side: set it on the other guy, too - if ( duelist->clientNum == pm->ps->clientNum ) - {//me - PM_SetAnim( SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); - } - else - {//other guy - NPC_SetAnim( &g_entities[duelist->clientNum], SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + // server-side: set it on the other guy, too + if (duelist->clientNum == pm->ps->clientNum) { // me + PM_SetAnim(SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); + } else { // other guy + NPC_SetAnim(&g_entities[duelist->clientNum], SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } #else - PM_SetAnim( SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + PM_SetAnim(SETANIM_BOTH, baseAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); #endif - if ( superBreak - && !won ) - {//if you lose a superbreak, you're defenseless + if (superBreak && !won) { // if you lose a superbreak, you're defenseless /* //Taken care of in SetSaberBoxSize() //make saberent not block @@ -1116,25 +932,25 @@ int PM_SaberLockResultAnim( playerState_t *duelist, qboolean superBreak, qboolea } */ #ifdef _GAME - if ( 1 ) + if (1) #else - if ( duelist->clientNum == pm->ps->clientNum ) + if (duelist->clientNum == pm->ps->clientNum) #endif { - //set sabermove to none + // set sabermove to none duelist->saberMove = LS_NONE; - //Hold the anim a little longer than it is + // Hold the anim a little longer than it is duelist->torsoTimer += 250; } } #ifdef _GAME - if ( 1 ) + if (1) #else - if ( duelist->clientNum == pm->ps->clientNum ) + if (duelist->clientNum == pm->ps->clientNum) #endif { - //no attacking during this anim + // no attacking during this anim duelist->weaponTime = duelist->torsoTimer; duelist->saberBlocked = BLOCKED_NONE; /* @@ -1149,28 +965,25 @@ int PM_SaberLockResultAnim( playerState_t *duelist, qboolean superBreak, qboolea return baseAnim; } -void PM_SaberLockBreak( playerState_t *genemy, qboolean victory, int strength ) -{ - //qboolean punishLoser = qfalse; +void PM_SaberLockBreak(playerState_t *genemy, qboolean victory, int strength) { + // qboolean punishLoser = qfalse; qboolean noKnockdown = qfalse; - qboolean superBreak = (strength+pm->ps->saberLockHits > Q_irand(2,4)); + qboolean superBreak = (strength + pm->ps->saberLockHits > Q_irand(2, 4)); - //a single vs. single break - if ( PM_SaberLockWinAnim( victory, superBreak ) != -1 ) - PM_SaberLockLoseAnim( genemy, victory, superBreak ); + // a single vs. single break + if (PM_SaberLockWinAnim(victory, superBreak) != -1) + PM_SaberLockLoseAnim(genemy, victory, superBreak); - //must be a saberlock that's not between single and single... + // must be a saberlock that's not between single and single... else { - PM_SaberLockResultAnim( pm->ps, superBreak, qtrue ); + PM_SaberLockResultAnim(pm->ps, superBreak, qtrue); pm->ps->weaponstate = WEAPON_FIRING; - PM_SaberLockResultAnim( genemy, superBreak, qfalse ); + PM_SaberLockResultAnim(genemy, superBreak, qfalse); genemy->weaponstate = WEAPON_READY; } - if ( victory ) - { //someone lost the lock, so punish them by knocking them down - if ( pm->ps->saberLockHits && !superBreak ) - {//there was some over-power in the win, but not enough to superbreak + if (victory) { // someone lost the lock, so punish them by knocking them down + if (pm->ps->saberLockHits && !superBreak) { // there was some over-power in the win, but not enough to superbreak vec3_t oppDir; int newstrength = 8; @@ -1178,50 +991,45 @@ void PM_SaberLockBreak( playerState_t *genemy, qboolean victory, int strength ) VectorSubtract(genemy->origin, pm->ps->origin, oppDir); VectorNormalize(oppDir); - if (noKnockdown) - { - if (!genemy->saberEntityNum) - { //if he has already lost his saber then just knock him down + if (noKnockdown) { + if (!genemy->saberEntityNum) { // if he has already lost his saber then just knock him down noKnockdown = qfalse; } } - if (!noKnockdown && BG_KnockDownable(genemy)) - { + if (!noKnockdown && BG_KnockDownable(genemy)) { genemy->forceHandExtend = HANDEXTEND_KNOCKDOWN; genemy->forceHandExtendTime = pm->cmd.serverTime + 1100; - genemy->forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim + genemy->forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim genemy->otherKiller = pm->ps->clientNum; genemy->otherKillerTime = pm->cmd.serverTime + 5000; genemy->otherKillerDebounceTime = pm->cmd.serverTime + 100; - genemy->velocity[0] = oppDir[0]*(newstrength*40); - genemy->velocity[1] = oppDir[1]*(newstrength*40); + genemy->velocity[0] = oppDir[0] * (newstrength * 40); + genemy->velocity[1] = oppDir[1] * (newstrength * 40); genemy->velocity[2] = 100; } - pm->checkDuelLoss = genemy->clientNum+1; + pm->checkDuelLoss = genemy->clientNum + 1; pm->ps->saberEventFlags |= SEF_LOCK_WON; } - } - else - { //If no one lost, then shove each player away from the other + } else { // If no one lost, then shove each player away from the other vec3_t oppDir; int newstrength = 4; VectorSubtract(genemy->origin, pm->ps->origin, oppDir); VectorNormalize(oppDir); - genemy->velocity[0] = oppDir[0]*(newstrength*40); - genemy->velocity[1] = oppDir[1]*(newstrength*40); + genemy->velocity[0] = oppDir[0] * (newstrength * 40); + genemy->velocity[1] = oppDir[1] * (newstrength * 40); genemy->velocity[2] = 150; VectorSubtract(pm->ps->origin, genemy->origin, oppDir); VectorNormalize(oppDir); - pm->ps->velocity[0] = oppDir[0]*(newstrength*40); - pm->ps->velocity[1] = oppDir[1]*(newstrength*40); + pm->ps->velocity[0] = oppDir[0] * (newstrength * 40); + pm->ps->velocity[1] = oppDir[1] * (newstrength * 40); pm->ps->velocity[2] = 150; genemy->forceHandExtend = HANDEXTEND_WEAPONREADY; @@ -1236,69 +1044,57 @@ void PM_SaberLockBreak( playerState_t *genemy, qboolean victory, int strength ) pm->ps->forceHandExtend = HANDEXTEND_WEAPONREADY; - PM_AddEvent( EV_JUMP ); - if ( !victory ) - {//no-one won + PM_AddEvent(EV_JUMP); + if (!victory) { // no-one won BG_AddPredictableEventToPlayerstate(EV_JUMP, 0, genemy); - } - else - { - if ( PM_irand_timesync( 0, 1 ) ) - { - BG_AddPredictableEventToPlayerstate(EV_JUMP, PM_irand_timesync( 0, 75 ), genemy); + } else { + if (PM_irand_timesync(0, 1)) { + BG_AddPredictableEventToPlayerstate(EV_JUMP, PM_irand_timesync(0, 75), genemy); } } } -qboolean BG_CheckIncrementLockAnim( int anim, int winOrLose ) -{ - qboolean increment = qfalse;//??? - //RULE: if you are the first style in the lock anim, you advance from LOSING position to WINNING position +qboolean BG_CheckIncrementLockAnim(int anim, int winOrLose) { + qboolean increment = qfalse; //??? + // RULE: if you are the first style in the lock anim, you advance from LOSING position to WINNING position // if you are the second style in the lock anim, you advance from WINNING position to LOSING position - switch ( anim ) - { - //increment to win: - case BOTH_LK_DL_DL_S_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_S_L_2: //lock if I'm using dual vs. dual and other initiated - case BOTH_LK_DL_DL_T_L_1: //lock if I'm using dual vs. dual and I initiated - case BOTH_LK_DL_DL_T_L_2: //lock if I'm using dual vs. dual and other initiated - case BOTH_LK_DL_S_S_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_S_T_L_1: //lock if I'm using dual vs. a single - case BOTH_LK_DL_ST_S_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_DL_ST_T_L_1: //lock if I'm using dual vs. a staff - case BOTH_LK_S_S_S_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_S_T_L_2: //lock if I'm using single vs. a single and other initiated - case BOTH_LK_ST_S_S_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_S_T_L_1: //lock if I'm using staff vs. a single - case BOTH_LK_ST_ST_T_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_T_L_2: //lock if I'm using staff vs. a staff and other initiated - if ( winOrLose == SABERLOCK_WIN ) - { + switch (anim) { + // increment to win: + case BOTH_LK_DL_DL_S_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_S_L_2: // lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_DL_T_L_1: // lock if I'm using dual vs. dual and I initiated + case BOTH_LK_DL_DL_T_L_2: // lock if I'm using dual vs. dual and other initiated + case BOTH_LK_DL_S_S_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_S_T_L_1: // lock if I'm using dual vs. a single + case BOTH_LK_DL_ST_S_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_DL_ST_T_L_1: // lock if I'm using dual vs. a staff + case BOTH_LK_S_S_S_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_S_T_L_2: // lock if I'm using single vs. a single and other initiated + case BOTH_LK_ST_S_S_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_S_T_L_1: // lock if I'm using staff vs. a single + case BOTH_LK_ST_ST_T_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_T_L_2: // lock if I'm using staff vs. a staff and other initiated + if (winOrLose == SABERLOCK_WIN) { increment = qtrue; - } - else - { + } else { increment = qfalse; } break; - //decrement to win: - case BOTH_LK_S_DL_S_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_DL_T_L_1: //lock if I'm using single vs. a dual - case BOTH_LK_S_S_S_L_2: //lock if I'm using single vs. a single and other intitiated - case BOTH_LK_S_S_T_L_1: //lock if I'm using single vs. a single and I initiated - case BOTH_LK_S_ST_S_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_S_ST_T_L_1: //lock if I'm using single vs. a staff - case BOTH_LK_ST_DL_S_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_DL_T_L_1: //lock if I'm using staff vs. dual - case BOTH_LK_ST_ST_S_L_1: //lock if I'm using staff vs. a staff and I initiated - case BOTH_LK_ST_ST_S_L_2: //lock if I'm using staff vs. a staff and other initiated - if ( winOrLose == SABERLOCK_WIN ) - { + // decrement to win: + case BOTH_LK_S_DL_S_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_DL_T_L_1: // lock if I'm using single vs. a dual + case BOTH_LK_S_S_S_L_2: // lock if I'm using single vs. a single and other intitiated + case BOTH_LK_S_S_T_L_1: // lock if I'm using single vs. a single and I initiated + case BOTH_LK_S_ST_S_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_S_ST_T_L_1: // lock if I'm using single vs. a staff + case BOTH_LK_ST_DL_S_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_DL_T_L_1: // lock if I'm using staff vs. dual + case BOTH_LK_ST_ST_S_L_1: // lock if I'm using staff vs. a staff and I initiated + case BOTH_LK_ST_ST_S_L_2: // lock if I'm using staff vs. a staff and other initiated + if (winOrLose == SABERLOCK_WIN) { increment = qfalse; - } - else - { + } else { increment = qtrue; } break; @@ -1308,22 +1104,19 @@ qboolean BG_CheckIncrementLockAnim( int anim, int winOrLose ) return increment; } -extern qboolean ValidAnimFileIndex ( int index ); -void PM_SaberLocked( void ) -{ - int remaining = 0; +extern qboolean ValidAnimFileIndex(int index); +void PM_SaberLocked(void) { + int remaining = 0; playerState_t *genemy; bgEntity_t *eGenemy = PM_BGEntForNum(pm->ps->saberLockEnemy); - if (!eGenemy) - { + if (!eGenemy) { return; } genemy = eGenemy->playerState; - if ( !genemy ) - { + if (!genemy) { return; } /*if ( ( (pm->ps->torsoAnim) == BOTH_BF2LOCK || @@ -1336,11 +1129,7 @@ void PM_SaberLocked( void ) (genemy->torsoAnim) == BOTH_CCWCIRCLELOCK ) ) */ //yeah.. - if (pm->ps->saberLockFrame && - genemy->saberLockFrame && - BG_InSaberLock(pm->ps->torsoAnim) && - BG_InSaberLock(genemy->torsoAnim)) - { + if (pm->ps->saberLockFrame && genemy->saberLockFrame && BG_InSaberLock(pm->ps->torsoAnim) && BG_InSaberLock(genemy->torsoAnim)) { float dist = 0; pm->ps->torsoTimer = 0; @@ -1348,10 +1137,9 @@ void PM_SaberLocked( void ) genemy->torsoTimer = 0; genemy->weaponTime = 0; - dist = DistanceSquared(pm->ps->origin,genemy->origin); - if ( dist < 64 || dist > 6400 ) - {//between 8 and 80 from each other - PM_SaberLockBreak( genemy, qfalse, 0 ); + dist = DistanceSquared(pm->ps->origin, genemy->origin); + if (dist < 64 || dist > 6400) { // between 8 and 80 from each other + PM_SaberLockBreak(genemy, qfalse, 0); return; } /* @@ -1362,12 +1150,11 @@ void PM_SaberLocked( void ) return; } */ - if ( pm->ps->saberLockAdvance ) - {//holding attack + if (pm->ps->saberLockAdvance) { // holding attack animation_t *anim; - float currentFrame; - int curFrame; - int strength = pm->ps->fd.forcePowerLevel[FP_SABER_OFFENSE]+1; + float currentFrame; + int curFrame; + int strength = pm->ps->fd.forcePowerLevel[FP_SABER_OFFENSE] + 1; pm->ps->saberLockAdvance = qfalse; @@ -1375,138 +1162,95 @@ void PM_SaberLocked( void ) currentFrame = pm->ps->saberLockFrame; - //advance/decrement my frame number - if ( BG_InSaberLockOld( pm->ps->torsoAnim ) ) - { //old locks - if ( (pm->ps->torsoAnim) == BOTH_CCWCIRCLELOCK || - (pm->ps->torsoAnim) == BOTH_BF2LOCK ) - { - curFrame = floor( currentFrame )-strength; - //drop my frame one - if ( curFrame <= anim->firstFrame ) - {//I won! Break out - PM_SaberLockBreak( genemy, qtrue, strength ); + // advance/decrement my frame number + if (BG_InSaberLockOld(pm->ps->torsoAnim)) { // old locks + if ((pm->ps->torsoAnim) == BOTH_CCWCIRCLELOCK || (pm->ps->torsoAnim) == BOTH_BF2LOCK) { + curFrame = floor(currentFrame) - strength; + // drop my frame one + if (curFrame <= anim->firstFrame) { // I won! Break out + PM_SaberLockBreak(genemy, qtrue, strength); return; + } else { + PM_SetAnimFrame(pm->ps, curFrame, qtrue, qtrue); + remaining = curFrame - anim->firstFrame; } - else - { - PM_SetAnimFrame( pm->ps, curFrame, qtrue, qtrue ); - remaining = curFrame-anim->firstFrame; - } - } - else - { - curFrame = ceil( currentFrame )+strength; - //advance my frame one - if ( curFrame >= anim->firstFrame+anim->numFrames ) - {//I won! Break out - PM_SaberLockBreak( genemy, qtrue, strength ); + } else { + curFrame = ceil(currentFrame) + strength; + // advance my frame one + if (curFrame >= anim->firstFrame + anim->numFrames) { // I won! Break out + PM_SaberLockBreak(genemy, qtrue, strength); return; - } - else - { - PM_SetAnimFrame( pm->ps, curFrame, qtrue, qtrue ); - remaining = anim->firstFrame+anim->numFrames-curFrame; + } else { + PM_SetAnimFrame(pm->ps, curFrame, qtrue, qtrue); + remaining = anim->firstFrame + anim->numFrames - curFrame; } } - } - else - { //new locks - if ( BG_CheckIncrementLockAnim( pm->ps->torsoAnim, SABERLOCK_WIN ) ) - { - curFrame = ceil( currentFrame )+strength; - //advance my frame one - if ( curFrame >= anim->firstFrame+anim->numFrames ) - {//I won! Break out - PM_SaberLockBreak( genemy, qtrue, strength ); + } else { // new locks + if (BG_CheckIncrementLockAnim(pm->ps->torsoAnim, SABERLOCK_WIN)) { + curFrame = ceil(currentFrame) + strength; + // advance my frame one + if (curFrame >= anim->firstFrame + anim->numFrames) { // I won! Break out + PM_SaberLockBreak(genemy, qtrue, strength); return; + } else { + PM_SetAnimFrame(pm->ps, curFrame, qtrue, qtrue); + remaining = anim->firstFrame + anim->numFrames - curFrame; } - else - { - PM_SetAnimFrame( pm->ps, curFrame, qtrue, qtrue ); - remaining = anim->firstFrame+anim->numFrames-curFrame; - } - } - else - { - curFrame = floor( currentFrame )-strength; - //drop my frame one - if ( curFrame <= anim->firstFrame ) - {//I won! Break out - PM_SaberLockBreak( genemy, qtrue, strength ); + } else { + curFrame = floor(currentFrame) - strength; + // drop my frame one + if (curFrame <= anim->firstFrame) { // I won! Break out + PM_SaberLockBreak(genemy, qtrue, strength); return; - } - else - { - PM_SetAnimFrame( pm->ps, curFrame, qtrue, qtrue ); - remaining = curFrame-anim->firstFrame; + } else { + PM_SetAnimFrame(pm->ps, curFrame, qtrue, qtrue); + remaining = curFrame - anim->firstFrame; } } } - if ( !PM_irand_timesync( 0, 2 ) ) - { - PM_AddEvent( EV_JUMP ); + if (!PM_irand_timesync(0, 2)) { + PM_AddEvent(EV_JUMP); } - //advance/decrement enemy frame number + // advance/decrement enemy frame number anim = &pm->animations[(genemy->torsoAnim)]; - if ( BG_InSaberLockOld( genemy->torsoAnim ) ) - { - if ( (genemy->torsoAnim) == BOTH_CWCIRCLELOCK || - (genemy->torsoAnim) == BOTH_BF1LOCK ) - { - if ( !PM_irand_timesync( 0, 2 ) ) - { - BG_AddPredictableEventToPlayerstate(EV_PAIN, floor((float)80/100*100.0f), genemy); + if (BG_InSaberLockOld(genemy->torsoAnim)) { + if ((genemy->torsoAnim) == BOTH_CWCIRCLELOCK || (genemy->torsoAnim) == BOTH_BF1LOCK) { + if (!PM_irand_timesync(0, 2)) { + BG_AddPredictableEventToPlayerstate(EV_PAIN, floor((float)80 / 100 * 100.0f), genemy); } - PM_SetAnimFrame( genemy, anim->firstFrame+remaining, qtrue, qtrue ); - } - else - { - PM_SetAnimFrame( genemy, anim->firstFrame+anim->numFrames-remaining, qtrue, qtrue ); + PM_SetAnimFrame(genemy, anim->firstFrame + remaining, qtrue, qtrue); + } else { + PM_SetAnimFrame(genemy, anim->firstFrame + anim->numFrames - remaining, qtrue, qtrue); } - } - else - {//new locks - if ( BG_CheckIncrementLockAnim( genemy->torsoAnim, SABERLOCK_LOSE ) ) - { - if ( !PM_irand_timesync( 0, 2 ) ) - { - BG_AddPredictableEventToPlayerstate(EV_PAIN, floor((float)80/100*100.0f), genemy); + } else { // new locks + if (BG_CheckIncrementLockAnim(genemy->torsoAnim, SABERLOCK_LOSE)) { + if (!PM_irand_timesync(0, 2)) { + BG_AddPredictableEventToPlayerstate(EV_PAIN, floor((float)80 / 100 * 100.0f), genemy); } - PM_SetAnimFrame( genemy, anim->firstFrame+anim->numFrames-remaining, qtrue, qtrue ); - } - else - { - PM_SetAnimFrame( genemy, anim->firstFrame+remaining, qtrue, qtrue ); + PM_SetAnimFrame(genemy, anim->firstFrame + anim->numFrames - remaining, qtrue, qtrue); + } else { + PM_SetAnimFrame(genemy, anim->firstFrame + remaining, qtrue, qtrue); } } } - } - else - {//something broke us out of it - PM_SaberLockBreak( genemy, qfalse, 0 ); + } else { // something broke us out of it + PM_SaberLockBreak(genemy, qfalse, 0); } } -qboolean PM_SaberInBrokenParry( int move ) -{ - if ( move >= LS_V1_BR && move <= LS_V1_B_ ) - { +qboolean PM_SaberInBrokenParry(int move) { + if (move >= LS_V1_BR && move <= LS_V1_B_) { return qtrue; } - if ( move >= LS_H1_T_ && move <= LS_H1_BL ) - { + if (move >= LS_H1_T_ && move <= LS_H1_BL) { return qtrue; } return qfalse; } - -int PM_BrokenParryForParry( int move ) -{ - switch ( move ) - { +int PM_BrokenParryForParry(int move) { + switch (move) { case LS_PARRY_UP: return LS_H1_T_; break; @@ -1531,8 +1275,7 @@ int PM_BrokenParryForParry( int move ) #define BACK_STAB_DISTANCE 128 -qboolean PM_CanBackstab(void) -{ +qboolean PM_CanBackstab(void) { trace_t tr; vec3_t flatAng; vec3_t fwd, back; @@ -1544,18 +1287,16 @@ qboolean PM_CanBackstab(void) AngleVectors(flatAng, fwd, 0, 0); - back[0] = pm->ps->origin[0] - fwd[0]*BACK_STAB_DISTANCE; - back[1] = pm->ps->origin[1] - fwd[1]*BACK_STAB_DISTANCE; - back[2] = pm->ps->origin[2] - fwd[2]*BACK_STAB_DISTANCE; + back[0] = pm->ps->origin[0] - fwd[0] * BACK_STAB_DISTANCE; + back[1] = pm->ps->origin[1] - fwd[1] * BACK_STAB_DISTANCE; + back[2] = pm->ps->origin[2] - fwd[2] * BACK_STAB_DISTANCE; pm->trace(&tr, pm->ps->origin, trmins, trmaxs, back, pm->ps->clientNum, MASK_PLAYERSOLID); - if (tr.fraction != 1.0 && tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE) - { + if (tr.fraction != 1.0 && tr.entityNum >= 0 && tr.entityNum < ENTITYNUM_NONE) { bgEntity_t *bgEnt = PM_BGEntForNum(tr.entityNum); - if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) - { + if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) { return qtrue; } } @@ -1563,48 +1304,37 @@ qboolean PM_CanBackstab(void) return qfalse; } -saberMoveName_t PM_SaberFlipOverAttackMove(void) -{ +saberMoveName_t PM_SaberFlipOverAttackMove(void) { vec3_t fwdAngles, jumpFwd; -// float zDiff = 0; -// playerState_t *psData; -// bgEntity_t *bgEnt; - - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) lunge move - if ( saber1 - && saber1->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber1->jumpAtkFwdMove != LS_NONE ) - { + // float zDiff = 0; + // playerState_t *psData; + // bgEntity_t *bgEnt; + + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) lunge move + if (saber1 && saber1->jumpAtkFwdMove != LS_INVALID) { + if (saber1->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber1->jumpAtkFwdMove; } } - if ( saber2 - && saber2->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber2->jumpAtkFwdMove != LS_NONE ) - { + if (saber2 && saber2->jumpAtkFwdMove != LS_INVALID) { + if (saber2->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber2->jumpAtkFwdMove; } } - //no overrides, cancelled? - if ( saber1 - && saber1->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + // no overrides, cancelled? + if (saber1 && saber1->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - if ( saber2 - && saber2->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + if (saber2 && saber2->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - //just do it - VectorCopy( pm->ps->viewangles, fwdAngles ); + // just do it + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity );//was 50 + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); // was 50 pm->ps->velocity[2] = 400; /* @@ -1615,7 +1345,7 @@ saberMoveName_t PM_SaberFlipOverAttackMove(void) return LS_A_FLIP_STAB; } - psData = bgEnt->playerState; + psData = bgEnt->playerState; //go higher for enemies higher than you, lower for those lower than you if (psData) @@ -1644,9 +1374,9 @@ saberMoveName_t PM_SaberFlipOverAttackMove(void) } */ - PM_SetForceJumpZStart(pm->ps->origin[2]);//so we don't take damage if we land at same height + PM_SetForceJumpZStart(pm->ps->origin[2]); // so we don't take damage if we land at same height - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); pm->ps->fd.forceJumpSound = 1; pm->cmd.upmove = 0; @@ -1657,62 +1387,47 @@ saberMoveName_t PM_SaberFlipOverAttackMove(void) } else */ - { - return LS_A_FLIP_SLASH; - } + { return LS_A_FLIP_SLASH; } } -int PM_SaberBackflipAttackMove( void ) -{ - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) lunge move - if ( saber1 - && saber1->jumpAtkBackMove != LS_INVALID ) - { - if ( saber1->jumpAtkBackMove != LS_NONE ) - { +int PM_SaberBackflipAttackMove(void) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) lunge move + if (saber1 && saber1->jumpAtkBackMove != LS_INVALID) { + if (saber1->jumpAtkBackMove != LS_NONE) { return (saberMoveName_t)saber1->jumpAtkBackMove; } } - if ( saber2 - && saber2->jumpAtkBackMove != LS_INVALID ) - { - if ( saber2->jumpAtkBackMove != LS_NONE ) - { + if (saber2 && saber2->jumpAtkBackMove != LS_INVALID) { + if (saber2->jumpAtkBackMove != LS_NONE) { return (saberMoveName_t)saber2->jumpAtkBackMove; } } - //no overrides, cancelled? - if ( saber1 - && saber1->jumpAtkBackMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + // no overrides, cancelled? + if (saber1 && saber1->jumpAtkBackMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - if ( saber2 - && saber2->jumpAtkBackMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + if (saber2 && saber2->jumpAtkBackMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - //just do it + // just do it pm->cmd.upmove = 127; pm->ps->velocity[2] = 500; return LS_A_BACKFLIP_ATK; } -int PM_SaberDualJumpAttackMove( void ) -{ - //FIXME: to make this move easier to execute, should be allowed to do it +int PM_SaberDualJumpAttackMove(void) { + // FIXME: to make this move easier to execute, should be allowed to do it // after you've already started your jump... but jump is delayed in // this anim, so how do we undo the jump? - pm->cmd.upmove = 0;//no jump just yet + pm->cmd.upmove = 0; // no jump just yet return LS_JUMPATTACK_DUAL; } #define FLIPHACK_DISTANCE 200 -qboolean PM_SomeoneInFront(trace_t *tr) -{ //Also a very simplified version of the sp counterpart +qboolean PM_SomeoneInFront(trace_t *tr) { // Also a very simplified version of the sp counterpart vec3_t flatAng; vec3_t fwd, back; vec3_t trmins = {-15, -15, -8}; @@ -1723,18 +1438,16 @@ qboolean PM_SomeoneInFront(trace_t *tr) AngleVectors(flatAng, fwd, 0, 0); - back[0] = pm->ps->origin[0] + fwd[0]*FLIPHACK_DISTANCE; - back[1] = pm->ps->origin[1] + fwd[1]*FLIPHACK_DISTANCE; - back[2] = pm->ps->origin[2] + fwd[2]*FLIPHACK_DISTANCE; + back[0] = pm->ps->origin[0] + fwd[0] * FLIPHACK_DISTANCE; + back[1] = pm->ps->origin[1] + fwd[1] * FLIPHACK_DISTANCE; + back[2] = pm->ps->origin[2] + fwd[2] * FLIPHACK_DISTANCE; pm->trace(tr, pm->ps->origin, trmins, trmaxs, back, pm->ps->clientNum, MASK_PLAYERSOLID); - if (tr->fraction != 1.0 && tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_NONE) - { + if (tr->fraction != 1.0 && tr->entityNum >= 0 && tr->entityNum < ENTITYNUM_NONE) { bgEntity_t *bgEnt = PM_BGEntForNum(tr->entityNum); - if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) - { + if (bgEnt && (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) { return qtrue; } } @@ -1742,104 +1455,74 @@ qboolean PM_SomeoneInFront(trace_t *tr) return qfalse; } -saberMoveName_t PM_SaberLungeAttackMove( qboolean noSpecials ) -{ +saberMoveName_t PM_SaberLungeAttackMove(qboolean noSpecials) { vec3_t fwdAngles, jumpFwd; - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) lunge move - if ( saber1 - && saber1->lungeAtkMove != LS_INVALID ) - { - if ( saber1->lungeAtkMove != LS_NONE ) - { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) lunge move + if (saber1 && saber1->lungeAtkMove != LS_INVALID) { + if (saber1->lungeAtkMove != LS_NONE) { return (saberMoveName_t)saber1->lungeAtkMove; } } - if ( saber2 - && saber2->lungeAtkMove != LS_INVALID ) - { - if ( saber2->lungeAtkMove != LS_NONE ) - { + if (saber2 && saber2->lungeAtkMove != LS_INVALID) { + if (saber2->lungeAtkMove != LS_NONE) { return (saberMoveName_t)saber2->lungeAtkMove; } } - //no overrides, cancelled? - if ( saber1 - && saber1->lungeAtkMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + // no overrides, cancelled? + if (saber1 && saber1->lungeAtkMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - if ( saber2 - && saber2->lungeAtkMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + if (saber2 && saber2->lungeAtkMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - //just do it - if (pm->ps->fd.saberAnimLevel == SS_FAST) - { - VectorCopy( pm->ps->viewangles, fwdAngles ); + // just do it + if (pm->ps->fd.saberAnimLevel == SS_FAST) { + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - //do the lunge - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 150, pm->ps->velocity ); - PM_AddEvent( EV_JUMP ); + // do the lunge + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 150, pm->ps->velocity); + PM_AddEvent(EV_JUMP); return LS_A_LUNGE; - } - else if ( !noSpecials && pm->ps->fd.saberAnimLevel == SS_STAFF) - { + } else if (!noSpecials && pm->ps->fd.saberAnimLevel == SS_STAFF) { return LS_SPINATTACK; - } - else if ( !noSpecials ) - { + } else if (!noSpecials) { return LS_SPINATTACK_DUAL; } return LS_A_T2B; } -saberMoveName_t PM_SaberJumpAttackMove2( void ) -{ - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) lunge move - if ( saber1 - && saber1->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber1->jumpAtkFwdMove != LS_NONE ) - { +saberMoveName_t PM_SaberJumpAttackMove2(void) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) lunge move + if (saber1 && saber1->jumpAtkFwdMove != LS_INVALID) { + if (saber1->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber1->jumpAtkFwdMove; } } - if ( saber2 - && saber2->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber2->jumpAtkFwdMove != LS_NONE ) - { + if (saber2 && saber2->jumpAtkFwdMove != LS_INVALID) { + if (saber2->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber2->jumpAtkFwdMove; } } - //no overrides, cancelled? - if ( saber1 - && saber1->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + // no overrides, cancelled? + if (saber1 && saber1->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - if ( saber2 - && saber2->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + if (saber2 && saber2->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - //just do it - if (pm->ps->fd.saberAnimLevel == SS_DUAL) - { + // just do it + if (pm->ps->fd.saberAnimLevel == SS_DUAL) { return PM_SaberDualJumpAttackMove(); - } - else - { - //rwwFIXMEFIXME I don't like randomness for this sort of thing, gives people reason to - //complain combat is unpredictable. Maybe do something more clever to determine - //if we should do a left or right? + } else { + // rwwFIXMEFIXME I don't like randomness for this sort of thing, gives people reason to + // complain combat is unpredictable. Maybe do something more clever to determine + // if we should do a left or right? /* if (PM_irand_timesync(0, 1)) { @@ -1847,63 +1530,49 @@ saberMoveName_t PM_SaberJumpAttackMove2( void ) } else */ - { - return LS_JUMPATTACK_STAFF_RIGHT; - } + { return LS_JUMPATTACK_STAFF_RIGHT; } } -// return LS_A_T2B; + // return LS_A_T2B; } -saberMoveName_t PM_SaberJumpAttackMove( void ) -{ +saberMoveName_t PM_SaberJumpAttackMove(void) { vec3_t fwdAngles, jumpFwd; - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) lunge move - if ( saber1 - && saber1->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber1->jumpAtkFwdMove != LS_NONE ) - { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) lunge move + if (saber1 && saber1->jumpAtkFwdMove != LS_INVALID) { + if (saber1->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber1->jumpAtkFwdMove; } } - if ( saber2 - && saber2->jumpAtkFwdMove != LS_INVALID ) - { - if ( saber2->jumpAtkFwdMove != LS_NONE ) - { + if (saber2 && saber2->jumpAtkFwdMove != LS_INVALID) { + if (saber2->jumpAtkFwdMove != LS_NONE) { return (saberMoveName_t)saber2->jumpAtkFwdMove; } } - //no overrides, cancelled? - if ( saber1 - && saber1->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + // no overrides, cancelled? + if (saber1 && saber1->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - if ( saber2 - && saber2->jumpAtkFwdMove == LS_NONE ) - { - return LS_A_T2B;//LS_NONE; + if (saber2 && saber2->jumpAtkFwdMove == LS_NONE) { + return LS_A_T2B; // LS_NONE; } - //just do it - VectorCopy( pm->ps->viewangles, fwdAngles ); + // just do it + VectorCopy(pm->ps->viewangles, fwdAngles); fwdAngles[PITCH] = fwdAngles[ROLL] = 0; - AngleVectors( fwdAngles, jumpFwd, NULL, NULL ); - VectorScale( jumpFwd, 300, pm->ps->velocity ); + AngleVectors(fwdAngles, jumpFwd, NULL, NULL); + VectorScale(jumpFwd, 300, pm->ps->velocity); pm->ps->velocity[2] = 280; - PM_SetForceJumpZStart(pm->ps->origin[2]);//so we don't take damage if we land at same height + PM_SetForceJumpZStart(pm->ps->origin[2]); // so we don't take damage if we land at same height - PM_AddEvent( EV_JUMP ); + PM_AddEvent(EV_JUMP); pm->ps->fd.forceJumpSound = 1; pm->cmd.upmove = 0; return LS_A_JUMP_T__B_; } -float PM_GroundDistance(void) -{ +float PM_GroundDistance(void) { trace_t tr; vec3_t down; @@ -1918,8 +1587,7 @@ float PM_GroundDistance(void) return VectorLength(down); } -float PM_WalkableGroundDistance(void) -{ +float PM_WalkableGroundDistance(void) { trace_t tr; vec3_t down; @@ -1929,8 +1597,7 @@ float PM_WalkableGroundDistance(void) pm->trace(&tr, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, MASK_SOLID); - if ( tr.plane.normal[2] < MIN_WALK_NORMAL ) - {//can't stand on this plane + if (tr.plane.normal[2] < MIN_WALK_NORMAL) { // can't stand on this plane return 4096; } @@ -1939,43 +1606,34 @@ float PM_WalkableGroundDistance(void) return VectorLength(down); } -qboolean BG_SaberInTransitionAny( int move ); -static qboolean PM_CanDoDualDoubleAttacks(void) -{ - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber = BG_MySaber( pm->ps->clientNum, 0 ); - if ( saber - && (saber->saberFlags&SFL_NO_MIRROR_ATTACKS) ) - { +qboolean BG_SaberInTransitionAny(int move); +static qboolean PM_CanDoDualDoubleAttacks(void) { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber = BG_MySaber(pm->ps->clientNum, 0); + if (saber && (saber->saberFlags & SFL_NO_MIRROR_ATTACKS)) { return qfalse; } - saber = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber - && (saber->saberFlags&SFL_NO_MIRROR_ATTACKS) ) - { + saber = BG_MySaber(pm->ps->clientNum, 1); + if (saber && (saber->saberFlags & SFL_NO_MIRROR_ATTACKS)) { return qfalse; } } - if (BG_SaberInSpecialAttack(pm->ps->torsoAnim) || - BG_SaberInSpecialAttack(pm->ps->legsAnim)) - { + if (BG_SaberInSpecialAttack(pm->ps->torsoAnim) || BG_SaberInSpecialAttack(pm->ps->legsAnim)) { return qfalse; } return qtrue; } -static qboolean PM_CheckEnemyPresence( int dir, float radius ) -{ //anyone in this dir? +static qboolean PM_CheckEnemyPresence(int dir, float radius) { // anyone in this dir? vec3_t angles; - vec3_t checkDir = { 0.0f }; + vec3_t checkDir = {0.0f}; vec3_t tTo; vec3_t tMins, tMaxs; trace_t tr; const float tSize = 12.0f; - //sp uses a bbox ent list check, but.. that's not so easy/fast to - //do in predicted code. So I'll just do a single box trace in the proper direction, - //and take whatever is first hit. + // sp uses a bbox ent list check, but.. that's not so easy/fast to + // do in predicted code. So I'll just do a single box trace in the proper direction, + // and take whatever is first hit. VectorSet(tMins, -tSize, -tSize, -tSize); VectorSet(tMaxs, tSize, tSize, tSize); @@ -1983,50 +1641,48 @@ static qboolean PM_CheckEnemyPresence( int dir, float radius ) VectorCopy(pm->ps->viewangles, angles); angles[PITCH] = 0.0f; - switch( dir ) - { + switch (dir) { case DIR_RIGHT: - AngleVectors( angles, NULL, checkDir, NULL ); + AngleVectors(angles, NULL, checkDir, NULL); break; case DIR_LEFT: - AngleVectors( angles, NULL, checkDir, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(angles, NULL, checkDir, NULL); + VectorScale(checkDir, -1, checkDir); break; case DIR_FRONT: - AngleVectors( angles, checkDir, NULL, NULL ); + AngleVectors(angles, checkDir, NULL, NULL); break; case DIR_BACK: - AngleVectors( angles, checkDir, NULL, NULL ); - VectorScale( checkDir, -1, checkDir ); + AngleVectors(angles, checkDir, NULL, NULL); + VectorScale(checkDir, -1, checkDir); break; } VectorMA(pm->ps->origin, radius, checkDir, tTo); pm->trace(&tr, pm->ps->origin, tMins, tMaxs, tTo, pm->ps->clientNum, MASK_PLAYERSOLID); - if (tr.fraction != 1.0f && tr.entityNum < ENTITYNUM_WORLD) - { //let's see who we hit + if (tr.fraction != 1.0f && tr.entityNum < ENTITYNUM_WORLD) { // let's see who we hit bgEntity_t *bgEnt = PM_BGEntForNum(tr.entityNum); if (bgEnt && - (bgEnt->s.eType == ET_PLAYER || bgEnt->s.eType == ET_NPC)) - { //this guy can be considered an "enemy"... if he is on the same team, oh well. can't bg-check that (without a whole lot of hassle). + (bgEnt->s.eType == ET_PLAYER || + bgEnt->s.eType == + ET_NPC)) { // this guy can be considered an "enemy"... if he is on the same team, oh well. can't bg-check that (without a whole lot of hassle). return qtrue; } } - //no one in the trace + // no one in the trace return qfalse; } -#define SABER_ALT_ATTACK_POWER 50//75? -#define SABER_ALT_ATTACK_POWER_LR 10//30? -#define SABER_ALT_ATTACK_POWER_FB 25//30/50? +#define SABER_ALT_ATTACK_POWER 50 // 75? +#define SABER_ALT_ATTACK_POWER_LR 10 // 30? +#define SABER_ALT_ATTACK_POWER_FB 25 // 30/50? -extern qboolean PM_SaberInReturn( int move ); //bg_panimate.c -saberMoveName_t PM_CheckPullAttack( void ) -{ -#if 0 //disabling these for MP, they aren't useful +extern qboolean PM_SaberInReturn(int move); // bg_panimate.c +saberMoveName_t PM_CheckPullAttack(void) { +#if 0 // disabling these for MP, they aren't useful if (!(pm->cmd.buttons & BUTTON_ATTACK)) { return LS_NONE; @@ -2135,391 +1791,244 @@ saberMoveName_t PM_CheckPullAttack( void ) return LS_NONE; } -qboolean PM_InSecondaryStyle( void ) -{ - if ( pm->ps->fd.saberAnimLevelBase == SS_STAFF - || pm->ps->fd.saberAnimLevelBase == SS_DUAL ) - { - if ( pm->ps->fd.saberAnimLevel != pm->ps->fd.saberAnimLevelBase ) - { +qboolean PM_InSecondaryStyle(void) { + if (pm->ps->fd.saberAnimLevelBase == SS_STAFF || pm->ps->fd.saberAnimLevelBase == SS_DUAL) { + if (pm->ps->fd.saberAnimLevel != pm->ps->fd.saberAnimLevelBase) { return qtrue; } } return qfalse; } -saberMoveName_t PM_SaberAttackForMovement(saberMoveName_t curmove) -{ +saberMoveName_t PM_SaberAttackForMovement(saberMoveName_t curmove) { saberMoveName_t newmove = LS_NONE; qboolean noSpecials = PM_InSecondaryStyle(); qboolean allowCartwheels = qtrue; saberMoveName_t overrideJumpRightAttackMove = LS_INVALID; saberMoveName_t overrideJumpLeftAttackMove = LS_INVALID; - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); - if ( saber1 - && saber1->jumpAtkRightMove != LS_INVALID ) - { - if ( saber1->jumpAtkRightMove != LS_NONE ) - {//actually overriding + if (saber1 && saber1->jumpAtkRightMove != LS_INVALID) { + if (saber1->jumpAtkRightMove != LS_NONE) { // actually overriding overrideJumpRightAttackMove = (saberMoveName_t)saber1->jumpAtkRightMove; - } - else if ( saber2 - && saber2->jumpAtkRightMove > LS_NONE ) - {//would be cancelling it, but check the second saber, too + } else if (saber2 && saber2->jumpAtkRightMove > LS_NONE) { // would be cancelling it, but check the second saber, too overrideJumpRightAttackMove = (saberMoveName_t)saber2->jumpAtkRightMove; - } - else - {//nope, just cancel it + } else { // nope, just cancel it overrideJumpRightAttackMove = LS_NONE; } - } - else if ( saber2 - && saber2->jumpAtkRightMove != LS_INVALID ) - {//first saber not overridden, check second + } else if (saber2 && saber2->jumpAtkRightMove != LS_INVALID) { // first saber not overridden, check second overrideJumpRightAttackMove = (saberMoveName_t)saber2->jumpAtkRightMove; } - if ( saber1 - && saber1->jumpAtkLeftMove != LS_INVALID ) - { - if ( saber1->jumpAtkLeftMove != LS_NONE ) - {//actually overriding + if (saber1 && saber1->jumpAtkLeftMove != LS_INVALID) { + if (saber1->jumpAtkLeftMove != LS_NONE) { // actually overriding overrideJumpLeftAttackMove = (saberMoveName_t)saber1->jumpAtkLeftMove; - } - else if ( saber2 - && saber2->jumpAtkLeftMove > LS_NONE ) - {//would be cancelling it, but check the second saber, too + } else if (saber2 && saber2->jumpAtkLeftMove > LS_NONE) { // would be cancelling it, but check the second saber, too overrideJumpLeftAttackMove = (saberMoveName_t)saber2->jumpAtkLeftMove; - } - else - {//nope, just cancel it + } else { // nope, just cancel it overrideJumpLeftAttackMove = LS_NONE; } - } - else if ( saber2 - && saber2->jumpAtkLeftMove != LS_INVALID ) - {//first saber not overridden, check second + } else if (saber2 && saber2->jumpAtkLeftMove != LS_INVALID) { // first saber not overridden, check second overrideJumpLeftAttackMove = (saberMoveName_t)saber1->jumpAtkLeftMove; } - if ( saber1 - && (saber1->saberFlags&SFL_NO_CARTWHEELS) ) - { + if (saber1 && (saber1->saberFlags & SFL_NO_CARTWHEELS)) { allowCartwheels = qfalse; } - if ( saber2 - && (saber2->saberFlags&SFL_NO_CARTWHEELS) ) - { + if (saber2 && (saber2->saberFlags & SFL_NO_CARTWHEELS)) { allowCartwheels = qfalse; } } - if ( pm->cmd.rightmove > 0 ) - {//moving right - if ( !noSpecials - && overrideJumpRightAttackMove != LS_NONE - && pm->ps->velocity[2] > 20.0f //pm->ps->groundEntityNum != ENTITYNUM_NONE//on ground - && (pm->cmd.buttons&BUTTON_ATTACK)//hitting attack - && PM_GroundDistance() < 70.0f //not too high above ground - && ( pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMP_HELD) )//focus-holding player - && BG_EnoughForcePowerForMove( SABER_ALT_ATTACK_POWER_LR ) )//have enough power - {//cartwheel right + if (pm->cmd.rightmove > 0) { // moving right + if (!noSpecials && overrideJumpRightAttackMove != LS_NONE && pm->ps->velocity[2] > 20.0f // pm->ps->groundEntityNum != ENTITYNUM_NONE//on ground + && (pm->cmd.buttons & BUTTON_ATTACK) // hitting attack + && PM_GroundDistance() < 70.0f // not too high above ground + && (pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMP_HELD)) // focus-holding player + && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_LR)) // have enough power + { // cartwheel right BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_LR); - if ( overrideJumpRightAttackMove != LS_INVALID ) - {//overridden with another move + if (overrideJumpRightAttackMove != LS_INVALID) { // overridden with another move return overrideJumpRightAttackMove; - } - else - { + } else { vec3_t right, fwdAngles; VectorSet(fwdAngles, 0.0f, pm->ps->viewangles[YAW], 0.0f); - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0.0f; - VectorMA( pm->ps->velocity, 190.0f, right, pm->ps->velocity ); - if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { + VectorMA(pm->ps->velocity, 190.0f, right, pm->ps->velocity); + if (pm->ps->fd.saberAnimLevel == SS_STAFF) { newmove = LS_BUTTERFLY_RIGHT; pm->ps->velocity[2] = 350.0f; - } - else if ( allowCartwheels ) - { - //PM_SetJumped( JUMP_VELOCITY, qtrue ); - PM_AddEvent( EV_JUMP ); + } else if (allowCartwheels) { + // PM_SetJumped( JUMP_VELOCITY, qtrue ); + PM_AddEvent(EV_JUMP); pm->ps->velocity[2] = 300.0f; - //if ( !Q_irand( 0, 1 ) ) - //if (PM_GroundDistance() >= 25.0f) - if (1) - { + // if ( !Q_irand( 0, 1 ) ) + // if (PM_GroundDistance() >= 25.0f) + if (1) { newmove = LS_JUMPATTACK_ARIAL_RIGHT; - } - else - { + } else { newmove = LS_JUMPATTACK_CART_RIGHT; } } } - } - else if ( pm->cmd.forwardmove > 0 ) - {//forward right = TL2BR slash + } else if (pm->cmd.forwardmove > 0) { // forward right = TL2BR slash newmove = LS_A_TL2BR; - } - else if ( pm->cmd.forwardmove < 0 ) - {//backward right = BL2TR uppercut + } else if (pm->cmd.forwardmove < 0) { // backward right = BL2TR uppercut newmove = LS_A_BL2TR; - } - else - {//just right is a left slice + } else { // just right is a left slice newmove = LS_A_L2R; } - } - else if ( pm->cmd.rightmove < 0 ) - {//moving left - if ( !noSpecials - && overrideJumpLeftAttackMove != LS_NONE - && pm->ps->velocity[2] > 20.0f //pm->ps->groundEntityNum != ENTITYNUM_NONE//on ground - && (pm->cmd.buttons&BUTTON_ATTACK)//hitting attack - && PM_GroundDistance() < 70.0f //not too high above ground - && ( pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMP_HELD) )//focus-holding player - && BG_EnoughForcePowerForMove( SABER_ALT_ATTACK_POWER_LR ) )//have enough power - {//cartwheel left + } else if (pm->cmd.rightmove < 0) { // moving left + if (!noSpecials && overrideJumpLeftAttackMove != LS_NONE && pm->ps->velocity[2] > 20.0f // pm->ps->groundEntityNum != ENTITYNUM_NONE//on ground + && (pm->cmd.buttons & BUTTON_ATTACK) // hitting attack + && PM_GroundDistance() < 70.0f // not too high above ground + && (pm->cmd.upmove > 0 || (pm->ps->pm_flags & PMF_JUMP_HELD)) // focus-holding player + && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_LR)) // have enough power + { // cartwheel left BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_LR); - if ( overrideJumpLeftAttackMove != LS_INVALID ) - {//overridden with another move + if (overrideJumpLeftAttackMove != LS_INVALID) { // overridden with another move return overrideJumpLeftAttackMove; - } - else - { + } else { vec3_t right, fwdAngles; VectorSet(fwdAngles, 0.0f, pm->ps->viewangles[YAW], 0.0f); - AngleVectors( fwdAngles, NULL, right, NULL ); + AngleVectors(fwdAngles, NULL, right, NULL); pm->ps->velocity[0] = pm->ps->velocity[1] = 0.0f; - VectorMA( pm->ps->velocity, -190.0f, right, pm->ps->velocity ); - if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { + VectorMA(pm->ps->velocity, -190.0f, right, pm->ps->velocity); + if (pm->ps->fd.saberAnimLevel == SS_STAFF) { newmove = LS_BUTTERFLY_LEFT; pm->ps->velocity[2] = 250.0f; - } - else if ( allowCartwheels ) - { - //PM_SetJumped( JUMP_VELOCITY, qtrue ); - PM_AddEvent( EV_JUMP ); + } else if (allowCartwheels) { + // PM_SetJumped( JUMP_VELOCITY, qtrue ); + PM_AddEvent(EV_JUMP); pm->ps->velocity[2] = 350.0f; - //if ( !Q_irand( 0, 1 ) ) - //if (PM_GroundDistance() >= 25.0f) - if (1) - { + // if ( !Q_irand( 0, 1 ) ) + // if (PM_GroundDistance() >= 25.0f) + if (1) { newmove = LS_JUMPATTACK_ARIAL_LEFT; - } - else - { + } else { newmove = LS_JUMPATTACK_CART_LEFT; } } } - } - else if ( pm->cmd.forwardmove > 0 ) - {//forward left = TR2BL slash + } else if (pm->cmd.forwardmove > 0) { // forward left = TR2BL slash newmove = LS_A_TR2BL; - } - else if ( pm->cmd.forwardmove < 0 ) - {//backward left = BR2TL uppercut + } else if (pm->cmd.forwardmove < 0) { // backward left = BR2TL uppercut newmove = LS_A_BR2TL; - } - else - {//just left is a right slice + } else { // just left is a right slice newmove = LS_A_R2L; } - } - else - {//not moving left or right - if ( pm->cmd.forwardmove > 0 ) - {//forward= T2B slash - if (!noSpecials&& - (pm->ps->fd.saberAnimLevel == SS_DUAL || pm->ps->fd.saberAnimLevel == SS_STAFF) && + } else { // not moving left or right + if (pm->cmd.forwardmove > 0) { // forward= T2B slash + if (!noSpecials && (pm->ps->fd.saberAnimLevel == SS_DUAL || pm->ps->fd.saberAnimLevel == SS_STAFF) && pm->ps->fd.forceRageRecoveryTime < pm->cmd.serverTime && - //pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && - (pm->ps->groundEntityNum != ENTITYNUM_NONE || PM_GroundDistance() <= 40) && - pm->ps->velocity[2] >= 0 && - (pm->cmd.upmove > 0 || pm->ps->pm_flags & PMF_JUMP_HELD) && - !BG_SaberInTransitionAny(pm->ps->saberMove) && - !BG_SaberInAttack(pm->ps->saberMove) && - pm->ps->weaponTime <= 0 && - pm->ps->forceHandExtend == HANDEXTEND_NONE && - (pm->cmd.buttons & BUTTON_ATTACK)&& - BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB) ) - { //DUAL/STAFF JUMP ATTACK + // pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && + (pm->ps->groundEntityNum != ENTITYNUM_NONE || PM_GroundDistance() <= 40) && pm->ps->velocity[2] >= 0 && + (pm->cmd.upmove > 0 || pm->ps->pm_flags & PMF_JUMP_HELD) && !BG_SaberInTransitionAny(pm->ps->saberMove) && + !BG_SaberInAttack(pm->ps->saberMove) && pm->ps->weaponTime <= 0 && pm->ps->forceHandExtend == HANDEXTEND_NONE && + (pm->cmd.buttons & BUTTON_ATTACK) && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) { // DUAL/STAFF JUMP ATTACK newmove = PM_SaberJumpAttackMove2(); - if ( newmove != LS_A_T2B - && newmove != LS_NONE ) - { + if (newmove != LS_A_T2B && newmove != LS_NONE) { BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); } - } - else if (!noSpecials&& - pm->ps->fd.saberAnimLevel == SS_MEDIUM && - pm->ps->velocity[2] > 100 && - PM_GroundDistance() < 32 && - !BG_InSpecialJump(pm->ps->legsAnim) && - !BG_SaberInSpecialAttack(pm->ps->torsoAnim)&& - BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) - { //FLIP AND DOWNWARD ATTACK - //trace_t tr; - - //if (PM_SomeoneInFront(&tr)) + } else if (!noSpecials && pm->ps->fd.saberAnimLevel == SS_MEDIUM && pm->ps->velocity[2] > 100 && PM_GroundDistance() < 32 && + !BG_InSpecialJump(pm->ps->legsAnim) && !BG_SaberInSpecialAttack(pm->ps->torsoAnim) && + BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) { // FLIP AND DOWNWARD ATTACK + // trace_t tr; + + // if (PM_SomeoneInFront(&tr)) { newmove = PM_SaberFlipOverAttackMove(); - if ( newmove != LS_A_T2B - && newmove != LS_NONE ) - { + if (newmove != LS_A_T2B && newmove != LS_NONE) { BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); } } - } - else if (!noSpecials&& - pm->ps->fd.saberAnimLevel == SS_STRONG && - pm->ps->velocity[2] > 100 && - PM_GroundDistance() < 32 && - !BG_InSpecialJump(pm->ps->legsAnim) && - !BG_SaberInSpecialAttack(pm->ps->torsoAnim)&& - BG_EnoughForcePowerForMove( SABER_ALT_ATTACK_POWER_FB )) - { //DFA - //trace_t tr; - - //if (PM_SomeoneInFront(&tr)) + } else if (!noSpecials && pm->ps->fd.saberAnimLevel == SS_STRONG && pm->ps->velocity[2] > 100 && PM_GroundDistance() < 32 && + !BG_InSpecialJump(pm->ps->legsAnim) && !BG_SaberInSpecialAttack(pm->ps->torsoAnim) && + BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) { // DFA + // trace_t tr; + + // if (PM_SomeoneInFront(&tr)) { newmove = PM_SaberJumpAttackMove(); - if ( newmove != LS_A_T2B - && newmove != LS_NONE ) - { + if (newmove != LS_A_T2B && newmove != LS_NONE) { BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); } } - } - else if ((pm->ps->fd.saberAnimLevel == SS_FAST || pm->ps->fd.saberAnimLevel == SS_DUAL || pm->ps->fd.saberAnimLevel == SS_STAFF) && - pm->ps->groundEntityNum != ENTITYNUM_NONE && - (pm->ps->pm_flags & PMF_DUCKED) && - pm->ps->weaponTime <= 0 && - !BG_SaberInSpecialAttack(pm->ps->torsoAnim)&& - BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) - { //LUNGE (weak) - newmove = PM_SaberLungeAttackMove( noSpecials ); - if ( newmove != LS_A_T2B - && newmove != LS_NONE ) - { + } else if ((pm->ps->fd.saberAnimLevel == SS_FAST || pm->ps->fd.saberAnimLevel == SS_DUAL || pm->ps->fd.saberAnimLevel == SS_STAFF) && + pm->ps->groundEntityNum != ENTITYNUM_NONE && (pm->ps->pm_flags & PMF_DUCKED) && pm->ps->weaponTime <= 0 && + !BG_SaberInSpecialAttack(pm->ps->torsoAnim) && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) { // LUNGE (weak) + newmove = PM_SaberLungeAttackMove(noSpecials); + if (newmove != LS_A_T2B && newmove != LS_NONE) { BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); } - } - else if ( !noSpecials ) - { + } else if (!noSpecials) { saberMoveName_t stabDownMove = PM_CheckStabDown(); - if (stabDownMove != LS_NONE - && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB) ) - { + if (stabDownMove != LS_NONE && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB)) { newmove = stabDownMove; BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); - } - else - { + } else { newmove = LS_A_T2B; } } - } - else if ( pm->cmd.forwardmove < 0 ) - {//backward= T2B slash//B2T uppercut? - if (!noSpecials&& - pm->ps->fd.saberAnimLevel == SS_STAFF && - pm->ps->fd.forceRageRecoveryTime < pm->cmd.serverTime && - pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && - (pm->ps->groundEntityNum != ENTITYNUM_NONE || PM_GroundDistance() <= 40) && - pm->ps->velocity[2] >= 0 && - (pm->cmd.upmove > 0 || pm->ps->pm_flags & PMF_JUMP_HELD) && - !BG_SaberInTransitionAny(pm->ps->saberMove) && - !BG_SaberInAttack(pm->ps->saberMove) && - pm->ps->weaponTime <= 0 && - pm->ps->forceHandExtend == HANDEXTEND_NONE && - (pm->cmd.buttons & BUTTON_ATTACK)) - { //BACKFLIP ATTACK + } else if (pm->cmd.forwardmove < 0) { // backward= T2B slash//B2T uppercut? + if (!noSpecials && pm->ps->fd.saberAnimLevel == SS_STAFF && pm->ps->fd.forceRageRecoveryTime < pm->cmd.serverTime && + pm->ps->fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1 && (pm->ps->groundEntityNum != ENTITYNUM_NONE || PM_GroundDistance() <= 40) && + pm->ps->velocity[2] >= 0 && (pm->cmd.upmove > 0 || pm->ps->pm_flags & PMF_JUMP_HELD) && !BG_SaberInTransitionAny(pm->ps->saberMove) && + !BG_SaberInAttack(pm->ps->saberMove) && pm->ps->weaponTime <= 0 && pm->ps->forceHandExtend == HANDEXTEND_NONE && + (pm->cmd.buttons & BUTTON_ATTACK)) { // BACKFLIP ATTACK newmove = PM_SaberBackflipAttackMove(); - } - else if (PM_CanBackstab() && !BG_SaberInSpecialAttack(pm->ps->torsoAnim)) - { //BACKSTAB (attack varies by level) - if (pm->ps->fd.saberAnimLevel >= FORCE_LEVEL_2 && pm->ps->fd.saberAnimLevel != SS_STAFF) - {//medium and higher attacks - if ( (pm->ps->pm_flags&PMF_DUCKED) || pm->cmd.upmove < 0 ) - { + } else if (PM_CanBackstab() && !BG_SaberInSpecialAttack(pm->ps->torsoAnim)) { // BACKSTAB (attack varies by level) + if (pm->ps->fd.saberAnimLevel >= FORCE_LEVEL_2 && pm->ps->fd.saberAnimLevel != SS_STAFF) { // medium and higher attacks + if ((pm->ps->pm_flags & PMF_DUCKED) || pm->cmd.upmove < 0) { newmove = LS_A_BACK_CR; - } - else - { + } else { newmove = LS_A_BACK; } - } - else - { //weak attack + } else { // weak attack newmove = LS_A_BACKSTAB; } - } - else - { + } else { newmove = LS_A_T2B; } - } - else if ( PM_SaberInBounce( curmove ) ) - {//bounces should go to their default attack if you don't specify a direction but are attacking + } else if (PM_SaberInBounce(curmove)) { // bounces should go to their default attack if you don't specify a direction but are attacking newmove = saberMoveData[curmove].chain_attack; - if ( PM_SaberKataDone(curmove, newmove) ) - { + if (PM_SaberKataDone(curmove, newmove)) { newmove = saberMoveData[curmove].chain_idle; - } - else - { + } else { newmove = saberMoveData[curmove].chain_attack; } - } - else if ( curmove == LS_READY ) - {//Not moving at all, shouldn't have gotten here...? - //for now, just pick a random attack - //newmove = Q_irand( LS_A_TL2BR, LS_A_T2B ); - //rww - If we don't seed with a "common" value, the client and server will get mismatched - //prediction values. Under laggy conditions this will cause the appearance of rapid swing - //sequence changes. + } else if (curmove == LS_READY) { // Not moving at all, shouldn't have gotten here...? + // for now, just pick a random attack + // newmove = Q_irand( LS_A_TL2BR, LS_A_T2B ); + // rww - If we don't seed with a "common" value, the client and server will get mismatched + // prediction values. Under laggy conditions this will cause the appearance of rapid swing + // sequence changes. - newmove = LS_A_T2B; //decided we don't like random attacks when idle, use an overhead instead. + newmove = LS_A_T2B; // decided we don't like random attacks when idle, use an overhead instead. } } - if (pm->ps->fd.saberAnimLevel == SS_DUAL) - { - if ( ( newmove == LS_A_R2L || newmove == LS_S_R2L - || newmove == LS_A_L2R || newmove == LS_S_L2R ) - && PM_CanDoDualDoubleAttacks() - && PM_CheckEnemyPresence( DIR_RIGHT, 100.0f ) - && PM_CheckEnemyPresence( DIR_LEFT, 100.0f ) ) - {//enemy both on left and right + if (pm->ps->fd.saberAnimLevel == SS_DUAL) { + if ((newmove == LS_A_R2L || newmove == LS_S_R2L || newmove == LS_A_L2R || newmove == LS_S_L2R) && PM_CanDoDualDoubleAttacks() && + PM_CheckEnemyPresence(DIR_RIGHT, 100.0f) && PM_CheckEnemyPresence(DIR_LEFT, 100.0f)) { // enemy both on left and right newmove = LS_DUAL_LR; - //probably already moved, but... + // probably already moved, but... pm->cmd.rightmove = 0; - } - else if ( (newmove == LS_A_T2B || newmove == LS_S_T2B - || newmove == LS_A_BACK || newmove == LS_A_BACK_CR ) - && PM_CanDoDualDoubleAttacks() - && PM_CheckEnemyPresence( DIR_FRONT, 100.0f ) - && PM_CheckEnemyPresence( DIR_BACK, 100.0f ) ) - {//enemy both in front and back + } else if ((newmove == LS_A_T2B || newmove == LS_S_T2B || newmove == LS_A_BACK || newmove == LS_A_BACK_CR) && PM_CanDoDualDoubleAttacks() && + PM_CheckEnemyPresence(DIR_FRONT, 100.0f) && PM_CheckEnemyPresence(DIR_BACK, 100.0f)) { // enemy both in front and back newmove = LS_DUAL_FB; - //probably already moved, but... + // probably already moved, but... pm->cmd.forwardmove = 0; } } @@ -2527,27 +2036,19 @@ saberMoveName_t PM_SaberAttackForMovement(saberMoveName_t curmove) return newmove; } -int PM_KickMoveForConditions(void) -{ +int PM_KickMoveForConditions(void) { int kickMove = -1; - //FIXME: only if FP_SABER_OFFENSE >= 3 - if ( pm->cmd.rightmove ) - {//kick to side - if ( pm->cmd.rightmove > 0 ) - {//kick right + // FIXME: only if FP_SABER_OFFENSE >= 3 + if (pm->cmd.rightmove) { // kick to side + if (pm->cmd.rightmove > 0) { // kick right kickMove = LS_KICK_R; - } - else - {//kick left + } else { // kick left kickMove = LS_KICK_L; } pm->cmd.rightmove = 0; - } - else if ( pm->cmd.forwardmove ) - {//kick front/back - if ( pm->cmd.forwardmove > 0 ) - {//kick fwd + } else if (pm->cmd.forwardmove) { // kick front/back + if (pm->cmd.forwardmove > 0) { // kick fwd /* if (pm->ps->groundEntityNum != ENTITYNUM_NONE && PM_CheckEnemyPresence( DIR_FRONT, 64.0f )) @@ -2556,40 +2057,27 @@ int PM_KickMoveForConditions(void) } else */ - { - kickMove = LS_KICK_F; - } - } - else - {//kick back + { kickMove = LS_KICK_F; } + } else { // kick back kickMove = LS_KICK_B; } pm->cmd.forwardmove = 0; - } - else - { - //if (pm->cmd.buttons & BUTTON_ATTACK) - //if (pm->ps->pm_flags & PMF_JUMP_HELD) - if (0) - { //ok, let's try some fancy kicks - //qboolean is actually of type int anyway, but just for safeness. - int front = (int)PM_CheckEnemyPresence( DIR_FRONT, 100.0f ); - int back = (int)PM_CheckEnemyPresence( DIR_BACK, 100.0f ); - int right = (int)PM_CheckEnemyPresence( DIR_RIGHT, 100.0f ); - int left = (int)PM_CheckEnemyPresence( DIR_LEFT, 100.0f ); - int numEnemy = front+back+right+left; - - if (numEnemy >= 3 || - ((!right || !left) && numEnemy >= 2)) - { //> 2 enemies near, or, >= 2 enemies near and they are not to the right and left. - kickMove = LS_KICK_S; - } - else if (right && left) - { //enemies on both sides + } else { + // if (pm->cmd.buttons & BUTTON_ATTACK) + // if (pm->ps->pm_flags & PMF_JUMP_HELD) + if (0) { // ok, let's try some fancy kicks + // qboolean is actually of type int anyway, but just for safeness. + int front = (int)PM_CheckEnemyPresence(DIR_FRONT, 100.0f); + int back = (int)PM_CheckEnemyPresence(DIR_BACK, 100.0f); + int right = (int)PM_CheckEnemyPresence(DIR_RIGHT, 100.0f); + int left = (int)PM_CheckEnemyPresence(DIR_LEFT, 100.0f); + int numEnemy = front + back + right + left; + + if (numEnemy >= 3 || ((!right || !left) && numEnemy >= 2)) { //> 2 enemies near, or, >= 2 enemies near and they are not to the right and left. + kickMove = LS_KICK_S; + } else if (right && left) { // enemies on both sides kickMove = LS_KICK_RL; - } - else - { //oh well, just do a forward kick + } else { // oh well, just do a forward kick kickMove = LS_KICK_F; } @@ -2600,56 +2088,43 @@ int PM_KickMoveForConditions(void) return kickMove; } -qboolean BG_InSlopeAnim( int anim ); -qboolean PM_RunningAnim( int anim ); +qboolean BG_InSlopeAnim(int anim); +qboolean PM_RunningAnim(int anim); -qboolean PM_SaberMoveOkayForKata( void ) -{ - if ( pm->ps->saberMove == LS_READY - || PM_SaberInStart( pm->ps->saberMove ) ) - { +qboolean PM_SaberMoveOkayForKata(void) { + if (pm->ps->saberMove == LS_READY || PM_SaberInStart(pm->ps->saberMove)) { return qtrue; - } - else - { + } else { return qfalse; } } -qboolean PM_CanDoKata( void ) -{ - if ( PM_InSecondaryStyle() ) - { +qboolean PM_CanDoKata(void) { + if (PM_InSecondaryStyle()) { return qfalse; } - if ( !pm->ps->saberInFlight//not throwing saber - && PM_SaberMoveOkayForKata() - && !BG_SaberInKata(pm->ps->saberMove) - && !BG_InKataAnim(pm->ps->legsAnim) - && !BG_InKataAnim(pm->ps->torsoAnim) + if (!pm->ps->saberInFlight // not throwing saber + && PM_SaberMoveOkayForKata() && !BG_SaberInKata(pm->ps->saberMove) && !BG_InKataAnim(pm->ps->legsAnim) && + !BG_InKataAnim(pm->ps->torsoAnim) /* && pm->ps->saberAnimLevel >= SS_FAST//fast, med or strong style && pm->ps->saberAnimLevel <= SS_STRONG//FIXME: Tavion, too? */ - && pm->ps->groundEntityNum != ENTITYNUM_NONE//not in the air - && (pm->cmd.buttons&BUTTON_ATTACK)//pressing attack - && (pm->cmd.buttons&BUTTON_ALT_ATTACK)//pressing alt attack - && !pm->cmd.forwardmove//not moving f/b - && !pm->cmd.rightmove//not moving r/l - && pm->cmd.upmove <= 0//not jumping...? - && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER) )// have enough power - {//FIXME: check rage, etc... - saberInfo_t *saber = BG_MySaber( pm->ps->clientNum, 0 ); - if ( saber - && saber->kataMove == LS_NONE ) - {//kata move has been overridden in a way that should stop you from doing it at all + && pm->ps->groundEntityNum != ENTITYNUM_NONE // not in the air + && (pm->cmd.buttons & BUTTON_ATTACK) // pressing attack + && (pm->cmd.buttons & BUTTON_ALT_ATTACK) // pressing alt attack + && !pm->cmd.forwardmove // not moving f/b + && !pm->cmd.rightmove // not moving r/l + && pm->cmd.upmove <= 0 // not jumping...? + && BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER)) // have enough power + { // FIXME: check rage, etc... + saberInfo_t *saber = BG_MySaber(pm->ps->clientNum, 0); + if (saber && saber->kataMove == LS_NONE) { // kata move has been overridden in a way that should stop you from doing it at all return qfalse; } - saber = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber - && saber->kataMove == LS_NONE ) - {//kata move has been overridden in a way that should stop you from doing it at all + saber = BG_MySaber(pm->ps->clientNum, 1); + if (saber && saber->kataMove == LS_NONE) { // kata move has been overridden in a way that should stop you from doing it at all return qfalse; } return qtrue; @@ -2657,72 +2132,49 @@ qboolean PM_CanDoKata( void ) return qfalse; } -qboolean PM_CheckAltKickAttack( void ) -{ - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber = BG_MySaber( pm->ps->clientNum, 0 ); - if ( saber - && (saber->saberFlags&SFL_NO_KICKS) ) - { +qboolean PM_CheckAltKickAttack(void) { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber = BG_MySaber(pm->ps->clientNum, 0); + if (saber && (saber->saberFlags & SFL_NO_KICKS)) { return qfalse; } - saber = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber - && (saber->saberFlags&SFL_NO_KICKS) ) - { + saber = BG_MySaber(pm->ps->clientNum, 1); + if (saber && (saber->saberFlags & SFL_NO_KICKS)) { return qfalse; } } - if ( (pm->cmd.buttons&BUTTON_ALT_ATTACK) + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK) //&& (!(pm->ps->pm_flags&PMF_ALT_ATTACK_HELD)||PM_SaberInReturn(pm->ps->saberMove)) - && (!BG_FlippingAnim(pm->ps->legsAnim)||pm->ps->legsTimer<=250) - && (pm->ps->fd.saberAnimLevel == SS_STAFF/*||!pm->ps->saber[0].throwable*/) && !pm->ps->saberHolstered ) - { + && (!BG_FlippingAnim(pm->ps->legsAnim) || pm->ps->legsTimer <= 250) && (pm->ps->fd.saberAnimLevel == SS_STAFF /*||!pm->ps->saber[0].throwable*/) && + !pm->ps->saberHolstered) { return qtrue; } return qfalse; } -int bg_parryDebounce[NUM_FORCE_POWER_LEVELS] = -{ - 500,//if don't even have defense, can't use defense! - 300, - 150, - 50 -}; +int bg_parryDebounce[NUM_FORCE_POWER_LEVELS] = {500, // if don't even have defense, can't use defense! + 300, 150, 50}; -qboolean PM_SaberPowerCheck(void) -{ - if (pm->ps->saberInFlight) - { //so we don't keep doing stupid force out thing while guiding saber. - if (pm->ps->fd.forcePower > forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW]) - { +qboolean PM_SaberPowerCheck(void) { + if (pm->ps->saberInFlight) { // so we don't keep doing stupid force out thing while guiding saber. + if (pm->ps->fd.forcePower > forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW]) { return qtrue; } - } - else - { + } else { return BG_EnoughForcePowerForMove(forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW]); } return qfalse; } -qboolean PM_CanDoRollStab( void ) -{ - if ( pm->ps->weapon == WP_SABER ) - { - saberInfo_t *saber = BG_MySaber( pm->ps->clientNum, 0 ); - if ( saber - && (saber->saberFlags&SFL_NO_ROLL_STAB) ) - { +qboolean PM_CanDoRollStab(void) { + if (pm->ps->weapon == WP_SABER) { + saberInfo_t *saber = BG_MySaber(pm->ps->clientNum, 0); + if (saber && (saber->saberFlags & SFL_NO_ROLL_STAB)) { return qfalse; } - saber = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber - && (saber->saberFlags&SFL_NO_ROLL_STAB) ) - { + saber = BG_MySaber(pm->ps->clientNum, 1); + if (saber && (saber->saberFlags & SFL_NO_ROLL_STAB)) { return qfalse; } } @@ -2738,45 +2190,36 @@ While this is a little different than the Quake 3 code, there is no clean way of */ // Ultimate goal is to set the sabermove to the proper next location // Note that if the resultant animation is NONE, then the animation is essentially "idle", and is set in WP_TorsoAnim -qboolean PM_WalkingAnim( int anim ); -qboolean PM_SwimmingAnim( int anim ); -int PM_SaberBounceForAttack( int move ); -qboolean BG_SuperBreakLoseAnim( int anim ); -qboolean BG_SuperBreakWinAnim( int anim ); -void PM_WeaponLightsaber(void) -{ - int addTime; - qboolean delayed_fire = qfalse; - int anim=-1, curmove, newmove=LS_NONE; +qboolean PM_WalkingAnim(int anim); +qboolean PM_SwimmingAnim(int anim); +int PM_SaberBounceForAttack(int move); +qboolean BG_SuperBreakLoseAnim(int anim); +qboolean BG_SuperBreakWinAnim(int anim); +void PM_WeaponLightsaber(void) { + int addTime; + qboolean delayed_fire = qfalse; + int anim = -1, curmove, newmove = LS_NONE; qboolean checkOnlyWeap = qfalse; - if ( PM_InKnockDown( pm->ps ) || BG_InRoll( pm->ps, pm->ps->legsAnim )) - {//in knockdown + if (PM_InKnockDown(pm->ps) || BG_InRoll(pm->ps, pm->ps->legsAnim)) { // in knockdown // make weapon function - if ( pm->ps->weaponTime > 0 ) { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; - if ( pm->ps->weaponTime <= 0 ) - { + if (pm->ps->weaponTime <= 0) { pm->ps->weaponTime = 0; } } - if ( pm->ps->legsAnim == BOTH_ROLL_F - && pm->ps->legsTimer <= 250 ) - { - if ( (pm->cmd.buttons&BUTTON_ATTACK) ) - { - if ( BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB) && !pm->ps->saberInFlight ) - { - if ( PM_CanDoRollStab() ) - { - //make sure the saber is on for this move! - if ( pm->ps->saberHolstered == 2 ) - {//all the way off + if (pm->ps->legsAnim == BOTH_ROLL_F && pm->ps->legsTimer <= 250) { + if ((pm->cmd.buttons & BUTTON_ATTACK)) { + if (BG_EnoughForcePowerForMove(SABER_ALT_ATTACK_POWER_FB) && !pm->ps->saberInFlight) { + if (PM_CanDoRollStab()) { + // make sure the saber is on for this move! + if (pm->ps->saberHolstered == 2) { // all the way off pm->ps->saberHolstered = 0; PM_AddEvent(EV_SABER_UNHOLSTER); } - PM_SetSaberMove( LS_ROLL_STAB ); + PM_SetSaberMove(LS_ROLL_STAB); BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER_FB); } } @@ -2785,35 +2228,26 @@ void PM_WeaponLightsaber(void) return; } - if ( pm->ps->saberLockTime > pm->cmd.serverTime ) - { + if (pm->ps->saberLockTime > pm->cmd.serverTime) { pm->ps->saberMove = LS_NONE; PM_SaberLocked(); return; - } - else - { - if ( /*( (pm->ps->torsoAnim) == BOTH_BF2LOCK || - (pm->ps->torsoAnim) == BOTH_BF1LOCK || - (pm->ps->torsoAnim) == BOTH_CWCIRCLELOCK || - (pm->ps->torsoAnim) == BOTH_CCWCIRCLELOCK ||*/ - pm->ps->saberLockFrame - ) - { - if (pm->ps->saberLockEnemy < ENTITYNUM_NONE && - pm->ps->saberLockEnemy >= 0) - { + } else { + if (/*( (pm->ps->torsoAnim) == BOTH_BF2LOCK || + (pm->ps->torsoAnim) == BOTH_BF1LOCK || + (pm->ps->torsoAnim) == BOTH_CWCIRCLELOCK || + (pm->ps->torsoAnim) == BOTH_CCWCIRCLELOCK ||*/ + pm->ps->saberLockFrame) { + if (pm->ps->saberLockEnemy < ENTITYNUM_NONE && pm->ps->saberLockEnemy >= 0) { bgEntity_t *bgEnt; playerState_t *en; bgEnt = PM_BGEntForNum(pm->ps->saberLockEnemy); - if (bgEnt) - { + if (bgEnt) { en = bgEnt->playerState; - if (en) - { + if (en) { PM_SaberLockBreak(en, qfalse, 0); return; } @@ -2824,73 +2258,53 @@ void PM_WeaponLightsaber(void) (pm->ps->torsoAnim) == BOTH_BF1LOCK || (pm->ps->torsoAnim) == BOTH_CWCIRCLELOCK || (pm->ps->torsoAnim) == BOTH_CCWCIRCLELOCK ||*/ - pm->ps->saberLockFrame - ) - { + pm->ps->saberLockFrame) { pm->ps->torsoTimer = 0; - PM_SetAnim(SETANIM_TORSO,BOTH_STAND1,SETANIM_FLAG_OVERRIDE); + PM_SetAnim(SETANIM_TORSO, BOTH_STAND1, SETANIM_FLAG_OVERRIDE); pm->ps->saberLockFrame = 0; } } } - if ( BG_KickingAnim( pm->ps->legsAnim ) || - BG_KickingAnim( pm->ps->torsoAnim )) - { - if ( pm->ps->legsTimer > 0 ) - {//you're kicking, no interruptions + if (BG_KickingAnim(pm->ps->legsAnim) || BG_KickingAnim(pm->ps->torsoAnim)) { + if (pm->ps->legsTimer > 0) { // you're kicking, no interruptions return; } - //done? be immeditately ready to do an attack + // done? be immeditately ready to do an attack pm->ps->saberMove = LS_READY; pm->ps->weaponTime = 0; } - if ( BG_SuperBreakLoseAnim( pm->ps->torsoAnim ) - || BG_SuperBreakWinAnim( pm->ps->torsoAnim ) ) - { - if ( pm->ps->torsoTimer > 0 ) - {//never interrupt these + if (BG_SuperBreakLoseAnim(pm->ps->torsoAnim) || BG_SuperBreakWinAnim(pm->ps->torsoAnim)) { + if (pm->ps->torsoTimer > 0) { // never interrupt these return; } } - if (BG_SabersOff( pm->ps )) - { - if (pm->ps->saberMove != LS_READY) - { - PM_SetSaberMove( LS_READY ); + if (BG_SabersOff(pm->ps)) { + if (pm->ps->saberMove != LS_READY) { + PM_SetSaberMove(LS_READY); } - if ((pm->ps->legsAnim) != (pm->ps->torsoAnim) && !BG_InSlopeAnim(pm->ps->legsAnim) && - pm->ps->torsoTimer <= 0) - { - PM_SetAnim(SETANIM_TORSO,(pm->ps->legsAnim),SETANIM_FLAG_OVERRIDE); - } - else if (BG_InSlopeAnim(pm->ps->legsAnim) && pm->ps->torsoTimer <= 0) - { - PM_SetAnim(SETANIM_TORSO,PM_GetSaberStance(),SETANIM_FLAG_OVERRIDE); + if ((pm->ps->legsAnim) != (pm->ps->torsoAnim) && !BG_InSlopeAnim(pm->ps->legsAnim) && pm->ps->torsoTimer <= 0) { + PM_SetAnim(SETANIM_TORSO, (pm->ps->legsAnim), SETANIM_FLAG_OVERRIDE); + } else if (BG_InSlopeAnim(pm->ps->legsAnim) && pm->ps->torsoTimer <= 0) { + PM_SetAnim(SETANIM_TORSO, PM_GetSaberStance(), SETANIM_FLAG_OVERRIDE); } - if (pm->ps->weaponTime < 1 && ((pm->cmd.buttons & BUTTON_ALT_ATTACK) || (pm->cmd.buttons & BUTTON_ATTACK))) - { - if (pm->ps->duelTime < pm->cmd.serverTime) - { - if (!pm->ps->m_iVehicleNum) - { //don't let em unholster the saber by attacking while on vehicle + if (pm->ps->weaponTime < 1 && ((pm->cmd.buttons & BUTTON_ALT_ATTACK) || (pm->cmd.buttons & BUTTON_ATTACK))) { + if (pm->ps->duelTime < pm->cmd.serverTime) { + if (!pm->ps->m_iVehicleNum) { // don't let em unholster the saber by attacking while on vehicle pm->ps->saberHolstered = 0; PM_AddEvent(EV_SABER_UNHOLSTER); - } - else - { + } else { pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; pm->cmd.buttons &= ~BUTTON_ATTACK; } } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { pm->ps->weaponTime -= pml.msec; } @@ -2898,8 +2312,7 @@ void PM_WeaponLightsaber(void) goto weapChecks; } - if (!pm->ps->saberEntityNum && pm->ps->saberInFlight) - { //this means our saber has been knocked away + if (!pm->ps->saberEntityNum && pm->ps->saberInFlight) { // this means our saber has been knocked away /* if (pm->ps->saberMove != LS_READY) { @@ -2918,74 +2331,58 @@ void PM_WeaponLightsaber(void) return; */ - //Old method, don't want to do this now because we want to finish up reflected attacks and things - //if our saber is pried out of our hands from one. - if ( pm->ps->fd.saberAnimLevel == SS_DUAL ) - { - if ( pm->ps->saberHolstered > 1 ) - { + // Old method, don't want to do this now because we want to finish up reflected attacks and things + // if our saber is pried out of our hands from one. + if (pm->ps->fd.saberAnimLevel == SS_DUAL) { + if (pm->ps->saberHolstered > 1) { pm->ps->saberHolstered = 1; } - } - else - { + } else { pm->cmd.buttons &= ~BUTTON_ATTACK; } pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; } - if ( (pm->cmd.buttons & BUTTON_ALT_ATTACK) ) - { //might as well just check for a saber throw right here - if (pm->ps->fd.saberAnimLevel == SS_STAFF) - { //kick instead of doing a throw - //if in a saber attack return anim, can interrupt it with a kick - if ( pm->ps->weaponTime > 0//can't fire yet - && PM_SaberInReturn( pm->ps->saberMove )//in a saber return move - FIXME: what about transitions? + if ((pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // might as well just check for a saber throw right here + if (pm->ps->fd.saberAnimLevel == SS_STAFF) { // kick instead of doing a throw + // if in a saber attack return anim, can interrupt it with a kick + if (pm->ps->weaponTime > 0 // can't fire yet + && PM_SaberInReturn(pm->ps->saberMove) // in a saber return move - FIXME: what about transitions? //&& pm->ps->weaponTime <= 250//should be able to fire soon //&& pm->ps->torsoTimer <= 250//torso almost done - && pm->ps->saberBlocked == BLOCKED_NONE//not interacting with any other saber - && !(pm->cmd.buttons&BUTTON_ATTACK) )//not trying to swing the saber + && pm->ps->saberBlocked == BLOCKED_NONE // not interacting with any other saber + && !(pm->cmd.buttons & BUTTON_ATTACK)) // not trying to swing the saber { - if ( (pm->cmd.forwardmove||pm->cmd.rightmove)//trying to kick in a specific direction - && PM_CheckAltKickAttack() )//trying to do a kick - {//allow them to do the kick now! + if ((pm->cmd.forwardmove || pm->cmd.rightmove) // trying to kick in a specific direction + && PM_CheckAltKickAttack()) // trying to do a kick + { // allow them to do the kick now! int kickMove = PM_KickMoveForConditions(); - if (kickMove != -1) - { + if (kickMove != -1) { pm->ps->weaponTime = 0; - PM_SetSaberMove( kickMove ); + PM_SetSaberMove(kickMove); return; } } } - } - else if ( pm->ps->weaponTime < 1&& - pm->ps->saberCanThrow && - //pm->ps->fd.forcePower >= forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW] && - !BG_HasYsalamiri(pm->gametype, pm->ps) && - BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_SABERTHROW) && - pm->ps->fd.forcePowerLevel[FP_SABERTHROW] > 0 && - PM_SaberPowerCheck() ) - { + } else if (pm->ps->weaponTime < 1 && pm->ps->saberCanThrow && + // pm->ps->fd.forcePower >= forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW] && + !BG_HasYsalamiri(pm->gametype, pm->ps) && BG_CanUseFPNow(pm->gametype, pm->ps, pm->cmd.serverTime, FP_SABERTHROW) && + pm->ps->fd.forcePowerLevel[FP_SABERTHROW] > 0 && PM_SaberPowerCheck()) { trace_t sabTr; - vec3_t fwd, minFwd, sabMins, sabMaxs; + vec3_t fwd, minFwd, sabMins, sabMaxs; - VectorSet( sabMins, SABERMINS_X, SABERMINS_Y, SABERMINS_Z ); - VectorSet( sabMaxs, SABERMAXS_X, SABERMAXS_Y, SABERMAXS_Z ); + VectorSet(sabMins, SABERMINS_X, SABERMINS_Y, SABERMINS_Z); + VectorSet(sabMaxs, SABERMAXS_X, SABERMAXS_Y, SABERMAXS_Z); - AngleVectors( pm->ps->viewangles, fwd, NULL, NULL ); - VectorMA( pm->ps->origin, SABER_MIN_THROW_DIST, fwd, minFwd ); + AngleVectors(pm->ps->viewangles, fwd, NULL, NULL); + VectorMA(pm->ps->origin, SABER_MIN_THROW_DIST, fwd, minFwd); pm->trace(&sabTr, pm->ps->origin, sabMins, sabMaxs, minFwd, pm->ps->clientNum, MASK_PLAYERSOLID); - if ( sabTr.allsolid || sabTr.startsolid || sabTr.fraction < 1.0f ) - {//not enough room to throw - } - else - {//throw it - //This will get set to false again once the saber makes it back to its owner game-side - if (!pm->ps->saberInFlight) - { + if (sabTr.allsolid || sabTr.startsolid || sabTr.fraction < 1.0f) { // not enough room to throw + } else { // throw it + // This will get set to false again once the saber makes it back to its owner game-side + if (!pm->ps->saberInFlight) { pm->ps->fd.forcePower -= forcePowerNeeded[pm->ps->fd.forcePowerLevel[FP_SABERTHROW]][FP_SABERTHROW]; } @@ -2994,30 +2391,26 @@ void PM_WeaponLightsaber(void) } } - if ( pm->ps->saberInFlight && pm->ps->saberEntityNum ) - {//guiding saber - if ( (pm->ps->fd.saberAnimLevel != SS_DUAL //not using 2 sabers - || pm->ps->saberHolstered //left one off - FIXME: saberHolstered 1 should be left one off, 0 should be both on, 2 should be both off - || (!(pm->cmd.buttons&BUTTON_ATTACK)//not trying to start an attack AND... - && (pm->ps->torsoAnim == BOTH_SABERDUAL_STANCE//not already attacking - || pm->ps->torsoAnim == BOTH_SABERPULL//not already attacking - || pm->ps->torsoAnim == BOTH_STAND1//not already attacking - || PM_RunningAnim( pm->ps->torsoAnim ) //not already attacking - || PM_WalkingAnim( pm->ps->torsoAnim ) //not already attacking - || PM_JumpingAnim( pm->ps->torsoAnim )//not already attacking - || PM_SwimmingAnim( pm->ps->torsoAnim ))//not already attacking - ) - ) - ) - { - PM_SetAnim(SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (pm->ps->saberInFlight && pm->ps->saberEntityNum) { // guiding saber + if ((pm->ps->fd.saberAnimLevel != SS_DUAL // not using 2 sabers + || pm->ps->saberHolstered // left one off - FIXME: saberHolstered 1 should be left one off, 0 should be both on, 2 should be both off + || (!(pm->cmd.buttons & BUTTON_ATTACK) // not trying to start an attack AND... + && (pm->ps->torsoAnim == BOTH_SABERDUAL_STANCE // not already attacking + || pm->ps->torsoAnim == BOTH_SABERPULL // not already attacking + || pm->ps->torsoAnim == BOTH_STAND1 // not already attacking + || PM_RunningAnim(pm->ps->torsoAnim) // not already attacking + || PM_WalkingAnim(pm->ps->torsoAnim) // not already attacking + || PM_JumpingAnim(pm->ps->torsoAnim) // not already attacking + || PM_SwimmingAnim(pm->ps->torsoAnim)) // not already attacking + ))) { + PM_SetAnim(SETANIM_TORSO, BOTH_SABERPULL, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); pm->ps->torsoTimer = 1; return; } } - // don't allow attack until all buttons are up - //This is bad. It freezes the attack state and the animations if you hold the button after respawning, and it looks strange. + // don't allow attack until all buttons are up + // This is bad. It freezes the attack state and the animations if you hold the button after respawning, and it looks strange. /* if ( pm->ps->pm_flags & PMF_RESPAWNED ) { return; @@ -3025,7 +2418,7 @@ void PM_WeaponLightsaber(void) */ // check for dead player - if ( pm->ps->stats[STAT_HEALTH] <= 0 ) { + if (pm->ps->stats[STAT_HEALTH] <= 0) { return; } @@ -3050,12 +2443,10 @@ void PM_WeaponLightsaber(void) */ // make weapon function - if ( pm->ps->weaponTime > 0 ) - { - //check for special pull move while busy + if (pm->ps->weaponTime > 0) { + // check for special pull move while busy saberMoveName_t pullmove = PM_CheckPullAttack(); - if (pullmove != LS_NONE) - { + if (pullmove != LS_NONE) { pm->ps->weaponTime = 0; pm->ps->torsoTimer = 0; pm->ps->legsTimer = 0; @@ -3067,155 +2458,125 @@ void PM_WeaponLightsaber(void) pm->ps->weaponTime -= pml.msec; - //This was stupid and didn't work right. Looks like things are fine without it. - // if (pm->ps->saberBlocked && pm->ps->torsoAnim != saberMoveData[pm->ps->saberMove].animToUse) - // { //rww - keep him in the blocking pose until he can attack again - // PM_SetAnim(SETANIM_TORSO,saberMoveData[pm->ps->saberMove].animToUse,saberMoveData[pm->ps->saberMove].animSetFlags|SETANIM_FLAG_HOLD); - // return; - // } - } - else - { + // This was stupid and didn't work right. Looks like things are fine without it. + // if (pm->ps->saberBlocked && pm->ps->torsoAnim != saberMoveData[pm->ps->saberMove].animToUse) + // { //rww - keep him in the blocking pose until he can attack again + // PM_SetAnim(SETANIM_TORSO,saberMoveData[pm->ps->saberMove].animToUse,saberMoveData[pm->ps->saberMove].animSetFlags|SETANIM_FLAG_HOLD); + // return; + // } + } else { pm->ps->weaponstate = WEAPON_READY; } // Now we react to a block action by the player's lightsaber. - if ( pm->ps->saberBlocked ) - { - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT - && pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ) - {//hold the parry for a bit - pm->ps->weaponTime = bg_parryDebounce[pm->ps->fd.forcePowerLevel[FP_SABER_DEFENSE]]+200; + if (pm->ps->saberBlocked) { + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT && pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ) { // hold the parry for a bit + pm->ps->weaponTime = bg_parryDebounce[pm->ps->fd.forcePowerLevel[FP_SABER_DEFENSE]] + 200; } - switch ( pm->ps->saberBlocked ) - { - case BLOCKED_BOUNCE_MOVE: - { //act as a bounceMove and reset the saberMove instead of using a seperate value for it - pm->ps->torsoTimer = 0; - PM_SetSaberMove( pm->ps->saberMove ); - pm->ps->weaponTime = pm->ps->torsoTimer; - pm->ps->saberBlocked = 0; - } - break; - case BLOCKED_PARRY_BROKEN: - //whatever parry we were is in now broken, play the appropriate knocked-away anim - { - int nextMove; + switch (pm->ps->saberBlocked) { + case BLOCKED_BOUNCE_MOVE: { // act as a bounceMove and reset the saberMove instead of using a seperate value for it + pm->ps->torsoTimer = 0; + PM_SetSaberMove(pm->ps->saberMove); + pm->ps->weaponTime = pm->ps->torsoTimer; + pm->ps->saberBlocked = 0; + } break; + case BLOCKED_PARRY_BROKEN: + // whatever parry we were is in now broken, play the appropriate knocked-away anim + { + int nextMove; - if ( PM_SaberInBrokenParry( pm->ps->saberMove ) ) - {//already have one...? - nextMove = pm->ps->saberMove; - } - else - { - nextMove = PM_BrokenParryForParry( pm->ps->saberMove ); - } - if ( nextMove != LS_NONE ) - { - PM_SetSaberMove( nextMove ); - pm->ps->weaponTime = pm->ps->torsoTimer; - } - else - {//Maybe in a knockaway? - } + if (PM_SaberInBrokenParry(pm->ps->saberMove)) { // already have one...? + nextMove = pm->ps->saberMove; + } else { + nextMove = PM_BrokenParryForParry(pm->ps->saberMove); } - break; - case BLOCKED_ATK_BOUNCE: - // If there is absolutely no blocked move in the chart, don't even mess with the animation. - // OR if we are already in a block or parry. - if (pm->ps->saberMove >= LS_T1_BR__R) - {//an actual bounce? Other bounces before this are actually transitions? - pm->ps->saberBlocked = BLOCKED_NONE; + if (nextMove != LS_NONE) { + PM_SetSaberMove(nextMove); + pm->ps->weaponTime = pm->ps->torsoTimer; + } else { // Maybe in a knockaway? } - else - { - int bounceMove; - - if ( PM_SaberInBounce( pm->ps->saberMove ) || !BG_SaberInAttack( pm->ps->saberMove ) ) - { - if ( pm->cmd.buttons & BUTTON_ATTACK ) - {//transition to a new attack - int newQuad = PM_SaberMoveQuadrantForMovement( &pm->cmd ); - while ( newQuad == saberMoveData[pm->ps->saberMove].startQuad ) - {//player is still in same attack quad, don't repeat that attack because it looks bad, - //FIXME: try to pick one that might look cool? - //newQuad = Q_irand( Q_BR, Q_BL ); - newQuad = PM_irand_timesync( Q_BR, Q_BL ); - //FIXME: sanity check, just in case? - }//else player is switching up anyway, take the new attack dir - bounceMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; - } - else - {//return to ready - if ( saberMoveData[pm->ps->saberMove].startQuad == Q_T ) - { - bounceMove = LS_R_BL2TR; - } - else if ( saberMoveData[pm->ps->saberMove].startQuad < Q_T ) - { - bounceMove = LS_R_TL2BR+saberMoveData[pm->ps->saberMove].startQuad-Q_BR; - } - else// if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) - { - bounceMove = LS_R_BR2TL+saberMoveData[pm->ps->saberMove].startQuad-Q_TL; - } + } + break; + case BLOCKED_ATK_BOUNCE: + // If there is absolutely no blocked move in the chart, don't even mess with the animation. + // OR if we are already in a block or parry. + if (pm->ps->saberMove >= LS_T1_BR__R) { // an actual bounce? Other bounces before this are actually transitions? + pm->ps->saberBlocked = BLOCKED_NONE; + } else { + int bounceMove; + + if (PM_SaberInBounce(pm->ps->saberMove) || !BG_SaberInAttack(pm->ps->saberMove)) { + if (pm->cmd.buttons & BUTTON_ATTACK) { // transition to a new attack + int newQuad = PM_SaberMoveQuadrantForMovement(&pm->cmd); + while ( + newQuad == + saberMoveData[pm->ps->saberMove].startQuad) { // player is still in same attack quad, don't repeat that attack because it looks bad, + // FIXME: try to pick one that might look cool? + // newQuad = Q_irand( Q_BR, Q_BL ); + newQuad = PM_irand_timesync(Q_BR, Q_BL); + // FIXME: sanity check, just in case? + } // else player is switching up anyway, take the new attack dir + bounceMove = transitionMove[saberMoveData[pm->ps->saberMove].startQuad][newQuad]; + } else { // return to ready + if (saberMoveData[pm->ps->saberMove].startQuad == Q_T) { + bounceMove = LS_R_BL2TR; + } else if (saberMoveData[pm->ps->saberMove].startQuad < Q_T) { + bounceMove = LS_R_TL2BR + saberMoveData[pm->ps->saberMove].startQuad - Q_BR; + } else // if ( saberMoveData[pm->ps->saberMove].startQuad > Q_T ) + { + bounceMove = LS_R_BR2TL + saberMoveData[pm->ps->saberMove].startQuad - Q_TL; } } - else - {//start the bounce - bounceMove = PM_SaberBounceForAttack( (saberMoveName_t)pm->ps->saberMove ); - } - - PM_SetSaberMove( bounceMove ); + } else { // start the bounce + bounceMove = PM_SaberBounceForAttack((saberMoveName_t)pm->ps->saberMove); + } - pm->ps->weaponTime = pm->ps->torsoTimer;//+saberMoveData[bounceMove].blendTime+SABER_BLOCK_DUR; + PM_SetSaberMove(bounceMove); - } - break; - case BLOCKED_UPPER_RIGHT: - PM_SetSaberMove( LS_PARRY_UR ); - break; - case BLOCKED_UPPER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_UR ); - break; - case BLOCKED_UPPER_LEFT: - PM_SetSaberMove( LS_PARRY_UL ); - break; - case BLOCKED_UPPER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_UL ); - break; - case BLOCKED_LOWER_RIGHT: - PM_SetSaberMove( LS_PARRY_LR ); - break; - case BLOCKED_LOWER_RIGHT_PROJ: - PM_SetSaberMove( LS_REFLECT_LR ); - break; - case BLOCKED_LOWER_LEFT: - PM_SetSaberMove( LS_PARRY_LL ); - break; - case BLOCKED_LOWER_LEFT_PROJ: - PM_SetSaberMove( LS_REFLECT_LL); - break; - case BLOCKED_TOP: - PM_SetSaberMove( LS_PARRY_UP ); - break; - case BLOCKED_TOP_PROJ: - PM_SetSaberMove( LS_REFLECT_UP ); - break; - default: - pm->ps->saberBlocked = BLOCKED_NONE; - break; + pm->ps->weaponTime = pm->ps->torsoTimer; //+saberMoveData[bounceMove].blendTime+SABER_BLOCK_DUR; + } + break; + case BLOCKED_UPPER_RIGHT: + PM_SetSaberMove(LS_PARRY_UR); + break; + case BLOCKED_UPPER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_UR); + break; + case BLOCKED_UPPER_LEFT: + PM_SetSaberMove(LS_PARRY_UL); + break; + case BLOCKED_UPPER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_UL); + break; + case BLOCKED_LOWER_RIGHT: + PM_SetSaberMove(LS_PARRY_LR); + break; + case BLOCKED_LOWER_RIGHT_PROJ: + PM_SetSaberMove(LS_REFLECT_LR); + break; + case BLOCKED_LOWER_LEFT: + PM_SetSaberMove(LS_PARRY_LL); + break; + case BLOCKED_LOWER_LEFT_PROJ: + PM_SetSaberMove(LS_REFLECT_LL); + break; + case BLOCKED_TOP: + PM_SetSaberMove(LS_PARRY_UP); + break; + case BLOCKED_TOP_PROJ: + PM_SetSaberMove(LS_REFLECT_UP); + break; + default: + pm->ps->saberBlocked = BLOCKED_NONE; + break; } - if ( pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT - && pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ) - {//hold the parry for a bit - if ( pm->ps->torsoTimer < pm->ps->weaponTime ) - { + if (pm->ps->saberBlocked >= BLOCKED_UPPER_RIGHT && pm->ps->saberBlocked < BLOCKED_UPPER_RIGHT_PROJ) { // hold the parry for a bit + if (pm->ps->torsoTimer < pm->ps->weaponTime) { pm->ps->torsoTimer = pm->ps->weaponTime; } } - //what the? I don't know why I was doing this. + // what the? I don't know why I was doing this. /* if (pm->ps->saberBlocked != BLOCKED_ATK_BOUNCE && pm->ps->saberBlocked != BLOCKED_PARRY_BROKEN && pm->ps->weaponTime < 1) { @@ -3224,7 +2585,7 @@ void PM_WeaponLightsaber(void) } */ - //clear block + // clear block pm->ps->saberBlocked = 0; // Charging is like a lead-up before attacking again. This is an appropriate use, or we can create a new weaponstate for blocking @@ -3235,98 +2596,77 @@ void PM_WeaponLightsaber(void) } weapChecks: - if (pm->ps->saberEntityNum) - { //only check if we have our saber with us + if (pm->ps->saberEntityNum) { // only check if we have our saber with us // check for weapon change // can't change if weapon is firing, but can change again if lowering or raising - //if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) { - if (pm->ps->weaponTime <= 0 && pm->ps->torsoTimer <= 0) - { - if ( pm->ps->weapon != pm->cmd.weapon ) { - PM_BeginWeaponChange( pm->cmd.weapon ); + // if ( pm->ps->weaponTime <= 0 || pm->ps->weaponstate != WEAPON_FIRING ) { + if (pm->ps->weaponTime <= 0 && pm->ps->torsoTimer <= 0) { + if (pm->ps->weapon != pm->cmd.weapon) { + PM_BeginWeaponChange(pm->cmd.weapon); } } } - if ( PM_CanDoKata() ) - { + if (PM_CanDoKata()) { saberMoveName_t overrideMove = LS_INVALID; - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - //see if we have an overridden (or cancelled) kata move - if ( saber1 && saber1->kataMove != LS_INVALID ) - { - if ( saber1->kataMove != LS_NONE ) - { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + // see if we have an overridden (or cancelled) kata move + if (saber1 && saber1->kataMove != LS_INVALID) { + if (saber1->kataMove != LS_NONE) { overrideMove = (saberMoveName_t)saber1->kataMove; } } - if ( overrideMove == LS_INVALID ) - {//not overridden by first saber, check second - if ( saber2 - && saber2->kataMove != LS_INVALID ) - { - if ( saber2->kataMove != LS_NONE ) - { + if (overrideMove == LS_INVALID) { // not overridden by first saber, check second + if (saber2 && saber2->kataMove != LS_INVALID) { + if (saber2->kataMove != LS_NONE) { overrideMove = (saberMoveName_t)saber2->kataMove; } } } - //no overrides, cancelled? - if ( overrideMove == LS_INVALID ) - { - if ( saber2 - && saber2->kataMove == LS_NONE ) - { + // no overrides, cancelled? + if (overrideMove == LS_INVALID) { + if (saber2 && saber2->kataMove == LS_NONE) { overrideMove = LS_NONE; - } - else if ( saber2 - && saber2->kataMove == LS_NONE ) - { + } else if (saber2 && saber2->kataMove == LS_NONE) { overrideMove = LS_NONE; } } - if ( overrideMove == LS_INVALID ) - {//not overridden - //FIXME: make sure to turn on saber(s)! - switch ( pm->ps->fd.saberAnimLevel ) - { + if (overrideMove == LS_INVALID) { // not overridden + // FIXME: make sure to turn on saber(s)! + switch (pm->ps->fd.saberAnimLevel) { case SS_FAST: case SS_TAVION: - PM_SetSaberMove( LS_A1_SPECIAL ); + PM_SetSaberMove(LS_A1_SPECIAL); break; case SS_MEDIUM: - PM_SetSaberMove( LS_A2_SPECIAL ); + PM_SetSaberMove(LS_A2_SPECIAL); break; case SS_STRONG: case SS_DESANN: - PM_SetSaberMove( LS_A3_SPECIAL ); + PM_SetSaberMove(LS_A3_SPECIAL); break; case SS_DUAL: - PM_SetSaberMove( LS_DUAL_SPIN_PROTECT );//PM_CheckDualSpinProtect(); + PM_SetSaberMove(LS_DUAL_SPIN_PROTECT); // PM_CheckDualSpinProtect(); break; case SS_STAFF: - PM_SetSaberMove( LS_STAFF_SOULCAL ); + PM_SetSaberMove(LS_STAFF_SOULCAL); break; } pm->ps->weaponstate = WEAPON_FIRING; - //G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER );//FP_SPEED, SINGLE_SPECIAL_POWER ); + // G_DrainPowerForSpecialMove( pm->gent, FP_SABER_OFFENSE, SABER_ALT_ATTACK_POWER );//FP_SPEED, SINGLE_SPECIAL_POWER ); BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER); - } - else if ( overrideMove != LS_NONE ) - { - PM_SetSaberMove( overrideMove ); + } else if (overrideMove != LS_NONE) { + PM_SetSaberMove(overrideMove); pm->ps->weaponstate = WEAPON_FIRING; BG_ForcePowerDrain(pm->ps, FP_GRIP, SABER_ALT_ATTACK_POWER); } - if ( overrideMove != LS_NONE ) - {//not cancelled + if (overrideMove != LS_NONE) { // not cancelled return; } } - if ( pm->ps->weaponTime > 0 ) - { + if (pm->ps->weaponTime > 0) { return; } @@ -3335,7 +2675,7 @@ void PM_WeaponLightsaber(void) // ********************************************************* // change weapon if time - if ( pm->ps->weaponstate == WEAPON_DROPPING ) { + if (pm->ps->weaponstate == WEAPON_DROPPING) { PM_FinishWeaponChange(); return; } @@ -3344,97 +2684,64 @@ void PM_WeaponLightsaber(void) // WEAPON_RAISING // ********************************************************* - if ( pm->ps->weaponstate == WEAPON_RAISING ) - {//Just selected the weapon + if (pm->ps->weaponstate == WEAPON_RAISING) { // Just selected the weapon pm->ps->weaponstate = WEAPON_IDLE; - if((pm->ps->legsAnim) == BOTH_WALK1 ) - { - PM_SetAnim(SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); - } - else if((pm->ps->legsAnim) == BOTH_RUN1 ) - { - PM_SetAnim(SETANIM_TORSO,BOTH_RUN1,SETANIM_FLAG_NORMAL); - } - else if((pm->ps->legsAnim) == BOTH_RUN2 ) - { - PM_SetAnim(SETANIM_TORSO,BOTH_RUN2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN_STAFF) - { - PM_SetAnim(SETANIM_TORSO,BOTH_RUN_STAFF,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_RUN_DUAL) - { - PM_SetAnim(SETANIM_TORSO,BOTH_RUN_DUAL,SETANIM_FLAG_NORMAL); - } - else if((pm->ps->legsAnim) == BOTH_WALK1 ) - { - PM_SetAnim(SETANIM_TORSO,BOTH_WALK1,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK2) - { - PM_SetAnim(SETANIM_TORSO,BOTH_WALK2,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK_STAFF) - { - PM_SetAnim(SETANIM_TORSO,BOTH_WALK_STAFF,SETANIM_FLAG_NORMAL); - } - else if( pm->ps->legsAnim == BOTH_WALK_DUAL) - { - PM_SetAnim(SETANIM_TORSO,BOTH_WALK_DUAL,SETANIM_FLAG_NORMAL); - } - else - { - PM_SetAnim(SETANIM_TORSO,PM_GetSaberStance(),SETANIM_FLAG_NORMAL); - } - - if (pm->ps->weaponstate == WEAPON_RAISING) - { + if ((pm->ps->legsAnim) == BOTH_WALK1) { + PM_SetAnim(SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else if ((pm->ps->legsAnim) == BOTH_RUN1) { + PM_SetAnim(SETANIM_TORSO, BOTH_RUN1, SETANIM_FLAG_NORMAL); + } else if ((pm->ps->legsAnim) == BOTH_RUN2) { + PM_SetAnim(SETANIM_TORSO, BOTH_RUN2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_STAFF) { + PM_SetAnim(SETANIM_TORSO, BOTH_RUN_STAFF, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_RUN_DUAL) { + PM_SetAnim(SETANIM_TORSO, BOTH_RUN_DUAL, SETANIM_FLAG_NORMAL); + } else if ((pm->ps->legsAnim) == BOTH_WALK1) { + PM_SetAnim(SETANIM_TORSO, BOTH_WALK1, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK2) { + PM_SetAnim(SETANIM_TORSO, BOTH_WALK2, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_STAFF) { + PM_SetAnim(SETANIM_TORSO, BOTH_WALK_STAFF, SETANIM_FLAG_NORMAL); + } else if (pm->ps->legsAnim == BOTH_WALK_DUAL) { + PM_SetAnim(SETANIM_TORSO, BOTH_WALK_DUAL, SETANIM_FLAG_NORMAL); + } else { + PM_SetAnim(SETANIM_TORSO, PM_GetSaberStance(), SETANIM_FLAG_NORMAL); + } + + if (pm->ps->weaponstate == WEAPON_RAISING) { return; } - } - if (checkOnlyWeap) - { + if (checkOnlyWeap) { return; } // ********************************************************* // Check for WEAPON ATTACK // ********************************************************* - if (pm->ps->fd.saberAnimLevel == SS_STAFF && - (pm->cmd.buttons & BUTTON_ALT_ATTACK)) - { //ok, try a kick I guess. + if (pm->ps->fd.saberAnimLevel == SS_STAFF && (pm->cmd.buttons & BUTTON_ALT_ATTACK)) { // ok, try a kick I guess. int kickMove = -1; - if ( !BG_KickingAnim(pm->ps->torsoAnim) && - !BG_KickingAnim(pm->ps->legsAnim) && - !BG_InRoll(pm->ps, pm->ps->legsAnim) && -// !BG_KickMove( pm->ps->saberMove )//not already in a kick - pm->ps->saberMove == LS_READY - && !(pm->ps->pm_flags&PMF_DUCKED)//not ducked - && (pm->cmd.upmove >= 0 ) //not trying to duck - )//&& pm->ps->groundEntityNum != ENTITYNUM_NONE) - {//player kicks + if (!BG_KickingAnim(pm->ps->torsoAnim) && !BG_KickingAnim(pm->ps->legsAnim) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && + // !BG_KickMove( pm->ps->saberMove )//not already in a kick + pm->ps->saberMove == LS_READY && !(pm->ps->pm_flags & PMF_DUCKED) // not ducked + && (pm->cmd.upmove >= 0) // not trying to duck + ) //&& pm->ps->groundEntityNum != ENTITYNUM_NONE) + { // player kicks kickMove = PM_KickMoveForConditions(); } - if (kickMove != -1) - { - if ( pm->ps->groundEntityNum == ENTITYNUM_NONE ) - {//if in air, convert kick to an in-air kick + if (kickMove != -1) { + if (pm->ps->groundEntityNum == ENTITYNUM_NONE) { // if in air, convert kick to an in-air kick float gDist = PM_GroundDistance(); - //let's only allow air kicks if a certain distance from the ground - //it's silly to be able to do them right as you land. - //also looks wrong to transition from a non-complete flip anim... - if ((!BG_FlippingAnim( pm->ps->legsAnim ) || pm->ps->legsTimer <= 0) && - gDist > 64.0f && //strict minimum - gDist > (-pm->ps->velocity[2])-64.0f //make sure we are high to ground relative to downward velocity as well - ) - { - switch ( kickMove ) - { + // let's only allow air kicks if a certain distance from the ground + // it's silly to be able to do them right as you land. + // also looks wrong to transition from a non-complete flip anim... + if ((!BG_FlippingAnim(pm->ps->legsAnim) || pm->ps->legsTimer <= 0) && gDist > 64.0f && // strict minimum + gDist > (-pm->ps->velocity[2]) - 64.0f // make sure we are high to ground relative to downward velocity as well + ) { + switch (kickMove) { case LS_KICK_F: kickMove = LS_KICK_F_AIR; break; @@ -3447,84 +2754,60 @@ void PM_WeaponLightsaber(void) case LS_KICK_L: kickMove = LS_KICK_L_AIR; break; - default: //oh well, can't do any other kick move while in-air + default: // oh well, can't do any other kick move while in-air kickMove = -1; break; } - } - else - {//leave it as a normal kick unless we're too high up - if ( gDist > 128.0f || pm->ps->velocity[2] >= 0 ) - { //off ground, but too close to ground + } else { // leave it as a normal kick unless we're too high up + if (gDist > 128.0f || pm->ps->velocity[2] >= 0) { // off ground, but too close to ground kickMove = -1; } } } - if (kickMove != -1) - { - PM_SetSaberMove( kickMove ); + if (kickMove != -1) { + PM_SetSaberMove(kickMove); return; } } } - //this is never a valid regular saber attack button + // this is never a valid regular saber attack button pm->cmd.buttons &= ~BUTTON_ALT_ATTACK; - if(!delayed_fire) - { + if (!delayed_fire) { // Start with the current move, and cross index it with the current control states. - if ( pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX ) - { + if (pm->ps->saberMove > LS_NONE && pm->ps->saberMove < LS_MOVE_MAX) { curmove = pm->ps->saberMove; - } - else - { + } else { curmove = LS_READY; } - if ( curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_ ) - {//must transition back to ready from this anim + if (curmove == LS_A_JUMP_T__B_ || pm->ps->torsoAnim == BOTH_FORCELEAP2_T__B_) { // must transition back to ready from this anim newmove = LS_R_T2B; } // check for fire - else if ( !(pm->cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//not attacking + else if (!(pm->cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // not attacking pm->ps->weaponTime = 0; - if ( pm->ps->weaponTime > 0 ) - {//Still firing + if (pm->ps->weaponTime > 0) { // Still firing pm->ps->weaponstate = WEAPON_FIRING; - } - else if ( pm->ps->weaponstate != WEAPON_READY ) - { + } else if (pm->ps->weaponstate != WEAPON_READY) { pm->ps->weaponstate = WEAPON_IDLE; } - //Check for finishing an anim if necc. - if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( curmove >= LS_A_TL2BR && curmove <= LS_A_T2B ) - {//finished an attack, must continue from here - newmove = LS_R_TL2BR + (curmove-LS_A_TL2BR); - } - else if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // Check for finishing an anim if necc. + if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (curmove >= LS_A_TL2BR && curmove <= LS_A_T2B) { // finished an attack, must continue from here + newmove = LS_R_TL2BR + (curmove - LS_A_TL2BR); + } else if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( PM_SaberInBounce( curmove ) ) - {//in a bounce - newmove = saberMoveData[curmove].chain_idle;//oops, not attacking, so don't chain - } - else - {//FIXME: what about returning from a parry? - //PM_SetSaberMove( LS_READY ); - //if ( pm->ps->saberBlockingTime > pm->cmd.serverTime ) - { - PM_SetSaberMove( LS_READY ); - } + } else if (PM_SaberInBounce(curmove)) { // in a bounce + newmove = saberMoveData[curmove].chain_idle; // oops, not attacking, so don't chain + } else { // FIXME: what about returning from a parry? + // PM_SetSaberMove( LS_READY ); + // if ( pm->ps->saberBlockingTime > pm->cmd.serverTime ) + { PM_SetSaberMove(LS_READY); } return; } } @@ -3532,31 +2815,21 @@ void PM_WeaponLightsaber(void) // *************************************************** // Pressing attack, so we must look up the proper attack move. - if ( pm->ps->weaponTime > 0 ) - { // Last attack is not yet complete. + if (pm->ps->weaponTime > 0) { // Last attack is not yet complete. pm->ps->weaponstate = WEAPON_FIRING; return; - } - else - { - int both = qfalse; - if ( pm->ps->torsoAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND ) - {//can't attack in these anims + } else { + int both = qfalse; + if (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_ATTACK || pm->ps->torsoAnim == BOTH_FORCELONGLEAP_LAND) { // can't attack in these anims return; - } - else if ( pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START ) - {//only 1 attack you can do from this anim - if ( pm->ps->torsoTimer >= 200 ) - {//hit it early enough to do the attack - PM_SetSaberMove( LS_LEAP_ATTACK ); + } else if (pm->ps->torsoAnim == BOTH_FORCELONGLEAP_START) { // only 1 attack you can do from this anim + if (pm->ps->torsoTimer >= 200) { // hit it early enough to do the attack + PM_SetSaberMove(LS_LEAP_ATTACK); } return; } - if ( curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL ) - {//from a parry or reflection, can go directly into an attack - switch ( saberMoveData[curmove].endQuad ) - { + if (curmove >= LS_PARRY_UP && curmove <= LS_REFLECT_LL) { // from a parry or reflection, can go directly into an attack + switch (saberMoveData[curmove].endQuad) { case Q_T: newmove = LS_A_T2B; break; @@ -3572,48 +2845,40 @@ void PM_WeaponLightsaber(void) case Q_BL: newmove = LS_A_BL2TR; break; - //shouldn't be a parry that ends at L, R or B + // shouldn't be a parry that ends at L, R or B } } - if ( newmove != LS_NONE ) - {//have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim + if (newmove != LS_NONE) { // have a valid, final LS_ move picked, so skip findingt he transition move and just get the anim anim = saberMoveData[newmove].animToUse; } - //FIXME: diagonal dirs use the figure-eight attacks from ready pose? - if ( anim == -1 ) - { - //FIXME: take FP_SABER_OFFENSE into account here somehow? - if ( PM_SaberInTransition( curmove ) ) - {//in a transition, must play sequential attack + // FIXME: diagonal dirs use the figure-eight attacks from ready pose? + if (anim == -1) { + // FIXME: take FP_SABER_OFFENSE into account here somehow? + if (PM_SaberInTransition(curmove)) { // in a transition, must play sequential attack newmove = saberMoveData[curmove].chain_attack; - } - else if ( curmove >= LS_S_TL2BR && curmove <= LS_S_T2B ) - {//started a swing, must continue from here - newmove = LS_A_TL2BR + (curmove-LS_S_TL2BR); - } - else if ( PM_SaberInBrokenParry( curmove ) ) - {//broken parries must always return to ready + } else if (curmove >= LS_S_TL2BR && curmove <= LS_S_T2B) { // started a swing, must continue from here + newmove = LS_A_TL2BR + (curmove - LS_S_TL2BR); + } else if (PM_SaberInBrokenParry(curmove)) { // broken parries must always return to ready newmove = LS_READY; - } - else//if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? - {//get attack move from movement command + } else // if ( pm->cmd.buttons&BUTTON_ATTACK && !(pm->ps->pm_flags&PMF_ATTACK_HELD) )//only do this if just pressed attack button? + { // get attack move from movement command /* if ( PM_SaberKataDone() ) {//we came from a bounce and cannot chain to another attack because our kata is done newmove = saberMoveData[curmove].chain_idle; } else */ - newmove = PM_SaberAttackForMovement( curmove ); - if ( (PM_SaberInBounce( curmove )||PM_SaberInBrokenParry( curmove )) - && saberMoveData[newmove].startQuad == saberMoveData[curmove].endQuad ) - {//this attack would be a repeat of the last (which was blocked), so don't actually use it, use the default chain attack for this bounce + newmove = PM_SaberAttackForMovement(curmove); + if ((PM_SaberInBounce(curmove) || PM_SaberInBrokenParry(curmove)) && + saberMoveData[newmove].startQuad == + saberMoveData[curmove].endQuad) { // this attack would be a repeat of the last (which was blocked), so don't actually use it, use + // the default chain attack for this bounce newmove = saberMoveData[curmove].chain_attack; } - if ( PM_SaberKataDone( curmove, newmove ) ) - {//cannot chain this time + if (PM_SaberKataDone(curmove, newmove)) { // cannot chain this time newmove = saberMoveData[curmove].chain_idle; } } @@ -3624,32 +2889,27 @@ void PM_WeaponLightsaber(void) newmove = PM_AttackMoveForQuad( saberMoveData[curmove].endQuad ); } */ - if ( newmove != LS_NONE ) - { - //Now get the proper transition move - newmove = PM_SaberAnimTransitionAnim( curmove, newmove ); + if (newmove != LS_NONE) { + // Now get the proper transition move + newmove = PM_SaberAnimTransitionAnim(curmove, newmove); anim = saberMoveData[newmove].animToUse; } } - if (anim == -1) - {//not side-stepping, pick neutral anim + if (anim == -1) { // not side-stepping, pick neutral anim // Add randomness for prototype? newmove = saberMoveData[curmove].chain_attack; - anim= saberMoveData[newmove].animToUse; + anim = saberMoveData[newmove].animToUse; - if ( !pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && pm->ps->groundEntityNum != ENTITYNUM_NONE ) - {//not moving at all, so set the anim on entire body + if (!pm->cmd.forwardmove && !pm->cmd.rightmove && pm->cmd.upmove >= 0 && + pm->ps->groundEntityNum != ENTITYNUM_NONE) { // not moving at all, so set the anim on entire body both = qtrue; } - } - if ( anim == -1) - { - switch ( pm->ps->legsAnim ) - { + if (anim == -1) { + switch (pm->ps->legsAnim) { case BOTH_WALK1: case BOTH_WALK2: case BOTH_WALK_STAFF: @@ -3672,21 +2932,20 @@ void PM_WeaponLightsaber(void) break; } -// if (PM_RunningAnim(anim) && !pm->cmd.forwardmove && !pm->cmd.rightmove) -// { //semi-hacky (if not moving on x-y and still playing the running anim, force the player out of it) -// anim = PM_GetSaberStance(); -// } + // if (PM_RunningAnim(anim) && !pm->cmd.forwardmove && !pm->cmd.rightmove) + // { //semi-hacky (if not moving on x-y and still playing the running anim, force the player out of it) + // anim = PM_GetSaberStance(); + // } newmove = LS_READY; } - PM_SetSaberMove( newmove ); + PM_SetSaberMove(newmove); - if ( both && pm->ps->torsoAnim == anim ) - { - PM_SetAnim(SETANIM_LEGS,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); + if (both && pm->ps->torsoAnim == anim) { + PM_SetAnim(SETANIM_LEGS, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } - //don't fire again until anim is done + // don't fire again until anim is done pm->ps->weaponTime = pm->ps->torsoTimer; } } @@ -3700,103 +2959,68 @@ void PM_WeaponLightsaber(void) addTime = pm->ps->weaponTime; pm->ps->saberAttackSequence = pm->ps->torsoAnim; - if ( !addTime ) - { + if (!addTime) { addTime = weaponData[pm->ps->weapon].fireTime; } pm->ps->weaponTime = addTime; } -void PM_SetSaberMove(short newMove) -{ +void PM_SetSaberMove(short newMove) { unsigned int setflags = saberMoveData[newMove].animSetFlags; - int anim = saberMoveData[newMove].animToUse; + int anim = saberMoveData[newMove].animToUse; int parts = SETANIM_TORSO; - if ( newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH ) - {//finished with a kata (or in a special move) reset attack counter + if (newMove == LS_READY || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH) { // finished with a kata (or in a special move) reset attack counter pm->ps->saberAttackChainCount = 0; - } - else if ( BG_SaberInAttack( newMove ) ) - {//continuing with a kata, increment attack counter + } else if (BG_SaberInAttack(newMove)) { // continuing with a kata, increment attack counter pm->ps->saberAttackChainCount++; } - if (pm->ps->saberAttackChainCount > 16) - { //for the sake of being able to send the value over the net within a reasonable bit count + if (pm->ps->saberAttackChainCount > 16) { // for the sake of being able to send the value over the net within a reasonable bit count pm->ps->saberAttackChainCount = 16; } - if ( newMove == LS_DRAW ) - { - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber1 - && saber1->drawAnim != -1 ) - { + if (newMove == LS_DRAW) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + if (saber1 && saber1->drawAnim != -1) { anim = saber1->drawAnim; - } - else if ( saber2 - && saber2->drawAnim != -1 ) - { + } else if (saber2 && saber2->drawAnim != -1) { anim = saber2->drawAnim; - } - else if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { + } else if (pm->ps->fd.saberAnimLevel == SS_STAFF) { anim = BOTH_S1_S7; - } - else if ( pm->ps->fd.saberAnimLevel == SS_DUAL ) - { + } else if (pm->ps->fd.saberAnimLevel == SS_DUAL) { anim = BOTH_S1_S6; } - } - else if ( newMove == LS_PUTAWAY ) - { - saberInfo_t *saber1 = BG_MySaber( pm->ps->clientNum, 0 ); - saberInfo_t *saber2 = BG_MySaber( pm->ps->clientNum, 1 ); - if ( saber1 - && saber1->putawayAnim != -1 ) - { + } else if (newMove == LS_PUTAWAY) { + saberInfo_t *saber1 = BG_MySaber(pm->ps->clientNum, 0); + saberInfo_t *saber2 = BG_MySaber(pm->ps->clientNum, 1); + if (saber1 && saber1->putawayAnim != -1) { anim = saber1->putawayAnim; - } - else if ( saber2 - && saber2->putawayAnim != -1 ) - { + } else if (saber2 && saber2->putawayAnim != -1) { anim = saber2->putawayAnim; - } - else if ( pm->ps->fd.saberAnimLevel == SS_STAFF ) - { + } else if (pm->ps->fd.saberAnimLevel == SS_STAFF) { anim = BOTH_S7_S1; - } - else if ( pm->ps->fd.saberAnimLevel == SS_DUAL ) - { + } else if (pm->ps->fd.saberAnimLevel == SS_DUAL) { anim = BOTH_S6_S1; } - } - else if ( pm->ps->fd.saberAnimLevel == SS_STAFF && newMove >= LS_S_TL2BR && newMove < LS_REFLECT_LL ) - {//staff has an entirely new set of anims, besides special attacks - //FIXME: include ready and draw/putaway? - //FIXME: get hand-made bounces and deflections? - if ( newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL ) - {//there aren't 1-7, just 1, 6 and 7, so just set it - anim = BOTH_P7_S7_T_ + (anim-BOTH_P1_S1_T_);//shift it up to the proper set - } - else - {//add the appropriate animLevel - anim += (pm->ps->fd.saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; - } - } - else if ( pm->ps->fd.saberAnimLevel == SS_DUAL && newMove >= LS_S_TL2BR && newMove < LS_REFLECT_LL ) - { //akimbo has an entirely new set of anims, besides special attacks - //FIXME: include ready and draw/putaway? - //FIXME: get hand-made bounces and deflections? - if ( newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL ) - {//there aren't 1-7, just 1, 6 and 7, so just set it - anim = BOTH_P6_S6_T_ + (anim-BOTH_P1_S1_T_);//shift it up to the proper set - } - else - {//add the appropriate animLevel - anim += (pm->ps->fd.saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + } else if (pm->ps->fd.saberAnimLevel == SS_STAFF && newMove >= LS_S_TL2BR && + newMove < LS_REFLECT_LL) { // staff has an entirely new set of anims, besides special attacks + // FIXME: include ready and draw/putaway? + // FIXME: get hand-made bounces and deflections? + if (newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL) { // there aren't 1-7, just 1, 6 and 7, so just set it + anim = BOTH_P7_S7_T_ + (anim - BOTH_P1_S1_T_); // shift it up to the proper set + } else { // add the appropriate animLevel + anim += (pm->ps->fd.saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + } + } else if (pm->ps->fd.saberAnimLevel == SS_DUAL && newMove >= LS_S_TL2BR && + newMove < LS_REFLECT_LL) { // akimbo has an entirely new set of anims, besides special attacks + // FIXME: include ready and draw/putaway? + // FIXME: get hand-made bounces and deflections? + if (newMove >= LS_V1_BR && newMove <= LS_REFLECT_LL) { // there aren't 1-7, just 1, 6 and 7, so just set it + anim = BOTH_P6_S6_T_ + (anim - BOTH_P1_S1_T_); // shift it up to the proper set + } else { // add the appropriate animLevel + anim += (pm->ps->fd.saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; } } /* @@ -3806,23 +3030,20 @@ void PM_SetSaberMove(short newMove) anim = BOTH_SABERSTAFF_STANCE; } */ - else if ( pm->ps->fd.saberAnimLevel > FORCE_LEVEL_1 && - !BG_SaberInIdle( newMove ) && !PM_SaberInParry( newMove ) && !PM_SaberInKnockaway( newMove ) && !PM_SaberInBrokenParry( newMove ) && !PM_SaberInReflect( newMove ) && !BG_SaberInSpecial(newMove)) - {//readies, parries and reflections have only 1 level - anim += (pm->ps->fd.saberAnimLevel-FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; + else if (pm->ps->fd.saberAnimLevel > FORCE_LEVEL_1 && !BG_SaberInIdle(newMove) && !PM_SaberInParry(newMove) && !PM_SaberInKnockaway(newMove) && + !PM_SaberInBrokenParry(newMove) && !PM_SaberInReflect(newMove) && + !BG_SaberInSpecial(newMove)) { // readies, parries and reflections have only 1 level + anim += (pm->ps->fd.saberAnimLevel - FORCE_LEVEL_1) * SABER_ANIM_GROUP_SIZE; } // If the move does the same animation as the last one, we need to force a restart... - if ( saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) - { + if (saberMoveData[pm->ps->saberMove].animToUse == anim && newMove > LS_PUTAWAY) { setflags |= SETANIM_FLAG_RESTART; } - //saber torso anims should always be highest priority (4/12/02 - for special anims only) - if (!pm->ps->m_iVehicleNum) - { //if not riding a vehicle - if (BG_SaberInSpecial(newMove)) - { + // saber torso anims should always be highest priority (4/12/02 - for special anims only) + if (!pm->ps->m_iVehicleNum) { // if not riding a vehicle + if (BG_SaberInSpecial(newMove)) { setflags |= SETANIM_FLAG_OVERRIDE; } /* @@ -3840,147 +3061,84 @@ void PM_SetSaberMove(short newMove) } */ } - if ( BG_InSaberStandAnim(anim) || anim == BOTH_STAND1 ) - { + if (BG_InSaberStandAnim(anim) || anim == BOTH_STAND1) { anim = (pm->ps->legsAnim); if ((anim >= BOTH_STAND1 && anim <= BOTH_STAND4TOATTACK2) || - (anim >= TORSO_DROPWEAP1 && anim <= TORSO_WEAPONIDLE10)) - { //If standing then use the special saber stand anim + (anim >= TORSO_DROPWEAP1 && anim <= TORSO_WEAPONIDLE10)) { // If standing then use the special saber stand anim anim = PM_GetSaberStance(); } - if (pm->ps->pm_flags & PMF_DUCKED) - { //Playing torso walk anims while crouched makes you look like a monkey + if (pm->ps->pm_flags & PMF_DUCKED) { // Playing torso walk anims while crouched makes you look like a monkey anim = PM_GetSaberStance(); } - if (anim == BOTH_WALKBACK1 || anim == BOTH_WALKBACK2 || anim == BOTH_WALK1) - { //normal stance when walking backward so saber doesn't look like it's cutting through leg + if (anim == BOTH_WALKBACK1 || anim == BOTH_WALKBACK2 || + anim == BOTH_WALK1) { // normal stance when walking backward so saber doesn't look like it's cutting through leg anim = PM_GetSaberStance(); } - if (BG_InSlopeAnim( anim )) - { + if (BG_InSlopeAnim(anim)) { anim = PM_GetSaberStance(); } parts = SETANIM_TORSO; } - if (!pm->ps->m_iVehicleNum) - { //if not riding a vehicle - if (newMove == LS_JUMPATTACK_ARIAL_RIGHT || - newMove == LS_JUMPATTACK_ARIAL_LEFT) - { //force only on legs + if (!pm->ps->m_iVehicleNum) { // if not riding a vehicle + if (newMove == LS_JUMPATTACK_ARIAL_RIGHT || newMove == LS_JUMPATTACK_ARIAL_LEFT) { // force only on legs parts = SETANIM_LEGS; - } - else if ( newMove == LS_A_LUNGE - || newMove == LS_A_JUMP_T__B_ - || newMove == LS_A_BACKSTAB - || newMove == LS_A_BACK - || newMove == LS_A_BACK_CR - || newMove == LS_ROLL_STAB - || newMove == LS_A_FLIP_STAB - || newMove == LS_A_FLIP_SLASH - || newMove == LS_JUMPATTACK_DUAL - || newMove == LS_JUMPATTACK_ARIAL_LEFT - || newMove == LS_JUMPATTACK_ARIAL_RIGHT - || newMove == LS_JUMPATTACK_CART_LEFT - || newMove == LS_JUMPATTACK_CART_RIGHT - || newMove == LS_JUMPATTACK_STAFF_LEFT - || newMove == LS_JUMPATTACK_STAFF_RIGHT - || newMove == LS_A_BACKFLIP_ATK - || newMove == LS_STABDOWN - || newMove == LS_STABDOWN_STAFF - || newMove == LS_STABDOWN_DUAL - || newMove == LS_DUAL_SPIN_PROTECT - || newMove == LS_STAFF_SOULCAL - || newMove == LS_A1_SPECIAL - || newMove == LS_A2_SPECIAL - || newMove == LS_A3_SPECIAL - || newMove == LS_UPSIDE_DOWN_ATTACK - || newMove == LS_PULL_ATTACK_STAB - || newMove == LS_PULL_ATTACK_SWING - || BG_KickMove( newMove ) ) - { + } else if (newMove == LS_A_LUNGE || newMove == LS_A_JUMP_T__B_ || newMove == LS_A_BACKSTAB || newMove == LS_A_BACK || newMove == LS_A_BACK_CR || + newMove == LS_ROLL_STAB || newMove == LS_A_FLIP_STAB || newMove == LS_A_FLIP_SLASH || newMove == LS_JUMPATTACK_DUAL || + newMove == LS_JUMPATTACK_ARIAL_LEFT || newMove == LS_JUMPATTACK_ARIAL_RIGHT || newMove == LS_JUMPATTACK_CART_LEFT || + newMove == LS_JUMPATTACK_CART_RIGHT || newMove == LS_JUMPATTACK_STAFF_LEFT || newMove == LS_JUMPATTACK_STAFF_RIGHT || + newMove == LS_A_BACKFLIP_ATK || newMove == LS_STABDOWN || newMove == LS_STABDOWN_STAFF || newMove == LS_STABDOWN_DUAL || + newMove == LS_DUAL_SPIN_PROTECT || newMove == LS_STAFF_SOULCAL || newMove == LS_A1_SPECIAL || newMove == LS_A2_SPECIAL || + newMove == LS_A3_SPECIAL || newMove == LS_UPSIDE_DOWN_ATTACK || newMove == LS_PULL_ATTACK_STAB || newMove == LS_PULL_ATTACK_SWING || + BG_KickMove(newMove)) { parts = SETANIM_BOTH; - } - else if ( BG_SpinningSaberAnim( anim ) ) - {//spins must be played on entire body + } else if (BG_SpinningSaberAnim(anim)) { // spins must be played on entire body parts = SETANIM_BOTH; - } - else if ( (!pm->cmd.forwardmove&&!pm->cmd.rightmove&&!pm->cmd.upmove)) - {//not trying to run, duck or jump - if ( !BG_FlippingAnim( pm->ps->legsAnim ) && - !BG_InRoll( pm->ps, pm->ps->legsAnim ) && - !PM_InKnockDown( pm->ps ) && - !PM_JumpingAnim( pm->ps->legsAnim ) && - !BG_InSpecialJump( pm->ps->legsAnim ) && - anim != PM_GetSaberStance() && - pm->ps->groundEntityNum != ENTITYNUM_NONE && - !(pm->ps->pm_flags & PMF_DUCKED)) - { + } else if ((!pm->cmd.forwardmove && !pm->cmd.rightmove && !pm->cmd.upmove)) { // not trying to run, duck or jump + if (!BG_FlippingAnim(pm->ps->legsAnim) && !BG_InRoll(pm->ps, pm->ps->legsAnim) && !PM_InKnockDown(pm->ps) && !PM_JumpingAnim(pm->ps->legsAnim) && + !BG_InSpecialJump(pm->ps->legsAnim) && anim != PM_GetSaberStance() && pm->ps->groundEntityNum != ENTITYNUM_NONE && + !(pm->ps->pm_flags & PMF_DUCKED)) { parts = SETANIM_BOTH; - } - else if ( !(pm->ps->pm_flags & PMF_DUCKED) - && ( newMove == LS_SPINATTACK_DUAL || newMove == LS_SPINATTACK ) ) - { + } else if (!(pm->ps->pm_flags & PMF_DUCKED) && (newMove == LS_SPINATTACK_DUAL || newMove == LS_SPINATTACK)) { parts = SETANIM_BOTH; } } PM_SetAnim(parts, anim, setflags); - if (parts != SETANIM_LEGS && - (pm->ps->legsAnim == BOTH_ARIAL_LEFT || - pm->ps->legsAnim == BOTH_ARIAL_RIGHT)) - { - if (pm->ps->legsTimer > pm->ps->torsoTimer) - { + if (parts != SETANIM_LEGS && (pm->ps->legsAnim == BOTH_ARIAL_LEFT || pm->ps->legsAnim == BOTH_ARIAL_RIGHT)) { + if (pm->ps->legsTimer > pm->ps->torsoTimer) { pm->ps->legsTimer = pm->ps->torsoTimer; } } - } - if ( (pm->ps->torsoAnim) == anim ) - {//successfully changed anims - //special check for *starting* a saber swing - //playing at attack - if ( BG_SaberInAttack( newMove ) || BG_SaberInSpecialAttack( anim ) ) - { - if ( pm->ps->saberMove != newMove ) - {//wasn't playing that attack before - if ( newMove != LS_KICK_F - && newMove != LS_KICK_B - && newMove != LS_KICK_R - && newMove != LS_KICK_L - && newMove != LS_KICK_F_AIR - && newMove != LS_KICK_B_AIR - && newMove != LS_KICK_R_AIR - && newMove != LS_KICK_L_AIR ) - { - PM_AddEvent(EV_SABER_ATTACK); + if ((pm->ps->torsoAnim) == anim) { // successfully changed anims + // special check for *starting* a saber swing + // playing at attack + if (BG_SaberInAttack(newMove) || BG_SaberInSpecialAttack(anim)) { + if (pm->ps->saberMove != newMove) { // wasn't playing that attack before + if (newMove != LS_KICK_F && newMove != LS_KICK_B && newMove != LS_KICK_R && newMove != LS_KICK_L && newMove != LS_KICK_F_AIR && + newMove != LS_KICK_B_AIR && newMove != LS_KICK_R_AIR && newMove != LS_KICK_L_AIR) { + PM_AddEvent(EV_SABER_ATTACK); } - if (pm->ps->brokenLimbs) - { //randomly make pain sounds with a broken arm because we are suffering. + if (pm->ps->brokenLimbs) { // randomly make pain sounds with a broken arm because we are suffering. int iFactor = -1; - if (pm->ps->brokenLimbs & (1<ps->brokenLimbs & (1 << BROKENLIMB_RARM)) { // You're using it more. So it hurts more. iFactor = 5; - } - else if (pm->ps->brokenLimbs & (1<ps->brokenLimbs & (1 << BROKENLIMB_LARM)) { iFactor = 10; } - if (iFactor != -1) - { - if ( !PM_irand_timesync( 0, iFactor ) ) - { - BG_AddPredictableEventToPlayerstate(EV_PAIN, PM_irand_timesync( 1, 100 ), pm->ps); + if (iFactor != -1) { + if (!PM_irand_timesync(0, iFactor)) { + BG_AddPredictableEventToPlayerstate(EV_PAIN, PM_irand_timesync(1, 100), pm->ps); } } } @@ -3988,8 +3146,8 @@ void PM_SetSaberMove(short newMove) } if (BG_SaberInSpecial(newMove) && - pm->ps->weaponTime < pm->ps->torsoTimer) - { //rww 01-02-03 - I think this will solve the issue of special attacks being interruptable, hopefully without side effects + pm->ps->weaponTime < + pm->ps->torsoTimer) { // rww 01-02-03 - I think this will solve the issue of special attacks being interruptable, hopefully without side effects pm->ps->weaponTime = pm->ps->torsoTimer; } @@ -3998,45 +3156,34 @@ void PM_SetSaberMove(short newMove) pm->ps->torsoAnim = anim; - if (pm->ps->weaponTime <= 0) - { + if (pm->ps->weaponTime <= 0) { pm->ps->saberBlocked = BLOCKED_NONE; } } } -saberInfo_t *BG_MySaber( int clientNum, int saberNum ) -{ - //returns a pointer to the requested saberNum +saberInfo_t *BG_MySaber(int clientNum, int saberNum) { + // returns a pointer to the requested saberNum #ifdef _GAME gentity_t *ent = &g_entities[clientNum]; - if ( ent->inuse && ent->client ) - { - if ( !ent->client->saber[saberNum].model[0] ) - { //don't have saber anymore! + if (ent->inuse && ent->client) { + if (!ent->client->saber[saberNum].model[0]) { // don't have saber anymore! return NULL; } return &ent->client->saber[saberNum]; } #elif defined(_CGAME) clientInfo_t *ci = NULL; - if (clientNum < MAX_CLIENTS) - { + if (clientNum < MAX_CLIENTS) { ci = &cgs.clientinfo[clientNum]; - } - else - { + } else { centity_t *cent = &cg_entities[clientNum]; - if (cent->npcClient) - { + if (cent->npcClient) { ci = cent->npcClient; } } - if ( ci - && ci->infoValid ) - { - if ( !ci->saber[saberNum].model[0] ) - { //don't have sabers anymore! + if (ci && ci->infoValid) { + if (!ci->saber[saberNum].model[0]) { // don't have sabers anymore! return NULL; } return &ci->saber[saberNum]; @@ -4045,4 +3192,3 @@ saberInfo_t *BG_MySaber( int clientNum, int saberNum ) return NULL; } - diff --git a/codemp/game/bg_saberLoad.c b/codemp/game/bg_saberLoad.c index ae7460dc1c..551d16f642 100644 --- a/codemp/game/bg_saberLoad.c +++ b/codemp/game/bg_saberLoad.c @@ -29,135 +29,131 @@ along with this program; if not, see . #include "w_saber.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif -extern stringID_table_t animTable[MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; -int BG_SoundIndex( const char *sound ) { +int BG_SoundIndex(const char *sound) { #ifdef _GAME - return G_SoundIndex( sound ); + return G_SoundIndex(sound); #elif defined(_CGAME) || defined(UI_BUILD) - return trap->S_RegisterSound( sound ); + return trap->S_RegisterSound(sound); #endif } extern stringID_table_t FPTable[]; -#define MAX_SABER_DATA_SIZE (1024*1024) // 1mb, was 512kb +#define MAX_SABER_DATA_SIZE (1024 * 1024) // 1mb, was 512kb static char saberParms[MAX_SABER_DATA_SIZE]; -stringID_table_t saberTable[] = { - ENUM2STRING( SABER_NONE ), - ENUM2STRING( SABER_SINGLE ), - ENUM2STRING( SABER_STAFF ), - ENUM2STRING( SABER_BROAD ), - ENUM2STRING( SABER_PRONG ), - ENUM2STRING( SABER_DAGGER ), - ENUM2STRING( SABER_ARC ), - ENUM2STRING( SABER_SAI ), - ENUM2STRING( SABER_CLAW ), - ENUM2STRING( SABER_LANCE ), - ENUM2STRING( SABER_STAR ), - ENUM2STRING( SABER_TRIDENT ), - { "", -1 } -}; - -stringID_table_t saberMoveTable[] = { - ENUM2STRING( LS_NONE ), - // Attacks - ENUM2STRING( LS_A_TL2BR ), - ENUM2STRING( LS_A_L2R ), - ENUM2STRING( LS_A_BL2TR ), - ENUM2STRING( LS_A_BR2TL ), - ENUM2STRING( LS_A_R2L ), - ENUM2STRING( LS_A_TR2BL ), - ENUM2STRING( LS_A_T2B ), - ENUM2STRING( LS_A_BACKSTAB ), - ENUM2STRING( LS_A_BACK ), - ENUM2STRING( LS_A_BACK_CR ), - ENUM2STRING( LS_ROLL_STAB ), - ENUM2STRING( LS_A_LUNGE ), - ENUM2STRING( LS_A_JUMP_T__B_ ), - ENUM2STRING( LS_A_FLIP_STAB ), - ENUM2STRING( LS_A_FLIP_SLASH ), - ENUM2STRING( LS_JUMPATTACK_DUAL ), - ENUM2STRING( LS_JUMPATTACK_ARIAL_LEFT ), - ENUM2STRING( LS_JUMPATTACK_ARIAL_RIGHT ), - ENUM2STRING( LS_JUMPATTACK_CART_LEFT ), - ENUM2STRING( LS_JUMPATTACK_CART_RIGHT ), - ENUM2STRING( LS_JUMPATTACK_STAFF_LEFT ), - ENUM2STRING( LS_JUMPATTACK_STAFF_RIGHT ), - ENUM2STRING( LS_BUTTERFLY_LEFT ), - ENUM2STRING( LS_BUTTERFLY_RIGHT ), - ENUM2STRING( LS_A_BACKFLIP_ATK ), - ENUM2STRING( LS_SPINATTACK_DUAL ), - ENUM2STRING( LS_SPINATTACK ), - ENUM2STRING( LS_LEAP_ATTACK ), - ENUM2STRING( LS_SWOOP_ATTACK_RIGHT ), - ENUM2STRING( LS_SWOOP_ATTACK_LEFT ), - ENUM2STRING( LS_TAUNTAUN_ATTACK_RIGHT ), - ENUM2STRING( LS_TAUNTAUN_ATTACK_LEFT ), - ENUM2STRING( LS_KICK_F ), - ENUM2STRING( LS_KICK_B ), - ENUM2STRING( LS_KICK_R ), - ENUM2STRING( LS_KICK_L ), - ENUM2STRING( LS_KICK_S ), - ENUM2STRING( LS_KICK_BF ), - ENUM2STRING( LS_KICK_RL ), - ENUM2STRING( LS_KICK_F_AIR ), - ENUM2STRING( LS_KICK_B_AIR ), - ENUM2STRING( LS_KICK_R_AIR ), - ENUM2STRING( LS_KICK_L_AIR ), - ENUM2STRING( LS_STABDOWN ), - ENUM2STRING( LS_STABDOWN_STAFF ), - ENUM2STRING( LS_STABDOWN_DUAL ), - ENUM2STRING( LS_DUAL_SPIN_PROTECT ), - ENUM2STRING( LS_STAFF_SOULCAL ), - ENUM2STRING( LS_A1_SPECIAL ), - ENUM2STRING( LS_A2_SPECIAL ), - ENUM2STRING( LS_A3_SPECIAL ), - ENUM2STRING( LS_UPSIDE_DOWN_ATTACK ), - ENUM2STRING( LS_PULL_ATTACK_STAB ), - ENUM2STRING( LS_PULL_ATTACK_SWING ), - ENUM2STRING( LS_SPINATTACK_ALORA ), - ENUM2STRING( LS_DUAL_FB ), - ENUM2STRING( LS_DUAL_LR ), - ENUM2STRING( LS_HILT_BASH ), - { "", -1 } -}; - -//Also used in npc code -qboolean BG_ParseLiteral( const char **data, const char *string ) { +stringID_table_t saberTable[] = {ENUM2STRING(SABER_NONE), + ENUM2STRING(SABER_SINGLE), + ENUM2STRING(SABER_STAFF), + ENUM2STRING(SABER_BROAD), + ENUM2STRING(SABER_PRONG), + ENUM2STRING(SABER_DAGGER), + ENUM2STRING(SABER_ARC), + ENUM2STRING(SABER_SAI), + ENUM2STRING(SABER_CLAW), + ENUM2STRING(SABER_LANCE), + ENUM2STRING(SABER_STAR), + ENUM2STRING(SABER_TRIDENT), + {"", -1}}; + +stringID_table_t saberMoveTable[] = {ENUM2STRING(LS_NONE), + // Attacks + ENUM2STRING(LS_A_TL2BR), + ENUM2STRING(LS_A_L2R), + ENUM2STRING(LS_A_BL2TR), + ENUM2STRING(LS_A_BR2TL), + ENUM2STRING(LS_A_R2L), + ENUM2STRING(LS_A_TR2BL), + ENUM2STRING(LS_A_T2B), + ENUM2STRING(LS_A_BACKSTAB), + ENUM2STRING(LS_A_BACK), + ENUM2STRING(LS_A_BACK_CR), + ENUM2STRING(LS_ROLL_STAB), + ENUM2STRING(LS_A_LUNGE), + ENUM2STRING(LS_A_JUMP_T__B_), + ENUM2STRING(LS_A_FLIP_STAB), + ENUM2STRING(LS_A_FLIP_SLASH), + ENUM2STRING(LS_JUMPATTACK_DUAL), + ENUM2STRING(LS_JUMPATTACK_ARIAL_LEFT), + ENUM2STRING(LS_JUMPATTACK_ARIAL_RIGHT), + ENUM2STRING(LS_JUMPATTACK_CART_LEFT), + ENUM2STRING(LS_JUMPATTACK_CART_RIGHT), + ENUM2STRING(LS_JUMPATTACK_STAFF_LEFT), + ENUM2STRING(LS_JUMPATTACK_STAFF_RIGHT), + ENUM2STRING(LS_BUTTERFLY_LEFT), + ENUM2STRING(LS_BUTTERFLY_RIGHT), + ENUM2STRING(LS_A_BACKFLIP_ATK), + ENUM2STRING(LS_SPINATTACK_DUAL), + ENUM2STRING(LS_SPINATTACK), + ENUM2STRING(LS_LEAP_ATTACK), + ENUM2STRING(LS_SWOOP_ATTACK_RIGHT), + ENUM2STRING(LS_SWOOP_ATTACK_LEFT), + ENUM2STRING(LS_TAUNTAUN_ATTACK_RIGHT), + ENUM2STRING(LS_TAUNTAUN_ATTACK_LEFT), + ENUM2STRING(LS_KICK_F), + ENUM2STRING(LS_KICK_B), + ENUM2STRING(LS_KICK_R), + ENUM2STRING(LS_KICK_L), + ENUM2STRING(LS_KICK_S), + ENUM2STRING(LS_KICK_BF), + ENUM2STRING(LS_KICK_RL), + ENUM2STRING(LS_KICK_F_AIR), + ENUM2STRING(LS_KICK_B_AIR), + ENUM2STRING(LS_KICK_R_AIR), + ENUM2STRING(LS_KICK_L_AIR), + ENUM2STRING(LS_STABDOWN), + ENUM2STRING(LS_STABDOWN_STAFF), + ENUM2STRING(LS_STABDOWN_DUAL), + ENUM2STRING(LS_DUAL_SPIN_PROTECT), + ENUM2STRING(LS_STAFF_SOULCAL), + ENUM2STRING(LS_A1_SPECIAL), + ENUM2STRING(LS_A2_SPECIAL), + ENUM2STRING(LS_A3_SPECIAL), + ENUM2STRING(LS_UPSIDE_DOWN_ATTACK), + ENUM2STRING(LS_PULL_ATTACK_STAB), + ENUM2STRING(LS_PULL_ATTACK_SWING), + ENUM2STRING(LS_SPINATTACK_ALORA), + ENUM2STRING(LS_DUAL_FB), + ENUM2STRING(LS_DUAL_LR), + ENUM2STRING(LS_HILT_BASH), + {"", -1}}; + +// Also used in npc code +qboolean BG_ParseLiteral(const char **data, const char *string) { const char *token; - token = COM_ParseExt( data, qtrue ); - if ( !token[0] ) { - Com_Printf( "unexpected EOF\n" ); + token = COM_ParseExt(data, qtrue); + if (!token[0]) { + Com_Printf("unexpected EOF\n"); return qtrue; } - if ( Q_stricmp( token, string ) ) { - Com_Printf( "required string '%s' missing\n", string ); + if (Q_stricmp(token, string)) { + Com_Printf("required string '%s' missing\n", string); return qtrue; } return qfalse; } -qboolean BG_ParseLiteralSilent( const char **data, const char *string ) { +qboolean BG_ParseLiteralSilent(const char **data, const char *string) { const char *token; - token = COM_ParseExt( data, qtrue ); - if ( !token[0] ) { + token = COM_ParseExt(data, qtrue); + if (!token[0]) { return qtrue; } - if ( Q_stricmp( token, string ) ) { + if (Q_stricmp(token, string)) { return qtrue; } @@ -165,160 +161,182 @@ qboolean BG_ParseLiteralSilent( const char **data, const char *string ) { return qfalse; } -saber_colors_t TranslateSaberColor( const char *name ) { - if ( !Q_stricmp( name, "red" ) ) +saber_colors_t TranslateSaberColor(const char *name) { + if (!Q_stricmp(name, "red")) return SABER_RED; - if ( !Q_stricmp( name, "orange" ) ) + if (!Q_stricmp(name, "orange")) return SABER_ORANGE; - if ( !Q_stricmp( name, "yellow" ) ) + if (!Q_stricmp(name, "yellow")) return SABER_YELLOW; - if ( !Q_stricmp( name, "green" ) ) + if (!Q_stricmp(name, "green")) return SABER_GREEN; - if ( !Q_stricmp( name, "blue" ) ) + if (!Q_stricmp(name, "blue")) return SABER_BLUE; - if ( !Q_stricmp( name, "purple" ) ) + if (!Q_stricmp(name, "purple")) return SABER_PURPLE; - if ( !Q_stricmp( name, "random" ) ) - return (saber_colors_t)Q_irand( SABER_ORANGE, SABER_PURPLE ); + if (!Q_stricmp(name, "random")) + return (saber_colors_t)Q_irand(SABER_ORANGE, SABER_PURPLE); return SABER_BLUE; } -const char *SaberColorToString( saber_colors_t color ) { - if ( color == SABER_RED ) return "red"; - if ( color == SABER_ORANGE ) return "orange"; - if ( color == SABER_YELLOW ) return "yellow"; - if ( color == SABER_GREEN ) return "green"; - if ( color == SABER_BLUE ) return "blue"; - if ( color == SABER_PURPLE ) return "purple"; +const char *SaberColorToString(saber_colors_t color) { + if (color == SABER_RED) + return "red"; + if (color == SABER_ORANGE) + return "orange"; + if (color == SABER_YELLOW) + return "yellow"; + if (color == SABER_GREEN) + return "green"; + if (color == SABER_BLUE) + return "blue"; + if (color == SABER_PURPLE) + return "purple"; return NULL; } -saber_styles_t TranslateSaberStyle( const char *name ) { - if ( !Q_stricmp( name, "fast" ) ) return SS_FAST; - if ( !Q_stricmp( name, "medium" ) ) return SS_MEDIUM; - if ( !Q_stricmp( name, "strong" ) ) return SS_STRONG; - if ( !Q_stricmp( name, "desann" ) ) return SS_DESANN; - if ( !Q_stricmp( name, "tavion" ) ) return SS_TAVION; - if ( !Q_stricmp( name, "dual" ) ) return SS_DUAL; - if ( !Q_stricmp( name, "staff" ) ) return SS_STAFF; +saber_styles_t TranslateSaberStyle(const char *name) { + if (!Q_stricmp(name, "fast")) + return SS_FAST; + if (!Q_stricmp(name, "medium")) + return SS_MEDIUM; + if (!Q_stricmp(name, "strong")) + return SS_STRONG; + if (!Q_stricmp(name, "desann")) + return SS_DESANN; + if (!Q_stricmp(name, "tavion")) + return SS_TAVION; + if (!Q_stricmp(name, "dual")) + return SS_DUAL; + if (!Q_stricmp(name, "staff")) + return SS_STAFF; return SS_NONE; } -saberType_t TranslateSaberType( const char *name ) { - if ( !Q_stricmp( name, "SABER_SINGLE" ) ) return SABER_SINGLE; - if ( !Q_stricmp( name, "SABER_STAFF" ) ) return SABER_STAFF; - if ( !Q_stricmp( name, "SABER_DAGGER" ) ) return SABER_DAGGER; - if ( !Q_stricmp( name, "SABER_BROAD" ) ) return SABER_BROAD; - if ( !Q_stricmp( name, "SABER_PRONG" ) ) return SABER_PRONG; - if ( !Q_stricmp( name, "SABER_ARC" ) ) return SABER_ARC; - if ( !Q_stricmp( name, "SABER_SAI" ) ) return SABER_SAI; - if ( !Q_stricmp( name, "SABER_CLAW" ) ) return SABER_CLAW; - if ( !Q_stricmp( name, "SABER_LANCE" ) ) return SABER_LANCE; - if ( !Q_stricmp( name, "SABER_STAR" ) ) return SABER_STAR; - if ( !Q_stricmp( name, "SABER_TRIDENT" ) ) return SABER_TRIDENT; - if ( !Q_stricmp( name, "SABER_SITH_SWORD" ) ) return SABER_SITH_SWORD; +saberType_t TranslateSaberType(const char *name) { + if (!Q_stricmp(name, "SABER_SINGLE")) + return SABER_SINGLE; + if (!Q_stricmp(name, "SABER_STAFF")) + return SABER_STAFF; + if (!Q_stricmp(name, "SABER_DAGGER")) + return SABER_DAGGER; + if (!Q_stricmp(name, "SABER_BROAD")) + return SABER_BROAD; + if (!Q_stricmp(name, "SABER_PRONG")) + return SABER_PRONG; + if (!Q_stricmp(name, "SABER_ARC")) + return SABER_ARC; + if (!Q_stricmp(name, "SABER_SAI")) + return SABER_SAI; + if (!Q_stricmp(name, "SABER_CLAW")) + return SABER_CLAW; + if (!Q_stricmp(name, "SABER_LANCE")) + return SABER_LANCE; + if (!Q_stricmp(name, "SABER_STAR")) + return SABER_STAR; + if (!Q_stricmp(name, "SABER_TRIDENT")) + return SABER_TRIDENT; + if (!Q_stricmp(name, "SABER_SITH_SWORD")) + return SABER_SITH_SWORD; return SABER_SINGLE; } -qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ) { - if ( saber - && saber->bladeStyle2Start > 0 - && bladeNum >= saber->bladeStyle2Start ) +qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum) { + if (saber && saber->bladeStyle2Start > 0 && bladeNum >= saber->bladeStyle2Start) return qtrue; return qfalse; } -qboolean WP_SaberBladeDoTransitionDamage( saberInfo_t *saber, int bladeNum ) { - //use first blade style for this blade - if ( !WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE) ) +qboolean WP_SaberBladeDoTransitionDamage(saberInfo_t *saber, int bladeNum) { + // use first blade style for this blade + if (!WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE)) return qtrue; - //use second blade style for this blade - else if ( WP_SaberBladeUseSecondBladeStyle( saber, bladeNum ) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE2) ) + // use second blade style for this blade + else if (WP_SaberBladeUseSecondBladeStyle(saber, bladeNum) && (saber->saberFlags2 & SFL2_TRANSITION_DAMAGE2)) return qtrue; return qfalse; } -qboolean WP_UseFirstValidSaberStyle( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel ) { +qboolean WP_UseFirstValidSaberStyle(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel) { qboolean styleInvalid = qfalse; qboolean saber1Active, saber2Active; qboolean dualSabers = qfalse; - int validStyles=0, styleNum; + int validStyles = 0, styleNum; - if ( saber2 && saber2->model[0] ) + if (saber2 && saber2->model[0]) dualSabers = qtrue; - //dual - if ( dualSabers ) { - if ( saberHolstered > 1 ) + // dual + if (dualSabers) { + if (saberHolstered > 1) saber1Active = saber2Active = qfalse; - else if ( saberHolstered > 0 ) { + else if (saberHolstered > 0) { saber1Active = qtrue; saber2Active = qfalse; - } - else + } else saber1Active = saber2Active = qtrue; } // single/staff else { saber2Active = qfalse; - if ( !saber1 || !saber1->model[0] ) + if (!saber1 || !saber1->model[0]) saber1Active = qfalse; - //staff - else if ( saber1->numBlades > 1 ) { - if ( saberHolstered > 1 ) + // staff + else if (saber1->numBlades > 1) { + if (saberHolstered > 1) saber1Active = qfalse; else saber1Active = qtrue; } - //single + // single else { - if ( saberHolstered ) + if (saberHolstered) saber1Active = qfalse; else saber1Active = qtrue; } } - //initially, all styles are valid - validStyles = (1<model[0] && saber1->stylesForbidden ) { - if ( (saber1->stylesForbidden & (1<<*saberAnimLevel)) ) { - //not a valid style for first saber! + if (saber1Active && saber1 && saber1->model[0] && saber1->stylesForbidden) { + if ((saber1->stylesForbidden & (1 << *saberAnimLevel))) { + // not a valid style for first saber! styleInvalid = qtrue; validStyles &= ~saber1->stylesForbidden; } } - if ( dualSabers ) { - if ( saber2Active && saber2->stylesForbidden ) { - if ( (saber2->stylesForbidden & (1<<*saberAnimLevel)) ) { - //not a valid style for second saber! + if (dualSabers) { + if (saber2Active && saber2->stylesForbidden) { + if ((saber2->stylesForbidden & (1 << *saberAnimLevel))) { + // not a valid style for second saber! styleInvalid = qtrue; - //only the ones both sabers allow is valid + // only the ones both sabers allow is valid validStyles &= ~saber2->stylesForbidden; } } } - if ( !validStyles ) { - if ( dualSabers ) - Com_Printf( "WARNING: No valid saber styles for %s/%s", saber1->name, saber2->name ); + if (!validStyles) { + if (dualSabers) + Com_Printf("WARNING: No valid saber styles for %s/%s", saber1->name, saber2->name); else - Com_Printf( "WARNING: No valid saber styles for %s", saber1->name ); + Com_Printf("WARNING: No valid saber styles for %s", saber1->name); } - //using an invalid style and have at least one valid style to use, so switch to it - else if ( styleInvalid ) { - for ( styleNum=SS_FAST; styleNummodel[0] ) + if (saber2 && saber2->model[0]) dualSabers = qtrue; - if ( dualSabers ) { - if ( saberHolstered > 1 ) + if (dualSabers) { + if (saberHolstered > 1) saber1Active = saber2Active = qfalse; - else if ( saberHolstered > 0 ) { + else if (saberHolstered > 0) { saber1Active = qtrue; saber2Active = qfalse; - } - else + } else saber1Active = saber2Active = qtrue; - } - else { + } else { saber2Active = qfalse; - if ( !saber1 || !saber1->model[0] ) + if (!saber1 || !saber1->model[0]) saber1Active = qfalse; - //staff - else if ( saber1->numBlades > 1 ) - saber1Active = (saberHolstered>1) ? qfalse : qtrue; + // staff + else if (saber1->numBlades > 1) + saber1Active = (saberHolstered > 1) ? qfalse : qtrue; - //single + // single else saber1Active = saberHolstered ? qfalse : qtrue; } - if ( saber1Active && saber1 && saber1->model[0] && saber1->stylesForbidden ) { - if ( (saber1->stylesForbidden & (1<model[0] && saber1->stylesForbidden) { + if ((saber1->stylesForbidden & (1 << saberAnimLevel))) return qfalse; } - if ( dualSabers && saber2Active && saber2 && saber2->model[0] ) - { - if ( saber2->stylesForbidden ) { - if ( (saber2->stylesForbidden & (1<model[0]) { + if (saber2->stylesForbidden) { + if ((saber2->stylesForbidden & (1 << saberAnimLevel))) return qfalse; } - //now: if using dual sabers, only dual and tavion (if given with this saber) are allowed - if ( saberAnimLevel != SS_DUAL ) { - if ( saberAnimLevel != SS_TAVION ) + // now: if using dual sabers, only dual and tavion (if given with this saber) are allowed + if (saberAnimLevel != SS_DUAL) { + if (saberAnimLevel != SS_TAVION) return qfalse; else { - //see if "tavion" style is okay - if ( !(saber1Active && (saber1->stylesLearned & (1<stylesLearned & (1<stylesLearned & (1 << SS_TAVION))) || !(saber2->stylesLearned & (1 << SS_TAVION))) return qfalse; } } @@ -384,1419 +398,1419 @@ qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, i return qtrue; } -qboolean WP_SaberCanTurnOffSomeBlades( saberInfo_t *saber ) { - if ( saber->bladeStyle2Start > 0 && saber->numBlades > saber->bladeStyle2Start ) { +qboolean WP_SaberCanTurnOffSomeBlades(saberInfo_t *saber) { + if (saber->bladeStyle2Start > 0 && saber->numBlades > saber->bladeStyle2Start) { // check if all blades are always on - if ( (saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE) && (saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2) ) + if ((saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE) && (saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) return qfalse; - } - else { + } else { // check if all blades are always on - if ( (saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE) ) + if ((saber->saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) return qfalse; } - //you can turn some off + // you can turn some off return qtrue; } -void WP_SaberSetDefaults( saberInfo_t *saber ) { +void WP_SaberSetDefaults(saberInfo_t *saber) { int i; - //Set defaults so that, if it fails, there's at least something there - for ( i=0; iblade[i].color = SABER_RED; saber->blade[i].radius = SABER_RADIUS_STANDARD; saber->blade[i].lengthMax = 32; } - Q_strncpyz( saber->name, DEFAULT_SABER, sizeof( saber->name ) ); - Q_strncpyz( saber->fullName, "lightsaber", sizeof( saber->fullName ) ); - Q_strncpyz( saber->model, DEFAULT_SABER_MODEL, sizeof( saber->model ) ); - saber->skin = 0; - saber->soundOn = BG_SoundIndex( "sound/weapons/saber/enemy_saber_on.wav" ); - saber->soundLoop = BG_SoundIndex( "sound/weapons/saber/saberhum3.wav" ); - saber->soundOff = BG_SoundIndex( "sound/weapons/saber/enemy_saber_off.wav" ); - saber->numBlades = 1; - saber->type = SABER_SINGLE; - saber->stylesLearned = 0; - saber->stylesForbidden = 0; // allow all styles - saber->maxChain = 0; // 0 = use default behavior - saber->forceRestrictions = 0; - saber->lockBonus = 0; - saber->parryBonus = 0; - saber->breakParryBonus = 0; - saber->breakParryBonus2 = 0; - saber->disarmBonus = 0; - saber->disarmBonus2 = 0; - saber->singleBladeStyle = SS_NONE; // makes it so that you use a different style if you only have the first blade active - -//===NEW======================================================================================== - //done in cgame (client-side code) - saber->saberFlags = 0; // see all the SFL_ flags - saber->saberFlags2 = 0; // see all the SFL2_ flags - - saber->spinSound = 0; // none - if set, plays this sound as it spins when thrown - saber->swingSound[0] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - saber->swingSound[1] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - saber->swingSound[2] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! - - //done in game (server-side code) - saber->moveSpeedScale = 1.0f; // 1.0 - you move faster/slower when using this saber - saber->animSpeedScale = 1.0f; // 1.0 - plays normal attack animations faster/slower - - saber->kataMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time - saber->lungeAtkMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they crouch+fwd+attack - saber->jumpAtkUpMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+attack - saber->jumpAtkFwdMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+fwd+attack - saber->jumpAtkBackMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+back+attack - saber->jumpAtkRightMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+rightattack - saber->jumpAtkLeftMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+left+attack - saber->readyAnim = -1; // -1 - anim to use when standing idle - saber->drawAnim = -1; // -1 - anim to use when drawing weapon - saber->putawayAnim = -1; // -1 - anim to use when putting weapon away - saber->tauntAnim = -1; // -1 - anim to use when hit "taunt" - saber->bowAnim = -1; // -1 - anim to use when hit "bow" - saber->meditateAnim = -1; // -1 - anim to use when hit "meditate" - saber->flourishAnim = -1; // -1 - anim to use when hit "flourish" - saber->gloatAnim = -1; // -1 - anim to use when hit "gloat" - - //***NOTE: you can only have a maximum of 2 "styles" of blades, so this next value, "bladeStyle2Start" is the number of the first blade to use these value on... all blades before this use the normal values above, all blades at and after this number use the secondary values below*** - saber->bladeStyle2Start = 0; // 0 - if set, blades from this number and higher use the following values (otherwise, they use the normal values already set) + Q_strncpyz(saber->name, DEFAULT_SABER, sizeof(saber->name)); + Q_strncpyz(saber->fullName, "lightsaber", sizeof(saber->fullName)); + Q_strncpyz(saber->model, DEFAULT_SABER_MODEL, sizeof(saber->model)); + saber->skin = 0; + saber->soundOn = BG_SoundIndex("sound/weapons/saber/enemy_saber_on.wav"); + saber->soundLoop = BG_SoundIndex("sound/weapons/saber/saberhum3.wav"); + saber->soundOff = BG_SoundIndex("sound/weapons/saber/enemy_saber_off.wav"); + saber->numBlades = 1; + saber->type = SABER_SINGLE; + saber->stylesLearned = 0; + saber->stylesForbidden = 0; // allow all styles + saber->maxChain = 0; // 0 = use default behavior + saber->forceRestrictions = 0; + saber->lockBonus = 0; + saber->parryBonus = 0; + saber->breakParryBonus = 0; + saber->breakParryBonus2 = 0; + saber->disarmBonus = 0; + saber->disarmBonus2 = 0; + saber->singleBladeStyle = SS_NONE; // makes it so that you use a different style if you only have the first blade active + + //===NEW======================================================================================== + // done in cgame (client-side code) + saber->saberFlags = 0; // see all the SFL_ flags + saber->saberFlags2 = 0; // see all the SFL2_ flags + + saber->spinSound = 0; // none - if set, plays this sound as it spins when thrown + saber->swingSound[0] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + saber->swingSound[1] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + saber->swingSound[2] = 0; // none - if set, plays one of these 3 sounds when swung during an attack - NOTE: must provide all 3!!! + + // done in game (server-side code) + saber->moveSpeedScale = 1.0f; // 1.0 - you move faster/slower when using this saber + saber->animSpeedScale = 1.0f; // 1.0 - plays normal attack animations faster/slower + + saber->kataMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time + saber->lungeAtkMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they crouch+fwd+attack + saber->jumpAtkUpMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+attack + saber->jumpAtkFwdMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+fwd+attack + saber->jumpAtkBackMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+back+attack + saber->jumpAtkRightMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+rightattack + saber->jumpAtkLeftMove = LS_INVALID; // LS_INVALID - if set, player will execute this move when they jump+left+attack + saber->readyAnim = -1; // -1 - anim to use when standing idle + saber->drawAnim = -1; // -1 - anim to use when drawing weapon + saber->putawayAnim = -1; // -1 - anim to use when putting weapon away + saber->tauntAnim = -1; // -1 - anim to use when hit "taunt" + saber->bowAnim = -1; // -1 - anim to use when hit "bow" + saber->meditateAnim = -1; // -1 - anim to use when hit "meditate" + saber->flourishAnim = -1; // -1 - anim to use when hit "flourish" + saber->gloatAnim = -1; // -1 - anim to use when hit "gloat" + + //***NOTE: you can only have a maximum of 2 "styles" of blades, so this next value, "bladeStyle2Start" is the number of the first blade to use these value + //on... all blades before this use the normal values above, all blades at and after this number use the secondary values below*** + saber->bladeStyle2Start = 0; // 0 - if set, blades from this number and higher use the following values (otherwise, they use the normal values already set) //***The following can be different for the extra blades - not setting them individually defaults them to the value for the whole saber (and first blade)*** //===PRIMARY BLADES===================== - //done in cgame (client-side code) - saber->trailStyle = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) - saber->g2MarksShader = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->g2WeaponMarkShader = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->hitSound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hitSound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hitSound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->blockSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->blockSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->blockSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->bounceSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounceSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounceSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->blockEffect = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") - saber->hitPersonEffect = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") - saber->hitOtherEffect = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") - saber->bladeEffect = 0; // none - if set, plays this effect at the blade tag - - //done in game (server-side code) - saber->knockbackScale = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback - saber->damageScale = 1.0f; // 1 - scale up or down the damage done by the saber - saber->splashRadius = 0.0f; // 0 - radius of splashDamage - saber->splashDamage = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius - saber->splashKnockback = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius + // done in cgame (client-side code) + saber->trailStyle = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) + saber->g2MarksShader = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->g2WeaponMarkShader = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->hitSound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hitSound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hitSound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->blockSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->blockSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->blockSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->bounceSound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounceSound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounceSound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->blockEffect = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") + saber->hitPersonEffect = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") + saber->hitOtherEffect = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") + saber->bladeEffect = 0; // none - if set, plays this effect at the blade tag + + // done in game (server-side code) + saber->knockbackScale = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback + saber->damageScale = 1.0f; // 1 - scale up or down the damage done by the saber + saber->splashRadius = 0.0f; // 0 - radius of splashDamage + saber->splashDamage = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius + saber->splashKnockback = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius //===SECONDARY BLADES=================== - //done in cgame (client-side code) - saber->trailStyle2 = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) - saber->g2MarksShader2 = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->g2WeaponMarkShader2 = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" - saber->hit2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hit2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->hit2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! - saber->block2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->block2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->block2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! - saber->bounce2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounce2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->bounce2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use these sounds) - NOTE: must provide all 3!!! - saber->blockEffect2 = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") - saber->hitPersonEffect2 = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") - saber->hitOtherEffect2 = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") - saber->bladeEffect2 = 0; // none - if set, plays this effect at the blade tag - - //done in game (server-side code) - saber->knockbackScale2 = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback - saber->damageScale2 = 1.0f; // 1 - scale up or down the damage done by the saber - saber->splashRadius2 = 0.0f; // 0 - radius of splashDamage - saber->splashDamage2 = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius - saber->splashKnockback2 = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius -//========================================================================================================================================= -} - - -static void Saber_ParseName( saberInfo_t *saber, const char **p ) { - const char *value; - if ( COM_ParseString( p, &value ) ) - return; - Q_strncpyz( saber->fullName, value, sizeof( saber->fullName ) ); -} -static void Saber_ParseSaberType( saberInfo_t *saber, const char **p ) { + // done in cgame (client-side code) + saber->trailStyle2 = 0; // 0 - default (0) is normal, 1 is a motion blur and 2 is no trail at all (good for real-sword type mods) + saber->g2MarksShader2 = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->g2WeaponMarkShader2 = 0; // none - if set, the game will use this shader for marks on enemies instead of the default "gfx/damage/saberglowmark" + saber->hit2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hit2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->hit2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber hits a person - NOTE: must provide all 3!!! + saber->block2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->block2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->block2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits another saber/sword - NOTE: must provide all 3!!! + saber->bounce2Sound[0] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounce2Sound[1] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->bounce2Sound[2] = 0; // none - if set, plays one of these 3 sounds when saber/sword hits a wall and bounces off (must set bounceOnWall to 1 to use + // these sounds) - NOTE: must provide all 3!!! + saber->blockEffect2 = 0; // none - if set, plays this effect when the saber/sword hits another saber/sword (instead of "saber/saber_block.efx") + saber->hitPersonEffect2 = 0; // none - if set, plays this effect when the saber/sword hits a person (instead of "saber/blood_sparks_mp.efx") + saber->hitOtherEffect2 = 0; // none - if set, plays this effect when the saber/sword hits something else damagable (instead of "saber/saber_cut.efx") + saber->bladeEffect2 = 0; // none - if set, plays this effect at the blade tag + + // done in game (server-side code) + saber->knockbackScale2 = 0; // 0 - if non-zero, uses damage done to calculate an appropriate amount of knockback + saber->damageScale2 = 1.0f; // 1 - scale up or down the damage done by the saber + saber->splashRadius2 = 0.0f; // 0 - radius of splashDamage + saber->splashDamage2 = 0; // 0 - amount of splashDamage, 100% at a distance of 0, 0% at a distance = splashRadius + saber->splashKnockback2 = 0.0f; // 0 - amount of splashKnockback, 100% at a distance of 0, 0% at a distance = splashRadius + //========================================================================================================================================= +} + +static void Saber_ParseName(saberInfo_t *saber, const char **p) { + const char *value; + if (COM_ParseString(p, &value)) + return; + Q_strncpyz(saber->fullName, value, sizeof(saber->fullName)); +} +static void Saber_ParseSaberType(saberInfo_t *saber, const char **p) { const char *value; int saberType; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberType = GetIDForString( saberTable, value ); - if ( saberType >= SABER_SINGLE && saberType <= NUM_SABERS ) + saberType = GetIDForString(saberTable, value); + if (saberType >= SABER_SINGLE && saberType <= NUM_SABERS) saber->type = (saberType_t)saberType; } -static void Saber_ParseSaberModel( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberModel(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - Q_strncpyz( saber->model, value, sizeof( saber->model ) ); + Q_strncpyz(saber->model, value, sizeof(saber->model)); } -static void Saber_ParseCustomSkin( saberInfo_t *saber, const char **p ) { +static void Saber_ParseCustomSkin(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->skin = trap->R_RegisterSkin( value ); + saber->skin = trap->R_RegisterSkin(value); } -static void Saber_ParseSoundOn( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundOn(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundOn = BG_SoundIndex( value ); + saber->soundOn = BG_SoundIndex(value); } -static void Saber_ParseSoundLoop( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundLoop(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundLoop = BG_SoundIndex( value ); + saber->soundLoop = BG_SoundIndex(value); } -static void Saber_ParseSoundOff( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSoundOff(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->soundOff = BG_SoundIndex( value ); + saber->soundOff = BG_SoundIndex(value); } -static void Saber_ParseNumBlades( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNumBlades(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n < 1 || n > MAX_BLADES ) { - Com_Error( ERR_DROP, "WP_SaberParseParms: saber %s has illegal number of blades (%d) max: %d", saber->name, n, MAX_BLADES ); + if (n < 1 || n > MAX_BLADES) { + Com_Error(ERR_DROP, "WP_SaberParseParms: saber %s has illegal number of blades (%d) max: %d", saber->name, n, MAX_BLADES); return; } saber->numBlades = n; } -static void Saber_ParseSaberColor( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor(saberInfo_t *saber, const char **p) { const char *value; - int i=0; + int i = 0; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); - for ( i=0; iblade[i].color = color; } -static void Saber_ParseSaberColor2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor2(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[1].color = color; } -static void Saber_ParseSaberColor3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor3(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[2].color = color; } -static void Saber_ParseSaberColor4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor4(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[3].color = color; } -static void Saber_ParseSaberColor5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor5(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[4].color = color; } -static void Saber_ParseSaberColor6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor6(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[5].color = color; } -static void Saber_ParseSaberColor7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberColor7(saberInfo_t *saber, const char **p) { const char *value; saber_colors_t color; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - color = TranslateSaberColor( value ); + color = TranslateSaberColor(value); saber->blade[6].color = color; } -static void Saber_ParseSaberLength( saberInfo_t *saber, const char **p ) { - int i=0; +static void Saber_ParseSaberLength(saberInfo_t *saber, const char **p) { + int i = 0; float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; - for ( i=0; iblade[i].lengthMax = f; } -static void Saber_ParseSaberLength2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[1].lengthMax = f; } -static void Saber_ParseSaberLength3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength3(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[2].lengthMax = f; } -static void Saber_ParseSaberLength4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength4(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[3].lengthMax = f; } -static void Saber_ParseSaberLength5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength5(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[4].lengthMax = f; } -static void Saber_ParseSaberLength6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength6(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[5].lengthMax = f; } -static void Saber_ParseSaberLength7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberLength7(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 4.0f ) + if (f < 4.0f) f = 4.0f; saber->blade[6].lengthMax = f; } -static void Saber_ParseSaberRadius( saberInfo_t *saber, const char **p ) { - int i=0; +static void Saber_ParseSaberRadius(saberInfo_t *saber, const char **p) { + int i = 0; float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; - for ( i=0; iblade[i].radius = f; } -static void Saber_ParseSaberRadius2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[1].radius = f; } -static void Saber_ParseSaberRadius3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius3(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[2].radius = f; } -static void Saber_ParseSaberRadius4( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius4(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[3].radius = f; } -static void Saber_ParseSaberRadius5( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius5(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[4].radius = f; } -static void Saber_ParseSaberRadius6( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius6(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[5].radius = f; } -static void Saber_ParseSaberRadius7( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberRadius7(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) + if (COM_ParseFloat(p, &f)) return; - if ( f < 0.25f ) + if (f < 0.25f) f = 0.25f; saber->blade[6].radius = f; } -static void Saber_ParseSaberStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyle(saberInfo_t *saber, const char **p) { const char *value; int style, styleNum; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - //OLD WAY: only allowed ONE style - style = TranslateSaberStyle( value ); - //learn only this style - saber->stylesLearned = (1<stylesLearned = (1 << style); + // forbid all other styles saber->stylesForbidden = 0; - for ( styleNum=SS_NONE+1; styleNumstylesForbidden |= (1<stylesForbidden |= (1 << styleNum); } } -static void Saber_ParseSaberStyleLearned( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyleLearned(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->stylesLearned |= (1<stylesLearned |= (1 << TranslateSaberStyle(value)); } -static void Saber_ParseSaberStyleForbidden( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSaberStyleForbidden(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->stylesForbidden |= (1<stylesForbidden |= (1 << TranslateSaberStyle(value)); } -static void Saber_ParseMaxChain( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMaxChain(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->maxChain = n; } -static void Saber_ParseLockable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLockable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_LOCKABLE; } -static void Saber_ParseThrowable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseThrowable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_THROWABLE; } -static void Saber_ParseDisarmable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_DISARMABLE; } -static void Saber_ParseBlocking( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlocking(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n == 0 ) + if (n == 0) saber->saberFlags |= SFL_NOT_ACTIVE_BLOCKING; } -static void Saber_ParseTwoHanded( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTwoHanded(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_TWO_HANDED; } -static void Saber_ParseForceRestrict( saberInfo_t *saber, const char **p ) { +static void Saber_ParseForceRestrict(saberInfo_t *saber, const char **p) { const char *value; int fp; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - fp = GetIDForString( FPTable, value ); - if ( fp >= FP_FIRST && fp < NUM_FORCE_POWERS ) - saber->forceRestrictions |= (1<= FP_FIRST && fp < NUM_FORCE_POWERS) + saber->forceRestrictions |= (1 << fp); } -static void Saber_ParseLockBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLockBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->lockBonus = n; } -static void Saber_ParseParryBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseParryBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->parryBonus = n; } -static void Saber_ParseBreakParryBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBreakParryBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->breakParryBonus = n; } -static void Saber_ParseBreakParryBonus2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBreakParryBonus2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->breakParryBonus2 = n; } -static void Saber_ParseDisarmBonus( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmBonus(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->disarmBonus = n; } -static void Saber_ParseDisarmBonus2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDisarmBonus2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->disarmBonus2 = n; } -static void Saber_ParseSingleBladeStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSingleBladeStyle(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->singleBladeStyle = TranslateSaberStyle( value ); + saber->singleBladeStyle = TranslateSaberStyle(value); } -static void Saber_ParseSingleBladeThrowable( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSingleBladeThrowable(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_SINGLE_BLADE_THROWABLE; } -static void Saber_ParseBrokenSaber1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBrokenSaber1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - //saber->brokenSaber1 = G_NewString( value ); + // saber->brokenSaber1 = G_NewString( value ); } -static void Saber_ParseBrokenSaber2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBrokenSaber2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - //saber->brokenSaber2 = G_NewString( value ); + // saber->brokenSaber2 = G_NewString( value ); } -static void Saber_ParseReturnDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseReturnDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_RETURN_DAMAGE; } -static void Saber_ParseSpinSound( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSpinSound(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->spinSound = BG_SoundIndex( value ); + saber->spinSound = BG_SoundIndex(value); } -static void Saber_ParseSwingSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[0] = BG_SoundIndex( value ); + saber->swingSound[0] = BG_SoundIndex(value); } -static void Saber_ParseSwingSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[1] = BG_SoundIndex( value ); + saber->swingSound[1] = BG_SoundIndex(value); } -static void Saber_ParseSwingSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSwingSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->swingSound[2] = BG_SoundIndex( value ); + saber->swingSound[2] = BG_SoundIndex(value); } -static void Saber_ParseMoveSpeedScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMoveSpeedScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->moveSpeedScale = f; } -static void Saber_ParseAnimSpeedScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAnimSpeedScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->animSpeedScale = f; } -static void Saber_ParseBounceOnWalls( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceOnWalls(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_BOUNCE_ON_WALLS; } -static void Saber_ParseBoltToWrist( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBoltToWrist(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_BOLT_TO_WRIST; } -static void Saber_ParseKataMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKataMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) - saber->kataMove = saberMove; //LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) + saber->kataMove = saberMove; // LS_INVALID - if set, player will execute this move when they press both attack buttons at the same time } -static void Saber_ParseLungeAtkMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseLungeAtkMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->lungeAtkMove = saberMove; } -static void Saber_ParseJumpAtkUpMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkUpMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkUpMove = saberMove; } -static void Saber_ParseJumpAtkFwdMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkFwdMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkFwdMove = saberMove; } -static void Saber_ParseJumpAtkBackMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkBackMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkBackMove = saberMove; } -static void Saber_ParseJumpAtkRightMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkRightMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkRightMove = saberMove; } -static void Saber_ParseJumpAtkLeftMove( saberInfo_t *saber, const char **p ) { +static void Saber_ParseJumpAtkLeftMove(saberInfo_t *saber, const char **p) { const char *value; int saberMove = LS_INVALID; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saberMove = GetIDForString( saberMoveTable, value ); - if ( saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX ) + saberMove = GetIDForString(saberMoveTable, value); + if (saberMove >= LS_INVALID && saberMove < LS_MOVE_MAX) saber->jumpAtkLeftMove = saberMove; } -static void Saber_ParseReadyAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseReadyAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->readyAnim = anim; } -static void Saber_ParseDrawAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDrawAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->drawAnim = anim; } -static void Saber_ParsePutawayAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParsePutawayAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->putawayAnim = anim; } -static void Saber_ParseTauntAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTauntAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->tauntAnim = anim; } -static void Saber_ParseBowAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBowAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->bowAnim = anim; } -static void Saber_ParseMeditateAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseMeditateAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->meditateAnim = anim; } -static void Saber_ParseFlourishAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseFlourishAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->flourishAnim = anim; } -static void Saber_ParseGloatAnim( saberInfo_t *saber, const char **p ) { +static void Saber_ParseGloatAnim(saberInfo_t *saber, const char **p) { const char *value; int anim = -1; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - anim = GetIDForString( animTable, value ); - if ( anim >= 0 && anim < MAX_ANIMATIONS ) + anim = GetIDForString(animTable, value); + if (anim >= 0 && anim < MAX_ANIMATIONS) saber->gloatAnim = anim; } -static void Saber_ParseNoRollStab( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoRollStab(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_ROLL_STAB; } -static void Saber_ParseNoPullAttack( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoPullAttack(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_PULL_ATTACK; } -static void Saber_ParseNoBackAttack( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBackAttack(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_BACK_ATTACK; } -static void Saber_ParseNoStabDown( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoStabDown(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_STABDOWN; } -static void Saber_ParseNoWallRuns( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallRuns(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_RUNS; } -static void Saber_ParseNoWallFlips( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallFlips(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_FLIPS; } -static void Saber_ParseNoWallGrab( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallGrab(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_WALL_GRAB; } -static void Saber_ParseNoRolls( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoRolls(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_ROLLS; } -static void Saber_ParseNoFlips( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoFlips(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_FLIPS; } -static void Saber_ParseNoCartwheels( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoCartwheels(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_CARTWHEELS; } -static void Saber_ParseNoKicks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoKicks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_KICKS; } -static void Saber_ParseNoMirrorAttacks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoMirrorAttacks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags |= SFL_NO_MIRROR_ATTACKS; } -static void Saber_ParseOnInWater( saberInfo_t *saber, const char **p ) { - SkipRestOfLine( p ); -} -static void Saber_ParseNotInMP( saberInfo_t *saber, const char **p ) { - SkipRestOfLine( p ); -} -static void Saber_ParseBladeStyle2Start( saberInfo_t *saber, const char **p ) { +static void Saber_ParseOnInWater(saberInfo_t *saber, const char **p) { SkipRestOfLine(p); } +static void Saber_ParseNotInMP(saberInfo_t *saber, const char **p) { SkipRestOfLine(p); } +static void Saber_ParseBladeStyle2Start(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->bladeStyle2Start = n; } -static void Saber_ParseNoWallMarks( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallMarks(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_WALL_MARKS; } -static void Saber_ParseNoDLight( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDLight(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DLIGHT; } -static void Saber_ParseNoBlade( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBlade(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_BLADE; } -static void Saber_ParseTrailStyle( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTrailStyle(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->trailStyle = n; } -static void Saber_ParseG2MarksShader( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2MarksShader(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } #ifdef _CGAME - saber->g2MarksShader = trap->R_RegisterShader( value ); + saber->g2MarksShader = trap->R_RegisterShader(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseG2WeaponMarkShader( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2WeaponMarkShader(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } #ifdef _CGAME - saber->g2WeaponMarkShader = trap->R_RegisterShader( value ); + saber->g2WeaponMarkShader = trap->R_RegisterShader(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseKnockbackScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKnockbackScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->knockbackScale = f; } -static void Saber_ParseDamageScale( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDamageScale(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->damageScale = f; } -static void Saber_ParseNoDismemberment( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDismemberment(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DISMEMBERMENT; } -static void Saber_ParseNoIdleEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoIdleEffect(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_IDLE_EFFECT; } -static void Saber_ParseAlwaysBlock( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAlwaysBlock(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_ALWAYS_BLOCK; } -static void Saber_ParseNoManualDeactivate( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoManualDeactivate(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_MANUAL_DEACTIVATE; } -static void Saber_ParseTransitionDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTransitionDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_TRANSITION_DAMAGE; } -static void Saber_ParseSplashRadius( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashRadius(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashRadius = f; } -static void Saber_ParseSplashDamage( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashDamage(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->splashDamage = n; } -static void Saber_ParseSplashKnockback( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashKnockback(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashKnockback = f; } -static void Saber_ParseHitSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[0] = BG_SoundIndex( value ); + saber->hitSound[0] = BG_SoundIndex(value); } -static void Saber_ParseHitSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[1] = BG_SoundIndex( value ); + saber->hitSound[1] = BG_SoundIndex(value); } -static void Saber_ParseHitSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hitSound[2] = BG_SoundIndex( value ); + saber->hitSound[2] = BG_SoundIndex(value); } -static void Saber_ParseBlockSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[0] = BG_SoundIndex( value ); + saber->blockSound[0] = BG_SoundIndex(value); } -static void Saber_ParseBlockSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[1] = BG_SoundIndex( value ); + saber->blockSound[1] = BG_SoundIndex(value); } -static void Saber_ParseBlockSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->blockSound[2] = BG_SoundIndex( value ); + saber->blockSound[2] = BG_SoundIndex(value); } -static void Saber_ParseBounceSound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[0] = BG_SoundIndex( value ); + saber->bounceSound[0] = BG_SoundIndex(value); } -static void Saber_ParseBounceSound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[1] = BG_SoundIndex( value ); + saber->bounceSound[1] = BG_SoundIndex(value); } -static void Saber_ParseBounceSound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounceSound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounceSound[2] = BG_SoundIndex( value ); + saber->bounceSound[2] = BG_SoundIndex(value); } -static void Saber_ParseBlockEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->blockEffect = trap->FX_RegisterEffect( value ); + saber->blockEffect = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseHitPersonEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitPersonEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->hitPersonEffect = trap->FX_RegisterEffect( value ); + saber->hitPersonEffect = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseHitOtherEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitOtherEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->hitOtherEffect = trap->FX_RegisterEffect( value ); + saber->hitOtherEffect = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseBladeEffect( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBladeEffect(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->bladeEffect = trap->FX_RegisterEffect( value ); + saber->bladeEffect = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseNoClashFlare( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoClashFlare(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_CLASH_FLARE; } -static void Saber_ParseNoWallMarks2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoWallMarks2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_WALL_MARKS2; } -static void Saber_ParseNoDLight2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDLight2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DLIGHT2; } -static void Saber_ParseNoBlade2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoBlade2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_BLADE2; } -static void Saber_ParseTrailStyle2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTrailStyle2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->trailStyle2 = n; } -static void Saber_ParseG2MarksShader2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2MarksShader2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } #ifdef _CGAME - saber->g2MarksShader2 = trap->R_RegisterShader( value ); + saber->g2MarksShader2 = trap->R_RegisterShader(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseG2WeaponMarkShader2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseG2WeaponMarkShader2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) { - SkipRestOfLine( p ); + if (COM_ParseString(p, &value)) { + SkipRestOfLine(p); return; } #ifdef _CGAME - saber->g2WeaponMarkShader2 = trap->R_RegisterShader( value ); + saber->g2WeaponMarkShader2 = trap->R_RegisterShader(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseKnockbackScale2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseKnockbackScale2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->knockbackScale2 = f; } -static void Saber_ParseDamageScale2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseDamageScale2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->damageScale2 = f; } -static void Saber_ParseNoDismemberment2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoDismemberment2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_DISMEMBERMENT2; } -static void Saber_ParseNoIdleEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoIdleEffect2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_IDLE_EFFECT2; } -static void Saber_ParseAlwaysBlock2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseAlwaysBlock2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_ALWAYS_BLOCK2; } -static void Saber_ParseNoManualDeactivate2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoManualDeactivate2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_MANUAL_DEACTIVATE2; } -static void Saber_ParseTransitionDamage2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseTransitionDamage2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_TRANSITION_DAMAGE2; } -static void Saber_ParseSplashRadius2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashRadius2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashRadius2 = f; } -static void Saber_ParseSplashDamage2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashDamage2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } saber->splashDamage2 = n; } -static void Saber_ParseSplashKnockback2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseSplashKnockback2(saberInfo_t *saber, const char **p) { float f; - if ( COM_ParseFloat( p, &f ) ) { - SkipRestOfLine( p ); + if (COM_ParseFloat(p, &f)) { + SkipRestOfLine(p); return; } saber->splashKnockback2 = f; } -static void Saber_ParseHit2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[0] = BG_SoundIndex( value ); + saber->hit2Sound[0] = BG_SoundIndex(value); } -static void Saber_ParseHit2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[1] = BG_SoundIndex( value ); + saber->hit2Sound[1] = BG_SoundIndex(value); } -static void Saber_ParseHit2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHit2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->hit2Sound[2] = BG_SoundIndex( value ); + saber->hit2Sound[2] = BG_SoundIndex(value); } -static void Saber_ParseBlock2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[0] = BG_SoundIndex( value ); + saber->block2Sound[0] = BG_SoundIndex(value); } -static void Saber_ParseBlock2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[1] = BG_SoundIndex( value ); + saber->block2Sound[1] = BG_SoundIndex(value); } -static void Saber_ParseBlock2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlock2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->block2Sound[2] = BG_SoundIndex( value ); + saber->block2Sound[2] = BG_SoundIndex(value); } -static void Saber_ParseBounce2Sound1( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound1(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[0] = BG_SoundIndex( value ); + saber->bounce2Sound[0] = BG_SoundIndex(value); } -static void Saber_ParseBounce2Sound2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[1] = BG_SoundIndex( value ); + saber->bounce2Sound[1] = BG_SoundIndex(value); } -static void Saber_ParseBounce2Sound3( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBounce2Sound3(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; - saber->bounce2Sound[2] = BG_SoundIndex( value ); + saber->bounce2Sound[2] = BG_SoundIndex(value); } -static void Saber_ParseBlockEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBlockEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->blockEffect2 = trap->FX_RegisterEffect( value ); + saber->blockEffect2 = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseHitPersonEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitPersonEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->hitPersonEffect2 = trap->FX_RegisterEffect( value ); + saber->hitPersonEffect2 = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseHitOtherEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseHitOtherEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->hitOtherEffect2 = trap->FX_RegisterEffect( value ); + saber->hitOtherEffect2 = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseBladeEffect2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseBladeEffect2(saberInfo_t *saber, const char **p) { const char *value; - if ( COM_ParseString( p, &value ) ) + if (COM_ParseString(p, &value)) return; #ifdef _CGAME - saber->bladeEffect2 = trap->FX_RegisterEffect( value ); + saber->bladeEffect2 = trap->FX_RegisterEffect(value); #else - SkipRestOfLine( p ); + SkipRestOfLine(p); #endif } -static void Saber_ParseNoClashFlare2( saberInfo_t *saber, const char **p ) { +static void Saber_ParseNoClashFlare2(saberInfo_t *saber, const char **p) { int n; - if ( COM_ParseInt( p, &n ) ) { - SkipRestOfLine( p ); + if (COM_ParseInt(p, &n)) { + SkipRestOfLine(p); return; } - if ( n ) + if (n) saber->saberFlags2 |= SFL2_NO_CLASH_FLARE2; } - /* =============== Keyword Hash @@ -1806,588 +1820,536 @@ Keyword Hash #define KEYWORDHASH_SIZE (512) typedef struct keywordHash_s { - char *keyword; - void (*func)(saberInfo_t *saber, const char **p); + char *keyword; + void (*func)(saberInfo_t *saber, const char **p); struct keywordHash_s *next; } keywordHash_t; -static int KeywordHash_Key( const char *keyword ) { +static int KeywordHash_Key(const char *keyword) { int register hash, i; hash = 0; - for ( i=0; keyword[i]; i++ ) { - if ( keyword[i] >= 'A' && keyword[i] <= 'Z' ) - hash += (keyword[i] + ('a'-'A')) * (119 + i); + for (i = 0; keyword[i]; i++) { + if (keyword[i] >= 'A' && keyword[i] <= 'Z') + hash += (keyword[i] + ('a' - 'A')) * (119 + i); else hash += keyword[i] * (119 + i); } - hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE-1); + hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE - 1); return hash; } -static void KeywordHash_Add( keywordHash_t *table[], keywordHash_t *key ) { - int hash = KeywordHash_Key( key->keyword ); +static void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) { + int hash = KeywordHash_Key(key->keyword); key->next = table[hash]; table[hash] = key; } -static keywordHash_t *KeywordHash_Find( keywordHash_t *table[], const char *keyword ) { +static keywordHash_t *KeywordHash_Find(keywordHash_t *table[], const char *keyword) { keywordHash_t *key; int hash = KeywordHash_Key(keyword); - for ( key=table[hash]; key; key=key->next ) { - if ( !Q_stricmp( key->keyword, keyword ) ) + for (key = table[hash]; key; key = key->next) { + if (!Q_stricmp(key->keyword, keyword)) return key; } return NULL; } -static keywordHash_t saberParseKeywords[] = { - { "name", Saber_ParseName, NULL }, - { "saberType", Saber_ParseSaberType, NULL }, - { "saberModel", Saber_ParseSaberModel, NULL }, - { "customSkin", Saber_ParseCustomSkin, NULL }, - { "soundOn", Saber_ParseSoundOn, NULL }, - { "soundLoop", Saber_ParseSoundLoop, NULL }, - { "soundOff", Saber_ParseSoundOff, NULL }, - { "numBlades", Saber_ParseNumBlades, NULL }, - { "saberColor", Saber_ParseSaberColor, NULL }, - { "saberColor2", Saber_ParseSaberColor2, NULL }, - { "saberColor3", Saber_ParseSaberColor3, NULL }, - { "saberColor4", Saber_ParseSaberColor4, NULL }, - { "saberColor5", Saber_ParseSaberColor5, NULL }, - { "saberColor6", Saber_ParseSaberColor6, NULL }, - { "saberColor7", Saber_ParseSaberColor7, NULL }, - { "saberLength", Saber_ParseSaberLength, NULL }, - { "saberLength2", Saber_ParseSaberLength2, NULL }, - { "saberLength3", Saber_ParseSaberLength3, NULL }, - { "saberLength4", Saber_ParseSaberLength4, NULL }, - { "saberLength5", Saber_ParseSaberLength5, NULL }, - { "saberLength6", Saber_ParseSaberLength6, NULL }, - { "saberLength7", Saber_ParseSaberLength7, NULL }, - { "saberRadius", Saber_ParseSaberRadius, NULL }, - { "saberRadius2", Saber_ParseSaberRadius2, NULL }, - { "saberRadius3", Saber_ParseSaberRadius3, NULL }, - { "saberRadius4", Saber_ParseSaberRadius4, NULL }, - { "saberRadius5", Saber_ParseSaberRadius5, NULL }, - { "saberRadius6", Saber_ParseSaberRadius6, NULL }, - { "saberRadius7", Saber_ParseSaberRadius7, NULL }, - { "saberStyle", Saber_ParseSaberStyle, NULL }, - { "saberStyleLearned", Saber_ParseSaberStyleLearned, NULL }, - { "saberStyleForbidden", Saber_ParseSaberStyleForbidden, NULL }, - { "maxChain", Saber_ParseMaxChain, NULL }, - { "lockable", Saber_ParseLockable, NULL }, - { "throwable", Saber_ParseThrowable, NULL }, - { "disarmable", Saber_ParseDisarmable, NULL }, - { "blocking", Saber_ParseBlocking, NULL }, - { "twoHanded", Saber_ParseTwoHanded, NULL }, - { "forceRestrict", Saber_ParseForceRestrict, NULL }, - { "lockBonus", Saber_ParseLockBonus, NULL }, - { "parryBonus", Saber_ParseParryBonus, NULL }, - { "breakParryBonus", Saber_ParseBreakParryBonus, NULL }, - { "breakParryBonus2", Saber_ParseBreakParryBonus2, NULL }, - { "disarmBonus", Saber_ParseDisarmBonus, NULL }, - { "disarmBonus2", Saber_ParseDisarmBonus2, NULL }, - { "singleBladeStyle", Saber_ParseSingleBladeStyle, NULL }, - { "singleBladeThrowable", Saber_ParseSingleBladeThrowable,NULL }, - { "brokenSaber1", Saber_ParseBrokenSaber1, NULL }, - { "brokenSaber2", Saber_ParseBrokenSaber2, NULL }, - { "returnDamage", Saber_ParseReturnDamage, NULL }, - { "spinSound", Saber_ParseSpinSound, NULL }, - { "swingSound1", Saber_ParseSwingSound1, NULL }, - { "swingSound2", Saber_ParseSwingSound2, NULL }, - { "swingSound3", Saber_ParseSwingSound3, NULL }, - { "moveSpeedScale", Saber_ParseMoveSpeedScale, NULL }, - { "animSpeedScale", Saber_ParseAnimSpeedScale, NULL }, - { "bounceOnWalls", Saber_ParseBounceOnWalls, NULL }, - { "boltToWrist", Saber_ParseBoltToWrist, NULL }, - { "kataMove", Saber_ParseKataMove, NULL }, - { "lungeAtkMove", Saber_ParseLungeAtkMove, NULL }, - { "jumpAtkUpMove", Saber_ParseJumpAtkUpMove, NULL }, - { "jumpAtkFwdMove", Saber_ParseJumpAtkFwdMove, NULL }, - { "jumpAtkBackMove", Saber_ParseJumpAtkBackMove, NULL }, - { "jumpAtkRightMove", Saber_ParseJumpAtkRightMove, NULL }, - { "jumpAtkLeftMove", Saber_ParseJumpAtkLeftMove, NULL }, - { "readyAnim", Saber_ParseReadyAnim, NULL }, - { "drawAnim", Saber_ParseDrawAnim, NULL }, - { "putawayAnim", Saber_ParsePutawayAnim, NULL }, - { "tauntAnim", Saber_ParseTauntAnim, NULL }, - { "bowAnim", Saber_ParseBowAnim, NULL }, - { "meditateAnim", Saber_ParseMeditateAnim, NULL }, - { "flourishAnim", Saber_ParseFlourishAnim, NULL }, - { "gloatAnim", Saber_ParseGloatAnim, NULL }, - { "noRollStab", Saber_ParseNoRollStab, NULL }, - { "noPullAttack", Saber_ParseNoPullAttack, NULL }, - { "noBackAttack", Saber_ParseNoBackAttack, NULL }, - { "noStabDown", Saber_ParseNoStabDown, NULL }, - { "noWallRuns", Saber_ParseNoWallRuns, NULL }, - { "noWallFlips", Saber_ParseNoWallFlips, NULL }, - { "noWallGrab", Saber_ParseNoWallGrab, NULL }, - { "noRolls", Saber_ParseNoRolls, NULL }, - { "noFlips", Saber_ParseNoFlips, NULL }, - { "noCartwheels", Saber_ParseNoCartwheels, NULL }, - { "noKicks", Saber_ParseNoKicks, NULL }, - { "noMirrorAttacks", Saber_ParseNoMirrorAttacks, NULL }, - { "onInWater", Saber_ParseOnInWater, NULL }, - { "notInMP", Saber_ParseNotInMP, NULL }, - { "bladeStyle2Start", Saber_ParseBladeStyle2Start, NULL }, - { "noWallMarks", Saber_ParseNoWallMarks, NULL }, - { "noWallMarks2", Saber_ParseNoWallMarks2, NULL }, - { "noDlight", Saber_ParseNoDLight, NULL }, - { "noDlight2", Saber_ParseNoDLight2, NULL }, - { "noBlade", Saber_ParseNoBlade, NULL }, - { "noBlade2", Saber_ParseNoBlade2, NULL }, - { "trailStyle", Saber_ParseTrailStyle, NULL }, - { "trailStyle2", Saber_ParseTrailStyle2, NULL }, - { "g2MarksShader", Saber_ParseG2MarksShader, NULL }, - { "g2MarksShader2", Saber_ParseG2MarksShader2, NULL }, - { "g2WeaponMarkShader", Saber_ParseG2WeaponMarkShader, NULL }, - { "g2WeaponMarkShader2", Saber_ParseG2WeaponMarkShader2, NULL }, - { "knockbackScale", Saber_ParseKnockbackScale, NULL }, - { "knockbackScale2", Saber_ParseKnockbackScale2, NULL }, - { "damageScale", Saber_ParseDamageScale, NULL }, - { "damageScale2", Saber_ParseDamageScale2, NULL }, - { "noDismemberment", Saber_ParseNoDismemberment, NULL }, - { "noDismemberment2", Saber_ParseNoDismemberment2, NULL }, - { "noIdleEffect", Saber_ParseNoIdleEffect, NULL }, - { "noIdleEffect2", Saber_ParseNoIdleEffect2, NULL }, - { "alwaysBlock", Saber_ParseAlwaysBlock, NULL }, - { "alwaysBlock2", Saber_ParseAlwaysBlock2, NULL }, - { "noManualDeactivate", Saber_ParseNoManualDeactivate, NULL }, - { "noManualDeactivate2", Saber_ParseNoManualDeactivate2, NULL }, - { "transitionDamage", Saber_ParseTransitionDamage, NULL }, - { "transitionDamage2", Saber_ParseTransitionDamage2, NULL }, - { "splashRadius", Saber_ParseSplashRadius, NULL }, - { "splashRadius2", Saber_ParseSplashRadius2, NULL }, - { "splashDamage", Saber_ParseSplashDamage, NULL }, - { "splashDamage2", Saber_ParseSplashDamage2, NULL }, - { "splashKnockback", Saber_ParseSplashKnockback, NULL }, - { "splashKnockback2", Saber_ParseSplashKnockback2, NULL }, - { "hitSound1", Saber_ParseHitSound1, NULL }, - { "hit2Sound1", Saber_ParseHit2Sound1, NULL }, - { "hitSound2", Saber_ParseHitSound2, NULL }, - { "hit2Sound2", Saber_ParseHit2Sound2, NULL }, - { "hitSound3", Saber_ParseHitSound3, NULL }, - { "hit2Sound3", Saber_ParseHit2Sound3, NULL }, - { "blockSound1", Saber_ParseBlockSound1, NULL }, - { "block2Sound1", Saber_ParseBlock2Sound1, NULL }, - { "blockSound2", Saber_ParseBlockSound2, NULL }, - { "block2Sound2", Saber_ParseBlock2Sound2, NULL }, - { "blockSound3", Saber_ParseBlockSound3, NULL }, - { "block2Sound3", Saber_ParseBlock2Sound3, NULL }, - { "bounceSound1", Saber_ParseBounceSound1, NULL }, - { "bounce2Sound1", Saber_ParseBounce2Sound1, NULL }, - { "bounceSound2", Saber_ParseBounceSound2, NULL }, - { "bounce2Sound2", Saber_ParseBounce2Sound2, NULL }, - { "bounceSound3", Saber_ParseBounceSound3, NULL }, - { "bounce2Sound3", Saber_ParseBounce2Sound3, NULL }, - { "blockEffect", Saber_ParseBlockEffect, NULL }, - { "blockEffect2", Saber_ParseBlockEffect2, NULL }, - { "hitPersonEffect", Saber_ParseHitPersonEffect, NULL }, - { "hitPersonEffect2", Saber_ParseHitPersonEffect2, NULL }, - { "hitOtherEffect", Saber_ParseHitOtherEffect, NULL }, - { "hitOtherEffect2", Saber_ParseHitOtherEffect2, NULL }, - { "bladeEffect", Saber_ParseBladeEffect, NULL }, - { "bladeEffect2", Saber_ParseBladeEffect2, NULL }, - { "noClashFlare", Saber_ParseNoClashFlare, NULL }, - { "noClashFlare2", Saber_ParseNoClashFlare2, NULL }, - { NULL, NULL, NULL } -}; +static keywordHash_t saberParseKeywords[] = {{"name", Saber_ParseName, NULL}, + {"saberType", Saber_ParseSaberType, NULL}, + {"saberModel", Saber_ParseSaberModel, NULL}, + {"customSkin", Saber_ParseCustomSkin, NULL}, + {"soundOn", Saber_ParseSoundOn, NULL}, + {"soundLoop", Saber_ParseSoundLoop, NULL}, + {"soundOff", Saber_ParseSoundOff, NULL}, + {"numBlades", Saber_ParseNumBlades, NULL}, + {"saberColor", Saber_ParseSaberColor, NULL}, + {"saberColor2", Saber_ParseSaberColor2, NULL}, + {"saberColor3", Saber_ParseSaberColor3, NULL}, + {"saberColor4", Saber_ParseSaberColor4, NULL}, + {"saberColor5", Saber_ParseSaberColor5, NULL}, + {"saberColor6", Saber_ParseSaberColor6, NULL}, + {"saberColor7", Saber_ParseSaberColor7, NULL}, + {"saberLength", Saber_ParseSaberLength, NULL}, + {"saberLength2", Saber_ParseSaberLength2, NULL}, + {"saberLength3", Saber_ParseSaberLength3, NULL}, + {"saberLength4", Saber_ParseSaberLength4, NULL}, + {"saberLength5", Saber_ParseSaberLength5, NULL}, + {"saberLength6", Saber_ParseSaberLength6, NULL}, + {"saberLength7", Saber_ParseSaberLength7, NULL}, + {"saberRadius", Saber_ParseSaberRadius, NULL}, + {"saberRadius2", Saber_ParseSaberRadius2, NULL}, + {"saberRadius3", Saber_ParseSaberRadius3, NULL}, + {"saberRadius4", Saber_ParseSaberRadius4, NULL}, + {"saberRadius5", Saber_ParseSaberRadius5, NULL}, + {"saberRadius6", Saber_ParseSaberRadius6, NULL}, + {"saberRadius7", Saber_ParseSaberRadius7, NULL}, + {"saberStyle", Saber_ParseSaberStyle, NULL}, + {"saberStyleLearned", Saber_ParseSaberStyleLearned, NULL}, + {"saberStyleForbidden", Saber_ParseSaberStyleForbidden, NULL}, + {"maxChain", Saber_ParseMaxChain, NULL}, + {"lockable", Saber_ParseLockable, NULL}, + {"throwable", Saber_ParseThrowable, NULL}, + {"disarmable", Saber_ParseDisarmable, NULL}, + {"blocking", Saber_ParseBlocking, NULL}, + {"twoHanded", Saber_ParseTwoHanded, NULL}, + {"forceRestrict", Saber_ParseForceRestrict, NULL}, + {"lockBonus", Saber_ParseLockBonus, NULL}, + {"parryBonus", Saber_ParseParryBonus, NULL}, + {"breakParryBonus", Saber_ParseBreakParryBonus, NULL}, + {"breakParryBonus2", Saber_ParseBreakParryBonus2, NULL}, + {"disarmBonus", Saber_ParseDisarmBonus, NULL}, + {"disarmBonus2", Saber_ParseDisarmBonus2, NULL}, + {"singleBladeStyle", Saber_ParseSingleBladeStyle, NULL}, + {"singleBladeThrowable", Saber_ParseSingleBladeThrowable, NULL}, + {"brokenSaber1", Saber_ParseBrokenSaber1, NULL}, + {"brokenSaber2", Saber_ParseBrokenSaber2, NULL}, + {"returnDamage", Saber_ParseReturnDamage, NULL}, + {"spinSound", Saber_ParseSpinSound, NULL}, + {"swingSound1", Saber_ParseSwingSound1, NULL}, + {"swingSound2", Saber_ParseSwingSound2, NULL}, + {"swingSound3", Saber_ParseSwingSound3, NULL}, + {"moveSpeedScale", Saber_ParseMoveSpeedScale, NULL}, + {"animSpeedScale", Saber_ParseAnimSpeedScale, NULL}, + {"bounceOnWalls", Saber_ParseBounceOnWalls, NULL}, + {"boltToWrist", Saber_ParseBoltToWrist, NULL}, + {"kataMove", Saber_ParseKataMove, NULL}, + {"lungeAtkMove", Saber_ParseLungeAtkMove, NULL}, + {"jumpAtkUpMove", Saber_ParseJumpAtkUpMove, NULL}, + {"jumpAtkFwdMove", Saber_ParseJumpAtkFwdMove, NULL}, + {"jumpAtkBackMove", Saber_ParseJumpAtkBackMove, NULL}, + {"jumpAtkRightMove", Saber_ParseJumpAtkRightMove, NULL}, + {"jumpAtkLeftMove", Saber_ParseJumpAtkLeftMove, NULL}, + {"readyAnim", Saber_ParseReadyAnim, NULL}, + {"drawAnim", Saber_ParseDrawAnim, NULL}, + {"putawayAnim", Saber_ParsePutawayAnim, NULL}, + {"tauntAnim", Saber_ParseTauntAnim, NULL}, + {"bowAnim", Saber_ParseBowAnim, NULL}, + {"meditateAnim", Saber_ParseMeditateAnim, NULL}, + {"flourishAnim", Saber_ParseFlourishAnim, NULL}, + {"gloatAnim", Saber_ParseGloatAnim, NULL}, + {"noRollStab", Saber_ParseNoRollStab, NULL}, + {"noPullAttack", Saber_ParseNoPullAttack, NULL}, + {"noBackAttack", Saber_ParseNoBackAttack, NULL}, + {"noStabDown", Saber_ParseNoStabDown, NULL}, + {"noWallRuns", Saber_ParseNoWallRuns, NULL}, + {"noWallFlips", Saber_ParseNoWallFlips, NULL}, + {"noWallGrab", Saber_ParseNoWallGrab, NULL}, + {"noRolls", Saber_ParseNoRolls, NULL}, + {"noFlips", Saber_ParseNoFlips, NULL}, + {"noCartwheels", Saber_ParseNoCartwheels, NULL}, + {"noKicks", Saber_ParseNoKicks, NULL}, + {"noMirrorAttacks", Saber_ParseNoMirrorAttacks, NULL}, + {"onInWater", Saber_ParseOnInWater, NULL}, + {"notInMP", Saber_ParseNotInMP, NULL}, + {"bladeStyle2Start", Saber_ParseBladeStyle2Start, NULL}, + {"noWallMarks", Saber_ParseNoWallMarks, NULL}, + {"noWallMarks2", Saber_ParseNoWallMarks2, NULL}, + {"noDlight", Saber_ParseNoDLight, NULL}, + {"noDlight2", Saber_ParseNoDLight2, NULL}, + {"noBlade", Saber_ParseNoBlade, NULL}, + {"noBlade2", Saber_ParseNoBlade2, NULL}, + {"trailStyle", Saber_ParseTrailStyle, NULL}, + {"trailStyle2", Saber_ParseTrailStyle2, NULL}, + {"g2MarksShader", Saber_ParseG2MarksShader, NULL}, + {"g2MarksShader2", Saber_ParseG2MarksShader2, NULL}, + {"g2WeaponMarkShader", Saber_ParseG2WeaponMarkShader, NULL}, + {"g2WeaponMarkShader2", Saber_ParseG2WeaponMarkShader2, NULL}, + {"knockbackScale", Saber_ParseKnockbackScale, NULL}, + {"knockbackScale2", Saber_ParseKnockbackScale2, NULL}, + {"damageScale", Saber_ParseDamageScale, NULL}, + {"damageScale2", Saber_ParseDamageScale2, NULL}, + {"noDismemberment", Saber_ParseNoDismemberment, NULL}, + {"noDismemberment2", Saber_ParseNoDismemberment2, NULL}, + {"noIdleEffect", Saber_ParseNoIdleEffect, NULL}, + {"noIdleEffect2", Saber_ParseNoIdleEffect2, NULL}, + {"alwaysBlock", Saber_ParseAlwaysBlock, NULL}, + {"alwaysBlock2", Saber_ParseAlwaysBlock2, NULL}, + {"noManualDeactivate", Saber_ParseNoManualDeactivate, NULL}, + {"noManualDeactivate2", Saber_ParseNoManualDeactivate2, NULL}, + {"transitionDamage", Saber_ParseTransitionDamage, NULL}, + {"transitionDamage2", Saber_ParseTransitionDamage2, NULL}, + {"splashRadius", Saber_ParseSplashRadius, NULL}, + {"splashRadius2", Saber_ParseSplashRadius2, NULL}, + {"splashDamage", Saber_ParseSplashDamage, NULL}, + {"splashDamage2", Saber_ParseSplashDamage2, NULL}, + {"splashKnockback", Saber_ParseSplashKnockback, NULL}, + {"splashKnockback2", Saber_ParseSplashKnockback2, NULL}, + {"hitSound1", Saber_ParseHitSound1, NULL}, + {"hit2Sound1", Saber_ParseHit2Sound1, NULL}, + {"hitSound2", Saber_ParseHitSound2, NULL}, + {"hit2Sound2", Saber_ParseHit2Sound2, NULL}, + {"hitSound3", Saber_ParseHitSound3, NULL}, + {"hit2Sound3", Saber_ParseHit2Sound3, NULL}, + {"blockSound1", Saber_ParseBlockSound1, NULL}, + {"block2Sound1", Saber_ParseBlock2Sound1, NULL}, + {"blockSound2", Saber_ParseBlockSound2, NULL}, + {"block2Sound2", Saber_ParseBlock2Sound2, NULL}, + {"blockSound3", Saber_ParseBlockSound3, NULL}, + {"block2Sound3", Saber_ParseBlock2Sound3, NULL}, + {"bounceSound1", Saber_ParseBounceSound1, NULL}, + {"bounce2Sound1", Saber_ParseBounce2Sound1, NULL}, + {"bounceSound2", Saber_ParseBounceSound2, NULL}, + {"bounce2Sound2", Saber_ParseBounce2Sound2, NULL}, + {"bounceSound3", Saber_ParseBounceSound3, NULL}, + {"bounce2Sound3", Saber_ParseBounce2Sound3, NULL}, + {"blockEffect", Saber_ParseBlockEffect, NULL}, + {"blockEffect2", Saber_ParseBlockEffect2, NULL}, + {"hitPersonEffect", Saber_ParseHitPersonEffect, NULL}, + {"hitPersonEffect2", Saber_ParseHitPersonEffect2, NULL}, + {"hitOtherEffect", Saber_ParseHitOtherEffect, NULL}, + {"hitOtherEffect2", Saber_ParseHitOtherEffect2, NULL}, + {"bladeEffect", Saber_ParseBladeEffect, NULL}, + {"bladeEffect2", Saber_ParseBladeEffect2, NULL}, + {"noClashFlare", Saber_ParseNoClashFlare, NULL}, + {"noClashFlare2", Saber_ParseNoClashFlare2, NULL}, + {NULL, NULL, NULL}}; static keywordHash_t *saberParseKeywordHash[KEYWORDHASH_SIZE]; static qboolean hashSetup = qfalse; -static void WP_SaberSetupKeywordHash( void ) { +static void WP_SaberSetupKeywordHash(void) { int i; - memset( saberParseKeywordHash, 0, sizeof( saberParseKeywordHash ) ); - for ( i=0; saberParseKeywords[i].keyword; i++ ) - KeywordHash_Add( saberParseKeywordHash, &saberParseKeywords[i] ); + memset(saberParseKeywordHash, 0, sizeof(saberParseKeywordHash)); + for (i = 0; saberParseKeywords[i].keyword; i++) + KeywordHash_Add(saberParseKeywordHash, &saberParseKeywords[i]); hashSetup = qtrue; } -qboolean WP_SaberParseParms( const char *saberName, saberInfo_t *saber ) { - const char *token, *p; - char useSaber[SABER_NAME_LENGTH]; - qboolean triedDefault = qfalse; +qboolean WP_SaberParseParms(const char *saberName, saberInfo_t *saber) { + const char *token, *p; + char useSaber[SABER_NAME_LENGTH]; + qboolean triedDefault = qfalse; keywordHash_t *key; // make sure the hash table has been setup - if ( !hashSetup ) + if (!hashSetup) WP_SaberSetupKeywordHash(); - if ( !saber ) + if (!saber) return qfalse; - //Set defaults so that, if it fails, there's at least something there - WP_SaberSetDefaults( saber ); + // Set defaults so that, if it fails, there's at least something there + WP_SaberSetDefaults(saber); - if ( !VALIDSTRING( saberName ) ) { - Q_strncpyz( useSaber, DEFAULT_SABER, sizeof( useSaber ) ); + if (!VALIDSTRING(saberName)) { + Q_strncpyz(useSaber, DEFAULT_SABER, sizeof(useSaber)); triedDefault = qtrue; - } - else - Q_strncpyz( useSaber, saberName, sizeof( useSaber ) ); + } else + Q_strncpyz(useSaber, saberName, sizeof(useSaber)); - //try to parse it out + // try to parse it out p = saberParms; - COM_BeginParseSession( "saberinfo" ); + COM_BeginParseSession("saberinfo"); // look for the right saber - while ( p ) { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) { - if ( !triedDefault ) { + while (p) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + if (!triedDefault) { // fall back to default and restart, should always be there p = saberParms; - COM_BeginParseSession( "saberinfo" ); - Q_strncpyz( useSaber, DEFAULT_SABER, sizeof( useSaber ) ); + COM_BeginParseSession("saberinfo"); + Q_strncpyz(useSaber, DEFAULT_SABER, sizeof(useSaber)); triedDefault = qtrue; - } - else + } else return qfalse; } - if ( !Q_stricmp( token, useSaber ) ) + if (!Q_stricmp(token, useSaber)) break; - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } // even the default saber isn't found? - if ( !p ) + if (!p) return qfalse; // got the name we're using for sure - Q_strncpyz( saber->name, useSaber, sizeof( saber->name ) ); + Q_strncpyz(saber->name, useSaber, sizeof(saber->name)); - if ( BG_ParseLiteral( &p, "{" ) ) + if (BG_ParseLiteral(&p, "{")) return qfalse; // parse the saber info block - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s' (WP_SaberParseParms)\n", useSaber ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s' (WP_SaberParseParms)\n", useSaber); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) + if (!Q_stricmp(token, "}")) break; - key = KeywordHash_Find( saberParseKeywordHash, token ); - if ( key ) { - key->func( saber, &p ); + key = KeywordHash_Find(saberParseKeywordHash, token); + if (key) { + key->func(saber, &p); continue; } - Com_Printf( "WARNING: unknown keyword '%s' while parsing saber '%s'\n", token, useSaber ); - SkipRestOfLine( &p ); + Com_Printf("WARNING: unknown keyword '%s' while parsing saber '%s'\n", token, useSaber); + SkipRestOfLine(&p); } - //FIXME: precache the saberModel(s)? + // FIXME: precache the saberModel(s)? return qtrue; } -qboolean WP_SaberParseParm( const char *saberName, const char *parmname, char *saberData ) -{ - const char *token; - const char *value; - const char *p; +qboolean WP_SaberParseParm(const char *saberName, const char *parmname, char *saberData) { + const char *token; + const char *value; + const char *p; - if ( !saberName || !saberName[0] ) - { + if (!saberName || !saberName[0]) { return qfalse; } - //try to parse it out + // try to parse it out p = saberParms; COM_BeginParseSession("saberinfo"); // look for the right saber - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { return qfalse; } - if ( !Q_stricmp( token, saberName ) ) - { + if (!Q_stricmp(token, saberName)) { break; } - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } - if ( !p ) - { + if (!p) { return qfalse; } - if ( BG_ParseLiteral( &p, "{" ) ) - { + if (BG_ParseLiteral(&p, "{")) { return qfalse; } // parse the saber info block - while ( 1 ) - { - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing '%s'\n", saberName ); + while (1) { + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing '%s'\n", saberName); return qfalse; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - if ( !Q_stricmp( token, parmname ) ) - { - if ( COM_ParseString( &p, &value ) ) - { + if (!Q_stricmp(token, parmname)) { + if (COM_ParseString(&p, &value)) { continue; } - strcpy( saberData, value ); + strcpy(saberData, value); return qtrue; } - SkipRestOfLine( &p ); + SkipRestOfLine(&p); continue; } return qfalse; } -qboolean WP_SaberValidForPlayerInMP( const char *saberName ) -{ - char allowed [8]={0}; - if ( !WP_SaberParseParm( saberName, "notInMP", allowed ) ) - {//not defined, default is yes +qboolean WP_SaberValidForPlayerInMP(const char *saberName) { + char allowed[8] = {0}; + if (!WP_SaberParseParm(saberName, "notInMP", allowed)) { // not defined, default is yes return qtrue; } - if ( !allowed[0] ) - {//not defined, default is yes + if (!allowed[0]) { // not defined, default is yes return qtrue; - } - else - {//return value - return ((qboolean)(atoi(allowed)==0)); + } else { // return value + return ((qboolean)(atoi(allowed) == 0)); } } -void WP_RemoveSaber( saberInfo_t *sabers, int saberNum ) -{ - if ( !sabers ) - { +void WP_RemoveSaber(saberInfo_t *sabers, int saberNum) { + if (!sabers) { return; } - //reset everything for this saber just in case - WP_SaberSetDefaults( &sabers[saberNum] ); + // reset everything for this saber just in case + WP_SaberSetDefaults(&sabers[saberNum]); strcpy(sabers[saberNum].name, "none"); sabers[saberNum].model[0] = 0; - //ent->client->ps.dualSabers = qfalse; + // ent->client->ps.dualSabers = qfalse; BG_SI_Deactivate(&sabers[saberNum]); BG_SI_SetLength(&sabers[saberNum], 0.0f); -// if ( ent->weaponModel[saberNum] > 0 ) -// { -// trap->G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[saberNum] ); -// ent->weaponModel[saberNum] = -1; -// } -// if ( saberNum == 1 ) -// { -// ent->client->ps.dualSabers = qfalse; -// } -} - -void WP_SetSaber( int entNum, saberInfo_t *sabers, int saberNum, const char *saberName ) -{ - if ( !sabers ) - { - return; - } - if ( Q_stricmp( "none", saberName ) == 0 || Q_stricmp( "remove", saberName ) == 0 ) - { - if (saberNum != 0) - { //can't remove saber 0 ever - WP_RemoveSaber( sabers, saberNum ); + // if ( ent->weaponModel[saberNum] > 0 ) + // { + // trap->G2API_RemoveGhoul2Model( ent->ghoul2, ent->weaponModel[saberNum] ); + // ent->weaponModel[saberNum] = -1; + // } + // if ( saberNum == 1 ) + // { + // ent->client->ps.dualSabers = qfalse; + // } +} + +void WP_SetSaber(int entNum, saberInfo_t *sabers, int saberNum, const char *saberName) { + if (!sabers) { + return; + } + if (Q_stricmp("none", saberName) == 0 || Q_stricmp("remove", saberName) == 0) { + if (saberNum != 0) { // can't remove saber 0 ever + WP_RemoveSaber(sabers, saberNum); } return; } - if ( entNum < MAX_CLIENTS && - !WP_SaberValidForPlayerInMP( saberName ) ) - { - WP_SaberParseParms( DEFAULT_SABER, &sabers[saberNum] );//get saber info - } - else - { - WP_SaberParseParms( saberName, &sabers[saberNum] );//get saber info + if (entNum < MAX_CLIENTS && !WP_SaberValidForPlayerInMP(saberName)) { + WP_SaberParseParms(DEFAULT_SABER, &sabers[saberNum]); // get saber info + } else { + WP_SaberParseParms(saberName, &sabers[saberNum]); // get saber info } - if ((sabers[1].saberFlags&SFL_TWO_HANDED)) - {//not allowed to use a 2-handed saber as second saber - WP_RemoveSaber( sabers, 1 ); + if ((sabers[1].saberFlags & SFL_TWO_HANDED)) { // not allowed to use a 2-handed saber as second saber + WP_RemoveSaber(sabers, 1); return; - } - else if ((sabers[0].saberFlags&SFL_TWO_HANDED) && - sabers[1].model[0]) - { //you can't use a two-handed saber with a second saber, so remove saber 2 - WP_RemoveSaber( sabers, 1 ); + } else if ((sabers[0].saberFlags & SFL_TWO_HANDED) && sabers[1].model[0]) { // you can't use a two-handed saber with a second saber, so remove saber 2 + WP_RemoveSaber(sabers, 1); return; } } -void WP_SaberSetColor( saberInfo_t *sabers, int saberNum, int bladeNum, char *colorName ) -{ - if ( !sabers ) - { +void WP_SaberSetColor(saberInfo_t *sabers, int saberNum, int bladeNum, char *colorName) { + if (!sabers) { return; } - sabers[saberNum].blade[bladeNum].color = TranslateSaberColor( colorName ); + sabers[saberNum].blade[bladeNum].color = TranslateSaberColor(colorName); } static char bgSaberParseTBuffer[MAX_SABER_DATA_SIZE]; -void WP_SaberLoadParms( void ) -{ - int len, totallen, saberExtFNLen, fileCnt, i; - char *holdChar, *marker; - char saberExtensionListBuf[2048]; // The list of file names read in - fileHandle_t f; +void WP_SaberLoadParms(void) { + int len, totallen, saberExtFNLen, fileCnt, i; + char *holdChar, *marker; + char saberExtensionListBuf[2048]; // The list of file names read in + fileHandle_t f; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = len; - marker = saberParms+totallen; + marker = saberParms + totallen; *marker = 0; - //now load in the extra .sab extensions - fileCnt = trap->FS_GetFileList( "ext_data/sabers", ".sab", saberExtensionListBuf, sizeof( saberExtensionListBuf ) ); + // now load in the extra .sab extensions + fileCnt = trap->FS_GetFileList("ext_data/sabers", ".sab", saberExtensionListBuf, sizeof(saberExtensionListBuf)); holdChar = saberExtensionListBuf; - for ( i=0; iFS_Open( va( "ext_data/sabers/%s", holdChar ), &f, FS_READ ); + len = trap->FS_Open(va("ext_data/sabers/%s", holdChar), &f, FS_READ); - if ( !f ) { - Com_Printf( "WP_SaberLoadParms: error reading file: %s\n", holdChar ); + if (!f) { + Com_Printf("WP_SaberLoadParms: error reading file: %s\n", holdChar); continue; } - if ( (totallen + len+1) >= MAX_SABER_DATA_SIZE ) { - trap->FS_Close( f ); + if ((totallen + len + 1) >= MAX_SABER_DATA_SIZE) { + trap->FS_Close(f); #ifdef UI_BUILD - Com_Error( ERR_FATAL, "WP_SaberLoadParms: Saber extensions (*.sab) are too large!\nRan out of space before reading %s", holdChar ); + Com_Error(ERR_FATAL, "WP_SaberLoadParms: Saber extensions (*.sab) are too large!\nRan out of space before reading %s", holdChar); #else - Com_Error( ERR_DROP, "WP_SaberLoadParms: Saber extensions (*.sab) are too large!\nRan out of space before reading %s", holdChar ); + Com_Error(ERR_DROP, "WP_SaberLoadParms: Saber extensions (*.sab) are too large!\nRan out of space before reading %s", holdChar); #endif } trap->FS_Read(bgSaberParseTBuffer, len, f); bgSaberParseTBuffer[len] = 0; - len = COM_Compress( bgSaberParseTBuffer ); + len = COM_Compress(bgSaberParseTBuffer); - Q_strcat( marker, MAX_SABER_DATA_SIZE-totallen, bgSaberParseTBuffer ); + Q_strcat(marker, MAX_SABER_DATA_SIZE - totallen, bgSaberParseTBuffer); trap->FS_Close(f); - //get around the stupid problem of not having an endline at the bottom - //of a sab file -rww - Q_strcat(marker, MAX_SABER_DATA_SIZE-totallen, "\n"); + // get around the stupid problem of not having an endline at the bottom + // of a sab file -rww + Q_strcat(marker, MAX_SABER_DATA_SIZE - totallen, "\n"); len++; totallen += len; - marker = saberParms+totallen; + marker = saberParms + totallen; } } #ifdef UI_BUILD -qboolean WP_IsSaberTwoHanded( const char *saberName ) -{ +qboolean WP_IsSaberTwoHanded(const char *saberName) { int twoHanded; - char twoHandedString[8]={0}; - WP_SaberParseParm( saberName, "twoHanded", twoHandedString ); - if ( !twoHandedString[0] ) - {//not defined defaults to "no" + char twoHandedString[8] = {0}; + WP_SaberParseParm(saberName, "twoHanded", twoHandedString); + if (!twoHandedString[0]) { // not defined defaults to "no" return qfalse; } - twoHanded = atoi( twoHandedString ); - return ((qboolean)(twoHanded!=0)); + twoHanded = atoi(twoHandedString); + return ((qboolean)(twoHanded != 0)); } -void WP_SaberGetHiltInfo( const char *singleHilts[MAX_SABER_HILTS], const char *staffHilts[MAX_SABER_HILTS] ) -{ - int numSingleHilts = 0, numStaffHilts = 0; - const char *saberName; - const char *token; - const char *p; +void WP_SaberGetHiltInfo(const char *singleHilts[MAX_SABER_HILTS], const char *staffHilts[MAX_SABER_HILTS]) { + int numSingleHilts = 0, numStaffHilts = 0; + const char *saberName; + const char *token; + const char *p; - //go through all the loaded sabers and put the valid ones in the proper list + // go through all the loaded sabers and put the valid ones in the proper list p = saberParms; COM_BeginParseSession("saberlist"); // look for a saber - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//invalid name + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // invalid name continue; } - saberName = String_Alloc( token ); - //see if there's a "{" on the next line - SkipRestOfLine( &p ); + saberName = String_Alloc(token); + // see if there's a "{" on the next line + SkipRestOfLine(&p); - if ( BG_ParseLiteralSilent( &p, "{" ) ) - {//nope, not a name, keep looking + if (BG_ParseLiteralSilent(&p, "{")) { // nope, not a name, keep looking continue; } - //this is a saber name - if ( !WP_SaberValidForPlayerInMP( saberName ) ) - { - SkipBracedSection( &p, 0 ); + // this is a saber name + if (!WP_SaberValidForPlayerInMP(saberName)) { + SkipBracedSection(&p, 0); continue; } - if ( WP_IsSaberTwoHanded( saberName ) ) - { - if ( numStaffHilts < MAX_SABER_HILTS-1 )//-1 because we have to NULL terminate the list + if (WP_IsSaberTwoHanded(saberName)) { + if (numStaffHilts < MAX_SABER_HILTS - 1) //-1 because we have to NULL terminate the list { staffHilts[numStaffHilts++] = saberName; + } else { + Com_Printf("WARNING: too many two-handed sabers, ignoring saber '%s'\n", saberName); } - else - { - Com_Printf( "WARNING: too many two-handed sabers, ignoring saber '%s'\n", saberName ); - } - } - else - { - if ( numSingleHilts < MAX_SABER_HILTS-1 )//-1 because we have to NULL terminate the list + } else { + if (numSingleHilts < MAX_SABER_HILTS - 1) //-1 because we have to NULL terminate the list { singleHilts[numSingleHilts++] = saberName; - } - else - { - Com_Printf( "WARNING: too many one-handed sabers, ignoring saber '%s'\n", saberName ); + } else { + Com_Printf("WARNING: too many one-handed sabers, ignoring saber '%s'\n", saberName); } } - //skip the whole braced section and move on to the next entry - SkipBracedSection( &p, 0 ); + // skip the whole braced section and move on to the next entry + SkipBracedSection(&p, 0); } - //null terminate the list so the UI code knows where to stop listing them + // null terminate the list so the UI code knows where to stop listing them singleHilts[numSingleHilts] = NULL; staffHilts[numStaffHilts] = NULL; } @@ -2404,34 +2366,28 @@ and BLADE indicates it was under bladeinfo. */ //--------------------------------------- -void BG_BLADE_ActivateTrail ( bladeInfo_t *blade, float duration ) -{ +void BG_BLADE_ActivateTrail(bladeInfo_t *blade, float duration) { blade->trail.inAction = qtrue; blade->trail.duration = duration; } -void BG_BLADE_DeactivateTrail ( bladeInfo_t *blade, float duration ) -{ +void BG_BLADE_DeactivateTrail(bladeInfo_t *blade, float duration) { blade->trail.inAction = qfalse; blade->trail.duration = duration; } //--------------------------------------- -void BG_SI_Activate( saberInfo_t *saber ) -{ +void BG_SI_Activate(saberInfo_t *saber) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { + for (i = 0; i < saber->numBlades; i++) { saber->blade[i].active = qtrue; } } -void BG_SI_Deactivate( saberInfo_t *saber ) -{ +void BG_SI_Deactivate(saberInfo_t *saber) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { + for (i = 0; i < saber->numBlades; i++) { saber->blade[i].active = qfalse; } } @@ -2441,174 +2397,137 @@ void BG_SI_Deactivate( saberInfo_t *saber ) // [in] int iBlade Which Blade to activate. // [in] bool bActive Whether to activate it (default true), or deactivate it (false). // [return] void -void BG_SI_BladeActivate( saberInfo_t *saber, int iBlade, qboolean bActive ) -{ +void BG_SI_BladeActivate(saberInfo_t *saber, int iBlade, qboolean bActive) { // Validate blade ID/Index. - if ( iBlade < 0 || iBlade >= saber->numBlades ) + if (iBlade < 0 || iBlade >= saber->numBlades) return; saber->blade[iBlade].active = bActive; } -qboolean BG_SI_Active(saberInfo_t *saber) -{ +qboolean BG_SI_Active(saberInfo_t *saber) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { - if ( saber->blade[i].active ) - { + for (i = 0; i < saber->numBlades; i++) { + if (saber->blade[i].active) { return qtrue; } } return qfalse; } -void BG_SI_SetLength( saberInfo_t *saber, float length ) -{ +void BG_SI_SetLength(saberInfo_t *saber, float length) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { + for (i = 0; i < saber->numBlades; i++) { saber->blade[i].length = length; } } -//not in sp, added it for my own convenience -void BG_SI_SetDesiredLength(saberInfo_t *saber, float len, int bladeNum ) -{ +// not in sp, added it for my own convenience +void BG_SI_SetDesiredLength(saberInfo_t *saber, float len, int bladeNum) { int i, startBlade = 0, maxBlades = saber->numBlades; - if ( bladeNum >= 0 && bladeNum < saber->numBlades) - {//doing this on a specific blade + if (bladeNum >= 0 && bladeNum < saber->numBlades) { // doing this on a specific blade startBlade = bladeNum; - maxBlades = bladeNum+1; + maxBlades = bladeNum + 1; } - for (i = startBlade; i < maxBlades; i++) - { + for (i = startBlade; i < maxBlades; i++) { saber->blade[i].desiredLength = len; } } -//also not in sp, added it for my own convenience -void BG_SI_SetLengthGradual(saberInfo_t *saber, int time) -{ +// also not in sp, added it for my own convenience +void BG_SI_SetLengthGradual(saberInfo_t *saber, int time) { int i; float amt, dLen; - for (i = 0; i < saber->numBlades; i++) - { + for (i = 0; i < saber->numBlades; i++) { dLen = saber->blade[i].desiredLength; - if (dLen == -1) - { //assume we want max blade len + if (dLen == -1) { // assume we want max blade len dLen = saber->blade[i].lengthMax; } - if (saber->blade[i].length == dLen) - { + if (saber->blade[i].length == dLen) { continue; } - if (saber->blade[i].length == saber->blade[i].lengthMax || - saber->blade[i].length == 0) - { + if (saber->blade[i].length == saber->blade[i].lengthMax || saber->blade[i].length == 0) { saber->blade[i].extendDebounce = time; - if (saber->blade[i].length == 0) - { + if (saber->blade[i].length == 0) { saber->blade[i].length++; - } - else - { + } else { saber->blade[i].length--; } } - amt = (time - saber->blade[i].extendDebounce)*0.01; + amt = (time - saber->blade[i].extendDebounce) * 0.01; - if (amt < 0.2f) - { + if (amt < 0.2f) { amt = 0.2f; } - if (saber->blade[i].length < dLen) - { + if (saber->blade[i].length < dLen) { saber->blade[i].length += amt; - if (saber->blade[i].length > dLen) - { + if (saber->blade[i].length > dLen) { saber->blade[i].length = dLen; } - if (saber->blade[i].length > saber->blade[i].lengthMax) - { + if (saber->blade[i].length > saber->blade[i].lengthMax) { saber->blade[i].length = saber->blade[i].lengthMax; } - } - else if (saber->blade[i].length > dLen) - { + } else if (saber->blade[i].length > dLen) { saber->blade[i].length -= amt; - if (saber->blade[i].length < dLen) - { + if (saber->blade[i].length < dLen) { saber->blade[i].length = dLen; } - if (saber->blade[i].length < 0) - { + if (saber->blade[i].length < 0) { saber->blade[i].length = 0; } } } } -float BG_SI_Length(saberInfo_t *saber) -{//return largest length +float BG_SI_Length(saberInfo_t *saber) { // return largest length int len1 = 0; int i; - for ( i = 0; i < saber->numBlades; i++ ) - { - if ( saber->blade[i].length > len1 ) - { + for (i = 0; i < saber->numBlades; i++) { + if (saber->blade[i].length > len1) { len1 = saber->blade[i].length; } } return len1; } -float BG_SI_LengthMax(saberInfo_t *saber) -{ +float BG_SI_LengthMax(saberInfo_t *saber) { int len1 = 0; int i; - for ( i = 0; i < saber->numBlades; i++ ) - { - if ( saber->blade[i].lengthMax > len1 ) - { + for (i = 0; i < saber->numBlades; i++) { + if (saber->blade[i].lengthMax > len1) { len1 = saber->blade[i].lengthMax; } } return len1; } -void BG_SI_ActivateTrail ( saberInfo_t *saber, float duration ) -{ +void BG_SI_ActivateTrail(saberInfo_t *saber, float duration) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { - //saber->blade[i].ActivateTrail( duration ); + for (i = 0; i < saber->numBlades; i++) { + // saber->blade[i].ActivateTrail( duration ); BG_BLADE_ActivateTrail(&saber->blade[i], duration); } } -void BG_SI_DeactivateTrail ( saberInfo_t *saber, float duration ) -{ +void BG_SI_DeactivateTrail(saberInfo_t *saber, float duration) { int i; - for ( i = 0; i < saber->numBlades; i++ ) - { - //saber->blade[i].DeactivateTrail( duration ); + for (i = 0; i < saber->numBlades; i++) { + // saber->blade[i].DeactivateTrail( duration ); BG_BLADE_DeactivateTrail(&saber->blade[i], duration); } } - diff --git a/codemp/game/bg_saga.c b/codemp/game/bg_saga.c index d67e339d80..fe830c47df 100644 --- a/codemp/game/bg_saga.c +++ b/codemp/game/bg_saga.c @@ -35,17 +35,17 @@ along with this program; if not, see . #include "bg_weapons.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif -#define SIEGECHAR_TAB 9 //perhaps a bit hacky, but I don't think there's any define existing for "tab" +#define SIEGECHAR_TAB 9 // perhaps a bit hacky, but I don't think there's any define existing for "tab" -char siege_info[MAX_SIEGE_INFO_SIZE]; -int siege_valid = 0; +char siege_info[MAX_SIEGE_INFO_SIZE]; +int siege_valid = 0; siegeTeam_t *team1Theme = NULL; siegeTeam_t *team2Theme = NULL; @@ -56,145 +56,115 @@ int bgNumSiegeClasses = 0; siegeTeam_t bgSiegeTeams[MAX_SIEGE_TEAMS]; int bgNumSiegeTeams = 0; -//class flags -stringID_table_t bgSiegeClassFlagNames[] = -{ - ENUM2STRING(CFL_MORESABERDMG), - ENUM2STRING(CFL_STRONGAGAINSTPHYSICAL), - ENUM2STRING(CFL_FASTFORCEREGEN), - ENUM2STRING(CFL_STATVIEWER), - ENUM2STRING(CFL_HEAVYMELEE), - ENUM2STRING(CFL_SINGLE_ROCKET), - ENUM2STRING(CFL_CUSTOMSKEL), - ENUM2STRING(CFL_EXTRA_AMMO), - {"", -1} -}; - -//saber stances -stringID_table_t StanceTable[] = -{ - ENUM2STRING(SS_NONE), - ENUM2STRING(SS_FAST), - ENUM2STRING(SS_MEDIUM), - ENUM2STRING(SS_STRONG), - ENUM2STRING(SS_DESANN), - ENUM2STRING(SS_TAVION), - ENUM2STRING(SS_DUAL), - ENUM2STRING(SS_STAFF), - {"", 0} -}; - -//Weapon and force power tables are also used in NPC parsing code and some other places. -stringID_table_t WPTable[] = -{ - {"NULL",WP_NONE}, - ENUM2STRING(WP_NONE), - // Player weapons - ENUM2STRING(WP_STUN_BATON), - ENUM2STRING(WP_MELEE), - ENUM2STRING(WP_SABER), - ENUM2STRING(WP_BRYAR_PISTOL), - {"WP_BLASTER_PISTOL", WP_BRYAR_PISTOL}, - ENUM2STRING(WP_BLASTER), - ENUM2STRING(WP_DISRUPTOR), - ENUM2STRING(WP_BOWCASTER), - ENUM2STRING(WP_REPEATER), - ENUM2STRING(WP_DEMP2), - ENUM2STRING(WP_FLECHETTE), - ENUM2STRING(WP_ROCKET_LAUNCHER), - ENUM2STRING(WP_THERMAL), - ENUM2STRING(WP_TRIP_MINE), - ENUM2STRING(WP_DET_PACK), - ENUM2STRING(WP_CONCUSSION), - ENUM2STRING(WP_BRYAR_OLD), - ENUM2STRING(WP_EMPLACED_GUN), - ENUM2STRING(WP_TURRET), - {"", 0} -}; - -stringID_table_t FPTable[] = -{ - ENUM2STRING(FP_HEAL), - ENUM2STRING(FP_LEVITATION), - ENUM2STRING(FP_SPEED), - ENUM2STRING(FP_PUSH), - ENUM2STRING(FP_PULL), - ENUM2STRING(FP_TELEPATHY), - ENUM2STRING(FP_GRIP), - ENUM2STRING(FP_LIGHTNING), - ENUM2STRING(FP_RAGE), - ENUM2STRING(FP_PROTECT), - ENUM2STRING(FP_ABSORB), - ENUM2STRING(FP_TEAM_HEAL), - ENUM2STRING(FP_TEAM_FORCE), - ENUM2STRING(FP_DRAIN), - ENUM2STRING(FP_SEE), - ENUM2STRING(FP_SABER_OFFENSE), - ENUM2STRING(FP_SABER_DEFENSE), - ENUM2STRING(FP_SABERTHROW), - {"", -1} -}; - -stringID_table_t HoldableTable[] = -{ - ENUM2STRING(HI_NONE), - - ENUM2STRING(HI_SEEKER), - ENUM2STRING(HI_SHIELD), - ENUM2STRING(HI_MEDPAC), - ENUM2STRING(HI_MEDPAC_BIG), - ENUM2STRING(HI_BINOCULARS), - ENUM2STRING(HI_SENTRY_GUN), - ENUM2STRING(HI_JETPACK), - ENUM2STRING(HI_HEALTHDISP), - ENUM2STRING(HI_AMMODISP), - ENUM2STRING(HI_EWEB), - ENUM2STRING(HI_CLOAK), - - {"", -1} -}; - -stringID_table_t PowerupTable[] = -{ - ENUM2STRING(PW_NONE), - #ifdef BASE_COMPAT - ENUM2STRING(PW_QUAD), - ENUM2STRING(PW_BATTLESUIT), - #endif // BASE_COMPAT - ENUM2STRING(PW_PULL), - ENUM2STRING(PW_REDFLAG), - ENUM2STRING(PW_BLUEFLAG), - ENUM2STRING(PW_NEUTRALFLAG), - ENUM2STRING(PW_SHIELDHIT), - ENUM2STRING(PW_SPEEDBURST), - ENUM2STRING(PW_DISINT_4), - ENUM2STRING(PW_SPEED), - ENUM2STRING(PW_CLOAKED), - ENUM2STRING(PW_FORCE_ENLIGHTENED_LIGHT), - ENUM2STRING(PW_FORCE_ENLIGHTENED_DARK), - ENUM2STRING(PW_FORCE_BOON), - ENUM2STRING(PW_YSALAMIRI), - - {"", -1} -}; - +// class flags +stringID_table_t bgSiegeClassFlagNames[] = {ENUM2STRING(CFL_MORESABERDMG), + ENUM2STRING(CFL_STRONGAGAINSTPHYSICAL), + ENUM2STRING(CFL_FASTFORCEREGEN), + ENUM2STRING(CFL_STATVIEWER), + ENUM2STRING(CFL_HEAVYMELEE), + ENUM2STRING(CFL_SINGLE_ROCKET), + ENUM2STRING(CFL_CUSTOMSKEL), + ENUM2STRING(CFL_EXTRA_AMMO), + {"", -1}}; + +// saber stances +stringID_table_t StanceTable[] = {ENUM2STRING(SS_NONE), ENUM2STRING(SS_FAST), ENUM2STRING(SS_MEDIUM), + ENUM2STRING(SS_STRONG), ENUM2STRING(SS_DESANN), ENUM2STRING(SS_TAVION), + ENUM2STRING(SS_DUAL), ENUM2STRING(SS_STAFF), {"", 0}}; + +// Weapon and force power tables are also used in NPC parsing code and some other places. +stringID_table_t WPTable[] = {{"NULL", WP_NONE}, + ENUM2STRING(WP_NONE), + // Player weapons + ENUM2STRING(WP_STUN_BATON), + ENUM2STRING(WP_MELEE), + ENUM2STRING(WP_SABER), + ENUM2STRING(WP_BRYAR_PISTOL), + {"WP_BLASTER_PISTOL", WP_BRYAR_PISTOL}, + ENUM2STRING(WP_BLASTER), + ENUM2STRING(WP_DISRUPTOR), + ENUM2STRING(WP_BOWCASTER), + ENUM2STRING(WP_REPEATER), + ENUM2STRING(WP_DEMP2), + ENUM2STRING(WP_FLECHETTE), + ENUM2STRING(WP_ROCKET_LAUNCHER), + ENUM2STRING(WP_THERMAL), + ENUM2STRING(WP_TRIP_MINE), + ENUM2STRING(WP_DET_PACK), + ENUM2STRING(WP_CONCUSSION), + ENUM2STRING(WP_BRYAR_OLD), + ENUM2STRING(WP_EMPLACED_GUN), + ENUM2STRING(WP_TURRET), + {"", 0}}; + +stringID_table_t FPTable[] = {ENUM2STRING(FP_HEAL), + ENUM2STRING(FP_LEVITATION), + ENUM2STRING(FP_SPEED), + ENUM2STRING(FP_PUSH), + ENUM2STRING(FP_PULL), + ENUM2STRING(FP_TELEPATHY), + ENUM2STRING(FP_GRIP), + ENUM2STRING(FP_LIGHTNING), + ENUM2STRING(FP_RAGE), + ENUM2STRING(FP_PROTECT), + ENUM2STRING(FP_ABSORB), + ENUM2STRING(FP_TEAM_HEAL), + ENUM2STRING(FP_TEAM_FORCE), + ENUM2STRING(FP_DRAIN), + ENUM2STRING(FP_SEE), + ENUM2STRING(FP_SABER_OFFENSE), + ENUM2STRING(FP_SABER_DEFENSE), + ENUM2STRING(FP_SABERTHROW), + {"", -1}}; + +stringID_table_t HoldableTable[] = {ENUM2STRING(HI_NONE), + + ENUM2STRING(HI_SEEKER), + ENUM2STRING(HI_SHIELD), + ENUM2STRING(HI_MEDPAC), + ENUM2STRING(HI_MEDPAC_BIG), + ENUM2STRING(HI_BINOCULARS), + ENUM2STRING(HI_SENTRY_GUN), + ENUM2STRING(HI_JETPACK), + ENUM2STRING(HI_HEALTHDISP), + ENUM2STRING(HI_AMMODISP), + ENUM2STRING(HI_EWEB), + ENUM2STRING(HI_CLOAK), + + {"", -1}}; + +stringID_table_t PowerupTable[] = {ENUM2STRING(PW_NONE), +#ifdef BASE_COMPAT + ENUM2STRING(PW_QUAD), + ENUM2STRING(PW_BATTLESUIT), +#endif // BASE_COMPAT + ENUM2STRING(PW_PULL), + ENUM2STRING(PW_REDFLAG), + ENUM2STRING(PW_BLUEFLAG), + ENUM2STRING(PW_NEUTRALFLAG), + ENUM2STRING(PW_SHIELDHIT), + ENUM2STRING(PW_SPEEDBURST), + ENUM2STRING(PW_DISINT_4), + ENUM2STRING(PW_SPEED), + ENUM2STRING(PW_CLOAKED), + ENUM2STRING(PW_FORCE_ENLIGHTENED_LIGHT), + ENUM2STRING(PW_FORCE_ENLIGHTENED_DARK), + ENUM2STRING(PW_FORCE_BOON), + ENUM2STRING(PW_YSALAMIRI), + + {"", -1}}; //====================================== -//Parsing functions +// Parsing functions //====================================== -void BG_SiegeStripTabs(char *buf) -{ +void BG_SiegeStripTabs(char *buf) { int i = 0; int i_r = 0; - while (buf[i]) - { - if (buf[i] != SIEGECHAR_TAB) - { //not a tab, just stick it in + while (buf[i]) { + if (buf[i] != SIEGECHAR_TAB) { // not a tab, just stick it in buf[i_r] = buf[i]; - } - else - { //If it's a tab, convert it to a space. + } else { // If it's a tab, convert it to a space. buf[i_r] = ' '; } @@ -205,34 +175,24 @@ void BG_SiegeStripTabs(char *buf) buf[i_r] = '\0'; } -int BG_SiegeGetValueGroup(char *buf, char *group, char *outbuf) -{ +int BG_SiegeGetValueGroup(char *buf, char *group, char *outbuf) { int i = 0; int j; char checkGroup[4096]; qboolean isGroup; int parseGroups = 0; - while (buf[i]) - { - if (buf[i] != ' ' && buf[i] != '{' && buf[i] != '}' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB) - { //we're on a valid character - if (buf[i] == '/' && - buf[i+1] == '/') - { //this is a comment, so skip over it - while (buf[i] && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB) - { + while (buf[i]) { + if (buf[i] != ' ' && buf[i] != '{' && buf[i] != '}' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB) { // we're on a valid character + if (buf[i] == '/' && buf[i + 1] == '/') { // this is a comment, so skip over it + while (buf[i] && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB) { i++; } - } - else - { //parse to the next space/endline/eos and check this value against our group value. + } else { // parse to the next space/endline/eos and check this value against our group value. j = 0; - while (buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB && buf[i] != '{' && buf[i]) - { - if (buf[i] == '/' && buf[i+1] == '/') - { //hit a comment, break out. + while (buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB && buf[i] != '{' && buf[i]) { + if (buf[i] == '/' && buf[i + 1] == '/') { // hit a comment, break out. break; } @@ -242,75 +202,59 @@ int BG_SiegeGetValueGroup(char *buf, char *group, char *outbuf) } checkGroup[j] = 0; - //Make sure this is a group as opposed to a globally defined value. - if (buf[i] == '/' && buf[i+1] == '/') - { //stopped on a comment, so first parse to the end of it. - while (buf[i] && buf[i] != '\n' && buf[i] != '\r') - { + // Make sure this is a group as opposed to a globally defined value. + if (buf[i] == '/' && buf[i + 1] == '/') { // stopped on a comment, so first parse to the end of it. + while (buf[i] && buf[i] != '\n' && buf[i] != '\r') { i++; } - while (buf[i] == '\n' || buf[i] == '\r') - { + while (buf[i] == '\n' || buf[i] == '\r') { i++; } } - if (!buf[i]) - { + if (!buf[i]) { Com_Error(ERR_DROP, "Unexpected EOF while looking for group '%s'", group); } isGroup = qfalse; - while ( buf[i] && (buf[i] == ' ' || buf[i] == SIEGECHAR_TAB || buf[i] == '\n' || buf[i] == '\r') ) - { //parse to the next valid character + while (buf[i] && (buf[i] == ' ' || buf[i] == SIEGECHAR_TAB || buf[i] == '\n' || buf[i] == '\r')) { // parse to the next valid character i++; } - if (buf[i] == '{') - { //if the next valid character is an opening bracket, then this is indeed a group + if (buf[i] == '{') { // if the next valid character is an opening bracket, then this is indeed a group isGroup = qtrue; } - //Is this the one we want? - if (isGroup && !Q_stricmp(checkGroup, group)) - { //guess so. Parse until we hit the { indicating the beginning of the group. - while (buf[i] != '{' && buf[i]) - { + // Is this the one we want? + if (isGroup && !Q_stricmp(checkGroup, group)) { // guess so. Parse until we hit the { indicating the beginning of the group. + while (buf[i] != '{' && buf[i]) { i++; } - if (buf[i]) - { //We're at the start of the group now, so parse to the closing bracket. + if (buf[i]) { // We're at the start of the group now, so parse to the closing bracket. j = 0; parseGroups = 0; - while ((buf[i] != '}' || parseGroups) && buf[i]) - { - if (buf[i] == '{') - { //increment for the opening bracket. + while ((buf[i] != '}' || parseGroups) && buf[i]) { + if (buf[i] == '{') { // increment for the opening bracket. parseGroups++; - } - else if (buf[i] == '}') - { //decrement for the closing bracket + } else if (buf[i] == '}') { // decrement for the closing bracket parseGroups--; } - if (parseGroups < 0) - { //Syntax error, I guess. + if (parseGroups < 0) { // Syntax error, I guess. Com_Error(ERR_DROP, "Found a closing bracket without an opening bracket while looking for group '%s'", group); } if ((buf[i] != '{' || parseGroups > 1) && - (buf[i] != '}' || parseGroups > 0)) - { //don't put the start and end brackets for this group into the output buffer + (buf[i] != '}' || parseGroups > 0)) { // don't put the start and end brackets for this group into the output buffer outbuf[j] = buf[i]; j++; } - if (buf[i] == '}' && !parseGroups) - { //Alright, we can break out now. + if (buf[i] == '}' && !parseGroups) { // Alright, we can break out now. break; } @@ -318,137 +262,102 @@ int BG_SiegeGetValueGroup(char *buf, char *group, char *outbuf) } outbuf[j] = 0; - //Verify that we ended up on the closing bracket. - if (buf[i] != '}') - { + // Verify that we ended up on the closing bracket. + if (buf[i] != '}') { Com_Error(ERR_DROP, "Group '%s' is missing a closing bracket", group); } - //Strip the tabs so we're friendly for value parsing. + // Strip the tabs so we're friendly for value parsing. BG_SiegeStripTabs(outbuf); - return 1; //we got it, so return 1. - } - else - { + return 1; // we got it, so return 1. + } else { Com_Error(ERR_DROP, "Error parsing group in file, unexpected EOF before opening bracket while looking for group '%s'", group); } - } - else if (!isGroup) - { //if it wasn't a group, parse to the end of the line - while (buf[i] && buf[i] != '\n' && buf[i] != '\r') - { + } else if (!isGroup) { // if it wasn't a group, parse to the end of the line + while (buf[i] && buf[i] != '\n' && buf[i] != '\r') { i++; } - } - else - { //this was a group but we not the one we wanted to find, so parse by it. + } else { // this was a group but we not the one we wanted to find, so parse by it. parseGroups = 0; - while (buf[i] && (buf[i] != '}' || parseGroups)) - { - if (buf[i] == '{') - { + while (buf[i] && (buf[i] != '}' || parseGroups)) { + if (buf[i] == '{') { parseGroups++; - } - else if (buf[i] == '}') - { + } else if (buf[i] == '}') { parseGroups--; } - if (parseGroups < 0) - { //Syntax error, I guess. + if (parseGroups < 0) { // Syntax error, I guess. Com_Error(ERR_DROP, "Found a closing bracket without an opening bracket while looking for group '%s'", group); } - if (buf[i] == '}' && !parseGroups) - { //Alright, we can break out now. + if (buf[i] == '}' && !parseGroups) { // Alright, we can break out now. break; } i++; } - if (buf[i] != '}') - { + if (buf[i] != '}') { Com_Error(ERR_DROP, "Found an opening bracket without a matching closing bracket while looking for group '%s'", group); } i++; } } - } - else if (buf[i] == '{') - { //we're in a group that isn't the one we want, so parse to the end. + } else if (buf[i] == '{') { // we're in a group that isn't the one we want, so parse to the end. parseGroups = 0; - while (buf[i] && (buf[i] != '}' || parseGroups)) - { - if (buf[i] == '{') - { + while (buf[i] && (buf[i] != '}' || parseGroups)) { + if (buf[i] == '{') { parseGroups++; - } - else if (buf[i] == '}') - { + } else if (buf[i] == '}') { parseGroups--; } - if (parseGroups < 0) - { //Syntax error, I guess. + if (parseGroups < 0) { // Syntax error, I guess. Com_Error(ERR_DROP, "Found a closing bracket without an opening bracket while looking for group '%s'", group); } - if (buf[i] == '}' && !parseGroups) - { //Alright, we can break out now. + if (buf[i] == '}' && !parseGroups) { // Alright, we can break out now. break; } i++; } - if (buf[i] != '}') - { + if (buf[i] != '}') { Com_Error(ERR_DROP, "Found an opening bracket without a matching closing bracket while looking for group '%s'", group); } } - if (!buf[i]) - { + if (!buf[i]) { break; } i++; } - return 0; //guess we never found it. + return 0; // guess we never found it. } -int BG_SiegeGetPairedValue(char *buf, char *key, char *outbuf) -{ +int BG_SiegeGetPairedValue(char *buf, char *key, char *outbuf) { int i = 0; int j; int k; char checkKey[4096]; - while (buf[i]) - { - if (buf[i] != ' ' && buf[i] != '{' && buf[i] != '}' && buf[i] != '\n' && buf[i] != '\r') - { //we're on a valid character - if (buf[i] == '/' && - buf[i+1] == '/') - { //this is a comment, so skip over it - while (buf[i] && buf[i] != '\n' && buf[i] != '\r') - { + while (buf[i]) { + if (buf[i] != ' ' && buf[i] != '{' && buf[i] != '}' && buf[i] != '\n' && buf[i] != '\r') { // we're on a valid character + if (buf[i] == '/' && buf[i + 1] == '/') { // this is a comment, so skip over it + while (buf[i] && buf[i] != '\n' && buf[i] != '\r') { i++; } - } - else - { //parse to the next space/endline/eos and check this value against our key value. + } else { // parse to the next space/endline/eos and check this value against our key value. j = 0; - while (buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB && buf[i]) - { - if (buf[i] == '/' && buf[i+1] == '/') - { //hit a comment, break out. + while (buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r' && buf[i] != SIEGECHAR_TAB && buf[i]) { + if (buf[i] == '/' && buf[i + 1] == '/') { // hit a comment, break out. break; } @@ -460,133 +369,103 @@ int BG_SiegeGetPairedValue(char *buf, char *key, char *outbuf) k = i; - while (buf[k] && (buf[k] == ' ' || buf[k] == '\n' || buf[k] == '\r')) - { + while (buf[k] && (buf[k] == ' ' || buf[k] == '\n' || buf[k] == '\r')) { k++; } - if (buf[k] == '{') - { //this is not the start of a value but rather of a group. We don't want to look in subgroups so skip over the whole thing. + if (buf[k] == '{') { // this is not the start of a value but rather of a group. We don't want to look in subgroups so skip over the whole thing. int openB = 0; - while (buf[i] && (buf[i] != '}' || openB)) - { - if (buf[i] == '{') - { + while (buf[i] && (buf[i] != '}' || openB)) { + if (buf[i] == '{') { openB++; - } - else if (buf[i] == '}') - { + } else if (buf[i] == '}') { openB--; } - if (openB < 0) - { + if (openB < 0) { Com_Error(ERR_DROP, "Unexpected closing bracket (too many) while parsing to end of group '%s'", checkKey); } - if (buf[i] == '}' && !openB) - { //this is the end of the group + if (buf[i] == '}' && !openB) { // this is the end of the group break; } i++; } - if (buf[i] == '}') - { + if (buf[i] == '}') { i++; } - } - else - { - //Is this the one we want? - if (buf[i] != '/' || buf[i+1] != '/') - { //make sure we didn't stop on a comment, if we did then this is considered an error in the file. - if (!Q_stricmp(checkKey, key)) - { //guess so. Parse along to the next valid character, then put that into the output buffer and return 1. - while ((buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r' || buf[i] == SIEGECHAR_TAB) && buf[i]) - { + } else { + // Is this the one we want? + if (buf[i] != '/' || buf[i + 1] != '/') { // make sure we didn't stop on a comment, if we did then this is considered an error in the file. + if (!Q_stricmp(checkKey, key)) { // guess so. Parse along to the next valid character, then put that into the output buffer and + // return 1. + while ((buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r' || buf[i] == SIEGECHAR_TAB) && buf[i]) { i++; } - if (buf[i]) - { //We're at the start of the value now. + if (buf[i]) { // We're at the start of the value now. qboolean parseToQuote = qfalse; - if (buf[i] == '\"') - { //if the value is in quotes, then stop at the next quote instead of ' ' + if (buf[i] == '\"') { // if the value is in quotes, then stop at the next quote instead of ' ' i++; parseToQuote = qtrue; } j = 0; - while ( ((!parseToQuote && buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r') || (parseToQuote && buf[i] != '\"')) ) - { + while (((!parseToQuote && buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\r') || (parseToQuote && buf[i] != '\"'))) { if (buf[i] == '/' && - buf[i+1] == '/') - { //hit a comment after the value? This isn't an ideal way to be writing things, but we'll support it anyway. + buf[i + 1] == + '/') { // hit a comment after the value? This isn't an ideal way to be writing things, but we'll support it anyway. break; } outbuf[j] = buf[i]; j++; i++; - if (!buf[i]) - { - if (parseToQuote) - { + if (!buf[i]) { + if (parseToQuote) { Com_Error(ERR_DROP, "Unexpected EOF while looking for endquote, error finding paired value for '%s'", key); - } - else - { + } else { Com_Error(ERR_DROP, "Unexpected EOF while looking for space or endline, error finding paired value for '%s'", key); } } } outbuf[j] = 0; - return 1; //we got it, so return 1. - } - else - { + return 1; // we got it, so return 1. + } else { Com_Error(ERR_DROP, "Error parsing file, unexpected EOF while looking for valud '%s'", key); } - } - else - { //if that wasn't the desired key, then make sure we parse to the end of the line, so we don't mistake a value for a key - while (buf[i] && buf[i] != '\n') - { + } else { // if that wasn't the desired key, then make sure we parse to the end of the line, so we don't mistake a value for a key + while (buf[i] && buf[i] != '\n') { i++; } } - } - else - { + } else { Com_Error(ERR_DROP, "Error parsing file, found comment, expected value for '%s'", key); } } } } - if (!buf[i]) - { + if (!buf[i]) { break; } i++; } - return 0; //guess we never found it. + return 0; // guess we never found it. } //====================================== -//End parsing functions +// End parsing functions //====================================== - //====================================== -//Class loading functions +// Class loading functions //====================================== -void BG_SiegeTranslateForcePowers(char *buf, siegeClass_t *siegeClass) -{ +void BG_SiegeTranslateForcePowers(char *buf, siegeClass_t *siegeClass) { char checkPower[1024]; char checkLevel[256]; int l = 0; @@ -597,56 +476,44 @@ void BG_SiegeTranslateForcePowers(char *buf, siegeClass_t *siegeClass) qboolean allPowers = qfalse; qboolean noPowers = qfalse; - if (!Q_stricmp(buf, "FP_ALL")) - { //this is a special case, just give us all the powers on level 3 + if (!Q_stricmp(buf, "FP_ALL")) { // this is a special case, just give us all the powers on level 3 allPowers = qtrue; } - if (buf[0] == '0' && !buf[1]) - { //no powers then + if (buf[0] == '0' && !buf[1]) { // no powers then noPowers = qtrue; } - //First clear out the powers, or in the allPowers case, give us all level 3. - while (i < NUM_FORCE_POWERS) - { - if (allPowers) - { + // First clear out the powers, or in the allPowers case, give us all level 3. + while (i < NUM_FORCE_POWERS) { + if (allPowers) { siegeClass->forcePowerLevels[i] = FORCE_LEVEL_3; - } - else - { + } else { siegeClass->forcePowerLevels[i] = 0; } i++; } - if (allPowers || noPowers) - { //we're done now then. + if (allPowers || noPowers) { // we're done now then. return; } i = 0; - while (buf[i]) - { //parse through the list which is seperated by |, and add all the weapons into a bitflag - if (buf[i] != ' ' && buf[i] != '|') - { + while (buf[i]) { // parse through the list which is seperated by |, and add all the weapons into a bitflag + if (buf[i] != ' ' && buf[i] != '|') { j = 0; - while (buf[i] && buf[i] != ' ' && buf[i] != '|' && buf[i] != ',') - { + while (buf[i] && buf[i] != ' ' && buf[i] != '|' && buf[i] != ',') { checkPower[j] = buf[i]; j++; i++; } checkPower[j] = 0; - if (buf[i] == ',') - { //parse the power level + if (buf[i] == ',') { // parse the power level i++; l = 0; - while (buf[i] && buf[i] != ' ' && buf[i] != '|') - { + while (buf[i] && buf[i] != ' ' && buf[i] != '|') { checkLevel[l] = buf[i]; l++; i++; @@ -654,34 +521,26 @@ void BG_SiegeTranslateForcePowers(char *buf, siegeClass_t *siegeClass) checkLevel[l] = 0; parsedLevel = atoi(checkLevel); - //keep sane limits on the powers - if (parsedLevel < 0) - { + // keep sane limits on the powers + if (parsedLevel < 0) { parsedLevel = 0; } - if (parsedLevel > FORCE_LEVEL_5) - { + if (parsedLevel > FORCE_LEVEL_5) { parsedLevel = FORCE_LEVEL_5; } - } - else - { //if it's not there, assume level 3 I guess. + } else { // if it's not there, assume level 3 I guess. parsedLevel = 3; } - if (checkPower[0]) - { //Got the name, compare it against the weapon table strings. + if (checkPower[0]) { // Got the name, compare it against the weapon table strings. k = 0; - if (!Q_stricmp(checkPower, "FP_JUMP")) - { //haqery + if (!Q_stricmp(checkPower, "FP_JUMP")) { // haqery Q_strncpyz(checkPower, "FP_LEVITATION", sizeof(checkPower)); } - while (FPTable[k].id != -1 && FPTable[k].name[0]) - { - if (!Q_stricmp(checkPower, FPTable[k].name)) - { //found it, add the weapon into the weapons value + while (FPTable[k].id != -1 && FPTable[k].name[0]) { + if (!Q_stricmp(checkPower, FPTable[k].name)) { // found it, add the weapon into the weapons value siegeClass->forcePowerLevels[k] = parsedLevel; break; } @@ -690,59 +549,47 @@ void BG_SiegeTranslateForcePowers(char *buf, siegeClass_t *siegeClass) } } - if (!buf[i]) - { + if (!buf[i]) { break; } i++; } } -//Used for the majority of generic val parsing stuff. buf should be the value string, -//table should be the appropriate string/id table. If bitflag is qtrue then the -//values are accumulated into a bitflag. If bitflag is qfalse then the first value -//is returned as a directly corresponding id and no further parsing is done. -int BG_SiegeTranslateGenericTable(char *buf, stringID_table_t *table, qboolean bitflag) -{ +// Used for the majority of generic val parsing stuff. buf should be the value string, +// table should be the appropriate string/id table. If bitflag is qtrue then the +// values are accumulated into a bitflag. If bitflag is qfalse then the first value +// is returned as a directly corresponding id and no further parsing is done. +int BG_SiegeTranslateGenericTable(char *buf, stringID_table_t *table, qboolean bitflag) { int items = 0; char checkItem[1024]; int i = 0; int j = 0; int k = 0; - if (buf[0] == '0' && !buf[1]) - { //special case, no items. + if (buf[0] == '0' && !buf[1]) { // special case, no items. return 0; } - while (buf[i]) - { //Using basically the same parsing method as we do for weapons and forcepowers. - if (buf[i] != ' ' && buf[i] != '|') - { + while (buf[i]) { // Using basically the same parsing method as we do for weapons and forcepowers. + if (buf[i] != ' ' && buf[i] != '|') { j = 0; - while (buf[i] && buf[i] != ' ' && buf[i] != '|') - { + while (buf[i] && buf[i] != ' ' && buf[i] != '|') { checkItem[j] = buf[i]; j++; i++; } checkItem[j] = 0; - if (checkItem[0]) - { + if (checkItem[0]) { k = 0; - while (table[k].name && table[k].name[0]) - { //go through the list and check the parsed flag name against the hardcoded names - if (!Q_stricmp(checkItem, table[k].name)) - { //Got it, so add the value into our items value. - if (bitflag) - { + while (table[k].name && table[k].name[0]) { // go through the list and check the parsed flag name against the hardcoded names + if (!Q_stricmp(checkItem, table[k].name)) { // Got it, so add the value into our items value. + if (bitflag) { items |= (1 << table[k].id); - } - else - { //return the value directly then. + } else { // return the value directly then. return table[k].id; } break; @@ -752,8 +599,7 @@ int BG_SiegeTranslateGenericTable(char *buf, stringID_table_t *table, qboolean b } } - if (!buf[i]) - { + if (!buf[i]) { break; } @@ -762,492 +608,389 @@ int BG_SiegeTranslateGenericTable(char *buf, stringID_table_t *table, qboolean b return items; } -char *classTitles[SPC_MAX] = -{ -"infantry", // SPC_INFANTRY -"vanguard", // SPC_VANGUARD -"support", // SPC_SUPPORT -"jedi_general", // SPC_JEDI -"demolitionist", // SPC_DEMOLITIONIST -"heavy_weapons", // SPC_HEAVY_WEAPONS +char *classTitles[SPC_MAX] = { + "infantry", // SPC_INFANTRY + "vanguard", // SPC_VANGUARD + "support", // SPC_SUPPORT + "jedi_general", // SPC_JEDI + "demolitionist", // SPC_DEMOLITIONIST + "heavy_weapons", // SPC_HEAVY_WEAPONS }; -void BG_SiegeParseClassFile(const char *filename, siegeClassDesc_t *descBuffer) -{ +void BG_SiegeParseClassFile(const char *filename, siegeClassDesc_t *descBuffer) { fileHandle_t f; int len; int i; char classInfo[4096]; char parseBuf[4096]; - len = trap->FS_Open( filename, &f, FS_READ ); + len = trap->FS_Open(filename, &f, FS_READ); if (!f) { return; } if (len >= 4096) { - trap->FS_Close( f ); + trap->FS_Close(f); return; } - trap->FS_Read( classInfo, len, f ); + trap->FS_Read(classInfo, len, f); - trap->FS_Close( f ); + trap->FS_Close(f); classInfo[len] = 0; - //first get the description if we have a buffer for it - if (descBuffer) - { - if (!BG_SiegeGetPairedValue(classInfo, "description", descBuffer->desc)) - { + // first get the description if we have a buffer for it + if (descBuffer) { + if (!BG_SiegeGetPairedValue(classInfo, "description", descBuffer->desc)) { Q_strncpyz(descBuffer->desc, "DESCRIPTION UNAVAILABLE", sizeof(descBuffer->desc)); } - //Hit this assert? Memory has already been trashed. Increase - //SIEGE_CLASS_DESC_LEN. + // Hit this assert? Memory has already been trashed. Increase + // SIEGE_CLASS_DESC_LEN. assert(strlen(descBuffer->desc) < SIEGE_CLASS_DESC_LEN); } BG_SiegeGetValueGroup(classInfo, "ClassInfo", classInfo); - //Parse name - if (BG_SiegeGetPairedValue(classInfo, "name", parseBuf)) - { + // Parse name + if (BG_SiegeGetPairedValue(classInfo, "name", parseBuf)) { Q_strncpyz(bgSiegeClasses[bgNumSiegeClasses].name, parseBuf, sizeof(bgSiegeClasses[0].name)); - } - else - { + } else { Com_Error(ERR_DROP, "Siege class without name entry"); } - //Parse forced model - if (BG_SiegeGetPairedValue(classInfo, "model", parseBuf)) - { + // Parse forced model + if (BG_SiegeGetPairedValue(classInfo, "model", parseBuf)) { Q_strncpyz(bgSiegeClasses[bgNumSiegeClasses].forcedModel, parseBuf, sizeof(bgSiegeClasses[0].forcedModel)); - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].forcedModel[0] = 0; } - //Parse forced skin - if (BG_SiegeGetPairedValue(classInfo, "skin", parseBuf)) - { + // Parse forced skin + if (BG_SiegeGetPairedValue(classInfo, "skin", parseBuf)) { Q_strncpyz(bgSiegeClasses[bgNumSiegeClasses].forcedSkin, parseBuf, sizeof(bgSiegeClasses[0].forcedSkin)); - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].forcedSkin[0] = 0; } - //Parse first saber - if (BG_SiegeGetPairedValue(classInfo, "saber1", parseBuf)) - { + // Parse first saber + if (BG_SiegeGetPairedValue(classInfo, "saber1", parseBuf)) { Q_strncpyz(bgSiegeClasses[bgNumSiegeClasses].saber1, parseBuf, sizeof(bgSiegeClasses[0].saber1)); - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].saber1[0] = 0; } - //Parse second saber - if (BG_SiegeGetPairedValue(classInfo, "saber2", parseBuf)) - { + // Parse second saber + if (BG_SiegeGetPairedValue(classInfo, "saber2", parseBuf)) { Q_strncpyz(bgSiegeClasses[bgNumSiegeClasses].saber2, parseBuf, sizeof(bgSiegeClasses[0].saber2)); - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].saber2[0] = 0; } - //Parse forced saber stance - if (BG_SiegeGetPairedValue(classInfo, "saberstyle", parseBuf)) - { + // Parse forced saber stance + if (BG_SiegeGetPairedValue(classInfo, "saberstyle", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].saberStance = BG_SiegeTranslateGenericTable(parseBuf, StanceTable, qtrue); - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].saberStance = 0; } - //Parse forced saber color - if (BG_SiegeGetPairedValue(classInfo, "sabercolor", parseBuf)) - { + // Parse forced saber color + if (BG_SiegeGetPairedValue(classInfo, "sabercolor", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].forcedSaberColor = atoi(parseBuf); bgSiegeClasses[bgNumSiegeClasses].hasForcedSaberColor = qtrue; - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].hasForcedSaberColor = qfalse; } - //Parse forced saber2 color - if (BG_SiegeGetPairedValue(classInfo, "saber2color", parseBuf)) - { + // Parse forced saber2 color + if (BG_SiegeGetPairedValue(classInfo, "saber2color", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].forcedSaber2Color = atoi(parseBuf); bgSiegeClasses[bgNumSiegeClasses].hasForcedSaber2Color = qtrue; - } - else - { //It's ok if there isn't one, it's optional. + } else { // It's ok if there isn't one, it's optional. bgSiegeClasses[bgNumSiegeClasses].hasForcedSaber2Color = qfalse; } - //Parse weapons - if (BG_SiegeGetPairedValue(classInfo, "weapons", parseBuf)) - { + // Parse weapons + if (BG_SiegeGetPairedValue(classInfo, "weapons", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].weapons = BG_SiegeTranslateGenericTable(parseBuf, WPTable, qtrue); - } - else - { + } else { Com_Error(ERR_DROP, "Siege class without weapons entry"); } - if (!(bgSiegeClasses[bgNumSiegeClasses].weapons & (1 << WP_SABER))) - { //make sure it has melee if there's no saber + if (!(bgSiegeClasses[bgNumSiegeClasses].weapons & (1 << WP_SABER))) { // make sure it has melee if there's no saber bgSiegeClasses[bgNumSiegeClasses].weapons |= (1 << WP_MELEE); - //always give them this too if they are not a saber user - //bgSiegeClasses[bgNumSiegeClasses].weapons |= (1 << WP_BRYAR_PISTOL); + // always give them this too if they are not a saber user + // bgSiegeClasses[bgNumSiegeClasses].weapons |= (1 << WP_BRYAR_PISTOL); } - //Parse forcepowers - if (BG_SiegeGetPairedValue(classInfo, "forcepowers", parseBuf)) - { + // Parse forcepowers + if (BG_SiegeGetPairedValue(classInfo, "forcepowers", parseBuf)) { BG_SiegeTranslateForcePowers(parseBuf, &bgSiegeClasses[bgNumSiegeClasses]); - } - else - { //fine, clear out the powers. + } else { // fine, clear out the powers. i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { bgSiegeClasses[bgNumSiegeClasses].forcePowerLevels[i] = 0; i++; } } - //Parse classflags - if (BG_SiegeGetPairedValue(classInfo, "classflags", parseBuf)) - { + // Parse classflags + if (BG_SiegeGetPairedValue(classInfo, "classflags", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].classflags = BG_SiegeTranslateGenericTable(parseBuf, bgSiegeClassFlagNames, qtrue); - } - else - { //fine, we'll 0 it. + } else { // fine, we'll 0 it. bgSiegeClasses[bgNumSiegeClasses].classflags = 0; } - //Parse maxhealth - if (BG_SiegeGetPairedValue(classInfo, "maxhealth", parseBuf)) - { + // Parse maxhealth + if (BG_SiegeGetPairedValue(classInfo, "maxhealth", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].maxhealth = atoi(parseBuf); - } - else - { //It's alright, just default to 100 then. + } else { // It's alright, just default to 100 then. bgSiegeClasses[bgNumSiegeClasses].maxhealth = 100; } - //Parse starthealth - if (BG_SiegeGetPairedValue(classInfo, "starthealth", parseBuf)) - { + // Parse starthealth + if (BG_SiegeGetPairedValue(classInfo, "starthealth", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].starthealth = atoi(parseBuf); - } - else - { //It's alright, just default to 100 then. + } else { // It's alright, just default to 100 then. bgSiegeClasses[bgNumSiegeClasses].starthealth = bgSiegeClasses[bgNumSiegeClasses].maxhealth; } - - //Parse startarmor - if (BG_SiegeGetPairedValue(classInfo, "maxarmor", parseBuf)) - { + // Parse startarmor + if (BG_SiegeGetPairedValue(classInfo, "maxarmor", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].maxarmor = atoi(parseBuf); - } - else - { //It's alright, just default to 0 then. + } else { // It's alright, just default to 0 then. bgSiegeClasses[bgNumSiegeClasses].maxarmor = 0; } - //Parse startarmor - if (BG_SiegeGetPairedValue(classInfo, "startarmor", parseBuf)) - { + // Parse startarmor + if (BG_SiegeGetPairedValue(classInfo, "startarmor", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].startarmor = atoi(parseBuf); - if (!bgSiegeClasses[bgNumSiegeClasses].maxarmor) - { //if they didn't specify a damn max armor then use this. + if (!bgSiegeClasses[bgNumSiegeClasses].maxarmor) { // if they didn't specify a damn max armor then use this. bgSiegeClasses[bgNumSiegeClasses].maxarmor = bgSiegeClasses[bgNumSiegeClasses].startarmor; } - } - else - { //default to maxarmor. + } else { // default to maxarmor. bgSiegeClasses[bgNumSiegeClasses].startarmor = bgSiegeClasses[bgNumSiegeClasses].maxarmor; } - //Parse speed (this is a multiplier value) - if (BG_SiegeGetPairedValue(classInfo, "speed", parseBuf)) - { + // Parse speed (this is a multiplier value) + if (BG_SiegeGetPairedValue(classInfo, "speed", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].speed = atof(parseBuf); - } - else - { //It's alright, just default to 1 then. + } else { // It's alright, just default to 1 then. bgSiegeClasses[bgNumSiegeClasses].speed = 1.0f; } - //Parse shader for ui to use - if (BG_SiegeGetPairedValue(classInfo, "uishader", parseBuf)) - { - #if defined(_GAME) - bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = 0; - memset(bgSiegeClasses[bgNumSiegeClasses].uiPortrait,0,sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); - #elif defined(_CGAME) - bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = 0; - memset(bgSiegeClasses[bgNumSiegeClasses].uiPortrait,0,sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); - #elif defined(UI_BUILD) //ui - bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = trap->R_RegisterShaderNoMip(parseBuf); - memcpy(bgSiegeClasses[bgNumSiegeClasses].uiPortrait,parseBuf,sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); - #endif - } - else - { //I guess this is an essential.. we don't want to render bad shaders or anything. + // Parse shader for ui to use + if (BG_SiegeGetPairedValue(classInfo, "uishader", parseBuf)) { +#if defined(_GAME) + bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = 0; + memset(bgSiegeClasses[bgNumSiegeClasses].uiPortrait, 0, sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); +#elif defined(_CGAME) + bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = 0; + memset(bgSiegeClasses[bgNumSiegeClasses].uiPortrait, 0, sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); +#elif defined(UI_BUILD) // ui + bgSiegeClasses[bgNumSiegeClasses].uiPortraitShader = trap->R_RegisterShaderNoMip(parseBuf); + memcpy(bgSiegeClasses[bgNumSiegeClasses].uiPortrait, parseBuf, sizeof(bgSiegeClasses[bgNumSiegeClasses].uiPortrait)); +#endif + } else { // I guess this is an essential.. we don't want to render bad shaders or anything. Com_Error(ERR_DROP, "Siege class without uishader entry"); } - //Parse shader for ui to use - if (BG_SiegeGetPairedValue(classInfo, "class_shader", parseBuf)) - { - #ifdef _GAME + // Parse shader for ui to use + if (BG_SiegeGetPairedValue(classInfo, "class_shader", parseBuf)) { +#ifdef _GAME bgSiegeClasses[bgNumSiegeClasses].classShader = 0; - #else //cgame, ui - #if defined(_CGAME) - bgSiegeClasses[bgNumSiegeClasses].classShader = trap->R_RegisterShaderNoMip(parseBuf); - #elif defined(UI_BUILD) - bgSiegeClasses[bgNumSiegeClasses].classShader = trap->R_RegisterShaderNoMip(parseBuf); - #endif - assert( bgSiegeClasses[bgNumSiegeClasses].classShader ); - if ( !bgSiegeClasses[bgNumSiegeClasses].classShader ) - { - //Com_Error( ERR_DROP, "ERROR: could not find class_shader %s for class %s\n", parseBuf, bgSiegeClasses[bgNumSiegeClasses].name ); - Com_Printf( "ERROR: could not find class_shader %s for class %s\n", parseBuf, bgSiegeClasses[bgNumSiegeClasses].name ); +#else // cgame, ui +#if defined(_CGAME) + bgSiegeClasses[bgNumSiegeClasses].classShader = trap->R_RegisterShaderNoMip(parseBuf); +#elif defined(UI_BUILD) + bgSiegeClasses[bgNumSiegeClasses].classShader = trap->R_RegisterShaderNoMip(parseBuf); +#endif + assert(bgSiegeClasses[bgNumSiegeClasses].classShader); + if (!bgSiegeClasses[bgNumSiegeClasses].classShader) { + // Com_Error( ERR_DROP, "ERROR: could not find class_shader %s for class %s\n", parseBuf, bgSiegeClasses[bgNumSiegeClasses].name ); + Com_Printf("ERROR: could not find class_shader %s for class %s\n", parseBuf, bgSiegeClasses[bgNumSiegeClasses].name); } // A very hacky way to determine class . . . else - #endif +#endif { // Find the base player class based on the icon name - very bad, I know. int titleLength, arrayTitleLength; char *holdBuf; titleLength = strlen(parseBuf); - for (i=0;ititleLength) // Too long + if (arrayTitleLength > titleLength) // Too long { break; } - holdBuf = parseBuf + ( titleLength - arrayTitleLength); - if (!strcmp(holdBuf,classTitles[i])) - { + holdBuf = parseBuf + (titleLength - arrayTitleLength); + if (!strcmp(holdBuf, classTitles[i])) { bgSiegeClasses[bgNumSiegeClasses].playerClass = i; break; } } // In case the icon name doesn't match up - if (i>=SPC_MAX) - { + if (i >= SPC_MAX) { bgSiegeClasses[bgNumSiegeClasses].playerClass = SPC_INFANTRY; } } - } - else - { //No entry! Bad bad bad - //Com_Error( ERR_DROP, "ERROR: no class_shader defined for class %s\n", bgSiegeClasses[bgNumSiegeClasses].name ); - Com_Printf( "ERROR: no class_shader defined for class %s\n", bgSiegeClasses[bgNumSiegeClasses].name ); + } else { // No entry! Bad bad bad + // Com_Error( ERR_DROP, "ERROR: no class_shader defined for class %s\n", bgSiegeClasses[bgNumSiegeClasses].name ); + Com_Printf("ERROR: no class_shader defined for class %s\n", bgSiegeClasses[bgNumSiegeClasses].name); } - //Parse holdable items to use - if (BG_SiegeGetPairedValue(classInfo, "holdables", parseBuf)) - { + // Parse holdable items to use + if (BG_SiegeGetPairedValue(classInfo, "holdables", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].invenItems = BG_SiegeTranslateGenericTable(parseBuf, HoldableTable, qtrue); - } - else - { //Just don't start out with any then. + } else { // Just don't start out with any then. bgSiegeClasses[bgNumSiegeClasses].invenItems = 0; } - //Parse powerups to use - if (BG_SiegeGetPairedValue(classInfo, "powerups", parseBuf)) - { + // Parse powerups to use + if (BG_SiegeGetPairedValue(classInfo, "powerups", parseBuf)) { bgSiegeClasses[bgNumSiegeClasses].powerups = BG_SiegeTranslateGenericTable(parseBuf, PowerupTable, qtrue); - } - else - { //Just don't start out with any then. + } else { // Just don't start out with any then. bgSiegeClasses[bgNumSiegeClasses].powerups = 0; } - //A successful read. + // A successful read. bgNumSiegeClasses++; } // Count the number of like base classes -int BG_SiegeCountBaseClass(const int team, const short classIndex) -{ - int count = 0,i; +int BG_SiegeCountBaseClass(const int team, const short classIndex) { + int count = 0, i; siegeTeam_t *stm; stm = BG_SiegeFindThemeForTeam(team); - if (!stm) - { - return(0); - + if (!stm) { + return (0); } - for (i=0;inumClasses;i++) - { + for (i = 0; i < stm->numClasses; i++) { - if (stm->classes[i]->playerClass == classIndex) - { + if (stm->classes[i]->playerClass == classIndex) { count++; } } - return(count); + return (count); } -char *BG_GetUIPortraitFile(const int team, const short classIndex, const short cntIndex) -{ - int count = 0,i; +char *BG_GetUIPortraitFile(const int team, const short classIndex, const short cntIndex) { + int count = 0, i; siegeTeam_t *stm; stm = BG_SiegeFindThemeForTeam(team); - if (!stm) - { - return(0); - + if (!stm) { + return (0); } // Loop through all the classes for this team - for (i=0;inumClasses;i++) - { + for (i = 0; i < stm->numClasses; i++) { // does it match the base class? - if (stm->classes[i]->playerClass == classIndex) - { - if (count==cntIndex) - { - return(stm->classes[i]->uiPortrait); + if (stm->classes[i]->playerClass == classIndex) { + if (count == cntIndex) { + return (stm->classes[i]->uiPortrait); } ++count; } } - return(0); + return (0); } -int BG_GetUIPortrait(const int team, const short classIndex, const short cntIndex) -{ - int count = 0,i; +int BG_GetUIPortrait(const int team, const short classIndex, const short cntIndex) { + int count = 0, i; siegeTeam_t *stm; stm = BG_SiegeFindThemeForTeam(team); - if (!stm) - { - return(0); - + if (!stm) { + return (0); } // Loop through all the classes for this team - for (i=0;inumClasses;i++) - { + for (i = 0; i < stm->numClasses; i++) { // does it match the base class? - if (stm->classes[i]->playerClass == classIndex) - { - if (count==cntIndex) - { - return(stm->classes[i]->uiPortraitShader); + if (stm->classes[i]->playerClass == classIndex) { + if (count == cntIndex) { + return (stm->classes[i]->uiPortraitShader); } ++count; } } - return(0); + return (0); } // This is really getting ugly - looking to get the base class (within a class) based on the index passed in -siegeClass_t *BG_GetClassOnBaseClass(const int team, const short classIndex, const short cntIndex) -{ - int count = 0,i; +siegeClass_t *BG_GetClassOnBaseClass(const int team, const short classIndex, const short cntIndex) { + int count = 0, i; siegeTeam_t *stm; stm = BG_SiegeFindThemeForTeam(team); - if (!stm) - { - return(0); + if (!stm) { + return (0); } // Loop through all the classes for this team - for (i=0;inumClasses;i++) - { + for (i = 0; i < stm->numClasses; i++) { // does it match the base class? - if (stm->classes[i]->playerClass == classIndex) - { - if (count==cntIndex) - { - return(stm->classes[i]); + if (stm->classes[i]->playerClass == classIndex) { + if (count == cntIndex) { + return (stm->classes[i]); } ++count; } } - return(0); + return (0); } -void BG_SiegeLoadClasses(siegeClassDesc_t *descBuffer) -{ +void BG_SiegeLoadClasses(siegeClassDesc_t *descBuffer) { int numFiles; int filelen; char filelist[4096]; char filename[MAX_QPATH]; - char* fileptr; + char *fileptr; int i; bgNumSiegeClasses = 0; - numFiles = trap->FS_GetFileList("ext_data/Siege/Classes", ".scl", filelist, sizeof( filelist ) ); + numFiles = trap->FS_GetFileList("ext_data/Siege/Classes", ".scl", filelist, sizeof(filelist)); fileptr = filelist; - for (i = 0; i < numFiles; i++, fileptr += filelen+1) - { + for (i = 0; i < numFiles; i++, fileptr += filelen + 1) { filelen = strlen(fileptr); Q_strncpyz(filename, "ext_data/Siege/Classes/", sizeof(filename)); Q_strcat(filename, sizeof(filename), fileptr); - if (descBuffer) - { + if (descBuffer) { BG_SiegeParseClassFile(filename, &descBuffer[i]); - } - else - { + } else { BG_SiegeParseClassFile(filename, NULL); } } } //====================================== -//End class loading functions +// End class loading functions //====================================== - //====================================== -//Team loading functions +// Team loading functions //====================================== -siegeClass_t *BG_SiegeFindClassByName(const char *classname) -{ +siegeClass_t *BG_SiegeFindClassByName(const char *classname) { int i = 0; - while (i < bgNumSiegeClasses) - { - if (!Q_stricmp(bgSiegeClasses[i].name, classname)) - { //found it + while (i < bgNumSiegeClasses) { + if (!Q_stricmp(bgSiegeClasses[i].name, classname)) { // found it return &bgSiegeClasses[i]; } i++; @@ -1256,8 +999,7 @@ siegeClass_t *BG_SiegeFindClassByName(const char *classname) return NULL; } -void BG_SiegeParseTeamFile(const char *filename) -{ +void BG_SiegeParseTeamFile(const char *filename) { fileHandle_t f; int len; char teamInfo[2048]; @@ -1272,52 +1014,45 @@ void BG_SiegeParseTeamFile(const char *filename) return; } if (len >= 2048) { - trap->FS_Close( f ); + trap->FS_Close(f); return; } - trap->FS_Read( teamInfo, len, f ); - trap->FS_Close( f ); + trap->FS_Read(teamInfo, len, f); + trap->FS_Close(f); teamInfo[len] = 0; - if (BG_SiegeGetPairedValue(teamInfo, "name", parseBuf)) - { + if (BG_SiegeGetPairedValue(teamInfo, "name", parseBuf)) { Q_strncpyz(bgSiegeTeams[bgNumSiegeTeams].name, parseBuf, sizeof(bgSiegeTeams[0].name)); - } - else - { + } else { Com_Error(ERR_DROP, "Siege team with no name definition"); } - //I don't entirely like doing things this way but it's the easiest way. - #ifdef _CGAME - if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", parseBuf)) - bgSiegeTeams[bgNumSiegeTeams].friendlyShader = trap->R_RegisterShaderNoMip(parseBuf); - #else - bgSiegeTeams[bgNumSiegeTeams].friendlyShader = 0; - #endif +// I don't entirely like doing things this way but it's the easiest way. +#ifdef _CGAME + if (BG_SiegeGetPairedValue(teamInfo, "FriendlyShader", parseBuf)) + bgSiegeTeams[bgNumSiegeTeams].friendlyShader = trap->R_RegisterShaderNoMip(parseBuf); +#else + bgSiegeTeams[bgNumSiegeTeams].friendlyShader = 0; +#endif bgSiegeTeams[bgNumSiegeTeams].numClasses = 0; - if (BG_SiegeGetValueGroup(teamInfo, "Classes", teamInfo)) - { - while (success && i < MAX_SIEGE_CLASSES) - { //keep checking for group values named class# up to MAX_SIEGE_CLASSES until we can't find one. + if (BG_SiegeGetValueGroup(teamInfo, "Classes", teamInfo)) { + while (success && i < MAX_SIEGE_CLASSES) { // keep checking for group values named class# up to MAX_SIEGE_CLASSES until we can't find one. Q_strncpyz(lookString, va("class%i", i), sizeof(lookString)); success = BG_SiegeGetPairedValue(teamInfo, lookString, parseBuf); - if (!success) - { + if (!success) { break; } bgSiegeTeams[bgNumSiegeTeams].classes[bgSiegeTeams[bgNumSiegeTeams].numClasses] = BG_SiegeFindClassByName(parseBuf); - if (!bgSiegeTeams[bgNumSiegeTeams].classes[bgSiegeTeams[bgNumSiegeTeams].numClasses]) - { - Com_Printf( "Invalid class specified: '%s'\n", parseBuf); + if (!bgSiegeTeams[bgNumSiegeTeams].classes[bgSiegeTeams[bgNumSiegeTeams].numClasses]) { + Com_Printf("Invalid class specified: '%s'\n", parseBuf); } bgSiegeTeams[bgNumSiegeTeams].numClasses++; @@ -1326,32 +1061,29 @@ void BG_SiegeParseTeamFile(const char *filename) } } - if (!bgSiegeTeams[bgNumSiegeTeams].numClasses) - { + if (!bgSiegeTeams[bgNumSiegeTeams].numClasses) { Com_Error(ERR_DROP, "Team defined with no allowable classes\n"); } - //If we get here then it was a success, so increment the team number + // If we get here then it was a success, so increment the team number bgNumSiegeTeams++; } -void BG_SiegeLoadTeams(void) -{ +void BG_SiegeLoadTeams(void) { int numFiles; int filelen; char filelist[4096]; char filename[MAX_QPATH]; - char* fileptr; + char *fileptr; int i; bgNumSiegeTeams = 0; - numFiles = trap->FS_GetFileList("ext_data/Siege/Teams", ".team", filelist, sizeof( filelist ) ); + numFiles = trap->FS_GetFileList("ext_data/Siege/Teams", ".team", filelist, sizeof(filelist)); fileptr = filelist; - for (i = 0; i < numFiles; i++, fileptr += filelen+1) - { + for (i = 0; i < numFiles; i++, fileptr += filelen + 1) { filelen = strlen(fileptr); Q_strncpyz(filename, "ext_data/Siege/Teams/", sizeof(filename)); Q_strcat(filename, sizeof(filename), fileptr); @@ -1359,34 +1091,28 @@ void BG_SiegeLoadTeams(void) } } //====================================== -//End team loading functions +// End team loading functions //====================================== - //====================================== -//Misc/utility functions +// Misc/utility functions //====================================== -siegeTeam_t *BG_SiegeFindThemeForTeam(int team) -{ - if (team == SIEGETEAM_TEAM1) - { +siegeTeam_t *BG_SiegeFindThemeForTeam(int team) { + if (team == SIEGETEAM_TEAM1) { return team1Theme; - } - else if (team == SIEGETEAM_TEAM2) - { + } else if (team == SIEGETEAM_TEAM2) { return team2Theme; } - return NULL; + return NULL; } -#if defined(_GAME) || defined(_CGAME) //only for game/cgame -//precache all the sabers for the active classes for the team -extern qboolean WP_SaberParseParms( const char *saberName, saberInfo_t *saber ); //bg_saberLoad.cpp -extern int BG_ModelCache(const char *modelName, const char *skinName); //bg_misc.c +#if defined(_GAME) || defined(_CGAME) // only for game/cgame +// precache all the sabers for the active classes for the team +extern qboolean WP_SaberParseParms(const char *saberName, saberInfo_t *saber); // bg_saberLoad.cpp +extern int BG_ModelCache(const char *modelName, const char *skinName); // bg_misc.c -void BG_PrecacheSabersForSiegeTeam(int team) -{ +void BG_PrecacheSabersForSiegeTeam(int team) { siegeTeam_t *t; saberInfo_t saber; char *saberName; @@ -1394,18 +1120,14 @@ void BG_PrecacheSabersForSiegeTeam(int team) t = BG_SiegeFindThemeForTeam(team); - if (t) - { + if (t) { int i = 0; - while (i < t->numClasses) - { + while (i < t->numClasses) { sNum = 0; - while (sNum < MAX_SABERS) - { - switch (sNum) - { + while (sNum < MAX_SABERS) { + switch (sNum) { case 0: saberName = &t->classes[i]->saber1[0]; break; @@ -1417,13 +1139,10 @@ void BG_PrecacheSabersForSiegeTeam(int team) break; } - if (saberName && saberName[0]) - { + if (saberName && saberName[0]) { WP_SaberParseParms(saberName, &saber); - if (!Q_stricmp(saberName, saber.name)) - { //found the matching saber - if (saber.model[0]) - { + if (!Q_stricmp(saberName, saber.name)) { // found the matching saber + if (saber.model[0]) { BG_ModelCache(saber.model, NULL); } } @@ -1438,54 +1157,41 @@ void BG_PrecacheSabersForSiegeTeam(int team) } #endif -qboolean BG_SiegeCheckClassLegality(int team, char *classname) -{ +qboolean BG_SiegeCheckClassLegality(int team, char *classname) { siegeTeam_t **teamPtr = NULL; int i = 0; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { teamPtr = &team1Theme; - } - else if (team == SIEGETEAM_TEAM2) - { + } else if (team == SIEGETEAM_TEAM2) { teamPtr = &team2Theme; - } - else - { //spectator? Whatever, you're legal then. + } else { // spectator? Whatever, you're legal then. return qtrue; } - if (!teamPtr || !(*teamPtr)) - { //Well, guess the class is ok, seeing as there is no team theme to begin with. + if (!teamPtr || !(*teamPtr)) { // Well, guess the class is ok, seeing as there is no team theme to begin with. return qtrue; } - //See if the class is listed on the team - while (i < (*teamPtr)->numClasses) - { - if (!Q_stricmp(classname, (*teamPtr)->classes[i]->name)) - { //found it, so it's alright + // See if the class is listed on the team + while (i < (*teamPtr)->numClasses) { + if (!Q_stricmp(classname, (*teamPtr)->classes[i]->name)) { // found it, so it's alright return qtrue; } i++; } - //Didn't find it, so copy the name of the first valid class over it. + // Didn't find it, so copy the name of the first valid class over it. strcpy(classname, (*teamPtr)->classes[0]->name); return qfalse; } -siegeTeam_t *BG_SiegeFindTeamForTheme(char *themeName) -{ +siegeTeam_t *BG_SiegeFindTeamForTheme(char *themeName) { int i = 0; - while (i < bgNumSiegeTeams) - { - if (bgSiegeTeams[i].name[0] && - !Q_stricmp(bgSiegeTeams[i].name, themeName)) - { //this is what we're looking for + while (i < bgNumSiegeTeams) { + if (bgSiegeTeams[i].name[0] && !Q_stricmp(bgSiegeTeams[i].name, themeName)) { // this is what we're looking for return &bgSiegeTeams[i]; } @@ -1495,30 +1201,23 @@ siegeTeam_t *BG_SiegeFindTeamForTheme(char *themeName) return NULL; } -void BG_SiegeSetTeamTheme(int team, char *themeName) -{ +void BG_SiegeSetTeamTheme(int team, char *themeName) { siegeTeam_t **teamPtr = NULL; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { teamPtr = &team1Theme; - } - else - { + } else { teamPtr = &team2Theme; } (*teamPtr) = BG_SiegeFindTeamForTheme(themeName); } -int BG_SiegeFindClassIndexByName(const char *classname) -{ +int BG_SiegeFindClassIndexByName(const char *classname) { int i = 0; - while (i < bgNumSiegeClasses) - { - if (!Q_stricmp(bgSiegeClasses[i].name, classname)) - { //found it + while (i < bgNumSiegeClasses) { + if (!Q_stricmp(bgSiegeClasses[i].name, classname)) { // found it return i; } i++; @@ -1527,5 +1226,5 @@ int BG_SiegeFindClassIndexByName(const char *classname) return -1; } //====================================== -//End misc/utility functions +// End misc/utility functions //====================================== diff --git a/codemp/game/bg_slidemove.c b/codemp/game/bg_slidemove.c index 1b8b884f4f..e9a244664b 100644 --- a/codemp/game/bg_slidemove.c +++ b/codemp/game/bg_slidemove.c @@ -29,11 +29,11 @@ along with this program; if not, see . #include "bg_local.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif /* @@ -44,119 +44,97 @@ output: origin, velocity, impacts, stairup boolean */ - -//do vehicle impact stuff -// slight rearrangement by BTO (VV) so that we only have one namespace include +// do vehicle impact stuff +// slight rearrangement by BTO (VV) so that we only have one namespace include #ifdef _GAME - extern void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force ); //g_vehicle.c - extern qboolean G_CanBeEnemy(gentity_t *self, gentity_t *enemy); //w_saber.c +extern void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force); // g_vehicle.c +extern qboolean G_CanBeEnemy(gentity_t *self, gentity_t *enemy); // w_saber.c #endif -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); - +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); extern bgEntity_t *pm_entSelf; extern bgEntity_t *pm_entVeh; -//vehicle impact stuff continued... +// vehicle impact stuff continued... #ifdef _GAME - extern qboolean FighterIsLanded( Vehicle_t *pVeh, playerState_t *parentPS ); +extern qboolean FighterIsLanded(Vehicle_t *pVeh, playerState_t *parentPS); #endif extern void PM_SetPMViewAngle(playerState_t *ps, vec3_t angle, usercmd_t *ucmd); #define MAX_IMPACT_TURN_ANGLE 45.0f -void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) -{ +void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) { // See if the vehicle has crashed into the ground. Vehicle_t *pSelfVeh = pEnt->m_pVehicle; - float magnitude = VectorLength( pm->ps->velocity ) * pSelfVeh->m_pVehicleInfo->mass / 50.0f; + float magnitude = VectorLength(pm->ps->velocity) * pSelfVeh->m_pVehicleInfo->mass / 50.0f; qboolean forceSurfDestruction = qfalse; #ifdef _GAME - gentity_t *hitEnt = trace!=NULL?&g_entities[trace->entityNum]:NULL; + gentity_t *hitEnt = trace != NULL ? &g_entities[trace->entityNum] : NULL; if (!hitEnt || - (pSelfVeh && pSelfVeh->m_pPilot && - hitEnt && hitEnt->s.eType == ET_MISSILE && hitEnt->inuse && - hitEnt->r.ownerNum == pSelfVeh->m_pPilot->s.number) - ) - { + (pSelfVeh && pSelfVeh->m_pPilot && hitEnt && hitEnt->s.eType == ET_MISSILE && hitEnt->inuse && hitEnt->r.ownerNum == pSelfVeh->m_pPilot->s.number)) { return; } - if ( pSelfVeh//I have a vehicle struct - && pSelfVeh->m_iRemovedSurfaces )//vehicle has bits removed - {//spiralling to our deaths, explode on any solid impact - if ( hitEnt->s.NPC_class == CLASS_VEHICLE ) - {//hit another vehicle, explode! - //Give credit to whoever got me into this death spiral state + if (pSelfVeh // I have a vehicle struct + && pSelfVeh->m_iRemovedSurfaces) // vehicle has bits removed + { // spiralling to our deaths, explode on any solid impact + if (hitEnt->s.NPC_class == CLASS_VEHICLE) { // hit another vehicle, explode! + // Give credit to whoever got me into this death spiral state gentity_t *parent = (gentity_t *)pSelfVeh->m_pParentEntity; gentity_t *killer = NULL; - if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && - parent->client->ps.otherKillerTime > level.time) - { + if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && parent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[parent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } - //FIXME: damage hitEnt, some, too? Our explosion should hurt them some, but... - G_Damage( (gentity_t *)pEnt, killer, killer, NULL, pm->ps->origin, 999999, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + // FIXME: damage hitEnt, some, too? Our explosion should hurt them some, but... + G_Damage((gentity_t *)pEnt, killer, killer, NULL, pm->ps->origin, 999999, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT return; - } - else if ( !VectorCompare( trace->plane.normal, vec3_origin ) - && (trace->entityNum == ENTITYNUM_WORLD || hitEnt->r.bmodel ) ) - {//have a valid hit plane and we hit a solid brush - vec3_t moveDir; - float impactDot; - VectorCopy( pm->ps->velocity, moveDir ); - VectorNormalize( moveDir ); - impactDot = DotProduct( moveDir, trace->plane.normal ); - if ( impactDot <= -0.7f )//hit rather head-on and hard - {// Just DIE now - //Give credit to whoever got me into this death spiral state + } else if (!VectorCompare(trace->plane.normal, vec3_origin) && + (trace->entityNum == ENTITYNUM_WORLD || hitEnt->r.bmodel)) { // have a valid hit plane and we hit a solid brush + vec3_t moveDir; + float impactDot; + VectorCopy(pm->ps->velocity, moveDir); + VectorNormalize(moveDir); + impactDot = DotProduct(moveDir, trace->plane.normal); + if (impactDot <= -0.7f) // hit rather head-on and hard + { // Just DIE now + // Give credit to whoever got me into this death spiral state gentity_t *parent = (gentity_t *)pSelfVeh->m_pParentEntity; gentity_t *killer = NULL; - if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && - parent->client->ps.otherKillerTime > level.time) - { + if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && parent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[parent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } - G_Damage( (gentity_t *)pEnt, killer, killer, NULL, pm->ps->origin, 999999, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + G_Damage((gentity_t *)pEnt, killer, killer, NULL, pm->ps->origin, 999999, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT return; } } } - if ( trace->entityNum < ENTITYNUM_WORLD - && hitEnt->s.eType == ET_MOVER - && hitEnt->s.apos.trType != TR_STATIONARY//rotating - && (hitEnt->spawnflags&16) //IMPACT - && Q_stricmp( "func_rotating", hitEnt->classname ) == 0 ) - {//hit a func_rotating that is supposed to destroy anything it touches! - //guarantee the hit will happen, thereby taking off a piece of the ship + if (trace->entityNum < ENTITYNUM_WORLD && hitEnt->s.eType == ET_MOVER && hitEnt->s.apos.trType != TR_STATIONARY // rotating + && (hitEnt->spawnflags & 16) // IMPACT + && Q_stricmp("func_rotating", hitEnt->classname) == 0) { // hit a func_rotating that is supposed to destroy anything it touches! + // guarantee the hit will happen, thereby taking off a piece of the ship forceSurfDestruction = qtrue; - } - else if ( (fabs(pm->ps->velocity[0])+fabs(pm->ps->velocity[1])) < 100.0f - && pm->ps->velocity[2] > -100.0f ) + } else if ((fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1])) < 100.0f && pm->ps->velocity[2] > -100.0f) #elif defined(_CGAME) - if ( (fabs(pm->ps->velocity[0])+fabs(pm->ps->velocity[1])) < 100.0f - && pm->ps->velocity[2] > -100.0f ) + if ((fabs(pm->ps->velocity[0]) + fabs(pm->ps->velocity[1])) < 100.0f && pm->ps->velocity[2] > -100.0f) #endif - /* - if ( (pSelfVeh->m_ulFlags&VEH_GEARSOPEN) - && trace->plane.normal[2] > 0.7f - && fabs(pSelfVeh->m_vOrientation[PITCH]) < 0.2f - && fabs(pSelfVeh->m_vOrientation[ROLL]) < 0.2f )*/ - {//we're landing, we're cool - //FIXME: some sort of landing "thump", not the impactFX + /* +if ( (pSelfVeh->m_ulFlags&VEH_GEARSOPEN) + && trace->plane.normal[2] > 0.7f + && fabs(pSelfVeh->m_vOrientation[PITCH]) < 0.2f + && fabs(pSelfVeh->m_vOrientation[ROLL]) < 0.2f )*/ + { // we're landing, we're cool + // FIXME: some sort of landing "thump", not the impactFX /* if ( pSelfVeh->m_pVehicleInfo->iImpactFX ) { @@ -168,178 +146,139 @@ void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) #endif } */ - //this was annoying me -rww - //FIXME: this shouldn't even be getting called when the vehicle is at rest! + // this was annoying me -rww + // FIXME: this shouldn't even be getting called when the vehicle is at rest! #ifdef _GAME - if (hitEnt && (hitEnt->s.eType == ET_PLAYER || hitEnt->s.eType == ET_NPC) && pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) - { //always smack players - } - else + if (hitEnt && (hitEnt->s.eType == ET_PLAYER || hitEnt->s.eType == ET_NPC) && pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) { // always smack players + } else #endif { return; } } - if ( pSelfVeh && - (pSelfVeh->m_pVehicleInfo->type == VH_SPEEDER || pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) && //this is kind of weird on tauntauns and atst's.. - (magnitude >= 100||forceSurfDestruction) ) - { - if ( pEnt->m_pVehicle->m_iHitDebounce < pm->cmd.serverTime - || forceSurfDestruction ) - {//a bit of a hack, may conflict with getting shot, but... - //FIXME: impact sound and effect should be gotten from g_vehicleInfo...? - //FIXME: should pass in trace.endpos and trace.plane.normal - vec3_t vehUp; + if (pSelfVeh && + (pSelfVeh->m_pVehicleInfo->type == VH_SPEEDER || pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) && // this is kind of weird on tauntauns and atst's.. + (magnitude >= 100 || forceSurfDestruction)) { + if (pEnt->m_pVehicle->m_iHitDebounce < pm->cmd.serverTime || forceSurfDestruction) { // a bit of a hack, may conflict with getting shot, but... + // FIXME: impact sound and effect should be gotten from g_vehicleInfo...? + // FIXME: should pass in trace.endpos and trace.plane.normal + vec3_t vehUp; #ifdef _CGAME bgEntity_t *hitEnt; #endif - if ( trace && !pSelfVeh->m_iRemovedSurfaces && !forceSurfDestruction ) - { + if (trace && !pSelfVeh->m_iRemovedSurfaces && !forceSurfDestruction) { qboolean turnFromImpact = qfalse, turnHitEnt = qfalse; - float l = pm->ps->speed*0.5f; - vec3_t bounceDir; + float l = pm->ps->speed * 0.5f; + vec3_t bounceDir; #ifdef _CGAME bgEntity_t *hitEnt = PM_BGEntForNum(trace->entityNum); #endif - if ( (trace->entityNum == ENTITYNUM_WORLD || hitEnt->s.solid == SOLID_BMODEL)//bounce off any brush - && !VectorCompare(trace->plane.normal, vec3_origin) )//have a valid plane to bounce off of - { //bounce off in the opposite direction of the impact - if (pSelfVeh->m_pVehicleInfo->type == VH_SPEEDER) - { + if ((trace->entityNum == ENTITYNUM_WORLD || hitEnt->s.solid == SOLID_BMODEL) // bounce off any brush + && !VectorCompare(trace->plane.normal, vec3_origin)) // have a valid plane to bounce off of + { // bounce off in the opposite direction of the impact + if (pSelfVeh->m_pVehicleInfo->type == VH_SPEEDER) { pm->ps->speed *= pml.frametime; VectorCopy(trace->plane.normal, bounceDir); - } - else if ( trace->plane.normal[2] >= MIN_LANDING_SLOPE//flat enough to land on - && pSelfVeh->m_LandTrace.fraction < 1.0f //ground present - && pm->ps->speed <= MIN_LANDING_SPEED ) - {//could land here, don't bounce off, in fact, return altogether! + } else if (trace->plane.normal[2] >= MIN_LANDING_SLOPE // flat enough to land on + && pSelfVeh->m_LandTrace.fraction < 1.0f // ground present + && pm->ps->speed <= MIN_LANDING_SPEED) { // could land here, don't bounce off, in fact, return altogether! return; - } - else - { - if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) - { + } else { + if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) { turnFromImpact = qtrue; } VectorCopy(trace->plane.normal, bounceDir); } - } - else if ( pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER ) - {//check for impact with another fighter + } else if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) { // check for impact with another fighter #ifdef _CGAME bgEntity_t *hitEnt = PM_BGEntForNum(trace->entityNum); #endif - if ( hitEnt->s.NPC_class == CLASS_VEHICLE - && hitEnt->m_pVehicle - && hitEnt->m_pVehicle->m_pVehicleInfo - && hitEnt->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//two vehicles hit each other, turn away from the impact + if (hitEnt->s.NPC_class == CLASS_VEHICLE && hitEnt->m_pVehicle && hitEnt->m_pVehicle->m_pVehicleInfo && + hitEnt->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // two vehicles hit each other, turn away from the impact turnFromImpact = qtrue; turnHitEnt = qtrue; - #ifdef _GAME - VectorSubtract( pm->ps->origin, hitEnt->r.currentOrigin, bounceDir ); - #else - VectorSubtract( pm->ps->origin, hitEnt->s.origin, bounceDir ); - #endif - VectorNormalize( bounceDir ); +#ifdef _GAME + VectorSubtract(pm->ps->origin, hitEnt->r.currentOrigin, bounceDir); +#else + VectorSubtract(pm->ps->origin, hitEnt->s.origin, bounceDir); +#endif + VectorNormalize(bounceDir); } } - if ( turnFromImpact ) - {//bounce off impact surf and turn away - vec3_t pushDir={0}, turnAwayAngles, turnDelta; - float turnStrength, pitchTurnStrength, yawTurnStrength; - vec3_t moveDir; + if (turnFromImpact) { // bounce off impact surf and turn away + vec3_t pushDir = {0}, turnAwayAngles, turnDelta; + float turnStrength, pitchTurnStrength, yawTurnStrength; + vec3_t moveDir; float bounceDot, turnDivider; - //bounce - if ( !turnHitEnt ) - {//hit wall - VectorScale(bounceDir, (pm->ps->speed*0.25f/pSelfVeh->m_pVehicleInfo->mass), pushDir); - } - else - {//hit another fighter - #ifdef _GAME - if ( hitEnt->client ) - { - VectorScale( bounceDir, (pm->ps->speed+hitEnt->client->ps.speed)*0.5f, pushDir ); - } - else - { - VectorScale( bounceDir, (pm->ps->speed+hitEnt->s.speed)*0.5f, pushDir ); - } - #else - VectorScale( bounceDir, (pm->ps->speed+hitEnt->s.speed)*0.5f, bounceDir ); - #endif - VectorScale(pushDir, (l/pSelfVeh->m_pVehicleInfo->mass), pushDir); + // bounce + if (!turnHitEnt) { // hit wall + VectorScale(bounceDir, (pm->ps->speed * 0.25f / pSelfVeh->m_pVehicleInfo->mass), pushDir); + } else { // hit another fighter +#ifdef _GAME + if (hitEnt->client) { + VectorScale(bounceDir, (pm->ps->speed + hitEnt->client->ps.speed) * 0.5f, pushDir); + } else { + VectorScale(bounceDir, (pm->ps->speed + hitEnt->s.speed) * 0.5f, pushDir); + } +#else + VectorScale(bounceDir, (pm->ps->speed + hitEnt->s.speed) * 0.5f, bounceDir); +#endif + VectorScale(pushDir, (l / pSelfVeh->m_pVehicleInfo->mass), pushDir); VectorScale(pushDir, 0.1f, pushDir); } - VectorNormalize2( pm->ps->velocity, moveDir ); - bounceDot = DotProduct( moveDir, bounceDir )*-1; - if ( bounceDot < 0.1f ) - { + VectorNormalize2(pm->ps->velocity, moveDir); + bounceDot = DotProduct(moveDir, bounceDir) * -1; + if (bounceDot < 0.1f) { bounceDot = 0.1f; } - VectorScale( pushDir, bounceDot, pushDir ); + VectorScale(pushDir, bounceDot, pushDir); VectorAdd(pm->ps->velocity, pushDir, pm->ps->velocity); - //turn - turnDivider = (pSelfVeh->m_pVehicleInfo->mass/400.0f); - if ( turnHitEnt ) - {//don't turn as much when hit another ship + // turn + turnDivider = (pSelfVeh->m_pVehicleInfo->mass / 400.0f); + if (turnHitEnt) { // don't turn as much when hit another ship turnDivider *= 4.0f; } - if ( turnDivider < 0.5f ) - { + if (turnDivider < 0.5f) { turnDivider = 0.5f; } - turnStrength = (magnitude/2000.0f); - if ( turnStrength < 0.1f ) - { + turnStrength = (magnitude / 2000.0f); + if (turnStrength < 0.1f) { turnStrength = 0.1f; - } - else if ( turnStrength > 2.0f ) - { + } else if (turnStrength > 2.0f) { turnStrength = 2.0f; } - //get the angles we are going to turn towards - vectoangles( bounceDir, turnAwayAngles ); - //get the delta from our current angles to those new angles - AnglesSubtract( turnAwayAngles, pSelfVeh->m_vOrientation, turnDelta ); - //now do pitch - if ( !bounceDir[2] ) - {//shouldn't be any pitch - } - else - { - pitchTurnStrength = turnStrength*turnDelta[PITCH]; - if ( pitchTurnStrength > MAX_IMPACT_TURN_ANGLE ) - { + // get the angles we are going to turn towards + vectoangles(bounceDir, turnAwayAngles); + // get the delta from our current angles to those new angles + AnglesSubtract(turnAwayAngles, pSelfVeh->m_vOrientation, turnDelta); + // now do pitch + if (!bounceDir[2]) { // shouldn't be any pitch + } else { + pitchTurnStrength = turnStrength * turnDelta[PITCH]; + if (pitchTurnStrength > MAX_IMPACT_TURN_ANGLE) { pitchTurnStrength = MAX_IMPACT_TURN_ANGLE; - } - else if ( pitchTurnStrength < -MAX_IMPACT_TURN_ANGLE ) - { + } else if (pitchTurnStrength < -MAX_IMPACT_TURN_ANGLE) { pitchTurnStrength = -MAX_IMPACT_TURN_ANGLE; } - //pSelfVeh->m_vOrientation[PITCH] = AngleNormalize180(pSelfVeh->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); - pSelfVeh->m_vFullAngleVelocity[PITCH] = AngleNormalize180(pSelfVeh->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + // pSelfVeh->m_vOrientation[PITCH] = + // AngleNormalize180(pSelfVeh->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + pSelfVeh->m_vFullAngleVelocity[PITCH] = + AngleNormalize180(pSelfVeh->m_vOrientation[PITCH] + pitchTurnStrength / turnDivider * pSelfVeh->m_fTimeModifier); } - //now do yaw - if ( !bounceDir[0] - && !bounceDir[1] ) - {//shouldn't be any yaw - } - else - { - yawTurnStrength = turnStrength*turnDelta[YAW]; - if ( yawTurnStrength > MAX_IMPACT_TURN_ANGLE ) - { + // now do yaw + if (!bounceDir[0] && !bounceDir[1]) { // shouldn't be any yaw + } else { + yawTurnStrength = turnStrength * turnDelta[YAW]; + if (yawTurnStrength > MAX_IMPACT_TURN_ANGLE) { yawTurnStrength = MAX_IMPACT_TURN_ANGLE; - } - else if ( yawTurnStrength < -MAX_IMPACT_TURN_ANGLE ) - { + } else if (yawTurnStrength < -MAX_IMPACT_TURN_ANGLE) { yawTurnStrength = -MAX_IMPACT_TURN_ANGLE; } - //pSelfVeh->m_vOrientation[ROLL] = AngleNormalize180(pSelfVeh->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); - pSelfVeh->m_vFullAngleVelocity[ROLL] = AngleNormalize180(pSelfVeh->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + // pSelfVeh->m_vOrientation[ROLL] = + // AngleNormalize180(pSelfVeh->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + pSelfVeh->m_vFullAngleVelocity[ROLL] = + AngleNormalize180(pSelfVeh->m_vOrientation[ROLL] - yawTurnStrength / turnDivider * pSelfVeh->m_fTimeModifier); } /* PM_SetPMViewAngle(pm->ps, pSelfVeh->m_vOrientation, &pSelfVeh->m_ucmd); @@ -353,79 +292,67 @@ void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) } } */ -#ifdef _GAME//server-side, turn the guy we hit away from us, too - if ( turnHitEnt//make the other guy turn and get pushed - && hitEnt->client //must be a valid client - && !FighterIsLanded( hitEnt->m_pVehicle, &hitEnt->client->ps )//but not if landed - && !(hitEnt->spawnflags&2) )//and not if suspended +#ifdef _GAME // server-side, turn the guy we hit away from us, too + if (turnHitEnt // make the other guy turn and get pushed + && hitEnt->client // must be a valid client + && !FighterIsLanded(hitEnt->m_pVehicle, &hitEnt->client->ps) // but not if landed + && !(hitEnt->spawnflags & 2)) // and not if suspended { l = hitEnt->client->ps.speed; - //now bounce *them* away and turn them - //flip the bounceDir - VectorScale( bounceDir, -1, bounceDir ); - //do bounce - VectorScale( bounceDir, (pm->ps->speed+l)*0.5f, pushDir ); - VectorScale(pushDir, (l*0.5f/hitEnt->m_pVehicle->m_pVehicleInfo->mass), pushDir); - VectorNormalize2( hitEnt->client->ps.velocity, moveDir ); - bounceDot = DotProduct( moveDir, bounceDir )*-1; - if ( bounceDot < 0.1f ) - { + // now bounce *them* away and turn them + // flip the bounceDir + VectorScale(bounceDir, -1, bounceDir); + // do bounce + VectorScale(bounceDir, (pm->ps->speed + l) * 0.5f, pushDir); + VectorScale(pushDir, (l * 0.5f / hitEnt->m_pVehicle->m_pVehicleInfo->mass), pushDir); + VectorNormalize2(hitEnt->client->ps.velocity, moveDir); + bounceDot = DotProduct(moveDir, bounceDir) * -1; + if (bounceDot < 0.1f) { bounceDot = 0.1f; } - VectorScale( pushDir, bounceDot, pushDir ); + VectorScale(pushDir, bounceDot, pushDir); VectorAdd(hitEnt->client->ps.velocity, pushDir, hitEnt->client->ps.velocity); - //turn - turnDivider = (hitEnt->m_pVehicle->m_pVehicleInfo->mass/400.0f); - if ( turnHitEnt ) - {//don't turn as much when hit another ship + // turn + turnDivider = (hitEnt->m_pVehicle->m_pVehicleInfo->mass / 400.0f); + if (turnHitEnt) { // don't turn as much when hit another ship turnDivider *= 4.0f; } - if ( turnDivider < 0.5f ) - { + if (turnDivider < 0.5f) { turnDivider = 0.5f; } - //get the angles we are going to turn towards - vectoangles( bounceDir, turnAwayAngles ); - //get the delta from our current angles to those new angles - AnglesSubtract( turnAwayAngles, hitEnt->m_pVehicle->m_vOrientation, turnDelta ); - //now do pitch - if ( !bounceDir[2] ) - {//shouldn't be any pitch - } - else - { - pitchTurnStrength = turnStrength*turnDelta[PITCH]; - if ( pitchTurnStrength > MAX_IMPACT_TURN_ANGLE ) - { + // get the angles we are going to turn towards + vectoangles(bounceDir, turnAwayAngles); + // get the delta from our current angles to those new angles + AnglesSubtract(turnAwayAngles, hitEnt->m_pVehicle->m_vOrientation, turnDelta); + // now do pitch + if (!bounceDir[2]) { // shouldn't be any pitch + } else { + pitchTurnStrength = turnStrength * turnDelta[PITCH]; + if (pitchTurnStrength > MAX_IMPACT_TURN_ANGLE) { pitchTurnStrength = MAX_IMPACT_TURN_ANGLE; - } - else if ( pitchTurnStrength < -MAX_IMPACT_TURN_ANGLE ) - { + } else if (pitchTurnStrength < -MAX_IMPACT_TURN_ANGLE) { pitchTurnStrength = -MAX_IMPACT_TURN_ANGLE; } - //hitEnt->m_pVehicle->m_vOrientation[PITCH] = AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); - hitEnt->m_pVehicle->m_vFullAngleVelocity[PITCH] = AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); - } - //now do yaw - if ( !bounceDir[0] - && !bounceDir[1] ) - {//shouldn't be any yaw + // hitEnt->m_pVehicle->m_vOrientation[PITCH] = + // AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[PITCH]+pitchTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + hitEnt->m_pVehicle->m_vFullAngleVelocity[PITCH] = + AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[PITCH] + pitchTurnStrength / turnDivider * pSelfVeh->m_fTimeModifier); } - else - { - yawTurnStrength = turnStrength*turnDelta[YAW]; - if ( yawTurnStrength > MAX_IMPACT_TURN_ANGLE ) - { + // now do yaw + if (!bounceDir[0] && !bounceDir[1]) { // shouldn't be any yaw + } else { + yawTurnStrength = turnStrength * turnDelta[YAW]; + if (yawTurnStrength > MAX_IMPACT_TURN_ANGLE) { yawTurnStrength = MAX_IMPACT_TURN_ANGLE; - } - else if ( yawTurnStrength < -MAX_IMPACT_TURN_ANGLE ) - { + } else if (yawTurnStrength < -MAX_IMPACT_TURN_ANGLE) { yawTurnStrength = -MAX_IMPACT_TURN_ANGLE; } - //hitEnt->m_pVehicle->m_vOrientation[ROLL] = AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); - hitEnt->m_pVehicle->m_vFullAngleVelocity[ROLL] = AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + // hitEnt->m_pVehicle->m_vOrientation[ROLL] = + // AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[ROLL]-yawTurnStrength/turnDivider*pSelfVeh->m_fTimeModifier); + hitEnt->m_pVehicle->m_vFullAngleVelocity[ROLL] = + AngleNormalize180(hitEnt->m_pVehicle->m_vOrientation[ROLL] - yawTurnStrength / turnDivider * pSelfVeh->m_fTimeModifier); } - //NOTE: will these angle changes stick or will they be stomped + // NOTE: will these angle changes stick or will they be stomped // when the vehicle goes through its own update and re-grabs // its angles from its pilot...? Should we do a // SetClientViewAngles on the pilot? @@ -443,41 +370,31 @@ void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) } #ifdef _GAME - if (!hitEnt) - { + if (!hitEnt) { return; } - AngleVectors( pSelfVeh->m_vOrientation, NULL, NULL, vehUp ); - if ( pSelfVeh->m_pVehicleInfo->iImpactFX ) - { - //G_PlayEffectID( pSelfVeh->m_pVehicleInfo->iImpactFX, pm->ps->origin, vehUp ); - //tempent use bad! + AngleVectors(pSelfVeh->m_vOrientation, NULL, NULL, vehUp); + if (pSelfVeh->m_pVehicleInfo->iImpactFX) { + // G_PlayEffectID( pSelfVeh->m_pVehicleInfo->iImpactFX, pm->ps->origin, vehUp ); + // tempent use bad! G_AddEvent((gentity_t *)pEnt, EV_PLAY_EFFECT_ID, pSelfVeh->m_pVehicleInfo->iImpactFX); } pEnt->m_pVehicle->m_iHitDebounce = pm->cmd.serverTime + 200; magnitude /= pSelfVeh->m_pVehicleInfo->toughness * 50.0f; - if (hitEnt && (hitEnt->s.eType != ET_TERRAIN || !(hitEnt->spawnflags & 1) || pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER)) - { //don't damage the vehicle from terrain that doesn't want to damage vehicles - if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) - { //increase the damage... - float mult = (pSelfVeh->m_vOrientation[PITCH]*0.1f); - if (mult < 1.0f) - { + if (hitEnt && (hitEnt->s.eType != ET_TERRAIN || !(hitEnt->spawnflags & 1) || + pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER)) { // don't damage the vehicle from terrain that doesn't want to damage vehicles + if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) { // increase the damage... + float mult = (pSelfVeh->m_vOrientation[PITCH] * 0.1f); + if (mult < 1.0f) { mult = 1.0f; } - if (hitEnt->inuse && hitEnt->takedamage) - { //if the other guy takes damage, don't hurt us a lot for ramming him - //unless it's a vehicle, then we get 1.5 times damage - if (hitEnt->s.eType == ET_NPC && - hitEnt->s.NPC_class == CLASS_VEHICLE && - hitEnt->m_pVehicle) - { + if (hitEnt->inuse && hitEnt->takedamage) { // if the other guy takes damage, don't hurt us a lot for ramming him + // unless it's a vehicle, then we get 1.5 times damage + if (hitEnt->s.eType == ET_NPC && hitEnt->s.NPC_class == CLASS_VEHICLE && hitEnt->m_pVehicle) { mult = 1.5f; - } - else - { + } else { mult = 0.5f; } } @@ -485,85 +402,68 @@ void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) magnitude *= mult; } pSelfVeh->m_iLastImpactDmg = magnitude; - //FIXME: what about proper death credit to the guy who shot you down? - //FIXME: actually damage part of the ship that impacted? - G_Damage( (gentity_t *)pEnt, NULL, NULL, NULL, pm->ps->origin, magnitude*5, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + // FIXME: what about proper death credit to the guy who shot you down? + // FIXME: actually damage part of the ship that impacted? + G_Damage((gentity_t *)pEnt, NULL, NULL, NULL, pm->ps->origin, magnitude * 5, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT - if (pSelfVeh->m_pVehicleInfo->surfDestruction) - { - G_FlyVehicleSurfaceDestruction((gentity_t *)pEnt, trace, magnitude, forceSurfDestruction ); + if (pSelfVeh->m_pVehicleInfo->surfDestruction) { + G_FlyVehicleSurfaceDestruction((gentity_t *)pEnt, trace, magnitude, forceSurfDestruction); } pSelfVeh->m_ulFlags |= VEH_CRASHING; } - if (hitEnt && - hitEnt->inuse && - hitEnt->takedamage) - { //damage this guy because we hit him + if (hitEnt && hitEnt->inuse && hitEnt->takedamage) { // damage this guy because we hit him float pmult = 1.0f; int finalD; gentity_t *attackEnt; - if ( (hitEnt->s.eType == ET_PLAYER && hitEnt->s.number < MAX_CLIENTS) || - (hitEnt->s.eType == ET_NPC && hitEnt->s.NPC_class != CLASS_VEHICLE) ) - { //probably a humanoid, or something - if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) - { //player die good.. if me fighter + if ((hitEnt->s.eType == ET_PLAYER && hitEnt->s.number < MAX_CLIENTS) || + (hitEnt->s.eType == ET_NPC && hitEnt->s.NPC_class != CLASS_VEHICLE)) { // probably a humanoid, or something + if (pSelfVeh->m_pVehicleInfo->type == VH_FIGHTER) { // player die good.. if me fighter pmult = 2000.0f; - } - else - { + } else { pmult = 40.0f; } - if (hitEnt->client && - BG_KnockDownable(&hitEnt->client->ps) && - G_CanBeEnemy((gentity_t *)pEnt, hitEnt)) - { //smash! - if (hitEnt->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) - { + if (hitEnt->client && BG_KnockDownable(&hitEnt->client->ps) && G_CanBeEnemy((gentity_t *)pEnt, hitEnt)) { // smash! + if (hitEnt->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) { hitEnt->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; hitEnt->client->ps.forceHandExtendTime = pm->cmd.serverTime + 1100; - hitEnt->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim + hitEnt->client->ps.forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim } hitEnt->client->ps.otherKiller = pEnt->s.number; hitEnt->client->ps.otherKillerTime = pm->cmd.serverTime + 5000; hitEnt->client->ps.otherKillerDebounceTime = pm->cmd.serverTime + 100; - //add my velocity into his to force him along in the correct direction from impact + // add my velocity into his to force him along in the correct direction from impact VectorAdd(hitEnt->client->ps.velocity, pm->ps->velocity, hitEnt->client->ps.velocity); - //upward thrust + // upward thrust hitEnt->client->ps.velocity[2] += 200.0f; } } - if (pSelfVeh->m_pPilot) - { + if (pSelfVeh->m_pPilot) { attackEnt = (gentity_t *)pSelfVeh->m_pPilot; - } - else - { + } else { attackEnt = (gentity_t *)pEnt; } - finalD = magnitude*pmult; - if (finalD < 1) - { + finalD = magnitude * pmult; + if (finalD < 1) { finalD = 1; } - G_Damage( hitEnt, attackEnt, attackEnt, NULL, pm->ps->origin, finalD, 0, MOD_MELEE );//FIXME: MOD_IMPACT + G_Damage(hitEnt, attackEnt, attackEnt, NULL, pm->ps->origin, finalD, 0, MOD_MELEE); // FIXME: MOD_IMPACT } -#else //this is gonna result in "double effects" for the client doing the prediction. - //it doesn't look bad though. could just use predicted events, but I'm too lazy. +#else // this is gonna result in "double effects" for the client doing the prediction. + // it doesn't look bad though. could just use predicted events, but I'm too lazy. hitEnt = PM_BGEntForNum(trace->entityNum); - if (!hitEnt || hitEnt->s.owner != pEnt->s.number) - { //don't hit your own missiles! - AngleVectors( pSelfVeh->m_vOrientation, NULL, NULL, vehUp ); + if (!hitEnt || hitEnt->s.owner != pEnt->s.number) { // don't hit your own missiles! + AngleVectors(pSelfVeh->m_vOrientation, NULL, NULL, vehUp); pEnt->m_pVehicle->m_iHitDebounce = pm->cmd.serverTime + 200; - trap->FX_PlayEffectID( pSelfVeh->m_pVehicleInfo->iImpactFX, pm->ps->origin, vehUp, -1, -1, qfalse ); + trap->FX_PlayEffectID(pSelfVeh->m_pVehicleInfo->iImpactFX, pm->ps->origin, vehUp, -1, -1, qfalse); pSelfVeh->m_ulFlags |= VEH_CRASHING; } @@ -572,22 +472,13 @@ void PM_VehicleImpact(bgEntity_t *pEnt, trace_t *trace) } } -qboolean PM_GroundSlideOkay( float zNormal ) -{ - if ( zNormal > 0 ) - { - if ( pm->ps->velocity[2] > 0 ) - { - if ( pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT - || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP - || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP - || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_START - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK - || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND - || BG_InReboundJump( pm->ps->legsAnim )) - { +qboolean PM_GroundSlideOkay(float zNormal) { + if (zNormal > 0) { + if (pm->ps->velocity[2] > 0) { + if (pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT || pm->ps->legsAnim == BOTH_WALL_RUN_LEFT || pm->ps->legsAnim == BOTH_WALL_RUN_RIGHT_STOP || + pm->ps->legsAnim == BOTH_WALL_RUN_LEFT_STOP || pm->ps->legsAnim == BOTH_FORCEWALLRUNFLIP_START || + pm->ps->legsAnim == BOTH_FORCELONGLEAP_START || pm->ps->legsAnim == BOTH_FORCELONGLEAP_ATTACK || pm->ps->legsAnim == BOTH_FORCELONGLEAP_LAND || + BG_InReboundJump(pm->ps->legsAnim)) { return qfalse; } } @@ -602,36 +493,29 @@ qboolean PM_ClientImpact( trace_t *trace, qboolean damageSelf ) =============== */ #ifdef _GAME -extern void Client_CheckImpactBBrush( gentity_t *self, gentity_t *other ); -qboolean PM_ClientImpact( trace_t *trace ) -{ - //don't try to predict this - gentity_t *traceEnt; - int otherEntityNum = trace->entityNum; - - if ( !pm_entSelf ) - { +extern void Client_CheckImpactBBrush(gentity_t *self, gentity_t *other); +qboolean PM_ClientImpact(trace_t *trace) { + // don't try to predict this + gentity_t *traceEnt; + int otherEntityNum = trace->entityNum; + + if (!pm_entSelf) { return qfalse; } - if ( otherEntityNum >= ENTITYNUM_WORLD ) - { + if (otherEntityNum >= ENTITYNUM_WORLD) { return qfalse; } traceEnt = &g_entities[otherEntityNum]; - if( VectorLength( pm->ps->velocity ) >= 100 - && pm_entSelf->s.NPC_class != CLASS_VEHICLE - && pm->ps->lastOnGround+100 < level.time ) - //&& pm->ps->groundEntityNum == ENTITYNUM_NONE ) + if (VectorLength(pm->ps->velocity) >= 100 && pm_entSelf->s.NPC_class != CLASS_VEHICLE && pm->ps->lastOnGround + 100 < level.time) + //&& pm->ps->groundEntityNum == ENTITYNUM_NONE ) { - Client_CheckImpactBBrush( (gentity_t *)(pm_entSelf), &g_entities[otherEntityNum] ); + Client_CheckImpactBBrush((gentity_t *)(pm_entSelf), &g_entities[otherEntityNum]); } - if ( !traceEnt - || !(traceEnt->r.contents&pm->tracemask) ) - {//it's dead or not in my way anymore, don't clip against it + if (!traceEnt || !(traceEnt->r.contents & pm->tracemask)) { // it's dead or not in my way anymore, don't clip against it return qtrue; } @@ -646,38 +530,36 @@ PM_SlideMove Returns qtrue if the velocity was clipped in some way ================== */ -#define MAX_CLIP_PLANES 5 -qboolean PM_SlideMove( qboolean gravity ) { - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t normal, planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity; - vec3_t clipVelocity; - int i, j, k; - trace_t trace; - vec3_t end; - float time_left; - float into; - vec3_t endVelocity; - vec3_t endClipVelocity; - //qboolean damageSelf = qtrue; +#define MAX_CLIP_PLANES 5 +qboolean PM_SlideMove(qboolean gravity) { + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t normal, planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity; + vec3_t clipVelocity; + int i, j, k; + trace_t trace; + vec3_t end; + float time_left; + float into; + vec3_t endVelocity; + vec3_t endClipVelocity; + // qboolean damageSelf = qtrue; numbumps = 4; - VectorCopy (pm->ps->velocity, primal_velocity); - VectorCopy (pm->ps->velocity, endVelocity); + VectorCopy(pm->ps->velocity, primal_velocity); + VectorCopy(pm->ps->velocity, endVelocity); - if ( gravity ) { + if (gravity) { endVelocity[2] -= pm->ps->gravity * pml.frametime; - pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5; + pm->ps->velocity[2] = (pm->ps->velocity[2] + endVelocity[2]) * 0.5; primal_velocity[2] = endVelocity[2]; - if ( pml.groundPlane ) { - if ( PM_GroundSlideOkay( pml.groundTrace.plane.normal[2] ) ) - {// slide along the ground plane - PM_ClipVelocity (pm->ps->velocity, pml.groundTrace.plane.normal, - pm->ps->velocity, OVERCLIP ); + if (pml.groundPlane) { + if (PM_GroundSlideOkay(pml.groundTrace.plane.normal[2])) { // slide along the ground plane + PM_ClipVelocity(pm->ps->velocity, pml.groundTrace.plane.normal, pm->ps->velocity, OVERCLIP); } } } @@ -685,63 +567,57 @@ qboolean PM_SlideMove( qboolean gravity ) { time_left = pml.frametime; // never turn against the ground plane - if ( pml.groundPlane ) { + if (pml.groundPlane) { numplanes = 1; - VectorCopy( pml.groundTrace.plane.normal, planes[0] ); - if ( !PM_GroundSlideOkay( planes[0][2] ) ) - { + VectorCopy(pml.groundTrace.plane.normal, planes[0]); + if (!PM_GroundSlideOkay(planes[0][2])) { planes[0][2] = 0; - VectorNormalize( planes[0] ); + VectorNormalize(planes[0]); } } else { numplanes = 0; } // never turn against original velocity - VectorNormalize2( pm->ps->velocity, planes[numplanes] ); + VectorNormalize2(pm->ps->velocity, planes[numplanes]); numplanes++; - for ( bumpcount=0 ; bumpcount < numbumps ; bumpcount++ ) { + for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { // calculate position we are trying to move to - VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end ); + VectorMA(pm->ps->origin, time_left, pm->ps->velocity, end); // see if we can make it there - pm->trace ( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask); if (trace.allsolid) { // entity is completely trapped in another solid - pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration + pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration return qtrue; } if (trace.fraction > 0) { // actually covered some distance - VectorCopy (trace.endpos, pm->ps->origin); + VectorCopy(trace.endpos, pm->ps->origin); } if (trace.fraction == 1) { - break; // moved the entire distance + break; // moved the entire distance } // save entity for contact - PM_AddTouchEnt( trace.entityNum ); + PM_AddTouchEnt(trace.entityNum); - if (pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { bgEntity_t *pEnt = pm_entSelf; - if (pEnt && pEnt->s.eType == ET_NPC && pEnt->s.NPC_class == CLASS_VEHICLE && - pEnt->m_pVehicle) - { //do vehicle impact stuff then + if (pEnt && pEnt->s.eType == ET_NPC && pEnt->s.NPC_class == CLASS_VEHICLE && pEnt->m_pVehicle) { // do vehicle impact stuff then PM_VehicleImpact(pEnt, &trace); } } #ifdef _GAME - else - { - if ( PM_ClientImpact( &trace ) ) - { + else { + if (PM_ClientImpact(&trace)) { continue; } } @@ -751,36 +627,34 @@ qboolean PM_SlideMove( qboolean gravity ) { if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen - VectorClear( pm->ps->velocity ); + VectorClear(pm->ps->velocity); return qtrue; } - VectorCopy( trace.plane.normal, normal ); + VectorCopy(trace.plane.normal, normal); - if ( !PM_GroundSlideOkay( normal[2] ) ) - {//wall-running - //never push up off a sloped wall + if (!PM_GroundSlideOkay(normal[2])) { // wall-running + // never push up off a sloped wall normal[2] = 0; - VectorNormalize( normal ); + VectorNormalize(normal); } // // if this is the same plane we hit before, nudge velocity // out along it, which fixes some epsilon issues with // non-axial planes // - if ( !(pm->ps->pm_flags&PMF_STUCK_TO_WALL) ) - {//no sliding if stuck to wall! - for ( i = 0 ; i < numplanes ; i++ ) { - if ( VectorCompare( normal, planes[i] ) ) {//DotProduct( normal, planes[i] ) > 0.99 ) { - VectorAdd( normal, pm->ps->velocity, pm->ps->velocity ); + if (!(pm->ps->pm_flags & PMF_STUCK_TO_WALL)) { // no sliding if stuck to wall! + for (i = 0; i < numplanes; i++) { + if (VectorCompare(normal, planes[i])) { // DotProduct( normal, planes[i] ) > 0.99 ) { + VectorAdd(normal, pm->ps->velocity, pm->ps->velocity); break; } } - if ( i < numplanes ) { + if (i < numplanes) { continue; } } - VectorCopy (normal, planes[numplanes]); + VectorCopy(normal, planes[numplanes]); numplanes++; // @@ -788,84 +662,84 @@ qboolean PM_SlideMove( qboolean gravity ) { // // find a plane that it enters - for ( i = 0 ; i < numplanes ; i++ ) { - into = DotProduct( pm->ps->velocity, planes[i] ); - if ( into >= 0.1 ) { - continue; // move doesn't interact with the plane + for (i = 0; i < numplanes; i++) { + into = DotProduct(pm->ps->velocity, planes[i]); + if (into >= 0.1) { + continue; // move doesn't interact with the plane } // see how hard we are hitting things - if ( -into > pml.impactSpeed ) { + if (-into > pml.impactSpeed) { pml.impactSpeed = -into; } // slide along the plane - PM_ClipVelocity (pm->ps->velocity, planes[i], clipVelocity, OVERCLIP ); + PM_ClipVelocity(pm->ps->velocity, planes[i], clipVelocity, OVERCLIP); // slide along the plane - PM_ClipVelocity (endVelocity, planes[i], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(endVelocity, planes[i], endClipVelocity, OVERCLIP); // see if there is a second plane that the new move enters - for ( j = 0 ; j < numplanes ; j++ ) { - if ( j == i ) { + for (j = 0; j < numplanes; j++) { + if (j == i) { continue; } - if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[j]) >= 0.1) { + continue; // move doesn't interact with the plane } // try clipping the move to the plane - PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP ); - PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP ); + PM_ClipVelocity(clipVelocity, planes[j], clipVelocity, OVERCLIP); + PM_ClipVelocity(endClipVelocity, planes[j], endClipVelocity, OVERCLIP); // see if it goes back into the first clip plane - if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) { + if (DotProduct(clipVelocity, planes[i]) >= 0) { continue; } // slide the original velocity along the crease - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, pm->ps->velocity ); - VectorScale( dir, d, clipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, pm->ps->velocity); + VectorScale(dir, d, clipVelocity); - CrossProduct (planes[i], planes[j], dir); - VectorNormalize( dir ); - d = DotProduct( dir, endVelocity ); - VectorScale( dir, d, endClipVelocity ); + CrossProduct(planes[i], planes[j], dir); + VectorNormalize(dir); + d = DotProduct(dir, endVelocity); + VectorScale(dir, d, endClipVelocity); // see if there is a third plane the the new move enters - for ( k = 0 ; k < numplanes ; k++ ) { - if ( k == i || k == j ) { + for (k = 0; k < numplanes; k++) { + if (k == i || k == j) { continue; } - if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) { - continue; // move doesn't interact with the plane + if (DotProduct(clipVelocity, planes[k]) >= 0.1) { + continue; // move doesn't interact with the plane } // stop dead at a triple plane interaction - VectorClear( pm->ps->velocity ); + VectorClear(pm->ps->velocity); return qtrue; } } // if we have fixed all interactions, try another move - VectorCopy( clipVelocity, pm->ps->velocity ); - VectorCopy( endClipVelocity, endVelocity ); + VectorCopy(clipVelocity, pm->ps->velocity); + VectorCopy(endClipVelocity, endVelocity); break; } } - if ( gravity ) { - VectorCopy( endVelocity, pm->ps->velocity ); + if (gravity) { + VectorCopy(endVelocity, pm->ps->velocity); } // don't change velocity if in a timer (FIXME: is this correct?) - if ( pm->ps->pm_time ) { - VectorCopy( primal_velocity, pm->ps->velocity ); + if (pm->ps->pm_time) { + VectorCopy(primal_velocity, pm->ps->velocity); } - return ( bumpcount != 0 ); + return (bumpcount != 0); } /* @@ -874,143 +748,116 @@ PM_StepSlideMove ================== */ -void PM_StepSlideMove( qboolean gravity ) { - vec3_t start_o, start_v; - vec3_t down_o, down_v; - trace_t trace; -// float down_dist, up_dist; -// vec3_t delta, delta2; - vec3_t up, down; - float stepSize; - qboolean isGiant = qfalse; - bgEntity_t *pEnt; +void PM_StepSlideMove(qboolean gravity) { + vec3_t start_o, start_v; + vec3_t down_o, down_v; + trace_t trace; + // float down_dist, up_dist; + // vec3_t delta, delta2; + vec3_t up, down; + float stepSize; + qboolean isGiant = qfalse; + bgEntity_t *pEnt; qboolean skipStep = qfalse; - VectorCopy (pm->ps->origin, start_o); - VectorCopy (pm->ps->velocity, start_v); + VectorCopy(pm->ps->origin, start_o); + VectorCopy(pm->ps->velocity, start_v); - if ( BG_InReboundHold( pm->ps->legsAnim ) ) - { + if (BG_InReboundHold(pm->ps->legsAnim)) { gravity = qfalse; } - if ( PM_SlideMove( gravity ) == 0 ) { - return; // we got exactly where we wanted to go first try + if (PM_SlideMove(gravity) == 0) { + return; // we got exactly where we wanted to go first try } pEnt = pm_entSelf; - if (pm->ps->clientNum >= MAX_CLIENTS) - { - if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE && - pEnt->m_pVehicle && pEnt->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { + if (pEnt && pEnt->s.NPC_class == CLASS_VEHICLE && pEnt->m_pVehicle && pEnt->m_pVehicle->m_pVehicleInfo->hoverHeight > 0) { return; } } VectorCopy(start_o, down); down[2] -= STEPSIZE; - pm->trace (&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); + pm->trace(&trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); VectorSet(up, 0, 0, 1); // never step up when you still have up velocity - if ( pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || - DotProduct(trace.plane.normal, up) < 0.7)) - { + if (pm->ps->velocity[2] > 0 && (trace.fraction == 1.0 || DotProduct(trace.plane.normal, up) < 0.7)) { return; } - VectorCopy (pm->ps->origin, down_o); - VectorCopy (pm->ps->velocity, down_v); + VectorCopy(pm->ps->origin, down_o); + VectorCopy(pm->ps->velocity, down_v); - VectorCopy (start_o, up); + VectorCopy(start_o, up); - if (pm->ps->clientNum >= MAX_CLIENTS) - { + if (pm->ps->clientNum >= MAX_CLIENTS) { // apply ground friction, even if on ladder - if (pEnt && - (pEnt->s.NPC_class == CLASS_ATST || - (pEnt->s.NPC_class == CLASS_VEHICLE && pEnt->m_pVehicle && pEnt->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) ) ) - {//AT-STs can step high + if (pEnt && (pEnt->s.NPC_class == CLASS_ATST || + (pEnt->s.NPC_class == CLASS_VEHICLE && pEnt->m_pVehicle && pEnt->m_pVehicle->m_pVehicleInfo->type == VH_WALKER))) { // AT-STs can step high up[2] += 66.0f; isGiant = qtrue; - } - else if ( pEnt && pEnt->s.NPC_class == CLASS_RANCOR ) - {//also can step up high + } else if (pEnt && pEnt->s.NPC_class == CLASS_RANCOR) { // also can step up high up[2] += 64.0f; isGiant = qtrue; - } - else - { + } else { up[2] += STEPSIZE; } - } - else - { + } else { up[2] += STEPSIZE; } // test the player position if they were a stepheight higher - pm->trace (&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask); - if ( trace.allsolid ) { - if ( pm->debugLevel ) { + pm->trace(&trace, start_o, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask); + if (trace.allsolid) { + if (pm->debugLevel) { Com_Printf("%i:bend can't step\n", c_pmove); } - return; // can't step up + return; // can't step up } stepSize = trace.endpos[2] - start_o[2]; // try slidemove from this position - VectorCopy (trace.endpos, pm->ps->origin); - VectorCopy (start_v, pm->ps->velocity); + VectorCopy(trace.endpos, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); - PM_SlideMove( gravity ); + PM_SlideMove(gravity); // push down the final amount - VectorCopy (pm->ps->origin, down); + VectorCopy(pm->ps->origin, down); down[2] -= stepSize; - pm->trace (&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); + pm->trace(&trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask); - if ( pm->stepSlideFix ) - { - if ( pm->ps->clientNum < MAX_CLIENTS - && trace.plane.normal[2] < MIN_WALK_NORMAL ) - {//normal players cannot step up slopes that are too steep to walk on! + if (pm->stepSlideFix) { + if (pm->ps->clientNum < MAX_CLIENTS && trace.plane.normal[2] < MIN_WALK_NORMAL) { // normal players cannot step up slopes that are too steep to walk on! vec3_t stepVec; - //okay, the step up ends on a slope that it too steep to step up onto, - //BUT: - //If the step looks like this: - // (B)\__ - // \_____(A) - //Then it might still be okay, so we figure out the slope of the entire move - //from (A) to (B) and if that slope is walk-upabble, then it's okay - VectorSubtract( trace.endpos, down_o, stepVec ); - VectorNormalize( stepVec ); - if ( stepVec[2] > (1.0f-MIN_WALK_NORMAL) ) - { + // okay, the step up ends on a slope that it too steep to step up onto, + // BUT: + // If the step looks like this: + // (B)\__ + // \_____(A) + // Then it might still be okay, so we figure out the slope of the entire move + // from (A) to (B) and if that slope is walk-upabble, then it's okay + VectorSubtract(trace.endpos, down_o, stepVec); + VectorNormalize(stepVec); + if (stepVec[2] > (1.0f - MIN_WALK_NORMAL)) { skipStep = qtrue; } } } - if ( !trace.allsolid - && !skipStep ) //normal players cannot step up slopes that are too steep to walk on! + if (!trace.allsolid && !skipStep) // normal players cannot step up slopes that are too steep to walk on! { - if ( pm->ps->clientNum >= MAX_CLIENTS//NPC - && isGiant - && trace.entityNum < MAX_CLIENTS - && pEnt - && pEnt->s.NPC_class == CLASS_RANCOR ) - {//Rancor don't step on clients - if ( pm->stepSlideFix ) - { - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); - } - else - { - VectorCopy (start_o, pm->ps->origin); - VectorCopy (start_v, pm->ps->velocity); + if (pm->ps->clientNum >= MAX_CLIENTS // NPC + && isGiant && trace.entityNum < MAX_CLIENTS && pEnt && pEnt->s.NPC_class == CLASS_RANCOR) { // Rancor don't step on clients + if (pm->stepSlideFix) { + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); + } else { + VectorCopy(start_o, pm->ps->origin); + VectorCopy(start_v, pm->ps->velocity); } } /* @@ -1025,29 +872,23 @@ void PM_StepSlideMove( qboolean gravity ) { VectorCopy (start_v, pm->ps->velocity); } */ - else - { - VectorCopy (trace.endpos, pm->ps->origin); - if ( pm->stepSlideFix ) - { - if ( trace.fraction < 1.0 ) { - PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); + else { + VectorCopy(trace.endpos, pm->ps->origin); + if (pm->stepSlideFix) { + if (trace.fraction < 1.0) { + PM_ClipVelocity(pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP); } } } - } - else - { - if ( pm->stepSlideFix ) - { - VectorCopy (down_o, pm->ps->origin); - VectorCopy (down_v, pm->ps->velocity); + } else { + if (pm->stepSlideFix) { + VectorCopy(down_o, pm->ps->origin); + VectorCopy(down_v, pm->ps->velocity); } } - if ( !pm->stepSlideFix ) - { - if ( trace.fraction < 1.0 ) { - PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP ); + if (!pm->stepSlideFix) { + if (trace.fraction < 1.0) { + PM_ClipVelocity(pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP); } } @@ -1065,24 +906,22 @@ void PM_StepSlideMove( qboolean gravity ) { #endif { // use the step move - float delta; + float delta; delta = pm->ps->origin[2] - start_o[2]; - if ( delta > 2 ) { - if ( delta < 7 ) { - PM_AddEvent( EV_STEP_4 ); - } else if ( delta < 11 ) { - PM_AddEvent( EV_STEP_8 ); - } else if ( delta < 15 ) { - PM_AddEvent( EV_STEP_12 ); + if (delta > 2) { + if (delta < 7) { + PM_AddEvent(EV_STEP_4); + } else if (delta < 11) { + PM_AddEvent(EV_STEP_8); + } else if (delta < 15) { + PM_AddEvent(EV_STEP_12); } else { - PM_AddEvent( EV_STEP_16 ); + PM_AddEvent(EV_STEP_16); } } - if ( pm->debugLevel ) { + if (pm->debugLevel) { Com_Printf("%i:stepped\n", c_pmove); } } } - - diff --git a/codemp/game/bg_vehicleLoad.c b/codemp/game/bg_vehicleLoad.c index a77d3dea0e..43e62b3fb2 100644 --- a/codemp/game/bg_vehicleLoad.c +++ b/codemp/game/bg_vehicleLoad.c @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -//bg_vehicleLoad.c +// bg_vehicleLoad.c #include "qcommon/q_shared.h" #include "bg_public.h" @@ -28,462 +28,433 @@ along with this program; if not, see . #include "bg_weapons.h" #ifdef _GAME - #include "g_local.h" +#include "g_local.h" #elif _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; // These buffers are filled in with the same contents and then just read from in // a few places. We only need one copy on Xbox. #define MAX_VEH_WEAPON_DATA_SIZE 0x40000 // 0x4000 -#define MAX_VEHICLE_DATA_SIZE 0x100000 // 0x10000 +#define MAX_VEHICLE_DATA_SIZE 0x100000 // 0x10000 -char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; -char VehicleParms[MAX_VEHICLE_DATA_SIZE]; +char VehWeaponParms[MAX_VEH_WEAPON_DATA_SIZE]; +char VehicleParms[MAX_VEHICLE_DATA_SIZE]; -void BG_ClearVehicleParseParms(void) -{ - //You can't strcat to these forever without clearing them! +void BG_ClearVehicleParseParms(void) { + // You can't strcat to these forever without clearing them! VehWeaponParms[0] = 0; VehicleParms[0] = 0; } #if defined(_GAME) || defined(_CGAME) - //These funcs are actually shared in both projects - extern void G_SetAnimalVehicleFunctions( vehicleInfo_t *pVehInfo ); - extern void G_SetSpeederVehicleFunctions( vehicleInfo_t *pVehInfo ); - extern void G_SetWalkerVehicleFunctions( vehicleInfo_t *pVehInfo ); - extern void G_SetFighterVehicleFunctions( vehicleInfo_t *pVehInfo ); +// These funcs are actually shared in both projects +extern void G_SetAnimalVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetSpeederVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetWalkerVehicleFunctions(vehicleInfo_t *pVehInfo); +extern void G_SetFighterVehicleFunctions(vehicleInfo_t *pVehInfo); #endif vehWeaponInfo_t g_vehWeaponInfo[MAX_VEH_WEAPONS]; -int numVehicleWeapons = 1;//first one is null/default +int numVehicleWeapons = 1; // first one is null/default vehicleInfo_t g_vehicleInfo[MAX_VEHICLES]; -int numVehicles = 0;//first one is null/default +int numVehicles = 0; // first one is null/default -void BG_VehicleLoadParms( void ); +void BG_VehicleLoadParms(void); typedef enum { VF_IGNORE, VF_INT, VF_FLOAT, - VF_STRING, // string on disk, pointer in memory + VF_STRING, // string on disk, pointer in memory VF_VECTOR, VF_BOOL, VF_VEHTYPE, VF_ANIM, - VF_WEAPON, // take string, resolve into index into VehWeaponParms - VF_MODEL, // take the string, get the G_ModelIndex - VF_MODEL_CLIENT, // (cgame only) take the string, get the G_ModelIndex - VF_EFFECT, // take the string, get the G_EffectIndex - VF_EFFECT_CLIENT, // (cgame only) take the string, get the index - VF_SHADER, // (cgame only) take the string, call trap->R_RegisterShader - VF_SHADER_NOMIP,// (cgame only) take the string, call trap->R_RegisterShaderNoMip - VF_SOUND, // take the string, get the G_SoundIndex - VF_SOUND_CLIENT // (cgame only) take the string, get the index + VF_WEAPON, // take string, resolve into index into VehWeaponParms + VF_MODEL, // take the string, get the G_ModelIndex + VF_MODEL_CLIENT, // (cgame only) take the string, get the G_ModelIndex + VF_EFFECT, // take the string, get the G_EffectIndex + VF_EFFECT_CLIENT, // (cgame only) take the string, get the index + VF_SHADER, // (cgame only) take the string, call trap->R_RegisterShader + VF_SHADER_NOMIP, // (cgame only) take the string, call trap->R_RegisterShaderNoMip + VF_SOUND, // take the string, get the G_SoundIndex + VF_SOUND_CLIENT // (cgame only) take the string, get the index } vehFieldType_t; typedef struct vehField_s { - const char *name; - size_t ofs; - vehFieldType_t type; + const char *name; + size_t ofs; + vehFieldType_t type; } vehField_t; -vehField_t vehWeaponFields[] = -{ - {"name", VWFOFS(name), VF_STRING}, //unique name of the vehicle - {"projectile", VWFOFS(bIsProjectile), VF_BOOL}, //traceline or entity? - {"hasGravity", VWFOFS(bHasGravity), VF_BOOL}, //if a projectile, drops - {"ionWeapon", VWFOFS(bIonWeapon), VF_BOOL}, //disables ship shields and sends them out of control - {"saberBlockable", VWFOFS(bSaberBlockable), VF_BOOL}, //lightsabers can deflect this projectile - {"muzzleFX", VWFOFS(iMuzzleFX), VF_EFFECT_CLIENT}, //index of Muzzle Effect - {"model", VWFOFS(iModel), VF_MODEL_CLIENT}, //handle to the model used by this projectile - {"shotFX", VWFOFS(iShotFX), VF_EFFECT_CLIENT}, //index of Shot Effect - {"impactFX", VWFOFS(iImpactFX), VF_EFFECT_CLIENT}, //index of Impact Effect - {"g2MarkShader", VWFOFS(iG2MarkShaderHandle), VF_SHADER}, //index of shader to use for G2 marks made on other models when hit by this projectile - {"g2MarkSize", VWFOFS(fG2MarkSize), VF_FLOAT}, //size (diameter) of the ghoul2 mark - {"loopSound", VWFOFS(iLoopSound), VF_SOUND_CLIENT}, //index of loopSound - {"speed", VWFOFS(fSpeed), VF_FLOAT}, //speed of projectile/range of traceline - {"homing", VWFOFS(fHoming), VF_FLOAT}, //0.0 = not homing, 0.5 = half vel to targ, half cur vel, 1.0 = all vel to targ - {"homingFOV", VWFOFS(fHomingFOV), VF_FLOAT},//missile will lose lock on if DotProduct of missile direction and direction to target ever drops below this (-1 to 1, -1 = never lose target, 0 = lose if ship gets behind missile, 1 = pretty much will lose it's target right away) - {"lockOnTime", VWFOFS(iLockOnTime), VF_INT}, //0 = no lock time needed, else # of ms needed to lock on - {"damage", VWFOFS(iDamage), VF_INT}, //damage done when traceline or projectile directly hits target - {"splashDamage", VWFOFS(iSplashDamage), VF_INT},//damage done to ents in splashRadius of end of traceline or projectile origin on impact - {"splashRadius", VWFOFS(fSplashRadius), VF_FLOAT},//radius that ent must be in to take splashDamage (linear fall-off) - {"ammoPerShot", VWFOFS(iAmmoPerShot), VF_INT},//how much "ammo" each shot takes - {"health", VWFOFS(iHealth), VF_INT}, //if non-zero, projectile can be shot, takes this much damage before being destroyed - {"width", VWFOFS(fWidth), VF_FLOAT}, //width of traceline or bounding box of projecile (non-rotating!) - {"height", VWFOFS(fHeight), VF_FLOAT}, //height of traceline or bounding box of projecile (non-rotating!) - {"lifetime", VWFOFS(iLifeTime), VF_INT}, //removes itself after this amount of time - {"explodeOnExpire", VWFOFS(bExplodeOnExpire), VF_BOOL}, //when iLifeTime is up, explodes rather than simply removing itself +vehField_t vehWeaponFields[] = { + {"name", VWFOFS(name), VF_STRING}, // unique name of the vehicle + {"projectile", VWFOFS(bIsProjectile), VF_BOOL}, // traceline or entity? + {"hasGravity", VWFOFS(bHasGravity), VF_BOOL}, // if a projectile, drops + {"ionWeapon", VWFOFS(bIonWeapon), VF_BOOL}, // disables ship shields and sends them out of control + {"saberBlockable", VWFOFS(bSaberBlockable), VF_BOOL}, // lightsabers can deflect this projectile + {"muzzleFX", VWFOFS(iMuzzleFX), VF_EFFECT_CLIENT}, // index of Muzzle Effect + {"model", VWFOFS(iModel), VF_MODEL_CLIENT}, // handle to the model used by this projectile + {"shotFX", VWFOFS(iShotFX), VF_EFFECT_CLIENT}, // index of Shot Effect + {"impactFX", VWFOFS(iImpactFX), VF_EFFECT_CLIENT}, // index of Impact Effect + {"g2MarkShader", VWFOFS(iG2MarkShaderHandle), VF_SHADER}, // index of shader to use for G2 marks made on other models when hit by this projectile + {"g2MarkSize", VWFOFS(fG2MarkSize), VF_FLOAT}, // size (diameter) of the ghoul2 mark + {"loopSound", VWFOFS(iLoopSound), VF_SOUND_CLIENT}, // index of loopSound + {"speed", VWFOFS(fSpeed), VF_FLOAT}, // speed of projectile/range of traceline + {"homing", VWFOFS(fHoming), VF_FLOAT}, // 0.0 = not homing, 0.5 = half vel to targ, half cur vel, 1.0 = all vel to targ + {"homingFOV", VWFOFS(fHomingFOV), + VF_FLOAT}, // missile will lose lock on if DotProduct of missile direction and direction to target ever drops below this (-1 to 1, -1 = never lose target, + // 0 = lose if ship gets behind missile, 1 = pretty much will lose it's target right away) + {"lockOnTime", VWFOFS(iLockOnTime), VF_INT}, // 0 = no lock time needed, else # of ms needed to lock on + {"damage", VWFOFS(iDamage), VF_INT}, // damage done when traceline or projectile directly hits target + {"splashDamage", VWFOFS(iSplashDamage), VF_INT}, // damage done to ents in splashRadius of end of traceline or projectile origin on impact + {"splashRadius", VWFOFS(fSplashRadius), VF_FLOAT}, // radius that ent must be in to take splashDamage (linear fall-off) + {"ammoPerShot", VWFOFS(iAmmoPerShot), VF_INT}, // how much "ammo" each shot takes + {"health", VWFOFS(iHealth), VF_INT}, // if non-zero, projectile can be shot, takes this much damage before being destroyed + {"width", VWFOFS(fWidth), VF_FLOAT}, // width of traceline or bounding box of projecile (non-rotating!) + {"height", VWFOFS(fHeight), VF_FLOAT}, // height of traceline or bounding box of projecile (non-rotating!) + {"lifetime", VWFOFS(iLifeTime), VF_INT}, // removes itself after this amount of time + {"explodeOnExpire", VWFOFS(bExplodeOnExpire), VF_BOOL}, // when iLifeTime is up, explodes rather than simply removing itself }; -static const size_t numVehWeaponFields = ARRAY_LEN( vehWeaponFields ); +static const size_t numVehWeaponFields = ARRAY_LEN(vehWeaponFields); -int vfieldcmp( const void *a, const void *b ) -{ - return Q_stricmp( (const char *)a, ((vehField_t*)b)->name ); -} +int vfieldcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((vehField_t *)b)->name); } -static qboolean BG_ParseVehWeaponParm( vehWeaponInfo_t *vehWeapon, const char *parmName, char *pValue ) -{ +static qboolean BG_ParseVehWeaponParm(vehWeaponInfo_t *vehWeapon, const char *parmName, char *pValue) { vehField_t *vehWeaponField; - vec3_t vec; - byte *b = (byte *)vehWeapon; - int _iFieldsRead = 0; + vec3_t vec; + byte *b = (byte *)vehWeapon; + int _iFieldsRead = 0; vehicleType_t vehType; - char value[1024]; + char value[1024]; - Q_strncpyz( value, pValue, sizeof(value) ); + Q_strncpyz(value, pValue, sizeof(value)); // Loop through possible parameters - vehWeaponField = (vehField_t *)Q_LinearSearch( parmName, vehWeaponFields, numVehWeaponFields, sizeof( vehWeaponFields[0] ), vfieldcmp ); + vehWeaponField = (vehField_t *)Q_LinearSearch(parmName, vehWeaponFields, numVehWeaponFields, sizeof(vehWeaponFields[0]), vfieldcmp); - if ( !vehWeaponField ) + if (!vehWeaponField) return qfalse; // found it - switch( vehWeaponField->type ) - { + switch (vehWeaponField->type) { case VF_INT: - *(int *)(b+vehWeaponField->ofs) = atoi(value); + *(int *)(b + vehWeaponField->ofs) = atoi(value); break; case VF_FLOAT: - *(float *)(b+vehWeaponField->ofs) = atof(value); + *(float *)(b + vehWeaponField->ofs) = atof(value); break; - case VF_STRING: // string on disk, pointer in memory - if (!*(char **)(b+vehWeaponField->ofs)) - { //just use 1024 bytes in case we want to write over the string - *(char **)(b+vehWeaponField->ofs) = (char *)BG_Alloc(1024);//(char *)BG_Alloc(strlen(value)); - strcpy(*(char **)(b+vehWeaponField->ofs), value); + case VF_STRING: // string on disk, pointer in memory + if (!*(char **)(b + vehWeaponField->ofs)) { // just use 1024 bytes in case we want to write over the string + *(char **)(b + vehWeaponField->ofs) = (char *)BG_Alloc(1024); //(char *)BG_Alloc(strlen(value)); + strcpy(*(char **)(b + vehWeaponField->ofs), value); } break; case VF_VECTOR: - _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - //assert(_iFieldsRead==3 ); - if (_iFieldsRead!=3) - { - Com_Printf (S_COLOR_YELLOW"BG_ParseVehWeaponParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); - VectorClear( vec ); + _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + // assert(_iFieldsRead==3 ); + if (_iFieldsRead != 3) { + Com_Printf(S_COLOR_YELLOW "BG_ParseVehWeaponParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + VectorClear(vec); } - ((float *)(b+vehWeaponField->ofs))[0] = vec[0]; - ((float *)(b+vehWeaponField->ofs))[1] = vec[1]; - ((float *)(b+vehWeaponField->ofs))[2] = vec[2]; + ((float *)(b + vehWeaponField->ofs))[0] = vec[0]; + ((float *)(b + vehWeaponField->ofs))[1] = vec[1]; + ((float *)(b + vehWeaponField->ofs))[2] = vec[2]; break; case VF_BOOL: - *(qboolean *)(b+vehWeaponField->ofs) = (qboolean)(atof(value)!=0); + *(qboolean *)(b + vehWeaponField->ofs) = (qboolean)(atof(value) != 0); break; case VF_VEHTYPE: - vehType = (vehicleType_t)GetIDForString( VehicleTable, value ); - *(vehicleType_t *)(b+vehWeaponField->ofs) = vehType; - break; - case VF_ANIM: - { - int anim = GetIDForString( animTable, value ); - *(int *)(b+vehWeaponField->ofs) = anim; - } + vehType = (vehicleType_t)GetIDForString(VehicleTable, value); + *(vehicleType_t *)(b + vehWeaponField->ofs) = vehType; break; - case VF_WEAPON: // take string, resolve into index into VehWeaponParms + case VF_ANIM: { + int anim = GetIDForString(animTable, value); + *(int *)(b + vehWeaponField->ofs) = anim; + } break; + case VF_WEAPON: // take string, resolve into index into VehWeaponParms //*(int *)(b+vehWeaponField->ofs) = VEH_VehWeaponIndexForName( value ); break; - case VF_MODEL:// take the string, get the G_ModelIndex + case VF_MODEL: // take the string, get the G_ModelIndex #ifdef _GAME - *(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_ModelIndex(value); #else - *(int *)(b+vehWeaponField->ofs) = trap->R_RegisterModel( value ); + *(int *)(b + vehWeaponField->ofs) = trap->R_RegisterModel(value); #endif break; - case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex + case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex #ifdef _GAME - *(int *)(b+vehWeaponField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_ModelIndex(value); #else - *(int *)(b+vehWeaponField->ofs) = trap->R_RegisterModel( value ); + *(int *)(b + vehWeaponField->ofs) = trap->R_RegisterModel(value); #endif break; - case VF_EFFECT: // take the string, get the G_EffectIndex + case VF_EFFECT: // take the string, get the G_EffectIndex #ifdef _GAME - //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); #elif _CGAME - *(int *)(b+vehWeaponField->ofs) = trap->FX_RegisterEffect( value ); + *(int *)(b + vehWeaponField->ofs) = trap->FX_RegisterEffect(value); #endif break; - case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the index + case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the index #ifdef _GAME - //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_EffectIndex( value ); #elif _CGAME - *(int *)(b+vehWeaponField->ofs) = trap->FX_RegisterEffect( value ); + *(int *)(b + vehWeaponField->ofs) = trap->FX_RegisterEffect(value); #endif break; - case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader + case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader #ifdef UI_BUILD - *(int *)(b+vehWeaponField->ofs) = trap->R_RegisterShaderNoMip( value ); + *(int *)(b + vehWeaponField->ofs) = trap->R_RegisterShaderNoMip(value); #elif CGAME - *(int *)(b+vehWeaponField->ofs) = trap->R_RegisterShader( value ); + *(int *)(b + vehWeaponField->ofs) = trap->R_RegisterShader(value); #endif break; - case VF_SHADER_NOMIP:// (cgame only) take the string, call trap_R_RegisterShaderNoMip + case VF_SHADER_NOMIP: // (cgame only) take the string, call trap_R_RegisterShaderNoMip #if defined(_CGAME) || defined(UI_BUILD) - *(int *)(b+vehWeaponField->ofs) = trap->R_RegisterShaderNoMip( value ); + *(int *)(b + vehWeaponField->ofs) = trap->R_RegisterShaderNoMip(value); #endif break; - case VF_SOUND: // take the string, get the G_SoundIndex + case VF_SOUND: // take the string, get the G_SoundIndex #ifdef _GAME - *(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehWeaponField->ofs) = G_SoundIndex(value); #else - *(int *)(b+vehWeaponField->ofs) = trap->S_RegisterSound( value ); + *(int *)(b + vehWeaponField->ofs) = trap->S_RegisterSound(value); #endif break; - case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the index + case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the index #ifdef _GAME - //*(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); + //*(int *)(b+vehWeaponField->ofs) = G_SoundIndex( value ); #else - *(int *)(b+vehWeaponField->ofs) = trap->S_RegisterSound( value ); + *(int *)(b + vehWeaponField->ofs) = trap->S_RegisterSound(value); #endif break; default: - //Unknown type? + // Unknown type? return qfalse; } return qtrue; } -int VEH_LoadVehWeapon( const char *vehWeaponName ) -{//load up specified vehWeapon and save in array: g_vehWeaponInfo - const char *token; - char parmName[128];//we'll assume that no parm name is longer than 128 - char *value; - const char *p; - vehWeaponInfo_t *vehWeapon = NULL; +int VEH_LoadVehWeapon(const char *vehWeaponName) { // load up specified vehWeapon and save in array: g_vehWeaponInfo + const char *token; + char parmName[128]; // we'll assume that no parm name is longer than 128 + char *value; + const char *p; + vehWeaponInfo_t *vehWeapon = NULL; - //BG_VehWeaponSetDefaults( &g_vehWeaponInfo[0] );//set the first vehicle to default data + // BG_VehWeaponSetDefaults( &g_vehWeaponInfo[0] );//set the first vehicle to default data - //try to parse data out + // try to parse data out p = VehWeaponParms; COM_BeginParseSession("vehWeapons"); vehWeapon = &g_vehWeaponInfo[numVehicleWeapons]; // look for the right vehicle weapon - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { return qfalse; } - if ( !Q_stricmp( token, vehWeaponName ) ) - { + if (!Q_stricmp(token, vehWeaponName)) { break; } - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } - if ( !p ) - { + if (!p) { return qfalse; } - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//barf + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // barf return VEH_WEAPON_NONE; } - if ( Q_stricmp( token, "{" ) != 0 ) - { + if (Q_stricmp(token, "{") != 0) { return VEH_WEAPON_NONE; } // parse the vehWeapon info block - while ( 1 ) - { - SkipRestOfLine( &p ); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing Vehicle Weapon '%s'\n", vehWeaponName ); + while (1) { + SkipRestOfLine(&p); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing Vehicle Weapon '%s'\n", vehWeaponName); return VEH_WEAPON_NONE; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - Q_strncpyz( parmName, token, sizeof(parmName) ); - value = COM_ParseExt( &p, qtrue ); - if ( !value || !value[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Vehicle Weapon token '%s' has no value!\n", parmName ); - } - else - { - if ( !BG_ParseVehWeaponParm( vehWeapon, parmName, value ) ) - { - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle Weapon key/value pair '%s','%s'!\n", parmName, value ); + Q_strncpyz(parmName, token, sizeof(parmName)); + value = COM_ParseExt(&p, qtrue); + if (!value || !value[0]) { + Com_Printf(S_COLOR_RED "ERROR: Vehicle Weapon token '%s' has no value!\n", parmName); + } else { + if (!BG_ParseVehWeaponParm(vehWeapon, parmName, value)) { + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle Weapon key/value pair '%s','%s'!\n", parmName, value); } } } - if ( vehWeapon->fHoming ) - {//all lock-on weapons use these 2 sounds + if (vehWeapon->fHoming) { // all lock-on weapons use these 2 sounds #ifdef _GAME - //Hmm, no need fo have server register this, is there? - //G_SoundIndex( "sound/weapons/torpedo/tick.wav" ); - //G_SoundIndex( "sound/weapons/torpedo/lock.wav" ); + // Hmm, no need fo have server register this, is there? + // G_SoundIndex( "sound/weapons/torpedo/tick.wav" ); + // G_SoundIndex( "sound/weapons/torpedo/lock.wav" ); #else - trap->S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" ); - trap->S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" ); - trap->S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" ); - trap->S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" ); - trap->S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" ); + trap->S_RegisterSound("sound/vehicles/weapons/common/tick.wav"); + trap->S_RegisterSound("sound/vehicles/weapons/common/lock.wav"); + trap->S_RegisterSound("sound/vehicles/common/lockalarm1.wav"); + trap->S_RegisterSound("sound/vehicles/common/lockalarm2.wav"); + trap->S_RegisterSound("sound/vehicles/common/lockalarm3.wav"); #endif } return (numVehicleWeapons++); } -int VEH_VehWeaponIndexForName( const char *vehWeaponName ) -{ +int VEH_VehWeaponIndexForName(const char *vehWeaponName) { int vw; - if ( !vehWeaponName || !vehWeaponName[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Trying to read Vehicle Weapon with no name!\n" ); + if (!vehWeaponName || !vehWeaponName[0]) { + Com_Printf(S_COLOR_RED "ERROR: Trying to read Vehicle Weapon with no name!\n"); return VEH_WEAPON_NONE; } - for ( vw = VEH_WEAPON_BASE; vw < numVehicleWeapons; vw++ ) - { - if ( g_vehWeaponInfo[vw].name - && Q_stricmp( g_vehWeaponInfo[vw].name, vehWeaponName ) == 0 ) - {//already loaded this one + for (vw = VEH_WEAPON_BASE; vw < numVehicleWeapons; vw++) { + if (g_vehWeaponInfo[vw].name && Q_stricmp(g_vehWeaponInfo[vw].name, vehWeaponName) == 0) { // already loaded this one return vw; } } - //haven't loaded it yet - if ( vw >= MAX_VEH_WEAPONS ) - {//no more room! - Com_Printf( S_COLOR_RED"ERROR: Too many Vehicle Weapons (max 16), aborting load on %s!\n", vehWeaponName ); + // haven't loaded it yet + if (vw >= MAX_VEH_WEAPONS) { // no more room! + Com_Printf(S_COLOR_RED "ERROR: Too many Vehicle Weapons (max 16), aborting load on %s!\n", vehWeaponName); return VEH_WEAPON_NONE; } - //we have room for another one, load it up and return the index - //HMM... should we not even load the .vwp file until we want to? - vw = VEH_LoadVehWeapon( vehWeaponName ); - if ( vw == VEH_WEAPON_NONE ) - { - Com_Printf( S_COLOR_RED"ERROR: Could not find Vehicle Weapon %s!\n", vehWeaponName ); + // we have room for another one, load it up and return the index + // HMM... should we not even load the .vwp file until we want to? + vw = VEH_LoadVehWeapon(vehWeaponName); + if (vw == VEH_WEAPON_NONE) { + Com_Printf(S_COLOR_RED "ERROR: Could not find Vehicle Weapon %s!\n", vehWeaponName); } return vw; } -vehField_t vehicleFields[] = -{ - {"name", VFOFS(name), VF_STRING}, //unique name of the vehicle - - //general data - {"type", VFOFS(type), VF_VEHTYPE}, //what kind of vehicle - {"numHands", VFOFS(numHands), VF_INT}, //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, //How far you can look up and down off the forward of the vehicle - {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, //How far you can look left and right off the forward of the vehicle - {"length", VFOFS(length), VF_FLOAT}, //how long it is - used for body length traces when turning/moving? - {"width", VFOFS(width), VF_FLOAT}, //how wide it is - used for body length traces when turning/moving? - {"height", VFOFS(height), VF_FLOAT}, //how tall it is - used for body length traces when turning/moving? - {"centerOfGravity", VFOFS(centerOfGravity), VF_VECTOR},//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - {"speedMax", VFOFS(speedMax), VF_FLOAT}, //top speed - {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, //turbo speed - {"speedMin", VFOFS(speedMin), VF_FLOAT}, //if < 0, can go in reverse - {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, //what speed it drifts to when no accel/decel input is given - {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, //if speedIdle > 0, how quickly it goes up to that speed - {"acceleration", VFOFS(acceleration), VF_FLOAT}, //when pressing on accelerator - {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, //when giving no input, how quickly it drops to speedIdle - {"throttleSticks", VFOFS(throttleSticks), VF_BOOL},//if true, speed stays at whatever you accel/decel to, unless you turbo or brake - {"strafePerc", VFOFS(strafePerc), VF_FLOAT}, //multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, //how quickly it pitches and rolls (not under player control) - {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, //how far it can roll forward or backward - {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, //how far it can roll to either side - {"braking", VFOFS(braking), VF_FLOAT}, //when pressing on decelerator - {"mouseYaw", VFOFS(mouseYaw), VF_FLOAT}, // The mouse yaw override. - {"mousePitch", VFOFS(mousePitch), VF_FLOAT}, // The mouse yaw override. - {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, //how quickly you can turn - {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL},//whether or not you can turn when not moving - {"traction", VFOFS(traction), VF_FLOAT}, //how much your command input affects velocity - {"friction", VFOFS(friction), VF_FLOAT}, //how much velocity is cut on its own - {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, //the max slope that it can go up with control - {"speedDependantTurning", VFOFS(speedDependantTurning), VF_BOOL},//vehicle turns faster the faster it's going - - //durability stats - {"mass", VFOFS(mass), VF_INT}, //for momentum and impact force (player mass is 10) - {"armor", VFOFS(armor), VF_INT}, //total points of damage it can take - {"shields", VFOFS(shields), VF_INT}, //energy shield damage points - {"shieldRechargeMS", VFOFS(shieldRechargeMS), VF_INT},//energy shield milliseconds per point recharged - {"toughness", VFOFS(toughness), VF_FLOAT}, //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT},//when armor drops to or below this point, start malfunctioning +vehField_t vehicleFields[] = { + {"name", VFOFS(name), VF_STRING}, // unique name of the vehicle + + // general data + {"type", VFOFS(type), VF_VEHTYPE}, // what kind of vehicle + {"numHands", VFOFS(numHands), VF_INT}, // if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + {"lookPitch", VFOFS(lookPitch), VF_FLOAT}, // How far you can look up and down off the forward of the vehicle + {"lookYaw", VFOFS(lookYaw), VF_FLOAT}, // How far you can look left and right off the forward of the vehicle + {"length", VFOFS(length), VF_FLOAT}, // how long it is - used for body length traces when turning/moving? + {"width", VFOFS(width), VF_FLOAT}, // how wide it is - used for body length traces when turning/moving? + {"height", VFOFS(height), VF_FLOAT}, // how tall it is - used for body length traces when turning/moving? + {"centerOfGravity", VFOFS(centerOfGravity), + VF_VECTOR}, // offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) + + // speed stats + {"speedMax", VFOFS(speedMax), VF_FLOAT}, // top speed + {"turboSpeed", VFOFS(turboSpeed), VF_FLOAT}, // turbo speed + {"speedMin", VFOFS(speedMin), VF_FLOAT}, // if < 0, can go in reverse + {"speedIdle", VFOFS(speedIdle), VF_FLOAT}, // what speed it drifts to when no accel/decel input is given + {"accelIdle", VFOFS(accelIdle), VF_FLOAT}, // if speedIdle > 0, how quickly it goes up to that speed + {"acceleration", VFOFS(acceleration), VF_FLOAT}, // when pressing on accelerator + {"decelIdle", VFOFS(decelIdle), VF_FLOAT}, // when giving no input, how quickly it drops to speedIdle + {"throttleSticks", VFOFS(throttleSticks), VF_BOOL}, // if true, speed stays at whatever you accel/decel to, unless you turbo or brake + {"strafePerc", VFOFS(strafePerc), + VF_FLOAT}, // multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing + + // handling stats + {"bankingSpeed", VFOFS(bankingSpeed), VF_FLOAT}, // how quickly it pitches and rolls (not under player control) + {"pitchLimit", VFOFS(pitchLimit), VF_FLOAT}, // how far it can roll forward or backward + {"rollLimit", VFOFS(rollLimit), VF_FLOAT}, // how far it can roll to either side + {"braking", VFOFS(braking), VF_FLOAT}, // when pressing on decelerator + {"mouseYaw", VFOFS(mouseYaw), VF_FLOAT}, // The mouse yaw override. + {"mousePitch", VFOFS(mousePitch), VF_FLOAT}, // The mouse yaw override. + {"turningSpeed", VFOFS(turningSpeed), VF_FLOAT}, // how quickly you can turn + {"turnWhenStopped", VFOFS(turnWhenStopped), VF_BOOL}, // whether or not you can turn when not moving + {"traction", VFOFS(traction), VF_FLOAT}, // how much your command input affects velocity + {"friction", VFOFS(friction), VF_FLOAT}, // how much velocity is cut on its own + {"maxSlope", VFOFS(maxSlope), VF_FLOAT}, // the max slope that it can go up with control + {"speedDependantTurning", VFOFS(speedDependantTurning), VF_BOOL}, // vehicle turns faster the faster it's going + + // durability stats + {"mass", VFOFS(mass), VF_INT}, // for momentum and impact force (player mass is 10) + {"armor", VFOFS(armor), VF_INT}, // total points of damage it can take + {"shields", VFOFS(shields), VF_INT}, // energy shield damage points + {"shieldRechargeMS", VFOFS(shieldRechargeMS), VF_INT}, // energy shield milliseconds per point recharged + {"toughness", VFOFS(toughness), + VF_FLOAT}, // modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction + {"malfunctionArmorLevel", VFOFS(malfunctionArmorLevel), VF_INT}, // when armor drops to or below this point, start malfunctioning {"surfDestruction", VFOFS(surfDestruction), VF_INT}, - //visuals & sounds - {"model", VFOFS(model), VF_STRING}, //what model to use - if make it an NPC's primary model, don't need this? - {"skin", VFOFS(skin), VF_STRING}, //what skin to use - if make it an NPC's primary model, don't need this? - {"g2radius", VFOFS(g2radius), VF_INT}, //render radius (really diameter, but...) for the ghoul2 model - {"riderAnim", VFOFS(riderAnim), VF_ANIM}, //what animation the rider uses - {"droidNPC", VFOFS(droidNPC), VF_STRING}, //NPC to attach to *droidunit tag (if it exists in the model) - - {"radarIcon", VFOFS(radarIconHandle), VF_SHADER_NOMIP}, //what icon to show on radar in MP - {"dmgIndicFrame", VFOFS(dmgIndicFrameHandle), VF_SHADER_NOMIP}, //what image to use for the frame of the damage indicator - {"dmgIndicShield", VFOFS(dmgIndicShieldHandle), VF_SHADER_NOMIP},//what image to use for the shield of the damage indicator - {"dmgIndicBackground", VFOFS(dmgIndicBackgroundHandle), VF_SHADER_NOMIP},//what image to use for the background of the damage indicator - {"icon_front", VFOFS(iconFrontHandle), VF_SHADER_NOMIP}, //what image to use for the front of the ship on the damage indicator - {"icon_back", VFOFS(iconBackHandle), VF_SHADER_NOMIP}, //what image to use for the back of the ship on the damage indicator - {"icon_right", VFOFS(iconRightHandle), VF_SHADER_NOMIP}, //what image to use for the right of the ship on the damage indicator - {"icon_left", VFOFS(iconLeftHandle), VF_SHADER_NOMIP}, //what image to use for the left of the ship on the damage indicator - {"crosshairShader", VFOFS(crosshairShaderHandle), VF_SHADER_NOMIP}, //what image to use as the crosshair - {"shieldShader", VFOFS(shieldShaderHandle), VF_SHADER}, //What shader to use when drawing the shield shell - - //individual "area" health -rww + // visuals & sounds + {"model", VFOFS(model), VF_STRING}, // what model to use - if make it an NPC's primary model, don't need this? + {"skin", VFOFS(skin), VF_STRING}, // what skin to use - if make it an NPC's primary model, don't need this? + {"g2radius", VFOFS(g2radius), VF_INT}, // render radius (really diameter, but...) for the ghoul2 model + {"riderAnim", VFOFS(riderAnim), VF_ANIM}, // what animation the rider uses + {"droidNPC", VFOFS(droidNPC), VF_STRING}, // NPC to attach to *droidunit tag (if it exists in the model) + + {"radarIcon", VFOFS(radarIconHandle), VF_SHADER_NOMIP}, // what icon to show on radar in MP + {"dmgIndicFrame", VFOFS(dmgIndicFrameHandle), VF_SHADER_NOMIP}, // what image to use for the frame of the damage indicator + {"dmgIndicShield", VFOFS(dmgIndicShieldHandle), VF_SHADER_NOMIP}, // what image to use for the shield of the damage indicator + {"dmgIndicBackground", VFOFS(dmgIndicBackgroundHandle), VF_SHADER_NOMIP}, // what image to use for the background of the damage indicator + {"icon_front", VFOFS(iconFrontHandle), VF_SHADER_NOMIP}, // what image to use for the front of the ship on the damage indicator + {"icon_back", VFOFS(iconBackHandle), VF_SHADER_NOMIP}, // what image to use for the back of the ship on the damage indicator + {"icon_right", VFOFS(iconRightHandle), VF_SHADER_NOMIP}, // what image to use for the right of the ship on the damage indicator + {"icon_left", VFOFS(iconLeftHandle), VF_SHADER_NOMIP}, // what image to use for the left of the ship on the damage indicator + {"crosshairShader", VFOFS(crosshairShaderHandle), VF_SHADER_NOMIP}, // what image to use as the crosshair + {"shieldShader", VFOFS(shieldShaderHandle), VF_SHADER}, // What shader to use when drawing the shield shell + + // individual "area" health -rww {"health_front", VFOFS(health_front), VF_INT}, {"health_back", VFOFS(health_back), VF_INT}, {"health_right", VFOFS(health_right), VF_INT}, {"health_left", VFOFS(health_left), VF_INT}, - {"soundOn", VFOFS(soundOn), VF_SOUND},//sound to play when get on it - {"soundOff", VFOFS(soundOff), VF_SOUND},//sound to play when get off - {"soundLoop", VFOFS(soundLoop), VF_SOUND},//sound to loop while riding it - {"soundTakeOff", VFOFS(soundTakeOff), VF_SOUND},//sound to play when ship takes off - {"soundEngineStart",VFOFS(soundEngineStart),VF_SOUND_CLIENT},//sound to play when ship's thrusters first activate - {"soundSpin", VFOFS(soundSpin), VF_SOUND},//sound to loop while spiraling out of control - {"soundTurbo", VFOFS(soundTurbo), VF_SOUND},//sound to play when turbo/afterburner kicks in - {"soundHyper", VFOFS(soundHyper), VF_SOUND_CLIENT},//sound to play when hits hyperspace - {"soundLand", VFOFS(soundLand), VF_SOUND},//sound to play when ship lands - {"soundFlyBy", VFOFS(soundFlyBy), VF_SOUND_CLIENT},//sound to play when they buzz you - {"soundFlyBy2", VFOFS(soundFlyBy2), VF_SOUND_CLIENT},//alternate sound to play when they buzz you - {"soundShift1", VFOFS(soundShift1), VF_SOUND},//sound to play when changing speeds - {"soundShift2", VFOFS(soundShift2), VF_SOUND},//sound to play when changing speeds - {"soundShift3", VFOFS(soundShift3), VF_SOUND},//sound to play when changing speeds - {"soundShift4", VFOFS(soundShift4), VF_SOUND},//sound to play when changing speeds - - {"exhaustFX", VFOFS(iExhaustFX), VF_EFFECT_CLIENT}, //exhaust effect, played from "*exhaust" bolt(s) - {"turboFX", VFOFS(iTurboFX), VF_EFFECT_CLIENT}, //turbo exhaust effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode - {"turboStartFX", VFOFS(iTurboStartFX), VF_EFFECT}, //turbo start effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode - {"trailFX", VFOFS(iTrailFX), VF_EFFECT_CLIENT}, //trail effect, played from "*trail" bolt(s) - {"impactFX", VFOFS(iImpactFX), VF_EFFECT_CLIENT}, //impact effect, for when it bumps into something - {"explodeFX", VFOFS(iExplodeFX), VF_EFFECT}, //explosion effect, for when it blows up (should have the sound built into explosion effect) - {"wakeFX", VFOFS(iWakeFX), VF_EFFECT_CLIENT}, //effect it makes when going across water - {"dmgFX", VFOFS(iDmgFX), VF_EFFECT_CLIENT}, //effect to play on damage from a weapon or something - {"injureFX", VFOFS(iInjureFX), VF_EFFECT_CLIENT}, //effect to play on partially damaged ship surface - {"noseFX", VFOFS(iNoseFX), VF_EFFECT_CLIENT}, //effect for nose piece flying away when blown off - {"lwingFX", VFOFS(iLWingFX), VF_EFFECT_CLIENT}, //effect for left wing piece flying away when blown off - {"rwingFX", VFOFS(iRWingFX), VF_EFFECT_CLIENT}, //effect for right wing piece flying away when blown off + {"soundOn", VFOFS(soundOn), VF_SOUND}, // sound to play when get on it + {"soundOff", VFOFS(soundOff), VF_SOUND}, // sound to play when get off + {"soundLoop", VFOFS(soundLoop), VF_SOUND}, // sound to loop while riding it + {"soundTakeOff", VFOFS(soundTakeOff), VF_SOUND}, // sound to play when ship takes off + {"soundEngineStart", VFOFS(soundEngineStart), VF_SOUND_CLIENT}, // sound to play when ship's thrusters first activate + {"soundSpin", VFOFS(soundSpin), VF_SOUND}, // sound to loop while spiraling out of control + {"soundTurbo", VFOFS(soundTurbo), VF_SOUND}, // sound to play when turbo/afterburner kicks in + {"soundHyper", VFOFS(soundHyper), VF_SOUND_CLIENT}, // sound to play when hits hyperspace + {"soundLand", VFOFS(soundLand), VF_SOUND}, // sound to play when ship lands + {"soundFlyBy", VFOFS(soundFlyBy), VF_SOUND_CLIENT}, // sound to play when they buzz you + {"soundFlyBy2", VFOFS(soundFlyBy2), VF_SOUND_CLIENT}, // alternate sound to play when they buzz you + {"soundShift1", VFOFS(soundShift1), VF_SOUND}, // sound to play when changing speeds + {"soundShift2", VFOFS(soundShift2), VF_SOUND}, // sound to play when changing speeds + {"soundShift3", VFOFS(soundShift3), VF_SOUND}, // sound to play when changing speeds + {"soundShift4", VFOFS(soundShift4), VF_SOUND}, // sound to play when changing speeds + + {"exhaustFX", VFOFS(iExhaustFX), VF_EFFECT_CLIENT}, // exhaust effect, played from "*exhaust" bolt(s) + {"turboFX", VFOFS(iTurboFX), VF_EFFECT_CLIENT}, // turbo exhaust effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode + {"turboStartFX", VFOFS(iTurboStartFX), VF_EFFECT}, // turbo start effect, played from "*exhaust" bolt(s) when ship is in "turbo" mode + {"trailFX", VFOFS(iTrailFX), VF_EFFECT_CLIENT}, // trail effect, played from "*trail" bolt(s) + {"impactFX", VFOFS(iImpactFX), VF_EFFECT_CLIENT}, // impact effect, for when it bumps into something + {"explodeFX", VFOFS(iExplodeFX), VF_EFFECT}, // explosion effect, for when it blows up (should have the sound built into explosion effect) + {"wakeFX", VFOFS(iWakeFX), VF_EFFECT_CLIENT}, // effect it makes when going across water + {"dmgFX", VFOFS(iDmgFX), VF_EFFECT_CLIENT}, // effect to play on damage from a weapon or something + {"injureFX", VFOFS(iInjureFX), VF_EFFECT_CLIENT}, // effect to play on partially damaged ship surface + {"noseFX", VFOFS(iNoseFX), VF_EFFECT_CLIENT}, // effect for nose piece flying away when blown off + {"lwingFX", VFOFS(iLWingFX), VF_EFFECT_CLIENT}, // effect for left wing piece flying away when blown off + {"rwingFX", VFOFS(iRWingFX), VF_EFFECT_CLIENT}, // effect for right wing piece flying away when blown off // Weapon stuff: - {"weap1", VFOFS(weapon[0].ID), VF_WEAPON}, //weapon used when press fire - {"weap2", VFOFS(weapon[1].ID), VF_WEAPON},//weapon used when press alt-fire + {"weap1", VFOFS(weapon[0].ID), VF_WEAPON}, // weapon used when press fire + {"weap2", VFOFS(weapon[1].ID), VF_WEAPON}, // weapon used when press alt-fire // The delay between shots for this weapon. {"weap1Delay", VFOFS(weapon[0].delay), VF_INT}, {"weap2Delay", VFOFS(weapon[1].delay), VF_INT}, @@ -493,15 +464,15 @@ vehField_t vehicleFields[] = // Whether or not to auto-aim the projectiles at the thing under the crosshair when we fire {"weap1Aim", VFOFS(weapon[0].aimCorrect), VF_BOOL}, {"weap2Aim", VFOFS(weapon[1].aimCorrect), VF_BOOL}, - //maximum ammo + // maximum ammo {"weap1AmmoMax", VFOFS(weapon[0].ammoMax), VF_INT}, {"weap2AmmoMax", VFOFS(weapon[1].ammoMax), VF_INT}, - //ammo recharge rate - milliseconds per unit (minimum of 100, which is 10 ammo per second) + // ammo recharge rate - milliseconds per unit (minimum of 100, which is 10 ammo per second) {"weap1AmmoRechargeMS", VFOFS(weapon[0].ammoRechargeMS), VF_INT}, {"weap2AmmoRechargeMS", VFOFS(weapon[1].ammoRechargeMS), VF_INT}, - //sound to play when out of ammo (plays default "no ammo" sound if none specified) - {"weap1SoundNoAmmo", VFOFS(weapon[0].soundNoAmmo), VF_SOUND_CLIENT},//sound to play when try to fire weapon 1 with no ammo - {"weap2SoundNoAmmo", VFOFS(weapon[1].soundNoAmmo), VF_SOUND_CLIENT},//sound to play when try to fire weapon 2 with no ammo + // sound to play when out of ammo (plays default "no ammo" sound if none specified) + {"weap1SoundNoAmmo", VFOFS(weapon[0].soundNoAmmo), VF_SOUND_CLIENT}, // sound to play when try to fire weapon 1 with no ammo + {"weap2SoundNoAmmo", VFOFS(weapon[1].soundNoAmmo), VF_SOUND_CLIENT}, // sound to play when try to fire weapon 2 with no ammo // Which weapon a muzzle fires (has to match one of the weapons this vehicle has). {"weapMuzzle1", VFOFS(weapMuzzle[0]), VF_WEAPON}, @@ -518,38 +489,39 @@ vehField_t vehicleFields[] = // The max height before this ship (?) starts (auto)landing. {"landingHeight", VFOFS(landingHeight), VF_FLOAT}, - //other misc stats - {"gravity", VFOFS(gravity), VF_INT}, //normal is 800 - {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, //if 0, it's a ground vehicle - {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, //how hard it pushes off ground when less than hover height... causes "bounce", like shocks - {"waterProof", VFOFS(waterProof), VF_BOOL}, //can drive underwater if it has to - {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, //when in water, how high it floats (1 is neutral bouyancy) - {"fuelMax", VFOFS(fuelMax), VF_INT}, //how much fuel it can hold (capacity) - {"fuelRate", VFOFS(fuelRate), VF_INT}, //how quickly is uses up fuel - {"turboDuration", VFOFS(turboDuration), VF_INT}, //how long turbo lasts - {"turboRecharge", VFOFS(turboRecharge), VF_INT}, //how long turbo takes to recharge - {"visibility", VFOFS(visibility), VF_INT}, //for sight alerts - {"loudness", VFOFS(loudness), VF_INT}, //for sound alerts - {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT},//range of explosion - {"explosionDamage", VFOFS(explosionDamage), VF_INT},//damage of explosion - - //new stuff - {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). - {"hideRider", VFOFS(hideRider), VF_BOOL}, // rider (and passengers?) should not be drawn - {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL},//if rider is on vehicle when it dies, they should die - {"flammable", VFOFS(flammable), VF_BOOL}, //whether or not the vehicle should catch on fire before it explodes - {"explosionDelay", VFOFS(explosionDelay), VF_INT}, //how long the vehicle should be on fire/dying before it explodes - //camera stuff - {"cameraOverride", VFOFS(cameraOverride), VF_BOOL},//override the third person camera with the below values - normal is 0 (off) - {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, //how far back the camera should be - normal is 80 - {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT},//how high over the vehicle origin the camera should be - normal is 16 - {"cameraHorzOffset", VFOFS(cameraHorzOffset), VF_FLOAT},//how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT},//a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, //third person camera FOV, default is 80 - {"cameraAlpha", VFOFS(cameraAlpha), VF_FLOAT}, //fade out the vehicle to this alpha (0.1-1.0f) if it's in the way of the crosshair - {"cameraPitchDependantVertOffset", VFOFS(cameraPitchDependantVertOffset), VF_BOOL}, //use the hacky AT-ST pitch dependant vertical offset -//===TURRETS=========================================================================== - //Turret 1 + // other misc stats + {"gravity", VFOFS(gravity), VF_INT}, // normal is 800 + {"hoverHeight", VFOFS(hoverHeight), VF_FLOAT}, // if 0, it's a ground vehicle + {"hoverStrength", VFOFS(hoverStrength), VF_FLOAT}, // how hard it pushes off ground when less than hover height... causes "bounce", like shocks + {"waterProof", VFOFS(waterProof), VF_BOOL}, // can drive underwater if it has to + {"bouyancy", VFOFS(bouyancy), VF_FLOAT}, // when in water, how high it floats (1 is neutral bouyancy) + {"fuelMax", VFOFS(fuelMax), VF_INT}, // how much fuel it can hold (capacity) + {"fuelRate", VFOFS(fuelRate), VF_INT}, // how quickly is uses up fuel + {"turboDuration", VFOFS(turboDuration), VF_INT}, // how long turbo lasts + {"turboRecharge", VFOFS(turboRecharge), VF_INT}, // how long turbo takes to recharge + {"visibility", VFOFS(visibility), VF_INT}, // for sight alerts + {"loudness", VFOFS(loudness), VF_INT}, // for sound alerts + {"explosionRadius", VFOFS(explosionRadius), VF_FLOAT}, // range of explosion + {"explosionDamage", VFOFS(explosionDamage), VF_INT}, // damage of explosion + + // new stuff + {"maxPassengers", VFOFS(maxPassengers), VF_INT}, // The max number of passengers this vehicle may have (Default = 0). + {"hideRider", VFOFS(hideRider), VF_BOOL}, // rider (and passengers?) should not be drawn + {"killRiderOnDeath", VFOFS(killRiderOnDeath), VF_BOOL}, // if rider is on vehicle when it dies, they should die + {"flammable", VFOFS(flammable), VF_BOOL}, // whether or not the vehicle should catch on fire before it explodes + {"explosionDelay", VFOFS(explosionDelay), VF_INT}, // how long the vehicle should be on fire/dying before it explodes + // camera stuff + {"cameraOverride", VFOFS(cameraOverride), VF_BOOL}, // override the third person camera with the below values - normal is 0 (off) + {"cameraRange", VFOFS(cameraRange), VF_FLOAT}, // how far back the camera should be - normal is 80 + {"cameraVertOffset", VFOFS(cameraVertOffset), VF_FLOAT}, // how high over the vehicle origin the camera should be - normal is 16 + {"cameraHorzOffset", VFOFS(cameraHorzOffset), + VF_FLOAT}, // how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 + {"cameraPitchOffset", VFOFS(cameraPitchOffset), VF_FLOAT}, // a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 + {"cameraFOV", VFOFS(cameraFOV), VF_FLOAT}, // third person camera FOV, default is 80 + {"cameraAlpha", VFOFS(cameraAlpha), VF_FLOAT}, // fade out the vehicle to this alpha (0.1-1.0f) if it's in the way of the crosshair + {"cameraPitchDependantVertOffset", VFOFS(cameraPitchDependantVertOffset), VF_BOOL}, // use the hacky AT-ST pitch dependant vertical offset + //===TURRETS=========================================================================== + // Turret 1 {"turret1Weap", VFOFS(turret[0].iWeapon), VF_WEAPON}, {"turret1Delay", VFOFS(turret[0].iDelay), VF_INT}, {"turret1AmmoMax", VFOFS(turret[0].iAmmoMax), VF_INT}, @@ -558,20 +530,20 @@ vehField_t vehicleFields[] = {"turret1PitchBone", VFOFS(turret[0].pitchBone), VF_STRING}, {"turret1YawAxis", VFOFS(turret[0].yawAxis), VF_INT}, {"turret1PitchAxis", VFOFS(turret[0].pitchAxis), VF_INT}, - {"turret1ClampYawL", VFOFS(turret[0].yawClampLeft), VF_FLOAT}, //how far the turret is allowed to turn left - {"turret1ClampYawR", VFOFS(turret[0].yawClampRight), VF_FLOAT}, //how far the turret is allowed to turn right - {"turret1ClampPitchU", VFOFS(turret[0].pitchClampUp), VF_FLOAT}, //how far the turret is allowed to title up - {"turret1ClampPitchD", VFOFS(turret[0].pitchClampDown), VF_FLOAT}, //how far the turret is allowed to tilt down + {"turret1ClampYawL", VFOFS(turret[0].yawClampLeft), VF_FLOAT}, // how far the turret is allowed to turn left + {"turret1ClampYawR", VFOFS(turret[0].yawClampRight), VF_FLOAT}, // how far the turret is allowed to turn right + {"turret1ClampPitchU", VFOFS(turret[0].pitchClampUp), VF_FLOAT}, // how far the turret is allowed to title up + {"turret1ClampPitchD", VFOFS(turret[0].pitchClampDown), VF_FLOAT}, // how far the turret is allowed to tilt down {"turret1Muzzle1", VFOFS(turret[0].iMuzzle[0]), VF_INT}, {"turret1Muzzle2", VFOFS(turret[0].iMuzzle[1]), VF_INT}, {"turret1TurnSpeed", VFOFS(turret[0].fTurnSpeed), VF_FLOAT}, {"turret1AI", VFOFS(turret[0].bAI), VF_BOOL}, {"turret1AILead", VFOFS(turret[0].bAILead), VF_BOOL}, {"turret1AIRange", VFOFS(turret[0].fAIRange), VF_FLOAT}, - {"turret1PassengerNum", VFOFS(turret[0].passengerNum), VF_INT},//which number passenger can control this turret + {"turret1PassengerNum", VFOFS(turret[0].passengerNum), VF_INT}, // which number passenger can control this turret {"turret1GunnerViewTag", VFOFS(turret[0].gunnerViewTag), VF_STRING}, - //Turret 2 + // Turret 2 {"turret2Weap", VFOFS(turret[1].iWeapon), VF_WEAPON}, {"turret2Delay", VFOFS(turret[1].iDelay), VF_INT}, {"turret2AmmoMax", VFOFS(turret[1].iAmmoMax), VF_INT}, @@ -580,849 +552,748 @@ vehField_t vehicleFields[] = {"turret2PitchBone", VFOFS(turret[1].pitchBone), VF_STRING}, {"turret2YawAxis", VFOFS(turret[1].yawAxis), VF_INT}, {"turret2PitchAxis", VFOFS(turret[1].pitchAxis), VF_INT}, - {"turret2ClampYawL", VFOFS(turret[1].yawClampLeft), VF_FLOAT}, //how far the turret is allowed to turn left - {"turret2ClampYawR", VFOFS(turret[1].yawClampRight), VF_FLOAT}, //how far the turret is allowed to turn right - {"turret2ClampPitchU", VFOFS(turret[1].pitchClampUp), VF_FLOAT}, //how far the turret is allowed to title up - {"turret2ClampPitchD", VFOFS(turret[1].pitchClampDown), VF_FLOAT}, //how far the turret is allowed to tilt down + {"turret2ClampYawL", VFOFS(turret[1].yawClampLeft), VF_FLOAT}, // how far the turret is allowed to turn left + {"turret2ClampYawR", VFOFS(turret[1].yawClampRight), VF_FLOAT}, // how far the turret is allowed to turn right + {"turret2ClampPitchU", VFOFS(turret[1].pitchClampUp), VF_FLOAT}, // how far the turret is allowed to title up + {"turret2ClampPitchD", VFOFS(turret[1].pitchClampDown), VF_FLOAT}, // how far the turret is allowed to tilt down {"turret2Muzzle1", VFOFS(turret[1].iMuzzle[0]), VF_INT}, {"turret2Muzzle2", VFOFS(turret[1].iMuzzle[1]), VF_INT}, {"turret2TurnSpeed", VFOFS(turret[1].fTurnSpeed), VF_FLOAT}, {"turret2AI", VFOFS(turret[1].bAI), VF_BOOL}, {"turret2AILead", VFOFS(turret[1].bAILead), VF_BOOL}, {"turret2AIRange", VFOFS(turret[1].fAIRange), VF_FLOAT}, - {"turret2PassengerNum", VFOFS(turret[1].passengerNum), VF_INT},//which number passenger can control this turret + {"turret2PassengerNum", VFOFS(turret[1].passengerNum), VF_INT}, // which number passenger can control this turret {"turret2GunnerViewTag", VFOFS(turret[1].gunnerViewTag), VF_STRING}, -//===END TURRETS=========================================================================== + //===END TURRETS=========================================================================== }; -static const size_t numVehicleFields = ARRAY_LEN( vehicleFields ); - -stringID_table_t VehicleTable[VH_NUM_VEHICLES+1] = -{ - ENUM2STRING(VH_NONE), - ENUM2STRING(VH_WALKER), //something you ride inside of, it walks like you, like an AT-ST - ENUM2STRING(VH_FIGHTER), //something you fly inside of, like an X-Wing or TIE fighter - ENUM2STRING(VH_SPEEDER), //something you ride on that hovers, like a speeder or swoop - ENUM2STRING(VH_ANIMAL), //animal you ride on top of that walks, like a tauntaun - ENUM2STRING(VH_FLIER), //animal you ride on top of that flies, like a giant mynoc? - {0, -1} -}; +static const size_t numVehicleFields = ARRAY_LEN(vehicleFields); + +stringID_table_t VehicleTable[VH_NUM_VEHICLES + 1] = {ENUM2STRING(VH_NONE), + ENUM2STRING(VH_WALKER), // something you ride inside of, it walks like you, like an AT-ST + ENUM2STRING(VH_FIGHTER), // something you fly inside of, like an X-Wing or TIE fighter + ENUM2STRING(VH_SPEEDER), // something you ride on that hovers, like a speeder or swoop + ENUM2STRING(VH_ANIMAL), // animal you ride on top of that walks, like a tauntaun + ENUM2STRING(VH_FLIER), // animal you ride on top of that flies, like a giant mynoc? + {0, -1}}; // Setup the shared functions (one's that all vehicles would generally use). -extern void G_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ); -void BG_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ +extern void G_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo); +void BG_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo) { #ifdef _GAME - //only do the whole thing if we're on game + // only do the whole thing if we're on game G_SetSharedVehicleFunctions(pVehInfo); #endif #if defined(_GAME) || defined(_CGAME) - switch( pVehInfo->type ) - { - case VH_SPEEDER: - G_SetSpeederVehicleFunctions( pVehInfo ); - break; - case VH_ANIMAL: - G_SetAnimalVehicleFunctions( pVehInfo ); - break; - case VH_FIGHTER: - G_SetFighterVehicleFunctions( pVehInfo ); - break; - case VH_WALKER: - G_SetWalkerVehicleFunctions( pVehInfo ); - break; - default: - break; + switch (pVehInfo->type) { + case VH_SPEEDER: + G_SetSpeederVehicleFunctions(pVehInfo); + break; + case VH_ANIMAL: + G_SetAnimalVehicleFunctions(pVehInfo); + break; + case VH_FIGHTER: + G_SetFighterVehicleFunctions(pVehInfo); + break; + case VH_WALKER: + G_SetWalkerVehicleFunctions(pVehInfo); + break; + default: + break; } #endif } -void BG_VehicleSetDefaults( vehicleInfo_t *vehicle ) -{ +void BG_VehicleSetDefaults(vehicleInfo_t *vehicle) { memset(vehicle, 0, sizeof(vehicleInfo_t)); -/* - if (!vehicle->name) - { - vehicle->name = (char *)BG_Alloc(1024); - } - strcpy(vehicle->name, "default"); - - //general data - vehicle->type = VH_SPEEDER; //what kind of vehicle - //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player - vehicle->numHands = 0; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons - vehicle->lookPitch = 0; //How far you can look up and down off the forward of the vehicle - vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle - vehicle->length = 0; //how long it is - used for body length traces when turning/moving? - vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? - vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? - VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is all the way forward) - - //speed stats - note: these are DESIRED speed, not actual current speed/velocity - vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed - vehicle->turboSpeed = 0; //turboBoost - vehicle->speedMin = 0; //if < 0, can go in reverse - vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given - vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed - vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) - vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle - vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going forward, 0.5 is half, 0 is no strafing - - //handling stats - vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) - vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side - vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward - vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) - vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn - vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving - vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity - vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own - vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control - - //durability stats - vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) - vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take - vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher materials/construction - vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning - - //visuals & sounds - //vehicle->model = "models/map_objects/ships/swoop.md3"; //what model to use - if make it an NPC's primary model, don't need this? - if (!vehicle->model) - { - vehicle->model = (char *)BG_Alloc(1024); - } - strcpy(vehicle->model, "models/map_objects/ships/swoop.md3"); - - vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level - vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? - vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses - - vehicle->soundOn = NULL; //sound to play when get on it - vehicle->soundLoop = NULL; //sound to loop while riding it - vehicle->soundOff = NULL; //sound to play when get off - vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) - vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) - vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) - vehicle->wakeFX = NULL; //effect itmakes when going across water - - //other misc stats - vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 - vehicle->hoverHeight = 0;//VEH_DEFAULT_HOVER_HEIGHT; //if 0, it's a ground vehicle - vehicle->hoverStrength = 0;//VEH_DEFAULT_HOVER_STRENGTH;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks - vehicle->waterProof = qtrue; //can drive underwater if it has to - vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) - vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) - vehicle->fuelRate = 1; //how quickly is uses up fuel - vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts - vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts - vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; - vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; - vehicle->maxPassengers = 0; - - //new stuff - vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn - vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die - vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes - vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes - //camera stuff - vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values - vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 - vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 - vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal is 0 - vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 - vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80 - vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair -*/ + /* + if (!vehicle->name) + { + vehicle->name = (char *)BG_Alloc(1024); + } + strcpy(vehicle->name, "default"); + + //general data + vehicle->type = VH_SPEEDER; //what kind of vehicle + //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player + vehicle->numHands = 0; //if 2 hands, no weapons, if 1 hand, can use 1-handed weapons, if 0 hands, can use 2-handed weapons + vehicle->lookPitch = 0; //How far you can look up and down off the forward of the vehicle + vehicle->lookYaw = 5; //How far you can look left and right off the forward of the vehicle + vehicle->length = 0; //how long it is - used for body length traces when turning/moving? + vehicle->width = 0; //how wide it is - used for body length traces when turning/moving? + vehicle->height = 0; //how tall it is - used for body length traces when turning/moving? + VectorClear( vehicle->centerOfGravity );//offset from origin: {forward, right, up} as a modifier on that dimension (-1.0f is all the way back, 1.0f is + all the way forward) + + //speed stats - note: these are DESIRED speed, not actual current speed/velocity + vehicle->speedMax = VEH_DEFAULT_SPEED_MAX; //top speed + vehicle->turboSpeed = 0; //turboBoost + vehicle->speedMin = 0; //if < 0, can go in reverse + vehicle->speedIdle = 0; //what speed it drifts to when no accel/decel input is given + vehicle->accelIdle = 0; //if speedIdle > 0, how quickly it goes up to that speed + vehicle->acceleration = VEH_DEFAULT_ACCEL; //when pressing on accelerator (1/2 this when going in reverse) + vehicle->decelIdle = VEH_DEFAULT_DECEL; //when giving no input, how quickly it desired speed drops to speedIdle + vehicle->strafePerc = VEH_DEFAULT_STRAFE_PERC;//multiplier on current speed for strafing. If 1.0f, you can strafe at the same speed as you're going + forward, 0.5 is half, 0 is no strafing + + //handling stats + vehicle->bankingSpeed = VEH_DEFAULT_BANKING_SPEED; //how quickly it pitches and rolls (not under player control) + vehicle->rollLimit = VEH_DEFAULT_ROLL_LIMIT; //how far it can roll to either side + vehicle->pitchLimit = VEH_DEFAULT_PITCH_LIMIT; //how far it can pitch forward or backward + vehicle->braking = VEH_DEFAULT_BRAKING; //when pressing on decelerator (backwards) + vehicle->turningSpeed = VEH_DEFAULT_TURNING_SPEED; //how quickly you can turn + vehicle->turnWhenStopped = qfalse; //whether or not you can turn when not moving + vehicle->traction = VEH_DEFAULT_TRACTION; //how much your command input affects velocity + vehicle->friction = VEH_DEFAULT_FRICTION; //how much velocity is cut on its own + vehicle->maxSlope = VEH_DEFAULT_MAX_SLOPE; //the max slope that it can go up with control + + //durability stats + vehicle->mass = VEH_DEFAULT_MASS; //for momentum and impact force (player mass is 10) + vehicle->armor = VEH_DEFAULT_MAX_ARMOR; //total points of damage it can take + vehicle->toughness = VEH_DEFAULT_TOUGHNESS; //modifies incoming damage, 1.0 is normal, 0.5 is half, etc. Simulates being made of tougher + materials/construction vehicle->malfunctionArmorLevel = 0; //when armor drops to or below this point, start malfunctioning + + //visuals & sounds + //vehicle->model = "models/map_objects/ships/swoop.md3"; //what model to use - if make it an NPC's primary model, don't need this? + if (!vehicle->model) + { + vehicle->model = (char *)BG_Alloc(1024); + } + strcpy(vehicle->model, "models/map_objects/ships/swoop.md3"); + + vehicle->modelIndex = 0; //set internally, not until this vehicle is spawned into the level + vehicle->skin = NULL; //what skin to use - if make it an NPC's primary model, don't need this? + vehicle->riderAnim = BOTH_GUNSIT1; //what animation the rider uses + + vehicle->soundOn = NULL; //sound to play when get on it + vehicle->soundLoop = NULL; //sound to loop while riding it + vehicle->soundOff = NULL; //sound to play when get off + vehicle->exhaustFX = NULL; //exhaust effect, played from "*exhaust" bolt(s) + vehicle->trailFX = NULL; //trail effect, played from "*trail" bolt(s) + vehicle->impactFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->explodeFX = NULL; //explosion effect, for when it blows up (should have the sound built into explosion effect) + vehicle->wakeFX = NULL; //effect itmakes when going across water + + //other misc stats + vehicle->gravity = VEH_DEFAULT_GRAVITY; //normal is 800 + vehicle->hoverHeight = 0;//VEH_DEFAULT_HOVER_HEIGHT; //if 0, it's a ground vehicle + vehicle->hoverStrength = 0;//VEH_DEFAULT_HOVER_STRENGTH;//how hard it pushes off ground when less than hover height... causes "bounce", like shocks + vehicle->waterProof = qtrue; //can drive underwater if it has to + vehicle->bouyancy = 1.0f; //when in water, how high it floats (1 is neutral bouyancy) + vehicle->fuelMax = 1000; //how much fuel it can hold (capacity) + vehicle->fuelRate = 1; //how quickly is uses up fuel + vehicle->visibility = VEH_DEFAULT_VISIBILITY; //radius for sight alerts + vehicle->loudness = VEH_DEFAULT_LOUDNESS; //radius for sound alerts + vehicle->explosionRadius = VEH_DEFAULT_EXP_RAD; + vehicle->explosionDamage = VEH_DEFAULT_EXP_DMG; + vehicle->maxPassengers = 0; + + //new stuff + vehicle->hideRider = qfalse; // rider (and passengers?) should not be drawn + vehicle->killRiderOnDeath = qfalse; //if rider is on vehicle when it dies, they should die + vehicle->flammable = qfalse; //whether or not the vehicle should catch on fire before it explodes + vehicle->explosionDelay = 0; //how long the vehicle should be on fire/dying before it explodes + //camera stuff + vehicle->cameraOverride = qfalse; //whether or not to use all of the following 3rd person camera override values + vehicle->cameraRange = 0.0f; //how far back the camera should be - normal is 80 + vehicle->cameraVertOffset = 0.0f; //how high over the vehicle origin the camera should be - normal is 16 + vehicle->cameraHorzOffset = 0.0f; //how far to left/right (negative/positive) of of the vehicle origin the camera should be - normal + is 0 vehicle->cameraPitchOffset = 0.0f; //a modifier on the camera's pitch (up/down angle) to the vehicle - normal is 0 + vehicle->cameraFOV = 0.0f; //third person camera FOV, default is 80 + vehicle->cameraAlpha = qfalse; //fade out the vehicle if it's in the way of the crosshair + */ } -void BG_VehicleClampData( vehicleInfo_t *vehicle ) -{//sanity check and clamp the vehicle's data - int i; +void BG_VehicleClampData(vehicleInfo_t *vehicle) { // sanity check and clamp the vehicle's data + int i; - for ( i = 0; i < 3; i++ ) - { - if ( vehicle->centerOfGravity[i] > 1.0f ) - { + for (i = 0; i < 3; i++) { + if (vehicle->centerOfGravity[i] > 1.0f) { vehicle->centerOfGravity[i] = 1.0f; - } - else if ( vehicle->centerOfGravity[i] < -1.0f ) - { + } else if (vehicle->centerOfGravity[i] < -1.0f) { vehicle->centerOfGravity[i] = -1.0f; } } // Validate passenger max. - if ( vehicle->maxPassengers > VEH_MAX_PASSENGERS ) - { + if (vehicle->maxPassengers > VEH_MAX_PASSENGERS) { vehicle->maxPassengers = VEH_MAX_PASSENGERS; - } - else if ( vehicle->maxPassengers < 0 ) - { + } else if (vehicle->maxPassengers < 0) { vehicle->maxPassengers = 0; } } -static qboolean BG_ParseVehicleParm( vehicleInfo_t *vehicle, const char *parmName, char *pValue ) -{ +static qboolean BG_ParseVehicleParm(vehicleInfo_t *vehicle, const char *parmName, char *pValue) { vehField_t *vehField; - vec3_t vec; - byte *b = (byte *)vehicle; - int _iFieldsRead = 0; + vec3_t vec; + byte *b = (byte *)vehicle; + int _iFieldsRead = 0; vehicleType_t vehType; char value[1024]; - Q_strncpyz( value, pValue, sizeof(value) ); + Q_strncpyz(value, pValue, sizeof(value)); // Loop through possible parameters - vehField = (vehField_t *)Q_LinearSearch( parmName, vehicleFields, numVehicleFields, sizeof( vehicleFields[0] ), vfieldcmp ); + vehField = (vehField_t *)Q_LinearSearch(parmName, vehicleFields, numVehicleFields, sizeof(vehicleFields[0]), vfieldcmp); - if ( !vehField ) + if (!vehField) return qfalse; // found it - switch( vehField->type ) - { + switch (vehField->type) { case VF_IGNORE: break; case VF_INT: - *(int *)(b+vehField->ofs) = atoi(value); + *(int *)(b + vehField->ofs) = atoi(value); break; case VF_FLOAT: - *(float *)(b+vehField->ofs) = atof(value); + *(float *)(b + vehField->ofs) = atof(value); break; - case VF_STRING: // string on disk, pointer in memory - if (!*(char **)(b+vehField->ofs)) - { //just use 128 bytes in case we want to write over the string - *(char **)(b+vehField->ofs) = (char *)BG_Alloc(128);//(char *)BG_Alloc(strlen(value)); - strcpy(*(char **)(b+vehField->ofs), value); + case VF_STRING: // string on disk, pointer in memory + if (!*(char **)(b + vehField->ofs)) { // just use 128 bytes in case we want to write over the string + *(char **)(b + vehField->ofs) = (char *)BG_Alloc(128); //(char *)BG_Alloc(strlen(value)); + strcpy(*(char **)(b + vehField->ofs), value); } break; case VF_VECTOR: - _iFieldsRead = sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); - //assert(_iFieldsRead==3 ); - if (_iFieldsRead!=3) - { - Com_Printf (S_COLOR_YELLOW"BG_ParseVehicleParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); - VectorClear( vec ); + _iFieldsRead = sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]); + // assert(_iFieldsRead==3 ); + if (_iFieldsRead != 3) { + Com_Printf(S_COLOR_YELLOW "BG_ParseVehicleParm: VEC3 sscanf() failed to read 3 floats ('angle' key bug?)\n"); + VectorClear(vec); } - ((float *)(b+vehField->ofs))[0] = vec[0]; - ((float *)(b+vehField->ofs))[1] = vec[1]; - ((float *)(b+vehField->ofs))[2] = vec[2]; + ((float *)(b + vehField->ofs))[0] = vec[0]; + ((float *)(b + vehField->ofs))[1] = vec[1]; + ((float *)(b + vehField->ofs))[2] = vec[2]; break; case VF_BOOL: - *(qboolean *)(b+vehField->ofs) = (qboolean)(atof(value)!=0); + *(qboolean *)(b + vehField->ofs) = (qboolean)(atof(value) != 0); break; case VF_VEHTYPE: - vehType = (vehicleType_t)GetIDForString( VehicleTable, value ); - *(vehicleType_t *)(b+vehField->ofs) = vehType; - break; - case VF_ANIM: - { - int anim = GetIDForString( animTable, value ); - *(int *)(b+vehField->ofs) = anim; - } + vehType = (vehicleType_t)GetIDForString(VehicleTable, value); + *(vehicleType_t *)(b + vehField->ofs) = vehType; break; - case VF_WEAPON: // take string, resolve into index into VehWeaponParms - *(int *)(b+vehField->ofs) = VEH_VehWeaponIndexForName( value ); + case VF_ANIM: { + int anim = GetIDForString(animTable, value); + *(int *)(b + vehField->ofs) = anim; + } break; + case VF_WEAPON: // take string, resolve into index into VehWeaponParms + *(int *)(b + vehField->ofs) = VEH_VehWeaponIndexForName(value); break; - case VF_MODEL: // take the string, get the G_ModelIndex + case VF_MODEL: // take the string, get the G_ModelIndex #ifdef _GAME - *(int *)(b+vehField->ofs) = G_ModelIndex( value ); + *(int *)(b + vehField->ofs) = G_ModelIndex(value); #else - *(int *)(b+vehField->ofs) = trap->R_RegisterModel( value ); + *(int *)(b + vehField->ofs) = trap->R_RegisterModel(value); #endif break; - case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex + case VF_MODEL_CLIENT: // (MP cgame only) take the string, get the G_ModelIndex #ifdef _GAME - //*(int *)(b+vehField->ofs) = G_ModelIndex( value ); + //*(int *)(b+vehField->ofs) = G_ModelIndex( value ); #else - *(int *)(b+vehField->ofs) = trap->R_RegisterModel( value ); + *(int *)(b + vehField->ofs) = trap->R_RegisterModel(value); #endif break; - case VF_EFFECT: // take the string, get the G_EffectIndex + case VF_EFFECT: // take the string, get the G_EffectIndex #ifdef _GAME - *(int *)(b+vehField->ofs) = G_EffectIndex( value ); + *(int *)(b + vehField->ofs) = G_EffectIndex(value); #elif _CGAME - *(int *)(b+vehField->ofs) = trap->FX_RegisterEffect( value ); + *(int *)(b + vehField->ofs) = trap->FX_RegisterEffect(value); #endif break; - case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the G_EffectIndex + case VF_EFFECT_CLIENT: // (MP cgame only) take the string, get the G_EffectIndex #ifdef _GAME - //*(int *)(b+vehField->ofs) = G_EffectIndex( value ); + //*(int *)(b+vehField->ofs) = G_EffectIndex( value ); #elif _CGAME - *(int *)(b+vehField->ofs) = trap->FX_RegisterEffect( value ); + *(int *)(b + vehField->ofs) = trap->FX_RegisterEffect(value); #endif break; - case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader + case VF_SHADER: // (cgame only) take the string, call trap_R_RegisterShader #ifdef UI_BUILD - *(int *)(b+vehField->ofs) = trap->R_RegisterShaderNoMip( value ); + *(int *)(b + vehField->ofs) = trap->R_RegisterShaderNoMip(value); #elif _CGAME - *(int *)(b+vehField->ofs) = trap->R_RegisterShader( value ); + *(int *)(b + vehField->ofs) = trap->R_RegisterShader(value); #endif break; - case VF_SHADER_NOMIP:// (cgame only) take the string, call trap_R_RegisterShaderNoMip + case VF_SHADER_NOMIP: // (cgame only) take the string, call trap_R_RegisterShaderNoMip #if defined(_CGAME) || defined(UI_BUILD) - *(int *)(b+vehField->ofs) = trap->R_RegisterShaderNoMip( value ); + *(int *)(b + vehField->ofs) = trap->R_RegisterShaderNoMip(value); #endif break; - case VF_SOUND: // take the string, get the G_SoundIndex + case VF_SOUND: // take the string, get the G_SoundIndex #ifdef _GAME - *(int *)(b+vehField->ofs) = G_SoundIndex( value ); + *(int *)(b + vehField->ofs) = G_SoundIndex(value); #else - *(int *)(b+vehField->ofs) = trap->S_RegisterSound( value ); + *(int *)(b + vehField->ofs) = trap->S_RegisterSound(value); #endif break; - case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the G_SoundIndex + case VF_SOUND_CLIENT: // (MP cgame only) take the string, get the G_SoundIndex #ifdef _GAME - //*(int *)(b+vehField->ofs) = G_SoundIndex( value ); + //*(int *)(b+vehField->ofs) = G_SoundIndex( value ); #else - *(int *)(b+vehField->ofs) = trap->S_RegisterSound( value ); + *(int *)(b + vehField->ofs) = trap->S_RegisterSound(value); #endif break; default: - //Unknown type? + // Unknown type? return qfalse; } return qtrue; } -int VEH_LoadVehicle( const char *vehicleName ) -{//load up specified vehicle and save in array: g_vehicleInfo - const char *token; - //we'll assume that no parm name is longer than 128 - char parmName[128] = { 0 }; - char weap1[128] = { 0 }, weap2[128] = { 0 }; - char weapMuzzle1[128] = { 0 }; - char weapMuzzle2[128] = { 0 }; - char weapMuzzle3[128] = { 0 }; - char weapMuzzle4[128] = { 0 }; - char weapMuzzle5[128] = { 0 }; - char weapMuzzle6[128] = { 0 }; - char weapMuzzle7[128] = { 0 }; - char weapMuzzle8[128] = { 0 }; - char weapMuzzle9[128] = { 0 }; - char weapMuzzle10[128] = { 0 }; - char *value = NULL; - const char *p = NULL; - vehicleInfo_t *vehicle = NULL; +int VEH_LoadVehicle(const char *vehicleName) { // load up specified vehicle and save in array: g_vehicleInfo + const char *token; + // we'll assume that no parm name is longer than 128 + char parmName[128] = {0}; + char weap1[128] = {0}, weap2[128] = {0}; + char weapMuzzle1[128] = {0}; + char weapMuzzle2[128] = {0}; + char weapMuzzle3[128] = {0}; + char weapMuzzle4[128] = {0}; + char weapMuzzle5[128] = {0}; + char weapMuzzle6[128] = {0}; + char weapMuzzle7[128] = {0}; + char weapMuzzle8[128] = {0}; + char weapMuzzle9[128] = {0}; + char weapMuzzle10[128] = {0}; + char *value = NULL; + const char *p = NULL; + vehicleInfo_t *vehicle = NULL; // Load the vehicle parms if no vehicles have been loaded yet. - if ( numVehicles == 0 ) - { + if (numVehicles == 0) { BG_VehicleLoadParms(); } - //try to parse data out + // try to parse data out p = VehicleParms; COM_BeginParseSession("vehicles"); vehicle = &g_vehicleInfo[numVehicles]; // look for the right vehicle - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - { + while (p) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { return VEHICLE_NONE; } - if ( !Q_stricmp( token, vehicleName ) ) - { + if (!Q_stricmp(token, vehicleName)) { break; } - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } - if ( !p ) - { + if (!p) { return VEHICLE_NONE; } - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) - {//barf + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { // barf return VEHICLE_NONE; } - if ( Q_stricmp( token, "{" ) != 0 ) - { + if (Q_stricmp(token, "{") != 0) { return VEHICLE_NONE; } - BG_VehicleSetDefaults( vehicle ); + BG_VehicleSetDefaults(vehicle); // parse the vehicle info block - while ( 1 ) - { - SkipRestOfLine( &p ); - token = COM_ParseExt( &p, qtrue ); - if ( !token[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: unexpected EOF while parsing Vehicle '%s'\n", vehicleName ); + while (1) { + SkipRestOfLine(&p); + token = COM_ParseExt(&p, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_RED "ERROR: unexpected EOF while parsing Vehicle '%s'\n", vehicleName); return VEHICLE_NONE; } - if ( !Q_stricmp( token, "}" ) ) - { + if (!Q_stricmp(token, "}")) { break; } - Q_strncpyz( parmName, token, sizeof(parmName) ); - value = COM_ParseExt( &p, qtrue ); - if ( !value || !value[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Vehicle token '%s' has no value!\n", parmName ); - } - else if ( Q_stricmp( "weap1", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weap1, value, sizeof(weap1) ); - } - else if ( Q_stricmp( "weap2", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weap2, value, sizeof(weap2) ); - } - else if ( Q_stricmp( "weapMuzzle1", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle1, value, sizeof(weapMuzzle1) ); - } - else if ( Q_stricmp( "weapMuzzle2", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle2, value, sizeof(weapMuzzle2) ); - } - else if ( Q_stricmp( "weapMuzzle3", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle3, value, sizeof(weapMuzzle3) ); - } - else if ( Q_stricmp( "weapMuzzle4", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle4, value, sizeof(weapMuzzle4) ); - } - else if ( Q_stricmp( "weapMuzzle5", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle5, value, sizeof(weapMuzzle5) ); - } - else if ( Q_stricmp( "weapMuzzle6", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle6, value, sizeof(weapMuzzle6) ); - } - else if ( Q_stricmp( "weapMuzzle7", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle7, value, sizeof(weapMuzzle7) ); - } - else if ( Q_stricmp( "weapMuzzle8", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle8, value, sizeof(weapMuzzle8) ); - } - else if ( Q_stricmp( "weapMuzzle9", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle9, value, sizeof(weapMuzzle9) ); - } - else if ( Q_stricmp( "weapMuzzle10", parmName ) == 0 ) - {//hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... - Q_strncpyz( weapMuzzle10, value, sizeof(weapMuzzle10) ); - } - else - { - if ( !BG_ParseVehicleParm( vehicle, parmName, value ) ) - { + Q_strncpyz(parmName, token, sizeof(parmName)); + value = COM_ParseExt(&p, qtrue); + if (!value || !value[0]) { + Com_Printf(S_COLOR_RED "ERROR: Vehicle token '%s' has no value!\n", parmName); + } else if (Q_stricmp("weap1", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weap1, value, sizeof(weap1)); + } else if (Q_stricmp("weap2", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weap2, value, sizeof(weap2)); + } else if (Q_stricmp("weapMuzzle1", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle1, value, sizeof(weapMuzzle1)); + } else if (Q_stricmp("weapMuzzle2", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle2, value, sizeof(weapMuzzle2)); + } else if (Q_stricmp("weapMuzzle3", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle3, value, sizeof(weapMuzzle3)); + } else if (Q_stricmp("weapMuzzle4", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle4, value, sizeof(weapMuzzle4)); + } else if (Q_stricmp("weapMuzzle5", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle5, value, sizeof(weapMuzzle5)); + } else if (Q_stricmp("weapMuzzle6", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle6, value, sizeof(weapMuzzle6)); + } else if (Q_stricmp("weapMuzzle7", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle7, value, sizeof(weapMuzzle7)); + } else if (Q_stricmp("weapMuzzle8", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle8, value, sizeof(weapMuzzle8)); + } else if (Q_stricmp("weapMuzzle9", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle9, value, sizeof(weapMuzzle9)); + } else if (Q_stricmp("weapMuzzle10", parmName) == + 0) { // hmm, store this off because we don't want to call another one of these text parsing routines while we're in the middle of one... + Q_strncpyz(weapMuzzle10, value, sizeof(weapMuzzle10)); + } else { + if (!BG_ParseVehicleParm(vehicle, parmName, value)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair '%s', '%s'!\n", parmName, value ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair '%s', '%s'!\n", parmName, value); #endif } } } - //NOW: if we have any weapons, go ahead and load them - if ( weap1[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weap1", weap1 ) ) - { + // NOW: if we have any weapons, go ahead and load them + if (weap1[0]) { + if (!BG_ParseVehicleParm(vehicle, "weap1", weap1)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weap1', '%s'!\n", weap1 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weap1', '%s'!\n", weap1); #endif } } - if ( weap2[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weap2", weap2 ) ) - { + if (weap2[0]) { + if (!BG_ParseVehicleParm(vehicle, "weap2", weap2)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weap2', '%s'!\n", weap2 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weap2', '%s'!\n", weap2); #endif } } - if ( weapMuzzle1[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle1", weapMuzzle1 ) ) - { + if (weapMuzzle1[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle1", weapMuzzle1)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle1', '%s'!\n", weapMuzzle1 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle1', '%s'!\n", weapMuzzle1); #endif } } - if ( weapMuzzle2[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle2", weapMuzzle2 ) ) - { + if (weapMuzzle2[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle2", weapMuzzle2)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle2', '%s'!\n", weapMuzzle2 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle2', '%s'!\n", weapMuzzle2); #endif } } - if ( weapMuzzle3[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle3", weapMuzzle3 ) ) - { + if (weapMuzzle3[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle3", weapMuzzle3)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle3', '%s'!\n", weapMuzzle3 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle3', '%s'!\n", weapMuzzle3); #endif } } - if ( weapMuzzle4[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle4", weapMuzzle4 ) ) - { + if (weapMuzzle4[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle4", weapMuzzle4)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle4', '%s'!\n", weapMuzzle4 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle4', '%s'!\n", weapMuzzle4); #endif } } - if ( weapMuzzle5[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle5", weapMuzzle5 ) ) - { + if (weapMuzzle5[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle5", weapMuzzle5)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle5', '%s'!\n", weapMuzzle5 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle5', '%s'!\n", weapMuzzle5); #endif } } - if ( weapMuzzle6[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle6", weapMuzzle6 ) ) - { + if (weapMuzzle6[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle6", weapMuzzle6)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle6', '%s'!\n", weapMuzzle6 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle6', '%s'!\n", weapMuzzle6); #endif } } - if ( weapMuzzle7[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle7", weapMuzzle7 ) ) - { + if (weapMuzzle7[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle7", weapMuzzle7)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle7', '%s'!\n", weapMuzzle7 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle7', '%s'!\n", weapMuzzle7); #endif } } - if ( weapMuzzle8[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle8", weapMuzzle8 ) ) - { + if (weapMuzzle8[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle8", weapMuzzle8)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle8', '%s'!\n", weapMuzzle8 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle8', '%s'!\n", weapMuzzle8); #endif } } - if ( weapMuzzle9[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle9", weapMuzzle9 ) ) - { + if (weapMuzzle9[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle9", weapMuzzle9)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle9', '%s'!\n", weapMuzzle9 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle9', '%s'!\n", weapMuzzle9); #endif } } - if ( weapMuzzle10[0] ) - { - if ( !BG_ParseVehicleParm( vehicle, "weapMuzzle10", weapMuzzle10 ) ) - { + if (weapMuzzle10[0]) { + if (!BG_ParseVehicleParm(vehicle, "weapMuzzle10", weapMuzzle10)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"ERROR: Unknown Vehicle key/value pair 'weapMuzzle10', '%s'!\n", weapMuzzle10 ); + Com_Printf(S_COLOR_RED "ERROR: Unknown Vehicle key/value pair 'weapMuzzle10', '%s'!\n", weapMuzzle10); #endif } } - //let's give these guys some defaults - if (!vehicle->health_front) - { - vehicle->health_front = vehicle->armor/4; + // let's give these guys some defaults + if (!vehicle->health_front) { + vehicle->health_front = vehicle->armor / 4; } - if (!vehicle->health_back) - { - vehicle->health_back = vehicle->armor/4; + if (!vehicle->health_back) { + vehicle->health_back = vehicle->armor / 4; } - if (!vehicle->health_right) - { - vehicle->health_right = vehicle->armor/4; + if (!vehicle->health_right) { + vehicle->health_right = vehicle->armor / 4; } - if (!vehicle->health_left) - { - vehicle->health_left = vehicle->armor/4; + if (!vehicle->health_left) { + vehicle->health_left = vehicle->armor / 4; } - if ( vehicle->model ) - { - #ifdef _GAME - vehicle->modelIndex = G_ModelIndex( va( "models/players/%s/model.glm", vehicle->model ) ); - #else - vehicle->modelIndex = trap->R_RegisterModel( va( "models/players/%s/model.glm", vehicle->model ) ); - #endif + if (vehicle->model) { +#ifdef _GAME + vehicle->modelIndex = G_ModelIndex(va("models/players/%s/model.glm", vehicle->model)); +#else + vehicle->modelIndex = trap->R_RegisterModel(va("models/players/%s/model.glm", vehicle->model)); +#endif } - #if defined(_CGAME) || defined(UI_BUILD) - if ( VALIDSTRING( vehicle->skin ) ) - trap->R_RegisterSkin( va( "models/players/%s/model_%s.skin", vehicle->model, vehicle->skin) ); - #endif +#if defined(_CGAME) || defined(UI_BUILD) + if (VALIDSTRING(vehicle->skin)) + trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", vehicle->model, vehicle->skin)); +#endif - //sanity check and clamp the vehicle's data - BG_VehicleClampData( vehicle ); + // sanity check and clamp the vehicle's data + BG_VehicleClampData(vehicle); // Setup the shared function pointers. - BG_SetSharedVehicleFunctions( vehicle ); - //misc effects... FIXME: not even used in MP, are they? - if ( vehicle->explosionDamage ) - { - #ifdef _GAME - G_EffectIndex( "ships/ship_explosion_mark" ); - #elif defined(_CGAME) - trap->FX_RegisterEffect( "ships/ship_explosion_mark" ); - #endif + BG_SetSharedVehicleFunctions(vehicle); + // misc effects... FIXME: not even used in MP, are they? + if (vehicle->explosionDamage) { +#ifdef _GAME + G_EffectIndex("ships/ship_explosion_mark"); +#elif defined(_CGAME) + trap->FX_RegisterEffect("ships/ship_explosion_mark"); +#endif } - if ( vehicle->flammable ) - { - #ifdef _GAME - G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); - #else - trap->S_RegisterSound( "sound/vehicles/common/fire_lp.wav" ); - #endif + if (vehicle->flammable) { +#ifdef _GAME + G_SoundIndex("sound/vehicles/common/fire_lp.wav"); +#else + trap->S_RegisterSound("sound/vehicles/common/fire_lp.wav"); +#endif } - if ( vehicle->hoverHeight > 0 ) - { - #ifdef _GAME - G_EffectIndex( "ships/swoop_dust" ); - #elif defined(_CGAME) - trap->FX_RegisterEffect( "ships/swoop_dust" ); - #endif + if (vehicle->hoverHeight > 0) { +#ifdef _GAME + G_EffectIndex("ships/swoop_dust"); +#elif defined(_CGAME) + trap->FX_RegisterEffect("ships/swoop_dust"); +#endif } #ifdef _GAME - G_EffectIndex( "volumetric/black_smoke" ); - G_EffectIndex( "ships/fire" ); - G_SoundIndex( "sound/vehicles/common/release.wav" ); + G_EffectIndex("volumetric/black_smoke"); + G_EffectIndex("ships/fire"); + G_SoundIndex("sound/vehicles/common/release.wav"); #elif defined(_CGAME) - trap->R_RegisterShader( "gfx/menus/radar/bracket" ); - trap->R_RegisterShader( "gfx/menus/radar/lead" ); - trap->R_RegisterShaderNoMip( "gfx/menus/radar/asteroid" ); - trap->S_RegisterSound( "sound/vehicles/common/impactalarm.wav" ); - trap->S_RegisterSound( "sound/vehicles/common/linkweaps.wav" ); - trap->S_RegisterSound( "sound/vehicles/common/release.wav" ); + trap->R_RegisterShader("gfx/menus/radar/bracket"); + trap->R_RegisterShader("gfx/menus/radar/lead"); + trap->R_RegisterShaderNoMip("gfx/menus/radar/asteroid"); + trap->S_RegisterSound("sound/vehicles/common/impactalarm.wav"); + trap->S_RegisterSound("sound/vehicles/common/linkweaps.wav"); + trap->S_RegisterSound("sound/vehicles/common/release.wav"); trap->FX_RegisterEffect("effects/ships/dest_burning.efx"); trap->FX_RegisterEffect("effects/ships/dest_destroyed.efx"); - trap->FX_RegisterEffect( "volumetric/black_smoke" ); - trap->FX_RegisterEffect( "ships/fire" ); + trap->FX_RegisterEffect("volumetric/black_smoke"); + trap->FX_RegisterEffect("ships/fire"); trap->FX_RegisterEffect("ships/hyperspace_stars"); - if ( vehicle->hideRider ) - { - trap->R_RegisterShaderNoMip( "gfx/menus/radar/circle_base" ); - trap->R_RegisterShaderNoMip( "gfx/menus/radar/circle_base_frame" ); - trap->R_RegisterShaderNoMip( "gfx/menus/radar/circle_base_shield" ); + if (vehicle->hideRider) { + trap->R_RegisterShaderNoMip("gfx/menus/radar/circle_base"); + trap->R_RegisterShaderNoMip("gfx/menus/radar/circle_base_frame"); + trap->R_RegisterShaderNoMip("gfx/menus/radar/circle_base_shield"); } #endif return (numVehicles++); } -int VEH_VehicleIndexForName( const char *vehicleName ) -{ +int VEH_VehicleIndexForName(const char *vehicleName) { int v; - if ( !vehicleName || !vehicleName[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: Trying to read Vehicle with no name!\n" ); + if (!vehicleName || !vehicleName[0]) { + Com_Printf(S_COLOR_RED "ERROR: Trying to read Vehicle with no name!\n"); return VEHICLE_NONE; } - for ( v = VEHICLE_BASE; v < numVehicles; v++ ) - { - if ( g_vehicleInfo[v].name - && Q_stricmp( g_vehicleInfo[v].name, vehicleName ) == 0 ) - {//already loaded this one + for (v = VEHICLE_BASE; v < numVehicles; v++) { + if (g_vehicleInfo[v].name && Q_stricmp(g_vehicleInfo[v].name, vehicleName) == 0) { // already loaded this one return v; } } - //haven't loaded it yet - if ( v >= MAX_VEHICLES ) - {//no more room! - Com_Printf( S_COLOR_RED"ERROR: Too many Vehicles (max %d), aborting load on %s!\n", MAX_VEHICLES, vehicleName ); + // haven't loaded it yet + if (v >= MAX_VEHICLES) { // no more room! + Com_Printf(S_COLOR_RED "ERROR: Too many Vehicles (max %d), aborting load on %s!\n", MAX_VEHICLES, vehicleName); return VEHICLE_NONE; } - //we have room for another one, load it up and return the index - //HMM... should we not even load the .veh file until we want to? - v = VEH_LoadVehicle( vehicleName ); - if ( v == VEHICLE_NONE ) - { - Com_Printf( S_COLOR_RED"ERROR: Could not find Vehicle %s!\n", vehicleName ); + // we have room for another one, load it up and return the index + // HMM... should we not even load the .veh file until we want to? + v = VEH_LoadVehicle(vehicleName); + if (v == VEHICLE_NONE) { + Com_Printf(S_COLOR_RED "ERROR: Could not find Vehicle %s!\n", vehicleName); } return v; } -void BG_VehWeaponLoadParms( void ) -{ - int len, totallen, vehExtFNLen, fileCnt, i; - char *holdChar, *marker; - char vehWeaponExtensionListBuf[2048]; // The list of file names read in - fileHandle_t f; - char *tempReadBuffer; +void BG_VehWeaponLoadParms(void) { + int len, totallen, vehExtFNLen, fileCnt, i; + char *holdChar, *marker; + char vehWeaponExtensionListBuf[2048]; // The list of file names read in + fileHandle_t f; + char *tempReadBuffer; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = len; - marker = VehWeaponParms+totallen; + marker = VehWeaponParms + totallen; *marker = 0; - //now load in the extra .veh extensions - fileCnt = trap->FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf) ); + // now load in the extra .veh extensions + fileCnt = trap->FS_GetFileList("ext_data/vehicles/weapons", ".vwp", vehWeaponExtensionListBuf, sizeof(vehWeaponExtensionListBuf)); holdChar = vehWeaponExtensionListBuf; tempReadBuffer = (char *)BG_TempAlloc(MAX_VEH_WEAPON_DATA_SIZE); // NOTE: Not use TempAlloc anymore... - //Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before - //the subsequent BG_TempFree or the pool will be screwed. + // Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before + // the subsequent BG_TempFree or the pool will be screwed. - for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 ) - { - vehExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1) { + vehExtFNLen = strlen(holdChar); -// Com_Printf( "Parsing %s\n", holdChar ); + // Com_Printf( "Parsing %s\n", holdChar ); - len = trap->FS_Open(va( "ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); + len = trap->FS_Open(va("ext_data/vehicles/weapons/%s", holdChar), &f, FS_READ); - if ( len == -1 ) - { - Com_Printf( "error reading file\n" ); - } - else - { + if (len == -1) { + Com_Printf("error reading file\n"); + } else { trap->FS_Read(tempReadBuffer, len, f); tempReadBuffer[len] = 0; // Don't let it end on a } because that should be a stand-alone token. - if ( totallen && *(marker-1) == '}' ) - { - strcat( marker, " " ); + if (totallen && *(marker - 1) == '}') { + strcat(marker, " "); totallen++; marker++; } - if ( totallen + len >= MAX_VEH_WEAPON_DATA_SIZE ) { - trap->FS_Close( f ); - Com_Error(ERR_DROP, "Vehicle Weapon extensions (*.vwp) are too large" ); + if (totallen + len >= MAX_VEH_WEAPON_DATA_SIZE) { + trap->FS_Close(f); + Com_Error(ERR_DROP, "Vehicle Weapon extensions (*.vwp) are too large"); } - strcat( marker, tempReadBuffer ); - trap->FS_Close( f ); + strcat(marker, tempReadBuffer); + trap->FS_Close(f); totallen += len; - marker = VehWeaponParms+totallen; + marker = VehWeaponParms + totallen; } } BG_TempFree(MAX_VEH_WEAPON_DATA_SIZE); } -void BG_VehicleLoadParms( void ) -{//HMM... only do this if there's a vehicle on the level? - int len, totallen, vehExtFNLen, fileCnt, i; -// const char *filename = "ext_data/vehicles.dat"; - char *holdChar, *marker; - char vehExtensionListBuf[2048]; // The list of file names read in - fileHandle_t f; - char *tempReadBuffer; +void BG_VehicleLoadParms(void) { // HMM... only do this if there's a vehicle on the level? + int len, totallen, vehExtFNLen, fileCnt, i; + // const char *filename = "ext_data/vehicles.dat"; + char *holdChar, *marker; + char vehExtensionListBuf[2048]; // The list of file names read in + fileHandle_t f; + char *tempReadBuffer; len = 0; - //remember where to store the next one + // remember where to store the next one totallen = len; - marker = VehicleParms+totallen; + marker = VehicleParms + totallen; *marker = 0; - //now load in the extra .veh extensions - fileCnt = trap->FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf) ); + // now load in the extra .veh extensions + fileCnt = trap->FS_GetFileList("ext_data/vehicles", ".veh", vehExtensionListBuf, sizeof(vehExtensionListBuf)); holdChar = vehExtensionListBuf; tempReadBuffer = (char *)BG_TempAlloc(MAX_VEHICLE_DATA_SIZE); // NOTE: Not use TempAlloc anymore... - //Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before - //the subsequent BG_TempFree or the pool will be screwed. + // Make ABSOLUTELY CERTAIN that BG_Alloc/etc. is not used before + // the subsequent BG_TempFree or the pool will be screwed. - for ( i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1 ) - { - vehExtFNLen = strlen( holdChar ); + for (i = 0; i < fileCnt; i++, holdChar += vehExtFNLen + 1) { + vehExtFNLen = strlen(holdChar); -// Com_Printf( "Parsing %s\n", holdChar ); + // Com_Printf( "Parsing %s\n", holdChar ); - len = trap->FS_Open(va( "ext_data/vehicles/%s", holdChar), &f, FS_READ); + len = trap->FS_Open(va("ext_data/vehicles/%s", holdChar), &f, FS_READ); - if ( len == -1 ) - { - Com_Printf( "error reading file\n" ); - } - else - { + if (len == -1) { + Com_Printf("error reading file\n"); + } else { trap->FS_Read(tempReadBuffer, len, f); tempReadBuffer[len] = 0; // Don't let it end on a } because that should be a stand-alone token. - if ( totallen && *(marker-1) == '}' ) - { - strcat( marker, " " ); + if (totallen && *(marker - 1) == '}') { + strcat(marker, " "); totallen++; marker++; } - if ( totallen + len >= MAX_VEHICLE_DATA_SIZE ) { - trap->FS_Close( f ); - Com_Error(ERR_DROP, "Vehicle extensions (*.veh) are too large" ); + if (totallen + len >= MAX_VEHICLE_DATA_SIZE) { + trap->FS_Close(f); + Com_Error(ERR_DROP, "Vehicle extensions (*.veh) are too large"); } - strcat( marker, tempReadBuffer ); - trap->FS_Close( f ); + strcat(marker, tempReadBuffer); + trap->FS_Close(f); totallen += len; - marker = VehicleParms+totallen; + marker = VehicleParms + totallen; } } BG_TempFree(MAX_VEHICLE_DATA_SIZE); - numVehicles = 1;//first one is null/default - //set the first vehicle to default data - BG_VehicleSetDefaults( &g_vehicleInfo[VEHICLE_BASE] ); - //sanity check and clamp the vehicle's data - BG_VehicleClampData( &g_vehicleInfo[VEHICLE_BASE] ); + numVehicles = 1; // first one is null/default + // set the first vehicle to default data + BG_VehicleSetDefaults(&g_vehicleInfo[VEHICLE_BASE]); + // sanity check and clamp the vehicle's data + BG_VehicleClampData(&g_vehicleInfo[VEHICLE_BASE]); // Setup the shared function pointers. - BG_SetSharedVehicleFunctions( &g_vehicleInfo[VEHICLE_BASE] ); + BG_SetSharedVehicleFunctions(&g_vehicleInfo[VEHICLE_BASE]); - //Load the Vehicle Weapons data, too + // Load the Vehicle Weapons data, too BG_VehWeaponLoadParms(); } -int BG_VehicleGetIndex( const char *vehicleName ) -{ - return (VEH_VehicleIndexForName( vehicleName )); -} +int BG_VehicleGetIndex(const char *vehicleName) { return (VEH_VehicleIndexForName(vehicleName)); } -//We get the vehicle name passed in as modelname -//with a $ in front of it. -//we are expected to then get the model for the -//vehicle and stomp over modelname with it. -void BG_GetVehicleModelName(char *modelName, const char *vehicleName, size_t len) -{ +// We get the vehicle name passed in as modelname +// with a $ in front of it. +// we are expected to then get the model for the +// vehicle and stomp over modelname with it. +void BG_GetVehicleModelName(char *modelName, const char *vehicleName, size_t len) { const char *vehName = &vehicleName[1]; int vIndex = BG_VehicleGetIndex(vehName); assert(vehicleName[0] == '$'); @@ -1430,11 +1301,10 @@ void BG_GetVehicleModelName(char *modelName, const char *vehicleName, size_t len if (vIndex == VEHICLE_NONE) Com_Error(ERR_DROP, "BG_GetVehicleModelName: couldn't find vehicle %s", vehName); - Q_strncpyz( modelName, g_vehicleInfo[vIndex].model, len ); + Q_strncpyz(modelName, g_vehicleInfo[vIndex].model, len); } -void BG_GetVehicleSkinName(char *skinname, int len) -{ +void BG_GetVehicleSkinName(char *skinname, int len) { char *vehName = &skinname[1]; int vIndex = BG_VehicleGetIndex(vehName); assert(skinname[0] == '$'); @@ -1442,23 +1312,21 @@ void BG_GetVehicleSkinName(char *skinname, int len) if (vIndex == VEHICLE_NONE) Com_Error(ERR_DROP, "BG_GetVehicleSkinName: couldn't find vehicle %s", vehName); - if ( !VALIDSTRING( g_vehicleInfo[vIndex].skin ) ) + if (!VALIDSTRING(g_vehicleInfo[vIndex].skin)) skinname[0] = 0; else - Q_strncpyz( skinname, g_vehicleInfo[vIndex].skin, len ); + Q_strncpyz(skinname, g_vehicleInfo[vIndex].skin, len); } #if defined(_GAME) || defined(_CGAME) -//so cgame can assign the function pointer for the vehicle attachment without having to -//bother with all the other funcs that don't really exist cgame-side. +// so cgame can assign the function pointer for the vehicle attachment without having to +// bother with all the other funcs that don't really exist cgame-side. extern int BG_GetTime(void); -void AttachRidersGeneric( Vehicle_t *pVeh ) -{ +void AttachRidersGeneric(Vehicle_t *pVeh) { // If we have a pilot, attach him to the driver tag. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles; + vec3_t yawOnlyAngles; bgEntity_t *parent = pVeh->m_pParentEntity; bgEntity_t *pilot = pVeh->m_pPilot; int crotchBolt = trap->G2API_AddBolt(parent->ghoul2, 0, "*driver"); @@ -1468,8 +1336,9 @@ void AttachRidersGeneric( Vehicle_t *pVeh ) VectorSet(yawOnlyAngles, 0, parent->playerState->viewangles[YAW], 0); // Get the driver tag. - trap->G2API_GetBoltMatrix( parent->ghoul2, 0, crotchBolt, &boltMatrix, yawOnlyAngles, parent->playerState->origin, BG_GetTime(), NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, pilot->playerState->origin ); + trap->G2API_GetBoltMatrix(parent->ghoul2, 0, crotchBolt, &boltMatrix, yawOnlyAngles, parent->playerState->origin, BG_GetTime(), NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pilot->playerState->origin); } } #endif diff --git a/codemp/game/bg_weapons.c b/codemp/game/bg_weapons.c index 9f0c4e8e0d..135b214fa0 100644 --- a/codemp/game/bg_weapons.c +++ b/codemp/game/bg_weapons.c @@ -27,396 +27,417 @@ along with this program; if not, see . #include "bg_local.h" // Muzzle point table... -vec3_t WP_MuzzlePoint[WP_NUM_WEAPONS] = -{// Fwd, right, up. - {0, 0, 0 }, // WP_NONE, - {0 , 8, 0 }, // WP_STUN_BATON, - {0 , 8, 0 }, // WP_MELEE, - {8 , 16, 0 }, // WP_SABER, - {12, 6, -6 }, // WP_BRYAR_PISTOL, - {12, 6, -6 }, // WP_BLASTER, - {12, 6, -6 }, // WP_DISRUPTOR, - {12, 2, -6 }, // WP_BOWCASTER, - {12, 4.5, -6 }, // WP_REPEATER, - {12, 6, -6 }, // WP_DEMP2, - {12, 6, -6 }, // WP_FLECHETTE, - {12, 8, -4 }, // WP_ROCKET_LAUNCHER, - {12, 0, -4 }, // WP_THERMAL, - {12, 0, -10 }, // WP_TRIP_MINE, - {12, 0, -4 }, // WP_DET_PACK, - {12, 6, -6 }, // WP_CONCUSSION - {12, 6, -6 }, // WP_BRYAR_OLD, -}; - -weaponData_t weaponData[WP_NUM_WEAPONS] = -{ - { // WP_NONE -// "No Weapon", // char classname[32]; // Spawning name - AMMO_NONE, // int ammoIndex; // Index to proper ammo slot - 0, // int ammoLow; // Count when ammo is low - 0, // int energyPerShot; // Amount of energy used per shot - 0, // int fireTime; // Amount of time between firings - 0, // int range; // Range of weapon - 0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 0, // int altFireTime; // Amount of time between alt-firings - 0, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_STUN_BATON -// "Stun Baton", // char classname[32]; // Spawning name - AMMO_NONE, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 0, // int energyPerShot; // Amount of energy used per shot - 400, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_MELEE -// "Melee", // char classname[32]; // Spawning name - AMMO_NONE, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 0, // int energyPerShot; // Amount of energy used per shot - 400, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_SABER, -// "Lightsaber", // char classname[32]; // Spawning name - AMMO_NONE, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 0, // int energyPerShot; // Amount of energy used per shot - 100, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 100, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_BRYAR_PISTOL, -// "Bryar Pistol", // char classname[32]; // Spawning name - AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot - 0,//15, // int ammoLow; // Count when ammo is low - 0,//2, // int energyPerShot; // Amount of energy used per shot - 800,//400, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 0,//2, // int altEnergyPerShot; // Amount of energy used for alt-fire - 800,//400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0,//200, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0,//1, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0,//1500 // int altMaxCharge; // above for secondary - }, - { // WP_BLASTER -// "E11 Blaster Rifle", // char classname[32]; // Spawning name - AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 2, // int energyPerShot; // Amount of energy used per shot - 350, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 3, // int altEnergyPerShot; // Amount of energy used for alt-fire - 150, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_DISRUPTOR -// "Tenloss Disruptor Rifle",// char classname[32]; // Spawning name - AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 5, // int energyPerShot; // Amount of energy used per shot - 600, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 6, // int altEnergyPerShot; // Amount of energy used for alt-fire - 1300, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 200, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 3, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 1700 // int altMaxCharge; // above for secondary - }, - { // WP_BOWCASTER -// "Wookiee Bowcaster", // char classname[32]; // Spawning name - AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 5, // int energyPerShot; // Amount of energy used per shot - 1000, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 5, // int altEnergyPerShot; // Amount of energy used for alt-fire - 750, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 400, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 5, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 1700, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_REPEATER -// "Imperial Heavy Repeater",// char classname[32]; // Spawning name - AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 1, // int energyPerShot; // Amount of energy used per shot - 100, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 15, // int altEnergyPerShot; // Amount of energy used for alt-fire - 800, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_DEMP2 -// "DEMP2", // char classname[32]; // Spawning name - AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 8, // int energyPerShot; // Amount of energy used per shot - 500, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 6, // int altEnergyPerShot; // Amount of energy used for alt-fire - 900, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 250, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 3, // int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 2100 // int altMaxCharge; // above for secondary - }, - { // WP_FLECHETTE -// "Golan Arms Flechette", // char classname[32]; // Spawning name - AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 10, // int energyPerShot; // Amount of energy used per shot - 700, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 15, // int altEnergyPerShot; // Amount of energy used for alt-fire - 800, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_ROCKET_LAUNCHER -// "Merr-Sonn Missile System", // char classname[32]; // Spawning name - AMMO_ROCKETS, // int ammoIndex; // Index to proper ammo slot - 5, // int ammoLow; // Count when ammo is low - 1, // int energyPerShot; // Amount of energy used per shot - 900, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 2, // int altEnergyPerShot; // Amount of energy used for alt-fire - 1200, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_THERMAL -// "Thermal Detonator", // char classname[32]; // Spawning name - AMMO_THERMAL, // int ammoIndex; // Index to proper ammo slot - 0, // int ammoLow; // Count when ammo is low - 1, // int energyPerShot; // Amount of energy used per shot - 800, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 1, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_TRIP_MINE -// "Trip Mine", // char classname[32]; // Spawning name - AMMO_TRIPMINE, // int ammoIndex; // Index to proper ammo slot - 0, // int ammoLow; // Count when ammo is low - 1, // int energyPerShot; // Amount of energy used per shot - 800, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 1, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_DET_PACK -// "Det Pack", // char classname[32]; // Spawning name - AMMO_DETPACK, // int ammoIndex; // Index to proper ammo slot - 0, // int ammoLow; // Count when ammo is low - 1, // int energyPerShot; // Amount of energy used per shot - 800, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_CONCUSSION -// "Concussion Rifle", // char classname[32]; // Spawning name - AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot - 40, // int ammoLow; // Count when ammo is low - 40, // int energyPerShot; // Amount of energy used per shot - 800, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 50, // int altEnergyPerShot; // Amount of energy used for alt-fire - 1200, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, // int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_BRYAR_OLD, -// "Bryar Pistol", // char classname[32]; // Spawning name - AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot - 15, // int ammoLow; // Count when ammo is low - 2, // int energyPerShot; // Amount of energy used per shot - 400, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - 2, // int altEnergyPerShot; // Amount of energy used for alt-fire - 400, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 200, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 1, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 1500 // int altMaxCharge; // above for secondary - }, - { // WP_EMPLCACED_GUN -// "Emplaced Gun", // char classname[32]; // Spawning name - /*AMMO_BLASTER*/0, // int ammoIndex; // Index to proper ammo slot - /*5*/0, // int ammoLow; // Count when ammo is low - /*2*/0, // int energyPerShot; // Amount of energy used per shot - 100, // int fireTime; // Amount of time between firings - 8192, // int range; // Range of weapon - /*3*/0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 100, // int altFireTime; // Amount of time between alt-firings - 8192, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - }, - { // WP_TURRET - NOTE NOT ACTUALLY USEABLE BY PLAYER! -// "Emplaced Gun", // char classname[32]; // Spawning name - /*AMMO_BLASTER*/0, // int ammoIndex; // Index to proper ammo slot - /*5*/0, // int ammoLow; // Count when ammo is low - /*2*/0, // int energyPerShot; // Amount of energy used per shot - 0, // int fireTime; // Amount of time between firings - 0, // int range; // Range of weapon - /*3*/0, // int altEnergyPerShot; // Amount of energy used for alt-fire - 0, // int altFireTime; // Amount of time between alt-firings - 0, // int altRange; // Range of alt-fire - 0, // int chargeSubTime; // ms interval for subtracting ammo during charge - 0, // int altChargeSubTime; // above for secondary - 0, // int chargeSub; // amount to subtract during charge on each interval - 0, //int altChargeSub; // above for secondary - 0, // int maxCharge; // stop subtracting once charged for this many ms - 0 // int altMaxCharge; // above for secondary - } -}; - -ammoData_t ammoData[AMMO_MAX] = -{ - { // AMMO_NONE -// "", // char icon[32]; // Name of ammo icon file - 0 // int max; // Max amount player can hold of ammo - }, - { // AMMO_FORCE -// "", // char icon[32]; // Name of ammo icon file - 100 // int max; // Max amount player can hold of ammo - }, - { // AMMO_BLASTER -// "", // char icon[32]; // Name of ammo icon file - 300 // int max; // Max amount player can hold of ammo - }, - { // AMMO_POWERCELL -// "", // char icon[32]; // Name of ammo icon file - 300 // int max; // Max amount player can hold of ammo - }, - { // AMMO_METAL_BOLTS -// "", // char icon[32]; // Name of ammo icon file - 300 // int max; // Max amount player can hold of ammo - }, - { // AMMO_ROCKETS -// "", // char icon[32]; // Name of ammo icon file - 25 // int max; // Max amount player can hold of ammo - }, - { // AMMO_EMPLACED -// "", // char icon[32]; // Name of ammo icon file - 800 // int max; // Max amount player can hold of ammo - }, - { // AMMO_THERMAL -// "", // char icon[32]; // Name of ammo icon file - 10 // int max; // Max amount player can hold of ammo - }, - { // AMMO_TRIPMINE -// "", // char icon[32]; // Name of ammo icon file - 10 // int max; // Max amount player can hold of ammo - }, - { // AMMO_DETPACK -// "", // char icon[32]; // Name of ammo icon file - 10 // int max; // Max amount player can hold of ammo - } +vec3_t WP_MuzzlePoint[WP_NUM_WEAPONS] = { + // Fwd, right, up. + {0, 0, 0}, // WP_NONE, + {0, 8, 0}, // WP_STUN_BATON, + {0, 8, 0}, // WP_MELEE, + {8, 16, 0}, // WP_SABER, + {12, 6, -6}, // WP_BRYAR_PISTOL, + {12, 6, -6}, // WP_BLASTER, + {12, 6, -6}, // WP_DISRUPTOR, + {12, 2, -6}, // WP_BOWCASTER, + {12, 4.5, -6}, // WP_REPEATER, + {12, 6, -6}, // WP_DEMP2, + {12, 6, -6}, // WP_FLECHETTE, + {12, 8, -4}, // WP_ROCKET_LAUNCHER, + {12, 0, -4}, // WP_THERMAL, + {12, 0, -10}, // WP_TRIP_MINE, + {12, 0, -4}, // WP_DET_PACK, + {12, 6, -6}, // WP_CONCUSSION + {12, 6, -6}, // WP_BRYAR_OLD, }; +weaponData_t weaponData[WP_NUM_WEAPONS] = {{ + // WP_NONE + // "No Weapon", // char classname[32]; // Spawning name + AMMO_NONE, // int ammoIndex; // Index to proper ammo slot + 0, // int ammoLow; // Count when ammo is low + 0, // int energyPerShot; // Amount of energy used per shot + 0, // int fireTime; // Amount of time between firings + 0, // int range; // Range of weapon + 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 0, // int altFireTime; // Amount of time between alt-firings + 0, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_STUN_BATON + // "Stun Baton", // char classname[32]; // Spawning name + AMMO_NONE, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 0, // int energyPerShot; // Amount of energy used per shot + 400, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_MELEE + // "Melee", // char classname[32]; // Spawning name + AMMO_NONE, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 0, // int energyPerShot; // Amount of energy used per shot + 400, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_SABER, + // "Lightsaber", // char classname[32]; // Spawning name + AMMO_NONE, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 0, // int energyPerShot; // Amount of energy used per shot + 100, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 100, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_BRYAR_PISTOL, + // "Bryar Pistol", // char classname[32]; // Spawning name + AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot + 0, // 15, // int ammoLow; // Count when ammo is low + 0, // 2, // int energyPerShot; // Amount of energy used per shot + 800, // 400, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 0, // 2, // int altEnergyPerShot; // Amount of energy used for alt-fire + 800, // 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // 200, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // 1, //int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0, // 1500 // int altMaxCharge; // above for secondary + }, + { + // WP_BLASTER + // "E11 Blaster Rifle", // char classname[32]; // Spawning name + AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 2, // int energyPerShot; // Amount of energy used per shot + 350, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 3, // int altEnergyPerShot; // Amount of energy used for alt-fire + 150, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_DISRUPTOR + // "Tenloss Disruptor Rifle",// char classname[32]; // Spawning name + AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 5, // int energyPerShot; // Amount of energy used per shot + 600, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 6, // int altEnergyPerShot; // Amount of energy used for alt-fire + 1300, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 200, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 3, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 1700 // int altMaxCharge; // above for secondary + }, + { + // WP_BOWCASTER + // "Wookiee Bowcaster", // char classname[32]; // Spawning name + AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 5, // int energyPerShot; // Amount of energy used per shot + 1000, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 5, // int altEnergyPerShot; // Amount of energy used for alt-fire + 750, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 400, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 5, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 1700, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_REPEATER + // "Imperial Heavy Repeater",// char classname[32]; // Spawning name + AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 1, // int energyPerShot; // Amount of energy used per shot + 100, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 15, // int altEnergyPerShot; // Amount of energy used for alt-fire + 800, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_DEMP2 + // "DEMP2", // char classname[32]; // Spawning name + AMMO_POWERCELL, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 8, // int energyPerShot; // Amount of energy used per shot + 500, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 6, // int altEnergyPerShot; // Amount of energy used for alt-fire + 900, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 250, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 3, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 2100 // int altMaxCharge; // above for secondary + }, + { + // WP_FLECHETTE + // "Golan Arms Flechette", // char classname[32]; // Spawning name + AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 10, // int energyPerShot; // Amount of energy used per shot + 700, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 15, // int altEnergyPerShot; // Amount of energy used for alt-fire + 800, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_ROCKET_LAUNCHER + // "Merr-Sonn Missile System", // char classname[32]; // Spawning name + AMMO_ROCKETS, // int ammoIndex; // Index to proper ammo slot + 5, // int ammoLow; // Count when ammo is low + 1, // int energyPerShot; // Amount of energy used per shot + 900, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 2, // int altEnergyPerShot; // Amount of energy used for alt-fire + 1200, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_THERMAL + // "Thermal Detonator", // char classname[32]; // Spawning name + AMMO_THERMAL, // int ammoIndex; // Index to proper ammo slot + 0, // int ammoLow; // Count when ammo is low + 1, // int energyPerShot; // Amount of energy used per shot + 800, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 1, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_TRIP_MINE + // "Trip Mine", // char classname[32]; // Spawning name + AMMO_TRIPMINE, // int ammoIndex; // Index to proper ammo slot + 0, // int ammoLow; // Count when ammo is low + 1, // int energyPerShot; // Amount of energy used per shot + 800, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 1, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_DET_PACK + // "Det Pack", // char classname[32]; // Spawning name + AMMO_DETPACK, // int ammoIndex; // Index to proper ammo slot + 0, // int ammoLow; // Count when ammo is low + 1, // int energyPerShot; // Amount of energy used per shot + 800, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_CONCUSSION + // "Concussion Rifle", // char classname[32]; // Spawning name + AMMO_METAL_BOLTS, // int ammoIndex; // Index to proper ammo slot + 40, // int ammoLow; // Count when ammo is low + 40, // int energyPerShot; // Amount of energy used per shot + 800, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 50, // int altEnergyPerShot; // Amount of energy used for alt-fire + 1200, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_BRYAR_OLD, + // "Bryar Pistol", // char classname[32]; // Spawning name + AMMO_BLASTER, // int ammoIndex; // Index to proper ammo slot + 15, // int ammoLow; // Count when ammo is low + 2, // int energyPerShot; // Amount of energy used per shot + 400, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + 2, // int altEnergyPerShot; // Amount of energy used for alt-fire + 400, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 200, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 1, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 1500 // int altMaxCharge; // above for secondary + }, + { + // WP_EMPLCACED_GUN + // "Emplaced Gun", // char classname[32]; // Spawning name + /*AMMO_BLASTER*/ 0, // int ammoIndex; // Index to proper ammo slot + /*5*/ 0, // int ammoLow; // Count when ammo is low + /*2*/ 0, // int energyPerShot; // Amount of energy used per shot + 100, // int fireTime; // Amount of time between firings + 8192, // int range; // Range of weapon + /*3*/ 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 100, // int altFireTime; // Amount of time between alt-firings + 8192, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }, + { + // WP_TURRET - NOTE NOT ACTUALLY USEABLE BY PLAYER! + // "Emplaced Gun", // char classname[32]; // Spawning name + /*AMMO_BLASTER*/ 0, // int ammoIndex; // Index to proper ammo slot + /*5*/ 0, // int ammoLow; // Count when ammo is low + /*2*/ 0, // int energyPerShot; // Amount of energy used per shot + 0, // int fireTime; // Amount of time between firings + 0, // int range; // Range of weapon + /*3*/ 0, // int altEnergyPerShot; // Amount of energy used for alt-fire + 0, // int altFireTime; // Amount of time between alt-firings + 0, // int altRange; // Range of alt-fire + 0, // int chargeSubTime; // ms interval for subtracting ammo during charge + 0, // int altChargeSubTime; // above for secondary + 0, // int chargeSub; // amount to subtract during charge on each interval + 0, // int altChargeSub; // above for secondary + 0, // int maxCharge; // stop subtracting once charged for this many ms + 0 // int altMaxCharge; // above for secondary + }}; +ammoData_t ammoData[AMMO_MAX] = {{ + // AMMO_NONE + // "", // char icon[32]; // Name of ammo icon file + 0 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_FORCE + // "", // char icon[32]; // Name of ammo icon file + 100 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_BLASTER + // "", // char icon[32]; // Name of ammo icon file + 300 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_POWERCELL + // "", // char icon[32]; // Name of ammo icon file + 300 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_METAL_BOLTS + // "", // char icon[32]; // Name of ammo icon file + 300 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_ROCKETS + // "", // char icon[32]; // Name of ammo icon file + 25 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_EMPLACED + // "", // char icon[32]; // Name of ammo icon file + 800 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_THERMAL + // "", // char icon[32]; // Name of ammo icon file + 10 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_TRIPMINE + // "", // char icon[32]; // Name of ammo icon file + 10 // int max; // Max amount player can hold of ammo + }, + { + // AMMO_DETPACK + // "", // char icon[32]; // Name of ammo icon file + 10 // int max; // Max amount player can hold of ammo + }}; diff --git a/codemp/game/g_ICARUScb.c b/codemp/game/g_ICARUScb.c index 657bf6c5da..6543f7bde7 100644 --- a/codemp/game/g_ICARUScb.c +++ b/codemp/game/g_ICARUScb.c @@ -22,7 +22,7 @@ along with this program; if not, see . //==================================================================================== // -//rww - ICARUS callback file, all that can be handled within vm's is handled in here. +// rww - ICARUS callback file, all that can be handled within vm's is handled in here. // //==================================================================================== @@ -33,22 +33,20 @@ along with this program; if not, see . #include "icarus/Q3_Registers.h" #include "g_nav.h" -qboolean BG_SabersOff( playerState_t *ps ); +qboolean BG_SabersOff(playerState_t *ps); extern stringID_table_t WPTable[]; extern stringID_table_t BSTable[]; - -//This is a hack I guess. It's because we can't include the file this enum is in -//unless we're using cpp. But we need it for the interpreter stuff. -//In any case, DO NOT modify this enum. +// This is a hack I guess. It's because we can't include the file this enum is in +// unless we're using cpp. But we need it for the interpreter stuff. +// In any case, DO NOT modify this enum. // Hack++ // This code is compiled as C++ on Xbox. We could try and rig something above // so that we only get the C version of the includes (no full Icarus) in that // scenario, but I think we'll just try to leave this out instead. //#if defined(__linux__) && defined(__GCC__) || !defined(__linux__) -enum -{ +enum { TK_EOF = -1, TK_UNDEFINED, TK_COMMENT, @@ -65,11 +63,10 @@ enum #include "icarus/interpreter.h" -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; -stringID_table_t setTable[] = -{ - ENUM2STRING(SET_SPAWNSCRIPT),//0 +stringID_table_t setTable[] = { + ENUM2STRING(SET_SPAWNSCRIPT), // 0 ENUM2STRING(SET_USESCRIPT), ENUM2STRING(SET_AWAKESCRIPT), ENUM2STRING(SET_ANGERSCRIPT), @@ -281,63 +278,57 @@ stringID_table_t setTable[] = ENUM2STRING(SET_CLEAN_DAMAGING_ENTS), ENUM2STRING(SET_HUD), -//FIXME: add BOTH_ attributes here too - {"", SET_}, + // FIXME: add BOTH_ attributes here too + {"", SET_}, }; -void Q3_TaskIDClear( int *taskID ) -{ - *taskID = -1; -} +void Q3_TaskIDClear(int *taskID) { *taskID = -1; } -void G_DebugPrint( int printLevel, const char *format, ... ) -{ - va_list argptr; - char text[1024] = {0}; +void G_DebugPrint(int printLevel, const char *format, ...) { + va_list argptr; + char text[1024] = {0}; - //Don't print messages they don't want to see - //if ( g_ICARUSDebug->integer < level ) + // Don't print messages they don't want to see + // if ( g_ICARUSDebug->integer < level ) if (developer.integer != 2) return; - va_start( argptr, format ); - Q_vsnprintf(text, sizeof( text ), format, argptr ); - va_end( argptr ); + va_start(argptr, format); + Q_vsnprintf(text, sizeof(text), format, argptr); + va_end(argptr); - //Add the color formatting - switch ( printLevel ) - { - case WL_ERROR: - Com_Printf ( S_COLOR_RED"ERROR: %s", text ); - break; + // Add the color formatting + switch (printLevel) { + case WL_ERROR: + Com_Printf(S_COLOR_RED "ERROR: %s", text); + break; - case WL_WARNING: - Com_Printf ( S_COLOR_YELLOW"WARNING: %s", text ); - break; + case WL_WARNING: + Com_Printf(S_COLOR_YELLOW "WARNING: %s", text); + break; - case WL_DEBUG: - { - int entNum; - char *buffer; + case WL_DEBUG: { + int entNum; + char *buffer; - entNum = atoi( text ); + entNum = atoi(text); - //if ( ( ICARUS_entFilter >= 0 ) && ( ICARUS_entFilter != entNum ) ) - // return; + // if ( ( ICARUS_entFilter >= 0 ) && ( ICARUS_entFilter != entNum ) ) + // return; - buffer = (char *) text; - buffer += 5; + buffer = (char *)text; + buffer += 5; - if ( ( entNum < 0 ) || ( entNum >= MAX_GENTITIES ) ) - entNum = 0; + if ((entNum < 0) || (entNum >= MAX_GENTITIES)) + entNum = 0; - Com_Printf ( S_COLOR_BLUE"DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer ); - break; - } - default: - case WL_VERBOSE: - Com_Printf ( S_COLOR_GREEN"INFO: %s", text ); - break; + Com_Printf(S_COLOR_BLUE "DEBUG: %s(%d): %s\n", g_entities[entNum].script_targetname, entNum, buffer); + break; + } + default: + case WL_VERBOSE: + Com_Printf(S_COLOR_GREEN "INFO: %s", text); + break; } } @@ -346,13 +337,11 @@ void G_DebugPrint( int printLevel, const char *format, ... ) Q3_GetAnimLower ------------------------- */ -static char *Q3_GetAnimLower( gentity_t *ent ) -{ +static char *Q3_GetAnimLower(gentity_t *ent) { int anim = 0; - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n" ); + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetAnimLower: attempted to read animation state off non-client!\n"); return NULL; } @@ -366,13 +355,11 @@ static char *Q3_GetAnimLower( gentity_t *ent ) Q3_GetAnimUpper ------------------------- */ -static char *Q3_GetAnimUpper( gentity_t *ent ) -{ +static char *Q3_GetAnimUpper(gentity_t *ent) { int anim = 0; - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n" ); + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetAnimUpper: attempted to read animation state off non-client!\n"); return NULL; } @@ -386,73 +373,63 @@ static char *Q3_GetAnimUpper( gentity_t *ent ) Q3_GetAnimBoth ------------------------- */ -static char *Q3_GetAnimBoth( gentity_t *ent ) -{ - char *lowerName, *upperName; +static char *Q3_GetAnimBoth(gentity_t *ent) { + char *lowerName, *upperName; - lowerName = Q3_GetAnimLower( ent ); - upperName = Q3_GetAnimUpper( ent ); + lowerName = Q3_GetAnimLower(ent); + upperName = Q3_GetAnimUpper(ent); - if ( !lowerName || !lowerName[0] ) - { - G_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n" ); + if (!lowerName || !lowerName[0]) { + G_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: NULL legs animation string found!\n"); return NULL; } - if ( !upperName || !upperName[0] ) - { - G_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n" ); + if (!upperName || !upperName[0]) { + G_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: NULL torso animation string found!\n"); return NULL; } - if ( Q_stricmp( lowerName, upperName ) ) - { -#ifdef _DEBUG // sigh, cut down on tester reports that aren't important - G_DebugPrint( WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n" ); + if (Q_stricmp(lowerName, upperName)) { +#ifdef _DEBUG // sigh, cut down on tester reports that aren't important + G_DebugPrint(WL_WARNING, "Q3_GetAnimBoth: legs and torso animations did not match : returning legs\n"); #endif } return lowerName; } -int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) -{ - gentity_t *ent = &g_entities[entID]; - char finalName[MAX_QPATH]; - soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch - qboolean type_voice = qfalse; - int soundHandle; - qboolean bBroadcast; +int Q3_PlaySound(int taskID, int entID, const char *name, const char *channel) { + gentity_t *ent = &g_entities[entID]; + char finalName[MAX_QPATH]; + soundChannel_t voice_chan = CHAN_VOICE; // set a default so the compiler doesn't bitch + qboolean type_voice = qfalse; + int soundHandle; + qboolean bBroadcast; - Q_strncpyz( finalName, name, MAX_QPATH ); + Q_strncpyz(finalName, name, MAX_QPATH); Q_strupr(finalName); - //G_AddSexToMunroString( finalName, qtrue ); + // G_AddSexToMunroString( finalName, qtrue ); - COM_StripExtension( (const char *)finalName, finalName, sizeof( finalName ) ); + COM_StripExtension((const char *)finalName, finalName, sizeof(finalName)); - soundHandle = G_SoundIndex( (char *) finalName ); + soundHandle = G_SoundIndex((char *)finalName); bBroadcast = qfalse; - if ( ( Q_stricmp( channel, "CHAN_ANNOUNCER" ) == 0 ) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname ) == 0) ) { + if ((Q_stricmp(channel, "CHAN_ANNOUNCER") == 0) || (ent->classname && Q_stricmp("target_scriptrunner", ent->classname) == 0)) { bBroadcast = qtrue; } - // moved here from further down so I can easily check channel-type without code dup... // - if ( Q_stricmp( channel, "CHAN_VOICE" ) == 0 ) - { + if (Q_stricmp(channel, "CHAN_VOICE") == 0) { voice_chan = CHAN_VOICE; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_ATTEN" ) == 0 ) - { - voice_chan = CHAN_AUTO;//CHAN_VOICE_ATTEN; + } else if (Q_stricmp(channel, "CHAN_VOICE_ATTEN") == 0) { + voice_chan = CHAN_AUTO; // CHAN_VOICE_ATTEN; type_voice = qtrue; - } - else if ( Q_stricmp( channel, "CHAN_VOICE_GLOBAL" ) == 0 ) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... + } else if (Q_stricmp(channel, "CHAN_VOICE_GLOBAL") == 0) // this should broadcast to everyone, put only casue animation on G_SoundOnEnt... { - voice_chan = CHAN_AUTO;//CHAN_VOICE_GLOBAL; + voice_chan = CHAN_AUTO; // CHAN_VOICE_GLOBAL; type_voice = qtrue; bBroadcast = qtrue; } @@ -476,7 +453,8 @@ int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) else //if (precacheWav[i].speaker==SP_NONE) // lower screen text { sharedEntity_t *ent2 = SV_GentityNum(0); - // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 by the computer core that was submitted as a bug report... + // the numbers in here were either the original ones Bob entered (350), or one arrived at from checking the distance Chell stands at in stasis2 + by the computer core that was submitted as a bug report... // if (bBroadcast || (DistanceSquared(ent->currentOrigin, ent2->currentOrigin) < ((voice_chan == CHAN_VOICE_ATTEN)?(350 * 350):(1200 * 1200)) ) ) { @@ -496,8 +474,7 @@ int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) } */ - if ( type_voice ) - { + if (type_voice) { char buf[128]; float tFVal = 0; @@ -505,33 +482,26 @@ int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) tFVal = atof(buf); - - if ( tFVal > 1.0f ) - {//Skip the damn sound! + if (tFVal > 1.0f) { // Skip the damn sound! return qtrue; + } else { + // This the voice channel + G_Sound(ent, voice_chan, G_SoundIndex((char *)finalName)); } - else - { - //This the voice channel - G_Sound( ent, voice_chan, G_SoundIndex((char *) finalName) ); - } - //Remember we're waiting for this - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_CHAN_VOICE, taskID ); + // Remember we're waiting for this + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_CHAN_VOICE, taskID); return qfalse; } - if ( bBroadcast ) - {//Broadcast the sound - gentity_t *te; + if (bBroadcast) { // Broadcast the sound + gentity_t *te; - te = G_TempEntity( ent->r.currentOrigin, EV_GLOBAL_SOUND ); + te = G_TempEntity(ent->r.currentOrigin, EV_GLOBAL_SOUND); te->s.eventParm = soundHandle; te->r.svFlags |= SVF_BROADCAST; - } - else - { - G_Sound( ent, CHAN_AUTO, soundHandle ); + } else { + G_Sound(ent, CHAN_AUTO, soundHandle); } return qtrue; @@ -542,35 +512,32 @@ int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) Q3_Play ------------------------- */ -void Q3_Play( int taskID, int entID, const char *type, const char *name ) -{ +void Q3_Play(int taskID, int entID, const char *type, const char *name) { gentity_t *ent = &g_entities[entID]; - if ( !Q_stricmp( type, "PLAY_ROFF" ) ) - { + if (!Q_stricmp(type, "PLAY_ROFF")) { // Try to load the requested ROFF - ent->roffid = trap->ROFF_Cache((char*)name); - if ( ent->roffid ) - { - ent->roffname = G_NewString( name ); + ent->roffid = trap->ROFF_Cache((char *)name); + if (ent->roffid) { + ent->roffname = G_NewString(name); // Start the roff from the beginning - //ent->roff_ctr = 0; + // ent->roff_ctr = 0; - //Save this off for later - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + // Save this off for later + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); // Let the ROFF playing start. - //ent->next_roff_time = level.time; + // ent->next_roff_time = level.time; - //rww - Maybe use pos1 and pos2? I don't think we need to care if these values are sent across the net. - // These need to be initialised up front... - //VectorCopy( ent->r.currentOrigin, ent->pos1 ); - //VectorCopy( ent->r.currentAngles, ent->pos2 ); - VectorCopy( ent->r.currentOrigin, ent->s.origin2 ); - VectorCopy( ent->r.currentAngles, ent->s.angles2 ); + // rww - Maybe use pos1 and pos2? I don't think we need to care if these values are sent across the net. + // These need to be initialised up front... + // VectorCopy( ent->r.currentOrigin, ent->pos1 ); + // VectorCopy( ent->r.currentAngles, ent->pos2 ); + VectorCopy(ent->r.currentOrigin, ent->s.origin2); + VectorCopy(ent->r.currentAngles, ent->s.angles2); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); trap->ROFF_Play(ent->s.number, ent->roffid, qtrue); } @@ -584,32 +551,30 @@ anglerCallback Utility function ============= */ -void anglerCallback( gentity_t *ent ) -{ - //Complete the task - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)ent, TID_ANGLE_FACE ); +void anglerCallback(gentity_t *ent) { + // Complete the task + trap->ICARUS_TaskIDComplete((sharedEntity_t *)ent, TID_ANGLE_FACE); - //Set the currentAngles, clear all movement - VectorMA( ent->s.apos.trBase, (ent->s.apos.trDuration*0.001f), ent->s.apos.trDelta, ent->r.currentAngles ); - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + // Set the currentAngles, clear all movement + VectorMA(ent->s.apos.trBase, (ent->s.apos.trDuration * 0.001f), ent->s.apos.trDelta, ent->r.currentAngles); + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trDuration = 1; ent->s.apos.trType = TR_STATIONARY; ent->s.apos.trTime = level.time; - //Stop thinking + // Stop thinking ent->reached = 0; - if ( ent->think == anglerCallback ) - { + if (ent->think == anglerCallback) { ent->think = 0; } - //link - trap->LinkEntity( (sharedEntity_t *)ent ); + // link + trap->LinkEntity((sharedEntity_t *)ent); } -void MatchTeam( gentity_t *teamLeader, int moverState, int time ); -void Blocked_Mover( gentity_t *ent, gentity_t *other ); +void MatchTeam(gentity_t *teamLeader, int moverState, int time); +void Blocked_Mover(gentity_t *ent, gentity_t *other); /* ============= @@ -618,60 +583,52 @@ moverCallback Utility function ============= */ -void moverCallback( gentity_t *ent ) -{ //complete the task - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)ent, TID_MOVE_NAV ); +void moverCallback(gentity_t *ent) { // complete the task + trap->ICARUS_TaskIDComplete((sharedEntity_t *)ent, TID_MOVE_NAV); // play sound - ent->s.loopSound = 0;//stop looping sound + ent->s.loopSound = 0; // stop looping sound ent->s.loopIsSoundset = qfalse; - G_PlayDoorSound( ent, BMS_END );//play end sound + G_PlayDoorSound(ent, BMS_END); // play end sound - if ( ent->moverState == MOVER_1TO2 ) - {//reached open + if (ent->moverState == MOVER_1TO2) { // reached open // reached pos2 - MatchTeam( ent, MOVER_POS2, level.time ); - //SetMoverState( ent, MOVER_POS2, level.time ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//reached closed - MatchTeam( ent, MOVER_POS1, level.time ); - //SetMoverState( ent, MOVER_POS1, level.time ); + MatchTeam(ent, MOVER_POS2, level.time); + // SetMoverState( ent, MOVER_POS2, level.time ); + } else if (ent->moverState == MOVER_2TO1) { // reached closed + MatchTeam(ent, MOVER_POS1, level.time); + // SetMoverState( ent, MOVER_POS1, level.time ); } - if ( ent->blocked == Blocked_Mover ) - { + if (ent->blocked == Blocked_Mover) { ent->blocked = 0; } -// if ( !Q_stricmp( "misc_model_breakable", ent->classname ) && ent->physicsBounce ) -// {//a gravity-affected model -// misc_model_breakable_gravity_init( ent, qfalse ); -// } + // if ( !Q_stricmp( "misc_model_breakable", ent->classname ) && ent->physicsBounce ) + // {//a gravity-affected model + // misc_model_breakable_gravity_init( ent, qfalse ); + // } } -void Blocked_Mover( gentity_t *ent, gentity_t *other ) -{ +void Blocked_Mover(gentity_t *ent, gentity_t *other) { // remove anything other than a client -- no longer the case // don't remove security keys or goodie keys - if ( other->s.eType == ET_ITEM) - { + if (other->s.eType == ET_ITEM) { // should we be doing anything special if a key blocks it... move it somehow..? } // if your not a client, or your a dead client remove yourself... - else if ( other->s.number && (!other->client || (other->client && other->health <= 0 && other->r.contents == CONTENTS_CORPSE && !other->message)) ) - { - //if ( !other->taskManager || !other->taskManager->IsRunning() ) + else if (other->s.number && (!other->client || (other->client && other->health <= 0 && other->r.contents == CONTENTS_CORPSE && !other->message))) { + // if ( !other->taskManager || !other->taskManager->IsRunning() ) { // if an item or weapon can we do a little explosion..? - G_FreeEntity( other ); + G_FreeEntity(other); return; } } - if ( ent->damage ) { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } } @@ -682,12 +639,11 @@ moveAndRotateCallback Utility function ============= */ -void moveAndRotateCallback( gentity_t *ent ) -{ - //stop turning - anglerCallback( ent ); - //stop moving - moverCallback( ent ); +void moveAndRotateCallback(gentity_t *ent) { + // stop turning + anglerCallback(ent); + // stop moving + moverCallback(ent); } /* @@ -697,45 +653,40 @@ Q3_Lerp2Start Lerps the origin of an entity to its starting position ============= */ -void Q3_Lerp2Start( int entID, int taskID, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +void Q3_Lerp2Start(int entID, int taskID, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_Lerp2Start: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Lerp2Start: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_Lerp2Start: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_Lerp2Start: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //FIXME: set up correctly!!! + // FIXME: set up correctly!!! ent->moverState = MOVER_2TO1; ent->s.eType = ET_MOVER; - ent->reached = moverCallback; //Callsback the the completion of the move - if ( ent->damage ) - { + ent->reached = moverCallback; // Callsback the the completion of the move + if (ent->damage) { ent->blocked = Blocked_Mover; } - ent->s.pos.trDuration = duration * 10; //In seconds + ent->s.pos.trDuration = duration * 10; // In seconds ent->s.pos.trTime = level.time; - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -745,48 +696,43 @@ Q3_Lerp2End Lerps the origin of an entity to its ending position ============= */ -void Q3_Lerp2End( int entID, int taskID, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +void Q3_Lerp2End(int entID, int taskID, float duration) { + gentity_t *ent = &g_entities[entID]; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_Lerp2End: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Lerp2End: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_Lerp2End: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_Lerp2End: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //FIXME: set up correctly!!! + // FIXME: set up correctly!!! ent->moverState = MOVER_1TO2; ent->s.eType = ET_MOVER; - ent->reached = moverCallback; //Callsback the the completion of the move - if ( ent->damage ) - { + ent->reached = moverCallback; // Callsback the the completion of the move + if (ent->damage) { ent->blocked = Blocked_Mover; } - ent->s.pos.trDuration = duration * 10; //In seconds + ent->s.pos.trDuration = duration * 10; // In seconds ent->s.time = level.time; - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } -void InitMoverTrData( gentity_t *ent ); +void InitMoverTrData(gentity_t *ent); /* ============= @@ -796,32 +742,28 @@ Lerps the origin and angles of an entity to the destination values ============= */ -void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +void Q3_Lerp2Pos(int taskID, int entID, vec3_t origin, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; moverState_t moverState; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_Lerp2Pos: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Lerp2Pos: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_Lerp2Pos: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_Lerp2Pos: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } - //Don't allow a zero duration - if ( duration == 0 ) + // Don't allow a zero duration + if (duration == 0) duration = 1; // @@ -829,49 +771,41 @@ void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float dur moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->r.currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->r.currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); moverState = MOVER_1TO2; - } - else - { - VectorCopy( ent->r.currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + } else { + VectorCopy(ent->r.currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); + InitMoverTrData(ent); ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); - //Only do the angles if specified - if ( angles != NULL ) - { + // Only do the angles if specified + if (angles != NULL) { // // Rotation - for ( i = 0; i < 3; i++ ) - { - ang[i] = AngleDelta( angles[i], ent->r.currentAngles[i] ); - ent->s.apos.trDelta[i] = ( ang[i] / ( duration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleDelta(angles[i], ent->r.currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (duration * 0.001f)); } - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trDuration = duration; @@ -879,25 +813,22 @@ void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float dur ent->s.apos.trTime = level.time; ent->reached = moveAndRotateCallback; - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANGLE_FACE, taskID ); - } - else - { - //Setup the last bits of information + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANGLE_FACE, taskID); + } else { + // Setup the last bits of information ent->reached = moverCallback; } - if ( ent->damage ) - { + if (ent->damage) { ent->blocked = Blocked_Mover; } - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -907,53 +838,46 @@ Q3_LerpAngles Lerps the angles to the destination value ============= */ -void Q3_Lerp2Angles( int taskID, int entID, vec3_t angles, float duration ) -{ - gentity_t *ent = &g_entities[entID]; - vec3_t ang; - int i; +void Q3_Lerp2Angles(int taskID, int entID, vec3_t angles, float duration) { + gentity_t *ent = &g_entities[entID]; + vec3_t ang; + int i; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_Lerp2Angles: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Lerp2Angles: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_Lerp2Angles: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_Lerp2Angles: ent %d is NOT a mover!\n", entID); return; } - //If we want an instant move, don't send 0... - ent->s.apos.trDuration = (duration>0) ? duration : 1; + // If we want an instant move, don't send 0... + ent->s.apos.trDuration = (duration > 0) ? duration : 1; - for ( i = 0; i < 3; i++ ) - { - ang [i] = AngleSubtract( angles[i], ent->r.currentAngles[i]); - ent->s.apos.trDelta[i] = ( ang[i] / ( ent->s.apos.trDuration * 0.001f ) ); + for (i = 0; i < 3; i++) { + ang[i] = AngleSubtract(angles[i], ent->r.currentAngles[i]); + ent->s.apos.trDelta[i] = (ang[i] / (ent->s.apos.trDuration * 0.001f)); } - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); - if ( ent->alt_fire ) - { + if (ent->alt_fire) { ent->s.apos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.apos.trType = TR_NONLINEAR_STOP; } ent->s.apos.trTime = level.time; - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANGLE_FACE, taskID ); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANGLE_FACE, taskID); - //ent->e_ReachedFunc = reachedF_NULL; + // ent->e_ReachedFunc = reachedF_NULL; ent->think = anglerCallback; ent->nextthink = level.time + duration; - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -963,24 +887,21 @@ Q3_GetTag Gets the value of a tag by the give name ============= */ -int Q3_GetTag( int entID, const char *name, int lookup, vec3_t info ) -{ - gentity_t *ent = &g_entities[entID]; +int Q3_GetTag(int entID, const char *name, int lookup, vec3_t info) { + gentity_t *ent = &g_entities[entID]; - if (!ent->inuse) - { + if (!ent->inuse) { assert(0); return 0; } - switch ( lookup ) - { + switch (lookup) { case TYPE_ORIGIN: - return TAG_GetOrigin( ent->ownername, name, info ); + return TAG_GetOrigin(ent->ownername, name, info); break; case TYPE_ANGLES: - return TAG_GetAngles( ent->ownername, name, info ); + return TAG_GetAngles(ent->ownername, name, info); break; } @@ -996,19 +917,16 @@ Q3_Use Uses an entity ============ */ -void Q3_Use( int entID, const char *target ) -{ - gentity_t *ent = &g_entities[entID]; +void Q3_Use(int entID, const char *target) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_Use: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Use: invalid entID %d\n", entID); return; } - if( !target || !target[0] ) - { - G_DebugPrint( WL_WARNING, "Q3_Use: string is NULL!\n" ); + if (!target || !target[0]) { + G_DebugPrint(WL_WARNING, "Q3_Use: string is NULL!\n"); return; } @@ -1024,47 +942,39 @@ Q3_Kill Argument : const char *name ============ */ -void Q3_Kill( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; - int o_health; +void Q3_Kill(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *victim = NULL; + int o_health; - if( !Q_stricmp( name, "self") ) - { + if (!Q_stricmp(name, "self")) { victim = ent; - } - else if( !Q_stricmp( name, "enemy" ) ) - { + } else if (!Q_stricmp(name, "enemy")) { victim = ent->enemy; - } - else - { - victim = G_Find (NULL, FOFS(targetname), (char *) name ); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); } - if ( !victim ) - { - G_DebugPrint( WL_WARNING, "Q3_Kill: can't find %s\n", name); + if (!victim) { + G_DebugPrint(WL_WARNING, "Q3_Kill: can't find %s\n", name); return; } - //rww - I guess this would only apply to NPCs anyway. I'm not going to bother. - //if ( victim == ent ) + // rww - I guess this would only apply to NPCs anyway. I'm not going to bother. + // if ( victim == ent ) //{//don't ICARUS_FreeEnt me, I'm in the middle of a script! (FIXME: shouldn't ICARUS handle this internally?) // victim->svFlags |= SVF_KILLED_SELF; - //} + // } o_health = victim->health; victim->health = 0; - if ( victim->client ) - { + if (victim->client) { victim->flags |= FL_NO_KNOCKBACK; } - //G_SetEnemy(victim, ent); - if( victim->die != NULL ) // check can be omitted + // G_SetEnemy(victim, ent); + if (victim->die != NULL) // check can be omitted { - //GEntity_DieFunc( victim, NULL, NULL, o_health, MOD_UNKNOWN ); + // GEntity_DieFunc( victim, NULL, NULL, o_health, MOD_UNKNOWN ); victim->die(victim, victim, victim, o_health, MOD_UNKNOWN); } } @@ -1077,23 +987,16 @@ Q3_RemoveEnt Argument : sharedEntity_t *victim ============ */ -void Q3_RemoveEnt( gentity_t *victim ) -{ - if( victim->client ) - { - if ( victim->s.eType != ET_NPC ) - { - G_DebugPrint( WL_WARNING, "Q3_RemoveEnt: You can't remove clients in MP!\n" ); - assert(0); //can't remove clients in MP - } - else - {//remove the NPC - if ( victim->client->NPC_class == CLASS_VEHICLE ) - {//eject everyone out of a vehicle that's about to remove itself +void Q3_RemoveEnt(gentity_t *victim) { + if (victim->client) { + if (victim->s.eType != ET_NPC) { + G_DebugPrint(WL_WARNING, "Q3_RemoveEnt: You can't remove clients in MP!\n"); + assert(0); // can't remove clients in MP + } else { // remove the NPC + if (victim->client->NPC_class == CLASS_VEHICLE) { // eject everyone out of a vehicle that's about to remove itself Vehicle_t *pVeh = victim->m_pVehicle; - if ( pVeh && pVeh->m_pVehicleInfo ) - { - pVeh->m_pVehicleInfo->EjectAll( pVeh ); + if (pVeh && pVeh->m_pVehicleInfo) { + pVeh->m_pVehicleInfo->EjectAll(pVeh); } } victim->think = G_FreeEntity; @@ -1125,15 +1028,12 @@ void Q3_RemoveEnt( gentity_t *victim ) victim->nextthink = level.time + 500; return; */ - } - else - { + } else { victim->think = G_FreeEntity; victim->nextthink = level.time + 100; } } - /* ============ Q3_Remove @@ -1143,44 +1043,34 @@ Q3_Remove Argument : const char *name ============ */ -void Q3_Remove( int entID, const char *name ) -{ +void Q3_Remove(int entID, const char *name) { gentity_t *ent = &g_entities[entID]; - gentity_t *victim = NULL; + gentity_t *victim = NULL; - if( !Q_stricmp( "self", name ) ) - { + if (!Q_stricmp("self", name)) { victim = ent; - if ( !victim ) - { - G_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + G_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else if( !Q_stricmp( "enemy", name ) ) - { + Q3_RemoveEnt(victim); + } else if (!Q_stricmp("enemy", name)) { victim = ent->enemy; - if ( !victim ) - { - G_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + if (!victim) { + G_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - Q3_RemoveEnt( victim ); - } - else - { - victim = G_Find( NULL, FOFS(targetname), (char *) name ); - if ( !victim ) - { - G_DebugPrint( WL_WARNING, "Q3_Remove: can't find %s\n", name ); + Q3_RemoveEnt(victim); + } else { + victim = G_Find(NULL, FOFS(targetname), (char *)name); + if (!victim) { + G_DebugPrint(WL_WARNING, "Q3_Remove: can't find %s\n", name); return; } - while ( victim ) - { - Q3_RemoveEnt( victim ); - victim = G_Find( victim, FOFS(targetname), (char *) name ); + while (victim) { + Q3_RemoveEnt(victim); + victim = G_Find(victim, FOFS(targetname), (char *)name); } } } @@ -1204,22 +1094,19 @@ Q3_GetFloat Argument : float *value ============ */ -int Q3_GetFloat( int entID, int type, const char *name, float *value ) -{ - gentity_t *ent = &g_entities[entID]; +int Q3_GetFloat(int entID, int type, const char *name, float *value) { + gentity_t *ent = &g_entities[entID]; int toGet = 0; - if ( !ent ) - { + if (!ent) { return 0; } - toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -1236,12 +1123,11 @@ int Q3_GetFloat( int entID, int type, const char *name, float *value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if (ent->parms == NULL) - { - G_DebugPrint( WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname ); - return 0; // would prefer qfalse, but I'm fitting in with what's here + if (ent->parms == NULL) { + G_DebugPrint(WL_ERROR, "GET_PARM: %s %s did not have any parms set!\n", ent->classname, ent->targetname); + return 0; // would prefer qfalse, but I'm fitting in with what's here } - *value = atof( ent->parms->parm[toGet - SET_PARM1] ); + *value = atof(ent->parms->parm[toGet - SET_PARM1]); break; case SET_COUNT: @@ -1256,28 +1142,25 @@ int Q3_GetFloat( int entID, int type, const char *name, float *value ) return 0; break; - case SET_XVELOCITY://## %f="0.0" # Velocity along X axis - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname ); + case SET_XVELOCITY: //## %f="0.0" # Velocity along X axis + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_XVELOCITY, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.velocity[0]; break; - case SET_YVELOCITY://## %f="0.0" # Velocity along Y axis - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname ); + case SET_YVELOCITY: //## %f="0.0" # Velocity along Y axis + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_YVELOCITY, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.velocity[1]; break; - case SET_ZVELOCITY://## %f="0.0" # Velocity along Z axis - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname ); + case SET_ZVELOCITY: //## %f="0.0" # Velocity along Z axis + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ZVELOCITY, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.velocity[2]; @@ -1287,258 +1170,255 @@ int Q3_GetFloat( int entID, int type, const char *name, float *value ) *value = ent->r.currentOrigin[2] - ent->s.origin[2]; break; - case SET_DPITCH://## %f="0.0" # Pitch for NPC to turn to + case SET_DPITCH: //## %f="0.0" # Pitch for NPC to turn to return 0; break; - case SET_DYAW://## %f="0.0" # Yaw for NPC to turn to + case SET_DYAW: //## %f="0.0" # Yaw for NPC to turn to return 0; break; - case SET_WIDTH://## %f="0.0" # Width of NPC bounding box + case SET_WIDTH: //## %f="0.0" # Width of NPC bounding box *value = ent->r.mins[0]; break; - case SET_TIMESCALE://## %f="0.0" # Speed-up slow down game (0 - 1.0) + case SET_TIMESCALE: //## %f="0.0" # Speed-up slow down game (0 - 1.0) return 0; break; - case SET_CAMERA_GROUP_Z_OFS://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_Z_OFS: //## %s="NULL" # all ents with this cameraGroup will be focused on return 0; break; - case SET_VISRANGE://## %f="0.0" # How far away NPC can see + case SET_VISRANGE: //## %f="0.0" # How far away NPC can see return 0; break; - case SET_EARSHOT://## %f="0.0" # How far an NPC can hear + case SET_EARSHOT: //## %f="0.0" # How far an NPC can hear return 0; break; - case SET_VIGILANCE://## %f="0.0" # How often to look for enemies (0 - 1.0) + case SET_VIGILANCE: //## %f="0.0" # How often to look for enemies (0 - 1.0) return 0; break; - case SET_GRAVITY://## %f="0.0" # Change this ent's gravity - 800 default + case SET_GRAVITY: //## %f="0.0" # Change this ent's gravity - 800 default *value = g_gravity.value; break; case SET_FACEEYESCLOSED: case SET_FACEEYESOPENED: - case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds - case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds - case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds - case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds - case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_FACE___ not implemented\n" ); + case SET_FACEAUX: //## %f="0.0" # Set face to Aux expression for number of seconds + case SET_FACEBLINK: //## %f="0.0" # Set face to Blink expression for number of seconds + case SET_FACEBLINKFROWN: //## %f="0.0" # Set face to Blinkfrown expression for number of seconds + case SET_FACEFROWN: //## %f="0.0" # Set face to Frown expression for number of seconds + case SET_FACENORMAL: //## %f="0.0" # Set face to Normal expression for number of seconds + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_FACE___ not implemented\n"); return 0; break; - case SET_WAIT: //## %f="0.0" # Change an entity's wait field + case SET_WAIT: //## %f="0.0" # Change an entity's wait field *value = ent->wait; break; - case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER + case SET_FOLLOWDIST: //## %f="0.0" # How far away to stay from leader in BS_FOLLOW_LEADER return 0; break; //# #sep ints - case SET_ANIM_HOLDTIME_LOWER://## %d="0" # Hold lower anim for number of milliseconds - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_LOWER: //## %d="0" # Hold lower anim for number of milliseconds + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_LOWER, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.legsTimer; break; - case SET_ANIM_HOLDTIME_UPPER://## %d="0" # Hold upper anim for number of milliseconds - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname ); + case SET_ANIM_HOLDTIME_UPPER: //## %d="0" # Hold upper anim for number of milliseconds + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_UPPER, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.torsoTimer; break; - case SET_ANIM_HOLDTIME_BOTH://## %d="0" # Hold lower and upper anims for number of milliseconds - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n" ); + case SET_ANIM_HOLDTIME_BOTH: //## %d="0" # Hold lower and upper anims for number of milliseconds + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ANIM_HOLDTIME_BOTH not implemented\n"); return 0; break; - case SET_ARMOR://## %d="0" # Change armor - if ( ent->client == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_ARMOR, %s not a client\n", ent->targetname ); + case SET_ARMOR: //## %d="0" # Change armor + if (ent->client == NULL) { + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_ARMOR, %s not a client\n", ent->targetname); return 0; } *value = ent->client->ps.stats[STAT_ARMOR]; break; - case SET_WALKSPEED://## %d="0" # Change walkSpeed + case SET_WALKSPEED: //## %d="0" # Change walkSpeed return 0; break; - case SET_RUNSPEED://## %d="0" # Change runSpeed + case SET_RUNSPEED: //## %d="0" # Change runSpeed return 0; break; - case SET_YAWSPEED://## %d="0" # Change yawSpeed + case SET_YAWSPEED: //## %d="0" # Change yawSpeed return 0; break; - case SET_AGGRESSION://## %d="0" # Change aggression 1-5 + case SET_AGGRESSION: //## %d="0" # Change aggression 1-5 return 0; break; - case SET_AIM://## %d="0" # Change aim 1-5 + case SET_AIM: //## %d="0" # Change aim 1-5 return 0; break; - case SET_FRICTION://## %d="0" # Change ent's friction - 6 default + case SET_FRICTION: //## %d="0" # Change ent's friction - 6 default return 0; break; - case SET_SHOOTDIST://## %d="0" # How far the ent can shoot - 0 uses weapon + case SET_SHOOTDIST: //## %d="0" # How far the ent can shoot - 0 uses weapon return 0; break; - case SET_HFOV://## %d="0" # Horizontal field of view + case SET_HFOV: //## %d="0" # Horizontal field of view return 0; break; - case SET_VFOV://## %d="0" # Vertical field of view + case SET_VFOV: //## %d="0" # Vertical field of view return 0; break; - case SET_DELAYSCRIPTTIME://## %d="0" # How many seconds to wait before running delayscript + case SET_DELAYSCRIPTTIME: //## %d="0" # How many seconds to wait before running delayscript return 0; break; - case SET_FORWARDMOVE://## %d="0" # NPC move forward -127(back) to 127 + case SET_FORWARDMOVE: //## %d="0" # NPC move forward -127(back) to 127 return 0; break; - case SET_RIGHTMOVE://## %d="0" # NPC move right -127(left) to 127 + case SET_RIGHTMOVE: //## %d="0" # NPC move right -127(left) to 127 return 0; break; - case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on + case SET_STARTFRAME: //## %d="0" # frame to start animation sequence on return 0; break; - case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on + case SET_ENDFRAME: //## %d="0" # frame to end animation sequence on return 0; break; - case SET_ANIMFRAME: //## %d="0" # of current frame + case SET_ANIMFRAME: //## %d="0" # of current frame return 0; break; - case SET_SHOT_SPACING://## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon + case SET_SHOT_SPACING: //## %d="1000" # Time between shots for an NPC - reset to defaults when changes weapon return 0; break; - case SET_MISSIONSTATUSTIME://## %d="0" # Amount of time until Mission Status should be shown after death + case SET_MISSIONSTATUSTIME: //## %d="0" # Amount of time until Mission Status should be shown after death return 0; break; //# #sep booleans - case SET_IGNOREPAIN://## %t="BOOL_TYPES" # Do not react to pain + case SET_IGNOREPAIN: //## %t="BOOL_TYPES" # Do not react to pain return 0; break; - case SET_IGNOREENEMIES://## %t="BOOL_TYPES" # Do not acquire enemies + case SET_IGNOREENEMIES: //## %t="BOOL_TYPES" # Do not acquire enemies return 0; break; - case SET_IGNOREALERTS://## Do not get enemy set by allies in area(ambush) + case SET_IGNOREALERTS: //## Do not get enemy set by allies in area(ambush) return 0; break; - case SET_DONTSHOOT://## %t="BOOL_TYPES" # Others won't shoot you + case SET_DONTSHOOT: //## %t="BOOL_TYPES" # Others won't shoot you return 0; break; - case SET_NOTARGET://## %t="BOOL_TYPES" # Others won't pick you as enemy - *value = (ent->flags&FL_NOTARGET); + case SET_NOTARGET: //## %t="BOOL_TYPES" # Others won't pick you as enemy + *value = (ent->flags & FL_NOTARGET); break; - case SET_DONTFIRE://## %t="BOOL_TYPES" # Don't fire your weapon + case SET_DONTFIRE: //## %t="BOOL_TYPES" # Don't fire your weapon return 0; break; - case SET_LOCKED_ENEMY://## %t="BOOL_TYPES" # Keep current enemy until dead + case SET_LOCKED_ENEMY: //## %t="BOOL_TYPES" # Keep current enemy until dead return 0; break; - case SET_CROUCHED://## %t="BOOL_TYPES" # Force NPC to crouch + case SET_CROUCHED: //## %t="BOOL_TYPES" # Force NPC to crouch return 0; break; - case SET_WALKING://## %t="BOOL_TYPES" # Force NPC to move at walkSpeed + case SET_WALKING: //## %t="BOOL_TYPES" # Force NPC to move at walkSpeed return 0; break; - case SET_RUNNING://## %t="BOOL_TYPES" # Force NPC to move at runSpeed + case SET_RUNNING: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed return 0; break; - case SET_CHASE_ENEMIES://## %t="BOOL_TYPES" # NPC will chase after enemies + case SET_CHASE_ENEMIES: //## %t="BOOL_TYPES" # NPC will chase after enemies return 0; break; - case SET_LOOK_FOR_ENEMIES://## %t="BOOL_TYPES" # NPC will be on the lookout for enemies + case SET_LOOK_FOR_ENEMIES: //## %t="BOOL_TYPES" # NPC will be on the lookout for enemies return 0; break; - case SET_FACE_MOVE_DIR://## %t="BOOL_TYPES" # NPC will face in the direction it's moving + case SET_FACE_MOVE_DIR: //## %t="BOOL_TYPES" # NPC will face in the direction it's moving return 0; break; - case SET_FORCED_MARCH://## %t="BOOL_TYPES" # Force NPC to move at runSpeed + case SET_FORCED_MARCH: //## %t="BOOL_TYPES" # Force NPC to move at runSpeed return 0; break; - case SET_UNDYING://## %t="BOOL_TYPES" # Can take damage down to 1 but not die + case SET_UNDYING: //## %t="BOOL_TYPES" # Can take damage down to 1 but not die return 0; break; - case SET_NOAVOID://## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture + case SET_NOAVOID: //## %t="BOOL_TYPES" # Will not avoid other NPCs or architecture return 0; break; - case SET_SOLID://## %t="BOOL_TYPES" # Make yourself notsolid or solid + case SET_SOLID: //## %t="BOOL_TYPES" # Make yourself notsolid or solid *value = ent->r.contents; break; - case SET_PLAYER_USABLE://## %t="BOOL_TYPES" # Can be activateby the player's "use" button - *value = (ent->r.svFlags&SVF_PLAYER_USABLE); + case SET_PLAYER_USABLE: //## %t="BOOL_TYPES" # Can be activateby the player's "use" button + *value = (ent->r.svFlags & SVF_PLAYER_USABLE); break; - case SET_LOOP_ANIM://## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence + case SET_LOOP_ANIM: //## %t="BOOL_TYPES" # For non-NPCs: loop your animation sequence return 0; break; - case SET_INTERFACE://## %t="BOOL_TYPES" # Player interface on/off - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_INTERFACE not implemented\n" ); + case SET_INTERFACE: //## %t="BOOL_TYPES" # Player interface on/off + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_INTERFACE not implemented\n"); return 0; break; - case SET_SHIELDS://## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) + case SET_SHIELDS: //## %t="BOOL_TYPES" # NPC has no shields (Borg do not adapt) return 0; break; - case SET_INVISIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible - *value = (ent->s.eFlags&EF_NODRAW); + case SET_INVISIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + *value = (ent->s.eFlags & EF_NODRAW); break; - case SET_VAMPIRE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + case SET_VAMPIRE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible return 0; break; - case SET_FORCE_INVINCIBLE://## %t="BOOL_TYPES" # Makes an NPC not solid and not visible + case SET_FORCE_INVINCIBLE: //## %t="BOOL_TYPES" # Makes an NPC not solid and not visible return 0; break; - case SET_GREET_ALLIES://## %t="BOOL_TYPES" # Makes an NPC greet teammates + case SET_GREET_ALLIES: //## %t="BOOL_TYPES" # Makes an NPC greet teammates return 0; break; - case SET_VIDEO_FADE_IN://## %t="BOOL_TYPES" # Makes video playback fade in - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_IN not implemented\n" ); + case SET_VIDEO_FADE_IN: //## %t="BOOL_TYPES" # Makes video playback fade in + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_IN not implemented\n"); return 0; break; - case SET_VIDEO_FADE_OUT://## %t="BOOL_TYPES" # Makes video playback fade out - G_DebugPrint( WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_OUT not implemented\n" ); + case SET_VIDEO_FADE_OUT: //## %t="BOOL_TYPES" # Makes video playback fade out + G_DebugPrint(WL_WARNING, "Q3_GetFloat: SET_VIDEO_FADE_OUT not implemented\n"); return 0; break; - case SET_PLAYER_LOCKED://## %t="BOOL_TYPES" # Makes it so player cannot move + case SET_PLAYER_LOCKED: //## %t="BOOL_TYPES" # Makes it so player cannot move return 0; break; - case SET_LOCK_PLAYER_WEAPONS://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + case SET_LOCK_PLAYER_WEAPONS: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons return 0; break; - case SET_NO_IMPACT_DAMAGE://## %t="BOOL_TYPES" # Makes it so player cannot switch weapons + case SET_NO_IMPACT_DAMAGE: //## %t="BOOL_TYPES" # Makes it so player cannot switch weapons return 0; break; - case SET_NO_KNOCKBACK://## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons - *value = (ent->flags&FL_NO_KNOCKBACK); + case SET_NO_KNOCKBACK: //## %t="BOOL_TYPES" # Stops this ent from taking knockback from weapons + *value = (ent->flags & FL_NO_KNOCKBACK); break; - case SET_ALT_FIRE://## %t="BOOL_TYPES" # Force NPC to use altfire when shooting + case SET_ALT_FIRE: //## %t="BOOL_TYPES" # Force NPC to use altfire when shooting return 0; break; - case SET_NO_RESPONSE://## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) + case SET_NO_RESPONSE: //## %t="BOOL_TYPES" # NPCs will do generic responses when this is on (usescripts override generic responses as well) return 0; break; - case SET_INVINCIBLE://## %t="BOOL_TYPES" # Completely unkillable - *value = (ent->flags&FL_GODMODE); + case SET_INVINCIBLE: //## %t="BOOL_TYPES" # Completely unkillable + *value = (ent->flags & FL_GODMODE); break; - case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen + case SET_MISSIONSTATUSACTIVE: //# Turns on Mission Status Screen return 0; break; - case SET_NO_COMBAT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + case SET_NO_COMBAT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on return 0; break; - case SET_NO_ALERT_TALK://## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on + case SET_NO_ALERT_TALK: //## %t="BOOL_TYPES" # NPCs will not do their combat talking noises when this is on return 0; break; - case SET_USE_CP_NEAREST://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + case SET_USE_CP_NEAREST: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player return 0; break; - case SET_DISMEMBERABLE://## %t="BOOL_TYPES" # NPC will not be affected by force powers + case SET_DISMEMBERABLE: //## %t="BOOL_TYPES" # NPC will not be affected by force powers return 0; break; case SET_NO_FORCE: @@ -1550,33 +1430,32 @@ int Q3_GetFloat( int entID, int type, const char *name, float *value ) case SET_USE_SUBTITLES: return 0; break; - case SET_NO_FALLTODEATH://## %t="BOOL_TYPES" # NPC will not be affected by force powers + case SET_NO_FALLTODEATH: //## %t="BOOL_TYPES" # NPC will not be affected by force powers return 0; break; - case SET_MORELIGHT://## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player + case SET_MORELIGHT: //## %t="BOOL_TYPES" # NPCs will use their closest combat points, not try and find ones next to the player, or flank player return 0; break; - case SET_TREASONED://## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig + case SET_TREASONED: //## %t="BOOL_TYPES" # Player has turned on his own- scripts will stop: NPCs will turn on him and level changes load the brig return 0; break; - case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate + case SET_DISABLE_SHADER_ANIM: //## %t="BOOL_TYPES" # Shaders won't animate return 0; break; - case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control + case SET_SHADER_ANIM: //## %t="BOOL_TYPES" # Shader will be under frame control return 0; break; default: - if ( trap->ICARUS_VariableDeclared( name ) != VTYPE_FLOAT ) + if (trap->ICARUS_VariableDeclared(name) != VTYPE_FLOAT) return 0; - return trap->ICARUS_GetFloatVariable( name, value ); + return trap->ICARUS_GetFloatVariable(name, value); } return 1; } - /* ============ Q3_GetVector @@ -1588,21 +1467,18 @@ Q3_GetVector Argument : vec3_t value ============ */ -int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) -{ - gentity_t *ent = &g_entities[entID]; +int Q3_GetVector(int entID, int type, const char *name, vec3_t value) { + gentity_t *ent = &g_entities[entID]; int toGet = 0; - if ( !ent ) - { + if (!ent) { return 0; } - toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well - //FIXME: I'm getting really sick of these huge switch statements! + toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well + // FIXME: I'm getting really sick of these huge switch statements! - //NOTENOTE: return true if the value was correctly obtained - switch ( toGet ) - { + // NOTENOTE: return true if the value was correctly obtained + switch (toGet) { case SET_PARM1: case SET_PARM2: case SET_PARM3: @@ -1619,9 +1495,9 @@ int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if ( sscanf( ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2] ) != 3 ) { - G_DebugPrint( WL_WARNING, "Q3_GetVector: failed sscanf on SET_PARM%d (%s)\n", toGet, name ); - VectorClear( value ); + if (sscanf(ent->parms->parm[toGet - SET_PARM1], "%f %f %f", &value[0], &value[1], &value[2]) != 3) { + G_DebugPrint(WL_WARNING, "Q3_GetVector: failed sscanf on SET_PARM%d (%s)\n", toGet, name); + VectorClear(value); } break; @@ -1633,17 +1509,17 @@ int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) VectorCopy(ent->r.currentAngles, value); break; - case SET_TELEPORT_DEST://## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear - G_DebugPrint( WL_WARNING, "Q3_GetVector: SET_TELEPORT_DEST not implemented\n" ); + case SET_TELEPORT_DEST: //## %v="0.0 0.0 0.0" # Set origin here as soon as the area is clear + G_DebugPrint(WL_WARNING, "Q3_GetVector: SET_TELEPORT_DEST not implemented\n"); return 0; break; default: - if ( trap->ICARUS_VariableDeclared( name ) != VTYPE_VECTOR ) + if (trap->ICARUS_VariableDeclared(name) != VTYPE_VECTOR) return 0; - return trap->ICARUS_GetVectorVariable( name, value ); + return trap->ICARUS_GetVectorVariable(name, value); } return 1; @@ -1660,23 +1536,20 @@ Q3_GetString Argument : char **value ============ */ -int Q3_GetString( int entID, int type, const char *name, char **value ) -{ - gentity_t *ent = &g_entities[entID]; +int Q3_GetString(int entID, int type, const char *name, char **value) { + gentity_t *ent = &g_entities[entID]; int toGet = 0; - if ( !ent ) - { + if (!ent) { return 0; } - toGet = GetIDForString( setTable, name ); //FIXME: May want to make a "getTable" as well + toGet = GetIDForString(setTable, name); // FIXME: May want to make a "getTable" as well - switch ( toGet ) - { + switch (toGet) { case SET_ANIM_BOTH: - *value = (char *) Q3_GetAnimBoth( ent ); + *value = (char *)Q3_GetAnimBoth(ent); - if ( !value || !value[0] ) + if (!value || !value[0]) return 0; break; @@ -1697,19 +1570,16 @@ int Q3_GetString( int entID, int type, const char *name, char **value ) case SET_PARM14: case SET_PARM15: case SET_PARM16: - if ( ent->parms ) - { - *value = (char *) ent->parms->parm[toGet - SET_PARM1]; - } - else - { - G_DebugPrint( WL_WARNING, "Q3_GetString: invalid ent %s has no parms!\n", ent->targetname ); + if (ent->parms) { + *value = (char *)ent->parms->parm[toGet - SET_PARM1]; + } else { + G_DebugPrint(WL_WARNING, "Q3_GetString: invalid ent %s has no parms!\n", ent->targetname); return 0; } break; case SET_TARGET: - *value = (char *) ent->target; + *value = (char *)ent->target; break; case SET_LOCATION: @@ -1717,80 +1587,81 @@ int Q3_GetString( int entID, int type, const char *name, char **value ) break; //# #sep Scripts and other file paths - case SET_SPAWNSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to BSET_SPAWN, etc + case SET_SPAWNSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when spawned //0 - do not change these, these are equal to + //BSET_SPAWN, etc *value = ent->behaviorSet[BSET_SPAWN]; break; - case SET_USESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used + case SET_USESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when used *value = ent->behaviorSet[BSET_USE]; break; - case SET_AWAKESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled + case SET_AWAKESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when startled *value = ent->behaviorSet[BSET_AWAKE]; break; - case SET_ANGERSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time + case SET_ANGERSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script run when find an enemy for the first time *value = ent->behaviorSet[BSET_ANGER]; break; - case SET_ATTACKSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot + case SET_ATTACKSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you shoot *value = ent->behaviorSet[BSET_ATTACK]; break; - case SET_VICTORYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone + case SET_VICTORYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed someone *value = ent->behaviorSet[BSET_VICTORY]; break; - case SET_LOSTENEMYSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy + case SET_LOSTENEMYSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when you can't find your enemy *value = ent->behaviorSet[BSET_LOSTENEMY]; break; - case SET_PAINSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit + case SET_PAINSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit *value = ent->behaviorSet[BSET_PAIN]; break; - case SET_FLEESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health + case SET_FLEESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when hit and low health *value = ent->behaviorSet[BSET_FLEE]; break; - case SET_DEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed + case SET_DEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when killed *value = ent->behaviorSet[BSET_DEATH]; break; - case SET_DELAYEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay + case SET_DELAYEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run after a delay *value = ent->behaviorSet[BSET_DELAYED]; break; - case SET_BLOCKEDSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate + case SET_BLOCKEDSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when blocked by teammate *value = ent->behaviorSet[BSET_BLOCKED]; break; - case SET_FFIRESCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly + case SET_FFIRESCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player has shot own team repeatedly *value = ent->behaviorSet[BSET_FFIRE]; break; - case SET_FFDEATHSCRIPT://## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate + case SET_FFDEATHSCRIPT: //## %s="NULL" !!"W:\game\base\scripts\!!#*.txt" # Script to run when player kills a teammate *value = ent->behaviorSet[BSET_FFDEATH]; break; //# #sep Standard strings - case SET_ENEMY://## %s="NULL" # Set enemy by targetname + case SET_ENEMY: //## %s="NULL" # Set enemy by targetname return 0; break; - case SET_LEADER://## %s="NULL" # Set for BS_FOLLOW_LEADER + case SET_LEADER: //## %s="NULL" # Set for BS_FOLLOW_LEADER return 0; break; - case SET_CAPTURE://## %s="NULL" # Set captureGoal by targetname + case SET_CAPTURE: //## %s="NULL" # Set captureGoal by targetname return 0; break; - case SET_TARGETNAME://## %s="NULL" # Set/change your targetname + case SET_TARGETNAME: //## %s="NULL" # Set/change your targetname *value = ent->targetname; break; - case SET_PAINTARGET://## %s="NULL" # Set/change what to use when hit + case SET_PAINTARGET: //## %s="NULL" # Set/change what to use when hit return 0; break; - case SET_CAMERA_GROUP://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP: //## %s="NULL" # all ents with this cameraGroup will be focused on return 0; break; - case SET_CAMERA_GROUP_TAG://## %s="NULL" # all ents with this cameraGroup will be focused on + case SET_CAMERA_GROUP_TAG: //## %s="NULL" # all ents with this cameraGroup will be focused on return 0; break; - case SET_LOOK_TARGET://## %s="NULL" # object for NPC to look at - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOOK_TARGET, NOT SUPPORTED IN MULTIPLAYER\n" ); + case SET_LOOK_TARGET: //## %s="NULL" # object for NPC to look at + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOOK_TARGET, NOT SUPPORTED IN MULTIPLAYER\n"); break; - case SET_TARGET2://## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo + case SET_TARGET2: //## %s="NULL" # Set/change your target2: on NPC's: this fires when they're knocked out by the red hypo return 0; break; - case SET_REMOVE_TARGET://## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState + case SET_REMOVE_TARGET: //## %s="NULL" # Target that is fired when someone completes the BS_REMOVE behaviorState return 0; break; case SET_WEAPON: @@ -1803,72 +1674,72 @@ int Q3_GetString( int entID, int type, const char *name, char **value ) case SET_MUSIC_STATE: return 0; break; - //The below cannot be gotten - case SET_NAVGOAL://## %s="NULL" # *Move to this navgoal then continue script - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_NAVGOAL not implemented\n" ); + // The below cannot be gotten + case SET_NAVGOAL: //## %s="NULL" # *Move to this navgoal then continue script + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_NAVGOAL not implemented\n"); return 0; break; - case SET_VIEWTARGET://## %s="NULL" # Set angles toward ent by targetname - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIEWTARGET not implemented\n" ); + case SET_VIEWTARGET: //## %s="NULL" # Set angles toward ent by targetname + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIEWTARGET not implemented\n"); return 0; break; - case SET_WATCHTARGET://## %s="NULL" # Set angles toward ent by targetname + case SET_WATCHTARGET: //## %s="NULL" # Set angles toward ent by targetname return 0; break; case SET_VIEWENTITY: - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIEWENTITY not implemented\n" ); + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIEWENTITY not implemented\n"); return 0; break; - case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_CAPTIONTEXTCOLOR not implemented\n" ); + case SET_CAPTIONTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_CAPTIONTEXTCOLOR not implemented\n"); return 0; break; - case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_CENTERTEXTCOLOR not implemented\n" ); + case SET_CENTERTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_CENTERTEXTCOLOR not implemented\n"); return 0; break; - case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_SCROLLTEXTCOLOR not implemented\n" ); + case SET_SCROLLTEXTCOLOR: //## %s="" # Color of text RED:WHITE:BLUE: YELLOW + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_SCROLLTEXTCOLOR not implemented\n"); return 0; break; - case SET_COPY_ORIGIN://## %s="targetname" # Copy the origin of the ent with targetname to your origin - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_COPY_ORIGIN: //## %s="targetname" # Copy the origin of the ent with targetname to your origin + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n"); return 0; break; - case SET_DEFEND_TARGET://## %s="targetname" # This NPC will attack the target NPC's enemies - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n" ); + case SET_DEFEND_TARGET: //## %s="targetname" # This NPC will attack the target NPC's enemies + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_COPY_ORIGIN not implemented\n"); return 0; break; - case SET_VIDEO_PLAY://## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_VIDEO_PLAY not implemented\n" ); + case SET_VIDEO_PLAY: //## %s="filename" !!"W:\game\base\video\!!#*.roq" # Play a Video (inGame) + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_VIDEO_PLAY not implemented\n"); return 0; break; - case SET_LOADGAME://## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOADGAME not implemented\n" ); + case SET_LOADGAME: //## %s="exitholodeck" # Load the savegame that was auto-saved when you started the holodeck + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOADGAME not implemented\n"); return 0; break; - case SET_LOCKYAW://## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_LOCKYAW not implemented\n" ); + case SET_LOCKYAW: //## %s="off" # Lock legs to a certain yaw angle (or "off" or "auto" uses current) + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_LOCKYAW not implemented\n"); return 0; break; - case SET_SCROLLTEXT: //## %s="" # key of text string to print - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_SCROLLTEXT not implemented\n" ); + case SET_SCROLLTEXT: //## %s="" # key of text string to print + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_SCROLLTEXT not implemented\n"); return 0; break; - case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame - G_DebugPrint( WL_WARNING, "Q3_GetString: SET_LCARSTEXT not implemented\n" ); + case SET_LCARSTEXT: //## %s="" # key of text string to print in LCARS frame + G_DebugPrint(WL_WARNING, "Q3_GetString: SET_LCARSTEXT not implemented\n"); return 0; break; - case SET_FULLNAME://## %s="NULL" # Set/change your targetname + case SET_FULLNAME: //## %s="NULL" # Set/change your targetname *value = ent->fullName; break; default: - if ( trap->ICARUS_VariableDeclared( name ) != VTYPE_STRING ) + if (trap->ICARUS_VariableDeclared(name) != VTYPE_STRING) return 0; - return trap->ICARUS_GetStringVariable( name, (const char *) *value ); + return trap->ICARUS_GetStringVariable(name, (const char *)*value); } return 1; @@ -1882,27 +1753,22 @@ MoveOwner Argument : sharedEntity_t *self ============ */ -qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ); -void MoveOwner( gentity_t *self ) -{ +qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest); +void MoveOwner(gentity_t *self) { gentity_t *owner = &g_entities[self->r.ownerNum]; self->nextthink = level.time + FRAMETIME; self->think = G_FreeEntity; - if ( !owner || !owner->inuse ) - { + if (!owner || !owner->inuse) { return; } - if ( SpotWouldTelefrag2( owner, self->r.currentOrigin ) ) - { + if (SpotWouldTelefrag2(owner, self->r.currentOrigin)) { self->think = MoveOwner; - } - else - { - G_SetOrigin( owner, self->r.currentOrigin ); - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)owner, TID_MOVE_NAV ); + } else { + G_SetOrigin(owner, self->r.currentOrigin); + trap->ICARUS_TaskIDComplete((sharedEntity_t *)owner, TID_MOVE_NAV); } } @@ -1913,27 +1779,22 @@ Q3_SetTeleportDest Copies passed origin to ent running script once there is nothing there blocking the spot ============= */ -static qboolean Q3_SetTeleportDest( int entID, vec3_t org ) -{ - gentity_t *teleEnt = &g_entities[entID]; +static qboolean Q3_SetTeleportDest(int entID, vec3_t org) { + gentity_t *teleEnt = &g_entities[entID]; - if ( teleEnt ) - { - if ( SpotWouldTelefrag2( teleEnt, org ) ) - { + if (teleEnt) { + if (SpotWouldTelefrag2(teleEnt, org)) { gentity_t *teleporter = G_Spawn(); - G_SetOrigin( teleporter, org ); + G_SetOrigin(teleporter, org); teleporter->r.ownerNum = teleEnt->s.number; teleporter->think = MoveOwner; teleporter->nextthink = level.time + FRAMETIME; return qfalse; - } - else - { - G_SetOrigin( teleEnt, org ); + } else { + G_SetOrigin(teleEnt, org); } } @@ -1947,38 +1808,33 @@ Q3_SetOrigin Sets the origin of an entity directly ============= */ -static void Q3_SetOrigin( int entID, vec3_t origin ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOrigin(int entID, vec3_t origin) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetOrigin: bad ent %d\n", entID); return; } - trap->UnlinkEntity ((sharedEntity_t *)ent); + trap->UnlinkEntity((sharedEntity_t *)ent); - if(ent->client) - { + if (ent->client) { VectorCopy(origin, ent->client->ps.origin); VectorCopy(origin, ent->r.currentOrigin); ent->client->ps.origin[2] += 1; - VectorClear (ent->client->ps.velocity); - ent->client->ps.pm_time = 160; // hold time + VectorClear(ent->client->ps.velocity); + ent->client->ps.pm_time = 160; // hold time ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; ent->client->ps.eFlags ^= EF_TELEPORT_BIT; -// G_KillBox (ent); - } - else - { - G_SetOrigin( ent, origin ); + // G_KillBox (ent); + } else { + G_SetOrigin(ent, origin); } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -1988,18 +1844,14 @@ Q3_SetCopyOrigin Copies origin of found ent into ent running script =============` */ -static void Q3_SetCopyOrigin( int entID, const char *name ) -{ - gentity_t *found = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCopyOrigin(int entID, const char *name) { + gentity_t *found = G_Find(NULL, FOFS(targetname), (char *)name); - if(found) - { - Q3_SetOrigin( entID, found->r.currentOrigin ); - SetClientViewAngle( &g_entities[entID], found->s.angles ); - } - else - { - G_DebugPrint( WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); + if (found) { + Q3_SetOrigin(entID, found->r.currentOrigin); + SetClientViewAngle(&g_entities[entID], found->s.angles); + } else { + G_DebugPrint(WL_WARNING, "Q3_SetCopyOrigin: ent %s not found!\n", name); } } @@ -2010,23 +1862,20 @@ Q3_SetVelocity Set the velocity of an entity directly ============= */ -static void Q3_SetVelocity( int entID, int axis, float speed ) -{ - gentity_t *found = &g_entities[entID]; - //FIXME: Not supported - if(!found) - { - G_DebugPrint( WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); +static void Q3_SetVelocity(int entID, int axis, float speed) { + gentity_t *found = &g_entities[entID]; + // FIXME: Not supported + if (!found) { + G_DebugPrint(WL_WARNING, "Q3_SetVelocity invalid entID %d\n", entID); return; } - if(!found->client) - { - G_DebugPrint( WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); + if (!found->client) { + G_DebugPrint(WL_WARNING, "Q3_SetVelocity: not a client %d\n", entID); return; } - //FIXME: add or set? + // FIXME: add or set? found->client->ps.velocity[axis] += speed; found->client->ps.pm_time = 500; @@ -2040,26 +1889,20 @@ Q3_SetAngles Sets the angles of an entity directly ============= */ -static void Q3_SetAngles( int entID, vec3_t angles ) -{ - gentity_t *ent = &g_entities[entID]; - +static void Q3_SetAngles(int entID, vec3_t angles) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetAngles: bad ent %d\n", entID); return; } - if (ent->client) - { - SetClientViewAngle( ent, angles ); - } - else - { - VectorCopy( angles, ent->s.angles ); + if (ent->client) { + SetClientViewAngle(ent, angles); + } else { + VectorCopy(angles, ent->s.angles); } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -2069,95 +1912,82 @@ Q3_Lerp2Origin Lerps the origin to the destination value ============= */ -void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ) -{ - gentity_t *ent = &g_entities[entID]; +void Q3_Lerp2Origin(int taskID, int entID, vec3_t origin, float duration) { + gentity_t *ent = &g_entities[entID]; moverState_t moverState; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_Lerp2Origin: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_Lerp2Origin: ent %d is NOT a mover!\n", entID); return; } - if ( ent->s.eType != ET_MOVER ) - { + if (ent->s.eType != ET_MOVER) { ent->s.eType = ET_MOVER; } moverState = ent->moverState; - if ( moverState == MOVER_POS1 || moverState == MOVER_2TO1 ) - { - VectorCopy( ent->r.currentOrigin, ent->pos1 ); - VectorCopy( origin, ent->pos2 ); + if (moverState == MOVER_POS1 || moverState == MOVER_2TO1) { + VectorCopy(ent->r.currentOrigin, ent->pos1); + VectorCopy(origin, ent->pos2); moverState = MOVER_1TO2; - } - else if ( moverState == MOVER_POS2 || moverState == MOVER_1TO2 ) - { - VectorCopy( ent->r.currentOrigin, ent->pos2 ); - VectorCopy( origin, ent->pos1 ); + } else if (moverState == MOVER_POS2 || moverState == MOVER_1TO2) { + VectorCopy(ent->r.currentOrigin, ent->pos2); + VectorCopy(origin, ent->pos1); moverState = MOVER_2TO1; } - InitMoverTrData( ent ); //FIXME: This will probably break normal things that are being moved... + InitMoverTrData(ent); // FIXME: This will probably break normal things that are being moved... ent->s.pos.trDuration = duration; // start it going - MatchTeam( ent, moverState, level.time ); - //SetMoverState( ent, moverState, level.time ); + MatchTeam(ent, moverState, level.time); + // SetMoverState( ent, moverState, level.time ); ent->reached = moverCallback; - if ( ent->damage ) - { + if (ent->damage) { ent->blocked = Blocked_Mover; } - if ( taskID != -1 ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + if (taskID != -1) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); } // starting sound - G_PlayDoorLoopSound( ent );//start looping sound - G_PlayDoorSound( ent, BMS_START ); //play start sound + G_PlayDoorLoopSound(ent); // start looping sound + G_PlayDoorSound(ent, BMS_START); // play start sound - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } -static void Q3_SetOriginOffset( int entID, int axis, float offset ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetOriginOffset(int entID, int axis, float offset) { + gentity_t *ent = &g_entities[entID]; vec3_t origin; float duration; - if(!ent) - { - G_DebugPrint( WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetOriginOffset: invalid entID %d\n", entID); return; } - if ( ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0 ) - { - G_DebugPrint( WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); + if (ent->client || Q_stricmp(ent->classname, "target_scriptrunner") == 0) { + G_DebugPrint(WL_ERROR, "Q3_SetOriginOffset: ent %d is NOT a mover!\n", entID); return; } - VectorCopy( ent->s.origin, origin ); + VectorCopy(ent->s.origin, origin); origin[axis] += offset; duration = 0; - if ( ent->speed ) - { - duration = fabs(offset)/fabs(ent->speed)*1000.0f; + if (ent->speed) { + duration = fabs(offset) / fabs(ent->speed) * 1000.0f; } - Q3_Lerp2Origin( -1, entID, origin, duration ); + Q3_Lerp2Origin(-1, entID, origin, duration); } /* @@ -2167,34 +1997,25 @@ Q3_SetEnemy Sets the enemy of an entity ============= */ -static void Q3_SetEnemy( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEnemy(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetEnemy: invalid entID %d\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { - if(ent->NPC) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { + if (ent->NPC) { G_ClearEnemy(ent); - } - else - { + } else { ent->enemy = NULL; } - } - else - { - gentity_t *enemy = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *enemy = G_Find(NULL, FOFS(targetname), (char *)name); - if(enemy == NULL) - { - G_DebugPrint( WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name ); + if (enemy == NULL) { + G_DebugPrint(WL_ERROR, "Q3_SetEnemy: no such enemy: '%s'\n", name); return; } /*else if(enemy->health <= 0) @@ -2202,22 +2023,17 @@ static void Q3_SetEnemy( int entID, const char *name ) //G_DebugPrint( WL_ERROR, "Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; }*/ - else - { - if(ent->NPC) - { - G_SetEnemy( ent, enemy ); + else { + if (ent->NPC) { + G_SetEnemy(ent, enemy); ent->cantHitEnemyCounter = 0; - } - else - { + } else { G_SetEnemy(ent, enemy); } } } } - /* ============= Q3_SetLeader @@ -2225,42 +2041,31 @@ Q3_SetLeader Sets the leader of an NPC ============= */ -static void Q3_SetLeader( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLeader(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetLeader: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "Q3_SetLeader: ent %d is NOT a player or NPC!\n", entID); return; } - if( !Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) - { + if (!Q_stricmp("NONE", name) || !Q_stricmp("NULL", name)) { ent->client->leader = NULL; - } - else - { - gentity_t *leader = G_Find( NULL, FOFS(targetname), (char *) name); + } else { + gentity_t *leader = G_Find(NULL, FOFS(targetname), (char *)name); - if(leader == NULL) - { - //G_DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); + if (leader == NULL) { + // G_DebugPrint( WL_ERROR,"Q3_SetEnemy: unable to locate enemy: '%s'\n", name ); return; - } - else if(leader->health <= 0) - { - //G_DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); + } else if (leader->health <= 0) { + // G_DebugPrint( WL_ERROR,"Q3_SetEnemy: ERROR - desired enemy has health %d\n", enemy->health ); return; - } - else - { + } else { ent->client->leader = leader; } } @@ -2273,68 +2078,53 @@ Q3_SetNavGoal Sets the navigational goal of an entity ============= */ -static qboolean Q3_SetNavGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[ entID ]; - vec3_t goalPos; +static qboolean Q3_SetNavGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + vec3_t goalPos; - if ( !ent->health ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, ent->script_targetname ); + if (!ent->health) { + G_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a corpse! \"%s\"\n", name, ent->script_targetname); return qfalse; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a non-NPC: \"%s\"\n", name, ent->script_targetname); return qfalse; } - if ( !ent->NPC->tempGoal ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal) { + G_DebugPrint(WL_ERROR, "Q3_SetNavGoal: tried to set a navgoal (\"%s\") on a dead NPC: \"%s\"\n", name, ent->script_targetname); return qfalse; } - if ( !ent->NPC->tempGoal->inuse ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname ); + if (!ent->NPC->tempGoal->inuse) { + G_DebugPrint(WL_ERROR, "Q3_SetNavGoal: NPC's (\"%s\") navgoal is freed: \"%s\"\n", name, ent->script_targetname); return qfalse; } - if( Q_stricmp( "null", name) == 0 - || Q_stricmp( "NULL", name) == 0 ) - { + if (Q_stricmp("null", name) == 0 || Q_stricmp("NULL", name) == 0) { ent->NPC->goalEntity = NULL; - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)ent, TID_MOVE_NAV ); + trap->ICARUS_TaskIDComplete((sharedEntity_t *)ent, TID_MOVE_NAV); return qfalse; - } - else - { - //Get the position of the goal - if ( TAG_GetOrigin2( NULL, name, goalPos ) == qfalse ) - { - gentity_t *targ = G_Find(NULL, FOFS(targetname), (char*)name); - if ( !targ ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name ); + } else { + // Get the position of the goal + if (TAG_GetOrigin2(NULL, name, goalPos) == qfalse) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), (char *)name); + if (!targ) { + G_DebugPrint(WL_ERROR, "Q3_SetNavGoal: can't find NAVGOAL \"%s\"\n", name); return qfalse; - } - else - { + } else { ent->NPC->goalEntity = targ; - ent->NPC->goalRadius = sqrt(ent->r.maxs[0]+ent->r.maxs[0]) + sqrt(targ->r.maxs[0]+targ->r.maxs[0]); + ent->NPC->goalRadius = sqrt(ent->r.maxs[0] + ent->r.maxs[0]) + sqrt(targ->r.maxs[0] + targ->r.maxs[0]); ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; } - } - else - { - int goalRadius = TAG_GetRadius( NULL, name ); - NPC_SetMoveGoal( ent, goalPos, goalRadius, qtrue, -1, NULL ); - //We know we want to clear the lastWaypoint here + } else { + int goalRadius = TAG_GetRadius(NULL, name); + NPC_SetMoveGoal(ent, goalPos, goalRadius, qtrue, -1, NULL); + // We know we want to clear the lastWaypoint here ent->NPC->goalEntity->lastWaypoint = WAYPOINT_NONE; ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; - #ifdef _DEBUG - //this is *only* for debugging navigation - ent->NPC->tempGoal->target = G_NewString( name ); - #endif// _DEBUG - return qtrue; +#ifdef _DEBUG + // this is *only* for debugging navigation + ent->NPC->tempGoal->target = G_NewString(name); +#endif // _DEBUG + return qtrue; } } return qfalse; @@ -2348,23 +2138,20 @@ SetLowerAnim Argument : int animID ============ */ -static void SetLowerAnim( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetLowerAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "SetLowerAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - G_SetAnim(ent,NULL,SETANIM_LEGS,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE,0); + G_SetAnim(ent, NULL, SETANIM_LEGS, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE, 0); } /* @@ -2376,23 +2163,20 @@ SetUpperAnim Argument : int animID ============ */ -static void SetUpperAnim ( int entID, int animID) -{ - gentity_t *ent = &g_entities[entID]; +static void SetUpperAnim(int entID, int animID) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "SetUpperAnim: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "SetLowerAnim: ent %d is NOT a player or NPC!\n", entID); return; } - G_SetAnim(ent,NULL,SETANIM_TORSO,animID,SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE,0); + G_SetAnim(ent, NULL, SETANIM_TORSO, animID, SETANIM_FLAG_RESTART | SETANIM_FLAG_HOLD | SETANIM_FLAG_OVERRIDE, 0); } /* @@ -2402,15 +2186,13 @@ Q3_SetAnimUpper Sets the upper animation of an entity ============= */ -static qboolean Q3_SetAnimUpper( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimUpper(int entID, const char *anim_name) { + int animID = 0; - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + G_DebugPrint(WL_WARNING, "Q3_SetAnimUpper: unknown animation sequence '%s'\n", anim_name); return qfalse; } @@ -2421,7 +2203,7 @@ static qboolean Q3_SetAnimUpper( int entID, const char *anim_name ) } */ - SetUpperAnim( entID, animID ); + SetUpperAnim(entID, animID); return qtrue; } @@ -2432,17 +2214,15 @@ Q3_SetAnimLower Sets the lower animation of an entity ============= */ -static qboolean Q3_SetAnimLower( int entID, const char *anim_name ) -{ - int animID = 0; +static qboolean Q3_SetAnimLower(int entID, const char *anim_name) { + int animID = 0; - //FIXME: Setting duck anim does not actually duck! + // FIXME: Setting duck anim does not actually duck! - animID = GetIDForString( animTable, anim_name ); + animID = GetIDForString(animTable, anim_name); - if( animID == -1 ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name ); + if (animID == -1) { + G_DebugPrint(WL_WARNING, "Q3_SetAnimLower: unknown animation sequence '%s'\n", anim_name); return qfalse; } @@ -2453,7 +2233,7 @@ static qboolean Q3_SetAnimLower( int entID, const char *anim_name ) } */ - SetLowerAnim( entID, animID ); + SetLowerAnim(entID, animID); return qtrue; } @@ -2467,9 +2247,8 @@ Q3_SetAnimHoldTime Argument : qboolean lower ============ */ -static void Q3_SetAnimHoldTime( int entID, int int_data, qboolean lower ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetAnimHoldTime is not currently supported in MP\n"); +static void Q3_SetAnimHoldTime(int entID, int int_data, qboolean lower) { + G_DebugPrint(WL_WARNING, "Q3_SetAnimHoldTime is not currently supported in MP\n"); /* gentity_t *ent = &g_entities[entID]; @@ -2505,54 +2284,45 @@ Q3_SetHealth Argument : int data ============ */ -static void Q3_SetHealth( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHealth(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetHealth: invalid entID %d\n", entID); return; } - if ( data < 0 ) - { + if (data < 0) { data = 0; } ent->health = data; - if(!ent->client) - { + if (!ent->client) { return; } ent->client->ps.stats[STAT_HEALTH] = data; - if ( ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->client->ps.stats[STAT_HEALTH] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_HEALTH] = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if ( data == 0 ) - { + if (data == 0) { ent->health = 1; - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) - { //this would be silly + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { // this would be silly return; } - if ( ent->client->tempSpectate >= level.time ) - { //this would also be silly + if (ent->client->tempSpectate >= level.time) { // this would also be silly return; } ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = -999; - player_die (ent, ent, ent, 100000, MOD_FALLING); + player_die(ent, ent, ent, 100000, MOD_FALLING); } } - /* ============ Q3_SetArmor @@ -2562,29 +2332,24 @@ Q3_SetArmor Argument : int data ============ */ -static void Q3_SetArmor( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetArmor(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetArmor: invalid entID %d\n", entID); return; } - if(!ent->client) - { + if (!ent->client) { return; } ent->client->ps.stats[STAT_ARMOR] = data; - if ( ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH] ) - { + if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; } } - /* ============ Q3_SetBState @@ -2596,41 +2361,32 @@ FIXME: this should be a general NPC wrapper function that is called ANY time a bState is changed... ============ */ -static qboolean Q3_SetBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetBState: invalid entID %d\n", entID); return qtrue; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { - if ( bSID == BS_SEARCH || bSID == BS_WANDER ) - { - //FIXME: Reimplement + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { + if (bSID == BS_SEARCH || bSID == BS_WANDER) { + // FIXME: Reimplement - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); - } - else - { - ent->waypoint = NAV_FindClosestWaypointForEnt( ent, WAYPOINT_NONE ); + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); + } else { + ent->waypoint = NAV_FindClosestWaypointForEnt(ent, WAYPOINT_NONE); - if( ent->waypoint != WAYPOINT_NONE ) - { - NPC_BSSearchStart( ent->waypoint, bSID ); + if (ent->waypoint != WAYPOINT_NONE) { + NPC_BSSearchStart(ent->waypoint, bSID); } /*else if( ent->lastWaypoint >=0 && ent->lastWaypoint < num_waypoints ) { @@ -2640,79 +2396,69 @@ static qboolean Q3_SetBState( int entID, const char *bs_name ) { NPC_BSSearchStart( ent->lastValidWaypoint, bSID ); }*/ - else - { - G_DebugPrint( WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname ); + else { + G_DebugPrint(WL_ERROR, "Q3_SetBState: '%s' is not in a valid waypoint to search from!\n", ent->targetname); return qtrue; } } } - - ent->NPC->tempBehavior = BS_DEFAULT;//need to clear any temp behaviour - if ( ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP ) - {//need to rise up out of the floor after noclipping + ent->NPC->tempBehavior = BS_DEFAULT; // need to clear any temp behaviour + if (ent->NPC->behaviorState == BS_NOCLIP && bSID != BS_NOCLIP) { // need to rise up out of the floor after noclipping ent->r.currentOrigin[2] += 0.125; - G_SetOrigin( ent, ent->r.currentOrigin ); + G_SetOrigin(ent, ent->r.currentOrigin); } ent->NPC->behaviorState = bSID; - if ( bSID == BS_DEFAULT ) - { + if (bSID == BS_DEFAULT) { ent->NPC->defaultBehavior = bSID; } } ent->NPC->aiFlags &= ~NPCAI_TOUCHED_GOAL; -// if ( bSID == BS_FLY ) -// {//FIXME: need a set bState wrapper -// ent->client->moveType = MT_FLYSWIM; -// } -// else + // if ( bSID == BS_FLY ) + // {//FIXME: need a set bState wrapper + // ent->client->moveType = MT_FLYSWIM; + // } + // else { - //FIXME: these are presumptions! - //Q3_SetGravity( entID, g_gravity->value ); - //ent->client->moveType = MT_RUNJUMP; + // FIXME: these are presumptions! + // Q3_SetGravity( entID, g_gravity->value ); + // ent->client->moveType = MT_RUNJUMP; } - if ( bSID == BS_NOCLIP ) - { + if (bSID == BS_NOCLIP) { ent->client->noclip = qtrue; - } - else - { + } else { ent->client->noclip = qfalse; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -// if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) - if ( bSID == BS_ADVANCE_FIGHT ) - { - return qfalse;//need to wait for task complete message + // if ( bSID == BS_SNIPER || bSID == BS_ADVANCE_FIGHT ) + if (bSID == BS_ADVANCE_FIGHT) { + return qfalse; // need to wait for task complete message } -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - if ( bSID == BS_JUMP ) - { + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + if (bSID == BS_JUMP) { ent->NPC->jumpState = JS_FACING; } - return qtrue;//ok to complete + return qtrue; // ok to complete } - /* ============ Q3_SetTempBState @@ -2722,47 +2468,42 @@ Q3_SetTempBState Argument : const char *bs_name ============ */ -static qboolean Q3_SetTempBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static qboolean Q3_SetTempBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetTempBState: invalid entID %d\n", entID); return qtrue; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname ); - return qtrue;//ok to complete + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetTempBState: '%s' is not an NPC\n", ent->targetname); + return qtrue; // ok to complete } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->tempBehavior = bSID; } -/* - if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) - { - ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds - return qfalse;//need to wait for task complete message - } -*/ + /* + if ( bSID == BS_FACE || bSID == BS_POINT_AND_SHOOT || bSID == BS_FACE_ENEMY ) + { + ent->NPC->aimTime = level.time + 5 * 1000;//try for 5 seconds + return qfalse;//need to wait for task complete message + } + */ -/* - if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) - {//Let them shoot right NOW - ent->NPC->shotTime = ent->attackDebounceTime = level.time; - } -*/ - return qtrue;//ok to complete + /* + if ( bSID == BS_SHOOT || bSID == BS_POINT_AND_SHOOT ) + {//Let them shoot right NOW + ent->NPC->shotTime = ent->attackDebounceTime = level.time; + } + */ + return qtrue; // ok to complete } - /* ============ Q3_SetDefaultBState @@ -2772,31 +2513,26 @@ Q3_SetDefaultBState Argument : const char *bs_name ============ */ -static void Q3_SetDefaultBState( int entID, const char *bs_name ) -{ - gentity_t *ent = &g_entities[entID]; - bState_t bSID; +static void Q3_SetDefaultBState(int entID, const char *bs_name) { + gentity_t *ent = &g_entities[entID]; + bState_t bSID; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDefaultBState: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetDefaultBState: '%s' is not an NPC\n", ent->targetname); return; } - bSID = (bState_t)(GetIDForString( BSTable, bs_name )); - if ( bSID != (bState_t)-1 ) - { + bSID = (bState_t)(GetIDForString(BSTable, bs_name)); + if (bSID != (bState_t)-1) { ent->NPC->defaultBehavior = bSID; } } - /* ============ Q3_SetDPitch @@ -2806,42 +2542,34 @@ Q3_SetDPitch Argument : float data ============ */ -static void Q3_SetDPitch( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDPitch(int entID, float data) { + gentity_t *ent = &g_entities[entID]; int pitchMin; int pitchMax; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDPitch: invalid entID %d\n", entID); return; } - if ( !ent->NPC || !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC || !ent->client) { + G_DebugPrint(WL_ERROR, "Q3_SetDPitch: '%s' is not an NPC\n", ent->targetname); return; } pitchMin = -ent->client->renderInfo.headPitchRangeUp + 1; pitchMax = ent->client->renderInfo.headPitchRangeDown - 1; - //clamp angle to -180 -> 180 - data = AngleNormalize180( data ); + // clamp angle to -180 -> 180 + data = AngleNormalize180(data); - //Clamp it to my valid range - if ( data < -1 ) - { - if ( data < pitchMin ) - { + // Clamp it to my valid range + if (data < -1) { + if (data < pitchMin) { data = pitchMin; } - } - else if ( data > 1 ) - { - if ( data > pitchMax ) - { + } else if (data > 1) { + if (data > pitchMax) { data = pitchMax; } } @@ -2849,7 +2577,6 @@ static void Q3_SetDPitch( int entID, float data ) ent->NPC->lockedDesiredPitch = ent->NPC->desiredPitch = data; } - /* ============ Q3_SetDYaw @@ -2859,33 +2586,26 @@ Q3_SetDYaw Argument : float data ============ */ -static void Q3_SetDYaw( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDYaw(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDYaw: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetDYaw: '%s' is not an NPC\n", ent->targetname); return; } - if(!ent->enemy) - {//don't mess with this if they're aiming at someone + if (!ent->enemy) { // don't mess with this if they're aiming at someone ent->NPC->lockedDesiredYaw = ent->NPC->desiredYaw = ent->s.angles[1] = data; - } - else - { - G_DebugPrint( WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname ); + } else { + G_DebugPrint(WL_WARNING, "Could not set DYAW: '%s' has an enemy (%s)!\n", ent->targetname, ent->enemy->targetname); } } - /* ============ Q3_SetShootDist @@ -2895,26 +2615,22 @@ Q3_SetShootDist Argument : float data ============ */ -static void Q3_SetShootDist( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetShootDist(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetShootDist: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetShootDist: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.shootDistance = data; } - /* ============ Q3_SetVisrange @@ -2924,26 +2640,22 @@ Q3_SetVisrange Argument : float data ============ */ -static void Q3_SetVisrange( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVisrange(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetVisrange: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetVisrange: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.visrange = data; } - /* ============ Q3_SetEarshot @@ -2953,26 +2665,22 @@ Q3_SetEarshot Argument : float data ============ */ -static void Q3_SetEarshot( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetEarshot(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetEarshot: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetEarshot: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.earshot = data; } - /* ============ Q3_SetVigilance @@ -2982,26 +2690,22 @@ Q3_SetVigilance Argument : float data ============ */ -static void Q3_SetVigilance( int entID, float data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVigilance(int entID, float data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetVigilance: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetVigilance: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vigilance = data; } - /* ============ Q3_SetVFOV @@ -3011,26 +2715,22 @@ Q3_SetVFOV Argument : int data ============ */ -static void Q3_SetVFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetVFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetVFOV: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetVFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.vfov = data; } - /* ============ Q3_SetHFOV @@ -3040,26 +2740,22 @@ Q3_SetHFOV Argument : int data ============ */ -static void Q3_SetHFOV( int entID, int data ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetHFOV(int entID, int data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetHFOV: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetHFOV: '%s' is not an NPC\n", ent->targetname); return; } ent->NPC->stats.hfov = data; } - /* ============ Q3_SetWidth @@ -3069,9 +2765,8 @@ Q3_SetWidth Argument : float data ============ */ -static void Q3_SetWidth( int entID, int data ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetWidth: NOT SUPPORTED IN MP\n"); +static void Q3_SetWidth(int entID, int data) { + G_DebugPrint(WL_WARNING, "Q3_SetWidth: NOT SUPPORTED IN MP\n"); return; } @@ -3084,11 +2779,7 @@ Q3_SetTimeScale Argument : const char *data ============ */ -static void Q3_SetTimeScale( int entID, const char *data ) -{ - trap->Cvar_Set("timescale", data); -} - +static void Q3_SetTimeScale(int entID, const char *data) { trap->Cvar_Set("timescale", data); } /* ============ @@ -3099,30 +2790,23 @@ Q3_SetInvisible Argument : qboolean invisible ============ */ -static void Q3_SetInvisible( int entID, qboolean invisible ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetInvisible(int entID, qboolean invisible) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetInvisible: invalid entID %d\n", entID); return; } - if ( invisible ) - { + if (invisible) { self->s.eFlags |= EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags |= EF_NODRAW; } self->r.contents = 0; - } - else - { + } else { self->s.eFlags &= ~EF_NODRAW; - if ( self->client ) - { + if (self->client) { self->client->ps.eFlags &= ~EF_NODRAW; } } @@ -3137,9 +2821,8 @@ Q3_SetVampire Argument : qboolean vampire ============ */ -static void Q3_SetVampire( int entID, qboolean vampire ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetVampire: NOT SUPPORTED IN MP\n"); +static void Q3_SetVampire(int entID, qboolean vampire) { + G_DebugPrint(WL_WARNING, "Q3_SetVampire: NOT SUPPORTED IN MP\n"); return; } /* @@ -3151,33 +2834,26 @@ Q3_SetGreetAllies Argument : qboolean greet ============ */ -static void Q3_SetGreetAllies( int entID, qboolean greet ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGreetAllies(int entID, qboolean greet) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetGreetAllies: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_WARNING, "Q3_SetGreetAllies: ent %s is not an NPC!\n", self->targetname); return; } - if ( greet ) - { + if (greet) { self->NPC->aiFlags |= NPCAI_GREET_ALLIES; - } - else - { + } else { self->NPC->aiFlags &= ~NPCAI_GREET_ALLIES; } } - /* ============ Q3_SetViewTarget @@ -3187,54 +2863,46 @@ Q3_SetViewTarget Argument : const char *name ============ */ -static void Q3_SetViewTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *viewtarget = G_Find( NULL, FOFS(targetname), (char *) name); - vec3_t viewspot, selfspot, viewvec, viewangles; +static void Q3_SetViewTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *viewtarget = G_Find(NULL, FOFS(targetname), (char *)name); + vec3_t viewspot, selfspot, viewvec, viewangles; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetViewTarget: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname ); + if (!self->client) { + G_DebugPrint(WL_ERROR, "Q3_SetViewTarget: '%s' is not a player/NPC!\n", self->targetname); return; } - //FIXME: Exception handle here - if (viewtarget == NULL) - { - G_DebugPrint( WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name ); + // FIXME: Exception handle here + if (viewtarget == NULL) { + G_DebugPrint(WL_WARNING, "Q3_SetViewTarget: can't find ViewTarget: '%s'\n", name); return; } - //FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves - //around for a script-specified length of time...? - VectorCopy ( self->s.origin, selfspot ); + // FIXME: should we set behavior to BS_FACE and keep facing this ent as it moves + // around for a script-specified length of time...? + VectorCopy(self->s.origin, selfspot); selfspot[2] += self->client->ps.viewheight; - if ( viewtarget->client ) - { - VectorCopy ( viewtarget->client->renderInfo.eyePoint, viewspot ); - } - else - { - VectorCopy ( viewtarget->s.origin, viewspot ); + if (viewtarget->client) { + VectorCopy(viewtarget->client->renderInfo.eyePoint, viewspot); + } else { + VectorCopy(viewtarget->s.origin, viewspot); } - VectorSubtract( viewspot, selfspot, viewvec ); + VectorSubtract(viewspot, selfspot, viewvec); - vectoangles( viewvec, viewangles ); + vectoangles(viewvec, viewangles); - Q3_SetDYaw( entID, viewangles[YAW] ); - Q3_SetDPitch( entID, viewangles[PITCH] ); + Q3_SetDYaw(entID, viewangles[YAW]); + Q3_SetDPitch(entID, viewangles[PITCH]); } - /* ============ Q3_SetWatchTarget @@ -3244,83 +2912,68 @@ Q3_SetWatchTarget Argument : const char *name ============ */ -static void Q3_SetWatchTarget (int entID, const char *name) -{ - gentity_t *self = &g_entities[entID]; - gentity_t *watchTarget = NULL; +static void Q3_SetWatchTarget(int entID, const char *name) { + gentity_t *self = &g_entities[entID]; + gentity_t *watchTarget = NULL; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetWatchTarget: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetWatchTarget: '%s' is not an NPC!\n", self->targetname); return; } - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name ) == 0 || ( self->targetname && (Q_stricmp( self->targetname, name ) == 0) ) ) - {//clearing watchTarget + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0 || (self->targetname && (Q_stricmp(self->targetname, name) == 0))) { // clearing + // watchTarget self->NPC->watchTarget = NULL; } - watchTarget = G_Find( NULL, FOFS(targetname), (char *) name); - if ( watchTarget == NULL ) - { - G_DebugPrint( WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name ); + watchTarget = G_Find(NULL, FOFS(targetname), (char *)name); + if (watchTarget == NULL) { + G_DebugPrint(WL_WARNING, "Q3_SetWatchTarget: can't find WatchTarget: '%s'\n", name); return; } self->NPC->watchTarget = watchTarget; } -void Q3_SetLoopSound(int entID, const char *name) -{ - sfxHandle_t index; - gentity_t *self = &g_entities[entID]; +void Q3_SetLoopSound(int entID, const char *name) { + sfxHandle_t index; + gentity_t *self = &g_entities[entID]; - if ( Q_stricmp( "NULL", name ) == 0 || Q_stricmp( "NONE", name )==0) - { + if (Q_stricmp("NULL", name) == 0 || Q_stricmp("NONE", name) == 0) { self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; return; } - index = G_SoundIndex( (char*)name ); + index = G_SoundIndex((char *)name); - if (index) - { + if (index) { self->s.loopSound = index; self->s.loopIsSoundset = qfalse; - } - else - { - G_DebugPrint( WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name ); + } else { + G_DebugPrint(WL_WARNING, "Q3_SetLoopSound: can't find sound file: '%s'\n", name); } } -void Q3_SetICARUSFreeze( int entID, const char *name, qboolean freeze ) -{ - gentity_t *self = G_Find( NULL, FOFS(targetname), name ); - if ( !self ) - {//hmm, targetname failed, try script_targetname? - self = G_Find( NULL, FOFS(script_targetname), name ); +void Q3_SetICARUSFreeze(int entID, const char *name, qboolean freeze) { + gentity_t *self = G_Find(NULL, FOFS(targetname), name); + if (!self) { // hmm, targetname failed, try script_targetname? + self = G_Find(NULL, FOFS(script_targetname), name); } - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetICARUSFreeze: invalid ent %s\n", name); return; } - if ( freeze ) - { + if (freeze) { self->r.svFlags |= SVF_ICARUS_FREEZE; - } - else - { + } else { self->r.svFlags &= ~SVF_ICARUS_FREEZE; } } @@ -3334,10 +2987,7 @@ Q3_SetViewEntity Argument : const char *name ============ */ -void Q3_SetViewEntity(int entID, const char *name) -{ - G_DebugPrint( WL_WARNING, "Q3_SetViewEntity currently unsupported in MP, ask if you need it.\n"); -} +void Q3_SetViewEntity(int entID, const char *name) { G_DebugPrint(WL_WARNING, "Q3_SetViewEntity currently unsupported in MP, ask if you need it.\n"); } /* ============ @@ -3348,14 +2998,13 @@ Q3_SetWeapon Argument : const char *wp_name ============ */ -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); -static void Q3_SetWeapon (int entID, const char *wp_name) -{ - gentity_t *ent = &g_entities[entID]; - int wp = GetIDForString( WPTable, wp_name ); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); +static void Q3_SetWeapon(int entID, const char *wp_name) { + gentity_t *ent = &g_entities[entID]; + int wp = GetIDForString(WPTable, wp_name); - ent->client->ps.stats[STAT_WEAPONS] = (1<client->ps.stats[STAT_WEAPONS] = (1 << wp); + ChangeWeapon(ent, wp); } /* @@ -3367,14 +3016,11 @@ Q3_SetItem Argument : const char *wp_name ============ */ -static void Q3_SetItem (int entID, const char *item_name) -{ //rww - unused in mp - G_DebugPrint( WL_WARNING, "Q3_SetItem: NOT SUPPORTED IN MP\n"); +static void Q3_SetItem(int entID, const char *item_name) { // rww - unused in mp + G_DebugPrint(WL_WARNING, "Q3_SetItem: NOT SUPPORTED IN MP\n"); return; } - - /* ============ Q3_SetWalkSpeed @@ -3384,31 +3030,26 @@ Q3_SetWalkSpeed Argument : int int_data ============ */ -static void Q3_SetWalkSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWalkSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetWalkSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetWalkSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.walkSpeed = self->client->ps.speed = 1; } self->NPC->stats.walkSpeed = self->client->ps.speed = int_data; } - /* ============ Q3_SetRunSpeed @@ -3418,31 +3059,26 @@ Q3_SetRunSpeed Argument : int int_data ============ */ -static void Q3_SetRunSpeed (int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRunSpeed(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetRunSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetRunSpeed: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data == 0) - { + if (int_data == 0) { self->NPC->stats.runSpeed = self->client->ps.speed = 1; } self->NPC->stats.runSpeed = self->client->ps.speed = int_data; } - /* ============ Q3_SetYawSpeed @@ -3452,26 +3088,22 @@ Q3_SetYawSpeed Argument : float float_data ============ */ -static void Q3_SetYawSpeed (int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetYawSpeed(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetYawSpeed: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetYawSpeed: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->stats.yawSpeed = float_data; } - /* ============ Q3_SetAggression @@ -3481,30 +3113,25 @@ Q3_SetAggression Argument : int int_data ============ */ -static void Q3_SetAggression(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; - +static void Q3_SetAggression(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetAggression: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetAggression: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aggression = int_data; } - /* ============ Q3_SetAim @@ -3514,29 +3141,25 @@ Q3_SetAim Argument : int int_data ============ */ -static void Q3_SetAim(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetAim(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetAim: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetAim: '%s' is not an NPC!\n", self->targetname); return; } - if(int_data < 1 || int_data > 5) + if (int_data < 1 || int_data > 5) return; self->NPC->stats.aim = int_data; } - /* ============ Q3_SetFriction @@ -3546,27 +3169,23 @@ Q3_SetFriction Argument : int int_data ============ */ -static void Q3_SetFriction(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFriction(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetFriction: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname ); + if (!self->client) { + G_DebugPrint(WL_ERROR, "Q3_SetFriction: '%s' is not an NPC/player!\n", self->targetname); return; } - G_DebugPrint( WL_WARNING, "Q3_SetFriction currently unsupported in MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetFriction currently unsupported in MP\n"); // self->client->ps.friction = int_data; } - /* ============ Q3_SetGravity @@ -3576,31 +3195,26 @@ Q3_SetGravity Argument : float float_data ============ */ -static void Q3_SetGravity(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetGravity(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetGravity: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname ); + if (!self->client) { + G_DebugPrint(WL_ERROR, "Q3_SetGravity: '%s' is not an NPC/player!\n", self->targetname); return; } - //FIXME: what if we want to return them to normal global gravity? - if ( self->NPC ) - { + // FIXME: what if we want to return them to normal global gravity? + if (self->NPC) { self->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; } self->client->ps.gravity = float_data; } - /* ============ Q3_SetWait @@ -3610,33 +3224,27 @@ Q3_SetWait Argument : float float_data ============ */ -static void Q3_SetWait(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetWait(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetWait: invalid entID %d\n", entID); return; } self->wait = float_data; } +static void Q3_SetShotSpacing(int entID, int int_data) { + gentity_t *self = &g_entities[entID]; -static void Q3_SetShotSpacing(int entID, int int_data) -{ - gentity_t *self = &g_entities[entID]; - - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetShotSpacing: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetShotSpacing: '%s' is not an NPC!\n", self->targetname); return; } @@ -3653,26 +3261,22 @@ Q3_SetFollowDist Argument : float float_data ============ */ -static void Q3_SetFollowDist(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFollowDist(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetFollowDist: invalid entID %d\n", entID); return; } - if ( !self->client || !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname ); + if (!self->client || !self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetFollowDist: '%s' is not an NPC!\n", self->targetname); return; } self->NPC->followDist = float_data; } - /* ============ Q3_SetScale @@ -3682,23 +3286,18 @@ Q3_SetScale Argument : float float_data ============ */ -static void Q3_SetScale(int entID, float float_data) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetScale(int entID, float float_data) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetScale: invalid entID %d\n", entID); return; } - if (self->client) - { - self->client->ps.iModelScale = float_data*100.0f; - } - else - { - self->s.iModelScale = float_data*100.0f; + if (self->client) { + self->client->ps.iModelScale = float_data * 100.0f; + } else { + self->s.iModelScale = float_data * 100.0f; } } @@ -3710,25 +3309,19 @@ Q3_GameSideCheckStringCounterIncrement Argument : const char *string ============ */ -static float Q3_GameSideCheckStringCounterIncrement( const char *string ) -{ - char *numString; - float val = 0.0f; +static float Q3_GameSideCheckStringCounterIncrement(const char *string) { + char *numString; + float val = 0.0f; - if ( string[0] == '+' ) - {//We want to increment whatever the value is by whatever follows the + - if ( string[1] ) - { + if (string[0] == '+') { // We want to increment whatever the value is by whatever follows the + + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ); + val = atof(numString); } - } - else if ( string[0] == '-' ) - {//we want to decrement - if ( string[1] ) - { + } else if (string[0] == '-') { // we want to decrement + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ) * -1; + val = atof(numString) * -1; } } @@ -3744,29 +3337,23 @@ Q3_SetCount Argument : const char *data ============ */ -static void Q3_SetCount(int entID, const char *data) -{ - gentity_t *self = &g_entities[entID]; - float val = 0.0f; +static void Q3_SetCount(int entID, const char *data) { + gentity_t *self = &g_entities[entID]; + float val = 0.0f; - //FIXME: use FOFS() stuff here to make a generic entity field setting? - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); + // FIXME: use FOFS() stuff here to make a generic entity field setting? + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetCount: invalid entID %d\n", entID); return; } - if ( (val = Q3_GameSideCheckStringCounterIncrement( data )) ) - { + if ((val = Q3_GameSideCheckStringCounterIncrement(data))) { self->count += (int)(val); - } - else - { - self->count = atoi((char *) data); + } else { + self->count = atoi((char *)data); } } - /* ============ Q3_SetTargetName @@ -3776,27 +3363,21 @@ Q3_SetTargetName Argument : const char *targetname ============ */ -static void Q3_SetTargetName (int entID, const char *targetname) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTargetName(int entID, const char *targetname) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetTargetName: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)targetname))) - { + if (!Q_stricmp("NULL", ((char *)targetname))) { self->targetname = NULL; - } - else - { - self->targetname = G_NewString( targetname ); + } else { + self->targetname = G_NewString(targetname); } } - /* ============ Q3_SetTarget @@ -3806,23 +3387,18 @@ Q3_SetTarget Argument : const char *target ============ */ -static void Q3_SetTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetTarget: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)target))) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target = NULL; - } - else - { - self->target = G_NewString( target ); + } else { + self->target = G_NewString(target); } } @@ -3835,9 +3411,8 @@ Q3_SetTarget2 Argument : const char *target ============ */ -static void Q3_SetTarget2 (int entID, const char *target2) -{ - G_DebugPrint( WL_WARNING, "Q3_SetTarget2 does not exist in MP\n"); +static void Q3_SetTarget2(int entID, const char *target2) { + G_DebugPrint(WL_WARNING, "Q3_SetTarget2 does not exist in MP\n"); /* sharedEntity_t *self = SV_GentityNum(entID); @@ -3866,33 +3441,26 @@ Q3_SetRemoveTarget Argument : const char *target ============ */ -static void Q3_SetRemoveTarget (int entID, const char *target) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetRemoveTarget(int entID, const char *target) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetRemoveTarget: invalid entID %d\n", entID); return; } - if ( !self->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname ); + if (!self->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetRemoveTarget: '%s' is not an NPC!\n", self->targetname); return; } - if( !Q_stricmp("NULL", ((char *)target)) ) - { + if (!Q_stricmp("NULL", ((char *)target))) { self->target3 = NULL; - } - else - { - self->target3 = G_NewString( target ); + } else { + self->target3 = G_NewString(target); } } - /* ============ Q3_SetPainTarget @@ -3902,9 +3470,8 @@ Q3_SetPainTarget Argument : const char *targetname ============ */ -static void Q3_SetPainTarget (int entID, const char *targetname) -{ - G_DebugPrint( WL_WARNING, "Q3_SetPainTarget: NOT SUPPORTED IN MP\n"); +static void Q3_SetPainTarget(int entID, const char *targetname) { + G_DebugPrint(WL_WARNING, "Q3_SetPainTarget: NOT SUPPORTED IN MP\n"); /* sharedEntity_t *self = SV_GentityNum(entID); @@ -3934,71 +3501,56 @@ Q3_SetFullName Argument : const char *fullName ============ */ -static void Q3_SetFullName (int entID, const char *fullName) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetFullName(int entID, const char *fullName) { + gentity_t *self = &g_entities[entID]; - if ( !self ) - { - G_DebugPrint( WL_WARNING, "Q3_SetFullName: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_WARNING, "Q3_SetFullName: invalid entID %d\n", entID); return; } - if(!Q_stricmp("NULL", ((char *)fullName))) - { + if (!Q_stricmp("NULL", ((char *)fullName))) { self->fullName = NULL; - } - else - { - self->fullName = G_NewString( fullName ); + } else { + self->fullName = G_NewString(fullName); } } -static void Q3_SetMusicState( const char *dms ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetMusicState: NOT SUPPORTED IN MP\n"); +static void Q3_SetMusicState(const char *dms) { + G_DebugPrint(WL_WARNING, "Q3_SetMusicState: NOT SUPPORTED IN MP\n"); return; } -static void Q3_SetForcePowerLevel ( int entID, int forcePower, int forceLevel ) -{ - gentity_t *self = &g_entities[entID]; +static void Q3_SetForcePowerLevel(int entID, int forcePower, int forceLevel) { + gentity_t *self = &g_entities[entID]; - if ( forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, (NUM_FORCE_POWERS-1) ); + if (forcePower < FP_FIRST || forceLevel >= NUM_FORCE_POWERS) { + G_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: Force Power index %d out of range (%d-%d)\n", forcePower, FP_FIRST, (NUM_FORCE_POWERS - 1)); return; } - if ( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS ) - { - if ( forcePower != FP_SABER_OFFENSE || forceLevel >= SS_NUM_SABER_STYLES ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel ); + if (forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS) { + if (forcePower != FP_SABER_OFFENSE || forceLevel >= SS_NUM_SABER_STYLES) { + G_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: Force power setting %d out of range (0-3)\n", forceLevel); return; } } - if ( !self ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); + if (!self) { + G_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: invalid entID %d\n", entID); return; } - if ( !self->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname ); + if (!self->client) { + G_DebugPrint(WL_ERROR, "Q3_SetForcePowerLevel: ent %s is not a player or NPC\n", self->targetname); return; } self->client->ps.fd.forcePowerLevel[forcePower] = forceLevel; - if ( forceLevel ) - { - self->client->ps.fd.forcePowersKnown |= ( 1 << forcePower ); - } - else - { - self->client->ps.fd.forcePowersKnown &= ~( 1 << forcePower ); + if (forceLevel) { + self->client->ps.fd.forcePowersKnown |= (1 << forcePower); + } else { + self->client->ps.fd.forcePowersKnown &= ~(1 << forcePower); } } /* @@ -4011,49 +3563,39 @@ Q3_SetParm Argument : const char *parmValue ============ */ -void Q3_SetParm (int entID, int parmNum, const char *parmValue) -{ - gentity_t *ent = &g_entities[entID]; - float val; +void Q3_SetParm(int entID, int parmNum, const char *parmValue) { + gentity_t *ent = &g_entities[entID]; + float val; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetParm: invalid entID %d\n", entID); return; } - if ( parmNum < 0 || parmNum >= MAX_PARMS ) - { - G_DebugPrint( WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum ); + if (parmNum < 0 || parmNum >= MAX_PARMS) { + G_DebugPrint(WL_WARNING, "SET_PARM: parmNum %d out of range!\n", parmNum); return; } - if( !ent->parms ) - { - ent->parms = (parms_t *)G_Alloc( sizeof(parms_t) ); - memset( ent->parms, 0, sizeof(parms_t) ); + if (!ent->parms) { + ent->parms = (parms_t *)G_Alloc(sizeof(parms_t)); + memset(ent->parms, 0, sizeof(parms_t)); } - if ( (val = Q3_GameSideCheckStringCounterIncrement( parmValue )) ) - { - val += atof( ent->parms->parm[parmNum] ); - Com_sprintf( ent->parms->parm[parmNum], sizeof(ent->parms->parm[parmNum]), "%f", val ); - } - else - {//Just copy the string - //copy only 16 characters - strncpy( ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[parmNum]) ); - //set the last character to null in case we had to truncate their passed string - if ( ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] != 0 ) - {//Tried to set a string that is too long + if ((val = Q3_GameSideCheckStringCounterIncrement(parmValue))) { + val += atof(ent->parms->parm[parmNum]); + Com_sprintf(ent->parms->parm[parmNum], sizeof(ent->parms->parm[parmNum]), "%f", val); + } else { // Just copy the string + // copy only 16 characters + strncpy(ent->parms->parm[parmNum], parmValue, sizeof(ent->parms->parm[parmNum])); + // set the last character to null in case we had to truncate their passed string + if (ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] != 0) { // Tried to set a string that is too long ent->parms->parm[parmNum][sizeof(ent->parms->parm[parmNum]) - 1] = 0; - G_DebugPrint( WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum] ); + G_DebugPrint(WL_WARNING, "SET_PARM: parm%d string too long, truncated to '%s'!\n", parmNum, ent->parms->parm[parmNum]); } } } - - /* ============= Q3_SetCaptureGoal @@ -4061,32 +3603,27 @@ Q3_SetCaptureGoal Sets the capture spot goal of an entity ============= */ -static void Q3_SetCaptureGoal( int entID, const char *name ) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *goal = G_Find( NULL, FOFS(targetname), (char *) name); +static void Q3_SetCaptureGoal(int entID, const char *name) { + gentity_t *ent = &g_entities[entID]; + gentity_t *goal = G_Find(NULL, FOFS(targetname), (char *)name); - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetCaptureGoal: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetCaptureGoal: '%s' is not an NPC!\n", ent->targetname); return; } - //FIXME: Exception handle here - if (goal == NULL) - { - G_DebugPrint( WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name ); + // FIXME: Exception handle here + if (goal == NULL) { + G_DebugPrint(WL_ERROR, "Q3_SetCaptureGoal: can't find CaptureGoal target: '%s'\n", name); return; } - if(ent->NPC) - { + if (ent->NPC) { ent->NPC->captureGoal = goal; ent->NPC->goalEntity = goal; ent->NPC->goalTime = level.time + 100000; @@ -4100,9 +3637,8 @@ Q3_SetEvent ? ============= */ -static void Q3_SetEvent( int entID, const char *event_name ) -{ //rwwFIXMEFIXME: Use in MP? - G_DebugPrint( WL_WARNING, "Q3_SetEvent: NOT SUPPORTED IN MP (may be in future, ask if needed)\n"); +static void Q3_SetEvent(int entID, const char *event_name) { // rwwFIXMEFIXME: Use in MP? + G_DebugPrint(WL_WARNING, "Q3_SetEvent: NOT SUPPORTED IN MP (may be in future, ask if needed)\n"); return; } @@ -4113,19 +3649,16 @@ Q3_SetIgnorePain ? ============ */ -static void Q3_SetIgnorePain( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnorePain(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetIgnorePain: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetIgnorePain: '%s' is not an NPC!\n", ent->targetname); return; } @@ -4139,10 +3672,9 @@ Q3_SetIgnoreEnemies ? ============ */ -static void Q3_SetIgnoreEnemies( int entID, qboolean data) -{ +static void Q3_SetIgnoreEnemies(int entID, qboolean data) { - G_DebugPrint( WL_WARNING, "Q3_SetIgnoreEnemies: NOT SUPPORTED IN MP"); + G_DebugPrint(WL_WARNING, "Q3_SetIgnoreEnemies: NOT SUPPORTED IN MP"); return; } @@ -4153,33 +3685,26 @@ Q3_SetIgnoreAlerts ? ============ */ -static void Q3_SetIgnoreAlerts( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetIgnoreAlerts(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetIgnoreAlerts: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetIgnoreAlerts: '%s' is not an NPC!\n", ent->targetname); return; } - if(data) - { + if (data) { ent->NPC->scriptFlags |= SCF_IGNORE_ALERTS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_IGNORE_ALERTS; } } - /* ============ Q3_SetNoTarget @@ -4187,17 +3712,15 @@ Q3_SetNoTarget ? ============ */ -static void Q3_SetNoTarget( int entID, qboolean data) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoTarget(int entID, qboolean data) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoTarget: invalid entID %d\n", entID); return; } - if(data) + if (data) ent->flags |= FL_NOTARGET; else ent->flags &= ~FL_NOTARGET; @@ -4210,22 +3733,17 @@ Q3_SetDontShoot ? ============ */ -static void Q3_SetDontShoot( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontShoot(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDontShoot: invalid entID %d\n", entID); return; } - if(add) - { + if (add) { ent->flags |= FL_DONT_SHOOT; - } - else - { + } else { ent->flags &= ~FL_DONT_SHOOT; } } @@ -4237,28 +3755,22 @@ Q3_SetDontFire ? ============ */ -static void Q3_SetDontFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDontFire: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetDontFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FIRE; } } @@ -4270,33 +3782,26 @@ Q3_SetFireWeapon ? ============ */ -static void Q3_SetFireWeapon(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFireWeapon(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_FireWeapon: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetFireWeapon: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FIRE_WEAPON; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FIRE_WEAPON; } } - /* ============ Q3_SetInactive @@ -4304,22 +3809,17 @@ Q3_SetInactive ? ============ */ -static void Q3_SetInactive(int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInactive(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetInactive: invalid entID %d\n", entID); return; } - if(add) - { + if (add) { ent->flags |= FL_INACTIVE; - } - else - { + } else { ent->flags &= ~FL_INACTIVE; } } @@ -4331,26 +3831,21 @@ Q3_SetFuncUsableVisible ? ============ */ -static void Q3_SetFuncUsableVisible(int entID, qboolean visible ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFuncUsableVisible(int entID, qboolean visible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetFuncUsableVisible: invalid entID %d\n", entID); return; } // Yeah, I know that this doesn't even do half of what the func_usable use code does, but if I've got two things on top of each other...and only // one is visible at a time....and neither can ever be used......and finally, the shader on it has the shader_anim stuff going on....It doesn't seem // like I can easily use the other version without nasty side effects. - if( visible ) - { + if (visible) { ent->r.svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; - } - else - { + } else { ent->r.svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; } @@ -4363,9 +3858,8 @@ Q3_SetLockedEnemy ? ============ */ -static void Q3_SetLockedEnemy ( int entID, qboolean locked) -{ - G_DebugPrint( WL_WARNING, "Q3_SetLockedEnemy: NOT SUPPORTED IN MP\n"); +static void Q3_SetLockedEnemy(int entID, qboolean locked) { + G_DebugPrint(WL_WARNING, "Q3_SetLockedEnemy: NOT SUPPORTED IN MP\n"); return; } @@ -4377,9 +3871,8 @@ Q3_SetCinematicSkipScript ============ */ -static void Q3_SetCinematicSkipScript( char *scriptname ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetCinematicSkipScript: NOT SUPPORTED IN MP\n"); +static void Q3_SetCinematicSkipScript(char *scriptname) { + G_DebugPrint(WL_WARNING, "Q3_SetCinematicSkipScript: NOT SUPPORTED IN MP\n"); return; } @@ -4390,9 +3883,8 @@ Q3_SetNoMindTrick ? ============ */ -static void Q3_SetNoMindTrick( int entID, qboolean add) -{ - G_DebugPrint( WL_WARNING, "Q3_SetNoMindTrick: NOT SUPPORTED IN MP\n"); +static void Q3_SetNoMindTrick(int entID, qboolean add) { + G_DebugPrint(WL_WARNING, "Q3_SetNoMindTrick: NOT SUPPORTED IN MP\n"); return; } @@ -4403,28 +3895,22 @@ Q3_SetCrouched ? ============ */ -static void Q3_SetCrouched( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetCrouched(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetCrouched: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetCrouched: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CROUCHED; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CROUCHED; } } @@ -4436,28 +3922,22 @@ Q3_SetWalking ? ============ */ -static void Q3_SetWalking( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetWalking(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetWalking: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetWalking: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_WALKING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_WALKING; } return; @@ -4470,28 +3950,22 @@ Q3_SetRunning ? ============ */ -static void Q3_SetRunning( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRunning(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetRunning: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetRunning: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_RUNNING; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_RUNNING; } } @@ -4503,28 +3977,22 @@ Q3_SetForcedMarch ? ============ */ -static void Q3_SetForcedMarch( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForcedMarch(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetForcedMarch: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetForcedMarch: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FORCED_MARCH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FORCED_MARCH; } } @@ -4535,28 +4003,22 @@ Q3_SetChaseEnemies indicates whether the npc should chase after an enemy ============ */ -static void Q3_SetChaseEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetChaseEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetChaseEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetChaseEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_CHASE_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_CHASE_ENEMIES; } } @@ -4569,28 +4031,22 @@ if set npc will be on the look out for potential enemies if not set, npc will ignore enemies ============ */ -static void Q3_SetLookForEnemies( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLookForEnemies(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetLookForEnemies: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetLookForEnemies: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_LOOK_FOR_ENEMIES; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_LOOK_FOR_ENEMIES; } } @@ -4601,28 +4057,22 @@ Q3_SetFaceMoveDir ============ */ -static void Q3_SetFaceMoveDir( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetFaceMoveDir(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetFaceMoveDir: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetFaceMoveDir: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_FACE_MOVE_DIR; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_FACE_MOVE_DIR; } } @@ -4634,32 +4084,26 @@ Q3_SetAltFire ? ============ */ -static void Q3_SetAltFire( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAltFire(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetAltFire: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetAltFire: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_ALT_FIRE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_ALT_FIRE; } - ChangeWeapon( ent, ent->client->ps.weapon ); + ChangeWeapon(ent, ent->client->ps.weapon); } /* @@ -4669,28 +4113,22 @@ Q3_SetDontFlee ? ============ */ -static void Q3_SetDontFlee( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetDontFlee(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetDontFlee: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetDontFlee: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_DONT_FLEE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_DONT_FLEE; } } @@ -4702,28 +4140,22 @@ Q3_SetNoResponse ? ============ */ -static void Q3_SetNoResponse( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoResponse(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoResponse: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNoResponse: '%s' is not an NPC!\n", ent->targetname); return; } - if(add) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_RESPONSE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_RESPONSE; } } @@ -4735,28 +4167,22 @@ Q3_SetCombatTalk ? ============ */ -static void Q3_SetCombatTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; - - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); +static void Q3_SetCombatTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; + + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetCombatTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetCombatTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_COMBAT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_COMBAT_TALK; } } @@ -4768,28 +4194,22 @@ Q3_SetAlertTalk ? ============ */ -static void Q3_SetAlertTalk( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetAlertTalk(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetAlertTalk: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetAlertTalk: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ALERT_TALK; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ALERT_TALK; } } @@ -4801,28 +4221,22 @@ Q3_SetUseCpNearest ? ============ */ -static void Q3_SetUseCpNearest( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUseCpNearest(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetUseCpNearest: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetUseCpNearest: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_USE_CP_NEAREST; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_USE_CP_NEAREST; } } @@ -4834,28 +4248,22 @@ Q3_SetNoForce ? ============ */ -static void Q3_SetNoForce( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoForce(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoForce: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNoForce: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FORCE; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FORCE; } } @@ -4867,28 +4275,22 @@ Q3_SetNoAcrobatics ? ============ */ -static void Q3_SetNoAcrobatics( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAcrobatics(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoAcrobatics: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNoAcrobatics: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_ACROBATICS; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_ACROBATICS; } } @@ -4900,9 +4302,8 @@ Q3_SetUseSubtitles ? ============ */ -static void Q3_SetUseSubtitles( int entID, qboolean add) -{ - G_DebugPrint( WL_WARNING, "Q3_SetUseSubtitles: NOT SUPPORTED IN MP\n"); +static void Q3_SetUseSubtitles(int entID, qboolean add) { + G_DebugPrint(WL_WARNING, "Q3_SetUseSubtitles: NOT SUPPORTED IN MP\n"); return; } @@ -4913,28 +4314,22 @@ Q3_SetNoFallToDeath ? ============ */ -static void Q3_SetNoFallToDeath( int entID, qboolean add) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoFallToDeath(int entID, qboolean add) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoFallToDeath: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNoFallToDeath: '%s' is not an NPC!\n", ent->targetname); return; } - if ( add ) - { + if (add) { ent->NPC->scriptFlags |= SCF_NO_FALLTODEATH; - } - else - { + } else { ent->NPC->scriptFlags &= ~SCF_NO_FALLTODEATH; } } @@ -4946,13 +4341,11 @@ Q3_SetDismemberable ? ============ */ -static void Q3_SetDismemberable( int entID, qboolean dismemberable) -{ - G_DebugPrint( WL_WARNING, "Q3_SetDismemberable: NOT SUPPORTED IN MP\n"); +static void Q3_SetDismemberable(int entID, qboolean dismemberable) { + G_DebugPrint(WL_WARNING, "Q3_SetDismemberable: NOT SUPPORTED IN MP\n"); return; } - /* ============ Q3_SetMoreLight @@ -4960,9 +4353,8 @@ Q3_SetMoreLight ? ============ */ -static void Q3_SetMoreLight( int entID, qboolean add ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetMoreLight: NOT SUPPORTED IN MP\n"); +static void Q3_SetMoreLight(int entID, qboolean add) { + G_DebugPrint(WL_WARNING, "Q3_SetMoreLight: NOT SUPPORTED IN MP\n"); return; } @@ -4973,22 +4365,17 @@ Q3_SetUndying ? ============ */ -static void Q3_SetUndying( int entID, qboolean undying) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetUndying(int entID, qboolean undying) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetUndying: invalid entID %d\n", entID); return; } - if(undying) - { + if (undying) { ent->flags |= FL_UNDYING; - } - else - { + } else { ent->flags &= ~FL_UNDYING; } } @@ -5000,35 +4387,26 @@ Q3_SetInvincible ? ============ */ -static void Q3_SetInvincible( int entID, qboolean invincible) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetInvincible(int entID, qboolean invincible) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetInvincible: invalid entID %d\n", entID); return; } - if ( !Q_stricmp( "func_breakable", ent->classname ) ) - { - if ( invincible ) - { + if (!Q_stricmp("func_breakable", ent->classname)) { + if (invincible) { ent->spawnflags |= 1; - } - else - { + } else { ent->spawnflags &= ~1; } return; } - if ( invincible ) - { + if (invincible) { ent->flags |= FL_GODMODE; - } - else - { + } else { ent->flags &= ~FL_GODMODE; } } @@ -5041,9 +4419,8 @@ Q3_SetForceInvincible Argument : qboolean forceInv ============ */ -static void Q3_SetForceInvincible( int entID, qboolean forceInv ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetForceInvicible: NOT SUPPORTED IN MP\n"); +static void Q3_SetForceInvincible(int entID, qboolean forceInv) { + G_DebugPrint(WL_WARNING, "Q3_SetForceInvicible: NOT SUPPORTED IN MP\n"); return; } @@ -5054,28 +4431,22 @@ Q3_SetNoAvoid ? ============ */ -static void Q3_SetNoAvoid( int entID, qboolean noAvoid) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoAvoid(int entID, qboolean noAvoid) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoAvoid: invalid entID %d\n", entID); return; } - if ( !ent->NPC ) - { - G_DebugPrint( WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname ); + if (!ent->NPC) { + G_DebugPrint(WL_ERROR, "Q3_SetNoAvoid: '%s' is not an NPC!\n", ent->targetname); return; } - if(noAvoid) - { + if (noAvoid) { ent->NPC->aiFlags |= NPCAI_NO_COLL_AVOID; - } - else - { + } else { ent->NPC->aiFlags &= ~NPCAI_NO_COLL_AVOID; } } @@ -5088,33 +4459,27 @@ SolidifyOwner Argument : sharedEntity_t *self ============ */ -void SolidifyOwner( gentity_t *self ) -{ +void SolidifyOwner(gentity_t *self) { int oldContents; gentity_t *owner = &g_entities[self->r.ownerNum]; self->nextthink = level.time + FRAMETIME; self->think = G_FreeEntity; - if ( !owner || !owner->inuse ) - { + if (!owner || !owner->inuse) { return; } oldContents = owner->r.contents; owner->r.contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( owner, owner->r.currentOrigin ) ) - { + if (SpotWouldTelefrag2(owner, owner->r.currentOrigin)) { owner->r.contents = oldContents; self->think = SolidifyOwner; - } - else - { - trap->ICARUS_TaskIDComplete( (sharedEntity_t *)owner, TID_RESIZE ); + } else { + trap->ICARUS_TaskIDComplete((sharedEntity_t *)owner, TID_RESIZE); } } - /* ============ Q3_SetSolid @@ -5122,22 +4487,18 @@ Q3_SetSolid ? ============ */ -static qboolean Q3_SetSolid( int entID, qboolean solid) -{ - gentity_t *ent = &g_entities[entID]; +static qboolean Q3_SetSolid(int entID, qboolean solid) { + gentity_t *ent = &g_entities[entID]; - if ( !ent || !ent->inuse ) - { - G_DebugPrint( WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); + if (!ent || !ent->inuse) { + G_DebugPrint(WL_WARNING, "Q3_SetSolid: invalid entID %d\n", entID); return qtrue; } - if ( solid ) - {//FIXME: Presumption + if (solid) { // FIXME: Presumption int oldContents = ent->r.contents; ent->r.contents = CONTENTS_BODY; - if ( SpotWouldTelefrag2( ent, ent->r.currentOrigin ) ) - { + if (SpotWouldTelefrag2(ent, ent->r.currentOrigin)) { gentity_t *solidifier = G_Spawn(); solidifier->r.ownerNum = ent->s.number; @@ -5149,15 +4510,10 @@ static qboolean Q3_SetSolid( int entID, qboolean solid) return qfalse; } ent->clipmask |= CONTENTS_BODY; - } - else - {//FIXME: Presumption - if ( ent->s.eFlags & EF_NODRAW ) - {//We're invisible too, so set contents to none + } else { // FIXME: Presumption + if (ent->s.eFlags & EF_NODRAW) { // We're invisible too, so set contents to none ent->r.contents = 0; - } - else - { + } else { ent->r.contents = CONTENTS_CORPSE; } } @@ -5171,24 +4527,21 @@ Q3_SetForwardMove ? ============ */ -static void Q3_SetForwardMove( int entID, int fmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetForwardMove(int entID, int fmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetForwardMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "Q3_SetForwardMove: '%s' is not an NPC/player!\n", ent->targetname); return; } - G_DebugPrint( WL_WARNING, "Q3_SetForwardMove: NOT SUPPORTED IN MP\n"); - //ent->client->forced_forwardmove = fmoveVal; + G_DebugPrint(WL_WARNING, "Q3_SetForwardMove: NOT SUPPORTED IN MP\n"); + // ent->client->forced_forwardmove = fmoveVal; } /* @@ -5198,24 +4551,21 @@ Q3_SetRightMove ? ============ */ -static void Q3_SetRightMove( int entID, int rmoveVal) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetRightMove(int entID, int rmoveVal) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetRightMove: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "Q3_SetRightMove: '%s' is not an NPC/player!\n", ent->targetname); return; } - G_DebugPrint( WL_WARNING, "Q3_SetRightMove: NOT SUPPORTED IN MP\n"); - //ent->client->forced_rightmove = rmoveVal; + G_DebugPrint(WL_WARNING, "Q3_SetRightMove: NOT SUPPORTED IN MP\n"); + // ent->client->forced_rightmove = rmoveVal; } /* @@ -5225,23 +4575,20 @@ Q3_SetLockAngle ? ============ */ -static void Q3_SetLockAngle( int entID, const char *lockAngle) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetLockAngle(int entID, const char *lockAngle) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetLockAngle: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "Q3_SetLockAngle: '%s' is not an NPC/player!\n", ent->targetname); return; } - G_DebugPrint( WL_WARNING, "Q3_SetLockAngle is not currently available. Ask if you really need it.\n"); + G_DebugPrint(WL_WARNING, "Q3_SetLockAngle is not currently available. Ask if you really need it.\n"); /* if(Q_stricmp("off", lockAngle) == 0) {//free it @@ -5264,7 +4611,6 @@ static void Q3_SetLockAngle( int entID, const char *lockAngle) */ } - /* ============ Q3_CameraGroup @@ -5272,9 +4618,8 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroup( int entID, char *camG) -{ - G_DebugPrint( WL_WARNING, "Q3_CameraGroup: NOT SUPPORTED IN MP\n"); +static void Q3_CameraGroup(int entID, char *camG) { + G_DebugPrint(WL_WARNING, "Q3_CameraGroup: NOT SUPPORTED IN MP\n"); return; } @@ -5285,9 +4630,8 @@ Q3_CameraGroupZOfs ? ============ */ -static void Q3_CameraGroupZOfs( float camGZOfs ) -{ - G_DebugPrint( WL_WARNING, "Q3_CameraGroupZOfs: NOT SUPPORTED IN MP\n"); +static void Q3_CameraGroupZOfs(float camGZOfs) { + G_DebugPrint(WL_WARNING, "Q3_CameraGroupZOfs: NOT SUPPORTED IN MP\n"); return; } /* @@ -5297,9 +4641,8 @@ Q3_CameraGroup ? ============ */ -static void Q3_CameraGroupTag( char *camGTag ) -{ - G_DebugPrint( WL_WARNING, "Q3_CameraGroupTag: NOT SUPPORTED IN MP\n"); +static void Q3_CameraGroupTag(char *camGTag) { + G_DebugPrint(WL_WARNING, "Q3_CameraGroupTag: NOT SUPPORTED IN MP\n"); return; } @@ -5308,40 +4651,28 @@ static void Q3_CameraGroupTag( char *camGTag ) Q3_RemoveRHandModel ============ */ -static void Q3_RemoveRHandModel( int entID, char *addModel) -{ - G_DebugPrint( WL_WARNING, "Q3_RemoveRHandModel: NOT SUPPORTED IN MP\n"); -} +static void Q3_RemoveRHandModel(int entID, char *addModel) { G_DebugPrint(WL_WARNING, "Q3_RemoveRHandModel: NOT SUPPORTED IN MP\n"); } /* ============ Q3_AddRHandModel ============ */ -static void Q3_AddRHandModel( int entID, char *addModel) -{ - G_DebugPrint( WL_WARNING, "Q3_AddRHandModel: NOT SUPPORTED IN MP\n"); -} +static void Q3_AddRHandModel(int entID, char *addModel) { G_DebugPrint(WL_WARNING, "Q3_AddRHandModel: NOT SUPPORTED IN MP\n"); } /* ============ Q3_AddLHandModel ============ */ -static void Q3_AddLHandModel( int entID, char *addModel) -{ - G_DebugPrint( WL_WARNING, "Q3_AddLHandModel: NOT SUPPORTED IN MP\n"); -} +static void Q3_AddLHandModel(int entID, char *addModel) { G_DebugPrint(WL_WARNING, "Q3_AddLHandModel: NOT SUPPORTED IN MP\n"); } /* ============ Q3_RemoveLHandModel ============ */ -static void Q3_RemoveLHandModel( int entID, char *addModel) -{ - G_DebugPrint( WL_WARNING, "Q3_RemoveLHandModel: NOT SUPPORTED IN MP\n"); -} +static void Q3_RemoveLHandModel(int entID, char *addModel) { G_DebugPrint(WL_WARNING, "Q3_RemoveLHandModel: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5350,45 +4681,38 @@ Q3_LookTarget ? ============ */ -static void Q3_LookTarget( int entID, char *targetName) -{ - gentity_t *ent = &g_entities[entID]; - gentity_t *targ = NULL; +static void Q3_LookTarget(int entID, char *targetName) { + gentity_t *ent = &g_entities[entID]; + gentity_t *targ = NULL; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_LookTarget: invalid entID %d\n", entID); return; } - if ( !ent->client ) - { - G_DebugPrint( WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname ); + if (!ent->client) { + G_DebugPrint(WL_ERROR, "Q3_LookTarget: '%s' is not an NPC/player!\n", ent->targetname); return; } - if(Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) - {//clearing look target - NPC_ClearLookTarget( ent ); + if (Q_stricmp("none", targetName) == 0 || Q_stricmp("NULL", targetName) == 0) { // clearing look target + NPC_ClearLookTarget(ent); return; } targ = G_Find(NULL, FOFS(targetname), targetName); - if(!targ) - { - targ = G_Find(NULL, FOFS(script_targetname), targetName); - if (!targ) - { - targ = G_Find(NULL, FOFS(NPC_targetname), targetName); - if (!targ) - { - G_DebugPrint( WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName ); + if (!targ) { + targ = G_Find(NULL, FOFS(script_targetname), targetName); + if (!targ) { + targ = G_Find(NULL, FOFS(NPC_targetname), targetName); + if (!targ) { + G_DebugPrint(WL_ERROR, "Q3_LookTarget: Can't find ent %s\n", targetName); return; } } } - NPC_SetLookTarget( ent, targ->s.number, 0 ); + NPC_SetLookTarget(ent, targ->s.number, 0); } /* @@ -5398,10 +4722,7 @@ Q3_Face ? ============ */ -static void Q3_Face( int entID,int expression, float holdtime) -{ - G_DebugPrint( WL_WARNING, "Q3_Face: NOT SUPPORTED IN MP\n"); -} +static void Q3_Face(int entID, int expression, float holdtime) { G_DebugPrint(WL_WARNING, "Q3_Face: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5412,9 +4733,8 @@ Q3_SetLocation Argument : const char *location ============ */ -static qboolean Q3_SetLocation( int entID, const char *location ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetLocation: NOT SUPPORTED IN MP\n"); +static qboolean Q3_SetLocation(int entID, const char *location) { + G_DebugPrint(WL_WARNING, "Q3_SetLocation: NOT SUPPORTED IN MP\n"); return qtrue; } @@ -5427,11 +4747,8 @@ Q3_SetPlayerLocked Argument : qboolean locked ============ */ -qboolean player_locked = qfalse; -static void Q3_SetPlayerLocked( int entID, qboolean locked ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetPlayerLocked: NOT SUPPORTED IN MP\n"); -} +qboolean player_locked = qfalse; +static void Q3_SetPlayerLocked(int entID, qboolean locked) { G_DebugPrint(WL_WARNING, "Q3_SetPlayerLocked: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5442,11 +4759,7 @@ Q3_SetLockPlayerWeapons Argument : qboolean locked ============ */ -static void Q3_SetLockPlayerWeapons( int entID, qboolean locked ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetLockPlayerWeapons: NOT SUPPORTED IN MP\n"); -} - +static void Q3_SetLockPlayerWeapons(int entID, qboolean locked) { G_DebugPrint(WL_WARNING, "Q3_SetLockPlayerWeapons: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5457,10 +4770,7 @@ Q3_SetNoImpactDamage Argument : qboolean locked ============ */ -static void Q3_SetNoImpactDamage( int entID, qboolean noImp ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetNoImpactDamage: NOT SUPPORTED IN MP\n"); -} +static void Q3_SetNoImpactDamage(int entID, qboolean noImp) { G_DebugPrint(WL_WARNING, "Q3_SetNoImpactDamage: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5469,19 +4779,16 @@ Q3_SetBehaviorSet ? ============ */ -static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) -{ - gentity_t *ent = &g_entities[entID]; - bSet_t bSet = BSET_INVALID; +static qboolean Q3_SetBehaviorSet(int entID, int toSet, const char *scriptname) { + gentity_t *ent = &g_entities[entID]; + bSet_t bSet = BSET_INVALID; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetBehaviorSet: invalid entID %d\n", entID); return qfalse; } - switch(toSet) - { + switch (toSet) { case SET_SPAWNSCRIPT: bSet = BSET_SPAWN; break; @@ -5529,35 +4836,28 @@ static qboolean Q3_SetBehaviorSet( int entID, int toSet, const char *scriptname) break; } - if(bSet < BSET_SPAWN || bSet >= NUM_BSETS) - { + if (bSet < BSET_SPAWN || bSet >= NUM_BSETS) { return qfalse; } - if(!Q_stricmp("NULL", scriptname)) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// trap->TagFree( ent->behaviorSet[bSet] ); + if (!Q_stricmp("NULL", scriptname)) { + if (ent->behaviorSet[bSet] != NULL) { + // trap->TagFree( ent->behaviorSet[bSet] ); } ent->behaviorSet[bSet] = NULL; - //memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); - } - else - { - if ( scriptname ) - { - if ( ent->behaviorSet[bSet] != NULL ) - { -// trap->TagFree( ent->behaviorSet[bSet] ); + // memset( &ent->behaviorSet[bSet], 0, sizeof(ent->behaviorSet[bSet]) ); + } else { + if (scriptname) { + if (ent->behaviorSet[bSet] != NULL) { + // trap->TagFree( ent->behaviorSet[bSet] ); } - ent->behaviorSet[bSet] = G_NewString( (char *) scriptname ); //FIXME: This really isn't good... + ent->behaviorSet[bSet] = G_NewString((char *)scriptname); // FIXME: This really isn't good... } - //ent->behaviorSet[bSet] = scriptname; - //strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); + // ent->behaviorSet[bSet] = scriptname; + // strncpy( (char *) &ent->behaviorSet[bSet], scriptname, MAX_BSET_LENGTH ); } return qtrue; } @@ -5569,13 +4869,7 @@ Q3_SetDelayScriptTime ? ============ */ -static void Q3_SetDelayScriptTime(int entID, int delayTime) -{ - G_DebugPrint( WL_WARNING, "Q3_SetDelayScriptTime: NOT SUPPORTED IN MP\n"); -} - - - +static void Q3_SetDelayScriptTime(int entID, int delayTime) { G_DebugPrint(WL_WARNING, "Q3_SetDelayScriptTime: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5586,22 +4880,17 @@ Q3_SetPlayerUsable Argument : qboolean usable ============ */ -static void Q3_SetPlayerUsable( int entID, qboolean usable ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetPlayerUsable(int entID, qboolean usable) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetPlayerUsable: invalid entID %d\n", entID); return; } - if(usable) - { + if (usable) { ent->r.svFlags |= SVF_PLAYER_USABLE; - } - else - { + } else { ent->r.svFlags &= ~SVF_PLAYER_USABLE; } } @@ -5615,9 +4904,8 @@ Q3_SetDisableShaderAnims Argument : int disabled ============ */ -static void Q3_SetDisableShaderAnims( int entID, int disabled ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetDisableShaderAnims: NOT SUPPORTED IN MP\n"); +static void Q3_SetDisableShaderAnims(int entID, int disabled) { + G_DebugPrint(WL_WARNING, "Q3_SetDisableShaderAnims: NOT SUPPORTED IN MP\n"); return; } @@ -5630,9 +4918,8 @@ Q3_SetShaderAnim Argument : int disabled ============ */ -static void Q3_SetShaderAnim( int entID, int disabled ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetShaderAnim: NOT SUPPORTED IN MP\n"); +static void Q3_SetShaderAnim(int entID, int disabled) { + G_DebugPrint(WL_WARNING, "Q3_SetShaderAnim: NOT SUPPORTED IN MP\n"); return; } @@ -5645,11 +4932,7 @@ Q3_SetStartFrame Argument : int startFrame ============ */ -static void Q3_SetStartFrame( int entID, int startFrame ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetStartFrame: NOT SUPPORTED IN MP\n"); -} - +static void Q3_SetStartFrame(int entID, int startFrame) { G_DebugPrint(WL_WARNING, "Q3_SetStartFrame: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5660,10 +4943,7 @@ Q3_SetEndFrame Argument : int endFrame ============ */ -static void Q3_SetEndFrame( int entID, int endFrame ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetEndFrame: NOT SUPPORTED IN MP\n"); -} +static void Q3_SetEndFrame(int entID, int endFrame) { G_DebugPrint(WL_WARNING, "Q3_SetEndFrame: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5674,10 +4954,7 @@ Q3_SetAnimFrame Argument : int startFrame ============ */ -static void Q3_SetAnimFrame( int entID, int animFrame ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetAnimFrame: NOT SUPPORTED IN MP\n"); -} +static void Q3_SetAnimFrame(int entID, int animFrame) { G_DebugPrint(WL_WARNING, "Q3_SetAnimFrame: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5688,11 +4965,7 @@ Q3_SetLoopAnim Argument : qboolean loopAnim ============ */ -static void Q3_SetLoopAnim( int entID, qboolean loopAnim ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetLoopAnim: NOT SUPPORTED IN MP\n"); -} - +static void Q3_SetLoopAnim(int entID, qboolean loopAnim) { G_DebugPrint(WL_WARNING, "Q3_SetLoopAnim: NOT SUPPORTED IN MP\n"); } /* ============ @@ -5703,9 +4976,8 @@ Q3_SetShields Argument : qboolean shields ============ */ -static void Q3_SetShields( int entID, qboolean shields ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetShields: NOT SUPPORTED IN MP\n"); +static void Q3_SetShields(int entID, qboolean shields) { + G_DebugPrint(WL_WARNING, "Q3_SetShields: NOT SUPPORTED IN MP\n"); return; } @@ -5718,27 +4990,21 @@ Q3_SetSaberActive Argument : qboolean shields ============ */ -static void Q3_SetSaberActive( int entID, qboolean active ) -{ +static void Q3_SetSaberActive(int entID, qboolean active) { gentity_t *ent = &g_entities[entID]; - if (!ent || !ent->inuse) - { + if (!ent || !ent->inuse) { return; } - if (!ent->client) - { - G_DebugPrint( WL_WARNING, "Q3_SetSaberActive: %d is not a client\n", entID); + if (!ent->client) { + G_DebugPrint(WL_WARNING, "Q3_SetSaberActive: %d is not a client\n", entID); } - //fixme: Take into account player being in state where saber won't toggle? For now we simply won't care. - if (!ent->client->ps.saberHolstered && active) - { + // fixme: Take into account player being in state where saber won't toggle? For now we simply won't care. + if (!ent->client->ps.saberHolstered && active) { Cmd_ToggleSaber_f(ent); - } - else if (BG_SabersOff( &ent->client->ps ) && !active) - { + } else if (BG_SabersOff(&ent->client->ps) && !active) { Cmd_ToggleSaber_f(ent); } } @@ -5752,22 +5018,17 @@ Q3_SetNoKnockback Argument : qboolean noKnockback ============ */ -static void Q3_SetNoKnockback( int entID, qboolean noKnockback ) -{ - gentity_t *ent = &g_entities[entID]; +static void Q3_SetNoKnockback(int entID, qboolean noKnockback) { + gentity_t *ent = &g_entities[entID]; - if ( !ent ) - { - G_DebugPrint( WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); + if (!ent) { + G_DebugPrint(WL_WARNING, "Q3_SetNoKnockback: invalid entID %d\n", entID); return; } - if ( noKnockback ) - { + if (noKnockback) { ent->flags |= FL_NO_KNOCKBACK; - } - else - { + } else { ent->flags &= ~FL_NO_KNOCKBACK; } } @@ -5779,9 +5040,8 @@ Q3_SetCleanDamagingEnts Return type : void ============ */ -static void Q3_SetCleanDamagingEnts( void ) -{ - G_DebugPrint( WL_WARNING, "Q3_SetCleanDamagingEnts: NOT SUPPORTED IN MP\n"); +static void Q3_SetCleanDamagingEnts(void) { + G_DebugPrint(WL_WARNING, "Q3_SetCleanDamagingEnts: NOT SUPPORTED IN MP\n"); return; } @@ -5794,9 +5054,8 @@ vec4_t textcolor_scroll; Q3_SetTextColor ------------------------- */ -static void Q3_SetTextColor ( vec4_t textcolor,const char *color) -{ - G_DebugPrint( WL_WARNING, "Q3_SetTextColor: NOT SUPPORTED IN MP\n"); +static void Q3_SetTextColor(vec4_t textcolor, const char *color) { + G_DebugPrint(WL_WARNING, "Q3_SetTextColor: NOT SUPPORTED IN MP\n"); return; } @@ -5807,10 +5066,7 @@ Q3_SetCaptionTextColor Change color text prints in ============= */ -static void Q3_SetCaptionTextColor ( const char *color) -{ - Q3_SetTextColor(textcolor_caption,color); -} +static void Q3_SetCaptionTextColor(const char *color) { Q3_SetTextColor(textcolor_caption, color); } /* ============= @@ -5819,10 +5075,7 @@ Q3_SetCenterTextColor Change color text prints in ============= */ -static void Q3_SetCenterTextColor ( const char *color) -{ - Q3_SetTextColor(textcolor_center,color); -} +static void Q3_SetCenterTextColor(const char *color) { Q3_SetTextColor(textcolor_center, color); } /* ============= @@ -5831,10 +5084,7 @@ Q3_SetScrollTextColor Change color text prints in ============= */ -static void Q3_SetScrollTextColor ( const char *color) -{ - Q3_SetTextColor(textcolor_scroll,color); -} +static void Q3_SetScrollTextColor(const char *color) { Q3_SetTextColor(textcolor_scroll, color); } /* ============= @@ -5843,10 +5093,9 @@ Q3_ScrollText Prints a message in the center of the screen ============= */ -static void Q3_ScrollText ( const char *id) -{ - G_DebugPrint( WL_WARNING, "Q3_ScrollText: NOT SUPPORTED IN MP\n"); - //trap->SendServerCommand( -1, va("st \"%s\"", id)); +static void Q3_ScrollText(const char *id) { + G_DebugPrint(WL_WARNING, "Q3_ScrollText: NOT SUPPORTED IN MP\n"); + // trap->SendServerCommand( -1, va("st \"%s\"", id)); return; } @@ -5858,10 +5107,9 @@ Q3_LCARSText Prints a message in the center of the screen giving it an LCARS frame around it ============= */ -static void Q3_LCARSText ( const char *id) -{ - G_DebugPrint( WL_WARNING, "Q3_ScrollText: NOT SUPPORTED IN MP\n"); - //trap->SendServerCommand( -1, va("lt \"%s\"", id)); +static void Q3_LCARSText(const char *id) { + G_DebugPrint(WL_WARNING, "Q3_ScrollText: NOT SUPPORTED IN MP\n"); + // trap->SendServerCommand( -1, va("lt \"%s\"", id)); return; } @@ -5869,441 +5117,421 @@ static void Q3_LCARSText ( const char *id) void UnLockDoors(gentity_t *const ent); void LockDoors(gentity_t *const ent); -//returns qtrue if it got to the end, otherwise qfalse. -qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data ) -{ - gentity_t *ent = &g_entities[entID]; - float float_data; - int int_data, toSet; - vec3_t vector_data; +// returns qtrue if it got to the end, otherwise qfalse. +qboolean Q3_Set(int taskID, int entID, const char *type_name, const char *data) { + gentity_t *ent = &g_entities[entID]; + float float_data; + int int_data, toSet; + vec3_t vector_data; - //Set this for callbacks - toSet = GetIDForString( setTable, type_name ); + // Set this for callbacks + toSet = GetIDForString(setTable, type_name); - //TODO: Throw in a showscript command that will list each command and what they're doing... + // TODO: Throw in a showscript command that will list each command and what they're doing... // maybe as simple as printing that line of the script to the console preceeded by the person's name? // showscript can take any number of targetnames or "all"? Groupname? - switch ( toSet ) - { + switch (toSet) { case SET_ORIGIN: - if ( sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ) != 3 ) { - G_DebugPrint( WL_WARNING, "Q3_Set: failed sscanf on SET_ORIGIN (%s)\n", type_name ); - VectorClear( vector_data ); + if (sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]) != 3) { + G_DebugPrint(WL_WARNING, "Q3_Set: failed sscanf on SET_ORIGIN (%s)\n", type_name); + VectorClear(vector_data); } - G_SetOrigin( ent, vector_data ); - if ( Q_strncmp( "NPC_", ent->classname, 4 ) == 0 ) - {//hack for moving spawners - VectorCopy( vector_data, ent->s.origin); + G_SetOrigin(ent, vector_data); + if (Q_strncmp("NPC_", ent->classname, 4) == 0) { // hack for moving spawners + VectorCopy(vector_data, ent->s.origin); } break; case SET_TELEPORT_DEST: - if ( sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ) != 3 ) { - G_DebugPrint( WL_WARNING, "Q3_Set: failed sscanf on SET_TELEPORT_DEST (%s)\n", type_name ); - VectorClear( vector_data ); + if (sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]) != 3) { + G_DebugPrint(WL_WARNING, "Q3_Set: failed sscanf on SET_TELEPORT_DEST (%s)\n", type_name); + VectorClear(vector_data); } - if ( !Q3_SetTeleportDest( entID, vector_data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); + if (!Q3_SetTeleportDest(entID, vector_data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); return qfalse; } break; case SET_COPY_ORIGIN: - Q3_SetCopyOrigin( entID, (char *) data ); + Q3_SetCopyOrigin(entID, (char *)data); break; case SET_ANGLES: - //Q3_SetAngles( entID, *(vec3_t *) data); - if ( sscanf( data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2] ) != 3 ) { - G_DebugPrint( WL_WARNING, "Q3_Set: failed sscanf on SET_ANGLES (%s)\n", type_name ); - VectorClear( vector_data ); + // Q3_SetAngles( entID, *(vec3_t *) data); + if (sscanf(data, "%f %f %f", &vector_data[0], &vector_data[1], &vector_data[2]) != 3) { + G_DebugPrint(WL_WARNING, "Q3_Set: failed sscanf on SET_ANGLES (%s)\n", type_name); + VectorClear(vector_data); } - Q3_SetAngles( entID, vector_data); + Q3_SetAngles(entID, vector_data); break; case SET_XVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 0, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 0, float_data); break; case SET_YVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 1, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 1, float_data); break; case SET_ZVELOCITY: - float_data = atof((char *) data); - Q3_SetVelocity( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetVelocity(entID, 2, float_data); break; case SET_Z_OFFSET: - float_data = atof((char *) data); - Q3_SetOriginOffset( entID, 2, float_data); + float_data = atof((char *)data); + Q3_SetOriginOffset(entID, 2, float_data); break; case SET_ENEMY: - Q3_SetEnemy( entID, (char *) data ); + Q3_SetEnemy(entID, (char *)data); break; case SET_LEADER: - Q3_SetLeader( entID, (char *) data ); + Q3_SetLeader(entID, (char *)data); break; case SET_NAVGOAL: - if ( Q3_SetNavGoal( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_MOVE_NAV, taskID ); - return qfalse; //Don't call it back + if (Q3_SetNavGoal(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_MOVE_NAV, taskID); + return qfalse; // Don't call it back } break; case SET_ANIM_UPPER: - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_UPPER, taskID ); - return qfalse; //Don't call it back + if (Q3_SetAnimUpper(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_UPPER, taskID); + return qfalse; // Don't call it back } break; case SET_ANIM_LOWER: - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_LOWER, taskID ); - return qfalse; //Don't call it back + if (Q3_SetAnimLower(entID, (char *)data)) { + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_LOWER, taskID); + return qfalse; // Don't call it back } break; - case SET_ANIM_BOTH: - { - int both = 0; - if ( Q3_SetAnimUpper( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_UPPER, taskID ); - both++; - } - else - { - G_DebugPrint( WL_ERROR, "Q3_SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( Q3_SetAnimLower( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_LOWER, taskID ); - both++; - } - else - { - G_DebugPrint( WL_ERROR, "Q3_SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data ); - } - if ( both >= 2 ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_BOTH, taskID ); - } - if ( both ) - { - return qfalse; //Don't call it back - } + case SET_ANIM_BOTH: { + int both = 0; + if (Q3_SetAnimUpper(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_UPPER, taskID); + both++; + } else { + G_DebugPrint(WL_ERROR, "Q3_SetAnimUpper: %s does not have anim %s!\n", ent->targetname, (char *)data); } - break; + if (Q3_SetAnimLower(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_LOWER, taskID); + both++; + } else { + G_DebugPrint(WL_ERROR, "Q3_SetAnimLower: %s does not have anim %s!\n", ent->targetname, (char *)data); + } + if (both >= 2) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_BOTH, taskID); + } + if (both) { + return qfalse; // Don't call it back + } + } break; case SET_ANIM_HOLDTIME_LOWER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the bottom - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_LOWER, taskID ); - return qfalse; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the bottom + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_LOWER, taskID); + return qfalse; // Don't call it back break; case SET_ANIM_HOLDTIME_UPPER: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_TaskIDClear( &ent->taskID[TID_ANIM_BOTH] );//We only want to wait for the top - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_UPPER, taskID ); - return qfalse; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_TaskIDClear(&ent->taskID[TID_ANIM_BOTH]); // We only want to wait for the top + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_UPPER, taskID); + return qfalse; // Don't call it back break; case SET_ANIM_HOLDTIME_BOTH: - int_data = atoi((char *) data); - Q3_SetAnimHoldTime( entID, int_data, qfalse ); - Q3_SetAnimHoldTime( entID, int_data, qtrue ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_BOTH, taskID ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_UPPER, taskID ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_LOWER, taskID ); - return qfalse; //Don't call it back + int_data = atoi((char *)data); + Q3_SetAnimHoldTime(entID, int_data, qfalse); + Q3_SetAnimHoldTime(entID, int_data, qtrue); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_BOTH, taskID); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_UPPER, taskID); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_LOWER, taskID); + return qfalse; // Don't call it back break; case SET_PLAYER_TEAM: - G_DebugPrint( WL_WARNING, "Q3_SetPlayerTeam: Not in MP ATM, let a programmer (ideally Rich) know if you need it\n"); + G_DebugPrint(WL_WARNING, "Q3_SetPlayerTeam: Not in MP ATM, let a programmer (ideally Rich) know if you need it\n"); break; case SET_ENEMY_TEAM: - G_DebugPrint( WL_WARNING, "Q3_SetEnemyTeam: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetEnemyTeam: NOT SUPPORTED IN MP\n"); break; case SET_HEALTH: - int_data = atoi((char *) data); - Q3_SetHealth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHealth(entID, int_data); break; case SET_ARMOR: - int_data = atoi((char *) data); - Q3_SetArmor( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetArmor(entID, int_data); break; case SET_BEHAVIOR_STATE: - if( !Q3_SetBState( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_BSTATE, taskID ); - return qfalse;//don't complete + if (!Q3_SetBState(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_BSTATE, taskID); + return qfalse; // don't complete } break; case SET_DEFAULT_BSTATE: - Q3_SetDefaultBState( entID, (char *) data ); + Q3_SetDefaultBState(entID, (char *)data); break; case SET_TEMP_BSTATE: - if( !Q3_SetTempBState( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_BSTATE, taskID ); - return qfalse;//don't complete + if (!Q3_SetTempBState(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_BSTATE, taskID); + return qfalse; // don't complete } break; case SET_CAPTURE: - Q3_SetCaptureGoal( entID, (char *) data ); + Q3_SetCaptureGoal(entID, (char *)data); break; - case SET_DPITCH://FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? - float_data = atof((char *) data); - Q3_SetDPitch( entID, float_data ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANGLE_FACE, taskID ); + case SET_DPITCH: // FIXME: make these set tempBehavior to BS_FACE and await completion? Or set lockedDesiredPitch/Yaw and aimTime? + float_data = atof((char *)data); + Q3_SetDPitch(entID, float_data); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANGLE_FACE, taskID); return qfalse; break; case SET_DYAW: - float_data = atof((char *) data); - Q3_SetDYaw( entID, float_data ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANGLE_FACE, taskID ); + float_data = atof((char *)data); + Q3_SetDYaw(entID, float_data); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANGLE_FACE, taskID); return qfalse; break; case SET_EVENT: - Q3_SetEvent( entID, (char *) data ); + Q3_SetEvent(entID, (char *)data); break; case SET_VIEWTARGET: - Q3_SetViewTarget( entID, (char *) data ); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANGLE_FACE, taskID ); + Q3_SetViewTarget(entID, (char *)data); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANGLE_FACE, taskID); return qfalse; break; case SET_WATCHTARGET: - Q3_SetWatchTarget( entID, (char *) data ); + Q3_SetWatchTarget(entID, (char *)data); break; case SET_VIEWENTITY: - Q3_SetViewEntity( entID, (char *) data ); + Q3_SetViewEntity(entID, (char *)data); break; case SET_LOOPSOUND: - Q3_SetLoopSound( entID, (char *) data ); + Q3_SetLoopSound(entID, (char *)data); break; case SET_ICARUS_FREEZE: case SET_ICARUS_UNFREEZE: - Q3_SetICARUSFreeze( entID, (char *) data, (qboolean)(toSet==SET_ICARUS_FREEZE) ); + Q3_SetICARUSFreeze(entID, (char *)data, (qboolean)(toSet == SET_ICARUS_FREEZE)); break; case SET_WEAPON: - Q3_SetWeapon ( entID, (char *) data); + Q3_SetWeapon(entID, (char *)data); break; case SET_ITEM: - Q3_SetItem ( entID, (char *) data); + Q3_SetItem(entID, (char *)data); break; case SET_WALKSPEED: - int_data = atoi((char *) data); - Q3_SetWalkSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetWalkSpeed(entID, int_data); break; case SET_RUNSPEED: - int_data = atoi((char *) data); - Q3_SetRunSpeed ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRunSpeed(entID, int_data); break; case SET_WIDTH: - int_data = atoi((char *) data); - Q3_SetWidth( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetWidth(entID, int_data); return qfalse; break; case SET_YAWSPEED: - float_data = atof((char *) data); - Q3_SetYawSpeed ( entID, float_data); + float_data = atof((char *)data); + Q3_SetYawSpeed(entID, float_data); break; case SET_AGGRESSION: - int_data = atoi((char *) data); - Q3_SetAggression ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAggression(entID, int_data); break; case SET_AIM: - int_data = atoi((char *) data); - Q3_SetAim ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetAim(entID, int_data); break; case SET_FRICTION: - int_data = atoi((char *) data); - Q3_SetFriction ( entID, int_data); + int_data = atoi((char *)data); + Q3_SetFriction(entID, int_data); break; case SET_GRAVITY: - float_data = atof((char *) data); - Q3_SetGravity ( entID, float_data); + float_data = atof((char *)data); + Q3_SetGravity(entID, float_data); break; case SET_WAIT: - float_data = atof((char *) data); - Q3_SetWait( entID, float_data); + float_data = atof((char *)data); + Q3_SetWait(entID, float_data); break; case SET_FOLLOWDIST: - float_data = atof((char *) data); - Q3_SetFollowDist( entID, float_data); + float_data = atof((char *)data); + Q3_SetFollowDist(entID, float_data); break; case SET_SCALE: - float_data = atof((char *) data); - Q3_SetScale( entID, float_data); + float_data = atof((char *)data); + Q3_SetScale(entID, float_data); break; case SET_COUNT: - Q3_SetCount( entID, (char *) data); + Q3_SetCount(entID, (char *)data); break; case SET_SHOT_SPACING: - int_data = atoi((char *) data); - Q3_SetShotSpacing( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetShotSpacing(entID, int_data); break; case SET_IGNOREPAIN: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnorePain( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnorePain( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnorePain(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnorePain(entID, qfalse); break; case SET_IGNOREENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreEnemies( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreEnemies(entID, qfalse); break; case SET_IGNOREALERTS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetIgnoreAlerts( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetIgnoreAlerts(entID, qfalse); break; case SET_DONTSHOOT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontShoot( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontShoot( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontShoot(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontShoot(entID, qfalse); break; case SET_DONTFIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFire( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetDontFire( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFire(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetDontFire(entID, qfalse); break; case SET_LOCKED_ENEMY: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLockedEnemy( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetLockedEnemy( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockedEnemy(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetLockedEnemy(entID, qfalse); break; case SET_NOTARGET: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoTarget( entID, qtrue); - else if(!Q_stricmp("false", ((char *)data))) - Q3_SetNoTarget( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoTarget(entID, qtrue); + else if (!Q_stricmp("false", ((char *)data))) + Q3_SetNoTarget(entID, qfalse); break; case SET_LEAN: - G_DebugPrint( WL_WARNING, "SET_LEAN NOT SUPPORTED IN MP\n" ); + G_DebugPrint(WL_WARNING, "SET_LEAN NOT SUPPORTED IN MP\n"); break; case SET_SHOOTDIST: - float_data = atof((char *) data); - Q3_SetShootDist( entID, float_data ); + float_data = atof((char *)data); + Q3_SetShootDist(entID, float_data); break; case SET_TIMESCALE: - Q3_SetTimeScale( entID, (char *) data ); + Q3_SetTimeScale(entID, (char *)data); break; case SET_VISRANGE: - float_data = atof((char *) data); - Q3_SetVisrange( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVisrange(entID, float_data); break; case SET_EARSHOT: - float_data = atof((char *) data); - Q3_SetEarshot( entID, float_data ); + float_data = atof((char *)data); + Q3_SetEarshot(entID, float_data); break; case SET_VIGILANCE: - float_data = atof((char *) data); - Q3_SetVigilance( entID, float_data ); + float_data = atof((char *)data); + Q3_SetVigilance(entID, float_data); break; case SET_VFOV: - int_data = atoi((char *) data); - Q3_SetVFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetVFOV(entID, int_data); break; case SET_HFOV: - int_data = atoi((char *) data); - Q3_SetHFOV( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetHFOV(entID, int_data); break; case SET_TARGETNAME: - Q3_SetTargetName( entID, (char *) data ); + Q3_SetTargetName(entID, (char *)data); break; case SET_TARGET: - Q3_SetTarget( entID, (char *) data ); + Q3_SetTarget(entID, (char *)data); break; case SET_TARGET2: - Q3_SetTarget2( entID, (char *) data ); + Q3_SetTarget2(entID, (char *)data); break; case SET_LOCATION: - if ( !Q3_SetLocation( entID, (char *) data ) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_LOCATION, taskID ); + if (!Q3_SetLocation(entID, (char *)data)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_LOCATION, taskID); return qfalse; } break; case SET_PAINTARGET: - Q3_SetPainTarget( entID, (char *) data ); + Q3_SetPainTarget(entID, (char *)data); break; case SET_DEFEND_TARGET: - G_DebugPrint( WL_WARNING, "Q3_SetDefendTarget unimplemented\n", entID ); - //Q3_SetEnemy( entID, (char *) data); + G_DebugPrint(WL_WARNING, "Q3_SetDefendTarget unimplemented\n", entID); + // Q3_SetEnemy( entID, (char *) data); break; case SET_PARM1: @@ -6322,7 +5550,7 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data case SET_PARM14: case SET_PARM15: case SET_PARM16: - Q3_SetParm( entID, (toSet-SET_PARM1), (char *) data ); + Q3_SetParm(entID, (toSet - SET_PARM1), (char *)data); break; case SET_SPAWNSCRIPT: @@ -6339,163 +5567,161 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data case SET_FFIRESCRIPT: case SET_FFDEATHSCRIPT: case SET_MINDTRICKSCRIPT: - if( !Q3_SetBehaviorSet(entID, toSet, (char *) data) ) - G_DebugPrint( WL_ERROR, "Q3_SetBehaviorSet: Invalid bSet %s\n", type_name ); + if (!Q3_SetBehaviorSet(entID, toSet, (char *)data)) + G_DebugPrint(WL_ERROR, "Q3_SetBehaviorSet: Invalid bSet %s\n", type_name); break; case SET_NO_MINDTRICK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoMindTrick( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoMindTrick(entID, qtrue); else - Q3_SetNoMindTrick( entID, qfalse); + Q3_SetNoMindTrick(entID, qfalse); break; - case SET_CINEMATIC_SKIPSCRIPT : - Q3_SetCinematicSkipScript((char *) data); + case SET_CINEMATIC_SKIPSCRIPT: + Q3_SetCinematicSkipScript((char *)data); break; - case SET_DELAYSCRIPTTIME: - int_data = atoi((char *) data); - Q3_SetDelayScriptTime( entID, int_data ); + int_data = atoi((char *)data); + Q3_SetDelayScriptTime(entID, int_data); break; case SET_CROUCHED: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCrouched( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCrouched(entID, qtrue); else - Q3_SetCrouched( entID, qfalse); + Q3_SetCrouched(entID, qfalse); break; case SET_WALKING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetWalking( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetWalking(entID, qtrue); else - Q3_SetWalking( entID, qfalse); + Q3_SetWalking(entID, qfalse); break; case SET_RUNNING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetRunning( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetRunning(entID, qtrue); else - Q3_SetRunning( entID, qfalse); + Q3_SetRunning(entID, qfalse); break; case SET_CHASE_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetChaseEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetChaseEnemies(entID, qtrue); else - Q3_SetChaseEnemies( entID, qfalse); + Q3_SetChaseEnemies(entID, qfalse); break; case SET_LOOK_FOR_ENEMIES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetLookForEnemies( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLookForEnemies(entID, qtrue); else - Q3_SetLookForEnemies( entID, qfalse); + Q3_SetLookForEnemies(entID, qfalse); break; case SET_FACE_MOVE_DIR: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetFaceMoveDir( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetFaceMoveDir(entID, qtrue); else - Q3_SetFaceMoveDir( entID, qfalse); + Q3_SetFaceMoveDir(entID, qfalse); break; case SET_ALT_FIRE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAltFire( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAltFire(entID, qtrue); else - Q3_SetAltFire( entID, qfalse); + Q3_SetAltFire(entID, qfalse); break; case SET_DONT_FLEE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDontFlee( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDontFlee(entID, qtrue); else - Q3_SetDontFlee( entID, qfalse); + Q3_SetDontFlee(entID, qfalse); break; case SET_FORCED_MARCH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetForcedMarch( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForcedMarch(entID, qtrue); else - Q3_SetForcedMarch( entID, qfalse); + Q3_SetForcedMarch(entID, qfalse); break; case SET_NO_RESPONSE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoResponse( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoResponse(entID, qtrue); else - Q3_SetNoResponse( entID, qfalse); + Q3_SetNoResponse(entID, qfalse); break; case SET_NO_COMBAT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetCombatTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetCombatTalk(entID, qtrue); else - Q3_SetCombatTalk( entID, qfalse); + Q3_SetCombatTalk(entID, qfalse); break; case SET_NO_ALERT_TALK: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetAlertTalk( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetAlertTalk(entID, qtrue); else - Q3_SetAlertTalk( entID, qfalse); + Q3_SetAlertTalk(entID, qfalse); break; case SET_USE_CP_NEAREST: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseCpNearest( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseCpNearest(entID, qtrue); else - Q3_SetUseCpNearest( entID, qfalse); + Q3_SetUseCpNearest(entID, qfalse); break; case SET_NO_FORCE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoForce( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoForce(entID, qtrue); else - Q3_SetNoForce( entID, qfalse); + Q3_SetNoForce(entID, qfalse); break; case SET_NO_ACROBATICS: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAcrobatics( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAcrobatics(entID, qtrue); else - Q3_SetNoAcrobatics( entID, qfalse); + Q3_SetNoAcrobatics(entID, qfalse); break; case SET_USE_SUBTITLES: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUseSubtitles( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUseSubtitles(entID, qtrue); else - Q3_SetUseSubtitles( entID, qfalse); + Q3_SetUseSubtitles(entID, qfalse); break; case SET_NO_FALLTODEATH: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoFallToDeath( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoFallToDeath(entID, qtrue); else - Q3_SetNoFallToDeath( entID, qfalse); + Q3_SetNoFallToDeath(entID, qfalse); break; case SET_DISMEMBERABLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetDismemberable( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetDismemberable(entID, qtrue); else - Q3_SetDismemberable( entID, qfalse); + Q3_SetDismemberable(entID, qfalse); break; case SET_MORELIGHT: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetMoreLight( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetMoreLight(entID, qtrue); else - Q3_SetMoreLight( entID, qfalse); + Q3_SetMoreLight(entID, qfalse); break; - case SET_TREASONED: - G_DebugPrint( WL_VERBOSE, "SET_TREASONED is disabled, do not use\n" ); + G_DebugPrint(WL_VERBOSE, "SET_TREASONED is disabled, do not use\n"); /* G_TeamRetaliation( NULL, SV_GentityNum(0), qfalse ); ffireLevel = FFIRE_LEVEL_RETALIATION; @@ -6503,116 +5729,112 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data break; case SET_UNDYING: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetUndying( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetUndying(entID, qtrue); else - Q3_SetUndying( entID, qfalse); + Q3_SetUndying(entID, qfalse); break; case SET_INVINCIBLE: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetInvincible( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvincible(entID, qtrue); else - Q3_SetInvincible( entID, qfalse); + Q3_SetInvincible(entID, qfalse); break; case SET_NOAVOID: - if(!Q_stricmp("true", ((char *)data))) - Q3_SetNoAvoid( entID, qtrue); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoAvoid(entID, qtrue); else - Q3_SetNoAvoid( entID, qfalse); + Q3_SetNoAvoid(entID, qfalse); break; case SET_SOLID: - if(!Q_stricmp("true", ((char *)data))) - { - if ( !Q3_SetSolid( entID, qtrue) ) - { - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_RESIZE, taskID ); + if (!Q_stricmp("true", ((char *)data))) { + if (!Q3_SetSolid(entID, qtrue)) { + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_RESIZE, taskID); return qfalse; } - } - else - { - Q3_SetSolid( entID, qfalse); + } else { + Q3_SetSolid(entID, qfalse); } break; case SET_INVISIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetInvisible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetInvisible(entID, qtrue); else - Q3_SetInvisible( entID, qfalse ); + Q3_SetInvisible(entID, qfalse); break; case SET_VAMPIRE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetVampire( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetVampire(entID, qtrue); else - Q3_SetVampire( entID, qfalse ); + Q3_SetVampire(entID, qfalse); break; case SET_FORCE_INVINCIBLE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetForceInvincible( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetForceInvincible(entID, qtrue); else - Q3_SetForceInvincible( entID, qfalse ); + Q3_SetForceInvincible(entID, qfalse); break; case SET_GREET_ALLIES: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetGreetAllies( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetGreetAllies(entID, qtrue); else - Q3_SetGreetAllies( entID, qfalse ); + Q3_SetGreetAllies(entID, qfalse); break; case SET_PLAYER_LOCKED: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetPlayerLocked( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetPlayerLocked(entID, qtrue); else - Q3_SetPlayerLocked( entID, qfalse ); + Q3_SetPlayerLocked(entID, qfalse); break; case SET_LOCK_PLAYER_WEAPONS: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetLockPlayerWeapons( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetLockPlayerWeapons(entID, qtrue); else - Q3_SetLockPlayerWeapons( entID, qfalse ); + Q3_SetLockPlayerWeapons(entID, qfalse); break; case SET_NO_IMPACT_DAMAGE: - if( !Q_stricmp("true", ((char *)data)) ) - Q3_SetNoImpactDamage( entID, qtrue ); + if (!Q_stricmp("true", ((char *)data))) + Q3_SetNoImpactDamage(entID, qtrue); else - Q3_SetNoImpactDamage( entID, qfalse ); + Q3_SetNoImpactDamage(entID, qfalse); break; case SET_FORWARDMOVE: - int_data = atoi((char *) data); - Q3_SetForwardMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetForwardMove(entID, int_data); break; case SET_RIGHTMOVE: - int_data = atoi((char *) data); - Q3_SetRightMove( entID, int_data); + int_data = atoi((char *)data); + Q3_SetRightMove(entID, int_data); break; case SET_LOCKYAW: - Q3_SetLockAngle( entID, data); + Q3_SetLockAngle(entID, data); break; case SET_CAMERA_GROUP: Q3_CameraGroup(entID, (char *)data); break; case SET_CAMERA_GROUP_Z_OFS: - float_data = atof((char *) data); - Q3_CameraGroupZOfs( float_data ); + float_data = atof((char *)data); + Q3_CameraGroupZOfs(float_data); break; case SET_CAMERA_GROUP_TAG: - Q3_CameraGroupTag( (char *)data ); + Q3_CameraGroupTag((char *)data); break; - //FIXME: put these into camera commands + // FIXME: put these into camera commands case SET_LOOK_TARGET: Q3_LookTarget(entID, (char *)data); break; @@ -6640,168 +5862,140 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data case SET_FACEBLINKFROWN: case SET_FACEFROWN: case SET_FACENORMAL: - float_data = atof((char *) data); + float_data = atof((char *)data); Q3_Face(entID, toSet, float_data); break; case SET_SCROLLTEXT: - Q3_ScrollText( (char *)data ); + Q3_ScrollText((char *)data); break; case SET_LCARSTEXT: - Q3_LCARSText( (char *)data ); + Q3_LCARSText((char *)data); break; case SET_CAPTIONTEXTCOLOR: - Q3_SetCaptionTextColor ( (char *)data ); + Q3_SetCaptionTextColor((char *)data); break; case SET_CENTERTEXTCOLOR: - Q3_SetCenterTextColor ( (char *)data ); + Q3_SetCenterTextColor((char *)data); break; case SET_SCROLLTEXTCOLOR: - Q3_SetScrollTextColor ( (char *)data ); + Q3_SetScrollTextColor((char *)data); break; case SET_PLAYER_USABLE: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetPlayerUsable(entID, qtrue); - } - else - { + } else { Q3_SetPlayerUsable(entID, qfalse); } break; case SET_STARTFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetStartFrame(entID, int_data); break; case SET_ENDFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetEndFrame(entID, int_data); - trap->ICARUS_TaskIDSet( (sharedEntity_t *)ent, TID_ANIM_BOTH, taskID ); + trap->ICARUS_TaskIDSet((sharedEntity_t *)ent, TID_ANIM_BOTH, taskID); return qfalse; break; case SET_ANIMFRAME: - int_data = atoi((char *) data); + int_data = atoi((char *)data); Q3_SetAnimFrame(entID, int_data); return qfalse; break; case SET_LOOP_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetLoopAnim(entID, qtrue); - } - else - { + } else { Q3_SetLoopAnim(entID, qfalse); } break; case SET_INTERFACE: - G_DebugPrint( WL_WARNING, "Q3_SetInterface: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetInterface: NOT SUPPORTED IN MP\n"); break; case SET_SHIELDS: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetShields(entID, qtrue); - } - else - { + } else { Q3_SetShields(entID, qfalse); } break; case SET_SABERACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetSaberActive( entID, qtrue ); - } - else - { - Q3_SetSaberActive( entID, qfalse ); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetSaberActive(entID, qtrue); + } else { + Q3_SetSaberActive(entID, qfalse); } break; case SET_ADJUST_AREA_PORTALS: - G_DebugPrint( WL_WARNING, "Q3_SetAdjustAreaPortals: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetAdjustAreaPortals: NOT SUPPORTED IN MP\n"); break; case SET_DMG_BY_HEAVY_WEAP_ONLY: - G_DebugPrint( WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetDmgByHeavyWeapOnly: NOT SUPPORTED IN MP\n"); break; case SET_SHIELDED: - G_DebugPrint( WL_WARNING, "Q3_SetShielded: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetShielded: NOT SUPPORTED IN MP\n"); break; case SET_NO_GROUPS: - G_DebugPrint( WL_WARNING, "Q3_SetNoGroups: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "Q3_SetNoGroups: NOT SUPPORTED IN MP\n"); break; case SET_FIRE_WEAPON: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFireWeapon( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFireWeapon( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFireWeapon(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFireWeapon(entID, qfalse); } break; case SET_INACTIVE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetInactive( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetInactive( entID, qfalse); - } - else if(!Q_stricmp("unlocked", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetInactive(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetInactive(entID, qfalse); + } else if (!Q_stricmp("unlocked", ((char *)data))) { UnLockDoors(&g_entities[entID]); - } - else if(!Q_stricmp("locked", ((char *)data))) - { + } else if (!Q_stricmp("locked", ((char *)data))) { LockDoors(&g_entities[entID]); } break; case SET_END_SCREENDISSOLVE: - G_DebugPrint( WL_WARNING, "SET_END_SCREENDISSOLVE: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_END_SCREENDISSOLVE: NOT SUPPORTED IN MP\n"); break; case SET_MISSION_STATUS_SCREEN: - //Cvar_Set("cg_missionstatusscreen", "1"); - G_DebugPrint( WL_WARNING, "SET_MISSION_STATUS_SCREEN: NOT SUPPORTED IN MP\n"); + // Cvar_Set("cg_missionstatusscreen", "1"); + G_DebugPrint(WL_WARNING, "SET_MISSION_STATUS_SCREEN: NOT SUPPORTED IN MP\n"); break; case SET_FUNC_USABLE_VISIBLE: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qtrue); - } - else if(!Q_stricmp("false", ((char *)data))) - { - Q3_SetFuncUsableVisible( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qtrue); + } else if (!Q_stricmp("false", ((char *)data))) { + Q3_SetFuncUsableVisible(entID, qfalse); } break; case SET_NO_KNOCKBACK: - if(!Q_stricmp("true", ((char *)data))) - { + if (!Q_stricmp("true", ((char *)data))) { Q3_SetNoKnockback(entID, qtrue); - } - else - { + } else { Q3_SetNoKnockback(entID, qfalse); } break; @@ -6811,98 +6005,92 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data // the "timescale" and "skippingCinematic" cvars will be set back to normal in the Video code, so doing a // skip will now only skip one section of a multiple-part story (eg VOY1 bridge sequence) // -// if ( g_timescale->value <= 1.0f ) + // if ( g_timescale->value <= 1.0f ) { - G_DebugPrint( WL_WARNING, "SET_VIDEO_PLAY: NOT SUPPORTED IN MP\n"); - //SV_SendConsoleCommand( va("inGameCinematic %s\n", (char *)data) ); + G_DebugPrint(WL_WARNING, "SET_VIDEO_PLAY: NOT SUPPORTED IN MP\n"); + // SV_SendConsoleCommand( va("inGameCinematic %s\n", (char *)data) ); } break; case SET_VIDEO_FADE_IN: - G_DebugPrint( WL_WARNING, "SET_VIDEO_FADE_IN: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_VIDEO_FADE_IN: NOT SUPPORTED IN MP\n"); break; case SET_VIDEO_FADE_OUT: - G_DebugPrint( WL_WARNING, "SET_VIDEO_FADE_OUT: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_VIDEO_FADE_OUT: NOT SUPPORTED IN MP\n"); break; case SET_REMOVE_TARGET: - Q3_SetRemoveTarget( entID, (const char *) data ); + Q3_SetRemoveTarget(entID, (const char *)data); break; case SET_LOADGAME: - //trap->SendConsoleCommand( va("load %s\n", (const char *) data ) ); - G_DebugPrint( WL_WARNING, "SET_LOADGAME: NOT SUPPORTED IN MP\n"); + // trap->SendConsoleCommand( va("load %s\n", (const char *) data ) ); + G_DebugPrint(WL_WARNING, "SET_LOADGAME: NOT SUPPORTED IN MP\n"); break; case SET_MENU_SCREEN: - //UI_SetActiveMenu( (const char *) data ); + // UI_SetActiveMenu( (const char *) data ); break; case SET_OBJECTIVE_SHOW: - G_DebugPrint( WL_WARNING, "SET_OBJECTIVE_SHOW: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_OBJECTIVE_SHOW: NOT SUPPORTED IN MP\n"); break; case SET_OBJECTIVE_HIDE: - G_DebugPrint( WL_WARNING, "SET_OBJECTIVE_HIDE: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_OBJECTIVE_HIDE: NOT SUPPORTED IN MP\n"); break; case SET_OBJECTIVE_SUCCEEDED: - G_DebugPrint( WL_WARNING, "SET_OBJECTIVE_SUCCEEDED: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_OBJECTIVE_SUCCEEDED: NOT SUPPORTED IN MP\n"); break; case SET_OBJECTIVE_FAILED: - G_DebugPrint( WL_WARNING, "SET_OBJECTIVE_FAILED: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_OBJECTIVE_FAILED: NOT SUPPORTED IN MP\n"); break; case SET_OBJECTIVE_CLEARALL: - G_DebugPrint( WL_WARNING, "SET_OBJECTIVE_CLEARALL: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_OBJECTIVE_CLEARALL: NOT SUPPORTED IN MP\n"); break; case SET_MISSIONFAILED: - G_DebugPrint( WL_WARNING, "SET_MISSIONFAILED: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_MISSIONFAILED: NOT SUPPORTED IN MP\n"); break; case SET_MISSIONSTATUSTEXT: - G_DebugPrint( WL_WARNING, "SET_MISSIONSTATUSTEXT: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_MISSIONSTATUSTEXT: NOT SUPPORTED IN MP\n"); break; case SET_MISSIONSTATUSTIME: - G_DebugPrint( WL_WARNING, "SET_MISSIONSTATUSTIME: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_MISSIONSTATUSTIME: NOT SUPPORTED IN MP\n"); break; case SET_CLOSINGCREDITS: - G_DebugPrint( WL_WARNING, "SET_CLOSINGCREDITS: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_CLOSINGCREDITS: NOT SUPPORTED IN MP\n"); break; case SET_SKILL: -// //can never be set + // //can never be set break; case SET_FULLNAME: - Q3_SetFullName( entID, (char *) data ); + Q3_SetFullName(entID, (char *)data); break; case SET_DISABLE_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetDisableShaderAnims( entID, qtrue); - } - else - { - Q3_SetDisableShaderAnims( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetDisableShaderAnims(entID, qtrue); + } else { + Q3_SetDisableShaderAnims(entID, qfalse); } break; case SET_SHADER_ANIM: - if(!Q_stricmp("true", ((char *)data))) - { - Q3_SetShaderAnim( entID, qtrue); - } - else - { - Q3_SetShaderAnim( entID, qfalse); + if (!Q_stricmp("true", ((char *)data))) { + Q3_SetShaderAnim(entID, qtrue); + } else { + Q3_SetShaderAnim(entID, qfalse); } break; case SET_MUSIC_STATE: - Q3_SetMusicState( (char *) data ); + Q3_SetMusicState((char *)data); break; case SET_CLEAN_DAMAGING_ENTS: @@ -6910,7 +6098,7 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data break; case SET_HUD: - G_DebugPrint( WL_WARNING, "SET_HUD: NOT SUPPORTED IN MP\n"); + G_DebugPrint(WL_WARNING, "SET_HUD: NOT SUPPORTED IN MP\n"); break; case SET_FORCE_HEAL_LEVEL: @@ -6924,13 +6112,13 @@ qboolean Q3_Set( int taskID, int entID, const char *type_name, const char *data case SET_SABER_THROW: case SET_SABER_DEFENSE: case SET_SABER_OFFENSE: - int_data = atoi((char *) data); - Q3_SetForcePowerLevel( entID, (toSet-SET_FORCE_HEAL_LEVEL), int_data ); + int_data = atoi((char *)data); + Q3_SetForcePowerLevel(entID, (toSet - SET_FORCE_HEAL_LEVEL), int_data); break; default: - //G_DebugPrint( WL_ERROR, "Q3_Set: '%s' is not a valid set field\n", type_name ); - trap->ICARUS_SetVar( taskID, entID, type_name, data ); + // G_DebugPrint( WL_ERROR, "Q3_Set: '%s' is not a valid set field\n", type_name ); + trap->ICARUS_SetVar(taskID, entID, type_name, data); break; } diff --git a/codemp/game/g_active.c b/codemp/game/g_active.c index 8fd94adc50..2e7e7e3881 100644 --- a/codemp/game/g_active.c +++ b/codemp/game/g_active.c @@ -25,17 +25,16 @@ along with this program; if not, see . #include "g_local.h" #include "bg_saga.h" -extern void Jedi_Cloak( gentity_t *self ); -extern void Jedi_Decloak( gentity_t *self ); +extern void Jedi_Cloak(gentity_t *self); +extern void Jedi_Decloak(gentity_t *self); -qboolean PM_SaberInTransition( int move ); -qboolean PM_SaberInStart( int move ); -qboolean PM_SaberInReturn( int move ); -qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel ); +qboolean PM_SaberInTransition(int move); +qboolean PM_SaberInStart(int move); +qboolean PM_SaberInReturn(int move); +qboolean WP_SaberStyleValidForSaber(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel); qboolean saberCheckKnockdown_DuelLoss(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other); -void P_SetTwitchInfo(gclient_t *client) -{ +void P_SetTwitchInfo(gclient_t *client) { client->ps.painTime = level.time; client->ps.painDirection ^= 1; } @@ -50,23 +49,23 @@ damage values to that client for pain blends and kicks, and global pain sound events for all clients. =============== */ -void P_DamageFeedback( gentity_t *player ) { - gclient_t *client; - float count; - vec3_t angles; +void P_DamageFeedback(gentity_t *player) { + gclient_t *client; + float count; + vec3_t angles; client = player->client; - if ( client->ps.pm_type == PM_DEAD || client->tempSpectate >= level.time ) { + if (client->ps.pm_type == PM_DEAD || client->tempSpectate >= level.time) { return; } // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor; - if ( count == 0 ) { - return; // didn't take any damage + if (count == 0) { + return; // didn't take any damage } - if ( count > 255 ) { + if (count > 255) { count = 255; } @@ -74,56 +73,49 @@ void P_DamageFeedback( gentity_t *player ) { // world damage (falling, slime, etc) uses a special code // to make the blend blob centered instead of positional - if ( client->damage_fromWorld ) { + if (client->damage_fromWorld) { client->ps.damagePitch = 255; client->ps.damageYaw = 255; client->damage_fromWorld = qfalse; } else { - vectoangles( client->damage_from, angles ); - client->ps.damagePitch = angles[PITCH]/360.0 * 256; - client->ps.damageYaw = angles[YAW]/360.0 * 256; + vectoangles(client->damage_from, angles); + client->ps.damagePitch = angles[PITCH] / 360.0 * 256; + client->ps.damageYaw = angles[YAW] / 360.0 * 256; - //cap them since we can't send negative values in here across the net - if (client->ps.damagePitch < 0) - { + // cap them since we can't send negative values in here across the net + if (client->ps.damagePitch < 0) { client->ps.damagePitch = 0; } - if (client->ps.damageYaw < 0) - { + if (client->ps.damageYaw < 0) { client->ps.damageYaw = 0; } } // play an appropriate pain sound - if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) && !(player->s.eFlags & EF_DEAD) && (player->client->tempSpectate < level.time)) { + if ((level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) && !(player->s.eFlags & EF_DEAD) && + (player->client->tempSpectate < level.time)) { // don't do more than two pain sounds a second // nmckenzie: also don't make him loud and whiny if he's only getting nicked. - if ( level.time - client->ps.painTime < 500 || count < 10) { + if (level.time - client->ps.painTime < 500 || count < 10) { return; } P_SetTwitchInfo(client); player->pain_debounce_time = level.time + 700; - G_AddEvent( player, EV_PAIN, player->health ); + G_AddEvent(player, EV_PAIN, player->health); client->ps.damageEvent++; - if (client->damage_armor && !client->damage_blood) - { - client->ps.damageType = 1; //pure shields - } - else if (client->damage_armor) - { - client->ps.damageType = 2; //shields and health - } - else - { - client->ps.damageType = 0; //pure health + if (client->damage_armor && !client->damage_blood) { + client->ps.damageType = 1; // pure shields + } else if (client->damage_armor) { + client->ps.damageType = 2; // shields and health + } else { + client->ps.damageType = 0; // pure health } } - client->ps.damageCount = count; // @@ -134,8 +126,6 @@ void P_DamageFeedback( gentity_t *player ) { client->damage_knockback = 0; } - - /* ============= P_WorldEffects @@ -143,38 +133,38 @@ P_WorldEffects Check for lava / slime contents and drowning ============= */ -void P_WorldEffects( gentity_t *ent ) { +void P_WorldEffects(gentity_t *ent) { #ifdef BASE_COMPAT - qboolean envirosuit = qfalse; + qboolean envirosuit = qfalse; #endif - int waterlevel; + int waterlevel; - if ( ent->client->noclip ) { - ent->client->airOutTime = level.time + 12000; // don't need air + if (ent->client->noclip) { + ent->client->airOutTime = level.time + 12000; // don't need air return; } waterlevel = ent->waterlevel; - #ifdef BASE_COMPAT - envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time; - #endif // BASE_COMPAT +#ifdef BASE_COMPAT + envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time; +#endif // BASE_COMPAT // // check for drowning // - if ( waterlevel == 3 ) { - #ifdef BASE_COMPAT - // envirosuit give air - if ( envirosuit ) - ent->client->airOutTime = level.time + 10000; - #endif // BASE_COMPAT + if (waterlevel == 3) { +#ifdef BASE_COMPAT + // envirosuit give air + if (envirosuit) + ent->client->airOutTime = level.time + 10000; +#endif // BASE_COMPAT // if out of air, start drowning - if ( ent->client->airOutTime < level.time) { + if (ent->client->airOutTime < level.time) { // drown! ent->client->airOutTime += 1000; - if ( ent->health > 0 && ent->client->tempSpectate < level.time ) { + if (ent->health > 0 && ent->client->tempSpectate < level.time) { // take more damage the longer underwater ent->damage += 2; if (ent->damage > 15) @@ -182,8 +172,8 @@ void P_WorldEffects( gentity_t *ent ) { // play a gurp sound instead of a normal pain sound if (ent->health <= ent->damage) { - G_Sound(ent, CHAN_VOICE, G_SoundIndex(/*"*drown.wav"*/"sound/player/gurp1.wav")); - } else if (rand()&1) { + G_Sound(ent, CHAN_VOICE, G_SoundIndex(/*"*drown.wav"*/ "sound/player/gurp1.wav")); + } else if (rand() & 1) { G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp1.wav")); } else { G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp2.wav")); @@ -192,8 +182,7 @@ void P_WorldEffects( gentity_t *ent ) { // don't play a normal pain sound ent->pain_debounce_time = level.time + 200; - G_Damage (ent, NULL, NULL, NULL, NULL, - ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); + G_Damage(ent, NULL, NULL, NULL, NULL, ent->damage, DAMAGE_NO_ARMOR, MOD_WATER); } } } else { @@ -204,73 +193,54 @@ void P_WorldEffects( gentity_t *ent ) { // // check for sizzle damage (move to pmove?) // - if ( waterlevel && (ent->watertype & (CONTENTS_LAVA|CONTENTS_SLIME)) ) - { - if ( ent->health > 0 && ent->client->tempSpectate < level.time && ent->pain_debounce_time <= level.time ) - { - #ifdef BASE_COMPAT - if ( envirosuit ) - G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 ); + if (waterlevel && (ent->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) { + if (ent->health > 0 && ent->client->tempSpectate < level.time && ent->pain_debounce_time <= level.time) { +#ifdef BASE_COMPAT + if (envirosuit) + G_AddEvent(ent, EV_POWERUP_BATTLESUIT, 0); else - #endif +#endif { - if ( ent->watertype & CONTENTS_LAVA ) - G_Damage( ent, NULL, NULL, NULL, NULL, 30*waterlevel, 0, MOD_LAVA ); + if (ent->watertype & CONTENTS_LAVA) + G_Damage(ent, NULL, NULL, NULL, NULL, 30 * waterlevel, 0, MOD_LAVA); - if ( ent->watertype & CONTENTS_SLIME ) - G_Damage( ent, NULL, NULL, NULL, NULL, 10*waterlevel, 0, MOD_SLIME ); + if (ent->watertype & CONTENTS_SLIME) + G_Damage(ent, NULL, NULL, NULL, NULL, 10 * waterlevel, 0, MOD_SLIME); } } } } - - - - //============================================================== -extern void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ); -void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) -{ +extern void G_ApplyKnockback(gentity_t *targ, vec3_t newDir, float knockback); +void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf) { float magnitude, my_mass; - vec3_t velocity; + vec3_t velocity; int cont; qboolean easyBreakBrush = qtrue; - if( self->client ) - { - VectorCopy( self->client->ps.velocity, velocity ); - if( !self->mass ) - { + if (self->client) { + VectorCopy(self->client->ps.velocity, velocity); + if (!self->mass) { my_mass = 10; - } - else - { + } else { my_mass = self->mass; } - } - else - { - VectorCopy( self->s.pos.trDelta, velocity ); - if ( self->s.pos.trType == TR_GRAVITY ) - { + } else { + VectorCopy(self->s.pos.trDelta, velocity); + if (self->s.pos.trType == TR_GRAVITY) { velocity[2] -= 0.25f * g_gravity.value; } - if( !self->mass ) - { + if (!self->mass) { my_mass = 1; - } - else if ( self->mass <= 10 ) - { + } else if (self->mass <= 10) { my_mass = 10; - } - else - { - my_mass = self->mass;///10; + } else { + my_mass = self->mass; /// 10; } } - magnitude = VectorLength( velocity ) * my_mass / 10; + magnitude = VectorLength(velocity) * my_mass / 10; /* if(pointcontents(self.absmax)==CONTENT_WATER)//FIXME: or other watertypes @@ -282,55 +252,43 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) if(self.frozen>0&&magnitude<300&&self.flags&FL_ONGROUND&&loser==world&&self.velocity_z<-20&&self.last_onground+0.3material == MAT_GLASS - || other->material == MAT_GLASS_METAL - || other->material == MAT_GRATE1 - || ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/)) - || (other->r.svFlags&SVF_GLASS_BRUSH) ) - { + if (other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || + ((other->flags & FL_BBRUSH) && (other->spawnflags & 8 /*THIN*/)) || (other->r.svFlags & SVF_GLASS_BRUSH)) { easyBreakBrush = qtrue; } - if ( !self->client || self->client->ps.lastOnGround+300client->ps.lastOnGround+100 < level.time && easyBreakBrush ) ) - { + if (!self->client || self->client->ps.lastOnGround + 300 < level.time || (self->client->ps.lastOnGround + 100 < level.time && easyBreakBrush)) { vec3_t dir1, dir2; float force = 0, dot; - if ( easyBreakBrush ) + if (easyBreakBrush) magnitude *= 2; - //damage them - if ( magnitude >= 100 && other->s.number < ENTITYNUM_WORLD ) - { - VectorCopy( velocity, dir1 ); - VectorNormalize( dir1 ); - if( VectorCompare( other->r.currentOrigin, vec3_origin ) ) - {//a brush with no origin - VectorCopy ( dir1, dir2 ); - } - else - { - VectorSubtract( other->r.currentOrigin, self->r.currentOrigin, dir2 ); - VectorNormalize( dir2 ); + // damage them + if (magnitude >= 100 && other->s.number < ENTITYNUM_WORLD) { + VectorCopy(velocity, dir1); + VectorNormalize(dir1); + if (VectorCompare(other->r.currentOrigin, vec3_origin)) { // a brush with no origin + VectorCopy(dir1, dir2); + } else { + VectorSubtract(other->r.currentOrigin, self->r.currentOrigin, dir2); + VectorNormalize(dir2); } - dot = DotProduct( dir1, dir2 ); + dot = DotProduct(dir1, dir2); - if ( dot >= 0.2 ) - { + if (dot >= 0.2) { force = dot; - } - else - { + } else { force = 0; } - force *= (magnitude/50); + force *= (magnitude / 50); - cont = trap->PointContents( other->r.absmax, other->s.number ); - if( (cont&CONTENTS_WATER) )//|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes + cont = trap->PointContents(other->r.absmax, other->s.number); + if ((cont & CONTENTS_WATER)) //|| (self.classname=="barrel"&&self.aflag))//FIXME: or other watertypes { - force /= 3; //water absorbs 2/3 velocity + force /= 3; // water absorbs 2/3 velocity } /* @@ -338,84 +296,74 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) force=10; */ - if( ( force >= 1 && other->s.number >= MAX_CLIENTS ) || force >= 10) - { - /* - dprint("Damage other ("); - dprint(loser.classname); - dprint("): "); - dprint(ftos(force)); - dprint("\n"); - */ - if ( other->r.svFlags & SVF_GLASS_BRUSH ) - { - other->splashRadius = (float)(self->r.maxs[0] - self->r.mins[0])/4.0f; - } - if ( other->takedamage ) - { - G_Damage( other, self, self, velocity, self->r.currentOrigin, force, DAMAGE_NO_ARMOR, MOD_CRUSH);//FIXME: MOD_IMPACT + if ((force >= 1 && other->s.number >= MAX_CLIENTS) || force >= 10) { + /* + dprint("Damage other ("); + dprint(loser.classname); + dprint("): "); + dprint(ftos(force)); + dprint("\n"); + */ + if (other->r.svFlags & SVF_GLASS_BRUSH) { + other->splashRadius = (float)(self->r.maxs[0] - self->r.mins[0]) / 4.0f; } - else - { - G_ApplyKnockback( other, dir2, force ); + if (other->takedamage) { + G_Damage(other, self, self, velocity, self->r.currentOrigin, force, DAMAGE_NO_ARMOR, MOD_CRUSH); // FIXME: MOD_IMPACT + } else { + G_ApplyKnockback(other, dir2, force); } } } - if ( damageSelf && self->takedamage ) - { - //Now damage me - //FIXME: more lenient falling damage, especially for when driving a vehicle - if ( self->client && self->client->ps.fd.forceJumpZStart ) - {//we were force-jumping - if ( self->r.currentOrigin[2] >= self->client->ps.fd.forceJumpZStart ) - {//we landed at same height or higher than we landed + if (damageSelf && self->takedamage) { + // Now damage me + // FIXME: more lenient falling damage, especially for when driving a vehicle + if (self->client && self->client->ps.fd.forceJumpZStart) { // we were force-jumping + if (self->r.currentOrigin[2] >= self->client->ps.fd.forceJumpZStart) { // we landed at same height or higher than we landed magnitude = 0; - } - else - {//FIXME: take off some of it, at least? - magnitude = (self->client->ps.fd.forceJumpZStart-self->r.currentOrigin[2])/3; + } else { // FIXME: take off some of it, at least? + magnitude = (self->client->ps.fd.forceJumpZStart - self->r.currentOrigin[2]) / 3; } } - //if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet - if( ( magnitude >= 100 + self->health && self->s.number >= MAX_CLIENTS && self->s.weapon != WP_SABER ) || ( magnitude >= 700 ) )//&& self.safe_time < level.time ))//health here is used to simulate structural integrity - { - if ( (self->s.weapon == WP_SABER) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && magnitude < 1000 ) - {//players and jedi take less impact damage - //allow for some lenience on high falls - magnitude /= 2; - /* - if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage - { - magnitude/=2; - } - */ - } - magnitude /= 40; - magnitude = magnitude - force/2;//If damage other, subtract half of that damage off of own injury - if ( magnitude >= 1 ) + // if(self.classname!="monster_mezzoman"&&self.netname!="spider")//Cats always land on their feet + if ((magnitude >= 100 + self->health && self->s.number >= MAX_CLIENTS && self->s.weapon != WP_SABER) || + (magnitude >= 700)) //&& self.safe_time < level.time ))//health here is used to simulate structural integrity + { + if ((self->s.weapon == WP_SABER) && self->client && self->client->ps.groundEntityNum < ENTITYNUM_NONE && + magnitude < 1000) { // players and jedi take less impact damage + // allow for some lenience on high falls + magnitude /= 2; + /* + if ( self.absorb_time >= time )//crouching on impact absorbs 1/2 the damage { - //FIXME: Put in a thingtype impact sound function - /* - dprint("Damage self ("); - dprint(self.classname); - dprint("): "); - dprint(ftos(magnitude)); - dprint("\n"); - */ - /* - if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 ) - return; - */ - G_Damage( self, NULL, NULL, NULL, self->r.currentOrigin, magnitude/2, DAMAGE_NO_ARMOR, MOD_FALLING );//FIXME: MOD_IMPACT + magnitude/=2; } + */ } + magnitude /= 40; + magnitude = magnitude - force / 2; // If damage other, subtract half of that damage off of own injury + if (magnitude >= 1) { + // FIXME: Put in a thingtype impact sound function + /* + dprint("Damage self ("); + dprint(self.classname); + dprint("): "); + dprint(ftos(magnitude)); + dprint("\n"); + */ + /* + if ( self.classname=="player_sheep "&& self.flags&FL_ONGROUND && self.velocity_z > -50 ) + return; + */ + G_Damage(self, NULL, NULL, NULL, self->r.currentOrigin, magnitude / 2, DAMAGE_NO_ARMOR, MOD_FALLING); // FIXME: MOD_IMPACT + } + } } - //FIXME: slow my velocity some? + // FIXME: slow my velocity some? // NOTENOTE We don't use lastimpact as of yet -// self->lastImpact = level.time; + // self->lastImpact = level.time; /* if(self.flags&FL_ONGROUND) @@ -424,16 +372,12 @@ void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ) } } -void Client_CheckImpactBBrush( gentity_t *self, gentity_t *other ) -{ - if ( !other || !other->inuse ) - { +void Client_CheckImpactBBrush(gentity_t *self, gentity_t *other) { + if (!other || !other->inuse) { return; } - if (!self || !self->inuse || !self->client || - self->client->tempSpectate >= level.time || - self->client->sess.sessionTeam == TEAM_SPECTATOR) - { //hmm.. let's not let spectators ram into breakables. + if (!self || !self->inuse || !self->client || self->client->tempSpectate >= level.time || + self->client->sess.sessionTeam == TEAM_SPECTATOR) { // hmm.. let's not let spectators ram into breakables. return; } @@ -444,40 +388,29 @@ void Client_CheckImpactBBrush( gentity_t *self, gentity_t *other ) } */ - if ( other->material == MAT_GLASS - || other->material == MAT_GLASS_METAL - || other->material == MAT_GRATE1 - || ((other->flags&FL_BBRUSH)&&(other->spawnflags&8/*THIN*/)) - || ((other->flags&FL_BBRUSH)&&(other->health<=10)) - || (other->r.svFlags&SVF_GLASS_BRUSH) ) - {//clients only do impact damage against easy-break breakables - DoImpact( self, other, qfalse ); + if (other->material == MAT_GLASS || other->material == MAT_GLASS_METAL || other->material == MAT_GRATE1 || + ((other->flags & FL_BBRUSH) && (other->spawnflags & 8 /*THIN*/)) || ((other->flags & FL_BBRUSH) && (other->health <= 10)) || + (other->r.svFlags & SVF_GLASS_BRUSH)) { // clients only do impact damage against easy-break breakables + DoImpact(self, other, qfalse); } } - /* =============== G_SetClientSound =============== */ -void G_SetClientSound( gentity_t *ent ) { - if (ent->client && ent->client->isHacking) - { //loop hacking sound +void G_SetClientSound(gentity_t *ent) { + if (ent->client && ent->client->isHacking) { // loop hacking sound ent->client->ps.loopSound = level.snd_hack; ent->s.loopIsSoundset = qfalse; - } - else if (ent->client && ent->client->isMedHealed > level.time) - { //loop healing sound + } else if (ent->client && ent->client->isMedHealed > level.time) { // loop healing sound ent->client->ps.loopSound = level.snd_medHealed; ent->s.loopIsSoundset = qfalse; - } - else if (ent->client && ent->client->isMedSupplied > level.time) - { //loop supplying sound + } else if (ent->client && ent->client->isMedSupplied > level.time) { // loop supplying sound ent->client->ps.loopSound = level.snd_medSupplied; ent->s.loopIsSoundset = qfalse; - } - else if (ent->client && ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) { + } else if (ent->client && ent->waterlevel && (ent->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) { ent->client->ps.loopSound = level.snd_fry; ent->s.loopIsSoundset = qfalse; } else if (ent->client) { @@ -489,8 +422,6 @@ void G_SetClientSound( gentity_t *ent ) { } } - - //============================================================== /* @@ -498,34 +429,33 @@ void G_SetClientSound( gentity_t *ent ) { ClientImpacts ============== */ -void ClientImpacts( gentity_t *ent, pmove_t *pmove ) { - int i, j; - trace_t trace; - gentity_t *other; - - memset( &trace, 0, sizeof( trace ) ); - for (i=0 ; inumtouch ; i++) { - for (j=0 ; jtouchents[j] == pmove->touchents[i] ) { +void ClientImpacts(gentity_t *ent, pmove_t *pmove) { + int i, j; + trace_t trace; + gentity_t *other; + + memset(&trace, 0, sizeof(trace)); + for (i = 0; i < pmove->numtouch; i++) { + for (j = 0; j < i; j++) { + if (pmove->touchents[j] == pmove->touchents[i]) { break; } } if (j != i) { - continue; // duplicated + continue; // duplicated } - other = &g_entities[ pmove->touchents[i] ]; + other = &g_entities[pmove->touchents[i]]; - if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) { - ent->touch( ent, other, &trace ); + if ((ent->r.svFlags & SVF_BOT) && (ent->touch)) { + ent->touch(ent, other, &trace); } - if ( !other->touch ) { + if (!other->touch) { continue; } - other->touch( other, ent, &trace ); + other->touch(other, ent, &trace); } - } /* @@ -536,45 +466,45 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_TouchTriggers( gentity_t *ent ) { - int i, num; - int touch[MAX_GENTITIES]; - gentity_t *hit; - trace_t trace; - vec3_t mins, maxs; - static vec3_t range = { 40, 40, 52 }; - - if ( !ent->client ) { +void G_TouchTriggers(gentity_t *ent) { + int i, num; + int touch[MAX_GENTITIES]; + gentity_t *hit; + trace_t trace; + vec3_t mins, maxs; + static vec3_t range = {40, 40, 52}; + + if (!ent->client) { return; } // dead clients don't activate triggers! - if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (ent->client->ps.stats[STAT_HEALTH] <= 0) { return; } - VectorSubtract( ent->client->ps.origin, range, mins ); - VectorAdd( ent->client->ps.origin, range, maxs ); + VectorSubtract(ent->client->ps.origin, range, mins); + VectorAdd(ent->client->ps.origin, range, maxs); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->r.absmin, because that has a one unit pad - VectorAdd( ent->client->ps.origin, ent->r.mins, mins ); - VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs ); + VectorAdd(ent->client->ps.origin, ent->r.mins, mins); + VectorAdd(ent->client->ps.origin, ent->r.maxs, maxs); - for ( i=0 ; itouch && !ent->touch ) { + if (!hit->touch && !ent->touch) { continue; } - if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) { + if (!(hit->r.contents & CONTENTS_TRIGGER)) { continue; } // ignore most entities if a spectator - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - if ( hit->s.eType != ET_TELEPORT_TRIGGER && + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + if (hit->s.eType != ET_TELEPORT_TRIGGER && // this is ugly but adding a new ET_? type will // most likely cause network incompatibilities hit->touch != Touch_DoorTrigger) { @@ -584,35 +514,34 @@ void G_TouchTriggers( gentity_t *ent ) { // use seperate code for determining if an item is picked up // so you don't have to actually contact its bounding box - if ( hit->s.eType == ET_ITEM ) { - if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) { + if (hit->s.eType == ET_ITEM) { + if (!BG_PlayerTouchesItem(&ent->client->ps, &hit->s, level.time)) { continue; } } else { - if ( !trap->EntityContact( mins, maxs, (sharedEntity_t *)hit, qfalse ) ) { + if (!trap->EntityContact(mins, maxs, (sharedEntity_t *)hit, qfalse)) { continue; } } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->touch ) { - hit->touch (hit, ent, &trace); + if (hit->touch) { + hit->touch(hit, ent, &trace); } - if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) { - ent->touch( ent, hit, &trace ); + if ((ent->r.svFlags & SVF_BOT) && (ent->touch)) { + ent->touch(ent, hit, &trace); } } // if we didn't touch a jump pad this pmove frame - if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) { + if (ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount) { ent->client->ps.jumppad_frame = 0; ent->client->ps.jumppad_ent = 0; } } - /* ============ G_MoverTouchTriggers @@ -621,80 +550,69 @@ Find all trigger entities that ent's current position touches. Spectators will only interact with teleporters. ============ */ -void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ) -{ - int i, num; - float step, stepSize, dist; - int touch[MAX_GENTITIES]; - gentity_t *hit; - trace_t trace; - vec3_t mins, maxs, dir, size, checkSpot; - const vec3_t range = { 40, 40, 52 }; +void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg) { + int i, num; + float step, stepSize, dist; + int touch[MAX_GENTITIES]; + gentity_t *hit; + trace_t trace; + vec3_t mins, maxs, dir, size, checkSpot; + const vec3_t range = {40, 40, 52}; // non-moving movers don't hit triggers! - if ( !VectorLengthSquared( ent->s.pos.trDelta ) ) - { + if (!VectorLengthSquared(ent->s.pos.trDelta)) { return; } - VectorSubtract( ent->r.mins, ent->r.maxs, size ); - stepSize = VectorLength( size ); - if ( stepSize < 1 ) - { + VectorSubtract(ent->r.mins, ent->r.maxs, size); + stepSize = VectorLength(size); + if (stepSize < 1) { stepSize = 1; } - VectorSubtract( ent->r.currentOrigin, oldOrg, dir ); - dist = VectorNormalize( dir ); - for ( step = 0; step <= dist; step += stepSize ) - { - VectorMA( ent->r.currentOrigin, step, dir, checkSpot ); - VectorSubtract( checkSpot, range, mins ); - VectorAdd( checkSpot, range, maxs ); + VectorSubtract(ent->r.currentOrigin, oldOrg, dir); + dist = VectorNormalize(dir); + for (step = 0; step <= dist; step += stepSize) { + VectorMA(ent->r.currentOrigin, step, dir, checkSpot); + VectorSubtract(checkSpot, range, mins); + VectorAdd(checkSpot, range, maxs); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); // can't use ent->r.absmin, because that has a one unit pad - VectorAdd( checkSpot, ent->r.mins, mins ); - VectorAdd( checkSpot, ent->r.maxs, maxs ); + VectorAdd(checkSpot, ent->r.mins, mins); + VectorAdd(checkSpot, ent->r.maxs, maxs); - for ( i=0 ; is.eType != ET_PUSH_TRIGGER ) - { + if (hit->s.eType != ET_PUSH_TRIGGER) { continue; } - if ( hit->touch == NULL ) - { + if (hit->touch == NULL) { continue; } - if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) - { + if (!(hit->r.contents & CONTENTS_TRIGGER)) { continue; } - - if ( !trap->EntityContact( mins, maxs, (sharedEntity_t *)hit, qfalse ) ) - { + if (!trap->EntityContact(mins, maxs, (sharedEntity_t *)hit, qfalse)) { continue; } - memset( &trace, 0, sizeof(trace) ); + memset(&trace, 0, sizeof(trace)); - if ( hit->touch != NULL ) - { + if (hit->touch != NULL) { hit->touch(hit, ent, &trace); } } } } -static void SV_PMTrace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask ) { - trap->Trace( results, start, mins, maxs, end, passEntityNum, contentMask, qfalse, 0, 10 ); +static void SV_PMTrace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentMask) { + trap->Trace(results, start, mins, maxs, end, passEntityNum, contentMask, qfalse, 0, 10); } /* @@ -702,29 +620,29 @@ static void SV_PMTrace( trace_t *results, const vec3_t start, const vec3_t mins, SpectatorThink ================= */ -void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) { - pmove_t pmove; - gclient_t *client; +void SpectatorThink(gentity_t *ent, usercmd_t *ucmd) { + pmove_t pmove; + gclient_t *client; client = ent->client; - if ( client->sess.spectatorState != SPECTATOR_FOLLOW ) { + if (client->sess.spectatorState != SPECTATOR_FOLLOW) { client->ps.pm_type = PM_SPECTATOR; - client->ps.speed = 400; // faster than normal + client->ps.speed = 400; // faster than normal client->ps.basespeed = 400; - //hmm, shouldn't have an anim if you're a spectator, make sure - //it gets cleared. + // hmm, shouldn't have an anim if you're a spectator, make sure + // it gets cleared. client->ps.legsAnim = 0; client->ps.legsTimer = 0; client->ps.torsoAnim = 0; client->ps.torsoTimer = 0; // set up for pmove - memset (&pmove, 0, sizeof(pmove)); + memset(&pmove, 0, sizeof(pmove)); pmove.ps = &client->ps; pmove.cmd = *ucmd; - pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies + pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies pmove.trace = SV_PMTrace; pmove.pointcontents = trap->PointContents; @@ -733,43 +651,38 @@ void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) { pmove.animations = NULL; pmove.nonHumanoid = qfalse; - //Set up bg entity data + // Set up bg entity data pmove.baseEnt = (bgEntity_t *)g_entities; pmove.entSize = sizeof(gentity_t); // perform a pmove - Pmove (&pmove); + Pmove(&pmove); // save results of pmove - VectorCopy( client->ps.origin, ent->s.origin ); + VectorCopy(client->ps.origin, ent->s.origin); - if (ent->client->tempSpectate < level.time) - { - G_TouchTriggers( ent ); + if (ent->client->tempSpectate < level.time) { + G_TouchTriggers(ent); } - trap->UnlinkEntity( (sharedEntity_t *)ent ); + trap->UnlinkEntity((sharedEntity_t *)ent); } client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; - if (client->tempSpectate < level.time) - { + if (client->tempSpectate < level.time) { // attack button cycles through spectators - if ( (client->buttons & BUTTON_ATTACK) && !(client->oldbuttons & BUTTON_ATTACK) ) - Cmd_FollowCycle_f( ent, 1 ); + if ((client->buttons & BUTTON_ATTACK) && !(client->oldbuttons & BUTTON_ATTACK)) + Cmd_FollowCycle_f(ent, 1); - else if ( client->sess.spectatorState == SPECTATOR_FOLLOW && (client->buttons & BUTTON_ALT_ATTACK) && !(client->oldbuttons & BUTTON_ALT_ATTACK) ) - Cmd_FollowCycle_f( ent, -1 ); + else if (client->sess.spectatorState == SPECTATOR_FOLLOW && (client->buttons & BUTTON_ALT_ATTACK) && !(client->oldbuttons & BUTTON_ALT_ATTACK)) + Cmd_FollowCycle_f(ent, -1); - if (client->sess.spectatorState == SPECTATOR_FOLLOW && (ucmd->upmove > 0)) - { //jump now removes you from follow mode + if (client->sess.spectatorState == SPECTATOR_FOLLOW && (ucmd->upmove > 0)) { // jump now removes you from follow mode StopFollowing(ent); } } } - - /* ================= ClientInactivityTimer @@ -777,26 +690,24 @@ ClientInactivityTimer Returns qfalse if the client is dropped ================= */ -qboolean ClientInactivityTimer( gclient_t *client ) { - if ( ! g_inactivity.integer ) { +qboolean ClientInactivityTimer(gclient_t *client) { + if (!g_inactivity.integer) { // give everyone some time, so if the operator sets g_inactivity during // gameplay, everyone isn't kicked client->inactivityTime = level.time + 60 * 1000; client->inactivityWarning = qfalse; - } else if ( client->pers.cmd.forwardmove || - client->pers.cmd.rightmove || - client->pers.cmd.upmove || - (client->pers.cmd.buttons & (BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) { + } else if (client->pers.cmd.forwardmove || client->pers.cmd.rightmove || client->pers.cmd.upmove || + (client->pers.cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { client->inactivityTime = level.time + g_inactivity.integer * 1000; client->inactivityWarning = qfalse; - } else if ( !client->pers.localClient ) { - if ( level.time > client->inactivityTime ) { - trap->DropClient( client - level.clients, "Dropped due to inactivity" ); + } else if (!client->pers.localClient) { + if (level.time > client->inactivityTime) { + trap->DropClient(client - level.clients, "Dropped due to inactivity"); return qfalse; } - if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) { + if (level.time > client->inactivityTime - 10000 && !client->inactivityWarning) { client->inactivityWarning = qtrue; - trap->SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" ); + trap->SendServerCommand(client - level.clients, "cp \"Ten seconds until inactivity drop!\n\""); } } return qtrue; @@ -809,23 +720,22 @@ ClientTimerActions Actions that happen once a second ================== */ -void ClientTimerActions( gentity_t *ent, int msec ) { - gclient_t *client; +void ClientTimerActions(gentity_t *ent, int msec) { + gclient_t *client; client = ent->client; client->timeResidual += msec; - while ( client->timeResidual >= 1000 ) - { + while (client->timeResidual >= 1000) { client->timeResidual -= 1000; // count down health when over max - if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) { + if (ent->health > client->ps.stats[STAT_MAX_HEALTH]) { ent->health--; } // count down armor when over max - if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) { + if (client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH]) { client->ps.stats[STAT_ARMOR]--; } } @@ -836,7 +746,7 @@ void ClientTimerActions( gentity_t *ent, int msec ) { ClientIntermissionThink ==================== */ -void ClientIntermissionThink( gclient_t *client ) { +void ClientIntermissionThink(gclient_t *client) { client->ps.eFlags &= ~EF_TALK; client->ps.eFlags &= ~EF_FIRING; @@ -845,82 +755,72 @@ void ClientIntermissionThink( gclient_t *client ) { // swap and latch button actions client->oldbuttons = client->buttons; client->buttons = client->pers.cmd.buttons; - if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) { + if (client->buttons & (BUTTON_ATTACK | BUTTON_USE_HOLDABLE) & (client->oldbuttons ^ client->buttons)) { // this used to be an ^1 but once a player says ready, it should stick client->readyToExit = qtrue; } } -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags); -void G_VehicleAttachDroidUnit( gentity_t *vehEnt ) -{ - if ( vehEnt && vehEnt->m_pVehicle && vehEnt->m_pVehicle->m_pDroidUnit != NULL ) - { +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags); +void G_VehicleAttachDroidUnit(gentity_t *vehEnt) { + if (vehEnt && vehEnt->m_pVehicle && vehEnt->m_pVehicle->m_pDroidUnit != NULL) { gentity_t *droidEnt = (gentity_t *)vehEnt->m_pVehicle->m_pDroidUnit; mdxaBone_t boltMatrix; - vec3_t fwd; + vec3_t fwd; - trap->G2API_GetBoltMatrix(vehEnt->ghoul2, 0, vehEnt->m_pVehicle->m_iDroidUnitTag, &boltMatrix, vehEnt->r.currentAngles, vehEnt->r.currentOrigin, level.time, - NULL, vehEnt->modelScale); + trap->G2API_GetBoltMatrix(vehEnt->ghoul2, 0, vehEnt->m_pVehicle->m_iDroidUnitTag, &boltMatrix, vehEnt->r.currentAngles, vehEnt->r.currentOrigin, + level.time, NULL, vehEnt->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droidEnt->r.currentOrigin); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd); - vectoangles( fwd, droidEnt->r.currentAngles ); + vectoangles(fwd, droidEnt->r.currentAngles); - if ( droidEnt->client ) - { - VectorCopy( droidEnt->r.currentAngles, droidEnt->client->ps.viewangles ); - VectorCopy( droidEnt->r.currentOrigin, droidEnt->client->ps.origin ); + if (droidEnt->client) { + VectorCopy(droidEnt->r.currentAngles, droidEnt->client->ps.viewangles); + VectorCopy(droidEnt->r.currentOrigin, droidEnt->client->ps.origin); } - G_SetOrigin( droidEnt, droidEnt->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)droidEnt ); + G_SetOrigin(droidEnt, droidEnt->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)droidEnt); - if ( droidEnt->NPC ) - { - NPC_SetAnim( droidEnt, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); + if (droidEnt->NPC) { + NPC_SetAnim(droidEnt, SETANIM_BOTH, BOTH_STAND2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD); } } } -//called gameside only from pmove code (convenience) -extern qboolean BG_SabersOff( playerState_t *ps ); -void G_CheapWeaponFire(int entNum, int ev) -{ +// called gameside only from pmove code (convenience) +extern qboolean BG_SabersOff(playerState_t *ps); +void G_CheapWeaponFire(int entNum, int ev) { gentity_t *ent = &g_entities[entNum]; - if (!ent->inuse || !ent->client) - { + if (!ent->inuse || !ent->client) { return; } - switch (ev) - { - case EV_FIRE_WEAPON: - if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && - ent->client && ent->client->ps.m_iVehicleNum) - { //a speeder with a pilot - gentity_t *rider = &g_entities[ent->client->ps.m_iVehicleNum-1]; - if (rider->inuse && rider->client) - { //pilot is valid... - if (rider->client->ps.weapon != WP_MELEE && - (rider->client->ps.weapon != WP_SABER || !BG_SabersOff(&rider->client->ps))) - { //can only attack on speeder when using melee or when saber is holstered - break; - } + switch (ev) { + case EV_FIRE_WEAPON: + if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER && ent->client && ent->client->ps.m_iVehicleNum) { // a speeder with a pilot + gentity_t *rider = &g_entities[ent->client->ps.m_iVehicleNum - 1]; + if (rider->inuse && rider->client) { // pilot is valid... + if (rider->client->ps.weapon != WP_MELEE && + (rider->client->ps.weapon != WP_SABER || + !BG_SabersOff(&rider->client->ps))) { // can only attack on speeder when using melee or when saber is holstered + break; } } + } - FireWeapon( ent, qfalse ); - ent->client->dangerTime = level.time; - ent->client->ps.eFlags &= ~EF_INVULNERABLE; - ent->client->invulnerableTimer = 0; - break; - case EV_ALT_FIRE: - FireWeapon( ent, qtrue ); - ent->client->dangerTime = level.time; - ent->client->ps.eFlags &= ~EF_INVULNERABLE; - ent->client->invulnerableTimer = 0; - break; + FireWeapon(ent, qfalse); + ent->client->dangerTime = level.time; + ent->client->ps.eFlags &= ~EF_INVULNERABLE; + ent->client->invulnerableTimer = 0; + break; + case EV_ALT_FIRE: + FireWeapon(ent, qtrue); + ent->client->dangerTime = level.time; + ent->client->ps.eFlags &= ~EF_INVULNERABLE; + ent->client->invulnerableTimer = 0; + break; } } @@ -932,101 +832,83 @@ Events will be passed on to the clients for presentation, but any server game effects are handled here ================ */ -qboolean BG_InKnockDownOnly( int anim ); +qboolean BG_InKnockDownOnly(int anim); -void ClientEvents( gentity_t *ent, int oldEventSequence ) { - int i;//, j; - int event; +void ClientEvents(gentity_t *ent, int oldEventSequence) { + int i; //, j; + int event; gclient_t *client; - int damage; - vec3_t dir; -// vec3_t origin, angles; -// qboolean fired; -// gitem_t *item; -// gentity_t *drop; + int damage; + vec3_t dir; + // vec3_t origin, angles; + // qboolean fired; + // gitem_t *item; + // gentity_t *drop; client = ent->client; - if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) { + if (oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS) { oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS; } - for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) { - event = client->ps.events[ i & (MAX_PS_EVENTS-1) ]; + for (i = oldEventSequence; i < client->ps.eventSequence; i++) { + event = client->ps.events[i & (MAX_PS_EVENTS - 1)]; - switch ( event ) { + switch (event) { case EV_FALL: - case EV_ROLL: - { - int delta = client->ps.eventParms[ i & (MAX_PS_EVENTS-1) ]; - qboolean knockDownage = qfalse; + case EV_ROLL: { + int delta = client->ps.eventParms[i & (MAX_PS_EVENTS - 1)]; + qboolean knockDownage = qfalse; - if (ent->client && ent->client->ps.fallingToDeath) - { - break; - } + if (ent->client && ent->client->ps.fallingToDeath) { + break; + } - if ( ent->s.eType != ET_PLAYER ) - { - break; // not in the player model - } + if (ent->s.eType != ET_PLAYER) { + break; // not in the player model + } - if ( dmflags.integer & DF_NO_FALLING ) - { - break; - } + if (dmflags.integer & DF_NO_FALLING) { + break; + } - if (BG_InKnockDownOnly(ent->client->ps.legsAnim)) - { - if (delta <= 14) - { - break; - } - knockDownage = qtrue; + if (BG_InKnockDownOnly(ent->client->ps.legsAnim)) { + if (delta <= 14) { + break; } - else - { - if (delta <= 44) - { - break; - } + knockDownage = qtrue; + } else { + if (delta <= 44) { + break; } + } - if (knockDownage) - { - damage = delta*1; //you suffer for falling unprepared. A lot. Makes throws and things useful, and more realistic I suppose. - } - else - { - if (level.gametype == GT_SIEGE && - delta > 60) - { //longer falls hurt more - damage = delta*1; //good enough for now, I guess - } - else - { - damage = delta*0.16; //good enough for now, I guess - } + if (knockDownage) { + damage = delta * 1; // you suffer for falling unprepared. A lot. Makes throws and things useful, and more realistic I suppose. + } else { + if (level.gametype == GT_SIEGE && delta > 60) { // longer falls hurt more + damage = delta * 1; // good enough for now, I guess + } else { + damage = delta * 0.16; // good enough for now, I guess } + } - VectorSet (dir, 0, 0, 1); - ent->pain_debounce_time = level.time + 200; // no normal pain sound - G_Damage (ent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING); + VectorSet(dir, 0, 0, 1); + ent->pain_debounce_time = level.time + 200; // no normal pain sound + G_Damage(ent, NULL, NULL, NULL, NULL, damage, DAMAGE_NO_ARMOR, MOD_FALLING); - if (ent->health < 1) - { - G_Sound(ent, CHAN_AUTO, G_SoundIndex( "sound/player/fallsplat.wav" )); - } + if (ent->health < 1) { + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/player/fallsplat.wav")); } - break; + } break; case EV_FIRE_WEAPON: - FireWeapon( ent, qfalse ); + FireWeapon(ent, qfalse); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; break; case EV_ALT_FIRE: - FireWeapon( ent, qtrue ); + FireWeapon(ent, qtrue); ent->client->dangerTime = level.time; ent->client->ps.eFlags &= ~EF_INVULNERABLE; ent->client->invulnerableTimer = 0; @@ -1038,45 +920,44 @@ void ClientEvents( gentity_t *ent, int oldEventSequence ) { ent->client->invulnerableTimer = 0; break; - //rww - Note that these must be in the same order (ITEM#-wise) as they are in holdable_t - case EV_USE_ITEM1: //seeker droid + // rww - Note that these must be in the same order (ITEM#-wise) as they are in holdable_t + case EV_USE_ITEM1: // seeker droid ItemUse_Seeker(ent); break; - case EV_USE_ITEM2: //shield + case EV_USE_ITEM2: // shield ItemUse_Shield(ent); break; - case EV_USE_ITEM3: //medpack + case EV_USE_ITEM3: // medpack ItemUse_MedPack(ent); break; - case EV_USE_ITEM4: //big medpack + case EV_USE_ITEM4: // big medpack ItemUse_MedPack_Big(ent); break; - case EV_USE_ITEM5: //binoculars + case EV_USE_ITEM5: // binoculars ItemUse_Binoculars(ent); break; - case EV_USE_ITEM6: //sentry gun + case EV_USE_ITEM6: // sentry gun ItemUse_Sentry(ent); break; - case EV_USE_ITEM7: //jetpack + case EV_USE_ITEM7: // jetpack ItemUse_Jetpack(ent); break; - case EV_USE_ITEM8: //health disp - //ItemUse_UseDisp(ent, HI_HEALTHDISP); + case EV_USE_ITEM8: // health disp + // ItemUse_UseDisp(ent, HI_HEALTHDISP); break; - case EV_USE_ITEM9: //ammo disp - //ItemUse_UseDisp(ent, HI_AMMODISP); + case EV_USE_ITEM9: // ammo disp + // ItemUse_UseDisp(ent, HI_AMMODISP); break; - case EV_USE_ITEM10: //eweb + case EV_USE_ITEM10: // eweb ItemUse_UseEWeb(ent); break; - case EV_USE_ITEM11: //cloak + case EV_USE_ITEM11: // cloak ItemUse_UseCloak(ent); break; default: break; } } - } /* @@ -1084,24 +965,24 @@ void ClientEvents( gentity_t *ent, int oldEventSequence ) { SendPendingPredictableEvents ============== */ -void SendPendingPredictableEvents( playerState_t *ps ) { +void SendPendingPredictableEvents(playerState_t *ps) { gentity_t *t; int event, seq; int extEvent, number; // if there are still events pending - if ( ps->entityEventSequence < ps->eventSequence ) { + if (ps->entityEventSequence < ps->eventSequence) { // create a temporary entity for this event which is sent to everyone // except the client who generated the event - seq = ps->entityEventSequence & (MAX_PS_EVENTS-1); - event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 ); + seq = ps->entityEventSequence & (MAX_PS_EVENTS - 1); + event = ps->events[seq] | ((ps->entityEventSequence & 3) << 8); // set external event to zero before calling BG_PlayerStateToEntityState extEvent = ps->externalEvent; ps->externalEvent = 0; // create temporary entity for event - t = G_TempEntity( ps->origin, event ); + t = G_TempEntity(ps->origin, event); number = t->s.number; - BG_PlayerStateToEntityState( ps, &t->s, qtrue ); + BG_PlayerStateToEntityState(ps, &t->s, qtrue); t->s.number = number; t->s.eType = ET_EVENTS + event; t->s.eFlags |= EF_PLAYER_EVENT; @@ -1116,10 +997,10 @@ void SendPendingPredictableEvents( playerState_t *ps ) { static const float maxJediMasterDistance = 2500.0f * 2500.0f; // x^2, optimisation static const float maxJediMasterFOV = 100.0f; -static const float maxForceSightDistance = Square( 1500.0f ) * 1500.0f; // x^2, optimisation +static const float maxForceSightDistance = Square(1500.0f) * 1500.0f; // x^2, optimisation static const float maxForceSightFOV = 100.0f; -void G_UpdateClientBroadcasts( gentity_t *self ) { +void G_UpdateClientBroadcasts(gentity_t *self) { int i; gentity_t *other; @@ -1131,90 +1012,80 @@ void G_UpdateClientBroadcasts( gentity_t *self ) { self->r.broadcastClients[0] = 0u; self->r.broadcastClients[1] = 0u; - for ( i = 0, other = g_entities; i < MAX_CLIENTS; i++, other++ ) { + for (i = 0, other = g_entities; i < MAX_CLIENTS; i++, other++) { qboolean send = qfalse; float dist; vec3_t angles; - if ( !other->inuse || other->client->pers.connected != CON_CONNECTED ) { + if (!other->inuse || other->client->pers.connected != CON_CONNECTED) { // no need to compute visibility for non-connected clients continue; } - if ( other == self ) { + if (other == self) { // we are always sent to ourselves anyway, this is purely an optimisation continue; } - VectorSubtract( self->client->ps.origin, other->client->ps.origin, angles ); - dist = VectorLengthSquared( angles ); - vectoangles( angles, angles ); + VectorSubtract(self->client->ps.origin, other->client->ps.origin, angles); + dist = VectorLengthSquared(angles); + vectoangles(angles, angles); // broadcast jedi master to everyone if we are in distance/field of view - if ( level.gametype == GT_JEDIMASTER && self->client->ps.isJediMaster ) { - if ( dist < maxJediMasterDistance - && InFieldOfVision( other->client->ps.viewangles, maxJediMasterFOV, angles ) ) - { + if (level.gametype == GT_JEDIMASTER && self->client->ps.isJediMaster) { + if (dist < maxJediMasterDistance && InFieldOfVision(other->client->ps.viewangles, maxJediMasterFOV, angles)) { send = qtrue; } } // broadcast this client to everyone using force sight if we are in distance/field of view - if ( (other->client->ps.fd.forcePowersActive & (1 << FP_SEE)) ) { - if ( dist < maxForceSightDistance - && InFieldOfVision( other->client->ps.viewangles, maxForceSightFOV, angles ) ) - { + if ((other->client->ps.fd.forcePowersActive & (1 << FP_SEE))) { + if (dist < maxForceSightDistance && InFieldOfVision(other->client->ps.viewangles, maxForceSightFOV, angles)) { send = qtrue; } } - if ( send ) { - Q_AddToBitflags( self->r.broadcastClients, i, 32 ); + if (send) { + Q_AddToBitflags(self->r.broadcastClients, i, 32); } } - trap->LinkEntity( (sharedEntity_t *)self ); + trap->LinkEntity((sharedEntity_t *)self); } -void G_AddPushVecToUcmd( gentity_t *self, usercmd_t *ucmd ) -{ - vec3_t forward, right, moveDir; - float pushSpeed, fMove, rMove; +void G_AddPushVecToUcmd(gentity_t *self, usercmd_t *ucmd) { + vec3_t forward, right, moveDir; + float pushSpeed, fMove, rMove; - if ( !self->client ) - { + if (!self->client) { return; } pushSpeed = VectorLengthSquared(self->client->pushVec); - if(!pushSpeed) - {//not being pushed + if (!pushSpeed) { // not being pushed return; } AngleVectors(self->client->ps.viewangles, forward, right, NULL); - VectorScale(forward, ucmd->forwardmove/127.0f * self->client->ps.speed, moveDir); - VectorMA(moveDir, ucmd->rightmove/127.0f * self->client->ps.speed, right, moveDir); - //moveDir is now our intended move velocity + VectorScale(forward, ucmd->forwardmove / 127.0f * self->client->ps.speed, moveDir); + VectorMA(moveDir, ucmd->rightmove / 127.0f * self->client->ps.speed, right, moveDir); + // moveDir is now our intended move velocity VectorAdd(moveDir, self->client->pushVec, moveDir); self->client->ps.speed = VectorNormalize(moveDir); - //moveDir is now our intended move velocity plus our push Vector + // moveDir is now our intended move velocity plus our push Vector fMove = 127.0 * DotProduct(forward, moveDir); rMove = 127.0 * DotProduct(right, moveDir); - ucmd->forwardmove = floor(fMove);//If in the same dir , will be positive - ucmd->rightmove = floor(rMove);//If in the same dir , will be positive + ucmd->forwardmove = floor(fMove); // If in the same dir , will be positive + ucmd->rightmove = floor(rMove); // If in the same dir , will be positive - if ( self->client->pushVecTime < level.time ) - { - VectorClear( self->client->pushVec ); + if (self->client->pushVecTime < level.time) { + VectorClear(self->client->pushVec); } } -qboolean G_StandingAnim( int anim ) -{//NOTE: does not check idles or special (cinematic) stands - switch ( anim ) - { +qboolean G_StandingAnim(int anim) { // NOTE: does not check idles or special (cinematic) stands + switch (anim) { case BOTH_STAND1: case BOTH_STAND2: case BOTH_STAND3: @@ -1225,106 +1096,66 @@ qboolean G_StandingAnim( int anim ) return qfalse; } -qboolean G_ActionButtonPressed(int buttons) -{ - if (buttons & BUTTON_ATTACK) - { +qboolean G_ActionButtonPressed(int buttons) { + if (buttons & BUTTON_ATTACK) { return qtrue; - } - else if (buttons & BUTTON_USE_HOLDABLE) - { + } else if (buttons & BUTTON_USE_HOLDABLE) { return qtrue; - } - else if (buttons & BUTTON_GESTURE) - { + } else if (buttons & BUTTON_GESTURE) { return qtrue; - } - else if (buttons & BUTTON_USE) - { + } else if (buttons & BUTTON_USE) { return qtrue; - } - else if (buttons & BUTTON_FORCEGRIP) - { + } else if (buttons & BUTTON_FORCEGRIP) { return qtrue; - } - else if (buttons & BUTTON_ALT_ATTACK) - { + } else if (buttons & BUTTON_ALT_ATTACK) { return qtrue; - } - else if (buttons & BUTTON_FORCEPOWER) - { + } else if (buttons & BUTTON_FORCEPOWER) { return qtrue; - } - else if (buttons & BUTTON_FORCE_LIGHTNING) - { + } else if (buttons & BUTTON_FORCE_LIGHTNING) { return qtrue; - } - else if (buttons & BUTTON_FORCE_DRAIN) - { + } else if (buttons & BUTTON_FORCE_DRAIN) { return qtrue; } return qfalse; } -void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) -{ +void G_CheckClientIdle(gentity_t *ent, usercmd_t *ucmd) { vec3_t viewChange; qboolean actionPressed; int buttons; - if ( !ent || !ent->client || ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || - ent->client->sess.sessionTeam == TEAM_SPECTATOR || (ent->client->ps.pm_flags & PMF_FOLLOW)) - { + if (!ent || !ent->client || ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || ent->client->sess.sessionTeam == TEAM_SPECTATOR || + (ent->client->ps.pm_flags & PMF_FOLLOW)) { return; } buttons = ucmd->buttons; - if (ent->r.svFlags & SVF_BOT) - { //they press use all the time.. + if (ent->r.svFlags & SVF_BOT) { // they press use all the time.. buttons &= ~BUTTON_USE; } actionPressed = G_ActionButtonPressed(buttons); VectorSubtract(ent->client->ps.viewangles, ent->client->idleViewAngles, viewChange); - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || !G_StandingAnim( ent->client->ps.legsAnim ) - || (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth - || VectorLength(viewChange) > 10 - || ent->client->ps.legsTimer > 0 - || ent->client->ps.torsoTimer > 0 - || ent->client->ps.weaponTime > 0 - || ent->client->ps.weaponstate == WEAPON_CHARGING - || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT - || ent->client->ps.zoomMode - || (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) - || ent->client->ps.forceHandExtend != HANDEXTEND_NONE - || ent->client->ps.saberBlocked != BLOCKED_NONE - || ent->client->ps.saberBlocking >= level.time - || ent->client->ps.weapon == WP_MELEE - || (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) - {//FIXME: also check for turning? + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || + !G_StandingAnim(ent->client->ps.legsAnim) || (ent->health + ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth || + VectorLength(viewChange) > 10 || ent->client->ps.legsTimer > 0 || ent->client->ps.torsoTimer > 0 || ent->client->ps.weaponTime > 0 || + ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT || ent->client->ps.zoomMode || + (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) || ent->client->ps.forceHandExtend != HANDEXTEND_NONE || + ent->client->ps.saberBlocked != BLOCKED_NONE || ent->client->ps.saberBlocking >= level.time || ent->client->ps.weapon == WP_MELEE || + (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) { // FIXME: also check for turning? qboolean brokeOut = qfalse; - if ( !VectorCompare( vec3_origin, ent->client->ps.velocity ) - || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove - || (ent->health+ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth - || ent->client->ps.zoomMode - || (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) - || (ent->client->ps.weaponTime > 0 && ent->client->ps.weapon == WP_SABER) - || ent->client->ps.weaponstate == WEAPON_CHARGING - || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT - || ent->client->ps.forceHandExtend != HANDEXTEND_NONE - || ent->client->ps.saberBlocked != BLOCKED_NONE - || ent->client->ps.saberBlocking >= level.time - || ent->client->ps.weapon == WP_MELEE - || (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) - { - //if in an idle, break out - switch ( ent->client->ps.legsAnim ) - { + if (!VectorCompare(vec3_origin, ent->client->ps.velocity) || actionPressed || ucmd->forwardmove || ucmd->rightmove || ucmd->upmove || + (ent->health + ent->client->ps.stats[STAT_ARMOR]) != ent->client->idleHealth || ent->client->ps.zoomMode || + (ent->client->ps.weaponstate != WEAPON_READY && ent->client->ps.weapon != WP_SABER) || + (ent->client->ps.weaponTime > 0 && ent->client->ps.weapon == WP_SABER) || ent->client->ps.weaponstate == WEAPON_CHARGING || + ent->client->ps.weaponstate == WEAPON_CHARGING_ALT || ent->client->ps.forceHandExtend != HANDEXTEND_NONE || + ent->client->ps.saberBlocked != BLOCKED_NONE || ent->client->ps.saberBlocking >= level.time || ent->client->ps.weapon == WP_MELEE || + (ent->client->ps.weapon != ent->client->pers.cmd.weapon && ent->s.eType != ET_NPC)) { + // if in an idle, break out + switch (ent->client->ps.legsAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -1334,8 +1165,7 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) brokeOut = qtrue; break; } - switch ( ent->client->ps.torsoAnim ) - { + switch (ent->client->ps.torsoAnim) { case BOTH_STAND1IDLE1: case BOTH_STAND2IDLE1: case BOTH_STAND2IDLE2: @@ -1349,29 +1179,23 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) } } // - ent->client->idleHealth = (ent->health+ent->client->ps.stats[STAT_ARMOR]); + ent->client->idleHealth = (ent->health + ent->client->ps.stats[STAT_ARMOR]); VectorCopy(ent->client->ps.viewangles, ent->client->idleViewAngles); - if ( ent->client->idleTime < level.time ) - { + if (ent->client->idleTime < level.time) { ent->client->idleTime = level.time; } - if (brokeOut && - (ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT)) - { + if (brokeOut && (ent->client->ps.weaponstate == WEAPON_CHARGING || ent->client->ps.weaponstate == WEAPON_CHARGING_ALT)) { ent->client->ps.torsoAnim = TORSO_RAISEWEAP1; } - } - else if ( level.time - ent->client->idleTime > 5000 ) - {//been idle for 5 seconds - int idleAnim = -1; - switch ( ent->client->ps.legsAnim ) - { + } else if (level.time - ent->client->idleTime > 5000) { // been idle for 5 seconds + int idleAnim = -1; + switch (ent->client->ps.legsAnim) { case BOTH_STAND1: idleAnim = BOTH_STAND1IDLE1; break; case BOTH_STAND2: - idleAnim = BOTH_STAND2IDLE1;//Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); + idleAnim = BOTH_STAND2IDLE1; // Q_irand(BOTH_STAND2IDLE1,BOTH_STAND2IDLE2); break; case BOTH_STAND3: idleAnim = BOTH_STAND3IDLE1; @@ -1381,73 +1205,52 @@ void G_CheckClientIdle( gentity_t *ent, usercmd_t *ucmd ) break; } - if (idleAnim == BOTH_STAND2IDLE1 && Q_irand(1, 10) <= 5) - { + if (idleAnim == BOTH_STAND2IDLE1 && Q_irand(1, 10) <= 5) { idleAnim = BOTH_STAND2IDLE2; } - if ( /*PM_HasAnimation( ent, idleAnim )*/idleAnim > 0 && idleAnim < MAX_ANIMATIONS ) - { - G_SetAnim(ent, ucmd, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + if (/*PM_HasAnimation( ent, idleAnim )*/ idleAnim > 0 && idleAnim < MAX_ANIMATIONS) { + G_SetAnim(ent, ucmd, SETANIM_BOTH, idleAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); - //don't idle again after this anim for a while - //ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); - ent->client->idleTime = level.time + ent->client->ps.legsTimer + Q_irand( 0, 2000 ); + // don't idle again after this anim for a while + // ent->client->idleTime = level.time + PM_AnimLength( ent->client->clientInfo.animFileIndex, (animNumber_t)idleAnim ) + Q_irand( 0, 2000 ); + ent->client->idleTime = level.time + ent->client->ps.legsTimer + Q_irand(0, 2000); } } } -void NPC_Accelerate( gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc ) -{ - if ( !ent->client || !ent->NPC ) - { +void NPC_Accelerate(gentity_t *ent, qboolean fullWalkAcc, qboolean fullRunAcc) { + if (!ent->client || !ent->NPC) { return; } - if ( !ent->NPC->stats.acceleration ) - {//No acceleration means just start and stop + if (!ent->NPC->stats.acceleration) { // No acceleration means just start and stop ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - //FIXME: in cinematics always accel/decel? - else if ( ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed ) - {//Only accelerate if at walkSpeeds - if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - { - //ent->client->ps.friction = 0; + // FIXME: in cinematics always accel/decel? + else if (ent->NPC->desiredSpeed <= ent->NPC->stats.walkSpeed) { // Only accelerate if at walkSpeeds + if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - { - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - {//decelerate even when walking + } else if (fullWalkAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { // decelerate even when walking ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//stop on a dime + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // stop on a dime ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } - } - else// if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) - {//Only decelerate if at runSpeeds - if ( fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration ) - {//Accelerate to runspeed - //ent->client->ps.friction = 0; + } else // if ( ent->NPC->desiredSpeed > ent->NPC->stats.walkSpeed ) + { // Only decelerate if at runSpeeds + if (fullRunAcc && ent->NPC->desiredSpeed > ent->NPC->currentSpeed + ent->NPC->stats.acceleration) { // Accelerate to runspeed + // ent->client->ps.friction = 0; ent->NPC->currentSpeed += ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed > ent->NPC->currentSpeed ) - {//accelerate instantly - //ent->client->ps.friction = 0; + } else if (ent->NPC->desiredSpeed > ent->NPC->currentSpeed) { // accelerate instantly + // ent->client->ps.friction = 0; ent->NPC->currentSpeed = ent->NPC->desiredSpeed; - } - else if ( fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration ) - { + } else if (fullRunAcc && ent->NPC->desiredSpeed < ent->NPC->currentSpeed - ent->NPC->stats.acceleration) { ent->NPC->currentSpeed -= ent->NPC->stats.acceleration; - } - else if ( ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - { + } else if (ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { ent->NPC->currentSpeed = ent->NPC->desiredSpeed; } } @@ -1459,16 +1262,14 @@ NPC_GetWalkSpeed ------------------------- */ -static int NPC_GetWalkSpeed( gentity_t *ent ) -{ - int walkSpeed = 0; +static int NPC_GetWalkSpeed(gentity_t *ent) { + int walkSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; - switch ( ent->client->playerTeam ) - { - case NPCTEAM_PLAYER: //To shutup compiler, will add entries later (this is stub code) + switch (ent->client->playerTeam) { + case NPCTEAM_PLAYER: // To shutup compiler, will add entries later (this is stub code) default: walkSpeed = ent->NPC->stats.walkSpeed; break; @@ -1482,17 +1283,15 @@ static int NPC_GetWalkSpeed( gentity_t *ent ) NPC_GetRunSpeed ------------------------- */ -static int NPC_GetRunSpeed( gentity_t *ent ) -{ - int runSpeed = 0; +static int NPC_GetRunSpeed(gentity_t *ent) { + int runSpeed = 0; - if ( ( ent->client == NULL ) || ( ent->NPC == NULL ) ) + if ((ent->client == NULL) || (ent->NPC == NULL)) return 0; // team no longer indicates species/race. Use NPC_class to adjust speed for specific npc types - switch( ent->client->NPC_class) - { - case CLASS_PROBE: // droid cases here to shut-up compiler + switch (ent->client->NPC_class) { + case CLASS_PROBE: // droid cases here to shut-up compiler case CLASS_GONK: case CLASS_R2D2: case CLASS_R5D2: @@ -1507,85 +1306,66 @@ static int NPC_GetRunSpeed( gentity_t *ent ) break; default: - runSpeed = ent->NPC->stats.runSpeed*1.3f; //rww - seems to slow in MP for some reason. + runSpeed = ent->NPC->stats.runSpeed * 1.3f; // rww - seems to slow in MP for some reason. break; } return runSpeed; } -//Seems like a slightly less than ideal method for this, could it be done on the client? -extern qboolean FlyingCreature( gentity_t *ent ); -void G_CheckMovingLoopingSounds( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent->client ) - { - if ( (ent->NPC&&!VectorCompare( vec3_origin, ent->client->ps.moveDir ))//moving using moveDir - || ucmd->forwardmove || ucmd->rightmove//moving using ucmds - || (ucmd->upmove&&FlyingCreature( ent ))//flier using ucmds to move - || (FlyingCreature( ent )&&!VectorCompare( vec3_origin, ent->client->ps.velocity )&&ent->health>0))//flier using velocity to move +// Seems like a slightly less than ideal method for this, could it be done on the client? +extern qboolean FlyingCreature(gentity_t *ent); +void G_CheckMovingLoopingSounds(gentity_t *ent, usercmd_t *ucmd) { + if (ent->client) { + if ((ent->NPC && !VectorCompare(vec3_origin, ent->client->ps.moveDir)) // moving using moveDir + || ucmd->forwardmove || ucmd->rightmove // moving using ucmds + || (ucmd->upmove && FlyingCreature(ent)) // flier using ucmds to move + || (FlyingCreature(ent) && !VectorCompare(vec3_origin, ent->client->ps.velocity) && ent->health > 0)) // flier using velocity to move { - switch( ent->client->NPC_class ) - { + switch (ent->client->NPC_class) { case CLASS_R2D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp.wav"); break; case CLASS_R5D2: - ent->s.loopSound = G_SoundIndex( "sound/chars/r2d2/misc/r2_move_lp2.wav" ); + ent->s.loopSound = G_SoundIndex("sound/chars/r2d2/misc/r2_move_lp2.wav"); break; case CLASS_MARK2: - ent->s.loopSound = G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mark2/misc/mark2_move_lp"); break; case CLASS_MOUSE: - ent->s.loopSound = G_SoundIndex( "sound/chars/mouse/misc/mouse_lp" ); + ent->s.loopSound = G_SoundIndex("sound/chars/mouse/misc/mouse_lp"); break; case CLASS_PROBE: - ent->s.loopSound = G_SoundIndex( "sound/chars/probe/misc/probedroidloop" ); + ent->s.loopSound = G_SoundIndex("sound/chars/probe/misc/probedroidloop"); default: break; } - } - else - {//not moving under your own control, stop loopSound - if ( ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_MARK2 || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_PROBE ) - { + } else { // not moving under your own control, stop loopSound + if (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_MARK2 || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_PROBE) { ent->s.loopSound = 0; } } } } -void G_HeldByMonster( gentity_t *ent, usercmd_t *ucmd ) -{ - if ( ent - && ent->client - && ent->client->ps.hasLookTarget )//NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... +void G_HeldByMonster(gentity_t *ent, usercmd_t *ucmd) { + if (ent && ent->client && ent->client->ps.hasLookTarget) // NOTE: lookTarget is an entity number, so this presumes that client 0 is NOT a Rancor... { gentity_t *monster = &g_entities[ent->client->ps.lookTarget]; - if ( monster && monster->client ) - { - //take the monster's waypoint as your own + if (monster && monster->client) { + // take the monster's waypoint as your own ent->waypoint = monster->waypoint; - if ( monster->s.NPC_class == CLASS_RANCOR ) - {//only possibility right now, may add Wampa and Sand Creature later - BG_AttachToRancor( monster->ghoul2, //ghoul2 info - monster->r.currentAngles[YAW], - monster->r.currentOrigin, - level.time, - NULL, - monster->modelScale, - (monster->client->ps.eFlags2&EF2_GENERIC_NPC_FLAG), - ent->client->ps.origin, - ent->client->ps.viewangles, - NULL ); - } - VectorClear( ent->client->ps.velocity ); - G_SetOrigin( ent, ent->client->ps.origin ); - SetClientViewAngle( ent, ent->client->ps.viewangles ); - G_SetAngles( ent, ent->client->ps.viewangles ); - trap->LinkEntity( (sharedEntity_t *)ent );//redundant? + if (monster->s.NPC_class == CLASS_RANCOR) { // only possibility right now, may add Wampa and Sand Creature later + BG_AttachToRancor(monster->ghoul2, // ghoul2 info + monster->r.currentAngles[YAW], monster->r.currentOrigin, level.time, NULL, monster->modelScale, + (monster->client->ps.eFlags2 & EF2_GENERIC_NPC_FLAG), ent->client->ps.origin, ent->client->ps.viewangles, NULL); + } + VectorClear(ent->client->ps.velocity); + G_SetOrigin(ent, ent->client->ps.origin); + SetClientViewAngle(ent, ent->client->ps.viewangles); + G_SetAngles(ent, ent->client->ps.viewangles); + trap->LinkEntity((sharedEntity_t *)ent); // redundant? } } // don't allow movement, weapon switching, and most kinds of button presses @@ -1594,27 +1374,14 @@ void G_HeldByMonster( gentity_t *ent, usercmd_t *ucmd ) ucmd->upmove = 0; } -typedef enum tauntTypes_e -{ - TAUNT_TAUNT = 0, - TAUNT_BOW, - TAUNT_MEDITATE, - TAUNT_FLOURISH, - TAUNT_GLOAT -} tauntTypes_t; - -void G_SetTauntAnim( gentity_t *ent, int taunt ) -{ - if (ent->client->pers.cmd.upmove || - ent->client->pers.cmd.forwardmove || - ent->client->pers.cmd.rightmove) - { //hack, don't do while moving +typedef enum tauntTypes_e { TAUNT_TAUNT = 0, TAUNT_BOW, TAUNT_MEDITATE, TAUNT_FLOURISH, TAUNT_GLOAT } tauntTypes_t; + +void G_SetTauntAnim(gentity_t *ent, int taunt) { + if (ent->client->pers.cmd.upmove || ent->client->pers.cmd.forwardmove || ent->client->pers.cmd.rightmove) { // hack, don't do while moving return; } - if ( taunt != TAUNT_TAUNT ) - {//normal taunt always allowed - if ( level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL ) - {//no taunts unless in Duel + if (taunt != TAUNT_TAUNT) { // normal taunt always allowed + if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) { // no taunts unless in Duel return; } } @@ -1622,43 +1389,25 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) // fix: rocket lock bug BG_ClearRocketLock(&ent->client->ps); - if ( ent->client->ps.torsoTimer < 1 - && ent->client->ps.forceHandExtend == HANDEXTEND_NONE - && ent->client->ps.legsTimer < 1 - && ent->client->ps.weaponTime < 1 - && ent->client->ps.saberLockTime < level.time ) - { + if (ent->client->ps.torsoTimer < 1 && ent->client->ps.forceHandExtend == HANDEXTEND_NONE && ent->client->ps.legsTimer < 1 && + ent->client->ps.weaponTime < 1 && ent->client->ps.saberLockTime < level.time) { int anim = -1; - switch ( taunt ) - { + switch (taunt) { case TAUNT_TAUNT: - if ( ent->client->ps.weapon != WP_SABER ) - { + if (ent->client->ps.weapon != WP_SABER) { anim = BOTH_ENGAGETAUNT; - } - else if ( ent->client->saber[0].tauntAnim != -1 ) - { + } else if (ent->client->saber[0].tauntAnim != -1) { anim = ent->client->saber[0].tauntAnim; - } - else if ( ent->client->saber[1].model[0] - && ent->client->saber[1].tauntAnim != -1 ) - { + } else if (ent->client->saber[1].model[0] && ent->client->saber[1].tauntAnim != -1) { anim = ent->client->saber[1].tauntAnim; - } - else - { - switch ( ent->client->ps.fd.saberAnimLevel ) - { + } else { + switch (ent->client->ps.fd.saberAnimLevel) { case SS_FAST: case SS_TAVION: - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn off second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); - } - else if ( ent->client->ps.saberHolstered == 0 ) - {//turn off first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn off second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOff); + } else if (ent->client->ps.saberHolstered == 0) { // turn off first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOff); } ent->client->ps.saberHolstered = 2; anim = BOTH_GESTURE1; @@ -1669,22 +1418,17 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) anim = BOTH_ENGAGETAUNT; break; case SS_DUAL: - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn on second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); - } - else if ( ent->client->ps.saberHolstered == 2 ) - {//turn on first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn on second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOn); + } else if (ent->client->ps.saberHolstered == 2) { // turn on first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; anim = BOTH_DUAL_TAUNT; break; case SS_STAFF: - if ( ent->client->ps.saberHolstered > 0 ) - {//turn on all blades - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.saberHolstered > 0) { // turn on all blades + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; anim = BOTH_STAFF_TAUNT; @@ -1693,81 +1437,49 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; case TAUNT_BOW: - if ( ent->client->saber[0].bowAnim != -1 ) - { + if (ent->client->saber[0].bowAnim != -1) { anim = ent->client->saber[0].bowAnim; - } - else if ( ent->client->saber[1].model[0] - && ent->client->saber[1].bowAnim != -1 ) - { + } else if (ent->client->saber[1].model[0] && ent->client->saber[1].bowAnim != -1) { anim = ent->client->saber[1].bowAnim; - } - else - { + } else { anim = BOTH_BOW; } - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn off second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); - } - else if ( ent->client->ps.saberHolstered == 0 ) - {//turn off first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn off second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOff); + } else if (ent->client->ps.saberHolstered == 0) { // turn off first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOff); } ent->client->ps.saberHolstered = 2; break; case TAUNT_MEDITATE: - if ( ent->client->saber[0].meditateAnim != -1 ) - { + if (ent->client->saber[0].meditateAnim != -1) { anim = ent->client->saber[0].meditateAnim; - } - else if ( ent->client->saber[1].model[0] - && ent->client->saber[1].meditateAnim != -1 ) - { + } else if (ent->client->saber[1].model[0] && ent->client->saber[1].meditateAnim != -1) { anim = ent->client->saber[1].meditateAnim; - } - else - { + } else { anim = BOTH_MEDITATE; } - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn off second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOff ); - } - else if ( ent->client->ps.saberHolstered == 0 ) - {//turn off first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOff ); + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn off second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOff); + } else if (ent->client->ps.saberHolstered == 0) { // turn off first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOff); } ent->client->ps.saberHolstered = 2; break; case TAUNT_FLOURISH: - if ( ent->client->ps.weapon == WP_SABER ) - { - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn on second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); - } - else if ( ent->client->ps.saberHolstered == 2 ) - {//turn on first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.weapon == WP_SABER) { + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn on second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOn); + } else if (ent->client->ps.saberHolstered == 2) { // turn on first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; - if ( ent->client->saber[0].flourishAnim != -1 ) - { + if (ent->client->saber[0].flourishAnim != -1) { anim = ent->client->saber[0].flourishAnim; - } - else if ( ent->client->saber[1].model[0] - && ent->client->saber[1].flourishAnim != -1 ) - { + } else if (ent->client->saber[1].model[0] && ent->client->saber[1].flourishAnim != -1) { anim = ent->client->saber[1].flourishAnim; - } - else - { - switch ( ent->client->ps.fd.saberAnimLevel ) - { + } else { + switch (ent->client->ps.fd.saberAnimLevel) { case SS_FAST: case SS_TAVION: anim = BOTH_SHOWOFF_FAST; @@ -1790,19 +1502,12 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; case TAUNT_GLOAT: - if ( ent->client->saber[0].gloatAnim != -1 ) - { + if (ent->client->saber[0].gloatAnim != -1) { anim = ent->client->saber[0].gloatAnim; - } - else if ( ent->client->saber[1].model[0] - && ent->client->saber[1].gloatAnim != -1 ) - { + } else if (ent->client->saber[1].model[0] && ent->client->saber[1].gloatAnim != -1) { anim = ent->client->saber[1].gloatAnim; - } - else - { - switch ( ent->client->ps.fd.saberAnimLevel ) - { + } else { + switch (ent->client->ps.fd.saberAnimLevel) { case SS_FAST: case SS_TAVION: anim = BOTH_VICTORY_FAST; @@ -1812,30 +1517,24 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) break; case SS_STRONG: case SS_DESANN: - if ( ent->client->ps.saberHolstered ) - {//turn on first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.saberHolstered) { // turn on first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_STRONG; break; case SS_DUAL: - if ( ent->client->ps.saberHolstered == 1 - && ent->client->saber[1].model[0] ) - {//turn on second saber - G_Sound( ent, CHAN_WEAPON, ent->client->saber[1].soundOn ); - } - else if ( ent->client->ps.saberHolstered == 2 ) - {//turn on first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.saberHolstered == 1 && ent->client->saber[1].model[0]) { // turn on second saber + G_Sound(ent, CHAN_WEAPON, ent->client->saber[1].soundOn); + } else if (ent->client->ps.saberHolstered == 2) { // turn on first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_DUAL; break; case SS_STAFF: - if ( ent->client->ps.saberHolstered ) - {//turn on first - G_Sound( ent, CHAN_WEAPON, ent->client->saber[0].soundOn ); + if (ent->client->ps.saberHolstered) { // turn on first + G_Sound(ent, CHAN_WEAPON, ent->client->saber[0].soundOn); } ent->client->ps.saberHolstered = 0; anim = BOTH_VICTORY_STAFF; @@ -1844,18 +1543,14 @@ void G_SetTauntAnim( gentity_t *ent, int taunt ) } break; } - if ( anim != -1 ) - { - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - { + if (anim != -1) { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { ent->client->ps.forceHandExtend = HANDEXTEND_TAUNT; ent->client->ps.forceDodgeAnim = anim; ent->client->ps.forceHandExtendTime = level.time + BG_AnimLength(ent->localAnimIndex, (animNumber_t)anim); } - if ( taunt != TAUNT_MEDITATE - && taunt != TAUNT_BOW ) - {//no sound for meditate or bow - G_AddEvent( ent, EV_TAUNT, taunt ); + if (taunt != TAUNT_MEDITATE && taunt != TAUNT_BOW) { // no sound for meditate or bow + G_AddEvent(ent, EV_TAUNT, taunt); } } } @@ -1872,21 +1567,20 @@ If "g_synchronousClients 1" is set, this will be called exactly once for each server frame, which makes for smooth demo recording. ============== */ -void ClientThink_real( gentity_t *ent ) { - gclient_t *client; - pmove_t pmove; - int oldEventSequence; - int msec; - usercmd_t *ucmd; - qboolean isNPC = qfalse; - qboolean controlledByPlayer = qfalse; - qboolean killJetFlags = qtrue; - qboolean isFollowing; +void ClientThink_real(gentity_t *ent) { + gclient_t *client; + pmove_t pmove; + int oldEventSequence; + int msec; + usercmd_t *ucmd; + qboolean isNPC = qfalse; + qboolean controlledByPlayer = qfalse; + qboolean killJetFlags = qtrue; + qboolean isFollowing; client = ent->client; - if (ent->s.eType == ET_NPC) - { + if (ent->s.eType == ET_NPC) { isNPC = qtrue; } @@ -1897,19 +1591,14 @@ void ClientThink_real( gentity_t *ent ) { // This code was moved here from clientThink to fix a problem with g_synchronousClients // being set to 1 when in vehicles. - if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) - {//driving a vehicle - if (g_entities[ent->client->ps.m_iVehicleNum].client) - { + if (ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum) { // driving a vehicle + if (g_entities[ent->client->ps.m_iVehicleNum].client) { gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) - { //only take input from the pilot... + if (veh->m_pVehicle && veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) { // only take input from the pilot... veh->client->ps.commandTime = ent->client->ps.commandTime; memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t)); - if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) - { //forced input if "chat bubble" is up + if (veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK) { // forced input if "chat bubble" is up veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; veh->m_pVehicle->m_ucmd.forwardmove = 0; veh->m_pVehicle->m_ucmd.rightmove = 0; @@ -1921,37 +1610,25 @@ void ClientThink_real( gentity_t *ent ) { isFollowing = (client->ps.pm_flags & PMF_FOLLOW) ? qtrue : qfalse; - if (!isFollowing) - { - if (level.gametype == GT_SIEGE && - client->siegeClass != -1 && - bgSiegeClasses[client->siegeClass].saberStance) - { //the class says we have to use this stance set. - if (!(bgSiegeClasses[client->siegeClass].saberStance & (1 << client->ps.fd.saberAnimLevel))) - { //the current stance is not in the bitmask, so find the first one that is. + if (!isFollowing) { + if (level.gametype == GT_SIEGE && client->siegeClass != -1 && + bgSiegeClasses[client->siegeClass].saberStance) { // the class says we have to use this stance set. + if (!(bgSiegeClasses[client->siegeClass].saberStance & + (1 << client->ps.fd.saberAnimLevel))) { // the current stance is not in the bitmask, so find the first one that is. int i = SS_FAST; - while (i < SS_NUM_SABER_STYLES) - { - if (bgSiegeClasses[client->siegeClass].saberStance & (1 << i)) - { - if (i == SS_DUAL - && client->ps.saberHolstered == 1 ) - {//one saber should be off, adjust saberAnimLevel accordinly + while (i < SS_NUM_SABER_STYLES) { + if (bgSiegeClasses[client->siegeClass].saberStance & (1 << i)) { + if (i == SS_DUAL && client->ps.saberHolstered == 1) { // one saber should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = i; client->ps.fd.saberAnimLevel = SS_FAST; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; - } - else if ( i == SS_STAFF - && client->ps.saberHolstered == 1 - && client->saber[0].singleBladeStyle != SS_NONE) - {//one saber or blade should be off, adjust saberAnimLevel accordinly + } else if (i == SS_STAFF && client->ps.saberHolstered == 1 && + client->saber[0].singleBladeStyle != SS_NONE) { // one saber or blade should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = i; client->ps.fd.saberAnimLevel = client->saber[0].singleBladeStyle; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; - } - else - { + } else { client->ps.fd.saberAnimLevelBase = client->ps.fd.saberAnimLevel = i; client->ps.fd.saberDrawAnimLevel = i; } @@ -1961,40 +1638,28 @@ void ClientThink_real( gentity_t *ent ) { i++; } } - } - else if (client->saber[0].model[0] && client->saber[1].model[0]) - { //with two sabs always use akimbo style - if ( client->ps.saberHolstered == 1 ) - {//one saber should be off, adjust saberAnimLevel accordinly + } else if (client->saber[0].model[0] && client->saber[1].model[0]) { // with two sabs always use akimbo style + if (client->ps.saberHolstered == 1) { // one saber should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevelBase = SS_DUAL; client->ps.fd.saberAnimLevel = SS_FAST; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; - } - else - { - if ( !WP_SaberStyleValidForSaber( &client->saber[0], &client->saber[1], client->ps.saberHolstered, client->ps.fd.saberAnimLevel ) ) - {//only use dual style if the style we're trying to use isn't valid + } else { + if (!WP_SaberStyleValidForSaber(&client->saber[0], &client->saber[1], client->ps.saberHolstered, + client->ps.fd.saberAnimLevel)) { // only use dual style if the style we're trying to use isn't valid client->ps.fd.saberAnimLevelBase = client->ps.fd.saberAnimLevel = SS_DUAL; } client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } - } - else - { - if (client->saber[0].stylesLearned == (1<saber[0].stylesLearned == (1 << SS_STAFF)) { // then *always* use the staff style client->ps.fd.saberAnimLevelBase = SS_STAFF; } - if ( client->ps.fd.saberAnimLevelBase == SS_STAFF ) - {//using staff style - if ( client->ps.saberHolstered == 1 - && client->saber[0].singleBladeStyle != SS_NONE) - {//one blade should be off, adjust saberAnimLevel accordinly + if (client->ps.fd.saberAnimLevelBase == SS_STAFF) { // using staff style + if (client->ps.saberHolstered == 1 && + client->saber[0].singleBladeStyle != SS_NONE) { // one blade should be off, adjust saberAnimLevel accordinly client->ps.fd.saberAnimLevel = client->saber[0].singleBladeStyle; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; - } - else - { + } else { client->ps.fd.saberAnimLevel = SS_STAFF; client->ps.fd.saberDrawAnimLevel = client->ps.fd.saberAnimLevel; } @@ -2005,159 +1670,130 @@ void ClientThink_real( gentity_t *ent ) { // mark the time, so the connection sprite can be removed ucmd = &ent->client->pers.cmd; - if ( client && !isFollowing && (client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - { - G_HeldByMonster( ent, ucmd ); + if (client && !isFollowing && (client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { + G_HeldByMonster(ent, ucmd); } // sanity check the command time to prevent speedup cheating - if ( ucmd->serverTime > level.time + 200 ) { + if (ucmd->serverTime > level.time + 200) { ucmd->serverTime = level.time + 200; -// trap->Print("serverTime <<<<<\n" ); + // trap->Print("serverTime <<<<<\n" ); } - if ( ucmd->serverTime < level.time - 1000 ) { + if (ucmd->serverTime < level.time - 1000) { ucmd->serverTime = level.time - 1000; -// trap->Print("serverTime >>>>>\n" ); + // trap->Print("serverTime >>>>>\n" ); } - if (isNPC && (ucmd->serverTime - client->ps.commandTime) < 1) - { + if (isNPC && (ucmd->serverTime - client->ps.commandTime) < 1) { ucmd->serverTime = client->ps.commandTime + 100; } msec = ucmd->serverTime - client->ps.commandTime; // following others may result in bad times, but we still want // to check for follow toggles - if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) { + if (msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW) { return; } - if ( msec > 200 ) { + if (msec > 200) { msec = 200; } - if ( pmove_msec.integer < 8 ) { + if (pmove_msec.integer < 8) { trap->Cvar_Set("pmove_msec", "8"); - } - else if (pmove_msec.integer > 33) { + } else if (pmove_msec.integer > 33) { trap->Cvar_Set("pmove_msec", "33"); } - if ( pmove_fixed.integer || client->pers.pmoveFixed ) { - ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer; - //if (ucmd->serverTime - client->ps.commandTime <= 0) + if (pmove_fixed.integer || client->pers.pmoveFixed) { + ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer - 1) / pmove_msec.integer) * pmove_msec.integer; + // if (ucmd->serverTime - client->ps.commandTime <= 0) // return; } // // check for exiting intermission // - if ( level.intermissiontime ) - { - if ( ent->s.number < MAX_CLIENTS - || client->NPC_class == CLASS_VEHICLE ) - {//players and vehicles do nothing in intermissions - ClientIntermissionThink( client ); + if (level.intermissiontime) { + if (ent->s.number < MAX_CLIENTS || client->NPC_class == CLASS_VEHICLE) { // players and vehicles do nothing in intermissions + ClientIntermissionThink(client); return; } } // spectators don't do much - if ( client->sess.sessionTeam == TEAM_SPECTATOR || client->tempSpectate >= level.time ) { - if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) { + if (client->sess.sessionTeam == TEAM_SPECTATOR || client->tempSpectate >= level.time) { + if (client->sess.spectatorState == SPECTATOR_SCOREBOARD) { return; } - SpectatorThink( ent, ucmd ); + SpectatorThink(ent, ucmd); return; } - if (ent && ent->client && (ent->client->ps.eFlags & EF_INVULNERABLE)) - { - if (ent->client->invulnerableTimer <= level.time) - { + if (ent && ent->client && (ent->client->ps.eFlags & EF_INVULNERABLE)) { + if (ent->client->invulnerableTimer <= level.time) { ent->client->ps.eFlags &= ~EF_INVULNERABLE; } } - if (ent->s.eType != ET_NPC) - { + if (ent->s.eType != ET_NPC) { // check for inactivity timer, but never drop the local client of a non-dedicated server - if ( !ClientInactivityTimer( client ) ) { + if (!ClientInactivityTimer(client)) { return; } } - //Check if we should have a fullbody push effect around the player - if (client->pushEffectTime > level.time) - { + // Check if we should have a fullbody push effect around the player + if (client->pushEffectTime > level.time) { client->ps.eFlags |= EF_BODYPUSH; - } - else if (client->pushEffectTime) - { + } else if (client->pushEffectTime) { client->pushEffectTime = 0; client->ps.eFlags &= ~EF_BODYPUSH; } - - if (client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) - { - client->ps.eFlags |= EF_JETPACK; - } - else - { + + if (client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) { + client->ps.eFlags |= EF_JETPACK; + } else { client->ps.eFlags &= ~EF_JETPACK; } - if ( client->noclip ) { + if (client->noclip) { client->ps.pm_type = PM_NOCLIP; - } else if ( client->ps.eFlags & EF_DISINTEGRATION ) { + } else if (client->ps.eFlags & EF_DISINTEGRATION) { client->ps.pm_type = PM_NOCLIP; - } else if ( client->ps.stats[STAT_HEALTH] <= 0 ) { + } else if (client->ps.stats[STAT_HEALTH] <= 0) { client->ps.pm_type = PM_DEAD; } else { - if (client->ps.forceGripChangeMovetype) - { + if (client->ps.forceGripChangeMovetype) { client->ps.pm_type = client->ps.forceGripChangeMovetype; - } - else - { - if (client->jetPackOn) - { + } else { + if (client->jetPackOn) { client->ps.pm_type = PM_JETPACK; client->ps.eFlags |= EF_JETPACK_ACTIVE; killJetFlags = qfalse; - } - else - { + } else { client->ps.pm_type = PM_NORMAL; } } } - if (killJetFlags) - { + if (killJetFlags) { client->ps.eFlags &= ~EF_JETPACK_ACTIVE; client->ps.eFlags &= ~EF_JETPACK_FLAMING; } -#define SLOWDOWN_DIST 128.0f -#define MIN_NPC_SPEED 16.0f +#define SLOWDOWN_DIST 128.0f +#define MIN_NPC_SPEED 16.0f - if (client->bodyGrabIndex != ENTITYNUM_NONE) - { + if (client->bodyGrabIndex != ENTITYNUM_NONE) { gentity_t *grabbed = &g_entities[client->bodyGrabIndex]; - if (!grabbed->inuse || grabbed->s.eType != ET_BODY || - (grabbed->s.eFlags & EF_DISINTEGRATION) || - (grabbed->s.eFlags & EF_NODRAW)) - { - if (grabbed->inuse && grabbed->s.eType == ET_BODY) - { + if (!grabbed->inuse || grabbed->s.eType != ET_BODY || (grabbed->s.eFlags & EF_DISINTEGRATION) || (grabbed->s.eFlags & EF_NODRAW)) { + if (grabbed->inuse && grabbed->s.eType == ET_BODY) { grabbed->s.ragAttach = 0; } client->bodyGrabIndex = ENTITYNUM_NONE; - } - else - { + } else { mdxaBone_t rhMat; vec3_t rhOrg, tAng; vec3_t bodyDir; @@ -2165,169 +1801,132 @@ void ClientThink_real( gentity_t *ent ) { ent->client->ps.forceHandExtend = HANDEXTEND_DRAGGING; - if (ent->client->ps.forceHandExtendTime < level.time + 500) - { + if (ent->client->ps.forceHandExtendTime < level.time + 500) { ent->client->ps.forceHandExtendTime = level.time + 1000; } VectorSet(tAng, 0, ent->client->ps.viewangles[YAW], 0); - trap->G2API_GetBoltMatrix(ent->ghoul2, 0, 0, &rhMat, tAng, ent->client->ps.origin, level.time, - NULL, ent->modelScale); //0 is always going to be right hand bolt + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, 0, &rhMat, tAng, ent->client->ps.origin, level.time, NULL, + ent->modelScale); // 0 is always going to be right hand bolt BG_GiveMeVectorFromMatrix(&rhMat, ORIGIN, rhOrg); VectorSubtract(rhOrg, grabbed->r.currentOrigin, bodyDir); bodyDist = VectorLength(bodyDir); - if (bodyDist > 40.0f) - { //can no longer reach + if (bodyDist > 40.0f) { // can no longer reach grabbed->s.ragAttach = 0; client->bodyGrabIndex = ENTITYNUM_NONE; - } - else if (bodyDist > 24.0f) - { - bodyDir[2] = 0; //don't want it floating - //VectorScale(bodyDir, 0.1f, bodyDir); + } else if (bodyDist > 24.0f) { + bodyDir[2] = 0; // don't want it floating + // VectorScale(bodyDir, 0.1f, bodyDir); VectorAdd(grabbed->epVelocity, bodyDir, grabbed->epVelocity); G_Sound(grabbed, CHAN_AUTO, G_SoundIndex("sound/player/roll1.wav")); } } - } - else if (ent->client->ps.forceHandExtend == HANDEXTEND_DRAGGING) - { + } else if (ent->client->ps.forceHandExtend == HANDEXTEND_DRAGGING) { ent->client->ps.forceHandExtend = HANDEXTEND_WEAPONREADY; } - if (ent->NPC && ent->s.NPC_class != CLASS_VEHICLE) //vehicles manage their own speed + if (ent->NPC && ent->s.NPC_class != CLASS_VEHICLE) // vehicles manage their own speed { - //FIXME: swoop should keep turning (and moving forward?) for a little bit? - if ( ent->NPC->combatMove == qfalse ) - { - //if ( !(ucmd->buttons & BUTTON_USE) ) - if (1) - {//Not leaning - qboolean Flying = (ucmd->upmove && (ent->client->ps.eFlags2&EF2_FLYING));//ent->client->moveType == MT_FLYSWIM); - qboolean Climbing = (ucmd->upmove && ent->watertype&CONTENTS_LADDER ); + // FIXME: swoop should keep turning (and moving forward?) for a little bit? + if (ent->NPC->combatMove == qfalse) { + // if ( !(ucmd->buttons & BUTTON_USE) ) + if (1) { // Not leaning + qboolean Flying = (ucmd->upmove && (ent->client->ps.eFlags2 & EF2_FLYING)); // ent->client->moveType == MT_FLYSWIM); + qboolean Climbing = (ucmd->upmove && ent->watertype & CONTENTS_LADDER); - //client->ps.friction = 6; + // client->ps.friction = 6; - if ( ucmd->forwardmove || ucmd->rightmove || Flying ) - { - //if ( ent->NPC->behaviorState != BS_FORMATION ) - {//In - Formation NPCs set thier desiredSpeed themselves - if ( ucmd->buttons & BUTTON_WALKING ) + if (ucmd->forwardmove || ucmd->rightmove || Flying) { + // if ( ent->NPC->behaviorState != BS_FORMATION ) + { // In - Formation NPCs set thier desiredSpeed themselves + if (ucmd->buttons & BUTTON_WALKING) { + ent->NPC->desiredSpeed = NPC_GetWalkSpeed(ent); // ent->NPC->stats.walkSpeed; + } else // running { - ent->NPC->desiredSpeed = NPC_GetWalkSpeed( ent );//ent->NPC->stats.walkSpeed; - } - else//running - { - ent->NPC->desiredSpeed = NPC_GetRunSpeed( ent );//ent->NPC->stats.runSpeed; + ent->NPC->desiredSpeed = NPC_GetRunSpeed(ent); // ent->NPC->stats.runSpeed; } - if ( ent->NPC->currentSpeed >= 80 && !controlledByPlayer ) - {//At higher speeds, need to slow down close to stuff - //Slow down as you approach your goal - if ( ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags&NPCAI_NO_SLOWDOWN) )//128 + if (ent->NPC->currentSpeed >= 80 && !controlledByPlayer) { // At higher speeds, need to slow down close to stuff + // Slow down as you approach your goal + if (ent->NPC->distToGoal < SLOWDOWN_DIST && !(ent->NPC->aiFlags & NPCAI_NO_SLOWDOWN)) // 128 { - if ( ent->NPC->desiredSpeed > MIN_NPC_SPEED ) - { + if (ent->NPC->desiredSpeed > MIN_NPC_SPEED) { float slowdownSpeed = ((float)ent->NPC->desiredSpeed) * ent->NPC->distToGoal / SLOWDOWN_DIST; ent->NPC->desiredSpeed = ceil(slowdownSpeed); - if ( ent->NPC->desiredSpeed < MIN_NPC_SPEED ) - {//don't slow down too much + if (ent->NPC->desiredSpeed < MIN_NPC_SPEED) { // don't slow down too much ent->NPC->desiredSpeed = MIN_NPC_SPEED; } } } } } - } - else if ( Climbing ) - { + } else if (Climbing) { ent->NPC->desiredSpeed = ent->NPC->stats.walkSpeed; - } - else - {//We want to stop + } else { // We want to stop ent->NPC->desiredSpeed = 0; } - NPC_Accelerate( ent, qfalse, qfalse ); + NPC_Accelerate(ent, qfalse, qfalse); - if ( ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed ) - {//No-one walks this slow - client->ps.speed = ent->NPC->currentSpeed = 0;//Full stop + if (ent->NPC->currentSpeed <= 24 && ent->NPC->desiredSpeed < ent->NPC->currentSpeed) { // No-one walks this slow + client->ps.speed = ent->NPC->currentSpeed = 0; // Full stop ucmd->forwardmove = 0; ucmd->rightmove = 0; - } - else - { - if ( ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed ) - {//Play the walkanim + } else { + if (ent->NPC->currentSpeed <= ent->NPC->stats.walkSpeed) { // Play the walkanim ucmd->buttons |= BUTTON_WALKING; - } - else - { + } else { ucmd->buttons &= ~BUTTON_WALKING; } - if ( ent->NPC->currentSpeed > 0 ) - {//We should be moving - if ( Climbing || Flying ) - { - if ( !ucmd->upmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->upmove = ent->NPC->last_ucmd.upmove;//was last_upmove; + if (ent->NPC->currentSpeed > 0) { // We should be moving + if (Climbing || Flying) { + if (!ucmd->upmove) { // We need to force them to take a couple more steps until stopped + ucmd->upmove = ent->NPC->last_ucmd.upmove; // was last_upmove; } - } - else if ( !ucmd->forwardmove && !ucmd->rightmove ) - {//We need to force them to take a couple more steps until stopped - ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove;//was last_forwardmove; - ucmd->rightmove = ent->NPC->last_ucmd.rightmove;//was last_rightmove; + } else if (!ucmd->forwardmove && !ucmd->rightmove) { // We need to force them to take a couple more steps until stopped + ucmd->forwardmove = ent->NPC->last_ucmd.forwardmove; // was last_forwardmove; + ucmd->rightmove = ent->NPC->last_ucmd.rightmove; // was last_rightmove; } } client->ps.speed = ent->NPC->currentSpeed; - // if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) - // { - // } - // else - //rwwFIXMEFIXME: do this and also check for all real client - if (1) - { - //Slow down on turns - don't orbit!!! + // if ( player && player->client && player->client->ps.viewEntity == ent->s.number ) + // { + // } + // else + // rwwFIXMEFIXME: do this and also check for all real client + if (1) { + // Slow down on turns - don't orbit!!! float turndelta = 0; - // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always thinks it trying to turn according to desiredYaw - //if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... - if (0) //rwwFIXMEFIXME: ... - { - turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->lockedDesiredYaw ) ))/180; - } - else + // if the NPC is locked into a Yaw, we want to check the lockedDesiredYaw...otherwise the NPC can't walk backwards, because it always + // thinks it trying to turn according to desiredYaw + // if( client->renderInfo.renderFlags & RF_LOCKEDANGLE ) // yeah I know the RF_ flag is a pretty ugly hack... + if (0) // rwwFIXMEFIXME: ... { - turndelta = (180 - fabs( AngleDelta( ent->r.currentAngles[YAW], ent->NPC->desiredYaw ) ))/180; + turndelta = (180 - fabs(AngleDelta(ent->r.currentAngles[YAW], ent->NPC->lockedDesiredYaw))) / 180; + } else { + turndelta = (180 - fabs(AngleDelta(ent->r.currentAngles[YAW], ent->NPC->desiredYaw))) / 180; } - if ( turndelta < 0.75f ) - { + if (turndelta < 0.75f) { client->ps.speed = 0; - } - else if ( ent->NPC->distToGoal < 100 && turndelta < 1.0 ) - {//Turn is greater than 45 degrees or closer than 100 to goal - client->ps.speed = floor(((float)(client->ps.speed))*turndelta); + } else if (ent->NPC->distToGoal < 100 && turndelta < 1.0) { // Turn is greater than 45 degrees or closer than 100 to goal + client->ps.speed = floor(((float)(client->ps.speed)) * turndelta); } } } } - } - else - { - ent->NPC->desiredSpeed = ( ucmd->buttons & BUTTON_WALKING ) ? NPC_GetWalkSpeed( ent ) : NPC_GetRunSpeed( ent ); + } else { + ent->NPC->desiredSpeed = (ucmd->buttons & BUTTON_WALKING) ? NPC_GetWalkSpeed(ent) : NPC_GetRunSpeed(ent); client->ps.speed = ent->NPC->desiredSpeed; } - if (ucmd->buttons & BUTTON_WALKING) - { //sort of a hack I guess since MP handles walking differently from SP (has some proxy cheat prevention methods) + if (ucmd->buttons & BUTTON_WALKING) { // sort of a hack I guess since MP handles walking differently from SP (has some proxy cheat prevention methods) /* if (ent->client->ps.speed > 64) { @@ -2335,105 +1934,75 @@ void ClientThink_real( gentity_t *ent ) { } */ - if (ucmd->forwardmove > 64) - { + if (ucmd->forwardmove > 64) { ucmd->forwardmove = 64; - } - else if (ucmd->forwardmove < -64) - { + } else if (ucmd->forwardmove < -64) { ucmd->forwardmove = -64; } - if (ucmd->rightmove > 64) - { + if (ucmd->rightmove > 64) { ucmd->rightmove = 64; - } - else if ( ucmd->rightmove < -64) - { + } else if (ucmd->rightmove < -64) { ucmd->rightmove = -64; } - //ent->client->ps.speed = ent->client->ps.basespeed = NPC_GetRunSpeed( ent ); + // ent->client->ps.speed = ent->client->ps.basespeed = NPC_GetRunSpeed( ent ); } client->ps.basespeed = client->ps.speed; - } - else if (!client->ps.m_iVehicleNum && - (!ent->NPC || ent->s.NPC_class != CLASS_VEHICLE)) //if riding a vehicle it will manage our speed and such + } else if (!client->ps.m_iVehicleNum && (!ent->NPC || ent->s.NPC_class != CLASS_VEHICLE)) // if riding a vehicle it will manage our speed and such { // set speed client->ps.speed = g_speed.value; - //Check for a siege class speed multiplier - if (level.gametype == GT_SIEGE && - client->siegeClass != -1) - { + // Check for a siege class speed multiplier + if (level.gametype == GT_SIEGE && client->siegeClass != -1) { client->ps.speed *= bgSiegeClasses[client->siegeClass].speed; } - if (client->bodyGrabIndex != ENTITYNUM_NONE) - { //can't go nearly as fast when dragging a body around + if (client->bodyGrabIndex != ENTITYNUM_NONE) { // can't go nearly as fast when dragging a body around client->ps.speed *= 0.2f; } client->ps.basespeed = client->ps.speed; } - if ( !ent->NPC || !(ent->NPC->aiFlags&NPCAI_CUSTOM_GRAVITY) ) - {//use global gravity - if (ent->NPC && ent->s.NPC_class == CLASS_VEHICLE && - ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->gravity) - { //use custom veh gravity + if (!ent->NPC || !(ent->NPC->aiFlags & NPCAI_CUSTOM_GRAVITY)) { // use global gravity + if (ent->NPC && ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->gravity) { // use custom veh gravity client->ps.gravity = ent->m_pVehicle->m_pVehicleInfo->gravity; - } - else - { - if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) - { //in space, so no gravity... + } else { + if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) { // in space, so no gravity... client->ps.gravity = 1.0f; - if (ent->s.number < MAX_CLIENTS) - { + if (ent->s.number < MAX_CLIENTS) { VectorScale(client->ps.velocity, 0.8f, client->ps.velocity); } - } - else - { - if (client->ps.eFlags2 & EF2_SHIP_DEATH) - { //float there + } else { + if (client->ps.eFlags2 & EF2_SHIP_DEATH) { // float there VectorClear(client->ps.velocity); client->ps.gravity = 1.0f; - } - else - { + } else { client->ps.gravity = g_gravity.value; } } } } - if (ent->client->ps.duelInProgress) - { + if (ent->client->ps.duelInProgress) { gentity_t *duelAgainst = &g_entities[ent->client->ps.duelIndex]; - //Keep the time updated, so once this duel ends this player can't engage in a duel for another - //10 seconds. This will give other people a chance to engage in duels in case this player wants - //to engage again right after he's done fighting and someone else is waiting. + // Keep the time updated, so once this duel ends this player can't engage in a duel for another + // 10 seconds. This will give other people a chance to engage in duels in case this player wants + // to engage again right after he's done fighting and someone else is waiting. ent->client->ps.fd.privateDuelTime = level.time + 10000; - if (ent->client->ps.duelTime < level.time) - { - //Bring out the sabers - if (ent->client->ps.weapon == WP_SABER - && ent->client->ps.saberHolstered - && ent->client->ps.duelTime ) - { + if (ent->client->ps.duelTime < level.time) { + // Bring out the sabers + if (ent->client->ps.weapon == WP_SABER && ent->client->ps.saberHolstered && ent->client->ps.duelTime) { ent->client->ps.saberHolstered = 0; - if (ent->client->saber[0].soundOn) - { + if (ent->client->saber[0].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOn); } - if (ent->client->saber[1].soundOn) - { + if (ent->client->saber[1].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOn); } @@ -2442,21 +2011,14 @@ void ClientThink_real( gentity_t *ent ) { ent->client->ps.duelTime = 0; } - if (duelAgainst - && duelAgainst->client - && duelAgainst->inuse - && duelAgainst->client->ps.weapon == WP_SABER - && duelAgainst->client->ps.saberHolstered - && duelAgainst->client->ps.duelTime) - { + if (duelAgainst && duelAgainst->client && duelAgainst->inuse && duelAgainst->client->ps.weapon == WP_SABER && + duelAgainst->client->ps.saberHolstered && duelAgainst->client->ps.duelTime) { duelAgainst->client->ps.saberHolstered = 0; - if (duelAgainst->client->saber[0].soundOn) - { + if (duelAgainst->client->saber[0].soundOn) { G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[0].soundOn); } - if (duelAgainst->client->saber[1].soundOn) - { + if (duelAgainst->client->saber[1].soundOn) { G_Sound(duelAgainst, CHAN_AUTO, duelAgainst->client->saber[1].soundOn); } @@ -2464,9 +2026,7 @@ void ClientThink_real( gentity_t *ent ) { duelAgainst->client->ps.duelTime = 0; } - } - else - { + } else { client->ps.speed = 0; client->ps.basespeed = 0; ucmd->forwardmove = 0; @@ -2474,30 +2034,23 @@ void ClientThink_real( gentity_t *ent ) { ucmd->upmove = 0; } - if (!duelAgainst || !duelAgainst->client || !duelAgainst->inuse || - duelAgainst->client->ps.duelIndex != ent->s.number) - { + if (!duelAgainst || !duelAgainst->client || !duelAgainst->inuse || duelAgainst->client->ps.duelIndex != ent->s.number) { ent->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); - } - else if (duelAgainst->health < 1 || duelAgainst->client->ps.stats[STAT_HEALTH] < 1) - { + } else if (duelAgainst->health < 1 || duelAgainst->client->ps.stats[STAT_HEALTH] < 1) { ent->client->ps.duelInProgress = 0; duelAgainst->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0); - //Winner gets full health.. providing he's still alive - if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) - { - if (ent->health < ent->client->ps.stats[STAT_MAX_HEALTH]) - { + // Winner gets full health.. providing he's still alive + if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) { + if (ent->health < ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->client->ps.stats[STAT_HEALTH] = ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if (g_spawnInvulnerability.integer) - { + if (g_spawnInvulnerability.integer) { ent->client->ps.eFlags |= EF_INVULNERABLE; ent->client->invulnerableTimer = level.time + g_spawnInvulnerability.integer; } @@ -2505,90 +2058,71 @@ void ClientThink_real( gentity_t *ent ) { /* trap->SendServerCommand( ent-g_entities, va("print \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER")) ); - trap->SendServerCommand( duelAgainst-g_entities, va("print \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER")) ); + trap->SendServerCommand( duelAgainst-g_entities, va("print \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", + "PLDUELWINNER")) ); */ - //Private duel announcements are now made globally because we only want one duel at a time. - if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) - { - trap->SendServerCommand( -1, va("cp \"%s %s %s!\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER"), duelAgainst->client->pers.netname) ); - } - else - { //it was a draw, because we both managed to die in the same frame - trap->SendServerCommand( -1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELTIE")) ); + // Private duel announcements are now made globally because we only want one duel at a time. + if (ent->health > 0 && ent->client->ps.stats[STAT_HEALTH] > 0) { + trap->SendServerCommand(-1, va("cp \"%s %s %s!\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELWINNER"), + duelAgainst->client->pers.netname)); + } else { // it was a draw, because we both managed to die in the same frame + trap->SendServerCommand(-1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELTIE"))); } - } - else - { + } else { vec3_t vSub; float subLen = 0; VectorSubtract(ent->client->ps.origin, duelAgainst->client->ps.origin, vSub); subLen = VectorLength(vSub); - if (subLen >= 1024) - { + if (subLen >= 1024) { ent->client->ps.duelInProgress = 0; duelAgainst->client->ps.duelInProgress = 0; G_AddEvent(ent, EV_PRIVATE_DUEL, 0); G_AddEvent(duelAgainst, EV_PRIVATE_DUEL, 0); - trap->SendServerCommand( -1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELSTOP")) ); + trap->SendServerCommand(-1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELSTOP"))); } } } - if (ent->client->doingThrow > level.time) - { + if (ent->client->doingThrow > level.time) { gentity_t *throwee = &g_entities[ent->client->throwingIndex]; - if (!throwee->inuse || !throwee->client || throwee->health < 1 || - throwee->client->sess.sessionTeam == TEAM_SPECTATOR || - (throwee->client->ps.pm_flags & PMF_FOLLOW) || - throwee->client->throwingIndex != ent->s.number) - { + if (!throwee->inuse || !throwee->client || throwee->health < 1 || throwee->client->sess.sessionTeam == TEAM_SPECTATOR || + (throwee->client->ps.pm_flags & PMF_FOLLOW) || throwee->client->throwingIndex != ent->s.number) { ent->client->doingThrow = 0; ent->client->ps.forceHandExtend = HANDEXTEND_NONE; - if (throwee->inuse && throwee->client) - { + if (throwee->inuse && throwee->client) { throwee->client->ps.heldByClient = 0; throwee->client->beingThrown = 0; - if (throwee->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) - { + if (throwee->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) { throwee->client->ps.forceHandExtend = HANDEXTEND_NONE; } } } } - if (ent->client->beingThrown > level.time) - { + if (ent->client->beingThrown > level.time) { gentity_t *thrower = &g_entities[ent->client->throwingIndex]; - if (!thrower->inuse || !thrower->client || thrower->health < 1 || - thrower->client->sess.sessionTeam == TEAM_SPECTATOR || - (thrower->client->ps.pm_flags & PMF_FOLLOW) || - thrower->client->throwingIndex != ent->s.number) - { + if (!thrower->inuse || !thrower->client || thrower->health < 1 || thrower->client->sess.sessionTeam == TEAM_SPECTATOR || + (thrower->client->ps.pm_flags & PMF_FOLLOW) || thrower->client->throwingIndex != ent->s.number) { ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; - if (ent->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) - { + if (ent->client->ps.forceHandExtend != HANDEXTEND_POSTTHROWN) { ent->client->ps.forceHandExtend = HANDEXTEND_NONE; } - if (thrower->inuse && thrower->client) - { + if (thrower->inuse && thrower->client) { thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; } - } - else if (thrower->inuse && thrower->client && thrower->ghoul2 && - trap->G2API_HaveWeGhoul2Models(thrower->ghoul2)) - { + } else if (thrower->inuse && thrower->client && thrower->ghoul2 && trap->G2API_HaveWeGhoul2Models(thrower->ghoul2)) { #if 0 int lHandBolt = trap->G2API_AddBolt(thrower->ghoul2, 0, "*l_hand"); int pelBolt = trap->G2API_AddBolt(thrower->ghoul2, 0, "pelvis"); @@ -2604,16 +2138,16 @@ void ClientThink_real( gentity_t *ent ) { vec3_t entDir, otherAngles; vec3_t fwd, right; - //Always look at the thrower. - VectorSubtract( thrower->client->ps.origin, ent->client->ps.origin, entDir ); - VectorCopy( ent->client->ps.viewangles, otherAngles ); - otherAngles[YAW] = vectoyaw( entDir ); - SetClientViewAngle( ent, otherAngles ); + // Always look at the thrower. + VectorSubtract(thrower->client->ps.origin, ent->client->ps.origin, entDir); + VectorCopy(ent->client->ps.viewangles, otherAngles); + otherAngles[YAW] = vectoyaw(entDir); + SetClientViewAngle(ent, otherAngles); VectorCopy(thrower->client->ps.viewangles, tAngles); tAngles[PITCH] = tAngles[ROLL] = 0; - //Get the direction between the pelvis and position of the hand + // Get the direction between the pelvis and position of the hand #if 0 mdxaBone_t boltMatrix, pBoltMatrix; @@ -2626,33 +2160,31 @@ void ClientThink_real( gentity_t *ent ) { pBoltOrg[0] = pBoltMatrix.matrix[0][3]; pBoltOrg[1] = pBoltMatrix.matrix[1][3]; pBoltOrg[2] = pBoltMatrix.matrix[2][3]; -#else //above tends to not work once in a while, for various reasons I suppose. +#else // above tends to not work once in a while, for various reasons I suppose. VectorCopy(thrower->client->ps.origin, pBoltOrg); AngleVectors(tAngles, fwd, right, 0); - boltOrg[0] = pBoltOrg[0] + fwd[0]*8 + right[0]*pDif; - boltOrg[1] = pBoltOrg[1] + fwd[1]*8 + right[1]*pDif; + boltOrg[0] = pBoltOrg[0] + fwd[0] * 8 + right[0] * pDif; + boltOrg[1] = pBoltOrg[1] + fwd[1] * 8 + right[1] * pDif; boltOrg[2] = pBoltOrg[2]; #endif - //G_TestLine(boltOrg, pBoltOrg, 0x0000ff, 50); + // G_TestLine(boltOrg, pBoltOrg, 0x0000ff, 50); VectorSubtract(ent->client->ps.origin, boltOrg, vDif); - if (VectorLength(vDif) > 32.0f && (thrower->client->doingThrow - level.time) < 4500) - { //the hand is too far away, and can no longer hold onto us, so escape. + if (VectorLength(vDif) > 32.0f && + (thrower->client->doingThrow - level.time) < 4500) { // the hand is too far away, and can no longer hold onto us, so escape. ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; - G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") ); + G_EntitySound(thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav")); ent->client->ps.forceDodgeAnim = 2; ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; ent->client->ps.forceHandExtendTime = level.time + 500; ent->client->ps.velocity[2] = 400; G_PreDefSound(ent->client->ps.origin, PDSOUND_FORCEJUMP); - } - else if ((client->beingThrown - level.time) < 4000) - { //step into the next part of the throw, and go flying back + } else if ((client->beingThrown - level.time) < 4000) { // step into the next part of the throw, and go flying back float vScale = 400.0f; ent->client->ps.forceHandExtend = HANDEXTEND_POSTTHROWN; ent->client->ps.forceHandExtendTime = level.time + 1200; @@ -2668,20 +2200,18 @@ void ClientThink_real( gentity_t *ent ) { thrower->client->doingThrow = 0; AngleVectors(thrower->client->ps.viewangles, vDif, 0, 0); - ent->client->ps.velocity[0] = vDif[0]*vScale; - ent->client->ps.velocity[1] = vDif[1]*vScale; + ent->client->ps.velocity[0] = vDif[0] * vScale; + ent->client->ps.velocity[1] = vDif[1] * vScale; ent->client->ps.velocity[2] = 400; - G_EntitySound( ent, CHAN_VOICE, G_SoundIndex("*pain100.wav") ); - G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*jump1.wav") ); + G_EntitySound(ent, CHAN_VOICE, G_SoundIndex("*pain100.wav")); + G_EntitySound(thrower, CHAN_VOICE, G_SoundIndex("*jump1.wav")); - //Set the thrower as the "other killer", so if we die from fall/impact damage he is credited. + // Set the thrower as the "other killer", so if we die from fall/impact damage he is credited. ent->client->ps.otherKiller = thrower->s.number; ent->client->ps.otherKillerTime = level.time + 8000; ent->client->ps.otherKillerDebounceTime = level.time + 100; - } - else - { //see if we can move to be next to the hand.. if it's not clear, break the throw. + } else { // see if we can move to be next to the hand.. if it's not clear, break the throw. vec3_t intendedOrigin; trace_t tr; trace_t tr2; @@ -2690,30 +2220,26 @@ void ClientThink_real( gentity_t *ent ) { VectorNormalize(vDif); VectorClear(ent->client->ps.velocity); - intendedOrigin[0] = pBoltOrg[0] + vDif[0]*pDif; - intendedOrigin[1] = pBoltOrg[1] + vDif[1]*pDif; + intendedOrigin[0] = pBoltOrg[0] + vDif[0] * pDif; + intendedOrigin[1] = pBoltOrg[1] + vDif[1] * pDif; intendedOrigin[2] = thrower->client->ps.origin[2]; trap->Trace(&tr, intendedOrigin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, ent->clipmask, qfalse, 0, 0); trap->Trace(&tr2, ent->client->ps.origin, ent->r.mins, ent->r.maxs, intendedOrigin, ent->s.number, CONTENTS_SOLID, qfalse, 0, 0); - if (tr.fraction == 1.0 && !tr.startsolid && tr2.fraction == 1.0 && !tr2.startsolid) - { + if (tr.fraction == 1.0 && !tr.startsolid && tr2.fraction == 1.0 && !tr2.startsolid) { VectorCopy(intendedOrigin, ent->client->ps.origin); - if ((client->beingThrown - level.time) < 4800) - { - ent->client->ps.heldByClient = thrower->s.number+1; + if ((client->beingThrown - level.time) < 4800) { + ent->client->ps.heldByClient = thrower->s.number + 1; } - } - else - { //if the guy can't be put here then it's time to break the throw off. + } else { // if the guy can't be put here then it's time to break the throw off. ent->client->ps.heldByClient = 0; ent->client->beingThrown = 0; thrower->client->doingThrow = 0; thrower->client->ps.forceHandExtend = HANDEXTEND_NONE; - G_EntitySound( thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav") ); + G_EntitySound(thrower, CHAN_VOICE, G_SoundIndex("*pain25.wav")); ent->client->ps.forceDodgeAnim = 2; ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; @@ -2724,9 +2250,7 @@ void ClientThink_real( gentity_t *ent ) { } } } - } - else if (ent->client->ps.heldByClient) - { + } else if (ent->client->ps.heldByClient) { ent->client->ps.heldByClient = 0; } @@ -2736,8 +2260,8 @@ void ClientThink_real( gentity_t *ent ) { } */ - //Will probably never need this again, since we have g2 properly serverside now. - //But just in case. + // Will probably never need this again, since we have g2 properly serverside now. + // But just in case. /* if (client->ps.usingATST && ent->health > 0) { //we have special shot clip boxes as an ATST @@ -2753,88 +2277,72 @@ void ClientThink_real( gentity_t *ent ) { } */ - //rww - moved this stuff into the pmove code so that it's predicted properly - //BG_AdjustClientSpeed(&client->ps, &client->pers.cmd, level.time); + // rww - moved this stuff into the pmove code so that it's predicted properly + // BG_AdjustClientSpeed(&client->ps, &client->pers.cmd, level.time); // set up for pmove oldEventSequence = client->ps.eventSequence; - memset (&pmove, 0, sizeof(pmove)); + memset(&pmove, 0, sizeof(pmove)); - if ( ent->flags & FL_FORCE_GESTURE ) { + if (ent->flags & FL_FORCE_GESTURE) { ent->flags &= ~FL_FORCE_GESTURE; ent->client->pers.cmd.buttons |= BUTTON_GESTURE; } - if (ent->client && ent->client->ps.fallingToDeath && - (level.time - FALL_FADE_TIME) > ent->client->ps.fallingToDeath) - { //die! - if (ent->health > 0) - { + if (ent->client && ent->client->ps.fallingToDeath && (level.time - FALL_FADE_TIME) > ent->client->ps.fallingToDeath) { // die! + if (ent->health > 0) { gentity_t *otherKiller = ent; - if (ent->client->ps.otherKillerTime > level.time && - ent->client->ps.otherKiller != ENTITYNUM_NONE) - { + if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.otherKiller != ENTITYNUM_NONE) { otherKiller = &g_entities[ent->client->ps.otherKiller]; - if (!otherKiller->inuse) - { + if (!otherKiller->inuse) { otherKiller = ent; } } G_Damage(ent, otherKiller, otherKiller, NULL, ent->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_FALLING); - //player_die(ent, ent, ent, 100000, MOD_FALLING); - // if (!ent->NPC) - // { - // ClientRespawn(ent); - // } - // ent->client->ps.fallingToDeath = 0; + // player_die(ent, ent, ent, 100000, MOD_FALLING); + // if (!ent->NPC) + // { + // ClientRespawn(ent); + // } + // ent->client->ps.fallingToDeath = 0; - G_MuteSound(ent->s.number, CHAN_VOICE); //stop screaming, because you are dead! + G_MuteSound(ent->s.number, CHAN_VOICE); // stop screaming, because you are dead! } } - if (ent->client->ps.otherKillerTime > level.time && - ent->client->ps.groundEntityNum != ENTITYNUM_NONE && - ent->client->ps.otherKillerDebounceTime < level.time) - { + if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.groundEntityNum != ENTITYNUM_NONE && + ent->client->ps.otherKillerDebounceTime < level.time) { ent->client->ps.otherKillerTime = 0; ent->client->ps.otherKiller = ENTITYNUM_NONE; - } - else if (ent->client->ps.otherKillerTime > level.time && - ent->client->ps.groundEntityNum == ENTITYNUM_NONE) - { - if (ent->client->ps.otherKillerDebounceTime < (level.time + 100)) - { + } else if (ent->client->ps.otherKillerTime > level.time && ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { + if (ent->client->ps.otherKillerDebounceTime < (level.time + 100)) { ent->client->ps.otherKillerDebounceTime = level.time + 100; } } -// WP_ForcePowersUpdate( ent, msec, ucmd); //update any active force powers -// WP_SaberPositionUpdate(ent, ucmd); //check the server-side saber point, do apprioriate server-side actions (effects are cs-only) + // WP_ForcePowersUpdate( ent, msec, ucmd); //update any active force powers + // WP_SaberPositionUpdate(ent, ucmd); //check the server-side saber point, do apprioriate server-side actions (effects are cs-only) - //NOTE: can't put USE here *before* PMove!! - if ( ent->client->ps.useDelay > level.time - && ent->client->ps.m_iVehicleNum ) - {//when in a vehicle, debounce the use... + // NOTE: can't put USE here *before* PMove!! + if (ent->client->ps.useDelay > level.time && ent->client->ps.m_iVehicleNum) { // when in a vehicle, debounce the use... ucmd->buttons &= ~BUTTON_USE; } - //FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) - G_AddPushVecToUcmd( ent, ucmd ); + // FIXME: need to do this before check to avoid walls and cliffs (or just cliffs?) + G_AddPushVecToUcmd(ent, ucmd); - //play/stop any looping sounds tied to controlled movement - G_CheckMovingLoopingSounds( ent, ucmd ); + // play/stop any looping sounds tied to controlled movement + G_CheckMovingLoopingSounds(ent, ucmd); pmove.ps = &client->ps; pmove.cmd = *ucmd; - if ( pmove.ps->pm_type == PM_DEAD ) { + if (pmove.ps->pm_type == PM_DEAD) { pmove.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; - } - else if ( ent->r.svFlags & SVF_BOT ) { + } else if (ent->r.svFlags & SVF_BOT) { pmove.tracemask = MASK_PLAYERSOLID | CONTENTS_MONSTERCLIP; - } - else { + } else { pmove.tracemask = MASK_PLAYERSOLID; } pmove.trace = SV_PMTrace; @@ -2846,33 +2354,27 @@ void ClientThink_real( gentity_t *ent ) { pmove.pmove_msec = pmove_msec.integer; pmove.pmove_float = pmove_float.integer; - pmove.animations = bgAllAnims[ent->localAnimIndex].anims;//NULL; + pmove.animations = bgAllAnims[ent->localAnimIndex].anims; // NULL; - //rww - bgghoul2 + // rww - bgghoul2 pmove.ghoul2 = NULL; #ifdef _DEBUG - if (g_disableServerG2.integer) - { + if (g_disableServerG2.integer) { - } - else + } else #endif - if (ent->ghoul2) - { - if (ent->localAnimIndex > 1) - { //if it isn't humanoid then we will be having none of this. + if (ent->ghoul2) { + if (ent->localAnimIndex > 1) { // if it isn't humanoid then we will be having none of this. pmove.ghoul2 = NULL; - } - else - { + } else { pmove.ghoul2 = ent->ghoul2; pmove.g2Bolts_LFoot = trap->G2API_AddBolt(ent->ghoul2, 0, "*l_leg_foot"); pmove.g2Bolts_RFoot = trap->G2API_AddBolt(ent->ghoul2, 0, "*r_leg_foot"); } } - //point the saber data to the right place + // point the saber data to the right place #if 0 k = 0; while (k < MAX_SABERS) @@ -2889,9 +2391,9 @@ void ClientThink_real( gentity_t *ent ) { } #endif - //I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that) + // I'll just do this every frame in case the scale changes in realtime (don't need to update the g2 inst for that) VectorCopy(ent->modelScale, pmove.modelScale); - //rww end bgghoul2 + // rww end bgghoul2 pmove.gametype = level.gametype; pmove.debugMelee = g_debugMelee.integer; @@ -2901,7 +2403,7 @@ void ClientThink_real( gentity_t *ent ) { pmove.nonHumanoid = (ent->localAnimIndex > 0); - VectorCopy( client->ps.origin, client->oldOrigin ); + VectorCopy(client->ps.origin, client->oldOrigin); /* if (level.intermissionQueued != 0 && g_singlePlayer.integer) { @@ -2918,43 +2420,34 @@ void ClientThink_real( gentity_t *ent ) { } */ - //Set up bg entity data + // Set up bg entity data pmove.baseEnt = (bgEntity_t *)g_entities; pmove.entSize = sizeof(gentity_t); - if (ent->client->ps.saberLockTime > level.time) - { + if (ent->client->ps.saberLockTime > level.time) { gentity_t *blockOpp = &g_entities[ent->client->ps.saberLockEnemy]; - if (blockOpp && blockOpp->inuse && blockOpp->client) - { + if (blockOpp && blockOpp->inuse && blockOpp->client) { vec3_t lockDir, lockAng; - //VectorClear( ent->client->ps.velocity ); - VectorSubtract( blockOpp->r.currentOrigin, ent->r.currentOrigin, lockDir ); - //lockAng[YAW] = vectoyaw( defDir ); + // VectorClear( ent->client->ps.velocity ); + VectorSubtract(blockOpp->r.currentOrigin, ent->r.currentOrigin, lockDir); + // lockAng[YAW] = vectoyaw( defDir ); vectoangles(lockDir, lockAng); - SetClientViewAngle( ent, lockAng ); + SetClientViewAngle(ent, lockAng); } - if ( ent->client->ps.saberLockHitCheckTime < level.time ) - {//have moved to next frame since last lock push - ent->client->ps.saberLockHitCheckTime = level.time;//so we don't push more than once per server frame - if ( ( ent->client->buttons & BUTTON_ATTACK ) && ! ( ent->client->oldbuttons & BUTTON_ATTACK ) ) - { - if ( ent->client->ps.saberLockHitIncrementTime < level.time ) - {//have moved to next frame since last saberlock attack button press + if (ent->client->ps.saberLockHitCheckTime < level.time) { // have moved to next frame since last lock push + ent->client->ps.saberLockHitCheckTime = level.time; // so we don't push more than once per server frame + if ((ent->client->buttons & BUTTON_ATTACK) && !(ent->client->oldbuttons & BUTTON_ATTACK)) { + if (ent->client->ps.saberLockHitIncrementTime < level.time) { // have moved to next frame since last saberlock attack button press int lockHits = 0; - ent->client->ps.saberLockHitIncrementTime = level.time;//so we don't register an attack key press more than once per server frame - //NOTE: FP_SABER_OFFENSE level already taken into account in PM_SaberLocked - if ( (ent->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowerLevel[FP_RAGE]; - } - else - {//normal attack - switch ( ent->client->ps.fd.saberAnimLevel ) - { + ent->client->ps.saberLockHitIncrementTime = level.time; // so we don't register an attack key press more than once per server frame + // NOTE: FP_SABER_OFFENSE level already taken into account in PM_SaberLocked + if ((ent->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) { // raging: push harder + lockHits = 1 + ent->client->ps.fd.forcePowerLevel[FP_RAGE]; + } else { // normal attack + switch (ent->client->ps.fd.saberAnimLevel) { case SS_FAST: lockHits = 1; break; @@ -2970,86 +2463,68 @@ void ClientThink_real( gentity_t *ent ) { break; } } - if ( ent->client->ps.fd.forceRageRecoveryTime > level.time - && Q_irand( 0, 1 ) ) - {//finished raging: weak + if (ent->client->ps.fd.forceRageRecoveryTime > level.time && Q_irand(0, 1)) { // finished raging: weak lockHits -= 1; } lockHits += ent->client->saber[0].lockBonus; - if ( ent->client->saber[1].model[0] - && !ent->client->ps.saberHolstered ) - { + if (ent->client->saber[1].model[0] && !ent->client->ps.saberHolstered) { lockHits += ent->client->saber[1].lockBonus; } ent->client->ps.saberLockHits += lockHits; - if ( g_saberLockRandomNess.integer ) - { - ent->client->ps.saberLockHits += Q_irand( 0, g_saberLockRandomNess.integer ); - if ( ent->client->ps.saberLockHits < 0 ) - { + if (g_saberLockRandomNess.integer) { + ent->client->ps.saberLockHits += Q_irand(0, g_saberLockRandomNess.integer); + if (ent->client->ps.saberLockHits < 0) { ent->client->ps.saberLockHits = 0; } } } } - if ( ent->client->ps.saberLockHits > 0 ) - { - if ( !ent->client->ps.saberLockAdvance ) - { + if (ent->client->ps.saberLockHits > 0) { + if (!ent->client->ps.saberLockAdvance) { ent->client->ps.saberLockHits--; } ent->client->ps.saberLockAdvance = qtrue; } } - } - else - { + } else { ent->client->ps.saberLockFrame = 0; - //check for taunt - if ( (pmove.cmd.generic_cmd == GENCMD_ENGAGE_DUEL) && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) ) - {//already in a duel, make it a taunt command + // check for taunt + if ((pmove.cmd.generic_cmd == GENCMD_ENGAGE_DUEL) && + (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL)) { // already in a duel, make it a taunt command pmove.cmd.buttons |= BUTTON_GESTURE; } } - if (ent->s.number >= MAX_CLIENTS) - { + if (ent->s.number >= MAX_CLIENTS) { VectorCopy(ent->r.mins, pmove.mins); VectorCopy(ent->r.maxs, pmove.maxs); #if 1 - if (ent->s.NPC_class == CLASS_VEHICLE && - ent->m_pVehicle ) - { - if ( ent->m_pVehicle->m_pPilot) - { //vehicles want to use their last pilot ucmd I guess - if ((level.time - ent->m_pVehicle->m_ucmd.serverTime) > 2000) - { //Previous owner disconnected, maybe + if (ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle) { + if (ent->m_pVehicle->m_pPilot) { // vehicles want to use their last pilot ucmd I guess + if ((level.time - ent->m_pVehicle->m_ucmd.serverTime) > 2000) { // Previous owner disconnected, maybe ent->m_pVehicle->m_ucmd.serverTime = level.time; - ent->client->ps.commandTime = level.time-100; + ent->client->ps.commandTime = level.time - 100; msec = 100; } memcpy(&pmove.cmd, &ent->m_pVehicle->m_ucmd, sizeof(usercmd_t)); - //no veh can strafe + // no veh can strafe pmove.cmd.rightmove = 0; - //no crouching or jumping! + // no crouching or jumping! pmove.cmd.upmove = 0; - //NOTE: button presses were getting lost! + // NOTE: button presses were getting lost! assert(g_entities[ent->m_pVehicle->m_pPilot->s.number].client); - pmove.cmd.buttons = (g_entities[ent->m_pVehicle->m_pPilot->s.number].client->pers.cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)); - } - if ( ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - { - if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//ATST crushes anything underneath it - gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; - if ( under && under->health && under->takedamage ) - { - vec3_t down = {0,0,-1}; - //FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin - G_Damage( under, ent, ent, down, under->r.currentOrigin, 100, 0, MOD_CRUSH ); + pmove.cmd.buttons = (g_entities[ent->m_pVehicle->m_pPilot->s.number].client->pers.cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK)); + } + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { + if (ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { // ATST crushes anything underneath it + gentity_t *under = &g_entities[ent->client->ps.groundEntityNum]; + if (under && under->health && under->takedamage) { + vec3_t down = {0, 0, -1}; + // FIXME: we'll be doing traces down from each foot, so we'll have a real impact origin + G_Damage(under, ent, ent, down, under->r.currentOrigin, 100, 0, MOD_CRUSH); } } } @@ -3057,34 +2532,27 @@ void ClientThink_real( gentity_t *ent ) { #endif } - Pmove (&pmove); + Pmove(&pmove); - if (ent->client->solidHack) - { - if (ent->client->solidHack > level.time) - { //whee! + if (ent->client->solidHack) { + if (ent->client->solidHack > level.time) { // whee! ent->r.contents = 0; - } - else - { + } else { ent->r.contents = CONTENTS_BODY; ent->client->solidHack = 0; } } - if ( ent->NPC ) - { - VectorCopy( ent->client->ps.viewangles, ent->r.currentAngles ); + if (ent->NPC) { + VectorCopy(ent->client->ps.viewangles, ent->r.currentAngles); } - if (pmove.checkDuelLoss) - { - if (pmove.checkDuelLoss > 0 && (pmove.checkDuelLoss <= MAX_CLIENTS || (pmove.checkDuelLoss < (MAX_GENTITIES-1) && g_entities[pmove.checkDuelLoss-1].s.eType == ET_NPC) ) ) - { - gentity_t *clientLost = &g_entities[pmove.checkDuelLoss-1]; + if (pmove.checkDuelLoss) { + if (pmove.checkDuelLoss > 0 && + (pmove.checkDuelLoss <= MAX_CLIENTS || (pmove.checkDuelLoss < (MAX_GENTITIES - 1) && g_entities[pmove.checkDuelLoss - 1].s.eType == ET_NPC))) { + gentity_t *clientLost = &g_entities[pmove.checkDuelLoss - 1]; - if (clientLost && clientLost->inuse && clientLost->client && Q_irand(0, 40) > clientLost->health) - { + if (clientLost && clientLost->inuse && clientLost->client && Q_irand(0, 40) > clientLost->health) { vec3_t attDir; VectorSubtract(ent->client->ps.origin, clientLost->client->ps.origin, attDir); VectorNormalize(attDir); @@ -3096,17 +2564,15 @@ void ClientThink_real( gentity_t *ent ) { gGAvoidDismember = 1; G_Damage(clientLost, ent, ent, attDir, clientLost->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_SABER); - if (clientLost->health < 1) - { + if (clientLost->health < 1) { gGAvoidDismember = 2; G_CheckForDismemberment(clientLost, ent, clientLost->client->ps.origin, 999, (clientLost->client->ps.legsAnim), qfalse); } gGAvoidDismember = 0; - } - else if (clientLost && clientLost->inuse && clientLost->client && - clientLost->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && clientLost->client->ps.saberEntityNum) - { //if we didn't knock down it was a circle lock. So as punishment, make them lose their saber and go into a proper anim + } else if (clientLost && clientLost->inuse && clientLost->client && clientLost->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && + clientLost->client->ps.saberEntityNum) { // if we didn't knock down it was a circle lock. So as punishment, make them lose their saber + // and go into a proper anim saberCheckKnockdown_DuelLoss(&g_entities[clientLost->client->ps.saberEntityNum], clientLost, ent); } } @@ -3114,29 +2580,22 @@ void ClientThink_real( gentity_t *ent ) { pmove.checkDuelLoss = 0; } - if (pmove.cmd.generic_cmd && - (pmove.cmd.generic_cmd != ent->client->lastGenCmd || ent->client->lastGenCmdTime < level.time)) - { + if (pmove.cmd.generic_cmd && (pmove.cmd.generic_cmd != ent->client->lastGenCmd || ent->client->lastGenCmdTime < level.time)) { ent->client->lastGenCmd = pmove.cmd.generic_cmd; if (pmove.cmd.generic_cmd != GENCMD_FORCE_THROW && - pmove.cmd.generic_cmd != GENCMD_FORCE_PULL) - { //these are the only two where you wouldn't care about a delay between - ent->client->lastGenCmdTime = level.time + 300; //default 100ms debounce between issuing the same command. + pmove.cmd.generic_cmd != GENCMD_FORCE_PULL) { // these are the only two where you wouldn't care about a delay between + ent->client->lastGenCmdTime = level.time + 300; // default 100ms debounce between issuing the same command. } - switch(pmove.cmd.generic_cmd) - { + switch (pmove.cmd.generic_cmd) { case 0: break; case GENCMD_SABERSWITCH: Cmd_ToggleSaber_f(ent); break; case GENCMD_ENGAGE_DUEL: - if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) - {//already in a duel, made it a taunt command - } - else - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // already in a duel, made it a taunt command + } else { Cmd_EngageDuel_f(ent); } break; @@ -3174,86 +2633,64 @@ void ClientThink_real( gentity_t *ent ) { ForceSeeing(ent); break; case GENCMD_USE_SEEKER: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) && - G_ItemUsable(&ent->client->ps, HI_SEEKER) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SEEKER)) && G_ItemUsable(&ent->client->ps, HI_SEEKER)) { ItemUse_Seeker(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_SEEKER, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_SEEKER, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SEEKER); } break; case GENCMD_USE_FIELD: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) && - G_ItemUsable(&ent->client->ps, HI_SHIELD) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SHIELD)) && G_ItemUsable(&ent->client->ps, HI_SHIELD)) { ItemUse_Shield(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_SHIELD, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_SHIELD, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SHIELD); } break; case GENCMD_USE_BACTA: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) && - G_ItemUsable(&ent->client->ps, HI_MEDPAC) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC)) && G_ItemUsable(&ent->client->ps, HI_MEDPAC)) { ItemUse_MedPack(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_MEDPAC, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC); } break; case GENCMD_USE_BACTABIG: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) && - G_ItemUsable(&ent->client->ps, HI_MEDPAC_BIG) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_MEDPAC_BIG)) && G_ItemUsable(&ent->client->ps, HI_MEDPAC_BIG)) { ItemUse_MedPack_Big(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_MEDPAC_BIG, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_MEDPAC_BIG, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_MEDPAC_BIG); } break; case GENCMD_USE_ELECTROBINOCULARS: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && - G_ItemUsable(&ent->client->ps, HI_BINOCULARS) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && G_ItemUsable(&ent->client->ps, HI_BINOCULARS)) { ItemUse_Binoculars(ent); - if (ent->client->ps.zoomMode == 0) - { - G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1); - } - else - { - G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2); + if (ent->client->ps.zoomMode == 0) { + G_AddEvent(ent, EV_USE_ITEM0 + HI_BINOCULARS, 1); + } else { + G_AddEvent(ent, EV_USE_ITEM0 + HI_BINOCULARS, 2); } } break; case GENCMD_ZOOM: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && - G_ItemUsable(&ent->client->ps, HI_BINOCULARS) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_BINOCULARS)) && G_ItemUsable(&ent->client->ps, HI_BINOCULARS)) { ItemUse_Binoculars(ent); - if (ent->client->ps.zoomMode == 0) - { - G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 1); - } - else - { - G_AddEvent(ent, EV_USE_ITEM0+HI_BINOCULARS, 2); + if (ent->client->ps.zoomMode == 0) { + G_AddEvent(ent, EV_USE_ITEM0 + HI_BINOCULARS, 1); + } else { + G_AddEvent(ent, EV_USE_ITEM0 + HI_BINOCULARS, 2); } } break; case GENCMD_USE_SENTRY: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) && - G_ItemUsable(&ent->client->ps, HI_SENTRY_GUN) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_SENTRY_GUN)) && G_ItemUsable(&ent->client->ps, HI_SENTRY_GUN)) { ItemUse_Sentry(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_SENTRY_GUN, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_SENTRY_GUN, 0); ent->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_SENTRY_GUN); } break; case GENCMD_USE_JETPACK: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) && - G_ItemUsable(&ent->client->ps, HI_JETPACK) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) && G_ItemUsable(&ent->client->ps, HI_JETPACK)) { ItemUse_Jetpack(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_JETPACK, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_JETPACK, 0); /* if (ent->client->ps.zoomMode == 0) { @@ -3267,40 +2704,29 @@ void ClientThink_real( gentity_t *ent ) { } break; case GENCMD_USE_HEALTHDISP: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) && - G_ItemUsable(&ent->client->ps, HI_HEALTHDISP) ) - { - //ItemUse_UseDisp(ent, HI_HEALTHDISP); - G_AddEvent(ent, EV_USE_ITEM0+HI_HEALTHDISP, 0); + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) && G_ItemUsable(&ent->client->ps, HI_HEALTHDISP)) { + // ItemUse_UseDisp(ent, HI_HEALTHDISP); + G_AddEvent(ent, EV_USE_ITEM0 + HI_HEALTHDISP, 0); } break; case GENCMD_USE_AMMODISP: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP)) && - G_ItemUsable(&ent->client->ps, HI_AMMODISP) ) - { - //ItemUse_UseDisp(ent, HI_AMMODISP); - G_AddEvent(ent, EV_USE_ITEM0+HI_AMMODISP, 0); + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP)) && G_ItemUsable(&ent->client->ps, HI_AMMODISP)) { + // ItemUse_UseDisp(ent, HI_AMMODISP); + G_AddEvent(ent, EV_USE_ITEM0 + HI_AMMODISP, 0); } break; case GENCMD_USE_EWEB: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_EWEB)) && - G_ItemUsable(&ent->client->ps, HI_EWEB) ) - { + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_EWEB)) && G_ItemUsable(&ent->client->ps, HI_EWEB)) { ItemUse_UseEWeb(ent); - G_AddEvent(ent, EV_USE_ITEM0+HI_EWEB, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_EWEB, 0); } break; case GENCMD_USE_CLOAK: - if ( (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_CLOAK)) && - G_ItemUsable(&ent->client->ps, HI_CLOAK) ) - { - if ( ent->client->ps.powerups[PW_CLOAKED] ) - {//decloak - Jedi_Decloak( ent ); - } - else - {//cloak - Jedi_Cloak( ent ); + if ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_CLOAK)) && G_ItemUsable(&ent->client->ps, HI_CLOAK)) { + if (ent->client->ps.powerups[PW_CLOAKED]) { // decloak + Jedi_Decloak(ent); + } else { // cloak + Jedi_Cloak(ent); } } break; @@ -3308,19 +2734,19 @@ void ClientThink_real( gentity_t *ent ) { Cmd_SaberAttackCycle_f(ent); break; case GENCMD_TAUNT: - G_SetTauntAnim( ent, TAUNT_TAUNT ); + G_SetTauntAnim(ent, TAUNT_TAUNT); break; case GENCMD_BOW: - G_SetTauntAnim( ent, TAUNT_BOW ); + G_SetTauntAnim(ent, TAUNT_BOW); break; case GENCMD_MEDITATE: - G_SetTauntAnim( ent, TAUNT_MEDITATE ); + G_SetTauntAnim(ent, TAUNT_MEDITATE); break; case GENCMD_FLOURISH: - G_SetTauntAnim( ent, TAUNT_FLOURISH ); + G_SetTauntAnim(ent, TAUNT_FLOURISH); break; case GENCMD_GLOAT: - G_SetTauntAnim( ent, TAUNT_GLOAT ); + G_SetTauntAnim(ent, TAUNT_GLOAT); break; default: break; @@ -3328,71 +2754,64 @@ void ClientThink_real( gentity_t *ent ) { } // save results of pmove - if ( ent->client->ps.eventSequence != oldEventSequence ) { + if (ent->client->ps.eventSequence != oldEventSequence) { ent->eventTime = level.time; } if (g_smoothClients.integer) { - BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse ); - //rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. - } - else { - BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse ); + BG_PlayerStateToEntityStateExtraPolate(&ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse); + // rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. + } else { + BG_PlayerStateToEntityState(&ent->client->ps, &ent->s, qfalse); } - if (isNPC) - { + if (isNPC) { ent->s.eType = ET_NPC; } - SendPendingPredictableEvents( &ent->client->ps ); + SendPendingPredictableEvents(&ent->client->ps); - if ( !( ent->client->ps.eFlags & EF_FIRING ) ) { - client->fireHeld = qfalse; // for grapple + if (!(ent->client->ps.eFlags & EF_FIRING)) { + client->fireHeld = qfalse; // for grapple } // use the snapped origin for linking so it matches client predicted versions - VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin ); + VectorCopy(ent->s.pos.trBase, ent->r.currentOrigin); - if (ent->s.eType != ET_NPC || - ent->s.NPC_class != CLASS_VEHICLE || - !ent->m_pVehicle || - !ent->m_pVehicle->m_iRemovedSurfaces) - { //let vehicles that are getting broken apart do their own crazy sizing stuff - VectorCopy (pmove.mins, ent->r.mins); - VectorCopy (pmove.maxs, ent->r.maxs); + if (ent->s.eType != ET_NPC || ent->s.NPC_class != CLASS_VEHICLE || !ent->m_pVehicle || + !ent->m_pVehicle->m_iRemovedSurfaces) { // let vehicles that are getting broken apart do their own crazy sizing stuff + VectorCopy(pmove.mins, ent->r.mins); + VectorCopy(pmove.maxs, ent->r.maxs); } ent->waterlevel = pmove.waterlevel; ent->watertype = pmove.watertype; // execute client events - ClientEvents( ent, oldEventSequence ); + ClientEvents(ent, oldEventSequence); - if ( pmove.useEvent ) - { - //TODO: Use -// TryUse( ent ); + if (pmove.useEvent) { + // TODO: Use + // TryUse( ent ); } - if ((ent->client->pers.cmd.buttons & BUTTON_USE) && ent->client->ps.useDelay < level.time) - { + if ((ent->client->pers.cmd.buttons & BUTTON_USE) && ent->client->ps.useDelay < level.time) { TryUse(ent); ent->client->ps.useDelay = level.time + 100; } // link entity now, after any personal teleporters have been used - trap->LinkEntity ((sharedEntity_t *)ent); - if ( !ent->client->noclip ) { - G_TouchTriggers( ent ); + trap->LinkEntity((sharedEntity_t *)ent); + if (!ent->client->noclip) { + G_TouchTriggers(ent); } // NOTE: now copy the exact origin over otherwise clients can be snapped into solid - VectorCopy( ent->client->ps.origin, ent->r.currentOrigin ); + VectorCopy(ent->client->ps.origin, ent->r.currentOrigin); - //test for solid areas in the AAS file -// BotTestAAS(ent->r.currentOrigin); + // test for solid areas in the AAS file + // BotTestAAS(ent->r.currentOrigin); // touch other objects - ClientImpacts( ent, &pmove ); + ClientImpacts(ent, &pmove); // save results of triggers and client events if (ent->client->ps.eventSequence != oldEventSequence) { @@ -3404,54 +2823,48 @@ void ClientThink_real( gentity_t *ent ) { client->buttons = ucmd->buttons; client->latched_buttons |= client->buttons & ~client->oldbuttons; -// G_VehicleAttachDroidUnit( ent ); + // G_VehicleAttachDroidUnit( ent ); // Did we kick someone in our pmove sequence? - if (client->ps.forceKickFlip) - { - gentity_t *faceKicked = &g_entities[client->ps.forceKickFlip-1]; + if (client->ps.forceKickFlip) { + gentity_t *faceKicked = &g_entities[client->ps.forceKickFlip - 1]; if (faceKicked && faceKicked->client && (!OnSameTeam(ent, faceKicked) || g_friendlyFire.integer) && (!faceKicked->client->ps.duelInProgress || faceKicked->client->ps.duelIndex == ent->s.number) && - (!ent->client->ps.duelInProgress || ent->client->ps.duelIndex == faceKicked->s.number)) - { - if ( faceKicked && faceKicked->client && faceKicked->health && faceKicked->takedamage ) - {//push them away and do pain + (!ent->client->ps.duelInProgress || ent->client->ps.duelIndex == faceKicked->s.number)) { + if (faceKicked && faceKicked->client && faceKicked->health && faceKicked->takedamage) { // push them away and do pain vec3_t oppDir; - int strength = (int)VectorNormalize2( client->ps.velocity, oppDir ); + int strength = (int)VectorNormalize2(client->ps.velocity, oppDir); strength *= 0.05; - VectorScale( oppDir, -1, oppDir ); + VectorScale(oppDir, -1, oppDir); - G_Damage( faceKicked, ent, ent, oppDir, client->ps.origin, strength, DAMAGE_NO_ARMOR, MOD_MELEE ); + G_Damage(faceKicked, ent, ent, oppDir, client->ps.origin, strength, DAMAGE_NO_ARMOR, MOD_MELEE); - if ( faceKicked->client->ps.weapon != WP_SABER || - faceKicked->client->ps.fd.saberAnimLevel != FORCE_LEVEL_3 || - (!BG_SaberInAttack(faceKicked->client->ps.saberMove) && !PM_SaberInStart(faceKicked->client->ps.saberMove) && !PM_SaberInReturn(faceKicked->client->ps.saberMove) && !PM_SaberInTransition(faceKicked->client->ps.saberMove)) ) - { - if (faceKicked->health > 0 && - faceKicked->client->ps.stats[STAT_HEALTH] > 0 && - faceKicked->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) - { - if (BG_KnockDownable(&faceKicked->client->ps) && Q_irand(1, 10) <= 3) - { //only actually knock over sometimes, but always do velocity hit + if (faceKicked->client->ps.weapon != WP_SABER || faceKicked->client->ps.fd.saberAnimLevel != FORCE_LEVEL_3 || + (!BG_SaberInAttack(faceKicked->client->ps.saberMove) && !PM_SaberInStart(faceKicked->client->ps.saberMove) && + !PM_SaberInReturn(faceKicked->client->ps.saberMove) && !PM_SaberInTransition(faceKicked->client->ps.saberMove))) { + if (faceKicked->health > 0 && faceKicked->client->ps.stats[STAT_HEALTH] > 0 && + faceKicked->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) { + if (BG_KnockDownable(&faceKicked->client->ps) && Q_irand(1, 10) <= 3) { // only actually knock over sometimes, but always do velocity + // hit faceKicked->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; faceKicked->client->ps.forceHandExtendTime = level.time + 1100; - faceKicked->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim + faceKicked->client->ps.forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim } faceKicked->client->ps.otherKiller = ent->s.number; faceKicked->client->ps.otherKillerTime = level.time + 5000; faceKicked->client->ps.otherKillerDebounceTime = level.time + 100; - faceKicked->client->ps.velocity[0] = oppDir[0]*(strength*40); - faceKicked->client->ps.velocity[1] = oppDir[1]*(strength*40); + faceKicked->client->ps.velocity[0] = oppDir[0] * (strength * 40); + faceKicked->client->ps.velocity[1] = oppDir[1] * (strength * 40); faceKicked->client->ps.velocity[2] = 200; } } - G_Sound( faceKicked, CHAN_AUTO, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + G_Sound(faceKicked, CHAN_AUTO, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); } } @@ -3459,64 +2872,52 @@ void ClientThink_real( gentity_t *ent ) { } // check for respawning - if ( client->ps.stats[STAT_HEALTH] <= 0 - && !(client->ps.eFlags2&EF2_HELD_BY_MONSTER)//can't respawn while being eaten - && ent->s.eType != ET_NPC ) { + if (client->ps.stats[STAT_HEALTH] <= 0 && !(client->ps.eFlags2 & EF2_HELD_BY_MONSTER) // can't respawn while being eaten + && ent->s.eType != ET_NPC) { // wait for the attack button to be pressed - if ( level.time > client->respawnTime && !gDoSlowMoDuel ) { + if (level.time > client->respawnTime && !gDoSlowMoDuel) { // forcerespawn is to prevent users from waiting out powerups int forceRes = g_forceRespawn.integer; - if (level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_POWERDUEL) { forceRes = 1; - } - else if (level.gametype == GT_SIEGE && g_siegeRespawn.integer) - { //wave respawning on + } else if (level.gametype == GT_SIEGE && g_siegeRespawn.integer) { // wave respawning on forceRes = 1; } - if ( forceRes > 0 && - ( level.time - client->respawnTime ) > forceRes * 1000 ) { - ClientRespawn( ent ); + if (forceRes > 0 && (level.time - client->respawnTime) > forceRes * 1000) { + ClientRespawn(ent); return; } // pressing attack or use is the normal respawn method - if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) { - ClientRespawn( ent ); + if (ucmd->buttons & (BUTTON_ATTACK | BUTTON_USE_HOLDABLE)) { + ClientRespawn(ent); } - } - else if (gDoSlowMoDuel) - { + } else if (gDoSlowMoDuel) { client->respawnTime = level.time + 1000; } return; } // perform once-a-second actions - ClientTimerActions( ent, msec ); + ClientTimerActions(ent, msec); - G_UpdateClientBroadcasts ( ent ); + G_UpdateClientBroadcasts(ent); - //try some idle anims on ent if getting no input and not moving for some time - G_CheckClientIdle( ent, ucmd ); + // try some idle anims on ent if getting no input and not moving for some time + G_CheckClientIdle(ent, ucmd); // This code was moved here from clientThink to fix a problem with g_synchronousClients // being set to 1 when in vehicles. - if ( ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum ) - {//driving a vehicle - //run it - if (g_entities[ent->client->ps.m_iVehicleNum].inuse && g_entities[ent->client->ps.m_iVehicleNum].client) - { + if (ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum) { // driving a vehicle + // run it + if (g_entities[ent->client->ps.m_iVehicleNum].inuse && g_entities[ent->client->ps.m_iVehicleNum].client) { ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd); - } - else - { //vehicle no longer valid? + } else { // vehicle no longer valid? ent->client->ps.m_iVehicleNum = 0; } } - } /* @@ -3526,25 +2927,21 @@ G_CheckClientTimeouts Checks whether a client has exceded any timeouts and act accordingly ================== */ -void G_CheckClientTimeouts ( gentity_t *ent ) -{ +void G_CheckClientTimeouts(gentity_t *ent) { // Only timeout supported right now is the timeout to spectator mode - if ( !g_timeouttospec.integer ) - { + if (!g_timeouttospec.integer) { return; } // Already a spectator, no need to boot them to spectator - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) - { + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { return; } // See how long its been since a command was received by the client and if its // longer than the timeout to spectator then force this client into spectator mode - if ( level.time - ent->client->pers.cmd.serverTime > g_timeouttospec.integer * 1000 ) - { - SetTeam ( ent, "spectator" ); + if (level.time - ent->client->pers.cmd.serverTime > g_timeouttospec.integer * 1000) { + SetTeam(ent, "spectator"); } } @@ -3555,84 +2952,81 @@ ClientThink A new command has arrived from the client ================== */ -void ClientThink( int clientNum, usercmd_t *ucmd ) { +void ClientThink(int clientNum, usercmd_t *ucmd) { gentity_t *ent; ent = g_entities + clientNum; - if (clientNum < MAX_CLIENTS) - { - trap->GetUsercmd( clientNum, &ent->client->pers.cmd ); + if (clientNum < MAX_CLIENTS) { + trap->GetUsercmd(clientNum, &ent->client->pers.cmd); } // mark the time we got info, so we can display the // phone jack if they don't get any for a while ent->client->lastCmdTime = level.time; - if (ucmd) - { + if (ucmd) { ent->client->pers.cmd = *ucmd; } -/* This was moved to clientthink_real, but since its sort of a risky change i left it here for - now as a more concrete reference - BSD + /* This was moved to clientthink_real, but since its sort of a risky change i left it here for + now as a more concrete reference - BSD - if ( clientNum < MAX_CLIENTS - && ent->client->ps.m_iVehicleNum ) - {//driving a vehicle - if (g_entities[ent->client->ps.m_iVehicleNum].client) - { - gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; + if ( clientNum < MAX_CLIENTS + && ent->client->ps.m_iVehicleNum ) + {//driving a vehicle + if (g_entities[ent->client->ps.m_iVehicleNum].client) + { + gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; - if (veh->m_pVehicle && - veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) - { //only take input from the pilot... - veh->client->ps.commandTime = ent->client->ps.commandTime; - memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t)); - if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) - { //forced input if "chat bubble" is up - veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; - veh->m_pVehicle->m_ucmd.forwardmove = 0; - veh->m_pVehicle->m_ucmd.rightmove = 0; - veh->m_pVehicle->m_ucmd.upmove = 0; + if (veh->m_pVehicle && + veh->m_pVehicle->m_pPilot == (bgEntity_t *)ent) + { //only take input from the pilot... + veh->client->ps.commandTime = ent->client->ps.commandTime; + memcpy(&veh->m_pVehicle->m_ucmd, &ent->client->pers.cmd, sizeof(usercmd_t)); + if ( veh->m_pVehicle->m_ucmd.buttons & BUTTON_TALK ) + { //forced input if "chat bubble" is up + veh->m_pVehicle->m_ucmd.buttons = BUTTON_TALK; + veh->m_pVehicle->m_ucmd.forwardmove = 0; + veh->m_pVehicle->m_ucmd.rightmove = 0; + veh->m_pVehicle->m_ucmd.upmove = 0; + } } } } - } -*/ - if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) { - ClientThink_real( ent ); + */ + if (!(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer) { + ClientThink_real(ent); } // vehicles are clients and when running synchronous they still need to think here // so special case them. - else if ( clientNum >= MAX_CLIENTS ) { - ClientThink_real( ent ); + else if (clientNum >= MAX_CLIENTS) { + ClientThink_real(ent); } -/* This was moved to clientthink_real, but since its sort of a risky change i left it here for - now as a more concrete reference - BSD + /* This was moved to clientthink_real, but since its sort of a risky change i left it here for + now as a more concrete reference - BSD - if ( clientNum < MAX_CLIENTS - && ent->client->ps.m_iVehicleNum ) - {//driving a vehicle - //run it - if (g_entities[ent->client->ps.m_iVehicleNum].inuse && - g_entities[ent->client->ps.m_iVehicleNum].client) - { - ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd); - } - else - { //vehicle no longer valid? - ent->client->ps.m_iVehicleNum = 0; + if ( clientNum < MAX_CLIENTS + && ent->client->ps.m_iVehicleNum ) + {//driving a vehicle + //run it + if (g_entities[ent->client->ps.m_iVehicleNum].inuse && + g_entities[ent->client->ps.m_iVehicleNum].client) + { + ClientThink(ent->client->ps.m_iVehicleNum, &g_entities[ent->client->ps.m_iVehicleNum].m_pVehicle->m_ucmd); + } + else + { //vehicle no longer valid? + ent->client->ps.m_iVehicleNum = 0; + } } - } -*/ + */ } - -void G_RunClient( gentity_t *ent ) { +void G_RunClient(gentity_t *ent) { // force client updates if they're not sending packets at roughly 4hz - if ( !(ent->r.svFlags & SVF_BOT) && g_forceClientUpdateRate.integer && ent->client->lastCmdTime < level.time - g_forceClientUpdateRate.integer ) { - trap->GetUsercmd( ent-g_entities, &ent->client->pers.cmd ); + if (!(ent->r.svFlags & SVF_BOT) && g_forceClientUpdateRate.integer && ent->client->lastCmdTime < level.time - g_forceClientUpdateRate.integer) { + trap->GetUsercmd(ent - g_entities, &ent->client->pers.cmd); ent->client->lastCmdTime = level.time; @@ -3641,65 +3035,63 @@ void G_RunClient( gentity_t *ent ) { ent->client->pers.cmd.buttons = 0; ent->client->pers.cmd.forwardmove = ent->client->pers.cmd.rightmove = ent->client->pers.cmd.upmove = 0; - ClientThink_real( ent ); + ClientThink_real(ent); return; } - if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) { + if (!(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer) { return; } ent->client->pers.cmd.serverTime = level.time; - ClientThink_real( ent ); + ClientThink_real(ent); } - /* ================== SpectatorClientEndFrame ================== */ -void SpectatorClientEndFrame( gentity_t *ent ) { - gclient_t *cl; +void SpectatorClientEndFrame(gentity_t *ent) { + gclient_t *cl; - if (ent->s.eType == ET_NPC) - { + if (ent->s.eType == ET_NPC) { assert(0); return; } // if we are doing a chase cam or a remote view, grab the latest info - if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) { - int clientNum;//, flags; + if (ent->client->sess.spectatorState == SPECTATOR_FOLLOW) { + int clientNum; //, flags; clientNum = ent->client->sess.spectatorClient; // team follow1 and team follow2 go to whatever clients are playing - if ( clientNum == -1 ) { + if (clientNum == -1) { clientNum = level.follow1; - } else if ( clientNum == -2 ) { + } else if (clientNum == -2) { clientNum = level.follow2; } - if ( clientNum >= 0 ) { - cl = &level.clients[ clientNum ]; - if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) { - //flags = (cl->mGameFlags & ~(PSG_VOTED | PSG_TEAMVOTED)) | (ent->client->mGameFlags & (PSG_VOTED | PSG_TEAMVOTED)); - //ent->client->mGameFlags = flags; + if (clientNum >= 0) { + cl = &level.clients[clientNum]; + if (cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR) { + // flags = (cl->mGameFlags & ~(PSG_VOTED | PSG_TEAMVOTED)) | (ent->client->mGameFlags & (PSG_VOTED | PSG_TEAMVOTED)); + // ent->client->mGameFlags = flags; ent->client->ps.eFlags = cl->ps.eFlags; ent->client->ps = cl->ps; ent->client->ps.pm_flags |= PMF_FOLLOW; return; } else { // drop them to free spectators unless they are dedicated camera followers - if ( ent->client->sess.spectatorClient >= 0 ) { + if (ent->client->sess.spectatorClient >= 0) { ent->client->sess.spectatorState = SPECTATOR_FREE; - ClientBegin( ent->client - level.clients, qtrue ); + ClientBegin(ent->client - level.clients, qtrue); } } } } - if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) { + if (ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD) { ent->client->ps.pm_flags |= PMF_SCOREBOARD; } else { ent->client->ps.pm_flags &= ~PMF_SCOREBOARD; @@ -3715,24 +3107,23 @@ A fast client will have multiple ClientThink for each ClientEdFrame, while a slow client may have multiple ClientEndFrame between ClientThink. ============== */ -void ClientEndFrame( gentity_t *ent ) { - int i; +void ClientEndFrame(gentity_t *ent) { + int i; qboolean isNPC = qfalse; - if (ent->s.eType == ET_NPC) - { + if (ent->s.eType == ET_NPC) { isNPC = qtrue; } - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - SpectatorClientEndFrame( ent ); + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + SpectatorClientEndFrame(ent); return; } // turn off any expired powerups - for ( i = 0 ; i < MAX_POWERUPS ; i++ ) { - if ( ent->client->ps.powerups[ i ] < level.time ) { - ent->client->ps.powerups[ i ] = 0; + for (i = 0; i < MAX_POWERUPS; i++) { + if (ent->client->ps.powerups[i] < level.time) { + ent->client->ps.powerups[i] = 0; } } @@ -3748,47 +3139,43 @@ void ClientEndFrame( gentity_t *ent ) { // If the end of unit layout is displayed, don't give // the player any normal movement attributes // - if ( level.intermissiontime ) { - if ( ent->s.number < MAX_CLIENTS - || ent->client->NPC_class == CLASS_VEHICLE ) - {//players and vehicles do nothing in intermissions + if (level.intermissiontime) { + if (ent->s.number < MAX_CLIENTS || ent->client->NPC_class == CLASS_VEHICLE) { // players and vehicles do nothing in intermissions return; } } // burn from lava, etc - P_WorldEffects (ent); + P_WorldEffects(ent); // apply all the damage taken this frame - P_DamageFeedback (ent); + P_DamageFeedback(ent); // add the EF_CONNECTION flag if we haven't gotten commands recently - if ( level.time - ent->client->lastCmdTime > 1000 ) + if (level.time - ent->client->lastCmdTime > 1000) ent->client->ps.eFlags |= EF_CONNECTION; else ent->client->ps.eFlags &= ~EF_CONNECTION; - ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... + ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health... - G_SetClientSound (ent); + G_SetClientSound(ent); // set the latest infor if (g_smoothClients.integer) { - BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse ); - //rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. - } - else { - BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qfalse ); + BG_PlayerStateToEntityStateExtraPolate(&ent->client->ps, &ent->s, ent->client->ps.commandTime, qfalse); + // rww - 12-03-02 - Don't snap the origin of players! It screws prediction all up. + } else { + BG_PlayerStateToEntityState(&ent->client->ps, &ent->s, qfalse); } - if (isNPC) - { + if (isNPC) { ent->s.eType = ET_NPC; } - SendPendingPredictableEvents( &ent->client->ps ); + SendPendingPredictableEvents(&ent->client->ps); // set the bit for the reachability area the client is currently in -// i = trap->AAS_PointReachabilityAreaIndex( ent->client->ps.origin ); -// ent->client->areabits[i >> 3] |= 1 << (i & 7); + // i = trap->AAS_PointReachabilityAreaIndex( ent->client->ps.origin ); + // ent->client->areabits[i >> 3] |= 1 << (i & 7); } diff --git a/codemp/game/g_bot.c b/codemp/game/g_bot.c index 474370b3cb..97fe7079f3 100644 --- a/codemp/game/g_bot.c +++ b/codemp/game/g_bot.c @@ -25,19 +25,19 @@ along with this program; if not, see . #include "g_local.h" -#define BOT_BEGIN_DELAY_BASE 2000 -#define BOT_BEGIN_DELAY_INCREMENT 1500 +#define BOT_BEGIN_DELAY_BASE 2000 +#define BOT_BEGIN_DELAY_INCREMENT 1500 -#define BOT_SPAWN_QUEUE_DEPTH 16 +#define BOT_SPAWN_QUEUE_DEPTH 16 static struct botSpawnQueue_s { - int clientNum; - int spawnTime; + int clientNum; + int spawnTime; } botSpawnQueue[BOT_SPAWN_QUEUE_DEPTH]; vmCvar_t bot_minplayers; -float trap_Cvar_VariableValue( const char *var_name ) { +float trap_Cvar_VariableValue(const char *var_name) { char buf[MAX_CVAR_VALUE_STRING]; trap->Cvar_VariableStringBuffer(var_name, buf, sizeof(buf)); @@ -49,50 +49,50 @@ float trap_Cvar_VariableValue( const char *var_name ) { G_ParseInfos =============== */ -int G_ParseInfos( char *buf, int max, char *infos[] ) { - char *token; - int count; - char key[MAX_TOKEN_CHARS]; - char info[MAX_INFO_STRING]; +int G_ParseInfos(char *buf, int max, char *infos[]) { + char *token; + int count; + char key[MAX_TOKEN_CHARS]; + char info[MAX_INFO_STRING]; count = 0; - COM_BeginParseSession ("G_ParseInfos"); - while ( 1 ) { - token = COM_Parse( (const char **)(&buf) ); - if ( !token[0] ) { + COM_BeginParseSession("G_ParseInfos"); + while (1) { + token = COM_Parse((const char **)(&buf)); + if (!token[0]) { break; } - if ( strcmp( token, "{" ) ) { - Com_Printf( "Missing { in info file\n" ); + if (strcmp(token, "{")) { + Com_Printf("Missing { in info file\n"); break; } - if ( count == max ) { - Com_Printf( "Max infos exceeded\n" ); + if (count == max) { + Com_Printf("Max infos exceeded\n"); break; } info[0] = '\0'; - while ( 1 ) { - token = COM_ParseExt( (const char **)(&buf), qtrue ); - if ( !token[0] ) { - Com_Printf( "Unexpected end of info file\n" ); + while (1) { + token = COM_ParseExt((const char **)(&buf), qtrue); + if (!token[0]) { + Com_Printf("Unexpected end of info file\n"); break; } - if ( !strcmp( token, "}" ) ) { + if (!strcmp(token, "}")) { break; } - Q_strncpyz( key, token, sizeof( key ) ); + Q_strncpyz(key, token, sizeof(key)); - token = COM_ParseExt( (const char **)(&buf), qfalse ); - if ( !token[0] ) { - strcpy( token, "" ); + token = COM_ParseExt((const char **)(&buf), qfalse); + if (!token[0]) { + strcpy(token, ""); } - Info_SetValueForKey( info, key, token ); + Info_SetValueForKey(info, key, token); } - //NOTE: extra space for arena number - infos[count] = (char *) G_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1); + // NOTE: extra space for arena number + infos[count] = (char *)G_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1); if (infos[count]) { strcpy(infos[count], info); count++; @@ -106,61 +106,60 @@ int G_ParseInfos( char *buf, int max, char *infos[] ) { G_LoadArenasFromFile =============== */ -void G_LoadArenasFromFile( char *filename ) { - int len; - fileHandle_t f; - char buf[MAX_ARENAS_TEXT]; - - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "file not found: %s\n", filename ); +void G_LoadArenasFromFile(char *filename) { + int len; + fileHandle_t f; + char buf[MAX_ARENAS_TEXT]; + + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "file not found: %s\n", filename); return; } - if ( len >= MAX_ARENAS_TEXT ) { - trap->Print( S_COLOR_RED "file too large: %s is %i, max allowed is %i\n", filename, len, MAX_ARENAS_TEXT ); - trap->FS_Close( f ); + if (len >= MAX_ARENAS_TEXT) { + trap->Print(S_COLOR_RED "file too large: %s is %i, max allowed is %i\n", filename, len, MAX_ARENAS_TEXT); + trap->FS_Close(f); return; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); - level.arenas.num += G_ParseInfos( buf, MAX_ARENAS - level.arenas.num, &level.arenas.infos[level.arenas.num] ); + level.arenas.num += G_ParseInfos(buf, MAX_ARENAS - level.arenas.num, &level.arenas.infos[level.arenas.num]); } -int G_GetMapTypeBits(char *type) -{ +int G_GetMapTypeBits(char *type) { int typeBits = 0; - if( *type ) { - if( strstr( type, "ffa" ) ) { + if (*type) { + if (strstr(type, "ffa")) { typeBits |= (1 << GT_FFA); typeBits |= (1 << GT_TEAM); typeBits |= (1 << GT_JEDIMASTER); } - if( strstr( type, "holocron" ) ) { + if (strstr(type, "holocron")) { typeBits |= (1 << GT_HOLOCRON); } - if( strstr( type, "jedimaster" ) ) { + if (strstr(type, "jedimaster")) { typeBits |= (1 << GT_JEDIMASTER); } - if( strstr( type, "duel" ) ) { + if (strstr(type, "duel")) { typeBits |= (1 << GT_DUEL); typeBits |= (1 << GT_POWERDUEL); } - if( strstr( type, "powerduel" ) ) { + if (strstr(type, "powerduel")) { typeBits |= (1 << GT_DUEL); typeBits |= (1 << GT_POWERDUEL); } - if( strstr( type, "siege" ) ) { + if (strstr(type, "siege")) { typeBits |= (1 << GT_SIEGE); } - if( strstr( type, "ctf" ) ) { + if (strstr(type, "ctf")) { typeBits |= (1 << GT_CTF); typeBits |= (1 << GT_CTY); } - if( strstr( type, "cty" ) ) { + if (strstr(type, "cty")) { typeBits |= (1 << GT_CTY); } } else { @@ -171,78 +170,66 @@ int G_GetMapTypeBits(char *type) return typeBits; } -qboolean G_DoesMapSupportGametype(const char *mapname, int gametype) -{ - int typeBits = 0; - int thisLevel = -1; - int n = 0; - char *type = NULL; +qboolean G_DoesMapSupportGametype(const char *mapname, int gametype) { + int typeBits = 0; + int thisLevel = -1; + int n = 0; + char *type = NULL; - if (!level.arenas.infos[0]) - { + if (!level.arenas.infos[0]) { return qfalse; } - if (!mapname || !mapname[0]) - { + if (!mapname || !mapname[0]) { return qfalse; } - for( n = 0; n < level.arenas.num; n++ ) - { - type = Info_ValueForKey( level.arenas.infos[n], "map" ); + for (n = 0; n < level.arenas.num; n++) { + type = Info_ValueForKey(level.arenas.infos[n], "map"); - if (Q_stricmp(mapname, type) == 0) - { + if (Q_stricmp(mapname, type) == 0) { thisLevel = n; break; } } - if (thisLevel == -1) - { + if (thisLevel == -1) { return qfalse; } type = Info_ValueForKey(level.arenas.infos[thisLevel], "type"); typeBits = G_GetMapTypeBits(type); - if (typeBits & (1 << gametype)) - { //the map in question supports the gametype in question, so.. + if (typeBits & (1 << gametype)) { // the map in question supports the gametype in question, so.. return qtrue; } return qfalse; } -//rww - auto-obtain nextmap. I could've sworn Q3 had something like this, but I guess not. -const char *G_RefreshNextMap(int gametype, qboolean forced) -{ - int typeBits = 0; - int thisLevel = 0; - int desiredMap = 0; - int n = 0; - char *type = NULL; - qboolean loopingUp = qfalse; - vmCvar_t mapname; - - if (!g_autoMapCycle.integer && !forced) - { +// rww - auto-obtain nextmap. I could've sworn Q3 had something like this, but I guess not. +const char *G_RefreshNextMap(int gametype, qboolean forced) { + int typeBits = 0; + int thisLevel = 0; + int desiredMap = 0; + int n = 0; + char *type = NULL; + qboolean loopingUp = qfalse; + vmCvar_t mapname; + + if (!g_autoMapCycle.integer && !forced) { return NULL; } - if (!level.arenas.infos[0]) - { + if (!level.arenas.infos[0]) { return NULL; } - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); - for( n = 0; n < level.arenas.num; n++ ) - { - type = Info_ValueForKey( level.arenas.infos[n], "map" ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); + for (n = 0; n < level.arenas.num; n++) { + type = Info_ValueForKey(level.arenas.infos[n], "map"); - if (Q_stricmp(mapname.string, type) == 0) - { + if (Q_stricmp(mapname.string, type) == 0) { thisLevel = n; break; } @@ -250,14 +237,11 @@ const char *G_RefreshNextMap(int gametype, qboolean forced) desiredMap = thisLevel; - n = thisLevel+1; - while (n != thisLevel) - { //now cycle through the arena list and find the next map that matches the gametype we're in - if (!level.arenas.infos[n] || n >= level.arenas.num) - { - if (loopingUp) - { //this shouldn't happen, but if it does we have a null entry break in the arena file - //if this is the case just break out of the loop instead of sticking in an infinite loop + n = thisLevel + 1; + while (n != thisLevel) { // now cycle through the arena list and find the next map that matches the gametype we're in + if (!level.arenas.infos[n] || n >= level.arenas.num) { + if (loopingUp) { // this shouldn't happen, but if it does we have a null entry break in the arena file + // if this is the case just break out of the loop instead of sticking in an infinite loop break; } n = 0; @@ -267,8 +251,7 @@ const char *G_RefreshNextMap(int gametype, qboolean forced) type = Info_ValueForKey(level.arenas.infos[n], "type"); typeBits = G_GetMapTypeBits(type); - if (typeBits & (1 << gametype)) - { + if (typeBits & (1 << gametype)) { desiredMap = n; break; } @@ -276,18 +259,15 @@ const char *G_RefreshNextMap(int gametype, qboolean forced) n++; } - if (desiredMap == thisLevel) - { //If this is the only level for this game mode or we just can't find a map for this game mode, then nextmap - //will always restart. - trap->Cvar_Set( "nextmap", "map_restart 0"); - } - else - { //otherwise we have a valid nextmap to cycle to, so use it. - type = Info_ValueForKey( level.arenas.infos[desiredMap], "map" ); - trap->Cvar_Set( "nextmap", va("map %s", type)); + if (desiredMap == thisLevel) { // If this is the only level for this game mode or we just can't find a map for this game mode, then nextmap + // will always restart. + trap->Cvar_Set("nextmap", "map_restart 0"); + } else { // otherwise we have a valid nextmap to cycle to, so use it. + type = Info_ValueForKey(level.arenas.infos[desiredMap], "map"); + trap->Cvar_Set("nextmap", va("map %s", type)); } - return Info_ValueForKey( level.arenas.infos[desiredMap], "map" ); + return Info_ValueForKey(level.arenas.infos[desiredMap], "map"); } /* @@ -299,7 +279,7 @@ G_LoadArenas #define MAX_MAPS 256 #define MAPSBUFSIZE (MAX_MAPS * 64) -void G_LoadArenas( void ) { +void G_LoadArenas(void) { #if 0 int numdirs; char filename[MAX_QPATH]; @@ -329,39 +309,38 @@ void G_LoadArenas( void ) { #else - int numFiles; - char filelist[MAPSBUFSIZE]; - char filename[MAX_QPATH]; - char* fileptr; - int i, n; - int len; + int numFiles; + char filelist[MAPSBUFSIZE]; + char filename[MAX_QPATH]; + char *fileptr; + int i, n; + int len; level.arenas.num = 0; // get all arenas from .arena files - numFiles = trap->FS_GetFileList("scripts", ".arena", filelist, ARRAY_LEN(filelist) ); + numFiles = trap->FS_GetFileList("scripts", ".arena", filelist, ARRAY_LEN(filelist)); - fileptr = filelist; + fileptr = filelist; i = 0; if (numFiles > MAX_MAPS) numFiles = MAX_MAPS; - for(; i < numFiles; i++) { + for (; i < numFiles; i++) { len = strlen(fileptr); Com_sprintf(filename, sizeof(filename), "scripts/%s", fileptr); G_LoadArenasFromFile(filename); fileptr += len + 1; } -// trap->Print( "%i arenas parsed\n", level.arenas.num ); + // trap->Print( "%i arenas parsed\n", level.arenas.num ); - for( n = 0; n < level.arenas.num; n++ ) { - Info_SetValueForKey( level.arenas.infos[n], "num", va( "%i", n ) ); + for (n = 0; n < level.arenas.num; n++) { + Info_SetValueForKey(level.arenas.infos[n], "num", va("%i", n)); } G_RefreshNextMap(level.gametype, qfalse); #endif - } /* @@ -369,11 +348,11 @@ void G_LoadArenas( void ) { G_GetArenaInfoByNumber =============== */ -const char *G_GetArenaInfoByMap( const char *map ) { - int n; +const char *G_GetArenaInfoByMap(const char *map) { + int n; - for( n = 0; n < level.arenas.num; n++ ) { - if( Q_stricmp( Info_ValueForKey( level.arenas.infos[n], "map" ), map ) == 0 ) { + for (n = 0; n < level.arenas.num; n++) { + if (Q_stricmp(Info_ValueForKey(level.arenas.infos[n], "map"), map) == 0) { return level.arenas.infos[n]; } } @@ -413,37 +392,34 @@ static void PlayerIntroSound( const char *modelAndSkin ) { G_AddRandomBot =============== */ -void G_AddRandomBot( int team ) { - int i, n, num; - float skill; - char *value, netname[36], *teamstr; - gclient_t *cl; +void G_AddRandomBot(int team) { + int i, n, num; + float skill; + char *value, netname[36], *teamstr; + gclient_t *cl; num = 0; - for ( n = 0; n < level.bots.num ; n++ ) { - value = Info_ValueForKey( level.bots.infos[n], "name" ); + for (n = 0; n < level.bots.num; n++) { + value = Info_ValueForKey(level.bots.infos[n], "name"); // - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) { + if (!(g_entities[i].r.svFlags & SVF_BOT)) { continue; } - if (level.gametype == GT_SIEGE) - { - if ( team >= 0 && cl->sess.siegeDesiredTeam != team ) { + if (level.gametype == GT_SIEGE) { + if (team >= 0 && cl->sess.siegeDesiredTeam != team) { continue; } - } - else - { - if ( team >= 0 && cl->sess.sessionTeam != team ) { + } else { + if (team >= 0 && cl->sess.sessionTeam != team) { continue; } } - if ( !Q_stricmp( value, cl->pers.netname ) ) { + if (!Q_stricmp(value, cl->pers.netname)) { break; } } @@ -452,43 +428,43 @@ void G_AddRandomBot( int team ) { } } num = Q_flrand(0.0f, 1.0f) * num; - for ( n = 0; n < level.bots.num ; n++ ) { - value = Info_ValueForKey( level.bots.infos[n], "name" ); + for (n = 0; n < level.bots.num; n++) { + value = Info_ValueForKey(level.bots.infos[n], "name"); // - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) { + if (!(g_entities[i].r.svFlags & SVF_BOT)) { continue; } - if (level.gametype == GT_SIEGE) - { - if ( team >= 0 && cl->sess.siegeDesiredTeam != team ) { + if (level.gametype == GT_SIEGE) { + if (team >= 0 && cl->sess.siegeDesiredTeam != team) { continue; } - } - else - { - if ( team >= 0 && cl->sess.sessionTeam != team ) { + } else { + if (team >= 0 && cl->sess.sessionTeam != team) { continue; } } - if ( !Q_stricmp( value, cl->pers.netname ) ) { + if (!Q_stricmp(value, cl->pers.netname)) { break; } } if (i >= sv_maxclients.integer) { num--; if (num <= 0) { - skill = trap->Cvar_VariableIntegerValue( "g_npcspskill" ); - if (team == TEAM_RED) teamstr = "red"; - else if (team == TEAM_BLUE) teamstr = "blue"; - else teamstr = ""; + skill = trap->Cvar_VariableIntegerValue("g_npcspskill"); + if (team == TEAM_RED) + teamstr = "red"; + else if (team == TEAM_BLUE) + teamstr = "blue"; + else + teamstr = ""; Q_strncpyz(netname, value, sizeof(netname)); Q_CleanStr(netname); - trap->SendConsoleCommand( EXEC_INSERT, va("addbot \"%s\" %.2f %s %i\n", netname, skill, teamstr, 0) ); + trap->SendConsoleCommand(EXEC_INSERT, va("addbot \"%s\" %.2f %s %i\n", netname, skill, teamstr, 0)); return; } } @@ -500,27 +476,27 @@ void G_AddRandomBot( int team ) { G_RemoveRandomBot =============== */ -int G_RemoveRandomBot( int team ) { +int G_RemoveRandomBot(int team) { int i; - gclient_t *cl; + gclient_t *cl; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) + if (!(g_entities[i].r.svFlags & SVF_BOT)) continue; - if ( cl->sess.sessionTeam == TEAM_SPECTATOR && cl->sess.spectatorState == SPECTATOR_FOLLOW ) + if (cl->sess.sessionTeam == TEAM_SPECTATOR && cl->sess.spectatorState == SPECTATOR_FOLLOW) continue; - if ( level.gametype == GT_SIEGE && team >= 0 && cl->sess.siegeDesiredTeam != team ) + if (level.gametype == GT_SIEGE && team >= 0 && cl->sess.siegeDesiredTeam != team) continue; - else if ( team >= 0 && cl->sess.sessionTeam != team ) + else if (team >= 0 && cl->sess.sessionTeam != team) continue; - trap->SendConsoleCommand( EXEC_INSERT, va("clientkick %d\n", i) ); + trap->SendConsoleCommand(EXEC_INSERT, va("clientkick %d\n", i)); return qtrue; } return qfalse; @@ -531,20 +507,20 @@ int G_RemoveRandomBot( int team ) { G_CountHumanPlayers =============== */ -int G_CountHumanPlayers( int team ) { +int G_CountHumanPlayers(int team) { int i, num; - gclient_t *cl; + gclient_t *cl; num = 0; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( g_entities[i].r.svFlags & SVF_BOT ) { + if (g_entities[i].r.svFlags & SVF_BOT) { continue; } - if ( team >= 0 && cl->sess.sessionTeam != team ) { + if (team >= 0 && cl->sess.sessionTeam != team) { continue; } num++; @@ -557,38 +533,35 @@ int G_CountHumanPlayers( int team ) { G_CountBotPlayers =============== */ -int G_CountBotPlayers( int team ) { +int G_CountBotPlayers(int team) { int i, n, num; - gclient_t *cl; + gclient_t *cl; num = 0; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) { + if (!(g_entities[i].r.svFlags & SVF_BOT)) { continue; } - if (level.gametype == GT_SIEGE) - { - if ( team >= 0 && cl->sess.siegeDesiredTeam != team ) { + if (level.gametype == GT_SIEGE) { + if (team >= 0 && cl->sess.siegeDesiredTeam != team) { continue; } - } - else - { - if ( team >= 0 && cl->sess.sessionTeam != team ) { + } else { + if (team >= 0 && cl->sess.sessionTeam != team) { continue; } } num++; } - for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) { - if( !botSpawnQueue[n].spawnTime ) { + for (n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++) { + if (!botSpawnQueue[n].spawnTime) { continue; } - if ( botSpawnQueue[n].spawnTime > level.time ) { + if (botSpawnQueue[n].spawnTime > level.time) { continue; } num++; @@ -601,43 +574,39 @@ int G_CountBotPlayers( int team ) { G_CheckMinimumPlayers =============== */ -void G_CheckMinimumPlayers( void ) { +void G_CheckMinimumPlayers(void) { int minplayers; int humanplayers, botplayers; static int checkminimumplayers_time; - if (level.gametype == GT_SIEGE) - { + if (level.gametype == GT_SIEGE) { return; } - if (level.intermissiontime) return; - //only check once each 10 seconds + if (level.intermissiontime) + return; + // only check once each 10 seconds if (checkminimumplayers_time > level.time - 10000) { return; } checkminimumplayers_time = level.time; trap->Cvar_Update(&bot_minplayers); minplayers = bot_minplayers.integer; - if (minplayers <= 0) return; + if (minplayers <= 0) + return; - if (minplayers > sv_maxclients.integer) - { + if (minplayers > sv_maxclients.integer) { minplayers = sv_maxclients.integer; } - humanplayers = G_CountHumanPlayers( -1 ); - botplayers = G_CountBotPlayers( -1 ); + humanplayers = G_CountHumanPlayers(-1); + botplayers = G_CountBotPlayers(-1); - if ((humanplayers+botplayers) < minplayers) - { + if ((humanplayers + botplayers) < minplayers) { G_AddRandomBot(-1); - } - else if ((humanplayers+botplayers) > minplayers && botplayers) - { + } else if ((humanplayers + botplayers) > minplayers && botplayers) { // try to remove spectators first - if (!G_RemoveRandomBot(TEAM_SPECTATOR)) - { + if (!G_RemoveRandomBot(TEAM_SPECTATOR)) { // just remove the bot that is playing G_RemoveRandomBot(-1); } @@ -729,19 +698,19 @@ void G_CheckMinimumPlayers( void ) { G_CheckBotSpawn =============== */ -void G_CheckBotSpawn( void ) { - int n; +void G_CheckBotSpawn(void) { + int n; G_CheckMinimumPlayers(); - for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) { - if( !botSpawnQueue[n].spawnTime ) { + for (n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++) { + if (!botSpawnQueue[n].spawnTime) { continue; } - if ( botSpawnQueue[n].spawnTime > level.time ) { + if (botSpawnQueue[n].spawnTime > level.time) { continue; } - ClientBegin( botSpawnQueue[n].clientNum, qfalse ); + ClientBegin(botSpawnQueue[n].clientNum, qfalse); botSpawnQueue[n].spawnTime = 0; /* @@ -758,19 +727,19 @@ void G_CheckBotSpawn( void ) { AddBotToSpawnQueue =============== */ -static void AddBotToSpawnQueue( int clientNum, int delay ) { - int n; +static void AddBotToSpawnQueue(int clientNum, int delay) { + int n; - for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) { - if( !botSpawnQueue[n].spawnTime ) { + for (n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++) { + if (!botSpawnQueue[n].spawnTime) { botSpawnQueue[n].spawnTime = level.time + delay; botSpawnQueue[n].clientNum = clientNum; return; } } - trap->Print( S_COLOR_YELLOW "Unable to delay spawn\n" ); - ClientBegin( clientNum, qfalse ); + trap->Print(S_COLOR_YELLOW "Unable to delay spawn\n"); + ClientBegin(clientNum, qfalse); } /* @@ -781,11 +750,11 @@ Called on client disconnect to make sure the delayed spawn doesn't happen on a freed index =============== */ -void G_RemoveQueuedBotBegin( int clientNum ) { - int n; +void G_RemoveQueuedBotBegin(int clientNum) { + int n; - for( n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++ ) { - if( botSpawnQueue[n].clientNum == clientNum ) { + for (n = 0; n < BOT_SPAWN_QUEUE_DEPTH; n++) { + if (botSpawnQueue[n].clientNum == clientNum) { botSpawnQueue[n].spawnTime = 0; return; } @@ -797,18 +766,18 @@ void G_RemoveQueuedBotBegin( int clientNum ) { G_BotConnect =============== */ -qboolean G_BotConnect( int clientNum, qboolean restart ) { - bot_settings_t settings; - char userinfo[MAX_INFO_STRING]; +qboolean G_BotConnect(int clientNum, qboolean restart) { + bot_settings_t settings; + char userinfo[MAX_INFO_STRING]; - trap->GetUserinfo( clientNum, userinfo, sizeof(userinfo) ); + trap->GetUserinfo(clientNum, userinfo, sizeof(userinfo)); - Q_strncpyz( settings.personalityfile, Info_ValueForKey( userinfo, "personality" ), sizeof(settings.personalityfile) ); - settings.skill = atof( Info_ValueForKey( userinfo, "skill" ) ); - Q_strncpyz( settings.team, Info_ValueForKey( userinfo, "team" ), sizeof(settings.team) ); + Q_strncpyz(settings.personalityfile, Info_ValueForKey(userinfo, "personality"), sizeof(settings.personalityfile)); + settings.skill = atof(Info_ValueForKey(userinfo, "skill")); + Q_strncpyz(settings.team, Info_ValueForKey(userinfo, "team"), sizeof(settings.team)); - if (!BotAISetupClient( clientNum, &settings, restart )) { - trap->DropClient( clientNum, "BotAISetupClient failed" ); + if (!BotAISetupClient(clientNum, &settings, restart)) { + trap->DropClient(clientNum, "BotAISetupClient failed"); return qfalse; } @@ -820,148 +789,162 @@ qboolean G_BotConnect( int clientNum, qboolean restart ) { G_AddBot =============== */ -static void G_AddBot( const char *name, float skill, const char *team, int delay, char *altname) { - gentity_t *bot = NULL; - int clientNum, preTeam = TEAM_FREE; - char userinfo[MAX_INFO_STRING] = {0}, - *botinfo = NULL, *key = NULL, *s = NULL, *botname = NULL, *model = NULL; +static void G_AddBot(const char *name, float skill, const char *team, int delay, char *altname) { + gentity_t *bot = NULL; + int clientNum, preTeam = TEAM_FREE; + char userinfo[MAX_INFO_STRING] = {0}, *botinfo = NULL, *key = NULL, *s = NULL, *botname = NULL, *model = NULL; // have the server allocate a client slot clientNum = trap->BotAllocateClient(); - if ( clientNum == -1 ) { -// trap->Print( S_COLOR_RED "Unable to add bot. All player slots are in use.\n" ); -// trap->Print( S_COLOR_RED "Start server with more 'open' slots.\n" ); - trap->SendServerCommand( -1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "UNABLE_TO_ADD_BOT"))); + if (clientNum == -1) { + // trap->Print( S_COLOR_RED "Unable to add bot. All player slots are in use.\n" ); + // trap->Print( S_COLOR_RED "Start server with more 'open' slots.\n" ); + trap->SendServerCommand(-1, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "UNABLE_TO_ADD_BOT"))); return; } // get the botinfo from bots.txt - botinfo = G_GetBotInfoByName( name ); - if ( !botinfo ) { - trap->Print( S_COLOR_RED "Error: Bot '%s' not defined\n", name ); - trap->BotFreeClient( clientNum ); + botinfo = G_GetBotInfoByName(name); + if (!botinfo) { + trap->Print(S_COLOR_RED "Error: Bot '%s' not defined\n", name); + trap->BotFreeClient(clientNum); return; } // create the bot's userinfo userinfo[0] = '\0'; - botname = Info_ValueForKey( botinfo, "funname" ); - if( !botname[0] ) - botname = Info_ValueForKey( botinfo, "name" ); + botname = Info_ValueForKey(botinfo, "funname"); + if (!botname[0]) + botname = Info_ValueForKey(botinfo, "name"); // check for an alternative name - if ( altname && altname[0] ) + if (altname && altname[0]) botname = altname; - Info_SetValueForKey( userinfo, "name", botname ); - Info_SetValueForKey( userinfo, "rate", "25000" ); - Info_SetValueForKey( userinfo, "snaps", "20" ); - Info_SetValueForKey( userinfo, "ip", "localhost" ); - Info_SetValueForKey( userinfo, "skill", va("%.2f", skill) ); - - if ( skill >= 1 && skill < 2 ) Info_SetValueForKey( userinfo, "handicap", "50" ); - else if ( skill >= 2 && skill < 3 ) Info_SetValueForKey( userinfo, "handicap", "70" ); - else if ( skill >= 3 && skill < 4 ) Info_SetValueForKey( userinfo, "handicap", "90" ); - else Info_SetValueForKey( userinfo, "handicap", "100" ); + Info_SetValueForKey(userinfo, "name", botname); + Info_SetValueForKey(userinfo, "rate", "25000"); + Info_SetValueForKey(userinfo, "snaps", "20"); + Info_SetValueForKey(userinfo, "ip", "localhost"); + Info_SetValueForKey(userinfo, "skill", va("%.2f", skill)); + + if (skill >= 1 && skill < 2) + Info_SetValueForKey(userinfo, "handicap", "50"); + else if (skill >= 2 && skill < 3) + Info_SetValueForKey(userinfo, "handicap", "70"); + else if (skill >= 3 && skill < 4) + Info_SetValueForKey(userinfo, "handicap", "90"); + else + Info_SetValueForKey(userinfo, "handicap", "100"); key = "model"; - model = Info_ValueForKey( botinfo, key ); - if ( !*model ) model = DEFAULT_MODEL"/default"; - Info_SetValueForKey( userinfo, key, model ); + model = Info_ValueForKey(botinfo, key); + if (!*model) + model = DEFAULT_MODEL "/default"; + Info_SetValueForKey(userinfo, key, model); key = "sex"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = Info_ValueForKey( botinfo, "gender" ); - if ( !*s ) s = "male"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = Info_ValueForKey(botinfo, "gender"); + if (!*s) + s = "male"; + Info_SetValueForKey(userinfo, key, s); key = "color1"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "4"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "4"; + Info_SetValueForKey(userinfo, key, s); key = "color2"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "4"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "4"; + Info_SetValueForKey(userinfo, key, s); key = "saber1"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = DEFAULT_SABER; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = DEFAULT_SABER; + Info_SetValueForKey(userinfo, key, s); key = "saber2"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "none"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "none"; + Info_SetValueForKey(userinfo, key, s); key = "forcepowers"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = DEFAULT_FORCEPOWERS; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = DEFAULT_FORCEPOWERS; + Info_SetValueForKey(userinfo, key, s); key = "cg_predictItems"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "1"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "1"; + Info_SetValueForKey(userinfo, key, s); key = "char_color_red"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "255"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "255"; + Info_SetValueForKey(userinfo, key, s); key = "char_color_green"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "255"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "255"; + Info_SetValueForKey(userinfo, key, s); key = "char_color_blue"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "255"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "255"; + Info_SetValueForKey(userinfo, key, s); key = "teamtask"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "0"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "0"; + Info_SetValueForKey(userinfo, key, s); key = "personality"; - s = Info_ValueForKey( botinfo, key ); - if ( !*s ) s = "botfiles/default.jkb"; - Info_SetValueForKey( userinfo, key, s ); + s = Info_ValueForKey(botinfo, key); + if (!*s) + s = "botfiles/default.jkb"; + Info_SetValueForKey(userinfo, key, s); // initialize the bot settings - if ( !team || !*team ) { - if ( level.gametype >= GT_TEAM ) { - if ( PickTeam( clientNum ) == TEAM_RED ) + if (!team || !*team) { + if (level.gametype >= GT_TEAM) { + if (PickTeam(clientNum) == TEAM_RED) team = "red"; else team = "blue"; - } - else + } else team = "red"; } - Info_SetValueForKey( userinfo, "team", team ); + Info_SetValueForKey(userinfo, "team", team); - bot = &g_entities[ clientNum ]; -// bot->r.svFlags |= SVF_BOT; -// bot->inuse = qtrue; + bot = &g_entities[clientNum]; + // bot->r.svFlags |= SVF_BOT; + // bot->inuse = qtrue; // register the userinfo - trap->SetUserinfo( clientNum, userinfo ); + trap->SetUserinfo(clientNum, userinfo); - if ( level.gametype >= GT_TEAM ) - { - if ( team && !Q_stricmp( team, "red" ) ) + if (level.gametype >= GT_TEAM) { + if (team && !Q_stricmp(team, "red")) bot->client->sess.sessionTeam = TEAM_RED; - else if ( team && !Q_stricmp( team, "blue" ) ) + else if (team && !Q_stricmp(team, "blue")) bot->client->sess.sessionTeam = TEAM_BLUE; else - bot->client->sess.sessionTeam = PickTeam( -1 ); + bot->client->sess.sessionTeam = PickTeam(-1); } - if ( level.gametype == GT_SIEGE ) - { + if (level.gametype == GT_SIEGE) { bot->client->sess.siegeDesiredTeam = bot->client->sess.sessionTeam; bot->client->sess.sessionTeam = TEAM_SPECTATOR; } @@ -969,66 +952,57 @@ static void G_AddBot( const char *name, float skill, const char *team, int delay preTeam = bot->client->sess.sessionTeam; // have it connect to the game as a normal client - if ( ClientConnect( clientNum, qtrue, qtrue ) ) + if (ClientConnect(clientNum, qtrue, qtrue)) return; - if ( bot->client->sess.sessionTeam != preTeam ) - { - trap->GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + if (bot->client->sess.sessionTeam != preTeam) { + trap->GetUserinfo(clientNum, userinfo, sizeof(userinfo)); - if ( bot->client->sess.sessionTeam == TEAM_SPECTATOR ) + if (bot->client->sess.sessionTeam == TEAM_SPECTATOR) bot->client->sess.sessionTeam = preTeam; - if ( bot->client->sess.sessionTeam == TEAM_RED ) + if (bot->client->sess.sessionTeam == TEAM_RED) team = "Red"; - else - { - if ( level.gametype == GT_SIEGE ) + else { + if (level.gametype == GT_SIEGE) team = (bot->client->sess.sessionTeam == TEAM_BLUE) ? "Blue" : "s"; else team = "Blue"; } - Info_SetValueForKey( userinfo, "team", team ); + Info_SetValueForKey(userinfo, "team", team); - trap->SetUserinfo( clientNum, userinfo ); + trap->SetUserinfo(clientNum, userinfo); - bot->client->ps.persistant[ PERS_TEAM ] = bot->client->sess.sessionTeam; + bot->client->ps.persistant[PERS_TEAM] = bot->client->sess.sessionTeam; - G_ReadSessionData( bot->client ); - if ( !ClientUserinfoChanged( clientNum ) ) + G_ReadSessionData(bot->client); + if (!ClientUserinfoChanged(clientNum)) return; } - if (level.gametype == GT_DUEL || - level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { int loners = 0; int doubles = 0; bot->client->sess.duelTeam = 0; G_PowerDuelCount(&loners, &doubles, qtrue); - if (!doubles || loners > (doubles/2)) - { - bot->client->sess.duelTeam = DUELTEAM_DOUBLE; - } - else - { - bot->client->sess.duelTeam = DUELTEAM_LONE; + if (!doubles || loners > (doubles / 2)) { + bot->client->sess.duelTeam = DUELTEAM_DOUBLE; + } else { + bot->client->sess.duelTeam = DUELTEAM_LONE; } bot->client->sess.sessionTeam = TEAM_SPECTATOR; SetTeam(bot, "s"); - } - else - { - if( delay == 0 ) { - ClientBegin( clientNum, qfalse ); + } else { + if (delay == 0) { + ClientBegin(clientNum, qfalse); return; } - AddBotToSpawnQueue( clientNum, delay ); + AddBotToSpawnQueue(clientNum, delay); } } @@ -1037,57 +1011,54 @@ static void G_AddBot( const char *name, float skill, const char *team, int delay Svcmd_AddBot_f =============== */ -void Svcmd_AddBot_f( void ) { - float skill; - int delay; - char name[MAX_TOKEN_CHARS]; - char altname[MAX_TOKEN_CHARS]; - char string[MAX_TOKEN_CHARS]; - char team[MAX_TOKEN_CHARS]; +void Svcmd_AddBot_f(void) { + float skill; + int delay; + char name[MAX_TOKEN_CHARS]; + char altname[MAX_TOKEN_CHARS]; + char string[MAX_TOKEN_CHARS]; + char team[MAX_TOKEN_CHARS]; // are bots enabled? - if ( !trap->Cvar_VariableIntegerValue( "bot_enable" ) ) { + if (!trap->Cvar_VariableIntegerValue("bot_enable")) { return; } // name - trap->Argv( 1, name, sizeof( name ) ); - if ( !name[0] ) { - trap->Print( "Usage: Addbot [skill 1-5] [team] [msec delay] [altname]\n" ); + trap->Argv(1, name, sizeof(name)); + if (!name[0]) { + trap->Print("Usage: Addbot [skill 1-5] [team] [msec delay] [altname]\n"); return; } // skill - trap->Argv( 2, string, sizeof( string ) ); - if ( !string[0] ) { + trap->Argv(2, string, sizeof(string)); + if (!string[0]) { skill = 4; - } - else { - skill = atof( string ); + } else { + skill = atof(string); } // team - trap->Argv( 3, team, sizeof( team ) ); + trap->Argv(3, team, sizeof(team)); // delay - trap->Argv( 4, string, sizeof( string ) ); - if ( !string[0] ) { + trap->Argv(4, string, sizeof(string)); + if (!string[0]) { delay = 0; - } - else { - delay = atoi( string ); + } else { + delay = atoi(string); } // alternative name - trap->Argv( 5, altname, sizeof( altname ) ); + trap->Argv(5, altname, sizeof(altname)); - G_AddBot( name, skill, team, delay, altname ); + G_AddBot(name, skill, team, delay, altname); // if this was issued during gameplay and we are playing locally, // go ahead and load the bot's media immediately - if ( level.time - level.startTime > 1000 && - trap->Cvar_VariableIntegerValue( "cl_running" ) ) { - trap->SendServerCommand( -1, "loaddefered\n" ); // FIXME: spelled wrong, but not changing for demo + if (level.time - level.startTime > 1000 && trap->Cvar_VariableIntegerValue("cl_running")) { + trap->SendServerCommand(-1, "loaddefered\n"); // FIXME: spelled wrong, but not changing for demo } } @@ -1096,7 +1067,7 @@ void Svcmd_AddBot_f( void ) { Svcmd_BotList_f =============== */ -void Svcmd_BotList_f( void ) { +void Svcmd_BotList_f(void) { int i; char name[MAX_NETNAME]; char funname[MAX_NETNAME]; @@ -1105,21 +1076,21 @@ void Svcmd_BotList_f( void ) { trap->Print("name model personality funname\n"); for (i = 0; i < level.bots.num; i++) { - Q_strncpyz(name, Info_ValueForKey( level.bots.infos[i], "name" ), sizeof( name )); - if ( !*name ) { - Q_strncpyz(name, "Padawan", sizeof( name )); + Q_strncpyz(name, Info_ValueForKey(level.bots.infos[i], "name"), sizeof(name)); + if (!*name) { + Q_strncpyz(name, "Padawan", sizeof(name)); } - Q_strncpyz(funname, Info_ValueForKey( level.bots.infos[i], "funname"), sizeof( funname )); - if ( !*funname ) { + Q_strncpyz(funname, Info_ValueForKey(level.bots.infos[i], "funname"), sizeof(funname)); + if (!*funname) { funname[0] = '\0'; } - Q_strncpyz(model, Info_ValueForKey( level.bots.infos[i], "model" ), sizeof( model )); - if ( !*model ) { - Q_strncpyz(model, DEFAULT_MODEL"/default", sizeof( model )); + Q_strncpyz(model, Info_ValueForKey(level.bots.infos[i], "model"), sizeof(model)); + if (!*model) { + Q_strncpyz(model, DEFAULT_MODEL "/default", sizeof(model)); } - Q_strncpyz(personality, Info_ValueForKey( level.bots.infos[i], "personality"), sizeof( personality )); - if (!*personality ) { - Q_strncpyz(personality, "botfiles/kyle.jkb", sizeof( personality )); + Q_strncpyz(personality, Info_ValueForKey(level.bots.infos[i], "personality"), sizeof(personality)); + if (!*personality) { + Q_strncpyz(personality, "botfiles/kyle.jkb", sizeof(personality)); } trap->Print("%-16s %-16s %-20s %-20s\n", name, model, COM_SkipPath(personality), funname); } @@ -1185,27 +1156,27 @@ static void G_SpawnBots( char *botList, int baseDelay ) { G_LoadBotsFromFile =============== */ -static void G_LoadBotsFromFile( char *filename ) { - int len; - fileHandle_t f; - char buf[MAX_BOTS_TEXT]; - - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "file not found: %s\n", filename ); +static void G_LoadBotsFromFile(char *filename) { + int len; + fileHandle_t f; + char buf[MAX_BOTS_TEXT]; + + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "file not found: %s\n", filename); return; } - if ( len >= MAX_BOTS_TEXT ) { - trap->Print( S_COLOR_RED "file too large: %s is %i, max allowed is %i\n", filename, len, MAX_BOTS_TEXT ); - trap->FS_Close( f ); + if (len >= MAX_BOTS_TEXT) { + trap->Print(S_COLOR_RED "file too large: %s is %i, max allowed is %i\n", filename, len, MAX_BOTS_TEXT); + trap->FS_Close(f); return; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); - level.bots.num += G_ParseInfos( buf, MAX_BOTS - level.bots.num, &level.bots.infos[level.bots.num] ); + level.bots.num += G_ParseInfos(buf, MAX_BOTS - level.bots.num, &level.bots.infos[level.bots.num]); } /* @@ -1213,40 +1184,39 @@ static void G_LoadBotsFromFile( char *filename ) { G_LoadBots =============== */ -static void G_LoadBots( void ) { - vmCvar_t botsFile; - int numdirs; - char filename[128]; - char dirlist[1024]; - char* dirptr; - int i; - int dirlen; +static void G_LoadBots(void) { + vmCvar_t botsFile; + int numdirs; + char filename[128]; + char dirlist[1024]; + char *dirptr; + int i; + int dirlen; - if ( !trap->Cvar_VariableIntegerValue( "bot_enable" ) ) { + if (!trap->Cvar_VariableIntegerValue("bot_enable")) { return; } level.bots.num = 0; - trap->Cvar_Register( &botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM ); - if( *botsFile.string ) { + trap->Cvar_Register(&botsFile, "g_botsFile", "", CVAR_INIT | CVAR_ROM); + if (*botsFile.string) { G_LoadBotsFromFile(botsFile.string); - } - else { - //G_LoadBotsFromFile("scripts/bots.txt"); + } else { + // G_LoadBotsFromFile("scripts/bots.txt"); G_LoadBotsFromFile("botfiles/bots.txt"); } // get all bots from .bot files - numdirs = trap->FS_GetFileList("scripts", ".bot", dirlist, 1024 ); - dirptr = dirlist; - for (i = 0; i < numdirs; i++, dirptr += dirlen+1) { + numdirs = trap->FS_GetFileList("scripts", ".bot", dirlist, 1024); + dirptr = dirlist; + for (i = 0; i < numdirs; i++, dirptr += dirlen + 1) { dirlen = strlen(dirptr); strcpy(filename, "scripts/"); strcat(filename, dirptr); G_LoadBotsFromFile(filename); } -// trap->Print( "%i bots parsed\n", level.bots.num ); + // trap->Print( "%i bots parsed\n", level.bots.num ); } /* @@ -1254,9 +1224,9 @@ static void G_LoadBots( void ) { G_GetBotInfoByNumber =============== */ -char *G_GetBotInfoByNumber( int num ) { - if( num < 0 || num >= level.bots.num ) { - trap->Print( S_COLOR_RED "Invalid bot number: %i\n", num ); +char *G_GetBotInfoByNumber(int num) { + if (num < 0 || num >= level.bots.num) { + trap->Print(S_COLOR_RED "Invalid bot number: %i\n", num); return NULL; } return level.bots.infos[num]; @@ -1267,13 +1237,13 @@ char *G_GetBotInfoByNumber( int num ) { G_GetBotInfoByName =============== */ -char *G_GetBotInfoByName( const char *name ) { - int n; - char *value; +char *G_GetBotInfoByName(const char *name) { + int n; + char *value; - for ( n = 0; n < level.bots.num ; n++ ) { - value = Info_ValueForKey( level.bots.infos[n], "name" ); - if ( !Q_stricmp( value, name ) ) { + for (n = 0; n < level.bots.num; n++) { + value = Info_ValueForKey(level.bots.infos[n], "name"); + if (!Q_stricmp(value, name)) { return level.bots.infos[n]; } } @@ -1281,22 +1251,22 @@ char *G_GetBotInfoByName( const char *name ) { return NULL; } -//rww - pd +// rww - pd void LoadPath_ThisLevel(void); -//end rww +// end rww /* =============== G_InitBots =============== */ -void G_InitBots( void ) { +void G_InitBots(void) { G_LoadBots(); G_LoadArenas(); - trap->Cvar_Register( &bot_minplayers, "bot_minplayers", "0", CVAR_SERVERINFO ); + trap->Cvar_Register(&bot_minplayers, "bot_minplayers", "0", CVAR_SERVERINFO); - //rww - new bot route stuff + // rww - new bot route stuff LoadPath_ThisLevel(); - //end rww + // end rww } diff --git a/codemp/game/g_client.c b/codemp/game/g_client.c index a46845ddb5..d369998cca 100644 --- a/codemp/game/g_client.c +++ b/codemp/game/g_client.c @@ -28,15 +28,15 @@ along with this program; if not, see . // g_client.c -- client functions that don't happen every frame -static vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; -static vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; +static vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; +static vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; extern int g_siegeRespawnCheck; -void WP_SaberAddG2Model( gentity_t *saberent, const char *saberModel, qhandle_t saberSkin ); -void WP_SaberRemoveG2Model( gentity_t *saberent ); -extern qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel ); -extern qboolean WP_UseFirstValidSaberStyle( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel ); +void WP_SaberAddG2Model(gentity_t *saberent, const char *saberModel, qhandle_t saberSkin); +void WP_SaberRemoveG2Model(gentity_t *saberent); +extern qboolean WP_SaberStyleValidForSaber(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel); +extern qboolean WP_UseFirstValidSaberStyle(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel); forcedata_t Client_Force[MAX_CLIENTS]; @@ -46,16 +46,15 @@ Targets will be fired when someone spawns in on them. "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_duel( gentity_t *ent ) -{ - int i; +void SP_info_player_duel(gentity_t *ent) { + int i; - G_SpawnInt( "nobots", "0", &i); - if ( i ) { + G_SpawnInt("nobots", "0", &i); + if (i) { ent->flags |= FL_NO_BOTS; } - G_SpawnInt( "nohumans", "0", &i ); - if ( i ) { + G_SpawnInt("nohumans", "0", &i); + if (i) { ent->flags |= FL_NO_HUMANS; } } @@ -66,16 +65,15 @@ Targets will be fired when someone spawns in on them. "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_duel1( gentity_t *ent ) -{ - int i; +void SP_info_player_duel1(gentity_t *ent) { + int i; - G_SpawnInt( "nobots", "0", &i); - if ( i ) { + G_SpawnInt("nobots", "0", &i); + if (i) { ent->flags |= FL_NO_BOTS; } - G_SpawnInt( "nohumans", "0", &i ); - if ( i ) { + G_SpawnInt("nohumans", "0", &i); + if (i) { ent->flags |= FL_NO_HUMANS; } } @@ -86,16 +84,15 @@ Targets will be fired when someone spawns in on them. "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_duel2( gentity_t *ent ) -{ - int i; +void SP_info_player_duel2(gentity_t *ent) { + int i; - G_SpawnInt( "nobots", "0", &i); - if ( i ) { + G_SpawnInt("nobots", "0", &i); + if (i) { ent->flags |= FL_NO_BOTS; } - G_SpawnInt( "nohumans", "0", &i ); - if ( i ) { + G_SpawnInt("nohumans", "0", &i); + if (i) { ent->flags |= FL_NO_HUMANS; } } @@ -107,15 +104,15 @@ Targets will be fired when someone spawns in on them. "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_deathmatch( gentity_t *ent ) { - int i; +void SP_info_player_deathmatch(gentity_t *ent) { + int i; - G_SpawnInt( "nobots", "0", &i); - if ( i ) { + G_SpawnInt("nobots", "0", &i); + if (i) { ent->flags |= FL_NO_BOTS; } - G_SpawnInt( "nohumans", "0", &i ); - if ( i ) { + G_SpawnInt("nohumans", "0", &i); + if (i) { ent->flags |= FL_NO_HUMANS; } } @@ -126,7 +123,7 @@ equivelant to info_player_deathmatch */ void SP_info_player_start(gentity_t *ent) { ent->classname = "info_player_deathmatch"; - SP_info_player_deathmatch( ent ); + SP_info_player_deathmatch(ent); } /*QUAKED info_player_start_red (1 0 0) (-16 -16 -24) (16 16 32) INITIAL @@ -140,9 +137,7 @@ INITIAL - The first time a player enters the game, they will be at an 'initial' "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_start_red(gentity_t *ent) { - SP_info_player_deathmatch( ent ); -} +void SP_info_player_start_red(gentity_t *ent) { SP_info_player_deathmatch(ent); } /*QUAKED info_player_start_blue (1 0 0) (-16 -16 -24) (16 16 32) INITIAL For Blue Team DM starts @@ -155,19 +150,13 @@ INITIAL - The first time a player enters the game, they will be at an 'initial' "nobots" will prevent bots from using this spot. "nohumans" will prevent non-bots from using this spot. */ -void SP_info_player_start_blue(gentity_t *ent) { - SP_info_player_deathmatch( ent ); -} +void SP_info_player_start_blue(gentity_t *ent) { SP_info_player_deathmatch(ent); } -void SiegePointUse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - //Toggle the point on/off - if (self->genericValue1) - { +void SiegePointUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + // Toggle the point on/off + if (self->genericValue1) { self->genericValue1 = 0; - } - else - { + } else { self->genericValue1 = 1; } } @@ -186,22 +175,18 @@ Targets will be fired when someone spawns in on them. void SP_info_player_siegeteam1(gentity_t *ent) { int soff = 0; - if (level.gametype != GT_SIEGE) - { //turn into a DM spawn if not in siege game mode + if (level.gametype != GT_SIEGE) { // turn into a DM spawn if not in siege game mode ent->classname = "info_player_deathmatch"; - SP_info_player_deathmatch( ent ); + SP_info_player_deathmatch(ent); return; } G_SpawnInt("startoff", "0", &soff); - if (soff) - { //start disabled + if (soff) { // start disabled ent->genericValue1 = 0; - } - else - { + } else { ent->genericValue1 = 1; } @@ -222,22 +207,18 @@ Targets will be fired when someone spawns in on them. void SP_info_player_siegeteam2(gentity_t *ent) { int soff = 0; - if (level.gametype != GT_SIEGE) - { //turn into a DM spawn if not in siege game mode + if (level.gametype != GT_SIEGE) { // turn into a DM spawn if not in siege game mode ent->classname = "info_player_deathmatch"; - SP_info_player_deathmatch( ent ); + SP_info_player_deathmatch(ent); return; } G_SpawnInt("startoff", "0", &soff); - if (soff) - { //start disabled + if (soff) { // start disabled ent->genericValue1 = 0; - } - else - { + } else { ent->genericValue1 = 1; } @@ -249,9 +230,7 @@ The intermission will be viewed from this point. Target an info_notnull for the RED - In a Siege game, the intermission will happen here if the Red (attacking) team wins BLUE - In a Siege game, the intermission will happen here if the Blue (defending) team wins */ -void SP_info_player_intermission( gentity_t *ent ) { - -} +void SP_info_player_intermission(gentity_t *ent) {} /*QUAKED info_player_intermission_red (1 0 1) (-16 -16 -24) (16 16 32) The intermission will be viewed from this point. Target an info_notnull for the view direction. @@ -260,9 +239,7 @@ In a Siege game, the intermission will happen here if the Red (attacking) team w target - ent to look at target2 - ents to use when this intermission point is chosen */ -void SP_info_player_intermission_red( gentity_t *ent ) { - -} +void SP_info_player_intermission_red(gentity_t *ent) {} /*QUAKED info_player_intermission_blue (1 0 1) (-16 -16 -24) (16 16 32) The intermission will be viewed from this point. Target an info_notnull for the view direction. @@ -271,28 +248,23 @@ In a Siege game, the intermission will happen here if the Blue (defending) team target - ent to look at target2 - ents to use when this intermission point is chosen */ -void SP_info_player_intermission_blue( gentity_t *ent ) { - -} +void SP_info_player_intermission_blue(gentity_t *ent) {} -#define JMSABER_RESPAWN_TIME 20000 //in case it gets stuck somewhere no one can reach +#define JMSABER_RESPAWN_TIME 20000 // in case it gets stuck somewhere no one can reach -void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) -{ +void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) { gentity_t *ent = &g_entities[self->client->ps.saberIndex]; vec3_t a; int altVelocity = 0; - if (!ent || ent->enemy != self) - { //something has gone very wrong (this should never happen) - //but in case it does.. find the saber manually + if (!ent || ent->enemy != self) { // something has gone very wrong (this should never happen) + // but in case it does.. find the saber manually #ifdef _DEBUG Com_Printf("Lost the saber! Attempting to use global pointer..\n"); #endif ent = gJMSaberEnt; - if (!ent) - { + if (!ent) { #ifdef _DEBUG Com_Printf("The global pointer was NULL. This is a bad thing.\n"); #endif @@ -307,16 +279,14 @@ void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) self->client->ps.saberIndex = ent->s.number; } - trap->SetConfigstring ( CS_CLIENT_JEDIMASTER, "-1" ); + trap->SetConfigstring(CS_CLIENT_JEDIMASTER, "-1"); - if (attacker && attacker->client && self->client->ps.saberInFlight) - { //someone killed us and we had the saber thrown, so actually move this saber to the saber location - //if we killed ourselves with saber thrown, however, same suicide rules of respawning at spawn spot still - //apply. + if (attacker && attacker->client && self->client->ps.saberInFlight) { // someone killed us and we had the saber thrown, so actually move this saber to the + // saber location if we killed ourselves with saber thrown, however, same suicide + // rules of respawning at spawn spot still apply. gentity_t *flyingsaber = &g_entities[self->client->ps.saberEntityNum]; - if (flyingsaber && flyingsaber->inuse) - { + if (flyingsaber && flyingsaber->inuse) { VectorCopy(flyingsaber->s.pos.trBase, ent->s.pos.trBase); VectorCopy(flyingsaber->s.pos.trDelta, ent->s.pos.trDelta); VectorCopy(flyingsaber->s.apos.trBase, ent->s.apos.trBase); @@ -328,17 +298,16 @@ void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) } } - self->client->ps.saberInFlight = qtrue; //say he threw it anyway in order to properly remove from dead body + self->client->ps.saberInFlight = qtrue; // say he threw it anyway in order to properly remove from dead body - WP_SaberAddG2Model( ent, self->client->saber[0].model, self->client->saber[0].skin ); + WP_SaberAddG2Model(ent, self->client->saber[0].model, self->client->saber[0].skin); ent->s.eFlags &= ~(EF_NODRAW); ent->s.modelGhoul2 = 1; ent->s.eType = ET_MISSILE; ent->enemy = NULL; - if (!attacker || !attacker->client) - { + if (!attacker || !attacker->client) { VectorCopy(ent->s.origin2, ent->s.pos.trBase); VectorCopy(ent->s.origin2, ent->s.origin); VectorCopy(ent->s.origin2, ent->r.currentOrigin); @@ -347,8 +316,7 @@ void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) return; } - if (!altVelocity) - { + if (!altVelocity) { VectorCopy(self->s.pos.trBase, ent->s.pos.trBase); VectorCopy(self->s.pos.trBase, ent->s.origin); VectorCopy(self->s.pos.trBase, ent->r.currentOrigin); @@ -357,42 +325,35 @@ void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker) VectorNormalize(a); - ent->s.pos.trDelta[0] = a[0]*256; - ent->s.pos.trDelta[1] = a[1]*256; + ent->s.pos.trDelta[0] = a[0] * 256; + ent->s.pos.trDelta[1] = a[1] * 256; ent->s.pos.trDelta[2] = 256; } trap->LinkEntity((sharedEntity_t *)ent); } -void JMSaberThink(gentity_t *ent) -{ +void JMSaberThink(gentity_t *ent) { gJMSaberEnt = ent; - if (ent->enemy) - { - if (!ent->enemy->client || !ent->enemy->inuse) - { //disconnected? + if (ent->enemy) { + if (!ent->enemy->client || !ent->enemy->inuse) { // disconnected? VectorCopy(ent->enemy->s.pos.trBase, ent->s.pos.trBase); VectorCopy(ent->enemy->s.pos.trBase, ent->s.origin); VectorCopy(ent->enemy->s.pos.trBase, ent->r.currentOrigin); - ent->s.modelindex = G_ModelIndex( DEFAULT_SABER_MODEL ); + ent->s.modelindex = G_ModelIndex(DEFAULT_SABER_MODEL); ent->s.eFlags &= ~(EF_NODRAW); ent->s.modelGhoul2 = 1; ent->s.eType = ET_MISSILE; ent->enemy = NULL; ent->pos2[0] = 1; - ent->pos2[1] = 0; //respawn next think + ent->pos2[1] = 0; // respawn next think trap->LinkEntity((sharedEntity_t *)ent); - } - else - { + } else { ent->pos2[1] = level.time + JMSABER_RESPAWN_TIME; } - } - else if (ent->pos2[0] && ent->pos2[1] < level.time) - { + } else if (ent->pos2[0] && ent->pos2[1] < level.time) { VectorCopy(ent->s.origin2, ent->s.pos.trBase); VectorCopy(ent->s.origin2, ent->s.origin); VectorCopy(ent->s.origin2, ent->r.currentOrigin); @@ -404,33 +365,27 @@ void JMSaberThink(gentity_t *ent) G_RunObject(ent); } -void JMSaberTouch(gentity_t *self, gentity_t *other, trace_t *trace) -{ +void JMSaberTouch(gentity_t *self, gentity_t *other, trace_t *trace) { int i = 0; -// gentity_t *te; + // gentity_t *te; - if (!other || !other->client || other->health < 1) - { + if (!other || !other->client || other->health < 1) { return; } - if (self->enemy) - { + if (self->enemy) { return; } - if (!self->s.modelindex) - { + if (!self->s.modelindex) { return; } - if (other->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) - { + if (other->client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { return; } - if (other->client->ps.isJediMaster) - { + if (other->client->ps.isJediMaster) { return; } @@ -442,31 +397,27 @@ void JMSaberTouch(gentity_t *self, gentity_t *other, trace_t *trace) G_AddEvent(other, EV_BECOME_JEDIMASTER, 0); // Track the jedi master - trap->SetConfigstring ( CS_CLIENT_JEDIMASTER, va("%i", other->s.number ) ); + trap->SetConfigstring(CS_CLIENT_JEDIMASTER, va("%i", other->s.number)); - if (g_spawnInvulnerability.integer) - { + if (g_spawnInvulnerability.integer) { other->client->ps.eFlags |= EF_INVULNERABLE; other->client->invulnerableTimer = level.time + g_spawnInvulnerability.integer; } - trap->SendServerCommand( -1, va("cp \"%s %s\n\"", other->client->pers.netname, G_GetStringEdString("MP_SVGAME", "BECOMEJM")) ); + trap->SendServerCommand(-1, va("cp \"%s %s\n\"", other->client->pers.netname, G_GetStringEdString("MP_SVGAME", "BECOMEJM"))); other->client->ps.isJediMaster = qtrue; other->client->ps.saberIndex = self->s.number; - if (other->health < 200 && other->health > 0) - { //full health when you become the Jedi Master + if (other->health < 200 && other->health > 0) { // full health when you become the Jedi Master other->client->ps.stats[STAT_HEALTH] = other->health = 200; } - if (other->client->ps.fd.forcePower < 100) - { + if (other->client->ps.fd.forcePower < 100) { other->client->ps.fd.forcePower = 100; } - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { other->client->ps.fd.forcePowersKnown |= (1 << i); other->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_3; @@ -496,10 +447,8 @@ gentity_t *gJMSaberEnt = NULL; /*QUAKED info_jedimaster_start (1 0 0) (-16 -16 -24) (16 16 32) "jedi master" saber spawn point */ -void SP_info_jedimaster_start(gentity_t *ent) -{ - if (level.gametype != GT_JEDIMASTER) - { +void SP_info_jedimaster_start(gentity_t *ent) { + if (level.gametype != GT_JEDIMASTER) { gJMSaberEnt = NULL; G_FreeEntity(ent); return; @@ -509,16 +458,16 @@ void SP_info_jedimaster_start(gentity_t *ent) ent->flags = FL_BOUNCE_HALF; - ent->s.modelindex = G_ModelIndex( DEFAULT_SABER_MODEL ); + ent->s.modelindex = G_ModelIndex(DEFAULT_SABER_MODEL); ent->s.modelGhoul2 = 1; ent->s.g2radius = 20; - //ent->s.eType = ET_GENERAL; + // ent->s.eType = ET_GENERAL; ent->s.eType = ET_MISSILE; ent->s.weapon = WP_SABER; ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; - VectorSet( ent->r.maxs, 3, 3, 3 ); - VectorSet( ent->r.mins, -3, -3, -3 ); + VectorSet(ent->r.maxs, 3, 3, 3); + VectorSet(ent->r.mins, -3, -3, -3); ent->r.contents = CONTENTS_TRIGGER; ent->clipmask = MASK_SOLID; @@ -528,7 +477,7 @@ void SP_info_jedimaster_start(gentity_t *ent) ent->physicsObject = qtrue; - VectorCopy(ent->s.pos.trBase, ent->s.origin2); //remember the spawn spot + VectorCopy(ent->s.pos.trBase, ent->s.origin2); // remember the spawn spot ent->touch = JMSaberTouch; @@ -552,49 +501,44 @@ SpotWouldTelefrag ================ */ -qboolean SpotWouldTelefrag( gentity_t *spot ) { - int i, num; - int touch[MAX_GENTITIES]; - gentity_t *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag(gentity_t *spot) { + int i, num; + int touch[MAX_GENTITIES]; + gentity_t *hit; + vec3_t mins, maxs; - VectorAdd( spot->s.origin, playerMins, mins ); - VectorAdd( spot->s.origin, playerMaxs, maxs ); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(spot->s.origin, playerMins, mins); + VectorAdd(spot->s.origin, playerMaxs, maxs); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient && hit->client->ps.stats[STAT_HEALTH] > 0 ) { - if ( hit->client) { + // if ( hit->client && hit->client->ps.stats[STAT_HEALTH] > 0 ) { + if (hit->client) { return qtrue; } - } return qfalse; } -qboolean SpotWouldTelefrag2( gentity_t *mover, vec3_t dest ) -{ - int i, num; - int touch[MAX_GENTITIES]; - gentity_t *hit; - vec3_t mins, maxs; +qboolean SpotWouldTelefrag2(gentity_t *mover, vec3_t dest) { + int i, num; + int touch[MAX_GENTITIES]; + gentity_t *hit; + vec3_t mins, maxs; - VectorAdd( dest, mover->r.mins, mins ); - VectorAdd( dest, mover->r.maxs, maxs ); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(dest, mover->r.mins, mins); + VectorAdd(dest, mover->r.maxs, maxs); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; ir.contents & mover->r.contents ) - { + if (hit->r.contents & mover->r.contents) { return qtrue; } } @@ -609,22 +553,22 @@ SelectNearestDeathmatchSpawnPoint Find the spot that we DON'T want to use ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from ) { - gentity_t *spot; - vec3_t delta; - float dist, nearestDist; - gentity_t *nearestSpot; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectNearestDeathmatchSpawnPoint(vec3_t from) { + gentity_t *spot; + vec3_t delta; + float dist, nearestDist; + gentity_t *nearestSpot; nearestDist = 999999; nearestSpot = NULL; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { - VectorSubtract( spot->s.origin, from, delta ); - dist = VectorLength( delta ); - if ( dist < nearestDist ) { + VectorSubtract(spot->s.origin, from, delta); + dist = VectorLength(delta); + if (dist < nearestDist) { nearestDist = dist; nearestSpot = spot; } @@ -633,7 +577,6 @@ gentity_t *SelectNearestDeathmatchSpawnPoint( vec3_t from ) { return nearestSpot; } - /* ================ SelectRandomDeathmatchSpawnPoint @@ -641,38 +584,36 @@ SelectRandomDeathmatchSpawnPoint go to a random point that doesn't telefrag ================ */ -#define MAX_SPAWN_POINTS 128 -gentity_t *SelectRandomDeathmatchSpawnPoint( qboolean isbot ) { - gentity_t *spot; - int count; - int selection; - gentity_t *spots[MAX_SPAWN_POINTS]; +#define MAX_SPAWN_POINTS 128 +gentity_t *SelectRandomDeathmatchSpawnPoint(qboolean isbot) { + gentity_t *spot; + int count; + int selection; + gentity_t *spots[MAX_SPAWN_POINTS]; count = 0; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { - if ( SpotWouldTelefrag( spot ) ) { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL && count < MAX_SPAWN_POINTS) { + if (SpotWouldTelefrag(spot)) { continue; } - if(((spot->flags & FL_NO_BOTS) && isbot) || - ((spot->flags & FL_NO_HUMANS) && !isbot)) - { + if (((spot->flags & FL_NO_BOTS) && isbot) || ((spot->flags & FL_NO_HUMANS) && !isbot)) { // spot is not for this human/bot player continue; } - spots[ count ] = spot; + spots[count] = spot; count++; } - if ( !count ) { // no spots that won't telefrag - return G_Find( NULL, FOFS(classname), "info_player_deathmatch"); + if (!count) { // no spots that won't telefrag + return G_Find(NULL, FOFS(classname), "info_player_deathmatch"); } selection = rand() % count; - return spots[ selection ]; + return spots[selection]; } /* @@ -682,52 +623,44 @@ SelectRandomFurthestSpawnPoint Chooses a player start, deathmatch start, etc ============ */ -gentity_t *SelectRandomFurthestSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles, team_t team, qboolean isbot ) { - gentity_t *spot; - vec3_t delta; - float dist; - float list_dist[MAX_SPAWN_POINTS]; - gentity_t *list_spot[MAX_SPAWN_POINTS]; - int numSpots, rnd, i, j; +gentity_t *SelectRandomFurthestSpawnPoint(vec3_t avoidPoint, vec3_t origin, vec3_t angles, team_t team, qboolean isbot) { + gentity_t *spot; + vec3_t delta; + float dist; + float list_dist[MAX_SPAWN_POINTS]; + gentity_t *list_spot[MAX_SPAWN_POINTS]; + int numSpots, rnd, i, j; numSpots = 0; spot = NULL; - //in Team DM, look for a team start spot first, if any - if ( level.gametype == GT_TEAM - && team != TEAM_FREE - && team != TEAM_SPECTATOR ) - { + // in Team DM, look for a team start spot first, if any + if (level.gametype == GT_TEAM && team != TEAM_FREE && team != TEAM_SPECTATOR) { const char *classname = NULL; - if ( team == TEAM_RED ) - { + if (team == TEAM_RED) { classname = "info_player_start_red"; - } - else - { + } else { classname = "info_player_start_blue"; } - while ((spot = G_Find (spot, FOFS(classname), classname)) != NULL) { - if ( SpotWouldTelefrag( spot ) ) { + while ((spot = G_Find(spot, FOFS(classname), classname)) != NULL) { + if (SpotWouldTelefrag(spot)) { continue; } - if(((spot->flags & FL_NO_BOTS) && isbot) || - ((spot->flags & FL_NO_HUMANS) && !isbot)) - { + if (((spot->flags & FL_NO_BOTS) && isbot) || ((spot->flags & FL_NO_HUMANS) && !isbot)) { // spot is not for this human/bot player continue; } - VectorSubtract( spot->s.origin, avoidPoint, delta ); - dist = VectorLength( delta ); + VectorSubtract(spot->s.origin, avoidPoint, delta); + dist = VectorLength(delta); for (i = 0; i < numSpots; i++) { - if ( dist > list_dist[i] ) { - if ( numSpots >= MAX_SPAWN_POINTS ) - numSpots = MAX_SPAWN_POINTS-1; + if (dist > list_dist[i]) { + if (numSpots >= MAX_SPAWN_POINTS) + numSpots = MAX_SPAWN_POINTS - 1; for (j = numSpots; j > i; j--) { - list_dist[j] = list_dist[j-1]; - list_spot[j] = list_spot[j-1]; + list_dist[j] = list_dist[j - 1]; + list_spot[j] = list_spot[j - 1]; } list_dist[i] = dist; list_spot[i] = spot; @@ -743,29 +676,26 @@ gentity_t *SelectRandomFurthestSpawnPoint ( vec3_t avoidPoint, vec3_t origin, ve } } - if ( !numSpots ) - {//couldn't find any of the above - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { - if ( SpotWouldTelefrag( spot ) ) { + if (!numSpots) { // couldn't find any of the above + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { + if (SpotWouldTelefrag(spot)) { continue; } - if(((spot->flags & FL_NO_BOTS) && isbot) || - ((spot->flags & FL_NO_HUMANS) && !isbot)) - { + if (((spot->flags & FL_NO_BOTS) && isbot) || ((spot->flags & FL_NO_HUMANS) && !isbot)) { // spot is not for this human/bot player continue; } - VectorSubtract( spot->s.origin, avoidPoint, delta ); - dist = VectorLength( delta ); + VectorSubtract(spot->s.origin, avoidPoint, delta); + dist = VectorLength(delta); for (i = 0; i < numSpots; i++) { - if ( dist > list_dist[i] ) { - if ( numSpots >= MAX_SPAWN_POINTS ) - numSpots = MAX_SPAWN_POINTS-1; + if (dist > list_dist[i]) { + if (numSpots >= MAX_SPAWN_POINTS) + numSpots = MAX_SPAWN_POINTS - 1; for (j = numSpots; j > i; j--) { - list_dist[j] = list_dist[j-1]; - list_spot[j] = list_spot[j-1]; + list_dist[j] = list_dist[j - 1]; + list_spot[j] = list_spot[j - 1]; } list_dist[i] = dist; list_spot[i] = spot; @@ -780,12 +710,12 @@ gentity_t *SelectRandomFurthestSpawnPoint ( vec3_t avoidPoint, vec3_t origin, ve } } if (!numSpots) { - spot = G_Find( NULL, FOFS(classname), "info_player_deathmatch"); + spot = G_Find(NULL, FOFS(classname), "info_player_deathmatch"); if (!spot) - trap->Error( ERR_DROP, "Couldn't find a spawn point" ); - VectorCopy (spot->s.origin, origin); + trap->Error(ERR_DROP, "Couldn't find a spawn point"); + VectorCopy(spot->s.origin, origin); origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } } @@ -793,37 +723,29 @@ gentity_t *SelectRandomFurthestSpawnPoint ( vec3_t avoidPoint, vec3_t origin, ve // select a random spot from the spawn points furthest away rnd = Q_flrand(0.0f, 1.0f) * (numSpots / 2); - VectorCopy (list_spot[rnd]->s.origin, origin); + VectorCopy(list_spot[rnd]->s.origin, origin); origin[2] += 9; - VectorCopy (list_spot[rnd]->s.angles, angles); + VectorCopy(list_spot[rnd]->s.angles, angles); return list_spot[rnd]; } -gentity_t *SelectDuelSpawnPoint( int team, vec3_t avoidPoint, vec3_t origin, vec3_t angles, qboolean isbot ) -{ - gentity_t *spot; - vec3_t delta; - float dist; - float list_dist[MAX_SPAWN_POINTS]; - gentity_t *list_spot[MAX_SPAWN_POINTS]; - int numSpots, rnd, i, j; - const char *spotName; - - if (team == DUELTEAM_LONE) - { +gentity_t *SelectDuelSpawnPoint(int team, vec3_t avoidPoint, vec3_t origin, vec3_t angles, qboolean isbot) { + gentity_t *spot; + vec3_t delta; + float dist; + float list_dist[MAX_SPAWN_POINTS]; + gentity_t *list_spot[MAX_SPAWN_POINTS]; + int numSpots, rnd, i, j; + const char *spotName; + + if (team == DUELTEAM_LONE) { spotName = "info_player_duel1"; - } - else if (team == DUELTEAM_DOUBLE) - { + } else if (team == DUELTEAM_DOUBLE) { spotName = "info_player_duel2"; - } - else if (team == DUELTEAM_SINGLE) - { + } else if (team == DUELTEAM_SINGLE) { spotName = "info_player_duel"; - } - else - { + } else { spotName = "info_player_deathmatch"; } tryAgain: @@ -831,27 +753,25 @@ gentity_t *SelectDuelSpawnPoint( int team, vec3_t avoidPoint, vec3_t origin, vec numSpots = 0; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), spotName)) != NULL) { - if ( SpotWouldTelefrag( spot ) ) { + while ((spot = G_Find(spot, FOFS(classname), spotName)) != NULL) { + if (SpotWouldTelefrag(spot)) { continue; } - if(((spot->flags & FL_NO_BOTS) && isbot) || - ((spot->flags & FL_NO_HUMANS) && !isbot)) - { + if (((spot->flags & FL_NO_BOTS) && isbot) || ((spot->flags & FL_NO_HUMANS) && !isbot)) { // spot is not for this human/bot player continue; } - VectorSubtract( spot->s.origin, avoidPoint, delta ); - dist = VectorLength( delta ); + VectorSubtract(spot->s.origin, avoidPoint, delta); + dist = VectorLength(delta); for (i = 0; i < numSpots; i++) { - if ( dist > list_dist[i] ) { - if ( numSpots >= MAX_SPAWN_POINTS ) - numSpots = MAX_SPAWN_POINTS-1; + if (dist > list_dist[i]) { + if (numSpots >= MAX_SPAWN_POINTS) + numSpots = MAX_SPAWN_POINTS - 1; for (j = numSpots; j > i; j--) { - list_dist[j] = list_dist[j-1]; - list_spot[j] = list_spot[j-1]; + list_dist[j] = list_dist[j - 1]; + list_spot[j] = list_spot[j - 1]; } list_dist[i] = dist; list_spot[i] = spot; @@ -865,30 +785,28 @@ gentity_t *SelectDuelSpawnPoint( int team, vec3_t avoidPoint, vec3_t origin, vec numSpots++; } } - if (!numSpots) - { - if (Q_stricmp(spotName, "info_player_deathmatch")) - { //try the loop again with info_player_deathmatch as the target if we couldn't find a duel spot + if (!numSpots) { + if (Q_stricmp(spotName, "info_player_deathmatch")) { // try the loop again with info_player_deathmatch as the target if we couldn't find a duel spot spotName = "info_player_deathmatch"; goto tryAgain; } - //If we got here we found no free duel or DM spots, just try the first DM spot - spot = G_Find( NULL, FOFS(classname), "info_player_deathmatch"); + // If we got here we found no free duel or DM spots, just try the first DM spot + spot = G_Find(NULL, FOFS(classname), "info_player_deathmatch"); if (!spot) - trap->Error( ERR_DROP, "Couldn't find a spawn point" ); - VectorCopy (spot->s.origin, origin); + trap->Error(ERR_DROP, "Couldn't find a spawn point"); + VectorCopy(spot->s.origin, origin); origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } // select a random spot from the spawn points furthest away rnd = Q_flrand(0.0f, 1.0f) * (numSpots / 2); - VectorCopy (list_spot[rnd]->s.origin, origin); + VectorCopy(list_spot[rnd]->s.origin, origin); origin[2] += 9; - VectorCopy (list_spot[rnd]->s.angles, angles); + VectorCopy(list_spot[rnd]->s.angles, angles); return list_spot[rnd]; } @@ -900,8 +818,8 @@ SelectSpawnPoint Chooses a player start, deathmatch start, etc ============ */ -gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, vec3_t origin, vec3_t angles, team_t team, qboolean isbot ) { - return SelectRandomFurthestSpawnPoint( avoidPoint, origin, angles, team, isbot ); +gentity_t *SelectSpawnPoint(vec3_t avoidPoint, vec3_t origin, vec3_t angles, team_t team, qboolean isbot) { + return SelectRandomFurthestSpawnPoint(avoidPoint, origin, angles, team, isbot); /* gentity_t *spot; @@ -940,29 +858,27 @@ Try to find a spawn point marked 'initial', otherwise use normal spawn selection. ============ */ -gentity_t *SelectInitialSpawnPoint( vec3_t origin, vec3_t angles, team_t team, qboolean isbot ) { - gentity_t *spot; +gentity_t *SelectInitialSpawnPoint(vec3_t origin, vec3_t angles, team_t team, qboolean isbot) { + gentity_t *spot; spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), "info_player_deathmatch")) != NULL) { - if(((spot->flags & FL_NO_BOTS) && isbot) || - ((spot->flags & FL_NO_HUMANS) && !isbot)) - { + while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { + if (((spot->flags & FL_NO_BOTS) && isbot) || ((spot->flags & FL_NO_HUMANS) && !isbot)) { continue; } - if ( spot->spawnflags & 1 ) { + if (spot->spawnflags & 1) { break; } } - if ( !spot || SpotWouldTelefrag( spot ) ) { - return SelectSpawnPoint( vec3_origin, origin, angles, team, isbot ); + if (!spot || SpotWouldTelefrag(spot)) { + return SelectSpawnPoint(vec3_origin, origin, angles, team, isbot); } - VectorCopy (spot->s.origin, origin); + VectorCopy(spot->s.origin, origin); origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } @@ -973,11 +889,11 @@ SelectSpectatorSpawnPoint ============ */ -gentity_t *SelectSpectatorSpawnPoint( vec3_t origin, vec3_t angles ) { +gentity_t *SelectSpectatorSpawnPoint(vec3_t origin, vec3_t angles) { FindIntermissionPoint(); - VectorCopy( level.intermission_origin, origin ); - VectorCopy( level.intermission_angle, angles ); + VectorCopy(level.intermission_origin, origin); + VectorCopy(level.intermission_angle, angles); return NULL; } @@ -998,19 +914,19 @@ BODYQUE ======================================================================= */ -#define BODY_SINK_TIME 30000//45000 +#define BODY_SINK_TIME 30000 // 45000 /* =============== InitBodyQue =============== */ -void InitBodyQue (void) { - int i; - gentity_t *ent; +void InitBodyQue(void) { + int i; + gentity_t *ent; level.bodyQueIndex = 0; - for (i=0; iclassname = "bodyque"; ent->neverFree = qtrue; @@ -1025,15 +941,15 @@ BodySink After sitting around for five seconds, fall into the ground and disappear ============= */ -void BodySink( gentity_t *ent ) { - if ( level.time - ent->timestamp > BODY_SINK_TIME + 2500 ) { +void BodySink(gentity_t *ent) { + if (level.time - ent->timestamp > BODY_SINK_TIME + 2500) { // the body ques are never actually freed, they are just unlinked - trap->UnlinkEntity( (sharedEntity_t *)ent ); + trap->UnlinkEntity((sharedEntity_t *)ent); ent->physicsObject = qfalse; return; } -// ent->nextthink = level.time + 100; -// ent->s.pos.trBase[2] -= 1; + // ent->nextthink = level.time + 100; + // ent->s.pos.trBase[2] -= 1; G_AddEvent(ent, EV_BODYFADE, 0); ent->nextthink = level.time + 18000; @@ -1048,62 +964,59 @@ A player is respawning, so make an entity that looks just like the existing corpse to leave behind. ============= */ -static qboolean CopyToBodyQue( gentity_t *ent ) { - gentity_t *body; - int contents; - int islight = 0; +static qboolean CopyToBodyQue(gentity_t *ent) { + gentity_t *body; + int contents; + int islight = 0; - if (level.intermissiontime) - { + if (level.intermissiontime) { return qfalse; } - trap->UnlinkEntity ((sharedEntity_t *)ent); + trap->UnlinkEntity((sharedEntity_t *)ent); // if client is in a nodrop area, don't leave the body - contents = trap->PointContents( ent->s.origin, -1 ); - if ( contents & CONTENTS_NODROP ) { + contents = trap->PointContents(ent->s.origin, -1); + if (contents & CONTENTS_NODROP) { return qfalse; } - if (ent->client && (ent->client->ps.eFlags & EF_DISINTEGRATION)) - { //for now, just don't spawn a body if you got disint'd + if (ent->client && (ent->client->ps.eFlags & EF_DISINTEGRATION)) { // for now, just don't spawn a body if you got disint'd return qfalse; } // grab a body que and cycle to the next one - body = level.bodyQue[ level.bodyQueIndex ]; + body = level.bodyQue[level.bodyQueIndex]; level.bodyQueIndex = (level.bodyQueIndex + 1) % BODY_QUEUE_SIZE; - trap->UnlinkEntity ((sharedEntity_t *)body); + trap->UnlinkEntity((sharedEntity_t *)body); body->s = ent->s; - //avoid oddly angled corpses floating around + // avoid oddly angled corpses floating around body->s.angles[PITCH] = body->s.angles[ROLL] = body->s.apos.trBase[PITCH] = body->s.apos.trBase[ROLL] = 0; body->s.g2radius = 100; body->s.eType = ET_BODY; - body->s.eFlags = EF_DEAD; // clear EF_TALK, etc + body->s.eFlags = EF_DEAD; // clear EF_TALK, etc - if (ent->client && (ent->client->ps.eFlags & EF_DISINTEGRATION)) - { + if (ent->client && (ent->client->ps.eFlags & EF_DISINTEGRATION)) { body->s.eFlags |= EF_DISINTEGRATION; } VectorCopy(ent->client->ps.lastHitLoc, body->s.origin2); - body->s.powerups = 0; // clear powerups - body->s.loopSound = 0; // clear lava burning + body->s.powerups = 0; // clear powerups + body->s.loopSound = 0; // clear lava burning body->s.loopIsSoundset = qfalse; body->s.number = body - g_entities; body->timestamp = level.time; body->physicsObject = qtrue; - body->physicsBounce = 0; // don't bounce - if ( body->s.groundEntityNum == ENTITYNUM_NONE ) { + body->physicsBounce = 0; // don't bounce + if (body->s.groundEntityNum == ENTITYNUM_NONE) { body->s.pos.trType = TR_GRAVITY; body->s.pos.trTime = level.time; - VectorCopy( ent->client->ps.velocity, body->s.pos.trDelta ); + VectorCopy(ent->client->ps.velocity, body->s.pos.trDelta); } else { body->s.pos.trType = TR_STATIONARY; } @@ -1111,24 +1024,22 @@ static qboolean CopyToBodyQue( gentity_t *ent ) { body->s.weapon = ent->s.bolt2; - if (body->s.weapon == WP_SABER && ent->client->ps.saberInFlight) - { - body->s.weapon = WP_BLASTER; //lie to keep from putting a saber on the corpse, because it was thrown at death + if (body->s.weapon == WP_SABER && ent->client->ps.saberInFlight) { + body->s.weapon = WP_BLASTER; // lie to keep from putting a saber on the corpse, because it was thrown at death } - //G_AddEvent(body, EV_BODY_QUEUE_COPY, ent->s.clientNum); - //Now doing this through a modified version of the rcg reliable command. - if (ent->client && ent->client->ps.fd.forceSide == FORCE_LIGHTSIDE) - { + // G_AddEvent(body, EV_BODY_QUEUE_COPY, ent->s.clientNum); + // Now doing this through a modified version of the rcg reliable command. + if (ent->client && ent->client->ps.fd.forceSide == FORCE_LIGHTSIDE) { islight = 1; } trap->SendServerCommand(-1, va("ircg %i %i %i %i", ent->s.number, body->s.number, body->s.weapon, islight)); body->r.svFlags = ent->r.svFlags | SVF_BROADCAST; - VectorCopy (ent->r.mins, body->r.mins); - VectorCopy (ent->r.maxs, body->r.maxs); - VectorCopy (ent->r.absmin, body->r.absmin); - VectorCopy (ent->r.absmax, body->r.absmax); + VectorCopy(ent->r.mins, body->r.mins); + VectorCopy(ent->r.maxs, body->r.maxs); + VectorCopy(ent->r.absmin, body->r.absmin); + VectorCopy(ent->r.absmax, body->r.absmax); body->s.torsoAnim = body->s.legsAnim = ent->client->ps.legsAnim; @@ -1147,68 +1058,59 @@ static qboolean CopyToBodyQue( gentity_t *ent ) { body->die = body_die; // don't take more damage if already gibbed - if ( ent->health <= GIB_HEALTH ) { + if (ent->health <= GIB_HEALTH) { body->takedamage = qfalse; } else { body->takedamage = qtrue; } - VectorCopy ( body->s.pos.trBase, body->r.currentOrigin ); - trap->LinkEntity ((sharedEntity_t *)body); + VectorCopy(body->s.pos.trBase, body->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)body); return qtrue; } //====================================================================== - /* ================== SetClientViewAngle ================== */ -void SetClientViewAngle( gentity_t *ent, vec3_t angle ) { - int i; +void SetClientViewAngle(gentity_t *ent, vec3_t angle) { + int i; // set the delta angle - for (i=0 ; i<3 ; i++) { - int cmdAngle; + for (i = 0; i < 3; i++) { + int cmdAngle; cmdAngle = ANGLE2SHORT(angle[i]); ent->client->ps.delta_angles[i] = cmdAngle - ent->client->pers.cmd.angles[i]; } - VectorCopy( angle, ent->s.angles ); - VectorCopy (ent->s.angles, ent->client->ps.viewangles); + VectorCopy(angle, ent->s.angles); + VectorCopy(ent->s.angles, ent->client->ps.viewangles); } -void MaintainBodyQueue(gentity_t *ent) -{ //do whatever should be done taking ragdoll and dismemberment states into account. +void MaintainBodyQueue(gentity_t *ent) { // do whatever should be done taking ragdoll and dismemberment states into account. qboolean doRCG = qfalse; assert(ent && ent->client); - if (ent->client->tempSpectate >= level.time || - (ent->client->ps.eFlags2 & EF2_SHIP_DEATH)) - { + if (ent->client->tempSpectate >= level.time || (ent->client->ps.eFlags2 & EF2_SHIP_DEATH)) { ent->client->noCorpse = qtrue; } - if (!ent->client->noCorpse && !ent->client->ps.fallingToDeath) - { - if (!CopyToBodyQue (ent)) - { + if (!ent->client->noCorpse && !ent->client->ps.fallingToDeath) { + if (!CopyToBodyQue(ent)) { doRCG = qtrue; } - } - else - { - ent->client->noCorpse = qfalse; //clear it for next time + } else { + ent->client->noCorpse = qfalse; // clear it for next time ent->client->ps.fallingToDeath = qfalse; doRCG = qtrue; } - if (doRCG) - { //bodyque func didn't manage to call ircg so call this to assure our limbs and ragdoll states are proper on the client. + if (doRCG) { // bodyque func didn't manage to call ircg so call this to assure our limbs and ragdoll states are proper on the client. trap->SendServerCommand(-1, va("rcg %i", ent->s.clientNum)); } } @@ -1219,11 +1121,10 @@ ClientRespawn ================ */ void SiegeRespawn(gentity_t *ent); -void ClientRespawn( gentity_t *ent ) { +void ClientRespawn(gentity_t *ent) { MaintainBodyQueue(ent); - if (gEscaping || level.gametype == GT_POWERDUEL) - { + if (gEscaping || level.gametype == GT_POWERDUEL) { ent->client->sess.sessionTeam = TEAM_SPECTATOR; ent->client->sess.spectatorState = SPECTATOR_FREE; ent->client->sess.spectatorClient = 0; @@ -1235,17 +1136,13 @@ void ClientRespawn( gentity_t *ent ) { return; } - trap->UnlinkEntity ((sharedEntity_t *)ent); + trap->UnlinkEntity((sharedEntity_t *)ent); - if (level.gametype == GT_SIEGE) - { - if (g_siegeRespawn.integer) - { - if (ent->client->tempSpectate < level.time) - { - int minDel = g_siegeRespawn.integer* 2000; - if (minDel < 20000) - { + if (level.gametype == GT_SIEGE) { + if (g_siegeRespawn.integer) { + if (ent->client->tempSpectate < level.time) { + int minDel = g_siegeRespawn.integer * 2000; + if (minDel < 20000) { minDel = 20000; } ent->client->tempSpectate = level.time + minDel; @@ -1259,9 +1156,8 @@ void ClientRespawn( gentity_t *ent ) { trap->LinkEntity((sharedEntity_t *)ent); // Respawn time. - if ( ent->s.number < MAX_CLIENTS ) - { - gentity_t *te = G_TempEntity( ent->client->ps.origin, EV_SIEGESPEC ); + if (ent->s.number < MAX_CLIENTS) { + gentity_t *te = G_TempEntity(ent->client->ps.origin, EV_SIEGESPEC); te->s.time = g_siegeRespawnCheck; te->s.owner = ent->s.number; } @@ -1270,9 +1166,7 @@ void ClientRespawn( gentity_t *ent ) { } } SiegeRespawn(ent); - } - else - { + } else { ClientSpawn(ent); } } @@ -1284,23 +1178,20 @@ TeamCount Returns number of players on a team ================ */ -int TeamCount( int ignoreClientNum, team_t team ) { - int i; - int count = 0; +int TeamCount(int ignoreClientNum, team_t team) { + int i; + int count = 0; - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( i == ignoreClientNum ) { + for (i = 0; i < level.maxclients; i++) { + if (i == ignoreClientNum) { continue; } - if ( level.clients[i].pers.connected == CON_DISCONNECTED ) { + if (level.clients[i].pers.connected == CON_DISCONNECTED) { continue; } - if ( level.clients[i].sess.sessionTeam == team ) { + if (level.clients[i].sess.sessionTeam == team) { count++; - } - else if (level.gametype == GT_SIEGE && - level.clients[i].sess.siegeDesiredTeam == team) - { + } else if (level.gametype == GT_SIEGE && level.clients[i].sess.siegeDesiredTeam == team) { count++; } } @@ -1315,15 +1206,15 @@ TeamLeader Returns the client number of the team leader ================ */ -int TeamLeader( int team ) { - int i; +int TeamLeader(int team) { + int i; - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected == CON_DISCONNECTED ) { + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_DISCONNECTED) { continue; } - if ( level.clients[i].sess.sessionTeam == team ) { - if ( level.clients[i].sess.teamLeader ) + if (level.clients[i].sess.sessionTeam == team) { + if (level.clients[i].sess.teamLeader) return i; } } @@ -1331,27 +1222,26 @@ int TeamLeader( int team ) { return -1; } - /* ================ PickTeam ================ */ -team_t PickTeam( int ignoreClientNum ) { - int counts[TEAM_NUM_TEAMS]; +team_t PickTeam(int ignoreClientNum) { + int counts[TEAM_NUM_TEAMS]; - counts[TEAM_BLUE] = TeamCount( ignoreClientNum, TEAM_BLUE ); - counts[TEAM_RED] = TeamCount( ignoreClientNum, TEAM_RED ); + counts[TEAM_BLUE] = TeamCount(ignoreClientNum, TEAM_BLUE); + counts[TEAM_RED] = TeamCount(ignoreClientNum, TEAM_RED); - if ( counts[TEAM_BLUE] > counts[TEAM_RED] ) { + if (counts[TEAM_BLUE] > counts[TEAM_RED]) { return TEAM_RED; } - if ( counts[TEAM_RED] > counts[TEAM_BLUE] ) { + if (counts[TEAM_RED] > counts[TEAM_BLUE]) { return TEAM_BLUE; } // equal team count, so join the team with the lowest score - if ( level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED] ) { + if (level.teamScores[TEAM_BLUE] > level.teamScores[TEAM_RED]) { return TEAM_RED; } return TEAM_BLUE; @@ -1382,46 +1272,36 @@ static void ForceClientSkin( gclient_t *client, char *model, const char *skin ) ClientCheckName ============ */ -static void ClientCleanName( const char *in, char *out, int outSize ) -{ +static void ClientCleanName(const char *in, char *out, int outSize) { int outpos = 0, colorlessLen = 0, spaces = 0, ats = 0; // discard leading spaces - for ( ; *in == ' '; in++); + for (; *in == ' '; in++) + ; // discard leading asterisk's (fail raven for using * as a skipnotify) // apparently .* causes the issue too so... derp - //for(; *in == '*'; in++); + // for(; *in == '*'; in++); - for(; *in && outpos < outSize - 1; in++) - { + for (; *in && outpos < outSize - 1; in++) { out[outpos] = *in; - if ( *in == ' ' ) - {// don't allow too many consecutive spaces - if ( spaces > 2 ) + if (*in == ' ') { // don't allow too many consecutive spaces + if (spaces > 2) continue; spaces++; - } - else if ( *in == '@' ) - {// don't allow too many consecutive at signs - if ( ++ats > 2 ) { + } else if (*in == '@') { // don't allow too many consecutive at signs + if (++ats > 2) { outpos -= 2; ats = 0; continue; } - } - else if ( (byte)*in < 0x20 - || (byte)*in == 0x81 || (byte)*in == 0x8D || (byte)*in == 0x8F || (byte)*in == 0x90 || (byte)*in == 0x9D - || (byte)*in == 0xA0 || (byte)*in == 0xAD ) - { + } else if ((byte)*in < 0x20 || (byte)*in == 0x81 || (byte)*in == 0x8D || (byte)*in == 0x8F || (byte)*in == 0x90 || (byte)*in == 0x9D || + (byte)*in == 0xA0 || (byte)*in == 0xAD) { continue; - } - else if ( outpos > 0 && out[outpos-1] == Q_COLOR_ESCAPE ) - { - if ( Q_IsColorStringExt( &out[outpos-1] ) ) - { + } else if (outpos > 0 && out[outpos - 1] == Q_COLOR_ESCAPE) { + if (Q_IsColorStringExt(&out[outpos - 1])) { colorlessLen--; #if 0 @@ -1431,15 +1311,11 @@ static void ClientCleanName( const char *in, char *out, int outSize ) continue; } #endif - } - else - { + } else { spaces = ats = 0; colorlessLen++; } - } - else - { + } else { spaces = ats = 0; colorlessLen++; } @@ -1450,90 +1326,73 @@ static void ClientCleanName( const char *in, char *out, int outSize ) out[outpos] = '\0'; // don't allow empty names - if ( *out == '\0' || colorlessLen == 0 ) - Q_strncpyz( out, "Padawan", outSize ); + if (*out == '\0' || colorlessLen == 0) + Q_strncpyz(out, "Padawan", outSize); } #ifdef _DEBUG -void G_DebugWrite(const char *path, const char *text) -{ +void G_DebugWrite(const char *path, const char *text) { fileHandle_t f; - trap->FS_Open( path, &f, FS_APPEND ); + trap->FS_Open(path, &f, FS_APPEND); trap->FS_Write(text, strlen(text), f); trap->FS_Close(f); } #endif -qboolean G_SaberModelSetup(gentity_t *ent) -{ +qboolean G_SaberModelSetup(gentity_t *ent) { int i = 0; qboolean fallbackForSaber = qtrue; - while (i < MAX_SABERS) - { - if (ent->client->saber[i].model[0]) - { - //first kill it off if we've already got it - if (ent->client->weaponGhoul2[i]) - { + while (i < MAX_SABERS) { + if (ent->client->saber[i].model[0]) { + // first kill it off if we've already got it + if (ent->client->weaponGhoul2[i]) { trap->G2API_CleanGhoul2Models(&(ent->client->weaponGhoul2[i])); } trap->G2API_InitGhoul2Model(&ent->client->weaponGhoul2[i], ent->client->saber[i].model, 0, 0, -20, 0, 0); - if (ent->client->weaponGhoul2[i]) - { + if (ent->client->weaponGhoul2[i]) { int j = 0; char *tagName; int tagBolt; - if (ent->client->saber[i].skin) - { + if (ent->client->saber[i].skin) { trap->G2API_SetSkin(ent->client->weaponGhoul2[i], 0, ent->client->saber[i].skin, ent->client->saber[i].skin); } - if (ent->client->saber[i].saberFlags & SFL_BOLT_TO_WRIST) - { - trap->G2API_SetBoltInfo(ent->client->weaponGhoul2[i], 0, 3+i); - } - else - { // bolt to right hand for 0, or left hand for 1 + if (ent->client->saber[i].saberFlags & SFL_BOLT_TO_WRIST) { + trap->G2API_SetBoltInfo(ent->client->weaponGhoul2[i], 0, 3 + i); + } else { // bolt to right hand for 0, or left hand for 1 trap->G2API_SetBoltInfo(ent->client->weaponGhoul2[i], 0, i); } - //Add all the bolt points - while (j < ent->client->saber[i].numBlades) - { - tagName = va("*blade%i", j+1); + // Add all the bolt points + while (j < ent->client->saber[i].numBlades) { + tagName = va("*blade%i", j + 1); tagBolt = trap->G2API_AddBolt(ent->client->weaponGhoul2[i], 0, tagName); - if (tagBolt == -1) - { - if (j == 0) - { //guess this is an 0ldsk3wl saber + if (tagBolt == -1) { + if (j == 0) { // guess this is an 0ldsk3wl saber tagBolt = trap->G2API_AddBolt(ent->client->weaponGhoul2[i], 0, "*flash"); fallbackForSaber = qfalse; break; } - if (tagBolt == -1) - { + if (tagBolt == -1) { assert(0); break; - } } j++; - fallbackForSaber = qfalse; //got at least one custom saber so don't need default + fallbackForSaber = qfalse; // got at least one custom saber so don't need default } - //Copy it into the main instance - trap->G2API_CopySpecificGhoul2Model(ent->client->weaponGhoul2[i], 0, ent->ghoul2, i+1); + // Copy it into the main instance + trap->G2API_CopySpecificGhoul2Model(ent->client->weaponGhoul2[i], 0, ent->ghoul2, i + 1); } - } - else - { + } else { break; } @@ -1556,44 +1415,38 @@ is used for determining where the lightsaber should be, and for per-poly collisi void *g2SaberInstance = NULL; qboolean BG_IsValidCharacterModel(const char *modelName, const char *skinName); -qboolean BG_ValidateSkinForTeam( const char *modelName, char *skinName, int team, float *colors ); +qboolean BG_ValidateSkinForTeam(const char *modelName, char *skinName, int team, float *colors); void BG_GetVehicleModelName(char *modelName, const char *vehicleName, size_t len); -void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) -{ +void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) { int handle; - char afilename[MAX_QPATH]; + char afilename[MAX_QPATH]; #if 0 char /**GLAName,*/ *slash; #endif - char GLAName[MAX_QPATH]; - vec3_t tempVec = {0,0,0}; + char GLAName[MAX_QPATH]; + vec3_t tempVec = {0, 0, 0}; - if (strlen(modelname) >= MAX_QPATH ) - { - Com_Error( ERR_FATAL, "SetupGameGhoul2Model(%s): modelname exceeds MAX_QPATH.\n", modelname ); + if (strlen(modelname) >= MAX_QPATH) { + Com_Error(ERR_FATAL, "SetupGameGhoul2Model(%s): modelname exceeds MAX_QPATH.\n", modelname); } - if (skinName && strlen(skinName) >= MAX_QPATH ) - { - Com_Error( ERR_FATAL, "SetupGameGhoul2Model(%s): skinName exceeds MAX_QPATH.\n", skinName ); + if (skinName && strlen(skinName) >= MAX_QPATH) { + Com_Error(ERR_FATAL, "SetupGameGhoul2Model(%s): skinName exceeds MAX_QPATH.\n", skinName); } // First things first. If this is a ghoul2 model, then let's make sure we demolish this first. - if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) - { + if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) { trap->G2API_CleanGhoul2Models(&(ent->ghoul2)); } - //rww - just load the "standard" model for the server" - if (!precachedKyle) - { + // rww - just load the "standard" model for the server" + if (!precachedKyle) { int defSkin; - Com_sprintf( afilename, sizeof( afilename ), "models/players/" DEFAULT_MODEL "/model.glm" ); + Com_sprintf(afilename, sizeof(afilename), "models/players/" DEFAULT_MODEL "/model.glm"); handle = trap->G2API_InitGhoul2Model(&precachedKyle, afilename, 0, 0, -20, 0, 0); - if (handle<0) - { + if (handle < 0) { return; } @@ -1601,11 +1454,9 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) trap->G2API_SetSkin(precachedKyle, 0, defSkin, defSkin); } - if (precachedKyle && trap->G2API_HaveWeGhoul2Models(precachedKyle)) - { + if (precachedKyle && trap->G2API_HaveWeGhoul2Models(precachedKyle)) { if (d_perPlayerGhoul2.integer || ent->s.number >= MAX_CLIENTS || - G_PlayerHasCustomSkeleton(ent)) - { //rww - allow option for perplayer models on server for collision and bolt stuff. + G_PlayerHasCustomSkeleton(ent)) { // rww - allow option for perplayer models on server for collision and bolt stuff. char modelFullPath[MAX_QPATH]; char truncModelName[MAX_QPATH]; char skin[MAX_QPATH]; @@ -1615,47 +1466,33 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) char *p; // If this is a vehicle, get it's model name. - if ( ent->client->NPC_class == CLASS_VEHICLE ) - { + if (ent->client->NPC_class == CLASS_VEHICLE) { char realModelName[MAX_QPATH]; - Q_strncpyz( vehicleName, modelname, sizeof( vehicleName ) ); - BG_GetVehicleModelName(realModelName, modelname, sizeof( realModelName )); + Q_strncpyz(vehicleName, modelname, sizeof(vehicleName)); + BG_GetVehicleModelName(realModelName, modelname, sizeof(realModelName)); strcpy(truncModelName, realModelName); skin[0] = 0; - if ( ent->m_pVehicle - && ent->m_pVehicle->m_pVehicleInfo - && ent->m_pVehicle->m_pVehicleInfo->skin - && ent->m_pVehicle->m_pVehicleInfo->skin[0] ) - { + if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo && ent->m_pVehicle->m_pVehicleInfo->skin && ent->m_pVehicle->m_pVehicleInfo->skin[0]) { skinHandle = trap->R_RegisterSkin(va("models/players/%s/model_%s.skin", realModelName, ent->m_pVehicle->m_pVehicleInfo->skin)); - } - else - { + } else { skinHandle = trap->R_RegisterSkin(va("models/players/%s/model_default.skin", realModelName)); } - } - else - { - if (skinName && skinName[0]) - { + } else { + if (skinName && skinName[0]) { strcpy(skin, skinName); strcpy(truncModelName, modelname); - } - else - { + } else { strcpy(skin, "default"); strcpy(truncModelName, modelname); p = Q_strrchr(truncModelName, '/'); - if (p) - { + if (p) { *p = 0; p++; - while (p && *p) - { + while (p && *p) { skin[i] = *p; i++; p++; @@ -1664,54 +1501,41 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) i = 0; } - if (!BG_IsValidCharacterModel(truncModelName, skin)) - { + if (!BG_IsValidCharacterModel(truncModelName, skin)) { strcpy(truncModelName, DEFAULT_MODEL); strcpy(skin, "default"); } - if ( level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer ) - { + if (level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer) { float colorOverride[3]; colorOverride[0] = colorOverride[1] = colorOverride[2] = 0.0f; - BG_ValidateSkinForTeam( truncModelName, skin, ent->client->sess.sessionTeam, colorOverride); - if (colorOverride[0] != 0.0f || - colorOverride[1] != 0.0f || - colorOverride[2] != 0.0f) - { - ent->client->ps.customRGBA[0] = colorOverride[0]*255.0f; - ent->client->ps.customRGBA[1] = colorOverride[1]*255.0f; - ent->client->ps.customRGBA[2] = colorOverride[2]*255.0f; + BG_ValidateSkinForTeam(truncModelName, skin, ent->client->sess.sessionTeam, colorOverride); + if (colorOverride[0] != 0.0f || colorOverride[1] != 0.0f || colorOverride[2] != 0.0f) { + ent->client->ps.customRGBA[0] = colorOverride[0] * 255.0f; + ent->client->ps.customRGBA[1] = colorOverride[1] * 255.0f; + ent->client->ps.customRGBA[2] = colorOverride[2] * 255.0f; } - //BG_ValidateSkinForTeam( truncModelName, skin, ent->client->sess.sessionTeam, NULL ); - } - else if (level.gametype == GT_SIEGE) - { //force skin for class if appropriate - if (ent->client->siegeClass != -1) - { + // BG_ValidateSkinForTeam( truncModelName, skin, ent->client->sess.sessionTeam, NULL ); + } else if (level.gametype == GT_SIEGE) { // force skin for class if appropriate + if (ent->client->siegeClass != -1) { siegeClass_t *scl = &bgSiegeClasses[ent->client->siegeClass]; - if (scl->forcedSkin[0]) - { - Q_strncpyz( skin, scl->forcedSkin, sizeof( skin ) ); + if (scl->forcedSkin[0]) { + Q_strncpyz(skin, scl->forcedSkin, sizeof(skin)); } } } } } - if (skin[0]) - { + if (skin[0]) { char *useSkinName; - if (strchr(skin, '|')) - {//three part skin + if (strchr(skin, '|')) { // three part skin useSkinName = va("models/players/%s/|%s", truncModelName, skin); - } - else - { + } else { useSkinName = va("models/players/%s/model_%s.skin", truncModelName, skin); } @@ -1721,79 +1545,63 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) strcpy(modelFullPath, va("models/players/%s/model.glm", truncModelName)); handle = trap->G2API_InitGhoul2Model(&ent->ghoul2, modelFullPath, 0, skinHandle, -20, 0, 0); - if (handle<0) - { //Huh. Guess we don't have this model. Use the default. + if (handle < 0) { // Huh. Guess we don't have this model. Use the default. - if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) - { + if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) { trap->G2API_CleanGhoul2Models(&(ent->ghoul2)); } ent->ghoul2 = NULL; trap->G2API_DuplicateGhoul2Instance(precachedKyle, &ent->ghoul2); - } - else - { + } else { trap->G2API_SetSkin(ent->ghoul2, 0, skinHandle, skinHandle); GLAName[0] = 0; - trap->G2API_GetGLAName( ent->ghoul2, 0, GLAName); + trap->G2API_GetGLAName(ent->ghoul2, 0, GLAName); - if (!GLAName[0] || (!strstr(GLAName, "players/_humanoid/") && ent->s.number < MAX_CLIENTS && !G_PlayerHasCustomSkeleton(ent))) - { //a bad model + if (!GLAName[0] || (!strstr(GLAName, "players/_humanoid/") && ent->s.number < MAX_CLIENTS && !G_PlayerHasCustomSkeleton(ent))) { // a bad model trap->G2API_CleanGhoul2Models(&(ent->ghoul2)); ent->ghoul2 = NULL; trap->G2API_DuplicateGhoul2Instance(precachedKyle, &ent->ghoul2); } - if (ent->s.number >= MAX_CLIENTS) - { - ent->s.modelGhoul2 = 1; //so we know to free it on the client when we're removed. + if (ent->s.number >= MAX_CLIENTS) { + ent->s.modelGhoul2 = 1; // so we know to free it on the client when we're removed. - if (skin[0]) - { //append it after a * - strcat( modelFullPath, va("*%s", skin) ); + if (skin[0]) { // append it after a * + strcat(modelFullPath, va("*%s", skin)); } - if ( ent->client->NPC_class == CLASS_VEHICLE ) - { //vehicles are tricky and send over their vehicle names as the model (the model is then retrieved based on the vehicle name) + if (ent->client->NPC_class == CLASS_VEHICLE) { // vehicles are tricky and send over their vehicle names as the model (the model is then + // retrieved based on the vehicle name) ent->s.modelindex = G_ModelIndex(vehicleName); - } - else - { + } else { ent->s.modelindex = G_ModelIndex(modelFullPath); } } } - } - else - { + } else { trap->G2API_DuplicateGhoul2Instance(precachedKyle, &ent->ghoul2); } - } - else - { + } else { return; } - //Attach the instance to this entity num so we can make use of client-server - //shared operations if possible. + // Attach the instance to this entity num so we can make use of client-server + // shared operations if possible. trap->G2API_AttachInstanceToEntNum(ent->ghoul2, ent->s.number, qtrue); // The model is now loaded. GLAName[0] = 0; - if (!BGPAFtextLoaded) - { - if (BG_ParseAnimationFile("models/players/_humanoid/animation.cfg", bgHumanoidAnimations, qtrue) == -1) - { - Com_Printf( "Failed to load humanoid animation file\n"); + if (!BGPAFtextLoaded) { + if (BG_ParseAnimationFile("models/players/_humanoid/animation.cfg", bgHumanoidAnimations, qtrue) == -1) { + Com_Printf("Failed to load humanoid animation file\n"); return; } } - if (ent->s.number >= MAX_CLIENTS || G_PlayerHasCustomSkeleton(ent)) - { + if (ent->s.number >= MAX_CLIENTS || G_PlayerHasCustomSkeleton(ent)) { ent->localAnimIndex = -1; GLAName[0] = 0; @@ -1803,102 +1611,80 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) !strstr(GLAName, "players/_humanoid/") /*&& !strstr(GLAName, "players/rockettrooper/")*/) { //it doesn't use humanoid anims. - char *slash = Q_strrchr( GLAName, '/' ); - if ( slash ) - { + char *slash = Q_strrchr(GLAName, '/'); + if (slash) { strcpy(slash, "/animation.cfg"); ent->localAnimIndex = BG_ParseAnimationFile(GLAName, NULL, qfalse); } - } - else - { //humanoid index. - if (strstr(GLAName, "players/rockettrooper/")) - { + } else { // humanoid index. + if (strstr(GLAName, "players/rockettrooper/")) { ent->localAnimIndex = 1; - } - else - { + } else { ent->localAnimIndex = 0; } } - if (ent->localAnimIndex == -1) - { + if (ent->localAnimIndex == -1) { Com_Error(ERR_DROP, "NPC had an invalid GLA\n"); } - } - else - { + } else { GLAName[0] = 0; trap->G2API_GetGLAName(ent->ghoul2, 0, GLAName); - if (strstr(GLAName, "players/rockettrooper/")) - { - //assert(!"Should not have gotten in here with rockettrooper skel"); + if (strstr(GLAName, "players/rockettrooper/")) { + // assert(!"Should not have gotten in here with rockettrooper skel"); ent->localAnimIndex = 1; - } - else - { + } else { ent->localAnimIndex = 0; } } - if (ent->s.NPC_class == CLASS_VEHICLE && - ent->m_pVehicle) - { //do special vehicle stuff + if (ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle) { // do special vehicle stuff char strTemp[128]; int i; // Setup the default first bolt - i = trap->G2API_AddBolt( ent->ghoul2, 0, "model_root" ); + i = trap->G2API_AddBolt(ent->ghoul2, 0, "model_root"); // Setup the droid unit. - ent->m_pVehicle->m_iDroidUnitTag = trap->G2API_AddBolt( ent->ghoul2, 0, "*droidunit" ); + ent->m_pVehicle->m_iDroidUnitTag = trap->G2API_AddBolt(ent->ghoul2, 0, "*droidunit"); // Setup the Exhausts. - for ( i = 0; i < MAX_VEHICLE_EXHAUSTS; i++ ) - { - Com_sprintf( strTemp, 128, "*exhaust%i", i + 1 ); - ent->m_pVehicle->m_iExhaustTag[i] = trap->G2API_AddBolt( ent->ghoul2, 0, strTemp ); + for (i = 0; i < MAX_VEHICLE_EXHAUSTS; i++) { + Com_sprintf(strTemp, 128, "*exhaust%i", i + 1); + ent->m_pVehicle->m_iExhaustTag[i] = trap->G2API_AddBolt(ent->ghoul2, 0, strTemp); } // Setup the Muzzles. - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - Com_sprintf( strTemp, 128, "*muzzle%i", i + 1 ); - ent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt( ent->ghoul2, 0, strTemp ); - if ( ent->m_pVehicle->m_iMuzzleTag[i] == -1 ) - {//ergh, try *flash? - Com_sprintf( strTemp, 128, "*flash%i", i + 1 ); - ent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt( ent->ghoul2, 0, strTemp ); + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + Com_sprintf(strTemp, 128, "*muzzle%i", i + 1); + ent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt(ent->ghoul2, 0, strTemp); + if (ent->m_pVehicle->m_iMuzzleTag[i] == -1) { // ergh, try *flash? + Com_sprintf(strTemp, 128, "*flash%i", i + 1); + ent->m_pVehicle->m_iMuzzleTag[i] = trap->G2API_AddBolt(ent->ghoul2, 0, strTemp); } } // Setup the Turrets. - for ( i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++ ) - { - if ( ent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag ) - { - ent->m_pVehicle->m_iGunnerViewTag[i] = trap->G2API_AddBolt( ent->ghoul2, 0, ent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag ); - } - else - { + for (i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++) { + if (ent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag) { + ent->m_pVehicle->m_iGunnerViewTag[i] = trap->G2API_AddBolt(ent->ghoul2, 0, ent->m_pVehicle->m_pVehicleInfo->turret[i].gunnerViewTag); + } else { ent->m_pVehicle->m_iGunnerViewTag[i] = -1; } } } - if (ent->client->ps.weapon == WP_SABER || ent->s.number < MAX_CLIENTS) - { //a player or NPC saber user + if (ent->client->ps.weapon == WP_SABER || ent->s.number < MAX_CLIENTS) { // a player or NPC saber user trap->G2API_AddBolt(ent->ghoul2, 0, "*r_hand"); trap->G2API_AddBolt(ent->ghoul2, 0, "*l_hand"); - //rhand must always be first bolt. lhand always second. Whichever you want the - //jetpack bolted to must always be third. + // rhand must always be first bolt. lhand always second. Whichever you want the + // jetpack bolted to must always be third. trap->G2API_AddBolt(ent->ghoul2, 0, "*chestg"); - //claw bolts + // claw bolts trap->G2API_AddBolt(ent->ghoul2, 0, "*r_hand_cap_r_arm"); trap->G2API_AddBolt(ent->ghoul2, 0, "*l_hand_cap_l_arm"); @@ -1906,12 +1692,10 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) trap->G2API_SetBoneAngles(ent->ghoul2, 0, "upper_lumbar", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, NULL, 0, level.time); trap->G2API_SetBoneAngles(ent->ghoul2, 0, "cranium", tempVec, BONE_ANGLES_POSTMULT, POSITIVE_Z, NEGATIVE_Y, POSITIVE_X, NULL, 0, level.time); - if (!g2SaberInstance) - { + if (!g2SaberInstance) { trap->G2API_InitGhoul2Model(&g2SaberInstance, DEFAULT_SABER_MODEL, 0, 0, -20, 0, 0); - if (g2SaberInstance) - { + if (g2SaberInstance) { // indicate we will be bolted to model 0 (ie the player) on bolt 0 (always the right hand) when we get copied trap->G2API_SetBoltInfo(g2SaberInstance, 0, 0); // now set up the gun bolt on it @@ -1919,27 +1703,20 @@ void SetupGameGhoul2Model(gentity_t *ent, char *modelname, char *skinName) } } - if (G_SaberModelSetup(ent)) - { - if (g2SaberInstance) - { + if (G_SaberModelSetup(ent)) { + if (g2SaberInstance) { trap->G2API_CopySpecificGhoul2Model(g2SaberInstance, 0, ent->ghoul2, 1); } } } - if (ent->s.number >= MAX_CLIENTS) - { //some extra NPC stuff - if (trap->G2API_AddBolt(ent->ghoul2, 0, "lower_lumbar") == -1) - { //check now to see if we have this bone for setting anims and such + if (ent->s.number >= MAX_CLIENTS) { // some extra NPC stuff + if (trap->G2API_AddBolt(ent->ghoul2, 0, "lower_lumbar") == -1) { // check now to see if we have this bone for setting anims and such ent->noLumbar = qtrue; } } } - - - /* =========== ClientUserInfoChanged @@ -1956,425 +1733,431 @@ qboolean G_SetSaber(gentity_t *ent, int saberNum, char *saberName, qboolean sieg void G_ValidateSiegeClassForTeam(gentity_t *ent, int team); typedef struct userinfoValidate_s { - const char *field, *fieldClean; - unsigned int minCount, maxCount; + const char *field, *fieldClean; + unsigned int minCount, maxCount; } userinfoValidate_t; -#define UIF( x, _min, _max ) { STRING(\\) #x STRING(\\), STRING( x ), _min, _max } +#define UIF(x, _min, _max) \ + { STRING(\\) #x STRING(\\), STRING(x), _min, _max } static userinfoValidate_t userinfoFields[] = { - UIF( cl_guid, 0, 0 ), // not allowed, q3fill protection - UIF( cl_punkbuster, 0, 0 ), // not allowed, q3fill protection - UIF( ip, 0, 1 ), // engine adds this at the end - UIF( name, 1, 1 ), - UIF( rate, 1, 1 ), - UIF( snaps, 1, 1 ), - UIF( model, 1, 1 ), - UIF( forcepowers, 1, 1 ), - UIF( color1, 1, 1 ), - UIF( color2, 1, 1 ), - UIF( handicap, 1, 1 ), - UIF( sex, 0, 1 ), - UIF( cg_predictItems, 1, 1 ), - UIF( saber1, 1, 1 ), - UIF( saber2, 1, 1 ), - UIF( char_color_red, 1, 1 ), - UIF( char_color_green, 1, 1 ), - UIF( char_color_blue, 1, 1 ), - UIF( teamtask, 0, 1 ), // optional - UIF( password, 0, 1 ), // optional - UIF( teamoverlay, 0, 1 ), // only registered in cgame, not sent when connecting + UIF(cl_guid, 0, 0), // not allowed, q3fill protection + UIF(cl_punkbuster, 0, 0), // not allowed, q3fill protection + UIF(ip, 0, 1), // engine adds this at the end + UIF(name, 1, 1), + UIF(rate, 1, 1), + UIF(snaps, 1, 1), + UIF(model, 1, 1), + UIF(forcepowers, 1, 1), + UIF(color1, 1, 1), + UIF(color2, 1, 1), + UIF(handicap, 1, 1), + UIF(sex, 0, 1), + UIF(cg_predictItems, 1, 1), + UIF(saber1, 1, 1), + UIF(saber2, 1, 1), + UIF(char_color_red, 1, 1), + UIF(char_color_green, 1, 1), + UIF(char_color_blue, 1, 1), + UIF(teamtask, 0, 1), // optional + UIF(password, 0, 1), // optional + UIF(teamoverlay, 0, 1), // only registered in cgame, not sent when connecting }; -static const size_t numUserinfoFields = ARRAY_LEN( userinfoFields ); +static const size_t numUserinfoFields = ARRAY_LEN(userinfoFields); static const char *userinfoValidateExtra[USERINFO_VALIDATION_MAX] = { - "Size", // USERINFO_VALIDATION_SIZE - "# of slashes", // USERINFO_VALIDATION_SLASH - "Extended ascii", // USERINFO_VALIDATION_EXTASCII - "Control characters", // USERINFO_VALIDATION_CONTROLCHARS + "Size", // USERINFO_VALIDATION_SIZE + "# of slashes", // USERINFO_VALIDATION_SLASH + "Extended ascii", // USERINFO_VALIDATION_EXTASCII + "Control characters", // USERINFO_VALIDATION_CONTROLCHARS }; -void Svcmd_ToggleUserinfoValidation_f( void ) { - if ( trap->Argc() == 1 ) { - int i=0; - for ( i=0; iPrint( "%2d [X] %s\n", i, userinfoFields[i].fieldClean ); - else trap->Print( "%2d [ ] %s\n", i, userinfoFields[i].fieldClean ); +void Svcmd_ToggleUserinfoValidation_f(void) { + if (trap->Argc() == 1) { + int i = 0; + for (i = 0; i < numUserinfoFields; i++) { + if ((g_userinfoValidate.integer & (1 << i))) + trap->Print("%2d [X] %s\n", i, userinfoFields[i].fieldClean); + else + trap->Print("%2d [ ] %s\n", i, userinfoFields[i].fieldClean); } - for ( ; iPrint( "%2d [X] %s\n", i, userinfoValidateExtra[i-numUserinfoFields] ); - else trap->Print( "%2d [ ] %s\n", i, userinfoValidateExtra[i-numUserinfoFields] ); + for (; i < numUserinfoFields + USERINFO_VALIDATION_MAX; i++) { + if ((g_userinfoValidate.integer & (1 << i))) + trap->Print("%2d [X] %s\n", i, userinfoValidateExtra[i - numUserinfoFields]); + else + trap->Print("%2d [ ] %s\n", i, userinfoValidateExtra[i - numUserinfoFields]); } return; - } - else { - char arg[8]={0}; + } else { + char arg[8] = {0}; int index; - trap->Argv( 1, arg, sizeof( arg ) ); - index = atoi( arg ); + trap->Argv(1, arg, sizeof(arg)); + index = atoi(arg); - if ( index < 0 || index > numUserinfoFields+USERINFO_VALIDATION_MAX-1 ) { - Com_Printf( "ToggleUserinfoValidation: Invalid range: %i [0, %i]\n", index, numUserinfoFields+USERINFO_VALIDATION_MAX-1 ); + if (index < 0 || index > numUserinfoFields + USERINFO_VALIDATION_MAX - 1) { + Com_Printf("ToggleUserinfoValidation: Invalid range: %i [0, %i]\n", index, numUserinfoFields + USERINFO_VALIDATION_MAX - 1); return; } - trap->Cvar_Set( "g_userinfoValidate", va( "%i", (1 << index) ^ (g_userinfoValidate.integer & ((1 << (numUserinfoFields + USERINFO_VALIDATION_MAX)) - 1)) ) ); - trap->Cvar_Update( &g_userinfoValidate ); + trap->Cvar_Set("g_userinfoValidate", + va("%i", (1 << index) ^ (g_userinfoValidate.integer & ((1 << (numUserinfoFields + USERINFO_VALIDATION_MAX)) - 1)))); + trap->Cvar_Update(&g_userinfoValidate); - if ( index < numUserinfoFields ) Com_Printf( "%s %s\n", userinfoFields[index].fieldClean, ((g_userinfoValidate.integer & (1<= MAX_INFO_STRING ) + else if (length >= MAX_INFO_STRING) return "Userinfo too long"; } // slash checks - if ( g_userinfoValidate.integer & (1<<(numUserinfoFields+USERINFO_VALIDATION_SLASH)) ) { + if (g_userinfoValidate.integer & (1 << (numUserinfoFields + USERINFO_VALIDATION_SLASH))) { // there must be a leading slash - if ( userinfo[0] != '\\' ) + if (userinfo[0] != '\\') return "Missing leading slash"; // no trailing slashes allowed, engine will append ip\\ip:port - if ( userinfo[length-1] == '\\' ) + if (userinfo[length - 1] == '\\') return "Trailing slash"; // format for userinfo field is: \\key\\value // so there must be an even amount of slashes - for ( i=0, count=0; iminCount && !fieldCount[i] ) - return va( "%s field not found", info->fieldClean ); - else if ( fieldCount[i] > info->maxCount ) - return va( "Too many %s fields (%i/%i)", info->fieldClean, fieldCount[i], info->maxCount ); + for (i = 0, info = userinfoFields; i < numUserinfoFields; i++, info++) { + if (g_userinfoValidate.integer & (1 << i)) { + if (info->minCount && !fieldCount[i]) + return va("%s field not found", info->fieldClean); + else if (fieldCount[i] > info->maxCount) + return va("Too many %s fields (%i/%i)", info->fieldClean, fieldCount[i], info->maxCount); } } return NULL; } -qboolean ClientUserinfoChanged( int clientNum ) { +qboolean ClientUserinfoChanged(int clientNum) { gentity_t *ent = g_entities + clientNum; gclient_t *client = ent->client; - int team=TEAM_FREE, health=100, maxHealth=100, teamLeader; - const char *s=NULL; - char *value=NULL, userinfo[MAX_INFO_STRING], buf[MAX_INFO_STRING], oldClientinfo[MAX_INFO_STRING], model[MAX_QPATH], - forcePowers[DEFAULT_FORCEPOWERS_LEN], oldname[MAX_NETNAME], className[MAX_QPATH], color1[16], color2[16]; + int team = TEAM_FREE, health = 100, maxHealth = 100, teamLeader; + const char *s = NULL; + char *value = NULL, userinfo[MAX_INFO_STRING], buf[MAX_INFO_STRING], oldClientinfo[MAX_INFO_STRING], model[MAX_QPATH], forcePowers[DEFAULT_FORCEPOWERS_LEN], + oldname[MAX_NETNAME], className[MAX_QPATH], color1[16], color2[16]; qboolean modelChanged = qfalse; gender_t gender = GENDER_MALE; - trap->GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + trap->GetUserinfo(clientNum, userinfo, sizeof(userinfo)); // check for malformed or illegal info strings - s = G_ValidateUserinfo( userinfo ); - if ( s && *s ) { - G_SecurityLogPrintf( "Client %d (%s) failed userinfo validation: %s [IP: %s]\n", clientNum, ent->client->pers.netname, s, client->sess.IP ); - trap->DropClient( clientNum, va( "Failed userinfo validation: %s", s ) ); - G_LogPrintf( "Userinfo: %s\n", userinfo ); + s = G_ValidateUserinfo(userinfo); + if (s && *s) { + G_SecurityLogPrintf("Client %d (%s) failed userinfo validation: %s [IP: %s]\n", clientNum, ent->client->pers.netname, s, client->sess.IP); + trap->DropClient(clientNum, va("Failed userinfo validation: %s", s)); + G_LogPrintf("Userinfo: %s\n", userinfo); return qfalse; } // check for local client - s = Info_ValueForKey( userinfo, "ip" ); - if ( !strcmp( s, "localhost" ) && !(ent->r.svFlags & SVF_BOT) ) + s = Info_ValueForKey(userinfo, "ip"); + if (!strcmp(s, "localhost") && !(ent->r.svFlags & SVF_BOT)) client->pers.localClient = qtrue; // check the item prediction - s = Info_ValueForKey( userinfo, "cg_predictItems" ); - if ( !atoi( s ) ) client->pers.predictItemPickup = qfalse; - else client->pers.predictItemPickup = qtrue; + s = Info_ValueForKey(userinfo, "cg_predictItems"); + if (!atoi(s)) + client->pers.predictItemPickup = qfalse; + else + client->pers.predictItemPickup = qtrue; // set name - Q_strncpyz( oldname, client->pers.netname, sizeof( oldname ) ); - s = Info_ValueForKey( userinfo, "name" ); - ClientCleanName( s, client->pers.netname, sizeof( client->pers.netname ) ); - Q_strncpyz( client->pers.netname_nocolor, client->pers.netname, sizeof( client->pers.netname_nocolor ) ); - Q_StripColor( client->pers.netname_nocolor ); - - if ( client->sess.sessionTeam == TEAM_SPECTATOR && client->sess.spectatorState == SPECTATOR_SCOREBOARD ) { - Q_strncpyz( client->pers.netname, "scoreboard", sizeof( client->pers.netname ) ); - Q_strncpyz( client->pers.netname_nocolor, "scoreboard", sizeof( client->pers.netname_nocolor ) ); - } - - if ( client->pers.connected == CON_CONNECTED && strcmp( oldname, client->pers.netname ) ) { - if ( client->pers.netnameTime > level.time ) { - trap->SendServerCommand( clientNum, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "NONAMECHANGE" ) ) ); - - Info_SetValueForKey( userinfo, "name", oldname ); - trap->SetUserinfo( clientNum, userinfo ); - Q_strncpyz( client->pers.netname, oldname, sizeof( client->pers.netname ) ); - Q_strncpyz( client->pers.netname_nocolor, oldname, sizeof( client->pers.netname_nocolor ) ); - Q_StripColor( client->pers.netname_nocolor ); - } - else { - trap->SendServerCommand( -1, va( "print \"%s" S_COLOR_WHITE " %s %s\n\"", oldname, G_GetStringEdString( "MP_SVGAME", "PLRENAME" ), client->pers.netname ) ); - G_LogPrintf( "ClientRename: %i [%s] (%s) \"%s^7\" -> \"%s^7\"\n", clientNum, ent->client->sess.IP, ent->client->pers.guid, oldname, ent->client->pers.netname ); + Q_strncpyz(oldname, client->pers.netname, sizeof(oldname)); + s = Info_ValueForKey(userinfo, "name"); + ClientCleanName(s, client->pers.netname, sizeof(client->pers.netname)); + Q_strncpyz(client->pers.netname_nocolor, client->pers.netname, sizeof(client->pers.netname_nocolor)); + Q_StripColor(client->pers.netname_nocolor); + + if (client->sess.sessionTeam == TEAM_SPECTATOR && client->sess.spectatorState == SPECTATOR_SCOREBOARD) { + Q_strncpyz(client->pers.netname, "scoreboard", sizeof(client->pers.netname)); + Q_strncpyz(client->pers.netname_nocolor, "scoreboard", sizeof(client->pers.netname_nocolor)); + } + + if (client->pers.connected == CON_CONNECTED && strcmp(oldname, client->pers.netname)) { + if (client->pers.netnameTime > level.time) { + trap->SendServerCommand(clientNum, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NONAMECHANGE"))); + + Info_SetValueForKey(userinfo, "name", oldname); + trap->SetUserinfo(clientNum, userinfo); + Q_strncpyz(client->pers.netname, oldname, sizeof(client->pers.netname)); + Q_strncpyz(client->pers.netname_nocolor, oldname, sizeof(client->pers.netname_nocolor)); + Q_StripColor(client->pers.netname_nocolor); + } else { + trap->SendServerCommand(-1, + va("print \"%s" S_COLOR_WHITE " %s %s\n\"", oldname, G_GetStringEdString("MP_SVGAME", "PLRENAME"), client->pers.netname)); + G_LogPrintf("ClientRename: %i [%s] (%s) \"%s^7\" -> \"%s^7\"\n", clientNum, ent->client->sess.IP, ent->client->pers.guid, oldname, + ent->client->pers.netname); client->pers.netnameTime = level.time + 5000; } } // set model - Q_strncpyz( model, Info_ValueForKey( userinfo, "model" ), sizeof( model ) ); + Q_strncpyz(model, Info_ValueForKey(userinfo, "model"), sizeof(model)); - if ( d_perPlayerGhoul2.integer&& Q_stricmp( model, client->modelname ) ) { - Q_strncpyz( client->modelname, model, sizeof( client->modelname ) ); + if (d_perPlayerGhoul2.integer && Q_stricmp(model, client->modelname)) { + Q_strncpyz(client->modelname, model, sizeof(client->modelname)); modelChanged = qtrue; } - client->ps.customRGBA[0] = (value=Info_ValueForKey( userinfo, "char_color_red" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; - client->ps.customRGBA[1] = (value=Info_ValueForKey( userinfo, "char_color_green" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; - client->ps.customRGBA[2] = (value=Info_ValueForKey( userinfo, "char_color_blue" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; + client->ps.customRGBA[0] = (value = Info_ValueForKey(userinfo, "char_color_red")) ? Com_Clampi(0, 255, atoi(value)) : 255; + client->ps.customRGBA[1] = (value = Info_ValueForKey(userinfo, "char_color_green")) ? Com_Clampi(0, 255, atoi(value)) : 255; + client->ps.customRGBA[2] = (value = Info_ValueForKey(userinfo, "char_color_blue")) ? Com_Clampi(0, 255, atoi(value)) : 255; - //Prevent skins being too dark - if ( g_charRestrictRGB.integer && ((client->ps.customRGBA[0]+client->ps.customRGBA[1]+client->ps.customRGBA[2]) < 100) ) + // Prevent skins being too dark + if (g_charRestrictRGB.integer && ((client->ps.customRGBA[0] + client->ps.customRGBA[1] + client->ps.customRGBA[2]) < 100)) client->ps.customRGBA[0] = client->ps.customRGBA[1] = client->ps.customRGBA[2] = 255; - client->ps.customRGBA[3]=255; + client->ps.customRGBA[3] = 255; - Q_strncpyz( forcePowers, Info_ValueForKey( userinfo, "forcepowers" ), sizeof( forcePowers ) ); + Q_strncpyz(forcePowers, Info_ValueForKey(userinfo, "forcepowers"), sizeof(forcePowers)); // update our customRGBA for team colors. - if ( level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer ) { + if (level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer) { char skin[MAX_QPATH] = {0}; vec3_t colorOverride = {0.0f}; - VectorClear( colorOverride ); + VectorClear(colorOverride); - BG_ValidateSkinForTeam( model, skin, client->sess.sessionTeam, colorOverride ); - if ( colorOverride[0] != 0.0f || colorOverride[1] != 0.0f || colorOverride[2] != 0.0f ) - VectorScaleM( colorOverride, 255.0f, client->ps.customRGBA ); + BG_ValidateSkinForTeam(model, skin, client->sess.sessionTeam, colorOverride); + if (colorOverride[0] != 0.0f || colorOverride[1] != 0.0f || colorOverride[2] != 0.0f) + VectorScaleM(colorOverride, 255.0f, client->ps.customRGBA); } // bots set their team a few frames later - if ( level.gametype >= GT_TEAM && g_entities[clientNum].r.svFlags & SVF_BOT ) { - s = Info_ValueForKey( userinfo, "team" ); - if ( !Q_stricmp( s, "red" ) || !Q_stricmp( s, "r" ) ) + if (level.gametype >= GT_TEAM && g_entities[clientNum].r.svFlags & SVF_BOT) { + s = Info_ValueForKey(userinfo, "team"); + if (!Q_stricmp(s, "red") || !Q_stricmp(s, "r")) team = TEAM_RED; - else if ( !Q_stricmp( s, "blue" ) || !Q_stricmp( s, "b" ) ) + else if (!Q_stricmp(s, "blue") || !Q_stricmp(s, "b")) team = TEAM_BLUE; else - team = PickTeam( clientNum ); // pick the team with the least number of players - } - else + team = PickTeam(clientNum); // pick the team with the least number of players + } else team = client->sess.sessionTeam; - //Testing to see if this fixes the problem with a bot's team getting set incorrectly. + // Testing to see if this fixes the problem with a bot's team getting set incorrectly. team = client->sess.sessionTeam; - //Set the siege class - if ( level.gametype == GT_SIEGE ) { - Q_strncpyz( className, client->sess.siegeClass, sizeof( className ) ); + // Set the siege class + if (level.gametype == GT_SIEGE) { + Q_strncpyz(className, client->sess.siegeClass, sizeof(className)); - //Now that the team is legal for sure, we'll go ahead and get an index for it. - client->siegeClass = BG_SiegeFindClassIndexByName( className ); - if ( client->siegeClass == -1 ) { + // Now that the team is legal for sure, we'll go ahead and get an index for it. + client->siegeClass = BG_SiegeFindClassIndexByName(className); + if (client->siegeClass == -1) { // ok, get the first valid class for the team you're on then, I guess. - BG_SiegeCheckClassLegality( team, className ); - Q_strncpyz( client->sess.siegeClass, className, sizeof( client->sess.siegeClass ) ); - client->siegeClass = BG_SiegeFindClassIndexByName( className ); - } - else { + BG_SiegeCheckClassLegality(team, className); + Q_strncpyz(client->sess.siegeClass, className, sizeof(client->sess.siegeClass)); + client->siegeClass = BG_SiegeFindClassIndexByName(className); + } else { // otherwise, make sure the class we are using is legal. - G_ValidateSiegeClassForTeam( ent, team ); - Q_strncpyz( className, client->sess.siegeClass, sizeof( className ) ); + G_ValidateSiegeClassForTeam(ent, team); + Q_strncpyz(className, client->sess.siegeClass, sizeof(className)); } - if ( client->siegeClass != -1 ) { + if (client->siegeClass != -1) { // Set the sabers if the class dictates siegeClass_t *scl = &bgSiegeClasses[client->siegeClass]; - G_SetSaber( ent, 0, scl->saber1[0] ? scl->saber1 : DEFAULT_SABER, qtrue ); - G_SetSaber( ent, 1, scl->saber2[0] ? scl->saber2 : "none", qtrue ); + G_SetSaber(ent, 0, scl->saber1[0] ? scl->saber1 : DEFAULT_SABER, qtrue); + G_SetSaber(ent, 1, scl->saber2[0] ? scl->saber2 : "none", qtrue); - //make sure the saber models are updated - G_SaberModelSetup( ent ); + // make sure the saber models are updated + G_SaberModelSetup(ent); - if ( scl->forcedModel[0] ) { + if (scl->forcedModel[0]) { // be sure to override the model we actually use - Q_strncpyz( model, scl->forcedModel, sizeof( model ) ); - if ( d_perPlayerGhoul2.integer && Q_stricmp( model, client->modelname ) ) { - Q_strncpyz( client->modelname, model, sizeof( client->modelname ) ); + Q_strncpyz(model, scl->forcedModel, sizeof(model)); + if (d_perPlayerGhoul2.integer && Q_stricmp(model, client->modelname)) { + Q_strncpyz(client->modelname, model, sizeof(client->modelname)); modelChanged = qtrue; } } - if ( G_PlayerHasCustomSkeleton( ent ) ) - {//force them to use their class model on the server, if the class dictates - if ( Q_stricmp( model, client->modelname ) || ent->localAnimIndex == 0 ) - { - Q_strncpyz( client->modelname, model, sizeof( client->modelname ) ); + if (G_PlayerHasCustomSkeleton(ent)) { // force them to use their class model on the server, if the class dictates + if (Q_stricmp(model, client->modelname) || ent->localAnimIndex == 0) { + Q_strncpyz(client->modelname, model, sizeof(client->modelname)); modelChanged = qtrue; } } } - } - else - Q_strncpyz( className, "none", sizeof( className ) ); + } else + Q_strncpyz(className, "none", sizeof(className)); // only set the saber name on the first connect. // it will be read from userinfo on ClientSpawn and stored in client->pers.saber1/2 - if ( !VALIDSTRING( client->pers.saber1 ) || !VALIDSTRING( client->pers.saber2 ) ) { - G_SetSaber( ent, 0, Info_ValueForKey( userinfo, "saber1" ), qfalse ); - G_SetSaber( ent, 1, Info_ValueForKey( userinfo, "saber2" ), qfalse ); + if (!VALIDSTRING(client->pers.saber1) || !VALIDSTRING(client->pers.saber2)) { + G_SetSaber(ent, 0, Info_ValueForKey(userinfo, "saber1"), qfalse); + G_SetSaber(ent, 1, Info_ValueForKey(userinfo, "saber2"), qfalse); } // set max health - if ( level.gametype == GT_SIEGE && client->siegeClass != -1 ) { + if (level.gametype == GT_SIEGE && client->siegeClass != -1) { siegeClass_t *scl = &bgSiegeClasses[client->siegeClass]; - if ( scl->maxhealth ) + if (scl->maxhealth) maxHealth = scl->maxhealth; health = maxHealth; - } - else - health = Com_Clampi( 1, 100, atoi( Info_ValueForKey( userinfo, "handicap" ) ) ); + } else + health = Com_Clampi(1, 100, atoi(Info_ValueForKey(userinfo, "handicap"))); client->pers.maxHealth = health; - if ( client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth ) + if (client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth) client->pers.maxHealth = 100; client->ps.stats[STAT_MAX_HEALTH] = client->pers.maxHealth; - if ( level.gametype >= GT_TEAM ) + if (level.gametype >= GT_TEAM) client->pers.teamInfo = qtrue; else { - s = Info_ValueForKey( userinfo, "teamoverlay" ); - if ( !*s || atoi( s ) != 0 ) + s = Info_ValueForKey(userinfo, "teamoverlay"); + if (!*s || atoi(s) != 0) client->pers.teamInfo = qtrue; else client->pers.teamInfo = qfalse; } // team task (0 = none, 1 = offence, 2 = defence) -// teamTask = atoi(Info_ValueForKey(userinfo, "teamtask")); + // teamTask = atoi(Info_ValueForKey(userinfo, "teamtask")); // team Leader (1 = leader, 0 is normal player) teamLeader = client->sess.teamLeader; // colors - Q_strncpyz( color1, Info_ValueForKey( userinfo, "color1" ), sizeof( color1 ) ); - Q_strncpyz( color2, Info_ValueForKey( userinfo, "color2" ), sizeof( color2 ) ); + Q_strncpyz(color1, Info_ValueForKey(userinfo, "color1"), sizeof(color1)); + Q_strncpyz(color2, Info_ValueForKey(userinfo, "color2"), sizeof(color2)); // gender hints - s = Info_ValueForKey( userinfo, "sex" ); - if ( !Q_stricmp( s, "female" ) ) + s = Info_ValueForKey(userinfo, "sex"); + if (!Q_stricmp(s, "female")) gender = GENDER_FEMALE; else gender = GENDER_MALE; - s = Info_ValueForKey( userinfo, "snaps" ); - if ( atoi( s ) < sv_fps.integer ) - trap->SendServerCommand( clientNum, va( "print \"" S_COLOR_YELLOW "Recommend setting /snaps %d or higher to match this server's sv_fps\n\"", sv_fps.integer ) ); + s = Info_ValueForKey(userinfo, "snaps"); + if (atoi(s) < sv_fps.integer) + trap->SendServerCommand(clientNum, + va("print \"" S_COLOR_YELLOW "Recommend setting /snaps %d or higher to match this server's sv_fps\n\"", sv_fps.integer)); // send over a subset of the userinfo keys so other clients can // print scoreboards, display models, and play custom sounds buf[0] = '\0'; - Q_strcat( buf, sizeof( buf ), va( "n\\%s\\", client->pers.netname ) ); - Q_strcat( buf, sizeof( buf ), va( "t\\%i\\", client->sess.sessionTeam ) ); - Q_strcat( buf, sizeof( buf ), va( "model\\%s\\", model ) ); - if ( gender == GENDER_FEMALE ) Q_strcat( buf, sizeof( buf ), va( "ds\\%c\\", 'f' ) ); - else Q_strcat( buf, sizeof( buf ), va( "ds\\%c\\", 'm' ) ); - Q_strcat( buf, sizeof( buf ), va( "st\\%s\\", client->pers.saber1 ) ); - Q_strcat( buf, sizeof( buf ), va( "st2\\%s\\", client->pers.saber2 ) ); - Q_strcat( buf, sizeof( buf ), va( "c1\\%s\\", color1 ) ); - Q_strcat( buf, sizeof( buf ), va( "c2\\%s\\", color2 ) ); - Q_strcat( buf, sizeof( buf ), va( "hc\\%i\\", client->pers.maxHealth ) ); - if ( ent->r.svFlags & SVF_BOT ) - Q_strcat( buf, sizeof( buf ), va( "skill\\%s\\", Info_ValueForKey( userinfo, "skill" ) ) ); - if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) { - Q_strcat( buf, sizeof( buf ), va( "w\\%i\\", client->sess.wins ) ); - Q_strcat( buf, sizeof( buf ), va( "l\\%i\\", client->sess.losses ) ); - } - if ( level.gametype == GT_POWERDUEL ) - Q_strcat( buf, sizeof( buf ), va( "dt\\%i\\", client->sess.duelTeam ) ); - if ( level.gametype >= GT_TEAM ) { - // Q_strcat( buf, sizeof( buf ), va( "tt\\%d\\", teamTask ) ); - Q_strcat( buf, sizeof( buf ), va( "tl\\%d\\", teamLeader ) ); - } - if ( level.gametype == GT_SIEGE ) { - Q_strcat( buf, sizeof( buf ), va( "siegeclass\\%s\\", className ) ); - Q_strcat( buf, sizeof( buf ), va( "sdt\\%i\\", client->sess.siegeDesiredTeam ) ); - } - - trap->GetConfigstring( CS_PLAYERS+clientNum, oldClientinfo, sizeof( oldClientinfo ) ); - trap->SetConfigstring( CS_PLAYERS+clientNum, buf ); + Q_strcat(buf, sizeof(buf), va("n\\%s\\", client->pers.netname)); + Q_strcat(buf, sizeof(buf), va("t\\%i\\", client->sess.sessionTeam)); + Q_strcat(buf, sizeof(buf), va("model\\%s\\", model)); + if (gender == GENDER_FEMALE) + Q_strcat(buf, sizeof(buf), va("ds\\%c\\", 'f')); + else + Q_strcat(buf, sizeof(buf), va("ds\\%c\\", 'm')); + Q_strcat(buf, sizeof(buf), va("st\\%s\\", client->pers.saber1)); + Q_strcat(buf, sizeof(buf), va("st2\\%s\\", client->pers.saber2)); + Q_strcat(buf, sizeof(buf), va("c1\\%s\\", color1)); + Q_strcat(buf, sizeof(buf), va("c2\\%s\\", color2)); + Q_strcat(buf, sizeof(buf), va("hc\\%i\\", client->pers.maxHealth)); + if (ent->r.svFlags & SVF_BOT) + Q_strcat(buf, sizeof(buf), va("skill\\%s\\", Info_ValueForKey(userinfo, "skill"))); + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + Q_strcat(buf, sizeof(buf), va("w\\%i\\", client->sess.wins)); + Q_strcat(buf, sizeof(buf), va("l\\%i\\", client->sess.losses)); + } + if (level.gametype == GT_POWERDUEL) + Q_strcat(buf, sizeof(buf), va("dt\\%i\\", client->sess.duelTeam)); + if (level.gametype >= GT_TEAM) { + // Q_strcat( buf, sizeof( buf ), va( "tt\\%d\\", teamTask ) ); + Q_strcat(buf, sizeof(buf), va("tl\\%d\\", teamLeader)); + } + if (level.gametype == GT_SIEGE) { + Q_strcat(buf, sizeof(buf), va("siegeclass\\%s\\", className)); + Q_strcat(buf, sizeof(buf), va("sdt\\%i\\", client->sess.siegeDesiredTeam)); + } + + trap->GetConfigstring(CS_PLAYERS + clientNum, oldClientinfo, sizeof(oldClientinfo)); + trap->SetConfigstring(CS_PLAYERS + clientNum, buf); // only going to be true for allowable server-side custom skeleton cases - if ( modelChanged ) { + if (modelChanged) { // update the server g2 instance if appropriate - char *modelname = Info_ValueForKey( userinfo, "model" ); - SetupGameGhoul2Model( ent, modelname, NULL ); + char *modelname = Info_ValueForKey(userinfo, "model"); + SetupGameGhoul2Model(ent, modelname, NULL); - if ( ent->ghoul2 && ent->client ) - ent->client->renderInfo.lastG2 = NULL; //update the renderinfo bolts next update. + if (ent->ghoul2 && ent->client) + ent->client->renderInfo.lastG2 = NULL; // update the renderinfo bolts next update. client->torsoAnimExecute = client->legsAnimExecute = -1; client->torsoLastFlip = client->legsLastFlip = qfalse; } - if ( g_logClientInfo.integer ) { - if ( strcmp( oldClientinfo, buf ) ) - G_LogPrintf( "ClientUserinfoChanged: %i %s\n", clientNum, buf ); + if (g_logClientInfo.integer) { + if (strcmp(oldClientinfo, buf)) + G_LogPrintf("ClientUserinfoChanged: %i %s\n", clientNum, buf); else - G_LogPrintf( "ClientUserinfoChanged: %i \n", clientNum ); + G_LogPrintf("ClientUserinfoChanged: %i \n", clientNum); } return qtrue; } - /* =========== ClientConnect @@ -2396,12 +2179,11 @@ restarts. ============ */ -static qboolean CompareIPs( const char *ip1, const char *ip2 ) -{ - while ( 1 ) { - if ( *ip1 != *ip2 ) +static qboolean CompareIPs(const char *ip1, const char *ip2) { + while (1) { + if (*ip1 != *ip2) return qfalse; - if ( !*ip1 || *ip1 == ':' ) + if (!*ip1 || *ip1 == ':') break; ip1++; ip2++; @@ -2410,55 +2192,49 @@ static qboolean CompareIPs( const char *ip1, const char *ip2 ) return qtrue; } -char *ClientConnect( int clientNum, qboolean firstTime, qboolean isBot ) { - char *value = NULL; - gentity_t *ent = NULL, *te = NULL; - gclient_t *client; - char userinfo[MAX_INFO_STRING] = {0}, - tmpIP[NET_ADDRSTRMAXLEN] = {0}, - guid[33] = {0}; +char *ClientConnect(int clientNum, qboolean firstTime, qboolean isBot) { + char *value = NULL; + gentity_t *ent = NULL, *te = NULL; + gclient_t *client; + char userinfo[MAX_INFO_STRING] = {0}, tmpIP[NET_ADDRSTRMAXLEN] = {0}, guid[33] = {0}; - ent = &g_entities[ clientNum ]; + ent = &g_entities[clientNum]; ent->s.number = clientNum; ent->classname = "connecting"; - trap->GetUserinfo( clientNum, userinfo, sizeof( userinfo ) ); + trap->GetUserinfo(clientNum, userinfo, sizeof(userinfo)); - value = Info_ValueForKey( userinfo, "ja_guid" ); - if( value[0] ) - Q_strncpyz( guid, value, sizeof( guid ) ); - else if( isBot ) - Q_strncpyz( guid, "BOT", sizeof( guid ) ); + value = Info_ValueForKey(userinfo, "ja_guid"); + if (value[0]) + Q_strncpyz(guid, value, sizeof(guid)); + else if (isBot) + Q_strncpyz(guid, "BOT", sizeof(guid)); else - Q_strncpyz( guid, "NOGUID", sizeof( guid ) ); + Q_strncpyz(guid, "NOGUID", sizeof(guid)); // check to see if they are on the banned IP list - value = Info_ValueForKey (userinfo, "ip"); - Q_strncpyz( tmpIP, isBot ? "Bot" : value, sizeof( tmpIP ) ); - if ( G_FilterPacket( value ) ) { + value = Info_ValueForKey(userinfo, "ip"); + Q_strncpyz(tmpIP, isBot ? "Bot" : value, sizeof(tmpIP)); + if (G_FilterPacket(value)) { return "Banned."; } - if ( !isBot && g_needpass.integer ) { + if (!isBot && g_needpass.integer) { // check for a password - value = Info_ValueForKey (userinfo, "password"); - if ( g_password.string[0] && Q_stricmp( g_password.string, "none" ) && - strcmp( g_password.string, value) != 0) { + value = Info_ValueForKey(userinfo, "password"); + if (g_password.string[0] && Q_stricmp(g_password.string, "none") && strcmp(g_password.string, value) != 0) { static char sTemp[1024]; - Q_strncpyz(sTemp, G_GetStringEdString("MP_SVGAME","INVALID_ESCAPE_TO_MAIN"), sizeof (sTemp) ); - return sTemp;// return "Invalid password"; + Q_strncpyz(sTemp, G_GetStringEdString("MP_SVGAME", "INVALID_ESCAPE_TO_MAIN"), sizeof(sTemp)); + return sTemp; // return "Invalid password"; } } - if ( !isBot && firstTime ) - { - if ( g_antiFakePlayer.integer ) - {// patched, check for > g_maxConnPerIP connections from same IP - int count=0, i=0; - for ( i=0; i g_maxConnPerIP connections from same IP + int count = 0, i = 0; + for (i = 0; i < sv_maxclients.integer; i++) { +#if 0 if ( level.clients[i].pers.connected != CON_DISCONNECTED && i != clientNum ) { if ( CompareIPs( clientNum, i ) ) @@ -2470,125 +2246,114 @@ char *ClientConnect( int clientNum, qboolean firstTime, qboolean isBot ) { } } } - #else - if ( CompareIPs( tmpIP, level.clients[i].sess.IP ) ) - count++; - #endif +#else + if (CompareIPs(tmpIP, level.clients[i].sess.IP)) + count++; +#endif } - if ( count > g_maxConnPerIP.integer ) - { - // client->pers.connected = CON_DISCONNECTED; + if (count > g_maxConnPerIP.integer) { + // client->pers.connected = CON_DISCONNECTED; return "Too many connections from the same IP"; } } } - if ( ent->inuse ) - {// if a player reconnects quickly after a disconnect, the client disconnect may never be called, thus flag can get lost in the ether - G_LogPrintf( "Forcing disconnect on active client: %i\n", clientNum ); + if (ent->inuse) { // if a player reconnects quickly after a disconnect, the client disconnect may never be called, thus flag can get lost in the ether + G_LogPrintf("Forcing disconnect on active client: %i\n", clientNum); // so lets just fix up anything that should happen on a disconnect - ClientDisconnect( clientNum ); + ClientDisconnect(clientNum); } // they can connect - client = &level.clients[ clientNum ]; + client = &level.clients[clientNum]; ent->client = client; - //assign the pointer for bg entity access + // assign the pointer for bg entity access ent->playerState = &ent->client->ps; - memset( client, 0, sizeof(*client) ); + memset(client, 0, sizeof(*client)); - Q_strncpyz( client->pers.guid, guid, sizeof( client->pers.guid ) ); + Q_strncpyz(client->pers.guid, guid, sizeof(client->pers.guid)); client->pers.connected = CON_CONNECTING; client->pers.connectTime = level.time; // read or initialize the session data - if ( firstTime || level.newSession ) { - G_InitSessionData( client, userinfo, isBot ); + if (firstTime || level.newSession) { + G_InitSessionData(client, userinfo, isBot); } - G_ReadSessionData( client ); + G_ReadSessionData(client); if (level.gametype == GT_SIEGE && - (firstTime || level.newSession)) - { //if this is the first time then auto-assign a desired siege team and show briefing for that team - client->sess.siegeDesiredTeam = 0;//PickTeam(ent->s.number); + (firstTime || level.newSession)) { // if this is the first time then auto-assign a desired siege team and show briefing for that team + client->sess.siegeDesiredTeam = 0; // PickTeam(ent->s.number); /* trap->SendServerCommand(ent->s.number, va("sb %i", client->sess.siegeDesiredTeam)); */ - //don't just show it - they'll see it if they switch to a team on purpose. + // don't just show it - they'll see it if they switch to a team on purpose. } - - if (level.gametype == GT_SIEGE && client->sess.sessionTeam != TEAM_SPECTATOR) - { - if (firstTime || level.newSession) - { //start as spec + if (level.gametype == GT_SIEGE && client->sess.sessionTeam != TEAM_SPECTATOR) { + if (firstTime || level.newSession) { // start as spec client->sess.siegeDesiredTeam = client->sess.sessionTeam; client->sess.sessionTeam = TEAM_SPECTATOR; } - } - else if (level.gametype == GT_POWERDUEL && client->sess.sessionTeam != TEAM_SPECTATOR) - { + } else if (level.gametype == GT_POWERDUEL && client->sess.sessionTeam != TEAM_SPECTATOR) { client->sess.sessionTeam = TEAM_SPECTATOR; } - if( isBot ) { + if (isBot) { ent->r.svFlags |= SVF_BOT; ent->inuse = qtrue; - if( !G_BotConnect( clientNum, !firstTime ) ) { + if (!G_BotConnect(clientNum, !firstTime)) { return "BotConnectfailed"; } } // get and distribute relevent paramters - if ( !ClientUserinfoChanged( clientNum ) ) + if (!ClientUserinfoChanged(clientNum)) return "Failed userinfo validation"; - if ( !isBot && firstTime ) - { - if ( !tmpIP[0] ) - {//No IP sent when connecting, probably an unban hack attempt + if (!isBot && firstTime) { + if (!tmpIP[0]) { // No IP sent when connecting, probably an unban hack attempt client->pers.connected = CON_DISCONNECTED; - G_SecurityLogPrintf( "Client %i (%s) sent no IP when connecting.\n", clientNum, client->pers.netname ); + G_SecurityLogPrintf("Client %i (%s) sent no IP when connecting.\n", clientNum, client->pers.netname); return "Invalid userinfo detected"; } } - if ( firstTime ) - Q_strncpyz( client->sess.IP, tmpIP, sizeof( client->sess.IP ) ); + if (firstTime) + Q_strncpyz(client->sess.IP, tmpIP, sizeof(client->sess.IP)); - G_LogPrintf( "ClientConnect: %i [%s] (%s) \"%s^7\"\n", clientNum, tmpIP, guid, client->pers.netname ); + G_LogPrintf("ClientConnect: %i [%s] (%s) \"%s^7\"\n", clientNum, tmpIP, guid, client->pers.netname); // don't do the "xxx connected" messages if they were caried over from previous level - if ( firstTime ) { - trap->SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLCONNECT")) ); + if (firstTime) { + trap->SendServerCommand(-1, va("print \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLCONNECT"))); } - if ( level.gametype >= GT_TEAM && - client->sess.sessionTeam != TEAM_SPECTATOR ) { - BroadcastTeamChange( client, -1 ); + if (level.gametype >= GT_TEAM && client->sess.sessionTeam != TEAM_SPECTATOR) { + BroadcastTeamChange(client, -1); } // count current clients and rank for scoreboard CalculateRanks(); - te = G_TempEntity( vec3_origin, EV_CLIENTJOIN ); + te = G_TempEntity(vec3_origin, EV_CLIENTJOIN); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = clientNum; // for statistics -// client->areabits = areabits; -// if ( !client->areabits ) -// client->areabits = G_Alloc( (trap->AAS_PointReachabilityAreaIndex( NULL ) + 7) / 8 ); + // client->areabits = areabits; + // if ( !client->areabits ) + // client->areabits = G_Alloc( (trap->AAS_PointReachabilityAreaIndex( NULL ) + 7) / 8 ); return NULL; } -void G_WriteClientSessionData( gclient_t *client ); +void G_WriteClientSessionData(gclient_t *client); -void WP_SetSaber( int entNum, saberInfo_t *sabers, int saberNum, const char *saberName ); +void WP_SetSaber(int entNum, saberInfo_t *sabers, int saberNum, const char *saberName); /* =========== @@ -2599,55 +2364,49 @@ to be placed into the level. This will happen every level load, and on transition between teams, but doesn't happen on respawns ============ */ -extern qboolean gSiegeRoundBegun; -extern qboolean gSiegeRoundEnded; -extern qboolean g_dontPenalizeTeam; //g_cmds.c +extern qboolean gSiegeRoundBegun; +extern qboolean gSiegeRoundEnded; +extern qboolean g_dontPenalizeTeam; // g_cmds.c void SetTeamQuick(gentity_t *ent, int team, qboolean doBegin); -void ClientBegin( int clientNum, qboolean allowTeamReset ) { - gentity_t *ent; - gclient_t *client; - int flags, i; - char userinfo[MAX_INFO_VALUE], *modelname; - int spawnCount; +void ClientBegin(int clientNum, qboolean allowTeamReset) { + gentity_t *ent; + gclient_t *client; + int flags, i; + char userinfo[MAX_INFO_VALUE], *modelname; + int spawnCount; ent = g_entities + clientNum; - if ((ent->r.svFlags & SVF_BOT) && level.gametype >= GT_TEAM) - { - if (allowTeamReset) - { + if ((ent->r.svFlags & SVF_BOT) && level.gametype >= GT_TEAM) { + if (allowTeamReset) { const char *team = "Red"; int preSess; - //SetTeam(ent, ""); + // SetTeam(ent, ""); ent->client->sess.sessionTeam = PickTeam(-1); trap->GetUserinfo(clientNum, userinfo, MAX_INFO_STRING); - if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { ent->client->sess.sessionTeam = TEAM_RED; } - if (ent->client->sess.sessionTeam == TEAM_RED) - { + if (ent->client->sess.sessionTeam == TEAM_RED) { team = "Red"; - } - else - { + } else { team = "Blue"; } - Info_SetValueForKey( userinfo, "team", team ); + Info_SetValueForKey(userinfo, "team", team); - trap->SetUserinfo( clientNum, userinfo ); + trap->SetUserinfo(clientNum, userinfo); - ent->client->ps.persistant[ PERS_TEAM ] = ent->client->sess.sessionTeam; + ent->client->ps.persistant[PERS_TEAM] = ent->client->sess.sessionTeam; preSess = ent->client->sess.sessionTeam; - G_ReadSessionData( ent->client ); + G_ReadSessionData(ent->client); ent->client->sess.sessionTeam = preSess; G_WriteClientSessionData(ent->client); - if ( !ClientUserinfoChanged( clientNum ) ) + if (!ClientUserinfoChanged(clientNum)) return; ClientBegin(clientNum, qfalse); return; @@ -2656,15 +2415,15 @@ void ClientBegin( int clientNum, qboolean allowTeamReset ) { client = level.clients + clientNum; - if ( ent->r.linked ) { - trap->UnlinkEntity( (sharedEntity_t *)ent ); + if (ent->r.linked) { + trap->UnlinkEntity((sharedEntity_t *)ent); } - G_InitGentity( ent ); + G_InitGentity(ent); ent->touch = 0; ent->pain = 0; ent->client = client; - //assign the pointer for bg entity access + // assign the pointer for bg entity access ent->playerState = &ent->client->ps; client->pers.connected = CON_CONNECTED; @@ -2681,10 +2440,8 @@ void ClientBegin( int clientNum, qboolean allowTeamReset ) { i = 0; - while (i < NUM_FORCE_POWERS) - { - if (ent->client->ps.fd.forcePowersActive & (1 << i)) - { + while (i < NUM_FORCE_POWERS) { + if (ent->client->ps.fd.forcePowersActive & (1 << i)) { WP_ForcePowerStop(ent, i); } i++; @@ -2692,53 +2449,51 @@ void ClientBegin( int clientNum, qboolean allowTeamReset ) { i = TRACK_CHANNEL_1; - while (i < NUM_TRACK_CHANNELS) - { - if (ent->client->ps.fd.killSoundEntIndex[i-50] && ent->client->ps.fd.killSoundEntIndex[i-50] < MAX_GENTITIES && ent->client->ps.fd.killSoundEntIndex[i-50] > 0) - { - G_MuteSound(ent->client->ps.fd.killSoundEntIndex[i-50], CHAN_VOICE); + while (i < NUM_TRACK_CHANNELS) { + if (ent->client->ps.fd.killSoundEntIndex[i - 50] && ent->client->ps.fd.killSoundEntIndex[i - 50] < MAX_GENTITIES && + ent->client->ps.fd.killSoundEntIndex[i - 50] > 0) { + G_MuteSound(ent->client->ps.fd.killSoundEntIndex[i - 50], CHAN_VOICE); } i++; } i = 0; - memset( &client->ps, 0, sizeof( client->ps ) ); + memset(&client->ps, 0, sizeof(client->ps)); client->ps.eFlags = flags; client->ps.persistant[PERS_SPAWN_COUNT] = spawnCount; client->ps.hasDetPackPlanted = qfalse; - //first-time force power initialization - WP_InitForcePowers( ent ); + // first-time force power initialization + WP_InitForcePowers(ent); - //init saber ent - WP_SaberInitBladeData( ent ); + // init saber ent + WP_SaberInitBladeData(ent); // First time model setup for that player. - trap->GetUserinfo( clientNum, userinfo, sizeof(userinfo) ); - modelname = Info_ValueForKey (userinfo, "model"); + trap->GetUserinfo(clientNum, userinfo, sizeof(userinfo)); + modelname = Info_ValueForKey(userinfo, "model"); SetupGameGhoul2Model(ent, modelname, NULL); - if ( ent->ghoul2 && ent->client ) - ent->client->renderInfo.lastG2 = NULL; //update the renderinfo bolts next update. + if (ent->ghoul2 && ent->client) + ent->client->renderInfo.lastG2 = NULL; // update the renderinfo bolts next update. - if ( level.gametype == GT_POWERDUEL && client->sess.sessionTeam != TEAM_SPECTATOR && client->sess.duelTeam == DUELTEAM_FREE ) - SetTeam( ent, "s" ); - else - { - if ( level.gametype == GT_SIEGE && (!gSiegeRoundBegun || gSiegeRoundEnded) ) - SetTeamQuick( ent, TEAM_SPECTATOR, qfalse ); + if (level.gametype == GT_POWERDUEL && client->sess.sessionTeam != TEAM_SPECTATOR && client->sess.duelTeam == DUELTEAM_FREE) + SetTeam(ent, "s"); + else { + if (level.gametype == GT_SIEGE && (!gSiegeRoundBegun || gSiegeRoundEnded)) + SetTeamQuick(ent, TEAM_SPECTATOR, qfalse); // locate ent at a spawn point - ClientSpawn( ent ); + ClientSpawn(ent); } - if ( client->sess.sessionTeam != TEAM_SPECTATOR ) { - if ( level.gametype != GT_DUEL || level.gametype == GT_POWERDUEL ) { - trap->SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLENTER")) ); + if (client->sess.sessionTeam != TEAM_SPECTATOR) { + if (level.gametype != GT_DUEL || level.gametype == GT_POWERDUEL) { + trap->SendServerCommand(-1, va("print \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLENTER"))); } } - G_LogPrintf( "ClientBegin: %i\n", clientNum ); + G_LogPrintf("ClientBegin: %i\n", clientNum); // count current clients and rank for scoreboard CalculateRanks(); @@ -2746,16 +2501,12 @@ void ClientBegin( int clientNum, qboolean allowTeamReset ) { G_ClearClientLog(clientNum); } -static qboolean AllForceDisabled(int force) -{ +static qboolean AllForceDisabled(int force) { int i; - if (force) - { - for (i=0;iclient); - if (ent->s.NPC_class == CLASS_VEHICLE || ent->localAnimIndex > 1) - { //no broken limbs for vehicles and non-humanoids + if (ent->s.NPC_class == CLASS_VEHICLE || ent->localAnimIndex > 1) { // no broken limbs for vehicles and non-humanoids return; } - if (!arm) - { //repair him + if (!arm) { // repair him ent->client->ps.brokenLimbs = 0; return; } - if (ent->client->ps.fd.saberAnimLevel == SS_STAFF) - { //I'm too lazy to deal with this as well for now. + if (ent->client->ps.fd.saberAnimLevel == SS_STAFF) { // I'm too lazy to deal with this as well for now. return; } - if (arm == BROKENLIMB_LARM) - { - if (ent->client->saber[1].model[0] && - ent->client->ps.weapon == WP_SABER && - !ent->client->ps.saberHolstered && - ent->client->saber[1].soundOff) - { //the left arm shuts off its saber upon being broken + if (arm == BROKENLIMB_LARM) { + if (ent->client->saber[1].model[0] && ent->client->ps.weapon == WP_SABER && !ent->client->ps.saberHolstered && + ent->client->saber[1].soundOff) { // the left arm shuts off its saber upon being broken G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOff); } } - ent->client->ps.brokenLimbs = 0; //make sure it's cleared out - ent->client->ps.brokenLimbs |= (1 << arm); //this arm is now marked as broken + ent->client->ps.brokenLimbs = 0; // make sure it's cleared out + ent->client->ps.brokenLimbs |= (1 << arm); // this arm is now marked as broken - //Do a pain anim based on the side. Since getting your arm broken does tend to hurt. - if (arm == BROKENLIMB_LARM) - { + // Do a pain anim based on the side. Since getting your arm broken does tend to hurt. + if (arm == BROKENLIMB_LARM) { anim = BOTH_PAIN2; - } - else if (arm == BROKENLIMB_RARM) - { + } else if (arm == BROKENLIMB_RARM) { anim = BOTH_PAIN3; } - if (anim == -1) - { + if (anim == -1) { return; } - G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); - //This could be combined into a single event. But I guess limbs don't break often enough to - //worry about it. - G_EntitySound( ent, CHAN_VOICE, G_SoundIndex("*pain25.wav") ); - //FIXME: A nice bone snapping sound instead if possible - G_Sound(ent, CHAN_AUTO, G_SoundIndex( va("sound/player/bodyfall_human%i.wav", Q_irand(1, 3)) )); + // This could be combined into a single event. But I guess limbs don't break often enough to + // worry about it. + G_EntitySound(ent, CHAN_VOICE, G_SoundIndex("*pain25.wav")); + // FIXME: A nice bone snapping sound instead if possible + G_Sound(ent, CHAN_AUTO, G_SoundIndex(va("sound/player/bodyfall_human%i.wav", Q_irand(1, 3)))); } -//Update the ghoul2 instance anims based on the playerstate values -qboolean BG_SaberStanceAnim( int anim ); -qboolean PM_RunningAnim( int anim ); -void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) -{ +// Update the ghoul2 instance anims based on the playerstate values +qboolean BG_SaberStanceAnim(int anim); +qboolean PM_RunningAnim(int anim); +void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) { static int f; static int torsoAnim; static int legsAnim; @@ -2843,47 +2581,41 @@ void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) torsoAnim = (self->client->ps.torsoAnim); legsAnim = (self->client->ps.legsAnim); - if (self->client->ps.saberLockFrame) - { - trap->G2API_SetBoneAnim(self->ghoul2, 0, "model_root", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); - trap->G2API_SetBoneAnim(self->ghoul2, 0, "lower_lumbar", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); - trap->G2API_SetBoneAnim(self->ghoul2, 0, "Motion", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame+1, BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); + if (self->client->ps.saberLockFrame) { + trap->G2API_SetBoneAnim(self->ghoul2, 0, "model_root", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame + 1, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); + trap->G2API_SetBoneAnim(self->ghoul2, 0, "lower_lumbar", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame + 1, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); + trap->G2API_SetBoneAnim(self->ghoul2, 0, "Motion", self->client->ps.saberLockFrame, self->client->ps.saberLockFrame + 1, + BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, animSpeedScale, level.time, -1, 150); return; } - if (self->localAnimIndex > 1 && - bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame == 0 && - bgAllAnims[self->localAnimIndex].anims[legsAnim].numFrames == 0) - { //We'll allow this for non-humanoids. + if (self->localAnimIndex > 1 && bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame == 0 && + bgAllAnims[self->localAnimIndex].anims[legsAnim].numFrames == 0) { // We'll allow this for non-humanoids. goto tryTorso; } - if (self->client->legsAnimExecute != legsAnim || self->client->legsLastFlip != self->client->ps.legsFlip) - { + if (self->client->legsAnimExecute != legsAnim || self->client->legsLastFlip != self->client->ps.legsFlip) { animSpeed = 50.0f / bgAllAnims[self->localAnimIndex].anims[legsAnim].frameLerp; lAnimSpeedScale = (animSpeed *= animSpeedScale); - if (bgAllAnims[self->localAnimIndex].anims[legsAnim].loopFrames != -1) - { + if (bgAllAnims[self->localAnimIndex].anims[legsAnim].loopFrames != -1) { aFlags = BONE_ANIM_OVERRIDE_LOOP; - } - else - { + } else { aFlags = BONE_ANIM_OVERRIDE_FREEZE; } - if (animSpeed < 0) - { + if (animSpeed < 0) { lastFrame = bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame; firstFrame = bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame + bgAllAnims[self->localAnimIndex].anims[legsAnim].numFrames; - } - else - { + } else { firstFrame = bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame; lastFrame = bgAllAnims[self->localAnimIndex].anims[legsAnim].firstFrame + bgAllAnims[self->localAnimIndex].anims[legsAnim].numFrames; } - aFlags |= BONE_ANIM_BLEND; //since client defaults to blend. Not sure if this will make much difference if any on server position, but it's here just for the sake of matching them. + aFlags |= BONE_ANIM_BLEND; // since client defaults to blend. Not sure if this will make much difference if any on server position, but it's here just + // for the sake of matching them. trap->G2API_SetBoneAnim(self->ghoul2, 0, "model_root", firstFrame, lastFrame, aFlags, lAnimSpeedScale, level.time, -1, 150); self->client->legsAnimExecute = legsAnim; @@ -2891,22 +2623,16 @@ void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) } tryTorso: - if (self->localAnimIndex > 1 && - bgAllAnims[self->localAnimIndex].anims[torsoAnim].firstFrame == 0 && + if (self->localAnimIndex > 1 && bgAllAnims[self->localAnimIndex].anims[torsoAnim].firstFrame == 0 && bgAllAnims[self->localAnimIndex].anims[torsoAnim].numFrames == 0) - { //If this fails as well just return. + { // If this fails as well just return. return; - } - else if (self->s.number >= MAX_CLIENTS && - self->s.NPC_class == CLASS_VEHICLE) - { //we only want to set the root bone for vehicles + } else if (self->s.number >= MAX_CLIENTS && self->s.NPC_class == CLASS_VEHICLE) { // we only want to set the root bone for vehicles return; } - if ((self->client->torsoAnimExecute != torsoAnim || self->client->torsoLastFlip != self->client->ps.torsoFlip) && - !self->noLumbar) - { + if ((self->client->torsoAnimExecute != torsoAnim || self->client->torsoLastFlip != self->client->ps.torsoFlip) && !self->noLumbar) { aFlags = 0; animSpeed = 0; @@ -2917,29 +2643,25 @@ void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) animSpeed = 50.0f / bgAllAnims[self->localAnimIndex].anims[f].frameLerp; lAnimSpeedScale = (animSpeed *= animSpeedScale); - if (bgAllAnims[self->localAnimIndex].anims[f].loopFrames != -1) - { + if (bgAllAnims[self->localAnimIndex].anims[f].loopFrames != -1) { aFlags = BONE_ANIM_OVERRIDE_LOOP; - } - else - { + } else { aFlags = BONE_ANIM_OVERRIDE_FREEZE; } - aFlags |= BONE_ANIM_BLEND; //since client defaults to blend. Not sure if this will make much difference if any on client position, but it's here just for the sake of matching them. + aFlags |= BONE_ANIM_BLEND; // since client defaults to blend. Not sure if this will make much difference if any on client position, but it's here just + // for the sake of matching them. - if (animSpeed < 0) - { + if (animSpeed < 0) { lastFrame = bgAllAnims[self->localAnimIndex].anims[f].firstFrame; firstFrame = bgAllAnims[self->localAnimIndex].anims[f].firstFrame + bgAllAnims[self->localAnimIndex].anims[f].numFrames; - } - else - { + } else { firstFrame = bgAllAnims[self->localAnimIndex].anims[f].firstFrame; lastFrame = bgAllAnims[self->localAnimIndex].anims[f].firstFrame + bgAllAnims[self->localAnimIndex].anims[f].numFrames; } - trap->G2API_SetBoneAnim(self->ghoul2, 0, "lower_lumbar", firstFrame, lastFrame, aFlags, lAnimSpeedScale, level.time, /*firstFrame why was it this before?*/-1, 150); + trap->G2API_SetBoneAnim(self->ghoul2, 0, "lower_lumbar", firstFrame, lastFrame, aFlags, lAnimSpeedScale, level.time, + /*firstFrame why was it this before?*/ -1, 150); self->client->torsoAnimExecute = torsoAnim; self->client->torsoLastFlip = self->client->ps.torsoFlip; @@ -2947,13 +2669,11 @@ void G_UpdateClientAnims(gentity_t *self, float animSpeedScale) setTorso = qtrue; } - if (setTorso && - self->localAnimIndex <= 1) - { //only set the motion bone for humanoids. + if (setTorso && self->localAnimIndex <= 1) { // only set the motion bone for humanoids. trap->G2API_SetBoneAnim(self->ghoul2, 0, "Motion", firstFrame, lastFrame, aFlags, lAnimSpeedScale, level.time, -1, 150); } -#if 0 //disabled for now +#if 0 // disabled for now if (self->client->ps.brokenLimbs != self->client->brokenLimbs || setTorso) { @@ -3086,150 +2806,121 @@ after the first ClientBegin, and after each respawn Initializes all non-persistant parts of playerState ============ */ -extern qboolean WP_HasForcePowers( const playerState_t *ps ); +extern qboolean WP_HasForcePowers(const playerState_t *ps); void ClientSpawn(gentity_t *ent) { - int i = 0, index = 0, saveSaberNum = ENTITYNUM_NONE, wDisable = 0, savedSiegeIndex = 0, maxHealth = 100; - vec3_t spawn_origin, spawn_angles; - gentity_t *spawnPoint = NULL, *tent = NULL; - gclient_t *client = NULL; - clientPersistant_t saved; - clientSession_t savedSess; - forcedata_t savedForce; - saberInfo_t saberSaved[MAX_SABERS]; - int persistant[MAX_PERSISTANT] = {0}; - int flags, gameFlags, savedPing, accuracy_hits, accuracy_shots, eventSequence; - void *g2WeaponPtrs[MAX_SABERS]; - char userinfo[MAX_INFO_STRING] = {0}, *key = NULL, *value = NULL, *saber = NULL; - qboolean changedSaber = qfalse, inSiegeWithClass = qfalse; + int i = 0, index = 0, saveSaberNum = ENTITYNUM_NONE, wDisable = 0, savedSiegeIndex = 0, maxHealth = 100; + vec3_t spawn_origin, spawn_angles; + gentity_t *spawnPoint = NULL, *tent = NULL; + gclient_t *client = NULL; + clientPersistant_t saved; + clientSession_t savedSess; + forcedata_t savedForce; + saberInfo_t saberSaved[MAX_SABERS]; + int persistant[MAX_PERSISTANT] = {0}; + int flags, gameFlags, savedPing, accuracy_hits, accuracy_shots, eventSequence; + void *g2WeaponPtrs[MAX_SABERS]; + char userinfo[MAX_INFO_STRING] = {0}, *key = NULL, *value = NULL, *saber = NULL; + qboolean changedSaber = qfalse, inSiegeWithClass = qfalse; index = ent - g_entities; client = ent->client; - //first we want the userinfo so we can see if we should update this client's saber -rww - trap->GetUserinfo( index, userinfo, sizeof( userinfo ) ); + // first we want the userinfo so we can see if we should update this client's saber -rww + trap->GetUserinfo(index, userinfo, sizeof(userinfo)); - for ( i=0; iclient->pers.saber2 : ent->client->pers.saber1; - value = Info_ValueForKey( userinfo, va( "saber%i", i+1 ) ); - if ( saber && value && - (Q_stricmp( value, saber ) || !saber[0] || !ent->client->saber[0].model[0]) ) - { //doesn't match up (or our saber is BS), we want to try setting it - if ( G_SetSaber( ent, i, value, qfalse ) ) + for (i = 0; i < MAX_SABERS; i++) { + saber = (i & 1) ? ent->client->pers.saber2 : ent->client->pers.saber1; + value = Info_ValueForKey(userinfo, va("saber%i", i + 1)); + if (saber && value && + (Q_stricmp(value, saber) || !saber[0] || !ent->client->saber[0].model[0])) { // doesn't match up (or our saber is BS), we want to try setting it + if (G_SetSaber(ent, i, value, qfalse)) changedSaber = qtrue; - //Well, we still want to say they changed then (it means this is siege and we have some overrides) - else if ( !saber[0] || !ent->client->saber[0].model[0] ) + // Well, we still want to say they changed then (it means this is siege and we have some overrides) + else if (!saber[0] || !ent->client->saber[0].model[0]) changedSaber = qtrue; } } - if ( changedSaber ) - { //make sure our new info is sent out to all the other clients, and give us a valid stance - if ( !ClientUserinfoChanged( ent->s.number ) ) + if (changedSaber) { // make sure our new info is sent out to all the other clients, and give us a valid stance + if (!ClientUserinfoChanged(ent->s.number)) return; - //make sure the saber models are updated - G_SaberModelSetup( ent ); - - for ( i=0; iclient->pers.saber2 : ent->client->pers.saber1; - key = va( "saber%d", i+1 ); - value = Info_ValueForKey( userinfo, key ); - if ( Q_stricmp( value, saber ) ) - {// they don't match up, force the user info - Info_SetValueForKey( userinfo, key, saber ); - trap->SetUserinfo( ent->s.number, userinfo ); + // make sure the saber models are updated + G_SaberModelSetup(ent); + + for (i = 0; i < MAX_SABERS; i++) { + saber = (i & 1) ? ent->client->pers.saber2 : ent->client->pers.saber1; + key = va("saber%d", i + 1); + value = Info_ValueForKey(userinfo, key); + if (Q_stricmp(value, saber)) { // they don't match up, force the user info + Info_SetValueForKey(userinfo, key, saber); + trap->SetUserinfo(ent->s.number, userinfo); } } - if ( ent->client->saber[0].model[0] && ent->client->saber[1].model[0] ) - { //dual + if (ent->client->saber[0].model[0] && ent->client->saber[1].model[0]) { // dual ent->client->ps.fd.saberAnimLevelBase = ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = SS_DUAL; - } - else if ( (ent->client->saber[0].saberFlags&SFL_TWO_HANDED) ) - { //staff + } else if ((ent->client->saber[0].saberFlags & SFL_TWO_HANDED)) { // staff ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = SS_STAFF; - } - else - { - ent->client->sess.saberLevel = Com_Clampi( SS_FAST, SS_STRONG, ent->client->sess.saberLevel ); + } else { + ent->client->sess.saberLevel = Com_Clampi(SS_FAST, SS_STRONG, ent->client->sess.saberLevel); ent->client->ps.fd.saberAnimLevelBase = ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = ent->client->sess.saberLevel; // limit our saber style to our force points allocated to saber offense - if ( level.gametype != GT_SIEGE && ent->client->ps.fd.saberAnimLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] ) - ent->client->ps.fd.saberAnimLevelBase = ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = ent->client->sess.saberLevel = ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]; - } - if ( level.gametype != GT_SIEGE ) - {// let's just make sure the styles we chose are cool - if ( !WP_SaberStyleValidForSaber( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, ent->client->ps.fd.saberAnimLevel ) ) - { - WP_UseFirstValidSaberStyle( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &ent->client->ps.fd.saberAnimLevel ); + if (level.gametype != GT_SIEGE && ent->client->ps.fd.saberAnimLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) + ent->client->ps.fd.saberAnimLevelBase = ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = + ent->client->sess.saberLevel = ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]; + } + if (level.gametype != GT_SIEGE) { // let's just make sure the styles we chose are cool + if (!WP_SaberStyleValidForSaber(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, + ent->client->ps.fd.saberAnimLevel)) { + WP_UseFirstValidSaberStyle(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &ent->client->ps.fd.saberAnimLevel); ent->client->ps.fd.saberAnimLevelBase = ent->client->saberCycleQueue = ent->client->ps.fd.saberAnimLevel; } } } - if (client->ps.fd.forceDoInit) - { //force a reread of force powers - WP_InitForcePowers( ent ); + if (client->ps.fd.forceDoInit) { // force a reread of force powers + WP_InitForcePowers(ent); client->ps.fd.forceDoInit = 0; } if (ent->client->ps.fd.saberAnimLevel != SS_STAFF && ent->client->ps.fd.saberAnimLevel != SS_DUAL && - ent->client->ps.fd.saberAnimLevel == ent->client->ps.fd.saberDrawAnimLevel && - ent->client->ps.fd.saberAnimLevel == ent->client->sess.saberLevel) - { - ent->client->sess.saberLevel = Com_Clampi( SS_FAST, SS_STRONG, ent->client->sess.saberLevel ); + ent->client->ps.fd.saberAnimLevel == ent->client->ps.fd.saberDrawAnimLevel && ent->client->ps.fd.saberAnimLevel == ent->client->sess.saberLevel) { + ent->client->sess.saberLevel = Com_Clampi(SS_FAST, SS_STRONG, ent->client->sess.saberLevel); ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = ent->client->sess.saberLevel; // limit our saber style to our force points allocated to saber offense - if ( level.gametype != GT_SIEGE && ent->client->ps.fd.saberAnimLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] ) - ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = ent->client->sess.saberLevel = ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]; + if (level.gametype != GT_SIEGE && ent->client->ps.fd.saberAnimLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) + ent->client->ps.fd.saberAnimLevel = ent->client->ps.fd.saberDrawAnimLevel = ent->client->sess.saberLevel = + ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]; } // find a spawn point // do it before setting health back up, so farthest // ranging doesn't count this client - if ( client->sess.sessionTeam == TEAM_SPECTATOR ) { - spawnPoint = SelectSpectatorSpawnPoint ( - spawn_origin, spawn_angles); + if (client->sess.sessionTeam == TEAM_SPECTATOR) { + spawnPoint = SelectSpectatorSpawnPoint(spawn_origin, spawn_angles); } else if (level.gametype == GT_CTF || level.gametype == GT_CTY) { // all base oriented team games use the CTF spawn points - spawnPoint = SelectCTFSpawnPoint ( - client->sess.sessionTeam, - client->pers.teamState.state, - spawn_origin, spawn_angles, !!(ent->r.svFlags & SVF_BOT)); - } - else if (level.gametype == GT_SIEGE) - { - spawnPoint = SelectSiegeSpawnPoint ( - client->siegeClass, - client->sess.sessionTeam, - client->pers.teamState.state, - spawn_origin, spawn_angles, !!(ent->r.svFlags & SVF_BOT)); - } - else { - if (level.gametype == GT_POWERDUEL) - { + spawnPoint = SelectCTFSpawnPoint(client->sess.sessionTeam, client->pers.teamState.state, spawn_origin, spawn_angles, !!(ent->r.svFlags & SVF_BOT)); + } else if (level.gametype == GT_SIEGE) { + spawnPoint = SelectSiegeSpawnPoint(client->siegeClass, client->sess.sessionTeam, client->pers.teamState.state, spawn_origin, spawn_angles, + !!(ent->r.svFlags & SVF_BOT)); + } else { + if (level.gametype == GT_POWERDUEL) { spawnPoint = SelectDuelSpawnPoint(client->sess.duelTeam, client->ps.origin, spawn_origin, spawn_angles, !!(ent->r.svFlags & SVF_BOT)); - } - else if (level.gametype == GT_DUEL) - { // duel + } else if (level.gametype == GT_DUEL) { // duel spawnPoint = SelectDuelSpawnPoint(DUELTEAM_SINGLE, client->ps.origin, spawn_origin, spawn_angles, !!(ent->r.svFlags & SVF_BOT)); - } - else - { + } else { // the first spawn should be at a good looking spot - if ( !client->pers.initialSpawn && client->pers.localClient ) { + if (!client->pers.initialSpawn && client->pers.localClient) { client->pers.initialSpawn = qtrue; - spawnPoint = SelectInitialSpawnPoint( spawn_origin, spawn_angles, client->sess.sessionTeam, !!(ent->r.svFlags & SVF_BOT) ); + spawnPoint = SelectInitialSpawnPoint(spawn_origin, spawn_angles, client->sess.sessionTeam, !!(ent->r.svFlags & SVF_BOT)); } else { // don't spawn near existing origin if possible - spawnPoint = SelectSpawnPoint ( - client->ps.origin, - spawn_origin, spawn_angles, client->sess.sessionTeam, !!(ent->r.svFlags & SVF_BOT) ); + spawnPoint = SelectSpawnPoint(client->ps.origin, spawn_origin, spawn_angles, client->sess.sessionTeam, !!(ent->r.svFlags & SVF_BOT)); } } } @@ -3239,17 +2930,17 @@ void ClientSpawn(gentity_t *ent) { // and never clear the voted flag flags = ent->client->ps.eFlags & (EF_TELEPORT_BIT); flags ^= EF_TELEPORT_BIT; - gameFlags = ent->client->mGameFlags & ( PSG_VOTED | PSG_TEAMVOTED); + gameFlags = ent->client->mGameFlags & (PSG_VOTED | PSG_TEAMVOTED); // clear everything but the persistant data saved = client->pers; savedSess = client->sess; savedPing = client->ps.ping; -// savedAreaBits = client->areabits; + // savedAreaBits = client->areabits; accuracy_hits = client->accuracy_hits; accuracy_shots = client->accuracy_shots; - for ( i=0; ips.persistant[i]; eventSequence = client->ps.eventSequence; @@ -3260,51 +2951,48 @@ void ClientSpawn(gentity_t *ent) { savedSiegeIndex = client->siegeClass; - for ( i=0; isaber[i]; g2WeaponPtrs[i] = client->weaponGhoul2[i]; } - for ( i=0; ilocationDamage[i] = 0; - memset( client, 0, sizeof( *client ) ); // bk FIXME: Com_Memset? + memset(client, 0, sizeof(*client)); // bk FIXME: Com_Memset? client->bodyGrabIndex = ENTITYNUM_NONE; - //Get the skin RGB based on his userinfo - client->ps.customRGBA[0] = (value=Info_ValueForKey( userinfo, "char_color_red" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; - client->ps.customRGBA[1] = (value=Info_ValueForKey( userinfo, "char_color_green" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; - client->ps.customRGBA[2] = (value=Info_ValueForKey( userinfo, "char_color_blue" )) ? Com_Clampi( 0, 255, atoi( value ) ) : 255; + // Get the skin RGB based on his userinfo + client->ps.customRGBA[0] = (value = Info_ValueForKey(userinfo, "char_color_red")) ? Com_Clampi(0, 255, atoi(value)) : 255; + client->ps.customRGBA[1] = (value = Info_ValueForKey(userinfo, "char_color_green")) ? Com_Clampi(0, 255, atoi(value)) : 255; + client->ps.customRGBA[2] = (value = Info_ValueForKey(userinfo, "char_color_blue")) ? Com_Clampi(0, 255, atoi(value)) : 255; - //Prevent skins being too dark - if ( g_charRestrictRGB.integer && ((client->ps.customRGBA[0]+client->ps.customRGBA[1]+client->ps.customRGBA[2]) < 100) ) + // Prevent skins being too dark + if (g_charRestrictRGB.integer && ((client->ps.customRGBA[0] + client->ps.customRGBA[1] + client->ps.customRGBA[2]) < 100)) client->ps.customRGBA[0] = client->ps.customRGBA[1] = client->ps.customRGBA[2] = 255; - client->ps.customRGBA[3]=255; + client->ps.customRGBA[3] = 255; - if ( level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer ) - { + if (level.gametype >= GT_TEAM && level.gametype != GT_SIEGE && !g_jediVmerc.integer) { char skin[MAX_QPATH] = {0}, model[MAX_QPATH] = {0}; vec3_t colorOverride = {0.0f}; - VectorClear( colorOverride ); - Q_strncpyz( model, Info_ValueForKey( userinfo, "model" ), sizeof( model ) ); + VectorClear(colorOverride); + Q_strncpyz(model, Info_ValueForKey(userinfo, "model"), sizeof(model)); - BG_ValidateSkinForTeam( model, skin, savedSess.sessionTeam, colorOverride ); - if ( colorOverride[0] != 0.0f || colorOverride[1] != 0.0f || colorOverride[2] != 0.0f ) - VectorScaleM( colorOverride, 255.0f, client->ps.customRGBA ); + BG_ValidateSkinForTeam(model, skin, savedSess.sessionTeam, colorOverride); + if (colorOverride[0] != 0.0f || colorOverride[1] != 0.0f || colorOverride[2] != 0.0f) + VectorScaleM(colorOverride, 255.0f, client->ps.customRGBA); } client->siegeClass = savedSiegeIndex; - for ( i=0; isaber[i] = saberSaved[i]; client->weaponGhoul2[i] = g2WeaponPtrs[i]; } - //or the saber ent num + // or the saber ent num client->ps.saberEntityNum = saveSaberNum; client->saberStoredIndex = saveSaberNum; @@ -3312,19 +3000,19 @@ void ClientSpawn(gentity_t *ent) { client->ps.duelIndex = ENTITYNUM_NONE; - //spawn with 100 + // spawn with 100 client->ps.jetpackFuel = 100; client->ps.cloakFuel = 100; client->pers = saved; client->sess = savedSess; client->ps.ping = savedPing; -// client->areabits = savedAreaBits; + // client->areabits = savedAreaBits; client->accuracy_hits = accuracy_hits; client->accuracy_shots = accuracy_shots; client->lastkilled_client = -1; - for ( i=0; ips.persistant[i] = persistant[i]; client->ps.eventSequence = eventSequence; @@ -3335,22 +3023,18 @@ void ClientSpawn(gentity_t *ent) { client->airOutTime = level.time + 12000; // set max health - if (level.gametype == GT_SIEGE && client->siegeClass != -1) - { + if (level.gametype == GT_SIEGE && client->siegeClass != -1) { siegeClass_t *scl = &bgSiegeClasses[client->siegeClass]; maxHealth = 100; - if (scl->maxhealth) - { + if (scl->maxhealth) { maxHealth = scl->maxhealth; } + } else { + maxHealth = Com_Clampi(1, 100, atoi(Info_ValueForKey(userinfo, "handicap"))); } - else - { - maxHealth = Com_Clampi( 1, 100, atoi( Info_ValueForKey( userinfo, "handicap" ) ) ); - } - client->pers.maxHealth = maxHealth;//atoi( Info_ValueForKey( userinfo, "handicap" ) ); - if ( client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth ) { + client->pers.maxHealth = maxHealth; // atoi( Info_ValueForKey( userinfo, "handicap" ) ); + if (client->pers.maxHealth < 1 || client->pers.maxHealth > maxHealth) { client->pers.maxHealth = 100; } // clear entity values @@ -3371,151 +3055,108 @@ void ClientSpawn(gentity_t *ent) { ent->watertype = 0; ent->flags = 0; - VectorCopy (playerMins, ent->r.mins); - VectorCopy (playerMaxs, ent->r.maxs); + VectorCopy(playerMins, ent->r.mins); + VectorCopy(playerMaxs, ent->r.maxs); client->ps.crouchheight = CROUCH_MAXS_2; client->ps.standheight = DEFAULT_MAXS_2; client->ps.clientNum = index; - //give default weapons - client->ps.stats[STAT_WEAPONS] = ( 1 << WP_NONE ); + // give default weapons + client->ps.stats[STAT_WEAPONS] = (1 << WP_NONE); - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { wDisable = g_duelWeaponDisable.integer; - } - else - { + } else { wDisable = g_weaponDisable.integer; } - - - if ( level.gametype != GT_HOLOCRON - && level.gametype != GT_JEDIMASTER - && !HasSetSaberOnly() - && !AllForceDisabled( g_forcePowerDisable.integer ) - && g_jediVmerc.integer ) - { - if ( level.gametype >= GT_TEAM && (client->sess.sessionTeam == TEAM_BLUE || client->sess.sessionTeam == TEAM_RED) ) - {//In Team games, force one side to be merc and other to be jedi - if ( level.numPlayingClients > 0 ) - {//already someone in the game + if (level.gametype != GT_HOLOCRON && level.gametype != GT_JEDIMASTER && !HasSetSaberOnly() && !AllForceDisabled(g_forcePowerDisable.integer) && + g_jediVmerc.integer) { + if (level.gametype >= GT_TEAM && + (client->sess.sessionTeam == TEAM_BLUE || client->sess.sessionTeam == TEAM_RED)) { // In Team games, force one side to be merc and other to be jedi + if (level.numPlayingClients > 0) { // already someone in the game int forceTeam = TEAM_SPECTATOR; - for ( i = 0 ; i < level.maxclients ; i++ ) - { - if ( level.clients[i].pers.connected == CON_DISCONNECTED ) { + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_DISCONNECTED) { continue; } - if ( level.clients[i].sess.sessionTeam == TEAM_BLUE || level.clients[i].sess.sessionTeam == TEAM_RED ) - {//in-game - if ( WP_HasForcePowers( &level.clients[i].ps ) ) - {//this side is using force + if (level.clients[i].sess.sessionTeam == TEAM_BLUE || level.clients[i].sess.sessionTeam == TEAM_RED) { // in-game + if (WP_HasForcePowers(&level.clients[i].ps)) { // this side is using force forceTeam = level.clients[i].sess.sessionTeam; - } - else - {//other team is using force - if ( level.clients[i].sess.sessionTeam == TEAM_BLUE ) - { + } else { // other team is using force + if (level.clients[i].sess.sessionTeam == TEAM_BLUE) { forceTeam = TEAM_RED; - } - else - { + } else { forceTeam = TEAM_BLUE; } } break; } } - if ( WP_HasForcePowers( &client->ps ) && client->sess.sessionTeam != forceTeam ) - {//using force but not on right team, switch him over - const char *teamName = TeamName( forceTeam ); - //client->sess.sessionTeam = forceTeam; - SetTeam( ent, (char *)teamName ); + if (WP_HasForcePowers(&client->ps) && client->sess.sessionTeam != forceTeam) { // using force but not on right team, switch him over + const char *teamName = TeamName(forceTeam); + // client->sess.sessionTeam = forceTeam; + SetTeam(ent, (char *)teamName); return; } } } - if ( WP_HasForcePowers( &client->ps ) ) - { + if (WP_HasForcePowers(&client->ps)) { client->ps.trueNonJedi = qfalse; client->ps.trueJedi = qtrue; - //make sure they only use the saber + // make sure they only use the saber client->ps.weapon = WP_SABER; client->ps.stats[STAT_WEAPONS] = (1 << WP_SABER); - } - else - {//no force powers set + } else { // no force powers set client->ps.trueNonJedi = qtrue; client->ps.trueJedi = qfalse; - if (!wDisable || !(wDisable & (1 << WP_BRYAR_PISTOL))) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BRYAR_PISTOL ); + if (!wDisable || !(wDisable & (1 << WP_BRYAR_PISTOL))) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BRYAR_PISTOL); } - if (!wDisable || !(wDisable & (1 << WP_BLASTER))) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BLASTER ); + if (!wDisable || !(wDisable & (1 << WP_BLASTER))) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BLASTER); } - if (!wDisable || !(wDisable & (1 << WP_BOWCASTER))) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BOWCASTER ); + if (!wDisable || !(wDisable & (1 << WP_BOWCASTER))) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BOWCASTER); } client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_SABER); client->ps.stats[STAT_WEAPONS] |= (1 << WP_MELEE); client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; client->ps.weapon = WP_BRYAR_PISTOL; } - } - else - {//jediVmerc is incompatible with this gametype, turn it off! - trap->Cvar_Set( "g_jediVmerc", "0" ); - trap->Cvar_Update( &g_jediVmerc ); - if (level.gametype == GT_HOLOCRON) - { - //always get free saber level 1 in holocron - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_SABER ); //these are precached in g_items, ClearRegisteredItems() - } - else - { - if (client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_SABER ); //these are precached in g_items, ClearRegisteredItems() - } - else - { //if you don't have saber attack rank then you don't get a saber + } else { // jediVmerc is incompatible with this gametype, turn it off! + trap->Cvar_Set("g_jediVmerc", "0"); + trap->Cvar_Update(&g_jediVmerc); + if (level.gametype == GT_HOLOCRON) { + // always get free saber level 1 in holocron + client->ps.stats[STAT_WEAPONS] |= (1 << WP_SABER); // these are precached in g_items, ClearRegisteredItems() + } else { + if (client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_SABER); // these are precached in g_items, ClearRegisteredItems() + } else { // if you don't have saber attack rank then you don't get a saber client->ps.stats[STAT_WEAPONS] |= (1 << WP_MELEE); } } - if (level.gametype != GT_SIEGE) - { - if (!wDisable || !(wDisable & (1 << WP_BRYAR_PISTOL))) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BRYAR_PISTOL ); - } - else if (level.gametype == GT_JEDIMASTER) - { - client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_BRYAR_PISTOL ); + if (level.gametype != GT_SIEGE) { + if (!wDisable || !(wDisable & (1 << WP_BRYAR_PISTOL))) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BRYAR_PISTOL); + } else if (level.gametype == GT_JEDIMASTER) { + client->ps.stats[STAT_WEAPONS] |= (1 << WP_BRYAR_PISTOL); } } - if (level.gametype == GT_JEDIMASTER) - { + if (level.gametype == GT_JEDIMASTER) { client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_SABER); client->ps.stats[STAT_WEAPONS] |= (1 << WP_MELEE); } - if (client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) - { + if (client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { client->ps.weapon = WP_SABER; - } - else if (client->ps.stats[STAT_WEAPONS] & (1 << WP_BRYAR_PISTOL)) - { + } else if (client->ps.stats[STAT_WEAPONS] & (1 << WP_BRYAR_PISTOL)) { client->ps.weapon = WP_BRYAR_PISTOL; - } - else - { + } else { client->ps.weapon = WP_MELEE; } } @@ -3526,65 +3167,42 @@ void ClientSpawn(gentity_t *ent) { */ if (level.gametype == GT_SIEGE && client->siegeClass != -1 && - client->sess.sessionTeam != TEAM_SPECTATOR) - { //well then, we will use a custom weaponset for our class + client->sess.sessionTeam != TEAM_SPECTATOR) { // well then, we will use a custom weaponset for our class int m = 0; client->ps.stats[STAT_WEAPONS] = bgSiegeClasses[client->siegeClass].weapons; - if (client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) - { + if (client->ps.stats[STAT_WEAPONS] & (1 << WP_SABER)) { client->ps.weapon = WP_SABER; - } - else if (client->ps.stats[STAT_WEAPONS] & (1 << WP_BRYAR_PISTOL)) - { + } else if (client->ps.stats[STAT_WEAPONS] & (1 << WP_BRYAR_PISTOL)) { client->ps.weapon = WP_BRYAR_PISTOL; - } - else - { + } else { client->ps.weapon = WP_MELEE; } inSiegeWithClass = qtrue; - while (m < WP_NUM_WEAPONS) - { - if (client->ps.stats[STAT_WEAPONS] & (1 << m)) - { - if (client->ps.weapon != WP_SABER) - { //try to find the highest ranking weapon we have - if (m > client->ps.weapon) - { + while (m < WP_NUM_WEAPONS) { + if (client->ps.stats[STAT_WEAPONS] & (1 << m)) { + if (client->ps.weapon != WP_SABER) { // try to find the highest ranking weapon we have + if (m > client->ps.weapon) { client->ps.weapon = m; } } - if (m >= WP_BRYAR_PISTOL) - { //Max his ammo out for all the weapons he has. - if ( level.gametype == GT_SIEGE - && m == WP_ROCKET_LAUNCHER ) - {//don't give full ammo! - //FIXME: extern this and check it when getting ammo from supplier, pickups or ammo stations! - if ( client->siegeClass != -1 && - (bgSiegeClasses[client->siegeClass].classflags & (1<= WP_BRYAR_PISTOL) { // Max his ammo out for all the weapons he has. + if (level.gametype == GT_SIEGE && m == WP_ROCKET_LAUNCHER) { // don't give full ammo! + // FIXME: extern this and check it when getting ammo from supplier, pickups or ammo stations! + if (client->siegeClass != -1 && (bgSiegeClasses[client->siegeClass].classflags & (1 << CFL_SINGLE_ROCKET))) { client->ps.ammo[weaponData[m].ammoIndex] = 1; - } - else - { + } else { client->ps.ammo[weaponData[m].ammoIndex] = 10; } - } - else - { - if ( level.gametype == GT_SIEGE - && client->siegeClass != -1 - && (bgSiegeClasses[client->siegeClass].classflags & (1<ps.ammo[weaponData[m].ammoIndex] = ammoData[weaponData[m].ammoIndex].max*2; + } else { + if (level.gametype == GT_SIEGE && client->siegeClass != -1 && + (bgSiegeClasses[client->siegeClass].classflags & (1 << CFL_EXTRA_AMMO))) { // double ammo + client->ps.ammo[weaponData[m].ammoIndex] = ammoData[weaponData[m].ammoIndex].max * 2; client->ps.eFlags |= EF_DOUBLE_AMMO; - } - else - { + } else { client->ps.ammo[weaponData[m].ammoIndex] = ammoData[weaponData[m].ammoIndex].max; } } @@ -3594,121 +3212,92 @@ void ClientSpawn(gentity_t *ent) { } } - if (level.gametype == GT_SIEGE && - client->siegeClass != -1 && - client->sess.sessionTeam != TEAM_SPECTATOR) - { //use class-specified inventory + if (level.gametype == GT_SIEGE && client->siegeClass != -1 && client->sess.sessionTeam != TEAM_SPECTATOR) { // use class-specified inventory client->ps.stats[STAT_HOLDABLE_ITEMS] = bgSiegeClasses[client->siegeClass].invenItems; client->ps.stats[STAT_HOLDABLE_ITEM] = 0; - } - else - { + } else { client->ps.stats[STAT_HOLDABLE_ITEMS] = 0; client->ps.stats[STAT_HOLDABLE_ITEM] = 0; } - if (level.gametype == GT_SIEGE && - client->siegeClass != -1 && - bgSiegeClasses[client->siegeClass].powerups && - client->sess.sessionTeam != TEAM_SPECTATOR) - { //this class has some start powerups + if (level.gametype == GT_SIEGE && client->siegeClass != -1 && bgSiegeClasses[client->siegeClass].powerups && + client->sess.sessionTeam != TEAM_SPECTATOR) { // this class has some start powerups i = 0; - while (i < PW_NUM_POWERUPS) - { - if (bgSiegeClasses[client->siegeClass].powerups & (1 << i)) - { + while (i < PW_NUM_POWERUPS) { + if (bgSiegeClasses[client->siegeClass].powerups & (1 << i)) { client->ps.powerups[i] = Q3_INFINITE; } i++; } } - if ( client->sess.sessionTeam == TEAM_SPECTATOR ) - { + if (client->sess.sessionTeam == TEAM_SPECTATOR) { client->ps.stats[STAT_WEAPONS] = 0; client->ps.stats[STAT_HOLDABLE_ITEMS] = 0; client->ps.stats[STAT_HOLDABLE_ITEM] = 0; } -// nmckenzie: DESERT_SIEGE... or well, siege generally. This was over-writing the max value, which was NOT good for siege. - if ( inSiegeWithClass == qfalse ) - { - client->ps.ammo[AMMO_BLASTER] = 100; //ammoData[AMMO_BLASTER].max; //100 seems fair. - } -// client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; -// client->ps.ammo[AMMO_FORCE] = ammoData[AMMO_FORCE].max; -// client->ps.ammo[AMMO_METAL_BOLTS] = ammoData[AMMO_METAL_BOLTS].max; -// client->ps.ammo[AMMO_ROCKETS] = ammoData[AMMO_ROCKETS].max; -/* - client->ps.stats[STAT_WEAPONS] = ( 1 << WP_BRYAR_PISTOL); - if ( level.gametype == GT_TEAM ) { - client->ps.ammo[WP_BRYAR_PISTOL] = 50; - } else { - client->ps.ammo[WP_BRYAR_PISTOL] = 100; + // nmckenzie: DESERT_SIEGE... or well, siege generally. This was over-writing the max value, which was NOT good for siege. + if (inSiegeWithClass == qfalse) { + client->ps.ammo[AMMO_BLASTER] = 100; // ammoData[AMMO_BLASTER].max; //100 seems fair. } -*/ + // client->ps.ammo[AMMO_POWERCELL] = ammoData[AMMO_POWERCELL].max; + // client->ps.ammo[AMMO_FORCE] = ammoData[AMMO_FORCE].max; + // client->ps.ammo[AMMO_METAL_BOLTS] = ammoData[AMMO_METAL_BOLTS].max; + // client->ps.ammo[AMMO_ROCKETS] = ammoData[AMMO_ROCKETS].max; + /* + client->ps.stats[STAT_WEAPONS] = ( 1 << WP_BRYAR_PISTOL); + if ( level.gametype == GT_TEAM ) { + client->ps.ammo[WP_BRYAR_PISTOL] = 50; + } else { + client->ps.ammo[WP_BRYAR_PISTOL] = 100; + } + */ client->ps.rocketLockIndex = ENTITYNUM_NONE; client->ps.rocketLockTime = 0; - //rww - Set here to initialize the circling seeker drone to off. - //A quick note about this so I don't forget how it works again: - //ps.genericEnemyIndex is kept in sync between the server and client. - //When it gets set then an entitystate value of the same name gets - //set along with an entitystate flag in the shared bg code. Which - //is why a value needs to be both on the player state and entity state. + // rww - Set here to initialize the circling seeker drone to off. + // A quick note about this so I don't forget how it works again: + // ps.genericEnemyIndex is kept in sync between the server and client. + // When it gets set then an entitystate value of the same name gets + // set along with an entitystate flag in the shared bg code. Which + // is why a value needs to be both on the player state and entity state. //(it doesn't seem to just carry over the entitystate value automatically - //because entity state value is derived from player state data or some - //such) + // because entity state value is derived from player state data or some + // such) client->ps.genericEnemyIndex = -1; client->ps.isJediMaster = qfalse; - if (client->ps.fallingToDeath) - { + if (client->ps.fallingToDeath) { client->ps.fallingToDeath = 0; client->noCorpse = qtrue; } - //Do per-spawn force power initialization - WP_SpawnInitForcePowers( ent ); + // Do per-spawn force power initialization + WP_SpawnInitForcePowers(ent); // health will count down towards max_health - if (level.gametype == GT_SIEGE && - client->siegeClass != -1 && - bgSiegeClasses[client->siegeClass].starthealth) - { //class specifies a start health, so use it + if (level.gametype == GT_SIEGE && client->siegeClass != -1 && bgSiegeClasses[client->siegeClass].starthealth) { // class specifies a start health, so use it ent->health = client->ps.stats[STAT_HEALTH] = bgSiegeClasses[client->siegeClass].starthealth; - } - else if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) - {//only start with 100 health in Duel - if ( level.gametype == GT_POWERDUEL && client->sess.duelTeam == DUELTEAM_LONE ) - { - if ( duel_fraglimit.integer ) - { + } else if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // only start with 100 health in Duel + if (level.gametype == GT_POWERDUEL && client->sess.duelTeam == DUELTEAM_LONE) { + if (duel_fraglimit.integer) { ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] = - g_powerDuelStartHealth.integer - ((g_powerDuelStartHealth.integer - g_powerDuelEndHealth.integer) * (float)client->sess.wins / (float)duel_fraglimit.integer); - } - else - { + g_powerDuelStartHealth.integer - + ((g_powerDuelStartHealth.integer - g_powerDuelEndHealth.integer) * (float)client->sess.wins / (float)duel_fraglimit.integer); + } else { ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] = 150; } - } - else - { + } else { ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] = 100; } - } - else if (client->ps.stats[STAT_MAX_HEALTH] <= 100) - { + } else if (client->ps.stats[STAT_MAX_HEALTH] <= 100) { ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH] * 1.25; - } - else if (client->ps.stats[STAT_MAX_HEALTH] < 125) - { + } else if (client->ps.stats[STAT_MAX_HEALTH] < 125) { ent->health = client->ps.stats[STAT_HEALTH] = 125; - } - else - { + } else { ent->health = client->ps.stats[STAT_HEALTH] = client->ps.stats[STAT_MAX_HEALTH]; } @@ -3718,24 +3307,20 @@ void ClientSpawn(gentity_t *ent) { bgSiegeClasses[client->siegeClass].startarmor*/) { //class specifies a start armor amount, so use it client->ps.stats[STAT_ARMOR] = bgSiegeClasses[client->siegeClass].startarmor; - } - else if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) - {//no armor in duel + } else if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // no armor in duel client->ps.stats[STAT_ARMOR] = 0; - } - else - { + } else { client->ps.stats[STAT_ARMOR] = client->ps.stats[STAT_MAX_HEALTH] * 0.25; } - G_SetOrigin( ent, spawn_origin ); - VectorCopy( spawn_origin, client->ps.origin ); + G_SetOrigin(ent, spawn_origin); + VectorCopy(spawn_origin, client->ps.origin); // the respawned flag will be cleared after the attack and jump keys come up client->ps.pm_flags |= PMF_RESPAWNED; - trap->GetUsercmd( client - level.clients, &ent->client->pers.cmd ); - SetClientViewAngle( ent, spawn_angles ); + trap->GetUsercmd(client - level.clients, &ent->client->pers.cmd); + SetClientViewAngle(ent, spawn_angles); // don't allow full run speed for a bit client->ps.pm_flags |= PMF_TIME_KNOCKBACK; client->ps.pm_time = 100; @@ -3748,29 +3333,24 @@ void ClientSpawn(gentity_t *ent) { if (ent->client->sess.sessionTeam != TEAM_SPECTATOR) { G_KillBox(ent); // force the base weapon up - //client->ps.weapon = WP_BRYAR_PISTOL; - //client->ps.weaponstate = FIRST_WEAPON; - if (client->ps.weapon <= WP_NONE) - { + // client->ps.weapon = WP_BRYAR_PISTOL; + // client->ps.weaponstate = FIRST_WEAPON; + if (client->ps.weapon <= WP_NONE) { client->ps.weapon = WP_BRYAR_PISTOL; } client->ps.torsoTimer = client->ps.legsTimer = 0; - if (client->ps.weapon == WP_SABER) - { - G_SetAnim(ent, NULL, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS, 0); - } - else - { - G_SetAnim(ent, NULL, SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS, 0); + if (client->ps.weapon == WP_SABER) { + G_SetAnim(ent, NULL, SETANIM_BOTH, BOTH_STAND1TO2, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 0); + } else { + G_SetAnim(ent, NULL, SETANIM_TORSO, TORSO_RAISEWEAP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 0); client->ps.legsAnim = WeaponReadyAnim[client->ps.weapon]; } client->ps.weaponstate = WEAPON_RAISING; client->ps.weaponTime = client->ps.torsoTimer; - if (g_spawnInvulnerability.integer) - { + if (g_spawnInvulnerability.integer) { ent->client->ps.eFlags |= EF_INVULNERABLE; ent->client->invulnerableTimer = level.time + g_spawnInvulnerability.integer; } @@ -3784,29 +3364,23 @@ void ClientSpawn(gentity_t *ent) { tent = G_TempEntity(ent->client->ps.origin, EV_PLAYER_TELEPORT_IN); tent->s.clientNum = ent->s.clientNum; - trap->LinkEntity ((sharedEntity_t *)ent); + trap->LinkEntity((sharedEntity_t *)ent); } } else { // move players to intermission MoveClientToIntermission(ent); } - //set teams for NPCs to recognize - if (level.gametype == GT_SIEGE) - { //Imperial (team1) team is allied with "enemy" NPCs in this mode - if (client->sess.sessionTeam == SIEGETEAM_TEAM1) - { + // set teams for NPCs to recognize + if (level.gametype == GT_SIEGE) { // Imperial (team1) team is allied with "enemy" NPCs in this mode + if (client->sess.sessionTeam == SIEGETEAM_TEAM1) { client->playerTeam = ent->s.teamowner = NPCTEAM_ENEMY; client->enemyTeam = NPCTEAM_PLAYER; - } - else - { + } else { client->playerTeam = ent->s.teamowner = NPCTEAM_PLAYER; client->enemyTeam = NPCTEAM_ENEMY; } - } - else - { + } else { client->playerTeam = ent->s.teamowner = NPCTEAM_PLAYER; client->enemyTeam = NPCTEAM_ENEMY; } @@ -3820,28 +3394,27 @@ void ClientSpawn(gentity_t *ent) { VectorSet(ent->modelScale, 1.25f, 1.25f, 1.25f); } */ - //Disabled. At least for now. Not sure if I'll want to do it or not eventually. + // Disabled. At least for now. Not sure if I'll want to do it or not eventually. // run a client frame to drop exactly to the floor, // initialize animations and other things client->ps.commandTime = level.time - 100; ent->client->pers.cmd.serverTime = level.time; - ClientThink( ent-g_entities, NULL ); + ClientThink(ent - g_entities, NULL); // run the presend to set anything else, follow spectators wait // until all clients have been reconnected after map_restart - if ( ent->client->sess.spectatorState != SPECTATOR_FOLLOW ) - ClientEndFrame( ent ); + if (ent->client->sess.spectatorState != SPECTATOR_FOLLOW) + ClientEndFrame(ent); // clear entity state values - BG_PlayerStateToEntityState( &client->ps, &ent->s, qtrue ); + BG_PlayerStateToEntityState(&client->ps, &ent->s, qtrue); - //rww - make sure client has a valid icarus instance - trap->ICARUS_FreeEnt( (sharedEntity_t *)ent ); - trap->ICARUS_InitEnt( (sharedEntity_t *)ent ); + // rww - make sure client has a valid icarus instance + trap->ICARUS_FreeEnt((sharedEntity_t *)ent); + trap->ICARUS_InitEnt((sharedEntity_t *)ent); } - /* =========== ClientDisconnect @@ -3854,40 +3427,41 @@ call trap->DropClient(), which will call this and do server system housekeeping. ============ */ -extern void G_LeaveVehicle( gentity_t* ent, qboolean ConCheck ); +extern void G_LeaveVehicle(gentity_t *ent, qboolean ConCheck); -void G_ClearVote( gentity_t *ent ) { - if ( level.voteTime ) { - if ( ent->client->mGameFlags & PSG_VOTED ) { - if ( ent->client->pers.vote == 1 ) { +void G_ClearVote(gentity_t *ent) { + if (level.voteTime) { + if (ent->client->mGameFlags & PSG_VOTED) { + if (ent->client->pers.vote == 1) { level.voteYes--; - trap->SetConfigstring( CS_VOTE_YES, va( "%i", level.voteYes ) ); - } - else if ( ent->client->pers.vote == 2 ) { + trap->SetConfigstring(CS_VOTE_YES, va("%i", level.voteYes)); + } else if (ent->client->pers.vote == 2) { level.voteNo--; - trap->SetConfigstring( CS_VOTE_NO, va( "%i", level.voteNo ) ); + trap->SetConfigstring(CS_VOTE_NO, va("%i", level.voteNo)); } } ent->client->mGameFlags &= ~(PSG_VOTED); ent->client->pers.vote = 0; } } -void G_ClearTeamVote( gentity_t *ent, int team ) { +void G_ClearTeamVote(gentity_t *ent, int team) { int voteteam; - if ( team == TEAM_RED ) voteteam = 0; - else if ( team == TEAM_BLUE ) voteteam = 1; - else return; + if (team == TEAM_RED) + voteteam = 0; + else if (team == TEAM_BLUE) + voteteam = 1; + else + return; - if ( level.teamVoteTime[voteteam] ) { - if ( ent->client->mGameFlags & PSG_TEAMVOTED ) { - if ( ent->client->pers.teamvote == 1 ) { + if (level.teamVoteTime[voteteam]) { + if (ent->client->mGameFlags & PSG_TEAMVOTED) { + if (ent->client->pers.teamvote == 1) { level.teamVoteYes[voteteam]--; - trap->SetConfigstring( CS_TEAMVOTE_YES, va( "%i", level.teamVoteYes[voteteam] ) ); - } - else if ( ent->client->pers.teamvote == 2 ) { + trap->SetConfigstring(CS_TEAMVOTE_YES, va("%i", level.teamVoteYes[voteteam])); + } else if (ent->client->pers.teamvote == 2) { level.teamVoteNo[voteteam]--; - trap->SetConfigstring( CS_TEAMVOTE_NO, va( "%i", level.teamVoteNo[voteteam] ) ); + trap->SetConfigstring(CS_TEAMVOTE_NO, va("%i", level.teamVoteNo[voteteam])); } } ent->client->mGameFlags &= ~(PSG_TEAMVOTED); @@ -3895,26 +3469,24 @@ void G_ClearTeamVote( gentity_t *ent, int team ) { } } -void ClientDisconnect( int clientNum ) { - gentity_t *ent; - gentity_t *tent; - int i; +void ClientDisconnect(int clientNum) { + gentity_t *ent; + gentity_t *tent; + int i; // cleanup if we are kicking a bot that // hasn't spawned yet - G_RemoveQueuedBotBegin( clientNum ); + G_RemoveQueuedBotBegin(clientNum); ent = g_entities + clientNum; - if ( !ent->client || ent->client->pers.connected == CON_DISCONNECTED ) { + if (!ent->client || ent->client->pers.connected == CON_DISCONNECTED) { return; } i = 0; - while (i < NUM_FORCE_POWERS) - { - if (ent->client->ps.fd.forcePowersActive & (1 << i)) - { + while (i < NUM_FORCE_POWERS) { + if (ent->client->ps.fd.forcePowersActive & (1 << i)) { WP_ForcePowerStop(ent, i); } i++; @@ -3922,89 +3494,81 @@ void ClientDisconnect( int clientNum ) { i = TRACK_CHANNEL_1; - while (i < NUM_TRACK_CHANNELS) - { - if (ent->client->ps.fd.killSoundEntIndex[i-50] && ent->client->ps.fd.killSoundEntIndex[i-50] < MAX_GENTITIES && ent->client->ps.fd.killSoundEntIndex[i-50] > 0) - { - G_MuteSound(ent->client->ps.fd.killSoundEntIndex[i-50], CHAN_VOICE); + while (i < NUM_TRACK_CHANNELS) { + if (ent->client->ps.fd.killSoundEntIndex[i - 50] && ent->client->ps.fd.killSoundEntIndex[i - 50] < MAX_GENTITIES && + ent->client->ps.fd.killSoundEntIndex[i - 50] > 0) { + G_MuteSound(ent->client->ps.fd.killSoundEntIndex[i - 50], CHAN_VOICE); } i++; } i = 0; - G_LeaveVehicle( ent, qtrue ); + G_LeaveVehicle(ent, qtrue); - if ( ent->client->ewebIndex ) - { + if (ent->client->ewebIndex) { gentity_t *eweb = &g_entities[ent->client->ewebIndex]; ent->client->ps.emplacedIndex = 0; ent->client->ewebIndex = 0; ent->client->ewebHealth = 0; - G_FreeEntity( eweb ); + G_FreeEntity(eweb); } // stop any following clients - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].sess.sessionTeam == TEAM_SPECTATOR - && level.clients[i].sess.spectatorState == SPECTATOR_FOLLOW - && level.clients[i].sess.spectatorClient == clientNum ) { - StopFollowing( &g_entities[i] ); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].sess.sessionTeam == TEAM_SPECTATOR && level.clients[i].sess.spectatorState == SPECTATOR_FOLLOW && + level.clients[i].sess.spectatorClient == clientNum) { + StopFollowing(&g_entities[i]); } } // send effect if they were completely connected - if ( ent->client->pers.connected == CON_CONNECTED - && ent->client->sess.sessionTeam != TEAM_SPECTATOR ) { - tent = G_TempEntity( ent->client->ps.origin, EV_PLAYER_TELEPORT_OUT ); + if (ent->client->pers.connected == CON_CONNECTED && ent->client->sess.sessionTeam != TEAM_SPECTATOR) { + tent = G_TempEntity(ent->client->ps.origin, EV_PLAYER_TELEPORT_OUT); tent->s.clientNum = ent->s.clientNum; // They don't get to take powerups with them! // Especially important for stuff like CTF flags - TossClientItems( ent ); + TossClientItems(ent); } - G_LogPrintf( "ClientDisconnect: %i [%s] (%s) \"%s^7\"\n", clientNum, ent->client->sess.IP, ent->client->pers.guid, ent->client->pers.netname ); + G_LogPrintf("ClientDisconnect: %i [%s] (%s) \"%s^7\"\n", clientNum, ent->client->sess.IP, ent->client->pers.guid, ent->client->pers.netname); // if we are playing in tourney mode, give a win to the other player and clear his frags for this round - if ( level.gametype == GT_DUEL && !level.intermissiontime && !level.warmupTime ) { - if ( level.sortedClients[1] == clientNum ) { - level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] = 0; - level.clients[ level.sortedClients[0] ].sess.wins++; - ClientUserinfoChanged( level.sortedClients[0] ); - } - else if ( level.sortedClients[0] == clientNum ) { - level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE] = 0; - level.clients[ level.sortedClients[1] ].sess.wins++; - ClientUserinfoChanged( level.sortedClients[1] ); + if (level.gametype == GT_DUEL && !level.intermissiontime && !level.warmupTime) { + if (level.sortedClients[1] == clientNum) { + level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] = 0; + level.clients[level.sortedClients[0]].sess.wins++; + ClientUserinfoChanged(level.sortedClients[0]); + } else if (level.sortedClients[0] == clientNum) { + level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] = 0; + level.clients[level.sortedClients[1]].sess.wins++; + ClientUserinfoChanged(level.sortedClients[1]); } } - if ( level.gametype == GT_DUEL && ent->client->sess.sessionTeam == TEAM_FREE && level.intermissiontime ) { - trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); + if (level.gametype == GT_DUEL && ent->client->sess.sessionTeam == TEAM_FREE && level.intermissiontime) { + trap->SendConsoleCommand(EXEC_APPEND, "map_restart 0\n"); level.restarted = qtrue; level.changemap = NULL; level.intermissiontime = 0; } - if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) - { + if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) { trap->G2API_CleanGhoul2Models(&ent->ghoul2); } i = 0; - while (i < MAX_SABERS) - { - if (ent->client->weaponGhoul2[i] && trap->G2API_HaveWeGhoul2Models(ent->client->weaponGhoul2[i])) - { + while (i < MAX_SABERS) { + if (ent->client->weaponGhoul2[i] && trap->G2API_HaveWeGhoul2Models(ent->client->weaponGhoul2[i])) { trap->G2API_CleanGhoul2Models(&ent->client->weaponGhoul2[i]); } i++; } - G_ClearVote( ent ); - G_ClearTeamVote( ent, ent->client->sess.sessionTeam ); + G_ClearVote(ent); + G_ClearTeamVote(ent, ent->client->sess.sessionTeam); - trap->UnlinkEntity ((sharedEntity_t *)ent); + trap->UnlinkEntity((sharedEntity_t *)ent); ent->s.modelindex = 0; ent->inuse = qfalse; ent->classname = "disconnected"; @@ -4013,25 +3577,22 @@ void ClientDisconnect( int clientNum ) { ent->client->sess.sessionTeam = TEAM_FREE; ent->r.contents = 0; - if (ent->client->holdingObjectiveItem > 0) - { //carrying a siege objective item - make sure it updates and removes itself from us now in case this is an instant death-respawn situation + if (ent->client->holdingObjectiveItem > + 0) { // carrying a siege objective item - make sure it updates and removes itself from us now in case this is an instant death-respawn situation gentity_t *objectiveItem = &g_entities[ent->client->holdingObjectiveItem]; - if (objectiveItem->inuse && objectiveItem->think) - { - objectiveItem->think(objectiveItem); + if (objectiveItem->inuse && objectiveItem->think) { + objectiveItem->think(objectiveItem); } } - trap->SetConfigstring( CS_PLAYERS + clientNum, ""); + trap->SetConfigstring(CS_PLAYERS + clientNum, ""); CalculateRanks(); - if ( ent->r.svFlags & SVF_BOT ) { - BotAIShutdownClient( clientNum, qfalse ); + if (ent->r.svFlags & SVF_BOT) { + BotAIShutdownClient(clientNum, qfalse); } G_ClearClientLog(clientNum); } - - diff --git a/codemp/game/g_cmds.c b/codemp/game/g_cmds.c index e5c7e24d29..d5e03f9c02 100644 --- a/codemp/game/g_cmds.c +++ b/codemp/game/g_cmds.c @@ -25,15 +25,15 @@ along with this program; if not, see . #include "g_local.h" #include "bg_saga.h" -#include "ui/menudef.h" // for the voice chats +#include "ui/menudef.h" // for the voice chats -//rww - for getting bot commands... +// rww - for getting bot commands... int AcceptBotCommand(char *cmd, gentity_t *pl); -//end rww +// end rww -void WP_SetSaber( int entNum, saberInfo_t *sabers, int saberNum, const char *saberName ); +void WP_SetSaber(int entNum, saberInfo_t *sabers, int saberNum, const char *saberName); -void Cmd_NPC_f( gentity_t *ent ); +void Cmd_NPC_f(gentity_t *ent); void SetTeamQuick(gentity_t *ent, int team, qboolean doBegin); /* @@ -42,13 +42,13 @@ DeathmatchScoreboardMessage ================== */ -void DeathmatchScoreboardMessage( gentity_t *ent ) { - char entry[256]; - char string[MAX_STRING_CHARS-1]; - int stringlength, prefix; - int i, j; - gclient_t *cl; - int numSorted, scoreFlags, accuracy, perfect; +void DeathmatchScoreboardMessage(gentity_t *ent) { + char entry[256]; + char string[MAX_STRING_CHARS - 1]; + int stringlength, prefix; + int i, j; + gclient_t *cl; + int numSorted, scoreFlags, accuracy, perfect; // send the latest information on all clients string[0] = '\0'; @@ -58,58 +58,47 @@ void DeathmatchScoreboardMessage( gentity_t *ent ) { numSorted = level.numConnectedClients; // This is dumb that we are capping to 20 clients but support 32 in server - if (numSorted > MAX_CLIENT_SCORE_SEND) - { + if (numSorted > MAX_CLIENT_SCORE_SEND) { numSorted = MAX_CLIENT_SCORE_SEND; } // estimate prefix length to avoid oversize of final string - prefix = Com_sprintf( entry, sizeof(entry), "scores %i %i %i", level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE], level.numConnectedClients ); + prefix = Com_sprintf(entry, sizeof(entry), "scores %i %i %i", level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE], level.numConnectedClients); - for (i=0 ; i < numSorted ; i++) { - int ping; + for (i = 0; i < numSorted; i++) { + int ping; cl = &level.clients[level.sortedClients[i]]; - if ( cl->pers.connected == CON_CONNECTING ) { + if (cl->pers.connected == CON_CONNECTING) { ping = -1; } else { ping = cl->ps.ping < 999 ? cl->ps.ping : 999; } - if( cl->accuracy_shots ) { + if (cl->accuracy_shots) { accuracy = cl->accuracy_hits * 100 / cl->accuracy_shots; - } - else { + } else { accuracy = 0; } - perfect = ( cl->ps.persistant[PERS_RANK] == 0 && cl->ps.persistant[PERS_KILLED] == 0 ) ? 1 : 0; + perfect = (cl->ps.persistant[PERS_RANK] == 0 && cl->ps.persistant[PERS_KILLED] == 0) ? 1 : 0; - j = Com_sprintf (entry, sizeof(entry), - " %i %i %i %i %i %i %i %i %i %i %i %i %i %i", level.sortedClients[i], - cl->ps.persistant[PERS_SCORE], ping, (level.time - cl->pers.enterTime)/60000, - scoreFlags, g_entities[level.sortedClients[i]].s.powerups, accuracy, - cl->ps.persistant[PERS_IMPRESSIVE_COUNT], - cl->ps.persistant[PERS_EXCELLENT_COUNT], - cl->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], - cl->ps.persistant[PERS_DEFEND_COUNT], - cl->ps.persistant[PERS_ASSIST_COUNT], - perfect, - cl->ps.persistant[PERS_CAPTURES]); + j = Com_sprintf(entry, sizeof(entry), " %i %i %i %i %i %i %i %i %i %i %i %i %i %i", level.sortedClients[i], cl->ps.persistant[PERS_SCORE], ping, + (level.time - cl->pers.enterTime) / 60000, scoreFlags, g_entities[level.sortedClients[i]].s.powerups, accuracy, + cl->ps.persistant[PERS_IMPRESSIVE_COUNT], cl->ps.persistant[PERS_EXCELLENT_COUNT], cl->ps.persistant[PERS_GAUNTLET_FRAG_COUNT], + cl->ps.persistant[PERS_DEFEND_COUNT], cl->ps.persistant[PERS_ASSIST_COUNT], perfect, cl->ps.persistant[PERS_CAPTURES]); if (stringlength + j + prefix >= sizeof(string)) break; - strcpy( string + stringlength, entry ); + strcpy(string + stringlength, entry); stringlength += j; } - trap->SendServerCommand( ent-g_entities, va("scores %i %i %i%s", level.numConnectedClients, - level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE], - string ) ); + trap->SendServerCommand(ent - g_entities, + va("scores %i %i %i%s", level.numConnectedClients, level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE], string)); } - /* ================== Cmd_Score_f @@ -117,32 +106,30 @@ Cmd_Score_f Request current scoreboard information ================== */ -void Cmd_Score_f( gentity_t *ent ) { - DeathmatchScoreboardMessage( ent ); -} +void Cmd_Score_f(gentity_t *ent) { DeathmatchScoreboardMessage(ent); } /* ================== ConcatArgs ================== */ -char *ConcatArgs( int start ) { - int i, c, tlen; - static char line[MAX_STRING_CHARS]; - int len; - char arg[MAX_STRING_CHARS]; +char *ConcatArgs(int start) { + int i, c, tlen; + static char line[MAX_STRING_CHARS]; + int len; + char arg[MAX_STRING_CHARS]; len = 0; c = trap->Argc(); - for ( i = start ; i < c ; i++ ) { - trap->Argv( i, arg, sizeof( arg ) ); - tlen = strlen( arg ); - if ( len + tlen >= MAX_STRING_CHARS - 1 ) { + for (i = start; i < c; i++) { + trap->Argv(i, arg, sizeof(arg)); + tlen = strlen(arg); + if (len + tlen >= MAX_STRING_CHARS - 1) { break; } - memcpy( line + len, arg, tlen ); + memcpy(line + len, arg, tlen); len += tlen; - if ( i != c - 1 ) { + if (i != c - 1) { line[len] = ' '; len++; } @@ -158,13 +145,12 @@ char *ConcatArgs( int start ) { StringIsInteger ================== */ -qboolean StringIsInteger( const char *s ) { - int i=0, len=0; - qboolean foundDigit=qfalse; +qboolean StringIsInteger(const char *s) { + int i = 0, len = 0; + qboolean foundDigit = qfalse; - for ( i=0, len=strlen( s ); i= 0 && idnum < level.maxclients ) - { +int ClientNumberFromString(gentity_t *to, const char *s, qboolean allowconnecting) { + gclient_t *cl; + int idnum; + char cleanInput[MAX_NETNAME]; + + if (StringIsInteger(s)) { // numeric values could be slot numbers + idnum = atoi(s); + if (idnum >= 0 && idnum < level.maxclients) { cl = &level.clients[idnum]; - if ( cl->pers.connected == CON_CONNECTED ) + if (cl->pers.connected == CON_CONNECTED) return idnum; - else if ( allowconnecting && cl->pers.connected == CON_CONNECTING ) + else if (allowconnecting && cl->pers.connected == CON_CONNECTING) return idnum; } } - Q_strncpyz( cleanInput, s, sizeof(cleanInput) ); - Q_StripColor( cleanInput ); + Q_strncpyz(cleanInput, s, sizeof(cleanInput)); + Q_StripColor(cleanInput); - for ( idnum=0,cl=level.clients; idnum < level.maxclients; idnum++,cl++ ) - {// check for a name match - if ( cl->pers.connected != CON_CONNECTED ) - if ( !allowconnecting || cl->pers.connected < CON_CONNECTING ) + for (idnum = 0, cl = level.clients; idnum < level.maxclients; idnum++, cl++) { // check for a name match + if (cl->pers.connected != CON_CONNECTED) + if (!allowconnecting || cl->pers.connected < CON_CONNECTING) continue; - if ( !Q_stricmp( cl->pers.netname_nocolor, cleanInput ) ) + if (!Q_stricmp(cl->pers.netname_nocolor, cleanInput)) return idnum; } - trap->SendServerCommand( to-g_entities, va( "print \"User %s is not on the server\n\"", s ) ); + trap->SendServerCommand(to - g_entities, va("print \"User %s is not on the server\n\"", s)); return -1; } @@ -223,173 +206,160 @@ Cmd_Give_f Give items to a client ================== */ -void G_Give( gentity_t *ent, const char *name, const char *args, int argc ) -{ - gitem_t *it; - int i; - qboolean give_all = qfalse; - gentity_t *it_ent; - trace_t trace; - - if ( !Q_stricmp( name, "all" ) ) +void G_Give(gentity_t *ent, const char *name, const char *args, int argc) { + gitem_t *it; + int i; + qboolean give_all = qfalse; + gentity_t *it_ent; + trace_t trace; + + if (!Q_stricmp(name, "all")) give_all = qtrue; - if ( give_all ) - { - for ( i=0; iclient->ps.stats[STAT_HOLDABLE_ITEMS] |= (1 << i); } - if ( give_all || !Q_stricmp( name, "health") ) - { - if ( argc == 3 ) - ent->health = Com_Clampi( 1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); - else - { - if ( level.gametype == GT_SIEGE && ent->client->siegeClass != -1 ) + if (give_all || !Q_stricmp(name, "health")) { + if (argc == 3) + ent->health = Com_Clampi(1, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); + else { + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1) ent->health = bgSiegeClasses[ent->client->siegeClass].maxhealth; else ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "armor" ) || !Q_stricmp( name, "shield" ) ) - { - if ( argc == 3 ) - ent->client->ps.stats[STAT_ARMOR] = Com_Clampi( 0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi( args ) ); - else - { - if ( level.gametype == GT_SIEGE && ent->client->siegeClass != -1 ) + if (give_all || !Q_stricmp(name, "armor") || !Q_stricmp(name, "shield")) { + if (argc == 3) + ent->client->ps.stats[STAT_ARMOR] = Com_Clampi(0, ent->client->ps.stats[STAT_MAX_HEALTH], atoi(args)); + else { + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1) ent->client->ps.stats[STAT_ARMOR] = bgSiegeClasses[ent->client->siegeClass].maxarmor; else ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH]; } - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "force" ) ) - { - if ( argc == 3 ) - ent->client->ps.fd.forcePower = Com_Clampi( 0, ent->client->ps.fd.forcePowerMax, atoi( args ) ); + if (give_all || !Q_stricmp(name, "force")) { + if (argc == 3) + ent->client->ps.fd.forcePower = Com_Clampi(0, ent->client->ps.fd.forcePowerMax, atoi(args)); else ent->client->ps.fd.forcePower = ent->client->ps.fd.forcePowerMax; - if ( !give_all ) + if (!give_all) return; } - if ( give_all || !Q_stricmp( name, "weapons" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] = (1 << (LAST_USEABLE_WEAPON+1)) - ( 1 << WP_NONE ); - if ( !give_all ) + if (give_all || !Q_stricmp(name, "weapons")) { + ent->client->ps.stats[STAT_WEAPONS] = (1 << (LAST_USEABLE_WEAPON + 1)) - (1 << WP_NONE); + if (!give_all) return; } - if ( !give_all && !Q_stricmp( name, "weaponnum" ) ) - { - ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi( args )); + if (!give_all && !Q_stricmp(name, "weaponnum")) { + ent->client->ps.stats[STAT_WEAPONS] |= (1 << atoi(args)); return; } - if ( give_all || !Q_stricmp( name, "ammo" ) ) - { + if (give_all || !Q_stricmp(name, "ammo")) { int num = 999; - if ( argc == 3 ) - num = Com_Clampi( 0, 999, atoi( args ) ); - for ( i=AMMO_BLASTER; iclient->ps.ammo[i] = num; - if ( !give_all ) + if (!give_all) return; } - if ( !Q_stricmp( name, "excellent" ) ) { + if (!Q_stricmp(name, "excellent")) { ent->client->ps.persistant[PERS_EXCELLENT_COUNT]++; return; } - if ( !Q_stricmp( name, "impressive" ) ) { + if (!Q_stricmp(name, "impressive")) { ent->client->ps.persistant[PERS_IMPRESSIVE_COUNT]++; return; } - if ( !Q_stricmp( name, "gauntletaward" ) ) { + if (!Q_stricmp(name, "gauntletaward")) { ent->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT]++; return; } - if ( !Q_stricmp( name, "defend" ) ) { + if (!Q_stricmp(name, "defend")) { ent->client->ps.persistant[PERS_DEFEND_COUNT]++; return; } - if ( !Q_stricmp( name, "assist" ) ) { + if (!Q_stricmp(name, "assist")) { ent->client->ps.persistant[PERS_ASSIST_COUNT]++; return; } // spawn a specific item right on the player - if ( !give_all ) { - it = BG_FindItem( name ); - if ( !it ) + if (!give_all) { + it = BG_FindItem(name); + if (!it) return; it_ent = G_Spawn(); - VectorCopy( ent->r.currentOrigin, it_ent->s.origin ); + VectorCopy(ent->r.currentOrigin, it_ent->s.origin); it_ent->classname = it->classname; - G_SpawnItem( it_ent, it ); - if ( !it_ent || !it_ent->inuse ) + G_SpawnItem(it_ent, it); + if (!it_ent || !it_ent->inuse) return; - FinishSpawningItem( it_ent ); - if ( !it_ent || !it_ent->inuse ) + FinishSpawningItem(it_ent); + if (!it_ent || !it_ent->inuse) return; - memset( &trace, 0, sizeof( trace ) ); - Touch_Item( it_ent, ent, &trace ); - if ( it_ent->inuse ) - G_FreeEntity( it_ent ); + memset(&trace, 0, sizeof(trace)); + Touch_Item(it_ent, ent, &trace); + if (it_ent->inuse) + G_FreeEntity(it_ent); } } -void Cmd_Give_f( gentity_t *ent ) -{ +void Cmd_Give_f(gentity_t *ent) { char name[MAX_TOKEN_CHARS] = {0}; - trap->Argv( 1, name, sizeof( name ) ); - G_Give( ent, name, ConcatArgs( 2 ), trap->Argc() ); + trap->Argv(1, name, sizeof(name)); + G_Give(ent, name, ConcatArgs(2), trap->Argc()); } -void Cmd_GiveOther_f( gentity_t *ent ) -{ - char name[MAX_TOKEN_CHARS] = {0}; - int i; - char otherindex[MAX_TOKEN_CHARS]; - gentity_t *otherEnt = NULL; +void Cmd_GiveOther_f(gentity_t *ent) { + char name[MAX_TOKEN_CHARS] = {0}; + int i; + char otherindex[MAX_TOKEN_CHARS]; + gentity_t *otherEnt = NULL; - if ( trap->Argc () < 3 ) { - trap->SendServerCommand( ent-g_entities, "print \"Usage: giveother \n\"" ); + if (trap->Argc() < 3) { + trap->SendServerCommand(ent - g_entities, "print \"Usage: giveother \n\""); return; } - trap->Argv( 1, otherindex, sizeof( otherindex ) ); - i = ClientNumberFromString( ent, otherindex, qfalse ); - if ( i == -1 ) { + trap->Argv(1, otherindex, sizeof(otherindex)); + i = ClientNumberFromString(ent, otherindex, qfalse); + if (i == -1) { return; } otherEnt = &g_entities[i]; - if ( !otherEnt->inuse || !otherEnt->client ) { + if (!otherEnt->inuse || !otherEnt->client) { return; } - if ( (otherEnt->health <= 0 || otherEnt->client->tempSpectate >= level.time || otherEnt->client->sess.sessionTeam == TEAM_SPECTATOR) ) - { + if ((otherEnt->health <= 0 || otherEnt->client->tempSpectate >= level.time || otherEnt->client->sess.sessionTeam == TEAM_SPECTATOR)) { // Intentionally displaying for the command user - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "MUSTBEALIVE" ) ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "MUSTBEALIVE"))); return; } - trap->Argv( 2, name, sizeof( name ) ); + trap->Argv(2, name, sizeof(name)); - G_Give( otherEnt, name, ConcatArgs( 3 ), trap->Argc()-1 ); + G_Give(otherEnt, name, ConcatArgs(3), trap->Argc() - 1); } /* @@ -401,19 +371,18 @@ Sets client to godmode argv(0) god ================== */ -void Cmd_God_f( gentity_t *ent ) { +void Cmd_God_f(gentity_t *ent) { char *msg = NULL; ent->flags ^= FL_GODMODE; - if ( !(ent->flags & FL_GODMODE) ) + if (!(ent->flags & FL_GODMODE)) msg = "godmode OFF"; else msg = "godmode ON"; - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", msg ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", msg)); } - /* ================== Cmd_Notarget_f @@ -423,19 +392,18 @@ Sets client to notarget argv(0) notarget ================== */ -void Cmd_Notarget_f( gentity_t *ent ) { +void Cmd_Notarget_f(gentity_t *ent) { char *msg = NULL; ent->flags ^= FL_NOTARGET; - if ( !(ent->flags & FL_NOTARGET) ) + if (!(ent->flags & FL_NOTARGET)) msg = "notarget OFF"; else msg = "notarget ON"; - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", msg ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", msg)); } - /* ================== Cmd_Noclip_f @@ -443,19 +411,18 @@ Cmd_Noclip_f argv(0) noclip ================== */ -void Cmd_Noclip_f( gentity_t *ent ) { +void Cmd_Noclip_f(gentity_t *ent) { char *msg = NULL; ent->client->noclip = !ent->client->noclip; - if ( !ent->client->noclip ) + if (!ent->client->noclip) msg = "noclip OFF"; else msg = "noclip ON"; - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", msg ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", msg)); } - /* ================== Cmd_LevelShot_f @@ -466,23 +433,20 @@ and sends over a command to the client to resize the view, hide the scoreboard, and take a special screenshot ================== */ -void Cmd_LevelShot_f( gentity_t *ent ) -{ - if ( !ent->client->pers.localClient ) - { - trap->SendServerCommand(ent-g_entities, "print \"The levelshot command must be executed by a local client\n\""); +void Cmd_LevelShot_f(gentity_t *ent) { + if (!ent->client->pers.localClient) { + trap->SendServerCommand(ent - g_entities, "print \"The levelshot command must be executed by a local client\n\""); return; } // doesn't work in single player - if ( level.gametype == GT_SINGLE_PLAYER ) - { - trap->SendServerCommand(ent-g_entities, "print \"Must not be in singleplayer mode for levelshot\n\"" ); + if (level.gametype == GT_SINGLE_PLAYER) { + trap->SendServerCommand(ent - g_entities, "print \"Must not be in singleplayer mode for levelshot\n\""); return; } BeginIntermission(); - trap->SendServerCommand( ent-g_entities, "clientLevelShot" ); + trap->SendServerCommand(ent - g_entities, "clientLevelShot"); } #if 0 @@ -512,20 +476,17 @@ void Cmd_TeamTask_f( gentity_t *ent ) { } #endif -void G_Kill( gentity_t *ent ) { - if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && - level.numPlayingClients > 1 && !level.warmupTime) - { - if (!g_allowDuelSuicide.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "ATTEMPTDUELKILL")) ); +void G_Kill(gentity_t *ent) { + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && level.numPlayingClients > 1 && !level.warmupTime) { + if (!g_allowDuelSuicide.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "ATTEMPTDUELKILL"))); return; } } ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = -999; - player_die (ent, ent, ent, 100000, MOD_SUICIDE); + player_die(ent, ent, ent, 100000, MOD_SUICIDE); } /* @@ -533,40 +494,36 @@ void G_Kill( gentity_t *ent ) { Cmd_Kill_f ================= */ -void Cmd_Kill_f( gentity_t *ent ) { - G_Kill( ent ); -} +void Cmd_Kill_f(gentity_t *ent) { G_Kill(ent); } -void Cmd_KillOther_f( gentity_t *ent ) -{ - int i; - char otherindex[MAX_TOKEN_CHARS]; - gentity_t *otherEnt = NULL; +void Cmd_KillOther_f(gentity_t *ent) { + int i; + char otherindex[MAX_TOKEN_CHARS]; + gentity_t *otherEnt = NULL; - if ( trap->Argc () < 2 ) { - trap->SendServerCommand( ent-g_entities, "print \"Usage: killother \n\"" ); + if (trap->Argc() < 2) { + trap->SendServerCommand(ent - g_entities, "print \"Usage: killother \n\""); return; } - trap->Argv( 1, otherindex, sizeof( otherindex ) ); - i = ClientNumberFromString( ent, otherindex, qfalse ); - if ( i == -1 ) { + trap->Argv(1, otherindex, sizeof(otherindex)); + i = ClientNumberFromString(ent, otherindex, qfalse); + if (i == -1) { return; } otherEnt = &g_entities[i]; - if ( !otherEnt->inuse || !otherEnt->client ) { + if (!otherEnt->inuse || !otherEnt->client) { return; } - if ( (otherEnt->health <= 0 || otherEnt->client->tempSpectate >= level.time || otherEnt->client->sess.sessionTeam == TEAM_SPECTATOR) ) - { + if ((otherEnt->health <= 0 || otherEnt->client->tempSpectate >= level.time || otherEnt->client->sess.sessionTeam == TEAM_SPECTATOR)) { // Intentionally displaying for the command user - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "MUSTBEALIVE" ) ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "MUSTBEALIVE"))); return; } - G_Kill( otherEnt ); + G_Kill(otherEnt); } /* @@ -576,51 +533,42 @@ BroadCastTeamChange Let everyone know about a team change ================= */ -void BroadcastTeamChange( gclient_t *client, int oldTeam ) -{ - client->ps.fd.forceDoInit = 1; //every time we change teams make sure our force powers are set right +void BroadcastTeamChange(gclient_t *client, int oldTeam) { + client->ps.fd.forceDoInit = 1; // every time we change teams make sure our force powers are set right - if (level.gametype == GT_SIEGE) - { //don't announce these things in siege + if (level.gametype == GT_SIEGE) { // don't announce these things in siege return; } - if ( client->sess.sessionTeam == TEAM_RED ) { - trap->SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", - client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEREDTEAM")) ); - } else if ( client->sess.sessionTeam == TEAM_BLUE ) { - trap->SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", - client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEBLUETEAM"))); - } else if ( client->sess.sessionTeam == TEAM_SPECTATOR && oldTeam != TEAM_SPECTATOR ) { - trap->SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", - client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHESPECTATORS"))); - } else if ( client->sess.sessionTeam == TEAM_FREE ) { - trap->SendServerCommand( -1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", - client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEBATTLE"))); + if (client->sess.sessionTeam == TEAM_RED) { + trap->SendServerCommand(-1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEREDTEAM"))); + } else if (client->sess.sessionTeam == TEAM_BLUE) { + trap->SendServerCommand(-1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEBLUETEAM"))); + } else if (client->sess.sessionTeam == TEAM_SPECTATOR && oldTeam != TEAM_SPECTATOR) { + trap->SendServerCommand(-1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHESPECTATORS"))); + } else if (client->sess.sessionTeam == TEAM_FREE) { + trap->SendServerCommand(-1, va("cp \"%s" S_COLOR_WHITE " %s\n\"", client->pers.netname, G_GetStringEdString("MP_SVGAME", "JOINEDTHEBATTLE"))); } - G_LogPrintf( "ChangeTeam: %i [%s] (%s) \"%s^7\" %s -> %s\n", (int)(client - level.clients), client->sess.IP, client->pers.guid, client->pers.netname, TeamName( oldTeam ), TeamName( client->sess.sessionTeam ) ); + G_LogPrintf("ChangeTeam: %i [%s] (%s) \"%s^7\" %s -> %s\n", (int)(client - level.clients), client->sess.IP, client->pers.guid, client->pers.netname, + TeamName(oldTeam), TeamName(client->sess.sessionTeam)); } -qboolean G_PowerDuelCheckFail(gentity_t *ent) -{ - int loners = 0; - int doubles = 0; +qboolean G_PowerDuelCheckFail(gentity_t *ent) { + int loners = 0; + int doubles = 0; - if (!ent->client || ent->client->sess.duelTeam == DUELTEAM_FREE) - { + if (!ent->client || ent->client->sess.duelTeam == DUELTEAM_FREE) { return qtrue; } G_PowerDuelCount(&loners, &doubles, qfalse); - if (ent->client->sess.duelTeam == DUELTEAM_LONE && loners >= 1) - { + if (ent->client->sess.duelTeam == DUELTEAM_LONE && loners >= 1) { return qtrue; } - if (ent->client->sess.duelTeam == DUELTEAM_DOUBLE && doubles >= 2) - { + if (ent->client->sess.duelTeam == DUELTEAM_DOUBLE && doubles >= 2) { return qtrue; } @@ -634,17 +582,16 @@ SetTeam */ qboolean g_dontPenalizeTeam = qfalse; qboolean g_preventTeamBegin = qfalse; -void SetTeam( gentity_t *ent, char *s ) { - int team, oldTeam; - gclient_t *client; - int clientNum; - spectatorState_t specState; - int specClient; - int teamLeader; +void SetTeam(gentity_t *ent, char *s) { + int team, oldTeam; + gclient_t *client; + int clientNum; + spectatorState_t specState; + int specClient; + int teamLeader; // fix: this prevents rare creation of invalid players - if (!ent->inuse) - { + if (!ent->inuse) { return; } @@ -656,30 +603,30 @@ void SetTeam( gentity_t *ent, char *s ) { clientNum = client - level.clients; specClient = 0; specState = SPECTATOR_NOT; - if ( !Q_stricmp( s, "scoreboard" ) || !Q_stricmp( s, "score" ) ) { + if (!Q_stricmp(s, "scoreboard") || !Q_stricmp(s, "score")) { team = TEAM_SPECTATOR; specState = SPECTATOR_FREE; // SPECTATOR_SCOREBOARD disabling this for now since it is totally broken on client side - } else if ( !Q_stricmp( s, "follow1" ) ) { + } else if (!Q_stricmp(s, "follow1")) { team = TEAM_SPECTATOR; specState = SPECTATOR_FOLLOW; specClient = -1; - } else if ( !Q_stricmp( s, "follow2" ) ) { + } else if (!Q_stricmp(s, "follow2")) { team = TEAM_SPECTATOR; specState = SPECTATOR_FOLLOW; specClient = -2; - } else if ( !Q_stricmp( s, "spectator" ) || !Q_stricmp( s, "s" ) ) { + } else if (!Q_stricmp(s, "spectator") || !Q_stricmp(s, "s")) { team = TEAM_SPECTATOR; specState = SPECTATOR_FREE; - } else if ( level.gametype >= GT_TEAM ) { + } else if (level.gametype >= GT_TEAM) { // if running a team game, assign player to one of the teams specState = SPECTATOR_NOT; - if ( !Q_stricmp( s, "red" ) || !Q_stricmp( s, "r" ) ) { + if (!Q_stricmp(s, "red") || !Q_stricmp(s, "r")) { team = TEAM_RED; - } else if ( !Q_stricmp( s, "blue" ) || !Q_stricmp( s, "b" ) ) { + } else if (!Q_stricmp(s, "blue") || !Q_stricmp(s, "b")) { team = TEAM_BLUE; } else { // pick the team with the least number of players - //For now, don't do this. The legalize function will set powers properly now. + // For now, don't do this. The legalize function will set powers properly now. /* if (g_forceBasedTeams.integer) { @@ -695,20 +642,20 @@ void SetTeam( gentity_t *ent, char *s ) { else { */ - team = PickTeam( clientNum ); + team = PickTeam(clientNum); //} } - if ( g_teamForceBalance.integer && !g_jediVmerc.integer ) { - int counts[TEAM_NUM_TEAMS]; + if (g_teamForceBalance.integer && !g_jediVmerc.integer) { + int counts[TEAM_NUM_TEAMS]; - //JAC: Invalid clientNum was being used - counts[TEAM_BLUE] = TeamCount( ent-g_entities, TEAM_BLUE ); - counts[TEAM_RED] = TeamCount( ent-g_entities, TEAM_RED ); + // JAC: Invalid clientNum was being used + counts[TEAM_BLUE] = TeamCount(ent - g_entities, TEAM_BLUE); + counts[TEAM_RED] = TeamCount(ent - g_entities, TEAM_RED); // We allow a spread of two - if ( team == TEAM_RED && counts[TEAM_RED] - counts[TEAM_BLUE] > 1 ) { - //For now, don't do this. The legalize function will set powers properly now. + if (team == TEAM_RED && counts[TEAM_RED] - counts[TEAM_BLUE] > 1) { + // For now, don't do this. The legalize function will set powers properly now. /* if (g_forceBasedTeams.integer && ent->client->ps.fd.forceSide == FORCE_DARKSIDE) { @@ -718,14 +665,13 @@ void SetTeam( gentity_t *ent, char *s ) { else */ { - //JAC: Invalid clientNum was being used - trap->SendServerCommand( ent-g_entities, - va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TOOMANYRED")) ); + // JAC: Invalid clientNum was being used + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TOOMANYRED"))); } return; // ignore the request } - if ( team == TEAM_BLUE && counts[TEAM_BLUE] - counts[TEAM_RED] > 1 ) { - //For now, don't do this. The legalize function will set powers properly now. + if (team == TEAM_BLUE && counts[TEAM_BLUE] - counts[TEAM_RED] > 1) { + // For now, don't do this. The legalize function will set powers properly now. /* if (g_forceBasedTeams.integer && ent->client->ps.fd.forceSide == FORCE_LIGHTSIDE) { @@ -735,9 +681,8 @@ void SetTeam( gentity_t *ent, char *s ) { else */ { - //JAC: Invalid clientNum was being used - trap->SendServerCommand( ent-g_entities, - va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TOOMANYBLUE")) ); + // JAC: Invalid clientNum was being used + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TOOMANYBLUE"))); } return; // ignore the request } @@ -745,7 +690,7 @@ void SetTeam( gentity_t *ent, char *s ) { // It's ok, the team we are switching to has less or same number of players } - //For now, don't do this. The legalize function will set powers properly now. + // For now, don't do this. The legalize function will set powers properly now. /* if (g_forceBasedTeams.integer) { @@ -769,19 +714,16 @@ void SetTeam( gentity_t *ent, char *s ) { oldTeam = client->sess.sessionTeam; - if (level.gametype == GT_SIEGE) - { - if (client->tempSpectate >= level.time && - team == TEAM_SPECTATOR) - { //sorry, can't do that. + if (level.gametype == GT_SIEGE) { + if (client->tempSpectate >= level.time && team == TEAM_SPECTATOR) { // sorry, can't do that. return; } - if ( team == oldTeam && team != TEAM_SPECTATOR ) + if (team == oldTeam && team != TEAM_SPECTATOR) return; client->sess.siegeDesiredTeam = team; - //oh well, just let them go. + // oh well, just let them go. /* if (team != TEAM_SPECTATOR) { //can't switch to anything in siege unless you want to switch to being a fulltime spectator @@ -793,32 +735,25 @@ void SetTeam( gentity_t *ent, char *s ) { } */ if (client->sess.sessionTeam != TEAM_SPECTATOR && - team != TEAM_SPECTATOR) - { //not a spectator now, and not switching to spec, so you have to wait til you die. - //trap->SendServerCommand( ent-g_entities, va("print \"You will be on the selected team the next time you respawn.\n\"") ); + team != TEAM_SPECTATOR) { // not a spectator now, and not switching to spec, so you have to wait til you die. + // trap->SendServerCommand( ent-g_entities, va("print \"You will be on the selected team the next time you respawn.\n\"") ); qboolean doBegin; - if (ent->client->tempSpectate >= level.time) - { + if (ent->client->tempSpectate >= level.time) { doBegin = qfalse; - } - else - { + } else { doBegin = qtrue; } - if (doBegin) - { + if (doBegin) { // Kill them so they automatically respawn in the team they wanted. - if (ent->health > 0) - { + if (ent->health > 0) { ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = 0; - player_die( ent, ent, ent, 100000, MOD_TEAM_CHANGE ); + player_die(ent, ent, ent, 100000, MOD_TEAM_CHANGE); } } - if (ent->client->sess.sessionTeam != ent->client->sess.siegeDesiredTeam) - { + if (ent->client->sess.sessionTeam != ent->client->sess.siegeDesiredTeam) { SetTeamQuick(ent, ent->client->sess.siegeDesiredTeam, qfalse); } @@ -827,26 +762,18 @@ void SetTeam( gentity_t *ent, char *s ) { } // override decision if limiting the players - if ( (level.gametype == GT_DUEL) - && level.numNonSpectatorClients >= 2 ) - { + if ((level.gametype == GT_DUEL) && level.numNonSpectatorClients >= 2) { team = TEAM_SPECTATOR; - } - else if ( (level.gametype == GT_POWERDUEL) - && (level.numPlayingClients >= 3 || G_PowerDuelCheckFail(ent)) ) - { + } else if ((level.gametype == GT_POWERDUEL) && (level.numPlayingClients >= 3 || G_PowerDuelCheckFail(ent))) { team = TEAM_SPECTATOR; - } - else if ( g_maxGameClients.integer > 0 && - level.numNonSpectatorClients >= g_maxGameClients.integer ) - { + } else if (g_maxGameClients.integer > 0 && level.numNonSpectatorClients >= g_maxGameClients.integer) { team = TEAM_SPECTATOR; } // // decide if we will allow the change // - if ( team == oldTeam && team != TEAM_SPECTATOR ) { + if (team == oldTeam && team != TEAM_SPECTATOR) { return; } @@ -854,72 +781,69 @@ void SetTeam( gentity_t *ent, char *s ) { // execute the team change // - //If it's siege then show the mission briefing for the team you just joined. -// if (level.gametype == GT_SIEGE && team != TEAM_SPECTATOR) -// { -// trap->SendServerCommand(clientNum, va("sb %i", team)); -// } + // If it's siege then show the mission briefing for the team you just joined. + // if (level.gametype == GT_SIEGE && team != TEAM_SPECTATOR) + // { + // trap->SendServerCommand(clientNum, va("sb %i", team)); + // } // if the player was dead leave the body - if ( client->ps.stats[STAT_HEALTH] <= 0 && client->sess.sessionTeam != TEAM_SPECTATOR ) { + if (client->ps.stats[STAT_HEALTH] <= 0 && client->sess.sessionTeam != TEAM_SPECTATOR) { MaintainBodyQueue(ent); } // he starts at 'base' client->pers.teamState.state = TEAM_BEGIN; - if ( oldTeam != TEAM_SPECTATOR ) { + if (oldTeam != TEAM_SPECTATOR) { // Kill him (makes sure he loses flags, etc) ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = 0; g_dontPenalizeTeam = qtrue; - player_die (ent, ent, ent, 100000, MOD_SUICIDE); + player_die(ent, ent, ent, 100000, MOD_SUICIDE); g_dontPenalizeTeam = qfalse; - } // they go to the end of the line for tournaments - if ( team == TEAM_SPECTATOR && oldTeam != team ) - AddTournamentQueue( client ); + if (team == TEAM_SPECTATOR && oldTeam != team) + AddTournamentQueue(client); // clear votes if going to spectator (specs can't vote) - if ( team == TEAM_SPECTATOR ) - G_ClearVote( ent ); + if (team == TEAM_SPECTATOR) + G_ClearVote(ent); // also clear team votes if switching red/blue or going to spec - G_ClearTeamVote( ent, oldTeam ); + G_ClearTeamVote(ent, oldTeam); client->sess.sessionTeam = (team_t)team; client->sess.spectatorState = specState; client->sess.spectatorClient = specClient; client->sess.teamLeader = qfalse; - if ( team == TEAM_RED || team == TEAM_BLUE ) { - teamLeader = TeamLeader( team ); + if (team == TEAM_RED || team == TEAM_BLUE) { + teamLeader = TeamLeader(team); // if there is no team leader or the team leader is a bot and this client is not a bot - if ( teamLeader == -1 || ( !(g_entities[clientNum].r.svFlags & SVF_BOT) && (g_entities[teamLeader].r.svFlags & SVF_BOT) ) ) { - //SetLeader( team, clientNum ); + if (teamLeader == -1 || (!(g_entities[clientNum].r.svFlags & SVF_BOT) && (g_entities[teamLeader].r.svFlags & SVF_BOT))) { + // SetLeader( team, clientNum ); } } // make sure there is a team leader on the team the player came from - if ( oldTeam == TEAM_RED || oldTeam == TEAM_BLUE ) { - CheckTeamLeader( oldTeam ); + if (oldTeam == TEAM_RED || oldTeam == TEAM_BLUE) { + CheckTeamLeader(oldTeam); } - BroadcastTeamChange( client, oldTeam ); + BroadcastTeamChange(client, oldTeam); - //make a disappearing effect where they were before teleporting them to the appropriate spawn point, - //if we were not on the spec team - if (oldTeam != TEAM_SPECTATOR) - { - gentity_t *tent = G_TempEntity( client->ps.origin, EV_PLAYER_TELEPORT_OUT ); + // make a disappearing effect where they were before teleporting them to the appropriate spawn point, + // if we were not on the spec team + if (oldTeam != TEAM_SPECTATOR) { + gentity_t *tent = G_TempEntity(client->ps.origin, EV_PLAYER_TELEPORT_OUT); tent->s.clientNum = clientNum; } // get and distribute relevent paramters - if ( !ClientUserinfoChanged( clientNum ) ) + if (!ClientUserinfoChanged(clientNum)) return; - if (!g_preventTeamBegin) - { - ClientBegin( clientNum, qfalse ); + if (!g_preventTeamBegin) { + ClientBegin(clientNum, qfalse); } } @@ -931,19 +855,19 @@ If the client being followed leaves the game, or you just want to drop to free floating spectator mode ================= */ -extern void G_LeaveVehicle( gentity_t *ent, qboolean ConCheck ); -void StopFollowing( gentity_t *ent ) { - int i=0; - ent->client->ps.persistant[ PERS_TEAM ] = TEAM_SPECTATOR; +extern void G_LeaveVehicle(gentity_t *ent, qboolean ConCheck); +void StopFollowing(gentity_t *ent) { + int i = 0; + ent->client->ps.persistant[PERS_TEAM] = TEAM_SPECTATOR; ent->client->sess.sessionTeam = TEAM_SPECTATOR; ent->client->sess.spectatorState = SPECTATOR_FREE; ent->client->ps.pm_flags &= ~PMF_FOLLOW; ent->r.svFlags &= ~SVF_BOT; ent->client->ps.clientNum = ent - g_entities; ent->client->ps.weapon = WP_NONE; - G_LeaveVehicle( ent, qfalse ); // clears m_iVehicleNum as well + G_LeaveVehicle(ent, qfalse); // clears m_iVehicleNum as well ent->client->ps.emplacedIndex = 0; - //ent->client->ps.m_iVehicleNum = 0; + // ent->client->ps.m_iVehicleNum = 0; ent->client->ps.viewangles[ROLL] = 0.0f; ent->client->ps.forceHandExtend = HANDEXTEND_NONE; ent->client->ps.forceHandExtendTime = 0; @@ -955,14 +879,14 @@ void StopFollowing( gentity_t *ent ) { ent->client->ps.legsTimer = 0; ent->client->ps.torsoAnim = 0; ent->client->ps.torsoTimer = 0; - ent->client->ps.isJediMaster = qfalse; // major exploit if you are spectating somebody and they are JM and you reconnect - ent->client->ps.cloakFuel = 100; // so that fuel goes away after stop following them - ent->client->ps.jetpackFuel = 100; // so that fuel goes away after stop following them + ent->client->ps.isJediMaster = qfalse; // major exploit if you are spectating somebody and they are JM and you reconnect + ent->client->ps.cloakFuel = 100; // so that fuel goes away after stop following them + ent->client->ps.jetpackFuel = 100; // so that fuel goes away after stop following them ent->health = ent->client->ps.stats[STAT_HEALTH] = 100; // so that you don't keep dead angles if you were spectating a dead person ent->client->ps.bobCycle = 0; ent->client->ps.pm_type = PM_SPECTATOR; ent->client->ps.eFlags &= ~EF_DISINTEGRATION; - for ( i=0; iclient->ps.powerups[i] = 0; } @@ -971,59 +895,56 @@ void StopFollowing( gentity_t *ent ) { Cmd_Team_f ================= */ -void Cmd_Team_f( gentity_t *ent ) { - int oldTeam; - char s[MAX_TOKEN_CHARS]; +void Cmd_Team_f(gentity_t *ent) { + int oldTeam; + char s[MAX_TOKEN_CHARS]; oldTeam = ent->client->sess.sessionTeam; - if ( trap->Argc() != 2 ) { - switch ( oldTeam ) { + if (trap->Argc() != 2) { + switch (oldTeam) { case TEAM_BLUE: - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTBLUETEAM")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTBLUETEAM"))); break; case TEAM_RED: - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTREDTEAM")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTREDTEAM"))); break; case TEAM_FREE: - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTFREETEAM")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTFREETEAM"))); break; case TEAM_SPECTATOR: - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTSPECTEAM")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PRINTSPECTEAM"))); break; } return; } - if ( ent->client->switchTeamTime > level.time ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH")) ); + if (ent->client->switchTeamTime > level.time) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH"))); return; } - if (gEscaping) - { + if (gEscaping) { return; } // if they are playing a tournament game, count as a loss - if ( level.gametype == GT_DUEL - && ent->client->sess.sessionTeam == TEAM_FREE ) {//in a tournament game - //disallow changing teams - trap->SendServerCommand( ent-g_entities, "print \"Cannot switch teams in Duel\n\"" ); + if (level.gametype == GT_DUEL && ent->client->sess.sessionTeam == TEAM_FREE) { // in a tournament game + // disallow changing teams + trap->SendServerCommand(ent - g_entities, "print \"Cannot switch teams in Duel\n\""); return; - //FIXME: why should this be a loss??? - //ent->client->sess.losses++; + // FIXME: why should this be a loss??? + // ent->client->sess.losses++; } - if (level.gametype == GT_POWERDUEL) - { //don't let clients change teams manually at all in powerduel, it will be taken care of through automated stuff - trap->SendServerCommand( ent-g_entities, "print \"Cannot switch teams in Power Duel\n\"" ); + if (level.gametype == GT_POWERDUEL) { // don't let clients change teams manually at all in powerduel, it will be taken care of through automated stuff + trap->SendServerCommand(ent - g_entities, "print \"Cannot switch teams in Power Duel\n\""); return; } - trap->Argv( 1, s, sizeof( s ) ); + trap->Argv(1, s, sizeof(s)); - SetTeam( ent, s ); + SetTeam(ent, s); // fix: update team switch time only if team change really happend if (oldTeam != ent->client->sess.sessionTeam) @@ -1035,13 +956,11 @@ void Cmd_Team_f( gentity_t *ent ) { Cmd_DuelTeam_f ================= */ -void Cmd_DuelTeam_f(gentity_t *ent) -{ - int oldTeam; - char s[MAX_TOKEN_CHARS]; +void Cmd_DuelTeam_f(gentity_t *ent) { + int oldTeam; + char s[MAX_TOKEN_CHARS]; - if (level.gametype != GT_POWERDUEL) - { //don't bother doing anything if this is not power duel + if (level.gametype != GT_POWERDUEL) { // don't bother doing anything if this is not power duel return; } @@ -1053,19 +972,17 @@ void Cmd_DuelTeam_f(gentity_t *ent) } */ - if ( trap->Argc() != 2 ) - { //No arg so tell what team we're currently on. + if (trap->Argc() != 2) { // No arg so tell what team we're currently on. oldTeam = ent->client->sess.duelTeam; - switch ( oldTeam ) - { + switch (oldTeam) { case DUELTEAM_FREE: - trap->SendServerCommand( ent-g_entities, va("print \"None\n\"") ); + trap->SendServerCommand(ent - g_entities, va("print \"None\n\"")); break; case DUELTEAM_LONE: - trap->SendServerCommand( ent-g_entities, va("print \"Single\n\"") ); + trap->SendServerCommand(ent - g_entities, va("print \"Single\n\"")); break; case DUELTEAM_DOUBLE: - trap->SendServerCommand( ent-g_entities, va("print \"Double\n\"") ); + trap->SendServerCommand(ent - g_entities, va("print \"Double\n\"")); break; default: break; @@ -1073,85 +990,68 @@ void Cmd_DuelTeam_f(gentity_t *ent) return; } - if ( ent->client->switchDuelTeamTime > level.time ) - { //debounce for changing - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH")) ); + if (ent->client->switchDuelTeamTime > level.time) { // debounce for changing + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH"))); return; } - trap->Argv( 1, s, sizeof( s ) ); + trap->Argv(1, s, sizeof(s)); oldTeam = ent->client->sess.duelTeam; - if (!Q_stricmp(s, "free")) - { + if (!Q_stricmp(s, "free")) { ent->client->sess.duelTeam = DUELTEAM_FREE; - } - else if (!Q_stricmp(s, "single")) - { + } else if (!Q_stricmp(s, "single")) { ent->client->sess.duelTeam = DUELTEAM_LONE; - } - else if (!Q_stricmp(s, "double")) - { + } else if (!Q_stricmp(s, "double")) { ent->client->sess.duelTeam = DUELTEAM_DOUBLE; - } - else - { - trap->SendServerCommand( ent-g_entities, va("print \"'%s' not a valid duel team.\n\"", s) ); + } else { + trap->SendServerCommand(ent - g_entities, va("print \"'%s' not a valid duel team.\n\"", s)); } - if (oldTeam == ent->client->sess.duelTeam) - { //didn't actually change, so don't care. + if (oldTeam == ent->client->sess.duelTeam) { // didn't actually change, so don't care. return; } - if (ent->client->sess.sessionTeam != TEAM_SPECTATOR) - { //ok..die + if (ent->client->sess.sessionTeam != TEAM_SPECTATOR) { // ok..die int curTeam = ent->client->sess.duelTeam; ent->client->sess.duelTeam = oldTeam; G_Damage(ent, ent, ent, NULL, ent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); ent->client->sess.duelTeam = curTeam; } - //reset wins and losses + // reset wins and losses ent->client->sess.wins = 0; ent->client->sess.losses = 0; - //get and distribute relevent paramters - if ( ClientUserinfoChanged( ent->s.number ) ) + // get and distribute relevent paramters + if (ClientUserinfoChanged(ent->s.number)) return; ent->client->switchDuelTeamTime = level.time + 5000; } -int G_TeamForSiegeClass(const char *clName) -{ +int G_TeamForSiegeClass(const char *clName) { int i = 0; int team = SIEGETEAM_TEAM1; siegeTeam_t *stm = BG_SiegeFindThemeForTeam(team); siegeClass_t *scl; - if (!stm) - { + if (!stm) { return 0; } - while (team <= SIEGETEAM_TEAM2) - { + while (team <= SIEGETEAM_TEAM2) { scl = stm->classes[i]; - if (scl && scl->name[0]) - { - if (!Q_stricmp(clName, scl->name)) - { + if (scl && scl->name[0]) { + if (!Q_stricmp(clName, scl->name)) { return team; } } i++; - if (i >= MAX_SIEGE_CLASSES || i >= stm->numClasses) - { - if (team == SIEGETEAM_TEAM2) - { + if (i >= MAX_SIEGE_CLASSES || i >= stm->numClasses) { + if (team == SIEGETEAM_TEAM2) { break; } team = SIEGETEAM_TEAM2; @@ -1168,101 +1068,84 @@ int G_TeamForSiegeClass(const char *clName) Cmd_SiegeClass_f ================= */ -void Cmd_SiegeClass_f( gentity_t *ent ) -{ +void Cmd_SiegeClass_f(gentity_t *ent) { char className[64]; int team = 0; int preScore; qboolean startedAsSpec = qfalse; - if (level.gametype != GT_SIEGE) - { //classes are only valid for this gametype + if (level.gametype != GT_SIEGE) { // classes are only valid for this gametype return; } - if (!ent->client) - { + if (!ent->client) { return; } - if (trap->Argc() < 1) - { + if (trap->Argc() < 1) { return; } - if ( ent->client->switchClassTime > level.time ) - { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOCLASSSWITCH")) ); + if (ent->client->switchClassTime > level.time) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOCLASSSWITCH"))); return; } - if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { startedAsSpec = qtrue; } - trap->Argv( 1, className, sizeof( className ) ); + trap->Argv(1, className, sizeof(className)); team = G_TeamForSiegeClass(className); - if (!team) - { //not a valid class name + if (!team) { // not a valid class name return; } - if (ent->client->sess.sessionTeam != team) - { //try changing it then + if (ent->client->sess.sessionTeam != team) { // try changing it then g_preventTeamBegin = qtrue; - if (team == TEAM_RED) - { + if (team == TEAM_RED) { SetTeam(ent, "red"); - } - else if (team == TEAM_BLUE) - { + } else if (team == TEAM_BLUE) { SetTeam(ent, "blue"); } g_preventTeamBegin = qfalse; - if (ent->client->sess.sessionTeam != team) - { //failed, oh well - if (ent->client->sess.sessionTeam != TEAM_SPECTATOR || - ent->client->sess.siegeDesiredTeam != team) - { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOCLASSTEAM")) ); + if (ent->client->sess.sessionTeam != team) { // failed, oh well + if (ent->client->sess.sessionTeam != TEAM_SPECTATOR || ent->client->sess.siegeDesiredTeam != team) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOCLASSTEAM"))); return; } } } - //preserve 'is score + // preserve 'is score preScore = ent->client->ps.persistant[PERS_SCORE]; - //Make sure the class is valid for the team + // Make sure the class is valid for the team BG_SiegeCheckClassLegality(team, className); - //Set the session data + // Set the session data strcpy(ent->client->sess.siegeClass, className); // get and distribute relevent paramters - if ( !ClientUserinfoChanged( ent->s.number ) ) + if (!ClientUserinfoChanged(ent->s.number)) return; - if (ent->client->tempSpectate < level.time) - { + if (ent->client->tempSpectate < level.time) { // Kill him (makes sure he loses flags, etc) - if (ent->health > 0 && !startedAsSpec) - { + if (ent->health > 0 && !startedAsSpec) { ent->flags &= ~FL_GODMODE; ent->client->ps.stats[STAT_HEALTH] = ent->health = 0; - player_die (ent, ent, ent, 100000, MOD_SUICIDE); + player_die(ent, ent, ent, 100000, MOD_SUICIDE); } - if (ent->client->sess.sessionTeam == TEAM_SPECTATOR || startedAsSpec) - { //respawn them instantly. - ClientBegin( ent->s.number, qfalse ); + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR || startedAsSpec) { // respawn them instantly. + ClientBegin(ent->s.number, qfalse); } } - //set it back after we do all the stuff + // set it back after we do all the stuff ent->client->ps.persistant[PERS_SCORE] = preScore; ent->client->switchClassTime = level.time + 5000; @@ -1273,16 +1156,14 @@ void Cmd_SiegeClass_f( gentity_t *ent ) Cmd_ForceChanged_f ================= */ -void Cmd_ForceChanged_f( gentity_t *ent ) -{ +void Cmd_ForceChanged_f(gentity_t *ent) { char fpChStr[1024]; const char *buf; -// Cmd_Kill_f(ent); - if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) - { //if it's a spec, just make the changes now - //trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "FORCEAPPLIED")) ); - //No longer print it, as the UI calls this a lot. - WP_InitForcePowers( ent ); + // Cmd_Kill_f(ent); + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { // if it's a spec, just make the changes now + // trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "FORCEAPPLIED")) ); + // No longer print it, as the UI calls this a lot. + WP_InitForcePowers(ent); goto argCheck; } @@ -1290,67 +1171,59 @@ void Cmd_ForceChanged_f( gentity_t *ent ) strcpy(fpChStr, buf); - trap->SendServerCommand( ent-g_entities, va("print \"%s%s\n\"", S_COLOR_GREEN, fpChStr) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s%s\n\"", S_COLOR_GREEN, fpChStr)); ent->client->ps.fd.forceDoInit = 1; argCheck: - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { //If this is duel, don't even bother changing team in relation to this. + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // If this is duel, don't even bother changing team in relation to this. return; } - if (trap->Argc() > 1) - { - char arg[MAX_TOKEN_CHARS]; + if (trap->Argc() > 1) { + char arg[MAX_TOKEN_CHARS]; - trap->Argv( 1, arg, sizeof( arg ) ); + trap->Argv(1, arg, sizeof(arg)); - if ( arg[0] ) - { //if there's an arg, assume it's a combo team command from the UI. + if (arg[0]) { // if there's an arg, assume it's a combo team command from the UI. Cmd_Team_f(ent); } } } -extern qboolean WP_SaberStyleValidForSaber( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel ); -extern qboolean WP_UseFirstValidSaberStyle( saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel ); -qboolean G_SetSaber(gentity_t *ent, int saberNum, char *saberName, qboolean siegeOverride) -{ +extern qboolean WP_SaberStyleValidForSaber(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int saberAnimLevel); +extern qboolean WP_UseFirstValidSaberStyle(saberInfo_t *saber1, saberInfo_t *saber2, int saberHolstered, int *saberAnimLevel); +qboolean G_SetSaber(gentity_t *ent, int saberNum, char *saberName, qboolean siegeOverride) { char truncSaberName[MAX_QPATH] = {0}; - if ( !siegeOverride && level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && - (bgSiegeClasses[ent->client->siegeClass].saberStance || bgSiegeClasses[ent->client->siegeClass].saber1[0] || bgSiegeClasses[ent->client->siegeClass].saber2[0]) ) - { //don't let it be changed if the siege class has forced any saber-related things + if (!siegeOverride && level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && + (bgSiegeClasses[ent->client->siegeClass].saberStance || bgSiegeClasses[ent->client->siegeClass].saber1[0] || + bgSiegeClasses[ent->client->siegeClass].saber2[0])) { // don't let it be changed if the siege class has forced any saber-related things return qfalse; } - Q_strncpyz( truncSaberName, saberName, sizeof( truncSaberName ) ); + Q_strncpyz(truncSaberName, saberName, sizeof(truncSaberName)); - if ( saberNum == 0 && (!Q_stricmp( "none", truncSaberName ) || !Q_stricmp( "remove", truncSaberName )) ) - { //can't remove saber 0 like this - Q_strncpyz( truncSaberName, DEFAULT_SABER, sizeof( truncSaberName ) ); + if (saberNum == 0 && (!Q_stricmp("none", truncSaberName) || !Q_stricmp("remove", truncSaberName))) { // can't remove saber 0 like this + Q_strncpyz(truncSaberName, DEFAULT_SABER, sizeof(truncSaberName)); } - //Set the saber with the arg given. If the arg is - //not a valid sabername defaults will be used. - WP_SetSaber( ent->s.number, ent->client->saber, saberNum, truncSaberName ); + // Set the saber with the arg given. If the arg is + // not a valid sabername defaults will be used. + WP_SetSaber(ent->s.number, ent->client->saber, saberNum, truncSaberName); - if ( !ent->client->saber[0].model[0] ) - { - assert(0); //should never happen! - Q_strncpyz( ent->client->pers.saber1, DEFAULT_SABER, sizeof( ent->client->pers.saber1 ) ); - } - else - Q_strncpyz( ent->client->pers.saber1, ent->client->saber[0].name, sizeof( ent->client->pers.saber1 ) ); + if (!ent->client->saber[0].model[0]) { + assert(0); // should never happen! + Q_strncpyz(ent->client->pers.saber1, DEFAULT_SABER, sizeof(ent->client->pers.saber1)); + } else + Q_strncpyz(ent->client->pers.saber1, ent->client->saber[0].name, sizeof(ent->client->pers.saber1)); - if ( !ent->client->saber[1].model[0] ) - Q_strncpyz( ent->client->pers.saber2, "none", sizeof( ent->client->pers.saber2 ) ); + if (!ent->client->saber[1].model[0]) + Q_strncpyz(ent->client->pers.saber2, "none", sizeof(ent->client->pers.saber2)); else - Q_strncpyz( ent->client->pers.saber2, ent->client->saber[1].name, sizeof( ent->client->pers.saber2 ) ); + Q_strncpyz(ent->client->pers.saber2, ent->client->saber[1].name, sizeof(ent->client->pers.saber2)); - if ( !WP_SaberStyleValidForSaber( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, ent->client->ps.fd.saberAnimLevel ) ) - { - WP_UseFirstValidSaberStyle( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &ent->client->ps.fd.saberAnimLevel ); + if (!WP_SaberStyleValidForSaber(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, ent->client->ps.fd.saberAnimLevel)) { + WP_UseFirstValidSaberStyle(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &ent->client->ps.fd.saberAnimLevel); ent->client->ps.fd.saberAnimLevelBase = ent->client->saberCycleQueue = ent->client->ps.fd.saberAnimLevel; } @@ -1362,52 +1235,51 @@ qboolean G_SetSaber(gentity_t *ent, int saberNum, char *saberName, qboolean sieg Cmd_Follow_f ================= */ -void Cmd_Follow_f( gentity_t *ent ) { - int i; - char arg[MAX_TOKEN_CHARS]; +void Cmd_Follow_f(gentity_t *ent) { + int i; + char arg[MAX_TOKEN_CHARS]; - if ( ent->client->sess.spectatorState == SPECTATOR_NOT && ent->client->switchTeamTime > level.time ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH")) ); + if (ent->client->sess.spectatorState == SPECTATOR_NOT && ent->client->switchTeamTime > level.time) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH"))); return; } - if ( trap->Argc() != 2 ) { - if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) { - StopFollowing( ent ); + if (trap->Argc() != 2) { + if (ent->client->sess.spectatorState == SPECTATOR_FOLLOW) { + StopFollowing(ent); } return; } - trap->Argv( 1, arg, sizeof( arg ) ); - i = ClientNumberFromString( ent, arg, qfalse ); - if ( i == -1 ) { + trap->Argv(1, arg, sizeof(arg)); + i = ClientNumberFromString(ent, arg, qfalse); + if (i == -1) { return; } // can't follow self - if ( &level.clients[ i ] == ent->client ) { + if (&level.clients[i] == ent->client) { return; } // can't follow another spectator - if ( level.clients[ i ].sess.sessionTeam == TEAM_SPECTATOR ) { + if (level.clients[i].sess.sessionTeam == TEAM_SPECTATOR) { return; } - if ( level.clients[ i ].tempSpectate >= level.time ) { + if (level.clients[i].tempSpectate >= level.time) { return; } // if they are playing a tournament game, count as a loss - if ( (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - && ent->client->sess.sessionTeam == TEAM_FREE ) { - //WTF??? + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && ent->client->sess.sessionTeam == TEAM_FREE) { + // WTF??? ent->client->sess.losses++; } // first set them to spectator - if ( ent->client->sess.sessionTeam != TEAM_SPECTATOR ) { - SetTeam( ent, "spectator" ); + if (ent->client->sess.sessionTeam != TEAM_SPECTATOR) { + SetTeam(ent, "spectator"); // fix: update team switch time only if team change really happend if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) ent->client->switchTeamTime = level.time + 5000; @@ -1422,32 +1294,30 @@ void Cmd_Follow_f( gentity_t *ent ) { Cmd_FollowCycle_f ================= */ -void Cmd_FollowCycle_f( gentity_t *ent, int dir ) { - int clientnum; - int original; - qboolean looped = qfalse; +void Cmd_FollowCycle_f(gentity_t *ent, int dir) { + int clientnum; + int original; + qboolean looped = qfalse; - if ( ent->client->sess.spectatorState == SPECTATOR_NOT && ent->client->switchTeamTime > level.time ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH")) ); + if (ent->client->sess.spectatorState == SPECTATOR_NOT && ent->client->switchTeamTime > level.time) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSWITCH"))); return; } // if they are playing a tournament game, count as a loss - if ( (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - && ent->client->sess.sessionTeam == TEAM_FREE ) {\ - //WTF??? + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && ent->client->sess.sessionTeam == TEAM_FREE) { // WTF??? ent->client->sess.losses++; } // first set them to spectator - if ( ent->client->sess.spectatorState == SPECTATOR_NOT ) { - SetTeam( ent, "spectator" ); + if (ent->client->sess.spectatorState == SPECTATOR_NOT) { + SetTeam(ent, "spectator"); // fix: update team switch time only if team change really happend if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) ent->client->switchTeamTime = level.time + 5000; } - if ( dir != 1 && dir != -1 ) { - trap->Error( ERR_DROP, "Cmd_FollowCycle_f: bad dir %i", dir ); + if (dir != 1 && dir != -1) { + trap->Error(ERR_DROP, "Cmd_FollowCycle_f: bad dir %i", dir); } clientnum = ent->client->sess.spectatorClient; @@ -1455,45 +1325,38 @@ void Cmd_FollowCycle_f( gentity_t *ent, int dir ) { do { clientnum += dir; - if ( clientnum >= level.maxclients ) - { + if (clientnum >= level.maxclients) { // Avoid /team follow1 crash - if ( looped ) - { + if (looped) { clientnum = original; break; - } - else - { + } else { clientnum = 0; looped = qtrue; } } - if ( clientnum < 0 ) { - if ( looped ) - { + if (clientnum < 0) { + if (looped) { clientnum = original; break; - } - else - { + } else { clientnum = level.maxclients - 1; looped = qtrue; } } // can only follow connected clients - if ( level.clients[ clientnum ].pers.connected != CON_CONNECTED ) { + if (level.clients[clientnum].pers.connected != CON_CONNECTED) { continue; } // can't follow another spectator - if ( level.clients[ clientnum ].sess.sessionTeam == TEAM_SPECTATOR ) { + if (level.clients[clientnum].sess.sessionTeam == TEAM_SPECTATOR) { continue; } // can't follow another spectator - if ( level.clients[ clientnum ].tempSpectate >= level.time ) { + if (level.clients[clientnum].tempSpectate >= level.time) { return; } @@ -1501,18 +1364,14 @@ void Cmd_FollowCycle_f( gentity_t *ent, int dir ) { ent->client->sess.spectatorClient = clientnum; ent->client->sess.spectatorState = SPECTATOR_FOLLOW; return; - } while ( clientnum != original ); + } while (clientnum != original); // leave it where it was } -void Cmd_FollowNext_f( gentity_t *ent ) { - Cmd_FollowCycle_f( ent, 1 ); -} +void Cmd_FollowNext_f(gentity_t *ent) { Cmd_FollowCycle_f(ent, 1); } -void Cmd_FollowPrev_f( gentity_t *ent ) { - Cmd_FollowCycle_f( ent, -1 ); -} +void Cmd_FollowPrev_f(gentity_t *ent) { Cmd_FollowCycle_f(ent, -1); } /* ================== @@ -1520,8 +1379,7 @@ G_Say ================== */ -static void G_SayTo( gentity_t *ent, gentity_t *other, int mode, int color, const char *name, const char *message, char *locMsg ) -{ +static void G_SayTo(gentity_t *ent, gentity_t *other, int mode, int color, const char *name, const char *message, char *locMsg) { if (!other) { return; } @@ -1531,10 +1389,10 @@ static void G_SayTo( gentity_t *ent, gentity_t *other, int mode, int color, cons if (!other->client) { return; } - if ( other->client->pers.connected != CON_CONNECTED ) { + if (other->client->pers.connected != CON_CONNECTED) { return; } - if ( mode == SAY_TEAM && !OnSameTeam(ent, other) ) { + if (mode == SAY_TEAM && !OnSameTeam(ent, other)) { return; } /* @@ -1546,123 +1404,106 @@ static void G_SayTo( gentity_t *ent, gentity_t *other, int mode, int color, cons return; } */ - //They've requested I take this out. + // They've requested I take this out. - if (level.gametype == GT_SIEGE && - ent->client && (ent->client->tempSpectate >= level.time || ent->client->sess.sessionTeam == TEAM_SPECTATOR) && + if (level.gametype == GT_SIEGE && ent->client && (ent->client->tempSpectate >= level.time || ent->client->sess.sessionTeam == TEAM_SPECTATOR) && other->client->sess.sessionTeam != TEAM_SPECTATOR && - other->client->tempSpectate < level.time) - { //siege temp spectators should not communicate to ingame players + other->client->tempSpectate < level.time) { // siege temp spectators should not communicate to ingame players return; } - if (locMsg) - { - trap->SendServerCommand( other-g_entities, va("%s \"%s\" \"%s\" \"%c\" \"%s\" %i", - mode == SAY_TEAM ? "ltchat" : "lchat", - name, locMsg, color, message, ent->s.number)); - } - else - { - trap->SendServerCommand( other-g_entities, va("%s \"%s%c%c%s\" %i", - mode == SAY_TEAM ? "tchat" : "chat", - name, Q_COLOR_ESCAPE, color, message, ent->s.number)); + if (locMsg) { + trap->SendServerCommand(other - g_entities, + va("%s \"%s\" \"%s\" \"%c\" \"%s\" %i", mode == SAY_TEAM ? "ltchat" : "lchat", name, locMsg, color, message, ent->s.number)); + } else { + trap->SendServerCommand(other - g_entities, + va("%s \"%s%c%c%s\" %i", mode == SAY_TEAM ? "tchat" : "chat", name, Q_COLOR_ESCAPE, color, message, ent->s.number)); } } -void G_Say( gentity_t *ent, gentity_t *target, int mode, const char *chatText ) { - int j; - gentity_t *other; - int color; - char name[64]; +void G_Say(gentity_t *ent, gentity_t *target, int mode, const char *chatText) { + int j; + gentity_t *other; + int color; + char name[64]; // don't let text be too long for malicious reasons - char text[MAX_SAY_TEXT]; - char location[64]; - char *locMsg = NULL; + char text[MAX_SAY_TEXT]; + char location[64]; + char *locMsg = NULL; - if ( level.gametype < GT_TEAM && mode == SAY_TEAM ) { + if (level.gametype < GT_TEAM && mode == SAY_TEAM) { mode = SAY_ALL; } - Q_strncpyz( text, chatText, sizeof(text) ); + Q_strncpyz(text, chatText, sizeof(text)); - Q_strstrip( text, "\n\r", " " ); + Q_strstrip(text, "\n\r", " "); - switch ( mode ) { + switch (mode) { default: case SAY_ALL: - G_LogPrintf( "say: %s: %s\n", ent->client->pers.netname, text ); - Com_sprintf (name, sizeof(name), "%s%c%c"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE ); + G_LogPrintf("say: %s: %s\n", ent->client->pers.netname, text); + Com_sprintf(name, sizeof(name), "%s%c%c" EC ": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE); color = COLOR_GREEN; break; case SAY_TEAM: - G_LogPrintf( "sayteam: %s: %s\n", ent->client->pers.netname, text ); - if (Team_GetLocationMsg(ent, location, sizeof(location))) - { - Com_sprintf (name, sizeof(name), EC"(%s%c%c"EC")"EC": ", - ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE ); + G_LogPrintf("sayteam: %s: %s\n", ent->client->pers.netname, text); + if (Team_GetLocationMsg(ent, location, sizeof(location))) { + Com_sprintf(name, sizeof(name), EC "(%s%c%c" EC ")" EC ": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE); locMsg = location; - } - else - { - Com_sprintf (name, sizeof(name), EC"(%s%c%c"EC")"EC": ", - ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE ); + } else { + Com_sprintf(name, sizeof(name), EC "(%s%c%c" EC ")" EC ": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE); } color = COLOR_CYAN; break; case SAY_TELL: - if (target && target->inuse && target->client && level.gametype >= GT_TEAM && - target->client->sess.sessionTeam == ent->client->sess.sessionTeam && - Team_GetLocationMsg(ent, location, sizeof(location))) - { - Com_sprintf (name, sizeof(name), EC"[%s%c%c"EC"]"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE ); + if (target && target->inuse && target->client && level.gametype >= GT_TEAM && target->client->sess.sessionTeam == ent->client->sess.sessionTeam && + Team_GetLocationMsg(ent, location, sizeof(location))) { + Com_sprintf(name, sizeof(name), EC "[%s%c%c" EC "]" EC ": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE); locMsg = location; - } - else - { - Com_sprintf (name, sizeof(name), EC"[%s%c%c"EC"]"EC": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE ); + } else { + Com_sprintf(name, sizeof(name), EC "[%s%c%c" EC "]" EC ": ", ent->client->pers.netname, Q_COLOR_ESCAPE, COLOR_WHITE); } color = COLOR_MAGENTA; break; } - if ( target ) { - G_SayTo( ent, target, mode, color, name, text, locMsg ); + if (target) { + G_SayTo(ent, target, mode, color, name, text, locMsg); return; } // echo the text to the console - if ( dedicated.integer ) { - trap->Print( "%s%s\n", name, text); + if (dedicated.integer) { + trap->Print("%s%s\n", name, text); } // send it to all the appropriate clients for (j = 0; j < level.maxclients; j++) { other = &g_entities[j]; - G_SayTo( ent, other, mode, color, name, text, locMsg ); + G_SayTo(ent, other, mode, color, name, text, locMsg); } } - /* ================== Cmd_Say_f ================== */ -static void Cmd_Say_f( gentity_t *ent ) { +static void Cmd_Say_f(gentity_t *ent) { char *p = NULL; - if ( trap->Argc () < 2 ) + if (trap->Argc() < 2) return; - p = ConcatArgs( 1 ); + p = ConcatArgs(1); - if ( strlen( p ) >= MAX_SAY_TEXT ) { - p[MAX_SAY_TEXT-1] = '\0'; - G_SecurityLogPrintf( "Cmd_Say_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p ); + if (strlen(p) >= MAX_SAY_TEXT) { + p[MAX_SAY_TEXT - 1] = '\0'; + G_SecurityLogPrintf("Cmd_Say_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p); } - G_Say( ent, NULL, SAY_ALL, p ); + G_Say(ent, NULL, SAY_ALL, p); } /* @@ -1670,20 +1511,20 @@ static void Cmd_Say_f( gentity_t *ent ) { Cmd_SayTeam_f ================== */ -static void Cmd_SayTeam_f( gentity_t *ent ) { +static void Cmd_SayTeam_f(gentity_t *ent) { char *p = NULL; - if ( trap->Argc () < 2 ) + if (trap->Argc() < 2) return; - p = ConcatArgs( 1 ); + p = ConcatArgs(1); - if ( strlen( p ) >= MAX_SAY_TEXT ) { - p[MAX_SAY_TEXT-1] = '\0'; - G_SecurityLogPrintf( "Cmd_SayTeam_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p ); + if (strlen(p) >= MAX_SAY_TEXT) { + p[MAX_SAY_TEXT - 1] = '\0'; + G_SecurityLogPrintf("Cmd_SayTeam_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p); } - G_Say( ent, NULL, (level.gametype>=GT_TEAM) ? SAY_TEAM : SAY_ALL, p ); + G_Say(ent, NULL, (level.gametype >= GT_TEAM) ? SAY_TEAM : SAY_ALL, p); } /* @@ -1691,95 +1532,85 @@ static void Cmd_SayTeam_f( gentity_t *ent ) { Cmd_Tell_f ================== */ -static void Cmd_Tell_f( gentity_t *ent ) { - int targetNum; - gentity_t *target; - char *p; - char arg[MAX_TOKEN_CHARS]; +static void Cmd_Tell_f(gentity_t *ent) { + int targetNum; + gentity_t *target; + char *p; + char arg[MAX_TOKEN_CHARS]; - if ( trap->Argc () < 3 ) { - trap->SendServerCommand( ent-g_entities, "print \"Usage: tell \n\"" ); + if (trap->Argc() < 3) { + trap->SendServerCommand(ent - g_entities, "print \"Usage: tell \n\""); return; } - trap->Argv( 1, arg, sizeof( arg ) ); - targetNum = ClientNumberFromString( ent, arg, qfalse ); - if ( targetNum == -1 ) { + trap->Argv(1, arg, sizeof(arg)); + targetNum = ClientNumberFromString(ent, arg, qfalse); + if (targetNum == -1) { return; } target = &g_entities[targetNum]; - if ( !target->inuse || !target->client ) { + if (!target->inuse || !target->client) { return; } - p = ConcatArgs( 2 ); + p = ConcatArgs(2); - if ( strlen( p ) >= MAX_SAY_TEXT ) { - p[MAX_SAY_TEXT-1] = '\0'; - G_SecurityLogPrintf( "Cmd_Tell_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p ); + if (strlen(p) >= MAX_SAY_TEXT) { + p[MAX_SAY_TEXT - 1] = '\0'; + G_SecurityLogPrintf("Cmd_Tell_f from %d (%s) has been truncated: %s\n", ent->s.number, ent->client->pers.netname, p); } - G_LogPrintf( "tell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, p ); - G_Say( ent, target, SAY_TELL, p ); + G_LogPrintf("tell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, p); + G_Say(ent, target, SAY_TELL, p); // don't tell to the player self if it was already directed to this player // also don't send the chat back to a bot - if ( ent != target && !(ent->r.svFlags & SVF_BOT)) { - G_Say( ent, ent, SAY_TELL, p ); + if (ent != target && !(ent->r.svFlags & SVF_BOT)) { + G_Say(ent, ent, SAY_TELL, p); } } -//siege voice command -static void Cmd_VoiceCommand_f(gentity_t *ent) -{ +// siege voice command +static void Cmd_VoiceCommand_f(gentity_t *ent) { gentity_t *te; char arg[MAX_TOKEN_CHARS]; char *s; int i = 0; - if (level.gametype < GT_TEAM) - { + if (level.gametype < GT_TEAM) { return; } - if (trap->Argc() < 2) - { + if (trap->Argc() < 2) { return; } - if (ent->client->sess.sessionTeam == TEAM_SPECTATOR || - ent->client->tempSpectate >= level.time) - { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOICECHATASSPEC")) ); + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR || ent->client->tempSpectate >= level.time) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOICECHATASSPEC"))); return; } trap->Argv(1, arg, sizeof(arg)); - if (arg[0] == '*') - { //hmm.. don't expect a * to be prepended already. maybe someone is trying to be sneaky. + if (arg[0] == '*') { // hmm.. don't expect a * to be prepended already. maybe someone is trying to be sneaky. return; } s = va("*%s", arg); - //now, make sure it's a valid sound to be playing like this.. so people can't go around - //screaming out death sounds or whatever. - while (i < MAX_CUSTOM_SIEGE_SOUNDS) - { - if (!bg_customSiegeSoundNames[i]) - { + // now, make sure it's a valid sound to be playing like this.. so people can't go around + // screaming out death sounds or whatever. + while (i < MAX_CUSTOM_SIEGE_SOUNDS) { + if (!bg_customSiegeSoundNames[i]) { break; } - if (!Q_stricmp(bg_customSiegeSoundNames[i], s)) - { //it matches this one, so it's ok + if (!Q_stricmp(bg_customSiegeSoundNames[i], s)) { // it matches this one, so it's ok break; } i++; } - if (i == MAX_CUSTOM_SIEGE_SOUNDS || !bg_customSiegeSoundNames[i]) - { //didn't find it in the list + if (i == MAX_CUSTOM_SIEGE_SOUNDS || !bg_customSiegeSoundNames[i]) { // didn't find it in the list return; } @@ -1789,52 +1620,43 @@ static void Cmd_VoiceCommand_f(gentity_t *ent) te->r.svFlags |= SVF_BROADCAST; } +static char *gc_orders[] = {"hold your position", "hold this position", "come here", "cover me", "guard location", "search and destroy", "report"}; +static size_t numgc_orders = ARRAY_LEN(gc_orders); -static char *gc_orders[] = { - "hold your position", - "hold this position", - "come here", - "cover me", - "guard location", - "search and destroy", - "report" -}; -static size_t numgc_orders = ARRAY_LEN( gc_orders ); - -void Cmd_GameCommand_f( gentity_t *ent ) { - int targetNum; - unsigned int order; - gentity_t *target; - char arg[MAX_TOKEN_CHARS] = {0}; +void Cmd_GameCommand_f(gentity_t *ent) { + int targetNum; + unsigned int order; + gentity_t *target; + char arg[MAX_TOKEN_CHARS] = {0}; - if ( trap->Argc() != 3 ) { - trap->SendServerCommand( ent-g_entities, va( "print \"Usage: gc \n\"", numgc_orders - 1 ) ); + if (trap->Argc() != 3) { + trap->SendServerCommand(ent - g_entities, va("print \"Usage: gc \n\"", numgc_orders - 1)); return; } - trap->Argv( 2, arg, sizeof( arg ) ); - order = atoi( arg ); + trap->Argv(2, arg, sizeof(arg)); + order = atoi(arg); - if ( order >= numgc_orders ) { - trap->SendServerCommand( ent-g_entities, va("print \"Bad order: %i\n\"", order)); + if (order >= numgc_orders) { + trap->SendServerCommand(ent - g_entities, va("print \"Bad order: %i\n\"", order)); return; } - trap->Argv( 1, arg, sizeof( arg ) ); - targetNum = ClientNumberFromString( ent, arg, qfalse ); - if ( targetNum == -1 ) + trap->Argv(1, arg, sizeof(arg)); + targetNum = ClientNumberFromString(ent, arg, qfalse); + if (targetNum == -1) return; target = &g_entities[targetNum]; - if ( !target->inuse || !target->client ) + if (!target->inuse || !target->client) return; - G_LogPrintf( "tell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, gc_orders[order] ); - G_Say( ent, target, SAY_TELL, gc_orders[order] ); + G_LogPrintf("tell: %s to %s: %s\n", ent->client->pers.netname, target->client->pers.netname, gc_orders[order]); + G_Say(ent, target, SAY_TELL, gc_orders[order]); // don't tell to the player self if it was already directed to this player // also don't send the chat back to a bot - if ( ent != target && !(ent->r.svFlags & SVF_BOT) ) - G_Say( ent, ent, SAY_TELL, gc_orders[order] ); + if (ent != target && !(ent->r.svFlags & SVF_BOT)) + G_Say(ent, ent, SAY_TELL, gc_orders[order]); } /* @@ -1842,397 +1664,378 @@ void Cmd_GameCommand_f( gentity_t *ent ) { Cmd_Where_f ================== */ -void Cmd_Where_f( gentity_t *ent ) { - //JAC: This wasn't working for non-spectators since s.origin doesn't update for active players. - if(ent->client && ent->client->sess.sessionTeam != TEAM_SPECTATOR ) - {//active players use currentOrigin - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", vtos( ent->r.currentOrigin ) ) ); +void Cmd_Where_f(gentity_t *ent) { + // JAC: This wasn't working for non-spectators since s.origin doesn't update for active players. + if (ent->client && ent->client->sess.sessionTeam != TEAM_SPECTATOR) { // active players use currentOrigin + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", vtos(ent->r.currentOrigin))); + } else { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", vtos(ent->s.origin))); } - else - { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", vtos( ent->s.origin ) ) ); - } - //trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", vtos( ent->s.origin ) ) ); -} - -static const char *gameNames[GT_MAX_GAME_TYPE] = { - "Free For All", - "Holocron FFA", - "Jedi Master", - "Duel", - "Power Duel", - "Single Player", - "Team FFA", - "Siege", - "Capture the Flag", - "Capture the Ysalamiri" -}; + // trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", vtos( ent->s.origin ) ) ); +} + +static const char *gameNames[GT_MAX_GAME_TYPE] = {"Free For All", "Holocron FFA", "Jedi Master", "Duel", "Power Duel", "Single Player", "Team FFA", + "Siege", "Capture the Flag", "Capture the Ysalamiri"}; /* ================== Cmd_CallVote_f ================== */ -extern void SiegeClearSwitchData(void); //g_saga.c +extern void SiegeClearSwitchData(void); // g_saga.c -qboolean G_VoteCapturelimit( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int n = Com_Clampi( 0, 0x7FFFFFFF, atoi( arg2 ) ); - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %i", arg1, n ); - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s", level.voteString ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); +qboolean G_VoteCapturelimit(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int n = Com_Clampi(0, 0x7FFFFFFF, atoi(arg2)); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %i", arg1, n); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "%s", level.voteString); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteClientkick( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int n = atoi ( arg2 ); +qboolean G_VoteClientkick(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int n = atoi(arg2); - if ( n < 0 || n >= level.maxclients ) { - trap->SendServerCommand( ent-g_entities, va( "print \"invalid client number %d.\n\"", n ) ); + if (n < 0 || n >= level.maxclients) { + trap->SendServerCommand(ent - g_entities, va("print \"invalid client number %d.\n\"", n)); return qfalse; } - if ( g_entities[n].client->pers.connected == CON_DISCONNECTED ) { - trap->SendServerCommand( ent-g_entities, va( "print \"there is no client with the client number %d.\n\"", n ) ); + if (g_entities[n].client->pers.connected == CON_DISCONNECTED) { + trap->SendServerCommand(ent - g_entities, va("print \"there is no client with the client number %d.\n\"", n)); return qfalse; } - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %s", arg1, arg2 ); - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s %s", arg1, g_entities[n].client->pers.netname ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %s", arg1, arg2); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "%s %s", arg1, g_entities[n].client->pers.netname); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteFraglimit( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int n = Com_Clampi( 0, 0x7FFFFFFF, atoi( arg2 ) ); - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %i", arg1, n ); - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s", level.voteString ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); +qboolean G_VoteFraglimit(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int n = Com_Clampi(0, 0x7FFFFFFF, atoi(arg2)); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %i", arg1, n); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "%s", level.voteString); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteGametype( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int gt = atoi( arg2 ); +qboolean G_VoteGametype(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int gt = atoi(arg2); // ffa, ctf, tdm, etc - if ( arg2[0] && isalpha( arg2[0] ) ) { - gt = BG_GetGametypeForString( arg2 ); - if ( gt == -1 ) - { - trap->SendServerCommand( ent-g_entities, va( "print \"Gametype (%s) unrecognised, defaulting to FFA/Deathmatch\n\"", arg2 ) ); + if (arg2[0] && isalpha(arg2[0])) { + gt = BG_GetGametypeForString(arg2); + if (gt == -1) { + trap->SendServerCommand(ent - g_entities, va("print \"Gametype (%s) unrecognised, defaulting to FFA/Deathmatch\n\"", arg2)); gt = GT_FFA; } } // numeric but out of range - else if ( gt < 0 || gt >= GT_MAX_GAME_TYPE ) { - trap->SendServerCommand( ent-g_entities, va( "print \"Gametype (%i) is out of range, defaulting to FFA/Deathmatch\n\"", gt ) ); + else if (gt < 0 || gt >= GT_MAX_GAME_TYPE) { + trap->SendServerCommand(ent - g_entities, va("print \"Gametype (%i) is out of range, defaulting to FFA/Deathmatch\n\"", gt)); gt = GT_FFA; } // logically invalid gametypes, or gametypes not fully implemented in MP - if ( gt == GT_SINGLE_PLAYER ) { - trap->SendServerCommand( ent-g_entities, va( "print \"This gametype is not supported (%s).\n\"", arg2 ) ); + if (gt == GT_SINGLE_PLAYER) { + trap->SendServerCommand(ent - g_entities, va("print \"This gametype is not supported (%s).\n\"", arg2)); return qfalse; } level.votingGametype = qtrue; level.votingGametypeTo = gt; - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %d", arg1, gt ); - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "%s %s", arg1, gameNames[gt] ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %d", arg1, gt); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "%s %s", arg1, gameNames[gt]); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteKick( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int clientid = ClientNumberFromString( ent, arg2, qtrue ); +qboolean G_VoteKick(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int clientid = ClientNumberFromString(ent, arg2, qtrue); gentity_t *target = NULL; - if ( clientid == -1 ) + if (clientid == -1) return qfalse; target = &g_entities[clientid]; - if ( !target || !target->inuse || !target->client ) + if (!target || !target->inuse || !target->client) return qfalse; - Com_sprintf( level.voteString, sizeof( level.voteString ), "clientkick %d", clientid ); - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "kick %s", target->client->pers.netname ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "clientkick %d", clientid); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "kick %s", target->client->pers.netname); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -const char *G_GetArenaInfoByMap( const char *map ); +const char *G_GetArenaInfoByMap(const char *map); -void Cmd_MapList_f( gentity_t *ent ) { - int i, toggle=0; +void Cmd_MapList_f(gentity_t *ent) { + int i, toggle = 0; char map[24] = "--", buf[512] = {0}; - Q_strcat( buf, sizeof( buf ), "Map list:" ); + Q_strcat(buf, sizeof(buf), "Map list:"); - for ( i=0; i= sizeof( buf ) ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\"", buf ) ); + if (G_DoesMapSupportGametype(map, level.gametype)) { + char *tmpMsg = va(" ^%c%s", (++toggle & 1) ? COLOR_GREEN : COLOR_YELLOW, map); + if (strlen(buf) + strlen(tmpMsg) >= sizeof(buf)) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\"", buf)); buf[0] = '\0'; } - Q_strcat( buf, sizeof( buf ), tmpMsg ); + Q_strcat(buf, sizeof(buf), tmpMsg); } } - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", buf ) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", buf)); } -qboolean G_VoteMap( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { +qboolean G_VoteMap(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { char s[MAX_CVAR_VALUE_STRING] = {0}, bspName[MAX_QPATH] = {0}, *mapName = NULL, *mapName2 = NULL; fileHandle_t fp = NULL_FILE; const char *arenaInfo; // didn't specify a map, show available maps - if ( numArgs < 3 ) { - Cmd_MapList_f( ent ); + if (numArgs < 3) { + Cmd_MapList_f(ent); return qfalse; } - if ( strchr( arg2, '\\' ) ) { - trap->SendServerCommand( ent-g_entities, "print \"Can't have mapnames with a \\\n\"" ); + if (strchr(arg2, '\\')) { + trap->SendServerCommand(ent - g_entities, "print \"Can't have mapnames with a \\\n\""); return qfalse; } - Com_sprintf( bspName, sizeof(bspName), "maps/%s.bsp", arg2 ); - if ( trap->FS_Open( bspName, &fp, FS_READ ) <= 0 ) { - trap->SendServerCommand( ent-g_entities, va( "print \"Can't find map %s on server\n\"", bspName ) ); - if( fp != NULL_FILE ) - trap->FS_Close( fp ); + Com_sprintf(bspName, sizeof(bspName), "maps/%s.bsp", arg2); + if (trap->FS_Open(bspName, &fp, FS_READ) <= 0) { + trap->SendServerCommand(ent - g_entities, va("print \"Can't find map %s on server\n\"", bspName)); + if (fp != NULL_FILE) + trap->FS_Close(fp); return qfalse; } - trap->FS_Close( fp ); + trap->FS_Close(fp); - if ( !G_DoesMapSupportGametype( arg2, level.gametype ) ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "NOVOTE_MAPNOTSUPPORTEDBYGAME" ) ) ); + if (!G_DoesMapSupportGametype(arg2, level.gametype)) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTE_MAPNOTSUPPORTEDBYGAME"))); return qfalse; } // preserve the map rotation - trap->Cvar_VariableStringBuffer( "nextmap", s, sizeof( s ) ); - if ( *s ) - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %s; set nextmap \"%s\"", arg1, arg2, s ); + trap->Cvar_VariableStringBuffer("nextmap", s, sizeof(s)); + if (*s) + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %s; set nextmap \"%s\"", arg1, arg2, s); else - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %s", arg1, arg2 ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %s", arg1, arg2); arenaInfo = G_GetArenaInfoByMap(arg2); - if ( arenaInfo ) { - mapName = Info_ValueForKey( arenaInfo, "longname" ); - mapName2 = Info_ValueForKey( arenaInfo, "map" ); + if (arenaInfo) { + mapName = Info_ValueForKey(arenaInfo, "longname"); + mapName2 = Info_ValueForKey(arenaInfo, "map"); } - if ( !mapName || !mapName[0] ) + if (!mapName || !mapName[0]) mapName = "ERROR"; - if ( !mapName2 || !mapName2[0] ) + if (!mapName2 || !mapName2[0]) mapName2 = "ERROR"; - Com_sprintf( level.voteDisplayString, sizeof( level.voteDisplayString ), "map %s (%s)", mapName, mapName2 ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteDisplayString, sizeof(level.voteDisplayString), "map %s (%s)", mapName, mapName2); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteMapRestart( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int n = Com_Clampi( 0, 60, atoi( arg2 ) ); - if ( numArgs < 3 ) +qboolean G_VoteMapRestart(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int n = Com_Clampi(0, 60, atoi(arg2)); + if (numArgs < 3) n = 5; - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %i", arg1, n ); - Q_strncpyz( level.voteDisplayString, level.voteString, sizeof( level.voteDisplayString ) ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %i", arg1, n); + Q_strncpyz(level.voteDisplayString, level.voteString, sizeof(level.voteDisplayString)); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteNextmap( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { +qboolean G_VoteNextmap(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { char s[MAX_CVAR_VALUE_STRING]; - trap->Cvar_VariableStringBuffer( "nextmap", s, sizeof( s ) ); - if ( !*s ) { - trap->SendServerCommand( ent-g_entities, "print \"nextmap not set.\n\"" ); + trap->Cvar_VariableStringBuffer("nextmap", s, sizeof(s)); + if (!*s) { + trap->SendServerCommand(ent - g_entities, "print \"nextmap not set.\n\""); return qfalse; } SiegeClearSwitchData(); - Com_sprintf( level.voteString, sizeof( level.voteString ), "vstr nextmap"); - Q_strncpyz( level.voteDisplayString, level.voteString, sizeof( level.voteDisplayString ) ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "vstr nextmap"); + Q_strncpyz(level.voteDisplayString, level.voteString, sizeof(level.voteDisplayString)); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteTimelimit( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - float tl = Com_Clamp( 0.0f, 35790.0f, atof( arg2 ) ); - if ( Q_isintegral( tl ) ) - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %i", arg1, (int)tl ); +qboolean G_VoteTimelimit(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + float tl = Com_Clamp(0.0f, 35790.0f, atof(arg2)); + if (Q_isintegral(tl)) + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %i", arg1, (int)tl); else - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %.3f", arg1, tl ); - Q_strncpyz( level.voteDisplayString, level.voteString, sizeof( level.voteDisplayString ) ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %.3f", arg1, tl); + Q_strncpyz(level.voteDisplayString, level.voteString, sizeof(level.voteDisplayString)); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } -qboolean G_VoteWarmup( gentity_t *ent, int numArgs, const char *arg1, const char *arg2 ) { - int n = Com_Clampi( 0, 1, atoi( arg2 ) ); - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s %i", arg1, n ); - Q_strncpyz( level.voteDisplayString, level.voteString, sizeof( level.voteDisplayString ) ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); +qboolean G_VoteWarmup(gentity_t *ent, int numArgs, const char *arg1, const char *arg2) { + int n = Com_Clampi(0, 1, atoi(arg2)); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s %i", arg1, n); + Q_strncpyz(level.voteDisplayString, level.voteString, sizeof(level.voteDisplayString)); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); return qtrue; } typedef struct voteString_s { - const char *string; - const char *aliases; // space delimited list of aliases, will always show the real vote string - qboolean (*func)(gentity_t *ent, int numArgs, const char *arg1, const char *arg2); - int numArgs; // number of REQUIRED arguments, not total/optional arguments - uint32_t validGT; // bit-flag of valid gametypes - qboolean voteDelay; // if true, will delay executing the vote string after it's accepted by g_voteDelay - const char *shortHelp; // NULL if no arguments needed + const char *string; + const char *aliases; // space delimited list of aliases, will always show the real vote string + qboolean (*func)(gentity_t *ent, int numArgs, const char *arg1, const char *arg2); + int numArgs; // number of REQUIRED arguments, not total/optional arguments + uint32_t validGT; // bit-flag of valid gametypes + qboolean voteDelay; // if true, will delay executing the vote string after it's accepted by g_voteDelay + const char *shortHelp; // NULL if no arguments needed } voteString_t; static voteString_t validVoteStrings[] = { // vote string aliases # args valid gametypes exec delay short help - { "capturelimit", "caps", G_VoteCapturelimit, 1, GTB_CTF|GTB_CTY, qtrue, "" }, - { "clientkick", NULL, G_VoteClientkick, 1, GTB_ALL, qfalse, "" }, - { "fraglimit", "frags", G_VoteFraglimit, 1, GTB_ALL & ~(GTB_SIEGE|GTB_CTF|GTB_CTY), qtrue, "" }, - { "g_doWarmup", "dowarmup warmup", G_VoteWarmup, 1, GTB_ALL, qtrue, "<0-1>" }, - { "g_gametype", "gametype gt mode", G_VoteGametype, 1, GTB_ALL, qtrue, "" }, - { "kick", NULL, G_VoteKick, 1, GTB_ALL, qfalse, "" }, - { "map", NULL, G_VoteMap, 0, GTB_ALL, qtrue, "" }, - { "map_restart", "restart", G_VoteMapRestart, 0, GTB_ALL, qtrue, "" }, - { "nextmap", NULL, G_VoteNextmap, 0, GTB_ALL, qtrue, NULL }, - { "timelimit", "time", G_VoteTimelimit, 1, GTB_ALL &~GTB_SIEGE, qtrue, "" }, + {"capturelimit", "caps", G_VoteCapturelimit, 1, GTB_CTF | GTB_CTY, qtrue, ""}, + {"clientkick", NULL, G_VoteClientkick, 1, GTB_ALL, qfalse, ""}, + {"fraglimit", "frags", G_VoteFraglimit, 1, GTB_ALL & ~(GTB_SIEGE | GTB_CTF | GTB_CTY), qtrue, ""}, + {"g_doWarmup", "dowarmup warmup", G_VoteWarmup, 1, GTB_ALL, qtrue, "<0-1>"}, + {"g_gametype", "gametype gt mode", G_VoteGametype, 1, GTB_ALL, qtrue, ""}, + {"kick", NULL, G_VoteKick, 1, GTB_ALL, qfalse, ""}, + {"map", NULL, G_VoteMap, 0, GTB_ALL, qtrue, ""}, + {"map_restart", "restart", G_VoteMapRestart, 0, GTB_ALL, qtrue, ""}, + {"nextmap", NULL, G_VoteNextmap, 0, GTB_ALL, qtrue, NULL}, + {"timelimit", "time", G_VoteTimelimit, 1, GTB_ALL & ~GTB_SIEGE, qtrue, ""}, }; -static const int validVoteStringsSize = ARRAY_LEN( validVoteStrings ); +static const int validVoteStringsSize = ARRAY_LEN(validVoteStrings); -void Svcmd_ToggleAllowVote_f( void ) { - if ( trap->Argc() == 1 ) { +void Svcmd_ToggleAllowVote_f(void) { + if (trap->Argc() == 1) { int i = 0; - for ( i = 0; iPrint( "%2d [X] %s\n", i, validVoteStrings[i].string ); - else trap->Print( "%2d [ ] %s\n", i, validVoteStrings[i].string ); + for (i = 0; i < validVoteStringsSize; i++) { + if ((g_allowVote.integer & (1 << i))) + trap->Print("%2d [X] %s\n", i, validVoteStrings[i].string); + else + trap->Print("%2d [ ] %s\n", i, validVoteStrings[i].string); } return; - } - else { - char arg[8] = { 0 }; + } else { + char arg[8] = {0}; int index; - trap->Argv( 1, arg, sizeof( arg ) ); - index = atoi( arg ); + trap->Argv(1, arg, sizeof(arg)); + index = atoi(arg); - if ( index < 0 || index >= validVoteStringsSize ) { - Com_Printf( "ToggleAllowVote: Invalid range: %i [0, %i]\n", index, validVoteStringsSize - 1 ); + if (index < 0 || index >= validVoteStringsSize) { + Com_Printf("ToggleAllowVote: Invalid range: %i [0, %i]\n", index, validVoteStringsSize - 1); return; } - trap->Cvar_Set( "g_allowVote", va( "%i", (1 << index) ^ (g_allowVote.integer & ((1 << validVoteStringsSize) - 1)) ) ); - trap->Cvar_Update( &g_allowVote ); + trap->Cvar_Set("g_allowVote", va("%i", (1 << index) ^ (g_allowVote.integer & ((1 << validVoteStringsSize) - 1)))); + trap->Cvar_Update(&g_allowVote); - Com_Printf( "%s %s^7\n", validVoteStrings[index].string, ((g_allowVote.integer & (1 << index)) ? "^2Enabled" : "^1Disabled") ); + Com_Printf("%s %s^7\n", validVoteStrings[index].string, ((g_allowVote.integer & (1 << index)) ? "^2Enabled" : "^1Disabled")); } } -void Cmd_CallVote_f( gentity_t *ent ) { - int i=0, numArgs=0; - char arg1[MAX_CVAR_VALUE_STRING] = {0}; - char arg2[MAX_CVAR_VALUE_STRING] = {0}; - voteString_t *vote = NULL; +void Cmd_CallVote_f(gentity_t *ent) { + int i = 0, numArgs = 0; + char arg1[MAX_CVAR_VALUE_STRING] = {0}; + char arg2[MAX_CVAR_VALUE_STRING] = {0}; + voteString_t *vote = NULL; // not allowed to vote at all - if ( !g_allowVote.integer ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "NOVOTE" ) ) ); + if (!g_allowVote.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTE"))); return; } // vote in progress - else if ( level.voteTime ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "VOTEINPROGRESS" ) ) ); + else if (level.voteTime) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "VOTEINPROGRESS"))); return; } // can't vote as a spectator, except in (power)duel - else if ( level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "NOSPECVOTE" ) ) ); + else if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSPECVOTE"))); return; } // make sure it is a valid command to vote on numArgs = trap->Argc(); - trap->Argv( 1, arg1, sizeof( arg1 ) ); - if ( numArgs > 1 ) - Q_strncpyz( arg2, ConcatArgs( 2 ), sizeof( arg2 ) ); + trap->Argv(1, arg1, sizeof(arg1)); + if (numArgs > 1) + Q_strncpyz(arg2, ConcatArgs(2), sizeof(arg2)); // filter ; \n \r - if ( Q_strchrs( arg1, ";\r\n" ) || Q_strchrs( arg2, ";\r\n" ) ) { - trap->SendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" ); + if (Q_strchrs(arg1, ";\r\n") || Q_strchrs(arg2, ";\r\n")) { + trap->SendServerCommand(ent - g_entities, "print \"Invalid vote string.\n\""); return; } // check for invalid votes - for ( i=0; iSendServerCommand( ent-g_entities, "print \"Invalid vote string.\n\"" ); - trap->SendServerCommand( ent-g_entities, "print \"Allowed vote strings are: \"" ); - for ( i=0; iSendServerCommand(ent - g_entities, "print \"Invalid vote string.\n\""); + trap->SendServerCommand(ent - g_entities, "print \"Allowed vote strings are: \""); + for (i = 0; i < validVoteStringsSize; i++) { + if (!(g_allowVote.integer & (1 << i))) continue; toggle = !toggle; - if ( validVoteStrings[i].shortHelp ) { - Q_strcat( buf, sizeof( buf ), va( "^%c%s %s ", - toggle ? COLOR_GREEN : COLOR_YELLOW, - validVoteStrings[i].string, - validVoteStrings[i].shortHelp ) ); - } - else { - Q_strcat( buf, sizeof( buf ), va( "^%c%s ", - toggle ? COLOR_GREEN : COLOR_YELLOW, - validVoteStrings[i].string ) ); + if (validVoteStrings[i].shortHelp) { + Q_strcat(buf, sizeof(buf), va("^%c%s %s ", toggle ? COLOR_GREEN : COLOR_YELLOW, validVoteStrings[i].string, validVoteStrings[i].shortHelp)); + } else { + Q_strcat(buf, sizeof(buf), va("^%c%s ", toggle ? COLOR_GREEN : COLOR_YELLOW, validVoteStrings[i].string)); } } - //FIXME: buffer and send in multiple messages in case of overflow - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", buf ) ); + // FIXME: buffer and send in multiple messages in case of overflow + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", buf)); return; } validVote: vote = &validVoteStrings[i]; - if ( !(vote->validGT & (1<SendServerCommand( ent-g_entities, va( "print \"%s is not applicable in this gametype.\n\"", arg1 ) ); + if (!(vote->validGT & (1 << level.gametype))) { + trap->SendServerCommand(ent - g_entities, va("print \"%s is not applicable in this gametype.\n\"", arg1)); return; } - if ( numArgs < vote->numArgs+2 ) { - trap->SendServerCommand( ent-g_entities, va( "print \"%s requires more arguments: %s\n\"", arg1, vote->shortHelp ) ); + if (numArgs < vote->numArgs + 2) { + trap->SendServerCommand(ent - g_entities, va("print \"%s requires more arguments: %s\n\"", arg1, vote->shortHelp)); return; } @@ -2241,32 +2044,33 @@ void Cmd_CallVote_f( gentity_t *ent ) { level.voteExecuteDelay = vote->voteDelay ? g_voteDelay.integer : 0; // there is still a vote to be executed, execute it and store the new vote - if ( level.voteExecuteTime ) { + if (level.voteExecuteTime) { level.voteExecuteTime = 0; - trap->SendConsoleCommand( EXEC_APPEND, va( "%s\n", level.voteString ) ); + trap->SendConsoleCommand(EXEC_APPEND, va("%s\n", level.voteString)); } // pass the args onto vote-specific handlers for parsing/filtering - if ( vote->func ) { - if ( !vote->func( ent, numArgs, arg1, arg2 ) ) + if (vote->func) { + if (!vote->func(ent, numArgs, arg1, arg2)) return; } // otherwise assume it's a command else { - Com_sprintf( level.voteString, sizeof( level.voteString ), "%s \"%s\"", arg1, arg2 ); - Q_strncpyz( level.voteDisplayString, level.voteString, sizeof( level.voteDisplayString ) ); - Q_strncpyz( level.voteStringClean, level.voteString, sizeof( level.voteStringClean ) ); + Com_sprintf(level.voteString, sizeof(level.voteString), "%s \"%s\"", arg1, arg2); + Q_strncpyz(level.voteDisplayString, level.voteString, sizeof(level.voteDisplayString)); + Q_strncpyz(level.voteStringClean, level.voteString, sizeof(level.voteStringClean)); } - Q_strstrip( level.voteStringClean, "\"\n\r", NULL ); + Q_strstrip(level.voteStringClean, "\"\n\r", NULL); - trap->SendServerCommand( -1, va( "print \"%s^7 %s (%s)\n\"", ent->client->pers.netname, G_GetStringEdString( "MP_SVGAME", "PLCALLEDVOTE" ), level.voteStringClean ) ); + trap->SendServerCommand(-1, + va("print \"%s^7 %s (%s)\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLCALLEDVOTE"), level.voteStringClean)); // start the voting, the caller automatically votes yes level.voteTime = level.time; level.voteYes = 1; level.voteNo = 0; - for ( i=0; iclient->mGameFlags |= PSG_VOTED; ent->client->pers.vote = 1; - trap->SetConfigstring( CS_VOTE_TIME, va( "%i", level.voteTime ) ); - trap->SetConfigstring( CS_VOTE_STRING, level.voteDisplayString ); - trap->SetConfigstring( CS_VOTE_YES, va( "%i", level.voteYes ) ); - trap->SetConfigstring( CS_VOTE_NO, va( "%i", level.voteNo ) ); + trap->SetConfigstring(CS_VOTE_TIME, va("%i", level.voteTime)); + trap->SetConfigstring(CS_VOTE_STRING, level.voteDisplayString); + trap->SetConfigstring(CS_VOTE_YES, va("%i", level.voteYes)); + trap->SetConfigstring(CS_VOTE_NO, va("%i", level.voteNo)); } /* @@ -2285,65 +2089,63 @@ void Cmd_CallVote_f( gentity_t *ent ) { Cmd_Vote_f ================== */ -void Cmd_Vote_f( gentity_t *ent ) { - char msg[64] = {0}; +void Cmd_Vote_f(gentity_t *ent) { + char msg[64] = {0}; - if ( !level.voteTime ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEINPROG")) ); + if (!level.voteTime) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEINPROG"))); return; } - if ( ent->client->mGameFlags & PSG_VOTED ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "VOTEALREADY")) ); + if (ent->client->mGameFlags & PSG_VOTED) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "VOTEALREADY"))); return; } - if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) - { - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEASSPEC")) ); + if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) { + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEASSPEC"))); return; } } - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLVOTECAST")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLVOTECAST"))); ent->client->mGameFlags |= PSG_VOTED; - trap->Argv( 1, msg, sizeof( msg ) ); + trap->Argv(1, msg, sizeof(msg)); - if ( tolower( msg[0] ) == 'y' || msg[0] == '1' ) { + if (tolower(msg[0]) == 'y' || msg[0] == '1') { level.voteYes++; ent->client->pers.vote = 1; - trap->SetConfigstring( CS_VOTE_YES, va("%i", level.voteYes ) ); + trap->SetConfigstring(CS_VOTE_YES, va("%i", level.voteYes)); } else { level.voteNo++; ent->client->pers.vote = 2; - trap->SetConfigstring( CS_VOTE_NO, va("%i", level.voteNo ) ); + trap->SetConfigstring(CS_VOTE_NO, va("%i", level.voteNo)); } // a majority will be determined in CheckVote, which will also account // for players entering or leaving } -qboolean G_TeamVoteLeader( gentity_t *ent, int cs_offset, team_t team, int numArgs, const char *arg1, const char *arg2 ) { - int clientid = numArgs == 2 ? ent->s.number : ClientNumberFromString( ent, arg2, qfalse ); +qboolean G_TeamVoteLeader(gentity_t *ent, int cs_offset, team_t team, int numArgs, const char *arg1, const char *arg2) { + int clientid = numArgs == 2 ? ent->s.number : ClientNumberFromString(ent, arg2, qfalse); gentity_t *target = NULL; - if ( clientid == -1 ) + if (clientid == -1) return qfalse; target = &g_entities[clientid]; - if ( !target || !target->inuse || !target->client ) + if (!target || !target->inuse || !target->client) return qfalse; - if ( target->client->sess.sessionTeam != team ) - { - trap->SendServerCommand( ent-g_entities, va( "print \"User %s is not on your team\n\"", arg2 ) ); + if (target->client->sess.sessionTeam != team) { + trap->SendServerCommand(ent - g_entities, va("print \"User %s is not on your team\n\"", arg2)); return qfalse; } - Com_sprintf( level.teamVoteString[cs_offset], sizeof( level.teamVoteString[cs_offset] ), "leader %d", clientid ); - Q_strncpyz( level.teamVoteDisplayString[cs_offset], level.teamVoteString[cs_offset], sizeof( level.teamVoteDisplayString[cs_offset] ) ); - Q_strncpyz( level.teamVoteStringClean[cs_offset], level.teamVoteString[cs_offset], sizeof( level.teamVoteStringClean[cs_offset] ) ); + Com_sprintf(level.teamVoteString[cs_offset], sizeof(level.teamVoteString[cs_offset]), "leader %d", clientid); + Q_strncpyz(level.teamVoteDisplayString[cs_offset], level.teamVoteString[cs_offset], sizeof(level.teamVoteDisplayString[cs_offset])); + Q_strncpyz(level.teamVoteStringClean[cs_offset], level.teamVoteString[cs_offset], sizeof(level.teamVoteStringClean[cs_offset])); return qtrue; } @@ -2352,67 +2154,67 @@ qboolean G_TeamVoteLeader( gentity_t *ent, int cs_offset, team_t team, int numAr Cmd_CallTeamVote_f ================== */ -void Cmd_CallTeamVote_f( gentity_t *ent ) { - team_t team = ent->client->sess.sessionTeam; - int i=0, cs_offset=0, numArgs=0; - char arg1[MAX_CVAR_VALUE_STRING] = {0}; - char arg2[MAX_CVAR_VALUE_STRING] = {0}; +void Cmd_CallTeamVote_f(gentity_t *ent) { + team_t team = ent->client->sess.sessionTeam; + int i = 0, cs_offset = 0, numArgs = 0; + char arg1[MAX_CVAR_VALUE_STRING] = {0}; + char arg2[MAX_CVAR_VALUE_STRING] = {0}; - if ( team == TEAM_RED ) + if (team == TEAM_RED) cs_offset = 0; - else if ( team == TEAM_BLUE ) + else if (team == TEAM_BLUE) cs_offset = 1; else return; // not allowed to vote at all - if ( !g_allowTeamVote.integer ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTE")) ); + if (!g_allowTeamVote.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTE"))); return; } // vote in progress - else if ( level.teamVoteTime[cs_offset] ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEALREADY")) ); + else if (level.teamVoteTime[cs_offset]) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEALREADY"))); return; } // can't vote as a spectator - else if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSPECVOTE")) ); + else if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOSPECVOTE"))); return; } // make sure it is a valid command to vote on numArgs = trap->Argc(); - trap->Argv( 1, arg1, sizeof( arg1 ) ); - if ( numArgs > 1 ) - Q_strncpyz( arg2, ConcatArgs( 2 ), sizeof( arg2 ) ); + trap->Argv(1, arg1, sizeof(arg1)); + if (numArgs > 1) + Q_strncpyz(arg2, ConcatArgs(2), sizeof(arg2)); // filter ; \n \r - if ( Q_strchrs( arg1, ";\r\n" ) || Q_strchrs( arg2, ";\r\n" ) ) { - trap->SendServerCommand( ent-g_entities, "print \"Invalid team vote string.\n\"" ); + if (Q_strchrs(arg1, ";\r\n") || Q_strchrs(arg2, ";\r\n")) { + trap->SendServerCommand(ent - g_entities, "print \"Invalid team vote string.\n\""); return; } // pass the args onto vote-specific handlers for parsing/filtering - if ( !Q_stricmp( arg1, "leader" ) ) { - if ( !G_TeamVoteLeader( ent, cs_offset, team, numArgs, arg1, arg2 ) ) + if (!Q_stricmp(arg1, "leader")) { + if (!G_TeamVoteLeader(ent, cs_offset, team, numArgs, arg1, arg2)) return; - } - else { - trap->SendServerCommand( ent-g_entities, "print \"Invalid team vote string.\n\"" ); - trap->SendServerCommand( ent-g_entities, va("print \"Allowed team vote strings are: ^%c%s %s\n\"", COLOR_GREEN, "leader", "" )); + } else { + trap->SendServerCommand(ent - g_entities, "print \"Invalid team vote string.\n\""); + trap->SendServerCommand(ent - g_entities, + va("print \"Allowed team vote strings are: ^%c%s %s\n\"", COLOR_GREEN, "leader", "")); return; } - Q_strstrip( level.teamVoteStringClean[cs_offset], "\"\n\r", NULL ); + Q_strstrip(level.teamVoteStringClean[cs_offset], "\"\n\r", NULL); - for ( i=0; iSendServerCommand( i, va("print \"%s^7 called a team vote (%s)\n\"", ent->client->pers.netname, level.teamVoteStringClean[cs_offset] ) ); + if (level.clients[i].sess.sessionTeam == team) + trap->SendServerCommand(i, va("print \"%s^7 called a team vote (%s)\n\"", ent->client->pers.netname, level.teamVoteStringClean[cs_offset])); } // start the voting, the caller autoamtically votes yes @@ -2420,10 +2222,10 @@ void Cmd_CallTeamVote_f( gentity_t *ent ) { level.teamVoteYes[cs_offset] = 1; level.teamVoteNo[cs_offset] = 0; - for ( i=0; iclient->mGameFlags |= PSG_TEAMVOTED; ent->client->pers.teamvote = 1; - trap->SetConfigstring( CS_TEAMVOTE_TIME + cs_offset, va("%i", level.teamVoteTime[cs_offset] ) ); - trap->SetConfigstring( CS_TEAMVOTE_STRING + cs_offset, level.teamVoteDisplayString[cs_offset] ); - trap->SetConfigstring( CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset] ) ); - trap->SetConfigstring( CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset] ) ); + trap->SetConfigstring(CS_TEAMVOTE_TIME + cs_offset, va("%i", level.teamVoteTime[cs_offset])); + trap->SetConfigstring(CS_TEAMVOTE_STRING + cs_offset, level.teamVoteDisplayString[cs_offset]); + trap->SetConfigstring(CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset])); + trap->SetConfigstring(CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset])); } /* @@ -2442,88 +2244,85 @@ void Cmd_CallTeamVote_f( gentity_t *ent ) { Cmd_TeamVote_f ================== */ -void Cmd_TeamVote_f( gentity_t *ent ) { - team_t team = ent->client->sess.sessionTeam; - int cs_offset=0; - char msg[64] = {0}; +void Cmd_TeamVote_f(gentity_t *ent) { + team_t team = ent->client->sess.sessionTeam; + int cs_offset = 0; + char msg[64] = {0}; - if ( team == TEAM_RED ) + if (team == TEAM_RED) cs_offset = 0; - else if ( team == TEAM_BLUE ) + else if (team == TEAM_BLUE) cs_offset = 1; else return; - if ( !level.teamVoteTime[cs_offset] ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOTEAMVOTEINPROG")) ); + if (!level.teamVoteTime[cs_offset]) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOTEAMVOTEINPROG"))); return; } - if ( ent->client->mGameFlags & PSG_TEAMVOTED ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEALREADYCAST")) ); + if (ent->client->mGameFlags & PSG_TEAMVOTED) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEALREADYCAST"))); return; } - if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) { - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEASSPEC")) ); + if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOVOTEASSPEC"))); return; } - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLTEAMVOTECAST")) ); + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "PLTEAMVOTECAST"))); ent->client->mGameFlags |= PSG_TEAMVOTED; - trap->Argv( 1, msg, sizeof( msg ) ); + trap->Argv(1, msg, sizeof(msg)); - if ( tolower( msg[0] ) == 'y' || msg[0] == '1' ) { + if (tolower(msg[0]) == 'y' || msg[0] == '1') { level.teamVoteYes[cs_offset]++; ent->client->pers.teamvote = 1; - trap->SetConfigstring( CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset] ) ); + trap->SetConfigstring(CS_TEAMVOTE_YES + cs_offset, va("%i", level.teamVoteYes[cs_offset])); } else { level.teamVoteNo[cs_offset]++; ent->client->pers.teamvote = 2; - trap->SetConfigstring( CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset] ) ); + trap->SetConfigstring(CS_TEAMVOTE_NO + cs_offset, va("%i", level.teamVoteNo[cs_offset])); } // a majority will be determined in TeamCheckVote, which will also account // for players entering or leaving } - /* ================= Cmd_SetViewpos_f ================= */ -void Cmd_SetViewpos_f( gentity_t *ent ) { - vec3_t origin, angles; - char buffer[MAX_TOKEN_CHARS]; - int i; +void Cmd_SetViewpos_f(gentity_t *ent) { + vec3_t origin, angles; + char buffer[MAX_TOKEN_CHARS]; + int i; - if ( trap->Argc() != 5 ) { - trap->SendServerCommand( ent-g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); + if (trap->Argc() != 5) { + trap->SendServerCommand(ent - g_entities, va("print \"usage: setviewpos x y z yaw\n\"")); return; } - VectorClear( angles ); - for ( i = 0 ; i < 3 ; i++ ) { - trap->Argv( i + 1, buffer, sizeof( buffer ) ); - origin[i] = atof( buffer ); + VectorClear(angles); + for (i = 0; i < 3; i++) { + trap->Argv(i + 1, buffer, sizeof(buffer)); + origin[i] = atof(buffer); } - trap->Argv( 4, buffer, sizeof( buffer ) ); - angles[YAW] = atof( buffer ); + trap->Argv(4, buffer, sizeof(buffer)); + angles[YAW] = atof(buffer); - TeleportPlayer( ent, origin, angles ); + TeleportPlayer(ent, origin, angles); } -void G_LeaveVehicle( gentity_t* ent, qboolean ConCheck ) { +void G_LeaveVehicle(gentity_t *ent, qboolean ConCheck) { - if (ent->client->ps.m_iVehicleNum) - { //tell it I'm getting off + if (ent->client->ps.m_iVehicleNum) { // tell it I'm getting off gentity_t *veh = &g_entities[ent->client->ps.m_iVehicleNum]; - if (veh->inuse && veh->client && veh->m_pVehicle) - { - if ( ConCheck ) { // check connection + if (veh->inuse && veh->client && veh->m_pVehicle) { + if (ConCheck) { // check connection clientConnected_t pCon = ent->client->pers.connected; ent->client->pers.connected = CON_DISCONNECTED; veh->m_pVehicle->m_pVehicleInfo->Eject(veh->m_pVehicle, (bgEntity_t *)ent, qtrue); @@ -2537,8 +2336,7 @@ void G_LeaveVehicle( gentity_t* ent, qboolean ConCheck ) { ent->client->ps.m_iVehicleNum = 0; } -int G_ItemUsable(playerState_t *ps, int forcedUse) -{ +int G_ItemUsable(playerState_t *ps, int forcedUse) { vec3_t fwd, fwdorg, dest, pos; vec3_t yawonly; vec3_t mins, maxs; @@ -2550,52 +2348,43 @@ int G_ItemUsable(playerState_t *ps, int forcedUse) return 0; } - if (ps->m_iVehicleNum) - { + if (ps->m_iVehicleNum) { return 0; } - if (ps->pm_flags & PMF_USE_ITEM_HELD) - { //force to let go first + if (ps->pm_flags & PMF_USE_ITEM_HELD) { // force to let go first return 0; } - if (!forcedUse) - { + if (!forcedUse) { forcedUse = bg_itemlist[ps->stats[STAT_HOLDABLE_ITEM]].giTag; } - if (!BG_IsItemSelectable(ps, forcedUse)) - { + if (!BG_IsItemSelectable(ps, forcedUse)) { return 0; } - switch (forcedUse) - { + switch (forcedUse) { case HI_MEDPAC: case HI_MEDPAC_BIG: - if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) - { + if (ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH]) { return 0; } - if (ps->stats[STAT_HEALTH] <= 0) - { + if (ps->stats[STAT_HEALTH] <= 0) { return 0; } return 1; case HI_SEEKER: - if (ps->eFlags & EF_SEEKERDRONE) - { + if (ps->eFlags & EF_SEEKERDRONE) { G_AddEvent(&g_entities[ps->clientNum], EV_ITEMUSEFAIL, SEEKER_ALREADYDEPLOYED); return 0; } return 1; case HI_SENTRY_GUN: - if (ps->fd.sentryDeployed) - { + if (ps->fd.sentryDeployed) { G_AddEvent(&g_entities[ps->clientNum], EV_ITEMUSEFAIL, SENTRY_ALREADYPLACED); return 0; } @@ -2604,23 +2393,22 @@ int G_ItemUsable(playerState_t *ps, int forcedUse) yawonly[PITCH] = 0; yawonly[YAW] = ps->viewangles[YAW]; - VectorSet( mins, -8, -8, 0 ); - VectorSet( maxs, 8, 8, 24 ); + VectorSet(mins, -8, -8, 0); + VectorSet(maxs, 8, 8, 24); AngleVectors(yawonly, fwd, NULL, NULL); - fwdorg[0] = ps->origin[0] + fwd[0]*64; - fwdorg[1] = ps->origin[1] + fwd[1]*64; - fwdorg[2] = ps->origin[2] + fwd[2]*64; + fwdorg[0] = ps->origin[0] + fwd[0] * 64; + fwdorg[1] = ps->origin[1] + fwd[1] * 64; + fwdorg[2] = ps->origin[2] + fwd[2] * 64; - trtest[0] = fwdorg[0] + fwd[0]*16; - trtest[1] = fwdorg[1] + fwd[1]*16; - trtest[2] = fwdorg[2] + fwd[2]*16; + trtest[0] = fwdorg[0] + fwd[0] * 16; + trtest[1] = fwdorg[1] + fwd[1] * 16; + trtest[2] = fwdorg[2] + fwd[2] * 16; trap->Trace(&tr, ps->origin, mins, maxs, trtest, ps->clientNum, MASK_PLAYERSOLID, qfalse, 0, 0); - if ((tr.fraction != 1 && tr.entityNum != ps->clientNum) || tr.startsolid || tr.allsolid) - { + if ((tr.fraction != 1 && tr.entityNum != ps->clientNum) || tr.startsolid || tr.allsolid) { G_AddEvent(&g_entities[ps->clientNum], EV_ITEMUSEFAIL, SENTRY_NOROOM); return 0; } @@ -2635,23 +2423,21 @@ int G_ItemUsable(playerState_t *ps, int forcedUse) maxs[1] = 8; maxs[2] = 8; - AngleVectors (ps->viewangles, fwd, NULL, NULL); + AngleVectors(ps->viewangles, fwd, NULL, NULL); fwd[2] = 0; VectorMA(ps->origin, 64, fwd, dest); - trap->Trace(&tr, ps->origin, mins, maxs, dest, ps->clientNum, MASK_SHOT, qfalse, 0, 0 ); - if (tr.fraction > 0.9 && !tr.startsolid && !tr.allsolid) - { + trap->Trace(&tr, ps->origin, mins, maxs, dest, ps->clientNum, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction > 0.9 && !tr.startsolid && !tr.allsolid) { VectorCopy(tr.endpos, pos); - VectorSet( dest, pos[0], pos[1], pos[2] - 4096 ); - trap->Trace( &tr, pos, mins, maxs, dest, ps->clientNum, MASK_SOLID, qfalse, 0, 0 ); - if ( !tr.startsolid && !tr.allsolid ) - { + VectorSet(dest, pos[0], pos[1], pos[2] - 4096); + trap->Trace(&tr, pos, mins, maxs, dest, ps->clientNum, MASK_SOLID, qfalse, 0, 0); + if (!tr.startsolid && !tr.allsolid) { return 1; } } G_AddEvent(&g_entities[ps->clientNum], EV_ITEMUSEFAIL, SHIELD_NOROOM); return 0; - case HI_JETPACK: //do something? + case HI_JETPACK: // do something? return 1; case HI_HEALTHDISP: return 1; @@ -2668,114 +2454,88 @@ int G_ItemUsable(playerState_t *ps, int forcedUse) void saberKnockDown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other); -void Cmd_ToggleSaber_f(gentity_t *ent) -{ - if (ent->client->ps.fd.forceGripCripple) - { //if they are being gripped, don't let them unholster their saber - if (ent->client->ps.saberHolstered) - { +void Cmd_ToggleSaber_f(gentity_t *ent) { + if (ent->client->ps.fd.forceGripCripple) { // if they are being gripped, don't let them unholster their saber + if (ent->client->ps.saberHolstered) { return; } } - if (ent->client->ps.saberInFlight) - { - if (ent->client->ps.saberEntityNum) - { //turn it off in midair + if (ent->client->ps.saberInFlight) { + if (ent->client->ps.saberEntityNum) { // turn it off in midair saberKnockDown(&g_entities[ent->client->ps.saberEntityNum], ent, ent); } return; } - if (ent->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (ent->client->ps.forceHandExtend != HANDEXTEND_NONE) { return; } - if (ent->client->ps.weapon != WP_SABER) - { + if (ent->client->ps.weapon != WP_SABER) { return; } -// if (ent->client->ps.duelInProgress && !ent->client->ps.saberHolstered) -// { -// return; -// } + // if (ent->client->ps.duelInProgress && !ent->client->ps.saberHolstered) + // { + // return; + // } - if (ent->client->ps.duelTime >= level.time) - { + if (ent->client->ps.duelTime >= level.time) { return; } - if (ent->client->ps.saberLockTime >= level.time) - { + if (ent->client->ps.saberLockTime >= level.time) { return; } - if (ent->client && ent->client->ps.weaponTime < 1) - { - if (ent->client->ps.saberHolstered == 2) - { + if (ent->client && ent->client->ps.weaponTime < 1) { + if (ent->client->ps.saberHolstered == 2) { ent->client->ps.saberHolstered = 0; - if (ent->client->saber[0].soundOn) - { + if (ent->client->saber[0].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOn); } - if (ent->client->saber[1].soundOn) - { + if (ent->client->saber[1].soundOn) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOn); } - } - else - { + } else { ent->client->ps.saberHolstered = 2; - if (ent->client->saber[0].soundOff) - { + if (ent->client->saber[0].soundOff) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOff); } - if (ent->client->saber[1].soundOff && - ent->client->saber[1].model[0]) - { + if (ent->client->saber[1].soundOff && ent->client->saber[1].model[0]) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOff); } - //prevent anything from being done for 400ms after holster + // prevent anything from being done for 400ms after holster ent->client->ps.weaponTime = 400; } } } -extern vmCvar_t d_saberStanceDebug; +extern vmCvar_t d_saberStanceDebug; -extern qboolean WP_SaberCanTurnOffSomeBlades( saberInfo_t *saber ); -void Cmd_SaberAttackCycle_f(gentity_t *ent) -{ +extern qboolean WP_SaberCanTurnOffSomeBlades(saberInfo_t *saber); +void Cmd_SaberAttackCycle_f(gentity_t *ent) { int selectLevel = 0; qboolean usingSiegeStyle = qfalse; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - if ( level.intermissionQueued || level.intermissiontime ) - { - trap->SendServerCommand( ent-g_entities, va( "print \"%s (saberAttackCycle)\n\"", G_GetStringEdString( "MP_SVGAME", "CANNOT_TASK_INTERMISSION" ) ) ); + if (level.intermissionQueued || level.intermissiontime) { + trap->SendServerCommand(ent - g_entities, va("print \"%s (saberAttackCycle)\n\"", G_GetStringEdString("MP_SVGAME", "CANNOT_TASK_INTERMISSION"))); return; } - if ( ent->health <= 0 - || ent->client->tempSpectate >= level.time - || ent->client->sess.sessionTeam == TEAM_SPECTATOR ) - { - trap->SendServerCommand( ent-g_entities, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "MUSTBEALIVE" ) ) ); + if (ent->health <= 0 || ent->client->tempSpectate >= level.time || ent->client->sess.sessionTeam == TEAM_SPECTATOR) { + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "MUSTBEALIVE"))); return; } - - if ( ent->client->ps.weapon != WP_SABER ) - { - return; + if (ent->client->ps.weapon != WP_SABER) { + return; } /* if (ent->client->ps.weaponTime > 0) @@ -2784,201 +2544,148 @@ void Cmd_SaberAttackCycle_f(gentity_t *ent) } */ - if (ent->client->saber[0].model[0] && ent->client->saber[1].model[0]) - { //no cycling for akimbo - if ( WP_SaberCanTurnOffSomeBlades( &ent->client->saber[1] ) ) - {//can turn second saber off - if ( ent->client->ps.saberHolstered == 1 ) - {//have one holstered - //unholster it + if (ent->client->saber[0].model[0] && ent->client->saber[1].model[0]) { // no cycling for akimbo + if (WP_SaberCanTurnOffSomeBlades(&ent->client->saber[1])) { // can turn second saber off + if (ent->client->ps.saberHolstered == 1) { // have one holstered + // unholster it G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOn); ent->client->ps.saberHolstered = 0; - //g_active should take care of this, but... + // g_active should take care of this, but... ent->client->ps.fd.saberAnimLevel = SS_DUAL; - } - else if ( ent->client->ps.saberHolstered == 0 ) - {//have none holstered - if ( (ent->client->saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) ) - {//can't turn it off manually - } - else if ( ent->client->saber[1].bladeStyle2Start > 0 - && (ent->client->saber[1].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE2) ) - {//can't turn it off manually - } - else - { - //turn it off + } else if (ent->client->ps.saberHolstered == 0) { // have none holstered + if ((ent->client->saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) { // can't turn it off manually + } else if (ent->client->saber[1].bladeStyle2Start > 0 && + (ent->client->saber[1].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) { // can't turn it off manually + } else { + // turn it off G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOff); ent->client->ps.saberHolstered = 1; - //g_active should take care of this, but... + // g_active should take care of this, but... ent->client->ps.fd.saberAnimLevel = SS_FAST; } } - if (d_saberStanceDebug.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle dual saber blade.\n\"") ); + if (d_saberStanceDebug.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle dual saber blade.\n\"")); } return; } - } - else if (ent->client->saber[0].numBlades > 1 - && WP_SaberCanTurnOffSomeBlades( &ent->client->saber[0] ) ) - { //use staff stance then. - if ( ent->client->ps.saberHolstered == 1 ) - {//second blade off - if ( ent->client->ps.saberInFlight ) - {//can't turn second blade back on if it's in the air, you naughty boy! - if (d_saberStanceDebug.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle staff blade in air.\n\"") ); + } else if (ent->client->saber[0].numBlades > 1 && WP_SaberCanTurnOffSomeBlades(&ent->client->saber[0])) { // use staff stance then. + if (ent->client->ps.saberHolstered == 1) { // second blade off + if (ent->client->ps.saberInFlight) { // can't turn second blade back on if it's in the air, you naughty boy! + if (d_saberStanceDebug.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle staff blade in air.\n\"")); } return; } - //turn it on + // turn it on G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOn); ent->client->ps.saberHolstered = 0; - //g_active should take care of this, but... - if ( ent->client->saber[0].stylesForbidden ) - {//have a style we have to use - WP_UseFirstValidSaberStyle( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &selectLevel ); - if ( ent->client->ps.weaponTime <= 0 ) - { //not busy, set it now + // g_active should take care of this, but... + if (ent->client->saber[0].stylesForbidden) { // have a style we have to use + WP_UseFirstValidSaberStyle(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &selectLevel); + if (ent->client->ps.weaponTime <= 0) { // not busy, set it now ent->client->ps.fd.saberAnimLevel = selectLevel; - } - else - { //can't set it now or we might cause unexpected chaining, so queue it + } else { // can't set it now or we might cause unexpected chaining, so queue it ent->client->saberCycleQueue = selectLevel; } } - } - else if ( ent->client->ps.saberHolstered == 0 ) - {//both blades on - if ( (ent->client->saber[0].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE) ) - {//can't turn it off manually - } - else if ( ent->client->saber[0].bladeStyle2Start > 0 - && (ent->client->saber[0].saberFlags2&SFL2_NO_MANUAL_DEACTIVATE2) ) - {//can't turn it off manually - } - else - { - //turn second one off + } else if (ent->client->ps.saberHolstered == 0) { // both blades on + if ((ent->client->saber[0].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE)) { // can't turn it off manually + } else if (ent->client->saber[0].bladeStyle2Start > 0 && + (ent->client->saber[0].saberFlags2 & SFL2_NO_MANUAL_DEACTIVATE2)) { // can't turn it off manually + } else { + // turn second one off G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOff); ent->client->ps.saberHolstered = 1; - //g_active should take care of this, but... - if ( ent->client->saber[0].singleBladeStyle != SS_NONE ) - { - if ( ent->client->ps.weaponTime <= 0 ) - { //not busy, set it now + // g_active should take care of this, but... + if (ent->client->saber[0].singleBladeStyle != SS_NONE) { + if (ent->client->ps.weaponTime <= 0) { // not busy, set it now ent->client->ps.fd.saberAnimLevel = ent->client->saber[0].singleBladeStyle; - } - else - { //can't set it now or we might cause unexpected chaining, so queue it + } else { // can't set it now or we might cause unexpected chaining, so queue it ent->client->saberCycleQueue = ent->client->saber[0].singleBladeStyle; } } } } - if (d_saberStanceDebug.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle staff blade.\n\"") ); + if (d_saberStanceDebug.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"SABERSTANCEDEBUG: Attempted to toggle staff blade.\n\"")); } return; } - if (ent->client->saberCycleQueue) - { //resume off of the queue if we haven't gotten a chance to update it yet + if (ent->client->saberCycleQueue) { // resume off of the queue if we haven't gotten a chance to update it yet selectLevel = ent->client->saberCycleQueue; - } - else - { + } else { selectLevel = ent->client->ps.fd.saberAnimLevel; } - if (level.gametype == GT_SIEGE && - ent->client->siegeClass != -1 && - bgSiegeClasses[ent->client->siegeClass].saberStance) - { //we have a flag of useable stances so cycle through it instead - int i = selectLevel+1; + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && + bgSiegeClasses[ent->client->siegeClass].saberStance) { // we have a flag of useable stances so cycle through it instead + int i = selectLevel + 1; usingSiegeStyle = qtrue; - while (i != selectLevel) - { //cycle around upward til we hit the next style or end up back on this one - if (i >= SS_NUM_SABER_STYLES) - { //loop back around to the first valid + while (i != selectLevel) { // cycle around upward til we hit the next style or end up back on this one + if (i >= SS_NUM_SABER_STYLES) { // loop back around to the first valid i = SS_FAST; } - if (bgSiegeClasses[ent->client->siegeClass].saberStance & (1 << i)) - { //we can use this one, select it and break out. + if (bgSiegeClasses[ent->client->siegeClass].saberStance & (1 << i)) { // we can use this one, select it and break out. selectLevel = i; break; } i++; } - if (d_saberStanceDebug.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"SABERSTANCEDEBUG: Attempted to cycle given class stance.\n\"") ); + if (d_saberStanceDebug.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"SABERSTANCEDEBUG: Attempted to cycle given class stance.\n\"")); } - } - else - { + } else { selectLevel++; - if ( selectLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] ) - { + if (selectLevel > ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { selectLevel = FORCE_LEVEL_1; } - if (d_saberStanceDebug.integer) - { - trap->SendServerCommand( ent-g_entities, va("print \"SABERSTANCEDEBUG: Attempted to cycle stance normally.\n\"") ); + if (d_saberStanceDebug.integer) { + trap->SendServerCommand(ent - g_entities, va("print \"SABERSTANCEDEBUG: Attempted to cycle stance normally.\n\"")); } } -/* -#ifndef FINAL_BUILD - switch ( selectLevel ) - { - case FORCE_LEVEL_1: - trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %sfast\n\"", S_COLOR_BLUE) ); - break; - case FORCE_LEVEL_2: - trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %smedium\n\"", S_COLOR_YELLOW) ); - break; - case FORCE_LEVEL_3: - trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %sstrong\n\"", S_COLOR_RED) ); - break; - } -#endif -*/ - if ( !usingSiegeStyle ) - { - //make sure it's valid, change it if not - WP_UseFirstValidSaberStyle( &ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &selectLevel ); + /* + #ifndef FINAL_BUILD + switch ( selectLevel ) + { + case FORCE_LEVEL_1: + trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %sfast\n\"", S_COLOR_BLUE) ); + break; + case FORCE_LEVEL_2: + trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %smedium\n\"", S_COLOR_YELLOW) ); + break; + case FORCE_LEVEL_3: + trap->SendServerCommand( ent-g_entities, va("print \"Lightsaber Combat Style: %sstrong\n\"", S_COLOR_RED) ); + break; + } + #endif + */ + if (!usingSiegeStyle) { + // make sure it's valid, change it if not + WP_UseFirstValidSaberStyle(&ent->client->saber[0], &ent->client->saber[1], ent->client->ps.saberHolstered, &selectLevel); } - if (ent->client->ps.weaponTime <= 0) - { //not busy, set it now + if (ent->client->ps.weaponTime <= 0) { // not busy, set it now ent->client->ps.fd.saberAnimLevelBase = ent->client->ps.fd.saberAnimLevel = selectLevel; - } - else - { //can't set it now or we might cause unexpected chaining, so queue it + } else { // can't set it now or we might cause unexpected chaining, so queue it ent->client->ps.fd.saberAnimLevelBase = ent->client->saberCycleQueue = selectLevel; } } -qboolean G_OtherPlayersDueling(void) -{ +qboolean G_OtherPlayersDueling(void) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->client && ent->client->ps.duelInProgress) - { + if (ent && ent->inuse && ent->client && ent->client->ps.duelInProgress) { return qtrue; } i++; @@ -2987,36 +2694,30 @@ qboolean G_OtherPlayersDueling(void) return qfalse; } -void Cmd_EngageDuel_f(gentity_t *ent) -{ +void Cmd_EngageDuel_f(gentity_t *ent) { trace_t tr; vec3_t forward, fwdOrg; - if (!g_privateDuel.integer) - { + if (!g_privateDuel.integer) { return; } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { //rather pointless in this mode.. - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NODUEL_GAMETYPE")) ); + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { // rather pointless in this mode.. + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NODUEL_GAMETYPE"))); return; } - //if (level.gametype >= GT_TEAM && level.gametype != GT_SIEGE) - if (level.gametype >= GT_TEAM) - { //no private dueling in team modes - trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NODUEL_GAMETYPE")) ); + // if (level.gametype >= GT_TEAM && level.gametype != GT_SIEGE) + if (level.gametype >= GT_TEAM) { // no private dueling in team modes + trap->SendServerCommand(ent - g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NODUEL_GAMETYPE"))); return; } - if (ent->client->ps.duelTime >= level.time) - { + if (ent->client->ps.duelTime >= level.time) { return; } - if (ent->client->ps.weapon != WP_SABER) - { + if (ent->client->ps.weapon != WP_SABER) { return; } @@ -3026,19 +2727,18 @@ void Cmd_EngageDuel_f(gentity_t *ent) return; } */ - //NOTE: No longer doing this.. + // NOTE: No longer doing this.. - if (ent->client->ps.saberInFlight) - { + if (ent->client->ps.saberInFlight) { return; } - if (ent->client->ps.duelInProgress) - { + if (ent->client->ps.duelInProgress) { return; } - //New: Don't let a player duel if he just did and hasn't waited 10 seconds yet (note: If someone challenges him, his duel timer will reset so he can accept) + // New: Don't let a player duel if he just did and hasn't waited 10 seconds yet (note: If someone challenges him, his duel timer will reset so he can + // accept) /*if (ent->client->ps.fd.privateDuelTime > level.time) { trap->SendServerCommand( ent-g_entities, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "CANTDUEL_JUSTDID")) ); @@ -3051,34 +2751,29 @@ void Cmd_EngageDuel_f(gentity_t *ent) return; }*/ - AngleVectors( ent->client->ps.viewangles, forward, NULL, NULL ); + AngleVectors(ent->client->ps.viewangles, forward, NULL, NULL); - fwdOrg[0] = ent->client->ps.origin[0] + forward[0]*256; - fwdOrg[1] = ent->client->ps.origin[1] + forward[1]*256; - fwdOrg[2] = (ent->client->ps.origin[2]+ent->client->ps.viewheight) + forward[2]*256; + fwdOrg[0] = ent->client->ps.origin[0] + forward[0] * 256; + fwdOrg[1] = ent->client->ps.origin[1] + forward[1] * 256; + fwdOrg[2] = (ent->client->ps.origin[2] + ent->client->ps.viewheight) + forward[2] * 256; trap->Trace(&tr, ent->client->ps.origin, NULL, NULL, fwdOrg, ent->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1 && tr.entityNum < MAX_CLIENTS) - { + if (tr.fraction != 1 && tr.entityNum < MAX_CLIENTS) { gentity_t *challenged = &g_entities[tr.entityNum]; - if (!challenged || !challenged->client || !challenged->inuse || - challenged->health < 1 || challenged->client->ps.stats[STAT_HEALTH] < 1 || - challenged->client->ps.weapon != WP_SABER || challenged->client->ps.duelInProgress || - challenged->client->ps.saberInFlight) - { + if (!challenged || !challenged->client || !challenged->inuse || challenged->health < 1 || challenged->client->ps.stats[STAT_HEALTH] < 1 || + challenged->client->ps.weapon != WP_SABER || challenged->client->ps.duelInProgress || challenged->client->ps.saberInFlight) { return; } - if (level.gametype >= GT_TEAM && OnSameTeam(ent, challenged)) - { + if (level.gametype >= GT_TEAM && OnSameTeam(ent, challenged)) { return; } - if (challenged->client->ps.duelIndex == ent->s.number && challenged->client->ps.duelTime >= level.time) - { - trap->SendServerCommand( /*challenged-g_entities*/-1, va("print \"%s %s %s!\n\"", challenged->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELACCEPT"), ent->client->pers.netname) ); + if (challenged->client->ps.duelIndex == ent->s.number && challenged->client->ps.duelTime >= level.time) { + trap->SendServerCommand(/*challenged-g_entities*/ -1, va("print \"%s %s %s!\n\"", challenged->client->pers.netname, + G_GetStringEdString("MP_SVGAME", "PLDUELACCEPT"), ent->client->pers.netname)); ent->client->ps.duelInProgress = qtrue; challenged->client->ps.duelInProgress = qtrue; @@ -3089,45 +2784,38 @@ void Cmd_EngageDuel_f(gentity_t *ent) G_AddEvent(ent, EV_PRIVATE_DUEL, 1); G_AddEvent(challenged, EV_PRIVATE_DUEL, 1); - //Holster their sabers now, until the duel starts (then they'll get auto-turned on to look cool) + // Holster their sabers now, until the duel starts (then they'll get auto-turned on to look cool) - if (!ent->client->ps.saberHolstered) - { - if (ent->client->saber[0].soundOff) - { + if (!ent->client->ps.saberHolstered) { + if (ent->client->saber[0].soundOff) { G_Sound(ent, CHAN_AUTO, ent->client->saber[0].soundOff); } - if (ent->client->saber[1].soundOff && - ent->client->saber[1].model[0]) - { + if (ent->client->saber[1].soundOff && ent->client->saber[1].model[0]) { G_Sound(ent, CHAN_AUTO, ent->client->saber[1].soundOff); } ent->client->ps.weaponTime = 400; ent->client->ps.saberHolstered = 2; } - if (!challenged->client->ps.saberHolstered) - { - if (challenged->client->saber[0].soundOff) - { + if (!challenged->client->ps.saberHolstered) { + if (challenged->client->saber[0].soundOff) { G_Sound(challenged, CHAN_AUTO, challenged->client->saber[0].soundOff); } - if (challenged->client->saber[1].soundOff && - challenged->client->saber[1].model[0]) - { + if (challenged->client->saber[1].soundOff && challenged->client->saber[1].model[0]) { G_Sound(challenged, CHAN_AUTO, challenged->client->saber[1].soundOff); } challenged->client->ps.weaponTime = 400; challenged->client->ps.saberHolstered = 2; } - } - else - { - //Print the message that a player has been challenged in private, only announce the actual duel initiation in private - trap->SendServerCommand( challenged-g_entities, va("cp \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELCHALLENGE")) ); - trap->SendServerCommand( ent-g_entities, va("cp \"%s %s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELCHALLENGED"), challenged->client->pers.netname) ); + } else { + // Print the message that a player has been challenged in private, only announce the actual duel initiation in private + trap->SendServerCommand(challenged - g_entities, + va("cp \"%s %s\n\"", ent->client->pers.netname, G_GetStringEdString("MP_SVGAME", "PLDUELCHALLENGE"))); + trap->SendServerCommand(ent - g_entities, + va("cp \"%s %s\n\"", G_GetStringEdString("MP_SVGAME", "PLDUELCHALLENGED"), challenged->client->pers.netname)); } - challenged->client->ps.fd.privateDuelTime = 0; //reset the timer in case this player just got out of a duel. He should still be able to accept the challenge. + challenged->client->ps.fd.privateDuelTime = + 0; // reset the timer in case this player just got out of a duel. He should still be able to accept the challenge. ent->client->ps.forceHandExtend = HANDEXTEND_DUELCHALLENGE; ent->client->ps.forceHandExtendTime = level.time + 1000; @@ -3138,79 +2826,66 @@ void Cmd_EngageDuel_f(gentity_t *ent) } #ifndef FINAL_BUILD -extern stringID_table_t animTable[MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; -void Cmd_DebugSetSaberMove_f(gentity_t *self) -{ +void Cmd_DebugSetSaberMove_f(gentity_t *self) { int argNum = trap->Argc(); char arg[MAX_STRING_CHARS]; - if (argNum < 2) - { + if (argNum < 2) { return; } - trap->Argv( 1, arg, sizeof( arg ) ); + trap->Argv(1, arg, sizeof(arg)); - if (!arg[0]) - { + if (!arg[0]) { return; } self->client->ps.saberMove = atoi(arg); self->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; - if (self->client->ps.saberMove >= LS_MOVE_MAX) - { - self->client->ps.saberMove = LS_MOVE_MAX-1; + if (self->client->ps.saberMove >= LS_MOVE_MAX) { + self->client->ps.saberMove = LS_MOVE_MAX - 1; } Com_Printf("Anim for move: %s\n", animTable[saberMoveData[self->client->ps.saberMove].animToUse].name); } -void Cmd_DebugSetBodyAnim_f(gentity_t *self) -{ +void Cmd_DebugSetBodyAnim_f(gentity_t *self) { int argNum = trap->Argc(); char arg[MAX_STRING_CHARS]; int i = 0; - if (argNum < 2) - { + if (argNum < 2) { return; } - trap->Argv( 1, arg, sizeof( arg ) ); + trap->Argv(1, arg, sizeof(arg)); - if (!arg[0]) - { + if (!arg[0]) { return; } - while (i < MAX_ANIMATIONS) - { - if (!Q_stricmp(arg, animTable[i].name)) - { + while (i < MAX_ANIMATIONS) { + if (!Q_stricmp(arg, animTable[i].name)) { break; } i++; } - if (i == MAX_ANIMATIONS) - { + if (i == MAX_ANIMATIONS) { Com_Printf("Animation '%s' does not exist\n", arg); return; } - G_SetAnim(self, NULL, SETANIM_BOTH, i, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + G_SetAnim(self, NULL, SETANIM_BOTH, i, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); Com_Printf("Set body anim to %s\n", arg); } #endif -void StandardSetBodyAnim(gentity_t *self, int anim, int flags) -{ - G_SetAnim(self, NULL, SETANIM_BOTH, anim, flags, 0); -} +void StandardSetBodyAnim(gentity_t *self, int anim, int flags) { G_SetAnim(self, NULL, SETANIM_BOTH, anim, flags, 0); } void DismembermentTest(gentity_t *self); @@ -3218,45 +2893,36 @@ void Bot_SetForcedMovement(int bot, int forward, int right, int up); #ifndef FINAL_BUILD extern void DismembermentByNum(gentity_t *self, int num); -extern void G_SetVehDamageFlags( gentity_t *veh, int shipSurf, int damageLevel ); +extern void G_SetVehDamageFlags(gentity_t *veh, int shipSurf, int damageLevel); #endif -qboolean TryGrapple(gentity_t *ent) -{ - if (ent->client->ps.weaponTime > 0) - { //weapon busy +qboolean TryGrapple(gentity_t *ent) { + if (ent->client->ps.weaponTime > 0) { // weapon busy return qfalse; } - if (ent->client->ps.forceHandExtend != HANDEXTEND_NONE) - { //force power or knockdown or something + if (ent->client->ps.forceHandExtend != HANDEXTEND_NONE) { // force power or knockdown or something return qfalse; } - if (ent->client->grappleState) - { //already grappling? but weapontime should be > 0 then.. + if (ent->client->grappleState) { // already grappling? but weapontime should be > 0 then.. return qfalse; } - if (ent->client->ps.weapon != WP_SABER && ent->client->ps.weapon != WP_MELEE) - { + if (ent->client->ps.weapon != WP_SABER && ent->client->ps.weapon != WP_MELEE) { return qfalse; } - if (ent->client->ps.weapon == WP_SABER && !ent->client->ps.saberHolstered) - { + if (ent->client->ps.weapon == WP_SABER && !ent->client->ps.saberHolstered) { Cmd_ToggleSaber_f(ent); - if (!ent->client->ps.saberHolstered) - { //must have saber holstered + if (!ent->client->ps.saberHolstered) { // must have saber holstered return qfalse; } } - //G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_PA_1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (ent->client->ps.torsoAnim == BOTH_KYLE_GRAB) - { //providing the anim set succeeded.. - ent->client->ps.torsoTimer += 500; //make the hand stick out a little longer than it normally would - if (ent->client->ps.legsAnim == ent->client->ps.torsoAnim) - { + // G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_PA_1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + G_SetAnim(ent, &ent->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_GRAB, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (ent->client->ps.torsoAnim == BOTH_KYLE_GRAB) { // providing the anim set succeeded.. + ent->client->ps.torsoTimer += 500; // make the hand stick out a little longer than it normally would + if (ent->client->ps.legsAnim == ent->client->ps.torsoAnim) { ent->client->ps.legsTimer = ent->client->ps.torsoTimer; } ent->client->ps.weaponTime = ent->client->ps.torsoTimer; @@ -3267,100 +2933,97 @@ qboolean TryGrapple(gentity_t *ent) return qfalse; } -void Cmd_TargetUse_f( gentity_t *ent ) -{ - if ( trap->Argc() > 1 ) - { +void Cmd_TargetUse_f(gentity_t *ent) { + if (trap->Argc() > 1) { char sArg[MAX_STRING_CHARS] = {0}; gentity_t *targ; - trap->Argv( 1, sArg, sizeof( sArg ) ); - targ = G_Find( NULL, FOFS( targetname ), sArg ); + trap->Argv(1, sArg, sizeof(sArg)); + targ = G_Find(NULL, FOFS(targetname), sArg); - while ( targ ) - { - if ( targ->use ) - targ->use( targ, ent, ent ); - targ = G_Find( targ, FOFS( targetname ), sArg ); + while (targ) { + if (targ->use) + targ->use(targ, ent, ent); + targ = G_Find(targ, FOFS(targetname), sArg); } } } -void Cmd_TheDestroyer_f( gentity_t *ent ) { - if ( !ent->client->ps.saberHolstered || ent->client->ps.weapon != WP_SABER ) +void Cmd_TheDestroyer_f(gentity_t *ent) { + if (!ent->client->ps.saberHolstered || ent->client->ps.weapon != WP_SABER) return; - Cmd_ToggleSaber_f( ent ); + Cmd_ToggleSaber_f(ent); } -void Cmd_BotMoveForward_f( gentity_t *ent ) { +void Cmd_BotMoveForward_f(gentity_t *ent) { int arg = 4000; int bCl = 0; char sarg[MAX_STRING_CHARS]; - assert( trap->Argc() > 1 ); - trap->Argv( 1, sarg, sizeof( sarg ) ); + assert(trap->Argc() > 1); + trap->Argv(1, sarg, sizeof(sarg)); - assert( sarg[0] ); - bCl = atoi( sarg ); - Bot_SetForcedMovement( bCl, arg, -1, -1 ); + assert(sarg[0]); + bCl = atoi(sarg); + Bot_SetForcedMovement(bCl, arg, -1, -1); } -void Cmd_BotMoveBack_f( gentity_t *ent ) { +void Cmd_BotMoveBack_f(gentity_t *ent) { int arg = -4000; int bCl = 0; char sarg[MAX_STRING_CHARS]; - assert( trap->Argc() > 1 ); - trap->Argv( 1, sarg, sizeof( sarg ) ); + assert(trap->Argc() > 1); + trap->Argv(1, sarg, sizeof(sarg)); - assert( sarg[0] ); - bCl = atoi( sarg ); - Bot_SetForcedMovement( bCl, arg, -1, -1 ); + assert(sarg[0]); + bCl = atoi(sarg); + Bot_SetForcedMovement(bCl, arg, -1, -1); } -void Cmd_BotMoveRight_f( gentity_t *ent ) { +void Cmd_BotMoveRight_f(gentity_t *ent) { int arg = 4000; int bCl = 0; char sarg[MAX_STRING_CHARS]; - assert( trap->Argc() > 1 ); - trap->Argv( 1, sarg, sizeof( sarg ) ); + assert(trap->Argc() > 1); + trap->Argv(1, sarg, sizeof(sarg)); - assert( sarg[0] ); - bCl = atoi( sarg ); - Bot_SetForcedMovement( bCl, -1, arg, -1 ); + assert(sarg[0]); + bCl = atoi(sarg); + Bot_SetForcedMovement(bCl, -1, arg, -1); } -void Cmd_BotMoveLeft_f( gentity_t *ent ) { +void Cmd_BotMoveLeft_f(gentity_t *ent) { int arg = -4000; int bCl = 0; char sarg[MAX_STRING_CHARS]; - assert( trap->Argc() > 1 ); - trap->Argv( 1, sarg, sizeof( sarg ) ); + assert(trap->Argc() > 1); + trap->Argv(1, sarg, sizeof(sarg)); - assert( sarg[0] ); - bCl = atoi( sarg ); - Bot_SetForcedMovement( bCl, -1, arg, -1 ); + assert(sarg[0]); + bCl = atoi(sarg); + Bot_SetForcedMovement(bCl, -1, arg, -1); } -void Cmd_BotMoveUp_f( gentity_t *ent ) { +void Cmd_BotMoveUp_f(gentity_t *ent) { int arg = 4000; int bCl = 0; char sarg[MAX_STRING_CHARS]; - assert( trap->Argc() > 1 ); - trap->Argv( 1, sarg, sizeof( sarg ) ); + assert(trap->Argc() > 1); + trap->Argv(1, sarg, sizeof(sarg)); - assert( sarg[0] ); - bCl = atoi( sarg ); - Bot_SetForcedMovement( bCl, -1, -1, arg ); + assert(sarg[0]); + bCl = atoi(sarg); + Bot_SetForcedMovement(bCl, -1, -1, arg); } -void Cmd_AddBot_f( gentity_t *ent ) { - //because addbot isn't a recognized command unless you're the server, but it is in the menus regardless - trap->SendServerCommand( ent-g_entities, va( "print \"%s.\n\"", G_GetStringEdString( "MP_SVGAME", "ONLY_ADD_BOTS_AS_SERVER" ) ) ); +void Cmd_AddBot_f(gentity_t *ent) { + // because addbot isn't a recognized command unless you're the server, but it is in the menus regardless + trap->SendServerCommand(ent - g_entities, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "ONLY_ADD_BOTS_AS_SERVER"))); } /* @@ -3369,111 +3032,100 @@ ClientCommand ================= */ -#define CMD_NOINTERMISSION (1<<0) -#define CMD_CHEAT (1<<1) -#define CMD_ALIVE (1<<2) +#define CMD_NOINTERMISSION (1 << 0) +#define CMD_CHEAT (1 << 1) +#define CMD_ALIVE (1 << 2) typedef struct command_s { - const char *name; - void (*func)(gentity_t *ent); - int flags; + const char *name; + void (*func)(gentity_t *ent); + int flags; } command_t; -int cmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((command_t*)b)->name ); -} +int cmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((command_t *)b)->name); } command_t commands[] = { - { "addbot", Cmd_AddBot_f, 0 }, - { "callteamvote", Cmd_CallTeamVote_f, CMD_NOINTERMISSION }, - { "callvote", Cmd_CallVote_f, CMD_NOINTERMISSION }, - { "debugBMove_Back", Cmd_BotMoveBack_f, CMD_CHEAT|CMD_ALIVE }, - { "debugBMove_Forward", Cmd_BotMoveForward_f, CMD_CHEAT|CMD_ALIVE }, - { "debugBMove_Left", Cmd_BotMoveLeft_f, CMD_CHEAT|CMD_ALIVE }, - { "debugBMove_Right", Cmd_BotMoveRight_f, CMD_CHEAT|CMD_ALIVE }, - { "debugBMove_Up", Cmd_BotMoveUp_f, CMD_CHEAT|CMD_ALIVE }, - { "duelteam", Cmd_DuelTeam_f, CMD_NOINTERMISSION }, - { "follow", Cmd_Follow_f, CMD_NOINTERMISSION }, - { "follownext", Cmd_FollowNext_f, CMD_NOINTERMISSION }, - { "followprev", Cmd_FollowPrev_f, CMD_NOINTERMISSION }, - { "forcechanged", Cmd_ForceChanged_f, 0 }, - { "gc", Cmd_GameCommand_f, CMD_NOINTERMISSION }, - { "give", Cmd_Give_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "giveother", Cmd_GiveOther_f, CMD_CHEAT|CMD_NOINTERMISSION }, - { "god", Cmd_God_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "kill", Cmd_Kill_f, CMD_ALIVE|CMD_NOINTERMISSION }, - { "killother", Cmd_KillOther_f, CMD_CHEAT|CMD_NOINTERMISSION }, -// { "kylesmash", TryGrapple, 0 }, - { "levelshot", Cmd_LevelShot_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "maplist", Cmd_MapList_f, CMD_NOINTERMISSION }, - { "noclip", Cmd_Noclip_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "notarget", Cmd_Notarget_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "npc", Cmd_NPC_f, CMD_CHEAT|CMD_ALIVE }, - { "say", Cmd_Say_f, 0 }, - { "say_team", Cmd_SayTeam_f, 0 }, - { "score", Cmd_Score_f, 0 }, - { "setviewpos", Cmd_SetViewpos_f, CMD_CHEAT|CMD_NOINTERMISSION }, - { "siegeclass", Cmd_SiegeClass_f, CMD_NOINTERMISSION }, - { "team", Cmd_Team_f, CMD_NOINTERMISSION }, -// { "teamtask", Cmd_TeamTask_f, CMD_NOINTERMISSION }, - { "teamvote", Cmd_TeamVote_f, CMD_NOINTERMISSION }, - { "tell", Cmd_Tell_f, 0 }, - { "thedestroyer", Cmd_TheDestroyer_f, CMD_CHEAT|CMD_ALIVE|CMD_NOINTERMISSION }, - { "t_use", Cmd_TargetUse_f, CMD_CHEAT|CMD_ALIVE }, - { "voice_cmd", Cmd_VoiceCommand_f, CMD_NOINTERMISSION }, - { "vote", Cmd_Vote_f, CMD_NOINTERMISSION }, - { "where", Cmd_Where_f, CMD_NOINTERMISSION }, + {"addbot", Cmd_AddBot_f, 0}, + {"callteamvote", Cmd_CallTeamVote_f, CMD_NOINTERMISSION}, + {"callvote", Cmd_CallVote_f, CMD_NOINTERMISSION}, + {"debugBMove_Back", Cmd_BotMoveBack_f, CMD_CHEAT | CMD_ALIVE}, + {"debugBMove_Forward", Cmd_BotMoveForward_f, CMD_CHEAT | CMD_ALIVE}, + {"debugBMove_Left", Cmd_BotMoveLeft_f, CMD_CHEAT | CMD_ALIVE}, + {"debugBMove_Right", Cmd_BotMoveRight_f, CMD_CHEAT | CMD_ALIVE}, + {"debugBMove_Up", Cmd_BotMoveUp_f, CMD_CHEAT | CMD_ALIVE}, + {"duelteam", Cmd_DuelTeam_f, CMD_NOINTERMISSION}, + {"follow", Cmd_Follow_f, CMD_NOINTERMISSION}, + {"follownext", Cmd_FollowNext_f, CMD_NOINTERMISSION}, + {"followprev", Cmd_FollowPrev_f, CMD_NOINTERMISSION}, + {"forcechanged", Cmd_ForceChanged_f, 0}, + {"gc", Cmd_GameCommand_f, CMD_NOINTERMISSION}, + {"give", Cmd_Give_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"giveother", Cmd_GiveOther_f, CMD_CHEAT | CMD_NOINTERMISSION}, + {"god", Cmd_God_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"kill", Cmd_Kill_f, CMD_ALIVE | CMD_NOINTERMISSION}, + {"killother", Cmd_KillOther_f, CMD_CHEAT | CMD_NOINTERMISSION}, + // { "kylesmash", TryGrapple, 0 }, + {"levelshot", Cmd_LevelShot_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"maplist", Cmd_MapList_f, CMD_NOINTERMISSION}, + {"noclip", Cmd_Noclip_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"notarget", Cmd_Notarget_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"npc", Cmd_NPC_f, CMD_CHEAT | CMD_ALIVE}, + {"say", Cmd_Say_f, 0}, + {"say_team", Cmd_SayTeam_f, 0}, + {"score", Cmd_Score_f, 0}, + {"setviewpos", Cmd_SetViewpos_f, CMD_CHEAT | CMD_NOINTERMISSION}, + {"siegeclass", Cmd_SiegeClass_f, CMD_NOINTERMISSION}, + {"team", Cmd_Team_f, CMD_NOINTERMISSION}, + // { "teamtask", Cmd_TeamTask_f, CMD_NOINTERMISSION }, + {"teamvote", Cmd_TeamVote_f, CMD_NOINTERMISSION}, + {"tell", Cmd_Tell_f, 0}, + {"thedestroyer", Cmd_TheDestroyer_f, CMD_CHEAT | CMD_ALIVE | CMD_NOINTERMISSION}, + {"t_use", Cmd_TargetUse_f, CMD_CHEAT | CMD_ALIVE}, + {"voice_cmd", Cmd_VoiceCommand_f, CMD_NOINTERMISSION}, + {"vote", Cmd_Vote_f, CMD_NOINTERMISSION}, + {"where", Cmd_Where_f, CMD_NOINTERMISSION}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); -void ClientCommand( int clientNum ) { - gentity_t *ent = NULL; - char cmd[MAX_TOKEN_CHARS] = {0}; - command_t *command = NULL; +void ClientCommand(int clientNum) { + gentity_t *ent = NULL; + char cmd[MAX_TOKEN_CHARS] = {0}; + command_t *command = NULL; ent = g_entities + clientNum; - if ( !ent->client || ent->client->pers.connected != CON_CONNECTED ) { - G_SecurityLogPrintf( "ClientCommand(%d) without an active connection\n", clientNum ); - return; // not fully in game yet + if (!ent->client || ent->client->pers.connected != CON_CONNECTED) { + G_SecurityLogPrintf("ClientCommand(%d) without an active connection\n", clientNum); + return; // not fully in game yet } - trap->Argv( 0, cmd, sizeof( cmd ) ); + trap->Argv(0, cmd, sizeof(cmd)); - //rww - redirect bot commands - if ( strstr( cmd, "bot_" ) && AcceptBotCommand( cmd, ent ) ) + // rww - redirect bot commands + if (strstr(cmd, "bot_") && AcceptBotCommand(cmd, ent)) return; - //end rww + // end rww - command = (command_t *)Q_LinearSearch( cmd, commands, numCommands, sizeof( commands[0] ), cmdcmp ); - if ( !command ) - { - trap->SendServerCommand( clientNum, va( "print \"Unknown command %s\n\"", cmd ) ); + command = (command_t *)Q_LinearSearch(cmd, commands, numCommands, sizeof(commands[0]), cmdcmp); + if (!command) { + trap->SendServerCommand(clientNum, va("print \"Unknown command %s\n\"", cmd)); return; } - else if ( (command->flags & CMD_NOINTERMISSION) - && ( level.intermissionQueued || level.intermissiontime ) ) - { - trap->SendServerCommand( clientNum, va( "print \"%s (%s)\n\"", G_GetStringEdString( "MP_SVGAME", "CANNOT_TASK_INTERMISSION" ), cmd ) ); + else if ((command->flags & CMD_NOINTERMISSION) && (level.intermissionQueued || level.intermissiontime)) { + trap->SendServerCommand(clientNum, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "CANNOT_TASK_INTERMISSION"), cmd)); return; } - else if ( (command->flags & CMD_CHEAT) - && !sv_cheats.integer ) - { - trap->SendServerCommand( clientNum, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "NOCHEATS" ) ) ); + else if ((command->flags & CMD_CHEAT) && !sv_cheats.integer) { + trap->SendServerCommand(clientNum, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "NOCHEATS"))); return; } - else if ( (command->flags & CMD_ALIVE) - && (ent->health <= 0 - || ent->client->tempSpectate >= level.time - || ent->client->sess.sessionTeam == TEAM_SPECTATOR) ) - { - trap->SendServerCommand( clientNum, va( "print \"%s\n\"", G_GetStringEdString( "MP_SVGAME", "MUSTBEALIVE" ) ) ); + else if ((command->flags & CMD_ALIVE) && (ent->health <= 0 || ent->client->tempSpectate >= level.time || ent->client->sess.sessionTeam == TEAM_SPECTATOR)) { + trap->SendServerCommand(clientNum, va("print \"%s\n\"", G_GetStringEdString("MP_SVGAME", "MUSTBEALIVE"))); return; } else - command->func( ent ); + command->func(ent); } diff --git a/codemp/game/g_combat.c b/codemp/game/g_combat.c index 3540974377..c5599b2cbd 100644 --- a/codemp/game/g_combat.c +++ b/codemp/game/g_combat.c @@ -26,55 +26,46 @@ along with this program; if not, see . #include "b_local.h" #include "bg_saga.h" -extern int G_ShipSurfaceForSurfName( const char *surfaceName ); -extern qboolean G_FlyVehicleDestroySurface( gentity_t *veh, int surface ); -extern void G_VehicleSetDamageLocFlags( gentity_t *veh, int impactDir, int deathPoint ); -extern void G_VehUpdateShields( gentity_t *targ ); -extern void G_LetGoOfWall( gentity_t *ent ); -extern void BG_ClearRocketLock( playerState_t *ps ); -//rww - pd +extern int G_ShipSurfaceForSurfName(const char *surfaceName); +extern qboolean G_FlyVehicleDestroySurface(gentity_t *veh, int surface); +extern void G_VehicleSetDamageLocFlags(gentity_t *veh, int impactDir, int deathPoint); +extern void G_VehUpdateShields(gentity_t *targ); +extern void G_LetGoOfWall(gentity_t *ent); +extern void BG_ClearRocketLock(playerState_t *ps); +// rww - pd void BotDamageNotification(gclient_t *bot, gentity_t *attacker); -//end rww +// end rww void ThrowSaberToAttacker(gentity_t *self, gentity_t *attacker); -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) -{ - if(self->target) - { +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { + if (self->target) { G_UseTargets(self, attacker); } - //remove my script_targetname - G_FreeEntity( self ); + // remove my script_targetname + G_FreeEntity(self); } -qboolean G_HeavyMelee( gentity_t *attacker ) -{ - if (level.gametype == GT_SIEGE - && attacker - && attacker->client - && attacker->client->siegeClass != -1 - && (bgSiegeClasses[attacker->client->siegeClass].classflags & (1<client && attacker->client->siegeClass != -1 && + (bgSiegeClasses[attacker->client->siegeClass].classflags & (1 << CFL_HEAVYMELEE))) { return qtrue; } return qfalse; } -int G_GetHitLocation(gentity_t *target, vec3_t ppoint) -{ - vec3_t point, point_dir; - vec3_t forward, right, up; - vec3_t tangles, tcenter; -// float tradius; - float udot, fdot, rdot; - int Vertical, Forward, Lateral; - int HitLoc; +int G_GetHitLocation(gentity_t *target, vec3_t ppoint) { + vec3_t point, point_dir; + vec3_t forward, right, up; + vec3_t tangles, tcenter; + // float tradius; + float udot, fdot, rdot; + int Vertical, Forward, Lateral; + int HitLoc; // Get target forward, right and up. - if(target->client) - { + if (target->client) { // Ignore player's pitch and roll. VectorSet(tangles, 0, target->r.currentAngles[YAW], 0); } @@ -86,197 +77,129 @@ int G_GetHitLocation(gentity_t *target, vec3_t ppoint) VectorScale(tcenter, 0.5, tcenter); // Get radius width of target. -// tradius = (fabs(target->r.maxs[0]) + fabs(target->r.maxs[1]) + fabs(target->r.mins[0]) + fabs(target->r.mins[1]))/4; + // tradius = (fabs(target->r.maxs[0]) + fabs(target->r.maxs[1]) + fabs(target->r.mins[0]) + fabs(target->r.mins[1]))/4; // Get impact point. - if(ppoint && !VectorCompare(ppoint, vec3_origin)) - { + if (ppoint && !VectorCompare(ppoint, vec3_origin)) { VectorCopy(ppoint, point); - } - else - { + } else { return HL_NONE; } -/* -//get impact dir - if(pdir && !VectorCompare(pdir, vec3_origin)) - { - VectorCopy(pdir, dir); - } - else - { - return; - } + /* + //get impact dir + if(pdir && !VectorCompare(pdir, vec3_origin)) + { + VectorCopy(pdir, dir); + } + else + { + return; + } -//put point at controlled distance from center - VectorSubtract(point, tcenter, tempvec); - tempvec[2] = 0; - hdist = VectorLength(tempvec); + //put point at controlled distance from center + VectorSubtract(point, tcenter, tempvec); + tempvec[2] = 0; + hdist = VectorLength(tempvec); - VectorMA(point, hdist - tradius, dir, point); - //now a point on the surface of a cylinder with a radius of tradius -*/ + VectorMA(point, hdist - tradius, dir, point); + //now a point on the surface of a cylinder with a radius of tradius + */ VectorSubtract(point, tcenter, point_dir); VectorNormalize(point_dir); // Get bottom to top (vertical) position index udot = DotProduct(up, point_dir); - if(udot>.800) - { + if (udot > .800) { Vertical = 4; - } - else if(udot>.400) - { + } else if (udot > .400) { Vertical = 3; - } - else if(udot>-.333) - { + } else if (udot > -.333) { Vertical = 2; - } - else if(udot>-.666) - { + } else if (udot > -.666) { Vertical = 1; - } - else - { + } else { Vertical = 0; } // Get back to front (forward) position index. fdot = DotProduct(forward, point_dir); - if(fdot>.666) - { + if (fdot > .666) { Forward = 4; - } - else if(fdot>.333) - { + } else if (fdot > .333) { Forward = 3; - } - else if(fdot>-.333) - { + } else if (fdot > -.333) { Forward = 2; - } - else if(fdot>-.666) - { + } else if (fdot > -.666) { Forward = 1; - } - else - { + } else { Forward = 0; } // Get left to right (lateral) position index. rdot = DotProduct(right, point_dir); - if(rdot>.666) - { + if (rdot > .666) { Lateral = 4; - } - else if(rdot>.333) - { + } else if (rdot > .333) { Lateral = 3; - } - else if(rdot>-.333) - { + } else if (rdot > -.333) { Lateral = 2; - } - else if(rdot>-.666) - { + } else if (rdot > -.666) { Lateral = 1; - } - else - { + } else { Lateral = 0; } HitLoc = Vertical * 25 + Forward * 5 + Lateral; - if(HitLoc <= 10) - { + if (HitLoc <= 10) { // Feet. - if ( rdot > 0 ) - { + if (rdot > 0) { return HL_FOOT_RT; - } - else - { + } else { return HL_FOOT_LT; } - } - else if(HitLoc <= 50) - { + } else if (HitLoc <= 50) { // Legs. - if ( rdot > 0 ) - { + if (rdot > 0) { return HL_LEG_RT; - } - else - { + } else { return HL_LEG_LT; } - } - else if(HitLoc == 56||HitLoc == 60||HitLoc == 61||HitLoc == 65||HitLoc == 66||HitLoc == 70) - { + } else if (HitLoc == 56 || HitLoc == 60 || HitLoc == 61 || HitLoc == 65 || HitLoc == 66 || HitLoc == 70) { // Hands. - if ( rdot > 0 ) - { + if (rdot > 0) { return HL_HAND_RT; - } - else - { + } else { return HL_HAND_LT; } - } - else if(HitLoc == 83||HitLoc == 87||HitLoc == 88||HitLoc == 92||HitLoc == 93||HitLoc == 97) - { + } else if (HitLoc == 83 || HitLoc == 87 || HitLoc == 88 || HitLoc == 92 || HitLoc == 93 || HitLoc == 97) { // Arms. - if ( rdot > 0 ) - { + if (rdot > 0) { return HL_ARM_RT; - } - else - { + } else { return HL_ARM_LT; } - } - else if((HitLoc >= 107 && HitLoc <= 109)||(HitLoc >= 112 && HitLoc <= 114)||(HitLoc >= 117 && HitLoc <= 119)) - { + } else if ((HitLoc >= 107 && HitLoc <= 109) || (HitLoc >= 112 && HitLoc <= 114) || (HitLoc >= 117 && HitLoc <= 119)) { // Head. return HL_HEAD; - } - else - { - if(udot < 0.3) - { + } else { + if (udot < 0.3) { return HL_WAIST; - } - else if(fdot < 0) - { - if(rdot > 0.4) - { + } else if (fdot < 0) { + if (rdot > 0.4) { return HL_BACK_RT; - } - else if(rdot < -0.4) - { + } else if (rdot < -0.4) { return HL_BACK_LT; - } - else if(fdot < 0) - { + } else if (fdot < 0) { return HL_BACK; } - } - else - { - if(rdot > 0.3) - { + } else { + if (rdot > 0.3) { return HL_CHEST_RT; - } - else if(rdot < -0.3) - { + } else if (rdot < -0.3) { return HL_CHEST_LT; - } - else if(fdot < 0) - { + } else if (fdot < 0) { return HL_CHEST; } } @@ -385,58 +308,53 @@ int G_PickPainAnim( gentity_t *self, vec3_t point, int damage ) } */ -void ExplodeDeath( gentity_t *self ) -{ -// gentity_t *tent; - vec3_t forward; +void ExplodeDeath(gentity_t *self) { + // gentity_t *tent; + vec3_t forward; - self->takedamage = qfalse;//stop chain reaction runaway loops + self->takedamage = qfalse; // stop chain reaction runaway loops self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; - VectorCopy( self->r.currentOrigin, self->s.pos.trBase ); + VectorCopy(self->r.currentOrigin, self->s.pos.trBase); -// tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); + // tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); AngleVectors(self->s.angles, forward, NULL, NULL); -/* - if ( self->fxID > 0 ) - { - G_PlayEffect( self->fxID, self->r.currentOrigin, forward ); - } - else - */ + /* + if ( self->fxID > 0 ) + { + G_PlayEffect( self->fxID, self->r.currentOrigin, forward ); + } + else + */ { -// CG_SurfaceExplosion( self->r.currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all exploders! -// G_Sound(self, self->sounds ); + // CG_SurfaceExplosion( self->r.currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all + //exploders! G_Sound(self, self->sounds ); } - if(self->splashDamage > 0 && self->splashRadius > 0) - { + if (self->splashDamage > 0 && self->splashRadius > 0) { gentity_t *attacker = self; - if ( self->parent ) - { + if (self->parent) { attacker = self->parent; } - G_RadiusDamage( self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, - attacker, NULL, MOD_UNKNOWN ); + G_RadiusDamage(self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, NULL, MOD_UNKNOWN); } - ObjectDie( self, self, self, 20, 0 ); + ObjectDie(self, self, self, 20, 0); } - /* ============ ScorePlum ============ */ -void ScorePlum( gentity_t *ent, vec3_t origin, int score ) { +void ScorePlum(gentity_t *ent, vec3_t origin, int score) { gentity_t *plum; - plum = G_TempEntity( origin, EV_SCOREPLUM ); + plum = G_TempEntity(origin, EV_SCOREPLUM); // only send this temp entity to a single client plum->r.svFlags |= SVF_SINGLECLIENT; plum->r.singleClient = ent->s.number; @@ -452,9 +370,8 @@ AddScore Adds score to both the client and his team ============ */ -extern qboolean g_dontPenalizeTeam; //g_cmds.c -void AddScore( gentity_t *ent, vec3_t origin, int score ) -{ +extern qboolean g_dontPenalizeTeam; // g_cmds.c +void AddScore(gentity_t *ent, vec3_t origin, int score) { /* if (level.gametype == GT_SIEGE) { //no scoring in this gametype at all. @@ -462,19 +379,19 @@ void AddScore( gentity_t *ent, vec3_t origin, int score ) } */ - if ( !ent->client ) { + if (!ent->client) { return; } // no scoring during pre-match warmup - if ( level.warmupTime ) { + if (level.warmupTime) { return; } // show score plum - //ScorePlum(ent, origin, score); + // ScorePlum(ent, origin, score); // ent->client->ps.persistant[PERS_SCORE] += score; - if ( level.gametype == GT_TEAM && !g_dontPenalizeTeam ) - level.teamScores[ ent->client->ps.persistant[PERS_TEAM] ] += score; + if (level.gametype == GT_TEAM && !g_dontPenalizeTeam) + level.teamScores[ent->client->ps.persistant[PERS_TEAM]] += score; CalculateRanks(); } @@ -485,49 +402,42 @@ TossClientItems rww - Toss the weapon away from the player in the specified direction ================= */ -void TossClientWeapon(gentity_t *self, vec3_t direction, float speed) -{ +void TossClientWeapon(gentity_t *self, vec3_t direction, float speed) { vec3_t vel; gitem_t *item; gentity_t *launched; int weapon = self->s.weapon; int ammoSub; - if (level.gametype == GT_SIEGE) - { //no dropping weaps + if (level.gametype == GT_SIEGE) { // no dropping weaps return; } - if (weapon <= WP_BRYAR_PISTOL) - { //can't have this + if (weapon <= WP_BRYAR_PISTOL) { // can't have this return; } - if (weapon == WP_EMPLACED_GUN || - weapon == WP_TURRET) - { + if (weapon == WP_EMPLACED_GUN || weapon == WP_TURRET) { return; } // find the item type for this weapon - item = BG_FindItemForWeapon( weapon ); + item = BG_FindItemForWeapon(weapon); ammoSub = (self->client->ps.ammo[weaponData[weapon].ammoIndex] - bg_itemlist[BG_GetItemIndexByTag(weapon, IT_WEAPON)].quantity); - if (ammoSub < 0) - { + if (ammoSub < 0) { int ammoQuan = item->quantity; ammoQuan -= (-ammoSub); - if (ammoQuan <= 0) - { //no ammo + if (ammoQuan <= 0) { // no ammo return; } } - vel[0] = direction[0]*speed; - vel[1] = direction[1]*speed; - vel[2] = direction[2]*speed; + vel[0] = direction[0] * speed; + vel[1] = direction[1] * speed; + vel[2] = direction[2] * speed; launched = LaunchItem(item, self->client->ps.origin, vel); @@ -538,37 +448,30 @@ void TossClientWeapon(gentity_t *self, vec3_t direction, float speed) self->client->ps.ammo[weaponData[weapon].ammoIndex] -= bg_itemlist[BG_GetItemIndexByTag(weapon, IT_WEAPON)].quantity; - if (self->client->ps.ammo[weaponData[weapon].ammoIndex] < 0) - { + if (self->client->ps.ammo[weaponData[weapon].ammoIndex] < 0) { launched->count -= (-self->client->ps.ammo[weaponData[weapon].ammoIndex]); self->client->ps.ammo[weaponData[weapon].ammoIndex] = 0; } if ((self->client->ps.ammo[weaponData[weapon].ammoIndex] < 1 && weapon != WP_DET_PACK) || - (weapon != WP_THERMAL && weapon != WP_DET_PACK && weapon != WP_TRIP_MINE)) - { + (weapon != WP_THERMAL && weapon != WP_DET_PACK && weapon != WP_TRIP_MINE)) { int i = 0; int weap = -1; self->client->ps.stats[STAT_WEAPONS] &= ~(1 << weapon); - while (i < WP_NUM_WEAPONS) - { - if ((self->client->ps.stats[STAT_WEAPONS] & (1 << i)) && i != WP_NONE) - { //this one's good + while (i < WP_NUM_WEAPONS) { + if ((self->client->ps.stats[STAT_WEAPONS] & (1 << i)) && i != WP_NONE) { // this one's good weap = i; break; } i++; } - if (weap != -1) - { + if (weap != -1) { self->s.weapon = weap; self->client->ps.weapon = weap; - } - else - { + } else { self->s.weapon = 0; self->client->ps.weapon = 0; } @@ -584,15 +487,14 @@ TossClientItems Toss the weapon and powerups for the killed player ================= */ -void TossClientItems( gentity_t *self ) { - gitem_t *item; - int weapon; - float angle; - int i; - gentity_t *drop; +void TossClientItems(gentity_t *self) { + gitem_t *item; + int weapon; + float angle; + int i; + gentity_t *drop; - if (level.gametype == GT_SIEGE) - { //just don't drop anything then + if (level.gametype == GT_SIEGE) { // just don't drop anything then return; } @@ -603,48 +505,45 @@ void TossClientItems( gentity_t *self ) { // weapon that isn't the mg or gauntlet. Without this, a client // can pick up a weapon, be killed, and not drop the weapon because // their weapon change hasn't completed yet and they are still holding the MG. - if ( weapon == WP_BRYAR_PISTOL) { - if ( self->client->ps.weaponstate == WEAPON_DROPPING ) { + if (weapon == WP_BRYAR_PISTOL) { + if (self->client->ps.weaponstate == WEAPON_DROPPING) { weapon = self->client->pers.cmd.weapon; } - if ( !( self->client->ps.stats[STAT_WEAPONS] & ( 1 << weapon ) ) ) { + if (!(self->client->ps.stats[STAT_WEAPONS] & (1 << weapon))) { weapon = WP_NONE; } } self->s.bolt2 = weapon; - if ( weapon > WP_BRYAR_PISTOL && - weapon != WP_EMPLACED_GUN && - weapon != WP_TURRET && - self->client->ps.ammo[ weaponData[weapon].ammoIndex ] ) { + if (weapon > WP_BRYAR_PISTOL && weapon != WP_EMPLACED_GUN && weapon != WP_TURRET && self->client->ps.ammo[weaponData[weapon].ammoIndex]) { gentity_t *te; // find the item type for this weapon - item = BG_FindItemForWeapon( weapon ); + item = BG_FindItemForWeapon(weapon); // tell all clients to remove the weapon model on this guy until he respawns - te = G_TempEntity( vec3_origin, EV_DESTROY_WEAPON_MODEL ); + te = G_TempEntity(vec3_origin, EV_DESTROY_WEAPON_MODEL); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = self->s.number; // spawn the item - Drop_Item( self, item, 0 ); + Drop_Item(self, item, 0); } // drop all the powerups if not in teamplay - if ( level.gametype != GT_TEAM && level.gametype != GT_SIEGE ) { + if (level.gametype != GT_TEAM && level.gametype != GT_SIEGE) { angle = 45; - for ( i = 1 ; i < PW_NUM_POWERUPS ; i++ ) { - if ( self->client->ps.powerups[ i ] > level.time ) { - item = BG_FindItemForPowerup( i ); - if ( !item ) { + for (i = 1; i < PW_NUM_POWERUPS; i++) { + if (self->client->ps.powerups[i] > level.time) { + item = BG_FindItemForPowerup(i); + if (!item) { continue; } - drop = Drop_Item( self, item, angle ); + drop = Drop_Item(self, item, angle); // decide how many seconds it has left - drop->count = ( self->client->ps.powerups[ i ] - level.time ) / 1000; - if ( drop->count < 1 ) { + drop->count = (self->client->ps.powerups[i] - level.time) / 1000; + if (drop->count < 1) { drop->count = 1; } angle += 45; @@ -653,25 +552,24 @@ void TossClientItems( gentity_t *self ) { } } - /* ================== LookAtKiller ================== */ -void LookAtKiller( gentity_t *self, gentity_t *inflictor, gentity_t *attacker ) { - vec3_t dir; +void LookAtKiller(gentity_t *self, gentity_t *inflictor, gentity_t *attacker) { + vec3_t dir; - if ( attacker && attacker != self ) - VectorSubtract (attacker->s.pos.trBase, self->s.pos.trBase, dir); - else if ( inflictor && inflictor != self ) - VectorSubtract (inflictor->s.pos.trBase, self->s.pos.trBase, dir); + if (attacker && attacker != self) + VectorSubtract(attacker->s.pos.trBase, self->s.pos.trBase, dir); + else if (inflictor && inflictor != self) + VectorSubtract(inflictor->s.pos.trBase, self->s.pos.trBase, dir); else { self->client->ps.stats[STAT_DEAD_YAW] = self->s.angles[YAW]; return; } - self->client->ps.stats[STAT_DEAD_YAW] = vectoyaw ( dir ); + self->client->ps.stats[STAT_DEAD_YAW] = vectoyaw(dir); } /* @@ -679,16 +577,15 @@ void LookAtKiller( gentity_t *self, gentity_t *inflictor, gentity_t *attacker ) GibEntity ================== */ -void GibEntity( gentity_t *self, int killer ) { - G_AddEvent( self, EV_GIB_PLAYER, killer ); +void GibEntity(gentity_t *self, int killer) { + G_AddEvent(self, EV_GIB_PLAYER, killer); self->takedamage = qfalse; self->s.eType = ET_INVISIBLE; self->r.contents = 0; } -void BodyRid(gentity_t *ent) -{ - trap->UnlinkEntity( (sharedEntity_t *)ent ); +void BodyRid(gentity_t *ent) { + trap->UnlinkEntity((sharedEntity_t *)ent); ent->physicsObject = qfalse; } @@ -697,66 +594,46 @@ void BodyRid(gentity_t *ent) body_die ================== */ -void body_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) { +void body_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { // NOTENOTE No gibbing right now, this is star wars. qboolean doDisint = qfalse; - if (self->s.eType == ET_NPC) - { //well, just rem it then, so long as it's done with its death anim and it's not a standard weapon. - if ( self->client && self->client->ps.torsoTimer <= 0 && - (meansOfDeath == MOD_UNKNOWN || - meansOfDeath == MOD_WATER || - meansOfDeath == MOD_SLIME || - meansOfDeath == MOD_LAVA || - meansOfDeath == MOD_CRUSH || - meansOfDeath == MOD_TELEFRAG || - meansOfDeath == MOD_FALLING || - meansOfDeath == MOD_SUICIDE || - meansOfDeath == MOD_TARGET_LASER || - meansOfDeath == MOD_TRIGGER_HURT) ) - { + if (self->s.eType == ET_NPC) { // well, just rem it then, so long as it's done with its death anim and it's not a standard weapon. + if (self->client && self->client->ps.torsoTimer <= 0 && + (meansOfDeath == MOD_UNKNOWN || meansOfDeath == MOD_WATER || meansOfDeath == MOD_SLIME || meansOfDeath == MOD_LAVA || meansOfDeath == MOD_CRUSH || + meansOfDeath == MOD_TELEFRAG || meansOfDeath == MOD_FALLING || meansOfDeath == MOD_SUICIDE || meansOfDeath == MOD_TARGET_LASER || + meansOfDeath == MOD_TRIGGER_HURT)) { self->think = G_FreeEntity; self->nextthink = level.time; } return; } - if (self->health < (GIB_HEALTH+1)) - { - self->health = GIB_HEALTH+1; + if (self->health < (GIB_HEALTH + 1)) { + self->health = GIB_HEALTH + 1; - if (self->client && (level.time - self->client->respawnTime) < 2000) - { + if (self->client && (level.time - self->client->respawnTime) < 2000) { doDisint = qfalse; - } - else - { + } else { doDisint = qtrue; } } - if (self->client && (self->client->ps.eFlags & EF_DISINTEGRATION)) - { + if (self->client && (self->client->ps.eFlags & EF_DISINTEGRATION)) { return; - } - else if (self->s.eFlags & EF_DISINTEGRATION) - { + } else if (self->s.eFlags & EF_DISINTEGRATION) { return; } - if (doDisint) - { - if (self->client) - { + if (doDisint) { + if (self->client) { self->client->ps.eFlags |= EF_DISINTEGRATION; VectorCopy(self->client->ps.origin, self->client->ps.lastHitLoc); - } - else - { + } else { self->s.eFlags |= EF_DISINTEGRATION; VectorCopy(self->r.currentOrigin, self->s.origin2); - //since it's the corpse entity, tell it to "remove" itself + // since it's the corpse entity, tell it to "remove" itself self->think = BodyRid; self->nextthink = level.time + 1000; } @@ -764,60 +641,56 @@ void body_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int d } } - // these are just for logging, the client prints its own messages -char *modNames[MOD_MAX] = { - "MOD_UNKNOWN", - "MOD_STUN_BATON", - "MOD_MELEE", - "MOD_SABER", - "MOD_BRYAR_PISTOL", - "MOD_BRYAR_PISTOL_ALT", - "MOD_BLASTER", - "MOD_TURBLAST", - "MOD_DISRUPTOR", - "MOD_DISRUPTOR_SPLASH", - "MOD_DISRUPTOR_SNIPER", - "MOD_BOWCASTER", - "MOD_REPEATER", - "MOD_REPEATER_ALT", - "MOD_REPEATER_ALT_SPLASH", - "MOD_DEMP2", - "MOD_DEMP2_ALT", - "MOD_FLECHETTE", - "MOD_FLECHETTE_ALT_SPLASH", - "MOD_ROCKET", - "MOD_ROCKET_SPLASH", - "MOD_ROCKET_HOMING", - "MOD_ROCKET_HOMING_SPLASH", - "MOD_THERMAL", - "MOD_THERMAL_SPLASH", - "MOD_TRIP_MINE_SPLASH", - "MOD_TIMED_MINE_SPLASH", - "MOD_DET_PACK_SPLASH", - "MOD_VEHICLE", - "MOD_CONC", - "MOD_CONC_ALT", - "MOD_FORCE_DARK", - "MOD_SENTRY", - "MOD_WATER", - "MOD_SLIME", - "MOD_LAVA", - "MOD_CRUSH", - "MOD_TELEFRAG", - "MOD_FALLING", - "MOD_SUICIDE", - "MOD_TARGET_LASER", - "MOD_TRIGGER_HURT" -}; - +char *modNames[MOD_MAX] = {"MOD_UNKNOWN", + "MOD_STUN_BATON", + "MOD_MELEE", + "MOD_SABER", + "MOD_BRYAR_PISTOL", + "MOD_BRYAR_PISTOL_ALT", + "MOD_BLASTER", + "MOD_TURBLAST", + "MOD_DISRUPTOR", + "MOD_DISRUPTOR_SPLASH", + "MOD_DISRUPTOR_SNIPER", + "MOD_BOWCASTER", + "MOD_REPEATER", + "MOD_REPEATER_ALT", + "MOD_REPEATER_ALT_SPLASH", + "MOD_DEMP2", + "MOD_DEMP2_ALT", + "MOD_FLECHETTE", + "MOD_FLECHETTE_ALT_SPLASH", + "MOD_ROCKET", + "MOD_ROCKET_SPLASH", + "MOD_ROCKET_HOMING", + "MOD_ROCKET_HOMING_SPLASH", + "MOD_THERMAL", + "MOD_THERMAL_SPLASH", + "MOD_TRIP_MINE_SPLASH", + "MOD_TIMED_MINE_SPLASH", + "MOD_DET_PACK_SPLASH", + "MOD_VEHICLE", + "MOD_CONC", + "MOD_CONC_ALT", + "MOD_FORCE_DARK", + "MOD_SENTRY", + "MOD_WATER", + "MOD_SLIME", + "MOD_LAVA", + "MOD_CRUSH", + "MOD_TELEFRAG", + "MOD_FALLING", + "MOD_SUICIDE", + "MOD_TARGET_LASER", + "MOD_TRIGGER_HURT"}; /* ================== CheckAlmostCapture ================== */ -void CheckAlmostCapture( gentity_t *self, gentity_t *attacker ) { +void CheckAlmostCapture(gentity_t *self, gentity_t *attacker) { #if 0 gentity_t *ent; vec3_t dir; @@ -864,10 +737,8 @@ void CheckAlmostCapture( gentity_t *self, gentity_t *attacker ) { #endif } -qboolean G_InKnockDown( playerState_t *ps ) -{ - switch ( (ps->legsAnim) ) - { +qboolean G_InKnockDown(playerState_t *ps) { + switch ((ps->legsAnim)) { case BOTH_KNOCKDOWN1: case BOTH_KNOCKDOWN2: case BOTH_KNOCKDOWN3: @@ -893,488 +764,325 @@ qboolean G_InKnockDown( playerState_t *ps ) return qfalse; } -static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{ +static int G_CheckSpecialDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, int hitLoc) { int deathAnim = -1; - if ( BG_InRoll( &self->client->ps, self->client->ps.legsAnim ) ) - { - deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll - } - else if ( BG_FlippingAnim( self->client->ps.legsAnim ) ) - { - deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip - } - else if ( G_InKnockDown( &self->client->ps ) ) - {//since these happen a lot, let's handle them case by case - int animLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.legsAnim].numFrames * fabs((float)(bgHumanoidAnimations[self->client->ps.legsAnim].frameLerp)); - switch ( self->client->ps.legsAnim ) - { + if (BG_InRoll(&self->client->ps, self->client->ps.legsAnim)) { + deathAnim = BOTH_DEATH_ROLL; //# Death anim from a roll + } else if (BG_FlippingAnim(self->client->ps.legsAnim)) { + deathAnim = BOTH_DEATH_FLIP; //# Death anim from a flip + } else if (G_InKnockDown(&self->client->ps)) { // since these happen a lot, let's handle them case by case + int animLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.legsAnim].numFrames * + fabs((float)(bgHumanoidAnimations[self->client->ps.legsAnim].frameLerp)); + switch (self->client->ps.legsAnim) { case BOTH_KNOCKDOWN1: - if ( animLength - self->client->ps.legsTimer > 100 ) - {//on our way down - if ( self->client->ps.legsTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsTimer > 100) { // on our way down + if (self->client->ps.legsTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_KNOCKDOWN2: - if ( animLength - self->client->ps.legsTimer > 700 ) - {//on our way down - if ( self->client->ps.legsTimer > 600 ) - {//still partially up + if (animLength - self->client->ps.legsTimer > 700) { // on our way down + if (self->client->ps.legsTimer > 600) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_KNOCKDOWN3: - if ( animLength - self->client->ps.legsTimer > 100 ) - {//on our way down - if ( self->client->ps.legsTimer > 1300 ) - {//still partially up + if (animLength - self->client->ps.legsTimer > 100) { // on our way down + if (self->client->ps.legsTimer > 1300) { // still partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_KNOCKDOWN4: - if ( animLength - self->client->ps.legsTimer > 300 ) - {//on our way down - if ( self->client->ps.legsTimer > 350 ) - {//still partially up + if (animLength - self->client->ps.legsTimer > 300) { // on our way down + if (self->client->ps.legsTimer > 350) { // still partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } - } - else - {//crouch death + } else { // crouch death vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } } break; case BOTH_KNOCKDOWN5: - if ( self->client->ps.legsTimer < 750 ) - {//flat + if (self->client->ps.legsTimer < 750) { // flat deathAnim = BOTH_DEATH_LYING_DN; } break; case BOTH_GETUP1: - if ( self->client->ps.legsTimer < 350 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 800 ) - {//crouching + if (self->client->ps.legsTimer < 350) { // standing up + } else if (self->client->ps.legsTimer < 800) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 450 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 450) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP2: - if ( self->client->ps.legsTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 850 ) - {//crouching + if (self->client->ps.legsTimer < 150) { // standing up + } else if (self->client->ps.legsTimer < 850) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched - } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 500 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 500) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP3: - if ( self->client->ps.legsTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 600 ) - {//crouching + if (self->client->ps.legsTimer < 250) { // standing up + } else if (self->client->ps.legsTimer < 600) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 150 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP4: - if ( self->client->ps.legsTimer < 250 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 600 ) - {//crouching + if (self->client->ps.legsTimer < 250) { // standing up + } else if (self->client->ps.legsTimer < 600) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 850 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 850) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP5: - if ( self->client->ps.legsTimer > 850 ) - {//lying down - if ( animLength - self->client->ps.legsTimer > 1500 ) - {//partially up + if (self->client->ps.legsTimer > 850) { // lying down + if (animLength - self->client->ps.legsTimer > 1500) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_GETUP_CROUCH_B1: - if ( self->client->ps.legsTimer < 800 ) - {//crouching + if (self->client->ps.legsTimer < 800) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 400 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 400) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_GETUP_CROUCH_F1: - if ( self->client->ps.legsTimer < 800 ) - {//crouching + if (self->client->ps.legsTimer < 800) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 150 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_B1: - if ( self->client->ps.legsTimer < 325 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 725 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsTimer < 900 ) - {//crouching + if (self->client->ps.legsTimer < 325) { // standing up + } else if (self->client->ps.legsTimer < 725) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsTimer < 900) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 50 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B2: - if ( self->client->ps.legsTimer < 575 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 875 ) - {//spinning up - deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards - } - else if ( self->client->ps.legsTimer < 900 ) - {//crouching + if (self->client->ps.legsTimer < 575) { // standing up + } else if (self->client->ps.legsTimer < 875) { // spinning up + deathAnim = BOTH_DEATH_SPIN_180; //# Death anim when facing backwards + } else if (self->client->ps.legsTimer < 900) { // crouching vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else - {//lying down - //partially up + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B3: - if ( self->client->ps.legsTimer < 150 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 775 ) - {//flipping - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - //partially up + if (self->client->ps.legsTimer < 150) { // standing up + } else if (self->client->ps.legsTimer < 775) { // flipping + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + // partially up deathAnim = BOTH_DEATH_FALLING_UP; } break; case BOTH_FORCE_GETUP_B4: - if ( self->client->ps.legsTimer < 325 ) - {//standing up - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 150 ) - {//partially up + if (self->client->ps.legsTimer < 325) { // standing up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 150) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B5: - if ( self->client->ps.legsTimer < 550 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 1025 ) - {//kicking up - deathAnim = BOTH_DEATHBACKWARD2; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 50 ) - {//partially up + if (self->client->ps.legsTimer < 550) { // standing up + } else if (self->client->ps.legsTimer < 1025) { // kicking up + deathAnim = BOTH_DEATHBACKWARD2; // backflip + } else { // lying down + if (animLength - self->client->ps.legsTimer > 50) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_B6: - if ( self->client->ps.legsTimer < 225 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 425 ) - {//crouching up + if (self->client->ps.legsTimer < 225) { // standing up + } else if (self->client->ps.legsTimer < 425) { // crouching up vec3_t fwd; float thrown = 0; - AngleVectors( self->client->ps.viewangles, fwd, NULL, NULL ); - thrown = DotProduct( fwd, self->client->ps.velocity ); + AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); + thrown = DotProduct(fwd, self->client->ps.velocity); - if ( thrown < -150 ) - { - deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back - } - else - { - deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched + if (thrown < -150) { + deathAnim = BOTH_DEATHBACKWARD1; //# Death anim when crouched and thrown back + } else { + deathAnim = BOTH_DEATH_CROUCHED; //# Death anim when crouched } - } - else if ( self->client->ps.legsTimer < 825 ) - {//flipping up - deathAnim = BOTH_DEATHFORWARD3; //backflip - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 225 ) - {//partially up + } else if (self->client->ps.legsTimer < 825) { // flipping up + deathAnim = BOTH_DEATHFORWARD3; // backflip + } else { // lying down + if (animLength - self->client->ps.legsTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_UP; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_UP; } } break; case BOTH_FORCE_GETUP_F1: - if ( self->client->ps.legsTimer < 275 ) - {//standing up - } - else if ( self->client->ps.legsTimer < 750 ) - {//flipping + if (self->client->ps.legsTimer < 275) { // standing up + } else if (self->client->ps.legsTimer < 750) { // flipping deathAnim = BOTH_DEATH14; - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 100 ) - {//partially up + } else { // lying down + if (animLength - self->client->ps.legsTimer > 100) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } break; case BOTH_FORCE_GETUP_F2: - if ( self->client->ps.legsTimer < 1200 ) - {//standing - } - else - {//lying down - if ( animLength - self->client->ps.legsTimer > 225 ) - {//partially up + if (self->client->ps.legsTimer < 1200) { // standing + } else { // lying down + if (animLength - self->client->ps.legsTimer > 225) { // partially up deathAnim = BOTH_DEATH_FALLING_DN; - } - else - {//down + } else { // down deathAnim = BOTH_DEATH_LYING_DN; } } @@ -1385,80 +1093,65 @@ static int G_CheckSpecialDeathAnim( gentity_t *self, vec3_t point, int damage, i return deathAnim; } -int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hitLoc ) -{//FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called +int G_PickDeathAnim(gentity_t *self, vec3_t point, int damage, int mod, + int hitLoc) { // FIXME: play dead flop anims on body if in an appropriate _DEAD anim when this func is called int deathAnim = -1; int max_health; int legAnim = 0; vec3_t objVelocity; - if (!self || !self->client) - { - if (!self || self->s.eType != ET_NPC) - { //g2animent + if (!self || !self->client) { + if (!self || self->s.eType != ET_NPC) { // g2animent return 0; } } - if (self->client) - { + if (self->client) { max_health = self->client->ps.stats[STAT_MAX_HEALTH]; - if (self->client->inSpaceIndex && self->client->inSpaceIndex != ENTITYNUM_NONE) - { + if (self->client->inSpaceIndex && self->client->inSpaceIndex != ENTITYNUM_NONE) { return BOTH_CHOKE3; } - } - else - { + } else { max_health = 60; } - if (self->client) - { + if (self->client) { VectorCopy(self->client->ps.velocity, objVelocity); - } - else - { + } else { VectorCopy(self->s.pos.trDelta, objVelocity); } - if ( hitLoc == HL_NONE ) - { - hitLoc = G_GetHitLocation( self, point );//self->hitLoc + if (hitLoc == HL_NONE) { + hitLoc = G_GetHitLocation(self, point); // self->hitLoc } - if (self->client) - { + if (self->client) { legAnim = self->client->ps.legsAnim; - } - else - { + } else { legAnim = self->s.legsAnim; } - if (gGAvoidDismember) - { + if (gGAvoidDismember) { return BOTH_RIGHTHANDCHOPPEDOFF; } - //dead flops - switch( legAnim ) - { - case BOTH_DEATH1: //# First Death anim + // dead flops + switch (legAnim) { + case BOTH_DEATH1: //# First Death anim case BOTH_DEAD1: - case BOTH_DEATH2: //# Second Death anim + case BOTH_DEATH2: //# Second Death anim case BOTH_DEAD2: - case BOTH_DEATH8: //# + case BOTH_DEATH8: //# case BOTH_DEAD8: - case BOTH_DEATH13: //# + case BOTH_DEATH13: //# case BOTH_DEAD13: - case BOTH_DEATH14: //# + case BOTH_DEATH14: //# case BOTH_DEAD14: - case BOTH_DEATH16: //# + case BOTH_DEATH16: //# case BOTH_DEAD16: - case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose - case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose + case BOTH_DEADBACKWARD1: //# First thrown backward death finished pose + case BOTH_DEADBACKWARD2: //# Second thrown backward death finished pose deathAnim = -2; break; /* @@ -1475,12 +1168,12 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit deathAnim = BOTH_DEADFLOP2; break; */ - case BOTH_DEATH10: //# + case BOTH_DEATH10: //# case BOTH_DEAD10: - case BOTH_DEATH15: //# + case BOTH_DEATH15: //# case BOTH_DEAD15: - case BOTH_DEADFORWARD1: //# First thrown forward death finished pose - case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose + case BOTH_DEADFORWARD1: //# First thrown forward death finished pose + case BOTH_DEADFORWARD2: //# Second thrown forward death finished pose deathAnim = -2; break; /* @@ -1496,123 +1189,94 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit */ case BOTH_DEADFLOP1: deathAnim = -2; - //deathAnim = BOTH_DEADFLOP1; + // deathAnim = BOTH_DEADFLOP1; break; - case BOTH_DEAD3: //# Third Death finished pose - case BOTH_DEAD4: //# Fourth Death finished pose - case BOTH_DEAD5: //# Fifth Death finished pose - case BOTH_DEAD6: //# Sixth Death finished pose - case BOTH_DEAD7: //# Seventh Death finished pose - case BOTH_DEAD9: //# - case BOTH_DEAD11: //# - case BOTH_DEAD12: //# - case BOTH_DEAD17: //# - case BOTH_DEAD18: //# - case BOTH_DEAD19: //# - case BOTH_LYINGDEAD1: //# Killed lying down death finished pose - case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose - case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose - case BOTH_DEATH3: //# Third Death anim - case BOTH_DEATH4: //# Fourth Death anim - case BOTH_DEATH5: //# Fifth Death anim - case BOTH_DEATH6: //# Sixth Death anim - case BOTH_DEATH7: //# Seventh Death anim - case BOTH_DEATH9: //# - case BOTH_DEATH11: //# - case BOTH_DEATH12: //# - case BOTH_DEATH17: //# - case BOTH_DEATH18: //# - case BOTH_DEATH19: //# - case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward - case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward - case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward - case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward - case BOTH_DEATH1IDLE: //# Idle while close to death - case BOTH_LYINGDEATH1: //# Death to play when killed lying down - case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death - case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start - case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop - case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom + case BOTH_DEAD3: //# Third Death finished pose + case BOTH_DEAD4: //# Fourth Death finished pose + case BOTH_DEAD5: //# Fifth Death finished pose + case BOTH_DEAD6: //# Sixth Death finished pose + case BOTH_DEAD7: //# Seventh Death finished pose + case BOTH_DEAD9: //# + case BOTH_DEAD11: //# + case BOTH_DEAD12: //# + case BOTH_DEAD17: //# + case BOTH_DEAD18: //# + case BOTH_DEAD19: //# + case BOTH_LYINGDEAD1: //# Killed lying down death finished pose + case BOTH_STUMBLEDEAD1: //# Stumble forward death finished pose + case BOTH_FALLDEAD1LAND: //# Fall forward and splat death finished pose + case BOTH_DEATH3: //# Third Death anim + case BOTH_DEATH4: //# Fourth Death anim + case BOTH_DEATH5: //# Fifth Death anim + case BOTH_DEATH6: //# Sixth Death anim + case BOTH_DEATH7: //# Seventh Death anim + case BOTH_DEATH9: //# + case BOTH_DEATH11: //# + case BOTH_DEATH12: //# + case BOTH_DEATH17: //# + case BOTH_DEATH18: //# + case BOTH_DEATH19: //# + case BOTH_DEATHFORWARD1: //# First Death in which they get thrown forward + case BOTH_DEATHFORWARD2: //# Second Death in which they get thrown forward + case BOTH_DEATHBACKWARD1: //# First Death in which they get thrown backward + case BOTH_DEATHBACKWARD2: //# Second Death in which they get thrown backward + case BOTH_DEATH1IDLE: //# Idle while close to death + case BOTH_LYINGDEATH1: //# Death to play when killed lying down + case BOTH_STUMBLEDEATH1: //# Stumble forward and fall face first death + case BOTH_FALLDEATH1: //# Fall forward off a high cliff and splat death - start + case BOTH_FALLDEATH1INAIR: //# Fall forward off a high cliff and splat death - loop + case BOTH_FALLDEATH1LAND: //# Fall forward off a high cliff and splat death - hit bottom deathAnim = -2; break; } - if ( deathAnim == -1 ) - { - if (self->client) - { - deathAnim = G_CheckSpecialDeathAnim( self, point, damage, mod, hitLoc ); + if (deathAnim == -1) { + if (self->client) { + deathAnim = G_CheckSpecialDeathAnim(self, point, damage, mod, hitLoc); } - if (deathAnim == -1) - { - //death anims - switch( hitLoc ) - { + if (deathAnim == -1) { + // death anims + switch (hitLoc) { case HL_FOOT_RT: case HL_FOOT_LT: - if ( mod == MOD_SABER && !Q_irand( 0, 2 ) ) - { - return BOTH_DEATH10;//chest: back flip - } - else if ( !Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH15;//back: forward + if (mod == MOD_SABER && !Q_irand(0, 2)) { + return BOTH_DEATH10; // chest: back flip + } else if (!Q_irand(0, 2)) { + deathAnim = BOTH_DEATH4; // back: forward + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH15; // back: forward } break; case HL_LEG_RT: - if ( !Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH15;//back: forward + if (!Q_irand(0, 2)) { + deathAnim = BOTH_DEATH4; // back: forward + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH15; // back: forward } break; case HL_LEG_LT: - if ( !Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH15;//back: forward + if (!Q_irand(0, 2)) { + deathAnim = BOTH_DEATH4; // back: forward + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH15; // back: forward } break; case HL_BACK: - if ( !VectorLengthSquared( objVelocity ) ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - if ( !Q_irand( 0, 2 ) ) - { - deathAnim = BOTH_DEATH4;//back: forward - } - else if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH5;//same as 4 - } - else - { - deathAnim = BOTH_DEATH15;//back: forward + if (!VectorLengthSquared(objVelocity)) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + if (!Q_irand(0, 2)) { + deathAnim = BOTH_DEATH4; // back: forward + } else if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH5; // same as 4 + } else { + deathAnim = BOTH_DEATH15; // back: forward } } break; @@ -1620,38 +1284,27 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit case HL_ARM_RT: case HL_HAND_RT: case HL_BACK_RT: - if ( damage <= max_health*0.25 ) - { - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward - } - else if ( damage <= max_health*0.5 ) - { - deathAnim = BOTH_DEATH3;//chest right: back - } - else if ( damage <= max_health*0.75 ) - { - deathAnim = BOTH_DEATH6;//chest right: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH8;//chest right: spin high - } - else - { - switch ( Q_irand( 0, 2 ) ) - { + if (damage <= max_health * 0.25) { + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward + } else if (damage <= max_health * 0.5) { + deathAnim = BOTH_DEATH3; // chest right: back + } else if (damage <= max_health * 0.75) { + deathAnim = BOTH_DEATH6; // chest right: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH8; // chest right: spin high + } else { + switch (Q_irand(0, 2)) { default: case 0: - deathAnim = BOTH_DEATH9;//chest right: snap, fall forward + deathAnim = BOTH_DEATH9; // chest right: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH3;//chest right: back + deathAnim = BOTH_DEATH3; // chest right: back break; case 2: - deathAnim = BOTH_DEATH6;//chest right: spin + deathAnim = BOTH_DEATH6; // chest right: spin break; } } @@ -1661,38 +1314,27 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit case HL_ARM_LT: case HL_HAND_LT: case HL_BACK_LT: - if ( damage <= max_health*0.25 ) - { - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward - } - else if ( damage <= max_health*0.5 ) - { - deathAnim = BOTH_DEATH7;//chest left: back - } - else if ( damage <= max_health*0.75 ) - { - deathAnim = BOTH_DEATH12;//chest left: spin - } - else - { - //TEMP HACK: play spinny deaths less often - if ( Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH14;//chest left: spin high - } - else - { - switch ( Q_irand( 0, 2 ) ) - { + if (damage <= max_health * 0.25) { + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward + } else if (damage <= max_health * 0.5) { + deathAnim = BOTH_DEATH7; // chest left: back + } else if (damage <= max_health * 0.75) { + deathAnim = BOTH_DEATH12; // chest left: spin + } else { + // TEMP HACK: play spinny deaths less often + if (Q_irand(0, 1)) { + deathAnim = BOTH_DEATH14; // chest left: spin high + } else { + switch (Q_irand(0, 2)) { default: case 0: - deathAnim = BOTH_DEATH11;//chest left: snap, fall forward + deathAnim = BOTH_DEATH11; // chest left: snap, fall forward break; case 1: - deathAnim = BOTH_DEATH7;//chest left: back + deathAnim = BOTH_DEATH7; // chest left: back break; case 2: - deathAnim = BOTH_DEATH12;//chest left: spin + deathAnim = BOTH_DEATH12; // chest left: spin break; } } @@ -1700,45 +1342,29 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit break; case HL_CHEST: case HL_WAIST: - if ( damage <= max_health*0.25 || !VectorLengthSquared( objVelocity ) ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH18;//gut: fall right - } - else - { - deathAnim = BOTH_DEATH19;//gut: fall left - } - } - else if ( damage <= max_health*0.5 ) - { - deathAnim = BOTH_DEATH2;//chest: backward short - } - else if ( damage <= max_health*0.75 ) - { - if ( !Q_irand( 0, 1 ) ) - { - deathAnim = BOTH_DEATH1;//chest: backward med + if (damage <= max_health * 0.25 || !VectorLengthSquared(objVelocity)) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH18; // gut: fall right + } else { + deathAnim = BOTH_DEATH19; // gut: fall left } - else - { - deathAnim = BOTH_DEATH16;//same as 1 + } else if (damage <= max_health * 0.5) { + deathAnim = BOTH_DEATH2; // chest: backward short + } else if (damage <= max_health * 0.75) { + if (!Q_irand(0, 1)) { + deathAnim = BOTH_DEATH1; // chest: backward med + } else { + deathAnim = BOTH_DEATH16; // same as 1 } - } - else - { - deathAnim = BOTH_DEATH10;//chest: back flip + } else { + deathAnim = BOTH_DEATH10; // chest: back flip } break; case HL_HEAD: - if ( damage <= max_health*0.5 ) - { - deathAnim = BOTH_DEATH17;//head/back: croak - } - else - { - deathAnim = BOTH_DEATH13;//head: stumble, fall back + if (damage <= max_health * 0.5) { + deathAnim = BOTH_DEATH17; // head/back: croak + } else { + deathAnim = BOTH_DEATH13; // head: stumble, fall back } break; default: @@ -1748,26 +1374,22 @@ int G_PickDeathAnim( gentity_t *self, vec3_t point, int damage, int mod, int hit } // Validate..... - if ( deathAnim == -1 || !BG_HasAnimation( self->localAnimIndex, deathAnim )) - { + if (deathAnim == -1 || !BG_HasAnimation(self->localAnimIndex, deathAnim)) { // I guess we'll take what we can get..... - deathAnim = BG_PickAnim( self->localAnimIndex, BOTH_DEATH1, BOTH_DEATH25 ); + deathAnim = BG_PickAnim(self->localAnimIndex, BOTH_DEATH1, BOTH_DEATH25); } return deathAnim; } -gentity_t *G_GetJediMaster(void) -{ +gentity_t *G_GetJediMaster(void) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->client && ent->client->ps.isJediMaster) - { + if (ent && ent->inuse && ent->client && ent->client->ps.isJediMaster) { return ent; } @@ -1783,92 +1405,85 @@ G_AlertTeam ------------------------- */ -void G_AlertTeam( gentity_t *victim, gentity_t *attacker, float radius, float soundDist ) -{ - int radiusEnts[ 128 ]; - gentity_t *check; - vec3_t mins, maxs; - int numEnts; - int i; - float distSq, sndDistSq = (soundDist*soundDist); - - if ( attacker == NULL || attacker->client == NULL ) +void G_AlertTeam(gentity_t *victim, gentity_t *attacker, float radius, float soundDist) { + int radiusEnts[128]; + gentity_t *check; + vec3_t mins, maxs; + int numEnts; + int i; + float distSq, sndDistSq = (soundDist * soundDist); + + if (attacker == NULL || attacker->client == NULL) return; - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = victim->r.currentOrigin[i] - radius; maxs[i] = victim->r.currentOrigin[i] + radius; } - //Get the number of entities in a given space - numEnts = trap->EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = trap->EntitiesInBox(mins, maxs, radiusEnts, 128); - //Cull this list - for ( i = 0; i < numEnts; i++ ) - { + // Cull this list + for (i = 0; i < numEnts; i++) { check = &g_entities[radiusEnts[i]]; - //Validate clients - if ( check->client == NULL ) + // Validate clients + if (check->client == NULL) continue; - //only want NPCs - if ( check->NPC == NULL ) + // only want NPCs + if (check->NPC == NULL) continue; - //Don't bother if they're ignoring enemies -// if ( check->svFlags & SVF_IGNORE_ENEMIES ) -// continue; + // Don't bother if they're ignoring enemies + // if ( check->svFlags & SVF_IGNORE_ENEMIES ) + // continue; - //This NPC specifically flagged to ignore alerts - if ( check->NPC->scriptFlags & SCF_IGNORE_ALERTS ) + // This NPC specifically flagged to ignore alerts + if (check->NPC->scriptFlags & SCF_IGNORE_ALERTS) continue; - //This NPC specifically flagged to ignore alerts - if ( !(check->NPC->scriptFlags&SCF_LOOK_FOR_ENEMIES) ) + // This NPC specifically flagged to ignore alerts + if (!(check->NPC->scriptFlags & SCF_LOOK_FOR_ENEMIES)) continue; - //this ent does not participate in group AI - if ( (check->NPC->scriptFlags&SCF_NO_GROUPS) ) + // this ent does not participate in group AI + if ((check->NPC->scriptFlags & SCF_NO_GROUPS)) continue; - //Skip the requested avoid check if present - if ( check == victim ) + // Skip the requested avoid check if present + if (check == victim) continue; - //Skip the attacker - if ( check == attacker ) + // Skip the attacker + if (check == attacker) continue; - //Must be on the same team - if ( check->client->playerTeam != victim->client->playerTeam ) + // Must be on the same team + if (check->client->playerTeam != victim->client->playerTeam) continue; - //Must be alive - if ( check->health <= 0 ) + // Must be alive + if (check->health <= 0) continue; - if ( check->enemy == NULL ) - {//only do this if they're not already mad at someone - distSq = DistanceSquared( check->r.currentOrigin, victim->r.currentOrigin ); - if ( distSq > 16384 /*128 squared*/ && !trap->InPVS( victim->r.currentOrigin, check->r.currentOrigin ) ) - {//not even potentially visible/hearable + if (check->enemy == NULL) { // only do this if they're not already mad at someone + distSq = DistanceSquared(check->r.currentOrigin, victim->r.currentOrigin); + if (distSq > 16384 /*128 squared*/ && !trap->InPVS(victim->r.currentOrigin, check->r.currentOrigin)) { // not even potentially visible/hearable continue; } - //NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... - if ( soundDist <= 0 || distSq > sndDistSq ) - {//out of sound range - if ( !InFOV( victim, check, check->NPC->stats.hfov, check->NPC->stats.vfov ) - || !NPC_ClearLOS2( check, victim->r.currentOrigin ) ) - {//out of FOV or no LOS + // NOTE: this allows sound alerts to still go through doors/PVS if the teammate is within 128 of the victim... + if (soundDist <= 0 || distSq > sndDistSq) { // out of sound range + if (!InFOV(victim, check, check->NPC->stats.hfov, check->NPC->stats.vfov) || + !NPC_ClearLOS2(check, victim->r.currentOrigin)) { // out of FOV or no LOS continue; } } - //FIXME: This can have a nasty cascading effect if setup wrong... - G_SetEnemy( check, attacker ); + // FIXME: This can have a nasty cascading effect if setup wrong... + G_SetEnemy(check, attacker); } } } @@ -1879,12 +1494,11 @@ G_DeathAlert ------------------------- */ -#define DEATH_ALERT_RADIUS 512 -#define DEATH_ALERT_SOUND_RADIUS 512 +#define DEATH_ALERT_RADIUS 512 +#define DEATH_ALERT_SOUND_RADIUS 512 -void G_DeathAlert( gentity_t *victim, gentity_t *attacker ) -{//FIXME: with all the other alert stuff, do we really need this? - G_AlertTeam( victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS ); +void G_DeathAlert(gentity_t *victim, gentity_t *attacker) { // FIXME: with all the other alert stuff, do we really need this? + G_AlertTeam(victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS); } /* @@ -1896,153 +1510,138 @@ Not to be confused with NPC_RemoveBodyEffects (NPC.cpp), which only applies effe ---------------------------------------- */ -void DeathFX( gentity_t *ent ) -{ - vec3_t effectPos, right; - vec3_t defaultDir; +void DeathFX(gentity_t *ent) { + vec3_t effectPos, right; + vec3_t defaultDir; - if ( !ent || !ent->client ) + if (!ent || !ent->client) return; VectorSet(defaultDir, 0, 0, 1); // team no longer indicates species/race. NPC_class should be used to identify certain npc types - switch(ent->client->NPC_class) - { + switch (ent->client->NPC_class) { case CLASS_MOUSE: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 20; - G_PlayEffectID( G_EffectIndex("env/small_explode"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/mouse/misc/death1") ); + G_PlayEffectID(G_EffectIndex("env/small_explode"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/mouse/misc/death1")); break; case CLASS_PROBE: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] += 50; - G_PlayEffectID( G_EffectIndex("explosions/probeexplosion1"), effectPos, defaultDir ); + G_PlayEffectID(G_EffectIndex("explosions/probeexplosion1"), effectPos, defaultDir); break; case CLASS_ATST: - AngleVectors( ent->r.currentAngles, NULL, right, NULL ); - VectorMA( ent->r.currentOrigin, 20, right, effectPos ); + AngleVectors(ent->r.currentAngles, NULL, right, NULL); + VectorMA(ent->r.currentOrigin, 20, right, effectPos); effectPos[2] += 180; - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - VectorMA( effectPos, -40, right, effectPos ); - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + VectorMA(effectPos, -40, right, effectPos); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); break; case CLASS_SEEKER: case CLASS_REMOTE: - G_PlayEffectID( G_EffectIndex("env/small_explode"), ent->r.currentOrigin, defaultDir ); + G_PlayEffectID(G_EffectIndex("env/small_explode"), ent->r.currentOrigin, defaultDir); break; case CLASS_GONK: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 5; -// statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex(va("sound/chars/gonk/misc/death%d.wav",Q_irand( 1, 3 ))) ); - G_PlayEffectID( G_EffectIndex("env/med_explode"), effectPos, defaultDir ); + // statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); + G_Sound(ent, CHAN_AUTO, G_SoundIndex(va("sound/chars/gonk/misc/death%d.wav", Q_irand(1, 3)))); + G_PlayEffectID(G_EffectIndex("env/med_explode"), effectPos, defaultDir); break; // should list all remaining droids here, hope I didn't miss any case CLASS_R2D2: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffectID( G_EffectIndex("env/med_explode"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo") ); + G_PlayEffectID(G_EffectIndex("env/med_explode"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo")); break; - case CLASS_PROTOCOL: //c3p0 + case CLASS_PROTOCOL: // c3p0 case CLASS_R5D2: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 10; - G_PlayEffectID( G_EffectIndex("env/med_explode"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo") ); + G_PlayEffectID(G_EffectIndex("env/med_explode"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo")); break; case CLASS_MARK2: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo") ); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark2/misc/mark2_explo")); break; case CLASS_INTERROGATOR: - VectorCopy( ent->r.currentOrigin, effectPos ); + VectorCopy(ent->r.currentOrigin, effectPos); effectPos[2] -= 15; - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/interrogator/misc/int_droid_explo") ); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/interrogator/misc/int_droid_explo")); break; case CLASS_MARK1: - AngleVectors( ent->r.currentAngles, NULL, right, NULL ); - VectorMA( ent->r.currentOrigin, 10, right, effectPos ); + AngleVectors(ent->r.currentAngles, NULL, right, NULL); + VectorMA(ent->r.currentOrigin, 10, right, effectPos); effectPos[2] -= 15; - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - VectorMA( effectPos, -20, right, effectPos ); - G_PlayEffectID( G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir ); - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_explo") ); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + VectorMA(effectPos, -20, right, effectPos); + G_PlayEffectID(G_EffectIndex("explosions/droidexplosion1"), effectPos, defaultDir); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_explo")); break; case CLASS_SENTRY: - G_Sound( ent, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_explo") ); - VectorCopy( ent->r.currentOrigin, effectPos ); - G_PlayEffectID( G_EffectIndex("env/med_explode"), effectPos, defaultDir ); + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/chars/sentry/misc/sentry_explo")); + VectorCopy(ent->r.currentOrigin, effectPos); + G_PlayEffectID(G_EffectIndex("env/med_explode"), effectPos, defaultDir); break; default: break; - } - } -void G_CheckVictoryScript(gentity_t *self) -{ - if ( !G_ActivateBehavior( self, BSET_VICTORY ) ) - { - if ( self->NPC && self->s.weapon == WP_SABER ) - {//Jedi taunt from within their AI - self->NPC->blockedSpeechDebounceTime = 0;//get them ready to taunt +void G_CheckVictoryScript(gentity_t *self) { + if (!G_ActivateBehavior(self, BSET_VICTORY)) { + if (self->NPC && self->s.weapon == WP_SABER) { // Jedi taunt from within their AI + self->NPC->blockedSpeechDebounceTime = 0; // get them ready to taunt return; } - if ( self->client && self->client->NPC_class == CLASS_GALAKMECH ) - { + if (self->client && self->client->NPC_class == CLASS_GALAKMECH) { self->wait = 1; - TIMER_Set( self, "gloatTime", Q_irand( 5000, 8000 ) ); - self->NPC->blockedSpeechDebounceTime = 0;//get him ready to taunt + TIMER_Set(self, "gloatTime", Q_irand(5000, 8000)); + self->NPC->blockedSpeechDebounceTime = 0; // get him ready to taunt return; } - //FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? - if ( self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand( 0, 2 ) ) - {//sometimes have the group commander speak instead - self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); - } - else if ( self->NPC ) - { - self->NPC->greetingDebounceTime = level.time + Q_irand( 2000, 5000 ); - //G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + // FIXME: any way to not say this *right away*? Wait for victim's death anim/scream to finish? + if (self->NPC && self->NPC->group && self->NPC->group->commander && self->NPC->group->commander->NPC && + self->NPC->group->commander->NPC->rank > self->NPC->rank && !Q_irand(0, 2)) { // sometimes have the group commander speak instead + self->NPC->group->commander->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self->NPC->group->commander, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); + } else if (self->NPC) { + self->NPC->greetingDebounceTime = level.time + Q_irand(2000, 5000); + // G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); } } } -void G_AddPowerDuelScore(int team, int score) -{ +void G_AddPowerDuelScore(int team, int score) { int i = 0; gentity_t *check; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { check = &g_entities[i]; - if (check->inuse && check->client && - check->client->pers.connected == CON_CONNECTED && !check->client->iAmALoser && - check->client->ps.stats[STAT_HEALTH] > 0 && - check->client->sess.sessionTeam != TEAM_SPECTATOR && - check->client->sess.duelTeam == team) - { //found a living client on the specified team + if (check->inuse && check->client && check->client->pers.connected == CON_CONNECTED && !check->client->iAmALoser && + check->client->ps.stats[STAT_HEALTH] > 0 && check->client->sess.sessionTeam != TEAM_SPECTATOR && + check->client->sess.duelTeam == team) { // found a living client on the specified team check->client->sess.wins += score; ClientUserinfoChanged(check->s.number); } @@ -2050,19 +1649,15 @@ void G_AddPowerDuelScore(int team, int score) } } -void G_AddPowerDuelLoserScore(int team, int score) -{ +void G_AddPowerDuelLoserScore(int team, int score) { int i = 0; gentity_t *check; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { check = &g_entities[i]; - if (check->inuse && check->client && - check->client->pers.connected == CON_CONNECTED && + if (check->inuse && check->client && check->client->pers.connected == CON_CONNECTED && (check->client->iAmALoser || (check->client->ps.stats[STAT_HEALTH] <= 0 && check->client->sess.sessionTeam != TEAM_SPECTATOR)) && - check->client->sess.duelTeam == team) - { //found a living client on the specified team + check->client->sess.duelTeam == team) { // found a living client on the specified team check->client->sess.losses += score; ClientUserinfoChanged(check->s.number); } @@ -2075,147 +1670,112 @@ void G_AddPowerDuelLoserScore(int team, int score) player_die ================== */ -extern stringID_table_t animTable[MAX_ANIMATIONS+1]; +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; -extern void AI_DeleteSelfFromGroup( gentity_t *self ); -extern void AI_GroupMemberKilled( gentity_t *self ); -extern void Boba_FlyStop( gentity_t *self ); -extern qboolean Jedi_WaitingAmbush( gentity_t *self ); -void CheckExitRules( void ); -extern void Rancor_DropVictim( gentity_t *self ); +extern void AI_DeleteSelfFromGroup(gentity_t *self); +extern void AI_GroupMemberKilled(gentity_t *self); +extern void Boba_FlyStop(gentity_t *self); +extern qboolean Jedi_WaitingAmbush(gentity_t *self); +void CheckExitRules(void); +extern void Rancor_DropVictim(gentity_t *self); extern qboolean g_dontFrickinCheck; extern qboolean g_endPDuel; extern qboolean g_noPDuelCheck; extern void saberReactivate(gentity_t *saberent, gentity_t *saberOwner); extern void saberBackToOwner(gentity_t *saberent); -void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) { - gentity_t *ent; - int anim; - int killer; - int i; - char *killerName, *obit; - qboolean wasJediMaster = qfalse; - int sPMType = 0; - char buf[512] = {0}; - - if ( self->client->ps.pm_type == PM_DEAD ) { +void player_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { + gentity_t *ent; + int anim; + int killer; + int i; + char *killerName, *obit; + qboolean wasJediMaster = qfalse; + int sPMType = 0; + char buf[512] = {0}; + + if (self->client->ps.pm_type == PM_DEAD) { return; } - if ( level.intermissiontime ) { + if (level.intermissiontime) { return; } - if ( !attacker ) + if (!attacker) return; - //check player stuff + // check player stuff g_dontFrickinCheck = qfalse; - if (level.gametype == GT_POWERDUEL) - { //don't want to wait til later in the frame if this is the case + if (level.gametype == GT_POWERDUEL) { // don't want to wait til later in the frame if this is the case CheckExitRules(); - if ( level.intermissiontime ) - { + if (level.intermissiontime) { return; } } - if (self->s.eType == ET_NPC && - self->s.NPC_class == CLASS_VEHICLE && - self->m_pVehicle && - !self->m_pVehicle->m_pVehicleInfo->explosionDelay && - (self->m_pVehicle->m_pPilot || self->m_pVehicle->m_iNumPassengers > 0 || self->m_pVehicle->m_pDroidUnit)) - { //kill everyone on board in the name of the attacker... if the vehicle has no death delay + if (self->s.eType == ET_NPC && self->s.NPC_class == CLASS_VEHICLE && self->m_pVehicle && !self->m_pVehicle->m_pVehicleInfo->explosionDelay && + (self->m_pVehicle->m_pPilot || self->m_pVehicle->m_iNumPassengers > 0 || + self->m_pVehicle->m_pDroidUnit)) { // kill everyone on board in the name of the attacker... if the vehicle has no death delay gentity_t *murderer = NULL; gentity_t *killEnt; - if (self->client->ps.otherKillerTime >= level.time) - { //use the last attacker + if (self->client->ps.otherKillerTime >= level.time) { // use the last attacker murderer = &g_entities[self->client->ps.otherKiller]; - if (!murderer->inuse || !murderer->client) - { + if (!murderer->inuse || !murderer->client) { murderer = NULL; - } - else - { - if (murderer->s.number >= MAX_CLIENTS && - murderer->s.eType == ET_NPC && - murderer->s.NPC_class == CLASS_VEHICLE && - murderer->m_pVehicle && - murderer->m_pVehicle->m_pPilot) - { + } else { + if (murderer->s.number >= MAX_CLIENTS && murderer->s.eType == ET_NPC && murderer->s.NPC_class == CLASS_VEHICLE && murderer->m_pVehicle && + murderer->m_pVehicle->m_pPilot) { gentity_t *murderPilot = &g_entities[murderer->m_pVehicle->m_pPilot->s.number]; - if (murderPilot->inuse && murderPilot->client) - { //give the pilot of the offending vehicle credit for the kill + if (murderPilot->inuse && murderPilot->client) { // give the pilot of the offending vehicle credit for the kill murderer = murderPilot; } } } - } - else if (attacker && attacker->inuse && attacker->client) - { - if (attacker->s.number >= MAX_CLIENTS && - attacker->s.eType == ET_NPC && - attacker->s.NPC_class == CLASS_VEHICLE && - attacker->m_pVehicle && - attacker->m_pVehicle->m_pPilot) - { //set vehicles pilot's killer as murderer + } else if (attacker && attacker->inuse && attacker->client) { + if (attacker->s.number >= MAX_CLIENTS && attacker->s.eType == ET_NPC && attacker->s.NPC_class == CLASS_VEHICLE && attacker->m_pVehicle && + attacker->m_pVehicle->m_pPilot) { // set vehicles pilot's killer as murderer murderer = &g_entities[attacker->m_pVehicle->m_pPilot->s.number]; - if (murderer->inuse && murderer->client &&murderer->client->ps.otherKillerTime >= level.time) - { + if (murderer->inuse && murderer->client && murderer->client->ps.otherKillerTime >= level.time) { murderer = &g_entities[murderer->client->ps.otherKiller]; - if (!murderer->inuse || !murderer->client) - { + if (!murderer->inuse || !murderer->client) { murderer = NULL; } - } - else - { + } else { murderer = NULL; } - } - else - { + } else { murderer = &g_entities[attacker->s.number]; } - } - else if (self->m_pVehicle->m_pPilot) - { + } else if (self->m_pVehicle->m_pPilot) { murderer = (gentity_t *)self->m_pVehicle->m_pPilot; - if (!murderer->inuse || !murderer->client) - { + if (!murderer->inuse || !murderer->client) { murderer = NULL; } } - //no valid murderer.. just use self I guess - if (!murderer) - { + // no valid murderer.. just use self I guess + if (!murderer) { murderer = self; } - if ( self->m_pVehicle->m_pVehicleInfo->hideRider ) - {//pilot is *inside* me, so kill him, too + if (self->m_pVehicle->m_pVehicleInfo->hideRider) { // pilot is *inside* me, so kill him, too killEnt = (gentity_t *)self->m_pVehicle->m_pPilot; - if (killEnt && killEnt->inuse && killEnt->client) - { + if (killEnt && killEnt->inuse && killEnt->client) { G_Damage(killEnt, murderer, murderer, NULL, killEnt->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_BLASTER); } - if ( self->m_pVehicle->m_pVehicleInfo ) - {//FIXME: this wile got stuck in an endless loop, that's BAD!! This method SUCKS (not initting "i", not incrementing it or using it directly, all sorts of badness), so I'm rewriting it - //while (i < self->m_pVehicle->m_iNumPassengers) + if (self->m_pVehicle->m_pVehicleInfo) { // FIXME: this wile got stuck in an endless loop, that's BAD!! This method SUCKS (not initting "i", not + // incrementing it or using it directly, all sorts of badness), so I'm rewriting it + // while (i < self->m_pVehicle->m_iNumPassengers) int numPass = self->m_pVehicle->m_iNumPassengers; - for ( i = 0; i < numPass && self->m_pVehicle->m_iNumPassengers; i++ ) - {//go through and eject the last passenger - killEnt = (gentity_t *)self->m_pVehicle->m_ppPassengers[self->m_pVehicle->m_iNumPassengers-1]; - if ( killEnt ) - { + for (i = 0; i < numPass && self->m_pVehicle->m_iNumPassengers; i++) { // go through and eject the last passenger + killEnt = (gentity_t *)self->m_pVehicle->m_ppPassengers[self->m_pVehicle->m_iNumPassengers - 1]; + if (killEnt) { self->m_pVehicle->m_pVehicleInfo->Eject(self->m_pVehicle, (bgEntity_t *)killEnt, qtrue); - if ( killEnt->inuse && killEnt->client ) - { + if (killEnt->inuse && killEnt->client) { G_Damage(killEnt, murderer, murderer, NULL, killEnt->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_BLASTER); } } @@ -2223,8 +1783,7 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } } killEnt = (gentity_t *)self->m_pVehicle->m_pDroidUnit; - if (killEnt && killEnt->inuse && killEnt->client) - { + if (killEnt && killEnt->inuse && killEnt->client) { killEnt->flags &= ~FL_UNDYING; G_Damage(killEnt, murderer, murderer, NULL, killEnt->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_BLASTER); } @@ -2232,65 +1791,55 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int self->client->ps.emplacedIndex = 0; - G_BreakArm(self, 0); //unbreak anything we have broken - self->client->ps.saberEntityNum = self->client->saberStoredIndex; //in case we died while our saber was knocked away. + G_BreakArm(self, 0); // unbreak anything we have broken + self->client->ps.saberEntityNum = self->client->saberStoredIndex; // in case we died while our saber was knocked away. self->client->bodyGrabIndex = ENTITYNUM_NONE; self->client->bodyGrabTime = 0; - if (self->client->holdingObjectiveItem > 0) - { //carrying a siege objective item - make sure it updates and removes itself from us now in case this is an instant death-respawn situation + if (self->client->holdingObjectiveItem > + 0) { // carrying a siege objective item - make sure it updates and removes itself from us now in case this is an instant death-respawn situation gentity_t *objectiveItem = &g_entities[self->client->holdingObjectiveItem]; - if (objectiveItem->inuse && objectiveItem->think) - { - objectiveItem->think(objectiveItem); + if (objectiveItem->inuse && objectiveItem->think) { + objectiveItem->think(objectiveItem); } } - if ( (self->client->inSpaceIndex && self->client->inSpaceIndex != ENTITYNUM_NONE) || - (self->client->ps.eFlags2 & EF2_SHIP_DEATH) ) - { + if ((self->client->inSpaceIndex && self->client->inSpaceIndex != ENTITYNUM_NONE) || (self->client->ps.eFlags2 & EF2_SHIP_DEATH)) { self->client->noCorpse = qtrue; } - if ( self->client->NPC_class != CLASS_VEHICLE - && self->client->ps.m_iVehicleNum ) - { //I'm riding a vehicle - //tell it I'm getting off + if (self->client->NPC_class != CLASS_VEHICLE && self->client->ps.m_iVehicleNum) { // I'm riding a vehicle + // tell it I'm getting off gentity_t *veh = &g_entities[self->client->ps.m_iVehicleNum]; - if (veh->inuse && veh->client && veh->m_pVehicle) - { + if (veh->inuse && veh->client && veh->m_pVehicle) { veh->m_pVehicle->m_pVehicleInfo->Eject(veh->m_pVehicle, (bgEntity_t *)self, qtrue); - if (veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //go into "die in ship" mode with flag + if (veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // go into "die in ship" mode with flag self->client->ps.eFlags2 |= EF2_SHIP_DEATH; - //put me over where my vehicle exploded + // put me over where my vehicle exploded G_SetOrigin(self, veh->client->ps.origin); VectorCopy(veh->client->ps.origin, self->client->ps.origin); } } - //droids throw heads if they haven't yet - switch(self->client->NPC_class) - { + // droids throw heads if they haven't yet + switch (self->client->NPC_class) { case CLASS_R2D2: - if ( !trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "head" ) ) - { - vec3_t up; - AngleVectors( self->r.currentAngles, NULL, NULL, up ); - G_PlayEffectID( G_EffectIndex("chunks/r2d2head_veh"), self->r.currentOrigin, up ); + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "head")) { + vec3_t up; + AngleVectors(self->r.currentAngles, NULL, NULL, up); + G_PlayEffectID(G_EffectIndex("chunks/r2d2head_veh"), self->r.currentOrigin, up); } break; case CLASS_R5D2: - if ( !trap->G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "head" ) ) - { - vec3_t up; - AngleVectors( self->r.currentAngles, NULL, NULL, up ); - G_PlayEffectID( G_EffectIndex("chunks/r5d2head_veh"), self->r.currentOrigin, up ); + if (!trap->G2API_GetSurfaceRenderStatus(self->ghoul2, 0, "head")) { + vec3_t up; + AngleVectors(self->r.currentAngles, NULL, NULL, up); + G_PlayEffectID(G_EffectIndex("chunks/r5d2head_veh"), self->r.currentOrigin, up); } break; default: @@ -2298,23 +1847,19 @@ void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int } } - if ( self->NPC ) - { - if ( self->client && Jedi_WaitingAmbush( self ) ) - {//ambushing trooper + if (self->NPC) { + if (self->client && Jedi_WaitingAmbush(self)) { // ambushing trooper self->client->noclip = qfalse; } - NPC_FreeCombatPoint( self->NPC->combatPoint, qfalse ); - if ( self->NPC->group ) - { - //lastInGroup = (self->NPC->group->numGroup < 2); - AI_GroupMemberKilled( self ); - AI_DeleteSelfFromGroup( self ); + NPC_FreeCombatPoint(self->NPC->combatPoint, qfalse); + if (self->NPC->group) { + // lastInGroup = (self->NPC->group->numGroup < 2); + AI_GroupMemberKilled(self); + AI_DeleteSelfFromGroup(self); } - if ( self->NPC->tempGoal ) - { - G_FreeEntity( self->NPC->tempGoal ); + if (self->NPC->tempGoal) { + G_FreeEntity(self->NPC->tempGoal); self->NPC->tempGoal = NULL; } /* @@ -2341,41 +1886,31 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); //self->owner = old; } */ - if ( self->client->NPC_class == CLASS_BOBAFETT && self->client->ps.eFlags2 & EF2_FLYING ) - Boba_FlyStop( self ); - if ( self->s.NPC_class == CLASS_RANCOR ) - Rancor_DropVictim( self ); + if (self->client->NPC_class == CLASS_BOBAFETT && self->client->ps.eFlags2 & EF2_FLYING) + Boba_FlyStop(self); + if (self->s.NPC_class == CLASS_RANCOR) + Rancor_DropVictim(self); } - if ( attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self ) - { + if (attacker && attacker->NPC && attacker->NPC->group && attacker->NPC->group->enemy == self) { attacker->NPC->group->enemy = NULL; } - //Cheap method until/if I decide to put fancier stuff in (e.g. sabers falling out of hand and slowly - //holstering on death like sp) - if (self->client->ps.weapon == WP_SABER && - !self->client->ps.saberHolstered && - self->client->ps.saberEntityNum) - { - if (!self->client->ps.saberInFlight && - self->client->saber[0].soundOff) - { + // Cheap method until/if I decide to put fancier stuff in (e.g. sabers falling out of hand and slowly + // holstering on death like sp) + if (self->client->ps.weapon == WP_SABER && !self->client->ps.saberHolstered && self->client->ps.saberEntityNum) { + if (!self->client->ps.saberInFlight && self->client->saber[0].soundOff) { G_Sound(self, CHAN_AUTO, self->client->saber[0].soundOff); } - if (self->client->saber[1].soundOff && - self->client->saber[1].model[0]) - { + if (self->client->saber[1].soundOff && self->client->saber[1].model[0]) { G_Sound(self, CHAN_AUTO, self->client->saber[1].soundOff); } } - //Use any target we had - G_UseTargets( self, self ); + // Use any target we had + G_UseTargets(self, self); - if (g_slowmoDuelEnd.integer && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && attacker && attacker->inuse && attacker->client) - { - if (!gDoSlowMoDuel) - { + if (g_slowmoDuelEnd.integer && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && attacker && attacker->inuse && attacker->client) { + if (!gDoSlowMoDuel) { gDoSlowMoDuel = qtrue; gSlowMoDuelTime = level.time; } @@ -2388,55 +1923,51 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); } */ - //Make sure the jetpack is turned off. + // Make sure the jetpack is turned off. Jetpack_Off(self); self->client->ps.heldByClient = 0; self->client->beingThrown = 0; self->client->doingThrow = 0; - BG_ClearRocketLock( &self->client->ps ); + BG_ClearRocketLock(&self->client->ps); self->client->isHacking = 0; self->client->ps.hackingTime = 0; - if (inflictor && inflictor->activator && !inflictor->client && !attacker->client && - inflictor->activator->client && inflictor->activator->inuse && - inflictor->s.weapon == WP_TURRET) - { + if (inflictor && inflictor->activator && !inflictor->client && !attacker->client && inflictor->activator->client && inflictor->activator->inuse && + inflictor->s.weapon == WP_TURRET) { attacker = inflictor->activator; } - if (self->client && self->client->ps.isJediMaster) - { + if (self->client && self->client->ps.isJediMaster) { wasJediMaster = qtrue; } - //if he was charging or anything else, kill the sound + // if he was charging or anything else, kill the sound G_MuteSound(self->s.number, CHAN_WEAPON); - //FIXME: this may not be enough - if ( level.gametype == GT_SIEGE && meansOfDeath == MOD_TEAM_CHANGE ) - RemoveDetpacks( self ); + // FIXME: this may not be enough + if (level.gametype == GT_SIEGE && meansOfDeath == MOD_TEAM_CHANGE) + RemoveDetpacks(self); else - BlowDetpacks(self); //blow detpacks if they're planted + BlowDetpacks(self); // blow detpacks if they're planted self->client->ps.fd.forceDeactivateAll = 1; if ((self == attacker || (attacker && !attacker->client)) && (meansOfDeath == MOD_CRUSH || meansOfDeath == MOD_FALLING || meansOfDeath == MOD_TRIGGER_HURT || meansOfDeath == MOD_UNKNOWN) && - self->client->ps.otherKillerTime > level.time) - { + self->client->ps.otherKillerTime > level.time) { attacker = &g_entities[self->client->ps.otherKiller]; } // check for an almost capture - CheckAlmostCapture( self, attacker ); + CheckAlmostCapture(self, attacker); self->client->ps.pm_type = PM_DEAD; self->client->ps.pm_flags &= ~PMF_STUCK_TO_WALL; - if ( attacker ) { + if (attacker) { killer = attacker->s.number; - if ( attacker->client ) { + if (attacker->client) { killerName = attacker->client->pers.netname; } else { killerName = ""; @@ -2446,64 +1977,60 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); killerName = ""; } - if ( killer < 0 || killer >= MAX_CLIENTS ) { + if (killer < 0 || killer >= MAX_CLIENTS) { killer = ENTITYNUM_WORLD; killerName = ""; } - if ( meansOfDeath < 0 || meansOfDeath >= sizeof( modNames ) / sizeof( modNames[0] ) ) { + if (meansOfDeath < 0 || meansOfDeath >= sizeof(modNames) / sizeof(modNames[0])) { obit = ""; } else { - obit = modNames[ meansOfDeath ]; + obit = modNames[meansOfDeath]; } // log the victim and attacker's names with the method of death - Com_sprintf( buf, sizeof( buf ), "Kill: %i %i %i: %s killed ", killer, self->s.number, meansOfDeath, killerName ); - if ( self->s.eType == ET_NPC ) { + Com_sprintf(buf, sizeof(buf), "Kill: %i %i %i: %s killed ", killer, self->s.number, meansOfDeath, killerName); + if (self->s.eType == ET_NPC) { // check for named NPCs - if ( self->targetname ) - Q_strcat( buf, sizeof( buf ), va( "%s (%s) by %s\n", self->NPC_type, self->targetname, obit ) ); + if (self->targetname) + Q_strcat(buf, sizeof(buf), va("%s (%s) by %s\n", self->NPC_type, self->targetname, obit)); else - Q_strcat( buf, sizeof( buf ), va( "%s by %s\n", self->NPC_type, obit ) ); - } - else - Q_strcat( buf, sizeof( buf ), va( "%s by %s\n", self->client->pers.netname, obit ) ); - G_LogPrintf( "%s", buf ); - - if ( g_austrian.integer - && level.gametype == GT_DUEL - && level.numPlayingClients >= 2 ) - { - int spawnTime = (level.clients[level.sortedClients[0]].respawnTime > level.clients[level.sortedClients[1]].respawnTime) ? level.clients[level.sortedClients[0]].respawnTime : level.clients[level.sortedClients[1]].respawnTime; + Q_strcat(buf, sizeof(buf), va("%s by %s\n", self->NPC_type, obit)); + } else + Q_strcat(buf, sizeof(buf), va("%s by %s\n", self->client->pers.netname, obit)); + G_LogPrintf("%s", buf); + + if (g_austrian.integer && level.gametype == GT_DUEL && level.numPlayingClients >= 2) { + int spawnTime = (level.clients[level.sortedClients[0]].respawnTime > level.clients[level.sortedClients[1]].respawnTime) + ? level.clients[level.sortedClients[0]].respawnTime + : level.clients[level.sortedClients[1]].respawnTime; G_LogPrintf("Duel Kill Details:\n"); - G_LogPrintf("Kill Time: %d\n", level.time-spawnTime ); - G_LogPrintf("victim: %s, hits on enemy %d\n", self->client->pers.netname, self->client->ps.persistant[PERS_HITS] ); - if ( attacker && attacker->client ) - { - G_LogPrintf("killer: %s, hits on enemy %d, health: %d\n", attacker->client->pers.netname, attacker->client->ps.persistant[PERS_HITS], attacker->health ); - //also - if MOD_SABER, list the animation and saber style - if ( meansOfDeath == MOD_SABER ) - { - G_LogPrintf("killer saber style: %d, killer saber anim %s\n", attacker->client->ps.fd.saberAnimLevel, animTable[(attacker->client->ps.torsoAnim)].name ); + G_LogPrintf("Kill Time: %d\n", level.time - spawnTime); + G_LogPrintf("victim: %s, hits on enemy %d\n", self->client->pers.netname, self->client->ps.persistant[PERS_HITS]); + if (attacker && attacker->client) { + G_LogPrintf("killer: %s, hits on enemy %d, health: %d\n", attacker->client->pers.netname, attacker->client->ps.persistant[PERS_HITS], + attacker->health); + // also - if MOD_SABER, list the animation and saber style + if (meansOfDeath == MOD_SABER) { + G_LogPrintf("killer saber style: %d, killer saber anim %s\n", attacker->client->ps.fd.saberAnimLevel, + animTable[(attacker->client->ps.torsoAnim)].name); } } } G_LogWeaponKill(killer, meansOfDeath); G_LogWeaponDeath(self->s.number, self->s.weapon); - if (attacker && attacker->client && attacker->inuse) - { + if (attacker && attacker->client && attacker->inuse) { G_LogWeaponFrag(killer, self->s.number); } // broadcast the death event to everyone - if (self->s.eType != ET_NPC && !g_noPDuelCheck) - { - ent = G_TempEntity( self->r.currentOrigin, EV_OBITUARY ); + if (self->s.eType != ET_NPC && !g_noPDuelCheck) { + ent = G_TempEntity(self->r.currentOrigin, EV_OBITUARY); ent->s.eventParm = meansOfDeath; ent->s.otherEntityNum = self->s.number; ent->s.otherEntityNum2 = killer; - ent->r.svFlags = SVF_BROADCAST; // send to everyone + ent->r.svFlags = SVF_BROADCAST; // send to everyone ent->s.isJediMaster = wasJediMaster; } @@ -2511,8 +2038,7 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->client->ps.persistant[PERS_KILLED]++; - if (self == attacker) - { + if (self == attacker) { self->client->ps.fd.suicides++; } @@ -2521,74 +2047,53 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); G_CheckVictoryScript(attacker); - if ( attacker == self || OnSameTeam (self, attacker ) ) { - if (level.gametype == GT_DUEL) - { //in duel, if you kill yourself, the person you are dueling against gets a kill for it + if (attacker == self || OnSameTeam(self, attacker)) { + if (level.gametype == GT_DUEL) { // in duel, if you kill yourself, the person you are dueling against gets a kill for it int otherClNum = -1; - if (level.sortedClients[0] == self->s.number) - { + if (level.sortedClients[0] == self->s.number) { otherClNum = level.sortedClients[1]; - } - else if (level.sortedClients[1] == self->s.number) - { + } else if (level.sortedClients[1] == self->s.number) { otherClNum = level.sortedClients[0]; } - if (otherClNum >= 0 && otherClNum < MAX_CLIENTS && - g_entities[otherClNum].inuse && g_entities[otherClNum].client && - otherClNum != attacker->s.number) - { - AddScore( &g_entities[otherClNum], self->r.currentOrigin, 1 ); - } - else - { - AddScore( attacker, self->r.currentOrigin, -1 ); + if (otherClNum >= 0 && otherClNum < MAX_CLIENTS && g_entities[otherClNum].inuse && g_entities[otherClNum].client && + otherClNum != attacker->s.number) { + AddScore(&g_entities[otherClNum], self->r.currentOrigin, 1); + } else { + AddScore(attacker, self->r.currentOrigin, -1); } + } else { + AddScore(attacker, self->r.currentOrigin, -1); } - else - { - AddScore( attacker, self->r.currentOrigin, -1 ); - } - if (level.gametype == GT_JEDIMASTER) - { - if (self->client && self->client->ps.isJediMaster) - { //killed ourself so return the saber to the original position - //(to avoid people jumping off ledges and making the saber - //unreachable for 60 seconds) + if (level.gametype == GT_JEDIMASTER) { + if (self->client && self->client->ps.isJediMaster) { // killed ourself so return the saber to the original position + //(to avoid people jumping off ledges and making the saber + // unreachable for 60 seconds) ThrowSaberToAttacker(self, NULL); self->client->ps.isJediMaster = qfalse; } } } else { - if (level.gametype == GT_JEDIMASTER) - { - if ((attacker->client && attacker->client->ps.isJediMaster) || - (self->client && self->client->ps.isJediMaster)) - { - AddScore( attacker, self->r.currentOrigin, 1 ); + if (level.gametype == GT_JEDIMASTER) { + if ((attacker->client && attacker->client->ps.isJediMaster) || (self->client && self->client->ps.isJediMaster)) { + AddScore(attacker, self->r.currentOrigin, 1); - if (self->client && self->client->ps.isJediMaster) - { + if (self->client && self->client->ps.isJediMaster) { ThrowSaberToAttacker(self, attacker); self->client->ps.isJediMaster = qfalse; } - } - else - { + } else { gentity_t *jmEnt = G_GetJediMaster(); - if (jmEnt && jmEnt->client) - { - AddScore( jmEnt, self->r.currentOrigin, 1 ); + if (jmEnt && jmEnt->client) { + AddScore(jmEnt, self->r.currentOrigin, 1); } } - } - else - { - AddScore( attacker, self->r.currentOrigin, 1 ); + } else { + AddScore(attacker, self->r.currentOrigin, 1); } - if( meansOfDeath == MOD_STUN_BATON ) { + if (meansOfDeath == MOD_STUN_BATON) { // play humiliation on player attacker->client->ps.persistant[PERS_GAUNTLET_FRAG_COUNT]++; @@ -2601,50 +2106,37 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); // check for two kills in a short amount of time // if this is close enough to the last kill, give a reward sound - if ( level.time - attacker->client->lastKillTime < CARNAGE_REWARD_TIME ) { + if (level.time - attacker->client->lastKillTime < CARNAGE_REWARD_TIME) { // play excellent on player attacker->client->ps.persistant[PERS_EXCELLENT_COUNT]++; attacker->client->rewardTime = level.time + REWARD_SPRITE_TIME; } attacker->client->lastKillTime = level.time; - } } else { - if (self->client && self->client->ps.isJediMaster) - { //killed ourself so return the saber to the original position - //(to avoid people jumping off ledges and making the saber - //unreachable for 60 seconds) + if (self->client && self->client->ps.isJediMaster) { // killed ourself so return the saber to the original position + //(to avoid people jumping off ledges and making the saber + // unreachable for 60 seconds) ThrowSaberToAttacker(self, NULL); self->client->ps.isJediMaster = qfalse; } - if (level.gametype == GT_DUEL) - { //in duel, if you kill yourself, the person you are dueling against gets a kill for it + if (level.gametype == GT_DUEL) { // in duel, if you kill yourself, the person you are dueling against gets a kill for it int otherClNum = -1; - if (level.sortedClients[0] == self->s.number) - { + if (level.sortedClients[0] == self->s.number) { otherClNum = level.sortedClients[1]; - } - else if (level.sortedClients[1] == self->s.number) - { + } else if (level.sortedClients[1] == self->s.number) { otherClNum = level.sortedClients[0]; } - if (otherClNum >= 0 && otherClNum < MAX_CLIENTS && - g_entities[otherClNum].inuse && g_entities[otherClNum].client && - otherClNum != self->s.number) - { - AddScore( &g_entities[otherClNum], self->r.currentOrigin, 1 ); - } - else - { - AddScore( self, self->r.currentOrigin, -1 ); + if (otherClNum >= 0 && otherClNum < MAX_CLIENTS && g_entities[otherClNum].inuse && g_entities[otherClNum].client && otherClNum != self->s.number) { + AddScore(&g_entities[otherClNum], self->r.currentOrigin, 1); + } else { + AddScore(self, self->r.currentOrigin, -1); } - } - else - { - AddScore( self, self->r.currentOrigin, -1 ); + } else { + AddScore(self, self->r.currentOrigin, -1); } } @@ -2653,77 +2145,67 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); // if I committed suicide, the flag does not fall, it returns. if (meansOfDeath == MOD_SUICIDE) { - if ( self->client->ps.powerups[PW_NEUTRALFLAG] ) { // only happens in One Flag CTF - Team_ReturnFlag( TEAM_FREE ); + if (self->client->ps.powerups[PW_NEUTRALFLAG]) { // only happens in One Flag CTF + Team_ReturnFlag(TEAM_FREE); self->client->ps.powerups[PW_NEUTRALFLAG] = 0; - } - else if ( self->client->ps.powerups[PW_REDFLAG] ) { // only happens in standard CTF - Team_ReturnFlag( TEAM_RED ); + } else if (self->client->ps.powerups[PW_REDFLAG]) { // only happens in standard CTF + Team_ReturnFlag(TEAM_RED); self->client->ps.powerups[PW_REDFLAG] = 0; - } - else if ( self->client->ps.powerups[PW_BLUEFLAG] ) { // only happens in standard CTF - Team_ReturnFlag( TEAM_BLUE ); + } else if (self->client->ps.powerups[PW_BLUEFLAG]) { // only happens in standard CTF + Team_ReturnFlag(TEAM_BLUE); self->client->ps.powerups[PW_BLUEFLAG] = 0; } } if (!self->client->ps.fallingToDeath) { - if (self->s.eType != ET_NPC) - { - TossClientItems( self ); + if (self->s.eType != ET_NPC) { + TossClientItems(self); } - } - else { - if ( self->client->ps.powerups[PW_NEUTRALFLAG] ) { // only happens in One Flag CTF - Team_ReturnFlag( TEAM_FREE ); + } else { + if (self->client->ps.powerups[PW_NEUTRALFLAG]) { // only happens in One Flag CTF + Team_ReturnFlag(TEAM_FREE); self->client->ps.powerups[PW_NEUTRALFLAG] = 0; - } - else if ( self->client->ps.powerups[PW_REDFLAG] ) { // only happens in standard CTF - Team_ReturnFlag( TEAM_RED ); + } else if (self->client->ps.powerups[PW_REDFLAG]) { // only happens in standard CTF + Team_ReturnFlag(TEAM_RED); self->client->ps.powerups[PW_REDFLAG] = 0; - } - else if ( self->client->ps.powerups[PW_BLUEFLAG] ) { // only happens in standard CTF - Team_ReturnFlag( TEAM_BLUE ); + } else if (self->client->ps.powerups[PW_BLUEFLAG]) { // only happens in standard CTF + Team_ReturnFlag(TEAM_BLUE); self->client->ps.powerups[PW_BLUEFLAG] = 0; } } - if ( MOD_TEAM_CHANGE == meansOfDeath ) - { + if (MOD_TEAM_CHANGE == meansOfDeath) { // Give them back a point since they didn't really die. - AddScore( self, self->r.currentOrigin, 1 ); - } - else - { - Cmd_Score_f( self ); // show scores + AddScore(self, self->r.currentOrigin, 1); + } else { + Cmd_Score_f(self); // show scores } // send updated scores to any clients that are following this one, // or they would get stale scoreboards - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { gclient_t *cl = &level.clients[i]; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( cl->sess.sessionTeam != TEAM_SPECTATOR ) { + if (cl->sess.sessionTeam != TEAM_SPECTATOR) { continue; } - if ( cl->sess.spectatorClient == self->s.number ) { - Cmd_Score_f( g_entities + i ); + if (cl->sess.spectatorClient == self->s.number) { + Cmd_Score_f(g_entities + i); } } - self->takedamage = qtrue; // can still be gibbed + self->takedamage = qtrue; // can still be gibbed self->s.weapon = WP_NONE; self->s.powerups = 0; - if (self->s.eType != ET_NPC) - { //handled differently for NPCs + if (self->s.eType != ET_NPC) { // handled differently for NPCs self->r.contents = CONTENTS_CORPSE; } - self->client->ps.zoomMode = 0; // Turn off zooming when we die + self->client->ps.zoomMode = 0; // Turn off zooming when we die - //rww - 07/19/02 - I removed this because it isn't working and it's ugly (for people on the outside) + // rww - 07/19/02 - I removed this because it isn't working and it's ugly (for people on the outside) /* self->s.angles[0] = 0; self->s.angles[2] = 0; @@ -2735,8 +2217,7 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; - if (self->s.eType != ET_NPC) - { //handled differently for NPCs + if (self->s.eType != ET_NPC) { // handled differently for NPCs self->r.maxs[2] = -8; } @@ -2745,7 +2226,7 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); self->client->respawnTime = level.time + 1700; // remove powerups - memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) ); + memset(self->client->ps.powerups, 0, sizeof(self->client->ps.powerups)); self->client->ps.stats[STAT_HOLDABLE_ITEMS] = 0; self->client->ps.stats[STAT_HOLDABLE_ITEM] = 0; @@ -2767,91 +2248,79 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); anim = G_PickDeathAnim(self, self->pos1, damage, meansOfDeath, HL_NONE); - if (anim >= 1) - { //Some droids don't have death anims + if (anim >= 1) { // Some droids don't have death anims // for the no-blood option, we need to prevent the health // from going to gib level - if ( self->health <= GIB_HEALTH ) { - self->health = GIB_HEALTH+1; + if (self->health <= GIB_HEALTH) { + self->health = GIB_HEALTH + 1; } - self->client->respawnTime = level.time + 1000;//((self->client->animations[anim].numFrames*40)/(50.0f / self->client->animations[anim].frameLerp))+300; + self->client->respawnTime = + level.time + 1000; //((self->client->animations[anim].numFrames*40)/(50.0f / self->client->animations[anim].frameLerp))+300; sPMType = self->client->ps.pm_type; - self->client->ps.pm_type = PM_NORMAL; //don't want pm type interfering with our setanim calls. + self->client->ps.pm_type = PM_NORMAL; // don't want pm type interfering with our setanim calls. - if (self->inuse) - { //not disconnecting - G_SetAnim(self, NULL, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_RESTART, 0); + if (self->inuse) { // not disconnecting + G_SetAnim(self, NULL, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_RESTART, 0); } self->client->ps.pm_type = sPMType; - if (meansOfDeath == MOD_SABER || (meansOfDeath == MOD_MELEE && G_HeavyMelee( attacker )) )//saber or heavy melee (claws) - { //update the anim on the actual skeleton (so bolt point will reflect the correct position) and then check for dismem + if (meansOfDeath == MOD_SABER || (meansOfDeath == MOD_MELEE && G_HeavyMelee(attacker))) // saber or heavy melee (claws) + { // update the anim on the actual skeleton (so bolt point will reflect the correct position) and then check for dismem G_UpdateClientAnims(self, 1.0f); G_CheckForDismemberment(self, attacker, self->pos1, damage, anim, qfalse); } - } - else if (self->NPC && self->client && self->client->NPC_class != CLASS_MARK1 && - self->client->NPC_class != CLASS_VEHICLE) - { //in this case if we're an NPC it's my guess that we want to get removed straight away. + } else if (self->NPC && self->client && self->client->NPC_class != CLASS_MARK1 && + self->client->NPC_class != CLASS_VEHICLE) { // in this case if we're an NPC it's my guess that we want to get removed straight away. self->think = G_FreeEntity; self->nextthink = level.time; } - //self->client->ps.legsAnim = anim; - //self->client->ps.torsoAnim = anim; -// self->client->ps.pm_flags |= PMF_UPDATE_ANIM; // Make sure the pmove sets up the GHOUL2 anims. + // self->client->ps.legsAnim = anim; + // self->client->ps.torsoAnim = anim; + // self->client->ps.pm_flags |= PMF_UPDATE_ANIM; // Make sure the pmove sets up the GHOUL2 anims. - //rww - do this on respawn, not death - //CopyToBodyQue (self); + // rww - do this on respawn, not death + // CopyToBodyQue (self); - //G_AddEvent( self, EV_DEATH1 + i, killer ); - if (wasJediMaster) - { - G_AddEvent( self, EV_DEATH1 + deathAnim, 1 ); - } - else - { - G_AddEvent( self, EV_DEATH1 + deathAnim, 0 ); + // G_AddEvent( self, EV_DEATH1 + i, killer ); + if (wasJediMaster) { + G_AddEvent(self, EV_DEATH1 + deathAnim, 1); + } else { + G_AddEvent(self, EV_DEATH1 + deathAnim, 0); } - if (self != attacker) - { //don't make NPCs want to murder you on respawn for killing yourself! - G_DeathAlert( self, attacker ); + if (self != attacker) { // don't make NPCs want to murder you on respawn for killing yourself! + G_DeathAlert(self, attacker); } // the body can still be gibbed - if (!self->NPC) - { //don't remove NPCs like this! + if (!self->NPC) { // don't remove NPCs like this! self->die = body_die; } - //It won't gib, it will disintegrate (because this is Star Wars). + // It won't gib, it will disintegrate (because this is Star Wars). self->takedamage = qtrue; // globally cycle through the different death animations - deathAnim = ( deathAnim + 1 ) % 3; + deathAnim = (deathAnim + 1) % 3; } - if ( self->NPC ) - {//If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths + if (self->NPC) { // If an NPC, make sure we start running our scripts again- this gets set to infinite while we fall to our deaths self->NPC->nextBStateThink = level.time; } - if ( G_ActivateBehavior( self, BSET_DEATH ) ) - { - //deathScript = qtrue; + if (G_ActivateBehavior(self, BSET_DEATH)) { + // deathScript = qtrue; } - if ( self->NPC && (self->NPC->scriptFlags&SCF_FFDEATH) ) - { - if ( G_ActivateBehavior( self, BSET_FFDEATH ) ) - {//FIXME: should running this preclude running the normal deathscript? - //deathScript = qtrue; + if (self->NPC && (self->NPC->scriptFlags & SCF_FFDEATH)) { + if (G_ActivateBehavior(self, BSET_FFDEATH)) { // FIXME: should running this preclude running the normal deathscript? + // deathScript = qtrue; } - G_UseTargets2( self, self, self->target4 ); + G_UseTargets2(self, self, self->target4); } /* @@ -2863,52 +2332,41 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); ICARUS_FreeEnt(self); } */ - //rwwFIXMEFIXME: Do this too? + // rwwFIXMEFIXME: Do this too? // Free up any timers we may have on us. - TIMER_Clear2( self ); + TIMER_Clear2(self); - trap->LinkEntity ((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); - if ( self->NPC ) - { - self->NPC->timeOfDeath = level.time;//this will change - used for debouncing post-death events + if (self->NPC) { + self->NPC->timeOfDeath = level.time; // this will change - used for debouncing post-death events } // Start any necessary death fx for this entity - if ( self->NPC ) - DeathFX( self ); - + if (self->NPC) + DeathFX(self); - if (level.gametype == GT_POWERDUEL && !g_noPDuelCheck) - { //powerduel checks - if (self->client->sess.duelTeam == DUELTEAM_LONE) - { //automatically means a win as there is only one + if (level.gametype == GT_POWERDUEL && !g_noPDuelCheck) { // powerduel checks + if (self->client->sess.duelTeam == DUELTEAM_LONE) { // automatically means a win as there is only one G_AddPowerDuelScore(DUELTEAM_DOUBLE, 1); G_AddPowerDuelLoserScore(DUELTEAM_LONE, 1); g_endPDuel = qtrue; - } - else if (self->client->sess.duelTeam == DUELTEAM_DOUBLE) - { + } else if (self->client->sess.duelTeam == DUELTEAM_DOUBLE) { gentity_t *check; qboolean heLives = qfalse; - for ( i=0; iinuse && check->client && check->s.number != self->s.number && - check->client->pers.connected == CON_CONNECTED && !check->client->iAmALoser && - check->client->ps.stats[STAT_HEALTH] > 0 && - check->client->sess.sessionTeam != TEAM_SPECTATOR && - check->client->sess.duelTeam == DUELTEAM_DOUBLE) - { //still an active living paired duelist so it's not over yet. + if (check->inuse && check->client && check->s.number != self->s.number && check->client->pers.connected == CON_CONNECTED && + !check->client->iAmALoser && check->client->ps.stats[STAT_HEALTH] > 0 && check->client->sess.sessionTeam != TEAM_SPECTATOR && + check->client->sess.duelTeam == DUELTEAM_DOUBLE) { // still an active living paired duelist so it's not over yet. heLives = qtrue; break; } } - if (!heLives) - { //they're all dead, give the lone duelist the win. + if (!heLives) { // they're all dead, give the lone duelist the win. G_AddPowerDuelScore(DUELTEAM_LONE, 1); G_AddPowerDuelLoserScore(DUELTEAM_DOUBLE, 1); g_endPDuel = qtrue; @@ -2917,17 +2375,15 @@ extern void RunEmplacedWeapon( gentity_t *ent, usercmd_t **ucmd ); } } - /* ================ CheckArmor ================ */ -int CheckArmor (gentity_t *ent, int damage, int dflags) -{ - gclient_t *client; - int save; - int count; +int CheckArmor(gentity_t *ent, int damage, int dflags) { + gclient_t *client; + int save; + int count; if (!damage) return 0; @@ -2940,21 +2396,16 @@ int CheckArmor (gentity_t *ent, int damage, int dflags) if (dflags & DAMAGE_NO_ARMOR) return 0; - if ( client->NPC_class == CLASS_VEHICLE - && ent->m_pVehicle - && ent->client->ps.electrifyTime > level.time ) - {//ion-cannon has disabled this ship's shields, take damage on hull! + if (client->NPC_class == CLASS_VEHICLE && ent->m_pVehicle && + ent->client->ps.electrifyTime > level.time) { // ion-cannon has disabled this ship's shields, take damage on hull! return 0; } // armor count = client->ps.stats[STAT_ARMOR]; - if (dflags & DAMAGE_HALF_ABSORB) - { // Half the damage gets absorbed by the shields, rather than 100% - save = ceil( damage * ARMOR_PROTECTION ); - } - else - { // All the damage gets absorbed by the shields. + if (dflags & DAMAGE_HALF_ABSORB) { // Half the damage gets absorbed by the shields, rather than 100% + save = ceil(damage * ARMOR_PROTECTION); + } else { // All the damage gets absorbed by the shields. save = damage; } @@ -2965,61 +2416,50 @@ int CheckArmor (gentity_t *ent, int damage, int dflags) if (!save) return 0; - if (dflags & DAMAGE_HALF_ARMOR_REDUCTION) // Armor isn't whittled so easily by sniper shots. - { - client->ps.stats[STAT_ARMOR] -= (int)(save*ARMOR_REDUCTION_FACTOR); - } - else + if (dflags & DAMAGE_HALF_ARMOR_REDUCTION) // Armor isn't whittled so easily by sniper shots. { + client->ps.stats[STAT_ARMOR] -= (int)(save * ARMOR_REDUCTION_FACTOR); + } else { client->ps.stats[STAT_ARMOR] -= save; } return save; } +void G_ApplyKnockback(gentity_t *targ, vec3_t newDir, float knockback) { + vec3_t kvel; + float mass; -void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) -{ - vec3_t kvel; - float mass; - - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass mass = targ->physicsBounce; else mass = 200; - if ( g_gravity.value > 0 ) - { - VectorScale( newDir, g_knockback.value * (float)knockback / mass * 0.8, kvel ); + if (g_gravity.value > 0) { + VectorScale(newDir, g_knockback.value * (float)knockback / mass * 0.8, kvel); kvel[2] = newDir[2] * g_knockback.value * (float)knockback / mass * 1.5; - } - else - { - VectorScale( newDir, g_knockback.value * (float)knockback / mass, kvel ); + } else { + VectorScale(newDir, g_knockback.value * (float)knockback / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->r.currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->r.currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = knockback * 2; - if ( t < 50 ) { + if (t < 50) { t = 50; } - if ( t > 200 ) { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -3032,7 +2472,7 @@ void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) RaySphereIntersections ================ */ -int RaySphereIntersections( vec3_t origin, float radius, vec3_t point, vec3_t dir, vec3_t intersections[2] ) { +int RaySphereIntersections(vec3_t origin, float radius, vec3_t point, vec3_t dir, vec3_t intersections[2]) { float b, c, d, t; // | origin - (point + t * dir) | = radius @@ -3043,21 +2483,18 @@ int RaySphereIntersections( vec3_t origin, float radius, vec3_t point, vec3_t di // normalize dir so a = 1 VectorNormalize(dir); b = 2 * (dir[0] * (point[0] - origin[0]) + dir[1] * (point[1] - origin[1]) + dir[2] * (point[2] - origin[2])); - c = (point[0] - origin[0]) * (point[0] - origin[0]) + - (point[1] - origin[1]) * (point[1] - origin[1]) + - (point[2] - origin[2]) * (point[2] - origin[2]) - + c = (point[0] - origin[0]) * (point[0] - origin[0]) + (point[1] - origin[1]) * (point[1] - origin[1]) + (point[2] - origin[2]) * (point[2] - origin[2]) - radius * radius; d = b * b - 4 * c; if (d > 0) { - t = (- b + sqrt(d)) / 2; + t = (-b + sqrt(d)) / 2; VectorMA(point, t, dir, intersections[0]); - t = (- b - sqrt(d)) / 2; + t = (-b - sqrt(d)) / 2; VectorMA(point, t, dir, intersections[1]); return 2; - } - else if (d == 0) { - t = (- b ) / 2; + } else if (d == 0) { + t = (-b) / 2; VectorMA(point, t, dir, intersections[0]); return 1; } @@ -3069,97 +2506,94 @@ int RaySphereIntersections( vec3_t origin, float radius, vec3_t point, vec3_t di rww - beginning of the majority of the dismemberment and location based damage code. =================================== */ -char *hitLocName[HL_MAX] = -{ - "none", //HL_NONE = 0, - "right foot", //HL_FOOT_RT, - "left foot", //HL_FOOT_LT, - "right leg", //HL_LEG_RT, - "left leg", //HL_LEG_LT, - "waist", //HL_WAIST, - "back right shoulder", //HL_BACK_RT, - "back left shoulder", //HL_BACK_LT, - "back", //HL_BACK, - "front right shouler", //HL_CHEST_RT, - "front left shoulder", //HL_CHEST_LT, - "chest", //HL_CHEST, - "right arm", //HL_ARM_RT, - "left arm", //HL_ARM_LT, - "right hand", //HL_HAND_RT, - "left hand", //HL_HAND_LT, - "head", //HL_HEAD - "generic1", //HL_GENERIC1, - "generic2", //HL_GENERIC2, - "generic3", //HL_GENERIC3, - "generic4", //HL_GENERIC4, - "generic5", //HL_GENERIC5, - "generic6" //HL_GENERIC6 +char *hitLocName[HL_MAX] = { + "none", // HL_NONE = 0, + "right foot", // HL_FOOT_RT, + "left foot", // HL_FOOT_LT, + "right leg", // HL_LEG_RT, + "left leg", // HL_LEG_LT, + "waist", // HL_WAIST, + "back right shoulder", // HL_BACK_RT, + "back left shoulder", // HL_BACK_LT, + "back", // HL_BACK, + "front right shouler", // HL_CHEST_RT, + "front left shoulder", // HL_CHEST_LT, + "chest", // HL_CHEST, + "right arm", // HL_ARM_RT, + "left arm", // HL_ARM_LT, + "right hand", // HL_HAND_RT, + "left hand", // HL_HAND_LT, + "head", // HL_HEAD + "generic1", // HL_GENERIC1, + "generic2", // HL_GENERIC2, + "generic3", // HL_GENERIC3, + "generic4", // HL_GENERIC4, + "generic5", // HL_GENERIC5, + "generic6" // HL_GENERIC6 }; -void G_GetDismemberLoc(gentity_t *self, vec3_t boltPoint, int limbType) -{ //Just get the general area without using server-side ghoul2 +void G_GetDismemberLoc(gentity_t *self, vec3_t boltPoint, int limbType) { // Just get the general area without using server-side ghoul2 vec3_t fwd, right, up; AngleVectors(self->r.currentAngles, fwd, right, up); VectorCopy(self->r.currentOrigin, boltPoint); - switch (limbType) - { + switch (limbType) { case G2_MODELPART_HEAD: - boltPoint[0] += up[0]*24; - boltPoint[1] += up[1]*24; - boltPoint[2] += up[2]*24; + boltPoint[0] += up[0] * 24; + boltPoint[1] += up[1] * 24; + boltPoint[2] += up[2] * 24; break; case G2_MODELPART_WAIST: - boltPoint[0] += up[0]*4; - boltPoint[1] += up[1]*4; - boltPoint[2] += up[2]*4; + boltPoint[0] += up[0] * 4; + boltPoint[1] += up[1] * 4; + boltPoint[2] += up[2] * 4; break; case G2_MODELPART_LARM: - boltPoint[0] += up[0]*18; - boltPoint[1] += up[1]*18; - boltPoint[2] += up[2]*18; + boltPoint[0] += up[0] * 18; + boltPoint[1] += up[1] * 18; + boltPoint[2] += up[2] * 18; - boltPoint[0] -= right[0]*10; - boltPoint[1] -= right[1]*10; - boltPoint[2] -= right[2]*10; + boltPoint[0] -= right[0] * 10; + boltPoint[1] -= right[1] * 10; + boltPoint[2] -= right[2] * 10; break; case G2_MODELPART_RARM: - boltPoint[0] += up[0]*18; - boltPoint[1] += up[1]*18; - boltPoint[2] += up[2]*18; + boltPoint[0] += up[0] * 18; + boltPoint[1] += up[1] * 18; + boltPoint[2] += up[2] * 18; - boltPoint[0] += right[0]*10; - boltPoint[1] += right[1]*10; - boltPoint[2] += right[2]*10; + boltPoint[0] += right[0] * 10; + boltPoint[1] += right[1] * 10; + boltPoint[2] += right[2] * 10; break; case G2_MODELPART_RHAND: - boltPoint[0] += up[0]*8; - boltPoint[1] += up[1]*8; - boltPoint[2] += up[2]*8; + boltPoint[0] += up[0] * 8; + boltPoint[1] += up[1] * 8; + boltPoint[2] += up[2] * 8; - boltPoint[0] += right[0]*10; - boltPoint[1] += right[1]*10; - boltPoint[2] += right[2]*10; + boltPoint[0] += right[0] * 10; + boltPoint[1] += right[1] * 10; + boltPoint[2] += right[2] * 10; break; case G2_MODELPART_LLEG: - boltPoint[0] -= up[0]*4; - boltPoint[1] -= up[1]*4; - boltPoint[2] -= up[2]*4; + boltPoint[0] -= up[0] * 4; + boltPoint[1] -= up[1] * 4; + boltPoint[2] -= up[2] * 4; - boltPoint[0] -= right[0]*10; - boltPoint[1] -= right[1]*10; - boltPoint[2] -= right[2]*10; + boltPoint[0] -= right[0] * 10; + boltPoint[1] -= right[1] * 10; + boltPoint[2] -= right[2] * 10; break; case G2_MODELPART_RLEG: - boltPoint[0] -= up[0]*4; - boltPoint[1] -= up[1]*4; - boltPoint[2] -= up[2]*4; + boltPoint[0] -= up[0] * 4; + boltPoint[1] -= up[1] * 4; + boltPoint[2] -= up[2] * 4; - boltPoint[0] += right[0]*10; - boltPoint[1] += right[1]*10; - boltPoint[2] += right[2]*10; + boltPoint[0] += right[0] * 10; + boltPoint[1] += right[1] * 10; + boltPoint[2] += right[2] * 10; break; default: break; @@ -3168,27 +2602,22 @@ void G_GetDismemberLoc(gentity_t *self, vec3_t boltPoint, int limbType) return; } -void G_GetDismemberBolt(gentity_t *self, vec3_t boltPoint, int limbType) -{ +void G_GetDismemberBolt(gentity_t *self, vec3_t boltPoint, int limbType) { int useBolt = self->genericValue5; vec3_t properOrigin, properAngles, addVel; - //matrix3_t legAxis; - mdxaBone_t boltMatrix; + // matrix3_t legAxis; + mdxaBone_t boltMatrix; float fVSpeed = 0; char *rotateBone = NULL; - switch (limbType) - { + switch (limbType) { case G2_MODELPART_HEAD: rotateBone = "cranium"; break; case G2_MODELPART_WAIST: - if (self->localAnimIndex <= 1) - { //humanoid + if (self->localAnimIndex <= 1) { // humanoid rotateBone = "thoracic"; - } - else - { + } else { rotateBone = "pelvis"; } break; @@ -3217,40 +2646,31 @@ void G_GetDismemberBolt(gentity_t *self, vec3_t boltPoint, int limbType) VectorCopy(self->client->ps.origin, properOrigin); VectorCopy(self->client->ps.viewangles, properAngles); - //try to predict the origin based on velocity so it's more like what the client is seeing + // try to predict the origin based on velocity so it's more like what the client is seeing VectorCopy(self->client->ps.velocity, addVel); VectorNormalize(addVel); - if (self->client->ps.velocity[0] < 0) - { + if (self->client->ps.velocity[0] < 0) { fVSpeed += (-self->client->ps.velocity[0]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[0]; } - if (self->client->ps.velocity[1] < 0) - { + if (self->client->ps.velocity[1] < 0) { fVSpeed += (-self->client->ps.velocity[1]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[1]; } - if (self->client->ps.velocity[2] < 0) - { + if (self->client->ps.velocity[2] < 0) { fVSpeed += (-self->client->ps.velocity[2]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[2]; } fVSpeed *= 0.08f; - properOrigin[0] += addVel[0]*fVSpeed; - properOrigin[1] += addVel[1]*fVSpeed; - properOrigin[2] += addVel[2]*fVSpeed; + properOrigin[0] += addVel[0] * fVSpeed; + properOrigin[1] += addVel[1] * fVSpeed; + properOrigin[2] += addVel[2] * fVSpeed; properAngles[0] = 0; properAngles[1] = self->client->ps.viewangles[YAW]; @@ -3264,8 +2684,7 @@ void G_GetDismemberBolt(gentity_t *self, vec3_t boltPoint, int limbType) trap->G2API_GetBoltMatrix(self->ghoul2, 1, 0, &boltMatrix, properAngles, properOrigin, level.time, NULL, self->modelScale); - if (self->client && limbType == G2_MODELPART_RHAND) - { //Make some saber hit sparks over the severed wrist area + if (self->client && limbType == G2_MODELPART_RHAND) { // Make some saber hit sparks over the severed wrist area vec3_t boltAngles; gentity_t *te; @@ -3273,36 +2692,31 @@ void G_GetDismemberBolt(gentity_t *self, vec3_t boltPoint, int limbType) boltAngles[1] = -boltMatrix.matrix[1][1]; boltAngles[2] = -boltMatrix.matrix[2][1]; - te = G_TempEntity( boltPoint, EV_SABER_HIT ); + te = G_TempEntity(boltPoint, EV_SABER_HIT); te->s.otherEntityNum = self->s.number; te->s.otherEntityNum2 = ENTITYNUM_NONE; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum VectorCopy(boltPoint, te->s.origin); VectorCopy(boltAngles, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { //don't let it play with no direction + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { // don't let it play with no direction te->s.angles[1] = 1; } - te->s.eventParm = 16; //lots of sparks + te->s.eventParm = 16; // lots of sparks } } -void LimbTouch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ -} +void LimbTouch(gentity_t *self, gentity_t *other, trace_t *trace) {} -void LimbThink( gentity_t *ent ) -{ +void LimbThink(gentity_t *ent) { float gravity = 3.0f; float mass = 0.09f; float bounce = 1.3f; - switch (ent->s.modelGhoul2) - { + switch (ent->s.modelGhoul2) { case G2_MODELPART_HEAD: mass = 0.08f; bounce = 1.4f; @@ -3320,15 +2734,13 @@ void LimbThink( gentity_t *ent ) break; } - if (ent->speed < level.time) - { + if (ent->speed < level.time) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; } - if (ent->genericValue5 <= level.time) - { //this will be every frame by standard, but we want to compensate in case sv_fps is not 20. + if (ent->genericValue5 <= level.time) { // this will be every frame by standard, but we want to compensate in case sv_fps is not 20. G_RunExPhys(ent, gravity, mass, bounce, qtrue, NULL, 0); ent->genericValue5 = level.time + 50; } @@ -3336,69 +2748,53 @@ void LimbThink( gentity_t *ent ) ent->nextthink = level.time; } -extern qboolean BG_GetRootSurfNameWithVariant( void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize ); +extern qboolean BG_GetRootSurfNameWithVariant(void *ghoul2, const char *rootSurfName, char *returnSurfName, int returnSize); -void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, qboolean postDeath ) -{ - vec3_t newPoint, dir, vel; +void G_Dismember(gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, float limbRollBase, float limbPitchBase, int deathAnim, qboolean postDeath) { + vec3_t newPoint, dir, vel; gentity_t *limb; - char limbName[MAX_QPATH]; - char stubName[MAX_QPATH]; - char stubCapName[MAX_QPATH]; - - if (limbType == G2_MODELPART_HEAD) - { - Q_strncpyz( limbName , "head", sizeof( limbName ) ); - Q_strncpyz( stubCapName, "torso_cap_head", sizeof( stubCapName ) ); - } - else if (limbType == G2_MODELPART_WAIST) - { - Q_strncpyz( limbName, "torso", sizeof( limbName ) ); - Q_strncpyz( stubCapName, "hips_cap_torso", sizeof( stubCapName ) ); - } - else if (limbType == G2_MODELPART_LARM) - { - BG_GetRootSurfNameWithVariant( ent->ghoul2, "l_arm", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "torso", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_arm", stubName ); - } - else if (limbType == G2_MODELPART_RARM) - { - BG_GetRootSurfNameWithVariant( ent->ghoul2, "r_arm", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "torso", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_arm", stubName ); - } - else if (limbType == G2_MODELPART_RHAND) - { - BG_GetRootSurfNameWithVariant( ent->ghoul2, "r_hand", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "r_arm", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_hand", stubName ); - } - else if (limbType == G2_MODELPART_LLEG) - { - BG_GetRootSurfNameWithVariant( ent->ghoul2, "l_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_l_leg", stubName ); - } - else if (limbType == G2_MODELPART_RLEG) - { - BG_GetRootSurfNameWithVariant( ent->ghoul2, "r_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_leg", stubName ); - } - else - {//umm... just default to the right leg, I guess (same as on client) - BG_GetRootSurfNameWithVariant( ent->ghoul2, "r_leg", limbName, sizeof(limbName) ); - BG_GetRootSurfNameWithVariant( ent->ghoul2, "hips", stubName, sizeof(stubName) ); - Com_sprintf( stubCapName, sizeof( stubCapName), "%s_cap_r_leg", stubName ); - } - - if (ent->ghoul2 && limbName[0] && trap->G2API_GetSurfaceRenderStatus(ent->ghoul2, 0, limbName)) - { //is it already off? If so there's no reason to be doing it again, so get out of here. + char limbName[MAX_QPATH]; + char stubName[MAX_QPATH]; + char stubCapName[MAX_QPATH]; + + if (limbType == G2_MODELPART_HEAD) { + Q_strncpyz(limbName, "head", sizeof(limbName)); + Q_strncpyz(stubCapName, "torso_cap_head", sizeof(stubCapName)); + } else if (limbType == G2_MODELPART_WAIST) { + Q_strncpyz(limbName, "torso", sizeof(limbName)); + Q_strncpyz(stubCapName, "hips_cap_torso", sizeof(stubCapName)); + } else if (limbType == G2_MODELPART_LARM) { + BG_GetRootSurfNameWithVariant(ent->ghoul2, "l_arm", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "torso", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_arm", stubName); + } else if (limbType == G2_MODELPART_RARM) { + BG_GetRootSurfNameWithVariant(ent->ghoul2, "r_arm", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "torso", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_arm", stubName); + } else if (limbType == G2_MODELPART_RHAND) { + BG_GetRootSurfNameWithVariant(ent->ghoul2, "r_hand", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "r_arm", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_hand", stubName); + } else if (limbType == G2_MODELPART_LLEG) { + BG_GetRootSurfNameWithVariant(ent->ghoul2, "l_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_l_leg", stubName); + } else if (limbType == G2_MODELPART_RLEG) { + BG_GetRootSurfNameWithVariant(ent->ghoul2, "r_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_leg", stubName); + } else { // umm... just default to the right leg, I guess (same as on client) + BG_GetRootSurfNameWithVariant(ent->ghoul2, "r_leg", limbName, sizeof(limbName)); + BG_GetRootSurfNameWithVariant(ent->ghoul2, "hips", stubName, sizeof(stubName)); + Com_sprintf(stubCapName, sizeof(stubCapName), "%s_cap_r_leg", stubName); + } + + if (ent->ghoul2 && limbName[0] && + trap->G2API_GetSurfaceRenderStatus(ent->ghoul2, 0, limbName)) { // is it already off? If so there's no reason to be doing it again, so get out of here. return; } - VectorCopy( point, newPoint ); + VectorCopy(point, newPoint); limb = G_Spawn(); limb->classname = "playerlimb"; @@ -3409,8 +2805,8 @@ void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, } */ - G_SetOrigin( limb, newPoint ); - VectorCopy( newPoint, limb->s.pos.trBase ); + G_SetOrigin(limb, newPoint); + VectorCopy(newPoint, limb->s.pos.trBase); limb->think = LimbThink; limb->touch = LimbTouch; limb->speed = level.time + Q_irand(8000, 16000); @@ -3420,8 +2816,8 @@ void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, limb->clipmask = MASK_SOLID; limb->r.contents = CONTENTS_TRIGGER; limb->physicsObject = qtrue; - VectorSet( limb->r.mins, -6.0f, -6.0f, -3.0f ); - VectorSet( limb->r.maxs, 6.0f, 6.0f, 6.0f ); + VectorSet(limb->r.mins, -6.0f, -6.0f, -3.0f); + VectorSet(limb->r.maxs, 6.0f, 6.0f, 6.0f); limb->s.g2radius = 200; @@ -3429,97 +2825,83 @@ void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, limb->s.weapon = G2_MODEL_PART; limb->s.modelGhoul2 = limbType; limb->s.modelindex = ent->s.number; - if (!ent->client) - { + if (!ent->client) { limb->s.modelindex = -1; limb->s.otherEntityNum2 = ent->s.number; } VectorClear(limb->s.apos.trDelta); - if (ent->client) - { + if (ent->client) { VectorCopy(ent->client->ps.viewangles, limb->r.currentAngles); VectorCopy(ent->client->ps.viewangles, limb->s.apos.trBase); - } - else - { + } else { VectorCopy(ent->r.currentAngles, limb->r.currentAngles); VectorCopy(ent->r.currentAngles, limb->s.apos.trBase); } - //Set up the ExPhys values for the entity. + // Set up the ExPhys values for the entity. limb->epGravFactor = 0; VectorClear(limb->epVelocity); - VectorSubtract( point, ent->r.currentOrigin, dir ); - VectorNormalize( dir ); - if (ent->client) - { + VectorSubtract(point, ent->r.currentOrigin, dir); + VectorNormalize(dir); + if (ent->client) { VectorCopy(ent->client->ps.velocity, vel); - } - else - { + } else { VectorCopy(ent->s.pos.trDelta, vel); } - VectorMA( vel, 80, dir, limb->epVelocity ); + VectorMA(vel, 80, dir, limb->epVelocity); - //add some vertical velocity - if (limbType == G2_MODELPART_HEAD || - limbType == G2_MODELPART_WAIST) - { + // add some vertical velocity + if (limbType == G2_MODELPART_HEAD || limbType == G2_MODELPART_WAIST) { limb->epVelocity[2] += 10; } - if (enemy && enemy->client && ent && ent != enemy && ent->s.number != enemy->s.number && - enemy->client->ps.weapon == WP_SABER && enemy->client->olderIsValid && - (level.time - enemy->client->lastSaberStorageTime) < 200) - { //The enemy has valid saber positions between this and last frame. Use them to factor in direction of the limb. + if (enemy && enemy->client && ent && ent != enemy && ent->s.number != enemy->s.number && enemy->client->ps.weapon == WP_SABER && + enemy->client->olderIsValid && + (level.time - enemy->client->lastSaberStorageTime) < + 200) { // The enemy has valid saber positions between this and last frame. Use them to factor in direction of the limb. vec3_t dif; float totalDistance; const float distScale = 1.2f; - //scale down the initial velocity first, which is based on the speed of the limb owner. - //ExPhys object velocity operates on a slightly different scale than Q3-based physics velocity. + // scale down the initial velocity first, which is based on the speed of the limb owner. + // ExPhys object velocity operates on a slightly different scale than Q3-based physics velocity. VectorScale(limb->epVelocity, 0.4f, limb->epVelocity); VectorSubtract(enemy->client->lastSaberBase_Always, enemy->client->olderSaberBase, dif); totalDistance = VectorNormalize(dif); - VectorScale(dif, totalDistance*distScale, dif); + VectorScale(dif, totalDistance * distScale, dif); VectorAdd(limb->epVelocity, dif, limb->epVelocity); - if (ent->client && (ent->client->ps.torsoTimer > 0 || !BG_InDeathAnim(ent->client->ps.torsoAnim))) - { //if he's done with his death anim we don't actually want the limbs going far + if (ent->client && (ent->client->ps.torsoTimer > 0 || + !BG_InDeathAnim(ent->client->ps.torsoAnim))) { // if he's done with his death anim we don't actually want the limbs going far vec3_t preVel; VectorCopy(limb->epVelocity, preVel); preVel[2] = 0; totalDistance = VectorNormalize(preVel); - if (totalDistance < 40.0f) - { - float mAmt = 40.0f;//60.0f/totalDistance; + if (totalDistance < 40.0f) { + float mAmt = 40.0f; // 60.0f/totalDistance; - limb->epVelocity[0] = preVel[0]*mAmt; - limb->epVelocity[1] = preVel[1]*mAmt; + limb->epVelocity[0] = preVel[0] * mAmt; + limb->epVelocity[1] = preVel[1] * mAmt; } - } - else if (ent->client) - { + } else if (ent->client) { VectorScale(limb->epVelocity, 0.3f, limb->epVelocity); } } - if (ent->s.eType == ET_NPC && ent->ghoul2 && limbName[0] && stubCapName[0]) - { //if it's an npc remove these surfs on the server too. For players we don't even care cause there's no further dismemberment after death. + if (ent->s.eType == ET_NPC && ent->ghoul2 && limbName[0] && stubCapName[0]) { // if it's an npc remove these surfs on the server too. For players we don't + // even care cause there's no further dismemberment after death. trap->G2API_SetSurfaceOnOff(ent->ghoul2, limbName, 0x00000100); trap->G2API_SetSurfaceOnOff(ent->ghoul2, stubCapName, 0); } - if ( level.gametype >= GT_TEAM && ent->s.eType != ET_NPC ) - {//Team game - switch ( ent->client->sess.sessionTeam ) - { + if (level.gametype >= GT_TEAM && ent->s.eType != ET_NPC) { // Team game + switch (ent->client->sess.sessionTeam) { case TEAM_RED: limb->s.customRGBA[0] = 255; limb->s.customRGBA[1] = 0; @@ -3539,38 +2921,32 @@ void G_Dismember( gentity_t *ent, gentity_t *enemy, vec3_t point, int limbType, limb->s.customRGBA[3] = ent->s.customRGBA[3]; break; } - } - else - {//FFA + } else { // FFA limb->s.customRGBA[0] = ent->s.customRGBA[0]; limb->s.customRGBA[1] = ent->s.customRGBA[1]; limb->s.customRGBA[2] = ent->s.customRGBA[2]; limb->s.customRGBA[3] = ent->s.customRGBA[3]; } - trap->LinkEntity( (sharedEntity_t *)limb ); + trap->LinkEntity((sharedEntity_t *)limb); } -void DismembermentTest(gentity_t *self) -{ +void DismembermentTest(gentity_t *self) { int sect = G2_MODELPART_HEAD; vec3_t boltPoint; - while (sect <= G2_MODELPART_RLEG) - { + while (sect <= G2_MODELPART_RLEG) { G_GetDismemberBolt(self, boltPoint, sect); - G_Dismember( self, self, boltPoint, sect, 90, 0, BOTH_DEATH1, qfalse ); + G_Dismember(self, self, boltPoint, sect, 90, 0, BOTH_DEATH1, qfalse); sect++; } } -void DismembermentByNum(gentity_t *self, int num) -{ +void DismembermentByNum(gentity_t *self, int num) { int sect = G2_MODELPART_HEAD; vec3_t boltPoint; - switch (num) - { + switch (num) { case 0: sect = G2_MODELPART_HEAD; break; @@ -3597,84 +2973,59 @@ void DismembermentByNum(gentity_t *self, int num) } G_GetDismemberBolt(self, boltPoint, sect); - G_Dismember( self, self, boltPoint, sect, 90, 0, BOTH_DEATH1, qfalse ); + G_Dismember(self, self, boltPoint, sect, 90, 0, BOTH_DEATH1, qfalse); } -int G_GetHitQuad( gentity_t *self, vec3_t hitloc ) -{ - vec3_t diff, fwdangles={0,0,0}, right; +int G_GetHitQuad(gentity_t *self, vec3_t hitloc) { + vec3_t diff, fwdangles = {0, 0, 0}, right; vec3_t clEye; float rightdot; float zdiff; int hitLoc = gPainHitLoc; - if (self->client) - { + if (self->client) { VectorCopy(self->client->ps.origin, clEye); clEye[2] += self->client->ps.viewheight; - } - else - { + } else { VectorCopy(self->s.pos.trBase, clEye); clEye[2] += 16; } - VectorSubtract( hitloc, clEye, diff ); + VectorSubtract(hitloc, clEye, diff); diff[2] = 0; - VectorNormalize( diff ); + VectorNormalize(diff); - if (self->client) - { + if (self->client) { fwdangles[1] = self->client->ps.viewangles[1]; - } - else - { + } else { fwdangles[1] = self->s.apos.trBase[1]; } // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); rightdot = DotProduct(right, diff); zdiff = hitloc[2] - clEye[2]; - if ( zdiff > 0 ) - { - if ( rightdot > 0.3 ) - { + if (zdiff > 0) { + if (rightdot > 0.3) { hitLoc = G2_MODELPART_RARM; - } - else if ( rightdot < -0.3 ) - { + } else if (rightdot < -0.3) { hitLoc = G2_MODELPART_LARM; - } - else - { + } else { hitLoc = G2_MODELPART_HEAD; } - } - else if ( zdiff > -20 ) - { - if ( rightdot > 0.1 ) - { + } else if (zdiff > -20) { + if (rightdot > 0.1) { hitLoc = G2_MODELPART_RARM; - } - else if ( rightdot < -0.1 ) - { + } else if (rightdot < -0.1) { hitLoc = G2_MODELPART_LARM; - } - else - { + } else { hitLoc = G2_MODELPART_HEAD; } - } - else - { - if ( rightdot >= 0 ) - { + } else { + if (rightdot >= 0) { hitLoc = G2_MODELPART_RLEG; - } - else - { + } else { hitLoc = G2_MODELPART_LLEG; } } @@ -3686,8 +3037,7 @@ int gGAvoidDismember = 0; void UpdateClientRenderBolts(gentity_t *self, vec3_t renderOrigin, vec3_t renderAngles); -qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod ) -{ +qboolean G_GetHitLocFromSurfName(gentity_t *ent, const char *surfName, int *hitLoc, vec3_t point, vec3_t dir, vec3_t bladeDir, int mod) { qboolean dismember = qfalse; int actualTime; int kneeLBolt = -1; @@ -3699,35 +3049,25 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit *hitLoc = HL_NONE; - if ( !surfName || !surfName[0] ) - { + if (!surfName || !surfName[0]) { return qfalse; } - if( !ent->client ) - { + if (!ent->client) { return qfalse; } - if (!point) - { + if (!point) { return qfalse; } - if ( ent->client - && ( ent->client->NPC_class == CLASS_R2D2 - || ent->client->NPC_class == CLASS_R5D2 - || ent->client->NPC_class == CLASS_GONK - || ent->client->NPC_class == CLASS_MOUSE - || ent->client->NPC_class == CLASS_SENTRY - || ent->client->NPC_class == CLASS_INTERROGATOR - || ent->client->NPC_class == CLASS_PROBE ) ) - {//we don't care about per-surface hit-locations or dismemberment for these guys + if (ent->client && (ent->client->NPC_class == CLASS_R2D2 || ent->client->NPC_class == CLASS_R5D2 || ent->client->NPC_class == CLASS_GONK || + ent->client->NPC_class == CLASS_MOUSE || ent->client->NPC_class == CLASS_SENTRY || ent->client->NPC_class == CLASS_INTERROGATOR || + ent->client->NPC_class == CLASS_PROBE)) { // we don't care about per-surface hit-locations or dismemberment for these guys return qfalse; } - if (ent->localAnimIndex <= 1) - { //humanoid + if (ent->localAnimIndex <= 1) { // humanoid handLBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*l_hand"); handRBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*r_hand"); kneeLBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*hips_l_knee"); @@ -3736,149 +3076,95 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit footRBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*r_leg_foot"); } - if ( ent->client && (ent->client->NPC_class == CLASS_ATST) ) - { - //FIXME: almost impossible to hit these... perhaps we should + if (ent->client && (ent->client->NPC_class == CLASS_ATST)) { + // FIXME: almost impossible to hit these... perhaps we should // check for splashDamage and do radius damage to these parts? // Or, if we ever get bbox G2 traces, that may fix it, too - if (!Q_stricmp("head_light_blaster_cann",surfName)) - { + if (!Q_stricmp("head_light_blaster_cann", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("head_concussion_charger",surfName)) - { + } else if (!Q_stricmp("head_concussion_charger", surfName)) { *hitLoc = HL_ARM_RT; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK1) ) - { - if (!Q_stricmp("l_arm",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK1)) { + if (!Q_stricmp("l_arm", surfName)) { *hitLoc = HL_ARM_LT; - } - else if (!Q_stricmp("r_arm",surfName)) - { + } else if (!Q_stricmp("r_arm", surfName)) { *hitLoc = HL_ARM_RT; - } - else if (!Q_stricmp("torso_front",surfName)) - { + } else if (!Q_stricmp("torso_front", surfName)) { *hitLoc = HL_CHEST; - } - else if (!Q_stricmp("torso_tube1",surfName)) - { + } else if (!Q_stricmp("torso_tube1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_tube2",surfName)) - { + } else if (!Q_stricmp("torso_tube2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_tube3",surfName)) - { + } else if (!Q_stricmp("torso_tube3", surfName)) { *hitLoc = HL_GENERIC3; - } - else if (!Q_stricmp("torso_tube4",surfName)) - { + } else if (!Q_stricmp("torso_tube4", surfName)) { *hitLoc = HL_GENERIC4; - } - else if (!Q_stricmp("torso_tube5",surfName)) - { + } else if (!Q_stricmp("torso_tube5", surfName)) { *hitLoc = HL_GENERIC5; - } - else if (!Q_stricmp("torso_tube6",surfName)) - { + } else if (!Q_stricmp("torso_tube6", surfName)) { *hitLoc = HL_GENERIC6; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_MARK2) ) - { - if (!Q_stricmp("torso_canister1",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_MARK2)) { + if (!Q_stricmp("torso_canister1", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_canister2",surfName)) - { + } else if (!Q_stricmp("torso_canister2", surfName)) { *hitLoc = HL_GENERIC2; - } - else if (!Q_stricmp("torso_canister3",surfName)) - { + } else if (!Q_stricmp("torso_canister3", surfName)) { *hitLoc = HL_GENERIC3; } - return(qfalse); - } - else if ( ent->client && (ent->client->NPC_class == CLASS_GALAKMECH) ) - { - if (!Q_stricmp("torso_antenna",surfName)||!Q_stricmp("torso_antenna_base",surfName)) - { + return (qfalse); + } else if (ent->client && (ent->client->NPC_class == CLASS_GALAKMECH)) { + if (!Q_stricmp("torso_antenna", surfName) || !Q_stricmp("torso_antenna_base", surfName)) { *hitLoc = HL_GENERIC1; - } - else if (!Q_stricmp("torso_shield",surfName)) - { + } else if (!Q_stricmp("torso_shield", surfName)) { *hitLoc = HL_GENERIC2; - } - else - { + } else { *hitLoc = HL_CHEST; } - return(qfalse); + return (qfalse); } - //FIXME: check the hitLoc and hitDir against the cap tag for the place - //where the split will be- if the hit dir is roughly perpendicular to - //the direction of the cap, then the split is allowed, otherwise we - //hit it at the wrong angle and should not dismember... + // FIXME: check the hitLoc and hitDir against the cap tag for the place + // where the split will be- if the hit dir is roughly perpendicular to + // the direction of the cap, then the split is allowed, otherwise we + // hit it at the wrong angle and should not dismember... actualTime = level.time; - if ( !Q_strncmp( "hips", surfName, 4 ) ) - {//FIXME: test properly for legs + if (!Q_strncmp("hips", surfName, 4)) { // FIXME: test properly for legs *hitLoc = HL_WAIST; - if ( ent->client != NULL && ent->ghoul2 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - if (kneeLBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, kneeLBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (ent->client != NULL && ent->ghoul2) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + if (kneeLBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, kneeLBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_LT; } } - if (*hitLoc == HL_WAIST) - { - if (kneeRBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, kneeRBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the knee + if (*hitLoc == HL_WAIST) { + if (kneeRBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, kneeRBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the knee *hitLoc = HL_LEG_RT; } } } - } - } - else if ( !Q_strncmp( "torso", surfName, 5 ) ) - { - if ( !ent->client ) - { - *hitLoc = HL_CHEST; - } - else - { - vec3_t t_fwd, t_rt, t_up, dirToImpact; + } + } else if (!Q_strncmp("torso", surfName, 5)) { + if (!ent->client) { + *hitLoc = HL_CHEST; + } else { + vec3_t t_fwd, t_rt, t_up, dirToImpact; float frontSide, rightSide, upSide; - AngleVectors( ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up ); + AngleVectors(ent->client->renderInfo.torsoAngles, t_fwd, t_rt, t_up); - if (ent->client->renderInfo.boltValidityTime != level.time) - { + if (ent->client->renderInfo.boltValidityTime != level.time) { vec3_t renderAng; renderAng[0] = 0; @@ -3888,159 +3174,103 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit UpdateClientRenderBolts(ent, ent->client->ps.origin, renderAng); } - VectorSubtract( point, ent->client->renderInfo.torsoPoint, dirToImpact ); - frontSide = DotProduct( t_fwd, dirToImpact ); - rightSide = DotProduct( t_rt, dirToImpact ); - upSide = DotProduct( t_up, dirToImpact ); - if ( upSide < -10 ) - {//hit at waist + VectorSubtract(point, ent->client->renderInfo.torsoPoint, dirToImpact); + frontSide = DotProduct(t_fwd, dirToImpact); + rightSide = DotProduct(t_rt, dirToImpact); + upSide = DotProduct(t_up, dirToImpact); + if (upSide < -10) { // hit at waist *hitLoc = HL_WAIST; - } - else - {//hit on upper torso - if ( rightSide > 4 ) - { + } else { // hit on upper torso + if (rightSide > 4) { *hitLoc = HL_ARM_RT; - } - else if ( rightSide < -4 ) - { + } else if (rightSide < -4) { *hitLoc = HL_ARM_LT; - } - else if ( rightSide > 2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide > 2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_RT; - } - else - { + } else { *hitLoc = HL_BACK_RT; } - } - else if ( rightSide < -2 ) - { - if ( frontSide > 0 ) - { + } else if (rightSide < -2) { + if (frontSide > 0) { *hitLoc = HL_CHEST_LT; - } - else - { + } else { *hitLoc = HL_BACK_LT; } - } - else if ( upSide > -3 && mod == MOD_SABER ) - { + } else if (upSide > -3 && mod == MOD_SABER) { *hitLoc = HL_HEAD; - } - else if ( frontSide > 0 ) - { + } else if (frontSide > 0) { *hitLoc = HL_CHEST; - } - else - { + } else { *hitLoc = HL_BACK; } } } - } - else if ( !Q_strncmp( "head", surfName, 4 ) ) - { + } else if (!Q_strncmp("head", surfName, 4)) { *hitLoc = HL_HEAD; - } - else if ( !Q_strncmp( "r_arm", surfName, 5 ) ) - { + } else if (!Q_strncmp("r_arm", surfName, 5)) { *hitLoc = HL_ARM_RT; - if ( ent->client != NULL && ent->ghoul2 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - if (handRBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, handRBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + if (handRBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, handRBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_RT; } } } - } - else if ( !Q_strncmp( "l_arm", surfName, 5 ) ) - { + } else if (!Q_strncmp("l_arm", surfName, 5)) { *hitLoc = HL_ARM_LT; - if ( ent->client != NULL && ent->ghoul2 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - if (handLBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, handLBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//actually hit the hand + if (ent->client != NULL && ent->ghoul2) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + if (handLBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, handLBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 256) { // actually hit the hand *hitLoc = HL_HAND_LT; } } } - } - else if ( !Q_strncmp( "r_leg", surfName, 5 ) ) - { + } else if (!Q_strncmp("r_leg", surfName, 5)) { *hitLoc = HL_LEG_RT; - if ( ent->client != NULL && ent->ghoul2 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - if (footRBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, footRBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + if (footRBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, footRBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_RT; } } } - } - else if ( !Q_strncmp( "l_leg", surfName, 5 ) ) - { + } else if (!Q_strncmp("l_leg", surfName, 5)) { *hitLoc = HL_LEG_LT; - if ( ent->client != NULL && ent->ghoul2 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - if (footLBolt>=0) - { - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, footLBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - if ( DistanceSquared( point, tagOrg ) < 100 ) - {//actually hit the foot + if (ent->client != NULL && ent->ghoul2) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + if (footLBolt >= 0) { + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, footLBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + if (DistanceSquared(point, tagOrg) < 100) { // actually hit the foot *hitLoc = HL_FOOT_LT; } } } - } - else if ( !Q_strncmp( "r_hand", surfName, 6 ) || !Q_strncmp( "w_", surfName, 2 ) ) - {//right hand or weapon + } else if (!Q_strncmp("r_hand", surfName, 6) || !Q_strncmp("w_", surfName, 2)) { // right hand or weapon *hitLoc = HL_HAND_RT; - } - else if ( !Q_strncmp( "l_hand", surfName, 6 ) ) - { + } else if (!Q_strncmp("l_hand", surfName, 6)) { *hitLoc = HL_HAND_LT; } /* @@ -4052,84 +3282,72 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit #endif //_DEBUG */ - //if ( g_dismemberment->integer >= 11381138 || !ent->client->dismembered ) - if (g_dismember.integer == 100) - { //full probability... - if ( ent->client && ent->client->NPC_class == CLASS_PROTOCOL ) - { + // if ( g_dismemberment->integer >= 11381138 || !ent->client->dismembered ) + if (g_dismember.integer == 100) { // full probability... + if (ent->client && ent->client->NPC_class == CLASS_PROTOCOL) { dismember = qtrue; - } - else if ( dir && (dir[0] || dir[1] || dir[2]) && - bladeDir && (bladeDir[0] || bladeDir[1] || bladeDir[2]) ) - {//we care about direction (presumably for dismemberment) - //if ( g_dismemberProbabilities->value<=0.0f||G_Dismemberable( ent, *hitLoc ) ) - if (1) //Fix me? - {//either we don't care about probabilties or the probability let us continue + } else if (dir && (dir[0] || dir[1] || dir[2]) && bladeDir && + (bladeDir[0] || bladeDir[1] || bladeDir[2])) { // we care about direction (presumably for dismemberment) + // if ( g_dismemberProbabilities->value<=0.0f||G_Dismemberable( ent, *hitLoc ) ) + if (1) // Fix me? + { // either we don't care about probabilties or the probability let us continue char *tagName = NULL; - float aoa = 0.5f; - //dir must be roughly perpendicular to the hitLoc's cap bolt - switch ( *hitLoc ) - { - case HL_LEG_RT: - tagName = "*hips_cap_r_leg"; - break; - case HL_LEG_LT: - tagName = "*hips_cap_l_leg"; - break; - case HL_WAIST: - tagName = "*hips_cap_torso"; - aoa = 0.25f; - break; - case HL_CHEST_RT: - case HL_ARM_RT: - case HL_BACK_LT: - tagName = "*torso_cap_r_arm"; - break; - case HL_CHEST_LT: - case HL_ARM_LT: - case HL_BACK_RT: - tagName = "*torso_cap_l_arm"; - break; - case HL_HAND_RT: - tagName = "*r_arm_cap_r_hand"; - break; - case HL_HAND_LT: - tagName = "*l_arm_cap_l_hand"; - break; - case HL_HEAD: - tagName = "*torso_cap_head"; - aoa = 0.25f; - break; - case HL_CHEST: - case HL_BACK: - case HL_FOOT_RT: - case HL_FOOT_LT: - default: - //no dismemberment possible with these, so no checks needed - break; + float aoa = 0.5f; + // dir must be roughly perpendicular to the hitLoc's cap bolt + switch (*hitLoc) { + case HL_LEG_RT: + tagName = "*hips_cap_r_leg"; + break; + case HL_LEG_LT: + tagName = "*hips_cap_l_leg"; + break; + case HL_WAIST: + tagName = "*hips_cap_torso"; + aoa = 0.25f; + break; + case HL_CHEST_RT: + case HL_ARM_RT: + case HL_BACK_LT: + tagName = "*torso_cap_r_arm"; + break; + case HL_CHEST_LT: + case HL_ARM_LT: + case HL_BACK_RT: + tagName = "*torso_cap_l_arm"; + break; + case HL_HAND_RT: + tagName = "*r_arm_cap_r_hand"; + break; + case HL_HAND_LT: + tagName = "*l_arm_cap_l_hand"; + break; + case HL_HEAD: + tagName = "*torso_cap_head"; + aoa = 0.25f; + break; + case HL_CHEST: + case HL_BACK: + case HL_FOOT_RT: + case HL_FOOT_LT: + default: + // no dismemberment possible with these, so no checks needed + break; } - if ( tagName ) - { - int tagBolt = trap->G2API_AddBolt( ent->ghoul2, 0, tagName ); - if ( tagBolt != -1 ) - { - mdxaBone_t boltMatrix; - vec3_t tagOrg, tagDir, angles; - - VectorSet( angles, 0, ent->r.currentAngles[YAW], 0 ); - trap->G2API_GetBoltMatrix( ent->ghoul2, 0, tagBolt, - &boltMatrix, angles, ent->r.currentOrigin, - actualTime, NULL, ent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, tagOrg ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, tagDir ); - if ( DistanceSquared( point, tagOrg ) < 256 ) - {//hit close - float dot = DotProduct( dir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//hit roughly perpendicular - dot = DotProduct( bladeDir, tagDir ); - if ( dot < aoa && dot > -aoa ) - {//blade was roughly perpendicular + if (tagName) { + int tagBolt = trap->G2API_AddBolt(ent->ghoul2, 0, tagName); + if (tagBolt != -1) { + mdxaBone_t boltMatrix; + vec3_t tagOrg, tagDir, angles; + + VectorSet(angles, 0, ent->r.currentAngles[YAW], 0); + trap->G2API_GetBoltMatrix(ent->ghoul2, 0, tagBolt, &boltMatrix, angles, ent->r.currentOrigin, actualTime, NULL, ent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, tagOrg); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, tagDir); + if (DistanceSquared(point, tagOrg) < 256) { // hit close + float dot = DotProduct(dir, tagDir); + if (dot < aoa && dot > -aoa) { // hit roughly perpendicular + dot = DotProduct(bladeDir, tagDir); + if (dot < aoa && dot > -aoa) { // blade was roughly perpendicular dismember = qtrue; } } @@ -4137,83 +3355,65 @@ qboolean G_GetHitLocFromSurfName( gentity_t *ent, const char *surfName, int *hit } } } - } - else - { //hmm, no direction supplied. + } else { // hmm, no direction supplied. dismember = qtrue; } } return dismember; } -void G_CheckForDismemberment(gentity_t *ent, gentity_t *enemy, vec3_t point, int damage, int deathAnim, qboolean postDeath) -{ +void G_CheckForDismemberment(gentity_t *ent, gentity_t *enemy, vec3_t point, int damage, int deathAnim, qboolean postDeath) { int hitLoc = -1, hitLocUse = -1; vec3_t boltPoint; int dismember = g_dismember.integer; - if (ent->localAnimIndex > 1) - { - if (!ent->NPC) - { + if (ent->localAnimIndex > 1) { + if (!ent->NPC) { return; } - if (ent->client->NPC_class != CLASS_PROTOCOL) - { //this is the only non-humanoid allowed to do dismemberment. + if (ent->client->NPC_class != CLASS_PROTOCOL) { // this is the only non-humanoid allowed to do dismemberment. return; } } - if (!dismember) - { + if (!dismember) { return; } - if (gGAvoidDismember == 1) - { + if (gGAvoidDismember == 1) { return; } - if (gGAvoidDismember != 2) - { //this means do the dismemberment regardless of randomness and damage - if (Q_irand(0, 100) > dismember) - { + if (gGAvoidDismember != 2) { // this means do the dismemberment regardless of randomness and damage + if (Q_irand(0, 100) > dismember) { return; } - if (damage < 5) - { + if (damage < 5) { return; } } - if (gGAvoidDismember == 2) - { + if (gGAvoidDismember == 2) { hitLoc = HL_HAND_RT; - } - else - { - if (d_saberGhoul2Collision.integer && ent->client && ent->client->g2LastSurfaceTime == level.time) - { + } else { + if (d_saberGhoul2Collision.integer && ent->client && ent->client->g2LastSurfaceTime == level.time) { char hitSurface[MAX_QPATH]; trap->G2API_GetSurfaceName(ent->ghoul2, ent->client->g2LastSurfaceHit, 0, hitSurface); - if (hitSurface[0]) - { + if (hitSurface[0]) { G_GetHitLocFromSurfName(ent, hitSurface, &hitLoc, point, vec3_origin, vec3_origin, MOD_UNKNOWN); } } - if (hitLoc == -1) - { - hitLoc = G_GetHitLocation( ent, point ); + if (hitLoc == -1) { + hitLoc = G_GetHitLocation(ent, point); } } - switch(hitLoc) - { + switch (hitLoc) { case HL_FOOT_RT: case HL_LEG_RT: hitLocUse = G2_MODELPART_RLEG; @@ -4253,76 +3453,64 @@ void G_CheckForDismemberment(gentity_t *ent, gentity_t *enemy, vec3_t point, int break; } - if (hitLocUse == -1) - { + if (hitLocUse == -1) { return; } - if (ent->client) - { + if (ent->client) { G_GetDismemberBolt(ent, boltPoint, hitLocUse); - if ( g_austrian.integer - && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) ) - { - G_LogPrintf( "Duel Dismemberment: %s dismembered at %s\n", ent->client->pers.netname, hitLocName[hitLoc] ); + if (g_austrian.integer && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL)) { + G_LogPrintf("Duel Dismemberment: %s dismembered at %s\n", ent->client->pers.netname, hitLocName[hitLoc]); } - } - else - { + } else { G_GetDismemberLoc(ent, boltPoint, hitLocUse); } G_Dismember(ent, enemy, boltPoint, hitLocUse, 90, 0, deathAnim, postDeath); } -void G_LocationBasedDamageModifier(gentity_t *ent, vec3_t point, int mod, int dflags, int *damage) -{ +void G_LocationBasedDamageModifier(gentity_t *ent, vec3_t point, int mod, int dflags, int *damage) { int hitLoc = -1; - if (!g_locationBasedDamage.integer) - { //then leave it alone + if (!g_locationBasedDamage.integer) { // then leave it alone return; } - if ( (dflags&DAMAGE_NO_HIT_LOC) ) - { //then leave it alone + if ((dflags & DAMAGE_NO_HIT_LOC)) { // then leave it alone return; } - if (mod == MOD_SABER && *damage <= 1) - { //don't bother for idle damage + if (mod == MOD_SABER && *damage <= 1) { // don't bother for idle damage return; } - if (!point) - { + if (!point) { return; } - if ( ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - {//no location-based damage on vehicles + if (ent->client && ent->client->NPC_class == CLASS_VEHICLE) { // no location-based damage on vehicles return; } - if ((d_saberGhoul2Collision.integer && ent->client && ent->client->g2LastSurfaceTime == level.time && mod == MOD_SABER) || //using ghoul2 collision? Then if the mod is a saber we should have surface data from the last hit (unless thrown). - (d_projectileGhoul2Collision.integer && ent->client && ent->client->g2LastSurfaceTime == level.time)) //It's safe to assume we died from the projectile that just set our surface index. So, go ahead and use that as the surf I guess. + if ((d_saberGhoul2Collision.integer && ent->client && ent->client->g2LastSurfaceTime == level.time && + mod == MOD_SABER) || // using ghoul2 collision? Then if the mod is a saber we should have surface data from the last hit (unless thrown). + (d_projectileGhoul2Collision.integer && ent->client && + ent->client->g2LastSurfaceTime == + level.time)) // It's safe to assume we died from the projectile that just set our surface index. So, go ahead and use that as the surf I guess. { char hitSurface[MAX_QPATH]; trap->G2API_GetSurfaceName(ent->ghoul2, ent->client->g2LastSurfaceHit, 0, hitSurface); - if (hitSurface[0]) - { + if (hitSurface[0]) { G_GetHitLocFromSurfName(ent, hitSurface, &hitLoc, point, vec3_origin, vec3_origin, MOD_UNKNOWN); } } - if (hitLoc == -1) - { - hitLoc = G_GetHitLocation( ent, point ); + if (hitLoc == -1) { + hitLoc = G_GetHitLocation(ent, point); } - switch (hitLoc) - { + switch (hitLoc) { case HL_FOOT_RT: case HL_FOOT_LT: *damage *= 0.5; @@ -4338,7 +3526,7 @@ void G_LocationBasedDamageModifier(gentity_t *ent, vec3_t point, int mod, int df case HL_CHEST_RT: case HL_CHEST_LT: case HL_CHEST: - break; //normal damage + break; // normal damage case HL_ARM_RT: case HL_ARM_LT: *damage *= 0.85; @@ -4351,7 +3539,7 @@ void G_LocationBasedDamageModifier(gentity_t *ent, vec3_t point, int mod, int df *damage *= 1.3; break; default: - break; //do nothing then + break; // do nothing then } } /* @@ -4360,17 +3548,14 @@ rww - end dismemberment/lbd =================================== */ -qboolean G_ThereIsAMaster(void) -{ +qboolean G_ThereIsAMaster(void) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->ps.isJediMaster) - { + if (ent && ent->client && ent->client->ps.isJediMaster) { return qtrue; } @@ -4380,10 +3565,8 @@ qboolean G_ThereIsAMaster(void) return qfalse; } -void G_Knockdown( gentity_t *victim ) -{ - if ( victim && victim->client && BG_KnockDownable(&victim->client->ps) ) - { +void G_Knockdown(gentity_t *victim) { + if (victim && victim->client && BG_KnockDownable(&victim->client->ps)) { victim->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; victim->client->ps.forceDodgeAnim = 0; victim->client->ps.forceHandExtendTime = level.time + 1100; @@ -4422,40 +3605,33 @@ int gPainMOD = 0; int gPainHitLoc = -1; vec3_t gPainPoint; -void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod ) { - gclient_t *client; - int take, asave, max, subamt = 0, knockback; - float famt = 0, hamt = 0, shieldAbsorbed = 0; +void G_Damage(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod) { + gclient_t *client; + int take, asave, max, subamt = 0, knockback; + float famt = 0, hamt = 0, shieldAbsorbed = 0; if (!targ) return; - if (targ && targ->damageRedirect) - { + if (targ && targ->damageRedirect) { G_Damage(&g_entities[targ->damageRedirectTo], inflictor, attacker, dir, point, damage, dflags, mod); return; } - if (mod == MOD_DEMP2 && targ && targ->inuse && targ->client) - { - if ( targ->client->ps.electrifyTime < level.time ) - {//electrocution effect - if (targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE && - targ->m_pVehicle && (targ->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || targ->m_pVehicle->m_pVehicleInfo->type == VH_WALKER)) - { //do some extra stuff to speeders/walkers - targ->client->ps.electrifyTime = level.time + Q_irand( 3000, 4000 ); - } - else if ( targ->s.NPC_class != CLASS_VEHICLE - || (targ->m_pVehicle && targ->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) ) - {//don't do this to fighters - targ->client->ps.electrifyTime = level.time + Q_irand( 300, 800 ); + if (mod == MOD_DEMP2 && targ && targ->inuse && targ->client) { + if (targ->client->ps.electrifyTime < level.time) { // electrocution effect + if (targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE && targ->m_pVehicle && + (targ->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || + targ->m_pVehicle->m_pVehicleInfo->type == VH_WALKER)) { // do some extra stuff to speeders/walkers + targ->client->ps.electrifyTime = level.time + Q_irand(3000, 4000); + } else if (targ->s.NPC_class != CLASS_VEHICLE || + (targ->m_pVehicle && targ->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER)) { // don't do this to fighters + targ->client->ps.electrifyTime = level.time + Q_irand(300, 800); } } } - if (level.gametype == GT_SIEGE && - !gSiegeRoundBegun) - { //nothing can be damaged til the round starts. + if (level.gametype == GT_SIEGE && !gSiegeRoundBegun) { // nothing can be damaged til the round starts. return; } @@ -4463,29 +3639,21 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ return; } - if ( (targ->flags&FL_SHIELDED) && mod != MOD_SABER && !targ->client) - {//magnetically protected, this thing can only be damaged by lightsabers + if ((targ->flags & FL_SHIELDED) && mod != MOD_SABER && !targ->client) { // magnetically protected, this thing can only be damaged by lightsabers return; } - if ((targ->flags & FL_DMG_BY_SABER_ONLY) && mod != MOD_SABER) - { //saber-only damage + if ((targ->flags & FL_DMG_BY_SABER_ONLY) && mod != MOD_SABER) { // saber-only damage return; } - if ( targ->client ) - {//don't take damage when in a walker, or fighter - //unless the walker/fighter is dead!!! -rww - if ( targ->client->ps.clientNum < MAX_CLIENTS && targ->client->ps.m_iVehicleNum ) - { + if (targ->client) { // don't take damage when in a walker, or fighter + // unless the walker/fighter is dead!!! -rww + if (targ->client->ps.clientNum < MAX_CLIENTS && targ->client->ps.m_iVehicleNum) { gentity_t *veh = &g_entities[targ->client->ps.m_iVehicleNum]; - if ( veh->m_pVehicle && veh->health > 0 ) - { - if ( veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || - veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { - if (!(dflags & DAMAGE_NO_PROTECTION)) - { + if (veh->m_pVehicle && veh->health > 0) { + if (veh->m_pVehicle->m_pVehicleInfo->type == VH_WALKER || veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { + if (!(dflags & DAMAGE_NO_PROTECTION)) { return; } } @@ -4493,226 +3661,162 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } } - if ((targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY)) - { //only take damage from explosives and such - if (mod != MOD_REPEATER_ALT && - mod != MOD_ROCKET && - mod != MOD_FLECHETTE_ALT_SPLASH && - mod != MOD_ROCKET_HOMING && - mod != MOD_THERMAL && - mod != MOD_THERMAL_SPLASH && - mod != MOD_TRIP_MINE_SPLASH && - mod != MOD_TIMED_MINE_SPLASH && - mod != MOD_DET_PACK_SPLASH && - mod != MOD_VEHICLE && - mod != MOD_CONC && - mod != MOD_CONC_ALT && - mod != MOD_SABER && - mod != MOD_TURBLAST && - mod != MOD_SUICIDE && - mod != MOD_FALLING && - mod != MOD_CRUSH && - mod != MOD_TELEFRAG && - mod != MOD_TRIGGER_HURT) - { - if ( mod != MOD_MELEE || !G_HeavyMelee( attacker ) ) - { //let classes with heavy melee ability damage heavy wpn dmg doors with fists + if ((targ->flags & FL_DMG_BY_HEAVY_WEAP_ONLY)) { // only take damage from explosives and such + if (mod != MOD_REPEATER_ALT && mod != MOD_ROCKET && mod != MOD_FLECHETTE_ALT_SPLASH && mod != MOD_ROCKET_HOMING && mod != MOD_THERMAL && + mod != MOD_THERMAL_SPLASH && mod != MOD_TRIP_MINE_SPLASH && mod != MOD_TIMED_MINE_SPLASH && mod != MOD_DET_PACK_SPLASH && mod != MOD_VEHICLE && + mod != MOD_CONC && mod != MOD_CONC_ALT && mod != MOD_SABER && mod != MOD_TURBLAST && mod != MOD_SUICIDE && mod != MOD_FALLING && mod != MOD_CRUSH && + mod != MOD_TELEFRAG && mod != MOD_TRIGGER_HURT) { + if (mod != MOD_MELEE || !G_HeavyMelee(attacker)) { // let classes with heavy melee ability damage heavy wpn dmg doors with fists return; } } } - if (targ->flags & FL_BBRUSH) - { - if (mod == MOD_DEMP2 || - mod == MOD_DEMP2_ALT || - mod == MOD_BRYAR_PISTOL || - mod == MOD_BRYAR_PISTOL_ALT || - mod == MOD_MELEE) - { //these don't damage bbrushes.. ever - if ( mod != MOD_MELEE || !G_HeavyMelee( attacker ) ) - { //let classes with heavy melee ability damage breakable brushes with fists + if (targ->flags & FL_BBRUSH) { + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT || mod == MOD_BRYAR_PISTOL || mod == MOD_BRYAR_PISTOL_ALT || + mod == MOD_MELEE) { // these don't damage bbrushes.. ever + if (mod != MOD_MELEE || !G_HeavyMelee(attacker)) { // let classes with heavy melee ability damage breakable brushes with fists return; } } } - if (targ && targ->client && targ->client->ps.duelInProgress) - { - if (attacker && attacker->client && attacker->s.number != targ->client->ps.duelIndex) - { + if (targ && targ->client && targ->client->ps.duelInProgress) { + if (attacker && attacker->client && attacker->s.number != targ->client->ps.duelIndex) { return; - } - else if (attacker && attacker->client && mod != MOD_SABER) - { + } else if (attacker && attacker->client && mod != MOD_SABER) { return; } } - if (attacker && attacker->client && attacker->client->ps.duelInProgress) - { - if (targ && targ->client && targ->s.number != attacker->client->ps.duelIndex) - { + if (attacker && attacker->client && attacker->client->ps.duelInProgress) { + if (targ && targ->client && targ->s.number != attacker->client->ps.duelIndex) { return; - } - else if (targ && targ->client && mod != MOD_SABER) - { + } else if (targ && targ->client && mod != MOD_SABER) { return; } } - if ( !(dflags & DAMAGE_NO_PROTECTION) ) - {//rage overridden by no_protection - if (targ && targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) - { + if (!(dflags & DAMAGE_NO_PROTECTION)) { // rage overridden by no_protection + if (targ && targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) { damage *= 0.5; } } // the intermission has allready been qualified for, so don't // allow any extra scoring - if ( level.intermissionQueued ) { + if (level.intermissionQueued) { return; } - if ( !inflictor ) { + if (!inflictor) { inflictor = &g_entities[ENTITYNUM_WORLD]; } - if ( !attacker ) { + if (!attacker) { attacker = &g_entities[ENTITYNUM_WORLD]; } // shootable doors / buttons don't actually have any health - //if genericValue4 == 1 then it's glass or a breakable and those do have health - if ( targ->s.eType == ET_MOVER && targ->genericValue4 != 1 ) { - if ( targ->use && targ->moverState == MOVER_POS1 ) { - GlobalUse( targ, inflictor, attacker ); + // if genericValue4 == 1 then it's glass or a breakable and those do have health + if (targ->s.eType == ET_MOVER && targ->genericValue4 != 1) { + if (targ->use && targ->moverState == MOVER_POS1) { + GlobalUse(targ, inflictor, attacker); } return; } // reduce damage by the attacker's handicap value // unless they are rocket jumping - if ( attacker->client - && attacker != targ - && attacker->s.eType == ET_PLAYER - && level.gametype != GT_SIEGE ) - { + if (attacker->client && attacker != targ && attacker->s.eType == ET_PLAYER && level.gametype != GT_SIEGE) { max = attacker->client->ps.stats[STAT_MAX_HEALTH]; damage = damage * max / 100; } - if ( !(dflags&DAMAGE_NO_HIT_LOC) ) - {//see if we should modify it by damage location - if (targ->inuse && (targ->client || targ->s.eType == ET_NPC) && - attacker->inuse && (attacker->client || attacker->s.eType == ET_NPC)) - { //check for location based damage stuff. + if (!(dflags & DAMAGE_NO_HIT_LOC)) { // see if we should modify it by damage location + if (targ->inuse && (targ->client || targ->s.eType == ET_NPC) && attacker->inuse && + (attacker->client || attacker->s.eType == ET_NPC)) { // check for location based damage stuff. G_LocationBasedDamageModifier(targ, point, mod, dflags, &damage); } } - if ( targ->client - && targ->client->NPC_class == CLASS_RANCOR - && (!attacker||!attacker->client||attacker->client->NPC_class!=CLASS_RANCOR) ) - { + if (targ->client && targ->client->NPC_class == CLASS_RANCOR && (!attacker || !attacker->client || attacker->client->NPC_class != CLASS_RANCOR)) { // I guess always do 10 points of damage...feel free to tweak as needed - if ( damage < 10 ) - {//ignore piddly little damage + if (damage < 10) { // ignore piddly little damage damage = 0; - } - else if ( damage >= 10 ) - { + } else if (damage >= 10) { damage = 10; } } client = targ->client; - if ( client ) { - if ( client->noclip ) { + if (client) { + if (client->noclip) { return; } } - if ( !dir ) { + if (!dir) { dflags |= DAMAGE_NO_KNOCKBACK; } else { VectorNormalize(dir); } knockback = damage; - if ( knockback > 200 ) { + if (knockback > 200) { knockback = 200; } - if ( targ->flags & FL_NO_KNOCKBACK ) { + if (targ->flags & FL_NO_KNOCKBACK) { knockback = 0; } - if ( dflags & DAMAGE_NO_KNOCKBACK ) { + if (dflags & DAMAGE_NO_KNOCKBACK) { knockback = 0; } // figure momentum add, even if the damage won't be taken - if ( knockback && targ->client ) { - vec3_t kvel; - float mass; + if (knockback && targ->client) { + vec3_t kvel; + float mass; mass = 200; - if (mod == MOD_SABER) - { + if (mod == MOD_SABER) { float saberKnockbackScale = g_saberDmgVelocityScale.value; - if ( (dflags&DAMAGE_SABER_KNOCKBACK1) - || (dflags&DAMAGE_SABER_KNOCKBACK2) ) - {//saber does knockback, scale it by the right number - if ( !saberKnockbackScale ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK1) || (dflags & DAMAGE_SABER_KNOCKBACK2)) { // saber does knockback, scale it by the right number + if (!saberKnockbackScale) { saberKnockbackScale = 1.0f; } - if ( attacker - && attacker->client ) - { - if ( (dflags&DAMAGE_SABER_KNOCKBACK1) ) - { - if ( attacker && attacker->client ) - { + if (attacker && attacker->client) { + if ((dflags & DAMAGE_SABER_KNOCKBACK1)) { + if (attacker && attacker->client) { saberKnockbackScale *= attacker->client->saber[0].knockbackScale; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK1_B2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK1_B2)) { + if (attacker && attacker->client) { saberKnockbackScale *= attacker->client->saber[0].knockbackScale2; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK2)) { + if (attacker && attacker->client) { saberKnockbackScale *= attacker->client->saber[1].knockbackScale; } } - if ( (dflags&DAMAGE_SABER_KNOCKBACK2_B2) ) - { - if ( attacker && attacker->client ) - { + if ((dflags & DAMAGE_SABER_KNOCKBACK2_B2)) { + if (attacker && attacker->client) { saberKnockbackScale *= attacker->client->saber[1].knockbackScale2; } } } } - VectorScale (dir, (g_knockback.value * (float)knockback / mass)*saberKnockbackScale, kvel); - } - else - { - VectorScale (dir, g_knockback.value * (float)knockback / mass, kvel); + VectorScale(dir, (g_knockback.value * (float)knockback / mass) * saberKnockbackScale, kvel); + } else { + VectorScale(dir, g_knockback.value * (float)knockback / mass, kvel); } - VectorAdd (targ->client->ps.velocity, kvel, targ->client->ps.velocity); + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); - if (attacker && attacker->client && attacker != targ) - { + if (attacker && attacker->client && attacker != targ) { float dur = 5000; float dur2 = 100; - if (targ->client && targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE) - { + if (targ->client && targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE) { dur = 25000; dur2 = 25000; } @@ -4722,36 +3826,31 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } // set the timer so that the other client can't cancel // out the movement immediately - if ( !targ->client->ps.pm_time && (g_saberDmgVelocityScale.integer || mod != MOD_SABER || (dflags&DAMAGE_SABER_KNOCKBACK1) || (dflags&DAMAGE_SABER_KNOCKBACK2) || (dflags&DAMAGE_SABER_KNOCKBACK1_B2) || (dflags&DAMAGE_SABER_KNOCKBACK2_B2) ) ) { - int t; + if (!targ->client->ps.pm_time && + (g_saberDmgVelocityScale.integer || mod != MOD_SABER || (dflags & DAMAGE_SABER_KNOCKBACK1) || (dflags & DAMAGE_SABER_KNOCKBACK2) || + (dflags & DAMAGE_SABER_KNOCKBACK1_B2) || (dflags & DAMAGE_SABER_KNOCKBACK2_B2))) { + int t; t = knockback * 2; - if ( t < 50 ) { + if (t < 50) { t = 50; } - if ( t > 200 ) { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; targ->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; } - } - else if (targ->client && targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE && attacker != targ) - { + } else if (targ->client && targ->s.eType == ET_NPC && targ->s.NPC_class == CLASS_VEHICLE && attacker != targ) { targ->client->ps.otherKiller = attacker->s.number; targ->client->ps.otherKillerTime = level.time + 25000; targ->client->ps.otherKillerDebounceTime = level.time + 25000; } - - if ( (g_jediVmerc.integer || level.gametype == GT_SIEGE) - && client ) - {//less explosive damage for jedi, more saber damage for non-jedi - if ( client->ps.trueJedi - || (level.gametype == GT_SIEGE&&client->ps.weapon == WP_SABER)) - {//if the target is a trueJedi, reduce splash and explosive damage to 1/2 - switch ( mod ) - { + if ((g_jediVmerc.integer || level.gametype == GT_SIEGE) && client) { // less explosive damage for jedi, more saber damage for non-jedi + if (client->ps.trueJedi || + (level.gametype == GT_SIEGE && client->ps.weapon == WP_SABER)) { // if the target is a trueJedi, reduce splash and explosive damage to 1/2 + switch (mod) { case MOD_REPEATER_ALT: case MOD_REPEATER_ALT_SPLASH: case MOD_DEMP2_ALT: @@ -4768,138 +3867,94 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ damage *= 0.75; break; } - } - else if ( (client->ps.trueNonJedi || (level.gametype == GT_SIEGE&&client->ps.weapon != WP_SABER)) - && mod == MOD_SABER ) - {//if the target is a trueNonJedi, take more saber damage... combined with the 1.5 in the w_saber stuff, this is 6 times damage! - if ( damage < 100 ) - { + } else if ((client->ps.trueNonJedi || (level.gametype == GT_SIEGE && client->ps.weapon != WP_SABER)) && + mod == MOD_SABER) { // if the target is a trueNonJedi, take more saber damage... combined with the 1.5 in the w_saber stuff, this is 6 times + // damage! + if (damage < 100) { damage *= 4; - if ( damage > 100 ) - { + if (damage > 100) { damage = 100; } } } } - if (attacker->client && targ->client && level.gametype == GT_SIEGE && - targ->client->siegeClass != -1 && (bgSiegeClasses[targ->client->siegeClass].classflags & (1<client && targ->client && level.gametype == GT_SIEGE && targ->client->siegeClass != -1 && + (bgSiegeClasses[targ->client->siegeClass].classflags & + (1 << CFL_STRONGAGAINSTPHYSICAL))) { // this class is flagged to take less damage from physical attacks. + // For now I'm just decreasing against any client-based attack, this can be changed later I guess. damage *= 0.5; } // check for completely getting out of the damage - if ( !(dflags & DAMAGE_NO_PROTECTION) ) { + if (!(dflags & DAMAGE_NO_PROTECTION)) { // if TF_NO_FRIENDLY_FIRE is set, don't do damage to the target // if the attacker was on the same team - if ( targ != attacker) - { - if (OnSameTeam (targ, attacker)) - { - if ( !g_friendlyFire.integer ) - { + if (targ != attacker) { + if (OnSameTeam(targ, attacker)) { + if (!g_friendlyFire.integer) { return; } - } - else if (attacker && attacker->inuse && - !attacker->client && attacker->activator && - targ != attacker->activator && - attacker->activator->inuse && attacker->activator->client) - { //emplaced guns don't hurt teammates of user - if (OnSameTeam (targ, attacker->activator)) - { - if ( !g_friendlyFire.integer ) - { + } else if (attacker && attacker->inuse && !attacker->client && attacker->activator && targ != attacker->activator && attacker->activator->inuse && + attacker->activator->client) { // emplaced guns don't hurt teammates of user + if (OnSameTeam(targ, attacker->activator)) { + if (!g_friendlyFire.integer) { return; } } - } - else if (targ->inuse && targ->client && - level.gametype >= GT_TEAM && - attacker->s.number >= MAX_CLIENTS && - attacker->alliedTeam && - targ->client->sess.sessionTeam == attacker->alliedTeam && - !g_friendlyFire.integer) - { //things allied with my team should't hurt me.. I guess + } else if (targ->inuse && targ->client && level.gametype >= GT_TEAM && attacker->s.number >= MAX_CLIENTS && attacker->alliedTeam && + targ->client->sess.sessionTeam == attacker->alliedTeam && + !g_friendlyFire.integer) { // things allied with my team should't hurt me.. I guess return; } } - if (level.gametype == GT_JEDIMASTER && !g_friendlyFire.integer && - targ && targ->client && attacker && attacker->client && - targ != attacker && !targ->client->ps.isJediMaster && !attacker->client->ps.isJediMaster && - G_ThereIsAMaster()) - { + if (level.gametype == GT_JEDIMASTER && !g_friendlyFire.integer && targ && targ->client && attacker && attacker->client && targ != attacker && + !targ->client->ps.isJediMaster && !attacker->client->ps.isJediMaster && G_ThereIsAMaster()) { return; } - if (targ->s.number >= MAX_CLIENTS && targ->client - && targ->s.shouldtarget && targ->s.teamowner && - attacker && attacker->inuse && attacker->client && targ->s.owner >= 0 && targ->s.owner < MAX_CLIENTS) - { + if (targ->s.number >= MAX_CLIENTS && targ->client && targ->s.shouldtarget && targ->s.teamowner && attacker && attacker->inuse && attacker->client && + targ->s.owner >= 0 && targ->s.owner < MAX_CLIENTS) { gentity_t *targown = &g_entities[targ->s.owner]; - if (targown && targown->inuse && targown->client && OnSameTeam(targown, attacker)) - { - if (!g_friendlyFire.integer) - { + if (targown && targown->inuse && targown->client && OnSameTeam(targown, attacker)) { + if (!g_friendlyFire.integer) { return; } } } // check for godmode - if ( (targ->flags & FL_GODMODE) && targ->s.eType != ET_NPC ) { + if ((targ->flags & FL_GODMODE) && targ->s.eType != ET_NPC) { return; } - if (targ && targ->client && (targ->client->ps.eFlags & EF_INVULNERABLE) && - attacker && attacker->client && targ != attacker) - { - if (targ->client->invulnerableTimer <= level.time) - { + if (targ && targ->client && (targ->client->ps.eFlags & EF_INVULNERABLE) && attacker && attacker->client && targ != attacker) { + if (targ->client->invulnerableTimer <= level.time) { targ->client->ps.eFlags &= ~EF_INVULNERABLE; - } - else - { + } else { return; } } } - //check for teamnodmg - //NOTE: non-client objects hitting clients (and clients hitting clients) purposely doesn't obey this teamnodmg (for emplaced guns) - if ( attacker && !targ->client ) - {//attacker hit a non-client - if ( level.gametype == GT_SIEGE && - !g_ff_objectives.integer ) - {//in siege mode (and...?) - if ( targ->teamnodmg ) - {//targ shouldn't take damage from a certain team - if ( attacker->client ) - {//a client hit a non-client object - if ( targ->teamnodmg == attacker->client->sess.sessionTeam ) - { + // check for teamnodmg + // NOTE: non-client objects hitting clients (and clients hitting clients) purposely doesn't obey this teamnodmg (for emplaced guns) + if (attacker && !targ->client) { // attacker hit a non-client + if (level.gametype == GT_SIEGE && !g_ff_objectives.integer) { // in siege mode (and...?) + if (targ->teamnodmg) { // targ shouldn't take damage from a certain team + if (attacker->client) { // a client hit a non-client object + if (targ->teamnodmg == attacker->client->sess.sessionTeam) { return; } - } - else if ( attacker->teamnodmg ) - {//a non-client hit a non-client object - //FIXME: maybe check alliedTeam instead? - if ( targ->teamnodmg == attacker->teamnodmg ) - { - if (attacker->activator && - attacker->activator->inuse && - attacker->activator->s.number < MAX_CLIENTS && - attacker->activator->client && - attacker->activator->client->sess.sessionTeam != targ->teamnodmg) - { //uh, let them damage it I guess. - } - else - { + } else if (attacker->teamnodmg) { // a non-client hit a non-client object + // FIXME: maybe check alliedTeam instead? + if (targ->teamnodmg == attacker->teamnodmg) { + if (attacker->activator && attacker->activator->inuse && attacker->activator->s.number < MAX_CLIENTS && attacker->activator->client && + attacker->activator->client->sess.sessionTeam != targ->teamnodmg) { // uh, let them damage it I guess. + } else { return; } } @@ -4908,103 +3963,85 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } } - #ifdef BASE_COMPAT - // battlesuit protects from all radius damage (but takes knockback) - // and protects 50% against all damage - if ( client && client->ps.powerups[PW_BATTLESUIT] ) { - G_AddEvent( targ, EV_POWERUP_BATTLESUIT, 0 ); - if ( ( dflags & DAMAGE_RADIUS ) || ( mod == MOD_FALLING ) ) { - return; - } - damage *= 0.5; +#ifdef BASE_COMPAT + // battlesuit protects from all radius damage (but takes knockback) + // and protects 50% against all damage + if (client && client->ps.powerups[PW_BATTLESUIT]) { + G_AddEvent(targ, EV_POWERUP_BATTLESUIT, 0); + if ((dflags & DAMAGE_RADIUS) || (mod == MOD_FALLING)) { + return; } - #endif + damage *= 0.5; + } +#endif // add to the attacker's hit counter (if the target isn't a general entity like a prox mine) - if ( attacker->client && targ != attacker && targ->health > 0 - && targ->s.eType != ET_MISSILE - && targ->s.eType != ET_GENERAL - && client) { - if ( OnSameTeam( targ, attacker ) ) { + if (attacker->client && targ != attacker && targ->health > 0 && targ->s.eType != ET_MISSILE && targ->s.eType != ET_GENERAL && client) { + if (OnSameTeam(targ, attacker)) { attacker->client->ps.persistant[PERS_HITS]--; } else { attacker->client->ps.persistant[PERS_HITS]++; } - attacker->client->ps.persistant[PERS_ATTACKEE_ARMOR] = (targ->health<<8)|(client->ps.stats[STAT_ARMOR]); + attacker->client->ps.persistant[PERS_ATTACKEE_ARMOR] = (targ->health << 8) | (client->ps.stats[STAT_ARMOR]); } // always give half damage if hurting self... but not in siege. Heavy weapons need a counter. // calculated after knockback, so rocket jumping works - if ( targ == attacker && !(dflags & DAMAGE_NO_SELF_PROTECTION)) { - if ( level.gametype == GT_SIEGE ) - { + if (targ == attacker && !(dflags & DAMAGE_NO_SELF_PROTECTION)) { + if (level.gametype == GT_SIEGE) { damage *= 1.5; - } - else - { + } else { damage *= 0.5; } } - if ( damage < 1 ) { + if (damage < 1) { damage = 1; } take = damage; // save some from armor - asave = CheckArmor (targ, take, dflags); + asave = CheckArmor(targ, take, dflags); - if (asave) - { + if (asave) { shieldAbsorbed = asave; } take -= asave; - if ( targ->client ) - {//update vehicle shields and armor, check for explode - if ( targ->client->NPC_class == CLASS_VEHICLE && - targ->m_pVehicle ) - {//FIXME: should be in its own function in g_vehicles.c now, too big to be here + if (targ->client) { // update vehicle shields and armor, check for explode + if (targ->client->NPC_class == CLASS_VEHICLE && targ->m_pVehicle) { // FIXME: should be in its own function in g_vehicles.c now, too big to be here int surface = -1; - if ( attacker ) - {//so we know the last guy who shot at us + if (attacker) { // so we know the last guy who shot at us targ->enemy = attacker; } - if ( targ->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL ) - { + if (targ->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { //((CVehicleNPC *)targ->NPC)->m_ulFlags |= CVehicleNPC::VEH_BUCKING; } targ->m_pVehicle->m_iShields = targ->client->ps.stats[STAT_ARMOR]; - G_VehUpdateShields( targ ); + G_VehUpdateShields(targ); targ->m_pVehicle->m_iArmor -= take; - if ( targ->m_pVehicle->m_iArmor <= 0 ) - { + if (targ->m_pVehicle->m_iArmor <= 0) { targ->s.eFlags |= EF_DEAD; targ->client->ps.eFlags |= EF_DEAD; targ->m_pVehicle->m_iArmor = 0; } - if ( targ->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//get the last surf that was hit - if ( targ->client && targ->client->g2LastSurfaceTime == level.time) - { + if (targ->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // get the last surf that was hit + if (targ->client && targ->client->g2LastSurfaceTime == level.time) { char hitSurface[MAX_QPATH]; trap->G2API_GetSurfaceName(targ->ghoul2, targ->client->g2LastSurfaceHit, 0, hitSurface); - if (hitSurface[0]) - { - surface = G_ShipSurfaceForSurfName( &hitSurface[0] ); + if (hitSurface[0]) { + surface = G_ShipSurfaceForSurfName(&hitSurface[0]); - if ( take && surface > 0 ) - {//hit a certain part of the ship + if (take && surface > 0) { // hit a certain part of the ship int deathPoint = 0; targ->locationDamage[surface] += take; - switch(surface) - { + switch (surface) { case SHIPSURF_FRONT: deathPoint = targ->m_pVehicle->m_pVehicleInfo->health_front; break; @@ -5021,27 +4058,21 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ break; } - //presume 0 means it wasn't set and so it should never die. - if ( deathPoint ) - { - if ( targ->locationDamage[surface] >= deathPoint) - { //this area of the ship is now dead - if ( G_FlyVehicleDestroySurface( targ, surface ) ) - {//actually took off a surface - G_VehicleSetDamageLocFlags( targ, surface, deathPoint ); + // presume 0 means it wasn't set and so it should never die. + if (deathPoint) { + if (targ->locationDamage[surface] >= deathPoint) { // this area of the ship is now dead + if (G_FlyVehicleDestroySurface(targ, surface)) { // actually took off a surface + G_VehicleSetDamageLocFlags(targ, surface, deathPoint); } - } - else - { - G_VehicleSetDamageLocFlags( targ, surface, deathPoint ); + } else { + G_VehicleSetDamageLocFlags(targ, surface, deathPoint); } } } } } } - if ( targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - { + if (targ->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { /* if ( targ->m_pVehicle->m_iArmor <= 0 ) {//vehicle all out of armor @@ -5052,144 +4083,100 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } } else*/ - if ( attacker - //&& attacker->client - && targ != attacker - && point - && !VectorCompare( targ->client->ps.origin, point ) - && targ->m_pVehicle->m_LandTrace.fraction >= 1.0f) - {//just took a hit, knock us around - vec3_t vUp, impactDir; - float impactStrength = (damage/200.0f)*10.0f; - float dot = 0.0f; - if ( impactStrength > 10.0f ) - { + if (attacker + //&& attacker->client + && targ != attacker && point && !VectorCompare(targ->client->ps.origin, point) && + targ->m_pVehicle->m_LandTrace.fraction >= 1.0f) { // just took a hit, knock us around + vec3_t vUp, impactDir; + float impactStrength = (damage / 200.0f) * 10.0f; + float dot = 0.0f; + if (impactStrength > 10.0f) { impactStrength = 10.0f; } - //pitch or roll us based on where we were hit - AngleVectors( targ->m_pVehicle->m_vOrientation, NULL, NULL, vUp ); - VectorSubtract( point, targ->r.currentOrigin, impactDir ); - VectorNormalize( impactDir ); - if ( surface <= 0 ) - {//no surf guess where we were hit, then - vec3_t vFwd, vRight; - AngleVectors( targ->m_pVehicle->m_vOrientation, vFwd, vRight, vUp ); - dot = DotProduct( vRight, impactDir ); - if ( dot > 0.4f ) - { + // pitch or roll us based on where we were hit + AngleVectors(targ->m_pVehicle->m_vOrientation, NULL, NULL, vUp); + VectorSubtract(point, targ->r.currentOrigin, impactDir); + VectorNormalize(impactDir); + if (surface <= 0) { // no surf guess where we were hit, then + vec3_t vFwd, vRight; + AngleVectors(targ->m_pVehicle->m_vOrientation, vFwd, vRight, vUp); + dot = DotProduct(vRight, impactDir); + if (dot > 0.4f) { surface = SHIPSURF_RIGHT; - } - else if ( dot < -0.4f ) - { + } else if (dot < -0.4f) { surface = SHIPSURF_LEFT; - } - else - { - dot = DotProduct( vFwd, impactDir ); - if ( dot > 0.0f ) - { + } else { + dot = DotProduct(vFwd, impactDir); + if (dot > 0.0f) { surface = SHIPSURF_FRONT; - } - else - { + } else { surface = SHIPSURF_BACK; } } } - switch ( surface ) - { + switch (surface) { case SHIPSURF_FRONT: - dot = DotProduct( vUp, impactDir ); - if ( dot > 0 ) - { + dot = DotProduct(vUp, impactDir); + if (dot > 0) { targ->m_pVehicle->m_vOrientation[PITCH] += impactStrength; - } - else - { + } else { targ->m_pVehicle->m_vOrientation[PITCH] -= impactStrength; } break; case SHIPSURF_BACK: - dot = DotProduct( vUp, impactDir ); - if ( dot > 0 ) - { + dot = DotProduct(vUp, impactDir); + if (dot > 0) { targ->m_pVehicle->m_vOrientation[PITCH] -= impactStrength; - } - else - { + } else { targ->m_pVehicle->m_vOrientation[PITCH] += impactStrength; } break; case SHIPSURF_RIGHT: - dot = DotProduct( vUp, impactDir ); - if ( dot > 0 ) - { + dot = DotProduct(vUp, impactDir); + if (dot > 0) { targ->m_pVehicle->m_vOrientation[ROLL] -= impactStrength; - } - else - { + } else { targ->m_pVehicle->m_vOrientation[ROLL] += impactStrength; } break; case SHIPSURF_LEFT: - dot = DotProduct( vUp, impactDir ); - if ( dot > 0 ) - { + dot = DotProduct(vUp, impactDir); + if (dot > 0) { targ->m_pVehicle->m_vOrientation[ROLL] += impactStrength; - } - else - { + } else { targ->m_pVehicle->m_vOrientation[ROLL] -= impactStrength; } break; } - } } } } - if ( mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT ) - {//FIXME: screw with non-animal vehicles, too? - if ( client ) - { - if ( client->NPC_class == CLASS_VEHICLE - && targ->m_pVehicle - && targ->m_pVehicle->m_pVehicleInfo - && targ->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER ) - {//all damage goes into the disruption of shields and systems + if (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT) { // FIXME: screw with non-animal vehicles, too? + if (client) { + if (client->NPC_class == CLASS_VEHICLE && targ->m_pVehicle && targ->m_pVehicle->m_pVehicleInfo && + targ->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // all damage goes into the disruption of shields and systems take = 0; - } - else - { + } else { - if (client->jetPackOn) - { //disable jetpack temporarily + if (client->jetPackOn) { // disable jetpack temporarily Jetpack_Off(targ); client->jetPackToggleTime = level.time + Q_irand(3000, 10000); } - if ( client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || - client->NPC_class == CLASS_R2D2 || client->NPC_class == CLASS_R5D2 || - client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK ) - { + if (client->NPC_class == CLASS_PROTOCOL || client->NPC_class == CLASS_SEEKER || client->NPC_class == CLASS_R2D2 || + client->NPC_class == CLASS_R5D2 || client->NPC_class == CLASS_MOUSE || client->NPC_class == CLASS_GONK) { // DEMP2 does more damage to these guys. take *= 2; - } - else if ( client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || - client->NPC_class == CLASS_MARK1 || client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || - client->NPC_class == CLASS_ATST ) - { + } else if (client->NPC_class == CLASS_PROBE || client->NPC_class == CLASS_INTERROGATOR || client->NPC_class == CLASS_MARK1 || + client->NPC_class == CLASS_MARK2 || client->NPC_class == CLASS_SENTRY || client->NPC_class == CLASS_ATST) { // DEMP2 does way more damage to these guys. take *= 5; - } - else - { - if (take > 0) - { + } else { + if (take > 0) { take /= 3; - if (take < 1) - { + if (take < 1) { take = 1; } } @@ -5198,16 +4185,15 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } } - if ( g_debugDamage.integer ) { - trap->Print( "%i: client:%i health:%i damage:%i armor:%i\n", level.time, targ->s.number, - targ->health, take, asave ); + if (g_debugDamage.integer) { + trap->Print("%i: client:%i health:%i damage:%i armor:%i\n", level.time, targ->s.number, targ->health, take, asave); } // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame - if ( client ) { - if ( attacker ) { + if (client) { + if (attacker) { client->ps.persistant[PERS_ATTACKER] = attacker->s.number; } else { client->ps.persistant[PERS_ATTACKER] = ENTITYNUM_WORLD; @@ -5215,26 +4201,23 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ client->damage_armor += asave; client->damage_blood += take; client->damage_knockback += knockback; - if ( dir ) { - VectorCopy ( dir, client->damage_from ); + if (dir) { + VectorCopy(dir, client->damage_from); client->damage_fromWorld = qfalse; } else { - VectorCopy ( targ->r.currentOrigin, client->damage_from ); + VectorCopy(targ->r.currentOrigin, client->damage_from); client->damage_fromWorld = qtrue; } - if (attacker && attacker->client) - { + if (attacker && attacker->client) { BotDamageNotification(client, attacker); - } - else if (inflictor && inflictor->client) - { + } else if (inflictor && inflictor->client) { BotDamageNotification(client, inflictor); } } // See if it's the player hurting the emeny flag carrier - if( level.gametype == GT_CTF || level.gametype == GT_CTY) { + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { Team_CheckHurtCarrier(targ, attacker); } @@ -5244,72 +4227,54 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ targ->client->lasthurt_mod = mod; } - if ( !(dflags & DAMAGE_NO_PROTECTION) ) - {//protect overridden by no_protection - if (take && targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_PROTECT))) - { - if (targ->client->ps.fd.forcePower) - { + if (!(dflags & DAMAGE_NO_PROTECTION)) { // protect overridden by no_protection + if (take && targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_PROTECT))) { + if (targ->client->ps.fd.forcePower) { int maxtake = take; - //G_Sound(targ, CHAN_AUTO, protectHitSound); - if (targ->client->forcePowerSoundDebounce < level.time) - { + // G_Sound(targ, CHAN_AUTO, protectHitSound); + if (targ->client->forcePowerSoundDebounce < level.time) { G_PreDefSound(targ->client->ps.origin, PDSOUND_PROTECTHIT); targ->client->forcePowerSoundDebounce = level.time + 400; } - if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_1) - { + if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_1) { famt = 1; hamt = 0.40f; - if (maxtake > 100) - { + if (maxtake > 100) { maxtake = 100; } - } - else if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_2) - { + } else if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_2) { famt = 0.5f; hamt = 0.60f; - if (maxtake > 200) - { + if (maxtake > 200) { maxtake = 200; } - } - else if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_3) - { + } else if (targ->client->ps.fd.forcePowerLevel[FP_PROTECT] == FORCE_LEVEL_3) { famt = 0.25f; hamt = 0.80f; - if (maxtake > 400) - { + if (maxtake > 400) { maxtake = 400; } } - if (!targ->client->ps.powerups[PW_FORCE_BOON]) - { - targ->client->ps.fd.forcePower -= maxtake*famt; + if (!targ->client->ps.powerups[PW_FORCE_BOON]) { + targ->client->ps.fd.forcePower -= maxtake * famt; + } else { + targ->client->ps.fd.forcePower -= (maxtake * famt) / 2; } - else - { - targ->client->ps.fd.forcePower -= (maxtake*famt)/2; - } - subamt = (maxtake*hamt)+(take-maxtake); - if (targ->client->ps.fd.forcePower < 0) - { + subamt = (maxtake * hamt) + (take - maxtake); + if (targ->client->ps.fd.forcePower < 0) { subamt += targ->client->ps.fd.forcePower; targ->client->ps.fd.forcePower = 0; } - if (subamt) - { + if (subamt) { take -= subamt; - if (take < 0) - { + if (take < 0) { take = 0; } } @@ -5317,8 +4282,7 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ } } - if (shieldAbsorbed) - { + if (shieldAbsorbed) { /* if ( targ->client->NPC_class == CLASS_VEHICLE ) { @@ -5327,158 +4291,126 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ else */ { - gentity_t *evEnt; + gentity_t *evEnt; // Send off an event to show a shield shell on the player, pointing in the right direction. - //evEnt = G_TempEntity(vec3_origin, EV_SHIELD_HIT); - //rww - er.. what the? This isn't broadcast, why is it being set on vec3_origin?! + // evEnt = G_TempEntity(vec3_origin, EV_SHIELD_HIT); + // rww - er.. what the? This isn't broadcast, why is it being set on vec3_origin?! evEnt = G_TempEntity(targ->r.currentOrigin, EV_SHIELD_HIT); evEnt->s.otherEntityNum = targ->s.number; evEnt->s.eventParm = DirToByte(dir); - evEnt->s.time2=shieldAbsorbed; - /* - shieldAbsorbed *= 20; + evEnt->s.time2 = shieldAbsorbed; + /* + shieldAbsorbed *= 20; - if (shieldAbsorbed > 1500) - { - shieldAbsorbed = 1500; - } - if (shieldAbsorbed < 200) - { - shieldAbsorbed = 200; - } + if (shieldAbsorbed > 1500) + { + shieldAbsorbed = 1500; + } + if (shieldAbsorbed < 200) + { + shieldAbsorbed = 200; + } - if (targ->client->ps.powerups[PW_SHIELDHIT] < (level.time + shieldAbsorbed)) - { - targ->client->ps.powerups[PW_SHIELDHIT] = level.time + shieldAbsorbed; - } - //flicker for as many ms as damage was absorbed (*20) - //therefore 10 damage causes 1/5 of a seond of flickering, whereas - //a full 100 causes 2 seconds (but is reduced to 1.5 seconds due to the max) + if (targ->client->ps.powerups[PW_SHIELDHIT] < (level.time + shieldAbsorbed)) + { + targ->client->ps.powerups[PW_SHIELDHIT] = level.time + shieldAbsorbed; + } + //flicker for as many ms as damage was absorbed (*20) + //therefore 10 damage causes 1/5 of a seond of flickering, whereas + //a full 100 causes 2 seconds (but is reduced to 1.5 seconds due to the max) - */ + */ } } // do the damage - if (take) - { + if (take) { if (targ->client && targ->s.number < MAX_CLIENTS && - (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT)) - { //uh.. shock them or something. what the hell, I don't know. - if (targ->client->ps.weaponTime <= 0) - { //yeah, we were supposed to be beta a week ago, I don't feel like - //breaking the game so I'm gonna be safe and only do this only - //if your weapon is not busy + (mod == MOD_DEMP2 || mod == MOD_DEMP2_ALT)) { // uh.. shock them or something. what the hell, I don't know. + if (targ->client->ps.weaponTime <= 0) { // yeah, we were supposed to be beta a week ago, I don't feel like + // breaking the game so I'm gonna be safe and only do this only + // if your weapon is not busy targ->client->ps.weaponTime = 2000; targ->client->ps.electrifyTime = level.time + 2000; - if (targ->client->ps.weaponstate == WEAPON_CHARGING || - targ->client->ps.weaponstate == WEAPON_CHARGING_ALT) - { + if (targ->client->ps.weaponstate == WEAPON_CHARGING || targ->client->ps.weaponstate == WEAPON_CHARGING_ALT) { targ->client->ps.weaponstate = WEAPON_READY; } } } - if ( !(dflags & DAMAGE_NO_PROTECTION) ) - {//rage overridden by no_protection - if (targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && (inflictor->client || attacker->client)) - { - take /= (targ->client->ps.fd.forcePowerLevel[FP_RAGE]+1); + if (!(dflags & DAMAGE_NO_PROTECTION)) { // rage overridden by no_protection + if (targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && (inflictor->client || attacker->client)) { + take /= (targ->client->ps.fd.forcePowerLevel[FP_RAGE] + 1); } } targ->health = targ->health - take; - if ( (targ->flags&FL_UNDYING) ) - {//take damage down to 1, but never die - if ( targ->health < 1 ) - { + if ((targ->flags & FL_UNDYING)) { // take damage down to 1, but never die + if (targ->health < 1) { targ->health = 1; } } - if ( targ->client ) { + if (targ->client) { targ->client->ps.stats[STAT_HEALTH] = targ->health; } - if ( !(dflags & DAMAGE_NO_PROTECTION) ) - {//rage overridden by no_protection - if (targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && (inflictor->client || attacker->client)) - { - if (targ->health <= 0) - { + if (!(dflags & DAMAGE_NO_PROTECTION)) { // rage overridden by no_protection + if (targ->client && (targ->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) && (inflictor->client || attacker->client)) { + if (targ->health <= 0) { targ->health = 1; } - if (targ->client->ps.stats[STAT_HEALTH] <= 0) - { + if (targ->client->ps.stats[STAT_HEALTH] <= 0) { targ->client->ps.stats[STAT_HEALTH] = 1; } } } - //We want to go ahead and set gPainHitLoc regardless of if we have a pain func, - //so we can adjust the location damage too. - if (targ->client && targ->ghoul2 && targ->client->g2LastSurfaceTime == level.time) - { //We updated the hit surface this frame, so it's valid. + // We want to go ahead and set gPainHitLoc regardless of if we have a pain func, + // so we can adjust the location damage too. + if (targ->client && targ->ghoul2 && targ->client->g2LastSurfaceTime == level.time) { // We updated the hit surface this frame, so it's valid. char hitSurface[MAX_QPATH]; trap->G2API_GetSurfaceName(targ->ghoul2, targ->client->g2LastSurfaceHit, 0, hitSurface); - if (hitSurface[0]) - { + if (hitSurface[0]) { G_GetHitLocFromSurfName(targ, hitSurface, &gPainHitLoc, point, dir, vec3_origin, mod); - } - else - { + } else { gPainHitLoc = -1; } if (gPainHitLoc < HL_MAX && gPainHitLoc >= 0 && targ->locationDamage[gPainHitLoc] < Q3_INFINITE && - (targ->s.eType == ET_PLAYER || targ->s.NPC_class != CLASS_VEHICLE)) - { + (targ->s.eType == ET_PLAYER || targ->s.NPC_class != CLASS_VEHICLE)) { targ->locationDamage[gPainHitLoc] += take; - if (g_armBreakage.integer && !targ->client->ps.brokenLimbs && - targ->client->ps.stats[STAT_HEALTH] > 0 && targ->health > 0 && - !(targ->s.eFlags & EF_DEAD)) - { //check for breakage - if (targ->locationDamage[HL_ARM_RT]+targ->locationDamage[HL_HAND_RT] >= 80) - { + if (g_armBreakage.integer && !targ->client->ps.brokenLimbs && targ->client->ps.stats[STAT_HEALTH] > 0 && targ->health > 0 && + !(targ->s.eFlags & EF_DEAD)) { // check for breakage + if (targ->locationDamage[HL_ARM_RT] + targ->locationDamage[HL_HAND_RT] >= 80) { G_BreakArm(targ, BROKENLIMB_RARM); - } - else if (targ->locationDamage[HL_ARM_LT]+targ->locationDamage[HL_HAND_LT] >= 80) - { + } else if (targ->locationDamage[HL_ARM_LT] + targ->locationDamage[HL_HAND_LT] >= 80) { G_BreakArm(targ, BROKENLIMB_LARM); } } } - } - else - { + } else { gPainHitLoc = -1; } - if (targ->maxHealth) - { //if this is non-zero this guy should be updated his s.health to send to the client + if (targ->maxHealth) { // if this is non-zero this guy should be updated his s.health to send to the client G_ScaleNetHealth(targ); } - if ( targ->health <= 0 ) { - if ( client ) - { + if (targ->health <= 0) { + if (client) { targ->flags |= FL_NO_KNOCKBACK; - if (point) - { - VectorCopy( point, targ->pos1 ); - } - else - { + if (point) { + VectorCopy(point, targ->pos1); + } else { VectorCopy(targ->client->ps.origin, targ->pos1); } - } - else if (targ->s.eType == ET_NPC) - { //g2animent + } else if (targ->s.eType == ET_NPC) { // g2animent VectorCopy(point, targ->pos1); } @@ -5486,69 +4418,49 @@ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_ targ->health = -999; // If we are a breaking glass brush, store the damage point so we can do cool things with it. - if ( targ->r.svFlags & SVF_GLASS_BRUSH ) - { - VectorCopy( point, targ->pos1 ); - if (dir) - { - VectorCopy( dir, targ->pos2 ); - } - else - { + if (targ->r.svFlags & SVF_GLASS_BRUSH) { + VectorCopy(point, targ->pos1); + if (dir) { + VectorCopy(dir, targ->pos2); + } else { VectorClear(targ->pos2); } } - if (targ->s.eType == ET_NPC && - targ->client && - (targ->s.eFlags & EF_DEAD)) - { //an NPC that's already dead. Maybe we can cut some more limbs off! - if ( (mod == MOD_SABER || (mod == MOD_MELEE && G_HeavyMelee( attacker )) )//saber or heavy melee (claws) - && take > 2 - && !(dflags&DAMAGE_NO_DISMEMBER) ) - { + if (targ->s.eType == ET_NPC && targ->client && (targ->s.eFlags & EF_DEAD)) { // an NPC that's already dead. Maybe we can cut some more limbs off! + if ((mod == MOD_SABER || (mod == MOD_MELEE && G_HeavyMelee(attacker))) // saber or heavy melee (claws) + && take > 2 && !(dflags & DAMAGE_NO_DISMEMBER)) { G_CheckForDismemberment(targ, attacker, targ->pos1, take, targ->client->ps.torsoAnim, qtrue); } } targ->enemy = attacker; - targ->die (targ, inflictor, attacker, take, mod); - G_ActivateBehavior( targ, BSET_DEATH ); + targ->die(targ, inflictor, attacker, take, mod); + G_ActivateBehavior(targ, BSET_DEATH); return; - } - else - { - if ( g_debugMelee.integer ) - {//getting hurt makes you let go of the wall - if ( targ->client && (targ->client->ps.pm_flags&PMF_STUCK_TO_WALL) ) - { - G_LetGoOfWall( targ ); + } else { + if (g_debugMelee.integer) { // getting hurt makes you let go of the wall + if (targ->client && (targ->client->ps.pm_flags & PMF_STUCK_TO_WALL)) { + G_LetGoOfWall(targ); } } - if ( targ->pain ) - { - if (targ->s.eType != ET_NPC || mod != MOD_SABER || take > 1) - { //don't even notify NPCs of pain if it's just idle saber damage + if (targ->pain) { + if (targ->s.eType != ET_NPC || mod != MOD_SABER || take > 1) { // don't even notify NPCs of pain if it's just idle saber damage gPainMOD = mod; - if (point) - { + if (point) { VectorCopy(point, gPainPoint); - } - else - { + } else { VectorCopy(targ->r.currentOrigin, gPainPoint); } - targ->pain (targ, attacker, take); + targ->pain(targ, attacker, take); } } } G_LogWeaponDamage(attacker->s.number, mod, take); } - } - /* ============ CanDamage @@ -5557,73 +4469,70 @@ Returns qtrue if the inflictor can directly damage the target. Used for explosions and melee attacks. ============ */ -qboolean CanDamage (gentity_t *targ, vec3_t origin) { - vec3_t dest; - trace_t tr; - vec3_t midpoint; +qboolean CanDamage(gentity_t *targ, vec3_t origin) { + vec3_t dest; + trace_t tr; + vec3_t midpoint; // use the midpoint of the bounds instead of the origin, because // bmodels may have their origin is 0,0,0 - VectorAdd (targ->r.absmin, targ->r.absmax, midpoint); - VectorScale (midpoint, 0.5, midpoint); + VectorAdd(targ->r.absmin, targ->r.absmax, midpoint); + VectorScale(midpoint, 0.5, midpoint); - VectorCopy (midpoint, dest); - trap->Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); + VectorCopy(midpoint, dest); + trap->Trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0 || tr.entityNum == targ->s.number) return qtrue; // this should probably check in the plane of projection, // rather than in world coordinate, and also include Z - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] += 15.0; - trap->Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); + trap->Trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] += 15.0; dest[1] -= 15.0; - trap->Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); + trap->Trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] += 15.0; - trap->Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); + trap->Trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0) return qtrue; - VectorCopy (midpoint, dest); + VectorCopy(midpoint, dest); dest[0] -= 15.0; dest[1] -= 15.0; - trap->Trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); + trap->Trace(&tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 0); if (tr.fraction == 1.0) return qtrue; - return qfalse; } - /* ============ G_RadiusDamage ============ */ -qboolean G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, float radius, - gentity_t *ignore, gentity_t *missile, int mod) { - float points, dist; - gentity_t *ent; - int entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - vec3_t dir; - int i, e; - qboolean hitClient = qfalse; - qboolean roastPeople = qfalse; +qboolean G_RadiusDamage(vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, gentity_t *missile, int mod) { + float points, dist; + gentity_t *ent; + int entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + vec3_t dir; + int i, e; + qboolean hitClient = qfalse; + qboolean roastPeople = qfalse; /* if (missile && !missile->client && missile->s.weapon > WP_NONE && @@ -5644,21 +4553,21 @@ qboolean G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, floa } } */ - //oh well.. maybe sometime? I am trying to cut down on tempent use. + // oh well.. maybe sometime? I am trying to cut down on tempent use. - if ( radius < 1 ) { + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) { - ent = &g_entities[entityList[ e ]]; + for (e = 0; e < numListedEntities; e++) { + ent = &g_entities[entityList[e]]; if (ent == ignore) continue; @@ -5666,69 +4575,62 @@ qboolean G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, floa continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) { - if ( origin[i] < ent->r.absmin[i] ) { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->r.absmin[i]) { v[i] = ent->r.absmin[i] - origin[i]; - } else if ( origin[i] > ent->r.absmax[i] ) { + } else if (origin[i] > ent->r.absmax[i]) { v[i] = origin[i] - ent->r.absmax[i]; } else { v[i] = 0; } } - dist = VectorLength( v ); - if ( dist >= radius ) { + dist = VectorLength(v); + if (dist >= radius) { continue; } - // if ( ent->health <= 0 ) - // continue; + // if ( ent->health <= 0 ) + // continue; - points = damage * ( 1.0 - dist / radius ); + points = damage * (1.0 - dist / radius); - if( CanDamage (ent, origin) ) { - if( LogAccuracyHit( ent, attacker ) ) { + if (CanDamage(ent, origin)) { + if (LogAccuracyHit(ent, attacker)) { hitClient = qtrue; } - VectorSubtract (ent->r.currentOrigin, origin, dir); + VectorSubtract(ent->r.currentOrigin, origin, dir); // push the center of mass higher than the origin so players // get knocked into the air more dir[2] += 24; - if (attacker && attacker->inuse && attacker->client && - attacker->s.eType == ET_NPC && attacker->s.NPC_class == CLASS_VEHICLE && - attacker->m_pVehicle && attacker->m_pVehicle->m_pPilot) - { //say my pilot did it. - G_Damage (ent, NULL, (gentity_t *)attacker->m_pVehicle->m_pPilot, dir, origin, (int)points, DAMAGE_RADIUS, mod); - } - else - { - G_Damage (ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod); + if (attacker && attacker->inuse && attacker->client && attacker->s.eType == ET_NPC && attacker->s.NPC_class == CLASS_VEHICLE && + attacker->m_pVehicle && attacker->m_pVehicle->m_pPilot) { // say my pilot did it. + G_Damage(ent, NULL, (gentity_t *)attacker->m_pVehicle->m_pPilot, dir, origin, (int)points, DAMAGE_RADIUS, mod); + } else { + G_Damage(ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod); } if (ent && ent->client && roastPeople && missile && - !VectorCompare(ent->r.currentOrigin, missile->r.currentOrigin)) - { //the thing calling this function can create burn marks on people, so create an event to do so + !VectorCompare(ent->r.currentOrigin, + missile->r.currentOrigin)) { // the thing calling this function can create burn marks on people, so create an event to do so gentity_t *evEnt = G_TempEntity(ent->r.currentOrigin, EV_GHOUL2_MARK); - evEnt->s.otherEntityNum = ent->s.number; //the entity the mark should be placed on - evEnt->s.weapon = WP_ROCKET_LAUNCHER; //always say it's rocket so we make the right mark + evEnt->s.otherEntityNum = ent->s.number; // the entity the mark should be placed on + evEnt->s.weapon = WP_ROCKET_LAUNCHER; // always say it's rocket so we make the right mark - //Try to place the decal by going from the missile location to the location of the person that was hit + // Try to place the decal by going from the missile location to the location of the person that was hit VectorCopy(missile->r.currentOrigin, evEnt->s.origin); VectorCopy(ent->r.currentOrigin, evEnt->s.origin2); - //it's hacky, but we want to move it up so it's more likely to hit - //the torso. - if (missile->r.currentOrigin[2] < ent->r.currentOrigin[2]) - { //move it up less so the decal is placed lower on the model then + // it's hacky, but we want to move it up so it's more likely to hit + // the torso. + if (missile->r.currentOrigin[2] < ent->r.currentOrigin[2]) { // move it up less so the decal is placed lower on the model then evEnt->s.origin2[2] += 8; - } - else - { + } else { evEnt->s.origin2[2] += 24; } - //Special col check + // Special col check evEnt->s.eventParm = 1; } } diff --git a/codemp/game/g_cvar.c b/codemp/game/g_cvar.c index ea8f8d0468..e3cbd3c6f5 100644 --- a/codemp/game/g_cvar.c +++ b/codemp/game/g_cvar.c @@ -33,56 +33,55 @@ static void CVU_Derpity( void ) { } */ - // // Cvar table // typedef struct cvarTable_s { - vmCvar_t *vmCvar; - char *cvarName; - char *defaultString; - void (*update)( void ); - uint32_t cvarFlags; - qboolean trackChange; // announce if value changes + vmCvar_t *vmCvar; + char *cvarName; + char *defaultString; + void (*update)(void); + uint32_t cvarFlags; + qboolean trackChange; // announce if value changes } cvarTable_t; #define XCVAR_DECL - #include "g_xcvar.h" +#include "g_xcvar.h" #undef XCVAR_DECL static const cvarTable_t gameCvarTable[] = { - #define XCVAR_LIST - #include "g_xcvar.h" - #undef XCVAR_LIST +#define XCVAR_LIST +#include "g_xcvar.h" +#undef XCVAR_LIST }; -static const size_t gameCvarTableSize = ARRAY_LEN( gameCvarTable ); +static const size_t gameCvarTableSize = ARRAY_LEN(gameCvarTable); -void G_RegisterCvars( void ) { +void G_RegisterCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=gameCvarTable; iCvar_Register( cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); - if ( cv->update ) + for (i = 0, cv = gameCvarTable; i < gameCvarTableSize; i++, cv++) { + trap->Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); + if (cv->update) cv->update(); } } -void G_UpdateCvars( void ) { +void G_UpdateCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=gameCvarTable; ivmCvar ) { + for (i = 0, cv = gameCvarTable; i < gameCvarTableSize; i++, cv++) { + if (cv->vmCvar) { int modCount = cv->vmCvar->modificationCount; - trap->Cvar_Update( cv->vmCvar ); - if ( cv->vmCvar->modificationCount != modCount ) { - if ( cv->update ) + trap->Cvar_Update(cv->vmCvar); + if (cv->vmCvar->modificationCount != modCount) { + if (cv->update) cv->update(); - if ( cv->trackChange ) - trap->SendServerCommand( -1, va("print \"Server: %s changed to %s\n\"", cv->cvarName, cv->vmCvar->string ) ); + if (cv->trackChange) + trap->SendServerCommand(-1, va("print \"Server: %s changed to %s\n\"", cv->cvarName, cv->vmCvar->string)); } } } diff --git a/codemp/game/g_exphysics.c b/codemp/game/g_exphysics.c index 3c556937f2..7beec2b52c 100644 --- a/codemp/game/g_exphysics.c +++ b/codemp/game/g_exphysics.c @@ -33,11 +33,10 @@ along with this program; if not, see . #define MAX_GRAVITY_PULL 512 -//Run physics on the object (purely origin-related) using custom epVelocity entity -//state value. Origin smoothing on the client is expected to compensate for choppy -//movement. -void G_RunExPhys(gentity_t *ent, float gravity, float mass, float bounce, qboolean autoKill, int *g2Bolts, int numG2Bolts) -{ +// Run physics on the object (purely origin-related) using custom epVelocity entity +// state value. Origin smoothing on the client is expected to compensate for choppy +// movement. +void G_RunExPhys(gentity_t *ent, float gravity, float mass, float bounce, qboolean autoKill, int *g2Bolts, int numG2Bolts) { trace_t tr; vec3_t projectedOrigin; vec3_t vNorm; @@ -47,70 +46,57 @@ void G_RunExPhys(gentity_t *ent, float gravity, float mass, float bounce, qboole assert(mass <= 1.0f && mass >= 0.01f); - if (gravity) - { //factor it in before we do anything. + if (gravity) { // factor it in before we do anything. VectorCopy(ent->r.currentOrigin, ground); ground[2] -= 0.1f; trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ground, ent->s.number, ent->clipmask, qfalse, 0, 0); - if (tr.fraction == 1.0f) - { + if (tr.fraction == 1.0f) { ent->s.groundEntityNum = ENTITYNUM_NONE; - } - else - { + } else { ent->s.groundEntityNum = tr.entityNum; } - if (ent->s.groundEntityNum == ENTITYNUM_NONE) - { + if (ent->s.groundEntityNum == ENTITYNUM_NONE) { ent->epGravFactor += gravity; - if (ent->epGravFactor > MAX_GRAVITY_PULL) - { //cap it off if needed + if (ent->epGravFactor > MAX_GRAVITY_PULL) { // cap it off if needed ent->epGravFactor = MAX_GRAVITY_PULL; } ent->epVelocity[2] -= ent->epGravFactor; - } - else - { //if we're sitting on something then reset the gravity factor. + } else { // if we're sitting on something then reset the gravity factor. ent->epGravFactor = 0; } } - if (!ent->epVelocity[0] && !ent->epVelocity[1] && !ent->epVelocity[2]) - { //nothing to do if we have no velocity even after gravity. - if (ent->touch) - { //call touch if we're in something + if (!ent->epVelocity[0] && !ent->epVelocity[1] && !ent->epVelocity[2]) { // nothing to do if we have no velocity even after gravity. + if (ent->touch) { // call touch if we're in something trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, ent->s.number, ent->clipmask, qfalse, 0, 0); - if (tr.startsolid || tr.allsolid) - { + if (tr.startsolid || tr.allsolid) { ent->touch(ent, &g_entities[tr.entityNum], &tr); } } return; } - //get the projected origin based on velocity. + // get the projected origin based on velocity. VectorMA(ent->r.currentOrigin, velScaling, ent->epVelocity, projectedOrigin); - VectorScale(ent->epVelocity, 1.0f-mass, ent->epVelocity); //scale it down based on mass + VectorScale(ent->epVelocity, 1.0f - mass, ent->epVelocity); // scale it down based on mass VectorCopy(ent->epVelocity, vNorm); vTotal = VectorNormalize(vNorm); - if (vTotal < 1 && ent->s.groundEntityNum != ENTITYNUM_NONE) - { //we've pretty much stopped moving anyway, just clear it out then. + if (vTotal < 1 && ent->s.groundEntityNum != ENTITYNUM_NONE) { // we've pretty much stopped moving anyway, just clear it out then. VectorClear(ent->epVelocity); ent->epGravFactor = 0; trap->LinkEntity((sharedEntity_t *)ent); return; } - if (ent->ghoul2 && g2Bolts) - { //Have we been passed a bolt index array to clip against points on the skeleton? + if (ent->ghoul2 && g2Bolts) { // Have we been passed a bolt index array to clip against points on the skeleton? vec3_t tMins, tMaxs; vec3_t trajDif; vec3_t gbmAngles; @@ -122,52 +108,43 @@ void G_RunExPhys(gentity_t *ent, float gravity, float mass, float bounce, qboole qboolean hasFirstCollision = qfalse; int i = 0; - //Maybe we could use a trap call and get the default radius for the bone specified, - //but this will do at least for now. + // Maybe we could use a trap call and get the default radius for the bone specified, + // but this will do at least for now. VectorSet(tMins, -3, -3, -3); VectorSet(tMaxs, 3, 3, 3); gbmAngles[PITCH] = gbmAngles[ROLL] = 0; gbmAngles[YAW] = ent->s.apos.trBase[YAW]; - //Get the difference relative to the entity origin and projected origin, to add to each bolt position. + // Get the difference relative to the entity origin and projected origin, to add to each bolt position. VectorSubtract(ent->r.currentOrigin, projectedOrigin, trajDif); - while (i < numG2Bolts) - { - //Get the position of the actual bolt for this frame + while (i < numG2Bolts) { + // Get the position of the actual bolt for this frame trap->G2API_GetBoltMatrix(ent->ghoul2, 0, g2Bolts[i], &matrix, gbmAngles, ent->r.currentOrigin, level.time, NULL, ent->modelScale); BG_GiveMeVectorFromMatrix(&matrix, ORIGIN, boneOrg); - //Now add the projected positional difference into the result + // Now add the projected positional difference into the result VectorAdd(boneOrg, trajDif, projectedBoneOrg); trap->Trace(&tr, boneOrg, tMins, tMaxs, projectedBoneOrg, ent->s.number, ent->clipmask, qfalse, 0, 0); - if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) - { //we've hit something - //Store the "deepest" collision we have - if (!hasFirstCollision) - { //don't have one yet so just use this one + if (tr.fraction != 1.0 || tr.startsolid || tr.allsolid) { // we've hit something + // Store the "deepest" collision we have + if (!hasFirstCollision) { // don't have one yet so just use this one bestCollision = tr; VectorCopy(boneOrg, collisionRootPos); hasFirstCollision = qtrue; - } - else - { - if (tr.allsolid && !bestCollision.allsolid) - { //If the whole trace is solid then this one is deeper + } else { + if (tr.allsolid && !bestCollision.allsolid) { // If the whole trace is solid then this one is deeper bestCollision = tr; VectorCopy(boneOrg, collisionRootPos); - } - else if (tr.startsolid && !bestCollision.startsolid && !bestCollision.allsolid) - { //Next deepest is if it's startsolid + } else if (tr.startsolid && !bestCollision.startsolid && !bestCollision.allsolid) { // Next deepest is if it's startsolid bestCollision = tr; VectorCopy(boneOrg, collisionRootPos); - } - else if (!bestCollision.startsolid && !bestCollision.allsolid && - tr.fraction < bestCollision.fraction) - { //and finally, if neither is startsolid/allsolid, but the new one has a smaller fraction, then it's closer to an impact point so we will use it + } else if (!bestCollision.startsolid && !bestCollision.allsolid && + tr.fraction < bestCollision.fraction) { // and finally, if neither is startsolid/allsolid, but the new one has a smaller + // fraction, then it's closer to an impact point so we will use it bestCollision = tr; VectorCopy(boneOrg, collisionRootPos); } @@ -177,73 +154,62 @@ void G_RunExPhys(gentity_t *ent, float gravity, float mass, float bounce, qboole i++; } - if (hasFirstCollision) - { //at least one bolt collided - //We'll get the offset between the collided bolt and endpos, then trace there - //from the origin so that our desired position becomes that point. + if (hasFirstCollision) { // at least one bolt collided + // We'll get the offset between the collided bolt and endpos, then trace there + // from the origin so that our desired position becomes that point. VectorSubtract(collisionRootPos, bestCollision.endpos, trajDif); VectorAdd(ent->r.currentOrigin, trajDif, projectedOrigin); } } - //If we didn't collide with any bolts projectedOrigin will still be the original desired - //projected position so all is well. If we did then projectedOrigin will be modified - //to provide us with a relative position which does not place the bolt in a solid. + // If we didn't collide with any bolts projectedOrigin will still be the original desired + // projected position so all is well. If we did then projectedOrigin will be modified + // to provide us with a relative position which does not place the bolt in a solid. trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, projectedOrigin, ent->s.number, ent->clipmask, qfalse, 0, 0); - if (tr.startsolid || tr.allsolid) - { //can't go anywhere from here + if (tr.startsolid || tr.allsolid) { // can't go anywhere from here #ifdef _DEBUG Com_Printf("ExPhys object in solid (%i)\n", ent->s.number); #endif - if (autoKill) - { + if (autoKill) { ent->think = G_FreeEntity; ent->nextthink = level.time; } return; } - //Go ahead and set it to the trace endpoint regardless of what it hit + // Go ahead and set it to the trace endpoint regardless of what it hit G_SetOrigin(ent, tr.endpos); trap->LinkEntity((sharedEntity_t *)ent); - if (tr.fraction == 1.0f) - { //Nothing was in the way. + if (tr.fraction == 1.0f) { // Nothing was in the way. return; } - if (bounce) - { - vTotal *= bounce; //scale it by bounce + if (bounce) { + vTotal *= bounce; // scale it by bounce - VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + VectorScale(tr.plane.normal, vTotal, vNorm); // scale the trace plane normal by the bounce factor - if (vNorm[2] > 0) - { - ent->epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. - if (ent->epGravFactor < 0) - { + if (vNorm[2] > 0) { + ent->epGravFactor -= vNorm[2] * (1.0f - mass); // The lighter it is the more gravity will be reduced by bouncing vertically. + if (ent->epGravFactor < 0) { ent->epGravFactor = 0; } } - //call touch first so we can check velocity upon impact if we want - if (tr.entityNum != ENTITYNUM_NONE && ent->touch) - { //then call the touch function + // call touch first so we can check velocity upon impact if we want + if (tr.entityNum != ENTITYNUM_NONE && ent->touch) { // then call the touch function ent->touch(ent, &g_entities[tr.entityNum], &tr); } - VectorAdd(ent->epVelocity, vNorm, ent->epVelocity); //add it into the existing velocity. - } - else - { //if no bounce, kill when it hits something. + VectorAdd(ent->epVelocity, vNorm, ent->epVelocity); // add it into the existing velocity. + } else { // if no bounce, kill when it hits something. ent->epVelocity[0] = 0; ent->epVelocity[1] = 0; - if (!gravity) - { + if (!gravity) { ent->epVelocity[2] = 0; } } diff --git a/codemp/game/g_items.c b/codemp/game/g_items.c index 14d76df705..28388793af 100644 --- a/codemp/game/g_items.c +++ b/codemp/game/g_items.c @@ -38,96 +38,78 @@ along with this program; if not, see . movers and respawn appropriately. */ - -#define RESPAWN_ARMOR 20 -#define RESPAWN_TEAM_WEAPON 30 -#define RESPAWN_HEALTH 30 -#define RESPAWN_AMMO 40 -#define RESPAWN_HOLDABLE 60 -#define RESPAWN_MEGAHEALTH 120 -#define RESPAWN_POWERUP 120 +#define RESPAWN_ARMOR 20 +#define RESPAWN_TEAM_WEAPON 30 +#define RESPAWN_HEALTH 30 +#define RESPAWN_AMMO 40 +#define RESPAWN_HOLDABLE 60 +#define RESPAWN_MEGAHEALTH 120 +#define RESPAWN_POWERUP 120 // Item Spawn flags -#define ITMSF_SUSPEND 1 -#define ITMSF_NOPLAYER 2 -#define ITMSF_ALLOWNPC 4 -#define ITMSF_NOTSOLID 8 -#define ITMSF_VERTICAL 16 -#define ITMSF_INVISIBLE 32 +#define ITMSF_SUSPEND 1 +#define ITMSF_NOPLAYER 2 +#define ITMSF_ALLOWNPC 4 +#define ITMSF_NOTSOLID 8 +#define ITMSF_VERTICAL 16 +#define ITMSF_INVISIBLE 32 extern gentity_t *droppedRedFlag; extern gentity_t *droppedBlueFlag; - //====================================================================== -#define MAX_MEDPACK_HEAL_AMOUNT 25 -#define MAX_MEDPACK_BIG_HEAL_AMOUNT 50 -#define MAX_SENTRY_DISTANCE 256 +#define MAX_MEDPACK_HEAL_AMOUNT 25 +#define MAX_MEDPACK_BIG_HEAL_AMOUNT 50 +#define MAX_SENTRY_DISTANCE 256 // For more than four players, adjust the respawn times, up to 1/4. -int adjustRespawnTime(float preRespawnTime, int itemType, int itemTag) -{ +int adjustRespawnTime(float preRespawnTime, int itemType, int itemTag) { float respawnTime = preRespawnTime; - if (itemType == IT_WEAPON) - { - if (itemTag == WP_THERMAL || - itemTag == WP_TRIP_MINE || - itemTag == WP_DET_PACK) - { //special case for these, use ammo respawn rate + if (itemType == IT_WEAPON) { + if (itemTag == WP_THERMAL || itemTag == WP_TRIP_MINE || itemTag == WP_DET_PACK) { // special case for these, use ammo respawn rate respawnTime = RESPAWN_AMMO; } } - if (!g_adaptRespawn.integer) - { - return((int)respawnTime); + if (!g_adaptRespawn.integer) { + return ((int)respawnTime); } - if (level.numPlayingClients > 4) - { // Start scaling the respawn times. - if (level.numPlayingClients > 32) - { // 1/4 time minimum. + if (level.numPlayingClients > 4) { // Start scaling the respawn times. + if (level.numPlayingClients > 32) { // 1/4 time minimum. respawnTime *= 0.25; - } - else if (level.numPlayingClients > 12) - { // From 12-32, scale from 0.5 to 0.25; + } else if (level.numPlayingClients > 12) { // From 12-32, scale from 0.5 to 0.25; respawnTime *= 20.0 / (float)(level.numPlayingClients + 8); - } - else - { // From 4-12, scale from 1.0 to 0.5; + } else { // From 4-12, scale from 1.0 to 0.5; respawnTime *= 8.0 / (float)(level.numPlayingClients + 4); } } - if (respawnTime < 1.0) - { // No matter what, don't go lower than 1 second, or the pickups become very noisy! + if (respawnTime < 1.0) { // No matter what, don't go lower than 1 second, or the pickups become very noisy! respawnTime = 1.0; } return ((int)respawnTime); } +#define SHIELD_HEALTH 250 +#define SHIELD_HEALTH_DEC 10 // 25 seconds +#define MAX_SHIELD_HEIGHT 254 +#define MAX_SHIELD_HALFWIDTH 255 +#define SHIELD_HALFTHICKNESS 4 +#define SHIELD_PLACEDIST 64 -#define SHIELD_HEALTH 250 -#define SHIELD_HEALTH_DEC 10 // 25 seconds -#define MAX_SHIELD_HEIGHT 254 -#define MAX_SHIELD_HALFWIDTH 255 -#define SHIELD_HALFTHICKNESS 4 -#define SHIELD_PLACEDIST 64 - -#define SHIELD_SIEGE_HEALTH 2000 -#define SHIELD_SIEGE_HEALTH_DEC (SHIELD_SIEGE_HEALTH/25) // still 25 seconds. - -static qhandle_t shieldLoopSound=0; -static qhandle_t shieldAttachSound=0; -static qhandle_t shieldActivateSound=0; -static qhandle_t shieldDeactivateSound=0; -static qhandle_t shieldDamageSound=0; +#define SHIELD_SIEGE_HEALTH 2000 +#define SHIELD_SIEGE_HEALTH_DEC (SHIELD_SIEGE_HEALTH / 25) // still 25 seconds. +static qhandle_t shieldLoopSound = 0; +static qhandle_t shieldAttachSound = 0; +static qhandle_t shieldActivateSound = 0; +static qhandle_t shieldDeactivateSound = 0; +static qhandle_t shieldDamageSound = 0; -void ShieldRemove(gentity_t *self) -{ +void ShieldRemove(gentity_t *self) { self->think = G_FreeEntity; self->nextthink = level.time + 100; @@ -139,42 +121,32 @@ void ShieldRemove(gentity_t *self) return; } - // Count down the health of the shield. -void ShieldThink(gentity_t *self) -{ +void ShieldThink(gentity_t *self) { self->s.trickedentindex = 0; - if ( level.gametype == GT_SIEGE ) - { + if (level.gametype == GT_SIEGE) { self->health -= SHIELD_SIEGE_HEALTH_DEC; - } - else - { + } else { self->health -= SHIELD_HEALTH_DEC; } self->nextthink = level.time + 1000; - if (self->health <= 0) - { + if (self->health <= 0) { ShieldRemove(self); } return; } - // The shield was damaged to below zero health. -void ShieldDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void ShieldDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { // Play damaging sound... G_AddEvent(self, EV_GENERAL_SOUND, shieldDamageSound); ShieldRemove(self); } - // The shield had damage done to it. Make it flicker. -void ShieldPain(gentity_t *self, gentity_t *attacker, int damage) -{ +void ShieldPain(gentity_t *self, gentity_t *attacker, int damage) { // Set the itemplaceholder flag to indicate the the shield drawing that the shield pain should be drawn. self->think = ShieldThink; self->nextthink = level.time + 400; @@ -187,29 +159,23 @@ void ShieldPain(gentity_t *self, gentity_t *attacker, int damage) return; } - // Try to turn the shield back on after a delay. -void ShieldGoSolid(gentity_t *self) -{ - trace_t tr; +void ShieldGoSolid(gentity_t *self) { + trace_t tr; // see if we're valid self->health--; - if (self->health <= 0) - { + if (self->health <= 0) { ShieldRemove(self); return; } - trap->Trace (&tr, self->r.currentOrigin, self->r.mins, self->r.maxs, self->r.currentOrigin, self->s.number, CONTENTS_BODY, qfalse, 0, 0 ); - if(tr.startsolid) - { // gah, we can't activate yet + trap->Trace(&tr, self->r.currentOrigin, self->r.mins, self->r.maxs, self->r.currentOrigin, self->s.number, CONTENTS_BODY, qfalse, 0, 0); + if (tr.startsolid) { // gah, we can't activate yet self->nextthink = level.time + 200; self->think = ShieldGoSolid; trap->LinkEntity((sharedEntity_t *)self); - } - else - { // get hard... huh-huh... + } else { // get hard... huh-huh... self->s.eFlags &= ~EF_NODRAW; self->r.contents = CONTENTS_SOLID; @@ -227,10 +193,8 @@ void ShieldGoSolid(gentity_t *self) return; } - // Turn the shield off to allow a friend to pass through. -void ShieldGoNotSolid(gentity_t *self) -{ +void ShieldGoNotSolid(gentity_t *self) { // make the shield non-solid very briefly self->r.contents = 0; self->s.eFlags |= EF_NODRAW; @@ -246,45 +210,35 @@ void ShieldGoNotSolid(gentity_t *self) self->s.loopIsSoundset = qfalse; } - // Somebody (a player) has touched the shield. See if it is a "friend". -void ShieldTouch(gentity_t *self, gentity_t *other, trace_t *trace) -{ - if (level.gametype >= GT_TEAM) - { // let teammates through +void ShieldTouch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (level.gametype >= GT_TEAM) { // let teammates through // compare the parent's team to the "other's" team - if (self->parent && ( self->parent->client) && (other->client)) - { - if (OnSameTeam(self->parent, other)) - { + if (self->parent && (self->parent->client) && (other->client)) { + if (OnSameTeam(self->parent, other)) { ShieldGoNotSolid(self); } } - } - else - {//let the person who dropped the shield through - if (self->parent && self->parent->s.number == other->s.number) - { + } else { // let the person who dropped the shield through + if (self->parent && self->parent->s.number == other->s.number) { ShieldGoNotSolid(self); } } } - // After a short delay, create the shield by expanding in all directions. -void CreateShield(gentity_t *ent) -{ - trace_t tr; - vec3_t mins, maxs, end, posTraceEnd, negTraceEnd, start; - int height, posWidth, negWidth, halfWidth = 0; - qboolean xaxis; - int paramData = 0; -// static int shieldID; +void CreateShield(gentity_t *ent) { + trace_t tr; + vec3_t mins, maxs, end, posTraceEnd, negTraceEnd, start; + int height, posWidth, negWidth, halfWidth = 0; + qboolean xaxis; + int paramData = 0; + // static int shieldID; // trace upward to find height of shield VectorCopy(ent->r.currentOrigin, end); end[2] += MAX_SHIELD_HEIGHT; - trap->Trace (&tr, ent->r.currentOrigin, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, ent->r.currentOrigin, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); height = (int)(MAX_SHIELD_HEIGHT * tr.fraction); // use angles to find the proper axis along which to align the shield @@ -295,81 +249,70 @@ void CreateShield(gentity_t *ent) if ((int)(ent->s.angles[YAW]) == 0) // shield runs along y-axis { - posTraceEnd[1]+=MAX_SHIELD_HALFWIDTH; - negTraceEnd[1]-=MAX_SHIELD_HALFWIDTH; + posTraceEnd[1] += MAX_SHIELD_HALFWIDTH; + negTraceEnd[1] -= MAX_SHIELD_HALFWIDTH; xaxis = qfalse; - } - else // shield runs along x-axis + } else // shield runs along x-axis { - posTraceEnd[0]+=MAX_SHIELD_HALFWIDTH; - negTraceEnd[0]-=MAX_SHIELD_HALFWIDTH; + posTraceEnd[0] += MAX_SHIELD_HALFWIDTH; + negTraceEnd[0] -= MAX_SHIELD_HALFWIDTH; xaxis = qtrue; } // trace horizontally to find extend of shield // positive trace VectorCopy(ent->r.currentOrigin, start); - start[2] += (height>>1); - trap->Trace (&tr, start, 0, 0, posTraceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + start[2] += (height >> 1); + trap->Trace(&tr, start, 0, 0, posTraceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0); posWidth = MAX_SHIELD_HALFWIDTH * tr.fraction; // negative trace - trap->Trace (&tr, start, 0, 0, negTraceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, start, 0, 0, negTraceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0); negWidth = MAX_SHIELD_HALFWIDTH * tr.fraction; // kef -- monkey with dimensions and place origin in center - halfWidth = (posWidth + negWidth)>>1; - if (xaxis) - { + halfWidth = (posWidth + negWidth) >> 1; + if (xaxis) { ent->r.currentOrigin[0] = ent->r.currentOrigin[0] - negWidth + halfWidth; - } - else - { + } else { ent->r.currentOrigin[1] = ent->r.currentOrigin[1] - negWidth + halfWidth; } - ent->r.currentOrigin[2] += (height>>1); + ent->r.currentOrigin[2] += (height >> 1); // set entity's mins and maxs to new values, make it solid, and link it - if (xaxis) - { - VectorSet(ent->r.mins, -halfWidth, -SHIELD_HALFTHICKNESS, -(height>>1)); - VectorSet(ent->r.maxs, halfWidth, SHIELD_HALFTHICKNESS, height>>1); - } - else - { - VectorSet(ent->r.mins, -SHIELD_HALFTHICKNESS, -halfWidth, -(height>>1)); + if (xaxis) { + VectorSet(ent->r.mins, -halfWidth, -SHIELD_HALFTHICKNESS, -(height >> 1)); + VectorSet(ent->r.maxs, halfWidth, SHIELD_HALFTHICKNESS, height >> 1); + } else { + VectorSet(ent->r.mins, -SHIELD_HALFTHICKNESS, -halfWidth, -(height >> 1)); VectorSet(ent->r.maxs, SHIELD_HALFTHICKNESS, halfWidth, height); } ent->clipmask = MASK_SHOT; // Information for shield rendering. -// xaxis - 1 bit -// height - 0-254 8 bits -// posWidth - 0-255 8 bits -// negWidth - 0 - 255 8 bits + // xaxis - 1 bit + // height - 0-254 8 bits + // posWidth - 0-255 8 bits + // negWidth - 0 - 255 8 bits paramData = (xaxis << 24) | (height << 16) | (posWidth << 8) | (negWidth); ent->s.time2 = paramData; - if ( level.gametype == GT_SIEGE ) - { - ent->health = ceil((float)(SHIELD_SIEGE_HEALTH*1)); - } - else - { - ent->health = ceil((float)(SHIELD_HEALTH*1)); + if (level.gametype == GT_SIEGE) { + ent->health = ceil((float)(SHIELD_SIEGE_HEALTH * 1)); + } else { + ent->health = ceil((float)(SHIELD_HEALTH * 1)); } - ent->s.time = ent->health;//??? + ent->s.time = ent->health; //??? ent->pain = ShieldPain; ent->die = ShieldDie; ent->touch = ShieldTouch; // see if we're valid - trap->Trace (&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, ent->s.number, CONTENTS_BODY, qfalse, 0, 0 ); + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, ent->s.number, CONTENTS_BODY, qfalse, 0, 0); - if (tr.startsolid) - { // Something in the way! + if (tr.startsolid) { // Something in the way! // make the shield non-solid very briefly ent->r.contents = 0; ent->s.eFlags |= EF_NODRAW; @@ -378,10 +321,8 @@ void CreateShield(gentity_t *ent) ent->think = ShieldGoSolid; ent->takedamage = qfalse; trap->LinkEntity((sharedEntity_t *)ent); - } - else - { // Get solid. - ent->r.contents = CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP;//CONTENTS_SOLID; + } else { // Get solid. + ent->r.contents = CONTENTS_PLAYERCLIP | CONTENTS_SHOTCLIP; // CONTENTS_SOLID; ent->nextthink = level.time; ent->think = ShieldThink; @@ -400,16 +341,14 @@ void CreateShield(gentity_t *ent) return; } -qboolean PlaceShield(gentity_t *playerent) -{ +qboolean PlaceShield(gentity_t *playerent) { static const gitem_t *shieldItem = NULL; - gentity_t *shield = NULL; - trace_t tr; - vec3_t fwd, pos, dest, mins = {-4,-4, 0}, maxs = {4,4,4}; + gentity_t *shield = NULL; + trace_t tr; + vec3_t fwd, pos, dest, mins = {-4, -4, 0}, maxs = {4, 4, 4}; static qboolean registered = qfalse; - if ( !registered ) - { + if (!registered) { shieldLoopSound = G_SoundIndex("sound/movers/doors/forcefield_lp.wav"); shieldAttachSound = G_SoundIndex("sound/weapons/detpack/stick.wav"); shieldActivateSound = G_SoundIndex("sound/movers/doors/forcefield_on.wav"); @@ -420,65 +359,57 @@ qboolean PlaceShield(gentity_t *playerent) } // can we place this in front of us? - AngleVectors (playerent->client->ps.viewangles, fwd, NULL, NULL); + AngleVectors(playerent->client->ps.viewangles, fwd, NULL, NULL); fwd[2] = 0; VectorMA(playerent->client->ps.origin, SHIELD_PLACEDIST, fwd, dest); - trap->Trace (&tr, playerent->client->ps.origin, mins, maxs, dest, playerent->s.number, MASK_SHOT, qfalse, 0, 0 ); - if (tr.fraction > 0.9) - {//room in front + trap->Trace(&tr, playerent->client->ps.origin, mins, maxs, dest, playerent->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction > 0.9) { // room in front VectorCopy(tr.endpos, pos); // drop to floor - VectorSet( dest, pos[0], pos[1], pos[2] - 4096 ); - trap->Trace( &tr, pos, mins, maxs, dest, playerent->s.number, MASK_SOLID, qfalse, 0, 0 ); - if ( !tr.startsolid && !tr.allsolid ) - { + VectorSet(dest, pos[0], pos[1], pos[2] - 4096); + trap->Trace(&tr, pos, mins, maxs, dest, playerent->s.number, MASK_SOLID, qfalse, 0, 0); + if (!tr.startsolid && !tr.allsolid) { // got enough room so place the portable shield shield = G_Spawn(); // Figure out what direction the shield is facing. - if (fabs(fwd[0]) > fabs(fwd[1])) - { // shield is north/south, facing east. + if (fabs(fwd[0]) > fabs(fwd[1])) { // shield is north/south, facing east. shield->s.angles[YAW] = 0; - } - else - { // shield is along the east/west axis, facing north + } else { // shield is along the east/west axis, facing north shield->s.angles[YAW] = 90; } shield->think = CreateShield; - shield->nextthink = level.time + 500; // power up after .5 seconds + shield->nextthink = level.time + 500; // power up after .5 seconds shield->parent = playerent; // Set team number. shield->s.otherEntityNum2 = playerent->client->sess.sessionTeam; shield->s.eType = ET_SPECIAL; - shield->s.modelindex = HI_SHIELD; // this'll be used in CG_Useable() for rendering. + shield->s.modelindex = HI_SHIELD; // this'll be used in CG_Useable() for rendering. shield->classname = shieldItem->classname; shield->r.contents = CONTENTS_TRIGGER; shield->touch = 0; // using an item causes it to respawn - shield->use = 0; //Use_Item; + shield->use = 0; // Use_Item; // allow to ride movers shield->s.groundEntityNum = tr.entityNum; - G_SetOrigin( shield, tr.endpos ); + G_SetOrigin(shield, tr.endpos); shield->s.eFlags &= ~EF_NODRAW; shield->r.svFlags &= ~SVF_NOCLIENT; - trap->LinkEntity ((sharedEntity_t *)shield); + trap->LinkEntity((sharedEntity_t *)shield); shield->s.owner = playerent->s.number; shield->s.shouldtarget = qtrue; - if (level.gametype >= GT_TEAM) - { + if (level.gametype >= GT_TEAM) { shield->s.teamowner = playerent->client->sess.sessionTeam; - } - else - { + } else { shield->s.teamowner = 16; } @@ -492,15 +423,12 @@ qboolean PlaceShield(gentity_t *playerent) return qfalse; } -void ItemUse_Binoculars(gentity_t *ent) -{ - if (!ent || !ent->client) - { +void ItemUse_Binoculars(gentity_t *ent) { + if (!ent || !ent->client) { return; } - if (ent->client->ps.weaponstate != WEAPON_READY) - { //So we can't fool it and reactivate while switching to the saber or something. + if (ent->client->ps.weaponstate != WEAPON_READY) { // So we can't fool it and reactivate while switching to the saber or something. return; } @@ -516,32 +444,24 @@ void ItemUse_Binoculars(gentity_t *ent) ent->client->ps.zoomMode = 2; ent->client->ps.zoomLocked = qfalse; ent->client->ps.zoomFov = 40.0f; - } - else if (ent->client->ps.zoomMode == 2) - { + } else if (ent->client->ps.zoomMode == 2) { ent->client->ps.zoomMode = 0; ent->client->ps.zoomTime = level.time; } } -void ItemUse_Shield(gentity_t *ent) -{ - PlaceShield(ent); -} +void ItemUse_Shield(gentity_t *ent) { PlaceShield(ent); } //-------------------------- // PERSONAL ASSAULT SENTRY //-------------------------- -#define PAS_DAMAGE 2 +#define PAS_DAMAGE 2 -void SentryTouch(gentity_t *ent, gentity_t *other, trace_t *trace) -{ - return; -} +void SentryTouch(gentity_t *ent, gentity_t *other, trace_t *trace) { return; } //---------------------------------------------------------------- -void pas_fire( gentity_t *ent ) +void pas_fire(gentity_t *ent) //---------------------------------------------------------------- { vec3_t fwd, myOrg, enOrg; @@ -555,11 +475,11 @@ void pas_fire( gentity_t *ent ) VectorSubtract(enOrg, myOrg, fwd); VectorNormalize(fwd); - myOrg[0] += fwd[0]*16; - myOrg[1] += fwd[1]*16; - myOrg[2] += fwd[2]*16; + myOrg[0] += fwd[0] * 16; + myOrg[1] += fwd[1] * 16; + myOrg[2] += fwd[2] * 16; - WP_FireTurretMissile(&g_entities[ent->genericValue3], myOrg, fwd, qfalse, 10, 2300, MOD_SENTRY, ent ); + WP_FireTurretMissile(&g_entities[ent->genericValue3], myOrg, fwd, qfalse, 10, 2300, MOD_SENTRY, ent); G_RunObject(ent); } @@ -567,91 +487,77 @@ void pas_fire( gentity_t *ent ) #define TURRET_RADIUS 800 //----------------------------------------------------- -static qboolean pas_find_enemies( gentity_t *self ) +static qboolean pas_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int count, i; - float bestDist = TURRET_RADIUS*TURRET_RADIUS; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target; - trace_t tr; - - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + qboolean found = qfalse; + int count, i; + float bestDist = TURRET_RADIUS * TURRET_RADIUS; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target; + trace_t tr; + + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - G_Sound(self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/chars/turret/ping.wav")); self->painDebounceTime = level.time + 1000; } } VectorCopy(self->s.pos.trBase, org2); - count = G_RadiusList( org2, TURRET_RADIUS, self, qtrue, entity_list ); + count = G_RadiusList(org2, TURRET_RADIUS, self, qtrue, entity_list); - for ( i = 0; i < count; i++ ) - { + for (i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( self->alliedTeam && target->client->sess.sessionTeam == self->alliedTeam ) - { + if (self->alliedTeam && target->client->sess.sessionTeam == self->alliedTeam) { continue; } - if (self->genericValue3 == target->s.number) - { + if (self->genericValue3 == target->s.number) { continue; } - if ( !trap->InPVS( org2, target->r.currentOrigin )) - { + if (!trap->InPVS(org2, target->r.currentOrigin)) { continue; } - if (target->s.eType == ET_NPC && - target->s.NPC_class == CLASS_VEHICLE) - { //don't get mad at vehicles, silly. + if (target->s.eType == ET_NPC && target->s.NPC_class == CLASS_VEHICLE) { // don't get mad at vehicles, silly. continue; } - if ( target->client ) - { - VectorCopy( target->client->ps.origin, org ); - } - else - { - VectorCopy( target->r.currentOrigin, org ); + if (target->client) { + VectorCopy(target->client->ps.origin, org); + } else { + VectorCopy(target->r.currentOrigin, org); } - trap->Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->r.currentOrigin, self->r.currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->r.currentOrigin, self->r.currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist )// all things equal, keep current + if (enemyDist < bestDist) // all things equal, keep current { - if ( self->attackDebounceTime + 100 < level.time ) - { + if (self->attackDebounceTime + 100 < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/chars/turret/startup.wav")); // Wind up turrets for a bit self->attackDebounceTime = level.time + 900 + Q_flrand(0.0f, 1.0f) * 200; } - G_SetEnemy( self, target ); + G_SetEnemy(self, target); bestDist = enemyDist; found = qtrue; } @@ -662,53 +568,43 @@ static qboolean pas_find_enemies( gentity_t *self ) } //--------------------------------- -void pas_adjust_enemy( gentity_t *ent ) +void pas_adjust_enemy(gentity_t *ent) //--------------------------------- { - trace_t tr; + trace_t tr; qboolean keep = qtrue; - if ( ent->enemy->health <= 0 ) - { + if (ent->enemy->health <= 0) { keep = qfalse; - } - else - { - vec3_t org, org2; + } else { + vec3_t org, org2; VectorCopy(ent->s.pos.trBase, org2); - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->ps.origin, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->ps.origin, org); org[2] -= 15; - } - else - { - VectorCopy( ent->enemy->r.currentOrigin, org ); + } else { + VectorCopy(ent->enemy->r.currentOrigin, org); } - trap->Trace( &tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, ent->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 0.9f || tr.entityNum == ent->s.number ) - { - if (tr.entityNum != ent->enemy->s.number) - { + if (tr.allsolid || tr.startsolid || tr.fraction < 0.9f || tr.entityNum == ent->s.number) { + if (tr.entityNum != ent->enemy->s.number) { // trace failed keep = qfalse; } } } - if ( keep ) - { - //ent->bounceCount = level.time + 500 + Q_flrand(0.0f, 1.0f) * 150; - } - else if ( ent->bounceCount < level.time && ent->enemy ) // don't ping pong on and off + if (keep) { + // ent->bounceCount = level.time + 500 + Q_flrand(0.0f, 1.0f) * 150; + } else if (ent->bounceCount < level.time && ent->enemy) // don't ping pong on and off { ent->enemy = NULL; // shut-down sound - G_Sound( ent, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + G_Sound(ent, CHAN_BODY, G_SoundIndex("sound/chars/turret/shutdown.wav")); ent->bounceCount = level.time + 500 + Q_flrand(0.0f, 1.0f) * 150; @@ -722,49 +618,42 @@ void pas_adjust_enemy( gentity_t *ent ) void turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod); -void sentryExpire(gentity_t *self) -{ - turret_die(self, self, self, 1000, MOD_UNKNOWN); -} +void sentryExpire(gentity_t *self) { turret_die(self, self, self, 1000, MOD_UNKNOWN); } //--------------------------------- -void pas_think( gentity_t *ent ) +void pas_think(gentity_t *ent) //--------------------------------- { - qboolean moved; - float diffYaw, diffPitch; - vec3_t enemyDir, org; - vec3_t frontAngles, backAngles; - vec3_t desiredAngles; - int iEntityList[MAX_GENTITIES]; - int numListedEntities; - int i = 0; - qboolean clTrapped = qfalse; - vec3_t testMins, testMaxs; - - testMins[0] = ent->r.currentOrigin[0] + ent->r.mins[0]+4; - testMins[1] = ent->r.currentOrigin[1] + ent->r.mins[1]+4; - testMins[2] = ent->r.currentOrigin[2] + ent->r.mins[2]+4; - - testMaxs[0] = ent->r.currentOrigin[0] + ent->r.maxs[0]-4; - testMaxs[1] = ent->r.currentOrigin[1] + ent->r.maxs[1]-4; - testMaxs[2] = ent->r.currentOrigin[2] + ent->r.maxs[2]-4; - - numListedEntities = trap->EntitiesInBox( testMins, testMaxs, iEntityList, MAX_GENTITIES ); - - while (i < numListedEntities) - { - if (iEntityList[i] < MAX_CLIENTS) - { //client stuck inside me. go nonsolid. + qboolean moved; + float diffYaw, diffPitch; + vec3_t enemyDir, org; + vec3_t frontAngles, backAngles; + vec3_t desiredAngles; + int iEntityList[MAX_GENTITIES]; + int numListedEntities; + int i = 0; + qboolean clTrapped = qfalse; + vec3_t testMins, testMaxs; + + testMins[0] = ent->r.currentOrigin[0] + ent->r.mins[0] + 4; + testMins[1] = ent->r.currentOrigin[1] + ent->r.mins[1] + 4; + testMins[2] = ent->r.currentOrigin[2] + ent->r.mins[2] + 4; + + testMaxs[0] = ent->r.currentOrigin[0] + ent->r.maxs[0] - 4; + testMaxs[1] = ent->r.currentOrigin[1] + ent->r.maxs[1] - 4; + testMaxs[2] = ent->r.currentOrigin[2] + ent->r.maxs[2] - 4; + + numListedEntities = trap->EntitiesInBox(testMins, testMaxs, iEntityList, MAX_GENTITIES); + + while (i < numListedEntities) { + if (iEntityList[i] < MAX_CLIENTS) { // client stuck inside me. go nonsolid. int clNum = iEntityList[i]; - numListedEntities = trap->EntitiesInBox( g_entities[clNum].r.absmin, g_entities[clNum].r.absmax, iEntityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(g_entities[clNum].r.absmin, g_entities[clNum].r.absmax, iEntityList, MAX_GENTITIES); i = 0; - while (i < numListedEntities) - { - if (iEntityList[i] == ent->s.number) - { + while (i < numListedEntities) { + if (iEntityList[i] == ent->s.number) { clTrapped = qtrue; break; } @@ -776,38 +665,32 @@ void pas_think( gentity_t *ent ) i++; } - if (clTrapped) - { + if (clTrapped) { ent->r.contents = 0; ent->s.fireflag = 0; ent->nextthink = level.time + FRAMETIME; return; - } - else - { + } else { ent->r.contents = CONTENTS_SOLID; } if (!g_entities[ent->genericValue3].inuse || !g_entities[ent->genericValue3].client || - g_entities[ent->genericValue3].client->sess.sessionTeam != ent->genericValue2) - { + g_entities[ent->genericValue3].client->sess.sessionTeam != ent->genericValue2) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; } -// G_RunObject(ent); + // G_RunObject(ent); - if ( !ent->damage ) - { + if (!ent->damage) { ent->damage = 1; ent->nextthink = level.time + FRAMETIME; return; } - if ((ent->genericValue8+TURRET_LIFETIME) < level.time) - { - G_Sound( ent, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + if ((ent->genericValue8 + TURRET_LIFETIME) < level.time) { + G_Sound(ent, CHAN_BODY, G_SoundIndex("sound/chars/turret/shutdown.wav")); ent->s.bolt2 = ENTITYNUM_NONE; ent->s.fireflag = 2; @@ -818,143 +701,109 @@ void pas_think( gentity_t *ent ) ent->nextthink = level.time + FRAMETIME; - if ( ent->enemy ) - { + if (ent->enemy) { // make sure that the enemy is still valid - pas_adjust_enemy( ent ); + pas_adjust_enemy(ent); } - if (ent->enemy) - { - if (!ent->enemy->client) - { + if (ent->enemy) { + if (!ent->enemy->client) { ent->enemy = NULL; - } - else if (ent->enemy->s.number == ent->s.number) - { + } else if (ent->enemy->s.number == ent->s.number) { ent->enemy = NULL; - } - else if (ent->enemy->health < 1) - { + } else if (ent->enemy->health < 1) { ent->enemy = NULL; } } - if ( !ent->enemy ) - { - pas_find_enemies( ent ); + if (!ent->enemy) { + pas_find_enemies(ent); } - if (ent->enemy) - { + if (ent->enemy) { ent->s.bolt2 = ent->enemy->s.number; - } - else - { + } else { ent->s.bolt2 = ENTITYNUM_NONE; } moved = qfalse; - diffYaw = 0.0f; diffPitch = 0.0f; + diffYaw = 0.0f; + diffPitch = 0.0f; - ent->speed = AngleNormalize360( ent->speed ); - ent->random = AngleNormalize360( ent->random ); + ent->speed = AngleNormalize360(ent->speed); + ent->random = AngleNormalize360(ent->random); - if ( ent->enemy ) - { + if (ent->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( ent->enemy->client ) - { - VectorCopy( ent->enemy->client->ps.origin, org ); - } - else - { - VectorCopy( ent->enemy->r.currentOrigin, org ); + if (ent->enemy->client) { + VectorCopy(ent->enemy->client->ps.origin, org); + } else { + VectorCopy(ent->enemy->r.currentOrigin, org); } - VectorSubtract( org, ent->r.currentOrigin, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, ent->r.currentOrigin, enemyDir); + vectoangles(enemyDir, desiredAngles); - diffYaw = AngleSubtract( ent->speed, desiredAngles[YAW] ); - diffPitch = AngleSubtract( ent->random, desiredAngles[PITCH] ); - } - else - { + diffYaw = AngleSubtract(ent->speed, desiredAngles[YAW]); + diffPitch = AngleSubtract(ent->random, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one - diffYaw = sin( level.time * 0.0001f + ent->count ) * 2.0f; + diffYaw = sin(level.time * 0.0001f + ent->count) * 2.0f; } - if ( fabs(diffYaw) > 0.25f ) - { + if (fabs(diffYaw) > 0.25f) { moved = qtrue; - if ( fabs(diffYaw) > 10.0f ) - { + if (fabs(diffYaw) > 10.0f) { // cap max speed ent->speed += (diffYaw > 0.0f) ? -10.0f : 10.0f; - } - else - { + } else { // small enough ent->speed -= diffYaw; } } - - if ( fabs(diffPitch) > 0.25f ) - { + if (fabs(diffPitch) > 0.25f) { moved = qtrue; - if ( fabs(diffPitch) > 4.0f ) - { + if (fabs(diffPitch) > 4.0f) { // cap max speed ent->random += (diffPitch > 0.0f) ? -4.0f : 4.0f; - } - else - { + } else { // small enough ent->random -= diffPitch; } } // the bone axes are messed up, so hence some dumbness here - VectorSet( frontAngles, -ent->random, 0.0f, 0.0f ); - VectorSet( backAngles, 0.0f, 0.0f, ent->speed ); + VectorSet(frontAngles, -ent->random, 0.0f, 0.0f); + VectorSet(backAngles, 0.0f, 0.0f, ent->speed); - if ( moved ) - { - //ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); - } - else - { + if (moved) { + // ent->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); + } else { ent->s.loopSound = 0; ent->s.loopIsSoundset = qfalse; } - if ( ent->enemy && ent->attackDebounceTime < level.time ) - { + if (ent->enemy && ent->attackDebounceTime < level.time) { ent->count--; - if ( ent->count ) - { - pas_fire( ent ); + if (ent->count) { + pas_fire(ent); ent->s.fireflag = 1; ent->attackDebounceTime = level.time + 200; - } - else - { - //ent->nextthink = 0; - G_Sound( ent, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + } else { + // ent->nextthink = 0; + G_Sound(ent, CHAN_BODY, G_SoundIndex("sound/chars/turret/shutdown.wav")); ent->s.bolt2 = ENTITYNUM_NONE; ent->s.fireflag = 2; ent->think = sentryExpire; ent->nextthink = level.time + TURRET_DEATH_DELAY; } - } - else - { + } else { ent->s.fireflag = 0; } } @@ -964,90 +813,84 @@ void turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int //------------------------------------------------------------------------------------------------------------ { // Turn off the thinking of the base & use it's targets - self->think = 0;//NULL; - self->use = 0;//NULL; + self->think = 0; // NULL; + self->use = 0; // NULL; - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - if (!g_entities[self->genericValue3].inuse || !g_entities[self->genericValue3].client) - { + if (!g_entities[self->genericValue3].inuse || !g_entities[self->genericValue3].client) { G_FreeEntity(self); return; } // clear my data - self->die = 0;//NULL; + self->die = 0; // NULL; self->takedamage = qfalse; self->health = 0; // hack the effect angle so that explode death can orient the effect properly - VectorSet( self->s.angles, 0, 0, 1 ); + VectorSet(self->s.angles, 0, 0, 1); G_PlayEffect(EFFECT_EXPLOSION_PAS, self->s.pos.trBase, self->s.angles); G_RadiusDamage(self->s.pos.trBase, &g_entities[self->genericValue3], 30, 256, self, self, MOD_UNKNOWN); g_entities[self->genericValue3].client->ps.fd.sentryDeployed = qfalse; - //ExplodeDeath( self ); - G_FreeEntity( self ); + // ExplodeDeath( self ); + G_FreeEntity(self); } -void turret_free(gentity_t *self) -{ - if (!g_entities[self->genericValue3].inuse || !g_entities[self->genericValue3].client) - { +void turret_free(gentity_t *self) { + if (!g_entities[self->genericValue3].inuse || !g_entities[self->genericValue3].client) { G_FreeEntity(self); return; } g_entities[self->genericValue3].client->ps.fd.sentryDeployed = qfalse; - G_FreeEntity( self ); + G_FreeEntity(self); } #define TURRET_AMMO_COUNT 40 //--------------------------------- -void SP_PAS( gentity_t *base ) +void SP_PAS(gentity_t *base) //--------------------------------- { - if ( base->count == 0 ) - { + if (base->count == 0) { // give ammo base->count = TURRET_AMMO_COUNT; } - base->s.bolt1 = 1; //This is a sort of hack to indicate that this model needs special turret things done to it - base->s.bolt2 = ENTITYNUM_NONE; //store our current enemy index + base->s.bolt1 = 1; // This is a sort of hack to indicate that this model needs special turret things done to it + base->s.bolt2 = ENTITYNUM_NONE; // store our current enemy index base->damage = 0; // start animation flag - VectorSet( base->r.mins, -8, -8, 0 ); - VectorSet( base->r.maxs, 8, 8, 24 ); + VectorSet(base->r.mins, -8, -8, 0); + VectorSet(base->r.maxs, 8, 8, 24); G_RunObject(base); base->think = pas_think; base->nextthink = level.time + FRAMETIME; - if ( !base->health ) - { + if (!base->health) { base->health = 50; } base->takedamage = qtrue; - base->die = turret_die; + base->die = turret_die; base->physicsObject = qtrue; - G_Sound( base, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); + G_Sound(base, CHAN_BODY, G_SoundIndex("sound/chars/turret/startup.wav")); } //------------------------------------------------------------------------ -void ItemUse_Sentry( gentity_t *ent ) +void ItemUse_Sentry(gentity_t *ent) //------------------------------------------------------------------------ { vec3_t fwd, fwdorg; @@ -1055,14 +898,12 @@ void ItemUse_Sentry( gentity_t *ent ) vec3_t mins, maxs; gentity_t *sentry; - if (!ent || !ent->client) - { + if (!ent || !ent->client) { return; } - VectorSet( mins, -8, -8, 0 ); - VectorSet( maxs, 8, 8, 24 ); - + VectorSet(mins, -8, -8, 0); + VectorSet(maxs, 8, 8, 24); yawonly[ROLL] = 0; yawonly[PITCH] = 0; @@ -1070,14 +911,14 @@ void ItemUse_Sentry( gentity_t *ent ) AngleVectors(yawonly, fwd, NULL, NULL); - fwdorg[0] = ent->client->ps.origin[0] + fwd[0]*64; - fwdorg[1] = ent->client->ps.origin[1] + fwd[1]*64; - fwdorg[2] = ent->client->ps.origin[2] + fwd[2]*64; + fwdorg[0] = ent->client->ps.origin[0] + fwd[0] * 64; + fwdorg[1] = ent->client->ps.origin[1] + fwd[1] * 64; + fwdorg[2] = ent->client->ps.origin[2] + fwd[2] * 64; sentry = G_Spawn(); sentry->classname = "sentryGun"; - sentry->s.modelindex = G_ModelIndex("models/items/psgun.glm"); //replace ASAP + sentry->s.modelindex = G_ModelIndex("models/items/psgun.glm"); // replace ASAP sentry->s.g2radius = 30.0f; sentry->s.modelGhoul2 = 1; @@ -1090,7 +931,7 @@ void ItemUse_Sentry( gentity_t *ent ) VectorCopy(mins, sentry->r.mins); VectorCopy(maxs, sentry->r.maxs); sentry->genericValue3 = ent->s.number; - sentry->genericValue2 = ent->client->sess.sessionTeam; //so we can remove ourself if our owner changes teams + sentry->genericValue2 = ent->client->sess.sessionTeam; // so we can remove ourself if our owner changes teams sentry->genericValue15 = HI_SENTRY_GUN; sentry->r.absmin[0] = sentry->s.pos.trBase[0] + sentry->r.mins[0]; sentry->r.absmin[1] = sentry->s.pos.trBase[1] + sentry->r.mins[1]; @@ -1099,11 +940,11 @@ void ItemUse_Sentry( gentity_t *ent ) sentry->r.absmax[1] = sentry->s.pos.trBase[1] + sentry->r.maxs[1]; sentry->r.absmax[2] = sentry->s.pos.trBase[2] + sentry->r.maxs[2]; sentry->s.eType = ET_GENERAL; - sentry->s.pos.trType = TR_GRAVITY;//STATIONARY; + sentry->s.pos.trType = TR_GRAVITY; // STATIONARY; sentry->s.pos.trTime = level.time; sentry->touch = SentryTouch; sentry->nextthink = level.time; - sentry->genericValue4 = ENTITYNUM_NONE; //genericValue4 used as enemy index + sentry->genericValue4 = ENTITYNUM_NONE; // genericValue4 used as enemy index sentry->genericValue5 = 1000; @@ -1117,116 +958,84 @@ void ItemUse_Sentry( gentity_t *ent ) sentry->s.owner = ent->s.number; sentry->s.shouldtarget = qtrue; - if (level.gametype >= GT_TEAM) - { + if (level.gametype >= GT_TEAM) { sentry->s.teamowner = ent->client->sess.sessionTeam; - } - else - { + } else { sentry->s.teamowner = 16; } - SP_PAS( sentry ); + SP_PAS(sentry); } -extern gentity_t *NPC_SpawnType( gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle ); -void ItemUse_Seeker(gentity_t *ent) -{ - if ( level.gametype == GT_SIEGE && d_siegeSeekerNPC.integer ) - {//actualy spawn a remote NPC - gentity_t *remote = NPC_SpawnType( ent, "remote", NULL, qfalse ); - if ( remote && remote->client ) - {//set it to my team +extern gentity_t *NPC_SpawnType(gentity_t *ent, char *npc_type, char *targetname, qboolean isVehicle); +void ItemUse_Seeker(gentity_t *ent) { + if (level.gametype == GT_SIEGE && d_siegeSeekerNPC.integer) { // actualy spawn a remote NPC + gentity_t *remote = NPC_SpawnType(ent, "remote", NULL, qfalse); + if (remote && remote->client) { // set it to my team remote->s.owner = remote->r.ownerNum = ent->s.number; remote->activator = ent; - if ( ent->client->sess.sessionTeam == TEAM_BLUE ) - { + if (ent->client->sess.sessionTeam == TEAM_BLUE) { remote->client->playerTeam = NPCTEAM_PLAYER; - } - else if ( ent->client->sess.sessionTeam == TEAM_RED ) - { + } else if (ent->client->sess.sessionTeam == TEAM_RED) { remote->client->playerTeam = NPCTEAM_ENEMY; - } - else - { + } else { remote->client->playerTeam = NPCTEAM_NEUTRAL; } } - } - else - { + } else { ent->client->ps.eFlags |= EF_SEEKERDRONE; ent->client->ps.droneExistTime = level.time + 30000; ent->client->ps.droneFireTime = level.time + 1500; } } -static void MedPackGive(gentity_t *ent, int amount) -{ - if (!ent || !ent->client) - { +static void MedPackGive(gentity_t *ent, int amount) { + if (!ent || !ent->client) { return; } - if (ent->health <= 0 || - ent->client->ps.stats[STAT_HEALTH] <= 0 || - (ent->client->ps.eFlags & EF_DEAD)) - { + if (ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || (ent->client->ps.eFlags & EF_DEAD)) { return; } - if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH]) { return; } ent->health += amount; - if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) - { + if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) { ent->health = ent->client->ps.stats[STAT_MAX_HEALTH]; } } -void ItemUse_MedPack_Big(gentity_t *ent) -{ - MedPackGive(ent, MAX_MEDPACK_BIG_HEAL_AMOUNT); -} +void ItemUse_MedPack_Big(gentity_t *ent) { MedPackGive(ent, MAX_MEDPACK_BIG_HEAL_AMOUNT); } -void ItemUse_MedPack(gentity_t *ent) -{ - MedPackGive(ent, MAX_MEDPACK_HEAL_AMOUNT); -} +void ItemUse_MedPack(gentity_t *ent) { MedPackGive(ent, MAX_MEDPACK_HEAL_AMOUNT); } -#define JETPACK_TOGGLE_TIME 1000 -void Jetpack_Off(gentity_t *ent) -{ //create effects? +#define JETPACK_TOGGLE_TIME 1000 +void Jetpack_Off(gentity_t *ent) { // create effects? assert(ent && ent->client); - if (!ent->client->jetPackOn) - { //aready off + if (!ent->client->jetPackOn) { // aready off return; } ent->client->jetPackOn = qfalse; } -void Jetpack_On(gentity_t *ent) -{ //create effects? +void Jetpack_On(gentity_t *ent) { // create effects? assert(ent && ent->client); - if (ent->client->jetPackOn) - { //aready on + if (ent->client->jetPackOn) { // aready on return; } - if (ent->client->ps.fd.forceGripBeingGripped >= level.time) - { //can't turn on during grip interval + if (ent->client->ps.fd.forceGripBeingGripped >= level.time) { // can't turn on during grip interval return; } - if (ent->client->ps.fallingToDeath) - { //too late! + if (ent->client->ps.fallingToDeath) { // too late! return; } @@ -1235,90 +1044,68 @@ void Jetpack_On(gentity_t *ent) ent->client->jetPackOn = qtrue; } -void ItemUse_Jetpack( gentity_t *ent ) -{ +void ItemUse_Jetpack(gentity_t *ent) { assert(ent && ent->client); - if (ent->client->jetPackToggleTime >= level.time) - { + if (ent->client->jetPackToggleTime >= level.time) { return; } - if (ent->health <= 0 || - ent->client->ps.stats[STAT_HEALTH] <= 0 || - (ent->client->ps.eFlags & EF_DEAD) || - ent->client->ps.pm_type == PM_DEAD) - { //can't use it when dead under any circumstances. + if (ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || (ent->client->ps.eFlags & EF_DEAD) || + ent->client->ps.pm_type == PM_DEAD) { // can't use it when dead under any circumstances. return; } - if (!ent->client->jetPackOn && - ent->client->ps.jetpackFuel < 5) - { //too low on fuel to start it up + if (!ent->client->jetPackOn && ent->client->ps.jetpackFuel < 5) { // too low on fuel to start it up return; } - if (ent->client->jetPackOn) - { + if (ent->client->jetPackOn) { Jetpack_Off(ent); - } - else - { + } else { Jetpack_On(ent); } ent->client->jetPackToggleTime = level.time + JETPACK_TOGGLE_TIME; } -#define CLOAK_TOGGLE_TIME 1000 -extern void Jedi_Cloak( gentity_t *self ); -extern void Jedi_Decloak( gentity_t *self ); -void ItemUse_UseCloak( gentity_t *ent ) -{ +#define CLOAK_TOGGLE_TIME 1000 +extern void Jedi_Cloak(gentity_t *self); +extern void Jedi_Decloak(gentity_t *self); +void ItemUse_UseCloak(gentity_t *ent) { assert(ent && ent->client); - if (ent->client->cloakToggleTime >= level.time) - { + if (ent->client->cloakToggleTime >= level.time) { return; } - if (ent->health <= 0 || - ent->client->ps.stats[STAT_HEALTH] <= 0 || - (ent->client->ps.eFlags & EF_DEAD) || - ent->client->ps.pm_type == PM_DEAD) - { //can't use it when dead under any circumstances. + if (ent->health <= 0 || ent->client->ps.stats[STAT_HEALTH] <= 0 || (ent->client->ps.eFlags & EF_DEAD) || + ent->client->ps.pm_type == PM_DEAD) { // can't use it when dead under any circumstances. return; } - if (!ent->client->ps.powerups[PW_CLOAKED] && - ent->client->ps.cloakFuel < 5) - { //too low on fuel to start it up + if (!ent->client->ps.powerups[PW_CLOAKED] && ent->client->ps.cloakFuel < 5) { // too low on fuel to start it up return; } - if ( ent->client->ps.powerups[PW_CLOAKED] ) - {//decloak - Jedi_Decloak( ent ); - } - else - {//cloak - Jedi_Cloak( ent ); + if (ent->client->ps.powerups[PW_CLOAKED]) { // decloak + Jedi_Decloak(ent); + } else { // cloak + Jedi_Cloak(ent); } ent->client->cloakToggleTime = level.time + CLOAK_TOGGLE_TIME; } -#define TOSSED_ITEM_STAY_PERIOD 20000 -#define TOSSED_ITEM_OWNER_NOTOUCH_DUR 1000 +#define TOSSED_ITEM_STAY_PERIOD 20000 +#define TOSSED_ITEM_OWNER_NOTOUCH_DUR 1000 -void SpecialItemThink(gentity_t *ent) -{ +void SpecialItemThink(gentity_t *ent) { float gravity = 3.0f; float mass = 0.09f; float bounce = 1.1f; - if (ent->genericValue5 < level.time) - { + if (ent->genericValue5 < level.time) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; @@ -1329,96 +1116,83 @@ void SpecialItemThink(gentity_t *ent) ent->nextthink = level.time + 50; } -void G_SpecialSpawnItem(gentity_t *ent, gitem_t *item) -{ - RegisterItem( item ); +void G_SpecialSpawnItem(gentity_t *ent, gitem_t *item) { + RegisterItem(item); ent->item = item; - //go away if no one wants me + // go away if no one wants me ent->genericValue5 = level.time + TOSSED_ITEM_STAY_PERIOD; ent->think = SpecialItemThink; ent->nextthink = level.time + 50; ent->clipmask = MASK_SOLID; - ent->physicsBounce = 0.50; // items are bouncy - VectorSet (ent->r.mins, -8, -8, -0); - VectorSet (ent->r.maxs, 8, 8, 16); + ent->physicsBounce = 0.50; // items are bouncy + VectorSet(ent->r.mins, -8, -8, -0); + VectorSet(ent->r.maxs, 8, 8, 16); ent->s.eType = ET_ITEM; - ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex + ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex ent->r.contents = CONTENTS_TRIGGER; ent->touch = Touch_Item; - //can't touch owner for x seconds + // can't touch owner for x seconds ent->genericValue11 = ent->r.ownerNum; ent->genericValue10 = level.time + TOSSED_ITEM_OWNER_NOTOUCH_DUR; - //so we know to remove when picked up, not respawn + // so we know to remove when picked up, not respawn ent->genericValue9 = 1; - //kind of a lame value to use, but oh well. This means don't - //pick up this item clientside with prediction, because we - //aren't sending over all the data necessary for the player - //to know if he can. + // kind of a lame value to use, but oh well. This means don't + // pick up this item clientside with prediction, because we + // aren't sending over all the data necessary for the player + // to know if he can. ent->s.brokenLimbs = 1; - //since it uses my server-only physics + // since it uses my server-only physics ent->s.eFlags |= EF_CLIENTSMOOTH; } -#define DISP_HEALTH_ITEM "item_medpak_instant" -#define DISP_AMMO_ITEM "ammo_all" +#define DISP_HEALTH_ITEM "item_medpak_instant" +#define DISP_AMMO_ITEM "ammo_all" -void G_PrecacheDispensers(void) -{ +void G_PrecacheDispensers(void) { gitem_t *item; item = BG_FindItem(DISP_HEALTH_ITEM); - if (item) - { + if (item) { RegisterItem(item); } item = BG_FindItem(DISP_AMMO_ITEM); - if (item) - { + if (item) { RegisterItem(item); } } -void ItemUse_UseDisp(gentity_t *ent, int type) -{ +void ItemUse_UseDisp(gentity_t *ent, int type) { gitem_t *item = NULL; gentity_t *eItem; - if (!ent->client || - ent->client->tossableItemDebounce > level.time) - { //can't use it again yet + if (!ent->client || ent->client->tossableItemDebounce > level.time) { // can't use it again yet return; } - if (ent->client->ps.weaponTime > 0 || - ent->client->ps.forceHandExtend != HANDEXTEND_NONE) - { //busy doing something else + if (ent->client->ps.weaponTime > 0 || ent->client->ps.forceHandExtend != HANDEXTEND_NONE) { // busy doing something else return; } ent->client->tossableItemDebounce = level.time + TOSS_DEBOUNCE_TIME; - if (type == HI_HEALTHDISP) - { + if (type == HI_HEALTHDISP) { item = BG_FindItem(DISP_HEALTH_ITEM); - } - else - { + } else { item = BG_FindItem(DISP_AMMO_ITEM); } - if (item) - { + if (item) { vec3_t fwd, pos; - gentity_t *te; + gentity_t *te; eItem = G_Spawn(); eItem->r.ownerNum = ent->s.number; @@ -1437,52 +1211,45 @@ void ItemUse_UseDisp(gentity_t *ent, int type) VectorScale(fwd, 128.0f, eItem->epVelocity); eItem->epVelocity[2] = 16.0f; - // G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + // G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_THERMAL_THROW, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - te = G_TempEntity( ent->client->ps.origin, EV_LOCALTIMER ); + te = G_TempEntity(ent->client->ps.origin, EV_LOCALTIMER); te->s.time = level.time; te->s.time2 = TOSS_DEBOUNCE_TIME; te->s.owner = ent->client->ps.clientNum; } } - //=============================================== -//Portable E-Web -rww +// Portable E-Web -rww //=============================================== -//put the e-web away/remove it from the owner -void EWebDisattach(gentity_t *owner, gentity_t *eweb) -{ - owner->client->ewebIndex = 0; +// put the e-web away/remove it from the owner +void EWebDisattach(gentity_t *owner, gentity_t *eweb) { + owner->client->ewebIndex = 0; owner->client->ps.emplacedIndex = 0; - if (owner->health > 0) - { + if (owner->health > 0) { owner->client->ps.stats[STAT_WEAPONS] = eweb->genericValue11; - } - else - { + } else { owner->client->ps.stats[STAT_WEAPONS] = 0; } eweb->think = G_FreeEntity; eweb->nextthink = level.time; } -//precache misc e-web assets -void EWebPrecache(void) -{ - RegisterItem( BG_FindItemForWeapon(WP_TURRET) ); +// precache misc e-web assets +void EWebPrecache(void) { + RegisterItem(BG_FindItemForWeapon(WP_TURRET)); G_EffectIndex("detpack/explosion.efx"); G_EffectIndex("turret/muzzle_flash.efx"); } -//e-web death -#define EWEB_DEATH_RADIUS 128 -#define EWEB_DEATH_DMG 90 +// e-web death +#define EWEB_DEATH_RADIUS 128 +#define EWEB_DEATH_DMG 90 -extern void BG_CycleInven(playerState_t *ps, int direction); //bg_misc.c +extern void BG_CycleInven(playerState_t *ps, int direction); // bg_misc.c -void EWebDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void EWebDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { vec3_t fxDir; G_RadiusDamage(self->r.currentOrigin, self, EWEB_DEATH_DMG, EWEB_DEATH_RADIUS, self, self, MOD_SUICIDE); @@ -1490,24 +1257,21 @@ void EWebDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int dam VectorSet(fxDir, 1.0f, 0.0f, 0.0f); G_PlayEffect(EFFECT_EXPLOSION_DETPACK, self->r.currentOrigin, fxDir); - if (self->r.ownerNum != ENTITYNUM_NONE) - { + if (self->r.ownerNum != ENTITYNUM_NONE) { gentity_t *owner = &g_entities[self->r.ownerNum]; - if (owner->inuse && owner->client) - { + if (owner->inuse && owner->client) { EWebDisattach(owner, self); - //make sure it resets next time we spawn one in case we someone obtain one before death + // make sure it resets next time we spawn one in case we someone obtain one before death owner->client->ewebHealth = -1; - //take it away from him, it is gone forever. - owner->client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1<client->ps.stats[STAT_HOLDABLE_ITEMS] &= ~(1 << HI_EWEB); - if (owner->client->ps.stats[STAT_HOLDABLE_ITEM] > 0 && - bg_itemlist[owner->client->ps.stats[STAT_HOLDABLE_ITEM]].giType == IT_HOLDABLE && - bg_itemlist[owner->client->ps.stats[STAT_HOLDABLE_ITEM]].giTag == HI_EWEB) - { //he has it selected so deselect it and select the first thing available + if (owner->client->ps.stats[STAT_HOLDABLE_ITEM] > 0 && bg_itemlist[owner->client->ps.stats[STAT_HOLDABLE_ITEM]].giType == IT_HOLDABLE && + bg_itemlist[owner->client->ps.stats[STAT_HOLDABLE_ITEM]].giTag == + HI_EWEB) { // he has it selected so deselect it and select the first thing available owner->client->ps.stats[STAT_HOLDABLE_ITEM] = 0; BG_CycleInven(&owner->client->ps, 1); } @@ -1515,24 +1279,20 @@ void EWebDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int dam } } -//e-web pain -void EWebPain(gentity_t *self, gentity_t *attacker, int damage) -{ - //update the owner's health status of me - if (self->r.ownerNum != ENTITYNUM_NONE) - { +// e-web pain +void EWebPain(gentity_t *self, gentity_t *attacker, int damage) { + // update the owner's health status of me + if (self->r.ownerNum != ENTITYNUM_NONE) { gentity_t *owner = &g_entities[self->r.ownerNum]; - if (owner->inuse && owner->client) - { + if (owner->inuse && owner->client) { owner->client->ewebHealth = self->health; } } } -//special routine for tracking angles between client and server -void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) -{ +// special routine for tracking angles between client and server +void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) { int *thebone = &ent->s.boneIndex1; int *firstFree = NULL; int i = 0; @@ -1541,23 +1301,17 @@ void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) vec3_t *boneVector = &ent->s.boneAngles1; vec3_t *freeBoneVec = NULL; - while (thebone) - { - if (!*thebone && !firstFree) - { //if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. + while (thebone) { + if (!*thebone && !firstFree) { // if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. firstFree = thebone; freeBoneVec = boneVector; - } - else if (*thebone) - { - if (*thebone == boneIndex) - { //this is it + } else if (*thebone) { + if (*thebone == boneIndex) { // this is it break; } } - switch (i) - { + switch (i) { case 0: thebone = &ent->s.boneIndex2; boneVector = &ent->s.boneAngles2; @@ -1579,10 +1333,8 @@ void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) i++; } - if (!thebone) - { //didn't find it, create it - if (!firstFree) - { //no free bones.. can't do a thing then. + if (!thebone) { // didn't find it, create it + if (!firstFree) { // no free bones.. can't do a thing then. Com_Printf("WARNING: E-Web has no free bone indexes\n"); return; } @@ -1593,16 +1345,15 @@ void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) boneVector = freeBoneVec; } - //If we got here then we have a vector and an index. + // If we got here then we have a vector and an index. - //Copy the angles over the vector in the entitystate, so we can use the corresponding index - //to set the bone angles on the client. + // Copy the angles over the vector in the entitystate, so we can use the corresponding index + // to set the bone angles on the client. VectorCopy(angles, *boneVector); - //Now set the angles on our server instance if we have one. + // Now set the angles on our server instance if we have one. - if (!ent->ghoul2) - { + if (!ent->ghoul2) { return; } @@ -1611,68 +1362,52 @@ void EWeb_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) right = NEGATIVE_Z; forward = NEGATIVE_X; - //first 3 bits is forward, second 3 bits is right, third 3 bits is up - ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); - - trap->G2API_SetBoneAngles( ent->ghoul2, - 0, - bone, - angles, - flags, - up, - right, - forward, - NULL, - 100, - level.time ); + // first 3 bits is forward, second 3 bits is right, third 3 bits is up + ent->s.boneOrient = ((forward) | (right << 3) | (up << 6)); + + trap->G2API_SetBoneAngles(ent->ghoul2, 0, bone, angles, flags, up, right, forward, NULL, 100, level.time); } -//start an animation on model_root both server side and client side -void EWeb_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) -{ - //set info on the entity so it knows to start the anim on the client next snapshot. +// start an animation on model_root both server side and client side +void EWeb_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) { + // set info on the entity so it knows to start the anim on the client next snapshot. eweb->s.eFlags |= EF_G2ANIMATING; - if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) - { //already playing this anim, let's flag it to restart + if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) { // already playing this anim, let's flag it to restart eweb->s.torsoFlip = !eweb->s.torsoFlip; - } - else - { + } else { eweb->s.torsoAnim = startFrame; eweb->s.legsAnim = endFrame; } - //now set the animation on the server ghoul2 instance. + // now set the animation on the server ghoul2 instance. assert(eweb->ghoul2); - trap->G2API_SetBoneAnim(eweb->ghoul2, 0, "model_root", startFrame, endFrame, - (BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); + trap->G2API_SetBoneAnim(eweb->ghoul2, 0, "model_root", startFrame, endFrame, (BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); } -//fire a shot off -#define EWEB_MISSILE_DAMAGE 20 -void EWebFire(gentity_t *owner, gentity_t *eweb) -{ +// fire a shot off +#define EWEB_MISSILE_DAMAGE 20 +void EWebFire(gentity_t *owner, gentity_t *eweb) { mdxaBone_t boltMatrix; gentity_t *missile; vec3_t p, d, bPoint; - if (eweb->genericValue10 == -1) - { //oh no + if (eweb->genericValue10 == -1) { // oh no assert(!"Bad e-web bolt"); return; } - //get the muzzle point - trap->G2API_GetBoltMatrix(eweb->ghoul2, 0, eweb->genericValue10, &boltMatrix, eweb->s.apos.trBase, eweb->r.currentOrigin, level.time, NULL, eweb->modelScale); + // get the muzzle point + trap->G2API_GetBoltMatrix(eweb->ghoul2, 0, eweb->genericValue10, &boltMatrix, eweb->s.apos.trBase, eweb->r.currentOrigin, level.time, NULL, + eweb->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, p); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, d); - //Start the thing backwards into the bounding box so it can't start inside other solid things + // Start the thing backwards into the bounding box so it can't start inside other solid things VectorMA(p, -16.0f, d, bPoint); - //create the missile - missile = CreateMissile( bPoint, d, 1200.0f, 10000, owner, qfalse ); + // create the missile + missile = CreateMissile(bPoint, d, 1200.0f, 10000, owner, qfalse); missile->classname = "generic_proj"; missile->s.weapon = WP_TURRET; @@ -1680,27 +1415,27 @@ void EWebFire(gentity_t *owner, gentity_t *eweb) missile->damage = EWEB_MISSILE_DAMAGE; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_TURBLAST; - missile->clipmask = (MASK_SHOT|CONTENTS_LIGHTSABER); + missile->clipmask = (MASK_SHOT | CONTENTS_LIGHTSABER); - //ignore the e-web entity - missile->passThroughNum = eweb->s.number+1; + // ignore the e-web entity + missile->passThroughNum = eweb->s.number + 1; - //times it can bounce before it dies + // times it can bounce before it dies missile->bounceCount = 8; - //play the muzzle flash + // play the muzzle flash vectoangles(d, d); G_PlayEffectID(G_EffectIndex("turret/muzzle_flash.efx"), p, d); } -//lock the owner into place relative to the cannon pos -void EWebPositionUser(gentity_t *owner, gentity_t *eweb) -{ +// lock the owner into place relative to the cannon pos +void EWebPositionUser(gentity_t *owner, gentity_t *eweb) { mdxaBone_t boltMatrix; vec3_t p, d; trace_t tr; - trap->G2API_GetBoltMatrix(eweb->ghoul2, 0, eweb->genericValue9, &boltMatrix, eweb->s.apos.trBase, eweb->r.currentOrigin, level.time, NULL, eweb->modelScale); + trap->G2API_GetBoltMatrix(eweb->ghoul2, 0, eweb->genericValue9, &boltMatrix, eweb->s.apos.trBase, eweb->r.currentOrigin, level.time, NULL, + eweb->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, p); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, d); @@ -1711,74 +1446,58 @@ void EWebPositionUser(gentity_t *owner, gentity_t *eweb) trap->Trace(&tr, owner->client->ps.origin, owner->r.mins, owner->r.maxs, p, owner->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (!tr.startsolid && !tr.allsolid && tr.fraction == 1.0f) - { //all clear, we can move there + if (!tr.startsolid && !tr.allsolid && tr.fraction == 1.0f) { // all clear, we can move there vec3_t pDown; VectorCopy(p, pDown); pDown[2] -= 7.0f; trap->Trace(&tr, p, owner->r.mins, owner->r.maxs, pDown, owner->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (!tr.startsolid && !tr.allsolid) - { + if (!tr.startsolid && !tr.allsolid) { VectorSubtract(owner->client->ps.origin, tr.endpos, d); - if (VectorLength(d) > 1.0f) - { //we moved, do some animating + if (VectorLength(d) > 1.0f) { // we moved, do some animating vec3_t dAng; int aFlags = SETANIM_FLAG_HOLD; vectoangles(d, dAng); dAng[YAW] = AngleSubtract(owner->client->ps.viewangles[YAW], dAng[YAW]); - if (dAng[YAW] > 0.0f) - { - if (owner->client->ps.legsAnim == BOTH_STRAFE_RIGHT1) - { //reset to change direction + if (dAng[YAW] > 0.0f) { + if (owner->client->ps.legsAnim == BOTH_STRAFE_RIGHT1) { // reset to change direction aFlags |= SETANIM_FLAG_OVERRIDE; } G_SetAnim(owner, &owner->client->pers.cmd, SETANIM_LEGS, BOTH_STRAFE_LEFT1, aFlags, 0); - } - else - { - if (owner->client->ps.legsAnim == BOTH_STRAFE_LEFT1) - { //reset to change direction + } else { + if (owner->client->ps.legsAnim == BOTH_STRAFE_LEFT1) { // reset to change direction aFlags |= SETANIM_FLAG_OVERRIDE; } G_SetAnim(owner, &owner->client->pers.cmd, SETANIM_LEGS, BOTH_STRAFE_RIGHT1, aFlags, 0); } - } - else if (owner->client->ps.legsAnim == BOTH_STRAFE_RIGHT1 || owner->client->ps.legsAnim == BOTH_STRAFE_LEFT1) - { //don't keep animating in place + } else if (owner->client->ps.legsAnim == BOTH_STRAFE_RIGHT1 || owner->client->ps.legsAnim == BOTH_STRAFE_LEFT1) { // don't keep animating in place owner->client->ps.legsTimer = 0; } G_SetOrigin(owner, tr.endpos); VectorCopy(tr.endpos, owner->client->ps.origin); } - } - else - { //can't move here.. stop using the thing I guess + } else { // can't move here.. stop using the thing I guess EWebDisattach(owner, eweb); } } -//keep the bone angles updated based on the owner's look dir -void EWebUpdateBoneAngles(gentity_t *owner, gentity_t *eweb) -{ +// keep the bone angles updated based on the owner's look dir +void EWebUpdateBoneAngles(gentity_t *owner, gentity_t *eweb) { vec3_t yAng; float ideal; float incr; - const float turnCap = 4.0f; //max degrees we can turn per update + const float turnCap = 4.0f; // max degrees we can turn per update VectorClear(yAng); ideal = AngleSubtract(owner->client->ps.viewangles[YAW], eweb->s.angles[YAW]); incr = AngleSubtract(ideal, eweb->angle); - if (incr > turnCap) - { + if (incr > turnCap) { incr = turnCap; - } - else if (incr < -turnCap) - { + } else if (incr < -turnCap) { incr = -turnCap; } @@ -1788,80 +1507,64 @@ void EWebUpdateBoneAngles(gentity_t *owner, gentity_t *eweb) EWeb_SetBoneAngles(eweb, "cannon_Yrot", yAng); EWebPositionUser(owner, eweb); - if (!owner->client->ewebIndex) - { //was removed during position function + if (!owner->client->ewebIndex) { // was removed during position function return; } VectorClear(yAng); - yAng[2] = AngleSubtract(owner->client->ps.viewangles[PITCH], eweb->s.angles[PITCH])*0.8f; + yAng[2] = AngleSubtract(owner->client->ps.viewangles[PITCH], eweb->s.angles[PITCH]) * 0.8f; EWeb_SetBoneAngles(eweb, "cannon_Xrot", yAng); } -//keep it updated -extern int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); //bg_misc.c +// keep it updated +extern int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); // bg_misc.c -void EWebThink(gentity_t *self) -{ +void EWebThink(gentity_t *self) { qboolean killMe = qfalse; const float gravity = 3.0f; const float mass = 0.09f; const float bounce = 1.1f; - if (self->r.ownerNum == ENTITYNUM_NONE) - { + if (self->r.ownerNum == ENTITYNUM_NONE) { killMe = qtrue; - } - else - { + } else { gentity_t *owner = &g_entities[self->r.ownerNum]; - if (!owner->inuse || !owner->client || owner->client->pers.connected != CON_CONNECTED || - owner->client->ewebIndex != self->s.number || owner->health < 1) - { + if (!owner->inuse || !owner->client || owner->client->pers.connected != CON_CONNECTED || owner->client->ewebIndex != self->s.number || + owner->health < 1) { killMe = qtrue; - } - else if (owner->client->ps.emplacedIndex != self->s.number) - { //just go back to the inventory then + } else if (owner->client->ps.emplacedIndex != self->s.number) { // just go back to the inventory then EWebDisattach(owner, self); return; } - if (!killMe) - { + if (!killMe) { float yaw; - if (BG_EmplacedView(owner->client->ps.viewangles, self->s.angles, &yaw, self->s.origin2[0])) - { + if (BG_EmplacedView(owner->client->ps.viewangles, self->s.angles, &yaw, self->s.origin2[0])) { owner->client->ps.viewangles[YAW] = yaw; } owner->client->ps.weapon = WP_EMPLACED_GUN; owner->client->ps.stats[STAT_WEAPONS] = WP_EMPLACED_GUN; - if (self->genericValue8 < level.time) - { //make sure the anim timer is done + if (self->genericValue8 < level.time) { // make sure the anim timer is done EWebUpdateBoneAngles(owner, self); - if (!owner->client->ewebIndex) - { //was removed during position function + if (!owner->client->ewebIndex) { // was removed during position function return; } - if (owner->client->pers.cmd.buttons & BUTTON_ATTACK) - { - if (self->genericValue5 < level.time) - { //we can fire another shot off + if (owner->client->pers.cmd.buttons & BUTTON_ATTACK) { + if (self->genericValue5 < level.time) { // we can fire another shot off EWebFire(owner, self); - //cheap firing anim + // cheap firing anim EWeb_SetBoneAnim(self, 2, 4); self->genericValue3 = 1; - //set fire debounce time + // set fire debounce time self->genericValue5 = level.time + 100; } - } - else if (self->genericValue5 < level.time && self->genericValue3) - { //reset the anim back to non-firing + } else if (self->genericValue5 < level.time && self->genericValue3) { // reset the anim back to non-firing EWeb_SetBoneAnim(self, 0, 1); self->genericValue3 = 0; } @@ -1869,23 +1572,21 @@ void EWebThink(gentity_t *self) } } - if (killMe) - { //something happened to the owner, let's explode + if (killMe) { // something happened to the owner, let's explode EWebDie(self, self, self, 999, MOD_SUICIDE); return; } - //run some physics on it real quick so it falls and stuff properly + // run some physics on it real quick so it falls and stuff properly G_RunExPhys(self, gravity, mass, bounce, qfalse, NULL, 0); self->nextthink = level.time; } -#define EWEB_HEALTH 200 +#define EWEB_HEALTH 200 -//spawn and set up an e-web ent -gentity_t *EWeb_Create(gentity_t *spawner) -{ +// spawn and set up an e-web ent +gentity_t *EWeb_Create(gentity_t *spawner) { const char *modelName = "models/map_objects/hoth/eweb_model.glm"; int failSound = G_SoundIndex("sound/interface/shieldcon_empty"); gentity_t *ent; @@ -1900,15 +1601,14 @@ gentity_t *EWeb_Create(gentity_t *spawner) AngleVectors(fAng, fwd, 0, 0); VectorCopy(spawner->client->ps.origin, s); - //allow some fudge + // allow some fudge s[2] += 12.0f; VectorMA(s, 48.0f, fwd, pos); trap->Trace(&tr, s, mins, maxs, pos, spawner->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.allsolid || tr.startsolid || tr.fraction != 1.0f) - { //can't spawn here, we are in solid + if (tr.allsolid || tr.startsolid || tr.fraction != 1.0f) { // can't spawn here, we are in solid G_Sound(spawner, CHAN_AUTO, failSound); return NULL; } @@ -1920,15 +1620,14 @@ gentity_t *EWeb_Create(gentity_t *spawner) ent->physicsObject = qtrue; - //for the sake of being able to differentiate client-side between this and an emplaced gun + // for the sake of being able to differentiate client-side between this and an emplaced gun ent->s.weapon = WP_NONE; VectorCopy(pos, downPos); downPos[2] -= 18.0f; trap->Trace(&tr, pos, mins, maxs, downPos, spawner->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.startsolid || tr.allsolid || tr.fraction == 1.0f || tr.entityNum < ENTITYNUM_WORLD) - { //didn't hit ground. + if (tr.startsolid || tr.allsolid || tr.fraction == 1.0f || tr.entityNum < ENTITYNUM_WORLD) { // didn't hit ground. G_FreeEntity(ent); G_Sound(spawner, CHAN_AUTO, failSound); return NULL; @@ -1946,12 +1645,11 @@ gentity_t *EWeb_Create(gentity_t *spawner) ent->takedamage = qtrue; - if (spawner->client->ewebHealth <= 0) - { //refresh the owner's e-web health if its last e-web did not exist or was killed + if (spawner->client->ewebHealth <= 0) { // refresh the owner's e-web health if its last e-web did not exist or was killed spawner->client->ewebHealth = EWEB_HEALTH; } - //resume health of last deployment + // resume health of last deployment ent->maxHealth = EWEB_HEALTH; ent->health = spawner->client->ewebHealth; G_ScaleNetHealth(ent); @@ -1962,43 +1660,42 @@ gentity_t *EWeb_Create(gentity_t *spawner) ent->think = EWebThink; ent->nextthink = level.time; - //set up the g2 model info + // set up the g2 model info ent->s.modelGhoul2 = 1; ent->s.g2radius = 128; ent->s.modelindex = G_ModelIndex((char *)modelName); trap->G2API_InitGhoul2Model(&ent->ghoul2, modelName, 0, 0, 0, 0, 0); - if (!ent->ghoul2) - { //should not happen, but just to be safe. + if (!ent->ghoul2) { // should not happen, but just to be safe. G_FreeEntity(ent); return NULL; } - //initialize bone angles + // initialize bone angles EWeb_SetBoneAngles(ent, "cannon_Yrot", vec3_origin); EWeb_SetBoneAngles(ent, "cannon_Xrot", vec3_origin); - ent->genericValue10 = trap->G2API_AddBolt(ent->ghoul2, 0, "*cannonflash"); //muzzle bolt - ent->genericValue9 = trap->G2API_AddBolt(ent->ghoul2, 0, "cannon_Yrot"); //for placing the owner relative to rotation + ent->genericValue10 = trap->G2API_AddBolt(ent->ghoul2, 0, "*cannonflash"); // muzzle bolt + ent->genericValue9 = trap->G2API_AddBolt(ent->ghoul2, 0, "cannon_Yrot"); // for placing the owner relative to rotation - //set the constraints for this guy as an emplaced weapon, and his constraint angles - ent->s.origin2[0] = 360.0f; //360 degrees in either direction + // set the constraints for this guy as an emplaced weapon, and his constraint angles + ent->s.origin2[0] = 360.0f; // 360 degrees in either direction - VectorCopy(fAng, ent->s.angles); //consider "angle 0" for constraint + VectorCopy(fAng, ent->s.angles); // consider "angle 0" for constraint - //angle of y rot bone + // angle of y rot bone ent->angle = 0.0f; ent->r.ownerNum = spawner->s.number; trap->LinkEntity((sharedEntity_t *)ent); - //store off the owner's current weapons, we will be forcing him to use the "emplaced" weapon + // store off the owner's current weapons, we will be forcing him to use the "emplaced" weapon ent->genericValue11 = spawner->client->ps.stats[STAT_WEAPONS]; - //start the "unfolding" anim + // start the "unfolding" anim EWeb_SetBoneAnim(ent, 4, 20); - //don't allow use until the anim is done playing (rough time estimate) + // don't allow use until the anim is done playing (rough time estimate) ent->genericValue8 = level.time + 500; VectorCopy(mins, ent->r.mins); @@ -2007,36 +1704,27 @@ gentity_t *EWeb_Create(gentity_t *spawner) return ent; } -#define EWEB_USE_DEBOUNCE 1000 -//use the e-web -void ItemUse_UseEWeb(gentity_t *ent) -{ - if (ent->client->ewebTime > level.time) - { //can't use again yet +#define EWEB_USE_DEBOUNCE 1000 +// use the e-web +void ItemUse_UseEWeb(gentity_t *ent) { + if (ent->client->ewebTime > level.time) { // can't use again yet return; } - if (ent->client->ps.weaponTime > 0 || - ent->client->ps.forceHandExtend != HANDEXTEND_NONE) - { //busy doing something else + if (ent->client->ps.weaponTime > 0 || ent->client->ps.forceHandExtend != HANDEXTEND_NONE) { // busy doing something else return; } - if (ent->client->ps.emplacedIndex && !ent->client->ewebIndex) - { //using an emplaced gun already that isn't our own e-web + if (ent->client->ps.emplacedIndex && !ent->client->ewebIndex) { // using an emplaced gun already that isn't our own e-web return; } - if (ent->client->ewebIndex) - { //put it away + if (ent->client->ewebIndex) { // put it away EWebDisattach(ent, &g_entities[ent->client->ewebIndex]); - } - else - { //create it + } else { // create it gentity_t *eweb = EWeb_Create(ent); - if (eweb) - { //if it's null the thing couldn't spawn (probably no room) + if (eweb) { // if it's null the thing couldn't spawn (probably no room) ent->client->ewebIndex = eweb->s.number; ent->client->ps.emplacedIndex = eweb->s.number; } @@ -2045,25 +1733,23 @@ void ItemUse_UseEWeb(gentity_t *ent) ent->client->ewebTime = level.time + EWEB_USE_DEBOUNCE; } //=============================================== -//End E-Web +// End E-Web //=============================================== +int Pickup_Powerup(gentity_t *ent, gentity_t *other) { + int quantity; + int i; + gclient_t *client; -int Pickup_Powerup( gentity_t *ent, gentity_t *other ) { - int quantity; - int i; - gclient_t *client; - - if ( !other->client->ps.powerups[ent->item->giTag] ) { + if (!other->client->ps.powerups[ent->item->giTag]) { // round timing to seconds to make multiple powerup timers // count in sync - other->client->ps.powerups[ent->item->giTag] = - level.time - ( level.time % 1000 ); + other->client->ps.powerups[ent->item->giTag] = level.time - (level.time % 1000); G_LogWeaponPowerup(other->s.number, ent->item->giTag); } - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; @@ -2071,53 +1757,52 @@ int Pickup_Powerup( gentity_t *ent, gentity_t *other ) { other->client->ps.powerups[ent->item->giTag] += quantity * 1000; - if (ent->item->giTag == PW_YSALAMIRI) - { + if (ent->item->giTag == PW_YSALAMIRI) { other->client->ps.powerups[PW_FORCE_ENLIGHTENED_LIGHT] = 0; other->client->ps.powerups[PW_FORCE_ENLIGHTENED_DARK] = 0; other->client->ps.powerups[PW_FORCE_BOON] = 0; } // give any nearby players a "denied" anti-reward - for ( i = 0 ; i < level.maxclients ; i++ ) { - vec3_t delta; - float len; - vec3_t forward; - trace_t tr; + for (i = 0; i < level.maxclients; i++) { + vec3_t delta; + float len; + vec3_t forward; + trace_t tr; client = &level.clients[i]; - if ( client == other->client ) { + if (client == other->client) { continue; } - if ( client->pers.connected == CON_DISCONNECTED ) { + if (client->pers.connected == CON_DISCONNECTED) { continue; } - if ( client->ps.stats[STAT_HEALTH] <= 0 ) { + if (client->ps.stats[STAT_HEALTH] <= 0) { continue; } - // if same team in team game, no sound - // cannot use OnSameTeam as it expects to g_entities, not clients - if ( level.gametype >= GT_TEAM && other->client->sess.sessionTeam == client->sess.sessionTeam ) { - continue; - } + // if same team in team game, no sound + // cannot use OnSameTeam as it expects to g_entities, not clients + if (level.gametype >= GT_TEAM && other->client->sess.sessionTeam == client->sess.sessionTeam) { + continue; + } // if too far away, no sound - VectorSubtract( ent->s.pos.trBase, client->ps.origin, delta ); - len = VectorNormalize( delta ); - if ( len > 192 ) { + VectorSubtract(ent->s.pos.trBase, client->ps.origin, delta); + len = VectorNormalize(delta); + if (len > 192) { continue; } // if not facing, no sound - AngleVectors( client->ps.viewangles, forward, NULL, NULL ); - if ( DotProduct( delta, forward ) < 0.4 ) { + AngleVectors(client->ps.viewangles, forward, NULL, NULL); + if (DotProduct(delta, forward) < 0.4) { continue; } // if not line of sight, no sound - trap->Trace( &tr, client->ps.origin, NULL, NULL, ent->s.pos.trBase, ENTITYNUM_NONE, CONTENTS_SOLID, qfalse, 0, 0 ); - if ( tr.fraction != 1.0 ) { + trap->Trace(&tr, client->ps.origin, NULL, NULL, ent->s.pos.trBase, ENTITYNUM_NONE, CONTENTS_SOLID, qfalse, 0, 0); + if (tr.fraction != 1.0) { continue; } @@ -2129,7 +1814,7 @@ int Pickup_Powerup( gentity_t *ent, gentity_t *other ) { //====================================================================== -int Pickup_Holdable( gentity_t *ent, gentity_t *other ) { +int Pickup_Holdable(gentity_t *ent, gentity_t *other) { other->client->ps.stats[STAT_HOLDABLE_ITEM] = ent->item - bg_itemlist; @@ -2140,70 +1825,56 @@ int Pickup_Holdable( gentity_t *ent, gentity_t *other ) { return adjustRespawnTime(RESPAWN_HOLDABLE, ent->item->giType, ent->item->giTag); } - //====================================================================== -void Add_Ammo (gentity_t *ent, int weapon, int count) -{ +void Add_Ammo(gentity_t *ent, int weapon, int count) { int max = ammoData[weapon].max; - if (ent->client->ps.eFlags & EF_DOUBLE_AMMO) - { // fix: double ammo for siege + if (ent->client->ps.eFlags & EF_DOUBLE_AMMO) { // fix: double ammo for siege max *= 2; } - if ( ent->client->ps.ammo[weapon] < max ) - { + if (ent->client->ps.ammo[weapon] < max) { ent->client->ps.ammo[weapon] += count; - if ( ent->client->ps.ammo[weapon] > max ) - { + if (ent->client->ps.ammo[weapon] > max) { ent->client->ps.ammo[weapon] = max; } } } -int Pickup_Ammo (gentity_t *ent, gentity_t *other) -{ - int quantity; +int Pickup_Ammo(gentity_t *ent, gentity_t *other) { + int quantity; - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; } - if (ent->item->giTag == -1) - { //an ammo_all, give them a bit of everything - if ( level.gametype == GT_SIEGE ) // complaints that siege tech's not giving enough ammo. Does anything else use ammo all? + if (ent->item->giTag == -1) { // an ammo_all, give them a bit of everything + if (level.gametype == GT_SIEGE) // complaints that siege tech's not giving enough ammo. Does anything else use ammo all? { Add_Ammo(other, AMMO_BLASTER, 100); Add_Ammo(other, AMMO_POWERCELL, 100); Add_Ammo(other, AMMO_METAL_BOLTS, 100); Add_Ammo(other, AMMO_ROCKETS, 5); - if (other->client->ps.stats[STAT_WEAPONS] & (1<client->ps.stats[STAT_WEAPONS] & (1 << WP_DET_PACK)) { Add_Ammo(other, AMMO_DETPACK, 2); } - if (other->client->ps.stats[STAT_WEAPONS] & (1<client->ps.stats[STAT_WEAPONS] & (1 << WP_THERMAL)) { Add_Ammo(other, AMMO_THERMAL, 2); } - if (other->client->ps.stats[STAT_WEAPONS] & (1<client->ps.stats[STAT_WEAPONS] & (1 << WP_TRIP_MINE)) { Add_Ammo(other, AMMO_TRIPMINE, 2); } - } - else - { + } else { Add_Ammo(other, AMMO_BLASTER, 50); Add_Ammo(other, AMMO_POWERCELL, 50); Add_Ammo(other, AMMO_METAL_BOLTS, 50); Add_Ammo(other, AMMO_ROCKETS, 2); } - } - else - { - Add_Ammo (other, ent->item->giTag, quantity); + } else { + Add_Ammo(other, ent->item->giTag, quantity); } return adjustRespawnTime(RESPAWN_AMMO, ent->item->giType, ent->item->giTag); @@ -2211,76 +1882,73 @@ int Pickup_Ammo (gentity_t *ent, gentity_t *other) //====================================================================== +int Pickup_Weapon(gentity_t *ent, gentity_t *other) { + int quantity; -int Pickup_Weapon (gentity_t *ent, gentity_t *other) { - int quantity; - - if ( ent->count < 0 ) { + if (ent->count < 0) { quantity = 0; // None for you, sir! } else { - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; } // dropped items and teamplay weapons always have full ammo - if ( ! (ent->flags & FL_DROPPED_ITEM) && level.gametype != GT_TEAM ) { + if (!(ent->flags & FL_DROPPED_ITEM) && level.gametype != GT_TEAM) { // respawning rules // New method: If the player has less than half the minimum, give them the minimum, else add 1/2 the min. // drop the quantity if the already have over the minimum - if ( other->client->ps.ammo[ ent->item->giTag ] < quantity*0.5 ) { - quantity = quantity - other->client->ps.ammo[ ent->item->giTag ]; + if (other->client->ps.ammo[ent->item->giTag] < quantity * 0.5) { + quantity = quantity - other->client->ps.ammo[ent->item->giTag]; } else { - quantity = quantity*0.5; // only add half the value. + quantity = quantity * 0.5; // only add half the value. } // Old method: If the player has less than the minimum, give them the minimum, else just add 1. -/* - // drop the quantity if the already have over the minimum - if ( other->client->ps.ammo[ ent->item->giTag ] < quantity ) { - quantity = quantity - other->client->ps.ammo[ ent->item->giTag ]; - } else { - quantity = 1; // only add a single shot - } - */ + /* + // drop the quantity if the already have over the minimum + if ( other->client->ps.ammo[ ent->item->giTag ] < quantity ) { + quantity = quantity - other->client->ps.ammo[ ent->item->giTag ]; + } else { + quantity = 1; // only add a single shot + } + */ } } // add the weapon - other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag ); + other->client->ps.stats[STAT_WEAPONS] |= (1 << ent->item->giTag); - //Add_Ammo( other, ent->item->giTag, quantity ); - Add_Ammo( other, weaponData[ent->item->giTag].ammoIndex, quantity ); + // Add_Ammo( other, ent->item->giTag, quantity ); + Add_Ammo(other, weaponData[ent->item->giTag].ammoIndex, quantity); G_LogWeaponPickup(other->s.number, ent->item->giTag); // team deathmatch has slow weapon respawns - if ( level.gametype == GT_TEAM ) - { + if (level.gametype == GT_TEAM) { return adjustRespawnTime(RESPAWN_TEAM_WEAPON, ent->item->giType, ent->item->giTag); } return adjustRespawnTime(g_weaponRespawn.integer, ent->item->giType, ent->item->giTag); } - //====================================================================== -int Pickup_Health (gentity_t *ent, gentity_t *other) { - int max; - int quantity; +int Pickup_Health(gentity_t *ent, gentity_t *other) { + int max; + int quantity; // small and mega healths will go over the max - if ( ent->item->quantity != 5 && ent->item->quantity != 100 ) { + if (ent->item->quantity != 5 && ent->item->quantity != 100) { max = other->client->ps.stats[STAT_MAX_HEALTH]; } else { max = other->client->ps.stats[STAT_MAX_HEALTH] * 2; } - if ( ent->count ) { + if (ent->count) { quantity = ent->count; } else { quantity = ent->item->quantity; @@ -2288,12 +1956,12 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { other->health += quantity; - if (other->health > max ) { + if (other->health > max) { other->health = max; } other->client->ps.stats[STAT_HEALTH] = other->health; - if ( ent->item->quantity == 100 ) { // mega health respawns slow + if (ent->item->quantity == 100) { // mega health respawns slow return RESPAWN_MEGAHEALTH; } @@ -2302,11 +1970,9 @@ int Pickup_Health (gentity_t *ent, gentity_t *other) { //====================================================================== -int Pickup_Armor( gentity_t *ent, gentity_t *other ) -{ +int Pickup_Armor(gentity_t *ent, gentity_t *other) { other->client->ps.stats[STAT_ARMOR] += ent->item->quantity; - if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] * ent->item->giTag ) - { + if (other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] * ent->item->giTag) { other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH] * ent->item->giTag; } @@ -2320,15 +1986,15 @@ int Pickup_Armor( gentity_t *ent, gentity_t *other ) RespawnItem =============== */ -void RespawnItem( gentity_t *ent ) { +void RespawnItem(gentity_t *ent) { // randomly select from teamed entities if (ent->team) { - gentity_t *master; - int count; + gentity_t *master; + int count; int choice; - if ( !ent->teammaster ) { - trap->Error( ERR_DROP, "RespawnItem: bad teammaster"); + if (!ent->teammaster) { + trap->Error(ERR_DROP, "RespawnItem: bad teammaster"); } master = ent->teammaster; @@ -2342,45 +2008,38 @@ void RespawnItem( gentity_t *ent ) { } ent->r.contents = CONTENTS_TRIGGER; - //ent->s.eFlags &= ~EF_NODRAW; + // ent->s.eFlags &= ~EF_NODRAW; ent->s.eFlags &= ~(EF_NODRAW | EF_ITEMPLACEHOLDER); ent->r.svFlags &= ~SVF_NOCLIENT; - trap->LinkEntity ((sharedEntity_t *)ent); + trap->LinkEntity((sharedEntity_t *)ent); - if ( ent->item->giType == IT_POWERUP ) { + if (ent->item->giType == IT_POWERUP) { // play powerup spawn sound to all clients - gentity_t *te; + gentity_t *te; // if the powerup respawn sound should Not be global if (ent->speed) { - te = G_TempEntity( ent->s.pos.trBase, EV_GENERAL_SOUND ); - } - else { - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_SOUND ); + te = G_TempEntity(ent->s.pos.trBase, EV_GENERAL_SOUND); + } else { + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_SOUND); } - te->s.eventParm = G_SoundIndex( "sound/items/respawn1" ); + te->s.eventParm = G_SoundIndex("sound/items/respawn1"); te->r.svFlags |= SVF_BROADCAST; } // play the normal respawn sound only to nearby clients - G_AddEvent( ent, EV_ITEM_RESPAWN, 0 ); + G_AddEvent(ent, EV_ITEM_RESPAWN, 0); ent->nextthink = 0; } -qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) -{ - if ( (item->flags&FL_DROPPED_ITEM) - && item->activator != &g_entities[0] - && pickerupper->s.number - && pickerupper->s.weapon == WP_NONE - && pickerupper->enemy - && pickerupper->painDebounceTime < level.time - && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time //not surrendering - && !(pickerupper->NPC->scriptFlags&SCF_FORCED_MARCH) //not being forced to march - /*&& item->item->giTag != INV_SECURITY_KEY*/ ) - {//non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key - if ( level.time - item->s.time < 3000 )//was 5000 +qboolean CheckItemCanBePickedUpByNPC(gentity_t *item, gentity_t *pickerupper) { + if ((item->flags & FL_DROPPED_ITEM) && item->activator != &g_entities[0] && pickerupper->s.number && pickerupper->s.weapon == WP_NONE && + pickerupper->enemy && pickerupper->painDebounceTime < level.time && pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time // not surrendering + && !(pickerupper->NPC->scriptFlags & SCF_FORCED_MARCH) // not being forced to march + /*&& item->item->giTag != INV_SECURITY_KEY*/) { // non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a + // security key + if (level.time - item->s.time < 3000) // was 5000 { return qfalse; } @@ -2394,31 +2053,24 @@ qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper ) Touch_Item =============== */ -void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { - int respawn; - qboolean predict; - - if (ent->genericValue10 > level.time && - other && - other->s.number == ent->genericValue11) - { //this is the ent that we don't want to be able to touch us for x seconds +void Touch_Item(gentity_t *ent, gentity_t *other, trace_t *trace) { + int respawn; + qboolean predict; + + if (ent->genericValue10 > level.time && other && + other->s.number == ent->genericValue11) { // this is the ent that we don't want to be able to touch us for x seconds return; } - if (ent->s.eFlags & EF_ITEMPLACEHOLDER) - { + if (ent->s.eFlags & EF_ITEMPLACEHOLDER) { return; } - if (ent->s.eFlags & EF_NODRAW) - { + if (ent->s.eFlags & EF_NODRAW) { return; } - if (ent->item->giType == IT_WEAPON && - ent->s.powerups && - ent->s.powerups < level.time) - { + if (ent->item->giType == IT_WEAPON && ent->s.powerups && ent->s.powerups < level.time) { ent->s.generic1 = 0; ent->s.powerups = 0; } @@ -2426,79 +2078,50 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { if (!other->client) return; if (other->health < 1) - return; // dead people can't pickup + return; // dead people can't pickup - if (ent->item->giType == IT_POWERUP && - (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK)) - { - if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) - { - if (other->client->ps.fd.forceSide != FORCE_LIGHTSIDE) - { + if (ent->item->giType == IT_POWERUP && (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK)) { + if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT) { + if (other->client->ps.fd.forceSide != FORCE_LIGHTSIDE) { return; } - } - else - { - if (other->client->ps.fd.forceSide != FORCE_DARKSIDE) - { + } else { + if (other->client->ps.fd.forceSide != FORCE_DARKSIDE) { return; } } } // the same pickup rules are used for client side and server side - if ( !BG_CanItemBeGrabbed( level.gametype, &ent->s, &other->client->ps ) ) { + if (!BG_CanItemBeGrabbed(level.gametype, &ent->s, &other->client->ps)) { return; } - - if ( other->client->NPC_class == CLASS_ATST || - other->client->NPC_class == CLASS_GONK || - other->client->NPC_class == CLASS_MARK1 || - other->client->NPC_class == CLASS_MARK2 || - other->client->NPC_class == CLASS_MOUSE || - other->client->NPC_class == CLASS_PROBE || - other->client->NPC_class == CLASS_PROTOCOL || - other->client->NPC_class == CLASS_R2D2 || - other->client->NPC_class == CLASS_R5D2 || - other->client->NPC_class == CLASS_SEEKER || - other->client->NPC_class == CLASS_REMOTE || - other->client->NPC_class == CLASS_RANCOR || + if (other->client->NPC_class == CLASS_ATST || other->client->NPC_class == CLASS_GONK || other->client->NPC_class == CLASS_MARK1 || + other->client->NPC_class == CLASS_MARK2 || other->client->NPC_class == CLASS_MOUSE || other->client->NPC_class == CLASS_PROBE || + other->client->NPC_class == CLASS_PROTOCOL || other->client->NPC_class == CLASS_R2D2 || other->client->NPC_class == CLASS_R5D2 || + other->client->NPC_class == CLASS_SEEKER || other->client->NPC_class == CLASS_REMOTE || other->client->NPC_class == CLASS_RANCOR || other->client->NPC_class == CLASS_WAMPA || - //other->client->NPC_class == CLASS_JAWA || //FIXME: in some cases it's okay? - other->client->NPC_class == CLASS_UGNAUGHT || //FIXME: in some cases it's okay? - other->client->NPC_class == CLASS_SENTRY ) - {//FIXME: some flag would be better - //droids can't pick up items/weapons! + // other->client->NPC_class == CLASS_JAWA || //FIXME: in some cases it's okay? + other->client->NPC_class == CLASS_UGNAUGHT || // FIXME: in some cases it's okay? + other->client->NPC_class == CLASS_SENTRY) { // FIXME: some flag would be better + // droids can't pick up items/weapons! return; } - if ( CheckItemCanBePickedUpByNPC( ent, other ) ) - { - if ( other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent ) - {//they were running to pick me up, they did, so clear goal + if (CheckItemCanBePickedUpByNPC(ent, other)) { + if (other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent) { // they were running to pick me up, they did, so clear goal other->NPC->goalEntity = NULL; other->NPC->squadState = SQUAD_STAND_AND_SHOOT; } - } - else if ( !(ent->spawnflags & ITMSF_ALLOWNPC) ) - {// NPCs cannot pick it up - if ( other->s.eType == ET_NPC ) - {// Not the player? + } else if (!(ent->spawnflags & ITMSF_ALLOWNPC)) { // NPCs cannot pick it up + if (other->s.eType == ET_NPC) { // Not the player? qboolean dontGo = qfalse; - if (ent->item->giType == IT_AMMO && - ent->item->giTag == -1 && - other->s.NPC_class == CLASS_VEHICLE && - other->m_pVehicle && - other->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) - { //yeah, uh, atst gets healed by these things - if (other->maxHealth && - other->health < other->maxHealth) - { + if (ent->item->giType == IT_AMMO && ent->item->giTag == -1 && other->s.NPC_class == CLASS_VEHICLE && other->m_pVehicle && + other->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // yeah, uh, atst gets healed by these things + if (other->maxHealth && other->health < other->maxHealth) { other->health += 80; - if (other->health > other->maxHealth) - { + if (other->health > other->maxHealth) { other->health = other->maxHealth; } G_ScaleNetHealth(other); @@ -2506,65 +2129,57 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { } } - if (!dontGo) - { + if (!dontGo) { return; } } } - G_LogPrintf( "Item: %i %s\n", other->s.number, ent->item->classname ); + G_LogPrintf("Item: %i %s\n", other->s.number, ent->item->classname); predict = other->client->pers.predictItemPickup; // call the item-specific pickup function - switch( ent->item->giType ) { + switch (ent->item->giType) { case IT_WEAPON: respawn = Pickup_Weapon(ent, other); -// predict = qfalse; + // predict = qfalse; predict = qtrue; break; case IT_AMMO: respawn = Pickup_Ammo(ent, other); - if (ent->item->giTag == AMMO_THERMAL || ent->item->giTag == AMMO_TRIPMINE || ent->item->giTag == AMMO_DETPACK) - { + if (ent->item->giTag == AMMO_THERMAL || ent->item->giTag == AMMO_TRIPMINE || ent->item->giTag == AMMO_DETPACK) { int weapForAmmo = 0; - if (ent->item->giTag == AMMO_THERMAL) - { + if (ent->item->giTag == AMMO_THERMAL) { weapForAmmo = WP_THERMAL; - } - else if (ent->item->giTag == AMMO_TRIPMINE) - { + } else if (ent->item->giTag == AMMO_TRIPMINE) { weapForAmmo = WP_TRIP_MINE; - } - else - { + } else { weapForAmmo = WP_DET_PACK; } - if (other && other->client && other->client->ps.ammo[weaponData[weapForAmmo].ammoIndex] > 0 ) - { + if (other && other->client && other->client->ps.ammo[weaponData[weapForAmmo].ammoIndex] > 0) { other->client->ps.stats[STAT_WEAPONS] |= (1 << weapForAmmo); } } -// predict = qfalse; + // predict = qfalse; predict = qtrue; break; case IT_ARMOR: respawn = Pickup_Armor(ent, other); -// predict = qfalse; + // predict = qfalse; predict = qtrue; break; case IT_HEALTH: respawn = Pickup_Health(ent, other); -// predict = qfalse; + // predict = qfalse; predict = qtrue; break; case IT_POWERUP: respawn = Pickup_Powerup(ent, other); predict = qfalse; -// predict = qtrue; + // predict = qtrue; break; case IT_TEAM: respawn = Pickup_Team(ent, other); @@ -2576,37 +2191,34 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { return; } - if ( !respawn ) { + if (!respawn) { return; } // play the normal pickup sound if (predict) { - if (other->client) - { - BG_AddPredictableEventToPlayerstate( EV_ITEM_PICKUP, ent->s.number, &other->client->ps); - } - else - { - G_AddPredictableEvent( other, EV_ITEM_PICKUP, ent->s.number ); + if (other->client) { + BG_AddPredictableEventToPlayerstate(EV_ITEM_PICKUP, ent->s.number, &other->client->ps); + } else { + G_AddPredictableEvent(other, EV_ITEM_PICKUP, ent->s.number); } } else { - G_AddEvent( other, EV_ITEM_PICKUP, ent->s.number ); + G_AddEvent(other, EV_ITEM_PICKUP, ent->s.number); } // powerup pickups are global broadcasts - if ( /*ent->item->giType == IT_POWERUP ||*/ ent->item->giType == IT_TEAM) { + if (/*ent->item->giType == IT_POWERUP ||*/ ent->item->giType == IT_TEAM) { // if we want the global sound to play if (!ent->speed) { - gentity_t *te; + gentity_t *te; - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP ); + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP); te->s.eventParm = ent->s.modelindex; te->r.svFlags |= SVF_BROADCAST; } else { - gentity_t *te; + gentity_t *te; - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP ); + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_ITEM_PICKUP); te->s.eventParm = ent->s.modelindex; // only send this temp entity to a single client te->r.svFlags |= SVF_SINGLECLIENT; @@ -2615,10 +2227,10 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { } // fire item targets - G_UseTargets (ent, other); + G_UseTargets(ent, other); // wait of -1 will not respawn - if ( ent->wait == -1 ) { + if (ent->wait == -1) { ent->r.svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; ent->r.contents = 0; @@ -2627,40 +2239,36 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { } // non zero wait overrides respawn time - if ( ent->wait ) { + if (ent->wait) { respawn = ent->wait; } // random can be used to vary the respawn time - if ( ent->random ) { + if (ent->random) { respawn += Q_flrand(-1.0f, 1.0f) * ent->random; - if ( respawn < 1 ) { + if (respawn < 1) { respawn = 1; } } // dropped items will not respawn - if ( ent->flags & FL_DROPPED_ITEM ) { + if (ent->flags & FL_DROPPED_ITEM) { ent->freeAfterEvent = qtrue; } // picked up items still stay around, they just don't // draw anything. This allows respawnable items // to be placed on movers. - if (!(ent->flags & FL_DROPPED_ITEM) && (ent->item->giType==IT_WEAPON || ent->item->giType==IT_POWERUP)) - { + if (!(ent->flags & FL_DROPPED_ITEM) && (ent->item->giType == IT_WEAPON || ent->item->giType == IT_POWERUP)) { ent->s.eFlags |= EF_ITEMPLACEHOLDER; ent->s.eFlags &= ~EF_NODRAW; - } - else - { + } else { ent->s.eFlags |= EF_NODRAW; ent->r.svFlags |= SVF_NOCLIENT; } ent->r.contents = 0; - if (ent->genericValue9) - { //dropped item, should be removed when picked up + if (ent->genericValue9) { // dropped item, should be removed when picked up ent->think = G_FreeEntity; ent->nextthink = level.time; return; @@ -2670,17 +2278,16 @@ void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) { // A negative respawn times means to never respawn this item (but don't // delete it). This is used by items that are respawned by third party // events such as ctf flags - if ( respawn <= 0 ) { + if (respawn <= 0) { ent->nextthink = 0; ent->think = 0; } else { ent->nextthink = level.time + respawn * 1000; ent->think = RespawnItem; } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } - //====================================================================== /* @@ -2690,46 +2297,42 @@ LaunchItem Spawns an item and tosses it forward ================ */ -gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity ) { - gentity_t *dropped; +gentity_t *LaunchItem(gitem_t *item, vec3_t origin, vec3_t velocity) { + gentity_t *dropped; dropped = G_Spawn(); dropped->s.eType = ET_ITEM; - dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex - if (dropped->s.modelindex < 0) - { + dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex + if (dropped->s.modelindex < 0) { dropped->s.modelindex = 0; } dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item dropped->classname = item->classname; dropped->item = item; - VectorSet (dropped->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS); - VectorSet (dropped->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); + VectorSet(dropped->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS); + VectorSet(dropped->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS); dropped->r.contents = CONTENTS_TRIGGER; dropped->touch = Touch_Item; - G_SetOrigin( dropped, origin ); + G_SetOrigin(dropped, origin); dropped->s.pos.trType = TR_GRAVITY; dropped->s.pos.trTime = level.time; - VectorCopy( velocity, dropped->s.pos.trDelta ); + VectorCopy(velocity, dropped->s.pos.trDelta); dropped->flags |= FL_BOUNCE_HALF; if ((level.gametype == GT_CTF || level.gametype == GT_CTY) && item->giType == IT_TEAM) { // Special case for CTF flags dropped->think = Team_DroppedFlagThink; dropped->nextthink = level.time + 30000; - Team_CheckDroppedItem( dropped ); + Team_CheckDroppedItem(dropped); - //rww - so bots know - if (dropped->item->giTag == PW_REDFLAG) - { + // rww - so bots know + if (dropped->item->giTag == PW_REDFLAG) { droppedRedFlag = dropped; - } - else if (dropped->item->giTag == PW_BLUEFLAG) - { + } else if (dropped->item->giTag == PW_BLUEFLAG) { droppedBlueFlag = dropped; } } else { // auto-remove after 30 seconds @@ -2739,30 +2342,24 @@ gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity ) { dropped->flags = FL_DROPPED_ITEM; - if (item->giType == IT_WEAPON || item->giType == IT_POWERUP) - { + if (item->giType == IT_WEAPON || item->giType == IT_POWERUP) { dropped->s.eFlags |= EF_DROPPEDWEAPON; } vectoangles(velocity, dropped->s.angles); dropped->s.angles[PITCH] = 0; - if (item->giTag == WP_TRIP_MINE || - item->giTag == WP_DET_PACK) - { + if (item->giTag == WP_TRIP_MINE || item->giTag == WP_DET_PACK) { dropped->s.angles[PITCH] = -90; } - if (item->giTag != WP_BOWCASTER && - item->giTag != WP_DET_PACK && - item->giTag != WP_THERMAL) - { + if (item->giTag != WP_BOWCASTER && item->giTag != WP_DET_PACK && item->giTag != WP_THERMAL) { dropped->s.angles[ROLL] = -90; } dropped->physicsObject = qtrue; - trap->LinkEntity ((sharedEntity_t *)dropped); + trap->LinkEntity((sharedEntity_t *)dropped); return dropped; } @@ -2774,22 +2371,21 @@ Drop_Item Spawns an item and tosses it forward ================ */ -gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle ) { - vec3_t velocity; - vec3_t angles; +gentity_t *Drop_Item(gentity_t *ent, gitem_t *item, float angle) { + vec3_t velocity; + vec3_t angles; - VectorCopy( ent->s.apos.trBase, angles ); + VectorCopy(ent->s.apos.trBase, angles); angles[YAW] += angle; - angles[PITCH] = 0; // always forward + angles[PITCH] = 0; // always forward - AngleVectors( angles, velocity, NULL, NULL ); - VectorScale( velocity, 150, velocity ); + AngleVectors(angles, velocity, NULL, NULL); + VectorScale(velocity, 150, velocity); velocity[2] += 200 + Q_flrand(-1.0f, 1.0f) * 50; - return LaunchItem( item, ent->s.pos.trBase, velocity ); + return LaunchItem(item, ent->s.pos.trBase, velocity); } - /* ================ Use_Item @@ -2797,9 +2393,7 @@ Use_Item Respawn the item ================ */ -void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - RespawnItem( ent ); -} +void Use_Item(gentity_t *ent, gentity_t *other, gentity_t *activator) { RespawnItem(ent); } //====================================================================== @@ -2811,100 +2405,72 @@ Traces down to find where an item should rest, instead of letting them free fall from their spawn points ================ */ -void FinishSpawningItem( gentity_t *ent ) { - trace_t tr; - vec3_t dest; -// gitem_t *item; +void FinishSpawningItem(gentity_t *ent) { + trace_t tr; + vec3_t dest; + // gitem_t *item; -// VectorSet( ent->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS ); -// VectorSet( ent->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS ); + // VectorSet( ent->r.mins, -ITEM_RADIUS, -ITEM_RADIUS, -ITEM_RADIUS ); + // VectorSet( ent->r.maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS ); - if (level.gametype == GT_SIEGE) - { //in siege remove all powerups - if (ent->item->giType == IT_POWERUP) - { + if (level.gametype == GT_SIEGE) { // in siege remove all powerups + if (ent->item->giType == IT_POWERUP) { G_FreeEntity(ent); return; } } - if (level.gametype != GT_JEDIMASTER) - { - if (HasSetSaberOnly()) - { - if (ent->item->giType == IT_AMMO) - { - G_FreeEntity( ent ); + if (level.gametype != GT_JEDIMASTER) { + if (HasSetSaberOnly()) { + if (ent->item->giType == IT_AMMO) { + G_FreeEntity(ent); return; } - if (ent->item->giType == IT_HOLDABLE) - { - if (ent->item->giTag == HI_SEEKER || - ent->item->giTag == HI_SHIELD || - ent->item->giTag == HI_SENTRY_GUN) - { - G_FreeEntity( ent ); + if (ent->item->giType == IT_HOLDABLE) { + if (ent->item->giTag == HI_SEEKER || ent->item->giTag == HI_SHIELD || ent->item->giTag == HI_SENTRY_GUN) { + G_FreeEntity(ent); return; } } } - } - else - { //no powerups in jedi master - if (ent->item->giType == IT_POWERUP) - { + } else { // no powerups in jedi master + if (ent->item->giType == IT_POWERUP) { G_FreeEntity(ent); return; } } - if (level.gametype == GT_HOLOCRON) - { - if (ent->item->giType == IT_POWERUP) - { - if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || - ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK) - { + if (level.gametype == GT_HOLOCRON) { + if (ent->item->giType == IT_POWERUP) { + if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK) { G_FreeEntity(ent); return; } } } - if (g_forcePowerDisable.integer) - { //if force powers disabled, don't add force powerups - if (ent->item->giType == IT_POWERUP) - { - if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || - ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK || - ent->item->giTag == PW_FORCE_BOON) - { + if (g_forcePowerDisable.integer) { // if force powers disabled, don't add force powerups + if (ent->item->giType == IT_POWERUP) { + if (ent->item->giTag == PW_FORCE_ENLIGHTENED_LIGHT || ent->item->giTag == PW_FORCE_ENLIGHTENED_DARK || ent->item->giTag == PW_FORCE_BOON) { G_FreeEntity(ent); return; } } } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { - if ( ent->item->giType == IT_ARMOR || - ent->item->giType == IT_HEALTH || - (ent->item->giType == IT_HOLDABLE && (ent->item->giTag == HI_MEDPAC || ent->item->giTag == HI_MEDPAC_BIG)) ) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + if (ent->item->giType == IT_ARMOR || ent->item->giType == IT_HEALTH || + (ent->item->giType == IT_HOLDABLE && (ent->item->giTag == HI_MEDPAC || ent->item->giTag == HI_MEDPAC_BIG))) { G_FreeEntity(ent); return; } } - if (level.gametype != GT_CTF && - level.gametype != GT_CTY && - ent->item->giType == IT_TEAM) - { + if (level.gametype != GT_CTF && level.gametype != GT_CTY && ent->item->giType == IT_TEAM) { int killMe = 0; - switch (ent->item->giTag) - { + switch (ent->item->giTag) { case PW_REDFLAG: killMe = 1; break; @@ -2918,19 +2484,18 @@ void FinishSpawningItem( gentity_t *ent ) { break; } - if (killMe) - { - G_FreeEntity( ent ); + if (killMe) { + G_FreeEntity(ent); return; } } - VectorSet (ent->r.mins, -8, -8, -0); - VectorSet (ent->r.maxs, 8, 8, 16); + VectorSet(ent->r.mins, -8, -8, -0); + VectorSet(ent->r.maxs, 8, 8, 16); ent->s.eType = ET_ITEM; - ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex - ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item + ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex + ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item ent->r.contents = CONTENTS_TRIGGER; ent->touch = Touch_Item; @@ -2938,43 +2503,43 @@ void FinishSpawningItem( gentity_t *ent ) { ent->use = Use_Item; // create a Ghoul2 model if the world model is a glm -/* item = &bg_itemlist[ ent->s.modelindex ]; - if (!Q_stricmp(&item->world_model[0][strlen(item->world_model[0]) - 4], ".glm")) - { - trap->G2API_InitGhoul2Model(&ent->s, item->world_model[0], G_ModelIndex(item->world_model[0] ), 0, 0, 0, 0); - ent->s.radius = 60; - } -*/ - if ( ent->spawnflags & ITMSF_SUSPEND ) { + /* item = &bg_itemlist[ ent->s.modelindex ]; + if (!Q_stricmp(&item->world_model[0][strlen(item->world_model[0]) - 4], ".glm")) + { + trap->G2API_InitGhoul2Model(&ent->s, item->world_model[0], G_ModelIndex(item->world_model[0] ), 0, 0, 0, 0); + ent->s.radius = 60; + } + */ + if (ent->spawnflags & ITMSF_SUSPEND) { // suspended - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); } else { // drop to floor - //if it is directly even with the floor it will return startsolid, so raise up by 0.1 - //and temporarily subtract 0.1 from the z maxs so that going up doesn't push into the ceiling + // if it is directly even with the floor it will return startsolid, so raise up by 0.1 + // and temporarily subtract 0.1 from the z maxs so that going up doesn't push into the ceiling ent->s.origin[2] += 0.1f; ent->r.maxs[2] -= 0.1f; - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 ); - trap->Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0 ); - if ( tr.startsolid ) { - trap->Print ("FinishSpawningItem: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin)); - G_FreeEntity( ent ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096); + trap->Trace(&tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0); + if (tr.startsolid) { + trap->Print("FinishSpawningItem: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin)); + G_FreeEntity(ent); return; } - //add the 0.1 back after the trace + // add the 0.1 back after the trace ent->r.maxs[2] += 0.1f; // allow to ride movers ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); } // team slaves and targeted items aren't present at start - if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) { + if ((ent->flags & FL_TEAMSLAVE) || ent->targetname) { ent->s.eFlags |= EF_NODRAW; ent->r.contents = 0; return; @@ -2994,33 +2559,32 @@ void FinishSpawningItem( gentity_t *ent ) { } */ - trap->LinkEntity ((sharedEntity_t *)ent); + trap->LinkEntity((sharedEntity_t *)ent); } - -qboolean itemRegistered[MAX_ITEMS]; +qboolean itemRegistered[MAX_ITEMS]; /* ================== G_CheckTeamItems ================== */ -void G_CheckTeamItems( void ) { +void G_CheckTeamItems(void) { // Set up team stuff Team_InitGame(); - if( level.gametype == GT_CTF || level.gametype == GT_CTY ) { - gitem_t *item; + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { + gitem_t *item; // check for the two flags - item = BG_FindItem( "team_CTF_redflag" ); - if ( !item || !itemRegistered[ item - bg_itemlist ] ) { - trap->Print( S_COLOR_YELLOW "WARNING: No team_CTF_redflag in map\n" ); + item = BG_FindItem("team_CTF_redflag"); + if (!item || !itemRegistered[item - bg_itemlist]) { + trap->Print(S_COLOR_YELLOW "WARNING: No team_CTF_redflag in map\n"); } - item = BG_FindItem( "team_CTF_blueflag" ); - if ( !item || !itemRegistered[ item - bg_itemlist ] ) { - trap->Print( S_COLOR_YELLOW "WARNING: No team_CTF_blueflag in map\n" ); + item = BG_FindItem("team_CTF_blueflag"); + if (!item || !itemRegistered[item - bg_itemlist]) { + trap->Print(S_COLOR_YELLOW "WARNING: No team_CTF_blueflag in map\n"); } } } @@ -3030,17 +2594,16 @@ void G_CheckTeamItems( void ) { ClearRegisteredItems ============== */ -void ClearRegisteredItems( void ) { - memset( itemRegistered, 0, sizeof( itemRegistered ) ); +void ClearRegisteredItems(void) { + memset(itemRegistered, 0, sizeof(itemRegistered)); // players always start with the base weapon - RegisterItem( BG_FindItemForWeapon( WP_BRYAR_PISTOL ) ); - RegisterItem( BG_FindItemForWeapon( WP_STUN_BATON ) ); - RegisterItem( BG_FindItemForWeapon( WP_MELEE ) ); - RegisterItem( BG_FindItemForWeapon( WP_SABER ) ); + RegisterItem(BG_FindItemForWeapon(WP_BRYAR_PISTOL)); + RegisterItem(BG_FindItemForWeapon(WP_STUN_BATON)); + RegisterItem(BG_FindItemForWeapon(WP_MELEE)); + RegisterItem(BG_FindItemForWeapon(WP_SABER)); - if (level.gametype == GT_SIEGE) - { //kind of cheesy, maybe check if siege class with disp's is gonna be on this map too + if (level.gametype == GT_SIEGE) { // kind of cheesy, maybe check if siege class with disp's is gonna be on this map too G_PrecacheDispensers(); } } @@ -3052,14 +2615,13 @@ RegisterItem The item will be added to the precache list =============== */ -void RegisterItem( gitem_t *item ) { - if ( !item ) { - trap->Error( ERR_DROP, "RegisterItem: NULL" ); +void RegisterItem(gitem_t *item) { + if (!item) { + trap->Error(ERR_DROP, "RegisterItem: NULL"); } - itemRegistered[ item - bg_itemlist ] = qtrue; + itemRegistered[item - bg_itemlist] = qtrue; } - /* =============== SaveRegisteredItems @@ -3068,23 +2630,23 @@ Write the needed items to a config string so the client will know which ones to precache =============== */ -void SaveRegisteredItems( void ) { - char string[MAX_ITEMS+1]; - int i; - int count; +void SaveRegisteredItems(void) { + char string[MAX_ITEMS + 1]; + int i; + int count; count = 0; - for ( i = 0 ; i < bg_numItems ; i++ ) { - if ( itemRegistered[i] ) { + for (i = 0; i < bg_numItems; i++) { + if (itemRegistered[i]) { count++; string[i] = '1'; } else { string[i] = '0'; } } - string[ bg_numItems ] = 0; + string[bg_numItems] = 0; -// trap->Print( "%i items registered\n", count ); + // trap->Print( "%i items registered\n", count ); trap->SetConfigstring(CS_ITEMS, string); } @@ -3093,12 +2655,12 @@ void SaveRegisteredItems( void ) { G_ItemDisabled ============ */ -int G_ItemDisabled( gitem_t *item ) { +int G_ItemDisabled(gitem_t *item) { char name[128]; Com_sprintf(name, sizeof(name), "disable_%s", item->classname); - return trap->Cvar_VariableIntegerValue( name ); + return trap->Cvar_VariableIntegerValue(name); } /* @@ -3111,34 +2673,27 @@ Items can't be immediately dropped to floor, because they might be on an entity that hasn't spawned yet. ============ */ -void G_SpawnItem (gentity_t *ent, gitem_t *item) { +void G_SpawnItem(gentity_t *ent, gitem_t *item) { int wDisable = 0; - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnFloat( "wait", "0", &ent->wait ); + G_SpawnFloat("random", "0", &ent->random); + G_SpawnFloat("wait", "0", &ent->wait); - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { wDisable = g_duelWeaponDisable.integer; - } - else - { + } else { wDisable = g_weaponDisable.integer; } - if (item->giType == IT_WEAPON && - wDisable && - (wDisable & (1 << item->giTag))) - { - if (level.gametype != GT_JEDIMASTER) - { - G_FreeEntity( ent ); + if (item->giType == IT_WEAPON && wDisable && (wDisable & (1 << item->giTag))) { + if (level.gametype != GT_JEDIMASTER) { + G_FreeEntity(ent); return; } } - RegisterItem( item ); - if ( G_ItemDisabled(item) ) + RegisterItem(item); + if (G_ItemDisabled(item)) return; ent->item = item; @@ -3147,134 +2702,126 @@ void G_SpawnItem (gentity_t *ent, gitem_t *item) { ent->nextthink = level.time + FRAMETIME * 2; ent->think = FinishSpawningItem; - ent->physicsBounce = 0.50; // items are bouncy + ent->physicsBounce = 0.50; // items are bouncy - if ( item->giType == IT_POWERUP ) { - G_SoundIndex( "sound/items/respawn1" ); - G_SpawnFloat( "noglobalsound", "0", &ent->speed); + if (item->giType == IT_POWERUP) { + G_SoundIndex("sound/items/respawn1"); + G_SpawnFloat("noglobalsound", "0", &ent->speed); } } - /* ================ G_BounceItem ================ */ -void G_BounceItem( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceItem(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - BG_EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + BG_EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); // cut the velocity to keep from bouncing forever - VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta ); + VectorScale(ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta); - if ((ent->s.weapon == WP_DET_PACK && ent->s.eType == ET_GENERAL && ent->physicsObject)) - { //detpacks only - if (ent->touch) - { + if ((ent->s.weapon == WP_DET_PACK && ent->s.eType == ET_GENERAL && ent->physicsObject)) { // detpacks only + if (ent->touch) { ent->touch(ent, &g_entities[trace->entityNum], trace); return; } } // check for stop - if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) { - trace->endpos[2] += 1.0; // make sure it is off ground - SnapVector( trace->endpos ); - G_SetOrigin( ent, trace->endpos ); + if (trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40) { + trace->endpos[2] += 1.0; // make sure it is off ground + SnapVector(trace->endpos); + G_SetOrigin(ent, trace->endpos); ent->s.groundEntityNum = trace->entityNum; return; } - VectorAdd( ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin); - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); + VectorAdd(ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin); + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; - if (ent->s.eType == ET_HOLOCRON || - (ent->s.shouldtarget && ent->s.eType == ET_GENERAL && ent->physicsObject)) - { //holocrons and sentry guns - if (ent->touch) - { + if (ent->s.eType == ET_HOLOCRON || (ent->s.shouldtarget && ent->s.eType == ET_GENERAL && ent->physicsObject)) { // holocrons and sentry guns + if (ent->touch) { ent->touch(ent, &g_entities[trace->entityNum], trace); } } } - /* ================ G_RunItem ================ */ -void G_RunItem( gentity_t *ent ) { - vec3_t origin; - trace_t tr; - int contents; - int mask; +void G_RunItem(gentity_t *ent) { + vec3_t origin; + trace_t tr; + int contents; + int mask; // if groundentity has been set to ENTITYNUM_NONE, it may have been pushed off an edge - if ( ent->s.groundEntityNum == ENTITYNUM_NONE ) { - if ( ent->s.pos.trType != TR_GRAVITY ) { + if (ent->s.groundEntityNum == ENTITYNUM_NONE) { + if (ent->s.pos.trType != TR_GRAVITY) { ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; } } - if ( ent->s.pos.trType == TR_STATIONARY ) { + if (ent->s.pos.trType == TR_STATIONARY) { // check think function - G_RunThink( ent ); + G_RunThink(ent); return; } // get current position - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); // trace a line from the previous position to the current position - if ( ent->clipmask ) { + if (ent->clipmask) { mask = ent->clipmask; } else { - mask = MASK_PLAYERSOLID & ~CONTENTS_BODY;//MASK_SOLID; + mask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // MASK_SOLID; } - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ent->r.ownerNum, mask, qfalse, 0, 0 ); + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ent->r.ownerNum, mask, qfalse, 0, 0); - VectorCopy( tr.endpos, ent->r.currentOrigin ); + VectorCopy(tr.endpos, ent->r.currentOrigin); - if ( tr.startsolid ) { + if (tr.startsolid) { tr.fraction = 0; } - trap->LinkEntity( (sharedEntity_t *)ent ); // FIXME: avoid this for stationary? + trap->LinkEntity((sharedEntity_t *)ent); // FIXME: avoid this for stationary? // check think function - G_RunThink( ent ); + G_RunThink(ent); - if ( tr.fraction == 1 ) { + if (tr.fraction == 1) { return; } // if it is in a nodrop volume, remove it - contents = trap->PointContents( ent->r.currentOrigin, -1 ); - if ( contents & CONTENTS_NODROP ) { + contents = trap->PointContents(ent->r.currentOrigin, -1); + if (contents & CONTENTS_NODROP) { if (ent->item && ent->item->giType == IT_TEAM) { Team_FreeEntity(ent); - } else if(ent->genericValue15 == HI_SENTRY_GUN) { + } else if (ent->genericValue15 == HI_SENTRY_GUN) { turret_free(ent); } else { - G_FreeEntity( ent ); + G_FreeEntity(ent); } return; } - G_BounceItem( ent, &tr ); + G_BounceItem(ent, &tr); } - diff --git a/codemp/game/g_log.c b/codemp/game/g_log.c index e789b363c5..fa8172004b 100644 --- a/codemp/game/g_log.c +++ b/codemp/game/g_log.c @@ -36,7 +36,6 @@ along with this program; if not, see . // Additionally, // --how many times each powerup or item is picked up - #ifdef LOGGING_WEAPONS int G_WeaponLogPickups[MAX_CLIENTS][WP_NUM_WEAPONS]; int G_WeaponLogFired[MAX_CLIENTS][WP_NUM_WEAPONS]; @@ -48,75 +47,57 @@ int G_WeaponLogTime[MAX_CLIENTS][WP_NUM_WEAPONS]; int G_WeaponLogLastTime[MAX_CLIENTS]; qboolean G_WeaponLogClientTouch[MAX_CLIENTS]; int G_WeaponLogPowerups[MAX_CLIENTS][HI_NUM_HOLDABLE]; -int G_WeaponLogItems[MAX_CLIENTS][PW_NUM_POWERUPS]; +int G_WeaponLogItems[MAX_CLIENTS][PW_NUM_POWERUPS]; // MOD-weapon mapping array. -int weaponFromMOD[MOD_MAX] = -{ - WP_NONE, //MOD_UNKNOWN, - WP_STUN_BATON, //MOD_STUN_BATON, - WP_MELEE, //MOD_MELEE, - WP_SABER, //MOD_SABER, - WP_BRYAR_PISTOL, //MOD_BRYAR_PISTOL, - WP_BRYAR_PISTOL, //MOD_BRYAR_PISTOL_ALT, - WP_BLASTER, //MOD_BLASTER, - WP_TURRET, //MOD_TURBLAST - WP_DISRUPTOR, //MOD_DISRUPTOR, - WP_DISRUPTOR, //MOD_DISRUPTOR_SPLASH, - WP_DISRUPTOR, //MOD_DISRUPTOR_SNIPER, - WP_BOWCASTER, //MOD_BOWCASTER, - WP_REPEATER, //MOD_REPEATER, - WP_REPEATER, //MOD_REPEATER_ALT, - WP_REPEATER, //MOD_REPEATER_ALT_SPLASH, - WP_DEMP2, //MOD_DEMP2, - WP_DEMP2, //MOD_DEMP2_ALT, - WP_FLECHETTE, //MOD_FLECHETTE, - WP_FLECHETTE, //MOD_FLECHETTE_ALT_SPLASH, - WP_ROCKET_LAUNCHER, //MOD_ROCKET, - WP_ROCKET_LAUNCHER, //MOD_ROCKET_SPLASH, - WP_ROCKET_LAUNCHER, //MOD_ROCKET_HOMING, - WP_ROCKET_LAUNCHER, //MOD_ROCKET_HOMING_SPLASH, - WP_THERMAL, //MOD_THERMAL, - WP_THERMAL, //MOD_THERMAL_SPLASH, - WP_TRIP_MINE, //MOD_TRIP_MINE_SPLASH, - WP_TRIP_MINE, //MOD_TIMED_MINE_SPLASH, - WP_DET_PACK, //MOD_DET_PACK_SPLASH, - WP_NONE, //MOD_FORCE_DARK, - WP_NONE, //MOD_SENTRY, - WP_NONE, //MOD_WATER, - WP_NONE, //MOD_SLIME, - WP_NONE, //MOD_LAVA, - WP_NONE, //MOD_CRUSH, - WP_NONE, //MOD_TELEFRAG, - WP_NONE, //MOD_FALLING, - WP_NONE, //MOD_SUICIDE, - WP_NONE, //MOD_TARGET_LASER, - WP_NONE, //MOD_TRIGGER_HURT, +int weaponFromMOD[MOD_MAX] = { + WP_NONE, // MOD_UNKNOWN, + WP_STUN_BATON, // MOD_STUN_BATON, + WP_MELEE, // MOD_MELEE, + WP_SABER, // MOD_SABER, + WP_BRYAR_PISTOL, // MOD_BRYAR_PISTOL, + WP_BRYAR_PISTOL, // MOD_BRYAR_PISTOL_ALT, + WP_BLASTER, // MOD_BLASTER, + WP_TURRET, // MOD_TURBLAST + WP_DISRUPTOR, // MOD_DISRUPTOR, + WP_DISRUPTOR, // MOD_DISRUPTOR_SPLASH, + WP_DISRUPTOR, // MOD_DISRUPTOR_SNIPER, + WP_BOWCASTER, // MOD_BOWCASTER, + WP_REPEATER, // MOD_REPEATER, + WP_REPEATER, // MOD_REPEATER_ALT, + WP_REPEATER, // MOD_REPEATER_ALT_SPLASH, + WP_DEMP2, // MOD_DEMP2, + WP_DEMP2, // MOD_DEMP2_ALT, + WP_FLECHETTE, // MOD_FLECHETTE, + WP_FLECHETTE, // MOD_FLECHETTE_ALT_SPLASH, + WP_ROCKET_LAUNCHER, // MOD_ROCKET, + WP_ROCKET_LAUNCHER, // MOD_ROCKET_SPLASH, + WP_ROCKET_LAUNCHER, // MOD_ROCKET_HOMING, + WP_ROCKET_LAUNCHER, // MOD_ROCKET_HOMING_SPLASH, + WP_THERMAL, // MOD_THERMAL, + WP_THERMAL, // MOD_THERMAL_SPLASH, + WP_TRIP_MINE, // MOD_TRIP_MINE_SPLASH, + WP_TRIP_MINE, // MOD_TIMED_MINE_SPLASH, + WP_DET_PACK, // MOD_DET_PACK_SPLASH, + WP_NONE, // MOD_FORCE_DARK, + WP_NONE, // MOD_SENTRY, + WP_NONE, // MOD_WATER, + WP_NONE, // MOD_SLIME, + WP_NONE, // MOD_LAVA, + WP_NONE, // MOD_CRUSH, + WP_NONE, // MOD_TELEFRAG, + WP_NONE, // MOD_FALLING, + WP_NONE, // MOD_SUICIDE, + WP_NONE, // MOD_TARGET_LASER, + WP_NONE, // MOD_TRIGGER_HURT, }; -char *weaponNameFromIndex[WP_NUM_WEAPONS] = -{ - "No Weapon", - "Stun Baton", - "Saber", - "Bryar Pistol", - "Blaster", - "Disruptor", - "Bowcaster", - "Repeater", - "Demp2", - "Flechette", - "Rocket Launcher", - "Thermal", - "Tripmine", - "Detpack", - "Emplaced gun", - "Turret" -}; +char *weaponNameFromIndex[WP_NUM_WEAPONS] = {"No Weapon", "Stun Baton", "Saber", "Bryar Pistol", "Blaster", "Disruptor", "Bowcaster", "Repeater", + "Demp2", "Flechette", "Rocket Launcher", "Thermal", "Tripmine", "Detpack", "Emplaced gun", "Turret"}; -extern char *modNames[]; +extern char *modNames[]; -#endif //LOGGING_WEAPONS +#endif // LOGGING_WEAPONS /* ================= @@ -135,13 +116,12 @@ void G_LogWeaponInit(void) { memset(G_WeaponLogLastTime, 0, sizeof(G_WeaponLogLastTime)); memset(G_WeaponLogPowerups, 0, sizeof(G_WeaponLogPowerups)); memset(G_WeaponLogItems, 0, sizeof(G_WeaponLogItems)); -#endif //LOGGING_WEAPONS +#endif // LOGGING_WEAPONS } -void QDECL G_LogWeaponPickup(int client, int weaponid) -{ +void QDECL G_LogWeaponPickup(int client, int weaponid) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogPickups[client][weaponid]++; @@ -149,17 +129,16 @@ void QDECL G_LogWeaponPickup(int client, int weaponid) #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponFire(int client, int weaponid) -{ +void QDECL G_LogWeaponFire(int client, int weaponid) { #ifdef LOGGING_WEAPONS int dur; - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogFired[client][weaponid]++; dur = level.time - G_WeaponLogLastTime[client]; - if (dur > 5000) // 5 second max. + if (dur > 5000) // 5 second max. G_WeaponLogTime[client][weaponid] += 5000; else G_WeaponLogTime[client][weaponid] += dur; @@ -168,67 +147,60 @@ void QDECL G_LogWeaponFire(int client, int weaponid) #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponDamage(int client, int mod, int amount) -{ +void QDECL G_LogWeaponDamage(int client, int mod, int amount) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogDamage[client][mod] += amount; G_WeaponLogClientTouch[client] = qtrue; #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponKill(int client, int mod) -{ +void QDECL G_LogWeaponKill(int client, int mod) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogKills[client][mod]++; G_WeaponLogClientTouch[client] = qtrue; #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponFrag(int attacker, int deadguy) -{ +void QDECL G_LogWeaponFrag(int attacker, int deadguy) { #ifdef LOGGING_WEAPONS - if ( (attacker>=MAX_CLIENTS) || (deadguy>=MAX_CLIENTS) ) + if ((attacker >= MAX_CLIENTS) || (deadguy >= MAX_CLIENTS)) return; G_WeaponLogFrags[attacker][deadguy]++; G_WeaponLogClientTouch[attacker] = qtrue; #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponDeath(int client, int weaponid) -{ +void QDECL G_LogWeaponDeath(int client, int weaponid) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogDeaths[client][weaponid]++; G_WeaponLogClientTouch[client] = qtrue; #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponPowerup(int client, int powerupid) -{ +void QDECL G_LogWeaponPowerup(int client, int powerupid) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogPowerups[client][powerupid]++; G_WeaponLogClientTouch[client] = qtrue; #endif //_LOGGING_WEAPONS } -void QDECL G_LogWeaponItem(int client, int itemid) -{ +void QDECL G_LogWeaponItem(int client, int itemid) { #ifdef LOGGING_WEAPONS - if (client>=MAX_CLIENTS) + if (client >= MAX_CLIENTS) return; G_WeaponLogItems[client][itemid]++; G_WeaponLogClientTouch[client] = qtrue; #endif //_LOGGING_WEAPONS } - // Run through each player. Print out: // -- Most commonly picked up weapon. // -- Weapon with which the most time was spent. @@ -248,10 +220,9 @@ void QDECL G_LogWeaponItem(int client, int itemid) // -- Damage per shot with each weapon. // -- Number of deaths with each weapon. -void G_LogWeaponOutput(void) -{ +void G_LogWeaponOutput(void) { #ifdef LOGGING_WEAPONS - int i,j,curwp; + int i, j, curwp; float pershot; fileHandle_t weaponfile; char string[1024]; @@ -267,14 +238,13 @@ void G_LogWeaponOutput(void) int percharacter[WP_NUM_WEAPONS]; char info[1024]; char mapname[128]; - char *nameptr, *unknownname=""; + char *nameptr, *unknownname = ""; - if (!g_statLog.integer) - { + if (!g_statLog.integer) { return; } - G_LogPrintf("*****************************Weapon Log:\n" ); + G_LogPrintf("*****************************Weapon Log:\n"); memset(totalpickups, 0, sizeof(totalpickups)); memset(totaltime, 0, sizeof(totaltime)); @@ -285,20 +255,16 @@ void G_LogWeaponOutput(void) memset(totalkills, 0, sizeof(totalkills)); memset(totalshots, 0, sizeof(totalshots)); - for (i=0; i 0) - { - pershot = (float)(totaldamage[j])/(float)(totalshots[j]); - } - else - { + G_LogPrintf("\n****Combat Data by Weapon:\n"); + for (j = 0; j < WP_NUM_WEAPONS; j++) { + if (totalshots[j] > 0) { + pershot = (float)(totaldamage[j]) / (float)(totalshots[j]); + } else { pershot = 0; } - G_LogPrintf("%15s: Damage: %6d, Kills: %5d, Dmg per Shot: %f\n", - weaponNameFromIndex[j], totaldamage[j], totalkills[j], pershot); + G_LogPrintf("%15s: Damage: %6d, Kills: %5d, Dmg per Shot: %f\n", weaponNameFromIndex[j], totaldamage[j], totalkills[j], pershot); } - G_LogPrintf( "\n****Combat Data By Damage Type:\n" ); - for (j=0; jFS_Open( g_statLogFile.string, &weaponfile, FS_APPEND ); - if (!weaponfile) { //failed to open file, let's not crash, shall we? + trap->FS_Open(g_statLogFile.string, &weaponfile, FS_APPEND); + if (!weaponfile) { // failed to open file, let's not crash, shall we? return; } // Write out the level name trap->GetServerinfo(info, sizeof(info)); - Q_strncpyz(mapname, Info_ValueForKey( info, "mapname" ), sizeof(mapname)); + Q_strncpyz(mapname, Info_ValueForKey(info, "mapname"), sizeof(mapname)); Com_sprintf(string, sizeof(string), "\n\n\nLevel:\t%s\n\n\n", mapname); - trap->FS_Write( string, strlen( string ), weaponfile); - + trap->FS_Write(string, strlen(string), weaponfile); // Combat data per character // Start with Pickups per character Com_sprintf(string, sizeof(string), "Weapon Pickups per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -379,22 +332,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -408,8 +355,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -417,16 +363,14 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - // Weapon fires per character Com_sprintf(string, sizeof(string), "Weapon Shots per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -434,22 +378,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -463,8 +401,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -472,16 +409,14 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - // Weapon time per character Com_sprintf(string, sizeof(string), "Weapon Use Time per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -489,22 +424,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -518,8 +447,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -527,17 +455,14 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - - // Weapon deaths per character Com_sprintf(string, sizeof(string), "Weapon Deaths per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -545,22 +470,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -574,8 +493,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -583,19 +501,15 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - - - // Weapon damage per character Com_sprintf(string, sizeof(string), "Weapon Damage per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -603,34 +517,26 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -644,8 +550,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -653,18 +558,15 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - - // Weapon kills per character Com_sprintf(string, sizeof(string), "Weapon Kills per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -672,34 +574,26 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -713,8 +607,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -722,17 +615,14 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - - // Damage type damage per character Com_sprintf(string, sizeof(string), "Typed Damage per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -740,22 +630,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -769,8 +653,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -778,17 +661,14 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - - // Damage type kills per character Com_sprintf(string, sizeof(string), "Damage-Typed Kills per Player:\n\n"); - trap->FS_Write( string, strlen( string ), weaponfile); + trap->FS_Write(string, strlen(string), weaponfile); Com_sprintf(string, sizeof(string), "Player"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0; jFS_Write(string, strlen(string), weaponfile); } @@ -796,22 +676,16 @@ void G_LogWeaponOutput(void) trap->FS_Write(string, strlen(string), weaponfile); // Cycle through each player, give their name and the number of times they picked up each weapon. - for (i=0; ipers.netname; - } - else - { + } else { nameptr = unknownname; } trap->FS_Write(nameptr, strlen(nameptr), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -825,8 +699,7 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n***TOTAL:"); trap->FS_Write(string, strlen(string), weaponfile); - for (j=0;jFS_Write(string, strlen(string), weaponfile); } @@ -834,46 +707,37 @@ void G_LogWeaponOutput(void) Com_sprintf(string, sizeof(string), "\n\n\n"); trap->FS_Write(string, strlen(string), weaponfile); - trap->FS_Close(weaponfile); - -#endif //LOGGING_WEAPONS +#endif // LOGGING_WEAPONS } // did this player earn the efficiency award? -qboolean CalculateEfficiency(gentity_t *ent, int *efficiency) -{ +qboolean CalculateEfficiency(gentity_t *ent, int *efficiency) { #ifdef LOGGING_WEAPONS - float fAccuracyRatio = 0, fBestRatio = 0; - int i = 0, nShotsFired = 0, nShotsHit = 0, nBestPlayer = -1, tempEff = 0; - gentity_t *player = NULL; - + float fAccuracyRatio = 0, fBestRatio = 0; + int i = 0, nShotsFired = 0, nShotsHit = 0, nBestPlayer = -1, tempEff = 0; + gentity_t *player = NULL; - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { player = g_entities + i; if (!player->inuse) continue; - nShotsFired = player->client->accuracy_shots; //player->client->ps.persistant[PERS_ACCURACY_SHOTS]; - nShotsHit = player->client->accuracy_hits; //player->client->ps.persistant[PERS_ACCURACY_HITS]; - fAccuracyRatio = ( ((float)nShotsHit)/((float)nShotsFired) ); - if (fAccuracyRatio > fBestRatio) - { + nShotsFired = player->client->accuracy_shots; // player->client->ps.persistant[PERS_ACCURACY_SHOTS]; + nShotsHit = player->client->accuracy_hits; // player->client->ps.persistant[PERS_ACCURACY_HITS]; + fAccuracyRatio = (((float)nShotsHit) / ((float)nShotsFired)); + if (fAccuracyRatio > fBestRatio) { fBestRatio = fAccuracyRatio; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { // huh? return qfalse; } - if (nBestPlayer == ent->s.number) - { - tempEff = (int)(100*fBestRatio); - if (tempEff > 50) - { + if (nBestPlayer == ent->s.number) { + tempEff = (int)(100 * fBestRatio); + if (tempEff > 50) { *efficiency = tempEff; return qtrue; } @@ -884,38 +748,31 @@ qboolean CalculateEfficiency(gentity_t *ent, int *efficiency) } // did this player earn the sharpshooter award? -qboolean CalculateSharpshooter(gentity_t *ent, int *frags) -{ +qboolean CalculateSharpshooter(gentity_t *ent, int *frags) { #ifdef LOGGING_WEAPONS - int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0, - playTime = (level.time - ent->client->pers.enterTime)/60000; - gentity_t *player = NULL; + int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0, playTime = (level.time - ent->client->pers.enterTime) / 60000; + gentity_t *player = NULL; // if this guy didn't get one kill per minute, reject him right now - if ( ((float)(G_WeaponLogKills[ent-g_entities][MOD_DISRUPTOR_SNIPER]))/((float)(playTime)) < 1.0 ) - { + if (((float)(G_WeaponLogKills[ent - g_entities][MOD_DISRUPTOR_SNIPER])) / ((float)(playTime)) < 1.0) { return qfalse; } - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nKills = 0; player = g_entities + i; if (!player->inuse) continue; nKills = G_WeaponLogKills[i][MOD_DISRUPTOR_SNIPER]; - if (nKills > nMostKills) - { + if (nKills > nMostKills) { nMostKills = nKills; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { *frags = nMostKills; return qtrue; } @@ -924,24 +781,21 @@ qboolean CalculateSharpshooter(gentity_t *ent, int *frags) } // did this player earn the untouchable award? -qboolean CalculateUntouchable(gentity_t *ent) -{ +qboolean CalculateUntouchable(gentity_t *ent) { #ifdef LOGGING_WEAPONS - int playTime; - playTime = (level.time - ent->client->pers.enterTime)/60000; + int playTime; + playTime = (level.time - ent->client->pers.enterTime) / 60000; - if ( level.gametype == GT_JEDIMASTER && ent->client->ps.isJediMaster ) - {//Jedi Master can only be killed once anyway + if (level.gametype == GT_JEDIMASTER && ent->client->ps.isJediMaster) { // Jedi Master can only be killed once anyway return qfalse; } //------------------------------------------------------ MUST HAVE ACHIEVED 2 KILLS PER MINUTE - if ( ((float)ent->client->ps.persistant[PERS_SCORE])/((float)(playTime)) < 2.0 || playTime==0) + if (((float)ent->client->ps.persistant[PERS_SCORE]) / ((float)(playTime)) < 2.0 || playTime == 0) return qfalse; //------------------------------------------------------ MUST HAVE ACHIEVED 2 KILLS PER MINUTE - // if this guy was never killed... Award Away!!! - if (ent->client->ps.persistant[PERS_KILLED]==0) + if (ent->client->ps.persistant[PERS_KILLED] == 0) return qtrue; #endif // LOGGING_WEAPONS @@ -949,52 +803,41 @@ qboolean CalculateUntouchable(gentity_t *ent) } // did this player earn the logistics award? -qboolean CalculateLogistics(gentity_t *ent, int *stuffUsed) -{ +qboolean CalculateLogistics(gentity_t *ent, int *stuffUsed) { #ifdef LOGGING_WEAPONS - int i = 0, j = 0, nBestPlayer = -1, nStuffUsed = 0, nMostStuffUsed = 0, - nDifferent = 0, nMostDifferent = 0; - gentity_t *player = NULL; + int i = 0, j = 0, nBestPlayer = -1, nStuffUsed = 0, nMostStuffUsed = 0, nDifferent = 0, nMostDifferent = 0; + gentity_t *player = NULL; - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nStuffUsed = 0; nDifferent = 0; player = g_entities + i; if (!player->inuse) continue; - for (j = HI_NONE+1; j < HI_NUM_HOLDABLE; j++) - { - if (G_WeaponLogPowerups[i][j]) - { + for (j = HI_NONE + 1; j < HI_NUM_HOLDABLE; j++) { + if (G_WeaponLogPowerups[i][j]) { nDifferent++; } nStuffUsed += G_WeaponLogPowerups[i][j]; } - for (j = PW_NONE+1; j < PW_NUM_POWERUPS; j++) - { - if (G_WeaponLogItems[i][j]) - { + for (j = PW_NONE + 1; j < PW_NUM_POWERUPS; j++) { + if (G_WeaponLogItems[i][j]) { nDifferent++; } nStuffUsed += G_WeaponLogItems[i][j]; } - if ( (nDifferent >= 4) && (nDifferent >= nMostDifferent) ) - { - if (nStuffUsed > nMostStuffUsed) - { + if ((nDifferent >= 4) && (nDifferent >= nMostDifferent)) { + if (nStuffUsed > nMostStuffUsed) { nMostDifferent = nDifferent; nMostStuffUsed = nStuffUsed; nBestPlayer = i; } } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { *stuffUsed = nMostDifferent; return qtrue; } @@ -1002,78 +845,62 @@ qboolean CalculateLogistics(gentity_t *ent, int *stuffUsed) return qfalse; } - - - // did this player earn the tactician award? -qboolean CalculateTactician(gentity_t *ent, int *kills) -{ +qboolean CalculateTactician(gentity_t *ent, int *kills) { #ifdef LOGGING_WEAPONS - int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0; - int person = 0, weapon = 0; - gentity_t *player = NULL; - int wasPickedUpBySomeone[WP_NUM_WEAPONS]; - int killsWithWeapon[WP_NUM_WEAPONS]; - int playTime = (level.time - ent->client->pers.enterTime)/60000; - - if ( HasSetSaberOnly() ) - {//duh, only 1 weapon + int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0; + int person = 0, weapon = 0; + gentity_t *player = NULL; + int wasPickedUpBySomeone[WP_NUM_WEAPONS]; + int killsWithWeapon[WP_NUM_WEAPONS]; + int playTime = (level.time - ent->client->pers.enterTime) / 60000; + + if (HasSetSaberOnly()) { // duh, only 1 weapon return qfalse; } - if ( level.gametype == GT_JEDIMASTER && ent->client->ps.isJediMaster ) - {//Jedi Master has only 1 weapon + if (level.gametype == GT_JEDIMASTER && ent->client->ps.isJediMaster) { // Jedi Master has only 1 weapon return qfalse; } //------------------------------------------------------ MUST HAVE ACHIEVED 2 KILLS PER MINUTE - if (playTime<0.3) + if (playTime < 0.3) return qfalse; - if ( ((float)ent->client->ps.persistant[PERS_SCORE])/((float)(playTime)) < 2.0 ) + if (((float)ent->client->ps.persistant[PERS_SCORE]) / ((float)(playTime)) < 2.0) return qfalse; //------------------------------------------------------ MUST HAVE ACHIEVED 2 KILLS PER MINUTE - - - //------------------------------------------------------ FOR EVERY WEAPON, ADD UP TOTAL PICKUPS - for (weapon = 0; weapon0) + for (person = 0; person < sv_maxclients.integer; person++) { + for (weapon = 0; weapon < WP_NUM_WEAPONS; weapon++) { + if (G_WeaponLogPickups[person][weapon] > 0) wasPickedUpBySomeone[weapon]++; } } //------------------------------------------------------ FOR EVERY WEAPON, ADD UP TOTAL PICKUPS - - - //------------------------------------------------------ FOR EVERY PERSON, CHECK FOR CANDIDATE - for (person=0; personinuse) continue; + if (!player->inuse) + continue; - nKills = 0; // This Persons's Kills - for (weapon=0; weapon0) ) - { + while (weapon < WP_NUM_WEAPONS && (!wasPickedUpBySomeone[weapon] || killsWithWeapon[weapon] > 0)) { weapon++; - nKills+=killsWithWeapon[weapon]; // Update the number of kills + nKills += killsWithWeapon[weapon]; // Update the number of kills } // // At this point we have either successfully gone through every weapon on the map and saw it had @@ -1082,18 +909,16 @@ qboolean CalculateTactician(gentity_t *ent, int *kills) // so we look to see if the weapon==Max (i.e. we used every one) and then we check to see // if we got the most kills out of anyone else who did this. // - if (weapon>=WP_NUM_WEAPONS && nKills>nMostKills) - { + if (weapon >= WP_NUM_WEAPONS && nKills > nMostKills) { // WE ARE A TACTICION CANDIDATE - nMostKills = nKills; + nMostKills = nKills; nBestPlayer = person; } } //------------------------------------------------------ FOR EVERY PERSON, CHECK FOR CANDIDATE - //Now, if we are the best player, return true and the number of kills we got - if (nBestPlayer == ent->s.number) - { + // Now, if we are the best player, return true and the number of kills we got + if (nBestPlayer == ent->s.number) { *kills = nMostKills; return qtrue; } @@ -1101,19 +926,13 @@ qboolean CalculateTactician(gentity_t *ent, int *kills) return qfalse; } - - - // did this player earn the demolitionist award? -qboolean CalculateDemolitionist(gentity_t *ent, int *kills) -{ +qboolean CalculateDemolitionist(gentity_t *ent, int *kills) { #ifdef LOGGING_WEAPONS - int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0, - playTime = (level.time - ent->client->pers.enterTime)/60000; - gentity_t *player = NULL; + int i = 0, nBestPlayer = -1, nKills = 0, nMostKills = 0, playTime = (level.time - ent->client->pers.enterTime) / 60000; + gentity_t *player = NULL; - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nKills = 0; player = g_entities + i; if (!player->inuse) @@ -1130,23 +949,19 @@ qboolean CalculateDemolitionist(gentity_t *ent, int *kills) nKills += G_WeaponLogKills[i][MOD_DET_PACK_SPLASH]; // if this guy didn't get two explosive kills per minute, reject him right now - if ( ((float)nKills)/((float)(playTime)) < 2.0 ) - { + if (((float)nKills) / ((float)(playTime)) < 2.0) { continue; } - if (nKills > nMostKills) - { + if (nKills > nMostKills) { nMostKills = nKills; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { *kills = nMostKills; return qtrue; } @@ -1154,8 +969,7 @@ qboolean CalculateDemolitionist(gentity_t *ent, int *kills) return qfalse; } -int CalculateStreak(gentity_t *ent) -{ +int CalculateStreak(gentity_t *ent) { #if 0 if (ent->client->ps.persistant[PERS_STREAK_COUNT] >= STREAK_CHAMPION) { @@ -1174,45 +988,37 @@ int CalculateStreak(gentity_t *ent) return STREAK_ACE; } #endif - //No streak calculation, at least for now. + // No streak calculation, at least for now. return 0; } -qboolean CalculateTeamMVP(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamMVP(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->ps.persistant[PERS_SCORE]; - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } -qboolean CalculateTeamDefender(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamDefender(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; /* if (CalculateTeamMVP(ent)) @@ -1220,35 +1026,29 @@ qboolean CalculateTeamDefender(gentity_t *ent) return qfalse; } */ - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->pers.teamState.basedefense; - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } -qboolean CalculateTeamWarrior(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamWarrior(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; /* if (CalculateTeamMVP(ent) || CalculateTeamDefender(ent)) @@ -1256,35 +1056,29 @@ qboolean CalculateTeamWarrior(gentity_t *ent) return qfalse; } */ - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->ps.persistant[PERS_SCORE]; - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } -qboolean CalculateTeamCarrier(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamCarrier(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; /* if (CalculateTeamMVP(ent) || CalculateTeamDefender(ent) || CalculateTeamWarrior(ent)) @@ -1292,35 +1086,29 @@ qboolean CalculateTeamCarrier(gentity_t *ent) return qfalse; } */ - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->pers.teamState.captures; - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } -qboolean CalculateTeamInterceptor(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamInterceptor(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; /* if (CalculateTeamMVP(ent) || CalculateTeamDefender(ent) || CalculateTeamWarrior(ent) || @@ -1329,36 +1117,30 @@ qboolean CalculateTeamInterceptor(gentity_t *ent) return qfalse; } */ - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->pers.teamState.flagrecovery; nScore += player->client->pers.teamState.fragcarrier; - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } -qboolean CalculateTeamRedShirt(gentity_t *ent) -{ - int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, - team = ent->client->ps.persistant[PERS_TEAM]; - gentity_t *player = NULL; +qboolean CalculateTeamRedShirt(gentity_t *ent) { + int i = 0, nBestPlayer = -1, nScore = 0, nHighestScore = 0, team = ent->client->ps.persistant[PERS_TEAM]; + gentity_t *player = NULL; /* if (CalculateTeamMVP(ent) || CalculateTeamDefender(ent) || CalculateTeamWarrior(ent) || @@ -1367,114 +1149,96 @@ qboolean CalculateTeamRedShirt(gentity_t *ent) return qfalse; } */ - for (i = 0; i < sv_maxclients.integer; i++) - { + for (i = 0; i < sv_maxclients.integer; i++) { nScore = 0; player = g_entities + i; if (!player->inuse || (player->client->ps.persistant[PERS_TEAM] != team)) continue; nScore = player->client->ps.persistant[PERS_KILLED]; nScore -= player->client->ps.fd.suicides; // suicides don't count, you big cheater. - if (nScore > nHighestScore) - { + if (nScore > nHighestScore) { nHighestScore = nScore; nBestPlayer = i; } } - if (-1 == nBestPlayer) - { + if (-1 == nBestPlayer) { return qfalse; } - if (nBestPlayer == ent->s.number) - { + if (nBestPlayer == ent->s.number) { return qtrue; } return qfalse; } typedef enum { - AWARD_EFFICIENCY, // Accuracy - AWARD_SHARPSHOOTER, // Most compression rifle frags - AWARD_UNTOUCHABLE, // Perfect (no deaths) - AWARD_LOGISTICS, // Most pickups - AWARD_TACTICIAN, // Kills with all weapons - AWARD_DEMOLITIONIST, // Most explosive damage kills - AWARD_STREAK, // Ace/Expert/Master/Champion - AWARD_TEAM, // MVP/Defender/Warrior/Carrier/Interceptor/Bravery - AWARD_SECTION31, // All-around god + AWARD_EFFICIENCY, // Accuracy + AWARD_SHARPSHOOTER, // Most compression rifle frags + AWARD_UNTOUCHABLE, // Perfect (no deaths) + AWARD_LOGISTICS, // Most pickups + AWARD_TACTICIAN, // Kills with all weapons + AWARD_DEMOLITIONIST, // Most explosive damage kills + AWARD_STREAK, // Ace/Expert/Master/Champion + AWARD_TEAM, // MVP/Defender/Warrior/Carrier/Interceptor/Bravery + AWARD_SECTION31, // All-around god AWARD_MAX } awardType_t; -typedef enum -{ - TEAM_NONE = 0, // ha ha! you suck! - TEAM_MVP, // most overall points - TEAM_DEFENDER, // killed the most baddies near your flag - TEAM_WARRIOR, // most frags - TEAM_CARRIER, // infected the most people with plague - TEAM_INTERCEPTOR, // returned your own flag the most - TEAM_BRAVERY, // Red Shirt Award (tm). you died more than anybody. +typedef enum { + TEAM_NONE = 0, // ha ha! you suck! + TEAM_MVP, // most overall points + TEAM_DEFENDER, // killed the most baddies near your flag + TEAM_WARRIOR, // most frags + TEAM_CARRIER, // infected the most people with plague + TEAM_INTERCEPTOR, // returned your own flag the most + TEAM_BRAVERY, // Red Shirt Award (tm). you died more than anybody. TEAM_MAX } teamAward_e; -int CalculateTeamAward(gentity_t *ent) -{ +int CalculateTeamAward(gentity_t *ent) { int teamAwards = 0; - if (CalculateTeamMVP(ent)) - { - teamAwards |= (1<inuse) continue; -// -// kef -- heh. -// -// if (strcmp("JaxxonPhred", ent->client->pers.netname)) -// { -// continue; -// } + // + // kef -- heh. + // + // if (strcmp("JaxxonPhred", ent->client->pers.netname)) + // { + // continue; + // } CalculateEfficiency(ent, &efficiency); - if (!CalculateSharpshooter(ent, &frags) || - !CalculateUntouchable(ent) || + if (!CalculateSharpshooter(ent, &frags) || !CalculateUntouchable(ent) || /*(CalculateStreak(ent) < STREAK_CHAMPION) ||*/ - (efficiency < 75)) - { + (efficiency < 75)) { continue; } return qtrue; @@ -1484,7 +1248,7 @@ qboolean CalculateSection31Award(gentity_t *ent) #if 0 -#define AWARDS_MSG_LENGTH 256 +#define AWARDS_MSG_LENGTH 256 void CalculateAwards(gentity_t *ent, char *msg) { @@ -1674,51 +1438,39 @@ int GetFavoriteWeaponForClient(int nClient) #endif // kef -- if a client leaves the game, clear out all counters he may have set -void QDECL G_ClearClientLog(int client) -{ +void QDECL G_ClearClientLog(int client) { int i = 0; - for (i = 0; i < WP_NUM_WEAPONS; i++) - { + for (i = 0; i < WP_NUM_WEAPONS; i++) { G_WeaponLogPickups[client][i] = 0; } - for (i = 0; i < WP_NUM_WEAPONS; i++) - { + for (i = 0; i < WP_NUM_WEAPONS; i++) { G_WeaponLogFired[client][i] = 0; } - for (i = 0; i < MOD_MAX; i++) - { + for (i = 0; i < MOD_MAX; i++) { G_WeaponLogDamage[client][i] = 0; } - for (i = 0; i < MOD_MAX; i++) - { + for (i = 0; i < MOD_MAX; i++) { G_WeaponLogKills[client][i] = 0; } - for (i = 0; i < WP_NUM_WEAPONS; i++) - { + for (i = 0; i < WP_NUM_WEAPONS; i++) { G_WeaponLogDeaths[client][i] = 0; } - for (i = 0; i < MAX_CLIENTS; i++) - { + for (i = 0; i < MAX_CLIENTS; i++) { G_WeaponLogFrags[client][i] = 0; } - for (i = 0; i < MAX_CLIENTS; i++) - { + for (i = 0; i < MAX_CLIENTS; i++) { G_WeaponLogFrags[i][client] = 0; } - for (i = 0; i < WP_NUM_WEAPONS; i++) - { + for (i = 0; i < WP_NUM_WEAPONS; i++) { G_WeaponLogTime[client][i] = 0; } G_WeaponLogLastTime[client] = 0; G_WeaponLogClientTouch[client] = qfalse; - for (i = 0; i < HI_NUM_HOLDABLE; i++) - { + for (i = 0; i < HI_NUM_HOLDABLE; i++) { G_WeaponLogPowerups[client][i] = 0; } - for (i = 0; i < PW_NUM_POWERUPS; i++) - { + for (i = 0; i < PW_NUM_POWERUPS; i++) { G_WeaponLogItems[client][i] = 0; } } - diff --git a/codemp/game/g_main.c b/codemp/game/g_main.c index 31715742ad..c083578855 100644 --- a/codemp/game/g_main.c +++ b/codemp/game/g_main.c @@ -22,7 +22,6 @@ along with this program; if not, see . =========================================================================== */ - #include "g_local.h" #include "g_ICARUScb.h" #include "g_nav.h" @@ -30,43 +29,42 @@ along with this program; if not, see . #include "b_local.h" #include "qcommon/q_version.h" -NORETURN_PTR void (*Com_Error)( int level, const char *error, ... ); -void (*Com_Printf)( const char *msg, ... ); +NORETURN_PTR void (*Com_Error)(int level, const char *error, ...); +void (*Com_Printf)(const char *msg, ...); -level_locals_t level; +level_locals_t level; -int eventClearTime = 0; +int eventClearTime = 0; static int navCalcPathTime = 0; extern int fatalErrors; int killPlayerTimer = 0; -gentity_t g_entities[MAX_GENTITIES]; -gclient_t g_clients[MAX_CLIENTS]; +gentity_t g_entities[MAX_GENTITIES]; +gclient_t g_clients[MAX_CLIENTS]; qboolean gDuelExit = qfalse; -void G_InitGame ( int levelTime, int randomSeed, int restart ); -void G_RunFrame ( int levelTime ); -void G_ShutdownGame ( int restart ); -void CheckExitRules ( void ); -void G_ROFF_NotetrackCallback ( gentity_t *cent, const char *notetrack); +void G_InitGame(int levelTime, int randomSeed, int restart); +void G_RunFrame(int levelTime); +void G_ShutdownGame(int restart); +void CheckExitRules(void); +void G_ROFF_NotetrackCallback(gentity_t *cent, const char *notetrack); extern stringID_table_t setTable[]; -qboolean G_ParseSpawnVars( qboolean inSubBSP ); -void G_SpawnGEntityFromSpawnVars( qboolean inSubBSP ); - +qboolean G_ParseSpawnVars(qboolean inSubBSP); +void G_SpawnGEntityFromSpawnVars(qboolean inSubBSP); -qboolean NAV_ClearPathToPoint( gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum ); -qboolean NPC_ClearLOS2( gentity_t *ent, const vec3_t end ); +qboolean NAV_ClearPathToPoint(gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum); +qboolean NPC_ClearLOS2(gentity_t *ent, const vec3_t end); int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask); -qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ); -qboolean G_EntIsUnlockedDoor( int entityNum ); -qboolean G_EntIsDoor( int entityNum ); -qboolean G_EntIsBreakable( int entityNum ); -qboolean G_EntIsRemovableUsable( int entNum ); -void CP_FindCombatPointWaypoints( void ); +qboolean NAV_CheckNodeFailedForEnt(gentity_t *ent, int nodeNum); +qboolean G_EntIsUnlockedDoor(int entityNum); +qboolean G_EntIsDoor(int entityNum); +qboolean G_EntIsBreakable(int entityNum); +qboolean G_EntIsRemovableUsable(int entNum); +void CP_FindCombatPointWaypoints(void); /* ================ @@ -79,35 +77,33 @@ All but the first will have the FL_TEAMSLAVE flag set and teammaster field set All but the last will have the teamchain field set to the next one ================ */ -void G_FindTeams( void ) { - gentity_t *e, *e2; - int i, j; - int c, c2; +void G_FindTeams(void) { + gentity_t *e, *e2; + int i, j; + int c, c2; c = 0; c2 = 0; - for ( i=MAX_CLIENTS, e=g_entities+i ; i < level.num_entities ; i++,e++ ) { + for (i = MAX_CLIENTS, e = g_entities + i; i < level.num_entities; i++, e++) { if (!e->inuse) continue; if (!e->team) continue; if (e->flags & FL_TEAMSLAVE) continue; - if (e->r.contents==CONTENTS_TRIGGER) - continue;//triggers NEVER link up in teams! + if (e->r.contents == CONTENTS_TRIGGER) + continue; // triggers NEVER link up in teams! e->teammaster = e; c++; c2++; - for (j=i+1, e2=e+1 ; j < level.num_entities ; j++,e2++) - { + for (j = i + 1, e2 = e + 1; j < level.num_entities; j++, e2++) { if (!e2->inuse) continue; if (!e2->team) continue; if (e2->flags & FL_TEAMSLAVE) continue; - if (!strcmp(e->team, e2->team)) - { + if (!strcmp(e->team, e2->team)) { c2++; e2->teamchain = e->teamchain; e->teamchain = e2; @@ -115,7 +111,7 @@ void G_FindTeams( void ) { e2->flags |= FL_TEAMSLAVE; // make sure that targets only point at the master - if ( e2->targetname ) { + if (e2->targetname) { e->targetname = e2->targetname; e2->targetname = NULL; } @@ -123,44 +119,36 @@ void G_FindTeams( void ) { } } -// trap->Print ("%i teams with %i entities\n", c, c2); + // trap->Print ("%i teams with %i entities\n", c, c2); } sharedBuffer_t gSharedBuffer; -void WP_SaberLoadParms( void ); -void BG_VehicleLoadParms( void ); +void WP_SaberLoadParms(void); +void BG_VehicleLoadParms(void); -void G_CacheGametype( void ) -{ +void G_CacheGametype(void) { // check some things - if ( g_gametype.string[0] && isalpha( g_gametype.string[0] ) ) - { - int gt = BG_GetGametypeForString( g_gametype.string ); - if ( gt == -1 ) - { - trap->Print( "Gametype '%s' unrecognised, defaulting to FFA/Deathmatch\n", g_gametype.string ); + if (g_gametype.string[0] && isalpha(g_gametype.string[0])) { + int gt = BG_GetGametypeForString(g_gametype.string); + if (gt == -1) { + trap->Print("Gametype '%s' unrecognised, defaulting to FFA/Deathmatch\n", g_gametype.string); level.gametype = GT_FFA; - } - else + } else level.gametype = gt; - } - else if ( g_gametype.integer < 0 || g_gametype.integer >= GT_MAX_GAME_TYPE ) - { - trap->Print( "g_gametype %i is out of range, defaulting to 0 (FFA/Deathmatch)\n", g_gametype.integer ); + } else if (g_gametype.integer < 0 || g_gametype.integer >= GT_MAX_GAME_TYPE) { + trap->Print("g_gametype %i is out of range, defaulting to 0 (FFA/Deathmatch)\n", g_gametype.integer); level.gametype = GT_FFA; - } - else - level.gametype = atoi( g_gametype.string ); + } else + level.gametype = atoi(g_gametype.string); - trap->Cvar_Set( "g_gametype", va( "%i", level.gametype ) ); - trap->Cvar_Update( &g_gametype ); + trap->Cvar_Set("g_gametype", va("%i", level.gametype)); + trap->Cvar_Update(&g_gametype); } -void G_CacheMapname( const vmCvar_t *mapname ) -{ - Com_sprintf( level.mapname, sizeof( level.mapname ), "maps/%s.bsp", mapname->string ); - Com_sprintf( level.rawmapname, sizeof( level.rawmapname ), "maps/%s", mapname->string ); +void G_CacheMapname(const vmCvar_t *mapname) { + Com_sprintf(level.mapname, sizeof(level.mapname), "maps/%s.bsp", mapname->string); + Com_sprintf(level.rawmapname, sizeof(level.rawmapname), "maps/%s", mapname->string); } /* @@ -171,36 +159,36 @@ G_InitGame */ extern void RemoveAllWP(void); extern void BG_ClearVehicleParseParms(void); -gentity_t *SelectRandomDeathmatchSpawnPoint( qboolean isbot ); -void SP_info_jedimaster_start( gentity_t *ent ); -void G_InitGame( int levelTime, int randomSeed, int restart ) { - int i; - vmCvar_t mapname; - vmCvar_t ckSum; +gentity_t *SelectRandomDeathmatchSpawnPoint(qboolean isbot); +void SP_info_jedimaster_start(gentity_t *ent); +void G_InitGame(int levelTime, int randomSeed, int restart) { + int i; + vmCvar_t mapname; + vmCvar_t ckSum; char serverinfo[MAX_INFO_STRING] = {0}; - Rand_Init( randomSeed ); - srand( randomSeed ); + Rand_Init(randomSeed); + srand(randomSeed); - //Init RMG to 0, it will be autoset to 1 if there is terrain on the level. + // Init RMG to 0, it will be autoset to 1 if there is terrain on the level. trap->Cvar_Set("RMG", "0"); RMG.integer = 0; - //Clean up any client-server ghoul2 instance attachments that may still exist exe-side + // Clean up any client-server ghoul2 instance attachments that may still exist exe-side trap->G2API_CleanEntAttachments(); - BG_InitAnimsets(); //clear it out + BG_InitAnimsets(); // clear it out - B_InitAlloc(); //make sure everything is clean + B_InitAlloc(); // make sure everything is clean - trap->SV_RegisterSharedMemory( gSharedBuffer.raw ); + trap->SV_RegisterSharedMemory(gSharedBuffer.raw); - //Load external vehicle data + // Load external vehicle data BG_VehicleLoadParms(); - trap->Print ("------- Game Initialization -------\n"); - trap->Print ("gamename: %s\n", GAMEVERSION); - trap->Print ("gamedate: %s\n", SOURCE_DATE); + trap->Print("------- Game Initialization -------\n"); + trap->Print("gamename: %s\n", GAMEVERSION); + trap->Print("gamedate: %s\n", SOURCE_DATE); G_RegisterCvars(); @@ -209,50 +197,45 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { G_InitMemory(); // set some level globals - memset( &level, 0, sizeof( level ) ); + memset(&level, 0, sizeof(level)); level.time = levelTime; level.startTime = levelTime; level.follow1 = level.follow2 = -1; - level.snd_fry = G_SoundIndex("sound/player/fry.wav"); // FIXME standing in lava / slime + level.snd_fry = G_SoundIndex("sound/player/fry.wav"); // FIXME standing in lava / slime level.snd_hack = G_SoundIndex("sound/player/hacking.wav"); level.snd_medHealed = G_SoundIndex("sound/player/supp_healed.wav"); level.snd_medSupplied = G_SoundIndex("sound/player/supp_supplied.wav"); - //trap->SP_RegisterServer("mp_svgame"); + // trap->SP_RegisterServer("mp_svgame"); - if ( g_log.string[0] ) - { - trap->FS_Open( g_log.string, &level.logFile, g_logSync.integer ? FS_APPEND_SYNC : FS_APPEND ); - if ( level.logFile ) - trap->Print( "Logging to %s\n", g_log.string ); + if (g_log.string[0]) { + trap->FS_Open(g_log.string, &level.logFile, g_logSync.integer ? FS_APPEND_SYNC : FS_APPEND); + if (level.logFile) + trap->Print("Logging to %s\n", g_log.string); else - trap->Print( "WARNING: Couldn't open logfile: %s\n", g_log.string ); - } - else - trap->Print( "Not logging game events to disk.\n" ); - - trap->GetServerinfo( serverinfo, sizeof( serverinfo ) ); - G_LogPrintf( "------------------------------------------------------------\n" ); - G_LogPrintf( "InitGame: %s\n", serverinfo ); - - if ( g_securityLog.integer ) - { - if ( g_securityLog.integer == 1 ) - trap->FS_Open( SECURITY_LOG, &level.security.log, FS_APPEND ); - else if ( g_securityLog.integer == 2 ) - trap->FS_Open( SECURITY_LOG, &level.security.log, FS_APPEND_SYNC ); - - if ( level.security.log ) - trap->Print( "Logging to "SECURITY_LOG"\n" ); + trap->Print("WARNING: Couldn't open logfile: %s\n", g_log.string); + } else + trap->Print("Not logging game events to disk.\n"); + + trap->GetServerinfo(serverinfo, sizeof(serverinfo)); + G_LogPrintf("------------------------------------------------------------\n"); + G_LogPrintf("InitGame: %s\n", serverinfo); + + if (g_securityLog.integer) { + if (g_securityLog.integer == 1) + trap->FS_Open(SECURITY_LOG, &level.security.log, FS_APPEND); + else if (g_securityLog.integer == 2) + trap->FS_Open(SECURITY_LOG, &level.security.log, FS_APPEND_SYNC); + + if (level.security.log) + trap->Print("Logging to " SECURITY_LOG "\n"); else - trap->Print( "WARNING: Couldn't open logfile: "SECURITY_LOG"\n" ); - } - else - trap->Print( "Not logging security events to disk.\n" ); - + trap->Print("WARNING: Couldn't open logfile: " SECURITY_LOG "\n"); + } else + trap->Print("Not logging security events to disk.\n"); G_LogWeaponInit(); @@ -261,16 +244,16 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { G_InitWorldSession(); // initialize all entities for this game - memset( g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0]) ); + memset(g_entities, 0, MAX_GENTITIES * sizeof(g_entities[0])); level.gentities = g_entities; // initialize all clients for this game level.maxclients = sv_maxclients.integer; - memset( g_clients, 0, MAX_CLIENTS * sizeof(g_clients[0]) ); + memset(g_clients, 0, MAX_CLIENTS * sizeof(g_clients[0])); level.clients = g_clients; // set client fields on player ents - for ( i=0 ; iLocateGameData( (sharedEntity_t *)level.gentities, level.num_entities, sizeof( gentity_t ), - &level.clients[0].ps, sizeof( level.clients[0] ) ); + trap->LocateGameData((sharedEntity_t *)level.gentities, level.num_entities, sizeof(gentity_t), &level.clients[0].ps, sizeof(level.clients[0])); - //Load sabers.cfg data + // Load sabers.cfg data WP_SaberLoadParms(); NPC_InitGame(); TIMER_Clear(); // - //ICARUS INIT START + // ICARUS INIT START -// Com_Printf("------ ICARUS Initialization ------\n"); + // Com_Printf("------ ICARUS Initialization ------\n"); trap->ICARUS_Init(); -// Com_Printf ("-----------------------------------\n"); + // Com_Printf ("-----------------------------------\n"); - //ICARUS INIT END + // ICARUS INIT END // // reserve some spots for dead player bodies @@ -310,14 +292,14 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { ClearRegisteredItems(); - //make sure saber data is loaded before this! (so we can precache the appropriate hilts) + // make sure saber data is loaded before this! (so we can precache the appropriate hilts) InitSiegeMode(); - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); - G_CacheMapname( &mapname ); - trap->Cvar_Register( &ckSum, "sv_mapChecksum", "", CVAR_ROM ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); + G_CacheMapname(&mapname); + trap->Cvar_Register(&ckSum, "sv_mapChecksum", "", CVAR_ROM); - navCalculatePaths = ( trap->Nav_Load( mapname.string, ckSum.integer ) == qfalse ); + navCalculatePaths = (trap->Nav_Load(mapname.string, ckSum.integer) == qfalse); // parse the key/value pairs and spawn gentities G_SpawnEntitiesFromString(qfalse); @@ -326,61 +308,52 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { G_FindTeams(); // make sure we have flags for CTF, etc - if( level.gametype >= GT_TEAM ) { + if (level.gametype >= GT_TEAM) { G_CheckTeamItems(); - } - else if ( level.gametype == GT_JEDIMASTER ) - { - trap->SetConfigstring ( CS_CLIENT_JEDIMASTER, "-1" ); + } else if (level.gametype == GT_JEDIMASTER) { + trap->SetConfigstring(CS_CLIENT_JEDIMASTER, "-1"); } - if (level.gametype == GT_POWERDUEL) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("-1|-1|-1") ); - } - else - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("-1|-1") ); + if (level.gametype == GT_POWERDUEL) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("-1|-1|-1")); + } else { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("-1|-1")); } -// nmckenzie: DUEL_HEALTH: Default. - trap->SetConfigstring ( CS_CLIENT_DUELHEALTHS, va("-1|-1|!") ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, va("-1") ); + // nmckenzie: DUEL_HEALTH: Default. + trap->SetConfigstring(CS_CLIENT_DUELHEALTHS, va("-1|-1|!")); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, va("-1")); SaveRegisteredItems(); - //trap->Print ("-----------------------------------\n"); + // trap->Print ("-----------------------------------\n"); - if( level.gametype == GT_SINGLE_PLAYER || trap->Cvar_VariableIntegerValue( "com_buildScript" ) ) { - G_ModelIndex( SP_PODIUM_MODEL ); - G_SoundIndex( "sound/player/gurp1.wav" ); - G_SoundIndex( "sound/player/gurp2.wav" ); + if (level.gametype == GT_SINGLE_PLAYER || trap->Cvar_VariableIntegerValue("com_buildScript")) { + G_ModelIndex(SP_PODIUM_MODEL); + G_SoundIndex("sound/player/gurp1.wav"); + G_SoundIndex("sound/player/gurp2.wav"); } - if ( trap->Cvar_VariableIntegerValue( "bot_enable" ) ) { - BotAISetup( restart ); - BotAILoadMap( restart ); - G_InitBots( ); + if (trap->Cvar_VariableIntegerValue("bot_enable")) { + BotAISetup(restart); + BotAILoadMap(restart); + G_InitBots(); } else { G_LoadArenas(); } - if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) - { - G_LogPrintf("Duel Tournament Begun: kill limit %d, win limit: %d\n", fraglimit.integer, duel_fraglimit.integer ); + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + G_LogPrintf("Duel Tournament Begun: kill limit %d, win limit: %d\n", fraglimit.integer, duel_fraglimit.integer); } - if ( navCalculatePaths ) - {//not loaded - need to calc paths - navCalcPathTime = level.time + START_TIME_NAV_CALC;//make sure all ents are in and linked - } - else - {//loaded - //FIXME: if this is from a loadgame, it needs to be sure to write this - //out whenever you do a savegame since the edges and routes are dynamic... - //OR: always do a navigator.CheckBlockedEdges() on map startup after nav-load/calc-paths - //navigator.pathsCalculated = qtrue;//just to be safe? Does this get saved out? No... assumed + if (navCalculatePaths) { // not loaded - need to calc paths + navCalcPathTime = level.time + START_TIME_NAV_CALC; // make sure all ents are in and linked + } else { // loaded + // FIXME: if this is from a loadgame, it needs to be sure to write this + // out whenever you do a savegame since the edges and routes are dynamic... + // OR: always do a navigator.CheckBlockedEdges() on map startup after nav-load/calc-paths + // navigator.pathsCalculated = qtrue;//just to be safe? Does this get saved out? No... assumed trap->Nav_SetPathsCalculated(qtrue); - //need to do this, because combatpoint waypoints aren't saved out...? + // need to do this, because combatpoint waypoints aren't saved out...? CP_FindCombatPointWaypoints(); navCalcPathTime = 0; @@ -390,15 +363,12 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { trap->Nav_ClearAllFailedEdges(); } */ - //No loading games in MP. + // No loading games in MP. } - if (level.gametype == GT_SIEGE) - { //just get these configstrings registered now... - while (i < MAX_CUSTOM_SIEGE_SOUNDS) - { - if (!bg_customSiegeSoundNames[i]) - { + if (level.gametype == GT_SIEGE) { // just get these configstrings registered now... + while (i < MAX_CUSTOM_SIEGE_SOUNDS) { + if (!bg_customSiegeSoundNames[i]) { break; } G_SoundIndex((char *)bg_customSiegeSoundNames[i]); @@ -406,65 +376,58 @@ void G_InitGame( int levelTime, int randomSeed, int restart ) { } } - if ( level.gametype == GT_JEDIMASTER ) { + if (level.gametype == GT_JEDIMASTER) { gentity_t *ent = NULL; - int i=0; - for ( i=0, ent=g_entities; iisSaberEntity ) + int i = 0; + for (i = 0, ent = g_entities; i < level.num_entities; i++, ent++) { + if (ent->isSaberEntity) break; } - if ( i == level.num_entities ) { + if (i == level.num_entities) { // no JM saber found. drop one at one of the player spawnpoints - gentity_t *spawnpoint = SelectRandomDeathmatchSpawnPoint( qfalse ); + gentity_t *spawnpoint = SelectRandomDeathmatchSpawnPoint(qfalse); - if( !spawnpoint ) { - trap->Error( ERR_DROP, "Couldn't find an FFA spawnpoint to drop the jedimaster saber at!\n" ); + if (!spawnpoint) { + trap->Error(ERR_DROP, "Couldn't find an FFA spawnpoint to drop the jedimaster saber at!\n"); return; } ent = G_Spawn(); - G_SetOrigin( ent, spawnpoint->s.origin ); - SP_info_jedimaster_start( ent ); + G_SetOrigin(ent, spawnpoint->s.origin); + SP_info_jedimaster_start(ent); } } } - - /* ================= G_ShutdownGame ================= */ -void G_ShutdownGame( int restart ) { +void G_ShutdownGame(int restart) { int i = 0; gentity_t *ent; -// trap->Print ("==== ShutdownGame ====\n"); + // trap->Print ("==== ShutdownGame ====\n"); - G_CleanAllFakeClients(); //get rid of dynamically allocated fake client structs. + G_CleanAllFakeClients(); // get rid of dynamically allocated fake client structs. - BG_ClearAnimsets(); //free all dynamic allocations made through the engine + BG_ClearAnimsets(); // free all dynamic allocations made through the engine -// Com_Printf("... Gameside GHOUL2 Cleanup\n"); - while (i < MAX_GENTITIES) - { //clean up all the ghoul2 instances + // Com_Printf("... Gameside GHOUL2 Cleanup\n"); + while (i < MAX_GENTITIES) { // clean up all the ghoul2 instances ent = &g_entities[i]; - if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) - { + if (ent->ghoul2 && trap->G2API_HaveWeGhoul2Models(ent->ghoul2)) { trap->G2API_CleanGhoul2Models(&ent->ghoul2); ent->ghoul2 = NULL; } - if (ent->client) - { + if (ent->client) { int j = 0; - while (j < MAX_SABERS) - { - if (ent->client->weaponGhoul2[j] && trap->G2API_HaveWeGhoul2Models(ent->client->weaponGhoul2[j])) - { + while (j < MAX_SABERS) { + if (ent->client->weaponGhoul2[j] && trap->G2API_HaveWeGhoul2Models(ent->client->weaponGhoul2[j])) { trap->G2API_CleanGhoul2Models(&ent->client->weaponGhoul2[j]); } j++; @@ -472,35 +435,32 @@ void G_ShutdownGame( int restart ) { } i++; } - if (g2SaberInstance && trap->G2API_HaveWeGhoul2Models(g2SaberInstance)) - { + if (g2SaberInstance && trap->G2API_HaveWeGhoul2Models(g2SaberInstance)) { trap->G2API_CleanGhoul2Models(&g2SaberInstance); g2SaberInstance = NULL; } - if (precachedKyle && trap->G2API_HaveWeGhoul2Models(precachedKyle)) - { + if (precachedKyle && trap->G2API_HaveWeGhoul2Models(precachedKyle)) { trap->G2API_CleanGhoul2Models(&precachedKyle); precachedKyle = NULL; } -// Com_Printf ("... ICARUS_Shutdown\n"); - trap->ICARUS_Shutdown (); //Shut ICARUS down + // Com_Printf ("... ICARUS_Shutdown\n"); + trap->ICARUS_Shutdown(); // Shut ICARUS down -// Com_Printf ("... Reference Tags Cleared\n"); - TAG_Init(); //Clear the reference tags + // Com_Printf ("... Reference Tags Cleared\n"); + TAG_Init(); // Clear the reference tags G_LogWeaponOutput(); - if ( level.logFile ) { - G_LogPrintf( "ShutdownGame:\n------------------------------------------------------------\n" ); - trap->FS_Close( level.logFile ); + if (level.logFile) { + G_LogPrintf("ShutdownGame:\n------------------------------------------------------------\n"); + trap->FS_Close(level.logFile); level.logFile = 0; } - if ( level.security.log ) - { - G_SecurityLogPrintf( "ShutdownGame\n\n" ); - trap->FS_Close( level.security.log ); + if (level.security.log) { + G_SecurityLogPrintf("ShutdownGame\n\n"); + trap->FS_Close(level.security.log); level.security.log = 0; } @@ -509,11 +469,11 @@ void G_ShutdownGame( int restart ) { trap->ROFF_Clean(); - if ( trap->Cvar_VariableIntegerValue( "bot_enable" ) ) { - BotAIShutdown( restart ); + if (trap->Cvar_VariableIntegerValue("bot_enable")) { + BotAIShutdown(restart); } - B_CleanupAlloc(); //clean up all allocations made with B_Alloc + B_CleanupAlloc(); // clean up all allocations made with B_Alloc } /* @@ -532,52 +492,50 @@ If there are less than two tournament players, put a spectator in the game and restart ============= */ -void AddTournamentPlayer( void ) { - int i; - gclient_t *client; - gclient_t *nextInLine; +void AddTournamentPlayer(void) { + int i; + gclient_t *client; + gclient_t *nextInLine; - if ( level.numPlayingClients >= 2 ) { + if (level.numPlayingClients >= 2) { return; } // never change during intermission -// if ( level.intermissiontime ) { -// return; -// } + // if ( level.intermissiontime ) { + // return; + // } nextInLine = NULL; - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { client = &level.clients[i]; - if ( client->pers.connected != CON_CONNECTED ) { + if (client->pers.connected != CON_CONNECTED) { continue; } - if (!g_allowHighPingDuelist.integer && client->ps.ping >= 999) - { //don't add people who are lagging out if cvar is not set to allow it. + if (!g_allowHighPingDuelist.integer && client->ps.ping >= 999) { // don't add people who are lagging out if cvar is not set to allow it. continue; } - if ( client->sess.sessionTeam != TEAM_SPECTATOR ) { + if (client->sess.sessionTeam != TEAM_SPECTATOR) { continue; } // never select the dedicated follow or scoreboard clients - if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD || - client->sess.spectatorClient < 0 ) { + if (client->sess.spectatorState == SPECTATOR_SCOREBOARD || client->sess.spectatorClient < 0) { continue; } - if ( !nextInLine || client->sess.spectatorNum > nextInLine->sess.spectatorNum ) + if (!nextInLine || client->sess.spectatorNum > nextInLine->sess.spectatorNum) nextInLine = client; } - if ( !nextInLine ) { + if (!nextInLine) { return; } level.warmupTime = -1; // set them to free-for-all team - SetTeam( &g_entities[ nextInLine - level.clients ], "f" ); + SetTeam(&g_entities[nextInLine - level.clients], "f"); } /* @@ -588,20 +546,17 @@ Add client to end of tournament queue ======================= */ -void AddTournamentQueue( gclient_t *client ) -{ +void AddTournamentQueue(gclient_t *client) { int index; gclient_t *curclient; - for( index = 0; index < level.maxclients; index++ ) - { + for (index = 0; index < level.maxclients; index++) { curclient = &level.clients[index]; - if ( curclient->pers.connected != CON_DISCONNECTED ) - { - if ( curclient == client ) + if (curclient->pers.connected != CON_DISCONNECTED) { + if (curclient == client) curclient->sess.spectatorNum = 0; - else if ( curclient->sess.sessionTeam == TEAM_SPECTATOR ) + else if (curclient->sess.sessionTeam == TEAM_SPECTATOR) curclient->sess.spectatorNum++; } } @@ -614,40 +569,34 @@ RemoveTournamentLoser Make the loser a spectator at the back of the line ======================= */ -void RemoveTournamentLoser( void ) { - int clientNum; +void RemoveTournamentLoser(void) { + int clientNum; - if ( level.numPlayingClients != 2 ) { + if (level.numPlayingClients != 2) { return; } clientNum = level.sortedClients[1]; - if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) { + if (level.clients[clientNum].pers.connected != CON_CONNECTED) { return; } // make them a spectator - SetTeam( &g_entities[ clientNum ], "s" ); + SetTeam(&g_entities[clientNum], "s"); } -void G_PowerDuelCount(int *loners, int *doubles, qboolean countSpec) -{ +void G_PowerDuelCount(int *loners, int *doubles, qboolean countSpec) { int i = 0; gclient_t *cl; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { cl = g_entities[i].client; - if (g_entities[i].inuse && cl && (countSpec || cl->sess.sessionTeam != TEAM_SPECTATOR)) - { - if (cl->sess.duelTeam == DUELTEAM_LONE) - { + if (g_entities[i].inuse && cl && (countSpec || cl->sess.sessionTeam != TEAM_SPECTATOR)) { + if (cl->sess.duelTeam == DUELTEAM_LONE) { (*loners)++; - } - else if (cl->sess.duelTeam == DUELTEAM_DOUBLE) - { + } else if (cl->sess.duelTeam == DUELTEAM_DOUBLE) { (*doubles)++; } } @@ -656,106 +605,94 @@ void G_PowerDuelCount(int *loners, int *doubles, qboolean countSpec) } qboolean g_duelAssigning = qfalse; -void AddPowerDuelPlayers( void ) -{ - int i; - int loners = 0; - int doubles = 0; - int nonspecLoners = 0; - int nonspecDoubles = 0; - gclient_t *client; - gclient_t *nextInLine; - - if ( level.numPlayingClients >= 3 ) - { +void AddPowerDuelPlayers(void) { + int i; + int loners = 0; + int doubles = 0; + int nonspecLoners = 0; + int nonspecDoubles = 0; + gclient_t *client; + gclient_t *nextInLine; + + if (level.numPlayingClients >= 3) { return; } nextInLine = NULL; G_PowerDuelCount(&nonspecLoners, &nonspecDoubles, qfalse); - if (nonspecLoners >= 1 && nonspecDoubles >= 2) - { //we have enough people, stop + if (nonspecLoners >= 1 && nonspecDoubles >= 2) { // we have enough people, stop return; } - //Could be written faster, but it's not enough to care I suppose. + // Could be written faster, but it's not enough to care I suppose. G_PowerDuelCount(&loners, &doubles, qtrue); - if (loners < 1 || doubles < 2) - { //don't bother trying to spawn anyone yet if the balance is not even set up between spectators + if (loners < 1 || doubles < 2) { // don't bother trying to spawn anyone yet if the balance is not even set up between spectators return; } - //Count again, with only in-game clients in mind. + // Count again, with only in-game clients in mind. loners = nonspecLoners; doubles = nonspecDoubles; -// G_PowerDuelCount(&loners, &doubles, qfalse); + // G_PowerDuelCount(&loners, &doubles, qfalse); - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { client = &level.clients[i]; - if ( client->pers.connected != CON_CONNECTED ) { + if (client->pers.connected != CON_CONNECTED) { continue; } - if ( client->sess.sessionTeam != TEAM_SPECTATOR ) { + if (client->sess.sessionTeam != TEAM_SPECTATOR) { continue; } - if (client->sess.duelTeam == DUELTEAM_FREE) - { + if (client->sess.duelTeam == DUELTEAM_FREE) { continue; } - if (client->sess.duelTeam == DUELTEAM_LONE && loners >= 1) - { + if (client->sess.duelTeam == DUELTEAM_LONE && loners >= 1) { continue; } - if (client->sess.duelTeam == DUELTEAM_DOUBLE && doubles >= 2) - { + if (client->sess.duelTeam == DUELTEAM_DOUBLE && doubles >= 2) { continue; } // never select the dedicated follow or scoreboard clients - if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD || - client->sess.spectatorClient < 0 ) { + if (client->sess.spectatorState == SPECTATOR_SCOREBOARD || client->sess.spectatorClient < 0) { continue; } - if ( !nextInLine || client->sess.spectatorNum > nextInLine->sess.spectatorNum ) + if (!nextInLine || client->sess.spectatorNum > nextInLine->sess.spectatorNum) nextInLine = client; } - if ( !nextInLine ) { + if (!nextInLine) { return; } level.warmupTime = -1; // set them to free-for-all team - SetTeam( &g_entities[ nextInLine - level.clients ], "f" ); + SetTeam(&g_entities[nextInLine - level.clients], "f"); - //Call recursively until everyone is in + // Call recursively until everyone is in AddPowerDuelPlayers(); } qboolean g_dontFrickinCheck = qfalse; -void RemovePowerDuelLosers(void) -{ +void RemovePowerDuelLosers(void) { int remClients[3]; int remNum = 0; int i = 0; gclient_t *cl; - while (i < MAX_CLIENTS && remNum < 3) - { - //cl = &level.clients[level.sortedClients[i]]; + while (i < MAX_CLIENTS && remNum < 3) { + // cl = &level.clients[level.sortedClients[i]]; cl = &level.clients[i]; - if (cl->pers.connected == CON_CONNECTED) - { + if (cl->pers.connected == CON_CONNECTED) { if ((cl->ps.stats[STAT_HEALTH] <= 0 || cl->iAmALoser) && - (cl->sess.sessionTeam != TEAM_SPECTATOR || cl->iAmALoser)) - { //he was dead or he was spectating as a loser - remClients[remNum] = i; + (cl->sess.sessionTeam != TEAM_SPECTATOR || cl->iAmALoser)) { // he was dead or he was spectating as a loser + remClients[remNum] = i; remNum++; } } @@ -763,63 +700,50 @@ void RemovePowerDuelLosers(void) i++; } - if (!remNum) - { //Time ran out or something? Oh well, just remove the main guy. + if (!remNum) { // Time ran out or something? Oh well, just remove the main guy. remClients[remNum] = level.sortedClients[0]; remNum++; } i = 0; - while (i < remNum) - { //set them all to spectator - SetTeam( &g_entities[ remClients[i] ], "s" ); + while (i < remNum) { // set them all to spectator + SetTeam(&g_entities[remClients[i]], "s"); i++; } g_dontFrickinCheck = qfalse; - //recalculate stuff now that we have reset teams. + // recalculate stuff now that we have reset teams. CalculateRanks(); } -void RemoveDuelDrawLoser(void) -{ +void RemoveDuelDrawLoser(void) { int clFirst = 0; int clSec = 0; int clFailure = 0; - if ( level.clients[ level.sortedClients[0] ].pers.connected != CON_CONNECTED ) - { + if (level.clients[level.sortedClients[0]].pers.connected != CON_CONNECTED) { return; } - if ( level.clients[ level.sortedClients[1] ].pers.connected != CON_CONNECTED ) - { + if (level.clients[level.sortedClients[1]].pers.connected != CON_CONNECTED) { return; } - clFirst = level.clients[ level.sortedClients[0] ].ps.stats[STAT_HEALTH] + level.clients[ level.sortedClients[0] ].ps.stats[STAT_ARMOR]; - clSec = level.clients[ level.sortedClients[1] ].ps.stats[STAT_HEALTH] + level.clients[ level.sortedClients[1] ].ps.stats[STAT_ARMOR]; + clFirst = level.clients[level.sortedClients[0]].ps.stats[STAT_HEALTH] + level.clients[level.sortedClients[0]].ps.stats[STAT_ARMOR]; + clSec = level.clients[level.sortedClients[1]].ps.stats[STAT_HEALTH] + level.clients[level.sortedClients[1]].ps.stats[STAT_ARMOR]; - if (clFirst > clSec) - { + if (clFirst > clSec) { clFailure = 1; - } - else if (clSec > clFirst) - { + } else if (clSec > clFirst) { clFailure = 0; - } - else - { + } else { clFailure = 2; } - if (clFailure != 2) - { - SetTeam( &g_entities[ level.sortedClients[clFailure] ], "s" ); - } - else - { //we could be more elegant about this, but oh well. - SetTeam( &g_entities[ level.sortedClients[1] ], "s" ); + if (clFailure != 2) { + SetTeam(&g_entities[level.sortedClients[clFailure]], "s"); + } else { // we could be more elegant about this, but oh well. + SetTeam(&g_entities[level.sortedClients[1]], "s"); } } @@ -828,21 +752,21 @@ void RemoveDuelDrawLoser(void) RemoveTournamentWinner ======================= */ -void RemoveTournamentWinner( void ) { - int clientNum; +void RemoveTournamentWinner(void) { + int clientNum; - if ( level.numPlayingClients != 2 ) { + if (level.numPlayingClients != 2) { return; } clientNum = level.sortedClients[0]; - if ( level.clients[ clientNum ].pers.connected != CON_CONNECTED ) { + if (level.clients[clientNum].pers.connected != CON_CONNECTED) { return; } // make them a spectator - SetTeam( &g_entities[ clientNum ], "s" ); + SetTeam(&g_entities[clientNum], "s"); } /* @@ -850,79 +774,66 @@ void RemoveTournamentWinner( void ) { AdjustTournamentScores ======================= */ -void AdjustTournamentScores( void ) { - int clientNum; +void AdjustTournamentScores(void) { + int clientNum; - if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == - level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && - level.clients[level.sortedClients[0]].pers.connected == CON_CONNECTED && - level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) - { - int clFirst = level.clients[ level.sortedClients[0] ].ps.stats[STAT_HEALTH] + level.clients[ level.sortedClients[0] ].ps.stats[STAT_ARMOR]; - int clSec = level.clients[ level.sortedClients[1] ].ps.stats[STAT_HEALTH] + level.clients[ level.sortedClients[1] ].ps.stats[STAT_ARMOR]; + if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && + level.clients[level.sortedClients[0]].pers.connected == CON_CONNECTED && level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) { + int clFirst = level.clients[level.sortedClients[0]].ps.stats[STAT_HEALTH] + level.clients[level.sortedClients[0]].ps.stats[STAT_ARMOR]; + int clSec = level.clients[level.sortedClients[1]].ps.stats[STAT_HEALTH] + level.clients[level.sortedClients[1]].ps.stats[STAT_ARMOR]; int clFailure = 0; int clSuccess = 0; - if (clFirst > clSec) - { + if (clFirst > clSec) { clFailure = 1; clSuccess = 0; - } - else if (clSec > clFirst) - { + } else if (clSec > clFirst) { clFailure = 0; clSuccess = 1; - } - else - { + } else { clFailure = 2; clSuccess = 2; } - if (clFailure != 2) - { + if (clFailure != 2) { clientNum = level.sortedClients[clSuccess]; - level.clients[ clientNum ].sess.wins++; - ClientUserinfoChanged( clientNum ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, va("%i", clientNum ) ); + level.clients[clientNum].sess.wins++; + ClientUserinfoChanged(clientNum); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, va("%i", clientNum)); clientNum = level.sortedClients[clFailure]; - level.clients[ clientNum ].sess.losses++; - ClientUserinfoChanged( clientNum ); - } - else - { + level.clients[clientNum].sess.losses++; + ClientUserinfoChanged(clientNum); + } else { clSuccess = 0; clFailure = 1; clientNum = level.sortedClients[clSuccess]; - level.clients[ clientNum ].sess.wins++; - ClientUserinfoChanged( clientNum ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, va("%i", clientNum ) ); + level.clients[clientNum].sess.wins++; + ClientUserinfoChanged(clientNum); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, va("%i", clientNum)); clientNum = level.sortedClients[clFailure]; - level.clients[ clientNum ].sess.losses++; - ClientUserinfoChanged( clientNum ); + level.clients[clientNum].sess.losses++; + ClientUserinfoChanged(clientNum); } - } - else - { + } else { clientNum = level.sortedClients[0]; - if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) { - level.clients[ clientNum ].sess.wins++; - ClientUserinfoChanged( clientNum ); + if (level.clients[clientNum].pers.connected == CON_CONNECTED) { + level.clients[clientNum].sess.wins++; + ClientUserinfoChanged(clientNum); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, va("%i", clientNum ) ); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, va("%i", clientNum)); } clientNum = level.sortedClients[1]; - if ( level.clients[ clientNum ].pers.connected == CON_CONNECTED ) { - level.clients[ clientNum ].sess.losses++; - ClientUserinfoChanged( clientNum ); + if (level.clients[clientNum].pers.connected == CON_CONNECTED) { + level.clients[clientNum].sess.losses++; + ClientUserinfoChanged(clientNum); } } } @@ -933,68 +844,62 @@ SortRanks ============= */ -int QDECL SortRanks( const void *a, const void *b ) { - gclient_t *ca, *cb; +int QDECL SortRanks(const void *a, const void *b) { + gclient_t *ca, *cb; ca = &level.clients[*(int *)a]; cb = &level.clients[*(int *)b]; - if (level.gametype == GT_POWERDUEL) - { - //sort single duelists first - if (ca->sess.duelTeam == DUELTEAM_LONE && ca->sess.sessionTeam != TEAM_SPECTATOR) - { + if (level.gametype == GT_POWERDUEL) { + // sort single duelists first + if (ca->sess.duelTeam == DUELTEAM_LONE && ca->sess.sessionTeam != TEAM_SPECTATOR) { return -1; } - if (cb->sess.duelTeam == DUELTEAM_LONE && cb->sess.sessionTeam != TEAM_SPECTATOR) - { + if (cb->sess.duelTeam == DUELTEAM_LONE && cb->sess.sessionTeam != TEAM_SPECTATOR) { return 1; } - //others will be auto-sorted below but above spectators. + // others will be auto-sorted below but above spectators. } // sort special clients last - if ( ca->sess.spectatorState == SPECTATOR_SCOREBOARD || ca->sess.spectatorClient < 0 ) { + if (ca->sess.spectatorState == SPECTATOR_SCOREBOARD || ca->sess.spectatorClient < 0) { return 1; } - if ( cb->sess.spectatorState == SPECTATOR_SCOREBOARD || cb->sess.spectatorClient < 0 ) { + if (cb->sess.spectatorState == SPECTATOR_SCOREBOARD || cb->sess.spectatorClient < 0) { return -1; } // then connecting clients - if ( ca->pers.connected == CON_CONNECTING ) { + if (ca->pers.connected == CON_CONNECTING) { return 1; } - if ( cb->pers.connected == CON_CONNECTING ) { + if (cb->pers.connected == CON_CONNECTING) { return -1; } - // then spectators - if ( ca->sess.sessionTeam == TEAM_SPECTATOR && cb->sess.sessionTeam == TEAM_SPECTATOR ) { - if ( ca->sess.spectatorNum > cb->sess.spectatorNum ) { + if (ca->sess.sessionTeam == TEAM_SPECTATOR && cb->sess.sessionTeam == TEAM_SPECTATOR) { + if (ca->sess.spectatorNum > cb->sess.spectatorNum) { return -1; } - if ( ca->sess.spectatorNum < cb->sess.spectatorNum ) { + if (ca->sess.spectatorNum < cb->sess.spectatorNum) { return 1; } return 0; } - if ( ca->sess.sessionTeam == TEAM_SPECTATOR ) { + if (ca->sess.sessionTeam == TEAM_SPECTATOR) { return 1; } - if ( cb->sess.sessionTeam == TEAM_SPECTATOR ) { + if (cb->sess.sessionTeam == TEAM_SPECTATOR) { return -1; } // then sort by score - if ( ca->ps.persistant[PERS_SCORE] - > cb->ps.persistant[PERS_SCORE] ) { + if (ca->ps.persistant[PERS_SCORE] > cb->ps.persistant[PERS_SCORE]) { return -1; } - if ( ca->ps.persistant[PERS_SCORE] - < cb->ps.persistant[PERS_SCORE] ) { + if (ca->ps.persistant[PERS_SCORE] < cb->ps.persistant[PERS_SCORE]) { return 1; } return 0; @@ -1003,21 +908,16 @@ int QDECL SortRanks( const void *a, const void *b ) { qboolean gQueueScoreMessage = qfalse; int gQueueScoreMessageTime = 0; -//A new duel started so respawn everyone and make sure their stats are reset -qboolean G_CanResetDuelists(void) -{ +// A new duel started so respawn everyone and make sure their stats are reset +qboolean G_CanResetDuelists(void) { int i; gentity_t *ent; i = 0; - while (i < 3) - { //precheck to make sure they are all respawnable + while (i < 3) { // precheck to make sure they are all respawnable ent = &g_entities[level.sortedClients[i]]; - if (!ent->inuse || !ent->client || ent->health <= 0 || - ent->client->sess.sessionTeam == TEAM_SPECTATOR || - ent->client->sess.duelTeam <= DUELTEAM_FREE) - { + if (!ent->inuse || !ent->client || ent->health <= 0 || ent->client->sess.sessionTeam == TEAM_SPECTATOR || ent->client->sess.duelTeam <= DUELTEAM_FREE) { return qfalse; } i++; @@ -1027,20 +927,18 @@ qboolean G_CanResetDuelists(void) } qboolean g_noPDuelCheck = qfalse; -void G_ResetDuelists(void) -{ +void G_ResetDuelists(void) { int i; gentity_t *ent = NULL; i = 0; - while (i < 3) - { + while (i < 3) { ent = &g_entities[level.sortedClients[i]]; g_noPDuelCheck = qtrue; player_die(ent, ent, ent, 999, MOD_SUICIDE); g_noPDuelCheck = qfalse; - trap->UnlinkEntity ((sharedEntity_t *)ent); + trap->UnlinkEntity((sharedEntity_t *)ent); ClientSpawn(ent); i++; } @@ -1055,58 +953,53 @@ This will be called on every client connect, begin, disconnect, death, and team change. ============ */ -void CalculateRanks( void ) { - int i; - int rank; - int score; - int newScore; -// int preNumSpec = 0; - //int nonSpecIndex = -1; - gclient_t *cl; +void CalculateRanks(void) { + int i; + int rank; + int score; + int newScore; + // int preNumSpec = 0; + // int nonSpecIndex = -1; + gclient_t *cl; -// preNumSpec = level.numNonSpectatorClients; + // preNumSpec = level.numNonSpectatorClients; level.follow1 = -1; level.follow2 = -1; level.numConnectedClients = 0; level.numNonSpectatorClients = 0; level.numPlayingClients = 0; - level.numVotingClients = 0; // don't count bots + level.numVotingClients = 0; // don't count bots - for ( i = 0; i < ARRAY_LEN(level.numteamVotingClients); i++ ) { + for (i = 0; i < ARRAY_LEN(level.numteamVotingClients); i++) { level.numteamVotingClients[i] = 0; } - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected != CON_DISCONNECTED ) { + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected != CON_DISCONNECTED) { level.sortedClients[level.numConnectedClients] = i; level.numConnectedClients++; - if ( level.clients[i].sess.sessionTeam != TEAM_SPECTATOR || level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) - { - if (level.clients[i].sess.sessionTeam != TEAM_SPECTATOR) - { + if (level.clients[i].sess.sessionTeam != TEAM_SPECTATOR || level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + if (level.clients[i].sess.sessionTeam != TEAM_SPECTATOR) { level.numNonSpectatorClients++; - //nonSpecIndex = i; + // nonSpecIndex = i; } // decide if this should be auto-followed - if ( level.clients[i].pers.connected == CON_CONNECTED ) - { - if (level.clients[i].sess.sessionTeam != TEAM_SPECTATOR || level.clients[i].iAmALoser) - { + if (level.clients[i].pers.connected == CON_CONNECTED) { + if (level.clients[i].sess.sessionTeam != TEAM_SPECTATOR || level.clients[i].iAmALoser) { level.numPlayingClients++; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) - { + if (!(g_entities[i].r.svFlags & SVF_BOT)) { level.numVotingClients++; - if ( level.clients[i].sess.sessionTeam == TEAM_RED ) + if (level.clients[i].sess.sessionTeam == TEAM_RED) level.numteamVotingClients[0]++; - else if ( level.clients[i].sess.sessionTeam == TEAM_BLUE ) + else if (level.clients[i].sess.sessionTeam == TEAM_BLUE) level.numteamVotingClients[1]++; } - if ( level.follow1 == -1 ) { + if (level.follow1 == -1) { level.follow1 = i; - } else if ( level.follow2 == -1 ) { + } else if (level.follow2 == -1) { level.follow2 = i; } } @@ -1114,20 +1007,19 @@ void CalculateRanks( void ) { } } - if ( !g_warmup.integer || level.gametype == GT_SIEGE ) + if (!g_warmup.integer || level.gametype == GT_SIEGE) level.warmupTime = 0; - qsort( level.sortedClients, level.numConnectedClients, - sizeof(level.sortedClients[0]), SortRanks ); + qsort(level.sortedClients, level.numConnectedClients, sizeof(level.sortedClients[0]), SortRanks); // set the rank value for all clients that are connected and not spectators - if ( level.gametype >= GT_TEAM ) { + if (level.gametype >= GT_TEAM) { // in team games, rank is just the order of the teams, 0=red, 1=blue, 2=tied - for ( i = 0; i < level.numConnectedClients; i++ ) { - cl = &level.clients[ level.sortedClients[i] ]; - if ( level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE] ) { + for (i = 0; i < level.numConnectedClients; i++) { + cl = &level.clients[level.sortedClients[i]]; + if (level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE]) { cl->ps.persistant[PERS_RANK] = 2; - } else if ( level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE] ) { + } else if (level.teamScores[TEAM_RED] > level.teamScores[TEAM_BLUE]) { cl->ps.persistant[PERS_RANK] = 0; } else { cl->ps.persistant[PERS_RANK] = 1; @@ -1136,50 +1028,47 @@ void CalculateRanks( void ) { } else { rank = -1; score = 0; - for ( i = 0; i < level.numPlayingClients; i++ ) { - cl = &level.clients[ level.sortedClients[i] ]; + for (i = 0; i < level.numPlayingClients; i++) { + cl = &level.clients[level.sortedClients[i]]; newScore = cl->ps.persistant[PERS_SCORE]; - if ( i == 0 || newScore != score ) { + if (i == 0 || newScore != score) { rank = i; // assume we aren't tied until the next client is checked - level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank; - } else if(i != 0 ){ + level.clients[level.sortedClients[i]].ps.persistant[PERS_RANK] = rank; + } else if (i != 0) { // we are tied with the previous client - level.clients[ level.sortedClients[i-1] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; - level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; + level.clients[level.sortedClients[i - 1]].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; + level.clients[level.sortedClients[i]].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; } score = newScore; - if ( level.gametype == GT_SINGLE_PLAYER && level.numPlayingClients == 1 ) { - level.clients[ level.sortedClients[i] ].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; + if (level.gametype == GT_SINGLE_PLAYER && level.numPlayingClients == 1) { + level.clients[level.sortedClients[i]].ps.persistant[PERS_RANK] = rank | RANK_TIED_FLAG; } } } // set the CS_SCORES1/2 configstrings, which will be visible to everyone - if ( level.gametype >= GT_TEAM ) { - trap->SetConfigstring( CS_SCORES1, va("%i", level.teamScores[TEAM_RED] ) ); - trap->SetConfigstring( CS_SCORES2, va("%i", level.teamScores[TEAM_BLUE] ) ); + if (level.gametype >= GT_TEAM) { + trap->SetConfigstring(CS_SCORES1, va("%i", level.teamScores[TEAM_RED])); + trap->SetConfigstring(CS_SCORES2, va("%i", level.teamScores[TEAM_BLUE])); } else { - if ( level.numConnectedClients == 0 ) { - trap->SetConfigstring( CS_SCORES1, va("%i", SCORE_NOT_PRESENT) ); - trap->SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) ); - } else if ( level.numConnectedClients == 1 ) { - trap->SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) ); - trap->SetConfigstring( CS_SCORES2, va("%i", SCORE_NOT_PRESENT) ); + if (level.numConnectedClients == 0) { + trap->SetConfigstring(CS_SCORES1, va("%i", SCORE_NOT_PRESENT)); + trap->SetConfigstring(CS_SCORES2, va("%i", SCORE_NOT_PRESENT)); + } else if (level.numConnectedClients == 1) { + trap->SetConfigstring(CS_SCORES1, va("%i", level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE])); + trap->SetConfigstring(CS_SCORES2, va("%i", SCORE_NOT_PRESENT)); } else { - trap->SetConfigstring( CS_SCORES1, va("%i", level.clients[ level.sortedClients[0] ].ps.persistant[PERS_SCORE] ) ); - trap->SetConfigstring( CS_SCORES2, va("%i", level.clients[ level.sortedClients[1] ].ps.persistant[PERS_SCORE] ) ); + trap->SetConfigstring(CS_SCORES1, va("%i", level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE])); + trap->SetConfigstring(CS_SCORES2, va("%i", level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE])); } - if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) - { //when not in duel, use this configstring to pass the index of the player currently in first place - if ( level.numConnectedClients >= 1 ) - { - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, va("%i", level.sortedClients[0] ) ); - } - else - { - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + if (level.gametype != GT_DUEL && + level.gametype != GT_POWERDUEL) { // when not in duel, use this configstring to pass the index of the player currently in first place + if (level.numConnectedClients >= 1) { + trap->SetConfigstring(CS_CLIENT_DUELWINNER, va("%i", level.sortedClients[0])); + } else { + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); } } } @@ -1188,15 +1077,14 @@ void CalculateRanks( void ) { CheckExitRules(); // if we are at the intermission or in multi-frag Duel game mode, send the new info to everyone - if ( level.intermissiontime || level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) { + if (level.intermissiontime || level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { gQueueScoreMessage = qtrue; gQueueScoreMessageTime = level.time + 500; - //SendScoreboardMessageToAllClients(); - //rww - Made this operate on a "queue" system because it was causing large overflows + // SendScoreboardMessageToAllClients(); + // rww - Made this operate on a "queue" system because it was causing large overflows } } - /* ======================================================================== @@ -1213,12 +1101,12 @@ Do this at BeginIntermission time and whenever ranks are recalculated due to enters/exits/forced team changes ======================== */ -void SendScoreboardMessageToAllClients( void ) { - int i; +void SendScoreboardMessageToAllClients(void) { + int i; - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[ i ].pers.connected == CON_CONNECTED ) { - DeathmatchScoreboardMessage( g_entities + i ); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { + DeathmatchScoreboardMessage(g_entities + i); } } } @@ -1231,24 +1119,24 @@ When the intermission starts, this will be called for all players. If a new client connects, this will be called after the spawn function. ======================== */ -extern void G_LeaveVehicle( gentity_t *ent, qboolean ConCheck ); -void MoveClientToIntermission( gentity_t *ent ) { +extern void G_LeaveVehicle(gentity_t *ent, qboolean ConCheck); +void MoveClientToIntermission(gentity_t *ent) { // take out of follow mode if needed - if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) { - StopFollowing( ent ); + if (ent->client->sess.spectatorState == SPECTATOR_FOLLOW) { + StopFollowing(ent); } FindIntermissionPoint(); // move to the spot - VectorCopy( level.intermission_origin, ent->s.origin ); - VectorCopy( level.intermission_origin, ent->client->ps.origin ); - VectorCopy (level.intermission_angle, ent->client->ps.viewangles); + VectorCopy(level.intermission_origin, ent->s.origin); + VectorCopy(level.intermission_origin, ent->client->ps.origin); + VectorCopy(level.intermission_angle, ent->client->ps.viewangles); ent->client->ps.pm_type = PM_INTERMISSION; // clean up powerup info - memset( ent->client->ps.powerups, 0, sizeof(ent->client->ps.powerups) ); + memset(ent->client->ps.powerups, 0, sizeof(ent->client->ps.powerups)); - G_LeaveVehicle( ent, qfalse ); + G_LeaveVehicle(ent, qfalse); ent->client->ps.rocketLockIndex = ENTITYNUM_NONE; ent->client->ps.rocketLockTime = 0; @@ -1272,52 +1160,42 @@ FindIntermissionPoint This is also used for spectator spawns ================== */ -extern qboolean gSiegeRoundBegun; -extern qboolean gSiegeRoundEnded; -extern int gSiegeRoundWinningTeam; -void FindIntermissionPoint( void ) { - gentity_t *ent = NULL; - gentity_t *target; - vec3_t dir; +extern qboolean gSiegeRoundBegun; +extern qboolean gSiegeRoundEnded; +extern int gSiegeRoundWinningTeam; +void FindIntermissionPoint(void) { + gentity_t *ent = NULL; + gentity_t *target; + vec3_t dir; // find the intermission spot - if ( level.gametype == GT_SIEGE - && level.intermissiontime - && level.intermissiontime <= level.time - && gSiegeRoundEnded ) - { - if (gSiegeRoundWinningTeam == SIEGETEAM_TEAM1) - { - ent = G_Find (NULL, FOFS(classname), "info_player_intermission_red"); - if ( ent && ent->target2 ) - { - G_UseTargets2( ent, ent, ent->target2 ); + if (level.gametype == GT_SIEGE && level.intermissiontime && level.intermissiontime <= level.time && gSiegeRoundEnded) { + if (gSiegeRoundWinningTeam == SIEGETEAM_TEAM1) { + ent = G_Find(NULL, FOFS(classname), "info_player_intermission_red"); + if (ent && ent->target2) { + G_UseTargets2(ent, ent, ent->target2); } - } - else if (gSiegeRoundWinningTeam == SIEGETEAM_TEAM2) - { - ent = G_Find (NULL, FOFS(classname), "info_player_intermission_blue"); - if ( ent && ent->target2 ) - { - G_UseTargets2( ent, ent, ent->target2 ); + } else if (gSiegeRoundWinningTeam == SIEGETEAM_TEAM2) { + ent = G_Find(NULL, FOFS(classname), "info_player_intermission_blue"); + if (ent && ent->target2) { + G_UseTargets2(ent, ent, ent->target2); } } } - if ( !ent ) - { - ent = G_Find (NULL, FOFS(classname), "info_player_intermission"); + if (!ent) { + ent = G_Find(NULL, FOFS(classname), "info_player_intermission"); } - if ( !ent ) { // the map creator forgot to put in an intermission point... - SelectSpawnPoint ( vec3_origin, level.intermission_origin, level.intermission_angle, TEAM_SPECTATOR, qfalse ); + if (!ent) { // the map creator forgot to put in an intermission point... + SelectSpawnPoint(vec3_origin, level.intermission_origin, level.intermission_angle, TEAM_SPECTATOR, qfalse); } else { - VectorCopy (ent->s.origin, level.intermission_origin); - VectorCopy (ent->s.angles, level.intermission_angle); + VectorCopy(ent->s.origin, level.intermission_origin); + VectorCopy(ent->s.angles, level.intermission_angle); // if it has a target, look towards it - if ( ent->target ) { - target = G_PickTarget( ent->target ); - if ( target ) { - VectorSubtract( target->s.origin, level.intermission_origin, dir ); - vectoangles( dir, level.intermission_angle ); + if (ent->target) { + target = G_PickTarget(ent->target); + if (target) { + VectorSubtract(target->s.origin, level.intermission_origin, dir); + vectoangles(dir, level.intermission_angle); } } } @@ -1330,28 +1208,24 @@ qboolean DuelLimitHit(void); BeginIntermission ================== */ -void BeginIntermission( void ) { - int i; - gentity_t *client; +void BeginIntermission(void) { + int i; + gentity_t *client; - if ( level.intermissiontime ) { - return; // already active + if (level.intermissiontime) { + return; // already active } // if in tournament mode, change the wins / losses - if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) { - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); - if (level.gametype != GT_POWERDUEL) - { + if (level.gametype != GT_POWERDUEL) { AdjustTournamentScores(); } - if (DuelLimitHit()) - { + if (DuelLimitHit()) { gDuelExit = qtrue; - } - else - { + } else { gDuelExit = qfalse; } } @@ -1359,39 +1233,35 @@ void BeginIntermission( void ) { level.intermissiontime = level.time; // move all clients to the intermission point - for (i=0 ; i< level.maxclients ; i++) { + for (i = 0; i < level.maxclients; i++) { client = g_entities + i; if (!client->inuse) continue; // respawn if dead if (client->health <= 0) { - if (level.gametype != GT_POWERDUEL || - !client->client || - client->client->sess.sessionTeam != TEAM_SPECTATOR) - { //don't respawn spectators in powerduel or it will mess the line order all up + if (level.gametype != GT_POWERDUEL || !client->client || + client->client->sess.sessionTeam != TEAM_SPECTATOR) { // don't respawn spectators in powerduel or it will mess the line order all up ClientRespawn(client); } } - MoveClientToIntermission( client ); + MoveClientToIntermission(client); } // send the current scoring to all clients SendScoreboardMessageToAllClients(); } -qboolean DuelLimitHit(void) -{ +qboolean DuelLimitHit(void) { int i; gclient_t *cl; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( duel_fraglimit.integer && cl->sess.wins >= duel_fraglimit.integer ) - { + if (duel_fraglimit.integer && cl->sess.wins >= duel_fraglimit.integer) { return qtrue; } } @@ -1399,14 +1269,13 @@ qboolean DuelLimitHit(void) return qfalse; } -void DuelResetWinsLosses(void) -{ +void DuelResetWinsLosses(void) { int i; gclient_t *cl; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } @@ -1424,19 +1293,18 @@ or moved to a new level based on the "nextmap" cvar ============= */ -extern void SiegeDoTeamAssign(void); //g_saga.c -extern siegePers_t g_siegePersistant; //g_saga.c -void ExitLevel (void) { - int i; +extern void SiegeDoTeamAssign(void); // g_saga.c +extern siegePers_t g_siegePersistant; // g_saga.c +void ExitLevel(void) { + int i; gclient_t *cl; // if we are running a tournament map, kick the loser to spectator status, // which will automatically grab the next spectator and restart - if ( level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL ) { - if (!DuelLimitHit()) - { - if ( !level.restarted ) { - trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + if (!DuelLimitHit()) { + if (!level.restarted) { + trap->SendConsoleCommand(EXEC_APPEND, "map_restart 0\n"); level.restarted = qtrue; level.changemap = NULL; level.intermissiontime = 0; @@ -1447,32 +1315,24 @@ void ExitLevel (void) { DuelResetWinsLosses(); } - - if (level.gametype == GT_SIEGE && - g_siegeTeamSwitch.integer && - g_siegePersistant.beatingTime) - { //restart same map... - trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); - } - else - { - trap->SendConsoleCommand( EXEC_APPEND, "vstr nextmap\n" ); + if (level.gametype == GT_SIEGE && g_siegeTeamSwitch.integer && g_siegePersistant.beatingTime) { // restart same map... + trap->SendConsoleCommand(EXEC_APPEND, "map_restart 0\n"); + } else { + trap->SendConsoleCommand(EXEC_APPEND, "vstr nextmap\n"); } level.changemap = NULL; level.intermissiontime = 0; - if (level.gametype == GT_SIEGE && - g_siegeTeamSwitch.integer) - { //switch out now + if (level.gametype == GT_SIEGE && g_siegeTeamSwitch.integer) { // switch out now SiegeDoTeamAssign(); } // reset all the scores so we don't enter the intermission again level.teamScores[TEAM_RED] = 0; level.teamScores[TEAM_BLUE] = 0; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } cl->ps.persistant[PERS_SCORE] = 0; @@ -1483,12 +1343,11 @@ void ExitLevel (void) { // change all client states to connecting, so the early players into the // next level will know the others aren't done reconnecting - for (i=0 ; i< sv_maxclients.integer ; i++) { - if ( level.clients[i].pers.connected == CON_CONNECTED ) { + for (i = 0; i < sv_maxclients.integer; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { level.clients[i].pers.connected = CON_CONNECTING; } } - } /* @@ -1498,33 +1357,33 @@ G_LogPrintf Print to the logfile with a time stamp if it is open ================= */ -void QDECL G_LogPrintf( const char *fmt, ... ) { - va_list argptr; - char string[1024] = {0}; - int mins, seconds, msec, l; +void QDECL G_LogPrintf(const char *fmt, ...) { + va_list argptr; + char string[1024] = {0}; + int mins, seconds, msec, l; msec = level.time - level.startTime; seconds = msec / 1000; mins = seconds / 60; seconds %= 60; -// msec %= 1000; + // msec %= 1000; - Com_sprintf( string, sizeof( string ), "%i:%02i ", mins, seconds ); + Com_sprintf(string, sizeof(string), "%i:%02i ", mins, seconds); - l = strlen( string ); + l = strlen(string); - va_start( argptr, fmt ); - Q_vsnprintf( string + l, sizeof( string ) - l, fmt, argptr ); - va_end( argptr ); + va_start(argptr, fmt); + Q_vsnprintf(string + l, sizeof(string) - l, fmt, argptr); + va_end(argptr); - if ( dedicated.integer ) - trap->Print( "%s", string + l ); + if (dedicated.integer) + trap->Print("%s", string + l); - if ( !level.logFile ) + if (!level.logFile) return; - trap->FS_Write( string, strlen( string ), level.logFile ); + trap->FS_Write(string, strlen(string), level.logFile); } /* ================= @@ -1533,28 +1392,28 @@ G_SecurityLogPrintf Print to the security logfile with a time stamp if it is open ================= */ -void QDECL G_SecurityLogPrintf( const char *fmt, ... ) { - va_list argptr; - char string[1024] = {0}; - time_t rawtime; - int timeLen=0; +void QDECL G_SecurityLogPrintf(const char *fmt, ...) { + va_list argptr; + char string[1024] = {0}; + time_t rawtime; + int timeLen = 0; - time( &rawtime ); - localtime( &rawtime ); - strftime( string, sizeof( string ), "[%Y-%m-%d] [%H:%M:%S] ", gmtime( &rawtime ) ); - timeLen = strlen( string ); + time(&rawtime); + localtime(&rawtime); + strftime(string, sizeof(string), "[%Y-%m-%d] [%H:%M:%S] ", gmtime(&rawtime)); + timeLen = strlen(string); - va_start( argptr, fmt ); - Q_vsnprintf( string+timeLen, sizeof( string ) - timeLen, fmt, argptr ); - va_end( argptr ); + va_start(argptr, fmt); + Q_vsnprintf(string + timeLen, sizeof(string) - timeLen, fmt, argptr); + va_end(argptr); - if ( dedicated.integer ) - trap->Print( "%s", string + timeLen ); + if (dedicated.integer) + trap->Print("%s", string + timeLen); - if ( !level.security.log ) + if (!level.security.log) return; - trap->FS_Write( string, strlen( string ), level.security.log ); + trap->FS_Write(string, strlen(string), level.security.log); } /* @@ -1564,56 +1423,57 @@ LogExit Append information about this game to the log file ================ */ -void LogExit( const char *string ) { - int i, numSorted; - gclient_t *cl; -// qboolean won = qtrue; - G_LogPrintf( "Exit: %s\n", string ); +void LogExit(const char *string) { + int i, numSorted; + gclient_t *cl; + // qboolean won = qtrue; + G_LogPrintf("Exit: %s\n", string); level.intermissionQueued = level.time; // this will keep the clients from playing any voice sounds // that will get cut off when the queued intermission starts - trap->SetConfigstring( CS_INTERMISSION, "1" ); + trap->SetConfigstring(CS_INTERMISSION, "1"); // don't send more than 32 scores (FIXME?) numSorted = level.numConnectedClients; - if ( numSorted > 32 ) { + if (numSorted > 32) { numSorted = 32; } - if ( level.gametype >= GT_TEAM ) { - G_LogPrintf( "red:%i blue:%i\n", - level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE] ); + if (level.gametype >= GT_TEAM) { + G_LogPrintf("red:%i blue:%i\n", level.teamScores[TEAM_RED], level.teamScores[TEAM_BLUE]); } - for (i=0 ; i < numSorted ; i++) { - int ping; + for (i = 0; i < numSorted; i++) { + int ping; cl = &level.clients[level.sortedClients[i]]; - if ( cl->sess.sessionTeam == TEAM_SPECTATOR ) { + if (cl->sess.sessionTeam == TEAM_SPECTATOR) { continue; } - if ( cl->pers.connected == CON_CONNECTING ) { + if (cl->pers.connected == CON_CONNECTING) { continue; } ping = cl->ps.ping < 999 ? cl->ps.ping : 999; if (level.gametype >= GT_TEAM) { - G_LogPrintf( "(%s) score: %i ping: %i client: [%s] %i \"%s^7\"\n", TeamName(cl->ps.persistant[PERS_TEAM]), cl->ps.persistant[PERS_SCORE], ping, cl->pers.guid, level.sortedClients[i], cl->pers.netname ); + G_LogPrintf("(%s) score: %i ping: %i client: [%s] %i \"%s^7\"\n", TeamName(cl->ps.persistant[PERS_TEAM]), cl->ps.persistant[PERS_SCORE], ping, + cl->pers.guid, level.sortedClients[i], cl->pers.netname); } else { - G_LogPrintf( "score: %i ping: %i client: [%s] %i \"%s^7\"\n", cl->ps.persistant[PERS_SCORE], ping, cl->pers.guid, level.sortedClients[i], cl->pers.netname ); + G_LogPrintf("score: %i ping: %i client: [%s] %i \"%s^7\"\n", cl->ps.persistant[PERS_SCORE], ping, cl->pers.guid, level.sortedClients[i], + cl->pers.netname); } -// if (g_singlePlayer.integer && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL)) { -// if (g_entities[cl - level.clients].r.svFlags & SVF_BOT && cl->ps.persistant[PERS_RANK] == 0) { -// won = qfalse; -// } -// } + // if (g_singlePlayer.integer && (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL)) { + // if (g_entities[cl - level.clients].r.svFlags & SVF_BOT && cl->ps.persistant[PERS_RANK] == 0) { + // won = qfalse; + // } + // } } - //yeah.. how about not. + // yeah.. how about not. /* if (g_singlePlayer.integer) { if (level.gametype >= GT_CTF) { @@ -1624,7 +1484,7 @@ void LogExit( const char *string ) { */ } -qboolean gDidDuelStuff = qfalse; //gets reset on game reinit +qboolean gDidDuelStuff = qfalse; // gets reset on game reinit /* ================= @@ -1636,28 +1496,28 @@ If one or more players have not acknowledged the continue, the game will wait 10 seconds before going on. ================= */ -void CheckIntermissionExit( void ) { - int ready, notReady; - int i; - gclient_t *cl; - int readyMask; +void CheckIntermissionExit(void) { + int ready, notReady; + int i; + gclient_t *cl; + int readyMask; // see which players are ready ready = 0; notReady = 0; readyMask = 0; - for (i=0 ; i< sv_maxclients.integer ; i++) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( g_entities[i].r.svFlags & SVF_BOT ) { + if (g_entities[i].r.svFlags & SVF_BOT) { continue; } - if ( cl->readyToExit ) { + if (cl->readyToExit) { ready++; - if ( i < 16 ) { + if (i < 16) { readyMask |= 1 << i; } } else { @@ -1665,161 +1525,111 @@ void CheckIntermissionExit( void ) { } } - if ( (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && !gDidDuelStuff && - (level.time > level.intermissiontime + 2000) ) - { + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && !gDidDuelStuff && (level.time > level.intermissiontime + 2000)) { gDidDuelStuff = qtrue; - if ( g_austrian.integer && level.gametype != GT_POWERDUEL ) - { + if (g_austrian.integer && level.gametype != GT_POWERDUEL) { G_LogPrintf("Duel Results:\n"); - //G_LogPrintf("Duel Time: %d\n", level.time ); - G_LogPrintf("winner: %s, score: %d, wins/losses: %d/%d\n", - level.clients[level.sortedClients[0]].pers.netname, - level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE], - level.clients[level.sortedClients[0]].sess.wins, - level.clients[level.sortedClients[0]].sess.losses ); - G_LogPrintf("loser: %s, score: %d, wins/losses: %d/%d\n", - level.clients[level.sortedClients[1]].pers.netname, - level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE], - level.clients[level.sortedClients[1]].sess.wins, - level.clients[level.sortedClients[1]].sess.losses ); + // G_LogPrintf("Duel Time: %d\n", level.time ); + G_LogPrintf("winner: %s, score: %d, wins/losses: %d/%d\n", level.clients[level.sortedClients[0]].pers.netname, + level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE], level.clients[level.sortedClients[0]].sess.wins, + level.clients[level.sortedClients[0]].sess.losses); + G_LogPrintf("loser: %s, score: %d, wins/losses: %d/%d\n", level.clients[level.sortedClients[1]].pers.netname, + level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE], level.clients[level.sortedClients[1]].sess.wins, + level.clients[level.sortedClients[1]].sess.losses); } // if we are running a tournament map, kick the loser to spectator status, // which will automatically grab the next spectator and restart - if (!DuelLimitHit()) - { - if (level.gametype == GT_POWERDUEL) - { + if (!DuelLimitHit()) { + if (level.gametype == GT_POWERDUEL) { RemovePowerDuelLosers(); AddPowerDuelPlayers(); - } - else - { - if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == - level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && + } else { + if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && level.clients[level.sortedClients[0]].pers.connected == CON_CONNECTED && - level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) - { + level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) { RemoveDuelDrawLoser(); - } - else - { + } else { RemoveTournamentLoser(); } AddTournamentPlayer(); } - if ( g_austrian.integer ) - { - if (level.gametype == GT_POWERDUEL) - { - G_LogPrintf("Power Duel Initiated: %s %d/%d vs %s %d/%d and %s %d/%d, kill limit: %d\n", - level.clients[level.sortedClients[0]].pers.netname, - level.clients[level.sortedClients[0]].sess.wins, - level.clients[level.sortedClients[0]].sess.losses, - level.clients[level.sortedClients[1]].pers.netname, - level.clients[level.sortedClients[1]].sess.wins, - level.clients[level.sortedClients[1]].sess.losses, - level.clients[level.sortedClients[2]].pers.netname, - level.clients[level.sortedClients[2]].sess.wins, - level.clients[level.sortedClients[2]].sess.losses, - fraglimit.integer ); - } - else - { - G_LogPrintf("Duel Initiated: %s %d/%d vs %s %d/%d, kill limit: %d\n", - level.clients[level.sortedClients[0]].pers.netname, - level.clients[level.sortedClients[0]].sess.wins, - level.clients[level.sortedClients[0]].sess.losses, - level.clients[level.sortedClients[1]].pers.netname, - level.clients[level.sortedClients[1]].sess.wins, - level.clients[level.sortedClients[1]].sess.losses, - fraglimit.integer ); + if (g_austrian.integer) { + if (level.gametype == GT_POWERDUEL) { + G_LogPrintf("Power Duel Initiated: %s %d/%d vs %s %d/%d and %s %d/%d, kill limit: %d\n", level.clients[level.sortedClients[0]].pers.netname, + level.clients[level.sortedClients[0]].sess.wins, level.clients[level.sortedClients[0]].sess.losses, + level.clients[level.sortedClients[1]].pers.netname, level.clients[level.sortedClients[1]].sess.wins, + level.clients[level.sortedClients[1]].sess.losses, level.clients[level.sortedClients[2]].pers.netname, + level.clients[level.sortedClients[2]].sess.wins, level.clients[level.sortedClients[2]].sess.losses, fraglimit.integer); + } else { + G_LogPrintf("Duel Initiated: %s %d/%d vs %s %d/%d, kill limit: %d\n", level.clients[level.sortedClients[0]].pers.netname, + level.clients[level.sortedClients[0]].sess.wins, level.clients[level.sortedClients[0]].sess.losses, + level.clients[level.sortedClients[1]].pers.netname, level.clients[level.sortedClients[1]].sess.wins, + level.clients[level.sortedClients[1]].sess.losses, fraglimit.integer); } } - if (level.gametype == GT_POWERDUEL) - { - if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2] ) ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + if (level.gametype == GT_POWERDUEL) { + if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2])); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); } - } - else - { - if (level.numPlayingClients >= 2) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1] ) ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + } else { + if (level.numPlayingClients >= 2) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1])); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); } } return; } - if ( g_austrian.integer && level.gametype != GT_POWERDUEL ) - { - G_LogPrintf("Duel Tournament Winner: %s wins/losses: %d/%d\n", - level.clients[level.sortedClients[0]].pers.netname, - level.clients[level.sortedClients[0]].sess.wins, - level.clients[level.sortedClients[0]].sess.losses ); + if (g_austrian.integer && level.gametype != GT_POWERDUEL) { + G_LogPrintf("Duel Tournament Winner: %s wins/losses: %d/%d\n", level.clients[level.sortedClients[0]].pers.netname, + level.clients[level.sortedClients[0]].sess.wins, level.clients[level.sortedClients[0]].sess.losses); } - if (level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_POWERDUEL) { RemovePowerDuelLosers(); AddPowerDuelPlayers(); - if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2] ) ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2])); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); } - } - else - { - //this means we hit the duel limit so reset the wins/losses - //but still push the loser to the back of the line, and retain the order for - //the map change - if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == - level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && + } else { + // this means we hit the duel limit so reset the wins/losses + // but still push the loser to the back of the line, and retain the order for + // the map change + if (level.clients[level.sortedClients[0]].ps.persistant[PERS_SCORE] == level.clients[level.sortedClients[1]].ps.persistant[PERS_SCORE] && level.clients[level.sortedClients[0]].pers.connected == CON_CONNECTED && - level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) - { + level.clients[level.sortedClients[1]].pers.connected == CON_CONNECTED) { RemoveDuelDrawLoser(); - } - else - { + } else { RemoveTournamentLoser(); } AddTournamentPlayer(); - if (level.numPlayingClients >= 2) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1] ) ); - trap->SetConfigstring ( CS_CLIENT_DUELWINNER, "-1" ); + if (level.numPlayingClients >= 2) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1])); + trap->SetConfigstring(CS_CLIENT_DUELWINNER, "-1"); } } } - if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && !gDuelExit) - { //in duel, we have different behaviour for between-round intermissions - if ( level.time > level.intermissiontime + 4000 ) - { //automatically go to next after 4 seconds + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && !gDuelExit) { // in duel, we have different behaviour for between-round intermissions + if (level.time > level.intermissiontime + 4000) { // automatically go to next after 4 seconds ExitLevel(); return; } - for (i=0 ; i< sv_maxclients.integer ; i++) - { //being in a "ready" state is not necessary here, so clear it for everyone - //yes, I also thinking holding this in a ps value uniquely for each player - //is bad and wrong, but it wasn't my idea. + for (i = 0; i < sv_maxclients.integer; i++) { // being in a "ready" state is not necessary here, so clear it for everyone + // yes, I also thinking holding this in a ps value uniquely for each player + // is bad and wrong, but it wasn't my idea. cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) - { + if (cl->pers.connected != CON_CONNECTED) { continue; } cl->ps.stats[STAT_CLIENTS_READY] = 0; @@ -1829,46 +1639,45 @@ void CheckIntermissionExit( void ) { // copy the readyMask to each player's stats so // it can be displayed on the scoreboard - for (i=0 ; i< sv_maxclients.integer ; i++) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } cl->ps.stats[STAT_CLIENTS_READY] = readyMask; } // never exit in less than five seconds - if ( level.time < level.intermissiontime + 5000 ) { + if (level.time < level.intermissiontime + 5000) { return; } - if (d_noIntermissionWait.integer) - { //don't care who wants to go, just go. + if (d_noIntermissionWait.integer) { // don't care who wants to go, just go. ExitLevel(); return; } // if nobody wants to go, clear timer - if ( !ready ) { + if (!ready) { level.readyToExit = qfalse; return; } // if everyone wants to go, go now - if ( !notReady ) { + if (!notReady) { ExitLevel(); return; } // the first person to ready starts the ten second timeout - if ( !level.readyToExit ) { + if (!level.readyToExit) { level.readyToExit = qtrue; level.exitTime = level.time; } // if we have waited ten seconds since at least one player // wanted to exit, go ahead - if ( level.time < level.exitTime + 10000 ) { + if (level.time < level.exitTime + 10000) { return; } @@ -1880,14 +1689,14 @@ void CheckIntermissionExit( void ) { ScoreIsTied ============= */ -qboolean ScoreIsTied( void ) { - int a, b; +qboolean ScoreIsTied(void) { + int a, b; - if ( level.numPlayingClients < 2 ) { + if (level.numPlayingClients < 2) { return qfalse; } - if ( level.gametype >= GT_TEAM ) { + if (level.gametype >= GT_TEAM) { return level.teamScores[TEAM_RED] == level.teamScores[TEAM_BLUE]; } @@ -1907,56 +1716,48 @@ can see the last frag. ================= */ qboolean g_endPDuel = qfalse; -void CheckExitRules( void ) { - int i; - gclient_t *cl; +void CheckExitRules(void) { + int i; + gclient_t *cl; char *sKillLimit; qboolean printLimit = qtrue; // if at the intermission, wait for all non-bots to // signal ready, then go to next level - if ( level.intermissiontime ) { - CheckIntermissionExit (); + if (level.intermissiontime) { + CheckIntermissionExit(); return; } - if (gDoSlowMoDuel) - { //don't go to intermission while in slow motion + if (gDoSlowMoDuel) { // don't go to intermission while in slow motion return; } - if (gEscaping) - { + if (gEscaping) { int numLiveClients = 0; - for ( i=0; i < MAX_CLIENTS; i++ ) - { - if (g_entities[i].inuse && g_entities[i].client && g_entities[i].health > 0) - { - if (g_entities[i].client->sess.sessionTeam != TEAM_SPECTATOR && - !(g_entities[i].client->ps.pm_flags & PMF_FOLLOW)) - { + for (i = 0; i < MAX_CLIENTS; i++) { + if (g_entities[i].inuse && g_entities[i].client && g_entities[i].health > 0) { + if (g_entities[i].client->sess.sessionTeam != TEAM_SPECTATOR && !(g_entities[i].client->ps.pm_flags & PMF_FOLLOW)) { numLiveClients++; } } } - if (gEscapeTime < level.time) - { + if (gEscapeTime < level.time) { gEscaping = qfalse; - LogExit( "Escape time ended." ); + LogExit("Escape time ended."); return; } - if (!numLiveClients) - { + if (!numLiveClients) { gEscaping = qfalse; - LogExit( "Everyone failed to escape." ); + LogExit("Everyone failed to escape."); return; } } - if ( level.intermissionQueued ) { - //int time = (g_singlePlayer.integer) ? SP_INTERMISSION_DELAY_TIME : INTERMISSION_DELAY_TIME; + if (level.intermissionQueued) { + // int time = (g_singlePlayer.integer) ? SP_INTERMISSION_DELAY_TIME : INTERMISSION_DELAY_TIME; int time = INTERMISSION_DELAY_TIME; - if ( level.time - level.intermissionQueued >= time ) { + if (level.time - level.intermissionQueued >= time) { level.intermissionQueued = 0; BeginIntermission(); } @@ -1982,45 +1783,38 @@ void CheckExitRules( void ) { */ // check for sudden death - if (level.gametype != GT_SIEGE) - { - if ( ScoreIsTied() ) { + if (level.gametype != GT_SIEGE) { + if (ScoreIsTied()) { // always wait for sudden death - if ((level.gametype != GT_DUEL) || !timelimit.value) - { - if (level.gametype != GT_POWERDUEL) - { + if ((level.gametype != GT_DUEL) || !timelimit.value) { + if (level.gametype != GT_POWERDUEL) { return; } } } } - if (level.gametype != GT_SIEGE) - { - if ( timelimit.value > 0.0f && !level.warmupTime ) { - if ( level.time - level.startTime >= timelimit.value*60000 ) { -// trap->SendServerCommand( -1, "print \"Timelimit hit.\n\""); - trap->SendServerCommand( -1, va("print \"%s.\n\"",G_GetStringEdString("MP_SVGAME", "TIMELIMIT_HIT"))); - if (d_powerDuelPrint.integer) - { + if (level.gametype != GT_SIEGE) { + if (timelimit.value > 0.0f && !level.warmupTime) { + if (level.time - level.startTime >= timelimit.value * 60000) { + // trap->SendServerCommand( -1, "print \"Timelimit hit.\n\""); + trap->SendServerCommand(-1, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "TIMELIMIT_HIT"))); + if (d_powerDuelPrint.integer) { Com_Printf("POWERDUEL WIN CONDITION: Timelimit hit (1)\n"); } - LogExit( "Timelimit hit." ); + LogExit("Timelimit hit."); return; } } } - if (level.gametype == GT_POWERDUEL && level.numPlayingClients >= 3) - { - if (g_endPDuel) - { + if (level.gametype == GT_POWERDUEL && level.numPlayingClients >= 3) { + if (g_endPDuel) { g_endPDuel = qfalse; LogExit("Powerduel ended."); } - //yeah, this stuff was completely insane. + // yeah, this stuff was completely insane. /* int duelists[3]; duelists[0] = level.sortedClients[0]; @@ -2126,110 +1920,91 @@ void CheckExitRules( void ) { return; } - if ( level.numPlayingClients < 2 ) { + if (level.numPlayingClients < 2) { return; } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { - if (fraglimit.integer > 1) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { + if (fraglimit.integer > 1) { sKillLimit = "Kill limit hit."; - } - else - { + } else { sKillLimit = ""; printLimit = qfalse; } - } - else - { + } else { sKillLimit = "Kill limit hit."; } - if ( level.gametype < GT_SIEGE && fraglimit.integer ) { - if ( level.teamScores[TEAM_RED] >= fraglimit.integer ) { - trap->SendServerCommand( -1, va("print \"Red %s\n\"", G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT")) ); - if (d_powerDuelPrint.integer) - { + if (level.gametype < GT_SIEGE && fraglimit.integer) { + if (level.teamScores[TEAM_RED] >= fraglimit.integer) { + trap->SendServerCommand(-1, va("print \"Red %s\n\"", G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT"))); + if (d_powerDuelPrint.integer) { Com_Printf("POWERDUEL WIN CONDITION: Kill limit (1)\n"); } - LogExit( sKillLimit ); + LogExit(sKillLimit); return; } - if ( level.teamScores[TEAM_BLUE] >= fraglimit.integer ) { - trap->SendServerCommand( -1, va("print \"Blue %s\n\"", G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT")) ); - if (d_powerDuelPrint.integer) - { + if (level.teamScores[TEAM_BLUE] >= fraglimit.integer) { + trap->SendServerCommand(-1, va("print \"Blue %s\n\"", G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT"))); + if (d_powerDuelPrint.integer) { Com_Printf("POWERDUEL WIN CONDITION: Kill limit (2)\n"); } - LogExit( sKillLimit ); + LogExit(sKillLimit); return; } - for ( i=0 ; i< sv_maxclients.integer ; i++ ) { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( cl->sess.sessionTeam != TEAM_FREE ) { + if (cl->sess.sessionTeam != TEAM_FREE) { continue; } - if ( (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && duel_fraglimit.integer && cl->sess.wins >= duel_fraglimit.integer ) - { - if (d_powerDuelPrint.integer) - { + if ((level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) && duel_fraglimit.integer && cl->sess.wins >= duel_fraglimit.integer) { + if (d_powerDuelPrint.integer) { Com_Printf("POWERDUEL WIN CONDITION: Duel limit hit (1)\n"); } - LogExit( "Duel limit hit." ); + LogExit("Duel limit hit."); gDuelExit = qtrue; - trap->SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " hit the win limit.\n\"", - cl->pers.netname ) ); + trap->SendServerCommand(-1, va("print \"%s" S_COLOR_WHITE " hit the win limit.\n\"", cl->pers.netname)); return; } - if ( cl->ps.persistant[PERS_SCORE] >= fraglimit.integer ) { - if (d_powerDuelPrint.integer) - { + if (cl->ps.persistant[PERS_SCORE] >= fraglimit.integer) { + if (d_powerDuelPrint.integer) { Com_Printf("POWERDUEL WIN CONDITION: Kill limit (3)\n"); } - LogExit( sKillLimit ); + LogExit(sKillLimit); gDuelExit = qfalse; - if (printLimit) - { - trap->SendServerCommand( -1, va("print \"%s" S_COLOR_WHITE " %s.\n\"", - cl->pers.netname, - G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT") - ) - ); + if (printLimit) { + trap->SendServerCommand( + -1, va("print \"%s" S_COLOR_WHITE " %s.\n\"", cl->pers.netname, G_GetStringEdString("MP_SVGAME", "HIT_THE_KILL_LIMIT"))); } return; } } } - if ( level.gametype >= GT_CTF && capturelimit.integer ) { + if (level.gametype >= GT_CTF && capturelimit.integer) { - if ( level.teamScores[TEAM_RED] >= capturelimit.integer ) - { - trap->SendServerCommand( -1, va("print \"%s \"", G_GetStringEdString("MP_SVGAME", "PRINTREDTEAM"))); - trap->SendServerCommand( -1, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "HIT_CAPTURE_LIMIT"))); - LogExit( "Capturelimit hit." ); + if (level.teamScores[TEAM_RED] >= capturelimit.integer) { + trap->SendServerCommand(-1, va("print \"%s \"", G_GetStringEdString("MP_SVGAME", "PRINTREDTEAM"))); + trap->SendServerCommand(-1, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "HIT_CAPTURE_LIMIT"))); + LogExit("Capturelimit hit."); return; } - if ( level.teamScores[TEAM_BLUE] >= capturelimit.integer ) { - trap->SendServerCommand( -1, va("print \"%s \"", G_GetStringEdString("MP_SVGAME", "PRINTBLUETEAM"))); - trap->SendServerCommand( -1, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "HIT_CAPTURE_LIMIT"))); - LogExit( "Capturelimit hit." ); + if (level.teamScores[TEAM_BLUE] >= capturelimit.integer) { + trap->SendServerCommand(-1, va("print \"%s \"", G_GetStringEdString("MP_SVGAME", "PRINTBLUETEAM"))); + trap->SendServerCommand(-1, va("print \"%s.\n\"", G_GetStringEdString("MP_SVGAME", "HIT_CAPTURE_LIMIT"))); + LogExit("Capturelimit hit."); return; } } } - - /* ======================================================================== @@ -2238,20 +2013,16 @@ FUNCTIONS CALLED EVERY FRAME ======================================================================== */ -void G_RemoveDuelist(int team) -{ +void G_RemoveDuelist(int team) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent->inuse && ent->client && ent->client->sess.sessionTeam != TEAM_SPECTATOR && - ent->client->sess.duelTeam == team) - { + if (ent->inuse && ent->client && ent->client->sess.sessionTeam != TEAM_SPECTATOR && ent->client->sess.duelTeam == team) { SetTeam(ent, "s"); } - i++; + i++; } } @@ -2263,56 +2034,46 @@ Once a frame, check for changes in tournament player state ============= */ int g_duelPrintTimer = 0; -void CheckTournament( void ) { +void CheckTournament(void) { // check because we run 3 game frames before calling Connect and/or ClientBegin // for clients on a map_restart -// if ( level.numPlayingClients == 0 && (level.gametype != GT_POWERDUEL) ) { -// return; -// } + // if ( level.numPlayingClients == 0 && (level.gametype != GT_POWERDUEL) ) { + // return; + // } - if (level.gametype == GT_POWERDUEL) - { - if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2] ) ); + if (level.gametype == GT_POWERDUEL) { + if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2])); } - } - else - { - if (level.numPlayingClients >= 2) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1] ) ); + } else { + if (level.numPlayingClients >= 2) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1])); } } - if ( level.gametype == GT_DUEL ) - { + if (level.gametype == GT_DUEL) { // pull in a spectator if needed - if ( level.numPlayingClients < 2 && !level.intermissiontime && !level.intermissionQueued ) { + if (level.numPlayingClients < 2 && !level.intermissiontime && !level.intermissionQueued) { AddTournamentPlayer(); - if (level.numPlayingClients >= 2) - { - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1] ) ); + if (level.numPlayingClients >= 2) { + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i", level.sortedClients[0], level.sortedClients[1])); } } - if (level.numPlayingClients >= 2) - { -// nmckenzie: DUEL_HEALTH - if ( g_showDuelHealths.integer >= 1 ) - { + if (level.numPlayingClients >= 2) { + // nmckenzie: DUEL_HEALTH + if (g_showDuelHealths.integer >= 1) { playerState_t *ps1, *ps2; ps1 = &level.clients[level.sortedClients[0]].ps; ps2 = &level.clients[level.sortedClients[1]].ps; - trap->SetConfigstring ( CS_CLIENT_DUELHEALTHS, va("%i|%i|!", - ps1->stats[STAT_HEALTH], ps2->stats[STAT_HEALTH])); + trap->SetConfigstring(CS_CLIENT_DUELHEALTHS, va("%i|%i|!", ps1->stats[STAT_HEALTH], ps2->stats[STAT_HEALTH])); } } - //rww - It seems we have decided there will be no warmup in duel. - //if (!g_warmup.integer) - { //don't care about any of this stuff then, just add people and leave me alone + // rww - It seems we have decided there will be no warmup in duel. + // if (!g_warmup.integer) + { // don't care about any of this stuff then, just add people and leave me alone level.warmupTime = 0; return; } @@ -2361,148 +2122,114 @@ void CheckTournament( void ) { return; } #endif - } - else if (level.gametype == GT_POWERDUEL) - { - if (level.numPlayingClients < 2) - { //hmm, ok, pull more in. + } else if (level.gametype == GT_POWERDUEL) { + if (level.numPlayingClients < 2) { // hmm, ok, pull more in. g_dontFrickinCheck = qfalse; } - if (level.numPlayingClients > 3) - { //umm..yes..lets take care of that then. + if (level.numPlayingClients > 3) { // umm..yes..lets take care of that then. int lone = 0, dbl = 0; G_PowerDuelCount(&lone, &dbl, qfalse); - if (lone > 1) - { + if (lone > 1) { G_RemoveDuelist(DUELTEAM_LONE); - } - else if (dbl > 2) - { + } else if (dbl > 2) { G_RemoveDuelist(DUELTEAM_DOUBLE); } - } - else if (level.numPlayingClients < 3) - { //hmm, someone disconnected or something and we need em + } else if (level.numPlayingClients < 3) { // hmm, someone disconnected or something and we need em int lone = 0, dbl = 0; G_PowerDuelCount(&lone, &dbl, qfalse); - if (lone < 1) - { + if (lone < 1) { g_dontFrickinCheck = qfalse; - } - else if (dbl < 1) - { + } else if (dbl < 1) { g_dontFrickinCheck = qfalse; } } // pull in a spectator if needed - if (level.numPlayingClients < 3 && !g_dontFrickinCheck) - { + if (level.numPlayingClients < 3 && !g_dontFrickinCheck) { AddPowerDuelPlayers(); - if (level.numPlayingClients >= 3 && - G_CanResetDuelists()) - { + if (level.numPlayingClients >= 3 && G_CanResetDuelists()) { gentity_t *te = G_TempEntity(vec3_origin, EV_GLOBAL_DUEL); te->r.svFlags |= SVF_BROADCAST; - //this is really pretty nasty, but.. + // this is really pretty nasty, but.. te->s.otherEntityNum = level.sortedClients[0]; te->s.otherEntityNum2 = level.sortedClients[1]; te->s.groundEntityNum = level.sortedClients[2]; - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2] ) ); + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2])); G_ResetDuelists(); g_dontFrickinCheck = qtrue; - } - else if (level.numPlayingClients > 0 || - level.numConnectedClients > 0) - { - if (g_duelPrintTimer < level.time) - { //print once every 10 seconds + } else if (level.numPlayingClients > 0 || level.numConnectedClients > 0) { + if (g_duelPrintTimer < level.time) { // print once every 10 seconds int lone = 0, dbl = 0; G_PowerDuelCount(&lone, &dbl, qtrue); - if (lone < 1) - { - trap->SendServerCommand( -1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "DUELMORESINGLE")) ); - } - else - { - trap->SendServerCommand( -1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "DUELMOREPAIRED")) ); + if (lone < 1) { + trap->SendServerCommand(-1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "DUELMORESINGLE"))); + } else { + trap->SendServerCommand(-1, va("cp \"%s\n\"", G_GetStringEdString("MP_SVGAME", "DUELMOREPAIRED"))); } g_duelPrintTimer = level.time + 10000; } } - if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) - { //pulled in a needed person - if (G_CanResetDuelists()) - { + if (level.numPlayingClients >= 3 && level.numNonSpectatorClients >= 3) { // pulled in a needed person + if (G_CanResetDuelists()) { gentity_t *te = G_TempEntity(vec3_origin, EV_GLOBAL_DUEL); te->r.svFlags |= SVF_BROADCAST; - //this is really pretty nasty, but.. + // this is really pretty nasty, but.. te->s.otherEntityNum = level.sortedClients[0]; te->s.otherEntityNum2 = level.sortedClients[1]; te->s.groundEntityNum = level.sortedClients[2]; - trap->SetConfigstring ( CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2] ) ); + trap->SetConfigstring(CS_CLIENT_DUELISTS, va("%i|%i|%i", level.sortedClients[0], level.sortedClients[1], level.sortedClients[2])); - if ( g_austrian.integer ) - { - G_LogPrintf("Duel Initiated: %s %d/%d vs %s %d/%d and %s %d/%d, kill limit: %d\n", - level.clients[level.sortedClients[0]].pers.netname, - level.clients[level.sortedClients[0]].sess.wins, - level.clients[level.sortedClients[0]].sess.losses, - level.clients[level.sortedClients[1]].pers.netname, - level.clients[level.sortedClients[1]].sess.wins, - level.clients[level.sortedClients[1]].sess.losses, - level.clients[level.sortedClients[2]].pers.netname, - level.clients[level.sortedClients[2]].sess.wins, - level.clients[level.sortedClients[2]].sess.losses, - fraglimit.integer ); + if (g_austrian.integer) { + G_LogPrintf("Duel Initiated: %s %d/%d vs %s %d/%d and %s %d/%d, kill limit: %d\n", level.clients[level.sortedClients[0]].pers.netname, + level.clients[level.sortedClients[0]].sess.wins, level.clients[level.sortedClients[0]].sess.losses, + level.clients[level.sortedClients[1]].pers.netname, level.clients[level.sortedClients[1]].sess.wins, + level.clients[level.sortedClients[1]].sess.losses, level.clients[level.sortedClients[2]].pers.netname, + level.clients[level.sortedClients[2]].sess.wins, level.clients[level.sortedClients[2]].sess.losses, fraglimit.integer); } - //trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); - //FIXME: This seems to cause problems. But we'd like to reset things whenever a new opponent is set. + // trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); + // FIXME: This seems to cause problems. But we'd like to reset things whenever a new opponent is set. } } - } - else - { //if you have proper num of players then don't try to add again + } else { // if you have proper num of players then don't try to add again g_dontFrickinCheck = qtrue; } level.warmupTime = 0; return; - } - else if ( level.warmupTime != 0 ) { - int counts[TEAM_NUM_TEAMS]; - qboolean notEnough = qfalse; + } else if (level.warmupTime != 0) { + int counts[TEAM_NUM_TEAMS]; + qboolean notEnough = qfalse; - if ( level.gametype > GT_TEAM ) { - counts[TEAM_BLUE] = TeamCount( -1, TEAM_BLUE ); - counts[TEAM_RED] = TeamCount( -1, TEAM_RED ); + if (level.gametype > GT_TEAM) { + counts[TEAM_BLUE] = TeamCount(-1, TEAM_BLUE); + counts[TEAM_RED] = TeamCount(-1, TEAM_RED); if (counts[TEAM_RED] < 1 || counts[TEAM_BLUE] < 1) { notEnough = qtrue; } - } else if ( level.numPlayingClients < 2 ) { + } else if (level.numPlayingClients < 2) { notEnough = qtrue; } - if ( notEnough ) { - if ( level.warmupTime != -1 ) { + if (notEnough) { + if (level.warmupTime != -1) { level.warmupTime = -1; - trap->SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) ); - G_LogPrintf( "Warmup:\n" ); + trap->SetConfigstring(CS_WARMUP, va("%i", level.warmupTime)); + G_LogPrintf("Warmup:\n"); } return; // still waiting for team members } - if ( level.warmupTime == 0 ) { + if (level.warmupTime == 0) { return; } @@ -2515,46 +2242,42 @@ void CheckTournament( void ) { */ // if all players have arrived, start the countdown - if ( level.warmupTime < 0 ) { + if (level.warmupTime < 0) { // fudge by -1 to account for extra delays - if ( g_warmup.integer > 1 ) { - level.warmupTime = level.time + ( g_warmup.integer - 1 ) * 1000; + if (g_warmup.integer > 1) { + level.warmupTime = level.time + (g_warmup.integer - 1) * 1000; } else { level.warmupTime = 0; } - trap->SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) ); + trap->SetConfigstring(CS_WARMUP, va("%i", level.warmupTime)); return; } // if the warmup time has counted down, restart - if ( level.time > level.warmupTime ) { + if (level.time > level.warmupTime) { level.warmupTime += 10000; - trap->Cvar_Set( "g_restarted", "1" ); - trap->Cvar_Update( &g_restarted ); - trap->SendConsoleCommand( EXEC_APPEND, "map_restart 0\n" ); + trap->Cvar_Set("g_restarted", "1"); + trap->Cvar_Update(&g_restarted); + trap->SendConsoleCommand(EXEC_APPEND, "map_restart 0\n"); level.restarted = qtrue; return; } } } -void G_KickAllBots(void) -{ +void G_KickAllBots(void) { int i; - gclient_t *cl; + gclient_t *cl; - for ( i=0 ; i< sv_maxclients.integer ; i++ ) - { + for (i = 0; i < sv_maxclients.integer; i++) { cl = level.clients + i; - if ( cl->pers.connected != CON_CONNECTED ) - { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !(g_entities[i].r.svFlags & SVF_BOT) ) - { + if (!(g_entities[i].r.svFlags & SVF_BOT)) { continue; } - trap->SendConsoleCommand( EXEC_INSERT, va("clientkick %d\n", i) ); + trap->SendConsoleCommand(EXEC_INSERT, va("clientkick %d\n", i)); } } @@ -2563,56 +2286,43 @@ void G_KickAllBots(void) CheckVote ================== */ -void CheckVote( void ) { - if ( level.voteExecuteTime && level.voteExecuteTime < level.time ) { +void CheckVote(void) { + if (level.voteExecuteTime && level.voteExecuteTime < level.time) { level.voteExecuteTime = 0; - trap->SendConsoleCommand( EXEC_APPEND, va( "%s\n", level.voteString ) ); + trap->SendConsoleCommand(EXEC_APPEND, va("%s\n", level.voteString)); - if (level.votingGametype) - { - if (level.gametype != level.votingGametypeTo) - { //If we're voting to a different game type, be sure to refresh all the map stuff + if (level.votingGametype) { + if (level.gametype != level.votingGametypeTo) { // If we're voting to a different game type, be sure to refresh all the map stuff const char *nextMap = G_RefreshNextMap(level.votingGametypeTo, qtrue); - if (level.votingGametypeTo == GT_SIEGE) - { //ok, kick all the bots, cause the aren't supported! - G_KickAllBots(); - //just in case, set this to 0 too... I guess...maybe? - //trap->Cvar_Set("bot_minplayers", "0"); + if (level.votingGametypeTo == GT_SIEGE) { // ok, kick all the bots, cause the aren't supported! + G_KickAllBots(); + // just in case, set this to 0 too... I guess...maybe? + // trap->Cvar_Set("bot_minplayers", "0"); } - if (nextMap && nextMap[0]) - { - trap->SendConsoleCommand( EXEC_APPEND, va("map %s\n", nextMap ) ); + if (nextMap && nextMap[0]) { + trap->SendConsoleCommand(EXEC_APPEND, va("map %s\n", nextMap)); } - } - else - { //otherwise, just leave the map until a restart + } else { // otherwise, just leave the map until a restart G_RefreshNextMap(level.votingGametypeTo, qfalse); } - if (g_fraglimitVoteCorrection.integer) - { //This means to auto-correct fraglimit when voting to and from duel. + if (g_fraglimitVoteCorrection.integer) { // This means to auto-correct fraglimit when voting to and from duel. const int currentGT = level.gametype; const int currentFL = fraglimit.integer; const int currentTL = timelimit.integer; - if ((level.votingGametypeTo == GT_DUEL || level.votingGametypeTo == GT_POWERDUEL) && currentGT != GT_DUEL && currentGT != GT_POWERDUEL) - { - if (currentFL > 3 || !currentFL) - { //if voting to duel, and fraglimit is more than 3 (or unlimited), then set it down to 3 + if ((level.votingGametypeTo == GT_DUEL || level.votingGametypeTo == GT_POWERDUEL) && currentGT != GT_DUEL && currentGT != GT_POWERDUEL) { + if (currentFL > 3 || !currentFL) { // if voting to duel, and fraglimit is more than 3 (or unlimited), then set it down to 3 trap->SendConsoleCommand(EXEC_APPEND, "fraglimit 3\n"); } - if (currentTL) - { //if voting to duel, and timelimit is set, make it unlimited + if (currentTL) { // if voting to duel, and timelimit is set, make it unlimited trap->SendConsoleCommand(EXEC_APPEND, "timelimit 0\n"); } - } - else if ((level.votingGametypeTo != GT_DUEL && level.votingGametypeTo != GT_POWERDUEL) && - (currentGT == GT_DUEL || currentGT == GT_POWERDUEL)) - { - if (currentFL && currentFL < 20) - { //if voting from duel, an fraglimit is less than 20, then set it up to 20 + } else if ((level.votingGametypeTo != GT_DUEL && level.votingGametypeTo != GT_POWERDUEL) && + (currentGT == GT_DUEL || currentGT == GT_POWERDUEL)) { + if (currentFL && currentFL < 20) { // if voting from duel, an fraglimit is less than 20, then set it up to 20 trap->SendConsoleCommand(EXEC_APPEND, "fraglimit 20\n"); } } @@ -2622,28 +2332,27 @@ void CheckVote( void ) { level.votingGametypeTo = 0; } } - if ( !level.voteTime ) { + if (!level.voteTime) { return; } - if ( level.time-level.voteTime >= VOTE_TIME || level.voteYes + level.voteNo == 0 ) { - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEFAILED"), level.voteStringClean) ); - } - else { - if ( level.voteYes > level.numVotingClients/2 ) { + if (level.time - level.voteTime >= VOTE_TIME || level.voteYes + level.voteNo == 0) { + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEFAILED"), level.voteStringClean)); + } else { + if (level.voteYes > level.numVotingClients / 2) { // execute the command, then remove the vote - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEPASSED"), level.voteStringClean) ); + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEPASSED"), level.voteStringClean)); level.voteExecuteTime = level.time + level.voteExecuteDelay; } // same behavior as a timeout - else if ( level.voteNo >= (level.numVotingClients+1)/2 ) - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEFAILED"), level.voteStringClean) ); + else if (level.voteNo >= (level.numVotingClients + 1) / 2) + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "VOTEFAILED"), level.voteStringClean)); else // still waiting for a majority return; } level.voteTime = 0; - trap->SetConfigstring( CS_VOTE_TIME, "" ); + trap->SetConfigstring(CS_VOTE_TIME, ""); } /* @@ -2654,10 +2363,10 @@ PrintTeam void PrintTeam(int team, char *message) { int i; - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { if (level.clients[i].sess.sessionTeam != team) continue; - trap->SendServerCommand( i, message ); + trap->SendServerCommand(i, message); } } @@ -2669,15 +2378,15 @@ SetLeader void SetLeader(int team, int client) { int i; - if ( level.clients[client].pers.connected == CON_DISCONNECTED ) { - PrintTeam(team, va("print \"%s is not connected\n\"", level.clients[client].pers.netname) ); + if (level.clients[client].pers.connected == CON_DISCONNECTED) { + PrintTeam(team, va("print \"%s is not connected\n\"", level.clients[client].pers.netname)); return; } if (level.clients[client].sess.sessionTeam != team) { - PrintTeam(team, va("print \"%s is not on the team anymore\n\"", level.clients[client].pers.netname) ); + PrintTeam(team, va("print \"%s is not on the team anymore\n\"", level.clients[client].pers.netname)); return; } - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { if (level.clients[i].sess.sessionTeam != team) continue; if (level.clients[i].sess.teamLeader) { @@ -2686,8 +2395,8 @@ void SetLeader(int team, int client) { } } level.clients[client].sess.teamLeader = qtrue; - ClientUserinfoChanged( client ); - PrintTeam(team, va("print \"%s %s\n\"", level.clients[client].pers.netname, G_GetStringEdString("MP_SVGAME", "NEWTEAMLEADER")) ); + ClientUserinfoChanged(client); + PrintTeam(team, va("print \"%s %s\n\"", level.clients[client].pers.netname, G_GetStringEdString("MP_SVGAME", "NEWTEAMLEADER"))); } /* @@ -2695,17 +2404,17 @@ void SetLeader(int team, int client) { CheckTeamLeader ================== */ -void CheckTeamLeader( int team ) { +void CheckTeamLeader(int team) { int i; - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { if (level.clients[i].sess.sessionTeam != team) continue; if (level.clients[i].sess.teamLeader) break; } if (i >= level.maxclients) { - for ( i = 0 ; i < level.maxclients ; i++ ) { + for (i = 0; i < level.maxclients; i++) { if (level.clients[i].sess.sessionTeam != team) continue; if (!(g_entities[i].r.svFlags & SVF_BOT)) { @@ -2713,9 +2422,9 @@ void CheckTeamLeader( int team ) { break; } } - if ( i >= level.maxclients ) { - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].sess.sessionTeam != team ) + if (i >= level.maxclients) { + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].sess.sessionTeam != team) continue; level.clients[i].sess.teamLeader = qtrue; break; @@ -2729,81 +2438,76 @@ void CheckTeamLeader( int team ) { CheckTeamVote ================== */ -void CheckTeamVote( int team ) { +void CheckTeamVote(int team) { int cs_offset; - if ( team == TEAM_RED ) + if (team == TEAM_RED) cs_offset = 0; - else if ( team == TEAM_BLUE ) + else if (team == TEAM_BLUE) cs_offset = 1; else return; - if ( level.teamVoteExecuteTime[cs_offset] && level.teamVoteExecuteTime[cs_offset] < level.time ) { + if (level.teamVoteExecuteTime[cs_offset] && level.teamVoteExecuteTime[cs_offset] < level.time) { level.teamVoteExecuteTime[cs_offset] = 0; - if ( !Q_strncmp( "leader", level.teamVoteString[cs_offset], 6) ) { - //set the team leader + if (!Q_strncmp("leader", level.teamVoteString[cs_offset], 6)) { + // set the team leader SetLeader(team, atoi(level.teamVoteString[cs_offset] + 7)); - } - else { - trap->SendConsoleCommand( EXEC_APPEND, va("%s\n", level.teamVoteString[cs_offset] ) ); + } else { + trap->SendConsoleCommand(EXEC_APPEND, va("%s\n", level.teamVoteString[cs_offset])); } } - if ( !level.teamVoteTime[cs_offset] ) { + if (!level.teamVoteTime[cs_offset]) { return; } - if ( level.time-level.teamVoteTime[cs_offset] >= VOTE_TIME || level.teamVoteYes[cs_offset] + level.teamVoteNo[cs_offset] == 0 ) { - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEFAILED"), level.teamVoteStringClean[cs_offset]) ); - } - else { - if ( level.teamVoteYes[cs_offset] > level.numteamVotingClients[cs_offset]/2 ) { + if (level.time - level.teamVoteTime[cs_offset] >= VOTE_TIME || level.teamVoteYes[cs_offset] + level.teamVoteNo[cs_offset] == 0) { + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEFAILED"), level.teamVoteStringClean[cs_offset])); + } else { + if (level.teamVoteYes[cs_offset] > level.numteamVotingClients[cs_offset] / 2) { // execute the command, then remove the vote - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEPASSED"), level.teamVoteStringClean[cs_offset]) ); + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEPASSED"), level.teamVoteStringClean[cs_offset])); level.voteExecuteTime = level.time + 3000; } // same behavior as a timeout - else if ( level.teamVoteNo[cs_offset] >= (level.numteamVotingClients[cs_offset]+1)/2 ) - trap->SendServerCommand( -1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEFAILED"), level.teamVoteStringClean[cs_offset]) ); + else if (level.teamVoteNo[cs_offset] >= (level.numteamVotingClients[cs_offset] + 1) / 2) + trap->SendServerCommand(-1, va("print \"%s (%s)\n\"", G_GetStringEdString("MP_SVGAME", "TEAMVOTEFAILED"), level.teamVoteStringClean[cs_offset])); else // still waiting for a majority return; } level.teamVoteTime[cs_offset] = 0; - trap->SetConfigstring( CS_TEAMVOTE_TIME + cs_offset, "" ); + trap->SetConfigstring(CS_TEAMVOTE_TIME + cs_offset, ""); } - /* ================== CheckCvars ================== */ -void CheckCvars( void ) { +void CheckCvars(void) { static int lastMod = -1; - if ( g_password.modificationCount != lastMod ) { + if (g_password.modificationCount != lastMod) { char password[MAX_INFO_STRING]; char *c = password; lastMod = g_password.modificationCount; - strcpy( password, g_password.string ); - while( *c ) - { - if ( *c == '%' ) - { + strcpy(password, g_password.string); + while (*c) { + if (*c == '%') { *c = '.'; } c++; } - trap->Cvar_Set("g_password", password ); + trap->Cvar_Set("g_password", password); - if ( *g_password.string && Q_stricmp( g_password.string, "none" ) ) { - trap->Cvar_Set( "g_needpass", "1" ); + if (*g_password.string && Q_stricmp(g_password.string, "none")) { + trap->Cvar_Set("g_needpass", "1"); } else { - trap->Cvar_Set( "g_needpass", "0" ); + trap->Cvar_Set("g_needpass", "0"); } } } @@ -2815,8 +2519,8 @@ G_RunThink Runs thinking code for this frame if necessary ============= */ -void G_RunThink (gentity_t *ent) { - float thinktime; +void G_RunThink(gentity_t *ent) { + float thinktime; thinktime = ent->nextthink; if (thinktime <= 0) { @@ -2828,18 +2532,16 @@ void G_RunThink (gentity_t *ent) { ent->nextthink = 0; if (!ent->think) { - //trap->Error( ERR_DROP, "NULL ent->think"); + // trap->Error( ERR_DROP, "NULL ent->think"); goto runicarus; } - ent->think (ent); + ent->think(ent); runicarus: - if ( ent->inuse ) - { + if (ent->inuse) { SaveNPCGlobals(); - if(NPCS.NPCInfo == NULL && ent->NPC != NULL) - { - SetNPCGlobals( ent ); + if (NPCS.NPCInfo == NULL && ent->NPC != NULL) { + SetNPCGlobals(ent); } trap->ICARUS_MaintainTaskManager(ent->s.number); RestoreNPCGlobals(); @@ -2854,44 +2556,36 @@ int gSlowMoDuelTime = 0; //#define _G_FRAME_PERFANAL -void NAV_CheckCalcPaths( void ) -{ - if ( navCalcPathTime && navCalcPathTime < level.time ) - {//first time we've ever loaded this map... - vmCvar_t mapname; - vmCvar_t ckSum; +void NAV_CheckCalcPaths(void) { + if (navCalcPathTime && navCalcPathTime < level.time) { // first time we've ever loaded this map... + vmCvar_t mapname; + vmCvar_t ckSum; - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); - trap->Cvar_Register( &ckSum, "sv_mapChecksum", "", CVAR_ROM ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); + trap->Cvar_Register(&ckSum, "sv_mapChecksum", "", CVAR_ROM); - //clear all the failed edges + // clear all the failed edges trap->Nav_ClearAllFailedEdges(); - //Calculate all paths - NAV_CalculatePaths( mapname.string, ckSum.integer ); + // Calculate all paths + NAV_CalculatePaths(mapname.string, ckSum.integer); trap->Nav_CalculatePaths(qfalse); #ifndef FINAL_BUILD - if ( fatalErrors ) - { - Com_Printf( S_COLOR_RED"Not saving .nav file due to fatal nav errors\n" ); - } - else + if (fatalErrors) { + Com_Printf(S_COLOR_RED "Not saving .nav file due to fatal nav errors\n"); + } else #endif - if ( trap->Nav_Save( mapname.string, ckSum.integer ) == qfalse ) - { - Com_Printf("Unable to save navigations data for map \"%s\" (checksum:%d)\n", mapname.string, ckSum.integer ); + if (trap->Nav_Save(mapname.string, ckSum.integer) == qfalse) { + Com_Printf("Unable to save navigations data for map \"%s\" (checksum:%d)\n", mapname.string, ckSum.integer); } navCalcPathTime = 0; } } -//so shared code can get the local time depending on the side it's executed on -int BG_GetTime(void) -{ - return level.time; -} +// so shared code can get the local time depending on the side it's executed on +int BG_GetTime(void) { return level.time; } /* ================ @@ -2900,46 +2594,39 @@ G_RunFrame Advances the non-player objects in the world ================ */ -void ClearNPCGlobals( void ); -void AI_UpdateGroups( void ); -void ClearPlayerAlertEvents( void ); +void ClearNPCGlobals(void); +void AI_UpdateGroups(void); +void ClearPlayerAlertEvents(void); void SiegeCheckTimers(void); -void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ); -extern void Jedi_Decloak( gentity_t *self ); -qboolean G_PointInBounds( vec3_t point, vec3_t mins, vec3_t maxs ); +void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd); +extern void Jedi_Decloak(gentity_t *self); +qboolean G_PointInBounds(vec3_t point, vec3_t mins, vec3_t maxs); int g_siegeRespawnCheck = 0; -void SetMoverState( gentity_t *ent, moverState_t moverState, int time ); +void SetMoverState(gentity_t *ent, moverState_t moverState, int time); -void G_RunFrame( int levelTime ) { - int i; - gentity_t *ent; +void G_RunFrame(int levelTime) { + int i; + gentity_t *ent; #ifdef _G_FRAME_PERFANAL - int iTimer_ItemRun = 0; - int iTimer_ROFF = 0; - int iTimer_ClientEndframe = 0; - int iTimer_GameChecks = 0; - int iTimer_Queues = 0; - void *timer_ItemRun; - void *timer_ROFF; - void *timer_ClientEndframe; - void *timer_GameChecks; - void *timer_Queues; + int iTimer_ItemRun = 0; + int iTimer_ROFF = 0; + int iTimer_ClientEndframe = 0; + int iTimer_GameChecks = 0; + int iTimer_Queues = 0; + void *timer_ItemRun; + void *timer_ROFF; + void *timer_ClientEndframe; + void *timer_GameChecks; + void *timer_Queues; #endif - if (level.gametype == GT_SIEGE && - g_siegeRespawn.integer && - g_siegeRespawnCheck < level.time) - { //check for a respawn wave + if (level.gametype == GT_SIEGE && g_siegeRespawn.integer && g_siegeRespawnCheck < level.time) { // check for a respawn wave gentity_t *clEnt; - for ( i=0; i < MAX_CLIENTS; i++ ) - { + for (i = 0; i < MAX_CLIENTS; i++) { clEnt = &g_entities[i]; - if (clEnt->inuse && clEnt->client && - clEnt->client->tempSpectate >= level.time && - clEnt->client->sess.sessionTeam != TEAM_SPECTATOR) - { + if (clEnt->inuse && clEnt->client && clEnt->client->tempSpectate >= level.time && clEnt->client->sess.sessionTeam != TEAM_SPECTATOR) { ClientRespawn(clEnt); clEnt->client->tempSpectate = 0; } @@ -2948,10 +2635,8 @@ void G_RunFrame( int levelTime ) { g_siegeRespawnCheck = level.time + g_siegeRespawn.integer * 1000; } - if (gDoSlowMoDuel) - { - if (level.restarted) - { + if (gDoSlowMoDuel) { + if (level.restarted) { char buf[128]; float tFVal = 0; @@ -2960,35 +2645,25 @@ void G_RunFrame( int levelTime ) { tFVal = atof(buf); trap->Cvar_Set("timescale", "1"); - if (tFVal == 1.0f) - { + if (tFVal == 1.0f) { gDoSlowMoDuel = qfalse; } - } - else - { - float timeDif = (level.time - gSlowMoDuelTime); //difference in time between when the slow motion was initiated and now - float useDif = 0; //the difference to use when actually setting the timescale + } else { + float timeDif = (level.time - gSlowMoDuelTime); // difference in time between when the slow motion was initiated and now + float useDif = 0; // the difference to use when actually setting the timescale - if (timeDif < 150) - { + if (timeDif < 150) { trap->Cvar_Set("timescale", "0.1f"); - } - else if (timeDif < 1150) - { - useDif = (timeDif/1000); //scale from 0.1 up to 1 - if (useDif < 0.1f) - { + } else if (timeDif < 1150) { + useDif = (timeDif / 1000); // scale from 0.1 up to 1 + if (useDif < 0.1f) { useDif = 0.1f; } - if (useDif > 1.0f) - { + if (useDif > 1.0f) { useDif = 1.0f; } trap->Cvar_Set("timescale", va("%f", useDif)); - } - else - { + } else { char buf[128]; float tFVal = 0; @@ -2997,8 +2672,7 @@ void G_RunFrame( int levelTime ) { tFVal = atof(buf); trap->Cvar_Set("timescale", "1"); - if (timeDif > 1500 && tFVal == 1.0f) - { + if (timeDif > 1500 && tFVal == 1.0f) { gDoSlowMoDuel = qfalse; } } @@ -3006,7 +2680,7 @@ void G_RunFrame( int levelTime ) { } // if we are waiting for the level to restart, do nothing - if ( level.restarted ) { + if (level.restarted) { return; } @@ -3014,42 +2688,35 @@ void G_RunFrame( int levelTime ) { level.previousTime = level.time; level.time = levelTime; - if (g_allowNPC.integer) - { + if (g_allowNPC.integer) { NAV_CheckCalcPaths(); } AI_UpdateGroups(); - if (g_allowNPC.integer) - { - if ( d_altRoutes.integer ) - { + if (g_allowNPC.integer) { + if (d_altRoutes.integer) { trap->Nav_CheckAllFailedEdges(); } trap->Nav_ClearCheckedNodes(); - //remember last waypoint, clear current one - for ( i = 0; i < level.num_entities ; i++) - { + // remember last waypoint, clear current one + for (i = 0; i < level.num_entities; i++) { ent = &g_entities[i]; - if ( !ent->inuse ) + if (!ent->inuse) continue; - if ( ent->waypoint != WAYPOINT_NONE - && ent->noWaypointTime < level.time ) - { + if (ent->waypoint != WAYPOINT_NONE && ent->noWaypointTime < level.time) { ent->lastWaypoint = ent->waypoint; ent->waypoint = WAYPOINT_NONE; } - if ( d_altRoutes.integer ) - { - trap->Nav_CheckFailedNodes( (sharedEntity_t *)ent ); + if (d_altRoutes.integer) { + trap->Nav_CheckFailedNodes((sharedEntity_t *)ent); } } - //Look to clear out old events + // Look to clear out old events ClearPlayerAlertEvents(); } @@ -3058,8 +2725,6 @@ void G_RunFrame( int levelTime ) { // get any cvar changes G_UpdateCvars(); - - #ifdef _G_FRAME_PERFANAL trap->PrecisionTimer_Start(&timer_ItemRun); #endif @@ -3067,59 +2732,56 @@ void G_RunFrame( int levelTime ) { // go through all allocated objects // ent = &g_entities[0]; - for (i=0 ; iinuse ) { + for (i = 0; i < level.num_entities; i++, ent++) { + if (!ent->inuse) { continue; } // clear events that are too old - if ( level.time - ent->eventTime > EVENT_VALID_MSEC ) { - if ( ent->s.event ) { - ent->s.event = 0; // &= EV_EVENT_BITS; - if ( ent->client ) { + if (level.time - ent->eventTime > EVENT_VALID_MSEC) { + if (ent->s.event) { + ent->s.event = 0; // &= EV_EVENT_BITS; + if (ent->client) { ent->client->ps.externalEvent = 0; // predicted events should never be set to zero - //ent->client->ps.events[0] = 0; - //ent->client->ps.events[1] = 0; + // ent->client->ps.events[0] = 0; + // ent->client->ps.events[1] = 0; } } - if ( ent->freeAfterEvent ) { + if (ent->freeAfterEvent) { // tempEntities or dropped items completely go away after their event - if (ent->s.eFlags & EF_SOUNDTRACKER) - { //don't trigger the event again.. + if (ent->s.eFlags & EF_SOUNDTRACKER) { // don't trigger the event again.. ent->s.event = 0; ent->s.eventParm = 0; ent->s.eType = 0; ent->eventTime = 0; - } - else - { - G_FreeEntity( ent ); + } else { + G_FreeEntity(ent); continue; } - } else if ( ent->unlinkAfterEvent ) { + } else if (ent->unlinkAfterEvent) { // items that will respawn will hide themselves after their pickup event ent->unlinkAfterEvent = qfalse; - trap->UnlinkEntity( (sharedEntity_t *)ent ); + trap->UnlinkEntity((sharedEntity_t *)ent); } } // temporary entities don't think - if ( ent->freeAfterEvent ) { + if (ent->freeAfterEvent) { continue; } - if ( !ent->r.linked && ent->neverFree ) { + if (!ent->r.linked && ent->neverFree) { continue; } - if ( ent->s.eType == ET_MISSILE ) { - G_RunMissile( ent ); + if (ent->s.eType == ET_MISSILE) { + G_RunMissile(ent); continue; } - if ( ent->s.eType == ET_ITEM || ent->physicsObject ) { -#if 0 //use if body dragging enabled? + if (ent->s.eType == ET_ITEM || ent->physicsObject) { +#if 0 // use if body dragging enabled? if (ent->s.eType == ET_BODY) { //special case for bodies float grav = 3.0f; @@ -3133,61 +2795,50 @@ void G_RunFrame( int levelTime ) { G_RunItem( ent ); } #else - G_RunItem( ent ); + G_RunItem(ent); #endif continue; } - if ( ent->s.eType == ET_MOVER ) { - G_RunMover( ent ); + if (ent->s.eType == ET_MOVER) { + G_RunMover(ent); continue; } - //fix for self-deactivating areaportals in Siege - if ( ent->s.eType == ET_MOVER && level.gametype == GT_SIEGE && level.intermissiontime) - { - if ( !Q_stricmp("func_door", ent->classname) && ent->moverState != MOVER_POS1 ) - { - SetMoverState( ent, MOVER_POS1, level.time ); - if ( ent->teammaster == ent || !ent->teammaster ) - { - trap->AdjustAreaPortalState( (sharedEntity_t *)ent, qfalse ); + // fix for self-deactivating areaportals in Siege + if (ent->s.eType == ET_MOVER && level.gametype == GT_SIEGE && level.intermissiontime) { + if (!Q_stricmp("func_door", ent->classname) && ent->moverState != MOVER_POS1) { + SetMoverState(ent, MOVER_POS1, level.time); + if (ent->teammaster == ent || !ent->teammaster) { + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qfalse); } - //stop the looping sound + // stop the looping sound ent->s.loopSound = 0; ent->s.loopIsSoundset = qfalse; } continue; } - if ( i < MAX_CLIENTS ) - { - G_CheckClientTimeouts ( ent ); + if (i < MAX_CLIENTS) { + G_CheckClientTimeouts(ent); - if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) - { //we're in space, check for suffocating and for exiting - gentity_t *spacetrigger = &g_entities[ent->client->inSpaceIndex]; + if (ent->client->inSpaceIndex && ent->client->inSpaceIndex != ENTITYNUM_NONE) { // we're in space, check for suffocating and for exiting + gentity_t *spacetrigger = &g_entities[ent->client->inSpaceIndex]; if (!spacetrigger->inuse || - !G_PointInBounds(ent->client->ps.origin, spacetrigger->r.absmin, spacetrigger->r.absmax)) - { //no longer in space then I suppose - ent->client->inSpaceIndex = 0; - } - else - { //check for suffocation - if (ent->client->inSpaceSuffocation < level.time) - { //suffocate! - if (ent->health > 0 && ent->takedamage) - { //if they're still alive.. + !G_PointInBounds(ent->client->ps.origin, spacetrigger->r.absmin, spacetrigger->r.absmax)) { // no longer in space then I suppose + ent->client->inSpaceIndex = 0; + } else { // check for suffocation + if (ent->client->inSpaceSuffocation < level.time) { // suffocate! + if (ent->health > 0 && ent->takedamage) { // if they're still alive.. G_Damage(ent, spacetrigger, spacetrigger, NULL, ent->client->ps.origin, Q_irand(50, 70), DAMAGE_NO_ARMOR, MOD_SUICIDE); - if (ent->health > 0) - { //did that last one kill them? - //play the choking sound - G_EntitySound(ent, CHAN_VOICE, G_SoundIndex(va( "*choke%d.wav", Q_irand( 1, 3 ) ))); + if (ent->health > 0) { // did that last one kill them? + // play the choking sound + G_EntitySound(ent, CHAN_VOICE, G_SoundIndex(va("*choke%d.wav", Q_irand(1, 3)))); - //make them grasp their throat + // make them grasp their throat ent->client->ps.forceHandExtend = HANDEXTEND_CHOKE; ent->client->ps.forceHandExtendTime = level.time + 2000; } @@ -3198,152 +2849,119 @@ void G_RunFrame( int levelTime ) { } } - if (ent->client->isHacking) - { //hacking checks + if (ent->client->isHacking) { // hacking checks gentity_t *hacked = &g_entities[ent->client->isHacking]; vec3_t angDif; VectorSubtract(ent->client->ps.viewangles, ent->client->hackingAngles, angDif); - //keep him in the "use" anim - if (ent->client->ps.torsoAnim != BOTH_CONSOLE1) - { - G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_CONSOLE1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - } - else - { + // keep him in the "use" anim + if (ent->client->ps.torsoAnim != BOTH_CONSOLE1) { + G_SetAnim(ent, NULL, SETANIM_TORSO, BOTH_CONSOLE1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + } else { ent->client->ps.torsoTimer = 500; } ent->client->ps.weaponTime = ent->client->ps.torsoTimer; - if (!(ent->client->pers.cmd.buttons & BUTTON_USE)) - { //have to keep holding use + if (!(ent->client->pers.cmd.buttons & BUTTON_USE)) { // have to keep holding use ent->client->isHacking = 0; ent->client->ps.hackingTime = 0; - } - else if (!hacked || !hacked->inuse) - { //shouldn't happen, but safety first + } else if (!hacked || !hacked->inuse) { // shouldn't happen, but safety first ent->client->isHacking = 0; ent->client->ps.hackingTime = 0; - } - else if (!G_PointInBounds( ent->client->ps.origin, hacked->r.absmin, hacked->r.absmax )) - { //they stepped outside the thing they're hacking, so reset hacking time + } else if (!G_PointInBounds(ent->client->ps.origin, hacked->r.absmin, + hacked->r.absmax)) { // they stepped outside the thing they're hacking, so reset hacking time ent->client->isHacking = 0; ent->client->ps.hackingTime = 0; - } - else if (VectorLength(angDif) > 10.0f) - { //must remain facing generally the same angle as when we start + } else if (VectorLength(angDif) > 10.0f) { // must remain facing generally the same angle as when we start ent->client->isHacking = 0; ent->client->ps.hackingTime = 0; } } -#define JETPACK_DEFUEL_RATE 200 //approx. 20 seconds of idle use from a fully charged fuel amt -#define JETPACK_REFUEL_RATE 150 //seems fair - if (ent->client->jetPackOn) - { //using jetpack, drain fuel - if (ent->client->jetPackDebReduce < level.time) - { - if (ent->client->pers.cmd.upmove > 0) - { //take more if they're thrusting +#define JETPACK_DEFUEL_RATE 200 // approx. 20 seconds of idle use from a fully charged fuel amt +#define JETPACK_REFUEL_RATE 150 // seems fair + if (ent->client->jetPackOn) { // using jetpack, drain fuel + if (ent->client->jetPackDebReduce < level.time) { + if (ent->client->pers.cmd.upmove > 0) { // take more if they're thrusting ent->client->ps.jetpackFuel -= 2; - } - else - { + } else { ent->client->ps.jetpackFuel--; } - if (ent->client->ps.jetpackFuel <= 0) - { //turn it off + if (ent->client->ps.jetpackFuel <= 0) { // turn it off ent->client->ps.jetpackFuel = 0; Jetpack_Off(ent); } ent->client->jetPackDebReduce = level.time + JETPACK_DEFUEL_RATE; } - } - else if (ent->client->ps.jetpackFuel < 100) - { //recharge jetpack - if (ent->client->jetPackDebRecharge < level.time) - { + } else if (ent->client->ps.jetpackFuel < 100) { // recharge jetpack + if (ent->client->jetPackDebRecharge < level.time) { ent->client->ps.jetpackFuel++; ent->client->jetPackDebRecharge = level.time + JETPACK_REFUEL_RATE; } } -#define CLOAK_DEFUEL_RATE 200 //approx. 20 seconds of idle use from a fully charged fuel amt -#define CLOAK_REFUEL_RATE 150 //seems fair - if (ent->client->ps.powerups[PW_CLOAKED]) - { //using cloak, drain battery - if (ent->client->cloakDebReduce < level.time) - { +#define CLOAK_DEFUEL_RATE 200 // approx. 20 seconds of idle use from a fully charged fuel amt +#define CLOAK_REFUEL_RATE 150 // seems fair + if (ent->client->ps.powerups[PW_CLOAKED]) { // using cloak, drain battery + if (ent->client->cloakDebReduce < level.time) { ent->client->ps.cloakFuel--; - if (ent->client->ps.cloakFuel <= 0) - { //turn it off + if (ent->client->ps.cloakFuel <= 0) { // turn it off ent->client->ps.cloakFuel = 0; Jedi_Decloak(ent); } ent->client->cloakDebReduce = level.time + CLOAK_DEFUEL_RATE; } - } - else if (ent->client->ps.cloakFuel < 100) - { //recharge cloak - if (ent->client->cloakDebRecharge < level.time) - { + } else if (ent->client->ps.cloakFuel < 100) { // recharge cloak + if (ent->client->cloakDebRecharge < level.time) { ent->client->ps.cloakFuel++; ent->client->cloakDebRecharge = level.time + CLOAK_REFUEL_RATE; } } - if (level.gametype == GT_SIEGE && - ent->client->siegeClass != -1 && - (bgSiegeClasses[ent->client->siegeClass].classflags & (1<client->siegeEDataSend < level.time) - { - G_SiegeClientExData(ent); - ent->client->siegeEDataSend = level.time + 1000; //once every sec seems ok + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && + (bgSiegeClasses[ent->client->siegeClass].classflags & (1 << CFL_STATVIEWER))) { // see if it's time to send this guy an update of extended info + if (ent->client->siegeEDataSend < level.time) { + G_SiegeClientExData(ent); + ent->client->siegeEDataSend = level.time + 1000; // once every sec seems ok } } - if((!level.intermissiontime)&&!(ent->client->ps.pm_flags&PMF_FOLLOW) && ent->client->sess.sessionTeam != TEAM_SPECTATOR) - { - WP_ForcePowersUpdate(ent, &ent->client->pers.cmd ); + if ((!level.intermissiontime) && !(ent->client->ps.pm_flags & PMF_FOLLOW) && ent->client->sess.sessionTeam != TEAM_SPECTATOR) { + WP_ForcePowersUpdate(ent, &ent->client->pers.cmd); WP_SaberPositionUpdate(ent, &ent->client->pers.cmd); WP_SaberStartMissileBlockCheck(ent, &ent->client->pers.cmd); } - if (g_allowNPC.integer) - { - //This was originally intended to only be done for client 0. - //Make sure it doesn't slow things down too much with lots of clients in game. + if (g_allowNPC.integer) { + // This was originally intended to only be done for client 0. + // Make sure it doesn't slow things down too much with lots of clients in game. NAV_FindPlayerWaypoint(i); } trap->ICARUS_MaintainTaskManager(ent->s.number); - G_RunClient( ent ); + G_RunClient(ent); continue; - } - else if (ent->s.eType == ET_NPC) - { + } else if (ent->s.eType == ET_NPC) { int j; // turn off any expired powerups - for ( j = 0 ; j < MAX_POWERUPS ; j++ ) { - if ( ent->client->ps.powerups[ j ] < level.time ) { - ent->client->ps.powerups[ j ] = 0; + for (j = 0; j < MAX_POWERUPS; j++) { + if (ent->client->ps.powerups[j] < level.time) { + ent->client->ps.powerups[j] = 0; } } - WP_ForcePowersUpdate(ent, &ent->client->pers.cmd ); + WP_ForcePowersUpdate(ent, &ent->client->pers.cmd); WP_SaberPositionUpdate(ent, &ent->client->pers.cmd); WP_SaberStartMissileBlockCheck(ent, &ent->client->pers.cmd); } - G_RunThink( ent ); + G_RunThink(ent); - if (g_allowNPC.integer) - { + if (g_allowNPC.integer) { ClearNPCGlobals(); } } @@ -3361,24 +2979,20 @@ void G_RunFrame( int levelTime ) { iTimer_ROFF = trap->PrecisionTimer_End(timer_ROFF); #endif - - #ifdef _G_FRAME_PERFANAL trap->PrecisionTimer_Start(&timer_ClientEndframe); #endif // perform final fixups on the players ent = &g_entities[0]; - for (i=0 ; i < level.maxclients ; i++, ent++ ) { - if ( ent->inuse ) { - ClientEndFrame( ent ); + for (i = 0; i < level.maxclients; i++, ent++) { + if (ent->inuse) { + ClientEndFrame(ent); } } #ifdef _G_FRAME_PERFANAL iTimer_ClientEndframe = trap->PrecisionTimer_End(timer_ClientEndframe); #endif - - #ifdef _G_FRAME_PERFANAL trap->PrecisionTimer_Start(&timer_GameChecks); #endif @@ -3395,8 +3009,8 @@ void G_RunFrame( int levelTime ) { CheckVote(); // check team votes - CheckTeamVote( TEAM_RED ); - CheckTeamVote( TEAM_BLUE ); + CheckTeamVote(TEAM_RED); + CheckTeamVote(TEAM_BLUE); // for tracking changes CheckCvars(); @@ -3405,18 +3019,14 @@ void G_RunFrame( int levelTime ) { iTimer_GameChecks = trap->PrecisionTimer_End(timer_GameChecks); #endif - - #ifdef _G_FRAME_PERFANAL trap->PrecisionTimer_Start(&timer_Queues); #endif - //At the end of the frame, send out the ghoul2 kill queue, if there is one + // At the end of the frame, send out the ghoul2 kill queue, if there is one G_SendG2KillQueue(); - if (gQueueScoreMessage) - { - if (gQueueScoreMessageTime < level.time) - { + if (gQueueScoreMessage) { + if (gQueueScoreMessageTime < level.time) { SendScoreboardMessageToAllClients(); gQueueScoreMessageTime = 0; @@ -3427,131 +3037,118 @@ void G_RunFrame( int levelTime ) { iTimer_Queues = trap->PrecisionTimer_End(timer_Queues); #endif - - #ifdef _G_FRAME_PERFANAL - Com_Printf("---------------\nItemRun: %i\nROFF: %i\nClientEndframe: %i\nGameChecks: %i\nQueues: %i\n---------------\n", - iTimer_ItemRun, - iTimer_ROFF, - iTimer_ClientEndframe, - iTimer_GameChecks, - iTimer_Queues); + Com_Printf("---------------\nItemRun: %i\nROFF: %i\nClientEndframe: %i\nGameChecks: %i\nQueues: %i\n---------------\n", iTimer_ItemRun, iTimer_ROFF, + iTimer_ClientEndframe, iTimer_GameChecks, iTimer_Queues); #endif g_LastFrameTime = level.time; } -const char *G_GetStringEdString(char *refSection, char *refName) -{ +const char *G_GetStringEdString(char *refSection, char *refName) { /* static char text[1024]={0}; trap->SP_GetStringTextString(va("%s_%s", refSection, refName), text, sizeof(text)); return text; */ - //Well, it would've been lovely doing it the above way, but it would mean mixing - //languages for the client depending on what the server is. So we'll mark this as - //a stringed reference with @@@ and send the refname to the client, and when it goes - //to print it will get scanned for the stringed reference indication and dealt with - //properly. - static char text[1024]={0}; + // Well, it would've been lovely doing it the above way, but it would mean mixing + // languages for the client depending on what the server is. So we'll mark this as + // a stringed reference with @@@ and send the refname to the client, and when it goes + // to print it will get scanned for the stringed reference indication and dealt with + // properly. + static char text[1024] = {0}; Com_sprintf(text, sizeof(text), "@@@%s", refName); return text; } -static void G_SpawnRMGEntity( void ) { - if ( G_ParseSpawnVars( qfalse ) ) - G_SpawnGEntityFromSpawnVars( qfalse ); +static void G_SpawnRMGEntity(void) { + if (G_ParseSpawnVars(qfalse)) + G_SpawnGEntityFromSpawnVars(qfalse); } -static void _G_ROFF_NotetrackCallback( int entID, const char *notetrack ) { - G_ROFF_NotetrackCallback( &g_entities[entID], notetrack ); -} +static void _G_ROFF_NotetrackCallback(int entID, const char *notetrack) { G_ROFF_NotetrackCallback(&g_entities[entID], notetrack); } -static int G_ICARUS_PlaySound( void ) { +static int G_ICARUS_PlaySound(void) { T_G_ICARUS_PLAYSOUND *sharedMem = &gSharedBuffer.playSound; - return Q3_PlaySound( sharedMem->taskID, sharedMem->entID, sharedMem->name, sharedMem->channel ); + return Q3_PlaySound(sharedMem->taskID, sharedMem->entID, sharedMem->name, sharedMem->channel); } -static qboolean G_ICARUS_Set( void ) { +static qboolean G_ICARUS_Set(void) { T_G_ICARUS_SET *sharedMem = &gSharedBuffer.set; - return Q3_Set( sharedMem->taskID, sharedMem->entID, sharedMem->type_name, sharedMem->data ); + return Q3_Set(sharedMem->taskID, sharedMem->entID, sharedMem->type_name, sharedMem->data); } -static void G_ICARUS_Lerp2Pos( void ) { +static void G_ICARUS_Lerp2Pos(void) { T_G_ICARUS_LERP2POS *sharedMem = &gSharedBuffer.lerp2Pos; - Q3_Lerp2Pos( sharedMem->taskID, sharedMem->entID, sharedMem->origin, sharedMem->nullAngles ? NULL : sharedMem->angles, sharedMem->duration ); + Q3_Lerp2Pos(sharedMem->taskID, sharedMem->entID, sharedMem->origin, sharedMem->nullAngles ? NULL : sharedMem->angles, sharedMem->duration); } -static void G_ICARUS_Lerp2Origin( void ) { +static void G_ICARUS_Lerp2Origin(void) { T_G_ICARUS_LERP2ORIGIN *sharedMem = &gSharedBuffer.lerp2Origin; - Q3_Lerp2Origin( sharedMem->taskID, sharedMem->entID, sharedMem->origin, sharedMem->duration ); + Q3_Lerp2Origin(sharedMem->taskID, sharedMem->entID, sharedMem->origin, sharedMem->duration); } -static void G_ICARUS_Lerp2Angles( void ) { +static void G_ICARUS_Lerp2Angles(void) { T_G_ICARUS_LERP2ANGLES *sharedMem = &gSharedBuffer.lerp2Angles; - Q3_Lerp2Angles( sharedMem->taskID, sharedMem->entID, sharedMem->angles, sharedMem->duration ); + Q3_Lerp2Angles(sharedMem->taskID, sharedMem->entID, sharedMem->angles, sharedMem->duration); } -static int G_ICARUS_GetTag( void ) { +static int G_ICARUS_GetTag(void) { T_G_ICARUS_GETTAG *sharedMem = &gSharedBuffer.getTag; - return Q3_GetTag( sharedMem->entID, sharedMem->name, sharedMem->lookup, sharedMem->info ); + return Q3_GetTag(sharedMem->entID, sharedMem->name, sharedMem->lookup, sharedMem->info); } -static void G_ICARUS_Lerp2Start( void ) { +static void G_ICARUS_Lerp2Start(void) { T_G_ICARUS_LERP2START *sharedMem = &gSharedBuffer.lerp2Start; - Q3_Lerp2Start( sharedMem->entID, sharedMem->taskID, sharedMem->duration ); + Q3_Lerp2Start(sharedMem->entID, sharedMem->taskID, sharedMem->duration); } -static void G_ICARUS_Lerp2End( void ) { +static void G_ICARUS_Lerp2End(void) { T_G_ICARUS_LERP2END *sharedMem = &gSharedBuffer.lerp2End; - Q3_Lerp2End( sharedMem->entID, sharedMem->taskID, sharedMem->duration ); + Q3_Lerp2End(sharedMem->entID, sharedMem->taskID, sharedMem->duration); } -static void G_ICARUS_Use( void ) { +static void G_ICARUS_Use(void) { T_G_ICARUS_USE *sharedMem = &gSharedBuffer.use; - Q3_Use( sharedMem->entID, sharedMem->target ); + Q3_Use(sharedMem->entID, sharedMem->target); } -static void G_ICARUS_Kill( void ) { +static void G_ICARUS_Kill(void) { T_G_ICARUS_KILL *sharedMem = &gSharedBuffer.kill; - Q3_Kill( sharedMem->entID, sharedMem->name ); + Q3_Kill(sharedMem->entID, sharedMem->name); } -static void G_ICARUS_Remove( void ) { +static void G_ICARUS_Remove(void) { T_G_ICARUS_REMOVE *sharedMem = &gSharedBuffer.remove; - Q3_Remove( sharedMem->entID, sharedMem->name ); + Q3_Remove(sharedMem->entID, sharedMem->name); } -static void G_ICARUS_Play( void ) { +static void G_ICARUS_Play(void) { T_G_ICARUS_PLAY *sharedMem = &gSharedBuffer.play; - Q3_Play( sharedMem->taskID, sharedMem->entID, sharedMem->type, sharedMem->name ); + Q3_Play(sharedMem->taskID, sharedMem->entID, sharedMem->type, sharedMem->name); } -static int G_ICARUS_GetFloat( void ) { +static int G_ICARUS_GetFloat(void) { T_G_ICARUS_GETFLOAT *sharedMem = &gSharedBuffer.getFloat; - return Q3_GetFloat( sharedMem->entID, sharedMem->type, sharedMem->name, &sharedMem->value ); + return Q3_GetFloat(sharedMem->entID, sharedMem->type, sharedMem->name, &sharedMem->value); } -static int G_ICARUS_GetVector( void ) { +static int G_ICARUS_GetVector(void) { T_G_ICARUS_GETVECTOR *sharedMem = &gSharedBuffer.getVector; - return Q3_GetVector( sharedMem->entID, sharedMem->type, sharedMem->name, sharedMem->value ); + return Q3_GetVector(sharedMem->entID, sharedMem->type, sharedMem->name, sharedMem->value); } -static int G_ICARUS_GetString( void ) { +static int G_ICARUS_GetString(void) { T_G_ICARUS_GETSTRING *sharedMem = &gSharedBuffer.getString; - char *crap = NULL; //I am sorry for this -rww - char **morecrap = &crap; //and this - int r = Q3_GetString( sharedMem->entID, sharedMem->type, sharedMem->name, morecrap ); + char *crap = NULL; // I am sorry for this -rww + char **morecrap = &crap; // and this + int r = Q3_GetString(sharedMem->entID, sharedMem->type, sharedMem->name, morecrap); - if ( crap ) - strcpy( sharedMem->value, crap ); + if (crap) + strcpy(sharedMem->value, crap); return r; } -static void G_ICARUS_SoundIndex( void ) { +static void G_ICARUS_SoundIndex(void) { T_G_ICARUS_SOUNDINDEX *sharedMem = &gSharedBuffer.soundIndex; - G_SoundIndex( sharedMem->filename ); + G_SoundIndex(sharedMem->filename); } -static int G_ICARUS_GetSetIDForString( void ) { +static int G_ICARUS_GetSetIDForString(void) { T_G_ICARUS_GETSETIDFORSTRING *sharedMem = &gSharedBuffer.getSetIDForString; - return GetIDForString( setTable, sharedMem->string ); -} -static qboolean G_NAV_ClearPathToPoint( int entID, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEnt ) { - return NAV_ClearPathToPoint( &g_entities[entID], pmins, pmaxs, point, clipmask, okToHitEnt ); -} -static qboolean G_NPC_ClearLOS2( int entID, const vec3_t end ) { - return NPC_ClearLOS2( &g_entities[entID], end ); + return GetIDForString(setTable, sharedMem->string); } -static qboolean G_NAV_CheckNodeFailedForEnt( int entID, int nodeNum ) { - return NAV_CheckNodeFailedForEnt( &g_entities[entID], nodeNum ); +static qboolean G_NAV_ClearPathToPoint(int entID, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEnt) { + return NAV_ClearPathToPoint(&g_entities[entID], pmins, pmaxs, point, clipmask, okToHitEnt); } +static qboolean G_NPC_ClearLOS2(int entID, const vec3_t end) { return NPC_ClearLOS2(&g_entities[entID], end); } +static qboolean G_NAV_CheckNodeFailedForEnt(int entID, int nodeNum) { return NAV_CheckNodeFailedForEnt(&g_entities[entID], nodeNum); } /* ============ @@ -3561,62 +3158,61 @@ GetModuleAPI gameImport_t *trap = NULL; -Q_EXPORT gameExport_t* QDECL GetModuleAPI( int apiVersion, gameImport_t *import ) -{ +Q_EXPORT gameExport_t *QDECL GetModuleAPI(int apiVersion, gameImport_t *import) { static gameExport_t ge = {0}; - assert( import ); + assert(import); trap = import; - Com_Printf = trap->Print; - Com_Error = trap->Error; + Com_Printf = trap->Print; + Com_Error = trap->Error; - memset( &ge, 0, sizeof( ge ) ); + memset(&ge, 0, sizeof(ge)); - if ( apiVersion != GAME_API_VERSION ) { - trap->Print( "Mismatched GAME_API_VERSION: expected %i, got %i\n", GAME_API_VERSION, apiVersion ); + if (apiVersion != GAME_API_VERSION) { + trap->Print("Mismatched GAME_API_VERSION: expected %i, got %i\n", GAME_API_VERSION, apiVersion); return NULL; } - ge.InitGame = G_InitGame; - ge.ShutdownGame = G_ShutdownGame; - ge.ClientConnect = ClientConnect; - ge.ClientBegin = ClientBegin; - ge.ClientUserinfoChanged = ClientUserinfoChanged; - ge.ClientDisconnect = ClientDisconnect; - ge.ClientCommand = ClientCommand; - ge.ClientThink = ClientThink; - ge.RunFrame = G_RunFrame; - ge.ConsoleCommand = ConsoleCommand; - ge.BotAIStartFrame = BotAIStartFrame; - ge.ROFF_NotetrackCallback = _G_ROFF_NotetrackCallback; - ge.SpawnRMGEntity = G_SpawnRMGEntity; - ge.ICARUS_PlaySound = G_ICARUS_PlaySound; - ge.ICARUS_Set = G_ICARUS_Set; - ge.ICARUS_Lerp2Pos = G_ICARUS_Lerp2Pos; - ge.ICARUS_Lerp2Origin = G_ICARUS_Lerp2Origin; - ge.ICARUS_Lerp2Angles = G_ICARUS_Lerp2Angles; - ge.ICARUS_GetTag = G_ICARUS_GetTag; - ge.ICARUS_Lerp2Start = G_ICARUS_Lerp2Start; - ge.ICARUS_Lerp2End = G_ICARUS_Lerp2End; - ge.ICARUS_Use = G_ICARUS_Use; - ge.ICARUS_Kill = G_ICARUS_Kill; - ge.ICARUS_Remove = G_ICARUS_Remove; - ge.ICARUS_Play = G_ICARUS_Play; - ge.ICARUS_GetFloat = G_ICARUS_GetFloat; - ge.ICARUS_GetVector = G_ICARUS_GetVector; - ge.ICARUS_GetString = G_ICARUS_GetString; - ge.ICARUS_SoundIndex = G_ICARUS_SoundIndex; - ge.ICARUS_GetSetIDForString = G_ICARUS_GetSetIDForString; - ge.NAV_ClearPathToPoint = G_NAV_ClearPathToPoint; - ge.NPC_ClearLOS2 = G_NPC_ClearLOS2; - ge.NAVNEW_ClearPathBetweenPoints = NAVNEW_ClearPathBetweenPoints; - ge.NAV_CheckNodeFailedForEnt = G_NAV_CheckNodeFailedForEnt; - ge.NAV_EntIsUnlockedDoor = G_EntIsUnlockedDoor; - ge.NAV_EntIsDoor = G_EntIsDoor; - ge.NAV_EntIsBreakable = G_EntIsBreakable; - ge.NAV_EntIsRemovableUsable = G_EntIsRemovableUsable; - ge.NAV_FindCombatPointWaypoints = CP_FindCombatPointWaypoints; - ge.BG_GetItemIndexByTag = BG_GetItemIndexByTag; + ge.InitGame = G_InitGame; + ge.ShutdownGame = G_ShutdownGame; + ge.ClientConnect = ClientConnect; + ge.ClientBegin = ClientBegin; + ge.ClientUserinfoChanged = ClientUserinfoChanged; + ge.ClientDisconnect = ClientDisconnect; + ge.ClientCommand = ClientCommand; + ge.ClientThink = ClientThink; + ge.RunFrame = G_RunFrame; + ge.ConsoleCommand = ConsoleCommand; + ge.BotAIStartFrame = BotAIStartFrame; + ge.ROFF_NotetrackCallback = _G_ROFF_NotetrackCallback; + ge.SpawnRMGEntity = G_SpawnRMGEntity; + ge.ICARUS_PlaySound = G_ICARUS_PlaySound; + ge.ICARUS_Set = G_ICARUS_Set; + ge.ICARUS_Lerp2Pos = G_ICARUS_Lerp2Pos; + ge.ICARUS_Lerp2Origin = G_ICARUS_Lerp2Origin; + ge.ICARUS_Lerp2Angles = G_ICARUS_Lerp2Angles; + ge.ICARUS_GetTag = G_ICARUS_GetTag; + ge.ICARUS_Lerp2Start = G_ICARUS_Lerp2Start; + ge.ICARUS_Lerp2End = G_ICARUS_Lerp2End; + ge.ICARUS_Use = G_ICARUS_Use; + ge.ICARUS_Kill = G_ICARUS_Kill; + ge.ICARUS_Remove = G_ICARUS_Remove; + ge.ICARUS_Play = G_ICARUS_Play; + ge.ICARUS_GetFloat = G_ICARUS_GetFloat; + ge.ICARUS_GetVector = G_ICARUS_GetVector; + ge.ICARUS_GetString = G_ICARUS_GetString; + ge.ICARUS_SoundIndex = G_ICARUS_SoundIndex; + ge.ICARUS_GetSetIDForString = G_ICARUS_GetSetIDForString; + ge.NAV_ClearPathToPoint = G_NAV_ClearPathToPoint; + ge.NPC_ClearLOS2 = G_NPC_ClearLOS2; + ge.NAVNEW_ClearPathBetweenPoints = NAVNEW_ClearPathBetweenPoints; + ge.NAV_CheckNodeFailedForEnt = G_NAV_CheckNodeFailedForEnt; + ge.NAV_EntIsUnlockedDoor = G_EntIsUnlockedDoor; + ge.NAV_EntIsDoor = G_EntIsDoor; + ge.NAV_EntIsBreakable = G_EntIsBreakable; + ge.NAV_EntIsRemovableUsable = G_EntIsRemovableUsable; + ge.NAV_FindCombatPointWaypoints = CP_FindCombatPointWaypoints; + ge.BG_GetItemIndexByTag = BG_GetItemIndexByTag; return ≥ } @@ -3629,53 +3225,52 @@ This is the only way control passes into the module. This must be the very first function compiled into the .q3vm file ================ */ -Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, - intptr_t arg5, intptr_t arg6, intptr_t arg7, intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11 ) -{ - switch ( command ) { +Q_EXPORT intptr_t vmMain(int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7, + intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11) { + switch (command) { case GAME_INIT: - G_InitGame( arg0, arg1, arg2 ); + G_InitGame(arg0, arg1, arg2); return 0; case GAME_SHUTDOWN: - G_ShutdownGame( arg0 ); + G_ShutdownGame(arg0); return 0; case GAME_CLIENT_CONNECT: - return (intptr_t)ClientConnect( arg0, arg1, arg2 ); + return (intptr_t)ClientConnect(arg0, arg1, arg2); case GAME_CLIENT_THINK: - ClientThink( arg0, NULL ); + ClientThink(arg0, NULL); return 0; case GAME_CLIENT_USERINFO_CHANGED: - ClientUserinfoChanged( arg0 ); + ClientUserinfoChanged(arg0); return 0; case GAME_CLIENT_DISCONNECT: - ClientDisconnect( arg0 ); + ClientDisconnect(arg0); return 0; case GAME_CLIENT_BEGIN: - ClientBegin( arg0, qtrue ); + ClientBegin(arg0, qtrue); return 0; case GAME_CLIENT_COMMAND: - ClientCommand( arg0 ); + ClientCommand(arg0); return 0; case GAME_RUN_FRAME: - G_RunFrame( arg0 ); + G_RunFrame(arg0); return 0; case GAME_CONSOLE_COMMAND: return ConsoleCommand(); case BOTAI_START_FRAME: - return BotAIStartFrame( arg0 ); + return BotAIStartFrame(arg0); case GAME_ROFF_NOTETRACK_CALLBACK: - _G_ROFF_NotetrackCallback( arg0, (const char *)arg1 ); + _G_ROFF_NotetrackCallback(arg0, (const char *)arg1); return 0; case GAME_SPAWN_RMG_ENTITY: @@ -3744,10 +3339,10 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return G_ICARUS_GetSetIDForString(); case GAME_NAV_CLEARPATHTOPOINT: - return G_NAV_ClearPathToPoint( arg0, (float *)arg1, (float *)arg2, (float *)arg3, arg4, arg5 ); + return G_NAV_ClearPathToPoint(arg0, (float *)arg1, (float *)arg2, (float *)arg3, arg4, arg5); case GAME_NAV_CLEARLOS: - return G_NPC_ClearLOS2( arg0, (const float *)arg1 ); + return G_NPC_ClearLOS2(arg0, (const float *)arg1); case GAME_NAV_CLEARPATHBETWEENPOINTS: return NAVNEW_ClearPathBetweenPoints((float *)arg0, (float *)arg1, (float *)arg2, (float *)arg3, arg4, arg5); diff --git a/codemp/game/g_mem.c b/codemp/game/g_mem.c index d677b1b8a6..843ede73ac 100644 --- a/codemp/game/g_mem.c +++ b/codemp/game/g_mem.c @@ -42,40 +42,38 @@ along with this program; if not, see . http://www.altdevblogaday.com/2011/02/12/alternatives-to-malloc-and-new/ */ -#define POOLSIZE (4 * 1024 * 1024) // (256*1024) +#define POOLSIZE (4 * 1024 * 1024) // (256*1024) -static char memoryPool[POOLSIZE]; -static int allocPoint; +static char memoryPool[POOLSIZE]; +static int allocPoint; -void *G_Alloc( int size ) { - char *p; +void *G_Alloc(int size) { + char *p; - if ( size <= 0 ) { - trap->Error( ERR_DROP, "G_Alloc: zero-size allocation\n", size ); + if (size <= 0) { + trap->Error(ERR_DROP, "G_Alloc: zero-size allocation\n", size); return NULL; } - if ( g_debugAlloc.integer ) { - trap->Print( "G_Alloc of %i bytes (%i left)\n", size, POOLSIZE - allocPoint - ( ( size + 31 ) & ~31 ) ); + if (g_debugAlloc.integer) { + trap->Print("G_Alloc of %i bytes (%i left)\n", size, POOLSIZE - allocPoint - ((size + 31) & ~31)); } - if ( allocPoint + size > POOLSIZE ) { - trap->Error( ERR_DROP, "G_Alloc: failed on allocation of %i bytes\n", size ); // bk010103 - was %u, but is signed + if (allocPoint + size > POOLSIZE) { + trap->Error(ERR_DROP, "G_Alloc: failed on allocation of %i bytes\n", size); // bk010103 - was %u, but is signed return NULL; } p = &memoryPool[allocPoint]; - allocPoint += ( size + 31 ) & ~31; + allocPoint += (size + 31) & ~31; return p; } -void G_InitMemory( void ) { - allocPoint = 0; -} +void G_InitMemory(void) { allocPoint = 0; } -void Svcmd_GameMem_f( void ) { +void Svcmd_GameMem_f(void) { float f = allocPoint; f /= POOLSIZE; f *= 100; diff --git a/codemp/game/g_misc.c b/codemp/game/g_misc.c index ef182490ce..74e6158fca 100644 --- a/codemp/game/g_misc.c +++ b/codemp/game/g_misc.c @@ -38,31 +38,21 @@ void HolocronThink(gentity_t *ent); Used to group brushes together just for editor convenience. They are turned into normal brushes by the utilities. */ - /*QUAKED info_camp (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay. */ -void SP_info_camp( gentity_t *self ) { - G_SetOrigin( self, self->s.origin ); -} - +void SP_info_camp(gentity_t *self) { G_SetOrigin(self, self->s.origin); } /*QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for calculations in the utilities (spotlights, etc), but removed during gameplay. */ -void SP_info_null( gentity_t *self ) { - G_FreeEntity( self ); -} - +void SP_info_null(gentity_t *self) { G_FreeEntity(self); } /*QUAKED info_notnull (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. target_position does the same thing */ -void SP_info_notnull( gentity_t *self ){ - G_SetOrigin( self, self->s.origin ); -} - +void SP_info_notnull(gentity_t *self) { G_SetOrigin(self, self->s.origin); } /*QUAKED lightJunior (0 0.7 0.3) (-8 -8 -8) (8 8 8) nonlinear angle negative_spot negative_point Non-displayed light that only affects dynamic game models, but does not contribute to lightmaps @@ -85,9 +75,9 @@ Lights pointed at a target will be spotlights. "scale" multiplier for the light intensity - does not affect size (default 1) greater than 1 is brighter, between 0 and 1 is dimmer. "color" sets the light's color -"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, styles or start_off flag) -"style" to specify a specify light style, even for switchable lights! -"style_off" light style to use when switched off (Only for switchable lights) +"targetname" to indicate a switchable light - NOTE that all lights with the same targetname will be grouped together and act as one light (ie: don't mix colors, +styles or start_off flag) "style" to specify a specify light style, even for switchable lights! "style_off" light style to use when switched off (Only for +switchable lights) 1 FLICKER (first variety) 2 SLOW STRONG PULSE @@ -103,74 +93,65 @@ Lights pointed at a target will be spotlights. 12 FAST PULSE FOR JEREMY 13 Test Blending */ -static void misc_lightstyle_set ( gentity_t *ent) -{ +static void misc_lightstyle_set(gentity_t *ent) { const int mLightStyle = ent->count; const int mLightSwitchStyle = ent->bounceCount; const int mLightOffStyle = ent->fly_sound_debounce_time; - if (!ent->alt_fire) - { //turn off - if (mLightOffStyle) //i have a light style i'd like to use when off + if (!ent->alt_fire) { // turn off + if (mLightOffStyle) // i have a light style i'd like to use when off { char lightstyle[32]; - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+0, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 0, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+1, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 1, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle*3)+2, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - }else - { - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "a"); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "a"); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "a"); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightOffStyle * 3) + 2, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "a"); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "a"); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "a"); } - } - else - { //Turn myself on now - if (mLightSwitchStyle) //i have a light style i'd like to use when on + } else { // Turn myself on now + if (mLightSwitchStyle) // i have a light style i'd like to use when on { char lightstyle[32]; - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+0, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, lightstyle); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 0, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, lightstyle); - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+1, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, lightstyle); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 1, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, lightstyle); - trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle*3)+2, lightstyle, 32); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, lightstyle); - } - else - { - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+0, "z"); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+1, "z"); - trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle*3)+2, "z"); + trap->GetConfigstring(CS_LIGHT_STYLES + (mLightSwitchStyle * 3) + 2, lightstyle, 32); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, lightstyle); + } else { + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 0, "z"); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 1, "z"); + trap->SetConfigstring(CS_LIGHT_STYLES + (mLightStyle * 3) + 2, "z"); } } } -void misc_dlight_use ( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +void misc_dlight_use(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - ent->alt_fire = !ent->alt_fire; //toggle - misc_lightstyle_set (ent); + ent->alt_fire = !ent->alt_fire; // toggle + misc_lightstyle_set(ent); } -void SP_light( gentity_t *self ) { - if (!self->targetname ) - {//if i don't have a light style switch, the i go away - G_FreeEntity( self ); +void SP_light(gentity_t *self) { + if (!self->targetname) { // if i don't have a light style switch, the i go away + G_FreeEntity(self); return; } - G_SpawnInt( "style", "0", &self->count ); - G_SpawnInt( "switch_style", "0", &self->bounceCount ); - G_SpawnInt( "style_off", "0", &self->fly_sound_debounce_time ); - G_SetOrigin( self, self->s.origin ); - trap->LinkEntity( (sharedEntity_t *)self ); + G_SpawnInt("style", "0", &self->count); + G_SpawnInt("switch_style", "0", &self->bounceCount); + G_SpawnInt("style_off", "0", &self->fly_sound_debounce_time); + G_SetOrigin(self, self->s.origin); + trap->LinkEntity((sharedEntity_t *)self); self->use = misc_dlight_use; @@ -178,14 +159,12 @@ void SP_light( gentity_t *self ) { self->alt_fire = qfalse; self->r.svFlags |= SVF_NOCLIENT; - if ( !(self->spawnflags & 4) ) - { //turn myself on now + if (!(self->spawnflags & 4)) { // turn myself on now self->alt_fire = qtrue; } - misc_lightstyle_set (self); + misc_lightstyle_set(self); } - /* ================================================================================= @@ -194,12 +173,11 @@ TELEPORTERS ================================================================================= */ -void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ) { - gentity_t *tent; - qboolean isNPC = qfalse; - qboolean noAngles; - if (player->s.eType == ET_NPC) - { +void TeleportPlayer(gentity_t *player, vec3_t origin, vec3_t angles) { + gentity_t *tent; + qboolean isNPC = qfalse; + qboolean noAngles; + if (player->s.eType == ET_NPC) { isNPC = qtrue; } @@ -207,63 +185,59 @@ void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ) { // use temp events at source and destination to prevent the effect // from getting dropped by a second player event - if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) { - tent = G_TempEntity( player->client->ps.origin, EV_PLAYER_TELEPORT_OUT ); + if (player->client->sess.sessionTeam != TEAM_SPECTATOR) { + tent = G_TempEntity(player->client->ps.origin, EV_PLAYER_TELEPORT_OUT); tent->s.clientNum = player->s.clientNum; - tent = G_TempEntity( origin, EV_PLAYER_TELEPORT_IN ); + tent = G_TempEntity(origin, EV_PLAYER_TELEPORT_IN); tent->s.clientNum = player->s.clientNum; } // unlink to make sure it can't possibly interfere with G_KillBox - trap->UnlinkEntity ((sharedEntity_t *)player); + trap->UnlinkEntity((sharedEntity_t *)player); - VectorCopy ( origin, player->client->ps.origin ); + VectorCopy(origin, player->client->ps.origin); player->client->ps.origin[2] += 1; // spit the player out - if ( !noAngles ) { - AngleVectors( angles, player->client->ps.velocity, NULL, NULL ); - VectorScale( player->client->ps.velocity, 400, player->client->ps.velocity ); - player->client->ps.pm_time = 160; // hold time + if (!noAngles) { + AngleVectors(angles, player->client->ps.velocity, NULL, NULL); + VectorScale(player->client->ps.velocity, 400, player->client->ps.velocity); + player->client->ps.pm_time = 160; // hold time player->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; // set angles - SetClientViewAngle( player, angles ); + SetClientViewAngle(player, angles); } // toggle the teleport bit so the client knows to not lerp player->client->ps.eFlags ^= EF_TELEPORT_BIT; // kill anything at the destination - if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) { - G_KillBox (player); + if (player->client->sess.sessionTeam != TEAM_SPECTATOR) { + G_KillBox(player); } // save results of pmove - BG_PlayerStateToEntityState( &player->client->ps, &player->s, qtrue ); - if (isNPC) - { + BG_PlayerStateToEntityState(&player->client->ps, &player->s, qtrue); + if (isNPC) { player->s.eType = ET_NPC; } // use the precise origin for linking - VectorCopy( player->client->ps.origin, player->r.currentOrigin ); + VectorCopy(player->client->ps.origin, player->r.currentOrigin); - if ( player->client->sess.sessionTeam != TEAM_SPECTATOR ) { - trap->LinkEntity ((sharedEntity_t *)player); + if (player->client->sess.sessionTeam != TEAM_SPECTATOR) { + trap->LinkEntity((sharedEntity_t *)player); } } - /*QUAKED misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16) Point teleporters at these. Now that we don't have teleport destination pads, this is just an info_notnull */ -void SP_misc_teleporter_dest( gentity_t *ent ) { -} - +void SP_misc_teleporter_dest(gentity_t *ent) {} //=========================================================== @@ -271,7 +245,7 @@ void SP_misc_teleporter_dest( gentity_t *ent ) { "model" arbitrary .md3 or .ase file to display turns into map triangles - not solid */ -void SP_misc_model( gentity_t *ent ) { +void SP_misc_model(gentity_t *ent) { #if 0 ent->s.modelindex = G_ModelIndex( ent->model ); @@ -282,7 +256,7 @@ void SP_misc_model( gentity_t *ent ) { G_SetOrigin( ent, ent->s.origin ); VectorCopy( ent->s.angles, ent->s.apos.trBase ); #else - G_FreeEntity( ent ); + G_FreeEntity(ent); #endif } @@ -299,10 +273,7 @@ void SP_misc_model( gentity_t *ent ) { loaded as a model in the renderer - does not take up precious bsp space! */ -void SP_misc_model_static(gentity_t *ent) -{ - G_FreeEntity( ent ); -} +void SP_misc_model_static(gentity_t *ent) { G_FreeEntity(ent); } /*QUAKED misc_model_breakable (1 0 0) (-16 -16 -16) (16 16 16) SOLID AUTOANIMATE DEADSOLID NO_DMODEL NO_SMOKE USE_MODEL USE_NOT_BREAK PLAYER_USE NO_EXPLOSION SOLID - Movement is blocked by it, if not set, can still be broken by explosions and shots if it has health @@ -315,15 +286,11 @@ PLAYER_USE - Player can use it with the use button NO_EXPLOSION - By default, will explode when it dies...this is your override. "model" arbitrary .md3 file to display -"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block NPCs or players from moving -"targetname" when used, dies and displays damagemodel, if any (if not, removes itself) -"target" What to use when it dies -"target2" What to use when it's repaired -"target3" What to use when it's used while it's broken -"paintarget" target to fire when hit (but not destroyed) -"count" the amount of armor/health/ammo given (default 50) -"gravity" if set to 1, this will be affected by gravity -"radius" Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks +"health" how much health to have - default is zero (not breakable) If you don't set the SOLID flag, but give it health, it can be shot but will not block +NPCs or players from moving "targetname" when used, dies and displays damagemodel, if any (if not, removes itself) "target" What to use when it dies "target2" +What to use when it's repaired "target3" What to use when it's used while it's broken "paintarget" target to fire when hit (but not destroyed) "count" the +amount of armor/health/ammo given (default 50) "gravity" if set to 1, this will be affected by gravity "radius" Chunk code tries to pick a good volume of +chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks Damage: default is none "splashDamage" - damage to do (will make it explode on death) @@ -356,116 +323,97 @@ set size better? multiple damage models? custom explosion effect/sound? */ -void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ); -void misc_model_breakable_init( gentity_t *ent ); +void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor); +void misc_model_breakable_init(gentity_t *ent); -void SP_misc_model_breakable( gentity_t *ent ) -{ +void SP_misc_model_breakable(gentity_t *ent) { float grav; - G_SpawnInt( "material", "8", (int*)&ent->material ); - G_SpawnFloat( "radius", "1", &ent->radius ); // used to scale chunk code if desired by a designer + G_SpawnInt("material", "8", (int *)&ent->material); + G_SpawnFloat("radius", "1", &ent->radius); // used to scale chunk code if desired by a designer - misc_model_breakable_init( ent ); + misc_model_breakable_init(ent); - if ( !ent->r.mins[0] && !ent->r.mins[1] && !ent->r.mins[2] ) - { - VectorSet (ent->r.mins, -16, -16, -16); + if (!ent->r.mins[0] && !ent->r.mins[1] && !ent->r.mins[2]) { + VectorSet(ent->r.mins, -16, -16, -16); } - if ( !ent->r.maxs[0] && !ent->r.maxs[1] && !ent->r.maxs[2] ) - { - VectorSet (ent->r.maxs, 16, 16, 16); + if (!ent->r.maxs[0] && !ent->r.maxs[1] && !ent->r.maxs[2]) { + VectorSet(ent->r.maxs, 16, 16, 16); } - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); - trap->LinkEntity ((sharedEntity_t *)ent); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); + trap->LinkEntity((sharedEntity_t *)ent); - if ( ent->spawnflags & 128 ) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->r.svFlags |= SVF_PLAYER_USABLE; } ent->s.teamowner = 0; - G_SpawnFloat( "gravity", "0", &grav ); - if ( grav ) - {//affected by gravity - G_SetAngles( ent, ent->s.angles ); - G_SetOrigin( ent, ent->r.currentOrigin ); - misc_model_breakable_gravity_init( ent, qtrue ); + G_SpawnFloat("gravity", "0", &grav); + if (grav) { // affected by gravity + G_SetAngles(ent, ent->s.angles); + G_SetOrigin(ent, ent->r.currentOrigin); + misc_model_breakable_gravity_init(ent, qtrue); } } -void misc_model_breakable_gravity_init( gentity_t *ent, qboolean dropToFloor ) -{ - trace_t tr; - vec3_t top, bottom; +void misc_model_breakable_gravity_init(gentity_t *ent, qboolean dropToFloor) { + trace_t tr; + vec3_t top, bottom; ent->s.eType = ET_GENERAL; - //ent->s.eFlags |= EF_BOUNCE_HALF; // FIXME - ent->clipmask = MASK_SOLID|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//? - ent->physicsBounce = ent->mass = VectorLength( ent->r.maxs ) + VectorLength( ent->r.mins ); + // ent->s.eFlags |= EF_BOUNCE_HALF; // FIXME + ent->clipmask = MASK_SOLID | CONTENTS_BODY | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP; //? + ent->physicsBounce = ent->mass = VectorLength(ent->r.maxs) + VectorLength(ent->r.mins); - //drop to floor + // drop to floor - if ( dropToFloor ) - { - VectorCopy( ent->r.currentOrigin, top ); + if (dropToFloor) { + VectorCopy(ent->r.currentOrigin, top); top[2] += 1; - VectorCopy( ent->r.currentOrigin, bottom ); + VectorCopy(ent->r.currentOrigin, bottom); bottom[2] = MIN_WORLD_COORD; - trap->Trace( &tr, top, ent->r.mins, ent->r.maxs, bottom, ent->s.number, MASK_NPCSOLID, qfalse, 0, 0 ); - if ( !tr.allsolid && !tr.startsolid && tr.fraction < 1.0 ) - { - G_SetOrigin( ent, tr.endpos ); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->Trace(&tr, top, ent->r.mins, ent->r.maxs, bottom, ent->s.number, MASK_NPCSOLID, qfalse, 0, 0); + if (!tr.allsolid && !tr.startsolid && tr.fraction < 1.0) { + G_SetOrigin(ent, tr.endpos); + trap->LinkEntity((sharedEntity_t *)ent); } + } else { + G_SetOrigin(ent, ent->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)ent); } - else - { - G_SetOrigin( ent, ent->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)ent ); - } - //set up for object thinking - if ( VectorCompare( ent->s.pos.trDelta, vec3_origin ) ) - {//not moving + // set up for object thinking + if (VectorCompare(ent->s.pos.trDelta, vec3_origin)) { // not moving ent->s.pos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.pos.trType = TR_GRAVITY; } - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; - if ( VectorCompare( ent->s.apos.trDelta, vec3_origin ) ) - {//not moving + if (VectorCompare(ent->s.apos.trDelta, vec3_origin)) { // not moving ent->s.apos.trType = TR_STATIONARY; - } - else - { + } else { ent->s.apos.trType = TR_LINEAR; } - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trTime = level.time; } -void misc_model_breakable_init( gentity_t *ent ) -{ +void misc_model_breakable_init(gentity_t *ent) { if (!ent->model) { - trap->Error( ERR_DROP, "no model set on %s at (%.1f %.1f %.1f)\n", ent->classname, ent->s.origin[0],ent->s.origin[1],ent->s.origin[2] ); + trap->Error(ERR_DROP, "no model set on %s at (%.1f %.1f %.1f)\n", ent->classname, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2]); } - //Main model - ent->s.modelindex = ent->sound2to1 = G_ModelIndex( ent->model ); + // Main model + ent->s.modelindex = ent->sound2to1 = G_ModelIndex(ent->model); - if ( ent->spawnflags & 1 ) - {//Blocks movement - ent->r.contents = CONTENTS_SOLID|CONTENTS_OPAQUE|CONTENTS_BODY|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP;//Was CONTENTS_SOLID, but only architecture should be this - } - else if ( ent->health ) - {//Can only be shot + if (ent->spawnflags & 1) { // Blocks movement + ent->r.contents = CONTENTS_SOLID | CONTENTS_OPAQUE | CONTENTS_BODY | CONTENTS_MONSTERCLIP | + CONTENTS_BOTCLIP; // Was CONTENTS_SOLID, but only architecture should be this + } else if (ent->health) { // Can only be shot ent->r.contents = CONTENTS_SHOTCLIP; } @@ -477,7 +425,7 @@ void misc_model_breakable_init( gentity_t *ent ) /*QUAKED misc_G2model (1 0 0) (-16 -16 -16) (16 16 16) "model" arbitrary .glm file to display */ -void SP_misc_G2model( gentity_t *ent ) { +void SP_misc_G2model(gentity_t *ent) { #if 0 char name1[200] = "models/players/kyle/modelmp.glm"; @@ -491,56 +439,55 @@ void SP_misc_G2model( gentity_t *ent ) { G_SetOrigin( ent, ent->s.origin ); VectorCopy( ent->s.angles, ent->s.apos.trBase ); #else - G_FreeEntity( ent ); + G_FreeEntity(ent); #endif } //=========================================================== -void locateCamera( gentity_t *ent ) { - vec3_t dir; - gentity_t *target; - gentity_t *owner; +void locateCamera(gentity_t *ent) { + vec3_t dir; + gentity_t *target; + gentity_t *owner; - owner = G_PickTarget( ent->target ); - if ( !owner ) { - trap->Print( "Couldn't find target for misc_partal_surface\n" ); - G_FreeEntity( ent ); + owner = G_PickTarget(ent->target); + if (!owner) { + trap->Print("Couldn't find target for misc_partal_surface\n"); + G_FreeEntity(ent); return; } ent->r.ownerNum = owner->s.number; // frame holds the rotate speed - if ( owner->spawnflags & 1 ) { + if (owner->spawnflags & 1) { ent->s.frame = 25; - } else if ( owner->spawnflags & 2 ) { + } else if (owner->spawnflags & 2) { ent->s.frame = 75; } // swing camera ? - if ( owner->spawnflags & 4 ) { + if (owner->spawnflags & 4) { // set to 0 for no rotation at all ent->s.powerups = 0; - } - else { + } else { ent->s.powerups = 1; } // clientNum holds the rotate offset ent->s.clientNum = owner->s.clientNum; - VectorCopy( owner->s.origin, ent->s.origin2 ); + VectorCopy(owner->s.origin, ent->s.origin2); // see if the portal_camera has a target - target = G_PickTarget( owner->target ); - if ( target ) { - VectorSubtract( target->s.origin, owner->s.origin, dir ); - VectorNormalize( dir ); + target = G_PickTarget(owner->target); + if (target) { + VectorSubtract(target->s.origin, owner->s.origin, dir); + VectorNormalize(dir); } else { - G_SetMovedir( owner->s.angles, dir ); + G_SetMovedir(owner->s.angles, dir); } - ent->s.eventParm = DirToByte( dir ); + ent->s.eventParm = DirToByte(dir); } /*QUAKED misc_portal_surface (0 0 1) (-8 -8 -8) (8 8 8) @@ -548,15 +495,15 @@ The portal surface nearest this entity will show a view from the targeted misc_p This must be within 64 world units of the surface! */ void SP_misc_portal_surface(gentity_t *ent) { - VectorClear( ent->r.mins ); - VectorClear( ent->r.maxs ); - trap->LinkEntity ((sharedEntity_t *)ent); + VectorClear(ent->r.mins); + VectorClear(ent->r.maxs); + trap->LinkEntity((sharedEntity_t *)ent); ent->r.svFlags = SVF_PORTAL; ent->s.eType = ET_PORTAL; - if ( !ent->target ) { - VectorCopy( ent->s.origin, ent->s.origin2 ); + if (!ent->target) { + VectorCopy(ent->s.origin, ent->s.origin2); } else { ent->think = locateCamera; ent->nextthink = level.time + 100; @@ -568,30 +515,28 @@ The target for a misc_portal_director. You can set either angles or target anot "roll" an angle modifier to orient the camera around the target vector; */ void SP_misc_portal_camera(gentity_t *ent) { - float roll; + float roll; - VectorClear( ent->r.mins ); - VectorClear( ent->r.maxs ); - trap->LinkEntity ((sharedEntity_t *)ent); + VectorClear(ent->r.mins); + VectorClear(ent->r.maxs); + trap->LinkEntity((sharedEntity_t *)ent); - G_SpawnFloat( "roll", "0", &roll ); + G_SpawnFloat("roll", "0", &roll); - ent->s.clientNum = roll/360.0 * 256; + ent->s.clientNum = roll / 360.0 * 256; } /*QUAKED misc_bsp (1 0 0) (-16 -16 -16) (16 16 16) "bspmodel" arbitrary .bsp file to display */ -void SP_misc_bsp(gentity_t *ent) -{ - char temp[MAX_QPATH]; - char *out; - float newAngle; - int tempint; - - G_SpawnFloat( "angle", "0", &newAngle ); - if (newAngle != 0.0) - { +void SP_misc_bsp(gentity_t *ent) { + char temp[MAX_QPATH]; + char *out; + float newAngle; + int tempint; + + G_SpawnFloat("angle", "0", &newAngle); + if (newAngle != 0.0) { ent->s.angles[1] = newAngle; } // don't support rotation any other way @@ -603,13 +548,13 @@ void SP_misc_bsp(gentity_t *ent) ent->s.eFlags = EF_PERMANENT; // Mainly for debugging - G_SpawnInt( "spacing", "0", &tempint); + G_SpawnInt("spacing", "0", &tempint); ent->s.time2 = tempint; - G_SpawnInt( "flatten", "0", &tempint); + G_SpawnInt("flatten", "0", &tempint); ent->s.time = tempint; Com_sprintf(temp, MAX_QPATH, "#%s", out); - trap->SetBrushModel( (sharedEntity_t *)ent, temp ); // SV_SetBrushModel -- sets mins and maxs + trap->SetBrushModel((sharedEntity_t *)ent, temp); // SV_SetBrushModel -- sets mins and maxs G_BSPIndex(temp); level.mNumBSPInstances++; @@ -617,7 +562,7 @@ void SP_misc_bsp(gentity_t *ent) VectorCopy(ent->s.origin, level.mOriginAdjust); level.mRotationAdjust = ent->s.angles[1]; level.mTargetAdjust = temp; - //level.hasBspInstances = qtrue; //rww - also not referenced anywhere. + // level.hasBspInstances = qtrue; //rww - also not referenced anywhere. level.mBSPInstanceDepth++; /* G_SpawnString("filter", "", &out); @@ -626,21 +571,21 @@ void SP_misc_bsp(gentity_t *ent) G_SpawnString("teamfilter", "", &out); strcpy(level.mTeamFilter, out); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - VectorCopy( ent->s.angles, ent->r.currentAngles ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + VectorCopy(ent->s.angles, ent->r.currentAngles); ent->s.eType = ET_MOVER; - trap->LinkEntity ((sharedEntity_t *)ent); + trap->LinkEntity((sharedEntity_t *)ent); trap->SetActiveSubBSP(ent->s.modelindex); G_SpawnEntitiesFromString(qtrue); trap->SetActiveSubBSP(-1); level.mBSPInstanceDepth--; - //level.mFilter[0] = level.mTeamFilter[0] = 0; + // level.mFilter[0] = level.mTeamFilter[0] = 0; level.mTeamFilter[0] = 0; /* @@ -675,37 +620,29 @@ densityMap - how dense the client models are packed */ void AddSpawnField(char *field, char *value); -#define MAX_INSTANCE_TYPES 16 -void SP_terrain(gentity_t *ent) -{ - G_FreeEntity (ent); -} - -//rww - Called by skyportal entities. This will check through entities and flag them -//as portal ents if they are in the same pvs as a skyportal entity and pass -//a direct point trace check between origins. I really wanted to use an eFlag for -//flagging portal entities, but too many entities like to reset their eFlags. -//Note that this was not part of the original wolf sky portal stuff. -void G_PortalifyEntities(gentity_t *ent) -{ +#define MAX_INSTANCE_TYPES 16 +void SP_terrain(gentity_t *ent) { G_FreeEntity(ent); } + +// rww - Called by skyportal entities. This will check through entities and flag them +// as portal ents if they are in the same pvs as a skyportal entity and pass +// a direct point trace check between origins. I really wanted to use an eFlag for +// flagging portal entities, but too many entities like to reset their eFlags. +// Note that this was not part of the original wolf sky portal stuff. +void G_PortalifyEntities(gentity_t *ent) { int i = 0; gentity_t *scan = NULL; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { scan = &g_entities[i]; - if (scan && scan->inuse && scan->s.number != ent->s.number && trap->InPVS(ent->s.origin, scan->r.currentOrigin)) - { + if (scan && scan->inuse && scan->s.number != ent->s.number && trap->InPVS(ent->s.origin, scan->r.currentOrigin)) { trace_t tr; trap->Trace(&tr, ent->s.origin, vec3_origin, vec3_origin, scan->r.currentOrigin, ent->s.number, CONTENTS_SOLID, qfalse, 0, 0); - if (tr.fraction == 1.0 || (tr.entityNum == scan->s.number && tr.entityNum != ENTITYNUM_NONE && tr.entityNum != ENTITYNUM_WORLD)) - { - if (!scan->client || scan->s.eType == ET_NPC) - { //making a client a portal entity would be bad. - scan->s.isPortalEnt = qtrue; //he's flagged now + if (tr.fraction == 1.0 || (tr.entityNum == scan->s.number && tr.entityNum != ENTITYNUM_NONE && tr.entityNum != ENTITYNUM_WORLD)) { + if (!scan->client || scan->s.eType == ET_NPC) { // making a client a portal entity would be bad. + scan->s.isPortalEnt = qtrue; // he's flagged now } } } @@ -713,7 +650,7 @@ void G_PortalifyEntities(gentity_t *ent) i++; } - ent->think = G_FreeEntity; //the portal entity is no longer needed because its information is stored in a config string. + ent->think = G_FreeEntity; // the portal entity is no longer needed because its information is stored in a config string. ent->nextthink = level.time; } @@ -723,11 +660,7 @@ to the regular view position. "modelscale" the scale at which to scale positions */ -void SP_misc_skyportal_orient (gentity_t *ent) -{ - G_FreeEntity(ent); -} - +void SP_misc_skyportal_orient(gentity_t *ent) { G_FreeEntity(ent); } /*QUAKED misc_skyportal (.6 .7 .7) (-8 -8 0) (8 8 16) "fov" for the skybox default is 80 @@ -742,27 +675,27 @@ is in the same PVS as them (only once otherwise, but still once no matter where the client is). In other words, don't go overboard with it or everything will explode. */ -void SP_misc_skyportal (gentity_t *ent) -{ - char *fov; - vec3_t fogv; //----(SA) - int fogn; //----(SA) - int fogf; //----(SA) - int isfog = 0; // (SA) +void SP_misc_skyportal(gentity_t *ent) { + char *fov; + vec3_t fogv; //----(SA) + int fogn; //----(SA) + int fogf; //----(SA) + int isfog = 0; // (SA) - float fov_x; + float fov_x; - G_SpawnString ("fov", "80", &fov); - fov_x = atof (fov); + G_SpawnString("fov", "80", &fov); + fov_x = atof(fov); - isfog += G_SpawnVector ("fogcolor", "0 0 0", fogv); - isfog += G_SpawnInt ("fognear", "0", &fogn); - isfog += G_SpawnInt ("fogfar", "300", &fogf); + isfog += G_SpawnVector("fogcolor", "0 0 0", fogv); + isfog += G_SpawnInt("fognear", "0", &fogn); + isfog += G_SpawnInt("fogfar", "300", &fogf); - trap->SetConfigstring( CS_SKYBOXORG, va("%.2f %.2f %.2f %.1f %i %.2f %.2f %.2f %i %i", ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], fov_x, (int)isfog, fogv[0], fogv[1], fogv[2], fogn, fogf ) ); + trap->SetConfigstring(CS_SKYBOXORG, va("%.2f %.2f %.2f %.1f %i %.2f %.2f %.2f %i %i", ent->s.origin[0], ent->s.origin[1], ent->s.origin[2], fov_x, + (int)isfog, fogv[0], fogv[1], fogv[2], fogn, fogf)); ent->think = G_PortalifyEntities; - ent->nextthink = level.time + 1050; //give it some time first so that all other entities are spawned. + ent->nextthink = level.time + 1050; // give it some time first so that all other entities are spawned. } /*QUAKED misc_holocron (0 0 1) (-8 -8 -8) (8 8 8) @@ -808,34 +741,23 @@ count Set to type of holocron (based on force power value) "models/chunks/rock/rock_big.md3"//FP_SABERTHROW };*/ -void HolocronRespawn(gentity_t *self) -{ - self->s.modelindex = (self->count - 128); -} +void HolocronRespawn(gentity_t *self) { self->s.modelindex = (self->count - 128); } -void HolocronPopOut(gentity_t *self) -{ - if (Q_irand(1, 10) < 5) - { +void HolocronPopOut(gentity_t *self) { + if (Q_irand(1, 10) < 5) { self->s.pos.trDelta[0] = 150 + Q_irand(1, 100); - } - else - { + } else { self->s.pos.trDelta[0] = -150 - Q_irand(1, 100); } - if (Q_irand(1, 10) < 5) - { + if (Q_irand(1, 10) < 5) { self->s.pos.trDelta[1] = 150 + Q_irand(1, 100); - } - else - { + } else { self->s.pos.trDelta[1] = -150 - Q_irand(1, 100); } self->s.pos.trDelta[2] = 150 + Q_irand(1, 100); } -void HolocronTouch(gentity_t *self, gentity_t *other, trace_t *trace) -{ +void HolocronTouch(gentity_t *self, gentity_t *other, trace_t *trace) { int i = 0; int othercarrying = 0; float time_lowest = 0; @@ -843,70 +765,57 @@ void HolocronTouch(gentity_t *self, gentity_t *other, trace_t *trace) int hasall = 1; int forceReselect = WP_NONE; - if (trace) - { + if (trace) { self->s.groundEntityNum = trace->entityNum; } - if (!other || !other->client || other->health < 1) - { + if (!other || !other->client || other->health < 1) { return; } - if (!self->s.modelindex) - { + if (!self->s.modelindex) { return; } - if (self->enemy) - { + if (self->enemy) { return; } - if (other->client->ps.holocronsCarried[self->count]) - { + if (other->client->ps.holocronsCarried[self->count]) { return; } - if (other->client->ps.holocronCantTouch == self->s.number && other->client->ps.holocronCantTouchTime > level.time) - { + if (other->client->ps.holocronCantTouch == self->s.number && other->client->ps.holocronCantTouchTime > level.time) { return; } - while (i < NUM_FORCE_POWERS) - { - if (other->client->ps.holocronsCarried[i]) - { + while (i < NUM_FORCE_POWERS) { + if (other->client->ps.holocronsCarried[i]) { othercarrying++; - if (index_lowest == -1 || other->client->ps.holocronsCarried[i] < time_lowest) - { + if (index_lowest == -1 || other->client->ps.holocronsCarried[i] < time_lowest) { index_lowest = i; time_lowest = other->client->ps.holocronsCarried[i]; } - } - else if (i != self->count) - { + } else if (i != self->count) { hasall = 0; } i++; } - if (hasall) - { //once we pick up this holocron we'll have all of them, so give us super special best prize! - //trap->Print("You deserve a pat on the back.\n"); + if (hasall) { // once we pick up this holocron we'll have all of them, so give us super special best prize! + // trap->Print("You deserve a pat on the back.\n"); } - if (!(other->client->ps.fd.forcePowersActive & (1 << other->client->ps.fd.forcePowerSelected))) - { //If the player isn't using his currently selected force power, select this one - if (self->count != FP_SABER_OFFENSE && self->count != FP_SABER_DEFENSE && self->count != FP_SABERTHROW && self->count != FP_LEVITATION) - { + if (!(other->client->ps.fd.forcePowersActive & + (1 << other->client->ps.fd.forcePowerSelected))) { // If the player isn't using his currently selected force power, select this one + if (self->count != FP_SABER_OFFENSE && self->count != FP_SABER_DEFENSE && self->count != FP_SABERTHROW && self->count != FP_LEVITATION) { other->client->ps.fd.forcePowerSelected = self->count; } } - if (g_maxHolocronCarry.integer && othercarrying >= g_maxHolocronCarry.integer) - { //make the oldest holocron carried by the player pop out to make room for this one + if (g_maxHolocronCarry.integer && + othercarrying >= g_maxHolocronCarry.integer) { // make the oldest holocron carried by the player pop out to make room for this one other->client->ps.holocronsCarried[index_lowest] = 0; /* @@ -921,11 +830,11 @@ void HolocronTouch(gentity_t *self, gentity_t *other, trace_t *trace) } } */ - //NOTE: No longer valid as we are now always giving a force level 1 saber attack level in holocron + // NOTE: No longer valid as we are now always giving a force level 1 saber attack level in holocron } - //G_Sound(other, CHAN_AUTO, G_SoundIndex("sound/weapons/w_pkup.wav")); - G_AddEvent( other, EV_ITEM_PICKUP, self->s.number ); + // G_Sound(other, CHAN_AUTO, G_SoundIndex("sound/weapons/w_pkup.wav")); + G_AddEvent(other, EV_ITEM_PICKUP, self->s.number); other->client->ps.holocronsCarried[self->count] = level.time; self->s.modelindex = 0; @@ -947,41 +856,33 @@ void HolocronTouch(gentity_t *self, gentity_t *other, trace_t *trace) } */ - if (forceReselect != WP_NONE) - { + if (forceReselect != WP_NONE) { G_AddEvent(other, EV_NOAMMO, forceReselect); } - //trap->Print("DON'T TOUCH ME\n"); + // trap->Print("DON'T TOUCH ME\n"); } -void HolocronThink(gentity_t *ent) -{ - if (ent->pos2[0] && (!ent->enemy || !ent->enemy->client || ent->enemy->health < 1)) - { - if (ent->enemy && ent->enemy->client) - { +void HolocronThink(gentity_t *ent) { + if (ent->pos2[0] && (!ent->enemy || !ent->enemy->client || ent->enemy->health < 1)) { + if (ent->enemy && ent->enemy->client) { HolocronRespawn(ent); VectorCopy(ent->enemy->client->ps.origin, ent->s.pos.trBase); VectorCopy(ent->enemy->client->ps.origin, ent->s.origin); VectorCopy(ent->enemy->client->ps.origin, ent->r.currentOrigin); - //copy to person carrying's origin before popping out of them + // copy to person carrying's origin before popping out of them HolocronPopOut(ent); ent->enemy->client->ps.holocronsCarried[ent->count] = 0; ent->enemy = NULL; goto justthink; } - } - else if (ent->pos2[0] && ent->enemy && ent->enemy->client) - { + } else if (ent->pos2[0] && ent->enemy && ent->enemy->client) { ent->pos2[1] = level.time + HOLOCRON_RESPAWN_TIME; } - if (ent->enemy && ent->enemy->client) - { - if (!ent->enemy->client->ps.holocronsCarried[ent->count]) - { + if (ent->enemy && ent->enemy->client) { + if (!ent->enemy->client->ps.holocronsCarried[ent->count]) { ent->enemy->client->ps.holocronCantTouch = ent->s.number; ent->enemy->client->ps.holocronCantTouchTime = level.time + 5000; @@ -989,17 +890,15 @@ void HolocronThink(gentity_t *ent) VectorCopy(ent->enemy->client->ps.origin, ent->s.pos.trBase); VectorCopy(ent->enemy->client->ps.origin, ent->s.origin); VectorCopy(ent->enemy->client->ps.origin, ent->r.currentOrigin); - //copy to person carrying's origin before popping out of them + // copy to person carrying's origin before popping out of them HolocronPopOut(ent); ent->enemy = NULL; goto justthink; } - if (!ent->enemy->inuse || (ent->enemy->client && ent->enemy->client->ps.fallingToDeath)) - { - if (ent->enemy->inuse && ent->enemy->client) - { + if (!ent->enemy->inuse || (ent->enemy->client && ent->enemy->client->ps.fallingToDeath)) { + if (ent->enemy->inuse && ent->enemy->client) { ent->enemy->client->ps.holocronBits &= ~(1 << ent->count); ent->enemy->client->ps.holocronsCarried[ent->count] = 0; } @@ -1019,8 +918,8 @@ void HolocronThink(gentity_t *ent) } } - if (ent->pos2[0] && ent->pos2[1] < level.time) - { //isn't in original place and has been there for (HOLOCRON_RESPAWN_TIME) seconds without being picked up, so respawn + if (ent->pos2[0] && + ent->pos2[1] < level.time) { // isn't in original place and has been there for (HOLOCRON_RESPAWN_TIME) seconds without being picked up, so respawn VectorCopy(ent->s.origin2, ent->s.pos.trBase); VectorCopy(ent->s.origin2, ent->s.origin); VectorCopy(ent->s.origin2, ent->r.currentOrigin); @@ -1035,29 +934,23 @@ void HolocronThink(gentity_t *ent) justthink: ent->nextthink = level.time + 50; - if (ent->s.pos.trDelta[0] || ent->s.pos.trDelta[1] || ent->s.pos.trDelta[2]) - { + if (ent->s.pos.trDelta[0] || ent->s.pos.trDelta[1] || ent->s.pos.trDelta[2]) { G_RunObject(ent); } } -void SP_misc_holocron(gentity_t *ent) -{ +void SP_misc_holocron(gentity_t *ent) { vec3_t dest; trace_t tr; - if (level.gametype != GT_HOLOCRON) - { + if (level.gametype != GT_HOLOCRON) { G_FreeEntity(ent); return; } - if (HasSetSaberOnly()) - { - if (ent->count == FP_SABER_OFFENSE || - ent->count == FP_SABER_DEFENSE || - ent->count == FP_SABERTHROW) - { //having saber holocrons in saber only mode is pointless + if (HasSetSaberOnly()) { + if (ent->count == FP_SABER_OFFENSE || ent->count == FP_SABER_DEFENSE || + ent->count == FP_SABERTHROW) { // having saber holocrons in saber only mode is pointless G_FreeEntity(ent); return; } @@ -1065,54 +958,51 @@ void SP_misc_holocron(gentity_t *ent) ent->s.isJediMaster = qtrue; - VectorSet( ent->r.maxs, 8, 8, 8 ); - VectorSet( ent->r.mins, -8, -8, -8 ); + VectorSet(ent->r.maxs, 8, 8, 8); + VectorSet(ent->r.mins, -8, -8, -8); ent->s.origin[2] += 0.1f; ent->r.maxs[2] -= 0.1f; - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 ); - trap->Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0 ); - if ( tr.startsolid ) - { - trap->Print ("SP_misc_holocron: misc_holocron startsolid at %s\n", vtos(ent->s.origin)); - G_FreeEntity( ent ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096); + trap->Trace(&tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0); + if (tr.startsolid) { + trap->Print("SP_misc_holocron: misc_holocron startsolid at %s\n", vtos(ent->s.origin)); + G_FreeEntity(ent); return; } - //add the 0.1 back after the trace + // add the 0.1 back after the trace ent->r.maxs[2] += 0.1f; // allow to ride movers -// ent->s.groundEntityNum = tr.entityNum; + // ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); - if (ent->count < 0) - { + if (ent->count < 0) { ent->count = 0; } - if (ent->count >= NUM_FORCE_POWERS) - { - ent->count = NUM_FORCE_POWERS-1; + if (ent->count >= NUM_FORCE_POWERS) { + ent->count = NUM_FORCE_POWERS - 1; } -/* - if (g_forcePowerDisable.integer && - (g_forcePowerDisable.integer & (1 << ent->count))) - { - G_FreeEntity(ent); - return; - } -*/ - //No longer doing this, causing too many complaints about accidentally setting no force powers at all - //and starting a holocron game (making it basically just FFA) + /* + if (g_forcePowerDisable.integer && + (g_forcePowerDisable.integer & (1 << ent->count))) + { + G_FreeEntity(ent); + return; + } + */ + // No longer doing this, causing too many complaints about accidentally setting no force powers at all + // and starting a holocron game (making it basically just FFA) ent->enemy = NULL; ent->flags = FL_BOUNCE_HALF; - ent->s.modelindex = (ent->count - 128);//G_ModelIndex(holocronTypeModels[ent->count]); + ent->s.modelindex = (ent->count - 128); // G_ModelIndex(holocronTypeModels[ent->count]); ent->s.eType = ET_HOLOCRON; ent->s.pos.trType = TR_GRAVITY; ent->s.pos.trTime = level.time; @@ -1122,22 +1012,17 @@ void SP_misc_holocron(gentity_t *ent) ent->s.trickedentindex4 = ent->count; - if (forcePowerDarkLight[ent->count] == FORCE_DARKSIDE) - { + if (forcePowerDarkLight[ent->count] == FORCE_DARKSIDE) { ent->s.trickedentindex3 = 1; - } - else if (forcePowerDarkLight[ent->count] == FORCE_LIGHTSIDE) - { + } else if (forcePowerDarkLight[ent->count] == FORCE_LIGHTSIDE) { ent->s.trickedentindex3 = 2; - } - else - { + } else { ent->s.trickedentindex3 = 3; } ent->physicsObject = qtrue; - VectorCopy(ent->s.pos.trBase, ent->s.origin2); //remember the spawn spot + VectorCopy(ent->s.pos.trBase, ent->s.origin2); // remember the spawn spot ent->touch = HolocronTouch; @@ -1155,84 +1040,75 @@ void SP_misc_holocron(gentity_t *ent) ====================================================================== */ -void Use_Shooter( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - vec3_t dir; - float deg; - vec3_t up, right; +void Use_Shooter(gentity_t *ent, gentity_t *other, gentity_t *activator) { + vec3_t dir; + float deg; + vec3_t up, right; // see if we have a target - if ( ent->enemy ) { - VectorSubtract( ent->enemy->r.currentOrigin, ent->s.origin, dir ); - VectorNormalize( dir ); + if (ent->enemy) { + VectorSubtract(ent->enemy->r.currentOrigin, ent->s.origin, dir); + VectorNormalize(dir); } else { - VectorCopy( ent->movedir, dir ); + VectorCopy(ent->movedir, dir); } // randomize a bit - PerpendicularVector( up, dir ); - CrossProduct( up, dir, right ); + PerpendicularVector(up, dir); + CrossProduct(up, dir, right); deg = Q_flrand(-1.0f, 1.0f) * ent->random; - VectorMA( dir, deg, up, dir ); + VectorMA(dir, deg, up, dir); deg = Q_flrand(-1.0f, 1.0f) * ent->random; - VectorMA( dir, deg, right, dir ); + VectorMA(dir, deg, right, dir); - VectorNormalize( dir ); + VectorNormalize(dir); - switch ( ent->s.weapon ) { + switch (ent->s.weapon) { case WP_BLASTER: - WP_FireBlasterMissile( ent, ent->s.origin, dir, qfalse ); + WP_FireBlasterMissile(ent, ent->s.origin, dir, qfalse); break; } - G_AddEvent( ent, EV_FIRE_WEAPON, 0 ); + G_AddEvent(ent, EV_FIRE_WEAPON, 0); } - -static void InitShooter_Finish( gentity_t *ent ) { - ent->enemy = G_PickTarget( ent->target ); +static void InitShooter_Finish(gentity_t *ent) { + ent->enemy = G_PickTarget(ent->target); ent->think = 0; ent->nextthink = 0; } -void InitShooter( gentity_t *ent, int weapon ) { +void InitShooter(gentity_t *ent, int weapon) { ent->use = Use_Shooter; ent->s.weapon = weapon; - RegisterItem( BG_FindItemForWeapon( weapon ) ); + RegisterItem(BG_FindItemForWeapon(weapon)); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); - if ( !ent->random ) { + if (!ent->random) { ent->random = 1.0; } - ent->random = sin( M_PI * ent->random / 180 ); + ent->random = sin(M_PI * ent->random / 180); // target might be a moving object, so we can't set movedir for it - if ( ent->target ) { + if (ent->target) { ent->think = InitShooter_Finish; ent->nextthink = level.time + 500; } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /*QUAKED shooter_blaster (1 0 0) (-16 -16 -16) (16 16 16) Fires at either the target or the current direction. "random" is the number of degrees of deviance from the taget. (1.0 default) */ -void SP_shooter_blaster( gentity_t *ent ) { - InitShooter( ent, WP_BLASTER); -} +void SP_shooter_blaster(gentity_t *ent) { InitShooter(ent, WP_BLASTER); } -void check_recharge(gentity_t *ent) -{ - if (ent->fly_sound_debounce_time < level.time || - !ent->activator || - !ent->activator->client || - !(ent->activator->client->pers.cmd.buttons & BUTTON_USE)) - { - if (ent->activator) - { +void check_recharge(gentity_t *ent) { + if (ent->fly_sound_debounce_time < level.time || !ent->activator || !ent->activator->client || !(ent->activator->client->pers.cmd.buttons & BUTTON_USE)) { + if (ent->activator) { G_Sound(ent, CHAN_AUTO, ent->genericValue7); } ent->s.loopSound = 0; @@ -1241,18 +1117,15 @@ void check_recharge(gentity_t *ent) ent->fly_sound_debounce_time = 0; } - if (!ent->activator) - { //don't recharge during use - if (ent->genericValue8 < level.time) - { - if (ent->count < ent->genericValue4) - { + if (!ent->activator) { // don't recharge during use + if (ent->genericValue8 < level.time) { + if (ent->count < ent->genericValue4) { ent->count++; } ent->genericValue8 = level.time + ent->genericValue5; } } - ent->s.health = ent->count; //the "health bar" is gonna be how full we are + ent->s.health = ent->count; // the "health bar" is gonna be how full we are ent->nextthink = level.time; } @@ -1261,14 +1134,12 @@ void check_recharge(gentity_t *ent) EnergyShieldStationSettings ================ */ -void EnergyShieldStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "200", &ent->count ); +void EnergyShieldStationSettings(gentity_t *ent) { + G_SpawnInt("count", "200", &ent->count); G_SpawnInt("chargerate", "0", &ent->genericValue5); - if (!ent->genericValue5) - { + if (!ent->genericValue5) { ent->genericValue5 = STATION_RECHARGE_TIME; } } @@ -1278,73 +1149,52 @@ void EnergyShieldStationSettings(gentity_t *ent) shield_power_converter_use ================ */ -void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int dif,add; +void shield_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int dif, add; int stop = 1; - if (!activator || !activator->client) - { + if (!activator || !activator->client) { return; } - if ( level.gametype == GT_SIEGE - && other - && other->client - && other->client->siegeClass ) - { - if ( !bgSiegeClasses[other->client->siegeClass].maxarmor ) - {//can't use it! + if (level.gametype == GT_SIEGE && other && other->client && other->client->siegeClass) { + if (!bgSiegeClasses[other->client->siegeClass].maxarmor) { // can't use it! G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/interface/shieldcon_empty")); return; } } - if (self->setTime < level.time) - { - int maxArmor; - if (!self->s.loopSound) - { + if (self->setTime < level.time) { + int maxArmor; + if (!self->s.loopSound) { self->s.loopSound = G_SoundIndex("sound/interface/shieldcon_run"); self->s.loopIsSoundset = qfalse; } self->setTime = level.time + 100; - if ( level.gametype == GT_SIEGE - && other - && other->client - && other->client->siegeClass != -1 ) - { + if (level.gametype == GT_SIEGE && other && other->client && other->client->siegeClass != -1) { maxArmor = bgSiegeClasses[other->client->siegeClass].maxarmor; - } - else - { + } else { maxArmor = activator->client->ps.stats[STAT_MAX_HEALTH]; } dif = maxArmor - activator->client->ps.stats[STAT_ARMOR]; - if (dif > 0) // Already at full armor? + if (dif > 0) // Already at full armor? { - if (dif >MAX_AMMO_GIVE) - { + if (dif > MAX_AMMO_GIVE) { add = MAX_AMMO_GIVE; - } - else - { + } else { add = dif; } - if (self->countcount < add) { add = self->count; } - if (!self->genericValue12) - { + if (!self->genericValue12) { self->count -= add; } - if (self->count <= 0) - { + if (self->count <= 0) { self->setTime = 0; } stop = 0; @@ -1356,42 +1206,33 @@ void shield_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *a } } - if (stop || self->count <= 0) - { - if (self->s.loopSound && self->setTime < level.time) - { - if (self->count <= 0) - { + if (stop || self->count <= 0) { + if (self->s.loopSound && self->setTime < level.time) { + if (self->count <= 0) { G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/interface/shieldcon_empty")); - } - else - { + } else { G_Sound(self, CHAN_AUTO, self->genericValue7); } } self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; - if (self->setTime < level.time) - { - self->setTime = level.time + self->genericValue5+100; + if (self->setTime < level.time) { + self->setTime = level.time + self->genericValue5 + 100; } } } -//dispense generic ammo -void ammo_generic_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ +// dispense generic ammo +void ammo_generic_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { int /*dif,*/ add; - //int ammoType; + // int ammoType; int stop = 1; - if (!activator || !activator->client) - { + if (!activator || !activator->client) { return; } - if (self->setTime < level.time) - { + if (self->setTime < level.time) { qboolean gaveSome = qfalse; /* while (i < 3) @@ -1463,68 +1304,49 @@ void ammo_generic_power_converter_use( gentity_t *self, gentity_t *other, gentit } */ int i = AMMO_BLASTER; - if (!self->s.loopSound) - { + if (!self->s.loopSound) { self->s.loopSound = G_SoundIndex("sound/interface/ammocon_run"); self->s.loopIsSoundset = qfalse; } - //self->setTime = level.time + 100; + // self->setTime = level.time + 100; self->fly_sound_debounce_time = level.time + 500; self->activator = activator; - while (i < AMMO_MAX) - { - add = ammoData[i].max*0.05; - if (add < 1) - { + while (i < AMMO_MAX) { + add = ammoData[i].max * 0.05; + if (add < 1) { add = 1; } - if ( ( (activator->client->ps.eFlags & EF_DOUBLE_AMMO) && (activator->client->ps.ammo[i] < ammoData[i].max*2)) || - ( activator->client->ps.ammo[i] < ammoData[i].max ) ) - { + if (((activator->client->ps.eFlags & EF_DOUBLE_AMMO) && (activator->client->ps.ammo[i] < ammoData[i].max * 2)) || + (activator->client->ps.ammo[i] < ammoData[i].max)) { gaveSome = qtrue; - if ( level.gametype == GT_SIEGE && i == AMMO_ROCKETS && activator->client->ps.ammo[i] >= 10 ) - { //this stuff is already a freaking mess, so.. + if (level.gametype == GT_SIEGE && i == AMMO_ROCKETS && activator->client->ps.ammo[i] >= 10) { // this stuff is already a freaking mess, so.. gaveSome = qfalse; } activator->client->ps.ammo[i] += add; - if ( level.gametype == GT_SIEGE && i == AMMO_ROCKETS && activator->client->ps.ammo[i] >= 10 ) - { // fixme - this should SERIOUSLY be externed. + if (level.gametype == GT_SIEGE && i == AMMO_ROCKETS && activator->client->ps.ammo[i] >= 10) { // fixme - this should SERIOUSLY be externed. activator->client->ps.ammo[i] = 10; - } - else if ( activator->client->ps.eFlags & EF_DOUBLE_AMMO ) - { - if (activator->client->ps.ammo[i] >= ammoData[i].max * 2) - { // yuck. + } else if (activator->client->ps.eFlags & EF_DOUBLE_AMMO) { + if (activator->client->ps.ammo[i] >= ammoData[i].max * 2) { // yuck. activator->client->ps.ammo[i] = ammoData[i].max * 2; - } - else - { + } else { stop = 0; } - } - else - { - if (activator->client->ps.ammo[i] >= ammoData[i].max) - { + } else { + if (activator->client->ps.ammo[i] >= ammoData[i].max) { activator->client->ps.ammo[i] = ammoData[i].max; - } - else - { + } else { stop = 0; } } } i++; - if (!self->genericValue12 && gaveSome) - { - int sub = (add*0.2); - if (sub < 1) - { + if (!self->genericValue12 && gaveSome) { + int sub = (add * 0.2); + if (sub < 1) { sub = 1; } self->count -= sub; - if (self->count <= 0) - { + if (self->count <= 0) { self->count = 0; stop = 1; break; @@ -1533,24 +1355,18 @@ void ammo_generic_power_converter_use( gentity_t *self, gentity_t *other, gentit } } - if (stop || self->count <= 0) - { - if (self->s.loopSound && self->setTime < level.time) - { - if (self->count <= 0) - { + if (stop || self->count <= 0) { + if (self->s.loopSound && self->setTime < level.time) { + if (self->count <= 0) { G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/interface/ammocon_empty")); - } - else - { + } else { G_Sound(self, CHAN_AUTO, self->genericValue7); } } self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; - if (self->setTime < level.time) - { - self->setTime = level.time + self->genericValue5+100; + if (self->setTime < level.time) { + self->setTime = level.time + self->genericValue5 + 100; } } } @@ -1563,45 +1379,41 @@ Gives generic ammo when used "chargerate" - rechage 1 point every this many milliseconds (default 2000) "nodrain" - don't drain power from station if 1 */ -void SP_misc_ammo_floor_unit(gentity_t *ent) -{ +void SP_misc_ammo_floor_unit(gentity_t *ent) { vec3_t dest; trace_t tr; - VectorSet( ent->r.mins, -16, -16, 0 ); - VectorSet( ent->r.maxs, 16, 16, 40 ); + VectorSet(ent->r.mins, -16, -16, 0); + VectorSet(ent->r.maxs, 16, 16, 40); ent->s.origin[2] += 0.1f; ent->r.maxs[2] -= 0.1f; - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 ); - trap->Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0 ); - if ( tr.startsolid ) - { - trap->Print ("SP_misc_ammo_floor_unit: misc_ammo_floor_unit startsolid at %s\n", vtos(ent->s.origin)); - G_FreeEntity( ent ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096); + trap->Trace(&tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0); + if (tr.startsolid) { + trap->Print("SP_misc_ammo_floor_unit: misc_ammo_floor_unit startsolid at %s\n", vtos(ent->s.origin)); + G_FreeEntity(ent); return; } - //add the 0.1 back after the trace + // add the 0.1 back after the trace ent->r.maxs[2] += 0.1f; // allow to ride movers ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); - if (!ent->health) - { + if (!ent->health) { ent->health = 60; } - if (!ent->model || !ent->model[0]) - { + if (!ent->model || !ent->model[0]) { ent->model = "/models/items/a_pwr_converter.md3"; } - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); ent->s.eFlags = 0; ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -1610,32 +1422,30 @@ void SP_misc_ammo_floor_unit(gentity_t *ent) EnergyShieldStationSettings(ent); - ent->genericValue4 = ent->count; //initial value + ent->genericValue4 = ent->count; // initial value ent->think = check_recharge; G_SpawnInt("nodrain", "0", &ent->genericValue12); - if (!ent->genericValue12) - { + if (!ent->genericValue12) { ent->s.maxhealth = ent->s.health = ent->count; } ent->s.shouldtarget = qtrue; ent->s.teamowner = 0; ent->s.owner = ENTITYNUM_NONE; - ent->nextthink = level.time + 200;// + STATION_RECHARGE_TIME; + ent->nextthink = level.time + 200; // + STATION_RECHARGE_TIME; ent->use = ammo_generic_power_converter_use; - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); G_SoundIndex("sound/interface/ammocon_run"); ent->genericValue7 = G_SoundIndex("sound/interface/ammocon_done"); G_SoundIndex("sound/interface/ammocon_empty"); - if (level.gametype == GT_SIEGE) - { //show on radar from everywhere + if (level.gametype == GT_SIEGE) { // show on radar from everywhere ent->r.svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_RADAROBJECT; ent->s.genericenemyindex = G_IconIndex("gfx/mp/siegeicons/desert/weapon_recharge"); @@ -1650,53 +1460,46 @@ Gives shield energy when used. "chargerate" - rechage 1 point every this many milliseconds (default 3000) "nodrain" - don't drain power from me */ -void SP_misc_shield_floor_unit( gentity_t *ent ) -{ +void SP_misc_shield_floor_unit(gentity_t *ent) { vec3_t dest; trace_t tr; - if (level.gametype != GT_CTF && - level.gametype != GT_CTY && - level.gametype != GT_SIEGE) - { - G_FreeEntity( ent ); + if (level.gametype != GT_CTF && level.gametype != GT_CTY && level.gametype != GT_SIEGE) { + G_FreeEntity(ent); return; } - VectorSet( ent->r.mins, -16, -16, 0 ); - VectorSet( ent->r.maxs, 16, 16, 40 ); + VectorSet(ent->r.mins, -16, -16, 0); + VectorSet(ent->r.maxs, 16, 16, 40); ent->s.origin[2] += 0.1f; ent->r.maxs[2] -= 0.1f; - VectorSet( dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096 ); - trap->Trace( &tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0 ); - if ( tr.startsolid ) - { - trap->Print ("SP_misc_shield_floor_unit: misc_shield_floor_unit startsolid at %s\n", vtos(ent->s.origin)); - G_FreeEntity( ent ); + VectorSet(dest, ent->s.origin[0], ent->s.origin[1], ent->s.origin[2] - 4096); + trap->Trace(&tr, ent->s.origin, ent->r.mins, ent->r.maxs, dest, ent->s.number, MASK_SOLID, qfalse, 0, 0); + if (tr.startsolid) { + trap->Print("SP_misc_shield_floor_unit: misc_shield_floor_unit startsolid at %s\n", vtos(ent->s.origin)); + G_FreeEntity(ent); return; } - //add the 0.1 back after the trace + // add the 0.1 back after the trace ent->r.maxs[2] += 0.1f; // allow to ride movers ent->s.groundEntityNum = tr.entityNum; - G_SetOrigin( ent, tr.endpos ); + G_SetOrigin(ent, tr.endpos); - if (!ent->health) - { + if (!ent->health) { ent->health = 60; } - if (!ent->model || !ent->model[0]) - { + if (!ent->model || !ent->model[0]) { ent->model = "/models/items/a_shield_converter.md3"; } - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); ent->s.eFlags = 0; ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -1705,39 +1508,36 @@ void SP_misc_shield_floor_unit( gentity_t *ent ) EnergyShieldStationSettings(ent); - ent->genericValue4 = ent->count; //initial value + ent->genericValue4 = ent->count; // initial value ent->think = check_recharge; G_SpawnInt("nodrain", "0", &ent->genericValue12); - if (!ent->genericValue12) - { + if (!ent->genericValue12) { ent->s.maxhealth = ent->s.health = ent->count; } ent->s.shouldtarget = qtrue; ent->s.teamowner = 0; ent->s.owner = ENTITYNUM_NONE; - ent->nextthink = level.time + 200;// + STATION_RECHARGE_TIME; + ent->nextthink = level.time + 200; // + STATION_RECHARGE_TIME; ent->use = shield_power_converter_use; - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); G_SoundIndex("sound/interface/shieldcon_run"); ent->genericValue7 = G_SoundIndex("sound/interface/shieldcon_done"); G_SoundIndex("sound/interface/shieldcon_empty"); - if (level.gametype == GT_SIEGE) - { //show on radar from everywhere + if (level.gametype == GT_SIEGE) { // show on radar from everywhere ent->r.svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_RADAROBJECT; ent->s.genericenemyindex = G_IconIndex("gfx/mp/siegeicons/desert/shield_recharge"); } } - /*QUAKED misc_model_shield_power_converter (1 0 0) (-16 -16 -16) (16 16 16) model="models/items/psd_big.md3" Gives shield energy when used. @@ -1745,17 +1545,15 @@ Gives shield energy when used. "count" - the amount of ammo given when used (default 200) */ //------------------------------------------------------------ -void SP_misc_model_shield_power_converter( gentity_t *ent ) -{ - if (!ent->health) - { +void SP_misc_model_shield_power_converter(gentity_t *ent) { + if (!ent->health) { ent->health = 60; } - VectorSet (ent->r.mins, -16, -16, -16); - VectorSet (ent->r.maxs, 16, 16, 16); + VectorSet(ent->r.mins, -16, -16, -16); + VectorSet(ent->r.maxs, 16, 16, 16); - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); ent->s.eFlags = 0; ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -1764,7 +1562,7 @@ void SP_misc_model_shield_power_converter( gentity_t *ent ) EnergyShieldStationSettings(ent); - ent->genericValue4 = ent->count; //initial value + ent->genericValue4 = ent->count; // initial value ent->think = check_recharge; ent->s.maxhealth = ent->s.health = ent->count; @@ -1772,77 +1570,64 @@ void SP_misc_model_shield_power_converter( gentity_t *ent ) ent->s.teamowner = 0; ent->s.owner = ENTITYNUM_NONE; - ent->nextthink = level.time + 200;// + STATION_RECHARGE_TIME; + ent->nextthink = level.time + 200; // + STATION_RECHARGE_TIME; ent->use = shield_power_converter_use; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); - //G_SoundIndex("sound/movers/objects/useshieldstation.wav"); + // G_SoundIndex("sound/movers/objects/useshieldstation.wav"); - ent->s.modelindex2 = G_ModelIndex("/models/items/psd_big.md3"); // Precache model + ent->s.modelindex2 = G_ModelIndex("/models/items/psd_big.md3"); // Precache model } - /* ================ EnergyAmmoShieldStationSettings ================ */ -void EnergyAmmoStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "200", &ent->count ); -} +void EnergyAmmoStationSettings(gentity_t *ent) { G_SpawnInt("count", "200", &ent->count); } /* ================ ammo_power_converter_use ================ */ -void ammo_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int add = 0.0f;//,highest; -// int difBlaster,difPowerCell,difMetalBolts; - int stop = 1; +void ammo_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int add = 0.0f; //,highest; + // int difBlaster,difPowerCell,difMetalBolts; + int stop = 1; - if (!activator || !activator->client) - { + if (!activator || !activator->client) { return; } - if (self->setTime < level.time) - { - if (!self->s.loopSound) - { + if (self->setTime < level.time) { + if (!self->s.loopSound) { self->s.loopSound = G_SoundIndex("sound/player/pickupshield.wav"); } self->setTime = level.time + 100; - if (self->count) // Has it got any power left? + if (self->count) // Has it got any power left? { int i = AMMO_BLASTER; - while (i < AMMO_MAX) - { - add = ammoData[i].max*0.1; - if (add < 1) - { + while (i < AMMO_MAX) { + add = ammoData[i].max * 0.1; + if (add < 1) { add = 1; } - if (activator->client->ps.ammo[i] < ammoData[i].max) - { + if (activator->client->ps.ammo[i] < ammoData[i].max) { activator->client->ps.ammo[i] += add; - if (activator->client->ps.ammo[i] > ammoData[i].max) - { + if (activator->client->ps.ammo[i] > ammoData[i].max) { activator->client->ps.ammo[i] = ammoData[i].max; } } i++; } - if (!self->genericValue12) - { + if (!self->genericValue12) { self->count -= add; } stop = 0; @@ -1893,14 +1678,12 @@ void ammo_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *act } } - if (stop) - { + if (stop) { self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; } } - /*QUAKED misc_model_ammo_power_converter (1 0 0) (-16 -16 -16) (16 16 16) model="models/items/power_converter.md3" Gives ammo energy when used. @@ -1909,17 +1692,15 @@ Gives ammo energy when used. "nodrain" - don't drain power from me */ //------------------------------------------------------------ -void SP_misc_model_ammo_power_converter( gentity_t *ent ) -{ - if (!ent->health) - { +void SP_misc_model_ammo_power_converter(gentity_t *ent) { + if (!ent->health) { ent->health = 60; } - VectorSet (ent->r.mins, -16, -16, -16); - VectorSet (ent->r.maxs, 16, 16, 16); + VectorSet(ent->r.mins, -16, -16, -16); + VectorSet(ent->r.maxs, 16, 16, 16); - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); ent->s.eFlags = 0; ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -1931,24 +1712,23 @@ void SP_misc_model_ammo_power_converter( gentity_t *ent ) EnergyAmmoStationSettings(ent); - ent->genericValue4 = ent->count; //initial value + ent->genericValue4 = ent->count; // initial value ent->think = check_recharge; - if (!ent->genericValue12) - { + if (!ent->genericValue12) { ent->s.maxhealth = ent->s.health = ent->count; } ent->s.shouldtarget = qtrue; ent->s.teamowner = 0; ent->s.owner = ENTITYNUM_NONE; - ent->nextthink = level.time + 200;// + STATION_RECHARGE_TIME; + ent->nextthink = level.time + 200; // + STATION_RECHARGE_TIME; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); - //G_SoundIndex("sound/movers/objects/useshieldstation.wav"); + // G_SoundIndex("sound/movers/objects/useshieldstation.wav"); } /* @@ -1956,53 +1736,42 @@ void SP_misc_model_ammo_power_converter( gentity_t *ent ) EnergyHealthStationSettings ================ */ -void EnergyHealthStationSettings(gentity_t *ent) -{ - G_SpawnInt( "count", "200", &ent->count ); -} +void EnergyHealthStationSettings(gentity_t *ent) { G_SpawnInt("count", "200", &ent->count); } /* ================ health_power_converter_use ================ */ -void health_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int dif,add; +void health_power_converter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int dif, add; int stop = 1; - if (!activator || !activator->client) - { + if (!activator || !activator->client) { return; } - if (self->setTime < level.time) - { - if (!self->s.loopSound) - { + if (self->setTime < level.time) { + if (!self->s.loopSound) { self->s.loopSound = G_SoundIndex("sound/player/pickuphealth.wav"); } self->setTime = level.time + 100; dif = activator->client->ps.stats[STAT_MAX_HEALTH] - activator->health; - if (dif > 0) // Already at full armor? + if (dif > 0) // Already at full armor? { - if (dif >/*MAX_AMMO_GIVE*/5) - { - add = 5;//MAX_AMMO_GIVE; - } - else - { + if (dif > /*MAX_AMMO_GIVE*/ 5) { + add = 5; // MAX_AMMO_GIVE; + } else { add = dif; } - if (self->countcount < add) { add = self->count; } - //self->count -= add; + // self->count -= add; stop = 0; self->fly_sound_debounce_time = level.time + 500; @@ -2012,14 +1781,12 @@ void health_power_converter_use( gentity_t *self, gentity_t *other, gentity_t *a } } - if (stop) - { + if (stop) { self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; } } - /*QUAKED misc_model_health_power_converter (1 0 0) (-16 -16 -16) (16 16 16) model="models/items/power_converter.md3" Gives ammo energy when used. @@ -2027,17 +1794,15 @@ Gives ammo energy when used. "count" - the amount of ammo given when used (default 200) */ //------------------------------------------------------------ -void SP_misc_model_health_power_converter( gentity_t *ent ) -{ - if (!ent->health) - { +void SP_misc_model_health_power_converter(gentity_t *ent) { + if (!ent->health) { ent->health = 60; } - VectorSet (ent->r.mins, -16, -16, -16); - VectorSet (ent->r.maxs, 16, 16, 16); + VectorSet(ent->r.mins, -16, -16, -16); + VectorSet(ent->r.maxs, 16, 16, 16); - ent->s.modelindex = G_ModelIndex( ent->model ); + ent->s.modelindex = G_ModelIndex(ent->model); ent->s.eFlags = 0; ent->r.svFlags |= SVF_PLAYER_USABLE; @@ -2048,33 +1813,32 @@ void SP_misc_model_health_power_converter( gentity_t *ent ) EnergyHealthStationSettings(ent); - ent->genericValue4 = ent->count; //initial value + ent->genericValue4 = ent->count; // initial value ent->think = check_recharge; - //ent->s.maxhealth = ent->s.health = ent->count; + // ent->s.maxhealth = ent->s.health = ent->count; ent->s.shouldtarget = qtrue; ent->s.teamowner = 0; ent->s.owner = ENTITYNUM_NONE; - ent->nextthink = level.time + 200;// + STATION_RECHARGE_TIME; + ent->nextthink = level.time + 200; // + STATION_RECHARGE_TIME; - G_SetOrigin( ent, ent->s.origin ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + G_SetOrigin(ent, ent->s.origin); + VectorCopy(ent->s.angles, ent->s.apos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); - //G_SoundIndex("sound/movers/objects/useshieldstation.wav"); + // G_SoundIndex("sound/movers/objects/useshieldstation.wav"); G_SoundIndex("sound/player/pickuphealth.wav"); ent->genericValue7 = G_SoundIndex("sound/interface/shieldcon_done"); - if (level.gametype == GT_SIEGE) - { //show on radar from everywhere + if (level.gametype == GT_SIEGE) { // show on radar from everywhere ent->r.svFlags |= SVF_BROADCAST; ent->s.eFlags |= EF_RADAROBJECT; ent->s.genericenemyindex = G_IconIndex("gfx/mp/siegeicons/desert/bacta"); } } -#if 0 //damage box stuff +#if 0 // damage box stuff void DmgBoxHit( gentity_t *self, gentity_t *other, trace_t *trace ) { return; @@ -2307,23 +2071,19 @@ Runs the specified effect, can also be targeted at an info_notnull to orient the */ #define FX_RUNNER_RESERVED 0x800000 #define FX_ENT_RADIUS 32 -extern int BMS_START; -extern int BMS_MID; -extern int BMS_END; +extern int BMS_START; +extern int BMS_MID; +extern int BMS_END; //---------------------------------------------------------- -void fx_runner_think( gentity_t *ent ) -{ - BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->r.currentOrigin ); - BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->r.currentAngles ); +void fx_runner_think(gentity_t *ent) { + BG_EvaluateTrajectory(&ent->s.pos, level.time, ent->r.currentOrigin); + BG_EvaluateTrajectory(&ent->s.apos, level.time, ent->r.currentAngles); // call the effect with the desired position and orientation - if (ent->s.isPortalEnt) - { -// G_AddEvent( ent, EV_PLAY_PORTAL_EFFECT_ID, ent->genericValue5 ); - } - else - { -// G_AddEvent( ent, EV_PLAY_EFFECT_ID, ent->genericValue5 ); + if (ent->s.isPortalEnt) { + // G_AddEvent( ent, EV_PLAY_PORTAL_EFFECT_ID, ent->genericValue5 ); + } else { + // G_AddEvent( ent, EV_PLAY_EFFECT_ID, ent->genericValue5 ); } // start the fx on the client (continuous) @@ -2334,96 +2094,81 @@ void fx_runner_think( gentity_t *ent ) ent->nextthink = level.time + ent->delay + Q_flrand(0.0f, 1.0f) * ent->random; - if ( ent->spawnflags & 4 ) // damage + if (ent->spawnflags & 4) // damage { - G_RadiusDamage( ent->r.currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, ent, MOD_UNKNOWN ); + G_RadiusDamage(ent->r.currentOrigin, ent, ent->splashDamage, ent->splashRadius, ent, ent, MOD_UNKNOWN); } - if ( ent->target2 && ent->target2[0] ) - { + if (ent->target2 && ent->target2[0]) { // let our target know that we have spawned an effect - G_UseTargets2( ent, ent, ent->target2 ); + G_UseTargets2(ent, ent, ent->target2); } - if ( !(ent->spawnflags & 2 ) && !ent->s.loopSound ) // NOT ONESHOT...this is an assy thing to do + if (!(ent->spawnflags & 2) && !ent->s.loopSound) // NOT ONESHOT...this is an assy thing to do { - if ( ent->soundSet && ent->soundSet[0] ) - { + if (ent->soundSet && ent->soundSet[0]) { ent->s.soundSetIndex = G_SoundSetIndex(ent->soundSet); ent->s.loopIsSoundset = qtrue; ent->s.loopSound = BMS_MID; } } - } //---------------------------------------------------------- -void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if (self->s.isPortalEnt) - { //rww - mark it as broadcast upon first use if it's within the area of a skyportal +void fx_runner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->s.isPortalEnt) { // rww - mark it as broadcast upon first use if it's within the area of a skyportal self->r.svFlags |= SVF_BROADCAST; } - if ( self->spawnflags & 2 ) // ONESHOT + if (self->spawnflags & 2) // ONESHOT { // call the effect with the desired position and orientation, as a safety thing, // make sure we aren't thinking at all. - int saveState = self->s.modelindex2 + 1; + int saveState = self->s.modelindex2 + 1; - fx_runner_think( self ); + fx_runner_think(self); self->nextthink = -1; // one shot indicator self->s.modelindex2 = saveState; - if (self->s.modelindex2 > FX_STATE_ONE_SHOT_LIMIT) - { + if (self->s.modelindex2 > FX_STATE_ONE_SHOT_LIMIT) { self->s.modelindex2 = FX_STATE_ONE_SHOT; } - if ( self->target2 ) - { + if (self->target2) { // let our target know that we have spawned an effect - G_UseTargets2( self, self, self->target2 ); + G_UseTargets2(self, self, self->target2); } - if ( self->soundSet && self->soundSet[0] ) - { + if (self->soundSet && self->soundSet[0]) { self->s.soundSetIndex = G_SoundSetIndex(self->soundSet); - G_AddEvent( self, EV_BMODEL_SOUND, BMS_START); + G_AddEvent(self, EV_BMODEL_SOUND, BMS_START); } - } - else - { + } else { // ensure we are working with the right think function self->think = fx_runner_think; // toggle our state - if ( self->nextthink == -1 ) - { + if (self->nextthink == -1) { // NOTE: we fire the effect immediately on use, the fx_runner_think func will set // up the nextthink time. - fx_runner_think( self ); + fx_runner_think(self); - if ( self->soundSet && self->soundSet[0] ) - { + if (self->soundSet && self->soundSet[0]) { self->s.soundSetIndex = G_SoundSetIndex(self->soundSet); - G_AddEvent( self, EV_BMODEL_SOUND, BMS_START); + G_AddEvent(self, EV_BMODEL_SOUND, BMS_START); self->s.loopSound = BMS_MID; self->s.loopIsSoundset = qtrue; } - } - else - { + } else { // turn off for now self->nextthink = -1; // turn off fx on client self->s.modelindex2 = FX_STATE_OFF; - if ( self->soundSet && self->soundSet[0] ) - { + if (self->soundSet && self->soundSet[0]) { self->s.soundSetIndex = G_SoundSetIndex(self->soundSet); - G_AddEvent( self, EV_BMODEL_SOUND, BMS_END ); + G_AddEvent(self, EV_BMODEL_SOUND, BMS_END); self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; } @@ -2432,57 +2177,47 @@ void fx_runner_use( gentity_t *self, gentity_t *other, gentity_t *activator ) } //---------------------------------------------------------- -void fx_runner_link( gentity_t *ent ) -{ - vec3_t dir; +void fx_runner_link(gentity_t *ent) { + vec3_t dir; - if ( ent->target && ent->target[0] ) - { + if (ent->target && ent->target[0]) { // try to use the target to override the orientation - gentity_t *target = NULL; + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target ); + target = G_Find(target, FOFS(targetname), ent->target); - if ( !target ) - { + if (!target) { // Bah, no good, dump a warning, but continue on and use the UP vector - Com_Printf( "fx_runner_link: target specified but not found: %s\n", ent->target ); - Com_Printf( " -assuming UP orientation.\n" ); - } - else - { + Com_Printf("fx_runner_link: target specified but not found: %s\n", ent->target); + Com_Printf(" -assuming UP orientation.\n"); + } else { // Our target is valid so let's override the default UP vector - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); } } // don't really do anything with this right now other than do a check to warn the designers if the target2 is bogus - if ( ent->target2 && ent->target2[0] ) - { - gentity_t *target = NULL; + if (ent->target2 && ent->target2[0]) { + gentity_t *target = NULL; - target = G_Find( target, FOFS(targetname), ent->target2 ); + target = G_Find(target, FOFS(targetname), ent->target2); - if ( !target ) - { + if (!target) { // Target2 is bogus, but we can still continue - Com_Printf( "fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2 ); + Com_Printf("fx_runner_link: target2 was specified but is not valid: %s\n", ent->target2); } } - G_SetAngles( ent, ent->s.angles ); + G_SetAngles(ent, ent->s.angles); - if ( ent->spawnflags & 1 || ent->spawnflags & 2 ) // STARTOFF || ONESHOT + if (ent->spawnflags & 1 || ent->spawnflags & 2) // STARTOFF || ONESHOT { // We won't even consider thinking until we are used ent->nextthink = -1; - } - else - { - if ( ent->soundSet && ent->soundSet[0] ) - { + } else { + if (ent->soundSet && ent->soundSet[0]) { ent->s.soundSetIndex = G_SoundSetIndex(ent->soundSet); ent->s.loopSound = BMS_MID; ent->s.loopIsSoundset = qtrue; @@ -2494,40 +2229,36 @@ void fx_runner_link( gentity_t *ent ) } // make us useable if we can be targeted - if ( ent->targetname && ent->targetname[0] ) - { + if (ent->targetname && ent->targetname[0]) { ent->use = fx_runner_use; } } //---------------------------------------------------------- -void SP_fx_runner( gentity_t *ent ) -{ +void SP_fx_runner(gentity_t *ent) { char *fxFile; - G_SpawnString( "fxFile", "", &fxFile ); + G_SpawnString("fxFile", "", &fxFile); // Get our defaults - G_SpawnInt( "delay", "200", &ent->delay ); - G_SpawnFloat( "random", "0", &ent->random ); - G_SpawnInt( "splashRadius", "16", &ent->splashRadius ); - G_SpawnInt( "splashDamage", "5", &ent->splashDamage ); + G_SpawnInt("delay", "200", &ent->delay); + G_SpawnFloat("random", "0", &ent->random); + G_SpawnInt("splashRadius", "16", &ent->splashRadius); + G_SpawnInt("splashDamage", "5", &ent->splashDamage); - if (!ent->s.angles[0] && !ent->s.angles[1] && !ent->s.angles[2]) - { + if (!ent->s.angles[0] && !ent->s.angles[1] && !ent->s.angles[2]) { // didn't have angles, so give us the default of up - VectorSet( ent->s.angles, -90, 0, 0 ); + VectorSet(ent->s.angles, -90, 0, 0); } - if ( !fxFile || !fxFile[0] ) - { - Com_Printf( S_COLOR_RED"ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin) ); - G_FreeEntity( ent ); + if (!fxFile || !fxFile[0]) { + Com_Printf(S_COLOR_RED "ERROR: fx_runner %s at %s has no fxFile specified\n", ent->targetname, vtos(ent->s.origin)); + G_FreeEntity(ent); return; } // Try and associate an effect file, unfortunately we won't know if this worked or not // until the cgame trys to register it... - ent->s.modelindex = G_EffectIndex( fxFile ); + ent->s.modelindex = G_EffectIndex(fxFile); // important info transmitted ent->s.eType = ET_FX; @@ -2540,12 +2271,12 @@ void SP_fx_runner( gentity_t *ent ) ent->nextthink = level.time + 400; // Save our position and link us up! - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); - VectorSet( ent->r.maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS ); - VectorScale( ent->r.maxs, -1, ent->r.mins ); + VectorSet(ent->r.maxs, FX_ENT_RADIUS, FX_ENT_RADIUS, FX_ENT_RADIUS); + VectorScale(ent->r.maxs, -1, ent->r.mins); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /*QUAKED fx_wind (0 .5 .8) (-16 -16 -16) (16 16 16) NORMAL CONSTANT GUSTING SWIRLING x FOG LIGHT_FOG @@ -2559,35 +2290,31 @@ SWIRLING causes random swirls of wind "angles" the direction for constant wind "speed" the speed for constant wind */ -void SP_CreateWind( gentity_t *ent ) -{ - char temp[256]; +void SP_CreateWind(gentity_t *ent) { + char temp[256]; // Normal Wind //------------- - if ( ent->spawnflags & 1 ) - { - G_EffectIndex( "*wind" ); + if (ent->spawnflags & 1) { + G_EffectIndex("*wind"); } // Constant Wind //--------------- - if ( ent->spawnflags & 2 ) - { - vec3_t windDir; - AngleVectors( ent->s.angles, windDir, 0, 0 ); - G_SpawnFloat( "speed", "500", &ent->speed ); - VectorScale( windDir, ent->speed, windDir ); + if (ent->spawnflags & 2) { + vec3_t windDir; + AngleVectors(ent->s.angles, windDir, 0, 0); + G_SpawnFloat("speed", "500", &ent->speed); + VectorScale(windDir, ent->speed, windDir); - Com_sprintf( temp, sizeof(temp), "*constantwind ( %f %f %f )", windDir[0], windDir[1], windDir[2] ); - G_EffectIndex( temp ); + Com_sprintf(temp, sizeof(temp), "*constantwind ( %f %f %f )", windDir[0], windDir[1], windDir[2]); + G_EffectIndex(temp); } // Gusting Wind //-------------- - if ( ent->spawnflags & 4 ) - { - G_EffectIndex( "*gustingwind" ); + if (ent->spawnflags & 4) { + G_EffectIndex("*gustingwind"); } // Swirling Wind @@ -2597,19 +2324,16 @@ void SP_CreateWind( gentity_t *ent ) G_EffectIndex( "*swirlingwind" ); }*/ - // MISTY FOG //=========== - if ( ent->spawnflags & 32 ) - { - G_EffectIndex( "*fog" ); + if (ent->spawnflags & 32) { + G_EffectIndex("*fog"); } // MISTY FOG //=========== - if ( ent->spawnflags & 64 ) - { - G_EffectIndex( "*light_fog" ); + if (ent->spawnflags & 64) { + G_EffectIndex("*light_fog"); } } @@ -2619,21 +2343,18 @@ This world effect will spawn space dust globally into the level. "count" the number of snow particles (default of 1000) */ //---------------------------------------------------------- -void SP_CreateSpaceDust( gentity_t *ent ) -{ +void SP_CreateSpaceDust(gentity_t *ent) { G_EffectIndex(va("*spacedust %i", ent->count)); - //G_EffectIndex("*constantwind ( 10 -10 0 )"); + // G_EffectIndex("*constantwind ( 10 -10 0 )"); } - /*QUAKED fx_snow (1 0 0) (-16 -16 -16) (16 16 16) This world effect will spawn snow globally into the level. "count" the number of snow particles (default of 1000) */ //---------------------------------------------------------- -void SP_CreateSnow( gentity_t *ent ) -{ +void SP_CreateSnow(gentity_t *ent) { G_EffectIndex("*snow"); G_EffectIndex("*fog"); G_EffectIndex("*constantwind ( 100 100 -100 )"); @@ -2650,98 +2371,77 @@ ACID create acid rain MISTY_FOG causes clouds of misty fog to float through the level */ //---------------------------------------------------------- -void SP_CreateRain( gentity_t *ent ) -{ - if ( ent->spawnflags == 0 ) - { - G_EffectIndex( "*rain" ); +void SP_CreateRain(gentity_t *ent) { + if (ent->spawnflags == 0) { + G_EffectIndex("*rain"); return; } // Different Types Of Rain //------------------------- - if ( ent->spawnflags & 1 ) - { - G_EffectIndex( "*lightrain" ); - } - else if ( ent->spawnflags & 2 ) - { - G_EffectIndex( "*rain" ); - } - else if ( ent->spawnflags & 4 ) - { - G_EffectIndex( "*heavyrain" ); + if (ent->spawnflags & 1) { + G_EffectIndex("*lightrain"); + } else if (ent->spawnflags & 2) { + G_EffectIndex("*rain"); + } else if (ent->spawnflags & 4) { + G_EffectIndex("*heavyrain"); // Automatically Get Heavy Fog //----------------------------- - G_EffectIndex( "*heavyrainfog" ); - } - else if ( ent->spawnflags & 8 ) - { - G_EffectIndex( "world/acid_fizz" ); - G_EffectIndex( "*acidrain" ); + G_EffectIndex("*heavyrainfog"); + } else if (ent->spawnflags & 8) { + G_EffectIndex("world/acid_fizz"); + G_EffectIndex("*acidrain"); } // MISTY FOG //=========== - if ( ent->spawnflags & 32 ) - { - G_EffectIndex( "*fog" ); + if (ent->spawnflags & 32) { + G_EffectIndex("*fog"); } } qboolean gEscaping = qfalse; int gEscapeTime = 0; -void Use_Target_Screenshake( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ +void Use_Target_Screenshake(gentity_t *ent, gentity_t *other, gentity_t *activator) { qboolean bGlobal = qfalse; - if (ent->genericValue6) - { + if (ent->genericValue6) { bGlobal = qtrue; } G_ScreenShake(ent->s.origin, NULL, ent->speed, ent->genericValue5, bGlobal); } -void SP_target_screenshake(gentity_t *ent) -{ - G_SpawnFloat( "intensity", "10", &ent->speed ); - //intensity of the shake - G_SpawnInt( "duration", "800", &ent->genericValue5 ); - //duration of the shake - G_SpawnInt( "globalshake", "1", &ent->genericValue6 ); - //non-0 if shake should be global (all clients). Otherwise, only in the PVS. +void SP_target_screenshake(gentity_t *ent) { + G_SpawnFloat("intensity", "10", &ent->speed); + // intensity of the shake + G_SpawnInt("duration", "800", &ent->genericValue5); + // duration of the shake + G_SpawnInt("globalshake", "1", &ent->genericValue6); + // non-0 if shake should be global (all clients). Otherwise, only in the PVS. ent->use = Use_Target_Screenshake; } -void LogExit( const char *string ); +void LogExit(const char *string); -void Use_Target_Escapetrig( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - if (!ent->genericValue6) - { +void Use_Target_Escapetrig(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (!ent->genericValue6) { gEscaping = qtrue; gEscapeTime = level.time + ent->genericValue5; - } - else if (gEscaping) - { + } else if (gEscaping) { int i = 0; gEscaping = qfalse; - while (i < MAX_CLIENTS) - { //all of the survivors get 100 points! - if (g_entities[i].inuse && g_entities[i].client && g_entities[i].health > 0 && - g_entities[i].client->sess.sessionTeam != TEAM_SPECTATOR && - !(g_entities[i].client->ps.pm_flags & PMF_FOLLOW)) - { + while (i < MAX_CLIENTS) { // all of the survivors get 100 points! + if (g_entities[i].inuse && g_entities[i].client && g_entities[i].health > 0 && g_entities[i].client->sess.sessionTeam != TEAM_SPECTATOR && + !(g_entities[i].client->ps.pm_flags & PMF_FOLLOW)) { AddScore(&g_entities[i], g_entities[i].client->ps.origin, 100); } i++; } - if (activator && activator->inuse && activator->client) - { //the one who escaped gets 500 + if (activator && activator->inuse && activator->client) { // the one who escaped gets 500 AddScore(activator, activator->client->ps.origin, 500); } @@ -2749,87 +2449,81 @@ void Use_Target_Escapetrig( gentity_t *ent, gentity_t *other, gentity_t *activat } } -void SP_target_escapetrig(gentity_t *ent) -{ - if (level.gametype != GT_SINGLE_PLAYER) - { +void SP_target_escapetrig(gentity_t *ent) { + if (level.gametype != GT_SINGLE_PLAYER) { G_FreeEntity(ent); return; } - G_SpawnInt( "escapetime", "60000", &ent->genericValue5); - //time given (in ms) for the escape - G_SpawnInt( "escapegoal", "0", &ent->genericValue6); - //if non-0, when used, will end an ongoing escape instead of start it + G_SpawnInt("escapetime", "60000", &ent->genericValue5); + // time given (in ms) for the escape + G_SpawnInt("escapegoal", "0", &ent->genericValue6); + // if non-0, when used, will end an ongoing escape instead of start it ent->use = Use_Target_Escapetrig; } /*QUAKED misc_maglock (0 .5 .8) (-8 -8 -8) (8 8 8) x x x x x x x x -Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door it's attached to +Place facing a door (using the angle, not a targetname) and it will lock that door. Can only be destroyed by lightsaber and will automatically unlock the door +it's attached to NOTE: place these half-way in the door to make it flush with the door's surface. "target" thing to use when destoryed (not doors - it automatically unlocks the door it was angled at) "health" default is 10 */ -void maglock_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ - //unlock our door if we're the last lock pointed at the door - if ( self->activator ) - { +void maglock_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { + // unlock our door if we're the last lock pointed at the door + if (self->activator) { self->activator->lockCount--; - if ( !self->activator->lockCount ) - { + if (!self->activator->lockCount) { self->activator->flags &= ~FL_INACTIVE; } } - //use targets - G_UseTargets( self, attacker ); - //die - //rwwFIXMEFIXME - weap expl func -// WP_Explode( self ); + // use targets + G_UseTargets(self, attacker); + // die + // rwwFIXMEFIXME - weap expl func + // WP_Explode( self ); } -void maglock_link( gentity_t *self ); -gentity_t *G_FindDoorTrigger( gentity_t *ent ); +void maglock_link(gentity_t *self); +gentity_t *G_FindDoorTrigger(gentity_t *ent); -void SP_misc_maglock ( gentity_t *self ) -{ - //NOTE: May have to make these only work on doors that are either untargeted +void SP_misc_maglock(gentity_t *self) { + // NOTE: May have to make these only work on doors that are either untargeted // or are targeted by a trigger, not doors fired off by scripts, counters // or other such things? - self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - self->genericValue1 = G_EffectIndex( "maglock/explosion" ); + self->s.modelindex = G_ModelIndex("models/map_objects/imp_detention/door_lock.md3"); + self->genericValue1 = G_EffectIndex("maglock/explosion"); - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->think = maglock_link; - //FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the START_TIME_FIND_LINKS - self->nextthink = level.time + START_TIME_FIND_LINKS+200;//START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! -} -void maglock_link( gentity_t *self ) -{ - //find what we're supposed to be attached to - vec3_t forward, start, end; - trace_t trace; + // FIXME: for some reason, when you re-load a level, these fail to find their doors...? Random? Testing an additional 200ms after the + // START_TIME_FIND_LINKS + self->nextthink = + level.time + START_TIME_FIND_LINKS + 200; // START_TIME_FIND_LINKS;//because we need to let the doors link up and spawn their triggers first! +} +void maglock_link(gentity_t *self) { + // find what we're supposed to be attached to + vec3_t forward, start, end; + trace_t trace; gentity_t *traceEnt; - AngleVectors( self->s.angles, forward, NULL, NULL ); - VectorMA( self->s.origin, 128, forward, end ); - VectorMA( self->s.origin, -4, forward, start ); + AngleVectors(self->s.angles, forward, NULL, NULL); + VectorMA(self->s.origin, 128, forward, end); + VectorMA(self->s.origin, -4, forward, start); - trap->Trace( &trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&trace, start, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( trace.allsolid || trace.startsolid ) - { - Com_Error( ERR_DROP,"misc_maglock at %s in solid\n", vtos(self->s.origin) ); - G_FreeEntity( self ); + if (trace.allsolid || trace.startsolid) { + Com_Error(ERR_DROP, "misc_maglock at %s in solid\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( trace.fraction == 1.0 ) - { + if (trace.fraction == 1.0) { self->think = maglock_link; self->nextthink = level.time + 100; /* @@ -2839,63 +2533,54 @@ void maglock_link( gentity_t *self ) return; } traceEnt = &g_entities[trace.entityNum]; - if ( trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp( "func_door", traceEnt->classname ) ) - { + if (trace.entityNum >= ENTITYNUM_WORLD || !traceEnt || Q_stricmp("func_door", traceEnt->classname)) { self->think = maglock_link; self->nextthink = level.time + 100; - //Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); - //G_FreeEntity( self ); + // Com_Error( ERR_DROP,"misc_maglock at %s not pointed at a door\n", vtos(self->s.origin) ); + // G_FreeEntity( self ); return; } - //check the traceEnt, make sure it's a door and give it a lockCount and deactivate it - //find the trigger for the door - self->activator = G_FindDoorTrigger( traceEnt ); - if ( !self->activator ) - { + // check the traceEnt, make sure it's a door and give it a lockCount and deactivate it + // find the trigger for the door + self->activator = G_FindDoorTrigger(traceEnt); + if (!self->activator) { self->activator = traceEnt; } self->activator->lockCount++; self->activator->flags |= FL_INACTIVE; - //now position and orient it - vectoangles( trace.plane.normal, end ); - G_SetOrigin( self, trace.endpos ); - G_SetAngles( self, end ); + // now position and orient it + vectoangles(trace.plane.normal, end); + G_SetOrigin(self, trace.endpos); + G_SetAngles(self, end); - //make it hittable - //FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? - //self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); - VectorSet( self->r.mins, -8, -8, -8 ); - VectorSet( self->r.maxs, 8, 8, 8 ); + // make it hittable + // FIXME: if rotated/inclined this bbox may be off... but okay if we're a ghoul model? + // self->s.modelindex = G_ModelIndex( "models/map_objects/imp_detention/door_lock.md3" ); + VectorSet(self->r.mins, -8, -8, -8); + VectorSet(self->r.maxs, 8, 8, 8); self->r.contents = CONTENTS_CORPSE; - //make it destroyable - self->flags |= FL_SHIELDED;//only damagable by lightsabers + // make it destroyable + self->flags |= FL_SHIELDED; // only damagable by lightsabers self->takedamage = qtrue; self->health = 10; self->die = maglock_die; - //self->fxID = G_EffectIndex( "maglock/explosion" ); + // self->fxID = G_EffectIndex( "maglock/explosion" ); - trap->LinkEntity( (sharedEntity_t *)self ); + trap->LinkEntity((sharedEntity_t *)self); } -void faller_touch(gentity_t *self, gentity_t *other, trace_t *trace) -{ - if (self->epVelocity[2] < -100 && self->genericValue7 < level.time) - { +void faller_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (self->epVelocity[2] < -100 && self->genericValue7 < level.time) { int r = Q_irand(1, 3); - if (r == 1) - { + if (r == 1) { self->genericValue11 = G_SoundIndex("sound/chars/stofficer1/misc/pain25"); - } - else if (r == 2) - { + } else if (r == 2) { self->genericValue11 = G_SoundIndex("sound/chars/stofficer1/misc/pain50"); - } - else - { + } else { self->genericValue11 = G_SoundIndex("sound/chars/stofficer1/misc/pain75"); } @@ -2908,29 +2593,23 @@ void faller_touch(gentity_t *self, gentity_t *other, trace_t *trace) } } -void faller_think(gentity_t *ent) -{ +void faller_think(gentity_t *ent) { float gravity = 3.0f; float mass = 0.09f; float bounce = 1.1f; - if (ent->genericValue6 < level.time) - { + if (ent->genericValue6 < level.time) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; } - if (ent->epVelocity[2] < -100) - { - if (!ent->genericValue8) - { + if (ent->epVelocity[2] < -100) { + if (!ent->genericValue8) { G_EntitySound(ent, CHAN_VOICE, ent->genericValue9); ent->genericValue8 = 1; } - } - else - { + } else { ent->genericValue8 = 0; } @@ -2939,8 +2618,7 @@ void faller_think(gentity_t *ent) ent->nextthink = level.time + 25; } -void misc_faller_create( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ +void misc_faller_create(gentity_t *ent, gentity_t *other, gentity_t *activator) { gentity_t *faller = G_Spawn(); faller->genericValue10 = G_SoundIndex("sound/player/fallsplat"); @@ -2956,10 +2634,10 @@ void misc_faller_create( gentity_t *ent, gentity_t *other, gentity_t *activator faller->s.modelindex = G_ModelIndex("models/players/stormtrooper/model.glm"); faller->s.g2radius = 100; - faller->s.customRGBA[0]=Q_irand(1,255); - faller->s.customRGBA[1]=Q_irand(1,255); - faller->s.customRGBA[2]=Q_irand(1,255); - faller->s.customRGBA[3]=255; + faller->s.customRGBA[0] = Q_irand(1, 255); + faller->s.customRGBA[1] = Q_irand(1, 255); + faller->s.customRGBA[2] = Q_irand(1, 255); + faller->s.customRGBA[3] = 255; VectorSet(faller->r.mins, -15, -15, DEFAULT_MINS_2); VectorSet(faller->r.maxs, 15, 15, DEFAULT_MAXS_2); @@ -2967,7 +2645,7 @@ void misc_faller_create( gentity_t *ent, gentity_t *other, gentity_t *activator faller->clipmask = MASK_PLAYERSOLID; faller->r.contents = MASK_PLAYERSOLID; - faller->s.eFlags = (EF_RAG|EF_CLIENTSMOOTH); + faller->s.eFlags = (EF_RAG | EF_CLIENTSMOOTH); faller->think = faller_think; faller->nextthink = level.time; @@ -2980,8 +2658,7 @@ void misc_faller_create( gentity_t *ent, gentity_t *other, gentity_t *activator trap->LinkEntity((sharedEntity_t *)faller); } -void misc_faller_think(gentity_t *ent) -{ +void misc_faller_think(gentity_t *ent) { misc_faller_create(ent, ent, ent); ent->nextthink = level.time + ent->genericValue1 + Q_irand(0, ent->genericValue2); } @@ -2994,8 +2671,7 @@ targetname - if specified, will only spawn when used interval - spawn every so often (milliseconds) fudgefactor - milliseconds between 0 and this number randomly added to interval */ -void SP_misc_faller(gentity_t *ent) -{ +void SP_misc_faller(gentity_t *ent) { G_ModelIndex("models/players/stormtrooper/model.glm"); G_SoundIndex("sound/chars/stofficer1/misc/pain25"); G_SoundIndex("sound/chars/stofficer1/misc/pain50"); @@ -3006,46 +2682,39 @@ void SP_misc_faller(gentity_t *ent) G_SpawnInt("interval", "500", &ent->genericValue1); G_SpawnInt("fudgefactor", "0", &ent->genericValue2); - if (!ent->targetname || !ent->targetname[0]) - { + if (!ent->targetname || !ent->targetname[0]) { ent->think = misc_faller_think; ent->nextthink = level.time + ent->genericValue1 + Q_irand(0, ent->genericValue2); - } - else - { + } else { ent->use = misc_faller_create; } } -//rww - ref tag stuff ported from SP (and C-ified) -#define TAG_GENERIC_NAME "__WORLD__" //If a designer chooses this name, cut a finger off as an example to the others +// rww - ref tag stuff ported from SP (and C-ified) +#define TAG_GENERIC_NAME "__WORLD__" // If a designer chooses this name, cut a finger off as an example to the others -//MAX_TAG_OWNERS is 16 for now in order to not use too much VM memory. -//Each tag owner has preallocated space for tags up to MAX_TAGS. -//As is this means 16*256 sizeof(reference_tag_t)'s in addition to name+inuse*16. +// MAX_TAG_OWNERS is 16 for now in order to not use too much VM memory. +// Each tag owner has preallocated space for tags up to MAX_TAGS. +// As is this means 16*256 sizeof(reference_tag_t)'s in addition to name+inuse*16. #define MAX_TAGS 256 #define MAX_TAG_OWNERS 16 -//Maybe I should use my trap->TrueMalloc/trap->TrueFree stuff with this. -//But I am not yet confident that it can be used without exploding at some point. +// Maybe I should use my trap->TrueMalloc/trap->TrueFree stuff with this. +// But I am not yet confident that it can be used without exploding at some point. -typedef struct tagOwner_s -{ - char name[MAX_REFNAME]; - reference_tag_t tags[MAX_TAGS]; - qboolean inuse; +typedef struct tagOwner_s { + char name[MAX_REFNAME]; + reference_tag_t tags[MAX_TAGS]; + qboolean inuse; } tagOwner_t; tagOwner_t refTagOwnerMap[MAX_TAG_OWNERS]; -tagOwner_t *FirstFreeTagOwner(void) -{ +tagOwner_t *FirstFreeTagOwner(void) { int i = 0; - while (i < MAX_TAG_OWNERS) - { - if (!refTagOwnerMap[i].inuse) - { + while (i < MAX_TAG_OWNERS) { + if (!refTagOwnerMap[i].inuse) { return &refTagOwnerMap[i]; } i++; @@ -3055,16 +2724,13 @@ tagOwner_t *FirstFreeTagOwner(void) return NULL; } -reference_tag_t *FirstFreeRefTag(tagOwner_t *tagOwner) -{ +reference_tag_t *FirstFreeRefTag(tagOwner_t *tagOwner) { int i = 0; assert(tagOwner); - while (i < MAX_TAGS) - { - if (!tagOwner->tags[i].inuse) - { + while (i < MAX_TAGS) { + if (!tagOwner->tags[i].inuse) { return &tagOwner->tags[i]; } i++; @@ -3080,15 +2746,12 @@ TAG_Init ------------------------- */ -void TAG_Init( void ) -{ +void TAG_Init(void) { int i = 0; int x = 0; - while (i < MAX_TAG_OWNERS) - { - while (x < MAX_TAGS) - { + while (i < MAX_TAG_OWNERS) { + while (x < MAX_TAGS) { memset(&refTagOwnerMap[i].tags[x], 0, sizeof(refTagOwnerMap[i].tags[x])); x++; } @@ -3103,14 +2766,11 @@ TAG_FindOwner ------------------------- */ -tagOwner_t *TAG_FindOwner( const char *owner ) -{ +tagOwner_t *TAG_FindOwner(const char *owner) { int i = 0; - while (i < MAX_TAG_OWNERS) - { - if (refTagOwnerMap[i].inuse && !Q_stricmp(refTagOwnerMap[i].name, owner)) - { + while (i < MAX_TAG_OWNERS) { + if (refTagOwnerMap[i].inuse && !Q_stricmp(refTagOwnerMap[i].name, owner)) { return &refTagOwnerMap[i]; } i++; @@ -3125,53 +2785,43 @@ TAG_Find ------------------------- */ -reference_tag_t *TAG_Find( const char *owner, const char *name ) -{ - tagOwner_t *tagOwner = NULL; +reference_tag_t *TAG_Find(const char *owner, const char *name) { + tagOwner_t *tagOwner = NULL; int i = 0; - if (owner && owner[0]) - { + if (owner && owner[0]) { tagOwner = TAG_FindOwner(owner); } - if (!tagOwner) - { + if (!tagOwner) { tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); } - //Not found... - if (!tagOwner) - { - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + // Not found... + if (!tagOwner) { + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if (!tagOwner) - { + if (!tagOwner) { return NULL; } } - while (i < MAX_TAGS) - { - if (tagOwner->tags[i].inuse && !Q_stricmp(tagOwner->tags[i].name, name)) - { + while (i < MAX_TAGS) { + if (tagOwner->tags[i].inuse && !Q_stricmp(tagOwner->tags[i].name, name)) { return &tagOwner->tags[i]; } i++; } - //Try the generic owner instead - tagOwner = TAG_FindOwner( TAG_GENERIC_NAME ); + // Try the generic owner instead + tagOwner = TAG_FindOwner(TAG_GENERIC_NAME); - if (!tagOwner) - { + if (!tagOwner) { return NULL; } i = 0; - while (i < MAX_TAGS) - { - if (tagOwner->tags[i].inuse && !Q_stricmp(tagOwner->tags[i].name, name)) - { + while (i < MAX_TAGS) { + if (tagOwner->tags[i].inuse && !Q_stricmp(tagOwner->tags[i].name, name)) { return &tagOwner->tags[i]; } i++; @@ -3186,69 +2836,61 @@ TAG_Add ------------------------- */ -reference_tag_t *TAG_Add( const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags ) -{ - reference_tag_t *tag = NULL; - tagOwner_t *tagOwner = NULL; +reference_tag_t *TAG_Add(const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags) { + reference_tag_t *tag = NULL; + tagOwner_t *tagOwner = NULL; - //Make sure this tag's name isn't alread in use - if ( TAG_Find( owner, name ) ) - { - Com_Printf(S_COLOR_RED"Duplicate tag name \"%s\"\n", name ); + // Make sure this tag's name isn't alread in use + if (TAG_Find(owner, name)) { + Com_Printf(S_COLOR_RED "Duplicate tag name \"%s\"\n", name); return NULL; } - //Attempt to add this to the owner's list - if ( !owner || !owner[0] ) - { - //If the owner isn't found, use the generic world name + // Attempt to add this to the owner's list + if (!owner || !owner[0]) { + // If the owner isn't found, use the generic world name owner = TAG_GENERIC_NAME; } - tagOwner = TAG_FindOwner( owner ); + tagOwner = TAG_FindOwner(owner); - if (!tagOwner) - { - //Create a new owner list - tagOwner = FirstFreeTagOwner();//new tagOwner_t; + if (!tagOwner) { + // Create a new owner list + tagOwner = FirstFreeTagOwner(); // new tagOwner_t; - if (!tagOwner) - { + if (!tagOwner) { assert(0); return 0; } } - //This is actually reverse order of how SP does it because of the way we're storing/allocating. - //Now that we have the owner, we want to get the first free reftag on the owner itself. + // This is actually reverse order of how SP does it because of the way we're storing/allocating. + // Now that we have the owner, we want to get the first free reftag on the owner itself. tag = FirstFreeRefTag(tagOwner); - if (!tag) - { + if (!tag) { assert(0); return NULL; } - //Copy the information - VectorCopy( origin, tag->origin ); - VectorCopy( angles, tag->angles ); + // Copy the information + VectorCopy(origin, tag->origin); + VectorCopy(angles, tag->angles); tag->radius = radius; - tag->flags = flags; + tag->flags = flags; - if ( !name || !name[0] ) - { - Com_Printf(S_COLOR_RED"ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); + if (!name || !name[0]) { + Com_Printf(S_COLOR_RED "ERROR: Nameless ref_tag found at (%i %i %i)\n", (int)origin[0], (int)origin[1], (int)origin[2]); return NULL; } + // Copy the name + Q_strncpyz((char *)tagOwner->name, owner, MAX_REFNAME); + Q_strlwr((char *)tagOwner->name); // NOTENOTE: For case insensitive searches on a map - //Copy the name - Q_strncpyz( (char *) tagOwner->name, owner, MAX_REFNAME ); - Q_strlwr( (char *) tagOwner->name ); //NOTENOTE: For case insensitive searches on a map - - //Copy the name - Q_strncpyz( (char *) tag->name, name, MAX_REFNAME ); - Q_strlwr( (char *) tag->name ); //NOTENOTE: For case insensitive searches on a map + // Copy the name + Q_strncpyz((char *)tag->name, name, MAX_REFNAME); + Q_strlwr((char *)tag->name); // NOTENOTE: For case insensitive searches on a map tagOwner->inuse = qtrue; tag->inuse = qtrue; @@ -3262,17 +2904,15 @@ TAG_GetOrigin ------------------------- */ -int TAG_GetOrigin( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { VectorClear(origin); return 0; } - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return 1; } @@ -3284,16 +2924,14 @@ Had to get rid of that damn assert for dev ------------------------- */ -int TAG_GetOrigin2( const char *owner, const char *name, vec3_t origin ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetOrigin2(const char *owner, const char *name, vec3_t origin) { + reference_tag_t *tag = TAG_Find(owner, name); - if( tag == NULL ) - { + if (tag == NULL) { return 0; } - VectorCopy( tag->origin, origin ); + VectorCopy(tag->origin, origin); return 1; } @@ -3303,17 +2941,15 @@ TAG_GetAngles ------------------------- */ -int TAG_GetAngles( const char *owner, const char *name, vec3_t angles ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetAngles(const char *owner, const char *name, vec3_t angles) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { assert(0); return 0; } - VectorCopy( tag->angles, angles ); + VectorCopy(tag->angles, angles); return 1; } @@ -3324,12 +2960,10 @@ TAG_GetRadius ------------------------- */ -int TAG_GetRadius( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetRadius(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { assert(0); return 0; } @@ -3343,12 +2977,10 @@ TAG_GetFlags ------------------------- */ -int TAG_GetFlags( const char *owner, const char *name ) -{ - reference_tag_t *tag = TAG_Find( owner, name ); +int TAG_GetFlags(const char *owner, const char *name) { + reference_tag_t *tag = TAG_Find(owner, name); - if (!tag) - { + if (!tag) { assert(0); return 0; } @@ -3417,48 +3049,39 @@ ownername - the owner of this tag target - use to point the tag at something for angles */ -void ref_link ( gentity_t *ent ) -{ - if ( ent->target ) - { - //TODO: Find the target and set our angles to that direction - gentity_t *target = G_Find( NULL, FOFS(targetname), ent->target ); - vec3_t dir; +void ref_link(gentity_t *ent) { + if (ent->target) { + // TODO: Find the target and set our angles to that direction + gentity_t *target = G_Find(NULL, FOFS(targetname), ent->target); + vec3_t dir; - if ( target ) - { - //Find the direction to the target - VectorSubtract( target->s.origin, ent->s.origin, dir ); - VectorNormalize( dir ); - vectoangles( dir, ent->s.angles ); + if (target) { + // Find the direction to the target + VectorSubtract(target->s.origin, ent->s.origin, dir); + VectorNormalize(dir); + vectoangles(dir, ent->s.angles); - //FIXME: Does pitch get flipped? - } - else - { - Com_Printf( S_COLOR_RED"ERROR: ref_tag (%s) has invalid target (%s)\n", ent->targetname, ent->target ); + // FIXME: Does pitch get flipped? + } else { + Com_Printf(S_COLOR_RED "ERROR: ref_tag (%s) has invalid target (%s)\n", ent->targetname, ent->target); } } - //Add the tag - TAG_Add( ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0 ); + // Add the tag + TAG_Add(ent->targetname, ent->ownername, ent->s.origin, ent->s.angles, 16, 0); - //Delete immediately, cannot be refered to as an entity again - //NOTE: this means if you wanted to link them in a chain for, say, a path, you can't - G_FreeEntity( ent ); + // Delete immediately, cannot be refered to as an entity again + // NOTE: this means if you wanted to link them in a chain for, say, a path, you can't + G_FreeEntity(ent); } -void SP_reference_tag ( gentity_t *ent ) -{ - if ( ent->target ) - { - //Init cannot occur until all entities have been spawned +void SP_reference_tag(gentity_t *ent) { + if (ent->target) { + // Init cannot occur until all entities have been spawned ent->think = ref_link; ent->nextthink = level.time + START_TIME_LINK_ENTS; - } - else - { - ref_link( ent ); + } else { + ref_link(ent); } } @@ -3492,30 +3115,25 @@ TOGGLE - keep firing until used again (fires at intervals of "wait") WP_RAPID_FIRE_CONC WP_BLASTER_PISTOL */ -//kind of hacky, but we have to do this with no dynamic allocation -#define MAX_SHOOTERS 16 -typedef struct shooterClient_s -{ - gclient_t cl; - qboolean inuse; +// kind of hacky, but we have to do this with no dynamic allocation +#define MAX_SHOOTERS 16 +typedef struct shooterClient_s { + gclient_t cl; + qboolean inuse; } shooterClient_t; static shooterClient_t g_shooterClients[MAX_SHOOTERS]; static qboolean g_shooterClientInit = qfalse; -gclient_t *G_ClientForShooter(void) -{ +gclient_t *G_ClientForShooter(void) { int i = 0; - if (!g_shooterClientInit) - { //in theory it should be initialized to 0 on the stack, but just in case. - memset(g_shooterClients, 0, sizeof(shooterClient_t)*MAX_SHOOTERS); + if (!g_shooterClientInit) { // in theory it should be initialized to 0 on the stack, but just in case. + memset(g_shooterClients, 0, sizeof(shooterClient_t) * MAX_SHOOTERS); g_shooterClientInit = qtrue; } - while (i < MAX_SHOOTERS) - { - if (!g_shooterClients[i].inuse) - { + while (i < MAX_SHOOTERS) { + if (!g_shooterClients[i].inuse) { return &g_shooterClients[i].cl; } i++; @@ -3525,13 +3143,10 @@ gclient_t *G_ClientForShooter(void) return NULL; } -void G_FreeClientForShooter(gclient_t *cl) -{ +void G_FreeClientForShooter(gclient_t *cl) { int i = 0; - while (i < MAX_SHOOTERS) - { - if (&g_shooterClients[i].cl == cl) - { + while (i < MAX_SHOOTERS) { + if (&g_shooterClients[i].cl == cl) { g_shooterClients[i].inuse = qfalse; return; } @@ -3539,20 +3154,16 @@ void G_FreeClientForShooter(gclient_t *cl) } } -void misc_weapon_shooter_fire( gentity_t *self ) -{ - FireWeapon( self, (self->spawnflags&1) ); - if ( (self->spawnflags&2) ) - {//repeat +void misc_weapon_shooter_fire(gentity_t *self) { + FireWeapon(self, (self->spawnflags & 1)); + if ((self->spawnflags & 2)) { // repeat self->think = misc_weapon_shooter_fire; self->nextthink = level.time + self->wait; } } -void misc_weapon_shooter_use ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->think == misc_weapon_shooter_fire ) - {//repeating fire, stop +void misc_weapon_shooter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->think == misc_weapon_shooter_fire) { // repeating fire, stop /* G_FreeClientForShooter(self->client); self->think = G_FreeEntity; @@ -3561,28 +3172,23 @@ void misc_weapon_shooter_use ( gentity_t *self, gentity_t *other, gentity_t *act self->nextthink = 0; return; } - //otherwise, fire - misc_weapon_shooter_fire( self ); + // otherwise, fire + misc_weapon_shooter_fire(self); } -void misc_weapon_shooter_aim( gentity_t *self ) -{ - //update my aim - if ( self->target ) - { - gentity_t *targ = G_Find( NULL, FOFS(targetname), self->target ); - if ( targ ) - { +void misc_weapon_shooter_aim(gentity_t *self) { + // update my aim + if (self->target) { + gentity_t *targ = G_Find(NULL, FOFS(targetname), self->target); + if (targ) { self->enemy = targ; - VectorSubtract( targ->r.currentOrigin, self->r.currentOrigin, self->pos1 ); - VectorCopy( targ->r.currentOrigin, self->pos1 ); - vectoangles( self->pos1, self->client->ps.viewangles ); - SetClientViewAngle( self, self->client->ps.viewangles ); - //FIXME: don't keep doing this unless target is a moving target? + VectorSubtract(targ->r.currentOrigin, self->r.currentOrigin, self->pos1); + VectorCopy(targ->r.currentOrigin, self->pos1); + vectoangles(self->pos1, self->client->ps.viewangles); + SetClientViewAngle(self, self->client->ps.viewangles); + // FIXME: don't keep doing this unless target is a moving target? self->nextthink = level.time + FRAMETIME; - } - else - { + } else { self->enemy = NULL; } } @@ -3590,46 +3196,40 @@ void misc_weapon_shooter_aim( gentity_t *self ) extern stringID_table_t WPTable[]; -void SP_misc_weapon_shooter( gentity_t *self ) -{ +void SP_misc_weapon_shooter(gentity_t *self) { char *s; - //alloc a client just for the weapon code to use - self->client = G_ClientForShooter();//(gclient_s *)trap->Malloc(sizeof(gclient_s), TAG_G_ALLOC, qtrue); + // alloc a client just for the weapon code to use + self->client = G_ClientForShooter(); //(gclient_s *)trap->Malloc(sizeof(gclient_s), TAG_G_ALLOC, qtrue); G_SpawnString("weapon", "", &s); - //set weapon + // set weapon self->s.weapon = self->client->ps.weapon = WP_BLASTER; - if ( s && s[0] ) - {//use a different weapon - self->s.weapon = self->client->ps.weapon = GetIDForString( WPTable, s ); + if (s && s[0]) { // use a different weapon + self->s.weapon = self->client->ps.weapon = GetIDForString(WPTable, s); } RegisterItem(BG_FindItemForWeapon(self->s.weapon)); - //set where our muzzle is - VectorCopy( self->s.origin, self->client->renderInfo.muzzlePoint ); - //permanently updated (don't need for MP) - //self->client->renderInfo.mPCalcTime = Q3_INFINITE; + // set where our muzzle is + VectorCopy(self->s.origin, self->client->renderInfo.muzzlePoint); + // permanently updated (don't need for MP) + // self->client->renderInfo.mPCalcTime = Q3_INFINITE; - //set up to link - if ( self->target ) - { - self->think = misc_weapon_shooter_aim; + // set up to link + if (self->target) { + self->think = misc_weapon_shooter_aim; self->nextthink = level.time + START_TIME_LINK_ENTS; - } - else - {//just set aim angles - VectorCopy( self->s.angles, self->client->ps.viewangles ); - AngleVectors( self->s.angles, self->pos1, NULL, NULL ); + } else { // just set aim angles + VectorCopy(self->s.angles, self->client->ps.viewangles); + AngleVectors(self->s.angles, self->pos1, NULL, NULL); } - //set up to fire when used - self->use = misc_weapon_shooter_use; + // set up to fire when used + self->use = misc_weapon_shooter_use; - if ( !self->wait ) - { + if (!self->wait) { self->wait = 500; } } @@ -3637,12 +3237,6 @@ void SP_misc_weapon_shooter( gentity_t *self ) /*QUAKED misc_weather_zone (0 .5 .8) ? Determines a region to check for weather contents - will significantly reduce load time */ -void SP_misc_weather_zone( gentity_t *ent ) -{ - G_FreeEntity(ent); -} +void SP_misc_weather_zone(gentity_t *ent) { G_FreeEntity(ent); } -void SP_misc_cubemap( gentity_t *ent ) -{ - G_FreeEntity( ent ); -} +void SP_misc_cubemap(gentity_t *ent) { G_FreeEntity(ent); } diff --git a/codemp/game/g_missile.c b/codemp/game/g_missile.c index d87a1e8175..8eac28ec6b 100644 --- a/codemp/game/g_missile.c +++ b/codemp/game/g_missile.c @@ -25,12 +25,12 @@ along with this program; if not, see . #include "w_saber.h" #include "qcommon/q_shared.h" -#define MISSILE_PRESTEP_TIME 50 +#define MISSILE_PRESTEP_TIME 50 -extern void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ); -extern void Jedi_Decloak( gentity_t *self ); +extern void laserTrapStick(gentity_t *ent, vec3_t endpos, vec3_t normal); +extern void Jedi_Decloak(gentity_t *self); -extern qboolean FighterIsLanded( Vehicle_t *pVeh, playerState_t *parentPS ); +extern qboolean FighterIsLanded(Vehicle_t *pVeh, playerState_t *parentPS); /* ================ @@ -40,106 +40,90 @@ G_ReflectMissile ================ */ float RandFloat(float min, float max); -void G_ReflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ) -{ - vec3_t bounce_dir; - int i; - float speed; - int isowner = 0; +void G_ReflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward) { + vec3_t bounce_dir; + int i; + float speed; + int isowner = 0; - if (missile->r.ownerNum == ent->s.number) - { //the original owner is bouncing the missile, so don't try to bounce it back at him + if (missile->r.ownerNum == ent->s.number) { // the original owner is bouncing the missile, so don't try to bounce it back at him isowner = 1; } - //save the original speed - speed = VectorNormalize( missile->s.pos.trDelta ); + // save the original speed + speed = VectorNormalize(missile->s.pos.trDelta); - if ( &g_entities[missile->r.ownerNum] && missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART && !isowner ) - {//bounce back at them if you can - VectorSubtract( g_entities[missile->r.ownerNum].r.currentOrigin, missile->r.currentOrigin, bounce_dir ); - VectorNormalize( bounce_dir ); - } - else if (isowner) - { //in this case, actually push the missile away from me, and since we're giving boost to our own missile by pushing it, up the velocity + if (&g_entities[missile->r.ownerNum] && missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART && !isowner) { // bounce back at them if you can + VectorSubtract(g_entities[missile->r.ownerNum].r.currentOrigin, missile->r.currentOrigin, bounce_dir); + VectorNormalize(bounce_dir); + } else if (isowner) { // in this case, actually push the missile away from me, and since we're giving boost to our own missile by pushing it, up the + // velocity vec3_t missile_dir; speed *= 1.5; - VectorSubtract( missile->r.currentOrigin, ent->r.currentOrigin, missile_dir ); - VectorCopy( missile->s.pos.trDelta, bounce_dir ); - VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); - VectorNormalize( bounce_dir ); - } - else - { + VectorSubtract(missile->r.currentOrigin, ent->r.currentOrigin, missile_dir); + VectorCopy(missile->s.pos.trDelta, bounce_dir); + VectorScale(bounce_dir, DotProduct(forward, missile_dir), bounce_dir); + VectorNormalize(bounce_dir); + } else { vec3_t missile_dir; - VectorSubtract( ent->r.currentOrigin, missile->r.currentOrigin, missile_dir ); - VectorCopy( missile->s.pos.trDelta, bounce_dir ); - VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); - VectorNormalize( bounce_dir ); + VectorSubtract(ent->r.currentOrigin, missile->r.currentOrigin, missile_dir); + VectorCopy(missile->s.pos.trDelta, bounce_dir); + VectorScale(bounce_dir, DotProduct(forward, missile_dir), bounce_dir); + VectorNormalize(bounce_dir); } - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += RandFloat( -0.2f, 0.2f ); + for (i = 0; i < 3; i++) { + bounce_dir[i] += RandFloat(-0.2f, 0.2f); } - VectorNormalize( bounce_dir ); - VectorScale( bounce_dir, speed, missile->s.pos.trDelta ); - missile->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( missile->r.currentOrigin, missile->s.pos.trBase ); - if ( missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART ) - {//you are mine, now! + VectorNormalize(bounce_dir); + VectorScale(bounce_dir, speed, missile->s.pos.trDelta); + missile->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(missile->r.currentOrigin, missile->s.pos.trBase); + if (missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART) { // you are mine, now! missile->r.ownerNum = ent->s.number; } - if ( missile->s.weapon == WP_ROCKET_LAUNCHER ) - {//stop homing + if (missile->s.weapon == WP_ROCKET_LAUNCHER) { // stop homing missile->think = 0; missile->nextthink = 0; } } -void G_DeflectMissile( gentity_t *ent, gentity_t *missile, vec3_t forward ) -{ - vec3_t bounce_dir; - int i; - float speed; +void G_DeflectMissile(gentity_t *ent, gentity_t *missile, vec3_t forward) { + vec3_t bounce_dir; + int i; + float speed; vec3_t missile_dir; - //save the original speed - speed = VectorNormalize( missile->s.pos.trDelta ); + // save the original speed + speed = VectorNormalize(missile->s.pos.trDelta); - if (ent->client) - { - //VectorSubtract( ent->r.currentOrigin, missile->r.currentOrigin, missile_dir ); + if (ent->client) { + // VectorSubtract( ent->r.currentOrigin, missile->r.currentOrigin, missile_dir ); AngleVectors(ent->client->ps.viewangles, missile_dir, 0, 0); VectorCopy(missile_dir, bounce_dir); - //VectorCopy( missile->s.pos.trDelta, bounce_dir ); - VectorScale( bounce_dir, DotProduct( forward, missile_dir ), bounce_dir ); - VectorNormalize( bounce_dir ); - } - else - { + // VectorCopy( missile->s.pos.trDelta, bounce_dir ); + VectorScale(bounce_dir, DotProduct(forward, missile_dir), bounce_dir); + VectorNormalize(bounce_dir); + } else { VectorCopy(forward, bounce_dir); VectorNormalize(bounce_dir); } - for ( i = 0; i < 3; i++ ) - { - bounce_dir[i] += RandFloat( -1.0f, 1.0f ); + for (i = 0; i < 3; i++) { + bounce_dir[i] += RandFloat(-1.0f, 1.0f); } - VectorNormalize( bounce_dir ); - VectorScale( bounce_dir, speed, missile->s.pos.trDelta ); - missile->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( missile->r.currentOrigin, missile->s.pos.trBase ); - if ( missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART ) - {//you are mine, now! + VectorNormalize(bounce_dir); + VectorScale(bounce_dir, speed, missile->s.pos.trDelta); + missile->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(missile->r.currentOrigin, missile->s.pos.trBase); + if (missile->s.weapon != WP_SABER && missile->s.weapon != G2_MODEL_PART) { // you are mine, now! missile->r.ownerNum = ent->s.number; } - if ( missile->s.weapon == WP_ROCKET_LAUNCHER ) - {//stop homing + if (missile->s.weapon == WP_ROCKET_LAUNCHER) { // stop homing missile->think = 0; missile->nextthink = 0; } @@ -151,66 +135,54 @@ G_BounceMissile ================ */ -void G_BounceMissile( gentity_t *ent, trace_t *trace ) { - vec3_t velocity; - float dot; - int hitTime; +void G_BounceMissile(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - BG_EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); - VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta ); + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + BG_EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + VectorMA(velocity, -2 * dot, trace->plane.normal, ent->s.pos.trDelta); - - if ( ent->flags & FL_BOUNCE_SHRAPNEL ) - { - VectorScale( ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta ); + if (ent->flags & FL_BOUNCE_SHRAPNEL) { + VectorScale(ent->s.pos.trDelta, 0.25f, ent->s.pos.trDelta); ent->s.pos.trType = TR_GRAVITY; // check for stop - if ( trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40 ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (trace->plane.normal[2] > 0.7 && ent->s.pos.trDelta[2] < 40) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - G_SetOrigin( ent, trace->endpos ); + G_SetOrigin(ent, trace->endpos); ent->nextthink = level.time + 100; return; } - } - else if ( ent->flags & FL_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.65f, ent->s.pos.trDelta ); + } else if (ent->flags & FL_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.65f, ent->s.pos.trDelta); // check for stop - if ( trace->plane.normal[2] > 0.2 && VectorLength( ent->s.pos.trDelta ) < 40 ) - { - G_SetOrigin( ent, trace->endpos ); + if (trace->plane.normal[2] > 0.2 && VectorLength(ent->s.pos.trDelta) < 40) { + G_SetOrigin(ent, trace->endpos); return; } } - if (ent->s.weapon == WP_THERMAL) - { //slight hack for hit sound + if (ent->s.weapon == WP_THERMAL) { // slight hack for hit sound G_Sound(ent, CHAN_BODY, G_SoundIndex(va("sound/weapons/thermal/bounce%i.wav", Q_irand(1, 2)))); - } - else if (ent->s.weapon == WP_SABER) - { + } else if (ent->s.weapon == WP_SABER) { G_Sound(ent, CHAN_BODY, G_SoundIndex(va("sound/weapons/saber/bounce%i.wav", Q_irand(1, 3)))); - } - else if (ent->s.weapon == G2_MODEL_PART) - { - //Limb bounce sound? + } else if (ent->s.weapon == G2_MODEL_PART) { + // Limb bounce sound? } - VectorAdd( ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin); - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); + VectorAdd(ent->r.currentOrigin, trace->plane.normal, ent->r.currentOrigin); + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; - if (ent->bounceCount != -5) - { + if (ent->bounceCount != -5) { ent->bounceCount--; } } - /* ================ G_ExplodeMissile @@ -218,61 +190,53 @@ G_ExplodeMissile Explode a missile without an impact ================ */ -void G_ExplodeMissile( gentity_t *ent ) { - vec3_t dir; - vec3_t origin; +void G_ExplodeMissile(gentity_t *ent) { + vec3_t dir; + vec3_t origin; - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); - SnapVector( origin ); - G_SetOrigin( ent, origin ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); + SnapVector(origin); + G_SetOrigin(ent, origin); // we don't have a valid direction, so just point straight up dir[0] = dir[1] = 0; dir[2] = 1; ent->s.eType = ET_GENERAL; - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); + G_AddEvent(ent, EV_MISSILE_MISS, DirToByte(dir)); ent->freeAfterEvent = qtrue; ent->takedamage = qfalse; // splash damage - if ( ent->splashDamage ) { - if( G_RadiusDamage( ent->r.currentOrigin, ent->parent, ent->splashDamage, ent->splashRadius, ent, - ent, ent->splashMethodOfDeath ) ) - { - if (ent->parent) - { + if (ent->splashDamage) { + if (G_RadiusDamage(ent->r.currentOrigin, ent->parent, ent->splashDamage, ent->splashRadius, ent, ent, ent->splashMethodOfDeath)) { + if (ent->parent) { g_entities[ent->parent->s.number].client->accuracy_hits++; - } - else if (ent->activator) - { + } else if (ent->activator) { g_entities[ent->activator->s.number].client->accuracy_hits++; } } } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } -void G_RunStuckMissile( gentity_t *ent ) -{ - if ( ent->takedamage ) - { - if ( ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD ) - { +void G_RunStuckMissile(gentity_t *ent) { + if (ent->takedamage) { + if (ent->s.groundEntityNum >= 0 && ent->s.groundEntityNum < ENTITYNUM_WORLD) { gentity_t *other = &g_entities[ent->s.groundEntityNum]; - if ( (!VectorCompare( vec3_origin, other->s.pos.trDelta ) && other->s.pos.trType != TR_STATIONARY) || - (!VectorCompare( vec3_origin, other->s.apos.trDelta ) && other->s.apos.trType != TR_STATIONARY) ) - {//thing I stuck to is moving or rotating now, kill me - G_Damage( ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH ); + if ((!VectorCompare(vec3_origin, other->s.pos.trDelta) && other->s.pos.trType != TR_STATIONARY) || + (!VectorCompare(vec3_origin, other->s.apos.trDelta) && + other->s.apos.trType != TR_STATIONARY)) { // thing I stuck to is moving or rotating now, kill me + G_Damage(ent, other, other, NULL, NULL, 99999, 0, MOD_CRUSH); return; } } } // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -280,25 +244,23 @@ void G_RunStuckMissile( gentity_t *ent ) G_BounceProjectile ================ */ -void G_BounceProjectile( vec3_t start, vec3_t impact, vec3_t dir, vec3_t endout ) { +void G_BounceProjectile(vec3_t start, vec3_t impact, vec3_t dir, vec3_t endout) { vec3_t v, newv; float dot; - VectorSubtract( impact, start, v ); - dot = DotProduct( v, dir ); - VectorMA( v, -2*dot, dir, newv ); + VectorSubtract(impact, start, v); + dot = DotProduct(v, dir); + VectorMA(v, -2 * dot, dir, newv); VectorNormalize(newv); VectorMA(impact, 8192, newv, endout); } - //----------------------------------------------------------------------------- -gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, - gentity_t *owner, qboolean altFire) +gentity_t *CreateMissile(vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire) //----------------------------------------------------------------------------- { - gentity_t *missile; + gentity_t *missile; missile = G_Spawn(); @@ -309,46 +271,41 @@ gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, missile->parent = owner; missile->r.ownerNum = owner->s.number; - if (altFire) - { + if (altFire) { missile->s.eFlags |= EF_ALT_FIRING; } missile->s.pos.trType = TR_LINEAR; - missile->s.pos.trTime = level.time;// - MISSILE_PRESTEP_TIME; // NOTENOTE This is a Quake 3 addition over JK2 + missile->s.pos.trTime = level.time; // - MISSILE_PRESTEP_TIME; // NOTENOTE This is a Quake 3 addition over JK2 missile->target_ent = NULL; SnapVector(org); - VectorCopy( org, missile->s.pos.trBase ); - VectorScale( dir, vel, missile->s.pos.trDelta ); - VectorCopy( org, missile->r.currentOrigin); + VectorCopy(org, missile->s.pos.trBase); + VectorScale(dir, vel, missile->s.pos.trDelta); + VectorCopy(org, missile->r.currentOrigin); SnapVector(missile->s.pos.trDelta); return missile; } -void G_MissileBounceEffect( gentity_t *ent, vec3_t org, vec3_t dir ) -{ - //FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect - switch( ent->s.weapon ) - { +void G_MissileBounceEffect(gentity_t *ent, vec3_t org, vec3_t dir) { + // FIXME: have an EV_BOUNCE_MISSILE event that checks the s.weapon and does the appropriate effect + switch (ent->s.weapon) { case WP_BOWCASTER: - G_PlayEffectID( G_EffectIndex("bowcaster/deflect"), ent->r.currentOrigin, dir ); + G_PlayEffectID(G_EffectIndex("bowcaster/deflect"), ent->r.currentOrigin, dir); break; case WP_BLASTER: case WP_BRYAR_PISTOL: - G_PlayEffectID( G_EffectIndex("blaster/deflect"), ent->r.currentOrigin, dir ); - break; - default: - { - gentity_t *te = G_TempEntity( org, EV_SABER_BLOCK ); - VectorCopy(org, te->s.origin); - VectorCopy(dir, te->s.angles); - te->s.eventParm = 0; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum - } + G_PlayEffectID(G_EffectIndex("blaster/deflect"), ent->r.currentOrigin, dir); break; + default: { + gentity_t *te = G_TempEntity(org, EV_SABER_BLOCK); + VectorCopy(org, te->s.origin); + VectorCopy(dir, te->s.angles); + te->s.eventParm = 0; + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum + } break; } } @@ -357,29 +314,24 @@ void G_MissileBounceEffect( gentity_t *ent, vec3_t org, vec3_t dir ) G_MissileImpact ================ */ -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ); -void WP_flechette_alt_blow( gentity_t *ent ); -void G_MissileImpact( gentity_t *ent, trace_t *trace ) { - gentity_t *other; - qboolean hitClient = qfalse; - qboolean isKnockedSaber = qfalse; +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock); +void WP_flechette_alt_blow(gentity_t *ent); +void G_MissileImpact(gentity_t *ent, trace_t *trace) { + gentity_t *other; + qboolean hitClient = qfalse; + qboolean isKnockedSaber = qfalse; other = &g_entities[trace->entityNum]; // check for bounce - if ( !other->takedamage && - (ent->bounceCount > 0 || ent->bounceCount == -5) && - ( ent->flags & ( FL_BOUNCE | FL_BOUNCE_HALF ) ) ) { - G_BounceMissile( ent, trace ); - G_AddEvent( ent, EV_GRENADE_BOUNCE, 0 ); + if (!other->takedamage && (ent->bounceCount > 0 || ent->bounceCount == -5) && (ent->flags & (FL_BOUNCE | FL_BOUNCE_HALF))) { + G_BounceMissile(ent, trace); + G_AddEvent(ent, EV_GRENADE_BOUNCE, 0); return; - } - else if (ent->neverFree && ent->s.weapon == WP_SABER && (ent->flags & FL_BOUNCE_HALF)) - { //this is a knocked-away saber - if (ent->bounceCount > 0 || ent->bounceCount == -5) - { - G_BounceMissile( ent, trace ); - G_AddEvent( ent, EV_GRENADE_BOUNCE, 0 ); + } else if (ent->neverFree && ent->s.weapon == WP_SABER && (ent->flags & FL_BOUNCE_HALF)) { // this is a knocked-away saber + if (ent->bounceCount > 0 || ent->bounceCount == -5) { + G_BounceMissile(ent, trace); + G_AddEvent(ent, EV_GRENADE_BOUNCE, 0); return; } @@ -387,12 +339,11 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { } // I would glom onto the FL_BOUNCE code section above, but don't feel like risking breaking something else - if ( (!other->takedamage && (ent->bounceCount > 0 || ent->bounceCount == -5) && ( ent->flags&(FL_BOUNCE_SHRAPNEL) ) ) || ((trace->surfaceFlags&SURF_FORCEFIELD)&&!ent->splashDamage&&!ent->splashRadius&&(ent->bounceCount > 0 || ent->bounceCount == -5)) ) - { - G_BounceMissile( ent, trace ); + if ((!other->takedamage && (ent->bounceCount > 0 || ent->bounceCount == -5) && (ent->flags & (FL_BOUNCE_SHRAPNEL))) || + ((trace->surfaceFlags & SURF_FORCEFIELD) && !ent->splashDamage && !ent->splashRadius && (ent->bounceCount > 0 || ent->bounceCount == -5))) { + G_BounceMissile(ent, trace); - if ( ent->bounceCount < 1 ) - { + if (ent->bounceCount < 1) { ent->flags &= ~FL_BOUNCE_SHRAPNEL; } return; @@ -411,50 +362,29 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { } */ - if ((other->r.contents & CONTENTS_LIGHTSABER) && !isKnockedSaber) - { //hit this person's saber, so.. + if ((other->r.contents & CONTENTS_LIGHTSABER) && !isKnockedSaber) { // hit this person's saber, so.. gentity_t *otherOwner = &g_entities[other->r.ownerNum]; - if (otherOwner->takedamage && otherOwner->client && otherOwner->client->ps.duelInProgress && - otherOwner->client->ps.duelIndex != ent->r.ownerNum) - { + if (otherOwner->takedamage && otherOwner->client && otherOwner->client->ps.duelInProgress && otherOwner->client->ps.duelIndex != ent->r.ownerNum) { goto killProj; } - } - else if (!isKnockedSaber) - { - if (other->takedamage && other->client && other->client->ps.duelInProgress && - other->client->ps.duelIndex != ent->r.ownerNum) - { + } else if (!isKnockedSaber) { + if (other->takedamage && other->client && other->client->ps.duelInProgress && other->client->ps.duelIndex != ent->r.ownerNum) { goto killProj; } } - if (other->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) - { - if (ent->methodOfDeath != MOD_REPEATER_ALT && - ent->methodOfDeath != MOD_ROCKET && - ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && - ent->methodOfDeath != MOD_ROCKET_HOMING && - ent->methodOfDeath != MOD_THERMAL && - ent->methodOfDeath != MOD_THERMAL_SPLASH && - ent->methodOfDeath != MOD_TRIP_MINE_SPLASH && - ent->methodOfDeath != MOD_TIMED_MINE_SPLASH && - ent->methodOfDeath != MOD_DET_PACK_SPLASH && - ent->methodOfDeath != MOD_VEHICLE && - ent->methodOfDeath != MOD_CONC && - ent->methodOfDeath != MOD_CONC_ALT && - ent->methodOfDeath != MOD_SABER && - ent->methodOfDeath != MOD_TURBLAST) - { + if (other->flags & FL_DMG_BY_HEAVY_WEAP_ONLY) { + if (ent->methodOfDeath != MOD_REPEATER_ALT && ent->methodOfDeath != MOD_ROCKET && ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && + ent->methodOfDeath != MOD_ROCKET_HOMING && ent->methodOfDeath != MOD_THERMAL && ent->methodOfDeath != MOD_THERMAL_SPLASH && + ent->methodOfDeath != MOD_TRIP_MINE_SPLASH && ent->methodOfDeath != MOD_TIMED_MINE_SPLASH && ent->methodOfDeath != MOD_DET_PACK_SPLASH && + ent->methodOfDeath != MOD_VEHICLE && ent->methodOfDeath != MOD_CONC && ent->methodOfDeath != MOD_CONC_ALT && ent->methodOfDeath != MOD_SABER && + ent->methodOfDeath != MOD_TURBLAST) { vec3_t fwd; - if (trace) - { + if (trace) { VectorCopy(trace->plane.normal, fwd); - } - else - { //oh well + } else { // oh well AngleVectors(other->r.currentAngles, fwd, NULL, NULL); } @@ -464,29 +394,15 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { } } - if ((other->flags & FL_SHIELDED) && - ent->s.weapon != WP_ROCKET_LAUNCHER && - ent->s.weapon != WP_THERMAL && - ent->s.weapon != WP_TRIP_MINE && - ent->s.weapon != WP_DET_PACK && - ent->s.weapon != WP_DEMP2 && - ent->s.weapon != WP_EMPLACED_GUN && - ent->methodOfDeath != MOD_REPEATER_ALT && - ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && - ent->methodOfDeath != MOD_TURBLAST && - ent->methodOfDeath != MOD_VEHICLE && - ent->methodOfDeath != MOD_CONC && - ent->methodOfDeath != MOD_CONC_ALT && - !(ent->dflags&DAMAGE_HEAVY_WEAP_CLASS) ) - { + if ((other->flags & FL_SHIELDED) && ent->s.weapon != WP_ROCKET_LAUNCHER && ent->s.weapon != WP_THERMAL && ent->s.weapon != WP_TRIP_MINE && + ent->s.weapon != WP_DET_PACK && ent->s.weapon != WP_DEMP2 && ent->s.weapon != WP_EMPLACED_GUN && ent->methodOfDeath != MOD_REPEATER_ALT && + ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && ent->methodOfDeath != MOD_TURBLAST && ent->methodOfDeath != MOD_VEHICLE && + ent->methodOfDeath != MOD_CONC && ent->methodOfDeath != MOD_CONC_ALT && !(ent->dflags & DAMAGE_HEAVY_WEAP_CLASS)) { vec3_t fwd; - if (other->client) - { + if (other->client) { AngleVectors(other->client->ps.viewangles, fwd, NULL, NULL); - } - else - { + } else { AngleVectors(other->r.currentAngles, fwd, NULL, NULL); } @@ -495,76 +411,57 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { return; } - if (other->takedamage && other->client && - ent->s.weapon != WP_ROCKET_LAUNCHER && - ent->s.weapon != WP_THERMAL && - ent->s.weapon != WP_TRIP_MINE && - ent->s.weapon != WP_DET_PACK && - ent->s.weapon != WP_DEMP2 && - ent->methodOfDeath != MOD_REPEATER_ALT && - ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && - ent->methodOfDeath != MOD_CONC && - ent->methodOfDeath != MOD_CONC_ALT && - other->client->ps.saberBlockTime < level.time && - !isKnockedSaber && - WP_SaberCanBlock(other, ent->r.currentOrigin, 0, 0, qtrue, 0)) - { //only block one projectile per 200ms (to prevent giant swarms of projectiles being blocked) + if (other->takedamage && other->client && ent->s.weapon != WP_ROCKET_LAUNCHER && ent->s.weapon != WP_THERMAL && ent->s.weapon != WP_TRIP_MINE && + ent->s.weapon != WP_DET_PACK && ent->s.weapon != WP_DEMP2 && ent->methodOfDeath != MOD_REPEATER_ALT && ent->methodOfDeath != MOD_FLECHETTE_ALT_SPLASH && + ent->methodOfDeath != MOD_CONC && ent->methodOfDeath != MOD_CONC_ALT && other->client->ps.saberBlockTime < level.time && !isKnockedSaber && + WP_SaberCanBlock(other, ent->r.currentOrigin, 0, 0, qtrue, + 0)) { // only block one projectile per 200ms (to prevent giant swarms of projectiles being blocked) vec3_t fwd; gentity_t *te; int otherDefLevel = other->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]; - te = G_TempEntity( ent->r.currentOrigin, EV_SABER_BLOCK ); + te = G_TempEntity(ent->r.currentOrigin, EV_SABER_BLOCK); VectorCopy(ent->r.currentOrigin, te->s.origin); VectorCopy(trace->plane.normal, te->s.angles); te->s.eventParm = 0; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum /*if (other->client->ps.velocity[2] > 0 || other->client->pers.cmd.forwardmove || other->client->pers.cmd.rightmove) */ if (other->client->ps.velocity[2] > 0 || - other->client->pers.cmd.forwardmove < 0) //now we only do it if jumping or running backward. Should be able to full-on charge. + other->client->pers.cmd.forwardmove < 0) // now we only do it if jumping or running backward. Should be able to full-on charge. { otherDefLevel -= 1; - if (otherDefLevel < 0) - { + if (otherDefLevel < 0) { otherDefLevel = 0; } } AngleVectors(other->client->ps.viewangles, fwd, NULL, NULL); - if (otherDefLevel == FORCE_LEVEL_1) - { - //if def is only level 1, instead of deflecting the shot it should just die here - } - else if (otherDefLevel == FORCE_LEVEL_2) - { + if (otherDefLevel == FORCE_LEVEL_1) { + // if def is only level 1, instead of deflecting the shot it should just die here + } else if (otherDefLevel == FORCE_LEVEL_2) { G_DeflectMissile(other, ent, fwd); - } - else - { + } else { G_ReflectMissile(other, ent, fwd); } - other->client->ps.saberBlockTime = level.time + (350 - (otherDefLevel*100)); //200; + other->client->ps.saberBlockTime = level.time + (350 - (otherDefLevel * 100)); // 200; - //For jedi AI + // For jedi AI other->client->ps.saberEventFlags |= SEF_DEFLECTED; - if (otherDefLevel == FORCE_LEVEL_3) - { + if (otherDefLevel == FORCE_LEVEL_3) { other->client->ps.saberBlockTime = 0; //^_^ } - if (otherDefLevel == FORCE_LEVEL_1) - { + if (otherDefLevel == FORCE_LEVEL_1) { goto killProj; } return; - } - else if ((other->r.contents & CONTENTS_LIGHTSABER) && !isKnockedSaber) - { //hit this person's saber, so.. + } else if ((other->r.contents & CONTENTS_LIGHTSABER) && !isKnockedSaber) { // hit this person's saber, so.. gentity_t *otherOwner = &g_entities[other->r.ownerNum]; if (otherOwner->takedamage && otherOwner->client && @@ -583,59 +480,50 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { gentity_t *te; int otherDefLevel = otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]; - //in this case, deflect it even if we can't actually block it because it hit our saber - //WP_SaberCanBlock(otherOwner, ent->r.currentOrigin, 0, 0, qtrue, 0); - if (otherOwner->client && otherOwner->client->ps.weaponTime <= 0) - { + // in this case, deflect it even if we can't actually block it because it hit our saber + // WP_SaberCanBlock(otherOwner, ent->r.currentOrigin, 0, 0, qtrue, 0); + if (otherOwner->client && otherOwner->client->ps.weaponTime <= 0) { WP_SaberBlockNonRandom(otherOwner, ent->r.currentOrigin, qtrue); } - te = G_TempEntity( ent->r.currentOrigin, EV_SABER_BLOCK ); + te = G_TempEntity(ent->r.currentOrigin, EV_SABER_BLOCK); VectorCopy(ent->r.currentOrigin, te->s.origin); VectorCopy(trace->plane.normal, te->s.angles); te->s.eventParm = 0; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum /*if (otherOwner->client->ps.velocity[2] > 0 || otherOwner->client->pers.cmd.forwardmove || otherOwner->client->pers.cmd.rightmove)*/ if (otherOwner->client->ps.velocity[2] > 0 || - otherOwner->client->pers.cmd.forwardmove < 0) //now we only do it if jumping or running backward. Should be able to full-on charge. + otherOwner->client->pers.cmd.forwardmove < 0) // now we only do it if jumping or running backward. Should be able to full-on charge. { otherDefLevel -= 1; - if (otherDefLevel < 0) - { + if (otherDefLevel < 0) { otherDefLevel = 0; } } AngleVectors(otherOwner->client->ps.viewangles, fwd, NULL, NULL); - if (otherDefLevel == FORCE_LEVEL_1) - { - //if def is only level 1, instead of deflecting the shot it should just die here - } - else if (otherDefLevel == FORCE_LEVEL_2) - { + if (otherDefLevel == FORCE_LEVEL_1) { + // if def is only level 1, instead of deflecting the shot it should just die here + } else if (otherDefLevel == FORCE_LEVEL_2) { G_DeflectMissile(otherOwner, ent, fwd); - } - else - { + } else { G_ReflectMissile(otherOwner, ent, fwd); } - otherOwner->client->ps.saberBlockTime = level.time + (350 - (otherDefLevel*100));//200; + otherOwner->client->ps.saberBlockTime = level.time + (350 - (otherDefLevel * 100)); // 200; - //For jedi AI + // For jedi AI otherOwner->client->ps.saberEventFlags |= SEF_DEFLECTED; - if (otherDefLevel == FORCE_LEVEL_3) - { + if (otherDefLevel == FORCE_LEVEL_3) { otherOwner->client->ps.saberBlockTime = 0; //^_^ } - if (otherDefLevel == FORCE_LEVEL_1) - { + if (otherDefLevel == FORCE_LEVEL_1) { goto killProj; } return; @@ -643,34 +531,30 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { } // check for sticking - if ( !other->takedamage && ( ent->s.eFlags & EF_MISSILE_STICK ) ) - { - laserTrapStick( ent, trace->endpos, trace->plane.normal ); - G_AddEvent( ent, EV_MISSILE_STICK, 0 ); + if (!other->takedamage && (ent->s.eFlags & EF_MISSILE_STICK)) { + laserTrapStick(ent, trace->endpos, trace->plane.normal); + G_AddEvent(ent, EV_MISSILE_STICK, 0); return; } // impact damage if (other->takedamage && !isKnockedSaber) { // FIXME: wrong damage direction? - if ( ent->damage ) { - vec3_t velocity; + if (ent->damage) { + vec3_t velocity; qboolean didDmg = qfalse; - if( LogAccuracyHit( other, &g_entities[ent->r.ownerNum] ) ) { + if (LogAccuracyHit(other, &g_entities[ent->r.ownerNum])) { g_entities[ent->r.ownerNum].client->accuracy_hits++; hitClient = qtrue; } - BG_EvaluateTrajectoryDelta( &ent->s.pos, level.time, velocity ); - if ( VectorLength( velocity ) == 0 ) { - velocity[2] = 1; // stepped on a grenade + BG_EvaluateTrajectoryDelta(&ent->s.pos, level.time, velocity); + if (VectorLength(velocity) == 0) { + velocity[2] = 1; // stepped on a grenade } - if (ent->s.weapon == WP_BOWCASTER || ent->s.weapon == WP_FLECHETTE || - ent->s.weapon == WP_ROCKET_LAUNCHER) - { - if (ent->s.weapon == WP_FLECHETTE && (ent->s.eFlags & EF_ALT_FIRING)) - { + if (ent->s.weapon == WP_BOWCASTER || ent->s.weapon == WP_FLECHETTE || ent->s.weapon == WP_ROCKET_LAUNCHER) { + if (ent->s.weapon == WP_FLECHETTE && (ent->s.eFlags & EF_ALT_FIRING)) { /* fix: there are rare situations where flechette did explode by timeout AND by impact in the very same frame, then here ent->think was set to G_FreeEntity, so the folowing think @@ -682,82 +566,63 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { very rare flag dissappearing bug. */ if (ent->think == WP_flechette_alt_blow) ent->think(ent); - } - else - { - G_Damage (other, ent, &g_entities[ent->r.ownerNum], velocity, - /*ent->s.origin*/ent->r.currentOrigin, ent->damage, - DAMAGE_HALF_ABSORB, ent->methodOfDeath); + } else { + G_Damage(other, ent, &g_entities[ent->r.ownerNum], velocity, + /*ent->s.origin*/ ent->r.currentOrigin, ent->damage, DAMAGE_HALF_ABSORB, ent->methodOfDeath); didDmg = qtrue; } - } - else - { - G_Damage (other, ent, &g_entities[ent->r.ownerNum], velocity, - /*ent->s.origin*/ent->r.currentOrigin, ent->damage, - 0, ent->methodOfDeath); + } else { + G_Damage(other, ent, &g_entities[ent->r.ownerNum], velocity, + /*ent->s.origin*/ ent->r.currentOrigin, ent->damage, 0, ent->methodOfDeath); didDmg = qtrue; } - if (didDmg && other && other->client) - { //What I'm wondering is why this isn't in the NPC pain funcs. But this is what SP does, so whatever. - class_t npc_class = other->client->NPC_class; + if (didDmg && other && other->client) { // What I'm wondering is why this isn't in the NPC pain funcs. But this is what SP does, so whatever. + class_t npc_class = other->client->NPC_class; // If we are a robot and we aren't currently doing the full body electricity... - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || - npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || //npc_class == CLASS_PROTOCOL ||//no protocol, looks odd - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || + npc_class == CLASS_R5D2 || npc_class == CLASS_REMOTE || npc_class == CLASS_MARK1 || + npc_class == CLASS_MARK2 || // npc_class == CLASS_PROTOCOL ||//no protocol, looks odd + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { // special droid only behaviors - if ( other->client->ps.electrifyTime < level.time + 100 ) - { + if (other->client->ps.electrifyTime < level.time + 100) { // ... do the effect for a split second for some more feedback other->client->ps.electrifyTime = level.time + 450; } - //FIXME: throw some sparks off droids,too + // FIXME: throw some sparks off droids,too } } } - if ( ent->s.weapon == WP_DEMP2 ) - {//a hit with demp2 decloaks people, disables ships - if ( other && other->client && other->client->NPC_class == CLASS_VEHICLE ) - {//hit a vehicle - if ( other->m_pVehicle //valid vehicle ent - && other->m_pVehicle->m_pVehicleInfo//valid stats - && (other->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER//always affect speeders - ||(other->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && ent->classname && Q_stricmp("vehicle_proj", ent->classname ) == 0) )//only vehicle ion weapons affect a fighter in this manner - && !FighterIsLanded( other->m_pVehicle , &other->client->ps )//not landed - && !(other->spawnflags&2) )//and not suspended - {//vehicles hit by "ion cannons" lose control - if ( other->client->ps.electrifyTime > level.time ) - {//add onto it - //FIXME: extern the length of the "out of control" time? - other->client->ps.electrifyTime += Q_irand(200,500); - if ( other->client->ps.electrifyTime > level.time + 4000 ) - {//cap it + if (ent->s.weapon == WP_DEMP2) { // a hit with demp2 decloaks people, disables ships + if (other && other->client && other->client->NPC_class == CLASS_VEHICLE) { // hit a vehicle + if (other->m_pVehicle // valid vehicle ent + && other->m_pVehicle->m_pVehicleInfo // valid stats + && (other->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER // always affect speeders + || (other->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && ent->classname && + Q_stricmp("vehicle_proj", ent->classname) == 0)) // only vehicle ion weapons affect a fighter in this manner + && !FighterIsLanded(other->m_pVehicle, &other->client->ps) // not landed + && !(other->spawnflags & 2)) // and not suspended + { // vehicles hit by "ion cannons" lose control + if (other->client->ps.electrifyTime > level.time) { // add onto it + // FIXME: extern the length of the "out of control" time? + other->client->ps.electrifyTime += Q_irand(200, 500); + if (other->client->ps.electrifyTime > level.time + 4000) { // cap it other->client->ps.electrifyTime = level.time + 4000; } - } - else - {//start it - //FIXME: extern the length of the "out of control" time? - other->client->ps.electrifyTime = level.time + Q_irand(200,500); + } else { // start it + // FIXME: extern the length of the "out of control" time? + other->client->ps.electrifyTime = level.time + Q_irand(200, 500); } } - } - else if ( other && other->client && other->client->ps.powerups[PW_CLOAKED] ) - { - Jedi_Decloak( other ); - if ( ent->methodOfDeath == MOD_DEMP2_ALT ) - {//direct hit with alt disables cloak forever - //permanently disable the saboteur's cloak + } else if (other && other->client && other->client->ps.powerups[PW_CLOAKED]) { + Jedi_Decloak(other); + if (ent->methodOfDeath == MOD_DEMP2_ALT) { // direct hit with alt disables cloak forever + // permanently disable the saboteur's cloak other->client->cloakToggleTime = Q3_INFINITE; - } - else - {//temp disable - other->client->cloakToggleTime = level.time + Q_irand( 3000, 10000 ); + } else { // temp disable + other->client->cloakToggleTime = level.time + Q_irand(3000, 10000); } } } @@ -766,45 +631,41 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { // is it cheaper in bandwidth to just remove this ent and create a new // one, rather than changing the missile into the explosion? - if ( other->takedamage && other->client && !isKnockedSaber ) { - G_AddEvent( ent, EV_MISSILE_HIT, DirToByte( trace->plane.normal ) ); + if (other->takedamage && other->client && !isKnockedSaber) { + G_AddEvent(ent, EV_MISSILE_HIT, DirToByte(trace->plane.normal)); ent->s.otherEntityNum = other->s.number; - } else if( trace->surfaceFlags & SURF_METALSTEPS ) { - G_AddEvent( ent, EV_MISSILE_MISS_METAL, DirToByte( trace->plane.normal ) ); + } else if (trace->surfaceFlags & SURF_METALSTEPS) { + G_AddEvent(ent, EV_MISSILE_MISS_METAL, DirToByte(trace->plane.normal)); } else if (ent->s.weapon != G2_MODEL_PART && !isKnockedSaber) { - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( trace->plane.normal ) ); + G_AddEvent(ent, EV_MISSILE_MISS, DirToByte(trace->plane.normal)); } - if (!isKnockedSaber) - { + if (!isKnockedSaber) { ent->freeAfterEvent = qtrue; // change over to a normal entity right at the point of impact ent->s.eType = ET_GENERAL; } - SnapVectorTowards( trace->endpos, ent->s.pos.trBase ); // save net bandwidth + SnapVectorTowards(trace->endpos, ent->s.pos.trBase); // save net bandwidth - G_SetOrigin( ent, trace->endpos ); + G_SetOrigin(ent, trace->endpos); ent->takedamage = qfalse; // splash damage (doesn't apply to person directly hit) - if ( ent->splashDamage ) { - if( G_RadiusDamage( trace->endpos, ent->parent, ent->splashDamage, ent->splashRadius, - other, ent, ent->splashMethodOfDeath ) ) { - if( !hitClient - && g_entities[ent->r.ownerNum].client ) { + if (ent->splashDamage) { + if (G_RadiusDamage(trace->endpos, ent->parent, ent->splashDamage, ent->splashRadius, other, ent, ent->splashMethodOfDeath)) { + if (!hitClient && g_entities[ent->r.ownerNum].client) { g_entities[ent->r.ownerNum].client->accuracy_hits++; } } } - if (ent->s.weapon == G2_MODEL_PART) - { - ent->freeAfterEvent = qfalse; //it will free itself + if (ent->s.weapon == G2_MODEL_PART) { + ent->freeAfterEvent = qfalse; // it will free itself } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -812,124 +673,105 @@ void G_MissileImpact( gentity_t *ent, trace_t *trace ) { G_RunMissile ================ */ -void G_RunMissile( gentity_t *ent ) { - vec3_t origin, groundSpot; - trace_t tr; - int passent; - qboolean isKnockedSaber = qfalse; - - if (ent->neverFree && ent->s.weapon == WP_SABER && (ent->flags & FL_BOUNCE_HALF)) - { +void G_RunMissile(gentity_t *ent) { + vec3_t origin, groundSpot; + trace_t tr; + int passent; + qboolean isKnockedSaber = qfalse; + + if (ent->neverFree && ent->s.weapon == WP_SABER && (ent->flags & FL_BOUNCE_HALF)) { isKnockedSaber = qtrue; ent->s.pos.trType = TR_GRAVITY; } // get current position - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); // if this missile bounced off an invulnerability sphere - if ( ent->target_ent ) { + if (ent->target_ent) { passent = ent->target_ent->s.number; - } - else { + } else { // ignore interactions with the missile owner - if ( (ent->r.svFlags&SVF_OWNERNOTSHARED) - && (ent->s.eFlags&EF_JETPACK_ACTIVE) ) - {//A vehicle missile that should be solid to its owner - //I don't care about hitting my owner + if ((ent->r.svFlags & SVF_OWNERNOTSHARED) && (ent->s.eFlags & EF_JETPACK_ACTIVE)) { // A vehicle missile that should be solid to its owner + // I don't care about hitting my owner passent = ent->s.number; - } - else - { + } else { passent = ent->r.ownerNum; } } // trace a line from the previous position to the current position - if (d_projectileGhoul2Collision.integer) - { - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passent, ent->clipmask, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_THICK|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); + if (d_projectileGhoul2Collision.integer) { + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passent, ent->clipmask, qfalse, + G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_THICK | G2TRFLAG_HITCORPSES, g_g2TraceLod.integer); - if (tr.fraction != 1.0 && tr.entityNum < ENTITYNUM_WORLD) - { + if (tr.fraction != 1.0 && tr.entityNum < ENTITYNUM_WORLD) { gentity_t *g2Hit = &g_entities[tr.entityNum]; - if (g2Hit->inuse && g2Hit->client && g2Hit->ghoul2) - { //since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the index of the surface on the ghoul2 model we collided with. + if (g2Hit->inuse && g2Hit->client && g2Hit->ghoul2) { // since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the index of the + // surface on the ghoul2 model we collided with. g2Hit->client->g2LastSurfaceHit = tr.surfaceFlags; g2Hit->client->g2LastSurfaceTime = level.time; } - if (g2Hit->ghoul2) - { - tr.surfaceFlags = 0; //clear the surface flags after, since we actually care about them in here. + if (g2Hit->ghoul2) { + tr.surfaceFlags = 0; // clear the surface flags after, since we actually care about them in here. } } - } - else - { - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passent, ent->clipmask, qfalse, 0, 0 ); + } else { + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passent, ent->clipmask, qfalse, 0, 0); } - if ( tr.startsolid || tr.allsolid ) { + if (tr.startsolid || tr.allsolid) { // make sure the tr.entityNum is set to the entity we're stuck in - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, passent, ent->clipmask, qfalse, 0, 0 ); + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, ent->r.currentOrigin, passent, ent->clipmask, qfalse, 0, 0); tr.fraction = 0; - } - else { - VectorCopy( tr.endpos, ent->r.currentOrigin ); + } else { + VectorCopy(tr.endpos, ent->r.currentOrigin); } - if (ent->passThroughNum && tr.entityNum == (ent->passThroughNum-1)) - { - VectorCopy( origin, ent->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)ent ); + if (ent->passThroughNum && tr.entityNum == (ent->passThroughNum - 1)) { + VectorCopy(origin, ent->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)ent); goto passthrough; } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); - if (ent->s.weapon == G2_MODEL_PART && !ent->bounceCount) - { + if (ent->s.weapon == G2_MODEL_PART && !ent->bounceCount) { vec3_t lowerOrg; trace_t trG; VectorCopy(ent->r.currentOrigin, lowerOrg); lowerOrg[2] -= 1; - trap->Trace( &trG, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, lowerOrg, passent, ent->clipmask, qfalse, 0, 0 ); + trap->Trace(&trG, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, lowerOrg, passent, ent->clipmask, qfalse, 0, 0); VectorCopy(trG.endpos, groundSpot); - if (!trG.startsolid && !trG.allsolid && trG.entityNum == ENTITYNUM_WORLD) - { + if (!trG.startsolid && !trG.allsolid && trG.entityNum == ENTITYNUM_WORLD) { ent->s.groundEntityNum = trG.entityNum; - } - else - { + } else { ent->s.groundEntityNum = ENTITYNUM_NONE; } } - if ( tr.fraction != 1) { + if (tr.fraction != 1) { // never explode or bounce on sky - if ( tr.surfaceFlags & SURF_NOIMPACT ) { + if (tr.surfaceFlags & SURF_NOIMPACT) { // If grapple, reset owner if (ent->parent && ent->parent->client && ent->parent->client->hook == ent) { ent->parent->client->hook = NULL; } - if ((ent->s.weapon == WP_SABER && ent->isSaberEntity) || isKnockedSaber) - { - G_RunThink( ent ); + if ((ent->s.weapon == WP_SABER && ent->isSaberEntity) || isKnockedSaber) { + G_RunThink(ent); return; - } - else if (ent->s.weapon != G2_MODEL_PART) - { - G_FreeEntity( ent ); + } else if (ent->s.weapon != G2_MODEL_PART) { + G_FreeEntity(ent); return; } } -#if 0 //will get stomped with missile impact event... +#if 0 // will get stomped with missile impact event... if (ent->s.weapon > WP_NONE && ent->s.weapon < WP_NUM_WEAPONS && (tr.entityNum < MAX_CLIENTS || g_entities[tr.entityNum].s.eType == ET_NPC)) { //player or NPC, try making a mark on him @@ -966,43 +808,36 @@ void G_RunMissile( gentity_t *ent ) { } #else if (ent->s.weapon > WP_NONE && ent->s.weapon < WP_NUM_WEAPONS && - (tr.entityNum < MAX_CLIENTS || g_entities[tr.entityNum].s.eType == ET_NPC)) - { //player or NPC, try making a mark on him - //copy current pos to s.origin, and current projected traj to origin2 + (tr.entityNum < MAX_CLIENTS || g_entities[tr.entityNum].s.eType == ET_NPC)) { // player or NPC, try making a mark on him + // copy current pos to s.origin, and current projected traj to origin2 VectorCopy(ent->r.currentOrigin, ent->s.origin); - BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->s.origin2 ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, ent->s.origin2); - if (VectorCompare(ent->s.origin, ent->s.origin2)) - { - ent->s.origin2[2] += 2.0f; //whatever, at least it won't mess up. + if (VectorCompare(ent->s.origin, ent->s.origin2)) { + ent->s.origin2[2] += 2.0f; // whatever, at least it won't mess up. } } #endif - G_MissileImpact( ent, &tr ); + G_MissileImpact(ent, &tr); - if (tr.entityNum == ent->s.otherEntityNum) - { //if the impact event other and the trace ent match then it's ok to do the g2 mark + if (tr.entityNum == ent->s.otherEntityNum) { // if the impact event other and the trace ent match then it's ok to do the g2 mark ent->s.trickedentindex = 1; } - if ( ent->s.eType != ET_MISSILE && ent->s.weapon != G2_MODEL_PART ) - { - return; // exploded + if (ent->s.eType != ET_MISSILE && ent->s.weapon != G2_MODEL_PART) { + return; // exploded } } passthrough: - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//stuck missiles should check some special stuff - G_RunStuckMissile( ent ); + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // stuck missiles should check some special stuff + G_RunStuckMissile(ent); return; } - if (ent->s.weapon == G2_MODEL_PART) - { - if (ent->s.groundEntityNum == ENTITYNUM_WORLD) - { + if (ent->s.weapon == G2_MODEL_PART) { + if (ent->s.groundEntityNum == ENTITYNUM_WORLD) { ent->s.pos.trType = TR_LINEAR; VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; @@ -1010,8 +845,7 @@ void G_RunMissile( gentity_t *ent ) { VectorCopy(groundSpot, ent->s.pos.trBase); VectorCopy(groundSpot, ent->r.currentOrigin); - if (ent->s.apos.trType != TR_STATIONARY) - { + if (ent->s.apos.trType != TR_STATIONARY) { ent->s.apos.trType = TR_STATIONARY; ent->s.apos.trTime = level.time; @@ -1022,12 +856,7 @@ void G_RunMissile( gentity_t *ent ) { } // check think function after bouncing - G_RunThink( ent ); + G_RunThink(ent); } - //============================================================================= - - - - diff --git a/codemp/game/g_mover.c b/codemp/game/g_mover.c index 105aa92132..cbbfd1278b 100644 --- a/codemp/game/g_mover.c +++ b/codemp/game/g_mover.c @@ -24,7 +24,6 @@ along with this program; if not, see . #include "g_local.h" - /* =============================================================================== @@ -33,28 +32,28 @@ PUSHMOVE =============================================================================== */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ); +void MatchTeam(gentity_t *teamLeader, int moverState, int time); typedef struct pushed_s { - gentity_t *ent; - vec3_t origin; - vec3_t angles; - float deltayaw; + gentity_t *ent; + vec3_t origin; + vec3_t angles; + float deltayaw; } pushed_t; -pushed_t pushed[MAX_GENTITIES], *pushed_p; +pushed_t pushed[MAX_GENTITIES], *pushed_p; -#define MOVER_START_ON 1 -#define MOVER_FORCE_ACTIVATE 2 -#define MOVER_CRUSHER 4 -#define MOVER_TOGGLE 8 -#define MOVER_LOCKED 16 -#define MOVER_GOODIE 32 -#define MOVER_PLAYER_USE 64 -#define MOVER_INACTIVE 128 +#define MOVER_START_ON 1 +#define MOVER_FORCE_ACTIVATE 2 +#define MOVER_CRUSHER 4 +#define MOVER_TOGGLE 8 +#define MOVER_LOCKED 16 +#define MOVER_GOODIE 32 +#define MOVER_PLAYER_USE 64 +#define MOVER_INACTIVE 128 -int BMS_START = 0; -int BMS_MID = 1; -int BMS_END = 2; +int BMS_START = 0; +int BMS_MID = 1; +int BMS_END = 2; /* ------------------------- @@ -62,10 +61,8 @@ G_PlayDoorLoopSound ------------------------- */ -void G_PlayDoorLoopSound( gentity_t *ent ) -{ - if (!ent->soundSet || !ent->soundSet[0]) - { +void G_PlayDoorLoopSound(gentity_t *ent) { + if (!ent->soundSet || !ent->soundSet[0]) { return; } @@ -85,10 +82,8 @@ G_PlayDoorSound ------------------------- */ -void G_PlayDoorSound( gentity_t *ent, int type ) -{ - if (!ent->soundSet || !ent->soundSet[0]) - { +void G_PlayDoorSound(gentity_t *ent, int type) { + if (!ent->soundSet || !ent->soundSet[0]) { return; } @@ -103,29 +98,28 @@ G_TestEntityPosition ============ */ -gentity_t *G_TestEntityPosition( gentity_t *ent ) { - trace_t tr; - int mask; +gentity_t *G_TestEntityPosition(gentity_t *ent) { + trace_t tr; + int mask; - if ( ent->clipmask ) { + if (ent->clipmask) { mask = ent->clipmask; } else { mask = MASK_SOLID; } - if ( ent->client ) { + if (ent->client) { vec3_t vMax; VectorCopy(ent->r.maxs, vMax); - if (vMax[2] < 1) - { + if (vMax[2] < 1) { vMax[2] = 1; } - trap->Trace( &tr, ent->client->ps.origin, ent->r.mins, vMax, ent->client->ps.origin, ent->s.number, mask, qfalse, 0, 0 ); + trap->Trace(&tr, ent->client->ps.origin, ent->r.mins, vMax, ent->client->ps.origin, ent->s.number, mask, qfalse, 0, 0); } else { - trap->Trace( &tr, ent->s.pos.trBase, ent->r.mins, ent->r.maxs, ent->s.pos.trBase, ent->s.number, mask, qfalse, 0, 0 ); + trap->Trace(&tr, ent->s.pos.trBase, ent->r.mins, ent->r.maxs, ent->s.pos.trBase, ent->s.number, mask, qfalse, 0, 0); } if (tr.startsolid) - return &g_entities[ tr.entityNum ]; + return &g_entities[tr.entityNum]; return NULL; } @@ -175,12 +169,12 @@ G_TryPushingEntity Returns qfalse if the move is blocked ================== */ -qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove ) { - matrix3_t matrix, transpose; - vec3_t org, org2, move2; - gentity_t *block; +qboolean G_TryPushingEntity(gentity_t *check, gentity_t *pusher, vec3_t move, vec3_t amove) { + matrix3_t matrix, transpose; + vec3_t org, org2, move2; + gentity_t *block; - //This was only serverside not to mention it was never set. + // This was only serverside not to mention it was never set. /* // EF_MOVER_STOP will just stop when contacting another entity // instead of pushing it, but entities can still ride on top of it @@ -189,85 +183,80 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v return qfalse; } */ - if ( pusher->s.apos.trType != TR_STATIONARY//rotating - && (pusher->spawnflags&16) //IMPACT - && Q_stricmp( "func_rotating", pusher->classname ) == 0 ) - {//just blow the fuck out of them - G_Damage( check, pusher, pusher, NULL, NULL, pusher->damage, DAMAGE_NO_KNOCKBACK, MOD_CRUSH ); + if (pusher->s.apos.trType != TR_STATIONARY // rotating + && (pusher->spawnflags & 16) // IMPACT + && Q_stricmp("func_rotating", pusher->classname) == 0) { // just blow the fuck out of them + G_Damage(check, pusher, pusher, NULL, NULL, pusher->damage, DAMAGE_NO_KNOCKBACK, MOD_CRUSH); return qtrue; } // save off the old position if (pushed_p > &pushed[MAX_GENTITIES]) { - trap->Error( ERR_DROP, "pushed_p > &pushed[MAX_GENTITIES]" ); + trap->Error(ERR_DROP, "pushed_p > &pushed[MAX_GENTITIES]"); } pushed_p->ent = check; - VectorCopy (check->s.pos.trBase, pushed_p->origin); - VectorCopy (check->s.apos.trBase, pushed_p->angles); - if ( check->client ) { + VectorCopy(check->s.pos.trBase, pushed_p->origin); + VectorCopy(check->s.apos.trBase, pushed_p->angles); + if (check->client) { pushed_p->deltayaw = check->client->ps.delta_angles[YAW]; - VectorCopy (check->client->ps.origin, pushed_p->origin); + VectorCopy(check->client->ps.origin, pushed_p->origin); } pushed_p++; // try moving the contacted entity // figure movement due to the pusher's amove - G_CreateRotationMatrix( amove, transpose ); - G_TransposeMatrix( transpose, matrix ); - if ( check->client ) { - VectorSubtract (check->client->ps.origin, pusher->r.currentOrigin, org); - } - else { - VectorSubtract (check->s.pos.trBase, pusher->r.currentOrigin, org); + G_CreateRotationMatrix(amove, transpose); + G_TransposeMatrix(transpose, matrix); + if (check->client) { + VectorSubtract(check->client->ps.origin, pusher->r.currentOrigin, org); + } else { + VectorSubtract(check->s.pos.trBase, pusher->r.currentOrigin, org); } - VectorCopy( org, org2 ); - G_RotatePoint( org2, matrix ); - VectorSubtract (org2, org, move2); + VectorCopy(org, org2); + G_RotatePoint(org2, matrix); + VectorSubtract(org2, org, move2); // add movement - VectorAdd (check->s.pos.trBase, move, check->s.pos.trBase); - VectorAdd (check->s.pos.trBase, move2, check->s.pos.trBase); - if ( check->client ) { - VectorAdd (check->client->ps.origin, move, check->client->ps.origin); - VectorAdd (check->client->ps.origin, move2, check->client->ps.origin); + VectorAdd(check->s.pos.trBase, move, check->s.pos.trBase); + VectorAdd(check->s.pos.trBase, move2, check->s.pos.trBase); + if (check->client) { + VectorAdd(check->client->ps.origin, move, check->client->ps.origin); + VectorAdd(check->client->ps.origin, move2, check->client->ps.origin); // make sure the client's view rotates when on a rotating mover check->client->ps.delta_angles[YAW] += ANGLE2SHORT(amove[YAW]); } // may have pushed them off an edge - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { check->s.groundEntityNum = ENTITYNUM_NONE; } - block = G_TestEntityPosition( check ); + block = G_TestEntityPosition(check); if (!block) { // pushed ok - if ( check->client ) { - VectorCopy( check->client->ps.origin, check->r.currentOrigin ); + if (check->client) { + VectorCopy(check->client->ps.origin, check->r.currentOrigin); } else { - VectorCopy( check->s.pos.trBase, check->r.currentOrigin ); + VectorCopy(check->s.pos.trBase, check->r.currentOrigin); } - trap->LinkEntity ((sharedEntity_t *)check); + trap->LinkEntity((sharedEntity_t *)check); return qtrue; } - if (check->takedamage && !check->client && check->s.weapon && check->r.ownerNum < MAX_CLIENTS && - check->health < 500) - { - if (check->health > 0) - { + if (check->takedamage && !check->client && check->s.weapon && check->r.ownerNum < MAX_CLIENTS && check->health < 500) { + if (check->health > 0) { G_Damage(check, pusher, pusher, vec3_origin, check->r.currentOrigin, 999, 0, MOD_UNKNOWN); } } // if it is ok to leave in the old position, do it // this is only relevent for riding entities, not pushed // Sliding trapdoors can cause this. - VectorCopy( (pushed_p-1)->origin, check->s.pos.trBase); - if ( check->client ) { - VectorCopy( (pushed_p-1)->origin, check->client->ps.origin); + VectorCopy((pushed_p - 1)->origin, check->s.pos.trBase); + if (check->client) { + VectorCopy((pushed_p - 1)->origin, check->client->ps.origin); } - VectorCopy( (pushed_p-1)->angles, check->s.apos.trBase ); - block = G_TestEntityPosition (check); - if ( !block ) { + VectorCopy((pushed_p - 1)->angles, check->s.apos.trBase); + block = G_TestEntityPosition(check); + if (!block) { check->s.groundEntityNum = ENTITYNUM_NONE; pushed_p--; return qtrue; @@ -277,8 +266,7 @@ qboolean G_TryPushingEntity( gentity_t *check, gentity_t *pusher, vec3_t move, v return qfalse; } - -void G_ExplodeMissile( gentity_t *ent ); +void G_ExplodeMissile(gentity_t *ent); /* ============ @@ -289,42 +277,40 @@ otherwise riders would continue to slide. If qfalse is returned, *obstacle will be the blocking entity ============ */ -void NPC_RemoveBody( gentity_t *self ); -qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle ) { - int i, e; - gentity_t *check; - vec3_t mins, maxs; - pushed_t *p; - int entityList[MAX_GENTITIES]; - int listedEntities; - vec3_t totalMins, totalMaxs; +void NPC_RemoveBody(gentity_t *self); +qboolean G_MoverPush(gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t **obstacle) { + int i, e; + gentity_t *check; + vec3_t mins, maxs; + pushed_t *p; + int entityList[MAX_GENTITIES]; + int listedEntities; + vec3_t totalMins, totalMaxs; *obstacle = NULL; - // mins/maxs are the bounds at the destination // totalMins / totalMaxs are the bounds for the entire move - if ( pusher->r.currentAngles[0] || pusher->r.currentAngles[1] || pusher->r.currentAngles[2] - || amove[0] || amove[1] || amove[2] ) { - float radius; + if (pusher->r.currentAngles[0] || pusher->r.currentAngles[1] || pusher->r.currentAngles[2] || amove[0] || amove[1] || amove[2]) { + float radius; - radius = RadiusFromBounds( pusher->r.mins, pusher->r.maxs ); - for ( i = 0 ; i < 3 ; i++ ) { + radius = RadiusFromBounds(pusher->r.mins, pusher->r.maxs); + for (i = 0; i < 3; i++) { mins[i] = pusher->r.currentOrigin[i] + move[i] - radius; maxs[i] = pusher->r.currentOrigin[i] + move[i] + radius; totalMins[i] = mins[i] - move[i]; totalMaxs[i] = maxs[i] - move[i]; } } else { - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { mins[i] = pusher->r.absmin[i] + move[i]; maxs[i] = pusher->r.absmax[i] + move[i]; } - VectorCopy( pusher->r.absmin, totalMins ); - VectorCopy( pusher->r.absmax, totalMaxs ); - for (i=0 ; i<3 ; i++) { - if ( move[i] > 0 ) { + VectorCopy(pusher->r.absmin, totalMins); + VectorCopy(pusher->r.absmax, totalMaxs); + for (i = 0; i < 3; i++) { + if (move[i] > 0) { totalMaxs[i] += move[i]; } else { totalMins[i] += move[i]; @@ -333,103 +319,93 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** } // unlink the pusher so we don't get it in the entityList - trap->UnlinkEntity( (sharedEntity_t *)pusher ); + trap->UnlinkEntity((sharedEntity_t *)pusher); - listedEntities = trap->EntitiesInBox( totalMins, totalMaxs, entityList, MAX_GENTITIES ); + listedEntities = trap->EntitiesInBox(totalMins, totalMaxs, entityList, MAX_GENTITIES); // move the pusher to it's final position - VectorAdd( pusher->r.currentOrigin, move, pusher->r.currentOrigin ); - VectorAdd( pusher->r.currentAngles, amove, pusher->r.currentAngles ); - trap->LinkEntity( (sharedEntity_t *)pusher ); + VectorAdd(pusher->r.currentOrigin, move, pusher->r.currentOrigin); + VectorAdd(pusher->r.currentAngles, amove, pusher->r.currentAngles); + trap->LinkEntity((sharedEntity_t *)pusher); // see if any solid entities are inside the final position - for ( e = 0 ; e < listedEntities ; e++ ) { - check = &g_entities[ entityList[ e ] ]; + for (e = 0; e < listedEntities; e++) { + check = &g_entities[entityList[e]]; // only push items and players - if ( /*check->s.eType != ET_ITEM &&*/ check->s.eType != ET_PLAYER && check->s.eType != ET_NPC && !check->physicsObject ) { + if (/*check->s.eType != ET_ITEM &&*/ check->s.eType != ET_PLAYER && check->s.eType != ET_NPC && !check->physicsObject) { continue; } // if the entity is standing on the pusher, it will definitely be moved - if ( check->s.groundEntityNum != pusher->s.number ) { + if (check->s.groundEntityNum != pusher->s.number) { // see if the ent needs to be tested - if ( check->r.absmin[0] >= maxs[0] - || check->r.absmin[1] >= maxs[1] - || check->r.absmin[2] >= maxs[2] - || check->r.absmax[0] <= mins[0] - || check->r.absmax[1] <= mins[1] - || check->r.absmax[2] <= mins[2] ) { + if (check->r.absmin[0] >= maxs[0] || check->r.absmin[1] >= maxs[1] || check->r.absmin[2] >= maxs[2] || check->r.absmax[0] <= mins[0] || + check->r.absmax[1] <= mins[1] || check->r.absmax[2] <= mins[2]) { continue; } // see if the ent's bbox is inside the pusher's final position // this does allow a fast moving object to pass through a thin entity... - if (!G_TestEntityPosition (check)) { + if (!G_TestEntityPosition(check)) { continue; } } // the entity needs to be pushed - if ( G_TryPushingEntity( check, pusher, move, amove ) ) { + if (G_TryPushingEntity(check, pusher, move, amove)) { continue; } - if (pusher->damage && check->client && (pusher->spawnflags & 32)) - { - G_Damage( check, pusher, pusher, NULL, NULL, pusher->damage, 0, MOD_CRUSH ); + if (pusher->damage && check->client && (pusher->spawnflags & 32)) { + G_Damage(check, pusher, pusher, NULL, NULL, pusher->damage, 0, MOD_CRUSH); continue; } - if (check->s.eType == ET_BODY || - (check->s.eType == ET_PLAYER && check->health < 1)) - { //whatever, just crush it - G_Damage( check, pusher, pusher, NULL, NULL, 999, 0, MOD_CRUSH ); + if (check->s.eType == ET_BODY || (check->s.eType == ET_PLAYER && check->health < 1)) { // whatever, just crush it + G_Damage(check, pusher, pusher, NULL, NULL, 999, 0, MOD_CRUSH); continue; } - if ( (check->r.contents & CONTENTS_TRIGGER) && check->s.weapon == G2_MODEL_PART) - {//keep limbs from blocking elevators. Kill the limb and keep moving. + if ((check->r.contents & CONTENTS_TRIGGER) && check->s.weapon == G2_MODEL_PART) { // keep limbs from blocking elevators. Kill the limb and keep moving. G_FreeEntity(check); continue; } - if( check->s.eFlags & EF_DROPPEDWEAPON ) - {//keep dropped weapons from blocking elevators. Kill the weapon and keep moving. + if (check->s.eFlags & EF_DROPPEDWEAPON) { // keep dropped weapons from blocking elevators. Kill the weapon and keep moving. G_FreeEntity(check); continue; } - if ( check->s.eType == ET_NPC //an NPC - && check->health <= 0 //NPC is dead - && !(check->flags & FL_NOTARGET) ) //NPC isn't still spawned or in no target mode. - {//dead npcs should be removed now! - NPC_RemoveBody( check ); + if (check->s.eType == ET_NPC // an NPC + && check->health <= 0 // NPC is dead + && !(check->flags & FL_NOTARGET)) // NPC isn't still spawned or in no target mode. + { // dead npcs should be removed now! + NPC_RemoveBody(check); continue; } // the move was blocked an entity // bobbing entities are instant-kill and never get blocked - if ( pusher->s.pos.trType == TR_SINE || pusher->s.apos.trType == TR_SINE ) { - G_Damage( check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH ); + if (pusher->s.pos.trType == TR_SINE || pusher->s.apos.trType == TR_SINE) { + G_Damage(check, pusher, pusher, NULL, NULL, 99999, 0, MOD_CRUSH); continue; } - // save off the obstacle so we can call the block function (crush, etc) *obstacle = check; // move back any entities we already moved // go backwards, so if the same entity was pushed // twice, it goes back to the original position - for ( p=pushed_p-1 ; p>=pushed ; p-- ) { - VectorCopy (p->origin, p->ent->s.pos.trBase); - VectorCopy (p->angles, p->ent->s.apos.trBase); - if ( p->ent->client ) { + for (p = pushed_p - 1; p >= pushed; p--) { + VectorCopy(p->origin, p->ent->s.pos.trBase); + VectorCopy(p->angles, p->ent->s.apos.trBase); + if (p->ent->client) { p->ent->client->ps.delta_angles[YAW] = p->deltayaw; - VectorCopy (p->origin, p->ent->client->ps.origin); + VectorCopy(p->origin, p->ent->client->ps.origin); } - trap->LinkEntity ((sharedEntity_t *)p->ent); + trap->LinkEntity((sharedEntity_t *)p->ent); } return qfalse; } @@ -437,16 +413,15 @@ qboolean G_MoverPush( gentity_t *pusher, vec3_t move, vec3_t amove, gentity_t ** return qtrue; } - /* ================= G_MoverTeam ================= */ -void G_MoverTeam( gentity_t *ent ) { - vec3_t move, amove; - gentity_t *part, *obstacle; - vec3_t origin, angles; +void G_MoverTeam(gentity_t *ent) { + vec3_t move, amove; + gentity_t *part, *obstacle; + vec3_t origin, angles; obstacle = NULL; @@ -454,46 +429,43 @@ void G_MoverTeam( gentity_t *ent ) { // any moves or calling any think functions // if the move is blocked, all moved objects will be backed out pushed_p = pushed; - for (part = ent ; part ; part=part->teamchain) { + for (part = ent; part; part = part->teamchain) { // get current position - BG_EvaluateTrajectory( &part->s.pos, level.time, origin ); - BG_EvaluateTrajectory( &part->s.apos, level.time, angles ); - VectorSubtract( origin, part->r.currentOrigin, move ); - VectorSubtract( angles, part->r.currentAngles, amove ); - if ( !VectorCompare( move, vec3_origin ) - || !VectorCompare( amove, vec3_origin ) ) - {//actually moved - if ( !G_MoverPush( part, move, amove, &obstacle ) ) { - break; // move was blocked + BG_EvaluateTrajectory(&part->s.pos, level.time, origin); + BG_EvaluateTrajectory(&part->s.apos, level.time, angles); + VectorSubtract(origin, part->r.currentOrigin, move); + VectorSubtract(angles, part->r.currentAngles, amove); + if (!VectorCompare(move, vec3_origin) || !VectorCompare(amove, vec3_origin)) { // actually moved + if (!G_MoverPush(part, move, amove, &obstacle)) { + break; // move was blocked } } } if (part) { // go back to the previous position - for ( part = ent ; part ; part = part->teamchain ) { + for (part = ent; part; part = part->teamchain) { part->s.pos.trTime += level.time - level.previousTime; part->s.apos.trTime += level.time - level.previousTime; - BG_EvaluateTrajectory( &part->s.pos, level.time, part->r.currentOrigin ); - BG_EvaluateTrajectory( &part->s.apos, level.time, part->r.currentAngles ); - trap->LinkEntity( (sharedEntity_t *)part ); + BG_EvaluateTrajectory(&part->s.pos, level.time, part->r.currentOrigin); + BG_EvaluateTrajectory(&part->s.apos, level.time, part->r.currentAngles); + trap->LinkEntity((sharedEntity_t *)part); } // if the pusher has a "blocked" function, call it if (ent->blocked) { - ent->blocked( ent, obstacle ); + ent->blocked(ent, obstacle); } return; } // the move succeeded - for ( part = ent ; part ; part = part->teamchain ) { + for (part = ent; part; part = part->teamchain) { // call the reached function if time is at or past end point - if ( part->s.pos.trType == TR_LINEAR_STOP || - part->s.pos.trType == TR_NONLINEAR_STOP) { - if ( level.time >= part->s.pos.trTime + part->s.pos.trDuration ) { - if ( part->reached ) { - part->reached( part ); + if (part->s.pos.trType == TR_LINEAR_STOP || part->s.pos.trType == TR_NONLINEAR_STOP) { + if (level.time >= part->s.pos.trTime + part->s.pos.trDuration) { + if (part->reached) { + part->reached(part); } } } @@ -506,20 +478,20 @@ G_RunMover ================ */ -void G_RunMover( gentity_t *ent ) { +void G_RunMover(gentity_t *ent) { // if not a team captain, don't do anything, because // the captain will handle everything - if ( ent->flags & FL_TEAMSLAVE ) { + if (ent->flags & FL_TEAMSLAVE) { return; } // if stationary at one of the positions, don't move anything - if ( ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY ) { - G_MoverTeam( ent ); + if (ent->s.pos.trType != TR_STATIONARY || ent->s.apos.trType != TR_STATIONARY) { + G_MoverTeam(ent); } // check think function - G_RunThink( ent ); + G_RunThink(ent); } /* @@ -538,20 +510,18 @@ CalcTeamDoorCenter Finds all the doors of a team and returns their center position */ -void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) -{ - vec3_t slavecenter; - gentity_t *slave; +void CalcTeamDoorCenter(gentity_t *ent, vec3_t center) { + vec3_t slavecenter; + gentity_t *slave; - //Start with our center + // Start with our center VectorAdd(ent->r.mins, ent->r.maxs, center); VectorScale(center, 0.5, center); - for ( slave = ent->teamchain ; slave ; slave = slave->teamchain ) - { - //Find slave's center + for (slave = ent->teamchain; slave; slave = slave->teamchain) { + // Find slave's center VectorAdd(slave->r.mins, slave->r.maxs, slavecenter); VectorScale(slavecenter, 0.5, slavecenter); - //Add that to our own, find middle + // Add that to our own, find middle VectorAdd(center, slavecenter, center); VectorScale(center, 0.5, center); } @@ -562,61 +532,54 @@ void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ) SetMoverState =============== */ -void SetMoverState( gentity_t *ent, moverState_t moverState, int time ) { - vec3_t delta; - float f; +void SetMoverState(gentity_t *ent, moverState_t moverState, int time) { + vec3_t delta; + float f; ent->moverState = moverState; ent->s.pos.trTime = time; - if ( ent->s.pos.trDuration <= 0 ) - {//Don't allow divide by zero! + if (ent->s.pos.trDuration <= 0) { // Don't allow divide by zero! ent->s.pos.trDuration = 1; } - switch( moverState ) { + switch (moverState) { case MOVER_POS1: - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_POS2: - VectorCopy( ent->pos2, ent->s.pos.trBase ); + VectorCopy(ent->pos2, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; break; case MOVER_1TO2: - VectorCopy( ent->pos1, ent->s.pos.trBase ); - VectorSubtract( ent->pos2, ent->pos1, delta ); + VectorCopy(ent->pos1, ent->s.pos.trBase); + VectorSubtract(ent->pos2, ent->pos1, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } - //ent->s.eFlags &= ~EF_BLOCKED_MOVER; + // ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; case MOVER_2TO1: - VectorCopy( ent->pos2, ent->s.pos.trBase ); - VectorSubtract( ent->pos1, ent->pos2, delta ); + VectorCopy(ent->pos2, ent->s.pos.trBase); + VectorSubtract(ent->pos1, ent->pos2, delta); f = 1000.0 / ent->s.pos.trDuration; - VectorScale( delta, f, ent->s.pos.trDelta ); - if ( ent->alt_fire ) - { + VectorScale(delta, f, ent->s.pos.trDelta); + if (ent->alt_fire) { ent->s.pos.trType = TR_LINEAR_STOP; - } - else - { + } else { ent->s.pos.trType = TR_NONLINEAR_STOP; } - //ent->s.eFlags &= ~EF_BLOCKED_MOVER; + // ent->s.eFlags &= ~EF_BLOCKED_MOVER; break; } - BG_EvaluateTrajectory( &ent->s.pos, level.time, ent->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)ent ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, ent->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -627,311 +590,265 @@ All entities in a mover team will move from pos1 to pos2 in the same amount of time ================ */ -void MatchTeam( gentity_t *teamLeader, int moverState, int time ) { - gentity_t *slave; +void MatchTeam(gentity_t *teamLeader, int moverState, int time) { + gentity_t *slave; - for ( slave = teamLeader ; slave ; slave = slave->teamchain ) { - SetMoverState( slave, (moverState_t) moverState, time ); + for (slave = teamLeader; slave; slave = slave->teamchain) { + SetMoverState(slave, (moverState_t)moverState, time); } } - - /* ================ ReturnToPos1 ================ */ -void ReturnToPos1( gentity_t *ent ) { +void ReturnToPos1(gentity_t *ent) { ent->think = 0; ent->nextthink = 0; ent->s.time = level.time; - MatchTeam( ent, MOVER_2TO1, level.time ); + MatchTeam(ent, MOVER_2TO1, level.time); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); //?? + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); //?? } - /* ================ Reached_BinaryMover ================ */ -void Reached_BinaryMover( gentity_t *ent ) -{ +void Reached_BinaryMover(gentity_t *ent) { // stop the looping sound ent->s.loopSound = 0; ent->s.loopIsSoundset = qfalse; - if ( ent->moverState == MOVER_1TO2 ) - {//reached open - vec3_t doorcenter; + if (ent->moverState == MOVER_1TO2) { // reached open + vec3_t doorcenter; // reached pos2 - SetMoverState( ent, MOVER_POS2, level.time ); + SetMoverState(ent, MOVER_POS2, level.time); - CalcTeamDoorCenter( ent, doorcenter ); + CalcTeamDoorCenter(ent, doorcenter); // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); - if ( ent->wait < 0 ) - {//Done for good + if (ent->wait < 0) { // Done for good ent->think = 0; ent->nextthink = 0; ent->use = 0; - } - else - { + } else { // return to pos1 after a delay ent->think = ReturnToPos1; - if(ent->spawnflags & 8) - {//Toggle, keep think, wait for next use? + if (ent->spawnflags & 8) { // Toggle, keep think, wait for next use? ent->nextthink = -1; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } } // fire targets - if ( !ent->activator ) - { + if (!ent->activator) { ent->activator = ent; } - G_UseTargets2( ent, ent->activator, ent->opentarget ); - } - else if ( ent->moverState == MOVER_2TO1 ) - {//closed - vec3_t doorcenter; + G_UseTargets2(ent, ent->activator, ent->opentarget); + } else if (ent->moverState == MOVER_2TO1) { // closed + vec3_t doorcenter; // reached pos1 - SetMoverState( ent, MOVER_POS1, level.time ); + SetMoverState(ent, MOVER_POS1, level.time); - CalcTeamDoorCenter( ent, doorcenter ); + CalcTeamDoorCenter(ent, doorcenter); // play sound - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); // close areaportals - if ( ent->teammaster == ent || !ent->teammaster ) - { - trap->AdjustAreaPortalState( (sharedEntity_t *)ent, qfalse ); + if (ent->teammaster == ent || !ent->teammaster) { + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qfalse); } - G_UseTargets2( ent, ent->activator, ent->closetarget ); - } - else - { - trap->Error( ERR_DROP, "Reached_BinaryMover: bad moverState" ); + G_UseTargets2(ent, ent->activator, ent->closetarget); + } else { + trap->Error(ERR_DROP, "Reached_BinaryMover: bad moverState"); } } - /* ================ Use_BinaryMover_Go ================ */ -void Use_BinaryMover_Go( gentity_t *ent ) -{ - int total; - int partial; -// gentity_t *other = ent->enemy; - gentity_t *activator = ent->activator; +void Use_BinaryMover_Go(gentity_t *ent) { + int total; + int partial; + // gentity_t *other = ent->enemy; + gentity_t *activator = ent->activator; ent->activator = activator; - if ( ent->moverState == MOVER_POS1 ) - { - vec3_t doorcenter; + if (ent->moverState == MOVER_POS1) { + vec3_t doorcenter; // start moving 50 msec later, becase if this was player // triggered, level.time hasn't been advanced yet - MatchTeam( ent, MOVER_1TO2, level.time + 50 ); + MatchTeam(ent, MOVER_1TO2, level.time + 50); - CalcTeamDoorCenter( ent, doorcenter ); + CalcTeamDoorCenter(ent, doorcenter); // starting sound - G_PlayDoorLoopSound( ent ); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorLoopSound(ent); + G_PlayDoorSound(ent, BMS_START); ent->s.time = level.time; // open areaportal - if ( ent->teammaster == ent || !ent->teammaster ) { - trap->AdjustAreaPortalState( (sharedEntity_t *)ent, qtrue ); + if (ent->teammaster == ent || !ent->teammaster) { + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qtrue); } - G_UseTargets( ent, ent->activator ); + G_UseTargets(ent, ent->activator); return; } // if all the way up, just delay before coming down - if ( ent->moverState == MOVER_POS2 ) { - //have to do this because the delay sets our think to Use_BinaryMover_Go + if (ent->moverState == MOVER_POS2) { + // have to do this because the delay sets our think to Use_BinaryMover_Go ent->think = ReturnToPos1; - if ( ent->spawnflags & 8 ) - {//TOGGLE doors don't use wait! + if (ent->spawnflags & 8) { // TOGGLE doors don't use wait! ent->nextthink = level.time + FRAMETIME; - } - else - { + } else { ent->nextthink = level.time + ent->wait; } - G_UseTargets2( ent, ent->activator, ent->target2 ); + G_UseTargets2(ent, ent->activator, ent->target2); return; } // only partway down before reversing - if ( ent->moverState == MOVER_2TO1 ) - { - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_2TO1) { + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; float fPartial; - total = ent->s.pos.trDuration-50; - VectorSubtract( ent->r.currentOrigin, ent->pos1, curDelta ); - fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + total = ent->s.pos.trDuration - 50; + VectorSubtract(ent->r.currentOrigin, ent->pos1, curDelta); + fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { total = ent->s.pos.trDuration; partial = level.time - ent->s.pos.trTime; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; - MatchTeam( ent, MOVER_1TO2, ent->s.pos.trTime ); + MatchTeam(ent, MOVER_1TO2, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } // only partway up before reversing - if ( ent->moverState == MOVER_1TO2 ) - { - if ( ent->s.pos.trType == TR_NONLINEAR_STOP ) - { + if (ent->moverState == MOVER_1TO2) { + if (ent->s.pos.trType == TR_NONLINEAR_STOP) { vec3_t curDelta; float fPartial; - total = ent->s.pos.trDuration-50; - VectorSubtract( ent->r.currentOrigin, ent->pos2, curDelta ); - fPartial = VectorLength( curDelta )/VectorLength( ent->s.pos.trDelta ); - VectorScale( ent->s.pos.trDelta, fPartial, curDelta ); + total = ent->s.pos.trDuration - 50; + VectorSubtract(ent->r.currentOrigin, ent->pos2, curDelta); + fPartial = VectorLength(curDelta) / VectorLength(ent->s.pos.trDelta); + VectorScale(ent->s.pos.trDelta, fPartial, curDelta); fPartial /= ent->s.pos.trDuration; fPartial /= 0.001f; - fPartial = acos( fPartial ); - fPartial = RAD2DEG( fPartial ); - fPartial = (90.0f - fPartial)/90.0f*ent->s.pos.trDuration; - partial = total - floor( fPartial ); - } - else - { + fPartial = acos(fPartial); + fPartial = RAD2DEG(fPartial); + fPartial = (90.0f - fPartial) / 90.0f * ent->s.pos.trDuration; + partial = total - floor(fPartial); + } else { total = ent->s.pos.trDuration; partial = level.time - ent->s.pos.trTime; } - if ( partial > total ) { + if (partial > total) { partial = total; } - ent->s.pos.trTime = level.time - ( total - partial );//ent->s.time; - MatchTeam( ent, MOVER_2TO1, ent->s.pos.trTime ); + ent->s.pos.trTime = level.time - (total - partial); // ent->s.time; + MatchTeam(ent, MOVER_2TO1, ent->s.pos.trTime); - G_PlayDoorSound( ent, BMS_START ); + G_PlayDoorSound(ent, BMS_START); return; } } -void UnLockDoors(gentity_t *const ent) -{ - //noise? - //go through and unlock the door and all the slaves - gentity_t *slave = ent; - do - { // want to allow locked toggle doors, so keep the targetname - if( !(slave->spawnflags & MOVER_TOGGLE) ) - { - slave->targetname = NULL;//not usable ever again +void UnLockDoors(gentity_t *const ent) { + // noise? + // go through and unlock the door and all the slaves + gentity_t *slave = ent; + do { // want to allow locked toggle doors, so keep the targetname + if (!(slave->spawnflags & MOVER_TOGGLE)) { + slave->targetname = NULL; // not usable ever again } slave->spawnflags &= ~MOVER_LOCKED; - slave->s.frame = 1;//second stage of anim + slave->s.frame = 1; // second stage of anim slave = slave->teamchain; - } while ( slave ); -} -void LockDoors(gentity_t *const ent) -{ - //noise? - //go through and lock the door and all the slaves - gentity_t *slave = ent; - do - { + } while (slave); +} +void LockDoors(gentity_t *const ent) { + // noise? + // go through and lock the door and all the slaves + gentity_t *slave = ent; + do { slave->spawnflags |= MOVER_LOCKED; - slave->s.frame = 0;//first stage of anim + slave->s.frame = 0; // first stage of anim slave = slave->teamchain; - } while ( slave ); + } while (slave); } /* ================ Use_BinaryMover ================ */ -void Use_BinaryMover( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - if ( !ent->use ) - {//I cannot be used anymore, must be a door with a wait of -1 that's opened. +void Use_BinaryMover(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (!ent->use) { // I cannot be used anymore, must be a door with a wait of -1 that's opened. return; } // only the master should be used - if ( ent->flags & FL_TEAMSLAVE ) - { - Use_BinaryMover( ent->teammaster, other, activator ); + if (ent->flags & FL_TEAMSLAVE) { + Use_BinaryMover(ent->teammaster, other, activator); return; } - if ( ent->flags & FL_INACTIVE ) - { + if (ent->flags & FL_INACTIVE) { return; } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, unlock it + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, unlock it UnLockDoors(ent); return; } - G_ActivateBehavior(ent,BSET_USE); + G_ActivateBehavior(ent, BSET_USE); ent->enemy = other; ent->activator = activator; - if(ent->delay) - { + if (ent->delay) { ent->think = Use_BinaryMover_Go; ent->nextthink = level.time + ent->delay; - } - else - { + } else { Use_BinaryMover_Go(ent); } } - - /* ================ InitMover @@ -940,72 +857,64 @@ InitMover so the movement delta can be calculated ================ */ -void InitMoverTrData( gentity_t *ent ) -{ - vec3_t move; - float distance; +void InitMoverTrData(gentity_t *ent) { + vec3_t move; + float distance; ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); // calculate time to reach second position from speed - VectorSubtract( ent->pos2, ent->pos1, move ); - distance = VectorLength( move ); - if ( ! ent->speed ) - { + VectorSubtract(ent->pos2, ent->pos1, move); + distance = VectorLength(move); + if (!ent->speed) { ent->speed = 100; } - VectorScale( move, ent->speed, ent->s.pos.trDelta ); + VectorScale(move, ent->speed, ent->s.pos.trDelta); ent->s.pos.trDuration = distance * 1000 / ent->speed; - if ( ent->s.pos.trDuration <= 0 ) - { + if (ent->s.pos.trDuration <= 0) { ent->s.pos.trDuration = 1; } } -void InitMover( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +void InitMover(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 ) - { - if ( strstr( ent->model2, ".glm" )) - { //for now, not supported in MP. + if (ent->model2) { + if (strstr(ent->model2, ".glm")) { // for now, not supported in MP. ent->s.modelindex2 = 0; - } - else - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + } else { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } ent->use = Use_BinaryMover; @@ -1013,22 +922,19 @@ void InitMover( gentity_t *ent ) ent->moverState = MOVER_POS1; ent->r.svFlags = SVF_USE_CURRENT_ORIGIN; - if ( ent->spawnflags & MOVER_INACTIVE ) - {// Make it inactive + if (ent->spawnflags & MOVER_INACTIVE) { // Make it inactive ent->flags |= FL_INACTIVE; } - if(ent->spawnflags & MOVER_PLAYER_USE) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & MOVER_PLAYER_USE) { // Can be used by the player's BUTTON_USE ent->r.svFlags |= SVF_PLAYER_USABLE; } ent->s.eType = ET_MOVER; - VectorCopy( ent->pos1, ent->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)ent ); + VectorCopy(ent->pos1, ent->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)ent); - InitMoverTrData( ent ); + InitMoverTrData(ent); } - /* =============================================================================== @@ -1045,33 +951,30 @@ targeted by another entity. Blocked_Door ================ */ -void Blocked_Door( gentity_t *ent, gentity_t *other ) -{ - //determines if we need to relock after moving or not. +void Blocked_Door(gentity_t *ent, gentity_t *other) { + // determines if we need to relock after moving or not. qboolean relock = (ent->spawnflags & MOVER_LOCKED) ? qtrue : qfalse; - if ( ent->damage ) { - G_Damage( other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH ); + if (ent->damage) { + G_Damage(other, ent, ent, NULL, NULL, ent->damage, 0, MOD_CRUSH); } - if ( ent->spawnflags & MOVER_CRUSHER ) { - return; // crushers don't reverse + if (ent->spawnflags & MOVER_CRUSHER) { + return; // crushers don't reverse } // reverse direction - Use_BinaryMover( ent, ent, other ); - if(relock) - {//door was locked before reverse move, relock door. + Use_BinaryMover(ent, ent, other); + if (relock) { // door was locked before reverse move, relock door. LockDoors(ent); } } - /* ================ Touch_DoorTriggerSpectator ================ */ -static vec3_t doorangles = { 10000000.0, 0, 0 }; -static void Touch_DoorTriggerSpectator( gentity_t *ent, gentity_t *other, trace_t *trace ) { +static vec3_t doorangles = {10000000.0, 0, 0}; +static void Touch_DoorTriggerSpectator(gentity_t *ent, gentity_t *other, trace_t *trace) { int axis; float doorMin, doorMax; vec3_t origin, pMins, pMaxs; @@ -1084,7 +987,8 @@ static void Touch_DoorTriggerSpectator( gentity_t *ent, gentity_t *other, trace_ VectorCopy(other->client->ps.origin, origin); - if (origin[axis] < doorMin || origin[axis] > doorMax) return; + if (origin[axis] < doorMin || origin[axis] > doorMax) + return; if (fabs(origin[axis] - doorMax) < fabs(origin[axis] - doorMin)) { origin[axis] = doorMin - 25; // 10 @@ -1095,12 +999,8 @@ static void Touch_DoorTriggerSpectator( gentity_t *ent, gentity_t *other, trace_ VectorSet(pMins, -15.0f, -15.0f, DEFAULT_MINS_2); VectorSet(pMaxs, 15.0f, 15.0f, DEFAULT_MAXS_2); trap->Trace(&tr, origin, pMins, pMaxs, origin, other->s.number, other->clipmask, qfalse, 0, 0); - if (!tr.startsolid && - !tr.allsolid && - tr.fraction == 1.0f && - tr.entityNum == ENTITYNUM_NONE) - { - TeleportPlayer( other, origin, doorangles ); + if (!tr.startsolid && !tr.allsolid && tr.fraction == 1.0f && tr.entityNum == ENTITYNUM_NONE) { + TeleportPlayer(other, origin, doorangles); } } @@ -1109,77 +1009,58 @@ static void Touch_DoorTriggerSpectator( gentity_t *ent, gentity_t *other, trace_ Touch_DoorTrigger ================ */ -void Touch_DoorTrigger( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ +void Touch_DoorTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { gentity_t *relockEnt = NULL; - if ( other->client && other->client->sess.sessionTeam == TEAM_SPECTATOR ) - { + if (other->client && other->client->sess.sessionTeam == TEAM_SPECTATOR) { // if the door is not open and not opening - if ( ent->parent->moverState != MOVER_1TO2 && - ent->parent->moverState != MOVER_POS2 ) - { - Touch_DoorTriggerSpectator( ent, other, trace ); + if (ent->parent->moverState != MOVER_1TO2 && ent->parent->moverState != MOVER_POS2) { + Touch_DoorTriggerSpectator(ent, other, trace); } return; } - if (!ent->genericValue14 && - (!ent->parent || !ent->parent->genericValue14)) - { - if (other->client && other->s.number >= MAX_CLIENTS && - other->s.eType == ET_NPC && other->s.NPC_class == CLASS_VEHICLE) - { //doors don't open for vehicles + if (!ent->genericValue14 && (!ent->parent || !ent->parent->genericValue14)) { + if (other->client && other->s.number >= MAX_CLIENTS && other->s.eType == ET_NPC && + other->s.NPC_class == CLASS_VEHICLE) { // doors don't open for vehicles return; } - if (other->client && other->s.number < MAX_CLIENTS && - other->client->ps.m_iVehicleNum) - { //can't open a door while on a vehicle + if (other->client && other->s.number < MAX_CLIENTS && other->client->ps.m_iVehicleNum) { // can't open a door while on a vehicle return; } } - if ( ent->flags & FL_INACTIVE ) - { + if (ent->flags & FL_INACTIVE) { return; } - if ( ent->parent->spawnflags & MOVER_LOCKED ) - {//don't even try to use the door if it's locked - if ( !ent->parent->alliedTeam //we don't have a "teamallow" team - || !other->client //we do have a "teamallow" team, but this isn't a client - || other->client->sess.sessionTeam != ent->parent->alliedTeam )//it is a client, but it's not on the right team + if (ent->parent->spawnflags & MOVER_LOCKED) { // don't even try to use the door if it's locked + if (!ent->parent->alliedTeam // we don't have a "teamallow" team + || !other->client // we do have a "teamallow" team, but this isn't a client + || other->client->sess.sessionTeam != ent->parent->alliedTeam) // it is a client, but it's not on the right team { return; - } - else - {//temporarily unlock us while we call Use_BinaryMover (so it doesn't unlock all the doors in this team) - if ( ent->parent->flags & FL_TEAMSLAVE ) - { + } else { // temporarily unlock us while we call Use_BinaryMover (so it doesn't unlock all the doors in this team) + if (ent->parent->flags & FL_TEAMSLAVE) { relockEnt = ent->parent->teammaster; - } - else - { + } else { relockEnt = ent->parent; } - if ( relockEnt != NULL ) - { + if (relockEnt != NULL) { relockEnt->spawnflags &= ~MOVER_LOCKED; } } } - if ( ent->parent->moverState != MOVER_1TO2 ) - {//Door is not already opening - //if ( ent->parent->moverState == MOVER_POS1 || ent->parent->moverState == MOVER_2TO1 ) + if (ent->parent->moverState != MOVER_1TO2) { // Door is not already opening + // if ( ent->parent->moverState == MOVER_POS1 || ent->parent->moverState == MOVER_2TO1 ) //{//only check these if closed or closing - //If door is closed, opening or open, check this - Use_BinaryMover( ent->parent, ent, other ); + // If door is closed, opening or open, check this + Use_BinaryMover(ent->parent, ent, other); } - if ( relockEnt != NULL ) - {//re-lock us + if (relockEnt != NULL) { // re-lock us relockEnt->spawnflags |= MOVER_LOCKED; } @@ -1199,34 +1080,31 @@ All of the parts of a door have been spawned, so create a trigger that encloses all of them ====================== */ -void Think_SpawnNewDoorTrigger( gentity_t *ent ) -{ - gentity_t *other; - vec3_t mins, maxs; - int i, best; +void Think_SpawnNewDoorTrigger(gentity_t *ent) { + gentity_t *other; + vec3_t mins, maxs; + int i, best; // set all of the slaves as shootable - if ( ent->takedamage ) - { - for ( other = ent ; other ; other = other->teamchain ) - { + if (ent->takedamage) { + for (other = ent; other; other = other->teamchain) { other->takedamage = qtrue; } } // find the bounds of everything on the team - VectorCopy (ent->r.absmin, mins); - VectorCopy (ent->r.absmax, maxs); + VectorCopy(ent->r.absmin, mins); + VectorCopy(ent->r.absmax, maxs); - for (other = ent->teamchain ; other ; other=other->teamchain) { - AddPointToBounds (other->r.absmin, mins, maxs); - AddPointToBounds (other->r.absmax, mins, maxs); + for (other = ent->teamchain; other; other = other->teamchain) { + AddPointToBounds(other->r.absmin, mins, maxs); + AddPointToBounds(other->r.absmax, mins, maxs); } // find the thinnest axis, which will be the one we expand best = 0; - for ( i = 1 ; i < 3 ; i++ ) { - if ( maxs[i] - mins[i] < maxs[best] - mins[best] ) { + for (i = 1; i < 3; i++) { + if (maxs[i] - mins[i] < maxs[best] - mins[best]) { best = i; } } @@ -1234,78 +1112,62 @@ void Think_SpawnNewDoorTrigger( gentity_t *ent ) mins[best] -= 120; // create a trigger with this size - other = G_Spawn (); - VectorCopy (mins, other->r.mins); - VectorCopy (maxs, other->r.maxs); + other = G_Spawn(); + VectorCopy(mins, other->r.mins); + VectorCopy(maxs, other->r.maxs); other->parent = ent; other->r.contents = CONTENTS_TRIGGER; other->touch = Touch_DoorTrigger; - trap->LinkEntity ((sharedEntity_t *)other); + trap->LinkEntity((sharedEntity_t *)other); other->classname = "trigger_door"; // remember the thinnest axis other->count = best; - MatchTeam( ent, ent->moverState, level.time ); + MatchTeam(ent, ent->moverState, level.time); } -void Think_MatchTeam( gentity_t *ent ) -{ - MatchTeam( ent, ent->moverState, level.time ); -} +void Think_MatchTeam(gentity_t *ent) { MatchTeam(ent, ent->moverState, level.time); } -qboolean G_EntIsDoor( int entityNum ) -{ +qboolean G_EntIsDoor(int entityNum) { gentity_t *ent; - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } ent = &g_entities[entityNum]; - if ( ent && !Q_stricmp( "func_door", ent->classname ) ) - {//blocked by a door + if (ent && !Q_stricmp("func_door", ent->classname)) { // blocked by a door return qtrue; } return qfalse; } -gentity_t *G_FindDoorTrigger( gentity_t *ent ) -{ +gentity_t *G_FindDoorTrigger(gentity_t *ent) { gentity_t *owner = NULL; gentity_t *door = ent; - if ( door->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( door->teammaster && (door->flags&FL_TEAMSLAVE)) - { + if (door->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (door->teammaster && (door->flags & FL_TEAMSLAVE)) { door = door->teammaster; } } - if ( door->targetname ) - {//find out what is targeting it - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), door->targetname )) != NULL ) - { - if ( owner && (owner->r.contents&CONTENTS_TRIGGER) ) - { + if (door->targetname) { // find out what is targeting it + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), door->targetname)) != NULL) { + if (owner && (owner->r.contents & CONTENTS_TRIGGER)) { return owner; } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), door->targetname )) != NULL ) - { - if ( owner && (owner->r.contents&CONTENTS_TRIGGER) ) - { + while ((owner = G_Find(owner, FOFS(target2), door->targetname)) != NULL) { + if (owner && (owner->r.contents & CONTENTS_TRIGGER)) { return owner; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( classname ), "trigger_door" )) != NULL ) - { - if ( owner->parent == door ) - { + while ((owner = G_Find(owner, FOFS(classname), "trigger_door")) != NULL) { + if (owner->parent == door) { return owner; } } @@ -1313,65 +1175,49 @@ gentity_t *G_FindDoorTrigger( gentity_t *ent ) return NULL; } -qboolean G_EntIsUnlockedDoor( int entityNum ) -{ - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { +qboolean G_EntIsUnlockedDoor(int entityNum) { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } - if ( G_EntIsDoor( entityNum ) ) - { + if (G_EntIsDoor(entityNum)) { gentity_t *ent = &g_entities[entityNum]; gentity_t *owner = NULL; - if ( ent->flags & FL_TEAMSLAVE ) - {//not the master door, get the master door - while ( ent->teammaster && (ent->flags&FL_TEAMSLAVE)) - { + if (ent->flags & FL_TEAMSLAVE) { // not the master door, get the master door + while (ent->teammaster && (ent->flags & FL_TEAMSLAVE)) { ent = ent->teammaster; } } - if ( ent->targetname ) - {//find out what is targetting it + if (ent->targetname) { // find out what is targetting it owner = NULL; - //FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? - while ( (owner = G_Find( owner, FOFS( target ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too? + // FIXME: if ent->targetname, check what kind of trigger/ent is targetting it? If a normal trigger (active, etc), then it's okay? + while ((owner = G_Find(owner, FOFS(target), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname)) // FIXME: other triggers okay too? { - if ( !(owner->flags & FL_INACTIVE) ) - { + if (!(owner->flags & FL_INACTIVE)) { return qtrue; } } } owner = NULL; - while ( (owner = G_Find( owner, FOFS( target2 ), ent->targetname )) != NULL ) - { - if ( !Q_stricmp( "trigger_multiple", owner->classname ) )//FIXME: other triggers okay too? + while ((owner = G_Find(owner, FOFS(target2), ent->targetname)) != NULL) { + if (!Q_stricmp("trigger_multiple", owner->classname)) // FIXME: other triggers okay too? { - if ( !(owner->flags & FL_INACTIVE) ) - { + if (!(owner->flags & FL_INACTIVE)) { return qtrue; } } } return qfalse; - } - else - {//check the door's auto-created trigger instead - owner = G_FindDoorTrigger( ent ); - if ( owner && (owner->flags&FL_INACTIVE) ) - {//owning auto-created trigger is inactive + } else { // check the door's auto-created trigger instead + owner = G_FindDoorTrigger(ent); + if (owner && (owner->flags & FL_INACTIVE)) { // owning auto-created trigger is inactive return qfalse; } } - if ( !(ent->flags & FL_INACTIVE) && //assumes that the reactivate trigger isn't right next to the door! - !ent->health && - !(ent->spawnflags & MOVER_PLAYER_USE) && - !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && - !(ent->spawnflags & MOVER_LOCKED)) - //FIXME: what about MOVER_GOODIE? + if (!(ent->flags & FL_INACTIVE) && // assumes that the reactivate trigger isn't right next to the door! + !ent->health && !(ent->spawnflags & MOVER_PLAYER_USE) && !(ent->spawnflags & MOVER_FORCE_ACTIVATE) && !(ent->spawnflags & MOVER_LOCKED)) + // FIXME: what about MOVER_GOODIE? { return qtrue; } @@ -1379,15 +1225,13 @@ qboolean G_EntIsUnlockedDoor( int entityNum ) return qfalse; } - /*QUAKED func_door (0 .5 .8) ? START_OPEN FORCE_ACTIVATE CRUSHER TOGGLE LOCKED x PLAYER_USE INACTIVE -START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors). -FORCE_ACTIVATE Can only be activated by a force push or pull -CRUSHER ? +START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when +triggered (not useful for touch or takedamage doors). FORCE_ACTIVATE Can only be activated by a force push or pull CRUSHER ? TOGGLE wait in both the start and end states for a trigger event - does NOT work on Trek doors. -LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates normally. Note that you cannot use the door again after this. -PLAYER_USE Player can use it with the use button -INACTIVE must be used by a target_activate before it can be used +LOCKED Starts locked, with the shader animmap at the first frame and inactive. Once used, the animmap changes to the second frame and the door operates +normally. Note that you cannot use the door again after this. PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate +before it can be used "target" Door fires this when it starts moving from it's closed position to its open position. "opentarget" Door fires this after reaching its "open" position @@ -1411,12 +1255,11 @@ INACTIVE must be used by a target_activate before it can be used 2 - blue "vehopen" if non-0, vehicles/players riding vehicles can open */ -void SP_func_door (gentity_t *ent) -{ - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_door(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; G_SpawnInt("vehopen", "0", &ent->genericValue14); @@ -1434,72 +1277,63 @@ void SP_func_door (gentity_t *ent) ent->delay *= 1000; // default lip of 8 units - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("lip", "8", &lip); // default damage of 2 points - G_SpawnInt( "dmg", "2", &ent->damage ); - if ( ent->damage < 0 ) - { + G_SpawnInt("dmg", "2", &ent->damage); + if (ent->damage < 0) { ent->damage = 0; } - G_SpawnInt( "teamallow", "0", &ent->alliedTeam ); + G_SpawnInt("teamallow", "0", &ent->alliedTeam); // first position at start - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); - G_SetMovedir( ent->s.angles, ent->movedir ); - abs_movedir[0] = fabs( ent->movedir[0] ); - abs_movedir[1] = fabs( ent->movedir[1] ); - abs_movedir[2] = fabs( ent->movedir[2] ); - VectorSubtract( ent->r.maxs, ent->r.mins, size ); - distance = DotProduct( abs_movedir, size ) - lip; - VectorMA( ent->pos1, distance, ent->movedir, ent->pos2 ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); + G_SetMovedir(ent->s.angles, ent->movedir); + abs_movedir[0] = fabs(ent->movedir[0]); + abs_movedir[1] = fabs(ent->movedir[1]); + abs_movedir[2] = fabs(ent->movedir[2]); + VectorSubtract(ent->r.maxs, ent->r.mins, size); + distance = DotProduct(abs_movedir, size) - lip; + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); // if "start_open", reverse position 1 and 2 - if ( ent->spawnflags & 1 ) - { - vec3_t temp; + if (ent->spawnflags & 1) { + vec3_t temp; - VectorCopy( ent->pos2, temp ); - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( temp, ent->pos1 ); + VectorCopy(ent->pos2, temp); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(temp, ent->pos1); } - if ( ent->spawnflags & MOVER_LOCKED ) - {//a locked door, set up as locked until used directly - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim + if (ent->spawnflags & MOVER_LOCKED) { // a locked door, set up as locked until used directly + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim } - InitMover( ent ); + InitMover(ent); ent->nextthink = level.time + FRAMETIME; - if ( !(ent->flags&FL_TEAMSLAVE) ) - { + if (!(ent->flags & FL_TEAMSLAVE)) { int health; - G_SpawnInt( "health", "0", &health ); + G_SpawnInt("health", "0", &health); - if ( health ) - { + if (health) { ent->takedamage = qtrue; } - if ( !(ent->spawnflags&MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE) ) - { + if (!(ent->spawnflags & MOVER_LOCKED) && (ent->targetname || health || ent->spawnflags & MOVER_PLAYER_USE || ent->spawnflags & MOVER_FORCE_ACTIVATE)) { // non touch/shoot doors ent->think = Think_MatchTeam; - if (ent->spawnflags & MOVER_FORCE_ACTIVATE) - { //so we know it's push/pullable on the client + if (ent->spawnflags & MOVER_FORCE_ACTIVATE) { // so we know it's push/pullable on the client ent->s.bolt1 = 1; } - } - else - {//locked doors still spawn a trigger + } else { // locked doors still spawn a trigger ent->think = Think_SpawnNewDoorTrigger; } } @@ -1520,13 +1354,13 @@ Touch_Plat Don't allow descent if a living player is on it =============== */ -void Touch_Plat( gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client || other->client->ps.stats[STAT_HEALTH] <= 0 ) { +void Touch_Plat(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client || other->client->ps.stats[STAT_HEALTH] <= 0) { return; } // delay return-to-pos1 by one second - if ( ent->moverState == MOVER_POS2 ) { + if (ent->moverState == MOVER_POS2) { ent->nextthink = level.time + 1000; } } @@ -1538,17 +1372,16 @@ Touch_PlatCenterTrigger If the plat is at the bottom position, start it going up =============== */ -void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_PlatCenterTrigger(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->parent->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent->parent, ent, other ); + if (ent->parent->moverState == MOVER_POS1) { + Use_BinaryMover(ent->parent, ent, other); } } - /* ================ SpawnPlatTrigger @@ -1558,9 +1391,9 @@ Elevator cars require that the trigger extend through the entire low position, not just sit on top of it. ================ */ -void SpawnPlatTrigger( gentity_t *ent ) { - gentity_t *trigger; - vec3_t tmin, tmax; +void SpawnPlatTrigger(gentity_t *ent) { + gentity_t *trigger; + vec3_t tmin, tmax; // the middle trigger will be a thin trigger just // above the starting position @@ -1577,22 +1410,21 @@ void SpawnPlatTrigger( gentity_t *ent ) { tmax[1] = ent->pos1[1] + ent->r.maxs[1] - 33; tmax[2] = ent->pos1[2] + ent->r.maxs[2] + 8; - if ( tmax[0] <= tmin[0] ) { - tmin[0] = ent->pos1[0] + (ent->r.mins[0] + ent->r.maxs[0]) *0.5; + if (tmax[0] <= tmin[0]) { + tmin[0] = ent->pos1[0] + (ent->r.mins[0] + ent->r.maxs[0]) * 0.5; tmax[0] = tmin[0] + 1; } - if ( tmax[1] <= tmin[1] ) { - tmin[1] = ent->pos1[1] + (ent->r.mins[1] + ent->r.maxs[1]) *0.5; + if (tmax[1] <= tmin[1]) { + tmin[1] = ent->pos1[1] + (ent->r.mins[1] + ent->r.maxs[1]) * 0.5; tmax[1] = tmin[1] + 1; } - VectorCopy (tmin, trigger->r.mins); - VectorCopy (tmax, trigger->r.maxs); + VectorCopy(tmin, trigger->r.mins); + VectorCopy(tmax, trigger->r.maxs); - trap->LinkEntity ((sharedEntity_t *)trigger); + trap->LinkEntity((sharedEntity_t *)trigger); } - /*QUAKED func_plat (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used @@ -1607,34 +1439,34 @@ Plats are always drawn in the extended position so they will light correctly. "color" constantLight color "light" constantLight radius */ -void SP_func_plat (gentity_t *ent) { - float lip, height; +void SP_func_plat(gentity_t *ent) { + float lip, height; -// ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); -// ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); + // ent->sound1to2 = ent->sound2to1 = G_SoundIndex("sound/movers/plats/pt1_strt.wav"); + // ent->soundPos1 = ent->soundPos2 = G_SoundIndex("sound/movers/plats/pt1_end.wav"); - VectorClear (ent->s.angles); + VectorClear(ent->s.angles); - G_SpawnFloat( "speed", "200", &ent->speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "wait", "1", &ent->wait ); - G_SpawnFloat( "lip", "8", &lip ); + G_SpawnFloat("speed", "200", &ent->speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("wait", "1", &ent->wait); + G_SpawnFloat("lip", "8", &lip); ent->wait = 1000; // create second position - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); - if ( !G_SpawnFloat( "height", "0", &height ) ) { + if (!G_SpawnFloat("height", "0", &height)) { height = (ent->r.maxs[2] - ent->r.mins[2]) - lip; } // pos1 is the rest (bottom) position, pos2 is the top - VectorCopy( ent->s.origin, ent->pos2 ); - VectorCopy( ent->pos2, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos2); + VectorCopy(ent->pos2, ent->pos1); ent->pos1[2] -= height; - InitMover( ent ); + InitMover(ent); // touch function keeps the plat from returning while // a live player is standing on it @@ -1642,10 +1474,10 @@ void SP_func_plat (gentity_t *ent) { ent->blocked = Blocked_Door; - ent->parent = ent; // so it can be treated as a door + ent->parent = ent; // so it can be treated as a door // spawn the trigger if one hasn't been custom made - if ( !ent->targetname ) { + if (!ent->targetname) { SpawnPlatTrigger(ent); } } @@ -1664,22 +1496,22 @@ Touch_Button =============== */ -void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ) { - if ( !other->client ) { +void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( ent->moverState == MOVER_POS1 ) { - Use_BinaryMover( ent, other, other ); + if (ent->moverState == MOVER_POS1) { + Use_BinaryMover(ent, other, other); } } - /*QUAKED func_button (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button INACTIVE must be used by a target_activate before it can be used -When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again. +When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original +position where it can be triggered again. "model2" .md3 model to also draw "angle" determines the opening direction @@ -1691,38 +1523,38 @@ When a button is touched, it moves some distance in the direction of it's angle, "color" constantLight color "light" constantLight radius */ -void SP_func_button( gentity_t *ent ) { - vec3_t abs_movedir; - float distance; - vec3_t size; - float lip; +void SP_func_button(gentity_t *ent) { + vec3_t abs_movedir; + float distance; + vec3_t size; + float lip; -// ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); + // ent->sound1to2 = G_SoundIndex("sound/movers/switches/butn2.wav"); - if ( !ent->speed ) { + if (!ent->speed) { ent->speed = 40; } - if ( !ent->wait ) { + if (!ent->wait) { ent->wait = 1; } ent->wait *= 1000; // first position - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); // calculate second position - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); - G_SpawnFloat( "lip", "4", &lip ); + G_SpawnFloat("lip", "4", &lip); - G_SetMovedir( ent->s.angles, ent->movedir ); + G_SetMovedir(ent->s.angles, ent->movedir); abs_movedir[0] = fabs(ent->movedir[0]); abs_movedir[1] = fabs(ent->movedir[1]); abs_movedir[2] = fabs(ent->movedir[2]); - VectorSubtract( ent->r.maxs, ent->r.mins, size ); + VectorSubtract(ent->r.maxs, ent->r.mins, size); distance = abs_movedir[0] * size[0] + abs_movedir[1] * size[1] + abs_movedir[2] * size[2] - lip; - VectorMA (ent->pos1, distance, ent->movedir, ent->pos2); + VectorMA(ent->pos1, distance, ent->movedir, ent->pos2); if (ent->health) { // shootable button @@ -1732,12 +1564,9 @@ void SP_func_button( gentity_t *ent ) { ent->touch = Touch_Button; } - InitMover( ent ); + InitMover(ent); } - - - /* =============================================================================== @@ -1746,10 +1575,9 @@ TRAIN =============================================================================== */ - -#define TRAIN_START_ON 1 -#define TRAIN_TOGGLE 2 -#define TRAIN_BLOCK_STOPS 4 +#define TRAIN_START_ON 1 +#define TRAIN_TOGGLE 2 +#define TRAIN_BLOCK_STOPS 4 /* =============== @@ -1758,9 +1586,9 @@ Think_BeginMoving The wait time at a corner has completed, so start moving again =============== */ -void Think_BeginMoving( gentity_t *ent ) { - G_PlayDoorSound( ent, BMS_START ); - G_PlayDoorLoopSound( ent ); +void Think_BeginMoving(gentity_t *ent) { + G_PlayDoorSound(ent, BMS_START); + G_PlayDoorLoopSound(ent); ent->s.pos.trTime = level.time; ent->s.pos.trType = TR_LINEAR_STOP; } @@ -1770,59 +1598,57 @@ void Think_BeginMoving( gentity_t *ent ) { Reached_Train =============== */ -void Reached_Train( gentity_t *ent ) { - gentity_t *next; - float speed; - vec3_t move; - float length; +void Reached_Train(gentity_t *ent) { + gentity_t *next; + float speed; + vec3_t move; + float length; // copy the apropriate values next = ent->nextTrain; - if ( !next || !next->nextTrain ) { - return; // just stop + if (!next || !next->nextTrain) { + return; // just stop } // fire all other targets - G_UseTargets( next, NULL ); + G_UseTargets(next, NULL); // set the new trajectory ent->nextTrain = next->nextTrain; - VectorCopy( next->s.origin, ent->pos1 ); - VectorCopy( next->nextTrain->s.origin, ent->pos2 ); + VectorCopy(next->s.origin, ent->pos1); + VectorCopy(next->nextTrain->s.origin, ent->pos2); // if the path_corner has a speed, use that - if ( next->speed ) { + if (next->speed) { speed = next->speed; } else { // otherwise use the train's speed speed = ent->speed; } - if ( speed < 1 ) { + if (speed < 1) { speed = 1; } // calculate duration - VectorSubtract( ent->pos2, ent->pos1, move ); - length = VectorLength( move ); + VectorSubtract(ent->pos2, ent->pos1, move); + length = VectorLength(move); ent->s.pos.trDuration = length * 1000 / speed; // start it going - SetMoverState( ent, MOVER_1TO2, level.time ); + SetMoverState(ent, MOVER_1TO2, level.time); - G_PlayDoorSound( ent, BMS_END ); + G_PlayDoorSound(ent, BMS_END); // if there is a "wait" value on the target, don't start moving yet - if ( next->wait ) { + if (next->wait) { ent->s.loopSound = 0; ent->s.loopIsSoundset = qfalse; ent->nextthink = level.time + next->wait * 1000; ent->think = Think_BeginMoving; ent->s.pos.trType = TR_STATIONARY; - } - else - { - G_PlayDoorLoopSound( ent ); + } else { + G_PlayDoorLoopSound(ent); } } @@ -1833,32 +1659,31 @@ Think_SetupTrainTargets Link all the corners together =============== */ -void Think_SetupTrainTargets( gentity_t *ent ) { - gentity_t *path, *next, *start; - - ent->nextTrain = G_Find( NULL, FOFS(targetname), ent->target ); - if ( !ent->nextTrain ) { - Com_Printf( "func_train at %s with an unfound target\n", - vtos(ent->r.absmin) ); - //Free me?` +void Think_SetupTrainTargets(gentity_t *ent) { + gentity_t *path, *next, *start; + + ent->nextTrain = G_Find(NULL, FOFS(targetname), ent->target); + if (!ent->nextTrain) { + Com_Printf("func_train at %s with an unfound target\n", vtos(ent->r.absmin)); + // Free me?` return; } - //FIXME: this can go into an infinite loop if last path_corner doesn't link to first - //path_corner, like so: - // t1---->t2---->t3 - // ^ | - // \_____| + // FIXME: this can go into an infinite loop if last path_corner doesn't link to first + // path_corner, like so: + // t1---->t2---->t3 + // ^ | + // \_____| start = NULL; - for ( path = ent->nextTrain ; path != start ; path = next ) { - if ( !start ) { + for (path = ent->nextTrain; path != start; path = next) { + if (!start) { start = path; } - if ( !path->target ) { -// trap->Printf( "Train corner at %s without a target\n", -// vtos(path->s.origin) ); - //end of path + if (!path->target) { + // trap->Printf( "Train corner at %s without a target\n", + // vtos(path->s.origin) ); + // end of path break; } @@ -1867,54 +1692,45 @@ void Think_SetupTrainTargets( gentity_t *ent ) { // is reached next = NULL; do { - next = G_Find( next, FOFS(targetname), path->target ); - if ( !next ) { -// trap->Printf( "Train corner at %s without a target path_corner\n", -// vtos(path->s.origin) ); - //end of path + next = G_Find(next, FOFS(targetname), path->target); + if (!next) { + // trap->Printf( "Train corner at %s without a target path_corner\n", + // vtos(path->s.origin) ); + // end of path break; } - } while ( strcmp( next->classname, "path_corner" ) ); + } while (strcmp(next->classname, "path_corner")); - if ( next ) - { + if (next) { path->nextTrain = next; - } - else - { + } else { break; } } - if ( !ent->targetname || (ent->spawnflags&1) /*start on*/) - { + if (!ent->targetname || (ent->spawnflags & 1) /*start on*/) { // start the train moving from the first corner - Reached_Train( ent ); - } - else - { - G_SetOrigin( ent, ent->s.origin ); + Reached_Train(ent); + } else { + G_SetOrigin(ent, ent->s.origin); } } - /*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8) Train path corners. Target: next path corner and other targets to fire "speed" speed to move to the next corner "wait" seconds to wait before behining move to next corner */ -void SP_path_corner( gentity_t *self ) { - if ( !self->targetname ) { - trap->Print ("path_corner with no targetname at %s\n", vtos(self->s.origin)); - G_FreeEntity( self ); +void SP_path_corner(gentity_t *self) { + if (!self->targetname) { + trap->Print("path_corner with no targetname at %s\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } // path corners don't need to be linked in } - - /*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS ? ? CRUSH_THROUGH PLAYER_USE INACTIVE A train is a mover that moves between path_corner target points. Trains MUST HAVE AN ORIGIN BRUSH. @@ -1928,8 +1744,8 @@ entities and damage them on contact as well. "color" constantLight color "light" constantLight radius */ -void SP_func_train (gentity_t *self) { - VectorClear (self->s.angles); +void SP_func_train(gentity_t *self) { + VectorClear(self->s.angles); if (self->spawnflags & TRAIN_BLOCK_STOPS) { self->damage = 0; @@ -1939,18 +1755,18 @@ void SP_func_train (gentity_t *self) { } } - if ( !self->speed ) { + if (!self->speed) { self->speed = 100; } - if ( !self->target ) { - trap->Print ("func_train without a target at %s\n", vtos(self->r.absmin)); - G_FreeEntity( self ); + if (!self->target) { + trap->Print("func_train without a target at %s\n", vtos(self->r.absmin)); + G_FreeEntity(self); return; } - trap->SetBrushModel( (sharedEntity_t *)self, self->model ); - InitMover( self ); + trap->SetBrushModel((sharedEntity_t *)self, self->model); + InitMover(self); self->reached = Reached_Train; @@ -1968,7 +1784,7 @@ STATIC =============================================================================== */ -void func_static_use ( gentity_t *self, gentity_t *other, gentity_t *activator ); +void func_static_use(gentity_t *self, gentity_t *other, gentity_t *activator); /*QUAKED func_static (0 .5 .8) ? F_PUSH F_PULL SWITCH_SHADER CRUSHER IMPACT x PLAYER_USE INACTIVE BROADCAST F_PUSH Will be used when you Force-Push it F_PULL Will be used when you Force-Pull it @@ -1981,78 +1797,65 @@ BROADCAST don't ever use this, it's evil A bmodel that just sits there, doing nothing. Can be used for conditional walls and models. "model2" .md3 model to also draw -"model2scale" percent of normal scale (on all x y and z axii) to scale the model2 if there is one. 100 is normal scale, min is 1 (100 times smaller than normal), max is 1000 (ten times normal). -"color" constantLight color -"light" constantLight radius -"dmg" how much damage to do when it crushes (use with CRUSHER spawnflag) -"linear" set to 1 and it will move linearly rather than with acceleration (default is 0) +"model2scale" percent of normal scale (on all x y and z axii) to scale the model2 if there is one. 100 is normal scale, min is 1 (100 times smaller than +normal), max is 1000 (ten times normal). "color" constantLight color "light" constantLight radius "dmg" how much damage to do when it crushes +(use with CRUSHER spawnflag) "linear" set to 1 and it will move linearly rather than with acceleration (default is 0) */ -void SP_func_static( gentity_t *ent ) -{ - int test; - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); +void SP_func_static(gentity_t *ent) { + int test; + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); + InitMover(ent); ent->use = func_static_use; ent->reached = 0; - G_SetOrigin( ent, ent->s.origin ); - G_SetAngles( ent, ent->s.angles ); + G_SetOrigin(ent, ent->s.origin); + G_SetAngles(ent, ent->s.angles); - if( ent->spawnflags & 2048 ) - { // yes this is very very evil, but for now (pre-alpha) it's a solution + if (ent->spawnflags & 2048) { // yes this is very very evil, but for now (pre-alpha) it's a solution ent->r.svFlags |= SVF_BROADCAST; // I need to rotate something that is huge and it's touching too many area portals... } - if ( ent->spawnflags & 4/*SWITCH_SHADER*/ ) - { - ent->s.eFlags |= EF_SHADER_ANIM;//use frame-controlled shader anim - ent->s.frame = 0;//first stage of anim + if (ent->spawnflags & 4 /*SWITCH_SHADER*/) { + ent->s.eFlags |= EF_SHADER_ANIM; // use frame-controlled shader anim + ent->s.frame = 0; // first stage of anim } - if ((ent->spawnflags & 1) || (ent->spawnflags & 2)) - { //so we know it's push/pullable on the client + if ((ent->spawnflags & 1) || (ent->spawnflags & 2)) { // so we know it's push/pullable on the client ent->s.bolt1 = 1; } G_SpawnInt("model2scale", "0", &ent->s.iModelScale); - if (ent->s.iModelScale < 0) - { + if (ent->s.iModelScale < 0) { ent->s.iModelScale = 0; - } - else if (ent->s.iModelScale > 1023) - { + } else if (ent->s.iModelScale > 1023) { ent->s.iModelScale = 1023; } - G_SpawnInt( "hyperspace", "0", &test ); - if ( test ) - { + G_SpawnInt("hyperspace", "0", &test); + if (test) { ent->r.svFlags |= SVF_BROADCAST; // I need to rotate something that is huge and it's touching too many area portals... ent->s.eFlags2 |= EF2_HYPERSPACE; } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); - if (level.mBSPInstanceDepth) - { // this means that this guy will never be updated, moved, changed, etc. + if (level.mBSPInstanceDepth) { // this means that this guy will never be updated, moved, changed, etc. ent->s.eFlags = EF_PERMANENT; } } -void func_static_use ( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior( self, BSET_USE ); +void func_static_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 4/*SWITCH_SHADER*/ ) - { - self->s.frame = self->s.frame ? 0 : 1;//toggle frame + if (self->spawnflags & 4 /*SWITCH_SHADER*/) { + self->s.frame = self->s.frame ? 0 : 1; // toggle frame } - G_UseTargets( self, activator ); + G_UseTargets(self, activator); } /* @@ -2063,27 +1866,21 @@ ROTATING =============================================================================== */ -void func_rotating_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if( self->s.apos.trType == TR_LINEAR ) - { +void func_rotating_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->s.apos.trType == TR_LINEAR) { self->s.apos.trType = TR_STATIONARY; // stop the sound if it stops moving self->s.loopSound = 0; self->s.loopIsSoundset = qfalse; // play stop sound too? - if ( self->soundSet && self->soundSet[0] ) - { + if (self->soundSet && self->soundSet[0]) { self->s.soundSetIndex = G_SoundSetIndex(self->soundSet); - G_AddEvent( self, EV_BMODEL_SOUND, BMS_END ); + G_AddEvent(self, EV_BMODEL_SOUND, BMS_END); } - } - else - { - if ( self->soundSet && self->soundSet[0] ) - { + } else { + if (self->soundSet && self->soundSet[0]) { self->s.soundSetIndex = G_SoundSetIndex(self->soundSet); - G_AddEvent( self, EV_BMODEL_SOUND, BMS_START ); + G_AddEvent(self, EV_BMODEL_SOUND, BMS_START); self->s.loopSound = BMS_MID; self->s.loopIsSoundset = qtrue; } @@ -2100,20 +1897,18 @@ the point around which it is rotated. It will rotate around the Z axis by defaul check either the X_AXIS or Y_AXIS box to change that. "model2" .md3 model to also draw -"model2scale" percent of normal scale (on all x y and z axii) to scale the model2 if there is one. 100 is normal scale, min is 1 (100 times smaller than normal), max is 1000 (ten times normal). -"speed" determines how fast it moves; default value is 100. -"dmg" damage to inflict when blocked (2 default) -"color" constantLight color -"light" constantLight radius -"spinangles" instead of using "speed", you can set use this to set rotation on all 3 axes (pitch yaw and roll) +"model2scale" percent of normal scale (on all x y and z axii) to scale the model2 if there is one. 100 is normal scale, min is 1 (100 times smaller than +normal), max is 1000 (ten times normal). "speed" determines how fast it moves; default value is 100. "dmg" damage to inflict when blocked +(2 default) "color" constantLight color "light" constantLight radius "spinangles" instead of using "speed", you can set use this to set +rotation on all 3 axes (pitch yaw and roll) ================================================== "health" default is 0 If health is set, the following key/values are available: -"numchunks" Multiplies the number of chunks spawned. Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks -"chunksize" scales up/down the chunk size by this number (default is 1) +"numchunks" Multiplies the number of chunks spawned. Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned +chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks "chunksize" scales up/down the chunk size by this number (default is 1) "showhealth" if non-0, will display the health bar on the hud when the crosshair is over this ent (in siege) "teamowner" in siege this will specify which team this thing is "owned" by. To that team the crosshair will @@ -2155,53 +1950,44 @@ Applicable only during Siege gametype: teamnodmg - if 1, team 1 can't damage this. If 2, team 2 can't damage this. */ -void SP_func_breakable( gentity_t *self ); -void SP_func_rotating (gentity_t *ent) { +void SP_func_breakable(gentity_t *self); +void SP_func_rotating(gentity_t *ent) { vec3_t spinangles; - if ( ent->health ) - { + if (ent->health) { int sav_spawnflags = ent->spawnflags; ent->spawnflags = 0; - SP_func_breakable( ent ); + SP_func_breakable(ent); ent->spawnflags = sav_spawnflags; - } - else - { - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); - InitMover( ent ); + } else { + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin ); - VectorCopy( ent->s.apos.trBase, ent->r.currentAngles ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.pos.trBase, ent->r.currentOrigin); + VectorCopy(ent->s.apos.trBase, ent->r.currentAngles); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } G_SpawnInt("model2scale", "0", &ent->s.iModelScale); - if (ent->s.iModelScale < 0) - { + if (ent->s.iModelScale < 0) { ent->s.iModelScale = 0; - } - else if (ent->s.iModelScale > 1023) - { + } else if (ent->s.iModelScale > 1023) { ent->s.iModelScale = 1023; } - if ( G_SpawnVector( "spinangles", "0 0 0", spinangles ) ) - { - ent->speed = VectorLength( spinangles ); + if (G_SpawnVector("spinangles", "0 0 0", spinangles)) { + ent->speed = VectorLength(spinangles); // set the axis of rotation - VectorCopy( spinangles, ent->s.apos.trDelta ); - } - else - { - if ( !ent->speed ) { + VectorCopy(spinangles, ent->s.apos.trDelta); + } else { + if (!ent->speed) { ent->speed = 100; } // set the axis of rotation - if ( ent->spawnflags & 4 ) { + if (ent->spawnflags & 4) { ent->s.apos.trDelta[2] = ent->speed; - } else if ( ent->spawnflags & 8 ) { + } else if (ent->spawnflags & 8) { ent->s.apos.trDelta[0] = ent->speed; } else { ent->s.apos.trDelta[1] = ent->speed; @@ -2210,23 +1996,20 @@ void SP_func_rotating (gentity_t *ent) { ent->s.apos.trType = TR_LINEAR; if (!ent->damage) { - if ( (ent->spawnflags&16) )//IMPACT + if ((ent->spawnflags & 16)) // IMPACT { ent->damage = 10000; - } - else - { + } else { ent->damage = 2; } } - if ( (ent->spawnflags&2) )//RADAR - {//show up on Radar at close range and play impact sound when close...? Range based on my size - ent->s.speed = Distance( ent->r.absmin, ent->r.absmax )*0.5f; + if ((ent->spawnflags & 2)) // RADAR + { // show up on Radar at close range and play impact sound when close...? Range based on my size + ent->s.speed = Distance(ent->r.absmin, ent->r.absmax) * 0.5f; ent->s.eFlags |= EF_RADAROBJECT; } } - /* =============================================================================== @@ -2235,7 +2018,6 @@ BOBBING =============================================================================== */ - /*QUAKED func_bobbing (0 .5 .8) ? X_AXIS Y_AXIS x x x x PLAYER_USE INACTIVE Normally bobs on the Z axis "model2" .md3 model to also draw @@ -2246,29 +2028,29 @@ Normally bobs on the Z axis "color" constantLight color "light" constantLight radius */ -void SP_func_bobbing (gentity_t *ent) { - float height; - float phase; +void SP_func_bobbing(gentity_t *ent) { + float height; + float phase; - G_SpawnFloat( "speed", "4", &ent->speed ); - G_SpawnFloat( "height", "32", &height ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "4", &ent->speed); + G_SpawnFloat("height", "32", &height); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); - InitMover( ent ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); ent->s.pos.trDuration = ent->speed * 1000; ent->s.pos.trTime = ent->s.pos.trDuration * phase; ent->s.pos.trType = TR_SINE; // set the axis of bobbing - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.pos.trDelta[0] = height; - } else if ( ent->spawnflags & 2 ) { + } else if (ent->spawnflags & 2) { ent->s.pos.trDelta[1] = height; } else { ent->s.pos.trDelta[2] = height; @@ -2283,7 +2065,6 @@ PENDULUM =============================================================================== */ - /*QUAKED func_pendulum (0 .5 .8) ? x x x x x x PLAYER_USE INACTIVE You need to have an origin brush as part of this entity. Pendulums always swing north / south on unrotated models. Add an angles field to the model to allow rotation in other directions. @@ -2296,33 +2077,33 @@ Pendulum frequency is a physical constant based on the length of the beam and gr "light" constantLight radius */ void SP_func_pendulum(gentity_t *ent) { - float freq; - float length; - float phase; - float speed; + float freq; + float length; + float phase; + float speed; - G_SpawnFloat( "speed", "30", &speed ); - G_SpawnInt( "dmg", "2", &ent->damage ); - G_SpawnFloat( "phase", "0", &phase ); + G_SpawnFloat("speed", "30", &speed); + G_SpawnInt("dmg", "2", &ent->damage); + G_SpawnFloat("phase", "0", &phase); - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); // find pendulum length - length = fabs( ent->r.mins[2] ); - if ( length < 8 ) { + length = fabs(ent->r.mins[2]); + if (length < 8) { length = 8; } - freq = 1 / ( M_PI * 2 ) * sqrt( g_gravity.value / ( 3 * length ) ); + freq = 1 / (M_PI * 2) * sqrt(g_gravity.value / (3 * length)); - ent->s.pos.trDuration = ( 1000 / freq ); + ent->s.pos.trDuration = (1000 / freq); - InitMover( ent ); + InitMover(ent); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->s.apos.trDuration = 1000 / freq; ent->s.apos.trTime = ent->s.apos.trDuration * phase; @@ -2338,57 +2119,54 @@ BREAKABLE BRUSH =============================================================================== */ //--------------------------------------------------- -static void CacheChunkEffects( material_t material ) -{ - switch( material ) - { +static void CacheChunkEffects(material_t material) { + switch (material) { case MAT_GLASS: - G_EffectIndex( "chunks/glassbreak" ); + G_EffectIndex("chunks/glassbreak"); break; case MAT_GLASS_METAL: - G_EffectIndex( "chunks/glassbreak" ); - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/glassbreak"); + G_EffectIndex("chunks/metalexplode"); break; case MAT_ELECTRICAL: case MAT_ELEC_METAL: - G_EffectIndex( "chunks/sparkexplode" ); + G_EffectIndex("chunks/sparkexplode"); break; case MAT_METAL: case MAT_METAL2: case MAT_METAL3: case MAT_CRATE1: case MAT_CRATE2: - G_EffectIndex( "chunks/metalexplode" ); + G_EffectIndex("chunks/metalexplode"); break; case MAT_GRATE1: - G_EffectIndex( "chunks/grateexplode" ); + G_EffectIndex("chunks/grateexplode"); break; case MAT_DRK_STONE: case MAT_LT_STONE: case MAT_GREY_STONE: case MAT_WHITE_METAL: // what is this crap really supposed to be?? case MAT_SNOWY_ROCK: - G_EffectIndex( "chunks/rockbreaklg" ); - G_EffectIndex( "chunks/rockbreakmed" ); + G_EffectIndex("chunks/rockbreaklg"); + G_EffectIndex("chunks/rockbreakmed"); break; case MAT_ROPE: - G_EffectIndex( "chunks/ropebreak" ); -// G_SoundIndex(); // FIXME: give it a sound + G_EffectIndex("chunks/ropebreak"); + // G_SoundIndex(); // FIXME: give it a sound break; default: break; } } -void G_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkType ) -{ +void G_MiscModelExplosion(vec3_t mins, vec3_t maxs, int size, material_t chunkType) { gentity_t *te; vec3_t mid; - VectorAdd( mins, maxs, mid ); - VectorScale( mid, 0.5f, mid ); + VectorAdd(mins, maxs, mid); + VectorScale(mid, 0.5f, mid); - te = G_TempEntity( mid, EV_MISC_MODEL_EXP ); + te = G_TempEntity(mid, EV_MISC_MODEL_EXP); VectorCopy(maxs, te->s.origin2); VectorCopy(mins, te->s.angles2); @@ -2396,12 +2174,11 @@ void G_MiscModelExplosion( vec3_t mins, vec3_t maxs, int size, material_t chunkT te->s.eventParm = chunkType; } -void G_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, - float speed, int numChunks, material_t chunkType, int customChunk, float baseScale ) -{ - gentity_t *te = G_TempEntity( origin, EV_DEBRIS ); +void G_Chunks(int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, const vec3_t maxs, float speed, int numChunks, material_t chunkType, + int customChunk, float baseScale) { + gentity_t *te = G_TempEntity(origin, EV_DEBRIS); - //Now it's time to cram everything horribly into the entitystate of an event entity. + // Now it's time to cram everything horribly into the entitystate of an event entity. te->s.owner = owner; VectorCopy(origin, te->s.origin); VectorCopy(normal, te->s.angles); @@ -2415,24 +2192,21 @@ void G_Chunks( int owner, vec3_t origin, const vec3_t normal, const vec3_t mins, } //-------------------------------------- -void funcBBrushDieGo (gentity_t *self) -{ - vec3_t org, dir, up; - gentity_t *attacker = self->enemy; - float scale; - int i, numChunks, size = 0; - material_t chunkType = self->material; +void funcBBrushDieGo(gentity_t *self) { + vec3_t org, dir, up; + gentity_t *attacker = self->enemy; + float scale; + int i, numChunks, size = 0; + material_t chunkType = self->material; // if a missile is stuck to us, blow it up so we don't look dumb - for ( i = 0; i < MAX_GENTITIES; i++ ) - { - if ( g_entities[i].s.groundEntityNum == self->s.number && ( g_entities[i].s.eFlags & EF_MISSILE_STICK )) - { - G_Damage( &g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH ); //?? MOD? + for (i = 0; i < MAX_GENTITIES; i++) { + if (g_entities[i].s.groundEntityNum == self->s.number && (g_entities[i].s.eFlags & EF_MISSILE_STICK)) { + G_Damage(&g_entities[i], self, self, NULL, NULL, 99999, 0, MOD_CRUSH); //?? MOD? } } - //So chunks don't get stuck inside me + // So chunks don't get stuck inside me self->s.solid = 0; self->r.contents = 0; self->clipmask = 0; @@ -2440,91 +2214,80 @@ void funcBBrushDieGo (gentity_t *self) VectorSet(up, 0, 0, 1); - if ( self->target && attacker != NULL ) - { + if (self->target && attacker != NULL) { G_UseTargets(self, attacker); } - VectorSubtract( self->r.absmax, self->r.absmin, org );// size + VectorSubtract(self->r.absmax, self->r.absmin, org); // size numChunks = Q_flrand(0.0f, 1.0f) * 6 + 18; // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = sqrt( sqrt( org[0] * org[1] * org[2] )) * 1.75f; + scale = sqrt(sqrt(org[0] * org[1] * org[2])) * 1.75f; - if ( scale > 48 ) - { + if (scale > 48) { size = 2; - } - else if ( scale > 24 ) - { + } else if (scale > 24) { size = 1; } scale = scale / numChunks; - if ( self->radius > 0.0f ) - { + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit + //weak numChunks *= self->radius; } - VectorMA( self->r.absmin, 0.5, org, org ); - VectorAdd( self->r.absmin,self->r.absmax, org ); - VectorScale( org, 0.5f, org ); + VectorMA(self->r.absmin, 0.5, org, org); + VectorAdd(self->r.absmin, self->r.absmax, org); + VectorScale(org, 0.5f, org); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( org, attacker->r.currentOrigin, dir ); - VectorNormalize( dir ); - } - else - { + if (attacker != NULL && attacker->client) { + VectorSubtract(org, attacker->r.currentOrigin, dir); + VectorNormalize(dir); + } else { VectorCopy(up, dir); } - if ( !(self->spawnflags & 2048) ) // NO_EXPLOSION + if (!(self->spawnflags & 2048)) // NO_EXPLOSION { // we are allowed to explode - G_MiscModelExplosion( self->r.absmin, self->r.absmax, size, chunkType ); + G_MiscModelExplosion(self->r.absmin, self->r.absmax, size, chunkType); } - if (self->genericValue15) - { //a custom effect to play + if (self->genericValue15) { // a custom effect to play vec3_t ang; VectorSet(ang, 0.0f, 1.0f, 0.0f); G_PlayEffectID(self->genericValue15, org, ang); } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { + if (self->splashDamage > 0 && self->splashRadius > 0) { gentity_t *te; - //explode - G_RadiusDamage( org, self, self->splashDamage, self->splashRadius, self, NULL, MOD_UNKNOWN ); + // explode + G_RadiusDamage(org, self, self->splashDamage, self->splashRadius, self, NULL, MOD_UNKNOWN); - te = G_TempEntity( org, EV_GENERAL_SOUND ); + te = G_TempEntity(org, EV_GENERAL_SOUND); te->s.eventParm = G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); } - //FIXME: base numChunks off size? - G_Chunks( self->s.number, org, dir, self->r.absmin, self->r.absmax, 300, numChunks, chunkType, 0, (scale*self->mass) ); + // FIXME: base numChunks off size? + G_Chunks(self->s.number, org, dir, self->r.absmin, self->r.absmax, 300, numChunks, chunkType, 0, (scale * self->mass)); - trap->AdjustAreaPortalState( (sharedEntity_t *)self, qtrue ); + trap->AdjustAreaPortalState((sharedEntity_t *)self, qtrue); self->think = G_FreeEntity; self->nextthink = level.time + 50; - //G_FreeEntity( self ); + // G_FreeEntity( self ); } -void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ - self->takedamage = qfalse;//stop chain reaction runaway loops +void funcBBrushDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { + self->takedamage = qfalse; // stop chain reaction runaway loops self->enemy = attacker; - if(self->delay) - { + if (self->delay) { self->think = funcBBrushDieGo; self->nextthink = level.time + floor(self->delay * 1000.0f); return; @@ -2533,82 +2296,62 @@ void funcBBrushDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, funcBBrushDieGo(self); } -void funcBBrushUse (gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior( self, BSET_USE ); - if(self->spawnflags & 64) - {//Using it doesn't break it, makes it use it's targets - if(self->target && self->target[0]) - { +void funcBBrushUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + if (self->spawnflags & 64) { // Using it doesn't break it, makes it use it's targets + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - } - else - { + } else { funcBBrushDie(self, other, activator, self->health, MOD_UNKNOWN); } } -void funcBBrushPain(gentity_t *self, gentity_t *attacker, int damage) -{ - if ( self->painDebounceTime > level.time ) - { +void funcBBrushPain(gentity_t *self, gentity_t *attacker, int damage) { + if (self->painDebounceTime > level.time) { return; } - if ( self->paintarget && self->paintarget[0] ) - { - if (!self->activator) - { - if (attacker && attacker->inuse && attacker->client) - { - G_UseTargets2 (self, attacker, self->paintarget); + if (self->paintarget && self->paintarget[0]) { + if (!self->activator) { + if (attacker && attacker->inuse && attacker->client) { + G_UseTargets2(self, attacker, self->paintarget); } - } - else - { - G_UseTargets2 (self, self->activator, self->paintarget); + } else { + G_UseTargets2(self, self->activator, self->paintarget); } } - G_ActivateBehavior( self, BSET_PAIN ); + G_ActivateBehavior(self, BSET_PAIN); - if ( self->material == MAT_DRK_STONE - || self->material == MAT_LT_STONE - || self->material == MAT_GREY_STONE - || self->material == MAT_SNOWY_ROCK ) - { - vec3_t org, dir; - float scale; - int numChunks; - VectorSubtract( self->r.absmax, self->r.absmin, org );// size + if (self->material == MAT_DRK_STONE || self->material == MAT_LT_STONE || self->material == MAT_GREY_STONE || self->material == MAT_SNOWY_ROCK) { + vec3_t org, dir; + float scale; + int numChunks; + VectorSubtract(self->r.absmax, self->r.absmin, org); // size // This formula really has no logical basis other than the fact that it seemed to be the closest to yielding the results that I wanted. // Volume is length * width * height...then break that volume down based on how many chunks we have - scale = VectorLength( org ) / 100.0f; - VectorMA( self->r.absmin, 0.5, org, org ); - VectorAdd( self->r.absmin,self->r.absmax, org ); - VectorScale( org, 0.5f, org ); - if ( attacker != NULL && attacker->client ) - { - VectorSubtract( attacker->r.currentOrigin, org, dir ); - VectorNormalize( dir ); - } - else - { - VectorSet( dir, 0, 0, 1 ); + scale = VectorLength(org) / 100.0f; + VectorMA(self->r.absmin, 0.5, org, org); + VectorAdd(self->r.absmin, self->r.absmax, org); + VectorScale(org, 0.5f, org); + if (attacker != NULL && attacker->client) { + VectorSubtract(attacker->r.currentOrigin, org, dir); + VectorNormalize(dir); + } else { + VectorSet(dir, 0, 0, 1); } - numChunks = Q_irand( 1, 3 ); - if ( self->radius > 0.0f ) - { + numChunks = Q_irand(1, 3); + if (self->radius > 0.0f) { // designer wants to scale number of chunks, helpful because the above scale code is far from perfect - // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a bit weak - numChunks = ceil(numChunks*self->radius); + // I do this after the scale calculation because it seems that the chunk size generally seems to be very close, it's just the number of chunks is a + //bit weak + numChunks = ceil(numChunks * self->radius); } - G_Chunks( self->s.number, org, dir, self->r.absmin, self->r.absmax, 300, numChunks, self->material, 0, (scale*self->mass) ); + G_Chunks(self->s.number, org, dir, self->r.absmin, self->r.absmax, 300, numChunks, self->material, 0, (scale * self->mass)); } - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->pain = 0; return; } @@ -2616,60 +2359,55 @@ void funcBBrushPain(gentity_t *self, gentity_t *attacker, int damage) self->painDebounceTime = level.time + self->wait; } -static void InitBBrush ( gentity_t *ent ) -{ - float light; - vec3_t color; - qboolean lightSet, colorSet; +static void InitBBrush(gentity_t *ent) { + float light; + vec3_t color; + qboolean lightSet, colorSet; - VectorCopy( ent->s.origin, ent->pos1 ); + VectorCopy(ent->s.origin, ent->pos1); - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); ent->die = funcBBrushDie; ent->flags |= FL_BBRUSH; - //This doesn't have to be an svFlag, can just be a flag. - //And it might not be needed anyway. - //ent->r.svFlags |= SVF_BBRUSH; - + // This doesn't have to be an svFlag, can just be a flag. + // And it might not be needed anyway. + // ent->r.svFlags |= SVF_BBRUSH; // if the "model2" key is set, use a seperate model // for drawing, but clip against the brushes - if ( ent->model2 && ent->model2[0] ) - { - ent->s.modelindex2 = G_ModelIndex( ent->model2 ); + if (ent->model2 && ent->model2[0]) { + ent->s.modelindex2 = G_ModelIndex(ent->model2); } // if the "color" or "light" keys are set, setup constantLight - lightSet = G_SpawnFloat( "light", "100", &light ); - colorSet = G_SpawnVector( "color", "1 1 1", color ); - if ( lightSet || colorSet ) - { - int r, g, b, i; + lightSet = G_SpawnFloat("light", "100", &light); + colorSet = G_SpawnVector("color", "1 1 1", color); + if (lightSet || colorSet) { + int r, g, b, i; r = color[0] * 255; - if ( r > 255 ) { + if (r > 255) { r = 255; } g = color[1] * 255; - if ( g > 255 ) { + if (g > 255) { g = 255; } b = color[2] * 255; - if ( b > 255 ) { + if (b > 255) { b = 255; } i = light / 4; - if ( i > 255 ) { + if (i > 255) { i = 255; } - ent->s.constantLight = r | ( g << 8 ) | ( b << 16 ) | ( i << 24 ); + ent->s.constantLight = r | (g << 8) | (b << 16) | (i << 24); } - if(ent->spawnflags & 128) - {//Can be used by the player's BUTTON_USE + if (ent->spawnflags & 128) { // Can be used by the player's BUTTON_USE ent->r.svFlags |= SVF_PLAYER_USABLE; } @@ -2677,12 +2415,10 @@ static void InitBBrush ( gentity_t *ent ) trap->LinkEntity((sharedEntity_t *)ent); ent->s.pos.trType = TR_STATIONARY; - VectorCopy( ent->pos1, ent->s.pos.trBase ); + VectorCopy(ent->pos1, ent->s.pos.trBase); } -void funcBBrushTouch( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ -} +void funcBBrushTouch(gentity_t *ent, gentity_t *other, trace_t *trace) {} /*QUAKED func_breakable (0 .8 .5) ? INVINCIBLE IMPACT CRUSHER THIN SABERONLY HEAVY_WEAP USE_NOT_BREAK PLAYER_USE NO_EXPLOSION INVINCIBLE - can only be broken by being used @@ -2704,9 +2440,9 @@ When destroyed, fires it's trigger and chunks and plays sound "noise" or sound f "model2" .md3 model to also draw "target" all entities with a matching targetname will be used when this is destoryed "health" default is 10 -"numchunks" Multiplies the number of chunks spawned. Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks -"chunksize" scales up/down the chunk size by this number (default is 1) -"playfx" path of effect to play on death +"numchunks" Multiplies the number of chunks spawned. Chunk code tries to pick a good volume of chunks, but you can alter this to scale the number of spawned +chunks. (default 1) (.5) is half as many chunks, (2) is twice as many chunks "chunksize" scales up/down the chunk size by this number (default is 1) "playfx" +path of effect to play on death "showhealth" if non-0, will display the health bar on the hud when the crosshair is over this ent (in siege) "teamowner" in siege this will specify which team this thing is "owned" by. To that team the crosshair will @@ -2748,71 +2484,60 @@ Applicable only during Siege gametype: teamnodmg - if 1, team 1 can't damage this. If 2, team 2 can't damage this. */ -void SP_func_breakable( gentity_t *self ) -{ +void SP_func_breakable(gentity_t *self) { int t; char *s = NULL; G_SpawnString("playfx", "", &s); - if (s && s[0]) - { //should we play a special death effect? + if (s && s[0]) { // should we play a special death effect? self->genericValue15 = G_EffectIndex(s); - } - else - { + } else { self->genericValue15 = 0; } - if(!(self->spawnflags & 1)) - { - if(!self->health) - { + if (!(self->spawnflags & 1)) { + if (!self->health) { self->health = 10; } } - G_SpawnInt( "showhealth", "0", &t ); + G_SpawnInt("showhealth", "0", &t); - if (t) - { //a non-0 maxhealth value will mean we want to show the health on the hud + if (t) { // a non-0 maxhealth value will mean we want to show the health on the hud self->maxHealth = self->health; G_ScaleNetHealth(self); } - //NOTE: g_spawn.c does this automatically now - //G_SpawnInt( "teamowner", "0", &t ); - //self->s.teamowner = t; + // NOTE: g_spawn.c does this automatically now + // G_SpawnInt( "teamowner", "0", &t ); + // self->s.teamowner = t; - if ( self->spawnflags & 16 ) // saber only + if (self->spawnflags & 16) // saber only { self->flags |= FL_DMG_BY_SABER_ONLY; - } - else if ( self->spawnflags & 32 ) // heavy weap + } else if (self->spawnflags & 32) // heavy weap { self->flags |= FL_DMG_BY_HEAVY_WEAP_ONLY; } - if (self->health) - { + if (self->health) { self->takedamage = qtrue; } - G_SoundIndex("sound/weapons/explosions/cargoexplode.wav");//precaching - G_SpawnFloat( "radius", "1", &self->radius ); // used to scale chunk code if desired by a designer - G_SpawnInt( "material", "0", (int*)&self->material ); + G_SoundIndex("sound/weapons/explosions/cargoexplode.wav"); // precaching + G_SpawnFloat("radius", "1", &self->radius); // used to scale chunk code if desired by a designer + G_SpawnInt("material", "0", (int *)&self->material); - G_SpawnInt( "splashDamage", "0", &self->splashDamage ); - G_SpawnInt( "splashRadius", "0", &self->splashRadius ); + G_SpawnInt("splashDamage", "0", &self->splashDamage); + G_SpawnInt("splashRadius", "0", &self->splashRadius); - CacheChunkEffects( self->material ); + CacheChunkEffects(self->material); self->use = funcBBrushUse; - //if ( self->paintarget ) - { - self->pain = funcBBrushPain; - } + // if ( self->paintarget ) + { self->pain = funcBBrushPain; } self->touch = funcBBrushTouch; @@ -2826,40 +2551,33 @@ void SP_func_breakable( gentity_t *self ) } } */ - if ( self->team && self->team[0] && level.gametype == GT_SIEGE && - !self->teamnodmg) - { + if (self->team && self->team[0] && level.gametype == GT_SIEGE && !self->teamnodmg) { self->teamnodmg = atoi(self->team); } self->team = NULL; if (!self->model) { - trap->Error( ERR_DROP, "func_breakable with NULL model\n" ); + trap->Error(ERR_DROP, "func_breakable with NULL model\n"); } - InitBBrush( self ); + InitBBrush(self); - if ( !self->radius ) - {//numchunks multiplier + if (!self->radius) { // numchunks multiplier self->radius = 1.0f; } - if ( !self->mass ) - {//chunksize multiplier + if (!self->mass) { // chunksize multiplier self->mass = 1.0f; } - self->genericValue4 = 1; //so damage sys knows it's a bbrush + self->genericValue4 = 1; // so damage sys knows it's a bbrush } -qboolean G_EntIsBreakable( int entityNum ) -{ +qboolean G_EntIsBreakable(int entityNum) { gentity_t *ent; - if ( entityNum < 0 || entityNum >= ENTITYNUM_WORLD ) - { + if (entityNum < 0 || entityNum >= ENTITYNUM_WORLD) { return qfalse; } ent = &g_entities[entityNum]; - if ( (ent->r.svFlags & SVF_GLASS_BRUSH) ) - { + if ((ent->r.svFlags & SVF_GLASS_BRUSH)) { return qtrue; } /* @@ -2868,17 +2586,14 @@ qboolean G_EntIsBreakable( int entityNum ) return qtrue; } */ - if ( !Q_stricmp( "func_breakable", ent->classname ) ) - { + if (!Q_stricmp("func_breakable", ent->classname)) { return qtrue; } - if ( !Q_stricmp( "misc_model_breakable", ent->classname ) ) - { + if (!Q_stricmp("misc_model_breakable", ent->classname)) { return qtrue; } - if ( !Q_stricmp( "misc_maglock", ent->classname ) ) - { + if (!Q_stricmp("misc_maglock", ent->classname)) { return qtrue; } @@ -2892,27 +2607,25 @@ GLASS =============================================================================== */ -void GlassDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void GlassDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { gentity_t *te; vec3_t dif; - if (self->genericValue5) - { //was already destroyed, do not retrigger it + if (self->genericValue5) { // was already destroyed, do not retrigger it return; } self->genericValue5 = 1; - dif[0] = (self->r.absmax[0]+self->r.absmin[0])/2; - dif[1] = (self->r.absmax[1]+self->r.absmin[1])/2; - dif[2] = (self->r.absmax[2]+self->r.absmin[2])/2; + dif[0] = (self->r.absmax[0] + self->r.absmin[0]) / 2; + dif[1] = (self->r.absmax[1] + self->r.absmin[1]) / 2; + dif[2] = (self->r.absmax[2] + self->r.absmin[2]) / 2; G_UseTargets(self, attacker); self->splashRadius = 40; // ?? some random number, maybe it's ok? - te = G_TempEntity( dif, EV_GLASS_SHATTER ); + te = G_TempEntity(dif, EV_GLASS_SHATTER); te->s.genericenemyindex = self->s.number; VectorCopy(self->pos1, te->s.origin); VectorCopy(self->pos2, te->s.angles); @@ -2922,18 +2635,17 @@ void GlassDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int da G_FreeEntity(self); } -void GlassDie_Old(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void GlassDie_Old(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { gentity_t *te; vec3_t dif; - dif[0] = (self->r.absmax[0]+self->r.absmin[0])/2; - dif[1] = (self->r.absmax[1]+self->r.absmin[1])/2; - dif[2] = (self->r.absmax[2]+self->r.absmin[2])/2; + dif[0] = (self->r.absmax[0] + self->r.absmin[0]) / 2; + dif[1] = (self->r.absmax[1] + self->r.absmin[1]) / 2; + dif[2] = (self->r.absmax[2] + self->r.absmin[2]) / 2; G_UseTargets(self, attacker); - te = G_TempEntity( dif, EV_GLASS_SHATTER ); + te = G_TempEntity(dif, EV_GLASS_SHATTER); te->s.genericenemyindex = self->s.number; VectorCopy(self->r.maxs, te->s.origin); VectorCopy(self->r.mins, te->s.angles); @@ -2941,28 +2653,26 @@ void GlassDie_Old(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, in G_FreeEntity(self); } -void GlassPain(gentity_t *self, gentity_t *attacker, int damage) -{ - //trap->Print("Mr. Glass says: PLZ NO IT HURTS\n"); - //Make "cracking" sound? +void GlassPain(gentity_t *self, gentity_t *attacker, int damage) { + // trap->Print("Mr. Glass says: PLZ NO IT HURTS\n"); + // Make "cracking" sound? } -void GlassUse(gentity_t *self, gentity_t *other, gentity_t *activator) -{ +void GlassUse(gentity_t *self, gentity_t *other, gentity_t *activator) { vec3_t temp1, temp2; - //no direct object to blame for the break, so fill the values with whatever - VectorAdd( self->r.mins, self->r.maxs, temp1 ); - VectorScale( temp1, 0.5f, temp1 ); + // no direct object to blame for the break, so fill the values with whatever + VectorAdd(self->r.mins, self->r.maxs, temp1); + VectorScale(temp1, 0.5f, temp1); - VectorAdd( other->r.mins, other->r.maxs, temp2 ); - VectorScale( temp2, 0.5f, temp2 ); + VectorAdd(other->r.mins, other->r.maxs, temp2); + VectorScale(temp2, 0.5f, temp2); - VectorSubtract( temp1, temp2, self->pos2 ); - VectorCopy( temp1, self->pos1 ); + VectorSubtract(temp1, temp2, self->pos2); + VectorCopy(temp1, self->pos1); - VectorNormalize( self->pos2 ); - VectorScale( self->pos2, 390, self->pos2 ); + VectorNormalize(self->pos2); + VectorScale(self->pos2, 390, self->pos2); GlassDie(self, other, activator, 100, MOD_UNKNOWN); } @@ -2974,16 +2684,15 @@ Breakable glass "light" constantLight radius "maxshards" Max number of shards to spawn on glass break */ -void SP_func_glass( gentity_t *ent ) { - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); - InitMover( ent ); +void SP_func_glass(gentity_t *ent) { + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); + InitMover(ent); ent->r.svFlags = SVF_GLASS_BRUSH; - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); - if (!ent->health) - { + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); + if (!ent->health) { ent->health = 1; } @@ -2995,12 +2704,9 @@ void SP_func_glass( gentity_t *ent ) { ent->moverState = MOVER_POS1; - if (ent->spawnflags & 1) - { + if (ent->spawnflags & 1) { ent->takedamage = qfalse; - } - else - { + } else { ent->takedamage = qtrue; } @@ -3009,106 +2715,85 @@ void SP_func_glass( gentity_t *ent ) { ent->pain = GlassPain; } -void func_usable_use (gentity_t *self, gentity_t *other, gentity_t *activator); +void func_usable_use(gentity_t *self, gentity_t *other, gentity_t *activator); -extern gentity_t *G_TestEntityPosition( gentity_t *ent ); -void func_wait_return_solid( gentity_t *self ) -{ - //once a frame, see if it's clear. +extern gentity_t *G_TestEntityPosition(gentity_t *ent); +void func_wait_return_solid(gentity_t *self) { + // once a frame, see if it's clear. self->clipmask = CONTENTS_BODY; - if ( !(self->spawnflags&16) || G_TestEntityPosition( self ) == NULL ) - { - trap->SetBrushModel( (sharedEntity_t *)self, self->model ); - InitMover( self ); - VectorCopy( self->s.origin, self->s.pos.trBase ); - VectorCopy( self->s.origin, self->r.currentOrigin ); + if (!(self->spawnflags & 16) || G_TestEntityPosition(self) == NULL) { + trap->SetBrushModel((sharedEntity_t *)self, self->model); + InitMover(self); + VectorCopy(self->s.origin, self->s.pos.trBase); + VectorCopy(self->s.origin, self->r.currentOrigin); self->r.svFlags &= ~SVF_NOCLIENT; self->s.eFlags &= ~EF_NODRAW; self->use = func_usable_use; self->clipmask = 0; - if ( self->target2 && self->target2[0] ) - { - G_UseTargets2( self, self->activator, self->target2 ); + if (self->target2 && self->target2[0]) { + G_UseTargets2(self, self->activator, self->target2); } - //FIXME: Animations? + // FIXME: Animations? /*if ( self->s.eFlags & EF_ANIM_ONCE ) {//Start our anim self->s.frame = 0; }*/ - } - else - { + } else { self->clipmask = 0; self->think = func_wait_return_solid; self->nextthink = level.time + FRAMETIME; } } -void func_usable_think( gentity_t *self ) -{ - if ( self->spawnflags & 8 ) - { - self->r.svFlags |= SVF_PLAYER_USABLE; //Replace the usable flag +void func_usable_think(gentity_t *self) { + if (self->spawnflags & 8) { + self->r.svFlags |= SVF_PLAYER_USABLE; // Replace the usable flag self->use = func_usable_use; self->think = 0; } } -qboolean G_EntIsRemovableUsable( int entNum ) -{ +qboolean G_EntIsRemovableUsable(int entNum) { gentity_t *ent = &g_entities[entNum]; - if ( ent->classname && !Q_stricmp( "func_usable", ent->classname ) ) - { - if ( !(ent->s.eFlags&EF_SHADER_ANIM) && !(ent->spawnflags&8) && ent->targetname ) - {//not just a shader-animator and not ALWAYS_ON, so it must be removable somehow + if (ent->classname && !Q_stricmp("func_usable", ent->classname)) { + if (!(ent->s.eFlags & EF_SHADER_ANIM) && !(ent->spawnflags & 8) && + ent->targetname) { // not just a shader-animator and not ALWAYS_ON, so it must be removable somehow return qtrue; } } return qfalse; } -void func_usable_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{//Toggle on and off - G_ActivateBehavior( self, BSET_USE ); - if ( self->s.eFlags & EF_SHADER_ANIM ) - {//animate shader when used - self->s.frame++;//inc frame - if ( self->s.frame > self->genericValue5 ) - {//wrap around +void func_usable_use(gentity_t *self, gentity_t *other, gentity_t *activator) { // Toggle on and off + G_ActivateBehavior(self, BSET_USE); + if (self->s.eFlags & EF_SHADER_ANIM) { // animate shader when used + self->s.frame++; // inc frame + if (self->s.frame > self->genericValue5) { // wrap around self->s.frame = 0; } - if ( self->target && self->target[0] ) - { - G_UseTargets( self, activator ); + if (self->target && self->target[0]) { + G_UseTargets(self, activator); } - } - else if ( self->spawnflags & 8 ) - {//ALWAYS_ON - //Remove the ability to use the entity directly + } else if (self->spawnflags & 8) { // ALWAYS_ON + // Remove the ability to use the entity directly self->r.svFlags &= ~SVF_PLAYER_USABLE; - //also remove ability to call any use func at all! + // also remove ability to call any use func at all! self->use = 0; - if(self->target && self->target[0]) - { + if (self->target && self->target[0]) { G_UseTargets(self, activator); } - if ( self->wait ) - { + if (self->wait) { self->think = func_usable_think; - self->nextthink = level.time + ( self->wait * 1000 ); + self->nextthink = level.time + (self->wait * 1000); } return; - } - else if ( !self->count ) - {//become solid again + } else if (!self->count) { // become solid again self->count = 1; - func_wait_return_solid( self ); - } - else - { + func_wait_return_solid(self); + } else { self->s.solid = 0; self->r.contents = 0; self->clipmask = 0; @@ -3116,8 +2801,7 @@ void func_usable_use (gentity_t *self, gentity_t *other, gentity_t *activator) self->s.eFlags |= EF_NODRAW; self->count = 0; - if(self->target && self->target[0]) - { + if (self->target && self->target[0]) { G_UseTargets(self, activator); } self->think = 0; @@ -3125,13 +2809,9 @@ void func_usable_use (gentity_t *self, gentity_t *other, gentity_t *activator) } } -void func_usable_pain(gentity_t *self, gentity_t *attacker, int damage) -{ - GlobalUse(self, attacker, attacker); -} +void func_usable_pain(gentity_t *self, gentity_t *attacker, int damage) { GlobalUse(self, attacker, attacker); } -void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void func_usable_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { self->takedamage = qfalse; GlobalUse(self, inflictor, attacker); } @@ -3157,31 +2837,25 @@ teamuser - if 1, team 2 can't use this. If 2, team 1 can't use this. */ -void SP_func_usable( gentity_t *self ) -{ - trap->SetBrushModel( (sharedEntity_t *)self, self->model ); - InitMover( self ); - VectorCopy( self->s.origin, self->s.pos.trBase ); - VectorCopy( self->s.origin, self->r.currentOrigin ); - VectorCopy( self->s.origin, self->pos1 ); +void SP_func_usable(gentity_t *self) { + trap->SetBrushModel((sharedEntity_t *)self, self->model); + InitMover(self); + VectorCopy(self->s.origin, self->s.pos.trBase); + VectorCopy(self->s.origin, self->r.currentOrigin); + VectorCopy(self->s.origin, self->pos1); G_SpawnInt("endframe", "0", &self->genericValue5); - if ( self->model2 && self->model2[0] ) - { - if ( strstr( self->model2, ".glm" )) - { //for now, not supported in MP. + if (self->model2 && self->model2[0]) { + if (strstr(self->model2, ".glm")) { // for now, not supported in MP. self->s.modelindex2 = 0; - } - else - { - self->s.modelindex2 = G_ModelIndex( self->model2 ); + } else { + self->s.modelindex2 = G_ModelIndex(self->model2); } } self->count = 1; - if (self->spawnflags & 1) - { + if (self->spawnflags & 1) { self->s.solid = 0; self->r.contents = 0; self->clipmask = 0; @@ -3190,7 +2864,7 @@ void SP_func_usable( gentity_t *self ) self->count = 0; } - //FIXME: Animation? + // FIXME: Animation? /* if (self->spawnflags & 2) { @@ -3205,24 +2879,21 @@ void SP_func_usable( gentity_t *self ) self->use = func_usable_use; - if ( self->health ) - { + if (self->health) { self->takedamage = qtrue; self->die = func_usable_die; self->pain = func_usable_pain; } - if ( self->genericValue5 > 0 ) - { + if (self->genericValue5 > 0) { self->s.frame = 0; self->s.eFlags |= EF_SHADER_ANIM; self->s.time = self->genericValue5 + 1; } - trap->LinkEntity ((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } - /* =============================================================================== @@ -3231,36 +2902,31 @@ WALL =============================================================================== */ -//static -slc -void use_wall( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - G_ActivateBehavior(ent,BSET_USE); +// static -slc +void use_wall(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); // Not there so make it there - if (!(ent->r.contents & CONTENTS_SOLID)) - { + if (!(ent->r.contents & CONTENTS_SOLID)) { ent->r.svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; ent->r.contents = CONTENTS_SOLID; - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - trap->AdjustAreaPortalState( (sharedEntity_t *)ent, qfalse ); + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qfalse); } } // Make it go away - else - { + else { ent->r.contents = 0; ent->r.svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; - if ( !(ent->spawnflags&1) ) - {//START_OFF doesn't effect area portals - trap->AdjustAreaPortalState( (sharedEntity_t *)ent, qtrue ); + if (!(ent->spawnflags & 1)) { // START_OFF doesn't effect area portals + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qtrue); } } } -#define FUNC_WALL_OFF 1 +#define FUNC_WALL_OFF 1 /*QUAKED func_wall (0 .5 .8) ? START_OFF x x x x x PLAYER_USE INACTIVE PLAYER_USE Player can use it with the use button @@ -3273,20 +2939,18 @@ A bmodel that just sits there, doing nothing. Can be used for conditional walls START_OFF - the wall will not be there */ -void SP_func_wall( gentity_t *ent ) -{ - trap->SetBrushModel( (sharedEntity_t *)ent, ent->model ); +void SP_func_wall(gentity_t *ent) { + trap->SetBrushModel((sharedEntity_t *)ent, ent->model); - VectorCopy( ent->s.origin, ent->pos1 ); - VectorCopy( ent->s.origin, ent->pos2 ); + VectorCopy(ent->s.origin, ent->pos1); + VectorCopy(ent->s.origin, ent->pos2); - InitMover( ent ); - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); + InitMover(ent); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); // it must be START_OFF - if (ent->spawnflags & FUNC_WALL_OFF) - { + if (ent->spawnflags & FUNC_WALL_OFF) { ent->r.contents = 0; ent->r.svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; @@ -3294,6 +2958,5 @@ void SP_func_wall( gentity_t *ent ) ent->use = use_wall; - trap->LinkEntity ((sharedEntity_t *)ent); - + trap->LinkEntity((sharedEntity_t *)ent); } diff --git a/codemp/game/g_nav.c b/codemp/game/g_nav.c index 7302127f8a..ba54a08c8d 100644 --- a/codemp/game/g_nav.c +++ b/codemp/game/g_nav.c @@ -23,105 +23,76 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -extern qboolean G_EntIsUnlockedDoor( int entityNum ); -extern qboolean G_EntIsDoor( int entityNum ); -extern qboolean G_EntIsBreakable( int entityNum ); -extern qboolean G_EntIsRemovableUsable( int entNum ); -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -//For debug graphics -//rwwFIXMEFIXME: Write these at some point for the sake of being able to debug visually -void G_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ) -{ +extern qboolean G_EntIsUnlockedDoor(int entityNum); +extern qboolean G_EntIsDoor(int entityNum); +extern qboolean G_EntIsBreakable(int entityNum); +extern qboolean G_EntIsRemovableUsable(int entNum); +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +// For debug graphics +// rwwFIXMEFIXME: Write these at some point for the sake of being able to debug visually +void G_Line(vec3_t start, vec3_t end, vec3_t color, float alpha) {} -} - -void G_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ) -{ - -} - -void G_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ) -{ - -} - -void G_DrawEdge( vec3_t start, vec3_t end, int type ) -{ - -} +void G_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha) {} -void G_DrawNode( vec3_t origin, int type ) -{ +void G_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha) {} -} +void G_DrawEdge(vec3_t start, vec3_t end, int type) {} -void G_DrawCombatPoint( vec3_t origin, int type ) -{ +void G_DrawNode(vec3_t origin, int type) {} -} +void G_DrawCombatPoint(vec3_t origin, int type) {} -void TAG_ShowTags( int flags ) -{ - -} +void TAG_ShowTags(int flags) {} -qboolean FlyingCreature( gentity_t *ent ) -{ - if (ent->client && ent->client->ps.gravity <= 0) - { +qboolean FlyingCreature(gentity_t *ent) { + if (ent->client && ent->client->ps.gravity <= 0) { return qtrue; } return qfalse; } -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t *trace, int clipmask ); -void NAV_StoreWaypoint( gentity_t *ent ); +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t *trace, int clipmask); +void NAV_StoreWaypoint(gentity_t *ent); extern vec3_t NPCDEBUG_RED; - /* ------------------------- NPC_Blocked ------------------------- */ - -void NPC_Blocked( gentity_t *self, gentity_t *blocker ) -{ - if ( self->NPC == NULL ) +void NPC_Blocked(gentity_t *self, gentity_t *blocker) { + if (self->NPC == NULL) return; - //Don't do this too often - if ( self->NPC->blockedSpeechDebounceTime > level.time ) + // Don't do this too often + if (self->NPC->blockedSpeechDebounceTime > level.time) return; - //Attempt to run any blocked scripts - if ( G_ActivateBehavior( self, BSET_BLOCKED ) ) - { + // Attempt to run any blocked scripts + if (G_ActivateBehavior(self, BSET_BLOCKED)) { return; } - //If this is one of our enemies, then just attack him - if ( blocker->client && ( blocker->client->playerTeam == self->client->enemyTeam ) ) - { - G_SetEnemy( self, blocker ); + // If this is one of our enemies, then just attack him + if (blocker->client && (blocker->client->playerTeam == self->client->enemyTeam)) { + G_SetEnemy(self, blocker); return; } - //Debutrap->Print( d_npcai, DEBUG_LEVEL_WARNING, "%s: Excuse me, %s %s!\n", self->targetname, blocker->classname, blocker->targetname ); + // Debutrap->Print( d_npcai, DEBUG_LEVEL_WARNING, "%s: Excuse me, %s %s!\n", self->targetname, blocker->classname, blocker->targetname ); - //If we're being blocked by the player, say something to them - if ( ( blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS ) && ( ( blocker->client->playerTeam == self->client->playerTeam ) ) ) - { - //guys in formation are not trying to get to a critical point, - //don't make them yell at the player (unless they have an enemy and - //are in combat because BP thinks it sounds cool during battle) - //NOTE: only imperials, misc crewmen and hazard team have these wav files now - //G_AddVoiceEvent( self, Q_irand(EV_BLOCKED1, EV_BLOCKED3), 0 ); + // If we're being blocked by the player, say something to them + if ((blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS) && ((blocker->client->playerTeam == self->client->playerTeam))) { + // guys in formation are not trying to get to a critical point, + // don't make them yell at the player (unless they have an enemy and + // are in combat because BP thinks it sounds cool during battle) + // NOTE: only imperials, misc crewmen and hazard team have these wav files now + // G_AddVoiceEvent( self, Q_irand(EV_BLOCKED1, EV_BLOCKED3), 0 ); } - self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + ( Q_flrand(0.0f, 1.0f) * 4000 ); + self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + (Q_flrand(0.0f, 1.0f) * 4000); self->NPC->blockingEntNum = blocker->s.number; } @@ -131,42 +102,35 @@ NPC_SetMoveGoal ------------------------- */ -void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt ) -{ - //Must be an NPC - if ( ent->NPC == NULL ) - { +void NPC_SetMoveGoal(gentity_t *ent, vec3_t point, int radius, qboolean isNavGoal, int combatPoint, gentity_t *targetEnt) { + // Must be an NPC + if (ent->NPC == NULL) { return; } - if ( ent->NPC->tempGoal == NULL ) - {//must still have a goal + if (ent->NPC->tempGoal == NULL) { // must still have a goal return; } - //Copy the origin - //VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! - VectorCopy( point, ent->NPC->tempGoal->r.currentOrigin ); + // Copy the origin + // VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! + VectorCopy(point, ent->NPC->tempGoal->r.currentOrigin); - //Copy the mins and maxs to the tempGoal - VectorCopy( ent->r.mins, ent->NPC->tempGoal->r.mins ); - VectorCopy( ent->r.mins, ent->NPC->tempGoal->r.maxs ); + // Copy the mins and maxs to the tempGoal + VectorCopy(ent->r.mins, ent->NPC->tempGoal->r.mins); + VectorCopy(ent->r.mins, ent->NPC->tempGoal->r.maxs); ent->NPC->tempGoal->target = NULL; ent->NPC->tempGoal->clipmask = ent->clipmask; ent->NPC->tempGoal->flags &= ~FL_NAVGOAL; - if ( targetEnt && targetEnt->waypoint >= 0 ) - { + if (targetEnt && targetEnt->waypoint >= 0) { ent->NPC->tempGoal->waypoint = targetEnt->waypoint; - } - else - { + } else { ent->NPC->tempGoal->waypoint = WAYPOINT_NONE; } ent->NPC->tempGoal->noWaypointTime = 0; - if ( isNavGoal ) - { + if (isNavGoal) { assert(ent->NPC->tempGoal->parent); ent->NPC->tempGoal->flags |= FL_NAVGOAL; } @@ -177,7 +141,7 @@ void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, qboolean isNavGo ent->NPC->goalEntity = ent->NPC->tempGoal; ent->NPC->goalRadius = radius; - trap->LinkEntity( (sharedEntity_t *)ent->NPC->goalEntity ); + trap->LinkEntity((sharedEntity_t *)ent->NPC->goalEntity); } /* @@ -186,52 +150,44 @@ NAV_HitNavGoal ------------------------- */ -qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying ) -{ - vec3_t dmins, dmaxs, pmins, pmaxs; +qboolean NAV_HitNavGoal(vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius, qboolean flying) { + vec3_t dmins, dmaxs, pmins, pmaxs; - if ( radius & NAVGOAL_USE_RADIUS ) - { + if (radius & NAVGOAL_USE_RADIUS) { radius &= ~NAVGOAL_USE_RADIUS; - //NOTE: This needs to do a DistanceSquared on navgoals that had + // NOTE: This needs to do a DistanceSquared on navgoals that had // a radius manually set! We can't do the smaller navgoals against // walls to get around this because player-sized traces to them // from angles will not work... - MCG - if ( !flying ) - {//Allow for a little z difference - vec3_t diff; - VectorSubtract( point, dest, diff ); - if ( fabs(diff[2]) <= 24 ) - { + if (!flying) { // Allow for a little z difference + vec3_t diff; + VectorSubtract(point, dest, diff); + if (fabs(diff[2]) <= 24) { diff[2] = 0; } - return ( VectorLengthSquared( diff ) <= (radius*radius) ); + return (VectorLengthSquared(diff) <= (radius * radius)); + } else { // must hit exactly + return (DistanceSquared(dest, point) <= (radius * radius)); } - else - {//must hit exactly - return ( DistanceSquared(dest, point) <= (radius*radius) ); - } - //There is probably a better way to do this, either by preserving the original + // There is probably a better way to do this, either by preserving the original // mins and maxs of the navgoal and doing this check ONLY if the radius // is non-zero (like the original implementation) or some boolean to // tell us to do this check rather than the fake bbox overlap check... - } - else - { - //Construct a dummy bounding box from our radius value - VectorSet( dmins, -radius, -radius, -radius ); - VectorSet( dmaxs, radius, radius, radius ); + } else { + // Construct a dummy bounding box from our radius value + VectorSet(dmins, -radius, -radius, -radius); + VectorSet(dmaxs, radius, radius, radius); - //Translate it - VectorAdd( dmins, dest, dmins ); - VectorAdd( dmaxs, dest, dmaxs ); + // Translate it + VectorAdd(dmins, dest, dmins); + VectorAdd(dmaxs, dest, dmaxs); - //Translate the starting box - VectorAdd( point, mins, pmins ); - VectorAdd( point, maxs, pmaxs ); + // Translate the starting box + VectorAdd(point, mins, pmins); + VectorAdd(point, maxs, pmaxs); - //See if they overlap - return G_BoundsOverlap( pmins, pmaxs, dmins, dmaxs ); + // See if they overlap + return G_BoundsOverlap(pmins, pmaxs, dmins, dmaxs); } } @@ -241,124 +197,103 @@ NAV_ClearPathToPoint ------------------------- */ -qboolean NAV_ClearPathToPoint( gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum ) -{ -// trace_t trace; -// return NAV_CheckAhead( self, point, trace, clipmask|CONTENTS_BOTCLIP ); +qboolean NAV_ClearPathToPoint(gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEntNum) { + // trace_t trace; + // return NAV_CheckAhead( self, point, trace, clipmask|CONTENTS_BOTCLIP ); - vec3_t mins, maxs; - trace_t trace; + vec3_t mins, maxs; + trace_t trace; - //Test if they're even conceivably close to one another - if ( !trap->InPVS( self->r.currentOrigin, point ) ) + // Test if they're even conceivably close to one another + if (!trap->InPVS(self->r.currentOrigin, point)) return qfalse; - if ( self->flags & FL_NAVGOAL ) - { - if ( !self->parent ) - { - //SHOULD NEVER HAPPEN!!! + if (self->flags & FL_NAVGOAL) { + if (!self->parent) { + // SHOULD NEVER HAPPEN!!! assert(self->parent); return qfalse; } - VectorCopy( self->parent->r.mins, mins ); - VectorCopy( self->parent->r.maxs, maxs ); - } - else - { - VectorCopy( pmins, mins ); - VectorCopy( pmaxs, maxs ); + VectorCopy(self->parent->r.mins, mins); + VectorCopy(self->parent->r.maxs, maxs); + } else { + VectorCopy(pmins, mins); + VectorCopy(pmaxs, maxs); } - if ( self->client || ( self->flags & FL_NAVGOAL ) ) - { - //Clients can step up things, or if this is a navgoal check, a client will be using this info + if (self->client || (self->flags & FL_NAVGOAL)) { + // Clients can step up things, or if this is a navgoal check, a client will be using this info mins[2] += STEPSIZE; - //don't let box get inverted - if ( mins[2] > maxs[2] ) - { + // don't let box get inverted + if (mins[2] > maxs[2]) { mins[2] = maxs[2]; } } - if ( self->flags & FL_NAVGOAL ) - { - //Trace from point to navgoal - trap->Trace( &trace, point, mins, maxs, self->r.currentOrigin, self->parent->s.number, (clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP)&~CONTENTS_BODY, qfalse, 0, 0 ); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (self->flags & FL_NAVGOAL) { + // Trace from point to navgoal + trap->Trace(&trace, point, mins, maxs, self->r.currentOrigin, self->parent->s.number, + (clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP) & ~CONTENTS_BODY, qfalse, 0, 0); + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - trap->Trace( &trace, point, mins, maxs, self->r.currentOrigin, self->parent->s.number, (clipmask|CONTENTS_MONSTERCLIP)&~CONTENTS_BODY, qfalse, 0, 0 ); + trap->Trace(&trace, point, mins, maxs, self->r.currentOrigin, self->parent->s.number, (clipmask | CONTENTS_MONSTERCLIP) & ~CONTENTS_BODY, qfalse, 0, + 0); } - if ( trace.startsolid || trace.allsolid ) - { + if (trace.startsolid || trace.allsolid) { return qfalse; } - //Made it - if ( trace.fraction == 1.0 ) - { + // Made it + if (trace.fraction == 1.0) { return qtrue; } - if ( okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum ) - { + if (okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum) { return qtrue; } - //Okay, didn't get all the way there, let's see if we got close enough: - if ( NAV_HitNavGoal( self->r.currentOrigin, self->parent->r.mins, self->parent->r.maxs, trace.endpos, NPCS.NPCInfo->goalRadius, FlyingCreature( self->parent ) ) ) - { + // Okay, didn't get all the way there, let's see if we got close enough: + if (NAV_HitNavGoal(self->r.currentOrigin, self->parent->r.mins, self->parent->r.maxs, trace.endpos, NPCS.NPCInfo->goalRadius, + FlyingCreature(self->parent))) { return qtrue; - } - else - { - if ( NAVDEBUG_showCollision ) - { - if ( trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && g_entities[trace.entityNum].s.eType != ET_MOVER ) - { - vec3_t p1, p2; - G_DrawEdge( point, trace.endpos, EDGE_PATH ); + } else { + if (NAVDEBUG_showCollision) { + if (trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && g_entities[trace.entityNum].s.eType != ET_MOVER) { + vec3_t p1, p2; + G_DrawEdge(point, trace.endpos, EDGE_PATH); VectorAdd(g_entities[trace.entityNum].r.mins, g_entities[trace.entityNum].r.currentOrigin, p1); VectorAdd(g_entities[trace.entityNum].r.maxs, g_entities[trace.entityNum].r.currentOrigin, p2); - G_CubeOutline( p1, p2, FRAMETIME, 0x0000ff, 0.5 ); + G_CubeOutline(p1, p2, FRAMETIME, 0x0000ff, 0.5); } - //FIXME: if it is a bmodel, light up the surf? + // FIXME: if it is a bmodel, light up the surf? } } - } - else - { - trap->Trace( &trace, self->r.currentOrigin, mins, maxs, point, self->s.number, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + } else { + trap->Trace(&trace, self->r.currentOrigin, mins, maxs, point, self->s.number, clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - trap->Trace( &trace, self->r.currentOrigin, mins, maxs, point, self->s.number, clipmask|CONTENTS_MONSTERCLIP, qfalse, 0, 0); + trap->Trace(&trace, self->r.currentOrigin, mins, maxs, point, self->s.number, clipmask | CONTENTS_MONSTERCLIP, qfalse, 0, 0); } - if( ( ( trace.startsolid == qfalse ) && ( trace.allsolid == qfalse ) ) && ( trace.fraction == 1.0f ) ) - {//FIXME: check for drops + if (((trace.startsolid == qfalse) && (trace.allsolid == qfalse)) && (trace.fraction == 1.0f)) { // FIXME: check for drops return qtrue; } - if ( okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum ) - { + if (okToHitEntNum != ENTITYNUM_NONE && trace.entityNum == okToHitEntNum) { return qtrue; } - if ( NAVDEBUG_showCollision ) - { - if ( trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && g_entities[trace.entityNum].s.eType != ET_MOVER ) - { - vec3_t p1, p2; - G_DrawEdge( self->r.currentOrigin, trace.endpos, EDGE_PATH ); + if (NAVDEBUG_showCollision) { + if (trace.entityNum < ENTITYNUM_WORLD && (&g_entities[trace.entityNum] != NULL) && g_entities[trace.entityNum].s.eType != ET_MOVER) { + vec3_t p1, p2; + G_DrawEdge(self->r.currentOrigin, trace.endpos, EDGE_PATH); VectorAdd(g_entities[trace.entityNum].r.mins, g_entities[trace.entityNum].r.currentOrigin, p1); VectorAdd(g_entities[trace.entityNum].r.maxs, g_entities[trace.entityNum].r.currentOrigin, p2); - G_CubeOutline( p1, p2, FRAMETIME, 0x0000ff, 0.5 ); + G_CubeOutline(p1, p2, FRAMETIME, 0x0000ff, 0.5); } - //FIXME: if it is a bmodel, light up the surf? + // FIXME: if it is a bmodel, light up the surf? } } @@ -371,60 +306,55 @@ NAV_FindClosestWaypointForEnt ------------------------- */ -int NAV_FindClosestWaypointForEnt( gentity_t *ent, int targWp ) -{ - //FIXME: Take the target into account - return trap->Nav_GetNearestNode( (sharedEntity_t *)ent, ent->waypoint, NF_CLEAR_PATH, targWp ); +int NAV_FindClosestWaypointForEnt(gentity_t *ent, int targWp) { + // FIXME: Take the target into account + return trap->Nav_GetNearestNode((sharedEntity_t *)ent, ent->waypoint, NF_CLEAR_PATH, targWp); } -int NAV_FindClosestWaypointForPoint( gentity_t *ent, vec3_t point ) -{ - int bestWP; - //FIXME: can we make this a static ent? +int NAV_FindClosestWaypointForPoint(gentity_t *ent, vec3_t point) { + int bestWP; + // FIXME: can we make this a static ent? gentity_t *marker = G_Spawn(); - if ( !marker ) - { + if (!marker) { return WAYPOINT_NONE; } - G_SetOrigin( marker, point ); + G_SetOrigin(marker, point); - VectorCopy( ent->r.mins, marker->r.mins );//stepsize? - VectorCopy( ent->r.mins, marker->r.maxs );//crouching? + VectorCopy(ent->r.mins, marker->r.mins); // stepsize? + VectorCopy(ent->r.mins, marker->r.maxs); // crouching? marker->clipmask = ent->clipmask; marker->waypoint = WAYPOINT_NONE; - bestWP = trap->Nav_GetNearestNode( (sharedEntity_t *)marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + bestWP = trap->Nav_GetNearestNode((sharedEntity_t *)marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); - G_FreeEntity( marker ); + G_FreeEntity(marker); return bestWP; } -int NAV_FindClosestWaypointForPoint2( vec3_t point ) -{ - int bestWP; - //FIXME: can we make this a static ent? +int NAV_FindClosestWaypointForPoint2(vec3_t point) { + int bestWP; + // FIXME: can we make this a static ent? gentity_t *marker = G_Spawn(); - if ( !marker ) - { + if (!marker) { return WAYPOINT_NONE; } - G_SetOrigin( marker, point ); + G_SetOrigin(marker, point); - VectorSet( marker->r.mins, -16, -16, -6 );//includes stepsize - VectorSet( marker->r.maxs, 16, 16, 32 ); + VectorSet(marker->r.mins, -16, -16, -6); // includes stepsize + VectorSet(marker->r.maxs, 16, 16, 32); marker->clipmask = MASK_NPCSOLID; marker->waypoint = WAYPOINT_NONE; - bestWP = trap->Nav_GetNearestNode( (sharedEntity_t *)marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + bestWP = trap->Nav_GetNearestNode((sharedEntity_t *)marker, marker->waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); - G_FreeEntity( marker ); + G_FreeEntity(marker); return bestWP; } @@ -435,8 +365,7 @@ NAV_ClearBlockedInfo ------------------------- */ -void NAV_ClearBlockedInfo( gentity_t *self ) -{ +void NAV_ClearBlockedInfo(gentity_t *self) { self->NPC->aiFlags &= ~NPCAI_BLOCKED; self->NPC->blockingEntNum = ENTITYNUM_WORLD; } @@ -447,8 +376,7 @@ NAV_SetBlockedInfo ------------------------- */ -void NAV_SetBlockedInfo( gentity_t *self, int entId ) -{ +void NAV_SetBlockedInfo(gentity_t *self, int entId) { self->NPC->aiFlags |= NPCAI_BLOCKED; self->NPC->blockingEntNum = entId; } @@ -459,50 +387,48 @@ NAV_Steer ------------------------- */ -int NAV_Steer( gentity_t *self, vec3_t dir, float distance ) -{ - vec3_t right_test, left_test; - vec3_t deviation; - trace_t tr; - float right_push; - float left_push; - float right_ang = dir[YAW] + 45; - float left_ang = dir[YAW] - 45; - - //Get the steering angles - VectorCopy( dir, deviation ); +int NAV_Steer(gentity_t *self, vec3_t dir, float distance) { + vec3_t right_test, left_test; + vec3_t deviation; + trace_t tr; + float right_push; + float left_push; + float right_ang = dir[YAW] + 45; + float left_ang = dir[YAW] - 45; + + // Get the steering angles + VectorCopy(dir, deviation); deviation[YAW] = right_ang; - AngleVectors( deviation, right_test, NULL, NULL ); + AngleVectors(deviation, right_test, NULL, NULL); deviation[YAW] = left_ang; - AngleVectors( deviation, left_test, NULL, NULL ); + AngleVectors(deviation, left_test, NULL, NULL); - //Find the end positions - VectorMA( self->r.currentOrigin, distance, right_test, right_test ); - VectorMA( self->r.currentOrigin, distance, left_test, left_test ); + // Find the end positions + VectorMA(self->r.currentOrigin, distance, right_test, right_test); + VectorMA(self->r.currentOrigin, distance, left_test, left_test); - //Draw for debug purposes - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, right_test, EDGE_PATH ); - G_DrawEdge( self->r.currentOrigin, left_test, EDGE_PATH ); + // Draw for debug purposes + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, right_test, EDGE_PATH); + G_DrawEdge(self->r.currentOrigin, left_test, EDGE_PATH); } - //Find the right influence - NAV_CheckAhead( self, right_test, &tr, self->clipmask|CONTENTS_BOTCLIP ); + // Find the right influence + NAV_CheckAhead(self, right_test, &tr, self->clipmask | CONTENTS_BOTCLIP); - right_push = -45 * ( 1.0f - tr.fraction ); + right_push = -45 * (1.0f - tr.fraction); - //Find the left influence - NAV_CheckAhead( self, left_test, &tr, self->clipmask|CONTENTS_BOTCLIP ); + // Find the left influence + NAV_CheckAhead(self, left_test, &tr, self->clipmask | CONTENTS_BOTCLIP); - left_push = 45 * ( 1.0f - tr.fraction ); + left_push = 45 * (1.0f - tr.fraction); - //Influence the mover to respond to the steering - VectorCopy( dir, deviation ); - deviation[YAW] += ( left_push + right_push ); + // Influence the mover to respond to the steering + VectorCopy(dir, deviation); + deviation[YAW] += (left_push + right_push); return deviation[YAW]; } @@ -513,51 +439,47 @@ NAV_CheckAhead ------------------------- */ -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t *trace, int clipmask ) -{ - vec3_t mins; - float radius; - float dist; - float tFrac; +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t *trace, int clipmask) { + vec3_t mins; + float radius; + float dist; + float tFrac; - //Offset the step height - VectorSet( mins, self->r.mins[0], self->r.mins[1], self->r.mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->r.mins[0], self->r.mins[1], self->r.mins[2] + STEPSIZE); - trap->Trace( trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0 ); + trap->Trace(trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0); - if ( trace->startsolid&&(trace->contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace->startsolid && (trace->contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - trap->Trace( trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0 ); + trap->Trace(trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0); } - //Do a simple check - if ( ( trace->allsolid == qfalse ) && ( trace->startsolid == qfalse ) && ( trace->fraction == 1.0f ) ) + // Do a simple check + if ((trace->allsolid == qfalse) && (trace->startsolid == qfalse) && (trace->fraction == 1.0f)) return qtrue; - //See if we're too far above - if ( fabs( self->r.currentOrigin[2] - end[2] ) > 48 ) + // See if we're too far above + if (fabs(self->r.currentOrigin[2] - end[2]) > 48) return qfalse; - //This is a work around - radius = ( self->r.maxs[0] > self->r.maxs[1] ) ? self->r.maxs[0] : self->r.maxs[1]; - dist = Distance( self->r.currentOrigin, end ); - tFrac = 1.0f - ( radius / dist ); + // This is a work around + radius = (self->r.maxs[0] > self->r.maxs[1]) ? self->r.maxs[0] : self->r.maxs[1]; + dist = Distance(self->r.currentOrigin, end); + tFrac = 1.0f - (radius / dist); - if ( trace->fraction >= tFrac ) + if (trace->fraction >= tFrac) return qtrue; - //Do a special check for doors - if ( trace->entityNum < ENTITYNUM_WORLD ) - { - gentity_t *blocker = &g_entities[trace->entityNum]; + // Do a special check for doors + if (trace->entityNum < ENTITYNUM_WORLD) { + gentity_t *blocker = &g_entities[trace->entityNum]; - if ( VALIDSTRING( blocker->classname ) ) - { - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + if (VALIDSTRING(blocker->classname)) { + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { - //We're too close, try and avoid the door (most likely stuck on a lip) - if ( DistanceSquared( self->r.currentOrigin, trace->endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) + // We're too close, try and avoid the door (most likely stuck on a lip) + if (DistanceSquared(self->r.currentOrigin, trace->endpos) < MIN_DOOR_BLOCK_DIST_SQR) return qfalse; return qtrue; @@ -574,27 +496,24 @@ NAV_TestBypass ------------------------- */ -static qboolean NAV_TestBypass( gentity_t *self, float yaw, float blocked_dist, vec3_t movedir ) -{ - trace_t tr; - vec3_t avoidAngles; - vec3_t block_test, block_pos; +static qboolean NAV_TestBypass(gentity_t *self, float yaw, float blocked_dist, vec3_t movedir) { + trace_t tr; + vec3_t avoidAngles; + vec3_t block_test, block_pos; - VectorClear( avoidAngles ); + VectorClear(avoidAngles); avoidAngles[YAW] = yaw; - AngleVectors( avoidAngles, block_test, NULL, NULL ); - VectorMA( self->r.currentOrigin, blocked_dist, block_test, block_pos ); + AngleVectors(avoidAngles, block_test, NULL, NULL); + VectorMA(self->r.currentOrigin, blocked_dist, block_test, block_pos); - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, block_pos, EDGE_BLOCKED ); + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, block_pos, EDGE_BLOCKED); } - //See if we're clear to move in that direction - if ( NAV_CheckAhead( self, block_pos, &tr, ( self->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - VectorCopy( block_test, movedir ); + // See if we're clear to move in that direction + if (NAV_CheckAhead(self, block_pos, &tr, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + VectorCopy(block_test, movedir); return qtrue; } @@ -608,77 +527,72 @@ NAV_Bypass ------------------------- */ -qboolean NAV_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir ) -{ +qboolean NAV_Bypass(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir) { float dot, yaw, avoidRadius, arcAngle; - vec3_t right; + vec3_t right; - //Draw debug info if requested - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, blocker->r.currentOrigin, EDGE_NORMAL ); + // Draw debug info if requested + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, blocker->r.currentOrigin, EDGE_NORMAL); } - AngleVectors( self->r.currentAngles, NULL, right, NULL ); + AngleVectors(self->r.currentAngles, NULL, right, NULL); - //Get the blocked direction - yaw = vectoyaw( blocked_dir ); + // Get the blocked direction + yaw = vectoyaw(blocked_dir); - //Get the avoid radius - avoidRadius = sqrt( ( blocker->r.maxs[0] * blocker->r.maxs[0] ) + ( blocker->r.maxs[1] * blocker->r.maxs[1] ) ) + - sqrt( ( self->r.maxs[0] * self->r.maxs[0] ) + ( self->r.maxs[1] * self->r.maxs[1] ) ); + // Get the avoid radius + avoidRadius = sqrt((blocker->r.maxs[0] * blocker->r.maxs[0]) + (blocker->r.maxs[1] * blocker->r.maxs[1])) + + sqrt((self->r.maxs[0] * self->r.maxs[0]) + (self->r.maxs[1] * self->r.maxs[1])); - //See if we're inside our avoidance radius - arcAngle = ( blocked_dist <= avoidRadius ) ? 135 : ( ( avoidRadius / blocked_dist ) * 90 ); + // See if we're inside our avoidance radius + arcAngle = (blocked_dist <= avoidRadius) ? 135 : ((avoidRadius / blocked_dist) * 90); - //FIXME: Although the below code will cause the NPC to take the "better" route, it can cause NPCs to become stuck on + // FIXME: Although the below code will cause the NPC to take the "better" route, it can cause NPCs to become stuck on // one another in certain situations where both decide to take the same direction. - //Check to see what dir the other guy is moving in (if any) and pick the opposite dir - if ( blocker->client && !VectorCompare( blocker->client->ps.velocity, vec3_origin ) ) - { + // Check to see what dir the other guy is moving in (if any) and pick the opposite dir + if (blocker->client && !VectorCompare(blocker->client->ps.velocity, vec3_origin)) { vec3_t blocker_movedir; - VectorNormalize2( blocker->client->ps.velocity, blocker_movedir ); - dot = DotProduct( blocker_movedir, blocked_dir ); - if ( dot < 0.35f && dot > -0.35f ) - {//he's moving to the side of me - vec3_t block_pos; - trace_t tr; - VectorScale( blocker_movedir, -1, blocker_movedir ); - VectorMA( self->r.currentOrigin, blocked_dist, blocker_movedir, block_pos ); - if ( NAV_CheckAhead( self, block_pos, &tr, ( self->clipmask & ~CONTENTS_BODY )|CONTENTS_BOTCLIP ) ) - { - VectorCopy( blocker_movedir, movedir ); + VectorNormalize2(blocker->client->ps.velocity, blocker_movedir); + dot = DotProduct(blocker_movedir, blocked_dir); + if (dot < 0.35f && dot > -0.35f) { // he's moving to the side of me + vec3_t block_pos; + trace_t tr; + VectorScale(blocker_movedir, -1, blocker_movedir); + VectorMA(self->r.currentOrigin, blocked_dist, blocker_movedir, block_pos); + if (NAV_CheckAhead(self, block_pos, &tr, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP)) { + VectorCopy(blocker_movedir, movedir); return qtrue; } } } - //FIXME: this makes NPCs stack up and ping-pong like crazy. + // FIXME: this makes NPCs stack up and ping-pong like crazy. // Need to keep track of this and stop trying after a while - dot = DotProduct( blocked_dir, right ); + dot = DotProduct(blocked_dir, right); - //Go right on the first try if that works better - if ( dot < 0.0f ) + // Go right on the first try if that works better + if (dot < 0.0f) arcAngle *= -1; - //Test full, best position first - if ( NAV_TestBypass( self, AngleNormalize360( yaw + arcAngle ), blocked_dist, movedir ) ) + // Test full, best position first + if (NAV_TestBypass(self, AngleNormalize360(yaw + arcAngle), blocked_dist, movedir)) return qtrue; - //Try a smaller arc - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( arcAngle * 0.5f ) ), blocked_dist, movedir ) ) + // Try a smaller arc + if (NAV_TestBypass(self, AngleNormalize360(yaw + (arcAngle * 0.5f)), blocked_dist, movedir)) return qtrue; - //Try the other direction - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( arcAngle * -1 ) ), blocked_dist, movedir ) ) + // Try the other direction + if (NAV_TestBypass(self, AngleNormalize360(yaw + (arcAngle * -1)), blocked_dist, movedir)) return qtrue; - //Try the other direction more precisely - if ( NAV_TestBypass( self, AngleNormalize360( yaw + ( ( arcAngle * -1 ) * 0.5f ) ), blocked_dist, movedir ) ) + // Try the other direction more precisely + if (NAV_TestBypass(self, AngleNormalize360(yaw + ((arcAngle * -1) * 0.5f)), blocked_dist, movedir)) return qtrue; - //Unable to go around + // Unable to go around return qfalse; } @@ -688,23 +602,22 @@ NAV_MoveBlocker ------------------------- */ -qboolean NAV_MoveBlocker( gentity_t *self, vec3_t shove_dir ) -{ - //FIXME: This is a temporary method for making blockers move +qboolean NAV_MoveBlocker(gentity_t *self, vec3_t shove_dir) { + // FIXME: This is a temporary method for making blockers move - //FIXME: This will, of course, push blockers off of cliffs, into walls and all over the place + // FIXME: This will, of course, push blockers off of cliffs, into walls and all over the place - vec3_t temp_dir, forward; + vec3_t temp_dir, forward; - vectoangles( shove_dir, temp_dir ); + vectoangles(shove_dir, temp_dir); temp_dir[YAW] += 45; - AngleVectors( temp_dir, forward, NULL, NULL ); + AngleVectors(temp_dir, forward, NULL, NULL); - VectorScale( forward, SHOVE_SPEED, self->client->ps.velocity ); + VectorScale(forward, SHOVE_SPEED, self->client->ps.velocity); self->client->ps.velocity[2] += SHOVE_LIFT; - //self->NPC->shoveDebounce = level.time + 100; + // self->NPC->shoveDebounce = level.time + 100; return qtrue; } @@ -715,15 +628,14 @@ NAV_ResolveBlock ------------------------- */ -qboolean NAV_ResolveBlock( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir ) -{ - //Stop double waiting - if ( ( blocker->NPC ) && ( blocker->NPC->blockingEntNum == self->s.number ) ) +qboolean NAV_ResolveBlock(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir) { + // Stop double waiting + if ((blocker->NPC) && (blocker->NPC->blockingEntNum == self->s.number)) return qtrue; - //For now, just complain about it - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker, qtrue ); + // For now, just complain about it + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker, qtrue); return qfalse; } @@ -734,37 +646,35 @@ NAV_TrueCollision ------------------------- */ -qboolean NAV_TrueCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t blocked_dir ) -{ - vec3_t velocityDir; +qboolean NAV_TrueCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t blocked_dir) { + vec3_t velocityDir; float speed, dot; - vec3_t testPos; - vec3_t ptmins, ptmaxs, tmins, tmaxs; + vec3_t testPos; + vec3_t ptmins, ptmaxs, tmins, tmaxs; - //TODO: Handle all ents - if ( blocker->client == NULL ) + // TODO: Handle all ents + if (blocker->client == NULL) return qfalse; - //Get the player's move direction and speed - speed = VectorNormalize2( self->client->ps.velocity, velocityDir ); + // Get the player's move direction and speed + speed = VectorNormalize2(self->client->ps.velocity, velocityDir); - //See if it's even feasible - dot = DotProduct( movedir, velocityDir ); + // See if it's even feasible + dot = DotProduct(movedir, velocityDir); - if ( dot < 0.85 ) + if (dot < 0.85) return qfalse; - VectorMA( self->r.currentOrigin, speed*FRAMETIME, velocityDir, testPos ); + VectorMA(self->r.currentOrigin, speed * FRAMETIME, velocityDir, testPos); - VectorAdd( blocker->r.currentOrigin, blocker->r.mins, tmins ); - VectorAdd( blocker->r.currentOrigin, blocker->r.maxs, tmaxs ); + VectorAdd(blocker->r.currentOrigin, blocker->r.mins, tmins); + VectorAdd(blocker->r.currentOrigin, blocker->r.maxs, tmaxs); - VectorAdd( testPos, self->r.mins, ptmins ); - VectorAdd( testPos, self->r.maxs, ptmaxs ); + VectorAdd(testPos, self->r.mins, ptmins); + VectorAdd(testPos, self->r.maxs, ptmaxs); - if ( G_BoundsOverlap( ptmins, ptmaxs, tmins, tmaxs ) ) - { - VectorCopy( velocityDir, blocked_dir ); + if (G_BoundsOverlap(ptmins, ptmaxs, tmins, tmaxs)) { + VectorCopy(velocityDir, blocked_dir); return qtrue; } @@ -777,61 +687,56 @@ NAV_StackedCanyon ------------------------- */ -qboolean NAV_StackedCanyon( gentity_t *self, gentity_t *blocker, vec3_t pathDir ) -{ - vec3_t perp, cross, test; - float avoidRadius; - int extraClip = CONTENTS_BOTCLIP; - trace_t tr; +qboolean NAV_StackedCanyon(gentity_t *self, gentity_t *blocker, vec3_t pathDir) { + vec3_t perp, cross, test; + float avoidRadius; + int extraClip = CONTENTS_BOTCLIP; + trace_t tr; - PerpendicularVector( perp, pathDir ); - CrossProduct( pathDir, perp, cross ); + PerpendicularVector(perp, pathDir); + CrossProduct(pathDir, perp, cross); - avoidRadius = sqrt( ( blocker->r.maxs[0] * blocker->r.maxs[0] ) + ( blocker->r.maxs[1] * blocker->r.maxs[1] ) ) + - sqrt( ( self->r.maxs[0] * self->r.maxs[0] ) + ( self->r.maxs[1] * self->r.maxs[1] ) ); + avoidRadius = sqrt((blocker->r.maxs[0] * blocker->r.maxs[0]) + (blocker->r.maxs[1] * blocker->r.maxs[1])) + + sqrt((self->r.maxs[0] * self->r.maxs[0]) + (self->r.maxs[1] * self->r.maxs[1])); - VectorMA( blocker->r.currentOrigin, avoidRadius, cross, test ); + VectorMA(blocker->r.currentOrigin, avoidRadius, cross, test); - trap->Trace( &tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask|extraClip, qfalse, 0, 0 ); - if ( tr.startsolid&&(tr.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + trap->Trace(&tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask | extraClip, qfalse, 0, 0); + if (tr.startsolid && (tr.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them extraClip &= ~CONTENTS_BOTCLIP; - trap->Trace( &tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask|extraClip, qfalse, 0, 0 ); + trap->Trace(&tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask | extraClip, qfalse, 0, 0); } - if ( NAVDEBUG_showCollision ) - { - vec3_t mins, maxs; - vec3_t RED = { 1.0f, 0.0f, 0.0f }; + if (NAVDEBUG_showCollision) { + vec3_t mins, maxs; + vec3_t RED = {1.0f, 0.0f, 0.0f}; - VectorAdd( test, self->r.mins, mins ); - VectorAdd( test, self->r.maxs, maxs ); - G_Cube( mins, maxs, RED, 0.25 ); + VectorAdd(test, self->r.mins, mins); + VectorAdd(test, self->r.maxs, maxs); + G_Cube(mins, maxs, RED, 0.25); } - if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) + if (tr.startsolid == qfalse && tr.allsolid == qfalse) return qfalse; - VectorMA( blocker->r.currentOrigin, -avoidRadius, cross, test ); + VectorMA(blocker->r.currentOrigin, -avoidRadius, cross, test); - trap->Trace( &tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask|extraClip, qfalse, 0, 0 ); - if ( tr.startsolid&&(tr.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + trap->Trace(&tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask | extraClip, qfalse, 0, 0); + if (tr.startsolid && (tr.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them extraClip &= ~CONTENTS_BOTCLIP; - trap->Trace( &tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask|extraClip, qfalse, 0, 0 ); + trap->Trace(&tr, test, self->r.mins, self->r.maxs, test, self->s.number, self->clipmask | extraClip, qfalse, 0, 0); } - if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) + if (tr.startsolid == qfalse && tr.allsolid == qfalse) return qfalse; - if ( NAVDEBUG_showCollision ) - { - vec3_t mins, maxs; - vec3_t RED = { 1.0f, 0.0f, 0.0f }; + if (NAVDEBUG_showCollision) { + vec3_t mins, maxs; + vec3_t RED = {1.0f, 0.0f, 0.0f}; - VectorAdd( test, self->r.mins, mins ); - VectorAdd( test, self->r.maxs, maxs ); - G_Cube( mins, maxs, RED, 0.25 ); + VectorAdd(test, self->r.mins, mins); + VectorAdd(test, self->r.maxs, maxs); + G_Cube(mins, maxs, RED, 0.25); } return qtrue; @@ -843,44 +748,41 @@ NAV_ResolveEntityCollision ------------------------- */ -qboolean NAV_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir ) -{ - vec3_t blocked_dir; +qboolean NAV_ResolveEntityCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir) { + vec3_t blocked_dir; float blocked_dist; - //Doors are ignored - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + // Doors are ignored + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { - if ( DistanceSquared( self->r.currentOrigin, blocker->r.currentOrigin ) > MIN_DOOR_BLOCK_DIST_SQR ) + if (DistanceSquared(self->r.currentOrigin, blocker->r.currentOrigin) > MIN_DOOR_BLOCK_DIST_SQR) return qtrue; } - VectorSubtract( blocker->r.currentOrigin, self->r.currentOrigin, blocked_dir ); - blocked_dist = VectorNormalize( blocked_dir ); + VectorSubtract(blocker->r.currentOrigin, self->r.currentOrigin, blocked_dir); + blocked_dist = VectorNormalize(blocked_dir); - //Make sure an actual collision is going to happen -// if ( NAV_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) -// return qtrue; + // Make sure an actual collision is going to happen + // if ( NAV_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) + // return qtrue; - //See if we can get around the blocker at all (only for player!) - if ( blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS ) - { - if ( NAV_StackedCanyon( self, blocker, pathDir ) ) - { - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker, qtrue ); + // See if we can get around the blocker at all (only for player!) + if (blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS) { + if (NAV_StackedCanyon(self, blocker, pathDir)) { + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker, qtrue); return qfalse; } } - //First, attempt to walk around the blocker - if ( NAV_Bypass( self, blocker, blocked_dir, blocked_dist, movedir ) ) + // First, attempt to walk around the blocker + if (NAV_Bypass(self, blocker, blocked_dir, blocked_dist, movedir)) return qtrue; - //Second, attempt to calculate a good move position for the blocker - if ( NAV_ResolveBlock( self, blocker, blocked_dir ) ) + // Second, attempt to calculate a good move position for the blocker + if (NAV_ResolveBlock(self, blocker, blocked_dir)) return qtrue; return qfalse; @@ -892,22 +794,19 @@ NAV_TestForBlocked ------------------------- */ -qboolean NAV_TestForBlocked( gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int *flags ) -{ - if ( goal == NULL ) +qboolean NAV_TestForBlocked(gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int *flags) { + if (goal == NULL) return qfalse; - if ( blocker->s.eType == ET_ITEM ) + if (blocker->s.eType == ET_ITEM) return qfalse; - if ( NAV_HitNavGoal( blocker->r.currentOrigin, blocker->r.mins, blocker->r.maxs, goal->r.currentOrigin, 12, qfalse ) ) - { + if (NAV_HitNavGoal(blocker->r.currentOrigin, blocker->r.mins, blocker->r.maxs, goal->r.currentOrigin, 12, qfalse)) { *flags |= NIF_BLOCKED; - if ( distance <= MIN_STOP_DIST ) - { - NPC_Blocked( self, blocker ); - NPC_FaceEntity( blocker, qtrue ); + if (distance <= MIN_STOP_DIST) { + NPC_Blocked(self, blocker); + NPC_FaceEntity(blocker, qtrue); return qtrue; } } @@ -921,64 +820,59 @@ NAV_AvoidCollsion ------------------------- */ -qboolean NAV_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t *info ) -{ - vec3_t movedir; - vec3_t movepos; +qboolean NAV_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t *info) { + vec3_t movedir; + vec3_t movepos; - //Clear our block info for this frame - NAV_ClearBlockedInfo( NPCS.NPC ); + // Clear our block info for this frame + NAV_ClearBlockedInfo(NPCS.NPC); - //Cap our distance - if ( info->distance > MAX_COLL_AVOID_DIST ) - { + // Cap our distance + if (info->distance > MAX_COLL_AVOID_DIST) { info->distance = MAX_COLL_AVOID_DIST; } - //Get an end position - VectorMA( self->r.currentOrigin, info->distance, info->direction, movepos ); - VectorCopy( info->direction, movedir ); + // Get an end position + VectorMA(self->r.currentOrigin, info->distance, info->direction, movepos); + VectorCopy(info->direction, movedir); - if ( self && self->NPC && (self->NPC->aiFlags&NPCAI_NO_COLL_AVOID) ) - {//pretend there's no-one in the way + if (self && self->NPC && (self->NPC->aiFlags & NPCAI_NO_COLL_AVOID)) { // pretend there's no-one in the way return qtrue; } - //Now test against entities - if ( NAV_CheckAhead( self, movepos, &info->trace, CONTENTS_BODY ) == qfalse ) - { - //Get the blocker - info->blocker = &g_entities[ info->trace.entityNum ]; + // Now test against entities + if (NAV_CheckAhead(self, movepos, &info->trace, CONTENTS_BODY) == qfalse) { + // Get the blocker + info->blocker = &g_entities[info->trace.entityNum]; info->flags |= NIF_COLLISION; - //Ok to hit our goal entity - if ( goal == info->blocker ) + // Ok to hit our goal entity + if (goal == info->blocker) return qtrue; - //See if we're moving along with them - //if ( NAV_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) + // See if we're moving along with them + // if ( NAV_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) // return qtrue; - //Test for blocking by standing on goal - if ( NAV_TestForBlocked( self, goal, info->blocker, info->distance, &info->flags ) == qtrue ) + // Test for blocking by standing on goal + if (NAV_TestForBlocked(self, goal, info->blocker, info->distance, &info->flags) == qtrue) return qfalse; - //If the above function said we're blocked, don't do the extra checks - if ( info->flags & NIF_BLOCKED ) + // If the above function said we're blocked, don't do the extra checks + if (info->flags & NIF_BLOCKED) return qtrue; - //See if we can get that entity to move out of our way - if ( NAV_ResolveEntityCollision( self, info->blocker, movedir, info->pathDirection ) == qfalse ) + // See if we can get that entity to move out of our way + if (NAV_ResolveEntityCollision(self, info->blocker, movedir, info->pathDirection) == qfalse) return qfalse; - VectorCopy( movedir, info->direction ); + VectorCopy(movedir, info->direction); return qtrue; } - //Our path is clear, just move there - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, movepos, EDGE_PATH ); + // Our path is clear, just move there + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, movepos, EDGE_PATH); } return qtrue; @@ -990,109 +884,86 @@ NAV_TestBestNode ------------------------- */ -int NAV_TestBestNode( gentity_t *self, int startID, int endID, qboolean failEdge ) -{//check only against architectrure - vec3_t end; - trace_t trace; - vec3_t mins; - int clipmask = (NPCS.NPC->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP; +int NAV_TestBestNode(gentity_t *self, int startID, int endID, qboolean failEdge) { // check only against architectrure + vec3_t end; + trace_t trace; + vec3_t mins; + int clipmask = (NPCS.NPC->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP; - //get the position for the test choice - trap->Nav_GetNodePosition( endID, end ); + // get the position for the test choice + trap->Nav_GetNodePosition(endID, end); - //Offset the step height - VectorSet( mins, self->r.mins[0], self->r.mins[1], self->r.mins[2] + STEPSIZE ); + // Offset the step height + VectorSet(mins, self->r.mins[0], self->r.mins[1], self->r.mins[2] + STEPSIZE); - trap->Trace( &trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0 ); + trap->Trace(&trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0); - if ( trace.startsolid&&(trace.contents&CONTENTS_BOTCLIP) ) - {//started inside do not enter, so ignore them + if (trace.startsolid && (trace.contents & CONTENTS_BOTCLIP)) { // started inside do not enter, so ignore them clipmask &= ~CONTENTS_BOTCLIP; - trap->Trace( &trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0 ); + trap->Trace(&trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, clipmask, qfalse, 0, 0); } - //Do a simple check - if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) - {//it's clear + // Do a simple check + if ((trace.allsolid == qfalse) && (trace.startsolid == qfalse) && (trace.fraction == 1.0f)) { // it's clear return endID; } - //See if we're too far above - if ( self->s.weapon != WP_SABER && fabs( self->r.currentOrigin[2] - end[2] ) > 48 ) - { - } - else - { - //This is a work around - float radius = ( self->r.maxs[0] > self->r.maxs[1] ) ? self->r.maxs[0] : self->r.maxs[1]; - float dist = Distance( self->r.currentOrigin, end ); - float tFrac = 1.0f - ( radius / dist ); + // See if we're too far above + if (self->s.weapon != WP_SABER && fabs(self->r.currentOrigin[2] - end[2]) > 48) { + } else { + // This is a work around + float radius = (self->r.maxs[0] > self->r.maxs[1]) ? self->r.maxs[0] : self->r.maxs[1]; + float dist = Distance(self->r.currentOrigin, end); + float tFrac = 1.0f - (radius / dist); - if ( trace.fraction >= tFrac ) - {//it's clear + if (trace.fraction >= tFrac) { // it's clear return endID; } } - //Do a special check for doors - if ( trace.entityNum < ENTITYNUM_WORLD ) - { - gentity_t *blocker = &g_entities[trace.entityNum]; - - if VALIDSTRING( blocker->classname ) - {//special case: doors are architecture, but are dynamic, like entitites - if ( G_EntIsUnlockedDoor( blocker->s.number ) ) - //if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) - {//it's unlocked, go for it - //We're too close, try and avoid the door (most likely stuck on a lip) - if ( DistanceSquared( self->r.currentOrigin, trace.endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) - { + // Do a special check for doors + if (trace.entityNum < ENTITYNUM_WORLD) { + gentity_t *blocker = &g_entities[trace.entityNum]; + + if VALIDSTRING (blocker->classname) { // special case: doors are architecture, but are dynamic, like entitites + if (G_EntIsUnlockedDoor(blocker->s.number)) + // if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) + { // it's unlocked, go for it + // We're too close, try and avoid the door (most likely stuck on a lip) + if (DistanceSquared(self->r.currentOrigin, trace.endpos) < MIN_DOOR_BLOCK_DIST_SQR) { return startID; } - //we can keep heading to the door, it should open - if ( self->s.weapon != WP_SABER && fabs( self->r.currentOrigin[2] - end[2] ) > 48 ) - {//too far above - } - else - { + // we can keep heading to the door, it should open + if (self->s.weapon != WP_SABER && fabs(self->r.currentOrigin[2] - end[2]) > 48) { // too far above + } else { return endID; } - } - else if ( G_EntIsDoor( blocker->s.number ) ) - {//a locked door! - //path is blocked by a locked door, mark it as such if instructed to do so - if ( failEdge ) - { - trap->Nav_AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsDoor(blocker->s.number)) { // a locked door! + // path is blocked by a locked door, mark it as such if instructed to do so + if (failEdge) { + trap->Nav_AddFailedEdge(self->s.number, startID, endID); } - } - else if ( G_EntIsBreakable( blocker->s.number ) ) - {//do same for breakable brushes/models/glass? - //path is blocked by a breakable, mark it as such if instructed to do so - if ( failEdge ) - { - trap->Nav_AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsBreakable(blocker->s.number)) { // do same for breakable brushes/models/glass? + // path is blocked by a breakable, mark it as such if instructed to do so + if (failEdge) { + trap->Nav_AddFailedEdge(self->s.number, startID, endID); } - } - else if ( G_EntIsRemovableUsable( blocker->s.number ) ) - {//and removable usables - //path is blocked by a removable usable, mark it as such if instructed to do so - if ( failEdge ) - { - trap->Nav_AddFailedEdge( self->s.number, startID, endID ); + } else if (G_EntIsRemovableUsable(blocker->s.number)) { // and removable usables + // path is blocked by a removable usable, mark it as such if instructed to do so + if (failEdge) { + trap->Nav_AddFailedEdge(self->s.number, startID, endID); } - } - else if ( blocker->targetname && blocker->s.solid == SOLID_BMODEL && ((blocker->r.contents&CONTENTS_MONSTERCLIP)|| (blocker->r.contents&CONTENTS_BOTCLIP)) ) - {//some other kind of do not enter entity brush that will probably be removed - //path is blocked by a removable brushent, mark it as such if instructed to do so - if ( failEdge ) - { - trap->Nav_AddFailedEdge( self->s.number, startID, endID ); + } else if (blocker->targetname && blocker->s.solid == SOLID_BMODEL && + ((blocker->r.contents & CONTENTS_MONSTERCLIP) || + (blocker->r.contents & CONTENTS_BOTCLIP))) { // some other kind of do not enter entity brush that will probably be removed + // path is blocked by a removable brushent, mark it as such if instructed to do so + if (failEdge) { + trap->Nav_AddFailedEdge(self->s.number, startID, endID); } } } } - //path is blocked - //use the fallback choice + // path is blocked + // use the fallback choice return startID; } @@ -1102,10 +973,7 @@ NAV_GetNearestNode ------------------------- */ -int NAV_GetNearestNode( gentity_t *self, int lastNode ) -{ - return trap->Nav_GetNearestNode( (sharedEntity_t *)self, lastNode, NF_CLEAR_PATH, WAYPOINT_NONE ); -} +int NAV_GetNearestNode(gentity_t *self, int lastNode) { return trap->Nav_GetNearestNode((sharedEntity_t *)self, lastNode, NF_CLEAR_PATH, WAYPOINT_NONE); } /* ------------------------- @@ -1113,12 +981,9 @@ NAV_MicroError ------------------------- */ -qboolean NAV_MicroError( vec3_t start, vec3_t end ) -{ - if ( VectorCompare( start, end ) ) - { - if ( DistanceSquared( NPCS.NPC->r.currentOrigin, start ) < (8*8) ) - { +qboolean NAV_MicroError(vec3_t start, vec3_t end) { + if (VectorCompare(start, end)) { + if (DistanceSquared(NPCS.NPC->r.currentOrigin, start) < (8 * 8)) { return qtrue; } } @@ -1132,102 +997,93 @@ NAV_MoveToGoal ------------------------- */ -int NAV_MoveToGoal( gentity_t *self, navInfo_t *info ) -{ +int NAV_MoveToGoal(gentity_t *self, navInfo_t *info) { int bestNode; - vec3_t origin, end; + vec3_t origin, end; - //Must have a goal entity to move there - if( self->NPC->goalEntity == NULL ) + // Must have a goal entity to move there + if (self->NPC->goalEntity == NULL) return WAYPOINT_NONE; - //Check special player optimizations - if ( self->NPC->goalEntity->s.number >= 0 && self->NPC->goalEntity->s.number < MAX_CLIENTS ) - { - //If we couldn't find the point, then we won't be able to this turn - if ( self->NPC->goalEntity->waypoint == WAYPOINT_NONE ) + // Check special player optimizations + if (self->NPC->goalEntity->s.number >= 0 && self->NPC->goalEntity->s.number < MAX_CLIENTS) { + // If we couldn't find the point, then we won't be able to this turn + if (self->NPC->goalEntity->waypoint == WAYPOINT_NONE) return WAYPOINT_NONE; - //NOTENOTE: Otherwise trust this waypoint for the whole frame (reduce all unnecessary calculations) - } - else - { - //Find the target's waypoint - if ( ( self->NPC->goalEntity->waypoint = NAV_GetNearestNode( self->NPC->goalEntity, self->NPC->goalEntity->waypoint ) ) == WAYPOINT_NONE ) + // NOTENOTE: Otherwise trust this waypoint for the whole frame (reduce all unnecessary calculations) + } else { + // Find the target's waypoint + if ((self->NPC->goalEntity->waypoint = NAV_GetNearestNode(self->NPC->goalEntity, self->NPC->goalEntity->waypoint)) == WAYPOINT_NONE) return WAYPOINT_NONE; } - //Find our waypoint - if ( ( self->waypoint = NAV_GetNearestNode( self, self->lastWaypoint ) ) == WAYPOINT_NONE ) + // Find our waypoint + if ((self->waypoint = NAV_GetNearestNode(self, self->lastWaypoint)) == WAYPOINT_NONE) return WAYPOINT_NONE; - bestNode = trap->Nav_GetBestNode( self->waypoint, self->NPC->goalEntity->waypoint, NODE_NONE ); + bestNode = trap->Nav_GetBestNode(self->waypoint, self->NPC->goalEntity->waypoint, NODE_NONE); - if ( bestNode == WAYPOINT_NONE ) - { - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t neworigin, torigin; + if (bestNode == WAYPOINT_NONE) { + if (NAVDEBUG_showEnemyPath) { + vec3_t neworigin, torigin; - trap->Nav_GetNodePosition( self->NPC->goalEntity->waypoint, torigin ); - trap->Nav_GetNodePosition( self->waypoint, neworigin ); + trap->Nav_GetNodePosition(self->NPC->goalEntity->waypoint, torigin); + trap->Nav_GetNodePosition(self->waypoint, neworigin); - G_DrawNode( torigin, NODE_GOAL ); - G_DrawNode( neworigin, NODE_GOAL ); - G_DrawNode( self->NPC->goalEntity->r.currentOrigin, NODE_START ); + G_DrawNode(torigin, NODE_GOAL); + G_DrawNode(neworigin, NODE_GOAL); + G_DrawNode(self->NPC->goalEntity->r.currentOrigin, NODE_START); } return WAYPOINT_NONE; } - //Check this node - bestNode = NAV_TestBestNode( self, bestNode, self->NPC->goalEntity->waypoint, qfalse ); + // Check this node + bestNode = NAV_TestBestNode(self, bestNode, self->NPC->goalEntity->waypoint, qfalse); - //trace_t trace; + // trace_t trace; - //Get this position - trap->Nav_GetNodePosition( bestNode, origin ); - trap->Nav_GetNodePosition( self->waypoint, end ); + // Get this position + trap->Nav_GetNodePosition(bestNode, origin); + trap->Nav_GetNodePosition(self->waypoint, end); - //Basically, see if the path we have isn't helping - //if ( NAV_MicroError( origin, end ) ) + // Basically, see if the path we have isn't helping + // if ( NAV_MicroError( origin, end ) ) // return WAYPOINT_NONE; - //Test the path connection from our current position to the best node - if ( NAV_CheckAhead( self, origin, &info->trace, (self->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP ) == qfalse ) - { - //First attempt to move to the closest point on the line between the waypoints - G_FindClosestPointOnLineSegment( origin, end, self->r.currentOrigin, origin ); + // Test the path connection from our current position to the best node + if (NAV_CheckAhead(self, origin, &info->trace, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP) == qfalse) { + // First attempt to move to the closest point on the line between the waypoints + G_FindClosestPointOnLineSegment(origin, end, self->r.currentOrigin, origin); - //See if we can go there - if ( NAV_CheckAhead( self, origin, &info->trace, (self->clipmask&~CONTENTS_BODY)|CONTENTS_BOTCLIP ) == qfalse ) - { - //Just move towards our current waypoint + // See if we can go there + if (NAV_CheckAhead(self, origin, &info->trace, (self->clipmask & ~CONTENTS_BODY) | CONTENTS_BOTCLIP) == qfalse) { + // Just move towards our current waypoint bestNode = self->waypoint; - trap->Nav_GetNodePosition( bestNode, origin ); + trap->Nav_GetNodePosition(bestNode, origin); } } - //Setup our new move information - VectorSubtract( origin, self->r.currentOrigin, info->direction ); - info->distance = VectorNormalize( info->direction ); + // Setup our new move information + VectorSubtract(origin, self->r.currentOrigin, info->direction); + info->distance = VectorNormalize(info->direction); - VectorSubtract( end, origin, info->pathDirection ); - VectorNormalize( info->pathDirection ); + VectorSubtract(end, origin, info->pathDirection); + VectorNormalize(info->pathDirection); - //Draw any debug info, if requested - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t dest, start; + // Draw any debug info, if requested + if (NAVDEBUG_showEnemyPath) { + vec3_t dest, start; - //Get the positions - trap->Nav_GetNodePosition( self->NPC->goalEntity->waypoint, dest ); - trap->Nav_GetNodePosition( bestNode, start ); + // Get the positions + trap->Nav_GetNodePosition(self->NPC->goalEntity->waypoint, dest); + trap->Nav_GetNodePosition(bestNode, start); - //Draw the route - G_DrawNode( start, NODE_START ); - G_DrawNode( dest, NODE_GOAL ); - trap->Nav_ShowPath( self->waypoint, self->NPC->goalEntity->waypoint ); + // Draw the route + G_DrawNode(start, NODE_START); + G_DrawNode(dest, NODE_GOAL); + trap->Nav_ShowPath(self->waypoint, self->NPC->goalEntity->waypoint); } return bestNode; @@ -1239,29 +1095,28 @@ waypoint_testDirection ------------------------- */ -unsigned int waypoint_testDirection( vec3_t origin, float yaw, unsigned int minDist ) -{ - vec3_t trace_dir, test_pos; - vec3_t maxs, mins; - vec3_t angles; - trace_t tr; +unsigned int waypoint_testDirection(vec3_t origin, float yaw, unsigned int minDist) { + vec3_t trace_dir, test_pos; + vec3_t maxs, mins; + vec3_t angles; + trace_t tr; - //Setup the mins and max - VectorSet( maxs, 15, 15, DEFAULT_MAXS_2 ); - VectorSet( mins, -15, -15, DEFAULT_MINS_2 + STEPSIZE ); + // Setup the mins and max + VectorSet(maxs, 15, 15, DEFAULT_MAXS_2); + VectorSet(mins, -15, -15, DEFAULT_MINS_2 + STEPSIZE); - //Get our test direction - VectorSet(angles, 0, yaw, 0 ); - AngleVectors( angles, trace_dir, NULL, NULL ); + // Get our test direction + VectorSet(angles, 0, yaw, 0); + AngleVectors(angles, trace_dir, NULL, NULL); - //Move ahead -// VectorMA( origin, MAX_RADIUS_CHECK, trace_dir, test_pos ); - VectorMA( origin, minDist, trace_dir, test_pos ); + // Move ahead + // VectorMA( origin, MAX_RADIUS_CHECK, trace_dir, test_pos ); + VectorMA(origin, minDist, trace_dir, test_pos); - trap->Trace( &tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, ( CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP ), qfalse, 0, 0 ); + trap->Trace(&tr, origin, mins, maxs, test_pos, ENTITYNUM_NONE, (CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP), qfalse, 0, 0); - //return (unsigned int) ( (float) MAX_RADIUS_CHECK * tr.fraction ); - return (unsigned int) ( (float) minDist * tr.fraction ); + // return (unsigned int) ( (float) MAX_RADIUS_CHECK * tr.fraction ); + return (unsigned int)((float)minDist * tr.fraction); } /* @@ -1270,17 +1125,15 @@ waypoint_getRadius ------------------------- */ -unsigned int waypoint_getRadius( gentity_t *ent ) -{ - unsigned int minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; - unsigned int dist; - int i; +unsigned int waypoint_getRadius(gentity_t *ent) { + unsigned int minDist = MAX_RADIUS_CHECK + 1; // (unsigned int) -1; + unsigned int dist; + int i; - for ( i = 0; i < YAW_ITERATIONS; i++ ) - { - dist = waypoint_testDirection( ent->r.currentOrigin, ((360.0f/YAW_ITERATIONS) * i), minDist ); + for (i = 0; i < YAW_ITERATIONS; i++) { + dist = waypoint_testDirection(ent->r.currentOrigin, ((360.0f / YAW_ITERATIONS) * i), minDist); - if ( dist < minDist ) + if (dist < minDist) minDist = dist; } @@ -1290,14 +1143,13 @@ unsigned int waypoint_getRadius( gentity_t *ent ) /*QUAKED waypoint (0.7 0.7 0) (-16 -16 -24) (16 16 32) SOLID_OK a place to go. -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) radius is automatically calculated in-world. */ -void SP_waypoint ( gentity_t *ent ) -{ - if ( navCalculatePaths ) - { +void SP_waypoint(gentity_t *ent) { + if (navCalculatePaths) { unsigned int radius; VectorSet(ent->r.mins, -15, -15, DEFAULT_MINS_2); @@ -1306,27 +1158,25 @@ void SP_waypoint ( gentity_t *ent ) ent->r.contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); ent->count = -1; ent->classname = "waypoint"; - if( !(ent->spawnflags&1) && G_CheckInSolid (ent, qtrue)) - {//if not SOLID_OK, and in solid + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { // if not SOLID_OK, and in solid ent->r.maxs[2] = CROUCH_MAXS_2; - if(G_CheckInSolid (ent, qtrue)) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (G_CheckInSolid(ent, qtrue)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0 && "Waypoint in solid!"); G_FreeEntity(ent); return; } } - radius = waypoint_getRadius( ent ); + radius = waypoint_getRadius(ent); - ent->health = trap->Nav_AddRawPoint( ent->r.currentOrigin, ent->spawnflags, radius ); - NAV_StoreWaypoint( ent ); + ent->health = trap->Nav_AddRawPoint(ent->r.currentOrigin, ent->spawnflags, radius); + NAV_StoreWaypoint(ent); G_FreeEntity(ent); return; } @@ -1335,37 +1185,34 @@ void SP_waypoint ( gentity_t *ent ) } /*QUAKED waypoint_small (0.7 0.7 0) (-2 -2 -24) (2 2 32) SOLID_OK -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) */ -void SP_waypoint_small (gentity_t *ent) -{ - if ( navCalculatePaths ) - { +void SP_waypoint_small(gentity_t *ent) { + if (navCalculatePaths) { VectorSet(ent->r.mins, -2, -2, DEFAULT_MINS_2); VectorSet(ent->r.maxs, 2, 2, DEFAULT_MAXS_2); ent->r.contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); ent->count = -1; ent->classname = "waypoint"; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qtrue ) ) - { + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qtrue)) { ent->r.maxs[2] = CROUCH_MAXS_2; - if ( G_CheckInSolid( ent, qtrue ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (G_CheckInSolid(ent, qtrue)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); G_FreeEntity(ent); return; } } - ent->health = trap->Nav_AddRawPoint( ent->r.currentOrigin, ent->spawnflags, 2 ); - NAV_StoreWaypoint( ent ); + ent->health = trap->Nav_AddRawPoint(ent->r.currentOrigin, ent->spawnflags, 2); + NAV_StoreWaypoint(ent); G_FreeEntity(ent); return; } @@ -1373,12 +1220,12 @@ void SP_waypoint_small (gentity_t *ent) G_FreeEntity(ent); } - /*QUAKED waypoint_navgoal (0.3 1 0.3) (-16 -16 -24) (16 16 32) SOLID_OK A waypoint for script navgoals Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1389,29 +1236,28 @@ targetname - name you would use in script when setting a navgoal (like so:) radius - how far from the navgoal an ent can be before it thinks it reached it - default is "0" which means no radius check, just have to touch it */ -void SP_waypoint_navgoal( gentity_t *ent ) -{ - int radius = ( ent->radius ) ? (((int)ent->radius)|NAVGOAL_USE_RADIUS) : 12; +void SP_waypoint_navgoal(gentity_t *ent) { + int radius = (ent->radius) ? (((int)ent->radius) | NAVGOAL_USE_RADIUS) : 12; - VectorSet( ent->r.mins, -16, -16, -24 ); - VectorSet( ent->r.maxs, 16, 16, 32 ); + VectorSet(ent->r.mins, -16, -16, -24); + VectorSet(ent->r.maxs, 16, 16, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_8 (0.3 1 0.3) (-8 -8 -24) (8 8 32) SOLID_OK A waypoint for script navgoals, 8 x 8 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1421,28 +1267,27 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_8( gentity_t *ent ) -{ - VectorSet( ent->r.mins, -8, -8, -24 ); - VectorSet( ent->r.maxs, 8, 8, 32 ); +void SP_waypoint_navgoal_8(gentity_t *ent) { + VectorSet(ent->r.mins, -8, -8, -24); + VectorSet(ent->r.maxs, 8, 8, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 8, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 8, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_4 (0.3 1 0.3) (-4 -4 -24) (4 4 32) SOLID_OK A waypoint for script navgoals, 4 x 4 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1452,28 +1297,27 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_4( gentity_t *ent ) -{ - VectorSet( ent->r.mins, -4, -4, -24 ); - VectorSet( ent->r.maxs, 4, 4, 32 ); +void SP_waypoint_navgoal_4(gentity_t *ent) { + VectorSet(ent->r.mins, -4, -4, -24); + VectorSet(ent->r.maxs, 4, 4, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 4, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 4, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_2 (0.3 1 0.3) (-2 -2 -24) (2 2 32) SOLID_OK A waypoint for script navgoals, 2 x 2 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1483,28 +1327,27 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_2( gentity_t *ent ) -{ - VectorSet( ent->r.mins, -2, -2, -24 ); - VectorSet( ent->r.maxs, 2, 2, 32 ); +void SP_waypoint_navgoal_2(gentity_t *ent) { + VectorSet(ent->r.mins, -2, -2, -24); + VectorSet(ent->r.maxs, 2, 2, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 2, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 2, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_1 (0.3 1 0.3) (-1 -1 -24) (1 1 32) SOLID_OK A waypoint for script navgoals, 1 x 1 size Not included in navigation data -SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top position) +SOLID_OK - only use if placing inside solid is unavoidable in map, but may be clear in-game (ie: at the bottom of a tall, solid lift that starts at the top +position) targetname - name you would use in script when setting a navgoal (like so:) @@ -1514,21 +1357,19 @@ targetname - name you would use in script when setting a navgoal (like so:) You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ -void SP_waypoint_navgoal_1( gentity_t *ent ) -{ - VectorSet( ent->r.mins, -1, -1, -24 ); - VectorSet( ent->r.maxs, 1, 1, 32 ); +void SP_waypoint_navgoal_1(gentity_t *ent) { + VectorSet(ent->r.mins, -1, -1, -24); + VectorSet(ent->r.maxs, 1, 1, 32); ent->s.origin[2] += 0.125; - if ( !(ent->spawnflags&1) && G_CheckInSolid( ent, qfalse ) ) - { - Com_Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); + if (!(ent->spawnflags & 1) && G_CheckInSolid(ent, qfalse)) { + Com_Printf(S_COLOR_RED "ERROR: Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->r.currentOrigin)); assert(0); } - TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 1, RTF_NAVGOAL ); + TAG_Add(ent->targetname, NULL, ent->s.origin, ent->s.angles, 1, RTF_NAVGOAL); ent->classname = "navgoal"; - G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? + G_FreeEntity(ent); // can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /* @@ -1537,96 +1378,69 @@ Svcmd_Nav_f ------------------------- */ -void Svcmd_Nav_f( void ) -{ +void Svcmd_Nav_f(void) { char cmd[1024]; - trap->Argv( 1, cmd, 1024 ); + trap->Argv(1, cmd, 1024); - if ( Q_stricmp( cmd, "show" ) == 0 ) - { + if (Q_stricmp(cmd, "show") == 0) { trap->Argv(2, cmd, 1024); - if ( Q_stricmp( cmd, "all" ) == 0 ) - { + if (Q_stricmp(cmd, "all") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - //NOTENOTE: This causes the two states to sync up if they aren't already - NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = - NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = - NAVDEBUG_showEdges = NAVDEBUG_showRadius = NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "nodes" ) == 0 ) - { + // NOTENOTE: This causes the two states to sync up if they aren't already + NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = NAVDEBUG_showEdges = NAVDEBUG_showRadius = + NAVDEBUG_showNodes; + } else if (Q_stricmp(cmd, "nodes") == 0) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; - } - else if ( Q_stricmp( cmd, "radius" ) == 0 ) - { + } else if (Q_stricmp(cmd, "radius") == 0) { NAVDEBUG_showRadius = !NAVDEBUG_showRadius; - } - else if ( Q_stricmp( cmd, "edges" ) == 0 ) - { + } else if (Q_stricmp(cmd, "edges") == 0) { NAVDEBUG_showEdges = !NAVDEBUG_showEdges; - } - else if ( Q_stricmp( cmd, "testpath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "testpath") == 0) { NAVDEBUG_showTestPath = !NAVDEBUG_showTestPath; - } - else if ( Q_stricmp( cmd, "enemypath" ) == 0 ) - { + } else if (Q_stricmp(cmd, "enemypath") == 0) { NAVDEBUG_showEnemyPath = !NAVDEBUG_showEnemyPath; - } - else if ( Q_stricmp( cmd, "combatpoints" ) == 0 ) - { + } else if (Q_stricmp(cmd, "combatpoints") == 0) { NAVDEBUG_showCombatPoints = !NAVDEBUG_showCombatPoints; - } - else if ( Q_stricmp( cmd, "navgoals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "navgoals") == 0) { NAVDEBUG_showNavGoals = !NAVDEBUG_showNavGoals; - } - else if ( Q_stricmp( cmd, "collision" ) == 0 ) - { + } else if (Q_stricmp(cmd, "collision") == 0) { NAVDEBUG_showCollision = !NAVDEBUG_showCollision; } - } - else if ( Q_stricmp( cmd, "set" ) == 0 ) - { - trap->Argv( 2, cmd, 1024 ); + } else if (Q_stricmp(cmd, "set") == 0) { + trap->Argv(2, cmd, 1024); - if ( Q_stricmp( cmd, "testgoal" ) == 0 ) - { - NAVDEBUG_curGoal = trap->Nav_GetNearestNode( (sharedEntity_t *)&g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); + if (Q_stricmp(cmd, "testgoal") == 0) { + NAVDEBUG_curGoal = trap->Nav_GetNearestNode((sharedEntity_t *)&g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH, WAYPOINT_NONE); } - } - else if ( Q_stricmp( cmd, "totals" ) == 0 ) - { + } else if (Q_stricmp(cmd, "totals") == 0) { Com_Printf("Navigation Totals:\n"); Com_Printf("------------------\n"); - Com_Printf("Total Nodes: %d\n", trap->Nav_GetNumNodes() ); - Com_Printf("Total Combat Points: %d\n", level.numCombatPoints ); - } - else - { - //Print the available commands - Com_Printf("nav - valid commands\n---\n" ); + Com_Printf("Total Nodes: %d\n", trap->Nav_GetNumNodes()); + Com_Printf("Total Combat Points: %d\n", level.numCombatPoints); + } else { + // Print the available commands + Com_Printf("nav - valid commands\n---\n"); Com_Printf("show\n - nodes\n - edges\n - testpath\n - enemypath\n - combatpoints\n - navgoals\n---\n"); - Com_Printf("set\n - testgoal\n---\n" ); + Com_Printf("set\n - testgoal\n---\n"); } } // -//JWEIER ADDITIONS START +// JWEIER ADDITIONS START -qboolean navCalculatePaths = qfalse; +qboolean navCalculatePaths = qfalse; -qboolean NAVDEBUG_showNodes = qfalse; -qboolean NAVDEBUG_showRadius = qfalse; -qboolean NAVDEBUG_showEdges = qfalse; -qboolean NAVDEBUG_showTestPath = qfalse; -qboolean NAVDEBUG_showEnemyPath = qfalse; -qboolean NAVDEBUG_showCombatPoints = qfalse; -qboolean NAVDEBUG_showNavGoals = qfalse; -qboolean NAVDEBUG_showCollision = qfalse; -int NAVDEBUG_curGoal = 0; +qboolean NAVDEBUG_showNodes = qfalse; +qboolean NAVDEBUG_showRadius = qfalse; +qboolean NAVDEBUG_showEdges = qfalse; +qboolean NAVDEBUG_showTestPath = qfalse; +qboolean NAVDEBUG_showEnemyPath = qfalse; +qboolean NAVDEBUG_showCombatPoints = qfalse; +qboolean NAVDEBUG_showNavGoals = qfalse; +qboolean NAVDEBUG_showCollision = qfalse; +int NAVDEBUG_curGoal = 0; /* ------------------------- @@ -1636,60 +1450,42 @@ NAV_CalculatePaths #ifndef FINAL_BUILD int fatalErrors = 0; char *fatalErrorPointer = NULL; -char fatalErrorString[4096]; -qboolean NAV_WaypointsTooFar( gentity_t *wp1, gentity_t *wp2 ) -{ - if ( Distance( wp1->r.currentOrigin, wp2->r.currentOrigin ) > 1024 ) - { - char temp[1024]; - int len; +char fatalErrorString[4096]; +qboolean NAV_WaypointsTooFar(gentity_t *wp1, gentity_t *wp2) { + if (Distance(wp1->r.currentOrigin, wp2->r.currentOrigin) > 1024) { + char temp[1024]; + int len; fatalErrors++; - if ( !wp1->targetname && !wp2->targetname ) - { - Com_sprintf( temp, sizeof(temp), S_COLOR_RED"Waypoint conn %s->%s > 1024\n", vtos( wp1->r.currentOrigin ), vtos( wp2->r.currentOrigin ) ); - } - else if ( !wp1->targetname ) - { - Com_sprintf( temp, sizeof(temp), S_COLOR_RED"Waypoint conn %s->%s > 1024\n", vtos( wp1->r.currentOrigin ), wp2->targetname ); + if (!wp1->targetname && !wp2->targetname) { + Com_sprintf(temp, sizeof(temp), S_COLOR_RED "Waypoint conn %s->%s > 1024\n", vtos(wp1->r.currentOrigin), vtos(wp2->r.currentOrigin)); + } else if (!wp1->targetname) { + Com_sprintf(temp, sizeof(temp), S_COLOR_RED "Waypoint conn %s->%s > 1024\n", vtos(wp1->r.currentOrigin), wp2->targetname); + } else if (!wp2->targetname) { + Com_sprintf(temp, sizeof(temp), S_COLOR_RED "Waypoint conn %s->%s > 1024\n", wp1->targetname, vtos(wp2->r.currentOrigin)); + } else { // they both have valid targetnames + Com_sprintf(temp, sizeof(temp), S_COLOR_RED "Waypoint conn %s->%s > 1024\n", wp1->targetname, wp2->targetname); } - else if ( !wp2->targetname ) - { - Com_sprintf( temp, sizeof(temp), S_COLOR_RED"Waypoint conn %s->%s > 1024\n", wp1->targetname, vtos( wp2->r.currentOrigin ) ); - } - else - {//they both have valid targetnames - Com_sprintf( temp, sizeof(temp), S_COLOR_RED"Waypoint conn %s->%s > 1024\n", wp1->targetname, wp2->targetname ); - } - len = strlen( temp ); - if ( (fatalErrorPointer-fatalErrorString)+len >= sizeof( fatalErrorString ) ) - { - Com_Error( ERR_DROP, "%s%s%dTOO MANY FATAL NAV ERRORS!!!\n", fatalErrorString, temp, fatalErrors ); + len = strlen(temp); + if ((fatalErrorPointer - fatalErrorString) + len >= sizeof(fatalErrorString)) { + Com_Error(ERR_DROP, "%s%s%dTOO MANY FATAL NAV ERRORS!!!\n", fatalErrorString, temp, fatalErrors); return qtrue; } - strcat( fatalErrorPointer, temp ); + strcat(fatalErrorPointer, temp); fatalErrorPointer += len; return qtrue; - } - else - { + } else { return qfalse; } } #endif static int numStoredWaypoints = 0; -//static waypointData_t *tempWaypointList=0; -static waypointData_t tempWaypointList[MAX_STORED_WAYPOINTS]; //rwwFIXMEFIXME: Need.. dynamic.. memory +// static waypointData_t *tempWaypointList=0; +static waypointData_t tempWaypointList[MAX_STORED_WAYPOINTS]; // rwwFIXMEFIXME: Need.. dynamic.. memory +void NAV_ClearStoredWaypoints(void) { numStoredWaypoints = 0; } -void NAV_ClearStoredWaypoints(void) -{ - numStoredWaypoints = 0; -} - - -void NAV_StoreWaypoint( gentity_t *ent ) -{ +void NAV_StoreWaypoint(gentity_t *ent) { /* if ( !tempWaypointList ) { @@ -1701,51 +1497,40 @@ void NAV_StoreWaypoint( gentity_t *ent ) } */ - if ( numStoredWaypoints >= MAX_STORED_WAYPOINTS ) - { - //trap->Error( ERR_DROP, "Too many waypoints! (%d > %d)\n", numStoredWaypoints, MAX_STORED_WAYPOINTS ); - //rwwFIXMEFIXME: commented this out so I can load some of the SP levels. + if (numStoredWaypoints >= MAX_STORED_WAYPOINTS) { + // trap->Error( ERR_DROP, "Too many waypoints! (%d > %d)\n", numStoredWaypoints, MAX_STORED_WAYPOINTS ); + // rwwFIXMEFIXME: commented this out so I can load some of the SP levels. return; } - if ( ent->targetname ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].targetname, ent->targetname, MAX_QPATH ); + if (ent->targetname) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].targetname, ent->targetname, MAX_QPATH); } - if ( ent->target ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target, ent->target, MAX_QPATH ); + if (ent->target) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target, ent->target, MAX_QPATH); } - if ( ent->target2 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target2, ent->target2, MAX_QPATH ); + if (ent->target2) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target2, ent->target2, MAX_QPATH); } - if ( ent->target3 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target3, ent->target3, MAX_QPATH ); + if (ent->target3) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target3, ent->target3, MAX_QPATH); } - if ( ent->target4 ) - { - Q_strncpyz( tempWaypointList[numStoredWaypoints].target4, ent->target4, MAX_QPATH ); + if (ent->target4) { + Q_strncpyz(tempWaypointList[numStoredWaypoints].target4, ent->target4, MAX_QPATH); } tempWaypointList[numStoredWaypoints].nodeID = ent->health; numStoredWaypoints++; } -int NAV_GetStoredWaypoint( char *targetname ) -{ +int NAV_GetStoredWaypoint(char *targetname) { int i; - if ( !targetname || !targetname[0] ) - { + if (!targetname || !targetname[0]) { return -1; } - for ( i = 0; i < numStoredWaypoints; i++ ) - { - if ( tempWaypointList[i].targetname[0] ) - { - if ( !Q_stricmp( targetname, tempWaypointList[i].targetname ) ) - { + for (i = 0; i < numStoredWaypoints; i++) { + if (tempWaypointList[i].targetname[0]) { + if (!Q_stricmp(targetname, tempWaypointList[i].targetname)) { return i; } } @@ -1753,100 +1538,85 @@ int NAV_GetStoredWaypoint( char *targetname ) return -1; } -void NAV_CalculatePaths( const char *filename, int checksum ) -{ +void NAV_CalculatePaths(const char *filename, int checksum) { int target = -1; int i; #ifdef _DISABLED - if ( !tempWaypointList ) - { + if (!tempWaypointList) { return; } #endif //_DISABLED #ifndef FINAL_BUILD fatalErrors = 0; - memset( fatalErrorString, 0, sizeof( fatalErrorString ) ); + memset(fatalErrorString, 0, sizeof(fatalErrorString)); fatalErrorPointer = &fatalErrorString[0]; #endif #if _HARD_CONNECT - //Find all connections and hard connect them - for ( i = 0; i < numStoredWaypoints; i++ ) - { - //Find the first connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target ); + // Find all connections and hard connect them + for (i = 0; i < numStoredWaypoints; i++) { + // Find the first connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - trap->Nav_HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { trap->Nav_HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible second connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target2 ); + // Find a possible second connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target2); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - trap->Nav_HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { trap->Nav_HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible third connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target3 ); + // Find a possible third connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target3); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - trap->Nav_HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { trap->Nav_HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } - //Find a possible fourth connection - target = NAV_GetStoredWaypoint( tempWaypointList[i].target4 ); + // Find a possible fourth connection + target = NAV_GetStoredWaypoint(tempWaypointList[i].target4); - if ( target != -1 ) - { + if (target != -1) { #ifndef FINAL_BUILD // if ( !NAV_WaypointsTooFar( ent, target ) ) #endif - { - trap->Nav_HardConnect( tempWaypointList[i].nodeID, tempWaypointList[target].nodeID ); - } + { trap->Nav_HardConnect(tempWaypointList[i].nodeID, tempWaypointList[target].nodeID); } } } #endif - //Remove all waypoints now that they're done - //trap->Free(tempWaypointList); + // Remove all waypoints now that they're done + // trap->Free(tempWaypointList); /* trap->TrueFree((void **)&tempWaypointList); tempWaypointList=0; */ - //Now check all blocked edges, mark failed ones + // Now check all blocked edges, mark failed ones trap->Nav_CheckBlockedEdges(); trap->Nav_SetPathsCalculated(qfalse); - //navigator.pathsCalculated = qfalse; + // navigator.pathsCalculated = qfalse; - //Calculate the paths based on the supplied waypoints - //trap->Nav_CalculatePaths(); + // Calculate the paths based on the supplied waypoints + // trap->Nav_CalculatePaths(); - //Save the resulting information + // Save the resulting information /* if ( trap->Nav_Save( filename, checksum ) == qfalse ) { @@ -1854,10 +1624,9 @@ void NAV_CalculatePaths( const char *filename, int checksum ) } */ #ifndef FINAL_BUILD - if ( fatalErrors ) - { - //Com_Error( ERR_DROP, "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); - Com_Printf( "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); + if (fatalErrors) { + // Com_Error( ERR_DROP, "%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors ); + Com_Printf("%s%d FATAL NAV ERRORS\n", fatalErrorString, fatalErrors); } #endif } @@ -1868,10 +1637,7 @@ NAV_Shutdown ------------------------- */ -void NAV_Shutdown( void ) -{ - trap->Nav_Free(); -} +void NAV_Shutdown(void) { trap->Nav_Free(); } /* ------------------------- @@ -1879,51 +1645,44 @@ NAV_ShowDebugInfo ------------------------- */ -void NAV_ShowDebugInfo( void ) -{ +void NAV_ShowDebugInfo(void) { int i; - if ( NAVDEBUG_showNodes ) - { + if (NAVDEBUG_showNodes) { trap->Nav_ShowNodes(); } - if ( NAVDEBUG_showEdges ) - { + if (NAVDEBUG_showEdges) { trap->Nav_ShowEdges(); } - if ( NAVDEBUG_showTestPath ) - { - //Get the nearest node to the player - int nearestNode = trap->Nav_GetNearestNode( (sharedEntity_t *)&g_entities[0], g_entities[0].waypoint, NF_ANY, WAYPOINT_NONE ); - int testNode = trap->Nav_GetBestNode( nearestNode, NAVDEBUG_curGoal, NODE_NONE ); - vec3_t dest, start; + if (NAVDEBUG_showTestPath) { + // Get the nearest node to the player + int nearestNode = trap->Nav_GetNearestNode((sharedEntity_t *)&g_entities[0], g_entities[0].waypoint, NF_ANY, WAYPOINT_NONE); + int testNode = trap->Nav_GetBestNode(nearestNode, NAVDEBUG_curGoal, NODE_NONE); + vec3_t dest, start; - nearestNode = NAV_TestBestNode( &g_entities[0], nearestNode, testNode, qfalse ); + nearestNode = NAV_TestBestNode(&g_entities[0], nearestNode, testNode, qfalse); - //Show the connection + // Show the connection - //Get the positions - trap->Nav_GetNodePosition( NAVDEBUG_curGoal, dest ); - trap->Nav_GetNodePosition( nearestNode, start ); + // Get the positions + trap->Nav_GetNodePosition(NAVDEBUG_curGoal, dest); + trap->Nav_GetNodePosition(nearestNode, start); - G_DrawNode( start, NODE_START ); - G_DrawNode( dest, NODE_GOAL ); - trap->Nav_ShowPath( nearestNode, NAVDEBUG_curGoal ); + G_DrawNode(start, NODE_START); + G_DrawNode(dest, NODE_GOAL); + trap->Nav_ShowPath(nearestNode, NAVDEBUG_curGoal); } - if ( NAVDEBUG_showCombatPoints ) - { - for ( i = 0; i < level.numCombatPoints; i++ ) - { - G_DrawCombatPoint( level.combatPoints[i].origin, 0 ); + if (NAVDEBUG_showCombatPoints) { + for (i = 0; i < level.numCombatPoints; i++) { + G_DrawCombatPoint(level.combatPoints[i].origin, 0); } } - if ( NAVDEBUG_showNavGoals ) - { - TAG_ShowTags( RTF_NAVGOAL ); + if (NAVDEBUG_showNavGoals) { + TAG_ShowTags(RTF_NAVGOAL); } } @@ -1933,10 +1692,9 @@ NAV_FindPlayerWaypoint ------------------------- */ -void NAV_FindPlayerWaypoint( int clNum ) -{ - g_entities[clNum].waypoint = trap->Nav_GetNearestNode( (sharedEntity_t *)&g_entities[clNum], g_entities[clNum].lastWaypoint, NF_CLEAR_PATH, WAYPOINT_NONE ); +void NAV_FindPlayerWaypoint(int clNum) { + g_entities[clNum].waypoint = trap->Nav_GetNearestNode((sharedEntity_t *)&g_entities[clNum], g_entities[clNum].lastWaypoint, NF_CLEAR_PATH, WAYPOINT_NONE); } // -//JWEIER ADDITIONS END +// JWEIER ADDITIONS END diff --git a/codemp/game/g_navnew.c b/codemp/game/g_navnew.c index 395ff598d3..341330703e 100644 --- a/codemp/game/g_navnew.c +++ b/codemp/game/g_navnew.c @@ -23,26 +23,24 @@ along with this program; if not, see . #include "b_local.h" #include "g_nav.h" -qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t *trace, int clipmask ); -qboolean NAV_TestForBlocked( gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int *flags ); - -void G_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); -void G_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); -void G_CubeOutline( vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha ); -void G_DrawEdge( vec3_t start, vec3_t end, int type ); -void G_DrawNode( vec3_t origin, int type ); -void G_DrawCombatPoint( vec3_t origin, int type ); -void TAG_ShowTags( int flags ); - -qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ) -{ +qboolean NAV_CheckAhead(gentity_t *self, vec3_t end, trace_t *trace, int clipmask); +qboolean NAV_TestForBlocked(gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int *flags); + +void G_Line(vec3_t start, vec3_t end, vec3_t color, float alpha); +void G_Cube(vec3_t mins, vec3_t maxs, vec3_t color, float alpha); +void G_CubeOutline(vec3_t mins, vec3_t maxs, int time, unsigned int color, float alpha); +void G_DrawEdge(vec3_t start, vec3_t end, int type); +void G_DrawNode(vec3_t origin, int type); +void G_DrawCombatPoint(vec3_t origin, int type); +void TAG_ShowTags(int flags); + +qboolean NAV_CheckNodeFailedForEnt(gentity_t *ent, int nodeNum) { int j; - //FIXME: must be a better way to do this - for ( j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] == nodeNum+1 )//+1 because 0 is a valid nodeNum, but also the default - {//we failed against this node + // FIXME: must be a better way to do this + for (j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] == nodeNum + 1) //+1 because 0 is a valid nodeNum, but also the default + { // we failed against this node return qtrue; } } @@ -53,22 +51,20 @@ qboolean NAV_CheckNodeFailedForEnt( gentity_t *ent, int nodeNum ) NPC_UnBlocked ------------------------- */ -void NPC_ClearBlocked( gentity_t *self ) -{ - if ( self->NPC == NULL ) +void NPC_ClearBlocked(gentity_t *self) { + if (self->NPC == NULL) return; - //self->NPC->aiFlags &= ~NPCAI_BLOCKED; + // self->NPC->aiFlags &= ~NPCAI_BLOCKED; self->NPC->blockingEntNum = ENTITYNUM_NONE; } -void NPC_SetBlocked( gentity_t *self, gentity_t *blocker ) -{ - if ( self->NPC == NULL ) +void NPC_SetBlocked(gentity_t *self, gentity_t *blocker) { + if (self->NPC == NULL) return; - //self->NPC->aiFlags |= NPCAI_BLOCKED; - self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + ( Q_flrand(0.0f, 1.0f) * 4000 ); + // self->NPC->aiFlags |= NPCAI_BLOCKED; + self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + (Q_flrand(0.0f, 1.0f) * 4000); self->NPC->blockingEntNum = blocker->s.number; } @@ -77,25 +73,23 @@ void NPC_SetBlocked( gentity_t *self, gentity_t *blocker ) NAVNEW_ClearPathBetweenPoints ------------------------- */ -int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask) -{ - trace_t trace; +int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask) { + trace_t trace; - //Test if they're even conceivably close to one another - if ( !trap->InPVS( start, end ) ) - { + // Test if they're even conceivably close to one another + if (!trap->InPVS(start, end)) { return ENTITYNUM_WORLD; } - trap->Trace( &trace, start, mins, maxs, end, ignore, clipmask, qfalse, 0, 0 ); + trap->Trace(&trace, start, mins, maxs, end, ignore, clipmask, qfalse, 0, 0); - //if( ( ( trace.startsolid == false ) && ( trace.allsolid == false ) ) && ( trace.fraction < 1.0f ) ) + // if( ( ( trace.startsolid == false ) && ( trace.allsolid == false ) ) && ( trace.fraction < 1.0f ) ) //{//FIXME: check for drops? - //FIXME: if startsolid or allsolid, then the path isn't clear... but returning ENTITYNUM_NONE indicates to CheckFailedEdge that is is clear...? - return trace.entityNum; + // FIXME: if startsolid or allsolid, then the path isn't clear... but returning ENTITYNUM_NONE indicates to CheckFailedEdge that is is clear...? + return trace.entityNum; //} - //return ENTITYNUM_NONE; + // return ENTITYNUM_NONE; } /* @@ -103,91 +97,71 @@ int NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t NAVNEW_PushBlocker ------------------------- */ -void NAVNEW_PushBlocker( gentity_t *self, gentity_t *blocker, vec3_t right, qboolean setBlockedInfo ) -{//try pushing blocker to one side - trace_t tr; - vec3_t mins, end; - float rightSucc, leftSucc, moveamt; - - if ( self->NPC->shoveCount > 30 ) - {//don't push for more than 3 seconds; +void NAVNEW_PushBlocker(gentity_t *self, gentity_t *blocker, vec3_t right, qboolean setBlockedInfo) { // try pushing blocker to one side + trace_t tr; + vec3_t mins, end; + float rightSucc, leftSucc, moveamt; + + if (self->NPC->shoveCount > 30) { // don't push for more than 3 seconds; return; } - if ( blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS ) - {//never push the player + if (blocker->s.number >= 0 && blocker->s.number < MAX_CLIENTS) { // never push the player return; } - if ( !blocker->client || !VectorCompare( blocker->client->pushVec, vec3_origin ) ) - {//someone else is pushing him, wait until they give up? + if (!blocker->client || !VectorCompare(blocker->client->pushVec, vec3_origin)) { // someone else is pushing him, wait until they give up? return; } - VectorCopy( blocker->r.mins, mins ); + VectorCopy(blocker->r.mins, mins); mins[2] += STEPSIZE; - moveamt = (self->r.maxs[1] + blocker->r.maxs[1]) * 1.2;//yes, magic number + moveamt = (self->r.maxs[1] + blocker->r.maxs[1]) * 1.2; // yes, magic number - VectorMA( blocker->r.currentOrigin, -moveamt, right, end ); - trap->Trace( &tr, blocker->r.currentOrigin, mins, blocker->r.maxs, end, blocker->s.number, blocker->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0); - if ( !tr.startsolid && !tr.allsolid ) - { + VectorMA(blocker->r.currentOrigin, -moveamt, right, end); + trap->Trace(&tr, blocker->r.currentOrigin, mins, blocker->r.maxs, end, blocker->s.number, blocker->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (!tr.startsolid && !tr.allsolid) { leftSucc = tr.fraction; - } - else - { + } else { leftSucc = 0.0f; } - if ( leftSucc >= 1.0f ) - {//it's clear, shove him that way - VectorScale( right, -moveamt, blocker->client->pushVec ); + if (leftSucc >= 1.0f) { // it's clear, shove him that way + VectorScale(right, -moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; - } - else - { - VectorMA( blocker->r.currentOrigin, moveamt, right, end ); - trap->Trace( &tr, blocker->r.currentOrigin, mins, blocker->r.maxs, end, blocker->s.number, blocker->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - if ( !tr.startsolid && !tr.allsolid ) - { + } else { + VectorMA(blocker->r.currentOrigin, moveamt, right, end); + trap->Trace(&tr, blocker->r.currentOrigin, mins, blocker->r.maxs, end, blocker->s.number, blocker->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); + if (!tr.startsolid && !tr.allsolid) { rightSucc = tr.fraction; - } - else - { + } else { rightSucc = 0.0f; } - if ( leftSucc == 0.0f && rightSucc == 0.0f ) - {//both sides failed - if ( d_patched.integer ) - {//use patch-style navigation + if (leftSucc == 0.0f && rightSucc == 0.0f) { // both sides failed + if (d_patched.integer) { // use patch-style navigation blocker->client->pushVecTime = 0; } return; } - if ( rightSucc >= 1.0f ) - {//it's clear, shove him that way - VectorScale( right, moveamt, blocker->client->pushVec ); + if (rightSucc >= 1.0f) { // it's clear, shove him that way + VectorScale(right, moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; } - //if neither are enough, we probably can't get around him, but keep trying - else if ( leftSucc >= rightSucc ) - {//favor the left, all things being equal - VectorScale( right, -moveamt, blocker->client->pushVec ); + // if neither are enough, we probably can't get around him, but keep trying + else if (leftSucc >= rightSucc) { // favor the left, all things being equal + VectorScale(right, -moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; - } - else - { - VectorScale( right, moveamt, blocker->client->pushVec ); + } else { + VectorScale(right, moveamt, blocker->client->pushVec); blocker->client->pushVecTime = level.time + 2000; } } - if ( setBlockedInfo ) - { - //we tried pushing + if (setBlockedInfo) { + // we tried pushing self->NPC->shoveCount++; } } @@ -197,28 +171,23 @@ void NAVNEW_PushBlocker( gentity_t *self, gentity_t *blocker, vec3_t right, qboo NAVNEW_DanceWithBlocker ------------------------- */ -qboolean NAVNEW_DanceWithBlocker( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t right ) -{//sees if blocker has any lateral movement - if ( blocker->client && !VectorCompare( blocker->client->ps.velocity, vec3_origin ) ) - { +qboolean NAVNEW_DanceWithBlocker(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t right) { // sees if blocker has any lateral movement + if (blocker->client && !VectorCompare(blocker->client->ps.velocity, vec3_origin)) { vec3_t blocker_movedir; float dot; - VectorCopy( blocker->client->ps.velocity, blocker_movedir ); - blocker_movedir[2] = 0;//cancel any vertical motion - dot = DotProduct( blocker_movedir, right ); - if ( dot > 50.0f ) - {//he's moving to the right of me at a relatively good speed - //go to my left - VectorMA( movedir, -1, right, movedir ); - VectorNormalize( movedir ); + VectorCopy(blocker->client->ps.velocity, blocker_movedir); + blocker_movedir[2] = 0; // cancel any vertical motion + dot = DotProduct(blocker_movedir, right); + if (dot > 50.0f) { // he's moving to the right of me at a relatively good speed + // go to my left + VectorMA(movedir, -1, right, movedir); + VectorNormalize(movedir); return qtrue; - } - else if ( dot > -50.0f ) - {//he's moving to the left of me at a relatively good speed - //go to my right - VectorAdd( right, movedir, movedir ); - VectorNormalize( movedir ); + } else if (dot > -50.0f) { // he's moving to the left of me at a relatively good speed + // go to my right + VectorAdd(right, movedir, movedir); + VectorNormalize(movedir); return qtrue; } /* @@ -241,25 +210,25 @@ qboolean NAVNEW_DanceWithBlocker( gentity_t *self, gentity_t *blocker, vec3_t mo NAVNEW_SidestepBlocker ------------------------- */ -qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, vec3_t right ) -{//trace to sides of blocker and see if either is clear - trace_t tr; - vec3_t avoidAngles; - vec3_t avoidRight_dir, avoidLeft_dir, block_pos, mins; - float rightSucc, leftSucc, yaw, avoidRadius, arcAngle; - - VectorCopy( self->r.mins, mins ); +qboolean NAVNEW_SidestepBlocker(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, + vec3_t right) { // trace to sides of blocker and see if either is clear + trace_t tr; + vec3_t avoidAngles; + vec3_t avoidRight_dir, avoidLeft_dir, block_pos, mins; + float rightSucc, leftSucc, yaw, avoidRadius, arcAngle; + + VectorCopy(self->r.mins, mins); mins[2] += STEPSIZE; - //Get the blocked direction - yaw = vectoyaw( blocked_dir ); + // Get the blocked direction + yaw = vectoyaw(blocked_dir); - //Get the avoid radius - avoidRadius = sqrt( ( blocker->r.maxs[0] * blocker->r.maxs[0] ) + ( blocker->r.maxs[1] * blocker->r.maxs[1] ) ) + - sqrt( ( self->r.maxs[0] * self->r.maxs[0] ) + ( self->r.maxs[1] * self->r.maxs[1] ) ); + // Get the avoid radius + avoidRadius = sqrt((blocker->r.maxs[0] * blocker->r.maxs[0]) + (blocker->r.maxs[1] * blocker->r.maxs[1])) + + sqrt((self->r.maxs[0] * self->r.maxs[0]) + (self->r.maxs[1] * self->r.maxs[1])); - //See if we're inside our avoidance radius - arcAngle = ( blocked_dist <= avoidRadius ) ? 135 : ( ( avoidRadius / blocked_dist ) * 90 ); + // See if we're inside our avoidance radius + arcAngle = (blocked_dist <= avoidRadius) ? 135 : ((avoidRadius / blocked_dist) * 90); /* float dot = DotProduct( blocked_dir, right ); @@ -269,95 +238,81 @@ qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blo arcAngle *= -1; */ - VectorClear( avoidAngles ); + VectorClear(avoidAngles); - //need to stop it from ping-ponging, so we have a bit of a debounce time on which side you try - if ( self->NPC->sideStepHoldTime > level.time ) - { - if ( self->NPC->lastSideStepSide == -1 )//left + // need to stop it from ping-ponging, so we have a bit of a debounce time on which side you try + if (self->NPC->sideStepHoldTime > level.time) { + if (self->NPC->lastSideStepSide == -1) // left { arcAngle *= -1; - }//else right - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, movedir, NULL, NULL ); - VectorMA( self->r.currentOrigin, blocked_dist, movedir, block_pos ); - trap->Trace( &tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); - return (tr.fraction==1.0&&!tr.allsolid&&!tr.startsolid); + } // else right + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, movedir, NULL, NULL); + VectorMA(self->r.currentOrigin, blocked_dist, movedir, block_pos); + trap->Trace(&tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); + return (tr.fraction == 1.0 && !tr.allsolid && !tr.startsolid); } - //test right - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, avoidRight_dir, NULL, NULL ); + // test right + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, avoidRight_dir, NULL, NULL); - VectorMA( self->r.currentOrigin, blocked_dist, avoidRight_dir, block_pos ); + VectorMA(self->r.currentOrigin, blocked_dist, avoidRight_dir, block_pos); - trap->Trace( &tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); + trap->Trace(&tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid ) - { - if ( tr.fraction >= 1.0f ) - {//all clear, go for it (favor the right if both are equal) - VectorCopy( avoidRight_dir, movedir ); + if (!tr.allsolid && !tr.startsolid) { + if (tr.fraction >= 1.0f) { // all clear, go for it (favor the right if both are equal) + VectorCopy(avoidRight_dir, movedir); self->NPC->lastSideStepSide = 1; self->NPC->sideStepHoldTime = level.time + 2000; return qtrue; } rightSucc = tr.fraction; - } - else - { + } else { rightSucc = 0.0f; } - //now test left + // now test left arcAngle *= -1; - avoidAngles[YAW] = AngleNormalize360( yaw + arcAngle ); - AngleVectors( avoidAngles, avoidLeft_dir, NULL, NULL ); + avoidAngles[YAW] = AngleNormalize360(yaw + arcAngle); + AngleVectors(avoidAngles, avoidLeft_dir, NULL, NULL); - VectorMA( self->r.currentOrigin, blocked_dist, avoidLeft_dir, block_pos ); + VectorMA(self->r.currentOrigin, blocked_dist, avoidLeft_dir, block_pos); - trap->Trace( &tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask|CONTENTS_BOTCLIP, qfalse, 0, 0 ); + trap->Trace(&tr, self->r.currentOrigin, mins, self->r.maxs, block_pos, self->s.number, self->clipmask | CONTENTS_BOTCLIP, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid ) - { - if ( tr.fraction >= 1.0f ) - {//all clear, go for it (right side would have already succeeded if as good as this) - VectorCopy( avoidLeft_dir, movedir ); + if (!tr.allsolid && !tr.startsolid) { + if (tr.fraction >= 1.0f) { // all clear, go for it (right side would have already succeeded if as good as this) + VectorCopy(avoidLeft_dir, movedir); self->NPC->lastSideStepSide = -1; self->NPC->sideStepHoldTime = level.time + 2000; return qtrue; } leftSucc = tr.fraction; - } - else - { + } else { leftSucc = 0.0f; } - if ( leftSucc == 0.0f && rightSucc == 0.0f ) - {//both sides failed + if (leftSucc == 0.0f && rightSucc == 0.0f) { // both sides failed return qfalse; } - if ( rightSucc*blocked_dist >= avoidRadius || leftSucc*blocked_dist >= avoidRadius ) - {//the traces hit something, but got a relatively good distance - if ( rightSucc >= leftSucc ) - {//favor the right, all things being equal - VectorCopy( avoidRight_dir, movedir ); + if (rightSucc * blocked_dist >= avoidRadius || leftSucc * blocked_dist >= avoidRadius) { // the traces hit something, but got a relatively good distance + if (rightSucc >= leftSucc) { // favor the right, all things being equal + VectorCopy(avoidRight_dir, movedir); self->NPC->lastSideStepSide = 1; self->NPC->sideStepHoldTime = level.time + 2000; - } - else - { - VectorCopy( avoidLeft_dir, movedir ); + } else { + VectorCopy(avoidLeft_dir, movedir); self->NPC->lastSideStepSide = -1; self->NPC->sideStepHoldTime = level.time + 2000; } return qtrue; } - //if neither are enough, we probably can't get around him + // if neither are enough, we probably can't get around him return qfalse; } @@ -366,34 +321,30 @@ qboolean NAVNEW_SidestepBlocker( gentity_t *self, gentity_t *blocker, vec3_t blo NAVNEW_Bypass ------------------------- */ -qboolean NAVNEW_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, qboolean setBlockedInfo ) -{ - vec3_t moveangles, right; +qboolean NAVNEW_Bypass(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir, qboolean setBlockedInfo) { + vec3_t moveangles, right; - //Draw debug info if requested - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, blocker->r.currentOrigin, EDGE_NORMAL ); + // Draw debug info if requested + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, blocker->r.currentOrigin, EDGE_NORMAL); } - vectoangles( movedir, moveangles ); + vectoangles(movedir, moveangles); moveangles[2] = 0; - AngleVectors( moveangles, NULL, right, NULL ); + AngleVectors(moveangles, NULL, right, NULL); - //Check to see what dir the other guy is moving in (if any) and pick the opposite dir - if ( NAVNEW_DanceWithBlocker( self, blocker, movedir, right ) ) - { + // Check to see what dir the other guy is moving in (if any) and pick the opposite dir + if (NAVNEW_DanceWithBlocker(self, blocker, movedir, right)) { return qtrue; } - //Okay, so he's not moving to my side, see which side of him is most clear - if ( NAVNEW_SidestepBlocker( self, blocker, blocked_dir, blocked_dist, movedir, right ) ) - { + // Okay, so he's not moving to my side, see which side of him is most clear + if (NAVNEW_SidestepBlocker(self, blocker, blocked_dir, blocked_dist, movedir, right)) { return qtrue; } - //Neither side is clear, tell him to step aside - NAVNEW_PushBlocker( self, blocker, right, setBlockedInfo ); + // Neither side is clear, tell him to step aside + NAVNEW_PushBlocker(self, blocker, right, setBlockedInfo); return qfalse; } @@ -403,10 +354,9 @@ qboolean NAVNEW_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, NAVNEW_CheckDoubleBlock ------------------------- */ -qboolean NAVNEW_CheckDoubleBlock( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir ) -{ - //Stop double waiting - if ( ( blocker->NPC ) && ( blocker->NPC->blockingEntNum == self->s.number ) ) +qboolean NAVNEW_CheckDoubleBlock(gentity_t *self, gentity_t *blocker, vec3_t blocked_dir) { + // Stop double waiting + if ((blocker->NPC) && (blocker->NPC->blockingEntNum == self->s.number)) return qtrue; return qfalse; @@ -417,40 +367,37 @@ qboolean NAVNEW_CheckDoubleBlock( gentity_t *self, gentity_t *blocker, vec3_t bl NAVNEW_ResolveEntityCollision ------------------------- */ -extern void CalcTeamDoorCenter ( gentity_t *ent, vec3_t center ); -qboolean NAVNEW_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir, qboolean setBlockedInfo ) -{ - vec3_t blocked_dir; +extern void CalcTeamDoorCenter(gentity_t *ent, vec3_t center); +qboolean NAVNEW_ResolveEntityCollision(gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir, qboolean setBlockedInfo) { + vec3_t blocked_dir; float blocked_dist; - //Doors are ignored - if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) - { + // Doors are ignored + if (Q_stricmp(blocker->classname, "func_door") == 0) { vec3_t center; - CalcTeamDoorCenter ( blocker, center ); - if ( DistanceSquared( self->r.currentOrigin, center ) > MIN_DOOR_BLOCK_DIST_SQR ) + CalcTeamDoorCenter(blocker, center); + if (DistanceSquared(self->r.currentOrigin, center) > MIN_DOOR_BLOCK_DIST_SQR) return qtrue; } - VectorSubtract( blocker->r.currentOrigin, self->r.currentOrigin, blocked_dir ); - blocked_dist = VectorNormalize( blocked_dir ); + VectorSubtract(blocker->r.currentOrigin, self->r.currentOrigin, blocked_dir); + blocked_dist = VectorNormalize(blocked_dir); - //Make sure an actual collision is going to happen -// if ( NAVNEW_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) -// return qtrue; + // Make sure an actual collision is going to happen + // if ( NAVNEW_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) + // return qtrue; - //First, attempt to walk around the blocker or shove him out of the way - if ( NAVNEW_Bypass( self, blocker, blocked_dir, blocked_dist, movedir, setBlockedInfo ) ) + // First, attempt to walk around the blocker or shove him out of the way + if (NAVNEW_Bypass(self, blocker, blocked_dir, blocked_dist, movedir, setBlockedInfo)) return qtrue; - //Can't get around him... see if I'm blocking him too... if so, I need to just keep moving? - if ( NAVNEW_CheckDoubleBlock( self, blocker, blocked_dir ) ) + // Can't get around him... see if I'm blocking him too... if so, I need to just keep moving? + if (NAVNEW_CheckDoubleBlock(self, blocker, blocked_dir)) return qtrue; - if ( setBlockedInfo ) - { - //Complain about it if we can - NPC_SetBlocked( self, blocker ); + if (setBlockedInfo) { + // Complain about it if we can + NPC_SetBlocked(self, blocker); } return qfalse; @@ -461,135 +408,117 @@ qboolean NAVNEW_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec NAVNEW_AvoidCollision ------------------------- */ -qboolean NAVNEW_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t *info, qboolean setBlockedInfo, int blockedMovesLimit ) -{ - vec3_t movedir; - vec3_t movepos; - - //Cap our distance - if ( info->distance > MAX_COLL_AVOID_DIST ) - { +qboolean NAVNEW_AvoidCollision(gentity_t *self, gentity_t *goal, navInfo_t *info, qboolean setBlockedInfo, int blockedMovesLimit) { + vec3_t movedir; + vec3_t movepos; + + // Cap our distance + if (info->distance > MAX_COLL_AVOID_DIST) { info->distance = MAX_COLL_AVOID_DIST; } - //Get an end position - VectorMA( self->r.currentOrigin, info->distance, info->direction, movepos ); - VectorCopy( info->direction, movedir ); + // Get an end position + VectorMA(self->r.currentOrigin, info->distance, info->direction, movepos); + VectorCopy(info->direction, movedir); - //Now test against entities - if ( NAV_CheckAhead( self, movepos, &info->trace, CONTENTS_BODY ) == qfalse ) - { - //Get the blocker - info->blocker = &g_entities[ info->trace.entityNum ]; + // Now test against entities + if (NAV_CheckAhead(self, movepos, &info->trace, CONTENTS_BODY) == qfalse) { + // Get the blocker + info->blocker = &g_entities[info->trace.entityNum]; info->flags |= NIF_COLLISION; - //Ok to hit our goal entity - if ( goal == info->blocker ) + // Ok to hit our goal entity + if (goal == info->blocker) return qtrue; - if ( setBlockedInfo ) - { - if ( self->NPC->consecutiveBlockedMoves > blockedMovesLimit ) - { - if ( d_patched.integer ) - {//use patch-style navigation + if (setBlockedInfo) { + if (self->NPC->consecutiveBlockedMoves > blockedMovesLimit) { + if (d_patched.integer) { // use patch-style navigation self->NPC->consecutiveBlockedMoves++; } - NPC_SetBlocked( self, info->blocker ); + NPC_SetBlocked(self, info->blocker); return qfalse; } self->NPC->consecutiveBlockedMoves++; } - //See if we're moving along with them - //if ( NAVNEW_TrueCollision( self, info->blocker, movedir, info->direction ) == qfalse ) + // See if we're moving along with them + // if ( NAVNEW_TrueCollision( self, info->blocker, movedir, info->direction ) == qfalse ) // return qtrue; - //Test for blocking by standing on goal - if ( NAV_TestForBlocked( self, goal, info->blocker, info->distance, &info->flags ) == qtrue ) + // Test for blocking by standing on goal + if (NAV_TestForBlocked(self, goal, info->blocker, info->distance, &info->flags) == qtrue) return qfalse; - //If the above function said we're blocked, don't do the extra checks + // If the above function said we're blocked, don't do the extra checks /* if ( info->flags & NIF_BLOCKED ) return qtrue; */ - //See if we can get that entity to move out of our way - if ( NAVNEW_ResolveEntityCollision( self, info->blocker, movedir, info->pathDirection, setBlockedInfo ) == qfalse ) + // See if we can get that entity to move out of our way + if (NAVNEW_ResolveEntityCollision(self, info->blocker, movedir, info->pathDirection, setBlockedInfo) == qfalse) return qfalse; - VectorCopy( movedir, info->direction ); + VectorCopy(movedir, info->direction); return qtrue; - } - else - { - if ( setBlockedInfo ) - { + } else { + if (setBlockedInfo) { self->NPC->consecutiveBlockedMoves = 0; } } - //Our path is clear, just move there - if ( NAVDEBUG_showCollision ) - { - G_DrawEdge( self->r.currentOrigin, movepos, EDGE_MOVEDIR ); + // Our path is clear, just move there + if (NAVDEBUG_showCollision) { + G_DrawEdge(self->r.currentOrigin, movepos, EDGE_MOVEDIR); } return qtrue; } -qboolean NAVNEW_TestNodeConnectionBlocked( int wp1, int wp2, gentity_t *ignoreEnt, int goalEntNum, qboolean checkWorld, qboolean checkEnts ) -{//see if the direct path between 2 nodes is blocked by architecture or an ent - vec3_t pos1, pos2, mins, maxs; - trace_t trace; - int clipmask = MASK_NPCSOLID|CONTENTS_BOTCLIP; +qboolean NAVNEW_TestNodeConnectionBlocked(int wp1, int wp2, gentity_t *ignoreEnt, int goalEntNum, qboolean checkWorld, + qboolean checkEnts) { // see if the direct path between 2 nodes is blocked by architecture or an ent + vec3_t pos1, pos2, mins, maxs; + trace_t trace; + int clipmask = MASK_NPCSOLID | CONTENTS_BOTCLIP; int ignoreEntNum; vec3_t playerMins, playerMaxs; - if ( !checkWorld && !checkEnts ) - {//duh, nothing to trace against + if (!checkWorld && !checkEnts) { // duh, nothing to trace against return qfalse; } VectorSet(playerMins, -15, -15, DEFAULT_MINS_2); VectorSet(playerMaxs, 15, 15, DEFAULT_MAXS_2); - trap->Nav_GetNodePosition( wp1, pos1 ); - trap->Nav_GetNodePosition( wp2, pos2 ); + trap->Nav_GetNodePosition(wp1, pos1); + trap->Nav_GetNodePosition(wp2, pos2); - if ( !checkWorld ) - { - clipmask &= ~(CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP); + if (!checkWorld) { + clipmask &= ~(CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP); } - if ( !checkEnts ) - { + if (!checkEnts) { clipmask &= ~CONTENTS_BODY; } - if ( ignoreEnt ) - { - VectorCopy( ignoreEnt->r.mins, mins ); - VectorCopy( ignoreEnt->r.maxs, maxs ); + if (ignoreEnt) { + VectorCopy(ignoreEnt->r.mins, mins); + VectorCopy(ignoreEnt->r.maxs, maxs); ignoreEntNum = ignoreEnt->s.number; - } - else - { - VectorCopy( playerMins, mins ); - VectorCopy( playerMaxs, maxs ); + } else { + VectorCopy(playerMins, mins); + VectorCopy(playerMaxs, maxs); ignoreEntNum = ENTITYNUM_NONE; } mins[2] += STEPSIZE; - //don't let box get inverted - if ( mins[2] > maxs[2] ) - { + // don't let box get inverted + if (mins[2] > maxs[2]) { mins[2] = maxs[2]; } - trap->Trace( &trace, pos1, mins, maxs, pos2, ignoreEntNum, clipmask, qfalse, 0, 0 ); - if ( trace.fraction >= 1.0f || trace.entityNum == goalEntNum ) - {//clear or hit goal + trap->Trace(&trace, pos1, mins, maxs, pos2, ignoreEntNum, clipmask, qfalse, 0, 0); + if (trace.fraction >= 1.0f || trace.entityNum == goalEntNum) { // clear or hit goal return qfalse; } - //hit something we weren't supposed to + // hit something we weren't supposed to return qtrue; } /* @@ -597,70 +526,60 @@ qboolean NAVNEW_TestNodeConnectionBlocked( int wp1, int wp2, gentity_t *ignoreEn NAVNEW_MoveToGoal ------------------------- */ -int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t *info ) -{ - int bestNode = WAYPOINT_NONE; - qboolean foundClearPath = qfalse; - vec3_t origin; - navInfo_t tempInfo; - qboolean setBlockedInfo = qtrue; - qboolean /*inBestWP, */inGoalWP/*, goalWPFailed = qfalse*/; - int numTries = 0; - - memcpy( &tempInfo, info, sizeof( tempInfo ) ); - - //Must have a goal entity to move there - if( self->NPC->goalEntity == NULL ) +int NAVNEW_MoveToGoal(gentity_t *self, navInfo_t *info) { + int bestNode = WAYPOINT_NONE; + qboolean foundClearPath = qfalse; + vec3_t origin; + navInfo_t tempInfo; + qboolean setBlockedInfo = qtrue; + qboolean /*inBestWP, */ inGoalWP /*, goalWPFailed = qfalse*/; + int numTries = 0; + + memcpy(&tempInfo, info, sizeof(tempInfo)); + + // Must have a goal entity to move there + if (self->NPC->goalEntity == NULL) return WAYPOINT_NONE; - if ( self->waypoint == WAYPOINT_NONE && self->noWaypointTime > level.time ) - {//didn't have a valid one in about the past second, don't look again just yet + if (self->waypoint == WAYPOINT_NONE && self->noWaypointTime > level.time) { // didn't have a valid one in about the past second, don't look again just yet return WAYPOINT_NONE; } - if ( self->NPC->goalEntity->waypoint == WAYPOINT_NONE && self->NPC->goalEntity->noWaypointTime > level.time ) - {//didn't have a valid one in about the past second, don't look again just yet + if (self->NPC->goalEntity->waypoint == WAYPOINT_NONE && + self->NPC->goalEntity->noWaypointTime > level.time) { // didn't have a valid one in about the past second, don't look again just yet return WAYPOINT_NONE; } - if ( self->noWaypointTime > level.time && - self->NPC->goalEntity->noWaypointTime > level.time ) - {//just use current waypoints - bestNode = trap->Nav_GetBestNodeAltRoute2( self->waypoint, self->NPC->goalEntity->waypoint, bestNode ); - } - //FIXME!!!!: this is making them wiggle back and forth between waypoints - else if ( (bestNode = trap->Nav_GetBestPathBetweenEnts( (sharedEntity_t *)self, (sharedEntity_t *)self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( self, qtrue ) ) - {//one of us didn't have a valid waypoint! - if ( self->waypoint == NODE_NONE ) - {//don't even try to find one again for a bit - self->noWaypointTime = level.time + Q_irand( 500, 1500 ); + if (self->noWaypointTime > level.time && self->NPC->goalEntity->noWaypointTime > level.time) { // just use current waypoints + bestNode = trap->Nav_GetBestNodeAltRoute2(self->waypoint, self->NPC->goalEntity->waypoint, bestNode); + } + // FIXME!!!!: this is making them wiggle back and forth between waypoints + else if ((bestNode = trap->Nav_GetBestPathBetweenEnts((sharedEntity_t *)self, (sharedEntity_t *)self->NPC->goalEntity, NF_CLEAR_PATH)) == + NODE_NONE) //! NAVNEW_GetWaypoints( self, qtrue ) ) + { // one of us didn't have a valid waypoint! + if (self->waypoint == NODE_NONE) { // don't even try to find one again for a bit + self->noWaypointTime = level.time + Q_irand(500, 1500); } - if ( self->NPC->goalEntity->waypoint == NODE_NONE ) - {//don't even try to find one again for a bit - self->NPC->goalEntity->noWaypointTime = level.time + Q_irand( 500, 1500 ); + if (self->NPC->goalEntity->waypoint == NODE_NONE) { // don't even try to find one again for a bit + self->NPC->goalEntity->noWaypointTime = level.time + Q_irand(500, 1500); } return WAYPOINT_NONE; - } - else - { - if ( self->NPC->goalEntity->noWaypointTime < level.time ) - { - self->NPC->goalEntity->noWaypointTime = level.time + Q_irand( 500, 1500 ); + } else { + if (self->NPC->goalEntity->noWaypointTime < level.time) { + self->NPC->goalEntity->noWaypointTime = level.time + Q_irand(500, 1500); } } - while( !foundClearPath ) - { - /*inBestWP = */inGoalWP = qfalse; + while (!foundClearPath) { + /*inBestWP = */ inGoalWP = qfalse; /* bestNode = trap->Nav_GetBestNodeAltRoute( self->waypoint, self->NPC->goalEntity->waypoint, bestNode ); */ - if ( bestNode == WAYPOINT_NONE ) - { + if (bestNode == WAYPOINT_NONE) { goto failed; } - //see if we can get directly to the next node off bestNode en route to goal's node... - //NOTE: shouldn't be necc. now + // see if we can get directly to the next node off bestNode en route to goal's node... + // NOTE: shouldn't be necc. now /* int oldBestNode = bestNode; bestNode = NAV_TestBestNode( self, self->waypoint, bestNode, qtrue );//, self->NPC->goalEntity->waypoint );// @@ -674,7 +593,7 @@ int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t *info ) } } */ - trap->Nav_GetNodePosition( bestNode, origin ); + trap->Nav_GetNodePosition(bestNode, origin); /* if ( !goalWPFailed ) {//we haven't already tried to go straight to goal or goal's wp @@ -692,179 +611,149 @@ int NAVNEW_MoveToGoal( gentity_t *self, navInfo_t *info ) } } */ - if ( !inGoalWP ) - {//not heading straight for goal - if ( bestNode == self->waypoint ) - {//we know it's clear or architecture - //trap->Nav_GetNodePosition( self->waypoint, origin ); + if (!inGoalWP) { // not heading straight for goal + if (bestNode == self->waypoint) { // we know it's clear or architecture + // trap->Nav_GetNodePosition( self->waypoint, origin ); /* if ( NAV_HitNavGoal( self->r.currentOrigin, self->r.mins, self->r.maxs, origin, trap->Nav_GetNodeRadius( bestNode ), FlyingCreature( self ) ) ) {//we're in the wp we're heading for already inBestWP = qtrue; } */ - } - else - {//heading to an edge off our confirmed clear waypoint... make sure it's clear - //it it's not, bestNode will fall back to our waypoint + } else { // heading to an edge off our confirmed clear waypoint... make sure it's clear + // it it's not, bestNode will fall back to our waypoint int oldBestNode = bestNode; - bestNode = NAV_TestBestNode( self, self->waypoint, bestNode, qtrue ); - if ( bestNode == self->waypoint ) - {//we fell back to our waypoint, reset the origin + bestNode = NAV_TestBestNode(self, self->waypoint, bestNode, qtrue); + if (bestNode == self->waypoint) { // we fell back to our waypoint, reset the origin self->NPC->aiFlags |= NPCAI_BLOCKED; - trap->Nav_GetNodePosition( oldBestNode, NPCS.NPCInfo->blockedDest ); - trap->Nav_GetNodePosition( bestNode, origin ); + trap->Nav_GetNodePosition(oldBestNode, NPCS.NPCInfo->blockedDest); + trap->Nav_GetNodePosition(bestNode, origin); } } } - //Com_Printf( "goalwp = %d, mywp = %d, node = %d, origin = %s\n", self->NPC->goalEntity->waypoint, self->waypoint, bestNode, vtos(origin) ); + // Com_Printf( "goalwp = %d, mywp = %d, node = %d, origin = %s\n", self->NPC->goalEntity->waypoint, self->waypoint, bestNode, vtos(origin) ); - memcpy( &tempInfo, info, sizeof( tempInfo ) ); - VectorSubtract( origin, self->r.currentOrigin, tempInfo.direction ); - VectorNormalize( tempInfo.direction ); + memcpy(&tempInfo, info, sizeof(tempInfo)); + VectorSubtract(origin, self->r.currentOrigin, tempInfo.direction); + VectorNormalize(tempInfo.direction); - //NOTE: One very important thing NAVNEW_AvoidCollision does is + // NOTE: One very important thing NAVNEW_AvoidCollision does is // it actually CHANGES the value of "direction" - it changes it to // whatever dir you need to go in to avoid the obstacle... - foundClearPath = NAVNEW_AvoidCollision( self, self->NPC->goalEntity, &tempInfo, setBlockedInfo, 5 ); - - if ( !foundClearPath ) - {//blocked by an ent - if ( inGoalWP ) - {//we were heading straight for the goal, head for the goal's wp instead - trap->Nav_GetNodePosition( bestNode, origin ); - foundClearPath = NAVNEW_AvoidCollision( self, self->NPC->goalEntity, &tempInfo, setBlockedInfo, 5 ); + foundClearPath = NAVNEW_AvoidCollision(self, self->NPC->goalEntity, &tempInfo, setBlockedInfo, 5); + + if (!foundClearPath) { // blocked by an ent + if (inGoalWP) { // we were heading straight for the goal, head for the goal's wp instead + trap->Nav_GetNodePosition(bestNode, origin); + foundClearPath = NAVNEW_AvoidCollision(self, self->NPC->goalEntity, &tempInfo, setBlockedInfo, 5); } } - if ( foundClearPath ) - {//clear! - //If we got set to blocked, clear it - NPC_ClearBlocked( self ); - //Take the dir - memcpy( info, &tempInfo, sizeof( *info ) ); - if ( self->s.weapon == WP_SABER ) - {//jedi - if ( info->direction[2] * info->distance > 64 ) - { + if (foundClearPath) { // clear! + // If we got set to blocked, clear it + NPC_ClearBlocked(self); + // Take the dir + memcpy(info, &tempInfo, sizeof(*info)); + if (self->s.weapon == WP_SABER) { // jedi + if (info->direction[2] * info->distance > 64) { self->NPC->aiFlags |= NPCAI_BLOCKED; - VectorCopy( origin, NPCS.NPCInfo->blockedDest ); + VectorCopy(origin, NPCS.NPCInfo->blockedDest); goto failed; } } - } - else - {//blocked by ent! - if ( setBlockedInfo ) - { + } else { // blocked by ent! + if (setBlockedInfo) { self->NPC->aiFlags |= NPCAI_BLOCKED; - trap->Nav_GetNodePosition( bestNode, NPCS.NPCInfo->blockedDest ); + trap->Nav_GetNodePosition(bestNode, NPCS.NPCInfo->blockedDest); } - //Only set blocked info first time + // Only set blocked info first time setBlockedInfo = qfalse; - if ( inGoalWP ) - {//we headed for our goal and failed and our goal's WP and failed - if ( self->waypoint == self->NPC->goalEntity->waypoint ) - {//our waypoint is our goal's waypoint, nothing we can do - //remember that this node is blocked - trap->Nav_AddFailedNode( (sharedEntity_t *)self, self->waypoint ); + if (inGoalWP) { // we headed for our goal and failed and our goal's WP and failed + if (self->waypoint == self->NPC->goalEntity->waypoint) { // our waypoint is our goal's waypoint, nothing we can do + // remember that this node is blocked + trap->Nav_AddFailedNode((sharedEntity_t *)self, self->waypoint); goto failed; - } - else - {//try going for our waypoint this time + } else { // try going for our waypoint this time inGoalWP = qfalse; } - } - else if ( bestNode != self->waypoint ) - {//we headed toward our next waypoint (instead of our waypoint) and failed - if ( d_altRoutes.integer ) - {//mark this edge failed and try our waypoint - //NOTE: don't assume there is something blocking the direct path + } else if (bestNode != self->waypoint) { // we headed toward our next waypoint (instead of our waypoint) and failed + if (d_altRoutes.integer) { // mark this edge failed and try our waypoint + // NOTE: don't assume there is something blocking the direct path // between my waypoint and the bestNode... I could be off // that path because of collision avoidance... - if ( d_patched.integer &&//use patch-style navigation - ( !trap->Nav_NodesAreNeighbors( self->waypoint, bestNode ) - || NAVNEW_TestNodeConnectionBlocked( self->waypoint, bestNode, self, self->NPC->goalEntity->s.number, qfalse, qtrue ) ) ) - {//the direct path between these 2 nodes is blocked by an ent - trap->Nav_AddFailedEdge( self->s.number, self->waypoint, bestNode ); + if (d_patched.integer && // use patch-style navigation + (!trap->Nav_NodesAreNeighbors(self->waypoint, bestNode) || + NAVNEW_TestNodeConnectionBlocked(self->waypoint, bestNode, self, self->NPC->goalEntity->s.number, qfalse, + qtrue))) { // the direct path between these 2 nodes is blocked by an ent + trap->Nav_AddFailedEdge(self->s.number, self->waypoint, bestNode); } bestNode = self->waypoint; - } - else - { - //we should stop + } else { + // we should stop goto failed; } - } - else - {//we headed for *our* waypoint and couldn't get to it - if ( d_altRoutes.integer ) - { - //remember that this node is blocked - trap->Nav_AddFailedNode( (sharedEntity_t *)self, self->waypoint ); - //Now we should get our waypoints again - //FIXME: cache the trace-data for subsequent calls as only the route info would have changed - //if ( (bestNode = trap->Nav_GetBestPathBetweenEnts( self, self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( self, qfalse ) ) - {//one of our waypoints is WAYPOINT_NONE now + } else { // we headed for *our* waypoint and couldn't get to it + if (d_altRoutes.integer) { + // remember that this node is blocked + trap->Nav_AddFailedNode((sharedEntity_t *)self, self->waypoint); + // Now we should get our waypoints again + // FIXME: cache the trace-data for subsequent calls as only the route info would have changed + // if ( (bestNode = trap->Nav_GetBestPathBetweenEnts( self, self->NPC->goalEntity, NF_CLEAR_PATH )) == NODE_NONE )//!NAVNEW_GetWaypoints( + // self, qfalse ) ) + { // one of our waypoints is WAYPOINT_NONE now goto failed; } - } - else - { - //we should stop + } else { + // we should stop goto failed; } } - if ( ++numTries >= 10 ) - { + if (++numTries >= 10) { goto failed; } } } -//finish: - //Draw any debug info, if requested - if ( NAVDEBUG_showEnemyPath ) - { - vec3_t dest, start; + // finish: + // Draw any debug info, if requested + if (NAVDEBUG_showEnemyPath) { + vec3_t dest, start; - //Get the positions - trap->Nav_GetNodePosition( self->NPC->goalEntity->waypoint, dest ); - trap->Nav_GetNodePosition( bestNode, start ); + // Get the positions + trap->Nav_GetNodePosition(self->NPC->goalEntity->waypoint, dest); + trap->Nav_GetNodePosition(bestNode, start); - //Draw the route - G_DrawNode( start, NODE_START ); - if ( bestNode != self->waypoint ) - { - vec3_t wpPos; - trap->Nav_GetNodePosition( self->waypoint, wpPos ); - G_DrawNode( wpPos, NODE_NAVGOAL ); + // Draw the route + G_DrawNode(start, NODE_START); + if (bestNode != self->waypoint) { + vec3_t wpPos; + trap->Nav_GetNodePosition(self->waypoint, wpPos); + G_DrawNode(wpPos, NODE_NAVGOAL); } - G_DrawNode( dest, NODE_GOAL ); - G_DrawEdge( dest, self->NPC->goalEntity->r.currentOrigin, EDGE_PATH ); - G_DrawNode( self->NPC->goalEntity->r.currentOrigin, NODE_GOAL ); - trap->Nav_ShowPath( bestNode, self->NPC->goalEntity->waypoint ); + G_DrawNode(dest, NODE_GOAL); + G_DrawEdge(dest, self->NPC->goalEntity->r.currentOrigin, EDGE_PATH); + G_DrawNode(self->NPC->goalEntity->r.currentOrigin, NODE_GOAL); + trap->Nav_ShowPath(bestNode, self->NPC->goalEntity->waypoint); } self->NPC->shoveCount = 0; - //let me keep this waypoint for a while - if ( self->noWaypointTime < level.time ) - { - self->noWaypointTime = level.time + Q_irand( 500, 1500 ); + // let me keep this waypoint for a while + if (self->noWaypointTime < level.time) { + self->noWaypointTime = level.time + Q_irand(500, 1500); } return bestNode; failed: - //FIXME: What we should really do here is have a list of the goal's and our + // FIXME: What we should really do here is have a list of the goal's and our // closest clearpath waypoints, ranked. If the first set fails, try the rest // until there are no alternatives. - trap->Nav_GetNodePosition( self->waypoint, origin ); + trap->Nav_GetNodePosition(self->waypoint, origin); - //do this to avoid ping-ponging? + // do this to avoid ping-ponging? return WAYPOINT_NONE; /* //this was causing ping-ponging diff --git a/codemp/game/g_object.c b/codemp/game/g_object.c index 6f6c3a7aaa..03524ebb0e 100644 --- a/codemp/game/g_object.c +++ b/codemp/game/g_object.c @@ -22,10 +22,10 @@ along with this program; if not, see . #include "g_local.h" -extern void G_MoverTouchPushTriggers( gentity_t *ent, vec3_t oldOrg ); -void G_StopObjectMoving( gentity_t *object ); +extern void G_MoverTouchPushTriggers(gentity_t *ent, vec3_t oldOrg); +void G_StopObjectMoving(gentity_t *object); -void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); +void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope); /* ================ @@ -33,38 +33,37 @@ G_BounceObject ================ */ -void G_BounceObject( gentity_t *ent, trace_t *trace ) -{ - vec3_t velocity; - float dot, bounceFactor; - int hitTime; +void G_BounceObject(gentity_t *ent, trace_t *trace) { + vec3_t velocity; + float dot, bounceFactor; + int hitTime; // reflect the velocity on the trace plane - hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction; - BG_EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity ); - dot = DotProduct( velocity, trace->plane.normal ); -// bounceFactor = 60/ent->mass; // NOTENOTE Mass is not yet implemented + hitTime = level.previousTime + (level.time - level.previousTime) * trace->fraction; + BG_EvaluateTrajectoryDelta(&ent->s.pos, hitTime, velocity); + dot = DotProduct(velocity, trace->plane.normal); + // bounceFactor = 60/ent->mass; // NOTENOTE Mass is not yet implemented bounceFactor = 1.0f; - if ( bounceFactor > 1.0f ) - { + if (bounceFactor > 1.0f) { bounceFactor = 1.0f; } - VectorMA( velocity, -2*dot*bounceFactor, trace->plane.normal, ent->s.pos.trDelta ); + VectorMA(velocity, -2 * dot * bounceFactor, trace->plane.normal, ent->s.pos.trDelta); - //FIXME: customized or material-based impact/bounce sounds - if ( ent->flags & FL_BOUNCE_HALF ) - { - VectorScale( ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta ); + // FIXME: customized or material-based impact/bounce sounds + if (ent->flags & FL_BOUNCE_HALF) { + VectorScale(ent->s.pos.trDelta, 0.5, ent->s.pos.trDelta); // check for stop - if ( ((trace->plane.normal[2] > 0.7&&g_gravity.value>0) || (trace->plane.normal[2]<-0.7&&g_gravity.value<0)) && ((ent->s.pos.trDelta[2]<40&&g_gravity.value>0)||(ent->s.pos.trDelta[2]>-40&&g_gravity.value<0)) ) //this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 + if (((trace->plane.normal[2] > 0.7 && g_gravity.value > 0) || (trace->plane.normal[2] < -0.7 && g_gravity.value < 0)) && + ((ent->s.pos.trDelta[2] < 40 && g_gravity.value > 0) || + (ent->s.pos.trDelta[2] > -40 && g_gravity.value < 0))) // this can happen even on very slightly sloped walls, so changed it from > 0 to > 0.7 { - //G_SetOrigin( ent, trace->endpos ); - //ent->nextthink = level.time + 500; + // G_SetOrigin( ent, trace->endpos ); + // ent->nextthink = level.time + 500; ent->s.apos.trType = TR_STATIONARY; - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); - VectorCopy( trace->endpos, ent->r.currentOrigin ); - VectorCopy( trace->endpos, ent->s.pos.trBase ); + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); + VectorCopy(trace->endpos, ent->r.currentOrigin); + VectorCopy(trace->endpos, ent->s.pos.trBase); ent->s.pos.trTime = level.time; return; } @@ -73,14 +72,13 @@ void G_BounceObject( gentity_t *ent, trace_t *trace ) // NEW--It would seem that we want to set our trBase to the trace endpos // and set the trTime to the actual time of impact.... // FIXME: Should we still consider adding the normal though?? - VectorCopy( trace->endpos, ent->r.currentOrigin ); + VectorCopy(trace->endpos, ent->r.currentOrigin); ent->s.pos.trTime = hitTime; - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); - VectorCopy( trace->plane.normal, ent->pos1 );//??? + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); + VectorCopy(trace->plane.normal, ent->pos1); //??? } - /* ================ G_RunObject @@ -89,54 +87,49 @@ G_RunObject TODO: When free-floating in air, apply some friction to your trDelta (based on mass?) ================ */ -extern void DoImpact( gentity_t *self, gentity_t *other, qboolean damageSelf ); -extern void pitch_roll_for_slope( gentity_t *forwhom, vec3_t pass_slope ); -void G_RunObject( gentity_t *ent ) -{ - vec3_t origin, oldOrg; - trace_t tr; - gentity_t *traceEnt = NULL; - - //FIXME: floaters need to stop floating up after a while, even if gravity stays negative? - if ( ent->s.pos.trType == TR_STATIONARY )//g_gravity.value <= 0 && +extern void DoImpact(gentity_t *self, gentity_t *other, qboolean damageSelf); +extern void pitch_roll_for_slope(gentity_t *forwhom, vec3_t pass_slope); +void G_RunObject(gentity_t *ent) { + vec3_t origin, oldOrg; + trace_t tr; + gentity_t *traceEnt = NULL; + + // FIXME: floaters need to stop floating up after a while, even if gravity stays negative? + if (ent->s.pos.trType == TR_STATIONARY) // g_gravity.value <= 0 && { ent->s.pos.trType = TR_GRAVITY; - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); - ent->s.pos.trTime = level.previousTime;//?necc? - if ( !g_gravity.value ) - { + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); + ent->s.pos.trTime = level.previousTime; //?necc? + if (!g_gravity.value) { ent->s.pos.trDelta[2] += 100; } } ent->nextthink = level.time + FRAMETIME; - VectorCopy( ent->r.currentOrigin, oldOrg ); + VectorCopy(ent->r.currentOrigin, oldOrg); // get current position - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); - //Get current angles? - BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->r.currentAngles ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); + // Get current angles? + BG_EvaluateTrajectory(&ent->s.apos, level.time, ent->r.currentAngles); - if ( VectorCompare( ent->r.currentOrigin, origin ) ) - {//error - didn't move at all! + if (VectorCompare(ent->r.currentOrigin, origin)) { // error - didn't move at all! return; } // trace a line from the previous position to the current position, // ignoring interactions with the missile owner - trap->Trace( &tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ent->parent ? ent->parent->s.number : ent->s.number, ent->clipmask, qfalse, 0, 0 ); + trap->Trace(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ent->parent ? ent->parent->s.number : ent->s.number, ent->clipmask, qfalse, 0, 0); - if ( !tr.startsolid && !tr.allsolid && tr.fraction ) - { - VectorCopy( tr.endpos, ent->r.currentOrigin ); - trap->LinkEntity( (sharedEntity_t *)ent ); - } - else - //if ( tr.startsolid ) + if (!tr.startsolid && !tr.allsolid && tr.fraction) { + VectorCopy(tr.endpos, ent->r.currentOrigin); + trap->LinkEntity((sharedEntity_t *)ent); + } else + // if ( tr.startsolid ) { tr.fraction = 0; } - G_MoverTouchPushTriggers( ent, oldOrg ); + G_MoverTouchPushTriggers(ent, oldOrg); /* if ( !(ent->s.eFlags & EF_TELEPORT_BIT) && !(ent->svFlags & SVF_NO_TELEPORT) ) { @@ -152,122 +145,99 @@ void G_RunObject( gentity_t *ent ) } */ - if ( tr.fraction == 1 ) - { - if ( g_gravity.value <= 0 ) - { - if ( ent->s.apos.trType == TR_STATIONARY ) - { - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); + if (tr.fraction == 1) { + if (g_gravity.value <= 0) { + if (ent->s.apos.trType == TR_STATIONARY) { + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); ent->s.apos.trType = TR_LINEAR; - ent->s.apos.trDelta[1] = flrand( -300, 300 ); - ent->s.apos.trDelta[0] = flrand( -10, 10 ); - ent->s.apos.trDelta[2] = flrand( -10, 10 ); + ent->s.apos.trDelta[1] = flrand(-300, 300); + ent->s.apos.trDelta[0] = flrand(-10, 10); + ent->s.apos.trDelta[2] = flrand(-10, 10); ent->s.apos.trTime = level.time; } } - //friction in zero-G - if ( !g_gravity.value ) - { + // friction in zero-G + if (!g_gravity.value) { float friction = 0.975f; - //friction -= ent->mass/1000.0f; - if ( friction < 0.1 ) - { + // friction -= ent->mass/1000.0f; + if (friction < 0.1) { friction = 0.1f; } - VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta ); - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); + VectorScale(ent->s.pos.trDelta, friction, ent->s.pos.trDelta); + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } return; } - //hit something + // hit something - //Do impact damage + // Do impact damage traceEnt = &g_entities[tr.entityNum]; - if ( tr.fraction || (traceEnt && traceEnt->takedamage) ) - { - if ( !VectorCompare( ent->r.currentOrigin, oldOrg ) ) - {//moved and impacted - if ( (traceEnt && traceEnt->takedamage) ) - {//hurt someone -// G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHurt.wav" ) ); + if (tr.fraction || (traceEnt && traceEnt->takedamage)) { + if (!VectorCompare(ent->r.currentOrigin, oldOrg)) { // moved and impacted + if ((traceEnt && traceEnt->takedamage)) { // hurt someone + // G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHurt.wav" ) ); } -// G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHit.wav" ) ); + // G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectHit.wav" ) ); } - if (ent->s.weapon != WP_SABER) - { - DoImpact( ent, traceEnt, qtrue ); + if (ent->s.weapon != WP_SABER) { + DoImpact(ent, traceEnt, qtrue); } } - if ( !ent || (ent->takedamage&&ent->health <= 0) ) - {//been destroyed by impact - //chunks? -// G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectBreak.wav" ) ); + if (!ent || (ent->takedamage && ent->health <= 0)) { // been destroyed by impact + // chunks? + // G_Sound( ent, G_SoundIndex( "sound/movers/objects/objectBreak.wav" ) ); return; } - //do impact physics - if ( ent->s.pos.trType == TR_GRAVITY )//tr.fraction < 1.0 && - {//FIXME: only do this if no trDelta - if ( g_gravity.value <= 0 || tr.plane.normal[2] < 0.7 ) - { - if ( ent->flags&(FL_BOUNCE|FL_BOUNCE_HALF) ) - { - if ( tr.fraction <= 0.0f ) - { - VectorCopy( tr.endpos, ent->r.currentOrigin ); - VectorCopy( tr.endpos, ent->s.pos.trBase ); - VectorClear( ent->s.pos.trDelta ); + // do impact physics + if (ent->s.pos.trType == TR_GRAVITY) // tr.fraction < 1.0 && + { // FIXME: only do this if no trDelta + if (g_gravity.value <= 0 || tr.plane.normal[2] < 0.7) { + if (ent->flags & (FL_BOUNCE | FL_BOUNCE_HALF)) { + if (tr.fraction <= 0.0f) { + VectorCopy(tr.endpos, ent->r.currentOrigin); + VectorCopy(tr.endpos, ent->s.pos.trBase); + VectorClear(ent->s.pos.trDelta); ent->s.pos.trTime = level.time; + } else { + G_BounceObject(ent, &tr); } - else - { - G_BounceObject( ent, &tr ); - } - } - else - {//slide down? - //FIXME: slide off the slope + } else { // slide down? + // FIXME: slide off the slope } - } - else - { + } else { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->r.currentAngles[0] = 0;//FIXME: match to slope - //ent->r.currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); - //okay, we hit the floor, might as well stop or prediction will - //make us go through the floor! - //FIXME: this means we can't fall if something is pulled out from under us... - G_StopObjectMoving( ent ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->r.currentAngles[0] = 0;//FIXME: match to slope + // ent->r.currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); + // okay, we hit the floor, might as well stop or prediction will + // make us go through the floor! + // FIXME: this means we can't fall if something is pulled out from under us... + G_StopObjectMoving(ent); } - } - else if (ent->s.weapon != WP_SABER) - { + } else if (ent->s.weapon != WP_SABER) { ent->s.apos.trType = TR_STATIONARY; - pitch_roll_for_slope( ent, tr.plane.normal ); - //ent->r.currentAngles[0] = 0;//FIXME: match to slope - //ent->r.currentAngles[2] = 0;//FIXME: match to slope - VectorCopy( ent->r.currentAngles, ent->s.apos.trBase ); + pitch_roll_for_slope(ent, tr.plane.normal); + // ent->r.currentAngles[0] = 0;//FIXME: match to slope + // ent->r.currentAngles[2] = 0;//FIXME: match to slope + VectorCopy(ent->r.currentAngles, ent->s.apos.trBase); } - //call touch func - ent->touch( ent, &g_entities[tr.entityNum], &tr ); + // call touch func + ent->touch(ent, &g_entities[tr.entityNum], &tr); } - -void G_StopObjectMoving( gentity_t *object ) -{ +void G_StopObjectMoving(gentity_t *object) { object->s.pos.trType = TR_STATIONARY; - VectorCopy( object->r.currentOrigin, object->s.origin ); - VectorCopy( object->r.currentOrigin, object->s.pos.trBase ); - VectorClear( object->s.pos.trDelta ); + VectorCopy(object->r.currentOrigin, object->s.origin); + VectorCopy(object->r.currentOrigin, object->s.pos.trBase); + VectorClear(object->s.pos.trDelta); /* //Stop spinning @@ -278,14 +248,13 @@ void G_StopObjectMoving( gentity_t *object ) */ } -void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t trType ) -{ - VectorNormalize (dir); +void G_StartObjectMoving(gentity_t *object, vec3_t dir, float speed, trType_t trType) { + VectorNormalize(dir); - //object->s.eType = ET_GENERAL; + // object->s.eType = ET_GENERAL; object->s.pos.trType = trType; - VectorCopy( object->r.currentOrigin, object->s.pos.trBase ); - VectorScale(dir, speed, object->s.pos.trDelta ); + VectorCopy(object->r.currentOrigin, object->s.pos.trBase); + VectorScale(dir, speed, object->s.pos.trDelta); object->s.pos.trTime = level.time; /* @@ -296,13 +265,10 @@ void G_StartObjectMoving( gentity_t *object, vec3_t dir, float speed, trType_t t object->s.apos.trTime = level.time; */ - //FIXME: make these objects go through G_RunObject automatically, like missiles do - if ( object->think == NULL ) - { + // FIXME: make these objects go through G_RunObject automatically, like missiles do + if (object->think == NULL) { object->nextthink = level.time + FRAMETIME; object->think = G_RunObject; - } - else - {//You're responsible for calling RunObject + } else { // You're responsible for calling RunObject } } diff --git a/codemp/game/g_saga.c b/codemp/game/g_saga.c index ce905adb37..435e1b3d60 100644 --- a/codemp/game/g_saga.c +++ b/codemp/game/g_saga.c @@ -34,68 +34,60 @@ along with this program; if not, see . #define SIEGEITEM_STARTOFFRADAR 8 -static char team1[512]; -static char team2[512]; +static char team1[512]; +static char team2[512]; -siegePers_t g_siegePersistant = {qfalse, 0, 0}; +siegePers_t g_siegePersistant = {qfalse, 0, 0}; -int imperial_goals_required = 0; -int imperial_goals_completed = 0; -int rebel_goals_required = 0; -int rebel_goals_completed = 0; +int imperial_goals_required = 0; +int imperial_goals_completed = 0; +int rebel_goals_required = 0; +int rebel_goals_completed = 0; -int imperial_time_limit = 0; -int rebel_time_limit = 0; +int imperial_time_limit = 0; +int rebel_time_limit = 0; -int gImperialCountdown = 0; -int gRebelCountdown = 0; +int gImperialCountdown = 0; +int gRebelCountdown = 0; -int rebel_attackers = 0; -int imperial_attackers = 0; +int rebel_attackers = 0; +int imperial_attackers = 0; -qboolean gSiegeRoundBegun = qfalse; -qboolean gSiegeRoundEnded = qfalse; -int gSiegeRoundWinningTeam = 0; -int gSiegeBeginTime = Q3_INFINITE; +qboolean gSiegeRoundBegun = qfalse; +qboolean gSiegeRoundEnded = qfalse; +int gSiegeRoundWinningTeam = 0; +int gSiegeBeginTime = Q3_INFINITE; -int g_preroundState = 0; //default to starting as spec (1 is starting ingame) +int g_preroundState = 0; // default to starting as spec (1 is starting ingame) -void LogExit( const char *string ); +void LogExit(const char *string); void SetTeamQuick(gentity_t *ent, int team, qboolean doBegin); static char gParseObjectives[MAX_SIEGE_INFO_SIZE]; static char gObjectiveCfgStr[1024]; -//go through all classes on a team and register their -//weapons and items for precaching. -void G_SiegeRegisterWeaponsAndHoldables(int team) -{ +// go through all classes on a team and register their +// weapons and items for precaching. +void G_SiegeRegisterWeaponsAndHoldables(int team) { siegeTeam_t *stm = BG_SiegeFindThemeForTeam(team); - if (stm) - { + if (stm) { int i = 0; siegeClass_t *scl; - while (i < stm->numClasses) - { + while (i < stm->numClasses) { scl = stm->classes[i]; - if (scl) - { + if (scl) { int j = 0; - while (j < WP_NUM_WEAPONS) - { - if (scl->weapons & (1 << j)) - { //we use this weapon so register it. + while (j < WP_NUM_WEAPONS) { + if (scl->weapons & (1 << j)) { // we use this weapon so register it. RegisterItem(BG_FindItemForWeapon(j)); } j++; } j = 0; - while (j < HI_NUM_HOLDABLE) - { - if (scl->invenItems & (1 << j)) - { //we use this item so register it. + while (j < HI_NUM_HOLDABLE) { + if (scl->invenItems & (1 << j)) { // we use this item so register it. RegisterItem(BG_FindItemForHoldable(j)); } j++; @@ -106,66 +98,54 @@ void G_SiegeRegisterWeaponsAndHoldables(int team) } } -//tell clients that this team won and print it on their scoreboard for intermission -//or whatever. -void SiegeSetCompleteData(int team) -{ - trap->SetConfigstring(CS_SIEGE_WINTEAM, va("%i", team)); -} +// tell clients that this team won and print it on their scoreboard for intermission +// or whatever. +void SiegeSetCompleteData(int team) { trap->SetConfigstring(CS_SIEGE_WINTEAM, va("%i", team)); } -void InitSiegeMode(void) -{ - vmCvar_t mapname; - char levelname[512]; - char teamIcon[128]; - char goalreq[64]; - char teams[2048]; +void InitSiegeMode(void) { + vmCvar_t mapname; + char levelname[512]; + char teamIcon[128]; + char goalreq[64]; + char teams[2048]; static char objective[MAX_SIEGE_INFO_SIZE]; - char objecStr[8192]; - int len = 0; - int i = 0; -// int j = 0; - int objectiveNumTeam1 = 0; - int objectiveNumTeam2 = 0; - fileHandle_t f; + char objecStr[8192]; + int len = 0; + int i = 0; + // int j = 0; + int objectiveNumTeam1 = 0; + int objectiveNumTeam2 = 0; + fileHandle_t f; objective[0] = '\0'; - if (level.gametype != GT_SIEGE) - { + if (level.gametype != GT_SIEGE) { goto failure; } - //reset + // reset SiegeSetCompleteData(0); - //get pers data in case it existed from last level - if (g_siegeTeamSwitch.integer) - { + // get pers data in case it existed from last level + if (g_siegeTeamSwitch.integer) { trap->SiegePersGet(&g_siegePersistant); - if (g_siegePersistant.beatingTime) - { + if (g_siegePersistant.beatingTime) { trap->SetConfigstring(CS_SIEGE_TIMEOVERRIDE, va("%i", g_siegePersistant.lastTime)); - } - else - { + } else { trap->SetConfigstring(CS_SIEGE_TIMEOVERRIDE, "0"); } - } - else - { //hmm, ok, nothing. + } else { // hmm, ok, nothing. trap->SetConfigstring(CS_SIEGE_TIMEOVERRIDE, "0"); } imperial_goals_completed = 0; rebel_goals_completed = 0; - trap->Cvar_Register( &mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM ); + trap->Cvar_Register(&mapname, "mapname", "", CVAR_SERVERINFO | CVAR_ROM); Com_sprintf(levelname, sizeof(levelname), "maps/%s.siege\0", mapname.string); - if ( !levelname[0] ) - { + if (!levelname[0]) { goto failure; } @@ -175,7 +155,7 @@ void InitSiegeMode(void) goto failure; } if (len >= MAX_SIEGE_INFO_SIZE) { - trap->FS_Close( f ); + trap->FS_Close(f); goto failure; } @@ -185,114 +165,81 @@ void InitSiegeMode(void) siege_valid = 1; - //See if players should be specs or ingame preround - if (BG_SiegeGetPairedValue(siege_info, "preround_state", teams)) - { - if (teams[0]) - { + // See if players should be specs or ingame preround + if (BG_SiegeGetPairedValue(siege_info, "preround_state", teams)) { + if (teams[0]) { g_preroundState = atoi(teams); } } - if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) - { - if (g_siegeTeam1.string[0] && Q_stricmp(g_siegeTeam1.string, "none")) - { //check for override + if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) { + if (g_siegeTeam1.string[0] && Q_stricmp(g_siegeTeam1.string, "none")) { // check for override strcpy(team1, g_siegeTeam1.string); - } - else - { //otherwise use level default + } else { // otherwise use level default BG_SiegeGetPairedValue(teams, "team1", team1); } - if (g_siegeTeam2.string[0] && Q_stricmp(g_siegeTeam2.string, "none")) - { //check for override + if (g_siegeTeam2.string[0] && Q_stricmp(g_siegeTeam2.string, "none")) { // check for override strcpy(team2, g_siegeTeam2.string); - } - else - { //otherwise use level default + } else { // otherwise use level default BG_SiegeGetPairedValue(teams, "team2", team2); } - } - else - { - trap->Error( ERR_DROP, "Siege teams not defined" ); + } else { + trap->Error(ERR_DROP, "Siege teams not defined"); } - if (BG_SiegeGetValueGroup(siege_info, team2, gParseObjectives)) - { - if (BG_SiegeGetPairedValue(gParseObjectives, "TeamIcon", teamIcon)) - { - trap->Cvar_Set( "team2_icon", teamIcon); + if (BG_SiegeGetValueGroup(siege_info, team2, gParseObjectives)) { + if (BG_SiegeGetPairedValue(gParseObjectives, "TeamIcon", teamIcon)) { + trap->Cvar_Set("team2_icon", teamIcon); } - if (BG_SiegeGetPairedValue(gParseObjectives, "RequiredObjectives", goalreq)) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "RequiredObjectives", goalreq)) { rebel_goals_required = atoi(goalreq); } - if (BG_SiegeGetPairedValue(gParseObjectives, "Timed", goalreq)) - { - rebel_time_limit = atoi(goalreq)*1000; - if (g_siegeTeamSwitch.integer && - g_siegePersistant.beatingTime) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "Timed", goalreq)) { + rebel_time_limit = atoi(goalreq) * 1000; + if (g_siegeTeamSwitch.integer && g_siegePersistant.beatingTime) { gRebelCountdown = level.time + g_siegePersistant.lastTime; - } - else - { + } else { gRebelCountdown = level.time + rebel_time_limit; } } - if (BG_SiegeGetPairedValue(gParseObjectives, "attackers", goalreq)) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "attackers", goalreq)) { rebel_attackers = atoi(goalreq); } } - if (BG_SiegeGetValueGroup(siege_info, team1, gParseObjectives)) - { + if (BG_SiegeGetValueGroup(siege_info, team1, gParseObjectives)) { - if (BG_SiegeGetPairedValue(gParseObjectives, "TeamIcon", teamIcon)) - { - trap->Cvar_Set( "team1_icon", teamIcon); + if (BG_SiegeGetPairedValue(gParseObjectives, "TeamIcon", teamIcon)) { + trap->Cvar_Set("team1_icon", teamIcon); } - if (BG_SiegeGetPairedValue(gParseObjectives, "RequiredObjectives", goalreq)) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "RequiredObjectives", goalreq)) { imperial_goals_required = atoi(goalreq); } - if (BG_SiegeGetPairedValue(gParseObjectives, "Timed", goalreq)) - { - if (rebel_time_limit) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "Timed", goalreq)) { + if (rebel_time_limit) { Com_Printf("Tried to set imperial time limit, but there's already a rebel time limit!\nOnly one team can have a time limit.\n"); - } - else - { - imperial_time_limit = atoi(goalreq)*1000; - if (g_siegeTeamSwitch.integer && - g_siegePersistant.beatingTime) - { + } else { + imperial_time_limit = atoi(goalreq) * 1000; + if (g_siegeTeamSwitch.integer && g_siegePersistant.beatingTime) { gImperialCountdown = level.time + g_siegePersistant.lastTime; - } - else - { + } else { gImperialCountdown = level.time + imperial_time_limit; } } } - if (BG_SiegeGetPairedValue(gParseObjectives, "attackers", goalreq)) - { + if (BG_SiegeGetPairedValue(gParseObjectives, "attackers", goalreq)) { imperial_attackers = atoi(goalreq); } } - //Load the player class types + // Load the player class types BG_SiegeLoadClasses(NULL); - if (!bgNumSiegeClasses) - { //We didn't find any?! - trap->Error( ERR_DROP, "Couldn't find any player classes for Siege" ); + if (!bgNumSiegeClasses) { // We didn't find any?! + trap->Error(ERR_DROP, "Couldn't find any player classes for Siege"); } /* @@ -318,73 +265,64 @@ void InitSiegeMode(void) i++; } */ - //Ok, I'm adding inventory item precaching now, so I'm finally going to optimize this - //to only do weapons/items for the current teams used on the level. + // Ok, I'm adding inventory item precaching now, so I'm finally going to optimize this + // to only do weapons/items for the current teams used on the level. - //Now load the teams since we have class data. + // Now load the teams since we have class data. BG_SiegeLoadTeams(); - if (!bgNumSiegeTeams) - { //React same as with classes. - trap->Error( ERR_DROP, "Couldn't find any player teams for Siege" ); + if (!bgNumSiegeTeams) { // React same as with classes. + trap->Error(ERR_DROP, "Couldn't find any player teams for Siege"); } - //Get and set the team themes for each team. This will control which classes can be - //used on each team. - if (BG_SiegeGetValueGroup(siege_info, team1, gParseObjectives)) - { - if (BG_SiegeGetPairedValue(gParseObjectives, "UseTeam", goalreq)) - { + // Get and set the team themes for each team. This will control which classes can be + // used on each team. + if (BG_SiegeGetValueGroup(siege_info, team1, gParseObjectives)) { + if (BG_SiegeGetPairedValue(gParseObjectives, "UseTeam", goalreq)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM1, goalreq); } - //Now count up the objectives for this team. + // Now count up the objectives for this team. i = 1; strcpy(objecStr, va("Objective%i", i)); - while (BG_SiegeGetValueGroup(gParseObjectives, objecStr, objective)) - { + while (BG_SiegeGetValueGroup(gParseObjectives, objecStr, objective)) { objectiveNumTeam1++; i++; strcpy(objecStr, va("Objective%i", i)); } } - if (BG_SiegeGetValueGroup(siege_info, team2, gParseObjectives)) - { - if (BG_SiegeGetPairedValue(gParseObjectives, "UseTeam", goalreq)) - { + if (BG_SiegeGetValueGroup(siege_info, team2, gParseObjectives)) { + if (BG_SiegeGetPairedValue(gParseObjectives, "UseTeam", goalreq)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM2, goalreq); } - //Now count up the objectives for this team. + // Now count up the objectives for this team. i = 1; strcpy(objecStr, va("Objective%i", i)); - while (BG_SiegeGetValueGroup(gParseObjectives, objecStr, objective)) - { + while (BG_SiegeGetValueGroup(gParseObjectives, objecStr, objective)) { objectiveNumTeam2++; i++; strcpy(objecStr, va("Objective%i", i)); } } - //Set the configstring to show status of all current objectives + // Set the configstring to show status of all current objectives strcpy(gObjectiveCfgStr, "t1"); - while (objectiveNumTeam1 > 0) - { //mark them all as not completed since we just initialized + while (objectiveNumTeam1 > 0) { // mark them all as not completed since we just initialized Q_strcat(gObjectiveCfgStr, 1024, "-0"); objectiveNumTeam1--; } - //Finished doing team 1's objectives, now do team 2's + // Finished doing team 1's objectives, now do team 2's Q_strcat(gObjectiveCfgStr, 1024, "|t2"); - while (objectiveNumTeam2 > 0) - { + while (objectiveNumTeam2 > 0) { Q_strcat(gObjectiveCfgStr, 1024, "-0"); objectiveNumTeam2--; } - //And finally set the actual config string + // And finally set the actual config string trap->SetConfigstring(CS_SIEGE_OBJECTIVES, gObjectiveCfgStr); - //precache saber data for classes that use sabers on both teams + // precache saber data for classes that use sabers on both teams BG_PrecacheSabersForSiegeTeam(SIEGETEAM_TEAM1); BG_PrecacheSabersForSiegeTeam(SIEGETEAM_TEAM2); @@ -397,48 +335,37 @@ void InitSiegeMode(void) siege_valid = 0; } -void G_SiegeSetObjectiveComplete(int team, int objective, qboolean failIt) -{ +void G_SiegeSetObjectiveComplete(int team, int objective, qboolean failIt) { char *p = NULL; int onObjective = 0; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { p = strstr(gObjectiveCfgStr, "t1"); - } - else if (team == SIEGETEAM_TEAM2) - { + } else if (team == SIEGETEAM_TEAM2) { p = strstr(gObjectiveCfgStr, "t2"); } - if (!p) - { + if (!p) { assert(0); return; } - //Parse from the beginning of this team's objectives until we get to the desired objective - //number. - while (p && *p && *p != '|') - { - if (*p == '-') - { + // Parse from the beginning of this team's objectives until we get to the desired objective + // number. + while (p && *p && *p != '|') { + if (*p == '-') { onObjective++; } - if (onObjective == objective) - { //this is the one we want - //Move to the next char, the status of this objective + if (onObjective == objective) { // this is the one we want + // Move to the next char, the status of this objective p++; - //Now change it from '0' to '1' if we are completeing the objective - //or vice versa if the objective has been taken away - if (failIt) - { + // Now change it from '0' to '1' if we are completeing the objective + // or vice versa if the objective has been taken away + if (failIt) { *p = '0'; - } - else - { + } else { *p = '1'; } break; @@ -447,52 +374,41 @@ void G_SiegeSetObjectiveComplete(int team, int objective, qboolean failIt) p++; } - //Now re-update the configstring. + // Now re-update the configstring. trap->SetConfigstring(CS_SIEGE_OBJECTIVES, gObjectiveCfgStr); } -//Returns qtrue if objective complete currently, otherwise qfalse -qboolean G_SiegeGetCompletionStatus(int team, int objective) -{ +// Returns qtrue if objective complete currently, otherwise qfalse +qboolean G_SiegeGetCompletionStatus(int team, int objective) { char *p = NULL; int onObjective = 0; - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { p = strstr(gObjectiveCfgStr, "t1"); - } - else if (team == SIEGETEAM_TEAM2) - { + } else if (team == SIEGETEAM_TEAM2) { p = strstr(gObjectiveCfgStr, "t2"); } - if (!p) - { + if (!p) { assert(0); return qfalse; } - //Parse from the beginning of this team's objectives until we get to the desired objective - //number. - while (p && *p && *p != '|') - { - if (*p == '-') - { + // Parse from the beginning of this team's objectives until we get to the desired objective + // number. + while (p && *p && *p != '|') { + if (*p == '-') { onObjective++; } - if (onObjective == objective) - { //this is the one we want - //Move to the next char, the status of this objective + if (onObjective == objective) { // this is the one we want + // Move to the next char, the status of this objective p++; - //return qtrue if it's '1', qfalse if it's anything else - if (*p == '1') - { + // return qtrue if it's '1', qfalse if it's anything else + if (*p == '1') { return qtrue; - } - else - { + } else { return qfalse; } break; @@ -504,107 +420,87 @@ qboolean G_SiegeGetCompletionStatus(int team, int objective) return qfalse; } -void UseSiegeTarget(gentity_t *other, gentity_t *en, char *target) -{ //actually use the player which triggered the object which triggered the siege objective to trigger the target - gentity_t *t; - gentity_t *ent; +void UseSiegeTarget(gentity_t *other, gentity_t *en, + char *target) { // actually use the player which triggered the object which triggered the siege objective to trigger the target + gentity_t *t; + gentity_t *ent; - if ( !en || !en->client ) - { //looks like we don't have access to a player, so just use the activating entity + if (!en || !en->client) { // looks like we don't have access to a player, so just use the activating entity ent = other; - } - else - { + } else { ent = en; } - if (!en) - { + if (!en) { return; } - if ( !target ) - { + if (!target) { return; } t = NULL; - while ( (t = G_Find (t, FOFS(targetname), target)) != NULL ) - { - if ( t == ent ) - { - trap->Print ("WARNING: Entity used itself.\n"); - } - else - { - if ( t->use ) - { + while ((t = G_Find(t, FOFS(targetname), target)) != NULL) { + if (t == ent) { + trap->Print("WARNING: Entity used itself.\n"); + } else { + if (t->use) { GlobalUse(t, ent, ent); } } - if ( !ent->inuse ) - { + if (!ent->inuse) { trap->Print("entity was removed while using targets\n"); return; } } } -void SiegeBroadcast_OBJECTIVECOMPLETE(int team, int client, int objective) -{ +void SiegeBroadcast_OBJECTIVECOMPLETE(int team, int client, int objective) { gentity_t *te; vec3_t nomatter; VectorClear(nomatter); - te = G_TempEntity( nomatter, EV_SIEGE_OBJECTIVECOMPLETE ); + te = G_TempEntity(nomatter, EV_SIEGE_OBJECTIVECOMPLETE); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = team; te->s.weapon = client; te->s.trickedentindex = objective; } -void SiegeBroadcast_ROUNDOVER(int winningteam, int winningclient) -{ +void SiegeBroadcast_ROUNDOVER(int winningteam, int winningclient) { gentity_t *te; vec3_t nomatter; VectorClear(nomatter); - te = G_TempEntity( nomatter, EV_SIEGE_ROUNDOVER ); + te = G_TempEntity(nomatter, EV_SIEGE_ROUNDOVER); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = winningteam; te->s.weapon = winningclient; } -void BroadcastObjectiveCompletion(int team, int objective, int final, int client) -{ - if (client != ENTITYNUM_NONE && g_entities[client].client && g_entities[client].client->sess.sessionTeam == team) - { //guy who completed this objective gets points, providing he's on the opposing team +void BroadcastObjectiveCompletion(int team, int objective, int final, int client) { + if (client != ENTITYNUM_NONE && g_entities[client].client && + g_entities[client].client->sess.sessionTeam == team) { // guy who completed this objective gets points, providing he's on the opposing team AddScore(&g_entities[client], g_entities[client].client->ps.origin, SIEGE_POINTS_OBJECTIVECOMPLETED); } SiegeBroadcast_OBJECTIVECOMPLETE(team, client, objective); - //trap->Print("Broadcast goal completion team %i objective %i final %i\n", team, objective, final); + // trap->Print("Broadcast goal completion team %i objective %i final %i\n", team, objective, final); } -void AddSiegeWinningTeamPoints(int team, int winner) -{ +void AddSiegeWinningTeamPoints(int team, int winner) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->client->sess.sessionTeam == team) - { - if (i == winner) - { - AddScore(ent, ent->client->ps.origin, SIEGE_POINTS_TEAMWONROUND+SIEGE_POINTS_FINALOBJECTIVECOMPLETED); - } - else - { + if (ent && ent->client && ent->client->sess.sessionTeam == team) { + if (i == winner) { + AddScore(ent, ent->client->ps.origin, SIEGE_POINTS_TEAMWONROUND + SIEGE_POINTS_FINALOBJECTIVECOMPLETED); + } else { AddScore(ent, ent->client->ps.origin, SIEGE_POINTS_TEAMWONROUND); } } @@ -613,40 +509,29 @@ void AddSiegeWinningTeamPoints(int team, int winner) } } -void SiegeClearSwitchData(void) -{ +void SiegeClearSwitchData(void) { memset(&g_siegePersistant, 0, sizeof(g_siegePersistant)); trap->SiegePersSet(&g_siegePersistant); } -void SiegeDoTeamAssign(void) -{ +void SiegeDoTeamAssign(void) { int i = 0; gentity_t *ent; - //yeah, this is great... - while (i < MAX_CLIENTS) - { + // yeah, this is great... + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent->inuse && ent->client && - ent->client->pers.connected == CON_CONNECTED) - { //a connected client, switch his frickin teams around - if (ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM1) - { + if (ent->inuse && ent->client && ent->client->pers.connected == CON_CONNECTED) { // a connected client, switch his frickin teams around + if (ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM1) { ent->client->sess.siegeDesiredTeam = SIEGETEAM_TEAM2; - } - else if (ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM2) - { + } else if (ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM2) { ent->client->sess.siegeDesiredTeam = SIEGETEAM_TEAM1; } - if (ent->client->sess.sessionTeam == SIEGETEAM_TEAM1) - { + if (ent->client->sess.sessionTeam == SIEGETEAM_TEAM1) { SetTeamQuick(ent, SIEGETEAM_TEAM2, qfalse); - } - else if (ent->client->sess.sessionTeam == SIEGETEAM_TEAM2) - { + } else if (ent->client->sess.sessionTeam == SIEGETEAM_TEAM2) { SetTeamQuick(ent, SIEGETEAM_TEAM1, qfalse); } } @@ -654,39 +539,33 @@ void SiegeDoTeamAssign(void) } } -void SiegeTeamSwitch(int winTeam, int winTime) -{ +void SiegeTeamSwitch(int winTeam, int winTime) { trap->SiegePersGet(&g_siegePersistant); - if (g_siegePersistant.beatingTime) - { //was already in "switched" mode, change back - //announce the winning team. - //either the first team won again, or the second - //team beat the time set by the initial team. In any - //case the winTeam here is the overall winning team. + if (g_siegePersistant.beatingTime) { // was already in "switched" mode, change back + // announce the winning team. + // either the first team won again, or the second + // team beat the time set by the initial team. In any + // case the winTeam here is the overall winning team. SiegeSetCompleteData(winTeam); SiegeClearSwitchData(); - } - else - { //go into "beat their time" mode + } else { // go into "beat their time" mode g_siegePersistant.beatingTime = qtrue; - g_siegePersistant.lastTeam = winTeam; + g_siegePersistant.lastTeam = winTeam; g_siegePersistant.lastTime = winTime; trap->SiegePersSet(&g_siegePersistant); } } -void SiegeRoundComplete(int winningteam, int winningclient) -{ +void SiegeRoundComplete(int winningteam, int winningclient) { vec3_t nomatter; char teamstr[1024]; int originalWinningClient = winningclient; - //trap->Print("Team %i won\n", winningteam); + // trap->Print("Team %i won\n", winningteam); if (winningclient != ENTITYNUM_NONE && g_entities[winningclient].client && - g_entities[winningclient].client->sess.sessionTeam != winningteam) - { //this person just won the round for the other team.. + g_entities[winningclient].client->sess.sessionTeam != winningteam) { // this person just won the round for the other team.. winningclient = ENTITYNUM_NONE; } @@ -696,42 +575,35 @@ void SiegeRoundComplete(int winningteam, int winningclient) AddSiegeWinningTeamPoints(winningteam, winningclient); - //Instead of exiting like this, fire off a target, and let it handle things. - //Can be a script or whatever the designer wants. - if (winningteam == SIEGETEAM_TEAM1) - { + // Instead of exiting like this, fire off a target, and let it handle things. + // Can be a script or whatever the designer wants. + if (winningteam == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - trap->SetConfigstring(CS_SIEGE_STATE, va("3|%i", level.time)); //ended + trap->SetConfigstring(CS_SIEGE_STATE, va("3|%i", level.time)); // ended gSiegeRoundBegun = qfalse; gSiegeRoundEnded = qtrue; gSiegeRoundWinningTeam = winningteam; - if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) - { - if (!BG_SiegeGetPairedValue(gParseObjectives, "roundover_target", teamstr)) - { //didn't find the name of the thing to target upon win, just logexit now then. - LogExit( "Objectives completed" ); + if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) { + if (!BG_SiegeGetPairedValue(gParseObjectives, "roundover_target", + teamstr)) { // didn't find the name of the thing to target upon win, just logexit now then. + LogExit("Objectives completed"); return; } - if (originalWinningClient == ENTITYNUM_NONE) - { //oh well, just find something active and use it then. - int i = 0; + if (originalWinningClient == ENTITYNUM_NONE) { // oh well, just find something active and use it then. + int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent->inuse) - { //sure, you'll do. - originalWinningClient = ent->s.number; + if (ent->inuse) { // sure, you'll do. + originalWinningClient = ent->s.number; break; } @@ -741,168 +613,127 @@ void SiegeRoundComplete(int winningteam, int winningclient) G_UseTargets2(&g_entities[originalWinningClient], &g_entities[originalWinningClient], teamstr); } - if (g_siegeTeamSwitch.integer && - (imperial_time_limit || rebel_time_limit)) - { //handle stupid team switching crap + if (g_siegeTeamSwitch.integer && (imperial_time_limit || rebel_time_limit)) { // handle stupid team switching crap int time = 0; - if (imperial_time_limit) - { - time = imperial_time_limit-(gImperialCountdown-level.time); - } - else if (rebel_time_limit) - { - time = rebel_time_limit-(gRebelCountdown-level.time); + if (imperial_time_limit) { + time = imperial_time_limit - (gImperialCountdown - level.time); + } else if (rebel_time_limit) { + time = rebel_time_limit - (gRebelCountdown - level.time); } - if (time < 1) - { + if (time < 1) { time = 1; } SiegeTeamSwitch(winningteam, time); - } - else - { //assure it's clear for next round + } else { // assure it's clear for next round SiegeClearSwitchData(); } } -void G_ValidateSiegeClassForTeam(gentity_t *ent, int team) -{ +void G_ValidateSiegeClassForTeam(gentity_t *ent, int team) { siegeClass_t *scl; siegeTeam_t *stm; int newClassIndex = -1; - if (ent->client->siegeClass == -1) - { //uh.. sure. + if (ent->client->siegeClass == -1) { // uh.. sure. return; } scl = &bgSiegeClasses[ent->client->siegeClass]; stm = BG_SiegeFindThemeForTeam(team); - if (stm) - { + if (stm) { int i = 0; - while (i < stm->numClasses) - { //go through the team and see its valid classes, can we find one that matches our current player class? - if (stm->classes[i]) - { - if (!Q_stricmp(scl->name, stm->classes[i]->name)) - { //the class we're using is already ok for this team. + while (i < stm->numClasses) { // go through the team and see its valid classes, can we find one that matches our current player class? + if (stm->classes[i]) { + if (!Q_stricmp(scl->name, stm->classes[i]->name)) { // the class we're using is already ok for this team. return; } - if (stm->classes[i]->playerClass == scl->playerClass || - newClassIndex == -1) - { + if (stm->classes[i]->playerClass == scl->playerClass || newClassIndex == -1) { newClassIndex = i; } } i++; } - if (newClassIndex != -1) - { //ok, let's find it in the global class array + if (newClassIndex != -1) { // ok, let's find it in the global class array ent->client->siegeClass = BG_SiegeFindClassIndexByName(stm->classes[newClassIndex]->name); - Q_strncpyz( ent->client->sess.siegeClass, stm->classes[newClassIndex]->name, sizeof( ent->client->sess.siegeClass )); + Q_strncpyz(ent->client->sess.siegeClass, stm->classes[newClassIndex]->name, sizeof(ent->client->sess.siegeClass)); } } } -//bypass most of the normal checks in SetTeam -void SetTeamQuick(gentity_t *ent, int team, qboolean doBegin) -{ +// bypass most of the normal checks in SetTeam +void SetTeamQuick(gentity_t *ent, int team, qboolean doBegin) { char userinfo[MAX_INFO_STRING]; - trap->GetUserinfo( ent->s.number, userinfo, sizeof( userinfo ) ); + trap->GetUserinfo(ent->s.number, userinfo, sizeof(userinfo)); - if (level.gametype == GT_SIEGE) - { + if (level.gametype == GT_SIEGE) { G_ValidateSiegeClassForTeam(ent, team); } ent->client->sess.sessionTeam = team; - if (team == TEAM_SPECTATOR) - { + if (team == TEAM_SPECTATOR) { ent->client->sess.spectatorState = SPECTATOR_FREE; Info_SetValueForKey(userinfo, "team", "s"); - } - else - { + } else { ent->client->sess.spectatorState = SPECTATOR_NOT; - if (team == TEAM_RED) - { + if (team == TEAM_RED) { Info_SetValueForKey(userinfo, "team", "r"); - } - else if (team == TEAM_BLUE) - { + } else if (team == TEAM_BLUE) { Info_SetValueForKey(userinfo, "team", "b"); - } - else - { + } else { Info_SetValueForKey(userinfo, "team", "?"); } } - trap->SetUserinfo( ent->s.number, userinfo ); + trap->SetUserinfo(ent->s.number, userinfo); ent->client->sess.spectatorClient = 0; ent->client->pers.teamState.state = TEAM_BEGIN; - if ( !ClientUserinfoChanged( ent->s.number ) ) + if (!ClientUserinfoChanged(ent->s.number)) return; - if (doBegin) - { - ClientBegin( ent->s.number, qfalse ); + if (doBegin) { + ClientBegin(ent->s.number, qfalse); } } -void SiegeRespawn(gentity_t *ent) -{ - if (ent->client->sess.sessionTeam != ent->client->sess.siegeDesiredTeam) - { +void SiegeRespawn(gentity_t *ent) { + if (ent->client->sess.sessionTeam != ent->client->sess.siegeDesiredTeam) { SetTeamQuick(ent, ent->client->sess.siegeDesiredTeam, qtrue); - } - else - { + } else { ClientSpawn(ent); } } -void SiegeBeginRound(int entNum) -{ //entNum is just used as something to fire targets from. +void SiegeBeginRound(int entNum) { // entNum is just used as something to fire targets from. char targname[1024]; - if (!g_preroundState) - { //if players are not ingame on round start then respawn them now + if (!g_preroundState) { // if players are not ingame on round start then respawn them now int i = 0; gentity_t *ent; qboolean spawnEnt = qfalse; - //respawn everyone now - while (i < MAX_CLIENTS) - { + // respawn everyone now + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent->inuse && ent->client) - { - if (ent->client->sess.sessionTeam != TEAM_SPECTATOR && - !(ent->client->ps.pm_flags & PMF_FOLLOW)) - { //not a spec, just respawn them + if (ent->inuse && ent->client) { + if (ent->client->sess.sessionTeam != TEAM_SPECTATOR && !(ent->client->ps.pm_flags & PMF_FOLLOW)) { // not a spec, just respawn them spawnEnt = qtrue; - } - else if (ent->client->sess.sessionTeam == TEAM_SPECTATOR && - (ent->client->sess.siegeDesiredTeam == TEAM_RED || - ent->client->sess.siegeDesiredTeam == TEAM_BLUE)) - { //spectator but has a desired team + } else if (ent->client->sess.sessionTeam == TEAM_SPECTATOR && + (ent->client->sess.siegeDesiredTeam == TEAM_RED || + ent->client->sess.siegeDesiredTeam == TEAM_BLUE)) { // spectator but has a desired team spawnEnt = qtrue; } } - if (spawnEnt) - { + if (spawnEnt) { SiegeRespawn(ent); spawnEnt = qfalse; @@ -911,52 +742,41 @@ void SiegeBeginRound(int entNum) } } - //Now check if there's something to fire off at the round start, if so do it. - if (BG_SiegeGetPairedValue(siege_info, "roundbegin_target", targname)) - { - if (targname[0]) - { + // Now check if there's something to fire off at the round start, if so do it. + if (BG_SiegeGetPairedValue(siege_info, "roundbegin_target", targname)) { + if (targname[0]) { G_UseTargets2(&g_entities[entNum], &g_entities[entNum], targname); } } - trap->SetConfigstring(CS_SIEGE_STATE, va("0|%i", level.time)); //we're ready to g0g0g0 + trap->SetConfigstring(CS_SIEGE_STATE, va("0|%i", level.time)); // we're ready to g0g0g0 } -void SiegeCheckTimers(void) -{ - int i=0; +void SiegeCheckTimers(void) { + int i = 0; gentity_t *ent; int numTeam1 = 0; int numTeam2 = 0; - if (level.gametype != GT_SIEGE) - { + if (level.gametype != GT_SIEGE) { return; } - if (level.intermissiontime) - { + if (level.intermissiontime) { return; } - if (gSiegeRoundEnded) - { + if (gSiegeRoundEnded) { return; } - if (!gSiegeRoundBegun) - { //check if anyone is active on this team - if not, keep the timer set up. + if (!gSiegeRoundBegun) { // check if anyone is active on this team - if not, keep the timer set up. i = 0; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->client && - ent->client->pers.connected == CON_CONNECTED && - ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM1) - { + if (ent && ent->inuse && ent->client && ent->client->pers.connected == CON_CONNECTED && ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM1) { numTeam1++; } i++; @@ -964,174 +784,128 @@ void SiegeCheckTimers(void) i = 0; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->client && - ent->client->pers.connected == CON_CONNECTED && - ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM2) - { + if (ent && ent->inuse && ent->client && ent->client->pers.connected == CON_CONNECTED && ent->client->sess.siegeDesiredTeam == SIEGETEAM_TEAM2) { numTeam2++; } i++; } - if (g_siegeTeamSwitch.integer && - g_siegePersistant.beatingTime) - { + if (g_siegeTeamSwitch.integer && g_siegePersistant.beatingTime) { gImperialCountdown = level.time + g_siegePersistant.lastTime; gRebelCountdown = level.time + g_siegePersistant.lastTime; - } - else - { + } else { gImperialCountdown = level.time + imperial_time_limit; gRebelCountdown = level.time + rebel_time_limit; } } - if (imperial_time_limit) - { //team1 - if (gImperialCountdown < level.time) - { + if (imperial_time_limit) { // team1 + if (gImperialCountdown < level.time) { SiegeRoundComplete(SIEGETEAM_TEAM2, ENTITYNUM_NONE); imperial_time_limit = 0; return; } } - if (rebel_time_limit) - { //team2 - if (gRebelCountdown < level.time) - { + if (rebel_time_limit) { // team2 + if (gRebelCountdown < level.time) { SiegeRoundComplete(SIEGETEAM_TEAM1, ENTITYNUM_NONE); rebel_time_limit = 0; return; } } - if (!gSiegeRoundBegun) - { - if (!numTeam1 || !numTeam2) - { //don't have people on both teams yet. + if (!gSiegeRoundBegun) { + if (!numTeam1 || !numTeam2) { // don't have people on both teams yet. gSiegeBeginTime = level.time + SIEGE_ROUND_BEGIN_TIME; trap->SetConfigstring(CS_SIEGE_STATE, "1"); //"waiting for players on both teams" - } - else if (gSiegeBeginTime < level.time) - { //mark the round as having begun + } else if (gSiegeBeginTime < level.time) { // mark the round as having begun gSiegeRoundBegun = qtrue; - SiegeBeginRound(i); //perform any round start tasks - } - else if (gSiegeBeginTime > (level.time + SIEGE_ROUND_BEGIN_TIME)) - { + SiegeBeginRound(i); // perform any round start tasks + } else if (gSiegeBeginTime > (level.time + SIEGE_ROUND_BEGIN_TIME)) { gSiegeBeginTime = level.time + SIEGE_ROUND_BEGIN_TIME; - } - else - { - trap->SetConfigstring(CS_SIEGE_STATE, va("2|%i", gSiegeBeginTime - SIEGE_ROUND_BEGIN_TIME)); //getting ready to begin + } else { + trap->SetConfigstring(CS_SIEGE_STATE, va("2|%i", gSiegeBeginTime - SIEGE_ROUND_BEGIN_TIME)); // getting ready to begin } } } -void SiegeObjectiveCompleted(int team, int objective, int final, int client) -{ +void SiegeObjectiveCompleted(int team, int objective, int final, int client) { int goals_completed, goals_required; - if (gSiegeRoundEnded) - { + if (gSiegeRoundEnded) { return; } - //Update the configstring status + // Update the configstring status G_SiegeSetObjectiveComplete(team, objective, qfalse); - if (final != -1) - { - if (team == SIEGETEAM_TEAM1) - { + if (final != -1) { + if (team == SIEGETEAM_TEAM1) { imperial_goals_completed++; - } - else - { + } else { rebel_goals_completed++; } } - if (team == SIEGETEAM_TEAM1) - { + if (team == SIEGETEAM_TEAM1) { goals_completed = imperial_goals_completed; goals_required = imperial_goals_required; - } - else - { + } else { goals_completed = rebel_goals_completed; goals_required = rebel_goals_required; } - if (final == 1 || goals_completed >= goals_required) - { + if (final == 1 || goals_completed >= goals_required) { SiegeRoundComplete(team, client); - } - else - { + } else { BroadcastObjectiveCompletion(team, objective, final, client); } } -void siegeTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - char teamstr[64]; - char objectivestr[64]; - static char desiredobjective[MAX_SIEGE_INFO_SIZE]; - int clUser = ENTITYNUM_NONE; - int final = 0; - int i = 0; +void siegeTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { + char teamstr[64]; + char objectivestr[64]; + static char desiredobjective[MAX_SIEGE_INFO_SIZE]; + int clUser = ENTITYNUM_NONE; + int final = 0; + int i = 0; desiredobjective[0] = '\0'; - if (!siege_valid) - { + if (!siege_valid) { return; } - if (!(ent->s.eFlags & EF_RADAROBJECT)) - { //toggle radar on and exit if it is not showing up already + if (!(ent->s.eFlags & EF_RADAROBJECT)) { // toggle radar on and exit if it is not showing up already ent->s.eFlags |= EF_RADAROBJECT; return; } - if (activator && activator->client) - { //activator will hopefully be the person who triggered this event + if (activator && activator->client) { // activator will hopefully be the person who triggered this event clUser = activator->s.number; } - if (ent->side == SIEGETEAM_TEAM1) - { + if (ent->side == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) { Com_sprintf(objectivestr, sizeof(objectivestr), "Objective%i", ent->objective); - if (BG_SiegeGetValueGroup(gParseObjectives, objectivestr, desiredobjective)) - { - if (BG_SiegeGetPairedValue(desiredobjective, "final", teamstr)) - { + if (BG_SiegeGetValueGroup(gParseObjectives, objectivestr, desiredobjective)) { + if (BG_SiegeGetPairedValue(desiredobjective, "final", teamstr)) { final = atoi(teamstr); } - if (BG_SiegeGetPairedValue(desiredobjective, "target", teamstr)) - { - while (teamstr[i]) - { - if (teamstr[i] == '\r' || - teamstr[i] == '\n') - { + if (BG_SiegeGetPairedValue(desiredobjective, "target", teamstr)) { + while (teamstr[i]) { + if (teamstr[i] == '\r' || teamstr[i] == '\n') { teamstr[i] = '\0'; } @@ -1140,8 +914,7 @@ void siegeTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) UseSiegeTarget(other, activator, teamstr); } - if (ent->target && ent->target[0]) - { //use this too + if (ent->target && ent->target[0]) { // use this too UseSiegeTarget(other, activator, ent->target); } @@ -1157,40 +930,35 @@ STARTOFFRADAR - start not displaying on radar, don't display until used. "side" - set to 1 to specify an imperial goal, 2 to specify rebels "icon" - icon that represents the objective on the radar */ -void SP_info_siege_objective (gentity_t *ent) -{ - char* s; +void SP_info_siege_objective(gentity_t *ent) { + char *s; - if (!siege_valid || level.gametype != GT_SIEGE) - { + if (!siege_valid || level.gametype != GT_SIEGE) { G_FreeEntity(ent); return; } ent->use = siegeTriggerUse; - G_SpawnInt( "objective", "0", &ent->objective); - G_SpawnInt( "side", "0", &ent->side); + G_SpawnInt("objective", "0", &ent->objective); + G_SpawnInt("side", "0", &ent->side); - if (!ent->objective || !ent->side) - { //j00 fux0red something up + if (!ent->objective || !ent->side) { // j00 fux0red something up G_FreeEntity(ent); trap->Print("ERROR: info_siege_objective without an objective or side value\n"); return; } - //Set it up to be drawn on radar - if (!(ent->spawnflags & SIEGEITEM_STARTOFFRADAR)) - { + // Set it up to be drawn on radar + if (!(ent->spawnflags & SIEGEITEM_STARTOFFRADAR)) { ent->s.eFlags |= EF_RADAROBJECT; } - //All clients want to know where it is at all times for radar + // All clients want to know where it is at all times for radar ent->r.svFlags |= SVF_BROADCAST; - G_SpawnString( "icon", "", &s ); + G_SpawnString("icon", "", &s); - if (s && s[0]) - { + if (s && s[0]) { // We have an icon, so index it now. We are reusing the genericenemyindex // variable rather than adding a new one to the entity state. ent->s.genericenemyindex = G_IconIndex(s); @@ -1201,16 +969,11 @@ void SP_info_siege_objective (gentity_t *ent) trap->LinkEntity((sharedEntity_t *)ent); } - -void SiegeIconUse(gentity_t *ent, gentity_t *other, gentity_t *activator) -{ //toggle it on and off - if (ent->s.eFlags & EF_RADAROBJECT) - { +void SiegeIconUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { // toggle it on and off + if (ent->s.eFlags & EF_RADAROBJECT) { ent->s.eFlags &= ~EF_RADAROBJECT; ent->r.svFlags &= ~SVF_BROADCAST; - } - else - { + } else { ent->s.eFlags |= EF_RADAROBJECT; ent->r.svFlags |= SVF_BROADCAST; } @@ -1223,29 +986,25 @@ to toggle on and off. "icon" - icon that represents the objective on the radar "startoff" - if 1 start off */ -void SP_info_siege_radaricon (gentity_t *ent) -{ - char* s; +void SP_info_siege_radaricon(gentity_t *ent) { + char *s; int i; - if (!siege_valid || level.gametype != GT_SIEGE) - { + if (!siege_valid || level.gametype != GT_SIEGE) { G_FreeEntity(ent); return; } G_SpawnInt("startoff", "0", &i); - if (!i) - { //start on then + if (!i) { // start on then ent->s.eFlags |= EF_RADAROBJECT; ent->r.svFlags |= SVF_BROADCAST; } - G_SpawnString( "icon", "", &s ); - if (!s || !s[0]) - { //that's the whole point of the entity - Com_Error(ERR_DROP, "misc_siege_radaricon without an icon"); + G_SpawnString("icon", "", &s); + if (!s || !s[0]) { // that's the whole point of the entity + Com_Error(ERR_DROP, "misc_siege_radaricon without an icon"); return; } @@ -1256,8 +1015,7 @@ void SP_info_siege_radaricon (gentity_t *ent) trap->LinkEntity((sharedEntity_t *)ent); } -void decompTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) -{ +void decompTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { int final = 0; char teamstr[1024]; char objectivestr[64]; @@ -1265,51 +1023,39 @@ void decompTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) desiredobjective[0] = '\0'; - if (gSiegeRoundEnded) - { + if (gSiegeRoundEnded) { return; } - if (!G_SiegeGetCompletionStatus(ent->side, ent->objective)) - { //if it's not complete then there's nothing to do here + if (!G_SiegeGetCompletionStatus(ent->side, ent->objective)) { // if it's not complete then there's nothing to do here return; } - //Update the configstring status + // Update the configstring status G_SiegeSetObjectiveComplete(ent->side, ent->objective, qtrue); - //Find out if this objective counts toward the final objective count - if (ent->side == SIEGETEAM_TEAM1) - { + // Find out if this objective counts toward the final objective count + if (ent->side == SIEGETEAM_TEAM1) { Com_sprintf(teamstr, sizeof(teamstr), team1); - } - else - { + } else { Com_sprintf(teamstr, sizeof(teamstr), team2); } - if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) - { + if (BG_SiegeGetValueGroup(siege_info, teamstr, gParseObjectives)) { Com_sprintf(objectivestr, sizeof(objectivestr), "Objective%i", ent->objective); - if (BG_SiegeGetValueGroup(gParseObjectives, objectivestr, desiredobjective)) - { - if (BG_SiegeGetPairedValue(desiredobjective, "final", teamstr)) - { + if (BG_SiegeGetValueGroup(gParseObjectives, objectivestr, desiredobjective)) { + if (BG_SiegeGetPairedValue(desiredobjective, "final", teamstr)) { final = atoi(teamstr); } } } - //Subtract the goal num if applicable - if (final != -1) - { - if (ent->side == SIEGETEAM_TEAM1) - { + // Subtract the goal num if applicable + if (final != -1) { + if (ent->side == SIEGETEAM_TEAM1) { imperial_goals_completed--; - } - else - { + } else { rebel_goals_completed--; } } @@ -1319,38 +1065,30 @@ void decompTriggerUse(gentity_t *ent, gentity_t *other, gentity_t *activator) "objective" - specifies the objective to decomplete upon activation "side" - set to 1 to specify an imperial (team1) goal, 2 to specify rebels (team2) */ -void SP_info_siege_decomplete (gentity_t *ent) -{ - if (!siege_valid || level.gametype != GT_SIEGE) - { +void SP_info_siege_decomplete(gentity_t *ent) { + if (!siege_valid || level.gametype != GT_SIEGE) { G_FreeEntity(ent); return; } ent->use = decompTriggerUse; - G_SpawnInt( "objective", "0", &ent->objective); - G_SpawnInt( "side", "0", &ent->side); + G_SpawnInt("objective", "0", &ent->objective); + G_SpawnInt("side", "0", &ent->side); - if (!ent->objective || !ent->side) - { //j00 fux0red something up + if (!ent->objective || !ent->side) { // j00 fux0red something up G_FreeEntity(ent); trap->Print("ERROR: info_siege_objective_decomplete without an objective or side value\n"); return; } } -void siegeEndUse(gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - LogExit("Round ended"); -} +void siegeEndUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { LogExit("Round ended"); } /*QUAKED target_siege_end (1 0 1) (-16 -16 -24) (16 16 32) Do a logexit for siege when used. */ -void SP_target_siege_end (gentity_t *ent) -{ - if (!siege_valid || level.gametype != GT_SIEGE) - { +void SP_target_siege_end(gentity_t *ent) { + if (!siege_valid || level.gametype != GT_SIEGE) { G_FreeEntity(ent); return; } @@ -1360,42 +1098,36 @@ void SP_target_siege_end (gentity_t *ent) #define SIEGE_ITEM_RESPAWN_TIME 20000 -void SiegeItemRemoveOwner(gentity_t *ent, gentity_t *carrier) -{ - ent->genericValue2 = 0; //Remove picked-up flag +void SiegeItemRemoveOwner(gentity_t *ent, gentity_t *carrier) { + ent->genericValue2 = 0; // Remove picked-up flag - ent->genericValue8 = ENTITYNUM_NONE; //Mark entity carrying us as none + ent->genericValue8 = ENTITYNUM_NONE; // Mark entity carrying us as none - if (carrier) - { - carrier->client->holdingObjectiveItem = 0; //The carrier is no longer carrying us + if (carrier) { + carrier->client->holdingObjectiveItem = 0; // The carrier is no longer carrying us carrier->r.svFlags &= ~SVF_BROADCAST; } } -static void SiegeItemRespawnEffect(gentity_t *ent, vec3_t newOrg) -{ +static void SiegeItemRespawnEffect(gentity_t *ent, vec3_t newOrg) { vec3_t upAng; - if (ent->target5 && ent->target5[0]) - { + if (ent->target5 && ent->target5[0]) { G_UseTargets2(ent, ent, ent->target5); } - if (!ent->genericValue10) - { //no respawn effect + if (!ent->genericValue10) { // no respawn effect return; } VectorSet(upAng, 0, 0, 1); - //Play it once on the current origin, and once on the origin we're respawning to. + // Play it once on the current origin, and once on the origin we're respawning to. G_PlayEffectID(ent->genericValue10, ent->r.currentOrigin, upAng); G_PlayEffectID(ent->genericValue10, newOrg, upAng); } -static void SiegeItemRespawnOnOriginalSpot(gentity_t *ent, gentity_t *carrier) -{ +static void SiegeItemRespawnOnOriginalSpot(gentity_t *ent, gentity_t *carrier) { SiegeItemRespawnEffect(ent, ent->pos1); G_SetOrigin(ent, ent->pos1); SiegeItemRemoveOwner(ent, carrier); @@ -1404,114 +1136,90 @@ static void SiegeItemRespawnOnOriginalSpot(gentity_t *ent, gentity_t *carrier) ent->s.time2 = 0; } -void SiegeItemThink(gentity_t *ent) -{ +void SiegeItemThink(gentity_t *ent) { gentity_t *carrier = NULL; - if (ent->genericValue12) - { //recharge health - if (ent->health > 0 && ent->health < ent->maxHealth && ent->genericValue14 < level.time) - { - ent->genericValue14 = level.time + ent->genericValue13; + if (ent->genericValue12) { // recharge health + if (ent->health > 0 && ent->health < ent->maxHealth && ent->genericValue14 < level.time) { + ent->genericValue14 = level.time + ent->genericValue13; ent->health += ent->genericValue12; - if (ent->health > ent->maxHealth) - { + if (ent->health > ent->maxHealth) { ent->health = ent->maxHealth; } } } - if (ent->genericValue8 != ENTITYNUM_NONE) - { //Just keep sticking it on top of the owner. We need it in the same PVS as him so it will render bolted onto him properly. + if (ent->genericValue8 != + ENTITYNUM_NONE) { // Just keep sticking it on top of the owner. We need it in the same PVS as him so it will render bolted onto him properly. carrier = &g_entities[ent->genericValue8]; - if (carrier->inuse && carrier->client) - { + if (carrier->inuse && carrier->client) { VectorCopy(carrier->client->ps.origin, ent->r.currentOrigin); trap->LinkEntity((sharedEntity_t *)ent); } - } - else if (ent->genericValue1) - { //this means we want to run physics on the object + } else if (ent->genericValue1) { // this means we want to run physics on the object G_RunExPhys(ent, ent->radius, ent->mass, ent->random, qfalse, NULL, 0); } - //Bolt us to whoever is carrying us if a client - if (ent->genericValue8 < MAX_CLIENTS) - { - ent->s.boltToPlayer = ent->genericValue8+1; - } - else - { + // Bolt us to whoever is carrying us if a client + if (ent->genericValue8 < MAX_CLIENTS) { + ent->s.boltToPlayer = ent->genericValue8 + 1; + } else { ent->s.boltToPlayer = 0; } - if (carrier) { - //This checking can be a bit iffy on the death stuff, but in theory we should always - //get a think in before the default minimum respawn time is exceeded. + // This checking can be a bit iffy on the death stuff, but in theory we should always + // get a think in before the default minimum respawn time is exceeded. if (!carrier->inuse || !carrier->client || (carrier->client->sess.sessionTeam != SIEGETEAM_TEAM1 && carrier->client->sess.sessionTeam != SIEGETEAM_TEAM2) || - (carrier->client->ps.pm_flags & PMF_FOLLOW)) - { //respawn on the original spot + (carrier->client->ps.pm_flags & PMF_FOLLOW)) { // respawn on the original spot SiegeItemRespawnOnOriginalSpot(ent, NULL); - } - else if (carrier->health < 1) - { //The carrier died so pop out where he is (unless in nodrop). - if (ent->target6 && ent->target6[0]) - { + } else if (carrier->health < 1) { // The carrier died so pop out where he is (unless in nodrop). + if (ent->target6 && ent->target6[0]) { G_UseTargets2(ent, ent, ent->target6); } - if ( trap->PointContents(carrier->client->ps.origin, carrier->s.number) & CONTENTS_NODROP ) - { //In nodrop land, go back to the original spot. + if (trap->PointContents(carrier->client->ps.origin, carrier->s.number) & CONTENTS_NODROP) { // In nodrop land, go back to the original spot. SiegeItemRespawnOnOriginalSpot(ent, carrier); - } - else - { - //perform a startsolid check to make sure the seige item doesn't get stuck - //in a wall or something + } else { + // perform a startsolid check to make sure the seige item doesn't get stuck + // in a wall or something trace_t tr; trap->Trace(&tr, carrier->client->ps.origin, ent->r.mins, ent->r.maxs, carrier->client->ps.origin, ent->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - {//bad spawning area, try again with the trace up a bit. + if (tr.startsolid) { // bad spawning area, try again with the trace up a bit. vec3_t TracePoint; VectorCopy(carrier->client->ps.origin, TracePoint); TracePoint[2] += 30; trap->Trace(&tr, TracePoint, ent->r.mins, ent->r.maxs, TracePoint, ent->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - {//hmm, well that didn't work. try one last time with the item back - //away from where the dude was facing (in case the carrier was - //close to something they were attacking.) + if (tr.startsolid) { // hmm, well that didn't work. try one last time with the item back + // away from where the dude was facing (in case the carrier was + // close to something they were attacking.) vec3_t fwd; - AngleVectors(carrier->client->ps.viewangles,fwd, NULL, NULL); + AngleVectors(carrier->client->ps.viewangles, fwd, NULL, NULL); VectorMA(TracePoint, -30, fwd, TracePoint); trap->Trace(&tr, TracePoint, ent->r.mins, ent->r.maxs, TracePoint, ent->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - { + if (tr.startsolid) { SiegeItemRespawnOnOriginalSpot(ent, carrier); return; } } G_SetOrigin(ent, TracePoint); - } - else - {//we're good at the player's origin + } else { // we're good at the player's origin G_SetOrigin(ent, carrier->client->ps.origin); } - - //G_SetOrigin(ent, carrier->client->ps.origin); + // G_SetOrigin(ent, carrier->client->ps.origin); ent->epVelocity[0] = Q_irand(-80, 80); ent->epVelocity[1] = Q_irand(-80, 80); ent->epVelocity[2] = Q_irand(40, 80); - //We're in a nonstandard place, so if we go this long without being touched, - //assume we may not be reachable and respawn on the original spot. + // We're in a nonstandard place, so if we go this long without being touched, + // assume we may not be reachable and respawn on the original spot. ent->genericValue9 = level.time + SIEGE_ITEM_RESPAWN_TIME; SiegeItemRemoveOwner(ent, carrier); @@ -1519,8 +1227,7 @@ void SiegeItemThink(gentity_t *ent) } } - if (ent->genericValue9 && ent->genericValue9 < level.time) - { //time to respawn on the original spot then + if (ent->genericValue9 && ent->genericValue9 < level.time) { // time to respawn on the original spot then SiegeItemRespawnEffect(ent, ent->pos1); G_SetOrigin(ent, ent->pos1); ent->genericValue9 = 0; @@ -1529,91 +1236,78 @@ void SiegeItemThink(gentity_t *ent) ent->s.time2 = 0; } - ent->nextthink = level.time + FRAMETIME/2; + ent->nextthink = level.time + FRAMETIME / 2; } -void SiegeItemTouch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if (!other || !other->inuse || - !other->client || other->s.eType == ET_NPC) - { - if (trace && trace->startsolid) - { //let me out! (ideally this should not happen, but such is life) +void SiegeItemTouch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other || !other->inuse || !other->client || other->s.eType == ET_NPC) { + if (trace && trace->startsolid) { // let me out! (ideally this should not happen, but such is life) vec3_t escapePos; VectorCopy(self->r.currentOrigin, escapePos); escapePos[2] += 1.0f; - //I hope you weren't stuck in the ceiling. + // I hope you weren't stuck in the ceiling. G_SetOrigin(self, escapePos); } return; } - if (other->health < 1) - { //dead people can't pick us up. + if (other->health < 1) { // dead people can't pick us up. return; } - if (other->client->holdingObjectiveItem) - { //this guy's already carrying a siege item + if (other->client->holdingObjectiveItem) { // this guy's already carrying a siege item return; } - if ( other->client->ps.pm_type == PM_SPECTATOR ) - {//spectators don't pick stuff up + if (other->client->ps.pm_type == PM_SPECTATOR) { // spectators don't pick stuff up return; } - if (self->genericValue2) - { //Am I already picked up? + if (self->genericValue2) { // Am I already picked up? return; } - if (self->genericValue6 == other->client->sess.sessionTeam) - { //Set to not be touchable by players on this team. + if (self->genericValue6 == other->client->sess.sessionTeam) { // Set to not be touchable by players on this team. return; } - if (!gSiegeRoundBegun) - { //can't pick it up if round hasn't started yet + if (!gSiegeRoundBegun) { // can't pick it up if round hasn't started yet return; } - if (self->noise_index) - { //play the pickup noise. + if (self->noise_index) { // play the pickup noise. G_Sound(other, CHAN_AUTO, self->noise_index); } - self->genericValue2 = 1; //Mark it as picked up. + self->genericValue2 = 1; // Mark it as picked up. other->client->holdingObjectiveItem = self->s.number; - other->r.svFlags |= SVF_BROADCAST; //broadcast player while he carries this - self->genericValue8 = other->s.number; //Keep the index so we know who is "carrying" us + other->r.svFlags |= SVF_BROADCAST; // broadcast player while he carries this + self->genericValue8 = other->s.number; // Keep the index so we know who is "carrying" us - self->genericValue9 = 0; //So it doesn't think it has to respawn. + self->genericValue9 = 0; // So it doesn't think it has to respawn. - if (self->target2 && self->target2[0] && (!self->genericValue4 || !self->genericValue5)) - { //fire the target for pickup, if it's set to fire every time, or set to only fire the first time and the first time has not yet occured. + if (self->target2 && self->target2[0] && + (!self->genericValue4 || !self->genericValue5)) { // fire the target for pickup, if it's set to fire every time, or set to only fire the first time and + // the first time has not yet occured. G_UseTargets2(self, self, self->target2); - self->genericValue5 = 1; //mark it as having been picked up + self->genericValue5 = 1; // mark it as having been picked up } // time2 set to -1 will blink the item on the radar indefinately self->s.time2 = 0xFFFFFFFF; } -void SiegeItemPain(gentity_t *self, gentity_t *attacker, int damage) -{ +void SiegeItemPain(gentity_t *self, gentity_t *attacker, int damage) { // Time 2 is used to pulse the radar icon to show its under attack self->s.time2 = level.time; } -void SiegeItemDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) -{ - self->takedamage = qfalse; //don't die more than once +void SiegeItemDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { + self->takedamage = qfalse; // don't die more than once - if (self->genericValue3) - { //An indexed effect to play on death + if (self->genericValue3) { // An indexed effect to play on death vec3_t upAng; VectorSet(upAng, 0, 0, 1); @@ -1624,92 +1318,74 @@ void SiegeItemDie( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, i self->think = G_FreeEntity; self->nextthink = level.time; - //Fire off the death target if we've got one. - if (self->target4 && self->target4[0]) - { + // Fire off the death target if we've got one. + if (self->target4 && self->target4[0]) { G_UseTargets2(self, self, self->target4); } } -void SiegeItemUse(gentity_t *ent, gentity_t *other, gentity_t *activator) -{ //once used, become active - if (ent->spawnflags & SIEGEITEM_STARTOFFRADAR) - { //start showing on radar +void SiegeItemUse(gentity_t *ent, gentity_t *other, gentity_t *activator) { // once used, become active + if (ent->spawnflags & SIEGEITEM_STARTOFFRADAR) { // start showing on radar ent->s.eFlags |= EF_RADAROBJECT; - if (!(ent->s.eFlags & EF_NODRAW)) - { //we've nothing else to do here + if (!(ent->s.eFlags & EF_NODRAW)) { // we've nothing else to do here return; } - } - else - { //make sure it's showing up + } else { // make sure it's showing up ent->s.eFlags |= EF_RADAROBJECT; } - if (ent->genericValue11 || !ent->takedamage) - { //We want to be able to walk into it to pick it up then. + if (ent->genericValue11 || !ent->takedamage) { // We want to be able to walk into it to pick it up then. ent->r.contents = CONTENTS_TRIGGER; - ent->clipmask = CONTENTS_SOLID|CONTENTS_TERRAIN; - if (ent->genericValue11) - { + ent->clipmask = CONTENTS_SOLID | CONTENTS_TERRAIN; + if (ent->genericValue11) { ent->touch = SiegeItemTouch; } - } - else - { //Make it solid. + } else { // Make it solid. ent->r.contents = MASK_PLAYERSOLID; ent->clipmask = MASK_PLAYERSOLID; } ent->think = SiegeItemThink; - ent->nextthink = level.time + FRAMETIME/2; + ent->nextthink = level.time + FRAMETIME / 2; - //take off nodraw + // take off nodraw ent->s.eFlags &= ~EF_NODRAW; - if (ent->paintarget && ent->paintarget[0]) - { //want to be on this guy's origin now then - gentity_t *targ = G_Find (NULL, FOFS(targetname), ent->paintarget); + if (ent->paintarget && ent->paintarget[0]) { // want to be on this guy's origin now then + gentity_t *targ = G_Find(NULL, FOFS(targetname), ent->paintarget); - if (targ && targ->inuse) - { - //perform a startsolid check to make sure the seige item doesn't get stuck - //in a wall or something + if (targ && targ->inuse) { + // perform a startsolid check to make sure the seige item doesn't get stuck + // in a wall or something trace_t tr; vec3_t TracePoint; VectorCopy(targ->r.currentOrigin, TracePoint); trap->Trace(&tr, targ->r.currentOrigin, ent->r.mins, ent->r.maxs, targ->r.currentOrigin, targ->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - {//bad spawning area, try again with the trace up a bit. + if (tr.startsolid) { // bad spawning area, try again with the trace up a bit. TracePoint[2] += 30; trap->Trace(&tr, TracePoint, ent->r.mins, ent->r.maxs, TracePoint, ent->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - {//hmm, well that didn't work. try one last time with the item back - //away from where the dude was facing (in case the carrier was - //close to something they were attacking.) + if (tr.startsolid) { // hmm, well that didn't work. try one last time with the item back + // away from where the dude was facing (in case the carrier was + // close to something they were attacking.) vec3_t fwd; - if(targ->client) - { - AngleVectors(targ->client->ps.viewangles,fwd, NULL, NULL); - } - else - { - AngleVectors(targ->r.currentAngles,fwd, NULL, NULL); + if (targ->client) { + AngleVectors(targ->client->ps.viewangles, fwd, NULL, NULL); + } else { + AngleVectors(targ->r.currentAngles, fwd, NULL, NULL); } VectorMA(TracePoint, -30, fwd, TracePoint); trap->Trace(&tr, TracePoint, ent->r.mins, ent->r.maxs, TracePoint, ent->s.number, ent->clipmask, qfalse, 0, 0); - if(tr.startsolid) - {//crap, that's all we got. just spawn at the defualt location. + if (tr.startsolid) { // crap, that's all we got. just spawn at the defualt location. return; } } } G_SetOrigin(ent, TracePoint); - //G_SetOrigin(ent, targ->r.currentOrigin); + // G_SetOrigin(ent, targ->r.currentOrigin); trap->LinkEntity((sharedEntity_t *)ent); } } @@ -1766,39 +1442,34 @@ health charge things only work with showhealth 1 on siege items that take damage "health_chargeamt" if non-0 will recharge this much health every... "health_chargerate" ...this many milliseconds */ -void SP_misc_siege_item (gentity_t *ent) -{ - int canpickup; - int noradar; - char *s; +void SP_misc_siege_item(gentity_t *ent) { + int canpickup; + int noradar; + char *s; - if (!siege_valid || level.gametype != GT_SIEGE) - { + if (!siege_valid || level.gametype != GT_SIEGE) { G_FreeEntity(ent); return; } - if (!ent->model || !ent->model[0]) - { - trap->Error( ERR_DROP, "You must specify a model for misc_siege_item types." ); + if (!ent->model || !ent->model[0]) { + trap->Error(ERR_DROP, "You must specify a model for misc_siege_item types."); } G_SpawnInt("canpickup", "1", &canpickup); G_SpawnInt("usephysics", "1", &ent->genericValue1); - if (ent->genericValue1) - { //if we're using physics we want lerporigin smoothing + if (ent->genericValue1) { // if we're using physics we want lerporigin smoothing ent->s.eFlags |= EF_CLIENTSMOOTH; } G_SpawnInt("noradar", "0", &noradar); - //Want it to always show up as a goal object on radar - if (!noradar && !(ent->spawnflags & SIEGEITEM_STARTOFFRADAR)) - { + // Want it to always show up as a goal object on radar + if (!noradar && !(ent->spawnflags & SIEGEITEM_STARTOFFRADAR)) { ent->s.eFlags |= EF_RADAROBJECT; } - //All clients want to know where it is at all times for radar + // All clients want to know where it is at all times for radar ent->r.svFlags |= SVF_BROADCAST; G_SpawnInt("pickuponlyonce", "1", &ent->genericValue4); @@ -1806,36 +1477,32 @@ void SP_misc_siege_item (gentity_t *ent) G_SpawnInt("teamnotouch", "0", &ent->genericValue6); G_SpawnInt("teamnocomplete", "0", &ent->genericValue7); - //Get default physics values. + // Get default physics values. G_SpawnFloat("mass", "0.09", &ent->mass); G_SpawnFloat("gravity", "3.0", &ent->radius); G_SpawnFloat("bounce", "1.3", &ent->random); - G_SpawnString( "pickupsound", "", &s ); + G_SpawnString("pickupsound", "", &s); - if (s && s[0]) - { //We have a pickup sound, so index it now. + if (s && s[0]) { // We have a pickup sound, so index it now. ent->noise_index = G_SoundIndex(s); } - G_SpawnString( "deathfx", "", &s ); + G_SpawnString("deathfx", "", &s); - if (s && s[0]) - { //We have a death effect, so index it now. + if (s && s[0]) { // We have a death effect, so index it now. ent->genericValue3 = G_EffectIndex(s); } - G_SpawnString( "respawnfx", "", &s ); + G_SpawnString("respawnfx", "", &s); - if (s && s[0]) - { //We have a respawn effect, so index it now. + if (s && s[0]) { // We have a respawn effect, so index it now. ent->genericValue10 = G_EffectIndex(s); } - G_SpawnString( "icon", "", &s ); + G_SpawnString("icon", "", &s); - if (s && s[0]) - { + if (s && s[0]) { // We have an icon, so index it now. We are reusing the genericenemyindex // variable rather than adding a new one to the entity state. ent->s.genericenemyindex = G_IconIndex(s); @@ -1843,19 +1510,18 @@ void SP_misc_siege_item (gentity_t *ent) ent->s.modelindex = G_ModelIndex(ent->model); - //Is the model a ghoul2 model? - if ( ent->model && !Q_stricmp( &ent->model[strlen(ent->model) - 4], ".glm" ) ) - { //apparently so. - ent->s.modelGhoul2 = 1; + // Is the model a ghoul2 model? + if (ent->model && !Q_stricmp(&ent->model[strlen(ent->model) - 4], ".glm")) { // apparently so. + ent->s.modelGhoul2 = 1; } ent->s.eType = ET_GENERAL; - //Set the mins/maxs with default values. + // Set the mins/maxs with default values. G_SpawnVector("mins", "-16 -16 -24", ent->r.mins); G_SpawnVector("maxs", "16 16 32", ent->r.maxs); - VectorCopy(ent->s.origin, ent->pos1); //store off the initial origin for respawning + VectorCopy(ent->s.origin, ent->pos1); // store off the initial origin for respawning G_SetOrigin(ent, ent->s.origin); VectorCopy(ent->s.angles, ent->r.currentAngles); @@ -1863,117 +1529,97 @@ void SP_misc_siege_item (gentity_t *ent) G_SpawnInt("forcelimit", "0", &ent->genericValue15); - if (ent->health > 0) - { //If it has health, it can be killed. + if (ent->health > 0) { // If it has health, it can be killed. int t; ent->pain = SiegeItemPain; ent->die = SiegeItemDie; ent->takedamage = qtrue; - G_SpawnInt( "showhealth", "0", &t ); - if (t) - { //a non-0 maxhealth value will mean we want to show the health on the hud + G_SpawnInt("showhealth", "0", &t); + if (t) { // a non-0 maxhealth value will mean we want to show the health on the hud ent->maxHealth = ent->health; G_ScaleNetHealth(ent); - G_SpawnInt( "health_chargeamt", "0", &ent->genericValue12); - G_SpawnInt( "health_chargerate", "0", &ent->genericValue13); + G_SpawnInt("health_chargeamt", "0", &ent->genericValue12); + G_SpawnInt("health_chargerate", "0", &ent->genericValue13); } - } - else - { //Otherwise no. + } else { // Otherwise no. ent->takedamage = qfalse; } - if (ent->spawnflags & SIEGEITEM_STARTOFFRADAR) - { + if (ent->spawnflags & SIEGEITEM_STARTOFFRADAR) { ent->use = SiegeItemUse; - } - else if (ent->targetname && ent->targetname[0]) - { - ent->s.eFlags |= EF_NODRAW; //kind of hacky, but whatever + } else if (ent->targetname && ent->targetname[0]) { + ent->s.eFlags |= EF_NODRAW; // kind of hacky, but whatever ent->genericValue11 = canpickup; - ent->use = SiegeItemUse; + ent->use = SiegeItemUse; ent->s.eFlags &= ~EF_RADAROBJECT; } - if ( (!ent->targetname || !ent->targetname[0]) || - (ent->spawnflags & SIEGEITEM_STARTOFFRADAR) ) - { - if (canpickup || !ent->takedamage) - { //We want to be able to walk into it to pick it up then. + if ((!ent->targetname || !ent->targetname[0]) || (ent->spawnflags & SIEGEITEM_STARTOFFRADAR)) { + if (canpickup || !ent->takedamage) { // We want to be able to walk into it to pick it up then. ent->r.contents = CONTENTS_TRIGGER; - ent->clipmask = CONTENTS_SOLID|CONTENTS_TERRAIN; - if (canpickup) - { + ent->clipmask = CONTENTS_SOLID | CONTENTS_TERRAIN; + if (canpickup) { ent->touch = SiegeItemTouch; } - } - else - { //Make it solid. + } else { // Make it solid. ent->r.contents = MASK_PLAYERSOLID; ent->clipmask = MASK_PLAYERSOLID; } ent->think = SiegeItemThink; - ent->nextthink = level.time + FRAMETIME/2; + ent->nextthink = level.time + FRAMETIME / 2; } - ent->genericValue8 = ENTITYNUM_NONE; //initialize the carrier to none + ent->genericValue8 = ENTITYNUM_NONE; // initialize the carrier to none - ent->neverFree = qtrue; //never free us unless we specifically request it. + ent->neverFree = qtrue; // never free us unless we specifically request it. trap->LinkEntity((sharedEntity_t *)ent); } -//sends extra data about other client's in this client's PVS -//used for support guy etc. -//with this formatting: -//sxd 16,999,999,999|17,999,999,999 -//assumed max 2 chars for cl num, 3 chars per ammo/health/maxhealth, even a single string full of -//info for all 32 clients should not get much past 450 bytes, which is well within a -//reasonable range. We don't need to send anything about the max ammo or current weapon, because -//currentState.weapon can be checked for the ent in question on the client. -rww -void G_SiegeClientExData(gentity_t *msgTarg) -{ +// sends extra data about other client's in this client's PVS +// used for support guy etc. +// with this formatting: +// sxd 16,999,999,999|17,999,999,999 +// assumed max 2 chars for cl num, 3 chars per ammo/health/maxhealth, even a single string full of +// info for all 32 clients should not get much past 450 bytes, which is well within a +// reasonable range. We don't need to send anything about the max ammo or current weapon, because +// currentState.weapon can be checked for the ent in question on the client. -rww +void G_SiegeClientExData(gentity_t *msgTarg) { gentity_t *ent; int count = 0; int i = 0; char str[MAX_STRING_CHARS]; char scratch[MAX_STRING_CHARS]; - while (i < level.num_entities && count < MAX_EXDATA_ENTS_TO_SEND) - { + while (i < level.num_entities && count < MAX_EXDATA_ENTS_TO_SEND) { ent = &g_entities[i]; - if (ent->inuse && ent->client && msgTarg->s.number != ent->s.number && - ent->s.eType == ET_PLAYER && msgTarg->client->sess.sessionTeam == ent->client->sess.sessionTeam && - trap->InPVS(msgTarg->client->ps.origin, ent->client->ps.origin)) - { //another client in the same pvs, send his jive - if (count) - { //append a separating space if we are not the first in the list + if (ent->inuse && ent->client && msgTarg->s.number != ent->s.number && ent->s.eType == ET_PLAYER && + msgTarg->client->sess.sessionTeam == ent->client->sess.sessionTeam && + trap->InPVS(msgTarg->client->ps.origin, ent->client->ps.origin)) { // another client in the same pvs, send his jive + if (count) { // append a separating space if we are not the first in the list Q_strcat(str, sizeof(str), " "); - } - else - { //otherwise create the prepended chunk + } else { // otherwise create the prepended chunk strcpy(str, "sxd "); } - //append the stats - Com_sprintf(scratch, sizeof(scratch), "%i|%i|%i|%i", ent->s.number, ent->client->ps.stats[STAT_HEALTH], - ent->client->ps.stats[STAT_MAX_HEALTH], ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex]); + // append the stats + Com_sprintf(scratch, sizeof(scratch), "%i|%i|%i|%i", ent->s.number, ent->client->ps.stats[STAT_HEALTH], ent->client->ps.stats[STAT_MAX_HEALTH], + ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex]); Q_strcat(str, sizeof(str), scratch); count++; } i++; } - if (!count) - { //nothing to send + if (!count) { // nothing to send return; } - //send the string to him - trap->SendServerCommand(msgTarg-g_entities, str); + // send the string to him + trap->SendServerCommand(msgTarg - g_entities, str); } diff --git a/codemp/game/g_session.c b/codemp/game/g_session.c index d582337126..ce7b262349 100644 --- a/codemp/game/g_session.c +++ b/codemp/game/g_session.c @@ -34,7 +34,7 @@ and tournament restarts. ======================================================================= */ -//TODO: Replace with reading/writing to file(s) +// TODO: Replace with reading/writing to file(s) /* ================ @@ -43,48 +43,46 @@ G_WriteClientSessionData Called on game shutdown ================ */ -void G_WriteClientSessionData( gclient_t *client ) -{ - char s[MAX_CVAR_VALUE_STRING] = {0}, - siegeClass[64] = {0}, IP[NET_ADDRSTRMAXLEN] = {0}; - const char *var; - int i = 0; +void G_WriteClientSessionData(gclient_t *client) { + char s[MAX_CVAR_VALUE_STRING] = {0}, siegeClass[64] = {0}, IP[NET_ADDRSTRMAXLEN] = {0}; + const char *var; + int i = 0; // for the strings, replace ' ' with 1 - Q_strncpyz( siegeClass, client->sess.siegeClass, sizeof( siegeClass ) ); - for ( i=0; siegeClass[i]; i++ ) { + Q_strncpyz(siegeClass, client->sess.siegeClass, sizeof(siegeClass)); + for (i = 0; siegeClass[i]; i++) { if (siegeClass[i] == ' ') siegeClass[i] = 1; } - if ( !siegeClass[0] ) - Q_strncpyz( siegeClass, "none", sizeof( siegeClass ) ); + if (!siegeClass[0]) + Q_strncpyz(siegeClass, "none", sizeof(siegeClass)); - Q_strncpyz( IP, client->sess.IP, sizeof( IP ) ); - for ( i=0; IP[i]; i++ ) { + Q_strncpyz(IP, client->sess.IP, sizeof(IP)); + for (i = 0; IP[i]; i++) { if (IP[i] == ' ') IP[i] = 1; } // Make sure there is no space on the last entry - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.sessionTeam ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.spectatorNum ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.spectatorState ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.spectatorClient ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.wins ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.losses ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.teamLeader ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.setForce ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.saberLevel ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.selectedFP ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.duelTeam ) ); - Q_strcat( s, sizeof( s ), va( "%i ", client->sess.siegeDesiredTeam ) ); - Q_strcat( s, sizeof( s ), va( "%s ", siegeClass ) ); - Q_strcat( s, sizeof( s ), va( "%s", IP ) ); - - var = va( "session%i", client - level.clients ); - - trap->Cvar_Set( var, s ); + Q_strcat(s, sizeof(s), va("%i ", client->sess.sessionTeam)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.spectatorNum)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.spectatorState)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.spectatorClient)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.wins)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.losses)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.teamLeader)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.setForce)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.saberLevel)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.selectedFP)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.duelTeam)); + Q_strcat(s, sizeof(s), va("%i ", client->sess.siegeDesiredTeam)); + Q_strcat(s, sizeof(s), va("%s ", siegeClass)); + Q_strcat(s, sizeof(s), va("%s", IP)); + + var = va("session%i", client - level.clients); + + trap->Cvar_Set(var, s); } /* @@ -94,45 +92,34 @@ G_ReadSessionData Called on a reconnect ================ */ -void G_ReadSessionData( gclient_t *client ) -{ - char s[MAX_CVAR_VALUE_STRING] = {0}; - const char *var; - int i=0, tempSessionTeam=0, tempSpectatorState, tempTeamLeader; - - var = va( "session%i", client - level.clients ); - trap->Cvar_VariableStringBuffer( var, s, sizeof(s) ); - - sscanf( s, "%i %i %i %i %i %i %i %i %i %i %i %i %s %s", - &tempSessionTeam, //&client->sess.sessionTeam, - &client->sess.spectatorNum, - &tempSpectatorState, //&client->sess.spectatorState, - &client->sess.spectatorClient, - &client->sess.wins, - &client->sess.losses, - &tempTeamLeader, //&client->sess.teamLeader, - &client->sess.setForce, - &client->sess.saberLevel, - &client->sess.selectedFP, - &client->sess.duelTeam, - &client->sess.siegeDesiredTeam, - client->sess.siegeClass, - client->sess.IP - ); - - client->sess.sessionTeam = (team_t)tempSessionTeam; - client->sess.spectatorState = (spectatorState_t)tempSpectatorState; - client->sess.teamLeader = (qboolean)tempTeamLeader; +void G_ReadSessionData(gclient_t *client) { + char s[MAX_CVAR_VALUE_STRING] = {0}; + const char *var; + int i = 0, tempSessionTeam = 0, tempSpectatorState, tempTeamLeader; + + var = va("session%i", client - level.clients); + trap->Cvar_VariableStringBuffer(var, s, sizeof(s)); + + sscanf(s, "%i %i %i %i %i %i %i %i %i %i %i %i %s %s", + &tempSessionTeam, //&client->sess.sessionTeam, + &client->sess.spectatorNum, + &tempSpectatorState, //&client->sess.spectatorState, + &client->sess.spectatorClient, &client->sess.wins, &client->sess.losses, + &tempTeamLeader, //&client->sess.teamLeader, + &client->sess.setForce, &client->sess.saberLevel, &client->sess.selectedFP, &client->sess.duelTeam, &client->sess.siegeDesiredTeam, + client->sess.siegeClass, client->sess.IP); + + client->sess.sessionTeam = (team_t)tempSessionTeam; + client->sess.spectatorState = (spectatorState_t)tempSpectatorState; + client->sess.teamLeader = (qboolean)tempTeamLeader; // convert back to spaces from unused chars, as session data is written that way. - for ( i=0; client->sess.siegeClass[i]; i++ ) - { + for (i = 0; client->sess.siegeClass[i]; i++) { if (client->sess.siegeClass[i] == 1) client->sess.siegeClass[i] = ' '; } - for ( i=0; client->sess.IP[i]; i++ ) - { + for (i = 0; client->sess.IP[i]; i++) { if (client->sess.IP[i] == 1) client->sess.IP[i] = ' '; } @@ -142,7 +129,6 @@ void G_ReadSessionData( gclient_t *client ) client->ps.fd.forcePowerSelected = client->sess.selectedFP; } - /* ================ G_InitSessionData @@ -150,57 +136,48 @@ G_InitSessionData Called on a first-time connect ================ */ -void G_InitSessionData( gclient_t *client, char *userinfo, qboolean isBot ) { - clientSession_t *sess; - const char *value; +void G_InitSessionData(gclient_t *client, char *userinfo, qboolean isBot) { + clientSession_t *sess; + const char *value; sess = &client->sess; client->sess.siegeDesiredTeam = TEAM_FREE; // initial team determination - if ( level.gametype >= GT_TEAM ) { - if ( g_teamAutoJoin.integer && !(g_entities[client-level.clients].r.svFlags & SVF_BOT) ) { - sess->sessionTeam = PickTeam( -1 ); - client->ps.fd.forceDoInit = 1; //every time we change teams make sure our force powers are set right + if (level.gametype >= GT_TEAM) { + if (g_teamAutoJoin.integer && !(g_entities[client - level.clients].r.svFlags & SVF_BOT)) { + sess->sessionTeam = PickTeam(-1); + client->ps.fd.forceDoInit = 1; // every time we change teams make sure our force powers are set right } else { // always spawn as spectator in team games - if (!isBot) - { + if (!isBot) { sess->sessionTeam = TEAM_SPECTATOR; - } - else - { //Bots choose their team on creation - value = Info_ValueForKey( userinfo, "team" ); - if (value[0] == 'r' || value[0] == 'R') - { + } else { // Bots choose their team on creation + value = Info_ValueForKey(userinfo, "team"); + if (value[0] == 'r' || value[0] == 'R') { sess->sessionTeam = TEAM_RED; - } - else if (value[0] == 'b' || value[0] == 'B') - { + } else if (value[0] == 'b' || value[0] == 'B') { sess->sessionTeam = TEAM_BLUE; + } else { + sess->sessionTeam = PickTeam(-1); } - else - { - sess->sessionTeam = PickTeam( -1 ); - } - client->ps.fd.forceDoInit = 1; //every time we change teams make sure our force powers are set right + client->ps.fd.forceDoInit = 1; // every time we change teams make sure our force powers are set right } } } else { - value = Info_ValueForKey( userinfo, "team" ); - if ( value[0] == 's' ) { + value = Info_ValueForKey(userinfo, "team"); + if (value[0] == 's') { // a willing spectator, not a waiting-in-line sess->sessionTeam = TEAM_SPECTATOR; } else { - switch ( level.gametype ) { + switch (level.gametype) { default: case GT_FFA: case GT_HOLOCRON: case GT_JEDIMASTER: case GT_SINGLE_PLAYER: - if ( g_maxGameClients.integer > 0 && - level.numNonSpectatorClients >= g_maxGameClients.integer ) { + if (g_maxGameClients.integer > 0 && level.numNonSpectatorClients >= g_maxGameClients.integer) { sess->sessionTeam = TEAM_SPECTATOR; } else { sess->sessionTeam = TEAM_FREE; @@ -208,26 +185,23 @@ void G_InitSessionData( gclient_t *client, char *userinfo, qboolean isBot ) { break; case GT_DUEL: // if the game is full, go into a waiting mode - if ( level.numNonSpectatorClients >= 2 ) { + if (level.numNonSpectatorClients >= 2) { sess->sessionTeam = TEAM_SPECTATOR; } else { sess->sessionTeam = TEAM_FREE; } break; case GT_POWERDUEL: - //sess->duelTeam = DUELTEAM_LONE; //default + // sess->duelTeam = DUELTEAM_LONE; //default { int loners = 0; int doubles = 0; G_PowerDuelCount(&loners, &doubles, qtrue); - if (!doubles || loners > (doubles/2)) - { + if (!doubles || loners > (doubles / 2)) { sess->duelTeam = DUELTEAM_DOUBLE; - } - else - { + } else { sess->duelTeam = DUELTEAM_LONE; } } @@ -242,28 +216,27 @@ void G_InitSessionData( gclient_t *client, char *userinfo, qboolean isBot ) { sess->siegeClass[0] = 0; - G_WriteClientSessionData( client ); + G_WriteClientSessionData(client); } - /* ================== G_InitWorldSession ================== */ -void G_InitWorldSession( void ) { - char s[MAX_STRING_CHARS]; - int gt; +void G_InitWorldSession(void) { + char s[MAX_STRING_CHARS]; + int gt; - trap->Cvar_VariableStringBuffer( "session", s, sizeof(s) ); - gt = atoi( s ); + trap->Cvar_VariableStringBuffer("session", s, sizeof(s)); + gt = atoi(s); // if the gametype changed since the last session, don't use any // client sessions - if ( level.gametype != gt ) { + if (level.gametype != gt) { level.newSession = qtrue; - trap->Print( "Gametype changed, clearing session data.\n" ); + trap->Print("Gametype changed, clearing session data.\n"); } } @@ -273,14 +246,14 @@ G_WriteSessionData ================== */ -void G_WriteSessionData( void ) { - int i; +void G_WriteSessionData(void) { + int i; - trap->Cvar_Set( "session", va("%i", level.gametype) ); + trap->Cvar_Set("session", va("%i", level.gametype)); - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected == CON_CONNECTED ) { - G_WriteClientSessionData( &level.clients[i] ); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { + G_WriteClientSessionData(&level.clients[i]); } } } diff --git a/codemp/game/g_spawn.c b/codemp/game/g_spawn.c index 44f991b073..6b4139ac93 100644 --- a/codemp/game/g_spawn.c +++ b/codemp/game/g_spawn.c @@ -23,16 +23,16 @@ along with this program; if not, see . #include "g_local.h" -qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) { - int i; +qboolean G_SpawnString(const char *key, const char *defaultString, char **out) { + int i; - if ( !level.spawning ) { + if (!level.spawning) { *out = (char *)defaultString; -// trap->Error( ERR_DROP, "G_SpawnString() called while not spawning" ); + // trap->Error( ERR_DROP, "G_SpawnString() called while not spawning" ); } - for ( i = 0 ; i < level.numSpawnVars ; i++ ) { - if ( !Q_stricmp( key, level.spawnVars[i][0] ) ) { + for (i = 0; i < level.numSpawnVars; i++) { + if (!Q_stricmp(key, level.spawnVars[i][0])) { *out = level.spawnVars[i][1]; return qtrue; } @@ -42,46 +42,46 @@ qboolean G_SpawnString( const char *key, const char *defaultString, char **out ) return qfalse; } -qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnFloat(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atof( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atof(s); return present; } -qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ) { - char *s; - qboolean present; +qboolean G_SpawnInt(const char *key, const char *defaultString, int *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - *out = atoi( s ); + present = G_SpawnString(key, defaultString, &s); + *out = atoi(s); return present; } -qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ) { - char *s; - qboolean present; +qboolean G_SpawnVector(const char *key, const char *defaultString, float *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); - if ( sscanf( s, "%f %f %f", &out[0], &out[1], &out[2] ) != 3 ) { - trap->Print( "G_SpawnVector: Failed sscanf on %s (default: %s)\n", key, defaultString ); - VectorClear( out ); + present = G_SpawnString(key, defaultString, &s); + if (sscanf(s, "%f %f %f", &out[0], &out[1], &out[2]) != 3) { + trap->Print("G_SpawnVector: Failed sscanf on %s (default: %s)\n", key, defaultString); + VectorClear(out); return qfalse; } return present; } -qboolean G_SpawnBoolean( const char *key, const char *defaultString, qboolean *out ) { - char *s; - qboolean present; +qboolean G_SpawnBoolean(const char *key, const char *defaultString, qboolean *out) { + char *s; + qboolean present; - present = G_SpawnString( key, defaultString, &s ); + present = G_SpawnString(key, defaultString, &s); - if ( !Q_stricmp( s, "qtrue" ) || !Q_stricmp( s, "true" ) || !Q_stricmp( s, "yes" ) || !Q_stricmp( s, "1" ) ) + if (!Q_stricmp(s, "qtrue") || !Q_stricmp(s, "true") || !Q_stricmp(s, "yes") || !Q_stricmp(s, "1")) *out = qtrue; - else if ( !Q_stricmp( s, "qfalse" ) || !Q_stricmp( s, "false" ) || !Q_stricmp( s, "no" ) || !Q_stricmp( s, "0" ) ) + else if (!Q_stricmp(s, "qfalse") || !Q_stricmp(s, "false") || !Q_stricmp(s, "no") || !Q_stricmp(s, "0")) *out = qfalse; else *out = qfalse; @@ -95,594 +95,576 @@ qboolean G_SpawnBoolean( const char *key, const char *defaultString, qboolean *o typedef enum { F_INT, F_FLOAT, - F_STRING, // string on disk, pointer in memory + F_STRING, // string on disk, pointer in memory F_VECTOR, F_ANGLEHACK, - F_PARM1, // Special case for parms - F_PARM2, // Special case for parms - F_PARM3, // Special case for parms - F_PARM4, // Special case for parms - F_PARM5, // Special case for parms - F_PARM6, // Special case for parms - F_PARM7, // Special case for parms - F_PARM8, // Special case for parms - F_PARM9, // Special case for parms - F_PARM10, // Special case for parms - F_PARM11, // Special case for parms - F_PARM12, // Special case for parms - F_PARM13, // Special case for parms - F_PARM14, // Special case for parms - F_PARM15, // Special case for parms - F_PARM16 // Special case for parms + F_PARM1, // Special case for parms + F_PARM2, // Special case for parms + F_PARM3, // Special case for parms + F_PARM4, // Special case for parms + F_PARM5, // Special case for parms + F_PARM6, // Special case for parms + F_PARM7, // Special case for parms + F_PARM8, // Special case for parms + F_PARM9, // Special case for parms + F_PARM10, // Special case for parms + F_PARM11, // Special case for parms + F_PARM12, // Special case for parms + F_PARM13, // Special case for parms + F_PARM14, // Special case for parms + F_PARM15, // Special case for parms + F_PARM16 // Special case for parms } fieldtype_t; typedef struct field_s { - const char *name; - size_t ofs; - fieldtype_t type; + const char *name; + size_t ofs; + fieldtype_t type; } field_t; field_t fields[] = { - { "alliedteam", FOFS( alliedTeam ), F_INT },//for misc_turrets - { "angerscript", FOFS( behaviorSet[BSET_ANGER] ), F_STRING },//name of script to run - { "angle", FOFS( s.angles ), F_ANGLEHACK }, - { "angles", FOFS( s.angles ), F_VECTOR }, - { "attackscript", FOFS( behaviorSet[BSET_ATTACK] ), F_STRING },//name of script to run - { "awakescript", FOFS( behaviorSet[BSET_AWAKE] ), F_STRING },//name of script to run - { "blockedscript", FOFS( behaviorSet[BSET_BLOCKED] ), F_STRING },//name of script to run - { "chunksize", FOFS( mass ), F_FLOAT },//for func_breakables - { "classname", FOFS( classname ), F_STRING }, - { "closetarget", FOFS( closetarget ), F_STRING },//for doors - { "count", FOFS( count ), F_INT }, - { "deathscript", FOFS( behaviorSet[BSET_DEATH] ), F_STRING },//name of script to run - { "delay", FOFS( delay ), F_INT }, - { "delayscript", FOFS( behaviorSet[BSET_DELAYED] ), F_STRING },//name of script to run - { "delayscripttime", FOFS( delayScriptTime ), F_INT },//name of script to run - { "dmg", FOFS( damage ), F_INT }, - { "ffdeathscript", FOFS( behaviorSet[BSET_FFDEATH] ), F_STRING },//name of script to run - { "ffirescript", FOFS( behaviorSet[BSET_FFIRE] ), F_STRING },//name of script to run - { "fleescript", FOFS( behaviorSet[BSET_FLEE] ), F_STRING },//name of script to run - { "fullname", FOFS( fullName ), F_STRING }, - { "goaltarget", FOFS( goaltarget ), F_STRING },//for siege - { "healingclass", FOFS( healingclass ), F_STRING }, - { "healingrate", FOFS( healingrate ), F_INT }, - { "healingsound", FOFS( healingsound ), F_STRING }, - { "health", FOFS( health ), F_INT }, - { "idealclass", FOFS( idealclass ), F_STRING },//for siege spawnpoints - { "linear", FOFS( alt_fire ), F_INT },//for movers to use linear movement - { "lostenemyscript", FOFS( behaviorSet[BSET_LOSTENEMY] ), F_STRING },//name of script to run - { "message", FOFS( message ), F_STRING }, - { "mindtrickscript", FOFS( behaviorSet[BSET_MINDTRICK] ), F_STRING },//name of script to run - { "model", FOFS( model ), F_STRING }, - { "model2", FOFS( model2 ), F_STRING }, - { "npc_target", FOFS( NPC_target ), F_STRING }, - { "npc_target2", FOFS( target2 ), F_STRING },//NPC_spawner only - { "npc_target4", FOFS( target4 ), F_STRING },//NPC_spawner only - { "npc_targetname", FOFS( NPC_targetname ), F_STRING }, - { "npc_type", FOFS( NPC_type ), F_STRING }, - { "numchunks", FOFS( radius ), F_FLOAT },//for func_breakables - { "opentarget", FOFS( opentarget ), F_STRING },//for doors - { "origin", FOFS( s.origin ), F_VECTOR }, - { "ownername", FOFS( ownername ), F_STRING }, - { "painscript", FOFS( behaviorSet[BSET_PAIN] ), F_STRING },//name of script to run - { "paintarget", FOFS( paintarget ), F_STRING },//for doors - { "parm1", 0, F_PARM1 }, - { "parm10", 0, F_PARM10 }, - { "parm11", 0, F_PARM11 }, - { "parm12", 0, F_PARM12 }, - { "parm13", 0, F_PARM13 }, - { "parm14", 0, F_PARM14 }, - { "parm15", 0, F_PARM15 }, - { "parm16", 0, F_PARM16 }, - { "parm2", 0, F_PARM2 }, - { "parm3", 0, F_PARM3 }, - { "parm4", 0, F_PARM4 }, - { "parm5", 0, F_PARM5 }, - { "parm6", 0, F_PARM6 }, - { "parm7", 0, F_PARM7 }, - { "parm8", 0, F_PARM8 }, - { "parm9", 0, F_PARM9 }, - { "radius", FOFS( radius ), F_FLOAT }, - { "random", FOFS( random ), F_FLOAT }, - { "roffname", FOFS( roffname ), F_STRING }, - { "rofftarget", FOFS( rofftarget ), F_STRING }, - { "script_targetname", FOFS( script_targetname ), F_STRING },//scripts look for this when "affecting" - { "soundset", FOFS( soundSet ), F_STRING }, - { "spawnflags", FOFS( spawnflags ), F_INT }, - { "spawnscript", FOFS( behaviorSet[BSET_SPAWN] ), F_STRING },//name of script to run - { "speed", FOFS( speed ), F_FLOAT }, - { "target", FOFS( target ), F_STRING }, - { "target2", FOFS( target2 ), F_STRING }, - { "target3", FOFS( target3 ), F_STRING }, - { "target4", FOFS( target4 ), F_STRING }, - { "target5", FOFS( target5 ), F_STRING }, - { "target6", FOFS( target6 ), F_STRING }, - { "targetname", FOFS( targetname ), F_STRING }, - { "targetshadername", FOFS( targetShaderName ), F_STRING }, - { "targetshadernewname", FOFS( targetShaderNewName ), F_STRING }, - { "team", FOFS( team ), F_STRING }, - { "teamnodmg", FOFS( teamnodmg ), F_INT }, - { "teamowner", FOFS( s.teamowner ), F_INT }, - { "teamuser", FOFS( alliedTeam ), F_INT }, - { "usescript", FOFS( behaviorSet[BSET_USE] ), F_STRING },//name of script to run - { "victoryscript", FOFS( behaviorSet[BSET_VICTORY] ), F_STRING },//name of script to run - { "wait", FOFS( wait ), F_FLOAT }, + {"alliedteam", FOFS(alliedTeam), F_INT}, // for misc_turrets + {"angerscript", FOFS(behaviorSet[BSET_ANGER]), F_STRING}, // name of script to run + {"angle", FOFS(s.angles), F_ANGLEHACK}, + {"angles", FOFS(s.angles), F_VECTOR}, + {"attackscript", FOFS(behaviorSet[BSET_ATTACK]), F_STRING}, // name of script to run + {"awakescript", FOFS(behaviorSet[BSET_AWAKE]), F_STRING}, // name of script to run + {"blockedscript", FOFS(behaviorSet[BSET_BLOCKED]), F_STRING}, // name of script to run + {"chunksize", FOFS(mass), F_FLOAT}, // for func_breakables + {"classname", FOFS(classname), F_STRING}, + {"closetarget", FOFS(closetarget), F_STRING}, // for doors + {"count", FOFS(count), F_INT}, + {"deathscript", FOFS(behaviorSet[BSET_DEATH]), F_STRING}, // name of script to run + {"delay", FOFS(delay), F_INT}, + {"delayscript", FOFS(behaviorSet[BSET_DELAYED]), F_STRING}, // name of script to run + {"delayscripttime", FOFS(delayScriptTime), F_INT}, // name of script to run + {"dmg", FOFS(damage), F_INT}, + {"ffdeathscript", FOFS(behaviorSet[BSET_FFDEATH]), F_STRING}, // name of script to run + {"ffirescript", FOFS(behaviorSet[BSET_FFIRE]), F_STRING}, // name of script to run + {"fleescript", FOFS(behaviorSet[BSET_FLEE]), F_STRING}, // name of script to run + {"fullname", FOFS(fullName), F_STRING}, + {"goaltarget", FOFS(goaltarget), F_STRING}, // for siege + {"healingclass", FOFS(healingclass), F_STRING}, + {"healingrate", FOFS(healingrate), F_INT}, + {"healingsound", FOFS(healingsound), F_STRING}, + {"health", FOFS(health), F_INT}, + {"idealclass", FOFS(idealclass), F_STRING}, // for siege spawnpoints + {"linear", FOFS(alt_fire), F_INT}, // for movers to use linear movement + {"lostenemyscript", FOFS(behaviorSet[BSET_LOSTENEMY]), F_STRING}, // name of script to run + {"message", FOFS(message), F_STRING}, + {"mindtrickscript", FOFS(behaviorSet[BSET_MINDTRICK]), F_STRING}, // name of script to run + {"model", FOFS(model), F_STRING}, + {"model2", FOFS(model2), F_STRING}, + {"npc_target", FOFS(NPC_target), F_STRING}, + {"npc_target2", FOFS(target2), F_STRING}, // NPC_spawner only + {"npc_target4", FOFS(target4), F_STRING}, // NPC_spawner only + {"npc_targetname", FOFS(NPC_targetname), F_STRING}, + {"npc_type", FOFS(NPC_type), F_STRING}, + {"numchunks", FOFS(radius), F_FLOAT}, // for func_breakables + {"opentarget", FOFS(opentarget), F_STRING}, // for doors + {"origin", FOFS(s.origin), F_VECTOR}, + {"ownername", FOFS(ownername), F_STRING}, + {"painscript", FOFS(behaviorSet[BSET_PAIN]), F_STRING}, // name of script to run + {"paintarget", FOFS(paintarget), F_STRING}, // for doors + {"parm1", 0, F_PARM1}, + {"parm10", 0, F_PARM10}, + {"parm11", 0, F_PARM11}, + {"parm12", 0, F_PARM12}, + {"parm13", 0, F_PARM13}, + {"parm14", 0, F_PARM14}, + {"parm15", 0, F_PARM15}, + {"parm16", 0, F_PARM16}, + {"parm2", 0, F_PARM2}, + {"parm3", 0, F_PARM3}, + {"parm4", 0, F_PARM4}, + {"parm5", 0, F_PARM5}, + {"parm6", 0, F_PARM6}, + {"parm7", 0, F_PARM7}, + {"parm8", 0, F_PARM8}, + {"parm9", 0, F_PARM9}, + {"radius", FOFS(radius), F_FLOAT}, + {"random", FOFS(random), F_FLOAT}, + {"roffname", FOFS(roffname), F_STRING}, + {"rofftarget", FOFS(rofftarget), F_STRING}, + {"script_targetname", FOFS(script_targetname), F_STRING}, // scripts look for this when "affecting" + {"soundset", FOFS(soundSet), F_STRING}, + {"spawnflags", FOFS(spawnflags), F_INT}, + {"spawnscript", FOFS(behaviorSet[BSET_SPAWN]), F_STRING}, // name of script to run + {"speed", FOFS(speed), F_FLOAT}, + {"target", FOFS(target), F_STRING}, + {"target2", FOFS(target2), F_STRING}, + {"target3", FOFS(target3), F_STRING}, + {"target4", FOFS(target4), F_STRING}, + {"target5", FOFS(target5), F_STRING}, + {"target6", FOFS(target6), F_STRING}, + {"targetname", FOFS(targetname), F_STRING}, + {"targetshadername", FOFS(targetShaderName), F_STRING}, + {"targetshadernewname", FOFS(targetShaderNewName), F_STRING}, + {"team", FOFS(team), F_STRING}, + {"teamnodmg", FOFS(teamnodmg), F_INT}, + {"teamowner", FOFS(s.teamowner), F_INT}, + {"teamuser", FOFS(alliedTeam), F_INT}, + {"usescript", FOFS(behaviorSet[BSET_USE]), F_STRING}, // name of script to run + {"victoryscript", FOFS(behaviorSet[BSET_VICTORY]), F_STRING}, // name of script to run + {"wait", FOFS(wait), F_FLOAT}, }; typedef struct spawn_s { - const char *name; - void (*spawn)(gentity_t *ent); + const char *name; + void (*spawn)(gentity_t *ent); } spawn_t; -void SP_info_player_start (gentity_t *ent); -void SP_info_player_duel( gentity_t *ent ); -void SP_info_player_duel1( gentity_t *ent ); -void SP_info_player_duel2( gentity_t *ent ); -void SP_info_player_deathmatch (gentity_t *ent); -void SP_info_player_siegeteam1 (gentity_t *ent); -void SP_info_player_siegeteam2 (gentity_t *ent); -void SP_info_player_intermission (gentity_t *ent); -void SP_info_player_intermission_red (gentity_t *ent); -void SP_info_player_intermission_blue (gentity_t *ent); -void SP_info_jedimaster_start (gentity_t *ent); -void SP_info_player_start_red (gentity_t *ent); -void SP_info_player_start_blue (gentity_t *ent); +void SP_info_player_start(gentity_t *ent); +void SP_info_player_duel(gentity_t *ent); +void SP_info_player_duel1(gentity_t *ent); +void SP_info_player_duel2(gentity_t *ent); +void SP_info_player_deathmatch(gentity_t *ent); +void SP_info_player_siegeteam1(gentity_t *ent); +void SP_info_player_siegeteam2(gentity_t *ent); +void SP_info_player_intermission(gentity_t *ent); +void SP_info_player_intermission_red(gentity_t *ent); +void SP_info_player_intermission_blue(gentity_t *ent); +void SP_info_jedimaster_start(gentity_t *ent); +void SP_info_player_start_red(gentity_t *ent); +void SP_info_player_start_blue(gentity_t *ent); void SP_info_firstplace(gentity_t *ent); void SP_info_secondplace(gentity_t *ent); void SP_info_thirdplace(gentity_t *ent); void SP_info_podium(gentity_t *ent); -void SP_info_siege_objective (gentity_t *ent); -void SP_info_siege_radaricon (gentity_t *ent); -void SP_info_siege_decomplete (gentity_t *ent); -void SP_target_siege_end (gentity_t *ent); -void SP_misc_siege_item (gentity_t *ent); - -void SP_func_plat (gentity_t *ent); -void SP_func_static (gentity_t *ent); -void SP_func_rotating (gentity_t *ent); -void SP_func_bobbing (gentity_t *ent); -void SP_func_pendulum( gentity_t *ent ); -void SP_func_button (gentity_t *ent); -void SP_func_door (gentity_t *ent); -void SP_func_train (gentity_t *ent); -void SP_func_timer (gentity_t *self); -void SP_func_breakable (gentity_t *ent); -void SP_func_glass (gentity_t *ent); -void SP_func_usable( gentity_t *ent); -void SP_func_wall( gentity_t *ent ); - -void SP_trigger_lightningstrike( gentity_t *ent ); - -void SP_trigger_always (gentity_t *ent); -void SP_trigger_multiple (gentity_t *ent); -void SP_trigger_once( gentity_t *ent ); -void SP_trigger_push (gentity_t *ent); -void SP_trigger_teleport (gentity_t *ent); -void SP_trigger_hurt (gentity_t *ent); +void SP_info_siege_objective(gentity_t *ent); +void SP_info_siege_radaricon(gentity_t *ent); +void SP_info_siege_decomplete(gentity_t *ent); +void SP_target_siege_end(gentity_t *ent); +void SP_misc_siege_item(gentity_t *ent); + +void SP_func_plat(gentity_t *ent); +void SP_func_static(gentity_t *ent); +void SP_func_rotating(gentity_t *ent); +void SP_func_bobbing(gentity_t *ent); +void SP_func_pendulum(gentity_t *ent); +void SP_func_button(gentity_t *ent); +void SP_func_door(gentity_t *ent); +void SP_func_train(gentity_t *ent); +void SP_func_timer(gentity_t *self); +void SP_func_breakable(gentity_t *ent); +void SP_func_glass(gentity_t *ent); +void SP_func_usable(gentity_t *ent); +void SP_func_wall(gentity_t *ent); + +void SP_trigger_lightningstrike(gentity_t *ent); + +void SP_trigger_always(gentity_t *ent); +void SP_trigger_multiple(gentity_t *ent); +void SP_trigger_once(gentity_t *ent); +void SP_trigger_push(gentity_t *ent); +void SP_trigger_teleport(gentity_t *ent); +void SP_trigger_hurt(gentity_t *ent); void SP_trigger_space(gentity_t *self); void SP_trigger_shipboundary(gentity_t *self); void SP_trigger_hyperspace(gentity_t *self); void SP_trigger_asteroid_field(gentity_t *self); -void SP_target_remove_powerups( gentity_t *ent ); -void SP_target_give (gentity_t *ent); -void SP_target_delay (gentity_t *ent); -void SP_target_speaker (gentity_t *ent); -void SP_target_print (gentity_t *ent); -void SP_target_laser (gentity_t *self); -void SP_target_character (gentity_t *ent); -void SP_target_score( gentity_t *ent ); -void SP_target_teleporter( gentity_t *ent ); -void SP_target_relay (gentity_t *ent); -void SP_target_kill (gentity_t *ent); -void SP_target_position (gentity_t *ent); -void SP_target_location (gentity_t *ent); -void SP_target_counter (gentity_t *self); -void SP_target_random (gentity_t *self); -void SP_target_scriptrunner( gentity_t *self ); -void SP_target_interest (gentity_t *self); -void SP_target_activate (gentity_t *self); -void SP_target_deactivate (gentity_t *self); -void SP_target_level_change( gentity_t *self ); -void SP_target_play_music( gentity_t *self ); -void SP_target_push (gentity_t *ent); - -void SP_light (gentity_t *self); -void SP_info_null (gentity_t *self); -void SP_info_notnull (gentity_t *self); -void SP_info_camp (gentity_t *self); -void SP_path_corner (gentity_t *self); - -void SP_misc_teleporter_dest (gentity_t *self); +void SP_target_remove_powerups(gentity_t *ent); +void SP_target_give(gentity_t *ent); +void SP_target_delay(gentity_t *ent); +void SP_target_speaker(gentity_t *ent); +void SP_target_print(gentity_t *ent); +void SP_target_laser(gentity_t *self); +void SP_target_character(gentity_t *ent); +void SP_target_score(gentity_t *ent); +void SP_target_teleporter(gentity_t *ent); +void SP_target_relay(gentity_t *ent); +void SP_target_kill(gentity_t *ent); +void SP_target_position(gentity_t *ent); +void SP_target_location(gentity_t *ent); +void SP_target_counter(gentity_t *self); +void SP_target_random(gentity_t *self); +void SP_target_scriptrunner(gentity_t *self); +void SP_target_interest(gentity_t *self); +void SP_target_activate(gentity_t *self); +void SP_target_deactivate(gentity_t *self); +void SP_target_level_change(gentity_t *self); +void SP_target_play_music(gentity_t *self); +void SP_target_push(gentity_t *ent); + +void SP_light(gentity_t *self); +void SP_info_null(gentity_t *self); +void SP_info_notnull(gentity_t *self); +void SP_info_camp(gentity_t *self); +void SP_path_corner(gentity_t *self); + +void SP_misc_teleporter_dest(gentity_t *self); void SP_misc_model(gentity_t *ent); void SP_misc_model_static(gentity_t *ent); -void SP_misc_model_breakable( gentity_t *ent ) ; +void SP_misc_model_breakable(gentity_t *ent); void SP_misc_G2model(gentity_t *ent); void SP_misc_portal_camera(gentity_t *ent); void SP_misc_portal_surface(gentity_t *ent); -void SP_misc_weather_zone( gentity_t *ent ); +void SP_misc_weather_zone(gentity_t *ent); -void SP_misc_bsp (gentity_t *ent); -void SP_terrain (gentity_t *ent); -void SP_misc_skyportal_orient (gentity_t *ent); -void SP_misc_skyportal (gentity_t *ent); +void SP_misc_bsp(gentity_t *ent); +void SP_terrain(gentity_t *ent); +void SP_misc_skyportal_orient(gentity_t *ent); +void SP_misc_skyportal(gentity_t *ent); void SP_misc_ammo_floor_unit(gentity_t *ent); -void SP_misc_shield_floor_unit( gentity_t *ent ); -void SP_misc_model_shield_power_converter( gentity_t *ent ); -void SP_misc_model_ammo_power_converter( gentity_t *ent ); -void SP_misc_model_health_power_converter( gentity_t *ent ); +void SP_misc_shield_floor_unit(gentity_t *ent); +void SP_misc_model_shield_power_converter(gentity_t *ent); +void SP_misc_model_ammo_power_converter(gentity_t *ent); +void SP_misc_model_health_power_converter(gentity_t *ent); -void SP_fx_runner( gentity_t *ent ); +void SP_fx_runner(gentity_t *ent); void SP_target_screenshake(gentity_t *ent); void SP_target_escapetrig(gentity_t *ent); -void SP_misc_maglock ( gentity_t *self ); +void SP_misc_maglock(gentity_t *self); void SP_misc_faller(gentity_t *ent); void SP_misc_holocron(gentity_t *ent); -void SP_reference_tag ( gentity_t *ent ); - -void SP_misc_weapon_shooter( gentity_t *self ); - -void SP_misc_cubemap( gentity_t *ent ); - -void SP_NPC_spawner( gentity_t *self ); - -void SP_NPC_Vehicle( gentity_t *self); - -void SP_NPC_Kyle( gentity_t *self ); -void SP_NPC_Lando( gentity_t *self ); -void SP_NPC_Jan( gentity_t *self ); -void SP_NPC_Luke( gentity_t *self ); -void SP_NPC_MonMothma( gentity_t *self ); -void SP_NPC_Tavion( gentity_t *self ); -void SP_NPC_Tavion_New( gentity_t *self ); -void SP_NPC_Alora( gentity_t *self ); -void SP_NPC_Reelo( gentity_t *self ); -void SP_NPC_Galak( gentity_t *self ); -void SP_NPC_Desann( gentity_t *self ); -void SP_NPC_Bartender( gentity_t *self ); -void SP_NPC_MorganKatarn( gentity_t *self ); -void SP_NPC_Jedi( gentity_t *self ); -void SP_NPC_Prisoner( gentity_t *self ); -void SP_NPC_Rebel( gentity_t *self ); -void SP_NPC_Human_Merc( gentity_t *self ); -void SP_NPC_Stormtrooper( gentity_t *self ); -void SP_NPC_StormtrooperOfficer( gentity_t *self ); -void SP_NPC_Snowtrooper( gentity_t *self); -void SP_NPC_Tie_Pilot( gentity_t *self ); -void SP_NPC_Ugnaught( gentity_t *self ); -void SP_NPC_Jawa( gentity_t *self ); -void SP_NPC_Gran( gentity_t *self ); -void SP_NPC_Rodian( gentity_t *self ); -void SP_NPC_Weequay( gentity_t *self ); -void SP_NPC_Trandoshan( gentity_t *self ); -void SP_NPC_Tusken( gentity_t *self ); -void SP_NPC_Noghri( gentity_t *self ); -void SP_NPC_SwampTrooper( gentity_t *self ); -void SP_NPC_Imperial( gentity_t *self ); -void SP_NPC_ImpWorker( gentity_t *self ); -void SP_NPC_BespinCop( gentity_t *self ); -void SP_NPC_Reborn( gentity_t *self ); -void SP_NPC_ShadowTrooper( gentity_t *self ); -void SP_NPC_Monster_Murjj( gentity_t *self ); -void SP_NPC_Monster_Swamp( gentity_t *self ); -void SP_NPC_Monster_Howler( gentity_t *self ); -void SP_NPC_Monster_Claw( gentity_t *self ); -void SP_NPC_Monster_Glider( gentity_t *self ); -void SP_NPC_Monster_Flier2( gentity_t *self ); -void SP_NPC_Monster_Lizard( gentity_t *self ); -void SP_NPC_Monster_Fish( gentity_t *self ); -void SP_NPC_Monster_Wampa( gentity_t *self ); -void SP_NPC_Monster_Rancor( gentity_t *self ); -void SP_NPC_MineMonster( gentity_t *self ); -void SP_NPC_Droid_Interrogator( gentity_t *self ); -void SP_NPC_Droid_Probe( gentity_t *self ); -void SP_NPC_Droid_Mark1( gentity_t *self ); -void SP_NPC_Droid_Mark2( gentity_t *self ); -void SP_NPC_Droid_ATST( gentity_t *self ); -void SP_NPC_Droid_Seeker( gentity_t *self ); -void SP_NPC_Droid_Remote( gentity_t *self ); -void SP_NPC_Droid_Sentry( gentity_t *self ); -void SP_NPC_Droid_Gonk( gentity_t *self ); -void SP_NPC_Droid_Mouse( gentity_t *self ); -void SP_NPC_Droid_R2D2( gentity_t *self ); -void SP_NPC_Droid_R5D2( gentity_t *self ); -void SP_NPC_Droid_Protocol( gentity_t *self ); - -void SP_NPC_Reborn_New( gentity_t *self); -void SP_NPC_Cultist( gentity_t *self ); -void SP_NPC_Cultist_Saber( gentity_t *self ); -void SP_NPC_Cultist_Saber_Powers( gentity_t *self ); -void SP_NPC_Cultist_Destroyer( gentity_t *self ); -void SP_NPC_Cultist_Commando( gentity_t *self ); - -void SP_waypoint (gentity_t *ent); -void SP_waypoint_small (gentity_t *ent); -void SP_waypoint_navgoal (gentity_t *ent); -void SP_waypoint_navgoal_8 (gentity_t *ent); -void SP_waypoint_navgoal_4 (gentity_t *ent); -void SP_waypoint_navgoal_2 (gentity_t *ent); -void SP_waypoint_navgoal_1 (gentity_t *ent); - -void SP_CreateWind( gentity_t *ent ); -void SP_CreateSpaceDust( gentity_t *ent ); -void SP_CreateSnow( gentity_t *ent ); -void SP_CreateRain( gentity_t *ent ); - -void SP_point_combat( gentity_t *self ); - -void SP_shooter_blaster( gentity_t *ent ); - -void SP_team_CTF_redplayer( gentity_t *ent ); -void SP_team_CTF_blueplayer( gentity_t *ent ); - -void SP_team_CTF_redspawn( gentity_t *ent ); -void SP_team_CTF_bluespawn( gentity_t *ent ); - -void SP_misc_turret( gentity_t *ent ); -void SP_misc_turretG2( gentity_t *base ); - -void SP_item_botroam( gentity_t *ent ) { } - -void SP_gametype_item ( gentity_t* ent ) -{ +void SP_reference_tag(gentity_t *ent); + +void SP_misc_weapon_shooter(gentity_t *self); + +void SP_misc_cubemap(gentity_t *ent); + +void SP_NPC_spawner(gentity_t *self); + +void SP_NPC_Vehicle(gentity_t *self); + +void SP_NPC_Kyle(gentity_t *self); +void SP_NPC_Lando(gentity_t *self); +void SP_NPC_Jan(gentity_t *self); +void SP_NPC_Luke(gentity_t *self); +void SP_NPC_MonMothma(gentity_t *self); +void SP_NPC_Tavion(gentity_t *self); +void SP_NPC_Tavion_New(gentity_t *self); +void SP_NPC_Alora(gentity_t *self); +void SP_NPC_Reelo(gentity_t *self); +void SP_NPC_Galak(gentity_t *self); +void SP_NPC_Desann(gentity_t *self); +void SP_NPC_Bartender(gentity_t *self); +void SP_NPC_MorganKatarn(gentity_t *self); +void SP_NPC_Jedi(gentity_t *self); +void SP_NPC_Prisoner(gentity_t *self); +void SP_NPC_Rebel(gentity_t *self); +void SP_NPC_Human_Merc(gentity_t *self); +void SP_NPC_Stormtrooper(gentity_t *self); +void SP_NPC_StormtrooperOfficer(gentity_t *self); +void SP_NPC_Snowtrooper(gentity_t *self); +void SP_NPC_Tie_Pilot(gentity_t *self); +void SP_NPC_Ugnaught(gentity_t *self); +void SP_NPC_Jawa(gentity_t *self); +void SP_NPC_Gran(gentity_t *self); +void SP_NPC_Rodian(gentity_t *self); +void SP_NPC_Weequay(gentity_t *self); +void SP_NPC_Trandoshan(gentity_t *self); +void SP_NPC_Tusken(gentity_t *self); +void SP_NPC_Noghri(gentity_t *self); +void SP_NPC_SwampTrooper(gentity_t *self); +void SP_NPC_Imperial(gentity_t *self); +void SP_NPC_ImpWorker(gentity_t *self); +void SP_NPC_BespinCop(gentity_t *self); +void SP_NPC_Reborn(gentity_t *self); +void SP_NPC_ShadowTrooper(gentity_t *self); +void SP_NPC_Monster_Murjj(gentity_t *self); +void SP_NPC_Monster_Swamp(gentity_t *self); +void SP_NPC_Monster_Howler(gentity_t *self); +void SP_NPC_Monster_Claw(gentity_t *self); +void SP_NPC_Monster_Glider(gentity_t *self); +void SP_NPC_Monster_Flier2(gentity_t *self); +void SP_NPC_Monster_Lizard(gentity_t *self); +void SP_NPC_Monster_Fish(gentity_t *self); +void SP_NPC_Monster_Wampa(gentity_t *self); +void SP_NPC_Monster_Rancor(gentity_t *self); +void SP_NPC_MineMonster(gentity_t *self); +void SP_NPC_Droid_Interrogator(gentity_t *self); +void SP_NPC_Droid_Probe(gentity_t *self); +void SP_NPC_Droid_Mark1(gentity_t *self); +void SP_NPC_Droid_Mark2(gentity_t *self); +void SP_NPC_Droid_ATST(gentity_t *self); +void SP_NPC_Droid_Seeker(gentity_t *self); +void SP_NPC_Droid_Remote(gentity_t *self); +void SP_NPC_Droid_Sentry(gentity_t *self); +void SP_NPC_Droid_Gonk(gentity_t *self); +void SP_NPC_Droid_Mouse(gentity_t *self); +void SP_NPC_Droid_R2D2(gentity_t *self); +void SP_NPC_Droid_R5D2(gentity_t *self); +void SP_NPC_Droid_Protocol(gentity_t *self); + +void SP_NPC_Reborn_New(gentity_t *self); +void SP_NPC_Cultist(gentity_t *self); +void SP_NPC_Cultist_Saber(gentity_t *self); +void SP_NPC_Cultist_Saber_Powers(gentity_t *self); +void SP_NPC_Cultist_Destroyer(gentity_t *self); +void SP_NPC_Cultist_Commando(gentity_t *self); + +void SP_waypoint(gentity_t *ent); +void SP_waypoint_small(gentity_t *ent); +void SP_waypoint_navgoal(gentity_t *ent); +void SP_waypoint_navgoal_8(gentity_t *ent); +void SP_waypoint_navgoal_4(gentity_t *ent); +void SP_waypoint_navgoal_2(gentity_t *ent); +void SP_waypoint_navgoal_1(gentity_t *ent); + +void SP_CreateWind(gentity_t *ent); +void SP_CreateSpaceDust(gentity_t *ent); +void SP_CreateSnow(gentity_t *ent); +void SP_CreateRain(gentity_t *ent); + +void SP_point_combat(gentity_t *self); + +void SP_shooter_blaster(gentity_t *ent); + +void SP_team_CTF_redplayer(gentity_t *ent); +void SP_team_CTF_blueplayer(gentity_t *ent); + +void SP_team_CTF_redspawn(gentity_t *ent); +void SP_team_CTF_bluespawn(gentity_t *ent); + +void SP_misc_turret(gentity_t *ent); +void SP_misc_turretG2(gentity_t *base); + +void SP_item_botroam(gentity_t *ent) {} + +void SP_gametype_item(gentity_t *ent) { gitem_t *item = NULL; char *value; int team = -1; G_SpawnString("teamfilter", "", &value); - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); // If a team filter is set then override any team settings for the spawns - if ( level.mTeamFilter[0] ) - { - if ( Q_stricmp ( level.mTeamFilter, "red") == 0 ) - { + if (level.mTeamFilter[0]) { + if (Q_stricmp(level.mTeamFilter, "red") == 0) { team = TEAM_RED; - } - else if ( Q_stricmp ( level.mTeamFilter, "blue") == 0 ) - { + } else if (Q_stricmp(level.mTeamFilter, "blue") == 0) { team = TEAM_BLUE; } } - if (ent->targetname && ent->targetname[0]) - { - if (team != -1) - { - if (strstr(ent->targetname, "flag")) - { - if (team == TEAM_RED) - { + if (ent->targetname && ent->targetname[0]) { + if (team != -1) { + if (strstr(ent->targetname, "flag")) { + if (team == TEAM_RED) { item = BG_FindItem("team_CTF_redflag"); - } - else - { //blue + } else { // blue item = BG_FindItem("team_CTF_blueflag"); } } - } - else if (strstr(ent->targetname, "red_flag")) - { + } else if (strstr(ent->targetname, "red_flag")) { item = BG_FindItem("team_CTF_redflag"); - } - else if (strstr(ent->targetname, "blue_flag")) - { + } else if (strstr(ent->targetname, "blue_flag")) { item = BG_FindItem("team_CTF_blueflag"); - } - else - { + } else { item = NULL; } - if (item) - { + if (item) { ent->targetname = NULL; ent->classname = item->classname; - G_SpawnItem( ent, item ); + G_SpawnItem(ent, item); } } } -void SP_emplaced_gun( gentity_t *ent ); - -spawn_t spawns[] = { - { "emplaced_gun", SP_emplaced_gun }, - { "func_bobbing", SP_func_bobbing }, - { "func_breakable", SP_func_breakable }, - { "func_button", SP_func_button }, - { "func_door", SP_func_door }, - { "func_glass", SP_func_glass }, - { "func_group", SP_info_null }, - { "func_pendulum", SP_func_pendulum }, - { "func_plat", SP_func_plat }, - { "func_rotating", SP_func_rotating }, - { "func_static", SP_func_static }, - { "func_timer", SP_func_timer }, // rename trigger_timer? - { "func_train", SP_func_train }, - { "func_usable", SP_func_usable }, - { "func_wall", SP_func_wall }, - { "fx_rain", SP_CreateRain }, - { "fx_runner", SP_fx_runner }, - { "fx_snow", SP_CreateSnow }, - { "fx_spacedust", SP_CreateSpaceDust }, - { "fx_wind", SP_CreateWind }, - { "gametype_item", SP_gametype_item }, - { "info_camp", SP_info_camp }, - { "info_jedimaster_start", SP_info_jedimaster_start }, - { "info_notnull", SP_info_notnull }, // use target_position instead - { "info_null", SP_info_null }, - { "info_player_deathmatch", SP_info_player_deathmatch }, - { "info_player_duel", SP_info_player_duel }, - { "info_player_duel1", SP_info_player_duel1 }, - { "info_player_duel2", SP_info_player_duel2 }, - { "info_player_intermission", SP_info_player_intermission }, - { "info_player_intermission_blue", SP_info_player_intermission_blue }, - { "info_player_intermission_red", SP_info_player_intermission_red }, - { "info_player_siegeteam1", SP_info_player_siegeteam1 }, - { "info_player_siegeteam2", SP_info_player_siegeteam2 }, - { "info_player_start", SP_info_player_start }, - { "info_player_start_blue", SP_info_player_start_blue }, - { "info_player_start_red", SP_info_player_start_red }, - { "info_siege_decomplete", SP_info_siege_decomplete }, - { "info_siege_objective", SP_info_siege_objective }, - { "info_siege_radaricon", SP_info_siege_radaricon }, - { "item_botroam", SP_item_botroam }, - { "light", SP_light }, - { "misc_ammo_floor_unit", SP_misc_ammo_floor_unit }, - { "misc_bsp", SP_misc_bsp }, - { "misc_cubemap", SP_misc_cubemap }, - { "misc_faller", SP_misc_faller }, - { "misc_G2model", SP_misc_G2model }, - { "misc_holocron", SP_misc_holocron }, - { "misc_maglock", SP_misc_maglock }, - { "misc_model", SP_misc_model }, - { "misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter }, - { "misc_model_breakable", SP_misc_model_breakable }, - { "misc_model_health_power_converter", SP_misc_model_health_power_converter }, - { "misc_model_shield_power_converter", SP_misc_model_shield_power_converter }, - { "misc_model_static", SP_misc_model_static }, - { "misc_portal_camera", SP_misc_portal_camera }, - { "misc_portal_surface", SP_misc_portal_surface }, - { "misc_shield_floor_unit", SP_misc_shield_floor_unit }, - { "misc_siege_item", SP_misc_siege_item }, - { "misc_skyportal", SP_misc_skyportal }, - { "misc_skyportal_orient", SP_misc_skyportal_orient }, - { "misc_teleporter_dest", SP_misc_teleporter_dest }, - { "misc_turret", SP_misc_turret }, - { "misc_turretG2", SP_misc_turretG2 }, - { "misc_weapon_shooter", SP_misc_weapon_shooter }, - { "misc_weather_zone", SP_misc_weather_zone }, - { "npc_alora", SP_NPC_Alora }, - { "npc_bartender", SP_NPC_Bartender }, - { "npc_bespincop", SP_NPC_BespinCop }, - { "npc_colombian_emplacedgunner", SP_NPC_ShadowTrooper }, - { "npc_colombian_rebel", SP_NPC_Reborn }, - { "npc_colombian_soldier", SP_NPC_Reborn }, - { "npc_cultist", SP_NPC_Cultist }, - { "npc_cultist_commando", SP_NPC_Cultist_Commando }, - { "npc_cultist_destroyer", SP_NPC_Cultist_Destroyer }, - { "npc_cultist_saber", SP_NPC_Cultist_Saber }, - { "npc_cultist_saber_powers", SP_NPC_Cultist_Saber_Powers }, - { "npc_desann", SP_NPC_Desann }, - { "npc_droid_atst", SP_NPC_Droid_ATST }, - { "npc_droid_gonk", SP_NPC_Droid_Gonk }, - { "npc_droid_interrogator", SP_NPC_Droid_Interrogator }, - { "npc_droid_mark1", SP_NPC_Droid_Mark1 }, - { "npc_droid_mark2", SP_NPC_Droid_Mark2 }, - { "npc_droid_mouse", SP_NPC_Droid_Mouse }, - { "npc_droid_probe", SP_NPC_Droid_Probe }, - { "npc_droid_protocol", SP_NPC_Droid_Protocol }, - { "npc_droid_r2d2", SP_NPC_Droid_R2D2 }, - { "npc_droid_r5d2", SP_NPC_Droid_R5D2 }, - { "npc_droid_remote", SP_NPC_Droid_Remote }, - { "npc_droid_seeker", SP_NPC_Droid_Seeker }, - { "npc_droid_sentry", SP_NPC_Droid_Sentry }, - { "npc_galak", SP_NPC_Galak }, - { "npc_gran", SP_NPC_Gran }, - { "npc_human_merc", SP_NPC_Human_Merc }, - { "npc_imperial", SP_NPC_Imperial }, - { "npc_impworker", SP_NPC_ImpWorker }, - { "npc_jan", SP_NPC_Jan }, - { "npc_jawa", SP_NPC_Jawa }, - { "npc_jedi", SP_NPC_Jedi }, - { "npc_kyle", SP_NPC_Kyle }, - { "npc_lando", SP_NPC_Lando }, - { "npc_luke", SP_NPC_Luke }, - { "npc_manuel_vergara_rmg", SP_NPC_Desann }, - { "npc_minemonster", SP_NPC_MineMonster }, - { "npc_monmothma", SP_NPC_MonMothma }, - { "npc_monster_claw", SP_NPC_Monster_Claw }, - { "npc_monster_fish", SP_NPC_Monster_Fish }, - { "npc_monster_flier2", SP_NPC_Monster_Flier2 }, - { "npc_monster_glider", SP_NPC_Monster_Glider }, - { "npc_monster_howler", SP_NPC_Monster_Howler }, - { "npc_monster_lizard", SP_NPC_Monster_Lizard }, - { "npc_monster_murjj", SP_NPC_Monster_Murjj }, - { "npc_monster_rancor", SP_NPC_Monster_Rancor }, - { "npc_monster_swamp", SP_NPC_Monster_Swamp }, - { "npc_monster_wampa", SP_NPC_Monster_Wampa }, - { "npc_morgankatarn", SP_NPC_MorganKatarn }, - { "npc_noghri", SP_NPC_Noghri }, - { "npc_prisoner", SP_NPC_Prisoner }, - { "npc_rebel", SP_NPC_Rebel }, - { "npc_reborn", SP_NPC_Reborn }, - { "npc_reborn_new", SP_NPC_Reborn_New }, - { "npc_reelo", SP_NPC_Reelo }, - { "npc_rodian", SP_NPC_Rodian }, - { "npc_shadowtrooper", SP_NPC_ShadowTrooper }, - { "npc_snowtrooper", SP_NPC_Snowtrooper }, - { "npc_spawner", SP_NPC_spawner }, - { "npc_stormtrooper", SP_NPC_Stormtrooper }, - { "npc_stormtrooperofficer", SP_NPC_StormtrooperOfficer }, - { "npc_swamptrooper", SP_NPC_SwampTrooper }, - { "npc_tavion", SP_NPC_Tavion }, - { "npc_tavion_new", SP_NPC_Tavion_New }, - { "npc_tie_pilot", SP_NPC_Tie_Pilot }, - { "npc_trandoshan", SP_NPC_Trandoshan }, - { "npc_tusken", SP_NPC_Tusken }, - { "npc_ugnaught", SP_NPC_Ugnaught }, - { "npc_vehicle", SP_NPC_Vehicle }, - { "npc_weequay", SP_NPC_Weequay }, - { "path_corner", SP_path_corner }, - { "point_combat", SP_point_combat }, - { "ref_tag", SP_reference_tag }, - { "ref_tag_huge", SP_reference_tag }, - { "shooter_blaster", SP_shooter_blaster }, - { "target_activate", SP_target_activate }, - { "target_counter", SP_target_counter }, - { "target_deactivate", SP_target_deactivate }, - { "target_delay", SP_target_delay }, - { "target_escapetrig", SP_target_escapetrig }, - { "target_give", SP_target_give }, - { "target_interest", SP_target_interest }, - { "target_kill", SP_target_kill }, - { "target_laser", SP_target_laser }, - { "target_level_change", SP_target_level_change }, - { "target_location", SP_target_location }, - { "target_play_music", SP_target_play_music }, - { "target_position", SP_target_position }, - { "target_print", SP_target_print }, - { "target_push", SP_target_push }, - { "target_random", SP_target_random }, - { "target_relay", SP_target_relay }, - { "target_remove_powerups", SP_target_remove_powerups }, - { "target_score", SP_target_score }, - { "target_screenshake", SP_target_screenshake }, - { "target_scriptrunner", SP_target_scriptrunner }, - { "target_siege_end", SP_target_siege_end }, - { "target_speaker", SP_target_speaker }, - { "target_teleporter", SP_target_teleporter }, - { "team_CTF_blueplayer", SP_team_CTF_blueplayer }, - { "team_CTF_bluespawn", SP_team_CTF_bluespawn }, - { "team_CTF_redplayer", SP_team_CTF_redplayer }, - { "team_CTF_redspawn", SP_team_CTF_redspawn }, - { "terrain", SP_terrain }, - { "trigger_always", SP_trigger_always }, - { "trigger_asteroid_field", SP_trigger_asteroid_field }, - { "trigger_hurt", SP_trigger_hurt }, - { "trigger_hyperspace", SP_trigger_hyperspace }, - { "trigger_lightningstrike", SP_trigger_lightningstrike }, - { "trigger_multiple", SP_trigger_multiple }, - { "trigger_once", SP_trigger_once }, - { "trigger_push", SP_trigger_push }, - { "trigger_shipboundary", SP_trigger_shipboundary }, - { "trigger_space", SP_trigger_space }, - { "trigger_teleport", SP_trigger_teleport }, - { "waypoint", SP_waypoint }, - { "waypoint_navgoal", SP_waypoint_navgoal }, - { "waypoint_navgoal_1", SP_waypoint_navgoal_1 }, - { "waypoint_navgoal_2", SP_waypoint_navgoal_2 }, - { "waypoint_navgoal_4", SP_waypoint_navgoal_4 }, - { "waypoint_navgoal_8", SP_waypoint_navgoal_8 }, - { "waypoint_small", SP_waypoint_small }, +void SP_emplaced_gun(gentity_t *ent); + +spawn_t spawns[] = { + {"emplaced_gun", SP_emplaced_gun}, + {"func_bobbing", SP_func_bobbing}, + {"func_breakable", SP_func_breakable}, + {"func_button", SP_func_button}, + {"func_door", SP_func_door}, + {"func_glass", SP_func_glass}, + {"func_group", SP_info_null}, + {"func_pendulum", SP_func_pendulum}, + {"func_plat", SP_func_plat}, + {"func_rotating", SP_func_rotating}, + {"func_static", SP_func_static}, + {"func_timer", SP_func_timer}, // rename trigger_timer? + {"func_train", SP_func_train}, + {"func_usable", SP_func_usable}, + {"func_wall", SP_func_wall}, + {"fx_rain", SP_CreateRain}, + {"fx_runner", SP_fx_runner}, + {"fx_snow", SP_CreateSnow}, + {"fx_spacedust", SP_CreateSpaceDust}, + {"fx_wind", SP_CreateWind}, + {"gametype_item", SP_gametype_item}, + {"info_camp", SP_info_camp}, + {"info_jedimaster_start", SP_info_jedimaster_start}, + {"info_notnull", SP_info_notnull}, // use target_position instead + {"info_null", SP_info_null}, + {"info_player_deathmatch", SP_info_player_deathmatch}, + {"info_player_duel", SP_info_player_duel}, + {"info_player_duel1", SP_info_player_duel1}, + {"info_player_duel2", SP_info_player_duel2}, + {"info_player_intermission", SP_info_player_intermission}, + {"info_player_intermission_blue", SP_info_player_intermission_blue}, + {"info_player_intermission_red", SP_info_player_intermission_red}, + {"info_player_siegeteam1", SP_info_player_siegeteam1}, + {"info_player_siegeteam2", SP_info_player_siegeteam2}, + {"info_player_start", SP_info_player_start}, + {"info_player_start_blue", SP_info_player_start_blue}, + {"info_player_start_red", SP_info_player_start_red}, + {"info_siege_decomplete", SP_info_siege_decomplete}, + {"info_siege_objective", SP_info_siege_objective}, + {"info_siege_radaricon", SP_info_siege_radaricon}, + {"item_botroam", SP_item_botroam}, + {"light", SP_light}, + {"misc_ammo_floor_unit", SP_misc_ammo_floor_unit}, + {"misc_bsp", SP_misc_bsp}, + {"misc_cubemap", SP_misc_cubemap}, + {"misc_faller", SP_misc_faller}, + {"misc_G2model", SP_misc_G2model}, + {"misc_holocron", SP_misc_holocron}, + {"misc_maglock", SP_misc_maglock}, + {"misc_model", SP_misc_model}, + {"misc_model_ammo_power_converter", SP_misc_model_ammo_power_converter}, + {"misc_model_breakable", SP_misc_model_breakable}, + {"misc_model_health_power_converter", SP_misc_model_health_power_converter}, + {"misc_model_shield_power_converter", SP_misc_model_shield_power_converter}, + {"misc_model_static", SP_misc_model_static}, + {"misc_portal_camera", SP_misc_portal_camera}, + {"misc_portal_surface", SP_misc_portal_surface}, + {"misc_shield_floor_unit", SP_misc_shield_floor_unit}, + {"misc_siege_item", SP_misc_siege_item}, + {"misc_skyportal", SP_misc_skyportal}, + {"misc_skyportal_orient", SP_misc_skyportal_orient}, + {"misc_teleporter_dest", SP_misc_teleporter_dest}, + {"misc_turret", SP_misc_turret}, + {"misc_turretG2", SP_misc_turretG2}, + {"misc_weapon_shooter", SP_misc_weapon_shooter}, + {"misc_weather_zone", SP_misc_weather_zone}, + {"npc_alora", SP_NPC_Alora}, + {"npc_bartender", SP_NPC_Bartender}, + {"npc_bespincop", SP_NPC_BespinCop}, + {"npc_colombian_emplacedgunner", SP_NPC_ShadowTrooper}, + {"npc_colombian_rebel", SP_NPC_Reborn}, + {"npc_colombian_soldier", SP_NPC_Reborn}, + {"npc_cultist", SP_NPC_Cultist}, + {"npc_cultist_commando", SP_NPC_Cultist_Commando}, + {"npc_cultist_destroyer", SP_NPC_Cultist_Destroyer}, + {"npc_cultist_saber", SP_NPC_Cultist_Saber}, + {"npc_cultist_saber_powers", SP_NPC_Cultist_Saber_Powers}, + {"npc_desann", SP_NPC_Desann}, + {"npc_droid_atst", SP_NPC_Droid_ATST}, + {"npc_droid_gonk", SP_NPC_Droid_Gonk}, + {"npc_droid_interrogator", SP_NPC_Droid_Interrogator}, + {"npc_droid_mark1", SP_NPC_Droid_Mark1}, + {"npc_droid_mark2", SP_NPC_Droid_Mark2}, + {"npc_droid_mouse", SP_NPC_Droid_Mouse}, + {"npc_droid_probe", SP_NPC_Droid_Probe}, + {"npc_droid_protocol", SP_NPC_Droid_Protocol}, + {"npc_droid_r2d2", SP_NPC_Droid_R2D2}, + {"npc_droid_r5d2", SP_NPC_Droid_R5D2}, + {"npc_droid_remote", SP_NPC_Droid_Remote}, + {"npc_droid_seeker", SP_NPC_Droid_Seeker}, + {"npc_droid_sentry", SP_NPC_Droid_Sentry}, + {"npc_galak", SP_NPC_Galak}, + {"npc_gran", SP_NPC_Gran}, + {"npc_human_merc", SP_NPC_Human_Merc}, + {"npc_imperial", SP_NPC_Imperial}, + {"npc_impworker", SP_NPC_ImpWorker}, + {"npc_jan", SP_NPC_Jan}, + {"npc_jawa", SP_NPC_Jawa}, + {"npc_jedi", SP_NPC_Jedi}, + {"npc_kyle", SP_NPC_Kyle}, + {"npc_lando", SP_NPC_Lando}, + {"npc_luke", SP_NPC_Luke}, + {"npc_manuel_vergara_rmg", SP_NPC_Desann}, + {"npc_minemonster", SP_NPC_MineMonster}, + {"npc_monmothma", SP_NPC_MonMothma}, + {"npc_monster_claw", SP_NPC_Monster_Claw}, + {"npc_monster_fish", SP_NPC_Monster_Fish}, + {"npc_monster_flier2", SP_NPC_Monster_Flier2}, + {"npc_monster_glider", SP_NPC_Monster_Glider}, + {"npc_monster_howler", SP_NPC_Monster_Howler}, + {"npc_monster_lizard", SP_NPC_Monster_Lizard}, + {"npc_monster_murjj", SP_NPC_Monster_Murjj}, + {"npc_monster_rancor", SP_NPC_Monster_Rancor}, + {"npc_monster_swamp", SP_NPC_Monster_Swamp}, + {"npc_monster_wampa", SP_NPC_Monster_Wampa}, + {"npc_morgankatarn", SP_NPC_MorganKatarn}, + {"npc_noghri", SP_NPC_Noghri}, + {"npc_prisoner", SP_NPC_Prisoner}, + {"npc_rebel", SP_NPC_Rebel}, + {"npc_reborn", SP_NPC_Reborn}, + {"npc_reborn_new", SP_NPC_Reborn_New}, + {"npc_reelo", SP_NPC_Reelo}, + {"npc_rodian", SP_NPC_Rodian}, + {"npc_shadowtrooper", SP_NPC_ShadowTrooper}, + {"npc_snowtrooper", SP_NPC_Snowtrooper}, + {"npc_spawner", SP_NPC_spawner}, + {"npc_stormtrooper", SP_NPC_Stormtrooper}, + {"npc_stormtrooperofficer", SP_NPC_StormtrooperOfficer}, + {"npc_swamptrooper", SP_NPC_SwampTrooper}, + {"npc_tavion", SP_NPC_Tavion}, + {"npc_tavion_new", SP_NPC_Tavion_New}, + {"npc_tie_pilot", SP_NPC_Tie_Pilot}, + {"npc_trandoshan", SP_NPC_Trandoshan}, + {"npc_tusken", SP_NPC_Tusken}, + {"npc_ugnaught", SP_NPC_Ugnaught}, + {"npc_vehicle", SP_NPC_Vehicle}, + {"npc_weequay", SP_NPC_Weequay}, + {"path_corner", SP_path_corner}, + {"point_combat", SP_point_combat}, + {"ref_tag", SP_reference_tag}, + {"ref_tag_huge", SP_reference_tag}, + {"shooter_blaster", SP_shooter_blaster}, + {"target_activate", SP_target_activate}, + {"target_counter", SP_target_counter}, + {"target_deactivate", SP_target_deactivate}, + {"target_delay", SP_target_delay}, + {"target_escapetrig", SP_target_escapetrig}, + {"target_give", SP_target_give}, + {"target_interest", SP_target_interest}, + {"target_kill", SP_target_kill}, + {"target_laser", SP_target_laser}, + {"target_level_change", SP_target_level_change}, + {"target_location", SP_target_location}, + {"target_play_music", SP_target_play_music}, + {"target_position", SP_target_position}, + {"target_print", SP_target_print}, + {"target_push", SP_target_push}, + {"target_random", SP_target_random}, + {"target_relay", SP_target_relay}, + {"target_remove_powerups", SP_target_remove_powerups}, + {"target_score", SP_target_score}, + {"target_screenshake", SP_target_screenshake}, + {"target_scriptrunner", SP_target_scriptrunner}, + {"target_siege_end", SP_target_siege_end}, + {"target_speaker", SP_target_speaker}, + {"target_teleporter", SP_target_teleporter}, + {"team_CTF_blueplayer", SP_team_CTF_blueplayer}, + {"team_CTF_bluespawn", SP_team_CTF_bluespawn}, + {"team_CTF_redplayer", SP_team_CTF_redplayer}, + {"team_CTF_redspawn", SP_team_CTF_redspawn}, + {"terrain", SP_terrain}, + {"trigger_always", SP_trigger_always}, + {"trigger_asteroid_field", SP_trigger_asteroid_field}, + {"trigger_hurt", SP_trigger_hurt}, + {"trigger_hyperspace", SP_trigger_hyperspace}, + {"trigger_lightningstrike", SP_trigger_lightningstrike}, + {"trigger_multiple", SP_trigger_multiple}, + {"trigger_once", SP_trigger_once}, + {"trigger_push", SP_trigger_push}, + {"trigger_shipboundary", SP_trigger_shipboundary}, + {"trigger_space", SP_trigger_space}, + {"trigger_teleport", SP_trigger_teleport}, + {"waypoint", SP_waypoint}, + {"waypoint_navgoal", SP_waypoint_navgoal}, + {"waypoint_navgoal_1", SP_waypoint_navgoal_1}, + {"waypoint_navgoal_2", SP_waypoint_navgoal_2}, + {"waypoint_navgoal_4", SP_waypoint_navgoal_4}, + {"waypoint_navgoal_8", SP_waypoint_navgoal_8}, + {"waypoint_small", SP_waypoint_small}, }; /* @@ -693,40 +675,37 @@ Finds the spawn function for the entity and calls it, returning qfalse if not found =============== */ -static int spawncmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((spawn_t*)b)->name ); -} +static int spawncmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((spawn_t *)b)->name); } -qboolean G_CallSpawn( gentity_t *ent ) { - spawn_t *s; - gitem_t *item; +qboolean G_CallSpawn(gentity_t *ent) { + spawn_t *s; + gitem_t *item; - if ( !ent->classname ) { - trap->Print( "G_CallSpawn: NULL classname\n" ); + if (!ent->classname) { + trap->Print("G_CallSpawn: NULL classname\n"); return qfalse; } // check item spawn functions - //TODO: cant reorder items because compat so....? - for ( item=bg_itemlist+1 ; item->classname ; item++ ) { - if ( !strcmp(item->classname, ent->classname) ) { - G_SpawnItem( ent, item ); + // TODO: cant reorder items because compat so....? + for (item = bg_itemlist + 1; item->classname; item++) { + if (!strcmp(item->classname, ent->classname)) { + G_SpawnItem(ent, item); return qtrue; } } // check normal spawn functions - s = (spawn_t *)Q_LinearSearch( ent->classname, spawns, ARRAY_LEN( spawns ), sizeof( spawn_t ), spawncmp ); - if ( s ) - {// found it - if ( VALIDSTRING( ent->healingsound ) ) - G_SoundIndex( ent->healingsound ); + s = (spawn_t *)Q_LinearSearch(ent->classname, spawns, ARRAY_LEN(spawns), sizeof(spawn_t), spawncmp); + if (s) { // found it + if (VALIDSTRING(ent->healingsound)) + G_SoundIndex(ent->healingsound); - s->spawn( ent ); + s->spawn(ent); return qtrue; } - trap->Print( "%s doesn't have a spawn function\n", ent->classname ); + trap->Print("%s doesn't have a spawn function\n", ent->classname); return qfalse; } @@ -738,57 +717,45 @@ Builds a copy of the string, translating \n to real linefeeds so message texts can be multi-line ============= */ -char *G_NewString( const char *string ) -{ - char *newb=NULL, *new_p=NULL; - int i=0, len=0; - - len = strlen( string )+1; - new_p = newb = (char *)G_Alloc( len ); - - for ( i=0; iname ); -} +static int fieldcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((field_t *)b)->name); } -void Q3_SetParm ( int entID, int parmNum, const char *parmValue ); -void G_ParseField( const char *key, const char *value, gentity_t *ent ) -{ - field_t *f; - byte *b; - float v; - vec3_t vec; - - f = (field_t *)Q_LinearSearch( key, fields, ARRAY_LEN( fields ), sizeof( field_t ), fieldcmp ); - if ( f ) - {// found it +void Q3_SetParm(int entID, int parmNum, const char *parmValue); +void G_ParseField(const char *key, const char *value, gentity_t *ent) { + field_t *f; + byte *b; + float v; + vec3_t vec; + + f = (field_t *)Q_LinearSearch(key, fields, ARRAY_LEN(fields), sizeof(field_t), fieldcmp); + if (f) { // found it b = (byte *)ent; - switch( f->type ) { + switch (f->type) { case F_STRING: - *(char **)(b+f->ofs) = G_NewString (value); + *(char **)(b + f->ofs) = G_NewString(value); break; case F_VECTOR: - if ( sscanf( value, "%f %f %f", &vec[0], &vec[1], &vec[2] ) == 3 ) { - ((float *)(b+f->ofs))[0] = vec[0]; - ((float *)(b+f->ofs))[1] = vec[1]; - ((float *)(b+f->ofs))[2] = vec[2]; - } - else { - trap->Print( "G_ParseField: Failed sscanf on F_VECTOR (key/value: %s/%s)\n", key, value ); - ((float *)(b+f->ofs))[0] = ((float *)(b+f->ofs))[1] = ((float *)(b+f->ofs))[2] = 0.0f; + if (sscanf(value, "%f %f %f", &vec[0], &vec[1], &vec[2]) == 3) { + ((float *)(b + f->ofs))[0] = vec[0]; + ((float *)(b + f->ofs))[1] = vec[1]; + ((float *)(b + f->ofs))[2] = vec[2]; + } else { + trap->Print("G_ParseField: Failed sscanf on F_VECTOR (key/value: %s/%s)\n", key, value); + ((float *)(b + f->ofs))[0] = ((float *)(b + f->ofs))[1] = ((float *)(b + f->ofs))[2] = 0.0f; } break; case F_INT: - *(int *)(b+f->ofs) = atoi(value); + *(int *)(b + f->ofs) = atoi(value); break; case F_FLOAT: - *(float *)(b+f->ofs) = atof(value); + *(float *)(b + f->ofs) = atof(value); break; case F_ANGLEHACK: v = atof(value); - ((float *)(b+f->ofs))[0] = 0; - ((float *)(b+f->ofs))[1] = v; - ((float *)(b+f->ofs))[2] = 0; + ((float *)(b + f->ofs))[0] = 0; + ((float *)(b + f->ofs))[1] = v; + ((float *)(b + f->ofs))[2] = 0; break; case F_PARM1: case F_PARM2: @@ -864,18 +826,17 @@ void G_ParseField( const char *key, const char *value, gentity_t *ent ) case F_PARM14: case F_PARM15: case F_PARM16: - Q3_SetParm( ent->s.number, (f->type - F_PARM1), (char *) value ); + Q3_SetParm(ent->s.number, (f->type - F_PARM1), (char *)value); break; } return; } } -#define ADJUST_AREAPORTAL() \ - if(ent->s.eType == ET_MOVER) \ - { \ - trap->LinkEntity((sharedEntity_t *)ent); \ - trap->AdjustAreaPortalState((sharedEntity_t *)ent, qtrue); \ +#define ADJUST_AREAPORTAL() \ + if (ent->s.eType == ET_MOVER) { \ + trap->LinkEntity((sharedEntity_t *)ent); \ + trap->AdjustAreaPortalState((sharedEntity_t *)ent, qtrue); \ } /* @@ -886,77 +847,74 @@ Spawn an entity and fill in all of the level fields from level.spawnVars[], then call the class specfic spawn function =================== */ -void G_SpawnGEntityFromSpawnVars( qboolean inSubBSP ) { - int i; - gentity_t *ent; - char *s, *value, *gametypeName; +void G_SpawnGEntityFromSpawnVars(qboolean inSubBSP) { + int i; + gentity_t *ent; + char *s, *value, *gametypeName; static char *gametypeNames[GT_MAX_GAME_TYPE] = {"ffa", "holocron", "jedimaster", "duel", "powerduel", "single", "team", "siege", "ctf", "cty"}; // get the next free entity ent = G_Spawn(); - for ( i = 0 ; i < level.numSpawnVars ; i++ ) { - G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent ); + for (i = 0; i < level.numSpawnVars; i++) { + G_ParseField(level.spawnVars[i][0], level.spawnVars[i][1], ent); } // check for "notsingle" flag - if ( level.gametype == GT_SINGLE_PLAYER ) { - G_SpawnInt( "notsingle", "0", &i ); - if ( i ) { + if (level.gametype == GT_SINGLE_PLAYER) { + G_SpawnInt("notsingle", "0", &i); + if (i) { ADJUST_AREAPORTAL(); - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } } // check for "notteam" flag (GT_FFA, GT_DUEL, GT_SINGLE_PLAYER) - if ( level.gametype >= GT_TEAM ) { - G_SpawnInt( "notteam", "0", &i ); - if ( i ) { + if (level.gametype >= GT_TEAM) { + G_SpawnInt("notteam", "0", &i); + if (i) { ADJUST_AREAPORTAL(); - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } } else { - G_SpawnInt( "notfree", "0", &i ); - if ( i ) { + G_SpawnInt("notfree", "0", &i); + if (i) { ADJUST_AREAPORTAL(); - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } } - if( G_SpawnString( "gametype", NULL, &value ) ) { - if( level.gametype >= GT_FFA && level.gametype < GT_MAX_GAME_TYPE ) { + if (G_SpawnString("gametype", NULL, &value)) { + if (level.gametype >= GT_FFA && level.gametype < GT_MAX_GAME_TYPE) { gametypeName = gametypeNames[level.gametype]; - s = strstr( value, gametypeName ); - if( !s ) { + s = strstr(value, gametypeName); + if (!s) { ADJUST_AREAPORTAL(); - G_FreeEntity( ent ); + G_FreeEntity(ent); return; } } } // move editor origin to pos - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - VectorCopy( ent->s.origin, ent->r.currentOrigin ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + VectorCopy(ent->s.origin, ent->r.currentOrigin); // if we didn't get a classname, don't bother spawning anything - if ( !G_CallSpawn( ent ) ) { - G_FreeEntity( ent ); + if (!G_CallSpawn(ent)) { + G_FreeEntity(ent); } - //Tag on the ICARUS scripting information only to valid recipients - if ( trap->ICARUS_ValidEnt( (sharedEntity_t *)ent ) ) - { - trap->ICARUS_InitEnt( (sharedEntity_t *)ent ); + // Tag on the ICARUS scripting information only to valid recipients + if (trap->ICARUS_ValidEnt((sharedEntity_t *)ent)) { + trap->ICARUS_InitEnt((sharedEntity_t *)ent); - if ( ent->classname && ent->classname[0] ) - { - if ( Q_strncmp( "NPC_", ent->classname, 4 ) != 0 ) - {//Not an NPC_spawner (rww - probably don't even care for MP, but whatever) - G_ActivateBehavior( ent, BSET_SPAWN ); + if (ent->classname && ent->classname[0]) { + if (Q_strncmp("NPC_", ent->classname, 4) != 0) { // Not an NPC_spawner (rww - probably don't even care for MP, but whatever) + G_ActivateBehavior(ent, BSET_SPAWN); } } } @@ -967,168 +925,144 @@ void G_SpawnGEntityFromSpawnVars( qboolean inSubBSP ) { G_AddSpawnVarToken ==================== */ -char *G_AddSpawnVarToken( const char *string ) { - int l; - char *dest; +char *G_AddSpawnVarToken(const char *string) { + int l; + char *dest; - l = strlen( string ); - if ( level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) { - trap->Error( ERR_DROP, "G_AddSpawnVarToken: MAX_SPAWN_VARS_CHARS" ); + l = strlen(string); + if (level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS) { + trap->Error(ERR_DROP, "G_AddSpawnVarToken: MAX_SPAWN_VARS_CHARS"); } dest = level.spawnVarChars + level.numSpawnVarChars; - memcpy( dest, string, l+1 ); + memcpy(dest, string, l + 1); level.numSpawnVarChars += l + 1; return dest; } -void AddSpawnField(char *field, char *value) -{ - int i; +void AddSpawnField(char *field, char *value) { + int i; - for(i=0;iPrint( "HandleEntityAdjustment: failed sscanf on 'origin' (%s)\n", value ); - VectorClear( origin ); + if (Q_stricmp(value, NOVALUE) != 0) { + if (sscanf(value, "%f %f %f", &origin[0], &origin[1], &origin[2]) != 3) { + trap->Print("HandleEntityAdjustment: failed sscanf on 'origin' (%s)\n", value); + VectorClear(origin); } - } - else - { + } else { origin[0] = origin[1] = origin[2] = 0.0; } rotation = DEG2RAD(level.mRotationAdjust); - newOrigin[0] = origin[0]*cos(rotation) - origin[1]*sin(rotation); - newOrigin[1] = origin[0]*sin(rotation) + origin[1]*cos(rotation); + newOrigin[0] = origin[0] * cos(rotation) - origin[1] * sin(rotation); + newOrigin[1] = origin[0] * sin(rotation) + origin[1] * cos(rotation); newOrigin[2] = origin[2]; VectorAdd(newOrigin, level.mOriginAdjust, newOrigin); // damn VMs don't handle outputing a float that is compatible with sscanf in all cases - Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", newOrigin[0], newOrigin[1], newOrigin[2]); + Com_sprintf(temp, sizeof(temp), "%0.0f %0.0f %0.0f", newOrigin[0], newOrigin[1], newOrigin[2]); AddSpawnField("origin", temp); G_SpawnString("angles", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - if ( sscanf( value, "%f %f %f", &angles[0], &angles[1], &angles[2] ) != 3 ) { - trap->Print( "HandleEntityAdjustment: failed sscanf on 'angles' (%s)\n", value ); - VectorClear( angles ); + if (Q_stricmp(value, NOVALUE) != 0) { + if (sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]) != 3) { + trap->Print("HandleEntityAdjustment: failed sscanf on 'angles' (%s)\n", value); + VectorClear(angles); } angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f); // damn VMs don't handle outputing a float that is compatible with sscanf in all cases - Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]); + Com_sprintf(temp, sizeof(temp), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]); AddSpawnField("angles", temp); - } - else - { + } else { G_SpawnString("angle", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - angles[YAW] = atof( value ); - } - else - { + if (Q_stricmp(value, NOVALUE) != 0) { + angles[YAW] = atof(value); + } else { angles[YAW] = 0.0; } angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f); - Com_sprintf(temp, sizeof( temp ), "%0.0f", angles[YAW]); + Com_sprintf(temp, sizeof(temp), "%0.0f", angles[YAW]); AddSpawnField("angle", temp); } // RJR experimental code for handling "direction" field of breakable brushes // though direction is rarely ever used. G_SpawnString("direction", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - if ( sscanf( value, "%f %f %f", &angles[0], &angles[1], &angles[2] ) != 3 ) { - trap->Print( "HandleEntityAdjustment: failed sscanf on 'direction' (%s)\n", value ); - VectorClear( angles ); + if (Q_stricmp(value, NOVALUE) != 0) { + if (sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]) != 3) { + trap->Print("HandleEntityAdjustment: failed sscanf on 'direction' (%s)\n", value); + VectorClear(angles); } - } - else - { + } else { angles[0] = angles[1] = angles[2] = 0.0; } angles[YAW] = fmod(angles[YAW] + level.mRotationAdjust, 360.0f); - Com_sprintf(temp, sizeof( temp ), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]); + Com_sprintf(temp, sizeof(temp), "%0.0f %0.0f %0.0f", angles[0], angles[1], angles[2]); AddSpawnField("direction", temp); - AddSpawnField("BSPInstanceID", level.mTargetAdjust); G_SpawnString("targetname", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("targetname", temp); } G_SpawnString("target", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("target", temp); } G_SpawnString("killtarget", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("killtarget", temp); } G_SpawnString("brushparent", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("brushparent", temp); } G_SpawnString("brushchild", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("brushchild", temp); } G_SpawnString("enemy", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("enemy", temp); } G_SpawnString("ICARUSname", NOVALUE, &value); - if (Q_stricmp(value, NOVALUE) != 0) - { - Com_sprintf(temp, sizeof( temp ), "%s%s", level.mTargetAdjust, value); + if (Q_stricmp(value, NOVALUE) != 0) { + Com_sprintf(temp, sizeof(temp), "%s%s", level.mTargetAdjust, value); AddSpawnField("ICARUSname", temp); } } @@ -1143,224 +1077,125 @@ level's entity strings into level.spawnVars[] This does not actually spawn an entity. ==================== */ -qboolean G_ParseSpawnVars( qboolean inSubBSP ) { - char keyname[MAX_TOKEN_CHARS]; - char com_token[MAX_TOKEN_CHARS]; +qboolean G_ParseSpawnVars(qboolean inSubBSP) { + char keyname[MAX_TOKEN_CHARS]; + char com_token[MAX_TOKEN_CHARS]; level.numSpawnVars = 0; level.numSpawnVarChars = 0; // parse the opening brace - if ( !trap->GetEntityToken( com_token, sizeof( com_token ) ) ) { + if (!trap->GetEntityToken(com_token, sizeof(com_token))) { // end of spawn string return qfalse; } - if ( com_token[0] != '{' ) { - trap->Error( ERR_DROP, "G_ParseSpawnVars: found %s when expecting {",com_token ); + if (com_token[0] != '{') { + trap->Error(ERR_DROP, "G_ParseSpawnVars: found %s when expecting {", com_token); } // go through all the key / value pairs - while ( 1 ) { + while (1) { // parse key - if ( !trap->GetEntityToken( keyname, sizeof( keyname ) ) ) { - trap->Error( ERR_DROP, "G_ParseSpawnVars: EOF without closing brace" ); + if (!trap->GetEntityToken(keyname, sizeof(keyname))) { + trap->Error(ERR_DROP, "G_ParseSpawnVars: EOF without closing brace"); } - if ( keyname[0] == '}' ) { + if (keyname[0] == '}') { break; } // parse value - if ( !trap->GetEntityToken( com_token, sizeof( com_token ) ) ) { - trap->Error( ERR_DROP, "G_ParseSpawnVars: EOF without closing brace" ); + if (!trap->GetEntityToken(com_token, sizeof(com_token))) { + trap->Error(ERR_DROP, "G_ParseSpawnVars: EOF without closing brace"); } - if ( com_token[0] == '}' ) { - trap->Error( ERR_DROP, "G_ParseSpawnVars: closing brace without data" ); + if (com_token[0] == '}') { + trap->Error(ERR_DROP, "G_ParseSpawnVars: closing brace without data"); } - if ( level.numSpawnVars == MAX_SPAWN_VARS ) { - trap->Error( ERR_DROP, "G_ParseSpawnVars: MAX_SPAWN_VARS" ); + if (level.numSpawnVars == MAX_SPAWN_VARS) { + trap->Error(ERR_DROP, "G_ParseSpawnVars: MAX_SPAWN_VARS"); } - level.spawnVars[ level.numSpawnVars ][0] = G_AddSpawnVarToken( keyname ); - level.spawnVars[ level.numSpawnVars ][1] = G_AddSpawnVarToken( com_token ); + level.spawnVars[level.numSpawnVars][0] = G_AddSpawnVarToken(keyname); + level.spawnVars[level.numSpawnVars][1] = G_AddSpawnVarToken(com_token); level.numSpawnVars++; } - if (inSubBSP) - { + if (inSubBSP) { HandleEntityAdjustment(); } return qtrue; } - -static char *defaultStyles[32][3] = -{ - { // 0 normal - "z", - "z", - "z" - }, - { // 1 FLICKER (first variety) - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo", - "mmnmmommommnonmmonqnmmo" - }, - { // 2 SLOW STRONG PULSE - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", - "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb" - }, - { // 3 CANDLE (first variety) - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", - "mmmmmaaaaammmmmaaaaaabcdefgabcdefg" - }, - { // 4 FAST STROBE - "mamamamamama", - "mamamamamama", - "mamamamamama" - }, - { // 5 GENTLE PULSE 1 - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj", - "jklmnopqrstuvwxyzyxwvutsrqponmlkj" - }, - { // 6 FLICKER (second variety) - "nmonqnmomnmomomno", - "nmonqnmomnmomomno", - "nmonqnmomnmomomno" - }, - { // 7 CANDLE (second variety) - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm", - "mmmaaaabcdefgmmmmaaaammmaamm" - }, - { // 8 CANDLE (third variety) - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", - "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa" - }, - { // 9 SLOW STROBE (fourth variety) - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz", - "aaaaaaaazzzzzzzz" - }, - { // 10 FLUORESCENT FLICKER - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma", - "mmamammmmammamamaaamammma" - }, - { // 11 SLOW PULSE NOT FADE TO BLACK - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba", - "abcdefghijklmnopqrrqponmlkjihgfedcba" - }, - { // 12 FAST PULSE FOR JEREMY - "mkigegik", - "mkigegik", - "mkigegik" - }, - { // 13 Test Blending - "abcdefghijklmqrstuvwxyz", - "zyxwvutsrqmlkjihgfedcba", - "aammbbzzccllcckkffyyggp" - }, - { // 14 - "", - "", - "" - }, - { // 15 - "", - "", - "" - }, - { // 16 - "", - "", - "" - }, - { // 17 - "", - "", - "" - }, - { // 18 - "", - "", - "" - }, - { // 19 - "", - "", - "" - }, - { // 20 - "", - "", - "" - }, - { // 21 - "", - "", - "" - }, - { // 22 - "", - "", - "" - }, - { // 23 - "", - "", - "" - }, - { // 24 - "", - "", - "" - }, - { // 25 - "", - "", - "" - }, - { // 26 - "", - "", - "" - }, - { // 27 - "", - "", - "" - }, - { // 28 - "", - "", - "" - }, - { // 29 - "", - "", - "" - }, - { // 30 - "", - "", - "" - }, - { // 31 - "", - "", - "" - } -}; +static char *defaultStyles[32][3] = { + {// 0 normal + "z", "z", "z"}, + {// 1 FLICKER (first variety) + "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo", "mmnmmommommnonmmonqnmmo"}, + {// 2 SLOW STRONG PULSE + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb", + "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcb"}, + {// 3 CANDLE (first variety) + "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg", "mmmmmaaaaammmmmaaaaaabcdefgabcdefg"}, + {// 4 FAST STROBE + "mamamamamama", "mamamamamama", "mamamamamama"}, + {// 5 GENTLE PULSE 1 + "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj", "jklmnopqrstuvwxyzyxwvutsrqponmlkj"}, + {// 6 FLICKER (second variety) + "nmonqnmomnmomomno", "nmonqnmomnmomomno", "nmonqnmomnmomomno"}, + {// 7 CANDLE (second variety) + "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm", "mmmaaaabcdefgmmmmaaaammmaamm"}, + {// 8 CANDLE (third variety) + "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa", "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa"}, + {// 9 SLOW STROBE (fourth variety) + "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz", "aaaaaaaazzzzzzzz"}, + {// 10 FLUORESCENT FLICKER + "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma", "mmamammmmammamamaaamammma"}, + {// 11 SLOW PULSE NOT FADE TO BLACK + "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba", "abcdefghijklmnopqrrqponmlkjihgfedcba"}, + {// 12 FAST PULSE FOR JEREMY + "mkigegik", "mkigegik", "mkigegik"}, + {// 13 Test Blending + "abcdefghijklmqrstuvwxyz", "zyxwvutsrqmlkjihgfedcba", "aammbbzzccllcckkffyyggp"}, + {// 14 + "", "", ""}, + {// 15 + "", "", ""}, + {// 16 + "", "", ""}, + {// 17 + "", "", ""}, + {// 18 + "", "", ""}, + {// 19 + "", "", ""}, + {// 20 + "", "", ""}, + {// 21 + "", "", ""}, + {// 22 + "", "", ""}, + {// 23 + "", "", ""}, + {// 24 + "", "", ""}, + {// 25 + "", "", ""}, + {// 26 + "", "", ""}, + {// 27 + "", "", ""}, + {// 28 + "", "", ""}, + {// 29 + "", "", ""}, + {// 30 + "", "", ""}, + {// 31 + "", "", ""}}; void *precachedKyle = 0; -void scriptrunner_run (gentity_t *self); +void scriptrunner_run(gentity_t *self); /*QUAKED worldspawn (0 0 0) ? @@ -1382,57 +1217,50 @@ BSP Options "fogstart" override fog start distance and force linear "radarrange" for Siege/Vehicle radar - default range is 2500 */ -extern void EWebPrecache(void); //g_items.c +extern void EWebPrecache(void); // g_items.c float g_cullDistance; -void SP_worldspawn( void ) -{ - char *text, temp[32]; - int i; - int lengthRed, lengthBlue, lengthGreen; - - //I want to "cull" entities out of net sends to clients to reduce - //net traffic on our larger open maps -rww +void SP_worldspawn(void) { + char *text, temp[32]; + int i; + int lengthRed, lengthBlue, lengthGreen; + + // I want to "cull" entities out of net sends to clients to reduce + // net traffic on our larger open maps -rww G_SpawnFloat("distanceCull", "6000.0", &g_cullDistance); trap->SetServerCull(g_cullDistance); - G_SpawnString( "classname", "", &text ); - if ( Q_stricmp( text, "worldspawn" ) ) { - trap->Error( ERR_DROP, "SP_worldspawn: The first entity isn't 'worldspawn'" ); + G_SpawnString("classname", "", &text); + if (Q_stricmp(text, "worldspawn")) { + trap->Error(ERR_DROP, "SP_worldspawn: The first entity isn't 'worldspawn'"); } - for ( i = 0 ; i < level.numSpawnVars ; i++ ) - { - if ( Q_stricmp( "spawnscript", level.spawnVars[i][0] ) == 0 ) - {//ONly let them set spawnscript, we don't want them setting an angle or something on the world. - G_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], &g_entities[ENTITYNUM_WORLD] ); + for (i = 0; i < level.numSpawnVars; i++) { + if (Q_stricmp("spawnscript", level.spawnVars[i][0]) == + 0) { // ONly let them set spawnscript, we don't want them setting an angle or something on the world. + G_ParseField(level.spawnVars[i][0], level.spawnVars[i][1], &g_entities[ENTITYNUM_WORLD]); } } - //The server will precache the standard model and animations, so that there is no hit - //when the first client connnects. - if (!BGPAFtextLoaded) - { + // The server will precache the standard model and animations, so that there is no hit + // when the first client connnects. + if (!BGPAFtextLoaded) { BG_ParseAnimationFile("models/players/_humanoid/animation.cfg", bgHumanoidAnimations, qtrue); } - if (!precachedKyle) - { + if (!precachedKyle) { int defSkin; trap->G2API_InitGhoul2Model(&precachedKyle, "models/players/" DEFAULT_MODEL "/model.glm", 0, 0, -20, 0, 0); - if (precachedKyle) - { + if (precachedKyle) { defSkin = trap->R_RegisterSkin("models/players/" DEFAULT_MODEL "/model_default.skin"); trap->G2API_SetSkin(precachedKyle, 0, defSkin, defSkin); } } - if (!g2SaberInstance) - { + if (!g2SaberInstance) { trap->G2API_InitGhoul2Model(&g2SaberInstance, DEFAULT_SABER_MODEL, 0, 0, -20, 0, 0); - if (g2SaberInstance) - { + if (g2SaberInstance) { // indicate we will be bolted to model 0 (ie the player) on bolt 0 (always the right hand) when we get copied trap->G2API_SetBoltInfo(g2SaberInstance, 0, 0); // now set up the gun bolt on it @@ -1440,32 +1268,31 @@ void SP_worldspawn( void ) } } - if (level.gametype == GT_SIEGE) - { //a tad bit of a hack, but.. + if (level.gametype == GT_SIEGE) { // a tad bit of a hack, but.. EWebPrecache(); } // make some data visible to connecting client - trap->SetConfigstring( CS_GAME_VERSION, GAME_VERSION ); + trap->SetConfigstring(CS_GAME_VERSION, GAME_VERSION); - trap->SetConfigstring( CS_LEVEL_START_TIME, va("%i", level.startTime ) ); + trap->SetConfigstring(CS_LEVEL_START_TIME, va("%i", level.startTime)); - G_SpawnString( "music", "", &text ); - trap->SetConfigstring( CS_MUSIC, text ); + G_SpawnString("music", "", &text); + trap->SetConfigstring(CS_MUSIC, text); - G_SpawnString( "message", "", &text ); - trap->SetConfigstring( CS_MESSAGE, text ); // map specific message + G_SpawnString("message", "", &text); + trap->SetConfigstring(CS_MESSAGE, text); // map specific message - trap->SetConfigstring( CS_MOTD, g_motd.string ); // message of the day + trap->SetConfigstring(CS_MOTD, g_motd.string); // message of the day - G_SpawnString( "gravity", "800", &text ); - trap->Cvar_Set( "g_gravity", text ); - trap->Cvar_Update( &g_gravity ); + G_SpawnString("gravity", "800", &text); + trap->Cvar_Set("g_gravity", text); + trap->Cvar_Update(&g_gravity); - G_SpawnString( "enableBreath", "0", &text ); + G_SpawnString("enableBreath", "0", &text); - G_SpawnString( "soundSet", "default", &text ); - trap->SetConfigstring( CS_GLOBAL_AMBIENT_SET, text ); + G_SpawnString("soundSet", "default", &text); + trap->SetConfigstring(CS_GLOBAL_AMBIENT_SET, text); g_entities[ENTITYNUM_WORLD].s.number = ENTITYNUM_WORLD; g_entities[ENTITYNUM_WORLD].r.ownerNum = ENTITYNUM_NONE; @@ -1476,67 +1303,56 @@ void SP_worldspawn( void ) g_entities[ENTITYNUM_NONE].classname = "nothing"; // see if we want a warmup time - trap->SetConfigstring( CS_WARMUP, "" ); - if ( g_restarted.integer ) { - trap->Cvar_Set( "g_restarted", "0" ); - trap->Cvar_Update( &g_restarted ); + trap->SetConfigstring(CS_WARMUP, ""); + if (g_restarted.integer) { + trap->Cvar_Set("g_restarted", "0"); + trap->Cvar_Update(&g_restarted); level.warmupTime = 0; - } - else if ( g_doWarmup.integer && level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && level.gametype != GT_SIEGE ) { // Turn it on + } else if (g_doWarmup.integer && level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && level.gametype != GT_SIEGE) { // Turn it on level.warmupTime = -1; - trap->SetConfigstring( CS_WARMUP, va("%i", level.warmupTime) ); - G_LogPrintf( "Warmup:\n" ); + trap->SetConfigstring(CS_WARMUP, va("%i", level.warmupTime)); + G_LogPrintf("Warmup:\n"); } - trap->SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+0, defaultStyles[0][0]); - trap->SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+1, defaultStyles[0][1]); - trap->SetConfigstring(CS_LIGHT_STYLES+(LS_STYLES_START*3)+2, defaultStyles[0][2]); + trap->SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 0, defaultStyles[0][0]); + trap->SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 1, defaultStyles[0][1]); + trap->SetConfigstring(CS_LIGHT_STYLES + (LS_STYLES_START * 3) + 2, defaultStyles[0][2]); - for(i=1;iSetConfigstring(CS_LIGHT_STYLES+((i+LS_STYLES_START)*3)+0, text); + trap->SetConfigstring(CS_LIGHT_STYLES + ((i + LS_STYLES_START) * 3) + 0, text); Com_sprintf(temp, sizeof(temp), "ls_%dg", i); G_SpawnString(temp, defaultStyles[i][1], &text); lengthGreen = strlen(text); - trap->SetConfigstring(CS_LIGHT_STYLES+((i+LS_STYLES_START)*3)+1, text); + trap->SetConfigstring(CS_LIGHT_STYLES + ((i + LS_STYLES_START) * 3) + 1, text); Com_sprintf(temp, sizeof(temp), "ls_%db", i); G_SpawnString(temp, defaultStyles[i][2], &text); lengthBlue = strlen(text); - trap->SetConfigstring(CS_LIGHT_STYLES+((i+LS_STYLES_START)*3)+2, text); + trap->SetConfigstring(CS_LIGHT_STYLES + ((i + LS_STYLES_START) * 3) + 2, text); - if (lengthRed != lengthGreen || lengthGreen != lengthBlue) - { - Com_Error(ERR_DROP, "Style %d has inconsistent lengths: R %d, G %d, B %d", - i, lengthRed, lengthGreen, lengthBlue); + if (lengthRed != lengthGreen || lengthGreen != lengthBlue) { + Com_Error(ERR_DROP, "Style %d has inconsistent lengths: R %d, G %d, B %d", i, lengthRed, lengthGreen, lengthBlue); } } } -//rww - Planning on having something here? -qboolean SP_bsp_worldspawn ( void ) -{ - return qtrue; -} +// rww - Planning on having something here? +qboolean SP_bsp_worldspawn(void) { return qtrue; } -void G_PrecacheSoundsets( void ) -{ - gentity_t *ent = NULL; +void G_PrecacheSoundsets(void) { + gentity_t *ent = NULL; int i; int countedSets = 0; - for ( i = 0; i < MAX_GENTITIES; i++ ) - { + for (i = 0; i < MAX_GENTITIES; i++) { ent = &g_entities[i]; - if (ent->inuse && ent->soundSet && ent->soundSet[0]) - { - if (countedSets >= MAX_AMBIENT_SETS) - { + if (ent->inuse && ent->soundSet && ent->soundSet[0]) { + if (countedSets >= MAX_AMBIENT_SETS) { Com_Error(ERR_DROP, "MAX_AMBIENT_SETS was exceeded! (too many soundsets)\n"); } @@ -1546,19 +1362,19 @@ void G_PrecacheSoundsets( void ) } } -void G_LinkLocations( void ) { +void G_LinkLocations(void) { int i, n; - if ( level.locations.linked ) + if (level.locations.linked) return; level.locations.linked = qtrue; - trap->SetConfigstring( CS_LOCATIONS, "unknown" ); + trap->SetConfigstring(CS_LOCATIONS, "unknown"); - for ( i=0, n=1; iSetConfigstring( CS_LOCATIONS + n, level.locations.data[i].message ); + trap->SetConfigstring(CS_LOCATIONS + n, level.locations.data[i].message); n++; } // All linked together now @@ -1571,7 +1387,7 @@ G_SpawnEntitiesFromString Parses textual entity definitions out of an entstring and spawns gentities. ============== */ -void G_SpawnEntitiesFromString( qboolean inSubBSP ) { +void G_SpawnEntitiesFromString(qboolean inSubBSP) { // allow calls to G_Spawn*() level.spawning = qtrue; level.numSpawnVars = 0; @@ -1579,53 +1395,45 @@ void G_SpawnEntitiesFromString( qboolean inSubBSP ) { // the worldspawn is not an actual entity, but it still // has a "spawn" function to perform any global setup // needed by a level (setting configstrings or cvars, etc) - if ( !G_ParseSpawnVars(qfalse) ) { - trap->Error( ERR_DROP, "SpawnEntities: no entities" ); + if (!G_ParseSpawnVars(qfalse)) { + trap->Error(ERR_DROP, "SpawnEntities: no entities"); } - if (!inSubBSP) - { + if (!inSubBSP) { SP_worldspawn(); - } - else - { + } else { // Skip this guy if its worldspawn fails - if ( !SP_bsp_worldspawn() ) - { + if (!SP_bsp_worldspawn()) { return; } } // parse ents - while( G_ParseSpawnVars(inSubBSP) ) { + while (G_ParseSpawnVars(inSubBSP)) { G_SpawnGEntityFromSpawnVars(inSubBSP); } - if( g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0] ) - {//World has a spawn script, but we don't want the world in ICARUS and running scripts, - //so make a scriptrunner and start it going. + if (g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN] && + g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN][0]) { // World has a spawn script, but we don't want the world in ICARUS and running scripts, + // so make a scriptrunner and start it going. gentity_t *script_runner = G_Spawn(); - if ( script_runner ) - { + if (script_runner) { script_runner->behaviorSet[BSET_USE] = g_entities[ENTITYNUM_WORLD].behaviorSet[BSET_SPAWN]; script_runner->count = 1; script_runner->think = scriptrunner_run; script_runner->nextthink = level.time + 100; - if ( script_runner->inuse ) - { - trap->ICARUS_InitEnt( (sharedEntity_t *)script_runner ); + if (script_runner->inuse) { + trap->ICARUS_InitEnt((sharedEntity_t *)script_runner); } } } - if (!inSubBSP) - { - level.spawning = qfalse; // any future calls to G_Spawn*() will be errors + if (!inSubBSP) { + level.spawning = qfalse; // any future calls to G_Spawn*() will be errors } G_LinkLocations(); G_PrecacheSoundsets(); } - diff --git a/codemp/game/g_svcmds.c b/codemp/game/g_svcmds.c index c1471595e6..d0684ff0a1 100644 --- a/codemp/game/g_svcmds.c +++ b/codemp/game/g_svcmds.c @@ -37,7 +37,8 @@ You can add or remove addresses from the filter list with: addip removeip -The ip address is specified in dot format, and any unspecified digits will match any value, so you can specify an entire class C network with "addip 192.246.40". +The ip address is specified in dot format, and any unspecified digits will match any value, so you can specify an entire class C network with "addip +192.246.40". Removeip will only remove an address specified exactly the same way. You cannot addip a subnet, then removeip a single host. @@ -48,7 +49,8 @@ g_filterban <0 or 1> If 1 (the default), then ip addresses matching the current list will be prohibited from entering the game. This is the default setting. -If 0, then only addresses matching the list will be allowed. This lets you easily set up a private game, or a game that only allows players from your local network. +If 0, then only addresses matching the list will be allowed. This lets you easily set up a private game, or a game that only allows players from your local +network. ============================================================================== @@ -58,47 +60,47 @@ typedef struct ipFilter_s { uint32_t mask, compare; } ipFilter_t; -#define MAX_IPFILTERS (1024) +#define MAX_IPFILTERS (1024) -static ipFilter_t ipFilters[MAX_IPFILTERS]; -static int numIPFilters; +static ipFilter_t ipFilters[MAX_IPFILTERS]; +static int numIPFilters; /* ================= StringToFilter ================= */ -static qboolean StringToFilter( char *s, ipFilter_t *f ) { +static qboolean StringToFilter(char *s, ipFilter_t *f) { char num[128]; int i, j; byteAlias_t b, m; b.ui = m.ui = 0u; - for ( i=0; i<4; i++ ) { - if ( *s < '0' || *s > '9' ) { - if ( *s == '*' ) { + for (i = 0; i < 4; i++) { + if (*s < '0' || *s > '9') { + if (*s == '*') { // 'match any' // b[i] and m[i] to 0 s++; - if ( !*s ) + if (!*s) break; s++; continue; } - trap->Print( "Bad filter address: %s\n", s ); + trap->Print("Bad filter address: %s\n", s); return qfalse; } j = 0; - while ( *s >= '0' && *s <= '9' ) + while (*s >= '0' && *s <= '9') num[j++] = *s++; num[j] = 0; - b.b[i] = (byte)atoi( num ); + b.b[i] = (byte)atoi(num); m.b[i] = 0xFF; - if ( !*s ) + if (!*s) break; s++; @@ -115,35 +117,35 @@ static qboolean StringToFilter( char *s, ipFilter_t *f ) { UpdateIPBans ================= */ -static void UpdateIPBans( void ) { +static void UpdateIPBans(void) { byteAlias_t b, m; int i, j; char ip[NET_ADDRSTRMAXLEN], iplist_final[MAX_CVAR_VALUE_STRING]; *iplist_final = 0; - for ( i=0; iCvar_Set( "g_banIPs", iplist_final ); + trap->Cvar_Set("g_banIPs", iplist_final); } /* @@ -151,7 +153,7 @@ static void UpdateIPBans( void ) { G_FilterPacket ================= */ -qboolean G_FilterPacket( char *from ) { +qboolean G_FilterPacket(char *from) { int i; uint32_t in; byteAlias_t m; @@ -159,21 +161,21 @@ qboolean G_FilterPacket( char *from ) { i = 0; p = from; - while ( *p && i < 4 ) { + while (*p && i < 4) { m.b[i] = 0; - while ( *p >= '0' && *p <= '9' ) { - m.b[i] = m.b[i]*10 + (*p - '0'); + while (*p >= '0' && *p <= '9') { + m.b[i] = m.b[i] * 10 + (*p - '0'); p++; } - if ( !*p || *p == ':' ) + if (!*p || *p == ':') break; i++, p++; } in = m.ui; - for ( i=0; iPrint( "IP filter list is full\n" ); + if (i == numIPFilters) { + if (numIPFilters == MAX_IPFILTERS) { + trap->Print("IP filter list is full\n"); return; } numIPFilters++; } - if ( !StringToFilter( str, &ipFilters[i] ) ) + if (!StringToFilter(str, &ipFilters[i])) ipFilters[i].compare = 0xFFFFFFFFu; UpdateIPBans(); @@ -211,21 +213,21 @@ static void AddIP( char *str ) { G_ProcessIPBans ================= */ -void G_ProcessIPBans( void ) { +void G_ProcessIPBans(void) { char *s = NULL, *t = NULL, str[MAX_CVAR_VALUE_STRING] = {0}; - Q_strncpyz( str, g_banIPs.string, sizeof( str ) ); + Q_strncpyz(str, g_banIPs.string, sizeof(str)); - for ( t=s=g_banIPs.string; *t; t=s ) { - s = strchr( s, ' ' ); - if ( !s ) + for (t = s = g_banIPs.string; *t; t = s) { + s = strchr(s, ' '); + if (!s) break; - while ( *s == ' ' ) + while (*s == ' ') *s++ = 0; - if ( *t ) - AddIP( t ); + if (*t) + AddIP(t); } } @@ -234,18 +236,17 @@ void G_ProcessIPBans( void ) { Svcmd_AddIP_f ================= */ -void Svcmd_AddIP_f (void) -{ - char str[MAX_TOKEN_CHARS]; +void Svcmd_AddIP_f(void) { + char str[MAX_TOKEN_CHARS]; - if ( trap->Argc() < 2 ) { + if (trap->Argc() < 2) { trap->Print("Usage: addip \n"); return; } - trap->Argv( 1, str, sizeof( str ) ); + trap->Argv(1, str, sizeof(str)); - AddIP( str ); + AddIP(str); } /* @@ -253,50 +254,47 @@ void Svcmd_AddIP_f (void) Svcmd_RemoveIP_f ================= */ -void Svcmd_RemoveIP_f (void) -{ - ipFilter_t f; - int i; - char str[MAX_TOKEN_CHARS]; +void Svcmd_RemoveIP_f(void) { + ipFilter_t f; + int i; + char str[MAX_TOKEN_CHARS]; - if ( trap->Argc() < 2 ) { + if (trap->Argc() < 2) { trap->Print("Usage: removeip \n"); return; } - trap->Argv( 1, str, sizeof( str ) ); + trap->Argv(1, str, sizeof(str)); - if (!StringToFilter (str, &f)) + if (!StringToFilter(str, &f)) return; - for (i=0 ; iPrint ("Removed.\n"); + trap->Print("Removed.\n"); UpdateIPBans(); return; } } - trap->Print ( "Didn't find %s.\n", str ); + trap->Print("Didn't find %s.\n", str); } -void Svcmd_ListIP_f (void) -{ - int i, count = 0; +void Svcmd_ListIP_f(void) { + int i, count = 0; byteAlias_t b; - for(i = 0; i < numIPFilters; i++) { - if ( ipFilters[i].compare == 0xffffffffu ) + for (i = 0; i < numIPFilters; i++) { + if (ipFilters[i].compare == 0xffffffffu) continue; b.ui = ipFilters[i].compare; - trap->Print ("%i.%i.%i.%i\n", b.b[0], b.b[1], b.b[2], b.b[3]); + trap->Print("%i.%i.%i.%i\n", b.b[0], b.b[1], b.b[2], b.b[3]); count++; } - trap->Print ("%i bans.\n", count); + trap->Print("%i bans.\n", count); } /* @@ -304,17 +302,17 @@ void Svcmd_ListIP_f (void) Svcmd_EntityList_f =================== */ -void Svcmd_EntityList_f (void) { - int e; - gentity_t *check; +void Svcmd_EntityList_f(void) { + int e; + gentity_t *check; check = g_entities; - for (e = 0; e < level.num_entities ; e++, check++) { - if ( !check->inuse ) { + for (e = 0; e < level.num_entities; e++, check++) { + if (!check->inuse) { continue; } trap->Print("%3i:", e); - switch ( check->s.eType ) { + switch (check->s.eType) { case ET_GENERAL: trap->Print("ET_GENERAL "); break; @@ -371,49 +369,49 @@ void Svcmd_EntityList_f (void) { break; } - if ( check->classname ) { + if (check->classname) { trap->Print("%s", check->classname); } trap->Print("\n"); } } -qboolean StringIsInteger( const char *s ); +qboolean StringIsInteger(const char *s); /* =================== ClientForString =================== */ -gclient_t *ClientForString( const char *s ) { - gclient_t *cl; - int idnum; - char cleanInput[MAX_STRING_CHARS]; +gclient_t *ClientForString(const char *s) { + gclient_t *cl; + int idnum; + char cleanInput[MAX_STRING_CHARS]; // numeric values could be slot numbers - if ( StringIsInteger( s ) ) { - idnum = atoi( s ); - if ( idnum >= 0 && idnum < level.maxclients ) { + if (StringIsInteger(s)) { + idnum = atoi(s); + if (idnum >= 0 && idnum < level.maxclients) { cl = &level.clients[idnum]; - if ( cl->pers.connected == CON_CONNECTED ) { + if (cl->pers.connected == CON_CONNECTED) { return cl; } } } - Q_strncpyz( cleanInput, s, sizeof(cleanInput) ); - Q_StripColor( cleanInput ); + Q_strncpyz(cleanInput, s, sizeof(cleanInput)); + Q_StripColor(cleanInput); // check for a name match - for ( idnum=0,cl=level.clients ; idnum < level.maxclients ; idnum++,cl++ ) { - if ( cl->pers.connected != CON_CONNECTED ) { + for (idnum = 0, cl = level.clients; idnum < level.maxclients; idnum++, cl++) { + if (cl->pers.connected != CON_CONNECTED) { continue; } - if ( !Q_stricmp( cl->pers.netname_nocolor, cleanInput ) ) { + if (!Q_stricmp(cl->pers.netname_nocolor, cleanInput)) { return cl; } } - trap->Print( "User %s is not on the server\n", s ); + trap->Print("User %s is not on the server\n", s); return NULL; } @@ -424,74 +422,72 @@ Svcmd_ForceTeam_f forceteam =================== */ -void Svcmd_ForceTeam_f( void ) { - gclient_t *cl; - char str[MAX_TOKEN_CHARS]; +void Svcmd_ForceTeam_f(void) { + gclient_t *cl; + char str[MAX_TOKEN_CHARS]; - if ( trap->Argc() < 3 ) { + if (trap->Argc() < 3) { trap->Print("Usage: forceteam \n"); return; } // find the player - trap->Argv( 1, str, sizeof( str ) ); - cl = ClientForString( str ); - if ( !cl ) { + trap->Argv(1, str, sizeof(str)); + cl = ClientForString(str); + if (!cl) { return; } // set the team - trap->Argv( 2, str, sizeof( str ) ); - SetTeam( &g_entities[cl - level.clients], str ); + trap->Argv(2, str, sizeof(str)); + SetTeam(&g_entities[cl - level.clients], str); } -char *ConcatArgs( int start ); -void Svcmd_Say_f( void ) { +char *ConcatArgs(int start); +void Svcmd_Say_f(void) { char *p = NULL; // don't let text be too long for malicious reasons char text[MAX_SAY_TEXT] = {0}; - if ( trap->Argc () < 2 ) + if (trap->Argc() < 2) return; - p = ConcatArgs( 1 ); + p = ConcatArgs(1); - if ( strlen( p ) >= MAX_SAY_TEXT ) { - p[MAX_SAY_TEXT-1] = '\0'; - G_SecurityLogPrintf( "Cmd_Say_f from -1 (server) has been truncated: %s\n", p ); + if (strlen(p) >= MAX_SAY_TEXT) { + p[MAX_SAY_TEXT - 1] = '\0'; + G_SecurityLogPrintf("Cmd_Say_f from -1 (server) has been truncated: %s\n", p); } - Q_strncpyz( text, p, sizeof(text) ); - Q_strstrip( text, "\n\r", " " ); + Q_strncpyz(text, p, sizeof(text)); + Q_strstrip(text, "\n\r", " "); - //G_LogPrintf( "say: server: %s\n", text ); - trap->SendServerCommand( -1, va("print \"server: %s\n\"", text ) ); + // G_LogPrintf( "say: server: %s\n", text ); + trap->SendServerCommand(-1, va("print \"server: %s\n\"", text)); } typedef struct svcmd_s { - const char *name; - void (*func)(void); - qboolean dedicated; + const char *name; + void (*func)(void); + qboolean dedicated; } svcmd_t; -int svcmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((svcmd_t*)b)->name ); -} +int svcmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((svcmd_t *)b)->name); } svcmd_t svcmds[] = { - { "addbot", Svcmd_AddBot_f, qfalse }, - { "addip", Svcmd_AddIP_f, qfalse }, - { "botlist", Svcmd_BotList_f, qfalse }, - { "entitylist", Svcmd_EntityList_f, qfalse }, - { "forceteam", Svcmd_ForceTeam_f, qfalse }, - { "game_memory", Svcmd_GameMem_f, qfalse }, - { "listip", Svcmd_ListIP_f, qfalse }, - { "removeip", Svcmd_RemoveIP_f, qfalse }, - { "say", Svcmd_Say_f, qtrue }, - { "toggleallowvote", Svcmd_ToggleAllowVote_f, qfalse }, - { "toggleuserinfovalidation", Svcmd_ToggleUserinfoValidation_f, qfalse }, + {"addbot", Svcmd_AddBot_f, qfalse}, + {"addip", Svcmd_AddIP_f, qfalse}, + {"botlist", Svcmd_BotList_f, qfalse}, + {"entitylist", Svcmd_EntityList_f, qfalse}, + {"forceteam", Svcmd_ForceTeam_f, qfalse}, + {"game_memory", Svcmd_GameMem_f, qfalse}, + {"listip", Svcmd_ListIP_f, qfalse}, + {"removeip", Svcmd_RemoveIP_f, qfalse}, + {"say", Svcmd_Say_f, qtrue}, + {"toggleallowvote", Svcmd_ToggleAllowVote_f, qfalse}, + {"toggleuserinfovalidation", Svcmd_ToggleUserinfoValidation_f, qfalse}, }; -static const size_t numsvcmds = ARRAY_LEN( svcmds ); +static const size_t numsvcmds = ARRAY_LEN(svcmds); /* ================= @@ -499,20 +495,19 @@ ConsoleCommand ================= */ -qboolean ConsoleCommand( void ) { - char cmd[MAX_TOKEN_CHARS] = {0}; - svcmd_t *command = NULL; +qboolean ConsoleCommand(void) { + char cmd[MAX_TOKEN_CHARS] = {0}; + svcmd_t *command = NULL; - trap->Argv( 0, cmd, sizeof( cmd ) ); + trap->Argv(0, cmd, sizeof(cmd)); - command = (svcmd_t *)Q_LinearSearch( cmd, svcmds, numsvcmds, sizeof( svcmds[0] ), svcmdcmp ); - if ( !command ) + command = (svcmd_t *)Q_LinearSearch(cmd, svcmds, numsvcmds, sizeof(svcmds[0]), svcmdcmp); + if (!command) return qfalse; - if ( command->dedicated && !dedicated.integer ) + if (command->dedicated && !dedicated.integer) return qfalse; command->func(); return qtrue; } - diff --git a/codemp/game/g_syscalls.c b/codemp/game/g_syscalls.c index 3e49935e17..f4fb9de4d1 100644 --- a/codemp/game/g_syscalls.c +++ b/codemp/game/g_syscalls.c @@ -25,892 +25,425 @@ along with this program; if not, see . // this file is only included when building a dll #include "g_local.h" -static void TranslateSyscalls( void ); +static void TranslateSyscalls(void); -static intptr_t (QDECL *Q_syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; -Q_EXPORT void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) { +static intptr_t(QDECL *Q_syscall)(intptr_t arg, ...) = (intptr_t(QDECL *)(intptr_t, ...)) - 1; +Q_EXPORT void dllEntry(intptr_t(QDECL *syscallptr)(intptr_t arg, ...)) { Q_syscall = syscallptr; TranslateSyscalls(); } -int PASSFLOAT( float x ) { +int PASSFLOAT(float x) { byteAlias_t fi; fi.f = x; return fi.i; } -void trap_Print( const char *fmt ) { - Q_syscall( G_PRINT, fmt ); -} -NORETURN void trap_Error( const char *fmt ) { - Q_syscall( G_ERROR, fmt ); +void trap_Print(const char *fmt) { Q_syscall(G_PRINT, fmt); } +NORETURN void trap_Error(const char *fmt) { + Q_syscall(G_ERROR, fmt); exit(1); } -int trap_Milliseconds( void ) { - return Q_syscall( G_MILLISECONDS ); -} -void trap_PrecisionTimer_Start(void **theNewTimer) { - Q_syscall(G_PRECISIONTIMER_START, theNewTimer); -} -int trap_PrecisionTimer_End(void *theTimer) { - return Q_syscall(G_PRECISIONTIMER_END, theTimer); -} -void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, uint32_t flags ) { - Q_syscall( G_CVAR_REGISTER, cvar, var_name, value, flags ); -} -void trap_Cvar_Update( vmCvar_t *cvar ) { - Q_syscall( G_CVAR_UPDATE, cvar ); -} -void trap_Cvar_Set( const char *var_name, const char *value ) { - Q_syscall( G_CVAR_SET, var_name, value ); -} -int trap_Cvar_VariableIntegerValue( const char *var_name ) { - return Q_syscall( G_CVAR_VARIABLE_INTEGER_VALUE, var_name ); -} -void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { - Q_syscall( G_CVAR_VARIABLE_STRING_BUFFER, var_name, buffer, bufsize ); -} -int trap_Argc( void ) { - return Q_syscall( G_ARGC ); -} -void trap_Argv( int n, char *buffer, int bufferLength ) { - Q_syscall( G_ARGV, n, buffer, bufferLength ); -} -int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - return Q_syscall( G_FS_FOPEN_FILE, qpath, f, mode ); -} -void trap_FS_Read( void *buffer, int len, fileHandle_t f ) { - Q_syscall( G_FS_READ, buffer, len, f ); -} -void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) { - Q_syscall( G_FS_WRITE, buffer, len, f ); -} -void trap_FS_FCloseFile( fileHandle_t f ) { - Q_syscall( G_FS_FCLOSE_FILE, f ); -} -void trap_SendConsoleCommand( int exec_when, const char *text ) { - Q_syscall( G_SEND_CONSOLE_COMMAND, exec_when, text ); -} -void trap_LocateGameData( sharedEntity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *clients, int sizeofGClient ) { - Q_syscall( G_LOCATE_GAME_DATA, gEnts, numGEntities, sizeofGEntity_t, clients, sizeofGClient ); -} -void trap_DropClient( int clientNum, const char *reason ) { - Q_syscall( G_DROP_CLIENT, clientNum, reason ); -} -void trap_SendServerCommand( int clientNum, const char *text ) { - if ( strlen( text ) > 1022 ) { - G_SecurityLogPrintf( "trap_SendServerCommand( %d, ... ) length exceeds 1022.\n", clientNum ); - G_SecurityLogPrintf( "text [%s]\n", text ); +int trap_Milliseconds(void) { return Q_syscall(G_MILLISECONDS); } +void trap_PrecisionTimer_Start(void **theNewTimer) { Q_syscall(G_PRECISIONTIMER_START, theNewTimer); } +int trap_PrecisionTimer_End(void *theTimer) { return Q_syscall(G_PRECISIONTIMER_END, theTimer); } +void trap_Cvar_Register(vmCvar_t *cvar, const char *var_name, const char *value, uint32_t flags) { Q_syscall(G_CVAR_REGISTER, cvar, var_name, value, flags); } +void trap_Cvar_Update(vmCvar_t *cvar) { Q_syscall(G_CVAR_UPDATE, cvar); } +void trap_Cvar_Set(const char *var_name, const char *value) { Q_syscall(G_CVAR_SET, var_name, value); } +int trap_Cvar_VariableIntegerValue(const char *var_name) { return Q_syscall(G_CVAR_VARIABLE_INTEGER_VALUE, var_name); } +void trap_Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize) { Q_syscall(G_CVAR_VARIABLE_STRING_BUFFER, var_name, buffer, bufsize); } +int trap_Argc(void) { return Q_syscall(G_ARGC); } +void trap_Argv(int n, char *buffer, int bufferLength) { Q_syscall(G_ARGV, n, buffer, bufferLength); } +int trap_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode) { return Q_syscall(G_FS_FOPEN_FILE, qpath, f, mode); } +void trap_FS_Read(void *buffer, int len, fileHandle_t f) { Q_syscall(G_FS_READ, buffer, len, f); } +void trap_FS_Write(const void *buffer, int len, fileHandle_t f) { Q_syscall(G_FS_WRITE, buffer, len, f); } +void trap_FS_FCloseFile(fileHandle_t f) { Q_syscall(G_FS_FCLOSE_FILE, f); } +void trap_SendConsoleCommand(int exec_when, const char *text) { Q_syscall(G_SEND_CONSOLE_COMMAND, exec_when, text); } +void trap_LocateGameData(sharedEntity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *clients, int sizeofGClient) { + Q_syscall(G_LOCATE_GAME_DATA, gEnts, numGEntities, sizeofGEntity_t, clients, sizeofGClient); +} +void trap_DropClient(int clientNum, const char *reason) { Q_syscall(G_DROP_CLIENT, clientNum, reason); } +void trap_SendServerCommand(int clientNum, const char *text) { + if (strlen(text) > 1022) { + G_SecurityLogPrintf("trap_SendServerCommand( %d, ... ) length exceeds 1022.\n", clientNum); + G_SecurityLogPrintf("text [%s]\n", text); return; } - Q_syscall( G_SEND_SERVER_COMMAND, clientNum, text ); -} -void trap_SetConfigstring( int num, const char *string ) { - Q_syscall( G_SET_CONFIGSTRING, num, string ); -} -void trap_GetConfigstring( int num, char *buffer, int bufferSize ) { - Q_syscall( G_GET_CONFIGSTRING, num, buffer, bufferSize ); -} -void trap_GetUserinfo( int num, char *buffer, int bufferSize ) { - Q_syscall( G_GET_USERINFO, num, buffer, bufferSize ); -} -void trap_SetUserinfo( int num, const char *buffer ) { - Q_syscall( G_SET_USERINFO, num, buffer ); -} -void trap_GetServerinfo( char *buffer, int bufferSize ) { - Q_syscall( G_GET_SERVERINFO, buffer, bufferSize ); -} -void trap_SetServerCull(float cullDistance) { - Q_syscall(G_SET_SERVER_CULL, PASSFLOAT(cullDistance)); -} -void trap_SetBrushModel( sharedEntity_t *ent, const char *name ) { - Q_syscall( G_SET_BRUSH_MODEL, ent, name ); -} -void trap_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) { - Q_syscall( G_TRACE, results, start, mins, maxs, end, passEntityNum, contentmask, 0, 10 ); -} -void trap_G2Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int g2TraceType, int traceLod ) { - Q_syscall( G_G2TRACE, results, start, mins, maxs, end, passEntityNum, contentmask, g2TraceType, traceLod ); -} -int trap_PointContents( const vec3_t point, int passEntityNum ) { - return Q_syscall( G_POINT_CONTENTS, point, passEntityNum ); -} -qboolean trap_InPVS( const vec3_t p1, const vec3_t p2 ) { - return Q_syscall( G_IN_PVS, p1, p2 ); -} -qboolean trap_InPVSIgnorePortals( const vec3_t p1, const vec3_t p2 ) { - return Q_syscall( G_IN_PVS_IGNORE_PORTALS, p1, p2 ); -} -void trap_AdjustAreaPortalState( sharedEntity_t *ent, qboolean open ) { - Q_syscall( G_ADJUST_AREA_PORTAL_STATE, ent, open ); -} -qboolean trap_AreasConnected( int area1, int area2 ) { - return Q_syscall( G_AREAS_CONNECTED, area1, area2 ); -} -void trap_LinkEntity( sharedEntity_t *ent ) { - Q_syscall( G_LINKENTITY, ent ); -} -void trap_UnlinkEntity( sharedEntity_t *ent ) { - Q_syscall( G_UNLINKENTITY, ent ); -} -int trap_EntitiesInBox( const vec3_t mins, const vec3_t maxs, int *list, int maxcount ) { - return Q_syscall( G_ENTITIES_IN_BOX, mins, maxs, list, maxcount ); -} -qboolean trap_EntityContact( const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent ) { - return Q_syscall( G_ENTITY_CONTACT, mins, maxs, ent ); -} -int trap_BotAllocateClient( void ) { - return Q_syscall( G_BOT_ALLOCATE_CLIENT ); -} -void trap_BotFreeClient( int clientNum ) { - Q_syscall( G_BOT_FREE_CLIENT, clientNum ); -} -void trap_GetUsercmd( int clientNum, usercmd_t *cmd ) { - Q_syscall( G_GET_USERCMD, clientNum, cmd ); -} -qboolean trap_GetEntityToken( char *buffer, int bufferSize ) { - return Q_syscall( G_GET_ENTITY_TOKEN, buffer, bufferSize ); -} -void trap_SiegePersSet(siegePers_t *pers) { - Q_syscall(G_SIEGEPERSSET, pers); -} -void trap_SiegePersGet(siegePers_t *pers) { - Q_syscall(G_SIEGEPERSGET, pers); -} -int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { - return Q_syscall( G_FS_GETFILELIST, path, extension, listbuf, bufsize ); -} -int trap_DebugPolygonCreate(int color, int numPoints, vec3_t *points) { - return Q_syscall( G_DEBUG_POLYGON_CREATE, color, numPoints, points ); -} -void trap_DebugPolygonDelete(int id) { - Q_syscall( G_DEBUG_POLYGON_DELETE, id ); -} -int trap_RealTime( qtime_t *qtime ) { - return Q_syscall( G_REAL_TIME, qtime ); -} -void trap_SnapVector( float *v ) { - Q_syscall( G_SNAPVECTOR, v ); -} -void trap_TraceCapsule( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask ) { - Q_syscall( G_TRACECAPSULE, results, start, mins, maxs, end, passEntityNum, contentmask, 0, 10 ); -} -qboolean trap_EntityContactCapsule( const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent ) { - return Q_syscall( G_ENTITY_CONTACTCAPSULE, mins, maxs, ent ); -} -int trap_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) { - return Q_syscall( SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength ); -} -qboolean trap_ROFF_Clean( void ) { - return Q_syscall( G_ROFF_CLEAN ); -} -void trap_ROFF_UpdateEntities( void ) { - Q_syscall( G_ROFF_UPDATE_ENTITIES ); -} -int trap_ROFF_Cache( char *file ) { - return Q_syscall( G_ROFF_CACHE, file ); -} -qboolean trap_ROFF_Play( int entID, int roffID, qboolean doTranslation ) { - return Q_syscall( G_ROFF_PLAY, entID, roffID, doTranslation ); -} -qboolean trap_ROFF_Purge_Ent( int entID ) { - return Q_syscall( G_ROFF_PURGE_ENT, entID ); -} -void trap_TrueMalloc(void **ptr, int size) { - Q_syscall(G_TRUEMALLOC, ptr, size); -} -void trap_TrueFree(void **ptr) { - Q_syscall(G_TRUEFREE, ptr); -} -int trap_ICARUS_RunScript( sharedEntity_t *ent, const char *name ) { - return Q_syscall(G_ICARUS_RUNSCRIPT, ent, name); -} -qboolean trap_ICARUS_RegisterScript( const char *name, qboolean bCalledDuringInterrogate) { + Q_syscall(G_SEND_SERVER_COMMAND, clientNum, text); +} +void trap_SetConfigstring(int num, const char *string) { Q_syscall(G_SET_CONFIGSTRING, num, string); } +void trap_GetConfigstring(int num, char *buffer, int bufferSize) { Q_syscall(G_GET_CONFIGSTRING, num, buffer, bufferSize); } +void trap_GetUserinfo(int num, char *buffer, int bufferSize) { Q_syscall(G_GET_USERINFO, num, buffer, bufferSize); } +void trap_SetUserinfo(int num, const char *buffer) { Q_syscall(G_SET_USERINFO, num, buffer); } +void trap_GetServerinfo(char *buffer, int bufferSize) { Q_syscall(G_GET_SERVERINFO, buffer, bufferSize); } +void trap_SetServerCull(float cullDistance) { Q_syscall(G_SET_SERVER_CULL, PASSFLOAT(cullDistance)); } +void trap_SetBrushModel(sharedEntity_t *ent, const char *name) { Q_syscall(G_SET_BRUSH_MODEL, ent, name); } +void trap_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask) { + Q_syscall(G_TRACE, results, start, mins, maxs, end, passEntityNum, contentmask, 0, 10); +} +void trap_G2Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, + int g2TraceType, int traceLod) { + Q_syscall(G_G2TRACE, results, start, mins, maxs, end, passEntityNum, contentmask, g2TraceType, traceLod); +} +int trap_PointContents(const vec3_t point, int passEntityNum) { return Q_syscall(G_POINT_CONTENTS, point, passEntityNum); } +qboolean trap_InPVS(const vec3_t p1, const vec3_t p2) { return Q_syscall(G_IN_PVS, p1, p2); } +qboolean trap_InPVSIgnorePortals(const vec3_t p1, const vec3_t p2) { return Q_syscall(G_IN_PVS_IGNORE_PORTALS, p1, p2); } +void trap_AdjustAreaPortalState(sharedEntity_t *ent, qboolean open) { Q_syscall(G_ADJUST_AREA_PORTAL_STATE, ent, open); } +qboolean trap_AreasConnected(int area1, int area2) { return Q_syscall(G_AREAS_CONNECTED, area1, area2); } +void trap_LinkEntity(sharedEntity_t *ent) { Q_syscall(G_LINKENTITY, ent); } +void trap_UnlinkEntity(sharedEntity_t *ent) { Q_syscall(G_UNLINKENTITY, ent); } +int trap_EntitiesInBox(const vec3_t mins, const vec3_t maxs, int *list, int maxcount) { return Q_syscall(G_ENTITIES_IN_BOX, mins, maxs, list, maxcount); } +qboolean trap_EntityContact(const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent) { return Q_syscall(G_ENTITY_CONTACT, mins, maxs, ent); } +int trap_BotAllocateClient(void) { return Q_syscall(G_BOT_ALLOCATE_CLIENT); } +void trap_BotFreeClient(int clientNum) { Q_syscall(G_BOT_FREE_CLIENT, clientNum); } +void trap_GetUsercmd(int clientNum, usercmd_t *cmd) { Q_syscall(G_GET_USERCMD, clientNum, cmd); } +qboolean trap_GetEntityToken(char *buffer, int bufferSize) { return Q_syscall(G_GET_ENTITY_TOKEN, buffer, bufferSize); } +void trap_SiegePersSet(siegePers_t *pers) { Q_syscall(G_SIEGEPERSSET, pers); } +void trap_SiegePersGet(siegePers_t *pers) { Q_syscall(G_SIEGEPERSGET, pers); } +int trap_FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize) { + return Q_syscall(G_FS_GETFILELIST, path, extension, listbuf, bufsize); +} +int trap_DebugPolygonCreate(int color, int numPoints, vec3_t *points) { return Q_syscall(G_DEBUG_POLYGON_CREATE, color, numPoints, points); } +void trap_DebugPolygonDelete(int id) { Q_syscall(G_DEBUG_POLYGON_DELETE, id); } +int trap_RealTime(qtime_t *qtime) { return Q_syscall(G_REAL_TIME, qtime); } +void trap_SnapVector(float *v) { Q_syscall(G_SNAPVECTOR, v); } +void trap_TraceCapsule(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask) { + Q_syscall(G_TRACECAPSULE, results, start, mins, maxs, end, passEntityNum, contentmask, 0, 10); +} +qboolean trap_EntityContactCapsule(const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent) { + return Q_syscall(G_ENTITY_CONTACTCAPSULE, mins, maxs, ent); +} +int trap_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) { return Q_syscall(SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength); } +qboolean trap_ROFF_Clean(void) { return Q_syscall(G_ROFF_CLEAN); } +void trap_ROFF_UpdateEntities(void) { Q_syscall(G_ROFF_UPDATE_ENTITIES); } +int trap_ROFF_Cache(char *file) { return Q_syscall(G_ROFF_CACHE, file); } +qboolean trap_ROFF_Play(int entID, int roffID, qboolean doTranslation) { return Q_syscall(G_ROFF_PLAY, entID, roffID, doTranslation); } +qboolean trap_ROFF_Purge_Ent(int entID) { return Q_syscall(G_ROFF_PURGE_ENT, entID); } +void trap_TrueMalloc(void **ptr, int size) { Q_syscall(G_TRUEMALLOC, ptr, size); } +void trap_TrueFree(void **ptr) { Q_syscall(G_TRUEFREE, ptr); } +int trap_ICARUS_RunScript(sharedEntity_t *ent, const char *name) { return Q_syscall(G_ICARUS_RUNSCRIPT, ent, name); } +qboolean trap_ICARUS_RegisterScript(const char *name, qboolean bCalledDuringInterrogate) { return Q_syscall(G_ICARUS_REGISTERSCRIPT, name, bCalledDuringInterrogate); } -void trap_ICARUS_Init( void ) { - Q_syscall(G_ICARUS_INIT); -} -qboolean trap_ICARUS_ValidEnt( sharedEntity_t *ent ) { - return Q_syscall(G_ICARUS_VALIDENT, ent); -} -qboolean trap_ICARUS_IsInitialized( int entID ) { - return Q_syscall(G_ICARUS_ISINITIALIZED, entID); -} -qboolean trap_ICARUS_MaintainTaskManager( int entID ) { - return Q_syscall(G_ICARUS_MAINTAINTASKMANAGER, entID); -} -qboolean trap_ICARUS_IsRunning( int entID ) { - return Q_syscall(G_ICARUS_ISRUNNING, entID); -} -qboolean trap_ICARUS_TaskIDPending(sharedEntity_t *ent, int taskID) { - return Q_syscall(G_ICARUS_TASKIDPENDING, ent, taskID); -} -void trap_ICARUS_InitEnt( sharedEntity_t *ent ) { - Q_syscall(G_ICARUS_INITENT, ent); -} -void trap_ICARUS_FreeEnt( sharedEntity_t *ent ) { - Q_syscall(G_ICARUS_FREEENT, ent); -} -void trap_ICARUS_AssociateEnt( sharedEntity_t *ent ) { - Q_syscall(G_ICARUS_ASSOCIATEENT, ent); -} -void trap_ICARUS_Shutdown( void ) { - Q_syscall(G_ICARUS_SHUTDOWN); -} -void trap_ICARUS_TaskIDSet(sharedEntity_t *ent, int taskType, int taskID) { - Q_syscall(G_ICARUS_TASKIDSET, ent, taskType, taskID); -} -void trap_ICARUS_TaskIDComplete(sharedEntity_t *ent, int taskType) { - Q_syscall(G_ICARUS_TASKIDCOMPLETE, ent, taskType); -} -void trap_ICARUS_SetVar(int taskID, int entID, const char *type_name, const char *data) { - Q_syscall(G_ICARUS_SETVAR, taskID, entID, type_name, data); -} -int trap_ICARUS_VariableDeclared(const char *type_name) { - return Q_syscall(G_ICARUS_VARIABLEDECLARED, type_name); -} -int trap_ICARUS_GetFloatVariable( const char *name, float *value ) { - return Q_syscall(G_ICARUS_GETFLOATVARIABLE, name, value); -} -int trap_ICARUS_GetStringVariable( const char *name, const char *value ) { - return Q_syscall(G_ICARUS_GETSTRINGVARIABLE, name, value); -} -int trap_ICARUS_GetVectorVariable( const char *name, const vec3_t value ) { - return Q_syscall(G_ICARUS_GETVECTORVARIABLE, name, value); -} -void trap_Nav_Init( void ) { - Q_syscall(G_NAV_INIT); -} -void trap_Nav_Free( void ) { - Q_syscall(G_NAV_FREE); -} -qboolean trap_Nav_Load( const char *filename, int checksum ) { - return Q_syscall(G_NAV_LOAD, filename, checksum); -} -qboolean trap_Nav_Save( const char *filename, int checksum ) { - return Q_syscall(G_NAV_SAVE, filename, checksum); -} -int trap_Nav_AddRawPoint( vec3_t point, int flags, int radius ) { - return Q_syscall(G_NAV_ADDRAWPOINT, point, flags, radius); -} -void trap_Nav_CalculatePaths( qboolean recalc ) { - Q_syscall(G_NAV_CALCULATEPATHS, recalc); -} -void trap_Nav_HardConnect( int first, int second ) { - Q_syscall(G_NAV_HARDCONNECT, first, second); -} -void trap_Nav_ShowNodes( void ) { - Q_syscall(G_NAV_SHOWNODES); -} -void trap_Nav_ShowEdges( void ) { - Q_syscall(G_NAV_SHOWEDGES); -} -void trap_Nav_ShowPath( int start, int end ) { - Q_syscall(G_NAV_SHOWPATH, start, end); -} -int trap_Nav_GetNearestNode( sharedEntity_t *ent, int lastID, int flags, int targetID ) { - return Q_syscall(G_NAV_GETNEARESTNODE, ent, lastID, flags, targetID); -} -int trap_Nav_GetBestNode( int startID, int endID, int rejectID ) { - return Q_syscall(G_NAV_GETBESTNODE, startID, endID, rejectID); -} -int trap_Nav_GetNodePosition( int nodeID, vec3_t out ) { - return Q_syscall(G_NAV_GETNODEPOSITION, nodeID, out); -} -int trap_Nav_GetNodeNumEdges( int nodeID ) { - return Q_syscall(G_NAV_GETNODENUMEDGES, nodeID); -} -int trap_Nav_GetNodeEdge( int nodeID, int edge ) { - return Q_syscall(G_NAV_GETNODEEDGE, nodeID, edge); -} -int trap_Nav_GetNumNodes( void ) { - return Q_syscall(G_NAV_GETNUMNODES); -} -qboolean trap_Nav_Connected( int startID, int endID ) { - return Q_syscall(G_NAV_CONNECTED, startID, endID); -} -int trap_Nav_GetPathCost( int startID, int endID ) { - return Q_syscall(G_NAV_GETPATHCOST, startID, endID); -} -int trap_Nav_GetEdgeCost( int startID, int endID ) { - return Q_syscall(G_NAV_GETEDGECOST, startID, endID); -} -int trap_Nav_GetProjectedNode( vec3_t origin, int nodeID ) { - return Q_syscall(G_NAV_GETPROJECTEDNODE, origin, nodeID); -} -void trap_Nav_CheckFailedNodes( sharedEntity_t *ent ) { - Q_syscall(G_NAV_CHECKFAILEDNODES, ent); -} -void trap_Nav_AddFailedNode( sharedEntity_t *ent, int nodeID ) { - Q_syscall(G_NAV_ADDFAILEDNODE, ent, nodeID); -} -qboolean trap_Nav_NodeFailed( sharedEntity_t *ent, int nodeID ) { - return Q_syscall(G_NAV_NODEFAILED, ent, nodeID); -} -qboolean trap_Nav_NodesAreNeighbors( int startID, int endID ) { - return Q_syscall(G_NAV_NODESARENEIGHBORS, startID, endID); -} -void trap_Nav_ClearFailedEdge( failedEdge_t *failedEdge ) { - Q_syscall(G_NAV_CLEARFAILEDEDGE, failedEdge); -} -void trap_Nav_ClearAllFailedEdges( void ) { - Q_syscall(G_NAV_CLEARALLFAILEDEDGES); -} -int trap_Nav_EdgeFailed( int startID, int endID ) { - return Q_syscall(G_NAV_EDGEFAILED, startID, endID); -} -void trap_Nav_AddFailedEdge( int entID, int startID, int endID ) { - Q_syscall(G_NAV_ADDFAILEDEDGE, entID, startID, endID); -} -qboolean trap_Nav_CheckFailedEdge( failedEdge_t *failedEdge ) { - return Q_syscall(G_NAV_CHECKFAILEDEDGE, failedEdge); -} -void trap_Nav_CheckAllFailedEdges( void ) { - Q_syscall(G_NAV_CHECKALLFAILEDEDGES); -} -qboolean trap_Nav_RouteBlocked( int startID, int testEdgeID, int endID, int rejectRank ) { +void trap_ICARUS_Init(void) { Q_syscall(G_ICARUS_INIT); } +qboolean trap_ICARUS_ValidEnt(sharedEntity_t *ent) { return Q_syscall(G_ICARUS_VALIDENT, ent); } +qboolean trap_ICARUS_IsInitialized(int entID) { return Q_syscall(G_ICARUS_ISINITIALIZED, entID); } +qboolean trap_ICARUS_MaintainTaskManager(int entID) { return Q_syscall(G_ICARUS_MAINTAINTASKMANAGER, entID); } +qboolean trap_ICARUS_IsRunning(int entID) { return Q_syscall(G_ICARUS_ISRUNNING, entID); } +qboolean trap_ICARUS_TaskIDPending(sharedEntity_t *ent, int taskID) { return Q_syscall(G_ICARUS_TASKIDPENDING, ent, taskID); } +void trap_ICARUS_InitEnt(sharedEntity_t *ent) { Q_syscall(G_ICARUS_INITENT, ent); } +void trap_ICARUS_FreeEnt(sharedEntity_t *ent) { Q_syscall(G_ICARUS_FREEENT, ent); } +void trap_ICARUS_AssociateEnt(sharedEntity_t *ent) { Q_syscall(G_ICARUS_ASSOCIATEENT, ent); } +void trap_ICARUS_Shutdown(void) { Q_syscall(G_ICARUS_SHUTDOWN); } +void trap_ICARUS_TaskIDSet(sharedEntity_t *ent, int taskType, int taskID) { Q_syscall(G_ICARUS_TASKIDSET, ent, taskType, taskID); } +void trap_ICARUS_TaskIDComplete(sharedEntity_t *ent, int taskType) { Q_syscall(G_ICARUS_TASKIDCOMPLETE, ent, taskType); } +void trap_ICARUS_SetVar(int taskID, int entID, const char *type_name, const char *data) { Q_syscall(G_ICARUS_SETVAR, taskID, entID, type_name, data); } +int trap_ICARUS_VariableDeclared(const char *type_name) { return Q_syscall(G_ICARUS_VARIABLEDECLARED, type_name); } +int trap_ICARUS_GetFloatVariable(const char *name, float *value) { return Q_syscall(G_ICARUS_GETFLOATVARIABLE, name, value); } +int trap_ICARUS_GetStringVariable(const char *name, const char *value) { return Q_syscall(G_ICARUS_GETSTRINGVARIABLE, name, value); } +int trap_ICARUS_GetVectorVariable(const char *name, const vec3_t value) { return Q_syscall(G_ICARUS_GETVECTORVARIABLE, name, value); } +void trap_Nav_Init(void) { Q_syscall(G_NAV_INIT); } +void trap_Nav_Free(void) { Q_syscall(G_NAV_FREE); } +qboolean trap_Nav_Load(const char *filename, int checksum) { return Q_syscall(G_NAV_LOAD, filename, checksum); } +qboolean trap_Nav_Save(const char *filename, int checksum) { return Q_syscall(G_NAV_SAVE, filename, checksum); } +int trap_Nav_AddRawPoint(vec3_t point, int flags, int radius) { return Q_syscall(G_NAV_ADDRAWPOINT, point, flags, radius); } +void trap_Nav_CalculatePaths(qboolean recalc) { Q_syscall(G_NAV_CALCULATEPATHS, recalc); } +void trap_Nav_HardConnect(int first, int second) { Q_syscall(G_NAV_HARDCONNECT, first, second); } +void trap_Nav_ShowNodes(void) { Q_syscall(G_NAV_SHOWNODES); } +void trap_Nav_ShowEdges(void) { Q_syscall(G_NAV_SHOWEDGES); } +void trap_Nav_ShowPath(int start, int end) { Q_syscall(G_NAV_SHOWPATH, start, end); } +int trap_Nav_GetNearestNode(sharedEntity_t *ent, int lastID, int flags, int targetID) { return Q_syscall(G_NAV_GETNEARESTNODE, ent, lastID, flags, targetID); } +int trap_Nav_GetBestNode(int startID, int endID, int rejectID) { return Q_syscall(G_NAV_GETBESTNODE, startID, endID, rejectID); } +int trap_Nav_GetNodePosition(int nodeID, vec3_t out) { return Q_syscall(G_NAV_GETNODEPOSITION, nodeID, out); } +int trap_Nav_GetNodeNumEdges(int nodeID) { return Q_syscall(G_NAV_GETNODENUMEDGES, nodeID); } +int trap_Nav_GetNodeEdge(int nodeID, int edge) { return Q_syscall(G_NAV_GETNODEEDGE, nodeID, edge); } +int trap_Nav_GetNumNodes(void) { return Q_syscall(G_NAV_GETNUMNODES); } +qboolean trap_Nav_Connected(int startID, int endID) { return Q_syscall(G_NAV_CONNECTED, startID, endID); } +int trap_Nav_GetPathCost(int startID, int endID) { return Q_syscall(G_NAV_GETPATHCOST, startID, endID); } +int trap_Nav_GetEdgeCost(int startID, int endID) { return Q_syscall(G_NAV_GETEDGECOST, startID, endID); } +int trap_Nav_GetProjectedNode(vec3_t origin, int nodeID) { return Q_syscall(G_NAV_GETPROJECTEDNODE, origin, nodeID); } +void trap_Nav_CheckFailedNodes(sharedEntity_t *ent) { Q_syscall(G_NAV_CHECKFAILEDNODES, ent); } +void trap_Nav_AddFailedNode(sharedEntity_t *ent, int nodeID) { Q_syscall(G_NAV_ADDFAILEDNODE, ent, nodeID); } +qboolean trap_Nav_NodeFailed(sharedEntity_t *ent, int nodeID) { return Q_syscall(G_NAV_NODEFAILED, ent, nodeID); } +qboolean trap_Nav_NodesAreNeighbors(int startID, int endID) { return Q_syscall(G_NAV_NODESARENEIGHBORS, startID, endID); } +void trap_Nav_ClearFailedEdge(failedEdge_t *failedEdge) { Q_syscall(G_NAV_CLEARFAILEDEDGE, failedEdge); } +void trap_Nav_ClearAllFailedEdges(void) { Q_syscall(G_NAV_CLEARALLFAILEDEDGES); } +int trap_Nav_EdgeFailed(int startID, int endID) { return Q_syscall(G_NAV_EDGEFAILED, startID, endID); } +void trap_Nav_AddFailedEdge(int entID, int startID, int endID) { Q_syscall(G_NAV_ADDFAILEDEDGE, entID, startID, endID); } +qboolean trap_Nav_CheckFailedEdge(failedEdge_t *failedEdge) { return Q_syscall(G_NAV_CHECKFAILEDEDGE, failedEdge); } +void trap_Nav_CheckAllFailedEdges(void) { Q_syscall(G_NAV_CHECKALLFAILEDEDGES); } +qboolean trap_Nav_RouteBlocked(int startID, int testEdgeID, int endID, int rejectRank) { return Q_syscall(G_NAV_ROUTEBLOCKED, startID, testEdgeID, endID, rejectRank); } -int trap_Nav_GetBestNodeAltRoute( int startID, int endID, int *pathCost, int rejectID ) { +int trap_Nav_GetBestNodeAltRoute(int startID, int endID, int *pathCost, int rejectID) { return Q_syscall(G_NAV_GETBESTNODEALTROUTE, startID, endID, pathCost, rejectID); } -int trap_Nav_GetBestNodeAltRoute2( int startID, int endID, int rejectID ) { - return Q_syscall(G_NAV_GETBESTNODEALT2, startID, endID, rejectID); -} -int trap_Nav_GetBestPathBetweenEnts( sharedEntity_t *ent, sharedEntity_t *goal, int flags ) { - return Q_syscall(G_NAV_GETBESTPATHBETWEENENTS, ent, goal, flags); -} -int trap_Nav_GetNodeRadius( int nodeID ) { - return Q_syscall(G_NAV_GETNODERADIUS, nodeID); -} -void trap_Nav_CheckBlockedEdges( void ) { - Q_syscall(G_NAV_CHECKBLOCKEDEDGES); -} -void trap_Nav_ClearCheckedNodes( void ) { - Q_syscall(G_NAV_CLEARCHECKEDNODES); -} -int trap_Nav_CheckedNode(int wayPoint, int ent) { - return Q_syscall(G_NAV_CHECKEDNODE, wayPoint, ent); -} -void trap_Nav_SetCheckedNode(int wayPoint, int ent, int value) { - Q_syscall(G_NAV_SETCHECKEDNODE, wayPoint, ent, value); -} -void trap_Nav_FlagAllNodes( int newFlag ) { - Q_syscall(G_NAV_FLAGALLNODES, newFlag); -} -qboolean trap_Nav_GetPathsCalculated(void) { - return Q_syscall(G_NAV_GETPATHSCALCULATED); -} -void trap_Nav_SetPathsCalculated(qboolean newVal) { - Q_syscall(G_NAV_SETPATHSCALCULATED, newVal); -} -void trap_SV_RegisterSharedMemory(char *memory) { - Q_syscall(G_SET_SHARED_BUFFER, memory); -} -int trap_BotLibSetup( void ) { - return Q_syscall( BOTLIB_SETUP ); -} -int trap_BotLibShutdown( void ) { - return Q_syscall( BOTLIB_SHUTDOWN ); -} -int trap_BotLibVarSet(char *var_name, char *value) { - return Q_syscall( BOTLIB_LIBVAR_SET, var_name, value ); -} -int trap_BotLibVarGet(char *var_name, char *value, int size) { - return Q_syscall( BOTLIB_LIBVAR_GET, var_name, value, size ); -} -int trap_BotLibDefine(char *string) { - return Q_syscall( BOTLIB_PC_ADD_GLOBAL_DEFINE, string ); -} -int trap_BotLibStartFrame(float time) { - return Q_syscall( BOTLIB_START_FRAME, PASSFLOAT( time ) ); -} -int trap_BotLibLoadMap(const char *mapname) { - return Q_syscall( BOTLIB_LOAD_MAP, mapname ); -} -int trap_BotLibUpdateEntity(int ent, void *bue) { - return Q_syscall( BOTLIB_UPDATENTITY, ent, bue ); -} -int trap_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) { - return Q_syscall( BOTLIB_TEST, parm0, parm1, parm2, parm3 ); -} -int trap_BotGetSnapshotEntity( int clientNum, int sequence ) { - return Q_syscall( BOTLIB_GET_SNAPSHOT_ENTITY, clientNum, sequence ); -} -int trap_BotGetServerCommand(int clientNum, char *message, int size) { - return Q_syscall( BOTLIB_GET_CONSOLE_MESSAGE, clientNum, message, size ); -} -void trap_BotUserCommand(int clientNum, usercmd_t *ucmd) { - Q_syscall( BOTLIB_USER_COMMAND, clientNum, ucmd ); -} -void trap_AAS_EntityInfo(int entnum, void *info) { - Q_syscall( BOTLIB_AAS_ENTITY_INFO, entnum, info ); -} -int trap_AAS_Initialized(void) { - return Q_syscall( BOTLIB_AAS_INITIALIZED ); -} +int trap_Nav_GetBestNodeAltRoute2(int startID, int endID, int rejectID) { return Q_syscall(G_NAV_GETBESTNODEALT2, startID, endID, rejectID); } +int trap_Nav_GetBestPathBetweenEnts(sharedEntity_t *ent, sharedEntity_t *goal, int flags) { return Q_syscall(G_NAV_GETBESTPATHBETWEENENTS, ent, goal, flags); } +int trap_Nav_GetNodeRadius(int nodeID) { return Q_syscall(G_NAV_GETNODERADIUS, nodeID); } +void trap_Nav_CheckBlockedEdges(void) { Q_syscall(G_NAV_CHECKBLOCKEDEDGES); } +void trap_Nav_ClearCheckedNodes(void) { Q_syscall(G_NAV_CLEARCHECKEDNODES); } +int trap_Nav_CheckedNode(int wayPoint, int ent) { return Q_syscall(G_NAV_CHECKEDNODE, wayPoint, ent); } +void trap_Nav_SetCheckedNode(int wayPoint, int ent, int value) { Q_syscall(G_NAV_SETCHECKEDNODE, wayPoint, ent, value); } +void trap_Nav_FlagAllNodes(int newFlag) { Q_syscall(G_NAV_FLAGALLNODES, newFlag); } +qboolean trap_Nav_GetPathsCalculated(void) { return Q_syscall(G_NAV_GETPATHSCALCULATED); } +void trap_Nav_SetPathsCalculated(qboolean newVal) { Q_syscall(G_NAV_SETPATHSCALCULATED, newVal); } +void trap_SV_RegisterSharedMemory(char *memory) { Q_syscall(G_SET_SHARED_BUFFER, memory); } +int trap_BotLibSetup(void) { return Q_syscall(BOTLIB_SETUP); } +int trap_BotLibShutdown(void) { return Q_syscall(BOTLIB_SHUTDOWN); } +int trap_BotLibVarSet(char *var_name, char *value) { return Q_syscall(BOTLIB_LIBVAR_SET, var_name, value); } +int trap_BotLibVarGet(char *var_name, char *value, int size) { return Q_syscall(BOTLIB_LIBVAR_GET, var_name, value, size); } +int trap_BotLibDefine(char *string) { return Q_syscall(BOTLIB_PC_ADD_GLOBAL_DEFINE, string); } +int trap_BotLibStartFrame(float time) { return Q_syscall(BOTLIB_START_FRAME, PASSFLOAT(time)); } +int trap_BotLibLoadMap(const char *mapname) { return Q_syscall(BOTLIB_LOAD_MAP, mapname); } +int trap_BotLibUpdateEntity(int ent, void *bue) { return Q_syscall(BOTLIB_UPDATENTITY, ent, bue); } +int trap_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) { return Q_syscall(BOTLIB_TEST, parm0, parm1, parm2, parm3); } +int trap_BotGetSnapshotEntity(int clientNum, int sequence) { return Q_syscall(BOTLIB_GET_SNAPSHOT_ENTITY, clientNum, sequence); } +int trap_BotGetServerCommand(int clientNum, char *message, int size) { return Q_syscall(BOTLIB_GET_CONSOLE_MESSAGE, clientNum, message, size); } +void trap_BotUserCommand(int clientNum, usercmd_t *ucmd) { Q_syscall(BOTLIB_USER_COMMAND, clientNum, ucmd); } +void trap_AAS_EntityInfo(int entnum, void *info) { Q_syscall(BOTLIB_AAS_ENTITY_INFO, entnum, info); } +int trap_AAS_Initialized(void) { return Q_syscall(BOTLIB_AAS_INITIALIZED); } void trap_AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) { - Q_syscall( BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX, presencetype, mins, maxs ); + Q_syscall(BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX, presencetype, mins, maxs); } float trap_AAS_Time(void) { byteAlias_t fi; - fi.i = Q_syscall( BOTLIB_AAS_TIME ); + fi.i = Q_syscall(BOTLIB_AAS_TIME); return fi.f; } -int trap_AAS_PointAreaNum(vec3_t point) { - return Q_syscall( BOTLIB_AAS_POINT_AREA_NUM, point ); -} -int trap_AAS_PointReachabilityAreaIndex(vec3_t point) { - return Q_syscall( BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX, point ); -} +int trap_AAS_PointAreaNum(vec3_t point) { return Q_syscall(BOTLIB_AAS_POINT_AREA_NUM, point); } +int trap_AAS_PointReachabilityAreaIndex(vec3_t point) { return Q_syscall(BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX, point); } int trap_AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) { - return Q_syscall( BOTLIB_AAS_TRACE_AREAS, start, end, areas, points, maxareas ); -} -int trap_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) { - return Q_syscall( BOTLIB_AAS_BBOX_AREAS, absmins, absmaxs, areas, maxareas ); -} -int trap_AAS_AreaInfo( int areanum, void *info ) { - return Q_syscall( BOTLIB_AAS_AREA_INFO, areanum, info ); -} -int trap_AAS_PointContents(vec3_t point) { - return Q_syscall( BOTLIB_AAS_POINT_CONTENTS, point ); -} -int trap_AAS_NextBSPEntity(int ent) { - return Q_syscall( BOTLIB_AAS_NEXT_BSP_ENTITY, ent ); -} -int trap_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) { - return Q_syscall( BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY, ent, key, value, size ); -} -int trap_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) { - return Q_syscall( BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY, ent, key, v ); -} -int trap_AAS_FloatForBSPEpairKey(int ent, char *key, float *value) { - return Q_syscall( BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY, ent, key, value ); -} -int trap_AAS_IntForBSPEpairKey(int ent, char *key, int *value) { - return Q_syscall( BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY, ent, key, value ); -} -int trap_AAS_AreaReachability(int areanum) { - return Q_syscall( BOTLIB_AAS_AREA_REACHABILITY, areanum ); -} + return Q_syscall(BOTLIB_AAS_TRACE_AREAS, start, end, areas, points, maxareas); +} +int trap_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) { return Q_syscall(BOTLIB_AAS_BBOX_AREAS, absmins, absmaxs, areas, maxareas); } +int trap_AAS_AreaInfo(int areanum, void *info) { return Q_syscall(BOTLIB_AAS_AREA_INFO, areanum, info); } +int trap_AAS_PointContents(vec3_t point) { return Q_syscall(BOTLIB_AAS_POINT_CONTENTS, point); } +int trap_AAS_NextBSPEntity(int ent) { return Q_syscall(BOTLIB_AAS_NEXT_BSP_ENTITY, ent); } +int trap_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) { return Q_syscall(BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY, ent, key, value, size); } +int trap_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) { return Q_syscall(BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY, ent, key, v); } +int trap_AAS_FloatForBSPEpairKey(int ent, char *key, float *value) { return Q_syscall(BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY, ent, key, value); } +int trap_AAS_IntForBSPEpairKey(int ent, char *key, int *value) { return Q_syscall(BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY, ent, key, value); } +int trap_AAS_AreaReachability(int areanum) { return Q_syscall(BOTLIB_AAS_AREA_REACHABILITY, areanum); } int trap_AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) { - return Q_syscall( BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA, areanum, origin, goalareanum, travelflags ); -} -int trap_AAS_EnableRoutingArea( int areanum, int enable ) { - return Q_syscall( BOTLIB_AAS_ENABLE_ROUTING_AREA, areanum, enable ); -} -int trap_AAS_PredictRoute(void *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, int stopcontents, int stoptfl, int stopareanum) { - return Q_syscall( BOTLIB_AAS_PREDICT_ROUTE, route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, stopcontents, stoptfl, stopareanum ); -} -int trap_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, void *altroutegoals, int maxaltroutegoals, int type) { - return Q_syscall( BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL, start, startareanum, goal, goalareanum, travelflags, altroutegoals, maxaltroutegoals, type ); -} -int trap_AAS_Swimming(vec3_t origin) { - return Q_syscall( BOTLIB_AAS_SWIMMING, origin ); -} -int trap_AAS_PredictClientMovement(void *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize) { - return Q_syscall( BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT, move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, PASSFLOAT(frametime), stopevent, stopareanum, visualize ); -} -void trap_EA_Say(int client, char *str) { - Q_syscall( BOTLIB_EA_SAY, client, str ); -} -void trap_EA_SayTeam(int client, char *str) { - Q_syscall( BOTLIB_EA_SAY_TEAM, client, str ); -} -void trap_EA_Command(int client, char *command) { - Q_syscall( BOTLIB_EA_COMMAND, client, command ); -} -void trap_EA_Action(int client, int action) { - Q_syscall( BOTLIB_EA_ACTION, client, action ); -} -void trap_EA_Gesture(int client) { - Q_syscall( BOTLIB_EA_GESTURE, client ); -} -void trap_EA_Talk(int client) { - Q_syscall( BOTLIB_EA_TALK, client ); -} -void trap_EA_Attack(int client) { - Q_syscall( BOTLIB_EA_ATTACK, client ); -} -void trap_EA_Alt_Attack(int client) { - Q_syscall( BOTLIB_EA_ALT_ATTACK, client ); -} -void trap_EA_ForcePower(int client) { - Q_syscall( BOTLIB_EA_FORCEPOWER, client ); -} -void trap_EA_Use(int client) { - Q_syscall( BOTLIB_EA_USE, client ); -} -void trap_EA_Respawn(int client) { - Q_syscall( BOTLIB_EA_RESPAWN, client ); -} -void trap_EA_Crouch(int client) { - Q_syscall( BOTLIB_EA_CROUCH, client ); -} -void trap_EA_MoveUp(int client) { - Q_syscall( BOTLIB_EA_MOVE_UP, client ); -} -void trap_EA_MoveDown(int client) { - Q_syscall( BOTLIB_EA_MOVE_DOWN, client ); -} -void trap_EA_MoveForward(int client) { - Q_syscall( BOTLIB_EA_MOVE_FORWARD, client ); -} -void trap_EA_MoveBack(int client) { - Q_syscall( BOTLIB_EA_MOVE_BACK, client ); -} -void trap_EA_MoveLeft(int client) { - Q_syscall( BOTLIB_EA_MOVE_LEFT, client ); -} -void trap_EA_MoveRight(int client) { - Q_syscall( BOTLIB_EA_MOVE_RIGHT, client ); -} -void trap_EA_SelectWeapon(int client, int weapon) { - Q_syscall( BOTLIB_EA_SELECT_WEAPON, client, weapon ); -} -void trap_EA_Jump(int client) { - Q_syscall( BOTLIB_EA_JUMP, client ); -} -void trap_EA_DelayedJump(int client) { - Q_syscall( BOTLIB_EA_DELAYED_JUMP, client ); -} -void trap_EA_Move(int client, vec3_t dir, float speed) { - Q_syscall( BOTLIB_EA_MOVE, client, dir, PASSFLOAT(speed) ); -} -void trap_EA_View(int client, vec3_t viewangles) { - Q_syscall( BOTLIB_EA_VIEW, client, viewangles ); -} -void trap_EA_EndRegular(int client, float thinktime) { - Q_syscall( BOTLIB_EA_END_REGULAR, client, PASSFLOAT(thinktime) ); -} -void trap_EA_GetInput(int client, float thinktime, void *input) { - Q_syscall( BOTLIB_EA_GET_INPUT, client, PASSFLOAT(thinktime), input ); -} -void trap_EA_ResetInput(int client) { - Q_syscall( BOTLIB_EA_RESET_INPUT, client ); -} -int trap_BotLoadCharacter(char *charfile, float skill) { - return Q_syscall( BOTLIB_AI_LOAD_CHARACTER, charfile, PASSFLOAT(skill)); -} -void trap_BotFreeCharacter(int character) { - Q_syscall( BOTLIB_AI_FREE_CHARACTER, character ); -} + return Q_syscall(BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA, areanum, origin, goalareanum, travelflags); +} +int trap_AAS_EnableRoutingArea(int areanum, int enable) { return Q_syscall(BOTLIB_AAS_ENABLE_ROUTING_AREA, areanum, enable); } +int trap_AAS_PredictRoute(void *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, int stopcontents, + int stoptfl, int stopareanum) { + return Q_syscall(BOTLIB_AAS_PREDICT_ROUTE, route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, stopcontents, stoptfl, + stopareanum); +} +int trap_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, void *altroutegoals, int maxaltroutegoals, + int type) { + return Q_syscall(BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL, start, startareanum, goal, goalareanum, travelflags, altroutegoals, maxaltroutegoals, type); +} +int trap_AAS_Swimming(vec3_t origin) { return Q_syscall(BOTLIB_AAS_SWIMMING, origin); } +int trap_AAS_PredictClientMovement(void *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, + int maxframes, float frametime, int stopevent, int stopareanum, int visualize) { + return Q_syscall(BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT, move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, + PASSFLOAT(frametime), stopevent, stopareanum, visualize); +} +void trap_EA_Say(int client, char *str) { Q_syscall(BOTLIB_EA_SAY, client, str); } +void trap_EA_SayTeam(int client, char *str) { Q_syscall(BOTLIB_EA_SAY_TEAM, client, str); } +void trap_EA_Command(int client, char *command) { Q_syscall(BOTLIB_EA_COMMAND, client, command); } +void trap_EA_Action(int client, int action) { Q_syscall(BOTLIB_EA_ACTION, client, action); } +void trap_EA_Gesture(int client) { Q_syscall(BOTLIB_EA_GESTURE, client); } +void trap_EA_Talk(int client) { Q_syscall(BOTLIB_EA_TALK, client); } +void trap_EA_Attack(int client) { Q_syscall(BOTLIB_EA_ATTACK, client); } +void trap_EA_Alt_Attack(int client) { Q_syscall(BOTLIB_EA_ALT_ATTACK, client); } +void trap_EA_ForcePower(int client) { Q_syscall(BOTLIB_EA_FORCEPOWER, client); } +void trap_EA_Use(int client) { Q_syscall(BOTLIB_EA_USE, client); } +void trap_EA_Respawn(int client) { Q_syscall(BOTLIB_EA_RESPAWN, client); } +void trap_EA_Crouch(int client) { Q_syscall(BOTLIB_EA_CROUCH, client); } +void trap_EA_MoveUp(int client) { Q_syscall(BOTLIB_EA_MOVE_UP, client); } +void trap_EA_MoveDown(int client) { Q_syscall(BOTLIB_EA_MOVE_DOWN, client); } +void trap_EA_MoveForward(int client) { Q_syscall(BOTLIB_EA_MOVE_FORWARD, client); } +void trap_EA_MoveBack(int client) { Q_syscall(BOTLIB_EA_MOVE_BACK, client); } +void trap_EA_MoveLeft(int client) { Q_syscall(BOTLIB_EA_MOVE_LEFT, client); } +void trap_EA_MoveRight(int client) { Q_syscall(BOTLIB_EA_MOVE_RIGHT, client); } +void trap_EA_SelectWeapon(int client, int weapon) { Q_syscall(BOTLIB_EA_SELECT_WEAPON, client, weapon); } +void trap_EA_Jump(int client) { Q_syscall(BOTLIB_EA_JUMP, client); } +void trap_EA_DelayedJump(int client) { Q_syscall(BOTLIB_EA_DELAYED_JUMP, client); } +void trap_EA_Move(int client, vec3_t dir, float speed) { Q_syscall(BOTLIB_EA_MOVE, client, dir, PASSFLOAT(speed)); } +void trap_EA_View(int client, vec3_t viewangles) { Q_syscall(BOTLIB_EA_VIEW, client, viewangles); } +void trap_EA_EndRegular(int client, float thinktime) { Q_syscall(BOTLIB_EA_END_REGULAR, client, PASSFLOAT(thinktime)); } +void trap_EA_GetInput(int client, float thinktime, void *input) { Q_syscall(BOTLIB_EA_GET_INPUT, client, PASSFLOAT(thinktime), input); } +void trap_EA_ResetInput(int client) { Q_syscall(BOTLIB_EA_RESET_INPUT, client); } +int trap_BotLoadCharacter(char *charfile, float skill) { return Q_syscall(BOTLIB_AI_LOAD_CHARACTER, charfile, PASSFLOAT(skill)); } +void trap_BotFreeCharacter(int character) { Q_syscall(BOTLIB_AI_FREE_CHARACTER, character); } float trap_Characteristic_Float(int character, int index) { byteAlias_t fi; - fi.i = Q_syscall( BOTLIB_AI_CHARACTERISTIC_FLOAT, character, index ); + fi.i = Q_syscall(BOTLIB_AI_CHARACTERISTIC_FLOAT, character, index); return fi.f; } float trap_Characteristic_BFloat(int character, int index, float min, float max) { byteAlias_t fi; - fi.i = Q_syscall( BOTLIB_AI_CHARACTERISTIC_BFLOAT, character, index, PASSFLOAT(min), PASSFLOAT(max) ); + fi.i = Q_syscall(BOTLIB_AI_CHARACTERISTIC_BFLOAT, character, index, PASSFLOAT(min), PASSFLOAT(max)); return fi.f; } -int trap_Characteristic_Integer(int character, int index) { - return Q_syscall( BOTLIB_AI_CHARACTERISTIC_INTEGER, character, index ); -} +int trap_Characteristic_Integer(int character, int index) { return Q_syscall(BOTLIB_AI_CHARACTERISTIC_INTEGER, character, index); } int trap_Characteristic_BInteger(int character, int index, int min, int max) { - return Q_syscall( BOTLIB_AI_CHARACTERISTIC_BINTEGER, character, index, min, max ); -} -void trap_Characteristic_String(int character, int index, char *buf, int size) { - Q_syscall( BOTLIB_AI_CHARACTERISTIC_STRING, character, index, buf, size ); -} -int trap_BotAllocChatState(void) { - return Q_syscall( BOTLIB_AI_ALLOC_CHAT_STATE ); -} -void trap_BotFreeChatState(int handle) { - Q_syscall( BOTLIB_AI_FREE_CHAT_STATE, handle ); -} -void trap_BotQueueConsoleMessage(int chatstate, int type, char *message) { - Q_syscall( BOTLIB_AI_QUEUE_CONSOLE_MESSAGE, chatstate, type, message ); -} -void trap_BotRemoveConsoleMessage(int chatstate, int handle) { - Q_syscall( BOTLIB_AI_REMOVE_CONSOLE_MESSAGE, chatstate, handle ); -} -int trap_BotNextConsoleMessage(int chatstate, void *cm) { - return Q_syscall( BOTLIB_AI_NEXT_CONSOLE_MESSAGE, chatstate, cm ); -} -int trap_BotNumConsoleMessages(int chatstate) { - return Q_syscall( BOTLIB_AI_NUM_CONSOLE_MESSAGE, chatstate ); -} -void trap_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { - Q_syscall( BOTLIB_AI_INITIAL_CHAT, chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); -} -int trap_BotNumInitialChats(int chatstate, char *type) { - return Q_syscall( BOTLIB_AI_NUM_INITIAL_CHATS, chatstate, type ); -} -int trap_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { - return Q_syscall( BOTLIB_AI_REPLY_CHAT, chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); -} -int trap_BotChatLength(int chatstate) { - return Q_syscall( BOTLIB_AI_CHAT_LENGTH, chatstate ); -} -void trap_BotEnterChat(int chatstate, int client, int sendto) { - Q_syscall( BOTLIB_AI_ENTER_CHAT, chatstate, client, sendto ); -} -void trap_BotGetChatMessage(int chatstate, char *buf, int size) { - Q_syscall( BOTLIB_AI_GET_CHAT_MESSAGE, chatstate, buf, size); -} -int trap_StringContains(char *str1, char *str2, int casesensitive) { - return Q_syscall( BOTLIB_AI_STRING_CONTAINS, str1, str2, casesensitive ); -} -int trap_BotFindMatch(char *str, void *match, unsigned long int context) { - return Q_syscall( BOTLIB_AI_FIND_MATCH, str, match, context ); -} -void trap_BotMatchVariable(void *match, int variable, char *buf, int size) { - Q_syscall( BOTLIB_AI_MATCH_VARIABLE, match, variable, buf, size ); -} -void trap_UnifyWhiteSpaces(char *string) { - Q_syscall( BOTLIB_AI_UNIFY_WHITE_SPACES, string ); -} -void trap_BotReplaceSynonyms(char *string, unsigned long int context) { - Q_syscall( BOTLIB_AI_REPLACE_SYNONYMS, string, context ); -} -int trap_BotLoadChatFile(int chatstate, char *chatfile, char *chatname) { - return Q_syscall( BOTLIB_AI_LOAD_CHAT_FILE, chatstate, chatfile, chatname ); -} -void trap_BotSetChatGender(int chatstate, int gender) { - Q_syscall( BOTLIB_AI_SET_CHAT_GENDER, chatstate, gender ); -} -void trap_BotSetChatName(int chatstate, char *name, int client) { - Q_syscall( BOTLIB_AI_SET_CHAT_NAME, chatstate, name, client ); -} -void trap_BotResetGoalState(int goalstate) { - Q_syscall( BOTLIB_AI_RESET_GOAL_STATE, goalstate ); -} -void trap_BotResetAvoidGoals(int goalstate) { - Q_syscall( BOTLIB_AI_RESET_AVOID_GOALS, goalstate ); -} -void trap_BotRemoveFromAvoidGoals(int goalstate, int number) { - Q_syscall( BOTLIB_AI_REMOVE_FROM_AVOID_GOALS, goalstate, number); -} -void trap_BotPushGoal(int goalstate, void *goal) { - Q_syscall( BOTLIB_AI_PUSH_GOAL, goalstate, goal ); -} -void trap_BotPopGoal(int goalstate) { - Q_syscall( BOTLIB_AI_POP_GOAL, goalstate ); -} -void trap_BotEmptyGoalStack(int goalstate) { - Q_syscall( BOTLIB_AI_EMPTY_GOAL_STACK, goalstate ); -} -void trap_BotDumpAvoidGoals(int goalstate) { - Q_syscall( BOTLIB_AI_DUMP_AVOID_GOALS, goalstate ); -} -void trap_BotDumpGoalStack(int goalstate) { - Q_syscall( BOTLIB_AI_DUMP_GOAL_STACK, goalstate ); -} -void trap_BotGoalName(int number, char *name, int size) { - Q_syscall( BOTLIB_AI_GOAL_NAME, number, name, size ); -} -int trap_BotGetTopGoal(int goalstate, void *goal) { - return Q_syscall( BOTLIB_AI_GET_TOP_GOAL, goalstate, goal ); -} -int trap_BotGetSecondGoal(int goalstate, void *goal) { - return Q_syscall( BOTLIB_AI_GET_SECOND_GOAL, goalstate, goal ); -} + return Q_syscall(BOTLIB_AI_CHARACTERISTIC_BINTEGER, character, index, min, max); +} +void trap_Characteristic_String(int character, int index, char *buf, int size) { Q_syscall(BOTLIB_AI_CHARACTERISTIC_STRING, character, index, buf, size); } +int trap_BotAllocChatState(void) { return Q_syscall(BOTLIB_AI_ALLOC_CHAT_STATE); } +void trap_BotFreeChatState(int handle) { Q_syscall(BOTLIB_AI_FREE_CHAT_STATE, handle); } +void trap_BotQueueConsoleMessage(int chatstate, int type, char *message) { Q_syscall(BOTLIB_AI_QUEUE_CONSOLE_MESSAGE, chatstate, type, message); } +void trap_BotRemoveConsoleMessage(int chatstate, int handle) { Q_syscall(BOTLIB_AI_REMOVE_CONSOLE_MESSAGE, chatstate, handle); } +int trap_BotNextConsoleMessage(int chatstate, void *cm) { return Q_syscall(BOTLIB_AI_NEXT_CONSOLE_MESSAGE, chatstate, cm); } +int trap_BotNumConsoleMessages(int chatstate) { return Q_syscall(BOTLIB_AI_NUM_CONSOLE_MESSAGE, chatstate); } +void trap_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, + char *var7) { + Q_syscall(BOTLIB_AI_INITIAL_CHAT, chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7); +} +int trap_BotNumInitialChats(int chatstate, char *type) { return Q_syscall(BOTLIB_AI_NUM_INITIAL_CHATS, chatstate, type); } +int trap_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, + char *var6, char *var7) { + return Q_syscall(BOTLIB_AI_REPLY_CHAT, chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7); +} +int trap_BotChatLength(int chatstate) { return Q_syscall(BOTLIB_AI_CHAT_LENGTH, chatstate); } +void trap_BotEnterChat(int chatstate, int client, int sendto) { Q_syscall(BOTLIB_AI_ENTER_CHAT, chatstate, client, sendto); } +void trap_BotGetChatMessage(int chatstate, char *buf, int size) { Q_syscall(BOTLIB_AI_GET_CHAT_MESSAGE, chatstate, buf, size); } +int trap_StringContains(char *str1, char *str2, int casesensitive) { return Q_syscall(BOTLIB_AI_STRING_CONTAINS, str1, str2, casesensitive); } +int trap_BotFindMatch(char *str, void *match, unsigned long int context) { return Q_syscall(BOTLIB_AI_FIND_MATCH, str, match, context); } +void trap_BotMatchVariable(void *match, int variable, char *buf, int size) { Q_syscall(BOTLIB_AI_MATCH_VARIABLE, match, variable, buf, size); } +void trap_UnifyWhiteSpaces(char *string) { Q_syscall(BOTLIB_AI_UNIFY_WHITE_SPACES, string); } +void trap_BotReplaceSynonyms(char *string, unsigned long int context) { Q_syscall(BOTLIB_AI_REPLACE_SYNONYMS, string, context); } +int trap_BotLoadChatFile(int chatstate, char *chatfile, char *chatname) { return Q_syscall(BOTLIB_AI_LOAD_CHAT_FILE, chatstate, chatfile, chatname); } +void trap_BotSetChatGender(int chatstate, int gender) { Q_syscall(BOTLIB_AI_SET_CHAT_GENDER, chatstate, gender); } +void trap_BotSetChatName(int chatstate, char *name, int client) { Q_syscall(BOTLIB_AI_SET_CHAT_NAME, chatstate, name, client); } +void trap_BotResetGoalState(int goalstate) { Q_syscall(BOTLIB_AI_RESET_GOAL_STATE, goalstate); } +void trap_BotResetAvoidGoals(int goalstate) { Q_syscall(BOTLIB_AI_RESET_AVOID_GOALS, goalstate); } +void trap_BotRemoveFromAvoidGoals(int goalstate, int number) { Q_syscall(BOTLIB_AI_REMOVE_FROM_AVOID_GOALS, goalstate, number); } +void trap_BotPushGoal(int goalstate, void *goal) { Q_syscall(BOTLIB_AI_PUSH_GOAL, goalstate, goal); } +void trap_BotPopGoal(int goalstate) { Q_syscall(BOTLIB_AI_POP_GOAL, goalstate); } +void trap_BotEmptyGoalStack(int goalstate) { Q_syscall(BOTLIB_AI_EMPTY_GOAL_STACK, goalstate); } +void trap_BotDumpAvoidGoals(int goalstate) { Q_syscall(BOTLIB_AI_DUMP_AVOID_GOALS, goalstate); } +void trap_BotDumpGoalStack(int goalstate) { Q_syscall(BOTLIB_AI_DUMP_GOAL_STACK, goalstate); } +void trap_BotGoalName(int number, char *name, int size) { Q_syscall(BOTLIB_AI_GOAL_NAME, number, name, size); } +int trap_BotGetTopGoal(int goalstate, void *goal) { return Q_syscall(BOTLIB_AI_GET_TOP_GOAL, goalstate, goal); } +int trap_BotGetSecondGoal(int goalstate, void *goal) { return Q_syscall(BOTLIB_AI_GET_SECOND_GOAL, goalstate, goal); } int trap_BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) { - return Q_syscall( BOTLIB_AI_CHOOSE_LTG_ITEM, goalstate, origin, inventory, travelflags ); + return Q_syscall(BOTLIB_AI_CHOOSE_LTG_ITEM, goalstate, origin, inventory, travelflags); } int trap_BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, void *ltg, float maxtime) { - return Q_syscall( BOTLIB_AI_CHOOSE_NBG_ITEM, goalstate, origin, inventory, travelflags, ltg, PASSFLOAT(maxtime) ); -} -int trap_BotTouchingGoal(vec3_t origin, void *goal) { - return Q_syscall( BOTLIB_AI_TOUCHING_GOAL, origin, goal ); + return Q_syscall(BOTLIB_AI_CHOOSE_NBG_ITEM, goalstate, origin, inventory, travelflags, ltg, PASSFLOAT(maxtime)); } +int trap_BotTouchingGoal(vec3_t origin, void *goal) { return Q_syscall(BOTLIB_AI_TOUCHING_GOAL, origin, goal); } int trap_BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, void *goal) { - return Q_syscall( BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE, viewer, eye, viewangles, goal ); -} -int trap_BotGetLevelItemGoal(int index, char *classname, void *goal) { - return Q_syscall( BOTLIB_AI_GET_LEVEL_ITEM_GOAL, index, classname, goal ); -} -int trap_BotGetNextCampSpotGoal(int num, void *goal) { - return Q_syscall( BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL, num, goal ); -} -int trap_BotGetMapLocationGoal(char *name, void *goal) { - return Q_syscall( BOTLIB_AI_GET_MAP_LOCATION_GOAL, name, goal ); + return Q_syscall(BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE, viewer, eye, viewangles, goal); } +int trap_BotGetLevelItemGoal(int index, char *classname, void *goal) { return Q_syscall(BOTLIB_AI_GET_LEVEL_ITEM_GOAL, index, classname, goal); } +int trap_BotGetNextCampSpotGoal(int num, void *goal) { return Q_syscall(BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL, num, goal); } +int trap_BotGetMapLocationGoal(char *name, void *goal) { return Q_syscall(BOTLIB_AI_GET_MAP_LOCATION_GOAL, name, goal); } float trap_BotAvoidGoalTime(int goalstate, int number) { byteAlias_t fi; - fi.i = Q_syscall( BOTLIB_AI_AVOID_GOAL_TIME, goalstate, number ); + fi.i = Q_syscall(BOTLIB_AI_AVOID_GOAL_TIME, goalstate, number); return fi.f; } -void trap_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { - Q_syscall( BOTLIB_AI_SET_AVOID_GOAL_TIME, goalstate, number, PASSFLOAT(avoidtime)); -} -void trap_BotInitLevelItems(void) { - Q_syscall( BOTLIB_AI_INIT_LEVEL_ITEMS ); -} -void trap_BotUpdateEntityItems(void) { - Q_syscall( BOTLIB_AI_UPDATE_ENTITY_ITEMS ); -} -int trap_BotLoadItemWeights(int goalstate, char *filename) { - return Q_syscall( BOTLIB_AI_LOAD_ITEM_WEIGHTS, goalstate, filename ); -} -void trap_BotFreeItemWeights(int goalstate) { - Q_syscall( BOTLIB_AI_FREE_ITEM_WEIGHTS, goalstate ); -} -void trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { - Q_syscall( BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC, parent1, parent2, child ); -} -void trap_BotSaveGoalFuzzyLogic(int goalstate, char *filename) { - Q_syscall( BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC, goalstate, filename ); -} -void trap_BotMutateGoalFuzzyLogic(int goalstate, float range) { - Q_syscall( BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC, goalstate, PASSFLOAT(range) ); -} -int trap_BotAllocGoalState(int state) { - return Q_syscall( BOTLIB_AI_ALLOC_GOAL_STATE, state ); -} -void trap_BotFreeGoalState(int handle) { - Q_syscall( BOTLIB_AI_FREE_GOAL_STATE, handle ); -} -void trap_BotResetMoveState(int movestate) { - Q_syscall( BOTLIB_AI_RESET_MOVE_STATE, movestate ); -} +void trap_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { Q_syscall(BOTLIB_AI_SET_AVOID_GOAL_TIME, goalstate, number, PASSFLOAT(avoidtime)); } +void trap_BotInitLevelItems(void) { Q_syscall(BOTLIB_AI_INIT_LEVEL_ITEMS); } +void trap_BotUpdateEntityItems(void) { Q_syscall(BOTLIB_AI_UPDATE_ENTITY_ITEMS); } +int trap_BotLoadItemWeights(int goalstate, char *filename) { return Q_syscall(BOTLIB_AI_LOAD_ITEM_WEIGHTS, goalstate, filename); } +void trap_BotFreeItemWeights(int goalstate) { Q_syscall(BOTLIB_AI_FREE_ITEM_WEIGHTS, goalstate); } +void trap_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { Q_syscall(BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC, parent1, parent2, child); } +void trap_BotSaveGoalFuzzyLogic(int goalstate, char *filename) { Q_syscall(BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC, goalstate, filename); } +void trap_BotMutateGoalFuzzyLogic(int goalstate, float range) { Q_syscall(BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC, goalstate, PASSFLOAT(range)); } +int trap_BotAllocGoalState(int state) { return Q_syscall(BOTLIB_AI_ALLOC_GOAL_STATE, state); } +void trap_BotFreeGoalState(int handle) { Q_syscall(BOTLIB_AI_FREE_GOAL_STATE, handle); } +void trap_BotResetMoveState(int movestate) { Q_syscall(BOTLIB_AI_RESET_MOVE_STATE, movestate); } void trap_BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) { - Q_syscall( BOTLIB_AI_ADD_AVOID_SPOT, movestate, origin, PASSFLOAT(radius), type); -} -void trap_BotMoveToGoal(void *result, int movestate, void *goal, int travelflags) { - Q_syscall( BOTLIB_AI_MOVE_TO_GOAL, result, movestate, goal, travelflags ); + Q_syscall(BOTLIB_AI_ADD_AVOID_SPOT, movestate, origin, PASSFLOAT(radius), type); } +void trap_BotMoveToGoal(void *result, int movestate, void *goal, int travelflags) { Q_syscall(BOTLIB_AI_MOVE_TO_GOAL, result, movestate, goal, travelflags); } int trap_BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) { - return Q_syscall( BOTLIB_AI_MOVE_IN_DIRECTION, movestate, dir, PASSFLOAT(speed), type ); -} -void trap_BotResetAvoidReach(int movestate) { - Q_syscall( BOTLIB_AI_RESET_AVOID_REACH, movestate ); -} -void trap_BotResetLastAvoidReach(int movestate) { - Q_syscall( BOTLIB_AI_RESET_LAST_AVOID_REACH,movestate ); -} -int trap_BotReachabilityArea(vec3_t origin, int testground) { - return Q_syscall( BOTLIB_AI_REACHABILITY_AREA, origin, testground ); + return Q_syscall(BOTLIB_AI_MOVE_IN_DIRECTION, movestate, dir, PASSFLOAT(speed), type); } +void trap_BotResetAvoidReach(int movestate) { Q_syscall(BOTLIB_AI_RESET_AVOID_REACH, movestate); } +void trap_BotResetLastAvoidReach(int movestate) { Q_syscall(BOTLIB_AI_RESET_LAST_AVOID_REACH, movestate); } +int trap_BotReachabilityArea(vec3_t origin, int testground) { return Q_syscall(BOTLIB_AI_REACHABILITY_AREA, origin, testground); } int trap_BotMovementViewTarget(int movestate, void *goal, int travelflags, float lookahead, vec3_t target) { - return Q_syscall( BOTLIB_AI_MOVEMENT_VIEW_TARGET, movestate, goal, travelflags, PASSFLOAT(lookahead), target ); + return Q_syscall(BOTLIB_AI_MOVEMENT_VIEW_TARGET, movestate, goal, travelflags, PASSFLOAT(lookahead), target); } int trap_BotPredictVisiblePosition(vec3_t origin, int areanum, void *goal, int travelflags, vec3_t target) { - return Q_syscall( BOTLIB_AI_PREDICT_VISIBLE_POSITION, origin, areanum, goal, travelflags, target ); -} -int trap_BotAllocMoveState(void) { - return Q_syscall( BOTLIB_AI_ALLOC_MOVE_STATE ); -} -void trap_BotFreeMoveState(int handle) { - Q_syscall( BOTLIB_AI_FREE_MOVE_STATE, handle ); -} -void trap_BotInitMoveState(int handle, void *initmove) { - Q_syscall( BOTLIB_AI_INIT_MOVE_STATE, handle, initmove ); -} -int trap_BotChooseBestFightWeapon(int weaponstate, int *inventory) { - return Q_syscall( BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON, weaponstate, inventory ); -} -void trap_BotGetWeaponInfo(int weaponstate, int weapon, void *weaponinfo) { - Q_syscall( BOTLIB_AI_GET_WEAPON_INFO, weaponstate, weapon, weaponinfo ); -} -int trap_BotLoadWeaponWeights(int weaponstate, char *filename) { - return Q_syscall( BOTLIB_AI_LOAD_WEAPON_WEIGHTS, weaponstate, filename ); -} -int trap_BotAllocWeaponState(void) { - return Q_syscall( BOTLIB_AI_ALLOC_WEAPON_STATE ); -} -void trap_BotFreeWeaponState(int weaponstate) { - Q_syscall( BOTLIB_AI_FREE_WEAPON_STATE, weaponstate ); -} -void trap_BotResetWeaponState(int weaponstate) { - Q_syscall( BOTLIB_AI_RESET_WEAPON_STATE, weaponstate ); -} + return Q_syscall(BOTLIB_AI_PREDICT_VISIBLE_POSITION, origin, areanum, goal, travelflags, target); +} +int trap_BotAllocMoveState(void) { return Q_syscall(BOTLIB_AI_ALLOC_MOVE_STATE); } +void trap_BotFreeMoveState(int handle) { Q_syscall(BOTLIB_AI_FREE_MOVE_STATE, handle); } +void trap_BotInitMoveState(int handle, void *initmove) { Q_syscall(BOTLIB_AI_INIT_MOVE_STATE, handle, initmove); } +int trap_BotChooseBestFightWeapon(int weaponstate, int *inventory) { return Q_syscall(BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON, weaponstate, inventory); } +void trap_BotGetWeaponInfo(int weaponstate, int weapon, void *weaponinfo) { Q_syscall(BOTLIB_AI_GET_WEAPON_INFO, weaponstate, weapon, weaponinfo); } +int trap_BotLoadWeaponWeights(int weaponstate, char *filename) { return Q_syscall(BOTLIB_AI_LOAD_WEAPON_WEIGHTS, weaponstate, filename); } +int trap_BotAllocWeaponState(void) { return Q_syscall(BOTLIB_AI_ALLOC_WEAPON_STATE); } +void trap_BotFreeWeaponState(int weaponstate) { Q_syscall(BOTLIB_AI_FREE_WEAPON_STATE, weaponstate); } +void trap_BotResetWeaponState(int weaponstate) { Q_syscall(BOTLIB_AI_RESET_WEAPON_STATE, weaponstate); } int trap_GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) { - return Q_syscall( BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION, numranks, ranks, parent1, parent2, child ); -} -int trap_PC_LoadSource( const char *filename ) { - return Q_syscall( BOTLIB_PC_LOAD_SOURCE, filename ); -} -int trap_PC_FreeSource( int handle ) { - return Q_syscall( BOTLIB_PC_FREE_SOURCE, handle ); -} -int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) { - return Q_syscall( BOTLIB_PC_READ_TOKEN, handle, pc_token ); -} -int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) { - return Q_syscall( BOTLIB_PC_SOURCE_FILE_AND_LINE, handle, filename, line ); -} -qhandle_t trap_R_RegisterSkin( const char *name ) { - return Q_syscall( G_R_REGISTERSKIN, name ); -} -void trap_G2_ListModelBones(void *ghlInfo, int frame) { - Q_syscall( G_G2_LISTBONES, ghlInfo, frame); -} -void trap_G2_ListModelSurfaces(void *ghlInfo) { - Q_syscall( G_G2_LISTSURFACES, ghlInfo); -} -qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { - return (qboolean)(Q_syscall(G_G2_HAVEWEGHOULMODELS, ghoul2)); -} -void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { - Q_syscall( G_G2_SETMODELS, ghoul2, modelList, skinList); -} -qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + return Q_syscall(BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION, numranks, ranks, parent1, parent2, child); +} +int trap_PC_LoadSource(const char *filename) { return Q_syscall(BOTLIB_PC_LOAD_SOURCE, filename); } +int trap_PC_FreeSource(int handle) { return Q_syscall(BOTLIB_PC_FREE_SOURCE, handle); } +int trap_PC_ReadToken(int handle, pc_token_t *pc_token) { return Q_syscall(BOTLIB_PC_READ_TOKEN, handle, pc_token); } +int trap_PC_SourceFileAndLine(int handle, char *filename, int *line) { return Q_syscall(BOTLIB_PC_SOURCE_FILE_AND_LINE, handle, filename, line); } +qhandle_t trap_R_RegisterSkin(const char *name) { return Q_syscall(G_R_REGISTERSKIN, name); } +void trap_G2_ListModelBones(void *ghlInfo, int frame) { Q_syscall(G_G2_LISTBONES, ghlInfo, frame); } +void trap_G2_ListModelSurfaces(void *ghlInfo) { Q_syscall(G_G2_LISTSURFACES, ghlInfo); } +qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { return (qboolean)(Q_syscall(G_G2_HAVEWEGHOULMODELS, ghoul2)); } +void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { Q_syscall(G_G2_SETMODELS, ghoul2, modelList, skinList); } +qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(G_G2_GETBOLT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { +qboolean trap_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(G_G2_GETBOLT_NOREC, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { +qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(G_G2_GETBOLT_NOREC_NOROT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias) { +int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { return Q_syscall(G_G2_INITGHOUL2MODEL, ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } qboolean trap_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { return Q_syscall(G_G2_SETSKIN, ghoul2, modelIndex, customSkin, renderSkin); } -int trap_G2API_Ghoul2Size ( void* ghlInfo ) { - return Q_syscall(G_G2_SIZE, ghlInfo ); -} -int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { - return Q_syscall(G_G2_ADDBOLT, ghoul2, modelIndex, boneName); -} -void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { - Q_syscall(G_G2_SETBOLTINFO, ghoul2, modelIndex, boltInfo); -} -qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, const int forward, qhandle_t *modelList, int blendTime , int currentTime ) { +int trap_G2API_Ghoul2Size(void *ghlInfo) { return Q_syscall(G_G2_SIZE, ghlInfo); } +int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { return Q_syscall(G_G2_ADDBOLT, ghoul2, modelIndex, boneName); } +void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { Q_syscall(G_G2_SETBOLTINFO, ghoul2, modelIndex, boltInfo); } +qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { return (Q_syscall(G_G2_ANGLEOVERRIDE, ghoul2, modelIndex, boneName, angles, flags, up, right, forward, modelList, blendTime, currentTime)); } -qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame , const int blendTime ) { - return Q_syscall(G_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), blendTime); +qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + return Q_syscall(G_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), + blendTime); } -qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList, const int modelIndex) { +qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { return Q_syscall(G_G2_GETBONEANIM, ghoul2, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, modelIndex); } -void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { - Q_syscall(G_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); -} -int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { - return Q_syscall(G_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); -} +void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { Q_syscall(G_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); } +int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { return Q_syscall(G_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); } void trap_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { Q_syscall(G_G2_COPYSPECIFICGHOUL2MODEL, g2From, modelFrom, g2To, modelTo); } -void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { - Q_syscall(G_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); -} -qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { - return Q_syscall(G_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); -} -qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { - return Q_syscall(G_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); -} -qboolean trap_G2API_RemoveGhoul2Models(void *ghlInfo) { - return Q_syscall(G_G2_REMOVEGHOUL2MODELS, ghlInfo); +void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { Q_syscall(G_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); } +qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { return Q_syscall(G_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); } +qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { return Q_syscall(G_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); } +qboolean trap_G2API_RemoveGhoul2Models(void *ghlInfo) { return Q_syscall(G_G2_REMOVEGHOUL2MODELS, ghlInfo); } +void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { Q_syscall(G_G2_CLEANMODELS, ghoul2Ptr); } +void trap_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(G_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius)); } -void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { - Q_syscall(G_G2_CLEANMODELS, ghoul2Ptr); -} -void trap_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( G_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); -} -void trap_G2API_CollisionDetectCache( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( G_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); +void trap_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(G_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, + PASSFLOAT(fRadius)); } void trap_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { Q_syscall(G_G2_GETSURFACENAME, ghoul2, surfNumber, modelIndex, fillBuf); @@ -921,437 +454,410 @@ qboolean trap_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const cha qboolean trap_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { return Q_syscall(G_G2_SETSURFACEONOFF, ghoul2, surfaceName, flags); } -qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { - return Q_syscall(G_G2_SETNEWORIGIN, ghoul2, boltIndex); -} -qboolean trap_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { - return Q_syscall(G_G2_DOESBONEEXIST, ghoul2, modelIndex, boneName); -} +qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { return Q_syscall(G_G2_SETNEWORIGIN, ghoul2, boltIndex); } +qboolean trap_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { return Q_syscall(G_G2_DOESBONEEXIST, ghoul2, modelIndex, boneName); } int trap_G2API_GetSurfaceRenderStatus(void *ghoul2, const int modelIndex, const char *surfaceName) { return Q_syscall(G_G2_GETSURFACERENDERSTATUS, ghoul2, modelIndex, surfaceName); } -void trap_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { - Q_syscall(G_G2_ABSURDSMOOTHING, ghoul2, status); -} -void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { - Q_syscall(G_G2_SETRAGDOLL, ghoul2, params); -} -void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { - Q_syscall(G_G2_ANIMATEG2MODELS, ghoul2, time, params); -} +void trap_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { Q_syscall(G_G2_ABSURDSMOOTHING, ghoul2, status); } +void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { Q_syscall(G_G2_SETRAGDOLL, ghoul2, params); } +void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { Q_syscall(G_G2_ANIMATEG2MODELS, ghoul2, time, params); } qboolean trap_G2API_RagPCJConstraint(void *ghoul2, const char *boneName, vec3_t min, vec3_t max) { return Q_syscall(G_G2_RAGPCJCONSTRAINT, ghoul2, boneName, min, max); } qboolean trap_G2API_RagPCJGradientSpeed(void *ghoul2, const char *boneName, const float speed) { return Q_syscall(G_G2_RAGPCJGRADIENTSPEED, ghoul2, boneName, PASSFLOAT(speed)); } -qboolean trap_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { - return Q_syscall(G_G2_RAGEFFECTORGOAL, ghoul2, boneName, pos); -} +qboolean trap_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { return Q_syscall(G_G2_RAGEFFECTORGOAL, ghoul2, boneName, pos); } qboolean trap_G2API_GetRagBonePos(void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { return Q_syscall(G_G2_GETRAGBONEPOS, ghoul2, boneName, pos, entAngles, entPos, entScale); } -qboolean trap_G2API_RagEffectorKick(void *ghoul2, const char *boneName, vec3_t velocity) { - return Q_syscall(G_G2_RAGEFFECTORKICK, ghoul2, boneName, velocity); -} -qboolean trap_G2API_RagForceSolve(void *ghoul2, qboolean force) { - return Q_syscall(G_G2_RAGFORCESOLVE, ghoul2, force); -} +qboolean trap_G2API_RagEffectorKick(void *ghoul2, const char *boneName, vec3_t velocity) { return Q_syscall(G_G2_RAGEFFECTORKICK, ghoul2, boneName, velocity); } +qboolean trap_G2API_RagForceSolve(void *ghoul2, qboolean force) { return Q_syscall(G_G2_RAGFORCESOLVE, ghoul2, force); } qboolean trap_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return Q_syscall(G_G2_SETBONEIKSTATE, ghoul2, time, boneName, ikState, params); } -qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { - return Q_syscall(G_G2_IKMOVE, ghoul2, time, params); -} -qboolean trap_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { - return Q_syscall(G_G2_REMOVEBONE, ghoul2, boneName, modelIndex); -} -void trap_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { - Q_syscall(G_G2_ATTACHINSTANCETOENTNUM, ghoul2, entityNum, server); -} -void trap_G2API_ClearAttachedInstance(int entityNum) { - Q_syscall(G_G2_CLEARATTACHEDINSTANCE, entityNum); -} -void trap_G2API_CleanEntAttachments(void) { - Q_syscall(G_G2_CLEANENTATTACHMENTS); -} -qboolean trap_G2API_OverrideServer(void *serverInstance) { - return Q_syscall(G_G2_OVERRIDESERVER, serverInstance); -} -const char *trap_SetActiveSubBSP(int index) { - return (char *)Q_syscall( G_SET_ACTIVE_SUBBSP, index ); -} -int trap_CM_RegisterTerrain(const char *config) { - return Q_syscall(G_CM_REGISTER_TERRAIN, config); -} -void trap_RMG_Init( void ) { - Q_syscall(G_RMG_INIT); -} -void trap_Bot_UpdateWaypoints(int wpnum, wpobject_t **wps) { - Q_syscall(G_BOT_UPDATEWAYPOINTS, wpnum, wps); -} -void trap_Bot_CalculatePaths(int rmg) { - Q_syscall(G_BOT_CALCULATEPATHS, rmg); -} - +qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { return Q_syscall(G_G2_IKMOVE, ghoul2, time, params); } +qboolean trap_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { return Q_syscall(G_G2_REMOVEBONE, ghoul2, boneName, modelIndex); } +void trap_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { Q_syscall(G_G2_ATTACHINSTANCETOENTNUM, ghoul2, entityNum, server); } +void trap_G2API_ClearAttachedInstance(int entityNum) { Q_syscall(G_G2_CLEARATTACHEDINSTANCE, entityNum); } +void trap_G2API_CleanEntAttachments(void) { Q_syscall(G_G2_CLEANENTATTACHMENTS); } +qboolean trap_G2API_OverrideServer(void *serverInstance) { return Q_syscall(G_G2_OVERRIDESERVER, serverInstance); } +const char *trap_SetActiveSubBSP(int index) { return (char *)Q_syscall(G_SET_ACTIVE_SUBBSP, index); } +int trap_CM_RegisterTerrain(const char *config) { return Q_syscall(G_CM_REGISTER_TERRAIN, config); } +void trap_RMG_Init(void) { Q_syscall(G_RMG_INIT); } +void trap_Bot_UpdateWaypoints(int wpnum, wpobject_t **wps) { Q_syscall(G_BOT_UPDATEWAYPOINTS, wpnum, wps); } +void trap_Bot_CalculatePaths(int rmg) { Q_syscall(G_BOT_CALCULATEPATHS, rmg); } // Translate import table funcptrs to syscalls -int SVSyscall_FS_Read( void *buffer, int len, fileHandle_t f ) { trap_FS_Read( buffer, len, f ); return 0; } -int SVSyscall_FS_Write( const void *buffer, int len, fileHandle_t f ) { trap_FS_Write( buffer, len, f ); return 0; } -qboolean SVSyscall_EntityContact( const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent, int capsule ) { if ( capsule ) return trap_EntityContactCapsule( mins, maxs, ent ); else return trap_EntityContact( mins, maxs, ent ); } +int SVSyscall_FS_Read(void *buffer, int len, fileHandle_t f) { + trap_FS_Read(buffer, len, f); + return 0; +} +int SVSyscall_FS_Write(const void *buffer, int len, fileHandle_t f) { + trap_FS_Write(buffer, len, f); + return 0; +} +qboolean SVSyscall_EntityContact(const vec3_t mins, const vec3_t maxs, const sharedEntity_t *ent, int capsule) { + if (capsule) + return trap_EntityContactCapsule(mins, maxs, ent); + else + return trap_EntityContact(mins, maxs, ent); +} -void SVSyscall_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule, int traceFlags, int useLod ) { - if ( capsule ) - trap_TraceCapsule( results, start, mins, maxs, end, passEntityNum, contentmask ); - else if ( traceFlags ) - trap_G2Trace( results, start, mins, maxs, end, passEntityNum, contentmask, traceFlags, useLod ); +void SVSyscall_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, + int capsule, int traceFlags, int useLod) { + if (capsule) + trap_TraceCapsule(results, start, mins, maxs, end, passEntityNum, contentmask); + else if (traceFlags) + trap_G2Trace(results, start, mins, maxs, end, passEntityNum, contentmask, traceFlags, useLod); else - trap_Trace( results, start, mins, maxs, end, passEntityNum, contentmask ); + trap_Trace(results, start, mins, maxs, end, passEntityNum, contentmask); } -NORETURN void QDECL G_Error( int errorLevel, const char *error, ... ) { +NORETURN void QDECL G_Error(int errorLevel, const char *error, ...) { va_list argptr; char text[1024]; - va_start( argptr, error ); - Q_vsnprintf( text, sizeof( text ), error, argptr ); - va_end( argptr ); + va_start(argptr, error); + Q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); - trap_Error( text ); + trap_Error(text); } -void QDECL G_Printf( const char *msg, ... ) { +void QDECL G_Printf(const char *msg, ...) { va_list argptr; char text[4096] = {0}; int ret; - va_start( argptr, msg ); - ret = Q_vsnprintf( text, sizeof( text ), msg, argptr ); - va_end( argptr ); + va_start(argptr, msg); + ret = Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - if ( ret == -1 ) - trap_Print( "G_Printf: overflow of 4096 bytes buffer\n" ); + if (ret == -1) + trap_Print("G_Printf: overflow of 4096 bytes buffer\n"); else - trap_Print( text ); + trap_Print(text); } -static void TranslateSyscalls( void ) { +static void TranslateSyscalls(void) { static gameImport_t import; - memset( &import, 0, sizeof( import ) ); + memset(&import, 0, sizeof(import)); trap = &import; - Com_Error = G_Error; - Com_Printf = G_Printf; + Com_Error = G_Error; + Com_Printf = G_Printf; - trap->Print = Com_Printf; - trap->Error = Com_Error; - trap->Milliseconds = trap_Milliseconds; - trap->PrecisionTimerStart = trap_PrecisionTimer_Start; - trap->PrecisionTimerEnd = trap_PrecisionTimer_End; - trap->SV_RegisterSharedMemory = trap_SV_RegisterSharedMemory; - trap->RealTime = trap_RealTime; - trap->TrueMalloc = trap_TrueMalloc; - trap->TrueFree = trap_TrueFree; - trap->SnapVector = trap_SnapVector; - trap->Cvar_Register = trap_Cvar_Register; - trap->Cvar_Set = trap_Cvar_Set; - trap->Cvar_Update = trap_Cvar_Update; - trap->Cvar_VariableIntegerValue = trap_Cvar_VariableIntegerValue; - trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; - trap->Argc = trap_Argc; - trap->Argv = trap_Argv; - trap->FS_Close = trap_FS_FCloseFile; - trap->FS_GetFileList = trap_FS_GetFileList; - trap->FS_Open = trap_FS_FOpenFile; - trap->FS_Read = SVSyscall_FS_Read; - trap->FS_Write = SVSyscall_FS_Write; - trap->AdjustAreaPortalState = trap_AdjustAreaPortalState; - trap->AreasConnected = trap_AreasConnected; - trap->DebugPolygonCreate = trap_DebugPolygonCreate; - trap->DebugPolygonDelete = trap_DebugPolygonDelete; - trap->DropClient = trap_DropClient; - trap->EntitiesInBox = trap_EntitiesInBox; - trap->EntityContact = SVSyscall_EntityContact; - trap->Trace = SVSyscall_Trace; - trap->GetConfigstring = trap_GetConfigstring; - trap->GetEntityToken = trap_GetEntityToken; - trap->GetServerinfo = trap_GetServerinfo; - trap->GetUsercmd = trap_GetUsercmd; - trap->GetUserinfo = trap_GetUserinfo; - trap->InPVS = trap_InPVS; - trap->InPVSIgnorePortals = trap_InPVSIgnorePortals; - trap->LinkEntity = trap_LinkEntity; - trap->LocateGameData = trap_LocateGameData; - trap->PointContents = trap_PointContents; - trap->SendConsoleCommand = trap_SendConsoleCommand; - trap->SendServerCommand = trap_SendServerCommand; - trap->SetBrushModel = trap_SetBrushModel; - trap->SetConfigstring = trap_SetConfigstring; - trap->SetServerCull = trap_SetServerCull; - trap->SetUserinfo = trap_SetUserinfo; - trap->SiegePersSet = trap_SiegePersSet; - trap->SiegePersGet = trap_SiegePersGet; - trap->UnlinkEntity = trap_UnlinkEntity; - trap->ROFF_Clean = trap_ROFF_Clean; - trap->ROFF_UpdateEntities = trap_ROFF_UpdateEntities; - trap->ROFF_Cache = trap_ROFF_Cache; - trap->ROFF_Play = trap_ROFF_Play; - trap->ROFF_Purge_Ent = trap_ROFF_Purge_Ent; - trap->ICARUS_RunScript = trap_ICARUS_RunScript; - trap->ICARUS_RegisterScript = trap_ICARUS_RegisterScript; - trap->ICARUS_Init = trap_ICARUS_Init; - trap->ICARUS_ValidEnt = trap_ICARUS_ValidEnt; - trap->ICARUS_IsInitialized = trap_ICARUS_IsInitialized; - trap->ICARUS_MaintainTaskManager = trap_ICARUS_MaintainTaskManager; - trap->ICARUS_IsRunning = trap_ICARUS_IsRunning; - trap->ICARUS_TaskIDPending = trap_ICARUS_TaskIDPending; - trap->ICARUS_InitEnt = trap_ICARUS_InitEnt; - trap->ICARUS_FreeEnt = trap_ICARUS_FreeEnt; - trap->ICARUS_AssociateEnt = trap_ICARUS_AssociateEnt; - trap->ICARUS_Shutdown = trap_ICARUS_Shutdown; - trap->ICARUS_TaskIDSet = trap_ICARUS_TaskIDSet; - trap->ICARUS_TaskIDComplete = trap_ICARUS_TaskIDComplete; - trap->ICARUS_SetVar = trap_ICARUS_SetVar; - trap->ICARUS_VariableDeclared = trap_ICARUS_VariableDeclared; - trap->ICARUS_GetFloatVariable = trap_ICARUS_GetFloatVariable; - trap->ICARUS_GetStringVariable = trap_ICARUS_GetStringVariable; - trap->ICARUS_GetVectorVariable = trap_ICARUS_GetVectorVariable; - trap->Nav_Init = trap_Nav_Init; - trap->Nav_Free = trap_Nav_Free; - trap->Nav_Load = trap_Nav_Load; - trap->Nav_Save = trap_Nav_Save; - trap->Nav_AddRawPoint = trap_Nav_AddRawPoint; - trap->Nav_CalculatePaths = trap_Nav_CalculatePaths; - trap->Nav_HardConnect = trap_Nav_HardConnect; - trap->Nav_ShowNodes = trap_Nav_ShowNodes; - trap->Nav_ShowEdges = trap_Nav_ShowEdges; - trap->Nav_ShowPath = trap_Nav_ShowPath; - trap->Nav_GetNearestNode = trap_Nav_GetNearestNode; - trap->Nav_GetBestNode = trap_Nav_GetBestNode; - trap->Nav_GetNodePosition = trap_Nav_GetNodePosition; - trap->Nav_GetNodeNumEdges = trap_Nav_GetNodeNumEdges; - trap->Nav_GetNodeEdge = trap_Nav_GetNodeEdge; - trap->Nav_GetNumNodes = trap_Nav_GetNumNodes; - trap->Nav_Connected = trap_Nav_Connected; - trap->Nav_GetPathCost = trap_Nav_GetPathCost; - trap->Nav_GetEdgeCost = trap_Nav_GetEdgeCost; - trap->Nav_GetProjectedNode = trap_Nav_GetProjectedNode; - trap->Nav_CheckFailedNodes = trap_Nav_CheckFailedNodes; - trap->Nav_AddFailedNode = trap_Nav_AddFailedNode; - trap->Nav_NodeFailed = trap_Nav_NodeFailed; - trap->Nav_NodesAreNeighbors = trap_Nav_NodesAreNeighbors; - trap->Nav_ClearFailedEdge = trap_Nav_ClearFailedEdge; - trap->Nav_ClearAllFailedEdges = trap_Nav_ClearAllFailedEdges; - trap->Nav_EdgeFailed = trap_Nav_EdgeFailed; - trap->Nav_AddFailedEdge = trap_Nav_AddFailedEdge; - trap->Nav_CheckFailedEdge = trap_Nav_CheckFailedEdge; - trap->Nav_CheckAllFailedEdges = trap_Nav_CheckAllFailedEdges; - trap->Nav_RouteBlocked = trap_Nav_RouteBlocked; - trap->Nav_GetBestNodeAltRoute = trap_Nav_GetBestNodeAltRoute; - trap->Nav_GetBestNodeAltRoute2 = trap_Nav_GetBestNodeAltRoute2; - trap->Nav_GetBestPathBetweenEnts = trap_Nav_GetBestPathBetweenEnts; - trap->Nav_GetNodeRadius = trap_Nav_GetNodeRadius; - trap->Nav_CheckBlockedEdges = trap_Nav_CheckBlockedEdges; - trap->Nav_ClearCheckedNodes = trap_Nav_ClearCheckedNodes; - trap->Nav_CheckedNode = trap_Nav_CheckedNode; - trap->Nav_SetCheckedNode = trap_Nav_SetCheckedNode; - trap->Nav_FlagAllNodes = trap_Nav_FlagAllNodes; - trap->Nav_GetPathsCalculated = trap_Nav_GetPathsCalculated; - trap->Nav_SetPathsCalculated = trap_Nav_SetPathsCalculated; - trap->BotAllocateClient = trap_BotAllocateClient; - trap->BotFreeClient = trap_BotFreeClient; - trap->BotLoadCharacter = trap_BotLoadCharacter; - trap->BotFreeCharacter = trap_BotFreeCharacter; - trap->Characteristic_Float = trap_Characteristic_Float; - trap->Characteristic_BFloat = trap_Characteristic_BFloat; - trap->Characteristic_Integer = trap_Characteristic_Integer; - trap->Characteristic_BInteger = trap_Characteristic_BInteger; - trap->Characteristic_String = trap_Characteristic_String; - trap->BotAllocChatState = trap_BotAllocChatState; - trap->BotFreeChatState = trap_BotFreeChatState; - trap->BotQueueConsoleMessage = trap_BotQueueConsoleMessage; - trap->BotRemoveConsoleMessage = trap_BotRemoveConsoleMessage; - trap->BotNextConsoleMessage = trap_BotNextConsoleMessage; - trap->BotNumConsoleMessages = trap_BotNumConsoleMessages; - trap->BotInitialChat = trap_BotInitialChat; - trap->BotReplyChat = trap_BotReplyChat; - trap->BotChatLength = trap_BotChatLength; - trap->BotEnterChat = trap_BotEnterChat; - trap->StringContains = trap_StringContains; - trap->BotFindMatch = trap_BotFindMatch; - trap->BotMatchVariable = trap_BotMatchVariable; - trap->UnifyWhiteSpaces = trap_UnifyWhiteSpaces; - trap->BotReplaceSynonyms = trap_BotReplaceSynonyms; - trap->BotLoadChatFile = trap_BotLoadChatFile; - trap->BotSetChatGender = trap_BotSetChatGender; - trap->BotSetChatName = trap_BotSetChatName; - trap->BotResetGoalState = trap_BotResetGoalState; - trap->BotResetAvoidGoals = trap_BotResetAvoidGoals; - trap->BotPushGoal = trap_BotPushGoal; - trap->BotPopGoal = trap_BotPopGoal; - trap->BotEmptyGoalStack = trap_BotEmptyGoalStack; - trap->BotDumpAvoidGoals = trap_BotDumpAvoidGoals; - trap->BotDumpGoalStack = trap_BotDumpGoalStack; - trap->BotGoalName = trap_BotGoalName; - trap->BotGetTopGoal = trap_BotGetTopGoal; - trap->BotGetSecondGoal = trap_BotGetSecondGoal; - trap->BotChooseLTGItem = trap_BotChooseLTGItem; - trap->BotChooseNBGItem = trap_BotChooseNBGItem; - trap->BotTouchingGoal = trap_BotTouchingGoal; - trap->BotItemGoalInVisButNotVisible = trap_BotItemGoalInVisButNotVisible; - trap->BotGetLevelItemGoal = trap_BotGetLevelItemGoal; - trap->BotAvoidGoalTime = trap_BotAvoidGoalTime; - trap->BotInitLevelItems = trap_BotInitLevelItems; - trap->BotUpdateEntityItems = trap_BotUpdateEntityItems; - trap->BotLoadItemWeights = trap_BotLoadItemWeights; - trap->BotFreeItemWeights = trap_BotFreeItemWeights; - trap->BotSaveGoalFuzzyLogic = trap_BotSaveGoalFuzzyLogic; - trap->BotAllocGoalState = trap_BotAllocGoalState; - trap->BotFreeGoalState = trap_BotFreeGoalState; - trap->BotResetMoveState = trap_BotResetMoveState; - trap->BotMoveToGoal = trap_BotMoveToGoal; - trap->BotMoveInDirection = trap_BotMoveInDirection; - trap->BotResetAvoidReach = trap_BotResetAvoidReach; - trap->BotResetLastAvoidReach = trap_BotResetLastAvoidReach; - trap->BotReachabilityArea = trap_BotReachabilityArea; - trap->BotMovementViewTarget = trap_BotMovementViewTarget; - trap->BotAllocMoveState = trap_BotAllocMoveState; - trap->BotFreeMoveState = trap_BotFreeMoveState; - trap->BotInitMoveState = trap_BotInitMoveState; - trap->BotChooseBestFightWeapon = trap_BotChooseBestFightWeapon; - trap->BotGetWeaponInfo = trap_BotGetWeaponInfo; - trap->BotLoadWeaponWeights = trap_BotLoadWeaponWeights; - trap->BotAllocWeaponState = trap_BotAllocWeaponState; - trap->BotFreeWeaponState = trap_BotFreeWeaponState; - trap->BotResetWeaponState = trap_BotResetWeaponState; - trap->GeneticParentsAndChildSelection = trap_GeneticParentsAndChildSelection; - trap->BotInterbreedGoalFuzzyLogic = trap_BotInterbreedGoalFuzzyLogic; - trap->BotMutateGoalFuzzyLogic = trap_BotMutateGoalFuzzyLogic; - trap->BotGetNextCampSpotGoal = trap_BotGetNextCampSpotGoal; - trap->BotGetMapLocationGoal = trap_BotGetMapLocationGoal; - trap->BotNumInitialChats = trap_BotNumInitialChats; - trap->BotGetChatMessage = trap_BotGetChatMessage; - trap->BotRemoveFromAvoidGoals = trap_BotRemoveFromAvoidGoals; - trap->BotPredictVisiblePosition = trap_BotPredictVisiblePosition; - trap->BotSetAvoidGoalTime = trap_BotSetAvoidGoalTime; - trap->BotAddAvoidSpot = trap_BotAddAvoidSpot; - trap->BotLibSetup = trap_BotLibSetup; - trap->BotLibShutdown = trap_BotLibShutdown; - trap->BotLibVarSet = trap_BotLibVarSet; - trap->BotLibVarGet = trap_BotLibVarGet; - trap->BotLibDefine = trap_BotLibDefine; - trap->BotLibStartFrame = trap_BotLibStartFrame; - trap->BotLibLoadMap = trap_BotLibLoadMap; - trap->BotLibUpdateEntity = trap_BotLibUpdateEntity; - trap->BotLibTest = trap_BotLibTest; - trap->BotGetSnapshotEntity = trap_BotGetSnapshotEntity; - trap->BotGetServerCommand = trap_BotGetServerCommand; - trap->BotUserCommand = trap_BotUserCommand; - trap->BotUpdateWaypoints = trap_Bot_UpdateWaypoints; - trap->BotCalculatePaths = trap_Bot_CalculatePaths; - trap->AAS_EnableRoutingArea = trap_AAS_EnableRoutingArea; - trap->AAS_BBoxAreas = trap_AAS_BBoxAreas; - trap->AAS_AreaInfo = trap_AAS_AreaInfo; - trap->AAS_EntityInfo = trap_AAS_EntityInfo; - trap->AAS_Initialized = trap_AAS_Initialized; - trap->AAS_PresenceTypeBoundingBox = trap_AAS_PresenceTypeBoundingBox; - trap->AAS_Time = trap_AAS_Time; - trap->AAS_PointAreaNum = trap_AAS_PointAreaNum; - trap->AAS_TraceAreas = trap_AAS_TraceAreas; - trap->AAS_PointContents = trap_AAS_PointContents; - trap->AAS_NextBSPEntity = trap_AAS_NextBSPEntity; - trap->AAS_ValueForBSPEpairKey = trap_AAS_ValueForBSPEpairKey; - trap->AAS_VectorForBSPEpairKey = trap_AAS_VectorForBSPEpairKey; - trap->AAS_FloatForBSPEpairKey = trap_AAS_FloatForBSPEpairKey; - trap->AAS_IntForBSPEpairKey = trap_AAS_IntForBSPEpairKey; - trap->AAS_AreaReachability = trap_AAS_AreaReachability; - trap->AAS_AreaTravelTimeToGoalArea = trap_AAS_AreaTravelTimeToGoalArea; - trap->AAS_Swimming = trap_AAS_Swimming; - trap->AAS_PredictClientMovement = trap_AAS_PredictClientMovement; - trap->AAS_AlternativeRouteGoals = trap_AAS_AlternativeRouteGoals; - trap->AAS_PredictRoute = trap_AAS_PredictRoute; - trap->AAS_PointReachabilityAreaIndex = trap_AAS_PointReachabilityAreaIndex; - trap->EA_Say = trap_EA_Say; - trap->EA_SayTeam = trap_EA_SayTeam; - trap->EA_Command = trap_EA_Command; - trap->EA_Action = trap_EA_Action; - trap->EA_Gesture = trap_EA_Gesture; - trap->EA_Talk = trap_EA_Talk; - trap->EA_Attack = trap_EA_Attack; - trap->EA_Alt_Attack = trap_EA_Alt_Attack; - trap->EA_ForcePower = trap_EA_ForcePower; - trap->EA_Use = trap_EA_Use; - trap->EA_Respawn = trap_EA_Respawn; - trap->EA_Crouch = trap_EA_Crouch; - trap->EA_MoveUp = trap_EA_MoveUp; - trap->EA_MoveDown = trap_EA_MoveDown; - trap->EA_MoveForward = trap_EA_MoveForward; - trap->EA_MoveBack = trap_EA_MoveBack; - trap->EA_MoveLeft = trap_EA_MoveLeft; - trap->EA_MoveRight = trap_EA_MoveRight; - trap->EA_SelectWeapon = trap_EA_SelectWeapon; - trap->EA_Jump = trap_EA_Jump; - trap->EA_DelayedJump = trap_EA_DelayedJump; - trap->EA_Move = trap_EA_Move; - trap->EA_View = trap_EA_View; - trap->EA_EndRegular = trap_EA_EndRegular; - trap->EA_GetInput = trap_EA_GetInput; - trap->EA_ResetInput = trap_EA_ResetInput; - trap->PC_LoadSource = trap_PC_LoadSource; - trap->PC_FreeSource = trap_PC_FreeSource; - trap->PC_ReadToken = trap_PC_ReadToken; - trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; - trap->R_RegisterSkin = trap_R_RegisterSkin; - trap->SetActiveSubBSP = trap_SetActiveSubBSP; - trap->CM_RegisterTerrain = trap_CM_RegisterTerrain; - trap->RMG_Init = trap_RMG_Init; - trap->G2API_ListModelBones = trap_G2_ListModelBones; - trap->G2API_ListModelSurfaces = trap_G2_ListModelSurfaces; - trap->G2API_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; - trap->G2API_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; - trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; - trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; - trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; - trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; - trap->G2API_SetSkin = trap_G2API_SetSkin; - trap->G2API_Ghoul2Size = trap_G2API_Ghoul2Size; - trap->G2API_AddBolt = trap_G2API_AddBolt; - trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; - trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; - trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; - trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; - trap->G2API_GetGLAName = trap_G2API_GetGLAName; - trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; - trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; - trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; - trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; - trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; - trap->G2API_RemoveGhoul2Models = trap_G2API_RemoveGhoul2Models; - trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; - trap->G2API_CollisionDetect = trap_G2API_CollisionDetect; - trap->G2API_CollisionDetectCache = trap_G2API_CollisionDetectCache; - trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; - trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; - trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; - trap->G2API_DoesBoneExist = trap_G2API_DoesBoneExist; - trap->G2API_GetSurfaceRenderStatus = trap_G2API_GetSurfaceRenderStatus; - trap->G2API_AbsurdSmoothing = trap_G2API_AbsurdSmoothing; - trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; - trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; - trap->G2API_RagPCJConstraint = trap_G2API_RagPCJConstraint; - trap->G2API_RagPCJGradientSpeed = trap_G2API_RagPCJGradientSpeed; - trap->G2API_RagEffectorGoal = trap_G2API_RagEffectorGoal; - trap->G2API_GetRagBonePos = trap_G2API_GetRagBonePos; - trap->G2API_RagEffectorKick = trap_G2API_RagEffectorKick; - trap->G2API_RagForceSolve = trap_G2API_RagForceSolve; - trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; - trap->G2API_IKMove = trap_G2API_IKMove; - trap->G2API_RemoveBone = trap_G2API_RemoveBone; - trap->G2API_AttachInstanceToEntNum = trap_G2API_AttachInstanceToEntNum; - trap->G2API_ClearAttachedInstance = trap_G2API_ClearAttachedInstance; - trap->G2API_CleanEntAttachments = trap_G2API_CleanEntAttachments; - trap->G2API_OverrideServer = trap_G2API_OverrideServer; - trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; + trap->Print = Com_Printf; + trap->Error = Com_Error; + trap->Milliseconds = trap_Milliseconds; + trap->PrecisionTimerStart = trap_PrecisionTimer_Start; + trap->PrecisionTimerEnd = trap_PrecisionTimer_End; + trap->SV_RegisterSharedMemory = trap_SV_RegisterSharedMemory; + trap->RealTime = trap_RealTime; + trap->TrueMalloc = trap_TrueMalloc; + trap->TrueFree = trap_TrueFree; + trap->SnapVector = trap_SnapVector; + trap->Cvar_Register = trap_Cvar_Register; + trap->Cvar_Set = trap_Cvar_Set; + trap->Cvar_Update = trap_Cvar_Update; + trap->Cvar_VariableIntegerValue = trap_Cvar_VariableIntegerValue; + trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; + trap->Argc = trap_Argc; + trap->Argv = trap_Argv; + trap->FS_Close = trap_FS_FCloseFile; + trap->FS_GetFileList = trap_FS_GetFileList; + trap->FS_Open = trap_FS_FOpenFile; + trap->FS_Read = SVSyscall_FS_Read; + trap->FS_Write = SVSyscall_FS_Write; + trap->AdjustAreaPortalState = trap_AdjustAreaPortalState; + trap->AreasConnected = trap_AreasConnected; + trap->DebugPolygonCreate = trap_DebugPolygonCreate; + trap->DebugPolygonDelete = trap_DebugPolygonDelete; + trap->DropClient = trap_DropClient; + trap->EntitiesInBox = trap_EntitiesInBox; + trap->EntityContact = SVSyscall_EntityContact; + trap->Trace = SVSyscall_Trace; + trap->GetConfigstring = trap_GetConfigstring; + trap->GetEntityToken = trap_GetEntityToken; + trap->GetServerinfo = trap_GetServerinfo; + trap->GetUsercmd = trap_GetUsercmd; + trap->GetUserinfo = trap_GetUserinfo; + trap->InPVS = trap_InPVS; + trap->InPVSIgnorePortals = trap_InPVSIgnorePortals; + trap->LinkEntity = trap_LinkEntity; + trap->LocateGameData = trap_LocateGameData; + trap->PointContents = trap_PointContents; + trap->SendConsoleCommand = trap_SendConsoleCommand; + trap->SendServerCommand = trap_SendServerCommand; + trap->SetBrushModel = trap_SetBrushModel; + trap->SetConfigstring = trap_SetConfigstring; + trap->SetServerCull = trap_SetServerCull; + trap->SetUserinfo = trap_SetUserinfo; + trap->SiegePersSet = trap_SiegePersSet; + trap->SiegePersGet = trap_SiegePersGet; + trap->UnlinkEntity = trap_UnlinkEntity; + trap->ROFF_Clean = trap_ROFF_Clean; + trap->ROFF_UpdateEntities = trap_ROFF_UpdateEntities; + trap->ROFF_Cache = trap_ROFF_Cache; + trap->ROFF_Play = trap_ROFF_Play; + trap->ROFF_Purge_Ent = trap_ROFF_Purge_Ent; + trap->ICARUS_RunScript = trap_ICARUS_RunScript; + trap->ICARUS_RegisterScript = trap_ICARUS_RegisterScript; + trap->ICARUS_Init = trap_ICARUS_Init; + trap->ICARUS_ValidEnt = trap_ICARUS_ValidEnt; + trap->ICARUS_IsInitialized = trap_ICARUS_IsInitialized; + trap->ICARUS_MaintainTaskManager = trap_ICARUS_MaintainTaskManager; + trap->ICARUS_IsRunning = trap_ICARUS_IsRunning; + trap->ICARUS_TaskIDPending = trap_ICARUS_TaskIDPending; + trap->ICARUS_InitEnt = trap_ICARUS_InitEnt; + trap->ICARUS_FreeEnt = trap_ICARUS_FreeEnt; + trap->ICARUS_AssociateEnt = trap_ICARUS_AssociateEnt; + trap->ICARUS_Shutdown = trap_ICARUS_Shutdown; + trap->ICARUS_TaskIDSet = trap_ICARUS_TaskIDSet; + trap->ICARUS_TaskIDComplete = trap_ICARUS_TaskIDComplete; + trap->ICARUS_SetVar = trap_ICARUS_SetVar; + trap->ICARUS_VariableDeclared = trap_ICARUS_VariableDeclared; + trap->ICARUS_GetFloatVariable = trap_ICARUS_GetFloatVariable; + trap->ICARUS_GetStringVariable = trap_ICARUS_GetStringVariable; + trap->ICARUS_GetVectorVariable = trap_ICARUS_GetVectorVariable; + trap->Nav_Init = trap_Nav_Init; + trap->Nav_Free = trap_Nav_Free; + trap->Nav_Load = trap_Nav_Load; + trap->Nav_Save = trap_Nav_Save; + trap->Nav_AddRawPoint = trap_Nav_AddRawPoint; + trap->Nav_CalculatePaths = trap_Nav_CalculatePaths; + trap->Nav_HardConnect = trap_Nav_HardConnect; + trap->Nav_ShowNodes = trap_Nav_ShowNodes; + trap->Nav_ShowEdges = trap_Nav_ShowEdges; + trap->Nav_ShowPath = trap_Nav_ShowPath; + trap->Nav_GetNearestNode = trap_Nav_GetNearestNode; + trap->Nav_GetBestNode = trap_Nav_GetBestNode; + trap->Nav_GetNodePosition = trap_Nav_GetNodePosition; + trap->Nav_GetNodeNumEdges = trap_Nav_GetNodeNumEdges; + trap->Nav_GetNodeEdge = trap_Nav_GetNodeEdge; + trap->Nav_GetNumNodes = trap_Nav_GetNumNodes; + trap->Nav_Connected = trap_Nav_Connected; + trap->Nav_GetPathCost = trap_Nav_GetPathCost; + trap->Nav_GetEdgeCost = trap_Nav_GetEdgeCost; + trap->Nav_GetProjectedNode = trap_Nav_GetProjectedNode; + trap->Nav_CheckFailedNodes = trap_Nav_CheckFailedNodes; + trap->Nav_AddFailedNode = trap_Nav_AddFailedNode; + trap->Nav_NodeFailed = trap_Nav_NodeFailed; + trap->Nav_NodesAreNeighbors = trap_Nav_NodesAreNeighbors; + trap->Nav_ClearFailedEdge = trap_Nav_ClearFailedEdge; + trap->Nav_ClearAllFailedEdges = trap_Nav_ClearAllFailedEdges; + trap->Nav_EdgeFailed = trap_Nav_EdgeFailed; + trap->Nav_AddFailedEdge = trap_Nav_AddFailedEdge; + trap->Nav_CheckFailedEdge = trap_Nav_CheckFailedEdge; + trap->Nav_CheckAllFailedEdges = trap_Nav_CheckAllFailedEdges; + trap->Nav_RouteBlocked = trap_Nav_RouteBlocked; + trap->Nav_GetBestNodeAltRoute = trap_Nav_GetBestNodeAltRoute; + trap->Nav_GetBestNodeAltRoute2 = trap_Nav_GetBestNodeAltRoute2; + trap->Nav_GetBestPathBetweenEnts = trap_Nav_GetBestPathBetweenEnts; + trap->Nav_GetNodeRadius = trap_Nav_GetNodeRadius; + trap->Nav_CheckBlockedEdges = trap_Nav_CheckBlockedEdges; + trap->Nav_ClearCheckedNodes = trap_Nav_ClearCheckedNodes; + trap->Nav_CheckedNode = trap_Nav_CheckedNode; + trap->Nav_SetCheckedNode = trap_Nav_SetCheckedNode; + trap->Nav_FlagAllNodes = trap_Nav_FlagAllNodes; + trap->Nav_GetPathsCalculated = trap_Nav_GetPathsCalculated; + trap->Nav_SetPathsCalculated = trap_Nav_SetPathsCalculated; + trap->BotAllocateClient = trap_BotAllocateClient; + trap->BotFreeClient = trap_BotFreeClient; + trap->BotLoadCharacter = trap_BotLoadCharacter; + trap->BotFreeCharacter = trap_BotFreeCharacter; + trap->Characteristic_Float = trap_Characteristic_Float; + trap->Characteristic_BFloat = trap_Characteristic_BFloat; + trap->Characteristic_Integer = trap_Characteristic_Integer; + trap->Characteristic_BInteger = trap_Characteristic_BInteger; + trap->Characteristic_String = trap_Characteristic_String; + trap->BotAllocChatState = trap_BotAllocChatState; + trap->BotFreeChatState = trap_BotFreeChatState; + trap->BotQueueConsoleMessage = trap_BotQueueConsoleMessage; + trap->BotRemoveConsoleMessage = trap_BotRemoveConsoleMessage; + trap->BotNextConsoleMessage = trap_BotNextConsoleMessage; + trap->BotNumConsoleMessages = trap_BotNumConsoleMessages; + trap->BotInitialChat = trap_BotInitialChat; + trap->BotReplyChat = trap_BotReplyChat; + trap->BotChatLength = trap_BotChatLength; + trap->BotEnterChat = trap_BotEnterChat; + trap->StringContains = trap_StringContains; + trap->BotFindMatch = trap_BotFindMatch; + trap->BotMatchVariable = trap_BotMatchVariable; + trap->UnifyWhiteSpaces = trap_UnifyWhiteSpaces; + trap->BotReplaceSynonyms = trap_BotReplaceSynonyms; + trap->BotLoadChatFile = trap_BotLoadChatFile; + trap->BotSetChatGender = trap_BotSetChatGender; + trap->BotSetChatName = trap_BotSetChatName; + trap->BotResetGoalState = trap_BotResetGoalState; + trap->BotResetAvoidGoals = trap_BotResetAvoidGoals; + trap->BotPushGoal = trap_BotPushGoal; + trap->BotPopGoal = trap_BotPopGoal; + trap->BotEmptyGoalStack = trap_BotEmptyGoalStack; + trap->BotDumpAvoidGoals = trap_BotDumpAvoidGoals; + trap->BotDumpGoalStack = trap_BotDumpGoalStack; + trap->BotGoalName = trap_BotGoalName; + trap->BotGetTopGoal = trap_BotGetTopGoal; + trap->BotGetSecondGoal = trap_BotGetSecondGoal; + trap->BotChooseLTGItem = trap_BotChooseLTGItem; + trap->BotChooseNBGItem = trap_BotChooseNBGItem; + trap->BotTouchingGoal = trap_BotTouchingGoal; + trap->BotItemGoalInVisButNotVisible = trap_BotItemGoalInVisButNotVisible; + trap->BotGetLevelItemGoal = trap_BotGetLevelItemGoal; + trap->BotAvoidGoalTime = trap_BotAvoidGoalTime; + trap->BotInitLevelItems = trap_BotInitLevelItems; + trap->BotUpdateEntityItems = trap_BotUpdateEntityItems; + trap->BotLoadItemWeights = trap_BotLoadItemWeights; + trap->BotFreeItemWeights = trap_BotFreeItemWeights; + trap->BotSaveGoalFuzzyLogic = trap_BotSaveGoalFuzzyLogic; + trap->BotAllocGoalState = trap_BotAllocGoalState; + trap->BotFreeGoalState = trap_BotFreeGoalState; + trap->BotResetMoveState = trap_BotResetMoveState; + trap->BotMoveToGoal = trap_BotMoveToGoal; + trap->BotMoveInDirection = trap_BotMoveInDirection; + trap->BotResetAvoidReach = trap_BotResetAvoidReach; + trap->BotResetLastAvoidReach = trap_BotResetLastAvoidReach; + trap->BotReachabilityArea = trap_BotReachabilityArea; + trap->BotMovementViewTarget = trap_BotMovementViewTarget; + trap->BotAllocMoveState = trap_BotAllocMoveState; + trap->BotFreeMoveState = trap_BotFreeMoveState; + trap->BotInitMoveState = trap_BotInitMoveState; + trap->BotChooseBestFightWeapon = trap_BotChooseBestFightWeapon; + trap->BotGetWeaponInfo = trap_BotGetWeaponInfo; + trap->BotLoadWeaponWeights = trap_BotLoadWeaponWeights; + trap->BotAllocWeaponState = trap_BotAllocWeaponState; + trap->BotFreeWeaponState = trap_BotFreeWeaponState; + trap->BotResetWeaponState = trap_BotResetWeaponState; + trap->GeneticParentsAndChildSelection = trap_GeneticParentsAndChildSelection; + trap->BotInterbreedGoalFuzzyLogic = trap_BotInterbreedGoalFuzzyLogic; + trap->BotMutateGoalFuzzyLogic = trap_BotMutateGoalFuzzyLogic; + trap->BotGetNextCampSpotGoal = trap_BotGetNextCampSpotGoal; + trap->BotGetMapLocationGoal = trap_BotGetMapLocationGoal; + trap->BotNumInitialChats = trap_BotNumInitialChats; + trap->BotGetChatMessage = trap_BotGetChatMessage; + trap->BotRemoveFromAvoidGoals = trap_BotRemoveFromAvoidGoals; + trap->BotPredictVisiblePosition = trap_BotPredictVisiblePosition; + trap->BotSetAvoidGoalTime = trap_BotSetAvoidGoalTime; + trap->BotAddAvoidSpot = trap_BotAddAvoidSpot; + trap->BotLibSetup = trap_BotLibSetup; + trap->BotLibShutdown = trap_BotLibShutdown; + trap->BotLibVarSet = trap_BotLibVarSet; + trap->BotLibVarGet = trap_BotLibVarGet; + trap->BotLibDefine = trap_BotLibDefine; + trap->BotLibStartFrame = trap_BotLibStartFrame; + trap->BotLibLoadMap = trap_BotLibLoadMap; + trap->BotLibUpdateEntity = trap_BotLibUpdateEntity; + trap->BotLibTest = trap_BotLibTest; + trap->BotGetSnapshotEntity = trap_BotGetSnapshotEntity; + trap->BotGetServerCommand = trap_BotGetServerCommand; + trap->BotUserCommand = trap_BotUserCommand; + trap->BotUpdateWaypoints = trap_Bot_UpdateWaypoints; + trap->BotCalculatePaths = trap_Bot_CalculatePaths; + trap->AAS_EnableRoutingArea = trap_AAS_EnableRoutingArea; + trap->AAS_BBoxAreas = trap_AAS_BBoxAreas; + trap->AAS_AreaInfo = trap_AAS_AreaInfo; + trap->AAS_EntityInfo = trap_AAS_EntityInfo; + trap->AAS_Initialized = trap_AAS_Initialized; + trap->AAS_PresenceTypeBoundingBox = trap_AAS_PresenceTypeBoundingBox; + trap->AAS_Time = trap_AAS_Time; + trap->AAS_PointAreaNum = trap_AAS_PointAreaNum; + trap->AAS_TraceAreas = trap_AAS_TraceAreas; + trap->AAS_PointContents = trap_AAS_PointContents; + trap->AAS_NextBSPEntity = trap_AAS_NextBSPEntity; + trap->AAS_ValueForBSPEpairKey = trap_AAS_ValueForBSPEpairKey; + trap->AAS_VectorForBSPEpairKey = trap_AAS_VectorForBSPEpairKey; + trap->AAS_FloatForBSPEpairKey = trap_AAS_FloatForBSPEpairKey; + trap->AAS_IntForBSPEpairKey = trap_AAS_IntForBSPEpairKey; + trap->AAS_AreaReachability = trap_AAS_AreaReachability; + trap->AAS_AreaTravelTimeToGoalArea = trap_AAS_AreaTravelTimeToGoalArea; + trap->AAS_Swimming = trap_AAS_Swimming; + trap->AAS_PredictClientMovement = trap_AAS_PredictClientMovement; + trap->AAS_AlternativeRouteGoals = trap_AAS_AlternativeRouteGoals; + trap->AAS_PredictRoute = trap_AAS_PredictRoute; + trap->AAS_PointReachabilityAreaIndex = trap_AAS_PointReachabilityAreaIndex; + trap->EA_Say = trap_EA_Say; + trap->EA_SayTeam = trap_EA_SayTeam; + trap->EA_Command = trap_EA_Command; + trap->EA_Action = trap_EA_Action; + trap->EA_Gesture = trap_EA_Gesture; + trap->EA_Talk = trap_EA_Talk; + trap->EA_Attack = trap_EA_Attack; + trap->EA_Alt_Attack = trap_EA_Alt_Attack; + trap->EA_ForcePower = trap_EA_ForcePower; + trap->EA_Use = trap_EA_Use; + trap->EA_Respawn = trap_EA_Respawn; + trap->EA_Crouch = trap_EA_Crouch; + trap->EA_MoveUp = trap_EA_MoveUp; + trap->EA_MoveDown = trap_EA_MoveDown; + trap->EA_MoveForward = trap_EA_MoveForward; + trap->EA_MoveBack = trap_EA_MoveBack; + trap->EA_MoveLeft = trap_EA_MoveLeft; + trap->EA_MoveRight = trap_EA_MoveRight; + trap->EA_SelectWeapon = trap_EA_SelectWeapon; + trap->EA_Jump = trap_EA_Jump; + trap->EA_DelayedJump = trap_EA_DelayedJump; + trap->EA_Move = trap_EA_Move; + trap->EA_View = trap_EA_View; + trap->EA_EndRegular = trap_EA_EndRegular; + trap->EA_GetInput = trap_EA_GetInput; + trap->EA_ResetInput = trap_EA_ResetInput; + trap->PC_LoadSource = trap_PC_LoadSource; + trap->PC_FreeSource = trap_PC_FreeSource; + trap->PC_ReadToken = trap_PC_ReadToken; + trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; + trap->R_RegisterSkin = trap_R_RegisterSkin; + trap->SetActiveSubBSP = trap_SetActiveSubBSP; + trap->CM_RegisterTerrain = trap_CM_RegisterTerrain; + trap->RMG_Init = trap_RMG_Init; + trap->G2API_ListModelBones = trap_G2_ListModelBones; + trap->G2API_ListModelSurfaces = trap_G2_ListModelSurfaces; + trap->G2API_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; + trap->G2API_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; + trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; + trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; + trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; + trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; + trap->G2API_SetSkin = trap_G2API_SetSkin; + trap->G2API_Ghoul2Size = trap_G2API_Ghoul2Size; + trap->G2API_AddBolt = trap_G2API_AddBolt; + trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; + trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; + trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; + trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; + trap->G2API_GetGLAName = trap_G2API_GetGLAName; + trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; + trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; + trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; + trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; + trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; + trap->G2API_RemoveGhoul2Models = trap_G2API_RemoveGhoul2Models; + trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; + trap->G2API_CollisionDetect = trap_G2API_CollisionDetect; + trap->G2API_CollisionDetectCache = trap_G2API_CollisionDetectCache; + trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; + trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; + trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; + trap->G2API_DoesBoneExist = trap_G2API_DoesBoneExist; + trap->G2API_GetSurfaceRenderStatus = trap_G2API_GetSurfaceRenderStatus; + trap->G2API_AbsurdSmoothing = trap_G2API_AbsurdSmoothing; + trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; + trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; + trap->G2API_RagPCJConstraint = trap_G2API_RagPCJConstraint; + trap->G2API_RagPCJGradientSpeed = trap_G2API_RagPCJGradientSpeed; + trap->G2API_RagEffectorGoal = trap_G2API_RagEffectorGoal; + trap->G2API_GetRagBonePos = trap_G2API_GetRagBonePos; + trap->G2API_RagEffectorKick = trap_G2API_RagEffectorKick; + trap->G2API_RagForceSolve = trap_G2API_RagForceSolve; + trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; + trap->G2API_IKMove = trap_G2API_IKMove; + trap->G2API_RemoveBone = trap_G2API_RemoveBone; + trap->G2API_AttachInstanceToEntNum = trap_G2API_AttachInstanceToEntNum; + trap->G2API_ClearAttachedInstance = trap_G2API_ClearAttachedInstance; + trap->G2API_CleanEntAttachments = trap_G2API_CleanEntAttachments; + trap->G2API_OverrideServer = trap_G2API_OverrideServer; + trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; } diff --git a/codemp/game/g_target.c b/codemp/game/g_target.c index 84aeb0fe0f..1dbad958a7 100644 --- a/codemp/game/g_target.c +++ b/codemp/game/g_target.c @@ -28,36 +28,33 @@ along with this program; if not, see . /*QUAKED target_give (1 0 0) (-8 -8 -8) (8 8 8) Gives the activator all the items pointed to. */ -void Use_Target_Give( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - gentity_t *t; - trace_t trace; +void Use_Target_Give(gentity_t *ent, gentity_t *other, gentity_t *activator) { + gentity_t *t; + trace_t trace; - if ( !activator->client ) { + if (!activator->client) { return; } - if ( !ent->target ) { + if (!ent->target) { return; } - memset( &trace, 0, sizeof( trace ) ); + memset(&trace, 0, sizeof(trace)); t = NULL; - while ( (t = G_Find (t, FOFS(targetname), ent->target)) != NULL ) { - if ( !t->item ) { + while ((t = G_Find(t, FOFS(targetname), ent->target)) != NULL) { + if (!t->item) { continue; } - Touch_Item( t, activator, &trace ); + Touch_Item(t, activator, &trace); // make sure it isn't going to respawn or show any events t->nextthink = 0; - trap->UnlinkEntity( (sharedEntity_t *)t ); + trap->UnlinkEntity((sharedEntity_t *)t); } } -void SP_target_give( gentity_t *ent ) { - ent->use = Use_Target_Give; -} - +void SP_target_give(gentity_t *ent) { ent->use = Use_Target_Give; } //========================================================== @@ -65,26 +62,23 @@ void SP_target_give( gentity_t *ent ) { takes away all the activators powerups. Used to drop flight powerups into death puts. */ -void Use_target_remove_powerups( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - if( !activator->client ) { +void Use_target_remove_powerups(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (!activator->client) { return; } - if( activator->client->ps.powerups[PW_REDFLAG] ) { - Team_ReturnFlag( TEAM_RED ); - } else if( activator->client->ps.powerups[PW_BLUEFLAG] ) { - Team_ReturnFlag( TEAM_BLUE ); - } else if( activator->client->ps.powerups[PW_NEUTRALFLAG] ) { - Team_ReturnFlag( TEAM_FREE ); + if (activator->client->ps.powerups[PW_REDFLAG]) { + Team_ReturnFlag(TEAM_RED); + } else if (activator->client->ps.powerups[PW_BLUEFLAG]) { + Team_ReturnFlag(TEAM_BLUE); + } else if (activator->client->ps.powerups[PW_NEUTRALFLAG]) { + Team_ReturnFlag(TEAM_FREE); } - memset( activator->client->ps.powerups, 0, sizeof( activator->client->ps.powerups ) ); -} - -void SP_target_remove_powerups( gentity_t *ent ) { - ent->use = Use_target_remove_powerups; + memset(activator->client->ps.powerups, 0, sizeof(activator->client->ps.powerups)); } +void SP_target_remove_powerups(gentity_t *ent) { ent->use = Use_target_remove_powerups; } //========================================================== @@ -96,34 +90,30 @@ activated again while it is counting down to an event. "wait" seconds to pause before firing targets. "random" delay variance, total delay = delay +/- random seconds */ -void Think_Target_Delay( gentity_t *ent ) { - G_UseTargets( ent, ent->activator ); -} +void Think_Target_Delay(gentity_t *ent) { G_UseTargets(ent, ent->activator); } -void Use_Target_Delay( gentity_t *ent, gentity_t *other, gentity_t *activator ) { - if (ent->nextthink > level.time && (ent->spawnflags & 1)) - { //Leave me alone, I am thinking. +void Use_Target_Delay(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (ent->nextthink > level.time && (ent->spawnflags & 1)) { // Leave me alone, I am thinking. return; } - G_ActivateBehavior(ent,BSET_USE); - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + G_ActivateBehavior(ent, BSET_USE); + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->think = Think_Target_Delay; ent->activator = activator; } -void SP_target_delay( gentity_t *ent ) { +void SP_target_delay(gentity_t *ent) { // check delay for backwards compatability - if ( !G_SpawnFloat( "delay", "0", &ent->wait ) ) { - G_SpawnFloat( "wait", "1", &ent->wait ); + if (!G_SpawnFloat("delay", "0", &ent->wait)) { + G_SpawnFloat("wait", "1", &ent->wait); } - if ( !ent->wait ) { + if (!ent->wait) { ent->wait = 1; } ent->use = Use_Target_Delay; } - //========================================================== /*QUAKED target_score (1 0 0) (-8 -8 -8) (8 8 8) @@ -131,18 +121,15 @@ void SP_target_delay( gentity_t *ent ) { The activator is given this many points. */ -void Use_Target_Score (gentity_t *ent, gentity_t *other, gentity_t *activator) { - AddScore( activator, ent->r.currentOrigin, ent->count ); -} +void Use_Target_Score(gentity_t *ent, gentity_t *other, gentity_t *activator) { AddScore(activator, ent->r.currentOrigin, ent->count); } -void SP_target_score( gentity_t *ent ) { - if ( !ent->count ) { +void SP_target_score(gentity_t *ent) { + if (!ent->count) { ent->count = 1; } ent->use = Use_Target_Score; } - //========================================================== /*QUAKED target_print (1 0 0) (-8 -8 -8) (8 8 8) redteam blueteam private @@ -150,52 +137,40 @@ void SP_target_score( gentity_t *ent ) { "wait" don't fire off again if triggered within this many milliseconds ago If "private", only the activator gets the message. If no checks, all clients get the message. */ -void Use_Target_Print (gentity_t *ent, gentity_t *other, gentity_t *activator) -{ - if (!ent || !ent->inuse) - { +void Use_Target_Print(gentity_t *ent, gentity_t *other, gentity_t *activator) { + if (!ent || !ent->inuse) { Com_Printf("ERROR: Bad ent in Use_Target_Print"); return; } - if (ent->wait) - { - if (ent->genericValue14 >= level.time) - { + if (ent->wait) { + if (ent->genericValue14 >= level.time) { return; } ent->genericValue14 = level.time + ent->wait; } #ifndef FINAL_BUILD - if (!ent || !ent->inuse) - { - // Com_Error(ERR_DROP, "Bad ent in Use_Target_Print"); + if (!ent || !ent->inuse) { + // Com_Error(ERR_DROP, "Bad ent in Use_Target_Print"); return; - } - else if (!activator || !activator->inuse) - { - // Com_Error(ERR_DROP, "Bad activator in Use_Target_Print"); + } else if (!activator || !activator->inuse) { + // Com_Error(ERR_DROP, "Bad activator in Use_Target_Print"); return; } - if (ent->genericValue15 > level.time) - { + if (ent->genericValue15 > level.time) { Com_Printf("TARGET PRINT ERRORS:\n"); - if (activator && activator->classname && activator->classname[0]) - { + if (activator && activator->classname && activator->classname[0]) { Com_Printf("activator classname: %s\n", activator->classname); } - if (activator && activator->target && activator->target[0]) - { + if (activator && activator->target && activator->target[0]) { Com_Printf("activator target: %s\n", activator->target); } - if (activator && activator->targetname && activator->targetname[0]) - { + if (activator && activator->targetname && activator->targetname[0]) { Com_Printf("activator targetname: %s\n", activator->targetname); } - if (ent->targetname && ent->targetname[0]) - { + if (ent->targetname && ent->targetname[0]) { Com_Printf("print targetname: %s\n", ent->targetname); } Com_Error(ERR_DROP, "target_print used in quick succession, fix it! See the console for details."); @@ -203,70 +178,51 @@ void Use_Target_Print (gentity_t *ent, gentity_t *other, gentity_t *activator) ent->genericValue15 = level.time + 5000; #endif - G_ActivateBehavior(ent,BSET_USE); - if ( ( ent->spawnflags & 4 ) ) - {//private, to one client only - if (!activator || !activator->inuse) - { + G_ActivateBehavior(ent, BSET_USE); + if ((ent->spawnflags & 4)) { // private, to one client only + if (!activator || !activator->inuse) { Com_Printf("ERROR: Bad activator in Use_Target_Print"); } - if ( activator && activator->client ) - {//make sure there's a valid client ent to send it to - if (ent->message[0] == '@' && ent->message[1] != '@') - { - trap->SendServerCommand( activator-g_entities, va("cps \"%s\"", ent->message )); - } - else - { - trap->SendServerCommand( activator-g_entities, va("cp \"%s\"", ent->message )); + if (activator && activator->client) { // make sure there's a valid client ent to send it to + if (ent->message[0] == '@' && ent->message[1] != '@') { + trap->SendServerCommand(activator - g_entities, va("cps \"%s\"", ent->message)); + } else { + trap->SendServerCommand(activator - g_entities, va("cp \"%s\"", ent->message)); } } - //NOTE: change in functionality - if there *is* no valid client ent, it won't send it to anyone at all + // NOTE: change in functionality - if there *is* no valid client ent, it won't send it to anyone at all return; } - if ( ent->spawnflags & 3 ) { - if ( ent->spawnflags & 1 ) { - if (ent->message[0] == '@' && ent->message[1] != '@') - { - G_TeamCommand( TEAM_RED, va("cps \"%s\"", ent->message) ); - } - else - { - G_TeamCommand( TEAM_RED, va("cp \"%s\"", ent->message) ); + if (ent->spawnflags & 3) { + if (ent->spawnflags & 1) { + if (ent->message[0] == '@' && ent->message[1] != '@') { + G_TeamCommand(TEAM_RED, va("cps \"%s\"", ent->message)); + } else { + G_TeamCommand(TEAM_RED, va("cp \"%s\"", ent->message)); } } - if ( ent->spawnflags & 2 ) { - if (ent->message[0] == '@' && ent->message[1] != '@') - { - G_TeamCommand( TEAM_BLUE, va("cps \"%s\"", ent->message) ); - } - else - { - G_TeamCommand( TEAM_BLUE, va("cp \"%s\"", ent->message) ); + if (ent->spawnflags & 2) { + if (ent->message[0] == '@' && ent->message[1] != '@') { + G_TeamCommand(TEAM_BLUE, va("cps \"%s\"", ent->message)); + } else { + G_TeamCommand(TEAM_BLUE, va("cp \"%s\"", ent->message)); } } return; } - if (ent->message[0] == '@' && ent->message[1] != '@') - { - trap->SendServerCommand( -1, va("cps \"%s\"", ent->message )); - } - else - { - trap->SendServerCommand( -1, va("cp \"%s\"", ent->message )); + if (ent->message[0] == '@' && ent->message[1] != '@') { + trap->SendServerCommand(-1, va("cps \"%s\"", ent->message)); + } else { + trap->SendServerCommand(-1, va("cp \"%s\"", ent->message)); } } -void SP_target_print( gentity_t *ent ) { - ent->use = Use_Target_Print; -} - +void SP_target_print(gentity_t *ent) { ent->use = Use_Target_Print; } //========================================================== - /*QUAKED target_speaker (1 0 0) (-8 -8 -8) (8 8 8) looped-on looped-off global activator "noise" wav file to play @@ -279,60 +235,56 @@ Multiple identical looping sounds will just increase volume without any speed co "wait" : Seconds between auto triggerings, 0 = don't auto trigger "random" wait variance, default is 0 */ -void Use_Target_Speaker (gentity_t *ent, gentity_t *other, gentity_t *activator) { - G_ActivateBehavior(ent,BSET_USE); +void Use_Target_Speaker(gentity_t *ent, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(ent, BSET_USE); - if (ent->spawnflags & 3) { // looping sound toggles - if (ent->s.loopSound) - { - ent->s.loopSound = 0; // turn it off + if (ent->spawnflags & 3) { // looping sound toggles + if (ent->s.loopSound) { + ent->s.loopSound = 0; // turn it off ent->s.loopIsSoundset = qfalse; ent->s.trickedentindex = 1; - } - else - { - ent->s.loopSound = ent->noise_index; // start it + } else { + ent->s.loopSound = ent->noise_index; // start it ent->s.loopIsSoundset = qfalse; ent->s.trickedentindex = 0; } - }else { // normal sound - if ( ent->spawnflags & 8 ) { - G_AddEvent( activator, EV_GENERAL_SOUND, ent->noise_index ); + } else { // normal sound + if (ent->spawnflags & 8) { + G_AddEvent(activator, EV_GENERAL_SOUND, ent->noise_index); } else if (ent->spawnflags & 4) { - G_AddEvent( ent, EV_GLOBAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GLOBAL_SOUND, ent->noise_index); } else { - G_AddEvent( ent, EV_GENERAL_SOUND, ent->noise_index ); + G_AddEvent(ent, EV_GENERAL_SOUND, ent->noise_index); } } } -void SP_target_speaker( gentity_t *ent ) { - char buffer[MAX_QPATH]; - char *s; +void SP_target_speaker(gentity_t *ent) { + char buffer[MAX_QPATH]; + char *s; - G_SpawnFloat( "wait", "0", &ent->wait ); - G_SpawnFloat( "random", "0", &ent->random ); + G_SpawnFloat("wait", "0", &ent->wait); + G_SpawnFloat("random", "0", &ent->random); - if ( G_SpawnString ( "soundSet", "", &s ) ) - { // this is a sound set + if (G_SpawnString("soundSet", "", &s)) { // this is a sound set ent->s.soundSetIndex = G_SoundSetIndex(s); ent->s.eFlags = EF_PERMANENT; - VectorCopy( ent->s.origin, ent->s.pos.trBase ); - trap->LinkEntity ((sharedEntity_t *)ent); + VectorCopy(ent->s.origin, ent->s.pos.trBase); + trap->LinkEntity((sharedEntity_t *)ent); return; } - if ( !G_SpawnString( "noise", "NOSOUND", &s ) ) { - trap->Error( ERR_DROP, "target_speaker without a noise key at %s", vtos( ent->s.origin ) ); + if (!G_SpawnString("noise", "NOSOUND", &s)) { + trap->Error(ERR_DROP, "target_speaker without a noise key at %s", vtos(ent->s.origin)); } // force all client reletive sounds to be "activator" speakers that // play on the entity that activates it - if ( s[0] == '*' ) { + if (s[0] == '*') { ent->spawnflags |= 8; } - Q_strncpyz( buffer, s, sizeof(buffer) ); + Q_strncpyz(buffer, s, sizeof(buffer)); ent->noise_index = G_SoundIndex(buffer); @@ -342,9 +294,8 @@ void SP_target_speaker( gentity_t *ent ) { ent->s.frame = ent->wait * 10; ent->s.clientNum = ent->random * 10; - // check for prestarted looping sound - if ( ent->spawnflags & 1 ) { + if (ent->spawnflags & 1) { ent->s.loopSound = ent->noise_index; ent->s.loopIsSoundset = qfalse; } @@ -355,132 +306,123 @@ void SP_target_speaker( gentity_t *ent ) { ent->r.svFlags |= SVF_BROADCAST; } - VectorCopy( ent->s.origin, ent->s.pos.trBase ); + VectorCopy(ent->s.origin, ent->s.pos.trBase); // must link the entity so we get areas and clusters so // the server can determine who to send updates to - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } - - //========================================================== /*QUAKED target_laser (0 .5 .8) (-8 -8 -8) (8 8 8) START_ON When triggered, fires a laser. You can either set a target or a direction. */ -void target_laser_think (gentity_t *self) { - vec3_t end; - trace_t tr; - vec3_t point; +void target_laser_think(gentity_t *self) { + vec3_t end; + trace_t tr; + vec3_t point; // if pointed at another entity, set movedir to point at it - if ( self->enemy ) { - VectorMA (self->enemy->s.origin, 0.5, self->enemy->r.mins, point); - VectorMA (point, 0.5, self->enemy->r.maxs, point); - VectorSubtract (point, self->s.origin, self->movedir); - VectorNormalize (self->movedir); + if (self->enemy) { + VectorMA(self->enemy->s.origin, 0.5, self->enemy->r.mins, point); + VectorMA(point, 0.5, self->enemy->r.maxs, point); + VectorSubtract(point, self->s.origin, self->movedir); + VectorNormalize(self->movedir); } // fire forward and see what we hit - VectorMA (self->s.origin, 2048, self->movedir, end); + VectorMA(self->s.origin, 2048, self->movedir, end); - trap->Trace( &tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_CORPSE, qfalse, 0, 0); + trap->Trace(&tr, self->s.origin, NULL, NULL, end, self->s.number, CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_CORPSE, qfalse, 0, 0); - if ( tr.entityNum ) { + if (tr.entityNum) { // hurt it if we can - G_Damage ( &g_entities[tr.entityNum], self, self->activator, self->movedir, - tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_TARGET_LASER); + G_Damage(&g_entities[tr.entityNum], self, self->activator, self->movedir, tr.endpos, self->damage, DAMAGE_NO_KNOCKBACK, MOD_TARGET_LASER); } - VectorCopy (tr.endpos, self->s.origin2); + VectorCopy(tr.endpos, self->s.origin2); - trap->LinkEntity( (sharedEntity_t *)self ); + trap->LinkEntity((sharedEntity_t *)self); self->nextthink = level.time + FRAMETIME; } -void target_laser_on (gentity_t *self) -{ +void target_laser_on(gentity_t *self) { if (!self->activator) self->activator = self; - target_laser_think (self); + target_laser_think(self); } -void target_laser_off (gentity_t *self) -{ - trap->UnlinkEntity( (sharedEntity_t *)self ); +void target_laser_off(gentity_t *self) { + trap->UnlinkEntity((sharedEntity_t *)self); self->nextthink = 0; } -void target_laser_use (gentity_t *self, gentity_t *other, gentity_t *activator) -{ +void target_laser_use(gentity_t *self, gentity_t *other, gentity_t *activator) { self->activator = activator; - if ( self->nextthink > 0 ) - target_laser_off (self); + if (self->nextthink > 0) + target_laser_off(self); else - target_laser_on (self); + target_laser_on(self); } -void target_laser_start (gentity_t *self) -{ +void target_laser_start(gentity_t *self) { gentity_t *ent; self->s.eType = ET_BEAM; if (self->target) { - ent = G_Find (NULL, FOFS(targetname), self->target); + ent = G_Find(NULL, FOFS(targetname), self->target); if (!ent) { - trap->Print ("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); + trap->Print("%s at %s: %s is a bad target\n", self->classname, vtos(self->s.origin), self->target); } self->enemy = ent; } else { - G_SetMovedir (self->s.angles, self->movedir); + G_SetMovedir(self->s.angles, self->movedir); } self->use = target_laser_use; self->think = target_laser_think; - if ( !self->damage ) { + if (!self->damage) { self->damage = 1; } if (self->spawnflags & 1) - target_laser_on (self); + target_laser_on(self); else - target_laser_off (self); + target_laser_off(self); } -void SP_target_laser (gentity_t *self) -{ +void SP_target_laser(gentity_t *self) { // let everything else get spawned before we start firing self->think = target_laser_start; self->nextthink = level.time + FRAMETIME; } - //========================================================== -void target_teleporter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { - gentity_t *dest; +void target_teleporter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + gentity_t *dest; if (!activator->client) return; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - trap->Print ("Couldn't find teleporter destination\n"); + trap->Print("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( activator, dest->s.origin, dest->s.angles ); + TeleportPlayer(activator, dest->s.origin, dest->s.angles); } /*QUAKED target_teleporter (1 0 0) (-8 -8 -8) (8 8 8) The activator will be teleported away. */ -void SP_target_teleporter( gentity_t *self ) { +void SP_target_teleporter(gentity_t *self) { if (!self->targetname) trap->Print("untargeted %s at %s\n", self->classname, vtos(self->s.origin)); @@ -489,7 +431,6 @@ void SP_target_teleporter( gentity_t *self ) { //========================================================== - /*QUAKED target_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) RED_ONLY BLUE_ONLY RANDOM x x x x INACTIVE This doesn't perform any actions except fire its targets. The activator can be forced to be from a certain team. @@ -499,75 +440,64 @@ if RANDOM is checked, only one of the targets will be fired, not all of them wait - set to -1 to use it only once */ -void target_relay_use (gentity_t *self, gentity_t *other, gentity_t *activator) { +void target_relay_use(gentity_t *self, gentity_t *other, gentity_t *activator) { qboolean ranscript = qfalse; - if ( ( self->spawnflags & 1 ) && activator->client - && activator->client->sess.sessionTeam != TEAM_RED ) { + if ((self->spawnflags & 1) && activator->client && activator->client->sess.sessionTeam != TEAM_RED) { return; } - if ( ( self->spawnflags & 2 ) && activator->client - && activator->client->sess.sessionTeam != TEAM_BLUE ) { + if ((self->spawnflags & 2) && activator->client && activator->client->sess.sessionTeam != TEAM_BLUE) { return; } - if ( self->flags & FL_INACTIVE ) - {//set by target_deactivate + if (self->flags & FL_INACTIVE) { // set by target_deactivate return; } - ranscript = G_ActivateBehavior( self, BSET_USE ); - if ( self->wait == -1 ) - {//never use again - if ( ranscript ) - {//crap, can't remove! + ranscript = G_ActivateBehavior(self, BSET_USE); + if (self->wait == -1) { // never use again + if (ranscript) { // crap, can't remove! self->use = NULL; - } - else - {//remove + } else { // remove self->think = G_FreeEntity; self->nextthink = level.time + FRAMETIME; } } - if ( self->spawnflags & 4 ) { - gentity_t *ent; + if (self->spawnflags & 4) { + gentity_t *ent; - ent = G_PickTarget( self->target ); - if ( ent && ent->use ) { - GlobalUse( ent, self, activator ); + ent = G_PickTarget(self->target); + if (ent && ent->use) { + GlobalUse(ent, self, activator); } return; } - G_UseTargets (self, activator); + G_UseTargets(self, activator); } -void SP_target_relay (gentity_t *self) { +void SP_target_relay(gentity_t *self) { self->use = target_relay_use; - if ( self->spawnflags&128 ) - { + if (self->spawnflags & 128) { self->flags |= FL_INACTIVE; } } - //========================================================== /*QUAKED target_kill (.5 .5 .5) (-8 -8 -8) (8 8 8) Kills the activator. */ -void target_kill_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { - G_ActivateBehavior(self,BSET_USE); - G_Damage ( activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); +void target_kill_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + G_Damage(activator, NULL, NULL, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); } -void SP_target_kill( gentity_t *self ) { - self->use = target_kill_use; -} +void SP_target_kill(gentity_t *self) { self->use = target_kill_use; } /*QUAKED target_position (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for in-game calculation, like jumppad targets. */ -void SP_target_position( gentity_t *self ){ - G_SetOrigin( self, self->s.origin ); +void SP_target_position(gentity_t *self) { + G_SetOrigin(self, self->s.origin); /* G_SetAngles( self, self->s.angles ); self->s.eType = ET_INVISIBLE; @@ -582,35 +512,34 @@ Set "count" to 0-7 for color. Closest target_location in sight used for the location, if none in site, closest in distance */ -void SP_target_location( gentity_t *self ) { - if ( self->targetname && self->targetname[0] ) { - SP_target_position( self ); +void SP_target_location(gentity_t *self) { + if (self->targetname && self->targetname[0]) { + SP_target_position(self); return; - } - else { + } else { static qboolean didwarn = qfalse; - if ( !self->message ) { - trap->Print( "target_location with no message at %s\n", vtos( self->s.origin ) ); - G_FreeEntity( self ); + if (!self->message) { + trap->Print("target_location with no message at %s\n", vtos(self->s.origin)); + G_FreeEntity(self); return; } - if ( level.locations.num >= MAX_LOCATIONS ) { - if ( !didwarn ) { - trap->Print( "Maximum target_locations hit (%d)! Remaining locations will be removed.\n", MAX_LOCATIONS ); + if (level.locations.num >= MAX_LOCATIONS) { + if (!didwarn) { + trap->Print("Maximum target_locations hit (%d)! Remaining locations will be removed.\n", MAX_LOCATIONS); didwarn = qtrue; } - G_FreeEntity( self ); + G_FreeEntity(self); return; } - VectorCopy( self->s.origin, level.locations.data[level.locations.num].origin ); - Q_strncpyz( level.locations.data[level.locations.num].message, self->message, sizeof( level.locations.data[level.locations.num].message ) ); - level.locations.data[level.locations.num].count = Com_Clampi( 0, 7, self->count ); + VectorCopy(self->s.origin, level.locations.data[level.locations.num].origin); + Q_strncpyz(level.locations.data[level.locations.num].message, self->message, sizeof(level.locations.data[level.locations.num].message)); + level.locations.data[level.locations.num].count = Com_Clampi(0, 7, self->count); level.locations.num++; - G_FreeEntity( self ); + G_FreeEntity(self); } } @@ -625,65 +554,55 @@ After the counter has been triggered "count" times (default 2), it will fire all bounceCount - number of times the counter should reset to it's full count when it's done */ -extern void G_DebugPrint( int level, const char *format, ... ); -void target_counter_use( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - if ( self->count == 0 ) - { +extern void G_DebugPrint(int level, const char *format, ...); +void target_counter_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->count == 0) { return; } - //trap->Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + // trap->Printf("target_counter %s used by %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); self->count--; - if ( activator ) - { - G_DebugPrint( WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, (self->genericValue1-self->count), self->genericValue1 ); + if (activator) { + G_DebugPrint(WL_VERBOSE, "target_counter %s used by %s (%d/%d)\n", self->targetname, activator->targetname, (self->genericValue1 - self->count), + self->genericValue1); } - if ( self->count ) - { - if ( self->target2 ) - { - //trap->Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); - G_UseTargets2( self, activator, self->target2 ); + if (self->count) { + if (self->target2) { + // trap->Printf("target_counter %s firing target2 from %s, entnum %d\n", self->targetname, activator->targetname, activator->s.number ); + G_UseTargets2(self, activator, self->target2); } return; } - G_ActivateBehavior( self,BSET_USE ); + G_ActivateBehavior(self, BSET_USE); - if ( self->spawnflags & 128 ) - { + if (self->spawnflags & 128) { self->flags |= FL_INACTIVE; } self->activator = activator; - G_UseTargets( self, activator ); + G_UseTargets(self, activator); - if ( self->count == 0 ) - { - if ( self->bounceCount == 0 ) - { + if (self->count == 0) { + if (self->bounceCount == 0) { return; } self->count = self->genericValue1; - if ( self->bounceCount > 0 ) - {//-1 means bounce back forever + if (self->bounceCount > 0) { //-1 means bounce back forever self->bounceCount--; } } } -void SP_target_counter (gentity_t *self) -{ +void SP_target_counter(gentity_t *self) { self->wait = -1; - if (!self->count) - { + if (!self->count) { self->count = 2; } - //if ( self->bounceCount > 0 )//let's always set this anyway - {//we will reset when we use up our count, remember our initial count + // if ( self->bounceCount > 0 )//let's always set this anyway + { // we will reset when we use up our count, remember our initial count self->genericValue1 = self->count; } @@ -696,81 +615,63 @@ Randomly fires off only one of it's targets each time used USEONCE set to never fire again */ -void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - int t_count = 0, pick; - gentity_t *t = NULL; +void target_random_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + int t_count = 0, pick; + gentity_t *t = NULL; - //trap->Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); - G_ActivateBehavior(self,BSET_USE); + // trap->Printf("target_random %s used by %s (entnum %d)\n", self->targetname, activator->targetname, activator->s.number ); + G_ActivateBehavior(self, BSET_USE); - if(self->spawnflags & 1) - { + if (self->spawnflags & 1) { self->use = 0; } - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; } } - if(!t_count) - { + if (!t_count) { return; } - if(t_count == 1) - { - G_UseTargets (self, activator); + if (t_count == 1) { + G_UseTargets(self, activator); return; } - //FIXME: need a seed + // FIXME: need a seed pick = Q_irand(1, t_count); t_count = 0; - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; - } - else - { + } else { continue; } - if (t == self) - { -// trap->Printf ("WARNING: Entity used itself.\n"); - } - else if(t_count == pick) - { - if (t->use != NULL) // check can be omitted + if (t == self) { + // trap->Printf ("WARNING: Entity used itself.\n"); + } else if (t_count == pick) { + if (t->use != NULL) // check can be omitted { GlobalUse(t, self, activator); return; } } - if (!self->inuse) - { + if (!self->inuse) { Com_Printf("entity was removed while using targets\n"); return; } } } -void SP_target_random (gentity_t *self) -{ - self->use = target_random_use; -} +void SP_target_random(gentity_t *self) { self->use = target_random_use; } -int numNewICARUSEnts = 0; -void scriptrunner_run (gentity_t *self) -{ +int numNewICARUSEnts = 0; +void scriptrunner_run(gentity_t *self) { /* if (self->behaviorSet[BSET_USE]) { @@ -782,95 +683,71 @@ void scriptrunner_run (gentity_t *self) } */ - if ( self->count != -1 ) - { - if ( self->count <= 0 ) - { + if (self->count != -1) { + if (self->count <= 0) { self->use = 0; self->behaviorSet[BSET_USE] = NULL; return; - } - else - { + } else { --self->count; } } - if (self->behaviorSet[BSET_USE]) - { - if ( self->spawnflags & 1 ) - { - if ( !self->activator ) - { - if (developer.integer) - { + if (self->behaviorSet[BSET_USE]) { + if (self->spawnflags & 1) { + if (!self->activator) { + if (developer.integer) { Com_Printf("target_scriptrunner tried to run on invalid entity!\n"); } return; } - //if ( !self->activator->sequencer || !self->activator->taskManager ) - if (!trap->ICARUS_IsInitialized(self->s.number)) - {//Need to be initialized through ICARUS - if ( !self->activator->script_targetname || !self->activator->script_targetname[0] ) - { - //We don't have a script_targetname, so create a new one - self->activator->script_targetname = va( "newICARUSEnt%d", numNewICARUSEnts++ ); + // if ( !self->activator->sequencer || !self->activator->taskManager ) + if (!trap->ICARUS_IsInitialized(self->s.number)) { // Need to be initialized through ICARUS + if (!self->activator->script_targetname || !self->activator->script_targetname[0]) { + // We don't have a script_targetname, so create a new one + self->activator->script_targetname = va("newICARUSEnt%d", numNewICARUSEnts++); } - if ( trap->ICARUS_ValidEnt( (sharedEntity_t *)self->activator ) ) - { - trap->ICARUS_InitEnt( (sharedEntity_t *)self->activator ); - } - else - { - if (developer.integer) - { + if (trap->ICARUS_ValidEnt((sharedEntity_t *)self->activator)) { + trap->ICARUS_InitEnt((sharedEntity_t *)self->activator); + } else { + if (developer.integer) { Com_Printf("target_scriptrunner tried to run on invalid ICARUS activator!\n"); } return; } } - if (developer.integer) - { - Com_Printf( "target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], self->activator->targetname ); + if (developer.integer) { + Com_Printf("target_scriptrunner running %s on activator %s\n", self->behaviorSet[BSET_USE], self->activator->targetname); } - trap->ICARUS_RunScript( (sharedEntity_t *)self->activator, va( "%s/%s", Q3_SCRIPT_DIR, self->behaviorSet[BSET_USE] ) ); - } - else - { - if ( developer.integer && self->activator ) - { - Com_Printf( "target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname ); + trap->ICARUS_RunScript((sharedEntity_t *)self->activator, va("%s/%s", Q3_SCRIPT_DIR, self->behaviorSet[BSET_USE])); + } else { + if (developer.integer && self->activator) { + Com_Printf("target_scriptrunner %s used by %s\n", self->targetname, self->activator->targetname); } - G_ActivateBehavior( self, BSET_USE ); + G_ActivateBehavior(self, BSET_USE); } } - if ( self->wait ) - { + if (self->wait) { self->nextthink = level.time + self->wait; } } -void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if ( self->nextthink > level.time ) - { +void target_scriptrunner_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (self->nextthink > level.time) { return; } self->activator = activator; self->enemy = other; - if ( self->delay ) - {//delay before firing scriptrunner + if (self->delay) { // delay before firing scriptrunner self->think = scriptrunner_run; self->nextthink = level.time + self->delay; - } - else - { - scriptrunner_run (self); + } else { + scriptrunner_run(self); } } @@ -886,17 +763,14 @@ wait - can't be used again in this amount of seconds (Default is 1 second if it' delay - how long to wait after use to run script */ -void SP_target_scriptrunner( gentity_t *self ) -{ +void SP_target_scriptrunner(gentity_t *self) { float v; - if ( self->spawnflags & 128 ) - { + if (self->spawnflags & 128) { self->flags |= FL_INACTIVE; } - if ( !self->count ) - { - self->count = 1;//default 1 use only + if (!self->count) { + self->count = 1; // default 1 use only } /* else if ( !self->wait ) @@ -904,65 +778,59 @@ void SP_target_scriptrunner( gentity_t *self ) self->wait = 1;//default wait of 1 sec } */ - // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be able to set less than a second delays - // no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next project + // FIXME: this is a hack... because delay is read in as an int, so I'm bypassing that because it's too late in the project to change it and I want to be + // able to set less than a second delays no one should be setting a radius on a scriptrunner, if they are this would be bad, take this out for the next + // project v = 0.0f; - G_SpawnFloat( "delay", "0", &v ); - self->delay = v * 1000;//sec to ms - self->wait *= 1000;//sec to ms + G_SpawnFloat("delay", "0", &v); + self->delay = v * 1000; // sec to ms + self->wait *= 1000; // sec to ms - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->use = target_scriptrunner_use; } -void G_SetActiveState(char *targetstring, qboolean actState) -{ - gentity_t *target = NULL; - while( NULL != (target = G_Find(target, FOFS(targetname), targetstring)) ) - { - target->flags = actState ? (target->flags&~FL_INACTIVE) : (target->flags|FL_INACTIVE); +void G_SetActiveState(char *targetstring, qboolean actState) { + gentity_t *target = NULL; + while (NULL != (target = G_Find(target, FOFS(targetname), targetstring))) { + target->flags = actState ? (target->flags & ~FL_INACTIVE) : (target->flags | FL_INACTIVE); } } -#define ACT_ACTIVE qtrue -#define ACT_INACTIVE qfalse +#define ACT_ACTIVE qtrue +#define ACT_INACTIVE qfalse -void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_activate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_ACTIVE); } -void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_deactivate_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); G_SetActiveState(self->target, ACT_INACTIVE); } -//FIXME: make these apply to doors, etc too? +// FIXME: make these apply to doors, etc too? /*QUAKED target_activate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be usable/triggerable */ -void SP_target_activate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_activate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->use = target_activate_use; } /*QUAKED target_deactivate (1 0 0) (-4 -4 -4) (4 4 4) Will set the target(s) to be non-usable/triggerable */ -void SP_target_deactivate( gentity_t *self ) -{ - G_SetOrigin( self, self->s.origin ); +void SP_target_deactivate(gentity_t *self) { + G_SetOrigin(self, self->s.origin); self->use = target_deactivate_use; } -void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); +void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); trap->SendConsoleCommand(EXEC_NOW, va("map %s", self->message)); } @@ -970,27 +838,24 @@ void target_level_change_use(gentity_t *self, gentity_t *other, gentity_t *activ /*QUAKED target_level_change (1 0 0) (-4 -4 -4) (4 4 4) "mapname" - Name of map to change to */ -void SP_target_level_change( gentity_t *self ) -{ +void SP_target_level_change(gentity_t *self) { char *s; - G_SpawnString( "mapname", "", &s ); + G_SpawnString("mapname", "", &s); self->message = G_NewString(s); - if ( !self->message || !self->message[0] ) - { - trap->Error( ERR_DROP, "target_level_change with no mapname!\n"); + if (!self->message || !self->message[0]) { + trap->Error(ERR_DROP, "target_level_change with no mapname!\n"); return; } - G_SetOrigin( self, self->s.origin ); + G_SetOrigin(self, self->s.origin); self->use = target_level_change_use; } -void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - G_ActivateBehavior(self,BSET_USE); - trap->SetConfigstring( CS_MUSIC, self->message ); +void target_play_music_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + G_ActivateBehavior(self, BSET_USE); + trap->SetConfigstring(CS_MUSIC, self->message); } /*QUAKED target_play_music (1 0 0) (-4 -4 -4) (4 4 4) @@ -1004,14 +869,12 @@ If an intro file and loop file are specified, the intro plays first, then the lo portion will start and loop indefinetly. If no introfile is entered, only the loopfile will play. */ -void SP_target_play_music( gentity_t *self ) -{ +void SP_target_play_music(gentity_t *self) { char *s; - G_SetOrigin( self, self->s.origin ); - if (!G_SpawnString( "music", "", &s )) - { - trap->Error( ERR_DROP, "target_play_music without a music key at %s", vtos( self->s.origin ) ); + G_SetOrigin(self, self->s.origin); + if (!G_SpawnString("music", "", &s)) { + trap->Error(ERR_DROP, "target_play_music without a music key at %s", vtos(self->s.origin)); } self->message = G_NewString(s); diff --git a/codemp/game/g_team.c b/codemp/game/g_team.c index f43fc1636f..75b333692b 100644 --- a/codemp/game/g_team.c +++ b/codemp/game/g_team.c @@ -25,29 +25,29 @@ along with this program; if not, see . #include "bg_saga.h" typedef struct teamgame_s { - float last_flag_capture; - int last_capture_team; - flagStatus_t redStatus; // CTF - flagStatus_t blueStatus; // CTF - flagStatus_t flagStatus; // One Flag CTF - int redTakenTime; - int blueTakenTime; + float last_flag_capture; + int last_capture_team; + flagStatus_t redStatus; // CTF + flagStatus_t blueStatus; // CTF + flagStatus_t flagStatus; // One Flag CTF + int redTakenTime; + int blueTakenTime; } teamgame_t; teamgame_t teamgame; -void Team_SetFlagStatus( int team, flagStatus_t status ); +void Team_SetFlagStatus(int team, flagStatus_t status); -void Team_InitGame( void ) { +void Team_InitGame(void) { memset(&teamgame, 0, sizeof teamgame); - switch( level.gametype ) { + switch (level.gametype) { case GT_CTF: case GT_CTY: teamgame.redStatus = -1; // Invalid to force update - Team_SetFlagStatus( TEAM_RED, FLAG_ATBASE ); + Team_SetFlagStatus(TEAM_RED, FLAG_ATBASE); teamgame.blueStatus = -1; // Invalid to force update - Team_SetFlagStatus( TEAM_BLUE, FLAG_ATBASE ); + Team_SetFlagStatus(TEAM_BLUE, FLAG_ATBASE); break; default: break; @@ -55,39 +55,39 @@ void Team_InitGame( void ) { } int OtherTeam(int team) { - if (team==TEAM_RED) + if (team == TEAM_RED) return TEAM_BLUE; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return TEAM_RED; return team; } -const char *TeamName(int team) { - if (team==TEAM_RED) +const char *TeamName(int team) { + if (team == TEAM_RED) return "RED"; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return "BLUE"; - else if (team==TEAM_SPECTATOR) + else if (team == TEAM_SPECTATOR) return "SPECTATOR"; return "FREE"; } const char *OtherTeamName(int team) { - if (team==TEAM_RED) + if (team == TEAM_RED) return "BLUE"; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return "RED"; - else if (team==TEAM_SPECTATOR) + else if (team == TEAM_SPECTATOR) return "SPECTATOR"; return "FREE"; } const char *TeamColorString(int team) { - if (team==TEAM_RED) + if (team == TEAM_RED) return S_COLOR_RED; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return S_COLOR_BLUE; - else if (team==TEAM_SPECTATOR) + else if (team == TEAM_SPECTATOR) return S_COLOR_YELLOW; return S_COLOR_WHITE; } @@ -112,21 +112,17 @@ void QDECL PrintMsg( gentity_t *ent, const char *fmt, ... ) { trap->SendServerCommand ( ( (ent == NULL) ? -1 : ent-g_entities ), va("print \"%s\"", msg )); } */ -//Printing messages to players via this method is no longer done, StringEd stuff is client only. - +// Printing messages to players via this method is no longer done, StringEd stuff is client only. -//plIndex used to print pl->client->pers.netname -//teamIndex used to print team name -void PrintCTFMessage(int plIndex, int teamIndex, int ctfMessage) -{ +// plIndex used to print pl->client->pers.netname +// teamIndex used to print team name +void PrintCTFMessage(int plIndex, int teamIndex, int ctfMessage) { gentity_t *te; - if (plIndex == -1) - { - plIndex = MAX_CLIENTS+1; + if (plIndex == -1) { + plIndex = MAX_CLIENTS + 1; } - if (teamIndex == -1) - { + if (teamIndex == -1) { teamIndex = 50; } @@ -134,19 +130,13 @@ void PrintCTFMessage(int plIndex, int teamIndex, int ctfMessage) te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = ctfMessage; te->s.trickedentindex = plIndex; - if (ctfMessage == CTFMESSAGE_PLAYER_CAPTURED_FLAG) - { - if (teamIndex == TEAM_RED) - { + if (ctfMessage == CTFMESSAGE_PLAYER_CAPTURED_FLAG) { + if (teamIndex == TEAM_RED) { te->s.trickedentindex2 = TEAM_BLUE; - } - else - { + } else { te->s.trickedentindex2 = TEAM_RED; } - } - else - { + } else { te->s.trickedentindex2 = teamIndex; } } @@ -160,42 +150,35 @@ AddTeamScore ============== */ void AddTeamScore(vec3_t origin, int team, int score) { - gentity_t *te; + gentity_t *te; - te = G_TempEntity(origin, EV_GLOBAL_TEAM_SOUND ); + te = G_TempEntity(origin, EV_GLOBAL_TEAM_SOUND); te->r.svFlags |= SVF_BROADCAST; - if ( team == TEAM_RED ) { - if ( level.teamScores[ TEAM_RED ] + score == level.teamScores[ TEAM_BLUE ] ) { - //teams are tied sound + if (team == TEAM_RED) { + if (level.teamScores[TEAM_RED] + score == level.teamScores[TEAM_BLUE]) { + // teams are tied sound te->s.eventParm = GTS_TEAMS_ARE_TIED; - } - else if ( level.teamScores[ TEAM_RED ] <= level.teamScores[ TEAM_BLUE ] && - level.teamScores[ TEAM_RED ] + score > level.teamScores[ TEAM_BLUE ]) { + } else if (level.teamScores[TEAM_RED] <= level.teamScores[TEAM_BLUE] && level.teamScores[TEAM_RED] + score > level.teamScores[TEAM_BLUE]) { // red took the lead sound te->s.eventParm = GTS_REDTEAM_TOOK_LEAD; - } - else { + } else { // red scored sound te->s.eventParm = GTS_REDTEAM_SCORED; } - } - else { - if ( level.teamScores[ TEAM_BLUE ] + score == level.teamScores[ TEAM_RED ] ) { - //teams are tied sound + } else { + if (level.teamScores[TEAM_BLUE] + score == level.teamScores[TEAM_RED]) { + // teams are tied sound te->s.eventParm = GTS_TEAMS_ARE_TIED; - } - else if ( level.teamScores[ TEAM_BLUE ] <= level.teamScores[ TEAM_RED ] && - level.teamScores[ TEAM_BLUE ] + score > level.teamScores[ TEAM_RED ]) { + } else if (level.teamScores[TEAM_BLUE] <= level.teamScores[TEAM_RED] && level.teamScores[TEAM_BLUE] + score > level.teamScores[TEAM_RED]) { // blue took the lead sound te->s.eventParm = GTS_BLUETEAM_TOOK_LEAD; - } - else { + } else { // blue scored sound te->s.eventParm = GTS_BLUETEAM_SCORED; } } - level.teamScores[ team ] += score; + level.teamScores[team] += score; } /* @@ -203,139 +186,115 @@ void AddTeamScore(vec3_t origin, int team, int score) { OnSameTeam ============== */ -qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) { - if ( !ent1->client || !ent2->client ) { +qboolean OnSameTeam(gentity_t *ent1, gentity_t *ent2) { + if (!ent1->client || !ent2->client) { return qfalse; } - if (level.gametype == GT_POWERDUEL) - { - if (ent1->client->sess.duelTeam == ent2->client->sess.duelTeam) - { + if (level.gametype == GT_POWERDUEL) { + if (ent1->client->sess.duelTeam == ent2->client->sess.duelTeam) { return qtrue; } return qfalse; } - if (level.gametype == GT_SINGLE_PLAYER) - { + if (level.gametype == GT_SINGLE_PLAYER) { qboolean ent1IsBot = qfalse; qboolean ent2IsBot = qfalse; - if (ent1->r.svFlags & SVF_BOT) - { + if (ent1->r.svFlags & SVF_BOT) { ent1IsBot = qtrue; } - if (ent2->r.svFlags & SVF_BOT) - { + if (ent2->r.svFlags & SVF_BOT) { ent2IsBot = qtrue; } - if ((ent1IsBot && ent2IsBot) || (!ent1IsBot && !ent2IsBot)) - { + if ((ent1IsBot && ent2IsBot) || (!ent1IsBot && !ent2IsBot)) { return qtrue; } return qfalse; } - if ( level.gametype < GT_TEAM ) { + if (level.gametype < GT_TEAM) { return qfalse; } - if (ent1->s.eType == ET_NPC && - ent1->s.NPC_class == CLASS_VEHICLE && - ent1->client && - ent1->client->sess.sessionTeam != TEAM_FREE && - ent2->client && - ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam) - { + if (ent1->s.eType == ET_NPC && ent1->s.NPC_class == CLASS_VEHICLE && ent1->client && ent1->client->sess.sessionTeam != TEAM_FREE && ent2->client && + ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam) { return qtrue; } - if (ent2->s.eType == ET_NPC && - ent2->s.NPC_class == CLASS_VEHICLE && - ent2->client && - ent2->client->sess.sessionTeam != TEAM_FREE && - ent1->client && - ent2->client->sess.sessionTeam == ent1->client->sess.sessionTeam) - { + if (ent2->s.eType == ET_NPC && ent2->s.NPC_class == CLASS_VEHICLE && ent2->client && ent2->client->sess.sessionTeam != TEAM_FREE && ent1->client && + ent2->client->sess.sessionTeam == ent1->client->sess.sessionTeam) { return qtrue; } - if (ent1->client->sess.sessionTeam == TEAM_FREE && - ent2->client->sess.sessionTeam == TEAM_FREE && - ent1->s.eType == ET_NPC && - ent2->s.eType == ET_NPC) - { //NPCs don't do normal team rules + if (ent1->client->sess.sessionTeam == TEAM_FREE && ent2->client->sess.sessionTeam == TEAM_FREE && ent1->s.eType == ET_NPC && + ent2->s.eType == ET_NPC) { // NPCs don't do normal team rules return qfalse; } - if (ent1->s.eType == ET_NPC && ent2->s.eType == ET_PLAYER) - { + if (ent1->s.eType == ET_NPC && ent2->s.eType == ET_PLAYER) { return qfalse; - } - else if (ent1->s.eType == ET_PLAYER && ent2->s.eType == ET_NPC) - { + } else if (ent1->s.eType == ET_PLAYER && ent2->s.eType == ET_NPC) { return qfalse; } - if ( ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam ) { + if (ent1->client->sess.sessionTeam == ent2->client->sess.sessionTeam) { return qtrue; } return qfalse; } -static char ctfFlagStatusRemap[] = { '0', '1', '*', '*', '2' }; +static char ctfFlagStatusRemap[] = {'0', '1', '*', '*', '2'}; -void Team_SetFlagStatus( int team, flagStatus_t status ) { +void Team_SetFlagStatus(int team, flagStatus_t status) { qboolean modified = qfalse; - switch( team ) { - case TEAM_RED: // CTF - if( teamgame.redStatus != status ) { + switch (team) { + case TEAM_RED: // CTF + if (teamgame.redStatus != status) { teamgame.redStatus = status; modified = qtrue; } break; - case TEAM_BLUE: // CTF - if( teamgame.blueStatus != status ) { + case TEAM_BLUE: // CTF + if (teamgame.blueStatus != status) { teamgame.blueStatus = status; modified = qtrue; } break; - case TEAM_FREE: // One Flag CTF - if( teamgame.flagStatus != status ) { + case TEAM_FREE: // One Flag CTF + if (teamgame.flagStatus != status) { teamgame.flagStatus = status; modified = qtrue; } break; } - if( modified ) { + if (modified) { char st[4]; - if( level.gametype == GT_CTF || level.gametype == GT_CTY ) { + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { st[0] = ctfFlagStatusRemap[teamgame.redStatus]; st[1] = ctfFlagStatusRemap[teamgame.blueStatus]; st[2] = 0; } - trap->SetConfigstring( CS_FLAGSTATUS, st ); + trap->SetConfigstring(CS_FLAGSTATUS, st); } } -void Team_CheckDroppedItem( gentity_t *dropped ) { - if( dropped->item->giTag == PW_REDFLAG ) { - Team_SetFlagStatus( TEAM_RED, FLAG_DROPPED ); - } - else if( dropped->item->giTag == PW_BLUEFLAG ) { - Team_SetFlagStatus( TEAM_BLUE, FLAG_DROPPED ); - } - else if( dropped->item->giTag == PW_NEUTRALFLAG ) { - Team_SetFlagStatus( TEAM_FREE, FLAG_DROPPED ); +void Team_CheckDroppedItem(gentity_t *dropped) { + if (dropped->item->giTag == PW_REDFLAG) { + Team_SetFlagStatus(TEAM_RED, FLAG_DROPPED); + } else if (dropped->item->giTag == PW_BLUEFLAG) { + Team_SetFlagStatus(TEAM_BLUE, FLAG_DROPPED); + } else if (dropped->item->giTag == PW_NEUTRALFLAG) { + Team_SetFlagStatus(TEAM_FREE, FLAG_DROPPED); } } @@ -348,8 +307,7 @@ Note that bonuses are not cumulative. You get one, they are in importance order. ================ */ -void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker) -{ +void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker) { int i; gentity_t *ent; int flag_pw, enemy_flag_pw; @@ -382,7 +340,7 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker attacker->client->pers.teamState.lastfraggedcarrier = level.time; AddScore(attacker, targ->r.currentOrigin, CTF_FRAG_CARRIER_BONUS); attacker->client->pers.teamState.fragcarrier++; - //PrintMsg(NULL, "%s" S_COLOR_WHITE " fragged %s's flag carrier!\n", + // PrintMsg(NULL, "%s" S_COLOR_WHITE " fragged %s's flag carrier!\n", // attacker->client->pers.netname, TeamName(team)); PrintCTFMessage(attacker->s.number, team, CTFMESSAGE_FRAGGED_FLAG_CARRIER); @@ -396,8 +354,7 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker return; } - if (targ->client->pers.teamState.lasthurtcarrier && - level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT && + if (targ->client->pers.teamState.lasthurtcarrier && level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT && !attacker->client->ps.powerups[flag_pw]) { // attacker is on the same team as the flag carrier and // fragged a guy who hurt our flag carrier @@ -413,8 +370,7 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker return; } - if (targ->client->pers.teamState.lasthurtcarrier && - level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT) { + if (targ->client->pers.teamState.lasthurtcarrier && level.time - targ->client->pers.teamState.lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT) { // attacker is on the same team as the skull carrier and AddScore(attacker, targ->r.currentOrigin, CTF_CARRIER_DANGER_PROTECT_BONUS); @@ -451,7 +407,7 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker carrier = NULL; } flag = NULL; - while ((flag = G_Find (flag, FOFS(classname), c)) != NULL) { + while ((flag = G_Find(flag, FOFS(classname), c)) != NULL) { if (!(flag->flags & FL_DROPPED_ITEM)) break; } @@ -465,10 +421,8 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker VectorSubtract(targ->r.currentOrigin, flag->r.currentOrigin, v1); VectorSubtract(attacker->r.currentOrigin, flag->r.currentOrigin, v2); - if ( ( ( VectorLength(v1) < CTF_TARGET_PROTECT_RADIUS && - trap->InPVS(flag->r.currentOrigin, targ->r.currentOrigin ) ) || - ( VectorLength(v2) < CTF_TARGET_PROTECT_RADIUS && - trap->InPVS(flag->r.currentOrigin, attacker->r.currentOrigin ) ) ) && + if (((VectorLength(v1) < CTF_TARGET_PROTECT_RADIUS && trap->InPVS(flag->r.currentOrigin, targ->r.currentOrigin)) || + (VectorLength(v2) < CTF_TARGET_PROTECT_RADIUS && trap->InPVS(flag->r.currentOrigin, attacker->r.currentOrigin))) && attacker->client->sess.sessionTeam != targ->client->sess.sessionTeam) { // we defended the base flag @@ -485,10 +439,8 @@ void Team_FragBonuses(gentity_t *targ, gentity_t *inflictor, gentity_t *attacker VectorSubtract(targ->r.currentOrigin, carrier->r.currentOrigin, v1); VectorSubtract(attacker->r.currentOrigin, carrier->r.currentOrigin, v1); - if ( ( ( VectorLength(v1) < CTF_ATTACKER_PROTECT_RADIUS && - trap->InPVS(carrier->r.currentOrigin, targ->r.currentOrigin ) ) || - ( VectorLength(v2) < CTF_ATTACKER_PROTECT_RADIUS && - trap->InPVS(carrier->r.currentOrigin, attacker->r.currentOrigin ) ) ) && + if (((VectorLength(v1) < CTF_ATTACKER_PROTECT_RADIUS && trap->InPVS(carrier->r.currentOrigin, targ->r.currentOrigin)) || + (VectorLength(v2) < CTF_ATTACKER_PROTECT_RADIUS && trap->InPVS(carrier->r.currentOrigin, attacker->r.currentOrigin))) && attacker->client->sess.sessionTeam != targ->client->sess.sessionTeam) { AddScore(attacker, targ->r.currentOrigin, CTF_CARRIER_PROTECT_BONUS); attacker->client->pers.teamState.carrierdefense++; @@ -509,8 +461,7 @@ Check to see if attacker hurt the flag carrier. Needed when handing out bonuses carrier defense. ================ */ -void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker) -{ +void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker) { int flag_pw; if (!targ->client || !attacker->client) @@ -522,18 +473,15 @@ void Team_CheckHurtCarrier(gentity_t *targ, gentity_t *attacker) flag_pw = PW_REDFLAG; // flags - if (targ->client->ps.powerups[flag_pw] && - targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam) + if (targ->client->ps.powerups[flag_pw] && targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam) attacker->client->pers.teamState.lasthurtcarrier = level.time; // skulls - if (targ->client->ps.generic1 && - targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam) + if (targ->client->ps.generic1 && targ->client->sess.sessionTeam != attacker->client->sess.sessionTeam) attacker->client->pers.teamState.lasthurtcarrier = level.time; } - -gentity_t *Team_ResetFlag( int team ) { +gentity_t *Team_ResetFlag(int team) { char *c; gentity_t *ent, *rent = NULL; @@ -552,7 +500,7 @@ gentity_t *Team_ResetFlag( int team ) { } ent = NULL; - while ((ent = G_Find (ent, FOFS(classname), c)) != NULL) { + while ((ent = G_Find(ent, FOFS(classname), c)) != NULL) { if (ent->flags & FL_DROPPED_ITEM) G_FreeEntity(ent); else { @@ -561,112 +509,106 @@ gentity_t *Team_ResetFlag( int team ) { } } - Team_SetFlagStatus( team, FLAG_ATBASE ); + Team_SetFlagStatus(team, FLAG_ATBASE); return rent; } -void Team_ResetFlags( void ) { - if( level.gametype == GT_CTF || level.gametype == GT_CTY ) { - Team_ResetFlag( TEAM_RED ); - Team_ResetFlag( TEAM_BLUE ); +void Team_ResetFlags(void) { + if (level.gametype == GT_CTF || level.gametype == GT_CTY) { + Team_ResetFlag(TEAM_RED); + Team_ResetFlag(TEAM_BLUE); } } -void Team_ReturnFlagSound( gentity_t *ent, int team ) { - gentity_t *te; +void Team_ReturnFlagSound(gentity_t *ent, int team) { + gentity_t *te; if (ent == NULL) { - trap->Print ("Warning: NULL passed to Team_ReturnFlagSound\n"); + trap->Print("Warning: NULL passed to Team_ReturnFlagSound\n"); return; } - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND ); - if( team == TEAM_BLUE ) { + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND); + if (team == TEAM_BLUE) { te->s.eventParm = GTS_RED_RETURN; - } - else { + } else { te->s.eventParm = GTS_BLUE_RETURN; } te->r.svFlags |= SVF_BROADCAST; } -void Team_TakeFlagSound( gentity_t *ent, int team ) { - gentity_t *te; +void Team_TakeFlagSound(gentity_t *ent, int team) { + gentity_t *te; if (ent == NULL) { - trap->Print ("Warning: NULL passed to Team_TakeFlagSound\n"); + trap->Print("Warning: NULL passed to Team_TakeFlagSound\n"); return; } // only play sound when the flag was at the base // or not picked up the last 10 seconds - switch(team) { - case TEAM_RED: - if( teamgame.blueStatus != FLAG_ATBASE ) { - if (teamgame.blueTakenTime > level.time - 10000) - return; - } - teamgame.blueTakenTime = level.time; - break; + switch (team) { + case TEAM_RED: + if (teamgame.blueStatus != FLAG_ATBASE) { + if (teamgame.blueTakenTime > level.time - 10000) + return; + } + teamgame.blueTakenTime = level.time; + break; - case TEAM_BLUE: // CTF - if( teamgame.redStatus != FLAG_ATBASE ) { - if (teamgame.redTakenTime > level.time - 10000) - return; - } - teamgame.redTakenTime = level.time; - break; + case TEAM_BLUE: // CTF + if (teamgame.redStatus != FLAG_ATBASE) { + if (teamgame.redTakenTime > level.time - 10000) + return; + } + teamgame.redTakenTime = level.time; + break; } - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND ); - if( team == TEAM_BLUE ) { + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND); + if (team == TEAM_BLUE) { te->s.eventParm = GTS_RED_TAKEN; - } - else { + } else { te->s.eventParm = GTS_BLUE_TAKEN; } te->r.svFlags |= SVF_BROADCAST; } -void Team_CaptureFlagSound( gentity_t *ent, int team ) { - gentity_t *te; +void Team_CaptureFlagSound(gentity_t *ent, int team) { + gentity_t *te; if (ent == NULL) { - trap->Print ("Warning: NULL passed to Team_CaptureFlagSound\n"); + trap->Print("Warning: NULL passed to Team_CaptureFlagSound\n"); return; } - te = G_TempEntity( ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND ); - if( team == TEAM_BLUE ) { + te = G_TempEntity(ent->s.pos.trBase, EV_GLOBAL_TEAM_SOUND); + if (team == TEAM_BLUE) { te->s.eventParm = GTS_BLUE_CAPTURE; - } - else { + } else { te->s.eventParm = GTS_RED_CAPTURE; } te->r.svFlags |= SVF_BROADCAST; } -void Team_ReturnFlag( int team ) { +void Team_ReturnFlag(int team) { Team_ReturnFlagSound(Team_ResetFlag(team), team); - if( team == TEAM_FREE ) { - //PrintMsg(NULL, "The flag has returned!\n" ); - } - else { //flag should always have team in normal CTF - //PrintMsg(NULL, "The %s flag has returned!\n", TeamName(team)); + if (team == TEAM_FREE) { + // PrintMsg(NULL, "The flag has returned!\n" ); + } else { // flag should always have team in normal CTF + // PrintMsg(NULL, "The %s flag has returned!\n", TeamName(team)); PrintCTFMessage(-1, team, CTFMESSAGE_FLAG_RETURNED); } } -void Team_FreeEntity( gentity_t *ent ) { - if( ent->item->giTag == PW_REDFLAG ) { - Team_ReturnFlag( TEAM_RED ); - } - else if( ent->item->giTag == PW_BLUEFLAG ) { - Team_ReturnFlag( TEAM_BLUE ); - } - else if( ent->item->giTag == PW_NEUTRALFLAG ) { - Team_ReturnFlag( TEAM_FREE ); +void Team_FreeEntity(gentity_t *ent) { + if (ent->item->giTag == PW_REDFLAG) { + Team_ReturnFlag(TEAM_RED); + } else if (ent->item->giTag == PW_BLUEFLAG) { + Team_ReturnFlag(TEAM_BLUE); + } else if (ent->item->giTag == PW_NEUTRALFLAG) { + Team_ReturnFlag(TEAM_FREE); } } @@ -680,23 +622,20 @@ Flags are unique in that if they are dropped, the base flag must be respawned wh ============== */ void Team_DroppedFlagThink(gentity_t *ent) { - int team = TEAM_FREE; + int team = TEAM_FREE; - if( ent->item->giTag == PW_REDFLAG ) { + if (ent->item->giTag == PW_REDFLAG) { team = TEAM_RED; - } - else if( ent->item->giTag == PW_BLUEFLAG ) { + } else if (ent->item->giTag == PW_BLUEFLAG) { team = TEAM_BLUE; - } - else if( ent->item->giTag == PW_NEUTRALFLAG ) { + } else if (ent->item->giTag == PW_NEUTRALFLAG) { team = TEAM_FREE; } - Team_ReturnFlagSound( Team_ResetFlag( team ), team ); + Team_ReturnFlagSound(Team_ResetFlag(team), team); // Reset Flag will delete this entity } - /* ============== Team_DroppedFlagThink @@ -707,20 +646,20 @@ Team_DroppedFlagThink // on flag stand and then flag gets returned. This leaded to bit random flag // grabs/captures, improved version takes distance to the center of flag stand // into consideration (closer player will get/capture the flag). -static vec3_t minFlagRange = { 50, 36, 36 }; -static vec3_t maxFlagRange = { 44, 36, 36 }; +static vec3_t minFlagRange = {50, 36, 36}; +static vec3_t maxFlagRange = {44, 36, 36}; -int Team_TouchEnemyFlag( gentity_t *ent, gentity_t *other, int team ); +int Team_TouchEnemyFlag(gentity_t *ent, gentity_t *other, int team); -int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { - int i, num, j, enemyTeam; - gentity_t *player; - gclient_t *cl = other->client; - int enemy_flag; - vec3_t mins, maxs; - int touch[MAX_GENTITIES]; - gentity_t* enemy; - float enemyDist, dist; +int Team_TouchOurFlag(gentity_t *ent, gentity_t *other, int team) { + int i, num, j, enemyTeam; + gentity_t *player; + gclient_t *cl = other->client; + int enemy_flag; + vec3_t mins, maxs; + int touch[MAX_GENTITIES]; + gentity_t *enemy; + float enemyDist, dist; if (cl->sess.sessionTeam == TEAM_RED) { enemy_flag = PW_BLUEFLAG; @@ -728,16 +667,16 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { enemy_flag = PW_REDFLAG; } - if ( ent->flags & FL_DROPPED_ITEM ) { + if (ent->flags & FL_DROPPED_ITEM) { // hey, its not home. return it by teleporting it back - //PrintMsg( NULL, "%s" S_COLOR_WHITE " returned the %s flag!\n", + // PrintMsg( NULL, "%s" S_COLOR_WHITE " returned the %s flag!\n", // cl->pers.netname, TeamName(team)); PrintCTFMessage(other->s.number, team, CTFMESSAGE_PLAYER_RETURNED_FLAG); AddScore(other, ent->r.currentOrigin, CTF_RECOVERY_BONUS); other->client->pers.teamState.flagrecovery++; other->client->pers.teamState.lastreturnedflag = level.time; - //ResetFlag will remove this entity! We must return zero + // ResetFlag will remove this entity! We must return zero Team_ReturnFlagSound(Team_ResetFlag(team), team); return 0; } @@ -753,12 +692,12 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { return 0; // check for enemy closer to grab the flag - VectorSubtract( ent->s.pos.trBase, minFlagRange, mins ); - VectorAdd( ent->s.pos.trBase, maxFlagRange, maxs ); + VectorSubtract(ent->s.pos.trBase, minFlagRange, mins); + VectorAdd(ent->s.pos.trBase, maxFlagRange, maxs); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - dist = Distance( ent->s.pos.trBase, other->client->ps.origin ); + dist = Distance(ent->s.pos.trBase, other->client->ps.origin); if (other->client->sess.sessionTeam == TEAM_RED) enemyTeam = TEAM_BLUE; @@ -774,31 +713,30 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { if (enemy->client->pers.connected != CON_CONNECTED) continue; - //check if its alive + // check if its alive if (enemy->health < 1) - continue; // dead people can't pickup + continue; // dead people can't pickup - //ignore specs + // ignore specs if (enemy->client->sess.sessionTeam == TEAM_SPECTATOR) continue; - //check if this is enemy - if ((enemy->client->sess.sessionTeam != TEAM_RED && enemy->client->sess.sessionTeam != TEAM_BLUE) || - enemy->client->sess.sessionTeam != enemyTeam){ + // check if this is enemy + if ((enemy->client->sess.sessionTeam != TEAM_RED && enemy->client->sess.sessionTeam != TEAM_BLUE) || enemy->client->sess.sessionTeam != enemyTeam) { continue; } - //check if enemy is closer to our flag than us + // check if enemy is closer to our flag than us enemyDist = Distance(ent->s.pos.trBase, enemy->client->ps.origin); if (enemyDist < dist) { // possible recursion is hidden in this, but // infinite recursion wont happen, because we cant // have a < b and b < a at the same time - return Team_TouchEnemyFlag( ent, enemy, team ); + return Team_TouchEnemyFlag(ent, enemy, team); } } - //PrintMsg( NULL, "%s" S_COLOR_WHITE " captured the %s flag!\n", cl->pers.netname, TeamName(OtherTeam(team))); + // PrintMsg( NULL, "%s" S_COLOR_WHITE " captured the %s flag!\n", cl->pers.netname, TeamName(OtherTeam(team))); PrintCTFMessage(other->s.number, team, CTFMESSAGE_PLAYER_CAPTURED_FLAG); cl->ps.powerups[enemy_flag] = 0; @@ -816,7 +754,7 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { // other gets another 10 frag bonus AddScore(other, ent->r.currentOrigin, CTF_CAPTURE_BONUS); - Team_CaptureFlagSound( ent, team ); + Team_CaptureFlagSound(ent, team); // Ok, let's do the player loop, hand out the bonuses for (i = 0; i < sv_maxclients.integer; i++) { @@ -824,24 +762,19 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { if (!player->inuse || player == other) continue; - if (player->client->sess.sessionTeam != - cl->sess.sessionTeam) { + if (player->client->sess.sessionTeam != cl->sess.sessionTeam) { player->client->pers.teamState.lasthurtcarrier = -5; - } else if (player->client->sess.sessionTeam == - cl->sess.sessionTeam) { + } else if (player->client->sess.sessionTeam == cl->sess.sessionTeam) { AddScore(player, ent->r.currentOrigin, CTF_TEAM_BONUS); // award extra points for capture assists - if (player->client->pers.teamState.lastreturnedflag + - CTF_RETURN_FLAG_ASSIST_TIMEOUT > level.time) { - AddScore (player, ent->r.currentOrigin, CTF_RETURN_FLAG_ASSIST_BONUS); + if (player->client->pers.teamState.lastreturnedflag + CTF_RETURN_FLAG_ASSIST_TIMEOUT > level.time) { + AddScore(player, ent->r.currentOrigin, CTF_RETURN_FLAG_ASSIST_BONUS); other->client->pers.teamState.assists++; player->client->ps.persistant[PERS_ASSIST_COUNT]++; player->client->rewardTime = level.time + REWARD_SPRITE_TIME; - } - if (player->client->pers.teamState.lastfraggedcarrier + - CTF_FRAG_CARRIER_ASSIST_TIMEOUT > level.time) { + if (player->client->pers.teamState.lastfraggedcarrier + CTF_FRAG_CARRIER_ASSIST_TIMEOUT > level.time) { AddScore(player, ent->r.currentOrigin, CTF_FRAG_CARRIER_ASSIST_BONUS); other->client->pers.teamState.assists++; player->client->ps.persistant[PERS_ASSIST_COUNT]++; @@ -856,57 +789,57 @@ int Team_TouchOurFlag( gentity_t *ent, gentity_t *other, int team ) { return 0; // Do not respawn this automatically } -int Team_TouchEnemyFlag( gentity_t *ent, gentity_t *other, int team ) { +int Team_TouchEnemyFlag(gentity_t *ent, gentity_t *other, int team) { gclient_t *cl = other->client; - vec3_t mins, maxs; - int num, j, ourFlag; - int touch[MAX_GENTITIES]; - gentity_t* enemy; - float enemyDist, dist; + vec3_t mins, maxs; + int num, j, ourFlag; + int touch[MAX_GENTITIES]; + gentity_t *enemy; + float enemyDist, dist; - VectorSubtract( ent->s.pos.trBase, minFlagRange, mins ); - VectorAdd( ent->s.pos.trBase, maxFlagRange, maxs ); + VectorSubtract(ent->s.pos.trBase, minFlagRange, mins); + VectorAdd(ent->s.pos.trBase, maxFlagRange, maxs); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); dist = Distance(ent->s.pos.trBase, other->client->ps.origin); - if (other->client->sess.sessionTeam == TEAM_RED){ - ourFlag = PW_REDFLAG; + if (other->client->sess.sessionTeam == TEAM_RED) { + ourFlag = PW_REDFLAG; } else { - ourFlag = PW_BLUEFLAG; + ourFlag = PW_BLUEFLAG; } - for(j = 0; j < num; ++j){ + for (j = 0; j < num; ++j) { enemy = (g_entities + touch[j]); - if (!enemy || !enemy->inuse || !enemy->client){ + if (!enemy || !enemy->inuse || !enemy->client) { continue; } - //ignore specs + // ignore specs if (enemy->client->sess.sessionTeam == TEAM_SPECTATOR) continue; - //check if its alive + // check if its alive if (enemy->health < 1) - continue; // dead people can't pick up items + continue; // dead people can't pick up items - //lets check if he has our flag + // lets check if he has our flag if (!enemy->client->ps.powerups[ourFlag]) continue; - //check if enemy is closer to our flag than us - enemyDist = Distance(ent->s.pos.trBase,enemy->client->ps.origin); - if (enemyDist < dist){ + // check if enemy is closer to our flag than us + enemyDist = Distance(ent->s.pos.trBase, enemy->client->ps.origin); + if (enemyDist < dist) { // possible recursion is hidden in this, but // infinite recursion wont happen, because we cant // have a < b and b < a at the same time - return Team_TouchOurFlag( ent, enemy, team ); + return Team_TouchOurFlag(ent, enemy, team); } } - //PrintMsg (NULL, "%s" S_COLOR_WHITE " got the %s flag!\n", + // PrintMsg (NULL, "%s" S_COLOR_WHITE " got the %s flag!\n", // other->client->pers.netname, TeamName(team)); PrintCTFMessage(other->s.number, team, CTFMESSAGE_PLAYER_GOT_FLAG); @@ -915,38 +848,35 @@ int Team_TouchEnemyFlag( gentity_t *ent, gentity_t *other, int team ) { else cl->ps.powerups[PW_BLUEFLAG] = INT_MAX; // flags never expire - Team_SetFlagStatus( team, FLAG_TAKEN ); + Team_SetFlagStatus(team, FLAG_TAKEN); AddScore(other, ent->r.currentOrigin, CTF_FLAG_BONUS); cl->pers.teamState.flagsince = level.time; - Team_TakeFlagSound( ent, team ); + Team_TakeFlagSound(ent, team); return -1; // Do not respawn this automatically, but do delete it if it was FL_DROPPED } -int Pickup_Team( gentity_t *ent, gentity_t *other ) { +int Pickup_Team(gentity_t *ent, gentity_t *other) { int team; gclient_t *cl = other->client; // figure out what team this flag is - if( strcmp(ent->classname, "team_CTF_redflag") == 0 ) { + if (strcmp(ent->classname, "team_CTF_redflag") == 0) { team = TEAM_RED; - } - else if( strcmp(ent->classname, "team_CTF_blueflag") == 0 ) { + } else if (strcmp(ent->classname, "team_CTF_blueflag") == 0) { team = TEAM_BLUE; - } - else if( strcmp(ent->classname, "team_CTF_neutralflag") == 0 ) { + } else if (strcmp(ent->classname, "team_CTF_neutralflag") == 0) { team = TEAM_FREE; - } - else { -// PrintMsg ( other, "Don't know what team the flag is on.\n"); + } else { + // PrintMsg ( other, "Don't know what team the flag is on.\n"); return 0; } // GT_CTF - if( team == cl->sess.sessionTeam) { - return Team_TouchOurFlag( ent, other, team ); + if (team == cl->sess.sessionTeam) { + return Team_TouchOurFlag(ent, other, team); } - return Team_TouchEnemyFlag( ent, other, team ); + return Team_TouchEnemyFlag(ent, other, team); } /* @@ -956,29 +886,27 @@ Team_GetLocation Report a location for the player. Uses placed nearby target_location entities ============ */ -locationData_t *Team_GetLocation(gentity_t *ent) -{ - locationData_t *loc, *best; - float bestlen, len; - vec3_t origin; - int i; +locationData_t *Team_GetLocation(gentity_t *ent) { + locationData_t *loc, *best; + float bestlen, len; + vec3_t origin; + int i; best = NULL; - bestlen = 3*8192.0*8192.0; + bestlen = 3 * 8192.0 * 8192.0; - VectorCopy( ent->r.currentOrigin, origin ); + VectorCopy(ent->r.currentOrigin, origin); - for ( i=0; iorigin[0] ) * ( origin[0] - loc->origin[0] ) - + ( origin[1] - loc->origin[1] ) * ( origin[1] - loc->origin[1] ) - + ( origin[2] - loc->origin[2] ) * ( origin[2] - loc->origin[2] ); + len = (origin[0] - loc->origin[0]) * (origin[0] - loc->origin[0]) + (origin[1] - loc->origin[1]) * (origin[1] - loc->origin[1]) + + (origin[2] - loc->origin[2]) * (origin[2] - loc->origin[2]); - if ( len > bestlen ) { + if (len > bestlen) { continue; } - if ( !trap->InPVS( origin, loc->origin ) ) { + if (!trap->InPVS(origin, loc->origin)) { continue; } @@ -989,7 +917,6 @@ locationData_t *Team_GetLocation(gentity_t *ent) return best; } - /* =========== Team_GetLocation @@ -997,11 +924,10 @@ Team_GetLocation Report a location for the player. Uses placed nearby target_location entities ============ */ -qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen) -{ +qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen) { locationData_t *best; - best = Team_GetLocation( ent ); + best = Team_GetLocation(ent); if (!best) return qfalse; @@ -1011,14 +937,13 @@ qboolean Team_GetLocationMsg(gentity_t *ent, char *loc, int loclen) best->count = 0; if (best->count > 7) best->count = 7; - Com_sprintf(loc, loclen, "%c%c%s" S_COLOR_WHITE, Q_COLOR_ESCAPE, best->count + '0', best->message ); + Com_sprintf(loc, loclen, "%c%c%s" S_COLOR_WHITE, Q_COLOR_ESCAPE, best->count + '0', best->message); } else Com_sprintf(loc, loclen, "%s", best->message); return qtrue; } - /*---------------------------------------------------------------------------*/ /* @@ -1028,30 +953,24 @@ SelectRandomTeamSpawnPoint go to a random point that doesn't telefrag ================ */ -#define MAX_TEAM_SPAWN_POINTS 32 -gentity_t *SelectRandomTeamSpawnPoint( int teamstate, team_t team, int siegeClass ) { - gentity_t *spot; - int count; - int selection; - gentity_t *spots[MAX_TEAM_SPAWN_POINTS]; - const char *classname; - qboolean mustBeEnabled = qfalse; - - if (level.gametype == GT_SIEGE) - { - if (team == SIEGETEAM_TEAM1) - { +#define MAX_TEAM_SPAWN_POINTS 32 +gentity_t *SelectRandomTeamSpawnPoint(int teamstate, team_t team, int siegeClass) { + gentity_t *spot; + int count; + int selection; + gentity_t *spots[MAX_TEAM_SPAWN_POINTS]; + const char *classname; + qboolean mustBeEnabled = qfalse; + + if (level.gametype == GT_SIEGE) { + if (team == SIEGETEAM_TEAM1) { classname = "info_player_siegeteam1"; - } - else - { + } else { classname = "info_player_siegeteam2"; } - mustBeEnabled = qtrue; //siege spawn points need to be "enabled" to be used (because multiple spawnpoint sets can be placed at once) - } - else - { + mustBeEnabled = qtrue; // siege spawn points need to be "enabled" to be used (because multiple spawnpoint sets can be placed at once) + } else { if (teamstate == TEAM_BEGIN) { if (team == TEAM_RED) classname = "team_CTF_redplayer"; @@ -1072,73 +991,67 @@ gentity_t *SelectRandomTeamSpawnPoint( int teamstate, team_t team, int siegeClas spot = NULL; - while ((spot = G_Find (spot, FOFS(classname), classname)) != NULL) { - if ( SpotWouldTelefrag( spot ) ) { + while ((spot = G_Find(spot, FOFS(classname), classname)) != NULL) { + if (SpotWouldTelefrag(spot)) { continue; } - if (mustBeEnabled && !spot->genericValue1) - { //siege point that's not enabled, can't use it + if (mustBeEnabled && !spot->genericValue1) { // siege point that's not enabled, can't use it continue; } - spots[ count ] = spot; + spots[count] = spot; if (++count == MAX_TEAM_SPAWN_POINTS) break; } - if ( !count ) { // no spots that won't telefrag - return G_Find( NULL, FOFS(classname), classname); + if (!count) { // no spots that won't telefrag + return G_Find(NULL, FOFS(classname), classname); } if (level.gametype == GT_SIEGE && siegeClass >= 0 && - bgSiegeClasses[siegeClass].name[0]) - { //out of the spots found, see if any have an idealclass to match our class name + bgSiegeClasses[siegeClass].name[0]) { // out of the spots found, see if any have an idealclass to match our class name gentity_t *classSpots[MAX_TEAM_SPAWN_POINTS]; int classCount = 0; int i = 0; - while (i < count) - { + while (i < count) { if (spots[i] && spots[i]->idealclass && spots[i]->idealclass[0] && - !Q_stricmp(spots[i]->idealclass, bgSiegeClasses[siegeClass].name)) - { //this spot's idealclass matches the class name - classSpots[classCount] = spots[i]; + !Q_stricmp(spots[i]->idealclass, bgSiegeClasses[siegeClass].name)) { // this spot's idealclass matches the class name + classSpots[classCount] = spots[i]; classCount++; } i++; } - if (classCount > 0) - { //found at least one + if (classCount > 0) { // found at least one selection = rand() % classCount; - return classSpots[ selection ]; + return classSpots[selection]; } } selection = rand() % count; - return spots[ selection ]; + return spots[selection]; } - /* =========== SelectCTFSpawnPoint ============ */ -gentity_t *SelectCTFSpawnPoint ( team_t team, int teamstate, vec3_t origin, vec3_t angles, qboolean isbot ) { - gentity_t *spot; +gentity_t *SelectCTFSpawnPoint(team_t team, int teamstate, vec3_t origin, vec3_t angles, qboolean isbot) { + gentity_t *spot; - spot = SelectRandomTeamSpawnPoint ( teamstate, team, -1 ); + spot = SelectRandomTeamSpawnPoint(teamstate, team, -1); if (!spot) { - return SelectSpawnPoint( vec3_origin, origin, angles, team, isbot ); + return SelectSpawnPoint(vec3_origin, origin, angles, team, isbot); } - VectorCopy (spot->s.origin, origin); + VectorCopy(spot->s.origin, origin); origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } @@ -1149,28 +1062,25 @@ SelectSiegeSpawnPoint ============ */ -gentity_t *SelectSiegeSpawnPoint ( int siegeClass, team_t team, int teamstate, vec3_t origin, vec3_t angles, qboolean isbot ) { - gentity_t *spot; +gentity_t *SelectSiegeSpawnPoint(int siegeClass, team_t team, int teamstate, vec3_t origin, vec3_t angles, qboolean isbot) { + gentity_t *spot; - spot = SelectRandomTeamSpawnPoint ( teamstate, team, siegeClass ); + spot = SelectRandomTeamSpawnPoint(teamstate, team, siegeClass); if (!spot) { - return SelectSpawnPoint( vec3_origin, origin, angles, team, isbot ); + return SelectSpawnPoint(vec3_origin, origin, angles, team, isbot); } - VectorCopy (spot->s.origin, origin); + VectorCopy(spot->s.origin, origin); origin[2] += 9; - VectorCopy (spot->s.angles, angles); + VectorCopy(spot->s.angles, angles); return spot; } /*---------------------------------------------------------------------------*/ -static int QDECL SortClients( const void *a, const void *b ) { - return *(int *)a - *(int *)b; -} - +static int QDECL SortClients(const void *a, const void *b) { return *(int *)a - *(int *)b; } /* ================== @@ -1181,27 +1091,26 @@ TeamplayLocationsMessage ================== */ -void TeamplayInfoMessage( gentity_t *ent ) { - char entry[1024]; - char string[8192]; - int stringlength; - int i, j; - gentity_t *player; - int cnt; - int h, a; - int clients[TEAM_MAXOVERLAY]; - int team; - - if ( ! ent->client->pers.teamInfo ) +void TeamplayInfoMessage(gentity_t *ent) { + char entry[1024]; + char string[8192]; + int stringlength; + int i, j; + gentity_t *player; + int cnt; + int h, a; + int clients[TEAM_MAXOVERLAY]; + int team; + + if (!ent->client->pers.teamInfo) return; // send team info to spectator for team of followed client if (ent->client->sess.sessionTeam == TEAM_SPECTATOR) { - if ( ent->client->sess.spectatorState != SPECTATOR_FOLLOW - || ent->client->sess.spectatorClient < 0 ) { - return; + if (ent->client->sess.spectatorState != SPECTATOR_FOLLOW || ent->client->sess.spectatorClient < 0) { + return; } - team = g_entities[ ent->client->sess.spectatorClient ].client->sess.sessionTeam; + team = g_entities[ent->client->sess.spectatorClient].client->sess.sessionTeam; } else { team = ent->client->sess.sessionTeam; } @@ -1215,13 +1124,13 @@ void TeamplayInfoMessage( gentity_t *ent ) { // but in client order (so they don't keep changing position on the overlay) for (i = 0, cnt = 0; i < sv_maxclients.integer && cnt < TEAM_MAXOVERLAY; i++) { player = g_entities + level.sortedClients[i]; - if (player->inuse && player->client->sess.sessionTeam == team ) { + if (player->inuse && player->client->sess.sessionTeam == team) { clients[cnt++] = level.sortedClients[i]; } } // We have the top eight players, sort them by clientNum - qsort( clients, cnt, sizeof( clients[0] ), SortClients ); + qsort(clients, cnt, sizeof(clients[0]), SortClients); // send the latest information on all clients string[0] = 0; @@ -1229,36 +1138,33 @@ void TeamplayInfoMessage( gentity_t *ent ) { for (i = 0, cnt = 0; i < sv_maxclients.integer && cnt < TEAM_MAXOVERLAY; i++) { player = g_entities + i; - if (player->inuse && player->client->sess.sessionTeam == team ) { + if (player->inuse && player->client->sess.sessionTeam == team) { - if ( player->client->tempSpectate >= level.time ) { + if (player->client->tempSpectate >= level.time) { h = a = 0; - Com_sprintf( entry, sizeof(entry), - " %i %i %i %i %i %i", - i, 0, h, a, 0, 0 ); - } - else { + Com_sprintf(entry, sizeof(entry), " %i %i %i %i %i %i", i, 0, h, a, 0, 0); + } else { h = player->client->ps.stats[STAT_HEALTH]; a = player->client->ps.stats[STAT_ARMOR]; - if ( h < 0 ) h = 0; - if ( a < 0 ) a = 0; + if (h < 0) + h = 0; + if (a < 0) + a = 0; - Com_sprintf( entry, sizeof(entry), - " %i %i %i %i %i %i", - i, player->client->pers.teamState.location, h, a, - player->client->ps.weapon, player->s.powerups ); + Com_sprintf(entry, sizeof(entry), " %i %i %i %i %i %i", i, player->client->pers.teamState.location, h, a, player->client->ps.weapon, + player->s.powerups); } j = strlen(entry); if (stringlength + j >= sizeof(string)) break; - strcpy (string + stringlength, entry); + strcpy(string + stringlength, entry); stringlength += j; cnt++; } } - trap->SendServerCommand( ent-g_entities, va("tinfo %i %s", cnt, string) ); + trap->SendServerCommand(ent - g_entities, va("tinfo %i %s", cnt, string)); } void CheckTeamStatus(void) { @@ -1273,17 +1179,16 @@ void CheckTeamStatus(void) { for (i = 0; i < sv_maxclients.integer; i++) { ent = g_entities + i; - if ( !ent->client ) - { + if (!ent->client) { continue; } - if ( ent->client->pers.connected != CON_CONNECTED ) { + if (ent->client->pers.connected != CON_CONNECTED) { continue; } - if (ent->inuse && (ent->client->sess.sessionTeam == TEAM_RED || ent->client->sess.sessionTeam == TEAM_BLUE)) { - loc = Team_GetLocation( ent ); + if (ent->inuse && (ent->client->sess.sessionTeam == TEAM_RED || ent->client->sess.sessionTeam == TEAM_BLUE)) { + loc = Team_GetLocation(ent); if (loc) ent->client->pers.teamState.location = loc->cs_index; else @@ -1294,15 +1199,15 @@ void CheckTeamStatus(void) { for (i = 0; i < sv_maxclients.integer; i++) { ent = g_entities + i; - if ( !ent->client ) // uhm + if (!ent->client) // uhm continue; - if ( ent->client->pers.connected != CON_CONNECTED ) { + if (ent->client->pers.connected != CON_CONNECTED) { continue; } if (ent->inuse) { - TeamplayInfoMessage( ent ); + TeamplayInfoMessage(ent); } } } @@ -1313,29 +1218,21 @@ void CheckTeamStatus(void) { /*QUAKED team_CTF_redplayer (1 0 0) (-16 -16 -16) (16 16 32) Only in CTF games. Red players spawn here at game start. */ -void SP_team_CTF_redplayer( gentity_t *ent ) { -} - +void SP_team_CTF_redplayer(gentity_t *ent) {} /*QUAKED team_CTF_blueplayer (0 0 1) (-16 -16 -16) (16 16 32) Only in CTF games. Blue players spawn here at game start. */ -void SP_team_CTF_blueplayer( gentity_t *ent ) { -} - +void SP_team_CTF_blueplayer(gentity_t *ent) {} /*QUAKED team_CTF_redspawn (1 0 0) (-16 -16 -24) (16 16 32) potential spawning position for red team in CTF games. Targets will be fired when someone spawns in on them. */ -void SP_team_CTF_redspawn(gentity_t *ent) { -} +void SP_team_CTF_redspawn(gentity_t *ent) {} /*QUAKED team_CTF_bluespawn (0 0 1) (-16 -16 -24) (16 16 32) potential spawning position for blue team in CTF games. Targets will be fired when someone spawns in on them. */ -void SP_team_CTF_bluespawn(gentity_t *ent) { -} - - +void SP_team_CTF_bluespawn(gentity_t *ent) {} diff --git a/codemp/game/g_timer.c b/codemp/game/g_timer.c index 63d146159a..450a136ee9 100644 --- a/codemp/game/g_timer.c +++ b/codemp/game/g_timer.c @@ -20,24 +20,23 @@ along with this program; if not, see . =========================================================================== */ -//rww - rewrite from C++ SP version. -//This is here only to make porting from SP easier, it's really sort of nasty (being static -//now). Basically it's slower and takes more memory. +// rww - rewrite from C++ SP version. +// This is here only to make porting from SP easier, it's really sort of nasty (being static +// now). Basically it's slower and takes more memory. #include "g_local.h" -//typedef map < string, int > timer_m; +// typedef map < string, int > timer_m; -#define MAX_GTIMERS 16384 +#define MAX_GTIMERS 16384 -typedef struct gtimer_s -{ +typedef struct gtimer_s { const char *name; int time; - struct gtimer_s *next; // In either free list or current list + struct gtimer_s *next; // In either free list or current list } gtimer_t; -gtimer_t g_timerPool[ MAX_GTIMERS ]; -gtimer_t *g_timers[ MAX_GENTITIES ]; +gtimer_t g_timerPool[MAX_GTIMERS]; +gtimer_t *g_timers[MAX_GENTITIES]; gtimer_t *g_timerFreeList; /* @@ -46,19 +45,16 @@ TIMER_Clear ------------------------- */ -void TIMER_Clear( void ) -{ +void TIMER_Clear(void) { int i; - for (i = 0; i < MAX_GENTITIES; i++) - { + for (i = 0; i < MAX_GENTITIES; i++) { g_timers[i] = NULL; } - for (i = 0; i < MAX_GTIMERS - 1; i++) - { - g_timerPool[i].next = &g_timerPool[i+1]; + for (i = 0; i < MAX_GTIMERS - 1; i++) { + g_timerPool[i].next = &g_timerPool[i + 1]; } - g_timerPool[MAX_GTIMERS-1].next = NULL; + g_timerPool[MAX_GTIMERS - 1].next = NULL; g_timerFreeList = &g_timerPool[0]; } @@ -68,22 +64,18 @@ TIMER_Clear ------------------------- */ -void TIMER_Clear2( gentity_t *ent ) -{ +void TIMER_Clear2(gentity_t *ent) { // rudimentary safety checks, might be other things to check? - if ( ent && ent->s.number >= 0 && ent->s.number < MAX_GENTITIES ) - { + if (ent && ent->s.number >= 0 && ent->s.number < MAX_GENTITIES) { gtimer_t *p = g_timers[ent->s.number]; // No timers at all -> do nothing - if (!p) - { + if (!p) { return; } // Find the end of this ents timer list - while (p->next) - { + while (p->next) { p = p->next; } @@ -95,18 +87,14 @@ void TIMER_Clear2( gentity_t *ent ) } } - -//New C "lookup" func. -//Returns existing timer in array if -gtimer_t *TIMER_GetNew(int num, const char *identifier) -{ +// New C "lookup" func. +// Returns existing timer in array if +gtimer_t *TIMER_GetNew(int num, const char *identifier) { gtimer_t *p = g_timers[num]; // Search for an existing timer with this name - while (p) - { - if (!Q_stricmp(p->name, identifier)) - { // Found it + while (p) { + if (!Q_stricmp(p->name, identifier)) { // Found it return p; } @@ -124,15 +112,12 @@ gtimer_t *TIMER_GetNew(int num, const char *identifier) return p; } -//don't return the first free if it doesn't already exist, return null. -gtimer_t *TIMER_GetExisting(int num, const char *identifier) -{ +// don't return the first free if it doesn't already exist, return null. +gtimer_t *TIMER_GetExisting(int num, const char *identifier) { gtimer_t *p = g_timers[num]; - while (p) - { - if (!Q_stricmp(p->name, identifier)) - { // Found it + while (p) { + if (!Q_stricmp(p->name, identifier)) { // Found it return p; } @@ -148,12 +133,10 @@ TIMER_Set ------------------------- */ -void TIMER_Set( gentity_t *ent, const char *identifier, int duration ) -{ +void TIMER_Set(gentity_t *ent, const char *identifier, int duration) { gtimer_t *timer = TIMER_GetNew(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return; } timer->name = identifier; @@ -166,12 +149,10 @@ TIMER_Get ------------------------- */ -int TIMER_Get( gentity_t *ent, const char *identifier ) -{ +int TIMER_Get(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return -1; } @@ -184,12 +165,10 @@ TIMER_Done ------------------------- */ -qboolean TIMER_Done( gentity_t *ent, const char *identifier ) -{ +qboolean TIMER_Done(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return qtrue; } @@ -206,13 +185,11 @@ timer from the list and put it on the free list Doesn't do much error checking, only called below ------------------------- */ -void TIMER_RemoveHelper( int num, gtimer_t *timer ) -{ +void TIMER_RemoveHelper(int num, gtimer_t *timer) { gtimer_t *p = g_timers[num]; // Special case: first timer in list - if (p == timer) - { + if (p == timer) { g_timers[num] = g_timers[num]->next; p->next = g_timerFreeList; g_timerFreeList = p; @@ -220,8 +197,7 @@ void TIMER_RemoveHelper( int num, gtimer_t *timer ) } // Find the predecessor - while (p->next != timer) - { + while (p->next != timer) { p = p->next; } @@ -242,20 +218,17 @@ timer was never started ------------------------- */ -qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) -{ +qboolean TIMER_Done2(gentity_t *ent, const char *identifier, qboolean remove) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); qboolean res; - if (!timer) - { + if (!timer) { return qfalse; } res = (timer->time < level.time); - if (res && remove) - { + if (res && remove) { // Put it back on the free list TIMER_RemoveHelper(ent->s.number, timer); } @@ -268,12 +241,10 @@ qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove ) TIMER_Exists ------------------------- */ -qboolean TIMER_Exists( gentity_t *ent, const char *identifier ) -{ +qboolean TIMER_Exists(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return qfalse; } @@ -286,12 +257,10 @@ TIMER_Remove Utility to get rid of any timer ------------------------- */ -void TIMER_Remove( gentity_t *ent, const char *identifier ) -{ +void TIMER_Remove(gentity_t *ent, const char *identifier) { gtimer_t *timer = TIMER_GetExisting(ent->s.number, identifier); - if (!timer) - { + if (!timer) { return; } @@ -305,11 +274,9 @@ TIMER_Start ------------------------- */ -qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ) -{ - if ( TIMER_Done( self, identifier ) ) - { - TIMER_Set( self, identifier, duration ); +qboolean TIMER_Start(gentity_t *self, const char *identifier, int duration) { + if (TIMER_Done(self, identifier)) { + TIMER_Set(self, identifier, duration); return qtrue; } return qfalse; diff --git a/codemp/game/g_trigger.c b/codemp/game/g_trigger.c index 8bf0553df6..796ba5db56 100644 --- a/codemp/game/g_trigger.c +++ b/codemp/game/g_trigger.c @@ -26,118 +26,94 @@ along with this program; if not, see . int gTrigFallSound; -void InitTrigger( gentity_t *self ) { - if (!VectorCompare (self->s.angles, vec3_origin)) - G_SetMovedir (self->s.angles, self->movedir); +void InitTrigger(gentity_t *self) { + if (!VectorCompare(self->s.angles, vec3_origin)) + G_SetMovedir(self->s.angles, self->movedir); - trap->SetBrushModel( (sharedEntity_t *)self, self->model ); - self->r.contents = CONTENTS_TRIGGER; // replaces the -1 from trap->SetBrushModel + trap->SetBrushModel((sharedEntity_t *)self, self->model); + self->r.contents = CONTENTS_TRIGGER; // replaces the -1 from trap->SetBrushModel self->r.svFlags = SVF_NOCLIENT; - if(self->spawnflags & 128) - { + if (self->spawnflags & 128) { self->flags |= FL_INACTIVE; } } // the wait time has passed, so set back up for another activation -void multi_wait( gentity_t *ent ) { - ent->nextthink = 0; -} +void multi_wait(gentity_t *ent) { ent->nextthink = 0; } -void trigger_cleared_fire (gentity_t *self); +void trigger_cleared_fire(gentity_t *self); // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing -void multi_trigger_run( gentity_t *ent ) -{ +void multi_trigger_run(gentity_t *ent) { ent->think = 0; - G_ActivateBehavior( ent, BSET_USE ); + G_ActivateBehavior(ent, BSET_USE); - if ( ent->soundSet && ent->soundSet[0] ) - { - trap->SetConfigstring( CS_GLOBAL_AMBIENT_SET, ent->soundSet ); + if (ent->soundSet && ent->soundSet[0]) { + trap->SetConfigstring(CS_GLOBAL_AMBIENT_SET, ent->soundSet); } - if (ent->genericValue4) - { //we want to activate target3 for team1 or target4 for team2 - if (ent->genericValue4 == SIEGETEAM_TEAM1 && - ent->target3 && ent->target3[0]) - { + if (ent->genericValue4) { // we want to activate target3 for team1 or target4 for team2 + if (ent->genericValue4 == SIEGETEAM_TEAM1 && ent->target3 && ent->target3[0]) { G_UseTargets2(ent, ent->activator, ent->target3); - } - else if (ent->genericValue4 == SIEGETEAM_TEAM2 && - ent->target4 && ent->target4[0]) - { + } else if (ent->genericValue4 == SIEGETEAM_TEAM2 && ent->target4 && ent->target4[0]) { G_UseTargets2(ent, ent->activator, ent->target4); } ent->genericValue4 = 0; } - G_UseTargets (ent, ent->activator); - if ( ent->noise_index ) - { - G_Sound( ent->activator, CHAN_AUTO, ent->noise_index ); + G_UseTargets(ent, ent->activator); + if (ent->noise_index) { + G_Sound(ent->activator, CHAN_AUTO, ent->noise_index); } - if ( ent->target2 && ent->target2[0] && ent->wait >= 0 ) - { + if (ent->target2 && ent->target2[0] && ent->wait >= 0) { ent->think = trigger_cleared_fire; ent->nextthink = level.time + ent->speed; - } - else if ( ent->wait > 0 ) - { - if ( ent->painDebounceTime != level.time ) - {//first ent to touch it this frame - //ent->e_ThinkFunc = thinkF_multi_wait; - ent->nextthink = level.time + ( ent->wait + ent->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + } else if (ent->wait > 0) { + if (ent->painDebounceTime != level.time) { // first ent to touch it this frame + // ent->e_ThinkFunc = thinkF_multi_wait; + ent->nextthink = level.time + (ent->wait + ent->random * Q_flrand(-1.0f, 1.0f)) * 1000; ent->painDebounceTime = level.time; } - } - else if ( ent->wait < 0 ) - { + } else if (ent->wait < 0) { // we can't just remove (self) here, because this is a touch function // called while looping through area links... - ent->r.contents &= ~CONTENTS_TRIGGER;//so the EntityContact trace doesn't have to be done against me + ent->r.contents &= ~CONTENTS_TRIGGER; // so the EntityContact trace doesn't have to be done against me ent->think = 0; ent->use = 0; - //Don't remove, Icarus may barf? - //ent->nextthink = level.time + FRAMETIME; - //ent->think = G_FreeEntity; + // Don't remove, Icarus may barf? + // ent->nextthink = level.time + FRAMETIME; + // ent->think = G_FreeEntity; } - if( ent->activator && ent->activator->client ) - { // mark the trigger as being touched by the player + if (ent->activator && ent->activator->client) { // mark the trigger as being touched by the player ent->aimDebounceTime = level.time; } } -//determine if the class given is listed in the string using the | formatting -qboolean G_NameInTriggerClassList(char *list, char *str) -{ +// determine if the class given is listed in the string using the | formatting +qboolean G_NameInTriggerClassList(char *list, char *str) { char cmp[MAX_STRING_CHARS]; int i = 0; int j; - while (list[i]) - { - j = 0; - while (list[i] && list[i] != '|') - { + while (list[i]) { + j = 0; + while (list[i] && list[i] != '|') { cmp[j] = list[i]; i++; j++; } cmp[j] = 0; - if (!Q_stricmp(str, cmp)) - { //found it + if (!Q_stricmp(str, cmp)) { // found it return qtrue; } - if (list[i] != '|') - { //reached the end and never found it + if (list[i] != '|') { // reached the end and never found it return qfalse; } i++; @@ -148,78 +124,54 @@ qboolean G_NameInTriggerClassList(char *list, char *str) extern qboolean gSiegeRoundBegun; void SiegeItemRemoveOwner(gentity_t *ent, gentity_t *carrier); -void multi_trigger( gentity_t *ent, gentity_t *activator ) -{ +void multi_trigger(gentity_t *ent, gentity_t *activator) { qboolean haltTrigger = qfalse; - if ( ent->think == multi_trigger_run ) - {//already triggered, just waiting to run + if (ent->think == multi_trigger_run) { // already triggered, just waiting to run return; } - if (level.gametype == GT_SIEGE && - !gSiegeRoundBegun) - { //nothing can be used til the round starts. + if (level.gametype == GT_SIEGE && !gSiegeRoundBegun) { // nothing can be used til the round starts. return; } - if (level.gametype == GT_SIEGE && - activator && activator->client && - ent->alliedTeam && - activator->client->sess.sessionTeam != ent->alliedTeam) - { //this team can't activate this trigger. + if (level.gametype == GT_SIEGE && activator && activator->client && ent->alliedTeam && + activator->client->sess.sessionTeam != ent->alliedTeam) { // this team can't activate this trigger. return; } - if (level.gametype == GT_SIEGE && - ent->idealclass && ent->idealclass[0]) - { //only certain classes can activate it - if (!activator || - !activator->client || - activator->client->siegeClass < 0) - { //no class + if (level.gametype == GT_SIEGE && ent->idealclass && ent->idealclass[0]) { // only certain classes can activate it + if (!activator || !activator->client || activator->client->siegeClass < 0) { // no class return; } - if (!G_NameInTriggerClassList(bgSiegeClasses[activator->client->siegeClass].name, ent->idealclass)) - { //wasn't in the list + if (!G_NameInTriggerClassList(bgSiegeClasses[activator->client->siegeClass].name, ent->idealclass)) { // wasn't in the list return; } } - if (level.gametype == GT_SIEGE && ent->genericValue1) - { + if (level.gametype == GT_SIEGE && ent->genericValue1) { haltTrigger = qtrue; - if (activator && activator->client && - activator->client->holdingObjectiveItem && - ent->targetname && ent->targetname[0]) - { + if (activator && activator->client && activator->client->holdingObjectiveItem && ent->targetname && ent->targetname[0]) { gentity_t *objItem = &g_entities[activator->client->holdingObjectiveItem]; - if (objItem && objItem->inuse) - { - if (objItem->goaltarget && objItem->goaltarget[0] && - !Q_stricmp(ent->targetname, objItem->goaltarget)) - { - if (objItem->genericValue7 != activator->client->sess.sessionTeam) - { //The carrier of the item is not on the team which disallows objective scoring for it - if (objItem->target3 && objItem->target3[0]) - { //if it has a target3, fire it off instead of using the trigger + if (objItem && objItem->inuse) { + if (objItem->goaltarget && objItem->goaltarget[0] && !Q_stricmp(ent->targetname, objItem->goaltarget)) { + if (objItem->genericValue7 != + activator->client->sess.sessionTeam) { // The carrier of the item is not on the team which disallows objective scoring for it + if (objItem->target3 && objItem->target3[0]) { // if it has a target3, fire it off instead of using the trigger G_UseTargets2(objItem, objItem, objItem->target3); - //3-24-03 - want to fire off the target too I guess, if we have one. - if (ent->targetname && ent->targetname[0]) - { + // 3-24-03 - want to fire off the target too I guess, if we have one. + if (ent->targetname && ent->targetname[0]) { haltTrigger = qfalse; } - } - else - { + } else { haltTrigger = qfalse; } - //now that the item has been delivered, it can go away. + // now that the item has been delivered, it can go away. SiegeItemRemoveOwner(objItem, activator); objItem->nextthink = 0; objItem->neverFree = qfalse; @@ -228,14 +180,11 @@ void multi_trigger( gentity_t *ent, gentity_t *activator ) } } } - } - else if (ent->genericValue1) - { //Never activate in non-siege gametype I guess. + } else if (ent->genericValue1) { // Never activate in non-siege gametype I guess. return; } - if (ent->genericValue2) - { //has "teambalance" property + if (ent->genericValue2) { // has "teambalance" property int i = 0; int team1ClNum = 0; int team2ClNum = 0; @@ -245,38 +194,28 @@ void multi_trigger( gentity_t *ent, gentity_t *activator ) int entityList[MAX_GENTITIES]; gentity_t *cl; - if (level.gametype != GT_SIEGE) - { + if (level.gametype != GT_SIEGE) { return; } - if (!activator->client || - (activator->client->sess.sessionTeam != SIEGETEAM_TEAM1 && activator->client->sess.sessionTeam != SIEGETEAM_TEAM2)) - { //activator must be a valid client to begin with + if (!activator->client || (activator->client->sess.sessionTeam != SIEGETEAM_TEAM1 && + activator->client->sess.sessionTeam != SIEGETEAM_TEAM2)) { // activator must be a valid client to begin with return; } - //Count up the number of clients standing within the bounds of the trigger and the number of them on each team - numEnts = trap->EntitiesInBox( ent->r.absmin, ent->r.absmax, entityList, MAX_GENTITIES ); - while (i < numEnts) - { - if (entityList[i] < MAX_CLIENTS) - { //only care about clients + // Count up the number of clients standing within the bounds of the trigger and the number of them on each team + numEnts = trap->EntitiesInBox(ent->r.absmin, ent->r.absmax, entityList, MAX_GENTITIES); + while (i < numEnts) { + if (entityList[i] < MAX_CLIENTS) { // only care about clients cl = &g_entities[entityList[i]]; - //the client is valid - if (cl->inuse && cl->client && - (cl->client->sess.sessionTeam == SIEGETEAM_TEAM1 || cl->client->sess.sessionTeam == SIEGETEAM_TEAM2) && - cl->health > 0 && - !(cl->client->ps.eFlags & EF_DEAD)) - { - //See which team he's on - if (cl->client->sess.sessionTeam == SIEGETEAM_TEAM1) - { + // the client is valid + if (cl->inuse && cl->client && (cl->client->sess.sessionTeam == SIEGETEAM_TEAM1 || cl->client->sess.sessionTeam == SIEGETEAM_TEAM2) && + cl->health > 0 && !(cl->client->ps.eFlags & EF_DEAD)) { + // See which team he's on + if (cl->client->sess.sessionTeam == SIEGETEAM_TEAM1) { team1ClNum++; - } - else - { + } else { team2ClNum++; } } @@ -284,248 +223,188 @@ void multi_trigger( gentity_t *ent, gentity_t *activator ) i++; } - if (!team1ClNum && !team2ClNum) - { //no one in the box? How did we get activated? Oh well. + if (!team1ClNum && !team2ClNum) { // no one in the box? How did we get activated? Oh well. return; } - if (team1ClNum == team2ClNum) - { //if equal numbers the ownership will remain the same as it is now + if (team1ClNum == team2ClNum) { // if equal numbers the ownership will remain the same as it is now return; } - //decide who owns it now - if (team1ClNum > team2ClNum) - { + // decide who owns it now + if (team1ClNum > team2ClNum) { newOwningTeam = SIEGETEAM_TEAM1; - } - else - { + } else { newOwningTeam = SIEGETEAM_TEAM2; } - if (owningTeam == newOwningTeam) - { //it's the same one it already was, don't care then. + if (owningTeam == newOwningTeam) { // it's the same one it already was, don't care then. return; } - //Set the new owner and set the variable which will tell us to activate a team-specific target + // Set the new owner and set the variable which will tell us to activate a team-specific target ent->genericValue3 = newOwningTeam; ent->genericValue4 = newOwningTeam; } - if (haltTrigger) - { //This is an objective trigger and the activator is not carrying an objective item that matches the targetname. + if (haltTrigger) { // This is an objective trigger and the activator is not carrying an objective item that matches the targetname. return; } - if ( ent->nextthink > level.time ) - { - if( ent->spawnflags & 2048 ) // MULTIPLE - allow multiple entities to touch this trigger in a single frame + if (ent->nextthink > level.time) { + if (ent->spawnflags & 2048) // MULTIPLE - allow multiple entities to touch this trigger in a single frame { - if ( ent->painDebounceTime && ent->painDebounceTime != level.time ) - {//this should still allow subsequent ents to fire this trigger in the current frame - return; // can't retrigger until the wait is over + if (ent->painDebounceTime && + ent->painDebounceTime != level.time) { // this should still allow subsequent ents to fire this trigger in the current frame + return; // can't retrigger until the wait is over } - } - else - { + } else { return; } - } // if the player has already activated this trigger this frame - if( activator && activator->s.number < MAX_CLIENTS && ent->aimDebounceTime == level.time ) - { + if (activator && activator->s.number < MAX_CLIENTS && ent->aimDebounceTime == level.time) { return; } - if ( ent->flags & FL_INACTIVE ) - {//Not active at this time + if (ent->flags & FL_INACTIVE) { // Not active at this time return; } ent->activator = activator; - if(ent->delay && ent->painDebounceTime < (level.time + ent->delay) ) - {//delay before firing trigger + if (ent->delay && ent->painDebounceTime < (level.time + ent->delay)) { // delay before firing trigger ent->think = multi_trigger_run; ent->nextthink = level.time + ent->delay; ent->painDebounceTime = level.time; - } - else - { - multi_trigger_run (ent); + } else { + multi_trigger_run(ent); } } -void Use_Multi( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ - multi_trigger( ent, activator ); -} +void Use_Multi(gentity_t *ent, gentity_t *other, gentity_t *activator) { multi_trigger(ent, activator); } -qboolean G_PointInBounds( vec3_t point, vec3_t mins, vec3_t maxs ); +qboolean G_PointInBounds(vec3_t point, vec3_t mins, vec3_t maxs); -void Touch_Multi( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if( !other->client ) - { +void Touch_Multi(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other->client) { return; } - if ( self->flags & FL_INACTIVE ) - {//set by target_deactivate + if (self->flags & FL_INACTIVE) { // set by target_deactivate return; } - if( self->alliedTeam ) - { - if ( other->client->sess.sessionTeam != self->alliedTeam ) - { + if (self->alliedTeam) { + if (other->client->sess.sessionTeam != self->alliedTeam) { return; } } -// moved to just above multi_trigger because up here it just checks if the trigger is not being touched -// we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" -// if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) -// {//We're waiting to fire our target2 first -// self->nextthink = level.time + self->speed; -// return; -// } + // moved to just above multi_trigger because up here it just checks if the trigger is not being touched + // we want it to check any conditions set on the trigger, if one of those isn't met, the trigger is considered to be "cleared" + // if ( self->e_ThinkFunc == thinkF_trigger_cleared_fire ) + // {//We're waiting to fire our target2 first + // self->nextthink = level.time + self->speed; + // return; + // } - if ( self->spawnflags & 1 ) - { - if ( other->s.eType == ET_NPC ) - { + if (self->spawnflags & 1) { + if (other->s.eType == ET_NPC) { return; } - } - else - { - if ( self->spawnflags & 16 ) - {//NPCONLY - if ( other->NPC == NULL ) - { + } else { + if (self->spawnflags & 16) { // NPCONLY + if (other->NPC == NULL) { return; } } - if ( self->NPC_targetname && self->NPC_targetname[0] ) - { - if ( other->script_targetname && other->script_targetname[0] ) - { - if ( Q_stricmp( self->NPC_targetname, other->script_targetname ) != 0 ) - {//not the right guy to fire me off + if (self->NPC_targetname && self->NPC_targetname[0]) { + if (other->script_targetname && other->script_targetname[0]) { + if (Q_stricmp(self->NPC_targetname, other->script_targetname) != 0) { // not the right guy to fire me off return; } - } - else - { + } else { return; } } } - if ( self->spawnflags & 2 ) - {//FACING - vec3_t forward; + if (self->spawnflags & 2) { // FACING + vec3_t forward; - AngleVectors( other->client->ps.viewangles, forward, NULL, NULL ); + AngleVectors(other->client->ps.viewangles, forward, NULL, NULL); - if ( DotProduct( self->movedir, forward ) < 0.5 ) - {//Not Within 45 degrees + if (DotProduct(self->movedir, forward) < 0.5) { // Not Within 45 degrees return; } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - if( !( other->client->pers.cmd.buttons & BUTTON_USE ) ) - {//not pressing use button + if (self->spawnflags & 4) { // USE_BUTTON + if (!(other->client->pers.cmd.buttons & BUTTON_USE)) { // not pressing use button return; } - if ((other->client->ps.weaponTime > 0 && other->client->ps.torsoAnim != BOTH_BUTTON_HOLD && other->client->ps.torsoAnim != BOTH_CONSOLE1) || other->health < 1 || - (other->client->ps.pm_flags & PMF_FOLLOW) || other->client->sess.sessionTeam == TEAM_SPECTATOR || - other->client->ps.forceHandExtend != HANDEXTEND_NONE) - { //player has to be free of other things to use. + if ((other->client->ps.weaponTime > 0 && other->client->ps.torsoAnim != BOTH_BUTTON_HOLD && other->client->ps.torsoAnim != BOTH_CONSOLE1) || + other->health < 1 || (other->client->ps.pm_flags & PMF_FOLLOW) || other->client->sess.sessionTeam == TEAM_SPECTATOR || + other->client->ps.forceHandExtend != HANDEXTEND_NONE) { // player has to be free of other things to use. return; } - if (self->genericValue7) - { //we have to be holding the use key in this trigger for x milliseconds before firing - if (level.gametype == GT_SIEGE && - self->idealclass && self->idealclass[0]) - { //only certain classes can activate it - if (!other || - !other->client || - other->client->siegeClass < 0) - { //no class + if (self->genericValue7) { // we have to be holding the use key in this trigger for x milliseconds before firing + if (level.gametype == GT_SIEGE && self->idealclass && self->idealclass[0]) { // only certain classes can activate it + if (!other || !other->client || other->client->siegeClass < 0) { // no class return; } - if (!G_NameInTriggerClassList(bgSiegeClasses[other->client->siegeClass].name, self->idealclass)) - { //wasn't in the list + if (!G_NameInTriggerClassList(bgSiegeClasses[other->client->siegeClass].name, self->idealclass)) { // wasn't in the list return; } } - if (!G_PointInBounds( other->client->ps.origin, self->r.absmin, self->r.absmax )) - { + if (!G_PointInBounds(other->client->ps.origin, self->r.absmin, self->r.absmax)) { return; - } - else if (other->client->isHacking != self->s.number && other->s.number < MAX_CLIENTS ) - { //start the hack + } else if (other->client->isHacking != self->s.number && other->s.number < MAX_CLIENTS) { // start the hack other->client->isHacking = self->s.number; VectorCopy(other->client->ps.viewangles, other->client->hackingAngles); other->client->ps.hackingTime = level.time + self->genericValue7; other->client->ps.hackingBaseTime = self->genericValue7; - if (other->client->ps.hackingBaseTime > 60000) - { //don't allow a bit overflow + if (other->client->ps.hackingBaseTime > 60000) { // don't allow a bit overflow other->client->ps.hackingTime = level.time + 60000; other->client->ps.hackingBaseTime = 60000; } return; - } - else if (other->client->ps.hackingTime < level.time) - { //finished with the hack, reset the hacking values and let it fall through - other->client->isHacking = 0; //can't hack a client + } else if (other->client->ps.hackingTime < level.time) { // finished with the hack, reset the hacking values and let it fall through + other->client->isHacking = 0; // can't hack a client other->client->ps.hackingTime = 0; - } - else - { //hack in progress + } else { // hack in progress return; } } } - if ( self->spawnflags & 8 ) - {//FIRE_BUTTON - if( !( other->client->pers.cmd.buttons & BUTTON_ATTACK ) && - !( other->client->pers.cmd.buttons & BUTTON_ALT_ATTACK ) ) - {//not pressing fire button or altfire button + if (self->spawnflags & 8) { // FIRE_BUTTON + if (!(other->client->pers.cmd.buttons & BUTTON_ATTACK) && + !(other->client->pers.cmd.buttons & BUTTON_ALT_ATTACK)) { // not pressing fire button or altfire button return; } } - if ( self->radius ) - { - vec3_t eyeSpot; + if (self->radius) { + vec3_t eyeSpot; - //Only works if your head is in it, but we allow leaning out - //NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this - //to be reliant on the physical model the player uses. + // Only works if your head is in it, but we allow leaning out + // NOTE: We don't use CalcEntitySpot SPOT_HEAD because we don't want this + // to be reliant on the physical model the player uses. VectorCopy(other->client->ps.origin, eyeSpot); eyeSpot[2] += other->client->ps.viewheight; - if ( G_PointInBounds( eyeSpot, self->r.absmin, self->r.absmax ) ) - { - if( !( other->client->pers.cmd.buttons & BUTTON_ATTACK ) && - !( other->client->pers.cmd.buttons & BUTTON_ALT_ATTACK ) ) - {//not attacking, so hiding bonus + if (G_PointInBounds(eyeSpot, self->r.absmin, self->r.absmax)) { + if (!(other->client->pers.cmd.buttons & BUTTON_ATTACK) && !(other->client->pers.cmd.buttons & BUTTON_ALT_ATTACK)) { // not attacking, so hiding + // bonus /* //FIXME: should really have sound events clear the hiddenDist other->client->hiddenDist = self->radius; @@ -539,42 +418,34 @@ void Touch_Multi( gentity_t *self, gentity_t *other, trace_t *trace ) VectorClear( other->client->hiddenDir ); } */ - //Not using this, at least not yet. + // Not using this, at least not yet. } } } - if ( self->spawnflags & 4 ) - {//USE_BUTTON - if (other->client->ps.torsoAnim != BOTH_BUTTON_HOLD && - other->client->ps.torsoAnim != BOTH_CONSOLE1) - { - G_SetAnim( other, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); - } - else - { + if (self->spawnflags & 4) { // USE_BUTTON + if (other->client->ps.torsoAnim != BOTH_BUTTON_HOLD && other->client->ps.torsoAnim != BOTH_CONSOLE1) { + G_SetAnim(other, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + } else { other->client->ps.torsoTimer = 500; } other->client->ps.weaponTime = other->client->ps.torsoTimer; } - if ( self->think == trigger_cleared_fire ) - {//We're waiting to fire our target2 first + if (self->think == trigger_cleared_fire) { // We're waiting to fire our target2 first self->nextthink = level.time + self->speed; return; } - multi_trigger( self, other ); + multi_trigger(self, other); } -void trigger_cleared_fire (gentity_t *self) -{ - G_UseTargets2( self, self->activator, self->target2 ); +void trigger_cleared_fire(gentity_t *self) { + G_UseTargets2(self, self->activator, self->target2); self->think = 0; // should start the wait timer now, because the trigger's just been cleared, so we must "wait" from this point - if ( self->wait > 0 ) - { - self->nextthink = level.time + ( self->wait + self->random * Q_flrand(-1.0f, 1.0f) ) * 1000; + if (self->wait > 0) { + self->nextthink = level.time + (self->wait + self->random * Q_flrand(-1.0f, 1.0f)) * 1000; } } @@ -590,8 +461,10 @@ MULTIPLE - multiple entities can touch this trigger in a single frame *and* if n "wait" Seconds between triggerings, 0 default, number < 0 means one time only. "random" wait variance, default is 0 "delay" how many seconds to wait to fire targets after tripped -"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but not standing should be 48 tall. -"target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') +"hiderange" As long as NPC's head is in this trigger, NPCs out of this hiderange cannot see him. If you set an angle on the trigger, they're only hidden from +enemies looking in that direction. the player's crouch viewheight is 36, his standing viewheight is 54. So a trigger thast should hide you when crouched but +not standing should be 48 tall. "target2" The trigger will fire this only when the trigger has been activated and subsequently 'cleared'( once any of the +conditions on the trigger have not been satisfied). This will not fire the "target" more than once until the "target2" is fired (trigger field is 'cleared') "speed" How many seconds to wait to fire the target2, default is 1 "noise" Sound to play when the trigger fires (plays at activator's origin) "NPC_targetname" Only the NPC with this NPC_targetname fires this trigger @@ -625,58 +498,48 @@ idealclass - Can only be used by this class/these classes. You can specify use b multiple classes with the use of |, e.g.: "Imperial Medic|Imperial Assassin|Imperial Demolitionist" */ -void SP_trigger_multiple( gentity_t *ent ) -{ - char *s; - if ( G_SpawnString( "noise", "", &s ) ) - { - if (s && s[0]) - { +void SP_trigger_multiple(gentity_t *ent) { + char *s; + if (G_SpawnString("noise", "", &s)) { + if (s && s[0]) { ent->noise_index = G_SoundIndex(s); - } - else - { + } else { ent->noise_index = 0; } } G_SpawnInt("usetime", "0", &ent->genericValue7); - //For siege gametype + // For siege gametype G_SpawnInt("siegetrig", "0", &ent->genericValue1); - G_SpawnInt("teambalance", "0", &ent->genericValue2); + G_SpawnInt("teambalance", "0", &ent->genericValue2); G_SpawnInt("delay", "0", &ent->delay); - if ( (ent->wait > 0) && (ent->random >= ent->wait) ) { + if ((ent->wait > 0) && (ent->random >= ent->wait)) { ent->random = ent->wait - FRAMETIME; - Com_Printf(S_COLOR_YELLOW"trigger_multiple has random >= wait\n"); + Com_Printf(S_COLOR_YELLOW "trigger_multiple has random >= wait\n"); } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec - if ( !ent->speed && ent->target2 && ent->target2[0] ) - { + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec + if (!ent->speed && ent->target2 && ent->target2[0]) { ent->speed = 1000; - } - else - { + } else { ent->speed *= 1000; } ent->touch = Touch_Multi; - ent->use = Use_Multi; + ent->use = Use_Multi; - if ( ent->team && ent->team[0] ) - { + if (ent->team && ent->team[0]) { ent->alliedTeam = atoi(ent->team); ent->team = NULL; } - InitTrigger( ent ); - trap->LinkEntity ((sharedEntity_t *)ent); + InitTrigger(ent); + trap->LinkEntity((sharedEntity_t *)ent); } - /*QUAKED trigger_once (.5 1 .5) ? CLIENTONLY FACING USE_BUTTON FIRE_BUTTON x x x INACTIVE MULTIPLE CLIENTONLY - only a player can trigger this by touch FACING - Won't fire unless triggering ent's view angles are within 45 degrees of trigger's angles (in addition to any other conditions) @@ -712,24 +575,19 @@ idealclass - Can only be used by this class/these classes. You can specify use b multiple classes with the use of |, e.g.: "Imperial Medic|Imperial Assassin|Imperial Demolitionist" */ -void SP_trigger_once( gentity_t *ent ) -{ - char *s; - if ( G_SpawnString( "noise", "", &s ) ) - { - if (s && s[0]) - { +void SP_trigger_once(gentity_t *ent) { + char *s; + if (G_SpawnString("noise", "", &s)) { + if (s && s[0]) { ent->noise_index = G_SoundIndex(s); - } - else - { + } else { ent->noise_index = 0; } } G_SpawnInt("usetime", "0", &ent->genericValue7); - //For siege gametype + // For siege gametype G_SpawnInt("siegetrig", "0", &ent->genericValue1); G_SpawnInt("delay", "0", &ent->delay); @@ -737,18 +595,17 @@ void SP_trigger_once( gentity_t *ent ) ent->wait = -1; ent->touch = Touch_Multi; - ent->use = Use_Multi; + ent->use = Use_Multi; - if ( ent->team && ent->team[0] ) - { + if (ent->team && ent->team[0]) { ent->alliedTeam = atoi(ent->team); ent->team = NULL; } - ent->delay *= 1000;//1 = 1 msec, 1000 = 1 sec + ent->delay *= 1000; // 1 = 1 msec, 1000 = 1 sec - InitTrigger( ent ); - trap->LinkEntity ((sharedEntity_t *)ent); + InitTrigger(ent); + trap->LinkEntity((sharedEntity_t *)ent); } /* @@ -756,49 +613,43 @@ void SP_trigger_once( gentity_t *ent ) trigger_lightningstrike -rww ====================================================================== */ -//lightning strike trigger lightning strike event -void Do_Strike(gentity_t *ent) -{ +// lightning strike trigger lightning strike event +void Do_Strike(gentity_t *ent) { trace_t localTrace; vec3_t strikeFrom; vec3_t strikePoint; vec3_t fxAng; - //maybe allow custom fx direction at some point? + // maybe allow custom fx direction at some point? VectorSet(fxAng, 90.0f, 0.0f, 0.0f); - //choose a random point to strike within the bounds of the trigger + // choose a random point to strike within the bounds of the trigger strikePoint[0] = flrand(ent->r.absmin[0], ent->r.absmax[0]); strikePoint[1] = flrand(ent->r.absmin[1], ent->r.absmax[1]); - //consider the bottom mins the ground level + // consider the bottom mins the ground level strikePoint[2] = ent->r.absmin[2]; - //set the from point + // set the from point strikeFrom[0] = strikePoint[0]; strikeFrom[1] = strikePoint[1]; - strikeFrom[2] = ent->r.absmax[2]-4.0f; + strikeFrom[2] = ent->r.absmax[2] - 4.0f; - //now trace for damaging stuff, and do the effect + // now trace for damaging stuff, and do the effect trap->Trace(&localTrace, strikeFrom, NULL, NULL, strikePoint, ent->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); VectorCopy(localTrace.endpos, strikePoint); - if (localTrace.startsolid || localTrace.allsolid) - { //got a bad spot, think again next frame to try another strike + if (localTrace.startsolid || localTrace.allsolid) { // got a bad spot, think again next frame to try another strike ent->nextthink = level.time; return; } - if (ent->radius) - { //do a radius damage at the end pos + if (ent->radius) { // do a radius damage at the end pos G_RadiusDamage(strikePoint, ent, ent->damage, ent->radius, ent, NULL, MOD_SUICIDE); - } - else - { //only damage individuals + } else { // only damage individuals gentity_t *trHit = &g_entities[localTrace.entityNum]; - if (trHit->inuse && trHit->takedamage) - { //damage it then + if (trHit->inuse && trHit->takedamage) { // damage it then G_Damage(trHit, ent, ent, NULL, trHit->r.currentOrigin, ent->damage, 0, MOD_SUICIDE); } } @@ -806,11 +657,9 @@ void Do_Strike(gentity_t *ent) G_PlayEffectID(ent->genericValue2, strikeFrom, fxAng); } -//lightning strike trigger think loop -void Think_Strike(gentity_t *ent) -{ - if (ent->genericValue1) - { //turned off currently +// lightning strike trigger think loop +void Think_Strike(gentity_t *ent) { + if (ent->genericValue1) { // turned off currently return; } @@ -818,13 +667,11 @@ void Think_Strike(gentity_t *ent) Do_Strike(ent); } -//lightning strike trigger use event function -void Use_Strike( gentity_t *ent, gentity_t *other, gentity_t *activator ) -{ +// lightning strike trigger use event function +void Use_Strike(gentity_t *ent, gentity_t *other, gentity_t *activator) { ent->genericValue1 = !ent->genericValue1; - if (!ent->genericValue1) - { //turn it back on + if (!ent->genericValue1) { // turn it back on ent->nextthink = level.time; } } @@ -842,8 +689,7 @@ START_OFF - start trigger disabled use to toggle on and off */ -void SP_trigger_lightningstrike( gentity_t *ent ) -{ +void SP_trigger_lightningstrike(gentity_t *ent) { char *s; ent->use = Use_Strike; @@ -851,37 +697,31 @@ void SP_trigger_lightningstrike( gentity_t *ent ) ent->nextthink = level.time + 500; G_SpawnString("lightningfx", "", &s); - if (!s || !s[0]) - { + if (!s || !s[0]) { Com_Error(ERR_DROP, "trigger_lightningstrike with no lightningfx"); } - //get a configstring index for it + // get a configstring index for it ent->genericValue2 = G_EffectIndex(s); - if (ent->spawnflags & 1) - { //START_OFF + if (ent->spawnflags & 1) { // START_OFF ent->genericValue1 = 1; } - if (!ent->wait) - { //default 1000 + if (!ent->wait) { // default 1000 ent->wait = 1000; } - if (!ent->random) - { //default 2000 + if (!ent->random) { // default 2000 ent->random = 2000; } - if (!ent->damage) - { //default 50 + if (!ent->damage) { // default 50 ent->damage = 50; } - InitTrigger( ent ); - trap->LinkEntity ((sharedEntity_t *)ent); + InitTrigger(ent); + trap->LinkEntity((sharedEntity_t *)ent); } - /* ============================================================================== @@ -890,21 +730,20 @@ trigger_always ============================================================================== */ -void trigger_always_think( gentity_t *ent ) { +void trigger_always_think(gentity_t *ent) { G_UseTargets(ent, ent); - G_FreeEntity( ent ); + G_FreeEntity(ent); } /*QUAKED trigger_always (.5 .5 .5) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ -void SP_trigger_always (gentity_t *ent) { +void SP_trigger_always(gentity_t *ent) { // we must have some delay to make sure our use targets are present ent->nextthink = level.time + 300; ent->think = trigger_always_think; } - /* ============================================================================== @@ -912,39 +751,36 @@ trigger_push ============================================================================== */ -//trigger_push -#define PUSH_LINEAR 4 -#define PUSH_RELATIVE 16 -#define PUSH_MULTIPLE 2048 -//target_push -#define PUSH_CONSTANT 2 - -void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { - if ( self->flags & FL_INACTIVE ) - {//set by target_deactivate +// trigger_push +#define PUSH_LINEAR 4 +#define PUSH_RELATIVE 16 +#define PUSH_MULTIPLE 2048 +// target_push +#define PUSH_CONSTANT 2 + +void trigger_push_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (self->flags & FL_INACTIVE) { // set by target_deactivate return; } - if ( !(self->spawnflags&PUSH_LINEAR) ) - {//normal throw - if ( !other->client ) { + if (!(self->spawnflags & PUSH_LINEAR)) { // normal throw + if (!other->client) { return; } - BG_TouchJumpPad( &other->client->ps, &self->s ); + BG_TouchJumpPad(&other->client->ps, &self->s); return; } - //linear - if( level.time < self->painDebounceTime + self->wait ) // normal 'wait' check + // linear + if (level.time < self->painDebounceTime + self->wait) // normal 'wait' check { - if( self->spawnflags & PUSH_MULTIPLE ) // MULTIPLE - allow multiple entities to touch this trigger in one frame + if (self->spawnflags & PUSH_MULTIPLE) // MULTIPLE - allow multiple entities to touch this trigger in one frame { - if ( self->painDebounceTime && level.time > self->painDebounceTime ) // if we haven't reached the next frame continue to let ents touch the trigger + if (self->painDebounceTime && level.time > self->painDebounceTime) // if we haven't reached the next frame continue to let ents touch the trigger { return; } - } - else // only allowing one ent per frame to touch trigger + } else // only allowing one ent per frame to touch trigger { return; } @@ -989,57 +825,44 @@ void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { } */ - if ( !other->client ) { - if ( other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && VectorLengthSquared( other->s.pos.trDelta ) ) - {//already moving - VectorCopy( other->r.currentOrigin, other->s.pos.trBase ); - VectorCopy( self->s.origin2, other->s.pos.trDelta ); + if (!other->client) { + if (other->s.pos.trType != TR_STATIONARY && other->s.pos.trType != TR_LINEAR_STOP && other->s.pos.trType != TR_NONLINEAR_STOP && + VectorLengthSquared(other->s.pos.trDelta)) { // already moving + VectorCopy(other->r.currentOrigin, other->s.pos.trBase); + VectorCopy(self->s.origin2, other->s.pos.trDelta); other->s.pos.trTime = level.time; } return; } - if ( other->client->ps.pm_type != PM_NORMAL - && other->client->ps.pm_type != PM_DEAD - && other->client->ps.pm_type != PM_FREEZE ) - { + if (other->client->ps.pm_type != PM_NORMAL && other->client->ps.pm_type != PM_DEAD && other->client->ps.pm_type != PM_FREEZE) { return; } - if ( (self->spawnflags&PUSH_RELATIVE) ) - {//relative, dir to it * speed + if ((self->spawnflags & PUSH_RELATIVE)) { // relative, dir to it * speed vec3_t dir; - VectorSubtract( self->s.origin2, other->r.currentOrigin, dir ); - if ( self->speed ) - { - VectorNormalize( dir ); - VectorScale( dir, self->speed, dir ); - } - VectorCopy( dir, other->client->ps.velocity ); - } - else if ( (self->spawnflags&PUSH_LINEAR) ) - {//linear dir * speed - VectorScale( self->s.origin2, self->speed, other->client->ps.velocity ); - } - else - { - VectorCopy( self->s.origin2, other->client->ps.velocity ); + VectorSubtract(self->s.origin2, other->r.currentOrigin, dir); + if (self->speed) { + VectorNormalize(dir); + VectorScale(dir, self->speed, dir); + } + VectorCopy(dir, other->client->ps.velocity); + } else if ((self->spawnflags & PUSH_LINEAR)) { // linear dir * speed + VectorScale(self->s.origin2, self->speed, other->client->ps.velocity); + } else { + VectorCopy(self->s.origin2, other->client->ps.velocity); } - //so we don't take damage unless we land lower than we start here... + // so we don't take damage unless we land lower than we start here... /* other->client->ps.forceJumpZStart = 0; other->client->ps.pm_flags |= PMF_TRIGGER_PUSHED;//pushed by a trigger other->client->ps.jumpZStart = other->client->ps.origin[2]; */ - if ( self->wait == -1 ) - { + if (self->wait == -1) { self->touch = NULL; - } - else if ( self->wait > 0 ) - { + } else if (self->wait > 0) { self->painDebounceTime = level.time; - } /* if( other && !other->s.number ) @@ -1049,7 +872,6 @@ void trigger_push_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { */ } - /* ================= AimAtTarget @@ -1057,81 +879,75 @@ AimAtTarget Calculate origin2 so the target apogee will be hit ================= */ -void AimAtTarget( gentity_t *self ) { - gentity_t *ent; - vec3_t origin; - float height, gravity, time, forward; - float dist; - - VectorAdd( self->r.absmin, self->r.absmax, origin ); - VectorScale ( origin, 0.5f, origin ); - - ent = G_PickTarget( self->target ); - if ( !ent ) { - G_FreeEntity( self ); +void AimAtTarget(gentity_t *self) { + gentity_t *ent; + vec3_t origin; + float height, gravity, time, forward; + float dist; + + VectorAdd(self->r.absmin, self->r.absmax, origin); + VectorScale(origin, 0.5f, origin); + + ent = G_PickTarget(self->target); + if (!ent) { + G_FreeEntity(self); return; } - if ( self->classname && !Q_stricmp( "trigger_push", self->classname ) ) - { - if ( (self->spawnflags&PUSH_RELATIVE) ) - {//relative, not an arc or linear - VectorCopy( ent->r.currentOrigin, self->s.origin2 ); + if (self->classname && !Q_stricmp("trigger_push", self->classname)) { + if ((self->spawnflags & PUSH_RELATIVE)) { // relative, not an arc or linear + VectorCopy(ent->r.currentOrigin, self->s.origin2); return; - } - else if ( (self->spawnflags&PUSH_LINEAR) ) - {//linear, not an arc - VectorSubtract( ent->r.currentOrigin, origin, self->s.origin2 ); - VectorNormalize( self->s.origin2 ); + } else if ((self->spawnflags & PUSH_LINEAR)) { // linear, not an arc + VectorSubtract(ent->r.currentOrigin, origin, self->s.origin2); + VectorNormalize(self->s.origin2); return; } } - if ( self->classname && !Q_stricmp( "target_push", self->classname ) ) - { - if( self->spawnflags & PUSH_CONSTANT ) - { - VectorSubtract ( ent->s.origin, self->s.origin, self->s.origin2 ); - VectorNormalize( self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + if (self->classname && !Q_stricmp("target_push", self->classname)) { + if (self->spawnflags & PUSH_CONSTANT) { + VectorSubtract(ent->s.origin, self->s.origin, self->s.origin2); + VectorNormalize(self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); return; } } height = ent->s.origin[2] - origin[2]; gravity = g_gravity.value; - time = sqrt( height / ( .5 * gravity ) ); - if ( !time ) { - G_FreeEntity( self ); + time = sqrt(height / (.5 * gravity)); + if (!time) { + G_FreeEntity(self); return; } // set s.origin2 to the push velocity - VectorSubtract ( ent->s.origin, origin, self->s.origin2 ); + VectorSubtract(ent->s.origin, origin, self->s.origin2); self->s.origin2[2] = 0; - dist = VectorNormalize( self->s.origin2); + dist = VectorNormalize(self->s.origin2); forward = dist / time; - VectorScale( self->s.origin2, forward, self->s.origin2 ); + VectorScale(self->s.origin2, forward, self->s.origin2); self->s.origin2[2] = time * gravity; } - /*QUAKED trigger_push (.5 .5 .5) ? x x LINEAR x RELATIVE x x INACTIVE MULTIPLE Must point at a target_position, which will be the apex of the leap. This will be client side predicted, unlike target_push LINEAR - Instead of tossing the client at the target_position, it will push them towards it. Must set a "speed" (see below) -RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the target_position, it pushes *you* toward the target position, relative to your current location (can use with "speed"... if don't set a speed, it will use the distance from you to the target_position) -INACTIVE - not active until targeted by a target_activate -MULTIPLE - multiple entities can touch this trigger in a single frame *and* if needed, the trigger can have a wait of > 0 +RELATIVE - instead of pushing you in a direction that is always from the center of the trigger to the target_position, it pushes *you* toward the target +position, relative to your current location (can use with "speed"... if don't set a speed, it will use the distance from you to the target_position) INACTIVE - +not active until targeted by a target_activate MULTIPLE - multiple entities can touch this trigger in a single frame *and* if needed, the trigger can have a +wait of > 0 wait - how long to wait between pushes: -1 = push only once speed - when used with the LINEAR spawnflag, pushes the client toward the position at a constant speed (default is 1000) */ -void SP_trigger_push( gentity_t *self ) { - InitTrigger (self); +void SP_trigger_push(gentity_t *self) { + InitTrigger(self); // unlike other triggers, we need to send this one to the client self->r.svFlags &= ~SVF_NOCLIENT; @@ -1141,40 +957,37 @@ void SP_trigger_push( gentity_t *self ) { self->s.eType = ET_PUSH_TRIGGER; - if ( !(self->spawnflags&2) ) - {//start on + if (!(self->spawnflags & 2)) { // start on self->touch = trigger_push_touch; } - if ( self->spawnflags & 4 ) - {//linear + if (self->spawnflags & 4) { // linear self->speed = 1000; } self->think = AimAtTarget; self->nextthink = level.time + FRAMETIME; - trap->LinkEntity ((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } -void Use_target_push( gentity_t *self, gentity_t *other, gentity_t *activator ) { - if ( !activator->client ) { +void Use_target_push(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!activator->client) { return; } - if ( activator->client->ps.pm_type != PM_NORMAL && activator->client->ps.pm_type != PM_FLOAT ) { + if (activator->client->ps.pm_type != PM_NORMAL && activator->client->ps.pm_type != PM_FLOAT) { return; } - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - VectorCopy (self->s.origin2, activator->client->ps.velocity); + VectorCopy(self->s.origin2, activator->client->ps.velocity); // play fly sound every 1.5 seconds - if ( activator->fly_sound_debounce_time < level.time ) { + if (activator->fly_sound_debounce_time < level.time) { activator->fly_sound_debounce_time = level.time + 1500; - if (self->noise_index) - { - G_Sound( activator, CHAN_AUTO, self->noise_index ); + if (self->noise_index) { + G_Sound(activator, CHAN_AUTO, self->noise_index); } } } @@ -1186,21 +999,21 @@ Pushes the activator in the direction.of angle, or towards a target apex. "speed" defaults to 1000 if "bouncepad", play bounce noise instead of none */ -void SP_target_push( gentity_t *self ) { +void SP_target_push(gentity_t *self) { if (!self->speed) { self->speed = 1000; } - G_SetMovedir (self->s.angles, self->s.origin2); - VectorScale (self->s.origin2, self->speed, self->s.origin2); + G_SetMovedir(self->s.angles, self->s.origin2); + VectorScale(self->s.origin2, self->speed, self->s.origin2); - if ( self->spawnflags & 1 ) { + if (self->spawnflags & 1) { self->noise_index = G_SoundIndex("sound/weapons/force/jump.wav"); } else { - self->noise_index = 0; //G_SoundIndex("sound/misc/windfly.wav"); + self->noise_index = 0; // G_SoundIndex("sound/misc/windfly.wav"); } - if ( self->target ) { - VectorCopy( self->s.origin, self->r.absmin ); - VectorCopy( self->s.origin, self->r.absmax ); + if (self->target) { + VectorCopy(self->s.origin, self->r.absmin); + VectorCopy(self->s.origin, self->r.absmax); self->think = AimAtTarget; self->nextthink = level.time + FRAMETIME; } @@ -1215,37 +1028,33 @@ trigger_teleport ============================================================================== */ -void trigger_teleporter_touch (gentity_t *self, gentity_t *other, trace_t *trace ) { - gentity_t *dest; +void trigger_teleporter_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *dest; - if ( self->flags & FL_INACTIVE ) - {//set by target_deactivate + if (self->flags & FL_INACTIVE) { // set by target_deactivate return; } - if ( !other->client ) { + if (!other->client) { return; } - if ( other->client->ps.pm_type == PM_DEAD ) { + if (other->client->ps.pm_type == PM_DEAD) { return; } // Spectators only? - if ( ( self->spawnflags & 1 ) && - other->client->sess.sessionTeam != TEAM_SPECTATOR ) { + if ((self->spawnflags & 1) && other->client->sess.sessionTeam != TEAM_SPECTATOR) { return; } - - dest = G_PickTarget( self->target ); + dest = G_PickTarget(self->target); if (!dest) { - trap->Print ("Couldn't find teleporter destination\n"); + trap->Print("Couldn't find teleporter destination\n"); return; } - TeleportPlayer( other, dest->s.origin, dest->s.angles ); + TeleportPlayer(other, dest->s.origin, dest->s.angles); } - /*QUAKED trigger_teleport (.5 .5 .5) ? SPECTATOR Allows client side prediction of teleportation events. Must point at a target_position, which will be the teleport destination. @@ -1254,12 +1063,12 @@ If spectator is set, only spectators can use this teleport Spectator teleporters are not normally placed in the editor, but are created automatically near doors to allow spectators to move through them */ -void SP_trigger_teleport( gentity_t *self ) { - InitTrigger (self); +void SP_trigger_teleport(gentity_t *self) { + InitTrigger(self); // unlike other triggers, we need to send this one to the client // unless is a spectator trigger - if ( self->spawnflags & 1 ) { + if (self->spawnflags & 1) { self->r.svFlags |= SVF_NOCLIENT; } else { self->r.svFlags &= ~SVF_NOCLIENT; @@ -1271,10 +1080,9 @@ void SP_trigger_teleport( gentity_t *self ) { self->s.eType = ET_TELEPORT_TRIGGER; self->touch = trigger_teleporter_touch; - trap->LinkEntity ((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } - /* ============================================================================== @@ -1298,70 +1106,59 @@ NO_PROTECTION *nothing* stops the damage If dmg is set to -1 this brush will use the fade-kill method */ -void hurt_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { - if (activator && activator->inuse && activator->client) - { +void hurt_use(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (activator && activator->inuse && activator->client) { self->activator = activator; - } - else - { + } else { self->activator = NULL; } - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); - if ( self->r.linked ) { - trap->UnlinkEntity( (sharedEntity_t *)self ); + if (self->r.linked) { + trap->UnlinkEntity((sharedEntity_t *)self); } else { - trap->LinkEntity( (sharedEntity_t *)self ); + trap->LinkEntity((sharedEntity_t *)self); } } -void hurt_touch( gentity_t *self, gentity_t *other, trace_t *trace ) { - int dflags; +void hurt_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + int dflags; - if (level.gametype == GT_SIEGE && self->team && self->team[0]) - { + if (level.gametype == GT_SIEGE && self->team && self->team[0]) { int team = atoi(self->team); - if (other->inuse && other->s.number < MAX_CLIENTS && other->client && - other->client->sess.sessionTeam != team) - { //real client don't hurt + if (other->inuse && other->s.number < MAX_CLIENTS && other->client && other->client->sess.sessionTeam != team) { // real client don't hurt return; - } - else if (other->inuse && other->client && other->s.eType == ET_NPC && - other->s.NPC_class == CLASS_VEHICLE && other->s.teamowner != team) - { //vehicle owned by team don't hurt + } else if (other->inuse && other->client && other->s.eType == ET_NPC && other->s.NPC_class == CLASS_VEHICLE && + other->s.teamowner != team) { // vehicle owned by team don't hurt return; } } - if ( self->flags & FL_INACTIVE ) - {//set by target_deactivate + if (self->flags & FL_INACTIVE) { // set by target_deactivate return; } - if ( !other->takedamage ) { + if (!other->takedamage) { return; } - if ( self->timestamp > level.time ) { + if (self->timestamp > level.time) { return; } - if (self->damage == -1 && other && other->client && other->health < 1) - { + if (self->damage == -1 && other && other->client && other->health < 1) { other->client->ps.fallingToDeath = 0; ClientRespawn(other); return; } - if (self->damage == -1 && other && other->client && other->client->ps.fallingToDeath) - { + if (self->damage == -1 && other && other->client && other->client->ps.fallingToDeath) { return; } - if ( self->spawnflags & 16 ) { + if (self->spawnflags & 16) { self->timestamp = level.time + 1000; } else { self->timestamp = level.time + FRAMETIME; @@ -1379,116 +1176,97 @@ void hurt_touch( gentity_t *self, gentity_t *other, trace_t *trace ) { else dflags = 0; - if (self->damage == -1 && other && other->client) - { - if (other->client->ps.otherKillerTime > level.time) - { //we're as good as dead, so if someone pushed us into this then remember them + if (self->damage == -1 && other && other->client) { + if (other->client->ps.otherKillerTime > level.time) { // we're as good as dead, so if someone pushed us into this then remember them other->client->ps.otherKillerTime = level.time + 20000; other->client->ps.otherKillerDebounceTime = level.time + 10000; } other->client->ps.fallingToDeath = level.time; - //rag on the way down, this flag will automatically be cleared for us on respawn + // rag on the way down, this flag will automatically be cleared for us on respawn other->client->ps.eFlags |= EF_RAG; - //make sure his jetpack is off + // make sure his jetpack is off Jetpack_Off(other); - if (other->NPC) - { //kill it now + if (other->NPC) { // kill it now vec3_t vDir; VectorSet(vDir, 0, 1, 0); G_Damage(other, other, other, vDir, other->client->ps.origin, Q3_INFINITE, 0, MOD_FALLING); - } - else - { + } else { G_EntitySound(other, CHAN_VOICE, G_SoundIndex("*falling1.wav")); } - self->timestamp = 0; //do not ignore others - } - else - { + self->timestamp = 0; // do not ignore others + } else { int dmg = self->damage; - if (dmg == -1) - { //so fall-to-blackness triggers destroy evertyhing + if (dmg == -1) { // so fall-to-blackness triggers destroy evertyhing dmg = 99999; self->timestamp = 0; } - if (self->activator && self->activator->inuse && self->activator->client) - { - G_Damage (other, self->activator, self->activator, NULL, NULL, dmg, dflags|DAMAGE_NO_PROTECTION, MOD_TRIGGER_HURT); - } - else - { - G_Damage (other, self, self, NULL, NULL, dmg, dflags|DAMAGE_NO_PROTECTION, MOD_TRIGGER_HURT); + if (self->activator && self->activator->inuse && self->activator->client) { + G_Damage(other, self->activator, self->activator, NULL, NULL, dmg, dflags | DAMAGE_NO_PROTECTION, MOD_TRIGGER_HURT); + } else { + G_Damage(other, self, self, NULL, NULL, dmg, dflags | DAMAGE_NO_PROTECTION, MOD_TRIGGER_HURT); } } } -void SP_trigger_hurt( gentity_t *self ) { - InitTrigger (self); +void SP_trigger_hurt(gentity_t *self) { + InitTrigger(self); gTrigFallSound = G_SoundIndex("*falling1.wav"); - self->noise_index = G_SoundIndex( "sound/weapons/force/speed.wav" ); + self->noise_index = G_SoundIndex("sound/weapons/force/speed.wav"); self->touch = hurt_touch; - if ( !self->damage ) { + if (!self->damage) { self->damage = 5; } self->r.contents = CONTENTS_TRIGGER; - if ( self->spawnflags & 2 ) { + if (self->spawnflags & 2) { self->use = hurt_use; } // link in to the world if starting active - if ( ! (self->spawnflags & 1) ) { - trap->LinkEntity ((sharedEntity_t *)self); - } - else if (self->r.linked) - { + if (!(self->spawnflags & 1)) { + trap->LinkEntity((sharedEntity_t *)self); + } else if (self->r.linked) { trap->UnlinkEntity((sharedEntity_t *)self); } } -#define INITIAL_SUFFOCATION_DELAY 500 //.5 seconds -void space_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ - if (!other || !other->inuse || !other->client ) - //NOTE: we need vehicles to know this, too... - //|| other->s.number >= MAX_CLIENTS) +#define INITIAL_SUFFOCATION_DELAY 500 //.5 seconds +void space_touch(gentity_t *self, gentity_t *other, trace_t *trace) { + if (!other || !other->inuse || !other->client) + // NOTE: we need vehicles to know this, too... + //|| other->s.number >= MAX_CLIENTS) { return; } - if ( other->s.number < MAX_CLIENTS//player - && other->client->ps.m_iVehicleNum//in a vehicle - && other->client->ps.m_iVehicleNum >= MAX_CLIENTS ) - {//a player client inside a vehicle + if (other->s.number < MAX_CLIENTS // player + && other->client->ps.m_iVehicleNum // in a vehicle + && other->client->ps.m_iVehicleNum >= MAX_CLIENTS) { // a player client inside a vehicle gentity_t *veh = &g_entities[other->client->ps.m_iVehicleNum]; if (veh->inuse && veh->client && veh->m_pVehicle && - veh->m_pVehicle->m_pVehicleInfo->hideRider) - { //if they are "inside" a vehicle, then let that protect them from THE HORRORS OF SPACE. + veh->m_pVehicle->m_pVehicleInfo->hideRider) { // if they are "inside" a vehicle, then let that protect them from THE HORRORS OF SPACE. other->client->inSpaceSuffocation = 0; other->client->inSpaceIndex = ENTITYNUM_NONE; return; } } - if (!G_PointInBounds(other->client->ps.origin, self->r.absmin, self->r.absmax)) - { //his origin must be inside the trigger + if (!G_PointInBounds(other->client->ps.origin, self->r.absmin, self->r.absmax)) { // his origin must be inside the trigger return; } - if (!other->client->inSpaceIndex || - other->client->inSpaceIndex == ENTITYNUM_NONE) - { //freshly entering space + if (!other->client->inSpaceIndex || other->client->inSpaceIndex == ENTITYNUM_NONE) { // freshly entering space other->client->inSpaceSuffocation = level.time + INITIAL_SUFFOCATION_DELAY; } @@ -1499,82 +1277,68 @@ void space_touch( gentity_t *self, gentity_t *other, trace_t *trace ) causes human clients to suffocate and have no gravity. */ -void SP_trigger_space(gentity_t *self) -{ +void SP_trigger_space(gentity_t *self) { InitTrigger(self); self->r.contents = CONTENTS_TRIGGER; self->touch = space_touch; - trap->LinkEntity((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } -void shipboundary_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void shipboundary_touch(gentity_t *self, gentity_t *other, trace_t *trace) { gentity_t *ent; - if (!other || !other->inuse || !other->client || - other->s.number < MAX_CLIENTS || - !other->m_pVehicle) - { //only let vehicles touch + if (!other || !other->inuse || !other->client || other->s.number < MAX_CLIENTS || !other->m_pVehicle) { // only let vehicles touch return; } - if ( other->client->ps.hyperSpaceTime && level.time - other->client->ps.hyperSpaceTime < HYPERSPACE_TIME ) - {//don't interfere with hyperspacing ships + if (other->client->ps.hyperSpaceTime && level.time - other->client->ps.hyperSpaceTime < HYPERSPACE_TIME) { // don't interfere with hyperspacing ships return; } - ent = G_Find (NULL, FOFS(targetname), self->target); - if (!ent || !ent->inuse) - { //this is bad - trap->Error( ERR_DROP, "trigger_shipboundary has invalid target '%s'\n", self->target ); + ent = G_Find(NULL, FOFS(targetname), self->target); + if (!ent || !ent->inuse) { // this is bad + trap->Error(ERR_DROP, "trigger_shipboundary has invalid target '%s'\n", self->target); return; } - if (!other->client->ps.m_iVehicleNum || other->m_pVehicle->m_iRemovedSurfaces) - { //if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up + if (!other->client->ps.m_iVehicleNum || + other->m_pVehicle->m_iRemovedSurfaces) { // if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up G_Damage(other, other, other, NULL, other->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); return; } - //make sure this sucker is linked so the prediction knows where to go + // make sure this sucker is linked so the prediction knows where to go trap->LinkEntity((sharedEntity_t *)ent); other->client->ps.vehTurnaroundIndex = ent->s.number; - other->client->ps.vehTurnaroundTime = level.time + (self->genericValue1*2); + other->client->ps.vehTurnaroundTime = level.time + (self->genericValue1 * 2); - //keep up the detailed checks for another 2 seconds + // keep up the detailed checks for another 2 seconds self->genericValue7 = level.time + 2000; } -void shipboundary_think(gentity_t *ent) -{ - int iEntityList[MAX_GENTITIES]; - int numListedEntities; - int i = 0; - gentity_t *listedEnt; +void shipboundary_think(gentity_t *ent) { + int iEntityList[MAX_GENTITIES]; + int numListedEntities; + int i = 0; + gentity_t *listedEnt; ent->nextthink = level.time + 100; - if (ent->genericValue7 < level.time) - { //don't need to be doing this check, no one has touched recently + if (ent->genericValue7 < level.time) { // don't need to be doing this check, no one has touched recently return; } - numListedEntities = trap->EntitiesInBox( ent->r.absmin, ent->r.absmax, iEntityList, MAX_GENTITIES ); - while (i < numListedEntities) - { + numListedEntities = trap->EntitiesInBox(ent->r.absmin, ent->r.absmax, iEntityList, MAX_GENTITIES); + while (i < numListedEntities) { listedEnt = &g_entities[iEntityList[i]]; - if (listedEnt->inuse && listedEnt->client && listedEnt->client->ps.m_iVehicleNum) - { - if (listedEnt->s.eType == ET_NPC && - listedEnt->s.NPC_class == CLASS_VEHICLE) - { + if (listedEnt->inuse && listedEnt->client && listedEnt->client->ps.m_iVehicleNum) { + if (listedEnt->s.eType == ET_NPC && listedEnt->s.NPC_class == CLASS_VEHICLE) { Vehicle_t *pVeh = listedEnt->m_pVehicle; - if (pVeh && pVeh->m_pVehicleInfo->type == VH_FIGHTER) - { - shipboundary_touch(ent, listedEnt, NULL); + if (pVeh && pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + shipboundary_touch(ent, listedEnt, NULL); } } } @@ -1589,109 +1353,93 @@ causes vehicle to turn toward target and travel in that direction for a set time "traveltime" time to travel in this direction */ -void SP_trigger_shipboundary(gentity_t *self) -{ +void SP_trigger_shipboundary(gentity_t *self) { InitTrigger(self); self->r.contents = CONTENTS_TRIGGER; - if (!self->target || !self->target[0]) - { - trap->Error( ERR_DROP, "trigger_shipboundary without a target." ); + if (!self->target || !self->target[0]) { + trap->Error(ERR_DROP, "trigger_shipboundary without a target."); } G_SpawnInt("traveltime", "0", &self->genericValue1); - if (!self->genericValue1) - { - trap->Error( ERR_DROP, "trigger_shipboundary without traveltime." ); + if (!self->genericValue1) { + trap->Error(ERR_DROP, "trigger_shipboundary without traveltime."); } self->think = shipboundary_think; self->nextthink = level.time + 500; self->touch = shipboundary_touch; - trap->LinkEntity((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } -void hyperspace_touch( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void hyperspace_touch(gentity_t *self, gentity_t *other, trace_t *trace) { gentity_t *ent; - if (!other || !other->inuse || !other->client || - other->s.number < MAX_CLIENTS || - !other->m_pVehicle) - { //only let vehicles touch + if (!other || !other->inuse || !other->client || other->s.number < MAX_CLIENTS || !other->m_pVehicle) { // only let vehicles touch return; } - if ( other->client->ps.hyperSpaceTime && level.time - other->client->ps.hyperSpaceTime < HYPERSPACE_TIME ) - {//already hyperspacing, just keep us moving - if ( (other->client->ps.eFlags2&EF2_HYPERSPACE) ) - {//they've started the hyperspace but haven't been teleported yet - float timeFrac = ((float)(level.time-other->client->ps.hyperSpaceTime))/HYPERSPACE_TIME; - if ( timeFrac >= HYPERSPACE_TELEPORT_FRAC ) - {//half-way, now teleport them! - vec3_t diff, fwd, right, up, newOrg; - float fDiff, rDiff, uDiff; - //take off the flag so we only do this once + if (other->client->ps.hyperSpaceTime && level.time - other->client->ps.hyperSpaceTime < HYPERSPACE_TIME) { // already hyperspacing, just keep us moving + if ((other->client->ps.eFlags2 & EF2_HYPERSPACE)) { // they've started the hyperspace but haven't been teleported yet + float timeFrac = ((float)(level.time - other->client->ps.hyperSpaceTime)) / HYPERSPACE_TIME; + if (timeFrac >= HYPERSPACE_TELEPORT_FRAC) { // half-way, now teleport them! + vec3_t diff, fwd, right, up, newOrg; + float fDiff, rDiff, uDiff; + // take off the flag so we only do this once other->client->ps.eFlags2 &= ~EF2_HYPERSPACE; - //Get the offset from the local position - ent = G_Find (NULL, FOFS(targetname), self->target); - if (!ent || !ent->inuse) - { //this is bad - trap->Error( ERR_DROP, "trigger_hyperspace has invalid target '%s'\n", self->target ); + // Get the offset from the local position + ent = G_Find(NULL, FOFS(targetname), self->target); + if (!ent || !ent->inuse) { // this is bad + trap->Error(ERR_DROP, "trigger_hyperspace has invalid target '%s'\n", self->target); return; } - VectorSubtract( other->client->ps.origin, ent->s.origin, diff ); - AngleVectors( ent->s.angles, fwd, right, up ); - fDiff = DotProduct( fwd, diff ); - rDiff = DotProduct( right, diff ); - uDiff = DotProduct( up, diff ); - //Now get the base position of the destination - ent = G_Find (NULL, FOFS(targetname), self->target2); - if (!ent || !ent->inuse) - { //this is bad - trap->Error( ERR_DROP, "trigger_hyperspace has invalid target2 '%s'\n", self->target2 ); + VectorSubtract(other->client->ps.origin, ent->s.origin, diff); + AngleVectors(ent->s.angles, fwd, right, up); + fDiff = DotProduct(fwd, diff); + rDiff = DotProduct(right, diff); + uDiff = DotProduct(up, diff); + // Now get the base position of the destination + ent = G_Find(NULL, FOFS(targetname), self->target2); + if (!ent || !ent->inuse) { // this is bad + trap->Error(ERR_DROP, "trigger_hyperspace has invalid target2 '%s'\n", self->target2); return; } - VectorCopy( ent->s.origin, newOrg ); - //finally, add the offset into the new origin - AngleVectors( ent->s.angles, fwd, right, up ); - VectorMA( newOrg, fDiff, fwd, newOrg ); - VectorMA( newOrg, rDiff, right, newOrg ); - VectorMA( newOrg, uDiff, up, newOrg ); - //trap->Print("hyperspace from %s to %s\n", vtos(other->client->ps.origin), vtos(newOrg) ); - //now put them in the offset position, facing the angles that position wants them to be facing - TeleportPlayer( other, newOrg, ent->s.angles ); - if ( other->m_pVehicle && other->m_pVehicle->m_pPilot ) - {//teleport the pilot, too - TeleportPlayer( (gentity_t*)other->m_pVehicle->m_pPilot, newOrg, ent->s.angles ); - //FIXME: and the passengers? + VectorCopy(ent->s.origin, newOrg); + // finally, add the offset into the new origin + AngleVectors(ent->s.angles, fwd, right, up); + VectorMA(newOrg, fDiff, fwd, newOrg); + VectorMA(newOrg, rDiff, right, newOrg); + VectorMA(newOrg, uDiff, up, newOrg); + // trap->Print("hyperspace from %s to %s\n", vtos(other->client->ps.origin), vtos(newOrg) ); + // now put them in the offset position, facing the angles that position wants them to be facing + TeleportPlayer(other, newOrg, ent->s.angles); + if (other->m_pVehicle && other->m_pVehicle->m_pPilot) { // teleport the pilot, too + TeleportPlayer((gentity_t *)other->m_pVehicle->m_pPilot, newOrg, ent->s.angles); + // FIXME: and the passengers? } - //make them face the new angle - //other->client->ps.hyperSpaceIndex = ent->s.number; - VectorCopy( ent->s.angles, other->client->ps.hyperSpaceAngles ); - //sound - G_Sound( other, CHAN_LOCAL, G_SoundIndex( "sound/vehicles/common/hyperend.wav" ) ); + // make them face the new angle + // other->client->ps.hyperSpaceIndex = ent->s.number; + VectorCopy(ent->s.angles, other->client->ps.hyperSpaceAngles); + // sound + G_Sound(other, CHAN_LOCAL, G_SoundIndex("sound/vehicles/common/hyperend.wav")); } } return; - } - else - { - ent = G_Find (NULL, FOFS(targetname), self->target); - if (!ent || !ent->inuse) - { //this is bad - trap->Error( ERR_DROP, "trigger_hyperspace has invalid target '%s'\n", self->target ); + } else { + ent = G_Find(NULL, FOFS(targetname), self->target); + if (!ent || !ent->inuse) { // this is bad + trap->Error(ERR_DROP, "trigger_hyperspace has invalid target '%s'\n", self->target); return; } - if (!other->client->ps.m_iVehicleNum || other->m_pVehicle->m_iRemovedSurfaces) - { //if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up + if (!other->client->ps.m_iVehicleNum || + other->m_pVehicle->m_iRemovedSurfaces) { // if a vehicle touches a boundary without a pilot in it or with parts missing, just blow the thing up G_Damage(other, other, other, NULL, other->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); return; } - //other->client->ps.hyperSpaceIndex = ent->s.number; - VectorCopy( ent->s.angles, other->client->ps.hyperSpaceAngles ); + // other->client->ps.hyperSpaceIndex = ent->s.number; + VectorCopy(ent->s.angles, other->client->ps.hyperSpaceAngles); other->client->ps.hyperSpaceTime = level.time; } } @@ -1717,36 +1465,34 @@ void trigger_hyperspace_find_targets( gentity_t *self ) } */ /*QUAKED trigger_hyperspace (.5 .5 .5) ? -Ship will turn to face the angles of the first target_position then fly forward, playing the hyperspace effect, then pop out at a relative point around the target +Ship will turn to face the angles of the first target_position then fly forward, playing the hyperspace effect, then pop out at a relative point around the +target -"target" whatever position the ship teleports from in relation to the target_position specified here, that's the relative position the ship will spawn at around the target2 target_position -"target2" name of target_position to teleport the ship to (will be relative to it's origin) +"target" whatever position the ship teleports from in relation to the target_position specified here, that's the relative position the ship will spawn at +around the target2 target_position "target2" name of target_position to teleport the ship to (will be relative to it's origin) */ -void SP_trigger_hyperspace(gentity_t *self) -{ - //register the hyperspace end sound (start sounds are customized) - G_SoundIndex( "sound/vehicles/common/hyperend.wav" ); +void SP_trigger_hyperspace(gentity_t *self) { + // register the hyperspace end sound (start sounds are customized) + G_SoundIndex("sound/vehicles/common/hyperend.wav"); InitTrigger(self); self->r.contents = CONTENTS_TRIGGER; - if (!self->target || !self->target[0]) - { - trap->Error( ERR_DROP, "trigger_hyperspace without a target." ); + if (!self->target || !self->target[0]) { + trap->Error(ERR_DROP, "trigger_hyperspace without a target."); } - if (!self->target2 || !self->target2[0]) - { - trap->Error( ERR_DROP, "trigger_hyperspace without a target2." ); + if (!self->target2 || !self->target2[0]) { + trap->Error(ERR_DROP, "trigger_hyperspace without a target2."); } - self->delay = Distance( self->r.absmax, self->r.absmin );//my size + self->delay = Distance(self->r.absmax, self->r.absmin); // my size self->touch = hyperspace_touch; - trap->LinkEntity((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); - //self->think = trigger_hyperspace_find_targets; - //self->nextthink = level.time + FRAMETIME; + // self->think = trigger_hyperspace_find_targets; + // self->nextthink = level.time + FRAMETIME; } /* ============================================================================== @@ -1756,7 +1502,6 @@ timer ============================================================================== */ - /*QUAKED func_timer (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) START_ON This should be renamed trigger_timer... Repeatedly fires its targets. @@ -1768,40 +1513,40 @@ so, the basic time between firing is a random time between (wait - random) and (wait + random) */ -void func_timer_think( gentity_t *self ) { - G_UseTargets (self, self->activator); +void func_timer_think(gentity_t *self) { + G_UseTargets(self, self->activator); // set time before next firing - self->nextthink = level.time + 1000 * ( self->wait + Q_flrand(-1.0f, 1.0f) * self->random ); + self->nextthink = level.time + 1000 * (self->wait + Q_flrand(-1.0f, 1.0f) * self->random); } -void func_timer_use( gentity_t *self, gentity_t *other, gentity_t *activator ) { +void func_timer_use(gentity_t *self, gentity_t *other, gentity_t *activator) { self->activator = activator; - G_ActivateBehavior(self,BSET_USE); + G_ActivateBehavior(self, BSET_USE); // if on, turn it off - if ( self->nextthink ) { + if (self->nextthink) { self->nextthink = 0; return; } // turn it on - func_timer_think (self); + func_timer_think(self); } -void SP_func_timer( gentity_t *self ) { - G_SpawnFloat( "random", "1", &self->random); - G_SpawnFloat( "wait", "1", &self->wait ); +void SP_func_timer(gentity_t *self) { + G_SpawnFloat("random", "1", &self->random); + G_SpawnFloat("wait", "1", &self->wait); self->use = func_timer_use; self->think = func_timer_think; - if ( self->random >= self->wait ) { - self->random = self->wait - 1;//NOTE: was - FRAMETIME, but FRAMETIME is in msec (100) and these numbers are in *seconds*! - trap->Print( "func_timer at %s has random >= wait\n", vtos( self->s.origin ) ); + if (self->random >= self->wait) { + self->random = self->wait - 1; // NOTE: was - FRAMETIME, but FRAMETIME is in msec (100) and these numbers are in *seconds*! + trap->Print("func_timer at %s has random >= wait\n", vtos(self->s.origin)); } - if ( self->spawnflags & 1 ) { + if (self->spawnflags & 1) { self->nextthink = level.time + FRAMETIME; self->activator = self; } @@ -1809,89 +1554,71 @@ void SP_func_timer( gentity_t *self ) { self->r.svFlags = SVF_NOCLIENT; } -gentity_t *asteroid_pick_random_asteroid( gentity_t *self ) -{ - int t_count = 0, pick; - gentity_t *t = NULL; +gentity_t *asteroid_pick_random_asteroid(gentity_t *self) { + int t_count = 0, pick; + gentity_t *t = NULL; - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; } } - if(!t_count) - { + if (!t_count) { return NULL; } - if(t_count == 1) - { + if (t_count == 1) { return t; } - //FIXME: need a seed + // FIXME: need a seed pick = Q_irand(1, t_count); t_count = 0; - while ( (t = G_Find (t, FOFS(targetname), self->target)) != NULL ) - { - if (t != self) - { + while ((t = G_Find(t, FOFS(targetname), self->target)) != NULL) { + if (t != self) { t_count++; - } - else - { + } else { continue; } - if(t_count == pick) - { + if (t_count == pick) { return t; } } return NULL; } -int asteroid_count_num_asteroids( gentity_t *self ) -{ - int i, count = 0; +int asteroid_count_num_asteroids(gentity_t *self) { + int i, count = 0; - for ( i = MAX_CLIENTS; i < ENTITYNUM_WORLD; i++ ) - { - if ( !g_entities[i].inuse ) - { + for (i = MAX_CLIENTS; i < ENTITYNUM_WORLD; i++) { + if (!g_entities[i].inuse) { continue; } - if ( g_entities[i].r.ownerNum == self->s.number ) - { + if (g_entities[i].r.ownerNum == self->s.number) { count++; } } return count; } -extern void SP_func_rotating (gentity_t *ent); -extern void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ); -void asteroid_field_think(gentity_t *self) -{ - int numAsteroids = asteroid_count_num_asteroids( self ); +extern void SP_func_rotating(gentity_t *ent); +extern void Q3_Lerp2Origin(int taskID, int entID, vec3_t origin, float duration); +void asteroid_field_think(gentity_t *self) { + int numAsteroids = asteroid_count_num_asteroids(self); self->nextthink = level.time + 500; - if ( numAsteroids < self->count ) - { - //need to spawn a new asteroid + if (numAsteroids < self->count) { + // need to spawn a new asteroid gentity_t *newAsteroid = G_Spawn(); - if ( newAsteroid ) - { + if (newAsteroid) { vec3_t startSpot, endSpot, startAngles; - float dist, speed = flrand( self->speed * 0.25f, self->speed * 2.0f ); - int capAxis, axis, time = 0; - gentity_t *copyAsteroid = asteroid_pick_random_asteroid( self ); - if ( copyAsteroid ) - { + float dist, speed = flrand(self->speed * 0.25f, self->speed * 2.0f); + int capAxis, axis, time = 0; + gentity_t *copyAsteroid = asteroid_pick_random_asteroid(self); + if (copyAsteroid) { newAsteroid->model = copyAsteroid->model; newAsteroid->model2 = copyAsteroid->model2; newAsteroid->health = copyAsteroid->health; @@ -1900,11 +1627,11 @@ void asteroid_field_think(gentity_t *self) newAsteroid->damage = copyAsteroid->damage; newAsteroid->speed = copyAsteroid->speed; - G_SetOrigin( newAsteroid, copyAsteroid->s.origin ); - G_SetAngles( newAsteroid, copyAsteroid->s.angles ); + G_SetOrigin(newAsteroid, copyAsteroid->s.origin); + G_SetAngles(newAsteroid, copyAsteroid->s.angles); newAsteroid->classname = "func_rotating"; - SP_func_rotating( newAsteroid ); + SP_func_rotating(newAsteroid); newAsteroid->genericValue15 = copyAsteroid->genericValue15; newAsteroid->s.iModelScale = copyAsteroid->s.iModelScale; @@ -1912,60 +1639,52 @@ void asteroid_field_think(gentity_t *self) G_ScaleNetHealth(newAsteroid); newAsteroid->radius = copyAsteroid->radius; newAsteroid->material = copyAsteroid->material; - //CacheChunkEffects( self->material ); + // CacheChunkEffects( self->material ); - //keep track of it + // keep track of it newAsteroid->r.ownerNum = self->s.number; - //move it - capAxis = Q_irand( 0, 2 ); - for ( axis = 0; axis < 3; axis++ ) - { - if ( axis == capAxis ) - { - if ( Q_irand( 0, 1 ) ) - { + // move it + capAxis = Q_irand(0, 2); + for (axis = 0; axis < 3; axis++) { + if (axis == capAxis) { + if (Q_irand(0, 1)) { startSpot[axis] = self->r.mins[axis]; endSpot[axis] = self->r.maxs[axis]; - } - else - { + } else { startSpot[axis] = self->r.maxs[axis]; endSpot[axis] = self->r.mins[axis]; } - } - else - { - startSpot[axis] = self->r.mins[axis]+(flrand(0,1.0f)*(self->r.maxs[axis]-self->r.mins[axis])); - endSpot[axis] = self->r.mins[axis]+(flrand(0,1.0f)*(self->r.maxs[axis]-self->r.mins[axis])); + } else { + startSpot[axis] = self->r.mins[axis] + (flrand(0, 1.0f) * (self->r.maxs[axis] - self->r.mins[axis])); + endSpot[axis] = self->r.mins[axis] + (flrand(0, 1.0f) * (self->r.maxs[axis] - self->r.mins[axis])); } } - //FIXME: maybe trace from start to end to make sure nothing is in the way? How big of a trace? - - G_SetOrigin( newAsteroid, startSpot ); - dist = Distance( endSpot, startSpot ); - time = ceil(dist/speed)*1000; - Q3_Lerp2Origin( -1, newAsteroid->s.number, endSpot, time ); - - //spin it - startAngles[0] = flrand( -360, 360 ); - startAngles[1] = flrand( -360, 360 ); - startAngles[2] = flrand( -360, 360 ); - G_SetAngles( newAsteroid, startAngles ); - newAsteroid->s.apos.trDelta[0] = flrand( -100, 100 ); - newAsteroid->s.apos.trDelta[1] = flrand( -100, 100 ); - newAsteroid->s.apos.trDelta[2] = flrand( -100, 100 ); + // FIXME: maybe trace from start to end to make sure nothing is in the way? How big of a trace? + + G_SetOrigin(newAsteroid, startSpot); + dist = Distance(endSpot, startSpot); + time = ceil(dist / speed) * 1000; + Q3_Lerp2Origin(-1, newAsteroid->s.number, endSpot, time); + + // spin it + startAngles[0] = flrand(-360, 360); + startAngles[1] = flrand(-360, 360); + startAngles[2] = flrand(-360, 360); + G_SetAngles(newAsteroid, startAngles); + newAsteroid->s.apos.trDelta[0] = flrand(-100, 100); + newAsteroid->s.apos.trDelta[1] = flrand(-100, 100); + newAsteroid->s.apos.trDelta[2] = flrand(-100, 100); newAsteroid->s.apos.trTime = level.time; newAsteroid->s.apos.trType = TR_LINEAR; - //remove itself when done + // remove itself when done newAsteroid->think = G_FreeEntity; - newAsteroid->nextthink = level.time+time; + newAsteroid->nextthink = level.time + time; - //think again sooner if need even more - if ( numAsteroids+1 < self->count ) - {//still need at least one more - //spawn it in 100ms + // think again sooner if need even more + if (numAsteroids + 1 < self->count) { // still need at least one more + // spawn it in 100ms self->nextthink = level.time + 100; } } @@ -1978,23 +1697,20 @@ speed - how fast, on average, the asteroid moves count - how many asteroids, max, to have at one time target - target this at func_rotating asteroids */ -void SP_trigger_asteroid_field(gentity_t *self) -{ - trap->SetBrushModel( (sharedEntity_t *)self, self->model ); +void SP_trigger_asteroid_field(gentity_t *self) { + trap->SetBrushModel((sharedEntity_t *)self, self->model); self->r.contents = 0; - if ( !self->count ) - { + if (!self->count) { self->health = 20; } - if ( !self->speed ) - { + if (!self->speed) { self->speed = 10000; } self->think = asteroid_field_think; self->nextthink = level.time + 100; - trap->LinkEntity((sharedEntity_t *)self); + trap->LinkEntity((sharedEntity_t *)self); } diff --git a/codemp/game/g_turret.c b/codemp/game/g_turret.c index 5d0c9d3b8f..e5833afc6e 100644 --- a/codemp/game/g_turret.c +++ b/codemp/game/g_turret.c @@ -24,43 +24,37 @@ along with this program; if not, see . #include "g_local.h" #include "qcommon/q_shared.h" -void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -qboolean turret_base_spawn_top( gentity_t *base ); -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ); +void G_SetEnemy(gentity_t *self, gentity_t *enemy); +qboolean turret_base_spawn_top(gentity_t *base); +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath); //------------------------------------------------------------------------------------------------------------ -void TurretPain( gentity_t *self, gentity_t *attacker, int damage ) +void TurretPain(gentity_t *self, gentity_t *attacker, int damage) //------------------------------------------------------------------------------------------------------------ { - if (self->target_ent) - { + if (self->target_ent) { self->target_ent->health = self->health; - if (self->target_ent->maxHealth) - { + if (self->target_ent->maxHealth) { G_ScaleNetHealth(self->target_ent); } } - if ( attacker->client && attacker->client->ps.weapon == WP_DEMP2 ) - { + if (attacker->client && attacker->client->ps.weapon == WP_DEMP2) { self->attackDebounceTime = level.time + 800 + Q_flrand(0.0f, 1.0f) * 500; self->painDebounceTime = self->attackDebounceTime; } - if ( !self->enemy ) - {//react to being hit - G_SetEnemy( self, attacker ); + if (!self->enemy) { // react to being hit + G_SetEnemy(self, attacker); } } //------------------------------------------------------------------------------------------------------------ -void TurretBasePain( gentity_t *self, gentity_t *attacker, int damage ) +void TurretBasePain(gentity_t *self, gentity_t *attacker, int damage) //------------------------------------------------------------------------------------------------------------ { - if (self->target_ent) - { + if (self->target_ent) { self->target_ent->health = self->health; - if (self->target_ent->maxHealth) - { + if (self->target_ent->maxHealth) { G_ScaleNetHealth(self->target_ent); } @@ -69,10 +63,10 @@ void TurretBasePain( gentity_t *self, gentity_t *attacker, int damage ) } //------------------------------------------------------------------------------------------------------------ -void auto_turret_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) +void auto_turret_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) //------------------------------------------------------------------------------------------------------------ { - vec3_t forward = { 0,0, 1 }, pos; + vec3_t forward = {0, 0, 1}, pos; // Turn off the thinking of the base & use it's targets g_entities[self->r.ownerNum].think = NULL; @@ -84,60 +78,45 @@ void auto_turret_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->s.health = self->health = 0; self->s.loopSound = 0; self->s.shouldtarget = qfalse; - //self->s.owner = MAX_CLIENTS; //not owned by any client + // self->s.owner = MAX_CLIENTS; //not owned by any client - VectorCopy( self->r.currentOrigin, pos ); - pos[2] += self->r.maxs[2]*0.5f; - G_PlayEffect( EFFECT_EXPLOSION_TURRET, pos, forward ); - G_PlayEffectID( G_EffectIndex( "turret/explode" ), pos, forward ); + VectorCopy(self->r.currentOrigin, pos); + pos[2] += self->r.maxs[2] * 0.5f; + G_PlayEffect(EFFECT_EXPLOSION_TURRET, pos, forward); + G_PlayEffectID(G_EffectIndex("turret/explode"), pos, forward); - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->r.currentOrigin, - attacker, - self->splashDamage, - self->splashRadius, - attacker, - NULL, - MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, NULL, MOD_UNKNOWN); } self->s.weapon = 0; // crosshair code uses this to mark crosshair red - - if ( self->s.modelindex2 ) - { + if (self->s.modelindex2) { // switch to damage model if we should self->s.modelindex = self->s.modelindex2; - if (self->target_ent && self->target_ent->s.modelindex2) - { + if (self->target_ent && self->target_ent->s.modelindex2) { self->target_ent->s.modelindex = self->target_ent->s.modelindex2; } - VectorCopy( self->r.currentAngles, self->s.apos.trBase ); - VectorClear( self->s.apos.trDelta ); + VectorCopy(self->r.currentAngles, self->s.apos.trBase); + VectorClear(self->s.apos.trDelta); - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - } - else - { - ObjectDie( self, inflictor, attacker, damage, meansOfDeath ); + } else { + ObjectDie(self, inflictor, attacker, damage, meansOfDeath); } } //------------------------------------------------------------------------------------------------------------ -void bottom_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) +void bottom_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) //------------------------------------------------------------------------------------------------------------ { - if (self->target_ent && self->target_ent->health > 0) - { + if (self->target_ent && self->target_ent->health > 0) { self->target_ent->health = self->health; - if (self->target_ent->maxHealth) - { + if (self->target_ent->maxHealth) { G_ScaleNetHealth(self->target_ent); } auto_turret_die(self->target_ent, inflictor, attacker, damage, meansOfDeath); @@ -147,25 +126,24 @@ void bottom_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, in #define START_DIS 15 //---------------------------------------------------------------- -static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) +static void turret_fire(gentity_t *ent, vec3_t start, vec3_t dir) //---------------------------------------------------------------- { - vec3_t org; - gentity_t *bolt; + vec3_t org; + gentity_t *bolt; - if ( (trap->PointContents( start, ent->s.number )&MASK_SHOT) ) - { + if ((trap->PointContents(start, ent->s.number) & MASK_SHOT)) { return; } - VectorMA( start, -START_DIS, dir, org ); // dumb.... - G_PlayEffectID( ent->genericValue13, org, dir ); + VectorMA(start, -START_DIS, dir, org); // dumb.... + G_PlayEffectID(ent->genericValue13, org, dir); bolt = G_Spawn(); - //use a custom shot effect + // use a custom shot effect bolt->s.otherEntityNum2 = ent->genericValue14; - //use a custom impact effect + // use a custom impact effect bolt->s.emplacedOwner = ent->genericValue15; bolt->classname = "turret_proj"; @@ -177,49 +155,45 @@ static void turret_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) bolt->damage = ent->damage; bolt->alliedTeam = ent->alliedTeam; bolt->teamnodmg = ent->teamnodmg; - //bolt->dflags = DAMAGE_NO_KNOCKBACK;// | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming + // bolt->dflags = DAMAGE_NO_KNOCKBACK;// | DAMAGE_HEAVY_WEAP_CLASS; // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = ent->damage; bolt->splashRadius = 100; bolt->methodOfDeath = MOD_TARGET_LASER; bolt->splashMethodOfDeath = MOD_TARGET_LASER; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - //bolt->trigger_formation = qfalse; // don't draw tail on first frame + // bolt->trigger_formation = qfalse; // don't draw tail on first frame - VectorSet( bolt->r.maxs, 1.5, 1.5, 1.5 ); - VectorScale( bolt->r.maxs, -1, bolt->r.mins ); + VectorSet(bolt->r.maxs, 1.5, 1.5, 1.5); + VectorScale(bolt->r.maxs, -1, bolt->r.mins); bolt->s.pos.trType = TR_LINEAR; bolt->s.pos.trTime = level.time; - VectorCopy( start, bolt->s.pos.trBase ); - VectorScale( dir, ent->mass, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( start, bolt->r.currentOrigin); + VectorCopy(start, bolt->s.pos.trBase); + VectorScale(dir, ent->mass, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->r.currentOrigin); bolt->parent = ent; } //----------------------------------------------------- -void turret_head_think( gentity_t *self ) +void turret_head_think(gentity_t *self) //----------------------------------------------------- { gentity_t *top = &g_entities[self->r.ownerNum]; - if ( !top ) - { + if (!top) { return; } - if ( self->painDebounceTime > level.time ) - { - vec3_t v_up; - VectorSet( v_up, 0, 0, 1 ); - G_PlayEffect( EFFECT_SPARKS, self->r.currentOrigin, v_up ); - if ( Q_irand( 0, 3) ) - {//25% chance of still firing + if (self->painDebounceTime > level.time) { + vec3_t v_up; + VectorSet(v_up, 0, 0, 1); + G_PlayEffect(EFFECT_SPARKS, self->r.currentOrigin, v_up); + if (Q_irand(0, 3)) { // 25% chance of still firing return; } } // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time - if ( self->enemy && self->setTime < level.time && self->attackDebounceTime < level.time ) - { - vec3_t fwd, org; + if (self->enemy && self->setTime < level.time && self->attackDebounceTime < level.time) { + vec3_t fwd, org; // set up our next fire time self->setTime = level.time + self->wait; @@ -235,66 +209,56 @@ void turret_head_think( gentity_t *self ) trap->G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); trap->G2API_GiveMeVectorFromMatrix( boltMatrix, POSITIVE_Y, fwd ); */ - VectorCopy( top->r.currentOrigin, org ); - org[2] += top->r.maxs[2]-8; - AngleVectors( top->r.currentAngles, fwd, NULL, NULL ); + VectorCopy(top->r.currentOrigin, org); + org[2] += top->r.maxs[2] - 8; + AngleVectors(top->r.currentAngles, fwd, NULL, NULL); - VectorMA( org, START_DIS, fwd, org ); + VectorMA(org, START_DIS, fwd, org); - turret_fire( top, org, fwd ); - self->fly_sound_debounce_time = level.time;//used as lastShotTime + turret_fire(top, org, fwd); + self->fly_sound_debounce_time = level.time; // used as lastShotTime } } //----------------------------------------------------- -static void turret_aim( gentity_t *self ) +static void turret_aim(gentity_t *self) //----------------------------------------------------- { - vec3_t enemyDir, org, org2; - vec3_t desiredAngles, setAngle; - float diffYaw = 0.0f, diffPitch = 0.0f, turnSpeed; + vec3_t enemyDir, org, org2; + vec3_t desiredAngles, setAngle; + float diffYaw = 0.0f, diffPitch = 0.0f, turnSpeed; const float pitchCap = 40.0f; gentity_t *top = &g_entities[self->r.ownerNum]; - if ( !top ) - { + if (!top) { return; } // move our gun base yaw to where we should be at this time.... - BG_EvaluateTrajectory( &top->s.apos, level.time, top->r.currentAngles ); - top->r.currentAngles[YAW] = AngleNormalize180( top->r.currentAngles[YAW] ); - top->r.currentAngles[PITCH] = AngleNormalize180( top->r.currentAngles[PITCH] ); + BG_EvaluateTrajectory(&top->s.apos, level.time, top->r.currentAngles); + top->r.currentAngles[YAW] = AngleNormalize180(top->r.currentAngles[YAW]); + top->r.currentAngles[PITCH] = AngleNormalize180(top->r.currentAngles[PITCH]); turnSpeed = top->speed; - if ( self->painDebounceTime > level.time ) - { - desiredAngles[YAW] = top->r.currentAngles[YAW]+flrand(-45,45); - desiredAngles[PITCH] = top->r.currentAngles[PITCH]+flrand(-10,10); + if (self->painDebounceTime > level.time) { + desiredAngles[YAW] = top->r.currentAngles[YAW] + flrand(-45, 45); + desiredAngles[PITCH] = top->r.currentAngles[PITCH] + flrand(-10, 10); - if (desiredAngles[PITCH] < -pitchCap) - { + if (desiredAngles[PITCH] < -pitchCap) { desiredAngles[PITCH] = -pitchCap; - } - else if (desiredAngles[PITCH] > pitchCap) - { + } else if (desiredAngles[PITCH] > pitchCap) { desiredAngles[PITCH] = pitchCap; } - diffYaw = AngleSubtract( desiredAngles[YAW], top->r.currentAngles[YAW] ); - diffPitch = AngleSubtract( desiredAngles[PITCH], top->r.currentAngles[PITCH] ); - turnSpeed = flrand( -5, 5 ); - } - else if ( self->enemy ) - { + diffYaw = AngleSubtract(desiredAngles[YAW], top->r.currentAngles[YAW]); + diffPitch = AngleSubtract(desiredAngles[PITCH], top->r.currentAngles[PITCH]); + turnSpeed = flrand(-5, 5); + } else if (self->enemy) { // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - VectorCopy( self->enemy->r.currentOrigin, org ); - org[2]+=self->enemy->r.maxs[2]*0.5f; - if (self->enemy->s.eType == ET_NPC && - self->enemy->s.NPC_class == CLASS_VEHICLE && - self->enemy->m_pVehicle && - self->enemy->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) - { //hack! + VectorCopy(self->enemy->r.currentOrigin, org); + org[2] += self->enemy->r.maxs[2] * 0.5f; + if (self->enemy->s.eType == ET_NPC && self->enemy->s.NPC_class == CLASS_VEHICLE && self->enemy->m_pVehicle && + self->enemy->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // hack! org[2] += 32.0f; } /* @@ -308,99 +272,85 @@ static void turret_aim( gentity_t *self ) trap->G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org2 ); */ - VectorCopy( top->r.currentOrigin, org2 ); + VectorCopy(top->r.currentOrigin, org2); - VectorSubtract( org, org2, enemyDir ); - vectoangles( enemyDir, desiredAngles ); + VectorSubtract(org, org2, enemyDir); + vectoangles(enemyDir, desiredAngles); desiredAngles[PITCH] = AngleNormalize180(desiredAngles[PITCH]); - if (desiredAngles[PITCH] < -pitchCap) - { + if (desiredAngles[PITCH] < -pitchCap) { desiredAngles[PITCH] = -pitchCap; - } - else if (desiredAngles[PITCH] > pitchCap) - { + } else if (desiredAngles[PITCH] > pitchCap) { desiredAngles[PITCH] = pitchCap; } - diffYaw = AngleSubtract( desiredAngles[YAW], top->r.currentAngles[YAW] ); - diffPitch = AngleSubtract( desiredAngles[PITCH], top->r.currentAngles[PITCH] ); - } - else - {//FIXME: Pan back and forth in original facing + diffYaw = AngleSubtract(desiredAngles[YAW], top->r.currentAngles[YAW]); + diffPitch = AngleSubtract(desiredAngles[PITCH], top->r.currentAngles[PITCH]); + } else { // FIXME: Pan back and forth in original facing // no enemy, so make us slowly sweep back and forth as if searching for a new one - desiredAngles[YAW] = sin( level.time * 0.0001f + top->count ); - desiredAngles[YAW] *= 60.0f; + desiredAngles[YAW] = sin(level.time * 0.0001f + top->count); + desiredAngles[YAW] *= 60.0f; desiredAngles[YAW] += self->s.angles[YAW]; - desiredAngles[YAW] = AngleNormalize180( desiredAngles[YAW] ); - diffYaw = AngleSubtract( desiredAngles[YAW], top->r.currentAngles[YAW] ); - diffPitch = AngleSubtract( 0, top->r.currentAngles[PITCH] ); + desiredAngles[YAW] = AngleNormalize180(desiredAngles[YAW]); + diffYaw = AngleSubtract(desiredAngles[YAW], top->r.currentAngles[YAW]); + diffPitch = AngleSubtract(0, top->r.currentAngles[PITCH]); turnSpeed = 1.0f; } - if ( diffYaw ) - { + if (diffYaw) { // cap max speed.... - if ( fabs(diffYaw) > turnSpeed ) - { - diffYaw = ( diffYaw >= 0 ? turnSpeed : -turnSpeed ); + if (fabs(diffYaw) > turnSpeed) { + diffYaw = (diffYaw >= 0 ? turnSpeed : -turnSpeed); } } - if ( diffPitch ) - { - if ( fabs(diffPitch) > turnSpeed ) - { + if (diffPitch) { + if (fabs(diffPitch) > turnSpeed) { // cap max speed - diffPitch = (diffPitch > 0.0f ? turnSpeed : -turnSpeed ); + diffPitch = (diffPitch > 0.0f ? turnSpeed : -turnSpeed); } } // ...then set up our desired yaw - VectorSet( setAngle, diffPitch, diffYaw, 0 ); + VectorSet(setAngle, diffPitch, diffYaw, 0); - VectorCopy( top->r.currentAngles, top->s.apos.trBase ); - VectorScale( setAngle, (1000/FRAMETIME), top->s.apos.trDelta ); + VectorCopy(top->r.currentAngles, top->s.apos.trBase); + VectorScale(setAngle, (1000 / FRAMETIME), top->s.apos.trDelta); top->s.apos.trTime = level.time; top->s.apos.trType = TR_LINEAR_STOP; top->s.apos.trDuration = FRAMETIME; - if ( diffYaw || diffPitch ) - { - top->s.loopSound = G_SoundIndex( "sound/vehicles/weapons/hoth_turret/turn.wav" ); - } - else - { + if (diffYaw || diffPitch) { + top->s.loopSound = G_SoundIndex("sound/vehicles/weapons/hoth_turret/turn.wav"); + } else { top->s.loopSound = 0; } } //----------------------------------------------------- -static void turret_turnoff( gentity_t *self ) +static void turret_turnoff(gentity_t *self) //----------------------------------------------------- { gentity_t *top = &g_entities[self->r.ownerNum]; - if ( top != NULL ) - {//still have a top - //stop it from rotating - VectorCopy( top->r.currentAngles, top->s.apos.trBase ); - VectorClear( top->s.apos.trDelta ); + if (top != NULL) { // still have a top + // stop it from rotating + VectorCopy(top->r.currentAngles, top->s.apos.trBase); + VectorClear(top->s.apos.trDelta); top->s.apos.trTime = level.time; top->s.apos.trType = TR_STATIONARY; } self->s.loopSound = 0; // shut-down sound - //G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + // G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); // Clear enemy self->enemy = NULL; } //----------------------------------------------------- -static void turret_sleep( gentity_t *self ) +static void turret_sleep(gentity_t *self) //----------------------------------------------------- { - if ( self->enemy == NULL ) - { + if (self->enemy == NULL) { // we don't need to play sound return; } @@ -413,96 +363,82 @@ static void turret_sleep( gentity_t *self ) } //----------------------------------------------------- -static qboolean turret_find_enemies( gentity_t *self ) +static qboolean turret_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int i, count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; - trace_t tr; + qboolean found = qfalse; + int i, count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; + trace_t tr; gentity_t *top = &g_entities[self->r.ownerNum]; - if ( !top ) - { + if (!top) { return qfalse; } - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->timestamp < level.time ) - { - //G_Sound(self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->timestamp < level.time) { + // G_Sound(self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/ping.wav" )); self->timestamp = level.time + 1000; } } - VectorCopy( top->r.currentOrigin, org2 ); + VectorCopy(top->r.currentOrigin, org2); - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( i = 0; i < count; i++ ) - { + for (i = 0; i < count; i++) { target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { // only attack clients continue; } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client->sess.sessionTeam == TEAM_SPECTATOR ) - { + if (target->client->sess.sessionTeam == TEAM_SPECTATOR) { continue; } - if ( target->client->tempSpectate >= level.time ) - { + if (target->client->tempSpectate >= level.time) { continue; } - if ( self->alliedTeam ) - { - if ( target->client ) - { - if ( target->client->sess.sessionTeam == self->alliedTeam ) - { + if (self->alliedTeam) { + if (target->client) { + if (target->client->sess.sessionTeam == self->alliedTeam) { // A bot/client/NPC we don't want to shoot continue; } - } - else if ( target->teamnodmg == self->alliedTeam ) - { + } else if (target->teamnodmg == self->alliedTeam) { // An ent we don't want to shoot continue; } } - if ( !trap->InPVS( org2, target->r.currentOrigin )) - { + if (!trap->InPVS(org2, target->r.currentOrigin)) { continue; } - VectorCopy( target->r.currentOrigin, org ); - org[2] += target->r.maxs[2]*0.5f; + VectorCopy(target->r.currentOrigin, org); + org[2] += target->r.maxs[2] * 0.5f; - trap->Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->r.currentOrigin, top->r.currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->r.currentOrigin, top->r.currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist // all things equal, keep current - || (!Q_stricmp( "atst_vehicle", target->NPC_type ) && bestTarget && Q_stricmp( "atst_vehicle", bestTarget->NPC_type ) ) )//target AT-STs over non-AT-STs... FIXME: must be a better, easier way to tell this, no? + if (enemyDist < bestDist // all things equal, keep current + || (!Q_stricmp("atst_vehicle", target->NPC_type) && bestTarget && + Q_stricmp("atst_vehicle", bestTarget->NPC_type))) // target AT-STs over non-AT-STs... FIXME: must be a better, easier way to tell this, no? { - if ( self->attackDebounceTime < level.time ) - { + if (self->attackDebounceTime < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - //G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); + // G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); // Wind up turrets for a bit self->attackDebounceTime = level.time + 1400; @@ -515,12 +451,10 @@ static qboolean turret_find_enemies( gentity_t *self ) } } - if ( found ) - { - G_SetEnemy( self, bestTarget ); - if ( VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + if (found) { + G_SetEnemy(self, bestTarget); + if (VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } } @@ -528,110 +462,86 @@ static qboolean turret_find_enemies( gentity_t *self ) } //----------------------------------------------------- -void turret_base_think( gentity_t *self ) +void turret_base_think(gentity_t *self) //----------------------------------------------------- { - qboolean turnOff = qtrue; - float enemyDist; - vec3_t enemyDir, org, org2; + qboolean turnOff = qtrue; + float enemyDist; + vec3_t enemyDir, org, org2; - if ( self->spawnflags & 1 ) - { + if (self->spawnflags & 1) { // not turned on - turret_turnoff( self ); + turret_turnoff(self); // No target self->flags |= FL_NOTARGET; - self->nextthink = -1;//never think again + self->nextthink = -1; // never think again return; - } - else - { + } else { // I'm all hot and bothered self->flags &= ~FL_NOTARGET; - //remember to keep thinking! + // remember to keep thinking! self->nextthink = level.time + FRAMETIME; } - if ( !self->enemy ) - { - if ( turret_find_enemies( self )) - { + if (!self->enemy) { + if (turret_find_enemies(self)) { turnOff = qfalse; } - } - else if ( self->enemy->client && self->enemy->client->sess.sessionTeam == TEAM_SPECTATOR ) - {//don't keep going after spectators + } else if (self->enemy->client && self->enemy->client->sess.sessionTeam == TEAM_SPECTATOR) { // don't keep going after spectators self->enemy = NULL; - } - else if ( self->enemy->client && self->enemy->client->tempSpectate >= level.time ) - {//don't keep going after spectators + } else if (self->enemy->client && self->enemy->client->tempSpectate >= level.time) { // don't keep going after spectators self->enemy = NULL; - } - else - {//FIXME: remain single-minded or look for a new enemy every now and then? - if ( self->enemy->health > 0 ) - { + } else { // FIXME: remain single-minded or look for a new enemy every now and then? + if (self->enemy->health > 0) { // enemy is alive - VectorSubtract( self->enemy->r.currentOrigin, self->r.currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(self->enemy->r.currentOrigin, self->r.currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < (self->radius * self->radius) ) - { + if (enemyDist < (self->radius * self->radius)) { // was in valid radius - if ( trap->InPVS( self->r.currentOrigin, self->enemy->r.currentOrigin ) ) - { + if (trap->InPVS(self->r.currentOrigin, self->enemy->r.currentOrigin)) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); - } - else - { - VectorCopy( self->enemy->r.currentOrigin, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->r.currentOrigin, org); } - VectorCopy( self->r.currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->r.currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 10; - } - else - { + } else { org2[2] -= 10; } - trap->Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number ) - { - turnOff = qfalse; // Can see our enemy + if (!tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number) { + turnOff = qfalse; // Can see our enemy } } } } - turret_head_think( self ); + turret_head_think(self); } - if ( turnOff ) - { - if ( self->bounceCount < level.time ) // bounceCount is used to keep the thing from ping-ponging from on to off + if (turnOff) { + if (self->bounceCount < level.time) // bounceCount is used to keep the thing from ping-ponging from on to off { - turret_sleep( self ); + turret_sleep(self); } - } - else - { + } else { // keep our enemy for a minimum of 2 seconds from now self->bounceCount = level.time + 2000 + Q_flrand(0.0f, 1.0f) * 150; } - turret_aim( self ); + turret_aim(self); } //----------------------------------------------------------------------------- -void turret_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void turret_base_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off @@ -649,7 +559,6 @@ void turret_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) */ } - /*QUAKED misc_turret (1 0 0) (-48 -48 0) (48 48 144) START_OFF Large 2-piece turbolaser turret @@ -690,73 +599,68 @@ Large 2-piece turbolaser turret "icon" - icon that represents the objective on the radar */ //----------------------------------------------------- -void SP_misc_turret( gentity_t *base ) +void SP_misc_turret(gentity_t *base) //----------------------------------------------------- { - char* s; + char *s; - base->s.modelindex2 = G_ModelIndex( "models/map_objects/hoth/turret_bottom.md3" ); - base->s.modelindex = G_ModelIndex( "models/map_objects/hoth/turret_base.md3" ); - //base->playerModel = trap->G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/turret_canon.glm", base->s.modelindex ); - //base->s.radius = 80.0f; + base->s.modelindex2 = G_ModelIndex("models/map_objects/hoth/turret_bottom.md3"); + base->s.modelindex = G_ModelIndex("models/map_objects/hoth/turret_base.md3"); + // base->playerModel = trap->G2API_InitGhoul2Model( base->ghoul2, "models/map_objects/imp_mine/turret_canon.glm", base->s.modelindex ); + // base->s.radius = 80.0f; - //trap->G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL ); - //base->torsoBolt = trap->G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash03" ); + // trap->G2API_SetBoneAngles( &base->ghoul2[base->playerModel], "Bone_body", vec3_origin, BONE_ANGLES_POSTMULT, POSITIVE_Y, POSITIVE_Z, POSITIVE_X, NULL ); + // base->torsoBolt = trap->G2API_AddBolt( &base->ghoul2[base->playerModel], "*flash03" ); - G_SpawnString( "icon", "", &s ); - if (s && s[0]) - { + G_SpawnString("icon", "", &s); + if (s && s[0]) { // We have an icon, so index it now. We are reusing the genericenemyindex // variable rather than adding a new one to the entity state. base->s.genericenemyindex = G_IconIndex(s); } - G_SetAngles( base, base->s.angles ); - G_SetOrigin( base, base->s.origin ); + G_SetAngles(base, base->s.angles); + G_SetOrigin(base, base->s.origin); base->r.contents = CONTENTS_BODY; - VectorSet( base->r.maxs, 32.0f, 32.0f, 128.0f ); - VectorSet( base->r.mins, -32.0f, -32.0f, 0.0f ); + VectorSet(base->r.maxs, 32.0f, 32.0f, 128.0f); + VectorSet(base->r.mins, -32.0f, -32.0f, 0.0f); base->use = turret_base_use; base->think = turret_base_think; // don't start working right away base->nextthink = level.time + FRAMETIME * 5; - trap->LinkEntity( (sharedEntity_t *)base ); + trap->LinkEntity((sharedEntity_t *)base); - if ( !turret_base_spawn_top( base ) ) - { - G_FreeEntity( base ); + if (!turret_base_spawn_top(base)) { + G_FreeEntity(base); } } //----------------------------------------------------- -qboolean turret_base_spawn_top( gentity_t *base ) -{ - vec3_t org; - int t; +qboolean turret_base_spawn_top(gentity_t *base) { + vec3_t org; + int t; gentity_t *top = G_Spawn(); - if ( !top ) - { + if (!top) { return qfalse; } - top->s.modelindex = G_ModelIndex( "models/map_objects/hoth/turret_top_new.md3" ); - top->s.modelindex2 = G_ModelIndex( "models/map_objects/hoth/turret_top.md3" ); - G_SetAngles( top, base->s.angles ); - VectorCopy( base->s.origin, org ); + top->s.modelindex = G_ModelIndex("models/map_objects/hoth/turret_top_new.md3"); + top->s.modelindex2 = G_ModelIndex("models/map_objects/hoth/turret_top.md3"); + G_SetAngles(top, base->s.angles); + VectorCopy(base->s.origin, org); org[2] += 128; - G_SetOrigin( top, org ); + G_SetOrigin(top, org); base->r.ownerNum = top->s.number; top->r.ownerNum = base->s.number; - if ( base->team && base->team[0] && //level.gametype == GT_SIEGE && - !base->teamnodmg) - { + if (base->team && base->team[0] && // level.gametype == GT_SIEGE && + !base->teamnodmg) { base->teamnodmg = atoi(base->team); } base->team = NULL; @@ -766,9 +670,9 @@ qboolean turret_base_spawn_top( gentity_t *base ) base->s.eType = ET_GENERAL; // Set up our explosion effect for the ExplodeDeath code.... - G_EffectIndex( "turret/explode" ); - G_EffectIndex( "sparks/spark_exp_nosnd" ); - G_EffectIndex( "turret/hoth_muzzle_flash" ); + G_EffectIndex("turret/explode"); + G_EffectIndex("sparks/spark_exp_nosnd"); + G_EffectIndex("turret/hoth_muzzle_flash"); // this is really the pitch angle..... top->speed = 0; @@ -776,17 +680,15 @@ qboolean turret_base_spawn_top( gentity_t *base ) // this is a random time offset for the no-enemy-search-around-mode top->count = Q_flrand(0.0f, 1.0f) * 9000; - if ( !base->health ) - { + if (!base->health) { base->health = 3000; } top->health = base->health; - G_SpawnInt( "showhealth", "0", &t ); + G_SpawnInt("showhealth", "0", &t); - if (t) - { //a non-0 maxhealth value will mean we want to show the health on the hud - top->maxHealth = base->health; //acts as "maxhealth" + if (t) { // a non-0 maxhealth value will mean we want to show the health on the hud + top->maxHealth = base->health; // acts as "maxhealth" G_ScaleNetHealth(top); base->maxHealth = base->health; @@ -797,13 +699,12 @@ qboolean turret_base_spawn_top( gentity_t *base ) base->pain = TurretBasePain; base->die = bottom_die; - //design specified shot speed - G_SpawnFloat( "shotspeed", "1100", &base->mass ); + // design specified shot speed + G_SpawnFloat("shotspeed", "1100", &base->mass); top->mass = base->mass; - //even if we don't want to show health, let's at least light the crosshair up properly over ourself - if ( !top->s.teamowner ) - { + // even if we don't want to show health, let's at least light the crosshair up properly over ourself + if (!top->s.teamowner) { top->s.teamowner = top->alliedTeam; } @@ -813,79 +714,73 @@ qboolean turret_base_spawn_top( gentity_t *base ) base->s.shouldtarget = qtrue; top->s.shouldtarget = qtrue; - //link them to each other + // link them to each other base->target_ent = top; top->target_ent = base; - //top->s.owner = MAX_CLIENTS; //not owned by any client + // top->s.owner = MAX_CLIENTS; //not owned by any client // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 1024; } top->radius = base->radius; // How quickly to fire - if ( !base->wait ) - { + if (!base->wait) { base->wait = 300 + Q_flrand(0.0f, 1.0f) * 55; } top->wait = base->wait; - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 300; } top->splashDamage = base->splashDamage; - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 128; } top->splashRadius = base->splashRadius; // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 100; } top->damage = base->damage; // how fast it turns - if ( !base->speed ) - { + if (!base->speed) { base->speed = 20; } top->speed = base->speed; - VectorSet( top->r.maxs, 48.0f, 48.0f, 16.0f ); - VectorSet( top->r.mins, -48.0f, -48.0f, 0.0f ); + VectorSet(top->r.maxs, 48.0f, 48.0f, 16.0f); + VectorSet(top->r.mins, -48.0f, -48.0f, 0.0f); // Precache moving sounds - //G_SoundIndex( "sound/chars/turret/startup.wav" ); - //G_SoundIndex( "sound/chars/turret/shutdown.wav" ); - //G_SoundIndex( "sound/chars/turret/ping.wav" ); - G_SoundIndex( "sound/vehicles/weapons/hoth_turret/turn.wav" ); - top->genericValue13 = G_EffectIndex( "turret/hoth_muzzle_flash" ); - top->genericValue14 = G_EffectIndex( "turret/hoth_shot" ); - top->genericValue15 = G_EffectIndex( "turret/hoth_impact" ); + // G_SoundIndex( "sound/chars/turret/startup.wav" ); + // G_SoundIndex( "sound/chars/turret/shutdown.wav" ); + // G_SoundIndex( "sound/chars/turret/ping.wav" ); + G_SoundIndex("sound/vehicles/weapons/hoth_turret/turn.wav"); + top->genericValue13 = G_EffectIndex("turret/hoth_muzzle_flash"); + top->genericValue14 = G_EffectIndex("turret/hoth_shot"); + top->genericValue15 = G_EffectIndex("turret/hoth_impact"); top->r.contents = CONTENTS_BODY; - //base->max_health = base->health; + // base->max_health = base->health; top->takedamage = qtrue; top->pain = TurretPain; - top->die = auto_turret_die; + top->die = auto_turret_die; top->material = MAT_METAL; - //base->r.svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; + // base->r.svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; // Register this so that we can use it for the missile effect - RegisterItem( BG_FindItemForWeapon( WP_EMPLACED_GUN )); + RegisterItem(BG_FindItemForWeapon(WP_EMPLACED_GUN)); // But set us as a turret so that we can be identified as a turret top->s.weapon = WP_EMPLACED_GUN; - trap->LinkEntity( (sharedEntity_t *)top ); + trap->LinkEntity((sharedEntity_t *)top); return qtrue; } diff --git a/codemp/game/g_turret_G2.c b/codemp/game/g_turret_G2.c index 5db87138c9..adf06d1eb3 100644 --- a/codemp/game/g_turret_G2.c +++ b/codemp/game/g_turret_G2.c @@ -24,27 +24,25 @@ along with this program; if not, see . #include "ghoul2/G2.h" #include "qcommon/q_shared.h" -void G_SetEnemy( gentity_t *self, gentity_t *enemy ); -void finish_spawning_turretG2( gentity_t *base ); -void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ); -void turretG2_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ); +void G_SetEnemy(gentity_t *self, gentity_t *enemy); +void finish_spawning_turretG2(gentity_t *base); +void ObjectDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath); +void turretG2_base_use(gentity_t *self, gentity_t *other, gentity_t *activator); +#define SPF_TURRETG2_CANRESPAWN 4 +#define SPF_TURRETG2_TURBO 8 +#define SPF_TURRETG2_LEAD_ENEMY 16 +#define SPF_SHOWONRADAR 32 -#define SPF_TURRETG2_CANRESPAWN 4 -#define SPF_TURRETG2_TURBO 8 -#define SPF_TURRETG2_LEAD_ENEMY 16 -#define SPF_SHOWONRADAR 32 - -#define ARM_ANGLE_RANGE 60 -#define HEAD_ANGLE_RANGE 90 +#define ARM_ANGLE_RANGE 60 +#define HEAD_ANGLE_RANGE 90 #define name "models/map_objects/imp_mine/turret_canon.glm" #define name2 "models/map_objects/imp_mine/turret_damage.md3" #define name3 "models/map_objects/wedge/laser_cannon_model.glm" -//special routine for tracking angles between client and server -rww -void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) -{ +// special routine for tracking angles between client and server -rww +void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) { int *thebone = &ent->s.boneIndex1; int *firstFree = NULL; int i = 0; @@ -53,23 +51,17 @@ void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) vec3_t *boneVector = &ent->s.boneAngles1; vec3_t *freeBoneVec = NULL; - while (thebone) - { - if (!*thebone && !firstFree) - { //if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. + while (thebone) { + if (!*thebone && !firstFree) { // if the value is 0 then this index is clear, we can use it if we don't find the bone we want already existing. firstFree = thebone; freeBoneVec = boneVector; - } - else if (*thebone) - { - if (*thebone == boneIndex) - { //this is it + } else if (*thebone) { + if (*thebone == boneIndex) { // this is it break; } } - switch (i) - { + switch (i) { case 0: thebone = &ent->s.boneIndex2; boneVector = &ent->s.boneAngles2; @@ -91,10 +83,8 @@ void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) i++; } - if (!thebone) - { //didn't find it, create it - if (!firstFree) - { //no free bones.. can't do a thing then. + if (!thebone) { // didn't find it, create it + if (!firstFree) { // no free bones.. can't do a thing then. Com_Printf("WARNING: NPC has no free bone indexes\n"); return; } @@ -105,16 +95,15 @@ void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) boneVector = freeBoneVec; } - //If we got here then we have a vector and an index. + // If we got here then we have a vector and an index. - //Copy the angles over the vector in the entitystate, so we can use the corresponding index - //to set the bone angles on the client. + // Copy the angles over the vector in the entitystate, so we can use the corresponding index + // to set the bone angles on the client. VectorCopy(angles, *boneVector); - //Now set the angles on our server instance if we have one. + // Now set the angles on our server instance if we have one. - if (!ent->ghoul2) - { + if (!ent->ghoul2) { return; } @@ -123,34 +112,21 @@ void G2Tur_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles) right = NEGATIVE_Z; forward = NEGATIVE_X; - //first 3 bits is forward, second 3 bits is right, third 3 bits is up - ent->s.boneOrient = ((forward)|(right<<3)|(up<<6)); - - trap->G2API_SetBoneAngles( ent->ghoul2, - 0, - bone, - angles, - flags, - up, - right, - forward, - NULL, - 100, - level.time ); + // first 3 bits is forward, second 3 bits is right, third 3 bits is up + ent->s.boneOrient = ((forward) | (right << 3) | (up << 6)); + + trap->G2API_SetBoneAngles(ent->ghoul2, 0, bone, angles, flags, up, right, forward, NULL, 100, level.time); } -void turretG2_set_models( gentity_t *self, qboolean dying ) -{ - if ( dying ) - { - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - self->s.modelindex = G_ModelIndex( name2 ); - self->s.modelindex2 = G_ModelIndex( name ); +void turretG2_set_models(gentity_t *self, qboolean dying) { + if (dying) { + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + self->s.modelindex = G_ModelIndex(name2); + self->s.modelindex2 = G_ModelIndex(name); } - trap->G2API_RemoveGhoul2Model( &self->ghoul2, 0 ); - G_KillG2Queue( self->s.number ); + trap->G2API_RemoveGhoul2Model(&self->ghoul2, 0); + G_KillG2Queue(self->s.number); self->s.modelGhoul2 = 0; /* trap->G2API_InitGhoul2Model( &self->ghoul2, @@ -164,232 +140,181 @@ void turretG2_set_models( gentity_t *self, qboolean dying ) 0, 0); */ - } - else - { - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - self->s.modelindex = G_ModelIndex( name ); - self->s.modelindex2 = G_ModelIndex( name2 ); - //set the new onw - trap->G2API_InitGhoul2Model( &self->ghoul2, - name, - 0, //base->s.modelindex, - //note, this is not the same kind of index - this one's referring to the actual - //index of the model in the g2 instance, whereas modelindex is the index of a - //configstring -rww - 0, - 0, - 0, - 0); - } - else - { - self->s.modelindex = G_ModelIndex( name3 ); - //set the new onw - trap->G2API_InitGhoul2Model( &self->ghoul2, - name3, - 0, //base->s.modelindex, - //note, this is not the same kind of index - this one's referring to the actual - //index of the model in the g2 instance, whereas modelindex is the index of a - //configstring -rww - 0, - 0, - 0, - 0); + } else { + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + self->s.modelindex = G_ModelIndex(name); + self->s.modelindex2 = G_ModelIndex(name2); + // set the new onw + trap->G2API_InitGhoul2Model(&self->ghoul2, name, + 0, // base->s.modelindex, + // note, this is not the same kind of index - this one's referring to the actual + // index of the model in the g2 instance, whereas modelindex is the index of a + // configstring -rww + 0, 0, 0, 0); + } else { + self->s.modelindex = G_ModelIndex(name3); + // set the new onw + trap->G2API_InitGhoul2Model(&self->ghoul2, name3, + 0, // base->s.modelindex, + // note, this is not the same kind of index - this one's referring to the actual + // index of the model in the g2 instance, whereas modelindex is the index of a + // configstring -rww + 0, 0, 0, 0); } self->s.modelGhoul2 = 1; - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - {//larger + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { // larger self->s.g2radius = 128; - } - else - { + } else { self->s.g2radius = 80; } - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - {//different pitch bone and muzzle flash points + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { // different pitch bone and muzzle flash points G2Tur_SetBoneAngles(self, "pitch", vec3_origin); - self->genericValue11 = trap->G2API_AddBolt( self->ghoul2, 0, "*muzzle1" ); - self->genericValue12 = trap->G2API_AddBolt( self->ghoul2, 0, "*muzzle2" ); - } - else - { + self->genericValue11 = trap->G2API_AddBolt(self->ghoul2, 0, "*muzzle1"); + self->genericValue12 = trap->G2API_AddBolt(self->ghoul2, 0, "*muzzle2"); + } else { G2Tur_SetBoneAngles(self, "Bone_body", vec3_origin); - self->genericValue11 = trap->G2API_AddBolt( self->ghoul2, 0, "*flash03" ); + self->genericValue11 = trap->G2API_AddBolt(self->ghoul2, 0, "*flash03"); } } } //------------------------------------------------------------------------------------------------------------ -void TurretG2Pain( gentity_t *self, gentity_t *attacker, int damage ) +void TurretG2Pain(gentity_t *self, gentity_t *attacker, int damage) //------------------------------------------------------------------------------------------------------------ { - if (self->paintarget && self->paintarget[0]) - { - if (self->genericValue8 < level.time) - { + if (self->paintarget && self->paintarget[0]) { + if (self->genericValue8 < level.time) { G_UseTargets2(self, self, self->paintarget); self->genericValue8 = level.time + self->genericValue4; } } - if ( attacker->client && attacker->client->ps.weapon == WP_DEMP2 ) - { + if (attacker->client && attacker->client->ps.weapon == WP_DEMP2) { self->attackDebounceTime = level.time + 2000 + Q_flrand(0.0f, 1.0f) * 500; self->painDebounceTime = self->attackDebounceTime; } - if ( !self->enemy ) - {//react to being hit - G_SetEnemy( self, attacker ); + if (!self->enemy) { // react to being hit + G_SetEnemy(self, attacker); } - //self->s.health = self->health; - //mmm..yes..bad. + // self->s.health = self->health; + // mmm..yes..bad. } //------------------------------------------------------------------------------------------------------------ -void turretG2_die ( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) +void turretG2_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) //------------------------------------------------------------------------------------------------------------ { - vec3_t forward = { 0,0,-1 }, pos; + vec3_t forward = {0, 0, -1}, pos; // Turn off the thinking of the base & use it's targets - //self->think = NULL; + // self->think = NULL; self->use = NULL; // clear my data - self->die = NULL; + self->die = NULL; self->pain = NULL; self->takedamage = qfalse; self->s.health = self->health = 0; self->s.loopSound = 0; self->s.shouldtarget = qfalse; - //self->s.owner = MAX_CLIENTS; //not owned by any client + // self->s.owner = MAX_CLIENTS; //not owned by any client // hack the effect angle so that explode death can orient the effect properly - if ( self->spawnflags & 2 ) - { - VectorSet( forward, 0, 0, 1 ); + if (self->spawnflags & 2) { + VectorSet(forward, 0, 0, 1); } -// VectorCopy( self->r.currentOrigin, self->s.pos.trBase ); + // VectorCopy( self->r.currentOrigin, self->s.pos.trBase ); - VectorMA( self->r.currentOrigin, 12, forward, pos ); - G_PlayEffect( EFFECT_EXPLOSION_TURRET, pos, forward ); + VectorMA(self->r.currentOrigin, 12, forward, pos); + G_PlayEffect(EFFECT_EXPLOSION_TURRET, pos, forward); - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->r.currentOrigin, - attacker, - self->splashDamage, - self->splashRadius, - attacker, - NULL, - MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, NULL, MOD_UNKNOWN); } - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 1; // black } self->s.weapon = 0; // crosshair code uses this to mark crosshair red - if ( self->s.modelindex2 ) - { + if (self->s.modelindex2) { // switch to damage model if we should - turretG2_set_models( self, qtrue ); + turretG2_set_models(self, qtrue); - VectorCopy( self->r.currentAngles, self->s.apos.trBase ); - VectorClear( self->s.apos.trDelta ); + VectorCopy(self->r.currentAngles, self->s.apos.trBase); + VectorClear(self->s.apos.trDelta); - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) - {//respawn - if (self->health < 1 && !self->genericValue5) - { //we are dead, set our respawn delay if we have one + if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) { // respawn + if (self->health < 1 && !self->genericValue5) { // we are dead, set our respawn delay if we have one self->genericValue5 = level.time + self->count; } } - } - else - { - ObjectDie( self, inflictor, attacker, damage, meansOfDeath ); + } else { + ObjectDie(self, inflictor, attacker, damage, meansOfDeath); } } #define START_DIS 15 -//start an animation on model_root both server side and client side -void TurboLaser_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) -{ - //set info on the entity so it knows to start the anim on the client next snapshot. +// start an animation on model_root both server side and client side +void TurboLaser_SetBoneAnim(gentity_t *eweb, int startFrame, int endFrame) { + // set info on the entity so it knows to start the anim on the client next snapshot. eweb->s.eFlags |= EF_G2ANIMATING; - if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) - { //already playing this anim, let's flag it to restart + if (eweb->s.torsoAnim == startFrame && eweb->s.legsAnim == endFrame) { // already playing this anim, let's flag it to restart eweb->s.torsoFlip = !eweb->s.torsoFlip; - } - else - { + } else { eweb->s.torsoAnim = startFrame; eweb->s.legsAnim = endFrame; } - //now set the animation on the server ghoul2 instance. + // now set the animation on the server ghoul2 instance. assert(eweb->ghoul2); - trap->G2API_SetBoneAnim(eweb->ghoul2, 0, "model_root", startFrame, endFrame, - (BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); + trap->G2API_SetBoneAnim(eweb->ghoul2, 0, "model_root", startFrame, endFrame, (BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND), 1.0f, level.time, -1, 100); } -extern void WP_FireTurboLaserMissile( gentity_t *ent, vec3_t start, vec3_t dir ); +extern void WP_FireTurboLaserMissile(gentity_t *ent, vec3_t start, vec3_t dir); //---------------------------------------------------------------- -static void turretG2_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) +static void turretG2_fire(gentity_t *ent, vec3_t start, vec3_t dir) //---------------------------------------------------------------- { - vec3_t org, ang; - gentity_t *bolt; + vec3_t org, ang; + gentity_t *bolt; - if ( (trap->PointContents( start, ent->s.number )&MASK_SHOT) ) - { + if ((trap->PointContents(start, ent->s.number) & MASK_SHOT)) { return; } - VectorMA( start, -START_DIS, dir, org ); // dumb.... + VectorMA(start, -START_DIS, dir, org); // dumb.... - if ( ent->random ) - { - vectoangles( dir, ang ); - ang[PITCH] += flrand( -ent->random, ent->random ); - ang[YAW] += flrand( -ent->random, ent->random ); - AngleVectors( ang, dir, NULL, NULL ); + if (ent->random) { + vectoangles(dir, ang); + ang[PITCH] += flrand(-ent->random, ent->random); + ang[YAW] += flrand(-ent->random, ent->random); + AngleVectors(ang, dir, NULL, NULL); } vectoangles(dir, ang); - if ( (ent->spawnflags&SPF_TURRETG2_TURBO) ) - { - //muzzle flash - G_PlayEffectID( ent->genericValue13, org, ang ); - WP_FireTurboLaserMissile( ent, start, dir ); - if ( ent->alt_fire ) - { - TurboLaser_SetBoneAnim( ent, 2, 3 ); - } - else - { - TurboLaser_SetBoneAnim( ent, 0, 1 ); - } - } - else - { - G_PlayEffectID( G_EffectIndex("blaster/muzzle_flash"), org, ang ); + if ((ent->spawnflags & SPF_TURRETG2_TURBO)) { + // muzzle flash + G_PlayEffectID(ent->genericValue13, org, ang); + WP_FireTurboLaserMissile(ent, start, dir); + if (ent->alt_fire) { + TurboLaser_SetBoneAnim(ent, 2, 3); + } else { + TurboLaser_SetBoneAnim(ent, 0, 1); + } + } else { + G_PlayEffectID(G_EffectIndex("blaster/muzzle_flash"), org, ang); bolt = G_Spawn(); bolt->classname = "turret_proj"; @@ -401,226 +326,175 @@ static void turretG2_fire ( gentity_t *ent, vec3_t start, vec3_t dir ) bolt->damage = ent->damage; bolt->alliedTeam = ent->alliedTeam; bolt->teamnodmg = ent->teamnodmg; - bolt->dflags = (DAMAGE_NO_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS); // Don't push them around, or else we are constantly re-aiming + bolt->dflags = (DAMAGE_NO_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS); // Don't push them around, or else we are constantly re-aiming bolt->splashDamage = ent->splashDamage; bolt->splashRadius = ent->splashDamage; - bolt->methodOfDeath = MOD_TARGET_LASER;//MOD_ENERGY; - bolt->splashMethodOfDeath = MOD_TARGET_LASER;//MOD_ENERGY; + bolt->methodOfDeath = MOD_TARGET_LASER; // MOD_ENERGY; + bolt->splashMethodOfDeath = MOD_TARGET_LASER; // MOD_ENERGY; bolt->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - //bolt->trigger_formation = qfalse; // don't draw tail on first frame + // bolt->trigger_formation = qfalse; // don't draw tail on first frame - VectorSet( bolt->r.maxs, 1.5, 1.5, 1.5 ); - VectorScale( bolt->r.maxs, -1, bolt->r.mins ); + VectorSet(bolt->r.maxs, 1.5, 1.5, 1.5); + VectorScale(bolt->r.maxs, -1, bolt->r.mins); bolt->s.pos.trType = TR_LINEAR; bolt->s.pos.trTime = level.time; - VectorCopy( start, bolt->s.pos.trBase ); - VectorScale( dir, ent->mass, bolt->s.pos.trDelta ); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy( start, bolt->r.currentOrigin); + VectorCopy(start, bolt->s.pos.trBase); + VectorScale(dir, ent->mass, bolt->s.pos.trDelta); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->r.currentOrigin); } } -void turretG2_respawn( gentity_t *self ) -{ +void turretG2_respawn(gentity_t *self) { self->use = turretG2_base_use; self->pain = TurretG2Pain; - self->die = turretG2_die; + self->die = turretG2_die; self->takedamage = qtrue; self->s.shouldtarget = qtrue; - //self->s.owner = MAX_CLIENTS; //not owned by any client - if ( self->s.eFlags & EF_SHADER_ANIM ) - { + // self->s.owner = MAX_CLIENTS; //not owned by any client + if (self->s.eFlags & EF_SHADER_ANIM) { self->s.frame = 0; // normal } self->s.weapon = WP_TURRET; // crosshair code uses this to mark crosshair red - turretG2_set_models( self, qfalse ); + turretG2_set_models(self, qfalse); self->s.health = self->health = self->genericValue6; if (self->maxHealth) { G_ScaleNetHealth(self); } - self->genericValue5 = 0;//clear this now + self->genericValue5 = 0; // clear this now } //----------------------------------------------------- -void turretG2_head_think( gentity_t *self ) +void turretG2_head_think(gentity_t *self) //----------------------------------------------------- { // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time - if ( self->enemy - && self->setTime < level.time - && self->attackDebounceTime < level.time ) - { - vec3_t fwd, org; - mdxaBone_t boltMatrix; + if (self->enemy && self->setTime < level.time && self->attackDebounceTime < level.time) { + vec3_t fwd, org; + mdxaBone_t boltMatrix; // set up our next fire time self->setTime = level.time + self->wait; // Getting the flash bolt here - trap->G2API_GetBoltMatrix( self->ghoul2, - 0, - (self->alt_fire?self->genericValue12:self->genericValue11), - &boltMatrix, - self->r.currentAngles, - self->r.currentOrigin, - level.time, - NULL, - self->modelScale ); - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { + trap->G2API_GetBoltMatrix(self->ghoul2, 0, (self->alt_fire ? self->genericValue12 : self->genericValue11), &boltMatrix, self->r.currentAngles, + self->r.currentOrigin, level.time, NULL, self->modelScale); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { self->alt_fire = !self->alt_fire; } - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); - //BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Y, fwd ); - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_X, fwd ); - } - else - { - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_X, fwd ); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org); + // BG_GiveMeVectorFromMatrix( &boltMatrix, POSITIVE_Y, fwd ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_X, fwd); + } else { + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, fwd); } - VectorMA( org, START_DIS, fwd, org ); + VectorMA(org, START_DIS, fwd, org); - turretG2_fire( self, org, fwd ); - self->fly_sound_debounce_time = level.time;//used as lastShotTime + turretG2_fire(self, org, fwd); + self->fly_sound_debounce_time = level.time; // used as lastShotTime } } //----------------------------------------------------- -static void turretG2_aim( gentity_t *self ) +static void turretG2_aim(gentity_t *self) //----------------------------------------------------- { - vec3_t enemyDir, org, org2; - vec3_t desiredAngles, setAngle; - float diffYaw = 0.0f, diffPitch = 0.0f; - float maxYawSpeed = (self->spawnflags&SPF_TURRETG2_TURBO)?30.0f:14.0f; - float maxPitchSpeed = (self->spawnflags&SPF_TURRETG2_TURBO)?15.0f:3.0f; + vec3_t enemyDir, org, org2; + vec3_t desiredAngles, setAngle; + float diffYaw = 0.0f, diffPitch = 0.0f; + float maxYawSpeed = (self->spawnflags & SPF_TURRETG2_TURBO) ? 30.0f : 14.0f; + float maxPitchSpeed = (self->spawnflags & SPF_TURRETG2_TURBO) ? 15.0f : 3.0f; // move our gun base yaw to where we should be at this time.... - BG_EvaluateTrajectory( &self->s.apos, level.time, self->r.currentAngles ); - self->r.currentAngles[YAW] = AngleNormalize360( self->r.currentAngles[YAW] ); - self->speed = AngleNormalize360( self->speed ); + BG_EvaluateTrajectory(&self->s.apos, level.time, self->r.currentAngles); + self->r.currentAngles[YAW] = AngleNormalize360(self->r.currentAngles[YAW]); + self->speed = AngleNormalize360(self->speed); - if ( self->enemy ) - { - mdxaBone_t boltMatrix; + if (self->enemy) { + mdxaBone_t boltMatrix; // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->r.currentOrigin, org); } - else - { - VectorCopy( self->enemy->r.currentOrigin, org ); - } - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] -= 5; } - if ( (self->spawnflags&SPF_TURRETG2_LEAD_ENEMY) ) - {//we want to lead them a bit + if ((self->spawnflags & SPF_TURRETG2_LEAD_ENEMY)) { // we want to lead them a bit vec3_t diff, velocity; float dist; - VectorSubtract( org, self->s.origin, diff ); - dist = VectorNormalize( diff ); - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->ps.velocity, velocity ); - } - else - { - VectorCopy( self->enemy->s.pos.trDelta, velocity ); + VectorSubtract(org, self->s.origin, diff); + dist = VectorNormalize(diff); + if (self->enemy->client) { + VectorCopy(self->enemy->client->ps.velocity, velocity); + } else { + VectorCopy(self->enemy->s.pos.trDelta, velocity); } - VectorMA( org, (dist/self->mass), velocity, org ); + VectorMA(org, (dist / self->mass), velocity, org); } // Getting the "eye" here - trap->G2API_GetBoltMatrix( self->ghoul2, - 0, - (self->alt_fire?self->genericValue12:self->genericValue11), - &boltMatrix, - self->r.currentAngles, - self->s.origin, - level.time, - NULL, - self->modelScale ); - - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org2 ); - - VectorSubtract( org, org2, enemyDir ); - vectoangles( enemyDir, desiredAngles ); - - diffYaw = AngleSubtract( self->r.currentAngles[YAW], desiredAngles[YAW] ); - diffPitch = AngleSubtract( self->speed, desiredAngles[PITCH] ); - } - else - { + trap->G2API_GetBoltMatrix(self->ghoul2, 0, (self->alt_fire ? self->genericValue12 : self->genericValue11), &boltMatrix, self->r.currentAngles, + self->s.origin, level.time, NULL, self->modelScale); + + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, org2); + + VectorSubtract(org, org2, enemyDir); + vectoangles(enemyDir, desiredAngles); + + diffYaw = AngleSubtract(self->r.currentAngles[YAW], desiredAngles[YAW]); + diffPitch = AngleSubtract(self->speed, desiredAngles[PITCH]); + } else { // no enemy, so make us slowly sweep back and forth as if searching for a new one -// diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. + // diffYaw = sin( level.time * 0.0001f + self->count ) * 5.0f; // don't do this for now since it can make it go into walls. } - if ( diffYaw ) - { + if (diffYaw) { // cap max speed.... - if ( fabs(diffYaw) > maxYawSpeed ) - { - diffYaw = ( diffYaw >= 0 ? maxYawSpeed : -maxYawSpeed ); + if (fabs(diffYaw) > maxYawSpeed) { + diffYaw = (diffYaw >= 0 ? maxYawSpeed : -maxYawSpeed); } // ...then set up our desired yaw - VectorSet( setAngle, 0.0f, diffYaw, 0.0f ); + VectorSet(setAngle, 0.0f, diffYaw, 0.0f); - VectorCopy( self->r.currentAngles, self->s.apos.trBase ); - VectorScale( setAngle,- 5, self->s.apos.trDelta ); + VectorCopy(self->r.currentAngles, self->s.apos.trBase); + VectorScale(setAngle, -5, self->s.apos.trDelta); self->s.apos.trTime = level.time; self->s.apos.trType = TR_LINEAR; } - if ( diffPitch ) - { - if ( fabs(diffPitch) > maxPitchSpeed ) - { + if (diffPitch) { + if (fabs(diffPitch) > maxPitchSpeed) { // cap max speed self->speed += (diffPitch > 0.0f) ? -maxPitchSpeed : maxPitchSpeed; - } - else - { + } else { // small enough, so just add half the diff so we smooth out the stopping - self->speed -= ( diffPitch );//desiredAngles[PITCH]; + self->speed -= (diffPitch); // desiredAngles[PITCH]; } // Note that this is NOT interpolated, so it will be less smooth...On the other hand, it does use Ghoul2 to blend, so it may smooth it out a bit? - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - if ( self->spawnflags & 2 ) - { - VectorSet( desiredAngles, 0.0f, 0.0f, -self->speed ); - } - else - { - VectorSet( desiredAngles, 0.0f, 0.0f, self->speed ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + if (self->spawnflags & 2) { + VectorSet(desiredAngles, 0.0f, 0.0f, -self->speed); + } else { + VectorSet(desiredAngles, 0.0f, 0.0f, self->speed); } G2Tur_SetBoneAngles(self, "pitch", desiredAngles); - } - else - { - if ( self->spawnflags & 2 ) - { - VectorSet( desiredAngles, self->speed, 0.0f, 0.0f ); - } - else - { - VectorSet( desiredAngles, -self->speed, 0.0f, 0.0f ); + } else { + if (self->spawnflags & 2) { + VectorSet(desiredAngles, self->speed, 0.0f, 0.0f); + } else { + VectorSet(desiredAngles, -self->speed, 0.0f, 0.0f); } G2Tur_SetBoneAngles(self, "Bone_body", desiredAngles); } @@ -639,40 +513,31 @@ static void turretG2_aim( gentity_t *self ) */ } - if ( diffYaw || diffPitch ) - {//FIXME: turbolaser sounds - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - self->s.loopSound = G_SoundIndex( "sound/vehicles/weapons/turbolaser/turn.wav" ); - } - else - { - self->s.loopSound = G_SoundIndex( "sound/chars/turret/move.wav" ); + if (diffYaw || diffPitch) { // FIXME: turbolaser sounds + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + self->s.loopSound = G_SoundIndex("sound/vehicles/weapons/turbolaser/turn.wav"); + } else { + self->s.loopSound = G_SoundIndex("sound/chars/turret/move.wav"); } - } - else - { + } else { self->s.loopSound = 0; } } //----------------------------------------------------- -static void turretG2_turnoff( gentity_t *self ) +static void turretG2_turnoff(gentity_t *self) //----------------------------------------------------- { - if ( self->enemy == NULL ) - { + if (self->enemy == NULL) { // we don't need to turnoff return; } - if ( (self->spawnflags&SPF_TURRETG2_TURBO) ) - { - TurboLaser_SetBoneAnim( self, 4, 5 ); + if ((self->spawnflags & SPF_TURRETG2_TURBO)) { + TurboLaser_SetBoneAnim(self, 4, 5); } // shut-down sound - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/shutdown.wav" )); + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/chars/turret/shutdown.wav")); } // make turret play ping sound for 5 seconds @@ -683,125 +548,101 @@ static void turretG2_turnoff( gentity_t *self ) } //----------------------------------------------------- -static qboolean turretG2_find_enemies( gentity_t *self ) +static qboolean turretG2_find_enemies(gentity_t *self) //----------------------------------------------------- { - qboolean found = qfalse; - int i, count; - float bestDist = self->radius * self->radius; - float enemyDist; - vec3_t enemyDir, org, org2; - qboolean foundClient = qfalse; - gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; - - if ( self->aimDebounceTime > level.time ) // time since we've been shut off + qboolean found = qfalse; + int i, count; + float bestDist = self->radius * self->radius; + float enemyDist; + vec3_t enemyDir, org, org2; + qboolean foundClient = qfalse; + gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; + + if (self->aimDebounceTime > level.time) // time since we've been shut off { // We were active and alert, i.e. had an enemy in the last 3 secs - if ( self->painDebounceTime < level.time ) - { - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - G_Sound(self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/ping.wav" )); + if (self->painDebounceTime < level.time) { + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/chars/turret/ping.wav")); } self->painDebounceTime = level.time + 1000; } } - VectorCopy( self->r.currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->r.currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 20; - } - else - { + } else { org2[2] -= 20; } - count = G_RadiusList( org2, self->radius, self, qtrue, entity_list ); + count = G_RadiusList(org2, self->radius, self, qtrue, entity_list); - for ( i = 0; i < count; i++ ) - { - trace_t tr; + for (i = 0; i < count; i++) { + trace_t tr; target = entity_list[i]; - if ( !target->client ) - { + if (!target->client) { // only attack clients - if ( !(target->flags&FL_BBRUSH)//not a breakable brush - || !target->takedamage//is a bbrush, but invincible - || (target->NPC_targetname&&self->targetname&&Q_stricmp(target->NPC_targetname,self->targetname)!=0) )//not in invicible bbrush, but can only be broken by an NPC that is not me + if (!(target->flags & FL_BBRUSH) // not a breakable brush + || !target->takedamage // is a bbrush, but invincible + || (target->NPC_targetname && self->targetname && + Q_stricmp(target->NPC_targetname, self->targetname) != 0)) // not in invicible bbrush, but can only be broken by an NPC that is not me { continue; } - //else: we will shoot at bbrushes! + // else: we will shoot at bbrushes! } - if ( target == self || !target->takedamage || target->health <= 0 || ( target->flags & FL_NOTARGET )) - { + if (target == self || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( target->client && target->client->sess.sessionTeam == TEAM_SPECTATOR ) - { + if (target->client && target->client->sess.sessionTeam == TEAM_SPECTATOR) { continue; } - if ( target->client && target->client->tempSpectate >= level.time ) - { + if (target->client && target->client->tempSpectate >= level.time) { continue; } - if ( self->alliedTeam ) - { - if ( target->client ) - { - if ( target->client->sess.sessionTeam == self->alliedTeam ) - { + if (self->alliedTeam) { + if (target->client) { + if (target->client->sess.sessionTeam == self->alliedTeam) { // A bot/client/NPC we don't want to shoot continue; } - } - else if ( target->teamnodmg == self->alliedTeam ) - { + } else if (target->teamnodmg == self->alliedTeam) { // An ent we don't want to shoot continue; } } - if ( !trap->InPVS( org2, target->r.currentOrigin )) - { + if (!trap->InPVS(org2, target->r.currentOrigin)) { continue; } - if ( target->client ) - { - VectorCopy( target->client->renderInfo.eyePoint, org ); - } - else - { - VectorCopy( target->r.currentOrigin, org ); + if (target->client) { + VectorCopy(target->client->renderInfo.eyePoint, org); + } else { + VectorCopy(target->r.currentOrigin, org); } - if ( self->spawnflags & 2 ) - { + if (self->spawnflags & 2) { org[2] -= 15; - } - else - { + } else { org[2] += 5; } - trap->Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid && ( tr.fraction == 1.0 || tr.entityNum == target->s.number )) - { + if (!tr.allsolid && !tr.startsolid && (tr.fraction == 1.0 || tr.entityNum == target->s.number)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->r.currentOrigin, self->r.currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->r.currentOrigin, self->r.currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist || (target->client && !foundClient))// all things equal, keep current + if (enemyDist < bestDist || (target->client && !foundClient)) // all things equal, keep current { - if ( self->attackDebounceTime < level.time ) - { + if (self->attackDebounceTime < level.time) { // We haven't fired or acquired an enemy in the last 2 seconds-start-up sound - if ( !(self->spawnflags&SPF_TURRETG2_TURBO) ) - { - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/chars/turret/startup.wav" )); + if (!(self->spawnflags & SPF_TURRETG2_TURBO)) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/chars/turret/startup.wav")); } // Wind up turrets for a bit @@ -811,16 +652,14 @@ static qboolean turretG2_find_enemies( gentity_t *self ) bestTarget = target; bestDist = enemyDist; found = qtrue; - if ( target->client ) - {//prefer clients over non-clients + if (target->client) { // prefer clients over non-clients foundClient = qtrue; } } } } - if ( found ) - { + if (found) { /* if ( !self->enemy ) {//just aquired one @@ -828,10 +667,9 @@ static qboolean turretG2_find_enemies( gentity_t *self ) AddSightEvent( bestTarget, self->r.currentOrigin, 512, AEL_DISCOVERED, 20 ); } */ - G_SetEnemy( self, bestTarget ); - if ( VALIDSTRING( self->target2 )) - { - G_UseTargets2( self, self, self->target2 ); + G_SetEnemy(self, bestTarget); + if (VALIDSTRING(self->target2)) { + G_UseTargets2(self, self, self->target2); } } @@ -839,157 +677,119 @@ static qboolean turretG2_find_enemies( gentity_t *self ) } //----------------------------------------------------- -void turretG2_base_think( gentity_t *self ) +void turretG2_base_think(gentity_t *self) //----------------------------------------------------- { - qboolean turnOff = qtrue; - float enemyDist; - vec3_t enemyDir, org, org2; + qboolean turnOff = qtrue; + float enemyDist; + vec3_t enemyDir, org, org2; self->nextthink = level.time + FRAMETIME; - if ( self->health <= 0 ) - {//dead - if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) - {//can respawn - if ( self->genericValue5 && self->genericValue5 < level.time ) - { //we are dead, see if it's time to respawn - turretG2_respawn( self ); + if (self->health <= 0) { // dead + if (self->spawnflags & SPF_TURRETG2_CANRESPAWN) { // can respawn + if (self->genericValue5 && self->genericValue5 < level.time) { // we are dead, see if it's time to respawn + turretG2_respawn(self); } } return; - } - else if ( self->spawnflags & 1 ) - {// not turned on - turretG2_turnoff( self ); - turretG2_aim( self ); + } else if (self->spawnflags & 1) { // not turned on + turretG2_turnoff(self); + turretG2_aim(self); // No target self->flags |= FL_NOTARGET; return; - } - else - { + } else { // I'm all hot and bothered self->flags &= ~FL_NOTARGET; } - if ( self->enemy ) - { - if ( self->enemy->health < 0 - || !self->enemy->inuse ) - { + if (self->enemy) { + if (self->enemy->health < 0 || !self->enemy->inuse) { self->enemy = NULL; } } - if ( self->last_move_time < level.time ) - {//MISNOMER: used a enemy recalcing debouncer - if ( turretG2_find_enemies( self ) ) - {//found one + if (self->last_move_time < level.time) { // MISNOMER: used a enemy recalcing debouncer + if (turretG2_find_enemies(self)) { // found one turnOff = qfalse; - if ( self->enemy && self->enemy->client ) - {//hold on to clients for a min of 3 seconds + if (self->enemy && self->enemy->client) { // hold on to clients for a min of 3 seconds self->last_move_time = level.time + 3000; - } - else - {//hold less + } else { // hold less self->last_move_time = level.time + 500; } } } - if ( self->enemy != NULL ) - { - if ( self->enemy->client && self->enemy->client->sess.sessionTeam == TEAM_SPECTATOR ) - {//don't keep going after spectators + if (self->enemy != NULL) { + if (self->enemy->client && self->enemy->client->sess.sessionTeam == TEAM_SPECTATOR) { // don't keep going after spectators self->enemy = NULL; - } - else if ( self->enemy->client && self->enemy->client->tempSpectate >= level.time ) - {//don't keep going after spectators + } else if (self->enemy->client && self->enemy->client->tempSpectate >= level.time) { // don't keep going after spectators self->enemy = NULL; - } - else - {//FIXME: remain single-minded or look for a new enemy every now and then? + } else { // FIXME: remain single-minded or look for a new enemy every now and then? // enemy is alive - VectorSubtract( self->enemy->r.currentOrigin, self->r.currentOrigin, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(self->enemy->r.currentOrigin, self->r.currentOrigin, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < self->radius * self->radius ) - { + if (enemyDist < self->radius * self->radius) { // was in valid radius - if ( trap->InPVS( self->r.currentOrigin, self->enemy->r.currentOrigin ) ) - { + if (trap->InPVS(self->r.currentOrigin, self->enemy->r.currentOrigin)) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; - if ( self->enemy->client ) - { - VectorCopy( self->enemy->client->renderInfo.eyePoint, org ); - } - else - { - VectorCopy( self->enemy->r.currentOrigin, org ); + if (self->enemy->client) { + VectorCopy(self->enemy->client->renderInfo.eyePoint, org); + } else { + VectorCopy(self->enemy->r.currentOrigin, org); } - VectorCopy( self->r.currentOrigin, org2 ); - if ( self->spawnflags & 2 ) - { + VectorCopy(self->r.currentOrigin, org2); + if (self->spawnflags & 2) { org2[2] += 10; - } - else - { + } else { org2[2] -= 10; } - trap->Trace( &tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( !tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number ) - { - turnOff = qfalse; // Can see our enemy + if (!tr.allsolid && !tr.startsolid && tr.entityNum == self->enemy->s.number) { + turnOff = qfalse; // Can see our enemy } } } - } } - if ( turnOff ) - { - if ( self->bounceCount < level.time ) // bounceCount is used to keep the thing from ping-ponging from on to off + if (turnOff) { + if (self->bounceCount < level.time) // bounceCount is used to keep the thing from ping-ponging from on to off { - turretG2_turnoff( self ); + turretG2_turnoff(self); } - } - else - { + } else { // keep our enemy for a minimum of 2 seconds from now self->bounceCount = level.time + 2000 + Q_flrand(0.0f, 1.0f) * 150; } - turretG2_aim( self ); - if ( !turnOff ) - { - turretG2_head_think( self ); + turretG2_aim(self); + if (!turnOff) { + turretG2_head_think(self); } } //----------------------------------------------------------------------------- -void turretG2_base_use( gentity_t *self, gentity_t *other, gentity_t *activator ) +void turretG2_base_use(gentity_t *self, gentity_t *other, gentity_t *activator) //----------------------------------------------------------------------------- { // Toggle on and off self->spawnflags = (self->spawnflags ^ 1); - if (( self->s.eFlags & EF_SHADER_ANIM ) && ( self->spawnflags & 1 )) // Start_Off + if ((self->s.eFlags & EF_SHADER_ANIM) && (self->spawnflags & 1)) // Start_Off { self->s.frame = 1; // black - } - else - { + } else { self->s.frame = 0; // glow } } - /*QUAKED misc_turretG2 (1 0 0) (-8 -8 -22) (8 8 0) START_OFF UPSIDE_DOWN CANRESPAWN TURBO LEAD SHOWRADAR Turret that hangs from the ceiling, will aim and shoot at enemies @@ -1043,53 +843,46 @@ Turret that hangs from the ceiling, will aim and shoot at enemies "icon" - icon that represents the objective on the radar */ //----------------------------------------------------- -void SP_misc_turretG2( gentity_t *base ) +void SP_misc_turretG2(gentity_t *base) //----------------------------------------------------- { int customscaleVal; - char* s; + char *s; - turretG2_set_models( base, qfalse ); + turretG2_set_models(base, qfalse); G_SpawnInt("painwait", "0", &base->genericValue4); base->genericValue8 = 0; G_SpawnInt("customscale", "0", &customscaleVal); base->s.iModelScale = customscaleVal; - if (base->s.iModelScale) - { - if (base->s.iModelScale > 1023) - { + if (base->s.iModelScale) { + if (base->s.iModelScale > 1023) { base->s.iModelScale = 1023; } - base->modelScale[0] = base->modelScale[1] = base->modelScale[2] = base->s.iModelScale/100.0f; + base->modelScale[0] = base->modelScale[1] = base->modelScale[2] = base->s.iModelScale / 100.0f; } - G_SpawnString( "icon", "", &s ); - if (s && s[0]) - { + G_SpawnString("icon", "", &s); + if (s && s[0]) { // We have an icon, so index it now. We are reusing the genericenemyindex // variable rather than adding a new one to the entity state. base->s.genericenemyindex = G_IconIndex(s); } - finish_spawning_turretG2( base ); + finish_spawning_turretG2(base); - if (( base->spawnflags & 1 )) // Start_Off + if ((base->spawnflags & 1)) // Start_Off { base->s.frame = 1; // black - } - else - { + } else { base->s.frame = 0; // glow } - if ( !(base->spawnflags&SPF_TURRETG2_TURBO) ) - { + if (!(base->spawnflags & SPF_TURRETG2_TURBO)) { base->s.eFlags |= EF_SHADER_ANIM; } - if (base->spawnflags & SPF_SHOWONRADAR) - { + if (base->spawnflags & SPF_SHOWONRADAR) { base->s.eFlags |= EF_RADAROBJECT; } #undef name @@ -1098,34 +891,31 @@ void SP_misc_turretG2( gentity_t *base ) } //----------------------------------------------------- -void finish_spawning_turretG2( gentity_t *base ) -{ - vec3_t fwd; - int t; +void finish_spawning_turretG2(gentity_t *base) { + vec3_t fwd; + int t; - if ( (base->spawnflags&2) ) - { + if ((base->spawnflags & 2)) { base->s.angles[ROLL] += 180; base->s.origin[2] -= 22.0f; } - G_SetAngles( base, base->s.angles ); - AngleVectors( base->r.currentAngles, fwd, NULL, NULL ); + G_SetAngles(base, base->s.angles); + AngleVectors(base->r.currentAngles, fwd, NULL, NULL); G_SetOrigin(base, base->s.origin); base->s.eType = ET_GENERAL; - if ( base->team && base->team[0] && //level.gametype == GT_SIEGE && - !base->teamnodmg) - { + if (base->team && base->team[0] && // level.gametype == GT_SIEGE && + !base->teamnodmg) { base->teamnodmg = atoi(base->team); } base->team = NULL; // Set up our explosion effect for the ExplodeDeath code.... - G_EffectIndex( "turret/explode" ); - G_EffectIndex( "sparks/spark_exp_nosnd" ); + G_EffectIndex("turret/explode"); + G_EffectIndex("sparks/spark_exp_nosnd"); base->use = turretG2_base_use; base->pain = TurretG2Pain; @@ -1138,177 +928,147 @@ void finish_spawning_turretG2( gentity_t *base ) base->speed = 0; // respawn time defaults to 20 seconds - if ( (base->spawnflags&SPF_TURRETG2_CANRESPAWN) && !base->count ) - { + if ((base->spawnflags & SPF_TURRETG2_CANRESPAWN) && !base->count) { base->count = 20000; } - G_SpawnFloat( "shotspeed", "0", &base->mass ); - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - if ( !base->random ) - {//error worked into projectile direction + G_SpawnFloat("shotspeed", "0", &base->mass); + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + if (!base->random) { // error worked into projectile direction base->random = 2.0f; } - if ( !base->mass ) - {//misnomer: speed of projectile + if (!base->mass) { // misnomer: speed of projectile base->mass = 20000; } - if ( !base->health ) - { + if (!base->health) { base->health = 2000; } // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 32768; } // How quickly to fire - if ( !base->wait ) - { - base->wait = 1000;// + Q_flrand(0.0f, 1.0f) * 500; + if (!base->wait) { + base->wait = 1000; // + Q_flrand(0.0f, 1.0f) * 500; } - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 200; } - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 500; } // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 500; } - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - VectorSet( base->r.maxs, 64.0f, 64.0f, 30.0f ); - VectorSet( base->r.mins, -64.0f, -64.0f, -30.0f ); + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + VectorSet(base->r.maxs, 64.0f, 64.0f, 30.0f); + VectorSet(base->r.mins, -64.0f, -64.0f, -30.0f); } - //start in "off" anim - TurboLaser_SetBoneAnim( base, 4, 5 ); - if ( level.gametype == GT_SIEGE ) - {//FIXME: designer-specified? - //FIXME: put on other entities, too, particularly siege objectives and bbrushes... + // start in "off" anim + TurboLaser_SetBoneAnim(base, 4, 5); + if (level.gametype == GT_SIEGE) { // FIXME: designer-specified? + // FIXME: put on other entities, too, particularly siege objectives and bbrushes... base->s.eFlags2 |= EF2_BRACKET_ENTITY; } - } - else - { - if ( !base->random ) - {//error worked into projectile direction + } else { + if (!base->random) { // error worked into projectile direction base->random = 2.0f; } - if ( !base->mass ) - {//misnomer: speed of projectile + if (!base->mass) { // misnomer: speed of projectile base->mass = 1100; } - if ( !base->health ) - { + if (!base->health) { base->health = 100; } // search radius - if ( !base->radius ) - { + if (!base->radius) { base->radius = 512; } // How quickly to fire - if ( !base->wait ) - { + if (!base->wait) { base->wait = 150 + Q_flrand(0.0f, 1.0f) * 55; } - if ( !base->splashDamage ) - { + if (!base->splashDamage) { base->splashDamage = 10; } - if ( !base->splashRadius ) - { + if (!base->splashRadius) { base->splashRadius = 25; } // how much damage each shot does - if ( !base->damage ) - { + if (!base->damage) { base->damage = 5; } - if ( base->spawnflags & 2 ) - {//upside-down, invert r.mins and maxe - VectorSet( base->r.maxs, 10.0f, 10.0f, 30.0f ); - VectorSet( base->r.mins, -10.0f, -10.0f, 0.0f ); - } - else - { - VectorSet( base->r.maxs, 10.0f, 10.0f, 0.0f ); - VectorSet( base->r.mins, -10.0f, -10.0f, -30.0f ); + if (base->spawnflags & 2) { // upside-down, invert r.mins and maxe + VectorSet(base->r.maxs, 10.0f, 10.0f, 30.0f); + VectorSet(base->r.mins, -10.0f, -10.0f, 0.0f); + } else { + VectorSet(base->r.maxs, 10.0f, 10.0f, 0.0f); + VectorSet(base->r.mins, -10.0f, -10.0f, -30.0f); } } - //stash health off for respawn. NOTE: cannot use maxhealth because that might not be set if not showing the health bar + // stash health off for respawn. NOTE: cannot use maxhealth because that might not be set if not showing the health bar base->genericValue6 = base->health; - G_SpawnInt( "showhealth", "0", &t ); - if (t) - { //a non-0 maxhealth value will mean we want to show the health on the hud + G_SpawnInt("showhealth", "0", &t); + if (t) { // a non-0 maxhealth value will mean we want to show the health on the hud base->maxHealth = base->health; G_ScaleNetHealth(base); base->s.shouldtarget = qtrue; - //base->s.owner = MAX_CLIENTS; //not owned by any client + // base->s.owner = MAX_CLIENTS; //not owned by any client } - if (base->s.iModelScale) - { //let's scale the bbox too... - float fScale = base->s.iModelScale/100.0f; + if (base->s.iModelScale) { // let's scale the bbox too... + float fScale = base->s.iModelScale / 100.0f; VectorScale(base->r.mins, fScale, base->r.mins); VectorScale(base->r.maxs, fScale, base->r.maxs); } // Precache special FX and moving sounds - if ( (base->spawnflags&SPF_TURRETG2_TURBO) ) - { - base->genericValue13 = G_EffectIndex( "turret/turb_muzzle_flash" ); - base->genericValue14 = G_EffectIndex( "turret/turb_shot" ); - base->genericValue15 = G_EffectIndex( "turret/turb_impact" ); - //FIXME: Turbo Laser Cannon sounds! - G_SoundIndex( "sound/vehicles/weapons/turbolaser/turn.wav" ); - } - else - { - G_SoundIndex( "sound/chars/turret/startup.wav" ); - G_SoundIndex( "sound/chars/turret/shutdown.wav" ); - G_SoundIndex( "sound/chars/turret/ping.wav" ); - G_SoundIndex( "sound/chars/turret/move.wav" ); + if ((base->spawnflags & SPF_TURRETG2_TURBO)) { + base->genericValue13 = G_EffectIndex("turret/turb_muzzle_flash"); + base->genericValue14 = G_EffectIndex("turret/turb_shot"); + base->genericValue15 = G_EffectIndex("turret/turb_impact"); + // FIXME: Turbo Laser Cannon sounds! + G_SoundIndex("sound/vehicles/weapons/turbolaser/turn.wav"); + } else { + G_SoundIndex("sound/chars/turret/startup.wav"); + G_SoundIndex("sound/chars/turret/shutdown.wav"); + G_SoundIndex("sound/chars/turret/ping.wav"); + G_SoundIndex("sound/chars/turret/move.wav"); } - base->r.contents = CONTENTS_BODY|CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_SHOTCLIP; + base->r.contents = CONTENTS_BODY | CONTENTS_PLAYERCLIP | CONTENTS_MONSTERCLIP | CONTENTS_SHOTCLIP; - //base->max_health = base->health; + // base->max_health = base->health; base->takedamage = qtrue; - base->die = turretG2_die; + base->die = turretG2_die; base->material = MAT_METAL; - //base->r.svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; + // base->r.svFlags |= SVF_NO_TELEPORT|SVF_NONNPC_ENEMY|SVF_SELF_ANIMATING; // Register this so that we can use it for the missile effect - RegisterItem( BG_FindItemForWeapon( WP_BLASTER )); + RegisterItem(BG_FindItemForWeapon(WP_BLASTER)); // But set us as a turret so that we can be identified as a turret base->s.weapon = WP_TURRET; - trap->LinkEntity( (sharedEntity_t *)base ); + trap->LinkEntity((sharedEntity_t *)base); } diff --git a/codemp/game/g_utils.c b/codemp/game/g_utils.c index bbda55a4c6..83b60eacb8 100644 --- a/codemp/game/g_utils.c +++ b/codemp/game/g_utils.c @@ -28,9 +28,9 @@ along with this program; if not, see . #include "qcommon/q_shared.h" typedef struct shaderRemap_s { - char oldShader[MAX_QPATH]; - char newShader[MAX_QPATH]; - float timeOffset; + char oldShader[MAX_QPATH]; + char newShader[MAX_QPATH]; + float timeOffset; } shaderRemap_t; #define MAX_SHADER_REMAPS 128 @@ -44,28 +44,28 @@ void AddRemap(const char *oldShader, const char *newShader, float timeOffset) { for (i = 0; i < remapCount; i++) { if (Q_stricmp(oldShader, remappedShaders[i].oldShader) == 0) { // found it, just update this one - strcpy(remappedShaders[i].newShader,newShader); + strcpy(remappedShaders[i].newShader, newShader); remappedShaders[i].timeOffset = timeOffset; return; } } if (remapCount < MAX_SHADER_REMAPS) { - strcpy(remappedShaders[remapCount].newShader,newShader); - strcpy(remappedShaders[remapCount].oldShader,oldShader); + strcpy(remappedShaders[remapCount].newShader, newShader); + strcpy(remappedShaders[remapCount].oldShader, oldShader); remappedShaders[remapCount].timeOffset = timeOffset; remapCount++; } } const char *BuildShaderStateConfig(void) { - static char buff[MAX_STRING_CHARS*4]; + static char buff[MAX_STRING_CHARS * 4]; char out[(MAX_QPATH * 2) + 5]; int i; memset(buff, 0, MAX_STRING_CHARS); for (i = 0; i < remapCount; i++) { Com_sprintf(out, (MAX_QPATH * 2) + 5, "%s=%s:%5.2f@", remappedShaders[i].oldShader, remappedShaders[i].newShader, remappedShaders[i].timeOffset); - Q_strcat( buff, sizeof( buff ), out); + Q_strcat(buff, sizeof(buff), out); } return buff; } @@ -84,33 +84,33 @@ G_FindConfigstringIndex ================ */ -static int G_FindConfigstringIndex( const char *name, int start, int max, qboolean create ) { - int i; - char s[MAX_STRING_CHARS]; +static int G_FindConfigstringIndex(const char *name, int start, int max, qboolean create) { + int i; + char s[MAX_STRING_CHARS]; - if ( !VALIDSTRING( name ) ) { + if (!VALIDSTRING(name)) { return 0; } - for ( i=1 ; iGetConfigstring( start + i, s, sizeof( s ) ); - if ( !s[0] ) { + for (i = 1; i < max; i++) { + trap->GetConfigstring(start + i, s, sizeof(s)); + if (!s[0]) { break; } - if ( !strcmp( s, name ) ) { + if (!strcmp(s, name)) { return i; } } - if ( !create ) { + if (!create) { return 0; } - if ( i == max ) { - trap->Error( ERR_DROP, "G_FindConfigstringIndex: overflow" ); + if (i == max) { + trap->Error(ERR_DROP, "G_FindConfigstringIndex: overflow"); } - trap->SetConfigstring( start + i, name ); + trap->SetConfigstring(start + i, name); return i; } @@ -119,69 +119,52 @@ static int G_FindConfigstringIndex( const char *name, int start, int max, qboole Ghoul2 Insert Start */ -int G_BoneIndex( const char *name ) { - return G_FindConfigstringIndex (name, CS_G2BONES, MAX_G2BONES, qtrue); -} +int G_BoneIndex(const char *name) { return G_FindConfigstringIndex(name, CS_G2BONES, MAX_G2BONES, qtrue); } /* Ghoul2 Insert End */ -int G_ModelIndex( const char *name ) { +int G_ModelIndex(const char *name) { #ifdef _DEBUG_MODEL_PATH_ON_SERVER - //debug to see if we are shoving data into configstrings for models that don't exist, and if - //so, where we are doing it from -rww + // debug to see if we are shoving data into configstrings for models that don't exist, and if + // so, where we are doing it from -rww fileHandle_t fh; trap->FS_Open(name, &fh, FS_READ); - if (!fh) - { //try models/ then, this is assumed for registering models + if (!fh) { // try models/ then, this is assumed for registering models trap->FS_Open(va("models/%s", name), &fh, FS_READ); - if (!fh) - { + if (!fh) { Com_Printf("ERROR: Server tried to modelindex %s but it doesn't exist.\n", name); } } - if (fh) - { + if (fh) { trap->FS_Close(fh); } #endif - return G_FindConfigstringIndex (name, CS_MODELS, MAX_MODELS, qtrue); + return G_FindConfigstringIndex(name, CS_MODELS, MAX_MODELS, qtrue); } -int G_IconIndex( const char* name ) -{ +int G_IconIndex(const char *name) { assert(name && name[0]); - return G_FindConfigstringIndex (name, CS_ICONS, MAX_ICONS, qtrue); + return G_FindConfigstringIndex(name, CS_ICONS, MAX_ICONS, qtrue); } -int G_SoundIndex( const char *name ) { +int G_SoundIndex(const char *name) { assert(name && name[0]); - return G_FindConfigstringIndex (name, CS_SOUNDS, MAX_SOUNDS, qtrue); + return G_FindConfigstringIndex(name, CS_SOUNDS, MAX_SOUNDS, qtrue); } -int G_SoundSetIndex(const char *name) -{ - return G_FindConfigstringIndex (name, CS_AMBIENT_SET, MAX_AMBIENT_SETS, qtrue); -} +int G_SoundSetIndex(const char *name) { return G_FindConfigstringIndex(name, CS_AMBIENT_SET, MAX_AMBIENT_SETS, qtrue); } -int G_EffectIndex( const char *name ) -{ - return G_FindConfigstringIndex (name, CS_EFFECTS, MAX_FX, qtrue); -} +int G_EffectIndex(const char *name) { return G_FindConfigstringIndex(name, CS_EFFECTS, MAX_FX, qtrue); } -int G_BSPIndex( const char *name ) -{ - return G_FindConfigstringIndex (name, CS_BSP_MODELS, MAX_SUB_BSP, qtrue); -} +int G_BSPIndex(const char *name) { return G_FindConfigstringIndex(name, CS_BSP_MODELS, MAX_SUB_BSP, qtrue); } //===================================================================== - -//see if we can or should allow this guy to use a custom skeleton -rww -qboolean G_PlayerHasCustomSkeleton(gentity_t *ent) -{ +// see if we can or should allow this guy to use a custom skeleton -rww +qboolean G_PlayerHasCustomSkeleton(gentity_t *ent) { /* siegeClass_t *scl; @@ -215,19 +198,18 @@ G_TeamCommand Broadcasts a command to only a specific team ================ */ -void G_TeamCommand( team_t team, char *cmd ) { - int i; +void G_TeamCommand(team_t team, char *cmd) { + int i; - for ( i = 0 ; i < level.maxclients ; i++ ) { - if ( level.clients[i].pers.connected == CON_CONNECTED ) { - if ( level.clients[i].sess.sessionTeam == team ) { - trap->SendServerCommand( i, va("%s", cmd )); + for (i = 0; i < level.maxclients; i++) { + if (level.clients[i].pers.connected == CON_CONNECTED) { + if (level.clients[i].sess.sessionTeam == team) { + trap->SendServerCommand(i, va("%s", cmd)); } } } } - /* ============= G_Find @@ -240,149 +222,123 @@ NULL will be returned if the end of the list is reached. ============= */ -gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match) -{ - char *s; +gentity_t *G_Find(gentity_t *from, int fieldofs, const char *match) { + char *s; if (!from) from = g_entities; else from++; - for ( ; from < &g_entities[level.num_entities] ; from++) - { + for (; from < &g_entities[level.num_entities]; from++) { if (!from->inuse) continue; - s = *(char **) ((byte *)from + fieldofs); + s = *(char **)((byte *)from + fieldofs); if (!s) continue; - if (!Q_stricmp (s, match)) + if (!Q_stricmp(s, match)) return from; } return NULL; } - - /* ============ G_RadiusList - given an origin and a radius, return all entities that are in use that are within the list ============ */ -int G_RadiusList ( vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) -{ - float dist; - gentity_t *ent; - int entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - - if ( radius < 1 ) - { +int G_RadiusList(vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]) { + float dist; + gentity_t *ent; + int entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + + if (radius < 1) { radius = 1; } - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = &g_entities[entityList[ e ]]; + for (e = 0; e < numListedEntities; e++) { + ent = &g_entities[entityList[e]]; if ((ent == ignore) || !(ent->inuse) || ent->takedamage != takeDamage) continue; // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( origin[i] < ent->r.absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (origin[i] < ent->r.absmin[i]) { v[i] = ent->r.absmin[i] - origin[i]; - } else if ( origin[i] > ent->r.absmax[i] ) - { + } else if (origin[i] > ent->r.absmax[i]) { v[i] = origin[i] - ent->r.absmax[i]; - } else - { + } else { v[i] = 0; } } - dist = VectorLength( v ); - if ( dist >= radius ) - { + dist = VectorLength(v); + if (dist >= radius) { continue; } // ok, we are within the radius, add us to the incoming list ent_list[ent_count] = ent; ent_count++; - } // we are done, return how many we found - return(ent_count); + return (ent_count); } - //---------------------------------------------------------- -void G_Throw( gentity_t *targ, vec3_t newDir, float push ) +void G_Throw(gentity_t *targ, vec3_t newDir, float push) //---------------------------------------------------------- { - vec3_t kvel; - float mass; + vec3_t kvel; + float mass; - if ( targ->physicsBounce > 0 ) //overide the mass + if (targ->physicsBounce > 0) // overide the mass { mass = targ->physicsBounce; - } - else - { + } else { mass = 200; } - if ( g_gravity.value > 0 ) - { - VectorScale( newDir, g_knockback.value * (float)push / mass * 0.8, kvel ); + if (g_gravity.value > 0) { + VectorScale(newDir, g_knockback.value * (float)push / mass * 0.8, kvel); kvel[2] = newDir[2] * g_knockback.value * (float)push / mass * 1.5; - } - else - { - VectorScale( newDir, g_knockback.value * (float)push / mass, kvel ); + } else { + VectorScale(newDir, g_knockback.value * (float)push / mass, kvel); } - if ( targ->client ) - { - VectorAdd( targ->client->ps.velocity, kvel, targ->client->ps.velocity ); - } - else if ( targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP ) - { - VectorAdd( targ->s.pos.trDelta, kvel, targ->s.pos.trDelta ); - VectorCopy( targ->r.currentOrigin, targ->s.pos.trBase ); + if (targ->client) { + VectorAdd(targ->client->ps.velocity, kvel, targ->client->ps.velocity); + } else if (targ->s.pos.trType != TR_STATIONARY && targ->s.pos.trType != TR_LINEAR_STOP && targ->s.pos.trType != TR_NONLINEAR_STOP) { + VectorAdd(targ->s.pos.trDelta, kvel, targ->s.pos.trDelta); + VectorCopy(targ->r.currentOrigin, targ->s.pos.trBase); targ->s.pos.trTime = level.time; } // set the timer so that the other client can't cancel // out the movement immediately - if ( targ->client && !targ->client->ps.pm_time ) - { - int t; + if (targ->client && !targ->client->ps.pm_time) { + int t; t = push * 2; - if ( t < 50 ) - { + if (t < 50) { t = 50; } - if ( t > 200 ) - { + if (t > 200) { t = 200; } targ->client->ps.pm_time = t; @@ -390,36 +346,31 @@ void G_Throw( gentity_t *targ, vec3_t newDir, float push ) } } -//methods of creating/freeing "fake" dynamically allocated client entity structures. -//You ABSOLUTELY MUST free this client after creating it before game shutdown. If -//it is left around you will have a memory leak, because true dynamic memory is -//allocated by the exe. -void G_FreeFakeClient(gclient_t **cl) -{ //or not, the dynamic stuff is busted somehow at the moment. Yet it still works in the test. - //I think something is messed up in being able to cast the memory to stuff to modify it, - //while modifying it directly seems to work fine. - //trap->TrueFree((void **)cl); +// methods of creating/freeing "fake" dynamically allocated client entity structures. +// You ABSOLUTELY MUST free this client after creating it before game shutdown. If +// it is left around you will have a memory leak, because true dynamic memory is +// allocated by the exe. +void G_FreeFakeClient(gclient_t **cl) { // or not, the dynamic stuff is busted somehow at the moment. Yet it still works in the test. + // I think something is messed up in being able to cast the memory to stuff to modify it, + // while modifying it directly seems to work fine. + // trap->TrueFree((void **)cl); } -//allocate a veh object -#define MAX_VEHICLES_AT_A_TIME 512//128 +// allocate a veh object +#define MAX_VEHICLES_AT_A_TIME 512 // 128 static Vehicle_t g_vehiclePool[MAX_VEHICLES_AT_A_TIME]; static qboolean g_vehiclePoolOccupied[MAX_VEHICLES_AT_A_TIME]; static qboolean g_vehiclePoolInit = qfalse; -void G_AllocateVehicleObject(Vehicle_t **pVeh) -{ +void G_AllocateVehicleObject(Vehicle_t **pVeh) { int i = 0; - if (!g_vehiclePoolInit) - { + if (!g_vehiclePoolInit) { g_vehiclePoolInit = qtrue; memset(g_vehiclePoolOccupied, 0, sizeof(g_vehiclePoolOccupied)); } - while (i < MAX_VEHICLES_AT_A_TIME) - { //iterate through and try to find a free one - if (!g_vehiclePoolOccupied[i]) - { + while (i < MAX_VEHICLES_AT_A_TIME) { // iterate through and try to find a free one + if (!g_vehiclePoolOccupied[i]) { g_vehiclePoolOccupied[i] = qtrue; memset(&g_vehiclePool[i], 0, sizeof(Vehicle_t)); *pVeh = &g_vehiclePool[i]; @@ -430,15 +381,11 @@ void G_AllocateVehicleObject(Vehicle_t **pVeh) Com_Error(ERR_DROP, "Ran out of vehicle pool slots."); } -//free the pointer, sort of a lame method -void G_FreeVehicleObject(Vehicle_t *pVeh) -{ +// free the pointer, sort of a lame method +void G_FreeVehicleObject(Vehicle_t *pVeh) { int i = 0; - while (i < MAX_VEHICLES_AT_A_TIME) - { - if (g_vehiclePoolOccupied[i] && - &g_vehiclePool[i] == pVeh) - { //guess this is it + while (i < MAX_VEHICLES_AT_A_TIME) { + if (g_vehiclePoolOccupied[i] && &g_vehiclePool[i] == pVeh) { // guess this is it g_vehiclePoolOccupied[i] = qfalse; break; } @@ -448,28 +395,23 @@ void G_FreeVehicleObject(Vehicle_t *pVeh) gclient_t *gClPtrs[MAX_GENTITIES]; -void G_CreateFakeClient(int entNum, gclient_t **cl) -{ - //trap->TrueMalloc((void **)cl, sizeof(gclient_t)); - if (!gClPtrs[entNum]) - { - gClPtrs[entNum] = (gclient_t *) BG_Alloc(sizeof(gclient_t)); +void G_CreateFakeClient(int entNum, gclient_t **cl) { + // trap->TrueMalloc((void **)cl, sizeof(gclient_t)); + if (!gClPtrs[entNum]) { + gClPtrs[entNum] = (gclient_t *)BG_Alloc(sizeof(gclient_t)); } *cl = gClPtrs[entNum]; } -//call this on game shutdown to run through and get rid of all the lingering client pointers. -void G_CleanAllFakeClients(void) -{ - int i = MAX_CLIENTS; //start off here since all ents below have real client structs. +// call this on game shutdown to run through and get rid of all the lingering client pointers. +void G_CleanAllFakeClients(void) { + int i = MAX_CLIENTS; // start off here since all ents below have real client structs. gentity_t *ent; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { ent = &g_entities[i]; - if (ent->inuse && ent->s.eType == ET_NPC && ent->client) - { + if (ent->inuse && ent->s.eType == ET_NPC && ent->client) { G_FreeFakeClient(&ent->client); } i++; @@ -484,11 +426,10 @@ Finally reworked PM_SetAnim to allow non-pmove calls, so we take our local anim index into account and make the call -rww ============= */ -void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags, int blendTime); +void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags, int blendTime); -void G_SetAnim(gentity_t *ent, usercmd_t *ucmd, int setAnimParts, int anim, int setAnimFlags, int blendTime) -{ -#if 0 //old hackish way +void G_SetAnim(gentity_t *ent, usercmd_t *ucmd, int setAnimParts, int anim, int setAnimFlags, int blendTime) { +#if 0 // old hackish way pmove_t pmv; assert(ent && ent->inuse && ent->client); @@ -511,13 +452,12 @@ void G_SetAnim(gentity_t *ent, usercmd_t *ucmd, int setAnimParts, int anim, int //don't need to bother with ghoul2 stuff, it's not even used in PM_SetAnim. pm = &pmv; PM_SetAnim(setAnimParts, anim, setAnimFlags, blendTime); -#else //new clean and shining way! +#else // new clean and shining way! assert(ent->client); - BG_SetAnim(&ent->client->ps, bgAllAnims[ent->localAnimIndex].anims, setAnimParts, anim, setAnimFlags, blendTime); + BG_SetAnim(&ent->client->ps, bgAllAnims[ent->localAnimIndex].anims, setAnimParts, anim, setAnimFlags, blendTime); #endif } - /* ============= G_PickTarget @@ -525,23 +465,20 @@ G_PickTarget Selects a random entity from among the targets ============= */ -#define MAXCHOICES 32 +#define MAXCHOICES 32 -gentity_t *G_PickTarget (char *targetname) -{ - gentity_t *ent = NULL; - int num_choices = 0; - gentity_t *choice[MAXCHOICES]; +gentity_t *G_PickTarget(char *targetname) { + gentity_t *ent = NULL; + int num_choices = 0; + gentity_t *choice[MAXCHOICES]; - if (!targetname) - { + if (!targetname) { trap->Print("G_PickTarget called with NULL targetname\n"); return NULL; } - while(1) - { - ent = G_Find (ent, FOFS(targetname), targetname); + while (1) { + ent = G_Find(ent, FOFS(targetname), targetname); if (!ent) break; choice[num_choices++] = ent; @@ -549,8 +486,7 @@ gentity_t *G_PickTarget (char *targetname) break; } - if (!num_choices) - { + if (!num_choices) { trap->Print("G_PickTarget: target %s not found\n", targetname); return NULL; } @@ -558,24 +494,21 @@ gentity_t *G_PickTarget (char *targetname) return choice[rand() % num_choices]; } -void GlobalUse(gentity_t *self, gentity_t *other, gentity_t *activator) -{ - if (!self || (self->flags & FL_INACTIVE)) - { +void GlobalUse(gentity_t *self, gentity_t *other, gentity_t *activator) { + if (!self || (self->flags & FL_INACTIVE)) { return; } - if (!self->use) - { + if (!self->use) { return; } self->use(self, other, activator); } -void G_UseTargets2( gentity_t *ent, gentity_t *activator, const char *string ) { - gentity_t *t; +void G_UseTargets2(gentity_t *ent, gentity_t *activator, const char *string) { + gentity_t *t; - if ( !ent ) { + if (!ent) { return; } @@ -585,20 +518,20 @@ void G_UseTargets2( gentity_t *ent, gentity_t *activator, const char *string ) { trap->SetConfigstring(CS_SHADERSTATE, BuildShaderStateConfig()); } - if ( !string || !string[0] ) { + if (!string || !string[0]) { return; } t = NULL; - while ( (t = G_Find (t, FOFS(targetname), string)) != NULL ) { - if ( t == ent ) { - trap->Print ("WARNING: Entity used itself.\n"); + while ((t = G_Find(t, FOFS(targetname), string)) != NULL) { + if (t == ent) { + trap->Print("WARNING: Entity used itself.\n"); } else { - if ( t->use ) { + if (t->use) { GlobalUse(t, ent, activator); } } - if ( !ent->inuse ) { + if (!ent->inuse) { trap->Print("entity was removed while using targets\n"); return; } @@ -615,16 +548,13 @@ match (string)self.target and call their .use function ============================== */ -void G_UseTargets( gentity_t *ent, gentity_t *activator ) -{ - if (!ent) - { +void G_UseTargets(gentity_t *ent, gentity_t *activator) { + if (!ent) { return; } G_UseTargets2(ent, activator, ent->target); } - /* ============= TempVector @@ -633,15 +563,15 @@ This is just a convenience function for making temporary vectors for function calls ============= */ -float *tv( float x, float y, float z ) { - static int index; - static vec3_t vecs[8]; - float *v; +float *tv(float x, float y, float z) { + static int index; + static vec3_t vecs[8]; + float *v; // use an array so that multiple tempvectors won't collide // for a while v = vecs[index]; - index = (index + 1)&7; + index = (index + 1) & 7; v[0] = x; v[1] = y; @@ -650,7 +580,6 @@ float *tv( float x, float y, float z ) { return v; } - /* ============= VectorToString @@ -659,21 +588,20 @@ This is just a convenience function for printing vectors ============= */ -char *vtos( const vec3_t v ) { - static int index; - static char str[8][32]; - char *s; +char *vtos(const vec3_t v) { + static int index; + static char str[8][32]; + char *s; // use an array so that multiple vtos won't collide s = str[index]; - index = (index + 1)&7; + index = (index + 1) & 7; - Com_sprintf (s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2]); + Com_sprintf(s, 32, "(%i %i %i)", (int)v[0], (int)v[1], (int)v[2]); return s; } - /* =============== G_SetMovedir @@ -684,35 +612,34 @@ Angles will be cleared, because it is being used to represent a direction instead of an orientation. =============== */ -void G_SetMovedir( vec3_t angles, vec3_t movedir ) { - static vec3_t VEC_UP = {0, -1, 0}; - static vec3_t MOVEDIR_UP = {0, 0, 1}; - static vec3_t VEC_DOWN = {0, -2, 0}; - static vec3_t MOVEDIR_DOWN = {0, 0, -1}; - - if ( VectorCompare (angles, VEC_UP) ) { - VectorCopy (MOVEDIR_UP, movedir); - } else if ( VectorCompare (angles, VEC_DOWN) ) { - VectorCopy (MOVEDIR_DOWN, movedir); +void G_SetMovedir(vec3_t angles, vec3_t movedir) { + static vec3_t VEC_UP = {0, -1, 0}; + static vec3_t MOVEDIR_UP = {0, 0, 1}; + static vec3_t VEC_DOWN = {0, -2, 0}; + static vec3_t MOVEDIR_DOWN = {0, 0, -1}; + + if (VectorCompare(angles, VEC_UP)) { + VectorCopy(MOVEDIR_UP, movedir); + } else if (VectorCompare(angles, VEC_DOWN)) { + VectorCopy(MOVEDIR_DOWN, movedir); } else { - AngleVectors (angles, movedir, NULL, NULL); + AngleVectors(angles, movedir, NULL, NULL); } - VectorClear( angles ); + VectorClear(angles); } -void G_InitGentity( gentity_t *e ) { +void G_InitGentity(gentity_t *e) { e->inuse = qtrue; e->classname = "noclass"; e->s.number = e - g_entities; e->r.ownerNum = ENTITYNUM_NONE; - e->s.modelGhoul2 = 0; //assume not + e->s.modelGhoul2 = 0; // assume not - trap->ICARUS_FreeEnt( (sharedEntity_t *)e ); //ICARUS information must be added after this point + trap->ICARUS_FreeEnt((sharedEntity_t *)e); // ICARUS information must be added after this point } -//give us some decent info on all the active ents -rww -static void G_SpewEntList(void) -{ +// give us some decent info on all the active ents -rww +static void G_SpewEntList(void) { int i = 0; int numNPC = 0; int numProjectile = 0; @@ -727,50 +654,37 @@ static void G_SpewEntList(void) trap->FS_Open("entspew.txt", &fh, FS_WRITE); #endif - while (i < ENTITYNUM_MAX_NORMAL) - { + while (i < ENTITYNUM_MAX_NORMAL) { ent = &g_entities[i]; - if (ent->inuse) - { - if (ent->s.eType == ET_NPC) - { + if (ent->inuse) { + if (ent->s.eType == ET_NPC) { numNPC++; - } - else if (ent->s.eType == ET_MISSILE) - { + } else if (ent->s.eType == ET_MISSILE) { numProjectile++; - } - else if (ent->freeAfterEvent) - { + } else if (ent->freeAfterEvent) { numTempEnt++; - if (ent->s.eFlags & EF_SOUNDTRACKER) - { + if (ent->s.eFlags & EF_SOUNDTRACKER) { numTempEntST++; } - str = va("TEMPENT %4i: EV %i\n", ent->s.number, ent->s.eType-ET_EVENTS); + str = va("TEMPENT %4i: EV %i\n", ent->s.number, ent->s.eType - ET_EVENTS); Com_Printf(str); #ifdef _DEBUG - if (fh) - { + if (fh) { trap->FS_Write(str, strlen(str), fh); } #endif } - if (ent->classname && ent->classname[0]) - { + if (ent->classname && ent->classname[0]) { strcpy(className, ent->classname); - } - else - { + } else { strcpy(className, "Unknown"); } str = va("ENT %4i: Classname %s\n", ent->s.number, className); Com_Printf(str); #ifdef _DEBUG - if (fh) - { + if (fh) { trap->FS_Write(str, strlen(str), fh); } #endif @@ -782,8 +696,7 @@ static void G_SpewEntList(void) str = va("TempEnt count: %i\nTempEnt ST: %i\nNPC count: %i\nProjectile count: %i\n", numTempEnt, numTempEntST, numNPC, numProjectile); Com_Printf(str); #ifdef _DEBUG - if (fh) - { + if (fh) { trap->FS_Write(str, strlen(str), fh); trap->FS_Close(fh); } @@ -805,54 +718,52 @@ instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ -gentity_t *G_Spawn( void ) { - int i, force; - gentity_t *e; +gentity_t *G_Spawn(void) { + int i, force; + gentity_t *e; - e = NULL; // shut up warning - i = 0; // shut up warning - for ( force = 0 ; force < 2 ; force++ ) { + e = NULL; // shut up warning + i = 0; // shut up warning + for (force = 0; force < 2; force++) { // if we go through all entities and can't find one to free, // override the normal minimum times before use e = &g_entities[MAX_CLIENTS]; - for ( i = MAX_CLIENTS ; iinuse ) { + for (i = MAX_CLIENTS; i < level.num_entities; i++, e++) { + if (e->inuse) { continue; } // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy - if ( !force && e->freetime > level.startTime + 2000 && level.time - e->freetime < 1000 ) - { + if (!force && e->freetime > level.startTime + 2000 && level.time - e->freetime < 1000) { continue; } // reuse this slot - G_InitGentity( e ); + G_InitGentity(e); return e; } - if ( i != MAX_GENTITIES ) { + if (i != MAX_GENTITIES) { break; } } - if ( i == ENTITYNUM_MAX_NORMAL ) { + if (i == ENTITYNUM_MAX_NORMAL) { /* for (i = 0; i < MAX_GENTITIES; i++) { trap->Print("%4i: %s\n", i, g_entities[i].classname); } */ G_SpewEntList(); - trap->Error( ERR_DROP, "G_Spawn: no free entities" ); + trap->Error(ERR_DROP, "G_Spawn: no free entities"); } // open up a new slot level.num_entities++; // let the server system know that there are more entities - trap->LocateGameData( (sharedEntity_t *)level.gentities, level.num_entities, sizeof( gentity_t ), - &level.clients[0].ps, sizeof( level.clients[0] ) ); + trap->LocateGameData((sharedEntity_t *)level.gentities, level.num_entities, sizeof(gentity_t), &level.clients[0].ps, sizeof(level.clients[0])); - G_InitGentity( e ); + G_InitGentity(e); return e; } @@ -861,13 +772,13 @@ gentity_t *G_Spawn( void ) { G_EntitiesFree ================= */ -qboolean G_EntitiesFree( void ) { - int i; - gentity_t *e; +qboolean G_EntitiesFree(void) { + int i; + gentity_t *e; e = &g_entities[MAX_CLIENTS]; - for ( i = MAX_CLIENTS; i < level.num_entities; i++, e++) { - if ( e->inuse ) { + for (i = MAX_CLIENTS; i < level.num_entities; i++, e++) { + if (e->inuse) { continue; } // slot available @@ -881,43 +792,37 @@ qboolean G_EntitiesFree( void ) { int gG2KillIndex[MAX_G2_KILL_QUEUE]; int gG2KillNum = 0; -void G_SendG2KillQueue(void) -{ +void G_SendG2KillQueue(void) { char g2KillString[1024]; int i = 0; - if (!gG2KillNum) - { + if (!gG2KillNum) { return; } Com_sprintf(g2KillString, 1024, "kg2"); - while (i < gG2KillNum && i < 64) - { //send 64 at once, max... + while (i < gG2KillNum && i < 64) { // send 64 at once, max... Q_strcat(g2KillString, 1024, va(" %i", gG2KillIndex[i])); i++; } trap->SendServerCommand(-1, g2KillString); - //Clear the count because we just sent off the whole queue + // Clear the count because we just sent off the whole queue gG2KillNum -= i; - if (gG2KillNum < 0) - { //hmm, should be impossible, but I'm paranoid as we're far past beta. + if (gG2KillNum < 0) { // hmm, should be impossible, but I'm paranoid as we're far past beta. assert(0); gG2KillNum = 0; } } -void G_KillG2Queue(int entNum) -{ - if (gG2KillNum >= MAX_G2_KILL_QUEUE) - { //This would be considered a Bad Thing. +void G_KillG2Queue(int entNum) { + if (gG2KillNum >= MAX_G2_KILL_QUEUE) { // This would be considered a Bad Thing. #ifdef _DEBUG Com_Printf("WARNING: Exceeded the MAX_G2_KILL_QUEUE count for this frame!\n"); #endif - //Since we're out of queue slots, just send it now as a seperate command (eats more bandwidth, but we have no choice) + // Since we're out of queue slots, just send it now as a seperate command (eats more bandwidth, but we have no choice) trap->SendServerCommand(-1, va("kg2 %i", entNum)); return; } @@ -933,74 +838,63 @@ G_FreeEntity Marks the entity as free ================= */ -void G_FreeEntity( gentity_t *ed ) { - //gentity_t *te; +void G_FreeEntity(gentity_t *ed) { + // gentity_t *te; - if (ed->isSaberEntity) - { + if (ed->isSaberEntity) { #ifdef _DEBUG Com_Printf("Tried to remove JM saber!\n"); #endif return; } - trap->UnlinkEntity ((sharedEntity_t *)ed); // unlink from world + trap->UnlinkEntity((sharedEntity_t *)ed); // unlink from world - trap->ICARUS_FreeEnt( (sharedEntity_t *)ed ); //ICARUS information must be added after this point + trap->ICARUS_FreeEnt((sharedEntity_t *)ed); // ICARUS information must be added after this point - if ( ed->neverFree ) { + if (ed->neverFree) { return; } - //rww - this may seem a bit hackish, but unfortunately we have no access - //to anything ghoul2-related on the server and thus must send a message - //to let the client know he needs to clean up all the g2 stuff for this - //now-removed entity - if (ed->s.modelGhoul2) - { //force all clients to accept an event to destroy this instance, right now + // rww - this may seem a bit hackish, but unfortunately we have no access + // to anything ghoul2-related on the server and thus must send a message + // to let the client know he needs to clean up all the g2 stuff for this + // now-removed entity + if (ed->s.modelGhoul2) { // force all clients to accept an event to destroy this instance, right now /* te = G_TempEntity( vec3_origin, EV_DESTROY_GHOUL2_INSTANCE ); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = ed->s.number; */ - //Or not. Events can be dropped, so that would be a bad thing. + // Or not. Events can be dropped, so that would be a bad thing. G_KillG2Queue(ed->s.number); } - //And, free the server instance too, if there is one. - if (ed->ghoul2) - { + // And, free the server instance too, if there is one. + if (ed->ghoul2) { trap->G2API_CleanGhoul2Models(&(ed->ghoul2)); } - if (ed->s.eType == ET_NPC && ed->m_pVehicle) - { //tell the "vehicle pool" that this one is now free + if (ed->s.eType == ET_NPC && ed->m_pVehicle) { // tell the "vehicle pool" that this one is now free G_FreeVehicleObject(ed->m_pVehicle); } - if (ed->s.eType == ET_NPC && ed->client) - { //this "client" structure is one of our dynamically allocated ones, so free the memory + if (ed->s.eType == ET_NPC && ed->client) { // this "client" structure is one of our dynamically allocated ones, so free the memory int saberEntNum = -1; int i = 0; - if (ed->client->ps.saberEntityNum) - { + if (ed->client->ps.saberEntityNum) { saberEntNum = ed->client->ps.saberEntityNum; - } - else if (ed->client->saberStoredIndex) - { + } else if (ed->client->saberStoredIndex) { saberEntNum = ed->client->saberStoredIndex; } - if (saberEntNum > 0 && g_entities[saberEntNum].inuse) - { + if (saberEntNum > 0 && g_entities[saberEntNum].inuse) { g_entities[saberEntNum].neverFree = qfalse; G_FreeEntity(&g_entities[saberEntNum]); } - while (i < MAX_SABERS) - { - if (ed->client->weaponGhoul2[i] && trap->G2API_HaveWeGhoul2Models(ed->client->weaponGhoul2[i])) - { + while (i < MAX_SABERS) { + if (ed->client->weaponGhoul2[i] && trap->G2API_HaveWeGhoul2Models(ed->client->weaponGhoul2[i])) { trap->G2API_CleanGhoul2Models(&ed->client->weaponGhoul2[i]); } i++; @@ -1009,23 +903,18 @@ void G_FreeEntity( gentity_t *ed ) { G_FreeFakeClient(&ed->client); } - if (ed->s.eFlags & EF_SOUNDTRACKER) - { + if (ed->s.eFlags & EF_SOUNDTRACKER) { int i = 0; gentity_t *ent; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->inuse && ent->client) - { - int ch = TRACK_CHANNEL_NONE-50; + if (ent && ent->inuse && ent->client) { + int ch = TRACK_CHANNEL_NONE - 50; - while (ch < NUM_TRACK_CHANNELS-50) - { - if (ent->client->ps.fd.killSoundEntIndex[ch] == ed->s.number) - { + while (ch < NUM_TRACK_CHANNELS - 50) { + if (ent->client->ps.fd.killSoundEntIndex[ch] == ed->s.number) { ent->client->ps.fd.killSoundEntIndex[ch] = 0; } @@ -1036,11 +925,11 @@ void G_FreeEntity( gentity_t *ed ) { i++; } - //make sure clientside loop sounds are killed on the tracker and client + // make sure clientside loop sounds are killed on the tracker and client trap->SendServerCommand(-1, va("kls %i %i", ed->s.trickedentindex, ed->s.number)); } - memset (ed, 0, sizeof(*ed)); + memset(ed, 0, sizeof(*ed)); ed->classname = "freed"; ed->freetime = level.time; ed->inuse = qfalse; @@ -1055,9 +944,9 @@ The origin will be snapped to save net bandwidth, so care must be taken if the origin is right on a surface (snap towards start vector first) ================= */ -gentity_t *G_TempEntity( vec3_t origin, int event ) { - gentity_t *e; - vec3_t snapped; +gentity_t *G_TempEntity(vec3_t origin, int event) { + gentity_t *e; + vec3_t snapped; e = G_Spawn(); e->s.eType = ET_EVENTS + event; @@ -1066,21 +955,20 @@ gentity_t *G_TempEntity( vec3_t origin, int event ) { e->eventTime = level.time; e->freeAfterEvent = qtrue; - VectorCopy( origin, snapped ); - SnapVector( snapped ); // save network bandwidth - G_SetOrigin( e, snapped ); - //WTF? Why aren't we setting the s.origin? (like below) - //cg_events.c code checks origin all over the place!!! - //Trying to save bandwidth...? - //VectorCopy( snapped, e->s.origin ); + VectorCopy(origin, snapped); + SnapVector(snapped); // save network bandwidth + G_SetOrigin(e, snapped); + // WTF? Why aren't we setting the s.origin? (like below) + // cg_events.c code checks origin all over the place!!! + // Trying to save bandwidth...? + // VectorCopy( snapped, e->s.origin ); // find cluster for PVS - trap->LinkEntity( (sharedEntity_t *)e ); + trap->LinkEntity((sharedEntity_t *)e); return e; } - /* ================= G_SoundTempEntity @@ -1088,9 +976,9 @@ G_SoundTempEntity Special event entity that keeps sound trackers in mind ================= */ -gentity_t *G_SoundTempEntity( vec3_t origin, int event, int channel ) { - gentity_t *e; - vec3_t snapped; +gentity_t *G_SoundTempEntity(vec3_t origin, int event, int channel) { + gentity_t *e; + vec3_t snapped; e = G_Spawn(); @@ -1101,52 +989,43 @@ gentity_t *G_SoundTempEntity( vec3_t origin, int event, int channel ) { e->eventTime = level.time; e->freeAfterEvent = qtrue; - VectorCopy( origin, snapped ); - SnapVector( snapped ); // save network bandwidth - G_SetOrigin( e, snapped ); + VectorCopy(origin, snapped); + SnapVector(snapped); // save network bandwidth + G_SetOrigin(e, snapped); // find cluster for PVS - trap->LinkEntity( (sharedEntity_t *)e ); + trap->LinkEntity((sharedEntity_t *)e); return e; } - -//scale health down below 1024 to fit in health bits -void G_ScaleNetHealth(gentity_t *self) -{ +// scale health down below 1024 to fit in health bits +void G_ScaleNetHealth(gentity_t *self) { int maxHealth = self->maxHealth; - if (maxHealth < 1000) - { //it's good then + if (maxHealth < 1000) { // it's good then self->s.maxhealth = maxHealth; self->s.health = self->health; - if (self->s.health < 0) - { //don't let it wrap around + if (self->s.health < 0) { // don't let it wrap around self->s.health = 0; } return; } - //otherwise, scale it down - self->s.maxhealth = (maxHealth/100); - self->s.health = (self->health/100); + // otherwise, scale it down + self->s.maxhealth = (maxHealth / 100); + self->s.health = (self->health / 100); - if (self->s.health < 0) - { //don't let it wrap around + if (self->s.health < 0) { // don't let it wrap around self->s.health = 0; } - if (self->health > 0 && - self->s.health <= 0) - { //don't let it scale to 0 if the thing is still not "dead" + if (self->health > 0 && self->s.health <= 0) { // don't let it scale to 0 if the thing is still not "dead" self->s.health = 1; } } - - /* ============================================================================== @@ -1163,37 +1042,33 @@ Kills all entities that would touch the proposed new positioning of ent. Ent should be unlinked before calling this! ================= */ -void G_KillBox (gentity_t *ent) { - int i, num; - int touch[MAX_GENTITIES]; - gentity_t *hit; - vec3_t mins, maxs; +void G_KillBox(gentity_t *ent) { + int i, num; + int touch[MAX_GENTITIES]; + gentity_t *hit; + vec3_t mins, maxs; - VectorAdd( ent->client->ps.origin, ent->r.mins, mins ); - VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs ); - num = trap->EntitiesInBox( mins, maxs, touch, MAX_GENTITIES ); + VectorAdd(ent->client->ps.origin, ent->r.mins, mins); + VectorAdd(ent->client->ps.origin, ent->r.maxs, maxs); + num = trap->EntitiesInBox(mins, maxs, touch, MAX_GENTITIES); - for (i=0 ; iclient ) { + if (!hit->client) { continue; } - if (hit->s.number == ent->s.number) - { //don't telefrag yourself! + if (hit->s.number == ent->s.number) { // don't telefrag yourself! continue; } - if (ent->r.ownerNum == hit->s.number) - { //don't telefrag your vehicle! + if (ent->r.ownerNum == hit->s.number) { // don't telefrag your vehicle! continue; } // nail it - G_Damage ( hit, ent, ent, NULL, NULL, - 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); + G_Damage(hit, ent, ent, NULL, NULL, 100000, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); } - } //============================================================================== @@ -1207,14 +1082,13 @@ client side: jumppads and item pickups Adds an event+parm and twiddles the event counter =============== */ -void G_AddPredictableEvent( gentity_t *ent, int event, int eventParm ) { - if ( !ent->client ) { +void G_AddPredictableEvent(gentity_t *ent, int event, int eventParm) { + if (!ent->client) { return; } - BG_AddPredictableEventToPlayerstate( event, eventParm, &ent->client->ps ); + BG_AddPredictableEventToPlayerstate(event, eventParm, &ent->client->ps); } - /* =============== G_AddEvent @@ -1222,24 +1096,24 @@ G_AddEvent Adds an event+parm and twiddles the event counter =============== */ -void G_AddEvent( gentity_t *ent, int event, int eventParm ) { - int bits; +void G_AddEvent(gentity_t *ent, int event, int eventParm) { + int bits; - if ( !event ) { - trap->Print( "G_AddEvent: zero event added for entity %i\n", ent->s.number ); + if (!event) { + trap->Print("G_AddEvent: zero event added for entity %i\n", ent->s.number); return; } // clients need to add the event in playerState_t instead of entityState_t - if ( ent->client ) { + if (ent->client) { bits = ent->client->ps.externalEvent & EV_EVENT_BITS; - bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS; + bits = (bits + EV_EVENT_BIT1) & EV_EVENT_BITS; ent->client->ps.externalEvent = event | bits; ent->client->ps.externalEventParm = eventParm; ent->client->ps.externalEventTime = level.time; } else { bits = ent->s.event & EV_EVENT_BITS; - bits = ( bits + EV_EVENT_BIT1 ) & EV_EVENT_BITS; + bits = (bits + EV_EVENT_BIT1) & EV_EVENT_BITS; ent->s.event = event | bits; ent->s.eventParm = eventParm; } @@ -1251,11 +1125,10 @@ void G_AddEvent( gentity_t *ent, int event, int eventParm ) { G_PlayEffect ============= */ -gentity_t *G_PlayEffect(int fxID, vec3_t org, vec3_t ang) -{ - gentity_t *te; +gentity_t *G_PlayEffect(int fxID, vec3_t org, vec3_t ang) { + gentity_t *te; - te = G_TempEntity( org, EV_PLAY_EFFECT ); + te = G_TempEntity(org, EV_PLAY_EFFECT); VectorCopy(ang, te->s.angles); VectorCopy(org, te->s.origin); te->s.eventParm = fxID; @@ -1268,19 +1141,15 @@ gentity_t *G_PlayEffect(int fxID, vec3_t org, vec3_t ang) G_PlayEffectID ============= */ -gentity_t *G_PlayEffectID(const int fxID, vec3_t org, vec3_t ang) -{ //play an effect by the G_EffectIndex'd ID instead of a predefined effect ID - gentity_t *te; +gentity_t *G_PlayEffectID(const int fxID, vec3_t org, vec3_t ang) { // play an effect by the G_EffectIndex'd ID instead of a predefined effect ID + gentity_t *te; - te = G_TempEntity( org, EV_PLAY_EFFECT_ID ); + te = G_TempEntity(org, EV_PLAY_EFFECT_ID); VectorCopy(ang, te->s.angles); VectorCopy(org, te->s.origin); te->s.eventParm = fxID; - if (!te->s.angles[0] && - !te->s.angles[1] && - !te->s.angles[2]) - { //play off this dir by default then. + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { // play off this dir by default then. te->s.angles[1] = 1; } @@ -1292,26 +1161,21 @@ gentity_t *G_PlayEffectID(const int fxID, vec3_t org, vec3_t ang) G_ScreenShake ============= */ -gentity_t *G_ScreenShake(vec3_t org, gentity_t *target, float intensity, int duration, qboolean global) -{ - gentity_t *te; +gentity_t *G_ScreenShake(vec3_t org, gentity_t *target, float intensity, int duration, qboolean global) { + gentity_t *te; - te = G_TempEntity( org, EV_SCREENSHAKE ); + te = G_TempEntity(org, EV_SCREENSHAKE); VectorCopy(org, te->s.origin); te->s.angles[0] = intensity; te->s.time = duration; - if (target) - { - te->s.modelindex = target->s.number+1; - } - else - { + if (target) { + te->s.modelindex = target->s.number + 1; + } else { te->s.modelindex = 0; } - if (global) - { + if (global) { te->r.svFlags |= SVF_BROADCAST; } @@ -1323,19 +1187,17 @@ gentity_t *G_ScreenShake(vec3_t org, gentity_t *target, float intensity, int dur G_MuteSound ============= */ -void G_MuteSound( int entnum, int channel ) -{ - gentity_t *te, *e; +void G_MuteSound(int entnum, int channel) { + gentity_t *te, *e; - te = G_TempEntity( vec3_origin, EV_MUTE_SOUND ); + te = G_TempEntity(vec3_origin, EV_MUTE_SOUND); te->r.svFlags = SVF_BROADCAST; te->s.trickedentindex2 = entnum; te->s.trickedentindex = channel; e = &g_entities[entnum]; - if (e && (e->s.eFlags & EF_SOUNDTRACKER)) - { + if (e && (e->s.eFlags & EF_SOUNDTRACKER)) { G_FreeEntity(e); e->s.eFlags = 0; } @@ -1346,35 +1208,32 @@ void G_MuteSound( int entnum, int channel ) G_Sound ============= */ -void G_Sound( gentity_t *ent, int channel, int soundIndex ) { - gentity_t *te; +void G_Sound(gentity_t *ent, int channel, int soundIndex) { + gentity_t *te; assert(soundIndex); - te = G_SoundTempEntity( ent->r.currentOrigin, EV_GENERAL_SOUND, channel ); + te = G_SoundTempEntity(ent->r.currentOrigin, EV_GENERAL_SOUND, channel); te->s.eventParm = soundIndex; te->s.saberEntityNum = channel; - if (ent && ent->client && channel > TRACK_CHANNEL_NONE) - { //let the client remember the index of the player entity so he can kill the most recent sound on request - if (g_entities[ent->client->ps.fd.killSoundEntIndex[channel-50]].inuse && - ent->client->ps.fd.killSoundEntIndex[channel-50] > MAX_CLIENTS) - { - G_MuteSound(ent->client->ps.fd.killSoundEntIndex[channel-50], CHAN_VOICE); - if (ent->client->ps.fd.killSoundEntIndex[channel-50] > MAX_CLIENTS && g_entities[ent->client->ps.fd.killSoundEntIndex[channel-50]].inuse) - { - G_FreeEntity(&g_entities[ent->client->ps.fd.killSoundEntIndex[channel-50]]); + if (ent && ent->client && + channel > TRACK_CHANNEL_NONE) { // let the client remember the index of the player entity so he can kill the most recent sound on request + if (g_entities[ent->client->ps.fd.killSoundEntIndex[channel - 50]].inuse && ent->client->ps.fd.killSoundEntIndex[channel - 50] > MAX_CLIENTS) { + G_MuteSound(ent->client->ps.fd.killSoundEntIndex[channel - 50], CHAN_VOICE); + if (ent->client->ps.fd.killSoundEntIndex[channel - 50] > MAX_CLIENTS && g_entities[ent->client->ps.fd.killSoundEntIndex[channel - 50]].inuse) { + G_FreeEntity(&g_entities[ent->client->ps.fd.killSoundEntIndex[channel - 50]]); } - ent->client->ps.fd.killSoundEntIndex[channel-50] = 0; + ent->client->ps.fd.killSoundEntIndex[channel - 50] = 0; } - ent->client->ps.fd.killSoundEntIndex[channel-50] = te->s.number; + ent->client->ps.fd.killSoundEntIndex[channel - 50] = te->s.number; te->s.trickedentindex = ent->s.number; te->s.eFlags = EF_SOUNDTRACKER; // fix: let other players know about this // for case that they will meet this one te->r.svFlags |= SVF_BROADCAST; - //te->freeAfterEvent = qfalse; + // te->freeAfterEvent = qfalse; } } @@ -1383,10 +1242,10 @@ void G_Sound( gentity_t *ent, int channel, int soundIndex ) { G_SoundAtLoc ============= */ -void G_SoundAtLoc( vec3_t loc, int channel, int soundIndex ) { - gentity_t *te; +void G_SoundAtLoc(vec3_t loc, int channel, int soundIndex) { + gentity_t *te; - te = G_TempEntity( loc, EV_GENERAL_SOUND ); + te = G_TempEntity(loc, EV_GENERAL_SOUND); te->s.eventParm = soundIndex; te->s.saberEntityNum = channel; } @@ -1396,25 +1255,23 @@ void G_SoundAtLoc( vec3_t loc, int channel, int soundIndex ) { G_EntitySound ============= */ -void G_EntitySound( gentity_t *ent, int channel, int soundIndex ) { - gentity_t *te; +void G_EntitySound(gentity_t *ent, int channel, int soundIndex) { + gentity_t *te; - te = G_TempEntity( ent->r.currentOrigin, EV_ENTITY_SOUND ); + te = G_TempEntity(ent->r.currentOrigin, EV_ENTITY_SOUND); te->s.eventParm = soundIndex; te->s.clientNum = ent->s.number; te->s.trickedentindex = channel; } -//To make porting from SP easier. -void G_SoundOnEnt( gentity_t *ent, int channel, const char *soundPath ) -{ - gentity_t *te; +// To make porting from SP easier. +void G_SoundOnEnt(gentity_t *ent, int channel, const char *soundPath) { + gentity_t *te; - te = G_TempEntity( ent->r.currentOrigin, EV_ENTITY_SOUND ); + te = G_TempEntity(ent->r.currentOrigin, EV_ENTITY_SOUND); te->s.eventParm = G_SoundIndex((char *)soundPath); te->s.clientNum = ent->s.number; te->s.trickedentindex = channel; - } //============================================================================== @@ -1426,148 +1283,114 @@ ValidUseTarget Returns whether or not the targeted entity is useable ============== */ -qboolean ValidUseTarget( gentity_t *ent ) -{ - if ( !ent->use ) - { +qboolean ValidUseTarget(gentity_t *ent) { + if (!ent->use) { return qfalse; } - if ( ent->flags & FL_INACTIVE ) - {//set by target_deactivate + if (ent->flags & FL_INACTIVE) { // set by target_deactivate return qfalse; } - if ( !(ent->r.svFlags & SVF_PLAYER_USABLE) ) - {//Check for flag that denotes BUTTON_USE useability + if (!(ent->r.svFlags & SVF_PLAYER_USABLE)) { // Check for flag that denotes BUTTON_USE useability return qfalse; } return qtrue; } -//use an ammo/health dispenser on another client -void G_UseDispenserOn(gentity_t *ent, int dispType, gentity_t *target) -{ - if (dispType == HI_HEALTHDISP) - { +// use an ammo/health dispenser on another client +void G_UseDispenserOn(gentity_t *ent, int dispType, gentity_t *target) { + if (dispType == HI_HEALTHDISP) { target->client->ps.stats[STAT_HEALTH] += 4; - if (target->client->ps.stats[STAT_HEALTH] > target->client->ps.stats[STAT_MAX_HEALTH]) - { + if (target->client->ps.stats[STAT_HEALTH] > target->client->ps.stats[STAT_MAX_HEALTH]) { target->client->ps.stats[STAT_HEALTH] = target->client->ps.stats[STAT_MAX_HEALTH]; } target->client->isMedHealed = level.time + 500; target->health = target->client->ps.stats[STAT_HEALTH]; - } - else if (dispType == HI_AMMODISP) - { - if (ent->client->medSupplyDebounce < level.time) - { //do the next increment - //increment based on the amount of ammo used per normal shot. + } else if (dispType == HI_AMMODISP) { + if (ent->client->medSupplyDebounce < level.time) { // do the next increment + // increment based on the amount of ammo used per normal shot. target->client->ps.ammo[weaponData[target->client->ps.weapon].ammoIndex] += weaponData[target->client->ps.weapon].energyPerShot; - if (target->client->ps.ammo[weaponData[target->client->ps.weapon].ammoIndex] > ammoData[weaponData[target->client->ps.weapon].ammoIndex].max) - { //cap it off + if (target->client->ps.ammo[weaponData[target->client->ps.weapon].ammoIndex] > + ammoData[weaponData[target->client->ps.weapon].ammoIndex].max) { // cap it off target->client->ps.ammo[weaponData[target->client->ps.weapon].ammoIndex] = ammoData[weaponData[target->client->ps.weapon].ammoIndex].max; } - //base the next supply time on how long the weapon takes to fire. Seems fair enough. + // base the next supply time on how long the weapon takes to fire. Seems fair enough. ent->client->medSupplyDebounce = level.time + weaponData[target->client->ps.weapon].fireTime; } target->client->isMedSupplied = level.time + 500; } } -//see if this guy needs servicing from a specific type of dispenser -int G_CanUseDispOn(gentity_t *ent, int dispType) -{ - if (!ent->client || !ent->inuse || ent->health < 1 || - ent->client->ps.stats[STAT_HEALTH] < 1) - { //dead or invalid +// see if this guy needs servicing from a specific type of dispenser +int G_CanUseDispOn(gentity_t *ent, int dispType) { + if (!ent->client || !ent->inuse || ent->health < 1 || ent->client->ps.stats[STAT_HEALTH] < 1) { // dead or invalid return 0; } - if (dispType == HI_HEALTHDISP) - { - if (ent->client->ps.stats[STAT_HEALTH] < ent->client->ps.stats[STAT_MAX_HEALTH]) - { //he's hurt + if (dispType == HI_HEALTHDISP) { + if (ent->client->ps.stats[STAT_HEALTH] < ent->client->ps.stats[STAT_MAX_HEALTH]) { // he's hurt return 1; } - //otherwise no + // otherwise no return 0; - } - else if (dispType == HI_AMMODISP) - { - if (ent->client->ps.weapon <= WP_NONE || ent->client->ps.weapon > LAST_USEABLE_WEAPON) - { //not a player-useable weapon + } else if (dispType == HI_AMMODISP) { + if (ent->client->ps.weapon <= WP_NONE || ent->client->ps.weapon > LAST_USEABLE_WEAPON) { // not a player-useable weapon return 0; } - if (ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex] < ammoData[weaponData[ent->client->ps.weapon].ammoIndex].max) - { //needs more ammo for current weapon + if (ent->client->ps.ammo[weaponData[ent->client->ps.weapon].ammoIndex] < + ammoData[weaponData[ent->client->ps.weapon].ammoIndex].max) { // needs more ammo for current weapon return 1; } - //needs none + // needs none return 0; } - //invalid type? + // invalid type? return 0; } -qboolean TryHeal(gentity_t *ent, gentity_t *target) -{ - if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && - target && target->inuse && target->maxHealth && target->healingclass && - target->healingclass[0] && target->health > 0 && target->health < target->maxHealth) - { //it's not dead yet... +qboolean TryHeal(gentity_t *ent, gentity_t *target) { + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1 && target && target->inuse && target->maxHealth && target->healingclass && + target->healingclass[0] && target->health > 0 && target->health < target->maxHealth) { // it's not dead yet... siegeClass_t *scl = &bgSiegeClasses[ent->client->siegeClass]; - if (!Q_stricmp(scl->name, target->healingclass)) - { //this thing can be healed by the class this player is using - if (target->healingDebounce < level.time) - { //do the actual heal + if (!Q_stricmp(scl->name, target->healingclass)) { // this thing can be healed by the class this player is using + if (target->healingDebounce < level.time) { // do the actual heal target->health += 10; - if (target->health > target->maxHealth) - { //don't go too high + if (target->health > target->maxHealth) { // don't go too high target->health = target->maxHealth; } target->healingDebounce = level.time + target->healingrate; - if (target->healingsound && target->healingsound[0]) - { //play it - if (target->s.solid == SOLID_BMODEL) - { //ok, well, just play it on the client then. + if (target->healingsound && target->healingsound[0]) { // play it + if (target->s.solid == SOLID_BMODEL) { // ok, well, just play it on the client then. G_Sound(ent, CHAN_AUTO, G_SoundIndex(target->healingsound)); - } - else - { + } else { G_Sound(target, CHAN_AUTO, G_SoundIndex(target->healingsound)); } } - //update net health for bar + // update net health for bar G_ScaleNetHealth(target); - if (target->target_ent && - target->target_ent->maxHealth) - { + if (target->target_ent && target->target_ent->maxHealth) { target->target_ent->health = target->health; G_ScaleNetHealth(target->target_ent); } } - //keep them in the healing anim even when the healing debounce is not yet expired - if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD || - ent->client->ps.torsoAnim == BOTH_CONSOLE1) - { //extend the time + // keep them in the healing anim even when the healing debounce is not yet expired + if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD || ent->client->ps.torsoAnim == BOTH_CONSOLE1) { // extend the time ent->client->ps.torsoTimer = 500; - } - else - { - G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + } else { + G_SetAnim(ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } return qtrue; @@ -1585,70 +1408,56 @@ Try and use an entity in the world, directly ahead of us ============== */ -#define USE_DISTANCE 64.0f +#define USE_DISTANCE 64.0f -extern void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ); +extern void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace); extern qboolean gSiegeRoundBegun; -static vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; -static vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; -void TryUse( gentity_t *ent ) -{ - gentity_t *target; - trace_t trace; - vec3_t src, dest, vf; - vec3_t viewspot; - - if (level.gametype == GT_SIEGE && - !gSiegeRoundBegun) - { //nothing can be used til the round starts. +static vec3_t playerMins = {-15, -15, DEFAULT_MINS_2}; +static vec3_t playerMaxs = {15, 15, DEFAULT_MAXS_2}; +void TryUse(gentity_t *ent) { + gentity_t *target; + trace_t trace; + vec3_t src, dest, vf; + vec3_t viewspot; + + if (level.gametype == GT_SIEGE && !gSiegeRoundBegun) { // nothing can be used til the round starts. return; } - if (!ent || !ent->client || (ent->client->ps.weaponTime > 0 && ent->client->ps.torsoAnim != BOTH_BUTTON_HOLD && ent->client->ps.torsoAnim != BOTH_CONSOLE1) || ent->health < 1 || + if (!ent || !ent->client || + (ent->client->ps.weaponTime > 0 && ent->client->ps.torsoAnim != BOTH_BUTTON_HOLD && ent->client->ps.torsoAnim != BOTH_CONSOLE1) || ent->health < 1 || (ent->client->ps.pm_flags & PMF_FOLLOW) || ent->client->sess.sessionTeam == TEAM_SPECTATOR || ent->client->tempSpectate >= level.time || - (ent->client->ps.forceHandExtend != HANDEXTEND_NONE && ent->client->ps.forceHandExtend != HANDEXTEND_DRAGGING)) - { + (ent->client->ps.forceHandExtend != HANDEXTEND_NONE && ent->client->ps.forceHandExtend != HANDEXTEND_DRAGGING)) { return; } - if (ent->client->ps.emplacedIndex) - { //on an emplaced gun or using a vehicle, don't do anything when hitting use key + if (ent->client->ps.emplacedIndex) { // on an emplaced gun or using a vehicle, don't do anything when hitting use key return; } - if (ent->s.number < MAX_CLIENTS && ent->client && ent->client->ps.m_iVehicleNum) - { + if (ent->s.number < MAX_CLIENTS && ent->client && ent->client->ps.m_iVehicleNum) { gentity_t *currentVeh = &g_entities[ent->client->ps.m_iVehicleNum]; - if (currentVeh->inuse && currentVeh->m_pVehicle) - { + if (currentVeh->inuse && currentVeh->m_pVehicle) { Vehicle_t *pVeh = currentVeh->m_pVehicle; - if (!pVeh->m_iBoarding) - { - pVeh->m_pVehicleInfo->Eject( pVeh, (bgEntity_t *)ent, qfalse ); + if (!pVeh->m_iBoarding) { + pVeh->m_pVehicleInfo->Eject(pVeh, (bgEntity_t *)ent, qfalse); } return; } } - if (ent->client->jetPackOn) - { //can't use anything else to jp is off + if (ent->client->jetPackOn) { // can't use anything else to jp is off goto tryJetPack; } - if (ent->client->bodyGrabIndex != ENTITYNUM_NONE) - { //then hitting the use key just means let go - if (ent->client->bodyGrabTime < level.time) - { + if (ent->client->bodyGrabIndex != ENTITYNUM_NONE) { // then hitting the use key just means let go + if (ent->client->bodyGrabTime < level.time) { gentity_t *grabbed = &g_entities[ent->client->bodyGrabIndex]; - if (grabbed->inuse) - { - if (grabbed->client) - { + if (grabbed->inuse) { + if (grabbed->client) { grabbed->client->ps.ragAttach = 0; - } - else - { + } else { grabbed->s.ragAttach = 0; } } @@ -1661,22 +1470,22 @@ void TryUse( gentity_t *ent ) VectorCopy(ent->client->ps.origin, viewspot); viewspot[2] += ent->client->ps.viewheight; - VectorCopy( viewspot, src ); - AngleVectors( ent->client->ps.viewangles, vf, NULL, NULL ); + VectorCopy(viewspot, src); + AngleVectors(ent->client->ps.viewangles, vf, NULL, NULL); - VectorMA( src, USE_DISTANCE, vf, dest ); + VectorMA(src, USE_DISTANCE, vf, dest); - //Trace ahead to find a valid target - trap->Trace( &trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE|CONTENTS_SOLID|CONTENTS_BODY|CONTENTS_ITEM|CONTENTS_CORPSE, qfalse, 0, 0 ); + // Trace ahead to find a valid target + trap->Trace(&trace, src, vec3_origin, vec3_origin, dest, ent->s.number, MASK_OPAQUE | CONTENTS_SOLID | CONTENTS_BODY | CONTENTS_ITEM | CONTENTS_CORPSE, + qfalse, 0, 0); - if ( trace.fraction == 1.0f || trace.entityNum == ENTITYNUM_NONE ) - { + if (trace.fraction == 1.0f || trace.entityNum == ENTITYNUM_NONE) { goto tryJetPack; } target = &g_entities[trace.entityNum]; -//Enable for corpse dragging +// Enable for corpse dragging #if 0 if (target->inuse && target->s.eType == ET_BODY && ent->client->bodyGrabTime < level.time) @@ -1696,34 +1505,26 @@ void TryUse( gentity_t *ent ) } #endif - if (target && target->m_pVehicle && target->client && - target->s.NPC_class == CLASS_VEHICLE && - !ent->client->ps.zoomMode) - { //if target is a vehicle then perform appropriate checks + if (target && target->m_pVehicle && target->client && target->s.NPC_class == CLASS_VEHICLE && + !ent->client->ps.zoomMode) { // if target is a vehicle then perform appropriate checks Vehicle_t *pVeh = target->m_pVehicle; - if (pVeh->m_pVehicleInfo) - { - if ( ent->r.ownerNum == target->s.number ) - { //user is already on this vehicle so eject him - pVeh->m_pVehicleInfo->Eject( pVeh, (bgEntity_t *)ent, qfalse ); - } - else - { // Otherwise board this vehicle. - if (level.gametype < GT_TEAM || - !target->alliedTeam || - (target->alliedTeam == ent->client->sess.sessionTeam)) - { //not belonging to a team, or client is on same team - pVeh->m_pVehicleInfo->Board( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pVehicleInfo) { + if (ent->r.ownerNum == target->s.number) { // user is already on this vehicle so eject him + pVeh->m_pVehicleInfo->Eject(pVeh, (bgEntity_t *)ent, qfalse); + } else { // Otherwise board this vehicle. + if (level.gametype < GT_TEAM || !target->alliedTeam || + (target->alliedTeam == ent->client->sess.sessionTeam)) { // not belonging to a team, or client is on same team + pVeh->m_pVehicleInfo->Board(pVeh, (bgEntity_t *)ent); } } - //clear the damn button! + // clear the damn button! ent->client->pers.cmd.buttons &= ~BUTTON_USE; return; } } -#if 0 //ye olde method +#if 0 // ye olde method if (ent->client->ps.stats[STAT_HOLDABLE_ITEM] > 0 && bg_itemlist[ent->client->ps.stats[STAT_HOLDABLE_ITEM]].giType == IT_HOLDABLE) { @@ -1750,27 +1551,21 @@ void TryUse( gentity_t *ent ) } } #else - if ( ((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) || (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP))) && - target && target->inuse && target->client && target->health > 0 && OnSameTeam(ent, target) && - (G_CanUseDispOn(target, HI_HEALTHDISP) || G_CanUseDispOn(target, HI_AMMODISP)) ) - { //a live target that's on my team, we can use him - if (G_CanUseDispOn(target, HI_HEALTHDISP)) - { + if (((ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_HEALTHDISP)) || (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_AMMODISP))) && target && + target->inuse && target->client && target->health > 0 && OnSameTeam(ent, target) && + (G_CanUseDispOn(target, HI_HEALTHDISP) || G_CanUseDispOn(target, HI_AMMODISP))) { // a live target that's on my team, we can use him + if (G_CanUseDispOn(target, HI_HEALTHDISP)) { G_UseDispenserOn(ent, HI_HEALTHDISP, target); } - if (G_CanUseDispOn(target, HI_AMMODISP)) - { + if (G_CanUseDispOn(target, HI_AMMODISP)) { G_UseDispenserOn(ent, HI_AMMODISP, target); } - //for now, we will use the standard use anim - if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD) - { //extend the time + // for now, we will use the standard use anim + if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD) { // extend the time ent->client->ps.torsoTimer = 500; - } - else - { - G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + } else { + G_SetAnim(ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } ent->client->ps.weaponTime = ent->client->ps.torsoTimer; return; @@ -1778,21 +1573,13 @@ void TryUse( gentity_t *ent ) #endif - //Check for a use command - if ( ValidUseTarget( target ) - && (level.gametype != GT_SIEGE - || !target->alliedTeam - || target->alliedTeam != ent->client->sess.sessionTeam - || g_ff_objectives.integer) ) - { - if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD || - ent->client->ps.torsoAnim == BOTH_CONSOLE1) - { //extend the time + // Check for a use command + if (ValidUseTarget(target) && + (level.gametype != GT_SIEGE || !target->alliedTeam || target->alliedTeam != ent->client->sess.sessionTeam || g_ff_objectives.integer)) { + if (ent->client->ps.torsoAnim == BOTH_BUTTON_HOLD || ent->client->ps.torsoAnim == BOTH_CONSOLE1) { // extend the time ent->client->ps.torsoTimer = 500; - } - else - { - G_SetAnim( ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0 ); + } else { + G_SetAnim(ent, NULL, SETANIM_TORSO, BOTH_BUTTON_HOLD, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } ent->client->ps.weaponTime = ent->client->ps.torsoTimer; /* @@ -1802,28 +1589,22 @@ void TryUse( gentity_t *ent ) NPC_SetAnim( ent, SETANIM_LEGS, BOTH_FORCEPUSH, SETANIM_FLAG_NORMAL|SETANIM_FLAG_HOLD ); } */ - if ( target->touch == Touch_Button ) - {//pretend we touched it + if (target->touch == Touch_Button) { // pretend we touched it target->touch(target, ent, NULL); - } - else - { + } else { GlobalUse(target, ent, ent); } return; } - if (TryHeal(ent, target)) - { + if (TryHeal(ent, target)) { return; } tryJetPack: - //if we got here, we didn't actually use anything else, so try to toggle jetpack if we are in the air, or if it is already on - if (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) - { - if (ent->client->jetPackOn || ent->client->ps.groundEntityNum == ENTITYNUM_NONE) - { + // if we got here, we didn't actually use anything else, so try to toggle jetpack if we are in the air, or if it is already on + if (ent->client->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << HI_JETPACK)) { + if (ent->client->jetPackOn || ent->client->ps.groundEntityNum == ENTITYNUM_NONE) { ItemUse_Jetpack(ent); return; } @@ -1839,29 +1620,24 @@ void TryUse( gentity_t *ent ) VectorSet(fAng, 0.0f, ent->client->ps.viewangles[YAW], 0.0f); AngleVectors(fAng, fwd, 0, 0); - VectorMA(ent->client->ps.origin, 64.0f, fwd, fwd); + VectorMA(ent->client->ps.origin, 64.0f, fwd, fwd); trap->Trace(&trToss, ent->client->ps.origin, playerMins, playerMaxs, fwd, ent->s.number, ent->clipmask, qfalse, 0, 0); - if (trToss.fraction == 1.0f && !trToss.allsolid && !trToss.startsolid) - { + if (trToss.fraction == 1.0f && !trToss.allsolid && !trToss.startsolid) { ItemUse_UseDisp(ent, HI_AMMODISP); - G_AddEvent(ent, EV_USE_ITEM0+HI_AMMODISP, 0); + G_AddEvent(ent, EV_USE_ITEM0 + HI_AMMODISP, 0); return; } } } -qboolean G_PointInBounds( vec3_t point, vec3_t mins, vec3_t maxs ) -{ +qboolean G_PointInBounds(vec3_t point, vec3_t mins, vec3_t maxs) { int i; - for(i = 0; i < 3; i++ ) - { - if ( point[i] < mins[i] ) - { + for (i = 0; i < 3; i++) { + if (point[i] < mins[i]) { return qfalse; } - if ( point[i] > maxs[i] ) - { + if (point[i] > maxs[i]) { return qfalse; } } @@ -1869,52 +1645,47 @@ qboolean G_PointInBounds( vec3_t point, vec3_t mins, vec3_t maxs ) return qtrue; } -qboolean G_BoxInBounds( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t boundsMins, vec3_t boundsMaxs ) -{ +qboolean G_BoxInBounds(vec3_t point, vec3_t mins, vec3_t maxs, vec3_t boundsMins, vec3_t boundsMaxs) { vec3_t boxMins; vec3_t boxMaxs; - VectorAdd( point, mins, boxMins ); - VectorAdd( point, maxs, boxMaxs ); + VectorAdd(point, mins, boxMins); + VectorAdd(point, maxs, boxMaxs); - if(boxMaxs[0]>boundsMaxs[0]) + if (boxMaxs[0] > boundsMaxs[0]) return qfalse; - if(boxMaxs[1]>boundsMaxs[1]) + if (boxMaxs[1] > boundsMaxs[1]) return qfalse; - if(boxMaxs[2]>boundsMaxs[2]) + if (boxMaxs[2] > boundsMaxs[2]) return qfalse; - if(boxMins[0]r.currentAngles ); - VectorCopy( angles, ent->s.angles ); - VectorCopy( angles, ent->s.apos.trBase ); +void G_SetAngles(gentity_t *ent, vec3_t angles) { + VectorCopy(angles, ent->r.currentAngles); + VectorCopy(angles, ent->s.angles); + VectorCopy(angles, ent->s.apos.trBase); } -qboolean G_ClearTrace( vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int ignore, int clipmask ) -{ - static trace_t tr; +qboolean G_ClearTrace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int ignore, int clipmask) { + static trace_t tr; - trap->Trace( &tr, start, mins, maxs, end, ignore, clipmask, qfalse, 0, 0 ); + trap->Trace(&tr, start, mins, maxs, end, ignore, clipmask, qfalse, 0, 0); - if ( tr.allsolid || tr.startsolid || tr.fraction < 1.0 ) - { + if (tr.allsolid || tr.startsolid || tr.fraction < 1.0) { return qfalse; } @@ -1928,20 +1699,19 @@ G_SetOrigin Sets the pos trajectory for a fixed position ================ */ -void G_SetOrigin( gentity_t *ent, vec3_t origin ) { - VectorCopy( origin, ent->s.pos.trBase ); +void G_SetOrigin(gentity_t *ent, vec3_t origin) { + VectorCopy(origin, ent->s.pos.trBase); ent->s.pos.trType = TR_STATIONARY; ent->s.pos.trTime = 0; ent->s.pos.trDuration = 0; - VectorClear( ent->s.pos.trDelta ); + VectorClear(ent->s.pos.trDelta); - VectorCopy( origin, ent->r.currentOrigin ); + VectorCopy(origin, ent->r.currentOrigin); } -qboolean G_CheckInSolid (gentity_t *self, qboolean fix) -{ - trace_t trace; - vec3_t end, mins; +qboolean G_CheckInSolid(gentity_t *self, qboolean fix) { + trace_t trace; + vec3_t end, mins; VectorCopy(self->r.currentOrigin, end); end[2] += self->r.mins[2]; @@ -1949,16 +1719,13 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) mins[2] = 0; trap->Trace(&trace, self->r.currentOrigin, mins, self->r.maxs, end, self->s.number, self->clipmask, qfalse, 0, 0); - if(trace.allsolid || trace.startsolid) - { + if (trace.allsolid || trace.startsolid) { return qtrue; } - if(trace.fraction < 1.0) - { - if(fix) - {//Put them at end of trace and check again - vec3_t neworg; + if (trace.fraction < 1.0) { + if (fix) { // Put them at end of trace and check again + vec3_t neworg; VectorCopy(trace.endpos, neworg); neworg[2] -= self->r.mins[2]; @@ -1966,9 +1733,7 @@ qboolean G_CheckInSolid (gentity_t *self, qboolean fix) trap->LinkEntity((sharedEntity_t *)self); return G_CheckInSolid(self, qfalse); - } - else - { + } else { return qtrue; } } @@ -1990,17 +1755,18 @@ int DebugLine(vec3_t start, vec3_t end, int color) { VectorCopy(start, points[0]); VectorCopy(start, points[1]); - //points[1][2] -= 2; + // points[1][2] -= 2; VectorCopy(end, points[2]); - //points[2][2] -= 2; + // points[2][2] -= 2; VectorCopy(end, points[3]); - VectorSubtract(end, start, dir); VectorNormalize(dir); dot = DotProduct(dir, up); - if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0); - else CrossProduct(dir, up, cross); + if (dot > 0.99 || dot < -0.99) + VectorSet(cross, 1, 0, 0); + else + CrossProduct(dir, up, cross); VectorNormalize(cross); @@ -2012,38 +1778,32 @@ int DebugLine(vec3_t start, vec3_t end, int color) { return trap->DebugPolygonCreate(color, 4, points); } -void G_ROFF_NotetrackCallback( gentity_t *cent, const char *notetrack) -{ +void G_ROFF_NotetrackCallback(gentity_t *cent, const char *notetrack) { char type[256]; int i = 0; int addlArg = 0; - if (!cent || !notetrack) - { + if (!cent || !notetrack) { return; } - while (notetrack[i] && notetrack[i] != ' ') - { + while (notetrack[i] && notetrack[i] != ' ') { type[i] = notetrack[i]; i++; } type[i] = '\0'; - if (!i || !type[0]) - { + if (!i || !type[0]) { return; } - if (notetrack[i] == ' ') - { + if (notetrack[i] == ' ') { addlArg = 1; } - if (strcmp(type, "loop") == 0) - { - if (addlArg) //including an additional argument means reset to original position before loop + if (strcmp(type, "loop") == 0) { + if (addlArg) // including an additional argument means reset to original position before loop { VectorCopy(cent->s.origin2, cent->s.pos.trBase); VectorCopy(cent->s.origin2, cent->r.currentOrigin); @@ -2055,140 +1815,121 @@ void G_ROFF_NotetrackCallback( gentity_t *cent, const char *notetrack) } } -void G_SpeechEvent( gentity_t *self, int event ) -{ - G_AddEvent(self, event, 0); -} +void G_SpeechEvent(gentity_t *self, int event) { G_AddEvent(self, event, 0); } -qboolean G_ExpandPointToBBox( vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask ) -{ - trace_t tr; - vec3_t start, end; +qboolean G_ExpandPointToBBox(vec3_t point, const vec3_t mins, const vec3_t maxs, int ignore, int clipmask) { + trace_t tr; + vec3_t start, end; int i; - VectorCopy( point, start ); + VectorCopy(point, start); - for ( i = 0; i < 3; i++ ) - { - VectorCopy( start, end ); + for (i = 0; i < 3; i++) { + VectorCopy(start, end); end[i] += mins[i]; - trap->Trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, qfalse, 0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + trap->Trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, qfalse, 0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { - VectorCopy( start, end ); - end[i] += maxs[i]-(mins[i]*tr.fraction); - trap->Trace( &tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, qfalse, 0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + if (tr.fraction < 1.0) { + VectorCopy(start, end); + end[i] += maxs[i] - (mins[i] * tr.fraction); + trap->Trace(&tr, start, vec3_origin, vec3_origin, end, ignore, clipmask, qfalse, 0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - if ( tr.fraction < 1.0 ) - { + if (tr.fraction < 1.0) { return qfalse; } - VectorCopy( end, start ); + VectorCopy(end, start); } } - //expanded it, now see if it's all clear - trap->Trace( &tr, start, mins, maxs, start, ignore, clipmask, qfalse, 0, 0 ); - if ( tr.allsolid || tr.startsolid ) - { + // expanded it, now see if it's all clear + trap->Trace(&tr, start, mins, maxs, start, ignore, clipmask, qfalse, 0, 0); + if (tr.allsolid || tr.startsolid) { return qfalse; } - VectorCopy( start, point ); + VectorCopy(start, point); return qtrue; } -extern qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); -float ShortestLineSegBewteen2LineSegs( vec3_t start1, vec3_t end1, vec3_t start2, vec3_t end2, vec3_t close_pnt1, vec3_t close_pnt2 ) -{ - float current_dist, new_dist; - vec3_t new_pnt; - //start1, end1 : the first segment - //start2, end2 : the second segment - - //output, one point on each segment, the closest two points on the segments. - - //compute some temporaries: - //vec start_dif = start2 - start1 - vec3_t start_dif; - vec3_t v1; - vec3_t v2; +extern qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result); +float ShortestLineSegBewteen2LineSegs(vec3_t start1, vec3_t end1, vec3_t start2, vec3_t end2, vec3_t close_pnt1, vec3_t close_pnt2) { + float current_dist, new_dist; + vec3_t new_pnt; + // start1, end1 : the first segment + // start2, end2 : the second segment + + // output, one point on each segment, the closest two points on the segments. + + // compute some temporaries: + // vec start_dif = start2 - start1 + vec3_t start_dif; + vec3_t v1; + vec3_t v2; float v1v1, v2v2, v1v2; float denom; - VectorSubtract( start2, start1, start_dif ); - //vec v1 = end1 - start1 - VectorSubtract( end1, start1, v1 ); - //vec v2 = end2 - start2 - VectorSubtract( end2, start2, v2 ); + VectorSubtract(start2, start1, start_dif); + // vec v1 = end1 - start1 + VectorSubtract(end1, start1, v1); + // vec v2 = end2 - start2 + VectorSubtract(end2, start2, v2); // - v1v1 = DotProduct( v1, v1 ); - v2v2 = DotProduct( v2, v2 ); - v1v2 = DotProduct( v1, v2 ); + v1v1 = DotProduct(v1, v1); + v2v2 = DotProduct(v2, v2); + v1v2 = DotProduct(v1, v2); - //the main computation + // the main computation denom = (v1v2 * v1v2) - (v1v1 * v2v2); - //if denom is small, then skip all this and jump to the section marked below - if ( fabs(denom) > 0.001f ) - { - float s = -( (v2v2*DotProduct( v1, start_dif )) - (v1v2*DotProduct( v2, start_dif )) ) / denom; - float t = ( (v1v1*DotProduct( v2, start_dif )) - (v1v2*DotProduct( v1, start_dif )) ) / denom; + // if denom is small, then skip all this and jump to the section marked below + if (fabs(denom) > 0.001f) { + float s = -((v2v2 * DotProduct(v1, start_dif)) - (v1v2 * DotProduct(v2, start_dif))) / denom; + float t = ((v1v1 * DotProduct(v2, start_dif)) - (v1v2 * DotProduct(v1, start_dif))) / denom; qboolean done = qtrue; - if ( s < 0 ) - { + if (s < 0) { done = qfalse; - s = 0;// and see note below + s = 0; // and see note below } - if ( s > 1 ) - { + if (s > 1) { done = qfalse; - s = 1;// and see note below + s = 1; // and see note below } - if ( t < 0 ) - { + if (t < 0) { done = qfalse; - t = 0;// and see note below + t = 0; // and see note below } - if ( t > 1 ) - { + if (t > 1) { done = qfalse; - t = 1;// and see note below + t = 1; // and see note below } - //vec close_pnt1 = start1 + s * v1 - VectorMA( start1, s, v1, close_pnt1 ); - //vec close_pnt2 = start2 + t * v2 - VectorMA( start2, t, v2, close_pnt2 ); + // vec close_pnt1 = start1 + s * v1 + VectorMA(start1, s, v1, close_pnt1); + // vec close_pnt2 = start2 + t * v2 + VectorMA(start2, t, v2, close_pnt2); - current_dist = Distance( close_pnt1, close_pnt2 ); - //now, if none of those if's fired, you are done. - if ( done ) - { + current_dist = Distance(close_pnt1, close_pnt2); + // now, if none of those if's fired, you are done. + if (done) { return current_dist; } - //If they did fire, then we need to do some additional tests. + // If they did fire, then we need to do some additional tests. - //What we are gonna do is see if we can find a shorter distance than the above - //involving the endpoints. - } - else - { + // What we are gonna do is see if we can find a shorter distance than the above + // involving the endpoints. + } else { //******start here for paralell lines with current_dist = infinity**** current_dist = Q3_INFINITE; } - //test 2 close_pnts first + // test 2 close_pnts first /* G_FindClosestPointOnLineSegment( start1, end1, close_pnt2, new_pnt ); new_dist = Distance( close_pnt2, new_pnt ); @@ -2208,74 +1949,66 @@ float ShortestLineSegBewteen2LineSegs( vec3_t start1, vec3_t end1, vec3_t start2 current_dist = new_dist; } */ - //test all the endpoints - new_dist = Distance( start1, start2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + // test all the endpoints + new_dist = Distance(start1, start2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( start1, end2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + new_dist = Distance(start1, end2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( end1, start2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + new_dist = Distance(end1, start2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - new_dist = Distance( end1, end2 ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + new_dist = Distance(end1, end2); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } - //Then we have 4 more point / segment tests + // Then we have 4 more point / segment tests - G_FindClosestPointOnLineSegment( start2, end2, start1, new_pnt ); - new_dist = Distance( start1, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( start1, close_pnt1 ); - VectorCopy( new_pnt, close_pnt2 ); + G_FindClosestPointOnLineSegment(start2, end2, start1, new_pnt); + new_dist = Distance(start1, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(start1, close_pnt1); + VectorCopy(new_pnt, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start2, end2, end1, new_pnt ); - new_dist = Distance( end1, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( end1, close_pnt1 ); - VectorCopy( new_pnt, close_pnt2 ); + G_FindClosestPointOnLineSegment(start2, end2, end1, new_pnt); + new_dist = Distance(end1, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(end1, close_pnt1); + VectorCopy(new_pnt, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start1, end1, start2, new_pnt ); - new_dist = Distance( start2, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( new_pnt, close_pnt1 ); - VectorCopy( start2, close_pnt2 ); + G_FindClosestPointOnLineSegment(start1, end1, start2, new_pnt); + new_dist = Distance(start2, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(new_pnt, close_pnt1); + VectorCopy(start2, close_pnt2); current_dist = new_dist; } - G_FindClosestPointOnLineSegment( start1, end1, end2, new_pnt ); - new_dist = Distance( end2, new_pnt ); - if ( new_dist < current_dist ) - {//then update close_pnt1 close_pnt2 and current_dist - VectorCopy( new_pnt, close_pnt1 ); - VectorCopy( end2, close_pnt2 ); + G_FindClosestPointOnLineSegment(start1, end1, end2, new_pnt); + new_dist = Distance(end2, new_pnt); + if (new_dist < current_dist) { // then update close_pnt1 close_pnt2 and current_dist + VectorCopy(new_pnt, close_pnt1); + VectorCopy(end2, close_pnt2); current_dist = new_dist; } diff --git a/codemp/game/g_vehicleTurret.c b/codemp/game/g_vehicleTurret.c index e2477376c7..83bdd12704 100644 --- a/codemp/game/g_vehicleTurret.c +++ b/codemp/game/g_vehicleTurret.c @@ -24,438 +24,347 @@ along with this program; if not, see . #include "b_local.h" #include "ghoul2/G2.h" -extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); +extern void G_SetEnemy(gentity_t *self, gentity_t *enemy); extern void WP_CalcVehMuzzle(gentity_t *ent, int muzzleNum); -extern gentity_t *WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon, qboolean alt_fire, qboolean isTurretWeap ); +extern gentity_t *WP_FireVehicleWeapon(gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon, qboolean alt_fire, qboolean isTurretWeap); -extern void G_VehMuzzleFireFX( gentity_t *ent, gentity_t *broadcaster, int muzzlesFired ); +extern void G_VehMuzzleFireFX(gentity_t *ent, gentity_t *broadcaster, int muzzlesFired); //----------------------------------------------------- -void VEH_TurretCheckFire( Vehicle_t *pVeh, - gentity_t *parent, - //gentity_t *turretEnemy, - turretStats_t *turretStats, - vehWeaponInfo_t *vehWeapon, - int turretNum, int curMuzzle ) -{ +void VEH_TurretCheckFire(Vehicle_t *pVeh, gentity_t *parent, + // gentity_t *turretEnemy, + turretStats_t *turretStats, vehWeaponInfo_t *vehWeapon, int turretNum, int curMuzzle) { // if it's time to fire and we have an enemy, then gun 'em down! pushDebounce time controls next fire time - if ( pVeh->m_iMuzzleTag[curMuzzle] == -1 ) - {//invalid muzzle? + if (pVeh->m_iMuzzleTag[curMuzzle] == -1) { // invalid muzzle? return; } - if ( pVeh->m_iMuzzleWait[curMuzzle] >= level.time ) - {//can't fire yet + if (pVeh->m_iMuzzleWait[curMuzzle] >= level.time) { // can't fire yet return; } - if ( pVeh->turretStatus[turretNum].ammo < vehWeapon->iAmmoPerShot ) - {//no ammo, can't fire + if (pVeh->turretStatus[turretNum].ammo < vehWeapon->iAmmoPerShot) { // no ammo, can't fire return; } - //if ( turretEnemy ) + // if ( turretEnemy ) { - //FIXME: check to see if I'm aiming generally where I want to - int nextMuzzle = 0, muzzlesFired = (1<m_vMuzzlePos[curMuzzle], pVeh->m_vMuzzleDir[curMuzzle], vehWeapon, (turretNum!=0), qtrue ); + // FIXME: some variation in fire dir + missile = WP_FireVehicleWeapon(parent, pVeh->m_vMuzzlePos[curMuzzle], pVeh->m_vMuzzleDir[curMuzzle], vehWeapon, (turretNum != 0), qtrue); - //play the weapon's muzzle effect if we have one - G_VehMuzzleFireFX(parent, missile, muzzlesFired ); + // play the weapon's muzzle effect if we have one + G_VehMuzzleFireFX(parent, missile, muzzlesFired); - //take the ammo away + // take the ammo away pVeh->turretStatus[turretNum].ammo -= vehWeapon->iAmmoPerShot; - //toggle to the next muzzle on this turret, if there is one - nextMuzzle = ((curMuzzle+1)==pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[0])?pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[1]:pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[0]; - if ( nextMuzzle ) - {//a valid muzzle to toggle to - pVeh->turretStatus[turretNum].nextMuzzle = nextMuzzle-1;//-1 because you type muzzles 1-10 in the .veh file + // toggle to the next muzzle on this turret, if there is one + nextMuzzle = ((curMuzzle + 1) == pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[0]) ? pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[1] + : pVeh->m_pVehicleInfo->turret[turretNum].iMuzzle[0]; + if (nextMuzzle) { // a valid muzzle to toggle to + pVeh->turretStatus[turretNum].nextMuzzle = nextMuzzle - 1; //-1 because you type muzzles 1-10 in the .veh file } - //add delay to the next muzzle so it doesn't fire right away on the next frame + // add delay to the next muzzle so it doesn't fire right away on the next frame pVeh->m_iMuzzleWait[pVeh->turretStatus[turretNum].nextMuzzle] = level.time + turretStats->iDelay; } } -void VEH_TurretAnglesToEnemy( Vehicle_t *pVeh, int curMuzzle, float fSpeed, gentity_t *turretEnemy, qboolean bAILead, vec3_t desiredAngles ) -{ - vec3_t enemyDir, org; - VectorCopy( turretEnemy->r.currentOrigin, org ); - if ( bAILead ) - {//we want to lead them a bit +void VEH_TurretAnglesToEnemy(Vehicle_t *pVeh, int curMuzzle, float fSpeed, gentity_t *turretEnemy, qboolean bAILead, vec3_t desiredAngles) { + vec3_t enemyDir, org; + VectorCopy(turretEnemy->r.currentOrigin, org); + if (bAILead) { // we want to lead them a bit vec3_t diff, velocity; float dist; - VectorSubtract( org, pVeh->m_vMuzzlePos[curMuzzle], diff ); - dist = VectorNormalize( diff ); - if ( turretEnemy->client ) - { - VectorCopy( turretEnemy->client->ps.velocity, velocity ); - } - else - { - VectorCopy( turretEnemy->s.pos.trDelta, velocity ); + VectorSubtract(org, pVeh->m_vMuzzlePos[curMuzzle], diff); + dist = VectorNormalize(diff); + if (turretEnemy->client) { + VectorCopy(turretEnemy->client->ps.velocity, velocity); + } else { + VectorCopy(turretEnemy->s.pos.trDelta, velocity); } - VectorMA( org, (dist/fSpeed), velocity, org ); + VectorMA(org, (dist / fSpeed), velocity, org); } - //FIXME: this isn't quite right, it's aiming from the muzzle, not the center of the turret... - VectorSubtract( org, pVeh->m_vMuzzlePos[curMuzzle], enemyDir ); - //Get the desired absolute, world angles to our target - vectoangles( enemyDir, desiredAngles ); + // FIXME: this isn't quite right, it's aiming from the muzzle, not the center of the turret... + VectorSubtract(org, pVeh->m_vMuzzlePos[curMuzzle], enemyDir); + // Get the desired absolute, world angles to our target + vectoangles(enemyDir, desiredAngles); } //----------------------------------------------------- -qboolean VEH_TurretAim( Vehicle_t *pVeh, - gentity_t *parent, - gentity_t *turretEnemy, - turretStats_t *turretStats, - vehWeaponInfo_t *vehWeapon, - int turretNum, int curMuzzle, vec3_t desiredAngles ) +qboolean VEH_TurretAim(Vehicle_t *pVeh, gentity_t *parent, gentity_t *turretEnemy, turretStats_t *turretStats, vehWeaponInfo_t *vehWeapon, int turretNum, + int curMuzzle, vec3_t desiredAngles) //----------------------------------------------------- { - vec3_t curAngles, addAngles, newAngles, yawAngles, pitchAngles; - float aimCorrect = qfalse; + vec3_t curAngles, addAngles, newAngles, yawAngles, pitchAngles; + float aimCorrect = qfalse; - WP_CalcVehMuzzle( parent, curMuzzle ); - //get the current absolute angles of the turret right now - vectoangles( pVeh->m_vMuzzleDir[curMuzzle], curAngles ); - //subtract out the vehicle's angles to get the relative alignment - AnglesSubtract( curAngles, pVeh->m_vOrientation, curAngles ); + WP_CalcVehMuzzle(parent, curMuzzle); + // get the current absolute angles of the turret right now + vectoangles(pVeh->m_vMuzzleDir[curMuzzle], curAngles); + // subtract out the vehicle's angles to get the relative alignment + AnglesSubtract(curAngles, pVeh->m_vOrientation, curAngles); - if ( turretEnemy ) - { + if (turretEnemy) { aimCorrect = qtrue; // ...then we'll calculate what new aim adjustments we should attempt to make this frame // Aim at enemy - VEH_TurretAnglesToEnemy( pVeh, curMuzzle, vehWeapon->fSpeed, turretEnemy, turretStats->bAILead, desiredAngles ); + VEH_TurretAnglesToEnemy(pVeh, curMuzzle, vehWeapon->fSpeed, turretEnemy, turretStats->bAILead, desiredAngles); } - //subtract out the vehicle's angles to get the relative desired alignment - AnglesSubtract( desiredAngles, pVeh->m_vOrientation, desiredAngles ); - //Now clamp the desired relative angles - //clamp yaw - desiredAngles[YAW] = AngleNormalize180( desiredAngles[YAW] ); - if ( pVeh->m_pVehicleInfo->turret[turretNum].yawClampLeft - && desiredAngles[YAW] > pVeh->m_pVehicleInfo->turret[turretNum].yawClampLeft ) - { + // subtract out the vehicle's angles to get the relative desired alignment + AnglesSubtract(desiredAngles, pVeh->m_vOrientation, desiredAngles); + // Now clamp the desired relative angles + // clamp yaw + desiredAngles[YAW] = AngleNormalize180(desiredAngles[YAW]); + if (pVeh->m_pVehicleInfo->turret[turretNum].yawClampLeft && desiredAngles[YAW] > pVeh->m_pVehicleInfo->turret[turretNum].yawClampLeft) { aimCorrect = qfalse; desiredAngles[YAW] = pVeh->m_pVehicleInfo->turret[turretNum].yawClampLeft; } - if ( pVeh->m_pVehicleInfo->turret[turretNum].yawClampRight - && desiredAngles[YAW] < pVeh->m_pVehicleInfo->turret[turretNum].yawClampRight ) - { + if (pVeh->m_pVehicleInfo->turret[turretNum].yawClampRight && desiredAngles[YAW] < pVeh->m_pVehicleInfo->turret[turretNum].yawClampRight) { aimCorrect = qfalse; desiredAngles[YAW] = pVeh->m_pVehicleInfo->turret[turretNum].yawClampRight; } - //clamp pitch - desiredAngles[PITCH] = AngleNormalize180( desiredAngles[PITCH] ); - if ( pVeh->m_pVehicleInfo->turret[turretNum].pitchClampDown - && desiredAngles[PITCH] > pVeh->m_pVehicleInfo->turret[turretNum].pitchClampDown ) - { + // clamp pitch + desiredAngles[PITCH] = AngleNormalize180(desiredAngles[PITCH]); + if (pVeh->m_pVehicleInfo->turret[turretNum].pitchClampDown && desiredAngles[PITCH] > pVeh->m_pVehicleInfo->turret[turretNum].pitchClampDown) { aimCorrect = qfalse; desiredAngles[PITCH] = pVeh->m_pVehicleInfo->turret[turretNum].pitchClampDown; } - if ( pVeh->m_pVehicleInfo->turret[turretNum].pitchClampUp - && desiredAngles[PITCH] < pVeh->m_pVehicleInfo->turret[turretNum].pitchClampUp ) - { + if (pVeh->m_pVehicleInfo->turret[turretNum].pitchClampUp && desiredAngles[PITCH] < pVeh->m_pVehicleInfo->turret[turretNum].pitchClampUp) { aimCorrect = qfalse; desiredAngles[PITCH] = pVeh->m_pVehicleInfo->turret[turretNum].pitchClampUp; } - //Now get the offset we want from our current relative angles - AnglesSubtract( desiredAngles, curAngles, addAngles ); - //Now cap the addAngles for our fTurnSpeed - if ( addAngles[PITCH] > turretStats->fTurnSpeed ) - { - //aimCorrect = qfalse;//??? + // Now get the offset we want from our current relative angles + AnglesSubtract(desiredAngles, curAngles, addAngles); + // Now cap the addAngles for our fTurnSpeed + if (addAngles[PITCH] > turretStats->fTurnSpeed) { + // aimCorrect = qfalse;//??? addAngles[PITCH] = turretStats->fTurnSpeed; - } - else if ( addAngles[PITCH] < -turretStats->fTurnSpeed ) - { - //aimCorrect = qfalse;//??? + } else if (addAngles[PITCH] < -turretStats->fTurnSpeed) { + // aimCorrect = qfalse;//??? addAngles[PITCH] = -turretStats->fTurnSpeed; } - if ( addAngles[YAW] > turretStats->fTurnSpeed ) - { - //aimCorrect = qfalse;//??? + if (addAngles[YAW] > turretStats->fTurnSpeed) { + // aimCorrect = qfalse;//??? addAngles[YAW] = turretStats->fTurnSpeed; - } - else if ( addAngles[YAW] < -turretStats->fTurnSpeed ) - { - //aimCorrect = qfalse;//??? + } else if (addAngles[YAW] < -turretStats->fTurnSpeed) { + // aimCorrect = qfalse;//??? addAngles[YAW] = -turretStats->fTurnSpeed; } - //Now add the additional angles back in to our current relative angles - //FIXME: add some AI aim error randomness...? - newAngles[PITCH] = AngleNormalize180( curAngles[PITCH]+addAngles[PITCH] ); - newAngles[YAW] = AngleNormalize180( curAngles[YAW]+addAngles[YAW] ); - //Now set the bone angles to the new angles - //set yaw - if ( turretStats->yawBone ) - { - VectorClear( yawAngles ); + // Now add the additional angles back in to our current relative angles + // FIXME: add some AI aim error randomness...? + newAngles[PITCH] = AngleNormalize180(curAngles[PITCH] + addAngles[PITCH]); + newAngles[YAW] = AngleNormalize180(curAngles[YAW] + addAngles[YAW]); + // Now set the bone angles to the new angles + // set yaw + if (turretStats->yawBone) { + VectorClear(yawAngles); yawAngles[turretStats->yawAxis] = newAngles[YAW]; - NPC_SetBoneAngles( parent, turretStats->yawBone, yawAngles ); + NPC_SetBoneAngles(parent, turretStats->yawBone, yawAngles); } - //set pitch - if ( turretStats->pitchBone ) - { - VectorClear( pitchAngles ); + // set pitch + if (turretStats->pitchBone) { + VectorClear(pitchAngles); pitchAngles[turretStats->pitchAxis] = newAngles[PITCH]; - NPC_SetBoneAngles( parent, turretStats->pitchBone, pitchAngles ); + NPC_SetBoneAngles(parent, turretStats->pitchBone, pitchAngles); } - //force muzzle to recalc next check + // force muzzle to recalc next check pVeh->m_iMuzzleTime[curMuzzle] = 0; return aimCorrect; } //----------------------------------------------------- -static qboolean VEH_TurretFindEnemies( Vehicle_t *pVeh, - gentity_t *parent, - turretStats_t *turretStats, - int turretNum, int curMuzzle ) +static qboolean VEH_TurretFindEnemies(Vehicle_t *pVeh, gentity_t *parent, turretStats_t *turretStats, int turretNum, int curMuzzle) //----------------------------------------------------- { - qboolean found = qfalse; - int i, count; - float bestDist = turretStats->fAIRange * turretStats->fAIRange; - float enemyDist; - vec3_t enemyDir, org, org2; - qboolean foundClient = qfalse; - gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; + qboolean found = qfalse; + int i, count; + float bestDist = turretStats->fAIRange * turretStats->fAIRange; + float enemyDist; + vec3_t enemyDir, org, org2; + qboolean foundClient = qfalse; + gentity_t *entity_list[MAX_GENTITIES], *target, *bestTarget = NULL; - WP_CalcVehMuzzle( parent, curMuzzle ); - VectorCopy( pVeh->m_vMuzzlePos[curMuzzle], org2 ); + WP_CalcVehMuzzle(parent, curMuzzle); + VectorCopy(pVeh->m_vMuzzlePos[curMuzzle], org2); - count = G_RadiusList( org2, turretStats->fAIRange, parent, qtrue, entity_list ); + count = G_RadiusList(org2, turretStats->fAIRange, parent, qtrue, entity_list); - for ( i = 0; i < count; i++ ) - { - trace_t tr; + for (i = 0; i < count; i++) { + trace_t tr; target = entity_list[i]; - if ( target == parent - || !target->takedamage - || target->health <= 0 - || ( target->flags & FL_NOTARGET )) - { + if (target == parent || !target->takedamage || target->health <= 0 || (target->flags & FL_NOTARGET)) { continue; } - if ( !target->client ) - {// only attack clients - if ( !(target->flags&FL_BBRUSH)//not a breakable brush - || !target->takedamage//is a bbrush, but invincible - || (target->NPC_targetname&&parent->targetname&&Q_stricmp(target->NPC_targetname,parent->targetname)!=0) )//not in invicible bbrush, but can only be broken by an NPC that is not me + if (!target->client) { // only attack clients + if (!(target->flags & FL_BBRUSH) // not a breakable brush + || !target->takedamage // is a bbrush, but invincible + || (target->NPC_targetname && parent->targetname && + Q_stricmp(target->NPC_targetname, parent->targetname) != 0)) // not in invicible bbrush, but can only be broken by an NPC that is not me { - if ( target->s.weapon == WP_TURRET - && target->classname - && Q_strncmp( "misc_turret", target->classname, 11 ) == 0 ) - {//these guys we want to shoot at - } - else - { + if (target->s.weapon == WP_TURRET && target->classname && + Q_strncmp("misc_turret", target->classname, 11) == 0) { // these guys we want to shoot at + } else { continue; } } - //else: we will shoot at bbrushes! - } - else if ( target->client->sess.sessionTeam == TEAM_SPECTATOR ) - { + // else: we will shoot at bbrushes! + } else if (target->client->sess.sessionTeam == TEAM_SPECTATOR) { continue; - } - else if ( target->client->tempSpectate >= level.time ) - { + } else if (target->client->tempSpectate >= level.time) { continue; } - if ( target == ((gentity_t*)pVeh->m_pPilot) - || target->r.ownerNum == parent->s.number ) - {//don't get angry at my pilot or passengers? + if (target == ((gentity_t *)pVeh->m_pPilot) || target->r.ownerNum == parent->s.number) { // don't get angry at my pilot or passengers? continue; } - if ( parent->client - && parent->client->sess.sessionTeam ) - { - if ( target->client ) - { - if ( target->client->sess.sessionTeam == parent->client->sess.sessionTeam ) - { + if (parent->client && parent->client->sess.sessionTeam) { + if (target->client) { + if (target->client->sess.sessionTeam == parent->client->sess.sessionTeam) { // A bot/client/NPC we don't want to shoot continue; } - } - else if ( target->teamnodmg == parent->client->sess.sessionTeam ) - {//some other entity that's allied with us + } else if (target->teamnodmg == parent->client->sess.sessionTeam) { // some other entity that's allied with us continue; } } - if ( !trap->InPVS( org2, target->r.currentOrigin )) - { + if (!trap->InPVS(org2, target->r.currentOrigin)) { continue; } - VectorCopy( target->r.currentOrigin, org ); + VectorCopy(target->r.currentOrigin, org); - trap->Trace( &tr, org2, NULL, NULL, org, parent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, org2, NULL, NULL, org, parent->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.entityNum == target->s.number - || (!tr.allsolid && !tr.startsolid && tr.fraction == 1.0 ) ) - { + if (tr.entityNum == target->s.number || (!tr.allsolid && !tr.startsolid && tr.fraction == 1.0)) { // Only acquire if have a clear shot, Is it in range and closer than our best? - VectorSubtract( target->r.currentOrigin, org2, enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + VectorSubtract(target->r.currentOrigin, org2, enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < bestDist || (target->client && !foundClient))// all things equal, keep current + if (enemyDist < bestDist || (target->client && !foundClient)) // all things equal, keep current { bestTarget = target; bestDist = enemyDist; found = qtrue; - if ( target->client ) - {//prefer clients over non-clients + if (target->client) { // prefer clients over non-clients foundClient = qtrue; } } } } - if ( found ) - { + if (found) { pVeh->turretStatus[turretNum].enemyEntNum = bestTarget->s.number; } return found; } -void VEH_TurretObeyPassengerControl( Vehicle_t *pVeh, gentity_t *parent, int turretNum ) -{ +void VEH_TurretObeyPassengerControl(Vehicle_t *pVeh, gentity_t *parent, int turretNum) { turretStats_t *turretStats = &pVeh->m_pVehicleInfo->turret[turretNum]; - gentity_t *passenger = (gentity_t *)pVeh->m_ppPassengers[turretStats->passengerNum-1]; + gentity_t *passenger = (gentity_t *)pVeh->m_ppPassengers[turretStats->passengerNum - 1]; - if ( passenger && passenger->client && passenger->health > 0 ) - {//a valid, living passenger client - vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[turretStats->iWeapon]; - int curMuzzle = pVeh->turretStatus[turretNum].nextMuzzle; + if (passenger && passenger->client && passenger->health > 0) { // a valid, living passenger client + vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[turretStats->iWeapon]; + int curMuzzle = pVeh->turretStatus[turretNum].nextMuzzle; vec3_t aimAngles; - VectorCopy( passenger->client->ps.viewangles, aimAngles ); + VectorCopy(passenger->client->ps.viewangles, aimAngles); - VEH_TurretAim( pVeh, parent, NULL, turretStats, vehWeapon, turretNum, curMuzzle, aimAngles ); - if ( (passenger->client->pers.cmd.buttons&(BUTTON_ATTACK|BUTTON_ALT_ATTACK)) ) - {//he's pressing an attack button, so fire! - VEH_TurretCheckFire( pVeh, parent, turretStats, vehWeapon, turretNum, curMuzzle ); + VEH_TurretAim(pVeh, parent, NULL, turretStats, vehWeapon, turretNum, curMuzzle, aimAngles); + if ((passenger->client->pers.cmd.buttons & (BUTTON_ATTACK | BUTTON_ALT_ATTACK))) { // he's pressing an attack button, so fire! + VEH_TurretCheckFire(pVeh, parent, turretStats, vehWeapon, turretNum, curMuzzle); } } } -void VEH_TurretThink( Vehicle_t *pVeh, gentity_t *parent, int turretNum ) +void VEH_TurretThink(Vehicle_t *pVeh, gentity_t *parent, int turretNum) //----------------------------------------------------- { - qboolean doAim = qfalse; - float enemyDist, rangeSq; - vec3_t enemyDir; + qboolean doAim = qfalse; + float enemyDist, rangeSq; + vec3_t enemyDir; turretStats_t *turretStats = &pVeh->m_pVehicleInfo->turret[turretNum]; - vehWeaponInfo_t *vehWeapon = NULL; - gentity_t *turretEnemy = NULL; - int curMuzzle = 0;//? - + vehWeaponInfo_t *vehWeapon = NULL; + gentity_t *turretEnemy = NULL; + int curMuzzle = 0; //? - if ( !turretStats || !turretStats->iAmmoMax ) - {//not a valid turret + if (!turretStats || !turretStats->iAmmoMax) { // not a valid turret return; } - if ( turretStats->passengerNum - && pVeh->m_iNumPassengers >= turretStats->passengerNum ) - {//the passenger that has control of this turret is on the ship - VEH_TurretObeyPassengerControl( pVeh, parent, turretNum ); + if (turretStats->passengerNum && pVeh->m_iNumPassengers >= turretStats->passengerNum) { // the passenger that has control of this turret is on the ship + VEH_TurretObeyPassengerControl(pVeh, parent, turretNum); return; - } - else if ( !turretStats->bAI )//try AI - {//this turret does not think on its own. + } else if (!turretStats->bAI) // try AI + { // this turret does not think on its own. return; } vehWeapon = &g_vehWeaponInfo[turretStats->iWeapon]; - rangeSq = (turretStats->fAIRange*turretStats->fAIRange); + rangeSq = (turretStats->fAIRange * turretStats->fAIRange); curMuzzle = pVeh->turretStatus[turretNum].nextMuzzle; - if ( pVeh->turretStatus[turretNum].enemyEntNum < ENTITYNUM_WORLD ) - { + if (pVeh->turretStatus[turretNum].enemyEntNum < ENTITYNUM_WORLD) { turretEnemy = &g_entities[pVeh->turretStatus[turretNum].enemyEntNum]; - if ( turretEnemy->health < 0 - || !turretEnemy->inuse - || turretEnemy == ((gentity_t*)pVeh->m_pPilot)//enemy became my pilot///? - || turretEnemy == parent - || turretEnemy->r.ownerNum == parent->s.number // a passenger? - || ( turretEnemy->client && turretEnemy->client->sess.sessionTeam == TEAM_SPECTATOR ) - || ( turretEnemy->client && turretEnemy->client->tempSpectate >= level.time ) ) - {//don't keep going after spectators, pilot, self, dead people, etc. + if (turretEnemy->health < 0 || !turretEnemy->inuse || turretEnemy == ((gentity_t *)pVeh->m_pPilot) // enemy became my pilot///? + || turretEnemy == parent || turretEnemy->r.ownerNum == parent->s.number // a passenger? + || (turretEnemy->client && turretEnemy->client->sess.sessionTeam == TEAM_SPECTATOR) || + (turretEnemy->client && turretEnemy->client->tempSpectate >= level.time)) { // don't keep going after spectators, pilot, self, dead people, etc. turretEnemy = NULL; pVeh->turretStatus[turretNum].enemyEntNum = ENTITYNUM_NONE; } } - if ( pVeh->turretStatus[turretNum].enemyHoldTime < level.time ) - { - if ( VEH_TurretFindEnemies( pVeh, parent, turretStats, turretNum, curMuzzle ) ) - { + if (pVeh->turretStatus[turretNum].enemyHoldTime < level.time) { + if (VEH_TurretFindEnemies(pVeh, parent, turretStats, turretNum, curMuzzle)) { turretEnemy = &g_entities[pVeh->turretStatus[turretNum].enemyEntNum]; doAim = qtrue; - } - else if ( parent->enemy && parent->enemy->s.number < ENTITYNUM_WORLD ) - { + } else if (parent->enemy && parent->enemy->s.number < ENTITYNUM_WORLD) { turretEnemy = parent->enemy; doAim = qtrue; } - if ( turretEnemy ) - {//found one - if ( turretEnemy->client ) - {//hold on to clients for a min of 3 seconds + if (turretEnemy) { // found one + if (turretEnemy->client) { // hold on to clients for a min of 3 seconds pVeh->turretStatus[turretNum].enemyHoldTime = level.time + 3000; - } - else - {//hold less + } else { // hold less pVeh->turretStatus[turretNum].enemyHoldTime = level.time + 500; } } } - if ( turretEnemy != NULL ) - { - if ( turretEnemy->health > 0 ) - { + if (turretEnemy != NULL) { + if (turretEnemy->health > 0) { // enemy is alive - WP_CalcVehMuzzle( parent, curMuzzle ); - VectorSubtract( turretEnemy->r.currentOrigin, pVeh->m_vMuzzlePos[curMuzzle], enemyDir ); - enemyDist = VectorLengthSquared( enemyDir ); + WP_CalcVehMuzzle(parent, curMuzzle); + VectorSubtract(turretEnemy->r.currentOrigin, pVeh->m_vMuzzlePos[curMuzzle], enemyDir); + enemyDist = VectorLengthSquared(enemyDir); - if ( enemyDist < rangeSq ) - { + if (enemyDist < rangeSq) { // was in valid radius - if ( trap->InPVS( pVeh->m_vMuzzlePos[curMuzzle], turretEnemy->r.currentOrigin ) ) - { + if (trap->InPVS(pVeh->m_vMuzzlePos[curMuzzle], turretEnemy->r.currentOrigin)) { // Every now and again, check to see if we can even trace to the enemy trace_t tr; vec3_t start, end; - VectorCopy( pVeh->m_vMuzzlePos[curMuzzle], start ); + VectorCopy(pVeh->m_vMuzzlePos[curMuzzle], start); - VectorCopy( turretEnemy->r.currentOrigin, end ); - trap->Trace( &tr, start, NULL, NULL, end, parent->s.number, MASK_SHOT, qfalse, 0, 0 ); + VectorCopy(turretEnemy->r.currentOrigin, end); + trap->Trace(&tr, start, NULL, NULL, end, parent->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.entityNum == turretEnemy->s.number - || (!tr.allsolid && !tr.startsolid ) ) - { - doAim = qtrue; // Can see our enemy + if (tr.entityNum == turretEnemy->s.number || (!tr.allsolid && !tr.startsolid)) { + doAim = qtrue; // Can see our enemy } } } } } - if ( doAim ) - { + if (doAim) { vec3_t aimAngles; - if ( VEH_TurretAim( pVeh, parent, turretEnemy, turretStats, vehWeapon, turretNum, curMuzzle, aimAngles ) ) - { - VEH_TurretCheckFire( pVeh, parent, /*turretEnemy,*/ turretStats, vehWeapon, turretNum, curMuzzle ); + if (VEH_TurretAim(pVeh, parent, turretEnemy, turretStats, vehWeapon, turretNum, curMuzzle, aimAngles)) { + VEH_TurretCheckFire(pVeh, parent, /*turretEnemy,*/ turretStats, vehWeapon, turretNum, curMuzzle); } } } diff --git a/codemp/game/g_vehicles.c b/codemp/game/g_vehicles.c index 1a91cf06c1..909a62e377 100644 --- a/codemp/game/g_vehicles.c +++ b/codemp/game/g_vehicles.c @@ -25,103 +25,89 @@ along with this program; if not, see . #include "bg_vehicles.h" -extern gentity_t *NPC_Spawn_Do( gentity_t *ent ); -extern void NPC_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags); +extern gentity_t *NPC_Spawn_Do(gentity_t *ent); +extern void NPC_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags); -extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts,int anim,int setAnimFlags, int blendTime); -extern void BG_SetLegsAnimTimer(playerState_t *ps, int time ); -extern void BG_SetTorsoAnimTimer(playerState_t *ps, int time ); -void G_VehUpdateShields( gentity_t *targ ); +extern void BG_SetAnim(playerState_t *ps, animation_t *animations, int setAnimParts, int anim, int setAnimFlags, int blendTime); +extern void BG_SetLegsAnimTimer(playerState_t *ps, int time); +extern void BG_SetTorsoAnimTimer(playerState_t *ps, int time); +void G_VehUpdateShields(gentity_t *targ); #ifdef _GAME - extern void VEH_TurretThink( Vehicle_t *pVeh, gentity_t *parent, int turretNum ); +extern void VEH_TurretThink(Vehicle_t *pVeh, gentity_t *parent, int turretNum); #endif -extern qboolean BG_UnrestrainedPitchRoll( playerState_t *ps, Vehicle_t *pVeh ); +extern qboolean BG_UnrestrainedPitchRoll(playerState_t *ps, Vehicle_t *pVeh); -void Vehicle_SetAnim(gentity_t *ent,int setAnimParts,int anim,int setAnimFlags, int iBlend) -{ +void Vehicle_SetAnim(gentity_t *ent, int setAnimParts, int anim, int setAnimFlags, int iBlend) { assert(ent->client); BG_SetAnim(&ent->client->ps, bgAllAnims[ent->localAnimIndex].anims, setAnimParts, anim, setAnimFlags, iBlend); ent->s.legsAnim = ent->client->ps.legsAnim; } -void G_VehicleTrace( trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask ) -{ +void G_VehicleTrace(trace_t *results, const vec3_t start, const vec3_t tMins, const vec3_t tMaxs, const vec3_t end, int passEntityNum, int contentmask) { trap->Trace(results, start, tMins, tMaxs, end, passEntityNum, contentmask, qfalse, 0, 0); } -Vehicle_t *G_IsRidingVehicle( gentity_t *pEnt ) -{ +Vehicle_t *G_IsRidingVehicle(gentity_t *pEnt) { gentity_t *ent = (gentity_t *)pEnt; - if ( ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && ent->s.m_iVehicleNum != 0 ) //ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) + if (ent && ent->client && ent->client->NPC_class != CLASS_VEHICLE && + ent->s.m_iVehicleNum != 0) // ent->client && ( ent->client->ps.eFlags & EF_IN_VEHICLE ) && ent->owner ) { return g_entities[ent->s.m_iVehicleNum].m_pVehicle; } return NULL; } - - -float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUcmd ) { - return 0.0f; -} +float G_CanJumpToEnemyVeh(Vehicle_t *pVeh, const usercmd_t *pUcmd) { return 0.0f; } // Spawn this vehicle into the world. -void G_VehicleSpawn( gentity_t *self ) -{ +void G_VehicleSpawn(gentity_t *self) { float yaw; gentity_t *vehEnt; - VectorCopy( self->r.currentOrigin, self->s.origin ); + VectorCopy(self->r.currentOrigin, self->s.origin); - trap->LinkEntity( (sharedEntity_t *)self ); + trap->LinkEntity((sharedEntity_t *)self); - if ( !self->count ) - { + if (!self->count) { self->count = 1; } - //save this because self gets removed in next func + // save this because self gets removed in next func yaw = self->s.angles[YAW]; - vehEnt = NPC_Spawn_Do( self ); + vehEnt = NPC_Spawn_Do(self); - if ( !vehEnt ) - { - return;//return NULL; + if (!vehEnt) { + return; // return NULL; } vehEnt->s.angles[YAW] = yaw; - if ( vehEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL ) - { + if (vehEnt->m_pVehicle->m_pVehicleInfo->type != VH_ANIMAL) { vehEnt->NPC->behaviorState = BS_CINEMATIC; } - if (vehEnt->spawnflags & 1) - { //die without pilot - if (!vehEnt->damage) - { //default 10 sec + if (vehEnt->spawnflags & 1) { // die without pilot + if (!vehEnt->damage) { // default 10 sec vehEnt->damage = 10000; } - if (!vehEnt->speed) - { //default 512 units + if (!vehEnt->speed) { // default 512 units vehEnt->speed = 512.0f; } vehEnt->m_pVehicle->m_iPilotTime = level.time + vehEnt->damage; } - //return vehEnt; + // return vehEnt; } // Attachs an entity to the vehicle it's riding (it's owner). -void G_AttachToVehicle( gentity_t *pEnt, usercmd_t **ucmd ) -{ - gentity_t *vehEnt; - mdxaBone_t boltMatrix; - gentity_t *ent; - int crotchBolt; - - if ( !pEnt || !ucmd ) +void G_AttachToVehicle(gentity_t *pEnt, usercmd_t **ucmd) { + gentity_t *vehEnt; + mdxaBone_t boltMatrix; + gentity_t *ent; + int crotchBolt; + + if (!pEnt || !ucmd) return; ent = (gentity_t *)pEnt; @@ -129,38 +115,33 @@ void G_AttachToVehicle( gentity_t *pEnt, usercmd_t **ucmd ) vehEnt = &g_entities[ent->r.ownerNum]; ent->waypoint = vehEnt->waypoint; // take the veh's waypoint as your own - if ( !vehEnt->m_pVehicle ) + if (!vehEnt->m_pVehicle) return; crotchBolt = trap->G2API_AddBolt(vehEnt->ghoul2, 0, "*driver"); // Get the driver tag. - trap->G2API_GetBoltMatrix( vehEnt->ghoul2, 0, crotchBolt, &boltMatrix, - vehEnt->m_pVehicle->m_vOrientation, vehEnt->r.currentOrigin, - level.time, NULL, vehEnt->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, ent->client->ps.origin ); + trap->G2API_GetBoltMatrix(vehEnt->ghoul2, 0, crotchBolt, &boltMatrix, vehEnt->m_pVehicle->m_vOrientation, vehEnt->r.currentOrigin, level.time, NULL, + vehEnt->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, ent->client->ps.origin); G_SetOrigin(ent, ent->client->ps.origin); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } // Animate the vehicle and it's riders. -void Animate( Vehicle_t *pVeh ) -{ +void Animate(Vehicle_t *pVeh) { // Validate a pilot rider. - if ( pVeh->m_pPilot ) - { - if (pVeh->m_pVehicleInfo->AnimateRiders) - { - pVeh->m_pVehicleInfo->AnimateRiders( pVeh ); + if (pVeh->m_pPilot) { + if (pVeh->m_pVehicleInfo->AnimateRiders) { + pVeh->m_pVehicleInfo->AnimateRiders(pVeh); } } - pVeh->m_pVehicleInfo->AnimateVehicle( pVeh ); + pVeh->m_pVehicleInfo->AnimateVehicle(pVeh); } // Determine whether this entity is able to board this vehicle or not. -qboolean ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +qboolean ValidateBoard(Vehicle_t *pVeh, bgEntity_t *pEnt) { // Determine where the entity is entering the vehicle from (left, right, or back). vec3_t vVehToEnt; vec3_t vVehDir; @@ -169,41 +150,29 @@ qboolean ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) vec3_t vVehAngles; float fDot; - if ( pVeh->m_iDieTime>0) - { + if (pVeh->m_iDieTime > 0) { return qfalse; } - if ( pVeh->m_pPilot != NULL ) - {//already have a driver! - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - {//I know, I know, this should by in the fighters's validateboard() - //can never steal a fighter from it's pilot - if ( pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers ) - { + if (pVeh->m_pPilot != NULL) { // already have a driver! + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // I know, I know, this should by in the fighters's validateboard() + // can never steal a fighter from it's pilot + if (pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers) { return qtrue; - } - else - { + } else { return qfalse; } - } - else if ( pVeh->m_pVehicleInfo->type == VH_WALKER ) - {//I know, I know, this should by in the walker's validateboard() - if ( !ent->client || ent->client->ps.groundEntityNum != parent->s.number ) - {//can only steal an occupied AT-ST if you're on top (by the hatch) + } else if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // I know, I know, this should by in the walker's validateboard() + if (!ent->client || ent->client->ps.groundEntityNum != parent->s.number) { // can only steal an occupied AT-ST if you're on top (by the hatch) return qfalse; } - } - else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) - {//you can only steal the bike from the driver if you landed on the driver or bike - return (pVeh->m_iBoarding==VEH_MOUNT_THROW_LEFT || pVeh->m_iBoarding==VEH_MOUNT_THROW_RIGHT); + } else if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { // you can only steal the bike from the driver if you landed on the driver or bike + return (pVeh->m_iBoarding == VEH_MOUNT_THROW_LEFT || pVeh->m_iBoarding == VEH_MOUNT_THROW_RIGHT); } } // Yes, you shouldn't have put this here (you 'should' have made an 'overriden' ValidateBoard func), but in this // instance it's more than adequate (which is why I do it too :-). Making a whole other function for this is silly. - else if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { + else if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // If you're a fighter, you allow everyone to enter you from all directions. return qtrue; } @@ -212,40 +181,36 @@ qboolean ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) VectorSet(vVehAngles, 0, parent->r.currentAngles[YAW], 0); // Vector from Entity to Vehicle. - VectorSubtract( ent->r.currentOrigin, parent->r.currentOrigin, vVehToEnt ); + VectorSubtract(ent->r.currentOrigin, parent->r.currentOrigin, vVehToEnt); vVehToEnt[2] = 0; - VectorNormalize( vVehToEnt ); + VectorNormalize(vVehToEnt); // Get the right vector. - AngleVectors( vVehAngles, NULL, vVehDir, NULL ); - VectorNormalize( vVehDir ); + AngleVectors(vVehAngles, NULL, vVehDir, NULL); + VectorNormalize(vVehDir); // Find the angle between the vehicle right vector and the vehicle to entity vector. - fDot = DotProduct( vVehToEnt, vVehDir ); + fDot = DotProduct(vVehToEnt, vVehDir); // If the entity is within a certain angle to the left of the vehicle... - if ( fDot >= 0.5f ) - { + if (fDot >= 0.5f) { // Right board. pVeh->m_iBoarding = -2; - } - else if ( fDot <= -0.5f ) - { + } else if (fDot <= -0.5f) { // Left board. pVeh->m_iBoarding = -1; } // Maybe they're trying to board from the back... - else - { + else { // The forward vector of the vehicle. - // AngleVectors( vVehAngles, vVehDir, NULL, NULL ); - // VectorNormalize( vVehDir ); + // AngleVectors( vVehAngles, vVehDir, NULL, NULL ); + // VectorNormalize( vVehDir ); // Find the angle between the vehicle forward and the vehicle to entity vector. - // fDot = DotProduct( vVehToEnt, vVehDir ); + // fDot = DotProduct( vVehToEnt, vVehDir ); // If the entity is within a certain angle behind the vehicle... - //if ( fDot <= -0.85f ) + // if ( fDot <= -0.85f ) { // Jump board. pVeh->m_iBoarding = -3; @@ -253,36 +218,32 @@ qboolean ValidateBoard( Vehicle_t *pVeh, bgEntity_t *pEnt ) } // If for some reason we couldn't board, leave... - if ( pVeh->m_iBoarding > -1 ) + if (pVeh->m_iBoarding > -1) return qfalse; return qtrue; } #ifdef VEH_CONTROL_SCHEME_4 -void FighterStorePilotViewAngles( Vehicle_t *pVeh, bgEntity_t *parent ) -{ +void FighterStorePilotViewAngles(Vehicle_t *pVeh, bgEntity_t *parent) { playerState_t *riderPS; bgEntity_t *rider = NULL; - if (parent->s.owner != ENTITYNUM_NONE) - { + if (parent->s.owner != ENTITYNUM_NONE) { rider = PM_BGEntForNum(parent->s.owner); //&g_entities[parent->r.ownerNum]; } - if ( !rider ) - { + if (!rider) { rider = parent; } riderPS = rider->playerState; - VectorClear( pVeh->m_vPrevRiderViewAngles ); + VectorClear(pVeh->m_vPrevRiderViewAngles); pVeh->m_vPrevRiderViewAngles[YAW] = AngleNormalize180(riderPS->viewangles[YAW]); } -#endif// VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 // Board this Vehicle (get on). The first entity to board an empty vehicle becomes the Pilot. -qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +qboolean Board(Vehicle_t *pVeh, bgEntity_t *pEnt) { vec3_t vPlayerDir; gentity_t *ent = (gentity_t *)pEnt; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; @@ -290,16 +251,15 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) // If it's not a valid entity, OR if the vehicle is blowing up (it's dead), OR it's not // empty, OR we're already being boarded, OR the person trying to get on us is already // in a vehicle (that was a fun bug :-), leave! - if ( !ent || parent->health <= 0 /*|| !( parent->client->ps.eFlags & EF_EMPTY_VEHICLE )*/ || (pVeh->m_iBoarding > 0) || - ( ent->client->ps.m_iVehicleNum ) ) + if (!ent || parent->health <= 0 /*|| !( parent->client->ps.eFlags & EF_EMPTY_VEHICLE )*/ || (pVeh->m_iBoarding > 0) || (ent->client->ps.m_iVehicleNum)) return qfalse; // Bucking so we can't do anything (NOTE: Should probably be a better name since fighters don't buck...). - if ( pVeh->m_ulFlags & VEH_BUCKING ) + if (pVeh->m_ulFlags & VEH_BUCKING) return qfalse; // Validate the entity's ability to board this vehicle. - if ( !pVeh->m_pVehicleInfo->ValidateBoard( pVeh, pEnt ) ) + if (!pVeh->m_pVehicleInfo->ValidateBoard(pVeh, pEnt)) return qfalse; // FIXME FIXME!!! Ask Mike monday where ent->client->ps.eFlags might be getting changed!!! It is always 0 (when it should @@ -307,30 +267,23 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) // Tell everybody their status. // ALWAYS let the player be the pilot. - if ( ent->s.number < MAX_CLIENTS ) - { + if (ent->s.number < MAX_CLIENTS) { pVeh->m_pOldPilot = pVeh->m_pPilot; - - if ( !pVeh->m_pPilot ) - { //become the pilot, if there isn't one now - pVeh->m_pVehicleInfo->SetPilot( pVeh, (bgEntity_t *)ent ); + if (!pVeh->m_pPilot) { // become the pilot, if there isn't one now + pVeh->m_pVehicleInfo->SetPilot(pVeh, (bgEntity_t *)ent); } // If we're not yet full... - else if ( pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers ) - { + else if (pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers) { int i; // Find an empty slot and put that passenger here. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] == NULL ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i] == NULL) { pVeh->m_ppPassengers[i] = (bgEntity_t *)ent; #ifdef _GAME - //Server just needs to tell client which passengernum he is - if ( ent->client ) - { - ent->client->ps.generic1 = i+1; + // Server just needs to tell client which passengernum he is + if (ent->client) { + ent->client->ps.generic1 = i + 1; } #endif break; @@ -339,39 +292,34 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) pVeh->m_iNumPassengers++; } // We're full, sorry... - else - { + else { return qfalse; } ent->s.m_iVehicleNum = parent->s.number; - if (ent->client) - { + if (ent->client) { ent->client->ps.m_iVehicleNum = ent->s.m_iVehicleNum; } - if ( pVeh->m_pPilot == (bgEntity_t *)ent ) - { + if (pVeh->m_pPilot == (bgEntity_t *)ent) { parent->r.ownerNum = ent->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction } #ifdef _GAME { gentity_t *gParent = (gentity_t *)parent; - if ( (gParent->spawnflags&2) ) - {//was being suspended - gParent->spawnflags &= ~2;//SUSPENDED - clear this spawnflag, no longer docked, okay to free-fall if not in space - //gParent->client->ps.eFlags &= ~EF_RADAROBJECT; - G_Sound( gParent, CHAN_AUTO, G_SoundIndex( "sound/vehicles/common/release.wav" ) ); - if ( gParent->fly_sound_debounce_time ) - {//we should drop like a rock for a few seconds + if ((gParent->spawnflags & 2)) { // was being suspended + gParent->spawnflags &= ~2; // SUSPENDED - clear this spawnflag, no longer docked, okay to free-fall if not in space + // gParent->client->ps.eFlags &= ~EF_RADAROBJECT; + G_Sound(gParent, CHAN_AUTO, G_SoundIndex("sound/vehicles/common/release.wav")); + if (gParent->fly_sound_debounce_time) { // we should drop like a rock for a few seconds pVeh->m_iDropTime = level.time + gParent->fly_sound_debounce_time; } } } #endif - //FIXME: rider needs to look in vehicle's direction when he gets in - // Clear these since they're used to turn the vehicle now. + // FIXME: rider needs to look in vehicle's direction when he gets in + // Clear these since they're used to turn the vehicle now. /*SetClientViewAngle( ent, pVeh->m_vOrientation ); memset( &parent->client->usercmd, 0, sizeof( usercmd_t ) ); memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); @@ -379,44 +327,35 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) VectorClear( parent->client->ps.delta_angles );*/ // Set the looping sound only when there is a pilot (when the vehicle is "on"). - if ( pVeh->m_pVehicleInfo->soundLoop ) - { + if (pVeh->m_pVehicleInfo->soundLoop) { parent->client->ps.loopSound = parent->s.loopSound = pVeh->m_pVehicleInfo->soundLoop; } - } - else - { + } else { // If there's no pilot, try to drive this vehicle. - if ( pVeh->m_pPilot == NULL ) - { - pVeh->m_pVehicleInfo->SetPilot( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pPilot == NULL) { + pVeh->m_pVehicleInfo->SetPilot(pVeh, (bgEntity_t *)ent); // TODO: Set pilot should do all this stuff.... parent->r.ownerNum = ent->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction // Set the looping sound only when there is a pilot (when the vehicle is "on"). - if ( pVeh->m_pVehicleInfo->soundLoop ) - { + if (pVeh->m_pVehicleInfo->soundLoop) { parent->client->ps.loopSound = parent->s.loopSound = pVeh->m_pVehicleInfo->soundLoop; } parent->client->ps.speed = 0; - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); } // If we're not yet full... - else if ( pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers ) - { + else if (pVeh->m_iNumPassengers < pVeh->m_pVehicleInfo->maxPassengers) { int i; // Find an empty slot and put that passenger here. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] == NULL ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i] == NULL) { pVeh->m_ppPassengers[i] = (bgEntity_t *)ent; #ifdef _GAME - //Server just needs to tell client which passengernum he is - if ( ent->client ) - { - ent->client->ps.generic1 = i+1; + // Server just needs to tell client which passengernum he is + if (ent->client) { + ent->client->ps.generic1 = i + 1; } #endif break; @@ -425,8 +364,7 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) pVeh->m_iNumPassengers++; } // We're full, sorry... - else - { + else { return qfalse; } } @@ -434,95 +372,84 @@ qboolean Board( Vehicle_t *pVeh, bgEntity_t *pEnt ) // Make sure the entity knows it's in a vehicle. ent->client->ps.m_iVehicleNum = parent->s.number; ent->r.ownerNum = parent->s.number; - ent->s.owner = ent->r.ownerNum; //for prediction - if (pVeh->m_pPilot == (bgEntity_t *)ent) - { - parent->client->ps.m_iVehicleNum = ent->s.number+1; //always gonna be under MAX_CLIENTS so no worries about 1 byte overflow + ent->s.owner = ent->r.ownerNum; // for prediction + if (pVeh->m_pPilot == (bgEntity_t *)ent) { + parent->client->ps.m_iVehicleNum = ent->s.number + 1; // always gonna be under MAX_CLIENTS so no worries about 1 byte overflow } - //memset( &ent->client->usercmd, 0, sizeof( usercmd_t ) ); + // memset( &ent->client->usercmd, 0, sizeof( usercmd_t ) ); - //FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player - if ( pVeh->m_pVehicleInfo->numHands == 2 ) - {//switch to vehicle weapon + // FIXME: no saber or weapons if numHands = 2, should switch to speeder weapon, no attack anim on player + if (pVeh->m_pVehicleInfo->numHands == 2) { // switch to vehicle weapon } - if ( pVeh->m_pVehicleInfo->hideRider ) - {//hide the rider - pVeh->m_pVehicleInfo->Ghost( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pVehicleInfo->hideRider) { // hide the rider + pVeh->m_pVehicleInfo->Ghost(pVeh, (bgEntity_t *)ent); } // Play the start sounds - if ( pVeh->m_pVehicleInfo->soundOn ) - { - G_Sound( parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn ); + if (pVeh->m_pVehicleInfo->soundOn) { + G_Sound(parent, CHAN_AUTO, pVeh->m_pVehicleInfo->soundOn); } #ifdef VEH_CONTROL_SCHEME_4 - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - {//clear their angles - FighterStorePilotViewAngles( pVeh, (bgEntity_t *)parent ); + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { // clear their angles + FighterStorePilotViewAngles(pVeh, (bgEntity_t *)parent); } -#endif //VEH_CONTROL_SCHEME_4 +#endif // VEH_CONTROL_SCHEME_4 - VectorCopy( pVeh->m_vOrientation, vPlayerDir ); + VectorCopy(pVeh->m_vOrientation, vPlayerDir); vPlayerDir[ROLL] = 0; - SetClientViewAngle( ent, vPlayerDir ); + SetClientViewAngle(ent, vPlayerDir); return qtrue; } -qboolean VEH_TryEject( Vehicle_t *pVeh, - gentity_t *parent, - gentity_t *ent, - int ejectDir, - vec3_t vExitPos ) -{ - float fBias; - float fVehDiag; - float fEntDiag; - int oldOwner; - vec3_t vEntMins, vEntMaxs, vVehLeaveDir, vVehAngles; - trace_t m_ExitTrace; +qboolean VEH_TryEject(Vehicle_t *pVeh, gentity_t *parent, gentity_t *ent, int ejectDir, vec3_t vExitPos) { + float fBias; + float fVehDiag; + float fEntDiag; + int oldOwner; + vec3_t vEntMins, vEntMaxs, vVehLeaveDir, vVehAngles; + trace_t m_ExitTrace; // Make sure that the entity is not 'stuck' inside the vehicle (since their bboxes will now intersect). // This makes the entity leave the vehicle from the right side. VectorSet(vVehAngles, 0, parent->r.currentAngles[YAW], 0); - switch ( ejectDir ) - { - // Left. - case VEH_EJECT_LEFT: - AngleVectors( vVehAngles, NULL, vVehLeaveDir, NULL ); - vVehLeaveDir[0] = -vVehLeaveDir[0]; - vVehLeaveDir[1] = -vVehLeaveDir[1]; - vVehLeaveDir[2] = -vVehLeaveDir[2]; - break; - // Right. - case VEH_EJECT_RIGHT: - AngleVectors( vVehAngles, NULL, vVehLeaveDir, NULL ); - break; - // Front. - case VEH_EJECT_FRONT: - AngleVectors( vVehAngles, vVehLeaveDir, NULL, NULL ); - break; - // Rear. - case VEH_EJECT_REAR: - AngleVectors( vVehAngles, vVehLeaveDir, NULL, NULL ); - vVehLeaveDir[0] = -vVehLeaveDir[0]; - vVehLeaveDir[1] = -vVehLeaveDir[1]; - vVehLeaveDir[2] = -vVehLeaveDir[2]; - break; - // Top. - case VEH_EJECT_TOP: - AngleVectors( vVehAngles, NULL, NULL, vVehLeaveDir ); - break; - // Bottom?. - case VEH_EJECT_BOTTOM: - break; + switch (ejectDir) { + // Left. + case VEH_EJECT_LEFT: + AngleVectors(vVehAngles, NULL, vVehLeaveDir, NULL); + vVehLeaveDir[0] = -vVehLeaveDir[0]; + vVehLeaveDir[1] = -vVehLeaveDir[1]; + vVehLeaveDir[2] = -vVehLeaveDir[2]; + break; + // Right. + case VEH_EJECT_RIGHT: + AngleVectors(vVehAngles, NULL, vVehLeaveDir, NULL); + break; + // Front. + case VEH_EJECT_FRONT: + AngleVectors(vVehAngles, vVehLeaveDir, NULL, NULL); + break; + // Rear. + case VEH_EJECT_REAR: + AngleVectors(vVehAngles, vVehLeaveDir, NULL, NULL); + vVehLeaveDir[0] = -vVehLeaveDir[0]; + vVehLeaveDir[1] = -vVehLeaveDir[1]; + vVehLeaveDir[2] = -vVehLeaveDir[2]; + break; + // Top. + case VEH_EJECT_TOP: + AngleVectors(vVehAngles, NULL, NULL, vVehLeaveDir); + break; + // Bottom?. + case VEH_EJECT_BOTTOM: + break; } - VectorNormalize( vVehLeaveDir ); - //NOTE: not sure why following line was needed - MCG - //pVeh->m_EjectDir = VEH_EJECT_LEFT; + VectorNormalize(vVehLeaveDir); + // NOTE: not sure why following line was needed - MCG + // pVeh->m_EjectDir = VEH_EJECT_LEFT; // Since (as of this time) the collidable geometry of the entity is just an axis // aligned box, we need to get the diagonal length of it in case we come out on that side. @@ -531,53 +458,49 @@ qboolean VEH_TryEject( Vehicle_t *pVeh, // TODO: DO diagonal for entity. fBias = 1.0f; - if (pVeh->m_pVehicleInfo->type == VH_WALKER) - { //hacktastic! + if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // hacktastic! fBias += 0.2f; } - VectorCopy( ent->r.currentOrigin, vExitPos ); - fVehDiag = sqrtf( ( parent->r.maxs[0] * parent->r.maxs[0] ) + ( parent->r.maxs[1] * parent->r.maxs[1] ) ); - VectorCopy( ent->r.maxs, vEntMaxs ); - if ( ent->s.number < MAX_CLIENTS ) - {//for some reason, in MP, player client mins and maxs are never stored permanently, just set to these hardcoded numbers in PMove + VectorCopy(ent->r.currentOrigin, vExitPos); + fVehDiag = sqrtf((parent->r.maxs[0] * parent->r.maxs[0]) + (parent->r.maxs[1] * parent->r.maxs[1])); + VectorCopy(ent->r.maxs, vEntMaxs); + if (ent->s.number < + MAX_CLIENTS) { // for some reason, in MP, player client mins and maxs are never stored permanently, just set to these hardcoded numbers in PMove vEntMaxs[0] = 15; vEntMaxs[1] = 15; } - fEntDiag = sqrtf( ( vEntMaxs[0] * vEntMaxs[0] ) + ( vEntMaxs[1] * vEntMaxs[1] ) ); - vVehLeaveDir[0] *= ( fVehDiag + fEntDiag ) * fBias; // x - vVehLeaveDir[1] *= ( fVehDiag + fEntDiag ) * fBias; // y - vVehLeaveDir[2] *= ( fVehDiag + fEntDiag ) * fBias; - VectorAdd( vExitPos, vVehLeaveDir, vExitPos ); + fEntDiag = sqrtf((vEntMaxs[0] * vEntMaxs[0]) + (vEntMaxs[1] * vEntMaxs[1])); + vVehLeaveDir[0] *= (fVehDiag + fEntDiag) * fBias; // x + vVehLeaveDir[1] *= (fVehDiag + fEntDiag) * fBias; // y + vVehLeaveDir[2] *= (fVehDiag + fEntDiag) * fBias; + VectorAdd(vExitPos, vVehLeaveDir, vExitPos); - //we actually could end up *not* getting off if the trace fails... - // Check to see if this new position is a valid place for our entity to go. + // we actually could end up *not* getting off if the trace fails... + // Check to see if this new position is a valid place for our entity to go. VectorSet(vEntMins, -15.0f, -15.0f, DEFAULT_MINS_2); VectorSet(vEntMaxs, 15.0f, 15.0f, DEFAULT_MAXS_2); oldOwner = ent->r.ownerNum; ent->r.ownerNum = ENTITYNUM_NONE; - G_VehicleTrace( &m_ExitTrace, ent->r.currentOrigin, vEntMins, vEntMaxs, vExitPos, ent->s.number, ent->clipmask ); + G_VehicleTrace(&m_ExitTrace, ent->r.currentOrigin, vEntMins, vEntMaxs, vExitPos, ent->s.number, ent->clipmask); ent->r.ownerNum = oldOwner; - if ( m_ExitTrace.allsolid//in solid - || m_ExitTrace.startsolid) - { + if (m_ExitTrace.allsolid // in solid + || m_ExitTrace.startsolid) { return qfalse; } // If the trace hit something, we can't go there! - if ( m_ExitTrace.fraction < 1.0f ) - {//not totally clear - if ( (parent->clipmask&ent->r.contents) )//vehicle could actually get stuck on body - {//the trace hit the vehicle, don't let them get out, just in case + if (m_ExitTrace.fraction < 1.0f) { // not totally clear + if ((parent->clipmask & ent->r.contents)) // vehicle could actually get stuck on body + { // the trace hit the vehicle, don't let them get out, just in case return qfalse; } - //otherwise, use the trace.endpos - VectorCopy( m_ExitTrace.endpos, vExitPos ); + // otherwise, use the trace.endpos + VectorCopy(m_ExitTrace.endpos, vExitPos); } return qtrue; } -void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) -{ +void G_EjectDroidUnit(Vehicle_t *pVeh, qboolean kill) { pVeh->m_pDroidUnit->s.m_iVehicleNum = ENTITYNUM_NONE; pVeh->m_pDroidUnit->s.owner = ENTITYNUM_NONE; // pVeh->m_pDroidUnit->s.otherEntityNum2 = ENTITYNUM_NONE; @@ -586,15 +509,13 @@ void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) gentity_t *droidEnt = (gentity_t *)pVeh->m_pDroidUnit; droidEnt->flags &= ~FL_UNDYING; droidEnt->r.ownerNum = ENTITYNUM_NONE; - if ( droidEnt->client ) - { + if (droidEnt->client) { droidEnt->client->ps.m_iVehicleNum = ENTITYNUM_NONE; } - if ( kill ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (kill) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(droidEnt->s.number, CHAN_VOICE); - G_Damage( droidEnt, NULL, NULL, NULL, droidEnt->s.origin, 10000, 0, MOD_SUICIDE );//FIXME: proper MOD? Get from vehicle? + G_Damage(droidEnt, NULL, NULL, NULL, droidEnt->s.origin, 10000, 0, MOD_SUICIDE); // FIXME: proper MOD? Get from vehicle? } } #endif @@ -602,45 +523,36 @@ void G_EjectDroidUnit( Vehicle_t *pVeh, qboolean kill ) } // Eject the pilot from the vehicle. -qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) -{ - gentity_t *parent; - vec3_t vExitPos; - gentity_t *ent = (gentity_t *)pEnt; - int firstEjectDir; +qboolean Eject(Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject) { + gentity_t *parent; + vec3_t vExitPos; + gentity_t *ent = (gentity_t *)pEnt; + int firstEjectDir; - qboolean taintedRider = qfalse; - qboolean deadRider = qfalse; + qboolean taintedRider = qfalse; + qboolean deadRider = qfalse; - if ( pEnt == pVeh->m_pDroidUnit ) - { - G_EjectDroidUnit( pVeh, qfalse ); + if (pEnt == pVeh->m_pDroidUnit) { + G_EjectDroidUnit(pVeh, qfalse); return qtrue; } - if (ent) - { - if (!ent->inuse || !ent->client || ent->client->pers.connected != CON_CONNECTED) - { + if (ent) { + if (!ent->inuse || !ent->client || ent->client->pers.connected != CON_CONNECTED) { taintedRider = qtrue; parent = (gentity_t *)pVeh->m_pParentEntity; goto getItOutOfMe; - } - else if (ent->health < 1) - { + } else if (ent->health < 1) { deadRider = qtrue; } } // Validate. - if ( !ent ) - { + if (!ent) { return qfalse; } - if ( !forceEject ) - { - if ( !( pVeh->m_iBoarding == 0 || pVeh->m_iBoarding == -999 || ( pVeh->m_iBoarding < -3 && pVeh->m_iBoarding >= -9 ) ) ) - { + if (!forceEject) { + if (!(pVeh->m_iBoarding == 0 || pVeh->m_iBoarding == -999 || (pVeh->m_iBoarding < -3 && pVeh->m_iBoarding >= -9))) { deadRider = qtrue; pVeh->m_iBoarding = 0; pVeh->m_bWasBoarding = qfalse; @@ -649,97 +561,79 @@ qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) parent = (gentity_t *)pVeh->m_pParentEntity; - //Try ejecting in every direction - if ( pVeh->m_EjectDir < VEH_EJECT_LEFT ) - { + // Try ejecting in every direction + if (pVeh->m_EjectDir < VEH_EJECT_LEFT) { pVeh->m_EjectDir = VEH_EJECT_LEFT; - } - else if ( pVeh->m_EjectDir > VEH_EJECT_BOTTOM ) - { + } else if (pVeh->m_EjectDir > VEH_EJECT_BOTTOM) { pVeh->m_EjectDir = VEH_EJECT_BOTTOM; } firstEjectDir = pVeh->m_EjectDir; - while ( !VEH_TryEject( pVeh, parent, ent, pVeh->m_EjectDir, vExitPos ) ) - { + while (!VEH_TryEject(pVeh, parent, ent, pVeh->m_EjectDir, vExitPos)) { pVeh->m_EjectDir++; - if ( pVeh->m_EjectDir > VEH_EJECT_BOTTOM ) - { + if (pVeh->m_EjectDir > VEH_EJECT_BOTTOM) { pVeh->m_EjectDir = VEH_EJECT_LEFT; } - if ( pVeh->m_EjectDir == firstEjectDir ) - {//they all failed - if (!deadRider) - { //if he's dead.. just shove him in solid, who cares. + if (pVeh->m_EjectDir == firstEjectDir) { // they all failed + if (!deadRider) { // if he's dead.. just shove him in solid, who cares. return qfalse; } - if ( forceEject ) - {//we want to always get out, just eject him here - VectorCopy( ent->r.currentOrigin, vExitPos ); + if (forceEject) { // we want to always get out, just eject him here + VectorCopy(ent->r.currentOrigin, vExitPos); break; - } - else - {//can't eject + } else { // can't eject return qfalse; } } } // Move them to the exit position. - G_SetOrigin( ent, vExitPos ); + G_SetOrigin(ent, vExitPos); VectorCopy(ent->r.currentOrigin, ent->client->ps.origin); - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); // If it's the player, stop overrides. - if ( ent->s.number < MAX_CLIENTS ) - { + if (ent->s.number < MAX_CLIENTS) { } getItOutOfMe: // If he's the pilot... - if ( (gentity_t *)pVeh->m_pPilot == ent ) - { + if ((gentity_t *)pVeh->m_pPilot == ent) { int j = 0; pVeh->m_pPilot = NULL; parent->r.ownerNum = ENTITYNUM_NONE; - parent->s.owner = parent->r.ownerNum; //for prediction + parent->s.owner = parent->r.ownerNum; // for prediction - //keep these current angles - //SetClientViewAngle( parent, pVeh->m_vOrientation ); - memset( &parent->client->pers.cmd, 0, sizeof( usercmd_t ) ); - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + // keep these current angles + // SetClientViewAngle( parent, pVeh->m_vOrientation ); + memset(&parent->client->pers.cmd, 0, sizeof(usercmd_t)); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); - while (j < pVeh->m_iNumPassengers) - { - if (pVeh->m_ppPassengers[j]) - { + while (j < pVeh->m_iNumPassengers) { + if (pVeh->m_ppPassengers[j]) { int k = 1; - pVeh->m_pVehicleInfo->SetPilot( pVeh, pVeh->m_ppPassengers[j] ); + pVeh->m_pVehicleInfo->SetPilot(pVeh, pVeh->m_ppPassengers[j]); parent->r.ownerNum = pVeh->m_ppPassengers[j]->s.number; - parent->s.owner = parent->r.ownerNum; //for prediction - parent->client->ps.m_iVehicleNum = pVeh->m_ppPassengers[j]->s.number+1; + parent->s.owner = parent->r.ownerNum; // for prediction + parent->client->ps.m_iVehicleNum = pVeh->m_ppPassengers[j]->s.number + 1; - //rearrange the passenger slots now.. + // rearrange the passenger slots now.. #ifdef _GAME - //Server just needs to tell client he's not a passenger anymore - if ( ((gentity_t *)pVeh->m_ppPassengers[j])->client ) - { + // Server just needs to tell client he's not a passenger anymore + if (((gentity_t *)pVeh->m_ppPassengers[j])->client) { ((gentity_t *)pVeh->m_ppPassengers[j])->client->ps.generic1 = 0; } #endif pVeh->m_ppPassengers[j] = NULL; - while (k < pVeh->m_iNumPassengers) - { - if (!pVeh->m_ppPassengers[k-1]) - { //move down - pVeh->m_ppPassengers[k-1] = pVeh->m_ppPassengers[k]; + while (k < pVeh->m_iNumPassengers) { + if (!pVeh->m_ppPassengers[k - 1]) { // move down + pVeh->m_ppPassengers[k - 1] = pVeh->m_ppPassengers[k]; pVeh->m_ppPassengers[k] = NULL; #ifdef _GAME - //Server just needs to tell client which passenger he is - if ( pVeh->m_ppPassengers[k-1] && ((gentity_t *)pVeh->m_ppPassengers[k-1])->client ) - { - ((gentity_t *)pVeh->m_ppPassengers[k-1])->client->ps.generic1 = k; + // Server just needs to tell client which passenger he is + if (pVeh->m_ppPassengers[k - 1] && ((gentity_t *)pVeh->m_ppPassengers[k - 1])->client) { + ((gentity_t *)pVeh->m_ppPassengers[k - 1])->client->ps.generic1 = k; } #endif } @@ -751,24 +645,17 @@ qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } j++; } - } - else if (ent==(gentity_t *)pVeh->m_pOldPilot) - { + } else if (ent == (gentity_t *)pVeh->m_pOldPilot) { pVeh->m_pOldPilot = 0; - } - else - { + } else { int i; // Look for this guy in the passenger list. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { // If we found him... - if ( (gentity_t *)pVeh->m_ppPassengers[i] == ent ) - { + if ((gentity_t *)pVeh->m_ppPassengers[i] == ent) { #ifdef _GAME - //Server just needs to tell client he's not a passenger anymore - if ( ((gentity_t *)pVeh->m_ppPassengers[i])->client ) - { + // Server just needs to tell client he's not a passenger anymore + if (((gentity_t *)pVeh->m_ppPassengers[i])->client) { ((gentity_t *)pVeh->m_ppPassengers[i])->client->ps.generic1 = 0; } #endif @@ -779,33 +666,28 @@ qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } // Didn't find him, can't eject because they aren't in the vehicle (hopefully)! - if ( i == pVeh->m_pVehicleInfo->maxPassengers ) - { + if (i == pVeh->m_pVehicleInfo->maxPassengers) { return qfalse; } } - //if (!taintedRider) + // if (!taintedRider) { - if ( pVeh->m_pVehicleInfo->hideRider ) - { - pVeh->m_pVehicleInfo->UnGhost( pVeh, (bgEntity_t *)ent ); + if (pVeh->m_pVehicleInfo->hideRider) { + pVeh->m_pVehicleInfo->UnGhost(pVeh, (bgEntity_t *)ent); } } // If the vehicle now has no pilot... - if ( pVeh->m_pPilot == NULL ) - { + if (pVeh->m_pPilot == NULL) { parent->client->ps.loopSound = parent->s.loopSound = 0; // Completely empty vehicle...? - if ( pVeh->m_iNumPassengers == 0 ) - { + if (pVeh->m_iNumPassengers == 0) { parent->client->ps.m_iVehicleNum = 0; } } - if (taintedRider) - { //you can go now + if (taintedRider) { // you can go now pVeh->m_iBoarding = level.time + 1000; return qtrue; } @@ -813,74 +695,70 @@ qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) // Client not in a vehicle. ent->client->ps.m_iVehicleNum = 0; ent->r.ownerNum = ENTITYNUM_NONE; - ent->s.owner = ent->r.ownerNum; //for prediction + ent->s.owner = ent->r.ownerNum; // for prediction ent->client->ps.viewangles[PITCH] = 0.0f; ent->client->ps.viewangles[ROLL] = 0.0f; ent->client->ps.viewangles[YAW] = pVeh->m_vOrientation[YAW]; SetClientViewAngle(ent, ent->client->ps.viewangles); - if (ent->client->solidHack) - { + if (ent->client->solidHack) { ent->client->solidHack = 0; ent->r.contents = CONTENTS_BODY; } ent->s.m_iVehicleNum = 0; // Jump out. -/* if ( ent->client->ps.velocity[2] < JUMP_VELOCITY ) - { - ent->client->ps.velocity[2] = JUMP_VELOCITY; - } - else - { - ent->client->ps.velocity[2] += JUMP_VELOCITY; - }*/ + /* if ( ent->client->ps.velocity[2] < JUMP_VELOCITY ) + { + ent->client->ps.velocity[2] = JUMP_VELOCITY; + } + else + { + ent->client->ps.velocity[2] += JUMP_VELOCITY; + }*/ // Make sure entity is facing the direction it got off at. - //if was using vehicle weapon, remove it and switch to normal weapon when hop out... - if ( ent->client->ps.weapon == WP_NONE ) - {//FIXME: check against this vehicle's gun from the g_vehicleInfo table - //remove the vehicle's weapon from me - //ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_EMPLACED_GUN ); - //ent->client->ps.ammo[weaponData[WP_EMPLACED_GUN].ammoIndex] = 0;//maybe store this ammo on the vehicle before clearing it? - //switch back to a normal weapon we're carrying + // if was using vehicle weapon, remove it and switch to normal weapon when hop out... + if (ent->client->ps.weapon == WP_NONE) { // FIXME: check against this vehicle's gun from the g_vehicleInfo table + // remove the vehicle's weapon from me + // ent->client->ps.stats[STAT_WEAPONS] &= ~( 1 << WP_EMPLACED_GUN ); + // ent->client->ps.ammo[weaponData[WP_EMPLACED_GUN].ammoIndex] = 0;//maybe store this ammo on the vehicle before + // clearing it? switch back to a normal weapon we're carrying - //FIXME: store the weapon we were using when we got on and restore that when hop off -/* if ( (ent->client->ps.stats[STAT_WEAPONS]&(1< WP_NONE; checkWp-- ) - { - if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<client->ps.stats[STAT_WEAPONS]&(1< WP_NONE; checkWp-- ) + { + if ( (ent->client->ps.stats[STAT_WEAPONS]&(1<s.number && ent->client->ps.weapon != WP_SABER - && cg_gunAutoFirst.value ) - { - trap->cvar_set( "cg_thirdperson", "0" ); - }*/ - BG_SetLegsAnimTimer( &ent->client->ps, 0 ); - BG_SetTorsoAnimTimer( &ent->client->ps, 0 ); + /* if ( !ent->s.number && ent->client->ps.weapon != WP_SABER + && cg_gunAutoFirst.value ) + { + trap->cvar_set( "cg_thirdperson", "0" ); + }*/ + BG_SetLegsAnimTimer(&ent->client->ps, 0); + BG_SetTorsoAnimTimer(&ent->client->ps, 0); // Set how long until this vehicle can be boarded again. pVeh->m_iBoarding = level.time + 1000; @@ -889,8 +767,7 @@ qboolean Eject( Vehicle_t *pVeh, bgEntity_t *pEnt, qboolean forceEject ) } // Eject all the inhabitants of this vehicle. -qboolean EjectAll( Vehicle_t *pVeh ) -{ +qboolean EjectAll(Vehicle_t *pVeh) { // TODO: Setup a default escape for ever vehicle type. pVeh->m_EjectDir = VEH_EJECT_TOP; @@ -899,54 +776,46 @@ qboolean EjectAll( Vehicle_t *pVeh ) pVeh->m_bWasBoarding = qfalse; // Throw them off. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { #ifdef _GAME - gentity_t *pilot = (gentity_t*)pVeh->m_pPilot; + gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; #endif - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); #ifdef _GAME - if ( pVeh->m_pVehicleInfo->killRiderOnDeath && pilot ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (pVeh->m_pVehicleInfo->killRiderOnDeath && pilot) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(pilot->s.number, CHAN_VOICE); - G_Damage( pilot, NULL, NULL, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE ); + G_Damage(pilot, NULL, NULL, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE); } #endif } - if ( pVeh->m_pOldPilot ) - { + if (pVeh->m_pOldPilot) { #ifdef _GAME - gentity_t *pilot = (gentity_t*)pVeh->m_pOldPilot; + gentity_t *pilot = (gentity_t *)pVeh->m_pOldPilot; #endif - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pOldPilot, qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pOldPilot, qtrue); #ifdef _GAME - if ( pVeh->m_pVehicleInfo->killRiderOnDeath && pilot ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (pVeh->m_pVehicleInfo->killRiderOnDeath && pilot) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(pilot->s.number, CHAN_VOICE); - G_Damage( pilot, NULL, NULL, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE ); + G_Damage(pilot, NULL, NULL, NULL, pilot->s.origin, 10000, 0, MOD_SUICIDE); } #endif } - if ( pVeh->m_iNumPassengers ) - { + if (pVeh->m_iNumPassengers) { int i; - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i]) { #ifdef _GAME - gentity_t *rider = (gentity_t*)pVeh->m_ppPassengers[i]; + gentity_t *rider = (gentity_t *)pVeh->m_ppPassengers[i]; #endif - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_ppPassengers[i], qtrue ); + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_ppPassengers[i], qtrue); #ifdef _GAME - if ( pVeh->m_pVehicleInfo->killRiderOnDeath && rider ) - {//Kill them, too - //FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? + if (pVeh->m_pVehicleInfo->killRiderOnDeath && rider) { // Kill them, too + // FIXME: proper origin, MOD and attacker (for credit/death message)? Get from vehicle? G_MuteSound(rider->s.number, CHAN_VOICE); - G_Damage( rider, NULL, NULL, NULL, rider->s.origin, 10000, 0, MOD_SUICIDE );//FIXME: proper MOD? Get from vehicle? + G_Damage(rider, NULL, NULL, NULL, rider->s.origin, 10000, 0, MOD_SUICIDE); // FIXME: proper MOD? Get from vehicle? } #endif } @@ -954,106 +823,88 @@ qboolean EjectAll( Vehicle_t *pVeh ) pVeh->m_iNumPassengers = 0; } - if ( pVeh->m_pDroidUnit ) - { - G_EjectDroidUnit( pVeh, pVeh->m_pVehicleInfo->killRiderOnDeath ); + if (pVeh->m_pDroidUnit) { + G_EjectDroidUnit(pVeh, pVeh->m_pVehicleInfo->killRiderOnDeath); } return qtrue; } // Start a delay until the vehicle explodes. -static void StartDeathDelay( Vehicle_t *pVeh, int iDelayTimeOverride ) -{ +static void StartDeathDelay(Vehicle_t *pVeh, int iDelayTimeOverride) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if ( iDelayTimeOverride ) - { + if (iDelayTimeOverride) { pVeh->m_iDieTime = level.time + iDelayTimeOverride; - } - else - { + } else { pVeh->m_iDieTime = level.time + pVeh->m_pVehicleInfo->explosionDelay; } - if ( pVeh->m_pVehicleInfo->flammable ) - { - parent->client->ps.loopSound = parent->s.loopSound = G_SoundIndex( "sound/vehicles/common/fire_lp.wav" ); + if (pVeh->m_pVehicleInfo->flammable) { + parent->client->ps.loopSound = parent->s.loopSound = G_SoundIndex("sound/vehicles/common/fire_lp.wav"); } } // Decide whether to explode the vehicle or not. -static void DeathUpdate( Vehicle_t *pVeh ) -{ +static void DeathUpdate(Vehicle_t *pVeh) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if ( level.time >= pVeh->m_iDieTime ) - { + if (level.time >= pVeh->m_iDieTime) { // If the vehicle is not empty. - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { - - pVeh->m_pVehicleInfo->EjectAll( pVeh ); - if ( pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { //if we've still got people in us, just kill the bastards - if ( pVeh->m_pPilot ) - { - //FIXME: does this give proper credit to the enemy who shot you down? - G_Damage((gentity_t *)pVeh->m_pPilot, (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, - NULL, pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_SUICIDE ); + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { + + pVeh->m_pVehicleInfo->EjectAll(pVeh); + if (pVeh->m_pVehicleInfo->Inhabited(pVeh)) { // if we've still got people in us, just kill the bastards + if (pVeh->m_pPilot) { + // FIXME: does this give proper credit to the enemy who shot you down? + G_Damage((gentity_t *)pVeh->m_pPilot, (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, NULL, + pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } - if ( pVeh->m_iNumPassengers ) - { + if (pVeh->m_iNumPassengers) { int i; - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { - if ( pVeh->m_ppPassengers[i] ) - { - //FIXME: does this give proper credit to the enemy who shot you down? - G_Damage((gentity_t *)pVeh->m_ppPassengers[i], (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, - NULL, pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_SUICIDE ); + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { + if (pVeh->m_ppPassengers[i]) { + // FIXME: does this give proper credit to the enemy who shot you down? + G_Damage((gentity_t *)pVeh->m_ppPassengers[i], (gentity_t *)pVeh->m_pParentEntity, (gentity_t *)pVeh->m_pParentEntity, NULL, + pVeh->m_pParentEntity->playerState->origin, 999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } } } } - if ( !pVeh->m_pVehicleInfo->Inhabited( pVeh ) ) - { //explode now as long as we managed to kick everyone out - vec3_t lMins, lMaxs, bottom; - trace_t trace; - + if (!pVeh->m_pVehicleInfo->Inhabited(pVeh)) { // explode now as long as we managed to kick everyone out + vec3_t lMins, lMaxs, bottom; + trace_t trace; - if ( pVeh->m_pVehicleInfo->iExplodeFX ) - { + if (pVeh->m_pVehicleInfo->iExplodeFX) { vec3_t fxAng; VectorSet(fxAng, -90.0f, 0.0f, 0.0f); - G_PlayEffectID( pVeh->m_pVehicleInfo->iExplodeFX, parent->r.currentOrigin, fxAng ); - //trace down and place mark - VectorCopy( parent->r.currentOrigin, bottom ); + G_PlayEffectID(pVeh->m_pVehicleInfo->iExplodeFX, parent->r.currentOrigin, fxAng); + // trace down and place mark + VectorCopy(parent->r.currentOrigin, bottom); bottom[2] -= 80; - G_VehicleTrace( &trace, parent->r.currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID ); - if ( trace.fraction < 1.0f ) - { - VectorCopy( trace.endpos, bottom ); + G_VehicleTrace(&trace, parent->r.currentOrigin, vec3_origin, vec3_origin, bottom, parent->s.number, CONTENTS_SOLID); + if (trace.fraction < 1.0f) { + VectorCopy(trace.endpos, bottom); bottom[2] += 2; VectorSet(fxAng, -90.0f, 0.0f, 0.0f); - G_PlayEffectID( G_EffectIndex("ships/ship_explosion_mark"), trace.endpos, fxAng ); + G_PlayEffectID(G_EffectIndex("ships/ship_explosion_mark"), trace.endpos, fxAng); } } - parent->takedamage = qfalse;//so we don't recursively damage ourselves - if ( pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0 ) - { - VectorCopy( parent->r.mins, lMins ); - lMins[2] = -4;//to keep it off the ground a *little* - VectorCopy( parent->r.maxs, lMaxs ); - VectorCopy( parent->r.currentOrigin, bottom ); + parent->takedamage = qfalse; // so we don't recursively damage ourselves + if (pVeh->m_pVehicleInfo->explosionRadius > 0 && pVeh->m_pVehicleInfo->explosionDamage > 0) { + VectorCopy(parent->r.mins, lMins); + lMins[2] = -4; // to keep it off the ground a *little* + VectorCopy(parent->r.maxs, lMaxs); + VectorCopy(parent->r.currentOrigin, bottom); bottom[2] += parent->r.mins[2] - 32; - G_VehicleTrace( &trace, parent->r.currentOrigin, lMins, lMaxs, bottom, parent->s.number, CONTENTS_SOLID ); - G_RadiusDamage( trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, NULL, MOD_SUICIDE );//FIXME: extern damage and radius or base on fuel + G_VehicleTrace(&trace, parent->r.currentOrigin, lMins, lMaxs, bottom, parent->s.number, CONTENTS_SOLID); + G_RadiusDamage(trace.endpos, NULL, pVeh->m_pVehicleInfo->explosionDamage, pVeh->m_pVehicleInfo->explosionRadius, NULL, NULL, + MOD_SUICIDE); // FIXME: extern damage and radius or base on fuel } parent->think = G_FreeEntity; @@ -1063,66 +914,56 @@ static void DeathUpdate( Vehicle_t *pVeh ) } // Register all the assets used by this vehicle. -void RegisterAssets( Vehicle_t *pVeh ) -{ -} +void RegisterAssets(Vehicle_t *pVeh) {} -extern void ChangeWeapon( gentity_t *ent, int newWeapon ); +extern void ChangeWeapon(gentity_t *ent, int newWeapon); // Initialize the vehicle. -qboolean Initialize( Vehicle_t *pVeh ) -{ +qboolean Initialize(Vehicle_t *pVeh) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; int i = 0; - if ( !parent || !parent->client ) + if (!parent || !parent->client) return qfalse; parent->client->ps.m_iVehicleNum = 0; parent->s.m_iVehicleNum = 0; { - pVeh->m_iArmor = pVeh->m_pVehicleInfo->armor; - parent->client->pers.maxHealth = parent->client->ps.stats[STAT_MAX_HEALTH] = parent->NPC->stats.health = parent->health = parent->client->ps.stats[STAT_HEALTH] = pVeh->m_iArmor; - pVeh->m_iShields = pVeh->m_pVehicleInfo->shields; - G_VehUpdateShields( parent ); - parent->client->ps.stats[STAT_ARMOR] = pVeh->m_iShields; + pVeh->m_iArmor = pVeh->m_pVehicleInfo->armor; + parent->client->pers.maxHealth = parent->client->ps.stats[STAT_MAX_HEALTH] = parent->NPC->stats.health = parent->health = + parent->client->ps.stats[STAT_HEALTH] = pVeh->m_iArmor; + pVeh->m_iShields = pVeh->m_pVehicleInfo->shields; + G_VehUpdateShields(parent); + parent->client->ps.stats[STAT_ARMOR] = pVeh->m_iShields; } parent->mass = pVeh->m_pVehicleInfo->mass; - //initialize the ammo to max - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - { + // initialize the ammo to max + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { parent->client->ps.ammo[i] = pVeh->weaponStatus[i].ammo = pVeh->m_pVehicleInfo->weapon[i].ammoMax; } - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - pVeh->turretStatus[i].nextMuzzle = (pVeh->m_pVehicleInfo->turret[i].iMuzzle[i]-1); - parent->client->ps.ammo[MAX_VEHICLE_WEAPONS+i] = pVeh->turretStatus[i].ammo = pVeh->m_pVehicleInfo->turret[i].iAmmoMax; - if ( pVeh->m_pVehicleInfo->turret[i].bAI ) - {//they're going to be finding enemies, init this to NONE + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + pVeh->turretStatus[i].nextMuzzle = (pVeh->m_pVehicleInfo->turret[i].iMuzzle[i] - 1); + parent->client->ps.ammo[MAX_VEHICLE_WEAPONS + i] = pVeh->turretStatus[i].ammo = pVeh->m_pVehicleInfo->turret[i].iAmmoMax; + if (pVeh->m_pVehicleInfo->turret[i].bAI) { // they're going to be finding enemies, init this to NONE pVeh->turretStatus[i].enemyEntNum = ENTITYNUM_NONE; } } - //begin stopped...? + // begin stopped...? parent->client->ps.speed = 0; - VectorClear( pVeh->m_vOrientation ); + VectorClear(pVeh->m_vOrientation); pVeh->m_vOrientation[YAW] = parent->s.angles[YAW]; - if ( pVeh->m_pVehicleInfo->gravity && - pVeh->m_pVehicleInfo->gravity != g_gravity.value ) - {//not normal gravity - if ( parent->NPC ) - { + if (pVeh->m_pVehicleInfo->gravity && pVeh->m_pVehicleInfo->gravity != g_gravity.value) { // not normal gravity + if (parent->NPC) { parent->NPC->aiFlags |= NPCAI_CUSTOM_GRAVITY; } parent->client->ps.gravity = pVeh->m_pVehicleInfo->gravity; } - if ( pVeh->m_pVehicleInfo->maxPassengers > 0 ) - { + if (pVeh->m_pVehicleInfo->maxPassengers > 0) { // Allocate an array of entity pointers. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { pVeh->m_ppPassengers[i] = NULL; } } @@ -1135,152 +976,136 @@ qboolean Initialize( Vehicle_t *pVeh ) } else */ - //why?! -rww - { - pVeh->m_ulFlags = 0; - } + // why?! -rww + { pVeh->m_ulFlags = 0; } pVeh->m_fTimeModifier = 1.0f; pVeh->m_iBoarding = 0; pVeh->m_bWasBoarding = qfalse; pVeh->m_pOldPilot = NULL; VectorClear(pVeh->m_vBoardingVelocity); pVeh->m_pPilot = NULL; - memset( &pVeh->m_ucmd, 0, sizeof( usercmd_t ) ); + memset(&pVeh->m_ucmd, 0, sizeof(usercmd_t)); pVeh->m_iDieTime = 0; pVeh->m_EjectDir = VEH_EJECT_LEFT; - //pVeh->m_iDriverTag = -1; - //pVeh->m_iLeftExhaustTag = -1; - //pVeh->m_iRightExhaustTag = -1; - //pVeh->m_iGun1Tag = -1; - //pVeh->m_iGun1Bone = -1; - //pVeh->m_iLeftWingBone = -1; - //pVeh->m_iRightWingBone = -1; - memset( pVeh->m_iExhaustTag, -1, sizeof( int ) * MAX_VEHICLE_EXHAUSTS ); - memset( pVeh->m_iMuzzleTag, -1, sizeof( int ) * MAX_VEHICLE_MUZZLES ); + // pVeh->m_iDriverTag = -1; + // pVeh->m_iLeftExhaustTag = -1; + // pVeh->m_iRightExhaustTag = -1; + // pVeh->m_iGun1Tag = -1; + // pVeh->m_iGun1Bone = -1; + // pVeh->m_iLeftWingBone = -1; + // pVeh->m_iRightWingBone = -1; + memset(pVeh->m_iExhaustTag, -1, sizeof(int) * MAX_VEHICLE_EXHAUSTS); + memset(pVeh->m_iMuzzleTag, -1, sizeof(int) * MAX_VEHICLE_MUZZLES); // FIXME! Use external values read from the vehicle data file! pVeh->m_iDroidUnitTag = -1; - //initialize to blaster, just since it's a basic weapon and there's no lightsaber crap...? + // initialize to blaster, just since it's a basic weapon and there's no lightsaber crap...? parent->client->ps.weapon = WP_BLASTER; parent->client->ps.weaponstate = WEAPON_READY; - parent->client->ps.stats[STAT_WEAPONS] |= (1<client->ps.stats[STAT_WEAPONS] |= (1 << WP_BLASTER); - //Initialize to landed (wings closed, gears down) animation + // Initialize to landed (wings closed, gears down) animation { int iFlags = SETANIM_FLAG_NORMAL, iBlend = 300; pVeh->m_ulFlags |= VEH_GEARSOPEN; - BG_SetAnim(pVeh->m_pParentEntity->playerState, - bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, - SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend); + BG_SetAnim(pVeh->m_pParentEntity->playerState, bgAllAnims[pVeh->m_pParentEntity->localAnimIndex].anims, SETANIM_BOTH, BOTH_VS_IDLE, iFlags, iBlend); } return qtrue; } // Like a think or move command, this updates various vehicle properties. -void G_VehicleDamageBoxSizing(Vehicle_t *pVeh); //declared below -static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) -{ +void G_VehicleDamageBoxSizing(Vehicle_t *pVeh); // declared below +static qboolean Update(Vehicle_t *pVeh, const usercmd_t *pUmcd) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilotEnt; - //static float fMod = 1000.0f / 60.0f; + // static float fMod = 1000.0f / 60.0f; vec3_t vVehAngles; int i; - int prevSpeed; - int nextSpeed; - int curTime; + int prevSpeed; + int nextSpeed; + int curTime; int halfMaxSpeed; playerState_t *parentPS; qboolean linkHeld = qfalse; - - parentPS = pVeh->m_pParentEntity->playerState; + parentPS = pVeh->m_pParentEntity->playerState; #ifdef _GAME curTime = level.time; #elif _CGAME - //FIXME: pass in ucmd? Not sure if this is reliable... + // FIXME: pass in ucmd? Not sure if this is reliable... curTime = pm->cmd.serverTime; #endif - //increment the ammo for all rechargeable weapons - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapon[i].ID > VEH_WEAPON_BASE//have a weapon in this slot - && pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS//its ammo is rechargable - && pVeh->weaponStatus[i].ammo < pVeh->m_pVehicleInfo->weapon[i].ammoMax//its ammo is below max - && pUmcd->serverTime-pVeh->weaponStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS )//enough time has passed - {//add 1 to the ammo + // increment the ammo for all rechargeable weapons + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { + if (pVeh->m_pVehicleInfo->weapon[i].ID > VEH_WEAPON_BASE // have a weapon in this slot + && pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS // its ammo is rechargable + && pVeh->weaponStatus[i].ammo < pVeh->m_pVehicleInfo->weapon[i].ammoMax // its ammo is below max + && pUmcd->serverTime - pVeh->weaponStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->weapon[i].ammoRechargeMS) // enough time has passed + { // add 1 to the ammo pVeh->weaponStatus[i].lastAmmoInc = pUmcd->serverTime; pVeh->weaponStatus[i].ammo++; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( parent && parent->client ) - { + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo + // array + if (parent && parent->client) { parent->client->ps.ammo[i] = pVeh->weaponStatus[i].ammo; } } } - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - { - if ( pVeh->m_pVehicleInfo->turret[i].iWeapon > VEH_WEAPON_BASE//have a weapon in this slot - && pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS//its ammo is rechargable - && pVeh->turretStatus[i].ammo < pVeh->m_pVehicleInfo->turret[i].iAmmoMax//its ammo is below max - && pUmcd->serverTime-pVeh->turretStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS )//enough time has passed - {//add 1 to the ammo + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { + if (pVeh->m_pVehicleInfo->turret[i].iWeapon > VEH_WEAPON_BASE // have a weapon in this slot + && pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS // its ammo is rechargable + && pVeh->turretStatus[i].ammo < pVeh->m_pVehicleInfo->turret[i].iAmmoMax // its ammo is below max + && pUmcd->serverTime - pVeh->turretStatus[i].lastAmmoInc >= pVeh->m_pVehicleInfo->turret[i].iAmmoRechargeMS) // enough time has passed + { // add 1 to the ammo pVeh->turretStatus[i].lastAmmoInc = pUmcd->serverTime; pVeh->turretStatus[i].ammo++; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( parent && parent->client ) - { - parent->client->ps.ammo[MAX_VEHICLE_WEAPONS+i] = pVeh->turretStatus[i].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo + // array + if (parent && parent->client) { + parent->client->ps.ammo[MAX_VEHICLE_WEAPONS + i] = pVeh->turretStatus[i].ammo; } } } - //increment shields for rechargable shields - if ( pVeh->m_pVehicleInfo->shieldRechargeMS - && parentPS->stats[STAT_ARMOR] > 0 //still have some shields left - && parentPS->stats[STAT_ARMOR] < pVeh->m_pVehicleInfo->shields//its below max - && pUmcd->serverTime-pVeh->lastShieldInc >= pVeh->m_pVehicleInfo->shieldRechargeMS )//enough time has passed + // increment shields for rechargable shields + if (pVeh->m_pVehicleInfo->shieldRechargeMS && parentPS->stats[STAT_ARMOR] > 0 // still have some shields left + && parentPS->stats[STAT_ARMOR] < pVeh->m_pVehicleInfo->shields // its below max + && pUmcd->serverTime - pVeh->lastShieldInc >= pVeh->m_pVehicleInfo->shieldRechargeMS) // enough time has passed { parentPS->stats[STAT_ARMOR]++; - if ( parentPS->stats[STAT_ARMOR] > pVeh->m_pVehicleInfo->shields ) - { + if (parentPS->stats[STAT_ARMOR] > pVeh->m_pVehicleInfo->shields) { parentPS->stats[STAT_ARMOR] = pVeh->m_pVehicleInfo->shields; } pVeh->m_iShields = parentPS->stats[STAT_ARMOR]; - G_VehUpdateShields( parent ); + G_VehUpdateShields(parent); } - if (parent && parent->r.ownerNum != parent->s.owner) - { + if (parent && parent->r.ownerNum != parent->s.owner) { parent->s.owner = parent->r.ownerNum; } - //keep the PS value in sync. set it up here in case we return below at some point. - if (pVeh->m_iBoarding) - { + // keep the PS value in sync. set it up here in case we return below at some point. + if (pVeh->m_iBoarding) { parent->client->ps.vehBoarding = qtrue; - } - else - { + } else { parent->client->ps.vehBoarding = qfalse; } // See whether this vehicle should be dieing or dead. - if ( pVeh->m_iDieTime != 0 ) - {//NOTE!!!: This HAS to be consistent with cgame!!! + if (pVeh->m_iDieTime != 0) { // NOTE!!!: This HAS to be consistent with cgame!!! // Keep track of the old orientation. - VectorCopy( pVeh->m_vOrientation, pVeh->m_vPrevOrientation ); + VectorCopy(pVeh->m_vOrientation, pVeh->m_vPrevOrientation); // Process the orient commands. - pVeh->m_pVehicleInfo->ProcessOrientCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessOrientCommands(pVeh); // Need to copy orientation to our entity's viewangles so that it renders at the proper angle and currentAngles is correct. - SetClientViewAngle( parent, pVeh->m_vOrientation ); - if ( pVeh->m_pPilot ) - { - SetClientViewAngle( (gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation ); + SetClientViewAngle(parent, pVeh->m_vOrientation); + if (pVeh->m_pPilot) { + SetClientViewAngle((gentity_t *)pVeh->m_pPilot, pVeh->m_vOrientation); } /* for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) @@ -1293,71 +1118,51 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) */ // Process the move commands. - pVeh->m_pVehicleInfo->ProcessMoveCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessMoveCommands(pVeh); // Setup the move direction. - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { - AngleVectors( pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL ); - } - else - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + AngleVectors(pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL); + } else { VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); } - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); return qfalse; } // Vehicle dead! - else if ( parent->health <= 0 ) - { + else if (parent->health <= 0) { // Instant kill. - if (pVeh->m_pVehicleInfo->type == VH_FIGHTER && - pVeh->m_iLastImpactDmg > 500) - { //explode instantly in inferno-y death - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, -1/* -1 causes instant death */); - } - else - { - pVeh->m_pVehicleInfo->StartDeathDelay( pVeh, 0 ); + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER && pVeh->m_iLastImpactDmg > 500) { // explode instantly in inferno-y death + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, -1 /* -1 causes instant death */); + } else { + pVeh->m_pVehicleInfo->StartDeathDelay(pVeh, 0); } - pVeh->m_pVehicleInfo->DeathUpdate( pVeh ); + pVeh->m_pVehicleInfo->DeathUpdate(pVeh); return qfalse; } #ifdef _GAME - if (parent->spawnflags & 1) - { - if (pVeh->m_pPilot || !pVeh->m_bHasHadPilot) - { - if (pVeh->m_pPilot && !pVeh->m_bHasHadPilot) - { + if (parent->spawnflags & 1) { + if (pVeh->m_pPilot || !pVeh->m_bHasHadPilot) { + if (pVeh->m_pPilot && !pVeh->m_bHasHadPilot) { pVeh->m_bHasHadPilot = qtrue; pVeh->m_iPilotLastIndex = pVeh->m_pPilot->s.number; } pVeh->m_iPilotTime = level.time + parent->damage; - } - else if (pVeh->m_iPilotTime) - { //die + } else if (pVeh->m_iPilotTime) { // die gentity_t *oldPilot = &g_entities[pVeh->m_iPilotLastIndex]; - if (!oldPilot->inuse || !oldPilot->client || - oldPilot->client->pers.connected != CON_CONNECTED) - { //no longer in the game? + if (!oldPilot->inuse || !oldPilot->client || oldPilot->client->pers.connected != CON_CONNECTED) { // no longer in the game? G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); - } - else - { + } else { vec3_t v; VectorSubtract(parent->client->ps.origin, oldPilot->client->ps.origin, v); - if (VectorLength(v) < parent->speed) - { //they are still within the minimum distance to their vehicle + if (VectorLength(v) < parent->speed) { // they are still within the minimum distance to their vehicle pVeh->m_iPilotTime = level.time + parent->damage; - } - else if (pVeh->m_iPilotTime < level.time) - { //dying time + } else if (pVeh->m_iPilotTime < level.time) { // dying time G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 99999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } @@ -1365,37 +1170,28 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) } #endif - if (pVeh->m_iBoarding != 0) - { + if (pVeh->m_iBoarding != 0) { pilotEnt = (gentity_t *)pVeh->m_pPilot; - if (pilotEnt) - { - if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || - pilotEnt->client->pers.connected != CON_CONNECTED) - { - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + if (pilotEnt) { + if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || pilotEnt->client->pers.connected != CON_CONNECTED) { + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); return qfalse; } } } // If we're not done mounting, can't do anything. - if ( pVeh->m_iBoarding != 0 ) - { - if (!pVeh->m_bWasBoarding) - { + if (pVeh->m_iBoarding != 0) { + if (!pVeh->m_bWasBoarding) { VectorCopy(parentPS->velocity, pVeh->m_vBoardingVelocity); pVeh->m_bWasBoarding = qtrue; } // See if we're done boarding. - if ( pVeh->m_iBoarding > -1 && pVeh->m_iBoarding <= level.time ) - { + if (pVeh->m_iBoarding > -1 && pVeh->m_iBoarding <= level.time) { pVeh->m_bWasBoarding = qfalse; pVeh->m_iBoarding = 0; - } - else - { + } else { goto maintainSelfDuringBoarding; } } @@ -1403,41 +1199,34 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) parent = (gentity_t *)pVeh->m_pParentEntity; // Validate vehicle. - if ( !parent || !parent->client || parent->health <= 0 ) + if (!parent || !parent->client || parent->health <= 0) return qfalse; // See if any of the riders are dead and if so kick em off. - if ( pVeh->m_pPilot ) - { + if (pVeh->m_pPilot) { pilotEnt = (gentity_t *)pVeh->m_pPilot; - if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || - pilotEnt->client->pers.connected != CON_CONNECTED) - { - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_pPilot, qtrue ); + if (!pilotEnt->inuse || !pilotEnt->client || pilotEnt->health <= 0 || pilotEnt->client->pers.connected != CON_CONNECTED) { + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_pPilot, qtrue); } } // If we're not empty... - if ( pVeh->m_iNumPassengers > 0 ) - { + if (pVeh->m_iNumPassengers > 0) { gentity_t *psngr; // See if any of these suckers are dead. - for ( i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++ ) - { + for (i = 0; i < pVeh->m_pVehicleInfo->maxPassengers; i++) { psngr = (gentity_t *)pVeh->m_ppPassengers[i]; - if ( psngr && - (!psngr->inuse || !psngr->client || psngr->health <= 0 || psngr->client->pers.connected != CON_CONNECTED) ) - { - pVeh->m_pVehicleInfo->Eject( pVeh, pVeh->m_ppPassengers[i], qtrue ); + if (psngr && (!psngr->inuse || !psngr->client || psngr->health <= 0 || psngr->client->pers.connected != CON_CONNECTED)) { + pVeh->m_pVehicleInfo->Eject(pVeh, pVeh->m_ppPassengers[i], qtrue); pVeh->m_iNumPassengers--; } } } // Copy over the commands for local storage. - memcpy( &parent->client->pers.cmd, &pVeh->m_ucmd, sizeof( usercmd_t ) ); - pVeh->m_ucmd.buttons &= ~(BUTTON_TALK);//|BUTTON_GESTURE); //don't want some of these buttons + memcpy(&parent->client->pers.cmd, &pVeh->m_ucmd, sizeof(usercmd_t)); + pVeh->m_ucmd.buttons &= ~(BUTTON_TALK); //|BUTTON_GESTURE); //don't want some of these buttons /* // Update time modifier. @@ -1455,62 +1244,49 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) pVeh->m_fTimeModifier = pVeh->m_fTimeModifier / fMod; */ - //check for weapon linking/unlinking command - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - if ( pVeh->m_pVehicleInfo->weapon[i].linkable == 2 ) - {//always linked - //FIXME: just set this once, on Initialize...? - if ( !pVeh->weaponStatus[i].linked ) - { + // check for weapon linking/unlinking command + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + if (pVeh->m_pVehicleInfo->weapon[i].linkable == 2) { // always linked + // FIXME: just set this once, on Initialize...? + if (!pVeh->weaponStatus[i].linked) { pVeh->weaponStatus[i].linked = qtrue; } - } - else if ( (pVeh->m_ucmd.buttons&BUTTON_USE_HOLDABLE) ) - {//pilot pressed the "weapon link" toggle button - if ( !pVeh->linkWeaponToggleHeld )//so we don't hold it down and toggle it back and forth - {//okay to toggle - if ( pVeh->m_pVehicleInfo->weapon[i].linkable == 1 ) - {//link-toggleable + } else if ((pVeh->m_ucmd.buttons & BUTTON_USE_HOLDABLE)) { // pilot pressed the "weapon link" toggle button + if (!pVeh->linkWeaponToggleHeld) // so we don't hold it down and toggle it back and forth + { // okay to toggle + if (pVeh->m_pVehicleInfo->weapon[i].linkable == 1) { // link-toggleable pVeh->weaponStatus[i].linked = !pVeh->weaponStatus[i].linked; } } linkHeld = qtrue; } } - if ( linkHeld ) - { - //so we don't hold it down and toggle it back and forth + if (linkHeld) { + // so we don't hold it down and toggle it back and forth pVeh->linkWeaponToggleHeld = qtrue; - } - else - { - //so we don't hold it down and toggle it back and forth + } else { + // so we don't hold it down and toggle it back and forth pVeh->linkWeaponToggleHeld = qfalse; } - //now pass it over the network so cgame knows about it - //NOTE: SP can just cheat and check directly + // now pass it over the network so cgame knows about it + // NOTE: SP can just cheat and check directly parentPS->vehWeaponsLinked = qfalse; - for ( i = 0; i < MAX_VEHICLE_WEAPONS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - if ( pVeh->weaponStatus[i].linked ) - { + for (i = 0; i < MAX_VEHICLE_WEAPONS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + if (pVeh->weaponStatus[i].linked) { parentPS->vehWeaponsLinked = qtrue; } } #ifdef _GAME - for ( i = 0; i < MAX_VEHICLE_TURRETS; i++ ) - {//HMM... can't get a seperate command for each weapon, so do them all...? - VEH_TurretThink( pVeh, parent, i ); + for (i = 0; i < MAX_VEHICLE_TURRETS; i++) { // HMM... can't get a seperate command for each weapon, so do them all...? + VEH_TurretThink(pVeh, parent, i); } #endif maintainSelfDuringBoarding: - if (pVeh->m_pPilot && pVeh->m_pPilot->playerState && pVeh->m_iBoarding != 0) - { - VectorCopy(pVeh->m_vOrientation, pVeh->m_pPilot->playerState->viewangles); + if (pVeh->m_pPilot && pVeh->m_pPilot->playerState && pVeh->m_iBoarding != 0) { + VectorCopy(pVeh->m_vOrientation, pVeh->m_pPilot->playerState->viewangles); pVeh->m_ucmd.buttons = 0; pVeh->m_ucmd.forwardmove = 0; pVeh->m_ucmd.rightmove = 0; @@ -1518,21 +1294,19 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) } // Keep track of the old orientation. - VectorCopy( pVeh->m_vOrientation, pVeh->m_vPrevOrientation ); + VectorCopy(pVeh->m_vOrientation, pVeh->m_vPrevOrientation); // Process the orient commands. - pVeh->m_pVehicleInfo->ProcessOrientCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessOrientCommands(pVeh); // Need to copy orientation to our entity's viewangles so that it renders at the proper angle and currentAngles is correct. - SetClientViewAngle( parent, pVeh->m_vOrientation ); - if ( pVeh->m_pPilot ) - { - if ( !BG_UnrestrainedPitchRoll( pVeh->m_pPilot->playerState, pVeh ) ) - { + SetClientViewAngle(parent, pVeh->m_vOrientation); + if (pVeh->m_pPilot) { + if (!BG_UnrestrainedPitchRoll(pVeh->m_pPilot->playerState, pVeh)) { vec3_t newVAngle; newVAngle[PITCH] = pVeh->m_pPilot->playerState->viewangles[PITCH]; newVAngle[YAW] = pVeh->m_pPilot->playerState->viewangles[YAW]; newVAngle[ROLL] = pVeh->m_vOrientation[ROLL]; - SetClientViewAngle( (gentity_t *)pVeh->m_pPilot, newVAngle ); + SetClientViewAngle((gentity_t *)pVeh->m_pPilot, newVAngle); } } /* @@ -1547,168 +1321,140 @@ static qboolean Update( Vehicle_t *pVeh, const usercmd_t *pUmcd ) // Process the move commands. prevSpeed = parentPS->speed; - pVeh->m_pVehicleInfo->ProcessMoveCommands( pVeh ); + pVeh->m_pVehicleInfo->ProcessMoveCommands(pVeh); nextSpeed = parentPS->speed; - halfMaxSpeed = pVeh->m_pVehicleInfo->speedMax*0.5f; - - -// Shifting Sounds -//===================================================================== - if (pVeh->m_iTurboTimem_iSoundDebounceTimerprevSpeed && nextSpeed>halfMaxSpeed && prevSpeedhalfMaxSpeed && !Q_irand(0,1000))) - ) - { - int shiftSound = Q_irand(1,4); - switch (shiftSound) - { - case 1: shiftSound=pVeh->m_pVehicleInfo->soundShift1; break; - case 2: shiftSound=pVeh->m_pVehicleInfo->soundShift2; break; - case 3: shiftSound=pVeh->m_pVehicleInfo->soundShift3; break; - case 4: shiftSound=pVeh->m_pVehicleInfo->soundShift4; break; + halfMaxSpeed = pVeh->m_pVehicleInfo->speedMax * 0.5f; + + // Shifting Sounds + //===================================================================== + if (pVeh->m_iTurboTime < curTime && pVeh->m_iSoundDebounceTimer < curTime && + ((nextSpeed > prevSpeed && nextSpeed > halfMaxSpeed && prevSpeed < halfMaxSpeed) || (nextSpeed > halfMaxSpeed && !Q_irand(0, 1000)))) { + int shiftSound = Q_irand(1, 4); + switch (shiftSound) { + case 1: + shiftSound = pVeh->m_pVehicleInfo->soundShift1; + break; + case 2: + shiftSound = pVeh->m_pVehicleInfo->soundShift2; + break; + case 3: + shiftSound = pVeh->m_pVehicleInfo->soundShift3; + break; + case 4: + shiftSound = pVeh->m_pVehicleInfo->soundShift4; + break; } - if (shiftSound) - { + if (shiftSound) { pVeh->m_iSoundDebounceTimer = curTime + Q_irand(1000, 4000); // TODO: MP Shift Sound Playback } } -//===================================================================== - + //===================================================================== // Setup the move direction. - if ( pVeh->m_pVehicleInfo->type == VH_FIGHTER ) - { - AngleVectors( pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL ); - } - else - { + if (pVeh->m_pVehicleInfo->type == VH_FIGHTER) { + AngleVectors(pVeh->m_vOrientation, parent->client->ps.moveDir, NULL, NULL); + } else { VectorSet(vVehAngles, 0, pVeh->m_vOrientation[YAW], 0); - AngleVectors( vVehAngles, parent->client->ps.moveDir, NULL, NULL ); + AngleVectors(vVehAngles, parent->client->ps.moveDir, NULL, NULL); } - if (pVeh->m_pVehicleInfo->surfDestruction) - { - if (pVeh->m_iRemovedSurfaces) - { + if (pVeh->m_pVehicleInfo->surfDestruction) { + if (pVeh->m_iRemovedSurfaces) { gentity_t *killer = parent; - float dmg; + float dmg; G_VehicleDamageBoxSizing(pVeh); - //damage him constantly if any chunks are currently taken off - if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && - parent->client->ps.otherKillerTime > level.time) - { + // damage him constantly if any chunks are currently taken off + if (parent->client->ps.otherKiller < ENTITYNUM_WORLD && parent->client->ps.otherKillerTime > level.time) { gentity_t *potentialKiller = &g_entities[parent->client->ps.otherKiller]; - if (potentialKiller->inuse && potentialKiller->client) - { //he's valid I guess + if (potentialKiller->inuse && potentialKiller->client) { // he's valid I guess killer = potentialKiller; } } - //FIXME: aside from bypassing shields, maybe set m_iShields to 0, too... ? + // FIXME: aside from bypassing shields, maybe set m_iShields to 0, too... ? // 3 seconds max on death. dmg = (float)parent->client->ps.stats[STAT_MAX_HEALTH] * pVeh->m_fTimeModifier / 180.0f; - G_Damage(parent, killer, killer, NULL, parent->client->ps.origin, dmg, DAMAGE_NO_SELF_PROTECTION|DAMAGE_NO_HIT_LOC|DAMAGE_NO_PROTECTION|DAMAGE_NO_ARMOR, MOD_SUICIDE); + G_Damage(parent, killer, killer, NULL, parent->client->ps.origin, dmg, + DAMAGE_NO_SELF_PROTECTION | DAMAGE_NO_HIT_LOC | DAMAGE_NO_PROTECTION | DAMAGE_NO_ARMOR, MOD_SUICIDE); } - //make sure playerstate value stays in sync + // make sure playerstate value stays in sync parent->client->ps.vehSurfaces = pVeh->m_iRemovedSurfaces; } - //keep the PS value in sync - if (pVeh->m_iBoarding) - { + // keep the PS value in sync + if (pVeh->m_iBoarding) { parent->client->ps.vehBoarding = qtrue; - } - else - { + } else { parent->client->ps.vehBoarding = qfalse; } return qtrue; } - // Update the properties of a Rider (that may reflect what happens to the vehicle). -static qboolean UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd ) -{ +static qboolean UpdateRider(Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUmcd) { gentity_t *parent; gentity_t *rider; - if ( pVeh->m_iBoarding != 0 && pVeh->m_iDieTime==0) + if (pVeh->m_iBoarding != 0 && pVeh->m_iDieTime == 0) return qtrue; parent = (gentity_t *)pVeh->m_pParentEntity; rider = (gentity_t *)pRider; - //MG FIXME !! Single player needs update! - if ( rider && rider->client - && parent && parent->client ) - {//so they know who we're locking onto with our rockets, if anyone + // MG FIXME !! Single player needs update! + if (rider && rider->client && parent && parent->client) { // so they know who we're locking onto with our rockets, if anyone rider->client->ps.rocketLockIndex = parent->client->ps.rocketLockIndex; rider->client->ps.rocketLockTime = parent->client->ps.rocketLockTime; rider->client->ps.rocketTargetTime = parent->client->ps.rocketTargetTime; } // Regular exit. - if ( pUmcd->buttons & BUTTON_USE && pVeh->m_pVehicleInfo->type!=VH_SPEEDER) - { - if ( pVeh->m_pVehicleInfo->type == VH_WALKER ) - {//just get the fuck out + if (pUmcd->buttons & BUTTON_USE && pVeh->m_pVehicleInfo->type != VH_SPEEDER) { + if (pVeh->m_pVehicleInfo->type == VH_WALKER) { // just get the fuck out pVeh->m_EjectDir = VEH_EJECT_REAR; - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) return qfalse; - } - else if ( !(pVeh->m_ulFlags & VEH_FLYING)) - { + } else if (!(pVeh->m_ulFlags & VEH_FLYING)) { // If going too fast, roll off. - if ((parent->client->ps.speed<=600) && pUmcd->rightmove!=0) - { - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if ((parent->client->ps.speed <= 600) && pUmcd->rightmove != 0) { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { animNumber_t Anim; int iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, iBlend = 300; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_ROLL_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else - { + } else { Anim = BOTH_ROLL_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; } - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, iFlags, iBlend ); + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, iFlags, iBlend); - //PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - rider->client->ps.weaponTime = rider->client->ps.torsoTimer - 200;//just to make sure it's cleared when roll is done - G_AddEvent( rider, EV_ROLL, 0 ); + // PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); + rider->client->ps.weaponTime = rider->client->ps.torsoTimer - 200; // just to make sure it's cleared when roll is done + G_AddEvent(rider, EV_ROLL, 0); return qfalse; } - } - else - { + } else { // FIXME: Check trace to see if we should start playing the animation. animNumber_t Anim; int iFlags = SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, iBlend = 500; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_VS_DISMOUNT_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else - { + } else { Anim = BOTH_VS_DISMOUNT_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; } - if ( pVeh->m_iBoarding <= 1 ) - { + if (pVeh->m_iBoarding <= 1) { int iAnimLen; // NOTE: I know I shouldn't reuse pVeh->m_iBoarding so many times for so many different // purposes, but it's not used anywhere else right here so why waste memory??? - iAnimLen = BG_AnimLength( rider->localAnimIndex, Anim ); + iAnimLen = BG_AnimLength(rider->localAnimIndex, Anim); pVeh->m_iBoarding = level.time + iAnimLen; // Weird huh? Well I wanted to reuse flags and this should never be set in an // entity, so what the heck. @@ -1718,138 +1464,114 @@ static qboolean UpdateRider( Vehicle_t *pVeh, bgEntity_t *pRider, usercmd_t *pUm rider->client->ps.weaponTime = iAnimLen; } - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, iFlags, iBlend ); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, iFlags, iBlend); } } // Flying, so just fall off. - else - { + else { pVeh->m_EjectDir = VEH_EJECT_LEFT; - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) return qfalse; } } // Getting off animation complete (if we had one going)? - if ( pVeh->m_iBoarding < level.time && (rider->flags & FL_VEH_BOARDING) ) - { + if (pVeh->m_iBoarding < level.time && (rider->flags & FL_VEH_BOARDING)) { rider->flags &= ~FL_VEH_BOARDING; // Eject this guy now. - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { return qfalse; } } - if ( pVeh->m_pVehicleInfo->type != VH_FIGHTER - && pVeh->m_pVehicleInfo->type != VH_WALKER ) - { + if (pVeh->m_pVehicleInfo->type != VH_FIGHTER && pVeh->m_pVehicleInfo->type != VH_WALKER) { // Jump off. - if ( pUmcd->upmove > 0 ) - { + if (pUmcd->upmove > 0) { - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { // Allow them to force jump off. - VectorScale( parent->client->ps.velocity, 0.5f, rider->client->ps.velocity ); + VectorScale(parent->client->ps.velocity, 0.5f, rider->client->ps.velocity); rider->client->ps.velocity[2] += JUMP_VELOCITY; rider->client->ps.fd.forceJumpZStart = rider->client->ps.origin[2]; - if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)rider, TID_CHAN_VOICE)) - { - G_AddEvent( rider, EV_JUMP, 0 ); + if (!trap->ICARUS_TaskIDPending((sharedEntity_t *)rider, TID_CHAN_VOICE)) { + G_AddEvent(rider, EV_JUMP, 0); } - Vehicle_SetAnim( rider, SETANIM_BOTH, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 300 ); + Vehicle_SetAnim(rider, SETANIM_BOTH, BOTH_JUMP1, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 300); return qfalse; } } // Roll off. - if ( pUmcd->upmove < 0 ) - { + if (pUmcd->upmove < 0) { animNumber_t Anim = BOTH_ROLL_B; pVeh->m_EjectDir = VEH_EJECT_REAR; - if ( pUmcd->rightmove > 0 ) - { + if (pUmcd->rightmove > 0) { Anim = BOTH_ROLL_R; pVeh->m_EjectDir = VEH_EJECT_RIGHT; - } - else if ( pUmcd->rightmove < 0 ) - { + } else if (pUmcd->rightmove < 0) { Anim = BOTH_ROLL_L; pVeh->m_EjectDir = VEH_EJECT_LEFT; - } - else if ( pUmcd->forwardmove < 0 ) - { + } else if (pUmcd->forwardmove < 0) { Anim = BOTH_ROLL_B; pVeh->m_EjectDir = VEH_EJECT_REAR; - } - else if ( pUmcd->forwardmove > 0 ) - { + } else if (pUmcd->forwardmove > 0) { Anim = BOTH_ROLL_F; pVeh->m_EjectDir = VEH_EJECT_FRONT; } - if ( pVeh->m_pVehicleInfo->Eject( pVeh, pRider, qfalse ) ) - { - if ( !(pVeh->m_ulFlags & VEH_FLYING) ) - { - VectorScale( parent->client->ps.velocity, 0.25f, rider->client->ps.velocity ); - Vehicle_SetAnim( rider, SETANIM_BOTH, Anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 300 ); - //PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); - rider->client->ps.weaponTime = rider->client->ps.torsoTimer - 200;//just to make sure it's cleared when roll is done - G_AddEvent( rider, EV_ROLL, 0 ); + if (pVeh->m_pVehicleInfo->Eject(pVeh, pRider, qfalse)) { + if (!(pVeh->m_ulFlags & VEH_FLYING)) { + VectorScale(parent->client->ps.velocity, 0.25f, rider->client->ps.velocity); + Vehicle_SetAnim(rider, SETANIM_BOTH, Anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD | SETANIM_FLAG_HOLDLESS, 300); + // PM_SetAnim(pm,SETANIM_BOTH,anim,SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD|SETANIM_FLAG_HOLDLESS); + rider->client->ps.weaponTime = rider->client->ps.torsoTimer - 200; // just to make sure it's cleared when roll is done + G_AddEvent(rider, EV_ROLL, 0); } return qfalse; } - } } return qtrue; } -//generic vehicle function we care about over there -extern void AttachRidersGeneric( Vehicle_t *pVeh ); +// generic vehicle function we care about over there +extern void AttachRidersGeneric(Vehicle_t *pVeh); // Attachs all the riders of this vehicle to their appropriate tag (*driver, *pass1, *pass2, whatever...). -static void AttachRiders( Vehicle_t *pVeh ) -{ +static void AttachRiders(Vehicle_t *pVeh) { int i = 0; AttachRidersGeneric(pVeh); - if (pVeh->m_pPilot) - { + if (pVeh->m_pPilot) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilot = (gentity_t *)pVeh->m_pPilot; pilot->waypoint = parent->waypoint; // take the veh's waypoint as your own - //assuming we updated him relative to the bolt in AttachRidersGeneric - G_SetOrigin( pilot, pilot->client->ps.origin ); - trap->LinkEntity( (sharedEntity_t *)pilot ); + // assuming we updated him relative to the bolt in AttachRidersGeneric + G_SetOrigin(pilot, pilot->client->ps.origin); + trap->LinkEntity((sharedEntity_t *)pilot); } - if (pVeh->m_pOldPilot) - { + if (pVeh->m_pOldPilot) { gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *oldpilot = (gentity_t *)pVeh->m_pOldPilot; oldpilot->waypoint = parent->waypoint; // take the veh's waypoint as your own - //assuming we updated him relative to the bolt in AttachRidersGeneric - G_SetOrigin( oldpilot, oldpilot->client->ps.origin ); - trap->LinkEntity( (sharedEntity_t *)oldpilot ); + // assuming we updated him relative to the bolt in AttachRidersGeneric + G_SetOrigin(oldpilot, oldpilot->client->ps.origin); + trap->LinkEntity((sharedEntity_t *)oldpilot); } - //attach passengers - while (i < pVeh->m_iNumPassengers) - { - if (pVeh->m_ppPassengers[i]) - { + // attach passengers + while (i < pVeh->m_iNumPassengers) { + if (pVeh->m_ppPassengers[i]) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles; + vec3_t yawOnlyAngles; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *pilot = (gentity_t *)pVeh->m_ppPassengers[i]; int crotchBolt; @@ -1862,50 +1584,44 @@ static void AttachRiders( Vehicle_t *pVeh ) VectorSet(yawOnlyAngles, 0, parent->client->ps.viewangles[YAW], 0); // Get the driver tag. - trap->G2API_GetBoltMatrix( parent->ghoul2, 0, crotchBolt, &boltMatrix, - yawOnlyAngles, parent->client->ps.origin, - level.time, NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, pilot->client->ps.origin ); + trap->G2API_GetBoltMatrix(parent->ghoul2, 0, crotchBolt, &boltMatrix, yawOnlyAngles, parent->client->ps.origin, level.time, NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pilot->client->ps.origin); - G_SetOrigin( pilot, pilot->client->ps.origin ); - trap->LinkEntity( (sharedEntity_t *)pilot ); + G_SetOrigin(pilot, pilot->client->ps.origin); + trap->LinkEntity((sharedEntity_t *)pilot); } i++; } - //attach droid - if (pVeh->m_pDroidUnit - && pVeh->m_iDroidUnitTag != -1) - { + // attach droid + if (pVeh->m_pDroidUnit && pVeh->m_iDroidUnitTag != -1) { mdxaBone_t boltMatrix; - vec3_t yawOnlyAngles, fwd; + vec3_t yawOnlyAngles, fwd; gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; gentity_t *droid = (gentity_t *)pVeh->m_pDroidUnit; assert(parent->ghoul2); assert(parent->client); - //assert(droid->client); + // assert(droid->client); - if ( droid->client ) - { + if (droid->client) { VectorSet(yawOnlyAngles, 0, parent->client->ps.viewangles[YAW], 0); // Get the droid tag. - trap->G2API_GetBoltMatrix( parent->ghoul2, 0, pVeh->m_iDroidUnitTag, &boltMatrix, - yawOnlyAngles, parent->r.currentOrigin, - level.time, NULL, parent->modelScale ); - BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, droid->client->ps.origin ); - BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, fwd ); - vectoangles( fwd, droid->client->ps.viewangles ); - - G_SetOrigin( droid, droid->client->ps.origin ); - G_SetAngles( droid, droid->client->ps.viewangles); - SetClientViewAngle( droid, droid->client->ps.viewangles ); - trap->LinkEntity( (sharedEntity_t *)droid ); - - if ( droid->NPC ) - { - NPC_SetAnim( droid, SETANIM_BOTH, BOTH_STAND2, (SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD) ); + trap->G2API_GetBoltMatrix(parent->ghoul2, 0, pVeh->m_iDroidUnitTag, &boltMatrix, yawOnlyAngles, parent->r.currentOrigin, level.time, NULL, + parent->modelScale); + BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, droid->client->ps.origin); + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, fwd); + vectoangles(fwd, droid->client->ps.viewangles); + + G_SetOrigin(droid, droid->client->ps.origin); + G_SetAngles(droid, droid->client->ps.viewangles); + SetClientViewAngle(droid, droid->client->ps.viewangles); + trap->LinkEntity((sharedEntity_t *)droid); + + if (droid->NPC) { + NPC_SetAnim(droid, SETANIM_BOTH, BOTH_STAND2, (SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD)); droid->client->ps.legsTimer = 500; droid->client->ps.torsoTimer = 500; } @@ -1914,11 +1630,10 @@ static void AttachRiders( Vehicle_t *pVeh ) } // Make someone invisible and un-collidable. -static void Ghost( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +static void Ghost(Vehicle_t *pVeh, bgEntity_t *pEnt) { gentity_t *ent; - if ( !pEnt ) + if (!pEnt) return; ent = (gentity_t *)pEnt; @@ -1927,19 +1642,17 @@ static void Ghost( Vehicle_t *pVeh, bgEntity_t *pEnt ) ent->r.svFlags |= SVF_NOCLIENT; ent->s.eFlags |= EF_NODRAW; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.eFlags |= EF_NODRAW; } ent->r.contents = 0; } // Make someone visible and collidable. -static void UnGhost( Vehicle_t *pVeh, bgEntity_t *pEnt ) -{ +static void UnGhost(Vehicle_t *pVeh, bgEntity_t *pEnt) { gentity_t *ent; - if ( !pEnt ) + if (!pEnt) return; ent = (gentity_t *)pEnt; @@ -1948,74 +1661,64 @@ static void UnGhost( Vehicle_t *pVeh, bgEntity_t *pEnt ) ent->r.svFlags &= ~SVF_NOCLIENT; ent->s.eFlags &= ~EF_NODRAW; - if ( ent->client ) - { + if (ent->client) { ent->client->ps.eFlags &= ~EF_NODRAW; } ent->r.contents = CONTENTS_BODY; } -//try to resize the bounding box around a torn apart ship -void G_VehicleDamageBoxSizing(Vehicle_t *pVeh) -{ +// try to resize the bounding box around a torn apart ship +void G_VehicleDamageBoxSizing(Vehicle_t *pVeh) { vec3_t fwd, right, up; - vec3_t nose; //maxs - vec3_t back; //mins + vec3_t nose; // maxs + vec3_t back; // mins trace_t trace; - const float fDist = 256.0f; //estimated distance to nose from origin - const float bDist = 256.0f; //estimated distance to back from origin - const float wDist = 32.0f; //width on each side from origin - const float hDist = 32.0f; //height on each side from origin + const float fDist = 256.0f; // estimated distance to nose from origin + const float bDist = 256.0f; // estimated distance to back from origin + const float wDist = 32.0f; // width on each side from origin + const float hDist = 32.0f; // height on each side from origin gentity_t *parent = (gentity_t *)pVeh->m_pParentEntity; - if (!parent->ghoul2 || !parent->m_pVehicle || !parent->client) - { //shouldn't have gotten in here then + if (!parent->ghoul2 || !parent->m_pVehicle || !parent->client) { // shouldn't have gotten in here then return; } - //for now, let's only do anything if all wings are stripped off. - //this is because I want to be able to tear my wings off and fling - //myself down narrow hallways to my death. Because it's fun! -rww - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F) ) - { + // for now, let's only do anything if all wings are stripped off. + // this is because I want to be able to tear my wings off and fling + // myself down narrow hallways to my death. Because it's fun! -rww + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || + !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { return; } - //get directions based on orientation + // get directions based on orientation AngleVectors(pVeh->m_vOrientation, fwd, right, up); - //get the nose and back positions (relative to 0, they're gonna be mins/maxs) + // get the nose and back positions (relative to 0, they're gonna be mins/maxs) VectorMA(vec3_origin, fDist, fwd, nose); VectorMA(vec3_origin, -bDist, fwd, back); - //move the nose and back to opposite right/left, they will end up as our relative mins and maxs + // move the nose and back to opposite right/left, they will end up as our relative mins and maxs VectorMA(nose, wDist, right, nose); VectorMA(nose, -wDist, right, back); - //use the same concept for up/down now + // use the same concept for up/down now VectorMA(nose, hDist, up, nose); VectorMA(nose, -hDist, up, back); - //and now, let's trace and see if our new mins/maxs are safe.. + // and now, let's trace and see if our new mins/maxs are safe.. trap->Trace(&trace, parent->client->ps.origin, back, nose, parent->client->ps.origin, parent->s.number, parent->clipmask, qfalse, 0, 0); - if (!trace.allsolid && !trace.startsolid && trace.fraction == 1.0f) - { //all clear! + if (!trace.allsolid && !trace.startsolid && trace.fraction == 1.0f) { // all clear! VectorCopy(nose, parent->r.maxs); VectorCopy(back, parent->r.mins); - } - else - { //oh well, DIE! - //FIXME: does this give proper credit to the enemy who shot you down? + } else { // oh well, DIE! + // FIXME: does this give proper credit to the enemy who shot you down? G_Damage(parent, parent, parent, NULL, parent->client->ps.origin, 9999, DAMAGE_NO_PROTECTION, MOD_SUICIDE); } } -//get one of 4 possible impact locations based on the trace direction -int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) -{ +// get one of 4 possible impact locations based on the trace direction +int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) { float impactAngle; float relativeAngle; trace_t localTrace; @@ -2026,8 +1729,7 @@ int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) Vehicle_t *pVeh = veh->m_pVehicle; qboolean noseClear = qfalse; - if (!trace || !pVeh || !veh->client) - { + if (!trace || !pVeh || !veh->client) { return -1; } @@ -2035,194 +1737,151 @@ int G_FlyVehicleImpactDir(gentity_t *veh, trace_t *trace) VectorSet(testMins, -24.0f, -24.0f, -24.0f); VectorSet(testMaxs, 24.0f, 24.0f, 24.0f); - //do a trace to determine if the nose is clear + // do a trace to determine if the nose is clear VectorMA(veh->client->ps.origin, 256.0f, fwd, fPos); trap->Trace(&localTrace, veh->client->ps.origin, testMins, testMaxs, fPos, veh->s.number, veh->clipmask, qfalse, 0, 0); - if (!localTrace.startsolid && !localTrace.allsolid && localTrace.fraction == 1.0f) - { //otherwise I guess it's not clear.. + if (!localTrace.startsolid && !localTrace.allsolid && localTrace.fraction == 1.0f) { // otherwise I guess it's not clear.. noseClear = qtrue; } - if (noseClear) - { //if nose is clear check for tearing the wings off - //sadly, the trace endpos given always matches the vehicle origin, so we - //can't get a real impact direction. First we'll trace forward and see if the wings are colliding - //with anything, and if not, we'll fall back to checking the trace plane normal. + if (noseClear) { // if nose is clear check for tearing the wings off + // sadly, the trace endpos given always matches the vehicle origin, so we + // can't get a real impact direction. First we'll trace forward and see if the wings are colliding + // with anything, and if not, we'll fall back to checking the trace plane normal. VectorMA(veh->client->ps.origin, 128.0f, right, rWing); VectorMA(veh->client->ps.origin, -128.0f, right, lWing); - //test the right wing - unless it's already removed - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) - { + // test the right wing - unless it's already removed + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_E) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_F)) { VectorMA(rWing, 256.0f, fwd, fPos); trap->Trace(&localTrace, rWing, testMins, testMaxs, fPos, veh->s.number, veh->clipmask, qfalse, 0, 0); - if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) - { //impact + if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) { // impact return SHIPSURF_RIGHT; } } - //test the left wing - unless it's already removed - if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || - !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) - { + // test the left wing - unless it's already removed + if (!(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_C) || !(pVeh->m_iRemovedSurfaces & SHIPSURF_BROKEN_D)) { VectorMA(lWing, 256.0f, fwd, fPos); trap->Trace(&localTrace, lWing, testMins, testMaxs, fPos, veh->s.number, veh->clipmask, qfalse, 0, 0); - if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) - { //impact + if (localTrace.startsolid || localTrace.allsolid || localTrace.fraction != 1.0f) { // impact return SHIPSURF_LEFT; } } } - //try to use the trace plane normal + // try to use the trace plane normal impactAngle = vectoyaw(trace->plane.normal); relativeAngle = AngleSubtract(impactAngle, veh->client->ps.viewangles[YAW]); - if (relativeAngle > 130 || - relativeAngle < -130) - { //consider this front + if (relativeAngle > 130 || relativeAngle < -130) { // consider this front return SHIPSURF_FRONT; - } - else if (relativeAngle > 0) - { + } else if (relativeAngle > 0) { return SHIPSURF_RIGHT; - } - else if (relativeAngle < 0) - { + } else if (relativeAngle < 0) { return SHIPSURF_LEFT; } return SHIPSURF_BACK; } -//try to break surfaces off the ship on impact -#define TURN_ON 0x00000000 -#define TURN_OFF 0x00000100 -extern void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags); //NPC_utils.c -int G_ShipSurfaceForSurfName( const char *surfaceName ) -{ - if ( !surfaceName ) - { +// try to break surfaces off the ship on impact +#define TURN_ON 0x00000000 +#define TURN_OFF 0x00000100 +extern void NPC_SetSurfaceOnOff(gentity_t *ent, const char *surfaceName, int surfaceFlags); // NPC_utils.c +int G_ShipSurfaceForSurfName(const char *surfaceName) { + if (!surfaceName) { return -1; } - if ( !Q_strncmp( "nose", surfaceName, 4 ) - || !Q_strncmp( "f_gear", surfaceName, 6 ) - || !Q_strncmp( "glass", surfaceName, 5 ) ) - { + if (!Q_strncmp("nose", surfaceName, 4) || !Q_strncmp("f_gear", surfaceName, 6) || !Q_strncmp("glass", surfaceName, 5)) { return SHIPSURF_FRONT; } - if ( !Q_strncmp( "body", surfaceName, 4 ) ) - { + if (!Q_strncmp("body", surfaceName, 4)) { return SHIPSURF_BACK; } - if ( !Q_strncmp( "r_wing1", surfaceName, 7 ) - || !Q_strncmp( "r_wing2", surfaceName, 7 ) - || !Q_strncmp( "r_gear", surfaceName, 6 ) ) - { + if (!Q_strncmp("r_wing1", surfaceName, 7) || !Q_strncmp("r_wing2", surfaceName, 7) || !Q_strncmp("r_gear", surfaceName, 6)) { return SHIPSURF_RIGHT; } - if ( !Q_strncmp( "l_wing1", surfaceName, 7 ) - || !Q_strncmp( "l_wing2", surfaceName, 7 ) - || !Q_strncmp( "l_gear", surfaceName, 6 ) ) - { + if (!Q_strncmp("l_wing1", surfaceName, 7) || !Q_strncmp("l_wing2", surfaceName, 7) || !Q_strncmp("l_gear", surfaceName, 6)) { return SHIPSURF_LEFT; } return -1; } -void G_SetVehDamageFlags( gentity_t *veh, int shipSurf, int damageLevel ) -{ +void G_SetVehDamageFlags(gentity_t *veh, int shipSurf, int damageLevel) { int dmgFlag; - switch ( damageLevel ) - { - case 3://destroyed - //add both flags so cgame side knows this surf is GONE - //add heavy - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs |= (1<client->ps.brokenLimbs |= (1 << dmgFlag); + // add light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs |= (1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; - //check droid - if ( shipSurf == SHIPSURF_BACK ) - {//destroy the droid if we have one - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pDroidUnit ) - {//we have one + // check droid + if (shipSurf == SHIPSURF_BACK) { // destroy the droid if we have one + if (veh->m_pVehicle && veh->m_pVehicle->m_pDroidUnit) { // we have one gentity_t *droidEnt = (gentity_t *)veh->m_pVehicle->m_pDroidUnit; - if ( droidEnt - && ((droidEnt->flags&FL_UNDYING) || droidEnt->health > 0) ) - {//boom - //make it vulnerable + if (droidEnt && ((droidEnt->flags & FL_UNDYING) || droidEnt->health > 0)) { // boom + // make it vulnerable droidEnt->flags &= ~FL_UNDYING; - //blow it up - G_Damage( droidEnt, veh->enemy, veh->enemy, NULL, NULL, 99999, 0, MOD_UNKNOWN ); + // blow it up + G_Damage(droidEnt, veh->enemy, veh->enemy, NULL, NULL, 99999, 0, MOD_UNKNOWN); } } } break; - case 2://heavy only - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs |= (1 << dmgFlag); + // remove light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; - //check droid - if ( shipSurf == SHIPSURF_BACK ) - {//make the droid vulnerable if we have one - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pDroidUnit ) - {//we have one + // check droid + if (shipSurf == SHIPSURF_BACK) { // make the droid vulnerable if we have one + if (veh->m_pVehicle && veh->m_pVehicle->m_pDroidUnit) { // we have one gentity_t *droidEnt = (gentity_t *)veh->m_pVehicle->m_pDroidUnit; - if ( droidEnt - && (droidEnt->flags&FL_UNDYING) ) - {//make it vulnerab;e + if (droidEnt && (droidEnt->flags & FL_UNDYING)) { // make it vulnerab;e droidEnt->flags &= ~FL_UNDYING; } } } break; - case 1://light only - //add light - dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs |= (1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs |= (1 << dmgFlag); + // remove heavy (shouldn't have to do this, but... + dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; break; - case 0://no damage + case 0: // no damage default: - //remove heavy - dmgFlag = SHIPSURF_DAMAGE_FRONT_HEAVY+(shipSurf-SHIPSURF_FRONT); - veh->client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs &= ~(1<client->ps.brokenLimbs &= ~(1 << dmgFlag); + // remove light + dmgFlag = SHIPSURF_DAMAGE_FRONT_LIGHT + (shipSurf - SHIPSURF_FRONT); + veh->client->ps.brokenLimbs &= ~(1 << dmgFlag); + // copy down veh->s.brokenLimbs = veh->client->ps.brokenLimbs; break; } } -void G_VehicleSetDamageLocFlags( gentity_t *veh, int impactDir, int deathPoint ) -{ - if ( !veh->client ) - { +void G_VehicleSetDamageLocFlags(gentity_t *veh, int impactDir, int deathPoint) { + if (!veh->client) { return; - } - else - { - int heavyDamagePoint, lightDamagePoint; - switch(impactDir) - { + } else { + int heavyDamagePoint, lightDamagePoint; + switch (impactDir) { case SHIPSURF_FRONT: deathPoint = veh->m_pVehicle->m_pVehicleInfo->health_front; break; @@ -2239,91 +1898,77 @@ void G_VehicleSetDamageLocFlags( gentity_t *veh, int impactDir, int deathPoint ) return; break; } - if ( veh->m_pVehicle - && veh->m_pVehicle->m_pVehicleInfo - && veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel - && veh->m_pVehicle->m_pVehicleInfo->armor ) - { - float perc = ((float)veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel/(float)veh->m_pVehicle->m_pVehicleInfo->armor); - if ( perc > 0.99f ) - { + if (veh->m_pVehicle && veh->m_pVehicle->m_pVehicleInfo && veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel && + veh->m_pVehicle->m_pVehicleInfo->armor) { + float perc = ((float)veh->m_pVehicle->m_pVehicleInfo->malfunctionArmorLevel / (float)veh->m_pVehicle->m_pVehicleInfo->armor); + if (perc > 0.99f) { perc = 0.99f; } - lightDamagePoint = ceil( deathPoint*perc*0.25f ); - heavyDamagePoint = ceil( deathPoint*perc ); - } - else - { - heavyDamagePoint = ceil( deathPoint*0.66f ); - lightDamagePoint = ceil( deathPoint*0.14f ); + lightDamagePoint = ceil(deathPoint * perc * 0.25f); + heavyDamagePoint = ceil(deathPoint * perc); + } else { + heavyDamagePoint = ceil(deathPoint * 0.66f); + lightDamagePoint = ceil(deathPoint * 0.14f); } - if ( veh->locationDamage[impactDir] >= deathPoint) - {//destroyed - G_SetVehDamageFlags( veh, impactDir, 3 ); - } - else if ( veh->locationDamage[impactDir] <= lightDamagePoint ) - {//light only - G_SetVehDamageFlags( veh, impactDir, 1 ); - } - else if ( veh->locationDamage[impactDir] <= heavyDamagePoint ) - {//heavy only - G_SetVehDamageFlags( veh, impactDir, 2 ); + if (veh->locationDamage[impactDir] >= deathPoint) { // destroyed + G_SetVehDamageFlags(veh, impactDir, 3); + } else if (veh->locationDamage[impactDir] <= lightDamagePoint) { // light only + G_SetVehDamageFlags(veh, impactDir, 1); + } else if (veh->locationDamage[impactDir] <= heavyDamagePoint) { // heavy only + G_SetVehDamageFlags(veh, impactDir, 2); } } } -qboolean G_FlyVehicleDestroySurface( gentity_t *veh, int surface ) -{ - char *surfName[4]; //up to 4 surfs at once +qboolean G_FlyVehicleDestroySurface(gentity_t *veh, int surface) { + char *surfName[4]; // up to 4 surfs at once int numSurfs = 0; int smashedBits = 0; - if (surface == -1) - { //not valid? + if (surface == -1) { // not valid? return qfalse; } - switch(surface) - { - case SHIPSURF_FRONT: //break the nose off + switch (surface) { + case SHIPSURF_FRONT: // break the nose off surfName[0] = "nose"; smashedBits = (SHIPSURF_BROKEN_G); numSurfs = 1; break; - case SHIPSURF_BACK: //break both the bottom wings off for a backward impact I guess + case SHIPSURF_BACK: // break both the bottom wings off for a backward impact I guess surfName[0] = "r_wing2"; surfName[1] = "l_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "r_gear"; surfName[3] = "l_gear"; - smashedBits = (SHIPSURF_BROKEN_A|SHIPSURF_BROKEN_B|SHIPSURF_BROKEN_D|SHIPSURF_BROKEN_F); + smashedBits = (SHIPSURF_BROKEN_A | SHIPSURF_BROKEN_B | SHIPSURF_BROKEN_D | SHIPSURF_BROKEN_F); numSurfs = 4; break; - case SHIPSURF_RIGHT: //break both right wings off + case SHIPSURF_RIGHT: // break both right wings off surfName[0] = "r_wing1"; surfName[1] = "r_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "r_gear"; - smashedBits = (SHIPSURF_BROKEN_B|SHIPSURF_BROKEN_E|SHIPSURF_BROKEN_F); + smashedBits = (SHIPSURF_BROKEN_B | SHIPSURF_BROKEN_E | SHIPSURF_BROKEN_F); numSurfs = 3; break; - case SHIPSURF_LEFT: //break both left wings off + case SHIPSURF_LEFT: // break both left wings off surfName[0] = "l_wing1"; surfName[1] = "l_wing2"; - //get rid of the landing gear + // get rid of the landing gear surfName[2] = "l_gear"; - smashedBits = (SHIPSURF_BROKEN_A|SHIPSURF_BROKEN_C|SHIPSURF_BROKEN_D); + smashedBits = (SHIPSURF_BROKEN_A | SHIPSURF_BROKEN_C | SHIPSURF_BROKEN_D); numSurfs = 3; break; @@ -2331,60 +1976,52 @@ qboolean G_FlyVehicleDestroySurface( gentity_t *veh, int surface ) break; } - if (numSurfs < 1) - { //didn't get any valid surfs.. + if (numSurfs < 1) { // didn't get any valid surfs.. return qfalse; } - while (numSurfs > 0) - { //use my silly system of automatically managing surf status on both client and server + while (numSurfs > 0) { // use my silly system of automatically managing surf status on both client and server numSurfs--; NPC_SetSurfaceOnOff(veh, surfName[numSurfs], TURN_OFF); } - if ( !veh->m_pVehicle->m_iRemovedSurfaces ) - {//first time something got blown off - if ( veh->m_pVehicle->m_pPilot ) - {//make the pilot scream to his death - G_EntitySound((gentity_t*)veh->m_pVehicle->m_pPilot, CHAN_VOICE, G_SoundIndex("*falling1.wav")); + if (!veh->m_pVehicle->m_iRemovedSurfaces) { // first time something got blown off + if (veh->m_pVehicle->m_pPilot) { // make the pilot scream to his death + G_EntitySound((gentity_t *)veh->m_pVehicle->m_pPilot, CHAN_VOICE, G_SoundIndex("*falling1.wav")); } } - //so we can check what's broken + // so we can check what's broken veh->m_pVehicle->m_iRemovedSurfaces |= smashedBits; - //do some explosive damage, but don't damage this ship with it + // do some explosive damage, but don't damage this ship with it G_RadiusDamage(veh->client->ps.origin, veh, 100, 500, veh, NULL, MOD_SUICIDE); - //when spiraling to your death, do the electical shader + // when spiraling to your death, do the electical shader veh->client->ps.electrifyTime = level.time + 10000; return qtrue; } -void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force) -{ +void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitude, qboolean force) { int impactDir; int secondImpact; int deathPoint = -1; qboolean alreadyRebroken = qfalse; - if (!veh->ghoul2 || !veh->m_pVehicle) - { //no g2 instance.. or no vehicle instance + if (!veh->ghoul2 || !veh->m_pVehicle) { // no g2 instance.. or no vehicle instance return; } - impactDir = G_FlyVehicleImpactDir(veh, trace); + impactDir = G_FlyVehicleImpactDir(veh, trace); anotherImpact: - if (impactDir == -1) - { //not valid? + if (impactDir == -1) { // not valid? return; } - veh->locationDamage[impactDir] += magnitude*7; + veh->locationDamage[impactDir] += magnitude * 7; - switch(impactDir) - { + switch (impactDir) { case SHIPSURF_FRONT: deathPoint = veh->m_pVehicle->m_pVehicleInfo->health_front; break; @@ -2401,30 +2038,22 @@ void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitud break; } - if ( deathPoint != -1 ) - {//got a valid health value - if ( force && veh->locationDamage[impactDir] < deathPoint ) - {//force that surf to be destroyed + if (deathPoint != -1) { // got a valid health value + if (force && veh->locationDamage[impactDir] < deathPoint) { // force that surf to be destroyed veh->locationDamage[impactDir] = deathPoint; } - if ( veh->locationDamage[impactDir] >= deathPoint) - { //do it - if ( G_FlyVehicleDestroySurface( veh, impactDir ) ) - {//actually took off a surface - G_VehicleSetDamageLocFlags( veh, impactDir, deathPoint ); + if (veh->locationDamage[impactDir] >= deathPoint) { // do it + if (G_FlyVehicleDestroySurface(veh, impactDir)) { // actually took off a surface + G_VehicleSetDamageLocFlags(veh, impactDir, deathPoint); } - } - else - { - G_VehicleSetDamageLocFlags( veh, impactDir, deathPoint ); + } else { + G_VehicleSetDamageLocFlags(veh, impactDir, deathPoint); } } - if (!alreadyRebroken) - { + if (!alreadyRebroken) { secondImpact = G_FlyVehicleImpactDir(veh, trace); - if (impactDir != secondImpact) - { //can break off another piece in this same impact.. but only break off up to 2 at once + if (impactDir != secondImpact) { // can break off another piece in this same impact.. but only break off up to 2 at once alreadyRebroken = qtrue; impactDir = secondImpact; goto anotherImpact; @@ -2432,56 +2061,50 @@ void G_FlyVehicleSurfaceDestruction(gentity_t *veh, trace_t *trace, int magnitud } } -void G_VehUpdateShields( gentity_t *targ ) -{ - if ( !targ || !targ->client - || !targ->m_pVehicle || !targ->m_pVehicle->m_pVehicleInfo ) - { +void G_VehUpdateShields(gentity_t *targ) { + if (!targ || !targ->client || !targ->m_pVehicle || !targ->m_pVehicle->m_pVehicleInfo) { return; } - if ( targ->m_pVehicle->m_pVehicleInfo->shields <= 0 ) - {//doesn't have shields, so don't have to send it + if (targ->m_pVehicle->m_pVehicleInfo->shields <= 0) { // doesn't have shields, so don't have to send it return; } - targ->client->ps.activeForcePass = floor(((float)targ->m_pVehicle->m_iShields/(float)targ->m_pVehicle->m_pVehicleInfo->shields)*10.0f); + targ->client->ps.activeForcePass = floor(((float)targ->m_pVehicle->m_iShields / (float)targ->m_pVehicle->m_pVehicleInfo->shields) * 10.0f); } // Set the parent entity of this Vehicle NPC. -void _SetParent( Vehicle_t *pVeh, bgEntity_t *pParentEntity ) { pVeh->m_pParentEntity = pParentEntity; } +void _SetParent(Vehicle_t *pVeh, bgEntity_t *pParentEntity) { pVeh->m_pParentEntity = pParentEntity; } // Add a pilot to the vehicle. -void SetPilot( Vehicle_t *pVeh, bgEntity_t *pPilot ) { pVeh->m_pPilot = pPilot; } +void SetPilot(Vehicle_t *pVeh, bgEntity_t *pPilot) { pVeh->m_pPilot = pPilot; } // Add a passenger to the vehicle (false if we're full). -qboolean AddPassenger( Vehicle_t *pVeh ) { return qfalse; } +qboolean AddPassenger(Vehicle_t *pVeh) { return qfalse; } // Whether this vehicle is currently inhabited (by anyone) or not. -qboolean Inhabited( Vehicle_t *pVeh ) { return ( pVeh->m_pPilot || pVeh->m_iNumPassengers ) ? qtrue : qfalse; } - +qboolean Inhabited(Vehicle_t *pVeh) { return (pVeh->m_pPilot || pVeh->m_iNumPassengers) ? qtrue : qfalse; } // Setup the shared functions (one's that all vehicles would generally use). -void G_SetSharedVehicleFunctions( vehicleInfo_t *pVehInfo ) -{ -// pVehInfo->AnimateVehicle = AnimateVehicle; -// pVehInfo->AnimateRiders = AnimateRiders; - pVehInfo->ValidateBoard = ValidateBoard; - pVehInfo->SetParent = _SetParent; - pVehInfo->SetPilot = SetPilot; - pVehInfo->AddPassenger = AddPassenger; - pVehInfo->Animate = Animate; - pVehInfo->Board = Board; - pVehInfo->Eject = Eject; - pVehInfo->EjectAll = EjectAll; - pVehInfo->StartDeathDelay = StartDeathDelay; - pVehInfo->DeathUpdate = DeathUpdate; - pVehInfo->RegisterAssets = RegisterAssets; - pVehInfo->Initialize = Initialize; - pVehInfo->Update = Update; - pVehInfo->UpdateRider = UpdateRider; -// pVehInfo->ProcessMoveCommands = ProcessMoveCommands; -// pVehInfo->ProcessOrientCommands = ProcessOrientCommands; - pVehInfo->AttachRiders = AttachRiders; - pVehInfo->Ghost = Ghost; - pVehInfo->UnGhost = UnGhost; - pVehInfo->Inhabited = Inhabited; +void G_SetSharedVehicleFunctions(vehicleInfo_t *pVehInfo) { + // pVehInfo->AnimateVehicle = AnimateVehicle; + // pVehInfo->AnimateRiders = AnimateRiders; + pVehInfo->ValidateBoard = ValidateBoard; + pVehInfo->SetParent = _SetParent; + pVehInfo->SetPilot = SetPilot; + pVehInfo->AddPassenger = AddPassenger; + pVehInfo->Animate = Animate; + pVehInfo->Board = Board; + pVehInfo->Eject = Eject; + pVehInfo->EjectAll = EjectAll; + pVehInfo->StartDeathDelay = StartDeathDelay; + pVehInfo->DeathUpdate = DeathUpdate; + pVehInfo->RegisterAssets = RegisterAssets; + pVehInfo->Initialize = Initialize; + pVehInfo->Update = Update; + pVehInfo->UpdateRider = UpdateRider; + // pVehInfo->ProcessMoveCommands = ProcessMoveCommands; + // pVehInfo->ProcessOrientCommands = ProcessOrientCommands; + pVehInfo->AttachRiders = AttachRiders; + pVehInfo->Ghost = Ghost; + pVehInfo->UnGhost = UnGhost; + pVehInfo->Inhabited = Inhabited; } diff --git a/codemp/game/g_weapon.c b/codemp/game/g_weapon.c index ba9b8dd1b2..51df0ae154 100644 --- a/codemp/game/g_weapon.c +++ b/codemp/game/g_weapon.c @@ -35,207 +35,196 @@ static vec3_t muzzle; // Bryar Pistol //-------- -#define BRYAR_PISTOL_VEL 1600 -#define BRYAR_PISTOL_DAMAGE 10 -#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in bg_pmove -#define BRYAR_ALT_SIZE 1.0f +#define BRYAR_PISTOL_VEL 1600 +#define BRYAR_PISTOL_DAMAGE 10 +#define BRYAR_CHARGE_UNIT 200.0f // bryar charging gives us one more unit every 200ms--if you change this, you'll have to do the same in bg_pmove +#define BRYAR_ALT_SIZE 1.0f // E11 Blaster //--------- -#define BLASTER_SPREAD 1.6f//1.2f -#define BLASTER_VELOCITY 2300 -#define BLASTER_DAMAGE 20 +#define BLASTER_SPREAD 1.6f // 1.2f +#define BLASTER_VELOCITY 2300 +#define BLASTER_DAMAGE 20 // Tenloss Disruptor //---------- -#define DISRUPTOR_MAIN_DAMAGE 30 //40 -#define DISRUPTOR_MAIN_DAMAGE_SIEGE 50 -#define DISRUPTOR_NPC_MAIN_DAMAGE_CUT 0.25f +#define DISRUPTOR_MAIN_DAMAGE 30 // 40 +#define DISRUPTOR_MAIN_DAMAGE_SIEGE 50 +#define DISRUPTOR_NPC_MAIN_DAMAGE_CUT 0.25f -#define DISRUPTOR_ALT_DAMAGE 100 //125 -#define DISRUPTOR_NPC_ALT_DAMAGE_CUT 0.2f -#define DISRUPTOR_ALT_TRACES 3 // can go through a max of 3 damageable(sp?) entities -#define DISRUPTOR_CHARGE_UNIT 50.0f // distruptor charging gives us one more unit every 50ms--if you change this, you'll have to do the same in bg_pmove +#define DISRUPTOR_ALT_DAMAGE 100 // 125 +#define DISRUPTOR_NPC_ALT_DAMAGE_CUT 0.2f +#define DISRUPTOR_ALT_TRACES 3 // can go through a max of 3 damageable(sp?) entities +#define DISRUPTOR_CHARGE_UNIT 50.0f // distruptor charging gives us one more unit every 50ms--if you change this, you'll have to do the same in bg_pmove // Wookiee Bowcaster //---------- -#define BOWCASTER_DAMAGE 50 -#define BOWCASTER_VELOCITY 1300 -#define BOWCASTER_SPLASH_DAMAGE 0 -#define BOWCASTER_SPLASH_RADIUS 0 -#define BOWCASTER_SIZE 2 +#define BOWCASTER_DAMAGE 50 +#define BOWCASTER_VELOCITY 1300 +#define BOWCASTER_SPLASH_DAMAGE 0 +#define BOWCASTER_SPLASH_RADIUS 0 +#define BOWCASTER_SIZE 2 -#define BOWCASTER_ALT_SPREAD 5.0f -#define BOWCASTER_VEL_RANGE 0.3f -#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in bg_pmove +#define BOWCASTER_ALT_SPREAD 5.0f +#define BOWCASTER_VEL_RANGE 0.3f +#define BOWCASTER_CHARGE_UNIT 200.0f // bowcaster charging gives us one more unit every 200ms--if you change this, you'll have to do the same in bg_pmove // Heavy Repeater //---------- -#define REPEATER_SPREAD 1.4f -#define REPEATER_DAMAGE 14 -#define REPEATER_VELOCITY 1600 +#define REPEATER_SPREAD 1.4f +#define REPEATER_DAMAGE 14 +#define REPEATER_VELOCITY 1600 -#define REPEATER_ALT_SIZE 3 // half of bbox size -#define REPEATER_ALT_DAMAGE 60 -#define REPEATER_ALT_SPLASH_DAMAGE 60 -#define REPEATER_ALT_SPLASH_RADIUS 128 -#define REPEATER_ALT_SPLASH_RAD_SIEGE 80 -#define REPEATER_ALT_VELOCITY 1100 +#define REPEATER_ALT_SIZE 3 // half of bbox size +#define REPEATER_ALT_DAMAGE 60 +#define REPEATER_ALT_SPLASH_DAMAGE 60 +#define REPEATER_ALT_SPLASH_RADIUS 128 +#define REPEATER_ALT_SPLASH_RAD_SIEGE 80 +#define REPEATER_ALT_VELOCITY 1100 // DEMP2 //---------- -#define DEMP2_DAMAGE 35 -#define DEMP2_VELOCITY 1800 -#define DEMP2_SIZE 2 // half of bbox size +#define DEMP2_DAMAGE 35 +#define DEMP2_VELOCITY 1800 +#define DEMP2_SIZE 2 // half of bbox size -#define DEMP2_ALT_DAMAGE 8 //12 // does 12, 36, 84 at each of the 3 charge levels. -#define DEMP2_CHARGE_UNIT 700.0f // demp2 charging gives us one more unit every 700ms--if you change this, you'll have to do the same in bg_weapons -#define DEMP2_ALT_RANGE 4096 -#define DEMP2_ALT_SPLASHRADIUS 256 +#define DEMP2_ALT_DAMAGE 8 // 12 // does 12, 36, 84 at each of the 3 charge levels. +#define DEMP2_CHARGE_UNIT 700.0f // demp2 charging gives us one more unit every 700ms--if you change this, you'll have to do the same in bg_weapons +#define DEMP2_ALT_RANGE 4096 +#define DEMP2_ALT_SPLASHRADIUS 256 // Golan Arms Flechette //--------- -#define FLECHETTE_SHOTS 5 -#define FLECHETTE_SPREAD 4.0f -#define FLECHETTE_DAMAGE 12//15 -#define FLECHETTE_VEL 3500 -#define FLECHETTE_SIZE 1 -#define FLECHETTE_MINE_RADIUS_CHECK 256 -#define FLECHETTE_ALT_DAMAGE 60 -#define FLECHETTE_ALT_SPLASH_DAM 60 -#define FLECHETTE_ALT_SPLASH_RAD 128 +#define FLECHETTE_SHOTS 5 +#define FLECHETTE_SPREAD 4.0f +#define FLECHETTE_DAMAGE 12 // 15 +#define FLECHETTE_VEL 3500 +#define FLECHETTE_SIZE 1 +#define FLECHETTE_MINE_RADIUS_CHECK 256 +#define FLECHETTE_ALT_DAMAGE 60 +#define FLECHETTE_ALT_SPLASH_DAM 60 +#define FLECHETTE_ALT_SPLASH_RAD 128 // Personal Rocket Launcher //--------- -#define ROCKET_VELOCITY 900 -#define ROCKET_DAMAGE 100 -#define ROCKET_SPLASH_DAMAGE 100 -#define ROCKET_SPLASH_RADIUS 160 -#define ROCKET_SIZE 3 -#define ROCKET_ALT_THINK_TIME 100 +#define ROCKET_VELOCITY 900 +#define ROCKET_DAMAGE 100 +#define ROCKET_SPLASH_DAMAGE 100 +#define ROCKET_SPLASH_RADIUS 160 +#define ROCKET_SIZE 3 +#define ROCKET_ALT_THINK_TIME 100 // Concussion Rifle //--------- -//primary -//man, this thing is too absurdly powerful. having to -//slash the values way down from sp. -#define CONC_VELOCITY 3000 -#define CONC_DAMAGE 75 //150 -#define CONC_NPC_DAMAGE_EASY 40 -#define CONC_NPC_DAMAGE_NORMAL 80 -#define CONC_NPC_DAMAGE_HARD 100 -#define CONC_SPLASH_DAMAGE 40 //50 -#define CONC_SPLASH_RADIUS 200 //300 -//alt -#define CONC_ALT_DAMAGE 25 //100 -#define CONC_ALT_NPC_DAMAGE_EASY 20 -#define CONC_ALT_NPC_DAMAGE_MEDIUM 35 -#define CONC_ALT_NPC_DAMAGE_HARD 50 +// primary +// man, this thing is too absurdly powerful. having to +// slash the values way down from sp. +#define CONC_VELOCITY 3000 +#define CONC_DAMAGE 75 // 150 +#define CONC_NPC_DAMAGE_EASY 40 +#define CONC_NPC_DAMAGE_NORMAL 80 +#define CONC_NPC_DAMAGE_HARD 100 +#define CONC_SPLASH_DAMAGE 40 // 50 +#define CONC_SPLASH_RADIUS 200 // 300 +// alt +#define CONC_ALT_DAMAGE 25 // 100 +#define CONC_ALT_NPC_DAMAGE_EASY 20 +#define CONC_ALT_NPC_DAMAGE_MEDIUM 35 +#define CONC_ALT_NPC_DAMAGE_HARD 50 // Stun Baton //-------------- -#define STUN_BATON_DAMAGE 20 -#define STUN_BATON_ALT_DAMAGE 20 -#define STUN_BATON_RANGE 8 +#define STUN_BATON_DAMAGE 20 +#define STUN_BATON_ALT_DAMAGE 20 +#define STUN_BATON_RANGE 8 // Melee //-------------- -#define MELEE_SWING1_DAMAGE 10 -#define MELEE_SWING2_DAMAGE 12 -#define MELEE_RANGE 8 +#define MELEE_SWING1_DAMAGE 10 +#define MELEE_SWING2_DAMAGE 12 +#define MELEE_RANGE 8 // ATST Main Gun //-------------- -#define ATST_MAIN_VEL 4000 // -#define ATST_MAIN_DAMAGE 25 // -#define ATST_MAIN_SIZE 3 // make it easier to hit things +#define ATST_MAIN_VEL 4000 // +#define ATST_MAIN_DAMAGE 25 // +#define ATST_MAIN_SIZE 3 // make it easier to hit things // ATST Side Gun //--------------- -#define ATST_SIDE_MAIN_DAMAGE 75 -#define ATST_SIDE_MAIN_VELOCITY 1300 -#define ATST_SIDE_MAIN_NPC_DAMAGE_EASY 30 -#define ATST_SIDE_MAIN_NPC_DAMAGE_NORMAL 40 -#define ATST_SIDE_MAIN_NPC_DAMAGE_HARD 50 -#define ATST_SIDE_MAIN_SIZE 4 -#define ATST_SIDE_MAIN_SPLASH_DAMAGE 10 // yeah, pretty small, either zero out or make it worth having? -#define ATST_SIDE_MAIN_SPLASH_RADIUS 16 // yeah, pretty small, either zero out or make it worth having? +#define ATST_SIDE_MAIN_DAMAGE 75 +#define ATST_SIDE_MAIN_VELOCITY 1300 +#define ATST_SIDE_MAIN_NPC_DAMAGE_EASY 30 +#define ATST_SIDE_MAIN_NPC_DAMAGE_NORMAL 40 +#define ATST_SIDE_MAIN_NPC_DAMAGE_HARD 50 +#define ATST_SIDE_MAIN_SIZE 4 +#define ATST_SIDE_MAIN_SPLASH_DAMAGE 10 // yeah, pretty small, either zero out or make it worth having? +#define ATST_SIDE_MAIN_SPLASH_RADIUS 16 // yeah, pretty small, either zero out or make it worth having? -#define ATST_SIDE_ALT_VELOCITY 1100 -#define ATST_SIDE_ALT_NPC_VELOCITY 600 -#define ATST_SIDE_ALT_DAMAGE 130 +#define ATST_SIDE_ALT_VELOCITY 1100 +#define ATST_SIDE_ALT_NPC_VELOCITY 600 +#define ATST_SIDE_ALT_DAMAGE 130 -#define ATST_SIDE_ROCKET_NPC_DAMAGE_EASY 30 -#define ATST_SIDE_ROCKET_NPC_DAMAGE_NORMAL 50 -#define ATST_SIDE_ROCKET_NPC_DAMAGE_HARD 90 +#define ATST_SIDE_ROCKET_NPC_DAMAGE_EASY 30 +#define ATST_SIDE_ROCKET_NPC_DAMAGE_NORMAL 50 +#define ATST_SIDE_ROCKET_NPC_DAMAGE_HARD 90 -#define ATST_SIDE_ALT_SPLASH_DAMAGE 130 -#define ATST_SIDE_ALT_SPLASH_RADIUS 200 -#define ATST_SIDE_ALT_ROCKET_SIZE 5 -#define ATST_SIDE_ALT_ROCKET_SPLASH_SCALE 0.5f // scales splash for NPC's +#define ATST_SIDE_ALT_SPLASH_DAMAGE 130 +#define ATST_SIDE_ALT_SPLASH_RADIUS 200 +#define ATST_SIDE_ALT_ROCKET_SIZE 5 +#define ATST_SIDE_ALT_ROCKET_SPLASH_SCALE 0.5f // scales splash for NPC's -extern qboolean G_BoxInBounds( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t boundsMins, vec3_t boundsMaxs ); -extern qboolean G_HeavyMelee( gentity_t *attacker ); -extern void Jedi_Decloak( gentity_t *self ); +extern qboolean G_BoxInBounds(vec3_t point, vec3_t mins, vec3_t maxs, vec3_t boundsMins, vec3_t boundsMaxs); +extern qboolean G_HeavyMelee(gentity_t *attacker); +extern void Jedi_Decloak(gentity_t *self); -static void WP_FireEmplaced( gentity_t *ent, qboolean altFire ); +static void WP_FireEmplaced(gentity_t *ent, qboolean altFire); -void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ); +void laserTrapStick(gentity_t *ent, vec3_t endpos, vec3_t normal); -void touch_NULL( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ - -} +void touch_NULL(gentity_t *ent, gentity_t *other, trace_t *trace) {} -void laserTrapExplode( gentity_t *self ); +void laserTrapExplode(gentity_t *self); void RocketDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod); -//We should really organize weapon data into tables or parse from the ext data so we have accurate info for this, -float WP_SpeedOfMissileForWeapon( int wp, qboolean alt_fire ) -{ - return 500; -} +// We should really organize weapon data into tables or parse from the ext data so we have accurate info for this, +float WP_SpeedOfMissileForWeapon(int wp, qboolean alt_fire) { return 500; } //----------------------------------------------------------------------------- -void W_TraceSetStart( gentity_t *ent, vec3_t start, vec3_t mins, vec3_t maxs ) +void W_TraceSetStart(gentity_t *ent, vec3_t start, vec3_t mins, vec3_t maxs) //----------------------------------------------------------------------------- { - //make sure our start point isn't on the other side of a wall - trace_t tr; - vec3_t entMins; - vec3_t entMaxs; - vec3_t eyePoint; + // make sure our start point isn't on the other side of a wall + trace_t tr; + vec3_t entMins; + vec3_t entMaxs; + vec3_t eyePoint; - VectorAdd( ent->r.currentOrigin, ent->r.mins, entMins ); - VectorAdd( ent->r.currentOrigin, ent->r.maxs, entMaxs ); + VectorAdd(ent->r.currentOrigin, ent->r.mins, entMins); + VectorAdd(ent->r.currentOrigin, ent->r.maxs, entMaxs); - if ( G_BoxInBounds( start, mins, maxs, entMins, entMaxs ) ) - { + if (G_BoxInBounds(start, mins, maxs, entMins, entMaxs)) { return; } - if ( !ent->client ) - { + if (!ent->client) { return; } - VectorCopy( ent->s.pos.trBase, eyePoint); + VectorCopy(ent->s.pos.trBase, eyePoint); eyePoint[2] += ent->client->ps.viewheight; - trap->Trace( &tr, eyePoint, mins, maxs, start, ent->s.number, MASK_SOLID|CONTENTS_SHOTCLIP, qfalse, 0, 0 ); + trap->Trace(&tr, eyePoint, mins, maxs, start, ent->s.number, MASK_SOLID | CONTENTS_SHOTCLIP, qfalse, 0, 0); - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { return; } - if ( tr.fraction < 1.0f ) - { - VectorCopy( tr.endpos, start ); + if (tr.fraction < 1.0f) { + VectorCopy(tr.endpos, start); } } - /* ---------------------------------------------- PLAYER WEAPONS @@ -251,57 +240,47 @@ BRYAR PISTOL */ //---------------------------------------------- -static void WP_FireBryarPistol( gentity_t *ent, qboolean altFire ) +static void WP_FireBryarPistol(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { int damage = BRYAR_PISTOL_DAMAGE; int count; - gentity_t *missile = CreateMissile( muzzle, forward, BRYAR_PISTOL_VEL, 10000, ent, altFire ); + gentity_t *missile = CreateMissile(muzzle, forward, BRYAR_PISTOL_VEL, 10000, ent, altFire); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; - if ( altFire ) - { + if (altFire) { float boxSize = 0; - count = ( level.time - ent->client->ps.weaponChargeTime ) / BRYAR_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / BRYAR_CHARGE_UNIT; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if (count > 1) - { - damage *= (count*1.7); - } - else - { - damage *= (count*1.5); + if (count > 1) { + damage *= (count * 1.7); + } else { + damage *= (count * 1.5); } missile->s.generic1 = count; // The missile will then render according to the charge level. - boxSize = BRYAR_ALT_SIZE*(count*0.5); + boxSize = BRYAR_ALT_SIZE * (count * 0.5); - VectorSet( missile->r.maxs, boxSize, boxSize, boxSize ); - VectorSet( missile->r.mins, -boxSize, -boxSize, -boxSize ); + VectorSet(missile->r.maxs, boxSize, boxSize, boxSize); + VectorSet(missile->r.mins, -boxSize, -boxSize, -boxSize); } missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if (altFire) - { + if (altFire) { missile->methodOfDeath = MOD_BRYAR_PISTOL_ALT; - } - else - { + } else { missile->methodOfDeath = MOD_BRYAR_PISTOL; } missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; @@ -319,12 +298,12 @@ GENERIC */ //--------------------------------------------------------- -void WP_FireTurretMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, int damage, int velocity, int mod, gentity_t *ignore ) +void WP_FireTurretMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, int damage, int velocity, int mod, gentity_t *ignore) //--------------------------------------------------------- { gentity_t *missile; - missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "generic_proj"; missile->s.weapon = WP_TURRET; @@ -334,9 +313,8 @@ void WP_FireTurretMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean al missile->methodOfDeath = mod; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - if (ignore) - { - missile->passThroughNum = ignore->s.number+1; + if (ignore) { + missile->passThroughNum = ignore->s.number + 1; } // we don't want it to bounce forever @@ -344,21 +322,20 @@ void WP_FireTurretMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean al } //----------------------------------------------------------------------------- -void WP_Explode( gentity_t *self ) +void WP_Explode(gentity_t *self) //----------------------------------------------------------------------------- { - gentity_t *attacker = self; - vec3_t forwardVec={0,0,1}; + gentity_t *attacker = self; + vec3_t forwardVec = {0, 0, 1}; // stop chain reaction runaway loops self->takedamage = qfalse; self->s.loopSound = 0; -// VectorCopy( self->currentOrigin, self->s.pos.trBase ); - if ( !self->client ) - { - AngleVectors( self->s.angles, forwardVec, NULL, NULL ); + // VectorCopy( self->currentOrigin, self->s.pos.trBase ); + if (!self->client) { + AngleVectors(self->s.angles, forwardVec, NULL, NULL); } // FIXME @@ -367,44 +344,37 @@ void WP_Explode( gentity_t *self ) G_PlayEffect( self->fxID, self->r.currentOrigin, forwardVec ); }*/ - if ( self->s.owner && self->s.owner != 1023 ) - { + if (self->s.owner && self->s.owner != 1023) { attacker = &g_entities[self->s.owner]; - } - else if ( self->activator ) - { + } else if (self->activator) { attacker = self->activator; - } - else if ( self->client ) - { + } else if (self->client) { attacker = self; } - if ( self->splashDamage > 0 && self->splashRadius > 0 ) - { - G_RadiusDamage( self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, 0/*don't ignore attacker*/, self, MOD_UNKNOWN ); + if (self->splashDamage > 0 && self->splashRadius > 0) { + G_RadiusDamage(self->r.currentOrigin, attacker, self->splashDamage, self->splashRadius, 0 /*don't ignore attacker*/, self, MOD_UNKNOWN); } - if ( self->target ) - { - G_UseTargets( self, attacker ); + if (self->target) { + G_UseTargets(self, attacker); } - G_SetOrigin( self, self->r.currentOrigin ); + G_SetOrigin(self, self->r.currentOrigin); self->nextthink = level.time + 50; self->think = G_FreeEntity; } -//Currently only the seeker drone uses this, but it might be useful for other things as well. +// Currently only the seeker drone uses this, but it might be useful for other things as well. //--------------------------------------------------------- -void WP_FireGenericBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, int damage, int velocity, int mod ) +void WP_FireGenericBlasterMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, int damage, int velocity, int mod) //--------------------------------------------------------- { gentity_t *missile; - missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "generic_proj"; missile->s.weapon = WP_BRYAR_PISTOL; @@ -427,19 +397,18 @@ BLASTER */ //--------------------------------------------------------- -void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire ) +void WP_FireBlasterMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire) //--------------------------------------------------------- { - int velocity = BLASTER_VELOCITY; - int damage = BLASTER_DAMAGE; + int velocity = BLASTER_VELOCITY; + int damage = BLASTER_DAMAGE; gentity_t *missile; - if (ent->s.eType == ET_NPC) - { //animent + if (ent->s.eType == ET_NPC) { // animent damage = 10; } - missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "blaster_proj"; missile->s.weapon = WP_BLASTER; @@ -454,64 +423,63 @@ void WP_FireBlasterMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean a } //--------------------------------------------------------- -void WP_FireTurboLaserMissile( gentity_t *ent, vec3_t start, vec3_t dir ) +void WP_FireTurboLaserMissile(gentity_t *ent, vec3_t start, vec3_t dir) //--------------------------------------------------------- { - int velocity = ent->mass; //FIXME: externalize + int velocity = ent->mass; // FIXME: externalize gentity_t *missile; - missile = CreateMissile( start, dir, velocity, 10000, ent, qfalse ); + missile = CreateMissile(start, dir, velocity, 10000, ent, qfalse); - //use a custom shot effect + // use a custom shot effect missile->s.otherEntityNum2 = ent->genericValue14; - //use a custom impact effect + // use a custom impact effect missile->s.emplacedOwner = ent->genericValue15; missile->classname = "turbo_proj"; missile->s.weapon = WP_TURRET; - missile->damage = ent->damage; //FIXME: externalize - missile->splashDamage = ent->splashDamage; //FIXME: externalize - missile->splashRadius = ent->splashRadius; //FIXME: externalize + missile->damage = ent->damage; // FIXME: externalize + missile->splashDamage = ent->splashDamage; // FIXME: externalize + missile->splashRadius = ent->splashRadius; // FIXME: externalize missile->dflags = DAMAGE_DEATH_KNOCKBACK; - missile->methodOfDeath = MOD_TURBLAST; //count as a heavy weap - missile->splashMethodOfDeath = MOD_TURBLAST;// ?SPLASH; + missile->methodOfDeath = MOD_TURBLAST; // count as a heavy weap + missile->splashMethodOfDeath = MOD_TURBLAST; // ?SPLASH; missile->clipmask = MASK_SHOT; // we don't want it to bounce forever missile->bounceCount = 8; - //set veh as cgame side owner for purpose of fx overrides + // set veh as cgame side owner for purpose of fx overrides missile->s.owner = ent->s.number; - //don't let them last forever + // don't let them last forever missile->think = G_FreeEntity; - missile->nextthink = level.time + 5000;//at 20000 speed, that should be more than enough + missile->nextthink = level.time + 5000; // at 20000 speed, that should be more than enough } //--------------------------------------------------------- -void WP_FireEmplacedMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, gentity_t *ignore ) +void WP_FireEmplacedMissile(gentity_t *ent, vec3_t start, vec3_t dir, qboolean altFire, gentity_t *ignore) //--------------------------------------------------------- { - int velocity = BLASTER_VELOCITY; - int damage = BLASTER_DAMAGE; + int velocity = BLASTER_VELOCITY; + int damage = BLASTER_DAMAGE; gentity_t *missile; - missile = CreateMissile( start, dir, velocity, 10000, ent, altFire ); + missile = CreateMissile(start, dir, velocity, 10000, ent, altFire); missile->classname = "emplaced_gun_proj"; - missile->s.weapon = WP_TURRET;//WP_EMPLACED_GUN; + missile->s.weapon = WP_TURRET; // WP_EMPLACED_GUN; missile->activator = ignore; missile->damage = damage; - missile->dflags = (DAMAGE_DEATH_KNOCKBACK|DAMAGE_HEAVY_WEAP_CLASS); + missile->dflags = (DAMAGE_DEATH_KNOCKBACK | DAMAGE_HEAVY_WEAP_CLASS); missile->methodOfDeath = MOD_VEHICLE; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; - if (ignore) - { - missile->passThroughNum = ignore->s.number+1; + if (ignore) { + missile->passThroughNum = ignore->s.number + 1; } // we don't want it to bounce forever @@ -519,27 +487,25 @@ void WP_FireEmplacedMissile( gentity_t *ent, vec3_t start, vec3_t dir, qboolean } //--------------------------------------------------------- -static void WP_FireBlaster( gentity_t *ent, qboolean altFire ) +static void WP_FireBlaster(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( forward, angs ); + vectoangles(forward, angs); - if ( altFire ) - { + if (altFire) { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BLASTER_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * BLASTER_SPREAD; } - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); // FIXME: if temp_org does not have clear trace to inside the bbox, don't shoot! - WP_FireBlasterMissile( ent, muzzle, dir, altFire ); + WP_FireBlasterMissile(ent, muzzle, dir, altFire); } - int G_GetHitLocation(gentity_t *target, vec3_t ppoint); /* @@ -550,223 +516,186 @@ DISRUPTOR ====================================================================== */ //--------------------------------------------------------- -static void WP_DisruptorMainFire( gentity_t *ent ) +static void WP_DisruptorMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = DISRUPTOR_MAIN_DAMAGE; - qboolean render_impact = qtrue; - vec3_t start, end; - trace_t tr; - gentity_t *traceEnt, *tent; - float shotRange = 8192; - int ignore, traces; - - if ( level.gametype == GT_SIEGE ) - { + int damage = DISRUPTOR_MAIN_DAMAGE; + qboolean render_impact = qtrue; + vec3_t start, end; + trace_t tr; + gentity_t *traceEnt, *tent; + float shotRange = 8192; + int ignore, traces; + + if (level.gametype == GT_SIEGE) { damage = DISRUPTOR_MAIN_DAMAGE_SIEGE; } - memset(&tr, 0, sizeof(tr)); //to shut the compiler up + memset(&tr, 0, sizeof(tr)); // to shut the compiler up - VectorCopy( ent->client->ps.origin, start ); - start[2] += ent->client->ps.viewheight;//By eyes + VectorCopy(ent->client->ps.origin, start); + start[2] += ent->client->ps.viewheight; // By eyes - VectorMA( start, shotRange, forward, end ); + VectorMA(start, shotRange, forward, end); ignore = ent->s.number; traces = 0; - while ( traces < 10 ) - {//need to loop this in case we hit a Jedi who dodges the shot - if (d_projectileGhoul2Collision.integer) - { - trap->Trace( &tr, start, NULL, NULL, end, ignore, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_THICK|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); - } - else - { - trap->Trace( &tr, start, NULL, NULL, end, ignore, MASK_SHOT, qfalse, 0, 0 ); + while (traces < 10) { // need to loop this in case we hit a Jedi who dodges the shot + if (d_projectileGhoul2Collision.integer) { + trap->Trace(&tr, start, NULL, NULL, end, ignore, MASK_SHOT, qfalse, + G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_THICK | G2TRFLAG_HITCORPSES, g_g2TraceLod.integer); + } else { + trap->Trace(&tr, start, NULL, NULL, end, ignore, MASK_SHOT, qfalse, 0, 0); } traceEnt = &g_entities[tr.entityNum]; - if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) - { //g2 collision checks -rww - if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) - { //since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the index of the surface on the ghoul2 model we collided with. + if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) { // g2 collision checks -rww + if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) { // since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the + // index of the surface on the ghoul2 model we collided with. traceEnt->client->g2LastSurfaceHit = tr.surfaceFlags; traceEnt->client->g2LastSurfaceTime = level.time; } - if (traceEnt->ghoul2) - { - tr.surfaceFlags = 0; //clear the surface flags after, since we actually care about them in here. + if (traceEnt->ghoul2) { + tr.surfaceFlags = 0; // clear the surface flags after, since we actually care about them in here. } } - if (traceEnt && traceEnt->client && traceEnt->client->ps.duelInProgress && - traceEnt->client->ps.duelIndex != ent->s.number) - { - VectorCopy( tr.endpos, start ); + if (traceEnt && traceEnt->client && traceEnt->client->ps.duelInProgress && traceEnt->client->ps.duelIndex != ent->s.number) { + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; } - if ( Jedi_DodgeEvasion( traceEnt, ent, &tr, G_GetHitLocation(traceEnt, tr.endpos) ) ) - {//act like we didn't even hit him - VectorCopy( tr.endpos, start ); + if (Jedi_DodgeEvasion(traceEnt, ent, &tr, G_GetHitLocation(traceEnt, tr.endpos))) { // act like we didn't even hit him + VectorCopy(tr.endpos, start); ignore = tr.entityNum; traces++; continue; - } - else if (traceEnt && traceEnt->client && traceEnt->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= FORCE_LEVEL_3) - { - if (WP_SaberCanBlock(traceEnt, tr.endpos, 0, MOD_DISRUPTOR, qtrue, 0)) - { //broadcast and stop the shot because it was blocked + } else if (traceEnt && traceEnt->client && traceEnt->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= FORCE_LEVEL_3) { + if (WP_SaberCanBlock(traceEnt, tr.endpos, 0, MOD_DISRUPTOR, qtrue, 0)) { // broadcast and stop the shot because it was blocked gentity_t *te = NULL; - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_MAIN_SHOT ); - VectorCopy( muzzle, tent->s.origin2 ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_MAIN_SHOT); + VectorCopy(muzzle, tent->s.origin2); tent->s.eventParm = ent->s.number; - te = G_TempEntity( tr.endpos, EV_SABER_BLOCK ); + te = G_TempEntity(tr.endpos, EV_SABER_BLOCK); VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { te->s.angles[1] = 1; } te->s.eventParm = 0; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum return; } - } - else if ( (traceEnt->flags&FL_SHIELDED) ) - {//stopped cold + } else if ((traceEnt->flags & FL_SHIELDED)) { // stopped cold return; } - //a Jedi is not dodging this shot + // a Jedi is not dodging this shot break; } - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_MAIN_SHOT ); - VectorCopy( muzzle, tent->s.origin2 ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_MAIN_SHOT); + VectorCopy(muzzle, tent->s.origin2); tent->s.eventParm = ent->s.number; traceEnt = &g_entities[tr.entityNum]; - if ( render_impact ) - { - if ( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - { - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - { + if (render_impact) { + if (tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) { + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { ent->client->accuracy_hits++; } - G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NORMAL, MOD_DISRUPTOR ); + G_Damage(traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NORMAL, MOD_DISRUPTOR); - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_HIT ); - tent->s.eventParm = DirToByte( tr.plane.normal ); - if (traceEnt->client) - { + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_HIT); + tent->s.eventParm = DirToByte(tr.plane.normal); + if (traceEnt->client) { tent->s.weapon = 1; } - } - else - { - // Hmmm, maybe don't make any marks on things that could break - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_MISS ); - tent->s.eventParm = DirToByte( tr.plane.normal ); + } else { + // Hmmm, maybe don't make any marks on things that could break + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_MISS); + tent->s.eventParm = DirToByte(tr.plane.normal); tent->s.weapon = 1; } } } - -qboolean G_CanDisruptify(gentity_t *ent) -{ - if (!ent || !ent->inuse || !ent->client || ent->s.eType != ET_NPC || - ent->s.NPC_class != CLASS_VEHICLE || !ent->m_pVehicle) - { //not vehicle +qboolean G_CanDisruptify(gentity_t *ent) { + if (!ent || !ent->inuse || !ent->client || ent->s.eType != ET_NPC || ent->s.NPC_class != CLASS_VEHICLE || !ent->m_pVehicle) { // not vehicle return qtrue; } - if (ent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) - { //animal is only type that can be disintigeiteigerated + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { // animal is only type that can be disintigeiteigerated return qtrue; } - //don't do it to any other veh + // don't do it to any other veh return qfalse; } //--------------------------------------------------------- -void WP_DisruptorAltFire( gentity_t *ent ) +void WP_DisruptorAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = 0, skip; - qboolean render_impact = qtrue; - vec3_t start, end; - //vec3_t muzzle2; - trace_t tr; - gentity_t *traceEnt, *tent; - float shotRange = 8192.0f; - int i; - int count, maxCount = 60; - int traces = DISRUPTOR_ALT_TRACES; - qboolean fullCharge = qfalse; - - damage = DISRUPTOR_ALT_DAMAGE-30; - - //VectorCopy( muzzle, muzzle2 ); // making a backup copy - - if (ent->client) - { - VectorCopy( ent->client->ps.origin, start ); - start[2] += ent->client->ps.viewheight;//By eyes - - count = ( level.time - ent->client->ps.weaponChargeTime ) / DISRUPTOR_CHARGE_UNIT; - if ( level.gametype == GT_SIEGE ) - {//maybe a full alt-charge should be a *bit* more dangerous in Siege mode? - //maxCount = ceil((200.0f-(float)damage)/2.0f);//cap at 200 damage total - maxCount = 200;//the previous line ALWAYS evaluated to 135 - was that on purpose? + int damage = 0, skip; + qboolean render_impact = qtrue; + vec3_t start, end; + // vec3_t muzzle2; + trace_t tr; + gentity_t *traceEnt, *tent; + float shotRange = 8192.0f; + int i; + int count, maxCount = 60; + int traces = DISRUPTOR_ALT_TRACES; + qboolean fullCharge = qfalse; + + damage = DISRUPTOR_ALT_DAMAGE - 30; + + // VectorCopy( muzzle, muzzle2 ); // making a backup copy + + if (ent->client) { + VectorCopy(ent->client->ps.origin, start); + start[2] += ent->client->ps.viewheight; // By eyes + + count = (level.time - ent->client->ps.weaponChargeTime) / DISRUPTOR_CHARGE_UNIT; + if (level.gametype == GT_SIEGE) { // maybe a full alt-charge should be a *bit* more dangerous in Siege mode? + // maxCount = ceil((200.0f-(float)damage)/2.0f);//cap at 200 damage total + maxCount = 200; // the previous line ALWAYS evaluated to 135 - was that on purpose? } - } - else - { - VectorCopy( ent->r.currentOrigin, start ); + } else { + VectorCopy(ent->r.currentOrigin, start); start[2] += 24; - count = ( 100 ) / DISRUPTOR_CHARGE_UNIT; + count = (100) / DISRUPTOR_CHARGE_UNIT; } count *= 2; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count >= maxCount ) - { + } else if (count >= maxCount) { count = maxCount; fullCharge = qtrue; } // more powerful charges go through more things - if ( count < 10 ) - { + if (count < 10) { traces = 1; - } - else if ( count < 20 ) - { + } else if (count < 20) { traces = 2; } @@ -774,104 +703,88 @@ void WP_DisruptorAltFire( gentity_t *ent ) skip = ent->s.number; - for (i = 0; i < traces; i++ ) - { - VectorMA( start, shotRange, forward, end ); + for (i = 0; i < traces; i++) { + VectorMA(start, shotRange, forward, end); - if (d_projectileGhoul2Collision.integer) - { - trap->Trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_THICK|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); - } - else - { - trap->Trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, qfalse, 0, 0 ); + if (d_projectileGhoul2Collision.integer) { + trap->Trace(&tr, start, NULL, NULL, end, skip, MASK_SHOT, qfalse, + G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_THICK | G2TRFLAG_HITCORPSES, g_g2TraceLod.integer); + } else { + trap->Trace(&tr, start, NULL, NULL, end, skip, MASK_SHOT, qfalse, 0, 0); } - if ( tr.entityNum == ent->s.number ) - { + if (tr.entityNum == ent->s.number) { // should never happen, but basically we don't want to consider a hit to ourselves? // Get ready for an attempt to trace through another person - //VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + // VectorCopy( tr.endpos, muzzle2 ); + VectorCopy(tr.endpos, start); skip = tr.entityNum; #ifdef _DEBUG - trap->Print( "BAD! Disruptor gun shot somehow traced back and hit the owner!\n" ); + trap->Print("BAD! Disruptor gun shot somehow traced back and hit the owner!\n"); #endif continue; } traceEnt = &g_entities[tr.entityNum]; - if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) - { //g2 collision checks -rww - if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) - { //since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the index of the surface on the ghoul2 model we collided with. + if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) { // g2 collision checks -rww + if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) { // since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the + // index of the surface on the ghoul2 model we collided with. traceEnt->client->g2LastSurfaceHit = tr.surfaceFlags; traceEnt->client->g2LastSurfaceTime = level.time; } - if (traceEnt->ghoul2) - { - tr.surfaceFlags = 0; //clear the surface flags after, since we actually care about them in here. + if (traceEnt->ghoul2) { + tr.surfaceFlags = 0; // clear the surface flags after, since we actually care about them in here. } } - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } - if (traceEnt && traceEnt->client && traceEnt->client->ps.duelInProgress && - traceEnt->client->ps.duelIndex != ent->s.number) - { + if (traceEnt && traceEnt->client && traceEnt->client->ps.duelInProgress && traceEnt->client->ps.duelIndex != ent->s.number) { skip = tr.entityNum; VectorCopy(tr.endpos, start); continue; } - if (Jedi_DodgeEvasion(traceEnt, ent, &tr, G_GetHitLocation(traceEnt, tr.endpos))) - { + if (Jedi_DodgeEvasion(traceEnt, ent, &tr, G_GetHitLocation(traceEnt, tr.endpos))) { skip = tr.entityNum; VectorCopy(tr.endpos, start); continue; - } - else if (traceEnt && traceEnt->client && traceEnt->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= FORCE_LEVEL_3) - { - if (WP_SaberCanBlock(traceEnt, tr.endpos, 0, MOD_DISRUPTOR_SNIPER, qtrue, 0)) - { //broadcast and stop the shot because it was blocked + } else if (traceEnt && traceEnt->client && traceEnt->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= FORCE_LEVEL_3) { + if (WP_SaberCanBlock(traceEnt, tr.endpos, 0, MOD_DISRUPTOR_SNIPER, qtrue, 0)) { // broadcast and stop the shot because it was blocked gentity_t *te = NULL; - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); - VectorCopy( muzzle, tent->s.origin2 ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_SHOT); + VectorCopy(muzzle, tent->s.origin2); tent->s.shouldtarget = fullCharge; tent->s.eventParm = ent->s.number; - te = G_TempEntity( tr.endpos, EV_SABER_BLOCK ); + te = G_TempEntity(tr.endpos, EV_SABER_BLOCK); VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { te->s.angles[1] = 1; } te->s.eventParm = 0; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum return; } } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_SHOT ); - VectorCopy( muzzle, tent->s.origin2 ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_SHOT); + VectorCopy(muzzle, tent->s.origin2); tent->s.shouldtarget = fullCharge; tent->s.eventParm = ent->s.number; // If the beam hits a skybox, etc. it would look foolish to add impact effects - if ( render_impact ) - { - if ( traceEnt->takedamage && traceEnt->client ) - { + if (render_impact) { + if (traceEnt->takedamage && traceEnt->client) { tent->s.otherEntityNum = traceEnt->s.number; // Create a simple impact type mark @@ -879,62 +792,47 @@ void WP_DisruptorAltFire( gentity_t *ent ) tent->s.eventParm = DirToByte(tr.plane.normal); tent->s.eFlags |= EF_ALT_FIRING; - if ( LogAccuracyHit( traceEnt, ent )) - { - if (ent->client) - { + if (LogAccuracyHit(traceEnt, ent)) { + if (ent->client) { ent->client->accuracy_hits++; } } - } - else - { - if ( traceEnt->r.svFlags & SVF_GLASS_BRUSH - || traceEnt->takedamage - || traceEnt->s.eType == ET_MOVER ) - { - if ( traceEnt->takedamage ) - { - G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, - DAMAGE_NO_KNOCKBACK, MOD_DISRUPTOR_SNIPER ); + } else { + if (traceEnt->r.svFlags & SVF_GLASS_BRUSH || traceEnt->takedamage || traceEnt->s.eType == ET_MOVER) { + if (traceEnt->takedamage) { + G_Damage(traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_DISRUPTOR_SNIPER); - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_HIT ); - tent->s.eventParm = DirToByte( tr.plane.normal ); + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_HIT); + tent->s.eventParm = DirToByte(tr.plane.normal); } - } - else - { - // Hmmm, maybe don't make any marks on things that could break - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_SNIPER_MISS ); - tent->s.eventParm = DirToByte( tr.plane.normal ); - } + } else { + // Hmmm, maybe don't make any marks on things that could break + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_SNIPER_MISS); + tent->s.eventParm = DirToByte(tr.plane.normal); + } break; // and don't try any more traces } - if ( (traceEnt->flags&FL_SHIELDED) ) - {//stops us cold + if ((traceEnt->flags & FL_SHIELDED)) { // stops us cold break; } - if ( traceEnt->takedamage ) - { + if (traceEnt->takedamage) { vec3_t preAng; int preHealth = traceEnt->health; int preLegs = 0; int preTorso = 0; - if (traceEnt->client) - { + if (traceEnt->client) { preLegs = traceEnt->client->ps.legsAnim; preTorso = traceEnt->client->ps.torsoAnim; VectorCopy(traceEnt->client->ps.viewangles, preAng); } - G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_DISRUPTOR_SNIPER ); + G_Damage(traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NO_KNOCKBACK, MOD_DISRUPTOR_SNIPER); if (traceEnt->client && preHealth > 0 && traceEnt->health <= 0 && fullCharge && - G_CanDisruptify(traceEnt)) - { //was killed by a fully charged sniper shot, so disintegrate + G_CanDisruptify(traceEnt)) { // was killed by a fully charged sniper shot, so disintegrate VectorCopy(preAng, traceEnt->client->ps.viewangles); traceEnt->client->ps.eFlags |= EF_DISINTEGRATION; @@ -948,53 +846,44 @@ void WP_DisruptorAltFire( gentity_t *ent ) VectorClear(traceEnt->client->ps.velocity); } - tent = G_TempEntity( tr.endpos, EV_DISRUPTOR_HIT ); - tent->s.eventParm = DirToByte( tr.plane.normal ); - if (traceEnt->client) - { + tent = G_TempEntity(tr.endpos, EV_DISRUPTOR_HIT); + tent->s.eventParm = DirToByte(tr.plane.normal); + if (traceEnt->client) { tent->s.weapon = 1; } } - } - else // not rendering impact, must be a skybox or other similar thing? + } else // not rendering impact, must be a skybox or other similar thing? { break; // don't try anymore traces } // Get ready for an attempt to trace through another person - VectorCopy( tr.endpos, muzzle ); - VectorCopy( tr.endpos, start ); + VectorCopy(tr.endpos, muzzle); + VectorCopy(tr.endpos, start); skip = tr.entityNum; } } - //--------------------------------------------------------- -static void WP_FireDisruptor( gentity_t *ent, qboolean altFire ) +static void WP_FireDisruptor(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - if (!ent || !ent->client || ent->client->ps.zoomMode != 1) - { //do not ever let it do the alt fire when not zoomed + if (!ent || !ent->client || ent->client->ps.zoomMode != 1) { // do not ever let it do the alt fire when not zoomed altFire = qfalse; } - if (ent && ent->s.eType == ET_NPC && !ent->client) - { //special case for animents - WP_DisruptorAltFire( ent ); + if (ent && ent->s.eType == ET_NPC && !ent->client) { // special case for animents + WP_DisruptorAltFire(ent); return; } - if ( altFire ) - { - WP_DisruptorAltFire( ent ); - } - else - { - WP_DisruptorMainFire( ent ); + if (altFire) { + WP_DisruptorAltFire(ent); + } else { + WP_DisruptorMainFire(ent); } } - /* ====================================================================== @@ -1003,17 +892,16 @@ BOWCASTER ====================================================================== */ -static void WP_BowcasterAltFire( gentity_t *ent ) -{ - int damage = BOWCASTER_DAMAGE; +static void WP_BowcasterAltFire(gentity_t *ent) { + int damage = BOWCASTER_DAMAGE; - gentity_t *missile = CreateMissile( muzzle, forward, BOWCASTER_VELOCITY, 10000, ent, qfalse); + gentity_t *missile = CreateMissile(muzzle, forward, BOWCASTER_VELOCITY, 10000, ent, qfalse); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -1025,81 +913,64 @@ static void WP_BowcasterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_BowcasterMainFire( gentity_t *ent ) +static void WP_BowcasterMainFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = BOWCASTER_DAMAGE, count; - float vel; - vec3_t angs, dir; - gentity_t *missile; + int damage = BOWCASTER_DAMAGE, count; + float vel; + vec3_t angs, dir; + gentity_t *missile; int i; - if (!ent->client) - { + if (!ent->client) { count = 1; - } - else - { - count = ( level.time - ent->client->ps.weaponChargeTime ) / BOWCASTER_CHARGE_UNIT; + } else { + count = (level.time - ent->client->ps.weaponChargeTime) / BOWCASTER_CHARGE_UNIT; } - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 5 ) - { + } else if (count > 5) { count = 5; } - if ( !(count & 1 )) - { + if (!(count & 1)) { // if we aren't odd, knock us down a level count--; } - //scale the damage down based on how many are about to be fired - if (count <= 1) - { + // scale the damage down based on how many are about to be fired + if (count <= 1) { damage = 50; - } - else if (count == 2) - { + } else if (count == 2) { damage = 45; - } - else if (count == 3) - { + } else if (count == 3) { damage = 40; - } - else if (count == 4) - { + } else if (count == 4) { damage = 35; - } - else - { + } else { damage = 30; } - for (i = 0; i < count; i++ ) - { + for (i = 0; i < count; i++) { // create a range of different velocities - vel = BOWCASTER_VELOCITY * ( Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f ); + vel = BOWCASTER_VELOCITY * (Q_flrand(-1.0f, 1.0f) * BOWCASTER_VEL_RANGE + 1.0f); - vectoangles( forward, angs ); + vectoangles(forward, angs); // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * BOWCASTER_ALT_SPREAD * 0.2f; - angs[YAW] += ((i+0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD ); + angs[YAW] += ((i + 0.5f) * BOWCASTER_ALT_SPREAD - count * 0.5f * BOWCASTER_ALT_SPREAD); - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); - missile = CreateMissile( muzzle, dir, vel, 10000, ent, qtrue ); + missile = CreateMissile(muzzle, dir, vel, 10000, ent, qtrue); missile->classname = "bowcaster_alt_proj"; missile->s.weapon = WP_BOWCASTER; - VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -1112,21 +983,16 @@ static void WP_BowcasterMainFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_FireBowcaster( gentity_t *ent, qboolean altFire ) +static void WP_FireBowcaster(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - if ( altFire ) - { - WP_BowcasterAltFire( ent ); - } - else - { - WP_BowcasterMainFire( ent ); + if (altFire) { + WP_BowcasterAltFire(ent); + } else { + WP_BowcasterMainFire(ent); } } - - /* ====================================================================== @@ -1136,12 +1002,12 @@ REPEATER */ //--------------------------------------------------------- -static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) +static void WP_RepeaterMainFire(gentity_t *ent, vec3_t dir) //--------------------------------------------------------- { - int damage = REPEATER_DAMAGE; + int damage = REPEATER_DAMAGE; - gentity_t *missile = CreateMissile( muzzle, dir, REPEATER_VELOCITY, 10000, ent, qfalse ); + gentity_t *missile = CreateMissile(muzzle, dir, REPEATER_VELOCITY, 10000, ent, qfalse); missile->classname = "repeater_proj"; missile->s.weapon = WP_REPEATER; @@ -1156,32 +1022,30 @@ static void WP_RepeaterMainFire( gentity_t *ent, vec3_t dir ) } //--------------------------------------------------------- -static void WP_RepeaterAltFire( gentity_t *ent ) +static void WP_RepeaterAltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = REPEATER_ALT_DAMAGE; + int damage = REPEATER_ALT_DAMAGE; - gentity_t *missile = CreateMissile( muzzle, forward, REPEATER_ALT_VELOCITY, 10000, ent, qtrue ); + gentity_t *missile = CreateMissile(muzzle, forward, REPEATER_ALT_VELOCITY, 10000, ent, qtrue); missile->classname = "repeater_alt_proj"; missile->s.weapon = WP_REPEATER; - VectorSet( missile->r.maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE, REPEATER_ALT_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->s.pos.trType = TR_GRAVITY; - missile->s.pos.trDelta[2] += 40.0f; //give a slight boost in the upward direction + missile->s.pos.trDelta[2] += 40.0f; // give a slight boost in the upward direction missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_REPEATER_ALT; missile->splashMethodOfDeath = MOD_REPEATER_ALT_SPLASH; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = REPEATER_ALT_SPLASH_DAMAGE; - if ( level.gametype == GT_SIEGE ) // we've been having problems with this being too hyper-potent because of it's radius + if (level.gametype == GT_SIEGE) // we've been having problems with this being too hyper-potent because of it's radius { missile->splashRadius = REPEATER_ALT_SPLASH_RAD_SIEGE; - } - else - { + } else { missile->splashRadius = REPEATER_ALT_SPLASH_RADIUS; } @@ -1190,30 +1054,26 @@ static void WP_RepeaterAltFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_FireRepeater( gentity_t *ent, qboolean altFire ) +static void WP_FireRepeater(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - vec3_t dir, angs; + vec3_t dir, angs; - vectoangles( forward, angs ); + vectoangles(forward, angs); - if ( altFire ) - { - WP_RepeaterAltFire( ent ); - } - else - { + if (altFire) { + WP_RepeaterAltFire(ent); + } else { // add some slop to the alt-fire direction angs[PITCH] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * REPEATER_SPREAD; - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); - WP_RepeaterMainFire( ent, dir ); + WP_RepeaterMainFire(ent, dir); } } - /* ====================================================================== @@ -1222,17 +1082,16 @@ DEMP2 ====================================================================== */ -static void WP_DEMP2_MainFire( gentity_t *ent ) -{ - int damage = DEMP2_DAMAGE; +static void WP_DEMP2_MainFire(gentity_t *ent) { + int damage = DEMP2_DAMAGE; - gentity_t *missile = CreateMissile( muzzle, forward, DEMP2_VELOCITY, 10000, ent, qfalse); + gentity_t *missile = CreateMissile(muzzle, forward, DEMP2_VELOCITY, 10000, ent, qfalse); missile->classname = "demp2_proj"; missile->s.weapon = WP_DEMP2; - VectorSet( missile->r.maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, DEMP2_SIZE, DEMP2_SIZE, DEMP2_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_DEMP2; @@ -1244,26 +1103,22 @@ static void WP_DEMP2_MainFire( gentity_t *ent ) static gentity_t *ent_list[MAX_GENTITIES]; -void DEMP2_AltRadiusDamage( gentity_t *ent ) -{ - float frac = ( level.time - ent->genericValue5 ) / 800.0f; // / 1600.0f; // synchronize with demp2 effect - float dist, radius, fact; - gentity_t *gent; - int iEntityList[MAX_GENTITIES]; - gentity_t *entityList[MAX_GENTITIES]; - gentity_t *myOwner = NULL; - int numListedEntities, i, e; - vec3_t mins, maxs; - vec3_t v, dir; - - if (ent->r.ownerNum >= 0 && - ent->r.ownerNum < /*MAX_CLIENTS ... let npc's/shooters use it*/MAX_GENTITIES) - { +void DEMP2_AltRadiusDamage(gentity_t *ent) { + float frac = (level.time - ent->genericValue5) / 800.0f; // / 1600.0f; // synchronize with demp2 effect + float dist, radius, fact; + gentity_t *gent; + int iEntityList[MAX_GENTITIES]; + gentity_t *entityList[MAX_GENTITIES]; + gentity_t *myOwner = NULL; + int numListedEntities, i, e; + vec3_t mins, maxs; + vec3_t v, dir; + + if (ent->r.ownerNum >= 0 && ent->r.ownerNum < /*MAX_CLIENTS ... let npc's/shooters use it*/ MAX_GENTITIES) { myOwner = &g_entities[ent->r.ownerNum]; } - if (!myOwner || !myOwner->inuse || !myOwner->client) - { + if (!myOwner || !myOwner->inuse || !myOwner->client) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; @@ -1273,52 +1128,41 @@ void DEMP2_AltRadiusDamage( gentity_t *ent ) radius = frac * 200.0f; // 200 is max radius...the model is aprox. 100 units tall...the fx draw code mults. this by 2. - fact = ent->count*0.6; + fact = ent->count * 0.6; - if (fact < 1) - { + if (fact < 1) { fact = 1; } radius *= fact; - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = ent->r.currentOrigin[i] - radius; maxs[i] = ent->r.currentOrigin[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, iEntityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, iEntityList, MAX_GENTITIES); i = 0; - while (i < numListedEntities) - { + while (i < numListedEntities) { entityList[i] = &g_entities[iEntityList[i]]; i++; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - gent = entityList[ e ]; + for (e = 0; e < numListedEntities; e++) { + gent = entityList[e]; - if ( !gent || !gent->takedamage || !gent->r.contents ) - { + if (!gent || !gent->takedamage || !gent->r.contents) { continue; } // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( ent->r.currentOrigin[i] < gent->r.absmin[i] ) - { + for (i = 0; i < 3; i++) { + if (ent->r.currentOrigin[i] < gent->r.absmin[i]) { v[i] = gent->r.absmin[i] - ent->r.currentOrigin[i]; - } - else if ( ent->r.currentOrigin[i] > gent->r.absmax[i] ) - { + } else if (ent->r.currentOrigin[i] > gent->r.absmax[i]) { v[i] = ent->r.currentOrigin[i] - gent->r.absmax[i]; - } - else - { + } else { v[i] = 0; } } @@ -1326,86 +1170,73 @@ void DEMP2_AltRadiusDamage( gentity_t *ent ) // shape is an ellipsoid, so cut vertical distance in half` v[2] *= 0.5f; - dist = VectorLength( v ); + dist = VectorLength(v); - if ( dist >= radius ) - { + if (dist >= radius) { // shockwave hasn't hit them yet continue; } - if (dist+(16*ent->count) < ent->genericValue6) - { + if (dist + (16 * ent->count) < ent->genericValue6) { // shockwave has already hit this thing... continue; } - VectorCopy( gent->r.currentOrigin, v ); - VectorSubtract( v, ent->r.currentOrigin, dir); + VectorCopy(gent->r.currentOrigin, v); + VectorSubtract(v, ent->r.currentOrigin, dir); // push the center of mass higher than the origin so players get knocked into the air more dir[2] += 12; - if (gent != myOwner) - { - G_Damage( gent, myOwner, myOwner, dir, ent->r.currentOrigin, ent->damage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath ); - if ( gent->takedamage - && gent->client ) - { - if ( gent->client->ps.electrifyTime < level.time ) - {//electrocution effect - if (gent->s.eType == ET_NPC && gent->s.NPC_class == CLASS_VEHICLE && - gent->m_pVehicle && (gent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || gent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER)) - { //do some extra stuff to speeders/walkers - gent->client->ps.electrifyTime = level.time + Q_irand( 3000, 4000 ); - } - else if ( gent->s.NPC_class != CLASS_VEHICLE - || (gent->m_pVehicle && gent->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER) ) - {//don't do this to fighters - gent->client->ps.electrifyTime = level.time + Q_irand( 300, 800 ); + if (gent != myOwner) { + G_Damage(gent, myOwner, myOwner, dir, ent->r.currentOrigin, ent->damage, DAMAGE_DEATH_KNOCKBACK, ent->splashMethodOfDeath); + if (gent->takedamage && gent->client) { + if (gent->client->ps.electrifyTime < level.time) { // electrocution effect + if (gent->s.eType == ET_NPC && gent->s.NPC_class == CLASS_VEHICLE && gent->m_pVehicle && + (gent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || + gent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER)) { // do some extra stuff to speeders/walkers + gent->client->ps.electrifyTime = level.time + Q_irand(3000, 4000); + } else if (gent->s.NPC_class != CLASS_VEHICLE || + (gent->m_pVehicle && gent->m_pVehicle->m_pVehicleInfo->type != VH_FIGHTER)) { // don't do this to fighters + gent->client->ps.electrifyTime = level.time + Q_irand(300, 800); } } - if ( gent->client->ps.powerups[PW_CLOAKED] ) - {//disable cloak temporarily - Jedi_Decloak( gent ); - gent->client->cloakToggleTime = level.time + Q_irand( 3000, 10000 ); + if (gent->client->ps.powerups[PW_CLOAKED]) { // disable cloak temporarily + Jedi_Decloak(gent); + gent->client->cloakToggleTime = level.time + Q_irand(3000, 10000); } } } } - // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge is + // store the last fraction so that next time around we can test against those things that fall between that last point and where the current shockwave edge + // is ent->genericValue6 = radius; - if ( frac < 1.0f ) - { + if (frac < 1.0f) { // shock is still happening so continue letting it expand ent->nextthink = level.time + 50; - } - else - { //don't just leave the entity around + } else { // don't just leave the entity around ent->think = G_FreeEntity; ent->nextthink = level.time; } } //--------------------------------------------------------- -void DEMP2_AltDetonate( gentity_t *ent ) +void DEMP2_AltDetonate(gentity_t *ent) //--------------------------------------------------------- { gentity_t *efEnt; - G_SetOrigin( ent, ent->r.currentOrigin ); - if (!ent->pos1[0] && !ent->pos1[1] && !ent->pos1[2]) - { //don't play effect with a 0'd out directional vector + G_SetOrigin(ent, ent->r.currentOrigin); + if (!ent->pos1[0] && !ent->pos1[1] && !ent->pos1[2]) { // don't play effect with a 0'd out directional vector ent->pos1[1] = 1; } - //Let's just save ourself some bandwidth and play both the effect and sphere spawn in 1 event - efEnt = G_PlayEffect( EFFECT_EXPLOSION_DEMP2ALT, ent->r.currentOrigin, ent->pos1 ); + // Let's just save ourself some bandwidth and play both the effect and sphere spawn in 1 event + efEnt = G_PlayEffect(EFFECT_EXPLOSION_DEMP2ALT, ent->r.currentOrigin, ent->pos1); - if (efEnt) - { - efEnt->s.weapon = ent->count*2; + if (efEnt) { + efEnt->s.weapon = ent->count * 2; } ent->genericValue5 = level.time; @@ -1416,53 +1247,48 @@ void DEMP2_AltDetonate( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_DEMP2_AltFire( gentity_t *ent ) +static void WP_DEMP2_AltFire(gentity_t *ent) //--------------------------------------------------------- { - int damage = DEMP2_ALT_DAMAGE; - int count, origcount; - float fact; - vec3_t start, end; - trace_t tr; + int damage = DEMP2_ALT_DAMAGE; + int count, origcount; + float fact; + vec3_t start, end; + trace_t tr; gentity_t *missile; - VectorCopy( muzzle, start ); + VectorCopy(muzzle, start); - VectorMA( start, DEMP2_ALT_RANGE, forward, end ); + VectorMA(start, DEMP2_ALT_RANGE, forward, end); - count = ( level.time - ent->client->ps.weaponChargeTime ) / DEMP2_CHARGE_UNIT; + count = (level.time - ent->client->ps.weaponChargeTime) / DEMP2_CHARGE_UNIT; origcount = count; - if ( count < 1 ) - { + if (count < 1) { count = 1; - } - else if ( count > 3 ) - { + } else if (count > 3) { count = 3; } - fact = count*0.8; - if (fact < 1) - { + fact = count * 0.8; + if (fact < 1) { fact = 1; } damage *= fact; - if (!origcount) - { //this was just a tap-fire + if (!origcount) { // this was just a tap-fire damage = 1; } - trap->Trace( &tr, start, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); + trap->Trace(&tr, start, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); missile = G_Spawn(); G_SetOrigin(missile, tr.endpos); - //In SP the impact actually travels as a missile based on the trace fraction, but we're - //just going to be instant. -rww + // In SP the impact actually travels as a missile based on the trace fraction, but we're + // just going to be instant. -rww - VectorCopy( tr.plane.normal, missile->pos1 ); + VectorCopy(tr.plane.normal, missile->pos1); missile->count = count; @@ -1486,21 +1312,16 @@ static void WP_DEMP2_AltFire( gentity_t *ent ) } //--------------------------------------------------------- -static void WP_FireDEMP2( gentity_t *ent, qboolean altFire ) +static void WP_FireDEMP2(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - if ( altFire ) - { - WP_DEMP2_AltFire( ent ); - } - else - { - WP_DEMP2_MainFire( ent ); + if (altFire) { + WP_DEMP2_AltFire(ent); + } else { + WP_DEMP2_MainFire(ent); } } - - /* ====================================================================== @@ -1510,32 +1331,30 @@ FLECHETTE */ //--------------------------------------------------------- -static void WP_FlechetteMainFire( gentity_t *ent ) +static void WP_FlechetteMainFire(gentity_t *ent) //--------------------------------------------------------- { - vec3_t fwd, angs; - gentity_t *missile; + vec3_t fwd, angs; + gentity_t *missile; int i; - for (i = 0; i < FLECHETTE_SHOTS; i++ ) - { - vectoangles( forward, angs ); + for (i = 0; i < FLECHETTE_SHOTS; i++) { + vectoangles(forward, angs); - if (i != 0) - { //do nothing on the first shot, it will hit the crosshairs + if (i != 0) { // do nothing on the first shot, it will hit the crosshairs angs[PITCH] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; - angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; + angs[YAW] += Q_flrand(-1.0f, 1.0f) * FLECHETTE_SPREAD; } - AngleVectors( angs, fwd, NULL, NULL ); + AngleVectors(angs, fwd, NULL, NULL); - missile = CreateMissile( muzzle, fwd, FLECHETTE_VEL, 10000, ent, qfalse); + missile = CreateMissile(muzzle, fwd, FLECHETTE_VEL, 10000, ent, qfalse); missile->classname = "flech_proj"; missile->s.weapon = WP_FLECHETTE; - VectorSet( missile->r.maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, FLECHETTE_SIZE, FLECHETTE_SIZE, FLECHETTE_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = FLECHETTE_DAMAGE; missile->dflags = DAMAGE_DEATH_KNOCKBACK; @@ -1543,93 +1362,78 @@ static void WP_FlechetteMainFire( gentity_t *ent ) missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; // we don't want it to bounce forever - missile->bounceCount = Q_irand(5,8); + missile->bounceCount = Q_irand(5, 8); missile->flags |= FL_BOUNCE_SHRAPNEL; } } //--------------------------------------------------------- -void prox_mine_think( gentity_t *ent ) +void prox_mine_think(gentity_t *ent) //--------------------------------------------------------- { - int count, i; - qboolean blow = qfalse; + int count, i; + qboolean blow = qfalse; // if it isn't time to auto-explode, do a small proximity check - if ( ent->delay > level.time ) - { - count = G_RadiusList( ent->r.currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list ); + if (ent->delay > level.time) { + count = G_RadiusList(ent->r.currentOrigin, FLECHETTE_MINE_RADIUS_CHECK, ent, qtrue, ent_list); - for ( i = 0; i < count; i++ ) - { - if ( ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number ) - { + for (i = 0; i < count; i++) { + if (ent_list[i]->client && ent_list[i]->health > 0 && ent->activator && ent_list[i]->s.number != ent->activator->s.number) { blow = qtrue; break; } } - } - else - { + } else { // well, we must die now blow = qtrue; } - if ( blow ) - { + if (blow) { ent->think = laserTrapExplode; ent->nextthink = level.time + 200; - } - else - { + } else { // we probably don't need to do this thinking logic very often...maybe this is fast enough? ent->nextthink = level.time + 500; } } //----------------------------------------------------------------------------- -static void WP_TraceSetStart( gentity_t *ent, vec3_t start, vec3_t mins, vec3_t maxs ) +static void WP_TraceSetStart(gentity_t *ent, vec3_t start, vec3_t mins, vec3_t maxs) //----------------------------------------------------------------------------- { - //make sure our start point isn't on the other side of a wall - trace_t tr; - vec3_t entMins; - vec3_t entMaxs; + // make sure our start point isn't on the other side of a wall + trace_t tr; + vec3_t entMins; + vec3_t entMaxs; - VectorAdd( ent->r.currentOrigin, ent->r.mins, entMins ); - VectorAdd( ent->r.currentOrigin, ent->r.maxs, entMaxs ); + VectorAdd(ent->r.currentOrigin, ent->r.mins, entMins); + VectorAdd(ent->r.currentOrigin, ent->r.maxs, entMaxs); - if ( G_BoxInBounds( start, mins, maxs, entMins, entMaxs ) ) - { + if (G_BoxInBounds(start, mins, maxs, entMins, entMaxs)) { return; } - if ( !ent->client ) - { + if (!ent->client) { return; } - trap->Trace( &tr, ent->client->ps.origin, mins, maxs, start, ent->s.number, MASK_SOLID|CONTENTS_SHOTCLIP, qfalse, 0, 0 ); + trap->Trace(&tr, ent->client->ps.origin, mins, maxs, start, ent->s.number, MASK_SOLID | CONTENTS_SHOTCLIP, qfalse, 0, 0); - if ( tr.startsolid || tr.allsolid ) - { + if (tr.startsolid || tr.allsolid) { return; } - if ( tr.fraction < 1.0f ) - { - VectorCopy( tr.endpos, start ); + if (tr.fraction < 1.0f) { + VectorCopy(tr.endpos, start); } } -void WP_ExplosiveDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ - laserTrapExplode(self); -} +void WP_ExplosiveDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { laserTrapExplode(self); } //---------------------------------------------- -void WP_flechette_alt_blow( gentity_t *ent ) +void WP_flechette_alt_blow(gentity_t *ent) //---------------------------------------------- { ent->s.pos.trDelta[0] = 1; @@ -1640,10 +1444,10 @@ void WP_flechette_alt_blow( gentity_t *ent ) } //------------------------------------------------------------------------------ -static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t *self ) +static void WP_CreateFlechetteBouncyThing(vec3_t start, vec3_t fwd, gentity_t *self) //------------------------------------------------------------------------------ { - gentity_t *missile = CreateMissile( start, fwd, 700 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue ); + gentity_t *missile = CreateMissile(start, fwd, 700 + Q_flrand(0.0f, 1.0f) * 700, 1500 + Q_flrand(0.0f, 1.0f) * 2000, self, qtrue); missile->think = WP_flechette_alt_blow; @@ -1654,8 +1458,8 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->mass = 4; // How 'bout we give this thing a size... - VectorSet( missile->r.mins, -3.0f, -3.0f, -3.0f ); - VectorSet( missile->r.maxs, 3.0f, 3.0f, 3.0f ); + VectorSet(missile->r.mins, -3.0f, -3.0f, -3.0f); + VectorSet(missile->r.maxs, 3.0f, 3.0f, 3.0f); missile->clipmask = MASK_SHOT; missile->touch = touch_NULL; @@ -1678,50 +1482,44 @@ static void WP_CreateFlechetteBouncyThing( vec3_t start, vec3_t fwd, gentity_t * missile->methodOfDeath = MOD_FLECHETTE_ALT_SPLASH; missile->splashMethodOfDeath = MOD_FLECHETTE_ALT_SPLASH; - VectorCopy( start, missile->pos2 ); + VectorCopy(start, missile->pos2); } //--------------------------------------------------------- -static void WP_FlechetteAltFire( gentity_t *self ) +static void WP_FlechetteAltFire(gentity_t *self) //--------------------------------------------------------- { - vec3_t dir, fwd, start, angs; + vec3_t dir, fwd, start, angs; int i; - vectoangles( forward, angs ); - VectorCopy( muzzle, start ); + vectoangles(forward, angs); + VectorCopy(muzzle, start); - WP_TraceSetStart( self, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + WP_TraceSetStart(self, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - for ( i = 0; i < 2; i++ ) - { - VectorCopy( angs, dir ); + for (i = 0; i < 2; i++) { + VectorCopy(angs, dir); dir[PITCH] -= Q_flrand(0.0f, 1.0f) * 4 + 8; // make it fly upwards dir[YAW] += Q_flrand(-1.0f, 1.0f) * 2; - AngleVectors( dir, fwd, NULL, NULL ); + AngleVectors(dir, fwd, NULL, NULL); - WP_CreateFlechetteBouncyThing( start, fwd, self ); + WP_CreateFlechetteBouncyThing(start, fwd, self); } } //--------------------------------------------------------- -static void WP_FireFlechette( gentity_t *ent, qboolean altFire ) +static void WP_FireFlechette(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - if ( altFire ) - { - //WP_FlechetteProxMine( ent ); + if (altFire) { + // WP_FlechetteProxMine( ent ); WP_FlechetteAltFire(ent); - } - else - { - WP_FlechetteMainFire( ent ); + } else { + WP_FlechetteMainFire(ent); } } - - /* ====================================================================== @@ -1731,72 +1529,56 @@ ROCKET LAUNCHER */ //--------------------------------------------------------- -void rocketThink( gentity_t *ent ) +void rocketThink(gentity_t *ent) //--------------------------------------------------------- { - vec3_t newdir, targetdir, - rup={0,0,1}, right; - vec3_t org; + vec3_t newdir, targetdir, rup = {0, 0, 1}, right; + vec3_t org; float dot, dot2, dis; int i; - float vel = (ent->spawnflags&1)?ent->speed:ROCKET_VELOCITY; + float vel = (ent->spawnflags & 1) ? ent->speed : ROCKET_VELOCITY; - if ( ent->genericValue1 && ent->genericValue1 < level.time ) - {//time's up, we're done, remove us - if ( ent->genericValue2 ) - {//explode when die - RocketDie( ent, &g_entities[ent->r.ownerNum], &g_entities[ent->r.ownerNum], 0, MOD_UNKNOWN ); - } - else - {//just remove when die - G_FreeEntity( ent ); + if (ent->genericValue1 && ent->genericValue1 < level.time) { // time's up, we're done, remove us + if (ent->genericValue2) { // explode when die + RocketDie(ent, &g_entities[ent->r.ownerNum], &g_entities[ent->r.ownerNum], 0, MOD_UNKNOWN); + } else { // just remove when die + G_FreeEntity(ent); } return; } - if ( !ent->enemy - || !ent->enemy->client - || ent->enemy->health <= 0 - || ent->enemy->client->ps.powerups[PW_CLOAKED] ) - {//no enemy or enemy not a client or enemy dead or enemy cloaked - if ( !ent->genericValue1 ) - {//doesn't have its own self-kill time + if (!ent->enemy || !ent->enemy->client || ent->enemy->health <= 0 || + ent->enemy->client->ps.powerups[PW_CLOAKED]) { // no enemy or enemy not a client or enemy dead or enemy cloaked + if (!ent->genericValue1) { // doesn't have its own self-kill time ent->nextthink = level.time + 10000; ent->think = G_FreeEntity; } return; } - if ( (ent->spawnflags&1) ) - {//vehicle rocket - if ( ent->enemy->client && ent->enemy->client->NPC_class == CLASS_VEHICLE ) - {//tracking another vehicle - if ( ent->enemy->client->ps.speed+4000 > vel ) - { - vel = ent->enemy->client->ps.speed+4000; + if ((ent->spawnflags & 1)) { // vehicle rocket + if (ent->enemy->client && ent->enemy->client->NPC_class == CLASS_VEHICLE) { // tracking another vehicle + if (ent->enemy->client->ps.speed + 4000 > vel) { + vel = ent->enemy->client->ps.speed + 4000; } } } - if ( ent->enemy && ent->enemy->inuse ) - { - float newDirMult = ent->angle?ent->angle*2.0f:1.0f; - float oldDirMult = ent->angle?(1.0f-ent->angle)*2.0f:1.0f; + if (ent->enemy && ent->enemy->inuse) { + float newDirMult = ent->angle ? ent->angle * 2.0f : 1.0f; + float oldDirMult = ent->angle ? (1.0f - ent->angle) * 2.0f : 1.0f; - VectorCopy( ent->enemy->r.currentOrigin, org ); + VectorCopy(ent->enemy->r.currentOrigin, org); org[2] += (ent->enemy->r.mins[2] + ent->enemy->r.maxs[2]) * 0.5f; - VectorSubtract( org, ent->r.currentOrigin, targetdir ); - VectorNormalize( targetdir ); + VectorSubtract(org, ent->r.currentOrigin, targetdir); + VectorNormalize(targetdir); // Now the rocket can't do a 180 in space, so we'll limit the turn to about 45 degrees. - dot = DotProduct( targetdir, ent->movedir ); - if ( (ent->spawnflags&1) ) - {//vehicle rocket - if ( ent->radius > -1.0f ) - {//can lose the lock if DotProduct drops below this number - if ( dot < ent->radius ) - {//lost the lock!!! - //HMM... maybe can re-lock on if they come in front again? + dot = DotProduct(targetdir, ent->movedir); + if ((ent->spawnflags & 1)) { // vehicle rocket + if (ent->radius > -1.0f) { // can lose the lock if DotProduct drops below this number + if (dot < ent->radius) { // lost the lock!!! + // HMM... maybe can re-lock on if they come in front again? /* //OR: should it stop trying to lock altogether? if ( ent->genericValue1 ) @@ -1822,129 +1604,111 @@ void rocketThink( gentity_t *ent ) } } - // a dot of 1.0 means right-on-target. - if ( dot < 0.0f ) - { + if (dot < 0.0f) { // Go in the direction opposite, start a 180. - CrossProduct( ent->movedir, rup, right ); - dot2 = DotProduct( targetdir, right ); + CrossProduct(ent->movedir, rup, right); + dot2 = DotProduct(targetdir, right); - if ( dot2 > 0 ) - { + if (dot2 > 0) { // Turn 45 degrees right. - VectorMA( ent->movedir, 0.4f*newDirMult, right, newdir ); - } - else - { + VectorMA(ent->movedir, 0.4f * newDirMult, right, newdir); + } else { // Turn 45 degrees left. - VectorMA( ent->movedir, -0.4f*newDirMult, right, newdir ); + VectorMA(ent->movedir, -0.4f * newDirMult, right, newdir); } // Yeah we've adjusted horizontally, but let's split the difference vertically, so we kinda try to move towards it. - newdir[2] = ( (targetdir[2]*newDirMult) + (ent->movedir[2]*oldDirMult) ) * 0.5; + newdir[2] = ((targetdir[2] * newDirMult) + (ent->movedir[2] * oldDirMult)) * 0.5; // let's also slow down a lot vel *= 0.5f; - } - else if ( dot < 0.70f ) - { + } else if (dot < 0.70f) { // Still a bit off, so we turn a bit softer - VectorMA( ent->movedir, 0.5f*newDirMult, targetdir, newdir ); - } - else - { + VectorMA(ent->movedir, 0.5f * newDirMult, targetdir, newdir); + } else { // getting close, so turn a bit harder - VectorMA( ent->movedir, 0.9f*newDirMult, targetdir, newdir ); + VectorMA(ent->movedir, 0.9f * newDirMult, targetdir, newdir); } // add crazy drunkenness - for (i = 0; i < 3; i++ ) - { + for (i = 0; i < 3; i++) { newdir[i] += Q_flrand(-1.0f, 1.0f) * ent->random * 0.25f; } // decay the randomness ent->random *= 0.9f; - if ( ent->enemy->client - && ent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//tracking a client who's on the ground, aim at the floor...? + if (ent->enemy->client && ent->enemy->client->ps.groundEntityNum != ENTITYNUM_NONE) { // tracking a client who's on the ground, aim at the floor...? // Try to crash into the ground if we get close enough to do splash damage - dis = Distance( ent->r.currentOrigin, org ); + dis = Distance(ent->r.currentOrigin, org); - if ( dis < 128 ) - { + if (dis < 128) { // the closer we get, the more we push the rocket down, heh heh. newdir[2] -= (1.0f - (dis / 128.0f)) * 0.6f; } } - VectorNormalize( newdir ); + VectorNormalize(newdir); - VectorScale( newdir, vel * 0.5f, ent->s.pos.trDelta ); - VectorCopy( newdir, ent->movedir ); - SnapVector( ent->s.pos.trDelta ); // save net bandwidth - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); + VectorScale(newdir, vel * 0.5f, ent->s.pos.trDelta); + VectorCopy(newdir, ent->movedir); + SnapVector(ent->s.pos.trDelta); // save net bandwidth + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); ent->s.pos.trTime = level.time; } - ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. + ent->nextthink = level.time + ROCKET_ALT_THINK_TIME; // Nothing at all spectacular happened, continue. return; } -extern void G_ExplodeMissile( gentity_t *ent ); -void RocketDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +extern void G_ExplodeMissile(gentity_t *ent); +void RocketDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { self->die = 0; self->r.contents = 0; - G_ExplodeMissile( self ); + G_ExplodeMissile(self); self->think = G_FreeEntity; self->nextthink = level.time; } //--------------------------------------------------------- -static void WP_FireRocket( gentity_t *ent, qboolean altFire ) +static void WP_FireRocket(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - int damage = ROCKET_DAMAGE; - int vel = ROCKET_VELOCITY; + int damage = ROCKET_DAMAGE; + int vel = ROCKET_VELOCITY; int dif = 0; float rTime; gentity_t *missile; - if ( altFire ) - { + if (altFire) { vel *= 0.5f; } - missile = CreateMissile( muzzle, forward, vel, 30000, ent, altFire ); + missile = CreateMissile(muzzle, forward, vel, 30000, ent, altFire); - if (ent->client && ent->client->ps.rocketLockIndex != ENTITYNUM_NONE) - { - float lockTimeInterval = ((level.gametype==GT_SIEGE)?2400.0f:1200.0f)/16.0f; + if (ent->client && ent->client->ps.rocketLockIndex != ENTITYNUM_NONE) { + float lockTimeInterval = ((level.gametype == GT_SIEGE) ? 2400.0f : 1200.0f) / 16.0f; rTime = ent->client->ps.rocketLockTime; - if (rTime == -1) - { + if (rTime == -1) { rTime = ent->client->ps.rocketLastValidTime; } - dif = ( level.time - rTime ) / lockTimeInterval; + dif = (level.time - rTime) / lockTimeInterval; - if (dif < 0) - { + if (dif < 0) { dif = 0; } - //It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in time between server and client - if ( dif >= 10 && rTime != -1 ) - { + // It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in time + // between server and client + if (dif >= 10 && rTime != -1) { missile->enemy = &g_entities[ent->client->ps.rocketLockIndex]; - if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && !OnSameTeam(ent, missile->enemy)) - { //if enemy became invalid, died, or is on the same team, then don't seek it + if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && + !OnSameTeam(ent, missile->enemy)) { // if enemy became invalid, died, or is on the same team, then don't seek it missile->angle = 0.5f; missile->think = rocketThink; missile->nextthink = level.time + ROCKET_ALT_THINK_TIME; @@ -1960,27 +1724,24 @@ static void WP_FireRocket( gentity_t *ent, qboolean altFire ) missile->s.weapon = WP_ROCKET_LAUNCHER; // Make it easier to hit things - VectorSet( missile->r.maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; - if (altFire) - { + if (altFire) { missile->methodOfDeath = MOD_ROCKET_HOMING; missile->splashMethodOfDeath = MOD_ROCKET_HOMING_SPLASH; - } - else - { + } else { missile->methodOfDeath = MOD_ROCKET; missile->splashMethodOfDeath = MOD_ROCKET_SPLASH; } -//===testing being able to shoot rockets out of the air================================== + //===testing being able to shoot rockets out of the air================================== missile->health = 10; missile->takedamage = qtrue; missile->r.contents = MASK_SHOT; missile->die = RocketDie; -//===testing being able to shoot rockets out of the air================================== + //===testing being able to shoot rockets out of the air================================== missile->clipmask = MASK_SHOT; missile->splashDamage = ROCKET_SPLASH_DAMAGE; @@ -1998,64 +1759,57 @@ THERMAL DETONATOR ====================================================================== */ -#define TD_DAMAGE 70 //only do 70 on a direct impact -#define TD_SPLASH_RAD 128 -#define TD_SPLASH_DAM 90 -#define TD_VELOCITY 900 -#define TD_MIN_CHARGE 0.15f -#define TD_TIME 3000//6000 -#define TD_ALT_TIME 3000 - -#define TD_ALT_DAMAGE 60//100 -#define TD_ALT_SPLASH_RAD 128 -#define TD_ALT_SPLASH_DAM 50//90 -#define TD_ALT_VELOCITY 600 -#define TD_ALT_MIN_CHARGE 0.15f -#define TD_ALT_TIME 3000 +#define TD_DAMAGE 70 // only do 70 on a direct impact +#define TD_SPLASH_RAD 128 +#define TD_SPLASH_DAM 90 +#define TD_VELOCITY 900 +#define TD_MIN_CHARGE 0.15f +#define TD_TIME 3000 // 6000 +#define TD_ALT_TIME 3000 + +#define TD_ALT_DAMAGE 60 // 100 +#define TD_ALT_SPLASH_RAD 128 +#define TD_ALT_SPLASH_DAM 50 // 90 +#define TD_ALT_VELOCITY 600 +#define TD_ALT_MIN_CHARGE 0.15f +#define TD_ALT_TIME 3000 void thermalThinkStandard(gentity_t *ent); //--------------------------------------------------------- -void thermalDetonatorExplode( gentity_t *ent ) +void thermalDetonatorExplode(gentity_t *ent) //--------------------------------------------------------- { - if ( !ent->count ) - { - G_Sound( ent, CHAN_WEAPON, G_SoundIndex( "sound/weapons/thermal/warning.wav" ) ); + if (!ent->count) { + G_Sound(ent, CHAN_WEAPON, G_SoundIndex("sound/weapons/thermal/warning.wav")); ent->count = 1; ent->genericValue5 = level.time + 500; ent->think = thermalThinkStandard; ent->nextthink = level.time; - ent->r.svFlags |= SVF_BROADCAST;//so everyone hears/sees the explosion? - } - else - { - vec3_t origin; - vec3_t dir={0,0,1}; + ent->r.svFlags |= SVF_BROADCAST; // so everyone hears/sees the explosion? + } else { + vec3_t origin; + vec3_t dir = {0, 0, 1}; - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); origin[2] += 8; - SnapVector( origin ); - G_SetOrigin( ent, origin ); + SnapVector(origin); + G_SetOrigin(ent, origin); ent->s.eType = ET_GENERAL; - G_AddEvent( ent, EV_MISSILE_MISS, DirToByte( dir ) ); + G_AddEvent(ent, EV_MISSILE_MISS, DirToByte(dir)); ent->freeAfterEvent = qtrue; - if (G_RadiusDamage( ent->r.currentOrigin, ent->parent, ent->splashDamage, ent->splashRadius, - ent, ent, ent->splashMethodOfDeath)) - { + if (G_RadiusDamage(ent->r.currentOrigin, ent->parent, ent->splashDamage, ent->splashRadius, ent, ent, ent->splashMethodOfDeath)) { g_entities[ent->r.ownerNum].client->accuracy_hits++; } - trap->LinkEntity( (sharedEntity_t *)ent ); + trap->LinkEntity((sharedEntity_t *)ent); } } -void thermalThinkStandard(gentity_t *ent) -{ - if (ent->genericValue5 < level.time) - { +void thermalThinkStandard(gentity_t *ent) { + if (ent->genericValue5 < level.time) { ent->think = thermalDetonatorExplode; ent->nextthink = level.time; return; @@ -2066,15 +1820,15 @@ void thermalThinkStandard(gentity_t *ent) } //--------------------------------------------------------- -gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean altFire ) +gentity_t *WP_FireThermalDetonator(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - gentity_t *bolt; - vec3_t dir, start; + gentity_t *bolt; + vec3_t dir, start; float chargeAmount = 1.0f; // default of full charge - VectorCopy( forward, dir ); - VectorCopy( muzzle, start ); + VectorCopy(forward, dir); + VectorCopy(muzzle, start); bolt = G_Spawn(); @@ -2086,26 +1840,22 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean altFire ) bolt->touch = touch_NULL; // How 'bout we give this thing a size... - VectorSet( bolt->r.mins, -3.0f, -3.0f, -3.0f ); - VectorSet( bolt->r.maxs, 3.0f, 3.0f, 3.0f ); + VectorSet(bolt->r.mins, -3.0f, -3.0f, -3.0f); + VectorSet(bolt->r.maxs, 3.0f, 3.0f, 3.0f); bolt->clipmask = MASK_SHOT; - W_TraceSetStart( ent, start, bolt->r.mins, bolt->r.maxs );//make sure our start point isn't on the other side of a wall + W_TraceSetStart(ent, start, bolt->r.mins, bolt->r.maxs); // make sure our start point isn't on the other side of a wall - if ( ent->client ) - { + if (ent->client) { chargeAmount = level.time - ent->client->ps.weaponChargeTime; } // get charge amount chargeAmount = chargeAmount / (float)TD_VELOCITY; - if ( chargeAmount > 1.0f ) - { + if (chargeAmount > 1.0f) { chargeAmount = 1.0f; - } - else if ( chargeAmount < TD_MIN_CHARGE ) - { + } else if (chargeAmount < TD_MIN_CHARGE) { chargeAmount = TD_MIN_CHARGE; } @@ -2114,19 +1864,17 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean altFire ) bolt->s.pos.trType = TR_GRAVITY; bolt->parent = ent; bolt->r.ownerNum = ent->s.number; - VectorScale( dir, TD_VELOCITY * chargeAmount, bolt->s.pos.trDelta ); + VectorScale(dir, TD_VELOCITY * chargeAmount, bolt->s.pos.trDelta); - if ( ent->health >= 0 ) - { + if (ent->health >= 0) { bolt->s.pos.trDelta[2] += 120; } - if ( !altFire ) - { + if (!altFire) { bolt->flags |= FL_BOUNCE_HALF; } - bolt->s.loopSound = G_SoundIndex( "sound/weapons/thermal/thermloop.wav" ); + bolt->s.loopSound = G_SoundIndex("sound/weapons/thermal/thermloop.wav"); bolt->s.loopIsSoundset = qfalse; bolt->damage = TD_DAMAGE; @@ -2141,170 +1889,138 @@ gentity_t *WP_FireThermalDetonator( gentity_t *ent, qboolean altFire ) bolt->methodOfDeath = MOD_THERMAL; bolt->splashMethodOfDeath = MOD_THERMAL_SPLASH; - bolt->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, bolt->s.pos.trBase ); + bolt->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, bolt->s.pos.trBase); - SnapVector( bolt->s.pos.trDelta ); // save net bandwidth - VectorCopy (start, bolt->r.currentOrigin); + SnapVector(bolt->s.pos.trDelta); // save net bandwidth + VectorCopy(start, bolt->r.currentOrigin); - VectorCopy( start, bolt->pos2 ); + VectorCopy(start, bolt->pos2); bolt->bounceCount = -5; return bolt; } -gentity_t *WP_DropThermal( gentity_t *ent ) -{ - AngleVectors( ent->client->ps.viewangles, forward, vright, up ); - return (WP_FireThermalDetonator( ent, qfalse )); +gentity_t *WP_DropThermal(gentity_t *ent) { + AngleVectors(ent->client->ps.viewangles, forward, vright, up); + return (WP_FireThermalDetonator(ent, qfalse)); } - //--------------------------------------------------------- -qboolean WP_LobFire( gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, - vec3_t velocity, qboolean tracePath, int ignoreEntNum, int enemyNum, - float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit ) +qboolean WP_LobFire(gentity_t *self, vec3_t start, vec3_t target, vec3_t mins, vec3_t maxs, int clipmask, vec3_t velocity, qboolean tracePath, int ignoreEntNum, + int enemyNum, float minSpeed, float maxSpeed, float idealSpeed, qboolean mustHit) //--------------------------------------------------------- -{ //for the galak mech NPC - float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE;//fireSpeed, - vec3_t targetDir, shotVel, failCase; - trace_t trace; - trajectory_t tr; - qboolean blocked; - int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; - vec3_t lastPos, testPos; - gentity_t *traceEnt; - - if ( !idealSpeed ) - { +{ // for the galak mech NPC + float targetDist, shotSpeed, speedInc = 100, travelTime, impactDist, bestImpactDist = Q3_INFINITE; // fireSpeed, + vec3_t targetDir, shotVel, failCase; + trace_t trace; + trajectory_t tr; + qboolean blocked; + int elapsedTime, skipNum, timeStep = 500, hitCount = 0, maxHits = 7; + vec3_t lastPos, testPos; + gentity_t *traceEnt; + + if (!idealSpeed) { idealSpeed = 300; - } - else if ( idealSpeed < speedInc ) - { + } else if (idealSpeed < speedInc) { idealSpeed = speedInc; } shotSpeed = idealSpeed; - skipNum = (idealSpeed-speedInc)/speedInc; - if ( !minSpeed ) - { + skipNum = (idealSpeed - speedInc) / speedInc; + if (!minSpeed) { minSpeed = 100; } - if ( !maxSpeed ) - { + if (!maxSpeed) { maxSpeed = 900; } - while ( hitCount < maxHits ) - { - VectorSubtract( target, start, targetDir ); - targetDist = VectorNormalize( targetDir ); + while (hitCount < maxHits) { + VectorSubtract(target, start, targetDir); + targetDist = VectorNormalize(targetDir); - VectorScale( targetDir, shotSpeed, shotVel ); - travelTime = targetDist/shotSpeed; + VectorScale(targetDir, shotSpeed, shotVel); + travelTime = targetDist / shotSpeed; shotVel[2] += travelTime * 0.5 * g_gravity.value; - if ( !hitCount ) - {//save the first (ideal) one as the failCase (fallback value) - if ( !mustHit ) - {//default is fine as a return value - VectorCopy( shotVel, failCase ); + if (!hitCount) { // save the first (ideal) one as the failCase (fallback value) + if (!mustHit) { // default is fine as a return value + VectorCopy(shotVel, failCase); } } - if ( tracePath ) - {//do a rough trace of the path + if (tracePath) { // do a rough trace of the path blocked = qfalse; - VectorCopy( start, tr.trBase ); - VectorCopy( shotVel, tr.trDelta ); + VectorCopy(start, tr.trBase); + VectorCopy(shotVel, tr.trDelta); tr.trType = TR_GRAVITY; tr.trTime = level.time; travelTime *= 1000.0f; - VectorCopy( start, lastPos ); + VectorCopy(start, lastPos); - //This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace just to apex and down? - for ( elapsedTime = timeStep; elapsedTime < floor(travelTime)+timeStep; elapsedTime += timeStep ) - { - if ( (float)elapsedTime > travelTime ) - {//cap it - elapsedTime = floor( travelTime ); + // This may be kind of wasteful, especially on long throws... use larger steps? Divide the travelTime into a certain hard number of slices? Trace + // just to apex and down? + for (elapsedTime = timeStep; elapsedTime < floor(travelTime) + timeStep; elapsedTime += timeStep) { + if ((float)elapsedTime > travelTime) { // cap it + elapsedTime = floor(travelTime); } - BG_EvaluateTrajectory( &tr, level.time + elapsedTime, testPos ); - trap->Trace( &trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, qfalse, 0, 0 ); + BG_EvaluateTrajectory(&tr, level.time + elapsedTime, testPos); + trap->Trace(&trace, lastPos, mins, maxs, testPos, ignoreEntNum, clipmask, qfalse, 0, 0); - if ( trace.allsolid || trace.startsolid ) - { + if (trace.allsolid || trace.startsolid) { blocked = qtrue; break; } - if ( trace.fraction < 1.0f ) - {//hit something - if ( trace.entityNum == enemyNum ) - {//hit the enemy, that's perfect! + if (trace.fraction < 1.0f) { // hit something + if (trace.entityNum == enemyNum) { // hit the enemy, that's perfect! break; - } - else if ( trace.plane.normal[2] > 0.7 && DistanceSquared( trace.endpos, target ) < 4096 )//hit within 64 of desired location, should be okay - {//close enough! + } else if (trace.plane.normal[2] > 0.7 && DistanceSquared(trace.endpos, target) < 4096) // hit within 64 of desired location, should be okay + { // close enough! break; - } - else - {//FIXME: maybe find the extents of this brush and go above or below it on next try somehow? - impactDist = DistanceSquared( trace.endpos, target ); - if ( impactDist < bestImpactDist ) - { + } else { // FIXME: maybe find the extents of this brush and go above or below it on next try somehow? + impactDist = DistanceSquared(trace.endpos, target); + if (impactDist < bestImpactDist) { bestImpactDist = impactDist; - VectorCopy( shotVel, failCase ); + VectorCopy(shotVel, failCase); } blocked = qtrue; - //see if we should store this as the failCase - if ( trace.entityNum < ENTITYNUM_WORLD ) - {//hit an ent + // see if we should store this as the failCase + if (trace.entityNum < ENTITYNUM_WORLD) { // hit an ent traceEnt = &g_entities[trace.entityNum]; - if ( traceEnt && traceEnt->takedamage && !OnSameTeam( self, traceEnt ) ) - {//hit something breakable, so that's okay - //we haven't found a clear shot yet so use this as the failcase - VectorCopy( shotVel, failCase ); + if (traceEnt && traceEnt->takedamage && !OnSameTeam(self, traceEnt)) { // hit something breakable, so that's okay + // we haven't found a clear shot yet so use this as the failcase + VectorCopy(shotVel, failCase); } } break; } } - if ( elapsedTime == floor( travelTime ) ) - {//reached end, all clear + if (elapsedTime == floor(travelTime)) { // reached end, all clear break; - } - else - { - //all clear, try next slice - VectorCopy( testPos, lastPos ); + } else { + // all clear, try next slice + VectorCopy(testPos, lastPos); } } - if ( blocked ) - {//hit something, adjust speed (which will change arc) + if (blocked) { // hit something, adjust speed (which will change arc) hitCount++; - shotSpeed = idealSpeed + ((hitCount-skipNum) * speedInc);//from min to max (skipping ideal) - if ( hitCount >= skipNum ) - {//skip ideal since that was the first value we tested + shotSpeed = idealSpeed + ((hitCount - skipNum) * speedInc); // from min to max (skipping ideal) + if (hitCount >= skipNum) { // skip ideal since that was the first value we tested shotSpeed += speedInc; } - } - else - {//made it! + } else { // made it! break; } - } - else - {//no need to check the path, go with first calc + } else { // no need to check the path, go with first calc break; } } - if ( hitCount >= maxHits ) - {//NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) - VectorCopy( failCase, velocity ); + if (hitCount >= maxHits) { // NOTE: worst case scenario, use the one that impacted closest to the target (or just use the first try...?) + VectorCopy(failCase, velocity); return qfalse; } - VectorCopy( shotVel, velocity ); + VectorCopy(shotVel, velocity); return qtrue; } @@ -2315,46 +2031,39 @@ LASER TRAP / TRIP MINE ====================================================================== */ -#define LT_DAMAGE 100 -#define LT_SPLASH_RAD 256.0f -#define LT_SPLASH_DAM 105 -#define LT_VELOCITY 900.0f -#define LT_SIZE 1.5f -#define LT_ALT_TIME 2000 -#define LT_ACTIVATION_DELAY 1000 -#define LT_DELAY_TIME 50 - -void laserTrapExplode( gentity_t *self ) -{ +#define LT_DAMAGE 100 +#define LT_SPLASH_RAD 256.0f +#define LT_SPLASH_DAM 105 +#define LT_VELOCITY 900.0f +#define LT_SIZE 1.5f +#define LT_ALT_TIME 2000 +#define LT_ACTIVATION_DELAY 1000 +#define LT_DELAY_TIME 50 + +void laserTrapExplode(gentity_t *self) { vec3_t v; self->takedamage = qfalse; - if (self->activator) - { - G_RadiusDamage( self->r.currentOrigin, self->activator, self->splashDamage, self->splashRadius, self, self, MOD_TRIP_MINE_SPLASH/*MOD_LT_SPLASH*/ ); + if (self->activator) { + G_RadiusDamage(self->r.currentOrigin, self->activator, self->splashDamage, self->splashRadius, self, self, MOD_TRIP_MINE_SPLASH /*MOD_LT_SPLASH*/); } - if (self->s.weapon != WP_FLECHETTE) - { - G_AddEvent( self, EV_MISSILE_MISS, 0); + if (self->s.weapon != WP_FLECHETTE) { + G_AddEvent(self, EV_MISSILE_MISS, 0); } VectorCopy(self->s.pos.trDelta, v); - //Explode outward from the surface + // Explode outward from the surface - if (self->s.time == -2) - { + if (self->s.time == -2) { v[0] = 0; v[1] = 0; v[2] = 0; } - if (self->s.weapon == WP_FLECHETTE) - { + if (self->s.weapon == WP_FLECHETTE) { G_PlayEffect(EFFECT_EXPLOSION_FLECHETTE, self->r.currentOrigin, v); - } - else - { + } else { G_PlayEffect(EFFECT_EXPLOSION_TRIPMINE, self->r.currentOrigin, v); } @@ -2362,82 +2071,62 @@ void laserTrapExplode( gentity_t *self ) self->nextthink = level.time; } -void laserTrapDelayedExplode( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) -{ +void laserTrapDelayedExplode(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath) { self->enemy = attacker; self->think = laserTrapExplode; self->nextthink = level.time + FRAMETIME; self->takedamage = qfalse; - if ( attacker && attacker->s.number < MAX_CLIENTS ) - { - //less damage when shot by player + if (attacker && attacker->s.number < MAX_CLIENTS) { + // less damage when shot by player self->splashDamage /= 3; self->splashRadius /= 3; } } -void touchLaserTrap( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ - if (other && other->s.number < ENTITYNUM_WORLD) - { //just explode if we hit any entity. This way we don't have things happening like tripmines floating - //in the air after getting stuck to a moving door - if ( ent->activator != other ) - { +void touchLaserTrap(gentity_t *ent, gentity_t *other, trace_t *trace) { + if (other && other->s.number < ENTITYNUM_WORLD) { // just explode if we hit any entity. This way we don't have things happening like tripmines floating + // in the air after getting stuck to a moving door + if (ent->activator != other) { ent->touch = 0; ent->nextthink = level.time + FRAMETIME; ent->think = laserTrapExplode; VectorCopy(trace->plane.normal, ent->s.pos.trDelta); } - } - else - { + } else { ent->touch = 0; - if (trace->entityNum != ENTITYNUM_NONE) - { + if (trace->entityNum != ENTITYNUM_NONE) { ent->enemy = &g_entities[trace->entityNum]; } laserTrapStick(ent, trace->endpos, trace->plane.normal); } } -void proxMineThink(gentity_t *ent) -{ +void proxMineThink(gentity_t *ent) { int i = 0; gentity_t *cl; gentity_t *owner = NULL; - if (ent->r.ownerNum < ENTITYNUM_WORLD) - { + if (ent->r.ownerNum < ENTITYNUM_WORLD) { owner = &g_entities[ent->r.ownerNum]; } ent->nextthink = level.time; - if (ent->genericValue15 < level.time || - !owner || - !owner->inuse || - !owner->client || - owner->client->pers.connected != CON_CONNECTED) - { //time to die! + if (ent->genericValue15 < level.time || !owner || !owner->inuse || !owner->client || owner->client->pers.connected != CON_CONNECTED) { // time to die! ent->think = laserTrapExplode; return; } - while (i < MAX_CLIENTS) - { //eh, just check for clients, don't care about anyone else... + while (i < MAX_CLIENTS) { // eh, just check for clients, don't care about anyone else... cl = &g_entities[i]; - if (cl->inuse && cl->client && cl->client->pers.connected == CON_CONNECTED && - owner != cl && cl->client->sess.sessionTeam != TEAM_SPECTATOR && - cl->client->tempSpectate < level.time && cl->health > 0) - { - if (!OnSameTeam(owner, cl) || g_friendlyFire.integer) - { //not on the same team, or friendly fire is enabled + if (cl->inuse && cl->client && cl->client->pers.connected == CON_CONNECTED && owner != cl && cl->client->sess.sessionTeam != TEAM_SPECTATOR && + cl->client->tempSpectate < level.time && cl->health > 0) { + if (!OnSameTeam(owner, cl) || g_friendlyFire.integer) { // not on the same team, or friendly fire is enabled vec3_t v; VectorSubtract(ent->r.currentOrigin, cl->client->ps.origin, v); - if (VectorLength(v) < (ent->splashRadius/2.0f)) - { + if (VectorLength(v) < (ent->splashRadius / 2.0f)) { ent->think = laserTrapExplode; return; } @@ -2447,103 +2136,93 @@ void proxMineThink(gentity_t *ent) } } -void laserTrapThink ( gentity_t *ent ) -{ - gentity_t *traceEnt; - vec3_t end; - trace_t tr; +void laserTrapThink(gentity_t *ent) { + gentity_t *traceEnt; + vec3_t end; + trace_t tr; - //just relink it every think + // just relink it every think trap->LinkEntity((sharedEntity_t *)ent); - //turn on the beam effect - if ( !(ent->s.eFlags&EF_FIRING) ) - {//arm me - G_Sound( ent, CHAN_WEAPON, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" ) ); + // turn on the beam effect + if (!(ent->s.eFlags & EF_FIRING)) { // arm me + G_Sound(ent, CHAN_WEAPON, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); ent->s.eFlags |= EF_FIRING; } ent->think = laserTrapThink; ent->nextthink = level.time + FRAMETIME; // Find the main impact point - VectorMA ( ent->s.pos.trBase, 1024, ent->movedir, end ); - trap->Trace ( &tr, ent->r.currentOrigin, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); + VectorMA(ent->s.pos.trBase, 1024, ent->movedir, end); + trap->Trace(&tr, ent->r.currentOrigin, NULL, NULL, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); - traceEnt = &g_entities[ tr.entityNum ]; + traceEnt = &g_entities[tr.entityNum]; - ent->s.time = -1; //let all clients know to draw a beam from this guy + ent->s.time = -1; // let all clients know to draw a beam from this guy - if ( traceEnt->client || tr.startsolid ) - { - //go boom + if (traceEnt->client || tr.startsolid) { + // go boom ent->touch = 0; ent->nextthink = level.time + LT_DELAY_TIME; ent->think = laserTrapExplode; } } -void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ) -{ - G_SetOrigin( ent, endpos ); - VectorCopy( normal, ent->pos1 ); +void laserTrapStick(gentity_t *ent, vec3_t endpos, vec3_t normal) { + G_SetOrigin(ent, endpos); + VectorCopy(normal, ent->pos1); - VectorClear( ent->s.apos.trDelta ); + VectorClear(ent->s.apos.trDelta); // This will orient the object to face in the direction of the normal - VectorCopy( normal, ent->s.pos.trDelta ); - //VectorScale( normal, -1, ent->s.pos.trDelta ); + VectorCopy(normal, ent->s.pos.trDelta); + // VectorScale( normal, -1, ent->s.pos.trDelta ); ent->s.pos.trTime = level.time; - - //This does nothing, cg_missile makes assumptions about direction of travel controlling angles - vectoangles( normal, ent->s.apos.trBase ); - VectorClear( ent->s.apos.trDelta ); + // This does nothing, cg_missile makes assumptions about direction of travel controlling angles + vectoangles(normal, ent->s.apos.trBase); + VectorClear(ent->s.apos.trDelta); ent->s.apos.trType = TR_STATIONARY; - VectorCopy( ent->s.apos.trBase, ent->s.angles ); - VectorCopy( ent->s.angles, ent->r.currentAngles ); + VectorCopy(ent->s.apos.trBase, ent->s.angles); + VectorCopy(ent->s.angles, ent->r.currentAngles); - - G_Sound( ent, CHAN_WEAPON, G_SoundIndex( "sound/weapons/laser_trap/stick.wav" ) ); - if ( ent->count ) - {//a tripwire - //add draw line flag - VectorCopy( normal, ent->movedir ); + G_Sound(ent, CHAN_WEAPON, G_SoundIndex("sound/weapons/laser_trap/stick.wav")); + if (ent->count) { // a tripwire + // add draw line flag + VectorCopy(normal, ent->movedir); ent->think = laserTrapThink; - ent->nextthink = level.time + LT_ACTIVATION_DELAY;//delay the activation + ent->nextthink = level.time + LT_ACTIVATION_DELAY; // delay the activation ent->touch = touch_NULL; - //make it shootable + // make it shootable ent->takedamage = qtrue; ent->health = 5; ent->die = laserTrapDelayedExplode; - //shove the box through the wall - VectorSet( ent->r.mins, -LT_SIZE*2, -LT_SIZE*2, -LT_SIZE*2 ); - VectorSet( ent->r.maxs, LT_SIZE*2, LT_SIZE*2, LT_SIZE*2 ); + // shove the box through the wall + VectorSet(ent->r.mins, -LT_SIZE * 2, -LT_SIZE * 2, -LT_SIZE * 2); + VectorSet(ent->r.maxs, LT_SIZE * 2, LT_SIZE * 2, LT_SIZE * 2); - //so that the owner can blow it up with projectiles + // so that the owner can blow it up with projectiles ent->r.svFlags |= SVF_OWNERNOTSHARED; - } - else - { + } else { ent->touch = touchLaserTrap; - ent->think = proxMineThink;//laserTrapExplode; - ent->genericValue15 = level.time + 30000; //auto-explode after 30 seconds. + ent->think = proxMineThink; // laserTrapExplode; + ent->genericValue15 = level.time + 30000; // auto-explode after 30 seconds. ent->nextthink = level.time + LT_ALT_TIME; // How long 'til she blows - //make it shootable + // make it shootable ent->takedamage = qtrue; ent->health = 5; ent->die = laserTrapDelayedExplode; - //shove the box through the wall - VectorSet( ent->r.mins, -LT_SIZE*2, -LT_SIZE*2, -LT_SIZE*2 ); - VectorSet( ent->r.maxs, LT_SIZE*2, LT_SIZE*2, LT_SIZE*2 ); + // shove the box through the wall + VectorSet(ent->r.mins, -LT_SIZE * 2, -LT_SIZE * 2, -LT_SIZE * 2); + VectorSet(ent->r.maxs, LT_SIZE * 2, LT_SIZE * 2, LT_SIZE * 2); - //so that the owner can blow it up with projectiles + // so that the owner can blow it up with projectiles ent->r.svFlags |= SVF_OWNERNOTSHARED; - if ( !(ent->s.eFlags&EF_FIRING) ) - {//arm me - G_Sound( ent, CHAN_WEAPON, G_SoundIndex( "sound/weapons/laser_trap/warning.wav" ) ); + if (!(ent->s.eFlags & EF_FIRING)) { // arm me + G_Sound(ent, CHAN_WEAPON, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); ent->s.eFlags |= EF_FIRING; ent->s.time = -1; ent->s.bolt2 = 1; @@ -2551,14 +2230,12 @@ void laserTrapStick( gentity_t *ent, vec3_t endpos, vec3_t normal ) } } -void TrapThink(gentity_t *ent) -{ //laser trap think +void TrapThink(gentity_t *ent) { // laser trap think ent->nextthink = level.time + 50; G_RunObject(ent); } -void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) -{ //create a laser trap entity +void CreateLaserTrap(gentity_t *laserTrap, vec3_t start, gentity_t *owner) { // create a laser trap entity laserTrap->classname = "laserTrap"; laserTrap->flags |= FL_BOUNCE_HALF; laserTrap->s.eFlags |= EF_MISSILE_STICK; @@ -2575,140 +2252,121 @@ void CreateLaserTrap( gentity_t *laserTrap, vec3_t start, gentity_t *owner ) laserTrap->parent = owner; laserTrap->activator = owner; laserTrap->r.ownerNum = owner->s.number; - VectorSet( laserTrap->r.mins, -LT_SIZE, -LT_SIZE, -LT_SIZE ); - VectorSet( laserTrap->r.maxs, LT_SIZE, LT_SIZE, LT_SIZE ); + VectorSet(laserTrap->r.mins, -LT_SIZE, -LT_SIZE, -LT_SIZE); + VectorSet(laserTrap->r.maxs, LT_SIZE, LT_SIZE, LT_SIZE); laserTrap->clipmask = MASK_SHOT; laserTrap->s.solid = 2; - laserTrap->s.modelindex = G_ModelIndex( "models/weapons2/laser_trap/laser_trap_w.glm" ); + laserTrap->s.modelindex = G_ModelIndex("models/weapons2/laser_trap/laser_trap_w.glm"); laserTrap->s.modelGhoul2 = 1; laserTrap->s.g2radius = 40; - laserTrap->s.genericenemyindex = owner->s.number+MAX_GENTITIES; + laserTrap->s.genericenemyindex = owner->s.number + MAX_GENTITIES; laserTrap->health = 1; laserTrap->s.time = 0; - laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( start, laserTrap->s.pos.trBase ); - SnapVector( laserTrap->s.pos.trBase ); // save net bandwidth + laserTrap->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(start, laserTrap->s.pos.trBase); + SnapVector(laserTrap->s.pos.trBase); // save net bandwidth - SnapVector( laserTrap->s.pos.trDelta ); // save net bandwidth - VectorCopy (start, laserTrap->r.currentOrigin); + SnapVector(laserTrap->s.pos.trDelta); // save net bandwidth + VectorCopy(start, laserTrap->r.currentOrigin); laserTrap->s.apos.trType = TR_GRAVITY; laserTrap->s.apos.trTime = level.time; - laserTrap->s.apos.trBase[YAW] = rand()%360; - laserTrap->s.apos.trBase[PITCH] = rand()%360; - laserTrap->s.apos.trBase[ROLL] = rand()%360; + laserTrap->s.apos.trBase[YAW] = rand() % 360; + laserTrap->s.apos.trBase[PITCH] = rand() % 360; + laserTrap->s.apos.trBase[ROLL] = rand() % 360; - if (rand()%10 < 5) - { + if (rand() % 10 < 5) { laserTrap->s.apos.trBase[YAW] = -laserTrap->s.apos.trBase[YAW]; } - VectorCopy( start, laserTrap->pos2 ); + VectorCopy(start, laserTrap->pos2); laserTrap->touch = touchLaserTrap; laserTrap->think = TrapThink; laserTrap->nextthink = level.time + 50; } -void WP_PlaceLaserTrap( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *laserTrap; - gentity_t *found = NULL; - vec3_t dir, start; - int trapcount = 0; - int foundLaserTraps[MAX_GENTITIES]; - int trapcount_org; - int lowestTimeStamp; - int removeMe; - int i; +void WP_PlaceLaserTrap(gentity_t *ent, qboolean alt_fire) { + gentity_t *laserTrap; + gentity_t *found = NULL; + vec3_t dir, start; + int trapcount = 0; + int foundLaserTraps[MAX_GENTITIES]; + int trapcount_org; + int lowestTimeStamp; + int removeMe; + int i; foundLaserTraps[0] = ENTITYNUM_NONE; - VectorCopy( forward, dir ); - VectorCopy( muzzle, start ); + VectorCopy(forward, dir); + VectorCopy(muzzle, start); laserTrap = G_Spawn(); - //limit to 10 placed at any one time - //see how many there are now - while ( (found = G_Find( found, FOFS(classname), "laserTrap" )) != NULL ) - { - if ( found->parent != ent ) - { + // limit to 10 placed at any one time + // see how many there are now + while ((found = G_Find(found, FOFS(classname), "laserTrap")) != NULL) { + if (found->parent != ent) { continue; } foundLaserTraps[trapcount++] = found->s.number; } - //now remove first ones we find until there are only 9 left + // now remove first ones we find until there are only 9 left found = NULL; trapcount_org = trapcount; lowestTimeStamp = level.time; - while ( trapcount > 9 ) - { + while (trapcount > 9) { removeMe = -1; - for ( i = 0; i < trapcount_org; i++ ) - { - if ( foundLaserTraps[i] == ENTITYNUM_NONE ) - { + for (i = 0; i < trapcount_org; i++) { + if (foundLaserTraps[i] == ENTITYNUM_NONE) { continue; } found = &g_entities[foundLaserTraps[i]]; - if ( laserTrap && found->setTime < lowestTimeStamp ) - { + if (laserTrap && found->setTime < lowestTimeStamp) { removeMe = i; lowestTimeStamp = found->setTime; } } - if ( removeMe != -1 ) - { - //remove it... or blow it? - if ( &g_entities[foundLaserTraps[removeMe]] == NULL ) - { + if (removeMe != -1) { + // remove it... or blow it? + if (&g_entities[foundLaserTraps[removeMe]] == NULL) { break; - } - else - { - G_FreeEntity( &g_entities[foundLaserTraps[removeMe]] ); + } else { + G_FreeEntity(&g_entities[foundLaserTraps[removeMe]]); } foundLaserTraps[removeMe] = ENTITYNUM_NONE; trapcount--; - } - else - { + } else { break; } } - //now make the new one - CreateLaserTrap( laserTrap, start, ent ); + // now make the new one + CreateLaserTrap(laserTrap, start, ent); - //set player-created-specific fields - laserTrap->setTime = level.time;//remember when we placed it + // set player-created-specific fields + laserTrap->setTime = level.time; // remember when we placed it - if (!alt_fire) - {//tripwire + if (!alt_fire) { // tripwire laserTrap->count = 1; } - //move it + // move it laserTrap->s.pos.trType = TR_GRAVITY; - if (alt_fire) - { - VectorScale( dir, 512, laserTrap->s.pos.trDelta ); - } - else - { - VectorScale( dir, 256, laserTrap->s.pos.trDelta ); + if (alt_fire) { + VectorScale(dir, 512, laserTrap->s.pos.trDelta); + } else { + VectorScale(dir, 256, laserTrap->s.pos.trDelta); } trap->LinkEntity((sharedEntity_t *)laserTrap); } - /* ====================================================================== @@ -2716,52 +2374,49 @@ DET PACK ====================================================================== */ -void VectorNPos(vec3_t in, vec3_t out) -{ - if (in[0] < 0) { out[0] = -in[0]; } else { out[0] = in[0]; } - if (in[1] < 0) { out[1] = -in[1]; } else { out[1] = in[1]; } - if (in[2] < 0) { out[2] = -in[2]; } else { out[2] = in[2]; } +void VectorNPos(vec3_t in, vec3_t out) { + if (in[0] < 0) { + out[0] = -in[0]; + } else { + out[0] = in[0]; + } + if (in[1] < 0) { + out[1] = -in[1]; + } else { + out[1] = in[1]; + } + if (in[2] < 0) { + out[2] = -in[2]; + } else { + out[2] = in[2]; + } } void DetPackBlow(gentity_t *self); -void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) -{ - gentity_t *tent; - - if ( other - && (other->flags&FL_BBRUSH) - && other->s.pos.trType == TR_STATIONARY - && other->s.apos.trType == TR_STATIONARY ) - {//a perfectly still breakable brush, let us attach directly to it! - self->target_ent = other;//remember them when we blow up - } - else if ( other - && other->s.number < ENTITYNUM_WORLD - && other->s.eType == ET_MOVER - && trace->plane.normal[2] > 0 ) - {//stick to it? +void charge_stick(gentity_t *self, gentity_t *other, trace_t *trace) { + gentity_t *tent; + + if (other && (other->flags & FL_BBRUSH) && other->s.pos.trType == TR_STATIONARY && + other->s.apos.trType == TR_STATIONARY) { // a perfectly still breakable brush, let us attach directly to it! + self->target_ent = other; // remember them when we blow up + } else if (other && other->s.number < ENTITYNUM_WORLD && other->s.eType == ET_MOVER && trace->plane.normal[2] > 0) { // stick to it? self->s.groundEntityNum = other->s.number; - } - else if (other && other->s.number < ENTITYNUM_WORLD && - (other->client || !other->s.weapon)) - { //hit another entity that is not stickable, "bounce" off + } else if (other && other->s.number < ENTITYNUM_WORLD && (other->client || !other->s.weapon)) { // hit another entity that is not stickable, "bounce" off vec3_t vNor, tN; VectorCopy(trace->plane.normal, vNor); VectorNormalize(vNor); VectorNPos(self->s.pos.trDelta, tN); - self->s.pos.trDelta[0] += vNor[0]*(tN[0]*(((float)Q_irand(1, 10))*0.1)); - self->s.pos.trDelta[1] += vNor[1]*(tN[1]*(((float)Q_irand(1, 10))*0.1)); - self->s.pos.trDelta[2] += vNor[2]*(tN[2]*(((float)Q_irand(1, 10))*0.1)); + self->s.pos.trDelta[0] += vNor[0] * (tN[0] * (((float)Q_irand(1, 10)) * 0.1)); + self->s.pos.trDelta[1] += vNor[1] * (tN[1] * (((float)Q_irand(1, 10)) * 0.1)); + self->s.pos.trDelta[2] += vNor[2] * (tN[2] * (((float)Q_irand(1, 10)) * 0.1)); vectoangles(vNor, self->s.angles); vectoangles(vNor, self->s.apos.trBase); self->touch = charge_stick; return; - } - else if (other && other->s.number < ENTITYNUM_WORLD) - { //hit an entity that we just want to explode on (probably another projectile or something) + } else if (other && other->s.number < ENTITYNUM_WORLD) { // hit an entity that we just want to explode on (probably another projectile or something) vec3_t v; self->touch = 0; @@ -2773,7 +2428,7 @@ void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) VectorClear(self->s.apos.trDelta); self->s.apos.trType = TR_STATIONARY; - G_RadiusDamage( self->r.currentOrigin, self->parent, self->splashDamage, self->splashRadius, self, self, MOD_DET_PACK_SPLASH ); + G_RadiusDamage(self->r.currentOrigin, self->parent, self->splashDamage, self->splashRadius, self, self, MOD_DET_PACK_SPLASH); VectorCopy(trace->plane.normal, v); VectorCopy(v, self->pos2); self->count = -1; @@ -2784,7 +2439,7 @@ void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) return; } - //if we get here I guess we hit hte world so we can stick to it + // if we get here I guess we hit hte world so we can stick to it // This requires a bit of explaining. // When you suicide, all of the detpacks you have placed (either on a wall, or still falling in the air) will have @@ -2796,7 +2451,7 @@ void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) // The fix Sil came up with is to check the think() function in charge_stick, and only overwrite it if they haven't // been primed to detonate - if ( self->think == G_RunObject ) { + if (self->think == G_RunObject) { self->touch = 0; self->think = DetPackBlow; self->nextthink = level.time + 30000; @@ -2806,16 +2461,16 @@ void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) self->s.apos.trType = TR_STATIONARY; self->s.pos.trType = TR_STATIONARY; - VectorCopy( self->r.currentOrigin, self->s.origin ); - VectorCopy( self->r.currentOrigin, self->s.pos.trBase ); - VectorClear( self->s.pos.trDelta ); + VectorCopy(self->r.currentOrigin, self->s.origin); + VectorCopy(self->r.currentOrigin, self->s.pos.trBase); + VectorClear(self->s.pos.trDelta); - VectorClear( self->s.apos.trDelta ); + VectorClear(self->s.apos.trDelta); VectorNormalize(trace->plane.normal); vectoangles(trace->plane.normal, self->s.angles); - VectorCopy(self->s.angles, self->r.currentAngles ); + VectorCopy(self->s.angles, self->r.currentAngles); VectorCopy(self->s.angles, self->s.apos.trBase); VectorCopy(trace->plane.normal, self->pos2); @@ -2823,34 +2478,31 @@ void charge_stick (gentity_t *self, gentity_t *other, trace_t *trace) G_Sound(self, CHAN_WEAPON, G_SoundIndex("sound/weapons/detpack/stick.wav")); - tent = G_TempEntity( self->r.currentOrigin, EV_MISSILE_MISS ); + tent = G_TempEntity(self->r.currentOrigin, EV_MISSILE_MISS); tent->s.weapon = 0; tent->parent = self; tent->r.ownerNum = self->s.number; - //so that the owner can blow it up with projectiles + // so that the owner can blow it up with projectiles self->r.svFlags |= SVF_OWNERNOTSHARED; } -void DetPackBlow(gentity_t *self) -{ +void DetPackBlow(gentity_t *self) { vec3_t v; self->pain = 0; self->die = 0; self->takedamage = qfalse; - if ( self->target_ent ) - {//we were attached to something, do *direct* damage to it! - G_Damage( self->target_ent, self, &g_entities[self->r.ownerNum], v, self->r.currentOrigin, self->damage, 0, MOD_DET_PACK_SPLASH ); + if (self->target_ent) { // we were attached to something, do *direct* damage to it! + G_Damage(self->target_ent, self, &g_entities[self->r.ownerNum], v, self->r.currentOrigin, self->damage, 0, MOD_DET_PACK_SPLASH); } - G_RadiusDamage( self->r.currentOrigin, self->parent, self->splashDamage, self->splashRadius, self, self, MOD_DET_PACK_SPLASH ); + G_RadiusDamage(self->r.currentOrigin, self->parent, self->splashDamage, self->splashRadius, self, self, MOD_DET_PACK_SPLASH); v[0] = 0; v[1] = 0; v[2] = 1; - if (self->count == -1) - { + if (self->count == -1) { VectorCopy(self->pos2, v); } @@ -2860,25 +2512,22 @@ void DetPackBlow(gentity_t *self) self->nextthink = level.time; } -void DetPackPain(gentity_t *self, gentity_t *attacker, int damage) -{ +void DetPackPain(gentity_t *self, gentity_t *attacker, int damage) { self->think = DetPackBlow; self->nextthink = level.time + Q_irand(50, 100); self->takedamage = qfalse; } -void DetPackDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) -{ +void DetPackDie(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { self->think = DetPackBlow; self->nextthink = level.time + Q_irand(50, 100); self->takedamage = qfalse; } -void drop_charge (gentity_t *self, vec3_t start, vec3_t dir) -{ - gentity_t *bolt; +void drop_charge(gentity_t *self, vec3_t start, vec3_t dir) { + gentity_t *bolt; - VectorNormalize (dir); + VectorNormalize(dir); bolt = G_Spawn(); bolt->classname = "detpack"; @@ -2903,11 +2552,11 @@ void drop_charge (gentity_t *self, vec3_t start, vec3_t dir) bolt->physicsObject = qtrue; - bolt->s.genericenemyindex = self->s.number+MAX_GENTITIES; - //rww - so client prediction knows we own this and won't hit it + bolt->s.genericenemyindex = self->s.number + MAX_GENTITIES; + // rww - so client prediction knows we own this and won't hit it - VectorSet( bolt->r.mins, -2, -2, -2 ); - VectorSet( bolt->r.maxs, 2, 2, 2 ); + VectorSet(bolt->r.mins, -2, -2, -2); + VectorSet(bolt->r.maxs, 2, 2, 2); bolt->health = 1; bolt->takedamage = qtrue; @@ -2920,399 +2569,343 @@ void drop_charge (gentity_t *self, vec3_t start, vec3_t dir) G_SetOrigin(bolt, start); bolt->s.pos.trType = TR_GRAVITY; - VectorCopy( start, bolt->s.pos.trBase ); - VectorScale(dir, 300, bolt->s.pos.trDelta ); + VectorCopy(start, bolt->s.pos.trBase); + VectorScale(dir, 300, bolt->s.pos.trDelta); bolt->s.pos.trTime = level.time; bolt->s.apos.trType = TR_GRAVITY; bolt->s.apos.trTime = level.time; - bolt->s.apos.trBase[YAW] = rand()%360; - bolt->s.apos.trBase[PITCH] = rand()%360; - bolt->s.apos.trBase[ROLL] = rand()%360; + bolt->s.apos.trBase[YAW] = rand() % 360; + bolt->s.apos.trBase[PITCH] = rand() % 360; + bolt->s.apos.trBase[ROLL] = rand() % 360; - if (rand()%10 < 5) - { + if (rand() % 10 < 5) { bolt->s.apos.trBase[YAW] = -bolt->s.apos.trBase[YAW]; } vectoangles(dir, bolt->s.angles); VectorCopy(bolt->s.angles, bolt->s.apos.trBase); - VectorSet(bolt->s.apos.trDelta, 300, 0, 0 ); + VectorSet(bolt->s.apos.trDelta, 300, 0, 0); bolt->s.apos.trTime = level.time; trap->LinkEntity((sharedEntity_t *)bolt); } -void BlowDetpacks(gentity_t *ent) -{ +void BlowDetpacks(gentity_t *ent) { gentity_t *found = NULL; - if ( ent->client->ps.hasDetPackPlanted ) - { - while ( (found = G_Find( found, FOFS(classname), "detpack") ) != NULL ) - {//loop through all ents and blow the crap out of them! - if ( found->parent == ent ) - { - VectorCopy( found->r.currentOrigin, found->s.origin ); + if (ent->client->ps.hasDetPackPlanted) { + while ((found = G_Find(found, FOFS(classname), "detpack")) != NULL) { // loop through all ents and blow the crap out of them! + if (found->parent == ent) { + VectorCopy(found->r.currentOrigin, found->s.origin); found->think = DetPackBlow; found->nextthink = level.time + 100 + Q_flrand(0.0f, 1.0f) * 200; - G_Sound( found, CHAN_BODY, G_SoundIndex("sound/weapons/detpack/warning.wav") ); + G_Sound(found, CHAN_BODY, G_SoundIndex("sound/weapons/detpack/warning.wav")); } } ent->client->ps.hasDetPackPlanted = qfalse; } } -void RemoveDetpacks(gentity_t *ent) -{ +void RemoveDetpacks(gentity_t *ent) { gentity_t *found = NULL; - if ( ent->client->ps.hasDetPackPlanted ) - { - while ( (found = G_Find( found, FOFS(classname), "detpack") ) != NULL ) - {//loop through all ents and blow the crap out of them! - if ( found->parent == ent ) - { - VectorCopy( found->r.currentOrigin, found->s.origin ); + if (ent->client->ps.hasDetPackPlanted) { + while ((found = G_Find(found, FOFS(classname), "detpack")) != NULL) { // loop through all ents and blow the crap out of them! + if (found->parent == ent) { + VectorCopy(found->r.currentOrigin, found->s.origin); found->think = G_FreeEntity; found->nextthink = level.time; - // G_Sound( found, CHAN_BODY, G_SoundIndex("sound/weapons/detpack/warning.wav") ); + // G_Sound( found, CHAN_BODY, G_SoundIndex("sound/weapons/detpack/warning.wav") ); } } ent->client->ps.hasDetPackPlanted = qfalse; } } -qboolean CheatsOn(void) -{ - if ( !sv_cheats.integer ) - { +qboolean CheatsOn(void) { + if (!sv_cheats.integer) { return qfalse; } return qtrue; } -void WP_DropDetPack( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *found = NULL; - int trapcount = 0; - int foundDetPacks[MAX_GENTITIES] = {ENTITYNUM_NONE}; - int trapcount_org; - int lowestTimeStamp; - int removeMe; - int i; - - if ( !ent || !ent->client ) - { +void WP_DropDetPack(gentity_t *ent, qboolean alt_fire) { + gentity_t *found = NULL; + int trapcount = 0; + int foundDetPacks[MAX_GENTITIES] = {ENTITYNUM_NONE}; + int trapcount_org; + int lowestTimeStamp; + int removeMe; + int i; + + if (!ent || !ent->client) { return; } - //limit to 10 placed at any one time - //see how many there are now - while ( (found = G_Find( found, FOFS(classname), "detpack" )) != NULL ) - { - if ( found->parent != ent ) - { + // limit to 10 placed at any one time + // see how many there are now + while ((found = G_Find(found, FOFS(classname), "detpack")) != NULL) { + if (found->parent != ent) { continue; } foundDetPacks[trapcount++] = found->s.number; } - //now remove first ones we find until there are only 9 left + // now remove first ones we find until there are only 9 left found = NULL; trapcount_org = trapcount; lowestTimeStamp = level.time; - while ( trapcount > 9 ) - { + while (trapcount > 9) { removeMe = -1; - for ( i = 0; i < trapcount_org; i++ ) - { - if ( foundDetPacks[i] == ENTITYNUM_NONE ) - { + for (i = 0; i < trapcount_org; i++) { + if (foundDetPacks[i] == ENTITYNUM_NONE) { continue; } found = &g_entities[foundDetPacks[i]]; - if ( found->setTime < lowestTimeStamp ) - { + if (found->setTime < lowestTimeStamp) { removeMe = i; lowestTimeStamp = found->setTime; } } - if ( removeMe != -1 ) - { - //remove it... or blow it? - if ( &g_entities[foundDetPacks[removeMe]] == NULL ) - { + if (removeMe != -1) { + // remove it... or blow it? + if (&g_entities[foundDetPacks[removeMe]] == NULL) { break; - } - else - { - if (!CheatsOn()) - { //Let them have unlimited if cheats are enabled - G_FreeEntity( &g_entities[foundDetPacks[removeMe]] ); + } else { + if (!CheatsOn()) { // Let them have unlimited if cheats are enabled + G_FreeEntity(&g_entities[foundDetPacks[removeMe]]); } } foundDetPacks[removeMe] = ENTITYNUM_NONE; trapcount--; - } - else - { + } else { break; } } - if ( alt_fire ) - { + if (alt_fire) { BlowDetpacks(ent); - } - else - { - AngleVectors( ent->client->ps.viewangles, forward, vright, up ); + } else { + AngleVectors(ent->client->ps.viewangles, forward, vright, up); - CalcMuzzlePoint( ent, forward, vright, up, muzzle ); + CalcMuzzlePoint(ent, forward, vright, up, muzzle); - VectorNormalize( forward ); - VectorMA( muzzle, -4, forward, muzzle ); - drop_charge( ent, muzzle, forward ); + VectorNormalize(forward); + VectorMA(muzzle, -4, forward, muzzle); + drop_charge(ent, muzzle, forward); ent->client->ps.hasDetPackPlanted = qtrue; } } -static void WP_FireConcussionAlt( gentity_t *ent ) -{//a rail-gun-like beam - int damage = CONC_ALT_DAMAGE, skip, traces = DISRUPTOR_ALT_TRACES; - qboolean render_impact = qtrue; - vec3_t start, end; - vec3_t /*muzzle2,*/ dir; - trace_t tr; - gentity_t *traceEnt, *tent; - float shotRange = 8192.0f; - qboolean hitDodged = qfalse; +static void WP_FireConcussionAlt(gentity_t *ent) { // a rail-gun-like beam + int damage = CONC_ALT_DAMAGE, skip, traces = DISRUPTOR_ALT_TRACES; + qboolean render_impact = qtrue; + vec3_t start, end; + vec3_t /*muzzle2,*/ dir; + trace_t tr; + gentity_t *traceEnt, *tent; + float shotRange = 8192.0f; + qboolean hitDodged = qfalse; vec3_t shot_mins, shot_maxs; - int i; + int i; - //Shove us backwards for half a second - VectorMA( ent->client->ps.velocity, -200, forward, ent->client->ps.velocity ); + // Shove us backwards for half a second + VectorMA(ent->client->ps.velocity, -200, forward, ent->client->ps.velocity); ent->client->ps.groundEntityNum = ENTITYNUM_NONE; - if ( (ent->client->ps.pm_flags&PMF_DUCKED) ) - {//hunkered down + if ((ent->client->ps.pm_flags & PMF_DUCKED)) { // hunkered down ent->client->ps.pm_time = 100; - } - else - { + } else { ent->client->ps.pm_time = 250; } -// ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK|PMF_TIME_NOFRICTION; - //FIXME: only if on ground? So no "rocket jump"? Or: (see next FIXME) - //FIXME: instead, set a forced ucmd backmove instead of this sliding + // ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK|PMF_TIME_NOFRICTION; + // FIXME: only if on ground? So no "rocket jump"? Or: (see next FIXME) + // FIXME: instead, set a forced ucmd backmove instead of this sliding - //VectorCopy( muzzle, muzzle2 ); // making a backup copy + // VectorCopy( muzzle, muzzle2 ); // making a backup copy - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin ); + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); skip = ent->s.number; -// if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) -// { -// // in overcharge mode, so doing double damage -// damage *= 2; -// } - - //Make it a little easier to hit guys at long range - VectorSet( shot_mins, -1, -1, -1 ); - VectorSet( shot_maxs, 1, 1, 1 ); - - for ( i = 0; i < traces; i++ ) - { - VectorMA( start, shotRange, forward, end ); - - //NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" - //alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter - //trap->trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); - if (d_projectileGhoul2Collision.integer) - { - trap->Trace( &tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); - } - else - { - trap->Trace( &tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, qfalse, 0, 0 ); + // if ( ent->client && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > 0 && ent->client->ps.powerups[PW_WEAPON_OVERCHARGE] > cg.time ) + // { + // // in overcharge mode, so doing double damage + // damage *= 2; + // } + + // Make it a little easier to hit guys at long range + VectorSet(shot_mins, -1, -1, -1); + VectorSet(shot_maxs, 1, 1, 1); + + for (i = 0; i < traces; i++) { + VectorMA(start, shotRange, forward, end); + + // NOTE: if you want to be able to hit guys in emplaced guns, use "G2_COLLIDE, 10" instead of "G2_RETURNONHIT, 0" + // alternately, if you end up hitting an emplaced_gun that has a sitter, just redo this one trace with the "G2_COLLIDE, 10" to see if we it the sitter + // trap->trace( &tr, start, NULL, NULL, end, skip, MASK_SHOT, G2_COLLIDE, 10 );//G2_RETURNONHIT, 0 ); + if (d_projectileGhoul2Collision.integer) { + trap->Trace(&tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_HITCORPSES, + g_g2TraceLod.integer); + } else { + trap->Trace(&tr, start, shot_mins, shot_maxs, end, skip, MASK_SHOT, qfalse, 0, 0); } traceEnt = &g_entities[tr.entityNum]; - if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) - { //g2 collision checks -rww - if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) - { //since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the index of the surface on the ghoul2 model we collided with. + if (d_projectileGhoul2Collision.integer && traceEnt->inuse && traceEnt->client) { // g2 collision checks -rww + if (traceEnt->inuse && traceEnt->client && traceEnt->ghoul2) { // since we used G2TRFLAG_GETSURFINDEX, tr.surfaceFlags will actually contain the + // index of the surface on the ghoul2 model we collided with. traceEnt->client->g2LastSurfaceHit = tr.surfaceFlags; traceEnt->client->g2LastSurfaceTime = level.time; } - if (traceEnt->ghoul2) - { - tr.surfaceFlags = 0; //clear the surface flags after, since we actually care about them in here. + if (traceEnt->ghoul2) { + tr.surfaceFlags = 0; // clear the surface flags after, since we actually care about them in here. } } - if ( tr.surfaceFlags & SURF_NOIMPACT ) - { + if (tr.surfaceFlags & SURF_NOIMPACT) { render_impact = qfalse; } - if ( tr.entityNum == ent->s.number ) - { + if (tr.entityNum == ent->s.number) { // should never happen, but basically we don't want to consider a hit to ourselves? // Get ready for an attempt to trace through another person - //VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + // VectorCopy( tr.endpos, muzzle2 ); + VectorCopy(tr.endpos, start); skip = tr.entityNum; #ifdef _DEBUG - Com_Printf( "BAD! Concussion gun shot somehow traced back and hit the owner!\n" ); + Com_Printf("BAD! Concussion gun shot somehow traced back and hit the owner!\n"); #endif continue; } // always render a shot beam, doing this the old way because I don't much feel like overriding the effect. - //NOTE: let's just draw one beam at the end - //tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); - //tent->svFlags |= SVF_BROADCAST; + // NOTE: let's just draw one beam at the end + // tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); + // tent->svFlags |= SVF_BROADCAST; - //VectorCopy( muzzle2, tent->s.origin2 ); + // VectorCopy( muzzle2, tent->s.origin2 ); - if ( tr.fraction >= 1.0f ) - { + if (tr.fraction >= 1.0f) { // draw the beam but don't do anything else break; } - if ( traceEnt->s.weapon == WP_SABER )//&& traceEnt->NPC - {//FIXME: need a more reliable way to know we hit a jedi? - hitDodged = Jedi_DodgeEvasion( traceEnt, ent, &tr, HL_NONE ); - //acts like we didn't even hit him + if (traceEnt->s.weapon == WP_SABER) //&& traceEnt->NPC + { // FIXME: need a more reliable way to know we hit a jedi? + hitDodged = Jedi_DodgeEvasion(traceEnt, ent, &tr, HL_NONE); + // acts like we didn't even hit him } - if ( !hitDodged ) - { - if ( render_impact ) - { - if (( tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage ) - || !Q_stricmp( traceEnt->classname, "misc_model_breakable" ) - || traceEnt->s.eType == ET_MOVER ) - { + if (!hitDodged) { + if (render_impact) { + if ((tr.entityNum < ENTITYNUM_WORLD && traceEnt->takedamage) || !Q_stricmp(traceEnt->classname, "misc_model_breakable") || + traceEnt->s.eType == ET_MOVER) { qboolean noKnockBack; // Create a simple impact type mark that doesn't last long in the world - //G_PlayEffectID( G_EffectIndex( "concussion/alt_hit" ), tr.endpos, tr.plane.normal ); - //no no no + // G_PlayEffectID( G_EffectIndex( "concussion/alt_hit" ), tr.endpos, tr.plane.normal ); + // no no no - if ( traceEnt->client && LogAccuracyHit( traceEnt, ent )) - {//NOTE: hitting multiple ents can still get you over 100% accuracy + if (traceEnt->client && LogAccuracyHit(traceEnt, ent)) { // NOTE: hitting multiple ents can still get you over 100% accuracy ent->client->accuracy_hits++; } - noKnockBack = (traceEnt->flags&FL_NO_KNOCKBACK);//will be set if they die, I want to know if it was on *before* they died - if ( traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH ) - {//hehe - G_Damage( traceEnt, ent, ent, forward, tr.endpos, 10, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_CONC_ALT ); + noKnockBack = (traceEnt->flags & FL_NO_KNOCKBACK); // will be set if they die, I want to know if it was on *before* they died + if (traceEnt && traceEnt->client && traceEnt->client->NPC_class == CLASS_GALAKMECH) { // hehe + G_Damage(traceEnt, ent, ent, forward, tr.endpos, 10, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_CONC_ALT); break; } - G_Damage( traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NO_KNOCKBACK|DAMAGE_NO_HIT_LOC, MOD_CONC_ALT ); + G_Damage(traceEnt, ent, ent, forward, tr.endpos, damage, DAMAGE_NO_KNOCKBACK | DAMAGE_NO_HIT_LOC, MOD_CONC_ALT); - //do knockback and knockdown manually - if ( traceEnt->client ) - {//only if we hit a client + // do knockback and knockdown manually + if (traceEnt->client) { // only if we hit a client vec3_t pushDir; - VectorCopy( forward, pushDir ); - if ( pushDir[2] < 0.2f ) - { + VectorCopy(forward, pushDir); + if (pushDir[2] < 0.2f) { pushDir[2] = 0.2f; - }//hmm, re-normalize? nah... + } // hmm, re-normalize? nah... /* if ( !noKnockBack ) {//knock-backable G_Throw( traceEnt, pushDir, 200 ); } */ - if ( traceEnt->health > 0 ) - {//alive - //if ( G_HasKnockdownAnims( traceEnt ) ) + if (traceEnt->health > 0) { // alive + // if ( G_HasKnockdownAnims( traceEnt ) ) if (!noKnockBack && !traceEnt->localAnimIndex && traceEnt->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && - BG_KnockDownable(&traceEnt->client->ps)) //just check for humanoids.. - {//knock-downable - //G_Knockdown( traceEnt, ent, pushDir, 400, qtrue ); + BG_KnockDownable(&traceEnt->client->ps)) // just check for humanoids.. + { // knock-downable + // G_Knockdown( traceEnt, ent, pushDir, 400, qtrue ); vec3_t plPDif; float pStr; - //cap it and stuff, base the strength and whether or not we can knockdown on the distance - //from the shooter to the target + // cap it and stuff, base the strength and whether or not we can knockdown on the distance + // from the shooter to the target VectorSubtract(traceEnt->client->ps.origin, ent->client->ps.origin, plPDif); - pStr = 500.0f-VectorLength(plPDif); - if (pStr < 150.0f) - { + pStr = 500.0f - VectorLength(plPDif); + if (pStr < 150.0f) { pStr = 150.0f; } - if (pStr > 200.0f) - { + if (pStr > 200.0f) { traceEnt->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; traceEnt->client->ps.forceHandExtendTime = level.time + 1100; - traceEnt->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim + traceEnt->client->ps.forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim } traceEnt->client->ps.otherKiller = ent->s.number; traceEnt->client->ps.otherKillerTime = level.time + 5000; traceEnt->client->ps.otherKillerDebounceTime = level.time + 100; - traceEnt->client->ps.velocity[0] += pushDir[0]*pStr; - traceEnt->client->ps.velocity[1] += pushDir[1]*pStr; + traceEnt->client->ps.velocity[0] += pushDir[0] * pStr; + traceEnt->client->ps.velocity[1] += pushDir[1] * pStr; traceEnt->client->ps.velocity[2] = pStr; } } } - if ( traceEnt->s.eType == ET_MOVER ) - {//stop the traces on any mover + if (traceEnt->s.eType == ET_MOVER) { // stop the traces on any mover break; } - } - else - { - // we only make this mark on things that can't break or move - // tent = G_TempEntity(tr.endpos, EV_MISSILE_MISS); - // tent->s.eventParm = DirToByte(tr.plane.normal); - // tent->s.eFlags |= EF_ALT_FIRING; - - //tent->svFlags |= SVF_BROADCAST; - //eh? why broadcast? - // VectorCopy( tr.plane.normal, tent->pos1 ); - - //mmm..no..don't do this more than once for no reason whatsoever. + } else { + // we only make this mark on things that can't break or move + // tent = G_TempEntity(tr.endpos, EV_MISSILE_MISS); + // tent->s.eventParm = DirToByte(tr.plane.normal); + // tent->s.eFlags |= EF_ALT_FIRING; + + // tent->svFlags |= SVF_BROADCAST; + // eh? why broadcast? + // VectorCopy( tr.plane.normal, tent->pos1 ); + + // mmm..no..don't do this more than once for no reason whatsoever. break; // hit solid, but doesn't take damage, so stop the shot...we _could_ allow it to shoot through walls, might be cool? } - } - else // not rendering impact, must be a skybox or other similar thing? + } else // not rendering impact, must be a skybox or other similar thing? { break; // don't try anymore traces } } // Get ready for an attempt to trace through another person - //VectorCopy( tr.endpos, muzzle2 ); - VectorCopy( tr.endpos, start ); + // VectorCopy( tr.endpos, muzzle2 ); + VectorCopy(tr.endpos, start); skip = tr.entityNum; hitDodged = qfalse; } - //just draw one beam all the way to the end -// tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); -// tent->svFlags |= SVF_BROADCAST; - //again, why broadcast? + // just draw one beam all the way to the end + // tent = G_TempEntity( tr.endpos, EV_CONC_ALT_SHOT ); + // tent->svFlags |= SVF_BROADCAST; + // again, why broadcast? -// tent = G_TempEntity(tr.endpos, EV_MISSILE_MISS); -// tent->s.eventParm = DirToByte(tr.plane.normal); -// tent->s.eFlags |= EF_ALT_FIRING; -// VectorCopy( muzzle, tent->s.origin2 ); + // tent = G_TempEntity(tr.endpos, EV_MISSILE_MISS); + // tent->s.eventParm = DirToByte(tr.plane.normal); + // tent->s.eFlags |= EF_ALT_FIRING; + // VectorCopy( muzzle, tent->s.origin2 ); // now go along the trail and make sight events - VectorSubtract( tr.endpos, muzzle, dir ); + VectorSubtract(tr.endpos, muzzle, dir); -// shotDist = VectorNormalize( dir ); + // shotDist = VectorNormalize( dir ); - //let's pack all this junk into a single tempent, and send it off. + // let's pack all this junk into a single tempent, and send it off. tent = G_TempEntity(tr.endpos, EV_CONC_ALT_IMPACT); tent->s.eventParm = DirToByte(tr.plane.normal); tent->s.owner = ent->s.number; @@ -3320,7 +2913,7 @@ static void WP_FireConcussionAlt( gentity_t *ent ) VectorCopy(muzzle, tent->s.origin2); VectorCopy(forward, tent->s.angles2); -#if 0 //yuck +#if 0 // yuck //FIXME: if shoot *really* close to someone, the alert could be way out of their FOV for ( dist = 0; dist < shotDist; dist += 64 ) { @@ -3338,37 +2931,36 @@ static void WP_FireConcussionAlt( gentity_t *ent ) #endif } -static void WP_FireConcussion( gentity_t *ent ) -{//a fast rocket-like projectile - vec3_t start; - int damage = CONC_DAMAGE; - float vel = CONC_VELOCITY; +static void WP_FireConcussion(gentity_t *ent) { // a fast rocket-like projectile + vec3_t start; + int damage = CONC_DAMAGE; + float vel = CONC_VELOCITY; gentity_t *missile; - //hold us still for a bit - //ent->client->ps.pm_time = 300; - //ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; - //add viewkick -// if ( ent->s.number < MAX_CLIENTS//player only -// && !cg.renderingThirdPerson )//gives an advantage to being in 3rd person, but would look silly otherwise -// {//kick the view back -// cg.kick_angles[PITCH] = Q_flrand( -10, -15 ); -// cg.kick_time = level.time; -// } - //mm..yeah..this needs some reworking for mp + // hold us still for a bit + // ent->client->ps.pm_time = 300; + // ent->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; + // add viewkick + // if ( ent->s.number < MAX_CLIENTS//player only + // && !cg.renderingThirdPerson )//gives an advantage to being in 3rd person, but would look silly otherwise + // {//kick the view back + // cg.kick_angles[PITCH] = Q_flrand( -10, -15 ); + // cg.kick_time = level.time; + // } + // mm..yeah..this needs some reworking for mp - VectorCopy( muzzle, start ); - WP_TraceSetStart( ent, start, vec3_origin, vec3_origin );//make sure our start point isn't on the other side of a wall + VectorCopy(muzzle, start); + WP_TraceSetStart(ent, start, vec3_origin, vec3_origin); // make sure our start point isn't on the other side of a wall - missile = CreateMissile( start, forward, vel, 10000, ent, qfalse ); + missile = CreateMissile(start, forward, vel, 10000, ent, qfalse); missile->classname = "conc_proj"; missile->s.weapon = WP_CONCUSSION; missile->mass = 10; // Make it easier to hit things - VectorSet( missile->r.maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE ); - VectorScale( missile->r.maxs, -1, missile->r.mins ); + VectorSet(missile->r.maxs, ROCKET_SIZE, ROCKET_SIZE, ROCKET_SIZE); + VectorScale(missile->r.maxs, -1, missile->r.mins); missile->damage = damage; missile->dflags = DAMAGE_EXTRA_KNOCKBACK; @@ -3384,171 +2976,132 @@ static void WP_FireConcussion( gentity_t *ent ) missile->bounceCount = 0; } - //--------------------------------------------------------- // FireStunBaton //--------------------------------------------------------- -void WP_FireStunBaton( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end; - vec3_t muzzleStun; +void WP_FireStunBaton(gentity_t *ent, qboolean alt_fire) { + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end; + vec3_t muzzleStun; - if (!ent->client) - { + if (!ent->client) { VectorCopy(ent->r.currentOrigin, muzzleStun); muzzleStun[2] += 8; - } - else - { + } else { VectorCopy(ent->client->ps.origin, muzzleStun); - muzzleStun[2] += ent->client->ps.viewheight-6; + muzzleStun[2] += ent->client->ps.viewheight - 6; } VectorMA(muzzleStun, 20.0f, forward, muzzleStun); VectorMA(muzzleStun, 4.0f, vright, muzzleStun); - VectorMA( muzzleStun, STUN_BATON_RANGE, forward, end ); + VectorMA(muzzleStun, STUN_BATON_RANGE, forward, end); - VectorSet( maxs, 6, 6, 6 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 6, 6, 6); + VectorScale(maxs, -1, mins); - trap->Trace ( &tr, muzzleStun, mins, maxs, end, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, muzzleStun, mins, maxs, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.entityNum >= ENTITYNUM_WORLD ) - { + if (tr.entityNum >= ENTITYNUM_WORLD) { return; } tr_ent = &g_entities[tr.entityNum]; - if (tr_ent && tr_ent->takedamage && tr_ent->client) - { //see if either party is involved in a duel - if (tr_ent->client->ps.duelInProgress && - tr_ent->client->ps.duelIndex != ent->s.number) - { + if (tr_ent && tr_ent->takedamage && tr_ent->client) { // see if either party is involved in a duel + if (tr_ent->client->ps.duelInProgress && tr_ent->client->ps.duelIndex != ent->s.number) { return; } - if (ent->client && - ent->client->ps.duelInProgress && - ent->client->ps.duelIndex != tr_ent->s.number) - { + if (ent->client && ent->client->ps.duelInProgress && ent->client->ps.duelIndex != tr_ent->s.number) { return; } } - if ( tr_ent && tr_ent->takedamage ) - { - G_PlayEffect( EFFECT_STUNHIT, tr.endpos, tr.plane.normal ); - - G_Sound( tr_ent, CHAN_WEAPON, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); - G_Damage( tr_ent, ent, ent, forward, tr.endpos, STUN_BATON_DAMAGE, (DAMAGE_NO_KNOCKBACK|DAMAGE_HALF_ABSORB), MOD_STUN_BATON ); - - if (tr_ent->client) - { //if it's a player then use the shock effect - if ( tr_ent->client->NPC_class == CLASS_VEHICLE ) - {//not on vehicles - if ( !tr_ent->m_pVehicle - || tr_ent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL - || tr_ent->m_pVehicle->m_pVehicleInfo->type == VH_FLIER ) - {//can zap animals - tr_ent->client->ps.electrifyTime = level.time + Q_irand( 3000, 4000 ); + if (tr_ent && tr_ent->takedamage) { + G_PlayEffect(EFFECT_STUNHIT, tr.endpos, tr.plane.normal); + + G_Sound(tr_ent, CHAN_WEAPON, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); + G_Damage(tr_ent, ent, ent, forward, tr.endpos, STUN_BATON_DAMAGE, (DAMAGE_NO_KNOCKBACK | DAMAGE_HALF_ABSORB), MOD_STUN_BATON); + + if (tr_ent->client) { // if it's a player then use the shock effect + if (tr_ent->client->NPC_class == CLASS_VEHICLE) { // not on vehicles + if (!tr_ent->m_pVehicle || tr_ent->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL || + tr_ent->m_pVehicle->m_pVehicleInfo->type == VH_FLIER) { // can zap animals + tr_ent->client->ps.electrifyTime = level.time + Q_irand(3000, 4000); } - } - else - { + } else { tr_ent->client->ps.electrifyTime = level.time + 700; } } } } - //--------------------------------------------------------- // FireMelee //--------------------------------------------------------- -void WP_FireMelee( gentity_t *ent, qboolean alt_fire ) -{ - gentity_t *tr_ent; - trace_t tr; - vec3_t mins, maxs, end; - vec3_t muzzlePunch; - - if (ent->client && ent->client->ps.torsoAnim == BOTH_MELEE2) - { //right - if (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_RARM)) - { +void WP_FireMelee(gentity_t *ent, qboolean alt_fire) { + gentity_t *tr_ent; + trace_t tr; + vec3_t mins, maxs, end; + vec3_t muzzlePunch; + + if (ent->client && ent->client->ps.torsoAnim == BOTH_MELEE2) { // right + if (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_RARM)) { return; } - } - else - { //left - if (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM)) - { + } else { // left + if (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM)) { return; } } - if (!ent->client) - { + if (!ent->client) { VectorCopy(ent->r.currentOrigin, muzzlePunch); muzzlePunch[2] += 8; - } - else - { + } else { VectorCopy(ent->client->ps.origin, muzzlePunch); - muzzlePunch[2] += ent->client->ps.viewheight-6; + muzzlePunch[2] += ent->client->ps.viewheight - 6; } VectorMA(muzzlePunch, 20.0f, forward, muzzlePunch); VectorMA(muzzlePunch, 4.0f, vright, muzzlePunch); - VectorMA( muzzlePunch, MELEE_RANGE, forward, end ); + VectorMA(muzzlePunch, MELEE_RANGE, forward, end); - VectorSet( maxs, 6, 6, 6 ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, 6, 6, 6); + VectorScale(maxs, -1, mins); - trap->Trace ( &tr, muzzlePunch, mins, maxs, end, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, muzzlePunch, mins, maxs, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); - if (tr.entityNum != ENTITYNUM_NONE) - { //hit something + if (tr.entityNum != ENTITYNUM_NONE) { // hit something tr_ent = &g_entities[tr.entityNum]; - G_Sound( ent, CHAN_AUTO, G_SoundIndex( va("sound/weapons/melee/punch%d", Q_irand(1, 4)) ) ); + G_Sound(ent, CHAN_AUTO, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); - if (tr_ent->takedamage && tr_ent->client) - { //special duel checks - if (tr_ent->client->ps.duelInProgress && - tr_ent->client->ps.duelIndex != ent->s.number) - { + if (tr_ent->takedamage && tr_ent->client) { // special duel checks + if (tr_ent->client->ps.duelInProgress && tr_ent->client->ps.duelIndex != ent->s.number) { return; } - if (ent->client && - ent->client->ps.duelInProgress && - ent->client->ps.duelIndex != tr_ent->s.number) - { + if (ent->client && ent->client->ps.duelInProgress && ent->client->ps.duelIndex != tr_ent->s.number) { return; } } - if ( tr_ent->takedamage ) - { //damage them, do more damage if we're in the second right hook + if (tr_ent->takedamage) { // damage them, do more damage if we're in the second right hook int dmg = MELEE_SWING1_DAMAGE; - if (ent->client && ent->client->ps.torsoAnim == BOTH_MELEE2) - { //do a tad bit more damage on the second swing + if (ent->client && ent->client->ps.torsoAnim == BOTH_MELEE2) { // do a tad bit more damage on the second swing dmg = MELEE_SWING2_DAMAGE; } - if ( G_HeavyMelee( ent ) ) - { //2x damage for heavy melee class + if (G_HeavyMelee(ent)) { // 2x damage for heavy melee class dmg *= 2; } - G_Damage( tr_ent, ent, ent, forward, tr.endpos, dmg, DAMAGE_NO_ARMOR, MOD_MELEE ); + G_Damage(tr_ent, ent, ent, forward, tr.endpos, dmg, DAMAGE_NO_ARMOR, MOD_MELEE); } } } @@ -3559,7 +3112,6 @@ void WP_FireMelee( gentity_t *ent, qboolean alt_fire ) //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// - /* ====================== SnapVectorTowards @@ -3570,61 +3122,57 @@ rather than blindly truncating. This prevents it from truncating into a wall. ====================== */ -void SnapVectorTowards( vec3_t v, vec3_t to ) { - int i; +void SnapVectorTowards(vec3_t v, vec3_t to) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { - if ( to[i] <= v[i] ) { - v[i] = floorf( v[i] ); + for (i = 0; i < 3; i++) { + if (to[i] <= v[i]) { + v[i] = floorf(v[i]); } else { - v[i] = ceilf( v[i] ); + v[i] = ceilf(v[i]); } } } - //====================================================================== - /* =============== LogAccuracyHit =============== */ -qboolean LogAccuracyHit( gentity_t *target, gentity_t *attacker ) { - if( !target->takedamage ) { +qboolean LogAccuracyHit(gentity_t *target, gentity_t *attacker) { + if (!target->takedamage) { return qfalse; } - if ( target == attacker ) { + if (target == attacker) { return qfalse; } - if( !target->client ) { + if (!target->client) { return qfalse; } - if (!attacker) - { + if (!attacker) { return qfalse; } - if( !attacker->client ) { + if (!attacker->client) { return qfalse; } - if( target->client->ps.stats[STAT_HEALTH] <= 0 ) { + if (target->client->ps.stats[STAT_HEALTH] <= 0) { return qfalse; } - if ( OnSameTeam( target, attacker ) ) { + if (OnSameTeam(target, attacker)) { return qfalse; } return qtrue; } - /* =============== CalcMuzzlePoint @@ -3636,19 +3184,17 @@ The down side would be that it does not necessarily look alright from a first person perspective. =============== */ -void CalcMuzzlePoint ( gentity_t *ent, const vec3_t inForward, const vec3_t inRight, const vec3_t inUp, vec3_t muzzlePoint ) -{ +void CalcMuzzlePoint(gentity_t *ent, const vec3_t inForward, const vec3_t inRight, const vec3_t inUp, vec3_t muzzlePoint) { int weapontype; vec3_t muzzleOffPoint; weapontype = ent->s.weapon; - VectorCopy( ent->s.pos.trBase, muzzlePoint ); + VectorCopy(ent->s.pos.trBase, muzzlePoint); VectorCopy(WP_MuzzlePoint[weapontype], muzzleOffPoint); - if (weapontype > WP_NONE && weapontype < WP_NUM_WEAPONS) - { // Use the table to generate the muzzlepoint; - { // Crouching. Use the add-to-Z method to adjust vertically. + if (weapontype > WP_NONE && weapontype < WP_NUM_WEAPONS) { // Use the table to generate the muzzlepoint; + { // Crouching. Use the add-to-Z method to adjust vertically. VectorMA(muzzlePoint, muzzleOffPoint[0], inForward, muzzlePoint); VectorMA(muzzlePoint, muzzleOffPoint[1], inRight, muzzlePoint); muzzlePoint[2] += ent->client->ps.viewheight + muzzleOffPoint[2]; @@ -3656,105 +3202,88 @@ void CalcMuzzlePoint ( gentity_t *ent, const vec3_t inForward, const vec3_t inRi } // snap to integer coordinates for more efficient network bandwidth usage - SnapVector( muzzlePoint ); + SnapVector(muzzlePoint); } -extern void G_MissileImpact( gentity_t *ent, trace_t *trace ); -void WP_TouchVehMissile( gentity_t *ent, gentity_t *other, trace_t *trace ) -{ - trace_t myTrace; - memcpy( (void *)&myTrace, (void *)trace, sizeof(myTrace) ); - if ( other ) - { +extern void G_MissileImpact(gentity_t *ent, trace_t *trace); +void WP_TouchVehMissile(gentity_t *ent, gentity_t *other, trace_t *trace) { + trace_t myTrace; + memcpy((void *)&myTrace, (void *)trace, sizeof(myTrace)); + if (other) { myTrace.entityNum = other->s.number; } - G_MissileImpact( ent, &myTrace ); + G_MissileImpact(ent, &myTrace); } -void WP_CalcVehMuzzle(gentity_t *ent, int muzzleNum) -{ +void WP_CalcVehMuzzle(gentity_t *ent, int muzzleNum) { Vehicle_t *pVeh = ent->m_pVehicle; mdxaBone_t boltMatrix; - vec3_t vehAngles; + vec3_t vehAngles; assert(pVeh); - if (pVeh->m_iMuzzleTime[muzzleNum] == level.time) - { //already done for this frame, don't need to do it again + if (pVeh->m_iMuzzleTime[muzzleNum] == level.time) { // already done for this frame, don't need to do it again return; } - //Uh... how about we set this, hunh...? :) + // Uh... how about we set this, hunh...? :) pVeh->m_iMuzzleTime[muzzleNum] = level.time; - VectorCopy( ent->client->ps.viewangles, vehAngles ); - if ( pVeh->m_pVehicleInfo - && (pVeh->m_pVehicleInfo->type == VH_ANIMAL - ||pVeh->m_pVehicleInfo->type == VH_WALKER - ||pVeh->m_pVehicleInfo->type == VH_SPEEDER) ) - { + VectorCopy(ent->client->ps.viewangles, vehAngles); + if (pVeh->m_pVehicleInfo && + (pVeh->m_pVehicleInfo->type == VH_ANIMAL || pVeh->m_pVehicleInfo->type == VH_WALKER || pVeh->m_pVehicleInfo->type == VH_SPEEDER)) { vehAngles[PITCH] = vehAngles[ROLL] = 0; } - trap->G2API_GetBoltMatrix_NoRecNoRot(ent->ghoul2, 0, pVeh->m_iMuzzleTag[muzzleNum], &boltMatrix, vehAngles, - ent->client->ps.origin, level.time, NULL, ent->modelScale); + trap->G2API_GetBoltMatrix_NoRecNoRot(ent->ghoul2, 0, pVeh->m_iMuzzleTag[muzzleNum], &boltMatrix, vehAngles, ent->client->ps.origin, level.time, NULL, + ent->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pVeh->m_vMuzzlePos[muzzleNum]); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, pVeh->m_vMuzzleDir[muzzleNum]); } -void WP_VehWeapSetSolidToOwner( gentity_t *self ) -{ +void WP_VehWeapSetSolidToOwner(gentity_t *self) { self->r.svFlags |= SVF_OWNERNOTSHARED; - if ( self->genericValue1 ) - {//expire after a time - if ( self->genericValue2 ) - {//blow up when your lifetime is up - self->think = G_ExplodeMissile;//FIXME: custom func? - } - else - {//just remove yourself - self->think = G_FreeEntity;//FIXME: custom func? + if (self->genericValue1) { // expire after a time + if (self->genericValue2) { // blow up when your lifetime is up + self->think = G_ExplodeMissile; // FIXME: custom func? + } else { // just remove yourself + self->think = G_FreeEntity; // FIXME: custom func? } self->nextthink = level.time + self->genericValue1; } } -#define VEH_HOMING_MISSILE_THINK_TIME 100 -gentity_t *WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon, qboolean alt_fire, qboolean isTurretWeap ) -{ - gentity_t *missile = NULL; +#define VEH_HOMING_MISSILE_THINK_TIME 100 +gentity_t *WP_FireVehicleWeapon(gentity_t *ent, vec3_t start, vec3_t dir, vehWeaponInfo_t *vehWeapon, qboolean alt_fire, qboolean isTurretWeap) { + gentity_t *missile = NULL; - //FIXME: add some randomness...? Inherent inaccuracy stat of weapon? Pilot skill? - if ( !vehWeapon ) - {//invalid vehicle weapon + // FIXME: add some randomness...? Inherent inaccuracy stat of weapon? Pilot skill? + if (!vehWeapon) { // invalid vehicle weapon return NULL; - } - else if ( vehWeapon->bIsProjectile ) - {//projectile entity - vec3_t mins, maxs; + } else if (vehWeapon->bIsProjectile) { // projectile entity + vec3_t mins, maxs; - VectorSet( maxs, vehWeapon->fWidth/2.0f,vehWeapon->fWidth/2.0f,vehWeapon->fHeight/2.0f ); - VectorScale( maxs, -1, mins ); + VectorSet(maxs, vehWeapon->fWidth / 2.0f, vehWeapon->fWidth / 2.0f, vehWeapon->fHeight / 2.0f); + VectorScale(maxs, -1, mins); - //make sure our start point isn't on the other side of a wall - WP_TraceSetStart( ent, start, mins, maxs ); + // make sure our start point isn't on the other side of a wall + WP_TraceSetStart(ent, start, mins, maxs); - //FIXME: CUSTOM MODEL? - //QUERY: alt_fire true or not? Does it matter? - missile = CreateMissile( start, dir, vehWeapon->fSpeed, 10000, ent, qfalse ); + // FIXME: CUSTOM MODEL? + // QUERY: alt_fire true or not? Does it matter? + missile = CreateMissile(start, dir, vehWeapon->fSpeed, 10000, ent, qfalse); missile->classname = "vehicle_proj"; - missile->s.genericenemyindex = ent->s.number+MAX_GENTITIES; + missile->s.genericenemyindex = ent->s.number + MAX_GENTITIES; missile->damage = vehWeapon->iDamage; missile->splashDamage = vehWeapon->iSplashDamage; missile->splashRadius = vehWeapon->fSplashRadius; - //FIXME: externalize some of these properties? + // FIXME: externalize some of these properties? missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->clipmask = MASK_SHOT; - //Maybe by checking flags...? - if ( vehWeapon->bSaberBlockable ) - { + // Maybe by checking flags...? + if (vehWeapon->bSaberBlockable) { missile->clipmask |= CONTENTS_LIGHTSABER; } /* @@ -3768,232 +3297,192 @@ gentity_t *WP_FireVehicleWeapon( gentity_t *ent, vec3_t start, vec3_t dir, vehWe } */ // Make it easier to hit things - VectorCopy( mins, missile->r.mins ); - VectorCopy( maxs, missile->r.maxs ); - //some slightly different stuff for things with bboxes - if ( vehWeapon->fWidth || vehWeapon->fHeight ) - {//we assume it's a rocket-like thing - missile->s.weapon = WP_ROCKET_LAUNCHER;//does this really matter? - missile->methodOfDeath = MOD_VEHICLE;//MOD_ROCKET; - missile->splashMethodOfDeath = MOD_VEHICLE;//MOD_ROCKET;// ?SPLASH; + VectorCopy(mins, missile->r.mins); + VectorCopy(maxs, missile->r.maxs); + // some slightly different stuff for things with bboxes + if (vehWeapon->fWidth || vehWeapon->fHeight) { // we assume it's a rocket-like thing + missile->s.weapon = WP_ROCKET_LAUNCHER; // does this really matter? + missile->methodOfDeath = MOD_VEHICLE; // MOD_ROCKET; + missile->splashMethodOfDeath = MOD_VEHICLE; // MOD_ROCKET;// ?SPLASH; // we don't want it to ever bounce missile->bounceCount = 0; missile->mass = 10; - } - else - {//a blaster-laser-like thing - missile->s.weapon = WP_BLASTER;//does this really matter? - missile->methodOfDeath = MOD_VEHICLE; //count as a heavy weap - missile->splashMethodOfDeath = MOD_VEHICLE;// ?SPLASH; + } else { // a blaster-laser-like thing + missile->s.weapon = WP_BLASTER; // does this really matter? + missile->methodOfDeath = MOD_VEHICLE; // count as a heavy weap + missile->splashMethodOfDeath = MOD_VEHICLE; // ?SPLASH; // we don't want it to bounce forever missile->bounceCount = 8; } - if ( vehWeapon->bHasGravity ) - {//TESTME: is this all we need to do? - missile->s.weapon = WP_THERMAL;//does this really matter? + if (vehWeapon->bHasGravity) { // TESTME: is this all we need to do? + missile->s.weapon = WP_THERMAL; // does this really matter? missile->s.pos.trType = TR_GRAVITY; } - if ( vehWeapon->bIonWeapon ) - {//so it disables ship shields and sends them out of control + if (vehWeapon->bIonWeapon) { // so it disables ship shields and sends them out of control missile->s.weapon = WP_DEMP2; } - if ( vehWeapon->iHealth ) - {//the missile can take damage + if (vehWeapon->iHealth) { // the missile can take damage missile->health = vehWeapon->iHealth; missile->takedamage = qtrue; missile->r.contents = MASK_SHOT; missile->die = RocketDie; } - //pilot should own this projectile on server if we have a pilot - if (ent->m_pVehicle && ent->m_pVehicle->m_pPilot) - {//owned by vehicle pilot + // pilot should own this projectile on server if we have a pilot + if (ent->m_pVehicle && ent->m_pVehicle->m_pPilot) { // owned by vehicle pilot missile->r.ownerNum = ent->m_pVehicle->m_pPilot->s.number; - } - else - {//owned by vehicle? + } else { // owned by vehicle? missile->r.ownerNum = ent->s.number; } - //set veh as cgame side owner for purpose of fx overrides + // set veh as cgame side owner for purpose of fx overrides missile->s.owner = ent->s.number; - if ( alt_fire ) - {//use the second weapon's iShotFX + if (alt_fire) { // use the second weapon's iShotFX missile->s.eFlags |= EF_ALT_FIRING; } - if ( isTurretWeap ) - {//look for the turret weapon info on cgame side, not vehicle weapon info + if (isTurretWeap) { // look for the turret weapon info on cgame side, not vehicle weapon info missile->s.weapon = WP_TURRET; } - if ( vehWeapon->iLifeTime ) - {//expire after a time - if ( vehWeapon->bExplodeOnExpire ) - {//blow up when your lifetime is up - missile->think = G_ExplodeMissile;//FIXME: custom func? - } - else - {//just remove yourself - missile->think = G_FreeEntity;//FIXME: custom func? + if (vehWeapon->iLifeTime) { // expire after a time + if (vehWeapon->bExplodeOnExpire) { // blow up when your lifetime is up + missile->think = G_ExplodeMissile; // FIXME: custom func? + } else { // just remove yourself + missile->think = G_FreeEntity; // FIXME: custom func? } missile->nextthink = level.time + vehWeapon->iLifeTime; } - missile->s.otherEntityNum2 = (vehWeapon-&g_vehWeaponInfo[0]); + missile->s.otherEntityNum2 = (vehWeapon - &g_vehWeaponInfo[0]); missile->s.eFlags |= EF_JETPACK_ACTIVE; - //homing - if ( vehWeapon->fHoming ) - {//homing missile - if ( ent->client && ent->client->ps.rocketLockIndex != ENTITYNUM_NONE ) - { + // homing + if (vehWeapon->fHoming) { // homing missile + if (ent->client && ent->client->ps.rocketLockIndex != ENTITYNUM_NONE) { int dif = 0; float rTime; rTime = ent->client->ps.rocketLockTime; - if (rTime == -1) - { + if (rTime == -1) { rTime = ent->client->ps.rocketLastValidTime; } - if ( !vehWeapon->iLockOnTime ) - {//no minimum lock-on time - dif = 10;//guaranteed lock-on - } - else - { - float lockTimeInterval = vehWeapon->iLockOnTime/16.0f; - dif = ( level.time - rTime ) / lockTimeInterval; + if (!vehWeapon->iLockOnTime) { // no minimum lock-on time + dif = 10; // guaranteed lock-on + } else { + float lockTimeInterval = vehWeapon->iLockOnTime / 16.0f; + dif = (level.time - rTime) / lockTimeInterval; } - if (dif < 0) - { + if (dif < 0) { dif = 0; } - //It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in time between server and client - if ( dif >= 10 && rTime != -1 ) - { + // It's 10 even though it locks client-side at 8, because we want them to have a sturdy lock first, and because there's a slight difference in + // time between server and client + if (dif >= 10 && rTime != -1) { missile->enemy = &g_entities[ent->client->ps.rocketLockIndex]; - if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && !OnSameTeam(ent, missile->enemy)) - { //if enemy became invalid, died, or is on the same team, then don't seek it - missile->spawnflags |= 1;//just to let it know it should be faster... + if (missile->enemy && missile->enemy->client && missile->enemy->health > 0 && + !OnSameTeam(ent, missile->enemy)) { // if enemy became invalid, died, or is on the same team, then don't seek it + missile->spawnflags |= 1; // just to let it know it should be faster... missile->speed = vehWeapon->fSpeed; missile->angle = vehWeapon->fHoming; missile->radius = vehWeapon->fHomingFOV; - //crap, if we have a lifetime, need to store that somewhere else on ent and have rocketThink func check it every frame... - if ( vehWeapon->iLifeTime ) - {//expire after a time + // crap, if we have a lifetime, need to store that somewhere else on ent and have rocketThink func check it every frame... + if (vehWeapon->iLifeTime) { // expire after a time missile->genericValue1 = level.time + vehWeapon->iLifeTime; missile->genericValue2 = (int)(vehWeapon->bExplodeOnExpire); } - //now go ahead and use the rocketThink func - missile->think = rocketThink;//FIXME: custom func? + // now go ahead and use the rocketThink func + missile->think = rocketThink; // FIXME: custom func? missile->nextthink = level.time + VEH_HOMING_MISSILE_THINK_TIME; - missile->s.eFlags |= EF_RADAROBJECT;//FIXME: externalize - if ( missile->enemy->s.NPC_class == CLASS_VEHICLE ) - {//let vehicle know we've locked on to them + missile->s.eFlags |= EF_RADAROBJECT; // FIXME: externalize + if (missile->enemy->s.NPC_class == CLASS_VEHICLE) { // let vehicle know we've locked on to them missile->s.otherEntityNum = missile->enemy->s.number; } } } - VectorCopy( dir, missile->movedir ); - missile->random = 1.0f;//FIXME: externalize? + VectorCopy(dir, missile->movedir); + missile->random = 1.0f; // FIXME: externalize? } } - if ( !vehWeapon->fSpeed ) - {//a mine or something? - //only do damage when someone touches us - missile->s.weapon = WP_THERMAL;//does this really matter? - G_SetOrigin( missile, start ); + if (!vehWeapon->fSpeed) { // a mine or something? + // only do damage when someone touches us + missile->s.weapon = WP_THERMAL; // does this really matter? + G_SetOrigin(missile, start); missile->touch = WP_TouchVehMissile; - missile->s.eFlags |= EF_RADAROBJECT;//FIXME: externalize - //crap, if we have a lifetime, need to store that somewhere else on ent and have rocketThink func check it every frame... - if ( vehWeapon->iLifeTime ) - {//expire after a time + missile->s.eFlags |= EF_RADAROBJECT; // FIXME: externalize + // crap, if we have a lifetime, need to store that somewhere else on ent and have rocketThink func check it every frame... + if (vehWeapon->iLifeTime) { // expire after a time missile->genericValue1 = vehWeapon->iLifeTime; missile->genericValue2 = (int)(vehWeapon->bExplodeOnExpire); } - //now go ahead and use the setsolidtoowner func + // now go ahead and use the setsolidtoowner func missile->think = WP_VehWeapSetSolidToOwner; missile->nextthink = level.time + 3000; } - } - else - {//traceline - //FIXME: implement + } else { // traceline + // FIXME: implement } return missile; } -//custom routine to not waste tempents horribly -rww -void G_VehMuzzleFireFX( gentity_t *ent, gentity_t *broadcaster, int muzzlesFired ) -{ +// custom routine to not waste tempents horribly -rww +void G_VehMuzzleFireFX(gentity_t *ent, gentity_t *broadcaster, int muzzlesFired) { Vehicle_t *pVeh = ent->m_pVehicle; gentity_t *b; - if (!pVeh) - { + if (!pVeh) { return; } - if (!broadcaster) - { //oh well. We will WASTE A TEMPENT. - b = G_TempEntity( ent->client->ps.origin, EV_VEH_FIRE ); - } - else - { //joy + if (!broadcaster) { // oh well. We will WASTE A TEMPENT. + b = G_TempEntity(ent->client->ps.origin, EV_VEH_FIRE); + } else { // joy b = broadcaster; } - //this guy owns it + // this guy owns it b->s.owner = ent->s.number; - //this is the bitfield of all muzzles fired this time - //NOTE: just need MAX_VEHICLE_MUZZLES bits for this... should be cool since it's currently 12 and we're sending it in 16 bits + // this is the bitfield of all muzzles fired this time + // NOTE: just need MAX_VEHICLE_MUZZLES bits for this... should be cool since it's currently 12 and we're sending it in 16 bits b->s.trickedentindex = muzzlesFired; - if ( broadcaster ) - { //add the event - G_AddEvent( b, EV_VEH_FIRE, 0 ); + if (broadcaster) { // add the event + G_AddEvent(b, EV_VEH_FIRE, 0); } } -void G_EstimateCamPos( vec3_t viewAngles, vec3_t cameraFocusLoc, float viewheight, float thirdPersonRange, - float thirdPersonHorzOffset, float vertOffset, float pitchOffset, - int ignoreEntNum, vec3_t camPos ) -{ - int MASK_CAMERACLIP = (MASK_SOLID|CONTENTS_PLAYERCLIP); - float CAMERA_SIZE = 4; - vec3_t cameramins; - vec3_t cameramaxs; - vec3_t cameraFocusAngles, camerafwd, cameraup; - vec3_t cameraIdealTarget, cameraCurTarget; - vec3_t cameraIdealLoc, cameraCurLoc; - vec3_t diff; - vec3_t camAngles; - matrix3_t viewaxis; - trace_t trace; - - VectorSet( cameramins, -CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE ); - VectorSet( cameramaxs, CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE ); - - VectorCopy( viewAngles, cameraFocusAngles ); +void G_EstimateCamPos(vec3_t viewAngles, vec3_t cameraFocusLoc, float viewheight, float thirdPersonRange, float thirdPersonHorzOffset, float vertOffset, + float pitchOffset, int ignoreEntNum, vec3_t camPos) { + int MASK_CAMERACLIP = (MASK_SOLID | CONTENTS_PLAYERCLIP); + float CAMERA_SIZE = 4; + vec3_t cameramins; + vec3_t cameramaxs; + vec3_t cameraFocusAngles, camerafwd, cameraup; + vec3_t cameraIdealTarget, cameraCurTarget; + vec3_t cameraIdealLoc, cameraCurLoc; + vec3_t diff; + vec3_t camAngles; + matrix3_t viewaxis; + trace_t trace; + + VectorSet(cameramins, -CAMERA_SIZE, -CAMERA_SIZE, -CAMERA_SIZE); + VectorSet(cameramaxs, CAMERA_SIZE, CAMERA_SIZE, CAMERA_SIZE); + + VectorCopy(viewAngles, cameraFocusAngles); cameraFocusAngles[PITCH] += pitchOffset; - if ( !bg_fighterAltControl.integer ) - {//clamp view pitch - cameraFocusAngles[PITCH] = AngleNormalize180( cameraFocusAngles[PITCH] ); - if (cameraFocusAngles[PITCH] > 80.0) - { + if (!bg_fighterAltControl.integer) { // clamp view pitch + cameraFocusAngles[PITCH] = AngleNormalize180(cameraFocusAngles[PITCH]); + if (cameraFocusAngles[PITCH] > 80.0) { cameraFocusAngles[PITCH] = 80.0; - } - else if (cameraFocusAngles[PITCH] < -80.0) - { + } else if (cameraFocusAngles[PITCH] < -80.0) { cameraFocusAngles[PITCH] = -80.0; } } @@ -4001,100 +3490,80 @@ void G_EstimateCamPos( vec3_t viewAngles, vec3_t cameraFocusLoc, float viewheigh cameraFocusLoc[2] += viewheight; - VectorCopy( cameraFocusLoc, cameraIdealTarget ); + VectorCopy(cameraFocusLoc, cameraIdealTarget); cameraIdealTarget[2] += vertOffset; - //NOTE: on cgame, this uses the thirdpersontargetdamp value, we ignore that here - VectorCopy( cameraIdealTarget, cameraCurTarget ); - trap->Trace( &trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, ignoreEntNum, MASK_CAMERACLIP, qfalse, 0, 0 ); - if (trace.fraction < 1.0) - { + // NOTE: on cgame, this uses the thirdpersontargetdamp value, we ignore that here + VectorCopy(cameraIdealTarget, cameraCurTarget); + trap->Trace(&trace, cameraFocusLoc, cameramins, cameramaxs, cameraCurTarget, ignoreEntNum, MASK_CAMERACLIP, qfalse, 0, 0); + if (trace.fraction < 1.0) { VectorCopy(trace.endpos, cameraCurTarget); } VectorMA(cameraIdealTarget, -(thirdPersonRange), camerafwd, cameraIdealLoc); - //NOTE: on cgame, this uses the thirdpersoncameradamp value, we ignore that here - VectorCopy( cameraIdealLoc, cameraCurLoc ); + // NOTE: on cgame, this uses the thirdpersoncameradamp value, we ignore that here + VectorCopy(cameraIdealLoc, cameraCurLoc); trap->Trace(&trace, cameraCurTarget, cameramins, cameramaxs, cameraCurLoc, ignoreEntNum, MASK_CAMERACLIP, qfalse, 0, 0); - if (trace.fraction < 1.0) - { - VectorCopy( trace.endpos, cameraCurLoc ); + if (trace.fraction < 1.0) { + VectorCopy(trace.endpos, cameraCurLoc); } VectorSubtract(cameraCurTarget, cameraCurLoc, diff); { float dist = VectorNormalize(diff); - //under normal circumstances, should never be 0.00000 and so on. - if ( !dist || (diff[0] == 0 || diff[1] == 0) ) - {//must be hitting something, need some value to calc angles, so use cam forward - VectorCopy( camerafwd, diff ); + // under normal circumstances, should never be 0.00000 and so on. + if (!dist || (diff[0] == 0 || diff[1] == 0)) { // must be hitting something, need some value to calc angles, so use cam forward + VectorCopy(camerafwd, diff); } } vectoangles(diff, camAngles); - if ( thirdPersonHorzOffset != 0.0f ) - { - AnglesToAxis( camAngles, viewaxis ); - VectorMA( cameraCurLoc, thirdPersonHorzOffset, viewaxis[1], cameraCurLoc ); + if (thirdPersonHorzOffset != 0.0f) { + AnglesToAxis(camAngles, viewaxis); + VectorMA(cameraCurLoc, thirdPersonHorzOffset, viewaxis[1], cameraCurLoc); } VectorCopy(cameraCurLoc, camPos); } -void WP_GetVehicleCamPos( gentity_t *ent, gentity_t *pilot, vec3_t camPos ) -{ +void WP_GetVehicleCamPos(gentity_t *ent, gentity_t *pilot, vec3_t camPos) { float thirdPersonHorzOffset = ent->m_pVehicle->m_pVehicleInfo->cameraHorzOffset; float thirdPersonRange = ent->m_pVehicle->m_pVehicleInfo->cameraRange; float pitchOffset = ent->m_pVehicle->m_pVehicleInfo->cameraPitchOffset; float vertOffset = ent->m_pVehicle->m_pVehicleInfo->cameraVertOffset; - if ( ent->client->ps.hackingTime ) - { - thirdPersonHorzOffset += (((float)ent->client->ps.hackingTime)/MAX_STRAFE_TIME) * -80.0f; - thirdPersonRange += fabs(((float)ent->client->ps.hackingTime)/MAX_STRAFE_TIME) * 100.0f; + if (ent->client->ps.hackingTime) { + thirdPersonHorzOffset += (((float)ent->client->ps.hackingTime) / MAX_STRAFE_TIME) * -80.0f; + thirdPersonRange += fabs(((float)ent->client->ps.hackingTime) / MAX_STRAFE_TIME) * 100.0f; } - if ( ent->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset ) - { - if ( pilot->client->ps.viewangles[PITCH] > 0 ) - { - vertOffset = 130+pilot->client->ps.viewangles[PITCH]*-10; - if ( vertOffset < -170 ) - { + if (ent->m_pVehicle->m_pVehicleInfo->cameraPitchDependantVertOffset) { + if (pilot->client->ps.viewangles[PITCH] > 0) { + vertOffset = 130 + pilot->client->ps.viewangles[PITCH] * -10; + if (vertOffset < -170) { vertOffset = -170; } - } - else if ( pilot->client->ps.viewangles[PITCH] < 0 ) - { - vertOffset = 130+pilot->client->ps.viewangles[PITCH]*-5; - if ( vertOffset > 130 ) - { + } else if (pilot->client->ps.viewangles[PITCH] < 0) { + vertOffset = 130 + pilot->client->ps.viewangles[PITCH] * -5; + if (vertOffset > 130) { vertOffset = 130; } - } - else - { + } else { vertOffset = 30; } - if ( pilot->client->ps.viewangles[PITCH] > 0 ) - { - pitchOffset = pilot->client->ps.viewangles[PITCH]*-0.75; - } - else if ( pilot->client->ps.viewangles[PITCH] < 0 ) - { - pitchOffset = pilot->client->ps.viewangles[PITCH]*-0.75; - } - else - { + if (pilot->client->ps.viewangles[PITCH] > 0) { + pitchOffset = pilot->client->ps.viewangles[PITCH] * -0.75; + } else if (pilot->client->ps.viewangles[PITCH] < 0) { + pitchOffset = pilot->client->ps.viewangles[PITCH] * -0.75; + } else { pitchOffset = 0; } } - //Control Scheme 3 Method: - G_EstimateCamPos( ent->client->ps.viewangles, pilot->client->ps.origin, pilot->client->ps.viewheight, thirdPersonRange, - thirdPersonHorzOffset, vertOffset, pitchOffset, - pilot->s.number, camPos ); + // Control Scheme 3 Method: + G_EstimateCamPos(ent->client->ps.viewangles, pilot->client->ps.origin, pilot->client->ps.viewheight, thirdPersonRange, thirdPersonHorzOffset, vertOffset, + pitchOffset, pilot->s.number, camPos); /* //Control Scheme 2 Method: G_EstimateCamPos( ent->m_pVehicle->m_vOrientation, ent->r.currentOrigin, pilot->client->ps.viewheight, thirdPersonRange, @@ -4103,77 +3572,60 @@ void WP_GetVehicleCamPos( gentity_t *ent, gentity_t *pilot, vec3_t camPos ) */ } -void WP_VehLeadCrosshairVeh( gentity_t *camTraceEnt, vec3_t newEnd, const vec3_t dir, const vec3_t shotStart, vec3_t shotDir ) -{ - if ( camTraceEnt - && camTraceEnt->client - && camTraceEnt->client->NPC_class == CLASS_VEHICLE ) - {//if the crosshair is on a vehicle, lead it - float distAdjust = DotProduct( camTraceEnt->client->ps.velocity, dir ); - VectorMA( newEnd, distAdjust, dir, newEnd ); - } - VectorSubtract( newEnd, shotStart, shotDir ); - VectorNormalize( shotDir ); +void WP_VehLeadCrosshairVeh(gentity_t *camTraceEnt, vec3_t newEnd, const vec3_t dir, const vec3_t shotStart, vec3_t shotDir) { + if (camTraceEnt && camTraceEnt->client && camTraceEnt->client->NPC_class == CLASS_VEHICLE) { // if the crosshair is on a vehicle, lead it + float distAdjust = DotProduct(camTraceEnt->client->ps.velocity, dir); + VectorMA(newEnd, distAdjust, dir, newEnd); + } + VectorSubtract(newEnd, shotStart, shotDir); + VectorNormalize(shotDir); } -#define MAX_XHAIR_DIST_ACCURACY 20000.0f +#define MAX_XHAIR_DIST_ACCURACY 20000.0f extern float g_cullDistance; -extern int BG_VehTraceFromCamPos( trace_t *camTrace, bgEntity_t *bgEnt, const vec3_t entOrg, const vec3_t shotStart, const vec3_t end, vec3_t newEnd, vec3_t shotDir, float bestDist ); -qboolean WP_VehCheckTraceFromCamPos( gentity_t *ent, const vec3_t shotStart, vec3_t shotDir ) -{ - //FIXME: only if dynamicCrosshair and dynamicCrosshairPrecision is on! - if ( !ent - || !ent->m_pVehicle - || !ent->m_pVehicle->m_pVehicleInfo - || !ent->m_pVehicle->m_pPilot//not being driven - || !((gentity_t*)ent->m_pVehicle->m_pPilot)->client//not being driven by a client...?!!! - || (ent->m_pVehicle->m_pPilot->s.number >= MAX_CLIENTS) )//being driven, but not by a real client, no need to worry about crosshair +extern int BG_VehTraceFromCamPos(trace_t *camTrace, bgEntity_t *bgEnt, const vec3_t entOrg, const vec3_t shotStart, const vec3_t end, vec3_t newEnd, + vec3_t shotDir, float bestDist); +qboolean WP_VehCheckTraceFromCamPos(gentity_t *ent, const vec3_t shotStart, vec3_t shotDir) { + // FIXME: only if dynamicCrosshair and dynamicCrosshairPrecision is on! + if (!ent || !ent->m_pVehicle || !ent->m_pVehicle->m_pVehicleInfo || !ent->m_pVehicle->m_pPilot // not being driven + || !((gentity_t *)ent->m_pVehicle->m_pPilot)->client // not being driven by a client...?!!! + || (ent->m_pVehicle->m_pPilot->s.number >= MAX_CLIENTS)) // being driven, but not by a real client, no need to worry about crosshair { return qfalse; } - if ( (ent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && g_cullDistance > MAX_XHAIR_DIST_ACCURACY ) - || ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) - { - //FIRST: simulate the normal crosshair trace from the center of the veh straight forward + if ((ent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER && g_cullDistance > MAX_XHAIR_DIST_ACCURACY) || + ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { + // FIRST: simulate the normal crosshair trace from the center of the veh straight forward trace_t trace; - vec3_t dir, start, end; - if ( ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - {//for some reason, the walker always draws the crosshair out from from the first muzzle point - AngleVectors( ent->client->ps.viewangles, dir, NULL, NULL ); - VectorCopy( ent->r.currentOrigin, start ); - start[2] += ent->m_pVehicle->m_pVehicleInfo->height-DEFAULT_MINS_2-48; - } - else - { + vec3_t dir, start, end; + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // for some reason, the walker always draws the crosshair out from from the first muzzle point + AngleVectors(ent->client->ps.viewangles, dir, NULL, NULL); + VectorCopy(ent->r.currentOrigin, start); + start[2] += ent->m_pVehicle->m_pVehicleInfo->height - DEFAULT_MINS_2 - 48; + } else { vec3_t ang; - if (ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) - { + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER) { VectorSet(ang, 0.0f, ent->m_pVehicle->m_vOrientation[1], 0.0f); - } - else - { + } else { VectorCopy(ent->m_pVehicle->m_vOrientation, ang); } - AngleVectors( ang, dir, NULL, NULL ); - VectorCopy( ent->r.currentOrigin, start ); + AngleVectors(ang, dir, NULL, NULL); + VectorCopy(ent->r.currentOrigin, start); } - VectorMA( start, g_cullDistance, dir, end ); - trap->Trace( &trace, start, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID|CONTENTS_BODY, qfalse, 0, 0 ); + VectorMA(start, g_cullDistance, dir, end); + trap->Trace(&trace, start, vec3_origin, vec3_origin, end, ent->s.number, CONTENTS_SOLID | CONTENTS_BODY, qfalse, 0, 0); - if ( ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - {//just use the result of that one trace since walkers don't do the extra trace - VectorSubtract( trace.endpos, shotStart, shotDir ); - VectorNormalize( shotDir ); + if (ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { // just use the result of that one trace since walkers don't do the extra trace + VectorSubtract(trace.endpos, shotStart, shotDir); + VectorNormalize(shotDir); return qtrue; - } - else - {//NOW do the trace from the camPos and compare with above trace - trace_t extraTrace; - vec3_t newEnd; - int camTraceEntNum = BG_VehTraceFromCamPos( &extraTrace, (bgEntity_t *)ent, ent->r.currentOrigin, shotStart, end, newEnd, shotDir, (trace.fraction*g_cullDistance) ); - if ( camTraceEntNum ) - { - WP_VehLeadCrosshairVeh( &g_entities[camTraceEntNum-1], newEnd, dir, shotStart, shotDir ); + } else { // NOW do the trace from the camPos and compare with above trace + trace_t extraTrace; + vec3_t newEnd; + int camTraceEntNum = + BG_VehTraceFromCamPos(&extraTrace, (bgEntity_t *)ent, ent->r.currentOrigin, shotStart, end, newEnd, shotDir, (trace.fraction * g_cullDistance)); + if (camTraceEntNum) { + WP_VehLeadCrosshairVeh(&g_entities[camTraceEntNum - 1], newEnd, dir, shotStart, shotDir); return qtrue; } } @@ -4182,28 +3634,24 @@ qboolean WP_VehCheckTraceFromCamPos( gentity_t *ent, const vec3_t shotStart, vec } //--------------------------------------------------------- -void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) +void FireVehicleWeapon(gentity_t *ent, qboolean alt_fire) //--------------------------------------------------------- { Vehicle_t *pVeh = ent->m_pVehicle; int muzzlesFired = 0; gentity_t *missile = NULL; vehWeaponInfo_t *vehWeapon = NULL; - qboolean clearRocketLockEntity = qfalse; + qboolean clearRocketLockEntity = qfalse; - if ( !pVeh ) - { + if (!pVeh) { return; } - if (pVeh->m_iRemovedSurfaces) - { //can't fire when the thing is breaking apart + if (pVeh->m_iRemovedSurfaces) { // can't fire when the thing is breaking apart return; } - if (pVeh->m_pVehicleInfo->type == VH_WALKER && - ent->client->ps.electrifyTime > level.time) - { //don't fire while being electrocuted + if (pVeh->m_pVehicleInfo->type == VH_WALKER && ent->client->ps.electrifyTime > level.time) { // don't fire while being electrocuted return; } @@ -4212,41 +3660,32 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) // would actually have to press the 2 key or something like that (I doubt I'd get a graphic for it anyways though). -AReis // If this is not the alternate fire, fire a normal blaster shot... - if ( pVeh->m_pVehicleInfo && - (pVeh->m_pVehicleInfo->type != VH_FIGHTER || (pVeh->m_ulFlags&VEH_WINGSOPEN)) ) // NOTE: Wings open also denotes that it has already launched. - {//fighters can only fire when wings are open - int weaponNum = 0, vehWeaponIndex = VEH_WEAPON_NONE; - int delay = 1000; + if (pVeh->m_pVehicleInfo && + (pVeh->m_pVehicleInfo->type != VH_FIGHTER || (pVeh->m_ulFlags & VEH_WINGSOPEN))) // NOTE: Wings open also denotes that it has already launched. + { // fighters can only fire when wings are open + int weaponNum = 0, vehWeaponIndex = VEH_WEAPON_NONE; + int delay = 1000; qboolean aimCorrect = qfalse; qboolean linkedFiring = qfalse; - if ( !alt_fire ) - { + if (!alt_fire) { weaponNum = 0; - } - else - { + } else { weaponNum = 1; } vehWeaponIndex = pVeh->m_pVehicleInfo->weapon[weaponNum].ID; - if ( pVeh->weaponStatus[weaponNum].ammo <= 0 ) - {//no ammo for this weapon - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo + if (pVeh->weaponStatus[weaponNum].ammo <= 0) { // no ammo for this weapon + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo int i; - //but only if one of the vehicle muzzles is actually ready to fire this weapon - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + // but only if one of the vehicle muzzles is actually ready to fire this weapon + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( pVeh->m_iMuzzleTag[i] != -1 - && pVeh->m_iMuzzleWait[i] < level.time ) - {//this one would have fired, send the no ammo message - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_iMuzzleWait[i] < level.time) { // this one would have fired, send the no ammo message + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); break; } } @@ -4256,211 +3695,169 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) delay = pVeh->m_pVehicleInfo->weapon[weaponNum].delay; aimCorrect = pVeh->m_pVehicleInfo->weapon[weaponNum].aimCorrect; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2//always linked - || ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 1//optionally linkable - && pVeh->weaponStatus[weaponNum].linked ) )//linked - {//we're linking the primary or alternate weapons, so we'll do *all* the muzzles + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2 // always linked + || (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 1 // optionally linkable + && pVeh->weaponStatus[weaponNum].linked)) // linked + { // we're linking the primary or alternate weapons, so we'll do *all* the muzzles linkedFiring = qtrue; } - if ( vehWeaponIndex <= VEH_WEAPON_BASE || vehWeaponIndex >= MAX_VEH_WEAPONS ) - {//invalid vehicle weapon + if (vehWeaponIndex <= VEH_WEAPON_BASE || vehWeaponIndex >= MAX_VEH_WEAPONS) { // invalid vehicle weapon return; - } - else - { + } else { int i, numMuzzles = 0, numMuzzlesReady = 0, cumulativeDelay = 0, cumulativeAmmo = 0; qboolean sentAmmoWarning = qfalse; vehWeapon = &g_vehWeaponInfo[vehWeaponIndex]; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2 ) - {//always linked weapons don't accumulate delay, just use specified delay + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable == 2) { // always linked weapons don't accumulate delay, just use specified delay cumulativeDelay = delay; } - //find out how many we've got for this weapon - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + // find out how many we've got for this weapon + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_iMuzzleWait[i] < level.time ) - { + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_iMuzzleWait[i] < level.time) { numMuzzlesReady++; } - if ( pVeh->m_pVehicleInfo->weapMuzzle[pVeh->weaponStatus[weaponNum].nextMuzzle] != vehWeaponIndex ) - {//Our designated next muzzle for this weapon isn't valid for this weapon (happens when ships fire for the first time) - //set the next to this one + if (pVeh->m_pVehicleInfo->weapMuzzle[pVeh->weaponStatus[weaponNum].nextMuzzle] != + vehWeaponIndex) { // Our designated next muzzle for this weapon isn't valid for this weapon (happens when ships fire for the first time) + // set the next to this one pVeh->weaponStatus[weaponNum].nextMuzzle = i; } - if ( linkedFiring ) - { + if (linkedFiring) { cumulativeAmmo += vehWeapon->iAmmoPerShot; - if ( pVeh->m_pVehicleInfo->weapon[weaponNum].linkable != 2 ) - {//always linked weapons don't accumulate delay, just use specified delay + if (pVeh->m_pVehicleInfo->weapon[weaponNum].linkable != 2) { // always linked weapons don't accumulate delay, just use specified delay cumulativeDelay += delay; } } numMuzzles++; } - if ( linkedFiring ) - {//firing all muzzles at once - if ( numMuzzlesReady != numMuzzles ) - {//can't fire all linked muzzles yet + if (linkedFiring) { // firing all muzzles at once + if (numMuzzlesReady != numMuzzles) { // can't fire all linked muzzles yet return; - } - else - {//can fire all linked muzzles, check ammo - if ( pVeh->weaponStatus[weaponNum].ammo < cumulativeAmmo ) - {//can't fire, not enough ammo - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + } else { // can fire all linked muzzles, check ammo + if (pVeh->weaponStatus[weaponNum].ammo < cumulativeAmmo) { // can't fire, not enough ammo + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); } return; } } } - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - if ( !linkedFiring - && i != pVeh->weaponStatus[weaponNum].nextMuzzle ) - {//we're only firing one muzzle and this isn't it + if (!linkedFiring && i != pVeh->weaponStatus[weaponNum].nextMuzzle) { // we're only firing one muzzle and this isn't it continue; } // Fire this muzzle. - if ( pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_iMuzzleWait[i] < level.time ) - { - vec3_t start, dir; + if (pVeh->m_iMuzzleTag[i] != -1 && pVeh->m_iMuzzleWait[i] < level.time) { + vec3_t start, dir; - if ( pVeh->weaponStatus[weaponNum].ammo < vehWeapon->iAmmoPerShot ) - {//out of ammo! - if ( !sentAmmoWarning ) - { + if (pVeh->weaponStatus[weaponNum].ammo < vehWeapon->iAmmoPerShot) { // out of ammo! + if (!sentAmmoWarning) { sentAmmoWarning = qtrue; - if ( pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS ) - {// let the client know he's out of ammo - G_AddEvent( (gentity_t*)pVeh->m_pPilot, EV_NOAMMO, weaponNum ); + if (pVeh->m_pPilot && pVeh->m_pPilot->s.number < MAX_CLIENTS) { // let the client know he's out of ammo + G_AddEvent((gentity_t *)pVeh->m_pPilot, EV_NOAMMO, weaponNum); } } - } - else - {//have enough ammo to shoot - //do the firing + } else { // have enough ammo to shoot + // do the firing WP_CalcVehMuzzle(ent, i); - VectorCopy( pVeh->m_vMuzzlePos[i], start ); - VectorCopy( pVeh->m_vMuzzleDir[i], dir ); - if ( WP_VehCheckTraceFromCamPos( ent, start, dir ) ) - {//auto-aim at whatever crosshair would be over from camera's point of view (if closer) - } - else if ( aimCorrect ) - {//auto-aim the missile at the crosshair if there's anything there + VectorCopy(pVeh->m_vMuzzlePos[i], start); + VectorCopy(pVeh->m_vMuzzleDir[i], dir); + if (WP_VehCheckTraceFromCamPos(ent, start, + dir)) { // auto-aim at whatever crosshair would be over from camera's point of view (if closer) + } else if (aimCorrect) { // auto-aim the missile at the crosshair if there's anything there trace_t trace; - vec3_t end; - vec3_t ang; - vec3_t fixedDir; + vec3_t end; + vec3_t ang; + vec3_t fixedDir; - if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) - { + if (pVeh->m_pVehicleInfo->type == VH_SPEEDER) { VectorSet(ang, 0.0f, pVeh->m_vOrientation[1], 0.0f); - } - else - { + } else { VectorCopy(pVeh->m_vOrientation, ang); } - AngleVectors( ang, fixedDir, NULL, NULL ); - VectorMA( ent->r.currentOrigin, 32768, fixedDir, end ); - //VectorMA( ent->r.currentOrigin, 8192, dir, end ); - trap->Trace( &trace, ent->r.currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( trace.fraction < 1.0f && !trace.allsolid && !trace.startsolid ) - { + AngleVectors(ang, fixedDir, NULL, NULL); + VectorMA(ent->r.currentOrigin, 32768, fixedDir, end); + // VectorMA( ent->r.currentOrigin, 8192, dir, end ); + trap->Trace(&trace, ent->r.currentOrigin, vec3_origin, vec3_origin, end, ent->s.number, MASK_SHOT, qfalse, 0, 0); + if (trace.fraction < 1.0f && !trace.allsolid && !trace.startsolid) { vec3_t newEnd; - VectorCopy( trace.endpos, newEnd ); - WP_VehLeadCrosshairVeh( &g_entities[trace.entityNum], newEnd, fixedDir, start, dir ); + VectorCopy(trace.endpos, newEnd); + WP_VehLeadCrosshairVeh(&g_entities[trace.entityNum], newEnd, fixedDir, start, dir); } } - //play the weapon's muzzle effect if we have one - //NOTE: just need MAX_VEHICLE_MUZZLES bits for this... should be cool since it's currently 12 and we're sending it in 16 bits - muzzlesFired |= (1<fHoming ) - {//clear the rocket lock entity *after* all muzzles have fired + missile = WP_FireVehicleWeapon(ent, start, dir, vehWeapon, alt_fire, qfalse); + if (vehWeapon->fHoming) { // clear the rocket lock entity *after* all muzzles have fired clearRocketLockEntity = qtrue; } } - if ( linkedFiring ) - {//we're linking the weapon, so continue on and fire all appropriate muzzles + if (linkedFiring) { // we're linking the weapon, so continue on and fire all appropriate muzzles continue; } - //else just firing one - //take the ammo, set the next muzzle and set the delay on it - if ( numMuzzles > 1 ) - {//more than one, look for it + // else just firing one + // take the ammo, set the next muzzle and set the delay on it + if (numMuzzles > 1) { // more than one, look for it int nextMuzzle = pVeh->weaponStatus[weaponNum].nextMuzzle; - while ( 1 ) - { + while (1) { nextMuzzle++; - if ( nextMuzzle >= MAX_VEHICLE_MUZZLES ) - { + if (nextMuzzle >= MAX_VEHICLE_MUZZLES) { nextMuzzle = 0; } - if ( nextMuzzle == pVeh->weaponStatus[weaponNum].nextMuzzle ) - {//WTF? Wrapped without finding another valid one! + if (nextMuzzle == pVeh->weaponStatus[weaponNum].nextMuzzle) { // WTF? Wrapped without finding another valid one! break; } - if ( pVeh->m_pVehicleInfo->weapMuzzle[nextMuzzle] == vehWeaponIndex ) - {//this is the next muzzle for this weapon + if (pVeh->m_pVehicleInfo->weapMuzzle[nextMuzzle] == vehWeaponIndex) { // this is the next muzzle for this weapon pVeh->weaponStatus[weaponNum].nextMuzzle = nextMuzzle; break; } } - }//else, just stay on the one we just fired - //set the delay on the next muzzle + } // else, just stay on the one we just fired + // set the delay on the next muzzle pVeh->m_iMuzzleWait[pVeh->weaponStatus[weaponNum].nextMuzzle] = level.time + delay; - //take away the ammo + // take away the ammo pVeh->weaponStatus[weaponNum].ammo -= vehWeapon->iAmmoPerShot; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( pVeh->m_pParentEntity && ((gentity_t*)(pVeh->m_pParentEntity))->client ) - { - ((gentity_t*)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's + // client->ps.ammo array + if (pVeh->m_pParentEntity && ((gentity_t *)(pVeh->m_pParentEntity))->client) { + ((gentity_t *)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; } - //done! - //we'll get in here again next frame and try the next muzzle... - //return; + // done! + // we'll get in here again next frame and try the next muzzle... + // return; goto tryFire; } } - //we went through all the muzzles, so apply the cumulative delay and ammo cost - if ( cumulativeAmmo ) - {//taking ammo one shot at a time - //take the ammo + // we went through all the muzzles, so apply the cumulative delay and ammo cost + if (cumulativeAmmo) { // taking ammo one shot at a time + // take the ammo pVeh->weaponStatus[weaponNum].ammo -= cumulativeAmmo; - //NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's client->ps.ammo array - if ( pVeh->m_pParentEntity && ((gentity_t*)(pVeh->m_pParentEntity))->client ) - { - ((gentity_t*)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; + // NOTE: in order to send the vehicle's ammo info to the client, we copy the ammo into the first 2 ammo slots on the vehicle NPC's + // client->ps.ammo array + if (pVeh->m_pParentEntity && ((gentity_t *)(pVeh->m_pParentEntity))->client) { + ((gentity_t *)(pVeh->m_pParentEntity))->client->ps.ammo[weaponNum] = pVeh->weaponStatus[weaponNum].ammo; } } - if ( cumulativeDelay ) - {//we linked muzzles so we need to apply the cumulative delay now, to each of the linked muzzles - for ( i = 0; i < MAX_VEHICLE_MUZZLES; i++ ) - { - if ( pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex ) - {//this muzzle doesn't match the weapon we're trying to use + if (cumulativeDelay) { // we linked muzzles so we need to apply the cumulative delay now, to each of the linked muzzles + for (i = 0; i < MAX_VEHICLE_MUZZLES; i++) { + if (pVeh->m_pVehicleInfo->weapMuzzle[i] != vehWeaponIndex) { // this muzzle doesn't match the weapon we're trying to use continue; } - //apply the cumulative delay + // apply the cumulative delay pVeh->m_iMuzzleWait[i] = level.time + cumulativeDelay; } } @@ -4468,16 +3865,14 @@ void FireVehicleWeapon( gentity_t *ent, qboolean alt_fire ) } tryFire: - if ( clearRocketLockEntity ) - {//hmm, should probably clear that anytime any weapon fires? + if (clearRocketLockEntity) { // hmm, should probably clear that anytime any weapon fires? ent->client->ps.rocketLockIndex = ENTITYNUM_NONE; ent->client->ps.rocketLockTime = 0; ent->client->ps.rocketTargetTime = 0; } - if ( vehWeapon && muzzlesFired > 0 ) - { - G_VehMuzzleFireFX(ent, missile, muzzlesFired ); + if (vehWeapon && muzzlesFired > 0) { + G_VehMuzzleFireFX(ent, missile, muzzlesFired); } } @@ -4488,94 +3883,71 @@ FireWeapon */ int BG_EmplacedView(vec3_t baseAngles, vec3_t angles, float *newYaw, float constraint); -void FireWeapon( gentity_t *ent, qboolean altFire ) { +void FireWeapon(gentity_t *ent, qboolean altFire) { // track shots taken for accuracy tracking. melee weapons are not tracked. - if( ent->s.weapon != WP_SABER && ent->s.weapon != WP_STUN_BATON && ent->s.weapon != WP_MELEE ) - { - if( ent->s.weapon == WP_FLECHETTE ) { + if (ent->s.weapon != WP_SABER && ent->s.weapon != WP_STUN_BATON && ent->s.weapon != WP_MELEE) { + if (ent->s.weapon == WP_FLECHETTE) { ent->client->accuracy_shots += FLECHETTE_SHOTS; } else { ent->client->accuracy_shots++; } } - if ( ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE ) - { - FireVehicleWeapon( ent, altFire ); + if (ent && ent->client && ent->client->NPC_class == CLASS_VEHICLE) { + FireVehicleWeapon(ent, altFire); return; - } - else - { + } else { // set aiming directions - if (ent->s.weapon == WP_EMPLACED_GUN && - ent->client->ps.emplacedIndex) - { //if using emplaced then base muzzle point off of gun position/angles + if (ent->s.weapon == WP_EMPLACED_GUN && ent->client->ps.emplacedIndex) { // if using emplaced then base muzzle point off of gun position/angles gentity_t *emp = &g_entities[ent->client->ps.emplacedIndex]; - if (emp->inuse) - { + if (emp->inuse) { float yaw; vec3_t viewAngCap; int override; VectorCopy(ent->client->ps.viewangles, viewAngCap); - if (viewAngCap[PITCH] > 40) - { + if (viewAngCap[PITCH] > 40) { viewAngCap[PITCH] = 40; } - override = BG_EmplacedView(ent->client->ps.viewangles, emp->s.angles, &yaw, - emp->s.origin2[0]); + override = BG_EmplacedView(ent->client->ps.viewangles, emp->s.angles, &yaw, emp->s.origin2[0]); - if (override) - { + if (override) { viewAngCap[YAW] = yaw; } - AngleVectors( viewAngCap, forward, vright, up ); + AngleVectors(viewAngCap, forward, vright, up); + } else { + AngleVectors(ent->client->ps.viewangles, forward, vright, up); } - else - { - AngleVectors( ent->client->ps.viewangles, forward, vright, up ); - } - } - else if (ent->s.number < MAX_CLIENTS && - ent->client->ps.m_iVehicleNum && ent->s.weapon == WP_BLASTER) - { //riding a vehicle...with blaster selected + } else if (ent->s.number < MAX_CLIENTS && ent->client->ps.m_iVehicleNum && ent->s.weapon == WP_BLASTER) { // riding a vehicle...with blaster selected vec3_t vehTurnAngles; gentity_t *vehEnt = &g_entities[ent->client->ps.m_iVehicleNum]; - if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) - { + if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) { VectorCopy(vehEnt->m_pVehicle->m_vOrientation, vehTurnAngles); vehTurnAngles[PITCH] = ent->client->ps.viewangles[PITCH]; - } - else - { + } else { VectorCopy(ent->client->ps.viewangles, vehTurnAngles); } - if (ent->client->pers.cmd.rightmove > 0) - { //shooting to right + if (ent->client->pers.cmd.rightmove > 0) { // shooting to right vehTurnAngles[YAW] -= 90.0f; - } - else if (ent->client->pers.cmd.rightmove < 0) - { //shooting to left + } else if (ent->client->pers.cmd.rightmove < 0) { // shooting to left vehTurnAngles[YAW] += 90.0f; } - AngleVectors( vehTurnAngles, forward, vright, up ); - } - else - { - AngleVectors( ent->client->ps.viewangles, forward, vright, up ); + AngleVectors(vehTurnAngles, forward, vright, up); + } else { + AngleVectors(ent->client->ps.viewangles, forward, vright, up); } - CalcMuzzlePoint ( ent, forward, vright, up, muzzle ); + CalcMuzzlePoint(ent, forward, vright, up, muzzle); // fire the specific weapon - switch( ent->s.weapon ) { + switch (ent->s.weapon) { case WP_STUN_BATON: - WP_FireStunBaton( ent, altFire ); + WP_FireStunBaton(ent, altFire); break; case WP_MELEE: @@ -4586,69 +3958,68 @@ void FireWeapon( gentity_t *ent, qboolean altFire ) { break; case WP_BRYAR_PISTOL: - WP_FireBryarPistol( ent, altFire ); + WP_FireBryarPistol(ent, altFire); break; case WP_CONCUSSION: - if ( altFire ) - WP_FireConcussionAlt( ent ); + if (altFire) + WP_FireConcussionAlt(ent); else - WP_FireConcussion( ent ); + WP_FireConcussion(ent); break; case WP_BRYAR_OLD: - WP_FireBryarPistol( ent, altFire ); + WP_FireBryarPistol(ent, altFire); break; case WP_BLASTER: - WP_FireBlaster( ent, altFire ); + WP_FireBlaster(ent, altFire); break; case WP_DISRUPTOR: - WP_FireDisruptor( ent, altFire ); + WP_FireDisruptor(ent, altFire); break; case WP_BOWCASTER: - WP_FireBowcaster( ent, altFire ); + WP_FireBowcaster(ent, altFire); break; case WP_REPEATER: - WP_FireRepeater( ent, altFire ); + WP_FireRepeater(ent, altFire); break; case WP_DEMP2: - WP_FireDEMP2( ent, altFire ); + WP_FireDEMP2(ent, altFire); break; case WP_FLECHETTE: - WP_FireFlechette( ent, altFire ); + WP_FireFlechette(ent, altFire); break; case WP_ROCKET_LAUNCHER: - WP_FireRocket( ent, altFire ); + WP_FireRocket(ent, altFire); break; case WP_THERMAL: - WP_FireThermalDetonator( ent, altFire ); + WP_FireThermalDetonator(ent, altFire); break; case WP_TRIP_MINE: - WP_PlaceLaserTrap( ent, altFire ); + WP_PlaceLaserTrap(ent, altFire); break; case WP_DET_PACK: - WP_DropDetPack( ent, altFire ); + WP_DropDetPack(ent, altFire); break; case WP_EMPLACED_GUN: - if (ent->client && ent->client->ewebIndex) - { //specially handled by the e-web itself + if (ent->client && ent->client->ewebIndex) { // specially handled by the e-web itself break; } - WP_FireEmplaced( ent, altFire ); + WP_FireEmplaced(ent, altFire); break; default: -// assert(!"unknown weapon fire"); + // assert(!"unknown weapon fire"); break; } } @@ -4657,28 +4028,26 @@ void FireWeapon( gentity_t *ent, qboolean altFire ) { } //--------------------------------------------------------- -static void WP_FireEmplaced( gentity_t *ent, qboolean altFire ) +static void WP_FireEmplaced(gentity_t *ent, qboolean altFire) //--------------------------------------------------------- { - vec3_t dir, angs, gunpoint; - vec3_t right; + vec3_t dir, angs, gunpoint; + vec3_t right; gentity_t *gun; int side; - if (!ent->client) - { + if (!ent->client) { return; } - if (!ent->client->ps.emplacedIndex) - { //shouldn't be using WP_EMPLACED_GUN if we aren't on an emplaced weapon + if (!ent->client->ps.emplacedIndex) { // shouldn't be using WP_EMPLACED_GUN if we aren't on an emplaced weapon return; } gun = &g_entities[ent->client->ps.emplacedIndex]; - if (!gun->inuse || gun->health <= 0) - { //gun was removed or killed, although we should never hit this check because we should have been forced off it already + if (!gun->inuse || + gun->health <= 0) { // gun was removed or killed, although we should never hit this check because we should have been forced off it already return; } @@ -4687,13 +4056,10 @@ static void WP_FireEmplaced( gentity_t *ent, qboolean altFire ) AngleVectors(ent->client->ps.viewangles, NULL, right, NULL); - if (gun->genericValue10) - { //fire out of the right cannon side + if (gun->genericValue10) { // fire out of the right cannon side VectorMA(gunpoint, 10.0f, right, gunpoint); side = 0; - } - else - { //the left + } else { // the left VectorMA(gunpoint, -10.0f, right, gunpoint); side = 1; } @@ -4701,11 +4067,11 @@ static void WP_FireEmplaced( gentity_t *ent, qboolean altFire ) gun->genericValue10 = side; G_AddEvent(gun, EV_FIRE_WEAPON, side); - vectoangles( forward, angs ); + vectoangles(forward, angs); - AngleVectors( angs, dir, NULL, NULL ); + AngleVectors(angs, dir, NULL, NULL); - WP_FireEmplacedMissile( gun, gunpoint, dir, altFire, ent ); + WP_FireEmplacedMissile(gun, gunpoint, dir, altFire, ent); } #define EMPLACED_CANRESPAWN 1 @@ -4736,9 +4102,8 @@ static void WP_FireEmplaced( gentity_t *ent, qboolean altFire ) */ //---------------------------------------------------------- -extern qboolean TryHeal(gentity_t *ent, gentity_t *target); //g_utils.c -void emplaced_gun_use( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +extern qboolean TryHeal(gentity_t *ent, gentity_t *target); // g_utils.c +void emplaced_gun_use(gentity_t *self, gentity_t *other, trace_t *trace) { vec3_t fwd1, fwd2; float dot; int oldWeapon; @@ -4748,76 +4113,65 @@ void emplaced_gun_use( gentity_t *self, gentity_t *other, trace_t *trace ) vec3_t vLen; float ownLen; - if ( self->health <= 0 ) - { //gun is destroyed + if (self->health <= 0) { // gun is destroyed return; } - if (self->activator) - { //someone is already using me + if (self->activator) { // someone is already using me return; } - if (!activator->client) - { + if (!activator->client) { return; } - if (activator->client->ps.emplacedTime > level.time) - { //last use attempt still too recent + if (activator->client->ps.emplacedTime > level.time) { // last use attempt still too recent return; } - if (activator->client->ps.forceHandExtend != HANDEXTEND_NONE) - { //don't use if busy doing something else + if (activator->client->ps.forceHandExtend != HANDEXTEND_NONE) { // don't use if busy doing something else return; } - if (activator->client->ps.origin[2] > self->s.origin[2]+zoffset-8) - { //can't use it from the top + if (activator->client->ps.origin[2] > self->s.origin[2] + zoffset - 8) { // can't use it from the top return; } - if (activator->client->ps.pm_flags & PMF_DUCKED) - { //must be standing + if (activator->client->ps.pm_flags & PMF_DUCKED) { // must be standing return; } - if (activator->client->ps.isJediMaster) - { //jm can't use weapons + if (activator->client->ps.isJediMaster) { // jm can't use weapons return; } VectorSubtract(self->s.origin, activator->client->ps.origin, vLen); ownLen = VectorLength(vLen); - if (ownLen > 64.0f) - { //must be within 64 units of the gun to use at all + if (ownLen > 64.0f) { // must be within 64 units of the gun to use at all return; } // Let's get some direction vectors for the user - AngleVectors( activator->client->ps.viewangles, fwd1, NULL, NULL ); + AngleVectors(activator->client->ps.viewangles, fwd1, NULL, NULL); // Get the guns direction vector - AngleVectors( self->pos1, fwd2, NULL, NULL ); + AngleVectors(self->pos1, fwd2, NULL, NULL); - dot = DotProduct( fwd1, fwd2 ); + dot = DotProduct(fwd1, fwd2); // Must be reasonably facing the way the gun points ( 110 degrees or so ), otherwise we don't allow to use it. - if ( dot < -0.2f ) - { + if (dot < -0.2f) { goto tryHeal; } VectorSubtract(self->s.origin, activator->client->ps.origin, fwd1); VectorNormalize(fwd1); - dot = DotProduct( fwd1, fwd2 ); + dot = DotProduct(fwd1, fwd2); - //check the positioning in relation to the gun as well - if ( dot < 0.6f ) - { + // check the positioning in relation to the gun as well + if (dot < 0.6f) { goto tryHeal; } @@ -4828,17 +4182,17 @@ void emplaced_gun_use( gentity_t *self, gentity_t *other, trace_t *trace ) // swap the users weapon with the emplaced gun activator->client->ps.weapon = self->s.weapon; activator->client->ps.weaponstate = WEAPON_READY; - activator->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_EMPLACED_GUN ); + activator->client->ps.stats[STAT_WEAPONS] |= (1 << WP_EMPLACED_GUN); activator->client->ps.emplacedIndex = self->s.number; self->s.emplacedOwner = activator->s.number; - self->s.activeForcePass = NUM_FORCE_POWERS+1; + self->s.activeForcePass = NUM_FORCE_POWERS + 1; // the gun will track which weapon we used to have self->s.weapon = oldWeapon; - //user's new owner becomes the gun ent + // user's new owner becomes the gun ent activator->r.ownerNum = self->s.number; self->activator = activator; @@ -4846,66 +4200,54 @@ void emplaced_gun_use( gentity_t *self, gentity_t *other, trace_t *trace ) vectoangles(anglesToOwner, anglesToOwner); return; -tryHeal: //well, not in the right dir, try healing it instead... +tryHeal: // well, not in the right dir, try healing it instead... TryHeal(activator, self); } -void emplaced_gun_realuse( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - emplaced_gun_use(self, other, NULL); -} +void emplaced_gun_realuse(gentity_t *self, gentity_t *other, gentity_t *activator) { emplaced_gun_use(self, other, NULL); } //---------------------------------------------------------- -void emplaced_gun_pain( gentity_t *self, gentity_t *attacker, int damage ) -{ +void emplaced_gun_pain(gentity_t *self, gentity_t *attacker, int damage) { self->s.health = self->health; - if ( self->health <= 0 ) - { - //death effect.. for now taken care of on cgame - } - else - { - //if we have a pain behavior set then use it I guess - G_ActivateBehavior( self, BSET_PAIN ); + if (self->health <= 0) { + // death effect.. for now taken care of on cgame + } else { + // if we have a pain behavior set then use it I guess + G_ActivateBehavior(self, BSET_PAIN); } } #define EMPLACED_GUN_HEALTH 800 //---------------------------------------------------------- -void emplaced_gun_update(gentity_t *self) -{ - vec3_t smokeOrg, puffAngle; +void emplaced_gun_update(gentity_t *self) { + vec3_t smokeOrg, puffAngle; int oldWeap; float ownLen = 0; - if (self->health < 1 && !self->genericValue5) - { //we are dead, set our respawn delay if we have one - if (self->spawnflags & EMPLACED_CANRESPAWN) - { + if (self->health < 1 && !self->genericValue5) { // we are dead, set our respawn delay if we have one + if (self->spawnflags & EMPLACED_CANRESPAWN) { self->genericValue5 = level.time + 4000 + self->count; } - } - else if (self->health < 1 && self->genericValue5 < level.time) - { //we are dead, see if it's time to respawn + } else if (self->health < 1 && self->genericValue5 < level.time) { // we are dead, see if it's time to respawn self->s.time = 0; self->genericValue4 = 0; self->genericValue3 = 0; - self->health = EMPLACED_GUN_HEALTH*0.4; + self->health = EMPLACED_GUN_HEALTH * 0.4; self->s.health = self->health; } - if (self->genericValue4 && self->genericValue4 < 2 && self->s.time < level.time) - { //we have finished our warning (red flashing) effect, it's time to finish dying + if (self->genericValue4 && self->genericValue4 < 2 && + self->s.time < level.time) { // we have finished our warning (red flashing) effect, it's time to finish dying vec3_t explOrg; - VectorSet( puffAngle, 0, 0, 1 ); + VectorSet(puffAngle, 0, 0, 1); VectorCopy(self->r.currentOrigin, explOrg); explOrg[2] += 16; - //just use the detpack explosion effect + // just use the detpack explosion effect G_PlayEffect(EFFECT_EXPLOSION_DETPACK, explOrg, puffAngle); self->genericValue3 = level.time + Q_irand(2500, 3500); @@ -4917,11 +4259,9 @@ void emplaced_gun_update(gentity_t *self) self->genericValue4 = 2; } - if (self->genericValue3 > level.time) - { //see if we are freshly dead and should be smoking - if (self->genericValue2 < level.time) - { //is it time yet to spawn another smoke puff? - VectorSet( puffAngle, 0, 0, 1 ); + if (self->genericValue3 > level.time) { // see if we are freshly dead and should be smoking + if (self->genericValue2 < level.time) { // is it time yet to spawn another smoke puff? + VectorSet(puffAngle, 0, 0, 1); VectorCopy(self->r.currentOrigin, smokeOrg); smokeOrg[2] += 60; @@ -4931,19 +4271,16 @@ void emplaced_gun_update(gentity_t *self) } } - if (self->activator && self->activator->client && self->activator->inuse) - { //handle updating current user + if (self->activator && self->activator->client && self->activator->inuse) { // handle updating current user vec3_t vLen; VectorSubtract(self->s.origin, self->activator->client->ps.origin, vLen); ownLen = VectorLength(vLen); - if (!(self->activator->client->pers.cmd.buttons & BUTTON_USE) && self->genericValue1) - { + if (!(self->activator->client->pers.cmd.buttons & BUTTON_USE) && self->genericValue1) { self->genericValue1 = 0; } - if ((self->activator->client->pers.cmd.buttons & BUTTON_USE) && !self->genericValue1) - { + if ((self->activator->client->pers.cmd.buttons & BUTTON_USE) && !self->genericValue1) { self->activator->client->ps.emplacedIndex = 0; self->activator->client->ps.saberHolstered = 0; self->nextthink = level.time + 50; @@ -4951,10 +4288,9 @@ void emplaced_gun_update(gentity_t *self) } } - if ((self->activator && self->activator->client) && - (!self->activator->inuse || self->activator->client->ps.emplacedIndex != self->s.number || self->genericValue4 || ownLen > 64)) - { //get the user off of me then - self->activator->client->ps.stats[STAT_WEAPONS] &= ~(1<activator && self->activator->client) && (!self->activator->inuse || self->activator->client->ps.emplacedIndex != self->s.number || + self->genericValue4 || ownLen > 64)) { // get the user off of me then + self->activator->client->ps.stats[STAT_WEAPONS] &= ~(1 << WP_EMPLACED_GUN); oldWeap = self->activator->client->ps.weapon; self->activator->client->ps.weapon = self->s.weapon; @@ -4966,9 +4302,7 @@ void emplaced_gun_update(gentity_t *self) self->activator = NULL; self->s.activeForcePass = 0; - } - else if (self->activator && self->activator->client) - { //make sure the user is using the emplaced gun weapon + } else if (self->activator && self->activator->client) { // make sure the user is using the emplaced gun weapon self->activator->client->ps.weapon = WP_EMPLACED_GUN; self->activator->client->ps.weaponstate = WEAPON_READY; } @@ -4976,10 +4310,8 @@ void emplaced_gun_update(gentity_t *self) } //---------------------------------------------------------- -void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod ) -{ //set us up to flash and then explode - if (self->genericValue4) - { +void emplaced_gun_die(gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod) { // set us up to flash and then explode + if (self->genericValue4) { return; } @@ -4990,22 +4322,21 @@ void emplaced_gun_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacke self->genericValue5 = 0; } -void SP_emplaced_gun( gentity_t *ent ) -{ +void SP_emplaced_gun(gentity_t *ent) { const char *name = "models/map_objects/mp/turret_chair.glm"; vec3_t down; trace_t tr; - //make sure our assets are precached - RegisterItem( BG_FindItemForWeapon(WP_EMPLACED_GUN) ); + // make sure our assets are precached + RegisterItem(BG_FindItemForWeapon(WP_EMPLACED_GUN)); ent->r.contents = CONTENTS_SOLID; ent->s.solid = SOLID_BBOX; ent->genericValue5 = 0; - VectorSet( ent->r.mins, -30, -20, 8 ); - VectorSet( ent->r.maxs, 30, 20, 60 ); + VectorSet(ent->r.mins, -30, -20, 8); + VectorSet(ent->r.maxs, 30, 20, 60); VectorCopy(ent->s.origin, down); @@ -5013,8 +4344,7 @@ void SP_emplaced_gun( gentity_t *ent ) trap->Trace(&tr, ent->s.origin, ent->r.mins, ent->r.maxs, down, ent->s.number, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction != 1 && !tr.allsolid && !tr.startsolid) - { + if (tr.fraction != 1 && !tr.allsolid && !tr.startsolid) { VectorCopy(tr.endpos, ent->s.origin); } @@ -5022,8 +4352,7 @@ void SP_emplaced_gun( gentity_t *ent ) ent->health = EMPLACED_GUN_HEALTH; - if (ent->spawnflags & EMPLACED_CANRESPAWN) - { //make it somewhat easier to kill if it can respawn + if (ent->spawnflags & EMPLACED_CANRESPAWN) { // make it somewhat easier to kill if it can respawn ent->health *= 0.4; } @@ -5041,23 +4370,23 @@ void SP_emplaced_gun( gentity_t *ent ) ent->splashRadius = 128; // amount of ammo that this little poochie has - G_SpawnInt( "count", "600", &ent->count ); + G_SpawnInt("count", "600", &ent->count); - G_SpawnFloat( "constraint", "60", &ent->s.origin2[0] ); + G_SpawnFloat("constraint", "60", &ent->s.origin2[0]); - ent->s.modelindex = G_ModelIndex( (char *)name ); + ent->s.modelindex = G_ModelIndex((char *)name); ent->s.modelGhoul2 = 1; ent->s.g2radius = 110; - //so the cgame knows for sure that we're an emplaced weapon + // so the cgame knows for sure that we're an emplaced weapon ent->s.weapon = WP_EMPLACED_GUN; - G_SetOrigin( ent, ent->s.origin ); + G_SetOrigin(ent, ent->s.origin); // store base angles for later - VectorCopy( ent->s.angles, ent->pos1 ); - VectorCopy( ent->s.angles, ent->r.currentAngles ); - VectorCopy( ent->s.angles, ent->s.apos.trBase ); + VectorCopy(ent->s.angles, ent->pos1); + VectorCopy(ent->s.angles, ent->r.currentAngles); + VectorCopy(ent->s.angles, ent->s.apos.trBase); ent->think = emplaced_gun_update; ent->nextthink = level.time + 50; @@ -5068,9 +4397,9 @@ void SP_emplaced_gun( gentity_t *ent ) ent->s.pos.trType = TR_STATIONARY; - ent->s.owner = MAX_CLIENTS+1; + ent->s.owner = MAX_CLIENTS + 1; ent->s.shouldtarget = qtrue; - //ent->s.teamowner = 0; + // ent->s.teamowner = 0; trap->LinkEntity((sharedEntity_t *)ent); } diff --git a/codemp/game/tri_coll_test.c b/codemp/game/tri_coll_test.c index dc63373353..3043a7664a 100644 --- a/codemp/game/tri_coll_test.c +++ b/codemp/game/tri_coll_test.c @@ -35,276 +35,255 @@ #include "game/g_local.h" /* if USE_EPSILON_TEST is true then we do a check: - if |dv|b) \ - { \ - float tmp; \ - tmp=a; \ - a=b; \ - b=tmp; \ - } - -#define ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1) \ - isect0=VV0+(VV1-VV0)*D0/(D0-D1); \ - isect1=VV0+(VV2-VV0)*D0/(D0-D2); - - -#define COMPUTE_INTERVALS(VV0,VV1,VV2,D0,D1,D2,D0D1,D0D2,isect0,isect1) \ - if(D0D1>0.0f) \ - { \ - /* here we know that D0D2<=0.0 */ \ - /* that is D0, D1 are on the same side, D2 on the other or on the plane */ \ - ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \ - } \ - else if(D0D2>0.0f) \ - { \ - /* here we know that d0d1<=0.0 */ \ - ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \ - } \ - else if(D1*D2>0.0f || D0!=0.0f) \ - { \ - /* here we know that d0d1<=0.0 or that D0!=0.0 */ \ - ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1); \ - } \ - else if(D1!=0.0f) \ - { \ - ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1); \ - } \ - else if(D2!=0.0f) \ - { \ - ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1); \ - } \ - else \ - { \ - /* triangles are coplanar */ \ - return coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2); \ - } - - +#define SORT(a, b) \ + if (a > b) { \ + float tmp; \ + tmp = a; \ + a = b; \ + b = tmp; \ + } + +#define ISECT(VV0, VV1, VV2, D0, D1, D2, isect0, isect1) \ + isect0 = VV0 + (VV1 - VV0) * D0 / (D0 - D1); \ + isect1 = VV0 + (VV2 - VV0) * D0 / (D0 - D2); + +#define COMPUTE_INTERVALS(VV0, VV1, VV2, D0, D1, D2, D0D1, D0D2, isect0, isect1) \ + if (D0D1 > 0.0f) { \ + /* here we know that D0D2<=0.0 */ \ + /* that is D0, D1 are on the same side, D2 on the other or on the plane */ \ + ISECT(VV2, VV0, VV1, D2, D0, D1, isect0, isect1); \ + } else if (D0D2 > 0.0f) { \ + /* here we know that d0d1<=0.0 */ \ + ISECT(VV1, VV0, VV2, D1, D0, D2, isect0, isect1); \ + } else if (D1 * D2 > 0.0f || D0 != 0.0f) { \ + /* here we know that d0d1<=0.0 or that D0!=0.0 */ \ + ISECT(VV0, VV1, VV2, D0, D1, D2, isect0, isect1); \ + } else if (D1 != 0.0f) { \ + ISECT(VV1, VV0, VV2, D1, D0, D2, isect0, isect1); \ + } else if (D2 != 0.0f) { \ + ISECT(VV2, VV0, VV1, D2, D0, D1, isect0, isect1); \ + } else { \ + /* triangles are coplanar */ \ + return coplanar_tri_tri(N1, V0, V1, V2, U0, U1, U2); \ + } /* this edge to edge test is based on Franlin Antonio's gem: "Faster Line Segment Intersection", in Graphics Gems III, pp. 199-202 */ -#define EDGE_EDGE_TEST(V0,U0,U1) \ - Bx=U0[i0]-U1[i0]; \ - By=U0[i1]-U1[i1]; \ - Cx=V0[i0]-U0[i0]; \ - Cy=V0[i1]-U0[i1]; \ - f=Ay*Bx-Ax*By; \ - d=By*Cx-Bx*Cy; \ - if((f>0 && d>=0 && d<=f) || (f<0 && d<=0 && d>=f)) \ - { \ - e=Ax*Cy-Ay*Cx; \ - if(f>0) \ - { \ - if(e>=0 && e<=f) return 1; \ - } \ - else \ - { \ - if(e<=0 && e>=f) return 1; \ - } \ - } - -#define EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2) \ -{ \ - float Ax,Ay,Bx,By,Cx,Cy,e,d,f; \ - Ax=V1[i0]-V0[i0]; \ - Ay=V1[i1]-V0[i1]; \ - /* test edge U0,U1 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U0,U1); \ - /* test edge U1,U2 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U1,U2); \ - /* test edge U2,U1 against V0,V1 */ \ - EDGE_EDGE_TEST(V0,U2,U0); \ -} - -#define POINT_IN_TRI(V0,U0,U1,U2) \ -{ \ - float a,b,c,d0,d1,d2; \ - /* is T1 completly inside T2? */ \ - /* check if V0 is inside tri(U0,U1,U2) */ \ - a=U1[i1]-U0[i1]; \ - b=-(U1[i0]-U0[i0]); \ - c=-a*U0[i0]-b*U0[i1]; \ - d0=a*V0[i0]+b*V0[i1]+c; \ - \ - a=U2[i1]-U1[i1]; \ - b=-(U2[i0]-U1[i0]); \ - c=-a*U1[i0]-b*U1[i1]; \ - d1=a*V0[i0]+b*V0[i1]+c; \ - \ - a=U0[i1]-U2[i1]; \ - b=-(U0[i0]-U2[i0]); \ - c=-a*U2[i0]-b*U2[i1]; \ - d2=a*V0[i0]+b*V0[i1]+c; \ - if(d0*d1>0.0) \ - { \ - if(d0*d2>0.0) return 1; \ - } \ -} - -qboolean coplanar_tri_tri(vec3_t N,vec3_t V0,vec3_t V1,vec3_t V2, - vec3_t U0,vec3_t U1,vec3_t U2) -{ - vec3_t A; - short i0,i1; - /* first project onto an axis-aligned plane, that maximizes the area */ - /* of the triangles, compute indices: i0,i1. */ - A[0]=fabs(N[0]); - A[1]=fabs(N[1]); - A[2]=fabs(N[2]); - if(A[0]>A[1]) - { - if(A[0]>A[2]) - { - i0=1; /* A[0] is greatest */ - i1=2; - } - else - { - i0=0; /* A[2] is greatest */ - i1=1; - } - } - else /* A[0]<=A[1] */ - { - if(A[2]>A[1]) - { - i0=0; /* A[2] is greatest */ - i1=1; - } - else - { - i0=0; /* A[1] is greatest */ - i1=2; - } - } - - /* test all edges of triangle 1 against the edges of triangle 2 */ - EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2); - EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2); - EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2); - - /* finally, test if tri1 is totally contained in tri2 or vice versa */ - POINT_IN_TRI(V0,U0,U1,U2); - POINT_IN_TRI(U0,V0,V1,V2); - - return qfalse; +#define EDGE_EDGE_TEST(V0, U0, U1) \ + Bx = U0[i0] - U1[i0]; \ + By = U0[i1] - U1[i1]; \ + Cx = V0[i0] - U0[i0]; \ + Cy = V0[i1] - U0[i1]; \ + f = Ay * Bx - Ax * By; \ + d = By * Cx - Bx * Cy; \ + if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) { \ + e = Ax * Cy - Ay * Cx; \ + if (f > 0) { \ + if (e >= 0 && e <= f) \ + return 1; \ + } else { \ + if (e <= 0 && e >= f) \ + return 1; \ + } \ + } + +#define EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2) \ + { \ + float Ax, Ay, Bx, By, Cx, Cy, e, d, f; \ + Ax = V1[i0] - V0[i0]; \ + Ay = V1[i1] - V0[i1]; \ + /* test edge U0,U1 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U0, U1); \ + /* test edge U1,U2 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U1, U2); \ + /* test edge U2,U1 against V0,V1 */ \ + EDGE_EDGE_TEST(V0, U2, U0); \ + } + +#define POINT_IN_TRI(V0, U0, U1, U2) \ + { \ + float a, b, c, d0, d1, d2; \ + /* is T1 completly inside T2? */ \ + /* check if V0 is inside tri(U0,U1,U2) */ \ + a = U1[i1] - U0[i1]; \ + b = -(U1[i0] - U0[i0]); \ + c = -a * U0[i0] - b * U0[i1]; \ + d0 = a * V0[i0] + b * V0[i1] + c; \ + \ + a = U2[i1] - U1[i1]; \ + b = -(U2[i0] - U1[i0]); \ + c = -a * U1[i0] - b * U1[i1]; \ + d1 = a * V0[i0] + b * V0[i1] + c; \ + \ + a = U0[i1] - U2[i1]; \ + b = -(U0[i0] - U2[i0]); \ + c = -a * U2[i0] - b * U2[i1]; \ + d2 = a * V0[i0] + b * V0[i1] + c; \ + if (d0 * d1 > 0.0) { \ + if (d0 * d2 > 0.0) \ + return 1; \ + } \ + } + +qboolean coplanar_tri_tri(vec3_t N, vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2) { + vec3_t A; + short i0, i1; + /* first project onto an axis-aligned plane, that maximizes the area */ + /* of the triangles, compute indices: i0,i1. */ + A[0] = fabs(N[0]); + A[1] = fabs(N[1]); + A[2] = fabs(N[2]); + if (A[0] > A[1]) { + if (A[0] > A[2]) { + i0 = 1; /* A[0] is greatest */ + i1 = 2; + } else { + i0 = 0; /* A[2] is greatest */ + i1 = 1; + } + } else /* A[0]<=A[1] */ + { + if (A[2] > A[1]) { + i0 = 0; /* A[2] is greatest */ + i1 = 1; + } else { + i0 = 0; /* A[1] is greatest */ + i1 = 2; + } + } + + /* test all edges of triangle 1 against the edges of triangle 2 */ + EDGE_AGAINST_TRI_EDGES(V0, V1, U0, U1, U2); + EDGE_AGAINST_TRI_EDGES(V1, V2, U0, U1, U2); + EDGE_AGAINST_TRI_EDGES(V2, V0, U0, U1, U2); + + /* finally, test if tri1 is totally contained in tri2 or vice versa */ + POINT_IN_TRI(V0, U0, U1, U2); + POINT_IN_TRI(U0, V0, V1, V2); + + return qfalse; } -qboolean tri_tri_intersect(vec3_t V0,vec3_t V1,vec3_t V2, - vec3_t U0,vec3_t U1,vec3_t U2) -{ - vec3_t E1,E2; - vec3_t N1,N2; - float d1,d2; - float du0,du1,du2,dv0,dv1,dv2; - vec3_t D; - float isect1[2], isect2[2]; - float du0du1,du0du2,dv0dv1,dv0dv2; - short index; - float vp0,vp1,vp2; - float up0,up1,up2; - float b,c,max; - - /* compute plane equation of triangle(V0,V1,V2) */ - SUB(E1,V1,V0); - SUB(E2,V2,V0); - CROSS(N1,E1,E2); - d1=-DOT(N1,V0); - /* plane equation 1: N1.X+d1=0 */ - - /* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/ - du0=DOT(N1,U0)+d1; - du1=DOT(N1,U1)+d1; - du2=DOT(N1,U2)+d1; - - /* coplanarity robustness check */ +qboolean tri_tri_intersect(vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2) { + vec3_t E1, E2; + vec3_t N1, N2; + float d1, d2; + float du0, du1, du2, dv0, dv1, dv2; + vec3_t D; + float isect1[2], isect2[2]; + float du0du1, du0du2, dv0dv1, dv0dv2; + short index; + float vp0, vp1, vp2; + float up0, up1, up2; + float b, c, max; + + /* compute plane equation of triangle(V0,V1,V2) */ + SUB(E1, V1, V0); + SUB(E2, V2, V0); + CROSS(N1, E1, E2); + d1 = -DOT(N1, V0); + /* plane equation 1: N1.X+d1=0 */ + + /* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/ + du0 = DOT(N1, U0) + d1; + du1 = DOT(N1, U1) + d1; + du2 = DOT(N1, U2) + d1; + + /* coplanarity robustness check */ #if USE_EPSILON_TEST - if(fabs(du0)0.0f && du0du2>0.0f) /* same sign on all of them + not equal 0 ? */ - return 0; /* no intersection occurs */ + if (du0du1 > 0.0f && du0du2 > 0.0f) /* same sign on all of them + not equal 0 ? */ + return 0; /* no intersection occurs */ - /* compute plane of triangle (U0,U1,U2) */ - SUB(E1,U1,U0); - SUB(E2,U2,U0); - CROSS(N2,E1,E2); - d2=-DOT(N2,U0); - /* plane equation 2: N2.X+d2=0 */ + /* compute plane of triangle (U0,U1,U2) */ + SUB(E1, U1, U0); + SUB(E2, U2, U0); + CROSS(N2, E1, E2); + d2 = -DOT(N2, U0); + /* plane equation 2: N2.X+d2=0 */ - /* put V0,V1,V2 into plane equation 2 */ - dv0=DOT(N2,V0)+d2; - dv1=DOT(N2,V1)+d2; - dv2=DOT(N2,V2)+d2; + /* put V0,V1,V2 into plane equation 2 */ + dv0 = DOT(N2, V0) + d2; + dv1 = DOT(N2, V1) + d2; + dv2 = DOT(N2, V2) + d2; #if USE_EPSILON_TEST - if(fabs(dv0)0.0f && dv0dv2>0.0f) /* same sign on all of them + not equal 0 ? */ - return 0; /* no intersection occurs */ + if (dv0dv1 > 0.0f && dv0dv2 > 0.0f) /* same sign on all of them + not equal 0 ? */ + return 0; /* no intersection occurs */ - /* compute direction of intersection line */ - CROSS(D,N1,N2); + /* compute direction of intersection line */ + CROSS(D, N1, N2); - /* compute and index to the largest component of D */ - max=fabs(D[0]); - index=0; - b=fabs(D[1]); - c=fabs(D[2]); - if(b>max) max=b,index=1; - if(c>max) max=c,index=2; + /* compute and index to the largest component of D */ + max = fabs(D[0]); + index = 0; + b = fabs(D[1]); + c = fabs(D[2]); + if (b > max) + max = b, index = 1; + if (c > max) + max = c, index = 2; - /* this is the simplified projection onto L*/ - vp0=V0[index]; - vp1=V1[index]; - vp2=V2[index]; + /* this is the simplified projection onto L*/ + vp0 = V0[index]; + vp1 = V1[index]; + vp2 = V2[index]; - up0=U0[index]; - up1=U1[index]; - up2=U2[index]; + up0 = U0[index]; + up1 = U1[index]; + up2 = U2[index]; - /* compute interval for triangle 1 */ - COMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,isect1[0],isect1[1]); + /* compute interval for triangle 1 */ + COMPUTE_INTERVALS(vp0, vp1, vp2, dv0, dv1, dv2, dv0dv1, dv0dv2, isect1[0], isect1[1]); - /* compute interval for triangle 2 */ - COMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,isect2[0],isect2[1]); + /* compute interval for triangle 2 */ + COMPUTE_INTERVALS(up0, up1, up2, du0, du1, du2, du0du1, du0du2, isect2[0], isect2[1]); - SORT(isect1[0],isect1[1]); - SORT(isect2[0],isect2[1]); + SORT(isect1[0], isect1[1]); + SORT(isect2[0], isect2[1]); - if(isect1[1]. #define METROID_JUMP 1 -//NEEDED FOR MIND-TRICK on NPCS========================================================= -extern void NPC_PlayConfusionSound( gentity_t *self ); -extern void NPC_Jedi_PlayConfusionSound( gentity_t *self ); -extern void NPC_UseResponse( gentity_t *self, gentity_t *user, qboolean useWhenDone ); -//NEEDED FOR MIND-TRICK on NPCS========================================================= -extern void Jedi_Decloak( gentity_t *self ); +// NEEDED FOR MIND-TRICK on NPCS========================================================= +extern void NPC_PlayConfusionSound(gentity_t *self); +extern void NPC_Jedi_PlayConfusionSound(gentity_t *self); +extern void NPC_UseResponse(gentity_t *self, gentity_t *user, qboolean useWhenDone); +// NEEDED FOR MIND-TRICK on NPCS========================================================= +extern void Jedi_Decloak(gentity_t *self); -extern qboolean BG_FullBodyTauntAnim( int anim ); +extern qboolean BG_FullBodyTauntAnim(int anim); extern bot_state_t *botstates[MAX_CLIENTS]; -int speedLoopSound = 0; -int rageLoopSound = 0; -int protectLoopSound = 0; -int absorbLoopSound = 0; -int seeLoopSound = 0; -int ysalamiriLoopSound = 0; +int speedLoopSound = 0; +int rageLoopSound = 0; +int protectLoopSound = 0; +int absorbLoopSound = 0; +int seeLoopSound = 0; +int ysalamiriLoopSound = 0; #define FORCE_VELOCITY_DAMAGE 0 -int ForceShootDrain( gentity_t *self ); +int ForceShootDrain(gentity_t *self); -gentity_t *G_PreDefSound(vec3_t org, int pdSound) -{ - gentity_t *te; +gentity_t *G_PreDefSound(vec3_t org, int pdSound) { + gentity_t *te; - te = G_TempEntity( org, EV_PREDEFSOUND ); + te = G_TempEntity(org, EV_PREDEFSOUND); te->s.eventParm = pdSound; VectorCopy(org, te->s.origin); return te; } -const int forcePowerMinRank[NUM_FORCE_POWER_LEVELS][NUM_FORCE_POWERS] = //0 == neutral -{ - { - 999,//FP_HEAL,//instant - 999,//FP_LEVITATION,//hold/duration - 999,//FP_SPEED,//duration - 999,//FP_PUSH,//hold/duration - 999,//FP_PULL,//hold/duration - 999,//FP_TELEPATHY,//instant - 999,//FP_GRIP,//hold/duration - 999,//FP_LIGHTNING,//hold/duration - 999,//FP_RAGE,//duration - 999,//FP_PROTECT,//duration - 999,//FP_ABSORB,//duration - 999,//FP_TEAM_HEAL,//instant - 999,//FP_TEAM_FORCE,//instant - 999,//FP_DRAIN,//hold/duration - 999,//FP_SEE,//duration - 999,//FP_SABER_OFFENSE, - 999,//FP_SABER_DEFENSE, - 999//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 10,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - 10,//FP_TELEPATHY,//instant - 15,//FP_GRIP,//hold/duration - 10,//FP_LIGHTNING,//hold/duration - 15,//FP_RAGE,//duration - 15,//FP_PROTECT,//duration - 15,//FP_ABSORB,//duration - 10,//FP_TEAM_HEAL,//instant - 10,//FP_TEAM_FORCE,//instant - 10,//FP_DRAIN,//hold/duration - 5,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 0,//FP_SABER_DEFENSE, - 0//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 10,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - 10,//FP_TELEPATHY,//instant - 15,//FP_GRIP,//hold/duration - 10,//FP_LIGHTNING,//hold/duration - 15,//FP_RAGE,//duration - 15,//FP_PROTECT,//duration - 15,//FP_ABSORB,//duration - 10,//FP_TEAM_HEAL,//instant - 10,//FP_TEAM_FORCE,//instant - 10,//FP_DRAIN,//hold/duration - 5,//FP_SEE,//duration - 5,//FP_SABER_OFFENSE, - 5,//FP_SABER_DEFENSE, - 5//FP_SABERTHROW, - //NUM_FORCE_POWERS - }, - { - 10,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - 10,//FP_TELEPATHY,//instant - 15,//FP_GRIP,//hold/duration - 10,//FP_LIGHTNING,//hold/duration - 15,//FP_RAGE,//duration - 15,//FP_PROTECT,//duration - 15,//FP_ABSORB,//duration - 10,//FP_TEAM_HEAL,//instant - 10,//FP_TEAM_FORCE,//instant - 10,//FP_DRAIN,//hold/duration - 5,//FP_SEE,//duration - 10,//FP_SABER_OFFENSE, - 10,//FP_SABER_DEFENSE, - 10//FP_SABERTHROW, - //NUM_FORCE_POWERS - } -}; - -const int mindTrickTime[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 5000, - 10000, - 15000 -}; - -void WP_InitForcePowers( gentity_t *ent ) { +const int forcePowerMinRank[NUM_FORCE_POWER_LEVELS][NUM_FORCE_POWERS] = // 0 == neutral + {{ + 999, // FP_HEAL,//instant + 999, // FP_LEVITATION,//hold/duration + 999, // FP_SPEED,//duration + 999, // FP_PUSH,//hold/duration + 999, // FP_PULL,//hold/duration + 999, // FP_TELEPATHY,//instant + 999, // FP_GRIP,//hold/duration + 999, // FP_LIGHTNING,//hold/duration + 999, // FP_RAGE,//duration + 999, // FP_PROTECT,//duration + 999, // FP_ABSORB,//duration + 999, // FP_TEAM_HEAL,//instant + 999, // FP_TEAM_FORCE,//instant + 999, // FP_DRAIN,//hold/duration + 999, // FP_SEE,//duration + 999, // FP_SABER_OFFENSE, + 999, // FP_SABER_DEFENSE, + 999 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 10, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + 10, // FP_TELEPATHY,//instant + 15, // FP_GRIP,//hold/duration + 10, // FP_LIGHTNING,//hold/duration + 15, // FP_RAGE,//duration + 15, // FP_PROTECT,//duration + 15, // FP_ABSORB,//duration + 10, // FP_TEAM_HEAL,//instant + 10, // FP_TEAM_FORCE,//instant + 10, // FP_DRAIN,//hold/duration + 5, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 0, // FP_SABER_DEFENSE, + 0 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 10, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + 10, // FP_TELEPATHY,//instant + 15, // FP_GRIP,//hold/duration + 10, // FP_LIGHTNING,//hold/duration + 15, // FP_RAGE,//duration + 15, // FP_PROTECT,//duration + 15, // FP_ABSORB,//duration + 10, // FP_TEAM_HEAL,//instant + 10, // FP_TEAM_FORCE,//instant + 10, // FP_DRAIN,//hold/duration + 5, // FP_SEE,//duration + 5, // FP_SABER_OFFENSE, + 5, // FP_SABER_DEFENSE, + 5 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }, + { + 10, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + 10, // FP_TELEPATHY,//instant + 15, // FP_GRIP,//hold/duration + 10, // FP_LIGHTNING,//hold/duration + 15, // FP_RAGE,//duration + 15, // FP_PROTECT,//duration + 15, // FP_ABSORB,//duration + 10, // FP_TEAM_HEAL,//instant + 10, // FP_TEAM_FORCE,//instant + 10, // FP_DRAIN,//hold/duration + 5, // FP_SEE,//duration + 10, // FP_SABER_OFFENSE, + 10, // FP_SABER_DEFENSE, + 10 // FP_SABERTHROW, + // NUM_FORCE_POWERS + }}; + +const int mindTrickTime[NUM_FORCE_POWER_LEVELS] = {0, // none + 5000, 10000, 15000}; + +void WP_InitForcePowers(gentity_t *ent) { int i, i_r, lastFPKnown = -1; qboolean warnClient = qfalse, warnClientLimit = qfalse, didEvent = qfalse; - char userinfo[MAX_INFO_STRING], forcePowers[DEFAULT_FORCEPOWERS_LEN+1], readBuf[DEFAULT_FORCEPOWERS_LEN+1]; + char userinfo[MAX_INFO_STRING], forcePowers[DEFAULT_FORCEPOWERS_LEN + 1], readBuf[DEFAULT_FORCEPOWERS_LEN + 1]; // if server has no max rank, default to max (50) - if ( g_maxForceRank.integer <= 0 || g_maxForceRank.integer >= NUM_FORCE_MASTERY_LEVELS ) { + if (g_maxForceRank.integer <= 0 || g_maxForceRank.integer >= NUM_FORCE_MASTERY_LEVELS) { // ack, prevent user from being dumb - trap->Cvar_Set( "g_maxForceRank", va( "%i", FORCE_MASTERY_JEDI_MASTER ) ); - trap->Cvar_Update( &g_maxForceRank ); + trap->Cvar_Set("g_maxForceRank", va("%i", FORCE_MASTERY_JEDI_MASTER)); + trap->Cvar_Update(&g_maxForceRank); } - if ( !ent || !ent->client ) + if (!ent || !ent->client) return; ent->client->ps.fd.saberAnimLevel = ent->client->sess.saberLevel; - if ( ent->client->ps.fd.saberAnimLevel < FORCE_LEVEL_1 || ent->client->ps.fd.saberAnimLevel > FORCE_LEVEL_3 ) + if (ent->client->ps.fd.saberAnimLevel < FORCE_LEVEL_1 || ent->client->ps.fd.saberAnimLevel > FORCE_LEVEL_3) ent->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; // so that the client configstring is already modified with this when we need it - if ( !speedLoopSound ) - speedLoopSound = G_SoundIndex( "sound/weapons/force/speedloop.wav" ); - if ( !rageLoopSound ) - rageLoopSound = G_SoundIndex( "sound/weapons/force/rageloop.wav" ); - if ( !absorbLoopSound ) - absorbLoopSound = G_SoundIndex( "sound/weapons/force/absorbloop.wav" ); - if ( !protectLoopSound ) - protectLoopSound = G_SoundIndex( "sound/weapons/force/protectloop.wav" ); - if ( !seeLoopSound ) - seeLoopSound = G_SoundIndex( "sound/weapons/force/seeloop.wav" ); - if ( !ysalamiriLoopSound ) - ysalamiriLoopSound = G_SoundIndex( "sound/player/nullifyloop.wav" ); - - if ( ent->s.eType == ET_NPC ) + if (!speedLoopSound) + speedLoopSound = G_SoundIndex("sound/weapons/force/speedloop.wav"); + if (!rageLoopSound) + rageLoopSound = G_SoundIndex("sound/weapons/force/rageloop.wav"); + if (!absorbLoopSound) + absorbLoopSound = G_SoundIndex("sound/weapons/force/absorbloop.wav"); + if (!protectLoopSound) + protectLoopSound = G_SoundIndex("sound/weapons/force/protectloop.wav"); + if (!seeLoopSound) + seeLoopSound = G_SoundIndex("sound/weapons/force/seeloop.wav"); + if (!ysalamiriLoopSound) + ysalamiriLoopSound = G_SoundIndex("sound/player/nullifyloop.wav"); + + if (ent->s.eType == ET_NPC) return; - for ( i=0; iclient->ps.fd.forcePowerLevel[i] = 0; - ent->client->ps.fd.forcePowersKnown &= ~(1<client->ps.fd.forcePowersKnown &= ~(1 << i); } ent->client->ps.fd.forcePowerSelected = -1; ent->client->ps.fd.forceSide = 0; // if in siege, then use the powers for this class, and skip all this nonsense. - if ( level.gametype == GT_SIEGE && ent->client->siegeClass != -1 ) { - for ( i=0; iclient->siegeClass != -1) { + for (i = 0; i < NUM_FORCE_POWERS; i++) { ent->client->ps.fd.forcePowerLevel[i] = bgSiegeClasses[ent->client->siegeClass].forcePowerLevels[i]; - if ( !ent->client->ps.fd.forcePowerLevel[i] ) + if (!ent->client->ps.fd.forcePowerLevel[i]) ent->client->ps.fd.forcePowersKnown &= ~(1 << i); else ent->client->ps.fd.forcePowersKnown |= (1 << i); } // bring up the class selection menu - if ( !ent->client->sess.setForce ) - trap->SendServerCommand( ent-g_entities, "scl" ); + if (!ent->client->sess.setForce) + trap->SendServerCommand(ent - g_entities, "scl"); ent->client->sess.setForce = qtrue; return; } - //rwwFIXMEFIXME: Temp - if ( ent->s.eType == ET_NPC && ent->s.number >= MAX_CLIENTS ) - Q_strncpyz( userinfo, "forcepowers\\7-1-333003000313003120", sizeof( userinfo ) ); + // rwwFIXMEFIXME: Temp + if (ent->s.eType == ET_NPC && ent->s.number >= MAX_CLIENTS) + Q_strncpyz(userinfo, "forcepowers\\7-1-333003000313003120", sizeof(userinfo)); else - trap->GetUserinfo( ent->s.number, userinfo, sizeof( userinfo ) ); + trap->GetUserinfo(ent->s.number, userinfo, sizeof(userinfo)); - Q_strncpyz( forcePowers, Info_ValueForKey( userinfo, "forcepowers" ), sizeof( forcePowers ) ); + Q_strncpyz(forcePowers, Info_ValueForKey(userinfo, "forcepowers"), sizeof(forcePowers)); - if ( strlen( forcePowers ) != DEFAULT_FORCEPOWERS_LEN ) { - Q_strncpyz( forcePowers, DEFAULT_FORCEPOWERS, sizeof( forcePowers ) ); - trap->SendServerCommand( ent-g_entities, "print \"" S_COLOR_RED "Invalid forcepowers string, setting default\n\"" ); + if (strlen(forcePowers) != DEFAULT_FORCEPOWERS_LEN) { + Q_strncpyz(forcePowers, DEFAULT_FORCEPOWERS, sizeof(forcePowers)); + trap->SendServerCommand(ent - g_entities, "print \"" S_COLOR_RED "Invalid forcepowers string, setting default\n\""); } - //if it's a bot just copy the info directly from its personality - if ( (ent->r.svFlags & SVF_BOT) && botstates[ent->s.number] ) - Q_strncpyz( forcePowers, botstates[ent->s.number]->forceinfo, sizeof( forcePowers ) ); + // if it's a bot just copy the info directly from its personality + if ((ent->r.svFlags & SVF_BOT) && botstates[ent->s.number]) + Q_strncpyz(forcePowers, botstates[ent->s.number]->forceinfo, sizeof(forcePowers)); - if ( g_forceBasedTeams.integer ) { - if ( ent->client->sess.sessionTeam == TEAM_RED ) - warnClient = !(BG_LegalizedForcePowers( forcePowers, sizeof (forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), FORCE_DARKSIDE, level.gametype, g_forcePowerDisable.integer )); - else if ( ent->client->sess.sessionTeam == TEAM_BLUE ) - warnClient = !(BG_LegalizedForcePowers( forcePowers, sizeof (forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), FORCE_LIGHTSIDE, level.gametype, g_forcePowerDisable.integer )); + if (g_forceBasedTeams.integer) { + if (ent->client->sess.sessionTeam == TEAM_RED) + warnClient = !(BG_LegalizedForcePowers(forcePowers, sizeof(forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), FORCE_DARKSIDE, level.gametype, + g_forcePowerDisable.integer)); + else if (ent->client->sess.sessionTeam == TEAM_BLUE) + warnClient = !(BG_LegalizedForcePowers(forcePowers, sizeof(forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), FORCE_LIGHTSIDE, level.gametype, + g_forcePowerDisable.integer)); else - warnClient = !(BG_LegalizedForcePowers( forcePowers, sizeof (forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), 0, level.gametype, g_forcePowerDisable.integer )); - } - else - warnClient = !(BG_LegalizedForcePowers( forcePowers, sizeof (forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), 0, level.gametype, g_forcePowerDisable.integer )); + warnClient = !(BG_LegalizedForcePowers(forcePowers, sizeof(forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), 0, level.gametype, + g_forcePowerDisable.integer)); + } else + warnClient = !(BG_LegalizedForcePowers(forcePowers, sizeof(forcePowers), g_maxForceRank.integer, HasSetSaberOnly(), 0, level.gametype, + g_forcePowerDisable.integer)); - //rww - parse through the string manually and eat out all the appropriate data + // rww - parse through the string manually and eat out all the appropriate data i = 0; i_r = 0; - while ( forcePowers[i] && forcePowers[i] != '-' ) { + while (forcePowers[i] && forcePowers[i] != '-') { readBuf[i_r] = forcePowers[i]; i_r++; i++; } readBuf[i_r] = 0; - //THE RANK - ent->client->ps.fd.forceRank = atoi( readBuf ); + // THE RANK + ent->client->ps.fd.forceRank = atoi(readBuf); i++; i_r = 0; - while ( forcePowers[i] && forcePowers[i] != '-' ) { + while (forcePowers[i] && forcePowers[i] != '-') { readBuf[i_r] = forcePowers[i]; i_r++; i++; } readBuf[i_r] = 0; - //THE SIDE - ent->client->ps.fd.forceSide = atoi( readBuf ); + // THE SIDE + ent->client->ps.fd.forceSide = atoi(readBuf); i++; - if ( level.gametype != GT_SIEGE && (ent->r.svFlags & SVF_BOT) && botstates[ent->s.number] ) { + if (level.gametype != GT_SIEGE && (ent->r.svFlags & SVF_BOT) && botstates[ent->s.number]) { // hmm..I'm going to cheat here. int oldI = i; i_r = 0; - while ( forcePowers[i] && forcePowers[i] != '\n' && i_r < NUM_FORCE_POWERS ) { - if ( ent->client->ps.fd.forceSide == FORCE_LIGHTSIDE ) { - if ( i_r == FP_ABSORB ) + while (forcePowers[i] && forcePowers[i] != '\n' && i_r < NUM_FORCE_POWERS) { + if (ent->client->ps.fd.forceSide == FORCE_LIGHTSIDE) { + if (i_r == FP_ABSORB) forcePowers[i] = '3'; - if ( botstates[ent->s.number]->settings.skill >= 4 ) { + if (botstates[ent->s.number]->settings.skill >= 4) { // cheat and give them more stuff - if ( i_r == FP_HEAL ) + if (i_r == FP_HEAL) forcePowers[i] = '3'; - else if ( i_r == FP_PROTECT ) + else if (i_r == FP_PROTECT) forcePowers[i] = '3'; } - } - else if ( ent->client->ps.fd.forceSide == FORCE_DARKSIDE ) { - if ( botstates[ent->s.number]->settings.skill >= 4 ) { - if ( i_r == FP_GRIP ) + } else if (ent->client->ps.fd.forceSide == FORCE_DARKSIDE) { + if (botstates[ent->s.number]->settings.skill >= 4) { + if (i_r == FP_GRIP) forcePowers[i] = '3'; - else if ( i_r == FP_LIGHTNING ) + else if (i_r == FP_LIGHTNING) forcePowers[i] = '3'; - else if ( i_r == FP_RAGE ) + else if (i_r == FP_RAGE) forcePowers[i] = '3'; - else if ( i_r == FP_DRAIN ) + else if (i_r == FP_DRAIN) forcePowers[i] = '3'; } } - if ( i_r == FP_PUSH ) + if (i_r == FP_PUSH) forcePowers[i] = '3'; - else if ( i_r == FP_PULL ) + else if (i_r == FP_PULL) forcePowers[i] = '3'; i++; @@ -311,127 +305,117 @@ void WP_InitForcePowers( gentity_t *ent ) { } i_r = 0; - while (forcePowers[i] && forcePowers[i] != '\n' && - i_r < NUM_FORCE_POWERS) - { + while (forcePowers[i] && forcePowers[i] != '\n' && i_r < NUM_FORCE_POWERS) { readBuf[0] = forcePowers[i]; readBuf[1] = 0; ent->client->ps.fd.forcePowerLevel[i_r] = atoi(readBuf); - if (ent->client->ps.fd.forcePowerLevel[i_r]) - { + if (ent->client->ps.fd.forcePowerLevel[i_r]) { ent->client->ps.fd.forcePowersKnown |= (1 << i_r); - } - else - { + } else { ent->client->ps.fd.forcePowersKnown &= ~(1 << i_r); } i++; i_r++; } - //THE POWERS + // THE POWERS - if ( ent->s.eType != ET_NPC ) { - if ( HasSetSaberOnly() ) { - gentity_t *te = G_TempEntity( vec3_origin, EV_SET_FREE_SABER ); + if (ent->s.eType != ET_NPC) { + if (HasSetSaberOnly()) { + gentity_t *te = G_TempEntity(vec3_origin, EV_SET_FREE_SABER); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = 1; - } - else { - gentity_t *te = G_TempEntity( vec3_origin, EV_SET_FREE_SABER ); + } else { + gentity_t *te = G_TempEntity(vec3_origin, EV_SET_FREE_SABER); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = 0; } - if ( g_forcePowerDisable.integer ) { - gentity_t *te = G_TempEntity( vec3_origin, EV_SET_FORCE_DISABLE ); + if (g_forcePowerDisable.integer) { + gentity_t *te = G_TempEntity(vec3_origin, EV_SET_FORCE_DISABLE); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = 1; - } - else { - gentity_t *te = G_TempEntity( vec3_origin, EV_SET_FORCE_DISABLE ); + } else { + gentity_t *te = G_TempEntity(vec3_origin, EV_SET_FORCE_DISABLE); te->r.svFlags |= SVF_BROADCAST; te->s.eventParm = 0; } } - if ( ent->s.eType == ET_NPC ) + if (ent->s.eType == ET_NPC) ent->client->sess.setForce = qtrue; - else if ( level.gametype == GT_SIEGE ) { - if ( !ent->client->sess.setForce ) { + else if (level.gametype == GT_SIEGE) { + if (!ent->client->sess.setForce) { ent->client->sess.setForce = qtrue; // bring up the class selection menu - trap->SendServerCommand( ent-g_entities, "scl" ); + trap->SendServerCommand(ent - g_entities, "scl"); } - } - else { - if ( warnClient || !ent->client->sess.setForce ) { + } else { + if (warnClient || !ent->client->sess.setForce) { // the client's rank is too high for the server and has been autocapped, so tell them - if ( level.gametype != GT_HOLOCRON && level.gametype != GT_JEDIMASTER ) { + if (level.gametype != GT_HOLOCRON && level.gametype != GT_JEDIMASTER) { didEvent = qtrue; - if ( !(ent->r.svFlags & SVF_BOT) && ent->s.eType != ET_NPC ) { - if ( !g_teamAutoJoin.integer ) { + if (!(ent->r.svFlags & SVF_BOT) && ent->s.eType != ET_NPC) { + if (!g_teamAutoJoin.integer) { // make them a spectator so they can set their powerups up without being bothered. ent->client->sess.sessionTeam = TEAM_SPECTATOR; ent->client->sess.spectatorState = SPECTATOR_FREE; ent->client->sess.spectatorClient = 0; ent->client->pers.teamState.state = TEAM_BEGIN; - trap->SendServerCommand( ent-g_entities, "spc" ); // Fire up the profile menu + trap->SendServerCommand(ent - g_entities, "spc"); // Fire up the profile menu } } // event isn't very reliable, I made it a string. This way I can send it to just one client also, // as opposed to making a broadcast event. - trap->SendServerCommand( ent->s.number, va( "nfr %i %i %i", g_maxForceRank.integer, 1, ent->client->sess.sessionTeam ) ); + trap->SendServerCommand(ent->s.number, va("nfr %i %i %i", g_maxForceRank.integer, 1, ent->client->sess.sessionTeam)); // arg1 is new max rank, arg2 is non-0 if force menu should be shown, arg3 is the current team } ent->client->sess.setForce = qtrue; } - if ( !didEvent ) - trap->SendServerCommand( ent->s.number, va( "nfr %i %i %i", g_maxForceRank.integer, 0, ent->client->sess.sessionTeam ) ); + if (!didEvent) + trap->SendServerCommand(ent->s.number, va("nfr %i %i %i", g_maxForceRank.integer, 0, ent->client->sess.sessionTeam)); // the server has one or more force powers disabled and the client is using them in his config - if ( warnClientLimit ) - trap->SendServerCommand( ent-g_entities, va( "print \"The server has one or more force powers that you have chosen disabled.\nYou will not be able to use the disable force power(s) while playing on this server.\n\"" ) ); + if (warnClientLimit) + trap->SendServerCommand(ent - g_entities, va("print \"The server has one or more force powers that you have chosen disabled.\nYou will not be able " + "to use the disable force power(s) while playing on this server.\n\"")); } - for ( i=0; iclient->ps.fd.forcePowersKnown & (1 << i)) && !ent->client->ps.fd.forcePowerLevel[i] ) + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if ((ent->client->ps.fd.forcePowersKnown & (1 << i)) && !ent->client->ps.fd.forcePowerLevel[i]) ent->client->ps.fd.forcePowersKnown &= ~(1 << i); - else if ( i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE && i != FP_SABERTHROW ) + else if (i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE && i != FP_SABERTHROW) lastFPKnown = i; } - if ( ent->client->ps.fd.forcePowersKnown & ent->client->sess.selectedFP ) + if (ent->client->ps.fd.forcePowersKnown & ent->client->sess.selectedFP) ent->client->ps.fd.forcePowerSelected = ent->client->sess.selectedFP; - if ( !(ent->client->ps.fd.forcePowersKnown & (1 << ent->client->ps.fd.forcePowerSelected)) ) { - if ( lastFPKnown != -1 ) + if (!(ent->client->ps.fd.forcePowersKnown & (1 << ent->client->ps.fd.forcePowerSelected))) { + if (lastFPKnown != -1) ent->client->ps.fd.forcePowerSelected = lastFPKnown; else ent->client->ps.fd.forcePowerSelected = 0; } - for ( /*i=0*/; iclient->ps.fd.forcePowerBaseLevel[i] = ent->client->ps.fd.forcePowerLevel[i]; ent->client->ps.fd.forceUsingAdded = 0; } -void WP_SpawnInitForcePowers( gentity_t *ent ) -{ +void WP_SpawnInitForcePowers(gentity_t *ent) { int i = 0; ent->client->ps.saberAttackChainCount = 0; i = 0; - while (i < NUM_FORCE_POWERS) - { - if (ent->client->ps.fd.forcePowersActive & (1 << i)) - { + while (i < NUM_FORCE_POWERS) { + if (ent->client->ps.fd.forcePowersActive & (1 << i)) { WP_ForcePowerStop(ent, i); } @@ -451,29 +435,23 @@ void WP_SpawnInitForcePowers( gentity_t *ent ) ent->client->ps.holocronBits = 0; i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { ent->client->ps.holocronsCarried[i] = 0; i++; } - if (level.gametype == GT_HOLOCRON) - { + if (level.gametype == GT_HOLOCRON) { i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { ent->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_0; i++; } - if (HasSetSaberOnly()) - { - if (ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_1) - { + if (HasSetSaberOnly()) { + if (ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_1) { ent->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; } - if (ent->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1) - { + if (ent->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1) { ent->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; } } @@ -481,8 +459,7 @@ void WP_SpawnInitForcePowers( gentity_t *ent ) i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { ent->client->ps.fd.forcePowerDebounce[i] = 0; ent->client->ps.fd.forcePowerDuration[i] = 0; @@ -505,32 +482,24 @@ void WP_SpawnInitForcePowers( gentity_t *ent ) ent->client->ps.fd.forceDrainTime = 0; i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { if ((ent->client->ps.fd.forcePowersKnown & (1 << i)) && - !ent->client->ps.fd.forcePowerLevel[i]) - { //make sure all known powers are cleared if we have level 0 in them + !ent->client->ps.fd.forcePowerLevel[i]) { // make sure all known powers are cleared if we have level 0 in them ent->client->ps.fd.forcePowersKnown &= ~(1 << i); } i++; } - if (level.gametype == GT_SIEGE && - ent->client->siegeClass != -1) - { //Then use the powers for this class. + if (level.gametype == GT_SIEGE && ent->client->siegeClass != -1) { // Then use the powers for this class. i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { ent->client->ps.fd.forcePowerLevel[i] = bgSiegeClasses[ent->client->siegeClass].forcePowerLevels[i]; - if (!ent->client->ps.fd.forcePowerLevel[i]) - { + if (!ent->client->ps.fd.forcePowerLevel[i]) { ent->client->ps.fd.forcePowersKnown &= ~(1 << i); - } - else - { + } else { ent->client->ps.fd.forcePowersKnown |= (1 << i); } i++; @@ -538,184 +507,135 @@ void WP_SpawnInitForcePowers( gentity_t *ent ) } } -extern qboolean BG_InKnockDown( int anim ); //bg_pmove.c +extern qboolean BG_InKnockDown(int anim); // bg_pmove.c -int ForcePowerUsableOn(gentity_t *attacker, gentity_t *other, forcePowers_t forcePower) -{ - if (other && other->client && BG_HasYsalamiri(level.gametype, &other->client->ps)) - { +int ForcePowerUsableOn(gentity_t *attacker, gentity_t *other, forcePowers_t forcePower) { + if (other && other->client && BG_HasYsalamiri(level.gametype, &other->client->ps)) { return 0; } - if (attacker && attacker->client && !BG_CanUseFPNow(level.gametype, &attacker->client->ps, level.time, forcePower)) - { + if (attacker && attacker->client && !BG_CanUseFPNow(level.gametype, &attacker->client->ps, level.time, forcePower)) { return 0; } - //Dueling fighters cannot use force powers on others, with the exception of force push when locked with each other - if (attacker && attacker->client && attacker->client->ps.duelInProgress) - { + // Dueling fighters cannot use force powers on others, with the exception of force push when locked with each other + if (attacker && attacker->client && attacker->client->ps.duelInProgress) { return 0; } - if (other && other->client && other->client->ps.duelInProgress) - { + if (other && other->client && other->client->ps.duelInProgress) { return 0; } - if (forcePower == FP_GRIP) - { - if (other && other->client && - (other->client->ps.fd.forcePowersActive & (1<client->forcePowerSoundDebounce < level.time) - { + if (forcePower == FP_GRIP) { + if (other && other->client && (other->client->ps.fd.forcePowersActive & (1 << FP_ABSORB))) { // don't allow gripping to begin with if they are absorbing + // play sound indicating that attack was absorbed + if (other->client->forcePowerSoundDebounce < level.time) { gentity_t *abSound = G_PreDefSound(other->client->ps.origin, PDSOUND_ABSORBHIT); abSound->s.trickedentindex = other->s.number; other->client->forcePowerSoundDebounce = level.time + 400; } return 0; - } - else if (other && other->client && - other->client->ps.weapon == WP_SABER && - BG_SaberInSpecial(other->client->ps.saberMove)) - { //don't grip person while they are in a special or some really bad things can happen. + } else if (other && other->client && other->client->ps.weapon == WP_SABER && + BG_SaberInSpecial(other->client->ps.saberMove)) { // don't grip person while they are in a special or some really bad things can happen. return 0; } } - if (other && other->client && - (forcePower == FP_PUSH || - forcePower == FP_PULL)) - { - if (BG_InKnockDown(other->client->ps.legsAnim)) - { + if (other && other->client && (forcePower == FP_PUSH || forcePower == FP_PULL)) { + if (BG_InKnockDown(other->client->ps.legsAnim)) { return 0; } } - if (other && other->client && other->s.eType == ET_NPC && - other->s.NPC_class == CLASS_VEHICLE) - { //can't use the force on vehicles.. except lightning - if (forcePower == FP_LIGHTNING) - { + if (other && other->client && other->s.eType == ET_NPC && other->s.NPC_class == CLASS_VEHICLE) { // can't use the force on vehicles.. except lightning + if (forcePower == FP_LIGHTNING) { return 1; - } - else - { + } else { return 0; } } - if (other && other->client && other->s.eType == ET_NPC && - level.gametype == GT_SIEGE) - { //can't use powers at all on npc's normally in siege... + if (other && other->client && other->s.eType == ET_NPC && level.gametype == GT_SIEGE) { // can't use powers at all on npc's normally in siege... return 0; } return 1; } -qboolean WP_ForcePowerAvailable( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ - int drain = overrideAmt ? overrideAmt : - forcePowerNeeded[self->client->ps.fd.forcePowerLevel[forcePower]][forcePower]; +qboolean WP_ForcePowerAvailable(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { + int drain = overrideAmt ? overrideAmt : forcePowerNeeded[self->client->ps.fd.forcePowerLevel[forcePower]][forcePower]; - if (self->client->ps.fd.forcePowersActive & (1 << forcePower)) - { //we're probably going to deactivate it.. + if (self->client->ps.fd.forcePowersActive & (1 << forcePower)) { // we're probably going to deactivate it.. return qtrue; } - if ( forcePower == FP_LEVITATION ) - { + if (forcePower == FP_LEVITATION) { return qtrue; } - if ( !drain ) - { + if (!drain) { return qtrue; } - if ((forcePower == FP_DRAIN || forcePower == FP_LIGHTNING) && - self->client->ps.fd.forcePower >= 25) - { //it's ok then, drain/lightning are actually duration + if ((forcePower == FP_DRAIN || forcePower == FP_LIGHTNING) && self->client->ps.fd.forcePower >= 25) { // it's ok then, drain/lightning are actually duration return qtrue; } - if ( self->client->ps.fd.forcePower < drain ) - { + if (self->client->ps.fd.forcePower < drain) { return qfalse; } return qtrue; } -qboolean WP_ForcePowerInUse( gentity_t *self, forcePowers_t forcePower ) -{ - if ( (self->client->ps.fd.forcePowersActive & ( 1 << forcePower )) ) - {//already using this power +qboolean WP_ForcePowerInUse(gentity_t *self, forcePowers_t forcePower) { + if ((self->client->ps.fd.forcePowersActive & (1 << forcePower))) { // already using this power return qtrue; } return qfalse; } -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ) -{ - if (BG_HasYsalamiri(level.gametype, &self->client->ps)) - { +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower) { + if (BG_HasYsalamiri(level.gametype, &self->client->ps)) { return qfalse; } - if (self->health <= 0 || self->client->ps.stats[STAT_HEALTH] <= 0 || - (self->client->ps.eFlags & EF_DEAD)) - { + if (self->health <= 0 || self->client->ps.stats[STAT_HEALTH] <= 0 || (self->client->ps.eFlags & EF_DEAD)) { return qfalse; } - if (self->client->ps.pm_flags & PMF_FOLLOW) - { //specs can't use powers through people + if (self->client->ps.pm_flags & PMF_FOLLOW) { // specs can't use powers through people return qfalse; } - if (self->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (self->client->sess.sessionTeam == TEAM_SPECTATOR) { return qfalse; } - if (self->client->tempSpectate >= level.time) - { + if (self->client->tempSpectate >= level.time) { return qfalse; } - if (!BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, forcePower)) - { + if (!BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, forcePower)) { return qfalse; } - if ( !(self->client->ps.fd.forcePowersKnown & ( 1 << forcePower )) ) - {//don't know this power + if (!(self->client->ps.fd.forcePowersKnown & (1 << forcePower))) { // don't know this power return qfalse; } - if ( (self->client->ps.fd.forcePowersActive & ( 1 << forcePower )) ) - {//already using this power - if (forcePower != FP_LEVITATION) - { + if ((self->client->ps.fd.forcePowersActive & (1 << forcePower))) { // already using this power + if (forcePower != FP_LEVITATION) { return qfalse; } } - if (forcePower == FP_LEVITATION && self->client->fjDidJump) - { + if (forcePower == FP_LEVITATION && self->client->fjDidJump) { return qfalse; } - if (!self->client->ps.fd.forcePowerLevel[forcePower]) - { + if (!self->client->ps.fd.forcePowerLevel[forcePower]) { return qfalse; } - if ( g_debugMelee.integer ) - { - if ( (self->client->ps.pm_flags&PMF_STUCK_TO_WALL) ) - {//no offensive force powers when stuck to wall - switch ( forcePower ) - { + if (g_debugMelee.integer) { + if ((self->client->ps.pm_flags & PMF_STUCK_TO_WALL)) { // no offensive force powers when stuck to wall + switch (forcePower) { case FP_GRIP: case FP_LIGHTNING: case FP_DRAIN: @@ -730,14 +650,10 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ) } } - if ( !self->client->ps.saberHolstered ) - { - if ( (self->client->saber[0].saberFlags&SFL_TWO_HANDED) ) - { - if ( g_saberRestrictForce.integer ) - { - switch ( forcePower ) - { + if (!self->client->ps.saberHolstered) { + if ((self->client->saber[0].saberFlags & SFL_TWO_HANDED)) { + if (g_saberRestrictForce.integer) { + switch (forcePower) { case FP_PUSH: case FP_PULL: case FP_TELEPATHY: @@ -752,21 +668,16 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ) } } - if ( (self->client->saber[0].saberFlags&SFL_TWO_HANDED) - || self->client->saber[0].model[0] ) - {//this saber requires the use of two hands OR our other hand is using an active saber too - if ( (self->client->saber[0].forceRestrictions&(1<client->saber[0].saberFlags & SFL_TWO_HANDED) || + self->client->saber[0].model[0]) { // this saber requires the use of two hands OR our other hand is using an active saber too + if ((self->client->saber[0].forceRestrictions & (1 << forcePower))) { // this power is verboten when using this saber return qfalse; } } - if ( self->client->saber[0].model[0] ) - {//both sabers on - if ( g_saberRestrictForce.integer ) - { - switch ( forcePower ) - { + if (self->client->saber[0].model[0]) { // both sabers on + if (g_saberRestrictForce.integer) { + switch (forcePower) { case FP_PUSH: case FP_PULL: case FP_TELEPATHY: @@ -779,65 +690,52 @@ qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ) break; } } - if ( (self->client->saber[1].forceRestrictions&(1<client->saber[1].forceRestrictions & (1 << forcePower))) { // this power is verboten when using this saber return qfalse; } } } - return WP_ForcePowerAvailable( self, forcePower, 0 ); // OVERRIDEFIXME + return WP_ForcePowerAvailable(self, forcePower, 0); // OVERRIDEFIXME } -int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacker, int atPower, int atPowerLevel, int atForceSpent) -{ +int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacker, int atPower, int atPowerLevel, int atForceSpent) { int getLevel = 0; int addTot = 0; gentity_t *abSound; - if (atPower != FP_LIGHTNING && - atPower != FP_DRAIN && - atPower != FP_GRIP && - atPower != FP_PUSH && - atPower != FP_PULL) - { //Only these powers can be absorbed + if (atPower != FP_LIGHTNING && atPower != FP_DRAIN && atPower != FP_GRIP && atPower != FP_PUSH && atPower != FP_PULL) { // Only these powers can be absorbed return -1; } - if (!atdAbsLevel) - { //looks like attacker doesn't have any absorb power + if (!atdAbsLevel) { // looks like attacker doesn't have any absorb power return -1; } - if (!(attacked->client->ps.fd.forcePowersActive & (1 << FP_ABSORB))) - { //absorb is not active + if (!(attacked->client->ps.fd.forcePowersActive & (1 << FP_ABSORB))) { // absorb is not active return -1; } - //Subtract absorb power level from the offensive force power + // Subtract absorb power level from the offensive force power getLevel = atPowerLevel; getLevel -= atdAbsLevel; - if (getLevel < 0) - { + if (getLevel < 0) { getLevel = 0; } - //let the attacker absorb an amount of force used in this attack based on his level of absorb - addTot = (atForceSpent/3)*attacked->client->ps.fd.forcePowerLevel[FP_ABSORB]; + // let the attacker absorb an amount of force used in this attack based on his level of absorb + addTot = (atForceSpent / 3) * attacked->client->ps.fd.forcePowerLevel[FP_ABSORB]; - if (addTot < 1 && atForceSpent >= 1) - { + if (addTot < 1 && atForceSpent >= 1) { addTot = 1; } attacked->client->ps.fd.forcePower += addTot; - if (attacked->client->ps.fd.forcePower > attacked->client->ps.fd.forcePowerMax) - { + if (attacked->client->ps.fd.forcePower > attacked->client->ps.fd.forcePowerMax) { attacked->client->ps.fd.forcePower = attacked->client->ps.fd.forcePowerMax; } - //play sound indicating that attack was absorbed - if (attacked->client->forcePowerSoundDebounce < level.time) - { + // play sound indicating that attack was absorbed + if (attacked->client->forcePowerSoundDebounce < level.time) { abSound = G_PreDefSound(attacked->client->ps.origin, PDSOUND_ABSORBHIT); abSound->s.trickedentindex = attacked->s.number; @@ -847,87 +745,69 @@ int WP_AbsorbConversion(gentity_t *attacked, int atdAbsLevel, gentity_t *attacke return getLevel; } -void WP_ForcePowerRegenerate( gentity_t *self, int overrideAmt ) -{ //called on a regular interval to regenerate force power. - if ( !self->client ) - { +void WP_ForcePowerRegenerate(gentity_t *self, int overrideAmt) { // called on a regular interval to regenerate force power. + if (!self->client) { return; } - if ( overrideAmt ) - { //custom regen amount + if (overrideAmt) { // custom regen amount self->client->ps.fd.forcePower += overrideAmt; - } - else - { //otherwise, just 1 + } else { // otherwise, just 1 self->client->ps.fd.forcePower++; } - if ( self->client->ps.fd.forcePower > self->client->ps.fd.forcePowerMax ) - { //cap it off at the max (default 100) + if (self->client->ps.fd.forcePower > self->client->ps.fd.forcePowerMax) { // cap it off at the max (default 100) self->client->ps.fd.forcePower = self->client->ps.fd.forcePowerMax; } } -void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int overrideAmt ) -{ //activate the given force power - int duration = 0; +void WP_ForcePowerStart(gentity_t *self, forcePowers_t forcePower, int overrideAmt) { // activate the given force power + int duration = 0; qboolean hearable = qfalse; float hearDist = 0; - if (!WP_ForcePowerAvailable( self, forcePower, overrideAmt )) - { + if (!WP_ForcePowerAvailable(self, forcePower, overrideAmt)) { return; } - if ( BG_FullBodyTauntAnim( self->client->ps.legsAnim ) ) - {//stop taunt + if (BG_FullBodyTauntAnim(self->client->ps.legsAnim)) { // stop taunt self->client->ps.legsTimer = 0; } - if ( BG_FullBodyTauntAnim( self->client->ps.torsoAnim ) ) - {//stop taunt + if (BG_FullBodyTauntAnim(self->client->ps.torsoAnim)) { // stop taunt self->client->ps.torsoTimer = 0; } - //hearable and hearDist are merely for the benefit of bots, and not related to if a sound is actually played. - //If duration is set, the force power will assume to be timer-based. - switch( (int)forcePower ) - { + // hearable and hearDist are merely for the benefit of bots, and not related to if a sound is actually played. + // If duration is set, the force power will assume to be timer-based. + switch ((int)forcePower) { case FP_HEAL: hearable = qtrue; hearDist = 256; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_LEVITATION: hearable = qtrue; hearDist = 256; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_SPEED: hearable = qtrue; hearDist = 256; - if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_1) { duration = 10000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_2) { duration = 15000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SPEED] == FORCE_LEVEL_3) { duration = 20000; - } - else //shouldn't get here + } else // shouldn't get here { break; } - if (overrideAmt) - { + if (overrideAmt) { duration = overrideAmt; } - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_PUSH: hearable = qtrue; @@ -940,29 +820,23 @@ void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int override case FP_TELEPATHY: hearable = qtrue; hearDist = 256; - if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_1) { duration = 20000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_2) { duration = 25000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_3) { duration = 30000; - } - else //shouldn't get here + } else // shouldn't get here { break; } - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_GRIP: hearable = qtrue; hearDist = 256; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); self->client->ps.powerups[PW_DISINT_4] = level.time + 60000; break; case FP_LIGHTNING: @@ -970,82 +844,70 @@ void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int override hearDist = 512; duration = overrideAmt; overrideAmt = 0; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); self->client->ps.activeForcePass = self->client->ps.fd.forcePowerLevel[FP_LIGHTNING]; break; case FP_RAGE: hearable = qtrue; hearDist = 256; - if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) { duration = 8000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) { duration = 14000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) { duration = 20000; - } - else //shouldn't get here + } else // shouldn't get here { break; } - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_PROTECT: hearable = qtrue; hearDist = 256; duration = 20000; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_ABSORB: hearable = qtrue; hearDist = 256; duration = 20000; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_TEAM_HEAL: hearable = qtrue; hearDist = 256; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_TEAM_FORCE: hearable = qtrue; hearDist = 256; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_DRAIN: hearable = qtrue; hearDist = 256; duration = overrideAmt; overrideAmt = 0; - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); - //self->client->ps.activeForcePass = self->client->ps.fd.forcePowerLevel[FP_DRAIN]; + self->client->ps.fd.forcePowersActive |= (1 << forcePower); + // self->client->ps.activeForcePass = self->client->ps.fd.forcePowerLevel[FP_DRAIN]; break; case FP_SEE: hearable = qtrue; hearDist = 256; - if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_1) { duration = 10000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_2) { duration = 20000; - } - else if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SEE] == FORCE_LEVEL_3) { duration = 30000; - } - else //shouldn't get here + } else // shouldn't get here { break; } - self->client->ps.fd.forcePowersActive |= ( 1 << forcePower ); + self->client->ps.fd.forcePowersActive |= (1 << forcePower); break; case FP_SABER_OFFENSE: break; @@ -1057,79 +919,60 @@ void WP_ForcePowerStart( gentity_t *self, forcePowers_t forcePower, int override break; } - if ( duration ) - { + if (duration) { self->client->ps.fd.forcePowerDuration[forcePower] = level.time + duration; - } - else - { + } else { self->client->ps.fd.forcePowerDuration[forcePower] = 0; } - if (hearable) - { + if (hearable) { self->client->ps.otherSoundLen = hearDist; self->client->ps.otherSoundTime = level.time + 100; } self->client->ps.fd.forcePowerDebounce[forcePower] = 0; - if ((int)forcePower == FP_SPEED && overrideAmt) - { - BG_ForcePowerDrain( &self->client->ps, forcePower, overrideAmt*0.025 ); - } - else if ((int)forcePower != FP_GRIP && (int)forcePower != FP_DRAIN) - { //grip and drain drain as damage is done - BG_ForcePowerDrain( &self->client->ps, forcePower, overrideAmt ); + if ((int)forcePower == FP_SPEED && overrideAmt) { + BG_ForcePowerDrain(&self->client->ps, forcePower, overrideAmt * 0.025); + } else if ((int)forcePower != FP_GRIP && (int)forcePower != FP_DRAIN) { // grip and drain drain as damage is done + BG_ForcePowerDrain(&self->client->ps, forcePower, overrideAmt); } } -void ForceHeal( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceHeal(gentity_t *self) { + if (self->health <= 0) { return; } - if ( !WP_ForcePowerUsable( self, FP_HEAL ) ) - { + if (!WP_ForcePowerUsable(self, FP_HEAL)) { return; } - if ( self->health >= self->client->ps.stats[STAT_MAX_HEALTH]) - { + if (self->health >= self->client->ps.stats[STAT_MAX_HEALTH]) { return; } - if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_3) - { - self->health += 25; //This was 50, but that angered the Balance God. + if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_3) { + self->health += 25; // This was 50, but that angered the Balance God. - if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) - { + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { self->health = self->client->ps.stats[STAT_MAX_HEALTH]; } - BG_ForcePowerDrain( &self->client->ps, FP_HEAL, 0 ); - } - else if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_2) - { + BG_ForcePowerDrain(&self->client->ps, FP_HEAL, 0); + } else if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_2) { self->health += 10; - if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) - { + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { self->health = self->client->ps.stats[STAT_MAX_HEALTH]; } - BG_ForcePowerDrain( &self->client->ps, FP_HEAL, 0 ); - } - else - { + BG_ForcePowerDrain(&self->client->ps, FP_HEAL, 0); + } else { self->health += 5; - if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) - { + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { self->health = self->client->ps.stats[STAT_MAX_HEALTH]; } - BG_ForcePowerDrain( &self->client->ps, FP_HEAL, 0 ); + BG_ForcePowerDrain(&self->client->ps, FP_HEAL, 0); } /* else @@ -1137,38 +980,28 @@ void ForceHeal( gentity_t *self ) WP_ForcePowerStart( self, FP_HEAL, 0 ); } */ - //NOTE: Decided to make all levels instant. + // NOTE: Decided to make all levels instant. - G_Sound( self, CHAN_ITEM, G_SoundIndex("sound/weapons/force/heal.wav") ); + G_Sound(self, CHAN_ITEM, G_SoundIndex("sound/weapons/force/heal.wav")); } -void WP_AddToClientBitflags(gentity_t *ent, int entNum) -{ - if (!ent) - { +void WP_AddToClientBitflags(gentity_t *ent, int entNum) { + if (!ent) { return; } - if (entNum > 47) - { - ent->s.trickedentindex4 |= (1 << (entNum-48)); - } - else if (entNum > 31) - { - ent->s.trickedentindex3 |= (1 << (entNum-32)); - } - else if (entNum > 15) - { - ent->s.trickedentindex2 |= (1 << (entNum-16)); - } - else - { + if (entNum > 47) { + ent->s.trickedentindex4 |= (1 << (entNum - 48)); + } else if (entNum > 31) { + ent->s.trickedentindex3 |= (1 << (entNum - 32)); + } else if (entNum > 15) { + ent->s.trickedentindex2 |= (1 << (entNum - 16)); + } else { ent->s.trickedentindex |= (1 << entNum); } } -void ForceTeamHeal( gentity_t *self ) -{ +void ForceTeamHeal(gentity_t *self) { float radius = 256; int i = 0; gentity_t *ent; @@ -1178,41 +1011,34 @@ void ForceTeamHeal( gentity_t *self ) int healthadd = 0; gentity_t *te = NULL; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !WP_ForcePowerUsable( self, FP_TEAM_HEAL ) ) - { + if (!WP_ForcePowerUsable(self, FP_TEAM_HEAL)) { return; } - if (self->client->ps.fd.forcePowerDebounce[FP_TEAM_HEAL] >= level.time) - { + if (self->client->ps.fd.forcePowerDebounce[FP_TEAM_HEAL] >= level.time) { return; } - if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_2) - { + if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_2) { radius *= 1.5; } - if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_3) - { + if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_3) { radius *= 2; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && self != ent && OnSameTeam(self, ent) && ent->client->ps.stats[STAT_HEALTH] < ent->client->ps.stats[STAT_MAX_HEALTH] && ent->client->ps.stats[STAT_HEALTH] > 0 && ForcePowerUsableOn(self, ent, FP_TEAM_HEAL) && - trap->InPVS(self->client->ps.origin, ent->client->ps.origin)) - { + if (ent && ent->client && self != ent && OnSameTeam(self, ent) && ent->client->ps.stats[STAT_HEALTH] < ent->client->ps.stats[STAT_MAX_HEALTH] && + ent->client->ps.stats[STAT_HEALTH] > 0 && ForcePowerUsableOn(self, ent, FP_TEAM_HEAL) && + trap->InPVS(self->client->ps.origin, ent->client->ps.origin)) { VectorSubtract(self->client->ps.origin, ent->client->ps.origin, a); - if (VectorLength(a) <= radius) - { + if (VectorLength(a) <= radius) { pl[numpl] = i; numpl++; } @@ -1221,59 +1047,47 @@ void ForceTeamHeal( gentity_t *self ) i++; } - if (numpl < 1) - { + if (numpl < 1) { return; } - if (numpl == 1) - { + if (numpl == 1) { healthadd = 50; - } - else if (numpl == 2) - { + } else if (numpl == 2) { healthadd = 33; - } - else - { + } else { healthadd = 25; } self->client->ps.fd.forcePowerDebounce[FP_TEAM_HEAL] = level.time + 2000; i = 0; - while (i < numpl) - { - if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > 0 && - g_entities[pl[i]].health > 0) - { + while (i < numpl) { + if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > 0 && g_entities[pl[i]].health > 0) { g_entities[pl[i]].client->ps.stats[STAT_HEALTH] += healthadd; - if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > g_entities[pl[i]].client->ps.stats[STAT_MAX_HEALTH]) - { + if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > g_entities[pl[i]].client->ps.stats[STAT_MAX_HEALTH]) { g_entities[pl[i]].client->ps.stats[STAT_HEALTH] = g_entities[pl[i]].client->ps.stats[STAT_MAX_HEALTH]; } g_entities[pl[i]].health = g_entities[pl[i]].client->ps.stats[STAT_HEALTH]; - //At this point we know we got one, so add him into the collective event client bitflag - if (!te) - { - te = G_TempEntity( self->client->ps.origin, EV_TEAM_POWER); - te->s.eventParm = 1; //eventParm 1 is heal, eventParm 2 is force regen + // At this point we know we got one, so add him into the collective event client bitflag + if (!te) { + te = G_TempEntity(self->client->ps.origin, EV_TEAM_POWER); + te->s.eventParm = 1; // eventParm 1 is heal, eventParm 2 is force regen - //since we had an extra check above, do the drain now because we got at least one guy - BG_ForcePowerDrain( &self->client->ps, FP_TEAM_HEAL, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL] ); + // since we had an extra check above, do the drain now because we got at least one guy + BG_ForcePowerDrain(&self->client->ps, FP_TEAM_HEAL, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL]); } WP_AddToClientBitflags(te, pl[i]); - //Now cramming it all into one event.. doing this many g_sound events at once was a Bad Thing. + // Now cramming it all into one event.. doing this many g_sound events at once was a Bad Thing. } i++; } } -void ForceTeamForceReplenish( gentity_t *self ) -{ +void ForceTeamForceReplenish(gentity_t *self) { float radius = 256; int i = 0; gentity_t *ent; @@ -1283,41 +1097,33 @@ void ForceTeamForceReplenish( gentity_t *self ) int poweradd = 0; gentity_t *te = NULL; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( !WP_ForcePowerUsable( self, FP_TEAM_FORCE ) ) - { + if (!WP_ForcePowerUsable(self, FP_TEAM_FORCE)) { return; } - if (self->client->ps.fd.forcePowerDebounce[FP_TEAM_FORCE] >= level.time) - { + if (self->client->ps.fd.forcePowerDebounce[FP_TEAM_FORCE] >= level.time) { return; } - if (self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE] == FORCE_LEVEL_2) - { + if (self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE] == FORCE_LEVEL_2) { radius *= 1.5; } - if (self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE] == FORCE_LEVEL_3) - { + if (self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE] == FORCE_LEVEL_3) { radius *= 2; } - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; if (ent && ent->client && self != ent && OnSameTeam(self, ent) && ent->client->ps.fd.forcePower < 100 && ForcePowerUsableOn(self, ent, FP_TEAM_FORCE) && - trap->InPVS(self->client->ps.origin, ent->client->ps.origin)) - { + trap->InPVS(self->client->ps.origin, ent->client->ps.origin)) { VectorSubtract(self->client->ps.origin, ent->client->ps.origin, a); - if (VectorLength(a) <= radius) - { + if (VectorLength(a) <= radius) { pl[numpl] = i; numpl++; } @@ -1326,106 +1132,83 @@ void ForceTeamForceReplenish( gentity_t *self ) i++; } - if (numpl < 1) - { + if (numpl < 1) { return; } - if (numpl == 1) - { + if (numpl == 1) { poweradd = 50; - } - else if (numpl == 2) - { + } else if (numpl == 2) { poweradd = 33; - } - else - { + } else { poweradd = 25; } self->client->ps.fd.forcePowerDebounce[FP_TEAM_FORCE] = level.time + 2000; - BG_ForcePowerDrain( &self->client->ps, FP_TEAM_FORCE, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE] ); + BG_ForcePowerDrain(&self->client->ps, FP_TEAM_FORCE, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_TEAM_FORCE]][FP_TEAM_FORCE]); i = 0; - while (i < numpl) - { + while (i < numpl) { g_entities[pl[i]].client->ps.fd.forcePower += poweradd; - if (g_entities[pl[i]].client->ps.fd.forcePower > g_entities[pl[i]].client->ps.fd.forcePowerMax) - { + if (g_entities[pl[i]].client->ps.fd.forcePower > g_entities[pl[i]].client->ps.fd.forcePowerMax) { g_entities[pl[i]].client->ps.fd.forcePower = g_entities[pl[i]].client->ps.fd.forcePowerMax; } - //At this point we know we got one, so add him into the collective event client bitflag - if (!te) - { - te = G_TempEntity( self->client->ps.origin, EV_TEAM_POWER); - te->s.eventParm = 2; //eventParm 1 is heal, eventParm 2 is force regen + // At this point we know we got one, so add him into the collective event client bitflag + if (!te) { + te = G_TempEntity(self->client->ps.origin, EV_TEAM_POWER); + te->s.eventParm = 2; // eventParm 1 is heal, eventParm 2 is force regen } WP_AddToClientBitflags(te, pl[i]); - //Now cramming it all into one event.. doing this many g_sound events at once was a Bad Thing. + // Now cramming it all into one event.. doing this many g_sound events at once was a Bad Thing. i++; } } -void ForceGrip( gentity_t *self ) -{ +void ForceGrip(gentity_t *self) { trace_t tr; vec3_t tfrom, tto, fwd; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return; } - if (self->client->ps.fd.forceGripUseTime > level.time) - { + if (self->client->ps.fd.forceGripUseTime > level.time) { return; } - if ( !WP_ForcePowerUsable( self, FP_GRIP ) ) - { + if (!WP_ForcePowerUsable(self, FP_GRIP)) { return; } VectorCopy(self->client->ps.origin, tfrom); tfrom[2] += self->client->ps.viewheight; AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); - tto[0] = tfrom[0] + fwd[0]*MAX_GRIP_DISTANCE; - tto[1] = tfrom[1] + fwd[1]*MAX_GRIP_DISTANCE; - tto[2] = tfrom[2] + fwd[2]*MAX_GRIP_DISTANCE; + tto[0] = tfrom[0] + fwd[0] * MAX_GRIP_DISTANCE; + tto[1] = tfrom[1] + fwd[1] * MAX_GRIP_DISTANCE; + tto[2] = tfrom[2] + fwd[2] * MAX_GRIP_DISTANCE; trap->Trace(&tr, tfrom, NULL, NULL, tto, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if ( tr.fraction != 1.0 && - tr.entityNum != ENTITYNUM_NONE && - g_entities[tr.entityNum].client && - !g_entities[tr.entityNum].client->ps.fd.forceGripCripple && - g_entities[tr.entityNum].client->ps.fd.forceGripBeingGripped < level.time && - ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_GRIP) && - (g_friendlyFire.integer || !OnSameTeam(self, &g_entities[tr.entityNum])) ) //don't grip someone who's still crippled + if (tr.fraction != 1.0 && tr.entityNum != ENTITYNUM_NONE && g_entities[tr.entityNum].client && !g_entities[tr.entityNum].client->ps.fd.forceGripCripple && + g_entities[tr.entityNum].client->ps.fd.forceGripBeingGripped < level.time && ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_GRIP) && + (g_friendlyFire.integer || !OnSameTeam(self, &g_entities[tr.entityNum]))) // don't grip someone who's still crippled { - if (g_entities[tr.entityNum].s.number < MAX_CLIENTS && g_entities[tr.entityNum].client->ps.m_iVehicleNum) - { //a player on a vehicle + if (g_entities[tr.entityNum].s.number < MAX_CLIENTS && g_entities[tr.entityNum].client->ps.m_iVehicleNum) { // a player on a vehicle gentity_t *vehEnt = &g_entities[g_entities[tr.entityNum].client->ps.m_iVehicleNum]; - if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) - { - if (vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || - vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) - { //push the guy off + if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) { + if (vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { // push the guy off vehEnt->m_pVehicle->m_pVehicleInfo->Eject(vehEnt->m_pVehicle, (bgEntity_t *)&g_entities[tr.entityNum], qfalse); } } @@ -1436,316 +1219,252 @@ void ForceGrip( gentity_t *self ) self->client->ps.forceHandExtend = HANDEXTEND_FORCE_HOLD; self->client->ps.forceHandExtendTime = level.time + 5000; - } - else - { + } else { self->client->ps.fd.forceGripEntityNum = ENTITYNUM_NONE; return; } } -void ForceSpeed( gentity_t *self, int forceDuration ) -{ - if ( self->health <= 0 ) - { +void ForceSpeed(gentity_t *self, int forceDuration) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) ) - { - WP_ForcePowerStop( self, FP_SPEED ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED))) { + WP_ForcePowerStop(self, FP_SPEED); return; } - if ( !WP_ForcePowerUsable( self, FP_SPEED ) ) - { + if (!WP_ForcePowerUsable(self, FP_SPEED)) { return; } - if ( self->client->holdingObjectiveItem >= MAX_CLIENTS - && self->client->holdingObjectiveItem < ENTITYNUM_WORLD ) - {//holding Siege item - if ( g_entities[self->client->holdingObjectiveItem].genericValue15 ) - {//disables force powers + if (self->client->holdingObjectiveItem >= MAX_CLIENTS && self->client->holdingObjectiveItem < ENTITYNUM_WORLD) { // holding Siege item + if (g_entities[self->client->holdingObjectiveItem].genericValue15) { // disables force powers return; } } self->client->ps.forceAllowDeactivateTime = level.time + 1500; - WP_ForcePowerStart( self, FP_SPEED, forceDuration ); - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/force/speed.wav") ); - G_Sound( self, TRACK_CHANNEL_2, speedLoopSound ); + WP_ForcePowerStart(self, FP_SPEED, forceDuration); + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/speed.wav")); + G_Sound(self, TRACK_CHANNEL_2, speedLoopSound); } -void ForceSeeing( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceSeeing(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_SEE)) ) - { - WP_ForcePowerStop( self, FP_SEE ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_SEE))) { + WP_ForcePowerStop(self, FP_SEE); return; } - if ( !WP_ForcePowerUsable( self, FP_SEE ) ) - { + if (!WP_ForcePowerUsable(self, FP_SEE)) { return; } self->client->ps.forceAllowDeactivateTime = level.time + 1500; - WP_ForcePowerStart( self, FP_SEE, 0 ); + WP_ForcePowerStart(self, FP_SEE, 0); - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/see.wav") ); - G_Sound( self, TRACK_CHANNEL_5, seeLoopSound ); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/see.wav")); + G_Sound(self, TRACK_CHANNEL_5, seeLoopSound); } -void ForceProtect( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceProtect(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT)) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT))) { + WP_ForcePowerStop(self, FP_PROTECT); return; } - if ( !WP_ForcePowerUsable( self, FP_PROTECT ) ) - { + if (!WP_ForcePowerUsable(self, FP_PROTECT)) { return; } // Make sure to turn off Force Rage and Force Absorb. - if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) { + WP_ForcePowerStop(self, FP_RAGE); } - if (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); } self->client->ps.forceAllowDeactivateTime = level.time + 1500; - WP_ForcePowerStart( self, FP_PROTECT, 0 ); + WP_ForcePowerStart(self, FP_PROTECT, 0); G_PreDefSound(self->client->ps.origin, PDSOUND_PROTECT); - G_Sound( self, TRACK_CHANNEL_3, protectLoopSound ); + G_Sound(self, TRACK_CHANNEL_3, protectLoopSound); } -void ForceAbsorb( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceAbsorb(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB)) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB))) { + WP_ForcePowerStop(self, FP_ABSORB); return; } - if ( !WP_ForcePowerUsable( self, FP_ABSORB ) ) - { + if (!WP_ForcePowerUsable(self, FP_ABSORB)) { return; } // Make sure to turn off Force Rage and Force Protection. - if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) { + WP_ForcePowerStop(self, FP_RAGE); } - if (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); } self->client->ps.forceAllowDeactivateTime = level.time + 1500; - WP_ForcePowerStart( self, FP_ABSORB, 0 ); + WP_ForcePowerStart(self, FP_ABSORB, 0); G_PreDefSound(self->client->ps.origin, PDSOUND_ABSORB); - G_Sound( self, TRACK_CHANNEL_3, absorbLoopSound ); + G_Sound(self, TRACK_CHANNEL_3, absorbLoopSound); } -void ForceRage( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceRage(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) ) - { - WP_ForcePowerStop( self, FP_RAGE ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE))) { + WP_ForcePowerStop(self, FP_RAGE); return; } - if ( !WP_ForcePowerUsable( self, FP_RAGE ) ) - { + if (!WP_ForcePowerUsable(self, FP_RAGE)) { return; } - if (self->client->ps.fd.forceRageRecoveryTime >= level.time) - { + if (self->client->ps.fd.forceRageRecoveryTime >= level.time) { return; } - if (self->health < 10) - { + if (self->health < 10) { return; } // Make sure to turn off Force Protection and Force Absorb. - if (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT) ) - { - WP_ForcePowerStop( self, FP_PROTECT ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_PROTECT)) { + WP_ForcePowerStop(self, FP_PROTECT); } - if (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB) ) - { - WP_ForcePowerStop( self, FP_ABSORB ); + if (self->client->ps.fd.forcePowersActive & (1 << FP_ABSORB)) { + WP_ForcePowerStop(self, FP_ABSORB); } self->client->ps.forceAllowDeactivateTime = level.time + 1500; - WP_ForcePowerStart( self, FP_RAGE, 0 ); + WP_ForcePowerStart(self, FP_RAGE, 0); - G_Sound( self, TRACK_CHANNEL_4, G_SoundIndex("sound/weapons/force/rage.wav") ); - G_Sound( self, TRACK_CHANNEL_3, rageLoopSound ); + G_Sound(self, TRACK_CHANNEL_4, G_SoundIndex("sound/weapons/force/rage.wav")); + G_Sound(self, TRACK_CHANNEL_3, rageLoopSound); } -void ForceLightning( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceLightning(gentity_t *self) { + if (self->health <= 0) { return; } - if ( self->client->ps.fd.forcePower < 25 || !WP_ForcePowerUsable( self, FP_LIGHTNING ) ) - { + if (self->client->ps.fd.forcePower < 25 || !WP_ForcePowerUsable(self, FP_LIGHTNING)) { return; } - if ( self->client->ps.fd.forcePowerDebounce[FP_LIGHTNING] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.fd.forcePowerDebounce[FP_LIGHTNING] > level.time) { // stops it while using it and also after using it, up to 3 second delay return; } - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return; } // fix: rocket lock bug BG_ClearRocketLock(&self->client->ps); - //Shoot lightning from hand - //using grip anim now, to extend the burst time + // Shoot lightning from hand + // using grip anim now, to extend the burst time self->client->ps.forceHandExtend = HANDEXTEND_FORCE_HOLD; self->client->ps.forceHandExtendTime = level.time + 20000; - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/force/lightning") ); + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/lightning")); - WP_ForcePowerStart( self, FP_LIGHTNING, 500 ); + WP_ForcePowerStart(self, FP_LIGHTNING, 500); } -void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint ) -{ +void ForceLightningDamage(gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint) { self->client->dangerTime = level.time; self->client->ps.eFlags &= ~EF_INVULNERABLE; self->client->invulnerableTimer = 0; - if ( traceEnt && traceEnt->takedamage ) - { - if (!traceEnt->client && traceEnt->s.eType == ET_NPC) - { //g2animent - if (traceEnt->s.genericenemyindex < level.time) - { + if (traceEnt && traceEnt->takedamage) { + if (!traceEnt->client && traceEnt->s.eType == ET_NPC) { // g2animent + if (traceEnt->s.genericenemyindex < level.time) { traceEnt->s.genericenemyindex = level.time + 2000; } } - if ( traceEnt->client ) - {//an enemy or object - if (traceEnt->client->noLightningTime >= level.time) - { //give them power and don't hurt them. + if (traceEnt->client) { // an enemy or object + if (traceEnt->client->noLightningTime >= level.time) { // give them power and don't hurt them. traceEnt->client->ps.fd.forcePower++; - if (traceEnt->client->ps.fd.forcePower > traceEnt->client->ps.fd.forcePowerMax) - { + if (traceEnt->client->ps.fd.forcePower > traceEnt->client->ps.fd.forcePowerMax) { traceEnt->client->ps.fd.forcePower = traceEnt->client->ps.fd.forcePowerMax; } return; } - if (ForcePowerUsableOn(self, traceEnt, FP_LIGHTNING)) - { - int dmg = Q_irand(1,2); //Q_irand( 1, 3 ); + if (ForcePowerUsableOn(self, traceEnt, FP_LIGHTNING)) { + int dmg = Q_irand(1, 2); // Q_irand( 1, 3 ); int modPowerLevel = -1; - if (traceEnt->client) - { - modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_LIGHTNING, self->client->ps.fd.forcePowerLevel[FP_LIGHTNING], 1); + if (traceEnt->client) { + modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_LIGHTNING, + self->client->ps.fd.forcePowerLevel[FP_LIGHTNING], 1); } - if (modPowerLevel != -1) - { - if (!modPowerLevel) - { + if (modPowerLevel != -1) { + if (!modPowerLevel) { dmg = 0; traceEnt->client->noLightningTime = level.time + 400; - } - else if (modPowerLevel == 1) - { + } else if (modPowerLevel == 1) { dmg = 1; traceEnt->client->noLightningTime = level.time + 300; - } - else if (modPowerLevel == 2) - { + } else if (modPowerLevel == 2) { dmg = 1; traceEnt->client->noLightningTime = level.time + 100; } } - if ( self->client->ps.weapon == WP_MELEE - && self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//2-handed lightning - //jackin' 'em up, Palpatine-style + if (self->client->ps.weapon == WP_MELEE && self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // 2-handed lightning + // jackin' 'em up, Palpatine-style dmg *= 2; } - if (dmg) - { - //rww - Shields can now absorb lightning too. - G_Damage( traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_DARK ); + if (dmg) { + // rww - Shields can now absorb lightning too. + G_Damage(traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_DARK); } - if ( traceEnt->client ) - { - if ( !Q_irand( 0, 2 ) ) - { - G_Sound( traceEnt, CHAN_BODY, G_SoundIndex( va("sound/weapons/force/lightninghit%i", Q_irand(1, 3) )) ); + if (traceEnt->client) { + if (!Q_irand(0, 2)) { + G_Sound(traceEnt, CHAN_BODY, G_SoundIndex(va("sound/weapons/force/lightninghit%i", Q_irand(1, 3)))); } - if (traceEnt->client->ps.electrifyTime < (level.time + 400)) - { //only update every 400ms to reduce bandwidth usage (as it is passing a 32-bit time value) + if (traceEnt->client->ps.electrifyTime < + (level.time + 400)) { // only update every 400ms to reduce bandwidth usage (as it is passing a 32-bit time value) traceEnt->client->ps.electrifyTime = level.time + 800; } - if ( traceEnt->client->ps.powerups[PW_CLOAKED] ) - {//disable cloak temporarily - Jedi_Decloak( traceEnt ); - traceEnt->client->cloakToggleTime = level.time + Q_irand( 3000, 10000 ); + if (traceEnt->client->ps.powerups[PW_CLOAKED]) { // disable cloak temporarily + Jedi_Decloak(traceEnt); + traceEnt->client->cloakToggleTime = level.time + Q_irand(3000, 10000); } } } @@ -1753,243 +1472,201 @@ void ForceLightningDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec } } -void ForceShootLightning( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; +void ForceShootLightning(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); - if ( self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2 ) - {//arc - vec3_t center, mins, maxs, dir, ent_org, size, v; - float radius = FORCE_LIGHTNING_RADIUS, dot, dist; - gentity_t *entityList[MAX_GENTITIES]; - int iEntityList[MAX_GENTITIES]; - int e, numListedEntities, i; + if (self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_2) { // arc + vec3_t center, mins, maxs, dir, ent_org, size, v; + float radius = FORCE_LIGHTNING_RADIUS, dot, dist; + gentity_t *entityList[MAX_GENTITIES]; + int iEntityList[MAX_GENTITIES]; + int e, numListedEntities, i; - VectorCopy( self->client->ps.origin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + VectorCopy(self->client->ps.origin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, iEntityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, iEntityList, MAX_GENTITIES); i = 0; - while (i < numListedEntities) - { + while (i < numListedEntities) { entityList[i] = &g_entities[iEntityList[i]]; i++; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { traceEnt = entityList[e]; - if ( !traceEnt ) + if (!traceEnt) continue; - if ( traceEnt == self ) + if (traceEnt == self) continue; - if ( traceEnt->r.ownerNum == self->s.number && traceEnt->s.weapon != WP_THERMAL )//can push your own thermals + if (traceEnt->r.ownerNum == self->s.number && traceEnt->s.weapon != WP_THERMAL) // can push your own thermals continue; - if ( !traceEnt->inuse ) + if (!traceEnt->inuse) continue; - if ( !traceEnt->takedamage ) + if (!traceEnt->takedamage) continue; - if ( traceEnt->health <= 0 )//no torturing corpses + if (traceEnt->health <= 0) // no torturing corpses continue; - if ( !g_friendlyFire.integer && OnSameTeam(self, traceEnt)) + if (!g_friendlyFire.integer && OnSameTeam(self, traceEnt)) continue; - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < traceEnt->r.absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < traceEnt->r.absmin[i]) { v[i] = traceEnt->r.absmin[i] - center[i]; - } else if ( center[i] > traceEnt->r.absmax[i] ) - { + } else if (center[i] > traceEnt->r.absmax[i]) { v[i] = center[i] - traceEnt->r.absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( traceEnt->r.absmax, traceEnt->r.absmin, size ); - VectorMA( traceEnt->r.absmin, 0.5, size, ent_org ); + VectorSubtract(traceEnt->r.absmax, traceEnt->r.absmin, size); + VectorMA(traceEnt->r.absmin, 0.5, size, ent_org); - //see if they're in front of me - //must be within the forward cone - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot = DotProduct( dir, forward )) < 0.5 ) + // see if they're in front of me + // must be within the forward cone + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot = DotProduct(dir, forward)) < 0.5) continue; - //must be close enough - dist = VectorLength( v ); - if ( dist >= radius ) - { + // must be close enough + dist = VectorLength(v); + if (dist >= radius) { continue; } - //in PVS? - if ( !traceEnt->r.bmodel && !trap->InPVS( ent_org, self->client->ps.origin ) ) - {//must be in PVS + // in PVS? + if (!traceEnt->r.bmodel && !trap->InPVS(ent_org, self->client->ps.origin)) { // must be in PVS continue; } - //Now check and see if we can actually hit it - trap->Trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number ) - {//must have clear LOS + // Now check and see if we can actually hit it + trap->Trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number) { // must have clear LOS continue; } // ok, we are within the radius, add us to the incoming list - ForceLightningDamage( self, traceEnt, dir, ent_org ); + ForceLightningDamage(self, traceEnt, dir, ent_org); } - } - else - {//trace-line - VectorMA( self->client->ps.origin, 2048, forward, end ); + } else { // trace-line + VectorMA(self->client->ps.origin, 2048, forward, end); - trap->Trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - { + trap->Trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { return; } traceEnt = &g_entities[tr.entityNum]; - ForceLightningDamage( self, traceEnt, forward, tr.endpos ); + ForceLightningDamage(self, traceEnt, forward, tr.endpos); } } -void ForceDrain( gentity_t *self ) -{ - if ( self->health <= 0 ) - { +void ForceDrain(gentity_t *self) { + if (self->health <= 0) { return; } - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return; } - if ( self->client->ps.fd.forcePower < 25 || !WP_ForcePowerUsable( self, FP_DRAIN ) ) - { + if (self->client->ps.fd.forcePower < 25 || !WP_ForcePowerUsable(self, FP_DRAIN)) { return; } - if ( self->client->ps.fd.forcePowerDebounce[FP_DRAIN] > level.time ) - {//stops it while using it and also after using it, up to 3 second delay + if (self->client->ps.fd.forcePowerDebounce[FP_DRAIN] > level.time) { // stops it while using it and also after using it, up to 3 second delay return; } -// self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; -// self->client->ps.forceHandExtendTime = level.time + 1000; + // self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; + // self->client->ps.forceHandExtendTime = level.time + 1000; self->client->ps.forceHandExtend = HANDEXTEND_FORCE_HOLD; self->client->ps.forceHandExtendTime = level.time + 20000; - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/force/drain.wav") ); + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/drain.wav")); - WP_ForcePowerStart( self, FP_DRAIN, 500 ); + WP_ForcePowerStart(self, FP_DRAIN, 500); } -void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint ) -{ +void ForceDrainDamage(gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t impactPoint) { gentity_t *tent; self->client->dangerTime = level.time; self->client->ps.eFlags &= ~EF_INVULNERABLE; self->client->invulnerableTimer = 0; - if ( traceEnt && traceEnt->takedamage ) - { - if ( traceEnt->client && (!OnSameTeam(self, traceEnt) || g_friendlyFire.integer) && self->client->ps.fd.forceDrainTime < level.time && traceEnt->client->ps.fd.forcePower ) - {//an enemy or object - if (!traceEnt->client && traceEnt->s.eType == ET_NPC) - { //g2animent - if (traceEnt->s.genericenemyindex < level.time) - { + if (traceEnt && traceEnt->takedamage) { + if (traceEnt->client && (!OnSameTeam(self, traceEnt) || g_friendlyFire.integer) && self->client->ps.fd.forceDrainTime < level.time && + traceEnt->client->ps.fd.forcePower) { // an enemy or object + if (!traceEnt->client && traceEnt->s.eType == ET_NPC) { // g2animent + if (traceEnt->s.genericenemyindex < level.time) { traceEnt->s.genericenemyindex = level.time + 2000; } } - if (ForcePowerUsableOn(self, traceEnt, FP_DRAIN)) - { + if (ForcePowerUsableOn(self, traceEnt, FP_DRAIN)) { int modPowerLevel = -1; - int dmg = 0; //Q_irand( 1, 3 ); - if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_1) - { - dmg = 2; //because it's one-shot - } - else if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_2) - { + int dmg = 0; // Q_irand( 1, 3 ); + if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_1) { + dmg = 2; // because it's one-shot + } else if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_2) { dmg = 3; - } - else if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_3) { dmg = 4; } - if (traceEnt->client) - { - modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, self->client->ps.fd.forcePowerLevel[FP_DRAIN], 1); + if (traceEnt->client) { + modPowerLevel = WP_AbsorbConversion(traceEnt, traceEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_DRAIN, + self->client->ps.fd.forcePowerLevel[FP_DRAIN], 1); } - if (modPowerLevel != -1) - { - if (!modPowerLevel) - { + if (modPowerLevel != -1) { + if (!modPowerLevel) { dmg = 0; - } - else if (modPowerLevel == 1) - { + } else if (modPowerLevel == 1) { dmg = 1; - } - else if (modPowerLevel == 2) - { + } else if (modPowerLevel == 2) { dmg = 2; } } - //G_Damage( traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_DARK ); + // G_Damage( traceEnt, self, self, dir, impactPoint, dmg, 0, MOD_FORCE_DARK ); - if (dmg) - { + if (dmg) { traceEnt->client->ps.fd.forcePower -= (dmg); } - if (traceEnt->client->ps.fd.forcePower < 0) - { + if (traceEnt->client->ps.fd.forcePower < 0) { traceEnt->client->ps.fd.forcePower = 0; } - if (self->client->ps.stats[STAT_HEALTH] < self->client->ps.stats[STAT_MAX_HEALTH] && - self->health > 0 && self->client->ps.stats[STAT_HEALTH] > 0) - { + if (self->client->ps.stats[STAT_HEALTH] < self->client->ps.stats[STAT_MAX_HEALTH] && self->health > 0 && + self->client->ps.stats[STAT_HEALTH] > 0) { self->health += dmg; - if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) - { + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { self->health = self->client->ps.stats[STAT_MAX_HEALTH]; } self->client->ps.stats[STAT_HEALTH] = self->health; } - traceEnt->client->ps.fd.forcePowerRegenDebounceTime = level.time + 800; //don't let the client being drained get force power back right away + traceEnt->client->ps.fd.forcePowerRegenDebounceTime = level.time + 800; // don't let the client being drained get force power back right away - //Drain the standard amount since we just drained someone else + // Drain the standard amount since we just drained someone else /* if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] == FORCE_LEVEL_1) @@ -2022,9 +1699,8 @@ void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t } */ - if (traceEnt->client->forcePowerSoundDebounce < level.time) - { - tent = G_TempEntity( impactPoint, EV_FORCE_DRAINED); + if (traceEnt->client->forcePowerSoundDebounce < level.time) { + tent = G_TempEntity(impactPoint, EV_FORCE_DRAINED); tent->s.eventParm = DirToByte(dir); tent->s.owner = traceEnt->s.number; @@ -2035,320 +1711,266 @@ void ForceDrainDamage( gentity_t *self, gentity_t *traceEnt, vec3_t dir, vec3_t } } -int ForceShootDrain( gentity_t *self ) -{ - trace_t tr; - vec3_t end, forward; - gentity_t *traceEnt; - int gotOneOrMore = 0; +int ForceShootDrain(gentity_t *self) { + trace_t tr; + vec3_t end, forward; + gentity_t *traceEnt; + int gotOneOrMore = 0; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return 0; } - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); - if ( self->client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2 ) - {//arc - vec3_t center, mins, maxs, dir, ent_org, size, v; - float radius = MAX_DRAIN_DISTANCE, dot, dist; - gentity_t *entityList[MAX_GENTITIES]; - int iEntityList[MAX_GENTITIES]; - int e, numListedEntities, i; + if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_2) { // arc + vec3_t center, mins, maxs, dir, ent_org, size, v; + float radius = MAX_DRAIN_DISTANCE, dot, dist; + gentity_t *entityList[MAX_GENTITIES]; + int iEntityList[MAX_GENTITIES]; + int e, numListedEntities, i; - VectorCopy( self->client->ps.origin, center ); - for ( i = 0 ; i < 3 ; i++ ) - { + VectorCopy(self->client->ps.origin, center); + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, iEntityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, iEntityList, MAX_GENTITIES); i = 0; - while (i < numListedEntities) - { + while (i < numListedEntities) { entityList[i] = &g_entities[iEntityList[i]]; i++; } - for ( e = 0 ; e < numListedEntities ; e++ ) - { + for (e = 0; e < numListedEntities; e++) { traceEnt = entityList[e]; - if ( !traceEnt ) + if (!traceEnt) continue; - if ( traceEnt == self ) + if (traceEnt == self) continue; - if ( !traceEnt->inuse ) + if (!traceEnt->inuse) continue; - if ( !traceEnt->takedamage ) + if (!traceEnt->takedamage) continue; - if ( traceEnt->health <= 0 )//no torturing corpses + if (traceEnt->health <= 0) // no torturing corpses continue; - if ( !traceEnt->client ) + if (!traceEnt->client) continue; - if ( !traceEnt->client->ps.fd.forcePower ) + if (!traceEnt->client->ps.fd.forcePower) continue; if (OnSameTeam(self, traceEnt) && !g_friendlyFire.integer) continue; - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < traceEnt->r.absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < traceEnt->r.absmin[i]) { v[i] = traceEnt->r.absmin[i] - center[i]; - } else if ( center[i] > traceEnt->r.absmax[i] ) - { + } else if (center[i] > traceEnt->r.absmax[i]) { v[i] = center[i] - traceEnt->r.absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( traceEnt->r.absmax, traceEnt->r.absmin, size ); - VectorMA( traceEnt->r.absmin, 0.5, size, ent_org ); + VectorSubtract(traceEnt->r.absmax, traceEnt->r.absmin, size); + VectorMA(traceEnt->r.absmin, 0.5, size, ent_org); - //see if they're in front of me - //must be within the forward cone - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot = DotProduct( dir, forward )) < 0.5 ) + // see if they're in front of me + // must be within the forward cone + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot = DotProduct(dir, forward)) < 0.5) continue; - //must be close enough - dist = VectorLength( v ); - if ( dist >= radius ) - { + // must be close enough + dist = VectorLength(v); + if (dist >= radius) { continue; } - //in PVS? - if ( !traceEnt->r.bmodel && !trap->InPVS( ent_org, self->client->ps.origin ) ) - {//must be in PVS + // in PVS? + if (!traceEnt->r.bmodel && !trap->InPVS(ent_org, self->client->ps.origin)) { // must be in PVS continue; } - //Now check and see if we can actually hit it - trap->Trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number ) - {//must have clear LOS + // Now check and see if we can actually hit it + trap->Trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction < 1.0f && tr.entityNum != traceEnt->s.number) { // must have clear LOS continue; } // ok, we are within the radius, add us to the incoming list - ForceDrainDamage( self, traceEnt, dir, ent_org ); + ForceDrainDamage(self, traceEnt, dir, ent_org); gotOneOrMore = 1; } - } - else - {//trace-line - VectorMA( self->client->ps.origin, 2048, forward, end ); + } else { // trace-line + VectorMA(self->client->ps.origin, 2048, forward, end); - trap->Trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid || !g_entities[tr.entityNum].client || !g_entities[tr.entityNum].inuse ) - { + trap->Trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.entityNum == ENTITYNUM_NONE || tr.fraction == 1.0 || tr.allsolid || tr.startsolid || !g_entities[tr.entityNum].client || + !g_entities[tr.entityNum].inuse) { return 0; } traceEnt = &g_entities[tr.entityNum]; - ForceDrainDamage( self, traceEnt, forward, tr.endpos ); + ForceDrainDamage(self, traceEnt, forward, tr.endpos); gotOneOrMore = 1; } self->client->ps.activeForcePass = self->client->ps.fd.forcePowerLevel[FP_DRAIN] + FORCE_LEVEL_3; - BG_ForcePowerDrain( &self->client->ps, FP_DRAIN, 5 ); //used to be 1, but this did, too, anger the God of Balance. + BG_ForcePowerDrain(&self->client->ps, FP_DRAIN, 5); // used to be 1, but this did, too, anger the God of Balance. self->client->ps.fd.forcePowerRegenDebounceTime = level.time + 500; return gotOneOrMore; } -void ForceJumpCharge( gentity_t *self, usercmd_t *ucmd ) -{ //I guess this is unused now. Was used for the "charge" jump type. - float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME/FRAMETIME); +void ForceJumpCharge(gentity_t *self, usercmd_t *ucmd) { // I guess this is unused now. Was used for the "charge" jump type. + float forceJumpChargeInterval = forceJumpStrength[0] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if (!self->client->ps.fd.forceJumpCharge && self->client->ps.groundEntityNum == ENTITYNUM_NONE) - { + if (!self->client->ps.fd.forceJumpCharge && self->client->ps.groundEntityNum == ENTITYNUM_NONE) { return; } - if (self->client->ps.fd.forcePower < forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION]) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); + if (self->client->ps.fd.forcePower < forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION]) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); return; } - if (!self->client->ps.fd.forceJumpCharge) - { + if (!self->client->ps.fd.forceJumpCharge) { self->client->ps.fd.forceJumpAddTime = 0; } - if (self->client->ps.fd.forceJumpAddTime >= level.time) - { + if (self->client->ps.fd.forceJumpAddTime >= level.time) { return; } - //need to play sound - if ( !self->client->ps.fd.forceJumpCharge ) - { - G_Sound( self, TRACK_CHANNEL_1, G_SoundIndex("sound/weapons/force/jumpbuild.wav") ); + // need to play sound + if (!self->client->ps.fd.forceJumpCharge) { + G_Sound(self, TRACK_CHANNEL_1, G_SoundIndex("sound/weapons/force/jumpbuild.wav")); } - //Increment - if (self->client->ps.fd.forceJumpAddTime < level.time) - { - self->client->ps.fd.forceJumpCharge += forceJumpChargeInterval*50; + // Increment + if (self->client->ps.fd.forceJumpAddTime < level.time) { + self->client->ps.fd.forceJumpCharge += forceJumpChargeInterval * 50; self->client->ps.fd.forceJumpAddTime = level.time + 500; } - //clamp to max strength for current level - if ( self->client->ps.fd.forceJumpCharge > forceJumpStrength[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]] ) - { + // clamp to max strength for current level + if (self->client->ps.fd.forceJumpCharge > forceJumpStrength[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]]) { self->client->ps.fd.forceJumpCharge = forceJumpStrength[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]]; - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); } - //clamp to max available force power - if ( self->client->ps.fd.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION] > self->client->ps.fd.forcePower ) - {//can't use more than you have - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); - self->client->ps.fd.forceJumpCharge = self->client->ps.fd.forcePower*forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + // clamp to max available force power + if (self->client->ps.fd.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * + forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION] > + self->client->ps.fd.forcePower) { // can't use more than you have + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); + self->client->ps.fd.forceJumpCharge = self->client->ps.fd.forcePower * forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); } - //trap->Print("%f\n", self->client->ps.fd.forceJumpCharge); + // trap->Print("%f\n", self->client->ps.fd.forceJumpCharge); } -int WP_GetVelocityForForceJump( gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd ) -{ +int WP_GetVelocityForForceJump(gentity_t *self, vec3_t jumpVel, usercmd_t *ucmd) { float pushFwd = 0, pushRt = 0; - vec3_t view, forward, right; - VectorCopy( self->client->ps.viewangles, view ); + vec3_t view, forward, right; + VectorCopy(self->client->ps.viewangles, view); view[0] = 0; - AngleVectors( view, forward, right, NULL ); - if ( ucmd->forwardmove && ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + AngleVectors(view, forward, right, NULL); + if (ucmd->forwardmove && ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 50; - } - else - { + } else { pushFwd = -50; } - if ( ucmd->rightmove > 0 ) - { + if (ucmd->rightmove > 0) { pushRt = 50; - } - else - { + } else { pushRt = -50; } - } - else if ( ucmd->forwardmove || ucmd->rightmove ) - { - if ( ucmd->forwardmove > 0 ) - { + } else if (ucmd->forwardmove || ucmd->rightmove) { + if (ucmd->forwardmove > 0) { pushFwd = 100; - } - else if ( ucmd->forwardmove < 0 ) - { + } else if (ucmd->forwardmove < 0) { pushFwd = -100; - } - else if ( ucmd->rightmove > 0 ) - { + } else if (ucmd->rightmove > 0) { pushRt = 100; - } - else if ( ucmd->rightmove < 0 ) - { + } else if (ucmd->rightmove < 0) { pushRt = -100; } } - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); G_PreDefSound(self->client->ps.origin, PDSOUND_FORCEJUMP); - if (self->client->ps.fd.forceJumpCharge < JUMP_VELOCITY+40) - { //give him at least a tiny boost from just a tap - self->client->ps.fd.forceJumpCharge = JUMP_VELOCITY+400; + if (self->client->ps.fd.forceJumpCharge < JUMP_VELOCITY + 40) { // give him at least a tiny boost from just a tap + self->client->ps.fd.forceJumpCharge = JUMP_VELOCITY + 400; } - if (self->client->ps.velocity[2] < -30) - { //so that we can get a good boost when force jumping in a fall + if (self->client->ps.velocity[2] < -30) { // so that we can get a good boost when force jumping in a fall self->client->ps.velocity[2] = -30; } - VectorMA( self->client->ps.velocity, pushFwd, forward, jumpVel ); - VectorMA( self->client->ps.velocity, pushRt, right, jumpVel ); + VectorMA(self->client->ps.velocity, pushFwd, forward, jumpVel); + VectorMA(self->client->ps.velocity, pushRt, right, jumpVel); jumpVel[2] += self->client->ps.fd.forceJumpCharge; - if ( pushFwd > 0 && self->client->ps.fd.forceJumpCharge > 200 ) - { + if (pushFwd > 0 && self->client->ps.fd.forceJumpCharge > 200) { return FJ_FORWARD; - } - else if ( pushFwd < 0 && self->client->ps.fd.forceJumpCharge > 200 ) - { + } else if (pushFwd < 0 && self->client->ps.fd.forceJumpCharge > 200) { return FJ_BACKWARD; - } - else if ( pushRt > 0 && self->client->ps.fd.forceJumpCharge > 200 ) - { + } else if (pushRt > 0 && self->client->ps.fd.forceJumpCharge > 200) { return FJ_RIGHT; - } - else if ( pushRt < 0 && self->client->ps.fd.forceJumpCharge > 200 ) - { + } else if (pushRt < 0 && self->client->ps.fd.forceJumpCharge > 200) { return FJ_LEFT; - } - else - { + } else { return FJ_UP; } } -void ForceJump( gentity_t *self, usercmd_t *ucmd ) -{ +void ForceJump(gentity_t *self, usercmd_t *ucmd) { float forceJumpChargeInterval; - vec3_t jumpVel; + vec3_t jumpVel; - if ( self->client->ps.fd.forcePowerDuration[FP_LEVITATION] > level.time ) - { + if (self->client->ps.fd.forcePowerDuration[FP_LEVITATION] > level.time) { return; } - if ( !WP_ForcePowerUsable( self, FP_LEVITATION ) ) - { + if (!WP_ForcePowerUsable(self, FP_LEVITATION)) { return; } - if ( self->s.groundEntityNum == ENTITYNUM_NONE ) - { + if (self->s.groundEntityNum == ENTITYNUM_NONE) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } self->client->fjDidJump = qtrue; - forceJumpChargeInterval = forceJumpStrength[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]]/(FORCE_JUMP_CHARGE_TIME/FRAMETIME); + forceJumpChargeInterval = forceJumpStrength[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]] / (FORCE_JUMP_CHARGE_TIME / FRAMETIME); - WP_GetVelocityForForceJump( self, jumpVel, ucmd ); + WP_GetVelocityForForceJump(self, jumpVel, ucmd); - //FIXME: sound effect - self->client->ps.fd.forceJumpZStart = self->client->ps.origin[2];//remember this for when we land - VectorCopy( jumpVel, self->client->ps.velocity ); - //wasn't allowing them to attack when jumping, but that was annoying - //self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; + // FIXME: sound effect + self->client->ps.fd.forceJumpZStart = self->client->ps.origin[2]; // remember this for when we land + VectorCopy(jumpVel, self->client->ps.velocity); + // wasn't allowing them to attack when jumping, but that was annoying + // self->client->ps.weaponTime = self->client->ps.torsoAnimTimer; - WP_ForcePowerStart( self, FP_LEVITATION, self->client->ps.fd.forceJumpCharge/forceJumpChargeInterval/(FORCE_JUMP_CHARGE_TIME/FRAMETIME)*forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION] ); - //self->client->ps.fd.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; + WP_ForcePowerStart(self, FP_LEVITATION, + self->client->ps.fd.forceJumpCharge / forceJumpChargeInterval / (FORCE_JUMP_CHARGE_TIME / FRAMETIME) * + forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_LEVITATION]][FP_LEVITATION]); + // self->client->ps.fd.forcePowerDuration[FP_LEVITATION] = level.time + self->client->ps.weaponTime; self->client->ps.fd.forceJumpCharge = 0; self->client->ps.forceJumpFlip = qtrue; @@ -2357,72 +1979,53 @@ void ForceJump( gentity_t *self, usercmd_t *ucmd ) self->client->ps.groundEntityNum = ENTITYNUM_NONE; } -void WP_AddAsMindtricked(forcedata_t *fd, int entNum) -{ - if (!fd) - { +void WP_AddAsMindtricked(forcedata_t *fd, int entNum) { + if (!fd) { return; } - if (entNum > 47) - { - fd->forceMindtrickTargetIndex4 |= (1 << (entNum-48)); - } - else if (entNum > 31) - { - fd->forceMindtrickTargetIndex3 |= (1 << (entNum-32)); - } - else if (entNum > 15) - { - fd->forceMindtrickTargetIndex2 |= (1 << (entNum-16)); - } - else - { + if (entNum > 47) { + fd->forceMindtrickTargetIndex4 |= (1 << (entNum - 48)); + } else if (entNum > 31) { + fd->forceMindtrickTargetIndex3 |= (1 << (entNum - 32)); + } else if (entNum > 15) { + fd->forceMindtrickTargetIndex2 |= (1 << (entNum - 16)); + } else { fd->forceMindtrickTargetIndex |= (1 << entNum); } } -qboolean ForceTelepathyCheckDirectNPCTarget( gentity_t *self, trace_t *tr, qboolean *tookPower ) -{ - gentity_t *traceEnt; - qboolean targetLive = qfalse; - vec3_t tfrom, tto, fwd; - float radius = MAX_TRICK_DISTANCE; +qboolean ForceTelepathyCheckDirectNPCTarget(gentity_t *self, trace_t *tr, qboolean *tookPower) { + gentity_t *traceEnt; + qboolean targetLive = qfalse; + vec3_t tfrom, tto, fwd; + float radius = MAX_TRICK_DISTANCE; - //Check for a direct usage on NPCs first + // Check for a direct usage on NPCs first VectorCopy(self->client->ps.origin, tfrom); tfrom[2] += self->client->ps.viewheight; AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); - tto[0] = tfrom[0] + fwd[0]*radius/2; - tto[1] = tfrom[1] + fwd[1]*radius/2; - tto[2] = tfrom[2] + fwd[2]*radius/2; - - trap->Trace( tr, tfrom, NULL, NULL, tto, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0 ); + tto[0] = tfrom[0] + fwd[0] * radius / 2; + tto[1] = tfrom[1] + fwd[1] * radius / 2; + tto[2] = tfrom[2] + fwd[2] * radius / 2; + trap->Trace(tr, tfrom, NULL, NULL, tto, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if ( tr->entityNum == ENTITYNUM_NONE - || tr->fraction == 1.0f - || tr->allsolid - || tr->startsolid ) - { + if (tr->entityNum == ENTITYNUM_NONE || tr->fraction == 1.0f || tr->allsolid || tr->startsolid) { return qfalse; } traceEnt = &g_entities[tr->entityNum]; - if( traceEnt->NPC - && traceEnt->NPC->scriptFlags & SCF_NO_FORCE ) - { + if (traceEnt->NPC && traceEnt->NPC->scriptFlags & SCF_NO_FORCE) { return qfalse; } - if ( traceEnt && traceEnt->client ) - { - switch ( traceEnt->client->NPC_class ) - { - case CLASS_GALAKMECH://cant grip him, he's in armor - case CLASS_ATST://much too big to grip! - //no droids either + if (traceEnt && traceEnt->client) { + switch (traceEnt->client->NPC_class) { + case CLASS_GALAKMECH: // cant grip him, he's in armor + case CLASS_ATST: // much too big to grip! + // no droids either case CLASS_PROBE: case CLASS_GONK: case CLASS_R2D2: @@ -2442,131 +2045,103 @@ qboolean ForceTelepathyCheckDirectNPCTarget( gentity_t *self, trace_t *tr, qbool } } - if ( traceEnt->s.number < MAX_CLIENTS ) - {//a regular client + if (traceEnt->s.number < MAX_CLIENTS) { // a regular client return qfalse; } - if ( targetLive && traceEnt->NPC ) - {//hit an organic non-player - vec3_t eyeDir; - if ( G_ActivateBehavior( traceEnt, BSET_MINDTRICK ) ) - {//activated a script on him - //FIXME: do the visual sparkles effect on their heads, still? - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); - } - else if ( (self->NPC && traceEnt->client->playerTeam != self->client->playerTeam) - || (!self->NPC && traceEnt->client->playerTeam != (npcteam_t)self->client->sess.sessionTeam) ) - {//an enemy + if (targetLive && traceEnt->NPC) { // hit an organic non-player + vec3_t eyeDir; + if (G_ActivateBehavior(traceEnt, BSET_MINDTRICK)) { // activated a script on him + // FIXME: do the visual sparkles effect on their heads, still? + WP_ForcePowerStart(self, FP_TELEPATHY, 0); + } else if ((self->NPC && traceEnt->client->playerTeam != self->client->playerTeam) || + (!self->NPC && traceEnt->client->playerTeam != (npcteam_t)self->client->sess.sessionTeam)) { // an enemy int override = 0; - if ( (traceEnt->NPC->scriptFlags&SCF_NO_MIND_TRICK) ) - { - } - else if ( traceEnt->s.weapon != WP_SABER - && traceEnt->client->NPC_class != CLASS_REBORN ) - {//haha! Jedi aren't easily confused! - if ( self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2 ) - {//turn them to our side - //if mind trick 3 and aiming at an enemy need more force power - if ( traceEnt->s.weapon != WP_NONE ) - {//don't charm people who aren't capable of fighting... like ugnaughts and droids + if ((traceEnt->NPC->scriptFlags & SCF_NO_MIND_TRICK)) { + } else if (traceEnt->s.weapon != WP_SABER && traceEnt->client->NPC_class != CLASS_REBORN) { // haha! Jedi aren't easily confused! + if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_2) { // turn them to our side + // if mind trick 3 and aiming at an enemy need more force power + if (traceEnt->s.weapon != WP_NONE) { // don't charm people who aren't capable of fighting... like ugnaughts and droids int newPlayerTeam, newEnemyTeam; - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); } - if ( traceEnt->NPC ) - { - //traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; + if (traceEnt->NPC) { + // traceEnt->NPC->tempBehavior = BS_FOLLOW_LEADER; traceEnt->client->leader = self; } - //FIXME: maybe pick an enemy right here? - if ( self->NPC ) - {//NPC + // FIXME: maybe pick an enemy right here? + if (self->NPC) { // NPC newPlayerTeam = self->client->playerTeam; newEnemyTeam = self->client->enemyTeam; - } - else - {//client/bot - if ( self->client->sess.sessionTeam == TEAM_BLUE ) - {//rebel + } else { // client/bot + if (self->client->sess.sessionTeam == TEAM_BLUE) { // rebel newPlayerTeam = NPCTEAM_PLAYER; newEnemyTeam = NPCTEAM_ENEMY; - } - else if ( self->client->sess.sessionTeam == TEAM_RED ) - {//imperial + } else if (self->client->sess.sessionTeam == TEAM_RED) { // imperial newPlayerTeam = NPCTEAM_ENEMY; newEnemyTeam = NPCTEAM_PLAYER; - } - else - {//neutral - wan't attack anyone + } else { // neutral - wan't attack anyone newPlayerTeam = NPCTEAM_NEUTRAL; newEnemyTeam = NPCTEAM_NEUTRAL; } } - //store these for retrieval later + // store these for retrieval later traceEnt->genericValue1 = traceEnt->client->playerTeam; traceEnt->genericValue2 = traceEnt->client->enemyTeam; traceEnt->genericValue3 = traceEnt->s.teamowner; - //set the new values + // set the new values traceEnt->client->playerTeam = newPlayerTeam; traceEnt->client->enemyTeam = newEnemyTeam; traceEnt->s.teamowner = newPlayerTeam; - //FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when done? + // FIXME: need a *charmed* timer on this...? Or do TEAM_PLAYERS assume that "confusion" means they should switch to team_enemy when + // done? traceEnt->NPC->charmedTime = level.time + mindTrickTime[self->client->ps.fd.forcePowerLevel[FP_TELEPATHY]]; } - } - else - {//just confuse them - //somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them pick one up for a while unless shot? - traceEnt->NPC->confusionTime = level.time + mindTrickTime[self->client->ps.fd.forcePowerLevel[FP_TELEPATHY]];//confused for about 10 seconds - NPC_PlayConfusionSound( traceEnt ); - if ( traceEnt->enemy ) - { - G_ClearEnemy( traceEnt ); + } else { // just confuse them + // somehow confuse them? Set don't fire to true for a while? Drop their aggression? Maybe just take their enemy away and don't let them + // pick one up for a while unless shot? + traceEnt->NPC->confusionTime = + level.time + mindTrickTime[self->client->ps.fd.forcePowerLevel[FP_TELEPATHY]]; // confused for about 10 seconds + NPC_PlayConfusionSound(traceEnt); + if (traceEnt->enemy) { + G_ClearEnemy(traceEnt); } } + } else { + NPC_Jedi_PlayConfusionSound(traceEnt); } - else - { - NPC_Jedi_PlayConfusionSound( traceEnt ); - } - WP_ForcePowerStart( self, FP_TELEPATHY, override ); - } - else if ( traceEnt->client->playerTeam == self->client->playerTeam ) - {//an ally - //maybe just have him look at you? Respond? Take your enemy? - if ( traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC!=NULL && !(traceEnt->NPC->scriptFlags&SCF_NO_RESPONSE) ) - { - NPC_UseResponse( traceEnt, self, qfalse ); - WP_ForcePowerStart( self, FP_TELEPATHY, 1 ); + WP_ForcePowerStart(self, FP_TELEPATHY, override); + } else if (traceEnt->client->playerTeam == self->client->playerTeam) { // an ally + // maybe just have him look at you? Respond? Take your enemy? + if (traceEnt->client->ps.pm_type < PM_DEAD && traceEnt->NPC != NULL && !(traceEnt->NPC->scriptFlags & SCF_NO_RESPONSE)) { + NPC_UseResponse(traceEnt, self, qfalse); + WP_ForcePowerStart(self, FP_TELEPATHY, 1); } - }//NOTE: no effect on TEAM_NEUTRAL? - AngleVectors( traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL ); - VectorNormalize( eyeDir ); - G_PlayEffectID( G_EffectIndex( "force/force_touch" ), traceEnt->client->renderInfo.eyePoint, eyeDir ); - - //make sure this plays and that you cannot press fire for about 1 second after this - //FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT - //NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); - //FIXME: build-up or delay this until in proper part of anim - } - else - { - if ( self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && tr->fraction * 2048 > 64 ) - {//don't create a diversion less than 64 from you of if at power level 1 - //use distraction anim instead - G_PlayEffectID( G_EffectIndex( "force/force_touch" ), tr->endpos, tr->plane.normal ); - //FIXME: these events don't seem to always be picked up...? - AddSoundEvent( self, tr->endpos, 512, AEL_SUSPICIOUS, qtrue );//, qtrue ); - AddSightEvent( self, tr->endpos, 512, AEL_SUSPICIOUS, 50 ); - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); + } // NOTE: no effect on TEAM_NEUTRAL? + AngleVectors(traceEnt->client->renderInfo.eyeAngles, eyeDir, NULL, NULL); + VectorNormalize(eyeDir); + G_PlayEffectID(G_EffectIndex("force/force_touch"), traceEnt->client->renderInfo.eyePoint, eyeDir); + + // make sure this plays and that you cannot press fire for about 1 second after this + // FIXME: BOTH_FORCEMINDTRICK or BOTH_FORCEDISTRACT + // NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); + // FIXME: build-up or delay this until in proper part of anim + } else { + if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] > FORCE_LEVEL_1 && + tr->fraction * 2048 > 64) { // don't create a diversion less than 64 from you of if at power level 1 + // use distraction anim instead + G_PlayEffectID(G_EffectIndex("force/force_touch"), tr->endpos, tr->plane.normal); + // FIXME: these events don't seem to always be picked up...? + AddSoundEvent(self, tr->endpos, 512, AEL_SUSPICIOUS, qtrue); //, qtrue ); + AddSightEvent(self, tr->endpos, 512, AEL_SUSPICIOUS, 50); + WP_ForcePowerStart(self, FP_TELEPATHY, 0); *tookPower = qtrue; } - //NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); + // NPC_SetAnim( self, SETANIM_TORSO, BOTH_MINDTRICK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_RESTART|SETANIM_FLAG_HOLD ); } - //self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in + // self->client->ps.saberMove = self->client->ps.saberBounceMove = LS_READY;//don't finish whatever saber anim you may have been in self->client->ps.saberBlocked = BLOCKED_NONE; self->client->ps.weaponTime = 1000; /* @@ -2578,109 +2153,85 @@ qboolean ForceTelepathyCheckDirectNPCTarget( gentity_t *self, trace_t *tr, qbool return qtrue; } -void ForceTelepathy(gentity_t *self) -{ +void ForceTelepathy(gentity_t *self) { trace_t tr; vec3_t tto, thispush_org, a; vec3_t mins, maxs, fwdangles, forward, right, center; int i; float visionArc = 0; float radius = MAX_TRICK_DISTANCE; - qboolean tookPower = qfalse; + qboolean tookPower = qfalse; - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return; } - if (self->client->ps.powerups[PW_REDFLAG] || - self->client->ps.powerups[PW_BLUEFLAG]) - { //can't mindtrick while carrying the flag + if (self->client->ps.powerups[PW_REDFLAG] || self->client->ps.powerups[PW_BLUEFLAG]) { // can't mindtrick while carrying the flag return; } - if (self->client->ps.forceAllowDeactivateTime < level.time && - (self->client->ps.fd.forcePowersActive & (1 << FP_TELEPATHY)) ) - { - WP_ForcePowerStop( self, FP_TELEPATHY ); + if (self->client->ps.forceAllowDeactivateTime < level.time && (self->client->ps.fd.forcePowersActive & (1 << FP_TELEPATHY))) { + WP_ForcePowerStop(self, FP_TELEPATHY); return; } - if ( !WP_ForcePowerUsable( self, FP_TELEPATHY ) ) - { + if (!WP_ForcePowerUsable(self, FP_TELEPATHY)) { return; } // fix: rocket lock bug BG_ClearRocketLock(&self->client->ps); - if ( ForceTelepathyCheckDirectNPCTarget( self, &tr, &tookPower ) ) - {//hit an NPC directly + if (ForceTelepathyCheckDirectNPCTarget(self, &tr, &tookPower)) { // hit an NPC directly self->client->ps.forceAllowDeactivateTime = level.time + 1500; - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav") ); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav")); self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; self->client->ps.forceHandExtendTime = level.time + 1000; return; } - if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_2) - { + if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_2) { visionArc = 180; - } - else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_3) { visionArc = 360; - radius = MAX_TRICK_DISTANCE*2.0f; + radius = MAX_TRICK_DISTANCE * 2.0f; } - VectorCopy( self->client->ps.viewangles, fwdangles ); - AngleVectors( fwdangles, forward, right, NULL ); - VectorCopy( self->client->ps.origin, center ); + VectorCopy(self->client->ps.viewangles, fwdangles); + AngleVectors(fwdangles, forward, right, NULL); + VectorCopy(self->client->ps.origin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_1) - { - if (tr.fraction != 1.0 && - tr.entityNum != ENTITYNUM_NONE && - g_entities[tr.entityNum].inuse && - g_entities[tr.entityNum].client && - g_entities[tr.entityNum].client->pers.connected && - g_entities[tr.entityNum].client->sess.sessionTeam != TEAM_SPECTATOR) - { + if (self->client->ps.fd.forcePowerLevel[FP_TELEPATHY] == FORCE_LEVEL_1) { + if (tr.fraction != 1.0 && tr.entityNum != ENTITYNUM_NONE && g_entities[tr.entityNum].inuse && g_entities[tr.entityNum].client && + g_entities[tr.entityNum].client->pers.connected && g_entities[tr.entityNum].client->sess.sessionTeam != TEAM_SPECTATOR) { WP_AddAsMindtricked(&self->client->ps.fd, tr.entityNum); - if ( !tookPower ) - { - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); + if (!tookPower) { + WP_ForcePowerStart(self, FP_TELEPATHY, 0); } - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav") ); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav")); self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; self->client->ps.forceHandExtendTime = level.time + 1000; return; - } - else - { + } else { return; } - } - else //level 2 & 3 + } else // level 2 & 3 { gentity_t *ent; int entityList[MAX_GENTITIES]; @@ -2688,20 +2239,15 @@ void ForceTelepathy(gentity_t *self) int e = 0; qboolean gotatleastone = qfalse; - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); - while (e < numListedEntities) - { + while (e < numListedEntities) { ent = &g_entities[entityList[e]]; - if (ent) - { //not in the arc, don't consider it - if (ent->client) - { + if (ent) { // not in the arc, don't consider it + if (ent->client) { VectorCopy(ent->client->ps.origin, thispush_org); - } - else - { + } else { VectorCopy(ent->s.pos.trBase, thispush_org); } VectorCopy(self->client->ps.origin, tto); @@ -2709,129 +2255,98 @@ void ForceTelepathy(gentity_t *self) VectorSubtract(thispush_org, tto, a); vectoangles(a, a); - if (!ent->client) - { + if (!ent->client) { entityList[e] = ENTITYNUM_NONE; - } - else if (!InFieldOfVision(self->client->ps.viewangles, visionArc, a)) - { //only bother with arc rules if the victim is a client + } else if (!InFieldOfVision(self->client->ps.viewangles, visionArc, a)) { // only bother with arc rules if the victim is a client entityList[e] = ENTITYNUM_NONE; - } - else if (!ForcePowerUsableOn(self, ent, FP_TELEPATHY)) - { + } else if (!ForcePowerUsableOn(self, ent, FP_TELEPATHY)) { entityList[e] = ENTITYNUM_NONE; - } - else if (OnSameTeam(self, ent)) - { + } else if (OnSameTeam(self, ent)) { entityList[e] = ENTITYNUM_NONE; } } ent = &g_entities[entityList[e]]; - if (ent && ent != self && ent->client) - { + if (ent && ent != self && ent->client) { gotatleastone = qtrue; WP_AddAsMindtricked(&self->client->ps.fd, ent->s.number); } e++; } - if (gotatleastone) - { + if (gotatleastone) { self->client->ps.forceAllowDeactivateTime = level.time + 1500; - if ( !tookPower ) - { - WP_ForcePowerStart( self, FP_TELEPATHY, 0 ); + if (!tookPower) { + WP_ForcePowerStart(self, FP_TELEPATHY, 0); } - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav") ); + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distract.wav")); self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; self->client->ps.forceHandExtendTime = level.time + 1000; } } - } -void GEntity_UseFunc( gentity_t *self, gentity_t *other, gentity_t *activator ) -{ - GlobalUse(self, other, activator); -} +void GEntity_UseFunc(gentity_t *self, gentity_t *other, gentity_t *activator) { GlobalUse(self, other, activator); } -qboolean CanCounterThrow(gentity_t *self, gentity_t *thrower, qboolean pull) -{ +qboolean CanCounterThrow(gentity_t *self, gentity_t *thrower, qboolean pull) { int powerUse = 0; - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return 0; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return 0; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return 0; } - if ( self->client->ps.powerups[PW_DISINT_4] > level.time ) - { + if (self->client->ps.powerups[PW_DISINT_4] > level.time) { return 0; } - if (self->client->ps.weaponstate == WEAPON_CHARGING || - self->client->ps.weaponstate == WEAPON_CHARGING_ALT) - { //don't autodefend when charging a weapon + if (self->client->ps.weaponstate == WEAPON_CHARGING || self->client->ps.weaponstate == WEAPON_CHARGING_ALT) { // don't autodefend when charging a weapon return 0; } - if (level.gametype == GT_SIEGE && - pull && - thrower && thrower->client) - { //in siege, pull will affect people if they are not facing you, so they can't run away so much + if (level.gametype == GT_SIEGE && pull && thrower && + thrower->client) { // in siege, pull will affect people if they are not facing you, so they can't run away so much vec3_t d; float a; - VectorSubtract(thrower->client->ps.origin, self->client->ps.origin, d); + VectorSubtract(thrower->client->ps.origin, self->client->ps.origin, d); vectoangles(d, d); - a = AngleSubtract(d[YAW], self->client->ps.viewangles[YAW]); + a = AngleSubtract(d[YAW], self->client->ps.viewangles[YAW]); - if (a > 60.0f || a < -60.0f) - { //if facing more than 60 degrees away they cannot defend + if (a > 60.0f || a < -60.0f) { // if facing more than 60 degrees away they cannot defend return 0; } } - if (pull) - { + if (pull) { powerUse = FP_PULL; - } - else - { + } else { powerUse = FP_PUSH; } - if ( !WP_ForcePowerUsable( self, powerUse ) ) - { + if (!WP_ForcePowerUsable(self, powerUse)) { return 0; } - if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) - { //you cannot counter a push/pull if you're in the air + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // you cannot counter a push/pull if you're in the air return 0; } return 1; } -qboolean G_InGetUpAnim(playerState_t *ps) -{ - switch( (ps->legsAnim) ) - { +qboolean G_InGetUpAnim(playerState_t *ps) { + switch ((ps->legsAnim)) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -2855,8 +2370,7 @@ qboolean G_InGetUpAnim(playerState_t *ps) return qtrue; } - switch( (ps->torsoAnim) ) - { + switch ((ps->torsoAnim)) { case BOTH_GETUP1: case BOTH_GETUP2: case BOTH_GETUP3: @@ -2882,209 +2396,165 @@ qboolean G_InGetUpAnim(playerState_t *ps) return qfalse; } -void G_LetGoOfWall( gentity_t *ent ) -{ - if ( !ent || !ent->client ) - { +void G_LetGoOfWall(gentity_t *ent) { + if (!ent || !ent->client) { return; } ent->client->ps.pm_flags &= ~PMF_STUCK_TO_WALL; - if ( BG_InReboundJump( ent->client->ps.legsAnim ) - || BG_InReboundHold( ent->client->ps.legsAnim ) ) - { + if (BG_InReboundJump(ent->client->ps.legsAnim) || BG_InReboundHold(ent->client->ps.legsAnim)) { ent->client->ps.legsTimer = 0; } - if ( BG_InReboundJump( ent->client->ps.torsoAnim ) - || BG_InReboundHold( ent->client->ps.torsoAnim ) ) - { + if (BG_InReboundJump(ent->client->ps.torsoAnim) || BG_InReboundHold(ent->client->ps.torsoAnim)) { ent->client->ps.torsoTimer = 0; } } -float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = -{ - 0,//none - 384,//256, - 448,//384, - 512 -}; -//rwwFIXMEFIXME: incorporate this into the below function? Currently it's only being used by jedi AI - -extern void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace ); -void ForceThrow( gentity_t *self, qboolean pull ) -{ - //shove things in front of you away - float dist; - gentity_t *ent; - int entityList[MAX_GENTITIES]; - gentity_t *push_list[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - vec3_t v; - int i, e; - int ent_count = 0; - int radius = 1024; //since it's view-based now. //350; - int powerLevel; - int visionArc; - int pushPower; - int pushPowerMod; - vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; - float dot1; - trace_t tr; - int x; - vec3_t pushDir; - vec3_t thispush_org; - vec3_t tfrom, tto, fwd, a; - int powerUse = 0; +float forcePushPullRadius[NUM_FORCE_POWER_LEVELS] = {0, // none + 384, // 256, + 448, // 384, + 512}; +// rwwFIXMEFIXME: incorporate this into the below function? Currently it's only being used by jedi AI + +extern void Touch_Button(gentity_t *ent, gentity_t *other, trace_t *trace); +void ForceThrow(gentity_t *self, qboolean pull) { + // shove things in front of you away + float dist; + gentity_t *ent; + int entityList[MAX_GENTITIES]; + gentity_t *push_list[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + vec3_t v; + int i, e; + int ent_count = 0; + int radius = 1024; // since it's view-based now. //350; + int powerLevel; + int visionArc; + int pushPower; + int pushPowerMod; + vec3_t center, ent_org, size, forward, right, end, dir, fwdangles = {0}; + float dot1; + trace_t tr; + int x; + vec3_t pushDir; + vec3_t thispush_org; + vec3_t tfrom, tto, fwd, a; + int powerUse = 0; visionArc = 0; - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE && (self->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN || !G_InGetUpAnim(&self->client->ps))) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE && + (self->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN || !G_InGetUpAnim(&self->client->ps))) { return; } - if (!g_useWhileThrowing.integer && self->client->ps.saberInFlight) - { + if (!g_useWhileThrowing.integer && self->client->ps.saberInFlight) { return; } - if (self->client->ps.weaponTime > 0) - { + if (self->client->ps.weaponTime > 0) { return; } - if ( self->health <= 0 ) - { + if (self->health <= 0) { return; } - if ( self->client->ps.powerups[PW_DISINT_4] > level.time ) - { + if (self->client->ps.powerups[PW_DISINT_4] > level.time) { return; } - if (pull) - { + if (pull) { powerUse = FP_PULL; - } - else - { + } else { powerUse = FP_PUSH; } - if ( !WP_ForcePowerUsable( self, powerUse ) ) - { + if (!WP_ForcePowerUsable(self, powerUse)) { return; } // fix: rocket lock bug BG_ClearRocketLock(&self->client->ps); - if (!pull && self->client->ps.saberLockTime > level.time && self->client->ps.saberLockFrame) - { - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/weapons/force/push.wav" ) ); + if (!pull && self->client->ps.saberLockTime > level.time && self->client->ps.saberLockFrame) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/push.wav")); self->client->ps.powerups[PW_DISINT_4] = level.time + 1500; - self->client->ps.saberLockHits += self->client->ps.fd.forcePowerLevel[FP_PUSH]*2; + self->client->ps.saberLockHits += self->client->ps.fd.forcePowerLevel[FP_PUSH] * 2; - WP_ForcePowerStart( self, FP_PUSH, 0 ); + WP_ForcePowerStart(self, FP_PUSH, 0); return; } - WP_ForcePowerStart( self, powerUse, 0 ); + WP_ForcePowerStart(self, powerUse, 0); - //make sure this plays and that you cannot press fire for about 1 second after this - if ( pull ) - { - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); - if (self->client->ps.forceHandExtend == HANDEXTEND_NONE) - { + // make sure this plays and that you cannot press fire for about 1 second after this + if (pull) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/pull.wav")); + if (self->client->ps.forceHandExtend == HANDEXTEND_NONE) { self->client->ps.forceHandExtend = HANDEXTEND_FORCEPULL; - if ( level.gametype == GT_SIEGE && self->client->ps.weapon == WP_SABER ) - {//hold less so can attack right after a pull + if (level.gametype == GT_SIEGE && self->client->ps.weapon == WP_SABER) { // hold less so can attack right after a pull self->client->ps.forceHandExtendTime = level.time + 200; - } - else - { + } else { self->client->ps.forceHandExtendTime = level.time + 400; } } self->client->ps.powerups[PW_DISINT_4] = self->client->ps.forceHandExtendTime + 200; self->client->ps.powerups[PW_PULL] = self->client->ps.powerups[PW_DISINT_4]; - } - else - { - G_Sound( self, CHAN_BODY, G_SoundIndex( "sound/weapons/force/push.wav" ) ); - if (self->client->ps.forceHandExtend == HANDEXTEND_NONE) - { + } else { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/push.wav")); + if (self->client->ps.forceHandExtend == HANDEXTEND_NONE) { self->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; self->client->ps.forceHandExtendTime = level.time + 1000; - } - else if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && G_InGetUpAnim(&self->client->ps)) - { - if (self->client->ps.forceDodgeAnim > 4) - { + } else if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && G_InGetUpAnim(&self->client->ps)) { + if (self->client->ps.forceDodgeAnim > 4) { self->client->ps.forceDodgeAnim -= 8; } - self->client->ps.forceDodgeAnim += 8; //special case, play push on upper torso, but keep playing current knockdown anim on legs + self->client->ps.forceDodgeAnim += 8; // special case, play push on upper torso, but keep playing current knockdown anim on legs } self->client->ps.powerups[PW_DISINT_4] = level.time + 1100; self->client->ps.powerups[PW_PULL] = 0; } - VectorCopy( self->client->ps.viewangles, fwdangles ); - AngleVectors( fwdangles, forward, right, NULL ); - VectorCopy( self->client->ps.origin, center ); + VectorCopy(self->client->ps.viewangles, fwdangles); + AngleVectors(fwdangles, forward, right, NULL); + VectorCopy(self->client->ps.origin, center); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = center[i] - radius; maxs[i] = center[i] + radius; } - - if (pull) - { + if (pull) { powerLevel = self->client->ps.fd.forcePowerLevel[FP_PULL]; - pushPower = 256*self->client->ps.fd.forcePowerLevel[FP_PULL]; - } - else - { + pushPower = 256 * self->client->ps.fd.forcePowerLevel[FP_PULL]; + } else { powerLevel = self->client->ps.fd.forcePowerLevel[FP_PUSH]; - pushPower = 256*self->client->ps.fd.forcePowerLevel[FP_PUSH]; + pushPower = 256 * self->client->ps.fd.forcePowerLevel[FP_PUSH]; } - if (!powerLevel) - { //Shouldn't have made it here.. + if (!powerLevel) { // Shouldn't have made it here.. return; } - if (powerLevel == FORCE_LEVEL_2) - { + if (powerLevel == FORCE_LEVEL_2) { visionArc = 60; - } - else if (powerLevel == FORCE_LEVEL_3) - { + } else if (powerLevel == FORCE_LEVEL_3) { visionArc = 180; } - if (powerLevel == FORCE_LEVEL_1) - { //can only push/pull targeted things at level 1 + if (powerLevel == FORCE_LEVEL_1) { // can only push/pull targeted things at level 1 VectorCopy(self->client->ps.origin, tfrom); tfrom[2] += self->client->ps.viewheight; AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); - tto[0] = tfrom[0] + fwd[0]*radius/2; - tto[1] = tfrom[1] + fwd[1]*radius/2; - tto[2] = tfrom[2] + fwd[2]*radius/2; + tto[0] = tfrom[0] + fwd[0] * radius / 2; + tto[1] = tfrom[1] + fwd[1] * radius / 2; + tto[2] = tfrom[2] + fwd[2] * radius / 2; trap->Trace(&tr, tfrom, NULL, NULL, tto, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction != 1.0 && - tr.entityNum != ENTITYNUM_NONE) - { - if (!g_entities[tr.entityNum].client && g_entities[tr.entityNum].s.eType == ET_NPC) - { //g2animent - if (g_entities[tr.entityNum].s.genericenemyindex < level.time) - { + if (tr.fraction != 1.0 && tr.entityNum != ENTITYNUM_NONE) { + if (!g_entities[tr.entityNum].client && g_entities[tr.entityNum].s.eType == ET_NPC) { // g2animent + if (g_entities[tr.entityNum].s.genericenemyindex < level.time) { g_entities[tr.entityNum].s.genericenemyindex = level.time + 2000; } } @@ -3092,83 +2562,58 @@ void ForceThrow( gentity_t *self, qboolean pull ) numListedEntities = 0; entityList[numListedEntities] = tr.entityNum; - if (pull) - { - if (!ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_PULL)) - { + if (pull) { + if (!ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_PULL)) { return; } - } - else - { - if (!ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_PUSH)) - { + } else { + if (!ForcePowerUsableOn(self, &g_entities[tr.entityNum], FP_PUSH)) { return; } } numListedEntities++; - } - else - { - //didn't get anything, so just + } else { + // didn't get anything, so just return; } - } - else - { - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + } else { + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); e = 0; - while (e < numListedEntities) - { + while (e < numListedEntities) { ent = &g_entities[entityList[e]]; - if (!ent->client && ent->s.eType == ET_NPC) - { //g2animent - if (ent->s.genericenemyindex < level.time) - { + if (!ent->client && ent->s.eType == ET_NPC) { // g2animent + if (ent->s.genericenemyindex < level.time) { ent->s.genericenemyindex = level.time + 2000; } } - if (ent) - { - if (ent->client) - { + if (ent) { + if (ent->client) { VectorCopy(ent->client->ps.origin, thispush_org); - } - else - { + } else { VectorCopy(ent->s.pos.trBase, thispush_org); } } - if (ent) - { //not in the arc, don't consider it + if (ent) { // not in the arc, don't consider it VectorCopy(self->client->ps.origin, tto); tto[2] += self->client->ps.viewheight; VectorSubtract(thispush_org, tto, a); vectoangles(a, a); if (ent->client && !InFieldOfVision(self->client->ps.viewangles, visionArc, a) && - ForcePowerUsableOn(self, ent, powerUse)) - { //only bother with arc rules if the victim is a client + ForcePowerUsableOn(self, ent, powerUse)) { // only bother with arc rules if the victim is a client entityList[e] = ENTITYNUM_NONE; - } - else if (ent->client) - { - if (pull) - { - if (!ForcePowerUsableOn(self, ent, FP_PULL)) - { + } else if (ent->client) { + if (pull) { + if (!ForcePowerUsableOn(self, ent, FP_PULL)) { entityList[e] = ENTITYNUM_NONE; } - } - else - { - if (!ForcePowerUsableOn(self, ent, FP_PUSH)) - { + } else { + if (!ForcePowerUsableOn(self, ent, FP_PUSH)) { entityList[e] = ENTITYNUM_NONE; } } @@ -3178,16 +2623,10 @@ void ForceThrow( gentity_t *self, qboolean pull ) } } - for ( e = 0 ; e < numListedEntities ; e++ ) - { - if (entityList[e] != ENTITYNUM_NONE && - entityList[e] >= 0 && - entityList[e] < MAX_GENTITIES) - { + for (e = 0; e < numListedEntities; e++) { + if (entityList[e] != ENTITYNUM_NONE && entityList[e] >= 0 && entityList[e] < MAX_GENTITIES) { ent = &g_entities[entityList[e]]; - } - else - { + } else { ent = NULL; } @@ -3195,123 +2634,94 @@ void ForceThrow( gentity_t *self, qboolean pull ) continue; if (ent == self) continue; - if (ent->client && OnSameTeam(ent, self)) - { + if (ent->client && OnSameTeam(ent, self)) { continue; } - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType != ET_MISSILE ) - { - if ( ent->s.eType != ET_ITEM ) - { - //FIXME: need pushable objects - if ( Q_stricmp( "func_button", ent->classname ) == 0 ) - {//we might push it - if ( pull || !(ent->spawnflags&SPF_BUTTON_FPUSHABLE) ) - {//not force-pushable, never pullable + if (ent->s.eType != ET_MISSILE) { + if (ent->s.eType != ET_ITEM) { + // FIXME: need pushable objects + if (Q_stricmp("func_button", ent->classname) == 0) { // we might push it + if (pull || !(ent->spawnflags & SPF_BUTTON_FPUSHABLE)) { // not force-pushable, never pullable continue; } - } - else - { - if ( ent->s.eFlags & EF_NODRAW ) - { + } else { + if (ent->s.eFlags & EF_NODRAW) { continue; } - if ( !ent->client ) - { - if ( Q_stricmp( "lightsaber", ent->classname ) != 0 ) - {//not a lightsaber - if ( Q_stricmp( "func_door", ent->classname ) != 0 || !(ent->spawnflags & 2/*MOVER_FORCE_ACTIVATE*/) ) - {//not a force-usable door - if ( Q_stricmp( "func_static", ent->classname ) != 0 || (!(ent->spawnflags&1/*F_PUSH*/)&&!(ent->spawnflags&2/*F_PULL*/)) ) - {//not a force-usable func_static - if ( Q_stricmp( "limb", ent->classname ) ) - {//not a limb + if (!ent->client) { + if (Q_stricmp("lightsaber", ent->classname) != 0) { // not a lightsaber + if (Q_stricmp("func_door", ent->classname) != 0 || !(ent->spawnflags & 2 /*MOVER_FORCE_ACTIVATE*/)) { // not a force-usable door + if (Q_stricmp("func_static", ent->classname) != 0 || + (!(ent->spawnflags & 1 /*F_PUSH*/) && !(ent->spawnflags & 2 /*F_PULL*/))) { // not a force-usable func_static + if (Q_stricmp("limb", ent->classname)) { // not a limb continue; } } - } - else if ( ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2 ) - {//not at rest + } else if (ent->moverState != MOVER_POS1 && ent->moverState != MOVER_POS2) { // not at rest continue; } } - } - else if ( ent->client->NPC_class == CLASS_GALAKMECH - || ent->client->NPC_class == CLASS_ATST - || ent->client->NPC_class == CLASS_RANCOR ) - {//can't push ATST or Galak or Rancor + } else if (ent->client->NPC_class == CLASS_GALAKMECH || ent->client->NPC_class == CLASS_ATST || + ent->client->NPC_class == CLASS_RANCOR) { // can't push ATST or Galak or Rancor continue; } } } - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) ) - {//can't force-push/pull stuck missiles (detpacks, tripmines) + } else { + if (ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags & EF_MISSILE_STICK)) { // can't force-push/pull stuck missiles (detpacks, tripmines) continue; } - if ( ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL ) - {//only thermal detonators can be pushed once stopped + if (ent->s.pos.trType == TR_STATIONARY && ent->s.weapon != WP_THERMAL) { // only thermal detonators can be pushed once stopped continue; } } - //this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter - // find the distance from the edge of the bounding box - for ( i = 0 ; i < 3 ; i++ ) - { - if ( center[i] < ent->r.absmin[i] ) - { + // this is all to see if we need to start a saber attack, if it's in flight, this doesn't matter + // find the distance from the edge of the bounding box + for (i = 0; i < 3; i++) { + if (center[i] < ent->r.absmin[i]) { v[i] = ent->r.absmin[i] - center[i]; - } else if ( center[i] > ent->r.absmax[i] ) - { + } else if (center[i] > ent->r.absmax[i]) { v[i] = center[i] - ent->r.absmax[i]; - } else - { + } else { v[i] = 0; } } - VectorSubtract( ent->r.absmax, ent->r.absmin, size ); - VectorMA( ent->r.absmin, 0.5, size, ent_org ); + VectorSubtract(ent->r.absmax, ent->r.absmin, size); + VectorMA(ent->r.absmin, 0.5, size, ent_org); - VectorSubtract( ent_org, center, dir ); - VectorNormalize( dir ); - if ( (dot1 = DotProduct( dir, forward )) < 0.6 ) + VectorSubtract(ent_org, center, dir); + VectorNormalize(dir); + if ((dot1 = DotProduct(dir, forward)) < 0.6) continue; - dist = VectorLength( v ); + dist = VectorLength(v); - //Now check and see if we can actually deflect it - //method1 - //if within a certain range, deflect it - if ( dist >= radius ) - { + // Now check and see if we can actually deflect it + // method1 + // if within a certain range, deflect it + if (dist >= radius) { continue; } - //in PVS? - if ( !ent->r.bmodel && !trap->InPVS( ent_org, self->client->ps.origin ) ) - {//must be in PVS + // in PVS? + if (!ent->r.bmodel && !trap->InPVS(ent_org, self->client->ps.origin)) { // must be in PVS continue; } - //really should have a clear LOS to this thing... - trap->Trace( &tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.fraction < 1.0f && tr.entityNum != ent->s.number ) - {//must have clear LOS - //try from eyes too before you give up + // really should have a clear LOS to this thing... + trap->Trace(&tr, self->client->ps.origin, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.fraction < 1.0f && tr.entityNum != ent->s.number) { // must have clear LOS + // try from eyes too before you give up vec3_t eyePoint; VectorCopy(self->client->ps.origin, eyePoint); eyePoint[2] += self->client->ps.viewheight; - trap->Trace( &tr, eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0 ); + trap->Trace(&tr, eyePoint, vec3_origin, vec3_origin, ent_org, self->s.number, MASK_SHOT, qfalse, 0, 0); - if ( tr.fraction < 1.0f && tr.entityNum != ent->s.number ) - { + if (tr.fraction < 1.0f && tr.entityNum != ent->s.number) { continue; } } @@ -3321,143 +2731,107 @@ void ForceThrow( gentity_t *self, qboolean pull ) ent_count++; } - if ( ent_count ) - { - //method1: - for ( x = 0; x < ent_count; x++ ) - { + if (ent_count) { + // method1: + for (x = 0; x < ent_count; x++) { int modPowerLevel = powerLevel; - - if (push_list[x]->client) - { - modPowerLevel = WP_AbsorbConversion(push_list[x], push_list[x]->client->ps.fd.forcePowerLevel[FP_ABSORB], self, powerUse, powerLevel, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[powerUse]][powerUse]); - if (modPowerLevel == -1) - { + if (push_list[x]->client) { + modPowerLevel = WP_AbsorbConversion(push_list[x], push_list[x]->client->ps.fd.forcePowerLevel[FP_ABSORB], self, powerUse, powerLevel, + forcePowerNeeded[self->client->ps.fd.forcePowerLevel[powerUse]][powerUse]); + if (modPowerLevel == -1) { modPowerLevel = powerLevel; } } - pushPower = 256*modPowerLevel; + pushPower = 256 * modPowerLevel; - if (push_list[x]->client) - { + if (push_list[x]->client) { VectorCopy(push_list[x]->client->ps.origin, thispush_org); - } - else - { + } else { VectorCopy(push_list[x]->s.origin, thispush_org); } - if ( push_list[x]->client ) - {//FIXME: make enemy jedi able to hunker down and resist this? + if (push_list[x]->client) { // FIXME: make enemy jedi able to hunker down and resist this? int otherPushPower = push_list[x]->client->ps.fd.forcePowerLevel[powerUse]; qboolean canPullWeapon = qtrue; float dirLen = 0; - if ( g_debugMelee.integer ) - { - if ( (push_list[x]->client->ps.pm_flags&PMF_STUCK_TO_WALL) ) - {//no resistance if stuck to wall - //push/pull them off the wall + if (g_debugMelee.integer) { + if ((push_list[x]->client->ps.pm_flags & PMF_STUCK_TO_WALL)) { // no resistance if stuck to wall + // push/pull them off the wall otherPushPower = 0; - G_LetGoOfWall( push_list[x] ); + G_LetGoOfWall(push_list[x]); } } pushPowerMod = pushPower; if (push_list[x]->client->pers.cmd.forwardmove || - push_list[x]->client->pers.cmd.rightmove) - { //if you are moving, you get one less level of defense + push_list[x]->client->pers.cmd.rightmove) { // if you are moving, you get one less level of defense otherPushPower--; - if (otherPushPower < 0) - { + if (otherPushPower < 0) { otherPushPower = 0; } } - if (otherPushPower && CanCounterThrow(push_list[x], self, pull)) - { - if ( pull ) - { - G_Sound( push_list[x], CHAN_BODY, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); + if (otherPushPower && CanCounterThrow(push_list[x], self, pull)) { + if (pull) { + G_Sound(push_list[x], CHAN_BODY, G_SoundIndex("sound/weapons/force/pull.wav")); push_list[x]->client->ps.forceHandExtend = HANDEXTEND_FORCEPULL; push_list[x]->client->ps.forceHandExtendTime = level.time + 400; - } - else - { - G_Sound( push_list[x], CHAN_BODY, G_SoundIndex( "sound/weapons/force/push.wav" ) ); + } else { + G_Sound(push_list[x], CHAN_BODY, G_SoundIndex("sound/weapons/force/push.wav")); push_list[x]->client->ps.forceHandExtend = HANDEXTEND_FORCEPUSH; push_list[x]->client->ps.forceHandExtendTime = level.time + 1000; } push_list[x]->client->ps.powerups[PW_DISINT_4] = push_list[x]->client->ps.forceHandExtendTime + 200; - if (pull) - { + if (pull) { push_list[x]->client->ps.powerups[PW_PULL] = push_list[x]->client->ps.powerups[PW_DISINT_4]; - } - else - { + } else { push_list[x]->client->ps.powerups[PW_PULL] = 0; } - //Make a counter-throw effect + // Make a counter-throw effect - if (otherPushPower >= modPowerLevel) - { + if (otherPushPower >= modPowerLevel) { pushPowerMod = 0; canPullWeapon = qfalse; - } - else - { + } else { int powerDif = (modPowerLevel - otherPushPower); - if (powerDif >= 3) - { - pushPowerMod -= pushPowerMod*0.2; - } - else if (powerDif == 2) - { - pushPowerMod -= pushPowerMod*0.4; - } - else if (powerDif == 1) - { - pushPowerMod -= pushPowerMod*0.8; + if (powerDif >= 3) { + pushPowerMod -= pushPowerMod * 0.2; + } else if (powerDif == 2) { + pushPowerMod -= pushPowerMod * 0.4; + } else if (powerDif == 1) { + pushPowerMod -= pushPowerMod * 0.8; } - if (pushPowerMod < 0) - { + if (pushPowerMod < 0) { pushPowerMod = 0; } } } - //shove them - if ( pull ) - { - VectorSubtract( self->client->ps.origin, thispush_org, pushDir ); + // shove them + if (pull) { + VectorSubtract(self->client->ps.origin, thispush_org, pushDir); - if (push_list[x]->client && VectorLength(pushDir) <= 256) - { + if (push_list[x]->client && VectorLength(pushDir) <= 256) { int randfact = 0; - if (modPowerLevel == FORCE_LEVEL_1) - { + if (modPowerLevel == FORCE_LEVEL_1) { randfact = 3; - } - else if (modPowerLevel == FORCE_LEVEL_2) - { + } else if (modPowerLevel == FORCE_LEVEL_2) { randfact = 7; - } - else if (modPowerLevel == FORCE_LEVEL_3) - { + } else if (modPowerLevel == FORCE_LEVEL_3) { randfact = 10; } - if (!OnSameTeam(self, push_list[x]) && Q_irand(1, 10) <= randfact && canPullWeapon) - { + if (!OnSameTeam(self, push_list[x]) && Q_irand(1, 10) <= randfact && canPullWeapon) { vec3_t uorg, vecnorm; VectorCopy(self->client->ps.origin, uorg); @@ -3469,36 +2843,26 @@ void ForceThrow( gentity_t *self, qboolean pull ) TossClientWeapon(push_list[x], vecnorm, 500); } } - } - else - { - VectorSubtract( thispush_org, self->client->ps.origin, pushDir ); + } else { + VectorSubtract(thispush_org, self->client->ps.origin, pushDir); } - if ((modPowerLevel > otherPushPower || push_list[x]->client->ps.m_iVehicleNum) && push_list[x]->client) - { - if (modPowerLevel == FORCE_LEVEL_3 && - push_list[x]->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) - { + if ((modPowerLevel > otherPushPower || push_list[x]->client->ps.m_iVehicleNum) && push_list[x]->client) { + if (modPowerLevel == FORCE_LEVEL_3 && push_list[x]->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN) { dirLen = VectorLength(pushDir); if (BG_KnockDownable(&push_list[x]->client->ps) && - dirLen <= (64*((modPowerLevel - otherPushPower)-1))) - { //can only do a knockdown if fairly close + dirLen <= (64 * ((modPowerLevel - otherPushPower) - 1))) { // can only do a knockdown if fairly close push_list[x]->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; push_list[x]->client->ps.forceHandExtendTime = level.time + 700; - push_list[x]->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim + push_list[x]->client->ps.forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim push_list[x]->client->ps.quickerGetup = qtrue; - } - else if (push_list[x]->s.number < MAX_CLIENTS && push_list[x]->client->ps.m_iVehicleNum && - dirLen <= 128.0f ) - { //a player on a vehicle + } else if (push_list[x]->s.number < MAX_CLIENTS && push_list[x]->client->ps.m_iVehicleNum && dirLen <= 128.0f) { // a player on a + // vehicle gentity_t *vehEnt = &g_entities[push_list[x]->client->ps.m_iVehicleNum]; - if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) - { + if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) { if (vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_SPEEDER || - vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) - { //push the guy off + vehEnt->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL) { // push the guy off vehEnt->m_pVehicle->m_pVehicleInfo->Eject(vehEnt->m_pVehicle, (bgEntity_t *)push_list[x], qfalse); } } @@ -3506,25 +2870,21 @@ void ForceThrow( gentity_t *self, qboolean pull ) } } - if (!dirLen) - { + if (!dirLen) { dirLen = VectorLength(pushDir); } VectorNormalize(pushDir); - if (push_list[x]->client) - { - //escape a force grip if we're in one - if (self->client->ps.fd.forceGripBeingGripped > level.time) - { //force the enemy to stop gripping me if I managed to push him - if (push_list[x]->client->ps.fd.forceGripEntityNum == self->s.number) - { - if (modPowerLevel >= push_list[x]->client->ps.fd.forcePowerLevel[FP_GRIP]) - { //only break the grip if our push/pull level is >= their grip level + if (push_list[x]->client) { + // escape a force grip if we're in one + if (self->client->ps.fd.forceGripBeingGripped > level.time) { // force the enemy to stop gripping me if I managed to push him + if (push_list[x]->client->ps.fd.forceGripEntityNum == self->s.number) { + if (modPowerLevel >= + push_list[x]->client->ps.fd.forcePowerLevel[FP_GRIP]) { // only break the grip if our push/pull level is >= their grip level WP_ForcePowerStop(push_list[x], FP_GRIP); self->client->ps.fd.forceGripBeingGripped = 0; - push_list[x]->client->ps.fd.forceGripUseTime = level.time + 1000; //since we just broke out of it.. + push_list[x]->client->ps.fd.forceGripUseTime = level.time + 1000; // since we just broke out of it.. } } } @@ -3533,157 +2893,123 @@ void ForceThrow( gentity_t *self, qboolean pull ) push_list[x]->client->ps.otherKillerTime = level.time + 5000; push_list[x]->client->ps.otherKillerDebounceTime = level.time + 100; - pushPowerMod -= (dirLen*0.7); - if (pushPowerMod < 16) - { + pushPowerMod -= (dirLen * 0.7); + if (pushPowerMod < 16) { pushPowerMod = 16; } - //fullbody push effect + // fullbody push effect push_list[x]->client->pushEffectTime = level.time + 600; - push_list[x]->client->ps.velocity[0] = pushDir[0]*pushPowerMod; - push_list[x]->client->ps.velocity[1] = pushDir[1]*pushPowerMod; + push_list[x]->client->ps.velocity[0] = pushDir[0] * pushPowerMod; + push_list[x]->client->ps.velocity[1] = pushDir[1] * pushPowerMod; - if ((int)push_list[x]->client->ps.velocity[2] == 0) - { //if not going anywhere vertically, boost them up a bit - push_list[x]->client->ps.velocity[2] = pushDir[2]*pushPowerMod; + if ((int)push_list[x]->client->ps.velocity[2] == 0) { // if not going anywhere vertically, boost them up a bit + push_list[x]->client->ps.velocity[2] = pushDir[2] * pushPowerMod; - if (push_list[x]->client->ps.velocity[2] < 128) - { + if (push_list[x]->client->ps.velocity[2] < 128) { push_list[x]->client->ps.velocity[2] = 128; } - } - else - { - push_list[x]->client->ps.velocity[2] = pushDir[2]*pushPowerMod; + } else { + push_list[x]->client->ps.velocity[2] = pushDir[2] * pushPowerMod; } } - } - else if ( push_list[x]->s.eType == ET_MISSILE && push_list[x]->s.pos.trType != TR_STATIONARY && (push_list[x]->s.pos.trType != TR_INTERPOLATE||push_list[x]->s.weapon != WP_THERMAL) )//rolling and stationary thermal detonators are dealt with below + } else if (push_list[x]->s.eType == ET_MISSILE && push_list[x]->s.pos.trType != TR_STATIONARY && + (push_list[x]->s.pos.trType != TR_INTERPOLATE || + push_list[x]->s.weapon != WP_THERMAL)) // rolling and stationary thermal detonators are dealt with below { - if ( pull ) - {//deflect rather than reflect? - } - else - { - G_ReflectMissile( self, push_list[x], forward ); + if (pull) { // deflect rather than reflect? + } else { + G_ReflectMissile(self, push_list[x], forward); } - } - else if ( !Q_stricmp( "func_static", push_list[x]->classname ) ) - {//force-usable func_static - if ( !pull && (push_list[x]->spawnflags&1/*F_PUSH*/) ) - { - GEntity_UseFunc( push_list[x], self, self ); + } else if (!Q_stricmp("func_static", push_list[x]->classname)) { // force-usable func_static + if (!pull && (push_list[x]->spawnflags & 1 /*F_PUSH*/)) { + GEntity_UseFunc(push_list[x], self, self); + } else if (pull && (push_list[x]->spawnflags & 2 /*F_PULL*/)) { + GEntity_UseFunc(push_list[x], self, self); } - else if ( pull && (push_list[x]->spawnflags&2/*F_PULL*/) ) - { - GEntity_UseFunc( push_list[x], self, self ); - } - } - else if ( !Q_stricmp( "func_door", push_list[x]->classname ) && (push_list[x]->spawnflags&2) ) - {//push/pull the door - vec3_t pos1, pos2; - vec3_t trFrom; + } else if (!Q_stricmp("func_door", push_list[x]->classname) && (push_list[x]->spawnflags & 2)) { // push/pull the door + vec3_t pos1, pos2; + vec3_t trFrom; VectorCopy(self->client->ps.origin, trFrom); trFrom[2] += self->client->ps.viewheight; - AngleVectors( self->client->ps.viewangles, forward, NULL, NULL ); - VectorNormalize( forward ); - VectorMA( trFrom, radius, forward, end ); - trap->Trace( &tr, trFrom, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0 ); - if ( tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid ) - {//must be pointing right at it + AngleVectors(self->client->ps.viewangles, forward, NULL, NULL); + VectorNormalize(forward); + VectorMA(trFrom, radius, forward, end); + trap->Trace(&tr, trFrom, vec3_origin, vec3_origin, end, self->s.number, MASK_SHOT, qfalse, 0, 0); + if (tr.entityNum != push_list[x]->s.number || tr.fraction == 1.0 || tr.allsolid || tr.startsolid) { // must be pointing right at it continue; } - if ( VectorCompare( vec3_origin, push_list[x]->s.origin ) ) - {//does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center - VectorSubtract( push_list[x]->r.absmax, push_list[x]->r.absmin, size ); - VectorMA( push_list[x]->r.absmin, 0.5, size, center ); - if ( (push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS1 ) - {//if at pos1 and started open, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos1, center ); + if (VectorCompare(vec3_origin, + push_list[x]->s.origin)) { // does not have an origin brush, so pos1 & pos2 are relative to world origin, need to calc center + VectorSubtract(push_list[x]->r.absmax, push_list[x]->r.absmin, size); + VectorMA(push_list[x]->r.absmin, 0.5, size, center); + if ((push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS1) { // if at pos1 and started open, make sure we get the center where it *started* because we're + // going to add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos1, center); + } else if (!(push_list[x]->spawnflags & 1) && + push_list[x]->moverState == MOVER_POS2) { // if at pos2, make sure we get the center where it *started* because we're going to + // add back in the relative values pos1 and pos2 + VectorSubtract(center, push_list[x]->pos2, center); } - else if ( !(push_list[x]->spawnflags&1) && push_list[x]->moverState == MOVER_POS2 ) - {//if at pos2, make sure we get the center where it *started* because we're going to add back in the relative values pos1 and pos2 - VectorSubtract( center, push_list[x]->pos2, center ); - } - VectorAdd( center, push_list[x]->pos1, pos1 ); - VectorAdd( center, push_list[x]->pos2, pos2 ); - } - else - {//actually has an origin, pos1 and pos2 are absolute - VectorCopy( push_list[x]->r.currentOrigin, center ); - VectorCopy( push_list[x]->pos1, pos1 ); - VectorCopy( push_list[x]->pos2, pos2 ); + VectorAdd(center, push_list[x]->pos1, pos1); + VectorAdd(center, push_list[x]->pos2, pos2); + } else { // actually has an origin, pos1 and pos2 are absolute + VectorCopy(push_list[x]->r.currentOrigin, center); + VectorCopy(push_list[x]->pos1, pos1); + VectorCopy(push_list[x]->pos2, pos2); } - if ( Distance( pos1, trFrom ) < Distance( pos2, trFrom ) ) - {//pos1 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + if (Distance(pos1, trFrom) < Distance(pos2, trFrom)) { // pos1 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } } - } - else - {//pos2 is closer - if ( push_list[x]->moverState == MOVER_POS1 ) - {//at the farthest pos - if ( !pull ) - {//trying to push, but already at farthest point, so screw it + } else { // pos2 is closer + if (push_list[x]->moverState == MOVER_POS1) { // at the farthest pos + if (!pull) { // trying to push, but already at farthest point, so screw it continue; } - } - else if ( push_list[x]->moverState == MOVER_POS2 ) - {//at closest pos - if ( pull ) - {//trying to pull, but already at closest point, so screw it + } else if (push_list[x]->moverState == MOVER_POS2) { // at closest pos + if (pull) { // trying to pull, but already at closest point, so screw it continue; } } } - GEntity_UseFunc( push_list[x], self, self ); - } - else if ( Q_stricmp( "func_button", push_list[x]->classname ) == 0 ) - {//pretend you pushed it - Touch_Button( push_list[x], self, NULL ); + GEntity_UseFunc(push_list[x], self, self); + } else if (Q_stricmp("func_button", push_list[x]->classname) == 0) { // pretend you pushed it + Touch_Button(push_list[x], self, NULL); continue; } } } - //attempt to break any leftover grips - //if we're still in a current grip that wasn't broken by the push, it will still remain + // attempt to break any leftover grips + // if we're still in a current grip that wasn't broken by the push, it will still remain self->client->dangerTime = level.time; self->client->ps.eFlags &= ~EF_INVULNERABLE; self->client->invulnerableTimer = 0; - if (self->client->ps.fd.forceGripBeingGripped > level.time) - { + if (self->client->ps.fd.forceGripBeingGripped > level.time) { self->client->ps.fd.forceGripBeingGripped = 0; } } -void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) -{ +void WP_ForcePowerStop(gentity_t *self, forcePowers_t forcePower) { int wasActive = self->client->ps.fd.forcePowersActive; - self->client->ps.fd.forcePowersActive &= ~( 1 << forcePower ); + self->client->ps.fd.forcePowersActive &= ~(1 << forcePower); - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: self->client->ps.fd.forceHealAmount = 0; self->client->ps.fd.forceHealTime = 0; @@ -3691,9 +3017,8 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) case FP_LEVITATION: break; case FP_SPEED: - if (wasActive & (1 << FP_SPEED)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_2-50], CHAN_VOICE); + if (wasActive & (1 << FP_SPEED)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_2 - 50], CHAN_VOICE); } break; case FP_PUSH: @@ -3701,9 +3026,8 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) case FP_PULL: break; case FP_TELEPATHY: - if (wasActive & (1 << FP_TELEPATHY)) - { - G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distractstop.wav") ); + if (wasActive & (1 << FP_TELEPATHY)) { + G_Sound(self, CHAN_AUTO, G_SoundIndex("sound/weapons/force/distractstop.wav")); } self->client->ps.fd.forceMindtrickTargetIndex = 0; self->client->ps.fd.forceMindtrickTargetIndex2 = 0; @@ -3711,34 +3035,27 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->client->ps.fd.forceMindtrickTargetIndex4 = 0; break; case FP_SEE: - if (wasActive & (1 << FP_SEE)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_5-50], CHAN_VOICE); + if (wasActive & (1 << FP_SEE)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_5 - 50], CHAN_VOICE); } break; case FP_GRIP: self->client->ps.fd.forceGripUseTime = level.time + 3000; - if (self->client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 && - g_entities[self->client->ps.fd.forceGripEntityNum].client && - g_entities[self->client->ps.fd.forceGripEntityNum].health > 0 && - g_entities[self->client->ps.fd.forceGripEntityNum].inuse && - (level.time - g_entities[self->client->ps.fd.forceGripEntityNum].client->ps.fd.forceGripStarted) > 500) - { //if we had our throat crushed in for more than half a second, gasp for air when we're let go - if (wasActive & (1 << FP_GRIP)) - { - G_EntitySound( &g_entities[self->client->ps.fd.forceGripEntityNum], CHAN_VOICE, G_SoundIndex("*gasp.wav") ); + if (self->client->ps.fd.forcePowerLevel[FP_GRIP] > FORCE_LEVEL_1 && g_entities[self->client->ps.fd.forceGripEntityNum].client && + g_entities[self->client->ps.fd.forceGripEntityNum].health > 0 && g_entities[self->client->ps.fd.forceGripEntityNum].inuse && + (level.time - g_entities[self->client->ps.fd.forceGripEntityNum].client->ps.fd.forceGripStarted) > + 500) { // if we had our throat crushed in for more than half a second, gasp for air when we're let go + if (wasActive & (1 << FP_GRIP)) { + G_EntitySound(&g_entities[self->client->ps.fd.forceGripEntityNum], CHAN_VOICE, G_SoundIndex("*gasp.wav")); } } - if (g_entities[self->client->ps.fd.forceGripEntityNum].client && - g_entities[self->client->ps.fd.forceGripEntityNum].inuse) - { + if (g_entities[self->client->ps.fd.forceGripEntityNum].client && g_entities[self->client->ps.fd.forceGripEntityNum].inuse) { g_entities[self->client->ps.fd.forceGripEntityNum].client->ps.forceGripChangeMovetype = PM_NORMAL; } - if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) - { + if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) { self->client->ps.forceHandExtendTime = 0; } @@ -3747,53 +3064,43 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) self->client->ps.powerups[PW_DISINT_4] = 0; break; case FP_LIGHTNING: - if ( self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] < FORCE_LEVEL_2 ) - {//don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) + if (self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] < + FORCE_LEVEL_2) { // don't do it again for 3 seconds, minimum... FIXME: this should be automatic once regeneration is slower (normal) self->client->ps.fd.forcePowerDebounce[FP_LIGHTNING] = level.time + 3000; - } - else - { + } else { self->client->ps.fd.forcePowerDebounce[FP_LIGHTNING] = level.time + 1500; } - if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) - { - self->client->ps.forceHandExtendTime = 0; //reset hand position + if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) { + self->client->ps.forceHandExtendTime = 0; // reset hand position } self->client->ps.activeForcePass = 0; break; case FP_RAGE: self->client->ps.fd.forceRageRecoveryTime = level.time + 10000; - if (wasActive & (1 << FP_RAGE)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3-50], CHAN_VOICE); + if (wasActive & (1 << FP_RAGE)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3 - 50], CHAN_VOICE); } break; case FP_ABSORB: - if (wasActive & (1 << FP_ABSORB)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3-50], CHAN_VOICE); + if (wasActive & (1 << FP_ABSORB)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3 - 50], CHAN_VOICE); } break; case FP_PROTECT: - if (wasActive & (1 << FP_PROTECT)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3-50], CHAN_VOICE); + if (wasActive & (1 << FP_PROTECT)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_3 - 50], CHAN_VOICE); } break; case FP_DRAIN: - if ( self->client->ps.fd.forcePowerLevel[FP_DRAIN] < FORCE_LEVEL_2 ) - {//don't do it again for 3 seconds, minimum... + if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] < FORCE_LEVEL_2) { // don't do it again for 3 seconds, minimum... self->client->ps.fd.forcePowerDebounce[FP_DRAIN] = level.time + 3000; - } - else - { + } else { self->client->ps.fd.forcePowerDebounce[FP_DRAIN] = level.time + 1500; } - if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) - { - self->client->ps.forceHandExtendTime = 0; //reset hand position + if (self->client->ps.forceHandExtend == HANDEXTEND_FORCE_HOLD) { + self->client->ps.forceHandExtendTime = 0; // reset hand position } self->client->ps.activeForcePass = 0; @@ -3802,8 +3109,7 @@ void WP_ForcePowerStop( gentity_t *self, forcePowers_t forcePower ) } } -void DoGripAction(gentity_t *self, forcePowers_t forcePower) -{ +void DoGripAction(gentity_t *self, forcePowers_t forcePower) { gentity_t *gripEnt; int gripLevel = 0; trace_t tr; @@ -3816,13 +3122,11 @@ void DoGripAction(gentity_t *self, forcePowers_t forcePower) gripEnt = &g_entities[self->client->ps.fd.forceGripEntityNum]; - if (!gripEnt || !gripEnt->client || !gripEnt->inuse || gripEnt->health < 1 || !ForcePowerUsableOn(self, gripEnt, FP_GRIP)) - { + if (!gripEnt || !gripEnt->client || !gripEnt->inuse || gripEnt->health < 1 || !ForcePowerUsableOn(self, gripEnt, FP_GRIP)) { WP_ForcePowerStop(self, forcePower); self->client->ps.fd.forceGripEntityNum = ENTITYNUM_NONE; - if (gripEnt && gripEnt->client && gripEnt->inuse) - { + if (gripEnt && gripEnt->client && gripEnt->inuse) { gripEnt->client->ps.forceGripChangeMovetype = PM_NORMAL; } return; @@ -3832,28 +3136,24 @@ void DoGripAction(gentity_t *self, forcePowers_t forcePower) trap->Trace(&tr, self->client->ps.origin, NULL, NULL, gripEnt->client->ps.origin, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - gripLevel = WP_AbsorbConversion(gripEnt, gripEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_GRIP, self->client->ps.fd.forcePowerLevel[FP_GRIP], forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_GRIP]][FP_GRIP]); + gripLevel = WP_AbsorbConversion(gripEnt, gripEnt->client->ps.fd.forcePowerLevel[FP_ABSORB], self, FP_GRIP, self->client->ps.fd.forcePowerLevel[FP_GRIP], + forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_GRIP]][FP_GRIP]); - if (gripLevel == -1) - { + if (gripLevel == -1) { gripLevel = self->client->ps.fd.forcePowerLevel[FP_GRIP]; } - if (!gripLevel) - { + if (!gripLevel) { WP_ForcePowerStop(self, forcePower); return; } - if (VectorLength(a) > MAX_GRIP_DISTANCE) - { + if (VectorLength(a) > MAX_GRIP_DISTANCE) { WP_ForcePowerStop(self, forcePower); return; } - if ( !InFront( gripEnt->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.9f ) && - gripLevel < FORCE_LEVEL_3) - { + if (!InFront(gripEnt->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.9f) && gripLevel < FORCE_LEVEL_3) { WP_ForcePowerStop(self, forcePower); return; } @@ -3866,34 +3166,30 @@ void DoGripAction(gentity_t *self, forcePowers_t forcePower) return; } - if (self->client->ps.fd.forcePowerDebounce[FP_GRIP] < level.time) - { //2 damage per second while choking, resulting in 10 damage total (not including The Squeeze) + if (self->client->ps.fd.forcePowerDebounce[FP_GRIP] < + level.time) { // 2 damage per second while choking, resulting in 10 damage total (not including The Squeeze) self->client->ps.fd.forcePowerDebounce[FP_GRIP] = level.time + 1000; G_Damage(gripEnt, self, self, NULL, NULL, 2, DAMAGE_NO_ARMOR, MOD_FORCE_DARK); } - Jetpack_Off(gripEnt); //make sure the guy being gripped has his jetpack off. + Jetpack_Off(gripEnt); // make sure the guy being gripped has his jetpack off. - if (gripLevel == FORCE_LEVEL_1) - { + if (gripLevel == FORCE_LEVEL_1) { gripEnt->client->ps.fd.forceGripBeingGripped = level.time + 1000; - if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 5000) - { + if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 5000) { WP_ForcePowerStop(self, forcePower); } return; } - if (gripLevel == FORCE_LEVEL_2) - { + if (gripLevel == FORCE_LEVEL_2) { gripEnt->client->ps.fd.forceGripBeingGripped = level.time + 1000; - if (gripEnt->client->ps.forceGripMoveInterval < level.time) - { + if (gripEnt->client->ps.forceGripMoveInterval < level.time) { gripEnt->client->ps.velocity[2] = 30; - gripEnt->client->ps.forceGripMoveInterval = level.time + 300; //only update velocity every 300ms, so as to avoid heavy bandwidth usage + gripEnt->client->ps.forceGripMoveInterval = level.time + 300; // only update velocity every 300ms, so as to avoid heavy bandwidth usage } gripEnt->client->ps.otherKiller = self->s.number; @@ -3902,31 +3198,27 @@ void DoGripAction(gentity_t *self, forcePowers_t forcePower) gripEnt->client->ps.forceGripChangeMovetype = PM_FLOAT; - if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 3000 && !self->client->ps.fd.forceGripDamageDebounceTime) - { //if we managed to lift him into the air for 2 seconds, give him a crack + if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 3000 && + !self->client->ps.fd.forceGripDamageDebounceTime) { // if we managed to lift him into the air for 2 seconds, give him a crack self->client->ps.fd.forceGripDamageDebounceTime = 1; G_Damage(gripEnt, self, self, NULL, NULL, 20, DAMAGE_NO_ARMOR, MOD_FORCE_DARK); - //Must play custom sounds on the actual entity. Don't use G_Sound (it creates a temp entity for the sound) - G_EntitySound( gripEnt, CHAN_VOICE, G_SoundIndex(va( "*choke%d.wav", Q_irand( 1, 3 ) )) ); + // Must play custom sounds on the actual entity. Don't use G_Sound (it creates a temp entity for the sound) + G_EntitySound(gripEnt, CHAN_VOICE, G_SoundIndex(va("*choke%d.wav", Q_irand(1, 3)))); gripEnt->client->ps.forceHandExtend = HANDEXTEND_CHOKE; gripEnt->client->ps.forceHandExtendTime = level.time + 2000; - if (gripEnt->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) - { //choking, so don't let him keep gripping himself + if (gripEnt->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) { // choking, so don't let him keep gripping himself WP_ForcePowerStop(gripEnt, FP_GRIP); } - } - else if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 4000) - { + } else if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 4000) { WP_ForcePowerStop(self, forcePower); } return; } - if (gripLevel == FORCE_LEVEL_3) - { + if (gripLevel == FORCE_LEVEL_3) { gripEnt->client->ps.fd.forceGripBeingGripped = level.time + 1000; gripEnt->client->ps.otherKiller = self->s.number; @@ -3935,91 +3227,76 @@ void DoGripAction(gentity_t *self, forcePowers_t forcePower) gripEnt->client->ps.forceGripChangeMovetype = PM_FLOAT; - if (gripEnt->client->ps.forceGripMoveInterval < level.time) - { + if (gripEnt->client->ps.forceGripMoveInterval < level.time) { float nvLen = 0; VectorCopy(gripEnt->client->ps.origin, start_o); AngleVectors(self->client->ps.viewangles, fwd, NULL, NULL); - fwd_o[0] = self->client->ps.origin[0] + fwd[0]*128; - fwd_o[1] = self->client->ps.origin[1] + fwd[1]*128; - fwd_o[2] = self->client->ps.origin[2] + fwd[2]*128; + fwd_o[0] = self->client->ps.origin[0] + fwd[0] * 128; + fwd_o[1] = self->client->ps.origin[1] + fwd[1] * 128; + fwd_o[2] = self->client->ps.origin[2] + fwd[2] * 128; fwd_o[2] += 16; VectorSubtract(fwd_o, start_o, nvel); nvLen = VectorLength(nvel); - if (nvLen < 16) - { //within x units of desired spot + if (nvLen < 16) { // within x units of desired spot VectorNormalize(nvel); - gripEnt->client->ps.velocity[0] = nvel[0]*8; - gripEnt->client->ps.velocity[1] = nvel[1]*8; - gripEnt->client->ps.velocity[2] = nvel[2]*8; - } - else if (nvLen < 64) - { + gripEnt->client->ps.velocity[0] = nvel[0] * 8; + gripEnt->client->ps.velocity[1] = nvel[1] * 8; + gripEnt->client->ps.velocity[2] = nvel[2] * 8; + } else if (nvLen < 64) { VectorNormalize(nvel); - gripEnt->client->ps.velocity[0] = nvel[0]*128; - gripEnt->client->ps.velocity[1] = nvel[1]*128; - gripEnt->client->ps.velocity[2] = nvel[2]*128; - } - else if (nvLen < 128) - { + gripEnt->client->ps.velocity[0] = nvel[0] * 128; + gripEnt->client->ps.velocity[1] = nvel[1] * 128; + gripEnt->client->ps.velocity[2] = nvel[2] * 128; + } else if (nvLen < 128) { VectorNormalize(nvel); - gripEnt->client->ps.velocity[0] = nvel[0]*256; - gripEnt->client->ps.velocity[1] = nvel[1]*256; - gripEnt->client->ps.velocity[2] = nvel[2]*256; - } - else if (nvLen < 200) - { + gripEnt->client->ps.velocity[0] = nvel[0] * 256; + gripEnt->client->ps.velocity[1] = nvel[1] * 256; + gripEnt->client->ps.velocity[2] = nvel[2] * 256; + } else if (nvLen < 200) { VectorNormalize(nvel); - gripEnt->client->ps.velocity[0] = nvel[0]*512; - gripEnt->client->ps.velocity[1] = nvel[1]*512; - gripEnt->client->ps.velocity[2] = nvel[2]*512; - } - else - { + gripEnt->client->ps.velocity[0] = nvel[0] * 512; + gripEnt->client->ps.velocity[1] = nvel[1] * 512; + gripEnt->client->ps.velocity[2] = nvel[2] * 512; + } else { VectorNormalize(nvel); - gripEnt->client->ps.velocity[0] = nvel[0]*700; - gripEnt->client->ps.velocity[1] = nvel[1]*700; - gripEnt->client->ps.velocity[2] = nvel[2]*700; + gripEnt->client->ps.velocity[0] = nvel[0] * 700; + gripEnt->client->ps.velocity[1] = nvel[1] * 700; + gripEnt->client->ps.velocity[2] = nvel[2] * 700; } - gripEnt->client->ps.forceGripMoveInterval = level.time + 300; //only update velocity every 300ms, so as to avoid heavy bandwidth usage + gripEnt->client->ps.forceGripMoveInterval = level.time + 300; // only update velocity every 300ms, so as to avoid heavy bandwidth usage } - if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 3000 && !self->client->ps.fd.forceGripDamageDebounceTime) - { //if we managed to lift him into the air for 2 seconds, give him a crack + if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 3000 && + !self->client->ps.fd.forceGripDamageDebounceTime) { // if we managed to lift him into the air for 2 seconds, give him a crack self->client->ps.fd.forceGripDamageDebounceTime = 1; G_Damage(gripEnt, self, self, NULL, NULL, 40, DAMAGE_NO_ARMOR, MOD_FORCE_DARK); - //Must play custom sounds on the actual entity. Don't use G_Sound (it creates a temp entity for the sound) - G_EntitySound( gripEnt, CHAN_VOICE, G_SoundIndex(va( "*choke%d.wav", Q_irand( 1, 3 ) )) ); + // Must play custom sounds on the actual entity. Don't use G_Sound (it creates a temp entity for the sound) + G_EntitySound(gripEnt, CHAN_VOICE, G_SoundIndex(va("*choke%d.wav", Q_irand(1, 3)))); gripEnt->client->ps.forceHandExtend = HANDEXTEND_CHOKE; gripEnt->client->ps.forceHandExtendTime = level.time + 2000; - if (gripEnt->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) - { //choking, so don't let him keep gripping himself + if (gripEnt->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) { // choking, so don't let him keep gripping himself WP_ForcePowerStop(gripEnt, FP_GRIP); } - } - else if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 4000) - { + } else if ((level.time - gripEnt->client->ps.fd.forceGripStarted) > 4000) { WP_ForcePowerStop(self, forcePower); } return; } } -qboolean G_IsMindTricked(forcedata_t *fd, int client) -{ +qboolean G_IsMindTricked(forcedata_t *fd, int client) { int checkIn; int trickIndex1, trickIndex2, trickIndex3, trickIndex4; int sub = 0; - if (!fd) - { + if (!fd) { return qfalse; } @@ -4028,55 +3305,38 @@ qboolean G_IsMindTricked(forcedata_t *fd, int client) trickIndex3 = fd->forceMindtrickTargetIndex3; trickIndex4 = fd->forceMindtrickTargetIndex4; - if (client > 47) - { + if (client > 47) { checkIn = trickIndex4; sub = 48; - } - else if (client > 31) - { + } else if (client > 31) { checkIn = trickIndex3; sub = 32; - } - else if (client > 15) - { + } else if (client > 15) { checkIn = trickIndex2; sub = 16; - } - else - { + } else { checkIn = trickIndex1; } - if (checkIn & (1 << (client-sub))) - { + if (checkIn & (1 << (client - sub))) { return qtrue; } return qfalse; } -static void RemoveTrickedEnt(forcedata_t *fd, int client) -{ - if (!fd) - { +static void RemoveTrickedEnt(forcedata_t *fd, int client) { + if (!fd) { return; } - if (client > 47) - { - fd->forceMindtrickTargetIndex4 &= ~(1 << (client-48)); - } - else if (client > 31) - { - fd->forceMindtrickTargetIndex3 &= ~(1 << (client-32)); - } - else if (client > 15) - { - fd->forceMindtrickTargetIndex2 &= ~(1 << (client-16)); - } - else - { + if (client > 47) { + fd->forceMindtrickTargetIndex4 &= ~(1 << (client - 48)); + } else if (client > 31) { + fd->forceMindtrickTargetIndex3 &= ~(1 << (client - 32)); + } else if (client > 15) { + fd->forceMindtrickTargetIndex2 &= ~(1 << (client - 16)); + } else { fd->forceMindtrickTargetIndex &= ~(1 << client); } } @@ -4084,31 +3344,21 @@ static void RemoveTrickedEnt(forcedata_t *fd, int client) extern int g_LastFrameTime; extern int g_TimeSinceLastFrame; -static void WP_UpdateMindtrickEnts(gentity_t *self) -{ +static void WP_UpdateMindtrickEnts(gentity_t *self) { int i = 0; - while (i < MAX_CLIENTS) - { - if (G_IsMindTricked(&self->client->ps.fd, i)) - { + while (i < MAX_CLIENTS) { + if (G_IsMindTricked(&self->client->ps.fd, i)) { gentity_t *ent = &g_entities[i]; - if ( !ent || !ent->client || !ent->inuse || ent->health < 1 || - (ent->client->ps.fd.forcePowersActive & (1 << FP_SEE)) ) - { + if (!ent || !ent->client || !ent->inuse || ent->health < 1 || (ent->client->ps.fd.forcePowersActive & (1 << FP_SEE))) { RemoveTrickedEnt(&self->client->ps.fd, i); - } - else if ((level.time - self->client->dangerTime) < g_TimeSinceLastFrame*4) - { //Untrick this entity if the tricker (self) fires while in his fov + } else if ((level.time - self->client->dangerTime) < g_TimeSinceLastFrame * 4) { // Untrick this entity if the tricker (self) fires while in his fov if (trap->InPVS(ent->client->ps.origin, self->client->ps.origin) && - OrgVisible(ent->client->ps.origin, self->client->ps.origin, ent->s.number)) - { + OrgVisible(ent->client->ps.origin, self->client->ps.origin, ent->s.number)) { RemoveTrickedEnt(&self->client->ps.fd, i); } - } - else if (BG_HasYsalamiri(level.gametype, &ent->client->ps)) - { + } else if (BG_HasYsalamiri(level.gametype, &ent->client->ps)) { RemoveTrickedEnt(&self->client->ps.fd, i); } } @@ -4116,77 +3366,61 @@ static void WP_UpdateMindtrickEnts(gentity_t *self) i++; } - if (!self->client->ps.fd.forceMindtrickTargetIndex && - !self->client->ps.fd.forceMindtrickTargetIndex2 && - !self->client->ps.fd.forceMindtrickTargetIndex3 && - !self->client->ps.fd.forceMindtrickTargetIndex4) - { //everyone who we had tricked is no longer tricked, so stop the power + if (!self->client->ps.fd.forceMindtrickTargetIndex && !self->client->ps.fd.forceMindtrickTargetIndex2 && !self->client->ps.fd.forceMindtrickTargetIndex3 && + !self->client->ps.fd.forceMindtrickTargetIndex4) { // everyone who we had tricked is no longer tricked, so stop the power WP_ForcePowerStop(self, FP_TELEPATHY); - } - else if (self->client->ps.powerups[PW_REDFLAG] || - self->client->ps.powerups[PW_BLUEFLAG]) - { + } else if (self->client->ps.powerups[PW_REDFLAG] || self->client->ps.powerups[PW_BLUEFLAG]) { WP_ForcePowerStop(self, FP_TELEPATHY); } } #define FORCE_DEBOUNCE_TIME 50 // sv_fps 20 = 50msec frametime, basejka balance/timing -static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd ) -{ -// extern usercmd_t ucmd; +static void WP_ForcePowerRun(gentity_t *self, forcePowers_t forcePower, usercmd_t *cmd) { + // extern usercmd_t ucmd; - switch( (int)forcePower ) - { + switch ((int)forcePower) { case FP_HEAL: - if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_1) - { - if (self->client->ps.velocity[0] || self->client->ps.velocity[1] || self->client->ps.velocity[2]) - { - WP_ForcePowerStop( self, forcePower ); + if (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_1) { + if (self->client->ps.velocity[0] || self->client->ps.velocity[1] || self->client->ps.velocity[2]) { + WP_ForcePowerStop(self, forcePower); break; } } - if (self->health < 1 || self->client->ps.stats[STAT_HEALTH] < 1) - { - WP_ForcePowerStop( self, forcePower ); + if (self->health < 1 || self->client->ps.stats[STAT_HEALTH] < 1) { + WP_ForcePowerStop(self, forcePower); break; } - if (self->client->ps.fd.forceHealTime > level.time) - { + if (self->client->ps.fd.forceHealTime > level.time) { break; } - if ( self->health > self->client->ps.stats[STAT_MAX_HEALTH]) - { //rww - we might start out over max_health and we don't want force heal taking us down to 100 or whatever max_health is - WP_ForcePowerStop( self, forcePower ); + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) { // rww - we might start out over max_health and we don't want force heal taking us down to + // 100 or whatever max_health is + WP_ForcePowerStop(self, forcePower); break; } self->client->ps.fd.forceHealTime = level.time + 1000; self->health++; self->client->ps.fd.forceHealAmount++; - if ( self->health > self->client->ps.stats[STAT_MAX_HEALTH]) // Past max health + if (self->health > self->client->ps.stats[STAT_MAX_HEALTH]) // Past max health { self->health = self->client->ps.stats[STAT_MAX_HEALTH]; - WP_ForcePowerStop( self, forcePower ); + WP_ForcePowerStop(self, forcePower); } - if ( (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_1 && self->client->ps.fd.forceHealAmount >= 25) || - (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_2 && self->client->ps.fd.forceHealAmount >= 33)) - { - WP_ForcePowerStop( self, forcePower ); + if ((self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_1 && self->client->ps.fd.forceHealAmount >= 25) || + (self->client->ps.fd.forcePowerLevel[FP_HEAL] == FORCE_LEVEL_2 && self->client->ps.fd.forceHealAmount >= 33)) { + WP_ForcePowerStop(self, forcePower); } break; case FP_SPEED: - //This is handled in PM_WalkMove and PM_StepSlideMove - if ( self->client->holdingObjectiveItem >= MAX_CLIENTS - && self->client->holdingObjectiveItem < ENTITYNUM_WORLD ) - { - if ( g_entities[self->client->holdingObjectiveItem].genericValue15 ) - {//disables force powers - WP_ForcePowerStop( self, forcePower ); + // This is handled in PM_WalkMove and PM_StepSlideMove + if (self->client->holdingObjectiveItem >= MAX_CLIENTS && self->client->holdingObjectiveItem < ENTITYNUM_WORLD) { + if (g_entities[self->client->holdingObjectiveItem].genericValue15) { // disables force powers + WP_ForcePowerStop(self, forcePower); } } /* @@ -4199,20 +3433,18 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd */ break; case FP_GRIP: - if (self->client->ps.forceHandExtend != HANDEXTEND_FORCE_HOLD) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_FORCE_HOLD) { WP_ForcePowerStop(self, FP_GRIP); break; } - if (self->client->ps.fd.forcePowerDebounce[FP_PULL] < level.time) - { //This is sort of not ideal. Using the debounce value reserved for pull for this because pull doesn't need it. - BG_ForcePowerDrain( &self->client->ps, forcePower, 1 ); + if (self->client->ps.fd.forcePowerDebounce[FP_PULL] < + level.time) { // This is sort of not ideal. Using the debounce value reserved for pull for this because pull doesn't need it. + BG_ForcePowerDrain(&self->client->ps, forcePower, 1); self->client->ps.fd.forcePowerDebounce[FP_PULL] = level.time + 100; } - if (self->client->ps.fd.forcePower < 1) - { + if (self->client->ps.fd.forcePower < 1) { WP_ForcePowerStop(self, FP_GRIP); break; } @@ -4220,40 +3452,31 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd DoGripAction(self, forcePower); break; case FP_LEVITATION: - if ( self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.fd.forceJumpZStart ) - {//done with jump - WP_ForcePowerStop( self, forcePower ); + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.fd.forceJumpZStart) { // done with jump + WP_ForcePowerStop(self, forcePower); } break; case FP_RAGE: - if (self->health < 1) - { + if (self->health < 1) { WP_ForcePowerStop(self, forcePower); break; } - if (self->client->ps.forceRageDrainTime < level.time) - { + if (self->client->ps.forceRageDrainTime < level.time) { int addTime = 400; self->health -= 2; - if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_1) { addTime = 150; - } - else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_2) { addTime = 300; - } - else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_RAGE] == FORCE_LEVEL_3) { addTime = 450; } self->client->ps.forceRageDrainTime = level.time + addTime; } - if (self->health < 1) - { + if (self->health < 1) { self->health = 1; WP_ForcePowerStop(self, forcePower); } @@ -4261,73 +3484,59 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd self->client->ps.stats[STAT_HEALTH] = self->health; break; case FP_DRAIN: - if (self->client->ps.forceHandExtend != HANDEXTEND_FORCE_HOLD) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_FORCE_HOLD) { WP_ForcePowerStop(self, forcePower); break; } - if ( self->client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1 ) - {//higher than level 1 - if ( (cmd->buttons & BUTTON_FORCE_DRAIN) || ((cmd->buttons & BUTTON_FORCEPOWER) && self->client->ps.fd.forcePowerSelected == FP_DRAIN) ) - {//holding it keeps it going + if (self->client->ps.fd.forcePowerLevel[FP_DRAIN] > FORCE_LEVEL_1) { // higher than level 1 + if ((cmd->buttons & BUTTON_FORCE_DRAIN) || + ((cmd->buttons & BUTTON_FORCEPOWER) && self->client->ps.fd.forcePowerSelected == FP_DRAIN)) { // holding it keeps it going self->client->ps.fd.forcePowerDuration[FP_DRAIN] = level.time + 500; } } // OVERRIDEFIXME - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) || self->client->ps.fd.forcePowerDuration[FP_DRAIN] < level.time || - self->client->ps.fd.forcePower < 25) - { - WP_ForcePowerStop( self, forcePower ); - } - else - { - while ( self->client->force.drainDebounce < level.time ) - { - ForceShootDrain( self ); + if (!WP_ForcePowerAvailable(self, forcePower, 0) || self->client->ps.fd.forcePowerDuration[FP_DRAIN] < level.time || + self->client->ps.fd.forcePower < 25) { + WP_ForcePowerStop(self, forcePower); + } else { + while (self->client->force.drainDebounce < level.time) { + ForceShootDrain(self); self->client->force.drainDebounce += FORCE_DEBOUNCE_TIME; } } break; case FP_LIGHTNING: - if (self->client->ps.forceHandExtend != HANDEXTEND_FORCE_HOLD) - { //Animation for hand extend doesn't end with hand out, so we have to limit lightning intervals by animation intervals (once hand starts to go in in animation, lightning should stop) + if (self->client->ps.forceHandExtend != + HANDEXTEND_FORCE_HOLD) { // Animation for hand extend doesn't end with hand out, so we have to limit lightning intervals by animation intervals + // (once hand starts to go in in animation, lightning should stop) WP_ForcePowerStop(self, forcePower); break; } - if ( self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1 ) - {//higher than level 1 - if ( (cmd->buttons & BUTTON_FORCE_LIGHTNING) || ((cmd->buttons & BUTTON_FORCEPOWER) && self->client->ps.fd.forcePowerSelected == FP_LIGHTNING) ) - {//holding it keeps it going + if (self->client->ps.fd.forcePowerLevel[FP_LIGHTNING] > FORCE_LEVEL_1) { // higher than level 1 + if ((cmd->buttons & BUTTON_FORCE_LIGHTNING) || + ((cmd->buttons & BUTTON_FORCEPOWER) && self->client->ps.fd.forcePowerSelected == FP_LIGHTNING)) { // holding it keeps it going self->client->ps.fd.forcePowerDuration[FP_LIGHTNING] = level.time + 500; } } // OVERRIDEFIXME - if ( !WP_ForcePowerAvailable( self, forcePower, 0 ) || self->client->ps.fd.forcePowerDuration[FP_LIGHTNING] < level.time || - self->client->ps.fd.forcePower < 25) - { - WP_ForcePowerStop( self, forcePower ); - } - else - { - while ( self->client->force.lightningDebounce < level.time ) - { - ForceShootLightning( self ); - BG_ForcePowerDrain( &self->client->ps, forcePower, 0 ); + if (!WP_ForcePowerAvailable(self, forcePower, 0) || self->client->ps.fd.forcePowerDuration[FP_LIGHTNING] < level.time || + self->client->ps.fd.forcePower < 25) { + WP_ForcePowerStop(self, forcePower); + } else { + while (self->client->force.lightningDebounce < level.time) { + ForceShootLightning(self); + BG_ForcePowerDrain(&self->client->ps, forcePower, 0); self->client->force.lightningDebounce += FORCE_DEBOUNCE_TIME; } } break; case FP_TELEPATHY: - if ( self->client->holdingObjectiveItem >= MAX_CLIENTS - && self->client->holdingObjectiveItem < ENTITYNUM_WORLD - && g_entities[self->client->holdingObjectiveItem].genericValue15 ) - { //if force hindered can't mindtrick whilst carrying a siege item - WP_ForcePowerStop( self, FP_TELEPATHY ); - } - else - { + if (self->client->holdingObjectiveItem >= MAX_CLIENTS && self->client->holdingObjectiveItem < ENTITYNUM_WORLD && + g_entities[self->client->holdingObjectiveItem].genericValue15) { // if force hindered can't mindtrick whilst carrying a siege item + WP_ForcePowerStop(self, FP_TELEPATHY); + } else { WP_UpdateMindtrickEnts(self); } break; @@ -4338,11 +3547,9 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd case FP_SABERTHROW: break; case FP_PROTECT: - if (self->client->ps.fd.forcePowerDebounce[forcePower] < level.time) - { - BG_ForcePowerDrain( &self->client->ps, forcePower, 1 ); - if (self->client->ps.fd.forcePower < 1) - { + if (self->client->ps.fd.forcePowerDebounce[forcePower] < level.time) { + BG_ForcePowerDrain(&self->client->ps, forcePower, 1); + if (self->client->ps.fd.forcePower < 1) { WP_ForcePowerStop(self, forcePower); } @@ -4350,11 +3557,9 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } break; case FP_ABSORB: - if (self->client->ps.fd.forcePowerDebounce[forcePower] < level.time) - { - BG_ForcePowerDrain( &self->client->ps, forcePower, 1 ); - if (self->client->ps.fd.forcePower < 1) - { + if (self->client->ps.fd.forcePowerDebounce[forcePower] < level.time) { + BG_ForcePowerDrain(&self->client->ps, forcePower, 1); + if (self->client->ps.fd.forcePower < 1) { WP_ForcePowerStop(self, forcePower); } @@ -4366,68 +3571,55 @@ static void WP_ForcePowerRun( gentity_t *self, forcePowers_t forcePower, usercmd } } -int WP_DoSpecificPower( gentity_t *self, usercmd_t *ucmd, forcePowers_t forcepower) -{ +int WP_DoSpecificPower(gentity_t *self, usercmd_t *ucmd, forcePowers_t forcepower) { int powerSucceeded; powerSucceeded = 1; // OVERRIDEFIXME - if ( !WP_ForcePowerAvailable( self, forcepower, 0 ) ) - { + if (!WP_ForcePowerAvailable(self, forcepower, 0)) { return 0; } - switch(forcepower) - { + switch (forcepower) { case FP_HEAL: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceHeal(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_LEVITATION: - //if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. + // if leave the ground by some other means, cancel the force jump so we don't suddenly jump when we land. - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { self->client->ps.fd.forceJumpCharge = 0; - G_MuteSound( self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE ); - //This only happens if the groundEntityNum == ENTITYNUM_NONE when the button is actually released - } - else - {//still on ground, so jump - ForceJump( self, ucmd ); + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); + // This only happens if the groundEntityNum == ENTITYNUM_NONE when the button is actually released + } else { // still on ground, so jump + ForceJump(self, ucmd); } break; case FP_SPEED: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceSpeed(self, 0); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_GRIP: - if (self->client->ps.fd.forceGripEntityNum == ENTITYNUM_NONE) - { - ForceGrip( self ); + if (self->client->ps.fd.forceGripEntityNum == ENTITYNUM_NONE) { + ForceGrip(self); } - if (self->client->ps.fd.forceGripEntityNum != ENTITYNUM_NONE) - { - if (!(self->client->ps.fd.forcePowersActive & (1 << FP_GRIP))) - { - WP_ForcePowerStart( self, FP_GRIP, 0 ); - BG_ForcePowerDrain( &self->client->ps, FP_GRIP, GRIP_DRAIN_AMOUNT ); + if (self->client->ps.fd.forceGripEntityNum != ENTITYNUM_NONE) { + if (!(self->client->ps.fd.forcePowersActive & (1 << FP_GRIP))) { + WP_ForcePowerStart(self, FP_GRIP, 0); + BG_ForcePowerDrain(&self->client->ps, FP_GRIP, GRIP_DRAIN_AMOUNT); } - } - else - { + } else { powerSucceeded = 0; } break; @@ -4435,72 +3627,64 @@ int WP_DoSpecificPower( gentity_t *self, usercmd_t *ucmd, forcePowers_t forcepow ForceLightning(self); break; case FP_PUSH: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease && !(self->r.svFlags & SVF_BOT)) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease && !(self->r.svFlags & SVF_BOT)) { // need to release before we can use nonhold powers again break; } ForceThrow(self, qfalse); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_PULL: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceThrow(self, qtrue); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_TELEPATHY: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceTelepathy(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_RAGE: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceRage(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_PROTECT: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceProtect(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_ABSORB: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceAbsorb(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_TEAM_HEAL: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceTeamHeal(self); self->client->ps.fd.forceButtonNeedRelease = 1; break; case FP_TEAM_FORCE: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceTeamForceReplenish(self); @@ -4510,9 +3694,8 @@ int WP_DoSpecificPower( gentity_t *self, usercmd_t *ucmd, forcePowers_t forcepow ForceDrain(self); break; case FP_SEE: - powerSucceeded = 0; //always 0 for nonhold powers - if (self->client->ps.fd.forceButtonNeedRelease) - { //need to release before we can use nonhold powers again + powerSucceeded = 0; // always 0 for nonhold powers + if (self->client->ps.fd.forceButtonNeedRelease) { // need to release before we can use nonhold powers again break; } ForceSeeing(self); @@ -4531,8 +3714,7 @@ int WP_DoSpecificPower( gentity_t *self, usercmd_t *ucmd, forcePowers_t forcepow return powerSucceeded; } -void FindGenericEnemyIndex(gentity_t *self) -{ //Find another client that would be considered a threat. +void FindGenericEnemyIndex(gentity_t *self) { // Find another client that would be considered a threat. int i = 0; float tlen; gentity_t *ent; @@ -4540,19 +3722,16 @@ void FindGenericEnemyIndex(gentity_t *self) float blen = 99999999.9f; vec3_t a; - while (i < MAX_CLIENTS) - { + while (i < MAX_CLIENTS) { ent = &g_entities[i]; - if (ent && ent->client && ent->s.number != self->s.number && ent->health > 0 && !OnSameTeam(self, ent) && ent->client->ps.pm_type != PM_INTERMISSION && ent->client->ps.pm_type != PM_SPECTATOR) - { + if (ent && ent->client && ent->s.number != self->s.number && ent->health > 0 && !OnSameTeam(self, ent) && ent->client->ps.pm_type != PM_INTERMISSION && + ent->client->ps.pm_type != PM_SPECTATOR) { VectorSubtract(ent->client->ps.origin, self->client->ps.origin, a); tlen = VectorLength(a); - if (tlen < blen && - InFront(ent->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.8f ) && - OrgVisible(self->client->ps.origin, ent->client->ps.origin, self->s.number)) - { + if (tlen < blen && InFront(ent->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.8f) && + OrgVisible(self->client->ps.origin, ent->client->ps.origin, self->s.number)) { blen = tlen; besten = ent; } @@ -4561,34 +3740,30 @@ void FindGenericEnemyIndex(gentity_t *self) i++; } - if (!besten) - { + if (!besten) { return; } self->client->ps.genericEnemyIndex = besten->s.number; } -void SeekerDroneUpdate(gentity_t *self) -{ +void SeekerDroneUpdate(gentity_t *self) { vec3_t org, elevated, dir, a, endir; gentity_t *en; float angle; float prefig = 0; trace_t tr; - if (!(self->client->ps.eFlags & EF_SEEKERDRONE)) - { + if (!(self->client->ps.eFlags & EF_SEEKERDRONE)) { self->client->ps.genericEnemyIndex = -1; return; } - if (self->health < 1) - { + if (self->health < 1) { VectorCopy(self->client->ps.origin, elevated); elevated[2] += 40; - angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; //magical numbers make magic happen + angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; // magical numbers make magic happen dir[0] = cos(angle) * 20; dir[1] = sin(angle) * 20; dir[2] = cos(angle) * 5; @@ -4606,36 +3781,28 @@ void SeekerDroneUpdate(gentity_t *self) return; } - if (self->client->ps.droneExistTime >= level.time && - self->client->ps.droneExistTime < (level.time+5000)) - { - self->client->ps.genericEnemyIndex = 1024+self->client->ps.droneExistTime; - if (self->client->ps.droneFireTime < level.time) - { - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/laser_trap/warning.wav") ); + if (self->client->ps.droneExistTime >= level.time && self->client->ps.droneExistTime < (level.time + 5000)) { + self->client->ps.genericEnemyIndex = 1024 + self->client->ps.droneExistTime; + if (self->client->ps.droneFireTime < level.time) { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/laser_trap/warning.wav")); self->client->ps.droneFireTime = level.time + 100; } return; - } - else if (self->client->ps.droneExistTime < level.time) - { + } else if (self->client->ps.droneExistTime < level.time) { VectorCopy(self->client->ps.origin, elevated); elevated[2] += 40; - prefig = (self->client->ps.droneExistTime-level.time)/80; + prefig = (self->client->ps.droneExistTime - level.time) / 80; - if (prefig > 55) - { + if (prefig > 55) { prefig = 55; - } - else if (prefig < 1) - { + } else if (prefig < 1) { prefig = 1; } - elevated[2] -= 55-prefig; + elevated[2] -= 55 - prefig; - angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; //magical numbers make magic happen + angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; // magical numbers make magic happen dir[0] = cos(angle) * 20; dir[1] = sin(angle) * 20; dir[2] = cos(angle) * 5; @@ -4653,74 +3820,56 @@ void SeekerDroneUpdate(gentity_t *self) return; } - if (self->client->ps.genericEnemyIndex == -1) - { + if (self->client->ps.genericEnemyIndex == -1) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; } - if (self->client->ps.genericEnemyIndex != ENTITYNUM_NONE && self->client->ps.genericEnemyIndex != -1) - { + if (self->client->ps.genericEnemyIndex != ENTITYNUM_NONE && self->client->ps.genericEnemyIndex != -1) { en = &g_entities[self->client->ps.genericEnemyIndex]; - if (!en || !en->client) - { + if (!en || !en->client) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; - } - else if (en->s.number == self->s.number) - { + } else if (en->s.number == self->s.number) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; - } - else if (en->health < 1) - { + } else if (en->health < 1) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; - } - else if (OnSameTeam(self, en)) - { + } else if (OnSameTeam(self, en)) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; - } - else - { - if (!InFront(en->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.8f )) - { + } else { + if (!InFront(en->client->ps.origin, self->client->ps.origin, self->client->ps.viewangles, 0.8f)) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; - } - else if (!OrgVisible(self->client->ps.origin, en->client->ps.origin, self->s.number)) - { + } else if (!OrgVisible(self->client->ps.origin, en->client->ps.origin, self->s.number)) { self->client->ps.genericEnemyIndex = ENTITYNUM_NONE; } } } - if (self->client->ps.genericEnemyIndex == ENTITYNUM_NONE || self->client->ps.genericEnemyIndex == -1) - { + if (self->client->ps.genericEnemyIndex == ENTITYNUM_NONE || self->client->ps.genericEnemyIndex == -1) { FindGenericEnemyIndex(self); } - if (self->client->ps.genericEnemyIndex != ENTITYNUM_NONE && self->client->ps.genericEnemyIndex != -1) - { + if (self->client->ps.genericEnemyIndex != ENTITYNUM_NONE && self->client->ps.genericEnemyIndex != -1) { en = &g_entities[self->client->ps.genericEnemyIndex]; VectorCopy(self->client->ps.origin, elevated); elevated[2] += 40; - angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; //magical numbers make magic happen + angle = ((level.time / 12) & 255) * (M_PI * 2) / 255; // magical numbers make magic happen dir[0] = cos(angle) * 20; dir[1] = sin(angle) * 20; dir[2] = cos(angle) * 5; VectorAdd(elevated, dir, org); - //org is now where the thing should be client-side because it uses the same time-based offset - if (self->client->ps.droneFireTime < level.time) - { + // org is now where the thing should be client-side because it uses the same time-based offset + if (self->client->ps.droneFireTime < level.time) { trap->Trace(&tr, org, NULL, NULL, en->client->ps.origin, -1, MASK_SOLID, qfalse, 0, 0); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { VectorSubtract(en->client->ps.origin, org, endir); VectorNormalize(endir); WP_FireGenericBlasterMissile(self, org, endir, 0, 15, 2000, MOD_BLASTER); - G_SoundAtLoc( org, CHAN_WEAPON, G_SoundIndex("sound/weapons/bryar/fire.wav") ); + G_SoundAtLoc(org, CHAN_WEAPON, G_SoundIndex("sound/weapons/bryar/fire.wav")); self->client->ps.droneFireTime = level.time + Q_irand(400, 700); } @@ -4728,88 +3877,62 @@ void SeekerDroneUpdate(gentity_t *self) } } -void HolocronUpdate(gentity_t *self) -{ //keep holocron status updated in holocron mode +void HolocronUpdate(gentity_t *self) { // keep holocron status updated in holocron mode int i = 0; int noHRank = 0; - if (noHRank < FORCE_LEVEL_0) - { + if (noHRank < FORCE_LEVEL_0) { noHRank = FORCE_LEVEL_0; } - if (noHRank > FORCE_LEVEL_3) - { + if (noHRank > FORCE_LEVEL_3) { noHRank = FORCE_LEVEL_3; } trap->Cvar_Update(&g_maxHolocronCarry); - while (i < NUM_FORCE_POWERS) - { - if (self->client->ps.holocronsCarried[i]) - { //carrying it, make sure we have the power + while (i < NUM_FORCE_POWERS) { + if (self->client->ps.holocronsCarried[i]) { // carrying it, make sure we have the power self->client->ps.holocronBits |= (1 << i); self->client->ps.fd.forcePowersKnown |= (1 << i); self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_3; - } - else - { //otherwise, make sure the power is cleared from us + } else { // otherwise, make sure the power is cleared from us self->client->ps.fd.forcePowerLevel[i] = 0; - if (self->client->ps.holocronBits & (1 << i)) - { + if (self->client->ps.holocronBits & (1 << i)) { self->client->ps.holocronBits -= (1 << i); } - if ((self->client->ps.fd.forcePowersKnown & (1 << i)) && i != FP_LEVITATION && i != FP_SABER_OFFENSE) - { + if ((self->client->ps.fd.forcePowersKnown & (1 << i)) && i != FP_LEVITATION && i != FP_SABER_OFFENSE) { self->client->ps.fd.forcePowersKnown -= (1 << i); } - if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION && i != FP_SABER_OFFENSE) - { + if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION && i != FP_SABER_OFFENSE) { WP_ForcePowerStop(self, i); } - if (i == FP_LEVITATION) - { - if (noHRank >= FORCE_LEVEL_1) - { + if (i == FP_LEVITATION) { + if (noHRank >= FORCE_LEVEL_1) { self->client->ps.fd.forcePowerLevel[i] = noHRank; - } - else - { + } else { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_1; } - } - else if (i == FP_SABER_OFFENSE) - { + } else if (i == FP_SABER_OFFENSE) { self->client->ps.fd.forcePowersKnown |= (1 << i); - if (noHRank >= FORCE_LEVEL_1) - { + if (noHRank >= FORCE_LEVEL_1) { self->client->ps.fd.forcePowerLevel[i] = noHRank; - } - else - { + } else { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_1; } - //make sure that the player's saber stance is reset so they can't continue to use that stance when they don't have the skill for it anymore. - if ( self->client->saber[0].model[0] && self->client->saber[1].model[0] ) - { //dual + // make sure that the player's saber stance is reset so they can't continue to use that stance when they don't have the skill for it anymore. + if (self->client->saber[0].model[0] && self->client->saber[1].model[0]) { // dual self->client->ps.fd.saberAnimLevelBase = self->client->ps.fd.saberAnimLevel = self->client->ps.fd.saberDrawAnimLevel = SS_DUAL; - } - else if ( (self->client->saber[0].saberFlags & SFL_TWO_HANDED) ) - { //staff + } else if ((self->client->saber[0].saberFlags & SFL_TWO_HANDED)) { // staff self->client->ps.fd.saberAnimLevel = self->client->ps.fd.saberDrawAnimLevel = SS_STAFF; - } - else - { + } else { self->client->ps.fd.saberAnimLevelBase = self->client->ps.fd.saberAnimLevel = self->client->ps.fd.saberDrawAnimLevel = SS_MEDIUM; } - } - else - { + } else { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_0; } } @@ -4817,66 +3940,51 @@ void HolocronUpdate(gentity_t *self) i++; } - if (HasSetSaberOnly()) - { //if saberonly, we get these powers no matter what (still need the holocrons for level 3) - if (self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_1) - { + if (HasSetSaberOnly()) { // if saberonly, we get these powers no matter what (still need the holocrons for level 3) + if (self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] < FORCE_LEVEL_1) { self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] = FORCE_LEVEL_1; } - if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < FORCE_LEVEL_1) { self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] = FORCE_LEVEL_1; } } } -void JediMasterUpdate(gentity_t *self) -{ //keep jedi master status updated for JM gametype +void JediMasterUpdate(gentity_t *self) { // keep jedi master status updated for JM gametype int i = 0; trap->Cvar_Update(&g_maxHolocronCarry); - while (i < NUM_FORCE_POWERS) - { - if (self->client->ps.isJediMaster) - { + while (i < NUM_FORCE_POWERS) { + if (self->client->ps.isJediMaster) { self->client->ps.fd.forcePowersKnown |= (1 << i); self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_3; - if (i == FP_TEAM_HEAL || i == FP_TEAM_FORCE || - i == FP_DRAIN || i == FP_ABSORB) - { //team powers are useless in JM, absorb is too because no one else has powers to absorb. Drain is just - //relatively useless in comparison, because its main intent is not to heal, but rather to cripple others - //by draining their force at the same time. And no one needs force in JM except the JM himself. + if (i == FP_TEAM_HEAL || i == FP_TEAM_FORCE || i == FP_DRAIN || + i == FP_ABSORB) { // team powers are useless in JM, absorb is too because no one else has powers to absorb. Drain is just + // relatively useless in comparison, because its main intent is not to heal, but rather to cripple others + // by draining their force at the same time. And no one needs force in JM except the JM himself. self->client->ps.fd.forcePowersKnown &= ~(1 << i); self->client->ps.fd.forcePowerLevel[i] = 0; } - if (i == FP_TELEPATHY) - { //this decision was made because level 3 mindtrick allows the JM to just hide too much, and no one else has force - //sight to counteract it. Since the JM himself is the focus of gameplay in this mode, having him hidden for large - //durations is indeed a bad thing. + if (i == FP_TELEPATHY) { // this decision was made because level 3 mindtrick allows the JM to just hide too much, and no one else has force + // sight to counteract it. Since the JM himself is the focus of gameplay in this mode, having him hidden for large + // durations is indeed a bad thing. self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_2; } - } - else - { - if ((self->client->ps.fd.forcePowersKnown & (1 << i)) && i != FP_LEVITATION) - { + } else { + if ((self->client->ps.fd.forcePowersKnown & (1 << i)) && i != FP_LEVITATION) { self->client->ps.fd.forcePowersKnown -= (1 << i); } - if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION) - { + if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION) { WP_ForcePowerStop(self, i); } - if (i == FP_LEVITATION) - { + if (i == FP_LEVITATION) { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_1; - } - else - { + } else { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_0; } } @@ -4885,22 +3993,15 @@ void JediMasterUpdate(gentity_t *self) } } -qboolean WP_HasForcePowers( const playerState_t *ps ) -{ +qboolean WP_HasForcePowers(const playerState_t *ps) { int i; - if ( ps ) - { - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( i == FP_LEVITATION ) - { - if ( ps->fd.forcePowerLevel[i] > FORCE_LEVEL_1 ) - { + if (ps) { + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (i == FP_LEVITATION) { + if (ps->fd.forcePowerLevel[i] > FORCE_LEVEL_1) { return qtrue; } - } - else if ( ps->fd.forcePowerLevel[i] > FORCE_LEVEL_0 ) - { + } else if (ps->fd.forcePowerLevel[i] > FORCE_LEVEL_0) { return qtrue; } } @@ -4908,9 +4009,9 @@ qboolean WP_HasForcePowers( const playerState_t *ps ) return qfalse; } -//try a special roll getup move -qboolean G_SpecialRollGetup(gentity_t *self) -{ //fixme: currently no knockdown will actually land you on your front... so froll's are pretty useless at the moment. +// try a special roll getup move +qboolean +G_SpecialRollGetup(gentity_t *self) { // fixme: currently no knockdown will actually land you on your front... so froll's are pretty useless at the moment. qboolean rolled = qfalse; /* @@ -4922,71 +4023,52 @@ qboolean G_SpecialRollGetup(gentity_t *self) */ if (/*!self->client->pers.cmd.upmove &&*/ - self->client->pers.cmd.rightmove > 0 && - !self->client->pers.cmd.forwardmove) - { + self->client->pers.cmd.rightmove > 0 && !self->client->pers.cmd.forwardmove) { G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP_BROLL_R, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); rolled = qtrue; - } - else if (/*!self->client->pers.cmd.upmove &&*/ - self->client->pers.cmd.rightmove < 0 && - !self->client->pers.cmd.forwardmove) - { + } else if (/*!self->client->pers.cmd.upmove &&*/ + self->client->pers.cmd.rightmove < 0 && !self->client->pers.cmd.forwardmove) { G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP_BROLL_L, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); rolled = qtrue; - } - else if (/*self->client->pers.cmd.upmove > 0 &&*/ - !self->client->pers.cmd.rightmove && - self->client->pers.cmd.forwardmove > 0) - { + } else if (/*self->client->pers.cmd.upmove > 0 &&*/ + !self->client->pers.cmd.rightmove && self->client->pers.cmd.forwardmove > 0) { G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP_BROLL_F, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); rolled = qtrue; - } - else if (/*self->client->pers.cmd.upmove > 0 &&*/ - !self->client->pers.cmd.rightmove && - self->client->pers.cmd.forwardmove < 0) - { + } else if (/*self->client->pers.cmd.upmove > 0 &&*/ + !self->client->pers.cmd.rightmove && self->client->pers.cmd.forwardmove < 0) { G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP_BROLL_B, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); rolled = qtrue; - } - else if (self->client->pers.cmd.upmove) - { + } else if (self->client->pers.cmd.upmove) { G_PreDefSound(self->client->ps.origin, PDSOUND_FORCEJUMP); self->client->ps.forceDodgeAnim = 2; self->client->ps.forceHandExtendTime = level.time + 500; - //self->client->ps.velocity[2] = 300; + // self->client->ps.velocity[2] = 300; } - if (rolled) - { - G_EntitySound( self, CHAN_VOICE, G_SoundIndex("*jump1.wav") ); + if (rolled) { + G_EntitySound(self, CHAN_VOICE, G_SoundIndex("*jump1.wav")); } return rolled; } -void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) -{ - int i, holo, holoregen; - int prepower = 0; - //see if any force powers are running - if ( !self ) - { +void WP_ForcePowersUpdate(gentity_t *self, usercmd_t *ucmd) { + int i, holo, holoregen; + int prepower = 0; + // see if any force powers are running + if (!self) { return; } - if ( !self->client ) - { + if (!self->client) { return; } - if (self->client->ps.pm_flags & PMF_FOLLOW) - { //not a "real" game client, it's a spectator following someone + if (self->client->ps.pm_flags & PMF_FOLLOW) { // not a "real" game client, it's a spectator following someone return; } - if (self->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (self->client->sess.sessionTeam == TEAM_SPECTATOR) { return; } @@ -5000,190 +4082,138 @@ void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; } */ - //The stance in relation to power level is no longer applicable with the crazy new akimbo/staff stances. - if (!self->client->ps.fd.saberAnimLevel) - { + // The stance in relation to power level is no longer applicable with the crazy new akimbo/staff stances. + if (!self->client->ps.fd.saberAnimLevel) { self->client->ps.fd.saberAnimLevel = FORCE_LEVEL_1; } - if (level.gametype != GT_SIEGE) - { - if (!(self->client->ps.fd.forcePowersKnown & (1 << FP_LEVITATION))) - { + if (level.gametype != GT_SIEGE) { + if (!(self->client->ps.fd.forcePowersKnown & (1 << FP_LEVITATION))) { self->client->ps.fd.forcePowersKnown |= (1 << FP_LEVITATION); } - if (self->client->ps.fd.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1) - { + if (self->client->ps.fd.forcePowerLevel[FP_LEVITATION] < FORCE_LEVEL_1) { self->client->ps.fd.forcePowerLevel[FP_LEVITATION] = FORCE_LEVEL_1; } } - if (self->client->ps.fd.forcePowerSelected < 0 || self->client->ps.fd.forcePowerSelected >= NUM_FORCE_POWERS) - { //bad + if (self->client->ps.fd.forcePowerSelected < 0 || self->client->ps.fd.forcePowerSelected >= NUM_FORCE_POWERS) { // bad self->client->ps.fd.forcePowerSelected = 0; } - if ( ((self->client->sess.selectedFP != self->client->ps.fd.forcePowerSelected) || - (self->client->sess.saberLevel != self->client->ps.fd.saberAnimLevel)) && - !(self->r.svFlags & SVF_BOT) ) - { - if (self->client->sess.updateUITime < level.time) - { //a bit hackish, but we don't want the client to flood with userinfo updates if they rapidly cycle - //through their force powers or saber attack levels + if (((self->client->sess.selectedFP != self->client->ps.fd.forcePowerSelected) || (self->client->sess.saberLevel != self->client->ps.fd.saberAnimLevel)) && + !(self->r.svFlags & SVF_BOT)) { + if (self->client->sess.updateUITime < level.time) { // a bit hackish, but we don't want the client to flood with userinfo updates if they rapidly cycle + // through their force powers or saber attack levels self->client->sess.selectedFP = self->client->ps.fd.forcePowerSelected; self->client->sess.saberLevel = self->client->ps.fd.saberAnimLevel; } } - if (!g_LastFrameTime) - { + if (!g_LastFrameTime) { g_LastFrameTime = level.time; } - if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN) - { + if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN) { self->client->ps.zoomFov = 0; self->client->ps.zoomMode = 0; self->client->ps.zoomLocked = qfalse; self->client->ps.zoomTime = 0; } - if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && - self->client->ps.forceHandExtendTime >= level.time) - { + if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && self->client->ps.forceHandExtendTime >= level.time) { self->client->ps.saberMove = 0; self->client->ps.saberBlocking = 0; self->client->ps.saberBlocked = 0; self->client->ps.weaponTime = 0; self->client->ps.weaponstate = WEAPON_READY; - } - else if (self->client->ps.forceHandExtend != HANDEXTEND_NONE && - self->client->ps.forceHandExtendTime < level.time) - { - if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && - !self->client->ps.forceDodgeAnim) - { - if (self->health < 1 || (self->client->ps.eFlags & EF_DEAD)) - { + } else if (self->client->ps.forceHandExtend != HANDEXTEND_NONE && self->client->ps.forceHandExtendTime < level.time) { + if (self->client->ps.forceHandExtend == HANDEXTEND_KNOCKDOWN && !self->client->ps.forceDodgeAnim) { + if (self->health < 1 || (self->client->ps.eFlags & EF_DEAD)) { self->client->ps.forceHandExtend = HANDEXTEND_NONE; - } - else if (G_SpecialRollGetup(self)) - { + } else if (G_SpecialRollGetup(self)) { self->client->ps.forceHandExtend = HANDEXTEND_NONE; - } - else - { //hmm.. ok.. no more getting up on your own, you've gotta push something, unless.. - if ((level.time-self->client->ps.forceHandExtendTime) > 4000) - { //4 seconds elapsed, I guess they're too dumb to push something to get up! - if (self->client->pers.cmd.upmove && - self->client->ps.fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) - { //force getup + } else { // hmm.. ok.. no more getting up on your own, you've gotta push something, unless.. + if ((level.time - self->client->ps.forceHandExtendTime) > 4000) { // 4 seconds elapsed, I guess they're too dumb to push something to get up! + if (self->client->pers.cmd.upmove && self->client->ps.fd.forcePowerLevel[FP_LEVITATION] > FORCE_LEVEL_1) { // force getup G_PreDefSound(self->client->ps.origin, PDSOUND_FORCEJUMP); self->client->ps.forceDodgeAnim = 2; self->client->ps.forceHandExtendTime = level.time + 500; - //self->client->ps.velocity[2] = 400; - } - else if (self->client->ps.quickerGetup) - { - G_EntitySound( self, CHAN_VOICE, G_SoundIndex("*jump1.wav") ); + // self->client->ps.velocity[2] = 400; + } else if (self->client->ps.quickerGetup) { + G_EntitySound(self, CHAN_VOICE, G_SoundIndex("*jump1.wav")); self->client->ps.forceDodgeAnim = 3; self->client->ps.forceHandExtendTime = level.time + 500; self->client->ps.velocity[2] = 300; - } - else - { + } else { self->client->ps.forceDodgeAnim = 1; self->client->ps.forceHandExtendTime = level.time + 1000; } } } self->client->ps.quickerGetup = qfalse; - } - else if (self->client->ps.forceHandExtend == HANDEXTEND_POSTTHROWN) - { - if (self->health < 1 || (self->client->ps.eFlags & EF_DEAD)) - { + } else if (self->client->ps.forceHandExtend == HANDEXTEND_POSTTHROWN) { + if (self->health < 1 || (self->client->ps.eFlags & EF_DEAD)) { self->client->ps.forceHandExtend = HANDEXTEND_NONE; - } - else if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceDodgeAnim) - { + } else if (self->client->ps.groundEntityNum != ENTITYNUM_NONE && !self->client->ps.forceDodgeAnim) { self->client->ps.forceDodgeAnim = 1; self->client->ps.forceHandExtendTime = level.time + 1000; - G_EntitySound( self, CHAN_VOICE, G_SoundIndex("*jump1.wav") ); + G_EntitySound(self, CHAN_VOICE, G_SoundIndex("*jump1.wav")); self->client->ps.velocity[2] = 100; - } - else if (!self->client->ps.forceDodgeAnim) - { + } else if (!self->client->ps.forceDodgeAnim) { self->client->ps.forceHandExtendTime = level.time + 100; - } - else - { + } else { self->client->ps.forceHandExtend = HANDEXTEND_WEAPONREADY; } - } - else - { + } else { self->client->ps.forceHandExtend = HANDEXTEND_WEAPONREADY; } } - if (level.gametype == GT_HOLOCRON) - { + if (level.gametype == GT_HOLOCRON) { HolocronUpdate(self); } - if (level.gametype == GT_JEDIMASTER) - { + if (level.gametype == GT_JEDIMASTER) { JediMasterUpdate(self); } SeekerDroneUpdate(self); - if (self->client->ps.powerups[PW_FORCE_BOON]) - { + if (self->client->ps.powerups[PW_FORCE_BOON]) { prepower = self->client->ps.fd.forcePower; } - if (self && self->client && (BG_HasYsalamiri(level.gametype, &self->client->ps) || - self->client->ps.fd.forceDeactivateAll || self->client->tempSpectate >= level.time)) - { //has ysalamiri.. or we want to forcefully stop all his active powers + if (self && self->client && + (BG_HasYsalamiri(level.gametype, &self->client->ps) || self->client->ps.fd.forceDeactivateAll || + self->client->tempSpectate >= level.time)) { // has ysalamiri.. or we want to forcefully stop all his active powers i = 0; - while (i < NUM_FORCE_POWERS) - { - if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION) - { + while (i < NUM_FORCE_POWERS) { + if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION) { WP_ForcePowerStop(self, i); } i++; } - if (self->client->tempSpectate >= level.time) - { + if (self->client->tempSpectate >= level.time) { self->client->ps.fd.forcePower = 100; self->client->ps.fd.forceRageRecoveryTime = 0; } self->client->ps.fd.forceDeactivateAll = 0; - if (self->client->ps.fd.forceJumpCharge) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); + if (self->client->ps.fd.forceJumpCharge) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); self->client->ps.fd.forceJumpCharge = 0; } - } - else - { //otherwise just do a check through them all to see if they need to be stopped for any reason. + } else { // otherwise just do a check through them all to see if they need to be stopped for any reason. i = 0; - while (i < NUM_FORCE_POWERS) - { - if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION && - !BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, i)) - { + while (i < NUM_FORCE_POWERS) { + if ((self->client->ps.fd.forcePowersActive & (1 << i)) && i != FP_LEVITATION && !BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, i)) { WP_ForcePowerStop(self, i); } @@ -5193,19 +4223,14 @@ void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) i = 0; - if (self->client->ps.powerups[PW_FORCE_ENLIGHTENED_LIGHT] || self->client->ps.powerups[PW_FORCE_ENLIGHTENED_DARK]) - { //enlightenment - if (!self->client->ps.fd.forceUsingAdded) - { + if (self->client->ps.powerups[PW_FORCE_ENLIGHTENED_LIGHT] || self->client->ps.powerups[PW_FORCE_ENLIGHTENED_DARK]) { // enlightenment + if (!self->client->ps.fd.forceUsingAdded) { i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { self->client->ps.fd.forcePowerBaseLevel[i] = self->client->ps.fd.forcePowerLevel[i]; - if (!forcePowerDarkLight[i] || - self->client->ps.fd.forceSide == forcePowerDarkLight[i]) - { + if (!forcePowerDarkLight[i] || self->client->ps.fd.forceSide == forcePowerDarkLight[i]) { self->client->ps.fd.forcePowerLevel[i] = FORCE_LEVEL_3; self->client->ps.fd.forcePowersKnown |= (1 << i); } @@ -5215,18 +4240,14 @@ void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) self->client->ps.fd.forceUsingAdded = 1; } - } - else if (self->client->ps.fd.forceUsingAdded) - { //we don't have enlightenment but we're still using enlightened powers, so clear them back to how they should be. + } else if (self->client->ps.fd + .forceUsingAdded) { // we don't have enlightenment but we're still using enlightened powers, so clear them back to how they should be. i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { self->client->ps.fd.forcePowerLevel[i] = self->client->ps.fd.forcePowerBaseLevel[i]; - if (!self->client->ps.fd.forcePowerLevel[i]) - { - if (self->client->ps.fd.forcePowersActive & (1 << i)) - { + if (!self->client->ps.fd.forcePowerLevel[i]) { + if (self->client->ps.fd.forcePowersActive & (1 << i)) { WP_ForcePowerStop(self, i); } self->client->ps.fd.forcePowersKnown &= ~(1 << i); @@ -5240,203 +4261,155 @@ void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) i = 0; - if (!(self->client->ps.fd.forcePowersActive & (1 << FP_TELEPATHY))) - { //clear the mindtrick index values + if (!(self->client->ps.fd.forcePowersActive & (1 << FP_TELEPATHY))) { // clear the mindtrick index values self->client->ps.fd.forceMindtrickTargetIndex = 0; self->client->ps.fd.forceMindtrickTargetIndex2 = 0; self->client->ps.fd.forceMindtrickTargetIndex3 = 0; self->client->ps.fd.forceMindtrickTargetIndex4 = 0; } - if (self->health < 1) - { + if (self->health < 1) { self->client->ps.fd.forceGripBeingGripped = 0; } - if (self->client->ps.fd.forceGripBeingGripped > level.time) - { + if (self->client->ps.fd.forceGripBeingGripped > level.time) { self->client->ps.fd.forceGripCripple = 1; - //keep the saber off during this period - if (self->client->ps.weapon == WP_SABER && !self->client->ps.saberHolstered) - { + // keep the saber off during this period + if (self->client->ps.weapon == WP_SABER && !self->client->ps.saberHolstered) { Cmd_ToggleSaber_f(self); } - } - else - { + } else { self->client->ps.fd.forceGripCripple = 0; } - if (self->client->ps.fd.forceJumpSound) - { + if (self->client->ps.fd.forceJumpSound) { G_PreDefSound(self->client->ps.origin, PDSOUND_FORCEJUMP); self->client->ps.fd.forceJumpSound = 0; } - if (self->client->ps.fd.forceGripCripple) - { - if (self->client->ps.fd.forceGripSoundTime < level.time) - { + if (self->client->ps.fd.forceGripCripple) { + if (self->client->ps.fd.forceGripSoundTime < level.time) { G_PreDefSound(self->client->ps.origin, PDSOUND_FORCEGRIP); self->client->ps.fd.forceGripSoundTime = level.time + 1000; } } - if (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) - { + if (self->client->ps.fd.forcePowersActive & (1 << FP_SPEED)) { self->client->ps.powerups[PW_SPEED] = level.time + 100; } - if ( self->health <= 0 ) - {//if dead, deactivate any active force powers - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.fd.forcePowerDuration[i] || (self->client->ps.fd.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerStop( self, (forcePowers_t)i ); + if (self->health <= 0) { // if dead, deactivate any active force powers + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.fd.forcePowerDuration[i] || (self->client->ps.fd.forcePowersActive & (1 << i))) { + WP_ForcePowerStop(self, (forcePowers_t)i); self->client->ps.fd.forcePowerDuration[i] = 0; } } goto powersetcheck; } - if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) - { + if (self->client->ps.groundEntityNum != ENTITYNUM_NONE) { self->client->fjDidJump = qfalse; } - if (self->client->ps.fd.forceJumpCharge && self->client->ps.groundEntityNum == ENTITYNUM_NONE && self->client->fjDidJump) - { //this was for the "charge" jump method... I guess - if (ucmd->upmove < 10 && (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_LEVITATION)) - { - G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1-50], CHAN_VOICE); + if (self->client->ps.fd.forceJumpCharge && self->client->ps.groundEntityNum == ENTITYNUM_NONE && + self->client->fjDidJump) { // this was for the "charge" jump method... I guess + if (ucmd->upmove < 10 && (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_LEVITATION)) { + G_MuteSound(self->client->ps.fd.killSoundEntIndex[TRACK_CHANNEL_1 - 50], CHAN_VOICE); self->client->ps.fd.forceJumpCharge = 0; } } #ifndef METROID_JUMP - else if ( (ucmd->upmove > 10) && (self->client->ps.pm_flags & PMF_JUMP_HELD) && self->client->ps.groundTime && (level.time - self->client->ps.groundTime) > 150 && !BG_HasYsalamiri(level.gametype, &self->client->ps) && BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, FP_LEVITATION) ) - {//just charging up - ForceJumpCharge( self, ucmd ); - } - else if (ucmd->upmove < 10 && self->client->ps.groundEntityNum == ENTITYNUM_NONE && self->client->ps.fd.forceJumpCharge) - { + else if ((ucmd->upmove > 10) && (self->client->ps.pm_flags & PMF_JUMP_HELD) && self->client->ps.groundTime && + (level.time - self->client->ps.groundTime) > 150 && !BG_HasYsalamiri(level.gametype, &self->client->ps) && + BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, FP_LEVITATION)) { // just charging up + ForceJumpCharge(self, ucmd); + } else if (ucmd->upmove < 10 && self->client->ps.groundEntityNum == ENTITYNUM_NONE && self->client->ps.fd.forceJumpCharge) { self->client->ps.pm_flags &= ~(PMF_JUMP_HELD); } #endif - if (!(self->client->ps.pm_flags & PMF_JUMP_HELD) && self->client->ps.fd.forceJumpCharge) - { - if (!(ucmd->buttons & BUTTON_FORCEPOWER) || - self->client->ps.fd.forcePowerSelected != FP_LEVITATION) - { - WP_DoSpecificPower( self, ucmd, FP_LEVITATION ); + if (!(self->client->ps.pm_flags & PMF_JUMP_HELD) && self->client->ps.fd.forceJumpCharge) { + if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_LEVITATION) { + WP_DoSpecificPower(self, ucmd, FP_LEVITATION); } } - if ( ucmd->buttons & BUTTON_FORCEGRIP ) - { //grip is one of the powers with its own button.. if it's held, call the specific grip power function. - WP_DoSpecificPower( self, ucmd, FP_GRIP ); - } - else - { //see if we're using it generically.. if not, stop. - if (self->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) - { - if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_GRIP) - { + if (ucmd->buttons & BUTTON_FORCEGRIP) { // grip is one of the powers with its own button.. if it's held, call the specific grip power function. + WP_DoSpecificPower(self, ucmd, FP_GRIP); + } else { // see if we're using it generically.. if not, stop. + if (self->client->ps.fd.forcePowersActive & (1 << FP_GRIP)) { + if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_GRIP) { WP_ForcePowerStop(self, FP_GRIP); } } } - if ( ucmd->buttons & BUTTON_FORCE_LIGHTNING ) - { //lightning + if (ucmd->buttons & BUTTON_FORCE_LIGHTNING) { // lightning WP_DoSpecificPower(self, ucmd, FP_LIGHTNING); - } - else - { //see if we're using it generically.. if not, stop. - if (self->client->ps.fd.forcePowersActive & (1 << FP_LIGHTNING)) - { - if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_LIGHTNING) - { + } else { // see if we're using it generically.. if not, stop. + if (self->client->ps.fd.forcePowersActive & (1 << FP_LIGHTNING)) { + if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_LIGHTNING) { WP_ForcePowerStop(self, FP_LIGHTNING); } } } - if ( ucmd->buttons & BUTTON_FORCE_DRAIN ) - { //drain + if (ucmd->buttons & BUTTON_FORCE_DRAIN) { // drain WP_DoSpecificPower(self, ucmd, FP_DRAIN); - } - else - { //see if we're using it generically.. if not, stop. - if (self->client->ps.fd.forcePowersActive & (1 << FP_DRAIN)) - { - if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_DRAIN) - { + } else { // see if we're using it generically.. if not, stop. + if (self->client->ps.fd.forcePowersActive & (1 << FP_DRAIN)) { + if (!(ucmd->buttons & BUTTON_FORCEPOWER) || self->client->ps.fd.forcePowerSelected != FP_DRAIN) { WP_ForcePowerStop(self, FP_DRAIN); } } } - if ( (ucmd->buttons & BUTTON_FORCEPOWER) && - BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, self->client->ps.fd.forcePowerSelected)) - { + if ((ucmd->buttons & BUTTON_FORCEPOWER) && BG_CanUseFPNow(level.gametype, &self->client->ps, level.time, self->client->ps.fd.forcePowerSelected)) { if (self->client->ps.fd.forcePowerSelected == FP_LEVITATION) - ForceJumpCharge( self, ucmd ); + ForceJumpCharge(self, ucmd); else - WP_DoSpecificPower( self, ucmd, self->client->ps.fd.forcePowerSelected ); - } - else - { + WP_DoSpecificPower(self, ucmd, self->client->ps.fd.forcePowerSelected); + } else { self->client->ps.fd.forceButtonNeedRelease = 0; } - for ( i = 0; i < NUM_FORCE_POWERS; i++ ) - { - if ( self->client->ps.fd.forcePowerDuration[i] ) - { - if ( self->client->ps.fd.forcePowerDuration[i] < level.time ) - { - if ( (self->client->ps.fd.forcePowersActive&( 1 << i )) ) - {//turn it off - WP_ForcePowerStop( self, (forcePowers_t)i ); + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (self->client->ps.fd.forcePowerDuration[i]) { + if (self->client->ps.fd.forcePowerDuration[i] < level.time) { + if ((self->client->ps.fd.forcePowersActive & (1 << i))) { // turn it off + WP_ForcePowerStop(self, (forcePowers_t)i); } self->client->ps.fd.forcePowerDuration[i] = 0; } } - if ( (self->client->ps.fd.forcePowersActive&( 1 << i )) ) - { - WP_ForcePowerRun( self, (forcePowers_t)i, ucmd ); + if ((self->client->ps.fd.forcePowersActive & (1 << i))) { + WP_ForcePowerRun(self, (forcePowers_t)i, ucmd); } } - if ( !(self->client->ps.fd.forcePowersActive & (1<client->ps.fd.forcePowersActive & (1 << FP_DRAIN))) self->client->force.drainDebounce = level.time; - if ( !(self->client->ps.fd.forcePowersActive & (1<client->ps.fd.forcePowersActive & (1 << FP_LIGHTNING))) self->client->force.lightningDebounce = level.time; - if ( (!self->client->ps.fd.forcePowersActive || self->client->ps.fd.forcePowersActive == (1 << FP_DRAIN)) && - !self->client->ps.saberInFlight && (self->client->ps.weapon != WP_SABER || !BG_SaberInSpecial(self->client->ps.saberMove)) ) - {//when not using the force, regenerate at 1 point per half second - while ( self->client->ps.fd.forcePowerRegenDebounceTime < level.time ) - { - if (level.gametype != GT_HOLOCRON || g_maxHolocronCarry.value) - { - if ( self->client->ps.powerups[PW_FORCE_BOON] ) - WP_ForcePowerRegenerate( self, 6 ); - else if ( self->client->ps.isJediMaster && level.gametype == GT_JEDIMASTER ) - WP_ForcePowerRegenerate( self, 4 ); //jedi master regenerates 4 times as fast + if ((!self->client->ps.fd.forcePowersActive || self->client->ps.fd.forcePowersActive == (1 << FP_DRAIN)) && !self->client->ps.saberInFlight && + (self->client->ps.weapon != WP_SABER || + !BG_SaberInSpecial(self->client->ps.saberMove))) { // when not using the force, regenerate at 1 point per half second + while (self->client->ps.fd.forcePowerRegenDebounceTime < level.time) { + if (level.gametype != GT_HOLOCRON || g_maxHolocronCarry.value) { + if (self->client->ps.powerups[PW_FORCE_BOON]) + WP_ForcePowerRegenerate(self, 6); + else if (self->client->ps.isJediMaster && level.gametype == GT_JEDIMASTER) + WP_ForcePowerRegenerate(self, 4); // jedi master regenerates 4 times as fast else - WP_ForcePowerRegenerate( self, 0 ); - } - else - { //regenerate based on the number of holocrons carried + WP_ForcePowerRegenerate(self, 0); + } else { // regenerate based on the number of holocrons carried holoregen = 0; holo = 0; - while (holo < NUM_FORCE_POWERS) - { + while (holo < NUM_FORCE_POWERS) { if (self->client->ps.holocronsCarried[holo]) holoregen++; holo++; @@ -5445,114 +4418,92 @@ void WP_ForcePowersUpdate( gentity_t *self, usercmd_t *ucmd ) WP_ForcePowerRegenerate(self, holoregen); } - if (level.gametype == GT_SIEGE) - { - if ( self->client->holdingObjectiveItem && g_entities[self->client->holdingObjectiveItem].inuse && g_entities[self->client->holdingObjectiveItem].genericValue15 ) - self->client->ps.fd.forcePowerRegenDebounceTime += 7000; //1 point per 7 seconds.. super slow - else if (self->client->siegeClass != -1 && (bgSiegeClasses[self->client->siegeClass].classflags & (1<client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer*0.2, 1); //if this is siege and our player class has the fast force regen ability, then recharge with 1/5th the usual delay + if (level.gametype == GT_SIEGE) { + if (self->client->holdingObjectiveItem && g_entities[self->client->holdingObjectiveItem].inuse && + g_entities[self->client->holdingObjectiveItem].genericValue15) + self->client->ps.fd.forcePowerRegenDebounceTime += 7000; // 1 point per 7 seconds.. super slow + else if (self->client->siegeClass != -1 && (bgSiegeClasses[self->client->siegeClass].classflags & (1 << CFL_FASTFORCEREGEN))) + self->client->ps.fd.forcePowerRegenDebounceTime += + Q_max(g_forceRegenTime.integer * 0.2, + 1); // if this is siege and our player class has the fast force regen ability, then recharge with 1/5th the usual delay else self->client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer, 1); - } - else - { - if ( level.gametype == GT_POWERDUEL && self->client->sess.duelTeam == DUELTEAM_LONE ) - { - if ( duel_fraglimit.integer ) - self->client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer * (0.6 + (.3 * (float)self->client->sess.wins / (float)duel_fraglimit.integer)), 1); + } else { + if (level.gametype == GT_POWERDUEL && self->client->sess.duelTeam == DUELTEAM_LONE) { + if (duel_fraglimit.integer) + self->client->ps.fd.forcePowerRegenDebounceTime += + Q_max(g_forceRegenTime.integer * (0.6 + (.3 * (float)self->client->sess.wins / (float)duel_fraglimit.integer)), 1); else - self->client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer*0.7, 1); - } - else + self->client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer * 0.7, 1); + } else self->client->ps.fd.forcePowerRegenDebounceTime += Q_max(g_forceRegenTime.integer, 1); } } - } - else - { + } else { self->client->ps.fd.forcePowerRegenDebounceTime = level.time; } powersetcheck: - if (prepower && self->client->ps.fd.forcePower < prepower) - { - int dif = ((prepower - self->client->ps.fd.forcePower)/2); - if (dif < 1) - { + if (prepower && self->client->ps.fd.forcePower < prepower) { + int dif = ((prepower - self->client->ps.fd.forcePower) / 2); + if (dif < 1) { dif = 1; } - self->client->ps.fd.forcePower = (prepower-dif); + self->client->ps.fd.forcePower = (prepower - dif); } } -qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc ) -{ - int dodgeAnim = -1; +qboolean Jedi_DodgeEvasion(gentity_t *self, gentity_t *shooter, trace_t *tr, int hitLoc) { + int dodgeAnim = -1; - if ( !self || !self->client || self->health <= 0 ) - { + if (!self || !self->client || self->health <= 0) { return qfalse; } - if (!g_forceDodge.integer) - { + if (!g_forceDodge.integer) { return qfalse; } - if (g_forceDodge.integer != 2) - { - if (!(self->client->ps.fd.forcePowersActive & (1 << FP_SEE))) - { + if (g_forceDodge.integer != 2) { + if (!(self->client->ps.fd.forcePowersActive & (1 << FP_SEE))) { return qfalse; } } - if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) - {//can't dodge in mid-air + if (self->client->ps.groundEntityNum == ENTITYNUM_NONE) { // can't dodge in mid-air return qfalse; } - if ( self->client->ps.weaponTime > 0 || self->client->ps.forceHandExtend != HANDEXTEND_NONE ) - {//in some effect that stops me from moving on my own + if (self->client->ps.weaponTime > 0 || self->client->ps.forceHandExtend != HANDEXTEND_NONE) { // in some effect that stops me from moving on my own return qfalse; } - if (g_forceDodge.integer == 2) - { - if (self->client->ps.fd.forcePowersActive) - { //for now just don't let us dodge if we're using a force power at all + if (g_forceDodge.integer == 2) { + if (self->client->ps.fd.forcePowersActive) { // for now just don't let us dodge if we're using a force power at all return qfalse; } } - if (g_forceDodge.integer == 2) - { - if ( !WP_ForcePowerUsable( self, FP_SPEED ) ) - {//make sure we have it and have enough force power + if (g_forceDodge.integer == 2) { + if (!WP_ForcePowerUsable(self, FP_SPEED)) { // make sure we have it and have enough force power return qfalse; } } - if (g_forceDodge.integer == 2) - { - if ( Q_irand( 1, 7 ) > self->client->ps.fd.forcePowerLevel[FP_SPEED] ) - {//more likely to fail on lower force speed level + if (g_forceDodge.integer == 2) { + if (Q_irand(1, 7) > self->client->ps.fd.forcePowerLevel[FP_SPEED]) { // more likely to fail on lower force speed level return qfalse; } - } - else - { - //We now dodge all the time, but only on level 3 - if (self->client->ps.fd.forcePowerLevel[FP_SEE] < FORCE_LEVEL_3) - {//more likely to fail on lower force sight level + } else { + // We now dodge all the time, but only on level 3 + if (self->client->ps.fd.forcePowerLevel[FP_SEE] < FORCE_LEVEL_3) { // more likely to fail on lower force sight level return qfalse; } } - switch( hitLoc ) - { + switch (hitLoc) { case HL_NONE: return qfalse; break; @@ -5595,22 +4546,18 @@ qboolean Jedi_DodgeEvasion( gentity_t *self, gentity_t *shooter, trace_t *tr, in return qfalse; } - if ( dodgeAnim != -1 ) - { - //Our own happy way of forcing an anim: + if (dodgeAnim != -1) { + // Our own happy way of forcing an anim: self->client->ps.forceHandExtend = HANDEXTEND_DODGE; self->client->ps.forceDodgeAnim = dodgeAnim; self->client->ps.forceHandExtendTime = level.time + 300; self->client->ps.powerups[PW_SPEEDBURST] = level.time + 100; - if (g_forceDodge.integer == 2) - { - ForceSpeed( self, 500 ); - } - else - { - G_Sound( self, CHAN_BODY, G_SoundIndex("sound/weapons/force/speed.wav") ); + if (g_forceDodge.integer == 2) { + ForceSpeed(self, 500); + } else { + G_Sound(self, CHAN_BODY, G_SoundIndex("sound/weapons/force/speed.wav")); } return qtrue; } diff --git a/codemp/game/w_saber.c b/codemp/game/w_saber.c index 5561b3ed8d..275425d106 100644 --- a/codemp/game/w_saber.c +++ b/codemp/game/w_saber.c @@ -28,47 +28,46 @@ along with this program; if not, see . #define SABER_BOX_SIZE 16.0f extern bot_state_t *botstates[MAX_CLIENTS]; -extern qboolean InFront( vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold ); +extern qboolean InFront(vec3_t spot, vec3_t from, vec3_t fromAngles, float threshHold); extern void G_TestLine(vec3_t start, vec3_t end, int color, int time); int saberSpinSound = 0; -//would be cleaner if these were renamed to BG_ and proto'd in a header. -qboolean PM_SaberInTransition( int move ); -qboolean PM_SaberInDeflect( int move ); -qboolean PM_SaberInBrokenParry( int move ); -qboolean PM_SaberInBounce( int move ); -qboolean BG_SaberInReturn( int move ); -qboolean BG_InKnockDownOnGround( playerState_t *ps ); -qboolean BG_StabDownAnim( int anim ); -qboolean BG_SabersOff( playerState_t *ps ); -qboolean BG_SaberInTransitionAny( int move ); -qboolean BG_SaberInAttackPure( int move ); -qboolean WP_SaberBladeUseSecondBladeStyle( saberInfo_t *saber, int bladeNum ); -qboolean WP_SaberBladeDoTransitionDamage( saberInfo_t *saber, int bladeNum ); - -void WP_SaberAddG2Model( gentity_t *saberent, const char *saberModel, qhandle_t saberSkin ); -void WP_SaberRemoveG2Model( gentity_t *saberent ); +// would be cleaner if these were renamed to BG_ and proto'd in a header. +qboolean PM_SaberInTransition(int move); +qboolean PM_SaberInDeflect(int move); +qboolean PM_SaberInBrokenParry(int move); +qboolean PM_SaberInBounce(int move); +qboolean BG_SaberInReturn(int move); +qboolean BG_InKnockDownOnGround(playerState_t *ps); +qboolean BG_StabDownAnim(int anim); +qboolean BG_SabersOff(playerState_t *ps); +qboolean BG_SaberInTransitionAny(int move); +qboolean BG_SaberInAttackPure(int move); +qboolean WP_SaberBladeUseSecondBladeStyle(saberInfo_t *saber, int bladeNum); +qboolean WP_SaberBladeDoTransitionDamage(saberInfo_t *saber, int bladeNum); + +void WP_SaberAddG2Model(gentity_t *saberent, const char *saberModel, qhandle_t saberSkin); +void WP_SaberRemoveG2Model(gentity_t *saberent); // g_randFix 0 == Same as basejka. Broken on Linux, fine on Windows // g_randFix 1 == Use proper behaviour of RAND_MAX. Fine on Linux, fine on Windows // g_randFix 2 == Intentionally break RAND_MAX. Broken on Linux, broken on Windows. -float RandFloat( float min, float max ) { +float RandFloat(float min, float max) { int randActual = rand(); float randMax = 32768.0f; #ifdef _WIN32 - if ( g_randFix.integer == 2 ) - randActual = (randActual<<16)|randActual; + if (g_randFix.integer == 2) + randActual = (randActual << 16) | randActual; #elif defined(__GCC__) - if ( g_randFix.integer == 1 ) + if (g_randFix.integer == 1) randMax = RAND_MAX; #endif return ((randActual * (max - min)) / randMax) + min; } #ifdef DEBUG_SABER_BOX -void G_DebugBoxLines(vec3_t mins, vec3_t maxs, int duration) -{ +void G_DebugBoxLines(vec3_t mins, vec3_t maxs, int duration) { vec3_t start; vec3_t end; @@ -102,66 +101,57 @@ void G_DebugBoxLines(vec3_t mins, vec3_t maxs, int duration) } #endif -//general check for performing certain attacks against others -qboolean G_CanBeEnemy( gentity_t *self, gentity_t *enemy ) -{ - //ptrs! - if ( !self->inuse || !enemy->inuse || !self->client || !enemy->client ) +// general check for performing certain attacks against others +qboolean G_CanBeEnemy(gentity_t *self, gentity_t *enemy) { + // ptrs! + if (!self->inuse || !enemy->inuse || !self->client || !enemy->client) return qfalse; if (level.gametype < GT_TEAM) return qtrue; - if ( g_friendlyFire.integer ) + if (g_friendlyFire.integer) return qtrue; - if ( OnSameTeam( self, enemy ) ) + if (OnSameTeam(self, enemy)) return qfalse; return qtrue; } -//This function gets the attack power which is used to decide broken parries, -//knockaways, and numerous other things. It is not directly related to the -//actual amount of damage done, however. -rww -static QINLINE int G_SaberAttackPower(gentity_t *ent, qboolean attacking) -{ +// This function gets the attack power which is used to decide broken parries, +// knockaways, and numerous other things. It is not directly related to the +// actual amount of damage done, however. -rww +static QINLINE int G_SaberAttackPower(gentity_t *ent, qboolean attacking) { int baseLevel; assert(ent && ent->client); baseLevel = ent->client->ps.fd.saberAnimLevel; - //Give "medium" strength for the two special stances. - if (baseLevel == SS_DUAL) - { + // Give "medium" strength for the two special stances. + if (baseLevel == SS_DUAL) { baseLevel = 2; - } - else if (baseLevel == SS_STAFF) - { + } else if (baseLevel == SS_STAFF) { baseLevel = 2; } - if (attacking) - { //the attacker gets a boost to help penetrate defense. - //General boost up so the individual levels make a bigger difference. + if (attacking) { // the attacker gets a boost to help penetrate defense. + // General boost up so the individual levels make a bigger difference. baseLevel *= 2; baseLevel++; - //Get the "speed" of the swing, roughly, and add more power - //to the attack based on it. - if (ent->client->lastSaberStorageTime >= (level.time-50) && - ent->client->olderIsValid) - { + // Get the "speed" of the swing, roughly, and add more power + // to the attack based on it. + if (ent->client->lastSaberStorageTime >= (level.time - 50) && ent->client->olderIsValid) { vec3_t vSub; int swingDist; int toleranceAmt; - //We want different "tolerance" levels for adding in the distance of the last swing - //to the base power level depending on which stance we are using. Otherwise fast - //would have more advantage than it should since the animations are all much faster. - switch (ent->client->ps.fd.saberAnimLevel) - { + // We want different "tolerance" levels for adding in the distance of the last swing + // to the base power level depending on which stance we are using. Otherwise fast + // would have more advantage than it should since the animations are all much faster. + switch (ent->client->ps.fd.saberAnimLevel) { case SS_STRONG: toleranceAmt = 8; break; @@ -171,67 +161,54 @@ static QINLINE int G_SaberAttackPower(gentity_t *ent, qboolean attacking) case SS_FAST: toleranceAmt = 24; break; - default: //dual, staff, etc. + default: // dual, staff, etc. toleranceAmt = 16; break; } - VectorSubtract(ent->client->lastSaberBase_Always, ent->client->olderSaberBase, vSub); + VectorSubtract(ent->client->lastSaberBase_Always, ent->client->olderSaberBase, vSub); swingDist = (int)VectorLength(vSub); - while (swingDist > 0) - { //I would like to do something more clever. But I suppose this works, at least for now. + while (swingDist > 0) { // I would like to do something more clever. But I suppose this works, at least for now. baseLevel++; swingDist -= toleranceAmt; } } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer > 1) - { + if (g_saberDebugPrint.integer > 1) { Com_Printf("Client %i: ATT STR: %i\n", ent->s.number, baseLevel); } #endif } if ((ent->client->ps.brokenLimbs & (1 << BROKENLIMB_RARM)) || - (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) - { //We're very weak when one of our arms is broken + (ent->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) { // We're very weak when one of our arms is broken baseLevel *= 0.3; } - //Cap at reasonable values now. - if (baseLevel < 1) - { + // Cap at reasonable values now. + if (baseLevel < 1) { baseLevel = 1; - } - else if (baseLevel > 16) - { + } else if (baseLevel > 16) { baseLevel = 16; } - if (level.gametype == GT_POWERDUEL && - ent->client->sess.duelTeam == DUELTEAM_LONE) - { //get more power then - return baseLevel*2; - } - else if (attacking && level.gametype == GT_SIEGE) - { //in siege, saber battles should be quicker and more biased toward the attacker - return baseLevel*3; + if (level.gametype == GT_POWERDUEL && ent->client->sess.duelTeam == DUELTEAM_LONE) { // get more power then + return baseLevel * 2; + } else if (attacking && level.gametype == GT_SIEGE) { // in siege, saber battles should be quicker and more biased toward the attacker + return baseLevel * 3; } return baseLevel; } -void WP_DeactivateSaber( gentity_t *self, qboolean clearLength ) -{ - if ( !self || !self->client ) - { +void WP_DeactivateSaber(gentity_t *self, qboolean clearLength) { + if (!self || !self->client) { return; } - //keep my saber off! - if ( !self->client->ps.saberHolstered ) - { + // keep my saber off! + if (!self->client->ps.saberHolstered) { self->client->ps.saberHolstered = 2; /* if ( clearLength ) @@ -239,61 +216,46 @@ void WP_DeactivateSaber( gentity_t *self, qboolean clearLength ) self->client->ps.SetSaberLength( 0 ); } */ - //Doens't matter ATM - if (self->client->saber[0].soundOff) - { + // Doens't matter ATM + if (self->client->saber[0].soundOff) { G_Sound(self, CHAN_WEAPON, self->client->saber[0].soundOff); } - if (self->client->saber[1].soundOff && - self->client->saber[1].model[0]) - { + if (self->client->saber[1].soundOff && self->client->saber[1].model[0]) { G_Sound(self, CHAN_WEAPON, self->client->saber[1].soundOff); } - } } -void WP_ActivateSaber( gentity_t *self ) -{ - if ( !self || !self->client ) - { +void WP_ActivateSaber(gentity_t *self) { + if (!self || !self->client) { return; } - if (self->NPC && - self->client->ps.forceHandExtend == HANDEXTEND_JEDITAUNT && - (self->client->ps.forceHandExtendTime - level.time) > 200) - { //if we're an NPC and in the middle of a taunt then stop it + if (self->NPC && self->client->ps.forceHandExtend == HANDEXTEND_JEDITAUNT && + (self->client->ps.forceHandExtendTime - level.time) > 200) { // if we're an NPC and in the middle of a taunt then stop it self->client->ps.forceHandExtend = HANDEXTEND_NONE; self->client->ps.forceHandExtendTime = 0; - } - else if (self->client->ps.fd.forceGripCripple) - { //can't activate saber while being gripped + } else if (self->client->ps.fd.forceGripCripple) { // can't activate saber while being gripped return; } - if ( self->client->ps.saberHolstered ) - { + if (self->client->ps.saberHolstered) { self->client->ps.saberHolstered = 0; - if (self->client->saber[0].soundOn) - { + if (self->client->saber[0].soundOn) { G_Sound(self, CHAN_WEAPON, self->client->saber[0].soundOn); } - if (self->client->saber[1].soundOn) - { + if (self->client->saber[1].soundOn) { G_Sound(self, CHAN_WEAPON, self->client->saber[1].soundOn); } } } -#define PROPER_THROWN_VALUE 999 //Ah, well.. +#define PROPER_THROWN_VALUE 999 // Ah, well.. -void SaberUpdateSelf(gentity_t *ent) -{ - if (ent->r.ownerNum == ENTITYNUM_NONE) - { +void SaberUpdateSelf(gentity_t *ent) { + if (ent->r.ownerNum == ENTITYNUM_NONE) { ent->think = G_FreeEntity; ent->nextthink = level.time; return; @@ -308,8 +270,8 @@ void SaberUpdateSelf(gentity_t *ent) return; } - if (g_entities[ent->r.ownerNum].client->ps.saberInFlight && g_entities[ent->r.ownerNum].health > 0) - { //let The Master take care of us now (we'll get treated like a missile until we return) + if (g_entities[ent->r.ownerNum].client->ps.saberInFlight && + g_entities[ent->r.ownerNum].health > 0) { // let The Master take care of us now (we'll get treated like a missile until we return) ent->nextthink = level.time; ent->genericValue5 = PROPER_THROWN_VALUE; return; @@ -317,43 +279,34 @@ void SaberUpdateSelf(gentity_t *ent) ent->genericValue5 = 0; - if (g_entities[ent->r.ownerNum].client->ps.weapon != WP_SABER || - (g_entities[ent->r.ownerNum].client->ps.pm_flags & PMF_FOLLOW) || - //RWW ADDED 7-19-03 BEGIN - g_entities[ent->r.ownerNum].client->sess.sessionTeam == TEAM_SPECTATOR || - g_entities[ent->r.ownerNum].client->tempSpectate >= level.time || - //RWW ADDED 7-19-03 END - g_entities[ent->r.ownerNum].health < 1 || - BG_SabersOff( &g_entities[ent->r.ownerNum].client->ps ) || - (!g_entities[ent->r.ownerNum].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] && g_entities[ent->r.ownerNum].s.eType != ET_NPC)) - { //owner is not using saber, spectating, dead, saber holstered, or has no attack level + if (g_entities[ent->r.ownerNum].client->ps.weapon != WP_SABER || (g_entities[ent->r.ownerNum].client->ps.pm_flags & PMF_FOLLOW) || + // RWW ADDED 7-19-03 BEGIN + g_entities[ent->r.ownerNum].client->sess.sessionTeam == TEAM_SPECTATOR || g_entities[ent->r.ownerNum].client->tempSpectate >= level.time || + // RWW ADDED 7-19-03 END + g_entities[ent->r.ownerNum].health < 1 || BG_SabersOff(&g_entities[ent->r.ownerNum].client->ps) || + (!g_entities[ent->r.ownerNum].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] && + g_entities[ent->r.ownerNum].s.eType != ET_NPC)) { // owner is not using saber, spectating, dead, saber holstered, or has no attack level ent->r.contents = 0; ent->clipmask = 0; - } - else - { //Standard contents (saber is active) + } else { // Standard contents (saber is active) #ifdef DEBUG_SABER_BOX - if (g_saberDebugBox.integer == 1|| g_saberDebugBox.integer == 4) - { + if (g_saberDebugBox.integer == 1 || g_saberDebugBox.integer == 4) { vec3_t dbgMins; vec3_t dbgMaxs; - VectorAdd( ent->r.currentOrigin, ent->r.mins, dbgMins ); - VectorAdd( ent->r.currentOrigin, ent->r.maxs, dbgMaxs ); + VectorAdd(ent->r.currentOrigin, ent->r.mins, dbgMins); + VectorAdd(ent->r.currentOrigin, ent->r.maxs, dbgMaxs); - G_DebugBoxLines(dbgMins, dbgMaxs, (10.0f/(float)sv_fps.integer)*100); + G_DebugBoxLines(dbgMins, dbgMaxs, (10.0f / (float)sv_fps.integer) * 100); } #endif - if (ent->r.contents != CONTENTS_LIGHTSABER) - { - if ((level.time - g_entities[ent->r.ownerNum].client->lastSaberStorageTime) <= 200) - { //Only go back to solid once we're sure our owner has updated recently + if (ent->r.contents != CONTENTS_LIGHTSABER) { + if ((level.time - g_entities[ent->r.ownerNum].client->lastSaberStorageTime) <= + 200) { // Only go back to solid once we're sure our owner has updated recently ent->r.contents = CONTENTS_LIGHTSABER; ent->clipmask = MASK_PLAYERSOLID | CONTENTS_LIGHTSABER; } - } - else - { + } else { ent->r.contents = CONTENTS_LIGHTSABER; ent->clipmask = MASK_PLAYERSOLID | CONTENTS_LIGHTSABER; } @@ -364,22 +317,19 @@ void SaberUpdateSelf(gentity_t *ent) ent->nextthink = level.time; } -void SaberGotHit( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void SaberGotHit(gentity_t *self, gentity_t *other, trace_t *trace) { gentity_t *own = &g_entities[self->r.ownerNum]; - if (!own || !own->client) - { + if (!own || !own->client) { return; } - //Do something here..? Was handling projectiles here, but instead they're now handled in their own functions. + // Do something here..? Was handling projectiles here, but instead they're now handled in their own functions. } -qboolean BG_SuperBreakLoseAnim( int anim ); +qboolean BG_SuperBreakLoseAnim(int anim); -static QINLINE void SetSaberBoxSize(gentity_t *saberent) -{ +static QINLINE void SetSaberBoxSize(gentity_t *saberent) { gentity_t *owner = NULL; vec3_t saberOrg, saberTip; int i; @@ -391,73 +341,52 @@ static QINLINE void SetSaberBoxSize(gentity_t *saberent) assert(saberent && saberent->inuse); - if (saberent->r.ownerNum < MAX_CLIENTS && saberent->r.ownerNum >= 0) - { + if (saberent->r.ownerNum < MAX_CLIENTS && saberent->r.ownerNum >= 0) { owner = &g_entities[saberent->r.ownerNum]; - } - else if (saberent->r.ownerNum >= 0 && saberent->r.ownerNum < ENTITYNUM_WORLD && - g_entities[saberent->r.ownerNum].s.eType == ET_NPC) - { + } else if (saberent->r.ownerNum >= 0 && saberent->r.ownerNum < ENTITYNUM_WORLD && g_entities[saberent->r.ownerNum].s.eType == ET_NPC) { owner = &g_entities[saberent->r.ownerNum]; } - if (!owner || !owner->inuse || !owner->client) - { + if (!owner || !owner->inuse || !owner->client) { assert(!"Saber with no owner?"); return; } - if ( owner->client->saber[1].model[0] ) - { + if (owner->client->saber[1].model[0]) { dualSabers = qtrue; } - if ( PM_SaberInBrokenParry(owner->client->ps.saberMove) - || BG_SuperBreakLoseAnim( owner->client->ps.torsoAnim ) ) - { //let swings go right through when we're in this state - for ( i = 0; i < MAX_SABERS; i++ ) - { - if ( i > 0 && !dualSabers ) - {//not using a second saber, set it to not blocking - for ( j = 0; j < MAX_BLADES; j++ ) - { + if (PM_SaberInBrokenParry(owner->client->ps.saberMove) || + BG_SuperBreakLoseAnim(owner->client->ps.torsoAnim)) { // let swings go right through when we're in this state + for (i = 0; i < MAX_SABERS; i++) { + if (i > 0 && !dualSabers) { // not using a second saber, set it to not blocking + for (j = 0; j < MAX_BLADES; j++) { alwaysBlock[i][j] = qfalse; } - } - else - { - if ( (owner->client->saber[i].saberFlags2&SFL2_ALWAYS_BLOCK) ) - { - for ( j = 0; j < owner->client->saber[i].numBlades; j++ ) - { + } else { + if ((owner->client->saber[i].saberFlags2 & SFL2_ALWAYS_BLOCK)) { + for (j = 0; j < owner->client->saber[i].numBlades; j++) { alwaysBlock[i][j] = qtrue; forceBlock = qtrue; } } - if ( owner->client->saber[i].bladeStyle2Start > 0 ) - { - for ( j = owner->client->saber[i].bladeStyle2Start; j < owner->client->saber[i].numBlades; j++ ) - { - if ( (owner->client->saber[i].saberFlags2&SFL2_ALWAYS_BLOCK2) ) - { + if (owner->client->saber[i].bladeStyle2Start > 0) { + for (j = owner->client->saber[i].bladeStyle2Start; j < owner->client->saber[i].numBlades; j++) { + if ((owner->client->saber[i].saberFlags2 & SFL2_ALWAYS_BLOCK2)) { alwaysBlock[i][j] = qtrue; forceBlock = qtrue; - } - else - { + } else { alwaysBlock[i][j] = qfalse; } } } } } - if ( !forceBlock ) - {//no sabers/blades to FORCE to be on, so turn off blocking altogether - VectorSet( saberent->r.mins, 0, 0, 0 ); - VectorSet( saberent->r.maxs, 0, 0, 0 ); + if (!forceBlock) { // no sabers/blades to FORCE to be on, so turn off blocking altogether + VectorSet(saberent->r.mins, 0, 0, 0); + VectorSet(saberent->r.maxs, 0, 0, 0); #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer > 1) - { + if (g_saberDebugPrint.integer > 1) { Com_Printf("Client %i in broken parry, saber box 0\n", owner->s.number); } #endif @@ -466,99 +395,78 @@ static QINLINE void SetSaberBoxSize(gentity_t *saberent) } if ((level.time - owner->client->lastSaberStorageTime) > 200 || - (level.time - owner->client->saber[j].blade[k].storageTime) > 100) - { //it's been too long since we got a reliable point storage, so use the defaults and leave. - VectorSet( saberent->r.mins, -SABER_BOX_SIZE, -SABER_BOX_SIZE, -SABER_BOX_SIZE ); - VectorSet( saberent->r.maxs, SABER_BOX_SIZE, SABER_BOX_SIZE, SABER_BOX_SIZE ); + (level.time - owner->client->saber[j].blade[k].storageTime) > + 100) { // it's been too long since we got a reliable point storage, so use the defaults and leave. + VectorSet(saberent->r.mins, -SABER_BOX_SIZE, -SABER_BOX_SIZE, -SABER_BOX_SIZE); + VectorSet(saberent->r.maxs, SABER_BOX_SIZE, SABER_BOX_SIZE, SABER_BOX_SIZE); return; } - if ( dualSabers - || owner->client->saber[0].numBlades > 1 ) - {//dual sabers or multi-blade saber - if ( owner->client->ps.saberHolstered > 1 ) - {//entirely off - //no blocking at all - VectorSet( saberent->r.mins, 0, 0, 0 ); - VectorSet( saberent->r.maxs, 0, 0, 0 ); + if (dualSabers || owner->client->saber[0].numBlades > 1) { // dual sabers or multi-blade saber + if (owner->client->ps.saberHolstered > 1) { // entirely off + // no blocking at all + VectorSet(saberent->r.mins, 0, 0, 0); + VectorSet(saberent->r.maxs, 0, 0, 0); return; } - } - else - {//single saber - if ( owner->client->ps.saberHolstered ) - {//off - //no blocking at all - VectorSet( saberent->r.mins, 0, 0, 0 ); - VectorSet( saberent->r.maxs, 0, 0, 0 ); + } else { // single saber + if (owner->client->ps.saberHolstered) { // off + // no blocking at all + VectorSet(saberent->r.mins, 0, 0, 0); + VectorSet(saberent->r.maxs, 0, 0, 0); return; } } - //Start out at the saber origin, then go through all the blades and push out the extents - //for each blade, then set the box relative to the origin. + // Start out at the saber origin, then go through all the blades and push out the extents + // for each blade, then set the box relative to the origin. VectorCopy(saberent->r.currentOrigin, saberent->r.mins); VectorCopy(saberent->r.currentOrigin, saberent->r.maxs); - for (i = 0; i < 3; i++) - { - for (j = 0; j < MAX_SABERS; j++) - { - if (!owner->client->saber[j].model[0]) - { + for (i = 0; i < 3; i++) { + for (j = 0; j < MAX_SABERS; j++) { + if (!owner->client->saber[j].model[0]) { break; } - if ( dualSabers - && owner->client->ps.saberHolstered == 1 - && j == 1 ) - { //this mother is holstered, get outta here. + if (dualSabers && owner->client->ps.saberHolstered == 1 && j == 1) { // this mother is holstered, get outta here. j++; continue; } - for (k = 0; k < owner->client->saber[j].numBlades; k++) - { - if ( k > 0 ) - {//not the first blade - if ( !dualSabers ) - {//using a single saber - if ( owner->client->saber[j].numBlades > 1 ) - {//with multiple blades - if( owner->client->ps.saberHolstered == 1 ) - {//all blades after the first one are off + for (k = 0; k < owner->client->saber[j].numBlades; k++) { + if (k > 0) { // not the first blade + if (!dualSabers) { // using a single saber + if (owner->client->saber[j].numBlades > 1) { // with multiple blades + if (owner->client->ps.saberHolstered == 1) { // all blades after the first one are off break; } } } } - if ( forceBlock ) - {//only do blocking with blades that are marked to block - if ( !alwaysBlock[j][k] ) - {//this blade shouldn't be blocking + if (forceBlock) { // only do blocking with blades that are marked to block + if (!alwaysBlock[j][k]) { // this blade shouldn't be blocking continue; } } - //VectorMA(owner->client->saber[j].blade[k].muzzlePoint, owner->client->saber[j].blade[k].lengthMax*0.5f, owner->client->saber[j].blade[k].muzzleDir, saberOrg); + // VectorMA(owner->client->saber[j].blade[k].muzzlePoint, owner->client->saber[j].blade[k].lengthMax*0.5f, + // owner->client->saber[j].blade[k].muzzleDir, saberOrg); VectorCopy(owner->client->saber[j].blade[k].muzzlePoint, saberOrg); - VectorMA(owner->client->saber[j].blade[k].muzzlePoint, owner->client->saber[j].blade[k].lengthMax, owner->client->saber[j].blade[k].muzzleDir, saberTip); + VectorMA(owner->client->saber[j].blade[k].muzzlePoint, owner->client->saber[j].blade[k].lengthMax, owner->client->saber[j].blade[k].muzzleDir, + saberTip); - if (saberOrg[i] < saberent->r.mins[i]) - { + if (saberOrg[i] < saberent->r.mins[i]) { saberent->r.mins[i] = saberOrg[i]; } - if (saberTip[i] < saberent->r.mins[i]) - { + if (saberTip[i] < saberent->r.mins[i]) { saberent->r.mins[i] = saberTip[i]; } - if (saberOrg[i] > saberent->r.maxs[i]) - { + if (saberOrg[i] > saberent->r.maxs[i]) { saberent->r.maxs[i] = saberOrg[i]; } - if (saberTip[i] > saberent->r.maxs[i]) - { + if (saberTip[i] > saberent->r.maxs[i]) { saberent->r.maxs[i] = saberTip[i]; } - //G_TestLine(saberOrg, saberTip, 0x0000ff, 50); + // G_TestLine(saberOrg, saberTip, 0x0000ff, 50); } } } @@ -567,34 +475,26 @@ static QINLINE void SetSaberBoxSize(gentity_t *saberent) VectorSubtract(saberent->r.maxs, saberent->r.currentOrigin, saberent->r.maxs); } -void WP_SaberInitBladeData( gentity_t *ent ) -{ +void WP_SaberInitBladeData(gentity_t *ent) { gentity_t *saberent = NULL; gentity_t *checkEnt; int i = 0; - while (i < level.num_entities) - { //make sure there are no other saber entities floating around that think they belong to this client. + while (i < level.num_entities) { // make sure there are no other saber entities floating around that think they belong to this client. checkEnt = &g_entities[i]; - if (checkEnt->inuse && checkEnt->neverFree && - checkEnt->r.ownerNum == ent->s.number && - checkEnt->classname && checkEnt->classname[0] && - !Q_stricmp(checkEnt->classname, "lightsaber")) - { - if (saberent) - { //already have one + if (checkEnt->inuse && checkEnt->neverFree && checkEnt->r.ownerNum == ent->s.number && checkEnt->classname && checkEnt->classname[0] && + !Q_stricmp(checkEnt->classname, "lightsaber")) { + if (saberent) { // already have one checkEnt->neverFree = qfalse; checkEnt->think = G_FreeEntity; checkEnt->nextthink = level.time; - } - else - { //hmm.. well then, take it as my own. - //free the bitch but don't issue a kg2 to avoid overflowing clients. + } else { // hmm.. well then, take it as my own. + // free the bitch but don't issue a kg2 to avoid overflowing clients. checkEnt->s.modelGhoul2 = 0; G_FreeEntity(checkEnt); - //now init it manually and reuse this ent slot. + // now init it manually and reuse this ent slot. G_InitGentity(checkEnt); saberent = checkEnt; } @@ -603,16 +503,15 @@ void WP_SaberInitBladeData( gentity_t *ent ) i++; } - //We do not want the client to have any real knowledge of the entity whatsoever. It will only - //ever be used on the server. - if (!saberent) - { //ok, make one then + // We do not want the client to have any real knowledge of the entity whatsoever. It will only + // ever be used on the server. + if (!saberent) { // ok, make one then saberent = G_Spawn(); } ent->client->ps.saberEntityNum = ent->client->saberStoredIndex = saberent->s.number; saberent->classname = "lightsaber"; - saberent->neverFree = qtrue; //the saber being removed would be a terrible thing. + saberent->neverFree = qtrue; // the saber being removed would be a terrible thing. saberent->r.svFlags = SVF_USE_CURRENT_ORIGIN; saberent->r.ownerNum = ent->s.number; @@ -628,8 +527,8 @@ void WP_SaberInitBladeData( gentity_t *ent ) saberent->r.svFlags |= SVF_NOCLIENT; saberent->s.modelGhoul2 = 1; - //should we happen to be removed (we belong to an NPC and he is removed) then - //we want to attempt to remove our g2 instance on the client in case we had one. + // should we happen to be removed (we belong to an NPC and he is removed) then + // we want to attempt to remove our g2 instance on the client in case we had one. saberent->touch = SaberGotHit; @@ -640,44 +539,35 @@ void WP_SaberInitBladeData( gentity_t *ent ) saberSpinSound = G_SoundIndex("sound/weapons/saber/saberspin.wav"); } -#define LOOK_DEFAULT_SPEED 0.15f -#define LOOK_TALKING_SPEED 0.15f +#define LOOK_DEFAULT_SPEED 0.15f +#define LOOK_TALKING_SPEED 0.15f -static QINLINE qboolean G_CheckLookTarget( gentity_t *ent, vec3_t lookAngles, float *lookingSpeed ) -{ - //FIXME: also clamp the lookAngles based on the clamp + the existing difference between +static QINLINE qboolean G_CheckLookTarget(gentity_t *ent, vec3_t lookAngles, float *lookingSpeed) { + // FIXME: also clamp the lookAngles based on the clamp + the existing difference between // headAngles and torsoAngles? But often the tag_torso is straight but the torso itself // is deformed to not face straight... sigh... - if (ent->s.eType == ET_NPC && - ent->s.m_iVehicleNum && - ent->s.NPC_class != CLASS_VEHICLE ) - { //an NPC bolted to a vehicle should just look around randomly - if ( TIMER_Done( ent, "lookAround" ) ) - { - ent->NPC->shootAngles[YAW] = flrand(0,360); - TIMER_Set( ent, "lookAround", Q_irand( 500, 3000 ) ); + if (ent->s.eType == ET_NPC && ent->s.m_iVehicleNum && ent->s.NPC_class != CLASS_VEHICLE) { // an NPC bolted to a vehicle should just look around randomly + if (TIMER_Done(ent, "lookAround")) { + ent->NPC->shootAngles[YAW] = flrand(0, 360); + TIMER_Set(ent, "lookAround", Q_irand(500, 3000)); } - VectorSet( lookAngles, 0, ent->NPC->shootAngles[YAW], 0 ); + VectorSet(lookAngles, 0, ent->NPC->shootAngles[YAW], 0); return qtrue; } - //Now calc head angle to lookTarget, if any - if ( ent->client->renderInfo.lookTarget >= 0 && ent->client->renderInfo.lookTarget < ENTITYNUM_WORLD ) - { - vec3_t lookDir, lookOrg, eyeOrg; + // Now calc head angle to lookTarget, if any + if (ent->client->renderInfo.lookTarget >= 0 && ent->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { + vec3_t lookDir, lookOrg, eyeOrg; int i; - if ( ent->client->renderInfo.lookMode == LM_ENT ) - { - gentity_t *lookCent = &g_entities[ent->client->renderInfo.lookTarget]; - if ( lookCent ) - { - if ( lookCent != ent->enemy ) - {//We turn heads faster than headbob speed, but not as fast as if watching an enemy + if (ent->client->renderInfo.lookMode == LM_ENT) { + gentity_t *lookCent = &g_entities[ent->client->renderInfo.lookTarget]; + if (lookCent) { + if (lookCent != ent->enemy) { // We turn heads faster than headbob speed, but not as fast as if watching an enemy *lookingSpeed = LOOK_DEFAULT_SPEED; } - //FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? + // FIXME: Ignore small deltas from current angles so we don't bob our head in synch with theirs? /* if ( ent->client->renderInfo.lookTarget == 0 && !cg.renderingThirdPerson )//!cg_thirdPerson.integer ) @@ -685,84 +575,65 @@ static QINLINE qboolean G_CheckLookTarget( gentity_t *ent, vec3_t lookAngles, fl VectorCopy( cg.refdef.vieworg, lookOrg ); } */ //No no no! - if ( lookCent->client ) - { - VectorCopy( lookCent->client->renderInfo.eyePoint, lookOrg ); - } - else if ( lookCent->inuse && !VectorCompare( lookCent->r.currentOrigin, vec3_origin ) ) - { - VectorCopy( lookCent->r.currentOrigin, lookOrg ); - } - else - {//at origin of world + if (lookCent->client) { + VectorCopy(lookCent->client->renderInfo.eyePoint, lookOrg); + } else if (lookCent->inuse && !VectorCompare(lookCent->r.currentOrigin, vec3_origin)) { + VectorCopy(lookCent->r.currentOrigin, lookOrg); + } else { // at origin of world return qfalse; } - //Look in dir of lookTarget + // Look in dir of lookTarget } - } - else if ( ent->client->renderInfo.lookMode == LM_INTEREST && ent->client->renderInfo.lookTarget > -1 && ent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS ) - { - VectorCopy( level.interestPoints[ent->client->renderInfo.lookTarget].origin, lookOrg ); - } - else - { + } else if (ent->client->renderInfo.lookMode == LM_INTEREST && ent->client->renderInfo.lookTarget > -1 && + ent->client->renderInfo.lookTarget < MAX_INTEREST_POINTS) { + VectorCopy(level.interestPoints[ent->client->renderInfo.lookTarget].origin, lookOrg); + } else { return qfalse; } - VectorCopy( ent->client->renderInfo.eyePoint, eyeOrg ); + VectorCopy(ent->client->renderInfo.eyePoint, eyeOrg); - VectorSubtract( lookOrg, eyeOrg, lookDir ); + VectorSubtract(lookOrg, eyeOrg, lookDir); - vectoangles( lookDir, lookAngles ); + vectoangles(lookDir, lookAngles); - for ( i = 0; i < 3; i++ ) - { - lookAngles[i] = AngleNormalize180( lookAngles[i] ); - ent->client->renderInfo.eyeAngles[i] = AngleNormalize180( ent->client->renderInfo.eyeAngles[i] ); + for (i = 0; i < 3; i++) { + lookAngles[i] = AngleNormalize180(lookAngles[i]); + ent->client->renderInfo.eyeAngles[i] = AngleNormalize180(ent->client->renderInfo.eyeAngles[i]); } - AnglesSubtract( lookAngles, ent->client->renderInfo.eyeAngles, lookAngles ); + AnglesSubtract(lookAngles, ent->client->renderInfo.eyeAngles, lookAngles); return qtrue; } return qfalse; } -//rww - attempted "port" of the SP version which is completely client-side and -//uses illegal gentity access. I am trying to keep this from being too -//bandwidth-intensive. -//This is primarily droid stuff I guess, I'm going to try to handle all humanoid -//NPC stuff in with the actual player stuff if possible. +// rww - attempted "port" of the SP version which is completely client-side and +// uses illegal gentity access. I am trying to keep this from being too +// bandwidth-intensive. +// This is primarily droid stuff I guess, I'm going to try to handle all humanoid +// NPC stuff in with the actual player stuff if possible. void NPC_SetBoneAngles(gentity_t *ent, char *bone, vec3_t angles); -static QINLINE void G_G2NPCAngles(gentity_t *ent, matrix3_t legs, vec3_t angles) -{ +static QINLINE void G_G2NPCAngles(gentity_t *ent, matrix3_t legs, vec3_t angles) { char *craniumBone = "cranium"; - char *thoracicBone = "thoracic"; //only used by atst so doesn't need a case + char *thoracicBone = "thoracic"; // only used by atst so doesn't need a case qboolean looking = qfalse; vec3_t viewAngles; vec3_t lookAngles; - if ( ent->client ) - { - if ( (ent->client->NPC_class == CLASS_PROBE ) - || (ent->client->NPC_class == CLASS_R2D2 ) - || (ent->client->NPC_class == CLASS_R5D2) - || (ent->client->NPC_class == CLASS_ATST) ) - { - vec3_t trailingLegsAngles; + if (ent->client) { + if ((ent->client->NPC_class == CLASS_PROBE) || (ent->client->NPC_class == CLASS_R2D2) || (ent->client->NPC_class == CLASS_R5D2) || + (ent->client->NPC_class == CLASS_ATST)) { + vec3_t trailingLegsAngles; - if (ent->s.eType == ET_NPC && - ent->s.m_iVehicleNum && - ent->s.NPC_class != CLASS_VEHICLE ) - { //an NPC bolted to a vehicle should use the full angles + if (ent->s.eType == ET_NPC && ent->s.m_iVehicleNum && ent->s.NPC_class != CLASS_VEHICLE) { // an NPC bolted to a vehicle should use the full angles VectorCopy(ent->r.currentAngles, angles); - } - else - { - VectorCopy( ent->client->ps.viewangles, angles ); + } else { + VectorCopy(ent->client->ps.viewangles, angles); angles[PITCH] = 0; } - //FIXME: use actual swing/clamp tolerances? + // FIXME: use actual swing/clamp tolerances? /* if ( ent->client->ps.groundEntityNum != ENTITYNUM_NONE ) {//on the ground @@ -774,29 +645,26 @@ static QINLINE void G_G2NPCAngles(gentity_t *ent, matrix3_t legs, vec3_t angles) } */ - VectorCopy( ent->client->ps.viewangles, viewAngles ); - // viewAngles[YAW] = viewAngles[ROLL] = 0; + VectorCopy(ent->client->ps.viewangles, viewAngles); + // viewAngles[YAW] = viewAngles[ROLL] = 0; viewAngles[PITCH] *= 0.5; - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); lookAngles[1] = 0; - if ( ent->client->NPC_class == CLASS_ATST ) - {//body pitch + if (ent->client->NPC_class == CLASS_ATST) { // body pitch NPC_SetBoneAngles(ent, thoracicBone, lookAngles); - //BG_G2SetBoneAngles( cent, ent, ent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT,POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + // BG_G2SetBoneAngles( cent, ent, ent->thoracicBone, lookAngles, BONE_ANGLES_POSTMULT,POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); } - VectorCopy( viewAngles, lookAngles ); + VectorCopy(viewAngles, lookAngles); - if ( ent && ent->client && ent->client->NPC_class == CLASS_ATST ) - { - //CG_ATSTLegsYaw( cent, trailingLegsAngles ); - AnglesToAxis( trailingLegsAngles, legs ); - } - else - { - //FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in place + if (ent && ent->client && ent->client->NPC_class == CLASS_ATST) { + // CG_ATSTLegsYaw( cent, trailingLegsAngles ); + AnglesToAxis(trailingLegsAngles, legs); + } else { + // FIXME: this needs to properly set the legs.yawing field so we don't erroneously play the turning anim, but we do play it when turning in + // place /* if ( angles[YAW] == cent->pe.legs.yawAngle ) { @@ -816,80 +684,66 @@ static QINLINE void G_G2NPCAngles(gentity_t *ent, matrix3_t legs, vec3_t angles) */ } - // if ( ent && ent->client && ent->client->NPC_class == CLASS_ATST ) - // { - // looking = qfalse; - // } - // else - { //look at lookTarget! - //FIXME: snaps to side when lets go of lookTarget... ? - float lookingSpeed = 0.3f; - looking = G_CheckLookTarget( ent, lookAngles, &lookingSpeed ); - lookAngles[PITCH] = lookAngles[ROLL] = 0;//droids can't pitch or roll their heads - if ( looking ) - {//want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) + // if ( ent && ent->client && ent->client->NPC_class == CLASS_ATST ) + // { + // looking = qfalse; + // } + // else + { // look at lookTarget! + // FIXME: snaps to side when lets go of lookTarget... ? + float lookingSpeed = 0.3f; + looking = G_CheckLookTarget(ent, lookAngles, &lookingSpeed); + lookAngles[PITCH] = lookAngles[ROLL] = 0; // droids can't pitch or roll their heads + if (looking) { // want to keep doing this lerp behavior for a full second after stopped looking (so don't snap) ent->client->renderInfo.lookingDebounceTime = level.time + 1000; } } - if ( ent->client->renderInfo.lookingDebounceTime > level.time ) - { //adjust for current body orientation - vec3_t oldLookAngles; + if (ent->client->renderInfo.lookingDebounceTime > level.time) { // adjust for current body orientation + vec3_t oldLookAngles; - lookAngles[YAW] -= 0;//ent->client->ps.viewangles[YAW];//cent->pe.torso.yawAngle; - //lookAngles[YAW] -= cent->pe.legs.yawAngle; + lookAngles[YAW] -= 0; // ent->client->ps.viewangles[YAW];//cent->pe.torso.yawAngle; + // lookAngles[YAW] -= cent->pe.legs.yawAngle; - //normalize - lookAngles[YAW] = AngleNormalize180( lookAngles[YAW] ); + // normalize + lookAngles[YAW] = AngleNormalize180(lookAngles[YAW]); - //slowly lerp to this new value - //Remember last headAngles - VectorCopy( ent->client->renderInfo.lastHeadAngles, oldLookAngles ); - if( VectorCompare( oldLookAngles, lookAngles ) == qfalse ) - { - //FIXME: This clamp goes off viewAngles, - //but really should go off the tag_torso's axis[0] angles, no? - lookAngles[YAW] = oldLookAngles[YAW]+(lookAngles[YAW]-oldLookAngles[YAW])*0.4f; + // slowly lerp to this new value + // Remember last headAngles + VectorCopy(ent->client->renderInfo.lastHeadAngles, oldLookAngles); + if (VectorCompare(oldLookAngles, lookAngles) == qfalse) { + // FIXME: This clamp goes off viewAngles, + // but really should go off the tag_torso's axis[0] angles, no? + lookAngles[YAW] = oldLookAngles[YAW] + (lookAngles[YAW] - oldLookAngles[YAW]) * 0.4f; } - //Remember current lookAngles next time - VectorCopy( lookAngles, ent->client->renderInfo.lastHeadAngles ); + // Remember current lookAngles next time + VectorCopy(lookAngles, ent->client->renderInfo.lastHeadAngles); + } else { // Remember current lookAngles next time + VectorCopy(lookAngles, ent->client->renderInfo.lastHeadAngles); } - else - {//Remember current lookAngles next time - VectorCopy( lookAngles, ent->client->renderInfo.lastHeadAngles ); - } - if ( ent->client->NPC_class == CLASS_ATST ) - { - VectorCopy( ent->client->ps.viewangles, lookAngles ); + if (ent->client->NPC_class == CLASS_ATST) { + VectorCopy(ent->client->ps.viewangles, lookAngles); lookAngles[0] = lookAngles[2] = 0; lookAngles[YAW] -= trailingLegsAngles[YAW]; - } - else - { + } else { lookAngles[PITCH] = lookAngles[ROLL] = 0; lookAngles[YAW] -= ent->client->ps.viewangles[YAW]; } NPC_SetBoneAngles(ent, craniumBone, lookAngles); - //BG_G2SetBoneAngles( cent, ent, ent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); - //return; - } - else//if ( (ent->client->NPC_class == CLASS_GONK ) || (ent->client->NPC_class == CLASS_INTERROGATOR) || (ent->client->NPC_class == CLASS_SENTRY) ) + // BG_G2SetBoneAngles( cent, ent, ent->craniumBone, lookAngles, BONE_ANGLES_POSTMULT, POSITIVE_X, NEGATIVE_Y, NEGATIVE_Z, cgs.model_draw); + // return; + } else // if ( (ent->client->NPC_class == CLASS_GONK ) || (ent->client->NPC_class == CLASS_INTERROGATOR) || (ent->client->NPC_class == CLASS_SENTRY) ) { - // VectorCopy( ent->client->ps.viewangles, angles ); - // AnglesToAxis( angles, legs ); - //return; + // VectorCopy( ent->client->ps.viewangles, angles ); + // AnglesToAxis( angles, legs ); + // return; } } } -static QINLINE void G_G2PlayerAngles( gentity_t *ent, matrix3_t legs, vec3_t legsAngles) -{ - qboolean tPitching = qfalse, - tYawing = qfalse, - lYawing = qfalse; - float tYawAngle = ent->client->ps.viewangles[YAW], - tPitchAngle = 0, - lYawAngle = ent->client->ps.viewangles[YAW]; +static QINLINE void G_G2PlayerAngles(gentity_t *ent, matrix3_t legs, vec3_t legsAngles) { + qboolean tPitching = qfalse, tYawing = qfalse, lYawing = qfalse; + float tYawAngle = ent->client->ps.viewangles[YAW], tPitchAngle = 0, lYawAngle = ent->client->ps.viewangles[YAW]; int ciLegs = ent->client->ps.legsAnim; int ciTorso = ent->client->ps.torsoAnim; @@ -897,27 +751,22 @@ static QINLINE void G_G2PlayerAngles( gentity_t *ent, matrix3_t legs, vec3_t leg vec3_t turAngles; vec3_t lerpOrg, lerpAng; - if (ent->s.eType == ET_NPC && ent->client) - { //sort of hacky, but it saves a pretty big load off the server + if (ent->s.eType == ET_NPC && ent->client) { // sort of hacky, but it saves a pretty big load off the server int i = 0; gentity_t *clEnt; - //If no real clients are in the same PVS then don't do any of this stuff, no one can see him anyway! - while (i < MAX_CLIENTS) - { + // If no real clients are in the same PVS then don't do any of this stuff, no one can see him anyway! + while (i < MAX_CLIENTS) { clEnt = &g_entities[i]; - if (clEnt && clEnt->inuse && clEnt->client && - trap->InPVS(clEnt->client->ps.origin, ent->client->ps.origin)) - { //this client can see him + if (clEnt && clEnt->inuse && clEnt->client && trap->InPVS(clEnt->client->ps.origin, ent->client->ps.origin)) { // this client can see him break; } i++; } - if (i == MAX_CLIENTS) - { //no one can see him, just return + if (i == MAX_CLIENTS) { // no one can see him, just return return; } } @@ -925,52 +774,41 @@ static QINLINE void G_G2PlayerAngles( gentity_t *ent, matrix3_t legs, vec3_t leg VectorCopy(ent->client->ps.origin, lerpOrg); VectorCopy(ent->client->ps.viewangles, lerpAng); - if (ent->localAnimIndex <= 1) - { //don't do these things on non-humanoids + if (ent->localAnimIndex <= 1) { // don't do these things on non-humanoids vec3_t lookAngles; entityState_t *emplaced = NULL; - if (ent->client->ps.hasLookTarget) - { + if (ent->client->ps.hasLookTarget) { VectorSubtract(g_entities[ent->client->ps.lookTarget].r.currentOrigin, ent->client->ps.origin, lookAngles); vectoangles(lookAngles, lookAngles); ent->client->lookTime = level.time + 1000; - } - else - { + } else { VectorCopy(ent->client->ps.origin, lookAngles); } lookAngles[PITCH] = 0; - if (ent->client->ps.emplacedIndex) - { + if (ent->client->ps.emplacedIndex) { emplaced = &g_entities[ent->client->ps.emplacedIndex].s; } - BG_G2PlayerAngles(ent->ghoul2, ent->client->renderInfo.motionBolt, &ent->s, level.time, lerpOrg, lerpAng, legs, - legsAngles, &tYawing, &tPitching, &lYawing, &tYawAngle, &tPitchAngle, &lYawAngle, FRAMETIME, turAngles, - ent->modelScale, ciLegs, ciTorso, &ent->client->corrTime, lookAngles, ent->client->lastHeadAngles, - ent->client->lookTime, emplaced, NULL); + BG_G2PlayerAngles(ent->ghoul2, ent->client->renderInfo.motionBolt, &ent->s, level.time, lerpOrg, lerpAng, legs, legsAngles, &tYawing, &tPitching, + &lYawing, &tYawAngle, &tPitchAngle, &lYawAngle, FRAMETIME, turAngles, ent->modelScale, ciLegs, ciTorso, &ent->client->corrTime, + lookAngles, ent->client->lastHeadAngles, ent->client->lookTime, emplaced, NULL); - if (ent->client->ps.heldByClient && ent->client->ps.heldByClient <= MAX_CLIENTS) - { //then put our arm in this client's hand - //is index+1 because index 0 is valid. - int heldByIndex = ent->client->ps.heldByClient-1; + if (ent->client->ps.heldByClient && ent->client->ps.heldByClient <= MAX_CLIENTS) { // then put our arm in this client's hand + // is index+1 because index 0 is valid. + int heldByIndex = ent->client->ps.heldByClient - 1; gentity_t *other = &g_entities[heldByIndex]; int lHandBolt = 0; - if (other && other->inuse && other->client && other->ghoul2) - { + if (other && other->inuse && other->client && other->ghoul2) { lHandBolt = trap->G2API_AddBolt(other->ghoul2, 0, "*l_hand"); - } - else - { //they left the game, perhaps? + } else { // they left the game, perhaps? ent->client->ps.heldByClient = 0; return; } - if (lHandBolt) - { + if (lHandBolt) { mdxaBone_t boltMatrix; vec3_t boltOrg; vec3_t tAngles; @@ -983,142 +821,101 @@ static QINLINE void G_G2PlayerAngles( gentity_t *ent, matrix3_t legs, vec3_t leg boltOrg[1] = boltMatrix.matrix[1][3]; boltOrg[2] = boltMatrix.matrix[2][3]; - BG_IK_MoveArm(ent->ghoul2, lHandBolt, level.time, &ent->s, ent->client->ps.torsoAnim/*BOTH_DEAD1*/, boltOrg, &ent->client->ikStatus, - ent->client->ps.origin, ent->client->ps.viewangles, ent->modelScale, 500, qfalse); + BG_IK_MoveArm(ent->ghoul2, lHandBolt, level.time, &ent->s, ent->client->ps.torsoAnim /*BOTH_DEAD1*/, boltOrg, &ent->client->ikStatus, + ent->client->ps.origin, ent->client->ps.viewangles, ent->modelScale, 500, qfalse); } - } - else if (ent->client->ikStatus) - { //make sure we aren't IKing if we don't have anyone to hold onto us. + } else if (ent->client->ikStatus) { // make sure we aren't IKing if we don't have anyone to hold onto us. int lHandBolt = 0; - if (ent && ent->inuse && ent->client && ent->ghoul2) - { + if (ent && ent->inuse && ent->client && ent->ghoul2) { lHandBolt = trap->G2API_AddBolt(ent->ghoul2, 0, "*l_hand"); - } - else - { //This shouldn't happen, but just in case it does, we'll have a failsafe. + } else { // This shouldn't happen, but just in case it does, we'll have a failsafe. ent->client->ikStatus = qfalse; } - if (lHandBolt) - { - BG_IK_MoveArm(ent->ghoul2, lHandBolt, level.time, &ent->s, - ent->client->ps.torsoAnim/*BOTH_DEAD1*/, vec3_origin, &ent->client->ikStatus, ent->client->ps.origin, ent->client->ps.viewangles, ent->modelScale, 500, qtrue); + if (lHandBolt) { + BG_IK_MoveArm(ent->ghoul2, lHandBolt, level.time, &ent->s, ent->client->ps.torsoAnim /*BOTH_DEAD1*/, vec3_origin, &ent->client->ikStatus, + ent->client->ps.origin, ent->client->ps.viewangles, ent->modelScale, 500, qtrue); } } - } - else if ( ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER ) - { + } else if (ent->m_pVehicle && ent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER) { vec3_t lookAngles; VectorCopy(ent->client->ps.viewangles, legsAngles); legsAngles[PITCH] = 0; - AnglesToAxis( legsAngles, legs ); + AnglesToAxis(legsAngles, legs); VectorCopy(ent->client->ps.viewangles, lookAngles); lookAngles[YAW] = lookAngles[ROLL] = 0; - BG_G2ATSTAngles( ent->ghoul2, level.time, lookAngles ); - } - else if (ent->NPC) - { //an NPC not using a humanoid skeleton, do special angle stuff. - if (ent->s.eType == ET_NPC && - ent->s.NPC_class == CLASS_VEHICLE && - ent->m_pVehicle && - ent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) - { //fighters actually want to take pitch and roll into account for the axial angles + BG_G2ATSTAngles(ent->ghoul2, level.time, lookAngles); + } else if (ent->NPC) { // an NPC not using a humanoid skeleton, do special angle stuff. + if (ent->s.eType == ET_NPC && ent->s.NPC_class == CLASS_VEHICLE && ent->m_pVehicle && + ent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER) { // fighters actually want to take pitch and roll into account for the axial angles VectorCopy(ent->client->ps.viewangles, legsAngles); - AnglesToAxis( legsAngles, legs ); - } - else - { + AnglesToAxis(legsAngles, legs); + } else { G_G2NPCAngles(ent, legs, legsAngles); } } } -static QINLINE qboolean SaberAttacking( gentity_t *self ) -{ - if ( PM_SaberInParry(self->client->ps.saberMove) ) +static QINLINE qboolean SaberAttacking(gentity_t *self) { + if (PM_SaberInParry(self->client->ps.saberMove)) return qfalse; - if ( PM_SaberInBrokenParry(self->client->ps.saberMove) ) + if (PM_SaberInBrokenParry(self->client->ps.saberMove)) return qfalse; - if ( PM_SaberInDeflect(self->client->ps.saberMove) ) + if (PM_SaberInDeflect(self->client->ps.saberMove)) return qfalse; - if ( PM_SaberInBounce(self->client->ps.saberMove) ) + if (PM_SaberInBounce(self->client->ps.saberMove)) return qfalse; - if ( PM_SaberInKnockaway(self->client->ps.saberMove) ) + if (PM_SaberInKnockaway(self->client->ps.saberMove)) return qfalse; - //if we're firing and not blocking, then we're attacking. + // if we're firing and not blocking, then we're attacking. if (BG_SaberInAttack(self->client->ps.saberMove)) if (self->client->ps.weaponstate == WEAPON_FIRING && self->client->ps.saberBlocked == BLOCKED_NONE) return qtrue; - if ( BG_SaberInSpecial( self->client->ps.saberMove ) ) + if (BG_SaberInSpecial(self->client->ps.saberMove)) return qtrue; return qfalse; } -typedef enum -{ - LOCK_FIRST = 0, - LOCK_TOP = LOCK_FIRST, - LOCK_DIAG_TR, - LOCK_DIAG_TL, - LOCK_DIAG_BR, - LOCK_DIAG_BL, - LOCK_R, - LOCK_L, - LOCK_RANDOM -} sabersLockMode_t; +typedef enum { LOCK_FIRST = 0, LOCK_TOP = LOCK_FIRST, LOCK_DIAG_TR, LOCK_DIAG_TL, LOCK_DIAG_BR, LOCK_DIAG_BL, LOCK_R, LOCK_L, LOCK_RANDOM } sabersLockMode_t; #define LOCK_IDEAL_DIST_TOP 32.0f #define LOCK_IDEAL_DIST_CIRCLE 48.0f #define SABER_HITDAMAGE 35 -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ); +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock); -int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSide, int lockOrBreakOrSuperBreak, int winOrLose ) -{ +int G_SaberLockAnim(int attackerSaberStyle, int defenderSaberStyle, int topOrSide, int lockOrBreakOrSuperBreak, int winOrLose) { int baseAnim = -1; - if ( lockOrBreakOrSuperBreak == SABERLOCK_LOCK ) - {//special case: if we're using the same style and locking - if ( attackerSaberStyle == defenderSaberStyle - || (attackerSaberStyle>=SS_FAST&&attackerSaberStyle<=SS_TAVION&&defenderSaberStyle>=SS_FAST&&defenderSaberStyle<=SS_TAVION) ) - {//using same style - if ( winOrLose == SABERLOCK_LOSE ) - {//you want the defender's stance... - switch ( defenderSaberStyle ) - { + if (lockOrBreakOrSuperBreak == SABERLOCK_LOCK) { // special case: if we're using the same style and locking + if (attackerSaberStyle == defenderSaberStyle || (attackerSaberStyle >= SS_FAST && attackerSaberStyle <= SS_TAVION && defenderSaberStyle >= SS_FAST && + defenderSaberStyle <= SS_TAVION)) { // using same style + if (winOrLose == SABERLOCK_LOSE) { // you want the defender's stance... + switch (defenderSaberStyle) { case SS_DUAL: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_DL_DL_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_DL_DL_S_L_2; } break; case SS_STAFF: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_ST_ST_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_ST_ST_S_L_2; } break; default: - if ( topOrSide == SABERLOCK_TOP ) - { + if (topOrSide == SABERLOCK_TOP) { baseAnim = BOTH_LK_S_S_T_L_2; - } - else - { + } else { baseAnim = BOTH_LK_S_S_S_L_2; } break; @@ -1126,72 +923,61 @@ int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSi } } } - if ( baseAnim == -1 ) - { - switch ( attackerSaberStyle ) - { + if (baseAnim == -1) { + switch (attackerSaberStyle) { case SS_DUAL: - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_DL_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_DL_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_DL_S_S_B_1_L; - break; + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_DL_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_DL_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_DL_S_S_B_1_L; + break; } break; case SS_STAFF: - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_ST_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_ST_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_ST_S_S_B_1_L; - break; + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_ST_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_ST_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_ST_S_S_B_1_L; + break; } break; - default://single - switch ( defenderSaberStyle ) - { - case SS_DUAL: - baseAnim = BOTH_LK_S_DL_S_B_1_L; - break; - case SS_STAFF: - baseAnim = BOTH_LK_S_ST_S_B_1_L; - break; - default://single - baseAnim = BOTH_LK_S_S_S_B_1_L; - break; + default: // single + switch (defenderSaberStyle) { + case SS_DUAL: + baseAnim = BOTH_LK_S_DL_S_B_1_L; + break; + case SS_STAFF: + baseAnim = BOTH_LK_S_ST_S_B_1_L; + break; + default: // single + baseAnim = BOTH_LK_S_S_S_B_1_L; + break; } break; } - //side lock or top lock? - if ( topOrSide == SABERLOCK_TOP ) - { + // side lock or top lock? + if (topOrSide == SABERLOCK_TOP) { baseAnim += 5; } - //lock, break or superbreak? - if ( lockOrBreakOrSuperBreak == SABERLOCK_LOCK ) - { + // lock, break or superbreak? + if (lockOrBreakOrSuperBreak == SABERLOCK_LOCK) { baseAnim += 2; - } - else - {//a break or superbreak - if ( lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK ) - { + } else { // a break or superbreak + if (lockOrBreakOrSuperBreak == SABERLOCK_SUPERBREAK) { baseAnim += 3; } - //winner or loser? - if ( winOrLose == SABERLOCK_WIN ) - { + // winner or loser? + if (winOrLose == SABERLOCK_WIN) { baseAnim += 1; } } @@ -1199,32 +985,27 @@ int G_SaberLockAnim( int attackerSaberStyle, int defenderSaberStyle, int topOrSi return baseAnim; } -extern qboolean BG_CheckIncrementLockAnim( int anim, int winOrLose ); //bg_saber.c -#define LOCK_IDEAL_DIST_JKA 46.0f//all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN - -static QINLINE qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode ) -{ - int attAnim, defAnim = 0; - float attStart = 0.5f, defStart = 0.5f; - float idealDist = 48.0f; - vec3_t attAngles, defAngles, defDir; - vec3_t newOrg; - vec3_t attDir; - float diff = 0; +extern qboolean BG_CheckIncrementLockAnim(int anim, int winOrLose); // bg_saber.c +#define LOCK_IDEAL_DIST_JKA 46.0f // all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN + +static QINLINE qboolean WP_SabersCheckLock2(gentity_t *attacker, gentity_t *defender, sabersLockMode_t lockMode) { + int attAnim, defAnim = 0; + float attStart = 0.5f, defStart = 0.5f; + float idealDist = 48.0f; + vec3_t attAngles, defAngles, defDir; + vec3_t newOrg; + vec3_t attDir; + float diff = 0; trace_t trace; - //MATCH ANIMS - if ( lockMode == LOCK_RANDOM ) - { - lockMode = (sabersLockMode_t)Q_irand( (int)LOCK_FIRST, (int)(LOCK_RANDOM)-1 ); - } - if ( attacker->client->ps.fd.saberAnimLevel >= SS_FAST - && attacker->client->ps.fd.saberAnimLevel <= SS_TAVION - && defender->client->ps.fd.saberAnimLevel >= SS_FAST - && defender->client->ps.fd.saberAnimLevel <= SS_TAVION ) - {//2 single sabers? Just do it the old way... - switch ( lockMode ) - { + // MATCH ANIMS + if (lockMode == LOCK_RANDOM) { + lockMode = (sabersLockMode_t)Q_irand((int)LOCK_FIRST, (int)(LOCK_RANDOM)-1); + } + if (attacker->client->ps.fd.saberAnimLevel >= SS_FAST && attacker->client->ps.fd.saberAnimLevel <= SS_TAVION && + defender->client->ps.fd.saberAnimLevel >= SS_FAST && + defender->client->ps.fd.saberAnimLevel <= SS_TAVION) { // 2 single sabers? Just do it the old way... + switch (lockMode) { case LOCK_TOP: attAnim = BOTH_BF2LOCK; defAnim = BOTH_BF1LOCK; @@ -1271,109 +1052,93 @@ static QINLINE qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *def return qfalse; break; } - } - else - {//use the new system - idealDist = LOCK_IDEAL_DIST_JKA;//all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN - if ( lockMode == LOCK_TOP ) - {//top lock - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_LOSE ); + } else { // use the new system + idealDist = LOCK_IDEAL_DIST_JKA; // all of the new saberlocks are 46.08 from each other because Richard Lico is da MAN + if (lockMode == LOCK_TOP) { // top lock + attAnim = + G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_WIN); + defAnim = + G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_TOP, SABERLOCK_LOCK, SABERLOCK_LOSE); attStart = defStart = 0.5f; - } - else - {//side lock - switch ( lockMode ) - { + } else { // side lock + switch (lockMode) { case LOCK_DIAG_TR: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); attStart = defStart = 0.5f; break; case LOCK_DIAG_TL: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); attStart = defStart = 0.5f; break; case LOCK_DIAG_BR: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - if ( BG_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.85f;//move to end of anim - } - else - { - attStart = 0.15f;//start at beginning of anim - } - if ( BG_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.85f;//start at end of anim - } - else - { - defStart = 0.15f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + if (BG_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.85f; // move to end of anim + } else { + attStart = 0.15f; // start at beginning of anim + } + if (BG_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.85f; // start at end of anim + } else { + defStart = 0.15f; // start at beginning of anim } break; case LOCK_DIAG_BL: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - if ( BG_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.85f;//move to end of anim - } - else - { - attStart = 0.15f;//start at beginning of anim - } - if ( BG_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.85f;//start at end of anim - } - else - { - defStart = 0.15f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + if (BG_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.85f; // move to end of anim + } else { + attStart = 0.15f; // start at beginning of anim + } + if (BG_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.85f; // start at end of anim + } else { + defStart = 0.15f; // start at beginning of anim } break; case LOCK_R: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - if ( BG_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.75f;//move to end of anim - } - else - { - attStart = 0.25f;//start at beginning of anim - } - if ( BG_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.75f;//start at end of anim - } - else - { - defStart = 0.25f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + if (BG_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.75f; // move to end of anim + } else { + attStart = 0.25f; // start at beginning of anim + } + if (BG_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.75f; // start at end of anim + } else { + defStart = 0.25f; // start at beginning of anim } break; case LOCK_L: - attAnim = G_SaberLockAnim( attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_WIN ); - defAnim = G_SaberLockAnim( defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, SABERLOCK_LOSE ); - //attacker starts with advantage - if ( BG_CheckIncrementLockAnim( attAnim, SABERLOCK_WIN ) ) - { - attStart = 0.75f;//move to end of anim - } - else - { - attStart = 0.25f;//start at beginning of anim - } - if ( BG_CheckIncrementLockAnim( defAnim, SABERLOCK_LOSE ) ) - { - defStart = 0.75f;//start at end of anim - } - else - { - defStart = 0.25f;//start at beginning of anim + attAnim = G_SaberLockAnim(attacker->client->ps.fd.saberAnimLevel, defender->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_WIN); + defAnim = G_SaberLockAnim(defender->client->ps.fd.saberAnimLevel, attacker->client->ps.fd.saberAnimLevel, SABERLOCK_SIDE, SABERLOCK_LOCK, + SABERLOCK_LOSE); + // attacker starts with advantage + if (BG_CheckIncrementLockAnim(attAnim, SABERLOCK_WIN)) { + attStart = 0.75f; // move to end of anim + } else { + attStart = 0.25f; // start at beginning of anim + } + if (BG_CheckIncrementLockAnim(defAnim, SABERLOCK_LOSE)) { + defStart = 0.75f; // start at end of anim + } else { + defStart = 0.25f; // start at beginning of anim } break; default: @@ -1383,11 +1148,13 @@ static QINLINE qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *def } } - G_SetAnim(attacker, NULL, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - attacker->client->ps.saberLockFrame = bgAllAnims[attacker->localAnimIndex].anims[attAnim].firstFrame+(bgAllAnims[attacker->localAnimIndex].anims[attAnim].numFrames*attStart); + G_SetAnim(attacker, NULL, SETANIM_BOTH, attAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + attacker->client->ps.saberLockFrame = + bgAllAnims[attacker->localAnimIndex].anims[attAnim].firstFrame + (bgAllAnims[attacker->localAnimIndex].anims[attAnim].numFrames * attStart); - G_SetAnim(defender, NULL, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - defender->client->ps.saberLockFrame = bgAllAnims[defender->localAnimIndex].anims[defAnim].firstFrame+(bgAllAnims[defender->localAnimIndex].anims[defAnim].numFrames*defStart); + G_SetAnim(defender, NULL, SETANIM_BOTH, defAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + defender->client->ps.saberLockFrame = + bgAllAnims[defender->localAnimIndex].anims[defAnim].firstFrame + (bgAllAnims[defender->localAnimIndex].anims[defAnim].numFrames * defStart); attacker->client->ps.saberLockHits = 0; defender->client->ps.saberLockHits = 0; @@ -1395,578 +1162,392 @@ static QINLINE qboolean WP_SabersCheckLock2( gentity_t *attacker, gentity_t *def attacker->client->ps.saberLockAdvance = qfalse; defender->client->ps.saberLockAdvance = qfalse; - VectorClear( attacker->client->ps.velocity ); - VectorClear( defender->client->ps.velocity ); + VectorClear(attacker->client->ps.velocity); + VectorClear(defender->client->ps.velocity); attacker->client->ps.saberLockTime = defender->client->ps.saberLockTime = level.time + 10000; attacker->client->ps.saberLockEnemy = defender->s.number; defender->client->ps.saberLockEnemy = attacker->s.number; - attacker->client->ps.weaponTime = defender->client->ps.weaponTime = Q_irand( 1000, 3000 );//delay 1 to 3 seconds before pushing - - VectorSubtract( defender->r.currentOrigin, attacker->r.currentOrigin, defDir ); - VectorCopy( attacker->client->ps.viewangles, attAngles ); - attAngles[YAW] = vectoyaw( defDir ); - SetClientViewAngle( attacker, attAngles ); - defAngles[PITCH] = attAngles[PITCH]*-1; - defAngles[YAW] = AngleNormalize180( attAngles[YAW] + 180); + attacker->client->ps.weaponTime = defender->client->ps.weaponTime = Q_irand(1000, 3000); // delay 1 to 3 seconds before pushing + + VectorSubtract(defender->r.currentOrigin, attacker->r.currentOrigin, defDir); + VectorCopy(attacker->client->ps.viewangles, attAngles); + attAngles[YAW] = vectoyaw(defDir); + SetClientViewAngle(attacker, attAngles); + defAngles[PITCH] = attAngles[PITCH] * -1; + defAngles[YAW] = AngleNormalize180(attAngles[YAW] + 180); defAngles[ROLL] = 0; - SetClientViewAngle( defender, defAngles ); + SetClientViewAngle(defender, defAngles); - //MATCH POSITIONS - diff = VectorNormalize( defDir ) - idealDist;//diff will be the total error in dist - //try to move attacker half the diff towards the defender - VectorMA( attacker->r.currentOrigin, diff*0.5f, defDir, newOrg ); + // MATCH POSITIONS + diff = VectorNormalize(defDir) - idealDist; // diff will be the total error in dist + // try to move attacker half the diff towards the defender + VectorMA(attacker->r.currentOrigin, diff * 0.5f, defDir, newOrg); - trap->Trace( &trace, attacker->r.currentOrigin, attacker->r.mins, attacker->r.maxs, newOrg, attacker->s.number, attacker->clipmask, qfalse, 0, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - G_SetOrigin( attacker, trace.endpos ); - if (attacker->client) - { + trap->Trace(&trace, attacker->r.currentOrigin, attacker->r.mins, attacker->r.maxs, newOrg, attacker->s.number, attacker->clipmask, qfalse, 0, 0); + if (!trace.startsolid && !trace.allsolid) { + G_SetOrigin(attacker, trace.endpos); + if (attacker->client) { VectorCopy(trace.endpos, attacker->client->ps.origin); } - trap->LinkEntity( (sharedEntity_t *)attacker ); + trap->LinkEntity((sharedEntity_t *)attacker); } - //now get the defender's dist and do it for him too - VectorSubtract( attacker->r.currentOrigin, defender->r.currentOrigin, attDir ); - diff = VectorNormalize( attDir ) - idealDist;//diff will be the total error in dist - //try to move defender all of the remaining diff towards the attacker - VectorMA( defender->r.currentOrigin, diff, attDir, newOrg ); - trap->Trace( &trace, defender->r.currentOrigin, defender->r.mins, defender->r.maxs, newOrg, defender->s.number, defender->clipmask, qfalse, 0, 0 ); - if ( !trace.startsolid && !trace.allsolid ) - { - if (defender->client) - { + // now get the defender's dist and do it for him too + VectorSubtract(attacker->r.currentOrigin, defender->r.currentOrigin, attDir); + diff = VectorNormalize(attDir) - idealDist; // diff will be the total error in dist + // try to move defender all of the remaining diff towards the attacker + VectorMA(defender->r.currentOrigin, diff, attDir, newOrg); + trap->Trace(&trace, defender->r.currentOrigin, defender->r.mins, defender->r.maxs, newOrg, defender->s.number, defender->clipmask, qfalse, 0, 0); + if (!trace.startsolid && !trace.allsolid) { + if (defender->client) { VectorCopy(trace.endpos, defender->client->ps.origin); } - G_SetOrigin( defender, trace.endpos ); - trap->LinkEntity( (sharedEntity_t *)defender ); + G_SetOrigin(defender, trace.endpos); + trap->LinkEntity((sharedEntity_t *)defender); } - //DONE! + // DONE! return qtrue; } -qboolean WP_SabersCheckLock( gentity_t *ent1, gentity_t *ent2 ) -{ +qboolean WP_SabersCheckLock(gentity_t *ent1, gentity_t *ent2) { float dist; - qboolean ent1BlockingPlayer = qfalse; - qboolean ent2BlockingPlayer = qfalse; + qboolean ent1BlockingPlayer = qfalse; + qboolean ent2BlockingPlayer = qfalse; - if ( g_debugSaberLocks.integer ) - { - WP_SabersCheckLock2( ent1, ent2, LOCK_RANDOM ); + if (g_debugSaberLocks.integer) { + WP_SabersCheckLock2(ent1, ent2, LOCK_RANDOM); return qtrue; } - //for now.. it's not fair to the lone duelist. - //we need dual saber lock animations. - if (level.gametype == GT_POWERDUEL) - { + // for now.. it's not fair to the lone duelist. + // we need dual saber lock animations. + if (level.gametype == GT_POWERDUEL) { return qfalse; } - if (!g_saberLocking.integer) - { + if (!g_saberLocking.integer) { return qfalse; } - if (!ent1->client || !ent2->client) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if (ent1->s.eType == ET_NPC || - ent2->s.eType == ET_NPC) - { //if either ents is NPC, then never let an NPC lock with someone on the same playerTeam - if (ent1->client->playerTeam == ent2->client->playerTeam) - { + if (ent1->s.eType == ET_NPC || ent2->s.eType == ET_NPC) { // if either ents is NPC, then never let an NPC lock with someone on the same playerTeam + if (ent1->client->playerTeam == ent2->client->playerTeam) { return qfalse; } } - if (!ent1->client->ps.saberEntityNum || - !ent2->client->ps.saberEntityNum || - ent1->client->ps.saberInFlight || - ent2->client->ps.saberInFlight) - { //can't get in lock if one of them has had the saber knocked out of his hand + if (!ent1->client->ps.saberEntityNum || !ent2->client->ps.saberEntityNum || ent1->client->ps.saberInFlight || + ent2->client->ps.saberInFlight) { // can't get in lock if one of them has had the saber knocked out of his hand return qfalse; } - if (ent1->s.eType != ET_NPC && ent2->s.eType != ET_NPC) - { //can always get into locks with NPCs - if (!ent1->client->ps.duelInProgress || - !ent2->client->ps.duelInProgress || - ent1->client->ps.duelIndex != ent2->s.number || - ent2->client->ps.duelIndex != ent1->s.number) - { //only allow saber locking if two players are dueling with each other directly - if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) - { + if (ent1->s.eType != ET_NPC && ent2->s.eType != ET_NPC) { // can always get into locks with NPCs + if (!ent1->client->ps.duelInProgress || !ent2->client->ps.duelInProgress || ent1->client->ps.duelIndex != ent2->s.number || + ent2->client->ps.duelIndex != ent1->s.number) { // only allow saber locking if two players are dueling with each other directly + if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL) { return qfalse; } } } - if ( fabs( ent1->r.currentOrigin[2]-ent2->r.currentOrigin[2] ) > 16 ) - { + if (fabs(ent1->r.currentOrigin[2] - ent2->r.currentOrigin[2]) > 16) { return qfalse; } - if ( ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || - ent2->client->ps.groundEntityNum == ENTITYNUM_NONE ) - { + if (ent1->client->ps.groundEntityNum == ENTITYNUM_NONE || ent2->client->ps.groundEntityNum == ENTITYNUM_NONE) { return qfalse; } - dist = DistanceSquared(ent1->r.currentOrigin,ent2->r.currentOrigin); - if ( dist < 64 || dist > 6400 ) - {//between 8 and 80 from each other + dist = DistanceSquared(ent1->r.currentOrigin, ent2->r.currentOrigin); + if (dist < 64 || dist > 6400) { // between 8 and 80 from each other return qfalse; } - if (BG_InSpecialJump(ent1->client->ps.legsAnim)) - { + if (BG_InSpecialJump(ent1->client->ps.legsAnim)) { return qfalse; } - if (BG_InSpecialJump(ent2->client->ps.legsAnim)) - { + if (BG_InSpecialJump(ent2->client->ps.legsAnim)) { return qfalse; } - if (BG_InRoll(&ent1->client->ps, ent1->client->ps.legsAnim)) - { + if (BG_InRoll(&ent1->client->ps, ent1->client->ps.legsAnim)) { return qfalse; } - if (BG_InRoll(&ent2->client->ps, ent2->client->ps.legsAnim)) - { + if (BG_InRoll(&ent2->client->ps, ent2->client->ps.legsAnim)) { return qfalse; } - if (ent1->client->ps.forceHandExtend != HANDEXTEND_NONE || - ent2->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (ent1->client->ps.forceHandExtend != HANDEXTEND_NONE || ent2->client->ps.forceHandExtend != HANDEXTEND_NONE) { return qfalse; } - if ((ent1->client->ps.pm_flags & PMF_DUCKED) || - (ent2->client->ps.pm_flags & PMF_DUCKED)) - { + if ((ent1->client->ps.pm_flags & PMF_DUCKED) || (ent2->client->ps.pm_flags & PMF_DUCKED)) { return qfalse; } - if ( (ent1->client->saber[0].saberFlags&SFL_NOT_LOCKABLE) - || (ent2->client->saber[0].saberFlags&SFL_NOT_LOCKABLE) ) - { + if ((ent1->client->saber[0].saberFlags & SFL_NOT_LOCKABLE) || (ent2->client->saber[0].saberFlags & SFL_NOT_LOCKABLE)) { return qfalse; } - if ( ent1->client->saber[1].model[0] - && !ent1->client->ps.saberHolstered - && (ent1->client->saber[1].saberFlags&SFL_NOT_LOCKABLE) ) - { + if (ent1->client->saber[1].model[0] && !ent1->client->ps.saberHolstered && (ent1->client->saber[1].saberFlags & SFL_NOT_LOCKABLE)) { return qfalse; } - if ( ent2->client->saber[1].model[0] - && !ent2->client->ps.saberHolstered - && (ent2->client->saber[1].saberFlags&SFL_NOT_LOCKABLE) ) - { + if (ent2->client->saber[1].model[0] && !ent2->client->ps.saberHolstered && (ent2->client->saber[1].saberFlags & SFL_NOT_LOCKABLE)) { return qfalse; } - if (!InFront( ent1->client->ps.origin, ent2->client->ps.origin, ent2->client->ps.viewangles, 0.4f )) - { + if (!InFront(ent1->client->ps.origin, ent2->client->ps.origin, ent2->client->ps.viewangles, 0.4f)) { return qfalse; } - if (!InFront( ent2->client->ps.origin, ent1->client->ps.origin, ent1->client->ps.viewangles, 0.4f )) - { + if (!InFront(ent2->client->ps.origin, ent1->client->ps.origin, ent1->client->ps.viewangles, 0.4f)) { return qfalse; } - //T to B lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A5_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A6_T__B_ || - ent1->client->ps.torsoAnim == BOTH_A7_T__B_) - {//ent1 is attacking top-down - return WP_SabersCheckLock2( ent1, ent2, LOCK_TOP ); + // T to B lock + if (ent1->client->ps.torsoAnim == BOTH_A1_T__B_ || ent1->client->ps.torsoAnim == BOTH_A2_T__B_ || ent1->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent1->client->ps.torsoAnim == BOTH_A4_T__B_ || ent1->client->ps.torsoAnim == BOTH_A5_T__B_ || ent1->client->ps.torsoAnim == BOTH_A6_T__B_ || + ent1->client->ps.torsoAnim == BOTH_A7_T__B_) { // ent1 is attacking top-down + return WP_SabersCheckLock2(ent1, ent2, LOCK_TOP); } - if ( ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A5_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A6_T__B_ || - ent2->client->ps.torsoAnim == BOTH_A7_T__B_) - {//ent2 is attacking top-down - return WP_SabersCheckLock2( ent2, ent1, LOCK_TOP ); + if (ent2->client->ps.torsoAnim == BOTH_A1_T__B_ || ent2->client->ps.torsoAnim == BOTH_A2_T__B_ || ent2->client->ps.torsoAnim == BOTH_A3_T__B_ || + ent2->client->ps.torsoAnim == BOTH_A4_T__B_ || ent2->client->ps.torsoAnim == BOTH_A5_T__B_ || ent2->client->ps.torsoAnim == BOTH_A6_T__B_ || + ent2->client->ps.torsoAnim == BOTH_A7_T__B_) { // ent2 is attacking top-down + return WP_SabersCheckLock2(ent2, ent1, LOCK_TOP); } - if ( ent1->s.number >= 0 && ent1->s.number < MAX_CLIENTS && - ent1->client->ps.saberBlocking == BLK_WIDE && ent1->client->ps.weaponTime <= 0 ) - { + if (ent1->s.number >= 0 && ent1->s.number < MAX_CLIENTS && ent1->client->ps.saberBlocking == BLK_WIDE && ent1->client->ps.weaponTime <= 0) { ent1BlockingPlayer = qtrue; } - if ( ent2->s.number >= 0 && ent2->s.number < MAX_CLIENTS && - ent2->client->ps.saberBlocking == BLK_WIDE && ent2->client->ps.weaponTime <= 0 ) - { + if (ent2->s.number >= 0 && ent2->s.number < MAX_CLIENTS && ent2->client->ps.saberBlocking == BLK_WIDE && ent2->client->ps.weaponTime <= 0) { ent2BlockingPlayer = qtrue; } - //TR to BL lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A7_TR_BL) - {//ent1 is attacking diagonally - if ( ent2BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TR ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A7_TR_BL || - ent2->client->ps.torsoAnim == BOTH_P1_S1_TL ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TR ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A5_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A6_BR_TL || - ent2->client->ps.torsoAnim == BOTH_A7_BR_TL || - ent2->client->ps.torsoAnim == BOTH_P1_S1_BL ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BL ); + // TR to BL lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A7_TR_BL) { // ent1 is attacking diagonally + if (ent2BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TR); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A7_TR_BL || ent2->client->ps.torsoAnim == BOTH_P1_S1_TL) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TR); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BR_TL || ent2->client->ps.torsoAnim == BOTH_A2_BR_TL || ent2->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent2->client->ps.torsoAnim == BOTH_A4_BR_TL || ent2->client->ps.torsoAnim == BOTH_A5_BR_TL || ent2->client->ps.torsoAnim == BOTH_A6_BR_TL || + ent2->client->ps.torsoAnim == BOTH_A7_BR_TL || ent2->client->ps.torsoAnim == BOTH_P1_S1_BL) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BL); } return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A7_TR_BL) - {//ent2 is attacking diagonally - if ( ent1BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TR ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A7_TR_BL || - ent1->client->ps.torsoAnim == BOTH_P1_S1_TL ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TR ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A5_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A6_BR_TL || - ent1->client->ps.torsoAnim == BOTH_A7_BR_TL || - ent1->client->ps.torsoAnim == BOTH_P1_S1_BL ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BL ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A7_TR_BL) { // ent2 is attacking diagonally + if (ent1BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TR); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A7_TR_BL || ent1->client->ps.torsoAnim == BOTH_P1_S1_TL) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TR); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_BR_TL || ent1->client->ps.torsoAnim == BOTH_A2_BR_TL || ent1->client->ps.torsoAnim == BOTH_A3_BR_TL || + ent1->client->ps.torsoAnim == BOTH_A4_BR_TL || ent1->client->ps.torsoAnim == BOTH_A5_BR_TL || ent1->client->ps.torsoAnim == BOTH_A6_BR_TL || + ent1->client->ps.torsoAnim == BOTH_A7_BR_TL || ent1->client->ps.torsoAnim == BOTH_P1_S1_BL) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BL); } return qfalse; } - //TL to BR lock - if ( ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A7_TL_BR) - {//ent1 is attacking diagonally - if ( ent2BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TL ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A7_TL_BR || - ent2->client->ps.torsoAnim == BOTH_P1_S1_TR ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_TL ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A5_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A6_BL_TR || - ent2->client->ps.torsoAnim == BOTH_A7_BL_TR || - ent2->client->ps.torsoAnim == BOTH_P1_S1_BR ) - {//ent2 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent1, ent2, LOCK_DIAG_BR ); + // TL to BR lock + if (ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A7_TL_BR) { // ent1 is attacking diagonally + if (ent2BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TL); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A7_TL_BR || ent2->client->ps.torsoAnim == BOTH_P1_S1_TR) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_TL); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_BL_TR || ent2->client->ps.torsoAnim == BOTH_A2_BL_TR || ent2->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent2->client->ps.torsoAnim == BOTH_A4_BL_TR || ent2->client->ps.torsoAnim == BOTH_A5_BL_TR || ent2->client->ps.torsoAnim == BOTH_A6_BL_TR || + ent2->client->ps.torsoAnim == BOTH_A7_BL_TR || ent2->client->ps.torsoAnim == BOTH_P1_S1_BR) { // ent2 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent1, ent2, LOCK_DIAG_BR); } return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A7_TL_BR) - {//ent2 is attacking diagonally - if ( ent1BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TL ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A7_TL_BR || - ent1->client->ps.torsoAnim == BOTH_P1_S1_TR ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_TL ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A5_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A6_BL_TR || - ent1->client->ps.torsoAnim == BOTH_A7_BL_TR || - ent1->client->ps.torsoAnim == BOTH_P1_S1_BR ) - {//ent1 is attacking in the opposite diagonal - return WP_SabersCheckLock2( ent2, ent1, LOCK_DIAG_BR ); + if (ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A7_TL_BR) { // ent2 is attacking diagonally + if (ent1BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TL); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A7_TL_BR || ent1->client->ps.torsoAnim == BOTH_P1_S1_TR) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_TL); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_BL_TR || ent1->client->ps.torsoAnim == BOTH_A2_BL_TR || ent1->client->ps.torsoAnim == BOTH_A3_BL_TR || + ent1->client->ps.torsoAnim == BOTH_A4_BL_TR || ent1->client->ps.torsoAnim == BOTH_A5_BL_TR || ent1->client->ps.torsoAnim == BOTH_A6_BL_TR || + ent1->client->ps.torsoAnim == BOTH_A7_BL_TR || ent1->client->ps.torsoAnim == BOTH_P1_S1_BR) { // ent1 is attacking in the opposite diagonal + return WP_SabersCheckLock2(ent2, ent1, LOCK_DIAG_BR); } return qfalse; } - //L to R lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__L__R || - ent1->client->ps.torsoAnim == BOTH_A2__L__R || - ent1->client->ps.torsoAnim == BOTH_A3__L__R || - ent1->client->ps.torsoAnim == BOTH_A4__L__R || - ent1->client->ps.torsoAnim == BOTH_A5__L__R || - ent1->client->ps.torsoAnim == BOTH_A6__L__R || - ent1->client->ps.torsoAnim == BOTH_A7__L__R) - {//ent1 is attacking l to r - if ( ent2BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent1, ent2, LOCK_L ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent2->client->ps.torsoAnim == BOTH_A7_TL_BR || - ent2->client->ps.torsoAnim == BOTH_P1_S1_TR || - ent2->client->ps.torsoAnim == BOTH_P1_S1_BL ) - {//ent2 is attacking or blocking on the r - return WP_SabersCheckLock2( ent1, ent2, LOCK_L ); + // L to R lock + if (ent1->client->ps.torsoAnim == BOTH_A1__L__R || ent1->client->ps.torsoAnim == BOTH_A2__L__R || ent1->client->ps.torsoAnim == BOTH_A3__L__R || + ent1->client->ps.torsoAnim == BOTH_A4__L__R || ent1->client->ps.torsoAnim == BOTH_A5__L__R || ent1->client->ps.torsoAnim == BOTH_A6__L__R || + ent1->client->ps.torsoAnim == BOTH_A7__L__R) { // ent1 is attacking l to r + if (ent2BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent1, ent2, LOCK_L); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_TL_BR || ent2->client->ps.torsoAnim == BOTH_A2_TL_BR || ent2->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A4_TL_BR || ent2->client->ps.torsoAnim == BOTH_A5_TL_BR || ent2->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent2->client->ps.torsoAnim == BOTH_A7_TL_BR || ent2->client->ps.torsoAnim == BOTH_P1_S1_TR || + ent2->client->ps.torsoAnim == BOTH_P1_S1_BL) { // ent2 is attacking or blocking on the r + return WP_SabersCheckLock2(ent1, ent2, LOCK_L); } return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A1__L__R || - ent2->client->ps.torsoAnim == BOTH_A2__L__R || - ent2->client->ps.torsoAnim == BOTH_A3__L__R || - ent2->client->ps.torsoAnim == BOTH_A4__L__R || - ent2->client->ps.torsoAnim == BOTH_A5__L__R || - ent2->client->ps.torsoAnim == BOTH_A6__L__R || - ent2->client->ps.torsoAnim == BOTH_A7__L__R) - {//ent2 is attacking l to r - if ( ent1BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent2, ent1, LOCK_L ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || - ent1->client->ps.torsoAnim == BOTH_A7_TL_BR || - ent1->client->ps.torsoAnim == BOTH_P1_S1_TR || - ent1->client->ps.torsoAnim == BOTH_P1_S1_BL ) - {//ent1 is attacking or blocking on the r - return WP_SabersCheckLock2( ent2, ent1, LOCK_L ); + if (ent2->client->ps.torsoAnim == BOTH_A1__L__R || ent2->client->ps.torsoAnim == BOTH_A2__L__R || ent2->client->ps.torsoAnim == BOTH_A3__L__R || + ent2->client->ps.torsoAnim == BOTH_A4__L__R || ent2->client->ps.torsoAnim == BOTH_A5__L__R || ent2->client->ps.torsoAnim == BOTH_A6__L__R || + ent2->client->ps.torsoAnim == BOTH_A7__L__R) { // ent2 is attacking l to r + if (ent1BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent2, ent1, LOCK_L); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_TL_BR || ent1->client->ps.torsoAnim == BOTH_A2_TL_BR || ent1->client->ps.torsoAnim == BOTH_A3_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A4_TL_BR || ent1->client->ps.torsoAnim == BOTH_A5_TL_BR || ent1->client->ps.torsoAnim == BOTH_A6_TL_BR || + ent1->client->ps.torsoAnim == BOTH_A7_TL_BR || ent1->client->ps.torsoAnim == BOTH_P1_S1_TR || + ent1->client->ps.torsoAnim == BOTH_P1_S1_BL) { // ent1 is attacking or blocking on the r + return WP_SabersCheckLock2(ent2, ent1, LOCK_L); } return qfalse; } - //R to L lock - if ( ent1->client->ps.torsoAnim == BOTH_A1__R__L || - ent1->client->ps.torsoAnim == BOTH_A2__R__L || - ent1->client->ps.torsoAnim == BOTH_A3__R__L || - ent1->client->ps.torsoAnim == BOTH_A4__R__L || - ent1->client->ps.torsoAnim == BOTH_A5__R__L || - ent1->client->ps.torsoAnim == BOTH_A6__R__L || - ent1->client->ps.torsoAnim == BOTH_A7__R__L) - {//ent1 is attacking r to l - if ( ent2BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent1, ent2, LOCK_R ); - } - if ( ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent2->client->ps.torsoAnim == BOTH_A7_TR_BL || - ent2->client->ps.torsoAnim == BOTH_P1_S1_TL || - ent2->client->ps.torsoAnim == BOTH_P1_S1_BR ) - {//ent2 is attacking or blocking on the l - return WP_SabersCheckLock2( ent1, ent2, LOCK_R ); + // R to L lock + if (ent1->client->ps.torsoAnim == BOTH_A1__R__L || ent1->client->ps.torsoAnim == BOTH_A2__R__L || ent1->client->ps.torsoAnim == BOTH_A3__R__L || + ent1->client->ps.torsoAnim == BOTH_A4__R__L || ent1->client->ps.torsoAnim == BOTH_A5__R__L || ent1->client->ps.torsoAnim == BOTH_A6__R__L || + ent1->client->ps.torsoAnim == BOTH_A7__R__L) { // ent1 is attacking r to l + if (ent2BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent1, ent2, LOCK_R); + } + if (ent2->client->ps.torsoAnim == BOTH_A1_TR_BL || ent2->client->ps.torsoAnim == BOTH_A2_TR_BL || ent2->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A4_TR_BL || ent2->client->ps.torsoAnim == BOTH_A5_TR_BL || ent2->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent2->client->ps.torsoAnim == BOTH_A7_TR_BL || ent2->client->ps.torsoAnim == BOTH_P1_S1_TL || + ent2->client->ps.torsoAnim == BOTH_P1_S1_BR) { // ent2 is attacking or blocking on the l + return WP_SabersCheckLock2(ent1, ent2, LOCK_R); } return qfalse; } - if ( ent2->client->ps.torsoAnim == BOTH_A1__R__L || - ent2->client->ps.torsoAnim == BOTH_A2__R__L || - ent2->client->ps.torsoAnim == BOTH_A3__R__L || - ent2->client->ps.torsoAnim == BOTH_A4__R__L || - ent2->client->ps.torsoAnim == BOTH_A5__R__L || - ent2->client->ps.torsoAnim == BOTH_A6__R__L || - ent2->client->ps.torsoAnim == BOTH_A7__R__L) - {//ent2 is attacking r to l - if ( ent1BlockingPlayer ) - {//player will block this anyway - return WP_SabersCheckLock2( ent2, ent1, LOCK_R ); - } - if ( ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || - ent1->client->ps.torsoAnim == BOTH_A7_TR_BL || - ent1->client->ps.torsoAnim == BOTH_P1_S1_TL || - ent1->client->ps.torsoAnim == BOTH_P1_S1_BR ) - {//ent1 is attacking or blocking on the l - return WP_SabersCheckLock2( ent2, ent1, LOCK_R ); + if (ent2->client->ps.torsoAnim == BOTH_A1__R__L || ent2->client->ps.torsoAnim == BOTH_A2__R__L || ent2->client->ps.torsoAnim == BOTH_A3__R__L || + ent2->client->ps.torsoAnim == BOTH_A4__R__L || ent2->client->ps.torsoAnim == BOTH_A5__R__L || ent2->client->ps.torsoAnim == BOTH_A6__R__L || + ent2->client->ps.torsoAnim == BOTH_A7__R__L) { // ent2 is attacking r to l + if (ent1BlockingPlayer) { // player will block this anyway + return WP_SabersCheckLock2(ent2, ent1, LOCK_R); + } + if (ent1->client->ps.torsoAnim == BOTH_A1_TR_BL || ent1->client->ps.torsoAnim == BOTH_A2_TR_BL || ent1->client->ps.torsoAnim == BOTH_A3_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A4_TR_BL || ent1->client->ps.torsoAnim == BOTH_A5_TR_BL || ent1->client->ps.torsoAnim == BOTH_A6_TR_BL || + ent1->client->ps.torsoAnim == BOTH_A7_TR_BL || ent1->client->ps.torsoAnim == BOTH_P1_S1_TL || + ent1->client->ps.torsoAnim == BOTH_P1_S1_BR) { // ent1 is attacking or blocking on the l + return WP_SabersCheckLock2(ent2, ent1, LOCK_R); } return qfalse; } - if ( !Q_irand( 0, 10 ) ) - { - return WP_SabersCheckLock2( ent1, ent2, LOCK_RANDOM ); + if (!Q_irand(0, 10)) { + return WP_SabersCheckLock2(ent1, ent2, LOCK_RANDOM); } return qfalse; } -static QINLINE int G_GetParryForBlock(int block) -{ - switch (block) - { - case BLOCKED_UPPER_RIGHT: - return LS_PARRY_UR; - break; - case BLOCKED_UPPER_RIGHT_PROJ: - return LS_REFLECT_UR; - break; - case BLOCKED_UPPER_LEFT: - return LS_PARRY_UL; - break; - case BLOCKED_UPPER_LEFT_PROJ: - return LS_REFLECT_UL; - break; - case BLOCKED_LOWER_RIGHT: - return LS_PARRY_LR; - break; - case BLOCKED_LOWER_RIGHT_PROJ: - return LS_REFLECT_LR; - break; - case BLOCKED_LOWER_LEFT: - return LS_PARRY_LL; - break; - case BLOCKED_LOWER_LEFT_PROJ: - return LS_REFLECT_LL; - break; - case BLOCKED_TOP: - return LS_PARRY_UP; - break; - case BLOCKED_TOP_PROJ: - return LS_REFLECT_UP; - break; - default: - break; +static QINLINE int G_GetParryForBlock(int block) { + switch (block) { + case BLOCKED_UPPER_RIGHT: + return LS_PARRY_UR; + break; + case BLOCKED_UPPER_RIGHT_PROJ: + return LS_REFLECT_UR; + break; + case BLOCKED_UPPER_LEFT: + return LS_PARRY_UL; + break; + case BLOCKED_UPPER_LEFT_PROJ: + return LS_REFLECT_UL; + break; + case BLOCKED_LOWER_RIGHT: + return LS_PARRY_LR; + break; + case BLOCKED_LOWER_RIGHT_PROJ: + return LS_REFLECT_LR; + break; + case BLOCKED_LOWER_LEFT: + return LS_PARRY_LL; + break; + case BLOCKED_LOWER_LEFT_PROJ: + return LS_REFLECT_LL; + break; + case BLOCKED_TOP: + return LS_PARRY_UP; + break; + case BLOCKED_TOP_PROJ: + return LS_REFLECT_UP; + break; + default: + break; } return LS_NONE; } -int PM_SaberBounceForAttack( int move ); -int PM_SaberDeflectionForQuad( int quad ); +int PM_SaberBounceForAttack(int move); +int PM_SaberDeflectionForQuad(int quad); -extern stringID_table_t animTable[MAX_ANIMATIONS+1]; -static QINLINE qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity_t *defender, float saberHitFraction ) -{ +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; +static QINLINE qboolean WP_GetSaberDeflectionAngle(gentity_t *attacker, gentity_t *defender, float saberHitFraction) { qboolean animBasedDeflection = qtrue; int attSaberLevel, defSaberLevel; - if ( !attacker || !attacker->client || !attacker->ghoul2 ) - { + if (!attacker || !attacker->client || !attacker->ghoul2) { return qfalse; } - if ( !defender || !defender->client || !defender->ghoul2 ) - { + if (!defender || !defender->client || !defender->ghoul2) { return qfalse; } - if ((level.time - attacker->client->lastSaberStorageTime) > 500) - { //last update was too long ago, something is happening to this client to prevent his saber from updating + if ((level.time - attacker->client->lastSaberStorageTime) > + 500) { // last update was too long ago, something is happening to this client to prevent his saber from updating return qfalse; } - if ((level.time - defender->client->lastSaberStorageTime) > 500) - { //ditto + if ((level.time - defender->client->lastSaberStorageTime) > 500) { // ditto return qfalse; } attSaberLevel = G_SaberAttackPower(attacker, SaberAttacking(attacker)); defSaberLevel = G_SaberAttackPower(defender, SaberAttacking(defender)); - if ( animBasedDeflection ) - { - //Hmm, let's try just basing it off the anim + if (animBasedDeflection) { + // Hmm, let's try just basing it off the anim int attQuadStart = saberMoveData[attacker->client->ps.saberMove].startQuad; int attQuadEnd = saberMoveData[attacker->client->ps.saberMove].endQuad; int defQuad = saberMoveData[defender->client->ps.saberMove].endQuad; - int quadDiff = fabs((float)(defQuad-attQuadStart)); - - if ( defender->client->ps.saberMove == LS_READY ) - { - //FIXME: we should probably do SOMETHING here... - //I have this return qfalse here in the hopes that - //the defender will pick a parry and the attacker - //will hit the defender's saber again. - //But maybe this func call should come *after* - //it's decided whether or not the defender is - //going to parry. + int quadDiff = fabs((float)(defQuad - attQuadStart)); + + if (defender->client->ps.saberMove == LS_READY) { + // FIXME: we should probably do SOMETHING here... + // I have this return qfalse here in the hopes that + // the defender will pick a parry and the attacker + // will hit the defender's saber again. + // But maybe this func call should come *after* + // it's decided whether or not the defender is + // going to parry. return qfalse; } - //reverse the left/right of the defQuad because of the mirrored nature of facing each other in combat - switch ( defQuad ) - { + // reverse the left/right of the defQuad because of the mirrored nature of facing each other in combat + switch (defQuad) { case Q_BR: defQuad = Q_BL; break; @@ -1987,111 +1568,87 @@ static QINLINE qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity break; } - if ( quadDiff > 4 ) - {//wrap around so diff is never greater than 180 (4 * 45) + if (quadDiff > 4) { // wrap around so diff is never greater than 180 (4 * 45) quadDiff = 4 - (quadDiff - 4); } - //have the quads, find a good anim to use - if ( (!quadDiff || (quadDiff == 1 && Q_irand(0,1))) //defender pretty much stopped the attack at a 90 degree angle - && (defSaberLevel == attSaberLevel || Q_irand( 0, defSaberLevel-attSaberLevel ) >= 0) )//and the defender's style is stronger + // have the quads, find a good anim to use + if ((!quadDiff || (quadDiff == 1 && Q_irand(0, 1))) // defender pretty much stopped the attack at a 90 degree angle + && (defSaberLevel == attSaberLevel || Q_irand(0, defSaberLevel - attSaberLevel) >= 0)) // and the defender's style is stronger { - //bounce straight back + // bounce straight back #ifndef FINAL_BUILD int attMove = attacker->client->ps.saberMove; #endif - attacker->client->ps.saberMove = PM_SaberBounceForAttack( attacker->client->ps.saberMove ); + attacker->client->ps.saberMove = PM_SaberBounceForAttack(attacker->client->ps.saberMove); #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { - Com_Printf( "attack %s vs. parry %s bounced to %s\n", - animTable[saberMoveData[attMove].animToUse].name, - animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, - animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name ); + if (g_saberDebugPrint.integer) { + Com_Printf("attack %s vs. parry %s bounced to %s\n", animTable[saberMoveData[attMove].animToUse].name, + animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, + animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name); } #endif attacker->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; return qfalse; - } - else - {//attack hit at an angle, figure out what angle it should bounce off att + } else { // attack hit at an angle, figure out what angle it should bounce off att int newQuad; quadDiff = defQuad - attQuadEnd; - //add half the diff of between the defense and attack end to the attack end - if ( quadDiff > 4 ) - { + // add half the diff of between the defense and attack end to the attack end + if (quadDiff > 4) { quadDiff = 4 - (quadDiff - 4); - } - else if ( quadDiff < -4 ) - { + } else if (quadDiff < -4) { quadDiff = -4 + (quadDiff + 4); } - newQuad = attQuadEnd + ceil( ((float)quadDiff)/2.0f ); - if ( newQuad < Q_BR ) - {//less than zero wraps around + newQuad = attQuadEnd + ceil(((float)quadDiff) / 2.0f); + if (newQuad < Q_BR) { // less than zero wraps around newQuad = Q_B + newQuad; } - if ( newQuad == attQuadStart ) - {//never come off at the same angle that we would have if the attack was not interrupted - if ( Q_irand(0, 1) ) - { + if (newQuad == attQuadStart) { // never come off at the same angle that we would have if the attack was not interrupted + if (Q_irand(0, 1)) { newQuad--; - } - else - { + } else { newQuad++; } - if ( newQuad < Q_BR ) - { + if (newQuad < Q_BR) { newQuad = Q_B; - } - else if ( newQuad > Q_B ) - { + } else if (newQuad > Q_B) { newQuad = Q_BR; } } - if ( newQuad == defQuad ) - {//bounce straight back + if (newQuad == defQuad) { // bounce straight back #ifndef FINAL_BUILD int attMove = attacker->client->ps.saberMove; #endif - attacker->client->ps.saberMove = PM_SaberBounceForAttack( attacker->client->ps.saberMove ); + attacker->client->ps.saberMove = PM_SaberBounceForAttack(attacker->client->ps.saberMove); #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { - Com_Printf( "attack %s vs. parry %s bounced to %s\n", - animTable[saberMoveData[attMove].animToUse].name, - animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, - animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name ); + if (g_saberDebugPrint.integer) { + Com_Printf("attack %s vs. parry %s bounced to %s\n", animTable[saberMoveData[attMove].animToUse].name, + animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, + animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name); } #endif attacker->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; return qfalse; } - //else, pick a deflection - else - { + // else, pick a deflection + else { #ifndef FINAL_BUILD int attMove = attacker->client->ps.saberMove; #endif - attacker->client->ps.saberMove = PM_SaberDeflectionForQuad( newQuad ); + attacker->client->ps.saberMove = PM_SaberDeflectionForQuad(newQuad); #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { - Com_Printf( "attack %s vs. parry %s deflected to %s\n", - animTable[saberMoveData[attMove].animToUse].name, - animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, - animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name ); + if (g_saberDebugPrint.integer) { + Com_Printf("attack %s vs. parry %s deflected to %s\n", animTable[saberMoveData[attMove].animToUse].name, + animTable[saberMoveData[defender->client->ps.saberMove].animToUse].name, + animTable[saberMoveData[attacker->client->ps.saberMove].animToUse].name); } #endif attacker->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; return qtrue; } } - } - else - { //old math-based method (probably broken) - vec3_t att_HitDir, def_BladeDir, temp; - float hitDot; + } else { // old math-based method (probably broken) + vec3_t att_HitDir, def_BladeDir, temp; + float hitDot; VectorCopy(attacker->client->lastSaberBase_Always, temp); @@ -2099,86 +1656,58 @@ static QINLINE qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity AngleVectors(defender->client->lastSaberDir_Always, def_BladeDir, 0, 0); - //now compare - hitDot = DotProduct( att_HitDir, def_BladeDir ); - if ( hitDot < 0.25f && hitDot > -0.25f ) - {//hit pretty much perpendicular, pop straight back - attacker->client->ps.saberMove = PM_SaberBounceForAttack( attacker->client->ps.saberMove ); + // now compare + hitDot = DotProduct(att_HitDir, def_BladeDir); + if (hitDot < 0.25f && hitDot > -0.25f) { // hit pretty much perpendicular, pop straight back + attacker->client->ps.saberMove = PM_SaberBounceForAttack(attacker->client->ps.saberMove); attacker->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; return qfalse; - } - else - {//a deflection - vec3_t att_Right, att_Up, att_DeflectionDir; - float swingRDot, swingUDot; - - //get the direction of the deflection - VectorScale( def_BladeDir, hitDot, att_DeflectionDir ); - //get our bounce straight back direction - VectorScale( att_HitDir, -1.0f, temp ); - //add the bounce back and deflection - VectorAdd( att_DeflectionDir, temp, att_DeflectionDir ); - //normalize the result to determine what direction our saber should bounce back toward - VectorNormalize( att_DeflectionDir ); - - //need to know the direction of the deflectoin relative to the attacker's facing - VectorSet( temp, 0, attacker->client->ps.viewangles[YAW], 0 );//presumes no pitch! - AngleVectors( temp, NULL, att_Right, att_Up ); - swingRDot = DotProduct( att_Right, att_DeflectionDir ); - swingUDot = DotProduct( att_Up, att_DeflectionDir ); - - if ( swingRDot > 0.25f ) - {//deflect to right - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // a deflection + vec3_t att_Right, att_Up, att_DeflectionDir; + float swingRDot, swingUDot; + + // get the direction of the deflection + VectorScale(def_BladeDir, hitDot, att_DeflectionDir); + // get our bounce straight back direction + VectorScale(att_HitDir, -1.0f, temp); + // add the bounce back and deflection + VectorAdd(att_DeflectionDir, temp, att_DeflectionDir); + // normalize the result to determine what direction our saber should bounce back toward + VectorNormalize(att_DeflectionDir); + + // need to know the direction of the deflectoin relative to the attacker's facing + VectorSet(temp, 0, attacker->client->ps.viewangles[YAW], 0); // presumes no pitch! + AngleVectors(temp, NULL, att_Right, att_Up); + swingRDot = DotProduct(att_Right, att_DeflectionDir); + swingUDot = DotProduct(att_Up, att_DeflectionDir); + + if (swingRDot > 0.25f) { // deflect to right + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberMove = LS_D1_TR; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberMove = LS_D1_BR; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberMove = LS_D1__R; } - } - else if ( swingRDot < -0.25f ) - {//deflect to left - if ( swingUDot > 0.25f ) - {//deflect to top + } else if (swingRDot < -0.25f) { // deflect to left + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberMove = LS_D1_TL; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberMove = LS_D1_BL; - } - else - {//deflect horizontally + } else { // deflect horizontally attacker->client->ps.saberMove = LS_D1__L; } - } - else - {//deflect in middle - if ( swingUDot > 0.25f ) - {//deflect to top + } else { // deflect in middle + if (swingUDot > 0.25f) { // deflect to top attacker->client->ps.saberMove = LS_D1_T_; - } - else if ( swingUDot < -0.25f ) - {//deflect to bottom + } else if (swingUDot < -0.25f) { // deflect to bottom attacker->client->ps.saberMove = LS_D1_B_; - } - else - {//deflect horizontally? Well, no such thing as straight back in my face, so use top - if ( swingRDot > 0 ) - { + } else { // deflect horizontally? Well, no such thing as straight back in my face, so use top + if (swingRDot > 0) { attacker->client->ps.saberMove = LS_D1_TR; - } - else if ( swingRDot < 0 ) - { + } else if (swingRDot < 0) { attacker->client->ps.saberMove = LS_D1_TL; - } - else - { + } else { attacker->client->ps.saberMove = LS_D1_T_; } } @@ -2190,128 +1719,119 @@ static QINLINE qboolean WP_GetSaberDeflectionAngle( gentity_t *attacker, gentity } } -int G_KnockawayForParry( int move ) -{ - //FIXME: need actual anims for this - //FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center - switch ( move ) - { +int G_KnockawayForParry(int move) { + // FIXME: need actual anims for this + // FIXME: need to know which side of the saber was hit! For now, we presume the saber gets knocked away from the center + switch (move) { case LS_PARRY_UP: - return LS_K1_T_;//push up + return LS_K1_T_; // push up break; case LS_PARRY_UR: - default://case LS_READY: - return LS_K1_TR;//push up, slightly to right + default: // case LS_READY: + return LS_K1_TR; // push up, slightly to right break; case LS_PARRY_UL: - return LS_K1_TL;//push up and to left + return LS_K1_TL; // push up and to left break; case LS_PARRY_LR: - return LS_K1_BR;//push down and to left + return LS_K1_BR; // push down and to left break; case LS_PARRY_LL: - return LS_K1_BL;//push down and to right + return LS_K1_BL; // push down and to right break; } } #define SABER_NONATTACK_DAMAGE 1 -//For strong attacks, we ramp damage based on the point in the attack animation -static QINLINE int G_GetAttackDamage(gentity_t *self, int minDmg, int maxDmg, float multPoint) -{ +// For strong attacks, we ramp damage based on the point in the attack animation +static QINLINE int G_GetAttackDamage(gentity_t *self, int minDmg, int maxDmg, float multPoint) { int speedDif = 0; int totalDamage = maxDmg; float peakPoint = 0; - float attackAnimLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].numFrames * fabs((float)(bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].frameLerp)); + float attackAnimLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].numFrames * + fabs((float)(bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].frameLerp)); float currentPoint = 0; float damageFactor = 0; float animSpeedFactor = 1.0f; - //Be sure to scale by the proper anim speed just as if we were going to play the animation - BG_SaberStartTransAnim(self->s.number, self->client->ps.fd.saberAnimLevel, self->client->ps.weapon, self->client->ps.torsoAnim, &animSpeedFactor, self->client->ps.brokenLimbs); + // Be sure to scale by the proper anim speed just as if we were going to play the animation + BG_SaberStartTransAnim(self->s.number, self->client->ps.fd.saberAnimLevel, self->client->ps.weapon, self->client->ps.torsoAnim, &animSpeedFactor, + self->client->ps.brokenLimbs); speedDif = attackAnimLength - (attackAnimLength * animSpeedFactor); attackAnimLength += speedDif; peakPoint = attackAnimLength; - peakPoint -= attackAnimLength*multPoint; + peakPoint -= attackAnimLength * multPoint; - //we treat torsoTimer as the point in the animation (closer it is to attackAnimLength, closer it is to beginning) + // we treat torsoTimer as the point in the animation (closer it is to attackAnimLength, closer it is to beginning) currentPoint = self->client->ps.torsoTimer; - damageFactor = (float)((currentPoint/peakPoint)); - if (damageFactor > 1) - { + damageFactor = (float)((currentPoint / peakPoint)); + if (damageFactor > 1) { damageFactor = (2.0f - damageFactor); } totalDamage *= damageFactor; - if (totalDamage < minDmg) - { + if (totalDamage < minDmg) { totalDamage = minDmg; } - if (totalDamage > maxDmg) - { + if (totalDamage > maxDmg) { totalDamage = maxDmg; } - //Com_Printf("%i\n", totalDamage); + // Com_Printf("%i\n", totalDamage); return totalDamage; } -//Get the point in the animation and return a percentage of the current point in the anim between 0 and the total anim length (0.0f - 1.0f) -static QINLINE float G_GetAnimPoint(gentity_t *self) -{ +// Get the point in the animation and return a percentage of the current point in the anim between 0 and the total anim length (0.0f - 1.0f) +static QINLINE float G_GetAnimPoint(gentity_t *self) { int speedDif = 0; - float attackAnimLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].numFrames * fabs((float)(bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].frameLerp)); + float attackAnimLength = bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].numFrames * + fabs((float)(bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].frameLerp)); float currentPoint = 0; float animSpeedFactor = 1.0f; float animPercentage = 0; - //Be sure to scale by the proper anim speed just as if we were going to play the animation - BG_SaberStartTransAnim(self->s.number, self->client->ps.fd.saberAnimLevel, self->client->ps.weapon, self->client->ps.torsoAnim, &animSpeedFactor, self->client->ps.brokenLimbs); + // Be sure to scale by the proper anim speed just as if we were going to play the animation + BG_SaberStartTransAnim(self->s.number, self->client->ps.fd.saberAnimLevel, self->client->ps.weapon, self->client->ps.torsoAnim, &animSpeedFactor, + self->client->ps.brokenLimbs); speedDif = attackAnimLength - (attackAnimLength * animSpeedFactor); attackAnimLength += speedDif; currentPoint = self->client->ps.torsoTimer; - animPercentage = currentPoint/attackAnimLength; + animPercentage = currentPoint / attackAnimLength; - //Com_Printf("%f\n", animPercentage); + // Com_Printf("%f\n", animPercentage); return animPercentage; } -static QINLINE qboolean G_ClientIdleInWorld(gentity_t *ent) -{ - if (ent->s.eType == ET_NPC) - { +static QINLINE qboolean G_ClientIdleInWorld(gentity_t *ent) { + if (ent->s.eType == ET_NPC) { return qfalse; } if (!ent->client->pers.cmd.upmove && !ent->client->pers.cmd.forwardmove && !ent->client->pers.cmd.rightmove && - !(ent->client->pers.cmd.buttons & BUTTON_GESTURE) && - !(ent->client->pers.cmd.buttons & BUTTON_FORCEGRIP) && - !(ent->client->pers.cmd.buttons & BUTTON_ALT_ATTACK) && - !(ent->client->pers.cmd.buttons & BUTTON_FORCEPOWER) && - !(ent->client->pers.cmd.buttons & BUTTON_FORCE_LIGHTNING) && - !(ent->client->pers.cmd.buttons & BUTTON_FORCE_DRAIN) && + !(ent->client->pers.cmd.buttons & BUTTON_GESTURE) && !(ent->client->pers.cmd.buttons & BUTTON_FORCEGRIP) && + !(ent->client->pers.cmd.buttons & BUTTON_ALT_ATTACK) && !(ent->client->pers.cmd.buttons & BUTTON_FORCEPOWER) && + !(ent->client->pers.cmd.buttons & BUTTON_FORCE_LIGHTNING) && !(ent->client->pers.cmd.buttons & BUTTON_FORCE_DRAIN) && !(ent->client->pers.cmd.buttons & BUTTON_ATTACK)) return qtrue; return qfalse; } -static QINLINE qboolean G_G2TraceCollide(trace_t *tr, vec3_t lastValidStart, vec3_t lastValidEnd, vec3_t traceMins, vec3_t traceMaxs) -{ //Hit the ent with the normal trace, try the collision trace. - G2Trace_t G2Trace; - gentity_t *g2Hit; - vec3_t angles; - int tN = 0; - float fRadius = 0; +static QINLINE qboolean G_G2TraceCollide(trace_t *tr, vec3_t lastValidStart, vec3_t lastValidEnd, vec3_t traceMins, + vec3_t traceMaxs) { // Hit the ent with the normal trace, try the collision trace. + G2Trace_t G2Trace; + gentity_t *g2Hit; + vec3_t angles; + int tN = 0; + float fRadius = 0; - if (!d_saberGhoul2Collision.integer) - { + if (!d_saberGhoul2Collision.integer) { return qfalse; } @@ -2321,69 +1841,50 @@ static QINLINE qboolean G_G2TraceCollide(trace_t *tr, vec3_t lastValidStart, vec return qfalse; } - if (traceMins[0] || - traceMins[1] || - traceMins[2] || - traceMaxs[0] || - traceMaxs[1] || - traceMaxs[2]) - { - fRadius=(traceMaxs[0]-traceMins[0])/2.0f; + if (traceMins[0] || traceMins[1] || traceMins[2] || traceMaxs[0] || traceMaxs[1] || traceMaxs[2]) { + fRadius = (traceMaxs[0] - traceMins[0]) / 2.0f; } - memset (&G2Trace, 0, sizeof(G2Trace)); + memset(&G2Trace, 0, sizeof(G2Trace)); - while (tN < MAX_G2_COLLISIONS) - { + while (tN < MAX_G2_COLLISIONS) { G2Trace[tN].mEntityNum = -1; tN++; } g2Hit = &g_entities[tr->entityNum]; - if (g2Hit && g2Hit->inuse && g2Hit->ghoul2) - { + if (g2Hit && g2Hit->inuse && g2Hit->ghoul2) { vec3_t g2HitOrigin; angles[ROLL] = angles[PITCH] = 0; - if (g2Hit->client) - { + if (g2Hit->client) { VectorCopy(g2Hit->client->ps.origin, g2HitOrigin); angles[YAW] = g2Hit->client->ps.viewangles[YAW]; - } - else - { + } else { VectorCopy(g2Hit->r.currentOrigin, g2HitOrigin); angles[YAW] = g2Hit->r.currentAngles[YAW]; } - if (com_optvehtrace.integer && - g2Hit->s.eType == ET_NPC && - g2Hit->s.NPC_class == CLASS_VEHICLE && - g2Hit->m_pVehicle) - { - trap->G2API_CollisionDetectCache ( G2Trace, g2Hit->ghoul2, angles, g2HitOrigin, level.time, g2Hit->s.number, lastValidStart, lastValidEnd, g2Hit->modelScale, 0, g_g2TraceLod.integer, fRadius ); - } - else - { - trap->G2API_CollisionDetect ( G2Trace, g2Hit->ghoul2, angles, g2HitOrigin, level.time, g2Hit->s.number, lastValidStart, lastValidEnd, g2Hit->modelScale, 0, g_g2TraceLod.integer, fRadius ); + if (com_optvehtrace.integer && g2Hit->s.eType == ET_NPC && g2Hit->s.NPC_class == CLASS_VEHICLE && g2Hit->m_pVehicle) { + trap->G2API_CollisionDetectCache(G2Trace, g2Hit->ghoul2, angles, g2HitOrigin, level.time, g2Hit->s.number, lastValidStart, lastValidEnd, + g2Hit->modelScale, 0, g_g2TraceLod.integer, fRadius); + } else { + trap->G2API_CollisionDetect(G2Trace, g2Hit->ghoul2, angles, g2HitOrigin, level.time, g2Hit->s.number, lastValidStart, lastValidEnd, + g2Hit->modelScale, 0, g_g2TraceLod.integer, fRadius); } - if (G2Trace[0].mEntityNum != g2Hit->s.number) - { + if (G2Trace[0].mEntityNum != g2Hit->s.number) { tr->fraction = 1.0f; tr->entityNum = ENTITYNUM_NONE; tr->startsolid = 0; tr->allsolid = 0; return qfalse; - } - else - { //The ghoul2 trace result matches, so copy the collision position into the trace endpos and send it back. + } else { // The ghoul2 trace result matches, so copy the collision position into the trace endpos and send it back. VectorCopy(G2Trace[0].mCollisionPosition, tr->endpos); VectorCopy(G2Trace[0].mCollisionNormal, tr->plane.normal); - if (g2Hit->client) - { + if (g2Hit->client) { g2Hit->client->g2LastSurfaceHit = G2Trace[0].mSurfaceIndex; g2Hit->client->g2LastSurfaceTime = level.time; } @@ -2394,10 +1895,8 @@ static QINLINE qboolean G_G2TraceCollide(trace_t *tr, vec3_t lastValidStart, vec return qfalse; } -static QINLINE qboolean G_SaberInBackAttack(int move) -{ - switch (move) - { +static QINLINE qboolean G_SaberInBackAttack(int move) { + switch (move) { case LS_A_BACK: case LS_A_BACK_CR: case LS_A_BACKSTAB: @@ -2411,18 +1910,14 @@ qboolean saberCheckKnockdown_Thrown(gentity_t *saberent, gentity_t *saberOwner, qboolean saberCheckKnockdown_Smashed(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other, int damage); qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other); - -typedef struct saberFace_s -{ +typedef struct saberFace_s { vec3_t v1; vec3_t v2; vec3_t v3; } saberFace_t; -//build faces around blade for collision checking -rww -static QINLINE void G_BuildSaberFaces(vec3_t base, vec3_t tip, float radius, vec3_t fwd, - vec3_t right, int *fNum, saberFace_t **fList) -{ +// build faces around blade for collision checking -rww +static QINLINE void G_BuildSaberFaces(vec3_t base, vec3_t tip, float radius, vec3_t fwd, vec3_t right, int *fNum, saberFace_t **fList) { static saberFace_t faces[12]; int i = 0; float *d1 = NULL, *d2 = NULL; @@ -2434,222 +1929,196 @@ static QINLINE void G_BuildSaberFaces(vec3_t base, vec3_t tip, float radius, vec VectorCopy(right, invRight); VectorInverse(invRight); - while (i < 8) - { - //yeah, this part is kind of a hack, but eh - if (i < 2) - { //"left" surface + while (i < 8) { + // yeah, this part is kind of a hack, but eh + if (i < 2) { //"left" surface d1 = &fwd[0]; d2 = &invRight[0]; - } - else if (i < 4) - { //"right" surface + } else if (i < 4) { //"right" surface d1 = &fwd[0]; d2 = &right[0]; - } - else if (i < 6) - { //"front" surface + } else if (i < 6) { //"front" surface d1 = &right[0]; d2 = &fwd[0]; - } - else if (i < 8) - { //"back" surface + } else if (i < 8) { //"back" surface d1 = &right[0]; d2 = &invFwd[0]; } - //first triangle for this surface - VectorMA(base, radius/2.0f, d1, faces[i].v1); - VectorMA(faces[i].v1, radius/2.0f, d2, faces[i].v1); + // first triangle for this surface + VectorMA(base, radius / 2.0f, d1, faces[i].v1); + VectorMA(faces[i].v1, radius / 2.0f, d2, faces[i].v1); - VectorMA(tip, radius/2.0f, d1, faces[i].v2); - VectorMA(faces[i].v2, radius/2.0f, d2, faces[i].v2); + VectorMA(tip, radius / 2.0f, d1, faces[i].v2); + VectorMA(faces[i].v2, radius / 2.0f, d2, faces[i].v2); - VectorMA(tip, -radius/2.0f, d1, faces[i].v3); - VectorMA(faces[i].v3, radius/2.0f, d2, faces[i].v3); + VectorMA(tip, -radius / 2.0f, d1, faces[i].v3); + VectorMA(faces[i].v3, radius / 2.0f, d2, faces[i].v3); i++; - //second triangle for this surface - VectorMA(tip, -radius/2.0f, d1, faces[i].v1); - VectorMA(faces[i].v1, radius/2.0f, d2, faces[i].v1); + // second triangle for this surface + VectorMA(tip, -radius / 2.0f, d1, faces[i].v1); + VectorMA(faces[i].v1, radius / 2.0f, d2, faces[i].v1); - VectorMA(base, radius/2.0f, d1, faces[i].v2); - VectorMA(faces[i].v2, radius/2.0f, d2, faces[i].v2); + VectorMA(base, radius / 2.0f, d1, faces[i].v2); + VectorMA(faces[i].v2, radius / 2.0f, d2, faces[i].v2); - VectorMA(base, -radius/2.0f, d1, faces[i].v3); - VectorMA(faces[i].v3, radius/2.0f, d2, faces[i].v3); + VectorMA(base, -radius / 2.0f, d1, faces[i].v3); + VectorMA(faces[i].v3, radius / 2.0f, d2, faces[i].v3); i++; } - //top surface - //face 1 - VectorMA(tip, radius/2.0f, fwd, faces[i].v1); - VectorMA(faces[i].v1, -radius/2.0f, right, faces[i].v1); + // top surface + // face 1 + VectorMA(tip, radius / 2.0f, fwd, faces[i].v1); + VectorMA(faces[i].v1, -radius / 2.0f, right, faces[i].v1); - VectorMA(tip, radius/2.0f, fwd, faces[i].v2); - VectorMA(faces[i].v2, radius/2.0f, right, faces[i].v2); + VectorMA(tip, radius / 2.0f, fwd, faces[i].v2); + VectorMA(faces[i].v2, radius / 2.0f, right, faces[i].v2); - VectorMA(tip, -radius/2.0f, fwd, faces[i].v3); - VectorMA(faces[i].v3, -radius/2.0f, right, faces[i].v3); + VectorMA(tip, -radius / 2.0f, fwd, faces[i].v3); + VectorMA(faces[i].v3, -radius / 2.0f, right, faces[i].v3); i++; - //face 2 - VectorMA(tip, radius/2.0f, fwd, faces[i].v1); - VectorMA(faces[i].v1, radius/2.0f, right, faces[i].v1); + // face 2 + VectorMA(tip, radius / 2.0f, fwd, faces[i].v1); + VectorMA(faces[i].v1, radius / 2.0f, right, faces[i].v1); - VectorMA(tip, -radius/2.0f, fwd, faces[i].v2); - VectorMA(faces[i].v2, -radius/2.0f, right, faces[i].v2); + VectorMA(tip, -radius / 2.0f, fwd, faces[i].v2); + VectorMA(faces[i].v2, -radius / 2.0f, right, faces[i].v2); - VectorMA(tip, -radius/2.0f, fwd, faces[i].v3); - VectorMA(faces[i].v3, radius/2.0f, right, faces[i].v3); + VectorMA(tip, -radius / 2.0f, fwd, faces[i].v3); + VectorMA(faces[i].v3, radius / 2.0f, right, faces[i].v3); i++; - //bottom surface - //face 1 - VectorMA(base, radius/2.0f, fwd, faces[i].v1); - VectorMA(faces[i].v1, -radius/2.0f, right, faces[i].v1); + // bottom surface + // face 1 + VectorMA(base, radius / 2.0f, fwd, faces[i].v1); + VectorMA(faces[i].v1, -radius / 2.0f, right, faces[i].v1); - VectorMA(base, radius/2.0f, fwd, faces[i].v2); - VectorMA(faces[i].v2, radius/2.0f, right, faces[i].v2); + VectorMA(base, radius / 2.0f, fwd, faces[i].v2); + VectorMA(faces[i].v2, radius / 2.0f, right, faces[i].v2); - VectorMA(base, -radius/2.0f, fwd, faces[i].v3); - VectorMA(faces[i].v3, -radius/2.0f, right, faces[i].v3); + VectorMA(base, -radius / 2.0f, fwd, faces[i].v3); + VectorMA(faces[i].v3, -radius / 2.0f, right, faces[i].v3); i++; - //face 2 - VectorMA(base, radius/2.0f, fwd, faces[i].v1); - VectorMA(faces[i].v1, radius/2.0f, right, faces[i].v1); + // face 2 + VectorMA(base, radius / 2.0f, fwd, faces[i].v1); + VectorMA(faces[i].v1, radius / 2.0f, right, faces[i].v1); - VectorMA(base, -radius/2.0f, fwd, faces[i].v2); - VectorMA(faces[i].v2, -radius/2.0f, right, faces[i].v2); + VectorMA(base, -radius / 2.0f, fwd, faces[i].v2); + VectorMA(faces[i].v2, -radius / 2.0f, right, faces[i].v2); - VectorMA(base, -radius/2.0f, fwd, faces[i].v3); - VectorMA(faces[i].v3, radius/2.0f, right, faces[i].v3); + VectorMA(base, -radius / 2.0f, fwd, faces[i].v3); + VectorMA(faces[i].v3, radius / 2.0f, right, faces[i].v3); i++; - //yeah.. always going to be 12 I suppose. + // yeah.. always going to be 12 I suppose. *fNum = i; *fList = &faces[0]; } -//collision utility function -rww -static QINLINE void G_SabCol_CalcPlaneEq(vec3_t x, vec3_t y, vec3_t z, float *planeEq) -{ - planeEq[0] = x[1]*(y[2]-z[2]) + y[1]*(z[2]-x[2]) + z[1]*(x[2]-y[2]); - planeEq[1] = x[2]*(y[0]-z[0]) + y[2]*(z[0]-x[0]) + z[2]*(x[0]-y[0]); - planeEq[2] = x[0]*(y[1]-z[1]) + y[0]*(z[1]-x[1]) + z[0]*(x[1]-y[1]); - planeEq[3] = -(x[0]*(y[1]*z[2] - z[1]*y[2]) + y[0]*(z[1]*x[2] - x[1]*z[2]) + z[0]*(x[1]*y[2] - y[1]*x[2]) ); +// collision utility function -rww +static QINLINE void G_SabCol_CalcPlaneEq(vec3_t x, vec3_t y, vec3_t z, float *planeEq) { + planeEq[0] = x[1] * (y[2] - z[2]) + y[1] * (z[2] - x[2]) + z[1] * (x[2] - y[2]); + planeEq[1] = x[2] * (y[0] - z[0]) + y[2] * (z[0] - x[0]) + z[2] * (x[0] - y[0]); + planeEq[2] = x[0] * (y[1] - z[1]) + y[0] * (z[1] - x[1]) + z[0] * (x[1] - y[1]); + planeEq[3] = -(x[0] * (y[1] * z[2] - z[1] * y[2]) + y[0] * (z[1] * x[2] - x[1] * z[2]) + z[0] * (x[1] * y[2] - y[1] * x[2])); } -//collision utility function -rww -static QINLINE int G_SabCol_PointRelativeToPlane(vec3_t pos, float *side, float *planeEq) -{ - *side = planeEq[0]*pos[0] + planeEq[1]*pos[1] + planeEq[2]*pos[2] + planeEq[3]; +// collision utility function -rww +static QINLINE int G_SabCol_PointRelativeToPlane(vec3_t pos, float *side, float *planeEq) { + *side = planeEq[0] * pos[0] + planeEq[1] * pos[1] + planeEq[2] * pos[2] + planeEq[3]; - if (*side > 0.0f) - { + if (*side > 0.0f) { return 1; - } - else if (*side < 0.0f) - { + } else if (*side < 0.0f) { return -1; } return 0; } -//do actual collision check using generated saber "faces" -static QINLINE qboolean G_SaberFaceCollisionCheck(int fNum, saberFace_t *fList, vec3_t atkStart, - vec3_t atkEnd, vec3_t atkMins, vec3_t atkMaxs, vec3_t impactPoint) -{ +// do actual collision check using generated saber "faces" +static QINLINE qboolean G_SaberFaceCollisionCheck(int fNum, saberFace_t *fList, vec3_t atkStart, vec3_t atkEnd, vec3_t atkMins, vec3_t atkMaxs, + vec3_t impactPoint) { static float planeEq[4]; static float side, side2, dist; static vec3_t dir; static vec3_t point; int i = 0; - if (VectorCompare(atkMins, vec3_origin) && VectorCompare(atkMaxs, vec3_origin)) - { + if (VectorCompare(atkMins, vec3_origin) && VectorCompare(atkMaxs, vec3_origin)) { VectorSet(atkMins, -1.0f, -1.0f, -1.0f); VectorSet(atkMaxs, 1.0f, 1.0f, 1.0f); } VectorSubtract(atkEnd, atkStart, dir); - while (i < fNum) - { + while (i < fNum) { G_SabCol_CalcPlaneEq(fList->v1, fList->v2, fList->v3, planeEq); if (G_SabCol_PointRelativeToPlane(atkStart, &side, planeEq) != - G_SabCol_PointRelativeToPlane(atkEnd, &side2, planeEq)) - { //start/end points intersect with the plane + G_SabCol_PointRelativeToPlane(atkEnd, &side2, planeEq)) { // start/end points intersect with the plane static vec3_t extruded; static vec3_t minPoint, maxPoint; static vec3_t planeNormal; static int facing; VectorCopy(&planeEq[0], planeNormal); - side2 = planeNormal[0]*dir[0] + planeNormal[1]*dir[1] + planeNormal[2]*dir[2]; + side2 = planeNormal[0] * dir[0] + planeNormal[1] * dir[1] + planeNormal[2] * dir[2]; - dist = side/side2; + dist = side / side2; VectorMA(atkStart, -dist, dir, point); VectorAdd(point, atkMins, minPoint); VectorAdd(point, atkMaxs, maxPoint); - //point is now the point at which we intersect on the plane. - //see if that point is within the edges of the face. - VectorMA(fList->v1, -2.0f, planeNormal, extruded); + // point is now the point at which we intersect on the plane. + // see if that point is within the edges of the face. + VectorMA(fList->v1, -2.0f, planeNormal, extruded); G_SabCol_CalcPlaneEq(fList->v1, fList->v2, extruded, planeEq); facing = G_SabCol_PointRelativeToPlane(point, &side, planeEq); - if (facing < 0) - { //not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane + if (facing < 0) { // not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane facing = G_SabCol_PointRelativeToPlane(minPoint, &side, planeEq); - if (facing < 0) - { + if (facing < 0) { facing = G_SabCol_PointRelativeToPlane(maxPoint, &side, planeEq); } } - if (facing >= 0) - { //first edge is facing... + if (facing >= 0) { // first edge is facing... VectorMA(fList->v2, -2.0f, planeNormal, extruded); G_SabCol_CalcPlaneEq(fList->v2, fList->v3, extruded, planeEq); facing = G_SabCol_PointRelativeToPlane(point, &side, planeEq); - if (facing < 0) - { //not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane + if (facing < 0) { // not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane facing = G_SabCol_PointRelativeToPlane(minPoint, &side, planeEq); - if (facing < 0) - { + if (facing < 0) { facing = G_SabCol_PointRelativeToPlane(maxPoint, &side, planeEq); } } - if (facing >= 0) - { //second edge is facing... + if (facing >= 0) { // second edge is facing... VectorMA(fList->v3, -2.0f, planeNormal, extruded); G_SabCol_CalcPlaneEq(fList->v3, fList->v1, extruded, planeEq); facing = G_SabCol_PointRelativeToPlane(point, &side, planeEq); - if (facing < 0) - { //not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane + if (facing < 0) { // not intersecting.. let's try with the mins/maxs and see if they interesect on the edge plane facing = G_SabCol_PointRelativeToPlane(minPoint, &side, planeEq); - if (facing < 0) - { + if (facing < 0) { facing = G_SabCol_PointRelativeToPlane(maxPoint, &side, planeEq); } } - if (facing >= 0) - { //third edge is facing.. success + if (facing >= 0) { // third edge is facing.. success VectorCopy(point, impactPoint); return qtrue; } @@ -2661,57 +2130,48 @@ static QINLINE qboolean G_SaberFaceCollisionCheck(int fNum, saberFace_t *fList, fList++; } - //did not hit anything + // did not hit anything return qfalse; } -//check for collision of 2 blades -rww -static QINLINE qboolean G_SaberCollide(gentity_t *atk, gentity_t *def, vec3_t atkStart, - vec3_t atkEnd, vec3_t atkMins, vec3_t atkMaxs, vec3_t impactPoint) -{ +// check for collision of 2 blades -rww +static QINLINE qboolean G_SaberCollide(gentity_t *atk, gentity_t *def, vec3_t atkStart, vec3_t atkEnd, vec3_t atkMins, vec3_t atkMaxs, vec3_t impactPoint) { static int i, j; - if (!g_saberBladeFaces.integer) - { //detailed check not enabled + if (!g_saberBladeFaces.integer) { // detailed check not enabled return qtrue; } - if (!atk->inuse || !atk->client || !def->inuse || !def->client) - { //must have 2 clients and a valid saber entity + if (!atk->inuse || !atk->client || !def->inuse || !def->client) { // must have 2 clients and a valid saber entity return qfalse; } i = 0; - while (i < MAX_SABERS) - { + while (i < MAX_SABERS) { j = 0; - if (def->client->saber[i].model[0]) - { //valid saber on the defender + if (def->client->saber[i].model[0]) { // valid saber on the defender bladeInfo_t *blade; vec3_t v, fwd, right, base, tip; int fNum; saberFace_t *fList; - //go through each blade on the defender's sabers - while (j < def->client->saber[i].numBlades) - { + // go through each blade on the defender's sabers + while (j < def->client->saber[i].numBlades) { blade = &def->client->saber[i].blade[j]; - if ((level.time-blade->storageTime) < 200) - { //recently updated - //first get base and tip of blade + if ((level.time - blade->storageTime) < 200) { // recently updated + // first get base and tip of blade VectorCopy(blade->muzzlePoint, base); VectorMA(base, blade->lengthMax, blade->muzzleDir, tip); - //Now get relative angles between the points + // Now get relative angles between the points VectorSubtract(tip, base, v); vectoangles(v, v); AngleVectors(v, NULL, right, fwd); - //now build collision faces for this blade - G_BuildSaberFaces(base, tip, blade->radius*3.0f, fwd, right, &fNum, &fList); - if (fNum > 0) - { + // now build collision faces for this blade + G_BuildSaberFaces(base, tip, blade->radius * 3.0f, fwd, right, &fNum, &fList); + if (fNum > 0) { #if 0 if (atk->s.number == 0) { @@ -2730,8 +2190,7 @@ static QINLINE qboolean G_SaberCollide(gentity_t *atk, gentity_t *def, vec3_t at } #endif - if (G_SaberFaceCollisionCheck(fNum, fList, atkStart, atkEnd, atkMins, atkMaxs, impactPoint)) - { //collided + if (G_SaberFaceCollisionCheck(fNum, fList, atkStart, atkEnd, atkMins, atkMaxs, impactPoint)) { // collided return qtrue; } } @@ -2745,66 +2204,55 @@ static QINLINE qboolean G_SaberCollide(gentity_t *atk, gentity_t *def, vec3_t at return qfalse; } -float WP_SaberBladeLength( saberInfo_t *saber ) -{//return largest length - int i; +float WP_SaberBladeLength(saberInfo_t *saber) { // return largest length + int i; float len = 0.0f; - for ( i = 0; i < saber->numBlades; i++ ) - { - if ( saber->blade[i].lengthMax > len ) - { + for (i = 0; i < saber->numBlades; i++) { + if (saber->blade[i].lengthMax > len) { len = saber->blade[i].lengthMax; } } return len; } -float WP_SaberLength( gentity_t *ent ) -{//return largest length - if ( !ent || !ent->client ) - { +float WP_SaberLength(gentity_t *ent) { // return largest length + if (!ent || !ent->client) { return 0.0f; - } - else - { + } else { int i; float len, bestLen = 0.0f; - for ( i = 0; i < MAX_SABERS; i++ ) - { - len = WP_SaberBladeLength( &ent->client->saber[i] ); - if ( len > bestLen ) - { + for (i = 0; i < MAX_SABERS; i++) { + len = WP_SaberBladeLength(&ent->client->saber[i]); + if (len > bestLen) { bestLen = len; } } return bestLen; } } -int WPDEBUG_SaberColor( saber_colors_t saberColor ) -{ - switch( (int)(saberColor) ) - { - case SABER_RED: - return 0x000000ff; - break; - case SABER_ORANGE: - return 0x000088ff; - break; - case SABER_YELLOW: - return 0x0000ffff; - break; - case SABER_GREEN: - return 0x0000ff00; - break; - case SABER_BLUE: - return 0x00ff0000; - break; - case SABER_PURPLE: - return 0x00ff00ff; - break; - default: - return 0x00ffffff;//white - break; +int WPDEBUG_SaberColor(saber_colors_t saberColor) { + switch ((int)(saberColor)) { + case SABER_RED: + return 0x000000ff; + break; + case SABER_ORANGE: + return 0x000088ff; + break; + case SABER_YELLOW: + return 0x0000ffff; + break; + case SABER_GREEN: + return 0x0000ff00; + break; + case SABER_BLUE: + return 0x00ff0000; + break; + case SABER_PURPLE: + return 0x00ff00ff; + break; + default: + return 0x00ffffff; // white + break; } } /* @@ -2813,114 +2261,113 @@ WP_SabersIntersect Breaks the two saber paths into 2 tris each and tests each tri for the first saber path against each of the other saber path's tris FIXME: subdivide the arc into a consistant increment -FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different times)? +FIXME: test the intersection to see if the sabers really did intersect (weren't going in the same direction and/or passed through same point at different +times)? */ -extern qboolean tri_tri_intersect(vec3_t V0,vec3_t V1,vec3_t V2,vec3_t U0,vec3_t U1,vec3_t U2); +extern qboolean tri_tri_intersect(vec3_t V0, vec3_t V1, vec3_t V2, vec3_t U0, vec3_t U1, vec3_t U2); #define SABER_EXTRAPOLATE_DIST 16.0f -qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum, gentity_t *ent2, qboolean checkDir ) -{ - vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; - vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; - int ent2SaberNum = 0, ent2BladeNum = 0; - vec3_t dir; - - if ( !ent1 || !ent2 ) - { +qboolean WP_SabersIntersect(gentity_t *ent1, int ent1SaberNum, int ent1BladeNum, gentity_t *ent2, qboolean checkDir) { + vec3_t saberBase1, saberTip1, saberBaseNext1, saberTipNext1; + vec3_t saberBase2, saberTip2, saberBaseNext2, saberTipNext2; + int ent2SaberNum = 0, ent2BladeNum = 0; + vec3_t dir; + + if (!ent1 || !ent2) { return qfalse; } - if ( !ent1->client || !ent2->client ) - { + if (!ent1->client || !ent2->client) { return qfalse; } - if ( BG_SabersOff( &ent1->client->ps ) - || BG_SabersOff( &ent2->client->ps ) ) - { + if (BG_SabersOff(&ent1->client->ps) || BG_SabersOff(&ent2->client->ps)) { return qfalse; } - for ( ent2SaberNum = 0; ent2SaberNum < MAX_SABERS; ent2SaberNum++ ) - { - if ( ent2->client->saber[ent2SaberNum].type != SABER_NONE ) - { - for ( ent2BladeNum = 0; ent2BladeNum < ent2->client->saber[ent2SaberNum].numBlades; ent2BladeNum++ ) - { - if ( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax > 0 ) - {//valid saber and this blade is on - //if ( ent1->client->saberInFlight ) + for (ent2SaberNum = 0; ent2SaberNum < MAX_SABERS; ent2SaberNum++) { + if (ent2->client->saber[ent2SaberNum].type != SABER_NONE) { + for (ent2BladeNum = 0; ent2BladeNum < ent2->client->saber[ent2SaberNum].numBlades; ent2BladeNum++) { + if (ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax > 0) { // valid saber and this blade is on + // if ( ent1->client->saberInFlight ) { - VectorCopy( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, saberBase1 ); - VectorCopy( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBaseNext1 ); - - VectorSubtract( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1 ); - - VectorMA( saberBase1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax+SABER_EXTRAPOLATE_DIST, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirOld, saberTip1 ); - VectorMA( saberBaseNext1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax+SABER_EXTRAPOLATE_DIST, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTipNext1 ); - - VectorSubtract( saberTipNext1, saberTip1, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1 ); + VectorCopy(ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, saberBase1); + VectorCopy(ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBaseNext1); + + VectorSubtract(ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, + ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext1, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext1); + + VectorMA(saberBase1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax + SABER_EXTRAPOLATE_DIST, + ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirOld, saberTip1); + VectorMA(saberBaseNext1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax + SABER_EXTRAPOLATE_DIST, + ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTipNext1); + + VectorSubtract(saberTipNext1, saberTip1, dir); + VectorNormalize(dir); + VectorMA(saberTipNext1, SABER_EXTRAPOLATE_DIST, dir, saberTipNext1); } /* else { VectorCopy( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePoint, saberBase1 ); VectorCopy( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzlePointNext, saberBaseNext1 ); - VectorMA( saberBase1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTip1 ); - VectorMA( saberBaseNext1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirNext, saberTipNext1 ); + VectorMA( saberBase1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax, + ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, saberTip1 ); VectorMA( saberBaseNext1, + ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].lengthMax, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDirNext, + saberTipNext1 ); } */ - //if ( ent2->client->saberInFlight ) + // if ( ent2->client->saberInFlight ) { - VectorCopy( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, saberBase2 ); - VectorCopy( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBaseNext2 ); - - VectorSubtract( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, dir ); - VectorNormalize( dir ); - VectorMA( saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2 ); - - VectorMA( saberBase2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax+SABER_EXTRAPOLATE_DIST, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirOld, saberTip2 ); - VectorMA( saberBaseNext2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax+SABER_EXTRAPOLATE_DIST, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTipNext2 ); - - VectorSubtract( saberTipNext2, saberTip2, dir ); - VectorNormalize( dir ); - VectorMA( saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2 ); + VectorCopy(ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, saberBase2); + VectorCopy(ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBaseNext2); + + VectorSubtract(ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointOld, dir); + VectorNormalize(dir); + VectorMA(saberBaseNext2, SABER_EXTRAPOLATE_DIST, dir, saberBaseNext2); + + VectorMA(saberBase2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax + SABER_EXTRAPOLATE_DIST, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirOld, saberTip2); + VectorMA(saberBaseNext2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax + SABER_EXTRAPOLATE_DIST, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTipNext2); + + VectorSubtract(saberTipNext2, saberTip2, dir); + VectorNormalize(dir); + VectorMA(saberTipNext2, SABER_EXTRAPOLATE_DIST, dir, saberTipNext2); } /* else { VectorCopy( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePoint, saberBase2 ); VectorCopy( ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzlePointNext, saberBaseNext2 ); - VectorMA( saberBase2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTip2 ); - VectorMA( saberBaseNext2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirNext, saberTipNext2 ); + VectorMA( saberBase2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir, saberTip2 ); VectorMA( saberBaseNext2, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].lengthMax, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDirNext, + saberTipNext2 ); } */ - if ( checkDir ) - {//check the direction of the two swings to make sure the sabers are swinging towards each other + if (checkDir) { // check the direction of the two swings to make sure the sabers are swinging towards each other vec3_t saberDir1, saberDir2; float dot = 0.0f; - VectorSubtract( saberTipNext1, saberTip1, saberDir1 ); - VectorSubtract( saberTipNext2, saberTip2, saberDir2 ); - VectorNormalize( saberDir1 ); - VectorNormalize( saberDir2 ); - if ( DotProduct( saberDir1, saberDir2 ) > 0.6f ) - {//sabers moving in same dir, probably didn't actually hit + VectorSubtract(saberTipNext1, saberTip1, saberDir1); + VectorSubtract(saberTipNext2, saberTip2, saberDir2); + VectorNormalize(saberDir1); + VectorNormalize(saberDir2); + if (DotProduct(saberDir1, saberDir2) > 0.6f) { // sabers moving in same dir, probably didn't actually hit continue; } - //now check orientation of sabers, make sure they're not parallel or close to it - dot = DotProduct( ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir ); - if ( dot > 0.9f || dot < -0.9f ) - {//too parallel to really block effectively? + // now check orientation of sabers, make sure they're not parallel or close to it + dot = DotProduct(ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].muzzleDir, + ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].muzzleDir); + if (dot > 0.9f || dot < -0.9f) { // too parallel to really block effectively? continue; } } #ifdef DEBUG_SABER_BOX - if ( g_saberDebugBox.integer == 2 || g_saberDebugBox.integer == 4 ) - { + if (g_saberDebugBox.integer == 2 || g_saberDebugBox.integer == 4) { G_TestLine(saberBase1, saberTip1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].color, 500); G_TestLine(saberTip1, saberTipNext1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].color, 500); G_TestLine(saberTipNext1, saberBase1, ent1->client->saber[ent1SaberNum].blade[ent1BladeNum].color, 500); @@ -2930,20 +2377,16 @@ qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum G_TestLine(saberTipNext2, saberBase2, ent2->client->saber[ent2SaberNum].blade[ent2BladeNum].color, 500); } #endif - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberBaseNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberBaseNext2)) { return qtrue; } - if ( tri_tri_intersect( saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2 ) ) - { + if (tri_tri_intersect(saberBase1, saberTip1, saberTipNext1, saberBase2, saberTip2, saberTipNext2)) { return qtrue; } } @@ -2953,86 +2396,64 @@ qboolean WP_SabersIntersect( gentity_t *ent1, int ent1SaberNum, int ent1BladeNum return qfalse; } -static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qboolean mySaberHit ) -{ - if ( !ent || !ent->client || saberNum >= MAX_SABERS ) - { +static QINLINE int G_PowerLevelForSaberAnim(gentity_t *ent, int saberNum, qboolean mySaberHit) { + if (!ent || !ent->client || saberNum >= MAX_SABERS) { return FORCE_LEVEL_0; - } - else - { + } else { int anim = ent->client->ps.torsoAnim; - int animTimer = ent->client->ps.torsoTimer; - int animTimeElapsed = BG_AnimLength( ent->localAnimIndex, (animNumber_t)anim ) - animTimer; + int animTimer = ent->client->ps.torsoTimer; + int animTimeElapsed = BG_AnimLength(ent->localAnimIndex, (animNumber_t)anim) - animTimer; saberInfo_t *saber = &ent->client->saber[saberNum]; - if ( anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____ ) - { - //FIXME: these two need their own style - if ( saber->type == SABER_LANCE ) - { + if (anim >= BOTH_A1_T__B_ && anim <= BOTH_D1_B____) { + // FIXME: these two need their own style + if (saber->type == SABER_LANCE) { return FORCE_LEVEL_4; - } - else if ( saber->type == SABER_TRIDENT ) - { + } else if (saber->type == SABER_TRIDENT) { return FORCE_LEVEL_3; } return FORCE_LEVEL_1; } - if ( anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____ ) - { + if (anim >= BOTH_A2_T__B_ && anim <= BOTH_D2_B____) { return FORCE_LEVEL_2; } - if ( anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____ ) - { + if (anim >= BOTH_A3_T__B_ && anim <= BOTH_D3_B____) { return FORCE_LEVEL_3; } - if ( anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____ ) - {//desann + if (anim >= BOTH_A4_T__B_ && anim <= BOTH_D4_B____) { // desann return FORCE_LEVEL_4; } - if ( anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____ ) - {//tavion + if (anim >= BOTH_A5_T__B_ && anim <= BOTH_D5_B____) { // tavion return FORCE_LEVEL_2; } - if ( anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____ ) - {//dual + if (anim >= BOTH_A6_T__B_ && anim <= BOTH_D6_B____) { // dual return FORCE_LEVEL_2; } - if ( anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____ ) - {//staff + if (anim >= BOTH_A7_T__B_ && anim <= BOTH_D7_B____) { // staff return FORCE_LEVEL_2; } - if ( anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR ) - {//parries, knockaways and broken parries - return FORCE_LEVEL_1;//FIXME: saberAnimLevel? + if (anim >= BOTH_P1_S1_T_ && anim <= BOTH_H1_S1_BR) { // parries, knockaways and broken parries + return FORCE_LEVEL_1; // FIXME: saberAnimLevel? } - switch ( anim ) - { + switch (anim) { case BOTH_A2_STABBACK1: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimer < 450 ) - {//end of anim + if (animTimer < 450) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_ATTACK_BACK: - if ( animTimer < 500 ) - {//end of anim + if (animTimer < 500) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_CROUCHATTACKBACK1: - if ( animTimer < 800 ) - {//end of anim + if (animTimer < 800) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -3041,45 +2462,38 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool case BOTH_BUTTERFLY_RIGHT: case BOTH_BUTTERFLY_FL1: case BOTH_BUTTERFLY_FR1: - //FIXME: break up? + // FIXME: break up? return FORCE_LEVEL_3; break; case BOTH_FJSS_TR_BL: case BOTH_FJSS_TL_BR: - //FIXME: break up? + // FIXME: break up? return FORCE_LEVEL_3; break; - case BOTH_K1_S1_T_: //# knockaway saber top - case BOTH_K1_S1_TR: //# knockaway saber top right - case BOTH_K1_S1_TL: //# knockaway saber top left - case BOTH_K1_S1_BL: //# knockaway saber bottom left - case BOTH_K1_S1_B_: //# knockaway saber bottom - case BOTH_K1_S1_BR: //# knockaway saber bottom right - //FIXME: break up? + case BOTH_K1_S1_T_: //# knockaway saber top + case BOTH_K1_S1_TR: //# knockaway saber top right + case BOTH_K1_S1_TL: //# knockaway saber top left + case BOTH_K1_S1_BL: //# knockaway saber bottom left + case BOTH_K1_S1_B_: //# knockaway saber bottom + case BOTH_K1_S1_BR: //# knockaway saber bottom right + // FIXME: break up? return FORCE_LEVEL_3; break; case BOTH_LUNGE2_B__T_: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimer < 400 ) - {//end of anim + if (animTimer < 400) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 150 ) - {//beginning of anim + } else if (animTimeElapsed < 150) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_FORCELEAP2_T__B_: - if ( animTimer < 400 ) - {//end of anim + if (animTimer < 400) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 550 ) - {//beginning of anim + } else if (animTimeElapsed < 550) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -3088,26 +2502,20 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool case BOTH_VS_ATL_S: case BOTH_VT_ATR_S: case BOTH_VT_ATL_S: - return FORCE_LEVEL_3;//??? + return FORCE_LEVEL_3; //??? break; case BOTH_JUMPFLIPSLASHDOWN1: - if ( animTimer <= 1000 ) - {//end of anim + if (animTimer <= 1000) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 600 ) - {//beginning of anim + } else if (animTimeElapsed < 600) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_JUMPFLIPSTABDOWN: - if ( animTimer <= 1300 ) - {//end of anim + if (animTimer <= 1300) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed <= 300 ) - {//beginning of anim + } else if (animTimeElapsed <= 300) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -3125,47 +2533,35 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool } } */ - if ( ( animTimer >= 1450 - && animTimeElapsed >= 400 ) - ||(animTimer >= 400 - && animTimeElapsed >= 1100 ) ) - {//pretty much sideways + if ((animTimer >= 1450 && animTimeElapsed >= 400) || (animTimer >= 400 && animTimeElapsed >= 1100)) { // pretty much sideways return FORCE_LEVEL_3; } return FORCE_LEVEL_0; break; case BOTH_JUMPATTACK7: - if ( animTimer <= 1200 ) - {//end of anim + if (animTimer <= 1200) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_SPINATTACK6: - if ( animTimeElapsed <= 200 ) - {//beginning of anim + if (animTimeElapsed <= 200) { // beginning of anim return FORCE_LEVEL_0; } - return FORCE_LEVEL_2;//FORCE_LEVEL_3; + return FORCE_LEVEL_2; // FORCE_LEVEL_3; break; case BOTH_SPINATTACK7: - if ( animTimer <= 500 ) - {//end of anim + if (animTimer <= 500) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 500 ) - {//beginning of anim + } else if (animTimeElapsed < 500) { // beginning of anim return FORCE_LEVEL_0; } - return FORCE_LEVEL_2;//FORCE_LEVEL_3; + return FORCE_LEVEL_2; // FORCE_LEVEL_3; break; case BOTH_FORCELONGLEAP_ATTACK: - if ( animTimeElapsed <= 200 ) - {//1st four frames of anim + if (animTimeElapsed <= 200) { // 1st four frames of anim return FORCE_LEVEL_3; } break; @@ -3179,74 +2575,56 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool break; */ case BOTH_STABDOWN: - if ( animTimer <= 900 ) - {//end of anim + if (animTimer <= 900) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_STABDOWN_STAFF: - if ( animTimer <= 850 ) - {//end of anim + if (animTimer <= 850) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_STABDOWN_DUAL: - if ( animTimer <= 900 ) - {//end of anim + if (animTimer <= 900) { // end of anim return FORCE_LEVEL_3; } break; case BOTH_A6_SABERPROTECT: - if ( animTimer < 650 ) - {//end of anim + if (animTimer < 650) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//start of anim + } else if (animTimeElapsed < 250) { // start of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A7_SOULCAL: - if ( animTimer < 650 ) - {//end of anim + if (animTimer < 650) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 600 ) - {//beginning of anim + } else if (animTimeElapsed < 600) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A1_SPECIAL: - if ( animTimer < 600 ) - {//end of anim + if (animTimer < 600) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A2_SPECIAL: - if ( animTimer < 300 ) - {//end of anim + if (animTimer < 300) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A3_SPECIAL: - if ( animTimer < 700 ) - {//end of anim + if (animTimer < 700) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 200 ) - {//beginning of anim + } else if (animTimeElapsed < 200) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -3255,64 +2633,48 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool return FORCE_LEVEL_3; break; case BOTH_PULL_IMPALE_STAB: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimer < 1000 ) - {//end of anim + if (animTimer < 1000) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_PULL_IMPALE_SWING: - if ( animTimer < 500 ) - {//end of anim + if (animTimer < 500) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 650 ) - {//beginning of anim + } else if (animTimeElapsed < 650) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_ALORA_SPIN_SLASH: - if ( animTimer < 900 ) - {//end of anim + if (animTimer < 900) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A6_FB: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimer < 250 ) - {//end of anim + if (animTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; break; case BOTH_A6_LR: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimer < 250 ) - {//end of anim + if (animTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_3; @@ -3320,41 +2682,33 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool case BOTH_A7_HILT: return FORCE_LEVEL_0; break; - //===SABERLOCK SUPERBREAKS START=========================================================================== + //===SABERLOCK SUPERBREAKS START=========================================================================== case BOTH_LK_S_DL_T_SB_1_W: - if ( animTimer < 700 ) - {//end of anim + if (animTimer < 700) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_ST_S_SB_1_W: - if ( animTimer < 300 ) - {//end of anim + if (animTimer < 300) { // end of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_DL_S_SB_1_W: case BOTH_LK_S_S_S_SB_1_W: - if ( animTimer < 700 ) - {//end of anim + if (animTimer < 700) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_S_ST_T_SB_1_W: case BOTH_LK_S_S_T_SB_1_W: - if ( animTimer < 150 ) - {//end of anim + if (animTimer < 150) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 400 ) - {//beginning of anim + } else if (animTimeElapsed < 400) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -3364,49 +2718,37 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool break; case BOTH_LK_DL_DL_S_SB_1_W: case BOTH_LK_DL_ST_S_SB_1_W: - if ( animTimeElapsed < 1000 ) - {//beginning of anim + if (animTimeElapsed < 1000) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_ST_T_SB_1_W: - if ( animTimer < 950 ) - {//end of anim + if (animTimer < 950) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 650 ) - {//beginning of anim + } else if (animTimeElapsed < 650) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_S_S_SB_1_W: - if ( saberNum != 0 ) - {//only right hand saber does damage in this suberbreak + if (saberNum != 0) { // only right hand saber does damage in this suberbreak return FORCE_LEVEL_0; } - if ( animTimer < 900 ) - {//end of anim + if (animTimer < 900) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 450 ) - {//beginning of anim + } else if (animTimeElapsed < 450) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; break; case BOTH_LK_DL_S_T_SB_1_W: - if ( saberNum != 0 ) - {//only right hand saber does damage in this suberbreak + if (saberNum != 0) { // only right hand saber does damage in this suberbreak return FORCE_LEVEL_0; } - if ( animTimer < 250 ) - {//end of anim + if (animTimer < 250) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 150 ) - {//beginning of anim + } else if (animTimeElapsed < 150) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -3415,17 +2757,14 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool return FORCE_LEVEL_5; break; case BOTH_LK_ST_DL_T_SB_1_W: - //special suberbreak - doesn't kill, just kicks them backwards + // special suberbreak - doesn't kill, just kicks them backwards return FORCE_LEVEL_0; break; case BOTH_LK_ST_ST_S_SB_1_W: case BOTH_LK_ST_S_S_SB_1_W: - if ( animTimer < 800 ) - {//end of anim + if (animTimer < 800) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 350 ) - {//beginning of anim + } else if (animTimeElapsed < 350) { // beginning of anim return FORCE_LEVEL_0; } return FORCE_LEVEL_5; @@ -3434,33 +2773,24 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool case BOTH_LK_ST_S_T_SB_1_W: return FORCE_LEVEL_5; break; - //===SABERLOCK SUPERBREAKS START=========================================================================== + //===SABERLOCK SUPERBREAKS START=========================================================================== case BOTH_HANG_ATTACK: - //FIME: break up - if ( animTimer < 1000 ) - {//end of anim + // FIME: break up + if (animTimer < 1000) { // end of anim return FORCE_LEVEL_0; - } - else if ( animTimeElapsed < 250 ) - {//beginning of anim + } else if (animTimeElapsed < 250) { // beginning of anim return FORCE_LEVEL_0; - } - else - {//sweet spot + } else { // sweet spot return FORCE_LEVEL_5; } break; case BOTH_ROLL_STAB: - if ( mySaberHit ) - {//someone else hit my saber, not asking for damage level, but defense strength + if (mySaberHit) { // someone else hit my saber, not asking for damage level, but defense strength return FORCE_LEVEL_1; } - if ( animTimeElapsed > 400 ) - {//end of anim + if (animTimeElapsed > 400) { // end of anim return FORCE_LEVEL_0; - } - else - { + } else { return FORCE_LEVEL_3; } break; @@ -3470,124 +2800,101 @@ static QINLINE int G_PowerLevelForSaberAnim( gentity_t *ent, int saberNum, qbool } #define MAX_SABER_VICTIMS 16 -static int victimEntityNum[MAX_SABER_VICTIMS]; +static int victimEntityNum[MAX_SABER_VICTIMS]; static qboolean victimHitEffectDone[MAX_SABER_VICTIMS]; -static float totalDmg[MAX_SABER_VICTIMS]; -static vec3_t dmgDir[MAX_SABER_VICTIMS]; -static vec3_t dmgSpot[MAX_SABER_VICTIMS]; +static float totalDmg[MAX_SABER_VICTIMS]; +static vec3_t dmgDir[MAX_SABER_VICTIMS]; +static vec3_t dmgSpot[MAX_SABER_VICTIMS]; static qboolean dismemberDmg[MAX_SABER_VICTIMS]; static int saberKnockbackFlags[MAX_SABER_VICTIMS]; static int numVictims = 0; -void WP_SaberClearDamage( void ) -{ +void WP_SaberClearDamage(void) { int ven; - for ( ven = 0; ven < MAX_SABER_VICTIMS; ven++ ) - { + for (ven = 0; ven < MAX_SABER_VICTIMS; ven++) { victimEntityNum[ven] = ENTITYNUM_NONE; } - memset( victimHitEffectDone, 0, sizeof( victimHitEffectDone ) ); - memset( totalDmg, 0, sizeof( totalDmg ) ); - memset( dmgDir, 0, sizeof( dmgDir ) ); - memset( dmgSpot, 0, sizeof( dmgSpot ) ); - memset( dismemberDmg, 0, sizeof( dismemberDmg ) ); - memset( saberKnockbackFlags, 0, sizeof( saberKnockbackFlags ) ); + memset(victimHitEffectDone, 0, sizeof(victimHitEffectDone)); + memset(totalDmg, 0, sizeof(totalDmg)); + memset(dmgDir, 0, sizeof(dmgDir)); + memset(dmgSpot, 0, sizeof(dmgSpot)); + memset(dismemberDmg, 0, sizeof(dismemberDmg)); + memset(saberKnockbackFlags, 0, sizeof(saberKnockbackFlags)); numVictims = 0; } -void WP_SaberDamageAdd( int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgSpot, - int trDmg, qboolean doDismemberment, int knockBackFlags ) -{ - if ( trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD ) - { +void WP_SaberDamageAdd(int trVictimEntityNum, vec3_t trDmgDir, vec3_t trDmgSpot, int trDmg, qboolean doDismemberment, int knockBackFlags) { + if (trVictimEntityNum < 0 || trVictimEntityNum >= ENTITYNUM_WORLD) { return; } - if ( trDmg ) - {//did some damage to something + if (trDmg) { // did some damage to something int curVictim = 0; int i; - for ( i = 0; i < numVictims; i++ ) - { - if ( victimEntityNum[i] == trVictimEntityNum ) - {//already hit this guy before + for (i = 0; i < numVictims; i++) { + if (victimEntityNum[i] == trVictimEntityNum) { // already hit this guy before curVictim = i; break; } } - if ( i == numVictims ) - {//haven't hit his guy before - if ( numVictims + 1 >= MAX_SABER_VICTIMS ) - {//can't add another victim at this time + if (i == numVictims) { // haven't hit his guy before + if (numVictims + 1 >= MAX_SABER_VICTIMS) { // can't add another victim at this time return; } - //add a new victim to the list + // add a new victim to the list curVictim = numVictims; victimEntityNum[numVictims++] = trVictimEntityNum; } totalDmg[curVictim] += trDmg; - if ( VectorCompare( dmgDir[curVictim], vec3_origin ) ) - { - VectorCopy( trDmgDir, dmgDir[curVictim] ); + if (VectorCompare(dmgDir[curVictim], vec3_origin)) { + VectorCopy(trDmgDir, dmgDir[curVictim]); } - if ( VectorCompare( dmgSpot[curVictim], vec3_origin ) ) - { - VectorCopy( trDmgSpot, dmgSpot[curVictim] ); + if (VectorCompare(dmgSpot[curVictim], vec3_origin)) { + VectorCopy(trDmgSpot, dmgSpot[curVictim]); } - if ( doDismemberment ) - { + if (doDismemberment) { dismemberDmg[curVictim] = qtrue; } saberKnockbackFlags[curVictim] |= knockBackFlags; } } -void WP_SaberApplyDamage( gentity_t *self ) -{ +void WP_SaberApplyDamage(gentity_t *self) { int i; - if ( !numVictims ) - { + if (!numVictims) { return; } - for ( i = 0; i < numVictims; i++ ) - { + for (i = 0; i < numVictims; i++) { gentity_t *victim = NULL; int dflags = 0; victim = &g_entities[victimEntityNum[i]]; -// nmckenzie: SABER_DAMAGE_WALLS - if ( !victim->client ) - { + // nmckenzie: SABER_DAMAGE_WALLS + if (!victim->client) { totalDmg[i] *= g_saberWallDamageScale.value; } - if ( !dismemberDmg[i] ) - {//don't do dismemberment! + if (!dismemberDmg[i]) { // don't do dismemberment! dflags |= DAMAGE_NO_DISMEMBER; } dflags |= saberKnockbackFlags[i]; - G_Damage( victim, self, self, dmgDir[i], dmgSpot[i], totalDmg[i], dflags, MOD_SABER ); + G_Damage(victim, self, self, dmgDir[i], dmgSpot[i], totalDmg[i], dflags, MOD_SABER); } } - -void WP_SaberDoHit( gentity_t *self, int saberNum, int bladeNum ) -{ +void WP_SaberDoHit(gentity_t *self, int saberNum, int bladeNum) { int i; - if ( !numVictims ) - { + if (!numVictims) { return; } - for ( i = 0; i < numVictims; i++ ) - { + for (i = 0; i < numVictims; i++) { gentity_t *te = NULL, *victim = NULL; qboolean isDroid = qfalse; - if ( victimHitEffectDone[i] ) - { + if (victimHitEffectDone[i]) { continue; } @@ -3595,67 +2902,48 @@ void WP_SaberDoHit( gentity_t *self, int saberNum, int bladeNum ) victim = &g_entities[victimEntityNum[i]]; - if ( victim->client ) - { + if (victim->client) { class_t npc_class = victim->client->NPC_class; - if ( npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || - npc_class == CLASS_GONK || npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || - npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || - npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY ) - { //don't make "blood" sparks for droids. + if (npc_class == CLASS_SEEKER || npc_class == CLASS_PROBE || npc_class == CLASS_MOUSE || npc_class == CLASS_REMOTE || npc_class == CLASS_GONK || + npc_class == CLASS_R2D2 || npc_class == CLASS_R5D2 || npc_class == CLASS_PROTOCOL || npc_class == CLASS_MARK1 || npc_class == CLASS_MARK2 || + npc_class == CLASS_INTERROGATOR || npc_class == CLASS_ATST || npc_class == CLASS_SENTRY) { // don't make "blood" sparks for droids. isDroid = qtrue; } } - te = G_TempEntity( dmgSpot[i], EV_SABER_HIT ); - if ( te ) - { + te = G_TempEntity(dmgSpot[i], EV_SABER_HIT); + if (te) { te->s.otherEntityNum = victimEntityNum[i]; te->s.otherEntityNum2 = self->s.number; te->s.weapon = saberNum; te->s.legsAnim = bladeNum; VectorCopy(dmgSpot[i], te->s.origin); - //VectorCopy(tr.plane.normal, te->s.angles); - VectorScale( dmgDir[i], -1, te->s.angles); + // VectorCopy(tr.plane.normal, te->s.angles); + VectorScale(dmgDir[i], -1, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { //don't let it play with no direction + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { // don't let it play with no direction te->s.angles[1] = 1; } - if (!isDroid && (victim->client || victim->s.eType == ET_NPC || - victim->s.eType == ET_BODY)) - { - if ( totalDmg[i] < 5 ) - { + if (!isDroid && (victim->client || victim->s.eType == ET_NPC || victim->s.eType == ET_BODY)) { + if (totalDmg[i] < 5) { te->s.eventParm = 3; - } - else if (totalDmg[i] < 20 ) - { + } else if (totalDmg[i] < 20) { te->s.eventParm = 2; - } - else - { + } else { te->s.eventParm = 1; } - } - else - { - if ( !WP_SaberBladeUseSecondBladeStyle( &self->client->saber[saberNum], bladeNum ) - && (self->client->saber[saberNum].saberFlags2&SFL2_NO_CLASH_FLARE) ) - {//don't do clash flare - } - else if ( WP_SaberBladeUseSecondBladeStyle( &self->client->saber[saberNum], bladeNum ) - && (self->client->saber[saberNum].saberFlags2&SFL2_NO_CLASH_FLARE2) ) - {//don't do clash flare - } - else - { - if (totalDmg[i] > SABER_NONATTACK_DAMAGE) - { //I suppose I could tie this into the saberblock event, but I'm tired of adding flags to that thing. - gentity_t *teS = G_TempEntity( te->s.origin, EV_SABER_CLASHFLARE ); + } else { + if (!WP_SaberBladeUseSecondBladeStyle(&self->client->saber[saberNum], bladeNum) && + (self->client->saber[saberNum].saberFlags2 & SFL2_NO_CLASH_FLARE)) { // don't do clash flare + } else if (WP_SaberBladeUseSecondBladeStyle(&self->client->saber[saberNum], bladeNum) && + (self->client->saber[saberNum].saberFlags2 & SFL2_NO_CLASH_FLARE2)) { // don't do clash flare + } else { + if (totalDmg[i] > + SABER_NONATTACK_DAMAGE) { // I suppose I could tie this into the saberblock event, but I'm tired of adding flags to that thing. + gentity_t *teS = G_TempEntity(te->s.origin, EV_SABER_CLASHFLARE); VectorCopy(te->s.origin, teS->s.origin); } te->s.eventParm = 0; @@ -3665,91 +2953,70 @@ void WP_SaberDoHit( gentity_t *self, int saberNum, int bladeNum ) } } -extern qboolean G_EntIsBreakable( int entityNum ); -extern void G_Knockdown( gentity_t *victim ); -void WP_SaberRadiusDamage( gentity_t *ent, vec3_t point, float radius, int damage, float knockBack ) -{ - if ( !ent || !ent->client ) - { +extern qboolean G_EntIsBreakable(int entityNum); +extern void G_Knockdown(gentity_t *victim); +void WP_SaberRadiusDamage(gentity_t *ent, vec3_t point, float radius, int damage, float knockBack) { + if (!ent || !ent->client) { return; - } - else if ( radius <= 0.0f || (damage <= 0 && knockBack <= 0) ) - { + } else if (radius <= 0.0f || (damage <= 0 && knockBack <= 0)) { return; - } - else - { - vec3_t mins, maxs, entDir; - int radiusEnts[128]; - gentity_t *radiusEnt = NULL; - int numEnts, i; - float dist; - - //Setup the bbox to search in - for ( i = 0; i < 3; i++ ) - { + } else { + vec3_t mins, maxs, entDir; + int radiusEnts[128]; + gentity_t *radiusEnt = NULL; + int numEnts, i; + float dist; + + // Setup the bbox to search in + for (i = 0; i < 3; i++) { mins[i] = point[i] - radius; maxs[i] = point[i] + radius; } - //Get the number of entities in a given space - numEnts = trap->EntitiesInBox( mins, maxs, radiusEnts, 128 ); + // Get the number of entities in a given space + numEnts = trap->EntitiesInBox(mins, maxs, radiusEnts, 128); - for ( i = 0; i < numEnts; i++ ) - { + for (i = 0; i < numEnts; i++) { radiusEnt = &g_entities[radiusEnts[i]]; - if ( !radiusEnt->inuse ) - { + if (!radiusEnt->inuse) { continue; } - if ( radiusEnt == ent ) - {//Skip myself + if (radiusEnt == ent) { // Skip myself continue; } - if ( radiusEnt->client == NULL ) - {//must be a client - if ( G_EntIsBreakable( radiusEnt->s.number ) ) - {//damage breakables within range, but not as much - G_Damage( radiusEnt, ent, ent, vec3_origin, radiusEnt->r.currentOrigin, 10, 0, MOD_MELEE ); + if (radiusEnt->client == NULL) { // must be a client + if (G_EntIsBreakable(radiusEnt->s.number)) { // damage breakables within range, but not as much + G_Damage(radiusEnt, ent, ent, vec3_origin, radiusEnt->r.currentOrigin, 10, 0, MOD_MELEE); } continue; } - if ( (radiusEnt->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//can't be one being held + if ((radiusEnt->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // can't be one being held continue; } - VectorSubtract( radiusEnt->r.currentOrigin, point, entDir ); - dist = VectorNormalize( entDir ); - if ( dist <= radius ) - {//in range - if ( damage > 0 ) - {//do damage - int points = ceil((float)damage*dist/radius); - G_Damage( radiusEnt, ent, ent, vec3_origin, radiusEnt->r.currentOrigin, points, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - if ( knockBack > 0 ) - {//do knockback - if ( radiusEnt->client - && radiusEnt->client->NPC_class != CLASS_RANCOR - && radiusEnt->client->NPC_class != CLASS_ATST - && !(radiusEnt->flags&FL_NO_KNOCKBACK) )//don't throw them back + VectorSubtract(radiusEnt->r.currentOrigin, point, entDir); + dist = VectorNormalize(entDir); + if (dist <= radius) { // in range + if (damage > 0) { // do damage + int points = ceil((float)damage * dist / radius); + G_Damage(radiusEnt, ent, ent, vec3_origin, radiusEnt->r.currentOrigin, points, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } + if (knockBack > 0) { // do knockback + if (radiusEnt->client && radiusEnt->client->NPC_class != CLASS_RANCOR && radiusEnt->client->NPC_class != CLASS_ATST && + !(radiusEnt->flags & FL_NO_KNOCKBACK)) // don't throw them back { - float knockbackStr = knockBack*dist/radius; + float knockbackStr = knockBack * dist / radius; entDir[2] += 0.1f; - VectorNormalize( entDir ); - G_Throw( radiusEnt, entDir, knockbackStr ); - if ( radiusEnt->health > 0 ) - {//still alive - if ( knockbackStr > 50 ) - {//close enough and knockback high enough to possibly knock down - if ( dist < (radius*0.5f) - || radiusEnt->client->ps.groundEntityNum != ENTITYNUM_NONE ) - {//within range of my fist or within ground-shaking range and not in the air - G_Knockdown( radiusEnt );//, ent, entDir, 500, qtrue ); + VectorNormalize(entDir); + G_Throw(radiusEnt, entDir, knockbackStr); + if (radiusEnt->health > 0) { // still alive + if (knockbackStr > 50) { // close enough and knockback high enough to possibly knock down + if (dist < (radius * 0.5f) || radiusEnt->client->ps.groundEntityNum != + ENTITYNUM_NONE) { // within range of my fist or within ground-shaking range and not in the air + G_Knockdown(radiusEnt); //, ent, entDir, 500, qtrue ); } } } @@ -3764,11 +3031,9 @@ static qboolean saberDoClashEffect = qfalse; static vec3_t saberClashPos = {0}; static vec3_t saberClashNorm = {0}; static int saberClashEventParm = 1; -void WP_SaberDoClash( gentity_t *self, int saberNum, int bladeNum ) -{ - if ( saberDoClashEffect ) - { - gentity_t *te = G_TempEntity( saberClashPos, EV_SABER_BLOCK ); +void WP_SaberDoClash(gentity_t *self, int saberNum, int bladeNum) { + if (saberDoClashEffect) { + gentity_t *te = G_TempEntity(saberClashPos, EV_SABER_BLOCK); VectorCopy(saberClashPos, te->s.origin); VectorCopy(saberClashNorm, te->s.angles); te->s.eventParm = saberClashEventParm; @@ -3778,52 +3043,38 @@ void WP_SaberDoClash( gentity_t *self, int saberNum, int bladeNum ) } } -void WP_SaberBounceSound( gentity_t *ent, int saberNum, int bladeNum ) -{ +void WP_SaberBounceSound(gentity_t *ent, int saberNum, int bladeNum) { int index = 1; - if ( !ent || !ent->client ) - { + if (!ent || !ent->client) { return; } - index = Q_irand( 1, 9 ); - if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->saber[saberNum], bladeNum ) - && ent->client->saber[saberNum].bounceSound[0] ) - { - G_Sound( ent, CHAN_AUTO, ent->client->saber[saberNum].bounceSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->saber[saberNum], bladeNum ) - && ent->client->saber[saberNum].bounce2Sound[0] ) - { - G_Sound( ent, CHAN_AUTO, ent->client->saber[saberNum].bounce2Sound[Q_irand( 0, 2 )] ); + index = Q_irand(1, 9); + if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->saber[saberNum], bladeNum) && ent->client->saber[saberNum].bounceSound[0]) { + G_Sound(ent, CHAN_AUTO, ent->client->saber[saberNum].bounceSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->saber[saberNum], bladeNum) && ent->client->saber[saberNum].bounce2Sound[0]) { + G_Sound(ent, CHAN_AUTO, ent->client->saber[saberNum].bounce2Sound[Q_irand(0, 2)]); } - else if ( !WP_SaberBladeUseSecondBladeStyle( &ent->client->saber[saberNum], bladeNum ) - && ent->client->saber[saberNum].blockSound[0] ) - { - G_Sound( ent, CHAN_AUTO, ent->client->saber[saberNum].blockSound[Q_irand( 0, 2 )] ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &ent->client->saber[saberNum], bladeNum ) - && ent->client->saber[saberNum].block2Sound[0] ) - { - G_Sound( ent, CHAN_AUTO, ent->client->saber[saberNum].block2Sound[Q_irand( 0, 2 )] ); - } - else - { - G_Sound( ent, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/saber/saberblock%d.wav", index ) ) ); + else if (!WP_SaberBladeUseSecondBladeStyle(&ent->client->saber[saberNum], bladeNum) && ent->client->saber[saberNum].blockSound[0]) { + G_Sound(ent, CHAN_AUTO, ent->client->saber[saberNum].blockSound[Q_irand(0, 2)]); + } else if (WP_SaberBladeUseSecondBladeStyle(&ent->client->saber[saberNum], bladeNum) && ent->client->saber[saberNum].block2Sound[0]) { + G_Sound(ent, CHAN_AUTO, ent->client->saber[saberNum].block2Sound[Q_irand(0, 2)]); + } else { + G_Sound(ent, CHAN_AUTO, G_SoundIndex(va("sound/weapons/saber/saberblock%d.wav", index))); } } static qboolean saberHitWall = qfalse; static qboolean saberHitSaber = qfalse; static float saberHitFraction = 1.0f; -//rww - MP version of the saber damage function. This is where all the things like blocking, triggering a parry, -//triggering a broken parry, doing actual damage, etc. are done for the saber. It doesn't resemble the SP -//version very much, but functionality is (hopefully) about the same. -//This is a large function. I feel sort of bad inlining it. But it does get called tons of times per frame. -qboolean BG_SuperBreakWinAnim( int anim ); - -static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBladeNum, vec3_t saberStart, vec3_t saberEnd, qboolean doInterpolate, int trMask, qboolean extrapolate ) -{ +// rww - MP version of the saber damage function. This is where all the things like blocking, triggering a parry, +// triggering a broken parry, doing actual damage, etc. are done for the saber. It doesn't resemble the SP +// version very much, but functionality is (hopefully) about the same. +// This is a large function. I feel sort of bad inlining it. But it does get called tons of times per frame. +qboolean BG_SuperBreakWinAnim(int anim); + +static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBladeNum, vec3_t saberStart, vec3_t saberEnd, qboolean doInterpolate, int trMask, + qboolean extrapolate) { static trace_t tr; static vec3_t dir; static vec3_t saberTrMins, saberTrMaxs; @@ -3846,68 +3097,49 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl gentity_t *otherOwner; - if (BG_SabersOff( &self->client->ps )) - { + if (BG_SabersOff(&self->client->ps)) { return qfalse; } selfSaberLevel = G_SaberAttackPower(self, SaberAttacking(self)); - //Add the standard radius into the box size - saberBoxSize += (self->client->saber[rSaberNum].blade[rBladeNum].radius*0.5f); + // Add the standard radius into the box size + saberBoxSize += (self->client->saber[rSaberNum].blade[rBladeNum].radius * 0.5f); - if (self->client->ps.weaponTime <= 0) - { //if not doing any attacks or anything, just use point traces. + if (self->client->ps.weaponTime <= 0) { // if not doing any attacks or anything, just use point traces. VectorClear(saberTrMins); VectorClear(saberTrMaxs); - } - else if (d_saberGhoul2Collision.integer) - { - if ( d_saberSPStyleDamage.integer ) - {//SP-size saber damage traces - VectorSet(saberTrMins, -2, -2, -2 ); - VectorSet(saberTrMaxs, 2, 2, 2 ); - } - else - { - VectorSet(saberTrMins, -saberBoxSize*3, -saberBoxSize*3, -saberBoxSize*3); - VectorSet(saberTrMaxs, saberBoxSize*3, saberBoxSize*3, saberBoxSize*3); - } - } - else if (self->client->ps.fd.saberAnimLevel < FORCE_LEVEL_2) - { //box trace for fast, because it doesn't get updated so often + } else if (d_saberGhoul2Collision.integer) { + if (d_saberSPStyleDamage.integer) { // SP-size saber damage traces + VectorSet(saberTrMins, -2, -2, -2); + VectorSet(saberTrMaxs, 2, 2, 2); + } else { + VectorSet(saberTrMins, -saberBoxSize * 3, -saberBoxSize * 3, -saberBoxSize * 3); + VectorSet(saberTrMaxs, saberBoxSize * 3, saberBoxSize * 3, saberBoxSize * 3); + } + } else if (self->client->ps.fd.saberAnimLevel < FORCE_LEVEL_2) { // box trace for fast, because it doesn't get updated so often VectorSet(saberTrMins, -saberBoxSize, -saberBoxSize, -saberBoxSize); VectorSet(saberTrMaxs, saberBoxSize, saberBoxSize, saberBoxSize); - } - else if (d_saberAlwaysBoxTrace.integer) - { + } else if (d_saberAlwaysBoxTrace.integer) { VectorSet(saberTrMins, -saberBoxSize, -saberBoxSize, -saberBoxSize); VectorSet(saberTrMaxs, saberBoxSize, saberBoxSize, saberBoxSize); - } - else - { //just trace the minimum blade radius - saberBoxSize = (self->client->saber[rSaberNum].blade[rBladeNum].radius*0.4f); + } else { // just trace the minimum blade radius + saberBoxSize = (self->client->saber[rSaberNum].blade[rBladeNum].radius * 0.4f); VectorSet(saberTrMins, -saberBoxSize, -saberBoxSize, -saberBoxSize); VectorSet(saberTrMaxs, saberBoxSize, saberBoxSize, saberBoxSize); } - while (!saberTraceDone) - { - if ( doInterpolate - && !d_saberSPStyleDamage.integer ) - { //This didn't quite work out like I hoped. But it's better than nothing. Sort of. + while (!saberTraceDone) { + if (doInterpolate && !d_saberSPStyleDamage.integer) { // This didn't quite work out like I hoped. But it's better than nothing. Sort of. vec3_t oldSaberStart, oldSaberEnd, saberDif, oldSaberDif; int traceTests = 0; float trDif = 8; - if ( (level.time-self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100 ) - {//no valid last pos, use current + if ((level.time - self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100) { // no valid last pos, use current VectorCopy(saberStart, oldSaberStart); VectorCopy(saberEnd, oldSaberEnd); - } - else - {//trace from last pos + } else { // trace from last pos VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.base, oldSaberStart); VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.tip, oldSaberEnd); } @@ -3918,43 +3150,35 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl VectorNormalize(saberDif); VectorNormalize(oldSaberDif); - saberEnd[0] = saberStart[0] - (saberDif[0]*trDif); - saberEnd[1] = saberStart[1] - (saberDif[1]*trDif); - saberEnd[2] = saberStart[2] - (saberDif[2]*trDif); + saberEnd[0] = saberStart[0] - (saberDif[0] * trDif); + saberEnd[1] = saberStart[1] - (saberDif[1] * trDif); + saberEnd[2] = saberStart[2] - (saberDif[2] * trDif); - oldSaberEnd[0] = oldSaberStart[0] - (oldSaberDif[0]*trDif); - oldSaberEnd[1] = oldSaberStart[1] - (oldSaberDif[1]*trDif); - oldSaberEnd[2] = oldSaberStart[2] - (oldSaberDif[2]*trDif); + oldSaberEnd[0] = oldSaberStart[0] - (oldSaberDif[0] * trDif); + oldSaberEnd[1] = oldSaberStart[1] - (oldSaberDif[1] * trDif); + oldSaberEnd[2] = oldSaberStart[2] - (oldSaberDif[2] * trDif); trap->Trace(&tr, saberEnd, saberTrMins, saberTrMaxs, saberStart, self->s.number, trMask, qfalse, 0, 0); VectorCopy(saberEnd, lastValidStart); VectorCopy(saberStart, lastValidEnd); - if (tr.entityNum < MAX_CLIENTS) - { + if (tr.entityNum < MAX_CLIENTS) { G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); - } - else if (tr.entityNum < ENTITYNUM_WORLD) - { + } else if (tr.entityNum < ENTITYNUM_WORLD) { gentity_t *trHit = &g_entities[tr.entityNum]; - if (trHit->inuse && trHit->ghoul2) - { //hit a non-client entity with a g2 instance + if (trHit->inuse && trHit->ghoul2) { // hit a non-client entity with a g2 instance G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); } } trDif++; - while (tr.fraction == 1.0 && traceTests < 4 && tr.entityNum >= ENTITYNUM_NONE) - { - if ( (level.time-self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100 ) - {//no valid last pos, use current + while (tr.fraction == 1.0 && traceTests < 4 && tr.entityNum >= ENTITYNUM_NONE) { + if ((level.time - self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100) { // no valid last pos, use current VectorCopy(saberStart, oldSaberStart); VectorCopy(saberEnd, oldSaberEnd); - } - else - {//trace from last pos + } else { // trace from last pos VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.base, oldSaberStart); VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.tip, oldSaberEnd); } @@ -3965,28 +3189,24 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl VectorNormalize(saberDif); VectorNormalize(oldSaberDif); - saberEnd[0] = saberStart[0] - (saberDif[0]*trDif); - saberEnd[1] = saberStart[1] - (saberDif[1]*trDif); - saberEnd[2] = saberStart[2] - (saberDif[2]*trDif); + saberEnd[0] = saberStart[0] - (saberDif[0] * trDif); + saberEnd[1] = saberStart[1] - (saberDif[1] * trDif); + saberEnd[2] = saberStart[2] - (saberDif[2] * trDif); - oldSaberEnd[0] = oldSaberStart[0] - (oldSaberDif[0]*trDif); - oldSaberEnd[1] = oldSaberStart[1] - (oldSaberDif[1]*trDif); - oldSaberEnd[2] = oldSaberStart[2] - (oldSaberDif[2]*trDif); + oldSaberEnd[0] = oldSaberStart[0] - (oldSaberDif[0] * trDif); + oldSaberEnd[1] = oldSaberStart[1] - (oldSaberDif[1] * trDif); + oldSaberEnd[2] = oldSaberStart[2] - (oldSaberDif[2] * trDif); trap->Trace(&tr, saberEnd, saberTrMins, saberTrMaxs, saberStart, self->s.number, trMask, qfalse, 0, 0); VectorCopy(saberEnd, lastValidStart); VectorCopy(saberStart, lastValidEnd); - if (tr.entityNum < MAX_CLIENTS) - { + if (tr.entityNum < MAX_CLIENTS) { G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); - } - else if (tr.entityNum < ENTITYNUM_WORLD) - { + } else if (tr.entityNum < ENTITYNUM_WORLD) { gentity_t *trHit = &g_entities[tr.entityNum]; - if (trHit->inuse && trHit->ghoul2) - { //hit a non-client entity with a g2 instance + if (trHit->inuse && trHit->ghoul2) { // hit a non-client entity with a g2 instance G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); } } @@ -3994,20 +3214,15 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl traceTests++; trDif += 8; } - } - else - { + } else { vec3_t saberEndExtrapolated; - if ( extrapolate ) - {//extrapolate 16 + if (extrapolate) { // extrapolate 16 vec3_t diff; - VectorSubtract( saberEnd, saberStart, diff ); - VectorNormalize( diff ); - VectorMA( saberStart, SABER_EXTRAPOLATE_DIST, diff, saberEndExtrapolated ); - } - else - { - VectorCopy( saberEnd, saberEndExtrapolated ); + VectorSubtract(saberEnd, saberStart, diff); + VectorNormalize(diff); + VectorMA(saberStart, SABER_EXTRAPOLATE_DIST, diff, saberEndExtrapolated); + } else { + VectorCopy(saberEnd, saberEndExtrapolated); } trap->Trace(&tr, saberStart, saberTrMins, saberTrMaxs, saberEndExtrapolated, self->s.number, trMask, qfalse, 0, 0); @@ -4023,16 +3238,12 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl Com_Printf( "saber trace start/all solid - ent is %d\n", tr.entityNum ); } */ - if (tr.entityNum < MAX_CLIENTS) - { + if (tr.entityNum < MAX_CLIENTS) { G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); - } - else if (tr.entityNum < ENTITYNUM_WORLD) - { + } else if (tr.entityNum < ENTITYNUM_WORLD) { gentity_t *trHit = &g_entities[tr.entityNum]; - if (trHit->inuse && trHit->ghoul2) - { //hit a non-client entity with a g2 instance + if (trHit->inuse && trHit->ghoul2) { // hit a non-client entity with a g2 instance G_G2TraceCollide(&tr, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs); } } @@ -4041,42 +3252,30 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl saberTraceDone = qtrue; } - if ( self->client->ps.saberAttackWound < level.time - && (SaberAttacking(self) - || BG_SuperBreakWinAnim(self->client->ps.torsoAnim) - || (d_saberSPStyleDamage.integer&&self->client->ps.saberInFlight&&rSaberNum==0) - || (WP_SaberBladeDoTransitionDamage( &self->client->saber[rSaberNum], rBladeNum )&&BG_SaberInTransitionAny(self->client->ps.saberMove)) - || (self->client->ps.m_iVehicleNum && self->client->ps.saberMove > LS_READY) ) - ) - { //this animation is that of the last attack movement, and so it should do full damage + if (self->client->ps.saberAttackWound < level.time && + (SaberAttacking(self) || BG_SuperBreakWinAnim(self->client->ps.torsoAnim) || + (d_saberSPStyleDamage.integer && self->client->ps.saberInFlight && rSaberNum == 0) || + (WP_SaberBladeDoTransitionDamage(&self->client->saber[rSaberNum], rBladeNum) && BG_SaberInTransitionAny(self->client->ps.saberMove)) || + (self->client->ps.m_iVehicleNum && + self->client->ps.saberMove > LS_READY))) { // this animation is that of the last attack movement, and so it should do full damage qboolean saberInSpecial = BG_SaberInSpecial(self->client->ps.saberMove); qboolean inBackAttack = G_SaberInBackAttack(self->client->ps.saberMove); - if ( d_saberSPStyleDamage.integer ) - { + if (d_saberSPStyleDamage.integer) { float fDmg = 0.0f; - if ( self->client->ps.saberInFlight ) - { + if (self->client->ps.saberInFlight) { gentity_t *saberEnt = &g_entities[self->client->ps.saberEntityNum]; - if ( !saberEnt - || !saberEnt->s.saberInFlight ) - {//does less damage on the way back + if (!saberEnt || !saberEnt->s.saberInFlight) { // does less damage on the way back fDmg = 1.0f; attackStr = FORCE_LEVEL_0; - } - else - { - fDmg = 2.5f*self->client->ps.fd.forcePowerLevel[FP_SABERTHROW]; + } else { + fDmg = 2.5f * self->client->ps.fd.forcePowerLevel[FP_SABERTHROW]; attackStr = FORCE_LEVEL_1; } - } - else - { - attackStr = G_PowerLevelForSaberAnim( self, rSaberNum, qfalse ); - if ( g_saberRealisticCombat.integer ) - { - switch ( attackStr ) - { + } else { + attackStr = G_PowerLevelForSaberAnim(self, rSaberNum, qfalse); + if (g_saberRealisticCombat.integer) { + switch (attackStr) { default: case FORCE_LEVEL_3: fDmg = 10.0f; @@ -4089,28 +3288,18 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl fDmg = 2.5f; break; } - } - else - { - if ( self->client->ps.torsoAnim == BOTH_SPINATTACK6 - || self->client->ps.torsoAnim == BOTH_SPINATTACK7 ) - {//too easy to do, lower damage + } else { + if (self->client->ps.torsoAnim == BOTH_SPINATTACK6 || self->client->ps.torsoAnim == BOTH_SPINATTACK7) { // too easy to do, lower damage fDmg = 2.5f; - } - else - { + } else { fDmg = 2.5f * (float)attackStr; } } } - if ( g_saberRealisticCombat.integer > 1 ) - {//always do damage, and lots of it - if ( g_saberRealisticCombat.integer > 2 ) - {//always do damage, and lots of it + if (g_saberRealisticCombat.integer > 1) { // always do damage, and lots of it + if (g_saberRealisticCombat.integer > 2) { // always do damage, and lots of it fDmg = 25.0f; - } - else if ( fDmg > 0.1f ) - {//only do super damage if we would have done damage according to normal rules + } else if (fDmg > 0.1f) { // only do super damage if we would have done damage according to normal rules fDmg = 25.0f; } } @@ -4127,304 +3316,206 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } } */ - if ( level.gametype != GT_DUEL - && level.gametype != GT_POWERDUEL - && level.gametype != GT_SIEGE ) - {//in faster-paced games, sabers do more damage + if (level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && level.gametype != GT_SIEGE) { // in faster-paced games, sabers do more damage fDmg *= 2.0f; } - if ( fDmg ) - {//the longer the trace, the more damage it does - //FIXME: in SP, we only use the part of the trace that's actually *inside* the hit ent... - float traceLength = Distance( saberEnd, saberStart ); - if ( tr.fraction >= 1.0f ) - {//allsolid? - dmg = ceil( fDmg*traceLength*0.1f*0.33f ); - } - else - {//fractional hit, the sooner you hit in the trace, the more damage you did - dmg = ceil( fDmg*traceLength*(1.0f-tr.fraction)*0.1f*0.33f );//(1.0f-tr.fraction) isn't really accurate, but kind of simulates what we have in SP + if (fDmg) { // the longer the trace, the more damage it does + // FIXME: in SP, we only use the part of the trace that's actually *inside* the hit ent... + float traceLength = Distance(saberEnd, saberStart); + if (tr.fraction >= 1.0f) { // allsolid? + dmg = ceil(fDmg * traceLength * 0.1f * 0.33f); + } else { // fractional hit, the sooner you hit in the trace, the more damage you did + dmg = ceil(fDmg * traceLength * (1.0f - tr.fraction) * 0.1f * + 0.33f); //(1.0f-tr.fraction) isn't really accurate, but kind of simulates what we have in SP } #ifdef DEBUG_SABER_BOX - if ( g_saberDebugBox.integer == 3 || g_saberDebugBox.integer == 4 ) - { - G_TestLine( saberStart, saberEnd, 0x0000ff, 50 ); + if (g_saberDebugBox.integer == 3 || g_saberDebugBox.integer == 4) { + G_TestLine(saberStart, saberEnd, 0x0000ff, 50); } #endif } /* if ( dmg ) { - Com_Printf("CL %i SABER DMG: %i, anim %s, torsoTimer %i\n", self->s.number, dmg, animTable[self->client->ps.torsoAnim].name, self->client->ps.torsoTimer ); + Com_Printf("CL %i SABER DMG: %i, anim %s, torsoTimer %i\n", self->s.number, dmg, animTable[self->client->ps.torsoAnim].name, + self->client->ps.torsoTimer ); } */ - if ( self->client->ps.torsoAnim == BOTH_A1_SPECIAL - || self->client->ps.torsoAnim == BOTH_A2_SPECIAL - || self->client->ps.torsoAnim == BOTH_A3_SPECIAL ) - {//parry/block/break-parry bonus for single-style kata moves + if (self->client->ps.torsoAnim == BOTH_A1_SPECIAL || self->client->ps.torsoAnim == BOTH_A2_SPECIAL || + self->client->ps.torsoAnim == BOTH_A3_SPECIAL) { // parry/block/break-parry bonus for single-style kata moves attackStr++; } - if ( BG_SuperBreakWinAnim( self->client->ps.torsoAnim ) ) - { + if (BG_SuperBreakWinAnim(self->client->ps.torsoAnim)) { trMask &= ~CONTENTS_LIGHTSABER; } - } - else - { + } else { dmg = SABER_HITDAMAGE; - if (self->client->ps.fd.saberAnimLevel == SS_STAFF || - self->client->ps.fd.saberAnimLevel == SS_DUAL) - { - if (saberInSpecial) - { - //it will get auto-ramped based on the point in the attack, later on + if (self->client->ps.fd.saberAnimLevel == SS_STAFF || self->client->ps.fd.saberAnimLevel == SS_DUAL) { + if (saberInSpecial) { + // it will get auto-ramped based on the point in the attack, later on if (self->client->ps.saberMove == LS_SPINATTACK || - self->client->ps.saberMove == LS_SPINATTACK_DUAL) - { //these attacks are long and have the potential to hit a lot so they will do less damage. + self->client->ps.saberMove == + LS_SPINATTACK_DUAL) { // these attacks are long and have the potential to hit a lot so they will do less damage. dmg = 10; - } - else - { - if ( BG_KickingAnim( self->client->ps.legsAnim ) || - BG_KickingAnim( self->client->ps.torsoAnim ) ) - { //saber shouldn't do more than min dmg during kicks + } else { + if (BG_KickingAnim(self->client->ps.legsAnim) || + BG_KickingAnim(self->client->ps.torsoAnim)) { // saber shouldn't do more than min dmg during kicks dmg = 2; - } - else if (BG_SaberInKata(self->client->ps.saberMove)) - { //special kata move - if (self->client->ps.fd.saberAnimLevel == SS_DUAL) - { //this is the nasty saber twirl, do big damage cause it makes you vulnerable + } else if (BG_SaberInKata(self->client->ps.saberMove)) { // special kata move + if (self->client->ps.fd.saberAnimLevel == SS_DUAL) { // this is the nasty saber twirl, do big damage cause it makes you vulnerable dmg = 90; - } - else - { //staff kata + } else { // staff kata dmg = G_GetAttackDamage(self, 60, 70, 0.5f); } - } - else - { - //dmg = 90; - //ramp from 2 to 90 by default for other specials + } else { + // dmg = 90; + // ramp from 2 to 90 by default for other specials dmg = G_GetAttackDamage(self, 2, 90, 0.5f); } } - } - else - { //otherwise we'll ramp up to 70 I guess, for both dual and staff + } else { // otherwise we'll ramp up to 70 I guess, for both dual and staff dmg = G_GetAttackDamage(self, 2, 70, 0.5f); } - } - else if (self->client->ps.fd.saberAnimLevel == 3) - { - //new damage-ramping system - if (!saberInSpecial && !inBackAttack) - { + } else if (self->client->ps.fd.saberAnimLevel == 3) { + // new damage-ramping system + if (!saberInSpecial && !inBackAttack) { dmg = G_GetAttackDamage(self, 2, 120, 0.5f); - } - else if (saberInSpecial && - (self->client->ps.saberMove == LS_A_JUMP_T__B_)) - { + } else if (saberInSpecial && (self->client->ps.saberMove == LS_A_JUMP_T__B_)) { dmg = G_GetAttackDamage(self, 2, 180, 0.65f); - } - else if (inBackAttack) - { - dmg = G_GetAttackDamage(self, 2, 30, 0.5f); //can hit multiple times (and almost always does), so.. - } - else - { + } else if (inBackAttack) { + dmg = G_GetAttackDamage(self, 2, 30, 0.5f); // can hit multiple times (and almost always does), so.. + } else { dmg = 100; } - } - else if (self->client->ps.fd.saberAnimLevel == 2) - { - if (saberInSpecial && - (self->client->ps.saberMove == LS_A_FLIP_STAB || self->client->ps.saberMove == LS_A_FLIP_SLASH)) - { //a well-timed hit with this can do a full 85 + } else if (self->client->ps.fd.saberAnimLevel == 2) { + if (saberInSpecial && (self->client->ps.saberMove == LS_A_FLIP_STAB || + self->client->ps.saberMove == LS_A_FLIP_SLASH)) { // a well-timed hit with this can do a full 85 dmg = G_GetAttackDamage(self, 2, 80, 0.5f); - } - else if (inBackAttack) - { + } else if (inBackAttack) { dmg = G_GetAttackDamage(self, 2, 25, 0.5f); - } - else - { + } else { dmg = 60; } - } - else if (self->client->ps.fd.saberAnimLevel == 1) - { - if (saberInSpecial && - (self->client->ps.saberMove == LS_A_LUNGE)) - { - dmg = G_GetAttackDamage(self, 2, SABER_HITDAMAGE-5, 0.3f); - } - else if (inBackAttack) - { + } else if (self->client->ps.fd.saberAnimLevel == 1) { + if (saberInSpecial && (self->client->ps.saberMove == LS_A_LUNGE)) { + dmg = G_GetAttackDamage(self, 2, SABER_HITDAMAGE - 5, 0.3f); + } else if (inBackAttack) { dmg = G_GetAttackDamage(self, 2, 30, 0.5f); - } - else - { + } else { dmg = SABER_HITDAMAGE; } } attackStr = self->client->ps.fd.saberAnimLevel; } - } - else if (self->client->ps.saberAttackWound < level.time && - self->client->ps.saberIdleWound < level.time) - { //just touching, do minimal damage and only check for it every 200ms (mainly to cut down on network traffic for hit events) - if ( (self->client->saber[0].saberFlags2&SFL2_NO_IDLE_EFFECT) ) - {//no idle damage or effects - return qtrue;//true cause even though we didn't get a hit, we don't want to do those extra traces because the debounce time says not to. + } else if (self->client->ps.saberAttackWound < level.time && + self->client->ps.saberIdleWound < + level.time) { // just touching, do minimal damage and only check for it every 200ms (mainly to cut down on network traffic for hit events) + if ((self->client->saber[0].saberFlags2 & SFL2_NO_IDLE_EFFECT)) { // no idle damage or effects + return qtrue; // true cause even though we didn't get a hit, we don't want to do those extra traces because the debounce time says not to. } trMask &= ~CONTENTS_LIGHTSABER; - if ( d_saberSPStyleDamage.integer ) - { - if ( BG_SaberInReturn( self->client->ps.saberMove ) ) - { + if (d_saberSPStyleDamage.integer) { + if (BG_SaberInReturn(self->client->ps.saberMove)) { dmg = SABER_NONATTACK_DAMAGE; - } - else - { - if (d_saberSPStyleDamage.integer == 2) - { + } else { + if (d_saberSPStyleDamage.integer == 2) { dmg = SABER_NONATTACK_DAMAGE; - } - else - { + } else { dmg = 0; } } - } - else - { + } else { dmg = SABER_NONATTACK_DAMAGE; } idleDamage = qtrue; - } - else - { - return qtrue; //true cause even though we didn't get a hit, we don't want to do those extra traces because the debounce time says not to. + } else { + return qtrue; // true cause even though we didn't get a hit, we don't want to do those extra traces because the debounce time says not to. } - if (BG_SaberInSpecial(self->client->ps.saberMove)) - { + if (BG_SaberInSpecial(self->client->ps.saberMove)) { qboolean inBackAttack = G_SaberInBackAttack(self->client->ps.saberMove); unblockable = qtrue; self->client->ps.saberBlocked = 0; - if ( d_saberSPStyleDamage.integer ) - { - } - else if (!inBackAttack) - { - if (self->client->ps.saberMove == LS_A_JUMP_T__B_) - { //do extra damage for special unblockables - dmg += 5; //This is very tiny, because this move has a huge damage ramp - } - else if (self->client->ps.saberMove == LS_A_FLIP_STAB || self->client->ps.saberMove == LS_A_FLIP_SLASH) - { - dmg += 5; //ditto - if (dmg <= 40 || G_GetAnimPoint(self) <= 0.4f) - { //sort of a hack, don't want it doing big damage in the off points of the anim + if (d_saberSPStyleDamage.integer) { + } else if (!inBackAttack) { + if (self->client->ps.saberMove == LS_A_JUMP_T__B_) { // do extra damage for special unblockables + dmg += 5; // This is very tiny, because this move has a huge damage ramp + } else if (self->client->ps.saberMove == LS_A_FLIP_STAB || self->client->ps.saberMove == LS_A_FLIP_SLASH) { + dmg += 5; // ditto + if (dmg <= 40 || G_GetAnimPoint(self) <= 0.4f) { // sort of a hack, don't want it doing big damage in the off points of the anim dmg = 2; } - } - else if (self->client->ps.saberMove == LS_A_LUNGE) - { - dmg += 2; //and ditto again - if (G_GetAnimPoint(self) <= 0.4f) - { //same as above + } else if (self->client->ps.saberMove == LS_A_LUNGE) { + dmg += 2; // and ditto again + if (G_GetAnimPoint(self) <= 0.4f) { // same as above dmg = 2; } - } - else if (self->client->ps.saberMove == LS_SPINATTACK || - self->client->ps.saberMove == LS_SPINATTACK_DUAL) - { //do a constant significant amount of damage but ramp up a little to the mid-point - dmg = G_GetAttackDamage(self, 2, dmg+3, 0.5f); + } else if (self->client->ps.saberMove == LS_SPINATTACK || + self->client->ps.saberMove == LS_SPINATTACK_DUAL) { // do a constant significant amount of damage but ramp up a little to the mid-point + dmg = G_GetAttackDamage(self, 2, dmg + 3, 0.5f); dmg += 10; - } - else - { - //dmg += 20; - if ( BG_KickingAnim( self->client->ps.legsAnim ) || - BG_KickingAnim( self->client->ps.torsoAnim ) ) - { //saber shouldn't do more than min dmg during kicks + } else { + // dmg += 20; + if (BG_KickingAnim(self->client->ps.legsAnim) || + BG_KickingAnim(self->client->ps.torsoAnim)) { // saber shouldn't do more than min dmg during kicks dmg = 2; - } - else - { //auto-ramp it I guess since it's a special we don't have a special case for. - dmg = G_GetAttackDamage(self, 5, dmg+5, 0.5f); + } else { // auto-ramp it I guess since it's a special we don't have a special case for. + dmg = G_GetAttackDamage(self, 5, dmg + 5, 0.5f); } } } } - if (!dmg) - { - if (tr.entityNum < MAX_CLIENTS || - (g_entities[tr.entityNum].inuse && (g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER))) - { + if (!dmg) { + if (tr.entityNum < MAX_CLIENTS || (g_entities[tr.entityNum].inuse && (g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER))) { return qtrue; } return qfalse; } - if (dmg > SABER_NONATTACK_DAMAGE) - { + if (dmg > SABER_NONATTACK_DAMAGE) { dmg *= g_saberDamageScale.value; - //see if this specific saber has a damagescale - if ( !WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && self->client->saber[rSaberNum].damageScale != 1.0f ) - { - dmg = ceil( (float)dmg*self->client->saber[rSaberNum].damageScale ); - } - else if ( WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && self->client->saber[rSaberNum].damageScale2 != 1.0f ) - { - dmg = ceil( (float)dmg*self->client->saber[rSaberNum].damageScale2 ); + // see if this specific saber has a damagescale + if (!WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && self->client->saber[rSaberNum].damageScale != 1.0f) { + dmg = ceil((float)dmg * self->client->saber[rSaberNum].damageScale); + } else if (WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && self->client->saber[rSaberNum].damageScale2 != 1.0f) { + dmg = ceil((float)dmg * self->client->saber[rSaberNum].damageScale2); } if ((self->client->ps.brokenLimbs & (1 << BROKENLIMB_RARM)) || - (self->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) - { //weaken it if an arm is broken + (self->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) { // weaken it if an arm is broken dmg *= 0.3; - if (dmg <= SABER_NONATTACK_DAMAGE) - { - dmg = SABER_NONATTACK_DAMAGE+1; + if (dmg <= SABER_NONATTACK_DAMAGE) { + dmg = SABER_NONATTACK_DAMAGE + 1; } } } - if (dmg > SABER_NONATTACK_DAMAGE && self->client->ps.isJediMaster) - { //give the Jedi Master more saber attack power + if (dmg > SABER_NONATTACK_DAMAGE && self->client->ps.isJediMaster) { // give the Jedi Master more saber attack power dmg *= 2; } - if (dmg > SABER_NONATTACK_DAMAGE && level.gametype == GT_SIEGE && - self->client->siegeClass != -1 && (bgSiegeClasses[self->client->siegeClass].classflags & (1< SABER_NONATTACK_DAMAGE && level.gametype == GT_SIEGE && self->client->siegeClass != -1 && + (bgSiegeClasses[self->client->siegeClass].classflags & + (1 << CFL_MORESABERDMG))) { // this class is flagged to do extra saber damage. I guess 2x will do for now. dmg *= 2; } if (level.gametype == GT_POWERDUEL && - self->client->sess.duelTeam == DUELTEAM_LONE) - { //always x2 when we're powerdueling alone... er, so, we apparently no longer want this? So they say. - if ( duel_fraglimit.integer ) - { - //dmg *= 1.5 - (.4 * (float)self->client->sess.wins / (float)duel_fraglimit.integer); - + self->client->sess.duelTeam == DUELTEAM_LONE) { // always x2 when we're powerdueling alone... er, so, we apparently no longer want this? So they say. + if (duel_fraglimit.integer) { + // dmg *= 1.5 - (.4 * (float)self->client->sess.wins / (float)duel_fraglimit.integer); } - //dmg *= 2; + // dmg *= 2; } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer > 2 && dmg > 1) - { + if (g_saberDebugPrint.integer > 2 && dmg > 1) { Com_Printf("CL %i SABER DMG: %i\n", self->s.number, dmg); } #endif @@ -4432,19 +3523,15 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl VectorSubtract(saberEnd, saberStart, dir); VectorNormalize(dir); - if (tr.entityNum == ENTITYNUM_WORLD || - g_entities[tr.entityNum].s.eType == ET_TERRAIN) - { //register this as a wall hit for jedi AI - self->client->ps.saberEventFlags |= SEF_HITWALL; + if (tr.entityNum == ENTITYNUM_WORLD || g_entities[tr.entityNum].s.eType == ET_TERRAIN) { // register this as a wall hit for jedi AI + self->client->ps.saberEventFlags |= SEF_HITWALL; saberHitWall = qtrue; } - if (saberHitWall - && (self->client->saber[rSaberNum].saberFlags & SFL_BOUNCE_ON_WALLS) - && (BG_SaberInAttackPure( self->client->ps.saberMove ) //only in a normal attack anim - || self->client->ps.saberMove == LS_A_JUMP_T__B_ ) //or in the strong jump-fwd-attack "death from above" move - ) - { //then bounce off + if (saberHitWall && (self->client->saber[rSaberNum].saberFlags & SFL_BOUNCE_ON_WALLS) && + (BG_SaberInAttackPure(self->client->ps.saberMove) // only in a normal attack anim + || self->client->ps.saberMove == LS_A_JUMP_T__B_) // or in the strong jump-fwd-attack "death from above" move + ) { // then bounce off /* qboolean onlyIfNotSpecial = qfalse; qboolean skipIt = qfalse; @@ -4480,121 +3567,93 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl self->client->ps.saberMove = BG_BrokenParryForAttack(self->client->ps.saberMove); self->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; - if (self->client->ps.torsoAnim == self->client->ps.legsAnim) - { //set anim now on both parts + if (self->client->ps.torsoAnim == self->client->ps.legsAnim) { // set anim now on both parts int anim = saberMoveData[self->client->ps.saberMove].animToUse; - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); } - //do bounce sound & force feedback - WP_SaberBounceSound( self, rSaberNum, rBladeNum ); - //do hit effect - te = G_TempEntity( tr.endpos, EV_SABER_HIT ); - te->s.otherEntityNum = ENTITYNUM_NONE;//we didn't hit anyone in particular - te->s.otherEntityNum2 = self->s.number;//send this so it knows who we are + // do bounce sound & force feedback + WP_SaberBounceSound(self, rSaberNum, rBladeNum); + // do hit effect + te = G_TempEntity(tr.endpos, EV_SABER_HIT); + te->s.otherEntityNum = ENTITYNUM_NONE; // we didn't hit anyone in particular + te->s.otherEntityNum2 = self->s.number; // send this so it knows who we are te->s.weapon = rSaberNum; te->s.legsAnim = rBladeNum; VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { //don't let it play with no direction + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { // don't let it play with no direction te->s.angles[1] = 1; } - //do radius damage/knockback, if any - if ( !WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) ) - { - WP_SaberRadiusDamage( self, tr.endpos, self->client->saber[rSaberNum].splashRadius, self->client->saber[rSaberNum].splashDamage, self->client->saber[rSaberNum].splashKnockback ); - } - else - { - WP_SaberRadiusDamage( self, tr.endpos, self->client->saber[rSaberNum].splashRadius2, self->client->saber[rSaberNum].splashDamage2, self->client->saber[rSaberNum].splashKnockback2 ); + // do radius damage/knockback, if any + if (!WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum)) { + WP_SaberRadiusDamage(self, tr.endpos, self->client->saber[rSaberNum].splashRadius, self->client->saber[rSaberNum].splashDamage, + self->client->saber[rSaberNum].splashKnockback); + } else { + WP_SaberRadiusDamage(self, tr.endpos, self->client->saber[rSaberNum].splashRadius2, self->client->saber[rSaberNum].splashDamage2, + self->client->saber[rSaberNum].splashKnockback2); } return qtrue; } } - //rww - I'm saying || tr.startsolid here, because otherwise your saber tends to skip positions and go through - //people, and the compensation traces start in their bbox too. Which results in the saber passing through people - //when you visually cut right through them. Which sucks. + // rww - I'm saying || tr.startsolid here, because otherwise your saber tends to skip positions and go through + // people, and the compensation traces start in their bbox too. Which results in the saber passing through people + // when you visually cut right through them. Which sucks. - if ((tr.fraction != 1 || tr.startsolid) && - g_entities[tr.entityNum].takedamage && - (g_entities[tr.entityNum].health > 0 || !(g_entities[tr.entityNum].s.eFlags & EF_DISINTEGRATION)) && - tr.entityNum != self->s.number && - g_entities[tr.entityNum].inuse) - {//hit something that had health and takes damage - if (idleDamage && - g_entities[tr.entityNum].client && - OnSameTeam(self, &g_entities[tr.entityNum]) && - !g_friendlySaber.integer) - { + if ((tr.fraction != 1 || tr.startsolid) && g_entities[tr.entityNum].takedamage && + (g_entities[tr.entityNum].health > 0 || !(g_entities[tr.entityNum].s.eFlags & EF_DISINTEGRATION)) && tr.entityNum != self->s.number && + g_entities[tr.entityNum].inuse) { // hit something that had health and takes damage + if (idleDamage && g_entities[tr.entityNum].client && OnSameTeam(self, &g_entities[tr.entityNum]) && !g_friendlySaber.integer) { return qfalse; } - if (g_entities[tr.entityNum].client && - g_entities[tr.entityNum].client->ps.duelInProgress && - g_entities[tr.entityNum].client->ps.duelIndex != self->s.number) - { + if (g_entities[tr.entityNum].client && g_entities[tr.entityNum].client->ps.duelInProgress && + g_entities[tr.entityNum].client->ps.duelIndex != self->s.number) { return qfalse; } - if (g_entities[tr.entityNum].client && - self->client->ps.duelInProgress && - self->client->ps.duelIndex != g_entities[tr.entityNum].s.number) - { + if (g_entities[tr.entityNum].client && self->client->ps.duelInProgress && self->client->ps.duelIndex != g_entities[tr.entityNum].s.number) { return qfalse; } - if ( BG_StabDownAnim( self->client->ps.torsoAnim ) - && g_entities[tr.entityNum].client - && !BG_InKnockDownOnGround( &g_entities[tr.entityNum].client->ps ) ) - {//stabdowns only damage people who are actually on the ground... + if (BG_StabDownAnim(self->client->ps.torsoAnim) && g_entities[tr.entityNum].client && + !BG_InKnockDownOnGround(&g_entities[tr.entityNum].client->ps)) { // stabdowns only damage people who are actually on the ground... return qfalse; } self->client->ps.saberIdleWound = level.time + g_saberDmgDelay_Idle.integer; didHit = qtrue; - if ( !d_saberSPStyleDamage.integer//let's trying making blocks have to be blocked by a saber - && g_entities[tr.entityNum].client - && !unblockable - && WP_SaberCanBlock(&g_entities[tr.entityNum], tr.endpos, 0, MOD_SABER, qfalse, attackStr)) - {//hit a client who blocked the attack (fake: didn't actually hit their saber) - if (dmg <= SABER_NONATTACK_DAMAGE) - { + if (!d_saberSPStyleDamage.integer // let's trying making blocks have to be blocked by a saber + && g_entities[tr.entityNum].client && !unblockable && + WP_SaberCanBlock(&g_entities[tr.entityNum], tr.endpos, 0, MOD_SABER, qfalse, + attackStr)) { // hit a client who blocked the attack (fake: didn't actually hit their saber) + if (dmg <= SABER_NONATTACK_DAMAGE) { self->client->ps.saberIdleWound = level.time + g_saberDmgDelay_Idle.integer; } saberDoClashEffect = qtrue; - VectorCopy( tr.endpos, saberClashPos ); - VectorCopy( tr.plane.normal, saberClashNorm ); + VectorCopy(tr.endpos, saberClashPos); + VectorCopy(tr.plane.normal, saberClashNorm); saberClashEventParm = 1; - if (dmg > SABER_NONATTACK_DAMAGE) - { + if (dmg > SABER_NONATTACK_DAMAGE) { int lockFactor = g_saberLockFactor.integer; if ((g_entities[tr.entityNum].client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] - self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) > 1 && - Q_irand(1, 10) < lockFactor*2) - { //Just got blocked by someone with a decently higher attack level, so enter into a lock (where they have the advantage due to a higher attack lev) - if (!G_ClientIdleInWorld(&g_entities[tr.entityNum])) - { - if ( (trMask&CONTENTS_LIGHTSABER) - && WP_SabersCheckLock(self, &g_entities[tr.entityNum])) - { + Q_irand(1, 10) < lockFactor * 2) { // Just got blocked by someone with a decently higher attack level, so enter into a lock (where they have + // the advantage due to a higher attack lev) + if (!G_ClientIdleInWorld(&g_entities[tr.entityNum])) { + if ((trMask & CONTENTS_LIGHTSABER) && WP_SabersCheckLock(self, &g_entities[tr.entityNum])) { self->client->ps.saberBlocked = BLOCKED_NONE; g_entities[tr.entityNum].client->ps.saberBlocked = BLOCKED_NONE; return didHit; } } - } - else if (Q_irand(1, 20) < lockFactor) - { - if (!G_ClientIdleInWorld(&g_entities[tr.entityNum])) - { - if ((trMask&CONTENTS_LIGHTSABER) - && WP_SabersCheckLock(self, &g_entities[tr.entityNum])) - { + } else if (Q_irand(1, 20) < lockFactor) { + if (!G_ClientIdleInWorld(&g_entities[tr.entityNum])) { + if ((trMask & CONTENTS_LIGHTSABER) && WP_SabersCheckLock(self, &g_entities[tr.entityNum])) { self->client->ps.saberBlocked = BLOCKED_NONE; g_entities[tr.entityNum].client->ps.saberBlocked = BLOCKED_NONE; return didHit; @@ -4604,16 +3663,12 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } otherOwner = &g_entities[tr.entityNum]; goto blockStuff; - } - else - {//damage the thing we hit + } else { // damage the thing we hit qboolean doDismemberment = qfalse; - int knockbackFlags = 0; + int knockbackFlags = 0; - if (g_entities[tr.entityNum].client) - { //not a "jedi", so make them suffer more - if ( dmg > SABER_NONATTACK_DAMAGE ) - { //don't bother increasing just for idle touch damage + if (g_entities[tr.entityNum].client) { // not a "jedi", so make them suffer more + if (dmg > SABER_NONATTACK_DAMAGE) { // don't bother increasing just for idle touch damage dmg *= 1.5; } } @@ -4628,20 +3683,15 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } */ - if ( !d_saberSPStyleDamage.integer ) - { - if (g_entities[tr.entityNum].client && g_entities[tr.entityNum].client->ps.weapon == WP_SABER) - { //for jedi using the saber, half the damage (this comes with the increased default dmg debounce time) - if (level.gametype != GT_SIEGE) - { //unless siege.. - if (dmg > SABER_NONATTACK_DAMAGE && !unblockable) - { //don't reduce damage if it's only 1, or if this is an unblockable attack - if (dmg == SABER_HITDAMAGE) - { //level 1 attack + if (!d_saberSPStyleDamage.integer) { + if (g_entities[tr.entityNum].client && + g_entities[tr.entityNum].client->ps.weapon == + WP_SABER) { // for jedi using the saber, half the damage (this comes with the increased default dmg debounce time) + if (level.gametype != GT_SIEGE) { // unless siege.. + if (dmg > SABER_NONATTACK_DAMAGE && !unblockable) { // don't reduce damage if it's only 1, or if this is an unblockable attack + if (dmg == SABER_HITDAMAGE) { // level 1 attack dmg *= 0.7; - } - else - { + } else { dmg *= 0.5; } } @@ -4649,200 +3699,144 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } } - if (self->s.eType == ET_NPC && - g_entities[tr.entityNum].client && - self->client->playerTeam == g_entities[tr.entityNum].client->playerTeam) - { //Oops. Since he's an NPC, we'll be forgiving and cut the damage down. + if (self->s.eType == ET_NPC && g_entities[tr.entityNum].client && + self->client->playerTeam == + g_entities[tr.entityNum].client->playerTeam) { // Oops. Since he's an NPC, we'll be forgiving and cut the damage down. dmg *= 0.2f; } - //store the damage, we'll apply it later - if ( !WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && !(self->client->saber[rSaberNum].saberFlags2&SFL2_NO_DISMEMBERMENT) ) - { + // store the damage, we'll apply it later + if (!WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && + !(self->client->saber[rSaberNum].saberFlags2 & SFL2_NO_DISMEMBERMENT)) { doDismemberment = qtrue; } - if ( WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && !(self->client->saber[rSaberNum].saberFlags2&SFL2_NO_DISMEMBERMENT) ) - { + if (WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && + !(self->client->saber[rSaberNum].saberFlags2 & SFL2_NO_DISMEMBERMENT)) { doDismemberment = qtrue; } - if ( !WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && self->client->saber[rSaberNum].knockbackScale > 0.0f ) - { - if ( rSaberNum < 1 ) - { + if (!WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && self->client->saber[rSaberNum].knockbackScale > 0.0f) { + if (rSaberNum < 1) { knockbackFlags = DAMAGE_SABER_KNOCKBACK1; - } - else - { + } else { knockbackFlags = DAMAGE_SABER_KNOCKBACK2; } } - if ( WP_SaberBladeUseSecondBladeStyle( &self->client->saber[rSaberNum], rBladeNum ) - && self->client->saber[rSaberNum].knockbackScale > 0.0f ) - { - if ( rSaberNum < 1 ) - { + if (WP_SaberBladeUseSecondBladeStyle(&self->client->saber[rSaberNum], rBladeNum) && self->client->saber[rSaberNum].knockbackScale > 0.0f) { + if (rSaberNum < 1) { knockbackFlags = DAMAGE_SABER_KNOCKBACK1_B2; - } - else - { + } else { knockbackFlags = DAMAGE_SABER_KNOCKBACK2_B2; } } - WP_SaberDamageAdd( tr.entityNum, dir, tr.endpos, dmg, doDismemberment, knockbackFlags ); + WP_SaberDamageAdd(tr.entityNum, dir, tr.endpos, dmg, doDismemberment, knockbackFlags); - if (g_entities[tr.entityNum].client) - { - //Let jedi AI know if it hit an enemy - if ( self->enemy && self->enemy == &g_entities[tr.entityNum] ) - { + if (g_entities[tr.entityNum].client) { + // Let jedi AI know if it hit an enemy + if (self->enemy && self->enemy == &g_entities[tr.entityNum]) { self->client->ps.saberEventFlags |= SEF_HITENEMY; - } - else - { - self->client->ps.saberEventFlags |= SEF_HITOBJECT; + } else { + self->client->ps.saberEventFlags |= SEF_HITOBJECT; } } - if ( d_saberSPStyleDamage.integer ) - { - } - else - { + if (d_saberSPStyleDamage.integer) { + } else { self->client->ps.saberAttackWound = level.time + 100; } } - } - else if ((tr.fraction != 1 || tr.startsolid) && - (g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER) && - g_entities[tr.entityNum].r.contents != -1 && - g_entities[tr.entityNum].inuse) - { //saber clash + } else if ((tr.fraction != 1 || tr.startsolid) && (g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER) && + g_entities[tr.entityNum].r.contents != -1 && g_entities[tr.entityNum].inuse) { // saber clash otherOwner = &g_entities[g_entities[tr.entityNum].r.ownerNum]; - if (!otherOwner->inuse || !otherOwner->client) - { + if (!otherOwner->inuse || !otherOwner->client) { return qfalse; } - if ( otherOwner - && otherOwner->client - && otherOwner->client->ps.saberInFlight ) - {//don't do extra collision checking vs sabers in air - } - else - {//hit an in-hand saber, do extra collision check against it - if ( d_saberSPStyleDamage.integer ) - {//use SP-style blade-collision test - if ( !WP_SabersIntersect( self, rSaberNum, rBladeNum, otherOwner, qfalse ) ) - {//sabers did not actually intersect + if (otherOwner && otherOwner->client && otherOwner->client->ps.saberInFlight) { // don't do extra collision checking vs sabers in air + } else { // hit an in-hand saber, do extra collision check against it + if (d_saberSPStyleDamage.integer) { // use SP-style blade-collision test + if (!WP_SabersIntersect(self, rSaberNum, rBladeNum, otherOwner, qfalse)) { // sabers did not actually intersect return qfalse; } - } - else - {//MP-style - if (!G_SaberCollide(self, otherOwner, lastValidStart, - lastValidEnd, saberTrMins, saberTrMaxs, tr.endpos)) - { //detailed collision did not produce results... + } else { // MP-style + if (!G_SaberCollide(self, otherOwner, lastValidStart, lastValidEnd, saberTrMins, saberTrMaxs, + tr.endpos)) { // detailed collision did not produce results... return qfalse; } } } - if (OnSameTeam(self, otherOwner) && - !g_friendlySaber.integer) - { + if (OnSameTeam(self, otherOwner) && !g_friendlySaber.integer) { return qfalse; } - if ((self->s.eType == ET_NPC || otherOwner->s.eType == ET_NPC) && //just make sure one of us is an npc + if ((self->s.eType == ET_NPC || otherOwner->s.eType == ET_NPC) && // just make sure one of us is an npc self->client->playerTeam == otherOwner->client->playerTeam && - level.gametype != GT_SIEGE) - { //don't hit your teammate's sabers if you are an NPC. It can be rather annoying. + level.gametype != GT_SIEGE) { // don't hit your teammate's sabers if you are an NPC. It can be rather annoying. return qfalse; } - if (otherOwner->client->ps.duelInProgress && - otherOwner->client->ps.duelIndex != self->s.number) - { + if (otherOwner->client->ps.duelInProgress && otherOwner->client->ps.duelIndex != self->s.number) { return qfalse; } - if (self->client->ps.duelInProgress && - self->client->ps.duelIndex != otherOwner->s.number) - { + if (self->client->ps.duelInProgress && self->client->ps.duelIndex != otherOwner->s.number) { return qfalse; } - if ( g_debugSaberLocks.integer ) - { - WP_SabersCheckLock2( self, otherOwner, LOCK_RANDOM ); + if (g_debugSaberLocks.integer) { + WP_SabersCheckLock2(self, otherOwner, LOCK_RANDOM); return qtrue; } didHit = qtrue; self->client->ps.saberIdleWound = level.time + g_saberDmgDelay_Idle.integer; - if (dmg <= SABER_NONATTACK_DAMAGE) - { + if (dmg <= SABER_NONATTACK_DAMAGE) { self->client->ps.saberIdleWound = level.time + g_saberDmgDelay_Idle.integer; } saberDoClashEffect = qtrue; - VectorCopy( tr.endpos, saberClashPos ); - VectorCopy( tr.plane.normal, saberClashNorm ); + VectorCopy(tr.endpos, saberClashPos); + VectorCopy(tr.plane.normal, saberClashNorm); saberClashEventParm = 1; sabersClashed = qtrue; saberHitSaber = qtrue; saberHitFraction = tr.fraction; - if (saberCheckKnockdown_Smashed(&g_entities[tr.entityNum], otherOwner, self, dmg)) - { //smashed it out of the air + if (saberCheckKnockdown_Smashed(&g_entities[tr.entityNum], otherOwner, self, dmg)) { // smashed it out of the air return qfalse; } - //is this my thrown saber? - if ( self->client->ps.saberEntityNum - && self->client->ps.saberInFlight - && rSaberNum == 0 - && saberCheckKnockdown_Smashed( &g_entities[self->client->ps.saberEntityNum], self, otherOwner, dmg)) - { //they smashed it out of the air + // is this my thrown saber? + if (self->client->ps.saberEntityNum && self->client->ps.saberInFlight && rSaberNum == 0 && + saberCheckKnockdown_Smashed(&g_entities[self->client->ps.saberEntityNum], self, otherOwner, dmg)) { // they smashed it out of the air return qfalse; } -blockStuff: + blockStuff: otherUnblockable = qfalse; - if (otherOwner && otherOwner->client && otherOwner->client->ps.saberInFlight) - { + if (otherOwner && otherOwner->client && otherOwner->client->ps.saberInFlight) { return qfalse; } - //this is a thrown saber, don't do any fancy saber-saber collision stuff - if ( self->client->ps.saberEntityNum - && self->client->ps.saberInFlight - && rSaberNum == 0 ) - { + // this is a thrown saber, don't do any fancy saber-saber collision stuff + if (self->client->ps.saberEntityNum && self->client->ps.saberInFlight && rSaberNum == 0) { return qfalse; } otherSaberLevel = G_SaberAttackPower(otherOwner, SaberAttacking(otherOwner)); - if (dmg > SABER_NONATTACK_DAMAGE && !unblockable && !otherUnblockable) - { + if (dmg > SABER_NONATTACK_DAMAGE && !unblockable && !otherUnblockable) { int lockFactor = g_saberLockFactor.integer; - if (sabersClashed && Q_irand(1, 20) <= lockFactor) - { - if (!G_ClientIdleInWorld(otherOwner)) - { - if (WP_SabersCheckLock(self, otherOwner)) - { + if (sabersClashed && Q_irand(1, 20) <= lockFactor) { + if (!G_ClientIdleInWorld(otherOwner)) { + if (WP_SabersCheckLock(self, otherOwner)) { self->client->ps.saberBlocked = BLOCKED_NONE; otherOwner->client->ps.saberBlocked = BLOCKED_NONE; return didHit; @@ -4851,221 +3845,168 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } } - if (!otherOwner || !otherOwner->client) - { + if (!otherOwner || !otherOwner->client) { return didHit; } - if (BG_SaberInSpecial(otherOwner->client->ps.saberMove)) - { + if (BG_SaberInSpecial(otherOwner->client->ps.saberMove)) { otherUnblockable = qtrue; otherOwner->client->ps.saberBlocked = 0; } - if ( sabersClashed && - dmg > SABER_NONATTACK_DAMAGE && - selfSaberLevel < FORCE_LEVEL_3 && - !PM_SaberInBounce(otherOwner->client->ps.saberMove) && - !PM_SaberInParry(self->client->ps.saberMove) && - !PM_SaberInBrokenParry(self->client->ps.saberMove) && - !BG_SaberInSpecial(self->client->ps.saberMove) && - !PM_SaberInBounce(self->client->ps.saberMove) && - !PM_SaberInDeflect(self->client->ps.saberMove) && - !PM_SaberInReflect(self->client->ps.saberMove) && - !unblockable ) - { - //if (Q_irand(1, 10) <= 6) - if (1) //for now, just always try a deflect. (deflect func can cause bounces too) + if (sabersClashed && dmg > SABER_NONATTACK_DAMAGE && selfSaberLevel < FORCE_LEVEL_3 && !PM_SaberInBounce(otherOwner->client->ps.saberMove) && + !PM_SaberInParry(self->client->ps.saberMove) && !PM_SaberInBrokenParry(self->client->ps.saberMove) && + !BG_SaberInSpecial(self->client->ps.saberMove) && !PM_SaberInBounce(self->client->ps.saberMove) && !PM_SaberInDeflect(self->client->ps.saberMove) && + !PM_SaberInReflect(self->client->ps.saberMove) && !unblockable) { + // if (Q_irand(1, 10) <= 6) + if (1) // for now, just always try a deflect. (deflect func can cause bounces too) { - if (!WP_GetSaberDeflectionAngle(self, otherOwner, tr.fraction)) - { - tryDeflectAgain = qtrue; //Failed the deflect, try it again if we can if the guy we're smashing goes into a parry and we don't break it - } - else - { + if (!WP_GetSaberDeflectionAngle(self, otherOwner, tr.fraction)) { + tryDeflectAgain = qtrue; // Failed the deflect, try it again if we can if the guy we're smashing goes into a parry and we don't break it + } else { self->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; didOffense = qtrue; } - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; didOffense = qtrue; #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i clashed into client %i's saber, did BLOCKED_ATK_BOUNCE\n", self->s.number, otherOwner->s.number); } #endif } } - if ( ((selfSaberLevel < FORCE_LEVEL_3 && ((tryDeflectAgain && Q_irand(1, 10) <= 3) || (!tryDeflectAgain && Q_irand(1, 10) <= 7))) || (Q_irand(1, 10) <= 1 && otherSaberLevel >= FORCE_LEVEL_3)) - && !PM_SaberInBounce(self->client->ps.saberMove) + if (((selfSaberLevel < FORCE_LEVEL_3 && ((tryDeflectAgain && Q_irand(1, 10) <= 3) || (!tryDeflectAgain && Q_irand(1, 10) <= 7))) || + (Q_irand(1, 10) <= 1 && otherSaberLevel >= FORCE_LEVEL_3)) && + !PM_SaberInBounce(self->client->ps.saberMove) - && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) - && !BG_SaberInSpecial(otherOwner->client->ps.saberMove) - && !PM_SaberInBounce(otherOwner->client->ps.saberMove) - && !PM_SaberInDeflect(otherOwner->client->ps.saberMove) - && !PM_SaberInReflect(otherOwner->client->ps.saberMove) + && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && + !PM_SaberInBounce(otherOwner->client->ps.saberMove) && !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && + !PM_SaberInReflect(otherOwner->client->ps.saberMove) - && (otherSaberLevel > FORCE_LEVEL_2 || ( otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= 3 && Q_irand(0, otherSaberLevel) )) - && !unblockable - && !otherUnblockable - && dmg > SABER_NONATTACK_DAMAGE - && !didOffense) //don't allow the person we're attacking to do this if we're making an unblockable attack - {//knockaways can make fast-attacker go into a broken parry anim if the ent is using fast or med. In MP, we also randomly decide this for level 3 attacks. - //Going to go ahead and let idle damage do simple knockaways. Looks sort of good that way. - //turn the parry into a knockaway - if (self->client->ps.saberEntityNum) //make sure he has his saber still + && (otherSaberLevel > FORCE_LEVEL_2 || (otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] >= 3 && Q_irand(0, otherSaberLevel))) && + !unblockable && !otherUnblockable && dmg > SABER_NONATTACK_DAMAGE && + !didOffense) // don't allow the person we're attacking to do this if we're making an unblockable attack + { // knockaways can make fast-attacker go into a broken parry anim if the ent is using fast or med. In MP, we also randomly decide this for level 3 + // attacks. + // Going to go ahead and let idle damage do simple knockaways. Looks sort of good that way. + // turn the parry into a knockaway + if (self->client->ps.saberEntityNum) // make sure he has his saber still { saberCheckKnockdown_BrokenParry(&g_entities[self->client->ps.saberEntityNum], self, otherOwner); } - if (!PM_SaberInParry(otherOwner->client->ps.saberMove)) - { + if (!PM_SaberInParry(otherOwner->client->ps.saberMove)) { WP_SaberBlockNonRandom(otherOwner, tr.endpos, qfalse); - otherOwner->client->ps.saberMove = BG_KnockawayForParry( otherOwner->client->ps.saberBlocked ); + otherOwner->client->ps.saberMove = BG_KnockawayForParry(otherOwner->client->ps.saberBlocked); otherOwner->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; - } - else - { - otherOwner->client->ps.saberMove = G_KnockawayForParry(otherOwner->client->ps.saberMove); //BG_KnockawayForParry( otherOwner->client->ps.saberBlocked ); + } else { + otherOwner->client->ps.saberMove = + G_KnockawayForParry(otherOwner->client->ps.saberMove); // BG_KnockawayForParry( otherOwner->client->ps.saberBlocked ); otherOwner->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; } - //make them (me) go into a broken parry - self->client->ps.saberMove = BG_BrokenParryForAttack( self->client->ps.saberMove ); + // make them (me) go into a broken parry + self->client->ps.saberMove = BG_BrokenParryForAttack(self->client->ps.saberMove); self->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i sent client %i into a reflected attack with a knockaway\n", otherOwner->s.number, self->s.number); } #endif didDefense = qtrue; - } - else if ((selfSaberLevel > FORCE_LEVEL_2 || unblockable) && //if we're doing a special attack, we can send them into a broken parry too (MP only) - ( otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < selfSaberLevel || (otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == selfSaberLevel && (Q_irand(1, 10) >= otherSaberLevel*1.5 || unblockable)) ) && - PM_SaberInParry(otherOwner->client->ps.saberMove) && - !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && - !PM_SaberInParry(self->client->ps.saberMove) && - !PM_SaberInBrokenParry(self->client->ps.saberMove) && - !PM_SaberInBounce(self->client->ps.saberMove) && - dmg > SABER_NONATTACK_DAMAGE && - !didOffense && - !otherUnblockable) - { //they are in a parry, and we are slamming down on them with a move of equal or greater force than their defense, so send them into a broken parry.. unless they are already in one. - if (otherOwner->client->ps.saberEntityNum) //make sure he has his saber still + } else if ((selfSaberLevel > FORCE_LEVEL_2 || unblockable) && // if we're doing a special attack, we can send them into a broken parry too (MP only) + (otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < selfSaberLevel || + (otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == selfSaberLevel && + (Q_irand(1, 10) >= otherSaberLevel * 1.5 || unblockable))) && + PM_SaberInParry(otherOwner->client->ps.saberMove) && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && + !PM_SaberInParry(self->client->ps.saberMove) && !PM_SaberInBrokenParry(self->client->ps.saberMove) && + !PM_SaberInBounce(self->client->ps.saberMove) && dmg > SABER_NONATTACK_DAMAGE && !didOffense && + !otherUnblockable) { // they are in a parry, and we are slamming down on them with a move of equal or greater force than their defense, so + // send them into a broken parry.. unless they are already in one. + if (otherOwner->client->ps.saberEntityNum) // make sure he has his saber still { saberCheckKnockdown_BrokenParry(&g_entities[otherOwner->client->ps.saberEntityNum], otherOwner, self); } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i sent client %i into a broken parry\n", self->s.number, otherOwner->s.number); } #endif - otherOwner->client->ps.saberMove = BG_BrokenParryForParry( otherOwner->client->ps.saberMove ); + otherOwner->client->ps.saberMove = BG_BrokenParryForParry(otherOwner->client->ps.saberMove); otherOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; didDefense = qtrue; - } - else if ((selfSaberLevel > FORCE_LEVEL_2) && //if we're doing a special attack, we can send them into a broken parry too (MP only) - //( otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < selfSaberLevel || (otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == selfSaberLevel && (Q_irand(1, 10) >= otherSaberLevel*3 || unblockable)) ) && - otherSaberLevel >= FORCE_LEVEL_3 && - PM_SaberInParry(otherOwner->client->ps.saberMove) && - !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && - !PM_SaberInParry(self->client->ps.saberMove) && - !PM_SaberInBrokenParry(self->client->ps.saberMove) && - !PM_SaberInBounce(self->client->ps.saberMove) && - !PM_SaberInDeflect(self->client->ps.saberMove) && - !PM_SaberInReflect(self->client->ps.saberMove) && - dmg > SABER_NONATTACK_DAMAGE && - !didOffense && - !unblockable) - { //they are in a parry, and we are slamming down on them with a move of equal or greater force than their defense, so send them into a broken parry.. unless they are already in one. + } else if ((selfSaberLevel > FORCE_LEVEL_2) && // if we're doing a special attack, we can send them into a broken parry too (MP only) + //( otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] < selfSaberLevel || + //(otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == selfSaberLevel && (Q_irand(1, 10) >= + //otherSaberLevel*3 || unblockable)) ) && + otherSaberLevel >= FORCE_LEVEL_3 && PM_SaberInParry(otherOwner->client->ps.saberMove) && + !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && !PM_SaberInParry(self->client->ps.saberMove) && + !PM_SaberInBrokenParry(self->client->ps.saberMove) && !PM_SaberInBounce(self->client->ps.saberMove) && + !PM_SaberInDeflect(self->client->ps.saberMove) && !PM_SaberInReflect(self->client->ps.saberMove) && dmg > SABER_NONATTACK_DAMAGE && + !didOffense && !unblockable) { // they are in a parry, and we are slamming down on them with a move of equal or greater force than their + // defense, so send them into a broken parry.. unless they are already in one. #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i bounced off of client %i's saber\n", self->s.number, otherOwner->s.number); } #endif - if (!tryDeflectAgain) - { - if (!WP_GetSaberDeflectionAngle(self, otherOwner, tr.fraction)) - { + if (!tryDeflectAgain) { + if (!WP_GetSaberDeflectionAngle(self, otherOwner, tr.fraction)) { tryDeflectAgain = qtrue; } } didOffense = qtrue; - } - else if (SaberAttacking(otherOwner) && dmg > SABER_NONATTACK_DAMAGE && !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && !didOffense && !otherUnblockable) - { //they were attacking and our saber hit their saber, make them bounce. But if they're in a special attack, leave them. - if (!PM_SaberInBounce(self->client->ps.saberMove) && - !PM_SaberInBounce(otherOwner->client->ps.saberMove) && - !PM_SaberInDeflect(self->client->ps.saberMove) && - !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && - - !PM_SaberInReflect(self->client->ps.saberMove) && - !PM_SaberInReflect(otherOwner->client->ps.saberMove)) - { - int attackAdv, defendStr = G_PowerLevelForSaberAnim( otherOwner, 0, qtrue ), attackBonus = 0; - if ( otherOwner->client->ps.torsoAnim == BOTH_A1_SPECIAL - || otherOwner->client->ps.torsoAnim == BOTH_A2_SPECIAL - || otherOwner->client->ps.torsoAnim == BOTH_A3_SPECIAL ) - {//parry/block/break-parry bonus for single-style kata moves + } else if (SaberAttacking(otherOwner) && dmg > SABER_NONATTACK_DAMAGE && !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && !didOffense && + !otherUnblockable) { // they were attacking and our saber hit their saber, make them bounce. But if they're in a special attack, leave them. + if (!PM_SaberInBounce(self->client->ps.saberMove) && !PM_SaberInBounce(otherOwner->client->ps.saberMove) && + !PM_SaberInDeflect(self->client->ps.saberMove) && !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && + + !PM_SaberInReflect(self->client->ps.saberMove) && !PM_SaberInReflect(otherOwner->client->ps.saberMove)) { + int attackAdv, defendStr = G_PowerLevelForSaberAnim(otherOwner, 0, qtrue), attackBonus = 0; + if (otherOwner->client->ps.torsoAnim == BOTH_A1_SPECIAL || otherOwner->client->ps.torsoAnim == BOTH_A2_SPECIAL || + otherOwner->client->ps.torsoAnim == BOTH_A3_SPECIAL) { // parry/block/break-parry bonus for single-style kata moves defendStr++; } - defendStr += Q_irand(0, otherOwner->client->saber[0].parryBonus ); - if ( otherOwner->client->saber[1].model[0] - && !otherOwner->client->ps.saberHolstered ) - { - defendStr += Q_irand(0, otherOwner->client->saber[1].parryBonus ); + defendStr += Q_irand(0, otherOwner->client->saber[0].parryBonus); + if (otherOwner->client->saber[1].model[0] && !otherOwner->client->ps.saberHolstered) { + defendStr += Q_irand(0, otherOwner->client->saber[1].parryBonus); } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i and client %i bounced off of each other's sabers\n", self->s.number, otherOwner->s.number); } #endif - attackBonus = Q_irand(0, self->client->saber[0].breakParryBonus ); - if ( self->client->saber[1].model[0] - && !self->client->ps.saberHolstered ) - { - attackBonus += Q_irand(0, self->client->saber[1].breakParryBonus ); + attackBonus = Q_irand(0, self->client->saber[0].breakParryBonus); + if (self->client->saber[1].model[0] && !self->client->ps.saberHolstered) { + attackBonus += Q_irand(0, self->client->saber[1].breakParryBonus); } - attackAdv = (attackStr+attackBonus+self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE])-(defendStr+otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]); + attackAdv = (attackStr + attackBonus + self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) - + (defendStr + otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]); - if ( attackAdv > 1 ) - {//I won, he should knockaway - otherOwner->client->ps.saberMove = BG_BrokenParryForAttack( otherOwner->client->ps.saberMove ); + if (attackAdv > 1) { // I won, he should knockaway + otherOwner->client->ps.saberMove = BG_BrokenParryForAttack(otherOwner->client->ps.saberMove); otherOwner->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; - } - else if ( attackAdv > 0 ) - {//I won, he should bounce, I should continue + } else if (attackAdv > 0) { // I won, he should bounce, I should continue otherOwner->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; - } - else if ( attackAdv < 1 ) - {//I lost, I get knocked away - self->client->ps.saberMove = BG_BrokenParryForAttack( self->client->ps.saberMove ); + } else if (attackAdv < 1) { // I lost, I get knocked away + self->client->ps.saberMove = BG_BrokenParryForAttack(self->client->ps.saberMove); self->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; - } - else if ( attackAdv < 0 ) - {//I lost, I bounce off + } else if (attackAdv < 0) { // I lost, I bounce off self->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; - } - else - {//even, both bounce off + } else { // even, both bounce off self->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; otherOwner->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; } @@ -5074,41 +4015,29 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } } - if (d_saberGhoul2Collision.integer && !didDefense && dmg <= SABER_NONATTACK_DAMAGE && !otherUnblockable) //with perpoly, it looks pretty weird to have clash flares coming off the guy's face and whatnot + if (d_saberGhoul2Collision.integer && !didDefense && dmg <= SABER_NONATTACK_DAMAGE && + !otherUnblockable) // with perpoly, it looks pretty weird to have clash flares coming off the guy's face and whatnot { - if (!PM_SaberInParry(otherOwner->client->ps.saberMove) && - !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && - !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && - !PM_SaberInBounce(otherOwner->client->ps.saberMove) && - !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && - !PM_SaberInReflect(otherOwner->client->ps.saberMove)) - { + if (!PM_SaberInParry(otherOwner->client->ps.saberMove) && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && + !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && !PM_SaberInBounce(otherOwner->client->ps.saberMove) && + !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && !PM_SaberInReflect(otherOwner->client->ps.saberMove)) { WP_SaberBlockNonRandom(otherOwner, tr.endpos, qfalse); otherOwner->client->ps.saberEventFlags |= SEF_PARRIED; } - } - else if (!didDefense && dmg > SABER_NONATTACK_DAMAGE && !otherUnblockable) //if not more than idle damage, don't even bother blocking. - { //block - if (!PM_SaberInParry(otherOwner->client->ps.saberMove) && - !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && - !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && - !PM_SaberInBounce(otherOwner->client->ps.saberMove) && - !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && - !PM_SaberInReflect(otherOwner->client->ps.saberMove)) - { + } else if (!didDefense && dmg > SABER_NONATTACK_DAMAGE && !otherUnblockable) // if not more than idle damage, don't even bother blocking. + { // block + if (!PM_SaberInParry(otherOwner->client->ps.saberMove) && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && + !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && !PM_SaberInBounce(otherOwner->client->ps.saberMove) && + !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && !PM_SaberInReflect(otherOwner->client->ps.saberMove)) { qboolean crushTheParry = qfalse; - if (unblockable) - { //It's unblockable. So send us into a broken parry immediately. + if (unblockable) { // It's unblockable. So send us into a broken parry immediately. crushTheParry = qtrue; } - if (!SaberAttacking(otherOwner)) - { + if (!SaberAttacking(otherOwner)) { int otherIdleStr = otherOwner->client->ps.fd.saberAnimLevel; - if ( otherIdleStr == SS_DUAL - || otherIdleStr == SS_STAFF ) - { + if (otherIdleStr == SS_DUAL || otherIdleStr == SS_STAFF) { otherIdleStr = SS_MEDIUM; } @@ -5116,85 +4045,62 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl otherOwner->client->ps.saberEventFlags |= SEF_PARRIED; self->client->ps.saberEventFlags |= SEF_BLOCKED; - if ( attackStr+self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > otherIdleStr+otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] ) - { + if (attackStr + self->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE] > + otherIdleStr + otherOwner->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]) { crushTheParry = qtrue; - } - else - { + } else { tryDeflectAgain = qtrue; } - } - else if (selfSaberLevel > otherSaberLevel || - (selfSaberLevel == otherSaberLevel && Q_irand(1, 10) <= 2)) - { //they are attacking, and we managed to make them break - //Give them a parry, so we can later break it. + } else if (selfSaberLevel > otherSaberLevel || + (selfSaberLevel == otherSaberLevel && Q_irand(1, 10) <= 2)) { // they are attacking, and we managed to make them break + // Give them a parry, so we can later break it. WP_SaberBlockNonRandom(otherOwner, tr.endpos, qfalse); crushTheParry = qtrue; - if (otherOwner->client->ps.saberEntityNum) //make sure he has his saber still + if (otherOwner->client->ps.saberEntityNum) // make sure he has his saber still { saberCheckKnockdown_BrokenParry(&g_entities[otherOwner->client->ps.saberEntityNum], otherOwner, self); } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i forced client %i into a broken parry with a stronger attack\n", self->s.number, otherOwner->s.number); } #endif - } - else - { //They are attacking, so are we, and obviously they have an attack level higher than or equal to ours - if (selfSaberLevel == otherSaberLevel) - { //equal level, try to bounce off each other's sabers - if (!didOffense && - !PM_SaberInParry(self->client->ps.saberMove) && - !PM_SaberInBrokenParry(self->client->ps.saberMove) && - !BG_SaberInSpecial(self->client->ps.saberMove) && - !PM_SaberInBounce(self->client->ps.saberMove) && - !PM_SaberInDeflect(self->client->ps.saberMove) && - !PM_SaberInReflect(self->client->ps.saberMove) && - !unblockable) - { + } else { // They are attacking, so are we, and obviously they have an attack level higher than or equal to ours + if (selfSaberLevel == otherSaberLevel) { // equal level, try to bounce off each other's sabers + if (!didOffense && !PM_SaberInParry(self->client->ps.saberMove) && !PM_SaberInBrokenParry(self->client->ps.saberMove) && + !BG_SaberInSpecial(self->client->ps.saberMove) && !PM_SaberInBounce(self->client->ps.saberMove) && + !PM_SaberInDeflect(self->client->ps.saberMove) && !PM_SaberInReflect(self->client->ps.saberMove) && !unblockable) { self->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; didOffense = qtrue; } - if (!didDefense && - !PM_SaberInParry(otherOwner->client->ps.saberMove) && - !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && - !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && - !PM_SaberInBounce(otherOwner->client->ps.saberMove) && - !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && - !PM_SaberInReflect(otherOwner->client->ps.saberMove) && - !unblockable) - { + if (!didDefense && !PM_SaberInParry(otherOwner->client->ps.saberMove) && !PM_SaberInBrokenParry(otherOwner->client->ps.saberMove) && + !BG_SaberInSpecial(otherOwner->client->ps.saberMove) && !PM_SaberInBounce(otherOwner->client->ps.saberMove) && + !PM_SaberInDeflect(otherOwner->client->ps.saberMove) && !PM_SaberInReflect(otherOwner->client->ps.saberMove) && !unblockable) { otherOwner->client->ps.saberBlocked = BLOCKED_ATK_BOUNCE; } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Equal attack level bounce/deflection for clients %i and %i\n", self->s.number, otherOwner->s.number); } #endif self->client->ps.saberEventFlags |= SEF_DEFLECTED; otherOwner->client->ps.saberEventFlags |= SEF_DEFLECTED; - } - else if ((level.time - otherOwner->client->lastSaberStorageTime) < 500 && !unblockable) //make sure the stored saber data is updated - { //They are higher, this means they can actually smash us into a broken parry - //Using reflected anims instead now + } else if ((level.time - otherOwner->client->lastSaberStorageTime) < 500 && !unblockable) // make sure the stored saber data is updated + { // They are higher, this means they can actually smash us into a broken parry + // Using reflected anims instead now self->client->ps.saberMove = BG_BrokenParryForAttack(self->client->ps.saberMove); self->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; - if (self->client->ps.saberEntityNum) //make sure he has his saber still + if (self->client->ps.saberEntityNum) // make sure he has his saber still { saberCheckKnockdown_BrokenParry(&g_entities[self->client->ps.saberEntityNum], self, otherOwner); } #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i hit client %i's stronger attack, was forced into a broken parry\n", self->s.number, otherOwner->s.number); } #endif @@ -5205,24 +4111,23 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } } - if (crushTheParry && PM_SaberInParry(G_GetParryForBlock(otherOwner->client->ps.saberBlocked))) - { //This means that the attack actually hit our saber, and we went to block it. - //But, one of the above cases says we actually can't. So we will be smashed into a broken parry instead. - otherOwner->client->ps.saberMove = BG_BrokenParryForParry( G_GetParryForBlock(otherOwner->client->ps.saberBlocked) ); + if (crushTheParry && PM_SaberInParry(G_GetParryForBlock( + otherOwner->client->ps.saberBlocked))) { // This means that the attack actually hit our saber, and we went to block it. + // But, one of the above cases says we actually can't. So we will be smashed + // into a broken parry instead. + otherOwner->client->ps.saberMove = BG_BrokenParryForParry(G_GetParryForBlock(otherOwner->client->ps.saberBlocked)); otherOwner->client->ps.saberBlocked = BLOCKED_PARRY_BROKEN; otherOwner->client->ps.saberEventFlags &= ~SEF_PARRIED; self->client->ps.saberEventFlags &= ~SEF_BLOCKED; #ifndef FINAL_BUILD - if (g_saberDebugPrint.integer) - { + if (g_saberDebugPrint.integer) { Com_Printf("Client %i broke through %i's parry with a special or stronger attack\n", self->s.number, otherOwner->s.number); } #endif - } - else if (PM_SaberInParry(G_GetParryForBlock(otherOwner->client->ps.saberBlocked)) && !didOffense && tryDeflectAgain) - { //We want to try deflecting again because the other is in the parry and we haven't made any new moves + } else if (PM_SaberInParry(G_GetParryForBlock(otherOwner->client->ps.saberBlocked)) && !didOffense && + tryDeflectAgain) { // We want to try deflecting again because the other is in the parry and we haven't made any new moves int preMove = otherOwner->client->ps.saberMove; otherOwner->client->ps.saberMove = G_GetParryForBlock(otherOwner->client->ps.saberBlocked); @@ -5239,133 +4144,112 @@ static QINLINE qboolean CheckSaberDamage(gentity_t *self, int rSaberNum, int rBl } #define MAX_SABER_SWING_INC 0.33f -void G_SPSaberDamageTraceLerped( gentity_t *self, int saberNum, int bladeNum, vec3_t baseNew, vec3_t endNew, int clipmask ) -{ +void G_SPSaberDamageTraceLerped(gentity_t *self, int saberNum, int bladeNum, vec3_t baseNew, vec3_t endNew, int clipmask) { vec3_t baseOld, endOld; vec3_t mp1, mp2; vec3_t md1, md2; - if ( (level.time-self->client->saber[saberNum].blade[bladeNum].trail.lastTime) > 100 ) - {//no valid last pos, use current + if ((level.time - self->client->saber[saberNum].blade[bladeNum].trail.lastTime) > 100) { // no valid last pos, use current VectorCopy(baseNew, baseOld); VectorCopy(endNew, endOld); - } - else - {//trace from last pos - VectorCopy( self->client->saber[saberNum].blade[bladeNum].trail.base, baseOld ); - VectorCopy( self->client->saber[saberNum].blade[bladeNum].trail.tip, endOld ); + } else { // trace from last pos + VectorCopy(self->client->saber[saberNum].blade[bladeNum].trail.base, baseOld); + VectorCopy(self->client->saber[saberNum].blade[bladeNum].trail.tip, endOld); } - VectorCopy( baseOld, mp1 ); - VectorCopy( baseNew, mp2 ); - VectorSubtract( endOld, baseOld, md1 ); - VectorNormalize( md1 ); - VectorSubtract( endNew, baseNew, md2 ); - VectorNormalize( md2 ); + VectorCopy(baseOld, mp1); + VectorCopy(baseNew, mp2); + VectorSubtract(endOld, baseOld, md1); + VectorNormalize(md1); + VectorSubtract(endNew, baseNew, md2); + VectorNormalize(md2); saberHitWall = qfalse; saberHitSaber = qfalse; saberHitFraction = 1.0f; - if ( VectorCompare2( baseOld, baseNew ) && VectorCompare2( endOld, endNew ) ) - {//no diff - CheckSaberDamage( self, saberNum, bladeNum, baseNew, endNew, qfalse, clipmask, qfalse ); - } - else - {//saber moved, lerp - float step = 8, stepsize = 8;//aveLength, - vec3_t ma1, ma2, md2ang, curBase1, curBase2; - int xx; - vec3_t curMD1, curMD2;//, mdDiff, dirDiff; + if (VectorCompare2(baseOld, baseNew) && VectorCompare2(endOld, endNew)) { // no diff + CheckSaberDamage(self, saberNum, bladeNum, baseNew, endNew, qfalse, clipmask, qfalse); + } else { // saber moved, lerp + float step = 8, stepsize = 8; // aveLength, + vec3_t ma1, ma2, md2ang, curBase1, curBase2; + int xx; + vec3_t curMD1, curMD2; //, mdDiff, dirDiff; float dirInc, curDirFrac; vec3_t baseDiff, bladePointOld, bladePointNew; qboolean extrapolate = qtrue; - //do the trace at the base first - VectorCopy( baseOld, bladePointOld ); - VectorCopy( baseNew, bladePointNew ); - CheckSaberDamage( self, saberNum, bladeNum, bladePointOld, bladePointNew, qfalse, clipmask, qtrue ); - - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0f ) - { - //adjust muzzleDir... - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], saberHitFraction ); - } - AngleVectors( md2ang, md2, NULL, NULL ); - //shorten the base pos - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, self->client->saber[saberNum].blade[bladeNum].lengthMax, md2, endNew ); - } - - //If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc - if ( BG_SaberInAttack( self->client->ps.saberMove ) - || BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || BG_SpinningSaberAnim( self->client->ps.torsoAnim ) - || BG_InSpecialJump( self->client->ps.torsoAnim ) ) - //|| (g_timescale->value<1.0f&&BG_SaberInTransitionAny( ent->client->ps.saberMove )) ) - { - curDirFrac = DotProduct( md1, md2 ); - } - else - { + // do the trace at the base first + VectorCopy(baseOld, bladePointOld); + VectorCopy(baseNew, bladePointNew); + CheckSaberDamage(self, saberNum, bladeNum, bladePointOld, bladePointNew, qfalse, clipmask, qtrue); + + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0f) { + // adjust muzzleDir... + vectoangles(md1, ma1); + vectoangles(md2, ma2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], saberHitFraction); + } + AngleVectors(md2ang, md2, NULL, NULL); + // shorten the base pos + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, self->client->saber[saberNum].blade[bladeNum].lengthMax, md2, endNew); + } + + // If the angle diff in the blade is high, need to do it in chunks of 33 to avoid flattening of the arc + if (BG_SaberInAttack(self->client->ps.saberMove) || BG_SaberInSpecialAttack(self->client->ps.torsoAnim) || + BG_SpinningSaberAnim(self->client->ps.torsoAnim) || BG_InSpecialJump(self->client->ps.torsoAnim)) + //|| (g_timescale->value<1.0f&&BG_SaberInTransitionAny( ent->client->ps.saberMove )) ) + { + curDirFrac = DotProduct(md1, md2); + } else { curDirFrac = 1.0f; } - //NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! - if ( fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC ) - {//the saber blade spun more than 33 degrees since the last damage trace - curDirFrac = dirInc = 1.0f/((1.0f - curDirFrac)/MAX_SABER_SWING_INC); - } - else - { + // NOTE: if saber spun at least 180 degrees since last damage trace, this is not reliable...! + if (fabs(curDirFrac) < 1.0f - MAX_SABER_SWING_INC) { // the saber blade spun more than 33 degrees since the last damage trace + curDirFrac = dirInc = 1.0f / ((1.0f - curDirFrac) / MAX_SABER_SWING_INC); + } else { curDirFrac = 1.0f; dirInc = 0.0f; } - //qboolean hit_saber = qfalse; + // qboolean hit_saber = qfalse; - vectoangles( md1, ma1 ); - vectoangles( md2, ma2 ); + vectoangles(md1, ma1); + vectoangles(md2, ma2); - //VectorSubtract( md2, md1, mdDiff ); - VectorCopy( md1, curMD2 ); - VectorCopy( baseOld, curBase2 ); + // VectorSubtract( md2, md1, mdDiff ); + VectorCopy(md1, curMD2); + VectorCopy(baseOld, curBase2); - while ( 1 ) - { - VectorCopy( curMD2, curMD1 ); - VectorCopy( curBase2, curBase1 ); - if ( curDirFrac >= 1.0f ) - { - VectorCopy( md2, curMD2 ); - VectorCopy( baseNew, curBase2 ); - } - else - { - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( ma1[xx], ma2[xx], curDirFrac ); + while (1) { + VectorCopy(curMD2, curMD1); + VectorCopy(curBase2, curBase1); + if (curDirFrac >= 1.0f) { + VectorCopy(md2, curMD2); + VectorCopy(baseNew, curBase2); + } else { + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(ma1[xx], ma2[xx], curDirFrac); } - AngleVectors( md2ang, curMD2, NULL, NULL ); - //VectorMA( md1, curDirFrac, mdDiff, curMD2 ); - VectorSubtract( baseNew, baseOld, baseDiff ); - VectorMA( baseOld, curDirFrac, baseDiff, curBase2 ); + AngleVectors(md2ang, curMD2, NULL, NULL); + // VectorMA( md1, curDirFrac, mdDiff, curMD2 ); + VectorSubtract(baseNew, baseOld, baseDiff); + VectorMA(baseOld, curDirFrac, baseDiff, curBase2); } // Move up the blade in intervals of stepsize - for ( step = stepsize; step <= self->client->saber[saberNum].blade[bladeNum].lengthMax /*&& step < self->client->saber[saberNum].blade[bladeNum].lengthOld*/; step += stepsize ) - { - VectorMA( curBase1, step, curMD1, bladePointOld ); - VectorMA( curBase2, step, curMD2, bladePointNew ); + for (step = stepsize; + step <= self->client->saber[saberNum].blade[bladeNum].lengthMax /*&& step < self->client->saber[saberNum].blade[bladeNum].lengthOld*/; + step += stepsize) { + VectorMA(curBase1, step, curMD1, bladePointOld); + VectorMA(curBase2, step, curMD2, bladePointNew); - if ( step+stepsize >= self->client->saber[saberNum].blade[bladeNum].lengthMax ) - { + if (step + stepsize >= self->client->saber[saberNum].blade[bladeNum].lengthMax) { extrapolate = qfalse; } - //do the damage trace - CheckSaberDamage( self, saberNum, bladeNum, bladePointOld, bladePointNew, qfalse, clipmask, extrapolate ); + // do the damage trace + CheckSaberDamage(self, saberNum, bladeNum, bladePointOld, bladePointNew, qfalse, clipmask, extrapolate); /* if ( WP_SaberDamageForTrace( ent->s.number, bladePointOld, bladePointNew, baseDamage, curMD2, qfalse, entPowerLevel, ent->client->ps.saber[saberNum].type, qtrue, @@ -5375,49 +4259,41 @@ void G_SPSaberDamageTraceLerped( gentity_t *self, int saberNum, int bladeNum, ve } */ - //if hit a saber, shorten rest of traces to match - if ( saberHitFraction < 1.0f ) - { + // if hit a saber, shorten rest of traces to match + if (saberHitFraction < 1.0f) { vec3_t curMA1, curMA2; - //adjust muzzle endpoint - VectorSubtract( mp2, mp1, baseDiff ); - VectorMA( mp1, saberHitFraction, baseDiff, baseNew ); - VectorMA( baseNew, self->client->saber[saberNum].blade[bladeNum].lengthMax, curMD2, endNew ); - //adjust muzzleDir... - vectoangles( curMD1, curMA1 ); - vectoangles( curMD2, curMA2 ); - for ( xx = 0; xx < 3; xx++ ) - { - md2ang[xx] = LerpAngle( curMA1[xx], curMA2[xx], saberHitFraction ); + // adjust muzzle endpoint + VectorSubtract(mp2, mp1, baseDiff); + VectorMA(mp1, saberHitFraction, baseDiff, baseNew); + VectorMA(baseNew, self->client->saber[saberNum].blade[bladeNum].lengthMax, curMD2, endNew); + // adjust muzzleDir... + vectoangles(curMD1, curMA1); + vectoangles(curMD2, curMA2); + for (xx = 0; xx < 3; xx++) { + md2ang[xx] = LerpAngle(curMA1[xx], curMA2[xx], saberHitFraction); } - AngleVectors( md2ang, curMD2, NULL, NULL ); + AngleVectors(md2ang, curMD2, NULL, NULL); saberHitSaber = qtrue; } - if (saberHitWall) - { + if (saberHitWall) { break; } } - if ( saberHitWall || saberHitSaber ) - { + if (saberHitWall || saberHitSaber) { break; } - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { break; - } - else - { + } else { curDirFrac += dirInc; - if ( curDirFrac >= 1.0f ) - { + if (curDirFrac >= 1.0f) { curDirFrac = 1.0f; } } } - //do the trace at the end last - //Special check- adjust for length of blade not being a multiple of 12 + // do the trace at the end last + // Special check- adjust for length of blade not being a multiple of 12 /* aveLength = (ent->client->ps.saber[saberNum].blade[bladeNum].lengthOld + ent->client->ps.saber[saberNum].blade[bladeNum].length)/2; if ( step > aveLength ) @@ -5435,143 +4311,113 @@ void G_SPSaberDamageTraceLerped( gentity_t *self, int saberNum, int bladeNum, ve } } -qboolean BG_SaberInTransitionAny( int move ); - -qboolean WP_ForcePowerUsable( gentity_t *self, forcePowers_t forcePower ); -qboolean InFOV3( vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV ); -qboolean Jedi_WaitingAmbush( gentity_t *self ); -void Jedi_Ambush( gentity_t *self ); -evasionType_t Jedi_SaberBlockGo( gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist ); -void NPC_SetLookTarget( gentity_t *self, int entNum, int clearTime ); -void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) -{ - float dist; - gentity_t *ent, *incoming = NULL; - int entityList[MAX_GENTITIES]; - int numListedEntities; - vec3_t mins, maxs; - int i, e; - float closestDist, radius = 256; - vec3_t forward, dir, missile_dir, fwdangles = {0}; - trace_t trace; - vec3_t traceTo, entDir; - float dot1, dot2; - float lookTDist = -1; - gentity_t *lookT = NULL; - qboolean doFullRoutine = qtrue; - - //keep this updated even if we don't get below - if ( !(self->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//lookTarget is set by and to the monster that's holding you, no other operations can change that +qboolean BG_SaberInTransitionAny(int move); + +qboolean WP_ForcePowerUsable(gentity_t *self, forcePowers_t forcePower); +qboolean InFOV3(vec3_t spot, vec3_t from, vec3_t fromAngles, int hFOV, int vFOV); +qboolean Jedi_WaitingAmbush(gentity_t *self); +void Jedi_Ambush(gentity_t *self); +evasionType_t Jedi_SaberBlockGo(gentity_t *self, usercmd_t *cmd, vec3_t pHitloc, vec3_t phitDir, gentity_t *incoming, float dist); +void NPC_SetLookTarget(gentity_t *self, int entNum, int clearTime); +void WP_SaberStartMissileBlockCheck(gentity_t *self, usercmd_t *ucmd) { + float dist; + gentity_t *ent, *incoming = NULL; + int entityList[MAX_GENTITIES]; + int numListedEntities; + vec3_t mins, maxs; + int i, e; + float closestDist, radius = 256; + vec3_t forward, dir, missile_dir, fwdangles = {0}; + trace_t trace; + vec3_t traceTo, entDir; + float dot1, dot2; + float lookTDist = -1; + gentity_t *lookT = NULL; + qboolean doFullRoutine = qtrue; + + // keep this updated even if we don't get below + if (!(self->client->ps.eFlags2 & EF2_HELD_BY_MONSTER)) { // lookTarget is set by and to the monster that's holding you, no other operations can change that self->client->ps.hasLookTarget = qfalse; } - if ( self->client->ps.weapon != WP_SABER && self->client->NPC_class != CLASS_BOBAFETT ) - { + if (self->client->ps.weapon != WP_SABER && self->client->NPC_class != CLASS_BOBAFETT) { doFullRoutine = qfalse; - } - else if ( self->client->ps.saberInFlight ) - { + } else if (self->client->ps.saberInFlight) { doFullRoutine = qfalse; - } - else if ( self->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersActive & (1 << FP_LIGHTNING)) { // can't block while zapping doFullRoutine = qfalse; - } - else if ( self->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersActive & (1 << FP_DRAIN)) { // can't block while draining doFullRoutine = qfalse; - } - else if ( self->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersActive & (1 << FP_PUSH)) { // can't block while shoving doFullRoutine = qfalse; - } - else if ( self->client->ps.fd.forcePowersActive&(1<client->ps.fd.forcePowersActive & + (1 << FP_GRIP)) { // can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) doFullRoutine = qfalse; } - if (self->client->ps.weaponTime > 0) - { //don't autoblock while busy with stuff + if (self->client->ps.weaponTime > 0) { // don't autoblock while busy with stuff return; } - if ( (self->client->saber[0].saberFlags&SFL_NOT_ACTIVE_BLOCKING) ) - {//can't actively block with this saber type + if ((self->client->saber[0].saberFlags & SFL_NOT_ACTIVE_BLOCKING)) { // can't actively block with this saber type return; } - if ( self->health <= 0 ) - {//dead don't try to block (NOTE: actual deflection happens in missile code) + if (self->health <= 0) { // dead don't try to block (NOTE: actual deflection happens in missile code) return; } - if ( PM_InKnockDown( &self->client->ps ) ) - {//can't block when knocked down + if (PM_InKnockDown(&self->client->ps)) { // can't block when knocked down return; } - if ( BG_SabersOff( &self->client->ps ) && self->client->NPC_class != CLASS_BOBAFETT ) - { - if ( self->s.eType != ET_NPC ) - {//player doesn't auto-activate + if (BG_SabersOff(&self->client->ps) && self->client->NPC_class != CLASS_BOBAFETT) { + if (self->s.eType != ET_NPC) { // player doesn't auto-activate doFullRoutine = qfalse; } } - if ( self->s.eType == ET_PLAYER ) - {//don't do this if already attacking! - if ( ucmd->buttons & BUTTON_ATTACK - || BG_SaberInAttack( self->client->ps.saberMove ) - || BG_SaberInSpecialAttack( self->client->ps.torsoAnim ) - || BG_SaberInTransitionAny( self->client->ps.saberMove )) - { + if (self->s.eType == ET_PLAYER) { // don't do this if already attacking! + if (ucmd->buttons & BUTTON_ATTACK || BG_SaberInAttack(self->client->ps.saberMove) || BG_SaberInSpecialAttack(self->client->ps.torsoAnim) || + BG_SaberInTransitionAny(self->client->ps.saberMove)) { doFullRoutine = qfalse; } } - if ( self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] > level.time ) - {//can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) + if (self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] > + level.time) { // can't block while gripping (FIXME: or should it break the grip? Pain should break the grip, I think...) doFullRoutine = qfalse; } fwdangles[1] = self->client->ps.viewangles[1]; - AngleVectors( fwdangles, forward, NULL, NULL ); + AngleVectors(fwdangles, forward, NULL, NULL); - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { mins[i] = self->r.currentOrigin[i] - radius; maxs[i] = self->r.currentOrigin[i] + radius; } - numListedEntities = trap->EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); + numListedEntities = trap->EntitiesInBox(mins, maxs, entityList, MAX_GENTITIES); closestDist = radius; - for ( e = 0 ; e < numListedEntities ; e++ ) - { - ent = &g_entities[entityList[ e ]]; + for (e = 0; e < numListedEntities; e++) { + ent = &g_entities[entityList[e]]; if (ent == self) continue; - //as long as we're here I'm going to get a looktarget too, I guess. -rww - if (self->s.eType == ET_PLAYER && - ent->client && - (ent->s.eType == ET_NPC || ent->s.eType == ET_PLAYER) && - !OnSameTeam(ent, self) && - ent->client->sess.sessionTeam != TEAM_SPECTATOR && - !(ent->client->ps.pm_flags & PMF_FOLLOW) && - (ent->s.eType != ET_NPC || ent->s.NPC_class != CLASS_VEHICLE) && //don't look at vehicle NPCs - ent->health > 0) - { //seems like a valid enemy to look at. + // as long as we're here I'm going to get a looktarget too, I guess. -rww + if (self->s.eType == ET_PLAYER && ent->client && (ent->s.eType == ET_NPC || ent->s.eType == ET_PLAYER) && !OnSameTeam(ent, self) && + ent->client->sess.sessionTeam != TEAM_SPECTATOR && !(ent->client->ps.pm_flags & PMF_FOLLOW) && + (ent->s.eType != ET_NPC || ent->s.NPC_class != CLASS_VEHICLE) && // don't look at vehicle NPCs + ent->health > 0) { // seems like a valid enemy to look at. vec3_t vecSub; float vecLen; VectorSubtract(self->client->ps.origin, ent->client->ps.origin, vecSub); vecLen = VectorLength(vecSub); - if (lookTDist == -1 || vecLen < lookTDist) - { + if (lookTDist == -1 || vecLen < lookTDist) { trace_t tr; vec3_t myEyes; @@ -5580,257 +4426,209 @@ void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) trap->Trace(&tr, myEyes, NULL, NULL, ent->client->ps.origin, self->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - if (tr.fraction == 1.0f || tr.entityNum == ent->s.number) - { //we have a clear line of sight to him, so it's all good. + if (tr.fraction == 1.0f || tr.entityNum == ent->s.number) { // we have a clear line of sight to him, so it's all good. lookT = ent; lookTDist = vecLen; } } } - if (!doFullRoutine) - { //don't care about the rest then + if (!doFullRoutine) { // don't care about the rest then continue; } if (ent->r.ownerNum == self->s.number) continue; - if ( !(ent->inuse) ) + if (!(ent->inuse)) continue; - if ( ent->s.eType != ET_MISSILE && !(ent->s.eFlags&EF_MISSILE_STICK) ) - {//not a normal projectile + if (ent->s.eType != ET_MISSILE && !(ent->s.eFlags & EF_MISSILE_STICK)) { // not a normal projectile gentity_t *pOwner; - if (ent->r.ownerNum < 0 || ent->r.ownerNum >= ENTITYNUM_WORLD) - { //not going to be a client then. + if (ent->r.ownerNum < 0 || ent->r.ownerNum >= ENTITYNUM_WORLD) { // not going to be a client then. continue; } pOwner = &g_entities[ent->r.ownerNum]; - if (!pOwner->inuse || !pOwner->client) - { - continue; //not valid cl owner + if (!pOwner->inuse || !pOwner->client) { + continue; // not valid cl owner } - if (!pOwner->client->ps.saberEntityNum || - !pOwner->client->ps.saberInFlight || - pOwner->client->ps.saberEntityNum != ent->s.number) - { //the saber is knocked away and/or not flying actively, or this ent is not the cl's saber ent at all + if (!pOwner->client->ps.saberEntityNum || !pOwner->client->ps.saberInFlight || + pOwner->client->ps.saberEntityNum != + ent->s.number) { // the saber is knocked away and/or not flying actively, or this ent is not the cl's saber ent at all continue; } - //If we get here then it's ok to be treated as a thrown saber, I guess. - } - else - { - if ( ent->s.pos.trType == TR_STATIONARY && self->s.eType == ET_PLAYER ) - {//nothing you can do with a stationary missile if you're the player + // If we get here then it's ok to be treated as a thrown saber, I guess. + } else { + if (ent->s.pos.trType == TR_STATIONARY && self->s.eType == ET_PLAYER) { // nothing you can do with a stationary missile if you're the player continue; } } - //see if they're in front of me - VectorSubtract( ent->r.currentOrigin, self->r.currentOrigin, dir ); - dist = VectorNormalize( dir ); - //FIXME: handle detpacks, proximity mines and tripmines - if ( ent->s.weapon == WP_THERMAL ) - {//thermal detonator! - if ( self->NPC && dist < ent->splashRadius ) - { - if ( dist < ent->splashRadius && - ent->nextthink < level.time + 600 && - ent->count && - self->client->ps.groundEntityNum != ENTITYNUM_NONE && - (ent->s.pos.trType == TR_STATIONARY|| - ent->s.pos.trType == TR_INTERPOLATE|| - (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE|| - !WP_ForcePowerUsable( self, FP_PUSH )) ) - {//TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and about to blow up, or I don't have force-push so force-jump! - //FIXME: sometimes this might make me just jump into it...? + // see if they're in front of me + VectorSubtract(ent->r.currentOrigin, self->r.currentOrigin, dir); + dist = VectorNormalize(dir); + // FIXME: handle detpacks, proximity mines and tripmines + if (ent->s.weapon == WP_THERMAL) { // thermal detonator! + if (self->NPC && dist < ent->splashRadius) { + if (dist < ent->splashRadius && ent->nextthink < level.time + 600 && ent->count && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (ent->s.pos.trType == TR_STATIONARY || ent->s.pos.trType == TR_INTERPOLATE || + (dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE || + !WP_ForcePowerUsable(self, FP_PUSH))) { // TD is close enough to hurt me, I'm on the ground and the thing is at rest or behind me and about + // to blow up, or I don't have force-push so force-jump! + // FIXME: sometimes this might make me just jump into it...? self->client->ps.fd.forceJumpCharge = 480; - } - else if ( self->client->NPC_class != CLASS_BOBAFETT ) - {//FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( self, qfalse ); + } else if (self->client->NPC_class != CLASS_BOBAFETT) { // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(self, qfalse); } } continue; - } - else if ( ent->splashDamage && ent->splashRadius ) - {//exploding missile - //FIXME: handle tripmines and detpacks somehow... + } else if (ent->splashDamage && ent->splashRadius) { // exploding missile + // FIXME: handle tripmines and detpacks somehow... // maybe do a force-gesture that makes them explode? // But what if we're within it's splashradius? - if ( self->s.eType == ET_PLAYER ) - {//players don't auto-handle these at all + if (self->s.eType == ET_PLAYER) { // players don't auto-handle these at all continue; - } - else - { - //if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) + } else { + // if ( ent->s.pos.trType == TR_STATIONARY && (ent->s.eFlags&EF_MISSILE_STICK) // && self->client->NPC_class != CLASS_BOBAFETT ) - if (0) //Maybe handle this later? - {//a placed explosive like a tripmine or detpack - if ( InFOV3( ent->r.currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90 ) ) - {//in front of me - if ( G_ClearLOS4( self, ent ) ) - {//can see it + if (0) // Maybe handle this later? + { // a placed explosive like a tripmine or detpack + if (InFOV3(ent->r.currentOrigin, self->client->renderInfo.eyePoint, self->client->ps.viewangles, 90, 90)) { // in front of me + if (G_ClearLOS4(self, ent)) { // can see it vec3_t throwDir; - //make the gesture - ForceThrow( self, qfalse ); - //take it off the wall and toss it + // make the gesture + ForceThrow(self, qfalse); + // take it off the wall and toss it ent->s.pos.trType = TR_GRAVITY; ent->s.eType = ET_MISSILE; ent->s.eFlags &= ~EF_MISSILE_STICK; ent->flags |= FL_BOUNCE_HALF; - AngleVectors( ent->r.currentAngles, throwDir, NULL, NULL ); - VectorMA( ent->r.currentOrigin, ent->r.maxs[0]+4, throwDir, ent->r.currentOrigin ); - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); - VectorScale( throwDir, 300, ent->s.pos.trDelta ); + AngleVectors(ent->r.currentAngles, throwDir, NULL, NULL); + VectorMA(ent->r.currentOrigin, ent->r.maxs[0] + 4, throwDir, ent->r.currentOrigin); + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); + VectorScale(throwDir, 300, ent->s.pos.trDelta); ent->s.pos.trDelta[2] += 150; - VectorMA( ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta ); - ent->s.pos.trTime = level.time; // move a bit on the very first frame - VectorCopy( ent->r.currentOrigin, ent->s.pos.trBase ); + VectorMA(ent->s.pos.trDelta, 800, dir, ent->s.pos.trDelta); + ent->s.pos.trTime = level.time; // move a bit on the very first frame + VectorCopy(ent->r.currentOrigin, ent->s.pos.trBase); ent->r.ownerNum = self->s.number; // make it explode, but with less damage ent->splashDamage /= 3; ent->splashRadius /= 3; - //ent->think = WP_Explode; - ent->nextthink = level.time + Q_irand( 500, 3000 ); + // ent->think = WP_Explode; + ent->nextthink = level.time + Q_irand(500, 3000); } } - } - else if ( dist < ent->splashRadius && - self->client->ps.groundEntityNum != ENTITYNUM_NONE && - (DotProduct( dir, forward ) < SABER_REFLECT_MISSILE_CONE|| - !WP_ForcePowerUsable( self, FP_PUSH )) ) - {//NPCs try to evade it + } else if (dist < ent->splashRadius && self->client->ps.groundEntityNum != ENTITYNUM_NONE && + (DotProduct(dir, forward) < SABER_REFLECT_MISSILE_CONE || !WP_ForcePowerUsable(self, FP_PUSH))) { // NPCs try to evade it self->client->ps.fd.forceJumpCharge = 480; - } - else if ( self->client->NPC_class != CLASS_BOBAFETT ) - {//else, try to force-throw it away - //FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] - ForceThrow( self, qfalse ); + } else if (self->client->NPC_class != CLASS_BOBAFETT) { // else, try to force-throw it away + // FIXME: check forcePushRadius[NPC->client->ps.forcePowerLevel[FP_PUSH]] + ForceThrow(self, qfalse); } } - //otherwise, can't block it, so we're screwed + // otherwise, can't block it, so we're screwed continue; } - if ( ent->s.weapon != WP_SABER ) - {//only block shots coming from behind - if ( (dot1 = DotProduct( dir, forward )) < SABER_REFLECT_MISSILE_CONE ) + if (ent->s.weapon != WP_SABER) { // only block shots coming from behind + if ((dot1 = DotProduct(dir, forward)) < SABER_REFLECT_MISSILE_CONE) continue; - } - else if ( self->s.eType == ET_PLAYER ) - {//player never auto-blocks thrown sabers + } else if (self->s.eType == ET_PLAYER) { // player never auto-blocks thrown sabers continue; - }//NPCs always try to block sabers coming from behind! + } // NPCs always try to block sabers coming from behind! - //see if they're heading towards me - VectorCopy( ent->s.pos.trDelta, missile_dir ); - VectorNormalize( missile_dir ); - if ( (dot2 = DotProduct( dir, missile_dir )) > 0 ) + // see if they're heading towards me + VectorCopy(ent->s.pos.trDelta, missile_dir); + VectorNormalize(missile_dir); + if ((dot2 = DotProduct(dir, missile_dir)) > 0) continue; - //FIXME: must have a clear trace to me, too... - if ( dist < closestDist ) - { - VectorCopy( self->r.currentOrigin, traceTo ); + // FIXME: must have a clear trace to me, too... + if (dist < closestDist) { + VectorCopy(self->r.currentOrigin, traceTo); traceTo[2] = self->r.absmax[2] - 4; - trap->Trace( &trace, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, traceTo, ent->s.number, ent->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//okay, try one more check - VectorNormalize2( ent->s.pos.trDelta, entDir ); - VectorMA( ent->r.currentOrigin, radius, entDir, traceTo ); - trap->Trace( &trace, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, traceTo, ent->s.number, ent->clipmask, qfalse, 0, 0 ); - if ( trace.allsolid || trace.startsolid || (trace.fraction < 1.0f && trace.entityNum != self->s.number && trace.entityNum != self->client->ps.saberEntityNum) ) - {//can't hit me, ignore it + trap->Trace(&trace, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, traceTo, ent->s.number, ent->clipmask, qfalse, 0, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // okay, try one more check + VectorNormalize2(ent->s.pos.trDelta, entDir); + VectorMA(ent->r.currentOrigin, radius, entDir, traceTo); + trap->Trace(&trace, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, traceTo, ent->s.number, ent->clipmask, qfalse, 0, 0); + if (trace.allsolid || trace.startsolid || + (trace.fraction < 1.0f && trace.entityNum != self->s.number && + trace.entityNum != self->client->ps.saberEntityNum)) { // can't hit me, ignore it continue; } } - if ( self->s.eType == ET_NPC ) - {//An NPC - if ( self->NPC && !self->enemy && ent->r.ownerNum != ENTITYNUM_NONE ) - { + if (self->s.eType == ET_NPC) { // An NPC + if (self->NPC && !self->enemy && ent->r.ownerNum != ENTITYNUM_NONE) { gentity_t *owner = &g_entities[ent->r.ownerNum]; - if ( owner->health >= 0 && (!owner->client || owner->client->playerTeam != self->client->playerTeam) ) - { - G_SetEnemy( self, owner ); + if (owner->health >= 0 && (!owner->client || owner->client->playerTeam != self->client->playerTeam)) { + G_SetEnemy(self, owner); } } } - //FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box (+/-saberLength?), don't try to deflect unless it does? + // FIXME: if NPC, predict the intersection between my current velocity/path and the missile's, see if it intersects my bounding box + // (+/-saberLength?), don't try to deflect unless it does? closestDist = dist; incoming = ent; } } - if (self->s.eType == ET_NPC && self->localAnimIndex <= 1) - { //humanoid NPCs don't set angles based on server angles for looking, unlike other NPCs - if (self->client && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD) - { + if (self->s.eType == ET_NPC && self->localAnimIndex <= 1) { // humanoid NPCs don't set angles based on server angles for looking, unlike other NPCs + if (self->client && self->client->renderInfo.lookTarget < ENTITYNUM_WORLD) { lookT = &g_entities[self->client->renderInfo.lookTarget]; } } - if (lookT) - { //we got a looktarget at some point so we'll assign it then. - if ( !(self->client->ps.eFlags2&EF2_HELD_BY_MONSTER) ) - {//lookTarget is set by and to the monster that's holding you, no other operations can change that + if (lookT) { // we got a looktarget at some point so we'll assign it then. + if (!(self->client->ps.eFlags2 & + EF2_HELD_BY_MONSTER)) { // lookTarget is set by and to the monster that's holding you, no other operations can change that self->client->ps.hasLookTarget = qtrue; self->client->ps.lookTarget = lookT->s.number; } } - if (!doFullRoutine) - { //then we're done now + if (!doFullRoutine) { // then we're done now return; } - if ( incoming ) - { - if ( self->NPC /*&& !G_ControlledByPlayer( self )*/ ) - { - if ( Jedi_WaitingAmbush( self ) ) - { - Jedi_Ambush( self ); - } - if ( self->client->NPC_class == CLASS_BOBAFETT - && (self->client->ps.eFlags2&EF2_FLYING)//moveType == MT_FLYSWIM - && incoming->methodOfDeath != MOD_ROCKET_HOMING ) - {//a hovering Boba Fett, not a tracking rocket - if ( !Q_irand( 0, 1 ) ) - {//strafe + if (incoming) { + if (self->NPC /*&& !G_ControlledByPlayer( self )*/) { + if (Jedi_WaitingAmbush(self)) { + Jedi_Ambush(self); + } + if (self->client->NPC_class == CLASS_BOBAFETT && (self->client->ps.eFlags2 & EF2_FLYING) // moveType == MT_FLYSWIM + && incoming->methodOfDeath != MOD_ROCKET_HOMING) { // a hovering Boba Fett, not a tracking rocket + if (!Q_irand(0, 1)) { // strafe self->NPC->standTime = 0; - self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand( 1000, 2000 ); + self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand(1000, 2000); } - if ( !Q_irand( 0, 1 ) ) - {//go up/down - TIMER_Set( self, "heightChange", Q_irand( 1000, 3000 ) ); - self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand( 1000, 2000 ); + if (!Q_irand(0, 1)) { // go up/down + TIMER_Set(self, "heightChange", Q_irand(1000, 3000)); + self->client->ps.fd.forcePowerDebounce[FP_SABER_DEFENSE] = level.time + Q_irand(1000, 2000); } - } - else if ( Jedi_SaberBlockGo( self, &self->NPC->last_ucmd, NULL, NULL, incoming, 0.0f ) != EVASION_NONE ) - {//make sure to turn on your saber if it's not on - if ( self->client->NPC_class != CLASS_BOBAFETT ) - { - //self->client->ps.SaberActivate(); + } else if (Jedi_SaberBlockGo(self, &self->NPC->last_ucmd, NULL, NULL, incoming, 0.0f) != + EVASION_NONE) { // make sure to turn on your saber if it's not on + if (self->client->NPC_class != CLASS_BOBAFETT) { + // self->client->ps.SaberActivate(); WP_ActivateSaber(self); } } - } - else//player + } else // player { gentity_t *owner = &g_entities[incoming->r.ownerNum]; - WP_SaberBlockNonRandom( self, incoming->r.currentOrigin, qtrue ); - if ( owner && owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER) )//keep enemy jedi over shooters + WP_SaberBlockNonRandom(self, incoming->r.currentOrigin, qtrue); + if (owner && owner->client && (!self->enemy || self->enemy->s.weapon != WP_SABER)) // keep enemy jedi over shooters { self->enemy = owner; - //NPC_SetLookTarget( self, owner->s.number, level.time+1000 ); - //player looktargetting done differently + // NPC_SetLookTarget( self, owner->s.number, level.time+1000 ); + // player looktargetting done differently } } } @@ -5843,131 +4641,103 @@ void WP_SaberStartMissileBlockCheck( gentity_t *self, usercmd_t *ucmd ) #define SABER_THROWN_HIT_DAMAGE 30 #define SABER_THROWN_RETURN_HIT_DAMAGE 5 -void thrownSaberTouch (gentity_t *saberent, gentity_t *other, trace_t *trace); +void thrownSaberTouch(gentity_t *saberent, gentity_t *other, trace_t *trace); -static QINLINE qboolean CheckThrownSaberDamaged(gentity_t *saberent, gentity_t *saberOwner, gentity_t *ent, int dist, int returning, qboolean noDCheck) -{ +static QINLINE qboolean CheckThrownSaberDamaged(gentity_t *saberent, gentity_t *saberOwner, gentity_t *ent, int dist, int returning, qboolean noDCheck) { vec3_t vecsub; float veclen; gentity_t *te; - if (!saberOwner || !saberOwner->client) - { + if (!saberOwner || !saberOwner->client) { return qfalse; } - if (saberOwner->client->ps.saberAttackWound > level.time) - { + if (saberOwner->client->ps.saberAttackWound > level.time) { return qfalse; } - if (ent && ent->client && ent->inuse && ent->s.number != saberOwner->s.number && - ent->health > 0 && ent->takedamage && - trap->InPVS(ent->client->ps.origin, saberent->r.currentOrigin) && - ent->client->sess.sessionTeam != TEAM_SPECTATOR && - (ent->client->pers.connected || ent->s.eType == ET_NPC)) - { //hit a client - if (ent->inuse && ent->client && - ent->client->ps.duelInProgress && - ent->client->ps.duelIndex != saberOwner->s.number) - { + if (ent && ent->client && ent->inuse && ent->s.number != saberOwner->s.number && ent->health > 0 && ent->takedamage && + trap->InPVS(ent->client->ps.origin, saberent->r.currentOrigin) && ent->client->sess.sessionTeam != TEAM_SPECTATOR && + (ent->client->pers.connected || ent->s.eType == ET_NPC)) { // hit a client + if (ent->inuse && ent->client && ent->client->ps.duelInProgress && ent->client->ps.duelIndex != saberOwner->s.number) { return qfalse; } - if (ent->inuse && ent->client && - saberOwner->client->ps.duelInProgress && - saberOwner->client->ps.duelIndex != ent->s.number) - { + if (ent->inuse && ent->client && saberOwner->client->ps.duelInProgress && saberOwner->client->ps.duelIndex != ent->s.number) { return qfalse; } VectorSubtract(saberent->r.currentOrigin, ent->client->ps.origin, vecsub); veclen = VectorLength(vecsub); - if (veclen < dist) - { //within range + if (veclen < dist) { // within range trace_t tr; trap->Trace(&tr, saberent->r.currentOrigin, NULL, NULL, ent->client->ps.origin, saberent->s.number, MASK_SHOT, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == ent->s.number) - { //Slice them - if (!saberOwner->client->ps.isJediMaster && WP_SaberCanBlock(ent, tr.endpos, 0, MOD_SABER, qfalse, 999)) - { //they blocked it + if (tr.fraction == 1 || tr.entityNum == ent->s.number) { // Slice them + if (!saberOwner->client->ps.isJediMaster && WP_SaberCanBlock(ent, tr.endpos, 0, MOD_SABER, qfalse, 999)) { // they blocked it WP_SaberBlockNonRandom(ent, tr.endpos, qfalse); - te = G_TempEntity( tr.endpos, EV_SABER_BLOCK ); + te = G_TempEntity(tr.endpos, EV_SABER_BLOCK); VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { te->s.angles[1] = 1; } te->s.eventParm = 1; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum - if (saberCheckKnockdown_Thrown(saberent, saberOwner, &g_entities[tr.entityNum])) - { //it was knocked out of the air + if (saberCheckKnockdown_Thrown(saberent, saberOwner, &g_entities[tr.entityNum])) { // it was knocked out of the air return qfalse; } - if (!returning) - { //return to owner if blocked + if (!returning) { // return to owner if blocked thrownSaberTouch(saberent, saberent, NULL); } saberOwner->client->ps.saberAttackWound = level.time + 500; return qfalse; - } - else - { //a good hit + } else { // a good hit vec3_t dir; int dflags = 0; VectorSubtract(tr.endpos, saberent->r.currentOrigin, dir); VectorNormalize(dir); - if (!dir[0] && !dir[1] && !dir[2]) - { + if (!dir[0] && !dir[1] && !dir[2]) { dir[1] = 1; } - if ( (saberOwner->client->saber[0].saberFlags2&SFL2_NO_DISMEMBERMENT) ) - { + if ((saberOwner->client->saber[0].saberFlags2 & SFL2_NO_DISMEMBERMENT)) { dflags |= DAMAGE_NO_DISMEMBER; } - if ( saberOwner->client->saber[0].knockbackScale > 0.0f ) - { + if (saberOwner->client->saber[0].knockbackScale > 0.0f) { dflags |= DAMAGE_SABER_KNOCKBACK1; } - if (saberOwner->client->ps.isJediMaster) - { //2x damage for the Jedi Master - G_Damage(ent, saberOwner, saberOwner, dir, tr.endpos, saberent->damage*2, dflags, MOD_SABER); - } - else - { + if (saberOwner->client->ps.isJediMaster) { // 2x damage for the Jedi Master + G_Damage(ent, saberOwner, saberOwner, dir, tr.endpos, saberent->damage * 2, dflags, MOD_SABER); + } else { G_Damage(ent, saberOwner, saberOwner, dir, tr.endpos, saberent->damage, dflags, MOD_SABER); } - te = G_TempEntity( tr.endpos, EV_SABER_HIT ); + te = G_TempEntity(tr.endpos, EV_SABER_HIT); te->s.otherEntityNum = ent->s.number; te->s.otherEntityNum2 = saberOwner->s.number; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { te->s.angles[1] = 1; } te->s.eventParm = 1; - if (!returning) - { //return to owner if blocked + if (!returning) { // return to owner if blocked thrownSaberTouch(saberent, saberent, NULL); } } @@ -5975,103 +4745,80 @@ static QINLINE qboolean CheckThrownSaberDamaged(gentity_t *saberent, gentity_t * saberOwner->client->ps.saberAttackWound = level.time + 500; } } - } - else if (ent && !ent->client && ent->inuse && ent->takedamage && ent->health > 0 && ent->s.number != saberOwner->s.number && - ent->s.number != saberent->s.number && (noDCheck ||trap->InPVS(ent->r.currentOrigin, saberent->r.currentOrigin))) - { //hit a non-client + } else if (ent && !ent->client && ent->inuse && ent->takedamage && ent->health > 0 && ent->s.number != saberOwner->s.number && + ent->s.number != saberent->s.number && (noDCheck || trap->InPVS(ent->r.currentOrigin, saberent->r.currentOrigin))) { // hit a non-client - if (noDCheck) - { + if (noDCheck) { veclen = 0; - } - else - { + } else { VectorSubtract(saberent->r.currentOrigin, ent->r.currentOrigin, vecsub); veclen = VectorLength(vecsub); } - if (veclen < dist) - { + if (veclen < dist) { trace_t tr; vec3_t entOrigin; - if (ent->s.eType == ET_MOVER) - { - VectorSubtract( ent->r.absmax, ent->r.absmin, entOrigin ); - VectorMA( ent->r.absmin, 0.5, entOrigin, entOrigin ); - VectorAdd( ent->r.absmin, ent->r.absmax, entOrigin ); - VectorScale( entOrigin, 0.5f, entOrigin ); - } - else - { + if (ent->s.eType == ET_MOVER) { + VectorSubtract(ent->r.absmax, ent->r.absmin, entOrigin); + VectorMA(ent->r.absmin, 0.5, entOrigin, entOrigin); + VectorAdd(ent->r.absmin, ent->r.absmax, entOrigin); + VectorScale(entOrigin, 0.5f, entOrigin); + } else { VectorCopy(ent->r.currentOrigin, entOrigin); } trap->Trace(&tr, saberent->r.currentOrigin, NULL, NULL, entOrigin, saberent->s.number, MASK_SHOT, qfalse, 0, 0); - if (tr.fraction == 1 || tr.entityNum == ent->s.number) - { + if (tr.fraction == 1 || tr.entityNum == ent->s.number) { vec3_t dir; int dflags = 0; VectorSubtract(tr.endpos, entOrigin, dir); VectorNormalize(dir); - if ( (saberOwner->client->saber[0].saberFlags2&SFL2_NO_DISMEMBERMENT) ) - { + if ((saberOwner->client->saber[0].saberFlags2 & SFL2_NO_DISMEMBERMENT)) { dflags |= DAMAGE_NO_DISMEMBER; } - if ( saberOwner->client->saber[0].knockbackScale > 0.0f ) - { + if (saberOwner->client->saber[0].knockbackScale > 0.0f) { dflags |= DAMAGE_SABER_KNOCKBACK1; } - if (ent->s.eType == ET_NPC) - { //an animent + if (ent->s.eType == ET_NPC) { // an animent G_Damage(ent, saberOwner, saberOwner, dir, tr.endpos, 40, dflags, MOD_SABER); - } - else - { + } else { G_Damage(ent, saberOwner, saberOwner, dir, tr.endpos, 5, dflags, MOD_SABER); } - te = G_TempEntity( tr.endpos, EV_SABER_HIT ); - te->s.otherEntityNum = ENTITYNUM_NONE; //don't do this for throw damage - //te->s.otherEntityNum = ent->s.number; - te->s.otherEntityNum2 = saberOwner->s.number;//actually, do send this, though - for the overridden per-saber hit effects/sounds - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te = G_TempEntity(tr.endpos, EV_SABER_HIT); + te->s.otherEntityNum = ENTITYNUM_NONE; // don't do this for throw damage + // te->s.otherEntityNum = ent->s.number; + te->s.otherEntityNum2 = saberOwner->s.number; // actually, do send this, though - for the overridden per-saber hit effects/sounds + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum VectorCopy(tr.endpos, te->s.origin); VectorCopy(tr.plane.normal, te->s.angles); - if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) - { + if (!te->s.angles[0] && !te->s.angles[1] && !te->s.angles[2]) { te->s.angles[1] = 1; } - if ( ent->s.eType == ET_MOVER ) - { - if ( saberOwner - && saberOwner->client - && (saberOwner->client->saber[0].saberFlags2&SFL2_NO_CLASH_FLARE) ) - {//don't do clash flare - NOTE: assumes same is true for both sabers if using dual sabers! - G_FreeEntity( te );//kind of a waste, but... - } - else - { - //I suppose I could tie this into the saberblock event, but I'm tired of adding flags to that thing. - gentity_t *teS = G_TempEntity( te->s.origin, EV_SABER_CLASHFLARE ); + if (ent->s.eType == ET_MOVER) { + if (saberOwner && saberOwner->client && + (saberOwner->client->saber[0].saberFlags2 & + SFL2_NO_CLASH_FLARE)) { // don't do clash flare - NOTE: assumes same is true for both sabers if using dual sabers! + G_FreeEntity(te); // kind of a waste, but... + } else { + // I suppose I could tie this into the saberblock event, but I'm tired of adding flags to that thing. + gentity_t *teS = G_TempEntity(te->s.origin, EV_SABER_CLASHFLARE); VectorCopy(te->s.origin, teS->s.origin); te->s.eventParm = 0; } - } - else - { + } else { te->s.eventParm = 1; } - if (!returning) - { //return to owner if blocked + if (!returning) { // return to owner if blocked thrownSaberTouch(saberent, saberent, NULL); } @@ -6083,34 +4830,29 @@ static QINLINE qboolean CheckThrownSaberDamaged(gentity_t *saberent, gentity_t * return qtrue; } -static QINLINE void saberCheckRadiusDamage(gentity_t *saberent, int returning) -{ //we're going to cheat and damage players within the saber's radius, just for the sake of doing things more "efficiently" (and because the saber entity has no server g2 instance) +static QINLINE void saberCheckRadiusDamage(gentity_t *saberent, + int returning) { // we're going to cheat and damage players within the saber's radius, just for the sake of doing + // things more "efficiently" (and because the saber entity has no server g2 instance) int i = 0; int dist = 0; gentity_t *ent; gentity_t *saberOwner = &g_entities[saberent->r.ownerNum]; - if (returning && returning != 2) - { + if (returning && returning != 2) { dist = MIN_SABER_SLICE_RETURN_DISTANCE; - } - else - { + } else { dist = MIN_SABER_SLICE_DISTANCE; } - if (!saberOwner || !saberOwner->client) - { + if (!saberOwner || !saberOwner->client) { return; } - if (saberOwner->client->ps.saberAttackWound > level.time) - { + if (saberOwner->client->ps.saberAttackWound > level.time) { return; } - while (i < level.num_entities) - { + while (i < level.num_entities) { ent = &g_entities[i]; CheckThrownSaberDamaged(saberent, saberOwner, ent, dist, returning, qfalse); @@ -6121,59 +4863,57 @@ static QINLINE void saberCheckRadiusDamage(gentity_t *saberent, int returning) #define THROWN_SABER_COMP -static QINLINE void saberMoveBack( gentity_t *ent, qboolean goingBack ) -{ - vec3_t origin, oldOrg; +static QINLINE void saberMoveBack(gentity_t *ent, qboolean goingBack) { + vec3_t origin, oldOrg; ent->s.pos.trType = TR_LINEAR; - VectorCopy( ent->r.currentOrigin, oldOrg ); + VectorCopy(ent->r.currentOrigin, oldOrg); // get current position - BG_EvaluateTrajectory( &ent->s.pos, level.time, origin ); - //Get current angles? - BG_EvaluateTrajectory( &ent->s.apos, level.time, ent->r.currentAngles ); + BG_EvaluateTrajectory(&ent->s.pos, level.time, origin); + // Get current angles? + BG_EvaluateTrajectory(&ent->s.apos, level.time, ent->r.currentAngles); - //compensation test code.. + // compensation test code.. #ifdef THROWN_SABER_COMP - if (!goingBack && ent->s.pos.trType != TR_GRAVITY) - { //acts as a fallback in case touch code fails, keeps saber from going through things between predictions + if (!goingBack && + ent->s.pos.trType != TR_GRAVITY) { // acts as a fallback in case touch code fails, keeps saber from going through things between predictions float originalLength = 0; int iCompensationLength = 32; trace_t tr; vec3_t mins, maxs; vec3_t calcComp, compensatedOrigin; - VectorSet( mins, -24.0f, -24.0f, -8.0f ); - VectorSet( maxs, 24.0f, 24.0f, 8.0f ); + VectorSet(mins, -24.0f, -24.0f, -8.0f); + VectorSet(maxs, 24.0f, 24.0f, 8.0f); VectorSubtract(origin, oldOrg, calcComp); originalLength = VectorLength(calcComp); VectorNormalize(calcComp); - compensatedOrigin[0] = oldOrg[0] + calcComp[0]*(originalLength+iCompensationLength); - compensatedOrigin[1] = oldOrg[1] + calcComp[1]*(originalLength+iCompensationLength); - compensatedOrigin[2] = oldOrg[2] + calcComp[2]*(originalLength+iCompensationLength); + compensatedOrigin[0] = oldOrg[0] + calcComp[0] * (originalLength + iCompensationLength); + compensatedOrigin[1] = oldOrg[1] + calcComp[1] * (originalLength + iCompensationLength); + compensatedOrigin[2] = oldOrg[2] + calcComp[2] * (originalLength + iCompensationLength); trap->Trace(&tr, oldOrg, mins, maxs, compensatedOrigin, ent->r.ownerNum, MASK_PLAYERSOLID, qfalse, 0, 0); - if ((tr.fraction != 1 || tr.startsolid || tr.allsolid) && tr.entityNum != ent->r.ownerNum && !(g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER)) - { + if ((tr.fraction != 1 || tr.startsolid || tr.allsolid) && tr.entityNum != ent->r.ownerNum && + !(g_entities[tr.entityNum].r.contents & CONTENTS_LIGHTSABER)) { VectorClear(ent->s.pos.trDelta); - //Unfortunately doing this would defeat the purpose of the compensation. We will have to settle for a jerk on the client. - //VectorCopy( origin, ent->r.currentOrigin ); + // Unfortunately doing this would defeat the purpose of the compensation. We will have to settle for a jerk on the client. + // VectorCopy( origin, ent->r.currentOrigin ); - //we'll skip the dist check, since we don't really care about that (we just hit it physically) + // we'll skip the dist check, since we don't really care about that (we just hit it physically) CheckThrownSaberDamaged(ent, &g_entities[ent->r.ownerNum], &g_entities[tr.entityNum], 256, 0, qtrue); - if (ent->s.pos.trType == TR_GRAVITY) - { //got blocked and knocked away in the damage func + if (ent->s.pos.trType == TR_GRAVITY) { // got blocked and knocked away in the damage func return; } tr.startsolid = 0; - if (tr.entityNum == ENTITYNUM_NONE) - { //eh, this is a filthy lie. (obviously it had to hit something or it wouldn't be in here, so we'll say it hit the world) + if (tr.entityNum == + ENTITYNUM_NONE) { // eh, this is a filthy lie. (obviously it had to hit something or it wouldn't be in here, so we'll say it hit the world) tr.entityNum = ENTITYNUM_WORLD; } thrownSaberTouch(ent, &g_entities[tr.entityNum], &tr); @@ -6182,19 +4922,16 @@ static QINLINE void saberMoveBack( gentity_t *ent, qboolean goingBack ) } #endif - VectorCopy( origin, ent->r.currentOrigin ); + VectorCopy(origin, ent->r.currentOrigin); } -void SaberBounceSound( gentity_t *self, gentity_t *other, trace_t *trace ) -{ +void SaberBounceSound(gentity_t *self, gentity_t *other, trace_t *trace) { VectorCopy(self->r.currentAngles, self->s.apos.trBase); self->s.apos.trBase[PITCH] = 90; } -void DeadSaberThink(gentity_t *saberent) -{ - if (saberent->speed < level.time) - { +void DeadSaberThink(gentity_t *saberent) { + if (saberent->speed < level.time) { saberent->think = G_FreeEntity; saberent->nextthink = level.time; return; @@ -6203,19 +4940,17 @@ void DeadSaberThink(gentity_t *saberent) G_RunObject(saberent); } -void MakeDeadSaber(gentity_t *ent) -{ //spawn a "dead" saber entity here so it looks like the saber fell out of the air. - //This entity will remove itself after a very short time period. +void MakeDeadSaber(gentity_t *ent) { // spawn a "dead" saber entity here so it looks like the saber fell out of the air. + // This entity will remove itself after a very short time period. vec3_t startorg; vec3_t startang; gentity_t *saberent; gentity_t *owner = NULL; - //trace stuct used for determining if it's safe to spawn at current location - trace_t tr; + // trace stuct used for determining if it's safe to spawn at current location + trace_t tr; - if (level.gametype == GT_JEDIMASTER) - { //never spawn a dead saber in JM, because the only saber on the level is really a world object - //G_Sound(ent, CHAN_AUTO, saberOffSound); + if (level.gametype == GT_JEDIMASTER) { // never spawn a dead saber in JM, because the only saber on the level is really a world object + // G_Sound(ent, CHAN_AUTO, saberOffSound); return; } @@ -6230,34 +4965,31 @@ void MakeDeadSaber(gentity_t *ent) saberent->r.ownerNum = ent->s.number; saberent->clipmask = MASK_PLAYERSOLID; - saberent->r.contents = CONTENTS_TRIGGER;//0; + saberent->r.contents = CONTENTS_TRIGGER; // 0; - VectorSet( saberent->r.mins, -3.0f, -3.0f, -1.5f ); - VectorSet( saberent->r.maxs, 3.0f, 3.0f, 1.5f ); + VectorSet(saberent->r.mins, -3.0f, -3.0f, -1.5f); + VectorSet(saberent->r.maxs, 3.0f, 3.0f, 1.5f); saberent->touch = SaberBounceSound; saberent->think = DeadSaberThink; saberent->nextthink = level.time; - //perform a trace before attempting to spawn at currently location. - //unfortunately, it's a fairly regular occurance that current saber location + // perform a trace before attempting to spawn at currently location. + // unfortunately, it's a fairly regular occurance that current saber location //(normally at the player's right hand) could result in the saber being stuck - //in the the map and then freaking out. + // in the the map and then freaking out. trap->Trace(&tr, startorg, saberent->r.mins, saberent->r.maxs, startorg, saberent->s.number, saberent->clipmask, qfalse, 0, 0); - if(tr.startsolid || tr.fraction != 1) - {//bad position, try popping our origin up a bit + if (tr.startsolid || tr.fraction != 1) { // bad position, try popping our origin up a bit startorg[2] += 20; trap->Trace(&tr, startorg, saberent->r.mins, saberent->r.maxs, startorg, saberent->s.number, saberent->clipmask, qfalse, 0, 0); - if(tr.startsolid || tr.fraction != 1) - {//still no luck, try using our owner's origin + if (tr.startsolid || tr.fraction != 1) { // still no luck, try using our owner's origin owner = &g_entities[ent->r.ownerNum]; - if( owner->inuse && owner->client ) - { + if (owner->inuse && owner->client) { G_SetOrigin(saberent, owner->client->ps.origin); } - //since this is our last chance, we don't care if this works or not. + // since this is our last chance, we don't care if this works or not. } } @@ -6274,24 +5006,19 @@ void MakeDeadSaber(gentity_t *ent) saberent->s.apos.trDelta[0] = Q_irand(200, 800); saberent->s.apos.trDelta[1] = Q_irand(200, 800); saberent->s.apos.trDelta[2] = Q_irand(200, 800); - saberent->s.apos.trTime = level.time-50; + saberent->s.apos.trTime = level.time - 50; saberent->s.pos.trType = TR_GRAVITY; - saberent->s.pos.trTime = level.time-50; + saberent->s.pos.trTime = level.time - 50; saberent->flags = FL_BOUNCE_HALF; - if (ent->r.ownerNum >= 0 && ent->r.ownerNum < ENTITYNUM_WORLD) - { + if (ent->r.ownerNum >= 0 && ent->r.ownerNum < ENTITYNUM_WORLD) { owner = &g_entities[ent->r.ownerNum]; - if (owner->inuse && owner->client && - owner->client->saber[0].model[0]) - { - WP_SaberAddG2Model( saberent, owner->client->saber[0].model, owner->client->saber[0].skin ); - } - else - { - //WP_SaberAddG2Model( saberent, NULL, 0 ); - //argh!!!! + if (owner->inuse && owner->client && owner->client->saber[0].model[0]) { + WP_SaberAddG2Model(saberent, owner->client->saber[0].model, owner->client->saber[0].skin); + } else { + // WP_SaberAddG2Model( saberent, NULL, 0 ); + // argh!!!! G_FreeEntity(saberent); return; } @@ -6307,7 +5034,7 @@ void MakeDeadSaber(gentity_t *ent) saberent->bounceCount = 12; - //fall off in the direction the real saber was headed + // fall off in the direction the real saber was headed VectorCopy(ent->s.pos.trDelta, saberent->s.pos.trDelta); saberMoveBack(saberent, qtrue); @@ -6321,16 +5048,14 @@ void MakeDeadSaber(gentity_t *ent) void saberReactivate(gentity_t *saberent, gentity_t *saberOwner); void saberBackToOwner(gentity_t *saberent); -void DownedSaberThink(gentity_t *saberent) -{ +void DownedSaberThink(gentity_t *saberent) { gentity_t *saberOwn = NULL; qboolean notDisowned = qfalse; qboolean pullBack = qfalse; saberent->nextthink = level.time; - if (saberent->r.ownerNum == ENTITYNUM_NONE) - { + if (saberent->r.ownerNum == ENTITYNUM_NONE) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -6340,12 +5065,8 @@ void DownedSaberThink(gentity_t *saberent) saberOwn = &g_entities[saberent->r.ownerNum]; - if (!saberOwn || - !saberOwn->inuse || - !saberOwn->client || - saberOwn->client->sess.sessionTeam == TEAM_SPECTATOR || - (saberOwn->client->ps.pm_flags & PMF_FOLLOW)) - { + if (!saberOwn || !saberOwn->inuse || !saberOwn->client || saberOwn->client->sess.sessionTeam == TEAM_SPECTATOR || + (saberOwn->client->ps.pm_flags & PMF_FOLLOW)) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -6353,14 +5074,11 @@ void DownedSaberThink(gentity_t *saberent) return; } - if (saberOwn->client->ps.saberEntityNum) - { - if (saberOwn->client->ps.saberEntityNum == saberent->s.number) - { //owner shouldn't have this set if we're thinking in here. Must've fallen off a cliff and instantly respawned or something. + if (saberOwn->client->ps.saberEntityNum) { + if (saberOwn->client->ps.saberEntityNum == + saberent->s.number) { // owner shouldn't have this set if we're thinking in here. Must've fallen off a cliff and instantly respawned or something. notDisowned = qtrue; - } - else - { //This should never happen, but just in case.. + } else { // This should never happen, but just in case.. assert(!"ULTRA BAD THING"); MakeDeadSaber(saberent); @@ -6370,24 +5088,22 @@ void DownedSaberThink(gentity_t *saberent) } } - if (notDisowned || saberOwn->health < 1 || !saberOwn->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) - { //He's dead, just go back to our normal saber status + if (notDisowned || saberOwn->health < 1 || + !saberOwn->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { // He's dead, just go back to our normal saber status saberOwn->client->ps.saberEntityNum = saberOwn->client->saberStoredIndex; - //MakeDeadSaber(saberent); //spawn a dead saber on top of where we are now. The "bodyqueue" method. - //Actually this will get taken care of when the thrown saber func sees we're dead. + // MakeDeadSaber(saberent); //spawn a dead saber on top of where we are now. The "bodyqueue" method. + // Actually this will get taken care of when the thrown saber func sees we're dead. #ifdef _DEBUG - if (saberOwn->client->saberStoredIndex != saberent->s.number) - { //I'm paranoid. + if (saberOwn->client->saberStoredIndex != saberent->s.number) { // I'm paranoid. assert(!"Bad saber index!!!"); } #endif saberReactivate(saberent, saberOwn); - if (saberOwn->health < 1) - { + if (saberOwn->health < 1) { saberOwn->client->ps.saberInFlight = qfalse; MakeDeadSaber(saberent); } @@ -6398,14 +5114,13 @@ void DownedSaberThink(gentity_t *saberent) saberent->nextthink = level.time; saberent->r.svFlags |= (SVF_NOCLIENT); - //saberent->r.contents = CONTENTS_LIGHTSABER; + // saberent->r.contents = CONTENTS_LIGHTSABER; saberent->s.loopSound = 0; saberent->s.loopIsSoundset = qfalse; - if (saberOwn->health > 0) - { //only set this if he's alive. If dead we want to reflect the lack of saber on the corpse, as he died with his saber out. + if (saberOwn->health > 0) { // only set this if he's alive. If dead we want to reflect the lack of saber on the corpse, as he died with his saber out. saberOwn->client->ps.saberInFlight = qfalse; - WP_SaberRemoveG2Model( saberent ); + WP_SaberRemoveG2Model(saberent); } saberOwn->client->ps.saberEntityState = 0; saberOwn->client->ps.saberThrowDelay = level.time + 500; @@ -6414,22 +5129,17 @@ void DownedSaberThink(gentity_t *saberent) return; } - if (saberOwn->client->saberKnockedTime < level.time && (saberOwn->client->pers.cmd.buttons & BUTTON_ATTACK)) - { //He wants us back + if (saberOwn->client->saberKnockedTime < level.time && (saberOwn->client->pers.cmd.buttons & BUTTON_ATTACK)) { // He wants us back pullBack = qtrue; - } - else if ((level.time - saberOwn->client->saberKnockedTime) > MAX_LEAVE_TIME) - { //Been sitting around for too long, go back no matter what he wants. + } else if ((level.time - saberOwn->client->saberKnockedTime) > MAX_LEAVE_TIME) { // Been sitting around for too long, go back no matter what he wants. pullBack = qtrue; } - if (pullBack) - { //Get going back to the owner. + if (pullBack) { // Get going back to the owner. saberOwn->client->ps.saberEntityNum = saberOwn->client->saberStoredIndex; #ifdef _DEBUG - if (saberOwn->client->saberStoredIndex != saberent->s.number) - { //I'm paranoid. + if (saberOwn->client->saberStoredIndex != saberent->s.number) { // I'm paranoid. assert(!"Bad saber index!!!"); } #endif @@ -6444,14 +5154,12 @@ void DownedSaberThink(gentity_t *saberent) saberent->r.contents = CONTENTS_LIGHTSABER; - G_Sound( saberOwn, CHAN_BODY, G_SoundIndex( "sound/weapons/force/pull.wav" ) ); - if (saberOwn->client->saber[0].soundOn) - { - G_Sound( saberent, CHAN_BODY, saberOwn->client->saber[0].soundOn ); + G_Sound(saberOwn, CHAN_BODY, G_SoundIndex("sound/weapons/force/pull.wav")); + if (saberOwn->client->saber[0].soundOn) { + G_Sound(saberent, CHAN_BODY, saberOwn->client->saber[0].soundOn); } - if (saberOwn->client->saber[1].soundOn) - { - G_Sound( saberOwn, CHAN_BODY, saberOwn->client->saber[1].soundOn ); + if (saberOwn->client->saber[1].soundOn) { + G_Sound(saberOwn, CHAN_BODY, saberOwn->client->saber[1].soundOn); } return; @@ -6461,8 +5169,7 @@ void DownedSaberThink(gentity_t *saberent) saberent->nextthink = level.time; } -void saberReactivate(gentity_t *saberent, gentity_t *saberOwner) -{ +void saberReactivate(gentity_t *saberent, gentity_t *saberOwner) { saberent->s.saberInFlight = qtrue; saberent->s.apos.trType = TR_LINEAR; @@ -6489,36 +5196,35 @@ void saberReactivate(gentity_t *saberent, gentity_t *saberOwner) trap->LinkEntity((sharedEntity_t *)saberent); } -#define SABER_RETRIEVE_DELAY 3000 //3 seconds for now. This will leave you nice and open if you lose your saber. +#define SABER_RETRIEVE_DELAY 3000 // 3 seconds for now. This will leave you nice and open if you lose your saber. -void saberKnockDown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) -{ - trace_t tr; +void saberKnockDown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) { + trace_t tr; - saberOwner->client->ps.saberEntityNum = 0; //still stored in client->saberStoredIndex + saberOwner->client->ps.saberEntityNum = 0; // still stored in client->saberStoredIndex saberOwner->client->saberKnockedTime = level.time + SABER_RETRIEVE_DELAY; saberent->clipmask = MASK_SOLID; - saberent->r.contents = CONTENTS_TRIGGER;//0; + saberent->r.contents = CONTENTS_TRIGGER; // 0; - VectorSet( saberent->r.mins, -3.0f, -3.0f, -1.5f ); - VectorSet( saberent->r.maxs, 3.0f, 3.0f, 1.5f ); + VectorSet(saberent->r.mins, -3.0f, -3.0f, -1.5f); + VectorSet(saberent->r.maxs, 3.0f, 3.0f, 1.5f); - //perform a trace before attempting to spawn at currently location. - //unfortunately, it's a fairly regular occurance that current saber location + // perform a trace before attempting to spawn at currently location. + // unfortunately, it's a fairly regular occurance that current saber location //(normally at the player's right hand) could result in the saber being stuck - //in the the map and then freaking out. - trap->Trace(&tr, saberent->r.currentOrigin, saberent->r.mins, saberent->r.maxs, saberent->r.currentOrigin, saberent->s.number, saberent->clipmask, qfalse, 0, 0); - if(tr.startsolid || tr.fraction != 1) - {//bad position, try popping our origin up a bit + // in the the map and then freaking out. + trap->Trace(&tr, saberent->r.currentOrigin, saberent->r.mins, saberent->r.maxs, saberent->r.currentOrigin, saberent->s.number, saberent->clipmask, qfalse, + 0, 0); + if (tr.startsolid || tr.fraction != 1) { // bad position, try popping our origin up a bit saberent->r.currentOrigin[2] += 20; G_SetOrigin(saberent, saberent->r.currentOrigin); - trap->Trace(&tr, saberent->r.currentOrigin, saberent->r.mins, saberent->r.maxs, saberent->r.currentOrigin, saberent->s.number, saberent->clipmask, qfalse, 0, 0); - if(tr.startsolid || tr.fraction != 1) - {//still no luck, try using our owner's origin + trap->Trace(&tr, saberent->r.currentOrigin, saberent->r.mins, saberent->r.maxs, saberent->r.currentOrigin, saberent->s.number, saberent->clipmask, + qfalse, 0, 0); + if (tr.startsolid || tr.fraction != 1) { // still no luck, try using our owner's origin G_SetOrigin(saberent, saberOwner->client->ps.origin); - //since this is our last chance, we don't care if this works or not. + // since this is our last chance, we don't care if this works or not. } } @@ -6526,13 +5232,13 @@ void saberKnockDown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other saberent->s.apos.trDelta[0] = Q_irand(200, 800); saberent->s.apos.trDelta[1] = Q_irand(200, 800); saberent->s.apos.trDelta[2] = Q_irand(200, 800); - saberent->s.apos.trTime = level.time-50; + saberent->s.apos.trTime = level.time - 50; saberent->s.pos.trType = TR_GRAVITY; - saberent->s.pos.trTime = level.time-50; + saberent->s.pos.trTime = level.time - 50; saberent->flags |= FL_BOUNCE_HALF; - WP_SaberAddG2Model( saberent, saberOwner->client->saber[0].model, saberOwner->client->saber[0].skin ); + WP_SaberAddG2Model(saberent, saberOwner->client->saber[0].model, saberOwner->client->saber[0].skin); saberent->s.modelGhoul2 = 1; saberent->s.g2radius = 20; @@ -6542,114 +5248,97 @@ void saberKnockDown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other saberent->speed = level.time + 4000; - saberent->bounceCount = -5;//8; + saberent->bounceCount = -5; // 8; saberMoveBack(saberent, qtrue); saberent->s.pos.trType = TR_GRAVITY; - saberent->s.loopSound = 0; //kill this in case it was spinning. + saberent->s.loopSound = 0; // kill this in case it was spinning. saberent->s.loopIsSoundset = qfalse; - saberent->r.svFlags &= ~(SVF_NOCLIENT); //make sure the client is getting updates on where it is and such. + saberent->r.svFlags &= ~(SVF_NOCLIENT); // make sure the client is getting updates on where it is and such. saberent->touch = SaberBounceSound; saberent->think = DownedSaberThink; saberent->nextthink = level.time; - if (saberOwner != other) - { //if someone knocked it out of the air and it wasn't turned off, go in the direction they were facing. - if (other->inuse && other->client) - { + if (saberOwner != other) { // if someone knocked it out of the air and it wasn't turned off, go in the direction they were facing. + if (other->inuse && other->client) { vec3_t otherFwd; float deflectSpeed = 200; AngleVectors(other->client->ps.viewangles, otherFwd, 0, 0); - saberent->s.pos.trDelta[0] = otherFwd[0]*deflectSpeed; - saberent->s.pos.trDelta[1] = otherFwd[1]*deflectSpeed; - saberent->s.pos.trDelta[2] = otherFwd[2]*deflectSpeed; + saberent->s.pos.trDelta[0] = otherFwd[0] * deflectSpeed; + saberent->s.pos.trDelta[1] = otherFwd[1] * deflectSpeed; + saberent->s.pos.trDelta[2] = otherFwd[2] * deflectSpeed; } } trap->LinkEntity((sharedEntity_t *)saberent); - if (saberOwner->client->saber[0].soundOff) - { - G_Sound( saberent, CHAN_BODY, saberOwner->client->saber[0].soundOff ); + if (saberOwner->client->saber[0].soundOff) { + G_Sound(saberent, CHAN_BODY, saberOwner->client->saber[0].soundOff); } - if (saberOwner->client->saber[1].soundOff && - saberOwner->client->saber[1].model[0]) - { - G_Sound( saberOwner, CHAN_BODY, saberOwner->client->saber[1].soundOff ); + if (saberOwner->client->saber[1].soundOff && saberOwner->client->saber[1].model[0]) { + G_Sound(saberOwner, CHAN_BODY, saberOwner->client->saber[1].soundOff); } } -//sort of a silly macro I guess. But if I change anything in here I'll probably want it to be everywhere. -#define SABERINVALID (!saberent || !saberOwner || !other || !saberent->inuse || !saberOwner->inuse || !other->inuse || !saberOwner->client || !other->client || !saberOwner->client->ps.saberEntityNum || saberOwner->client->ps.saberLockTime > (level.time-100)) +// sort of a silly macro I guess. But if I change anything in here I'll probably want it to be everywhere. +#define SABERINVALID \ + (!saberent || !saberOwner || !other || !saberent->inuse || !saberOwner->inuse || !other->inuse || !saberOwner->client || !other->client || \ + !saberOwner->client->ps.saberEntityNum || saberOwner->client->ps.saberLockTime > (level.time - 100)) -void WP_SaberRemoveG2Model( gentity_t *saberent ) -{ - if ( saberent->ghoul2 ) - { - trap->G2API_RemoveGhoul2Models( &saberent->ghoul2 ); +void WP_SaberRemoveG2Model(gentity_t *saberent) { + if (saberent->ghoul2) { + trap->G2API_RemoveGhoul2Models(&saberent->ghoul2); } } -void WP_SaberAddG2Model( gentity_t *saberent, const char *saberModel, qhandle_t saberSkin ) -{ - WP_SaberRemoveG2Model( saberent ); - if ( saberModel && saberModel[0] ) - { +void WP_SaberAddG2Model(gentity_t *saberent, const char *saberModel, qhandle_t saberSkin) { + WP_SaberRemoveG2Model(saberent); + if (saberModel && saberModel[0]) { saberent->s.modelindex = G_ModelIndex(saberModel); + } else { + saberent->s.modelindex = G_ModelIndex(DEFAULT_SABER_MODEL); } - else - { - saberent->s.modelindex = G_ModelIndex( DEFAULT_SABER_MODEL ); - } - //FIXME: use customSkin? - trap->G2API_InitGhoul2Model( &saberent->ghoul2, saberModel, saberent->s.modelindex, saberSkin, 0, 0, 0 ); + // FIXME: use customSkin? + trap->G2API_InitGhoul2Model(&saberent->ghoul2, saberModel, saberent->s.modelindex, saberSkin, 0, 0, 0); } -//Make the saber go flying directly out of the owner's hand in the specified direction -qboolean saberKnockOutOfHand(gentity_t *saberent, gentity_t *saberOwner, vec3_t velocity) -{ - if (!saberent || !saberOwner || - !saberent->inuse || !saberOwner->inuse || - !saberOwner->client) - { +// Make the saber go flying directly out of the owner's hand in the specified direction +qboolean saberKnockOutOfHand(gentity_t *saberent, gentity_t *saberOwner, vec3_t velocity) { + if (!saberent || !saberOwner || !saberent->inuse || !saberOwner->inuse || !saberOwner->client) { return qfalse; } - if (!saberOwner->client->ps.saberEntityNum) - { //already gone + if (!saberOwner->client->ps.saberEntityNum) { // already gone return qfalse; } - if ((level.time - saberOwner->client->lastSaberStorageTime) > 50) - { //must have a reasonably updated saber base pos + if ((level.time - saberOwner->client->lastSaberStorageTime) > 50) { // must have a reasonably updated saber base pos return qfalse; } - if (saberOwner->client->ps.saberLockTime > (level.time-100)) - { + if (saberOwner->client->ps.saberLockTime > (level.time - 100)) { return qfalse; } - if ( (saberOwner->client->saber[0].saberFlags&SFL_NOT_DISARMABLE) ) - { + if ((saberOwner->client->saber[0].saberFlags & SFL_NOT_DISARMABLE)) { return qfalse; } saberOwner->client->ps.saberInFlight = qtrue; saberOwner->client->ps.saberEntityState = 1; - saberent->s.saberInFlight = qfalse;//qtrue; + saberent->s.saberInFlight = qfalse; // qtrue; saberent->s.pos.trType = TR_LINEAR; saberent->s.eType = ET_GENERAL; saberent->s.eFlags = 0; - WP_SaberAddG2Model( saberent, saberOwner->client->saber[0].model, saberOwner->client->saber[0].skin ); + WP_SaberAddG2Model(saberent, saberOwner->client->saber[0].model, saberOwner->client->saber[0].skin); saberent->s.modelGhoul2 = 127; @@ -6663,140 +5352,118 @@ qboolean saberKnockOutOfHand(gentity_t *saberent, gentity_t *saberOwner, vec3_t saberent->genericValue5 = 0; - VectorSet( saberent->r.mins, -24.0f, -24.0f, -8.0f ); - VectorSet( saberent->r.maxs, 24.0f, 24.0f, 8.0f ); + VectorSet(saberent->r.mins, -24.0f, -24.0f, -8.0f); + VectorSet(saberent->r.maxs, 24.0f, 24.0f, 8.0f); - saberent->s.genericenemyindex = saberOwner->s.number+1024; + saberent->s.genericenemyindex = saberOwner->s.number + 1024; saberent->s.weapon = WP_SABER; saberent->genericValue5 = 0; - G_SetOrigin(saberent, saberOwner->client->lastSaberBase_Always); //use this as opposed to the right hand bolt, - //because I don't want to risk reconstructing the skel again to get it here. And it isn't worth storing. + G_SetOrigin(saberent, saberOwner->client->lastSaberBase_Always); // use this as opposed to the right hand bolt, + // because I don't want to risk reconstructing the skel again to get it here. And it isn't worth storing. saberKnockDown(saberent, saberOwner, saberOwner); - VectorCopy(velocity, saberent->s.pos.trDelta); //override the velocity on the knocked away saber. + VectorCopy(velocity, saberent->s.pos.trDelta); // override the velocity on the knocked away saber. return qtrue; } -//Called at the result of a circle lock duel - the loser gets his saber tossed away and is put into a reflected attack anim -qboolean saberCheckKnockdown_DuelLoss(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) -{ +// Called at the result of a circle lock duel - the loser gets his saber tossed away and is put into a reflected attack anim +qboolean saberCheckKnockdown_DuelLoss(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) { vec3_t dif; float totalDistance = 1; float distScale = 6.5f; qboolean validMomentum = qtrue; - int disarmChance = 1; + int disarmChance = 1; - if (SABERINVALID) - { + if (SABERINVALID) { return qfalse; } VectorClear(dif); - if (!other->client->olderIsValid || (level.time - other->client->lastSaberStorageTime) >= 200) - { //see if the spots are valid + if (!other->client->olderIsValid || (level.time - other->client->lastSaberStorageTime) >= 200) { // see if the spots are valid validMomentum = qfalse; } - if (validMomentum) - { - //Get the difference + if (validMomentum) { + // Get the difference VectorSubtract(other->client->lastSaberBase_Always, other->client->olderSaberBase, dif); totalDistance = VectorNormalize(dif); - if (!totalDistance) - { //fine, try our own - if (!saberOwner->client->olderIsValid || (level.time - saberOwner->client->lastSaberStorageTime) >= 200) - { + if (!totalDistance) { // fine, try our own + if (!saberOwner->client->olderIsValid || (level.time - saberOwner->client->lastSaberStorageTime) >= 200) { validMomentum = qfalse; } - if (validMomentum) - { + if (validMomentum) { VectorSubtract(saberOwner->client->lastSaberBase_Always, saberOwner->client->olderSaberBase, dif); totalDistance = VectorNormalize(dif); } } - if (validMomentum) - { - if (!totalDistance) - { //try the difference between the two blades + if (validMomentum) { + if (!totalDistance) { // try the difference between the two blades VectorSubtract(saberOwner->client->lastSaberBase_Always, other->client->lastSaberBase_Always, dif); totalDistance = VectorNormalize(dif); } - if (totalDistance) - { //if we still have no difference somehow, just let it fall to the ground when the time comes. - if (totalDistance < 20) - { + if (totalDistance) { // if we still have no difference somehow, just let it fall to the ground when the time comes. + if (totalDistance < 20) { totalDistance = 20; } - VectorScale(dif, totalDistance*distScale, dif); + VectorScale(dif, totalDistance * distScale, dif); } } } - saberOwner->client->ps.saberMove = LS_V1_BL; //rwwFIXMEFIXME: Ideally check which lock it was exactly and use the proper anim (same goes for the attacker) + saberOwner->client->ps.saberMove = LS_V1_BL; // rwwFIXMEFIXME: Ideally check which lock it was exactly and use the proper anim (same goes for the attacker) saberOwner->client->ps.saberBlocked = BLOCKED_BOUNCE_MOVE; - if ( other && other->client ) - { + if (other && other->client) { disarmChance += other->client->saber[0].disarmBonus; - if ( other->client->saber[1].model[0] - && !other->client->ps.saberHolstered ) - { + if (other->client->saber[1].model[0] && !other->client->ps.saberHolstered) { disarmChance += other->client->saber[1].disarmBonus; } } - if ( Q_irand( 0, disarmChance ) ) - { + if (Q_irand(0, disarmChance)) { return saberKnockOutOfHand(saberent, saberOwner, dif); - } - else - { + } else { return qfalse; } } -//Called when we want to try knocking the saber out of the owner's hand upon them going into a broken parry. -//Also called on reflected attacks. -qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) -{ +// Called when we want to try knocking the saber out of the owner's hand upon them going into a broken parry. +// Also called on reflected attacks. +qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) { int myAttack; int otherAttack; qboolean doKnock = qfalse; - int disarmChance = 1; + int disarmChance = 1; - if (SABERINVALID) - { + if (SABERINVALID) { return qfalse; } - //Neither gets an advantage based on attack state, when it comes to knocking - //saber out of hand. + // Neither gets an advantage based on attack state, when it comes to knocking + // saber out of hand. myAttack = G_SaberAttackPower(saberOwner, qfalse); otherAttack = G_SaberAttackPower(other, qfalse); - if (!other->client->olderIsValid || (level.time - other->client->lastSaberStorageTime) >= 200) - { //if we don't know which way to throw the saber based on momentum between saber positions, just don't throw it + if (!other->client->olderIsValid || + (level.time - other->client->lastSaberStorageTime) >= + 200) { // if we don't know which way to throw the saber based on momentum between saber positions, just don't throw it return qfalse; } - //only knock the saber out of the hand if they're in a stronger stance I suppose. Makes strong more advantageous. - if (otherAttack > myAttack+1 && Q_irand(1, 10) <= 7) - { //This would be, say, strong stance against light stance. + // only knock the saber out of the hand if they're in a stronger stance I suppose. Makes strong more advantageous. + if (otherAttack > myAttack + 1 && Q_irand(1, 10) <= 7) { // This would be, say, strong stance against light stance. doKnock = qtrue; - } - else if (otherAttack > myAttack && Q_irand(1, 10) <= 3) - { //Strong vs. medium, medium vs. light + } else if (otherAttack > myAttack && Q_irand(1, 10) <= 3) { // Strong vs. medium, medium vs. light doKnock = qtrue; } - if (doKnock) - { + if (doKnock) { vec3_t dif; float totalDistance; float distScale = 6.5f; @@ -6804,10 +5471,10 @@ qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOw VectorSubtract(other->client->lastSaberBase_Always, other->client->olderSaberBase, dif); totalDistance = VectorNormalize(dif); - if (!totalDistance) - { //fine, try our own - if (!saberOwner->client->olderIsValid || (level.time - saberOwner->client->lastSaberStorageTime) >= 200) - { //if we don't know which way to throw the saber based on momentum between saber positions, just don't throw it + if (!totalDistance) { // fine, try our own + if (!saberOwner->client->olderIsValid || + (level.time - saberOwner->client->lastSaberStorageTime) >= + 200) { // if we don't know which way to throw the saber based on momentum between saber positions, just don't throw it return qfalse; } @@ -6815,28 +5482,22 @@ qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOw totalDistance = VectorNormalize(dif); } - if (!totalDistance) - { //...forget it then. + if (!totalDistance) { //...forget it then. return qfalse; } - if (totalDistance < 20) - { + if (totalDistance < 20) { totalDistance = 20; } - VectorScale(dif, totalDistance*distScale, dif); + VectorScale(dif, totalDistance * distScale, dif); - if ( other && other->client ) - { + if (other && other->client) { disarmChance += other->client->saber[0].disarmBonus; - if ( other->client->saber[1].model[0] - && !other->client->ps.saberHolstered ) - { + if (other->client->saber[1].model[0] && !other->client->ps.saberHolstered) { disarmChance += other->client->saber[1].disarmBonus; } } - if ( Q_irand( 0, disarmChance ) ) - { + if (Q_irand(0, disarmChance)) { return saberKnockOutOfHand(saberent, saberOwner, dif); } } @@ -6844,32 +5505,24 @@ qboolean saberCheckKnockdown_BrokenParry(gentity_t *saberent, gentity_t *saberOw return qfalse; } -qboolean BG_InExtraDefenseSaberMove( int move ); +qboolean BG_InExtraDefenseSaberMove(int move); -//Called upon an enemy actually slashing into a thrown saber -qboolean saberCheckKnockdown_Smashed(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other, int damage) -{ - if (SABERINVALID) - { +// Called upon an enemy actually slashing into a thrown saber +qboolean saberCheckKnockdown_Smashed(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other, int damage) { + if (SABERINVALID) { return qfalse; } - if (!saberOwner->client->ps.saberInFlight) - { //can only do this if the saber is already actually in flight + if (!saberOwner->client->ps.saberInFlight) { // can only do this if the saber is already actually in flight return qfalse; } - if ( other - && other->inuse - && other->client - && BG_InExtraDefenseSaberMove( other->client->ps.saberMove ) ) - { //make sure the blow was strong enough + if (other && other->inuse && other->client && BG_InExtraDefenseSaberMove(other->client->ps.saberMove)) { // make sure the blow was strong enough saberKnockDown(saberent, saberOwner, other); return qtrue; } - if (damage > 10) - { //make sure the blow was strong enough + if (damage > 10) { // make sure the blow was strong enough saberKnockDown(saberent, saberOwner, other); return qtrue; } @@ -6877,34 +5530,28 @@ qboolean saberCheckKnockdown_Smashed(gentity_t *saberent, gentity_t *saberOwner, return qfalse; } -//Called upon blocking a thrown saber. If the throw level compared to the blocker's defense level -//is inferior, or equal and a random factor is met, then the saber will be tossed to the ground. -qboolean saberCheckKnockdown_Thrown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) -{ +// Called upon blocking a thrown saber. If the throw level compared to the blocker's defense level +// is inferior, or equal and a random factor is met, then the saber will be tossed to the ground. +qboolean saberCheckKnockdown_Thrown(gentity_t *saberent, gentity_t *saberOwner, gentity_t *other) { int throwLevel = 0; int defenLevel = 0; qboolean tossIt = qfalse; - if (SABERINVALID) - { + if (SABERINVALID) { return qfalse; } defenLevel = other->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE]; throwLevel = saberOwner->client->ps.fd.forcePowerLevel[FP_SABERTHROW]; - if (defenLevel > throwLevel) - { + if (defenLevel > throwLevel) { tossIt = qtrue; - } - else if (defenLevel == throwLevel && Q_irand(1, 10) <= 4) - { + } else if (defenLevel == throwLevel && Q_irand(1, 10) <= 4) { tossIt = qtrue; } - //otherwise don't + // otherwise don't - if (tossIt) - { + if (tossIt) { saberKnockDown(saberent, saberOwner, other); return qtrue; } @@ -6912,14 +5559,12 @@ qboolean saberCheckKnockdown_Thrown(gentity_t *saberent, gentity_t *saberOwner, return qfalse; } -void saberBackToOwner(gentity_t *saberent) -{ +void saberBackToOwner(gentity_t *saberent) { gentity_t *saberOwner = &g_entities[saberent->r.ownerNum]; vec3_t dir; float ownerLen; - if (saberent->r.ownerNum == ENTITYNUM_NONE) - { + if (saberent->r.ownerNum == ENTITYNUM_NONE) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -6927,10 +5572,7 @@ void saberBackToOwner(gentity_t *saberent) return; } - if (!saberOwner->inuse || - !saberOwner->client || - saberOwner->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (!saberOwner->inuse || !saberOwner->client || saberOwner->client->sess.sessionTeam == TEAM_SPECTATOR) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -6938,16 +5580,13 @@ void saberBackToOwner(gentity_t *saberent) return; } - if (saberOwner->health < 1 || !saberOwner->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) - { //He's dead, just go back to our normal saber status + if (saberOwner->health < 1 || !saberOwner->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { // He's dead, just go back to our normal saber status saberent->touch = SaberGotHit; saberent->think = SaberUpdateSelf; saberent->genericValue5 = 0; saberent->nextthink = level.time; - if (saberOwner->client && - saberOwner->client->saber[0].soundOff) - { + if (saberOwner->client && saberOwner->client->saber[0].soundOff) { G_Sound(saberent, CHAN_AUTO, saberOwner->client->saber[0].soundOff); } MakeDeadSaber(saberent); @@ -6957,7 +5596,7 @@ void saberBackToOwner(gentity_t *saberent) SetSaberBoxSize(saberent); saberent->s.loopSound = 0; saberent->s.loopIsSoundset = qfalse; - WP_SaberRemoveG2Model( saberent ); + WP_SaberRemoveG2Model(saberent); saberOwner->client->ps.saberInFlight = qfalse; saberOwner->client->ps.saberEntityState = 0; @@ -6967,9 +5606,8 @@ void saberBackToOwner(gentity_t *saberent) return; } - //make sure this is set alright - assert(saberOwner->client->ps.saberEntityNum == saberent->s.number || - saberOwner->client->saberStoredIndex == saberent->s.number); + // make sure this is set alright + assert(saberOwner->client->ps.saberEntityNum == saberent->s.number || saberOwner->client->saberStoredIndex == saberent->s.number); saberOwner->client->ps.saberEntityNum = saberent->s.number; saberent->r.contents = CONTENTS_LIGHTSABER; @@ -6978,8 +5616,7 @@ void saberBackToOwner(gentity_t *saberent) ownerLen = VectorLength(dir); - if (saberent->speed < level.time) - { + if (saberent->speed < level.time) { float baseSpeed = 900; VectorNormalize(dir); @@ -6987,34 +5624,25 @@ void saberBackToOwner(gentity_t *saberent) saberMoveBack(saberent, qtrue); VectorCopy(saberent->r.currentOrigin, saberent->s.pos.trBase); - if (saberOwner->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= FORCE_LEVEL_3) - { //allow players with high saber throw rank to control the return speed of the saber + if (saberOwner->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= + FORCE_LEVEL_3) { // allow players with high saber throw rank to control the return speed of the saber baseSpeed = 900; - saberent->speed = level.time;// + 200; - } - else - { + saberent->speed = level.time; // + 200; + } else { baseSpeed = 700; saberent->speed = level.time + 50; } - //Gradually slow down as it approaches, so it looks smoother coming into the hand. - if (ownerLen < 64) - { - VectorScale(dir, baseSpeed-200, saberent->s.pos.trDelta ); - } - else if (ownerLen < 128) - { - VectorScale(dir, baseSpeed-150, saberent->s.pos.trDelta ); - } - else if (ownerLen < 256) - { - VectorScale(dir, baseSpeed-100, saberent->s.pos.trDelta ); - } - else - { - VectorScale(dir, baseSpeed, saberent->s.pos.trDelta ); + // Gradually slow down as it approaches, so it looks smoother coming into the hand. + if (ownerLen < 64) { + VectorScale(dir, baseSpeed - 200, saberent->s.pos.trDelta); + } else if (ownerLen < 128) { + VectorScale(dir, baseSpeed - 150, saberent->s.pos.trDelta); + } else if (ownerLen < 256) { + VectorScale(dir, baseSpeed - 100, saberent->s.pos.trDelta); + } else { + VectorScale(dir, baseSpeed, saberent->s.pos.trDelta); } saberent->s.pos.trTime = level.time; @@ -7028,20 +5656,16 @@ void saberBackToOwner(gentity_t *saberent) saberent->s.loopIsSoundset = qfalse; } */ - //I'm just doing this now. I don't really like the spin on the way back. And it does weird stuff with the new saber-knocked-away code. - if (saberOwner->client->ps.saberEntityNum == saberent->s.number) - { - if ( !(saberOwner->client->saber[0].saberFlags&SFL_RETURN_DAMAGE) - || saberOwner->client->ps.saberHolstered ) - { + // I'm just doing this now. I don't really like the spin on the way back. And it does weird stuff with the new saber-knocked-away code. + if (saberOwner->client->ps.saberEntityNum == saberent->s.number) { + if (!(saberOwner->client->saber[0].saberFlags & SFL_RETURN_DAMAGE) || saberOwner->client->ps.saberHolstered) { saberent->s.saberInFlight = qfalse; } saberent->s.loopSound = saberOwner->client->saber[0].soundLoop; saberent->s.loopIsSoundset = qfalse; - if (ownerLen <= 32) - { - G_Sound( saberent, CHAN_AUTO, G_SoundIndex( "sound/weapons/saber/saber_catch.wav" ) ); + if (ownerLen <= 32) { + G_Sound(saberent, CHAN_AUTO, G_SoundIndex("sound/weapons/saber/saber_catch.wav")); saberOwner->client->ps.saberInFlight = qfalse; saberOwner->client->ps.saberEntityState = 0; @@ -7053,17 +5677,14 @@ void saberBackToOwner(gentity_t *saberent) saberent->think = SaberUpdateSelf; saberent->genericValue5 = 0; saberent->nextthink = level.time + 50; - WP_SaberRemoveG2Model( saberent ); + WP_SaberRemoveG2Model(saberent); return; } - if (!saberent->s.saberInFlight) - { + if (!saberent->s.saberInFlight) { saberCheckRadiusDamage(saberent, 1); - } - else - { + } else { saberCheckRadiusDamage(saberent, 2); } @@ -7075,12 +5696,10 @@ void saberBackToOwner(gentity_t *saberent) void saberFirstThrown(gentity_t *saberent); -void thrownSaberTouch (gentity_t *saberent, gentity_t *other, trace_t *trace) -{ +void thrownSaberTouch(gentity_t *saberent, gentity_t *other, trace_t *trace) { gentity_t *hitEnt = other; - if (other && other->s.number == saberent->r.ownerNum) - { + if (other && other->s.number == saberent->r.ownerNum) { return; } VectorClear(saberent->s.pos.trDelta); @@ -7096,15 +5715,12 @@ void thrownSaberTouch (gentity_t *saberent, gentity_t *other, trace_t *trace) saberent->think = saberBackToOwner; saberent->nextthink = level.time; - if (other && other->r.ownerNum < MAX_CLIENTS && - (other->r.contents & CONTENTS_LIGHTSABER) && - g_entities[other->r.ownerNum].client && - g_entities[other->r.ownerNum].inuse) - { + if (other && other->r.ownerNum < MAX_CLIENTS && (other->r.contents & CONTENTS_LIGHTSABER) && g_entities[other->r.ownerNum].client && + g_entities[other->r.ownerNum].inuse) { hitEnt = &g_entities[other->r.ownerNum]; } - //we'll skip the dist check, since we don't really care about that (we just hit it physically) + // we'll skip the dist check, since we don't really care about that (we just hit it physically) CheckThrownSaberDamaged(saberent, &g_entities[saberent->r.ownerNum], hitEnt, 256, 0, qtrue); saberent->speed = 0; @@ -7112,14 +5728,12 @@ void thrownSaberTouch (gentity_t *saberent, gentity_t *other, trace_t *trace) #define SABER_MAX_THROW_DISTANCE 700 -void saberFirstThrown(gentity_t *saberent) -{ - vec3_t vSub; - float vLen; - gentity_t *saberOwn = &g_entities[saberent->r.ownerNum]; +void saberFirstThrown(gentity_t *saberent) { + vec3_t vSub; + float vLen; + gentity_t *saberOwn = &g_entities[saberent->r.ownerNum]; - if (saberent->r.ownerNum == ENTITYNUM_NONE) - { + if (saberent->r.ownerNum == ENTITYNUM_NONE) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -7127,11 +5741,7 @@ void saberFirstThrown(gentity_t *saberent) return; } - if (!saberOwn || - !saberOwn->inuse || - !saberOwn->client || - saberOwn->client->sess.sessionTeam == TEAM_SPECTATOR) - { + if (!saberOwn || !saberOwn->inuse || !saberOwn->client || saberOwn->client->sess.sessionTeam == TEAM_SPECTATOR) { MakeDeadSaber(saberent); saberent->think = G_FreeEntity; @@ -7139,16 +5749,13 @@ void saberFirstThrown(gentity_t *saberent) return; } - if (saberOwn->health < 1 || !saberOwn->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) - { //He's dead, just go back to our normal saber status + if (saberOwn->health < 1 || !saberOwn->client->ps.fd.forcePowerLevel[FP_SABER_OFFENSE]) { // He's dead, just go back to our normal saber status saberent->touch = SaberGotHit; saberent->think = SaberUpdateSelf; saberent->genericValue5 = 0; saberent->nextthink = level.time; - if (saberOwn->client && - saberOwn->client->saber[0].soundOff) - { + if (saberOwn->client && saberOwn->client->saber[0].soundOff) { G_Sound(saberent, CHAN_AUTO, saberOwn->client->saber[0].soundOff); } MakeDeadSaber(saberent); @@ -7158,7 +5765,7 @@ void saberFirstThrown(gentity_t *saberent) SetSaberBoxSize(saberent); saberent->s.loopSound = 0; saberent->s.loopIsSoundset = qfalse; - WP_SaberRemoveG2Model( saberent ); + WP_SaberRemoveG2Model(saberent); saberOwn->client->ps.saberInFlight = qfalse; saberOwn->client->ps.saberEntityState = 0; @@ -7168,28 +5775,22 @@ void saberFirstThrown(gentity_t *saberent) return; } - if ((level.time - saberOwn->client->ps.saberDidThrowTime) > 500) - { - if (!(saberOwn->client->buttons & BUTTON_ALT_ATTACK)) - { //If owner releases altattack 500ms or later after throwing saber, it autoreturns + if ((level.time - saberOwn->client->ps.saberDidThrowTime) > 500) { + if (!(saberOwn->client->buttons & BUTTON_ALT_ATTACK)) { // If owner releases altattack 500ms or later after throwing saber, it autoreturns thrownSaberTouch(saberent, saberent, NULL); goto runMin; - } - else if ((level.time - saberOwn->client->ps.saberDidThrowTime) > 6000) - { //if it's out longer than 6 seconds, return it + } else if ((level.time - saberOwn->client->ps.saberDidThrowTime) > 6000) { // if it's out longer than 6 seconds, return it thrownSaberTouch(saberent, saberent, NULL); goto runMin; } } - if (BG_HasYsalamiri(level.gametype, &saberOwn->client->ps)) - { + if (BG_HasYsalamiri(level.gametype, &saberOwn->client->ps)) { thrownSaberTouch(saberent, saberent, NULL); goto runMin; } - if (!BG_CanUseFPNow(level.gametype, &saberOwn->client->ps, level.time, FP_SABERTHROW)) - { + if (!BG_CanUseFPNow(level.gametype, &saberOwn->client->ps, level.time, FP_SABERTHROW)) { thrownSaberTouch(saberent, saberent, NULL); goto runMin; } @@ -7197,15 +5798,13 @@ void saberFirstThrown(gentity_t *saberent) VectorSubtract(saberOwn->client->ps.origin, saberent->r.currentOrigin, vSub); vLen = VectorLength(vSub); - if (vLen >= (SABER_MAX_THROW_DISTANCE*saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW])) - { + if (vLen >= (SABER_MAX_THROW_DISTANCE * saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW])) { thrownSaberTouch(saberent, saberent, NULL); goto runMin; } if (saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= FORCE_LEVEL_2 && - saberent->speed < level.time) - { //if owner is rank 3 in saber throwing, the saber goes where he points + saberent->speed < level.time) { // if owner is rank 3 in saber throwing, the saber goes where he points vec3_t fwd, traceFrom, traceTo, dir; trace_t tr; @@ -7215,19 +5814,17 @@ void saberFirstThrown(gentity_t *saberent) traceFrom[2] += saberOwn->client->ps.viewheight; VectorCopy(traceFrom, traceTo); - traceTo[0] += fwd[0]*4096; - traceTo[1] += fwd[1]*4096; - traceTo[2] += fwd[2]*4096; + traceTo[0] += fwd[0] * 4096; + traceTo[1] += fwd[1] * 4096; + traceTo[2] += fwd[2] * 4096; saberMoveBack(saberent, qfalse); VectorCopy(saberent->r.currentOrigin, saberent->s.pos.trBase); - if (saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= FORCE_LEVEL_3) - { //if highest saber throw rank, we can direct the saber toward players directly by looking at them + if (saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= + FORCE_LEVEL_3) { // if highest saber throw rank, we can direct the saber toward players directly by looking at them trap->Trace(&tr, traceFrom, NULL, NULL, traceTo, saberOwn->s.number, MASK_PLAYERSOLID, qfalse, 0, 0); - } - else - { + } else { trap->Trace(&tr, traceFrom, NULL, NULL, traceTo, saberOwn->s.number, MASK_SOLID, qfalse, 0, 0); } @@ -7235,15 +5832,13 @@ void saberFirstThrown(gentity_t *saberent) VectorNormalize(dir); - VectorScale(dir, 500, saberent->s.pos.trDelta ); + VectorScale(dir, 500, saberent->s.pos.trDelta); saberent->s.pos.trTime = level.time; - if (saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= FORCE_LEVEL_3) - { //we'll treat them to a quicker update rate if their throw rank is high enough + if (saberOwn->client->ps.fd.forcePowerLevel[FP_SABERTHROW] >= + FORCE_LEVEL_3) { // we'll treat them to a quicker update rate if their throw rank is high enough saberent->speed = level.time + 100; - } - else - { + } else { saberent->speed = level.time + 400; } } @@ -7254,13 +5849,11 @@ void saberFirstThrown(gentity_t *saberent) G_RunObject(saberent); } -void UpdateClientRenderBolts(gentity_t *self, vec3_t renderOrigin, vec3_t renderAngles) -{ +void UpdateClientRenderBolts(gentity_t *self, vec3_t renderOrigin, vec3_t renderAngles) { mdxaBone_t boltMatrix; renderInfo_t *ri = &self->client->renderInfo; - if (!self->ghoul2) - { + if (!self->ghoul2) { VectorCopy(self->client->ps.origin, ri->headPoint); VectorCopy(self->client->ps.origin, ri->handRPoint); VectorCopy(self->client->ps.origin, ri->handLPoint); @@ -7268,46 +5861,44 @@ void UpdateClientRenderBolts(gentity_t *self, vec3_t renderOrigin, vec3_t render VectorCopy(self->client->ps.origin, ri->crotchPoint); VectorCopy(self->client->ps.origin, ri->footRPoint); VectorCopy(self->client->ps.origin, ri->footLPoint); - } - else - { - //head + } else { + // head trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->headBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->headPoint[0] = boltMatrix.matrix[0][3]; ri->headPoint[1] = boltMatrix.matrix[1][3]; ri->headPoint[2] = boltMatrix.matrix[2][3]; - //right hand + // right hand trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handRBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->handRPoint[0] = boltMatrix.matrix[0][3]; ri->handRPoint[1] = boltMatrix.matrix[1][3]; ri->handRPoint[2] = boltMatrix.matrix[2][3]; - //left hand + // left hand trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handLBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->handLPoint[0] = boltMatrix.matrix[0][3]; ri->handLPoint[1] = boltMatrix.matrix[1][3]; ri->handLPoint[2] = boltMatrix.matrix[2][3]; - //chest + // chest trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->torsoBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->torsoPoint[0] = boltMatrix.matrix[0][3]; ri->torsoPoint[1] = boltMatrix.matrix[1][3]; ri->torsoPoint[2] = boltMatrix.matrix[2][3]; - //crotch + // crotch trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->crotchBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->crotchPoint[0] = boltMatrix.matrix[0][3]; ri->crotchPoint[1] = boltMatrix.matrix[1][3]; ri->crotchPoint[2] = boltMatrix.matrix[2][3]; - //right foot + // right foot trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->footRBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->footRPoint[0] = boltMatrix.matrix[0][3]; ri->footRPoint[1] = boltMatrix.matrix[1][3]; ri->footRPoint[2] = boltMatrix.matrix[2][3]; - //left foot + // left foot trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->footLBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->footLPoint[0] = boltMatrix.matrix[0][3]; ri->footLPoint[1] = boltMatrix.matrix[1][3]; @@ -7317,15 +5908,13 @@ void UpdateClientRenderBolts(gentity_t *self, vec3_t renderOrigin, vec3_t render self->client->renderInfo.boltValidityTime = level.time; } -void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderAngles) -{ +void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderAngles) { renderInfo_t *ri = &self->client->renderInfo; - if ( ri->mPCalcTime < level.time ) - { - //We're just going to give rough estimates on most of this stuff, - //it's not like most of it matters. + if (ri->mPCalcTime < level.time) { + // We're just going to give rough estimates on most of this stuff, + // it's not like most of it matters. - #if 0 //#if 0'd since it's a waste setting all this to 0 each frame. +#if 0 //#if 0'd since it's a waste setting all this to 0 each frame. //Should you wish to make any of this valid then feel free to do so. ri->headYawRangeLeft = ri->headYawRangeRight = ri->headPitchRangeUp = ri->headPitchRangeDown = 0; ri->torsoYawRangeLeft = ri->torsoYawRangeRight = ri->torsoPitchRangeUp = ri->torsoPitchRangeDown = 0; @@ -7343,16 +5932,13 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA //VectorClear(ri->eyeAngles); ri->legsYaw = 0; - #endif +#endif - if (self->ghoul2 && - self->ghoul2 != ri->lastG2) - { //the g2 instance changed, so update all the bolts. - //rwwFIXMEFIXME: Base on skeleton used? Assuming humanoid currently. + if (self->ghoul2 && self->ghoul2 != ri->lastG2) { // the g2 instance changed, so update all the bolts. + // rwwFIXMEFIXME: Base on skeleton used? Assuming humanoid currently. ri->lastG2 = self->ghoul2; - if (self->localAnimIndex <= 1) - { + if (self->localAnimIndex <= 1) { ri->headBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*head_eyes"); ri->handRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_hand"); ri->handLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_hand"); @@ -7361,9 +5947,7 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA ri->footRBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*r_leg_foot"); ri->footLBolt = trap->G2API_AddBolt(self->ghoul2, 0, "*l_leg_foot"); ri->motionBolt = trap->G2API_AddBolt(self->ghoul2, 0, "Motion"); - } - else - { + } else { ri->headBolt = -1; ri->handRBolt = -1; ri->handLBolt = -1; @@ -7377,20 +5961,18 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA ri->lastG2 = self->ghoul2; } - VectorCopy( self->client->ps.viewangles, self->client->renderInfo.eyeAngles ); + VectorCopy(self->client->ps.viewangles, self->client->renderInfo.eyeAngles); - //we'll just say the legs/torso are whatever the first frame of our current anim is. + // we'll just say the legs/torso are whatever the first frame of our current anim is. ri->torsoFrame = bgAllAnims[self->localAnimIndex].anims[self->client->ps.torsoAnim].firstFrame; ri->legsFrame = bgAllAnims[self->localAnimIndex].anims[self->client->ps.legsAnim].firstFrame; - if (g_debugServerSkel.integer) - { //Alright, I was doing this, but it's just too slow to do every frame. - //From now on if we want this data to be valid we're going to have to make a verify call for it before - //accessing it. I'm only doing this now if we want to debug the server skel by drawing lines from bolt - //positions every frame. + if (g_debugServerSkel.integer) { // Alright, I was doing this, but it's just too slow to do every frame. + // From now on if we want this data to be valid we're going to have to make a verify call for it before + // accessing it. I'm only doing this now if we want to debug the server skel by drawing lines from bolt + // positions every frame. mdxaBone_t boltMatrix; - if (!self->ghoul2) - { + if (!self->ghoul2) { VectorCopy(self->client->ps.origin, ri->headPoint); VectorCopy(self->client->ps.origin, ri->handRPoint); VectorCopy(self->client->ps.origin, ri->handLPoint); @@ -7398,53 +5980,51 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA VectorCopy(self->client->ps.origin, ri->crotchPoint); VectorCopy(self->client->ps.origin, ri->footRPoint); VectorCopy(self->client->ps.origin, ri->footLPoint); - } - else - { - //head + } else { + // head trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->headBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->headPoint[0] = boltMatrix.matrix[0][3]; ri->headPoint[1] = boltMatrix.matrix[1][3]; ri->headPoint[2] = boltMatrix.matrix[2][3]; - //right hand + // right hand trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handRBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->handRPoint[0] = boltMatrix.matrix[0][3]; ri->handRPoint[1] = boltMatrix.matrix[1][3]; ri->handRPoint[2] = boltMatrix.matrix[2][3]; - //left hand + // left hand trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handLBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->handLPoint[0] = boltMatrix.matrix[0][3]; ri->handLPoint[1] = boltMatrix.matrix[1][3]; ri->handLPoint[2] = boltMatrix.matrix[2][3]; - //chest + // chest trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->torsoBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->torsoPoint[0] = boltMatrix.matrix[0][3]; ri->torsoPoint[1] = boltMatrix.matrix[1][3]; ri->torsoPoint[2] = boltMatrix.matrix[2][3]; - //crotch + // crotch trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->crotchBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->crotchPoint[0] = boltMatrix.matrix[0][3]; ri->crotchPoint[1] = boltMatrix.matrix[1][3]; ri->crotchPoint[2] = boltMatrix.matrix[2][3]; - //right foot + // right foot trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->footRBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->footRPoint[0] = boltMatrix.matrix[0][3]; ri->footRPoint[1] = boltMatrix.matrix[1][3]; ri->footRPoint[2] = boltMatrix.matrix[2][3]; - //left foot + // left foot trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->footLBolt, &boltMatrix, renderAngles, renderOrigin, level.time, NULL, self->modelScale); ri->footLPoint[0] = boltMatrix.matrix[0][3]; ri->footLPoint[1] = boltMatrix.matrix[1][3]; ri->footLPoint[2] = boltMatrix.matrix[2][3]; } - //Now draw the skel for debug + // Now draw the skel for debug G_TestLine(ri->headPoint, ri->torsoPoint, 0x000000ff, 50); G_TestLine(ri->torsoPoint, ri->handRPoint, 0x000000ff, 50); G_TestLine(ri->torsoPoint, ri->handLPoint, 0x000000ff, 50); @@ -7453,7 +6033,7 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA G_TestLine(ri->crotchPoint, ri->footLPoint, 0x000000ff, 50); } - //muzzle point calc (we are going to be cheap here) + // muzzle point calc (we are going to be cheap here) VectorCopy(ri->muzzlePoint, ri->muzzlePointOld); VectorCopy(self->client->ps.origin, ri->muzzlePoint); VectorCopy(ri->muzzleDir, ri->muzzleDirOld); @@ -7466,98 +6046,76 @@ void UpdateClientRenderinfo(gentity_t *self, vec3_t renderOrigin, vec3_t renderA } #define STAFF_KICK_RANGE 16 -extern void G_GetBoltPosition( gentity_t *self, int boltIndex, vec3_t pos, int modelIndex ); //NPC_utils.c +extern void G_GetBoltPosition(gentity_t *self, int boltIndex, vec3_t pos, int modelIndex); // NPC_utils.c -extern qboolean BG_InKnockDown( int anim ); -static qboolean G_KickDownable(gentity_t *ent) -{ - if (!d_saberKickTweak.integer) - { +extern qboolean BG_InKnockDown(int anim); +static qboolean G_KickDownable(gentity_t *ent) { + if (!d_saberKickTweak.integer) { return qtrue; } - if (!ent || !ent->inuse || !ent->client) - { + if (!ent || !ent->inuse || !ent->client) { return qfalse; } - if (BG_InKnockDown(ent->client->ps.legsAnim) || - BG_InKnockDown(ent->client->ps.torsoAnim)) - { + if (BG_InKnockDown(ent->client->ps.legsAnim) || BG_InKnockDown(ent->client->ps.torsoAnim)) { return qfalse; } - if (ent->client->ps.weaponTime <= 0 && - ent->client->ps.weapon == WP_SABER && - ent->client->ps.groundEntityNum != ENTITYNUM_NONE) - { + if (ent->client->ps.weaponTime <= 0 && ent->client->ps.weapon == WP_SABER && ent->client->ps.groundEntityNum != ENTITYNUM_NONE) { return qfalse; } return qtrue; } -static void G_TossTheMofo(gentity_t *ent, vec3_t tossDir, float tossStr) -{ - if (!ent->inuse || !ent->client) - { //no good +static void G_TossTheMofo(gentity_t *ent, vec3_t tossDir, float tossStr) { + if (!ent->inuse || !ent->client) { // no good return; } - if (ent->s.eType == ET_NPC && ent->s.NPC_class == CLASS_VEHICLE) - { //no, silly + if (ent->s.eType == ET_NPC && ent->s.NPC_class == CLASS_VEHICLE) { // no, silly return; } VectorMA(ent->client->ps.velocity, tossStr, tossDir, ent->client->ps.velocity); ent->client->ps.velocity[2] = 200; - if (ent->health > 0 && ent->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && - BG_KnockDownable(&ent->client->ps) && - G_KickDownable(ent)) - { //if they are alive, knock them down I suppose + if (ent->health > 0 && ent->client->ps.forceHandExtend != HANDEXTEND_KNOCKDOWN && BG_KnockDownable(&ent->client->ps) && + G_KickDownable(ent)) { // if they are alive, knock them down I suppose ent->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; ent->client->ps.forceHandExtendTime = level.time + 700; - ent->client->ps.forceDodgeAnim = 0; //this toggles between 1 and 0, when it's 1 we should play the get up anim - //ent->client->ps.quickerGetup = qtrue; + ent->client->ps.forceDodgeAnim = 0; // this toggles between 1 and 0, when it's 1 we should play the get up anim + // ent->client->ps.quickerGetup = qtrue; } } -static gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t kickEnd, int kickDamage, float kickPush ) -{ - vec3_t traceOrg, traceEnd, kickMins, kickMaxs; - trace_t trace; - gentity_t *hitEnt = NULL; +static gentity_t *G_KickTrace(gentity_t *ent, vec3_t kickDir, float kickDist, vec3_t kickEnd, int kickDamage, float kickPush) { + vec3_t traceOrg, traceEnd, kickMins, kickMaxs; + trace_t trace; + gentity_t *hitEnt = NULL; VectorSet(kickMins, -2.0f, -2.0f, -2.0f); VectorSet(kickMaxs, 2.0f, 2.0f, 2.0f); - //FIXME: variable kick height? - if ( kickEnd && !VectorCompare( kickEnd, vec3_origin ) ) - {//they passed us the end point of the trace, just use that - //this makes the trace flat - VectorSet( traceOrg, ent->r.currentOrigin[0], ent->r.currentOrigin[1], kickEnd[2] ); - VectorCopy( kickEnd, traceEnd ); - } - else - {//extrude - VectorSet( traceOrg, ent->r.currentOrigin[0], ent->r.currentOrigin[1], ent->r.currentOrigin[2]+ent->r.maxs[2]*0.5f ); - VectorMA( traceOrg, kickDist, kickDir, traceEnd ); - } - - if (d_saberKickTweak.integer) - { - trap->Trace( &trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_THICK|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); - } - else - { - trap->Trace( &trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0 ); - } - - //G_TestLine(traceOrg, traceEnd, 0x0000ff, 5000); - if ( trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid ) - { - if (ent->client->jediKickTime > level.time) - { - if (trace.entityNum == ent->client->jediKickIndex) - { //we are hitting the same ent we last hit in this same anim, don't hit it again + // FIXME: variable kick height? + if (kickEnd && !VectorCompare(kickEnd, vec3_origin)) { // they passed us the end point of the trace, just use that + // this makes the trace flat + VectorSet(traceOrg, ent->r.currentOrigin[0], ent->r.currentOrigin[1], kickEnd[2]); + VectorCopy(kickEnd, traceEnd); + } else { // extrude + VectorSet(traceOrg, ent->r.currentOrigin[0], ent->r.currentOrigin[1], ent->r.currentOrigin[2] + ent->r.maxs[2] * 0.5f); + VectorMA(traceOrg, kickDist, kickDir, traceEnd); + } + + if (d_saberKickTweak.integer) { + trap->Trace(&trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, qfalse, + G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_THICK | G2TRFLAG_HITCORPSES, g_g2TraceLod.integer); + } else { + trap->Trace(&trace, traceOrg, kickMins, kickMaxs, traceEnd, ent->s.number, MASK_SHOT, qfalse, 0, 0); + } + + // G_TestLine(traceOrg, traceEnd, 0x0000ff, 5000); + if (trace.fraction < 1.0f && !trace.startsolid && !trace.allsolid) { + if (ent->client->jediKickTime > level.time) { + if (trace.entityNum == ent->client->jediKickIndex) { // we are hitting the same ent we last hit in this same anim, don't hit it again return NULL; } } @@ -7565,51 +6123,37 @@ static gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, v ent->client->jediKickTime = level.time + ent->client->ps.legsTimer; hitEnt = &g_entities[trace.entityNum]; - //FIXME: regardless of what we hit, do kick hit sound and impact effect - //G_PlayEffect( "misc/kickHit", trace.endpos, trace.plane.normal ); - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - { - G_Sound( ent, CHAN_AUTO, G_SoundIndex( "sound/movers/objects/saber_slam" ) ); - } - else - { - G_Sound( ent, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - } - if ( hitEnt->inuse ) - {//we hit an entity - //FIXME: don't hit same ent more than once per kick - if ( hitEnt->takedamage ) - {//hurt it - if (hitEnt->client) - { + // FIXME: regardless of what we hit, do kick hit sound and impact effect + // G_PlayEffect( "misc/kickHit", trace.endpos, trace.plane.normal ); + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { + G_Sound(ent, CHAN_AUTO, G_SoundIndex("sound/movers/objects/saber_slam")); + } else { + G_Sound(ent, CHAN_AUTO, G_SoundIndex(va("sound/weapons/melee/punch%d", Q_irand(1, 4)))); + } + if (hitEnt->inuse) { // we hit an entity + // FIXME: don't hit same ent more than once per kick + if (hitEnt->takedamage) { // hurt it + if (hitEnt->client) { hitEnt->client->ps.otherKiller = ent->s.number; hitEnt->client->ps.otherKillerDebounceTime = level.time + 10000; hitEnt->client->ps.otherKillerTime = level.time + 10000; } - if (d_saberKickTweak.integer) - { - G_Damage( hitEnt, ent, ent, kickDir, trace.endpos, kickDamage*0.2f, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); - } - else - { - G_Damage( hitEnt, ent, ent, kickDir, trace.endpos, kickDamage, DAMAGE_NO_KNOCKBACK, MOD_MELEE ); + if (d_saberKickTweak.integer) { + G_Damage(hitEnt, ent, ent, kickDir, trace.endpos, kickDamage * 0.2f, DAMAGE_NO_KNOCKBACK, MOD_MELEE); + } else { + G_Damage(hitEnt, ent, ent, kickDir, trace.endpos, kickDamage, DAMAGE_NO_KNOCKBACK, MOD_MELEE); } } - if ( hitEnt->client - && !(hitEnt->client->ps.pm_flags&PMF_TIME_KNOCKBACK) //not already flying through air? Intended to stop multiple hits, but... - && G_CanBeEnemy(ent, hitEnt) ) - {//FIXME: this should not always work - if ( hitEnt->health <= 0 ) - {//we kicked a dead guy - //throw harder - FIXME: no matter how hard I push them, they don't go anywhere... corpses use less physics??? - // G_Throw( hitEnt, kickDir, kickPush*4 ); - //see if we should play a better looking death on them - // G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); - G_TossTheMofo(hitEnt, kickDir, kickPush*4.0f); - } - else - { + if (hitEnt->client && !(hitEnt->client->ps.pm_flags & PMF_TIME_KNOCKBACK) // not already flying through air? Intended to stop multiple hits, but... + && G_CanBeEnemy(ent, hitEnt)) { // FIXME: this should not always work + if (hitEnt->health <= 0) { // we kicked a dead guy + // throw harder - FIXME: no matter how hard I push them, they don't go anywhere... corpses use less physics??? + // G_Throw( hitEnt, kickDir, kickPush*4 ); + // see if we should play a better looking death on them + // G_ThrownDeathAnimForDeathAnim( hitEnt, trace.endpos ); + G_TossTheMofo(hitEnt, kickDir, kickPush * 4.0f); + } else { /* G_Throw( hitEnt, kickDir, kickPush ); if ( kickPush >= 75.0f && !Q_irand( 0, 2 ) ) @@ -7621,12 +6165,9 @@ static gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, v G_Knockdown( hitEnt, ent, kickDir, kickPush, qtrue ); } */ - if ( kickPush >= 75.0f && !Q_irand( 0, 2 ) ) - { + if (kickPush >= 75.0f && !Q_irand(0, 2)) { G_TossTheMofo(hitEnt, kickDir, 300.0f); - } - else - { + } else { G_TossTheMofo(hitEnt, kickDir, kickPush); } } @@ -7636,15 +6177,14 @@ static gentity_t *G_KickTrace( gentity_t *ent, vec3_t kickDir, float kickDist, v return (hitEnt); } -static void G_KickSomeMofos(gentity_t *ent) -{ - vec3_t kickDir, kickEnd, fwdAngs; - float animLength = BG_AnimLength( ent->localAnimIndex, (animNumber_t)ent->client->ps.legsAnim ); - float elapsedTime = (float)(animLength-ent->client->ps.legsTimer); - float remainingTime = (animLength-elapsedTime); - float kickDist = (ent->r.maxs[0]*1.5f)+STAFF_KICK_RANGE+8.0f;//fudge factor of 8 - int kickDamage = Q_irand(10, 15);//Q_irand( 3, 8 ); //since it can only hit a guy once now - int kickPush = flrand( 50.0f, 100.0f ); +static void G_KickSomeMofos(gentity_t *ent) { + vec3_t kickDir, kickEnd, fwdAngs; + float animLength = BG_AnimLength(ent->localAnimIndex, (animNumber_t)ent->client->ps.legsAnim); + float elapsedTime = (float)(animLength - ent->client->ps.legsTimer); + float remainingTime = (animLength - elapsedTime); + float kickDist = (ent->r.maxs[0] * 1.5f) + STAFF_KICK_RANGE + 8.0f; // fudge factor of 8 + int kickDamage = Q_irand(10, 15); // Q_irand( 3, 8 ); //since it can only hit a guy once now + int kickPush = flrand(50.0f, 100.0f); qboolean doKick = qfalse; renderInfo_t *ri = &ent->client->renderInfo; @@ -7652,46 +6192,34 @@ static void G_KickSomeMofos(gentity_t *ent) VectorSet(kickEnd, 0.0f, 0.0f, 0.0f); VectorSet(fwdAngs, 0.0f, ent->client->ps.viewangles[YAW], 0.0f); - //HMM... or maybe trace from origin to footRBolt/footLBolt? Which one? G2 trace? Will do hitLoc, if so... - if ( ent->client->ps.torsoAnim == BOTH_A7_HILT ) - { - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + // HMM... or maybe trace from origin to footRBolt/footLBolt? Which one? G2 trace? Will do hitLoc, if so... + if (ent->client->ps.torsoAnim == BOTH_A7_HILT) { + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ri->handRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->handRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->client->ps.origin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ri->handRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->handRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->client->ps.origin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } - } - else - { - switch ( ent->client->ps.legsAnim ) - { + } else { + switch (ent->client->ps.legsAnim) { case BOTH_GETUP_BROLL_B: case BOTH_GETUP_BROLL_F: case BOTH_GETUP_FROLL_B: case BOTH_GETUP_FROLL_F: - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->client->ps.origin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->client->ps.origin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; @@ -7699,270 +6227,208 @@ static void G_KickSomeMofos(gentity_t *ent) case BOTH_A7_KICK_B_AIR: case BOTH_A7_KICK_R_AIR: case BOTH_A7_KICK_L_AIR: - if ( elapsedTime >= 100 && remainingTime >= 250 ) - {//air + if (elapsedTime >= 100 && remainingTime >= 250) { // air doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; case BOTH_A7_KICK_F: - //FIXME: push forward? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//front + // FIXME: push forward? + if (elapsedTime >= 250 && remainingTime >= 250) { // front doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); } } break; case BOTH_A7_KICK_B: - //FIXME: push back? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//back + // FIXME: push back? + if (elapsedTime >= 250 && remainingTime >= 250) { // back doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_R: - //FIXME: push right? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//right + // FIXME: push right? + if (elapsedTime >= 250 && remainingTime >= 250) { // right doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); } } break; case BOTH_A7_KICK_L: - //FIXME: push left? - if ( elapsedTime >= 250 && remainingTime >= 250 ) - {//left + // FIXME: push left? + if (elapsedTime >= 250 && remainingTime >= 250) { // left doKick = qtrue; - if ( ri->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footLBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ri->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footLBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_S: - kickPush = flrand( 75.0f, 125.0f ); - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - if ( elapsedTime >= 550 - && elapsedTime <= 1050 ) - { + kickPush = flrand(75.0f, 125.0f); + if (ri->footRBolt != -1) { // actually trace to a bolt + if (elapsedTime >= 550 && elapsedTime <= 1050) { doKick = qtrue; - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8.0f, kickDir, kickEnd ); - } - } - else - {//guess - if ( elapsedTime >= 400 && elapsedTime < 500 ) - {//front + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8.0f, kickDir, kickEnd); + } + } else { // guess + if (elapsedTime >= 400 && elapsedTime < 500) { // front doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 500 && elapsedTime < 600 ) - {//front-right? + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 500 && elapsedTime < 600) { // front-right? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 600 && elapsedTime < 700 ) - {//right + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 600 && elapsedTime < 700) { // right doKick = qtrue; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - } - else if ( elapsedTime >= 700 && elapsedTime < 800 ) - {//back-right? + AngleVectors(fwdAngs, NULL, kickDir, NULL); + } else if (elapsedTime >= 700 && elapsedTime < 800) { // back-right? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - } - else if ( elapsedTime >= 800 && elapsedTime < 900 ) - {//back + AngleVectors(fwdAngs, NULL, kickDir, NULL); + } else if (elapsedTime >= 800 && elapsedTime < 900) { // back doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); - } - else if ( elapsedTime >= 900 && elapsedTime < 1000 ) - {//back-left? + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); + } else if (elapsedTime >= 900 && elapsedTime < 1000) { // back-left? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 1000 && elapsedTime < 1100 ) - {//left + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 1000 && elapsedTime < 1100) { // left doKick = qtrue; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); - } - else if ( elapsedTime >= 1100 && elapsedTime < 1200 ) - {//front-left? + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); + } else if (elapsedTime >= 1100 && elapsedTime < 1200) { // front-left? doKick = qtrue; fwdAngs[YAW] += 45; - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_BF: - kickPush = flrand( 75.0f, 125.0f ); + kickPush = flrand(75.0f, 125.0f); kickDist += 20.0f; - if ( elapsedTime < 1500 ) - {//auto-aim! - // overridAngles = PM_AdjustAnglesForBFKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; - //FIXME: if we haven't done the back kick yet and there's no-one there to + if (elapsedTime < 1500) { // auto-aim! + // overridAngles = PM_AdjustAnglesForBFKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; + // FIXME: if we haven't done the back kick yet and there's no-one there to // kick anymore, go into some anim that returns us to our base stance } - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - if ( ( elapsedTime >= 750 && elapsedTime < 850 ) - || ( elapsedTime >= 1400 && elapsedTime < 1500 ) ) - {//right, though either would do + if (ri->footRBolt != -1) { // actually trace to a bolt + if ((elapsedTime >= 750 && elapsedTime < 850) || (elapsedTime >= 1400 && elapsedTime < 1500)) { // right, though either would do doKick = qtrue; - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); - } - } - else - {//guess - if ( elapsedTime >= 250 && elapsedTime < 350 ) - {//front + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); + } + } else { // guess + if (elapsedTime >= 250 && elapsedTime < 350) { // front doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - } - else if ( elapsedTime >= 350 && elapsedTime < 450 ) - {//back + AngleVectors(fwdAngs, kickDir, NULL, NULL); + } else if (elapsedTime >= 350 && elapsedTime < 450) { // back doKick = qtrue; - AngleVectors( fwdAngs, kickDir, NULL, NULL ); - VectorScale( kickDir, -1, kickDir ); + AngleVectors(fwdAngs, kickDir, NULL, NULL); + VectorScale(kickDir, -1, kickDir); } } break; case BOTH_A7_KICK_RL: - kickPush = flrand( 75.0f, 125.0f ); + kickPush = flrand(75.0f, 125.0f); kickDist += 10.0f; - //ok, I'm tracing constantly on these things, they NEVER hit otherwise (in MP at least) + // ok, I'm tracing constantly on these things, they NEVER hit otherwise (in MP at least) - //FIXME: auto aim at enemies on the side of us? - //overridAngles = PM_AdjustAnglesForRLKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; - //if ( elapsedTime >= 250 && elapsedTime < 350 ) - if (level.framenum&1) - {//right + // FIXME: auto aim at enemies on the side of us? + // overridAngles = PM_AdjustAnglesForRLKick( ent, ucmd, fwdAngs, qboolean(elapsedTime<850) )?qtrue:overridAngles; + // if ( elapsedTime >= 250 && elapsedTime < 350 ) + if (level.framenum & 1) { // right doKick = qtrue; - if ( ri->footRBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footRBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - } - } - //else if ( elapsedTime >= 350 && elapsedTime < 450 ) - else - {//left + if (ri->footRBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footRBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + } + } + // else if ( elapsedTime >= 350 && elapsedTime < 450 ) + else { // left doKick = qtrue; - if ( ri->footLBolt != -1 ) - {//actually trace to a bolt - G_GetBoltPosition( ent, ri->footLBolt, kickEnd, 0 ); - VectorSubtract( kickEnd, ent->r.currentOrigin, kickDir ); - kickDir[2] = 0;//ah, flatten it, I guess... - VectorNormalize( kickDir ); - //NOTE: have to fudge this a little because it's not getting enough range with the anim as-is - VectorMA( kickEnd, 8, kickDir, kickEnd ); - } - else - {//guess - AngleVectors( fwdAngs, NULL, kickDir, NULL ); - VectorScale( kickDir, -1, kickDir ); + if (ri->footLBolt != -1) { // actually trace to a bolt + G_GetBoltPosition(ent, ri->footLBolt, kickEnd, 0); + VectorSubtract(kickEnd, ent->r.currentOrigin, kickDir); + kickDir[2] = 0; // ah, flatten it, I guess... + VectorNormalize(kickDir); + // NOTE: have to fudge this a little because it's not getting enough range with the anim as-is + VectorMA(kickEnd, 8, kickDir, kickEnd); + } else { // guess + AngleVectors(fwdAngs, NULL, kickDir, NULL); + VectorScale(kickDir, -1, kickDir); } } break; } } - if ( doKick ) - { -// G_KickTrace( ent, kickDir, kickDist, kickEnd, kickDamage, kickPush ); - G_KickTrace( ent, kickDir, kickDist, NULL, kickDamage, kickPush ); + if (doKick) { + // G_KickTrace( ent, kickDir, kickDist, kickEnd, kickDamage, kickPush ); + G_KickTrace(ent, kickDir, kickDist, NULL, kickDamage, kickPush); } } -static QINLINE qboolean G_PrettyCloseIGuess(float a, float b, float tolerance) -{ - if ((a-b) < tolerance && - (a-b) > -tolerance) - { +static QINLINE qboolean G_PrettyCloseIGuess(float a, float b, float tolerance) { + if ((a - b) < tolerance && (a - b) > -tolerance) { return qtrue; } return qfalse; } -static void G_GrabSomeMofos(gentity_t *self) -{ +static void G_GrabSomeMofos(gentity_t *self) { renderInfo_t *ri = &self->client->renderInfo; mdxaBone_t boltMatrix; vec3_t flatAng; @@ -7970,55 +6436,43 @@ static void G_GrabSomeMofos(gentity_t *self) vec3_t grabMins, grabMaxs; trace_t trace; - if (!self->ghoul2 || ri->handRBolt == -1) - { //no good + if (!self->ghoul2 || ri->handRBolt == -1) { // no good return; } - VectorSet(flatAng, 0.0f, self->client->ps.viewangles[1], 0.0f); - trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handRBolt, &boltMatrix, flatAng, self->client->ps.origin, - level.time, NULL, self->modelScale); + VectorSet(flatAng, 0.0f, self->client->ps.viewangles[1], 0.0f); + trap->G2API_GetBoltMatrix(self->ghoul2, 0, ri->handRBolt, &boltMatrix, flatAng, self->client->ps.origin, level.time, NULL, self->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, pos); VectorSet(grabMins, -4.0f, -4.0f, -4.0f); VectorSet(grabMaxs, 4.0f, 4.0f, 4.0f); - //trace from my origin to my hand, if we hit anyone then get 'em - trap->Trace( &trace, self->client->ps.origin, grabMins, grabMaxs, pos, self->s.number, MASK_SHOT, qfalse, G2TRFLAG_DOGHOULTRACE|G2TRFLAG_GETSURFINDEX|G2TRFLAG_THICK|G2TRFLAG_HITCORPSES, g_g2TraceLod.integer ); + // trace from my origin to my hand, if we hit anyone then get 'em + trap->Trace(&trace, self->client->ps.origin, grabMins, grabMaxs, pos, self->s.number, MASK_SHOT, qfalse, + G2TRFLAG_DOGHOULTRACE | G2TRFLAG_GETSURFINDEX | G2TRFLAG_THICK | G2TRFLAG_HITCORPSES, g_g2TraceLod.integer); - if (trace.fraction != 1.0f && - trace.entityNum < ENTITYNUM_WORLD) - { + if (trace.fraction != 1.0f && trace.entityNum < ENTITYNUM_WORLD) { gentity_t *grabbed = &g_entities[trace.entityNum]; - if (grabbed->inuse && (grabbed->s.eType == ET_PLAYER || grabbed->s.eType == ET_NPC) && - grabbed->client && grabbed->health > 0 && - G_CanBeEnemy(self, grabbed) && - G_PrettyCloseIGuess(grabbed->client->ps.origin[2], self->client->ps.origin[2], 4.0f) && + if (grabbed->inuse && (grabbed->s.eType == ET_PLAYER || grabbed->s.eType == ET_NPC) && grabbed->client && grabbed->health > 0 && + G_CanBeEnemy(self, grabbed) && G_PrettyCloseIGuess(grabbed->client->ps.origin[2], self->client->ps.origin[2], 4.0f) && (!BG_InGrappleMove(grabbed->client->ps.torsoAnim) || grabbed->client->ps.torsoAnim == BOTH_KYLE_GRAB) && - (!BG_InGrappleMove(grabbed->client->ps.legsAnim) || grabbed->client->ps.legsAnim == BOTH_KYLE_GRAB)) - { //grabbed an active player/npc + (!BG_InGrappleMove(grabbed->client->ps.legsAnim) || grabbed->client->ps.legsAnim == BOTH_KYLE_GRAB)) { // grabbed an active player/npc int tortureAnim = -1; int correspondingAnim = -1; - if (self->client->pers.cmd.forwardmove > 0) - { //punch grab + if (self->client->pers.cmd.forwardmove > 0) { // punch grab tortureAnim = BOTH_KYLE_PA_1; correspondingAnim = BOTH_PLAYER_PA_1; - } - else if (self->client->pers.cmd.forwardmove < 0) - { //knee-throw + } else if (self->client->pers.cmd.forwardmove < 0) { // knee-throw tortureAnim = BOTH_KYLE_PA_2; correspondingAnim = BOTH_PLAYER_PA_2; } - if (tortureAnim == -1 || correspondingAnim == -1) - { - if (self->client->ps.torsoTimer < 300 && !self->client->grappleState) - { //you failed to grab anyone, play the "failed to grab" anim - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) - { //providing the anim set succeeded.. + if (tortureAnim == -1 || correspondingAnim == -1) { + if (self->client->ps.torsoTimer < 300 && !self->client->grappleState) { // you failed to grab anyone, play the "failed to grab" anim + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) { // providing the anim set succeeded.. self->client->ps.weaponTime = self->client->ps.torsoTimer; } } @@ -8031,34 +6485,26 @@ static void G_GrabSomeMofos(gentity_t *self) grabbed->client->grappleIndex = self->s.number; grabbed->client->grappleState = 20; - //time to crack some heads - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, tortureAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (self->client->ps.torsoAnim == tortureAnim) - { //providing the anim set succeeded.. + // time to crack some heads + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, tortureAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (self->client->ps.torsoAnim == tortureAnim) { // providing the anim set succeeded.. self->client->ps.weaponTime = self->client->ps.torsoTimer; } - G_SetAnim(grabbed, &grabbed->client->pers.cmd, SETANIM_BOTH, correspondingAnim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (grabbed->client->ps.torsoAnim == correspondingAnim) - { //providing the anim set succeeded.. - if (grabbed->client->ps.weapon == WP_SABER) - { //turn it off - if (!grabbed->client->ps.saberHolstered) - { + G_SetAnim(grabbed, &grabbed->client->pers.cmd, SETANIM_BOTH, correspondingAnim, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (grabbed->client->ps.torsoAnim == correspondingAnim) { // providing the anim set succeeded.. + if (grabbed->client->ps.weapon == WP_SABER) { // turn it off + if (!grabbed->client->ps.saberHolstered) { grabbed->client->ps.saberHolstered = 2; - if (grabbed->client->saber[0].soundOff) - { + if (grabbed->client->saber[0].soundOff) { G_Sound(grabbed, CHAN_AUTO, grabbed->client->saber[0].soundOff); } - if (grabbed->client->saber[1].soundOff && - grabbed->client->saber[1].model[0]) - { + if (grabbed->client->saber[1].soundOff && grabbed->client->saber[1].model[0]) { G_Sound(grabbed, CHAN_AUTO, grabbed->client->saber[1].soundOff); } } } - if (grabbed->client->ps.torsoTimer < self->client->ps.torsoTimer) - { //make sure they stay in the anim at least as long as the grabber + if (grabbed->client->ps.torsoTimer < self->client->ps.torsoTimer) { // make sure they stay in the anim at least as long as the grabber grabbed->client->ps.torsoTimer = self->client->ps.torsoTimer; } grabbed->client->ps.weaponTime = grabbed->client->ps.torsoTimer; @@ -8066,21 +6512,20 @@ static void G_GrabSomeMofos(gentity_t *self) } } - if (self->client->ps.torsoTimer < 300 && !self->client->grappleState) - { //you failed to grab anyone, play the "failed to grab" anim - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) - { //providing the anim set succeeded.. + if (self->client->ps.torsoTimer < 300 && !self->client->grappleState) { // you failed to grab anyone, play the "failed to grab" anim + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) { // providing the anim set succeeded.. self->client->ps.weaponTime = self->client->ps.torsoTimer; } } } -void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) -{ //rww - keep the saber position as updated as possible on the server so that we can try to do realistic-looking contact stuff - //Note that this function also does the majority of working in maintaining the server g2 client instance (updating angles/anims/etc) +void WP_SaberPositionUpdate( + gentity_t *self, + usercmd_t *ucmd) { // rww - keep the saber position as updated as possible on the server so that we can try to do realistic-looking contact stuff + // Note that this function also does the majority of working in maintaining the server g2 client instance (updating angles/anims/etc) gentity_t *mySaber = NULL; - mdxaBone_t boltMatrix; + mdxaBone_t boltMatrix; vec3_t properAngles, properOrigin; vec3_t boltAngles, boltOrigin; vec3_t end; @@ -8097,111 +6542,78 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) int rBladeNum = 0; #ifdef _DEBUG - if (g_disableServerG2.integer) - { + if (g_disableServerG2.integer) { return; } #endif - if (self && self->inuse && self->client) - { - if (self->client->saberCycleQueue) - { + if (self && self->inuse && self->client) { + if (self->client->saberCycleQueue) { self->client->ps.fd.saberDrawAnimLevel = self->client->saberCycleQueue; - } - else - { + } else { self->client->ps.fd.saberDrawAnimLevel = self->client->ps.fd.saberAnimLevel; } } - if (self && - self->inuse && - self->client && - self->client->saberCycleQueue && - (self->client->ps.weaponTime <= 0 || self->health < 1)) - { //we cycled attack levels while we were busy, so update now that we aren't (even if that means we're dead) + if (self && self->inuse && self->client && self->client->saberCycleQueue && + (self->client->ps.weaponTime <= 0 || + self->health < 1)) { // we cycled attack levels while we were busy, so update now that we aren't (even if that means we're dead) self->client->ps.fd.saberAnimLevel = self->client->saberCycleQueue; self->client->saberCycleQueue = 0; } - if (!self || - !self->inuse || - !self->client || - !self->ghoul2 || - !g2SaberInstance) - { + if (!self || !self->inuse || !self->client || !self->ghoul2 || !g2SaberInstance) { return; } - if (BG_KickingAnim(self->client->ps.legsAnim)) - { //do some kick traces and stuff if we're in the appropriate anim + if (BG_KickingAnim(self->client->ps.legsAnim)) { // do some kick traces and stuff if we're in the appropriate anim G_KickSomeMofos(self); - } - else if (self->client->ps.torsoAnim == BOTH_KYLE_GRAB) - { //try to grab someone + } else if (self->client->ps.torsoAnim == BOTH_KYLE_GRAB) { // try to grab someone G_GrabSomeMofos(self); - } - else if (self->client->grappleState) - { + } else if (self->client->grappleState) { gentity_t *grappler = &g_entities[self->client->grappleIndex]; - if (!grappler->inuse || !grappler->client || grappler->client->grappleIndex != self->s.number || - !BG_InGrappleMove(grappler->client->ps.torsoAnim) || !BG_InGrappleMove(grappler->client->ps.legsAnim) || - !BG_InGrappleMove(self->client->ps.torsoAnim) || !BG_InGrappleMove(self->client->ps.legsAnim) || - !self->client->grappleState || !grappler->client->grappleState || - grappler->health < 1 || self->health < 1 || - !G_PrettyCloseIGuess(self->client->ps.origin[2], grappler->client->ps.origin[2], 4.0f)) - { + if (!grappler->inuse || !grappler->client || grappler->client->grappleIndex != self->s.number || !BG_InGrappleMove(grappler->client->ps.torsoAnim) || + !BG_InGrappleMove(grappler->client->ps.legsAnim) || !BG_InGrappleMove(self->client->ps.torsoAnim) || !BG_InGrappleMove(self->client->ps.legsAnim) || + !self->client->grappleState || !grappler->client->grappleState || grappler->health < 1 || self->health < 1 || + !G_PrettyCloseIGuess(self->client->ps.origin[2], grappler->client->ps.origin[2], 4.0f)) { self->client->grappleState = 0; if ((BG_InGrappleMove(self->client->ps.torsoAnim) && self->client->ps.torsoTimer > 100) || - (BG_InGrappleMove(self->client->ps.legsAnim) && self->client->ps.legsTimer > 100)) - { //if they're pretty far from finishing the anim then shove them into another anim - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) - { //providing the anim set succeeded.. + (BG_InGrappleMove(self->client->ps.legsAnim) && + self->client->ps.legsTimer > 100)) { // if they're pretty far from finishing the anim then shove them into another anim + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) { // providing the anim set succeeded.. self->client->ps.weaponTime = self->client->ps.torsoTimer; } } - } - else - { + } else { vec3_t grapAng; VectorSubtract(grappler->client->ps.origin, self->client->ps.origin, grapAng); - if (VectorLength(grapAng) > 64.0f) - { //too far away, break it off + if (VectorLength(grapAng) > 64.0f) { // too far away, break it off if ((BG_InGrappleMove(self->client->ps.torsoAnim) && self->client->ps.torsoTimer > 100) || - (BG_InGrappleMove(self->client->ps.legsAnim) && self->client->ps.legsTimer > 100)) - { + (BG_InGrappleMove(self->client->ps.legsAnim) && self->client->ps.legsTimer > 100)) { self->client->grappleState = 0; - G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); - if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) - { //providing the anim set succeeded.. + G_SetAnim(self, &self->client->pers.cmd, SETANIM_BOTH, BOTH_KYLE_MISS, SETANIM_FLAG_OVERRIDE | SETANIM_FLAG_HOLD, 0); + if (self->client->ps.torsoAnim == BOTH_KYLE_MISS) { // providing the anim set succeeded.. self->client->ps.weaponTime = self->client->ps.torsoTimer; } } - } - else - { + } else { vectoangles(grapAng, grapAng); SetClientViewAngle(self, grapAng); - if (self->client->grappleState >= 20) - { //grapplee - //try to position myself at the correct distance from my grappler + if (self->client->grappleState >= 20) { // grapplee + // try to position myself at the correct distance from my grappler float idealDist; vec3_t gFwd, idealSpot; trace_t trace; - if (grappler->client->ps.torsoAnim == BOTH_KYLE_PA_1) - { //grab punch + if (grappler->client->ps.torsoAnim == BOTH_KYLE_PA_1) { // grab punch idealDist = 46.0f; - } - else - { //knee-throw + } else { // knee-throw idealDist = 34.0f; } @@ -8209,47 +6621,35 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) VectorMA(grappler->client->ps.origin, idealDist, gFwd, idealSpot); trap->Trace(&trace, self->client->ps.origin, self->r.mins, self->r.maxs, idealSpot, self->s.number, self->clipmask, qfalse, 0, 0); - if (!trace.startsolid && !trace.allsolid && trace.fraction == 1.0f) - { //go there + if (!trace.startsolid && !trace.allsolid && trace.fraction == 1.0f) { // go there G_SetOrigin(self, idealSpot); VectorCopy(idealSpot, self->client->ps.origin); } - } - else if (self->client->grappleState >= 1) - { //grappler - if (grappler->client->ps.weapon == WP_SABER) - { //make sure their saber is shut off - if (!grappler->client->ps.saberHolstered) - { + } else if (self->client->grappleState >= 1) { // grappler + if (grappler->client->ps.weapon == WP_SABER) { // make sure their saber is shut off + if (!grappler->client->ps.saberHolstered) { grappler->client->ps.saberHolstered = 2; - if (grappler->client->saber[0].soundOff) - { + if (grappler->client->saber[0].soundOff) { G_Sound(grappler, CHAN_AUTO, grappler->client->saber[0].soundOff); } - if (grappler->client->saber[1].soundOff && - grappler->client->saber[1].model[0]) - { + if (grappler->client->saber[1].soundOff && grappler->client->saber[1].model[0]) { G_Sound(grappler, CHAN_AUTO, grappler->client->saber[1].soundOff); } } } - //check for smashy events - if (self->client->ps.torsoAnim == BOTH_KYLE_PA_1) - { //grab punch - if (self->client->grappleState == 1) - { //smack - if (self->client->ps.torsoTimer < 3400) - { + // check for smashy events + if (self->client->ps.torsoAnim == BOTH_KYLE_PA_1) { // grab punch + if (self->client->grappleState == 1) { // smack + if (self->client->ps.torsoTimer < 3400) { int grapplerAnim = grappler->client->ps.torsoAnim; int grapplerTime = grappler->client->ps.torsoTimer; G_Damage(grappler, self, self, NULL, self->client->ps.origin, 10, 0, MOD_MELEE); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - //it might try to put them into a pain anim or something, so override it back again - if (grappler->health > 0) - { + // it might try to put them into a pain anim or something, so override it back again + if (grappler->health > 0) { grappler->client->ps.torsoAnim = grapplerAnim; grappler->client->ps.torsoTimer = grapplerTime; grappler->client->ps.legsAnim = grapplerAnim; @@ -8258,20 +6658,16 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) } self->client->grappleState++; } - } - else if (self->client->grappleState == 2) - { //smack! - if (self->client->ps.torsoTimer < 2550) - { + } else if (self->client->grappleState == 2) { // smack! + if (self->client->ps.torsoTimer < 2550) { int grapplerAnim = grappler->client->ps.torsoAnim; int grapplerTime = grappler->client->ps.torsoTimer; G_Damage(grappler, self, self, NULL, self->client->ps.origin, 10, 0, MOD_MELEE); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - //it might try to put them into a pain anim or something, so override it back again - if (grappler->health > 0) - { + // it might try to put them into a pain anim or something, so override it back again + if (grappler->health > 0) { grappler->client->ps.torsoAnim = grapplerAnim; grappler->client->ps.torsoTimer = grapplerTime; grappler->client->ps.legsAnim = grapplerAnim; @@ -8280,15 +6676,12 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) } self->client->grappleState++; } - } - else - { //SMACK! - if (self->client->ps.torsoTimer < 1300) - { + } else { // SMACK! + if (self->client->ps.torsoTimer < 1300) { vec3_t tossDir; G_Damage(grappler, self, self, NULL, self->client->ps.origin, 30, 0, MOD_MELEE); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); self->client->grappleState = 0; @@ -8299,29 +6692,23 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) VectorAdd(grappler->client->ps.velocity, tossDir, grappler->client->ps.velocity); - if (grappler->health > 0) - { //if still alive knock them down + if (grappler->health > 0) { // if still alive knock them down grappler->client->ps.forceHandExtend = HANDEXTEND_KNOCKDOWN; grappler->client->ps.forceHandExtendTime = level.time + 1300; } } } - } - else if (self->client->ps.torsoAnim == BOTH_KYLE_PA_2) - { //knee throw - if (self->client->grappleState == 1) - { //knee to the face - if (self->client->ps.torsoTimer < 3200) - { + } else if (self->client->ps.torsoAnim == BOTH_KYLE_PA_2) { // knee throw + if (self->client->grappleState == 1) { // knee to the face + if (self->client->ps.torsoTimer < 3200) { int grapplerAnim = grappler->client->ps.torsoAnim; int grapplerTime = grappler->client->ps.torsoTimer; G_Damage(grappler, self, self, NULL, self->client->ps.origin, 20, 0, MOD_MELEE); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - //it might try to put them into a pain anim or something, so override it back again - if (grappler->health > 0) - { + // it might try to put them into a pain anim or something, so override it back again + if (grappler->health > 0) { grappler->client->ps.torsoAnim = grapplerAnim; grappler->client->ps.torsoTimer = grapplerTime; grappler->client->ps.legsAnim = grapplerAnim; @@ -8330,34 +6717,25 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) } self->client->grappleState++; } - } - else if (self->client->grappleState == 2) - { //smashed on the ground - if (self->client->ps.torsoTimer < 2000) - { - //G_Damage(grappler, self, self, NULL, self->client->ps.origin, 10, 0, MOD_MELEE); - //don't do damage on this one, it would look very freaky if they died - G_EntitySound( grappler, CHAN_VOICE, G_SoundIndex("*pain100.wav") ); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + } else if (self->client->grappleState == 2) { // smashed on the ground + if (self->client->ps.torsoTimer < 2000) { + // G_Damage(grappler, self, self, NULL, self->client->ps.origin, 10, 0, MOD_MELEE); + // don't do damage on this one, it would look very freaky if they died + G_EntitySound(grappler, CHAN_VOICE, G_SoundIndex("*pain100.wav")); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); self->client->grappleState++; } - } - else - { //and another smash - if (self->client->ps.torsoTimer < 1000) - { + } else { // and another smash + if (self->client->ps.torsoTimer < 1000) { G_Damage(grappler, self, self, NULL, self->client->ps.origin, 30, 0, MOD_MELEE); - //G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); + // G_Sound( grappler, CHAN_AUTO, G_SoundIndex( va( "sound/weapons/melee/punch%d", Q_irand( 1, 4 ) ) ) ); - //it might try to put them into a pain anim or something, so override it back again - if (grappler->health > 0) - { + // it might try to put them into a pain anim or something, so override it back again + if (grappler->health > 0) { grappler->client->ps.torsoTimer = 1000; - //G_SetAnim(grappler, &grappler->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); + // G_SetAnim(grappler, &grappler->client->pers.cmd, SETANIM_BOTH, BOTH_GETUP3, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD, 0); grappler->client->grappleState = 0; - } - else - { //override death anim + } else { // override death anim grappler->client->ps.torsoAnim = BOTH_DEADFLOP1; grappler->client->ps.legsAnim = BOTH_DEADFLOP1; } @@ -8365,212 +6743,167 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) self->client->grappleState = 0; } } - } - else - { //? + } else { //? } } } } } - //If this is a listen server (client+server running on same machine), - //then lets try to steal the skeleton/etc data off the client instance - //for this entity to save us processing time. + // If this is a listen server (client+server running on same machine), + // then lets try to steal the skeleton/etc data off the client instance + // for this entity to save us processing time. clientOverride = trap->G2API_OverrideServer(self->ghoul2); saberNum = self->client->ps.saberEntityNum; - if (!saberNum) - { + if (!saberNum) { saberNum = self->client->saberStoredIndex; } - if (!saberNum) - { + if (!saberNum) { returnAfterUpdate = 1; goto nextStep; } mySaber = &g_entities[saberNum]; - if (self->health < 1) - { //we don't want to waste precious CPU time calculating saber positions for corpses. But we want to avoid the saber ent position lagging on spawn, so.. - //I guess it's good to keep the position updated even when contents are 0 - if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && !self->client->ps.saberInFlight) - { //Since we haven't got a bolt position, place it on top of the player origin. + if (self->health < 1) { // we don't want to waste precious CPU time calculating saber positions for corpses. But we want to avoid the saber ent position + // lagging on spawn, so.. + // I guess it's good to keep the position updated even when contents are 0 + if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && + !self->client->ps.saberInFlight) { // Since we haven't got a bolt position, place it on top of the player origin. VectorCopy(self->client->ps.origin, mySaber->r.currentOrigin); } - //I don't want to return now actually, I want to keep g2 instances for corpses up to - //date because I'm doing better corpse hit detection/dismem (particularly for the - //npc's) - //return; + // I don't want to return now actually, I want to keep g2 instances for corpses up to + // date because I'm doing better corpse hit detection/dismem (particularly for the + // npc's) + // return; } - if ( BG_SuperBreakWinAnim( self->client->ps.torsoAnim ) ) - { + if (BG_SuperBreakWinAnim(self->client->ps.torsoAnim)) { self->client->ps.weaponstate = WEAPON_FIRING; } - if (self->client->ps.weapon != WP_SABER || - self->client->ps.weaponstate == WEAPON_RAISING || - self->client->ps.weaponstate == WEAPON_DROPPING || - self->health < 1) - { - if (!self->client->ps.saberInFlight) - { + if (self->client->ps.weapon != WP_SABER || self->client->ps.weaponstate == WEAPON_RAISING || self->client->ps.weaponstate == WEAPON_DROPPING || + self->health < 1) { + if (!self->client->ps.saberInFlight) { returnAfterUpdate = 1; } } - if (self->client->ps.saberThrowDelay < level.time) - { - if ( (self->client->saber[0].saberFlags&SFL_NOT_THROWABLE) ) - {//cant throw it normally! - if ( (self->client->saber[0].saberFlags&SFL_SINGLE_BLADE_THROWABLE) ) - {//but can throw it if only have 1 blade on - if ( self->client->saber[0].numBlades > 1 - && self->client->ps.saberHolstered == 1 ) - {//have multiple blades and only one blade on - self->client->ps.saberCanThrow = qtrue;//qfalse; - //huh? want to be able to throw then right? - } - else - {//multiple blades on, can't throw + if (self->client->ps.saberThrowDelay < level.time) { + if ((self->client->saber[0].saberFlags & SFL_NOT_THROWABLE)) { // cant throw it normally! + if ((self->client->saber[0].saberFlags & SFL_SINGLE_BLADE_THROWABLE)) { // but can throw it if only have 1 blade on + if (self->client->saber[0].numBlades > 1 && self->client->ps.saberHolstered == 1) { // have multiple blades and only one blade on + self->client->ps.saberCanThrow = qtrue; // qfalse; + // huh? want to be able to throw then right? + } else { // multiple blades on, can't throw self->client->ps.saberCanThrow = qfalse; } - } - else - {//never can throw it + } else { // never can throw it self->client->ps.saberCanThrow = qfalse; } - } - else - {//can throw it! + } else { // can throw it! self->client->ps.saberCanThrow = qtrue; } } nextStep: - if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) - { + if (self->client->ps.fd.forcePowersActive & (1 << FP_RAGE)) { animSpeedScale = 2; } VectorCopy(self->client->ps.origin, properOrigin); - //try to predict the origin based on velocity so it's more like what the client is seeing + // try to predict the origin based on velocity so it's more like what the client is seeing VectorCopy(self->client->ps.velocity, addVel); VectorNormalize(addVel); - if (self->client->ps.velocity[0] < 0) - { + if (self->client->ps.velocity[0] < 0) { fVSpeed += (-self->client->ps.velocity[0]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[0]; } - if (self->client->ps.velocity[1] < 0) - { + if (self->client->ps.velocity[1] < 0) { fVSpeed += (-self->client->ps.velocity[1]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[1]; } - if (self->client->ps.velocity[2] < 0) - { + if (self->client->ps.velocity[2] < 0) { fVSpeed += (-self->client->ps.velocity[2]); - } - else - { + } else { fVSpeed += self->client->ps.velocity[2]; } - //fVSpeed *= 0.08; - fVSpeed *= 1.6f/sv_fps.value; + // fVSpeed *= 0.08; + fVSpeed *= 1.6f / sv_fps.value; - //Cap it off at reasonable values so the saber box doesn't go flying ahead of us or - //something if we get a big speed boost from something. - if (fVSpeed > 70) - { + // Cap it off at reasonable values so the saber box doesn't go flying ahead of us or + // something if we get a big speed boost from something. + if (fVSpeed > 70) { fVSpeed = 70; } - if (fVSpeed < -70) - { + if (fVSpeed < -70) { fVSpeed = -70; } - properOrigin[0] += addVel[0]*fVSpeed; - properOrigin[1] += addVel[1]*fVSpeed; - properOrigin[2] += addVel[2]*fVSpeed; + properOrigin[0] += addVel[0] * fVSpeed; + properOrigin[1] += addVel[1] * fVSpeed; + properOrigin[2] += addVel[2] * fVSpeed; properAngles[0] = 0; - if (self->s.number < MAX_CLIENTS && self->client->ps.m_iVehicleNum) - { + if (self->s.number < MAX_CLIENTS && self->client->ps.m_iVehicleNum) { vehEnt = &g_entities[self->client->ps.m_iVehicleNum]; - if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) - { + if (vehEnt->inuse && vehEnt->client && vehEnt->m_pVehicle) { properAngles[1] = vehEnt->m_pVehicle->m_vOrientation[YAW]; - } - else - { + } else { properAngles[1] = self->client->ps.viewangles[YAW]; vehEnt = NULL; } - } - else - { + } else { properAngles[1] = self->client->ps.viewangles[YAW]; } properAngles[2] = 0; - AnglesToAxis( properAngles, legAxis ); + AnglesToAxis(properAngles, legAxis); UpdateClientRenderinfo(self, properOrigin, properAngles); - if (!clientOverride) - { //if we get the client instance we don't need to do this - G_G2PlayerAngles( self, legAxis, properAngles ); + if (!clientOverride) { // if we get the client instance we don't need to do this + G_G2PlayerAngles(self, legAxis, properAngles); } - if (vehEnt) - { + if (vehEnt) { properAngles[1] = vehEnt->m_pVehicle->m_vOrientation[YAW]; } - if (returnAfterUpdate && saberNum) - { //We don't even need to do GetBoltMatrix if we're only in here to keep the g2 server instance in sync - //but keep our saber entity in sync too, just copy it over our origin. + if (returnAfterUpdate && saberNum) { // We don't even need to do GetBoltMatrix if we're only in here to keep the g2 server instance in sync + // but keep our saber entity in sync too, just copy it over our origin. - //I guess it's good to keep the position updated even when contents are 0 - if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && !self->client->ps.saberInFlight) - { //Since we haven't got a bolt position, place it on top of the player origin. + // I guess it's good to keep the position updated even when contents are 0 + if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && + !self->client->ps.saberInFlight) { // Since we haven't got a bolt position, place it on top of the player origin. VectorCopy(self->client->ps.origin, mySaber->r.currentOrigin); } goto finalUpdate; } - if (returnAfterUpdate) - { + if (returnAfterUpdate) { goto finalUpdate; } - //We'll get data for blade 0 first no matter what it is and stick them into - //the constant ("_Always") values. Later we will handle going through each blade. + // We'll get data for blade 0 first no matter what it is and stick them into + // the constant ("_Always") values. Later we will handle going through each blade. trap->G2API_GetBoltMatrix(self->ghoul2, 1, 0, &boltMatrix, properAngles, properOrigin, level.time, NULL, self->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, boltOrigin); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, boltAngles); - //immediately store these values so we don't have to recalculate this again - if (self->client->lastSaberStorageTime && (level.time - self->client->lastSaberStorageTime) < 200) - { //alright + // immediately store these values so we don't have to recalculate this again + if (self->client->lastSaberStorageTime && (level.time - self->client->lastSaberStorageTime) < 200) { // alright VectorCopy(self->client->lastSaberBase_Always, self->client->olderSaberBase); self->client->olderIsValid = qtrue; - } - else - { + } else { self->client->olderIsValid = qfalse; } @@ -8580,36 +6913,32 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) VectorCopy(boltAngles, rawAngles); - VectorMA( boltOrigin, self->client->saber[0].blade[0].lengthMax, boltAngles, end ); + VectorMA(boltOrigin, self->client->saber[0].blade[0].lengthMax, boltAngles, end); - if (self->client->ps.saberEntityNum) - { - //I guess it's good to keep the position updated even when contents are 0 - if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && !self->client->ps.saberInFlight) - { //place it roughly in the middle of the saber.. - VectorMA( boltOrigin, self->client->saber[0].blade[0].lengthMax, boltAngles, mySaber->r.currentOrigin ); + if (self->client->ps.saberEntityNum) { + // I guess it's good to keep the position updated even when contents are 0 + if (mySaber && ((mySaber->r.contents & CONTENTS_LIGHTSABER) || mySaber->r.contents == 0) && + !self->client->ps.saberInFlight) { // place it roughly in the middle of the saber.. + VectorMA(boltOrigin, self->client->saber[0].blade[0].lengthMax, boltAngles, mySaber->r.currentOrigin); } } boltAngles[YAW] = self->client->ps.viewangles[YAW]; -/* { - static int lastDTime = 0; - if (lastDTime < level.time) - { - G_TestLine(boltOrigin, end, 0x0000ff, 200); - lastDTime = level.time + 200; + /* { + static int lastDTime = 0; + if (lastDTime < level.time) + { + G_TestLine(boltOrigin, end, 0x0000ff, 200); + lastDTime = level.time + 200; + } } - } -*/ - if (self->client->ps.saberInFlight) - { //do the thrown-saber stuff + */ + if (self->client->ps.saberInFlight) { // do the thrown-saber stuff gentity_t *saberent = &g_entities[saberNum]; - if (saberent) - { - if (!self->client->ps.saberEntityState && self->client->ps.saberEntityNum) - { + if (saberent) { + if (!self->client->ps.saberEntityState && self->client->ps.saberEntityNum) { vec3_t startorg, startang, dir; VectorCopy(boltOrigin, saberent->r.currentOrigin); @@ -8617,9 +6946,9 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) VectorCopy(boltOrigin, startorg); VectorCopy(boltAngles, startang); - //startang[0] = 90; - //Instead of this we'll sort of fake it and slowly tilt it down on the client via - //a perframe method (which doesn't actually affect where or how the saber hits) + // startang[0] = 90; + // Instead of this we'll sort of fake it and slowly tilt it down on the client via + // a perframe method (which doesn't actually affect where or how the saber hits) saberent->r.svFlags &= ~(SVF_NOCLIENT); VectorCopy(startorg, saberent->s.pos.trBase); @@ -8639,7 +6968,7 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) saberent->s.eType = ET_GENERAL; saberent->s.eFlags = 0; - WP_SaberAddG2Model( saberent, self->client->saber[0].model, self->client->saber[0].skin ); + WP_SaberAddG2Model(saberent, self->client->saber[0].model, self->client->saber[0].skin); saberent->s.modelGhoul2 = 127; @@ -8647,7 +6976,7 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) self->client->ps.saberEntityState = 1; - //Projectile stuff: + // Projectile stuff: AngleVectors(self->client->ps.viewangles, dir, NULL, NULL); saberent->nextthink = level.time + FRAMETIME; @@ -8661,24 +6990,21 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) saberent->genericValue5 = 0; - VectorSet( saberent->r.mins, SABERMINS_X, SABERMINS_Y, SABERMINS_Z ); - VectorSet( saberent->r.maxs, SABERMAXS_X, SABERMAXS_Y, SABERMAXS_Z ); + VectorSet(saberent->r.mins, SABERMINS_X, SABERMINS_Y, SABERMINS_Z); + VectorSet(saberent->r.maxs, SABERMAXS_X, SABERMAXS_Y, SABERMAXS_Z); - saberent->s.genericenemyindex = self->s.number+1024; + saberent->s.genericenemyindex = self->s.number + 1024; saberent->touch = thrownSaberTouch; saberent->s.weapon = WP_SABER; - VectorScale(dir, 400, saberent->s.pos.trDelta ); + VectorScale(dir, 400, saberent->s.pos.trDelta); saberent->s.pos.trTime = level.time; - if ( self->client->saber[0].spinSound ) - { + if (self->client->saber[0].spinSound) { saberent->s.loopSound = self->client->saber[0].spinSound; - } - else - { + } else { saberent->s.loopSound = saberSpinSound; } saberent->s.loopIsSoundset = qfalse; @@ -8690,18 +7016,16 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) self->client->invulnerableTimer = 0; trap->LinkEntity((sharedEntity_t *)saberent); - } - else if (self->client->ps.saberEntityNum) //only do this stuff if your saber is active and has not been knocked out of the air. + } else if (self->client->ps.saberEntityNum) // only do this stuff if your saber is active and has not been knocked out of the air. { VectorCopy(boltOrigin, saberent->pos1); trap->LinkEntity((sharedEntity_t *)saberent); - if (saberent->genericValue5 == PROPER_THROWN_VALUE) - { //return to the owner now, this is a bad state to be in for here.. + if (saberent->genericValue5 == PROPER_THROWN_VALUE) { // return to the owner now, this is a bad state to be in for here.. saberent->genericValue5 = 0; saberent->think = SaberUpdateSelf; saberent->nextthink = level.time; - WP_SaberRemoveG2Model( saberent ); + WP_SaberRemoveG2Model(saberent); self->client->ps.saberInFlight = qfalse; self->client->ps.saberEntityState = 0; @@ -8719,12 +7043,10 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) } */ - if (!BG_SabersOff(&self->client->ps)) - { + if (!BG_SabersOff(&self->client->ps)) { gentity_t *saberent = &g_entities[saberNum]; - if (!self->client->ps.saberInFlight && saberent) - { + if (!self->client->ps.saberInFlight && saberent) { saberent->r.svFlags |= (SVF_NOCLIENT); saberent->r.contents = CONTENTS_LIGHTSABER; SetSaberBoxSize(saberent); @@ -8732,28 +7054,26 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) saberent->s.loopIsSoundset = qfalse; } - if (self->client->ps.saberLockTime > level.time && self->client->ps.saberEntityNum) - { - if (self->client->ps.saberIdleWound < level.time) - { + if (self->client->ps.saberLockTime > level.time && self->client->ps.saberEntityNum) { + if (self->client->ps.saberIdleWound < level.time) { gentity_t *te; vec3_t dir; - te = G_TempEntity( g_entities[saberNum].r.currentOrigin, EV_SABER_BLOCK ); - VectorSet( dir, 0, 1, 0 ); + te = G_TempEntity(g_entities[saberNum].r.currentOrigin, EV_SABER_BLOCK); + VectorSet(dir, 0, 1, 0); VectorCopy(g_entities[saberNum].r.currentOrigin, te->s.origin); VectorCopy(dir, te->s.angles); te->s.eventParm = 1; - te->s.weapon = 0;//saberNum - te->s.legsAnim = 0;//bladeNum + te->s.weapon = 0; // saberNum + te->s.legsAnim = 0; // bladeNum self->client->ps.saberIdleWound = level.time + Q_irand(400, 600); } - while (rSaberNum < MAX_SABERS) - { + while (rSaberNum < MAX_SABERS) { rBladeNum = 0; - while (rBladeNum < self->client->saber[rSaberNum].numBlades) - { //Don't bother updating the bolt for each blade for this, it's just a very rough fallback method for during saberlocks + while (rBladeNum < + self->client->saber[rSaberNum] + .numBlades) { // Don't bother updating the bolt for each blade for this, it's just a very rough fallback method for during saberlocks VectorCopy(boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].trail.base); VectorCopy(end, self->client->saber[rSaberNum].blade[rBladeNum].trail.tip); self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime = level.time; @@ -8770,29 +7090,24 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) goto finalUpdate; } - //reset it in case we used it for cycling before + // reset it in case we used it for cycling before rSaberNum = rBladeNum = 0; - if (self->client->ps.saberInFlight) - { //if saber is thrown then only do the standard stuff for the left hand saber - if (!self->client->ps.saberEntityNum) - { //however, if saber is not in flight but rather knocked away, our left saber is off, and thus we may do nothing. - rSaberNum = 1;//was 2? - } - else - {//thrown saber still in flight, so do damage - rSaberNum = 0;//was 1? + if (self->client->ps.saberInFlight) { // if saber is thrown then only do the standard stuff for the left hand saber + if (!self->client->ps + .saberEntityNum) { // however, if saber is not in flight but rather knocked away, our left saber is off, and thus we may do nothing. + rSaberNum = 1; // was 2? + } else { // thrown saber still in flight, so do damage + rSaberNum = 0; // was 1? } } WP_SaberClearDamage(); saberDoClashEffect = qfalse; - //Now cycle through each saber and each blade on the saber and do damage traces. - while (rSaberNum < MAX_SABERS) - { - if (!self->client->saber[rSaberNum].model[0]) - { + // Now cycle through each saber and each blade on the saber and do damage traces. + while (rSaberNum < MAX_SABERS) { + if (!self->client->saber[rSaberNum].model[0]) { rSaberNum++; continue; } @@ -8804,141 +7119,111 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) continue; } */ - //for now I'm keeping a broken right arm swingable, it will just look and act damaged - //but still be useable + // for now I'm keeping a broken right arm swingable, it will just look and act damaged + // but still be useable - if (rSaberNum == 1 && (self->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) - { //don't to saber 1 if the left arm is broken + if (rSaberNum == 1 && (self->client->ps.brokenLimbs & (1 << BROKENLIMB_LARM))) { // don't to saber 1 if the left arm is broken break; } - if (rSaberNum > 0 - && self->client->saber[1].model[0] - && self->client->ps.saberHolstered == 1 ) - { //don't to saber 2 if it's off + if (rSaberNum > 0 && self->client->saber[1].model[0] && self->client->ps.saberHolstered == 1) { // don't to saber 2 if it's off break; } rBladeNum = 0; - while (rBladeNum < self->client->saber[rSaberNum].numBlades) - { - //update muzzle data for the blade + while (rBladeNum < self->client->saber[rSaberNum].numBlades) { + // update muzzle data for the blade VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint, self->client->saber[rSaberNum].blade[rBladeNum].muzzlePointOld); VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDirOld); - if ( rBladeNum > 0 //more than one blade - && (!self->client->saber[1].model[0])//not using dual blades - && self->client->saber[rSaberNum].numBlades > 1//using a multi-bladed saber - && self->client->ps.saberHolstered == 1 )// - { //don't to extra blades if they're off + if (rBladeNum > 0 // more than one blade + && (!self->client->saber[1].model[0]) // not using dual blades + && self->client->saber[rSaberNum].numBlades > 1 // using a multi-bladed saber + && self->client->ps.saberHolstered == 1) // + { // don't to extra blades if they're off break; } - //get the new data - //then update the bolt pos/dir. rBladeNum corresponds to the bolt index because blade bolts are added in order. - if ( rSaberNum == 0 && self->client->ps.saberInFlight ) - { - if ( !self->client->ps.saberEntityNum ) - {//dropped it... shouldn't get here, but... - //assert(0); - //FIXME: It's getting here a lot actually.... + // get the new data + // then update the bolt pos/dir. rBladeNum corresponds to the bolt index because blade bolts are added in order. + if (rSaberNum == 0 && self->client->ps.saberInFlight) { + if (!self->client->ps.saberEntityNum) { // dropped it... shouldn't get here, but... + // assert(0); + // FIXME: It's getting here a lot actually.... rSaberNum++; rBladeNum = 0; continue; - } - else - { + } else { gentity_t *saberEnt = &g_entities[self->client->ps.saberEntityNum]; vec3_t saberOrg, saberAngles; - if ( !saberEnt - || !saberEnt->inuse - || !saberEnt->ghoul2 ) - {//wtf? + if (!saberEnt || !saberEnt->inuse || !saberEnt->ghoul2) { // wtf? rSaberNum++; rBladeNum = 0; continue; } - if ( saberent->s.saberInFlight ) - {//spinning - BG_EvaluateTrajectory( &saberEnt->s.pos, level.time+50, saberOrg ); - BG_EvaluateTrajectory( &saberEnt->s.apos, level.time+50, saberAngles ); - } - else - {//coming right back + if (saberent->s.saberInFlight) { // spinning + BG_EvaluateTrajectory(&saberEnt->s.pos, level.time + 50, saberOrg); + BG_EvaluateTrajectory(&saberEnt->s.apos, level.time + 50, saberAngles); + } else { // coming right back vec3_t saberDir; - BG_EvaluateTrajectory( &saberEnt->s.pos, level.time, saberOrg ); - VectorSubtract( self->r.currentOrigin, saberOrg, saberDir ); - vectoangles( saberDir, saberAngles ); + BG_EvaluateTrajectory(&saberEnt->s.pos, level.time, saberOrg); + VectorSubtract(self->r.currentOrigin, saberOrg, saberDir); + vectoangles(saberDir, saberAngles); } trap->G2API_GetBoltMatrix(saberEnt->ghoul2, 0, rBladeNum, &boltMatrix, saberAngles, saberOrg, level.time, NULL, self->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir); - VectorCopy( self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint, boltOrigin ); - VectorMA( boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].lengthMax, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir, end ); + VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint, boltOrigin); + VectorMA(boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].lengthMax, + self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir, end); } - } - else - { - trap->G2API_GetBoltMatrix(self->ghoul2, rSaberNum+1, rBladeNum, &boltMatrix, properAngles, properOrigin, level.time, NULL, self->modelScale); + } else { + trap->G2API_GetBoltMatrix(self->ghoul2, rSaberNum + 1, rBladeNum, &boltMatrix, properAngles, properOrigin, level.time, NULL, + self->modelScale); BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint); BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir); - VectorCopy( self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint, boltOrigin ); - VectorMA( boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].lengthMax, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir, end ); + VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].muzzlePoint, boltOrigin); + VectorMA(boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].lengthMax, self->client->saber[rSaberNum].blade[rBladeNum].muzzleDir, + end); } self->client->saber[rSaberNum].blade[rBladeNum].storageTime = level.time; - if (self->client->hasCurrentPosition && d_saberInterpolate.integer) - { - if (self->client->ps.weaponTime <= 0) - { //rww - 07/17/02 - don't bother doing the extra stuff unless actually attacking. This is in attempt to save CPU. - CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT), qfalse); - } - else if (d_saberInterpolate.integer == 1) - { - int trMask = CONTENTS_LIGHTSABER|CONTENTS_BODY; + if (self->client->hasCurrentPosition && d_saberInterpolate.integer) { + if (self->client->ps.weaponTime <= + 0) { // rww - 07/17/02 - don't bother doing the extra stuff unless actually attacking. This is in attempt to save CPU. + CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT), qfalse); + } else if (d_saberInterpolate.integer == 1) { + int trMask = CONTENTS_LIGHTSABER | CONTENTS_BODY; int sN = 0; qboolean gotHit = qfalse; qboolean clientUnlinked[MAX_CLIENTS]; qboolean skipSaberTrace = qfalse; - if (!g_saberTraceSaberFirst.integer) - { + if (!g_saberTraceSaberFirst.integer) { skipSaberTrace = qtrue; - } - else if (g_saberTraceSaberFirst.integer >= 2 && - level.gametype != GT_DUEL && - level.gametype != GT_POWERDUEL && - !self->client->ps.duelInProgress) - { //if value is >= 2, and not in a duel, skip + } else if (g_saberTraceSaberFirst.integer >= 2 && level.gametype != GT_DUEL && level.gametype != GT_POWERDUEL && + !self->client->ps.duelInProgress) { // if value is >= 2, and not in a duel, skip skipSaberTrace = qtrue; } - if (skipSaberTrace) - { //skip the saber-contents-only trace and get right to the full trace - trMask = (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT); - } - else - { - while (sN < MAX_CLIENTS) - { - if (g_entities[sN].inuse && g_entities[sN].client && g_entities[sN].r.linked && g_entities[sN].health > 0 && (g_entities[sN].r.contents & CONTENTS_BODY)) - { //Take this mask off before the saber trace, because we want to hit the saber first + if (skipSaberTrace) { // skip the saber-contents-only trace and get right to the full trace + trMask = (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT); + } else { + while (sN < MAX_CLIENTS) { + if (g_entities[sN].inuse && g_entities[sN].client && g_entities[sN].r.linked && g_entities[sN].health > 0 && + (g_entities[sN].r.contents & + CONTENTS_BODY)) { // Take this mask off before the saber trace, because we want to hit the saber first g_entities[sN].r.contents &= ~CONTENTS_BODY; clientUnlinked[sN] = qtrue; - } - else - { + } else { clientUnlinked[sN] = qfalse; } sN++; } } - while (!gotHit) - { - if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, trMask, qfalse)) - { - if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qtrue, trMask, qfalse)) - { + while (!gotHit) { + if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, trMask, qfalse)) { + if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qtrue, trMask, qfalse)) { vec3_t oldSaberStart; vec3_t oldSaberEnd; vec3_t saberAngleNow; @@ -8950,13 +7235,10 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) vec3_t saberSubBase; float deltaX, deltaY, deltaZ; - if ( (level.time-self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100 ) - {//no valid last pos, use current + if ((level.time - self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime) > 100) { // no valid last pos, use current VectorCopy(boltOrigin, oldSaberStart); VectorCopy(end, oldSaberEnd); - } - else - {//trace from last pos + } else { // trace from last pos VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.base, oldSaberStart); VectorCopy(self->client->saber[rSaberNum].blade[rBladeNum].trail.tip, oldSaberEnd); } @@ -8971,51 +7253,44 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) deltaY = AngleDelta(saberAngleBefore[1], saberAngleNow[1]); deltaZ = AngleDelta(saberAngleBefore[2], saberAngleNow[2]); - if ( (deltaX != 0 || deltaY != 0 || deltaZ != 0) && deltaX < 180 && deltaY < 180 && deltaZ < 180 && (BG_SaberInAttack(self->client->ps.saberMove) || PM_SaberInTransition(self->client->ps.saberMove)) ) - { //don't go beyond here if we aren't attacking/transitioning or the angle is too large. - //and don't bother if the angle is the same - saberMidAngle[0] = saberAngleBefore[0] + (deltaX/2); - saberMidAngle[1] = saberAngleBefore[1] + (deltaY/2); - saberMidAngle[2] = saberAngleBefore[2] + (deltaZ/2); - - //Now that I have the angle, I'll just say the base for it is the difference between the two start - //points (even though that's quite possibly completely false) + if ((deltaX != 0 || deltaY != 0 || deltaZ != 0) && deltaX < 180 && deltaY < 180 && deltaZ < 180 && + (BG_SaberInAttack(self->client->ps.saberMove) || + PM_SaberInTransition(self->client->ps.saberMove))) { // don't go beyond here if we aren't attacking/transitioning or + // the angle is too large. + // and don't bother if the angle is the same + saberMidAngle[0] = saberAngleBefore[0] + (deltaX / 2); + saberMidAngle[1] = saberAngleBefore[1] + (deltaY / 2); + saberMidAngle[2] = saberAngleBefore[2] + (deltaZ / 2); + + // Now that I have the angle, I'll just say the base for it is the difference between the two start + // points (even though that's quite possibly completely false) VectorSubtract(boltOrigin, oldSaberStart, saberSubBase); - saberMidPoint[0] = boltOrigin[0] + (saberSubBase[0]*0.5); - saberMidPoint[1] = boltOrigin[1] + (saberSubBase[1]*0.5); - saberMidPoint[2] = boltOrigin[2] + (saberSubBase[2]*0.5); + saberMidPoint[0] = boltOrigin[0] + (saberSubBase[0] * 0.5); + saberMidPoint[1] = boltOrigin[1] + (saberSubBase[1] * 0.5); + saberMidPoint[2] = boltOrigin[2] + (saberSubBase[2] * 0.5); AngleVectors(saberMidAngle, saberMidDir, 0, 0); - saberMidEnd[0] = saberMidPoint[0] + saberMidDir[0]*self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; - saberMidEnd[1] = saberMidPoint[1] + saberMidDir[1]*self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; - saberMidEnd[2] = saberMidPoint[2] + saberMidDir[2]*self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; + saberMidEnd[0] = saberMidPoint[0] + saberMidDir[0] * self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; + saberMidEnd[1] = saberMidPoint[1] + saberMidDir[1] * self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; + saberMidEnd[2] = saberMidPoint[2] + saberMidDir[2] * self->client->saber[rSaberNum].blade[rBladeNum].lengthMax; - //I'll just trace straight out and not even trace between positions to save speed. - if (CheckSaberDamage(self, rSaberNum, rBladeNum, saberMidPoint, saberMidEnd, qfalse, trMask, qfalse)) - { + // I'll just trace straight out and not even trace between positions to save speed. + if (CheckSaberDamage(self, rSaberNum, rBladeNum, saberMidPoint, saberMidEnd, qfalse, trMask, qfalse)) { gotHit = qtrue; } } - } - else - { + } else { gotHit = qtrue; } - } - else - { + } else { gotHit = qtrue; } - if (g_saberTraceSaberFirst.integer) - { + if (g_saberTraceSaberFirst.integer) { sN = 0; - while (sN < MAX_CLIENTS) - { - if (clientUnlinked[sN]) - { //Make clients clip properly again. - if (g_entities[sN].inuse && g_entities[sN].health > 0) - { + while (sN < MAX_CLIENTS) { + if (clientUnlinked[sN]) { // Make clients clip properly again. + if (g_entities[sN].inuse && g_entities[sN].health > 0) { g_entities[sN].r.contents |= CONTENTS_BODY; } } @@ -9023,46 +7298,37 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) } } - if (!gotHit) - { - if (trMask != (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT)) - { - trMask = (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT); - } - else - { - gotHit = qtrue; //break out of the loop + if (!gotHit) { + if (trMask != (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT)) { + trMask = (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT); + } else { + gotHit = qtrue; // break out of the loop } } } - } - else if (d_saberInterpolate.integer) //anything but 0 or 1, use the old plain method. + } else if (d_saberInterpolate.integer) // anything but 0 or 1, use the old plain method. { - if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT), qfalse)) - { - CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qtrue, (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT), qfalse); + if (!CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT), + qfalse)) { + CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qtrue, (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT), qfalse); } } - } - else if ( d_saberSPStyleDamage.integer ) - { - G_SPSaberDamageTraceLerped( self, rSaberNum, rBladeNum, boltOrigin, end, (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT) ); - } - else - { - CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID|CONTENTS_LIGHTSABER|MASK_SHOT), qfalse); + } else if (d_saberSPStyleDamage.integer) { + G_SPSaberDamageTraceLerped(self, rSaberNum, rBladeNum, boltOrigin, end, (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT)); + } else { + CheckSaberDamage(self, rSaberNum, rBladeNum, boltOrigin, end, qfalse, (MASK_PLAYERSOLID | CONTENTS_LIGHTSABER | MASK_SHOT), qfalse); } VectorCopy(boltOrigin, self->client->saber[rSaberNum].blade[rBladeNum].trail.base); VectorCopy(end, self->client->saber[rSaberNum].blade[rBladeNum].trail.tip); self->client->saber[rSaberNum].blade[rBladeNum].trail.lastTime = level.time; - //VectorCopy(boltOrigin, self->client->lastSaberBase); - //VectorCopy(end, self->client->lastSaberTip); + // VectorCopy(boltOrigin, self->client->lastSaberBase); + // VectorCopy(end, self->client->lastSaberTip); self->client->hasCurrentPosition = qtrue; - //do hit effects - WP_SaberDoHit( self, rSaberNum, rBladeNum ); - WP_SaberDoClash( self, rSaberNum, rBladeNum ); + // do hit effects + WP_SaberDoHit(self, rSaberNum, rBladeNum); + WP_SaberDoClash(self, rSaberNum, rBladeNum); rBladeNum++; } @@ -9070,35 +7336,30 @@ void WP_SaberPositionUpdate( gentity_t *self, usercmd_t *ucmd ) rSaberNum++; } - WP_SaberApplyDamage( self ); - //NOTE: doing one call like this after the 2 loops above is a bit cheaper, tempentity-wise... but won't use the correct saber and blade numbers... - //now actually go through and apply all the damage we did - //WP_SaberDoHit( self, 0, 0 ); - //WP_SaberDoClash( self, 0, 0 ); + WP_SaberApplyDamage(self); + // NOTE: doing one call like this after the 2 loops above is a bit cheaper, tempentity-wise... but won't use the correct saber and blade numbers... + // now actually go through and apply all the damage we did + // WP_SaberDoHit( self, 0, 0 ); + // WP_SaberDoClash( self, 0, 0 ); - if (mySaber && mySaber->inuse) - { + if (mySaber && mySaber->inuse) { trap->LinkEntity((sharedEntity_t *)mySaber); } - if (!self->client->ps.saberInFlight) - { + if (!self->client->ps.saberInFlight) { self->client->ps.saberEntityState = 0; } } finalUpdate: - if (clientOverride) - { //if we get the client instance we don't even need to bother setting anims and stuff + if (clientOverride) { // if we get the client instance we don't even need to bother setting anims and stuff return; } G_UpdateClientAnims(self, animSpeedScale); } -int WP_MissileBlockForBlock( int saberBlock ) -{ - switch( saberBlock ) - { +int WP_MissileBlockForBlock(int saberBlock) { + switch (saberBlock) { case BLOCKED_UPPER_RIGHT: return BLOCKED_UPPER_RIGHT_PROJ; break; @@ -9118,9 +7379,8 @@ int WP_MissileBlockForBlock( int saberBlock ) return saberBlock; } -void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlock ) -{ - vec3_t diff, fwdangles={0,0,0}, right; +void WP_SaberBlockNonRandom(gentity_t *self, vec3_t hitloc, qboolean missileBlock) { + vec3_t diff, fwdangles = {0, 0, 0}, right; vec3_t clEye; float rightdot; float zdiff; @@ -9128,72 +7388,52 @@ void WP_SaberBlockNonRandom( gentity_t *self, vec3_t hitloc, qboolean missileBlo VectorCopy(self->client->ps.origin, clEye); clEye[2] += self->client->ps.viewheight; - VectorSubtract( hitloc, clEye, diff ); + VectorSubtract(hitloc, clEye, diff); diff[2] = 0; - VectorNormalize( diff ); + VectorNormalize(diff); fwdangles[1] = self->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); rightdot = DotProduct(right, diff); zdiff = hitloc[2] - clEye[2]; - if ( zdiff > 0 ) - { - if ( rightdot > 0.3 ) - { + if (zdiff > 0) { + if (rightdot > 0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.3 ) - { + } else if (rightdot < -0.3) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else if ( zdiff > -20 )//20 ) + } else if (zdiff > -20) // 20 ) { - if ( zdiff < -10 )//30 ) - {//hmm, pretty low, but not low enough to use the low block, so we need to duck - + if (zdiff < -10) // 30 ) + { // hmm, pretty low, but not low enough to use the low block, so we need to duck } - if ( rightdot > 0.1 ) - { + if (rightdot > 0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; - } - else if ( rightdot < -0.1 ) - { + } else if (rightdot < -0.1) { self->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_TOP; } - } - else - { - if ( rightdot >= 0 ) - { + } else { + if (rightdot >= 0) { self->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { self->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - if ( missileBlock ) - { - self->client->ps.saberBlocked = WP_MissileBlockForBlock( self->client->ps.saberBlocked ); + if (missileBlock) { + self->client->ps.saberBlocked = WP_MissileBlockForBlock(self->client->ps.saberBlocked); } } -void WP_SaberBlock( gentity_t *playerent, vec3_t hitloc, qboolean missileBlock ) -{ - vec3_t diff, fwdangles={0,0,0}, right; +void WP_SaberBlock(gentity_t *playerent, vec3_t hitloc, qboolean missileBlock) { + vec3_t diff, fwdangles = {0, 0, 0}, right; float rightdot; float zdiff; @@ -9202,40 +7442,27 @@ void WP_SaberBlock( gentity_t *playerent, vec3_t hitloc, qboolean missileBlock ) fwdangles[1] = playerent->client->ps.viewangles[1]; // Ultimately we might care if the shot was ahead or behind, but for now, just quadrant is fine. - AngleVectors( fwdangles, NULL, right, NULL ); + AngleVectors(fwdangles, NULL, right, NULL); - rightdot = DotProduct(right, diff) + RandFloat(-0.2f,0.2f); - zdiff = hitloc[2] - playerent->client->ps.origin[2] + Q_irand(-8,8); + rightdot = DotProduct(right, diff) + RandFloat(-0.2f, 0.2f); + zdiff = hitloc[2] - playerent->client->ps.origin[2] + Q_irand(-8, 8); // Figure out what quadrant the block was in. - if (zdiff > 24) - { // Attack from above - if (Q_irand(0,1)) - { + if (zdiff > 24) { // Attack from above + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_TOP; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; } - } - else if (zdiff > 13) - { // The upper half has three viable blocks... - if (rightdot > 0.25) - { // In the right quadrant... - if (Q_irand(0,1)) - { + } else if (zdiff > 13) { // The upper half has three viable blocks... + if (rightdot > 0.25) { // In the right quadrant... + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_UPPER_LEFT; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } - } - else - { - switch(Q_irand(0,3)) - { + } else { + switch (Q_irand(0, 3)) { case 0: playerent->client->ps.saberBlocked = BLOCKED_UPPER_RIGHT; break; @@ -9248,82 +7475,64 @@ void WP_SaberBlock( gentity_t *playerent, vec3_t hitloc, qboolean missileBlock ) break; } } - } - else - { // The lower half is a bit iffy as far as block coverage. Pick one of the "low" ones at random. - if (Q_irand(0,1)) - { + } else { // The lower half is a bit iffy as far as block coverage. Pick one of the "low" ones at random. + if (Q_irand(0, 1)) { playerent->client->ps.saberBlocked = BLOCKED_LOWER_RIGHT; - } - else - { + } else { playerent->client->ps.saberBlocked = BLOCKED_LOWER_LEFT; } } - if ( missileBlock ) - { - playerent->client->ps.saberBlocked = WP_MissileBlockForBlock( playerent->client->ps.saberBlocked ); + if (missileBlock) { + playerent->client->ps.saberBlocked = WP_MissileBlockForBlock(playerent->client->ps.saberBlocked); } } -int WP_SaberCanBlock(gentity_t *self, vec3_t point, int dflags, int mod, qboolean projectile, int attackStr) -{ +int WP_SaberCanBlock(gentity_t *self, vec3_t point, int dflags, int mod, qboolean projectile, int attackStr) { qboolean thrownSaber = qfalse; float blockFactor = 0; - if (!self || !self->client || !point) - { + if (!self || !self->client || !point) { return 0; } - if (attackStr == 999) - { + if (attackStr == 999) { attackStr = 0; thrownSaber = qtrue; } - if (BG_SaberInAttack(self->client->ps.saberMove)) - { + if (BG_SaberInAttack(self->client->ps.saberMove)) { return 0; } - if (PM_InSaberAnim(self->client->ps.torsoAnim) && !self->client->ps.saberBlocked && - self->client->ps.saberMove != LS_READY && self->client->ps.saberMove != LS_NONE) - { - if ( self->client->ps.saberMove < LS_PARRY_UP || self->client->ps.saberMove > LS_REFLECT_LL ) - { + if (PM_InSaberAnim(self->client->ps.torsoAnim) && !self->client->ps.saberBlocked && self->client->ps.saberMove != LS_READY && + self->client->ps.saberMove != LS_NONE) { + if (self->client->ps.saberMove < LS_PARRY_UP || self->client->ps.saberMove > LS_REFLECT_LL) { return 0; } } - if (PM_SaberInBrokenParry(self->client->ps.saberMove)) - { + if (PM_SaberInBrokenParry(self->client->ps.saberMove)) { return 0; } - if (!self->client->ps.saberEntityNum) - { //saber is knocked away + if (!self->client->ps.saberEntityNum) { // saber is knocked away return 0; } - if (BG_SabersOff( &self->client->ps )) - { + if (BG_SabersOff(&self->client->ps)) { return 0; } - if (self->client->ps.weapon != WP_SABER) - { + if (self->client->ps.weapon != WP_SABER) { return 0; } - if (self->client->ps.weaponstate == WEAPON_RAISING) - { + if (self->client->ps.weaponstate == WEAPON_RAISING) { return 0; } - if (self->client->ps.saberInFlight) - { + if (self->client->ps.saberInFlight) { return 0; } @@ -9333,8 +7542,8 @@ int WP_SaberCanBlock(gentity_t *self, vec3_t point, int dflags, int mod, qboolea return 0; } - //Removed this for now, the new broken parry stuff should handle it. This is how - //blocks were decided before the 1.03 patch (as you can see, it was STUPID.. for the most part) + // Removed this for now, the new broken parry stuff should handle it. This is how + // blocks were decided before the 1.03 patch (as you can see, it was STUPID.. for the most part) /* if (attackStr == FORCE_LEVEL_3) { @@ -9377,97 +7586,71 @@ int WP_SaberCanBlock(gentity_t *self, vec3_t point, int dflags, int mod, qboolea } */ - if (SaberAttacking(self)) - { //attacking, can't block now + if (SaberAttacking(self)) { // attacking, can't block now return 0; } - if (self->client->ps.saberMove != LS_READY && - !self->client->ps.saberBlocking) - { + if (self->client->ps.saberMove != LS_READY && !self->client->ps.saberBlocking) { return 0; } - if (self->client->ps.saberBlockTime >= level.time) - { + if (self->client->ps.saberBlockTime >= level.time) { return 0; } - if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) - { + if (self->client->ps.forceHandExtend != HANDEXTEND_NONE) { return 0; } - if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_3) - { - if (d_saberGhoul2Collision.integer) - { + if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_3) { + if (d_saberGhoul2Collision.integer) { blockFactor = 0.3f; - } - else - { + } else { blockFactor = 0.05f; } - } - else if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_2) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_2) { blockFactor = 0.6f; - } - else if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_1) - { + } else if (self->client->ps.fd.forcePowerLevel[FP_SABER_DEFENSE] == FORCE_LEVEL_1) { blockFactor = 0.9f; - } - else - { //for now we just don't get to autoblock with no def + } else { // for now we just don't get to autoblock with no def return 0; } - if (thrownSaber) - { + if (thrownSaber) { blockFactor -= 0.25f; } - if (attackStr) - { //blocking a saber, not a projectile. + if (attackStr) { // blocking a saber, not a projectile. blockFactor -= 0.25f; } - if (!InFront( point, self->client->ps.origin, self->client->ps.viewangles, blockFactor )) //orig 0.2f + if (!InFront(point, self->client->ps.origin, self->client->ps.viewangles, blockFactor)) // orig 0.2f { return 0; } - if (projectile) - { + if (projectile) { WP_SaberBlockNonRandom(self, point, projectile); } return 1; } -qboolean HasSetSaberOnly(void) -{ +qboolean HasSetSaberOnly(void) { int i = 0; int wDisable = 0; - if (level.gametype == GT_JEDIMASTER) - { //set to 0 + if (level.gametype == GT_JEDIMASTER) { // set to 0 return qfalse; } - if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) - { + if (level.gametype == GT_DUEL || level.gametype == GT_POWERDUEL) { wDisable = g_duelWeaponDisable.integer; - } - else - { + } else { wDisable = g_weaponDisable.integer; } - while (i < WP_NUM_WEAPONS) - { - if (!(wDisable & (1 << i)) && - i != WP_SABER && i != WP_NONE) - { + while (i < WP_NUM_WEAPONS) { + if (!(wDisable & (1 << i)) && i != WP_SABER && i != WP_NONE) { return qfalse; } diff --git a/codemp/ghoul2/G2_gore.cpp b/codemp/ghoul2/G2_gore.cpp index ecc90dba8d..2a8224e776 100644 --- a/codemp/ghoul2/G2_gore.cpp +++ b/codemp/ghoul2/G2_gore.cpp @@ -25,17 +25,11 @@ along with this program; if not, see . #ifdef _G2_GORE -GoreTextureCoordinates::GoreTextureCoordinates() -{ - Com_Memset (tex, 0, sizeof (tex)); -} +GoreTextureCoordinates::GoreTextureCoordinates() { Com_Memset(tex, 0, sizeof(tex)); } -GoreTextureCoordinates::~GoreTextureCoordinates() -{ - for ( int i = 0; i < MAX_LODS; i++ ) - { - if ( tex[i] ) - { +GoreTextureCoordinates::~GoreTextureCoordinates() { + for (int i = 0; i < MAX_LODS; i++) { + if (tex[i]) { ri.Z_Free(tex[i]); tex[i] = NULL; } diff --git a/codemp/icarus/BlockStream.cpp b/codemp/icarus/BlockStream.cpp index 2c0398186a..adebead8e9 100644 --- a/codemp/icarus/BlockStream.cpp +++ b/codemp/icarus/BlockStream.cpp @@ -38,17 +38,13 @@ along with this program; if not, see . =================================================================================================== */ -CBlockMember::CBlockMember( void ) -{ +CBlockMember::CBlockMember(void) { m_id = -1; m_size = -1; m_data = NULL; } -CBlockMember::~CBlockMember( void ) -{ - Free(); -} +CBlockMember::~CBlockMember(void) { Free(); } /* ------------------------- @@ -56,11 +52,9 @@ Free ------------------------- */ -void CBlockMember::Free( void ) -{ - if ( m_data != NULL ) - { - ICARUS_Free ( m_data ); +void CBlockMember::Free(void) { + if (m_data != NULL) { + ICARUS_Free(m_data); m_data = NULL; m_id = m_size = -1; @@ -73,8 +67,7 @@ GetInfo ------------------------- */ -void CBlockMember::GetInfo( int *id, int *size, void **data ) -{ +void CBlockMember::GetInfo(int *id, int *size, void **data) { *id = m_id; *size = m_size; *data = m_data; @@ -86,23 +79,16 @@ SetData overloads ------------------------- */ -void CBlockMember::SetData( const char *data ) -{ - WriteDataPointer( data, strlen(data)+1 ); -} +void CBlockMember::SetData(const char *data) { WriteDataPointer(data, strlen(data) + 1); } -void CBlockMember::SetData( vector_t data ) -{ - WriteDataPointer( data, 3 ); -} +void CBlockMember::SetData(vector_t data) { WriteDataPointer(data, 3); } -void CBlockMember::SetData( void *data, int size ) -{ - if ( m_data ) - ICARUS_Free( m_data ); +void CBlockMember::SetData(void *data, int size) { + if (m_data) + ICARUS_Free(m_data); - m_data = ICARUS_Malloc( size ); - memcpy( m_data, data, size ); + m_data = ICARUS_Malloc(size); + memcpy(m_data, data, size); m_size = size; } @@ -114,25 +100,22 @@ ReadMember ------------------------- */ -int CBlockMember::ReadMember( char **stream, int *streamPos ) -{ - m_id = LittleLong(*(int *) (*stream + *((int *)streamPos))); - *streamPos += sizeof( int ); +int CBlockMember::ReadMember(char **stream, int *streamPos) { + m_id = LittleLong(*(int *)(*stream + *((int *)streamPos))); + *streamPos += sizeof(int); - if ( m_id == ID_RANDOM ) - {//special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time random is checked when inside a wait - m_size = sizeof( float ); - *streamPos += sizeof( int ); - m_data = ICARUS_Malloc( m_size ); + if (m_id == ID_RANDOM) { // special case, need to initialize this member's data to Q3_INFINITE so we can randomize the number only the first time random is + // checked when inside a wait + m_size = sizeof(float); + *streamPos += sizeof(int); + m_data = ICARUS_Malloc(m_size); float infinite = Q3_INFINITE; - memcpy( m_data, &infinite, m_size ); - } - else - { - m_size = LittleLong(*(int *) (*stream + *streamPos)); - *streamPos += sizeof( int ); - m_data = ICARUS_Malloc( m_size ); - memcpy( m_data, (*stream + *streamPos), m_size ); + memcpy(m_data, &infinite, m_size); + } else { + m_size = LittleLong(*(int *)(*stream + *streamPos)); + *streamPos += sizeof(int); + m_data = ICARUS_Malloc(m_size); + memcpy(m_data, (*stream + *streamPos), m_size); #ifdef Q3_BIG_ENDIAN // only TK_INT, TK_VECTOR and TK_FLOAT has to be swapped, but just in case if (m_size == 4 && m_id != TK_STRING && m_id != TK_IDENTIFIER && m_id != TK_CHAR) @@ -150,11 +133,10 @@ WriteMember ------------------------- */ -int CBlockMember::WriteMember( FILE *m_fileHandle ) -{ - fwrite( &m_id, sizeof(m_id), 1, m_fileHandle ); - fwrite( &m_size, sizeof(m_size), 1, m_fileHandle ); - fwrite( m_data, m_size, 1, m_fileHandle ); +int CBlockMember::WriteMember(FILE *m_fileHandle) { + fwrite(&m_id, sizeof(m_id), 1, m_fileHandle); + fwrite(&m_size, sizeof(m_size), 1, m_fileHandle); + fwrite(m_data, m_size, 1, m_fileHandle); return true; } @@ -165,16 +147,15 @@ Duplicate ------------------------- */ -CBlockMember *CBlockMember::Duplicate( void ) -{ - CBlockMember *newblock = new CBlockMember; +CBlockMember *CBlockMember::Duplicate(void) { + CBlockMember *newblock = new CBlockMember; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->SetData( m_data, m_size ); - newblock->SetSize( m_size ); - newblock->SetID( m_id ); + newblock->SetData(m_data, m_size); + newblock->SetSize(m_size); + newblock->SetID(m_id); return newblock; } @@ -187,16 +168,12 @@ CBlockMember *CBlockMember::Duplicate( void ) =================================================================================================== */ -CBlock::CBlock( void ) -{ - m_flags = 0; - m_id = 0; +CBlock::CBlock(void) { + m_flags = 0; + m_id = 0; } -CBlock::~CBlock( void ) -{ - Free(); -} +CBlock::~CBlock(void) { Free(); } /* ------------------------- @@ -204,10 +181,9 @@ Init ------------------------- */ -int CBlock::Init( void ) -{ - m_flags = 0; - m_id = 0; +int CBlock::Init(void) { + m_flags = 0; + m_id = 0; return true; } @@ -218,8 +194,7 @@ Create ------------------------- */ -int CBlock::Create( int block_id ) -{ +int CBlock::Create(int block_id) { Init(); m_id = block_id; @@ -233,14 +208,12 @@ Free ------------------------- */ -int CBlock::Free( void ) -{ - int numMembers = GetNumMembers(); - CBlockMember *bMember; +int CBlock::Free(void) { + int numMembers = GetNumMembers(); + CBlockMember *bMember; - while ( numMembers-- ) - { - bMember = GetMember( numMembers ); + while (numMembers--) { + bMember = GetMember(numMembers); if (!bMember) return false; @@ -248,7 +221,7 @@ int CBlock::Free( void ) delete bMember; } - m_members.clear(); //List of all CBlockMembers owned by this list + m_members.clear(); // List of all CBlockMembers owned by this list return true; } @@ -261,67 +234,61 @@ Write ------------------------- */ -int CBlock::Write( int member_id, const char *member_data ) -{ +int CBlock::Write(int member_id, const char *member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); + bMember->SetID(member_id); - bMember->SetData( member_data ); - bMember->SetSize( strlen(member_data) + 1 ); + bMember->SetData(member_data); + bMember->SetSize(strlen(member_data) + 1); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, vector_t member_data ) -{ +int CBlock::Write(int member_id, vector_t member_data) { CBlockMember *bMember; bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->SetData( member_data ); - bMember->SetSize( sizeof(vector_t) ); + bMember->SetID(member_id); + bMember->SetData(member_data); + bMember->SetSize(sizeof(vector_t)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, float member_data ) -{ +int CBlock::Write(int member_id, float member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data ); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } -int CBlock::Write( int member_id, int member_data ) -{ +int CBlock::Write(int member_id, int member_data) { CBlockMember *bMember = new CBlockMember; - bMember->SetID( member_id ); - bMember->WriteData( member_data ); - bMember->SetSize( sizeof(member_data) ); + bMember->SetID(member_id); + bMember->WriteData(member_data); + bMember->SetSize(sizeof(member_data)); - AddMember( bMember ); + AddMember(bMember); return true; } +int CBlock::Write(CBlockMember *bMember) { + // findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); -int CBlock::Write( CBlockMember *bMember ) -{ -// findme: this is wrong: bMember->SetSize( sizeof(bMember->GetData()) ); - - AddMember( bMember ); + AddMember(bMember); return true; } @@ -334,9 +301,8 @@ AddMember ------------------------- */ -int CBlock::AddMember( CBlockMember *member ) -{ - m_members.insert( m_members.end(), member ); +int CBlock::AddMember(CBlockMember *member) { + m_members.insert(m_members.end(), member); return true; } @@ -346,13 +312,11 @@ GetMember ------------------------- */ -CBlockMember *CBlock::GetMember( int memberNum ) -{ - if ( memberNum > GetNumMembers()-1 ) - { +CBlockMember *CBlock::GetMember(int memberNum) { + if (memberNum > GetNumMembers() - 1) { return NULL; } - return m_members[ memberNum ]; + return m_members[memberNum]; } /* @@ -361,13 +325,11 @@ GetMemberData ------------------------- */ -void *CBlock::GetMemberData( int memberNum ) -{ - if ( memberNum >= GetNumMembers() ) - { +void *CBlock::GetMemberData(int memberNum) { + if (memberNum >= GetNumMembers()) { return NULL; } - return (void *) ((GetMember( memberNum ))->GetData()); + return (void *)((GetMember(memberNum))->GetData()); } /* @@ -376,22 +338,20 @@ Duplicate ------------------------- */ -CBlock *CBlock::Duplicate( void ) -{ - blockMember_v::iterator mi; - CBlock *newblock; +CBlock *CBlock::Duplicate(void) { + blockMember_v::iterator mi; + CBlock *newblock; newblock = new CBlock; - if ( newblock == NULL ) + if (newblock == NULL) return NULL; - newblock->Create( m_id ); + newblock->Create(m_id); - //Duplicate entire block and return the cc - for ( mi = m_members.begin(); mi != m_members.end(); ++mi ) - { - newblock->AddMember( (*mi)->Duplicate() ); + // Duplicate entire block and return the cc + for (mi = m_members.begin(); mi != m_members.end(); ++mi) { + newblock->AddMember((*mi)->Duplicate()); } return newblock; @@ -405,15 +365,12 @@ CBlock *CBlock::Duplicate( void ) =================================================================================================== */ -CBlockStream::CBlockStream( void ) -{ +CBlockStream::CBlockStream(void) { m_stream = NULL; m_streamPos = 0; } -CBlockStream::~CBlockStream( void ) -{ -} +CBlockStream::~CBlockStream(void) {} /* ------------------------- @@ -421,12 +378,11 @@ GetChar ------------------------- */ -char CBlockStream::GetChar( void ) -{ +char CBlockStream::GetChar(void) { char data; - data = *(char*) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(char *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -437,12 +393,11 @@ GetUnsignedInteger ------------------------- */ -unsigned CBlockStream::GetUnsignedInteger( void ) -{ +unsigned CBlockStream::GetUnsignedInteger(void) { unsigned data; - data = *(unsigned *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(unsigned *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -453,12 +408,11 @@ GetInteger ------------------------- */ -int CBlockStream::GetInteger( void ) -{ +int CBlockStream::GetInteger(void) { int data; - data = *(int *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(int *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -469,12 +423,11 @@ GetLong ------------------------- */ -long CBlockStream::GetLong( void ) -{ +long CBlockStream::GetLong(void) { long data; - data = *(int *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(int *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -485,12 +438,11 @@ GetFloat ------------------------- */ -float CBlockStream::GetFloat( void ) -{ +float CBlockStream::GetFloat(void) { float data; - data = *(float *) (m_stream + m_streamPos); - m_streamPos += sizeof( data ); + data = *(float *)(m_stream + m_streamPos); + m_streamPos += sizeof(data); return data; } @@ -501,9 +453,8 @@ Free ------------------------- */ -int CBlockStream::Free( void ) -{ - //NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call +int CBlockStream::Free(void) { + // NOTENOTE: It is assumed that the user will free the passed memory block (m_stream) immediately after the run call // That's why this doesn't free the memory, it only clears its internal pointer m_stream = NULL; @@ -518,22 +469,20 @@ Create ------------------------- */ -int CBlockStream::Create( char *filename ) -{ - char *id_header = IBI_HEADER_ID; - float version = IBI_VERSION; +int CBlockStream::Create(char *filename) { + char *id_header = IBI_HEADER_ID; + float version = IBI_VERSION; - //Strip the extension and add the BLOCK_EXT extension - COM_StripExtension( filename, m_fileName, sizeof(m_fileName) ); - COM_DefaultExtension( m_fileName, sizeof(m_fileName), IBI_EXT ); + // Strip the extension and add the BLOCK_EXT extension + COM_StripExtension(filename, m_fileName, sizeof(m_fileName)); + COM_DefaultExtension(m_fileName, sizeof(m_fileName), IBI_EXT); - if ( (m_fileHandle = fopen(m_fileName, "wb")) == NULL ) - { + if ((m_fileHandle = fopen(m_fileName, "wb")) == NULL) { return false; } - fwrite( id_header, IBI_HEADER_ID_LENGTH, 1, m_fileHandle ); - fwrite( &version, sizeof(version), 1, m_fileHandle ); + fwrite(id_header, IBI_HEADER_ID_LENGTH, 1, m_fileHandle); + fwrite(&version, sizeof(version), 1, m_fileHandle); return true; } @@ -544,8 +493,7 @@ Init ------------------------- */ -int CBlockStream::Init( void ) -{ +int CBlockStream::Init(void) { m_fileHandle = NULL; memset(m_fileName, 0, sizeof(m_fileName)); @@ -563,21 +511,19 @@ WriteBlock ------------------------- */ -int CBlockStream::WriteBlock( CBlock *block ) -{ - CBlockMember *bMember; - int id = block->GetBlockID(); - int numMembers = block->GetNumMembers(); - unsigned char flags = block->GetFlags(); - - fwrite ( &id, sizeof(id), 1, m_fileHandle ); - fwrite ( &numMembers, sizeof(numMembers), 1, m_fileHandle ); - fwrite ( &flags, sizeof( flags ), 1, m_fileHandle ); - - for ( int i = 0; i < numMembers; i++ ) - { - bMember = block->GetMember( i ); - bMember->WriteMember( m_fileHandle ); +int CBlockStream::WriteBlock(CBlock *block) { + CBlockMember *bMember; + int id = block->GetBlockID(); + int numMembers = block->GetNumMembers(); + unsigned char flags = block->GetFlags(); + + fwrite(&id, sizeof(id), 1, m_fileHandle); + fwrite(&numMembers, sizeof(numMembers), 1, m_fileHandle); + fwrite(&flags, sizeof(flags), 1, m_fileHandle); + + for (int i = 0; i < numMembers; i++) { + bMember = block->GetMember(i); + bMember->WriteMember(m_fileHandle); } block->Free(); @@ -591,9 +537,8 @@ BlockAvailable ------------------------- */ -int CBlockStream::BlockAvailable( void ) -{ - if ( m_streamPos >= m_fileSize ) +int CBlockStream::BlockAvailable(void) { + if (m_streamPos >= m_fileSize) return false; return true; @@ -605,32 +550,30 @@ ReadBlock ------------------------- */ -int CBlockStream::ReadBlock( CBlock *get ) -{ - CBlockMember *bMember; - int b_id, numMembers; - unsigned char flags; +int CBlockStream::ReadBlock(CBlock *get) { + CBlockMember *bMember; + int b_id, numMembers; + unsigned char flags; if (!BlockAvailable()) return false; - b_id = LittleLong(GetInteger()); - numMembers = LittleLong(GetInteger()); - flags = (unsigned char) GetChar(); + b_id = LittleLong(GetInteger()); + numMembers = LittleLong(GetInteger()); + flags = (unsigned char)GetChar(); if (numMembers < 0) return false; - get->Create( b_id ); - get->SetFlags( flags ); + get->Create(b_id); + get->SetFlags(flags); // Stream blocks are generally temporary as they // are just used in an initial parsing phase... - while ( numMembers-- > 0) - { + while (numMembers-- > 0) { bMember = new CBlockMember; - bMember->ReadMember( &m_stream, &m_streamPos ); - get->AddMember( bMember ); + bMember->ReadMember(&m_stream, &m_streamPos); + get->AddMember(bMember); } return true; @@ -642,10 +585,9 @@ Open ------------------------- */ -int CBlockStream::Open( char *buffer, long size ) -{ - char id_header[IBI_HEADER_ID_LENGTH]; - float version; +int CBlockStream::Open(char *buffer, long size) { + char id_header[IBI_HEADER_ID_LENGTH]; + float version; Init(); @@ -653,24 +595,21 @@ int CBlockStream::Open( char *buffer, long size ) m_stream = buffer; - for ( size_t i = 0; i < sizeof( id_header ); i++ ) - { + for (size_t i = 0; i < sizeof(id_header); i++) { id_header[i] = GetChar(); } version = GetFloat(); version = LittleFloat(version); - //Check for valid header - if ( strcmp( id_header, IBI_HEADER_ID ) ) - { + // Check for valid header + if (strcmp(id_header, IBI_HEADER_ID)) { Free(); return false; } - //Check for valid version - if ( version != IBI_VERSION ) - { + // Check for valid version + if (version != IBI_VERSION) { Free(); return false; } diff --git a/codemp/icarus/GameInterface.cpp b/codemp/icarus/GameInterface.cpp index d32b2bb964..b1eb1d3126 100644 --- a/codemp/icarus/GameInterface.cpp +++ b/codemp/icarus/GameInterface.cpp @@ -21,7 +21,7 @@ along with this program; if not, see . */ // ICARUS Utility functions -//rww - mangled to work in server exe setting. +// rww - mangled to work in server exe setting. #include "game/g_public.h" #include "server/server.h" @@ -31,14 +31,14 @@ along with this program; if not, see . #include "Q3_Interface.h" #include "server/sv_gameapi.h" -ICARUS_Instance *iICARUS; -bufferlist_t ICARUS_BufferList; -entlist_t ICARUS_EntList; +ICARUS_Instance *iICARUS; +bufferlist_t ICARUS_BufferList; +entlist_t ICARUS_EntList; -extern uint32_t Com_BlockChecksum (const void *buffer, int length); -extern void Q3_DebugPrint( int level, const char *format, ... ); +extern uint32_t Com_BlockChecksum(const void *buffer, int length); +extern void Q3_DebugPrint(int level, const char *format, ...); -int ICARUS_entFilter = -1; +int ICARUS_entFilter = -1; /* ============= @@ -48,26 +48,23 @@ gets the named script from the cache or disk if not already loaded ============= */ -int ICARUS_GetScript( const char *name, char **buf ) -{ - bufferlist_t::iterator ei; - //Make sure the caller is valid +int ICARUS_GetScript(const char *name, char **buf) { + bufferlist_t::iterator ei; + // Make sure the caller is valid - //Attempt to retrieve a precached script - ei = ICARUS_BufferList.find( (char *) name ); + // Attempt to retrieve a precached script + ei = ICARUS_BufferList.find((char *)name); - //Not found, check the disk - if ( ei == ICARUS_BufferList.end() ) - { - if ( ICARUS_RegisterScript( name ) == false ) + // Not found, check the disk + if (ei == ICARUS_BufferList.end()) { + if (ICARUS_RegisterScript(name) == false) return 0; - //Script is now inserted, retrieve it and pass through - ei = ICARUS_BufferList.find( (char *) name ); + // Script is now inserted, retrieve it and pass through + ei = ICARUS_BufferList.find((char *)name); - if ( ei == ICARUS_BufferList.end() ) - { - //NOTENOTE: This is an internal error in STL if this happens... + if (ei == ICARUS_BufferList.end()) { + // NOTENOTE: This is an internal error in STL if this happens... assert(0); return 0; } @@ -84,67 +81,57 @@ ICARUS_RunScript Runs the script by the given name ============= */ -int ICARUS_RunScript( sharedEntity_t *ent, const char *name ) -{ +int ICARUS_RunScript(sharedEntity_t *ent, const char *name) { char *buf; int len; - //Make sure the caller is valid - if ( gSequencers[ent->s.number] == NULL ) - { - //Com_Printf( "%s : entity is not a valid script user\n", ent->classname ); + // Make sure the caller is valid + if (gSequencers[ent->s.number] == NULL) { + // Com_Printf( "%s : entity is not a valid script user\n", ent->classname ); return false; } #ifdef _HACK_FOR_TESTING_ONLY_1 char namex[1024]; char *blah = strstr(name, "stu/"); int r = blah - name; - if (blah) - { + if (blah) { int i = 0; - while (i < r) - { + while (i < r) { namex[i] = name[i]; i++; } namex[i] = 0; strcat(namex, "ignorethisfolder/"); i = strlen(namex); - while (name[r] != '/') - { + while (name[r] != '/') { r++; } r++; - while (name[r]) - { + while (name[r]) { namex[i] = name[r]; r++; i++; } namex[i] = 0; - } - else - { + } else { strcpy(namex, name); } - len = ICARUS_GetScript (namex, &buf); + len = ICARUS_GetScript(namex, &buf); #else - len = ICARUS_GetScript (name, &buf); + len = ICARUS_GetScript(name, &buf); #endif - if (len == 0) - { + if (len == 0) { return false; } - //Attempt to run the script - if S_FAILED(gSequencers[ent->s.number]->Run( buf, len )) + // Attempt to run the script + if S_FAILED (gSequencers[ent->s.number]->Run(buf, len)) return false; - if ( ( ICARUS_entFilter == -1 ) || ( ICARUS_entFilter == ent->s.number ) ) - { - Q3_DebugPrint( WL_VERBOSE, "%d Script %s executed by %s %s\n", svs.time, (char *) name, ent->classname, ent->targetname ); + if ((ICARUS_entFilter == -1) || (ICARUS_entFilter == ent->s.number)) { + Q3_DebugPrint(WL_VERBOSE, "%d Script %s executed by %s %s\n", svs.time, (char *)name, ent->classname, ent->targetname); } return true; @@ -158,17 +145,15 @@ Allocates a new ICARUS instance ================= */ -void ICARUS_Init( void ) -{ - //Link all interface functions - Interface_Init( &interface_export ); +void ICARUS_Init(void) { + // Link all interface functions + Interface_Init(&interface_export); - //Create the ICARUS instance for this session - iICARUS = ICARUS_Instance::Create( &interface_export ); + // Create the ICARUS instance for this session + iICARUS = ICARUS_Instance::Create(&interface_export); - if ( iICARUS == NULL ) - { - Com_Error( ERR_DROP, "Unable to initialize ICARUS instance\n" ); + if (iICARUS == NULL) { + Com_Error(ERR_DROP, "Unable to initialize ICARUS instance\n"); return; } } @@ -181,44 +166,37 @@ Frees up ICARUS resources from all entities ================= */ -void ICARUS_Shutdown( void ) -{ - bufferlist_t::iterator ei; - sharedEntity_t *ent = SV_GentityNum(0); +void ICARUS_Shutdown(void) { + bufferlist_t::iterator ei; + sharedEntity_t *ent = SV_GentityNum(0); - //Release all ICARUS resources from the entities - for ( int i = 0; i < /*globals.num_entities*/MAX_GENTITIES; i++ ) - { + // Release all ICARUS resources from the entities + for (int i = 0; i < /*globals.num_entities*/ MAX_GENTITIES; i++) { ent = SV_GentityNum(i); - if (gSequencers[i]) - { - if (ent->s.number >= MAX_GENTITIES || - ent->s.number < 0) - { + if (gSequencers[i]) { + if (ent->s.number >= MAX_GENTITIES || ent->s.number < 0) { ent->s.number = i; assert(0); } - ICARUS_FreeEnt( ent ); + ICARUS_FreeEnt(ent); } } - //Clear out all precached scripts - for ( ei = ICARUS_BufferList.begin(); ei != ICARUS_BufferList.end(); ++ei ) - { - //gi.Free( (*ei).second->buffer ); + // Clear out all precached scripts + for (ei = ICARUS_BufferList.begin(); ei != ICARUS_BufferList.end(); ++ei) { + // gi.Free( (*ei).second->buffer ); ICARUS_Free((*ei).second->buffer); delete (*ei).second; } ICARUS_BufferList.clear(); - //Clear the name map + // Clear the name map ICARUS_EntList.clear(); - //Free this instance - if ( iICARUS ) - { + // Free this instance + if (iICARUS) { iICARUS->Delete(); iICARUS = NULL; } @@ -235,46 +213,40 @@ FIXME: shouldn't ICARUS handle this internally? ============== */ -void ICARUS_FreeEnt( sharedEntity_t *ent ) -{ - assert( iICARUS ); +void ICARUS_FreeEnt(sharedEntity_t *ent) { + assert(iICARUS); - if (ent->s.number >= MAX_GENTITIES || - ent->s.number < 0) - { + if (ent->s.number >= MAX_GENTITIES || ent->s.number < 0) { assert(0); return; } - //Make sure the ent is valid - if ( gSequencers[ent->s.number] == NULL ) + // Make sure the ent is valid + if (gSequencers[ent->s.number] == NULL) return; - //Remove them from the ICARUSE_EntList list so that when their g_entity index is reused, ICARUS doesn't try to affect the new (incorrect) ent. - if VALIDSTRING( ent->script_targetname ) - { - char temp[1024]; + // Remove them from the ICARUSE_EntList list so that when their g_entity index is reused, ICARUS doesn't try to affect the new (incorrect) ent. + if VALIDSTRING (ent->script_targetname) { + char temp[1024]; - strncpy( (char *) temp, ent->script_targetname, 1023 ); - temp[ 1023 ] = 0; + strncpy((char *)temp, ent->script_targetname, 1023); + temp[1023] = 0; - entlist_t::iterator it = ICARUS_EntList.find( Q_strupr(temp) ); + entlist_t::iterator it = ICARUS_EntList.find(Q_strupr(temp)); - if (it != ICARUS_EntList.end()) - { + if (it != ICARUS_EntList.end()) { ICARUS_EntList.erase(it); } } - //Delete the sequencer and the task manager - iICARUS->DeleteSequencer( gSequencers[ent->s.number] ); + // Delete the sequencer and the task manager + iICARUS->DeleteSequencer(gSequencers[ent->s.number]); - //Clean up the pointers - gSequencers[ent->s.number] = NULL; - gTaskManagers[ent->s.number] = NULL; + // Clean up the pointers + gSequencers[ent->s.number] = NULL; + gTaskManagers[ent->s.number] = NULL; } - /* ============== ICARUS_ValidEnt @@ -283,29 +255,26 @@ Determines whether or not an entity needs ICARUS information ============== */ -bool ICARUS_ValidEnt( sharedEntity_t *ent ) -{ +bool ICARUS_ValidEnt(sharedEntity_t *ent) { int i; - //Targeted by a script - if VALIDSTRING( ent->script_targetname ) + // Targeted by a script + if VALIDSTRING (ent->script_targetname) return true; - //Potentially able to call a script - for ( i = 0; i < NUM_BSETS; i++ ) - { - if VALIDSTRING( ent->behaviorSet[i] ) - { - //Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", ent->s.number, ent->targetname ); + // Potentially able to call a script + for (i = 0; i < NUM_BSETS; i++) { + if VALIDSTRING (ent->behaviorSet[i]) { + // Com_Printf( "WARNING: Entity %d (%s) has behaviorSet but no script_targetname -- using targetname\n", ent->s.number, ent->targetname ); - //ent->script_targetname = ent->targetname; - //rww - You CANNOT do things like this now. We're switching memory around to be able to read this memory from vm land, - //and while this allows us to read it on our "fake" entity here, we can't modify pointers like this. We can however do - //something completely hackish such as the following. + // ent->script_targetname = ent->targetname; + // rww - You CANNOT do things like this now. We're switching memory around to be able to read this memory from vm land, + // and while this allows us to read it on our "fake" entity here, we can't modify pointers like this. We can however do + // something completely hackish such as the following. assert(ent->s.number >= 0 && ent->s.number < MAX_GENTITIES); sharedEntity_t *trueEntity = SV_GentityNum(ent->s.number); - //This works because we're modifying the actual shared game vm data and turning one pointer into another. - //While these pointers both look like garbage to us in here, they are not. + // This works because we're modifying the actual shared game vm data and turning one pointer into another. + // While these pointers both look like garbage to us in here, they are not. trueEntity->script_targetname = trueEntity->targetname; return true; } @@ -322,17 +291,16 @@ Associate the entity's id and name so that it can be referenced later ============== */ -void ICARUS_AssociateEnt( sharedEntity_t *ent ) -{ - char temp[1024]; +void ICARUS_AssociateEnt(sharedEntity_t *ent) { + char temp[1024]; - if ( VALIDSTRING( ent->script_targetname ) == false ) + if (VALIDSTRING(ent->script_targetname) == false) return; - strncpy( (char *) temp, ent->script_targetname, 1023 ); - temp[ 1023 ] = 0; + strncpy((char *)temp, ent->script_targetname, 1023); + temp[1023] = 0; - ICARUS_EntList[ Q_strupr( (char *) temp ) ] = ent->s.number; + ICARUS_EntList[Q_strupr((char *)temp)] = ent->s.number; } /* @@ -343,26 +311,24 @@ Loads and caches a script ============== */ -bool ICARUS_RegisterScript( const char *name, qboolean bCalledDuringInterrogate /* = false */ ) -{ - bufferlist_t::iterator ei; - pscript_t *pscript; - char newname[MAX_FILENAME_LENGTH]; - char *buffer = NULL; // lose compiler warning about uninitialised vars - long length; +bool ICARUS_RegisterScript(const char *name, qboolean bCalledDuringInterrogate /* = false */) { + bufferlist_t::iterator ei; + pscript_t *pscript; + char newname[MAX_FILENAME_LENGTH]; + char *buffer = NULL; // lose compiler warning about uninitialised vars + long length; - //Make sure this isn't already cached - ei = ICARUS_BufferList.find( (char *) name ); + // Make sure this isn't already cached + ei = ICARUS_BufferList.find((char *)name); // note special return condition here, if doing interrogate and we already have this file then we MUST return // false (which stops the interrogator proceeding), this not only saves some time, but stops a potential // script recursion bug which could lock the program in an infinite loop... Return TRUE for normal though! // - if ( ei != ICARUS_BufferList.end() ) - return (bCalledDuringInterrogate)?false:true; - - Com_sprintf( newname, sizeof(newname), "%s%s", name, IBI_EXT ); + if (ei != ICARUS_BufferList.end()) + return (bCalledDuringInterrogate) ? false : true; + Com_sprintf(newname, sizeof(newname), "%s%s", name, IBI_EXT); // small update here, if called during interrogate, don't let gi.FS_ReadFile() complain because it can't // find stuff like BS_RUN_AND_SHOOT as scriptname... During FINALBUILD the message won't appear anyway, hence @@ -371,7 +337,7 @@ bool ICARUS_RegisterScript( const char *name, qboolean bCalledDuringInterrogate qboolean qbIgnoreFileRead = qfalse; // // NOTENOTE: For the moment I've taken this back out, to avoid doubling the number of fopen()'s per file. -#if 0//#ifndef FINAL_BUILD +#if 0 //#ifndef FINAL_BUILD if (bCalledDuringInterrogate) { fileHandle_t file; @@ -389,43 +355,39 @@ bool ICARUS_RegisterScript( const char *name, qboolean bCalledDuringInterrogate } #endif - length = qbIgnoreFileRead ? -1 : FS_ReadFile( newname, (void **) &buffer ); + length = qbIgnoreFileRead ? -1 : FS_ReadFile(newname, (void **)&buffer); - if ( length <= 0 ) - { + if (length <= 0) { // File not found, but keep quiet during interrogate stage, because of stuff like BS_RUN_AND_SHOOT as scriptname // - if (!bCalledDuringInterrogate) - { - Com_Printf(S_COLOR_RED"Could not open file '%s'\n", newname ); + if (!bCalledDuringInterrogate) { + Com_Printf(S_COLOR_RED "Could not open file '%s'\n", newname); } return false; } pscript = new pscript_t; - pscript->buffer = (char *) ICARUS_Malloc(length);//gi.Malloc(length, TAG_ICARUS, qfalse); - memcpy (pscript->buffer, buffer, length); + pscript->buffer = (char *)ICARUS_Malloc(length); // gi.Malloc(length, TAG_ICARUS, qfalse); + memcpy(pscript->buffer, buffer, length); pscript->length = length; - FS_FreeFile( buffer ); + FS_FreeFile(buffer); - ICARUS_BufferList[ name ] = pscript; + ICARUS_BufferList[name] = pscript; return true; } -void ICARUS_SoundPrecache(const char *filename) -{ +void ICARUS_SoundPrecache(const char *filename) { T_G_ICARUS_SOUNDINDEX *sharedMem = (T_G_ICARUS_SOUNDINDEX *)sv.mSharedMemory; - strcpy( sharedMem->filename, filename ); + strcpy(sharedMem->filename, filename); GVM_ICARUS_SoundIndex(); } -int ICARUS_GetIDForString( const char *string ) -{ +int ICARUS_GetIDForString(const char *string) { T_G_ICARUS_GETSETIDFORSTRING *sharedMem = (T_G_ICARUS_GETSETIDFORSTRING *)sv.mSharedMemory; strcpy(sharedMem->string, string); @@ -441,122 +403,110 @@ ICARUS_InterrogateScript // at this point the filename should have had the "scripts" (Q3_SCRIPT_DIR) added to it (but not the IBI extension) // -void ICARUS_InterrogateScript( const char *filename ) -{ - CBlockStream stream; - CBlockMember *blockMember; - CBlock block; +void ICARUS_InterrogateScript(const char *filename) { + CBlockStream stream; + CBlockMember *blockMember; + CBlock block; - if (!Q_stricmp(filename,"NULL") || !Q_stricmp(filename,"default")) + if (!Q_stricmp(filename, "NULL") || !Q_stricmp(filename, "default")) return; ////////////////////////////////// // // ensure "scripts" (Q3_SCRIPT_DIR), which will be missing if this was called recursively... // - char sFilename[MAX_FILENAME_LENGTH]; // should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code + char sFilename[MAX_FILENAME_LENGTH]; // should really be MAX_QPATH (and 64 bytes instead of 1024), but this fits the rest of the code - if (!Q_stricmpn(filename,Q3_SCRIPT_DIR,strlen(Q3_SCRIPT_DIR))) - { - Q_strncpyz(sFilename,filename,sizeof(sFilename)); - } - else - { - Q_strncpyz(sFilename,va("%s/%s",Q3_SCRIPT_DIR,filename),sizeof(sFilename)); + if (!Q_stricmpn(filename, Q3_SCRIPT_DIR, strlen(Q3_SCRIPT_DIR))) { + Q_strncpyz(sFilename, filename, sizeof(sFilename)); + } else { + Q_strncpyz(sFilename, va("%s/%s", Q3_SCRIPT_DIR, filename), sizeof(sFilename)); } // ////////////////////////////////// - - //Attempt to register this script - if ( ICARUS_RegisterScript( sFilename, qtrue ) == false ) // true = bCalledDuringInterrogate + // Attempt to register this script + if (ICARUS_RegisterScript(sFilename, qtrue) == false) // true = bCalledDuringInterrogate return; - char *buf; - long len; + char *buf; + long len; - //Attempt to retrieve the new script data - if ( ( len = ICARUS_GetScript ( sFilename, &buf ) ) == 0 ) + // Attempt to retrieve the new script data + if ((len = ICARUS_GetScript(sFilename, &buf)) == 0) return; - //Open the stream - if ( stream.Open( buf, len ) == qfalse ) + // Open the stream + if (stream.Open(buf, len) == qfalse) return; - const char *sVal1, *sVal2; - char temp[1024]; - int setID; + const char *sVal1, *sVal2; + char temp[1024]; + int setID; - //Now iterate through all blocks of the script, searching for keywords - while ( stream.BlockAvailable() ) - { - //Get a block - if ( stream.ReadBlock( &block ) == qfalse ) + // Now iterate through all blocks of the script, searching for keywords + while (stream.BlockAvailable()) { + // Get a block + if (stream.ReadBlock(&block) == qfalse) return; - //Determine what type of block this is - switch( block.GetBlockID() ) + // Determine what type of block this is + switch (block.GetBlockID()) { + case ID_CAMERA: // to cache ROFF files { - case ID_CAMERA: // to cache ROFF files - { - float f = *(float *) block.GetMemberData( 0 ); + float f = *(float *)block.GetMemberData(0); - if (f == TYPE_PATH) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (f == TYPE_PATH) { + sVal1 = (const char *)block.GetMemberData(1); - //we can do this I guess since the roff is loaded on the server. - theROFFSystem.Cache((char *)sVal1, qfalse); - } + // we can do this I guess since the roff is loaded on the server. + theROFFSystem.Cache((char *)sVal1, qfalse); } - break; + } break; - case ID_PLAY: // to cache ROFF files + case ID_PLAY: // to cache ROFF files - sVal1 = (const char *) block.GetMemberData( 0 ); + sVal1 = (const char *)block.GetMemberData(0); - if (!Q_stricmp(sVal1,"PLAY_ROFF")) - { - sVal1 = (const char *) block.GetMemberData( 1 ); + if (!Q_stricmp(sVal1, "PLAY_ROFF")) { + sVal1 = (const char *)block.GetMemberData(1); - //we can do this I guess since the roff is loaded on the server. + // we can do this I guess since the roff is loaded on the server. theROFFSystem.Cache((char *)sVal1, qfalse); } break; - //Run commands + // Run commands case ID_RUN: - sVal1 = (const char *) block.GetMemberData( 0 ); + sVal1 = (const char *)block.GetMemberData(0); - COM_StripExtension( sVal1, (char *) temp, sizeof( temp ) ); - ICARUS_InterrogateScript( (const char *) &temp ); + COM_StripExtension(sVal1, (char *)temp, sizeof(temp)); + ICARUS_InterrogateScript((const char *)&temp); break; case ID_SOUND: - //We can't just call over to S_RegisterSound or whatever because this is on the server. - sVal1 = (const char *) block.GetMemberData( 1 ); //0 is channel, 1 is filename + // We can't just call over to S_RegisterSound or whatever because this is on the server. + sVal1 = (const char *)block.GetMemberData(1); // 0 is channel, 1 is filename ICARUS_SoundPrecache(sVal1); break; case ID_SET: - blockMember = block.GetMember( 0 ); + blockMember = block.GetMember(0); - //NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) + // NOTENOTE: This will not catch special case get() inlines! (There's not really a good way to do that) - //Make sure we're testing against strings - if ( blockMember->GetID() == TK_STRING ) - { - sVal1 = (const char *) block.GetMemberData( 0 ); - sVal2 = (const char *) block.GetMemberData( 1 ); + // Make sure we're testing against strings + if (blockMember->GetID() == TK_STRING) { + sVal1 = (const char *)block.GetMemberData(0); + sVal2 = (const char *)block.GetMemberData(1); - //Get the id for this set identifier - setID = ICARUS_GetIDForString( sVal1 ); + // Get the id for this set identifier + setID = ICARUS_GetIDForString(sVal1); - //Check against valid types - switch ( setID ) - { + // Check against valid types + switch (setID) { case SET_SPAWNSCRIPT: case SET_USESCRIPT: case SET_AWAKESCRIPT: @@ -573,18 +523,18 @@ void ICARUS_InterrogateScript( const char *filename ) case SET_FFDEATHSCRIPT: case SET_MINDTRICKSCRIPT: case SET_CINEMATIC_SKIPSCRIPT: - //Recursively obtain all embedded scripts - ICARUS_InterrogateScript( sVal2 ); + // Recursively obtain all embedded scripts + ICARUS_InterrogateScript(sVal2); break; - case SET_LOOPSOUND: //like ID_SOUND, but set's looping + case SET_LOOPSOUND: // like ID_SOUND, but set's looping ICARUS_SoundPrecache(sVal2); break; - case SET_VIDEO_PLAY: //in game cinematic - //do nothing for MP. + case SET_VIDEO_PLAY: // in game cinematic + // do nothing for MP. break; case SET_ADDRHANDBOLT_MODEL: case SET_ADDLHANDBOLT_MODEL: - //do nothing for MP + // do nothing for MP break; default: break; @@ -596,29 +546,26 @@ void ICARUS_InterrogateScript( const char *filename ) break; } - //Clean out the block for the next pass + // Clean out the block for the next pass block.Free(); } - //All done + // All done stream.Free(); } -stringID_table_t BSTable[] = -{ - ENUM2STRING(BS_DEFAULT),//# default behavior for that NPC - ENUM2STRING(BS_ADVANCE_FIGHT),//# Advance to captureGoal and shoot enemies if you can - ENUM2STRING(BS_SLEEP),//# Play awake script when startled by sound - ENUM2STRING(BS_FOLLOW_LEADER),//# Follow your leader and shoot any enemies you come across - ENUM2STRING(BS_JUMP),//# Face navgoal and jump to it. - ENUM2STRING(BS_SEARCH),//# Using current waypoint as a base), search the immediate branches of waypoints for enemies - ENUM2STRING(BS_WANDER),//# Wander down random waypoint paths - ENUM2STRING(BS_NOCLIP),//# Moves through walls), etc. - ENUM2STRING(BS_REMOVE),//# Waits for player to leave PVS then removes itself - ENUM2STRING(BS_CINEMATIC),//# Does nothing but face it's angles and move to a goal if it has one - //the rest are internal only - { "", -1 } -}; +stringID_table_t BSTable[] = {ENUM2STRING(BS_DEFAULT), //# default behavior for that NPC + ENUM2STRING(BS_ADVANCE_FIGHT), //# Advance to captureGoal and shoot enemies if you can + ENUM2STRING(BS_SLEEP), //# Play awake script when startled by sound + ENUM2STRING(BS_FOLLOW_LEADER), //# Follow your leader and shoot any enemies you come across + ENUM2STRING(BS_JUMP), //# Face navgoal and jump to it. + ENUM2STRING(BS_SEARCH), //# Using current waypoint as a base), search the immediate branches of waypoints for enemies + ENUM2STRING(BS_WANDER), //# Wander down random waypoint paths + ENUM2STRING(BS_NOCLIP), //# Moves through walls), etc. + ENUM2STRING(BS_REMOVE), //# Waits for player to leave PVS then removes itself + ENUM2STRING(BS_CINEMATIC), //# Does nothing but face it's angles and move to a goal if it has one + // the rest are internal only + {"", -1}}; /* ============== @@ -628,22 +575,19 @@ Precache all scripts being used by the entity ============== */ -void ICARUS_PrecacheEnt( sharedEntity_t *ent ) -{ - char newname[MAX_FILENAME_LENGTH]; - int i; +void ICARUS_PrecacheEnt(sharedEntity_t *ent) { + char newname[MAX_FILENAME_LENGTH]; + int i; - for ( i = 0; i < NUM_BSETS; i++ ) - { - if ( ent->behaviorSet[i] == NULL ) + for (i = 0; i < NUM_BSETS; i++) { + if (ent->behaviorSet[i] == NULL) continue; - if ( GetIDForString( BSTable, ent->behaviorSet[i] ) == -1 ) - {//not a behavior set - Com_sprintf( newname, sizeof(newname), "%s/%s", Q3_SCRIPT_DIR, ent->behaviorSet[i] ); + if (GetIDForString(BSTable, ent->behaviorSet[i]) == -1) { // not a behavior set + Com_sprintf(newname, sizeof(newname), "%s/%s", Q3_SCRIPT_DIR, ent->behaviorSet[i]); - //Precache this, and all internally referenced scripts - ICARUS_InterrogateScript( newname ); + // Precache this, and all internally referenced scripts + ICARUS_InterrogateScript(newname); } } } @@ -656,32 +600,31 @@ Allocates a sequencer and task manager only if an entity is a potential script u ============== */ -void Q3_TaskIDClear( int *taskID ); -void ICARUS_InitEnt( sharedEntity_t *ent ) -{ - //Make sure this is a fresh ent - assert( iICARUS ); - assert( gTaskManagers[ent->s.number] == NULL ); - assert( gSequencers[ent->s.number] == NULL ); +void Q3_TaskIDClear(int *taskID); +void ICARUS_InitEnt(sharedEntity_t *ent) { + // Make sure this is a fresh ent + assert(iICARUS); + assert(gTaskManagers[ent->s.number] == NULL); + assert(gSequencers[ent->s.number] == NULL); - if ( gSequencers[ent->s.number] != NULL ) + if (gSequencers[ent->s.number] != NULL) return; - if ( gTaskManagers[ent->s.number] != NULL ) + if (gTaskManagers[ent->s.number] != NULL) return; - //Create the sequencer and setup the task manager - gSequencers[ent->s.number] = iICARUS->GetSequencer( ent->s.number ); - gTaskManagers[ent->s.number] = gSequencers[ent->s.number]->GetTaskManager(); + // Create the sequencer and setup the task manager + gSequencers[ent->s.number] = iICARUS->GetSequencer(ent->s.number); + gTaskManagers[ent->s.number] = gSequencers[ent->s.number]->GetTaskManager(); - //Initialize all taskIDs to -1 - memset( &ent->taskID, -1, sizeof( ent->taskID ) ); + // Initialize all taskIDs to -1 + memset(&ent->taskID, -1, sizeof(ent->taskID)); - //Add this entity to a map of valid associated ents for quick retrieval later - ICARUS_AssociateEnt( ent ); + // Add this entity to a map of valid associated ents for quick retrieval later + ICARUS_AssociateEnt(ent); - //Precache all the entity's scripts - ICARUS_PrecacheEnt( ent ); + // Precache all the entity's scripts + ICARUS_PrecacheEnt(ent); } /* @@ -690,17 +633,16 @@ ICARUS_LinkEntity ------------------------- */ -int ICARUS_LinkEntity( int entID, CSequencer *sequencer, CTaskManager *taskManager ) -{ - sharedEntity_t *ent = SV_GentityNum(entID); +int ICARUS_LinkEntity(int entID, CSequencer *sequencer, CTaskManager *taskManager) { + sharedEntity_t *ent = SV_GentityNum(entID); - if ( ent == NULL ) + if (ent == NULL) return false; gSequencers[ent->s.number] = sequencer; gTaskManagers[ent->s.number] = taskManager; - ICARUS_AssociateEnt( ent ); + ICARUS_AssociateEnt(ent); return true; } @@ -711,9 +653,8 @@ Svcmd_ICARUS_f ------------------------- */ -void Svcmd_ICARUS_f( void ) -{ - //rwwFIXMEFIXME: Do something with this for debugging purposes at some point. +void Svcmd_ICARUS_f(void) { + // rwwFIXMEFIXME: Do something with this for debugging purposes at some point. /* char *cmd = Cmd_Argv( 1 ); diff --git a/codemp/icarus/Instance.cpp b/codemp/icarus/Instance.cpp index 58b32617f3..454c12c279 100644 --- a/codemp/icarus/Instance.cpp +++ b/codemp/icarus/Instance.cpp @@ -32,39 +32,35 @@ along with this program; if not, see . class CSequencer; class CTaskManager; -//We can't put these on entity fields since all that stuff is in C -//which can't be changed due to VMs. So we'll use a global array -//and access by the entity index given. -CSequencer *gSequencers[MAX_GENTITIES]; -CTaskManager *gTaskManagers[MAX_GENTITIES]; +// We can't put these on entity fields since all that stuff is in C +// which can't be changed due to VMs. So we'll use a global array +// and access by the entity index given. +CSequencer *gSequencers[MAX_GENTITIES]; +CTaskManager *gTaskManagers[MAX_GENTITIES]; // Instance -ICARUS_Instance::ICARUS_Instance( void ) -{ +ICARUS_Instance::ICARUS_Instance(void) { m_GUID = 0; - //to be safe - memset(gSequencers,0, sizeof(gSequencers)); - memset(gTaskManagers,0, sizeof(gTaskManagers)); + // to be safe + memset(gSequencers, 0, sizeof(gSequencers)); + memset(gTaskManagers, 0, sizeof(gTaskManagers)); #ifdef _DEBUG - m_DEBUG_NumSequencerAlloc = 0; - m_DEBUG_NumSequencerFreed = 0; - m_DEBUG_NumSequencerResidual = 0; + m_DEBUG_NumSequencerAlloc = 0; + m_DEBUG_NumSequencerFreed = 0; + m_DEBUG_NumSequencerResidual = 0; - m_DEBUG_NumSequenceAlloc = 0; - m_DEBUG_NumSequenceFreed = 0; - m_DEBUG_NumSequenceResidual = 0; + m_DEBUG_NumSequenceAlloc = 0; + m_DEBUG_NumSequenceFreed = 0; + m_DEBUG_NumSequenceResidual = 0; #endif - } -ICARUS_Instance::~ICARUS_Instance( void ) -{ -} +ICARUS_Instance::~ICARUS_Instance(void) {} /* ------------------------- @@ -72,11 +68,10 @@ Create ------------------------- */ -ICARUS_Instance *ICARUS_Instance::Create( interface_export_t *ie ) -{ +ICARUS_Instance *ICARUS_Instance::Create(interface_export_t *ie) { ICARUS_Instance *instance = new ICARUS_Instance; instance->m_interface = ie; - Com_OPrintf( "ICARUS Instance successfully created\n" ); + Com_OPrintf("ICARUS Instance successfully created\n"); return instance; } @@ -86,13 +81,11 @@ Free ------------------------- */ -int ICARUS_Instance::Free( void ) -{ - sequencer_l::iterator sri; +int ICARUS_Instance::Free(void) { + sequencer_l::iterator sri; - //Delete any residual sequencers - STL_ITERATE( sri, m_sequencers ) - { + // Delete any residual sequencers + STL_ITERATE(sri, m_sequencers) { delete (*sri); #ifdef _DEBUG @@ -100,20 +93,18 @@ int ICARUS_Instance::Free( void ) m_DEBUG_NumSequencerResidual++; #endif - } m_sequencers.clear(); - //all these are deleted now so clear the global map. - memset(gSequencers,0, sizeof(gSequencers)); - memset(gTaskManagers,0, sizeof(gTaskManagers)); + // all these are deleted now so clear the global map. + memset(gSequencers, 0, sizeof(gSequencers)); + memset(gTaskManagers, 0, sizeof(gTaskManagers)); m_signals.clear(); - sequence_l::iterator si; + sequence_l::iterator si; - //Delete any residual sequences - STL_ITERATE( si, m_sequences ) - { + // Delete any residual sequences + STL_ITERATE(si, m_sequences) { delete (*si); #ifdef _DEBUG @@ -121,7 +112,6 @@ int ICARUS_Instance::Free( void ) m_DEBUG_NumSequenceResidual++; #endif - } m_sequences.clear(); @@ -135,28 +125,27 @@ Delete ------------------------- */ -int ICARUS_Instance::Delete( void ) -{ +int ICARUS_Instance::Delete(void) { Free(); #ifdef _DEBUG - Com_OPrintf( "\nICARUS Instance Debug Info:\n---------------------------\n" ); + Com_OPrintf("\nICARUS Instance Debug Info:\n---------------------------\n"); - Com_OPrintf( "Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc ); + Com_OPrintf("Sequencers Allocated:\t%d\n", m_DEBUG_NumSequencerAlloc); - Com_OPrintf( "Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed ); + Com_OPrintf("Sequencers Freed:\t\t%d\n", m_DEBUG_NumSequencerFreed); - Com_OPrintf( "Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual ); + Com_OPrintf("Sequencers Residual:\t%d\n\n", m_DEBUG_NumSequencerResidual); - Com_OPrintf( "Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc ); + Com_OPrintf("Sequences Allocated:\t%d\n", m_DEBUG_NumSequenceAlloc); - Com_OPrintf( "Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed ); + Com_OPrintf("Sequences Freed:\t\t%d\n", m_DEBUG_NumSequenceFreed); - Com_OPrintf( "Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual ); + Com_OPrintf("Sequences Residual:\t\t%d\n\n", m_DEBUG_NumSequenceResidual); - Com_OPrintf( "\n" ); + Com_OPrintf("\n"); #endif @@ -171,16 +160,15 @@ GetSequencer ------------------------- */ -CSequencer *ICARUS_Instance::GetSequencer( int ownerID ) -{ - CSequencer *sequencer = CSequencer::Create(); - CTaskManager *taskManager = CTaskManager::Create(); +CSequencer *ICARUS_Instance::GetSequencer(int ownerID) { + CSequencer *sequencer = CSequencer::Create(); + CTaskManager *taskManager = CTaskManager::Create(); - sequencer->Init( ownerID, m_interface, taskManager, this ); + sequencer->Init(ownerID, m_interface, taskManager, this); - taskManager->Init( sequencer ); + taskManager->Init(sequencer); - STL_INSERT( m_sequencers, sequencer ); + STL_INSERT(m_sequencers, sequencer); #ifdef _DEBUG @@ -197,20 +185,18 @@ DeleteSequencer ------------------------- */ -void ICARUS_Instance::DeleteSequencer( CSequencer *sequencer ) -{ +void ICARUS_Instance::DeleteSequencer(CSequencer *sequencer) { // added 2/12/2 to properly delete blocks that were passed to the task manager sequencer->Recall(); - CTaskManager *taskManager = sequencer->GetTaskManager(); + CTaskManager *taskManager = sequencer->GetTaskManager(); - if ( taskManager ) - { + if (taskManager) { taskManager->Free(); delete taskManager; } - m_sequencers.remove( sequencer ); + m_sequencers.remove(sequencer); sequencer->Free(); delete sequencer; @@ -220,7 +206,6 @@ void ICARUS_Instance::DeleteSequencer( CSequencer *sequencer ) m_DEBUG_NumSequencerFreed++; #endif - } /* @@ -229,15 +214,14 @@ GetSequence ------------------------- */ -CSequence *ICARUS_Instance::GetSequence( void ) -{ - CSequence *sequence = CSequence::Create(); +CSequence *ICARUS_Instance::GetSequence(void) { + CSequence *sequence = CSequence::Create(); - //Assign the GUID - sequence->SetID( m_GUID++ ); - sequence->SetOwner( this ); + // Assign the GUID + sequence->SetID(m_GUID++); + sequence->SetOwner(this); - STL_INSERT( m_sequences, sequence ); + STL_INSERT(m_sequences, sequence); #ifdef _DEBUG @@ -254,12 +238,10 @@ GetSequence ------------------------- */ -CSequence *ICARUS_Instance::GetSequence( int id ) -{ - sequence_l::iterator si; - STL_ITERATE( si, m_sequences ) - { - if ( (*si)->GetID() == id ) +CSequence *ICARUS_Instance::GetSequence(int id) { + sequence_l::iterator si; + STL_ITERATE(si, m_sequences) { + if ((*si)->GetID() == id) return (*si); } @@ -272,9 +254,8 @@ DeleteSequence ------------------------- */ -void ICARUS_Instance::DeleteSequence( CSequence *sequence ) -{ - m_sequences.remove( sequence ); +void ICARUS_Instance::DeleteSequence(CSequence *sequence) { + m_sequences.remove(sequence); delete sequence; @@ -291,22 +272,20 @@ AllocateSequences ------------------------- */ -int ICARUS_Instance::AllocateSequences( int numSequences, int *idTable ) -{ - CSequence *sequence; +int ICARUS_Instance::AllocateSequences(int numSequences, int *idTable) { + CSequence *sequence; - for ( int i = 0; i < numSequences; i++ ) - { - //If the GUID of this sequence is higher than the current, take this a the "current" GUID - if ( idTable[i] > m_GUID ) + for (int i = 0; i < numSequences; i++) { + // If the GUID of this sequence is higher than the current, take this a the "current" GUID + if (idTable[i] > m_GUID) m_GUID = idTable[i]; - //Allocate the container sequence - if ( ( sequence = GetSequence() ) == NULL ) + // Allocate the container sequence + if ((sequence = GetSequence()) == NULL) return false; - //Override the given GUID with the real one - sequence->SetID( idTable[i] ); + // Override the given GUID with the real one + sequence->SetID(idTable[i]); } return true; @@ -318,28 +297,24 @@ SaveSequenceIDTable ------------------------- */ -int ICARUS_Instance::SaveSequenceIDTable( void ) -{ - //Save out the number of sequences to follow - int numSequences = m_sequences.size(); - m_interface->I_WriteSaveData( INT_ID('#','S','E','Q'), &numSequences, sizeof( numSequences ) ); +int ICARUS_Instance::SaveSequenceIDTable(void) { + // Save out the number of sequences to follow + int numSequences = m_sequences.size(); + m_interface->I_WriteSaveData(INT_ID('#', 'S', 'E', 'Q'), &numSequences, sizeof(numSequences)); - //Sequences are saved first, by ID and information - sequence_l::iterator sqi; + // Sequences are saved first, by ID and information + sequence_l::iterator sqi; - //First pass, save all sequences ID for reconstruction - int *idTable = new int[ numSequences ]; - int itr = 0; + // First pass, save all sequences ID for reconstruction + int *idTable = new int[numSequences]; + int itr = 0; - if ( idTable == NULL ) + if (idTable == NULL) return false; - STL_ITERATE( sqi, m_sequences ) - { - idTable[itr++] = (*sqi)->GetID(); - } + STL_ITERATE(sqi, m_sequences) { idTable[itr++] = (*sqi)->GetID(); } - m_interface->I_WriteSaveData( INT_ID('S','Q','T','B'), idTable, sizeof( int ) * numSequences ); + m_interface->I_WriteSaveData(INT_ID('S', 'Q', 'T', 'B'), idTable, sizeof(int) * numSequences); delete[] idTable; @@ -352,17 +327,13 @@ SaveSequences ------------------------- */ -int ICARUS_Instance::SaveSequences( void ) -{ - //Save out a listing of all the used sequences by ID +int ICARUS_Instance::SaveSequences(void) { + // Save out a listing of all the used sequences by ID SaveSequenceIDTable(); - //Save all the information in order - sequence_l::iterator sqi; - STL_ITERATE( sqi, m_sequences ) - { - (*sqi)->Save(); - } + // Save all the information in order + sequence_l::iterator sqi; + STL_ITERATE(sqi, m_sequences) { (*sqi)->Save(); } return true; } @@ -373,18 +344,14 @@ SaveSequencers ------------------------- */ -int ICARUS_Instance::SaveSequencers( void ) -{ - //Save out the number of sequences to follow - int numSequencers = m_sequencers.size(); - m_interface->I_WriteSaveData( INT_ID('#','S','Q','R'), &numSequencers, sizeof( numSequencers ) ); - - //The sequencers are then saved - sequencer_l::iterator si; - STL_ITERATE( si, m_sequencers ) - { - (*si)->Save(); - } +int ICARUS_Instance::SaveSequencers(void) { + // Save out the number of sequences to follow + int numSequencers = m_sequencers.size(); + m_interface->I_WriteSaveData(INT_ID('#', 'S', 'Q', 'R'), &numSequencers, sizeof(numSequencers)); + + // The sequencers are then saved + sequencer_l::iterator si; + STL_ITERATE(si, m_sequencers) { (*si)->Save(); } return true; } @@ -395,28 +362,26 @@ SaveSignals ------------------------- */ -int ICARUS_Instance::SaveSignals( void ) -{ - int numSignals = m_signals.size(); +int ICARUS_Instance::SaveSignals(void) { + int numSignals = m_signals.size(); - m_interface->I_WriteSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); + m_interface->I_WriteSaveData(INT_ID('I', 'S', 'I', 'G'), &numSignals, sizeof(numSignals)); - signal_m::iterator si; - STL_ITERATE( si, m_signals ) - { - //m_interface->I_WriteSaveData( 'ISIG', &numSignals, sizeof( numSignals ) ); + signal_m::iterator si; + STL_ITERATE(si, m_signals) { + // m_interface->I_WriteSaveData( 'ISIG', &numSignals, sizeof( numSignals ) ); const char *name = ((*si).first).c_str(); - //Make sure this is a valid string - assert( ( name != NULL ) && ( name[0] != '\0' ) ); + // Make sure this is a valid string + assert((name != NULL) && (name[0] != '\0')); - int length = strlen( name ) + 1; + int length = strlen(name) + 1; - //Save out the string size - m_interface->I_WriteSaveData( INT_ID('S','I','G','#'), &length, sizeof ( length ) ); + // Save out the string size + m_interface->I_WriteSaveData(INT_ID('S', 'I', 'G', '#'), &length, sizeof(length)); - //Write out the string - m_interface->I_WriteSaveData( INT_ID('S','I','G','N'), (void *) name, length ); + // Write out the string + m_interface->I_WriteSaveData(INT_ID('S', 'I', 'G', 'N'), (void *)name, length); } return true; @@ -428,25 +393,24 @@ Save ------------------------- */ -int ICARUS_Instance::Save( void ) -{ - //Save out a ICARUS save block header with the ICARUS version - double version = ICARUS_VERSION; - m_interface->I_WriteSaveData( INT_ID('I','C','A','R'), &version, sizeof( version ) ); +int ICARUS_Instance::Save(void) { + // Save out a ICARUS save block header with the ICARUS version + double version = ICARUS_VERSION; + m_interface->I_WriteSaveData(INT_ID('I', 'C', 'A', 'R'), &version, sizeof(version)); - //Save out the signals - if ( SaveSignals() == false ) + // Save out the signals + if (SaveSignals() == false) return false; - //Save out the sequences - if ( SaveSequences() == false ) + // Save out the sequences + if (SaveSequences() == false) return false; - //Save out the sequencers - if ( SaveSequencers() == false ) + // Save out the sequencers + if (SaveSequencers() == false) return false; - m_interface->I_WriteSaveData( INT_ID('I','E','N','D'), &version, sizeof( version ) ); + m_interface->I_WriteSaveData(INT_ID('I', 'E', 'N', 'D'), &version, sizeof(version)); return true; } @@ -457,27 +421,25 @@ LoadSignals ------------------------- */ -int ICARUS_Instance::LoadSignals( void ) -{ +int ICARUS_Instance::LoadSignals(void) { int numSignals; - m_interface->I_ReadSaveData( INT_ID('I','S','I','G'), &numSignals, sizeof( numSignals ) ); + m_interface->I_ReadSaveData(INT_ID('I', 'S', 'I', 'G'), &numSignals, sizeof(numSignals)); - for ( int i = 0; i < numSignals; i++ ) - { - char buffer[1024]; - int length; + for (int i = 0; i < numSignals; i++) { + char buffer[1024]; + int length; - //Get the size of the string - m_interface->I_ReadSaveData( INT_ID('S','I','G','#'), &length, sizeof( length ) ); + // Get the size of the string + m_interface->I_ReadSaveData(INT_ID('S', 'I', 'G', '#'), &length, sizeof(length)); - assert( length < (int)sizeof( buffer ) ); + assert(length < (int)sizeof(buffer)); - //Get the string - m_interface->I_ReadSaveData( INT_ID('S','I','G','N'), &buffer, length ); + // Get the string + m_interface->I_ReadSaveData(INT_ID('S', 'I', 'G', 'N'), &buffer, length); - //Turn it on and add it to the system - Signal( (const char *) &buffer ); + // Turn it on and add it to the system + Signal((const char *)&buffer); } return true; @@ -489,15 +451,14 @@ LoadSequence ------------------------- */ -int ICARUS_Instance::LoadSequence( void ) -{ - CSequence *sequence = GetSequence(); +int ICARUS_Instance::LoadSequence(void) { + CSequence *sequence = GetSequence(); - //Load the sequence back in + // Load the sequence back in sequence->Load(); - //If this sequence had a higher GUID than the current, save it - if ( sequence->GetID() > m_GUID ) + // If this sequence had a higher GUID than the current, save it + if (sequence->GetID() > m_GUID) m_GUID = sequence->GetID(); return true; @@ -509,39 +470,37 @@ LoadSequence ------------------------- */ -int ICARUS_Instance::LoadSequences( void ) -{ - CSequence *sequence; - int numSequences; +int ICARUS_Instance::LoadSequences(void) { + CSequence *sequence; + int numSequences; - //Get the number of sequences to read in - m_interface->I_ReadSaveData( INT_ID('#','S','E','Q'), &numSequences, sizeof( numSequences ) ); + // Get the number of sequences to read in + m_interface->I_ReadSaveData(INT_ID('#', 'S', 'E', 'Q'), &numSequences, sizeof(numSequences)); - int *idTable = new int[ numSequences ]; + int *idTable = new int[numSequences]; - if ( idTable == NULL ) + if (idTable == NULL) return false; - //Load the sequencer ID table - m_interface->I_ReadSaveData( INT_ID('S','Q','T','B'), idTable, sizeof( int ) * numSequences ); + // Load the sequencer ID table + m_interface->I_ReadSaveData(INT_ID('S', 'Q', 'T', 'B'), idTable, sizeof(int) * numSequences); - //First pass, allocate all container sequences and give them their proper IDs - if ( AllocateSequences( numSequences, idTable ) == false ) + // First pass, allocate all container sequences and give them their proper IDs + if (AllocateSequences(numSequences, idTable) == false) return false; - //Second pass, load all sequences - for ( int i = 0; i < numSequences; i++ ) - { - //Get the proper sequence for this load - if ( ( sequence = GetSequence( idTable[i] ) ) == NULL ) + // Second pass, load all sequences + for (int i = 0; i < numSequences; i++) { + // Get the proper sequence for this load + if ((sequence = GetSequence(idTable[i])) == NULL) return false; - //Load the sequence - if ( ( sequence->Load() ) == false ) + // Load the sequence + if ((sequence->Load()) == false) return false; } - //Free the idTable + // Free the idTable delete[] idTable; return true; @@ -553,22 +512,20 @@ LoadSequencers ------------------------- */ -int ICARUS_Instance::LoadSequencers( void ) -{ - CSequencer *sequencer; - int numSequencers; +int ICARUS_Instance::LoadSequencers(void) { + CSequencer *sequencer; + int numSequencers; - //Get the number of sequencers to load - m_interface->I_ReadSaveData( INT_ID('#','S','Q','R'), &numSequencers, sizeof( numSequencers ) ); + // Get the number of sequencers to load + m_interface->I_ReadSaveData(INT_ID('#', 'S', 'Q', 'R'), &numSequencers, sizeof(numSequencers)); - //Load all sequencers - for ( int i = 0; i < numSequencers; i++ ) - { - //NOTENOTE: The ownerID will be replaced in the loading process - if ( ( sequencer = GetSequencer( -1 ) ) == NULL ) + // Load all sequencers + for (int i = 0; i < numSequencers; i++) { + // NOTENOTE: The ownerID will be replaced in the loading process + if ((sequencer = GetSequencer(-1)) == NULL) return false; - if ( sequencer->Load() == false ) + if (sequencer->Load() == false) return false; } @@ -581,44 +538,39 @@ Load ------------------------- */ -int ICARUS_Instance::Load( void ) -{ - //Clear out any old information +int ICARUS_Instance::Load(void) { + // Clear out any old information Free(); - //Check to make sure we're at the ICARUS save block - double version; - m_interface->I_ReadSaveData( INT_ID('I','C','A','R'), &version, sizeof( version ) ); + // Check to make sure we're at the ICARUS save block + double version; + m_interface->I_ReadSaveData(INT_ID('I', 'C', 'A', 'R'), &version, sizeof(version)); - //Versions must match! - if ( version != ICARUS_VERSION ) - { - m_interface->I_DPrintf( WL_ERROR, "save game data contains outdated ICARUS version information!\n"); + // Versions must match! + if (version != ICARUS_VERSION) { + m_interface->I_DPrintf(WL_ERROR, "save game data contains outdated ICARUS version information!\n"); return false; } - //Load all signals - if ( LoadSignals() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load signals from save game!\n"); + // Load all signals + if (LoadSignals() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load signals from save game!\n"); return false; } - //Load in all sequences - if ( LoadSequences() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load sequences from save game!\n"); + // Load in all sequences + if (LoadSequences() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load sequences from save game!\n"); return false; } - //Load in all sequencers - if ( LoadSequencers() == false ) - { - m_interface->I_DPrintf( WL_ERROR, "failed to load sequencers from save game!\n"); + // Load in all sequencers + if (LoadSequencers() == false) { + m_interface->I_DPrintf(WL_ERROR, "failed to load sequencers from save game!\n"); return false; } - m_interface->I_ReadSaveData( INT_ID('I','E','N','D'), &version, sizeof( version ) ); + m_interface->I_ReadSaveData(INT_ID('I', 'E', 'N', 'D'), &version, sizeof(version)); return true; } @@ -629,10 +581,7 @@ Signal ------------------------- */ -void ICARUS_Instance::Signal( const char *identifier ) -{ - m_signals[ identifier ] = 1; -} +void ICARUS_Instance::Signal(const char *identifier) { m_signals[identifier] = 1; } /* ------------------------- @@ -640,13 +589,12 @@ CheckSignal ------------------------- */ -bool ICARUS_Instance::CheckSignal( const char *identifier ) -{ - signal_m::iterator smi; +bool ICARUS_Instance::CheckSignal(const char *identifier) { + signal_m::iterator smi; - smi = m_signals.find( identifier ); + smi = m_signals.find(identifier); - if ( smi == m_signals.end() ) + if (smi == m_signals.end()) return false; return true; @@ -658,7 +606,4 @@ ClearSignal ------------------------- */ -void ICARUS_Instance::ClearSignal( const char *identifier ) -{ - m_signals.erase( identifier ); -} +void ICARUS_Instance::ClearSignal(const char *identifier) { m_signals.erase(identifier); } diff --git a/codemp/icarus/Interpreter.cpp b/codemp/icarus/Interpreter.cpp index 53a29dc0ff..9dfc8213d2 100644 --- a/codemp/icarus/Interpreter.cpp +++ b/codemp/icarus/Interpreter.cpp @@ -3,13 +3,13 @@ // -- jweier #ifdef _WIN32 -#include //For getcwd() +#include //For getcwd() #include //For getch() #else #include #include extern void *ICARUS_Malloc(int iSize); -extern void ICARUS_Free(void *pMem); +extern void ICARUS_Free(void *pMem); #endif #include @@ -25,110 +25,110 @@ extern void ICARUS_Free(void *pMem); =================================================================================================== */ -//FIXME: The following tables should be passed in to the interpreter for flexibility - -//Symbol Table - -keywordArray_t CInterpreter::m_symbolKeywords[] = -{ - //Blocks - "{", TK_BLOCK_START, - "}", TK_BLOCK_END, - - //Vectors - "<", TK_VECTOR_START, - ">", TK_VECTOR_END, - - //Groups - "(", TK_OPEN_PARENTHESIS, - ")", TK_CLOSED_PARENTHESIS, - - "=", TK_EQUALS, - "!", TK_NOT, - - //End - "", TK_EOF, +// FIXME: The following tables should be passed in to the interpreter for flexibility + +// Symbol Table + +keywordArray_t CInterpreter::m_symbolKeywords[] = { + // Blocks + "{", + TK_BLOCK_START, + "}", + TK_BLOCK_END, + + // Vectors + "<", + TK_VECTOR_START, + ">", + TK_VECTOR_END, + + // Groups + "(", + TK_OPEN_PARENTHESIS, + ")", + TK_CLOSED_PARENTHESIS, + + "=", + TK_EQUALS, + "!", + TK_NOT, + + // End + "", + TK_EOF, }; -keywordArray_t CInterpreter::m_conditionalKeywords[] = -{ - "", TK_EOF, +keywordArray_t CInterpreter::m_conditionalKeywords[] = { + "", + TK_EOF, }; -//ID Table - -keywordArray_t CInterpreter::m_IDKeywords[] = -{ - "AFFECT", ID_AFFECT, - "SOUND", ID_SOUND, - "MOVE", ID_MOVE, - "ROTATE", ID_ROTATE, - "WAIT", ID_WAIT, - "SET", ID_SET, - "LOOP", ID_LOOP, - "PRINT", ID_PRINT, - "TAG", ID_TAG, - "USE", ID_USE, - "FLUSH", ID_FLUSH, - "RUN", ID_RUN, - "KILL", ID_KILL, - "REMOVE", ID_REMOVE, - "CAMERA", ID_CAMERA, - "GET", ID_GET, - "RANDOM", ID_RANDOM, - "IF", ID_IF, - "ELSE", ID_ELSE, - "REM", ID_REM, - "FLOAT", TK_FLOAT, - "VECTOR", TK_VECTOR, - "STRING", TK_STRING, - "TASK", ID_TASK, - "DO", ID_DO, - "DECLARE", ID_DECLARE, - "FREE", ID_FREE, - "DOWAIT", ID_DOWAIT, - "SIGNAL", ID_SIGNAL, - "WAITSIGNAL", ID_WAITSIGNAL, - "PLAY", ID_PLAY, - - "", ID_EOF, -}; +// ID Table + +keywordArray_t CInterpreter::m_IDKeywords[] = { + "AFFECT", ID_AFFECT, "SOUND", ID_SOUND, "MOVE", ID_MOVE, "ROTATE", ID_ROTATE, "WAIT", ID_WAIT, "SET", ID_SET, "LOOP", + ID_LOOP, "PRINT", ID_PRINT, "TAG", ID_TAG, "USE", ID_USE, "FLUSH", ID_FLUSH, "RUN", ID_RUN, "KILL", ID_KILL, + "REMOVE", ID_REMOVE, "CAMERA", ID_CAMERA, "GET", ID_GET, "RANDOM", ID_RANDOM, "IF", ID_IF, "ELSE", ID_ELSE, "REM", + ID_REM, "FLOAT", TK_FLOAT, "VECTOR", TK_VECTOR, "STRING", TK_STRING, "TASK", ID_TASK, "DO", ID_DO, "DECLARE", ID_DECLARE, + "FREE", ID_FREE, "DOWAIT", ID_DOWAIT, "SIGNAL", ID_SIGNAL, "WAITSIGNAL", ID_WAITSIGNAL, "PLAY", ID_PLAY, -//Type Table - -keywordArray_t CInterpreter::m_typeKeywords[] = -{ - //Set types - "ANGLES", TYPE_ANGLES, - "ORIGIN", TYPE_ORIGIN, - - //Affect types - "INSERT", TYPE_INSERT, - "FLUSH", TYPE_FLUSH, - - //Get types - "FLOAT", TK_FLOAT, - "INT", TK_INT, - "VECTOR", TK_VECTOR, - "STRING", TK_STRING, - - "PAN", TYPE_PAN, - "ZOOM", TYPE_ZOOM, - "MOVE", TYPE_MOVE, - "FADE", TYPE_FADE, - "PATH", TYPE_PATH, - "ENABLE", TYPE_ENABLE, - "DISABLE", TYPE_DISABLE, - "SHAKE", TYPE_SHAKE, - "ROLL", TYPE_ROLL, - "TRACK", TYPE_TRACK, - "FOLLOW", TYPE_FOLLOW, - "DISTANCE", TYPE_DISTANCE, - - //End - "", TYPE_EOF, + "", ID_EOF, }; +// Type Table + +keywordArray_t CInterpreter::m_typeKeywords[] = { + // Set types + "ANGLES", + TYPE_ANGLES, + "ORIGIN", + TYPE_ORIGIN, + + // Affect types + "INSERT", + TYPE_INSERT, + "FLUSH", + TYPE_FLUSH, + + // Get types + "FLOAT", + TK_FLOAT, + "INT", + TK_INT, + "VECTOR", + TK_VECTOR, + "STRING", + TK_STRING, + + "PAN", + TYPE_PAN, + "ZOOM", + TYPE_ZOOM, + "MOVE", + TYPE_MOVE, + "FADE", + TYPE_FADE, + "PATH", + TYPE_PATH, + "ENABLE", + TYPE_ENABLE, + "DISABLE", + TYPE_DISABLE, + "SHAKE", + TYPE_SHAKE, + "ROLL", + TYPE_ROLL, + "TRACK", + TYPE_TRACK, + "FOLLOW", + TYPE_FOLLOW, + "DISTANCE", + TYPE_DISTANCE, + + // End + "", + TYPE_EOF, +}; /* =================================================================================================== @@ -138,13 +138,9 @@ keywordArray_t CInterpreter::m_typeKeywords[] = =================================================================================================== */ -CInterpreter::CInterpreter() -{ -} +CInterpreter::CInterpreter() {} -CInterpreter::~CInterpreter() -{ -} +CInterpreter::~CInterpreter() {} /* =================================================================================================== @@ -154,37 +150,31 @@ CInterpreter::~CInterpreter() =================================================================================================== */ -int CInterpreter::Error( char *format, ... ) -{ - va_list argptr; - char *error_file, error_msg[1024]="", work_dir[1024]="", out_msg[1024]=""; - int error_line = m_iCurrentLine; // m_tokenizer->GetCurLine(); +int CInterpreter::Error(char *format, ...) { + va_list argptr; + char *error_file, error_msg[1024] = "", work_dir[1024] = "", out_msg[1024] = ""; + int error_line = m_iCurrentLine; // m_tokenizer->GetCurLine(); - m_tokenizer->GetCurFilename( &error_file ); - if (!error_file) - { + m_tokenizer->GetCurFilename(&error_file); + if (!error_file) { // 99% of the time we'll get here now, because of pushed parse streams // error_file = (char *)m_sCurrentFile.c_str(); } - va_start (argptr, format); - vsprintf (error_msg, format, argptr); - va_end (argptr); + va_start(argptr, format); + vsprintf(error_msg, format, argptr); + va_end(argptr); - strcpy((char *) work_dir, getcwd( (char *) &work_dir, 1024 ) ); + strcpy((char *)work_dir, getcwd((char *)&work_dir, 1024)); - if (error_file[1] == ':') - { - sprintf((char *) out_msg, "%s (%d) : error: %s\n", error_file, error_line, error_msg); - } - else - { - sprintf((char *) out_msg, "%s\\%s (%d) : error: %s\n", work_dir, error_file, error_line, error_msg); + if (error_file[1] == ':') { + sprintf((char *)out_msg, "%s (%d) : error: %s\n", error_file, error_line, error_msg); + } else { + sprintf((char *)out_msg, "%s\\%s (%d) : error: %s\n", work_dir, error_file, error_line, error_msg); } - if (m_sCurrentLine.length()) - { + if (m_sCurrentLine.length()) { strcat(out_msg, "\nLine:\n\n"); strcat(out_msg, m_sCurrentLine.c_str()); strcat(out_msg, "\n"); @@ -192,7 +182,7 @@ int CInterpreter::Error( char *format, ... ) #ifdef __POP_UPS__ - MessageBox( NULL, out_msg, "Error", MB_OK ); + MessageBox(NULL, out_msg, "Error", MB_OK); #else @@ -206,8 +196,7 @@ int CInterpreter::Error( char *format, ... ) // This'll mean that technically it's saying block 1 is wrong, rather than the one in between them, but I can // live with that. // - if (m_iBadCBlockNumber == 0) - { + if (m_iBadCBlockNumber == 0) { m_iBadCBlockNumber = 1; } return false; @@ -227,8 +216,7 @@ InitVars ------------------------- */ -void CInterpreter::InitVars( void ) -{ +void CInterpreter::InitVars(void) { m_vars.clear(); m_varMap.clear(); } @@ -239,12 +227,10 @@ FreeVars ------------------------- */ -void CInterpreter::FreeVars( void ) -{ - variable_v::iterator vi; +void CInterpreter::FreeVars(void) { + variable_v::iterator vi; - for ( vi = m_vars.begin(); vi != m_vars.end(); ++vi ) - { + for (vi = m_vars.begin(); vi != m_vars.end(); ++vi) { delete (*vi); } @@ -257,23 +243,22 @@ AddVar ------------------------- */ -variable_t *CInterpreter::AddVar( const char *name, int type ) -{ - variable_t *var; +variable_t *CInterpreter::AddVar(const char *name, int type) { + variable_t *var; var = new variable_t; - if ( var == NULL ) + if (var == NULL) return NULL; - //Specify the type + // Specify the type var->type = type; - //Retain the name internally - strncpy( (char *) var->name, name, MAX_VAR_NAME ); + // Retain the name internally + strncpy((char *)var->name, name, MAX_VAR_NAME); - //Associate it - m_varMap[ name ] = var; + // Associate it + m_varMap[name] = var; return var; } @@ -284,13 +269,12 @@ FindVar ------------------------- */ -variable_t *CInterpreter::FindVar( const char *name ) -{ - variable_m::iterator vmi; +variable_t *CInterpreter::FindVar(const char *name) { + variable_m::iterator vmi; - vmi = m_varMap.find( name ); + vmi = m_varMap.find(name); - if ( vmi == m_varMap.end() ) + if (vmi == m_varMap.end()) return NULL; return (*vmi).second; @@ -302,35 +286,34 @@ GetVariable ------------------------- */ -int CInterpreter::GetVariable( int type ) -{ - const char *varName; - variable_t *var; - CToken *token; +int CInterpreter::GetVariable(int type) { + const char *varName; + variable_t *var; + CToken *token; - //Get the variable's name - token = m_tokenizer->GetToken( 0, 0 ); + // Get the variable's name + token = m_tokenizer->GetToken(0, 0); varName = token->GetStringValue(); - //See if we already have a variable by this name - var = FindVar( varName ); + // See if we already have a variable by this name + var = FindVar(varName); - //Variable names must be unique on creation - if ( var ) - return Error( "\"%s\" : already exists\n", varName ); + // Variable names must be unique on creation + if (var) + return Error("\"%s\" : already exists\n", varName); - //Add the variable - AddVar( varName, type ); + // Add the variable + AddVar(varName, type); - //Insert the variable into the stream + // Insert the variable into the stream - CBlock block; + CBlock block; - block.Create( TYPE_VARIABLE ); - block.Write( TK_FLOAT, (float) type ); - block.Write( TK_STRING, varName ); + block.Create(TYPE_VARIABLE); + block.Write(TK_FLOAT, (float)type); + block.Write(TK_STRING, varName); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); token->Delete(); @@ -345,30 +328,25 @@ int CInterpreter::GetVariable( int type ) =================================================================================================== */ -int CInterpreter::GetVector( CBlock *block ) -{ - //Look for a tag - if ( MatchTag() ) - { - return GetTag( block ); +int CInterpreter::GetVector(CBlock *block) { + // Look for a tag + if (MatchTag()) { + return GetTag(block); } - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - if ( Match( TK_VECTOR_START ) ) - { - //Get the vector - block->Write( TK_VECTOR, (float) TK_VECTOR ); + if (Match(TK_VECTOR_START)) { + // Get the vector + block->Write(TK_VECTOR, (float)TK_VECTOR); - for (int i=0; i<3; i++) - GetFloat( block ); + for (int i = 0; i < 3; i++) + GetFloat(block); - if (!Match( TK_VECTOR_END )) - { + if (!Match(TK_VECTOR_END)) { return Error("syntax error : expected end of vector"); } @@ -388,20 +366,18 @@ int CInterpreter::GetVector( CBlock *block ) =================================================================================================== */ -int CInterpreter::MatchTag( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchTag(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_TAG ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_TAG) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -419,20 +395,18 @@ int CInterpreter::MatchTag( void ) =================================================================================================== */ -int CInterpreter::MatchGet( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchGet(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_GET ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_GET) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -450,20 +424,18 @@ int CInterpreter::MatchGet( void ) =================================================================================================== */ -int CInterpreter::MatchRandom( void ) -{ - CToken *token; - const char *idName; - int id; +int CInterpreter::MatchRandom(void) { + CToken *token; + const char *idName; + int id; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); idName = token->GetStringValue(); - id = FindSymbol( idName, m_IDKeywords ); + id = FindSymbol(idName, m_IDKeywords); - if ( id != ID_RANDOM ) - { - //Return the token - m_tokenizer->PutBackToken( token ); + if (id != ID_RANDOM) { + // Return the token + m_tokenizer->PutBackToken(token); return false; } @@ -481,12 +453,10 @@ int CInterpreter::MatchRandom( void ) =================================================================================================== */ -int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) -{ +int CInterpreter::FindSymbol(const char *name, keywordArray_t *table) { keywordArray_t *ids; - for (ids = table; (strcmp(ids->m_keyword, "")); ids++) - { + for (ids = table; (strcmp(ids->m_keyword, "")); ids++) { if (!stricmp(name, ids->m_keyword)) return ids->m_tokenvalue; } @@ -494,7 +464,6 @@ int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) return -1; } - /* =================================================================================================== @@ -505,18 +474,16 @@ int CInterpreter::FindSymbol( const char *name, keywordArray_t *table) =================================================================================================== */ -//NOTENOTE: LookAhead() was separated from Match() for clarity +// NOTENOTE: LookAhead() was separated from Match() for clarity -int CInterpreter::Match( int token_id ) -{ - CToken *token; +int CInterpreter::Match(int token_id) { + CToken *token; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); - if ( token->GetType() != token_id ) - { - //This may have been a check, so don't loose the token - m_tokenizer->PutBackToken( token ); + if (token->GetType() != token_id) { + // This may have been a check, so don't loose the token + m_tokenizer->PutBackToken(token); return false; } @@ -530,12 +497,11 @@ GetNextType ------------------------- */ -int CInterpreter::GetNextType( void ) -{ - CToken *token = m_tokenizer->GetToken( 0, 0 ); - int id = token->GetType(); +int CInterpreter::GetNextType(void) { + CToken *token = m_tokenizer->GetToken(0, 0); + int id = token->GetType(); - m_tokenizer->PutBackToken( token ); + m_tokenizer->PutBackToken(token); return id; } @@ -550,20 +516,18 @@ int CInterpreter::GetNextType( void ) =================================================================================================== */ -int CInterpreter::LookAhead( int token_id ) -{ - CToken *token; +int CInterpreter::LookAhead(int token_id) { + CToken *token; - token = m_tokenizer->GetToken( 0, 0 ); + token = m_tokenizer->GetToken(0, 0); - if ( token->GetType() != token_id ) - { - m_tokenizer->PutBackToken( token ); + if (token->GetType() != token_id) { + m_tokenizer->PutBackToken(token); return false; } - m_tokenizer->PutBackToken( token ); + m_tokenizer->PutBackToken(token); return true; } @@ -578,10 +542,8 @@ int CInterpreter::LookAhead( int token_id ) =================================================================================================== */ -const char *CInterpreter::GetTokenName( int token_id ) -{ - switch ( token_id ) - { +const char *CInterpreter::GetTokenName(int token_id) { + switch (token_id) { case TK_STRING: return "STRING"; break; @@ -626,39 +588,32 @@ const char *CInterpreter::GetTokenName( int token_id ) =================================================================================================== */ -int CInterpreter::GetFloat( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetFloat(CBlock *block) { + CToken *token; + int type; - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - //Look for a random - if ( MatchRandom() ) - { - return GetRandom( block ); + // Look for a random + if (MatchRandom()) { + return GetRandom(block); } - token = m_tokenizer->GetToken(0,0); + token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - //Floats can accept either int or float values - if ( ( type != TK_FLOAT ) && ( type != TK_INT ) ) - { - return Error("syntax error : expected float; found %s", GetTokenName(type) ); + // Floats can accept either int or float values + if ((type != TK_FLOAT) && (type != TK_INT)) { + return Error("syntax error : expected float; found %s", GetTokenName(type)); } - if (type == TK_FLOAT) - { - block->Write( TK_FLOAT, (float) token->GetFloatValue() ); - } - else - { - block->Write( TK_FLOAT, (float) token->GetIntValue() ); + if (type == TK_FLOAT) { + block->Write(TK_FLOAT, (float)token->GetFloatValue()); + } else { + block->Write(TK_FLOAT, (float)token->GetIntValue()); } token->Delete(); @@ -676,10 +631,7 @@ int CInterpreter::GetFloat( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetInteger( CBlock *block ) -{ - return GetFloat( block ); -} +int CInterpreter::GetInteger(CBlock *block) { return GetFloat(block); } /* =================================================================================================== @@ -691,56 +643,50 @@ int CInterpreter::GetInteger( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetString( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetString(CBlock *block) { + CToken *token; + int type; - //Look for a get - if ( MatchGet() ) - { - return GetGet( block ); + // Look for a get + if (MatchGet()) { + return GetGet(block); } - //Look for a random - if ( MatchRandom() ) - { - return GetRandom( block ); + // Look for a random + if (MatchRandom()) { + return GetRandom(block); } token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( (type != TK_STRING) && (type != TK_CHAR) ) - { + if ((type != TK_STRING) && (type != TK_CHAR)) { return Error("syntax error : expected string; found %s", GetTokenName(type)); } -//UGLY HACK!!! + // UGLY HACK!!! - const char *temptr; - char temp[1024]; + const char *temptr; + char temp[1024]; temptr = token->GetStringValue(); - if ( strlen(temptr)+1 > sizeof( temp ) ) - { + if (strlen(temptr) + 1 > sizeof(temp)) { return false; } - for ( int i = 0; i < (int)strlen( temptr ); i++ ) - { - if ( temptr[i] == '#' ) + for (int i = 0; i < (int)strlen(temptr); i++) { + if (temptr[i] == '#') temp[i] = '\n'; else temp[i] = temptr[i]; } - temp[ strlen( temptr ) ] = 0; + temp[strlen(temptr)] = 0; -//UGLY HACK END!!! + // UGLY HACK END!!! - block->Write( TK_STRING, (const char *) &temp ); + block->Write(TK_STRING, (const char *)&temp); token->Delete(); @@ -757,15 +703,13 @@ int CInterpreter::GetString( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetIdentifier( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetIdentifier(CBlock *block) { + CToken *token; + int type; - //FIXME: Should identifiers do this? - if ( MatchGet() ) - { - if ( GetGet( block ) == false ) + // FIXME: Should identifiers do this? + if (MatchGet()) { + if (GetGet(block) == false) return false; return true; @@ -774,12 +718,11 @@ int CInterpreter::GetIdentifier( CBlock *block ) token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( type != TK_IDENTIFIER ) - { + if (type != TK_IDENTIFIER) { return Error("syntax error : expected indentifier; found %s", GetTokenName(type)); } - block->Write( TK_IDENTIFIER, (const char *) token->GetStringValue() ); + block->Write(TK_IDENTIFIER, (const char *)token->GetStringValue()); token->Delete(); @@ -796,23 +739,21 @@ int CInterpreter::GetIdentifier( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetEvaluator( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetEvaluator(CBlock *block) { + CToken *token; + int type; - if ( MatchGet() ) + if (MatchGet()) return false; - if ( MatchRandom() ) + if (MatchRandom()) return false; token = m_tokenizer->GetToken(0, 0); type = token->GetType(); token->Delete(); - switch ( type ) - { + switch (type) { case TK_GREATER_THAN: case TK_LESS_THAN: case TK_EQUALS: @@ -828,10 +769,10 @@ int CInterpreter::GetEvaluator( CBlock *block ) break; default: - return Error("syntax error : expected operator type, found %s", GetTokenName( type ) ); + return Error("syntax error : expected operator type, found %s", GetTokenName(type)); } - block->Write( type, 0 ); + block->Write(type, 0); return true; } @@ -846,30 +787,26 @@ int CInterpreter::GetEvaluator( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetAny( CBlock *block ) -{ - CToken *token; - int type; +int CInterpreter::GetAny(CBlock *block) { + CToken *token; + int type; - if ( MatchGet() ) - { - if ( GetGet( block ) == false ) + if (MatchGet()) { + if (GetGet(block) == false) return false; return true; } - if ( MatchRandom() ) - { - if ( GetRandom( block ) == false ) + if (MatchRandom()) { + if (GetRandom(block) == false) return false; return true; } - if ( MatchTag() ) - { - if ( GetTag( block ) == false ) + if (MatchTag()) { + if (GetTag(block) == false) return false; return true; @@ -878,40 +815,39 @@ int CInterpreter::GetAny( CBlock *block ) token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - switch ( type ) - { + switch (type) { case TK_FLOAT: - m_tokenizer->PutBackToken( token ); - if ( GetFloat( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetFloat(block) == false) return false; break; case TK_INT: - m_tokenizer->PutBackToken( token ); - if ( GetInteger( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetInteger(block) == false) return false; break; case TK_VECTOR_START: - m_tokenizer->PutBackToken( token ); - if ( GetVector( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetVector(block) == false) return false; break; case TK_STRING: case TK_CHAR: - m_tokenizer->PutBackToken( token ); - if ( GetString( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetString(block) == false) return false; break; case TK_IDENTIFIER: - m_tokenizer->PutBackToken( token ); - if ( GetIdentifier( block ) == false ) + m_tokenizer->PutBackToken(token); + if (GetIdentifier(block) == false) return false; break; @@ -933,24 +869,21 @@ int CInterpreter::GetAny( CBlock *block ) =================================================================================================== */ -int CInterpreter::GetType( char *get ) -{ - CToken *token; - char *string; - int type; +int CInterpreter::GetType(char *get) { + CToken *token; + char *string; + int type; token = m_tokenizer->GetToken(0, 0); type = token->GetType(); - if ( type != TK_IDENTIFIER ) - { + if (type != TK_IDENTIFIER) { return Error("syntax error : expected identifier; found %s", GetTokenName(type)); } - string = (char *) token->GetStringValue(); + string = (char *)token->GetStringValue(); - if ( (strlen(string) + 1) > MAX_STRING_LENGTH) - { + if ((strlen(string) + 1) > MAX_STRING_LENGTH) { Error("string exceeds 256 character limit"); return false; } @@ -970,35 +903,33 @@ int CInterpreter::GetType( char *get ) =================================================================================================== */ -//FIXME: This should use an externally defined table to match ID and functions +// FIXME: This should use an externally defined table to match ID and functions -int CInterpreter::GetID( char *id_name ) -{ - int id; +int CInterpreter::GetID(char *id_name) { + int id; - id = FindSymbol( id_name, m_IDKeywords ); + id = FindSymbol(id_name, m_IDKeywords); - if ( id == -1 ) + if (id == -1) return Error("'%s' : unknown identifier", id_name); - //FIXME: Function pointers would be awfully nice.. but not inside a class! Weee!! + // FIXME: Function pointers would be awfully nice.. but not inside a class! Weee!! - switch (id) - { + switch (id) { - //Affect takes control of an entity + // Affect takes control of an entity case ID_AFFECT: return GetAffect(); break; - //Wait for a specified amount of time + // Wait for a specified amount of time case ID_WAIT: return GetWait(); break; - //Generic set call + // Generic set call case ID_SET: return GetSet(); @@ -1053,8 +984,8 @@ int CInterpreter::GetID( char *id_name ) break; case ID_ELSE: - //return Error("syntax error : else without matching if"); - return GetElse(); //FIXME: Protect this call so that floating else's aren't allowed + // return Error("syntax error : else without matching if"); + return GetElse(); // FIXME: Protect this call so that floating else's aren't allowed break; case ID_GET: @@ -1098,18 +1029,18 @@ int CInterpreter::GetID( char *id_name ) break; case ID_PLAY: - GetPlay(); //Bad eighties slang joke... yeah, it's not really funny, I know... + GetPlay(); // Bad eighties slang joke... yeah, it's not really funny, I know... break; - //Local variable types + // Local variable types case TK_FLOAT: case TK_INT: case TK_STRING: case TK_VECTOR: - GetVariable( id ); + GetVariable(id); break; - //Unknown ID + // Unknown ID default: case -1: @@ -1134,69 +1065,65 @@ GetDeclare ------------------------- */ -int CInterpreter::GetDeclare( void ) -{ - CBlock block; - char typeName[MAX_STRING_LENGTH]; - int type; +int CInterpreter::GetDeclare(void) { + CBlock block; + char typeName[MAX_STRING_LENGTH]; + int type; - block.Create( ID_DECLARE ); + block.Create(ID_DECLARE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TK_FLOAT: case TK_VECTOR: case TK_STRING: - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); break; default: - return Error("unknown identifier %s", typeName ); + return Error("unknown identifier %s", typeName); break; } - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("declare : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } - /* ------------------------- GetFree ------------------------- */ -int CInterpreter::GetFree( void ) -{ - CBlock block; +int CInterpreter::GetFree(void) { + CBlock block; - block.Create( ID_FREE ); + block.Create(ID_FREE); - if ( Match( TK_OPEN_PARENTHESIS ) == false ) + if (Match(TK_OPEN_PARENTHESIS) == false) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if ( Match( TK_CLOSED_PARENTHESIS ) == false ) + if (Match(TK_CLOSED_PARENTHESIS) == false) return Error("free : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1213,28 +1140,27 @@ int CInterpreter::GetFree( void ) // if ( STRING ? STRING ) -int CInterpreter::GetIf( void ) -{ - CBlock block; +int CInterpreter::GetIf(void) { + CBlock block; - block.Create( ID_IF ); + block.Create(ID_IF); - if ( Match( TK_OPEN_PARENTHESIS ) == false ) + if (Match(TK_OPEN_PARENTHESIS) == false) return Error("syntax error : '(' not found"); - if ( GetAny( &block ) == false ) + if (GetAny(&block) == false) return false; - if ( GetEvaluator( &block ) == false ) + if (GetEvaluator(&block) == false) return false; - if ( GetAny( &block ) == false ) + if (GetAny(&block) == false) return false; - if ( Match( TK_CLOSED_PARENTHESIS ) == false ) + if (Match(TK_CLOSED_PARENTHESIS) == false) return Error("if : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1251,11 +1177,10 @@ int CInterpreter::GetIf( void ) // else -int CInterpreter::GetElse( void ) -{ - CBlock block; +int CInterpreter::GetElse(void) { + CBlock block; - block.Create( ID_ELSE ); + block.Create(ID_ELSE); /* if ( Match( TK_OPEN_PARENTHESIS ) == false ) @@ -1278,7 +1203,7 @@ int CInterpreter::GetElse( void ) return Error("sound : too many parameters"); */ - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1293,27 +1218,25 @@ int CInterpreter::GetElse( void ) =================================================================================================== */ -//task ( name ) { } +// task ( name ) { } -int CInterpreter::GetTask( void ) -{ - CBlock block; +int CInterpreter::GetTask(void) { + CBlock block; - block.Create( ID_TASK ); + block.Create(ID_TASK); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("GetTask: too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; - } /* @@ -1326,24 +1249,23 @@ int CInterpreter::GetTask( void ) =================================================================================================== */ -//do ( taskName ) +// do ( taskName ) -int CInterpreter::GetDo( void ) -{ - CBlock block; +int CInterpreter::GetDo(void) { + CBlock block; - block.Create( ID_DO ); + block.Create(ID_DO); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("do : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1360,39 +1282,37 @@ int CInterpreter::GetDo( void ) // get( TYPE, NAME ); -int CInterpreter::GetGet( CBlock *block ) -{ - char typeName[MAX_STRING_LENGTH]; - int type; +int CInterpreter::GetGet(CBlock *block) { + char typeName[MAX_STRING_LENGTH]; + int type; - block->Write( ID_GET, (float) ID_GET ); + block->Write(ID_GET, (float)ID_GET); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TK_FLOAT: case TK_INT: case TK_VECTOR: case TK_STRING: - block->Write( TK_FLOAT, (float) type ); + block->Write(TK_FLOAT, (float)type); break; default: - return Error("unknown identifier %s", typeName ); + return Error("unknown identifier %s", typeName); break; } - if ( GetString( block ) == false ) + if (GetString(block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); return true; @@ -1410,20 +1330,19 @@ int CInterpreter::GetGet( CBlock *block ) // random( low, high ); -int CInterpreter::GetRandom( CBlock *block ) -{ - block->Write( ID_RANDOM, (float) ID_RANDOM ); +int CInterpreter::GetRandom(CBlock *block) { + block->Write(ID_RANDOM, (float)ID_RANDOM); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetFloat( block ) == false ) + if (GetFloat(block) == false) return false; - if ( GetFloat( block ) == false ) + if (GetFloat(block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); return true; @@ -1441,25 +1360,24 @@ int CInterpreter::GetRandom( CBlock *block ) // sound( NAME ); -int CInterpreter::GetSound( void ) -{ - CBlock block; +int CInterpreter::GetSound(void) { + CBlock block; - block.Create( ID_SOUND ); + block.Create(ID_SOUND); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetIdentifier( &block ) == false ) + if (GetIdentifier(&block) == false) return false; - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("sound : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1476,32 +1394,30 @@ int CInterpreter::GetSound( void ) // move( ORIGIN, ANGLES, DURATION ); -int CInterpreter::GetMove( void ) -{ - CBlock block; +int CInterpreter::GetMove(void) { + CBlock block; - block.Create( ID_MOVE ); + block.Create(ID_MOVE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - //Angles are optional - if ( LookAhead( TK_VECTOR_START ) || LookAhead( TK_IDENTIFIER ) ) - { - if ( GetVector( &block ) == false ) + // Angles are optional + if (LookAhead(TK_VECTOR_START) || LookAhead(TK_IDENTIFIER)) { + if (GetVector(&block) == false) return false; } - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("move : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1518,25 +1434,24 @@ int CInterpreter::GetMove( void ) // move( ANGLES, DURATION ); -int CInterpreter::GetRotate( void ) -{ - CBlock block; +int CInterpreter::GetRotate(void) { + CBlock block; - block.Create( ID_ROTATE ); + block.Create(ID_ROTATE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("move : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1551,54 +1466,51 @@ int CInterpreter::GetRotate( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetAffect( void ) -{ - CBlock block; - char typeName[MAX_STRING_SIZE]; - int type; +int CInterpreter::GetAffect(void) { + CBlock block; + char typeName[MAX_STRING_SIZE]; + int type; - block.Create( ID_AFFECT ); + block.Create(ID_AFFECT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!LookAhead( TK_IDENTIFIER )) + if (!LookAhead(TK_IDENTIFIER)) return Error("syntax error : identifier not found"); - if ( MatchGet() ) + if (MatchGet()) return Error("syntax error : illegal use of \"get\""); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { + switch (type) { case TYPE_INSERT: case TYPE_FLUSH: - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); break; default: - return Error("'%s': unknown affect type", typeName ); + return Error("'%s': unknown affect type", typeName); break; - } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("affect : too many parameters"); - if (!LookAhead( TK_BLOCK_START )) + if (!LookAhead(TK_BLOCK_START)) return Error("syntax error : '{' not found"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1613,32 +1525,28 @@ int CInterpreter::GetAffect( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetWait( void ) -{ - CBlock block; +int CInterpreter::GetWait(void) { + CBlock block; - block.Create( ID_WAIT ); + block.Create(ID_WAIT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( LookAhead( TK_STRING ) ) - { - if ( GetString( &block ) == false ) + if (LookAhead(TK_STRING)) { + if (GetString(&block) == false) return false; - } - else - { - if ( GetFloat( &block ) == false ) + } else { + if (GetFloat(&block) == false) return false; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("wait : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1653,69 +1561,62 @@ int CInterpreter::GetWait( void ) =================================================================================================== */ -//FIXME: This should be externally defined +// FIXME: This should be externally defined -int CInterpreter::GetSet( void ) -{ - CBlock block; +int CInterpreter::GetSet(void) { + CBlock block; - block.Create( ID_SET ); + block.Create(ID_SET); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - //Check for get placement - if ( MatchGet() ) - { - if ( GetGet( &block ) == false ) + // Check for get placement + if (MatchGet()) { + if (GetGet(&block) == false) return false; - } - else - { - switch( GetNextType() ) - { + } else { + switch (GetNextType()) { case TK_INT: - if ( GetInteger( &block ) == false ) + if (GetInteger(&block) == false) return false; break; case TK_FLOAT: - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; case TK_STRING: - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; break; case TK_VECTOR_START: - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; break; default: - if ( MatchTag() ) - { - GetTag( &block ); + if (MatchTag()) { + GetTag(&block); break; } - if ( MatchRandom() ) - { - GetRandom( &block ); + if (MatchRandom()) { + GetRandom(&block); break; } @@ -1724,10 +1625,10 @@ int CInterpreter::GetSet( void ) } } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("set : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1742,30 +1643,26 @@ int CInterpreter::GetSet( void ) =================================================================================================== */ -int CInterpreter::GetLoop( void ) -{ - CBlock block; +int CInterpreter::GetLoop(void) { + CBlock block; - block.Create( ID_LOOP ); + block.Create(ID_LOOP); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( LookAhead( TK_CLOSED_PARENTHESIS ) ) - { + if (LookAhead(TK_CLOSED_PARENTHESIS)) { //-1 denotes an infinite loop - block.Write( TK_FLOAT, (float) -1); - } - else - { - if ( GetInteger( &block ) == false ) + block.Write(TK_FLOAT, (float)-1); + } else { + if (GetInteger(&block) == false) return false; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("GetLoop : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1780,22 +1677,21 @@ int CInterpreter::GetLoop( void ) =================================================================================================== */ -int CInterpreter::GetPrint( void ) -{ - CBlock block; +int CInterpreter::GetPrint(void) { + CBlock block; - block.Create( ID_PRINT ); + block.Create(ID_PRINT); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("print : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1810,22 +1706,21 @@ int CInterpreter::GetPrint( void ) =================================================================================================== */ -int CInterpreter::GetUse( void ) -{ - CBlock block; +int CInterpreter::GetUse(void) { + CBlock block; - block.Create( ID_USE ); + block.Create(ID_USE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("use : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1840,19 +1735,18 @@ int CInterpreter::GetUse( void ) =================================================================================================== */ -int CInterpreter::GetFlush( void ) -{ - CBlock block; +int CInterpreter::GetFlush(void) { + CBlock block; - block.Create( ID_FLUSH ); + block.Create(ID_FLUSH); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("flush : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1867,22 +1761,21 @@ int CInterpreter::GetFlush( void ) =================================================================================================== */ -int CInterpreter::GetRun( void ) -{ - CBlock block; +int CInterpreter::GetRun(void) { + CBlock block; - block.Create( ID_RUN ); + block.Create(ID_RUN); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("run : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1897,22 +1790,21 @@ int CInterpreter::GetRun( void ) =================================================================================================== */ -int CInterpreter::GetKill( void ) -{ - CBlock block; +int CInterpreter::GetKill(void) { + CBlock block; - block.Create( ID_KILL ); + block.Create(ID_KILL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("kill : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1927,22 +1819,21 @@ int CInterpreter::GetKill( void ) =================================================================================================== */ -int CInterpreter::GetRemove( void ) -{ - CBlock block; +int CInterpreter::GetRemove(void) { + CBlock block; - block.Create( ID_REMOVE ); + block.Create(ID_REMOVE); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("remove : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -1959,29 +1850,27 @@ int CInterpreter::GetRemove( void ) // this is just so people can put comments in scripts in BehavEd and not have them lost as normal comments would be. // -int CInterpreter::GetRem( void ) -{ - CBlock block; +int CInterpreter::GetRem(void) { + CBlock block; - block.Create( ID_REM ); + block.Create(ID_REM); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); // optional string? - if (Match( TK_CLOSED_PARENTHESIS )) + if (Match(TK_CLOSED_PARENTHESIS)) return true; - GetString( &block ); + GetString(&block); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("rem : function only takes 1 optional parameter"); return true; } - /* =================================================================================================== @@ -1992,91 +1881,89 @@ int CInterpreter::GetRem( void ) =================================================================================================== */ -int CInterpreter::GetCamera( void ) -{ - CBlock block; - char typeName[MAX_STRING_SIZE]; - int type; +int CInterpreter::GetCamera(void) { + CBlock block; + char typeName[MAX_STRING_SIZE]; + int type; - block.Create( ID_CAMERA ); + block.Create(ID_CAMERA); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetType( (char *) typeName ) == false ) + if (GetType((char *)typeName) == false) return false; - type = FindSymbol( typeName, m_typeKeywords); + type = FindSymbol(typeName, m_typeKeywords); - switch ( type ) - { - case TYPE_PAN: //PAN ( ANGLES, DURATION ) + switch (type) { + case TYPE_PAN: // PAN ( ANGLES, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; - case TYPE_ZOOM: //ZOOM ( FOV, DURATION ) + case TYPE_ZOOM: // ZOOM ( FOV, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; - case TYPE_MOVE: //MOVE ( ORIGIN, DURATION ) + case TYPE_MOVE: // MOVE ( ORIGIN, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - if ( GetVector( &block ) == false ) + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; break; - case TYPE_FADE: //FADE ( SOURCE(R,G,B,A), DEST(R,G,B,A), DURATION ) + case TYPE_FADE: // FADE ( SOURCE(R,G,B,A), DEST(R,G,B,A), DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Source color - if ( GetVector( &block ) == false ) + // Source color + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - //Dest color - if ( GetVector( &block ) == false ) + // Dest color + if (GetVector(&block) == false) return false; - if ( GetFloat( &block ) == false ) + if (GetFloat(&block) == false) return false; - //Duration - if ( GetFloat( &block ) == false ) + // Duration + if (GetFloat(&block) == false) return false; break; - case TYPE_PATH: //PATH ( FILENAME ) + case TYPE_PATH: // PATH ( FILENAME ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Filename - if ( GetString( &block ) == false ) + // Filename + if (GetString(&block) == false) return false; break; @@ -2084,92 +1971,92 @@ int CInterpreter::GetCamera( void ) case TYPE_ENABLE: case TYPE_DISABLE: - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); break; - case TYPE_SHAKE: //SHAKE ( INTENSITY, DURATION ) + case TYPE_SHAKE: // SHAKE ( INTENSITY, DURATION ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Intensity - if ( GetFloat( &block ) == false ) + // Intensity + if (GetFloat(&block) == false) return false; - //Duration - if ( GetFloat( &block ) == false ) + // Duration + if (GetFloat(&block) == false) return false; break; - case TYPE_ROLL: //ROLL ( ANGLE, TIME ) + case TYPE_ROLL: // ROLL ( ANGLE, TIME ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Angle - if ( GetFloat( &block ) == false ) + // Angle + if (GetFloat(&block) == false) return false; - //Time - if ( GetFloat( &block ) == false ) + // Time + if (GetFloat(&block) == false) return false; break; - case TYPE_TRACK: //TRACK ( TARGETNAME, SPEED, INITLERP ) + case TYPE_TRACK: // TRACK ( TARGETNAME, SPEED, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Target name - if ( GetString( &block ) == false ) + // Target name + if (GetString(&block) == false) return false; - //Speed - if ( GetFloat( &block ) == false ) + // Speed + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; - case TYPE_FOLLOW: //FOLLOW ( CAMERAGROUP, SPEED, INITLERP ) + case TYPE_FOLLOW: // FOLLOW ( CAMERAGROUP, SPEED, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Camera group - if ( GetString( &block ) == false ) + // Camera group + if (GetString(&block) == false) return false; - //Speed - if ( GetFloat( &block ) == false ) + // Speed + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; - case TYPE_DISTANCE: //DISTANCE ( DISTANCE, INITLERP ) + case TYPE_DISTANCE: // DISTANCE ( DISTANCE, INITLERP ) - block.Write( TK_FLOAT, (float) type ); + block.Write(TK_FLOAT, (float)type); - //Distance - if ( GetFloat( &block ) == false ) + // Distance + if (GetFloat(&block) == false) return false; - //Init lerp - if ( GetFloat( &block ) == false ) + // Init lerp + if (GetFloat(&block) == false) return false; break; } - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("camera : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2180,33 +2067,32 @@ GetDoWait ------------------------- */ -int CInterpreter::GetDoWait( void ) -{ - CBlock block; +int CInterpreter::GetDoWait(void) { + CBlock block; - //Write out the "do" portion - block.Create( ID_DO ); + // Write out the "do" portion + block.Create(ID_DO); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("do : too many parameters"); - //Write out the accompanying "wait" - char *str = (char *) block.GetMemberData( 0 ); + // Write out the accompanying "wait" + char *str = (char *)block.GetMemberData(0); - CBlock block2; + CBlock block2; - block2.Create( ID_WAIT ); + block2.Create(ID_WAIT); - block2.Write( TK_STRING, (char *) str ); + block2.Write(TK_STRING, (char *)str); - m_blockStream->WriteBlock( &block ); - m_blockStream->WriteBlock( &block2 ); + m_blockStream->WriteBlock(&block); + m_blockStream->WriteBlock(&block2); return true; } @@ -2217,22 +2103,21 @@ GetSignal ------------------------- */ -int CInterpreter::GetSignal( void ) -{ - CBlock block; +int CInterpreter::GetSignal(void) { + CBlock block; - block.Create( ID_SIGNAL ); + block.Create(ID_SIGNAL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("signal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2243,22 +2128,21 @@ GetSignal ------------------------- */ -int CInterpreter::GetWaitSignal( void ) -{ - CBlock block; +int CInterpreter::GetWaitSignal(void) { + CBlock block; - block.Create( ID_WAITSIGNAL ); + block.Create(ID_WAITSIGNAL); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("waitsignal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2269,25 +2153,24 @@ GetPlay ------------------------- */ -int CInterpreter::GetPlay( void ) -{ - CBlock block; +int CInterpreter::GetPlay(void) { + CBlock block; - block.Create( ID_PLAY ); + block.Create(ID_PLAY); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if ( GetString( &block ) == false ) + if (GetString(&block) == false) return false; - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("waitsignal : too many parameters"); - m_blockStream->WriteBlock( &block ); + m_blockStream->WriteBlock(&block); return true; } @@ -2302,37 +2185,35 @@ int CInterpreter::GetPlay( void ) =================================================================================================== */ -//NOTENOTE: The tag's information is included as block members, not as a separate block. +// NOTENOTE: The tag's information is included as block members, not as a separate block. -int CInterpreter::GetTag( CBlock *block ) -{ - char typeName[MAX_STRING_SIZE]; - int typeID; +int CInterpreter::GetTag(CBlock *block) { + char typeName[MAX_STRING_SIZE]; + int typeID; - //Mark as a tag - block->Write( ID_TAG, (float) ID_TAG ); + // Mark as a tag + block->Write(ID_TAG, (float)ID_TAG); - if (!Match( TK_OPEN_PARENTHESIS )) + if (!Match(TK_OPEN_PARENTHESIS)) return Error("syntax error : '(' not found"); - //Get the tag name - if ( GetString( block ) == false ) + // Get the tag name + if (GetString(block) == false) return false; - //Get the lookup ID - GetType( (char *) typeName ); + // Get the lookup ID + GetType((char *)typeName); - typeID = FindSymbol( (char *) typeName, m_typeKeywords); + typeID = FindSymbol((char *)typeName, m_typeKeywords); - //Tags only contain origin and angles lookups - if ( (typeID != TYPE_ORIGIN) && (typeID != TYPE_ANGLES) ) - { - return Error("syntax error : 'tag' : %s is not a valid look up identifier", typeName ); + // Tags only contain origin and angles lookups + if ((typeID != TYPE_ORIGIN) && (typeID != TYPE_ANGLES)) { + return Error("syntax error : 'tag' : %s is not a valid look up identifier", typeName); } - block->Write( TK_FLOAT, (float) typeID ); + block->Write(TK_FLOAT, (float)typeID); - if (!Match( TK_CLOSED_PARENTHESIS )) + if (!Match(TK_CLOSED_PARENTHESIS)) return Error("tag : too many parameters"); return true; @@ -2351,16 +2232,15 @@ int CInterpreter::GetTag( CBlock *block ) // I also return -ve block numbers for errors between blocks. Eg if you read 3 good blocks, then find an unexpected // float in the script between blocks 3 & 4 then I return -3 to indicate the error is after that, but not block 4 // -int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, char *filename ) -{ - CBlock block; - CToken *token; - int type, blockLevel = 0, parenthesisLevel = 0; +int CInterpreter::Interpret(CTokenizer *Tokenizer, CBlockStream *BlockStream, char *filename) { + CBlock block; + CToken *token; + int type, blockLevel = 0, parenthesisLevel = 0; - m_sCurrentFile = filename; // used during error reporting because you can't ask tokenizer for pushed streams + m_sCurrentFile = filename; // used during error reporting because you can't ask tokenizer for pushed streams - m_tokenizer = Tokenizer; - m_blockStream = BlockStream; + m_tokenizer = Tokenizer; + m_blockStream = BlockStream; m_iCurrentLine = m_tokenizer->GetCurLine(); token = m_tokenizer->GetToEndOfLine(TK_STRING); @@ -2369,13 +2249,11 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c m_iBadCBlockNumber = 0; - while (m_tokenizer->GetRemainingSize() > 0) - { - token = m_tokenizer->GetToken( TKF_USES_EOL, 0 ); + while (m_tokenizer->GetRemainingSize() > 0) { + token = m_tokenizer->GetToken(TKF_USES_EOL, 0); type = token->GetType(); - switch ( type ) - { + switch (type) { case TK_UNDEFINED: token->Delete(); m_iBadCBlockNumber = -m_iBadCBlockNumber; @@ -2419,8 +2297,7 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c case TK_IDENTIFIER: m_iBadCBlockNumber++; - if (!GetID( (char *) token->GetStringValue() )) - { + if (!GetID((char *)token->GetStringValue())) { token->Delete(); return m_iBadCBlockNumber; } @@ -2429,8 +2306,7 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c case TK_BLOCK_START: token->Delete(); - if (parenthesisLevel) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : brace inside parenthesis"); return m_iBadCBlockNumber; @@ -2441,15 +2317,14 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c case TK_BLOCK_END: token->Delete(); - if (parenthesisLevel) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : brace inside parenthesis"); return m_iBadCBlockNumber; } - block.Create( ID_BLOCK_END ); - m_blockStream->WriteBlock( &block ); + block.Create(ID_BLOCK_END); + m_blockStream->WriteBlock(&block); block.Free(); blockLevel--; @@ -2466,8 +2341,7 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c blockLevel--; parenthesisLevel--; - if (parenthesisLevel<0) - { + if (parenthesisLevel < 0) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("syntax error : closed parenthesis with no opening match"); return m_iBadCBlockNumber; @@ -2490,24 +2364,21 @@ int CInterpreter::Interpret( CTokenizer *Tokenizer, CBlockStream *BlockStream, c } } - if ( blockLevel ) - { + if (blockLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("error : open brace was not closed"); return m_iBadCBlockNumber; } - if ( parenthesisLevel ) - { + if (parenthesisLevel) { m_iBadCBlockNumber = -m_iBadCBlockNumber; Error("error: open parenthesis"); return m_iBadCBlockNumber; } - //Release all the variable information, because it's already been written out + // Release all the variable information, because it's already been written out FreeVars(); m_iBadCBlockNumber = 0; - return m_iBadCBlockNumber; //true; + return m_iBadCBlockNumber; // true; } - diff --git a/codemp/icarus/Memory.cpp b/codemp/icarus/Memory.cpp index d9d907cf19..e862a71c3b 100644 --- a/codemp/icarus/Memory.cpp +++ b/codemp/icarus/Memory.cpp @@ -24,16 +24,14 @@ along with this program; if not, see . // leave these two as standard mallocs for the moment, there's something weird happening in ICARUS... // -void *ICARUS_Malloc(int iSize) -{ - //return gi.Malloc(iSize, TAG_ICARUS); - //return malloc(iSize); +void *ICARUS_Malloc(int iSize) { + // return gi.Malloc(iSize, TAG_ICARUS); + // return malloc(iSize); return Z_Malloc(iSize, TAG_ICARUS5, qfalse); } -void ICARUS_Free(void *pMem) -{ - //gi.Free(pMem); - //free(pMem); +void ICARUS_Free(void *pMem) { + // gi.Free(pMem); + // free(pMem); Z_Free(pMem); } diff --git a/codemp/icarus/Q3_Interface.cpp b/codemp/icarus/Q3_Interface.cpp index 059d65dc46..f54afe6573 100644 --- a/codemp/icarus/Q3_Interface.cpp +++ b/codemp/icarus/Q3_Interface.cpp @@ -35,7 +35,7 @@ along with this program; if not, see . #include "Q3_Registers.h" #include "server/sv_gameapi.h" -#define stringIDExpand(str, strEnum) str, strEnum, ENUM2STRING(strEnum) +#define stringIDExpand(str, strEnum) str, strEnum, ENUM2STRING(strEnum) //#define stringIDExpand(str, strEnum) str,strEnum /* @@ -45,12 +45,11 @@ stringID_table_t tagsTable [] = */ extern float Q_flrand(float min, float max); -extern qboolean COM_ParseString( char **data, char **s ); +extern qboolean COM_ParseString(char **data, char **s); //======================================================================= -interface_export_t interface_export; - +interface_export_t interface_export; /* ============ @@ -61,10 +60,9 @@ Q3_ReadScript Argument : void **buf ============ */ -extern int ICARUS_GetScript( const char *name, char **buf ); //g_icarus.cpp -static int Q3_ReadScript( const char *name, void **buf ) -{ - return ICARUS_GetScript( va( "%s/%s", Q3_SCRIPT_DIR, name ), (char**)buf ); //get a (hopefully) cached file +extern int ICARUS_GetScript(const char *name, char **buf); // g_icarus.cpp +static int Q3_ReadScript(const char *name, void **buf) { + return ICARUS_GetScript(va("%s/%s", Q3_SCRIPT_DIR, name), (char **)buf); // get a (hopefully) cached file } /* @@ -76,36 +74,33 @@ Q3_CenterPrint Argument : ... ============ */ -static void Q3_CenterPrint ( const char *format, ... ) -{ +static void Q3_CenterPrint(const char *format, ...) { - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr, format); + va_start(argptr, format); Q_vsnprintf(text, sizeof(text), format, argptr); - va_end (argptr); + va_end(argptr); // FIXME: added '!' so you can print something that's hasn't been precached, '@' searches only for precache text // this is just a TEMPORARY placeholder until objectives are in!!! -- dmv 11/26/01 - if ((text[0] == '@') || text[0] == '!') // It's a key + if ((text[0] == '@') || text[0] == '!') // It's a key { - if( text[0] == '!') - { - SV_SendServerCommand( NULL, "cp \"%s\"", (text+1) ); + if (text[0] == '!') { + SV_SendServerCommand(NULL, "cp \"%s\"", (text + 1)); return; } - SV_SendServerCommand( NULL, "cp \"%s\"", text ); + SV_SendServerCommand(NULL, "cp \"%s\"", text); } - Q3_DebugPrint( WL_VERBOSE, "%s\n", text); // Just a developers note + Q3_DebugPrint(WL_VERBOSE, "%s\n", text); // Just a developers note return; } - /* ------------------------- void Q3_ClearTaskID( int *taskID ) @@ -114,29 +109,23 @@ WARNING: Clearing a taskID will make that task never finish unless you intend to return the same taskID from somewhere else. ------------------------- */ -void Q3_TaskIDClear( int *taskID ) -{ - *taskID = -1; -} +void Q3_TaskIDClear(int *taskID) { *taskID = -1; } /* ------------------------- qboolean Q3_TaskIDPending( sharedEntity_t *ent, taskID_t taskType ) ------------------------- */ -qboolean Q3_TaskIDPending( sharedEntity_t *ent, taskID_t taskType ) -{ - if ( !gSequencers[ent->s.number] || !gTaskManagers[ent->s.number] ) - { +qboolean Q3_TaskIDPending(sharedEntity_t *ent, taskID_t taskType) { + if (!gSequencers[ent->s.number] || !gTaskManagers[ent->s.number]) { return qfalse; } - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return qfalse; } - if ( ent->taskID[taskType] >= 0 )//-1 is none + if (ent->taskID[taskType] >= 0) //-1 is none { return qtrue; } @@ -149,31 +138,26 @@ qboolean Q3_TaskIDPending( sharedEntity_t *ent, taskID_t taskType ) void Q3_TaskIDComplete( sharedEntity_t *ent, taskID_t taskType ) ------------------------- */ -void Q3_TaskIDComplete( sharedEntity_t *ent, taskID_t taskType ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +void Q3_TaskIDComplete(sharedEntity_t *ent, taskID_t taskType) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - if ( gTaskManagers[ent->s.number] && Q3_TaskIDPending( ent, taskType ) ) - {//Complete it - gTaskManagers[ent->s.number]->Completed( ent->taskID[taskType] ); - - //See if any other tasks have the name number and clear them so we don't complete more than once - int clearTask = ent->taskID[taskType]; - for ( int tid = 0; tid < NUM_TIDS; tid++ ) - { - if ( ent->taskID[tid] == clearTask ) - { - Q3_TaskIDClear( &ent->taskID[tid] ); + if (gTaskManagers[ent->s.number] && Q3_TaskIDPending(ent, taskType)) { // Complete it + gTaskManagers[ent->s.number]->Completed(ent->taskID[taskType]); + + // See if any other tasks have the name number and clear them so we don't complete more than once + int clearTask = ent->taskID[taskType]; + for (int tid = 0; tid < NUM_TIDS; tid++) { + if (ent->taskID[tid] == clearTask) { + Q3_TaskIDClear(&ent->taskID[tid]); } } - //clear it - should be cleared in for loop above - //Q3_TaskIDClear( &ent->taskID[taskType] ); + // clear it - should be cleared in for loop above + // Q3_TaskIDClear( &ent->taskID[taskType] ); } - //otherwise, wasn't waiting for a task to complete anyway + // otherwise, wasn't waiting for a task to complete anyway } /* @@ -182,20 +166,17 @@ void Q3_SetTaskID( sharedEntity_t *ent, taskID_t taskType, int taskID ) ------------------------- */ -void Q3_TaskIDSet( sharedEntity_t *ent, taskID_t taskType, int taskID ) -{ - if ( taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS ) - { +void Q3_TaskIDSet(sharedEntity_t *ent, taskID_t taskType, int taskID) { + if (taskType < TID_CHAN_VOICE || taskType >= NUM_TIDS) { return; } - //Might be stomping an old task, so complete and clear previous task if there was one - Q3_TaskIDComplete( ent, taskType ); + // Might be stomping an old task, so complete and clear previous task if there was one + Q3_TaskIDComplete(ent, taskType); ent->taskID[taskType] = taskID; } - /* ============ Q3_CheckStringCounterIncrement @@ -204,25 +185,19 @@ Q3_CheckStringCounterIncrement Argument : const char *string ============ */ -static float Q3_CheckStringCounterIncrement( const char *string ) -{ - char *numString; - float val = 0.0f; +static float Q3_CheckStringCounterIncrement(const char *string) { + char *numString; + float val = 0.0f; - if ( string[0] == '+' ) - {//We want to increment whatever the value is by whatever follows the + - if ( string[1] ) - { + if (string[0] == '+') { // We want to increment whatever the value is by whatever follows the + + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ); + val = atof(numString); } - } - else if ( string[0] == '-' ) - {//we want to decrement - if ( string[1] ) - { + } else if (string[0] == '-') { // we want to decrement + if (string[1]) { numString = (char *)&string[1]; - val = atof( numString ) * -1; + val = atof(numString) * -1; } } @@ -236,30 +211,29 @@ Q3_GetEntityByName Returns the sequencer of the entity by the given name ============= */ -static sharedEntity_t *Q3_GetEntityByName( const char *name ) -{ - sharedEntity_t *ent; - entlist_t::iterator ei; - char temp[1024]; +static sharedEntity_t *Q3_GetEntityByName(const char *name) { + sharedEntity_t *ent; + entlist_t::iterator ei; + char temp[1024]; - if ( name == NULL || name[0] == '\0' ) + if (name == NULL || name[0] == '\0') return NULL; - strncpy( (char *) temp, name, sizeof(temp) ); - temp[sizeof(temp)-1] = 0; + strncpy((char *)temp, name, sizeof(temp)); + temp[sizeof(temp) - 1] = 0; - ei = ICARUS_EntList.find( Q_strupr( (char *) temp ) ); + ei = ICARUS_EntList.find(Q_strupr((char *)temp)); - if ( ei == ICARUS_EntList.end() ) + if (ei == ICARUS_EntList.end()) return NULL; ent = SV_GentityNum((*ei).second); return ent; // this now returns the ent instead of the sequencer -- dmv 06/27/01 -// if (ent == NULL) -// return NULL; -// return gSequencers[ent->s.number]; + // if (ent == NULL) + // return NULL; + // return gSequencers[ent->s.number]; } /* @@ -269,10 +243,7 @@ Q3_GetTime Get the current game time ============= */ -static unsigned int Q3_GetTime( void ) -{ - return svs.time; -} +static unsigned int Q3_GetTime(void) { return svs.time; } /* ============= @@ -328,8 +299,7 @@ Q3_PlaySound Plays a sound from an entity ============= */ -static int Q3_PlaySound( int taskID, int entID, const char *name, const char *channel ) -{ +static int Q3_PlaySound(int taskID, int entID, const char *name, const char *channel) { T_G_ICARUS_PLAYSOUND *sharedMem = (T_G_ICARUS_PLAYSOUND *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -340,7 +310,6 @@ static int Q3_PlaySound( int taskID, int entID, const char *name, const char *ch return GVM_ICARUS_PlaySound(); } - /* ============ Q3_SetVar @@ -352,44 +321,37 @@ Q3_SetVar Argument : const char *data ============ */ -void Q3_SetVar( int taskID, int entID, const char *type_name, const char *data ) -{ - int vret = Q3_VariableDeclared( type_name ) ; - float float_data; - float val = 0.0f; - +void Q3_SetVar(int taskID, int entID, const char *type_name, const char *data) { + int vret = Q3_VariableDeclared(type_name); + float float_data; + float val = 0.0f; - if ( vret != VTYPE_NONE ) - { - switch ( vret ) - { + if (vret != VTYPE_NONE) { + switch (vret) { case VTYPE_FLOAT: - //Check to see if increment command - if ( (val = Q3_CheckStringCounterIncrement( data )) ) - { - Q3_GetFloatVariable( type_name, &float_data ); + // Check to see if increment command + if ((val = Q3_CheckStringCounterIncrement(data))) { + Q3_GetFloatVariable(type_name, &float_data); float_data += val; + } else { + float_data = atof((char *)data); } - else - { - float_data = atof((char *) data); - } - Q3_SetFloatVariable( type_name, float_data ); + Q3_SetFloatVariable(type_name, float_data); break; case VTYPE_STRING: - Q3_SetStringVariable( type_name, data ); + Q3_SetStringVariable(type_name, data); break; case VTYPE_VECTOR: - Q3_SetVectorVariable( type_name, (char *) data ); + Q3_SetVectorVariable(type_name, (char *)data); break; } return; } - Q3_DebugPrint( WL_ERROR, "%s variable or field not found!\n", type_name ); + Q3_DebugPrint(WL_ERROR, "%s variable or field not found!\n", type_name); } /* @@ -403,8 +365,7 @@ Q3_Set Argument : const char *data ============ */ -static void Q3_Set( int taskID, int entID, const char *type_name, const char *data ) -{ +static void Q3_Set(int taskID, int entID, const char *type_name, const char *data) { T_G_ICARUS_SET *sharedMem = (T_G_ICARUS_SET *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -412,13 +373,11 @@ static void Q3_Set( int taskID, int entID, const char *type_name, const char *da strcpy(sharedMem->type_name, type_name); strcpy(sharedMem->data, data); - if ( GVM_ICARUS_Set() ) - { - gTaskManagers[entID]->Completed( taskID ); + if (GVM_ICARUS_Set()) { + gTaskManagers[entID]->Completed(taskID); } } - /* ============ Q3_Evaluate @@ -431,197 +390,188 @@ Q3_Evaluate Argument : int operatorType ============ */ -static int Q3_Evaluate( int p1Type, const char *p1, int p2Type, const char *p2, int operatorType ) -{ - float f1=0, f2=0; - vec3_t v1, v2; - char *c1=0, *c2=0; - int i1=0, i2=0; - - //Always demote to int on float to integer comparisons - if ( ( ( p1Type == TK_FLOAT ) && ( p2Type == TK_INT ) ) || ( ( p1Type == TK_INT ) && ( p2Type == TK_FLOAT ) ) ) - { +static int Q3_Evaluate(int p1Type, const char *p1, int p2Type, const char *p2, int operatorType) { + float f1 = 0, f2 = 0; + vec3_t v1, v2; + char *c1 = 0, *c2 = 0; + int i1 = 0, i2 = 0; + + // Always demote to int on float to integer comparisons + if (((p1Type == TK_FLOAT) && (p2Type == TK_INT)) || ((p1Type == TK_INT) && (p2Type == TK_FLOAT))) { p1Type = TK_INT; p2Type = TK_INT; } - //Cannot compare two disimilar types - if ( p1Type != p2Type ) - { - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate comparing two disimilar types!\n"); + // Cannot compare two disimilar types + if (p1Type != p2Type) { + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate comparing two disimilar types!\n"); return false; } - //Format the parameters - switch ( p1Type ) - { + // Format the parameters + switch (p1Type) { case TK_FLOAT: - sscanf( p1, "%f", &f1 ); - sscanf( p2, "%f", &f2 ); + sscanf(p1, "%f", &f1); + sscanf(p2, "%f", &f2); break; case TK_INT: - sscanf( p1, "%d", &i1 ); - sscanf( p2, "%d", &i2 ); + sscanf(p1, "%d", &i1); + sscanf(p2, "%d", &i2); break; case TK_VECTOR: - sscanf( p1, "%f %f %f", &v1[0], &v1[1], &v1[2] ); - sscanf( p2, "%f %f %f", &v2[0], &v2[1], &v2[2] ); + sscanf(p1, "%f %f %f", &v1[0], &v1[1], &v1[2]); + sscanf(p2, "%f %f %f", &v2[0], &v2[1], &v2[2]); break; case TK_STRING: case TK_IDENTIFIER: - c1 = (char *) p1; - c2 = (char *) p2; + c1 = (char *)p1; + c2 = (char *)p2; break; default: - Q3_DebugPrint( WL_WARNING, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_WARNING, "Q3_Evaluate unknown type used!\n"); return false; } - //Compare them and return the result + // Compare them and return the result - //FIXME: YUCK!!! Better way to do this? + // FIXME: YUCK!!! Better way to do this? - switch ( operatorType ) - { + switch (operatorType) { - // - // EQUAL TO - // + // + // EQUAL TO + // case TK_EQUALS: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 == f2 ); + return (int)(f1 == f2); break; case TK_INT: - return (int) ( i1 == i2 ); + return (int)(i1 == i2); break; case TK_VECTOR: - return (int) VectorCompare( v1, v2 ); + return (int)VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) !Q_stricmp( c1, c2 ); //NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) + return (int)!Q_stricmp(c1, c2); // NOTENOTE: The script uses proper string comparison logic (ex. ( a == a ) == true ) break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // GREATER THAN - // + // + // GREATER THAN + // case TK_GREATER_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 > f2 ); + return (int)(f1 > f2); break; case TK_INT: - return (int) ( i1 > i2 ); + return (int)(i1 > i2); break; case TK_VECTOR: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate vector comparisons of type GREATER THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate vector comparisons of type GREATER THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate string comparisons of type GREATER THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate string comparisons of type GREATER THAN cannot be performed!"); return false; break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // LESS THAN - // + // + // LESS THAN + // case TK_LESS_THAN: - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 < f2 ); + return (int)(f1 < f2); break; case TK_INT: - return (int) ( i1 < i2 ); + return (int)(i1 < i2); break; case TK_VECTOR: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate vector comparisons of type LESS THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate vector comparisons of type LESS THAN cannot be performed!"); return false; break; case TK_STRING: case TK_IDENTIFIER: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate string comparisons of type LESS THAN cannot be performed!"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate string comparisons of type LESS THAN cannot be performed!"); return false; break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; - // - // NOT - // + // + // NOT + // - case TK_NOT: //NOTENOTE: Implied "NOT EQUAL TO" + case TK_NOT: // NOTENOTE: Implied "NOT EQUAL TO" - switch ( p1Type ) - { + switch (p1Type) { case TK_FLOAT: - return (int) ( f1 != f2 ); + return (int)(f1 != f2); break; case TK_INT: - return (int) ( i1 != i2 ); + return (int)(i1 != i2); break; case TK_VECTOR: - return (int) !VectorCompare( v1, v2 ); + return (int)!VectorCompare(v1, v2); break; case TK_STRING: case TK_IDENTIFIER: - return (int) Q_stricmp( c1, c2 ); + return (int)Q_stricmp(c1, c2); break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown type used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown type used!\n"); return false; } break; default: - Q3_DebugPrint( WL_ERROR, "Q3_Evaluate unknown operator used!\n"); + Q3_DebugPrint(WL_ERROR, "Q3_Evaluate unknown operator used!\n"); break; } @@ -633,9 +583,8 @@ static int Q3_Evaluate( int p1Type, const char *p1, int p2Type, const char *p2, Q3_CameraFade ------------------------- */ -static void Q3_CameraFade( float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration ) -{ - Q3_DebugPrint( WL_WARNING, "Q3_CameraFade: NOT SUPPORTED IN MP\n"); +static void Q3_CameraFade(float sr, float sg, float sb, float sa, float dr, float dg, float db, float da, float duration) { + Q3_DebugPrint(WL_WARNING, "Q3_CameraFade: NOT SUPPORTED IN MP\n"); } /* @@ -643,173 +592,119 @@ static void Q3_CameraFade( float sr, float sg, float sb, float sa, float dr, flo Q3_CameraPath ------------------------- */ -static void Q3_CameraPath( const char *name ) -{ - Q3_DebugPrint( WL_WARNING, "Q3_CameraPath: NOT SUPPORTED IN MP\n"); -} +static void Q3_CameraPath(const char *name) { Q3_DebugPrint(WL_WARNING, "Q3_CameraPath: NOT SUPPORTED IN MP\n"); } /* ------------------------- Q3_DebugPrint ------------------------- */ -void Q3_DebugPrint( int level, const char *format, ... ) -{ - //Don't print messages they don't want to see - //if ( g_ICARUSDebug->integer < level ) +void Q3_DebugPrint(int level, const char *format, ...) { + // Don't print messages they don't want to see + // if ( g_ICARUSDebug->integer < level ) if (!com_developer || !com_developer->integer) return; - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr, format); + va_start(argptr, format); Q_vsnprintf(text, sizeof(text), format, argptr); - va_end (argptr); + va_end(argptr); - //Add the color formatting - switch ( level ) - { - case WL_ERROR: - Com_Printf ( S_COLOR_RED"ERROR: %s", text ); - break; + // Add the color formatting + switch (level) { + case WL_ERROR: + Com_Printf(S_COLOR_RED "ERROR: %s", text); + break; - case WL_WARNING: - Com_Printf ( S_COLOR_YELLOW"WARNING: %s", text ); - break; + case WL_WARNING: + Com_Printf(S_COLOR_YELLOW "WARNING: %s", text); + break; - case WL_DEBUG: - { - int entNum; - char *buffer; + case WL_DEBUG: { + int entNum; + char *buffer; - sscanf( text, "%d", &entNum ); + sscanf(text, "%d", &entNum); - if ( ( ICARUS_entFilter >= 0 ) && ( ICARUS_entFilter != entNum ) ) - return; + if ((ICARUS_entFilter >= 0) && (ICARUS_entFilter != entNum)) + return; - buffer = (char *) text; - buffer += 5; + buffer = (char *)text; + buffer += 5; - if ( ( entNum < 0 ) || ( entNum >= MAX_GENTITIES ) ) - entNum = 0; + if ((entNum < 0) || (entNum >= MAX_GENTITIES)) + entNum = 0; - Com_Printf ( S_COLOR_BLUE"DEBUG: %s(%d): %s\n", SV_GentityNum(entNum)->script_targetname, entNum, buffer ); - break; - } - default: - case WL_VERBOSE: - Com_Printf ( S_COLOR_GREEN"INFO: %s", text ); - break; + Com_Printf(S_COLOR_BLUE "DEBUG: %s(%d): %s\n", SV_GentityNum(entNum)->script_targetname, entNum, buffer); + break; + } + default: + case WL_VERBOSE: + Com_Printf(S_COLOR_GREEN "INFO: %s", text); + break; } } -void CGCam_Anything( void ) -{ - Q3_DebugPrint( WL_WARNING, "Camera functions NOT SUPPORTED IN MP\n"); -} +void CGCam_Anything(void) { Q3_DebugPrint(WL_WARNING, "Camera functions NOT SUPPORTED IN MP\n"); } -//These are useless for MP. Just taking it for now since I don't want to remove all calls to this in ICARUS. -int AppendToSaveGame(unsigned long chid, const void *data, int length) -{ - return 1; -} +// These are useless for MP. Just taking it for now since I don't want to remove all calls to this in ICARUS. +int AppendToSaveGame(unsigned long chid, const void *data, int length) { return 1; } // Changed by BTO (VV) - Visual C++ 7.1 doesn't allow default args on funcion pointers -int ReadFromSaveGame(unsigned long chid, void *pvAddress, int iLength /* , void **ppvAddressPtr = NULL */ ) -{ - return 1; -} +int ReadFromSaveGame(unsigned long chid, void *pvAddress, int iLength /* , void **ppvAddressPtr = NULL */) { return 1; } -void CGCam_Enable( void ) -{ - CGCam_Anything(); -} +void CGCam_Enable(void) { CGCam_Anything(); } -void CGCam_Disable( void ) -{ - CGCam_Anything(); -} +void CGCam_Disable(void) { CGCam_Anything(); } -void CGCam_Zoom( float FOV, float duration ) -{ - CGCam_Anything(); -} +void CGCam_Zoom(float FOV, float duration) { CGCam_Anything(); } -void CGCam_Pan( vec3_t dest, vec3_t panDirection, float duration ) -{ - CGCam_Anything(); -} +void CGCam_Pan(vec3_t dest, vec3_t panDirection, float duration) { CGCam_Anything(); } -void CGCam_Move( vec3_t dest, float duration ) -{ - CGCam_Anything(); -} +void CGCam_Move(vec3_t dest, float duration) { CGCam_Anything(); } -void CGCam_Shake( float intensity, int duration ) -{ - CGCam_Anything(); -} +void CGCam_Shake(float intensity, int duration) { CGCam_Anything(); } -void CGCam_Follow( const char *cameraGroup, float speed, float initLerp ) -{ - CGCam_Anything(); -} +void CGCam_Follow(const char *cameraGroup, float speed, float initLerp) { CGCam_Anything(); } -void CGCam_Track( const char *trackName, float speed, float initLerp ) -{ - CGCam_Anything(); -} +void CGCam_Track(const char *trackName, float speed, float initLerp) { CGCam_Anything(); } -void CGCam_Distance( float distance, float initLerp ) -{ - CGCam_Anything(); -} +void CGCam_Distance(float distance, float initLerp) { CGCam_Anything(); } -void CGCam_Roll( float dest, float duration ) -{ - CGCam_Anything(); -} +void CGCam_Roll(float dest, float duration) { CGCam_Anything(); } -int ICARUS_LinkEntity( int entID, CSequencer *sequencer, CTaskManager *taskManager ); +int ICARUS_LinkEntity(int entID, CSequencer *sequencer, CTaskManager *taskManager); -static unsigned int Q3_GetTimeScale( void ) -{ - return com_timescale->value; -} +static unsigned int Q3_GetTimeScale(void) { return com_timescale->value; } -static void Q3_Lerp2Pos( int taskID, int entID, vec3_t origin, vec3_t angles, float duration ) -{ +static void Q3_Lerp2Pos(int taskID, int entID, vec3_t origin, vec3_t angles, float duration) { T_G_ICARUS_LERP2POS *sharedMem = (T_G_ICARUS_LERP2POS *)sv.mSharedMemory; sharedMem->taskID = taskID; sharedMem->entID = entID; VectorCopy(origin, sharedMem->origin); - if (angles) - { + if (angles) { VectorCopy(angles, sharedMem->angles); sharedMem->nullAngles = qfalse; - } - else - { + } else { sharedMem->nullAngles = qtrue; } sharedMem->duration = duration; GVM_ICARUS_Lerp2Pos(); - //We do this in case the values are modified in the game. It would be expected by icarus that - //the values passed in here are modified equally. + // We do this in case the values are modified in the game. It would be expected by icarus that + // the values passed in here are modified equally. VectorCopy(sharedMem->origin, origin); - if (angles) - { + if (angles) { VectorCopy(sharedMem->angles, angles); } } -static void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration ) -{ +static void Q3_Lerp2Origin(int taskID, int entID, vec3_t origin, float duration) { T_G_ICARUS_LERP2ORIGIN *sharedMem = (T_G_ICARUS_LERP2ORIGIN *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -821,8 +716,7 @@ static void Q3_Lerp2Origin( int taskID, int entID, vec3_t origin, float duration VectorCopy(sharedMem->origin, origin); } -static void Q3_Lerp2Angles( int taskID, int entID, vec3_t angles, float duration ) -{ +static void Q3_Lerp2Angles(int taskID, int entID, vec3_t angles, float duration) { T_G_ICARUS_LERP2ANGLES *sharedMem = (T_G_ICARUS_LERP2ANGLES *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -834,8 +728,7 @@ static void Q3_Lerp2Angles( int taskID, int entID, vec3_t angles, float duration VectorCopy(sharedMem->angles, angles); } -static int Q3_GetTag( int entID, const char *name, int lookup, vec3_t info ) -{ +static int Q3_GetTag(int entID, const char *name, int lookup, vec3_t info) { int r; T_G_ICARUS_GETTAG *sharedMem = (T_G_ICARUS_GETTAG *)sv.mSharedMemory; @@ -849,8 +742,7 @@ static int Q3_GetTag( int entID, const char *name, int lookup, vec3_t info ) return r; } -static void Q3_Lerp2Start( int entID, int taskID, float duration ) -{ +static void Q3_Lerp2Start(int entID, int taskID, float duration) { T_G_ICARUS_LERP2START *sharedMem = (T_G_ICARUS_LERP2START *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -860,8 +752,7 @@ static void Q3_Lerp2Start( int entID, int taskID, float duration ) GVM_ICARUS_Lerp2Start(); } -static void Q3_Lerp2End( int entID, int taskID, float duration ) -{ +static void Q3_Lerp2End(int entID, int taskID, float duration) { T_G_ICARUS_LERP2END *sharedMem = (T_G_ICARUS_LERP2END *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -871,8 +762,7 @@ static void Q3_Lerp2End( int entID, int taskID, float duration ) GVM_ICARUS_Lerp2End(); } -static void Q3_Use( int entID, const char *target ) -{ +static void Q3_Use(int entID, const char *target) { T_G_ICARUS_USE *sharedMem = (T_G_ICARUS_USE *)sv.mSharedMemory; sharedMem->entID = entID; @@ -881,8 +771,7 @@ static void Q3_Use( int entID, const char *target ) GVM_ICARUS_Use(); } -static void Q3_Kill( int entID, const char *name ) -{ +static void Q3_Kill(int entID, const char *name) { T_G_ICARUS_KILL *sharedMem = (T_G_ICARUS_KILL *)sv.mSharedMemory; sharedMem->entID = entID; @@ -891,8 +780,7 @@ static void Q3_Kill( int entID, const char *name ) GVM_ICARUS_Kill(); } -static void Q3_Remove( int entID, const char *name ) -{ +static void Q3_Remove(int entID, const char *name) { T_G_ICARUS_REMOVE *sharedMem = (T_G_ICARUS_REMOVE *)sv.mSharedMemory; sharedMem->entID = entID; @@ -901,8 +789,7 @@ static void Q3_Remove( int entID, const char *name ) GVM_ICARUS_Remove(); } -static void Q3_Play( int taskID, int entID, const char *type, const char *name ) -{ +static void Q3_Play(int taskID, int entID, const char *type, const char *name) { T_G_ICARUS_PLAY *sharedMem = (T_G_ICARUS_PLAY *)sv.mSharedMemory; sharedMem->taskID = taskID; @@ -913,23 +800,21 @@ static void Q3_Play( int taskID, int entID, const char *type, const char *name ) GVM_ICARUS_Play(); } -static int Q3_GetFloat( int entID, int type, const char *name, float *value ) -{ +static int Q3_GetFloat(int entID, int type, const char *name, float *value) { int r; T_G_ICARUS_GETFLOAT *sharedMem = (T_G_ICARUS_GETFLOAT *)sv.mSharedMemory; sharedMem->entID = entID; sharedMem->type = type; strcpy(sharedMem->name, name); - sharedMem->value = 0;//*value; + sharedMem->value = 0; //*value; r = GVM_ICARUS_GetFloat(); *value = sharedMem->value; return r; } -static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) -{ +static int Q3_GetVector(int entID, int type, const char *name, vec3_t value) { int r; T_G_ICARUS_GETVECTOR *sharedMem = (T_G_ICARUS_GETVECTOR *)sv.mSharedMemory; @@ -943,8 +828,7 @@ static int Q3_GetVector( int entID, int type, const char *name, vec3_t value ) return r; } -static int Q3_GetString( int entID, int type, const char *name, char **value ) -{ +static int Q3_GetString(int entID, int type, const char *name, char **value) { int r; T_G_ICARUS_GETSTRING *sharedMem = (T_G_ICARUS_GETSTRING *)sv.mSharedMemory; @@ -953,12 +837,11 @@ static int Q3_GetString( int entID, int type, const char *name, char **value ) strcpy(sharedMem->name, name); r = GVM_ICARUS_GetString(); - //rww - careful with this, next time shared memory is altered this will get stomped + // rww - careful with this, next time shared memory is altered this will get stomped *value = &sharedMem->value[0]; return r; } - /* ============ Interface_Init @@ -967,57 +850,56 @@ Interface_Init Argument : interface_export_t *pe ============ */ -void Interface_Init( interface_export_t *pe ) -{ - //TODO: This is where you link up all your functions to the engine - - //General - pe->I_LoadFile = Q3_ReadScript; - pe->I_CenterPrint = Q3_CenterPrint; - pe->I_DPrintf = Q3_DebugPrint; - pe->I_GetEntityByName = Q3_GetEntityByName; - pe->I_GetTime = Q3_GetTime; - pe->I_GetTimeScale = Q3_GetTimeScale; - pe->I_PlaySound = Q3_PlaySound; - pe->I_Lerp2Pos = Q3_Lerp2Pos; - pe->I_Lerp2Origin = Q3_Lerp2Origin; - pe->I_Lerp2Angles = Q3_Lerp2Angles; - pe->I_GetTag = Q3_GetTag; - pe->I_Lerp2Start = Q3_Lerp2Start; - pe->I_Lerp2End = Q3_Lerp2End; - pe->I_Use = Q3_Use; - pe->I_Kill = Q3_Kill; - pe->I_Remove = Q3_Remove; - pe->I_Set = Q3_Set; - pe->I_Random = Q_flrand; - pe->I_Play = Q3_Play; - - //Camera functions - pe->I_CameraEnable = CGCam_Enable; - pe->I_CameraDisable = CGCam_Disable; - pe->I_CameraZoom = CGCam_Zoom; - pe->I_CameraMove = CGCam_Move; - pe->I_CameraPan = CGCam_Pan; - pe->I_CameraRoll = CGCam_Roll; - pe->I_CameraTrack = CGCam_Track; - pe->I_CameraFollow = CGCam_Follow; - pe->I_CameraDistance = CGCam_Distance; - pe->I_CameraShake = CGCam_Shake; - pe->I_CameraFade = Q3_CameraFade; - pe->I_CameraPath = Q3_CameraPath; - - //Variable information - pe->I_GetFloat = Q3_GetFloat; - pe->I_GetVector = Q3_GetVector; - pe->I_GetString = Q3_GetString; - - pe->I_Evaluate = Q3_Evaluate; - - pe->I_DeclareVariable = Q3_DeclareVariable; - pe->I_FreeVariable = Q3_FreeVariable; - - //Save / Load functions - pe->I_WriteSaveData = AppendToSaveGame; - pe->I_ReadSaveData = ReadFromSaveGame; - pe->I_LinkEntity = ICARUS_LinkEntity; +void Interface_Init(interface_export_t *pe) { + // TODO: This is where you link up all your functions to the engine + + // General + pe->I_LoadFile = Q3_ReadScript; + pe->I_CenterPrint = Q3_CenterPrint; + pe->I_DPrintf = Q3_DebugPrint; + pe->I_GetEntityByName = Q3_GetEntityByName; + pe->I_GetTime = Q3_GetTime; + pe->I_GetTimeScale = Q3_GetTimeScale; + pe->I_PlaySound = Q3_PlaySound; + pe->I_Lerp2Pos = Q3_Lerp2Pos; + pe->I_Lerp2Origin = Q3_Lerp2Origin; + pe->I_Lerp2Angles = Q3_Lerp2Angles; + pe->I_GetTag = Q3_GetTag; + pe->I_Lerp2Start = Q3_Lerp2Start; + pe->I_Lerp2End = Q3_Lerp2End; + pe->I_Use = Q3_Use; + pe->I_Kill = Q3_Kill; + pe->I_Remove = Q3_Remove; + pe->I_Set = Q3_Set; + pe->I_Random = Q_flrand; + pe->I_Play = Q3_Play; + + // Camera functions + pe->I_CameraEnable = CGCam_Enable; + pe->I_CameraDisable = CGCam_Disable; + pe->I_CameraZoom = CGCam_Zoom; + pe->I_CameraMove = CGCam_Move; + pe->I_CameraPan = CGCam_Pan; + pe->I_CameraRoll = CGCam_Roll; + pe->I_CameraTrack = CGCam_Track; + pe->I_CameraFollow = CGCam_Follow; + pe->I_CameraDistance = CGCam_Distance; + pe->I_CameraShake = CGCam_Shake; + pe->I_CameraFade = Q3_CameraFade; + pe->I_CameraPath = Q3_CameraPath; + + // Variable information + pe->I_GetFloat = Q3_GetFloat; + pe->I_GetVector = Q3_GetVector; + pe->I_GetString = Q3_GetString; + + pe->I_Evaluate = Q3_Evaluate; + + pe->I_DeclareVariable = Q3_DeclareVariable; + pe->I_FreeVariable = Q3_FreeVariable; + + // Save / Load functions + pe->I_WriteSaveData = AppendToSaveGame; + pe->I_ReadSaveData = ReadFromSaveGame; + pe->I_LinkEntity = ICARUS_LinkEntity; } diff --git a/codemp/icarus/Q3_Registers.cpp b/codemp/icarus/Q3_Registers.cpp index 53fd3b01dc..5ef7e094cb 100644 --- a/codemp/icarus/Q3_Registers.cpp +++ b/codemp/icarus/Q3_Registers.cpp @@ -23,13 +23,13 @@ along with this program; if not, see . #include "game/g_public.h" #include "Q3_Registers.h" -extern void Q3_DebugPrint( int level, const char *format, ... ); +extern void Q3_DebugPrint(int level, const char *format, ...); -varString_m varStrings; -varFloat_m varFloats; -varString_m varVectors; //Work around for vector types +varString_m varStrings; +varFloat_m varFloats; +varString_m varVectors; // Work around for vector types -int numVariables = 0; +int numVariables = 0; /* ------------------------- @@ -37,24 +37,23 @@ Q3_VariableDeclared ------------------------- */ -int Q3_VariableDeclared( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_VariableDeclared(const char *name) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) + if (vsi != varStrings.end()) return VTYPE_STRING; - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) + if (vfi != varFloats.end()) return VTYPE_FLOAT; - //Check the vectors - varString_m::iterator vvi = varVectors.find( name ); + // Check the vectors + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) + if (vvi != varVectors.end()) return VTYPE_VECTOR; return VTYPE_NONE; @@ -66,34 +65,31 @@ Q3_DeclareVariable ------------------------- */ -void Q3_DeclareVariable( int type, const char *name ) -{ - //Cannot declare the same variable twice - if ( Q3_VariableDeclared( name ) != VTYPE_NONE ) +void Q3_DeclareVariable(int type, const char *name) { + // Cannot declare the same variable twice + if (Q3_VariableDeclared(name) != VTYPE_NONE) return; - if ( numVariables > MAX_VARIABLES ) - { - Q3_DebugPrint( WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES ); + if (numVariables > MAX_VARIABLES) { + Q3_DebugPrint(WL_ERROR, "too many variables already declared, maximum is %d\n", MAX_VARIABLES); return; } - switch( type ) - { + switch (type) { case TK_FLOAT: - varFloats[ name ] = 0.0f; + varFloats[name] = 0.0f; break; case TK_STRING: - varStrings[ name ] = "NULL"; + varStrings[name] = "NULL"; break; case TK_VECTOR: - varVectors[ name ] = "0.0 0.0 0.0"; + varVectors[name] = "0.0 0.0 0.0"; break; default: - Q3_DebugPrint( WL_ERROR, "unknown 'type' for declare() function!\n" ); + Q3_DebugPrint(WL_ERROR, "unknown 'type' for declare() function!\n"); return; break; } @@ -107,34 +103,30 @@ Q3_FreeVariable ------------------------- */ -void Q3_FreeVariable( const char *name ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +void Q3_FreeVariable(const char *name) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) - { - varStrings.erase( vsi ); + if (vsi != varStrings.end()) { + varStrings.erase(vsi); numVariables--; return; } - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) - { - varFloats.erase( vfi ); + if (vfi != varFloats.end()) { + varFloats.erase(vfi); numVariables--; return; } - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) - { - varVectors.erase( vvi ); + if (vvi != varVectors.end()) { + varVectors.erase(vvi); numVariables--; return; } @@ -146,13 +138,11 @@ Q3_GetFloatVariable ------------------------- */ -int Q3_GetFloatVariable( const char *name, float *value ) -{ - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); +int Q3_GetFloatVariable(const char *name, float *value) { + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi != varFloats.end() ) - { + if (vfi != varFloats.end()) { *value = (*vfi).second; return true; } @@ -166,14 +156,12 @@ Q3_GetStringVariable ------------------------- */ -int Q3_GetStringVariable( const char *name, const char **value ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_GetStringVariable(const char *name, const char **value) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi != varStrings.end() ) - { - *value = (const char *) ((*vsi).second).c_str(); + if (vsi != varStrings.end()) { + *value = (const char *)((*vsi).second).c_str(); return true; } @@ -186,16 +174,14 @@ Q3_GetVectorVariable ------------------------- */ -int Q3_GetVectorVariable( const char *name, vec3_t value ) -{ - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); +int Q3_GetVectorVariable(const char *name, vec3_t value) { + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi != varVectors.end() ) - { + if (vvi != varVectors.end()) { const char *str = ((*vvi).second).c_str(); - sscanf( str, "%f %f %f", &value[0], &value[1], &value[2] ); + sscanf(str, "%f %f %f", &value[0], &value[1], &value[2]); return true; } @@ -208,14 +194,13 @@ Q3_InitVariables ------------------------- */ -void Q3_InitVariables( void ) -{ +void Q3_InitVariables(void) { varStrings.clear(); varFloats.clear(); varVectors.clear(); - if ( numVariables > 0 ) - Q3_DebugPrint( WL_WARNING, "%d residual variables found!\n", numVariables ); + if (numVariables > 0) + Q3_DebugPrint(WL_WARNING, "%d residual variables found!\n", numVariables); numVariables = 0; } @@ -226,12 +211,11 @@ Q3_SetVariable_Float ------------------------- */ -int Q3_SetFloatVariable( const char *name, float value ) -{ - //Check the floats - varFloat_m::iterator vfi = varFloats.find( name ); +int Q3_SetFloatVariable(const char *name, float value) { + // Check the floats + varFloat_m::iterator vfi = varFloats.find(name); - if ( vfi == varFloats.end() ) + if (vfi == varFloats.end()) return VTYPE_FLOAT; (*vfi).second = value; @@ -245,12 +229,11 @@ Q3_SetVariable_String ------------------------- */ -int Q3_SetStringVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vsi = varStrings.find( name ); +int Q3_SetStringVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vsi = varStrings.find(name); - if ( vsi == varStrings.end() ) + if (vsi == varStrings.end()) return false; (*vsi).second = value; @@ -264,12 +247,11 @@ Q3_SetVariable_Vector ------------------------- */ -int Q3_SetVectorVariable( const char *name, const char *value ) -{ - //Check the strings - varString_m::iterator vvi = varVectors.find( name ); +int Q3_SetVectorVariable(const char *name, const char *value) { + // Check the strings + varString_m::iterator vvi = varVectors.find(name); - if ( vvi == varVectors.end() ) + if (vvi == varVectors.end()) return false; (*vvi).second = value; @@ -283,8 +265,7 @@ Q3_VariableSaveFloats ------------------------- */ -void Q3_VariableSaveFloats( varFloat_m &fmap ) -{ +void Q3_VariableSaveFloats(varFloat_m &fmap) { return; /* int numFloats = fmap.size(); @@ -312,8 +293,7 @@ Q3_VariableSaveStrings ------------------------- */ -void Q3_VariableSaveStrings( varString_m &smap ) -{ +void Q3_VariableSaveStrings(varString_m &smap) { return; /* int numStrings = smap.size(); @@ -344,11 +324,10 @@ Q3_VariableSave ------------------------- */ -int Q3_VariableSave( void ) -{ - Q3_VariableSaveFloats( varFloats ); - Q3_VariableSaveStrings( varStrings ); - Q3_VariableSaveStrings( varVectors); +int Q3_VariableSave(void) { + Q3_VariableSaveFloats(varFloats); + Q3_VariableSaveStrings(varStrings); + Q3_VariableSaveStrings(varVectors); return qtrue; } @@ -359,8 +338,7 @@ Q3_VariableLoadFloats ------------------------- */ -void Q3_VariableLoadFloats( varFloat_m &fmap ) -{ +void Q3_VariableLoadFloats(varFloat_m &fmap) { return; /* int numFloats; @@ -392,8 +370,7 @@ Q3_VariableLoadStrings ------------------------- */ -void Q3_VariableLoadStrings( int type, varString_m &fmap ) -{ +void Q3_VariableLoadStrings(int type, varString_m &fmap) { return; /* int numFloats; @@ -436,13 +413,12 @@ Q3_VariableLoad ------------------------- */ -int Q3_VariableLoad( void ) -{ +int Q3_VariableLoad(void) { Q3_InitVariables(); - Q3_VariableLoadFloats( varFloats ); - Q3_VariableLoadStrings( TK_STRING, varStrings ); - Q3_VariableLoadStrings( TK_VECTOR, varVectors); + Q3_VariableLoadFloats(varFloats); + Q3_VariableLoadStrings(TK_STRING, varStrings); + Q3_VariableLoadStrings(TK_VECTOR, varVectors); return qfalse; } diff --git a/codemp/icarus/Sequence.cpp b/codemp/icarus/Sequence.cpp index 9f39c929bf..c121f851d5 100644 --- a/codemp/icarus/Sequence.cpp +++ b/codemp/icarus/Sequence.cpp @@ -29,37 +29,32 @@ along with this program; if not, see . #include -CSequence::CSequence( void ) -{ - m_numCommands = 0; - m_flags = 0; - m_iterations = 1; - - m_parent = NULL; - m_return = NULL; -} +CSequence::CSequence(void) { + m_numCommands = 0; + m_flags = 0; + m_iterations = 1; -CSequence::~CSequence( void ) -{ - Delete(); + m_parent = NULL; + m_return = NULL; } +CSequence::~CSequence(void) { Delete(); } + /* ------------------------- Create ------------------------- */ -CSequence *CSequence::Create( void ) -{ +CSequence *CSequence::Create(void) { CSequence *seq = new CSequence; - //TODO: Emit warning + // TODO: Emit warning assert(seq); - if ( seq == NULL ) + if (seq == NULL) return NULL; - seq->SetFlag( SQ_COMMON ); + seq->SetFlag(SQ_COMMON); return seq; } @@ -70,55 +65,48 @@ Delete ------------------------- */ -void CSequence::Delete( void ) -{ - block_l::iterator bi; +void CSequence::Delete(void) { + block_l::iterator bi; sequence_l::iterator si; - //Notify the parent of the deletion - if ( m_parent ) - { - m_parent->RemoveChild( this ); + // Notify the parent of the deletion + if (m_parent) { + m_parent->RemoveChild(this); } - //Clear all children - if ( m_children.size() > 0 ) - { + // Clear all children + if (m_children.size() > 0) { /*for ( iterSeq = m_childrenMap.begin(); iterSeq != m_childrenMap.end(); iterSeq++ ) { (*iterSeq).second->SetParent( NULL ); }*/ - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->SetParent( NULL ); + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->SetParent(NULL); } } m_children.clear(); - //Clear all held commands - for ( bi = m_commands.begin(); bi != m_commands.end(); ++bi ) - { - delete (*bi); //Free() handled internally + // Clear all held commands + for (bi = m_commands.begin(); bi != m_commands.end(); ++bi) { + delete (*bi); // Free() handled internally } m_commands.clear(); } - /* ------------------------- AddChild ------------------------- */ -void CSequence::AddChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::AddChild(CSequence *child) { + assert(child); + if (child == NULL) return; - m_children.insert( m_children.end(), child ); + m_children.insert(m_children.end(), child); } /* @@ -127,14 +115,13 @@ RemoveChild ------------------------- */ -void CSequence::RemoveChild( CSequence *child ) -{ - assert( child ); - if ( child == NULL ) +void CSequence::RemoveChild(CSequence *child) { + assert(child); + if (child == NULL) return; - //Remove the child - m_children.remove( child ); + // Remove the child + m_children.remove(child); } /* @@ -143,16 +130,14 @@ HasChild ------------------------- */ -bool CSequence::HasChild( CSequence *sequence ) -{ - sequence_l::iterator ci; +bool CSequence::HasChild(CSequence *sequence) { + sequence_l::iterator ci; - for ( ci = m_children.begin(); ci != m_children.end(); ++ci ) - { - if ( (*ci) == sequence ) + for (ci = m_children.begin(); ci != m_children.end(); ++ci) { + if ((*ci) == sequence) return true; - if ( (*ci)->HasChild( sequence ) ) + if ((*ci)->HasChild(sequence)) return true; } @@ -165,18 +150,17 @@ SetParent ------------------------- */ -void CSequence::SetParent( CSequence *parent ) -{ +void CSequence::SetParent(CSequence *parent) { m_parent = parent; - if ( parent == NULL ) + if (parent == NULL) return; - //Inherit the parent's properties (this avoids messy tree walks later on) - if ( parent->m_flags & SQ_RETAIN ) + // Inherit the parent's properties (this avoids messy tree walks later on) + if (parent->m_flags & SQ_RETAIN) m_flags |= SQ_RETAIN; - if ( parent->m_flags & SQ_PENDING ) + if (parent->m_flags & SQ_PENDING) m_flags |= SQ_PENDING; } @@ -186,18 +170,16 @@ PopCommand ------------------------- */ -CBlock *CSequence::PopCommand( int type ) -{ - CBlock *command = NULL; +CBlock *CSequence::PopCommand(int type) { + CBlock *command = NULL; - //Make sure everything is ok - assert( (type == POP_FRONT) || (type == POP_BACK) ); + // Make sure everything is ok + assert((type == POP_FRONT) || (type == POP_BACK)); - if ( m_commands.empty() ) + if (m_commands.empty()) return NULL; - switch ( type ) - { + switch (type) { case POP_FRONT: command = m_commands.front(); @@ -217,7 +199,7 @@ CBlock *CSequence::PopCommand( int type ) break; } - //Invalid flag + // Invalid flag return NULL; } @@ -227,17 +209,15 @@ PushCommand ------------------------- */ -int CSequence::PushCommand( CBlock *block, int type ) -{ - //Make sure everything is ok - assert( (type == PUSH_FRONT) || (type == PUSH_BACK) ); - assert( block ); +int CSequence::PushCommand(CBlock *block, int type) { + // Make sure everything is ok + assert((type == PUSH_FRONT) || (type == PUSH_BACK)); + assert(block); - switch ( type ) - { + switch (type) { case PUSH_FRONT: - m_commands.push_front( block ); + m_commands.push_front(block); m_numCommands++; return true; @@ -245,14 +225,14 @@ int CSequence::PushCommand( CBlock *block, int type ) case PUSH_BACK: - m_commands.push_back( block ); + m_commands.push_back(block); m_numCommands++; return true; break; } - //Invalid flag + // Invalid flag return false; } @@ -262,10 +242,7 @@ SetFlag ------------------------- */ -void CSequence::SetFlag( int flag ) -{ - m_flags |= flag; -} +void CSequence::SetFlag(int flag) { m_flags |= flag; } /* ------------------------- @@ -273,17 +250,14 @@ RemoveFlag ------------------------- */ -void CSequence::RemoveFlag( int flag, bool children ) -{ +void CSequence::RemoveFlag(int flag, bool children) { m_flags &= ~flag; - if ( children ) - { - sequence_l::iterator si; + if (children) { + sequence_l::iterator si; - for ( si = m_children.begin(); si != m_children.end(); ++si ) - { - (*si)->RemoveFlag( flag, true ); + for (si = m_children.begin(); si != m_children.end(); ++si) { + (*si)->RemoveFlag(flag, true); } } } @@ -294,10 +268,7 @@ HasFlag ------------------------- */ -int CSequence::HasFlag( int flag ) -{ - return (m_flags & flag); -} +int CSequence::HasFlag(int flag) { return (m_flags & flag); } /* ------------------------- @@ -305,9 +276,8 @@ SetReturn ------------------------- */ -void CSequence::SetReturn ( CSequence *sequence ) -{ - assert( sequence != this ); +void CSequence::SetReturn(CSequence *sequence) { + assert(sequence != this); m_return = sequence; } @@ -317,14 +287,12 @@ GetChild ------------------------- */ -CSequence *CSequence::GetChildByIndex( int iIndex ) -{ - if ( iIndex < 0 || iIndex >= (int)m_children.size() ) +CSequence *CSequence::GetChildByIndex(int iIndex) { + if (iIndex < 0 || iIndex >= (int)m_children.size()) return NULL; sequence_l::iterator iterSeq = m_children.begin(); - for ( int i = 0; i < iIndex; i++ ) - { + for (int i = 0; i < iIndex; i++) { ++iterSeq; } return (*iterSeq); @@ -336,38 +304,36 @@ SaveCommand ------------------------- */ -int CSequence::SaveCommand( CBlock *block ) -{ - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; +int CSequence::SaveCommand(CBlock *block) { + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','L','I','D'), &bID, sizeof ( bID ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'L', 'I', 'D'), &bID, sizeof(bID)); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','F','L','G'), &flags, sizeof ( flags ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'F', 'L', 'G'), &flags, sizeof(flags)); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','N','U','M'), &numMembers, sizeof ( numMembers ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'N', 'U', 'M'), &numMembers, sizeof(numMembers)); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','M','I','D'), &bID, sizeof ( bID ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'M', 'I', 'D'), &bID, sizeof(bID)); - //Save out the data size + // Save out the data size size = bm->GetSize(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','S','I','Z'), &size, sizeof( size ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'S', 'I', 'Z'), &size, sizeof(size)); - //Save out the raw data - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','M','E','M'), bm->GetData(), size ); + // Save out the raw data + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'M', 'E', 'M'), bm->GetData(), size); } return true; @@ -379,9 +345,8 @@ Save ------------------------- */ -int CSequence::Save( void ) -{ -#if 0 //piss off, stupid function +int CSequence::Save(void) { +#if 0 // piss off, stupid function sequence_l::iterator ci; block_l::iterator bi; int id; @@ -430,9 +395,8 @@ Load ------------------------- */ -int CSequence::Load( void ) -{ -#if 0 //piss off, stupid function +int CSequence::Load(void) { +#if 0 // piss off, stupid function unsigned char flags; CSequence *sequence; CBlock *block; diff --git a/codemp/icarus/Sequencer.cpp b/codemp/icarus/Sequencer.cpp index 6a21194b82..53dbf68c9a 100644 --- a/codemp/icarus/Sequencer.cpp +++ b/codemp/icarus/Sequencer.cpp @@ -32,12 +32,11 @@ along with this program; if not, see . // Sequencer -CSequencer::CSequencer( void ) -{ - m_numCommands = 0; +CSequencer::CSequencer(void) { + m_numCommands = 0; - m_curStream = NULL; - m_curSequence = NULL; + m_curStream = NULL; + m_curSequence = NULL; m_elseValid = 0; m_elseOwner = NULL; @@ -45,9 +44,8 @@ CSequencer::CSequencer( void ) m_curGroup = NULL; } -CSequencer::~CSequencer( void ) -{ - Free(); //Safe even if already freed +CSequencer::~CSequencer(void) { + Free(); // Safe even if already freed } /* @@ -58,8 +56,7 @@ Static creation function ======================== */ -CSequencer *CSequencer::Create ( void ) -{ +CSequencer *CSequencer::Create(void) { CSequencer *sequencer = new CSequencer; return sequencer; @@ -72,12 +69,11 @@ Init Initializes the sequencer ======================== */ -int CSequencer::Init( int ownerID, interface_export_t *ie, CTaskManager *taskManager, ICARUS_Instance *iICARUS ) -{ - m_ownerID = ownerID; - m_owner = iICARUS; - m_taskManager = taskManager; - m_ie = ie; +int CSequencer::Init(int ownerID, interface_export_t *ie, CTaskManager *taskManager, ICARUS_Instance *iICARUS) { + m_ownerID = ownerID; + m_owner = iICARUS; + m_taskManager = taskManager; + m_ie = ie; return SEQ_OK; } @@ -89,26 +85,23 @@ Free Releases all resources and re-inits the sequencer ======================== */ -int CSequencer::Free( void ) -{ - sequence_l::iterator sli; +int CSequencer::Free(void) { + sequence_l::iterator sli; - //Flush the sequences - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ++sli ) - { - m_owner->DeleteSequence( (*sli) ); + // Flush the sequences + for (sli = m_sequences.begin(); sli != m_sequences.end(); ++sli) { + m_owner->DeleteSequence((*sli)); } m_sequences.clear(); m_taskSequences.clear(); - //Clean up any other info + // Clean up any other info m_numCommands = 0; m_curSequence = NULL; bstream_t *streamToDel; - while(!m_streamsCreated.empty()) - { + while (!m_streamsCreated.empty()) { streamToDel = m_streamsCreated.back(); DeleteStream(streamToDel); } @@ -122,35 +115,32 @@ Flush ------------------------- */ -int CSequencer::Flush( CSequence *owner ) -{ - if ( owner == NULL ) +int CSequencer::Flush(CSequence *owner) { + if (owner == NULL) return SEQ_FAILED; Recall(); - sequence_l::iterator sli; + sequence_l::iterator sli; - //Flush the sequences - for ( sli = m_sequences.begin(); sli != m_sequences.end(); ) - { - if ( ( (*sli) == owner ) || ( owner->HasChild( (*sli) ) ) || ( (*sli)->HasFlag( SQ_PENDING ) ) || ( (*sli)->HasFlag( SQ_TASK ) ) ) - { + // Flush the sequences + for (sli = m_sequences.begin(); sli != m_sequences.end();) { + if (((*sli) == owner) || (owner->HasChild((*sli))) || ((*sli)->HasFlag(SQ_PENDING)) || ((*sli)->HasFlag(SQ_TASK))) { ++sli; continue; } - //Delete it, and remove all references - RemoveSequence( (*sli) ); - m_owner->DeleteSequence( (*sli) ); + // Delete it, and remove all references + RemoveSequence((*sli)); + m_owner->DeleteSequence((*sli)); - //Delete from the sequence list and move on - sli = m_sequences.erase( sli ); + // Delete from the sequence list and move on + sli = m_sequences.erase(sli); } - //Make sure this owner knows it's now the root sequence - owner->SetParent( NULL ); - owner->SetReturn( NULL ); + // Make sure this owner knows it's now the root sequence + owner->SetParent(NULL); + owner->SetReturn(NULL); return SEQ_OK; } @@ -163,12 +153,11 @@ Creates a stream for parsing ======================== */ -bstream_t *CSequencer::AddStream( void ) -{ - bstream_t *stream; +bstream_t *CSequencer::AddStream(void) { + bstream_t *stream; - stream = new bstream_t; //deleted in Route() - stream->stream = new CBlockStream; //deleted in Route() + stream = new bstream_t; // deleted in Route() + stream->stream = new CBlockStream; // deleted in Route() stream->last = m_curStream; m_streamsCreated.push_back(stream); @@ -183,11 +172,9 @@ DeleteStream Deletes parsing stream ======================== */ -void CSequencer::DeleteStream( bstream_t *bstream ) -{ - std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); - if(finder != m_streamsCreated.end()) - { +void CSequencer::DeleteStream(bstream_t *bstream) { + std::vector::iterator finder = std::find(m_streamsCreated.begin(), m_streamsCreated.end(), bstream); + if (finder != m_streamsCreated.end()) { m_streamsCreated.erase(finder); } @@ -205,10 +192,7 @@ AddTaskSequence ------------------------- */ -void CSequencer::AddTaskSequence( CSequence *sequence, CTaskGroup *group ) -{ - m_taskSequences[ group ] = sequence; -} +void CSequencer::AddTaskSequence(CSequence *sequence, CTaskGroup *group) { m_taskSequences[group] = sequence; } /* ------------------------- @@ -216,13 +200,12 @@ GetTaskSequence ------------------------- */ -CSequence *CSequencer::GetTaskSequence( CTaskGroup *group ) -{ - taskSequence_m::iterator tsi; +CSequence *CSequencer::GetTaskSequence(CTaskGroup *group) { + taskSequence_m::iterator tsi; - tsi = m_taskSequences.find( group ); + tsi = m_taskSequences.find(group); - if ( tsi == m_taskSequences.end() ) + if (tsi == m_taskSequences.end()) return NULL; return (*tsi).second; @@ -236,37 +219,35 @@ Creates and adds a sequence to the sequencer ======================== */ -CSequence *CSequencer::AddSequence( void ) -{ - CSequence *sequence = m_owner->GetSequence(); +CSequence *CSequencer::AddSequence(void) { + CSequence *sequence = m_owner->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); - //FIXME: Temp fix - sequence->SetFlag( SQ_PENDING ); + // FIXME: Temp fix + sequence->SetFlag(SQ_PENDING); return sequence; } -CSequence *CSequencer::AddSequence( CSequence *parent, CSequence *returnSeq, int flags ) -{ - CSequence *sequence = m_owner->GetSequence(); +CSequence *CSequencer::AddSequence(CSequence *parent, CSequence *returnSeq, int flags) { + CSequence *sequence = m_owner->GetSequence(); - assert( sequence ); - if ( sequence == NULL ) + assert(sequence); + if (sequence == NULL) return NULL; - //Add it to the list - m_sequences.insert( m_sequences.end(), sequence ); + // Add it to the list + m_sequences.insert(m_sequences.end(), sequence); - sequence->SetFlags( flags ); - sequence->SetParent( parent ); - sequence->SetReturn( returnSeq ); + sequence->SetFlags(flags); + sequence->SetParent(parent); + sequence->SetReturn(returnSeq); return sequence; } @@ -279,21 +260,19 @@ Retrieves a sequence by its ID ======================== */ -CSequence *CSequencer::GetSequence( int id ) -{ -/* sequenceID_m::iterator mi; +CSequence *CSequencer::GetSequence(int id) { + /* sequenceID_m::iterator mi; - mi = m_sequenceMap.find( id ); + mi = m_sequenceMap.find( id ); - if ( mi == m_sequenceMap.end() ) - return NULL; + if ( mi == m_sequenceMap.end() ) + return NULL; - return (*mi).second;*/ + return (*mi).second;*/ sequence_l::iterator iterSeq; - STL_ITERATE( iterSeq, m_sequences ) - { - if ( (*iterSeq)->GetID() == id ) + STL_ITERATE(iterSeq, m_sequences) { + if ((*iterSeq)->GetID() == id) return (*iterSeq); } @@ -306,15 +285,14 @@ Interrupt ------------------------- */ -void CSequencer::Interrupt( void ) -{ - CBlock *command = m_taskManager->GetCurrentTask(); +void CSequencer::Interrupt(void) { + CBlock *command = m_taskManager->GetCurrentTask(); - if ( command == NULL ) + if (command == NULL) return; - //Save it - PushCommand( command, PUSH_BACK ); + // Save it + PushCommand(command, PUSH_BACK); } /* @@ -324,28 +302,25 @@ Run Runs a script ======================== */ -int CSequencer::Run( char *buffer, long size ) -{ - bstream_t *blockStream; +int CSequencer::Run(char *buffer, long size) { + bstream_t *blockStream; Recall(); - //Create a new stream + // Create a new stream blockStream = AddStream(); - //Open the stream as an IBI stream - if (!blockStream->stream->Open( buffer, size )) - { - m_ie->I_DPrintf( WL_ERROR, "invalid stream" ); + // Open the stream as an IBI stream + if (!blockStream->stream->Open(buffer, size)) { + m_ie->I_DPrintf(WL_ERROR, "invalid stream"); return SEQ_FAILED; } - CSequence *sequence = AddSequence( NULL, m_curSequence, SQ_COMMON ); + CSequence *sequence = AddSequence(NULL, m_curSequence, SQ_COMMON); // Interpret the command blocks and route them properly - if ( S_FAILED( Route( sequence, blockStream )) ) - { - //Error code is set inside of Route() + if (S_FAILED(Route(sequence, blockStream))) { + // Error code is set inside of Route() return SEQ_FAILED; } @@ -360,49 +335,45 @@ Parses a user triggered run command ======================== */ -int CSequencer::ParseRun( CBlock *block ) -{ - CSequence *new_sequence; - bstream_t *new_stream; - char *buffer; - char newname[ MAX_STRING_SIZE ]; - int buffer_size; +int CSequencer::ParseRun(CBlock *block) { + CSequence *new_sequence; + bstream_t *new_stream; + char *buffer; + char newname[MAX_STRING_SIZE]; + int buffer_size; - //Get the name and format it - COM_StripExtension( (char*) block->GetMemberData( 0 ), (char *) newname, sizeof(newname) ); + // Get the name and format it + COM_StripExtension((char *)block->GetMemberData(0), (char *)newname, sizeof(newname)); - //Get the file from the game engine - buffer_size = m_ie->I_LoadFile( newname, (void **) &buffer ); + // Get the file from the game engine + buffer_size = m_ie->I_LoadFile(newname, (void **)&buffer); - if ( buffer_size <= 0 ) - { - m_ie->I_DPrintf( WL_ERROR, "'%s' : could not open file\n", (char*) block->GetMemberData( 0 )); + if (buffer_size <= 0) { + m_ie->I_DPrintf(WL_ERROR, "'%s' : could not open file\n", (char *)block->GetMemberData(0)); delete block; block = NULL; return SEQ_FAILED; } - //Create a new stream for this file + // Create a new stream for this file new_stream = AddStream(); - //Begin streaming the file - if (!new_stream->stream->Open( buffer, buffer_size )) - { - m_ie->I_DPrintf( WL_ERROR, "invalid stream" ); + // Begin streaming the file + if (!new_stream->stream->Open(buffer, buffer_size)) { + m_ie->I_DPrintf(WL_ERROR, "invalid stream"); delete block; block = NULL; return SEQ_FAILED; } - //Create a new sequence - new_sequence = AddSequence( m_curSequence, m_curSequence, ( SQ_RUN | SQ_PENDING ) ); + // Create a new sequence + new_sequence = AddSequence(m_curSequence, m_curSequence, (SQ_RUN | SQ_PENDING)); - m_curSequence->AddChild( new_sequence ); + m_curSequence->AddChild(new_sequence); // Interpret the command blocks and route them properly - if ( S_FAILED( Route( new_sequence, new_stream )) ) - { - //Error code is set inside of Route() + if (S_FAILED(Route(new_sequence, new_stream))) { + // Error code is set inside of Route() delete block; block = NULL; return SEQ_FAILED; @@ -410,10 +381,10 @@ int CSequencer::ParseRun( CBlock *block ) m_curSequence = m_curSequence->GetReturn(); - assert( m_curSequence ); + assert(m_curSequence); - block->Write( TK_FLOAT, (float) new_sequence->GetID() ); - PushCommand( block, PUSH_FRONT ); + block->Write(TK_FLOAT, (float)new_sequence->GetID()); + PushCommand(block, PUSH_FRONT); return SEQ_OK; } @@ -426,32 +397,30 @@ Parses an if statement ======================== */ -int CSequencer::ParseIf( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; +int CSequencer::ParseIf(CBlock *block, bstream_t *bstream) { + CSequence *sequence; - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_CONDITIONAL ); + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_CONDITIONAL); - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseIf: failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseIf: failed to allocate container sequence"); delete block; block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Add a unique conditional identifier to the block for reference later - block->Write( TK_FLOAT, (float) sequence->GetID() ); + // Add a unique conditional identifier to the block for reference later + block->Write(TK_FLOAT, (float)sequence->GetID()); - //Push this onto the stack to mark the conditional entrance - PushCommand( block, PUSH_FRONT ); + // Push this onto the stack to mark the conditional entrance + PushCommand(block, PUSH_FRONT); - //Recursively obtain the conditional body - Route( sequence, bstream ); + // Recursively obtain the conditional body + Route(sequence, bstream); m_elseValid = 2; m_elseOwner = block; @@ -467,40 +436,37 @@ Parses an else statement ======================== */ -int CSequencer::ParseElse( CBlock *block, bstream_t *bstream ) -{ - //The else is not retained +int CSequencer::ParseElse(CBlock *block, bstream_t *bstream) { + // The else is not retained delete block; block = NULL; - CSequence *sequence; + CSequence *sequence; - //Create the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_CONDITIONAL ); + // Create the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_CONDITIONAL); - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseIf: failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseIf: failed to allocate container sequence"); return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Add a unique conditional identifier to the block for reference later - //TODO: Emit warning - if ( m_elseOwner == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Invalid 'else' found!\n" ); + // Add a unique conditional identifier to the block for reference later + // TODO: Emit warning + if (m_elseOwner == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - m_elseOwner->Write( TK_FLOAT, (float) sequence->GetID() ); + m_elseOwner->Write(TK_FLOAT, (float)sequence->GetID()); - m_elseOwner->SetFlag( BF_ELSE ); + m_elseOwner->SetFlag(BF_ELSE); - //Recursively obtain the conditional body - Route( sequence, bstream ); + // Recursively obtain the conditional body + Route(sequence, bstream); m_elseValid = 0; m_elseOwner = NULL; @@ -516,54 +482,49 @@ Parses a loop command ======================== */ -int CSequencer::ParseLoop( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; - CBlockMember *bm; - float min, max; - int rIter; - int memberNum = 0; +int CSequencer::ParseLoop(CBlock *block, bstream_t *bstream) { + CSequence *sequence; + CBlockMember *bm; + float min, max; + int rIter; + int memberNum = 0; - //Set the parent - sequence = AddSequence( m_curSequence, m_curSequence, ( SQ_LOOP | SQ_RETAIN ) ); + // Set the parent + sequence = AddSequence(m_curSequence, m_curSequence, (SQ_LOOP | SQ_RETAIN)); - assert( sequence ); - if ( sequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "ParseLoop : failed to allocate container sequence" ); + assert(sequence); + if (sequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "ParseLoop : failed to allocate container sequence"); delete block; block = NULL; return SEQ_FAILED; } - m_curSequence->AddChild( sequence ); + m_curSequence->AddChild(sequence); - //Set the number of iterations of this sequence + // Set the number of iterations of this sequence - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); - if ( bm->GetID() == ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + if (bm->GetID() == ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - rIter = (int) m_ie->I_Random( min, max ); - sequence->SetIterations( rIter ); - } - else - { - sequence->SetIterations ( (int) (*(float *) bm->GetData()) ); + rIter = (int)m_ie->I_Random(min, max); + sequence->SetIterations(rIter); + } else { + sequence->SetIterations((int)(*(float *)bm->GetData())); } - //Add a unique loop identifier to the block for reference later - block->Write( TK_FLOAT, (float) sequence->GetID() ); + // Add a unique loop identifier to the block for reference later + block->Write(TK_FLOAT, (float)sequence->GetID()); - //Push this onto the stack to mark the loop entrance - PushCommand( block, PUSH_FRONT ); + // Push this onto the stack to mark the loop entrance + PushCommand(block, PUSH_FRONT); - //Recursively obtain the loop - Route( sequence, bstream ); + // Recursively obtain the loop + Route(sequence, bstream); return SEQ_OK; } @@ -576,31 +537,29 @@ Adds a sequence that is saved until the affect is called by the parent ======================== */ -int CSequencer::AddAffect( bstream_t *bstream, int retain, int *id ) -{ - CSequence *sequence = AddSequence(); - bstream_t new_stream; +int CSequencer::AddAffect(bstream_t *bstream, int retain, int *id) { + CSequence *sequence = AddSequence(); + bstream_t new_stream; - sequence->SetFlag( SQ_AFFECT | SQ_PENDING ); + sequence->SetFlag(SQ_AFFECT | SQ_PENDING); - if ( retain ) - sequence->SetFlag( SQ_RETAIN ); + if (retain) + sequence->SetFlag(SQ_RETAIN); - //This will be replaced once it's actually used, but this will restore the route state properly - sequence->SetReturn( m_curSequence ); + // This will be replaced once it's actually used, but this will restore the route state properly + sequence->SetReturn(m_curSequence); - //We need this as a temp holder + // We need this as a temp holder new_stream.last = m_curStream; new_stream.stream = bstream->stream; - if S_FAILED( Route( sequence, &new_stream ) ) - { + if S_FAILED (Route(sequence, &new_stream)) { return SEQ_FAILED; } *id = sequence->GetID(); - sequence->SetReturn( NULL ); + sequence->SetReturn(NULL); return SEQ_OK; } @@ -613,126 +572,117 @@ Parses an affect command ======================== */ -int CSequencer::ParseAffect( CBlock *block, bstream_t *bstream ) -{ - CSequencer *stream_sequencer = NULL; - char *entname = NULL; - int ret; - sharedEntity_t *ent = 0; +int CSequencer::ParseAffect(CBlock *block, bstream_t *bstream) { + CSequencer *stream_sequencer = NULL; + char *entname = NULL; + int ret; + sharedEntity_t *ent = 0; - entname = (char*) block->GetMemberData( 0 ); - ent = m_ie->I_GetEntityByName( entname ); + entname = (char *)block->GetMemberData(0); + ent = m_ie->I_GetEntityByName(entname); - if( !ent ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (!ent) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' + // try to parse a 'get' command that is embeded in this 'affect' - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - switch ( id ) - { - // these 3 cases probably aren't necessary - case TK_STRING: - case TK_IDENTIFIER: - case TK_CHAR: - p1 = (char *) bm->GetData(); + switch (id) { + // these 3 cases probably aren't necessary + case TK_STRING: + case TK_IDENTIFIER: + case TK_CHAR: + p1 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; + case ID_GET: { + int type; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( 1 )); - name = (char *) block->GetMemberData( 2 ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(1)); + name = (char *)block->GetMemberData(2); - switch ( type ) // what type are they attempting to get - { + switch (type) // what type are they attempting to get + { - case TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - { - delete block; - block = NULL; - return false; - } - break; - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _1" ); - delete block; - block = NULL; - return false; - break; + case TK_STRING: + // only string is acceptable for affect, store result in p1 + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) { + delete block; + block = NULL; + return false; } - break; - } - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _1"); delete block; block = NULL; return false; break; - }//end id switch + } - if(p1) - { - ent = m_ie->I_GetEntityByName( p1 ); + break; } - if(!ent) - { // a valid entity name was not returned from the get command - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n"); + + default: + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _2"); + delete block; + block = NULL; + return false; + break; + } // end id switch + + if (p1) { + ent = m_ie->I_GetEntityByName(p1); + } + if (!ent) { // a valid entity name was not returned from the get command + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n"); } } // end if(!ent) - if( ent ) - { - stream_sequencer = gSequencers[ent->s.number];//ent->sequencer; + if (ent) { + stream_sequencer = gSequencers[ent->s.number]; // ent->sequencer; } - if (stream_sequencer == NULL) - { - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n", entname ); + if (stream_sequencer == NULL) { + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n", entname); - //Fast-forward out of this affect block onto the next valid code + // Fast-forward out of this affect block onto the next valid code CSequence *backSeq = m_curSequence; CSequence *trashSeq = m_owner->GetSequence(); - Route( trashSeq, bstream ); + Route(trashSeq, bstream); Recall(); - DestroySequence( trashSeq ); + DestroySequence(trashSeq); m_curSequence = backSeq; delete block; block = NULL; return SEQ_OK; } - if S_FAILED ( stream_sequencer->AddAffect( bstream, (int) m_curSequence->HasFlag( SQ_RETAIN ), &ret ) ) - { + if S_FAILED (stream_sequencer->AddAffect(bstream, (int)m_curSequence->HasFlag(SQ_RETAIN), &ret)) { delete block; block = NULL; return SEQ_FAILED; } - //Hold onto the id for later use - //FIXME: If the target sequence is freed, what then? (!suspect!) + // Hold onto the id for later use + // FIXME: If the target sequence is freed, what then? (!suspect!) - block->Write( TK_FLOAT, (float) ret ); + block->Write(TK_FLOAT, (float)ret); - PushCommand( block, PUSH_FRONT ); + PushCommand(block, PUSH_FRONT); /* //Don't actually do these right now, we're just pre-processing (parsing) the affect if( ent ) @@ -750,43 +700,41 @@ ParseTask ------------------------- */ -int CSequencer::ParseTask( CBlock *block, bstream_t *bstream ) -{ - CSequence *sequence; - CTaskGroup *group; - const char *taskName; +int CSequencer::ParseTask(CBlock *block, bstream_t *bstream) { + CSequence *sequence; + CTaskGroup *group; + const char *taskName; - //Setup the container sequence - sequence = AddSequence( m_curSequence, m_curSequence, SQ_TASK | SQ_RETAIN ); - m_curSequence->AddChild( sequence ); + // Setup the container sequence + sequence = AddSequence(m_curSequence, m_curSequence, SQ_TASK | SQ_RETAIN); + m_curSequence->AddChild(sequence); - //Get the name of this task for reference later - taskName = (const char *) block->GetMemberData( 0 ); + // Get the name of this task for reference later + taskName = (const char *)block->GetMemberData(0); - //Get a new task group from the task manager - group = m_taskManager->AddTaskGroup( taskName ); + // Get a new task group from the task manager + group = m_taskManager->AddTaskGroup(taskName); - if ( group == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "error : unable to allocate a new task group" ); + if (group == NULL) { + m_ie->I_DPrintf(WL_ERROR, "error : unable to allocate a new task group"); delete block; block = NULL; return SEQ_FAILED; } - //The current group is set to this group, all subsequent commands (until a block end) will fall into this task group - group->SetParent( m_curGroup ); + // The current group is set to this group, all subsequent commands (until a block end) will fall into this task group + group->SetParent(m_curGroup); m_curGroup = group; - //Keep an association between this task and the container sequence - AddTaskSequence( sequence, group ); + // Keep an association between this task and the container sequence + AddTaskSequence(sequence, group); - //PushCommand( block, PUSH_FRONT ); + // PushCommand( block, PUSH_FRONT ); delete block; block = NULL; - //Recursively obtain the loop - Route( sequence, bstream ); + // Recursively obtain the loop + Route(sequence, bstream); return SEQ_OK; } @@ -799,48 +747,43 @@ Properly handles and routes commands to the sequencer ======================== */ -//FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently +// FIXME: Re-entering this code will produce unpredictable results if a script has already been routed and is running currently -//FIXME: A sequencer cannot properly affect itself +// FIXME: A sequencer cannot properly affect itself -int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) -{ - CBlockStream *stream; - CBlock *block; +int CSequencer::Route(CSequence *sequence, bstream_t *bstream) { + CBlockStream *stream; + CBlock *block; - //Take the stream as the current stream + // Take the stream as the current stream m_curStream = bstream; stream = bstream->stream; m_curSequence = sequence; - //Obtain all blocks - while ( stream->BlockAvailable() ) - { - block = new CBlock; //deleted in Free() - stream->ReadBlock( block ); + // Obtain all blocks + while (stream->BlockAvailable()) { + block = new CBlock; // deleted in Free() + stream->ReadBlock(block); - //TEMP: HACK! - if ( m_elseValid ) + // TEMP: HACK! + if (m_elseValid) m_elseValid--; - switch( block->GetBlockID() ) - { - //Marks the end of a blocked section + switch (block->GetBlockID()) { + // Marks the end of a blocked section case ID_BLOCK_END: - //Save this as a pre-process marker - PushCommand( block, PUSH_FRONT ); + // Save this as a pre-process marker + PushCommand(block, PUSH_FRONT); - if ( m_curSequence->HasFlag( SQ_RUN ) || m_curSequence->HasFlag( SQ_AFFECT ) ) - { - //Go back to the last stream + if (m_curSequence->HasFlag(SQ_RUN) || m_curSequence->HasFlag(SQ_AFFECT)) { + // Go back to the last stream m_curStream = bstream->last; } - if ( m_curSequence->HasFlag( SQ_TASK ) ) - { - //Go back to the last stream + if (m_curSequence->HasFlag(SQ_TASK)) { + // Go back to the last stream m_curStream = bstream->last; m_curGroup = m_curGroup->GetParent(); } @@ -850,60 +793,59 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) return SEQ_OK; break; - //Affect pre-processor + // Affect pre-processor case ID_AFFECT: - if S_FAILED( ParseAffect( block, bstream ) ) + if S_FAILED (ParseAffect(block, bstream)) return SEQ_FAILED; break; - //Run pre-processor + // Run pre-processor case ID_RUN: - if S_FAILED( ParseRun( block ) ) + if S_FAILED (ParseRun(block)) return SEQ_FAILED; break; - //Loop pre-processor + // Loop pre-processor case ID_LOOP: - if S_FAILED( ParseLoop( block, bstream ) ) + if S_FAILED (ParseLoop(block, bstream)) return SEQ_FAILED; break; - //Conditional pre-processor + // Conditional pre-processor case ID_IF: - if S_FAILED( ParseIf( block, bstream ) ) + if S_FAILED (ParseIf(block, bstream)) return SEQ_FAILED; break; case ID_ELSE: - //TODO: Emit warning - if ( m_elseValid == 0 ) - { - m_ie->I_DPrintf( WL_ERROR, "Invalid 'else' found!\n" ); + // TODO: Emit warning + if (m_elseValid == 0) { + m_ie->I_DPrintf(WL_ERROR, "Invalid 'else' found!\n"); return SEQ_FAILED; } - if S_FAILED( ParseElse( block, bstream ) ) + if S_FAILED (ParseElse(block, bstream)) return SEQ_FAILED; break; case ID_TASK: - if S_FAILED( ParseTask( block, bstream ) ) + if S_FAILED (ParseTask(block, bstream)) return SEQ_FAILED; break; - //FIXME: For now this is to catch problems, but can ultimately be removed + // FIXME: For now this is to catch problems, but can ultimately be removed case ID_WAIT: case ID_PRINT: case ID_SOUND: @@ -922,26 +864,25 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) case ID_WAITSIGNAL: case ID_PLAY: - //Commands go directly into the sequence without pre-process - PushCommand( block, PUSH_FRONT ); + // Commands go directly into the sequence without pre-process + PushCommand(block, PUSH_FRONT); break; - //Error + // Error default: - m_ie->I_DPrintf( WL_ERROR, "'%d' : invalid block ID", block->GetBlockID() ); + m_ie->I_DPrintf(WL_ERROR, "'%d' : invalid block ID", block->GetBlockID()); return SEQ_FAILED; break; } } - //Check for a run sequence, it must be marked - if ( m_curSequence->HasFlag( SQ_RUN ) ) - { + // Check for a run sequence, it must be marked + if (m_curSequence->HasFlag(SQ_RUN)) { block = new CBlock; - block->Create( ID_BLOCK_END ); - PushCommand( block, PUSH_FRONT ); //mark the end of the run + block->Create(ID_BLOCK_END); + PushCommand(block, PUSH_FRONT); // mark the end of the run /* //Free the stream @@ -952,17 +893,16 @@ int CSequencer::Route( CSequence *sequence, bstream_t *bstream ) return SEQ_OK; } - //Check to start the communication - if ( ( bstream->last == NULL ) && ( m_numCommands > 0 ) ) - { - //Everything is routed, so get it all rolling - Prime( m_taskManager, PopCommand( POP_BACK ) ); + // Check to start the communication + if ((bstream->last == NULL) && (m_numCommands > 0)) { + // Everything is routed, so get it all rolling + Prime(m_taskManager, PopCommand(POP_BACK)); } m_curStream = bstream->last; - //Free the stream - DeleteStream( bstream ); + // Free the stream + DeleteStream(bstream); return SEQ_OK; } @@ -975,81 +915,69 @@ Checks for run command pre-processing ======================== */ -//Directly changes the parameter to avoid excess push/pop +// Directly changes the parameter to avoid excess push/pop -void CSequencer::CheckRun( CBlock **command ) -{ - CBlock *block = *command; +void CSequencer::CheckRun(CBlock **command) { + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - //Check for a run command - if ( block->GetBlockID() == ID_RUN ) - { - int id = (int) (*(float *) block->GetMemberData( 1 )); + // Check for a run command + if (block->GetBlockID() == ID_RUN) { + int id = (int)(*(float *)block->GetMemberData(1)); - m_ie->I_DPrintf( WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *) block->GetMemberData(0), m_ie->I_GetTime() ); + m_ie->I_DPrintf(WL_DEBUG, "%4d run( \"%s\" ); [%d]", m_ownerID, (char *)block->GetMemberData(0), m_ie->I_GetTime()); - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_curSequence = GetSequence( id ); + m_curSequence = GetSequence(id); - //TODO: Emit warning - assert( m_curSequence ); - if ( m_curSequence == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find 'run' sequence!\n" ); + // TODO: Emit warning + assert(m_curSequence); + if (m_curSequence == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find 'run' sequence!\n"); *command = NULL; return; } - if ( m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( POP_BACK ); + if (m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(POP_BACK); - Prep( command ); //Account for any other pre-processes + Prep(command); // Account for any other pre-processes return; } return; } - //Check for the end of a run - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_RUN ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check for the end of a run + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_RUN))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_curSequence = ReturnSequence( m_curSequence ); + m_curSequence = ReturnSequence(m_curSequence); - if ( m_curSequence && m_curSequence->GetNumCommands() > 0 ) - { - *command = PopCommand( POP_BACK ); + if (m_curSequence && m_curSequence->GetNumCommands() > 0) { + *command = PopCommand(POP_BACK); - Prep( command ); //Account for any other pre-processes + Prep(command); // Account for any other pre-processes return; } - //FIXME: Check this... + // FIXME: Check this... } } @@ -1059,45 +987,42 @@ EvaluateConditional ------------------------- */ -//FIXME: This function will be written better later once the functionality of the ideas here are tested +// FIXME: This function will be written better later once the functionality of the ideas here are tested -int CSequencer::EvaluateConditional( CBlock *block ) -{ - CBlockMember *bm; - char tempString1[128], tempString2[128]; - vector_t vec; - int id, i, oper, memberNum = 0; - char *p1 = NULL, *p2 = NULL; - int t1, t2; +int CSequencer::EvaluateConditional(CBlock *block) { + CBlockMember *bm; + char tempString1[128], tempString2[128]; + vector_t vec; + int id, i, oper, memberNum = 0; + char *p1 = NULL, *p2 = NULL; + int t1, t2; // // Get the first parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t1 = id; - switch ( id ) - { + switch (id) { case TK_FLOAT: - Com_sprintf( tempString1, sizeof(tempString1), "%.3f", *(float *) bm->GetData() ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", *(float *)bm->GetData()); + p1 = (char *)tempString1; break; case TK_VECTOR: tempString1[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - Com_sprintf( tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; break; @@ -1105,115 +1030,106 @@ int CSequencer::EvaluateConditional( CBlock *block ) case TK_IDENTIFIER: case TK_CHAR: - p1 = (char *) bm->GetData(); + p1 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; - char *name; + case ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t1 = type; + // Get the type returned and hold onto it + t1 = type; - switch ( type ) - { - case TK_FLOAT: - { - float fVal; + switch (type) { + case TK_FLOAT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString1, sizeof(tempString1), "%.3f", fVal ); - p1 = (char *) tempString1; - } + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", fVal); + p1 = (char *)tempString1; + } - break; + break; - case TK_INT: - { - float fVal; + case TK_INT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString1, sizeof(tempString1), "%d", (int) fVal ); - p1 = (char *) tempString1; - } - break; + Com_sprintf(tempString1, sizeof(tempString1), "%d", (int)fVal); + p1 = (char *)tempString1; + } break; - case TK_STRING: + case TK_STRING: - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - return false; + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) + return false; - break; + break; - case TK_VECTOR: - { - vector_t vVal; + case TK_VECTOR: { + vector_t vVal; - if ( m_ie->I_GetVector( m_ownerID, type, name, vVal ) == false) - return false; + if (m_ie->I_GetVector(m_ownerID, type, name, vVal) == false) + return false; - Com_sprintf( tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p1 = (char *) tempString1; - } + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p1 = (char *)tempString1; + } - break; + break; } break; } - case ID_RANDOM: - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements + case ID_RANDOM: { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - //A float value is returned from the function - t1 = TK_FLOAT; + // A float value is returned from the function + t1 = TK_FLOAT; - Com_sprintf( tempString1, sizeof(tempString1), "%.3f", m_ie->I_Random( min, max ) ); - p1 = (char *) tempString1; - } + Com_sprintf(tempString1, sizeof(tempString1), "%.3f", m_ie->I_Random(min, max)); + p1 = (char *)tempString1; + } - break; + break; - case ID_TAG: - { - char *name; - float type; + case ID_TAG: { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t1 = TK_VECTOR; + t1 = TK_VECTOR; - //TODO: Emit warning - if ( m_ie->I_GetTag( m_ownerID, name, (int) type, vec ) == false) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (m_ie->I_GetTag(m_ownerID, name, (int)type, vec) == false) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - Com_sprintf( tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p1 = (char *) tempString1; + Com_sprintf(tempString1, sizeof(tempString1), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p1 = (char *)tempString1; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on conditional"); return false; break; } @@ -1222,11 +1138,10 @@ int CSequencer::EvaluateConditional( CBlock *block ) // Get the comparison operator // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); - switch ( id ) - { + switch (id) { case TK_EQUALS: case TK_GREATER_THAN: case TK_LESS_THAN: @@ -1235,8 +1150,8 @@ int CSequencer::EvaluateConditional( CBlock *block ) break; default: - m_ie->I_DPrintf( WL_ERROR, "Invalid operator type found on conditional!\n" ); - return false; //FIXME: Emit warning + m_ie->I_DPrintf(WL_ERROR, "Invalid operator type found on conditional!\n"); + return false; // FIXME: Emit warning break; } @@ -1244,30 +1159,28 @@ int CSequencer::EvaluateConditional( CBlock *block ) // Get the second parameter // - bm = block->GetMember( memberNum++ ); + bm = block->GetMember(memberNum++); id = bm->GetID(); t2 = id; - switch ( id ) - { + switch (id) { case TK_FLOAT: - Com_sprintf( tempString2, sizeof(tempString2), "%.3f", *(float *) bm->GetData() ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", *(float *)bm->GetData()); + p2 = (char *)tempString2; break; case TK_VECTOR: tempString2[0] = '\0'; - for ( i = 0; i < 3; i++ ) - { - bm = block->GetMember( memberNum++ ); - vec[i] = *(float *) bm->GetData(); + for (i = 0; i < 3; i++) { + bm = block->GetMember(memberNum++); + vec[i] = *(float *)bm->GetData(); } - Com_sprintf( tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; break; @@ -1275,67 +1188,61 @@ int CSequencer::EvaluateConditional( CBlock *block ) case TK_IDENTIFIER: case TK_CHAR: - p2 = (char *) bm->GetData(); + p2 = (char *)bm->GetData(); break; - case ID_GET: - { - int type; - char *name; + case ID_GET: { + int type; + char *name; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Get the type returned and hold onto it - t2 = type; + // Get the type returned and hold onto it + t2 = type; - switch ( type ) - { - case TK_FLOAT: - { - float fVal; + switch (type) { + case TK_FLOAT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString2, sizeof(tempString2), "%.3f", fVal ); - p2 = (char *) tempString2; - } + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", fVal); + p2 = (char *)tempString2; + } - break; + break; - case TK_INT: - { - float fVal; + case TK_INT: { + float fVal; - if ( m_ie->I_GetFloat( m_ownerID, type, name, &fVal ) == false) - return false; + if (m_ie->I_GetFloat(m_ownerID, type, name, &fVal) == false) + return false; - Com_sprintf( tempString2, sizeof(tempString2), "%d", (int) fVal ); - p2 = (char *) tempString2; - } - break; + Com_sprintf(tempString2, sizeof(tempString2), "%d", (int)fVal); + p2 = (char *)tempString2; + } break; - case TK_STRING: + case TK_STRING: - if ( m_ie->I_GetString( m_ownerID, type, name, &p2 ) == false) - return false; + if (m_ie->I_GetString(m_ownerID, type, name, &p2) == false) + return false; - break; + break; - case TK_VECTOR: - { - vector_t vVal; + case TK_VECTOR: { + vector_t vVal; - if ( m_ie->I_GetVector( m_ownerID, type, name, vVal ) == false) - return false; + if (m_ie->I_GetVector(m_ownerID, type, name, vVal) == false) + return false; - Com_sprintf( tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2] ); - p2 = (char *) tempString2; - } + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vVal[0], vVal[1], vVal[2]); + p2 = (char *)tempString2; + } - break; + break; } break; @@ -1343,54 +1250,53 @@ int CSequencer::EvaluateConditional( CBlock *block ) case ID_RANDOM: - { - float min, max; - //FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements + { + float min, max; + // FIXME: This will not account for nested Q_flrand(0.0f, 1.0f) statements - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - //A float value is returned from the function - t2 = TK_FLOAT; + // A float value is returned from the function + t2 = TK_FLOAT; - Com_sprintf( tempString2, sizeof(tempString2), "%.3f", m_ie->I_Random( min, max ) ); - p2 = (char *) tempString2; - } + Com_sprintf(tempString2, sizeof(tempString2), "%.3f", m_ie->I_Random(min, max)); + p2 = (char *)tempString2; + } - break; + break; case ID_TAG: - { - char *name; - float type; + { + char *name; + float type; - name = (char *) block->GetMemberData( memberNum++ ); - type = *(float *) block->GetMemberData( memberNum++ ); + name = (char *)block->GetMemberData(memberNum++); + type = *(float *)block->GetMemberData(memberNum++); - t2 = TK_VECTOR; + t2 = TK_VECTOR; - //TODO: Emit warning - if ( m_ie->I_GetTag( m_ownerID, name, (int) type, vec ) == false) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", name ); - return false; - } + // TODO: Emit warning + if (m_ie->I_GetTag(m_ownerID, name, (int)type, vec) == false) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", name); + return false; + } - Com_sprintf( tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2] ); - p2 = (char *) tempString2; + Com_sprintf(tempString2, sizeof(tempString2), "%.3f %.3f %.3f", vec[0], vec[1], vec[2]); + p2 = (char *)tempString2; - break; - } + break; + } default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on conditional" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on conditional"); return false; break; } - return m_ie->I_Evaluate( t1, p1, t2, p2, oper ); + return m_ie->I_Evaluate(t1, p1, t2, p2, oper); } /* @@ -1401,48 +1307,38 @@ Checks for if statement pre-processing ======================== */ -void CSequencer::CheckIf( CBlock **command ) -{ - CBlock *block = *command; - int successID, failureID; - CSequence *successSeq, *failureSeq; +void CSequencer::CheckIf(CBlock **command) { + CBlock *block = *command; + int successID, failureID; + CSequence *successSeq, *failureSeq; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_IF ) - { - int ret = EvaluateConditional( block ); + if (block->GetBlockID() == ID_IF) { + int ret = EvaluateConditional(block); - if ( ret /*TRUE*/ ) - { - if ( block->HasFlag( BF_ELSE ) ) - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 2 )); - } - else - { - successID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); + if (ret /*TRUE*/) { + if (block->HasFlag(BF_ELSE)) { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 2)); + } else { + successID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); } - successSeq = GetSequence( successID ); + successSeq = GetSequence(successID); - //TODO: Emit warning - assert( successSeq ); - if ( successSeq == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find conditional success sequence!\n" ); + // TODO: Emit warning + assert(successSeq); + if (successSeq == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find conditional success sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; @@ -1450,34 +1346,29 @@ void CSequencer::CheckIf( CBlock **command ) m_curSequence = successSeq; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); return; } - if ( ( ret == false ) && ( block->HasFlag( BF_ELSE ) ) ) - { - failureID = (int) (*(float *) block->GetMemberData( block->GetNumMembers() - 1 )); - failureSeq = GetSequence( failureID ); + if ((ret == false) && (block->HasFlag(BF_ELSE))) { + failureID = (int)(*(float *)block->GetMemberData(block->GetNumMembers() - 1)); + failureSeq = GetSequence(failureID); - //TODO: Emit warning - assert( failureSeq ); - if ( failureSeq == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find conditional failure sequence!\n" ); + // TODO: Emit warning + assert(failureSeq); + if (failureSeq == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find conditional failure sequence!\n"); *command = NULL; return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; @@ -1485,65 +1376,56 @@ void CSequencer::CheckIf( CBlock **command ) m_curSequence = failureSeq; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); return; } - //Only save the conditional statement if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the conditional statement if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Conditional failed, just move on to the next command - *command = PopCommand( POP_BACK ); - Prep( command ); + // Conditional failed, just move on to the next command + *command = PopCommand(POP_BACK); + Prep(command); return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_CONDITIONAL ) ) ) - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_CONDITIONAL))) { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Back out of the conditional and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); + // Back out of the conditional and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); - //This can safely happen - if ( m_curSequence == NULL ) - { + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } @@ -1555,67 +1437,57 @@ Checks for loop command pre-processing ======================== */ -void CSequencer::CheckLoop( CBlock **command ) -{ - CBlockMember *bm; - CBlock *block = *command; - float min, max; - int iterations; - int loopID; - int memberNum = 0; +void CSequencer::CheckLoop(CBlock **command) { + CBlockMember *bm; + CBlock *block = *command; + float min, max; + int iterations; + int loopID; + int memberNum = 0; - if ( block == NULL ) + if (block == NULL) return; - //Check for a loop - if ( block->GetBlockID() == ID_LOOP ) - { - //Get the loop ID - bm = block->GetMember( memberNum++ ); + // Check for a loop + if (block->GetBlockID() == ID_LOOP) { + // Get the loop ID + bm = block->GetMember(memberNum++); - if ( bm->GetID() == ID_RANDOM ) - { - //Parse out the random number - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + if (bm->GetID() == ID_RANDOM) { + // Parse out the random number + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - iterations = (int) m_ie->I_Random( min, max ); - } - else - { - iterations = (int) (*(float *) bm->GetData()); + iterations = (int)m_ie->I_Random(min, max); + } else { + iterations = (int)(*(float *)bm->GetData()); } - loopID = (int) (*(float *) block->GetMemberData( memberNum++ )); + loopID = (int)(*(float *)block->GetMemberData(memberNum++)); - CSequence *loop = GetSequence( loopID ); + CSequence *loop = GetSequence(loopID); - //TODO: Emit warning - assert( loop ); - if ( loop == NULL ) - { - m_ie->I_DPrintf( WL_ERROR, "Unable to find 'loop' sequence!\n" ); + // TODO: Emit warning + assert(loop); + if (loop == NULL) { + m_ie->I_DPrintf(WL_ERROR, "Unable to find 'loop' sequence!\n"); *command = NULL; return; } - assert( loop->GetParent() ); - if ( loop->GetParent() == NULL ) - { + assert(loop->GetParent()); + if (loop->GetParent() == NULL) { *command = NULL; return; } - //Restore the count if it has been lost - loop->SetIterations( iterations ); + // Restore the count if it has been lost + loop->SetIterations(iterations); - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; @@ -1623,64 +1495,55 @@ void CSequencer::CheckLoop( CBlock **command ) m_curSequence = loop; - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); return; } - //Check for the end of the loop - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_LOOP ) ) ) - { - //We don't want to decrement -1 - if ( m_curSequence->GetIterations() > 0 ) - m_curSequence->SetIterations( m_curSequence->GetIterations()-1 ); //Nice, eh? + // Check for the end of the loop + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_LOOP))) { + // We don't want to decrement -1 + if (m_curSequence->GetIterations() > 0) + m_curSequence->SetIterations(m_curSequence->GetIterations() - 1); // Nice, eh? - //Either there's another iteration, or it's infinite - if ( m_curSequence->GetIterations() != 0 ) - { - //Another iteration is going to happen, so this will need to be considered again - PushCommand( block, PUSH_FRONT ); + // Either there's another iteration, or it's infinite + if (m_curSequence->GetIterations() != 0) { + // Another iteration is going to happen, so this will need to be considered again + PushCommand(block, PUSH_FRONT); - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); return; - } - else - { - assert( m_curSequence->GetReturn() ); - if ( m_curSequence->GetReturn() == NULL ) - { + } else { + assert(m_curSequence->GetReturn()); + if (m_curSequence->GetReturn() == NULL) { *command = NULL; return; } - //Check to retain it - if ( m_curSequence->GetParent()->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->GetParent()->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Back out of the loop and resume the previous sequence - m_curSequence = ReturnSequence( m_curSequence ); + // Back out of the loop and resume the previous sequence + m_curSequence = ReturnSequence(m_curSequence); - //This can safely happen - if ( m_curSequence == NULL ) - { + // This can safely happen + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } } @@ -1693,32 +1556,27 @@ Checks for flush command pre-processing ======================== */ -void CSequencer::CheckFlush( CBlock **command ) -{ - CBlock *block = *command; +void CSequencer::CheckFlush(CBlock **command) { + CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_FLUSH ) - { - //Flush the sequence - Flush( m_curSequence ); + if (block->GetBlockID() == ID_FLUSH) { + // Flush the sequence + Flush(m_curSequence); - //Check to retain it - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Check to retain it + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); return; } @@ -1732,165 +1590,143 @@ Checks for affect command pre-processing ======================== */ -void CSequencer::CheckAffect( CBlock **command ) -{ +void CSequencer::CheckAffect(CBlock **command) { CBlock *block = *command; - sharedEntity_t *ent = NULL; - char *entname = NULL; - int memberNum = 0; + sharedEntity_t *ent = NULL; + char *entname = NULL; + int memberNum = 0; - if ( block == NULL ) - { + if (block == NULL) { return; } - if ( block->GetBlockID() == ID_AFFECT ) - { - CSequencer *sequencer = NULL; - entname = (char*) block->GetMemberData( memberNum++ ); - ent = m_ie->I_GetEntityByName( entname ); + if (block->GetBlockID() == ID_AFFECT) { + CSequencer *sequencer = NULL; + entname = (char *)block->GetMemberData(memberNum++); + ent = m_ie->I_GetEntityByName(entname); - if( !ent ) // if there wasn't a valid entname in the affect, we need to check if it's a get command + if (!ent) // if there wasn't a valid entname in the affect, we need to check if it's a get command { - //try to parse a 'get' command that is embeded in this 'affect' + // try to parse a 'get' command that is embeded in this 'affect' - int id; - char *p1 = NULL; - char *name = 0; - CBlockMember *bm = NULL; + int id; + char *p1 = NULL; + char *name = 0; + CBlockMember *bm = NULL; // // Get the first parameter (this should be the get) // - bm = block->GetMember( 0 ); + bm = block->GetMember(0); id = bm->GetID(); - switch ( id ) - { - // these 3 cases probably aren't necessary - case TK_STRING: - case TK_IDENTIFIER: - case TK_CHAR: - p1 = (char *) bm->GetData(); + switch (id) { + // these 3 cases probably aren't necessary + case TK_STRING: + case TK_IDENTIFIER: + case TK_CHAR: + p1 = (char *)bm->GetData(); break; - case ID_GET: + case ID_GET: { + int type; + + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); + + switch (type) // what type are they attempting to get { - int type; - - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); - - switch ( type ) // what type are they attempting to get - { - - case TK_STRING: - //only string is acceptable for affect, store result in p1 - if ( m_ie->I_GetString( m_ownerID, type, name, &p1 ) == false) - { - return; - } - break; - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _1" ); - return; - break; - } + case TK_STRING: + // only string is acceptable for affect, store result in p1 + if (m_ie->I_GetString(m_ownerID, type, name, &p1) == false) { + return; + } break; - } - default: - //FIXME: Make an enum id for the error... - m_ie->I_DPrintf( WL_ERROR, "Invalid parameter type on affect _2" ); + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _1"); return; break; - }//end id switch + } - if(p1) - { - ent = m_ie->I_GetEntityByName( p1 ); + break; + } + + default: + // FIXME: Make an enum id for the error... + m_ie->I_DPrintf(WL_ERROR, "Invalid parameter type on affect _2"); + return; + break; + } // end id switch + + if (p1) { + ent = m_ie->I_GetEntityByName(p1); } - if(!ent) - { // a valid entity name was not returned from the get command - m_ie->I_DPrintf( WL_WARNING, "'%s' : invalid affect() target\n"); + if (!ent) { // a valid entity name was not returned from the get command + m_ie->I_DPrintf(WL_WARNING, "'%s' : invalid affect() target\n"); } } // end if(!ent) - if( ent ) - { - sequencer = gSequencers[ent->s.number];//ent->sequencer; + if (ent) { + sequencer = gSequencers[ent->s.number]; // ent->sequencer; } - if(memberNum == 0) - { //there was no get, increment manually before next step + if (memberNum == 0) { // there was no get, increment manually before next step memberNum++; } - int type = (int) (*(float *) block->GetMemberData( memberNum )); - int id = (int) (*(float *) block->GetMemberData( memberNum+1 )); + int type = (int)(*(float *)block->GetMemberData(memberNum)); + int id = (int)(*(float *)block->GetMemberData(memberNum + 1)); - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //NOTENOTE: If this isn't found, continue on to the next command - if ( sequencer == NULL ) - { - *command = PopCommand( POP_BACK ); - Prep( command ); + // NOTENOTE: If this isn't found, continue on to the next command + if (sequencer == NULL) { + *command = PopCommand(POP_BACK); + Prep(command); return; } - sequencer->Affect( id, type ); + sequencer->Affect(id, type); - *command = PopCommand( POP_BACK ); - Prep( command ); - if( ent ) - { // ents need to update upon being affected - //ent->taskManager->Update(); + *command = PopCommand(POP_BACK); + Prep(command); + if (ent) { // ents need to update upon being affected + // ent->taskManager->Update(); gTaskManagers[ent->s.number]->Update(); } return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_AFFECT ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_AFFECT))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_curSequence = ReturnSequence( m_curSequence ); + m_curSequence = ReturnSequence(m_curSequence); - if ( m_curSequence == NULL ) - { + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); - if( ent ) - { // ents need to update upon being affected - //ent->taskManager->Update(); + *command = PopCommand(POP_BACK); + Prep(command); + if (ent) { // ents need to update upon being affected + // ent->taskManager->Update(); gTaskManagers[ent->s.number]->Update(); } - } } @@ -1900,97 +1736,85 @@ CheckDo ------------------------- */ -void CSequencer::CheckDo( CBlock **command ) -{ +void CSequencer::CheckDo(CBlock **command) { CBlock *block = *command; - if ( block == NULL ) + if (block == NULL) return; - if ( block->GetBlockID() == ID_DO ) - { - //Get the sequence - const char *groupName = (const char *) block->GetMemberData( 0 ); - CTaskGroup *group = m_taskManager->GetTaskGroup( groupName ); - CSequence *sequence = GetTaskSequence( group ); - - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - m_ie->I_DPrintf( WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName ); + if (block->GetBlockID() == ID_DO) { + // Get the sequence + const char *groupName = (const char *)block->GetMemberData(0); + CTaskGroup *group = m_taskManager->GetTaskGroup(groupName); + CSequence *sequence = GetTaskSequence(group); + + // TODO: Emit warning + assert(group); + if (group == NULL) { + // TODO: Give name/number of entity trying to execute, too + m_ie->I_DPrintf(WL_ERROR, "ICARUS Unable to find task group \"%s\"!\n", groupName); *command = NULL; return; } - //TODO: Emit warning - assert( sequence ); - if ( sequence == NULL ) - { - //TODO: Give name/number of entity trying to execute, too - m_ie->I_DPrintf( WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName ); + // TODO: Emit warning + assert(sequence); + if (sequence == NULL) { + // TODO: Give name/number of entity trying to execute, too + m_ie->I_DPrintf(WL_ERROR, "ICARUS Unable to find task 'group' sequence!\n", groupName); *command = NULL; return; } - //Only save the loop command if the calling sequence is retained - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + // Only save the loop command if the calling sequence is retained + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - //Set this to our current sequence - sequence->SetReturn( m_curSequence ); + // Set this to our current sequence + sequence->SetReturn(m_curSequence); m_curSequence = sequence; - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - //Mark all the following commands as being in the task - m_taskManager->MarkTask( group->GetGUID(), TASK_START ); + // Mark all the following commands as being in the task + m_taskManager->MarkTask(group->GetGUID(), TASK_START); - //Recursively work out any other pre-processors - *command = PopCommand( POP_BACK ); - Prep( command ); + // Recursively work out any other pre-processors + *command = PopCommand(POP_BACK); + Prep(command); return; } - if ( ( block->GetBlockID() == ID_BLOCK_END ) && ( m_curSequence->HasFlag( SQ_TASK ) ) ) - { - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) - { - PushCommand( block, PUSH_FRONT ); - } - else - { + if ((block->GetBlockID() == ID_BLOCK_END) && (m_curSequence->HasFlag(SQ_TASK))) { + if (m_curSequence->HasFlag(SQ_RETAIN)) { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; *command = NULL; } - m_taskManager->MarkTask( m_curGroup->GetGUID(), TASK_END ); + m_taskManager->MarkTask(m_curGroup->GetGUID(), TASK_END); m_curGroup = m_curGroup->GetParent(); - CSequence *returnSeq = ReturnSequence( m_curSequence ); - m_curSequence->SetReturn( NULL ); + CSequence *returnSeq = ReturnSequence(m_curSequence); + m_curSequence->SetReturn(NULL); m_curSequence = returnSeq; - if ( m_curSequence == NULL ) - { + if (m_curSequence == NULL) { *command = NULL; return; } - *command = PopCommand( POP_BACK ); - Prep( command ); + *command = PopCommand(POP_BACK); + Prep(command); } } @@ -2002,15 +1826,14 @@ Handles internal sequencer maintenance ======================== */ -void CSequencer::Prep( CBlock **command ) -{ - //Check all pre-processes - CheckAffect( command ); - CheckFlush( command ); - CheckLoop( command ); - CheckRun( command ); - CheckIf( command ); - CheckDo( command ); +void CSequencer::Prep(CBlock **command) { + // Check all pre-processes + CheckAffect(command); + CheckFlush(command); + CheckLoop(command); + CheckRun(command); + CheckIf(command); + CheckDo(command); } /* @@ -2021,13 +1844,11 @@ Starts communication between the task manager and this sequencer ======================== */ -int CSequencer::Prime( CTaskManager *taskManager, CBlock *command ) -{ - Prep( &command ); +int CSequencer::Prime(CTaskManager *taskManager, CBlock *command) { + Prep(&command); - if ( command ) - { - taskManager->SetCommand( command, PUSH_BACK ); + if (command) { + taskManager->SetCommand(command, PUSH_BACK); } return SEQ_OK; @@ -2041,51 +1862,45 @@ Handles a completed task and returns a new task to be completed ======================== */ -int CSequencer::Callback( CTaskManager *taskManager, CBlock *block, int returnCode ) -{ - CBlock *command; +int CSequencer::Callback(CTaskManager *taskManager, CBlock *block, int returnCode) { + CBlock *command; - if (returnCode == TASK_RETURN_COMPLETE) - { - //There are no more pending commands - if ( m_curSequence == NULL ) - { + if (returnCode == TASK_RETURN_COMPLETE) { + // There are no more pending commands + if (m_curSequence == NULL) { delete block; block = NULL; return SEQ_OK; } - //Check to retain the command - if ( m_curSequence->HasFlag( SQ_RETAIN ) ) //This isn't true for affect sequences...? - { - PushCommand( block, PUSH_FRONT ); - } - else + // Check to retain the command + if (m_curSequence->HasFlag(SQ_RETAIN)) // This isn't true for affect sequences...? { + PushCommand(block, PUSH_FRONT); + } else { delete block; block = NULL; } - //Check for pending commands - if ( m_curSequence->GetNumCommands() <= 0 ) - { - if ( m_curSequence->GetReturn() == NULL) + // Check for pending commands + if (m_curSequence->GetNumCommands() <= 0) { + if (m_curSequence->GetReturn() == NULL) return SEQ_OK; m_curSequence = m_curSequence->GetReturn(); } - command = PopCommand( POP_BACK ); - Prep( &command ); + command = PopCommand(POP_BACK); + Prep(&command); - if ( command ) - taskManager->SetCommand( command, PUSH_FRONT ); + if (command) + taskManager->SetCommand(command, PUSH_FRONT); return SEQ_OK; } - //FIXME: This could be more descriptive - m_ie->I_DPrintf( WL_ERROR, "command could not be called back\n" ); + // FIXME: This could be more descriptive + m_ie->I_DPrintf(WL_ERROR, "command could not be called back\n"); assert(0); return SEQ_FAILED; @@ -2097,24 +1912,18 @@ Recall ------------------------- */ -int CSequencer::Recall( void ) -{ - CBlock *block = NULL; +int CSequencer::Recall(void) { + CBlock *block = NULL; - if (!m_taskManager) - { //uh.. ok. + if (!m_taskManager) { // uh.. ok. assert(0); return true; } - while ( ( block = m_taskManager->RecallTask() ) != NULL ) - { - if (m_curSequence) - { - PushCommand( block, PUSH_BACK ); - } - else - { + while ((block = m_taskManager->RecallTask()) != NULL) { + if (m_curSequence) { + PushCommand(block, PUSH_BACK); + } else { delete block; block = NULL; } @@ -2129,28 +1938,25 @@ Affect ------------------------- */ -int CSequencer::Affect( int id, int type ) -{ - CSequence *sequence = GetSequence( id ); +int CSequencer::Affect(int id, int type) { + CSequence *sequence = GetSequence(id); - if ( sequence == NULL ) - { + if (sequence == NULL) { return SEQ_FAILED; } - switch ( type ) - { + switch (type) { case TYPE_FLUSH: - //Get rid of all old code - Flush( sequence ); + // Get rid of all old code + Flush(sequence); - sequence->RemoveFlag( SQ_PENDING, true ); + sequence->RemoveFlag(SQ_PENDING, true); m_curSequence = sequence; - Prime( m_taskManager, PopCommand( POP_BACK ) ); + Prime(m_taskManager, PopCommand(POP_BACK)); break; @@ -2158,19 +1964,18 @@ int CSequencer::Affect( int id, int type ) Recall(); - sequence->SetReturn( m_curSequence ); + sequence->SetReturn(m_curSequence); - sequence->RemoveFlag( SQ_PENDING, true ); + sequence->RemoveFlag(SQ_PENDING, true); m_curSequence = sequence; - Prime( m_taskManager, PopCommand( POP_BACK ) ); + Prime(m_taskManager, PopCommand(POP_BACK)); break; - default: - m_ie->I_DPrintf( WL_ERROR, "unknown affect type found" ); + m_ie->I_DPrintf(WL_ERROR, "unknown affect type found"); break; } @@ -2185,17 +1990,16 @@ Pushes a commands onto the current sequence ======================== */ -int CSequencer::PushCommand( CBlock *command, int flag ) -{ - //Make sure everything is ok - assert( m_curSequence ); - if ( m_curSequence == NULL ) +int CSequencer::PushCommand(CBlock *command, int flag) { + // Make sure everything is ok + assert(m_curSequence); + if (m_curSequence == NULL) return SEQ_FAILED; - m_curSequence->PushCommand( command, flag ); + m_curSequence->PushCommand(command, flag); m_numCommands++; - //Invalid flag + // Invalid flag return SEQ_OK; } @@ -2207,16 +2011,15 @@ Pops a command off the current sequence ======================== */ -CBlock *CSequencer::PopCommand( int flag ) -{ - //Make sure everything is ok - assert( m_curSequence ); - if ( m_curSequence == NULL ) +CBlock *CSequencer::PopCommand(int flag) { + // Make sure everything is ok + assert(m_curSequence); + if (m_curSequence == NULL) return NULL; - CBlock *block = m_curSequence->PopCommand( flag ); + CBlock *block = m_curSequence->PopCommand(flag); - if ( block != NULL ) + if (block != NULL) m_numCommands--; return block; @@ -2228,77 +2031,64 @@ RemoveSequence ------------------------- */ -//NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) +// NOTENOTE: This only removes references to the sequence, IT DOES NOT FREE THE ALLOCATED MEMORY! You've be warned! =) -int CSequencer::RemoveSequence( CSequence *sequence ) -{ +int CSequencer::RemoveSequence(CSequence *sequence) { CSequence *temp; int numChildren = sequence->GetNumChildren(); - //Add all the children - for ( int i = 0; i < numChildren; i++ ) - { - temp = sequence->GetChildByIndex( i ); + // Add all the children + for (int i = 0; i < numChildren; i++) { + temp = sequence->GetChildByIndex(i); - //TODO: Emit warning - assert( temp ); - if ( temp == NULL ) - { - m_ie->I_DPrintf( WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n" ); + // TODO: Emit warning + assert(temp); + if (temp == NULL) { + m_ie->I_DPrintf(WL_WARNING, "Unable to find child sequence on RemoveSequence call!\n"); continue; } - //Remove the references to this sequence - temp->SetParent( NULL ); - temp->SetReturn( NULL ); - + // Remove the references to this sequence + temp->SetParent(NULL); + temp->SetReturn(NULL); } return SEQ_OK; } -int CSequencer::DestroySequence( CSequence *sequence ) -{ - if ( !sequence ) +int CSequencer::DestroySequence(CSequence *sequence) { + if (!sequence) return SEQ_FAILED; - //m_sequenceMap.erase( sequence->GetID() ); - m_sequences.remove( sequence ); + // m_sequenceMap.erase( sequence->GetID() ); + m_sequences.remove(sequence); - taskSequence_m::iterator tsi; - for ( tsi = m_taskSequences.begin(); tsi != m_taskSequences.end(); ) - { - if((*tsi).second == sequence) - { + taskSequence_m::iterator tsi; + for (tsi = m_taskSequences.begin(); tsi != m_taskSequences.end();) { + if ((*tsi).second == sequence) { m_taskSequences.erase(tsi++); - } - else - { + } else { ++tsi; } } - CSequence* parent = sequence->GetParent(); - if ( parent ) - { - parent->RemoveChild( sequence ); + CSequence *parent = sequence->GetParent(); + if (parent) { + parent->RemoveChild(sequence); parent = NULL; } int curChild = sequence->GetNumChildren(); - while( curChild ) - { + while (curChild) { // Stop if we're about to go negative (invalid index!). - if ( curChild > 0 ) - { - DestroySequence( sequence->GetChildByIndex( --curChild ) ); - } - else + if (curChild > 0) { + DestroySequence(sequence->GetChildByIndex(--curChild)); + } else break; } - m_owner->DeleteSequence( sequence ); + m_owner->DeleteSequence(sequence); return SEQ_OK; } @@ -2309,23 +2099,21 @@ ReturnSequence ------------------------- */ -inline CSequence *CSequencer::ReturnSequence( CSequence *sequence ) -{ - while ( sequence->GetReturn() ) - { - assert(sequence != sequence->GetReturn() ); - if ( sequence == sequence->GetReturn() ) +inline CSequence *CSequencer::ReturnSequence(CSequence *sequence) { + while (sequence->GetReturn()) { + assert(sequence != sequence->GetReturn()); + if (sequence == sequence->GetReturn()) return NULL; sequence = sequence->GetReturn(); - if ( sequence->GetNumCommands() > 0 ) + if (sequence->GetNumCommands() > 0) return sequence; } return NULL; } -//Save / Load +// Save / Load /* ------------------------- @@ -2333,9 +2121,8 @@ Save ------------------------- */ -int CSequencer::Save( void ) -{ -#if 0 //asfsfasadf +int CSequencer::Save(void) { +#if 0 // asfsfasadf sequence_l::iterator si; taskSequence_m::iterator ti; int numSequences = 0, id, numTasks; @@ -2396,9 +2183,8 @@ Load ------------------------- */ -int CSequencer::Load( void ) -{ -#if 0 //asfsfasadf +int CSequencer::Load(void) { +#if 0 // asfsfasadf //Get the owner of this sequencer m_ie->I_ReadSaveData( 'SQRE', &m_ownerID, sizeof( m_ownerID ) ); diff --git a/codemp/icarus/TaskManager.cpp b/codemp/icarus/TaskManager.cpp index ec0b1bea44..155cfcada4 100644 --- a/codemp/icarus/TaskManager.cpp +++ b/codemp/icarus/TaskManager.cpp @@ -29,7 +29,9 @@ along with this program; if not, see . #include #include "server/server.h" -#define ICARUS_VALIDATE(a) if ( a == false ) return TASK_FAILED; +#define ICARUS_VALIDATE(a) \ + if (a == false) \ + return TASK_FAILED; /* ================================================= @@ -39,26 +41,21 @@ CTask ================================================= */ -CTask::CTask( void ) -{ -} +CTask::CTask(void) {} -CTask::~CTask( void ) -{ -} +CTask::~CTask(void) {} -CTask *CTask::Create( int GUID, CBlock *block ) -{ +CTask *CTask::Create(int GUID, CBlock *block) { CTask *task = new CTask; - //TODO: Emit warning - assert( task ); - if ( task == NULL ) + // TODO: Emit warning + assert(task); + if (task == NULL) return NULL; - task->SetTimeStamp( 0 ); - task->SetBlock( block ); - task->SetGUID( GUID ); + task->SetTimeStamp(0); + task->SetBlock(block); + task->SetGUID(GUID); return task; } @@ -69,9 +66,8 @@ Free ------------------------- */ -void CTask::Free( void ) -{ - //NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up +void CTask::Free(void) { + // NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up delete this; } @@ -83,18 +79,14 @@ CTaskGroup ================================================= */ -CTaskGroup::CTaskGroup( void ) -{ +CTaskGroup::CTaskGroup(void) { Init(); - m_GUID = 0; - m_parent = NULL; + m_GUID = 0; + m_parent = NULL; } -CTaskGroup::~CTaskGroup( void ) -{ - m_completedTasks.clear(); -} +CTaskGroup::~CTaskGroup(void) { m_completedTasks.clear(); } /* ------------------------- @@ -102,10 +94,7 @@ SetGUID ------------------------- */ -void CTaskGroup::SetGUID( int GUID ) -{ - m_GUID = GUID; -} +void CTaskGroup::SetGUID(int GUID) { m_GUID = GUID; } /* ------------------------- @@ -113,12 +102,11 @@ Init ------------------------- */ -void CTaskGroup::Init( void ) -{ +void CTaskGroup::Init(void) { m_completedTasks.clear(); - m_numCompleted = 0; - m_parent = NULL; + m_numCompleted = 0; + m_parent = NULL; } /* @@ -127,9 +115,8 @@ Add ------------------------- */ -int CTaskGroup::Add( CTask *task ) -{ - m_completedTasks[ task->GetGUID() ] = false; +int CTaskGroup::Add(CTask *task) { + m_completedTasks[task->GetGUID()] = false; return TASK_OK; } @@ -139,11 +126,9 @@ MarkTaskComplete ------------------------- */ -bool CTaskGroup::MarkTaskComplete( int id ) -{ - if ( (m_completedTasks.find( id )) != m_completedTasks.end() ) - { - m_completedTasks[ id ] = true; +bool CTaskGroup::MarkTaskComplete(int id) { + if ((m_completedTasks.find(id)) != m_completedTasks.end()) { + m_completedTasks[id] = true; m_numCompleted++; return true; @@ -160,13 +145,9 @@ CTaskManager ================================================= */ -CTaskManager::CTaskManager( void ) -{ -} +CTaskManager::CTaskManager(void) {} -CTaskManager::~CTaskManager( void ) -{ -} +CTaskManager::~CTaskManager(void) {} /* ------------------------- @@ -174,10 +155,7 @@ Create ------------------------- */ -CTaskManager *CTaskManager::Create( void ) -{ - return new CTaskManager; -} +CTaskManager *CTaskManager::Create(void) { return new CTaskManager; } /* ------------------------- @@ -185,18 +163,17 @@ Init ------------------------- */ -int CTaskManager::Init( CSequencer *owner ) -{ - //TODO: Emit warning - if ( owner == NULL ) +int CTaskManager::Init(CSequencer *owner) { + // TODO: Emit warning + if (owner == NULL) return TASK_FAILED; m_tasks.clear(); - m_owner = owner; - m_ownerID = owner->GetOwnerID(); - m_curGroup = NULL; - m_GUID = 0; - m_resident = false; + m_owner = owner; + m_ownerID = owner->GetOwnerID(); + m_curGroup = NULL; + m_GUID = 0; + m_resident = false; return TASK_OK; } @@ -207,22 +184,19 @@ Free ------------------------- */ -int CTaskManager::Free( void ) -{ - taskGroup_v::iterator gi; - tasks_l::iterator ti; +int CTaskManager::Free(void) { + taskGroup_v::iterator gi; + tasks_l::iterator ti; - //Clear out all pending tasks - for ( ti = m_tasks.begin(); ti != m_tasks.end(); ++ti ) - { + // Clear out all pending tasks + for (ti = m_tasks.begin(); ti != m_tasks.end(); ++ti) { (*ti)->Free(); } m_tasks.clear(); - //Clear out all taskGroups - for ( gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi ) - { + // Clear out all taskGroups + for (gi = m_taskGroups.begin(); gi != m_taskGroups.end(); ++gi) { delete (*gi); } @@ -239,9 +213,8 @@ Flush ------------------------- */ -int CTaskManager::Flush( void ) -{ - //FIXME: Rewrite +int CTaskManager::Flush(void) { + // FIXME: Rewrite return true; } @@ -252,42 +225,40 @@ AddTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::AddTaskGroup( const char *name ) -{ +CTaskGroup *CTaskManager::AddTaskGroup(const char *name) { CTaskGroup *group; - //Collect any garbage - taskGroupName_m::iterator tgni; - tgni = m_taskGroupNameMap.find( name ); + // Collect any garbage + taskGroupName_m::iterator tgni; + tgni = m_taskGroupNameMap.find(name); - if ( tgni != m_taskGroupNameMap.end() ) - { + if (tgni != m_taskGroupNameMap.end()) { group = (*tgni).second; - //Clear it and just move on + // Clear it and just move on group->Init(); return group; } - //Allocate a new one - group = new CTaskGroup;; + // Allocate a new one + group = new CTaskGroup; + ; - //TODO: Emit warning - assert( group ); - if ( group == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate task group \"%s\"\n", name ); + // TODO: Emit warning + assert(group); + if (group == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to allocate task group \"%s\"\n", name); return NULL; } - //Setup the internal information - group->SetGUID( m_GUID++ ); + // Setup the internal information + group->SetGUID(m_GUID++); - //Add it to the list and associate it for retrieval later - m_taskGroups.insert( m_taskGroups.end(), group ); - m_taskGroupNameMap[ name ] = group; - m_taskGroupIDMap[ group->GetGUID() ] = group; + // Add it to the list and associate it for retrieval later + m_taskGroups.insert(m_taskGroups.end(), group); + m_taskGroupNameMap[name] = group; + m_taskGroupIDMap[group->GetGUID()] = group; return group; } @@ -298,30 +269,26 @@ GetTaskGroup ------------------------- */ -CTaskGroup *CTaskManager::GetTaskGroup( const char *name ) -{ - taskGroupName_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(const char *name) { + taskGroupName_m::iterator tgi; - tgi = m_taskGroupNameMap.find( name ); + tgi = m_taskGroupNameMap.find(name); - if ( tgi == m_taskGroupNameMap.end() ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%s\"\n", name ); + if (tgi == m_taskGroupNameMap.end()) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Could not find task group \"%s\"\n", name); return NULL; } return (*tgi).second; } -CTaskGroup *CTaskManager::GetTaskGroup( int id ) -{ - taskGroupID_m::iterator tgi; +CTaskGroup *CTaskManager::GetTaskGroup(int id) { + taskGroupID_m::iterator tgi; - tgi = m_taskGroupIDMap.find( id ); + tgi = m_taskGroupIDMap.find(id); - if ( tgi == m_taskGroupIDMap.end() ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%d\"\n", id ); + if (tgi == m_taskGroupIDMap.end()) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Could not find task group \"%d\"\n", id); return NULL; } @@ -334,15 +301,13 @@ Update ------------------------- */ -int CTaskManager::Update( void ) -{ +int CTaskManager::Update(void) { sharedEntity_t *owner = SV_GentityNum(m_ownerID); - if ( (owner->r.svFlags&SVF_ICARUS_FREEZE) ) - { + if ((owner->r.svFlags & SVF_ICARUS_FREEZE)) { return TASK_FAILED; } - m_count = 0; //Needed for runaway init + m_count = 0; // Needed for runaway init m_resident = true; int returnVal = Go(); @@ -358,19 +323,15 @@ IsRunning ------------------------- */ -qboolean CTaskManager::IsRunning( void ) -{ - return (qboolean)( m_tasks.empty() == false ); -} +qboolean CTaskManager::IsRunning(void) { return (qboolean)(m_tasks.empty() == false); } /* ------------------------- Check ------------------------- */ -inline bool CTaskManager::Check( int targetID, CBlock *block, int memberNum ) -{ - if ( (block->GetMember( memberNum ))->GetID() == targetID ) +inline bool CTaskManager::Check(int targetID, CBlock *block, int memberNum) { + if ((block->GetMember(memberNum))->GetID() == targetID) return true; return false; @@ -382,67 +343,57 @@ GetFloat ------------------------- */ -int CTaskManager::GetFloat( int entID, CBlock *block, int &memberNum, float &value ) -{ - char *name; - int type; +int CTaskManager::GetFloat(int entID, CBlock *block, int &memberNum, float &value) { + char *name; + int type; - //See if this is a get() command replacement - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != TK_FLOAT ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n" ); + // TODO: Emit warning + if (type != TK_FLOAT) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n"); return false; } - return (m_owner->GetInterface())->I_GetFloat( entID, type, name, &value ); + return (m_owner->GetInterface())->I_GetFloat(entID, type, name, &value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - value = (m_owner->GetInterface())->I_Random( min, max ); + value = (m_owner->GetInterface())->I_Random(min, max); return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n" ); + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n"); return false; } - CBlockMember *bm = block->GetMember( memberNum ); + CBlockMember *bm = block->GetMember(memberNum); - if ( bm->GetID() == TK_INT ) - { - value = (float) (*(int *) block->GetMemberData( memberNum++ )); - } - else if ( bm->GetID() == TK_FLOAT ) - { - value = *(float *) block->GetMemberData( memberNum++ ); - } - else - { + if (bm->GetID() == TK_INT) { + value = (float)(*(int *)block->GetMemberData(memberNum++)); + } else if (bm->GetID() == TK_FLOAT) { + value = *(float *)block->GetMemberData(memberNum++); + } else { assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type FLOAT\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Unexpected value; expected type FLOAT\n"); return false; } @@ -455,82 +406,73 @@ GetVector ------------------------- */ -int CTaskManager::GetVector( int entID, CBlock *block, int &memberNum, vector_t &value ) -{ - char *name; - int type, i; +int CTaskManager::GetVector(int entID, CBlock *block, int &memberNum, vector_t &value) { + char *name; + int type, i; - //See if this is a get() command replacement - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // See if this is a get() command replacement + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //TODO: Emit warning - if ( type != TK_VECTOR ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n" ); + // TODO: Emit warning + if (type != TK_VECTOR) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n"); } - return (m_owner->GetInterface())->I_GetVector( entID, type, name, value ); + return (m_owner->GetInterface())->I_GetVector(entID, type, name, value); } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - for ( i = 0; i < 3; i++ ) - { - value[i] = (float) (m_owner->GetInterface())->I_Random( min, max ); //FIXME: Just truncating it for now.. should be fine though + for (i = 0; i < 3; i++) { + value[i] = (float)(m_owner->GetInterface())->I_Random(min, max); // FIXME: Just truncating it for now.. should be fine though } return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { - char *tagName; - float tagLookup; + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { + char *tagName; + float tagLookup; memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup)); - if ( (m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, value ) == false) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\" for ent %i!\n", tagName, entID ); -// assert(0); + if ((m_owner->GetInterface())->I_GetTag(entID, tagName, (int)tagLookup, value) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\" for ent %i!\n", tagName, entID); + // assert(0); return TASK_FAILED; } return true; } - //Check for a real vector here - type = (int) (*(float *) block->GetMemberData( memberNum )); + // Check for a real vector here + type = (int)(*(float *)block->GetMemberData(memberNum)); - if ( type != TK_VECTOR ) - { -// (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); + if (type != TK_VECTOR) { + // (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" ); return false; } memberNum++; - for ( i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, value[i] ) == false ) + for (i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, value[i]) == false) return false; } @@ -543,165 +485,146 @@ Get ------------------------- */ -int CTaskManager::Get( int entID, CBlock *block, int &memberNum, char **value ) -{ - static char tempBuffer[128]; //FIXME: EEEK! - vector_t vector; - char *name, *tagName; - float tagLookup; - int type; +int CTaskManager::Get(int entID, CBlock *block, int &memberNum, char **value) { + static char tempBuffer[128]; // FIXME: EEEK! + vector_t vector; + char *name, *tagName; + float tagLookup; + int type; - //Look for a get() inline call - if ( Check( ID_GET, block, memberNum ) ) - { - //Update the member past the header id + // Look for a get() inline call + if (Check(ID_GET, block, memberNum)) { + // Update the member past the header id memberNum++; - //get( TYPE, NAME ) - type = (int) (*(float *) block->GetMemberData( memberNum++ )); - name = (char *) block->GetMemberData( memberNum++ ); + // get( TYPE, NAME ) + type = (int)(*(float *)block->GetMemberData(memberNum++)); + name = (char *)block->GetMemberData(memberNum++); - //Format the return properly - //FIXME: This is probably doing double formatting in certain cases... - //FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! - switch ( type ) - { + // Format the return properly + // FIXME: This is probably doing double formatting in certain cases... + // FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!! + switch (type) { case TK_STRING: - if ( ( m_owner->GetInterface())->I_GetString( entID, type, name, value ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); + if ((m_owner->GetInterface())->I_GetString(entID, type, name, value) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); return false; } return true; break; - case TK_FLOAT: - { - float temp; - - if ( (m_owner->GetInterface())->I_GetFloat( entID, type, name, &temp ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case TK_FLOAT: { + float temp; - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", temp ); - *value = (char *) tempBuffer; + if ((m_owner->GetInterface())->I_GetFloat(entID, type, name, &temp) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", temp); + *value = (char *)tempBuffer; + } + return true; break; - case TK_VECTOR: - { - vector_t vval; - - if ( (m_owner->GetInterface())->I_GetVector( entID, type, name, vval ) == false ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name ); - return false; - } + case TK_VECTOR: { + vector_t vval; - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + if ((m_owner->GetInterface())->I_GetVector(entID, type, name, vval) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name); + return false; } + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; + } + return true; break; default: - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return an unknown type!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Get() call tried to return an unknown type!\n"); return false; break; } } - //Look for a Q_flrand(0.0f, 1.0f) inline call - if ( Check( ID_RANDOM, block, memberNum ) ) - { - float min, max, ret; + // Look for a Q_flrand(0.0f, 1.0f) inline call + if (Check(ID_RANDOM, block, memberNum)) { + float min, max, ret; memberNum++; - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - ret = ( m_owner->GetInterface())->I_Random( min, max ); + ret = (m_owner->GetInterface())->I_Random(min, max); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", ret ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", ret); + *value = (char *)tempBuffer; return true; } - //Look for a tag() inline call - if ( Check( ID_TAG, block, memberNum ) ) - { + // Look for a tag() inline call + if (Check(ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(entID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(entID, block, memberNum, tagLookup)); - if ( ( m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, vector ) == false) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if ((m_owner->GetInterface())->I_GetTag(entID, tagName, (int)tagLookup, vector) == false) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0 && "Unable to find tag"); return false; } - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vector[0], vector[1], vector[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vector[0], vector[1], vector[2]); + *value = (char *)tempBuffer; return true; } - //Get an actual piece of data + // Get an actual piece of data - CBlockMember *bm = block->GetMember( memberNum ); + CBlockMember *bm = block->GetMember(memberNum); - if ( bm->GetID() == TK_INT ) - { - float fval = (float) (*(int *) block->GetMemberData( memberNum++ )); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", fval ); - *value = (char *) tempBuffer; + if (bm->GetID() == TK_INT) { + float fval = (float)(*(int *)block->GetMemberData(memberNum++)); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == TK_FLOAT ) - { - float fval = *(float *) block->GetMemberData( memberNum++ ); - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f", fval ); - *value = (char *) tempBuffer; + } else if (bm->GetID() == TK_FLOAT) { + float fval = *(float *)block->GetMemberData(memberNum++); + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f", fval); + *value = (char *)tempBuffer; return true; - } - else if ( bm->GetID() == TK_VECTOR ) - { - vector_t vval; + } else if (bm->GetID() == TK_VECTOR) { + vector_t vval; memberNum++; - for ( int i = 0; i < 3; i++ ) - { - if ( GetFloat( entID, block, memberNum, vval[i] ) == false ) + for (int i = 0; i < 3; i++) { + if (GetFloat(entID, block, memberNum, vval[i]) == false) return false; } - Com_sprintf( tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2] ); - *value = (char *) tempBuffer; + Com_sprintf(tempBuffer, sizeof(tempBuffer), "%f %f %f", vval[0], vval[1], vval[2]); + *value = (char *)tempBuffer; return true; - } - else if ( ( bm->GetID() == TK_STRING ) || ( bm->GetID() == TK_IDENTIFIER ) ) - { - *value = (char *) block->GetMemberData( memberNum++ ); + } else if ((bm->GetID() == TK_STRING) || (bm->GetID() == TK_IDENTIFIER)) { + *value = (char *)block->GetMemberData(memberNum++); return true; } - //TODO: Emit warning - assert( 0 ); - (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type STRING\n" ); + // TODO: Emit warning + assert(0); + (m_owner->GetInterface())->I_DPrintf(WL_WARNING, "Unexpected value; expected type STRING\n"); return false; } @@ -712,136 +635,129 @@ Go ------------------------- */ -int CTaskManager::Go( void ) -{ - CTask *task = NULL; - bool completed = false; +int CTaskManager::Go(void) { + CTask *task = NULL; + bool completed = false; - //Check for run away scripts - if ( m_count++ > RUNAWAY_LIMIT ) - { + // Check for run away scripts + if (m_count++ > RUNAWAY_LIMIT) { assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Runaway loop detected!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Runaway loop detected!\n"); return TASK_FAILED; } - //If there are tasks to complete, do so - if ( m_tasks.empty() == false ) - { - //Get the next task - task = PopTask( POP_BACK ); + // If there are tasks to complete, do so + if (m_tasks.empty() == false) { + // Get the next task + task = PopTask(POP_BACK); - assert( task ); - if ( task == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Invalid task found in Go()!\n" ); + assert(task); + if (task == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Invalid task found in Go()!\n"); return TASK_FAILED; } - //If this hasn't been stamped, do so - if ( task->GetTimeStamp() == 0 ) - task->SetTimeStamp( ( m_owner->GetInterface())->I_GetTime() ); + // If this hasn't been stamped, do so + if (task->GetTimeStamp() == 0) + task->SetTimeStamp((m_owner->GetInterface())->I_GetTime()); - //Switch and call the proper function - switch( task->GetID() ) - { + // Switch and call the proper function + switch (task->GetID()) { case ID_WAIT: - Wait( task, completed ); + Wait(task, completed); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, PUSH_BACK ); + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; case ID_WAITSIGNAL: - WaitSignal( task, completed ); + WaitSignal(task, completed); - //Push it to consider it again on the next frame if not complete - if ( completed == false ) - { - PushTask( task, PUSH_BACK ); + // Push it to consider it again on the next frame if not complete + if (completed == false) { + PushTask(task, PUSH_BACK); return TASK_OK; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); break; - case ID_PRINT: //print( STRING ) - Print( task ); + case ID_PRINT: // print( STRING ) + Print(task); break; - case ID_SOUND: //sound( name ) - Sound( task ); + case ID_SOUND: // sound( name ) + Sound(task); break; - case ID_MOVE: //move ( ORIGIN, ANGLES, DURATION ) - Move( task ); + case ID_MOVE: // move ( ORIGIN, ANGLES, DURATION ) + Move(task); break; - case ID_ROTATE: //rotate( ANGLES, DURATION ) - Rotate( task ); + case ID_ROTATE: // rotate( ANGLES, DURATION ) + Rotate(task); break; - case ID_KILL: //kill( NAME ) - Kill( task ); + case ID_KILL: // kill( NAME ) + Kill(task); break; - case ID_REMOVE: //remove( NAME ) - Remove( task ); + case ID_REMOVE: // remove( NAME ) + Remove(task); break; - case ID_CAMERA: //camera( ? ) - Camera( task ); + case ID_CAMERA: // camera( ? ) + Camera(task); break; - case ID_SET: //set( NAME, ? ) - Set( task ); + case ID_SET: // set( NAME, ? ) + Set(task); break; - case ID_USE: //use( NAME ) - Use( task ); + case ID_USE: // use( NAME ) + Use(task); break; - case ID_DECLARE://declare( TYPE, NAME ) - DeclareVariable( task ); + case ID_DECLARE: // declare( TYPE, NAME ) + DeclareVariable(task); break; - case ID_FREE: //free( NAME ) - FreeVariable( task ); + case ID_FREE: // free( NAME ) + FreeVariable(task); break; - case ID_SIGNAL: //signal( NAME ) - Signal( task ); + case ID_SIGNAL: // signal( NAME ) + Signal(task); break; - case ID_PLAY: //play ( NAME ) - Play( task ); + case ID_PLAY: // play ( NAME ) + Play(task); break; default: assert(0); task->Free(); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Found unknown task type!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Found unknown task type!\n"); return TASK_FAILED; break; } - //Pump the sequencer for another task - CallbackCommand( task, TASK_RETURN_COMPLETE ); + // Pump the sequencer for another task + CallbackCommand(task, TASK_RETURN_COMPLETE); task->Free(); } - //FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't + // FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't // execute too many commands in one cycle. This may, however, cause timing errors to surface. return TASK_OK; @@ -853,25 +769,22 @@ SetCommand ------------------------- */ -int CTaskManager::SetCommand( CBlock *command, int type ) -{ - CTask *task = CTask::Create( m_GUID++, command ); +int CTaskManager::SetCommand(CBlock *command, int type) { + CTask *task = CTask::Create(m_GUID++, command); - //If this is part of a task group, add it in - if ( m_curGroup ) - { - m_curGroup->Add( task ); + // If this is part of a task group, add it in + if (m_curGroup) { + m_curGroup->Add(task); } - //TODO: Emit warning - assert( task ); - if ( task == NULL ) - { - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate new task!\n" ); + // TODO: Emit warning + assert(task); + if (task == NULL) { + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to allocate new task!\n"); return TASK_FAILED; } - PushTask( task, type ); + PushTask(task, type); return TASK_OK; } @@ -882,35 +795,30 @@ MarkTask ------------------------- */ -int CTaskManager::MarkTask( int id, int operation ) -{ - CTaskGroup *group = GetTaskGroup( id ); +int CTaskManager::MarkTask(int id, int operation) { + CTaskGroup *group = GetTaskGroup(id); - assert( group ); + assert(group); - if ( group == NULL ) + if (group == NULL) return TASK_FAILED; - if ( operation == TASK_START ) - { - //Reset all the completion information + if (operation == TASK_START) { + // Reset all the completion information group->Init(); - group->SetParent( m_curGroup ); + group->SetParent(m_curGroup); m_curGroup = group; - } - else if ( operation == TASK_END ) - { - assert( m_curGroup ); - if ( m_curGroup == NULL ) + } else if (operation == TASK_END) { + assert(m_curGroup); + if (m_curGroup == NULL) return TASK_FAILED; m_curGroup = m_curGroup->GetParent(); } #ifdef _DEBUG - else - { + else { assert(0); } #endif @@ -924,15 +832,13 @@ Completed ------------------------- */ -int CTaskManager::Completed( int id ) -{ - taskGroup_v::iterator tgi; +int CTaskManager::Completed(int id) { + taskGroup_v::iterator tgi; - //Mark the task as completed - for ( tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi ) - { - //If this returns true, then the task was marked properly - if ( (*tgi)->MarkTaskComplete( id ) ) + // Mark the task as completed + for (tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); ++tgi) { + // If this returns true, then the task was marked properly + if ((*tgi)->MarkTaskComplete(id)) break; } @@ -945,14 +851,13 @@ CallbackCommand ------------------------- */ -int CTaskManager::CallbackCommand( CTask *task, int returnCode ) -{ - if ( m_owner->Callback( this, task->GetBlock(), returnCode ) == SEQ_OK ) - return Go( ); +int CTaskManager::CallbackCommand(CTask *task, int returnCode) { + if (m_owner->Callback(this, task->GetBlock(), returnCode) == SEQ_OK) + return Go(); assert(0); - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Command callback failure!\n" ); + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Command callback failure!\n"); return TASK_FAILED; } @@ -962,20 +867,18 @@ RecallTask ------------------------- */ -CBlock *CTaskManager::RecallTask( void ) -{ - CTask *task; +CBlock *CTaskManager::RecallTask(void) { + CTask *task; - task = PopTask( POP_BACK ); + task = PopTask(POP_BACK); - if ( task ) - { - // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) - CBlock* retBlock = task->GetBlock(); + if (task) { + // fixed 2/12/2 to free the task that has been popped (called from sequencer Recall) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; - // return task->GetBlock(); + // return task->GetBlock(); } return NULL; @@ -987,12 +890,10 @@ PushTask ------------------------- */ -int CTaskManager::PushTask( CTask *task, int flag ) -{ - assert( (flag == PUSH_FRONT) || (flag == PUSH_BACK) ); +int CTaskManager::PushTask(CTask *task, int flag) { + assert((flag == PUSH_FRONT) || (flag == PUSH_BACK)); - switch ( flag ) - { + switch (flag) { case PUSH_FRONT: m_tasks.insert(m_tasks.begin(), task); @@ -1006,7 +907,7 @@ int CTaskManager::PushTask( CTask *task, int flag ) break; } - //Invalid flag + // Invalid flag return SEQ_FAILED; } @@ -1016,17 +917,15 @@ PopTask ------------------------- */ -CTask *CTaskManager::PopTask( int flag ) -{ - CTask *task; +CTask *CTaskManager::PopTask(int flag) { + CTask *task; - assert( (flag == POP_FRONT) || (flag == POP_BACK) ); + assert((flag == POP_FRONT) || (flag == POP_BACK)); - if ( m_tasks.empty() ) + if (m_tasks.empty()) return NULL; - switch ( flag ) - { + switch (flag) { case POP_FRONT: task = m_tasks.front(); m_tasks.pop_front(); @@ -1042,7 +941,7 @@ CTask *CTaskManager::PopTask( int flag ) break; } - //Invalid flag + // Invalid flag return NULL; } @@ -1052,18 +951,17 @@ GetCurrentTask ------------------------- */ -CBlock *CTaskManager::GetCurrentTask( void ) -{ - CTask *task = PopTask( POP_BACK ); +CBlock *CTaskManager::GetCurrentTask(void) { + CTask *task = PopTask(POP_BACK); - if ( task == NULL ) + if (task == NULL) return NULL; -// fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) - CBlock* retBlock = task->GetBlock(); + // fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt) + CBlock *retBlock = task->GetBlock(); task->Free(); return retBlock; -// return task->GetBlock(); + // return task->GetBlock(); } /* @@ -1074,77 +972,65 @@ CBlock *CTaskManager::GetCurrentTask( void ) ================================================= */ -int CTaskManager::Wait( CTask *task, bool &completed ) -{ - CBlockMember *bm; - CBlock *block = task->GetBlock(); - char *sVal; - float dwtime; - int memberNum = 0; +int CTaskManager::Wait(CTask *task, bool &completed) { + CBlockMember *bm; + CBlock *block = task->GetBlock(); + char *sVal; + float dwtime; + int memberNum = 0; completed = false; - bm = block->GetMember( 0 ); + bm = block->GetMember(0); - //Check if this is a task completion wait - if ( bm->GetID() == TK_STRING ) - { - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + // Check if this is a task completion wait + if (bm->GetID() == TK_STRING) { + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - CTaskGroup *group = GetTaskGroup( sVal ); + CTaskGroup *group = GetTaskGroup(sVal); - if ( group == NULL ) - { - //TODO: Emit warning + if (group == NULL) { + // TODO: Emit warning completed = false; return TASK_FAILED; } completed = group->Complete(); - } - else //Otherwise it's a time completion wait + } else // Otherwise it's a time completion wait { - if ( Check( ID_RANDOM, block, memberNum ) ) - {//get it random only the first time - float min, max; + if (Check(ID_RANDOM, block, memberNum)) { // get it random only the first time + float min, max; - dwtime = *(float *) block->GetMemberData( memberNum++ ); - if ( dwtime == Q3_INFINITE ) - {//we have not evaluated this random yet - min = *(float *) block->GetMemberData( memberNum++ ); - max = *(float *) block->GetMemberData( memberNum++ ); + dwtime = *(float *)block->GetMemberData(memberNum++); + if (dwtime == Q3_INFINITE) { // we have not evaluated this random yet + min = *(float *)block->GetMemberData(memberNum++); + max = *(float *)block->GetMemberData(memberNum++); - dwtime = (m_owner->GetInterface())->I_Random( min, max ); + dwtime = (m_owner->GetInterface())->I_Random(min, max); - //store the result in the first member - bm->SetData( &dwtime, sizeof( dwtime ) ); + // store the result in the first member + bm->SetData(&dwtime, sizeof(dwtime)); } - } - else - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, dwtime ) ); + } else { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, dwtime)); } - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int) dwtime, task->GetTimeStamp() ); + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int)dwtime, task->GetTimeStamp()); } - if ( (task->GetTimeStamp() + dwtime) < ((m_owner->GetInterface())->I_GetTime()) ) - { + if ((task->GetTimeStamp() + dwtime) < ((m_owner->GetInterface())->I_GetTime())) { completed = true; memberNum = 0; - if ( Check( ID_RANDOM, block, memberNum ) ) - {//set the data back to 0 so it will be re-randomized next time + if (Check(ID_RANDOM, block, memberNum)) { // set the data back to 0 so it will be re-randomized next time dwtime = Q3_INFINITE; - bm->SetData( &dwtime, sizeof( dwtime ) ); + bm->SetData(&dwtime, sizeof(dwtime)); } } } @@ -1158,26 +1044,23 @@ WaitSignal ------------------------- */ -int CTaskManager::WaitSignal( CTask *task, bool &completed ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::WaitSignal(CTask *task, bool &completed) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; completed = false; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() ) - { - //Print out the debug info - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + if (task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime()) { + // Print out the debug info + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); } - if ( (m_owner->GetOwner())->CheckSignal( sVal ) ) - { + if ((m_owner->GetOwner())->CheckSignal(sVal)) { completed = true; - (m_owner->GetOwner())->ClearSignal( sVal ); + (m_owner->GetOwner())->ClearSignal(sVal); } return TASK_OK; @@ -1189,19 +1072,18 @@ Print ------------------------- */ -int CTaskManager::Print( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Print(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); - (m_owner->GetInterface())->I_CenterPrint( sVal ); + (m_owner->GetInterface())->I_CenterPrint(sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1212,20 +1094,19 @@ Sound ------------------------- */ -int CTaskManager::Sound( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Sound(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); - //Only instantly complete if the user has requested it - if( (m_owner->GetInterface())->I_PlaySound( task->GetGUID(), m_ownerID, sVal2, sVal ) ) - Completed( task->GetGUID() ); + // Only instantly complete if the user has requested it + if ((m_owner->GetInterface())->I_PlaySound(task->GetGUID(), m_ownerID, sVal2, sVal)) + Completed(task->GetGUID()); return TASK_OK; } @@ -1236,41 +1117,37 @@ Rotate ------------------------- */ -int CTaskManager::Rotate( CTask *task ) -{ - vector_t vector; - CBlock *block = task->GetBlock(); - char *tagName; - float tagLookup, duration; - int memberNum = 0; +int CTaskManager::Rotate(CTask *task) { + vector_t vector; + CBlock *block = task->GetBlock(); + char *tagName; + float tagLookup, duration; + int memberNum = 0; - //Check for a tag reference - if ( Check( ID_TAG, block, memberNum ) ) - { + // Check for a tag reference + if (Check(ID_TAG, block, memberNum)) { memberNum++; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &tagName ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, tagLookup ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &tagName)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, tagLookup)); - if ( (m_owner->GetInterface())->I_GetTag( m_ownerID, tagName, (int) tagLookup, vector ) == false ) - { - //TODO: Emit warning - (m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName ); + if ((m_owner->GetInterface())->I_GetTag(m_ownerID, tagName, (int)tagLookup, vector) == false) { + // TODO: Emit warning + (m_owner->GetInterface())->I_DPrintf(WL_ERROR, "Unable to find tag \"%s\"!\n", tagName); assert(0); return TASK_FAILED; } - } - else - { - //Get a normal vector - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); + } else { + // Get a normal vector + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); } - //Find the duration - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); + // Find the duration + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int) duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Angles( task->GetGUID(), m_ownerID, vector, duration ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int)duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Angles(task->GetGUID(), m_ownerID, vector, duration); return TASK_OK; } @@ -1281,18 +1158,17 @@ Remove ------------------------- */ -int CTaskManager::Remove( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Remove(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Remove( m_ownerID, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Remove(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1303,130 +1179,133 @@ Camera ------------------------- */ -int CTaskManager::Camera( CTask *task ) -{ - interface_export_t *ie = ( m_owner->GetInterface() ); - CBlock *block = task->GetBlock(); - vector_t vector, vector2; - float type, fVal, fVal2, fVal3; - char *sVal; - int memberNum = 0; +int CTaskManager::Camera(CTask *task) { + interface_export_t *ie = (m_owner->GetInterface()); + CBlock *block = task->GetBlock(); + vector_t vector, vector2; + float type, fVal, fVal2, fVal3; + char *sVal; + int memberNum = 0; - //Get the camera function type - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, type ) ); + // Get the camera function type + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, type)); - switch ( (int) type ) - { + switch ((int)type) { case TYPE_PAN: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2)); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], fVal, task->GetTimeStamp() ); - ie->I_CameraPan( vector, vector2, fVal ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], + vector2[2], fVal, task->GetTimeStamp()); + ie->I_CameraPan(vector, vector2, fVal); break; case TYPE_ZOOM: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraZoom( fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraZoom(fVal, fVal2); break; case TYPE_MOVE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp() ); - ie->I_CameraMove( vector, fVal ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp()); + ie->I_CameraMove(vector, fVal); break; case TYPE_ROLL: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraRoll( fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraRoll(fVal, fVal2); break; case TYPE_FOLLOW: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraFollow( (const char *) sVal, fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraFollow((const char *)sVal, fVal, fVal2); break; case TYPE_TRACK: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraTrack( (const char *) sVal, fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraTrack((const char *)sVal, fVal, fVal2); break; case TYPE_DISTANCE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraDistance( fVal, fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraDistance(fVal, fVal2); break; case TYPE_FADE: - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector2)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal3 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal3)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp() ); - ie->I_CameraFade( vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3 ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], + vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp()); + ie->I_CameraFade(vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3); break; case TYPE_PATH: - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - ie->I_CameraPath( sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + ie->I_CameraPath(sVal); break; case TYPE_ENABLE: - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp()); ie->I_CameraEnable(); break; case TYPE_DISABLE: - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp() ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp()); ie->I_CameraDisable(); break; case TYPE_SHAKE: - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() ); - ie->I_CameraShake( fVal, (int) fVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp()); + ie->I_CameraShake(fVal, (int)fVal2); break; } - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1437,33 +1316,33 @@ Move ------------------------- */ -int CTaskManager::Move( CTask *task ) -{ - vector_t vector, vector2; - CBlock *block = task->GetBlock(); - float duration; - int memberNum = 0; +int CTaskManager::Move(CTask *task) { + vector_t vector, vector2; + CBlock *block = task->GetBlock(); + float duration; + int memberNum = 0; - //Get the goal position - ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) ); - - //Check for possible angles field - if ( GetVector( m_ownerID, block, memberNum, vector2 ) == false ) - { - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); + // Get the goal position + ICARUS_VALIDATE(GetVector(m_ownerID, block, memberNum, vector)); + // Check for possible angles field + if (GetVector(m_ownerID, block, memberNum, vector2) == false) { + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, NULL, duration ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Pos(task->GetGUID(), m_ownerID, vector, NULL, duration); return TASK_OK; } - //Get the duration and make the call - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) ); + // Get the duration and make the call + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, duration)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], duration, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, vector2, duration ); + (m_owner->GetInterface()) + ->I_DPrintf(WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], + duration, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Lerp2Pos(task->GetGUID(), m_ownerID, vector, vector2, duration); return TASK_OK; } @@ -1474,18 +1353,17 @@ Kill ------------------------- */ -int CTaskManager::Kill( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Kill(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Kill( m_ownerID, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Kill(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1496,17 +1374,16 @@ Set ------------------------- */ -int CTaskManager::Set( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Set(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Set( task->GetGUID(), m_ownerID, sVal, sVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Set(task->GetGUID(), m_ownerID, sVal, sVal2); return TASK_OK; } @@ -1517,18 +1394,17 @@ Use ------------------------- */ -int CTaskManager::Use( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Use(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Use( m_ownerID, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Use(m_ownerID, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1539,23 +1415,21 @@ DeclareVariable ------------------------- */ -int CTaskManager::DeclareVariable( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; - float fVal; +int CTaskManager::DeclareVariable(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; + float fVal; - ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(GetFloat(m_ownerID, block, memberNum, fVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int) fVal, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_DeclareVariable( (int) fVal, sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int)fVal, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_DeclareVariable((int)fVal, sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1564,21 +1438,19 @@ FreeVariable ------------------------- */ -int CTaskManager::FreeVariable( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::FreeVariable(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_FreeVariable( sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + (m_owner->GetInterface())->I_FreeVariable(sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; - } /* @@ -1587,18 +1459,17 @@ Signal ------------------------- */ -int CTaskManager::Signal( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal; - int memberNum = 0; +int CTaskManager::Signal(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() ); - m_owner->GetOwner()->Signal( (const char *) sVal ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp()); + m_owner->GetOwner()->Signal((const char *)sVal); - Completed( task->GetGUID() ); + Completed(task->GetGUID()); return TASK_OK; } @@ -1609,17 +1480,16 @@ Play ------------------------- */ -int CTaskManager::Play( CTask *task ) -{ - CBlock *block = task->GetBlock(); - char *sVal, *sVal2; - int memberNum = 0; +int CTaskManager::Play(CTask *task) { + CBlock *block = task->GetBlock(); + char *sVal, *sVal2; + int memberNum = 0; - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) ); - ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) ); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal)); + ICARUS_VALIDATE(Get(m_ownerID, block, memberNum, &sVal2)); - (m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() ); - (m_owner->GetInterface())->I_Play( task->GetGUID(), m_ownerID, (const char *) sVal, (const char *) sVal2 ); + (m_owner->GetInterface())->I_DPrintf(WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp()); + (m_owner->GetInterface())->I_Play(task->GetGUID(), m_ownerID, (const char *)sVal, (const char *)sVal2); return TASK_OK; } @@ -1630,40 +1500,38 @@ SaveCommand ------------------------- */ -//FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... +// FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way... -int CTaskManager::SaveCommand( CBlock *block ) -{ - unsigned char flags; - int numMembers, bID, size; - CBlockMember *bm; +int CTaskManager::SaveCommand(CBlock *block) { + unsigned char flags; + int numMembers, bID, size; + CBlockMember *bm; - //Save out the block ID + // Save out the block ID bID = block->GetBlockID(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','L','I','D'), &bID, sizeof ( bID ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'L', 'I', 'D'), &bID, sizeof(bID)); - //Save out the block's flags + // Save out the block's flags flags = block->GetFlags(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','F','L','G'), &flags, sizeof ( flags ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'F', 'L', 'G'), &flags, sizeof(flags)); - //Save out the number of members to read + // Save out the number of members to read numMembers = block->GetNumMembers(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','N','U','M'), &numMembers, sizeof ( numMembers ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'N', 'U', 'M'), &numMembers, sizeof(numMembers)); - for ( int i = 0; i < numMembers; i++ ) - { - bm = block->GetMember( i ); + for (int i = 0; i < numMembers; i++) { + bm = block->GetMember(i); - //Save the block id + // Save the block id bID = bm->GetID(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','M','I','D'), &bID, sizeof ( bID ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'M', 'I', 'D'), &bID, sizeof(bID)); - //Save out the data size + // Save out the data size size = bm->GetSize(); - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','S','I','Z'), &size, sizeof( size ) ); + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'S', 'I', 'Z'), &size, sizeof(size)); - //Save out the raw data - (m_owner->GetInterface())->I_WriteSaveData( INT_ID('B','M','E','M'), bm->GetData(), size ); + // Save out the raw data + (m_owner->GetInterface())->I_WriteSaveData(INT_ID('B', 'M', 'E', 'M'), bm->GetData(), size); } return true; @@ -1675,8 +1543,7 @@ Save ------------------------- */ -void CTaskManager::Save( void ) -{ +void CTaskManager::Save(void) { #if 0 CTaskGroup *taskGroup; const char *name; @@ -1802,8 +1669,7 @@ Load ------------------------- */ -void CTaskManager::Load( void ) -{ +void CTaskManager::Load(void) { #if 0 unsigned char flags; CTaskGroup *taskGroup; diff --git a/codemp/icarus/Tokenizer.cpp b/codemp/icarus/Tokenizer.cpp index 83248b7b41..be9d2acfad 100644 --- a/codemp/icarus/Tokenizer.cpp +++ b/codemp/icarus/Tokenizer.cpp @@ -9,18 +9,17 @@ #endif #include "tokenizer.h" -#pragma warning(disable : 4100) //unreferenced formal parameter -#pragma warning(disable : 4127) //conditional expression is constant -#pragma warning(disable : 4189) //local variable is initialized but not referenced -#pragma warning(disable : 4244) //conversion from x to x, possible loss of data +#pragma warning(disable : 4100) // unreferenced formal parameter +#pragma warning(disable : 4127) // conditional expression is constant +#pragma warning(disable : 4189) // local variable is initialized but not referenced +#pragma warning(disable : 4244) // conversion from x to x, possible loss of data #ifndef _WIN32 #include #include #endif -enum -{ +enum { DIR_INCLUDE = TK_USERDEF, DIR_IFDEF, DIR_IFNDEF, @@ -30,78 +29,77 @@ enum DIR_UNDEFINE, }; -keywordArray_t CTokenizer::directiveKeywords[] = -{ - "include", DIR_INCLUDE, - "ifdef", DIR_IFDEF, - "ifndef", DIR_IFNDEF, - "endif", DIR_ENDIF, - "else", DIR_ELSE, - "define", DIR_DEFINE, - "undefine", DIR_UNDEFINE, - "", TK_EOF, +keywordArray_t CTokenizer::directiveKeywords[] = { + "include", DIR_INCLUDE, "ifdef", DIR_IFDEF, "ifndef", DIR_IFNDEF, "endif", DIR_ENDIF, + "else", DIR_ELSE, "define", DIR_DEFINE, "undefine", DIR_UNDEFINE, "", TK_EOF, }; -keywordArray_t CTokenizer::errorMessages[] = -{ - "No Error", TKERR_NONE, - "Unknown Error", TKERR_UNKNOWN, - "Buffer creation failed", TKERR_BUFFERCREATE, - "Unrecognized symbol", TKERR_UNRECOGNIZEDSYMBOL, - "Duplicate symbol", TKERR_DUPLICATESYMBOL, - "String length exceeded", TKERR_STRINGLENGTHEXCEEDED, - "Identifier length exceeded", TKERR_IDENTIFIERLENGTHEXCEEDED, - "Expected integer", TKERR_EXPECTED_INTEGER, - "Expected identifier", TKERR_EXPECTED_IDENTIFIER, - "Expected string", TKERR_EXPECTED_STRING, - "Expected char", TKERR_EXPECTED_CHAR, - "Expected float", TKERR_EXPECTED_FLOAT, - "Unexpected token", TKERR_UNEXPECTED_TOKEN, - "Invalid directive", TKERR_INVALID_DIRECTIVE, - "Include file not found", TKERR_INCLUDE_FILE_NOTFOUND, - "Unmatched directive", TKERR_UNMATCHED_DIRECTIVE, - "", TKERR_USERERROR, +keywordArray_t CTokenizer::errorMessages[] = { + "No Error", + TKERR_NONE, + "Unknown Error", + TKERR_UNKNOWN, + "Buffer creation failed", + TKERR_BUFFERCREATE, + "Unrecognized symbol", + TKERR_UNRECOGNIZEDSYMBOL, + "Duplicate symbol", + TKERR_DUPLICATESYMBOL, + "String length exceeded", + TKERR_STRINGLENGTHEXCEEDED, + "Identifier length exceeded", + TKERR_IDENTIFIERLENGTHEXCEEDED, + "Expected integer", + TKERR_EXPECTED_INTEGER, + "Expected identifier", + TKERR_EXPECTED_IDENTIFIER, + "Expected string", + TKERR_EXPECTED_STRING, + "Expected char", + TKERR_EXPECTED_CHAR, + "Expected float", + TKERR_EXPECTED_FLOAT, + "Unexpected token", + TKERR_UNEXPECTED_TOKEN, + "Invalid directive", + TKERR_INVALID_DIRECTIVE, + "Include file not found", + TKERR_INCLUDE_FILE_NOTFOUND, + "Unmatched directive", + TKERR_UNMATCHED_DIRECTIVE, + "", + TKERR_USERERROR, }; // // CSymbol // -CSymbol::CSymbol() -{ -} +CSymbol::CSymbol() {} -CSymbol::~CSymbol() -{ -} +CSymbol::~CSymbol() {} -CSymbol* CSymbol::Create(LPCTSTR symbolName) -{ - CSymbol* retval = new CSymbol(); +CSymbol *CSymbol::Create(LPCTSTR symbolName) { + CSymbol *retval = new CSymbol(); retval->Init(symbolName); return retval; } -LPCTSTR CSymbol::GetName() -{ - if (m_symbolName == NULL) - { +LPCTSTR CSymbol::GetName() { + if (m_symbolName == NULL) { return ""; } return m_symbolName; } -void CSymbol::InitBaseSymbol(LPCTSTR symbolName) -{ - m_symbolName = (char*)malloc(strlen(symbolName) + 1); -// ASSERT(m_symbolName); +void CSymbol::InitBaseSymbol(LPCTSTR symbolName) { + m_symbolName = (char *)malloc(strlen(symbolName) + 1); + // ASSERT(m_symbolName); strcpy(m_symbolName, symbolName); } -void CSymbol::Delete() -{ - if (m_symbolName != NULL) - { +void CSymbol::Delete() { + if (m_symbolName != NULL) { free(m_symbolName); m_symbolName = NULL; } @@ -112,258 +110,174 @@ void CSymbol::Delete() // CDirectiveSymbol // -CDirectiveSymbol::CDirectiveSymbol() -{ -} +CDirectiveSymbol::CDirectiveSymbol() {} -CDirectiveSymbol::~CDirectiveSymbol() -{ -} +CDirectiveSymbol::~CDirectiveSymbol() {} -CDirectiveSymbol* CDirectiveSymbol::Create(LPCTSTR symbolName) -{ - CDirectiveSymbol* retval = new CDirectiveSymbol(); +CDirectiveSymbol *CDirectiveSymbol::Create(LPCTSTR symbolName) { + CDirectiveSymbol *retval = new CDirectiveSymbol(); retval->Init(symbolName); return retval; } -void CDirectiveSymbol::Init(LPCTSTR symbolName) -{ +void CDirectiveSymbol::Init(LPCTSTR symbolName) { CSymbol::InitBaseSymbol(symbolName); m_value = NULL; } -void CDirectiveSymbol::Delete() -{ - if (m_value != NULL) - { +void CDirectiveSymbol::Delete() { + if (m_value != NULL) { free(m_value); m_value = NULL; } CSymbol::Delete(); } -void CDirectiveSymbol::SetValue(LPCTSTR value) -{ - if (m_value != NULL) - { +void CDirectiveSymbol::SetValue(LPCTSTR value) { + if (m_value != NULL) { free(m_value); } - m_value = (char*)malloc(strlen(value) + 1); + m_value = (char *)malloc(strlen(value) + 1); strcpy(m_value, value); } -LPCTSTR CDirectiveSymbol::GetValue() -{ - return m_value; -} +LPCTSTR CDirectiveSymbol::GetValue() { return m_value; } // // CIntSymbol // -CIntSymbol::CIntSymbol() -{ -} +CIntSymbol::CIntSymbol() {} -CIntSymbol* CIntSymbol::Create(LPCTSTR symbolName, int value) -{ - CIntSymbol* retval = new CIntSymbol(); +CIntSymbol *CIntSymbol::Create(LPCTSTR symbolName, int value) { + CIntSymbol *retval = new CIntSymbol(); retval->Init(symbolName, value); return retval; } -void CIntSymbol::Delete() -{ - CSymbol::Delete(); -} +void CIntSymbol::Delete() { CSymbol::Delete(); } -void CIntSymbol::Init(LPCTSTR symbolName, int value) -{ +void CIntSymbol::Init(LPCTSTR symbolName, int value) { CSymbol::InitBaseSymbol(symbolName); m_value = value; } -int CIntSymbol::GetValue() -{ - return m_value; -} +int CIntSymbol::GetValue() { return m_value; } // // CSymbolTable // -CSymbolTable::CSymbolTable() -{ - Init(); -} +CSymbolTable::CSymbolTable() { Init(); } -CSymbolTable::~CSymbolTable() -{ -} +CSymbolTable::~CSymbolTable() {} -CSymbolTable* CSymbolTable::Create() -{ - CSymbolTable* retval = new CSymbolTable(); +CSymbolTable *CSymbolTable::Create() { + CSymbolTable *retval = new CSymbolTable(); retval->Init(); return retval; } -void CSymbolTable::Init() -{ -} +void CSymbolTable::Init() {} -void CSymbolTable::DiscardSymbols() -{ - for (symbolmap_t::iterator isymbol = m_symbols.begin(); isymbol != m_symbols.end(); ++isymbol) - { +void CSymbolTable::DiscardSymbols() { + for (symbolmap_t::iterator isymbol = m_symbols.begin(); isymbol != m_symbols.end(); ++isymbol) { (*isymbol).second->Delete(); } m_symbols.erase(m_symbols.begin(), m_symbols.end()); } -void CSymbolTable::Delete() -{ +void CSymbolTable::Delete() { DiscardSymbols(); delete this; } -bool CSymbolTable::AddSymbol(CSymbol* theSymbol) -{ +bool CSymbolTable::AddSymbol(CSymbol *theSymbol) { LPCTSTR name = theSymbol->GetName(); symbolmap_t::iterator iter = m_symbols.find(name); - if (iter != m_symbols.end()) - { + if (iter != m_symbols.end()) { return false; } m_symbols.insert(symbolmap_t::value_type(name, theSymbol)); return true; } -CSymbol* CSymbolTable::FindSymbol(LPCTSTR symbolName) -{ +CSymbol *CSymbolTable::FindSymbol(LPCTSTR symbolName) { symbolmap_t::iterator iter = m_symbols.find(symbolName); - if (iter != m_symbols.end()) - { + if (iter != m_symbols.end()) { return (*iter).second; } return NULL; } -CSymbol* CSymbolTable::ExtractSymbol(LPCTSTR symbolName) -{ +CSymbol *CSymbolTable::ExtractSymbol(LPCTSTR symbolName) { symbolmap_t::iterator iter = m_symbols.find(symbolName); - if (iter != m_symbols.end()) - { - CSymbol* retval = (*iter).second; + if (iter != m_symbols.end()) { + CSymbol *retval = (*iter).second; m_symbols.erase(iter); } return NULL; } -void CSymbolTable::RemoveSymbol(LPCTSTR symbolName) -{ - m_symbols.erase(symbolName); -} +void CSymbolTable::RemoveSymbol(LPCTSTR symbolName) { m_symbols.erase(symbolName); } // // CParseStream // -CParseStream::CParseStream() -{ -} +CParseStream::CParseStream() {} -CParseStream::~CParseStream() -{ -} +CParseStream::~CParseStream() {} -CParseStream* CParseStream::Create() -{ - return NULL; -} +CParseStream *CParseStream::Create() { return NULL; } -void CParseStream::Delete() -{ - delete this; -} +void CParseStream::Delete() { delete this; } -bool CParseStream::InitBaseStream() -{ +bool CParseStream::InitBaseStream() { m_next = NULL; return true; } -bool CParseStream::NextChar(byte& theByte) -{ - return false; -} +bool CParseStream::NextChar(byte &theByte) { return false; } -long CParseStream::GetRemainingSize() -{ - return 0; -} +long CParseStream::GetRemainingSize() { return 0; } -CParseStream* CParseStream::GetNext() -{ - return m_next; -} +CParseStream *CParseStream::GetNext() { return m_next; } -void CParseStream::SetNext(CParseStream* next) -{ - m_next = next; -} +void CParseStream::SetNext(CParseStream *next) { m_next = next; } -int CParseStream::GetCurLine() -{ - return 0; -} +int CParseStream::GetCurLine() { return 0; } -void CParseStream::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseStream::GetCurFilename(char **theBuff) { *theBuff = NULL; } -bool CParseStream::IsThisDefinition(void* theDefinition) -{ - return false; -} +bool CParseStream::IsThisDefinition(void *theDefinition) { return false; } // // CParsePutBack // -CParsePutBack::CParsePutBack() -{ -} +CParsePutBack::CParsePutBack() {} -CParsePutBack::~CParsePutBack() -{ -} +CParsePutBack::~CParsePutBack() {} -CParsePutBack* CParsePutBack::Create(byte theByte, int curLine, LPCTSTR filename) -{ - CParsePutBack* curParsePutBack = new CParsePutBack(); +CParsePutBack *CParsePutBack::Create(byte theByte, int curLine, LPCTSTR filename) { + CParsePutBack *curParsePutBack = new CParsePutBack(); curParsePutBack->Init(theByte, curLine, filename); return curParsePutBack; } -void CParsePutBack::Delete() -{ - if (m_curFile != NULL) - { +void CParsePutBack::Delete() { + if (m_curFile != NULL) { free(m_curFile); m_curFile = NULL; } delete this; } -bool CParsePutBack::NextChar(byte& theByte) -{ - if (m_consumed) - { +bool CParsePutBack::NextChar(byte &theByte) { + if (m_consumed) { return false; } theByte = m_byte; @@ -371,48 +285,35 @@ bool CParsePutBack::NextChar(byte& theByte) return true; } -void CParsePutBack::Init(byte theByte, int curLine, LPCTSTR filename) -{ +void CParsePutBack::Init(byte theByte, int curLine, LPCTSTR filename) { CParseStream::InitBaseStream(); m_consumed = false; m_byte = theByte; m_curLine = curLine; - if (filename != NULL) - { - m_curFile = (char*)malloc(strlen(filename) + 1); + if (filename != NULL) { + m_curFile = (char *)malloc(strlen(filename) + 1); strcpy(m_curFile, filename); - } - else - { + } else { m_curFile = NULL; } } -long CParsePutBack::GetRemainingSize() -{ - if (m_consumed) - { +long CParsePutBack::GetRemainingSize() { + if (m_consumed) { return 0; - } - else - { + } else { return 1; } } -int CParsePutBack::GetCurLine() -{ - return m_curLine; -} +int CParsePutBack::GetCurLine() { return m_curLine; } -void CParsePutBack::GetCurFilename(char** theBuff) -{ - if (m_curFile == NULL) - { +void CParsePutBack::GetCurFilename(char **theBuff) { + if (m_curFile == NULL) { *theBuff = NULL; return; } - *theBuff = (char*)malloc(strlen(m_curFile) + 1); + *theBuff = (char *)malloc(strlen(m_curFile) + 1); strcpy(*theBuff, m_curFile); } @@ -420,20 +321,14 @@ void CParsePutBack::GetCurFilename(char** theBuff) // CParseFile // -CParseFile::CParseFile() -{ -} +CParseFile::CParseFile() {} -CParseFile::~CParseFile() -{ -} +CParseFile::~CParseFile() {} -CParseFile* CParseFile::Create() -{ - CParseFile* theParseFile = new CParseFile(); +CParseFile *CParseFile::Create() { + CParseFile *theParseFile = new CParseFile(); - if ( !theParseFile->Init() ) - { + if (!theParseFile->Init()) { delete theParseFile; return NULL; } @@ -441,25 +336,21 @@ CParseFile* CParseFile::Create() return theParseFile; } -CParseFile* CParseFile::Create(LPCTSTR filename, CTokenizer* tokenizer) -{ - CParseFile* theParseFile = new CParseFile(); +CParseFile *CParseFile::Create(LPCTSTR filename, CTokenizer *tokenizer) { + CParseFile *theParseFile = new CParseFile(); - if ( theParseFile->Init(filename, tokenizer) ) + if (theParseFile->Init(filename, tokenizer)) return theParseFile; return NULL; } -void CParseFile::Delete() -{ - if (m_buff != NULL) - { +void CParseFile::Delete() { + if (m_buff != NULL) { free(m_buff); m_buff = NULL; } - if (m_ownsFile && (m_fileHandle != NULL)) - { + if (m_ownsFile && (m_fileHandle != NULL)) { #ifdef _WIN32 CloseHandle(m_fileHandle); #else @@ -467,16 +358,14 @@ void CParseFile::Delete() #endif m_fileHandle = NULL; } - if (m_fileName != NULL) - { + if (m_fileName != NULL) { free(m_fileName); m_fileName = NULL; } delete this; } -bool CParseFile::Init() -{ +bool CParseFile::Init() { m_fileHandle = NULL; m_buff = NULL; m_ownsFile = false; @@ -486,8 +375,7 @@ bool CParseFile::Init() return CParseStream::InitBaseStream(); } -unsigned int CParseFile::GetFileSize() -{ +unsigned int CParseFile::GetFileSize() { #ifdef _WIN32 unsigned int dwCur = SetFilePointer(m_fileHandle, 0L, NULL, FILE_CURRENT); unsigned int dwLen = SetFilePointer(m_fileHandle, 0, NULL, FILE_END); @@ -500,8 +388,7 @@ unsigned int CParseFile::GetFileSize() return dwLen; } -void CParseFile::Read(void* buff, UINT buffsize) -{ +void CParseFile::Read(void *buff, UINT buffsize) { unsigned int bytesRead; #ifdef _WIN32 ReadFile(m_fileHandle, buff, buffsize, &bytesRead, NULL); @@ -510,96 +397,77 @@ void CParseFile::Read(void* buff, UINT buffsize) #endif } -bool CParseFile::Init(LPCTSTR filename, CTokenizer* tokenizer) -{ +bool CParseFile::Init(LPCTSTR filename, CTokenizer *tokenizer) { CParseStream::InitBaseStream(); - m_fileName = (char*)malloc(strlen(filename) + 1); + m_fileName = (char *)malloc(strlen(filename) + 1); strcpy(m_fileName, filename); #ifdef _WIN32 - unsigned int dwAccess = GENERIC_READ; - unsigned int dwShareMode = FILE_SHARE_WRITE | FILE_SHARE_READ; - SECURITY_ATTRIBUTES sa; - sa.nLength = sizeof(sa); - sa.lpSecurityDescriptor = NULL; - sa.bInheritHandle = 0; - unsigned int dwCreateFlag = OPEN_EXISTING; + unsigned int dwAccess = GENERIC_READ; + unsigned int dwShareMode = FILE_SHARE_WRITE | FILE_SHARE_READ; + SECURITY_ATTRIBUTES sa; + sa.nLength = sizeof(sa); + sa.lpSecurityDescriptor = NULL; + sa.bInheritHandle = 0; + unsigned int dwCreateFlag = OPEN_EXISTING; - m_fileHandle = CreateFile(filename, dwAccess, dwShareMode, &sa, dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL); + m_fileHandle = CreateFile(filename, dwAccess, dwShareMode, &sa, dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL); - if (m_fileHandle == (HANDLE)-1) - { - tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); - Init(); + if (m_fileHandle == (HANDLE)-1) { + tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); + Init(); - return false; - } + return false; + } #else - m_fileHandle = fopen(filename, "r+"); + m_fileHandle = fopen(filename, "r+"); - if (m_fileHandle == NULL) - { - tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); - Init(); + if (m_fileHandle == NULL) { + tokenizer->Error(TKERR_INCLUDE_FILE_NOTFOUND); + Init(); - return false; - } + return false; + } #endif - m_filesize = GetFileSize(); - m_buff = (byte*)malloc(m_filesize); - if (m_buff == NULL) - { - tokenizer->Error(TKERR_BUFFERCREATE); - Init(); - return false; - } - Read(m_buff, m_filesize); - m_curByte = 0; - m_curPos = 1; - m_ownsFile = true; - m_curLine = 1; + m_filesize = GetFileSize(); + m_buff = (byte *)malloc(m_filesize); + if (m_buff == NULL) { + tokenizer->Error(TKERR_BUFFERCREATE); + Init(); + return false; + } + Read(m_buff, m_filesize); + m_curByte = 0; + m_curPos = 1; + m_ownsFile = true; + m_curLine = 1; return true; } -long CParseFile::GetRemainingSize() -{ - return m_filesize - m_curByte; -} +long CParseFile::GetRemainingSize() { return m_filesize - m_curByte; } -bool CParseFile::NextChar(byte& theByte) -{ - if (m_curByte < m_filesize) - { - if (m_buff[m_curByte] == '\n') - { +bool CParseFile::NextChar(byte &theByte) { + if (m_curByte < m_filesize) { + if (m_buff[m_curByte] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_buff[m_curByte++]; return true; - } - else - { + } else { return false; } } -int CParseFile::GetCurLine() -{ - return m_curLine; -} +int CParseFile::GetCurLine() { return m_curLine; } -void CParseFile::GetCurFilename(char** theBuff) -{ +void CParseFile::GetCurFilename(char **theBuff) { *theBuff = NULL; - if (m_fileName != NULL) - { - *theBuff = (char*)malloc(strlen(m_fileName) + 1); + if (m_fileName != NULL) { + *theBuff = (char *)malloc(strlen(m_fileName) + 1); strcpy(*theBuff, m_fileName); } } @@ -608,50 +476,34 @@ void CParseFile::GetCurFilename(char** theBuff) // CParseMemory // -CParseMemory::CParseMemory() -{ -} +CParseMemory::CParseMemory() {} -CParseMemory::~CParseMemory() -{ -} +CParseMemory::~CParseMemory() {} -CParseMemory* CParseMemory::Create(byte* data, long datasize) -{ - CParseMemory* curParse = new CParseMemory(); +CParseMemory *CParseMemory::Create(byte *data, long datasize) { + CParseMemory *curParse = new CParseMemory(); curParse->Init(data, datasize); return curParse; } -void CParseMemory::Delete() -{ - delete this; -} +void CParseMemory::Delete() { delete this; } -bool CParseMemory::NextChar(byte& theByte) -{ - if (m_offset < m_datasize) - { - if (m_data[m_offset] == '\n') - { +bool CParseMemory::NextChar(byte &theByte) { + if (m_offset < m_datasize) { + if (m_data[m_offset] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_data[m_offset++]; return true; - } - else - { + } else { return false; } } -void CParseMemory::Init(byte* data, long datasize) -{ +void CParseMemory::Init(byte *data, long datasize) { m_data = data; m_curLine = 1; m_curPos = 1; @@ -659,53 +511,36 @@ void CParseMemory::Init(byte* data, long datasize) m_datasize = datasize; } -long CParseMemory::GetRemainingSize() -{ - return m_datasize - m_offset; -} +long CParseMemory::GetRemainingSize() { return m_datasize - m_offset; } -int CParseMemory::GetCurLine() -{ - return m_curLine; -} +int CParseMemory::GetCurLine() { return m_curLine; } -void CParseMemory::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseMemory::GetCurFilename(char **theBuff) { *theBuff = NULL; } // // CParseBlock // -CParseBlock::CParseBlock() -{ -} +CParseBlock::CParseBlock() {} -CParseBlock::~CParseBlock() -{ -} +CParseBlock::~CParseBlock() {} -CParseBlock* CParseBlock::Create(byte* data, long datasize) -{ - CParseBlock* curParse = new CParseBlock(); +CParseBlock *CParseBlock::Create(byte *data, long datasize) { + CParseBlock *curParse = new CParseBlock(); curParse->Init(data, datasize); return curParse; } -void CParseBlock::Delete() -{ - if (m_data != NULL) - { +void CParseBlock::Delete() { + if (m_data != NULL) { free(m_data); m_data = NULL; } delete this; } -void CParseBlock::Init(byte* data, long datasize) -{ - m_data = (byte*)malloc(datasize); +void CParseBlock::Init(byte *data, long datasize) { + m_data = (byte *)malloc(datasize); memcpy(m_data, data, datasize); m_curLine = 1; m_curPos = 1; @@ -717,64 +552,46 @@ void CParseBlock::Init(byte* data, long datasize) // CParseToken // -CParseToken::CParseToken() -{ -} +CParseToken::CParseToken() {} -CParseToken::~CParseToken() -{ -} +CParseToken::~CParseToken() {} -CParseToken* CParseToken::Create(CToken* token) -{ - CParseToken* curParse = new CParseToken(); +CParseToken *CParseToken::Create(CToken *token) { + CParseToken *curParse = new CParseToken(); curParse->Init(token); return curParse; } -void CParseToken::Delete() -{ - if (m_data != NULL) - { +void CParseToken::Delete() { + if (m_data != NULL) { free(m_data); m_data = NULL; } delete this; } -bool CParseToken::NextChar(byte& theByte) -{ - if (m_offset < m_datasize) - { - if (m_data[m_offset] == '\n') - { +bool CParseToken::NextChar(byte &theByte) { + if (m_offset < m_datasize) { + if (m_data[m_offset] == '\n') { m_curLine += 1; m_curPos = 1; - } - else - { + } else { m_curPos++; } theByte = m_data[m_offset++]; return true; - } - else - { + } else { return false; } } -void CParseToken::Init(CToken* token) -{ +void CParseToken::Init(CToken *token) { LPCTSTR tokenString = token->GetStringValue(); m_datasize = strlen(tokenString); - if (m_datasize > 0) - { - m_data = (byte*) malloc(m_datasize); + if (m_datasize > 0) { + m_data = (byte *)malloc(m_datasize); memcpy(m_data, tokenString, m_datasize); - } - else - { + } else { m_data = NULL; } m_curLine = 1; @@ -783,294 +600,203 @@ void CParseToken::Init(CToken* token) token->Delete(); } -long CParseToken::GetRemainingSize() -{ - return m_datasize - m_offset; -} +long CParseToken::GetRemainingSize() { return m_datasize - m_offset; } -int CParseToken::GetCurLine() -{ - return m_curLine; -} +int CParseToken::GetCurLine() { return m_curLine; } -void CParseToken::GetCurFilename(char** theBuff) -{ - *theBuff = NULL; -} +void CParseToken::GetCurFilename(char **theBuff) { *theBuff = NULL; } // // CParseDefine // -CParseDefine::CParseDefine() -{ -} +CParseDefine::CParseDefine() {} -CParseDefine::~CParseDefine() -{ -} +CParseDefine::~CParseDefine() {} -CParseDefine* CParseDefine::Create(CDirectiveSymbol* definesymbol) -{ - CParseDefine* retval = new CParseDefine(); +CParseDefine *CParseDefine::Create(CDirectiveSymbol *definesymbol) { + CParseDefine *retval = new CParseDefine(); retval->Init(definesymbol); return retval; } -void CParseDefine::Delete() -{ - CParseMemory::Delete(); -} +void CParseDefine::Delete() { CParseMemory::Delete(); } -void CParseDefine::Init(CDirectiveSymbol* definesymbol) -{ - CParseMemory::Init((byte*)definesymbol->GetValue(), strlen(definesymbol->GetValue())); +void CParseDefine::Init(CDirectiveSymbol *definesymbol) { + CParseMemory::Init((byte *)definesymbol->GetValue(), strlen(definesymbol->GetValue())); m_defineSymbol = definesymbol; } -bool CParseDefine::IsThisDefinition(void* theDefinition) -{ - return (CDirectiveSymbol*)theDefinition == m_defineSymbol; -} +bool CParseDefine::IsThisDefinition(void *theDefinition) { return (CDirectiveSymbol *)theDefinition == m_defineSymbol; } // // CToken // -CToken::CToken() -{ -} +CToken::CToken() {} -CToken::~CToken() -{ -} +CToken::~CToken() {} -CToken* CToken::Create() -{ - CToken* theToken = new CToken(); +CToken *CToken::Create() { + CToken *theToken = new CToken(); theToken->InitBaseToken(); return theToken; } -void CToken::Delete() -{ - if (m_string != NULL) - { +void CToken::Delete() { + if (m_string != NULL) { free(m_string); m_string = NULL; } delete this; } -void CToken::InitBaseToken() -{ +void CToken::InitBaseToken() { m_next = NULL; m_string = NULL; } -void CToken::SetNext(CToken* theToken) -{ - m_next = theToken; -} +void CToken::SetNext(CToken *theToken) { m_next = theToken; } -CToken* CToken::GetNext() -{ - return m_next; -} +CToken *CToken::GetNext() { return m_next; } -int CToken::GetType() -{ - return TK_EOF; -} +int CToken::GetType() { return TK_EOF; } -int CToken::GetIntValue() -{ - return 0; -} +int CToken::GetIntValue() { return 0; } -LPCTSTR CToken::GetStringValue() -{ - if (m_string == NULL) - { +LPCTSTR CToken::GetStringValue() { + if (m_string == NULL) { return ""; } return m_string; } -float CToken::GetFloatValue() -{ - return 0.0; -} +float CToken::GetFloatValue() { return 0.0; } // // CCharToken // -CCharToken::CCharToken() -{ -} +CCharToken::CCharToken() {} -CCharToken::~CCharToken() -{ -} +CCharToken::~CCharToken() {} -CCharToken* CCharToken::Create(byte theByte) -{ - CCharToken* theToken = new CCharToken(); +CCharToken *CCharToken::Create(byte theByte) { + CCharToken *theToken = new CCharToken(); theToken->Init(theByte); return theToken; } -void CCharToken::Delete() -{ - CToken::Delete(); -} +void CCharToken::Delete() { CToken::Delete(); } -void CCharToken::Init(byte theByte) -{ +void CCharToken::Init(byte theByte) { CToken::InitBaseToken(); char charString[10]; - switch(theByte) - { - case '\0': - strcpy(charString, "\\0"); - break; - case '\n': - strcpy(charString, "\\n"); - break; - case '\\': - strcpy(charString, "\\\\"); - break; - case '\'': - strcpy(charString, "\\'"); - break; - case '\?': - strcpy(charString, "\\?"); - break; - case '\a': - strcpy(charString, "\\a"); - break; - case '\b': - strcpy(charString, "\\b"); - break; - case '\f': - strcpy(charString, "\\f"); - break; - case '\r': - strcpy(charString, "\\r"); - break; - case '\t': - strcpy(charString, "\\t"); - break; - case '\v': - strcpy(charString, "\\v"); - break; - default: - charString[0] = (char)theByte; - charString[1] = '\0'; - break; + switch (theByte) { + case '\0': + strcpy(charString, "\\0"); + break; + case '\n': + strcpy(charString, "\\n"); + break; + case '\\': + strcpy(charString, "\\\\"); + break; + case '\'': + strcpy(charString, "\\'"); + break; + case '\?': + strcpy(charString, "\\?"); + break; + case '\a': + strcpy(charString, "\\a"); + break; + case '\b': + strcpy(charString, "\\b"); + break; + case '\f': + strcpy(charString, "\\f"); + break; + case '\r': + strcpy(charString, "\\r"); + break; + case '\t': + strcpy(charString, "\\t"); + break; + case '\v': + strcpy(charString, "\\v"); + break; + default: + charString[0] = (char)theByte; + charString[1] = '\0'; + break; } - m_string = (char*)malloc(strlen(charString) + 1); + m_string = (char *)malloc(strlen(charString) + 1); strcpy(m_string, charString); } -int CCharToken::GetType() -{ - return TK_CHAR; -} +int CCharToken::GetType() { return TK_CHAR; } // // CStringToken // -CStringToken::CStringToken() -{ -} +CStringToken::CStringToken() {} -CStringToken::~CStringToken() -{ -} +CStringToken::~CStringToken() {} -CStringToken* CStringToken::Create(LPCTSTR theString) -{ - CStringToken* theToken = new CStringToken(); +CStringToken *CStringToken::Create(LPCTSTR theString) { + CStringToken *theToken = new CStringToken(); theToken->Init(theString); return theToken; } -void CStringToken::Delete() -{ - CToken::Delete(); -} +void CStringToken::Delete() { CToken::Delete(); } -void CStringToken::Init(LPCTSTR theString) -{ +void CStringToken::Init(LPCTSTR theString) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(theString) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(theString) + 1); + // ASSERT(m_string); strcpy(m_string, theString); } -int CStringToken::GetType() -{ - return TK_STRING; -} +int CStringToken::GetType() { return TK_STRING; } // // CIntToken // -CIntToken::CIntToken() -{ -} +CIntToken::CIntToken() {} -CIntToken::~CIntToken() -{ -} +CIntToken::~CIntToken() {} -CIntToken* CIntToken::Create(long value) -{ - CIntToken* theToken = new CIntToken(); +CIntToken *CIntToken::Create(long value) { + CIntToken *theToken = new CIntToken(); theToken->Init(value); return theToken; } -void CIntToken::Delete() -{ - CToken::Delete(); -} +void CIntToken::Delete() { CToken::Delete(); } -void CIntToken::Init(long value) -{ +void CIntToken::Init(long value) { CToken::InitBaseToken(); m_value = value; } -int CIntToken::GetType() -{ - return TK_INT; -} +int CIntToken::GetType() { return TK_INT; } -int CIntToken::GetIntValue() -{ - return m_value; -} +int CIntToken::GetIntValue() { return m_value; } -float CIntToken::GetFloatValue() -{ - return (float)m_value; -} +float CIntToken::GetFloatValue() { return (float)m_value; } -LPCTSTR CIntToken::GetStringValue() -{ - if (m_string != NULL) - { +LPCTSTR CIntToken::GetStringValue() { + if (m_string != NULL) { free(m_string); m_string = NULL; } char temp[128]; sprintf(temp, "%d", m_value); - m_string = (char*)malloc(strlen(temp) + 1); + m_string = (char *)malloc(strlen(temp) + 1); strcpy(m_string, temp); return m_string; } @@ -1079,52 +805,35 @@ LPCTSTR CIntToken::GetStringValue() // CFloatToken // -CFloatToken::CFloatToken() -{ -} +CFloatToken::CFloatToken() {} -CFloatToken::~CFloatToken() -{ -} +CFloatToken::~CFloatToken() {} -CFloatToken* CFloatToken::Create(float value) -{ - CFloatToken* theToken = new CFloatToken(); +CFloatToken *CFloatToken::Create(float value) { + CFloatToken *theToken = new CFloatToken(); theToken->Init(value); return theToken; } -void CFloatToken::Delete() -{ - CToken::Delete(); -} +void CFloatToken::Delete() { CToken::Delete(); } -void CFloatToken::Init(float value) -{ +void CFloatToken::Init(float value) { CToken::InitBaseToken(); m_value = value; } -int CFloatToken::GetType() -{ - return TK_FLOAT; -} +int CFloatToken::GetType() { return TK_FLOAT; } -float CFloatToken::GetFloatValue() -{ - return m_value; -} +float CFloatToken::GetFloatValue() { return m_value; } -LPCTSTR CFloatToken::GetStringValue() -{ - if (m_string != NULL) - { +LPCTSTR CFloatToken::GetStringValue() { + if (m_string != NULL) { free(m_string); m_string = NULL; } char temp[128]; sprintf(temp, "%g", m_value); - m_string = (char*)malloc(strlen(temp) + 1); + m_string = (char *)malloc(strlen(temp) + 1); strcpy(m_string, temp); return m_string; } @@ -1133,238 +842,157 @@ LPCTSTR CFloatToken::GetStringValue() // CIdentifierToken // -CIdentifierToken::CIdentifierToken() -{ -} +CIdentifierToken::CIdentifierToken() {} -CIdentifierToken::~CIdentifierToken() -{ -} +CIdentifierToken::~CIdentifierToken() {} -CIdentifierToken* CIdentifierToken::Create(LPCTSTR name) -{ - CIdentifierToken* theToken = new CIdentifierToken(); +CIdentifierToken *CIdentifierToken::Create(LPCTSTR name) { + CIdentifierToken *theToken = new CIdentifierToken(); theToken->Init(name); return theToken; } -void CIdentifierToken::Delete() -{ - CToken::Delete(); -} +void CIdentifierToken::Delete() { CToken::Delete(); } -void CIdentifierToken::Init(LPCTSTR name) -{ +void CIdentifierToken::Init(LPCTSTR name) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(name) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(name) + 1); + // ASSERT(m_string); strcpy(m_string, name); } -int CIdentifierToken::GetType() -{ - return TK_IDENTIFIER; -} +int CIdentifierToken::GetType() { return TK_IDENTIFIER; } // // CCommentToken // -CCommentToken::CCommentToken() -{ -} +CCommentToken::CCommentToken() {} -CCommentToken::~CCommentToken() -{ -} +CCommentToken::~CCommentToken() {} -CCommentToken* CCommentToken::Create(LPCTSTR name) -{ - CCommentToken* theToken = new CCommentToken(); +CCommentToken *CCommentToken::Create(LPCTSTR name) { + CCommentToken *theToken = new CCommentToken(); theToken->Init(name); return theToken; } -void CCommentToken::Delete() -{ - CToken::Delete(); -} +void CCommentToken::Delete() { CToken::Delete(); } -void CCommentToken::Init(LPCTSTR name) -{ +void CCommentToken::Init(LPCTSTR name) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(name) + 1); -// ASSERT(m_string); + m_string = (char *)malloc(strlen(name) + 1); + // ASSERT(m_string); strcpy(m_string, name); } -int CCommentToken::GetType() -{ - return TK_COMMENT; -} +int CCommentToken::GetType() { return TK_COMMENT; } // // CUserToken // -CUserToken::CUserToken() -{ -} +CUserToken::CUserToken() {} -CUserToken::~CUserToken() -{ -} +CUserToken::~CUserToken() {} -CUserToken* CUserToken::Create(int value, LPCTSTR string) -{ - CUserToken* theToken = new CUserToken(); +CUserToken *CUserToken::Create(int value, LPCTSTR string) { + CUserToken *theToken = new CUserToken(); theToken->Init(value, string); return theToken; } -void CUserToken::Delete() -{ - CToken::Delete(); -} +void CUserToken::Delete() { CToken::Delete(); } -void CUserToken::Init(int value, LPCTSTR string) -{ +void CUserToken::Init(int value, LPCTSTR string) { CToken::InitBaseToken(); m_value = value; - m_string = (char*)malloc(strlen(string) + 1); + m_string = (char *)malloc(strlen(string) + 1); strcpy(m_string, string); } -int CUserToken::GetType() -{ - return m_value; -} +int CUserToken::GetType() { return m_value; } // // CUndefinedToken // -CUndefinedToken::CUndefinedToken() -{ -} +CUndefinedToken::CUndefinedToken() {} -CUndefinedToken::~CUndefinedToken() -{ -} +CUndefinedToken::~CUndefinedToken() {} -CUndefinedToken* CUndefinedToken::Create(LPCTSTR string) -{ - CUndefinedToken* theToken = new CUndefinedToken(); +CUndefinedToken *CUndefinedToken::Create(LPCTSTR string) { + CUndefinedToken *theToken = new CUndefinedToken(); theToken->Init(string); return theToken; } -void CUndefinedToken::Delete() -{ - CToken::Delete(); -} +void CUndefinedToken::Delete() { CToken::Delete(); } -void CUndefinedToken::Init(LPCTSTR string) -{ +void CUndefinedToken::Init(LPCTSTR string) { CToken::InitBaseToken(); - m_string = (char*)malloc(strlen(string) + 1); + m_string = (char *)malloc(strlen(string) + 1); strcpy(m_string, string); } -int CUndefinedToken::GetType() -{ - return TK_UNDEFINED; -} +int CUndefinedToken::GetType() { return TK_UNDEFINED; } // // CTokenizerState // -CTokenizerState::CTokenizerState() -{ -} +CTokenizerState::CTokenizerState() {} -CTokenizerState::~CTokenizerState() -{ -} +CTokenizerState::~CTokenizerState() {} -CTokenizerState* CTokenizerState::Create(bool skip) -{ - CTokenizerState* retval = new CTokenizerState(); +CTokenizerState *CTokenizerState::Create(bool skip) { + CTokenizerState *retval = new CTokenizerState(); retval->Init(skip); return retval; } -void CTokenizerState::Init(bool skip) -{ +void CTokenizerState::Init(bool skip) { m_next = NULL; m_skip = skip; m_elseHit = false; } -void CTokenizerState::Delete() -{ - delete this; -} +void CTokenizerState::Delete() { delete this; } -CTokenizerState* CTokenizerState::GetNext() -{ - return m_next; -} +CTokenizerState *CTokenizerState::GetNext() { return m_next; } -bool CTokenizerState::ProcessElse() -{ - if (!m_elseHit) - { +bool CTokenizerState::ProcessElse() { + if (!m_elseHit) { m_elseHit = true; m_skip = !m_skip; } return m_elseHit; } -void CTokenizerState::SetNext(CTokenizerState* next) -{ - m_next = next; -} +void CTokenizerState::SetNext(CTokenizerState *next) { m_next = next; } -bool CTokenizerState::Skipping() -{ - return m_skip; -} +bool CTokenizerState::Skipping() { return m_skip; } // // CTokenizerHolderState // -CTokenizerHolderState::CTokenizerHolderState() -{ -} +CTokenizerHolderState::CTokenizerHolderState() {} -CTokenizerHolderState::~CTokenizerHolderState() -{ -} +CTokenizerHolderState::~CTokenizerHolderState() {} -CTokenizerHolderState* CTokenizerHolderState::Create() -{ - CTokenizerHolderState* retval = new CTokenizerHolderState(); +CTokenizerHolderState *CTokenizerHolderState::Create() { + CTokenizerHolderState *retval = new CTokenizerHolderState(); retval->Init(); return retval; } -void CTokenizerHolderState::Init() -{ - CTokenizerState::Init(true); -} +void CTokenizerHolderState::Init() { CTokenizerState::Init(true); } -void CTokenizerHolderState::Delete() -{ - delete this; -} +void CTokenizerHolderState::Delete() { delete this; } -bool CTokenizerHolderState::ProcessElse() -{ - if (!m_elseHit) - { +bool CTokenizerHolderState::ProcessElse() { + if (!m_elseHit) { m_elseHit = true; } return m_elseHit; @@ -1374,143 +1002,112 @@ bool CTokenizerHolderState::ProcessElse() // CKeywordTable // -CKeywordTable::CKeywordTable(CTokenizer* tokenizer, keywordArray_t* keywords) -{ +CKeywordTable::CKeywordTable(CTokenizer *tokenizer, keywordArray_t *keywords) { m_tokenizer = tokenizer; m_holdKeywords = tokenizer->SetKeywords(keywords); } -CKeywordTable::~CKeywordTable() -{ - m_tokenizer->SetKeywords(m_holdKeywords); -} +CKeywordTable::~CKeywordTable() { m_tokenizer->SetKeywords(m_holdKeywords); } // // CTokenizer // -CTokenizer::CTokenizer() -{ -} +CTokenizer::CTokenizer() {} -CTokenizer::~CTokenizer() -{ -} +CTokenizer::~CTokenizer() {} -CTokenizer* CTokenizer::Create(UINT dwFlags) -{ - CTokenizer* theTokenizer = new CTokenizer(); +CTokenizer *CTokenizer::Create(UINT dwFlags) { + CTokenizer *theTokenizer = new CTokenizer(); theTokenizer->Init(dwFlags); return theTokenizer; } -void CTokenizer::Delete() -{ - while (m_curParseStream != NULL) - { - CParseStream* curStream = m_curParseStream; +void CTokenizer::Delete() { + while (m_curParseStream != NULL) { + CParseStream *curStream = m_curParseStream; m_curParseStream = curStream->GetNext(); curStream->Delete(); } - if (m_symbolLookup != NULL) - { + if (m_symbolLookup != NULL) { m_symbolLookup->Delete(); m_symbolLookup = NULL; } - while (m_nextToken != NULL) - { - CToken* curToken = m_nextToken; + while (m_nextToken != NULL) { + CToken *curToken = m_nextToken; m_nextToken = curToken->GetNext(); curToken->Delete(); } - while (m_state != NULL) - { + while (m_state != NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); - CTokenizerState* curState = m_state; + CTokenizerState *curState = m_state; m_state = curState->GetNext(); curState->Delete(); } -/* if (m_lastErrMsg != NULL) - { - free(m_lastErrMsg); - m_lastErrMsg = NULL; - }*/ + /* if (m_lastErrMsg != NULL) + { + free(m_lastErrMsg); + m_lastErrMsg = NULL; + }*/ delete this; } -void CTokenizer::Error(int theError) -{ +void CTokenizer::Error(int theError) { char errString[128]; char lookupstring[128]; int i = 0; - while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) - { + while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) { i++; } - if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) - { + if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) { i = 0; - while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) - { + while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) { i++; } strcpy(lookupstring, m_errors[i].m_keyword); - } - else - { + } else { strcpy(lookupstring, errorMessages[i].m_keyword); } sprintf(errString, "Error -- %d, %s", theError, lookupstring); Error(errString, theError); } -void CTokenizer::Error(int theError, LPCTSTR errString) -{ +void CTokenizer::Error(int theError, LPCTSTR errString) { char errstring[128]; char lookupstring[128]; int i = 0; - while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) - { + while ((errorMessages[i].m_tokenvalue != TKERR_USERERROR) && (errorMessages[i].m_tokenvalue != theError)) { i++; } - if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) - { + if ((errorMessages[i].m_tokenvalue == TKERR_USERERROR) && (m_errors != NULL)) { i = 0; - while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) - { + while ((m_errors[i].m_tokenvalue != TK_EOF) && (m_errors[i].m_tokenvalue != theError)) { i++; } strcpy(lookupstring, m_errors[i].m_keyword); - } - else - { + } else { strcpy(lookupstring, errorMessages[i].m_keyword); } sprintf(errstring, "Error -- %d, %s - %s", theError, lookupstring, errString); Error(errstring, theError); } -void CTokenizer::Error(LPCTSTR errString, int theError) -{ - if (m_errorProc != NULL) - { +void CTokenizer::Error(LPCTSTR errString, int theError) { + if (m_errorProc != NULL) { m_errorProc(errString); } #ifdef USES_MODULES - else - { + else { ReportError(theError, errString); } #endif } -bool CTokenizer::AddParseFile(LPCTSTR filename) -{ - CParseStream* newStream = CParseFile::Create(filename, this); +bool CTokenizer::AddParseFile(LPCTSTR filename) { + CParseStream *newStream = CParseFile::Create(filename, this); - if ( newStream != NULL ) - { + if (newStream != NULL) { newStream->SetNext(m_curParseStream); m_curParseStream = newStream; return true; @@ -1519,41 +1116,33 @@ bool CTokenizer::AddParseFile(LPCTSTR filename) return false; } -void CTokenizer::AddParseStream(byte* data, long datasize) -{ - CParseStream* newStream = CParseMemory::Create(data, datasize); +void CTokenizer::AddParseStream(byte *data, long datasize) { + CParseStream *newStream = CParseMemory::Create(data, datasize); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; } -long CTokenizer::GetRemainingSize() -{ +long CTokenizer::GetRemainingSize() { long retval = 0; - CParseStream* curStream = m_curParseStream; - while (curStream != NULL) - { + CParseStream *curStream = m_curParseStream; + while (curStream != NULL) { retval += curStream->GetRemainingSize(); curStream = curStream->GetNext(); } return retval; } -LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t* theTable) -{ - if (theTable == NULL) - { +LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t *theTable) { + if (theTable == NULL) { theTable = m_keywords; } - if (theTable == NULL) - { + if (theTable == NULL) { return NULL; } int i = 0; - while (theTable[i].m_tokenvalue != TK_EOF) - { - if (theTable[i].m_tokenvalue == tokenID) - { + while (theTable[i].m_tokenvalue != TK_EOF) { + if (theTable[i].m_tokenvalue == tokenID) { return theTable[i].m_keyword; } i++; @@ -1561,34 +1150,30 @@ LPCTSTR CTokenizer::LookupToken(int tokenID, keywordArray_t* theTable) return NULL; } -void CTokenizer::PutBackToken(CToken* theToken, bool commented, LPCTSTR addedChars, bool bIgnoreThisTokenType) -{ - if (commented) - { - CParseToken* newStream = CParseToken::Create(theToken); +void CTokenizer::PutBackToken(CToken *theToken, bool commented, LPCTSTR addedChars, bool bIgnoreThisTokenType) { + if (commented) { + CParseToken *newStream = CParseToken::Create(theToken); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; - if (addedChars != NULL) - { - CParsePutBack* spacer = CParsePutBack::Create(' ', 0, NULL); + if (addedChars != NULL) { + CParsePutBack *spacer = CParsePutBack::Create(' ', 0, NULL); spacer->SetNext(m_curParseStream); m_curParseStream = spacer; - CParseBlock* newBlock = CParseBlock::Create((byte*)addedChars, strlen(addedChars)); + CParseBlock *newBlock = CParseBlock::Create((byte *)addedChars, strlen(addedChars)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; } char temp[] = "// * "; - CParseBlock* newBlock = CParseBlock::Create((byte*)temp, strlen(temp)); + CParseBlock *newBlock = CParseBlock::Create((byte *)temp, strlen(temp)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; return; } - switch(theToken->GetType()) - { + switch (theToken->GetType()) { case TK_INT: case TK_EOF: case TK_UNDEFINED: @@ -1597,57 +1182,48 @@ void CTokenizer::PutBackToken(CToken* theToken, bool commented, LPCTSTR addedCha case TK_STRING: case TK_EOL: case TK_COMMENT: - if (!bIgnoreThisTokenType) - { + if (!bIgnoreThisTokenType) { theToken->SetNext(m_nextToken); m_nextToken = theToken; break; } default: - CParseToken* newStream = CParseToken::Create(theToken); + CParseToken *newStream = CParseToken::Create(theToken); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; break; } - if (addedChars != NULL) - { - CParseBlock* newBlock = CParseBlock::Create((byte*)addedChars, strlen(addedChars)); + if (addedChars != NULL) { + CParseBlock *newBlock = CParseBlock::Create((byte *)addedChars, strlen(addedChars)); newBlock->SetNext(m_curParseStream); m_curParseStream = newBlock; } } -CToken* CTokenizer::GetToken(keywordArray_t* keywords, UINT onFlags, UINT offFlags) -{ - keywordArray_t* holdKeywords = SetKeywords(keywords); - CToken* retval = GetToken(onFlags, offFlags); +CToken *CTokenizer::GetToken(keywordArray_t *keywords, UINT onFlags, UINT offFlags) { + keywordArray_t *holdKeywords = SetKeywords(keywords); + CToken *retval = GetToken(onFlags, offFlags); SetKeywords(holdKeywords); return retval; } -CToken* CTokenizer::GetToken(UINT onFlags, UINT offFlags) -{ +CToken *CTokenizer::GetToken(UINT onFlags, UINT offFlags) { UINT holdFlags = m_flags; m_flags |= onFlags; m_flags &= (~offFlags); - CToken* theToken = NULL; - while (theToken == NULL) - { + CToken *theToken = NULL; + while (theToken == NULL) { theToken = FetchToken(); - if (theToken == NULL) - { + if (theToken == NULL) { continue; } - if (theToken->GetType() == TK_EOF) - { + if (theToken->GetType() == TK_EOF) { break; } - if (m_state != NULL) - { - if (m_state->Skipping()) - { + if (m_state != NULL) { + if (m_state->Skipping()) { theToken->Delete(); theToken = NULL; } @@ -1658,23 +1234,18 @@ CToken* CTokenizer::GetToken(UINT onFlags, UINT offFlags) return theToken; } -CToken* CTokenizer::GetToEndOfLine(int tokenType) -{ +CToken *CTokenizer::GetToEndOfLine(int tokenType) { // update, if you just want the whole line returned as a string, then allow a much bigger size than // the default string size of only 128 chars... // - if (tokenType == TK_STRING) - { - #define iRETURN_STRING_SIZE 2048 + if (tokenType == TK_STRING) { +#define iRETURN_STRING_SIZE 2048 char theString[iRETURN_STRING_SIZE]; theString[0] = ' '; - for (int i = 1; i < iRETURN_STRING_SIZE; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '\n') - { + for (int i = 1; i < iRETURN_STRING_SIZE; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '\n') { continue; } PutBackChar(theString[i]); @@ -1687,31 +1258,23 @@ CToken* CTokenizer::GetToEndOfLine(int tokenType) // line would maks a string too big to fit in buffer... // Error(TKERR_STRINGLENGTHEXCEEDED); - } - else - { + } else { char theString[MAX_IDENTIFIER_LENGTH]; theString[0] = ' '; - while (theString[0] == ' ') - { - if (!NextChar((byte&)theString[0])) - { + while (theString[0] == ' ') { + if (!NextChar((byte &)theString[0])) { return NULL; } } - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '\n') - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '\n') { continue; } PutBackChar(theString[i]); } theString[i] = '\0'; - switch(tokenType) - { + switch (tokenType) { case TK_COMMENT: return CCommentToken::Create(theString); case TK_IDENTIFIER: @@ -1724,55 +1287,41 @@ CToken* CTokenizer::GetToEndOfLine(int tokenType) return NULL; } -void CTokenizer::SkipToLineEnd() -{ +void CTokenizer::SkipToLineEnd() { byte theByte; - while(NextChar(theByte)) - { - if (theByte == '\n') - { + while (NextChar(theByte)) { + if (theByte == '\n') { break; } } } -CToken* CTokenizer::FetchToken() -{ - if (m_nextToken != NULL) - { - CToken* curToken = m_nextToken; +CToken *CTokenizer::FetchToken() { + if (m_nextToken != NULL) { + CToken *curToken = m_nextToken; m_nextToken = curToken->GetNext(); curToken->SetNext(NULL); return curToken; } byte theByte; - CToken* theToken = NULL; + CToken *theToken = NULL; - while (true) - { - if (!NextChar(theByte)) - { + while (true) { + if (!NextChar(theByte)) { return CToken::Create(); } - if (theByte <= ' ') - { - if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) - { + if (theByte <= ' ') { + if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) { return CUserToken::Create(TK_EOL, "-EOLN-"); } continue; } - switch(theByte) - { + switch (theByte) { case '#': - if ((m_flags & TKF_IGNOREDIRECTIVES) == 0) - { + if ((m_flags & TKF_IGNOREDIRECTIVES) == 0) { theToken = HandleDirective(); - } - else - { - if ((m_flags & TKF_NODIRECTIVES) != 0) - { + } else { + if ((m_flags & TKF_NODIRECTIVES) != 0) { return HandleSymbol('#'); } SkipToLineEnd(); @@ -1788,89 +1337,65 @@ CToken* CTokenizer::FetchToken() theToken = HandleQuote(); break; default: - if (((theByte >= 'a') && (theByte <= 'z')) - || ((theByte >= 'A') && (theByte <= 'Z')) - || ((theByte == '_') && ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0))) - { + if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || + ((theByte == '_') && ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0))) { theToken = HandleIdentifier(theByte); - } - else if (((m_flags & TKF_NUMERICIDENTIFIERSTART) != 0) && (theByte >= '0') && (theByte <= '9')) - { + } else if (((m_flags & TKF_NUMERICIDENTIFIERSTART) != 0) && (theByte >= '0') && (theByte <= '9')) { theToken = HandleIdentifier(theByte); - } - else if (((theByte >= '0') && (theByte <= '9')) || (theByte == '-')) - { + } else if (((theByte >= '0') && (theByte <= '9')) || (theByte == '-')) { theToken = HandleNumeric(theByte); - } - else if (theByte == '.') - { + } else if (theByte == '.') { theToken = HandleDecimal(); - } - else if (theByte <= ' ') - { + } else if (theByte <= ' ') { break; - } - else - { + } else { theToken = HandleSymbol(theByte); } } - if (theToken != NULL) - { + if (theToken != NULL) { return theToken; } } } -bool CTokenizer::NextChar(byte& theByte) -{ - while (m_curParseStream != NULL) - { - if (m_curParseStream->NextChar(theByte)) - { +bool CTokenizer::NextChar(byte &theByte) { + while (m_curParseStream != NULL) { + if (m_curParseStream->NextChar(theByte)) { return true; } - CParseStream* curParseStream = m_curParseStream; + CParseStream *curParseStream = m_curParseStream; m_curParseStream = curParseStream->GetNext(); curParseStream->Delete(); } return false; } -bool CTokenizer::RequireToken(int tokenType) -{ - CToken* theToken = GetToken(); +bool CTokenizer::RequireToken(int tokenType) { + CToken *theToken = GetToken(); bool retValue = theToken->GetType() == tokenType; theToken->Delete(); return retValue; } -void CTokenizer::ScanUntilToken(int tokenType) -{ - CToken* curToken; +void CTokenizer::ScanUntilToken(int tokenType) { + CToken *curToken; int tokenValue = TK_UNDEFINED; - while (tokenValue != tokenType) - { + while (tokenValue != tokenType) { curToken = GetToken(); tokenValue = curToken->GetType(); - if (tokenValue == TK_EOF) - { + if (tokenValue == TK_EOF) { PutBackToken(curToken); break; } - if (tokenValue == tokenType) - { + if (tokenValue == tokenType) { PutBackToken(curToken); - } - else - { + } else { curToken->Delete(); } } } -void CTokenizer::Init(UINT dwFlags) -{ +void CTokenizer::Init(UINT dwFlags) { m_symbolLookup = NULL; m_nextToken = NULL; m_curParseStream = NULL; @@ -1882,64 +1407,48 @@ void CTokenizer::Init(UINT dwFlags) m_errorProc = NULL; } -void CTokenizer::SetErrorProc(LPTokenizerErrorProc errorProc) -{ - m_errorProc = errorProc; -} +void CTokenizer::SetErrorProc(LPTokenizerErrorProc errorProc) { m_errorProc = errorProc; } -void CTokenizer::SetAdditionalErrors(keywordArray_t* theErrors) -{ - m_errors = theErrors; -} +void CTokenizer::SetAdditionalErrors(keywordArray_t *theErrors) { m_errors = theErrors; } -keywordArray_t* CTokenizer::SetKeywords(keywordArray_t* theKeywords) -{ - keywordArray_t* retval = m_keywords; +keywordArray_t *CTokenizer::SetKeywords(keywordArray_t *theKeywords) { + keywordArray_t *retval = m_keywords; m_keywords = theKeywords; return retval; } -void CTokenizer::SetSymbols(keywordArray_t* theSymbols) -{ +void CTokenizer::SetSymbols(keywordArray_t *theSymbols) { m_symbols = theSymbols; - if (m_symbolLookup != NULL) - { + if (m_symbolLookup != NULL) { m_symbolLookup->Delete(); m_symbolLookup = NULL; } int i = 0; - if (theSymbols == NULL) - { + if (theSymbols == NULL) { return; } - while(theSymbols[i].m_tokenvalue != TK_EOF) - { + while (theSymbols[i].m_tokenvalue != TK_EOF) { InsertSymbol(theSymbols[i].m_keyword, theSymbols[i].m_tokenvalue); i++; } } -void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) -{ - CSymbolLookup** curHead = &m_symbolLookup; - CSymbolLookup* curParent = NULL; - CSymbolLookup* curLookup = NULL; +void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) { + CSymbolLookup **curHead = &m_symbolLookup; + CSymbolLookup *curParent = NULL; + CSymbolLookup *curLookup = NULL; - for (UINT i = 0; i < strlen(theSymbol); i++) - { + for (UINT i = 0; i < strlen(theSymbol); i++) { bool found = false; curLookup = *curHead; - while (curLookup != NULL) - { - if (curLookup->GetByte() == theSymbol[i]) - { + while (curLookup != NULL) { + if (curLookup->GetByte() == theSymbol[i]) { found = true; break; } curLookup = curLookup->GetNext(); } - if (!found) - { + if (!found) { curLookup = CSymbolLookup::Create(theSymbol[i]); curLookup->SetParent(curParent); curLookup->SetNext(*curHead); @@ -1948,29 +1457,23 @@ void CTokenizer::InsertSymbol(LPCTSTR theSymbol, int theValue) curHead = curLookup->GetChildAddress(); curParent = curLookup; } - if (curLookup->GetValue() != -1) - { + if (curLookup->GetValue() != -1) { Error(TKERR_DUPLICATESYMBOL); } curLookup->SetValue(theValue); } -CToken* CTokenizer::HandleString() -{ +CToken *CTokenizer::HandleString() { char theString[MAX_STRING_LENGTH]; - for (int i = 0; i < MAX_STRING_LENGTH; i++) - { - if (!NextChar((byte&)theString[i])) - { + for (int i = 0; i < MAX_STRING_LENGTH; i++) { + if (!NextChar((byte &)theString[i])) { return NULL; } - if (theString[i] == '"') - { + if (theString[i] == '"') { theString[i] = '\0'; return CStringToken::Create(theString); } - if (theString[i] == '\\') - { + if (theString[i] == '\\') { theString[i] = Escapement(); } } @@ -1978,55 +1481,43 @@ CToken* CTokenizer::HandleString() return NULL; } -void CTokenizer::GetCurFilename(char** filename) -{ - if (m_curParseStream == NULL) - { - *filename = (char*)malloc(1); +void CTokenizer::GetCurFilename(char **filename) { + if (m_curParseStream == NULL) { + *filename = (char *)malloc(1); *filename[0] = '\0'; return; } m_curParseStream->GetCurFilename(filename); } -int CTokenizer::GetCurLine() -{ - if (m_curParseStream == NULL) - { +int CTokenizer::GetCurLine() { + if (m_curParseStream == NULL) { return 0; } return m_curParseStream->GetCurLine(); } -void CTokenizer::PutBackChar(byte theByte, int curLine, LPCTSTR filename) -{ - CParseStream* newStream; - if (filename == NULL) - { +void CTokenizer::PutBackChar(byte theByte, int curLine, LPCTSTR filename) { + CParseStream *newStream; + if (filename == NULL) { curLine = m_curParseStream->GetCurLine(); - char* theFile = NULL; + char *theFile = NULL; m_curParseStream->GetCurFilename(&theFile); newStream = CParsePutBack::Create(theByte, curLine, theFile); - if (theFile != NULL) - { + if (theFile != NULL) { free(theFile); } - } - else - { + } else { newStream = CParsePutBack::Create(theByte, curLine, filename); } newStream->SetNext(m_curParseStream); m_curParseStream = newStream; } -byte CTokenizer::Escapement() -{ +byte CTokenizer::Escapement() { byte theByte; - if (NextChar(theByte)) - { - switch(theByte) - { + if (NextChar(theByte)) { + switch (theByte) { case 'n': return '\n'; case '\\': @@ -2057,53 +1548,39 @@ byte CTokenizer::Escapement() return '\\'; } -bool CTokenizer::AddDefineSymbol(CDirectiveSymbol* definesymbol) -{ - CParseStream* curStream = m_curParseStream; - while(curStream != NULL) - { - if (curStream->IsThisDefinition(definesymbol)) - { +bool CTokenizer::AddDefineSymbol(CDirectiveSymbol *definesymbol) { + CParseStream *curStream = m_curParseStream; + while (curStream != NULL) { + if (curStream->IsThisDefinition(definesymbol)) { return false; } curStream = curStream->GetNext(); } - CParseStream* newStream = CParseDefine::Create(definesymbol); + CParseStream *newStream = CParseDefine::Create(definesymbol); newStream->SetNext(m_curParseStream); m_curParseStream = newStream; return true; } -CToken* CTokenizer::TokenFromName(LPCTSTR name) -{ - CDirectiveSymbol* defineSymbol = (CDirectiveSymbol*)m_defines.FindSymbol(name); - if (defineSymbol != NULL) - { - if (AddDefineSymbol(defineSymbol)) - { +CToken *CTokenizer::TokenFromName(LPCTSTR name) { + CDirectiveSymbol *defineSymbol = (CDirectiveSymbol *)m_defines.FindSymbol(name); + if (defineSymbol != NULL) { + if (AddDefineSymbol(defineSymbol)) { return FetchToken(); } } - if ((m_keywords != NULL) && ((m_flags & TKF_IGNOREKEYWORDS) == 0)) - { + if ((m_keywords != NULL) && ((m_flags & TKF_IGNOREKEYWORDS) == 0)) { int i = 0; - if ((m_flags & TKF_NOCASEKEYWORDS) == 0) - { - while (m_keywords[i].m_tokenvalue != TK_EOF) - { - if (strcmp(m_keywords[i].m_keyword, name) == 0) - { + if ((m_flags & TKF_NOCASEKEYWORDS) == 0) { + while (m_keywords[i].m_tokenvalue != TK_EOF) { + if (strcmp(m_keywords[i].m_keyword, name) == 0) { return CUserToken::Create(m_keywords[i].m_tokenvalue, name); } i++; } - } - else - { - while (m_keywords[i].m_tokenvalue != TK_EOF) - { - if (stricmp(m_keywords[i].m_keyword, name) == 0) - { + } else { + while (m_keywords[i].m_tokenvalue != TK_EOF) { + if (stricmp(m_keywords[i].m_keyword, name) == 0) { return CUserToken::Create(m_keywords[i].m_tokenvalue, name); } i++; @@ -2113,15 +1590,11 @@ CToken* CTokenizer::TokenFromName(LPCTSTR name) return CIdentifierToken::Create(name); } -int CTokenizer::DirectiveFromName(LPCTSTR name) -{ - if (directiveKeywords != NULL) - { +int CTokenizer::DirectiveFromName(LPCTSTR name) { + if (directiveKeywords != NULL) { int i = 0; - while (directiveKeywords[i].m_tokenvalue != TK_EOF) - { - if (strcmp(directiveKeywords[i].m_keyword, name) == 0) - { + while (directiveKeywords[i].m_tokenvalue != TK_EOF) { + if (strcmp(directiveKeywords[i].m_keyword, name) == 0) { return directiveKeywords[i].m_tokenvalue; } i++; @@ -2130,22 +1603,15 @@ int CTokenizer::DirectiveFromName(LPCTSTR name) return -1; } -CToken* CTokenizer::HandleIdentifier(byte theByte) -{ +CToken *CTokenizer::HandleIdentifier(byte theByte) { char theString[MAX_IDENTIFIER_LENGTH]; theString[0] = theByte; - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { if (((theString[i] != '_') || ((m_flags & TKF_NOUNDERSCOREINIDENTIFIER) == 0)) && - ((theString[i] != '-') || ((m_flags & TKF_NODASHINIDENTIFIER) == 0))) - { - if (((theString[i] >= 'A') && (theString[i] <= 'Z')) - || ((theString[i] >= 'a') && (theString[i] <= 'z')) - || ((theString[i] >= '0') && (theString[i] <= '9')) - || (theString[i] == '_') || (theString[i] == '-')) - { + ((theString[i] != '-') || ((m_flags & TKF_NODASHINIDENTIFIER) == 0))) { + if (((theString[i] >= 'A') && (theString[i] <= 'Z')) || ((theString[i] >= 'a') && (theString[i] <= 'z')) || + ((theString[i] >= '0') && (theString[i] <= '9')) || (theString[i] == '_') || (theString[i] == '-')) { continue; } } @@ -2158,48 +1624,35 @@ CToken* CTokenizer::HandleIdentifier(byte theByte) return NULL; } -CToken* CTokenizer::HandleSlash() -{ +CToken *CTokenizer::HandleSlash() { byte theByte; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { return NULL; } - if (theByte == '/') - { - if (m_flags & TKF_COMMENTTOKENS) - { + if (theByte == '/') { + if (m_flags & TKF_COMMENTTOKENS) { return GetToEndOfLine(TK_COMMENT); } SkipToLineEnd(); return NULL; } - if (theByte == '*') - { - if (m_flags & TKF_COMMENTTOKENS) - { + if (theByte == '*') { + if (m_flags & TKF_COMMENTTOKENS) { char theString[MAX_IDENTIFIER_LENGTH + 1]; theString[0] = ' '; - while (theString[0] == ' ') - { - if (!NextChar((byte&)theString[0])) - { + while (theString[0] == ' ') { + if (!NextChar((byte &)theString[0])) { return NULL; } } - for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) - { - if (NextChar((byte&)theString[i])) - { - if (theString[i] != '*') - { + for (int i = 1; i < MAX_IDENTIFIER_LENGTH; i++) { + if (NextChar((byte &)theString[i])) { + if (theString[i] != '*') { continue; } i++; - if (NextChar((byte&)theString[i])) - { - if (theString[i] == '/') - { + if (NextChar((byte &)theString[i])) { + if (theString[i] == '/') { i--; theString[i] = '\0'; return CCommentToken::Create(theString); @@ -2210,16 +1663,12 @@ CToken* CTokenizer::HandleSlash() Error(TKERR_IDENTIFIERLENGTHEXCEEDED); return NULL; } - while(NextChar(theByte)) - { - while(theByte == '*') - { - if (!NextChar(theByte)) - { + while (NextChar(theByte)) { + while (theByte == '*') { + if (!NextChar(theByte)) { break; } - if (theByte == '/') - { + if (theByte == '/') { return NULL; } } @@ -2230,101 +1679,77 @@ CToken* CTokenizer::HandleSlash() return HandleSymbol('/'); } -CToken* CTokenizer::HandleNumeric(byte theByte) -{ +CToken *CTokenizer::HandleNumeric(byte theByte) { bool thesign = theByte == '-'; - if (thesign) - { - if (!NextChar(theByte)) - { + if (thesign) { + if (!NextChar(theByte)) { return HandleSymbol('-'); } - if (theByte == '.') - { + if (theByte == '.') { return HandleDecimal(thesign); } - if ((theByte < '0') || (theByte > '9')) - { + if ((theByte < '0') || (theByte > '9')) { PutBackChar(theByte); return HandleSymbol('-'); } } - if (theByte == '0') - { + if (theByte == '0') { return HandleOctal(thesign); } long value = 0; bool digithit = false; - while((theByte >= '0') && (theByte <= '9')) - { + while ((theByte >= '0') && (theByte <= '9')) { value = (value * 10) + (theByte - '0'); - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); } digithit = true; } - if (theByte == '.') - { - if (digithit) - { + if (theByte == '.') { + if (digithit) { return HandleFloat(thesign, value); } - if (thesign) - { + if (thesign) { PutBackChar(theByte); theByte = '-'; } return HandleSymbol(theByte); } PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); } -CToken* CTokenizer::HandleOctal(bool thesign) -{ +CToken *CTokenizer::HandleOctal(bool thesign) { byte theByte; int value = 0; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { return CIntToken::Create(value); } - if (theByte == '.') - { + if (theByte == '.') { return HandleDecimal(thesign); } - if ((theByte == 'x') || (theByte == 'X')) - { + if ((theByte == 'x') || (theByte == 'X')) { return HandleHex(thesign); } - while(true) - { - if((theByte >= '0') && (theByte <='7')) - { + while (true) { + if ((theByte >= '0') && (theByte <= '7')) { value = (value * 8) + (theByte - '0'); - } - else - { + } else { PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); } - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); @@ -2332,23 +1757,18 @@ CToken* CTokenizer::HandleOctal(bool thesign) } } -CToken* CTokenizer::HandleHex(bool thesign) -{ +CToken *CTokenizer::HandleHex(bool thesign) { int value = 0; - while (true) - { + while (true) { byte theByte; - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { value = -value; } return CIntToken::Create(value); } - switch (theByte) - { + switch (theByte) { case '0': case '1': case '2': @@ -2379,8 +1799,7 @@ CToken* CTokenizer::HandleHex(bool thesign) break; default: PutBackChar(theByte); - if (thesign) - { + if (thesign) { value = -value; } return CIntToken::Create(value); @@ -2389,44 +1808,34 @@ CToken* CTokenizer::HandleHex(bool thesign) } } -CToken* CTokenizer::HandleDecimal(bool thesign) -{ +CToken *CTokenizer::HandleDecimal(bool thesign) { byte theByte; - if (!NextChar(theByte)) - { - if (thesign) - { + if (!NextChar(theByte)) { + if (thesign) { PutBackChar('.'); return HandleSymbol('-'); } HandleSymbol('.'); } PutBackChar(theByte); - if ((theByte <= '9') && (theByte >= '0')) - { + if ((theByte <= '9') && (theByte >= '0')) { return HandleFloat(thesign); } - if (thesign) - { + if (thesign) { PutBackChar('.'); theByte = '-'; - } - else - { + } else { theByte = '.'; } return HandleSymbol(theByte); } -CToken* CTokenizer::HandleFloat(bool thesign, long value) -{ +CToken *CTokenizer::HandleFloat(bool thesign, long value) { float lower = 1.0; float newValue = (float)value; byte theByte; - while(NextChar(theByte)) - { - if ((theByte >= '0') && (theByte <= '9')) - { + while (NextChar(theByte)) { + if ((theByte >= '0') && (theByte <= '9')) { lower = lower / 10; newValue = newValue + ((theByte - '0') * lower); continue; @@ -2434,33 +1843,27 @@ CToken* CTokenizer::HandleFloat(bool thesign, long value) PutBackChar(theByte); break; } - if (thesign) - { + if (thesign) { newValue = -newValue; } return CFloatToken::Create(newValue); } -CToken* CTokenizer::HandleQuote() -{ +CToken *CTokenizer::HandleQuote() { byte theByte; - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { Error(TKERR_EXPECTED_CHAR); return NULL; } - if (theByte == '\\') - { + if (theByte == '\\') { theByte = Escapement(); } byte dummy; - if (!NextChar(dummy)) - { + if (!NextChar(dummy)) { Error(TKERR_EXPECTED_CHAR); return NULL; } - if (dummy != '\'') - { + if (dummy != '\'') { PutBackChar(dummy); PutBackChar(theByte); Error(TKERR_EXPECTED_CHAR); @@ -2469,47 +1872,33 @@ CToken* CTokenizer::HandleQuote() return CCharToken::Create(theByte); } -void CTokenizer::SetFlags(UINT flags) -{ - m_flags = flags; -} +void CTokenizer::SetFlags(UINT flags) { m_flags = flags; } -UINT CTokenizer::GetFlags() -{ - return m_flags; -} +UINT CTokenizer::GetFlags() { return m_flags; } -CToken* CTokenizer::HandleSymbol(byte theByte) -{ +CToken *CTokenizer::HandleSymbol(byte theByte) { char symbolString[128]; int curStrLen = 0; symbolString[0] = '\0'; bool consumed = false; - CSymbolLookup* curLookup; - if ((m_flags & TKF_RAWSYMBOLSONLY) == 0) - { + CSymbolLookup *curLookup; + if ((m_flags & TKF_RAWSYMBOLSONLY) == 0) { curLookup = m_symbolLookup; - } - else - { + } else { curLookup = NULL; } - CSymbolLookup* lastLookup = NULL; - while(curLookup != NULL) - { - if (curLookup->GetByte() == theByte) - { + CSymbolLookup *lastLookup = NULL; + while (curLookup != NULL) { + if (curLookup->GetByte() == theByte) { symbolString[curStrLen++] = theByte; symbolString[curStrLen] = '\0'; lastLookup = curLookup; consumed = true; - if (curLookup->GetChild() == NULL) - { + if (curLookup->GetChild() == NULL) { break; } - if (!NextChar(theByte)) - { + if (!NextChar(theByte)) { PutBackToken(CToken::Create()); break; } @@ -2519,60 +1908,44 @@ CToken* CTokenizer::HandleSymbol(byte theByte) } curLookup = curLookup->GetNext(); } - if ((!consumed) && (lastLookup != NULL)) - { + if ((!consumed) && (lastLookup != NULL)) { PutBackChar(theByte); } - while ((lastLookup != NULL) && (lastLookup->GetValue() == -1)) - { + while ((lastLookup != NULL) && (lastLookup->GetValue() == -1)) { curStrLen--; symbolString[curStrLen] = '\0'; - // symbolString = symbolString.Left(symbolString.GetLength() - 1); - if (lastLookup->GetParent() == NULL) - { - if ((m_flags & TKF_WANTUNDEFINED) == 0) - { + // symbolString = symbolString.Left(symbolString.GetLength() - 1); + if (lastLookup->GetParent() == NULL) { + if ((m_flags & TKF_WANTUNDEFINED) == 0) { Error(TKERR_UNRECOGNIZEDSYMBOL); } - } - else - { + } else { PutBackChar(lastLookup->GetByte()); } lastLookup = lastLookup->GetParent(); } - if (lastLookup == NULL) - { - if ((m_flags & TKF_WANTUNDEFINED) == 0) - { + if (lastLookup == NULL) { + if ((m_flags & TKF_WANTUNDEFINED) == 0) { return NULL; } curStrLen = 0; symbolString[curStrLen++] = char(theByte); symbolString[curStrLen] = '\0'; - if ((m_flags & TKF_WIDEUNDEFINEDSYMBOLS) != 0) - { - while (true) - { - if (!NextChar(theByte)) - { + if ((m_flags & TKF_WIDEUNDEFINEDSYMBOLS) != 0) { + while (true) { + if (!NextChar(theByte)) { PutBackToken(CToken::Create()); break; } - if (theByte == ' ') - { + if (theByte == ' ') { break; } - if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || - ((theByte >= '0') && (theByte <= '9'))) - { + if (((theByte >= 'a') && (theByte <= 'z')) || ((theByte >= 'A') && (theByte <= 'Z')) || ((theByte >= '0') && (theByte <= '9'))) { PutBackChar(theByte); break; } - if (theByte < ' ') - { - if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) - { + if (theByte < ' ') { + if ((theByte == '\n') && ((TKF_USES_EOL & m_flags) != 0)) { PutBackToken(CUserToken::Create(TK_EOL, "-EOLN-")); break; } @@ -2587,37 +1960,31 @@ CToken* CTokenizer::HandleSymbol(byte theByte) return CUserToken::Create(lastLookup->GetValue(), symbolString); } -CToken* CTokenizer::HandleDirective() -{ +CToken *CTokenizer::HandleDirective() { int tokenValue = 0; - CToken* theToken = FetchToken(); - if (theToken->GetType() == TK_EOF) - { + CToken *theToken = FetchToken(); + if (theToken->GetType() == TK_EOF) { return theToken; } - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_INVALID_DIRECTIVE); theToken->Delete(); SkipToLineEnd(); return NULL; } - CDirectiveSymbol* curSymbol; - CTokenizerState* state; + CDirectiveSymbol *curSymbol; + CTokenizerState *state; int theDirective = DirectiveFromName(theToken->GetStringValue()); theToken->Delete(); byte theByte; - switch(theDirective) - { + switch (theDirective) { case DIR_INCLUDE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_STRING) - { + if (theToken->GetType() != TK_STRING) { Error(TKERR_INCLUDE_FILE_NOTFOUND); theToken->Delete(); SkipToLineEnd(); @@ -2627,16 +1994,14 @@ CToken* CTokenizer::HandleDirective() theToken->Delete(); break; case DIR_IFDEF: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { state = CTokenizerHolderState::Create(); state->SetNext(m_state); m_state = state; break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2648,16 +2013,14 @@ CToken* CTokenizer::HandleDirective() m_state = state; break; case DIR_IFNDEF: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { state = CTokenizerHolderState::Create(); state->SetNext(m_state); m_state = state; break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2669,8 +2032,7 @@ CToken* CTokenizer::HandleDirective() m_state = state; break; case DIR_ENDIF: - if (m_state == NULL) - { + if (m_state == NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } @@ -2679,25 +2041,21 @@ CToken* CTokenizer::HandleDirective() state->Delete(); break; case DIR_ELSE: - if (m_state == NULL) - { + if (m_state == NULL) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } - if (!m_state->ProcessElse()) - { + if (!m_state->ProcessElse()) { Error(TKERR_UNMATCHED_DIRECTIVE); break; } break; case DIR_DEFINE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2708,30 +2066,25 @@ CToken* CTokenizer::HandleDirective() curSymbol = CDirectiveSymbol::Create(theToken->GetStringValue()); char temp[128]; int tempsize = 0; - while(NextChar(theByte)) - { - if (theByte == '\n') - { + while (NextChar(theByte)) { + if (theByte == '\n') { break; } temp[tempsize++] = char(theByte); } temp[tempsize] = '\0'; curSymbol->SetValue(temp); - if (!m_defines.AddSymbol(curSymbol)) - { + if (!m_defines.AddSymbol(curSymbol)) { curSymbol->Delete(); } } break; case DIR_UNDEFINE: - if ((m_state != NULL) && (m_state->Skipping())) - { + if ((m_state != NULL) && (m_state->Skipping())) { break; } theToken = GetToken(); - if (theToken->GetType() != TK_IDENTIFIER) - { + if (theToken->GetType() != TK_IDENTIFIER) { Error(TKERR_EXPECTED_IDENTIFIER); theToken->Delete(); SkipToLineEnd(); @@ -2747,11 +2100,9 @@ CToken* CTokenizer::HandleDirective() return NULL; } -COLORREF CTokenizer::ParseRGB() -{ - CToken* theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { +COLORREF CTokenizer::ParseRGB() { + CToken *theToken = GetToken(); + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2759,8 +2110,7 @@ COLORREF CTokenizer::ParseRGB() int red = theToken->GetIntValue(); theToken->Delete(); theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2768,8 +2118,7 @@ COLORREF CTokenizer::ParseRGB() int green = theToken->GetIntValue(); theToken->Delete(); theToken = GetToken(); - if (theToken->GetType() != TK_INT) - { + if (theToken->GetType() != TK_INT) { Error(TKERR_EXPECTED_INTEGER); theToken->Delete(); return RGB(0, 0, 0); @@ -2783,38 +2132,29 @@ COLORREF CTokenizer::ParseRGB() // CSymbolLookup // -CSymbolLookup::CSymbolLookup() -{ -} +CSymbolLookup::CSymbolLookup() {} -CSymbolLookup::~CSymbolLookup() -{ -} +CSymbolLookup::~CSymbolLookup() {} -CSymbolLookup* CSymbolLookup::Create(byte theByte) -{ - CSymbolLookup* curLookup = new CSymbolLookup(); +CSymbolLookup *CSymbolLookup::Create(byte theByte) { + CSymbolLookup *curLookup = new CSymbolLookup(); curLookup->Init(theByte); return curLookup; } -void CSymbolLookup::Delete() -{ - if (m_sibling != NULL) - { +void CSymbolLookup::Delete() { + if (m_sibling != NULL) { m_sibling->Delete(); m_sibling = NULL; } - if (m_child != NULL) - { + if (m_child != NULL) { m_child->Delete(); m_child = NULL; } delete this; } -void CSymbolLookup::Init(byte theByte) -{ +void CSymbolLookup::Init(byte theByte) { m_parent = NULL; m_child = NULL; m_sibling = NULL; @@ -2822,47 +2162,20 @@ void CSymbolLookup::Init(byte theByte) m_byte = theByte; } -CSymbolLookup* CSymbolLookup::GetNext() -{ - return m_sibling; -} +CSymbolLookup *CSymbolLookup::GetNext() { return m_sibling; } -void CSymbolLookup::SetNext(CSymbolLookup* next) -{ - m_sibling = next; -} +void CSymbolLookup::SetNext(CSymbolLookup *next) { m_sibling = next; } -void CSymbolLookup::SetParent(CSymbolLookup* parent) -{ - m_parent = parent; -} +void CSymbolLookup::SetParent(CSymbolLookup *parent) { m_parent = parent; } -void CSymbolLookup::SetValue(int value) -{ - m_value = value; -} +void CSymbolLookup::SetValue(int value) { m_value = value; } -int CSymbolLookup::GetValue() -{ - return m_value; -} +int CSymbolLookup::GetValue() { return m_value; } -byte CSymbolLookup::GetByte() -{ - return m_byte; -} +byte CSymbolLookup::GetByte() { return m_byte; } -CSymbolLookup** CSymbolLookup::GetChildAddress() -{ - return &m_child; -} +CSymbolLookup **CSymbolLookup::GetChildAddress() { return &m_child; } -CSymbolLookup* CSymbolLookup::GetChild() -{ - return m_child; -} +CSymbolLookup *CSymbolLookup::GetChild() { return m_child; } -CSymbolLookup* CSymbolLookup::GetParent() -{ - return m_parent; -} +CSymbolLookup *CSymbolLookup::GetParent() { return m_parent; } diff --git a/codemp/mp3code/cdct.c b/codemp/mp3code/cdct.c index 7afb95f608..80cc841ae9 100644 --- a/codemp/mp3code/cdct.c +++ b/codemp/mp3code/cdct.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -40,279 +40,252 @@ portable C #include #include -float coef32[31]; /* 32 pt dct coefs */ // !!!!!!!!!!!!!!!!!! (only generated once (always to same value) +float coef32[31]; /* 32 pt dct coefs */ // !!!!!!!!!!!!!!!!!! (only generated once (always to same value) /*------------------------------------------------------------*/ -float *dct_coef_addr() -{ - return coef32; -} +float *dct_coef_addr() { return coef32; } /*------------------------------------------------------------*/ -static void forward_bf(int m, int n, float x[], float f[], float coef[]) -{ - int i, j, n2; - int p, q, p0, k; +static void forward_bf(int m, int n, float x[], float f[], float coef[]) { + int i, j, n2; + int p, q, p0, k; - p0 = 0; - n2 = n >> 1; - for (i = 0; i < m; i++, p0 += n) - { - k = 0; - p = p0; - q = p + n - 1; - for (j = 0; j < n2; j++, p++, q--, k++) - { - f[p] = x[p] + x[q]; - f[n2 + p] = coef[k] * (x[p] - x[q]); - } - } + p0 = 0; + n2 = n >> 1; + for (i = 0; i < m; i++, p0 += n) { + k = 0; + p = p0; + q = p + n - 1; + for (j = 0; j < n2; j++, p++, q--, k++) { + f[p] = x[p] + x[q]; + f[n2 + p] = coef[k] * (x[p] - x[q]); + } + } } /*------------------------------------------------------------*/ -static void back_bf(int m, int n, float x[], float f[]) -{ - int i, j, n2, n21; - int p, q, p0; +static void back_bf(int m, int n, float x[], float f[]) { + int i, j, n2, n21; + int p, q, p0; - p0 = 0; - n2 = n >> 1; - n21 = n2 - 1; - for (i = 0; i < m; i++, p0 += n) - { - p = p0; - q = p0; - for (j = 0; j < n2; j++, p += 2, q++) - f[p] = x[q]; - p = p0 + 1; - for (j = 0; j < n21; j++, p += 2, q++) - f[p] = x[q] + x[q + 1]; - f[p] = x[q]; - } + p0 = 0; + n2 = n >> 1; + n21 = n2 - 1; + for (i = 0; i < m; i++, p0 += n) { + p = p0; + q = p0; + for (j = 0; j < n2; j++, p += 2, q++) + f[p] = x[q]; + p = p0 + 1; + for (j = 0; j < n21; j++, p += 2, q++) + f[p] = x[q] + x[q + 1]; + f[p] = x[q]; + } } /*------------------------------------------------------------*/ +void fdct32(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + int p, q; -void fdct32(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - int p, q; - - float *src = x; + float *src = x; -/* special first stage */ - for (p = 0, q = 31; p < 16; p++, q--) - { - a[p] = src[p] + src[q]; - a[16 + p] = coef32[p] * (src[p] - src[q]); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage */ + for (p = 0, q = 31; p < 16; p++, q--) { + a[p] = src[p] + src[q]; + a[16 + p] = coef32[p] * (src[p] - src[q]); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*------------------------------------------------------------*/ -void fdct32_dual(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - int p, pp, qq; +void fdct32_dual(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + int p, pp, qq; -/* special first stage for dual chan (interleaved x) */ - pp = 0; - qq = 2 * 31; - for (p = 0; p < 16; p++, pp += 2, qq -= 2) - { - a[p] = x[pp] + x[qq]; - a[16 + p] = coef32[p] * (x[pp] - x[qq]); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage for dual chan (interleaved x) */ + pp = 0; + qq = 2 * 31; + for (p = 0; p < 16; p++, pp += 2, qq -= 2) { + a[p] = x[pp] + x[qq]; + a[16 + p] = coef32[p] * (x[pp] - x[qq]); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*---------------convert dual to mono------------------------------*/ -void fdct32_dual_mono(float x[], float c[]) -{ - float a[32]; /* ping pong buffers */ - float b[32]; - float t1, t2; - int p, pp, qq; +void fdct32_dual_mono(float x[], float c[]) { + float a[32]; /* ping pong buffers */ + float b[32]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - pp = 0; - qq = 2 * 31; - for (p = 0; p < 16; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - a[p] = t1 + t2; - a[16 + p] = coef32[p] * (t1 - t2); - } - forward_bf(2, 16, a, b, coef32 + 16); - forward_bf(4, 8, b, a, coef32 + 16 + 8); - forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); - forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); - back_bf(8, 4, a, b); - back_bf(4, 8, b, a); - back_bf(2, 16, a, b); - back_bf(1, 32, b, c); + /* special first stage */ + pp = 0; + qq = 2 * 31; + for (p = 0; p < 16; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + a[p] = t1 + t2; + a[16 + p] = coef32[p] * (t1 - t2); + } + forward_bf(2, 16, a, b, coef32 + 16); + forward_bf(4, 8, b, a, coef32 + 16 + 8); + forward_bf(8, 4, a, b, coef32 + 16 + 8 + 4); + forward_bf(16, 2, b, a, coef32 + 16 + 8 + 4 + 2); + back_bf(8, 4, a, b); + back_bf(4, 8, b, a); + back_bf(2, 16, a, b); + back_bf(1, 32, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct -------------------------------*/ -void fdct16(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - int p, q; +void fdct16(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + int p, q; -/* special first stage (drop highest sb) */ - a[0] = x[0]; - a[8] = coef32[16] * x[0]; - for (p = 1, q = 14; p < 8; p++, q--) - { - a[p] = x[p] + x[q]; - a[8 + p] = coef32[16 + p] * (x[p] - x[q]); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage (drop highest sb) */ + a[0] = x[0]; + a[8] = coef32[16] * x[0]; + for (p = 1, q = 14; p < 8; p++, q--) { + a[p] = x[p] + x[q]; + a[8 + p] = coef32[16 + p] * (x[p] - x[q]); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual chan---------------------*/ -void fdct16_dual(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - int p, pp, qq; +void fdct16_dual(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + int p, pp, qq; -/* special first stage for interleaved input */ - a[0] = x[0]; - a[8] = coef32[16] * x[0]; - pp = 2; - qq = 2 * 14; - for (p = 1; p < 8; p++, pp += 2, qq -= 2) - { - a[p] = x[pp] + x[qq]; - a[8 + p] = coef32[16 + p] * (x[pp] - x[qq]); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage for interleaved input */ + a[0] = x[0]; + a[8] = coef32[16] * x[0]; + pp = 2; + qq = 2 * 14; + for (p = 1; p < 8; p++, pp += 2, qq -= 2) { + a[p] = x[pp] + x[qq]; + a[8 + p] = coef32[16 + p] * (x[pp] - x[qq]); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 16 pt fdct dual to mono-------------------*/ -void fdct16_dual_mono(float x[], float c[]) -{ - float a[16]; /* ping pong buffers */ - float b[16]; - float t1, t2; - int p, pp, qq; +void fdct16_dual_mono(float x[], float c[]) { + float a[16]; /* ping pong buffers */ + float b[16]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - a[0] = 0.5F * (x[0] + x[1]); - a[8] = coef32[16] * a[0]; - pp = 2; - qq = 2 * 14; - for (p = 1; p < 8; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - a[p] = t1 + t2; - a[8 + p] = coef32[16 + p] * (t1 - t2); - } - forward_bf(2, 8, a, b, coef32 + 16 + 8); - forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(4, 4, b, a); - back_bf(2, 8, a, b); - back_bf(1, 16, b, c); + /* special first stage */ + a[0] = 0.5F * (x[0] + x[1]); + a[8] = coef32[16] * a[0]; + pp = 2; + qq = 2 * 14; + for (p = 1; p < 8; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + a[p] = t1 + t2; + a[8 + p] = coef32[16 + p] * (t1 - t2); + } + forward_bf(2, 8, a, b, coef32 + 16 + 8); + forward_bf(4, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(8, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(4, 4, b, a); + back_bf(2, 8, a, b); + back_bf(1, 16, b, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct -------------------------------*/ -void fdct8(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - int p, q; +void fdct8(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + int p, q; -/* special first stage */ + /* special first stage */ - b[0] = x[0] + x[7]; - b[4] = coef32[16 + 8] * (x[0] - x[7]); - for (p = 1, q = 6; p < 4; p++, q--) - { - b[p] = x[p] + x[q]; - b[4 + p] = coef32[16 + 8 + p] * (x[p] - x[q]); - } + b[0] = x[0] + x[7]; + b[4] = coef32[16 + 8] * (x[0] - x[7]); + for (p = 1, q = 6; p < 4; p++, q--) { + b[p] = x[p] + x[q]; + b[4 + p] = coef32[16 + 8 + p] * (x[p] - x[q]); + } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual chan---------------------*/ -void fdct8_dual(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - int p, pp, qq; +void fdct8_dual(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + int p, pp, qq; -/* special first stage for interleaved input */ - b[0] = x[0] + x[14]; - b[4] = coef32[16 + 8] * (x[0] - x[14]); - pp = 2; - qq = 2 * 6; - for (p = 1; p < 4; p++, pp += 2, qq -= 2) - { - b[p] = x[pp] + x[qq]; - b[4 + p] = coef32[16 + 8 + p] * (x[pp] - x[qq]); - } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + /* special first stage for interleaved input */ + b[0] = x[0] + x[14]; + b[4] = coef32[16 + 8] * (x[0] - x[14]); + pp = 2; + qq = 2 * 6; + for (p = 1; p < 4; p++, pp += 2, qq -= 2) { + b[p] = x[pp] + x[qq]; + b[4 + p] = coef32[16 + 8 + p] * (x[pp] - x[qq]); + } + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ /*---------------- 8 pt fdct dual to mono---------------------*/ -void fdct8_dual_mono(float x[], float c[]) -{ - float a[8]; /* ping pong buffers */ - float b[8]; - float t1, t2; - int p, pp, qq; +void fdct8_dual_mono(float x[], float c[]) { + float a[8]; /* ping pong buffers */ + float b[8]; + float t1, t2; + int p, pp, qq; -/* special first stage */ - t1 = 0.5F * (x[0] + x[1]); - t2 = 0.5F * (x[14] + x[15]); - b[0] = t1 + t2; - b[4] = coef32[16 + 8] * (t1 - t2); - pp = 2; - qq = 2 * 6; - for (p = 1; p < 4; p++, pp += 2, qq -= 2) - { - t1 = 0.5F * (x[pp] + x[pp + 1]); - t2 = 0.5F * (x[qq] + x[qq + 1]); - b[p] = t1 + t2; - b[4 + p] = coef32[16 + 8 + p] * (t1 - t2); - } - forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); - forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); - back_bf(2, 4, b, a); - back_bf(1, 8, a, c); + /* special first stage */ + t1 = 0.5F * (x[0] + x[1]); + t2 = 0.5F * (x[14] + x[15]); + b[0] = t1 + t2; + b[4] = coef32[16 + 8] * (t1 - t2); + pp = 2; + qq = 2 * 6; + for (p = 1; p < 4; p++, pp += 2, qq -= 2) { + t1 = 0.5F * (x[pp] + x[pp + 1]); + t2 = 0.5F * (x[qq] + x[qq + 1]); + b[p] = t1 + t2; + b[4 + p] = coef32[16 + 8 + p] * (t1 - t2); + } + forward_bf(2, 4, b, a, coef32 + 16 + 8 + 4); + forward_bf(4, 2, a, b, coef32 + 16 + 8 + 4 + 2); + back_bf(2, 4, b, a); + back_bf(1, 8, a, c); } /*------------------------------------------------------------*/ diff --git a/codemp/mp3code/csbt.c b/codemp/mp3code/csbt.c index b264317528..bff51cfeac 100644 --- a/codemp/mp3code/csbt.c +++ b/codemp/mp3code/csbt.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -66,290 +66,246 @@ void window8_dual(float *vbuf, int vb_ptr, short *pcm); float *dct_coef_addr(); /*======================================================================*/ -static void gencoef() /* gen coef for N=32 (31 coefs) */ +static void gencoef() /* gen coef for N=32 (31 coefs) */ { static int iOnceOnly = 0; - int p, n, i, k; - double t, pi; - float *coef32; - - if (!iOnceOnly++) - { - coef32 = dct_coef_addr(); - - pi = 4.0 * atan(1.0); - n = 16; - k = 0; - for (i = 0; i < 5; i++, n = n / 2) - { - - for (p = 0; p < n; p++, k++) - { - t = (pi / (4 * n)) * (2 * p + 1); - coef32[k] = (float) (0.50 / cos(t)); - } - } - } + int p, n, i, k; + double t, pi; + float *coef32; + + if (!iOnceOnly++) { + coef32 = dct_coef_addr(); + + pi = 4.0 * atan(1.0); + n = 16; + k = 0; + for (i = 0; i < 5; i++, n = n / 2) { + + for (p = 0; p < n; p++, k++) { + t = (pi / (4 * n)) * (2 * p + 1); + coef32[k] = (float)(0.50 / cos(t)); + } + } + } } /*------------------------------------------------------------*/ -void sbt_init() -{ - int i; - static int first_pass = 1; - - if (first_pass) - { - gencoef(); - first_pass = 0; - } - -/* clear window pMP3Stream->vbuf */ - for (i = 0; i < 512; i++) - { - pMP3Stream->vbuf[i] = 0.0F; - pMP3Stream->vbuf2[i] = 0.0F; - } - pMP3Stream->vb2_ptr = pMP3Stream->vb_ptr = 0; - +void sbt_init() { + int i; + static int first_pass = 1; + + if (first_pass) { + gencoef(); + first_pass = 0; + } + + /* clear window pMP3Stream->vbuf */ + for (i = 0; i < 512; i++) { + pMP3Stream->vbuf[i] = 0.0F; + pMP3Stream->vbuf2[i] = 0.0F; + } + pMP3Stream->vb2_ptr = pMP3Stream->vb_ptr = 0; } /*============================================================*/ /*============================================================*/ /*============================================================*/ -void sbt_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbt_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbt_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 64; - } - - +void sbt_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 64; + } } /*------------------------------------------------------------*/ /* convert dual to mono */ -void sbt_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbt_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to left */ -void sbt_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbt_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to right */ -void sbt_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; /* point to right chan */ - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbt_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; /* point to right chan */ + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt16_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } - - +void sbt16_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } +void sbt16_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbt16_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt16_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbt16_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt8_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } - +void sbt8_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 16; - } +void sbt8_dual(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbt8_dual_mono(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_mono(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual_left(float *sample, short *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_left(float *sample, short *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbt8_dual_right(float *sample, short *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbt8_dual_right(float *sample, short *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ #define COMPILE_ME -#include "csbtb.c" /* 8 bit output */ -#include "csbtl3.c" /* Layer III */ +#include "csbtb.c" /* 8 bit output */ +#include "csbtl3.c" /* Layer III */ /*------------------------------------------------------------*/ diff --git a/codemp/mp3code/csbtb.c b/codemp/mp3code/csbtb.c index dfb401171c..1e1e30e43d 100644 --- a/codemp/mp3code/csbtb.c +++ b/codemp/mp3code/csbtb.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -42,237 +42,200 @@ void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm); void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm); /*============================================================*/ -void sbtB_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbtB_mono(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbtB_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 64; - } - - +void sbtB_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct32_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 64; + } } /*------------------------------------------------------------*/ /* convert dual to mono */ -void sbtB_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } - +void sbtB_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to left */ -void sbtB_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbtB_dual_left(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /* convert dual to right */ -void sbtB_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; /* point to right chan */ - for (i = 0; i < n; i++) - { - fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; - pcm += 32; - } +void sbtB_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; /* point to right chan */ + for (i = 0; i < n; i++) { + fdct32_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; + pcm += 32; + } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB16_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } - +void sbtB16_mono(float *sample, unsigned char *pcm, int n) { + int i; + for (i = 0; i < n; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } +void sbtB16_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct16_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB16_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } + for (i = 0; i < n; i++) { + fdct16_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB16_dual_left(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB16_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 16; - } +void sbtB16_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct16_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 16; + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB8_mono(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbtB8_mono(float *sample, unsigned char *pcm, int n) { + int i; + for (i = 0; i < n; i++) { + fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual(float *sample, unsigned char *pcm, int n) -{ - int i; - - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); - windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 16; - } +void sbtB8_dual(float *sample, unsigned char *pcm, int n) { + int i; + + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + fdct8_dual(sample + 1, pMP3Stream->vbuf2 + pMP3Stream->vb_ptr); + windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb_ptr, pcm + 1); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 16; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } + for (i = 0; i < n; i++) { + fdct8_dual_mono(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_left(float *sample, unsigned char *pcm, int n) -{ - int i; +void sbtB8_dual_left(float *sample, unsigned char *pcm, int n) { + int i; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -void sbtB8_dual_right(float *sample, unsigned char *pcm, int n) -{ - int i; - - sample++; - for (i = 0; i < n; i++) - { - fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 64; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; - pcm += 8; - } +void sbtB8_dual_right(float *sample, unsigned char *pcm, int n) { + int i; + + sample++; + for (i = 0; i < n; i++) { + fdct8_dual(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 64; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; + pcm += 8; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/csbtl3.c b/codemp/mp3code/csbtl3.c index e63995c08e..9d59ea8e94 100644 --- a/codemp/mp3code/csbtl3.c +++ b/codemp/mp3code/csbtl3.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -35,13 +35,11 @@ layer III /*============================================================*/ /*============ Layer III =====================================*/ /*============================================================*/ -void sbt_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -50,25 +48,19 @@ void sbt_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt_dual_L3(float *sample, short *pcm, int ch) -{ +void sbt_dual_L3(float *sample, short *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; pcm += 64; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); window_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -81,13 +73,11 @@ void sbt_dual_L3(float *sample, short *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt16_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt16_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -96,43 +86,35 @@ void sbt16_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt16_dual_L3(float *sample, short *pcm, int ch) -{ - int i; +void sbt16_dual_L3(float *sample, short *pcm, int ch) { + int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { - fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); - window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); - sample += 32; - pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; - pcm += 32; - } - } - else - { - for (i = 0; i < 18; i++) - { - fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); - window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); - sample += 32; - pMP3Stream->vb2_ptr = (pMP3Stream->vb2_ptr - 16) & 255; - pcm += 32; - } - } + if (ch == 0) { + for (i = 0; i < 18; i++) { + fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); + window16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); + sample += 32; + pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; + pcm += 32; + } + } else { + for (i = 0; i < 18; i++) { + fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); + window16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); + sample += 32; + pMP3Stream->vb2_ptr = (pMP3Stream->vb2_ptr - 16) & 255; + pcm += 32; + } + } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ -void sbt8_mono_L3(float *sample, short *pcm, int ch) -{ +void sbt8_mono_L3(float *sample, short *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -141,25 +123,19 @@ void sbt8_mono_L3(float *sample, short *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbt8_dual_L3(float *sample, short *pcm, int ch) -{ +void sbt8_dual_L3(float *sample, short *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); window8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; pcm += 16; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); window8_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -171,13 +147,11 @@ void sbt8_dual_L3(float *sample, short *pcm, int ch) /*------------------------------------------------------------*/ /*------- 8 bit output ---------------------------------------*/ /*------------------------------------------------------------*/ -void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -186,25 +160,19 @@ void sbtB_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 32) & 511; pcm += 64; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct32(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -217,13 +185,11 @@ void sbtB_dual_L3(float *sample, unsigned char *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 16 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB16(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -232,25 +198,19 @@ void sbtB16_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB16_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 16) & 255; pcm += 32; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct16(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB16_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -262,13 +222,11 @@ void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch) /*------------------------------------------------------------*/ /*---------------- 8 pt sbtB's -------------------------------*/ /*------------------------------------------------------------*/ -void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) { int i; ch = 0; - for (i = 0; i < 18; i++) - { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB8(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; @@ -277,25 +235,19 @@ void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) -{ +void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) { int i; - if (ch == 0) - { - for (i = 0; i < 18; i++) - { + if (ch == 0) { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf + pMP3Stream->vb_ptr); windowB8_dual(pMP3Stream->vbuf, pMP3Stream->vb_ptr, pcm); sample += 32; pMP3Stream->vb_ptr = (pMP3Stream->vb_ptr - 8) & 127; pcm += 16; } - } - else - { - for (i = 0; i < 18; i++) - { + } else { + for (i = 0; i < 18; i++) { fdct8(sample, pMP3Stream->vbuf2 + pMP3Stream->vb2_ptr); windowB8_dual(pMP3Stream->vbuf2, pMP3Stream->vb2_ptr, pcm + 1); sample += 32; @@ -305,4 +257,4 @@ void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch) } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/cup.c b/codemp/mp3code/cup.c index beaa54ffd3..516faa76a7 100644 --- a/codemp/mp3code/cup.c +++ b/codemp/mp3code/cup.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,43 +37,43 @@ mods 11/15/95 for Layer I ******************************************************************/ /****************************************************************** - MPEG audio software decoder portable ANSI c. - Decodes all Layer I/II to 16 bit linear pcm. - Optional stereo to mono conversion. Optional - output sample rate conversion to half or quarter of - native mpeg rate. dec8.c adds oupuut conversion features. + MPEG audio software decoder portable ANSI c. + Decodes all Layer I/II to 16 bit linear pcm. + Optional stereo to mono conversion. Optional + output sample rate conversion to half or quarter of + native mpeg rate. dec8.c adds oupuut conversion features. ------------------------------------- int audio_decode_init(MPEG_HEAD *h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) + int reduction_code, int transform_code, int convert_code, + int freq_limit) initilize decoder: - return 0 = fail, not 0 = success + return 0 = fail, not 0 = success MPEG_HEAD *h input, mpeg header info (returned by call to head_info) pMP3Stream->framebytes input, mpeg frame size (returned by call to head_info) reduction_code input, sample rate reduction code - 0 = full rate - 1 = half rate - 2 = quarter rate + 0 = full rate + 1 = half rate + 2 = quarter rate transform_code input, ignored convert_code input, channel conversion - convert_code: 0 = two chan output - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan + convert_code: 0 = two chan output + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan freq_limit input, limits bandwidth of pcm output to specified - frequency. Special use. Set to 24000 for normal use. + frequency. Special use. Set to 24000 for normal use. --------------------------------- void audio_decode_info( DEC_INFO *info) information return: - Call after audio_decode_init. See mhead.h for - information returned in DEC_INFO structure. + Call after audio_decode_init. See mhead.h for + information returned in DEC_INFO structure. --------------------------------- @@ -81,27 +81,25 @@ IN_OUT audio_decode(unsigned char *bs, void *pcmbuf) decode one mpeg audio frame: bs input, mpeg bitstream, must start with - sync word. Caution: may read up to 3 bytes - beyond end of frame. + sync word. Caution: may read up to 3 bytes + beyond end of frame. pcmbuf output, pcm samples. IN_OUT structure returns: - Number bytes conceptually removed from mpeg bitstream. - Returns 0 if sync loss. - Number bytes of pcm output. + Number bytes conceptually removed from mpeg bitstream. + Returns 0 if sync loss. + Number bytes of pcm output. *******************************************************************/ - #include #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ #include "mp3struct.h" - /*------------------------------------------------------- NOTE: Decoder may read up to three bytes beyond end of frame. Calling application must ensure that this does @@ -111,22 +109,22 @@ not cause a memory access violation (protection fault) /*====================================================================*/ /*----------------*/ //@@@@ This next one (decinfo) is ok: -DEC_INFO decinfo; /* global for Layer III */ // only written into by decode init funcs, then copied to stack struct higher up +DEC_INFO decinfo; /* global for Layer III */ // only written into by decode init funcs, then copied to stack struct higher up /*----------------*/ -static float look_c_value[18]; /* built by init */ // effectively constant +static float look_c_value[18]; /* built by init */ // effectively constant /*----------------*/ ////@@@@static int pMP3Stream->outbytes; // !!!!!!!!!!!!!!? ////@@@@static int pMP3Stream->framebytes; // !!!!!!!!!!!!!!!! ////@@@@static int pMP3Stream->outvalues; // !!!!!!!!!!!!? ////@@@@static int pad; -static const int look_joint[16] = -{ /* lookup stereo sb's by mode+ext */ - 64, 64, 64, 64, /* stereo */ - 2 * 4, 2 * 8, 2 * 12, 2 * 16, /* joint */ - 64, 64, 64, 64, /* dual */ - 32, 32, 32, 32, /* mono */ +static const int look_joint[16] = { + /* lookup stereo sb's by mode+ext */ + 64, 64, 64, 64, /* stereo */ + 2 * 4, 2 * 8, 2 * 12, 2 * 16, /* joint */ + 64, 64, 64, 64, /* dual */ + 32, 32, 32, 32, /* mono */ }; /*----------------*/ @@ -136,28 +134,26 @@ static const int look_joint[16] = /*----------------*/ ////@@@@static int pMP3Stream->nsb_limit = 6; ////@@@@static int bit_skip; -static const int bat_bit_master[] = -{ - 0, 5, 7, 9, 10, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}; +static const int bat_bit_master[] = {0, 5, 7, 9, 10, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}; /*----------------*/ ////@@@@static int nbat[4] = {3, 8, 12, 7}; // !!!!!!!!!!!!! not constant!!!! ////@@@@static int bat[4][16]; // built as constant, but built according to header type (sigh) -static int ballo[64]; /* set by unpack_ba */ // scratchpad -static unsigned int samp_dispatch[66]; /* set by unpack_ba */ // scratchpad? -static float c_value[64]; /* set by unpack_ba */ // scratchpad +static int ballo[64]; /* set by unpack_ba */ // scratchpad +static unsigned int samp_dispatch[66]; /* set by unpack_ba */ // scratchpad? +static float c_value[64]; /* set by unpack_ba */ // scratchpad /*----------------*/ -static unsigned int sf_dispatch[66]; /* set by unpack_ba */ // scratchpad? -static float sf_table[64]; // effectively constant +static unsigned int sf_dispatch[66]; /* set by unpack_ba */ // scratchpad? +static float sf_table[64]; // effectively constant ////@@@@ static float cs_factor[3][64]; /*----------------*/ ////@@@@FINDME - groan.... (I shoved a *2 in just in case it needed it for stereo. This whole thing is crap now -float sample[2304*2]; /* global for use by Later 3 */ // !!!!!!!!!!!!!!!!!!!!!! // scratchpad? -static signed char group3_table[32][3]; // effectively constant -static signed char group5_table[128][3]; // effectively constant -static signed short group9_table[1024][3]; // effectively constant +float sample[2304 * 2]; /* global for use by Later 3 */ // !!!!!!!!!!!!!!!!!!!!!! // scratchpad? +static signed char group3_table[32][3]; // effectively constant +static signed char group5_table[128][3]; // effectively constant +static signed short group9_table[1024][3]; // effectively constant /*----------------*/ @@ -166,8 +162,7 @@ void sbt_mono(float *sample, short *pcm, int n); void sbt_dual(float *sample, short *pcm, int n); ////@@@@static SBT_FUNCTION sbt = sbt_mono; - -typedef IN_OUT(*AUDIO_DECODE_ROUTINE) (unsigned char *bs, signed short *pcm); +typedef IN_OUT (*AUDIO_DECODE_ROUTINE)(unsigned char *bs, signed short *pcm); IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm); static AUDIO_DECODE_ROUTINE audio_decode_routine = L2audio_decode; @@ -181,361 +176,343 @@ static int bits; static long bitval; /*------------- initialize bit getter -------------*/ -static void load_init(unsigned char *buf) -{ - bs_ptr = buf; - bits = 0; - bitbuf = 0; +static void load_init(unsigned char *buf) { + bs_ptr = buf; + bits = 0; + bitbuf = 0; } /*------------- get n bits from bitstream -------------*/ -static long load(int n) -{ - unsigned long x; - - if (bits < n) - { /* refill bit buf if necessary */ - while (bits <= 24) - { - bitbuf = (bitbuf << 8) | *bs_ptr++; - bits += 8; - } - } - bits -= n; - x = bitbuf >> bits; - bitbuf -= x << bits; - return x; +static long load(int n) { + unsigned long x; + + if (bits < n) { /* refill bit buf if necessary */ + while (bits <= 24) { + bitbuf = (bitbuf << 8) | *bs_ptr++; + bits += 8; + } + } + bits -= n; + x = bitbuf >> bits; + bitbuf -= x << bits; + return x; } /*------------- skip over n bits in bitstream -------------*/ -static void skip(int n) -{ - int k; - - if (bits < n) - { - n -= bits; - k = n >> 3; -/*--- bytes = n/8 --*/ - bs_ptr += k; - n -= k << 3; - bitbuf = *bs_ptr++; - bits = 8; - } - bits -= n; - bitbuf -= (bitbuf >> bits) << bits; +static void skip(int n) { + int k; + + if (bits < n) { + n -= bits; + k = n >> 3; + /*--- bytes = n/8 --*/ + bs_ptr += k; + n -= k << 3; + bitbuf = *bs_ptr++; + bits = 8; + } + bits -= n; + bitbuf -= (bitbuf >> bits) << bits; } /*--------------------------------------------------------------*/ -#define mac_load_check(n) if( bits < (n) ) { \ - while( bits <= 24 ) { \ - bitbuf = (bitbuf << 8) | *bs_ptr++; \ - bits += 8; \ - } \ - } +#define mac_load_check(n) \ + if (bits < (n)) { \ + while (bits <= 24) { \ + bitbuf = (bitbuf << 8) | *bs_ptr++; \ + bits += 8; \ + } \ + } /*--------------------------------------------------------------*/ -#define mac_load(n) ( bits -= n, \ - bitval = bitbuf >> bits, \ - bitbuf -= bitval << bits, \ - bitval ) +#define mac_load(n) (bits -= n, bitval = bitbuf >> bits, bitbuf -= bitval << bits, bitval) /*======================================================================*/ -static void unpack_ba() -{ - int i, j, k; - static int nbit[4] = - {4, 4, 3, 2}; - int nstereo; - - pMP3Stream->bit_skip = 0; - nstereo = pMP3Stream->stereo_sb; - k = 0; - for (i = 0; i < 4; i++) - { - for (j = 0; j < pMP3Stream->nbat[i]; j++, k++) - { - mac_load_check(4); - ballo[k] = samp_dispatch[k] = pMP3Stream->bat[i][mac_load(nbit[i])]; - if (k >= pMP3Stream->nsb_limit) - pMP3Stream->bit_skip += bat_bit_master[samp_dispatch[k]]; - c_value[k] = look_c_value[samp_dispatch[k]]; - if (--nstereo < 0) - { - ballo[k + 1] = ballo[k]; - samp_dispatch[k] += 18; /* flag as joint */ - samp_dispatch[k + 1] = samp_dispatch[k]; /* flag for sf */ - c_value[k + 1] = c_value[k]; - k++; - j++; - } - } - } - samp_dispatch[pMP3Stream->nsb_limit] = 37; /* terminate the dispatcher with skip */ - samp_dispatch[k] = 36; /* terminate the dispatcher */ - +static void unpack_ba() { + int i, j, k; + static int nbit[4] = {4, 4, 3, 2}; + int nstereo; + + pMP3Stream->bit_skip = 0; + nstereo = pMP3Stream->stereo_sb; + k = 0; + for (i = 0; i < 4; i++) { + for (j = 0; j < pMP3Stream->nbat[i]; j++, k++) { + mac_load_check(4); + ballo[k] = samp_dispatch[k] = pMP3Stream->bat[i][mac_load(nbit[i])]; + if (k >= pMP3Stream->nsb_limit) + pMP3Stream->bit_skip += bat_bit_master[samp_dispatch[k]]; + c_value[k] = look_c_value[samp_dispatch[k]]; + if (--nstereo < 0) { + ballo[k + 1] = ballo[k]; + samp_dispatch[k] += 18; /* flag as joint */ + samp_dispatch[k + 1] = samp_dispatch[k]; /* flag for sf */ + c_value[k + 1] = c_value[k]; + k++; + j++; + } + } + } + samp_dispatch[pMP3Stream->nsb_limit] = 37; /* terminate the dispatcher with skip */ + samp_dispatch[k] = 36; /* terminate the dispatcher */ } /*-------------------------------------------------------------------------*/ -static void unpack_sfs() /* unpack scale factor selectors */ +static void unpack_sfs() /* unpack scale factor selectors */ { - int i; - - for (i = 0; i < pMP3Stream->max_sb; i++) - { - mac_load_check(2); - if (ballo[i]) - sf_dispatch[i] = mac_load(2); - else - sf_dispatch[i] = 4; /* no allo */ - } - sf_dispatch[i] = 5; /* terminate dispatcher */ + int i; + + for (i = 0; i < pMP3Stream->max_sb; i++) { + mac_load_check(2); + if (ballo[i]) + sf_dispatch[i] = mac_load(2); + else + sf_dispatch[i] = 4; /* no allo */ + } + sf_dispatch[i] = 5; /* terminate dispatcher */ } /*-------------------------------------------------------------------------*/ -static void unpack_sf() /* unpack scale factor */ -{ /* combine dequant and scale factors */ - int i; - - i = -1; - dispatch:switch (sf_dispatch[++i]) - { - case 0: /* 3 factors 012 */ - mac_load_check(18); - pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 1: /* 2 factors 002 */ - mac_load_check(12); - pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 2: /* 1 factor 000 */ - mac_load_check(6); - pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = - c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 3: /* 2 factors 022 */ - mac_load_check(12); - pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; - pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; - goto dispatch; - case 4: /* no allo */ -/*-- pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = 0.0; --*/ - goto dispatch; - case 5: /* all done */ - ; - } /* end switch */ +static void unpack_sf() /* unpack scale factor */ +{ /* combine dequant and scale factors */ + int i; + + i = -1; +dispatch: + switch (sf_dispatch[++i]) { + case 0: /* 3 factors 012 */ + mac_load_check(18); + pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 1: /* 2 factors 002 */ + mac_load_check(12); + pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 2: /* 1 factor 000 */ + mac_load_check(6); + pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 3: /* 2 factors 022 */ + mac_load_check(12); + pMP3Stream->cs_factor[0][i] = c_value[i] * sf_table[mac_load(6)]; + pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = c_value[i] * sf_table[mac_load(6)]; + goto dispatch; + case 4: /* no allo */ + /*-- pMP3Stream->cs_factor[2][i] = pMP3Stream->cs_factor[1][i] = pMP3Stream->cs_factor[0][i] = 0.0; --*/ + goto dispatch; + case 5: /* all done */ + ; + } /* end switch */ } /*-------------------------------------------------------------------------*/ -#define UNPACK_N(n) s[k] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACK_N2(n) mac_load_check(3*n); \ - s[k] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACK_N3(n) mac_load_check(2*n); \ - s[k] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - mac_load_check(n); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*(mac_load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACKJ_N(n) tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k+64] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+64+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k+128] = pMP3Stream->cs_factor[i][k]*tmp; \ - s[k+128+1] = pMP3Stream->cs_factor[i][k+1]*tmp; \ - k++; /* skip right chan dispatch */ \ - goto dispatch; +#define UNPACK_N(n) \ + s[k] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACK_N2(n) \ + mac_load_check(3 * n); \ + s[k] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACK_N3(n) \ + mac_load_check(2 * n); \ + s[k] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + mac_load_check(n); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * (mac_load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACKJ_N(n) \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 64] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k + 128] = pMP3Stream->cs_factor[i][k] * tmp; \ + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * tmp; \ + k++; /* skip right chan dispatch */ \ + goto dispatch; /*-------------------------------------------------------------------------*/ -static void unpack_samp() /* unpack samples */ +static void unpack_samp() /* unpack samples */ { - int i, j, k; - float *s; - int n; - long tmp; - - s = sample; - for (i = 0; i < 3; i++) - { /* 3 groups of scale factors */ - for (j = 0; j < 4; j++) - { - k = -1; - dispatch:switch (samp_dispatch[++k]) - { - case 0: - s[k + 128] = s[k + 64] = s[k] = 0.0F; - goto dispatch; - case 1: /* 3 levels grouped 5 bits */ - mac_load_check(5); - n = mac_load(5); - s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; - goto dispatch; - case 2: /* 5 levels grouped 7 bits */ - mac_load_check(7); - n = mac_load(7); - s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; - goto dispatch; - case 3: - UNPACK_N2(3) /* 7 levels */ - case 4: /* 9 levels grouped 10 bits */ - mac_load_check(10); - n = mac_load(10); - s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; - goto dispatch; - case 5: - UNPACK_N2(4) /* 15 levels */ - case 6: - UNPACK_N2(5) /* 31 levels */ - case 7: - UNPACK_N2(6) /* 63 levels */ - case 8: - UNPACK_N2(7) /* 127 levels */ - case 9: - UNPACK_N2(8) /* 255 levels */ - case 10: - UNPACK_N3(9) /* 511 levels */ - case 11: - UNPACK_N3(10) /* 1023 levels */ - case 12: - UNPACK_N3(11) /* 2047 levels */ - case 13: - UNPACK_N3(12) /* 4095 levels */ - case 14: - UNPACK_N(13) /* 8191 levels */ - case 15: - UNPACK_N(14) /* 16383 levels */ - case 16: - UNPACK_N(15) /* 32767 levels */ - case 17: - UNPACK_N(16) /* 65535 levels */ -/* -- joint ---- */ - case 18 + 0: - s[k + 128 + 1] = s[k + 128] = s[k + 64 + 1] = s[k + 64] = s[k + 1] = s[k] = 0.0F; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 1: /* 3 levels grouped 5 bits */ - n = load(5); - s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 2: /* 5 levels grouped 7 bits */ - n = load(7); - s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 3: - UNPACKJ_N(3) /* 7 levels */ - case 18 + 4: /* 9 levels grouped 10 bits */ - n = load(10); - s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; - s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][0]; - s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; - s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][1]; - s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; - s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][2]; - k++; /* skip right chan dispatch */ - goto dispatch; - case 18 + 5: - UNPACKJ_N(4) /* 15 levels */ - case 18 + 6: - UNPACKJ_N(5) /* 31 levels */ - case 18 + 7: - UNPACKJ_N(6) /* 63 levels */ - case 18 + 8: - UNPACKJ_N(7) /* 127 levels */ - case 18 + 9: - UNPACKJ_N(8) /* 255 levels */ - case 18 + 10: - UNPACKJ_N(9) /* 511 levels */ - case 18 + 11: - UNPACKJ_N(10) /* 1023 levels */ - case 18 + 12: - UNPACKJ_N(11) /* 2047 levels */ - case 18 + 13: - UNPACKJ_N(12) /* 4095 levels */ - case 18 + 14: - UNPACKJ_N(13) /* 8191 levels */ - case 18 + 15: - UNPACKJ_N(14) /* 16383 levels */ - case 18 + 16: - UNPACKJ_N(15) /* 32767 levels */ - case 18 + 17: - UNPACKJ_N(16) /* 65535 levels */ -/* -- end of dispatch -- */ - case 37: - skip(pMP3Stream->bit_skip); - case 36: - s += 3 * 64; - } /* end switch */ - } /* end j loop */ - } /* end i loop */ - - + int i, j, k; + float *s; + int n; + long tmp; + + s = sample; + for (i = 0; i < 3; i++) { /* 3 groups of scale factors */ + for (j = 0; j < 4; j++) { + k = -1; + dispatch: + switch (samp_dispatch[++k]) { + case 0: + s[k + 128] = s[k + 64] = s[k] = 0.0F; + goto dispatch; + case 1: /* 3 levels grouped 5 bits */ + mac_load_check(5); + n = mac_load(5); + s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; + goto dispatch; + case 2: /* 5 levels grouped 7 bits */ + mac_load_check(7); + n = mac_load(7); + s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; + goto dispatch; + case 3: + UNPACK_N2(3) /* 7 levels */ + case 4: /* 9 levels grouped 10 bits */ + mac_load_check(10); + n = mac_load(10); + s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; + goto dispatch; + case 5: + UNPACK_N2(4) /* 15 levels */ + case 6: + UNPACK_N2(5) /* 31 levels */ + case 7: + UNPACK_N2(6) /* 63 levels */ + case 8: + UNPACK_N2(7) /* 127 levels */ + case 9: + UNPACK_N2(8) /* 255 levels */ + case 10: + UNPACK_N3(9) /* 511 levels */ + case 11: + UNPACK_N3(10) /* 1023 levels */ + case 12: + UNPACK_N3(11) /* 2047 levels */ + case 13: + UNPACK_N3(12) /* 4095 levels */ + case 14: + UNPACK_N(13) /* 8191 levels */ + case 15: + UNPACK_N(14) /* 16383 levels */ + case 16: + UNPACK_N(15) /* 32767 levels */ + case 17: + UNPACK_N(16) /* 65535 levels */ + /* -- joint ---- */ + case 18 + 0: + s[k + 128 + 1] = s[k + 128] = s[k + 64 + 1] = s[k + 64] = s[k + 1] = s[k] = 0.0F; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 1: /* 3 levels grouped 5 bits */ + n = load(5); + s[k] = pMP3Stream->cs_factor[i][k] * group3_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group3_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group3_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group3_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 2: /* 5 levels grouped 7 bits */ + n = load(7); + s[k] = pMP3Stream->cs_factor[i][k] * group5_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group5_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group5_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group5_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 3: + UNPACKJ_N(3) /* 7 levels */ + case 18 + 4: /* 9 levels grouped 10 bits */ + n = load(10); + s[k] = pMP3Stream->cs_factor[i][k] * group9_table[n][0]; + s[k + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][0]; + s[k + 64] = pMP3Stream->cs_factor[i][k] * group9_table[n][1]; + s[k + 64 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][1]; + s[k + 128] = pMP3Stream->cs_factor[i][k] * group9_table[n][2]; + s[k + 128 + 1] = pMP3Stream->cs_factor[i][k + 1] * group9_table[n][2]; + k++; /* skip right chan dispatch */ + goto dispatch; + case 18 + 5: + UNPACKJ_N(4) /* 15 levels */ + case 18 + 6: + UNPACKJ_N(5) /* 31 levels */ + case 18 + 7: + UNPACKJ_N(6) /* 63 levels */ + case 18 + 8: + UNPACKJ_N(7) /* 127 levels */ + case 18 + 9: + UNPACKJ_N(8) /* 255 levels */ + case 18 + 10: + UNPACKJ_N(9) /* 511 levels */ + case 18 + 11: + UNPACKJ_N(10) /* 1023 levels */ + case 18 + 12: + UNPACKJ_N(11) /* 2047 levels */ + case 18 + 13: + UNPACKJ_N(12) /* 4095 levels */ + case 18 + 14: + UNPACKJ_N(13) /* 8191 levels */ + case 18 + 15: + UNPACKJ_N(14) /* 16383 levels */ + case 18 + 16: + UNPACKJ_N(15) /* 32767 levels */ + case 18 + 17: + UNPACKJ_N(16) /* 65535 levels */ + /* -- end of dispatch -- */ + case 37: + skip(pMP3Stream->bit_skip); + case 36: + s += 3 * 64; + } /* end switch */ + } /* end j loop */ + } /* end i loop */ } /*-------------------------------------------------------------------------*/ unsigned char *gpNextByteAfterData = NULL; -IN_OUT audio_decode(unsigned char *bs, signed short *pcm, unsigned char *pNextByteAfterData) -{ - gpNextByteAfterData = pNextByteAfterData; // sigh.... - return audio_decode_routine(bs, pcm); +IN_OUT audio_decode(unsigned char *bs, signed short *pcm, unsigned char *pNextByteAfterData) { + gpNextByteAfterData = pNextByteAfterData; // sigh.... + return audio_decode_routine(bs, pcm); } /*-------------------------------------------------------------------------*/ -IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm) -{ - int sync, prot; - IN_OUT in_out; - - load_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = load(12); - if (sync != 0xFFF) - return in_out; /* sync fail */ - - load(3); /* skip id and option (checked by init) */ - prot = load(1); /* load prot bit */ - load(6); /* skip to pad */ - pMP3Stream->pad = load(1); - load(1); /* skip to mode */ - pMP3Stream->stereo_sb = look_joint[load(4)]; - if (prot) - load(4); /* skip to data */ - else - load(20); /* skip crc */ - - unpack_ba(); /* unpack bit allocation */ - unpack_sfs(); /* unpack scale factor selectors */ - unpack_sf(); /* unpack scale factor */ - unpack_samp(); /* unpack samples */ - - pMP3Stream->sbt(sample, pcm, 36); -/*-----------*/ - in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.out_bytes = pMP3Stream->outbytes; - - return in_out; +IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm) { + int sync, prot; + IN_OUT in_out; + + load_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = load(12); + if (sync != 0xFFF) + return in_out; /* sync fail */ + + load(3); /* skip id and option (checked by init) */ + prot = load(1); /* load prot bit */ + load(6); /* skip to pad */ + pMP3Stream->pad = load(1); + load(1); /* skip to mode */ + pMP3Stream->stereo_sb = look_joint[load(4)]; + if (prot) + load(4); /* skip to data */ + else + load(20); /* skip crc */ + + unpack_ba(); /* unpack bit allocation */ + unpack_sfs(); /* unpack scale factor selectors */ + unpack_sf(); /* unpack scale factor */ + unpack_samp(); /* unpack samples */ + + pMP3Stream->sbt(sample, pcm, 36); + /*-----------*/ + in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.out_bytes = pMP3Stream->outbytes; + + return in_out; } /*-------------------------------------------------------------------------*/ #define COMPILE_ME -#include "cupini.c" /* initialization */ -#include "cupl1.c" /* Layer I */ +#include "cupini.c" /* initialization */ +#include "cupl1.c" /* Layer I */ /*-------------------------------------------------------------------------*/ diff --git a/codemp/mp3code/cupini.c b/codemp/mp3code/cupini.c index c014920b57..bf55e28e96 100644 --- a/codemp/mp3code/cupini.c +++ b/codemp/mp3code/cupini.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -34,7 +34,7 @@ mod 8/6/96 add 8 bit output mod 5/10/95 add quick (low precision) window mod 5/16/95 sb limit for reduced samprate output - changed from 94% to 100% of Nyquist sb + changed from 94% to 100% of Nyquist sb mod 11/15/95 for Layer I @@ -42,82 +42,68 @@ mod 11/15/95 for Layer I =========================================================*/ /*-- compiler bug, floating constant overflow w/ansi --*/ -static const long steps[18] = -{ - 0, 3, 5, 7, 9, 15, 31, 63, 127, - 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; - +static const long steps[18] = {0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; /* ABCD_INDEX = lookqt[mode][sr_index][br_index] */ /* -1 = invalid */ -static const signed char lookqt[4][3][16] = -{ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ - {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ - {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ - {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ -// mono extended beyond legal br index -// 1,2,2,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 44ks single chan */ -// 0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,-1, /* 48ks */ -// 1,3,3,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 32ks */ -// legal mono - {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ - {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ - {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ +static const signed char lookqt[4][3][16] = { + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks stereo */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks joint stereo */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + {{1, -1, -1, -1, 2, -1, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1}, /* 44ks dual chan */ + {0, -1, -1, -1, 2, -1, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1}, /* 48ks */ + {1, -1, -1, -1, 3, -1, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1}}, /* 32ks */ + // mono extended beyond legal br index + // 1,2,2,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 44ks single chan */ + // 0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,-1, /* 48ks */ + // 1,3,3,0,0,0,1,1,1,1,1,1,1,1,1,-1, /* 32ks */ + // legal mono + {{1, 2, 2, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}, /* 44ks single chan */ + {0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1}, /* 48ks */ + {1, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}}, /* 32ks */ }; -static const long sr_table[8] = -{22050L, 24000L, 16000L, 1L, - 44100L, 48000L, 32000L, 1L}; +static const long sr_table[8] = {22050L, 24000L, 16000L, 1L, 44100L, 48000L, 32000L, 1L}; /* bit allocation table look up */ /* table per mpeg spec tables 3b2a/b/c/d /e is mpeg2 */ /* look_bat[abcd_index][4][16] */ -static const unsigned char look_bat[5][4][16] = -{ -/* LOOK_BATA */ - {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, - {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATB */ - {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, - {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATC */ - {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATD */ - {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, -/* LOOK_BATE */ - {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, +static const unsigned char look_bat[5][4][16] = { + /* LOOK_BATA */ + {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, + {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATB */ + {{0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17}, + {0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATC */ + {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATD */ + {{0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + /* LOOK_BATE */ + {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0}, + {0, 1, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, }; /* look_nbat[abcd_index]][4] */ -static const unsigned char look_nbat[5][4] = -{ - {3, 8, 12, 4}, - {3, 8, 12, 7}, - {2, 0, 6, 0}, - {2, 0, 10, 0}, - {4, 0, 7, 19}, +static const unsigned char look_nbat[5][4] = { + {3, 8, 12, 4}, {3, 8, 12, 7}, {2, 0, 6, 0}, {2, 0, 10, 0}, {4, 0, 7, 19}, }; - void sbt_mono(float *sample, short *pcm, int n); void sbt_dual(float *sample, short *pcm, int n); void sbt_dual_mono(float *sample, short *pcm, int n); @@ -151,243 +137,191 @@ void sbtB8_dual_mono(float *sample, unsigned char *pcm, int n); void sbtB8_dual_left(float *sample, unsigned char *pcm, int n); void sbtB8_dual_right(float *sample, unsigned char *pcm, int n); - -static const SBT_FUNCTION sbt_table[2][3][5] = -{ - {{sbt_mono, sbt_dual, sbt_dual_mono, sbt_dual_left, sbt_dual_right}, - {sbt16_mono, sbt16_dual, sbt16_dual_mono, sbt16_dual_left, sbt16_dual_right}, - {sbt8_mono, sbt8_dual, sbt8_dual_mono, sbt8_dual_left, sbt8_dual_right}}, - {{(SBT_FUNCTION) sbtB_mono, - (SBT_FUNCTION) sbtB_dual, - (SBT_FUNCTION) sbtB_dual_mono, - (SBT_FUNCTION) sbtB_dual_left, - (SBT_FUNCTION) sbtB_dual_right}, - {(SBT_FUNCTION) sbtB16_mono, - (SBT_FUNCTION) sbtB16_dual, - (SBT_FUNCTION) sbtB16_dual_mono, - (SBT_FUNCTION) sbtB16_dual_left, - (SBT_FUNCTION) sbtB16_dual_right}, - {(SBT_FUNCTION) sbtB8_mono, - (SBT_FUNCTION) sbtB8_dual, - (SBT_FUNCTION) sbtB8_dual_mono, - (SBT_FUNCTION) sbtB8_dual_left, - (SBT_FUNCTION) sbtB8_dual_right}}, +static const SBT_FUNCTION sbt_table[2][3][5] = { + {{sbt_mono, sbt_dual, sbt_dual_mono, sbt_dual_left, sbt_dual_right}, + {sbt16_mono, sbt16_dual, sbt16_dual_mono, sbt16_dual_left, sbt16_dual_right}, + {sbt8_mono, sbt8_dual, sbt8_dual_mono, sbt8_dual_left, sbt8_dual_right}}, + {{(SBT_FUNCTION)sbtB_mono, (SBT_FUNCTION)sbtB_dual, (SBT_FUNCTION)sbtB_dual_mono, (SBT_FUNCTION)sbtB_dual_left, (SBT_FUNCTION)sbtB_dual_right}, + {(SBT_FUNCTION)sbtB16_mono, (SBT_FUNCTION)sbtB16_dual, (SBT_FUNCTION)sbtB16_dual_mono, (SBT_FUNCTION)sbtB16_dual_left, (SBT_FUNCTION)sbtB16_dual_right}, + {(SBT_FUNCTION)sbtB8_mono, (SBT_FUNCTION)sbtB8_dual, (SBT_FUNCTION)sbtB8_dual_mono, (SBT_FUNCTION)sbtB8_dual_left, (SBT_FUNCTION)sbtB8_dual_right}}, }; -static const int out_chans[5] = -{1, 2, 1, 1, 1}; +static const int out_chans[5] = {1, 2, 1, 1, 1}; - -int audio_decode_initL1(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); +int audio_decode_initL1(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); void sbt_init(); - IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm); IN_OUT L2audio_decode(unsigned char *bs, signed short *pcm); IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm); -static const AUDIO_DECODE_ROUTINE decode_routine_table[4] = -{ - L2audio_decode, - (AUDIO_DECODE_ROUTINE)L3audio_decode, - L2audio_decode, - L1audio_decode,}; +static const AUDIO_DECODE_ROUTINE decode_routine_table[4] = { + L2audio_decode, + (AUDIO_DECODE_ROUTINE)L3audio_decode, + L2audio_decode, + L1audio_decode, +}; /*---------------------------------------------------------*/ -static void table_init() -{ - int i, j; - int code; - static int iOnceOnly=0; - - if (!iOnceOnly++) - { - /*-- c_values (dequant) --*/ - for (i = 1; i < 18; i++) - look_c_value[i] = 2.0F / steps[i]; - - /*-- scale factor table, scale by 32768 for 16 pcm output --*/ - for (i = 0; i < 64; i++) - sf_table[i] = (float) (32768.0 * 2.0 * pow(2.0, -i / 3.0)); - - /*-- grouped 3 level lookup table 5 bit token --*/ - for (i = 0; i < 32; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group3_table[i][j] = (char) ((code % 3) - 1); - code /= 3; - } - } - - /*-- grouped 5 level lookup table 7 bit token --*/ - for (i = 0; i < 128; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group5_table[i][j] = (char) ((code % 5) - 2); - code /= 5; - } - } - - /*-- grouped 9 level lookup table 10 bit token --*/ - for (i = 0; i < 1024; i++) - { - code = i; - for (j = 0; j < 3; j++) - { - group9_table[i][j] = (short) ((code % 9) - 4); - code /= 9; - } - } - } +static void table_init() { + int i, j; + int code; + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*-- c_values (dequant) --*/ + for (i = 1; i < 18; i++) + look_c_value[i] = 2.0F / steps[i]; + + /*-- scale factor table, scale by 32768 for 16 pcm output --*/ + for (i = 0; i < 64; i++) + sf_table[i] = (float)(32768.0 * 2.0 * pow(2.0, -i / 3.0)); + + /*-- grouped 3 level lookup table 5 bit token --*/ + for (i = 0; i < 32; i++) { + code = i; + for (j = 0; j < 3; j++) { + group3_table[i][j] = (char)((code % 3) - 1); + code /= 3; + } + } + + /*-- grouped 5 level lookup table 7 bit token --*/ + for (i = 0; i < 128; i++) { + code = i; + for (j = 0; j < 3; j++) { + group5_table[i][j] = (char)((code % 5) - 2); + code /= 5; + } + } + + /*-- grouped 9 level lookup table 10 bit token --*/ + for (i = 0; i < 1024; i++) { + code = i; + for (j = 0; j < 3; j++) { + group9_table[i][j] = (short)((code % 9) - 4); + code /= 9; + } + } + } } /*---------------------------------------------------------*/ -int L1audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); -int L3audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit); +int L1audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); +int L3audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pad */ -int audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, j, k; - static int first_pass = 1; - int abcd_index; - long samprate; - int limit; - int bit_code; - - if (first_pass) - { - table_init(); - first_pass = 0; - } - -/* select decoder routine Layer I,II,III */ - audio_decode_routine = decode_routine_table[h->option & 3]; - - - if (h->option == 3) /* layer I */ - return L1audio_decode_init(h, framebytes_arg, - reduction_code, transform_code, convert_code, freq_limit); - - if (h->option == 1) /* layer III */ - return L3audio_decode_init(h, framebytes_arg, - reduction_code, transform_code, convert_code, freq_limit); - - - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - pMP3Stream->framebytes = framebytes_arg; -/* check if code handles */ - if (h->option != 2) - return 0; /* layer II only */ - if (h->sr_index == 3) - return 0; /* reserved */ - -/* compute abcd index for bit allo table selection */ - if (h->id) /* mpeg 1 */ - abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; - else - abcd_index = 4; /* mpeg 2 */ - - if (abcd_index < 0) - return 0; // fail invalid Layer II bit rate index - - for (i = 0; i < 4; i++) - for (j = 0; j < 16; j++) - pMP3Stream->bat[i][j] = look_bat[abcd_index][i][j]; - for (i = 0; i < 4; i++) - pMP3Stream->nbat[i] = look_nbat[abcd_index][i]; - pMP3Stream->max_sb = pMP3Stream->nbat[0] + pMP3Stream->nbat[1] + pMP3Stream->nbat[2] + pMP3Stream->nbat[3]; -/*----- compute pMP3Stream->nsb_limit --------*/ - samprate = sr_table[4 * h->id + h->sr_index]; - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ -/*---- limit = 0.94*(32>>reduction_code); ----*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) - pMP3Stream->nsb_limit = pMP3Stream->max_sb; - - pMP3Stream->outvalues = 1152 >> reduction_code; - if (h->mode != 3) - { /* adjust for 2 channel modes */ - for (i = 0; i < 4; i++) - pMP3Stream->nbat[i] *= 2; - pMP3Stream->max_sb *= 2; - pMP3Stream->nsb_limit *= 2; - } - -/* set sbt function */ - k = 1 + convert_code; - if (h->mode == 3) - { - k = 0; - } - pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; - pMP3Stream->outvalues *= out_chans[k]; - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - decinfo.channels = out_chans[k]; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - - -/* clear sample buffer, unused sub bands must be 0 */ - for (i = 0; i < 2304*2; i++) // the *2 here was inserted by me just in case, since the array is now *2, because of stereo files unpacking at 4608 bytes per frame (which may or may not be relevant, but in any case I don't think we use the L1 versions of MP3 now anyway - sample[i] = 0.0F; - - -/* init sub-band transform */ - sbt_init(); - - return 1; +int audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, j, k; + static int first_pass = 1; + int abcd_index; + long samprate; + int limit; + int bit_code; + + if (first_pass) { + table_init(); + first_pass = 0; + } + + /* select decoder routine Layer I,II,III */ + audio_decode_routine = decode_routine_table[h->option & 3]; + + if (h->option == 3) /* layer I */ + return L1audio_decode_init(h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); + + if (h->option == 1) /* layer III */ + return L3audio_decode_init(h, framebytes_arg, reduction_code, transform_code, convert_code, freq_limit); + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + pMP3Stream->framebytes = framebytes_arg; + /* check if code handles */ + if (h->option != 2) + return 0; /* layer II only */ + if (h->sr_index == 3) + return 0; /* reserved */ + + /* compute abcd index for bit allo table selection */ + if (h->id) /* mpeg 1 */ + abcd_index = lookqt[h->mode][h->sr_index][h->br_index]; + else + abcd_index = 4; /* mpeg 2 */ + + if (abcd_index < 0) + return 0; // fail invalid Layer II bit rate index + + for (i = 0; i < 4; i++) + for (j = 0; j < 16; j++) + pMP3Stream->bat[i][j] = look_bat[abcd_index][i][j]; + for (i = 0; i < 4; i++) + pMP3Stream->nbat[i] = look_nbat[abcd_index][i]; + pMP3Stream->max_sb = pMP3Stream->nbat[0] + pMP3Stream->nbat[1] + pMP3Stream->nbat[2] + pMP3Stream->nbat[3]; + /*----- compute pMP3Stream->nsb_limit --------*/ + samprate = sr_table[4 * h->id + h->sr_index]; + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + /*---- limit = 0.94*(32>>reduction_code); ----*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) + pMP3Stream->nsb_limit = pMP3Stream->max_sb; + + pMP3Stream->outvalues = 1152 >> reduction_code; + if (h->mode != 3) { /* adjust for 2 channel modes */ + for (i = 0; i < 4; i++) + pMP3Stream->nbat[i] *= 2; + pMP3Stream->max_sb *= 2; + pMP3Stream->nsb_limit *= 2; + } + + /* set sbt function */ + k = 1 + convert_code; + if (h->mode == 3) { + k = 0; + } + pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; + pMP3Stream->outvalues *= out_chans[k]; + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + decinfo.channels = out_chans[k]; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + /* clear sample buffer, unused sub bands must be 0 */ + for (i = 0; i < 2304 * 2; i++) // the *2 here was inserted by me just in case, since the array is now *2, because of stereo files unpacking at 4608 bytes + // per frame (which may or may not be relevant, but in any case I don't think we use the L1 versions of MP3 now anyway + sample[i] = 0.0F; + + /* init sub-band transform */ + sbt_init(); + + return 1; } /*---------------------------------------------------------*/ -void audio_decode_info(DEC_INFO * info) -{ - *info = decinfo; /* info return, call after init */ -} +void audio_decode_info(DEC_INFO *info) { *info = decinfo; /* info return, call after init */ } /*---------------------------------------------------------*/ -void decode_table_init() -{ -/* dummy for asm version compatability */ -} +void decode_table_init() { /* dummy for asm version compatability */ } /*---------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME - +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/cupl1.c b/codemp/mp3code/cupl1.c index 8d095e22b0..06ebb94568 100644 --- a/codemp/mp3code/cupl1.c +++ b/codemp/mp3code/cupl1.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -34,288 +34,270 @@ include to clup.c ******************************************************************/ /*======================================================================*/ -static const int bat_bit_masterL1[] = -{ - 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 -}; +static const int bat_bit_masterL1[] = {0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; ////@@@@static float *pMP3Stream->cs_factorL1 = &pMP3Stream->cs_factor[0]; // !!!!!!!!!!!!!!!! -static float look_c_valueL1[16]; // effectively constant +static float look_c_valueL1[16]; // effectively constant ////@@@@static int nbatL1 = 32; /*======================================================================*/ -static void unpack_baL1() -{ - int j; - int nstereo; - - pMP3Stream->bit_skip = 0; - nstereo = pMP3Stream->stereo_sb; - - for (j = 0; j < pMP3Stream->nbatL1; j++) - { - mac_load_check(4); - ballo[j] = samp_dispatch[j] = mac_load(4); - if (j >= pMP3Stream->nsb_limit) - pMP3Stream->bit_skip += bat_bit_masterL1[samp_dispatch[j]]; - c_value[j] = look_c_valueL1[samp_dispatch[j]]; - if (--nstereo < 0) - { - ballo[j + 1] = ballo[j]; - samp_dispatch[j] += 15; /* flag as joint */ - samp_dispatch[j + 1] = samp_dispatch[j]; /* flag for sf */ - c_value[j + 1] = c_value[j]; - j++; - } - } -/*-- terminate with bit skip and end --*/ - samp_dispatch[pMP3Stream->nsb_limit] = 31; - samp_dispatch[j] = 30; +static void unpack_baL1() { + int j; + int nstereo; + + pMP3Stream->bit_skip = 0; + nstereo = pMP3Stream->stereo_sb; + + for (j = 0; j < pMP3Stream->nbatL1; j++) { + mac_load_check(4); + ballo[j] = samp_dispatch[j] = mac_load(4); + if (j >= pMP3Stream->nsb_limit) + pMP3Stream->bit_skip += bat_bit_masterL1[samp_dispatch[j]]; + c_value[j] = look_c_valueL1[samp_dispatch[j]]; + if (--nstereo < 0) { + ballo[j + 1] = ballo[j]; + samp_dispatch[j] += 15; /* flag as joint */ + samp_dispatch[j + 1] = samp_dispatch[j]; /* flag for sf */ + c_value[j + 1] = c_value[j]; + j++; + } + } + /*-- terminate with bit skip and end --*/ + samp_dispatch[pMP3Stream->nsb_limit] = 31; + samp_dispatch[j] = 30; } /*-------------------------------------------------------------------------*/ -static void unpack_sfL1(void) /* unpack scale factor */ -{ /* combine dequant and scale factors */ - int i; - - for (i = 0; i < pMP3Stream->nbatL1; i++) - { - if (ballo[i]) - { - mac_load_check(6); - pMP3Stream->cs_factorL1[i] = c_value[i] * sf_table[mac_load(6)]; - } - } -/*-- done --*/ +static void unpack_sfL1(void) /* unpack scale factor */ +{ /* combine dequant and scale factors */ + int i; + + for (i = 0; i < pMP3Stream->nbatL1; i++) { + if (ballo[i]) { + mac_load_check(6); + pMP3Stream->cs_factorL1[i] = c_value[i] * sf_table[mac_load(6)]; + } + } + /*-- done --*/ } /*-------------------------------------------------------------------------*/ -#define UNPACKL1_N(n) s[k] = pMP3Stream->cs_factorL1[k]*(load(n)-((1 << (n-1)) -1)); \ - goto dispatch; -#define UNPACKL1J_N(n) tmp = (load(n)-((1 << (n-1)) -1)); \ - s[k] = pMP3Stream->cs_factorL1[k]*tmp; \ - s[k+1] = pMP3Stream->cs_factorL1[k+1]*tmp; \ - k++; \ - goto dispatch; +#define UNPACKL1_N(n) \ + s[k] = pMP3Stream->cs_factorL1[k] * (load(n) - ((1 << (n - 1)) - 1)); \ + goto dispatch; +#define UNPACKL1J_N(n) \ + tmp = (load(n) - ((1 << (n - 1)) - 1)); \ + s[k] = pMP3Stream->cs_factorL1[k] * tmp; \ + s[k + 1] = pMP3Stream->cs_factorL1[k + 1] * tmp; \ + k++; \ + goto dispatch; /*-------------------------------------------------------------------------*/ -static void unpack_sampL1() /* unpack samples */ +static void unpack_sampL1() /* unpack samples */ { - int j, k; - float *s; - long tmp; - - s = sample; - for (j = 0; j < 12; j++) - { - k = -1; - dispatch:switch (samp_dispatch[++k]) - { - case 0: - s[k] = 0.0F; - goto dispatch; - case 1: - UNPACKL1_N(2) /* 3 levels */ - case 2: - UNPACKL1_N(3) /* 7 levels */ - case 3: - UNPACKL1_N(4) /* 15 levels */ - case 4: - UNPACKL1_N(5) /* 31 levels */ - case 5: - UNPACKL1_N(6) /* 63 levels */ - case 6: - UNPACKL1_N(7) /* 127 levels */ - case 7: - UNPACKL1_N(8) /* 255 levels */ - case 8: - UNPACKL1_N(9) /* 511 levels */ - case 9: - UNPACKL1_N(10) /* 1023 levels */ - case 10: - UNPACKL1_N(11) /* 2047 levels */ - case 11: - UNPACKL1_N(12) /* 4095 levels */ - case 12: - UNPACKL1_N(13) /* 8191 levels */ - case 13: - UNPACKL1_N(14) /* 16383 levels */ - case 14: - UNPACKL1_N(15) /* 32767 levels */ -/* -- joint ---- */ - case 15 + 0: - s[k + 1] = s[k] = 0.0F; - k++; /* skip right chan dispatch */ - goto dispatch; -/* -- joint ---- */ - case 15 + 1: - UNPACKL1J_N(2) /* 3 levels */ - case 15 + 2: - UNPACKL1J_N(3) /* 7 levels */ - case 15 + 3: - UNPACKL1J_N(4) /* 15 levels */ - case 15 + 4: - UNPACKL1J_N(5) /* 31 levels */ - case 15 + 5: - UNPACKL1J_N(6) /* 63 levels */ - case 15 + 6: - UNPACKL1J_N(7) /* 127 levels */ - case 15 + 7: - UNPACKL1J_N(8) /* 255 levels */ - case 15 + 8: - UNPACKL1J_N(9) /* 511 levels */ - case 15 + 9: - UNPACKL1J_N(10) /* 1023 levels */ - case 15 + 10: - UNPACKL1J_N(11) /* 2047 levels */ - case 15 + 11: - UNPACKL1J_N(12) /* 4095 levels */ - case 15 + 12: - UNPACKL1J_N(13) /* 8191 levels */ - case 15 + 13: - UNPACKL1J_N(14) /* 16383 levels */ - case 15 + 14: - UNPACKL1J_N(15) /* 32767 levels */ - -/* -- end of dispatch -- */ - case 31: - skip(pMP3Stream->bit_skip); - case 30: - s += 64; - } /* end switch */ - } /* end j loop */ - -/*-- done --*/ + int j, k; + float *s; + long tmp; + + s = sample; + for (j = 0; j < 12; j++) { + k = -1; + dispatch: + switch (samp_dispatch[++k]) { + case 0: + s[k] = 0.0F; + goto dispatch; + case 1: + UNPACKL1_N(2) /* 3 levels */ + case 2: + UNPACKL1_N(3) /* 7 levels */ + case 3: + UNPACKL1_N(4) /* 15 levels */ + case 4: + UNPACKL1_N(5) /* 31 levels */ + case 5: + UNPACKL1_N(6) /* 63 levels */ + case 6: + UNPACKL1_N(7) /* 127 levels */ + case 7: + UNPACKL1_N(8) /* 255 levels */ + case 8: + UNPACKL1_N(9) /* 511 levels */ + case 9: + UNPACKL1_N(10) /* 1023 levels */ + case 10: + UNPACKL1_N(11) /* 2047 levels */ + case 11: + UNPACKL1_N(12) /* 4095 levels */ + case 12: + UNPACKL1_N(13) /* 8191 levels */ + case 13: + UNPACKL1_N(14) /* 16383 levels */ + case 14: + UNPACKL1_N(15) /* 32767 levels */ + /* -- joint ---- */ + case 15 + 0: + s[k + 1] = s[k] = 0.0F; + k++; /* skip right chan dispatch */ + goto dispatch; + /* -- joint ---- */ + case 15 + 1: + UNPACKL1J_N(2) /* 3 levels */ + case 15 + 2: + UNPACKL1J_N(3) /* 7 levels */ + case 15 + 3: + UNPACKL1J_N(4) /* 15 levels */ + case 15 + 4: + UNPACKL1J_N(5) /* 31 levels */ + case 15 + 5: + UNPACKL1J_N(6) /* 63 levels */ + case 15 + 6: + UNPACKL1J_N(7) /* 127 levels */ + case 15 + 7: + UNPACKL1J_N(8) /* 255 levels */ + case 15 + 8: + UNPACKL1J_N(9) /* 511 levels */ + case 15 + 9: + UNPACKL1J_N(10) /* 1023 levels */ + case 15 + 10: + UNPACKL1J_N(11) /* 2047 levels */ + case 15 + 11: + UNPACKL1J_N(12) /* 4095 levels */ + case 15 + 12: + UNPACKL1J_N(13) /* 8191 levels */ + case 15 + 13: + UNPACKL1J_N(14) /* 16383 levels */ + case 15 + 14: + UNPACKL1J_N(15) /* 32767 levels */ + + /* -- end of dispatch -- */ + case 31: + skip(pMP3Stream->bit_skip); + case 30: + s += 64; + } /* end switch */ + } /* end j loop */ + + /*-- done --*/ } /*-------------------------------------------------------------------*/ -IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm) -{ - int sync, prot; - IN_OUT in_out; - - load_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = load(12); - if (sync != 0xFFF) - return in_out; /* sync fail */ - - - load(3); /* skip id and option (checked by init) */ - prot = load(1); /* load prot bit */ - load(6); /* skip to pad */ - pMP3Stream->pad = (load(1)) << 2; - load(1); /* skip to mode */ - pMP3Stream->stereo_sb = look_joint[load(4)]; - if (prot) - load(4); /* skip to data */ - else - load(20); /* skip crc */ - - unpack_baL1(); /* unpack bit allocation */ - unpack_sfL1(); /* unpack scale factor */ - unpack_sampL1(); /* unpack samples */ - - pMP3Stream->sbt(sample, pcm, 12); -/*-----------*/ - in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.out_bytes = pMP3Stream->outbytes; - - return in_out; +IN_OUT L1audio_decode(unsigned char *bs, signed short *pcm) { + int sync, prot; + IN_OUT in_out; + + load_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = load(12); + if (sync != 0xFFF) + return in_out; /* sync fail */ + + load(3); /* skip id and option (checked by init) */ + prot = load(1); /* load prot bit */ + load(6); /* skip to pad */ + pMP3Stream->pad = (load(1)) << 2; + load(1); /* skip to mode */ + pMP3Stream->stereo_sb = look_joint[load(4)]; + if (prot) + load(4); /* skip to data */ + else + load(20); /* skip crc */ + + unpack_baL1(); /* unpack bit allocation */ + unpack_sfL1(); /* unpack scale factor */ + unpack_sampL1(); /* unpack samples */ + + pMP3Stream->sbt(sample, pcm, 12); + /*-----------*/ + in_out.in_bytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.out_bytes = pMP3Stream->outbytes; + + return in_out; } /*-------------------------------------------------------------------------*/ -int L1audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, k; - static int first_pass = 1; - long samprate; - int limit; - long step; - int bit_code; - -/*--- sf init done by layer II init ---*/ - if (first_pass) - { - for (step = 4, i = 1; i < 16; i++, step <<= 1) - look_c_valueL1[i] = (float) (2.0 / (step - 1)); - first_pass = 0; - } - pMP3Stream->cs_factorL1 = pMP3Stream->cs_factor[0]; - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - pMP3Stream->framebytes = framebytes_arg; -/* check if code handles */ - if (h->option != 3) - return 0; /* layer I only */ - - pMP3Stream->nbatL1 = 32; - pMP3Stream->max_sb = pMP3Stream->nbatL1; -/*----- compute pMP3Stream->nsb_limit --------*/ - samprate = sr_table[4 * h->id + h->sr_index]; - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ -/*---- limit = 0.94*(32>>reduction_code); ----*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) - pMP3Stream->nsb_limit = pMP3Stream->max_sb; - - pMP3Stream->outvalues = 384 >> reduction_code; - if (h->mode != 3) - { /* adjust for 2 channel modes */ - pMP3Stream->nbatL1 *= 2; - pMP3Stream->max_sb *= 2; - pMP3Stream->nsb_limit *= 2; - } - -/* set sbt function */ - k = 1 + convert_code; - if (h->mode == 3) - { - k = 0; - } - pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; - pMP3Stream->outvalues *= out_chans[k]; - - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - decinfo.channels = out_chans[k]; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - -/* clear sample buffer, unused sub bands must be 0 */ - for (i = 0; i < 768; i++) - sample[i] = 0.0F; - - -/* init sub-band transform */ - sbt_init(); - - return 1; +int L1audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, k; + static int first_pass = 1; + long samprate; + int limit; + long step; + int bit_code; + + /*--- sf init done by layer II init ---*/ + if (first_pass) { + for (step = 4, i = 1; i < 16; i++, step <<= 1) + look_c_valueL1[i] = (float)(2.0 / (step - 1)); + first_pass = 0; + } + pMP3Stream->cs_factorL1 = pMP3Stream->cs_factor[0]; + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + pMP3Stream->framebytes = framebytes_arg; + /* check if code handles */ + if (h->option != 3) + return 0; /* layer I only */ + + pMP3Stream->nbatL1 = 32; + pMP3Stream->max_sb = pMP3Stream->nbatL1; + /*----- compute pMP3Stream->nsb_limit --------*/ + samprate = sr_table[4 * h->id + h->sr_index]; + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + /*---- limit = 0.94*(32>>reduction_code); ----*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + if (pMP3Stream->nsb_limit > pMP3Stream->max_sb) + pMP3Stream->nsb_limit = pMP3Stream->max_sb; + + pMP3Stream->outvalues = 384 >> reduction_code; + if (h->mode != 3) { /* adjust for 2 channel modes */ + pMP3Stream->nbatL1 *= 2; + pMP3Stream->max_sb *= 2; + pMP3Stream->nsb_limit *= 2; + } + + /* set sbt function */ + k = 1 + convert_code; + if (h->mode == 3) { + k = 0; + } + pMP3Stream->sbt = sbt_table[bit_code][reduction_code][k]; + pMP3Stream->outvalues *= out_chans[k]; + + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + decinfo.channels = out_chans[k]; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + /* clear sample buffer, unused sub bands must be 0 */ + for (i = 0; i < 768; i++) + sample[i] = 0.0F; + + /* init sub-band transform */ + sbt_init(); + + return 1; } /*---------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/cupl3.c b/codemp/mp3code/cupl3.c index d3562f9eb4..30d04100f5 100644 --- a/codemp/mp3code/cupl3.c +++ b/codemp/mp3code/cupl3.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -53,22 +53,20 @@ TO DO: Test mixed blocks (mixed long/short) #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ #include "l3.h" #include "jdw.h" #include "mp3struct.h" #if !defined(min) -# define min(a, b) ((a) < (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) #endif /*====================================================================*/ -static const int mp_sr20_table[2][4] = -{{441, 480, 320, -999}, {882, 960, 640, -999}}; -static const int mp_br_tableL3[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ - {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; +static const int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; +static const int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ + {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; /*====================================================================*/ @@ -80,12 +78,12 @@ static const int mp_br_tableL3[2][16] = /*====================================================================*/ /*----------------*/ -extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then chucked. +extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then chucked. /*----------------*/ ////@@@@static int pMP3Stream->mpeg25_flag; // L3 only -//int iframe; +// int iframe; /*-------*/ ////@@@@static int pMP3Stream->band_limit = (576); // L3 only @@ -105,18 +103,18 @@ extern DEC_INFO decinfo; ////@@@@ this is ok, only written to during init, then ////@@@@static int pMP3Stream->half_outbytes; // L3 only ////@@@@static int pMP3Stream->framebytes; // -//static int padframebytes; +// static int padframebytes; ////@@@@static int pMP3Stream->crcbytes; // L3 only ////@@@@static int pMP3Stream->pad; // -//static int stereo_flag; // only written to +// static int stereo_flag; // only written to ////@@@@static int pMP3Stream->nchan; // L3 only ////@@@@static int pMP3Stream->ms_mode; // L3 only (99%) ////@@@@static int pMP3Stream->is_mode; // L3 only ////@@@@static unsigned int pMP3Stream->zero_level_pcm = 0; // L3 only /* cb_info[igr][ch], compute by dequant, used by joint */ -static CB_INFO cb_info[2][2]; // L3 only ############ I think this is ok, only a scratchpad? -static IS_SF_INFO is_sf_info; /* MPEG-2 intensity stereo */ // L3 only ############## scratchpad? +static CB_INFO cb_info[2][2]; // L3 only ############ I think this is ok, only a scratchpad? +static IS_SF_INFO is_sf_info; /* MPEG-2 intensity stereo */ // L3 only ############## scratchpad? /*---------------------------------*/ //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -130,17 +128,17 @@ static int buf_ptr1 = 0; // !!!!!!!!!!! static int main_pos_bit; */ /*---------------------------------*/ -static SIDE_INFO side_info; // ####### scratchpad? +static SIDE_INFO side_info; // ####### scratchpad? -static SCALEFACT sf[2][2]; /* [gr][ch] */ // ########## scratchpad? +static SCALEFACT sf[2][2]; /* [gr][ch] */ // ########## scratchpad? -static int nsamp[2][2]; /* must start = 0, for nsamp[igr_prev] */ // ########## scratchpad? +static int nsamp[2][2]; /* must start = 0, for nsamp[igr_prev] */ // ########## scratchpad? /*- sample union of int/float sample[ch][gr][576] */ /* static SAMPLE sample[2][2][576]; */ // @@@@FINDME ////@@@@extern SAMPLE sample[2][2][576]; ////////////????? suspicious, mainly used in decode loop, but zeroed init code -static float yout[576]; /* hybrid out, sbt in */ //////////// scratchpad +static float yout[576]; /* hybrid out, sbt in */ //////////// scratchpad ////@@@@typedef void (*SBT_FUNCTION) (float *sample, short *pcm, int ch); void sbt_dual_L3(float *sample, short *pcm, int n); @@ -155,906 +153,696 @@ IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm); ////@@@@typedef IN_OUT(*DECODE_FUNCTION) (unsigned char *bs, unsigned char *pcm); ////@@@@static DECODE_FUNCTION decode_function = L3audio_decode_MPEG1; <------------------ needs streaming, ditto above!!! - /*====================================================================*/ -int hybrid(void *xin, void *xprev, float *y, - int btype, int nlong, int ntot, int nprev); -int hybrid_sum(void *xin, void *xin_left, float *y, - int btype, int nlong, int ntot); +int hybrid(void *xin, void *xprev, float *y, int btype, int nlong, int ntot, int nprev); +int hybrid_sum(void *xin, void *xin_left, float *y, int btype, int nlong, int ntot); void sum_f_bands(void *a, void *b, int n); void FreqInvert(float *y, int n); void antialias(void *x, int n); -void ms_process(void *x, int n); /* sum-difference stereo */ -void is_process_MPEG1(void *x, /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - int nsamp, int ms_mode); -void is_process_MPEG2(void *x, /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - IS_SF_INFO * is_sf_info, - int nsamp, int ms_mode); +void ms_process(void *x, int n); /* sum-difference stereo */ +void is_process_MPEG1(void *x, /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + int nsamp, int ms_mode); +void is_process_MPEG2(void *x, /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + IS_SF_INFO *is_sf_info, int nsamp, int ms_mode); void unpack_huff(void *xy, int n, int ntable); int unpack_huff_quad(void *vwxy, int n, int nbits, int ntable); -void dequant(SAMPLE sample[], int *nsamp, - SCALEFACT * sf, - GR * gr, - CB_INFO * cb_info, int ncbl_mixed); -void unpack_sf_sub_MPEG1(SCALEFACT * scalefac, GR * gr, - int scfsi, /* bit flag */ - int igr); -void unpack_sf_sub_MPEG2(SCALEFACT sf[], /* return intensity scale */ - GR * grdat, - int is_and_ch, IS_SF_INFO * is_sf_info); +void dequant(SAMPLE sample[], int *nsamp, SCALEFACT *sf, GR *gr, CB_INFO *cb_info, int ncbl_mixed); +void unpack_sf_sub_MPEG1(SCALEFACT *scalefac, GR *gr, int scfsi, /* bit flag */ + int igr); +void unpack_sf_sub_MPEG2(SCALEFACT sf[], /* return intensity scale */ + GR *grdat, int is_and_ch, IS_SF_INFO *is_sf_info); /*====================================================================*/ /* get bits from bitstream in endian independent way */ -BITDAT bitdat; /* global for inline use by Huff */ // !!!!!!!!!!!!!!!!!!! +BITDAT bitdat; /* global for inline use by Huff */ // !!!!!!!!!!!!!!!!!!! /*------------- initialize bit getter -------------*/ -static void bitget_init(unsigned char *buf) -{ - bitdat.bs_ptr0 = bitdat.bs_ptr = buf; - bitdat.bits = 0; - bitdat.bitbuf = 0; +static void bitget_init(unsigned char *buf) { + bitdat.bs_ptr0 = bitdat.bs_ptr = buf; + bitdat.bits = 0; + bitdat.bitbuf = 0; } /*------------- initialize bit getter -------------*/ -static void bitget_init_end(unsigned char *buf_end) -{ - bitdat.bs_ptr_end = buf_end; -} +static void bitget_init_end(unsigned char *buf_end) { bitdat.bs_ptr_end = buf_end; } /*------------- get n bits from bitstream -------------*/ -int bitget_bits_used() -{ - int n; /* compute bits used from last init call */ +int bitget_bits_used() { + int n; /* compute bits used from last init call */ - n = ((bitdat.bs_ptr - bitdat.bs_ptr0) << 3) - bitdat.bits; - return n; + n = ((bitdat.bs_ptr - bitdat.bs_ptr0) << 3) - bitdat.bits; + return n; } /*------------- check for n bits in bitbuf -------------*/ -void bitget_check(int n) -{ - if (bitdat.bits < n) - { - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } +void bitget_check(int n) { + if (bitdat.bits < n) { + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } } /*------------- get n bits from bitstream -------------*/ -unsigned int bitget(int n) -{ - unsigned int x; - - if (bitdat.bits < n) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits -= n; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +unsigned int bitget(int n) { + unsigned int x; + + if (bitdat.bits < n) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits -= n; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } /*------------- get 1 bit from bitstream -------------*/ -unsigned int bitget_1bit() -{ - unsigned int x; - - if (bitdat.bits <= 0) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits--; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +unsigned int bitget_1bit() { + unsigned int x; + + if (bitdat.bits <= 0) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits--; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } /*====================================================================*/ -static void Xform_mono(void *pcm, int igr) -{ - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - n1 = n2 = nsamp[igr][0]; /* total number bands */ - if (side_info.gr[igr][0].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][0].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - igr_prev = igr ^ 1; - - nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); - FreqInvert(yout, nsamp[igr][0]); - pMP3Stream->sbt_L3(yout, pcm, 0); - +static void Xform_mono(void *pcm, int igr) { + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + n1 = n2 = nsamp[igr][0]; /* total number bands */ + if (side_info.gr[igr][0].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][0].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + igr_prev = igr ^ 1; + + nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + FreqInvert(yout, nsamp[igr][0]); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ -static void Xform_dual_right(void *pcm, int igr) -{ - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - n1 = n2 = nsamp[igr][1]; /* total number bands */ - if (side_info.gr[igr][1].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][1].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - igr_prev = igr ^ 1; - nsamp[igr][1] = hybrid(pMP3Stream->sample[1][igr], pMP3Stream->sample[1][igr_prev], - yout, side_info.gr[igr][1].block_type, n1, n2, nsamp[igr_prev][1]); - FreqInvert(yout, nsamp[igr][1]); - pMP3Stream->sbt_L3(yout, pcm, 0); - +static void Xform_dual_right(void *pcm, int igr) { + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + n1 = n2 = nsamp[igr][1]; /* total number bands */ + if (side_info.gr[igr][1].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][1].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + igr_prev = igr ^ 1; + nsamp[igr][1] = hybrid(pMP3Stream->sample[1][igr], pMP3Stream->sample[1][igr_prev], yout, side_info.gr[igr][1].block_type, n1, n2, nsamp[igr_prev][1]); + FreqInvert(yout, nsamp[igr][1]); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ -static void Xform_dual(void *pcm, int igr) -{ - int ch; - int igr_prev, n1, n2; - -/*--- hybrid + sbt ---*/ - igr_prev = igr ^ 1; - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - n1 = n2 = nsamp[igr][ch]; /* total number bands */ - if (side_info.gr[igr][ch].block_type == 2) - { /* long bands */ - n1 = 0; - if (side_info.gr[igr][ch].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - if (n1 > pMP3Stream->band_limit) - n1 = pMP3Stream->band_limit; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - nsamp[igr][ch] = hybrid(pMP3Stream->sample[ch][igr], pMP3Stream->sample[ch][igr_prev], - yout, side_info.gr[igr][ch].block_type, n1, n2, nsamp[igr_prev][ch]); - FreqInvert(yout, nsamp[igr][ch]); - pMP3Stream->sbt_L3(yout, pcm, ch); - } - +static void Xform_dual(void *pcm, int igr) { + int ch; + int igr_prev, n1, n2; + + /*--- hybrid + sbt ---*/ + igr_prev = igr ^ 1; + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + n1 = n2 = nsamp[igr][ch]; /* total number bands */ + if (side_info.gr[igr][ch].block_type == 2) { /* long bands */ + n1 = 0; + if (side_info.gr[igr][ch].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + if (n1 > pMP3Stream->band_limit) + n1 = pMP3Stream->band_limit; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + nsamp[igr][ch] = + hybrid(pMP3Stream->sample[ch][igr], pMP3Stream->sample[ch][igr_prev], yout, side_info.gr[igr][ch].block_type, n1, n2, nsamp[igr_prev][ch]); + FreqInvert(yout, nsamp[igr][ch]); + pMP3Stream->sbt_L3(yout, pcm, ch); + } } /*--------------------------------------------------------------------*/ -static void Xform_dual_mono(void *pcm, int igr) -{ - int igr_prev, n1, n2, n3; - -/*--- hybrid + sbt ---*/ - igr_prev = igr ^ 1; - if ((side_info.gr[igr][0].block_type == side_info.gr[igr][1].block_type) - && (side_info.gr[igr][0].mixed_block_flag == 0) - && (side_info.gr[igr][1].mixed_block_flag == 0)) - { - - n2 = nsamp[igr][0]; /* total number bands max of L R */ - if (n2 < nsamp[igr][1]) - n2 = nsamp[igr][1]; - if (n2 > pMP3Stream->band_limit) - n2 = pMP3Stream->band_limit; - n1 = n2; /* n1 = number long bands */ - if (side_info.gr[igr][0].block_type == 2) - n1 = 0; - sum_f_bands(pMP3Stream->sample[0][igr], pMP3Stream->sample[1][igr], n2); - n3 = nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); - } - else - { /* transform and then sum (not tested - never happens in test) */ -/*-- left chan --*/ - n1 = n2 = nsamp[igr][0]; /* total number bands */ - if (side_info.gr[igr][0].block_type == 2) - { - n1 = 0; /* long bands */ - if (side_info.gr[igr][0].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - n3 = nsamp[igr][0] = hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], - yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); -/*-- right chan --*/ - n1 = n2 = nsamp[igr][1]; /* total number bands */ - if (side_info.gr[igr][1].block_type == 2) - { - n1 = 0; /* long bands */ - if (side_info.gr[igr][1].mixed_block_flag) - n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; - } - nsamp[igr][1] = hybrid_sum(pMP3Stream->sample[1][igr], pMP3Stream->sample[0][igr], - yout, side_info.gr[igr][1].block_type, n1, n2); - if (n3 < nsamp[igr][1]) - n1 = nsamp[igr][1]; - } - -/*--------*/ - FreqInvert(yout, n3); - pMP3Stream->sbt_L3(yout, pcm, 0); +static void Xform_dual_mono(void *pcm, int igr) { + int igr_prev, n1, n2, n3; + + /*--- hybrid + sbt ---*/ + igr_prev = igr ^ 1; + if ((side_info.gr[igr][0].block_type == side_info.gr[igr][1].block_type) && (side_info.gr[igr][0].mixed_block_flag == 0) && + (side_info.gr[igr][1].mixed_block_flag == 0)) { + + n2 = nsamp[igr][0]; /* total number bands max of L R */ + if (n2 < nsamp[igr][1]) + n2 = nsamp[igr][1]; + if (n2 > pMP3Stream->band_limit) + n2 = pMP3Stream->band_limit; + n1 = n2; /* n1 = number long bands */ + if (side_info.gr[igr][0].block_type == 2) + n1 = 0; + sum_f_bands(pMP3Stream->sample[0][igr], pMP3Stream->sample[1][igr], n2); + n3 = nsamp[igr][0] = + hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + } else { /* transform and then sum (not tested - never happens in test) */ + /*-- left chan --*/ + n1 = n2 = nsamp[igr][0]; /* total number bands */ + if (side_info.gr[igr][0].block_type == 2) { + n1 = 0; /* long bands */ + if (side_info.gr[igr][0].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + n3 = nsamp[igr][0] = + hybrid(pMP3Stream->sample[0][igr], pMP3Stream->sample[0][igr_prev], yout, side_info.gr[igr][0].block_type, n1, n2, nsamp[igr_prev][0]); + /*-- right chan --*/ + n1 = n2 = nsamp[igr][1]; /* total number bands */ + if (side_info.gr[igr][1].block_type == 2) { + n1 = 0; /* long bands */ + if (side_info.gr[igr][1].mixed_block_flag) + n1 = pMP3Stream->sfBandIndex[0][pMP3Stream->ncbl_mixed - 1]; + } + nsamp[igr][1] = hybrid_sum(pMP3Stream->sample[1][igr], pMP3Stream->sample[0][igr], yout, side_info.gr[igr][1].block_type, n1, n2); + if (n3 < nsamp[igr][1]) + n1 = nsamp[igr][1]; + } + /*--------*/ + FreqInvert(yout, n3); + pMP3Stream->sbt_L3(yout, pcm, 0); } /*--------------------------------------------------------------------*/ /*====================================================================*/ -static int unpack_side_MPEG1() -{ - int prot; - int br_index; - int igr, ch; - int side_bytes; - -/* decode partial header plus initial side info */ -/* at entry bit getter points at id, sync skipped by caller */ - - pMP3Stream->id = bitget(1); /* id */ - bitget(2); /* skip layer */ - prot = bitget(1); /* bitget prot bit */ - br_index = bitget(4); - pMP3Stream->sr_index = bitget(2); - pMP3Stream->pad = bitget(1); - bitget(1); /* skip to mode */ - side_info.mode = bitget(2); /* mode */ - side_info.mode_ext = bitget(2); /* mode ext */ - - if (side_info.mode != 1) - side_info.mode_ext = 0; - -/* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ - pMP3Stream->ms_mode = side_info.mode_ext >> 1; - pMP3Stream->is_mode = side_info.mode_ext & 1; - - - pMP3Stream->crcbytes = 0; - if (prot) - bitget(4); /* skip to data */ - else - { - bitget(20); /* skip crc */ - pMP3Stream->crcbytes = 2; - } - - if (br_index > 0) /* pMP3Stream->framebytes fixed for free format */ +static int unpack_side_MPEG1() { + int prot; + int br_index; + int igr, ch; + int side_bytes; + + /* decode partial header plus initial side info */ + /* at entry bit getter points at id, sync skipped by caller */ + + pMP3Stream->id = bitget(1); /* id */ + bitget(2); /* skip layer */ + prot = bitget(1); /* bitget prot bit */ + br_index = bitget(4); + pMP3Stream->sr_index = bitget(2); + pMP3Stream->pad = bitget(1); + bitget(1); /* skip to mode */ + side_info.mode = bitget(2); /* mode */ + side_info.mode_ext = bitget(2); /* mode ext */ + + if (side_info.mode != 1) + side_info.mode_ext = 0; + + /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ + pMP3Stream->ms_mode = side_info.mode_ext >> 1; + pMP3Stream->is_mode = side_info.mode_ext & 1; + + pMP3Stream->crcbytes = 0; + if (prot) + bitget(4); /* skip to data */ + else { + bitget(20); /* skip crc */ + pMP3Stream->crcbytes = 2; + } + + if (br_index > 0) /* pMP3Stream->framebytes fixed for free format */ { - pMP3Stream->framebytes = - 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - } - - side_info.main_data_begin = bitget(9); - if (side_info.mode == 3) - { - side_info.private_bits = bitget(5); - pMP3Stream->nchan = 1; -// stereo_flag = 0; - side_bytes = (4 + 17); -/*-- with header --*/ - } - else - { - side_info.private_bits = bitget(3); - pMP3Stream->nchan = 2; -// stereo_flag = 1; - side_bytes = (4 + 32); -/*-- with header --*/ - } - for (ch = 0; ch < pMP3Stream->nchan; ch++) - side_info.scfsi[ch] = bitget(4); -/* this always 0 (both igr) for short blocks */ - - for (igr = 0; igr < 2; igr++) - { - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - side_info.gr[igr][ch].part2_3_length = bitget(12); - side_info.gr[igr][ch].big_values = bitget(9); - side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; - if (pMP3Stream->ms_mode) - side_info.gr[igr][ch].global_gain -= 2; - side_info.gr[igr][ch].scalefac_compress = bitget(4); - side_info.gr[igr][ch].window_switching_flag = bitget(1); - if (side_info.gr[igr][ch].window_switching_flag) - { - side_info.gr[igr][ch].block_type = bitget(2); - side_info.gr[igr][ch].mixed_block_flag = bitget(1); - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].subblock_gain[0] = bitget(3); - side_info.gr[igr][ch].subblock_gain[1] = bitget(3); - side_info.gr[igr][ch].subblock_gain[2] = bitget(3); - /* region count set in terms of long block cb's/bands */ - /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ - /* if(window_switching_flag) always 36 samples in region0 */ - side_info.gr[igr][ch].region0_count = (8 - 1); /* 36 samples */ - side_info.gr[igr][ch].region1_count = 20 - (8 - 1); - } - else - { - side_info.gr[igr][ch].mixed_block_flag = 0; - side_info.gr[igr][ch].block_type = 0; - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].table_select[2] = bitget(5); - side_info.gr[igr][ch].region0_count = bitget(4); - side_info.gr[igr][ch].region1_count = bitget(3); - } - side_info.gr[igr][ch].preflag = bitget(1); - side_info.gr[igr][ch].scalefac_scale = bitget(1); - side_info.gr[igr][ch].count1table_select = bitget(1); - } - } - - - -/* return bytes in header + side info */ - return side_bytes; + pMP3Stream->framebytes = 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + } + + side_info.main_data_begin = bitget(9); + if (side_info.mode == 3) { + side_info.private_bits = bitget(5); + pMP3Stream->nchan = 1; + // stereo_flag = 0; + side_bytes = (4 + 17); + /*-- with header --*/ + } else { + side_info.private_bits = bitget(3); + pMP3Stream->nchan = 2; + // stereo_flag = 1; + side_bytes = (4 + 32); + /*-- with header --*/ + } + for (ch = 0; ch < pMP3Stream->nchan; ch++) + side_info.scfsi[ch] = bitget(4); + /* this always 0 (both igr) for short blocks */ + + for (igr = 0; igr < 2; igr++) { + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + side_info.gr[igr][ch].part2_3_length = bitget(12); + side_info.gr[igr][ch].big_values = bitget(9); + side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; + if (pMP3Stream->ms_mode) + side_info.gr[igr][ch].global_gain -= 2; + side_info.gr[igr][ch].scalefac_compress = bitget(4); + side_info.gr[igr][ch].window_switching_flag = bitget(1); + if (side_info.gr[igr][ch].window_switching_flag) { + side_info.gr[igr][ch].block_type = bitget(2); + side_info.gr[igr][ch].mixed_block_flag = bitget(1); + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].subblock_gain[0] = bitget(3); + side_info.gr[igr][ch].subblock_gain[1] = bitget(3); + side_info.gr[igr][ch].subblock_gain[2] = bitget(3); + /* region count set in terms of long block cb's/bands */ + /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ + /* if(window_switching_flag) always 36 samples in region0 */ + side_info.gr[igr][ch].region0_count = (8 - 1); /* 36 samples */ + side_info.gr[igr][ch].region1_count = 20 - (8 - 1); + } else { + side_info.gr[igr][ch].mixed_block_flag = 0; + side_info.gr[igr][ch].block_type = 0; + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].table_select[2] = bitget(5); + side_info.gr[igr][ch].region0_count = bitget(4); + side_info.gr[igr][ch].region1_count = bitget(3); + } + side_info.gr[igr][ch].preflag = bitget(1); + side_info.gr[igr][ch].scalefac_scale = bitget(1); + side_info.gr[igr][ch].count1table_select = bitget(1); + } + } + + /* return bytes in header + side info */ + return side_bytes; } /*====================================================================*/ -static int unpack_side_MPEG2(int igr) -{ - int prot; - int br_index; - int ch; - int side_bytes; - -/* decode partial header plus initial side info */ -/* at entry bit getter points at id, sync skipped by caller */ - - pMP3Stream->id = bitget(1); /* id */ - bitget(2); /* skip layer */ - prot = bitget(1); /* bitget prot bit */ - br_index = bitget(4); - pMP3Stream->sr_index = bitget(2); - pMP3Stream->pad = bitget(1); - bitget(1); /* skip to mode */ - side_info.mode = bitget(2); /* mode */ - side_info.mode_ext = bitget(2); /* mode ext */ - - if (side_info.mode != 1) - side_info.mode_ext = 0; - -/* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ - pMP3Stream->ms_mode = side_info.mode_ext >> 1; - pMP3Stream->is_mode = side_info.mode_ext & 1; - - pMP3Stream->crcbytes = 0; - if (prot) - bitget(4); /* skip to data */ - else - { - bitget(20); /* skip crc */ - pMP3Stream->crcbytes = 2; - } - - if (br_index > 0) - { /* pMP3Stream->framebytes fixed for free format */ - if (pMP3Stream->mpeg25_flag == 0) - { - pMP3Stream->framebytes = - 1440 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - } - else - { - pMP3Stream->framebytes = - 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; - //if( pMP3Stream->sr_index == 2 ) return 0; // fail mpeg25 8khz - } - } - side_info.main_data_begin = bitget(8); - if (side_info.mode == 3) - { - side_info.private_bits = bitget(1); - pMP3Stream->nchan = 1; -// stereo_flag = 0; - side_bytes = (4 + 9); -/*-- with header --*/ - } - else - { - side_info.private_bits = bitget(2); - pMP3Stream->nchan = 2; -// stereo_flag = 1; - side_bytes = (4 + 17); -/*-- with header --*/ - } - side_info.scfsi[1] = side_info.scfsi[0] = 0; - - - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - side_info.gr[igr][ch].part2_3_length = bitget(12); - side_info.gr[igr][ch].big_values = bitget(9); - side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; - if (pMP3Stream->ms_mode) - side_info.gr[igr][ch].global_gain -= 2; - side_info.gr[igr][ch].scalefac_compress = bitget(9); - side_info.gr[igr][ch].window_switching_flag = bitget(1); - if (side_info.gr[igr][ch].window_switching_flag) - { - side_info.gr[igr][ch].block_type = bitget(2); - side_info.gr[igr][ch].mixed_block_flag = bitget(1); - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].subblock_gain[0] = bitget(3); - side_info.gr[igr][ch].subblock_gain[1] = bitget(3); - side_info.gr[igr][ch].subblock_gain[2] = bitget(3); - /* region count set in terms of long block cb's/bands */ - /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ - /* bt=1 or 3 54 samples */ - /* bt=2 mixed=0 36 samples */ - /* bt=2 mixed=1 54 (8 long sf) samples? or maybe 36 */ - /* region0 discussion says 54 but this would mix long */ - /* and short in region0 if scale factors switch */ - /* at band 36 (6 long scale factors) */ - if (side_info.gr[igr][ch].block_type == 2) - { - side_info.gr[igr][ch].region0_count = (6 - 1); /* 36 samples */ - side_info.gr[igr][ch].region1_count = 20 - (6 - 1); - } - else - { /* long block type 1 or 3 */ - side_info.gr[igr][ch].region0_count = (8 - 1); /* 54 samples */ - side_info.gr[igr][ch].region1_count = 20 - (8 - 1); - } - } - else - { - side_info.gr[igr][ch].mixed_block_flag = 0; - side_info.gr[igr][ch].block_type = 0; - side_info.gr[igr][ch].table_select[0] = bitget(5); - side_info.gr[igr][ch].table_select[1] = bitget(5); - side_info.gr[igr][ch].table_select[2] = bitget(5); - side_info.gr[igr][ch].region0_count = bitget(4); - side_info.gr[igr][ch].region1_count = bitget(3); - } - side_info.gr[igr][ch].preflag = 0; - side_info.gr[igr][ch].scalefac_scale = bitget(1); - side_info.gr[igr][ch].count1table_select = bitget(1); - } - -/* return bytes in header + side info */ - return side_bytes; +static int unpack_side_MPEG2(int igr) { + int prot; + int br_index; + int ch; + int side_bytes; + + /* decode partial header plus initial side info */ + /* at entry bit getter points at id, sync skipped by caller */ + + pMP3Stream->id = bitget(1); /* id */ + bitget(2); /* skip layer */ + prot = bitget(1); /* bitget prot bit */ + br_index = bitget(4); + pMP3Stream->sr_index = bitget(2); + pMP3Stream->pad = bitget(1); + bitget(1); /* skip to mode */ + side_info.mode = bitget(2); /* mode */ + side_info.mode_ext = bitget(2); /* mode ext */ + + if (side_info.mode != 1) + side_info.mode_ext = 0; + + /* adjust global gain in ms mode to avoid having to mult by 1/sqrt(2) */ + pMP3Stream->ms_mode = side_info.mode_ext >> 1; + pMP3Stream->is_mode = side_info.mode_ext & 1; + + pMP3Stream->crcbytes = 0; + if (prot) + bitget(4); /* skip to data */ + else { + bitget(20); /* skip crc */ + pMP3Stream->crcbytes = 2; + } + + if (br_index > 0) { /* pMP3Stream->framebytes fixed for free format */ + if (pMP3Stream->mpeg25_flag == 0) { + pMP3Stream->framebytes = 1440 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + } else { + pMP3Stream->framebytes = 2880 * mp_br_tableL3[pMP3Stream->id][br_index] / mp_sr20_table[pMP3Stream->id][pMP3Stream->sr_index]; + // if( pMP3Stream->sr_index == 2 ) return 0; // fail mpeg25 8khz + } + } + side_info.main_data_begin = bitget(8); + if (side_info.mode == 3) { + side_info.private_bits = bitget(1); + pMP3Stream->nchan = 1; + // stereo_flag = 0; + side_bytes = (4 + 9); + /*-- with header --*/ + } else { + side_info.private_bits = bitget(2); + pMP3Stream->nchan = 2; + // stereo_flag = 1; + side_bytes = (4 + 17); + /*-- with header --*/ + } + side_info.scfsi[1] = side_info.scfsi[0] = 0; + + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + side_info.gr[igr][ch].part2_3_length = bitget(12); + side_info.gr[igr][ch].big_values = bitget(9); + side_info.gr[igr][ch].global_gain = bitget(8) + pMP3Stream->gain_adjust; + if (pMP3Stream->ms_mode) + side_info.gr[igr][ch].global_gain -= 2; + side_info.gr[igr][ch].scalefac_compress = bitget(9); + side_info.gr[igr][ch].window_switching_flag = bitget(1); + if (side_info.gr[igr][ch].window_switching_flag) { + side_info.gr[igr][ch].block_type = bitget(2); + side_info.gr[igr][ch].mixed_block_flag = bitget(1); + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].subblock_gain[0] = bitget(3); + side_info.gr[igr][ch].subblock_gain[1] = bitget(3); + side_info.gr[igr][ch].subblock_gain[2] = bitget(3); + /* region count set in terms of long block cb's/bands */ + /* r1 set so r0+r1+1 = 21 (lookup produces 576 bands ) */ + /* bt=1 or 3 54 samples */ + /* bt=2 mixed=0 36 samples */ + /* bt=2 mixed=1 54 (8 long sf) samples? or maybe 36 */ + /* region0 discussion says 54 but this would mix long */ + /* and short in region0 if scale factors switch */ + /* at band 36 (6 long scale factors) */ + if (side_info.gr[igr][ch].block_type == 2) { + side_info.gr[igr][ch].region0_count = (6 - 1); /* 36 samples */ + side_info.gr[igr][ch].region1_count = 20 - (6 - 1); + } else { /* long block type 1 or 3 */ + side_info.gr[igr][ch].region0_count = (8 - 1); /* 54 samples */ + side_info.gr[igr][ch].region1_count = 20 - (8 - 1); + } + } else { + side_info.gr[igr][ch].mixed_block_flag = 0; + side_info.gr[igr][ch].block_type = 0; + side_info.gr[igr][ch].table_select[0] = bitget(5); + side_info.gr[igr][ch].table_select[1] = bitget(5); + side_info.gr[igr][ch].table_select[2] = bitget(5); + side_info.gr[igr][ch].region0_count = bitget(4); + side_info.gr[igr][ch].region1_count = bitget(3); + } + side_info.gr[igr][ch].preflag = 0; + side_info.gr[igr][ch].scalefac_scale = bitget(1); + side_info.gr[igr][ch].count1table_select = bitget(1); + } + + /* return bytes in header + side info */ + return side_bytes; } /*-----------------------------------------------------------------*/ -static void unpack_main(unsigned char *pcm, int igr) -{ - int ch; - int bit0; - int n1, n2, n3, n4, nn2, nn3; - int nn4; - int qbits; - int m0; - - - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - bitget_init(pMP3Stream->buf + (pMP3Stream->main_pos_bit >> 3)); - bit0 = (pMP3Stream->main_pos_bit & 7); - if (bit0) - bitget(bit0); - pMP3Stream->main_pos_bit += side_info.gr[igr][ch].part2_3_length; - bitget_init_end(pMP3Stream->buf + ((pMP3Stream->main_pos_bit + 39) >> 3)); -/*-- scale factors --*/ - if (pMP3Stream->id) - unpack_sf_sub_MPEG1(&sf[igr][ch], - &side_info.gr[igr][ch], side_info.scfsi[ch], igr); - else - unpack_sf_sub_MPEG2(&sf[igr][ch], - &side_info.gr[igr][ch], pMP3Stream->is_mode & ch, &is_sf_info); -/*--- huff data ---*/ - n1 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count]; - n2 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count - + side_info.gr[igr][ch].region1_count + 1]; - n3 = side_info.gr[igr][ch].big_values; - n3 = n3 + n3; - - - if (n3 > pMP3Stream->band_limit) - n3 = pMP3Stream->band_limit; - if (n2 > n3) - n2 = n3; - if (n1 > n3) - n1 = n3; - nn3 = n3 - n2; - nn2 = n2 - n1; - unpack_huff(pMP3Stream->sample[ch][igr], n1, side_info.gr[igr][ch].table_select[0]); - unpack_huff(pMP3Stream->sample[ch][igr] + n1, nn2, side_info.gr[igr][ch].table_select[1]); - unpack_huff(pMP3Stream->sample[ch][igr] + n2, nn3, side_info.gr[igr][ch].table_select[2]); - qbits = side_info.gr[igr][ch].part2_3_length - (bitget_bits_used() - bit0); - nn4 = unpack_huff_quad(pMP3Stream->sample[ch][igr] + n3, pMP3Stream->band_limit - n3, qbits, - side_info.gr[igr][ch].count1table_select); - n4 = n3 + nn4; - nsamp[igr][ch] = n4; - //limit n4 or allow deqaunt to sf band 22 - if (side_info.gr[igr][ch].block_type == 2) - n4 = min(n4, pMP3Stream->band_limit12); - else - n4 = min(n4, pMP3Stream->band_limit21); - if (n4 < 576) - memset(pMP3Stream->sample[ch][igr] + n4, 0, sizeof(SAMPLE) * (576 - n4)); - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - { // bad data overrun - - memset(pMP3Stream->sample[ch][igr], 0, sizeof(SAMPLE) * (576)); - } - } - - - -/*--- dequant ---*/ - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - dequant(pMP3Stream->sample[ch][igr], - &nsamp[igr][ch], /* nsamp updated for shorts */ - &sf[igr][ch], &side_info.gr[igr][ch], - &cb_info[igr][ch], pMP3Stream->ncbl_mixed); - } - -/*--- ms stereo processing ---*/ - if (pMP3Stream->ms_mode) - { - if (pMP3Stream->is_mode == 0) - { - m0 = nsamp[igr][0]; /* process to longer of left/right */ - if (m0 < nsamp[igr][1]) - m0 = nsamp[igr][1]; - } - else - { /* process to last cb in right */ - m0 = pMP3Stream->sfBandIndex[cb_info[igr][1].cbtype][cb_info[igr][1].cbmax]; - } - ms_process(pMP3Stream->sample[0][igr], m0); - } - -/*--- is stereo processing ---*/ - if (pMP3Stream->is_mode) - { - if (pMP3Stream->id) - is_process_MPEG1(pMP3Stream->sample[0][igr], &sf[igr][1], - cb_info[igr], nsamp[igr][0], pMP3Stream->ms_mode); - else - is_process_MPEG2(pMP3Stream->sample[0][igr], &sf[igr][1], - cb_info[igr], &is_sf_info, - nsamp[igr][0], pMP3Stream->ms_mode); - } - -/*-- adjust ms and is modes to max of left/right */ - if (side_info.mode_ext) - { - if (nsamp[igr][0] < nsamp[igr][1]) - nsamp[igr][0] = nsamp[igr][1]; - else - nsamp[igr][1] = nsamp[igr][0]; - } - -/*--- antialias ---*/ - for (ch = 0; ch < pMP3Stream->nchan; ch++) - { - if (cb_info[igr][ch].ncbl == 0) - continue; /* have no long blocks */ - if (side_info.gr[igr][ch].mixed_block_flag) - n1 = 1; /* 1 -> 36 samples */ - else - n1 = (nsamp[igr][ch] + 7) / 18; - if (n1 > 31) - n1 = 31; - antialias(pMP3Stream->sample[ch][igr], n1); - n1 = 18 * n1 + 8; /* update number of samples */ - if (n1 > nsamp[igr][ch]) - nsamp[igr][ch] = n1; - } - - - -/*--- hybrid + sbt ---*/ - pMP3Stream->Xform(pcm, igr); - - -/*-- done --*/ +static void unpack_main(unsigned char *pcm, int igr) { + int ch; + int bit0; + int n1, n2, n3, n4, nn2, nn3; + int nn4; + int qbits; + int m0; + + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + bitget_init(pMP3Stream->buf + (pMP3Stream->main_pos_bit >> 3)); + bit0 = (pMP3Stream->main_pos_bit & 7); + if (bit0) + bitget(bit0); + pMP3Stream->main_pos_bit += side_info.gr[igr][ch].part2_3_length; + bitget_init_end(pMP3Stream->buf + ((pMP3Stream->main_pos_bit + 39) >> 3)); + /*-- scale factors --*/ + if (pMP3Stream->id) + unpack_sf_sub_MPEG1(&sf[igr][ch], &side_info.gr[igr][ch], side_info.scfsi[ch], igr); + else + unpack_sf_sub_MPEG2(&sf[igr][ch], &side_info.gr[igr][ch], pMP3Stream->is_mode & ch, &is_sf_info); + /*--- huff data ---*/ + n1 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count]; + n2 = pMP3Stream->sfBandIndex[0][side_info.gr[igr][ch].region0_count + side_info.gr[igr][ch].region1_count + 1]; + n3 = side_info.gr[igr][ch].big_values; + n3 = n3 + n3; + + if (n3 > pMP3Stream->band_limit) + n3 = pMP3Stream->band_limit; + if (n2 > n3) + n2 = n3; + if (n1 > n3) + n1 = n3; + nn3 = n3 - n2; + nn2 = n2 - n1; + unpack_huff(pMP3Stream->sample[ch][igr], n1, side_info.gr[igr][ch].table_select[0]); + unpack_huff(pMP3Stream->sample[ch][igr] + n1, nn2, side_info.gr[igr][ch].table_select[1]); + unpack_huff(pMP3Stream->sample[ch][igr] + n2, nn3, side_info.gr[igr][ch].table_select[2]); + qbits = side_info.gr[igr][ch].part2_3_length - (bitget_bits_used() - bit0); + nn4 = unpack_huff_quad(pMP3Stream->sample[ch][igr] + n3, pMP3Stream->band_limit - n3, qbits, side_info.gr[igr][ch].count1table_select); + n4 = n3 + nn4; + nsamp[igr][ch] = n4; + // limit n4 or allow deqaunt to sf band 22 + if (side_info.gr[igr][ch].block_type == 2) + n4 = min(n4, pMP3Stream->band_limit12); + else + n4 = min(n4, pMP3Stream->band_limit21); + if (n4 < 576) + memset(pMP3Stream->sample[ch][igr] + n4, 0, sizeof(SAMPLE) * (576 - n4)); + if (bitdat.bs_ptr > bitdat.bs_ptr_end) { // bad data overrun + + memset(pMP3Stream->sample[ch][igr], 0, sizeof(SAMPLE) * (576)); + } + } + + /*--- dequant ---*/ + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + dequant(pMP3Stream->sample[ch][igr], &nsamp[igr][ch], /* nsamp updated for shorts */ + &sf[igr][ch], &side_info.gr[igr][ch], &cb_info[igr][ch], pMP3Stream->ncbl_mixed); + } + + /*--- ms stereo processing ---*/ + if (pMP3Stream->ms_mode) { + if (pMP3Stream->is_mode == 0) { + m0 = nsamp[igr][0]; /* process to longer of left/right */ + if (m0 < nsamp[igr][1]) + m0 = nsamp[igr][1]; + } else { /* process to last cb in right */ + m0 = pMP3Stream->sfBandIndex[cb_info[igr][1].cbtype][cb_info[igr][1].cbmax]; + } + ms_process(pMP3Stream->sample[0][igr], m0); + } + + /*--- is stereo processing ---*/ + if (pMP3Stream->is_mode) { + if (pMP3Stream->id) + is_process_MPEG1(pMP3Stream->sample[0][igr], &sf[igr][1], cb_info[igr], nsamp[igr][0], pMP3Stream->ms_mode); + else + is_process_MPEG2(pMP3Stream->sample[0][igr], &sf[igr][1], cb_info[igr], &is_sf_info, nsamp[igr][0], pMP3Stream->ms_mode); + } + + /*-- adjust ms and is modes to max of left/right */ + if (side_info.mode_ext) { + if (nsamp[igr][0] < nsamp[igr][1]) + nsamp[igr][0] = nsamp[igr][1]; + else + nsamp[igr][1] = nsamp[igr][0]; + } + + /*--- antialias ---*/ + for (ch = 0; ch < pMP3Stream->nchan; ch++) { + if (cb_info[igr][ch].ncbl == 0) + continue; /* have no long blocks */ + if (side_info.gr[igr][ch].mixed_block_flag) + n1 = 1; /* 1 -> 36 samples */ + else + n1 = (nsamp[igr][ch] + 7) / 18; + if (n1 > 31) + n1 = 31; + antialias(pMP3Stream->sample[ch][igr], n1); + n1 = 18 * n1 + 8; /* update number of samples */ + if (n1 > nsamp[igr][ch]) + nsamp[igr][ch] = n1; + } + + /*--- hybrid + sbt ---*/ + pMP3Stream->Xform(pcm, igr); + + /*-- done --*/ } /*--------------------------------------------------------------------*/ /*-----------------------------------------------------------------*/ -IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm) -{ - return pMP3Stream->decode_function(bs, pcm); -} +IN_OUT L3audio_decode(unsigned char *bs, unsigned char *pcm) { return pMP3Stream->decode_function(bs, pcm); } /*--------------------------------------------------------------------*/ extern unsigned char *gpNextByteAfterData; -IN_OUT L3audio_decode_MPEG1(unsigned char *bs, unsigned char *pcm) -{ - int sync; - IN_OUT in_out; - int side_bytes; - int nbytes; - - int padframebytes; ////@@@@ - -// iframe++; - - bitget_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = bitget(12); - - if (sync != 0xFFF) - return in_out; /* sync fail */ -/*-----------*/ - -/*-- unpack side info --*/ - side_bytes = unpack_side_MPEG1(); - padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; - - if (bs + padframebytes > gpNextByteAfterData) - return in_out; // error check if we're about to read off the end of the legal memory (caused by certain MP3 writers' goofy comment formats) -ste. - in_out.in_bytes = padframebytes; - -/*-- load main data and update buf pointer --*/ -/*------------------------------------------- - if start point < 0, must just cycle decoder - if jumping into middle of stream, -w---------------------------------------------*/ - pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ - if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) - { /* shift buffer */ - memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = side_info.main_data_begin; - } - nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - - // RAK: This is no bueno. :-( - if (nbytes < 0 || nbytes > NBUF) - { - in_out.in_bytes = 0; - return in_out; - } +IN_OUT L3audio_decode_MPEG1(unsigned char *bs, unsigned char *pcm) { + int sync; + IN_OUT in_out; + int side_bytes; + int nbytes; + + int padframebytes; ////@@@@ + + // iframe++; + + bitget_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = bitget(12); + + if (sync != 0xFFF) + return in_out; /* sync fail */ + /*-----------*/ + + /*-- unpack side info --*/ + side_bytes = unpack_side_MPEG1(); + padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; + + if (bs + padframebytes > gpNextByteAfterData) + return in_out; // error check if we're about to read off the end of the legal memory (caused by certain MP3 writers' goofy comment formats) -ste. + in_out.in_bytes = padframebytes; + + /*-- load main data and update buf pointer --*/ + /*------------------------------------------- + if start point < 0, must just cycle decoder + if jumping into middle of stream, + w---------------------------------------------*/ + pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ + if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ + memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = side_info.main_data_begin; + } + nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - if (bFastEstimateOnly) - { + // RAK: This is no bueno. :-( + if (nbytes < 0 || nbytes > NBUF) { + in_out.in_bytes = 0; + return in_out; + } + + if (bFastEstimateOnly) { in_out.out_bytes = pMP3Stream->outbytes; return in_out; } - memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); - pMP3Stream->buf_ptr1 += nbytes; -/*-----------------------*/ - - if (pMP3Stream->buf_ptr0 >= 0) - { -// dump_frame(buf+buf_ptr0, 64); - pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; - unpack_main(pcm, 0); - unpack_main(pcm + pMP3Stream->half_outbytes, 1); - in_out.out_bytes = pMP3Stream->outbytes; - } - else - { - memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ - in_out.out_bytes = pMP3Stream->outbytes; -/* iframe--; in_out.out_bytes = 0; // test test */ - } - - return in_out; + memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); + pMP3Stream->buf_ptr1 += nbytes; + /*-----------------------*/ + + if (pMP3Stream->buf_ptr0 >= 0) { + // dump_frame(buf+buf_ptr0, 64); + pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; + unpack_main(pcm, 0); + unpack_main(pcm + pMP3Stream->half_outbytes, 1); + in_out.out_bytes = pMP3Stream->outbytes; + } else { + memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ + in_out.out_bytes = pMP3Stream->outbytes; + /* iframe--; in_out.out_bytes = 0; // test test */ + } + + return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm) -{ - int sync; - IN_OUT in_out; - int side_bytes; - int nbytes; - static int igr = 0; - - int padframebytes; ////@@@@ - -// iframe++; - - - bitget_init(bs); /* initialize bit getter */ -/* test sync */ - in_out.in_bytes = 0; /* assume fail */ - in_out.out_bytes = 0; - sync = bitget(12); - -// if( sync != 0xFFF ) return in_out; /* sync fail */ - - pMP3Stream->mpeg25_flag = 0; - if (sync != 0xFFF) - { - pMP3Stream->mpeg25_flag = 1; /* mpeg 2.5 sync */ - if (sync != 0xFFE) - return in_out; /* sync fail */ - } -/*-----------*/ - - -/*-- unpack side info --*/ - side_bytes = unpack_side_MPEG2(igr); - padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; - in_out.in_bytes = padframebytes; - - pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ - if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) - { /* shift buffer */ - memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = side_info.main_data_begin; - } - nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; - // RAK: This is no bueno. :-( - if (nbytes < 0 || nbytes > NBUF) - { - in_out.in_bytes = 0; - return in_out; - } +IN_OUT L3audio_decode_MPEG2(unsigned char *bs, unsigned char *pcm) { + int sync; + IN_OUT in_out; + int side_bytes; + int nbytes; + static int igr = 0; + + int padframebytes; ////@@@@ + + // iframe++; + + bitget_init(bs); /* initialize bit getter */ + /* test sync */ + in_out.in_bytes = 0; /* assume fail */ + in_out.out_bytes = 0; + sync = bitget(12); + + // if( sync != 0xFFF ) return in_out; /* sync fail */ + + pMP3Stream->mpeg25_flag = 0; + if (sync != 0xFFF) { + pMP3Stream->mpeg25_flag = 1; /* mpeg 2.5 sync */ + if (sync != 0xFFE) + return in_out; /* sync fail */ + } + /*-----------*/ + + /*-- unpack side info --*/ + side_bytes = unpack_side_MPEG2(igr); + padframebytes = pMP3Stream->framebytes + pMP3Stream->pad; + in_out.in_bytes = padframebytes; + + pMP3Stream->buf_ptr0 = pMP3Stream->buf_ptr1 - side_info.main_data_begin; /* decode start point */ + if (pMP3Stream->buf_ptr1 > BUF_TRIGGER) { /* shift buffer */ + memmove(pMP3Stream->buf, pMP3Stream->buf + pMP3Stream->buf_ptr0, side_info.main_data_begin); + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = side_info.main_data_begin; + } + nbytes = padframebytes - side_bytes - pMP3Stream->crcbytes; + // RAK: This is no bueno. :-( + if (nbytes < 0 || nbytes > NBUF) { + in_out.in_bytes = 0; + return in_out; + } - if (bFastEstimateOnly) - { + if (bFastEstimateOnly) { in_out.out_bytes = pMP3Stream->outbytes; return in_out; } - memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); - pMP3Stream->buf_ptr1 += nbytes; -/*-----------------------*/ - - if (pMP3Stream->buf_ptr0 >= 0) - { - pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; - unpack_main(pcm, igr); - in_out.out_bytes = pMP3Stream->outbytes; - } - else - { - memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ - in_out.out_bytes = pMP3Stream->outbytes; -// iframe--; in_out.out_bytes = 0; return in_out;// test test */ - } - + memmove(pMP3Stream->buf + pMP3Stream->buf_ptr1, bs + side_bytes + pMP3Stream->crcbytes, nbytes); + pMP3Stream->buf_ptr1 += nbytes; + /*-----------------------*/ + if (pMP3Stream->buf_ptr0 >= 0) { + pMP3Stream->main_pos_bit = pMP3Stream->buf_ptr0 << 3; + unpack_main(pcm, igr); + in_out.out_bytes = pMP3Stream->outbytes; + } else { + memset(pcm, pMP3Stream->zero_level_pcm, pMP3Stream->outbytes); /* fill out skipped frames */ + in_out.out_bytes = pMP3Stream->outbytes; + // iframe--; in_out.out_bytes = 0; return in_out;// test test */ + } - igr = igr ^ 1; - return in_out; + igr = igr ^ 1; + return in_out; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -static const int sr_table[8] = -{22050, 24000, 16000, 1, - 44100, 48000, 32000, 1}; - -static const struct -{ - int l[23]; - int s[14]; -} -sfBandIndexTable[3][3] = -{ -/* mpeg-2 */ - { - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , - } - , -/* mpeg-1 */ - { - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192 - } - } - , - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192 - } - } - , - { - { - 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576 - } - , - { - 0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192 - } - } - } - , - -/* mpeg-2.5, 11 & 12 KHz seem ok, 8 ok */ - { - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , - { - { - 0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 - } - , - { - 0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 - } - } - , -// this 8khz table, and only 8khz, from mpeg123) - { - { - 0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576 - } - , - { - 0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192 - } - } - , - } - , -}; +static const int sr_table[8] = {22050, 24000, 16000, 1, 44100, 48000, 32000, 1}; +static const struct { + int l[23]; + int s[14]; +} sfBandIndexTable[3][3] = { + /* mpeg-2 */ + { + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + }, + /* mpeg-1 */ + {{{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576}, + {0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192}}, + {{0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576}, + {0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192}}, + {{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576}, + {0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192}}}, + + /* mpeg-2.5, 11 & 12 KHz seem ok, 8 ok */ + { + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576}, + {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}}, + // this 8khz table, and only 8khz, from mpeg123) + {{0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576}, + {0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192}}, + }, +}; void sbt_mono_L3(float *sample, signed short *pcm, int ch); void sbt_dual_L3(float *sample, signed short *pcm, int ch); @@ -1070,38 +858,22 @@ void sbtB16_dual_L3(float *sample, unsigned char *pcm, int ch); void sbtB8_mono_L3(float *sample, unsigned char *pcm, int ch); void sbtB8_dual_L3(float *sample, unsigned char *pcm, int ch); - - -static const SBT_FUNCTION sbt_table[2][3][2] = -{ -{{ (SBT_FUNCTION) sbt_mono_L3, - (SBT_FUNCTION) sbt_dual_L3 } , - { (SBT_FUNCTION) sbt16_mono_L3, - (SBT_FUNCTION) sbt16_dual_L3 } , - { (SBT_FUNCTION) sbt8_mono_L3, - (SBT_FUNCTION) sbt8_dual_L3 }} , -/*-- 8 bit output -*/ -{{ (SBT_FUNCTION) sbtB_mono_L3, - (SBT_FUNCTION) sbtB_dual_L3 }, - { (SBT_FUNCTION) sbtB16_mono_L3, - (SBT_FUNCTION) sbtB16_dual_L3 }, - { (SBT_FUNCTION) sbtB8_mono_L3, - (SBT_FUNCTION) sbtB8_dual_L3 }} -}; - +static const SBT_FUNCTION sbt_table[2][3][2] = {{{(SBT_FUNCTION)sbt_mono_L3, (SBT_FUNCTION)sbt_dual_L3}, + {(SBT_FUNCTION)sbt16_mono_L3, (SBT_FUNCTION)sbt16_dual_L3}, + {(SBT_FUNCTION)sbt8_mono_L3, (SBT_FUNCTION)sbt8_dual_L3}}, + /*-- 8 bit output -*/ + {{(SBT_FUNCTION)sbtB_mono_L3, (SBT_FUNCTION)sbtB_dual_L3}, + {(SBT_FUNCTION)sbtB16_mono_L3, (SBT_FUNCTION)sbtB16_dual_L3}, + {(SBT_FUNCTION)sbtB8_mono_L3, (SBT_FUNCTION)sbtB8_dual_L3}}}; void Xform_mono(void *pcm, int igr); void Xform_dual(void *pcm, int igr); void Xform_dual_mono(void *pcm, int igr); void Xform_dual_right(void *pcm, int igr); -static XFORM_FUNCTION xform_table[5] = -{ - Xform_mono, - Xform_dual, - Xform_dual_mono, - Xform_mono, /* left */ - Xform_dual_right, +static XFORM_FUNCTION xform_table[5] = { + Xform_mono, Xform_dual, Xform_dual_mono, Xform_mono, /* left */ + Xform_dual_right, }; int L3table_init(); void msis_init(); @@ -1113,178 +885,161 @@ iARRAY22 *msis_init_band_addr(); /*---------------------------------------------------------*/ /* mpeg_head defined in mhead.h frame bytes is without pMP3Stream->pad */ ////@@@@INIT -int L3audio_decode_init(MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, int convert_code, - int freq_limit) -{ - int i, j, k; - // static int first_pass = 1; - int samprate; - int limit; - int bit_code; - int out_chans; - - pMP3Stream->buf_ptr0 = 0; - pMP3Stream->buf_ptr1 = 0; - -/* check if code handles */ - if (h->option != 1) - return 0; /* layer III only */ - - if (h->id) - pMP3Stream->ncbl_mixed = 8; /* mpeg-1 */ - else - pMP3Stream->ncbl_mixed = 6; /* mpeg-2 */ - - pMP3Stream->framebytes = framebytes_arg; - - bit_code = 0; - if (convert_code & 8) - bit_code = 1; - convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ - if (reduction_code < 0) - reduction_code = 0; - if (reduction_code > 2) - reduction_code = 2; - if (freq_limit < 1000) - freq_limit = 1000; - - - samprate = sr_table[4 * h->id + h->sr_index]; - if ((h->sync & 1) == 0) - samprate = samprate / 2; // mpeg 2.5 -/*----- compute pMP3Stream->nsb_limit --------*/ - pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; -/*- caller limit -*/ - limit = (32 >> reduction_code); - if (limit > 8) - limit--; - if (pMP3Stream->nsb_limit > limit) - pMP3Stream->nsb_limit = limit; - limit = 18 * pMP3Stream->nsb_limit; - - k = h->id; - if ((h->sync & 1) == 0) - k = 2; // mpeg 2.5 - - if (k == 1) - { - pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[13]; - pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[22]; - } - else - { - pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[12]; - pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[21]; - } - pMP3Stream->band_limit += 8; /* allow for antialias */ - if (pMP3Stream->band_limit > limit) - pMP3Stream->band_limit = limit; - - if (pMP3Stream->band_limit21 > pMP3Stream->band_limit) - pMP3Stream->band_limit21 = pMP3Stream->band_limit; - if (pMP3Stream->band_limit12 > pMP3Stream->band_limit) - pMP3Stream->band_limit12 = pMP3Stream->band_limit; - - - pMP3Stream->band_limit_nsb = (pMP3Stream->band_limit + 17) / 18; /* limit nsb's rounded up */ -/*----------------------------------------------*/ - pMP3Stream->gain_adjust = 0; /* adjust gain e.g. cvt to mono sum channel */ - if ((h->mode != 3) && (convert_code == 1)) - pMP3Stream->gain_adjust = -4; - - pMP3Stream->outvalues = 1152 >> reduction_code; - if (h->id == 0) - pMP3Stream->outvalues /= 2; - - out_chans = 2; - if (h->mode == 3) - out_chans = 1; - if (convert_code) - out_chans = 1; - - pMP3Stream->sbt_L3 = sbt_table[bit_code][reduction_code][out_chans - 1]; - k = 1 + convert_code; - if (h->mode == 3) - k = 0; - pMP3Stream->Xform = xform_table[k]; - - - pMP3Stream->outvalues *= out_chans; - - if (bit_code) - pMP3Stream->outbytes = pMP3Stream->outvalues; - else - pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; - - if (bit_code) - pMP3Stream->zero_level_pcm = 128; /* 8 bit output */ - else - pMP3Stream->zero_level_pcm = 0; - - - decinfo.channels = out_chans; - decinfo.outvalues = pMP3Stream->outvalues; - decinfo.samprate = samprate >> reduction_code; - if (bit_code) - decinfo.bits = 8; - else - decinfo.bits = sizeof(short) * 8; - - decinfo.framebytes = pMP3Stream->framebytes; - decinfo.type = 0; - - pMP3Stream->half_outbytes = pMP3Stream->outbytes / 2; -/*------------------------------------------*/ - -/*- init band tables --*/ - - - k = h->id; - if ((h->sync & 1) == 0) - k = 2; // mpeg 2.5 - - for (i = 0; i < 22; i++) - pMP3Stream->sfBandIndex[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1]; - for (i = 0; i < 13; i++) - pMP3Stream->sfBandIndex[1][i] = 3 * sfBandIndexTable[k][h->sr_index].s[i + 1]; - for (i = 0; i < 22; i++) - pMP3Stream->nBand[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1] - sfBandIndexTable[k][h->sr_index].l[i]; - for (i = 0; i < 13; i++) - pMP3Stream->nBand[1][i] = sfBandIndexTable[k][h->sr_index].s[i + 1] - sfBandIndexTable[k][h->sr_index].s[i]; - - -/* init tables */ - L3table_init(); -/* init ms and is stereo modes */ - msis_init(); - -/*----- init sbt ---*/ - sbt_init(); - - - -/*--- clear buffers --*/ - for (i = 0; i < 576; i++) - yout[i] = 0.0f; - for (j = 0; j < 2; j++) - { - for (k = 0; k < 2; k++) - { - for (i = 0; i < 576; i++) - { - pMP3Stream->sample[j][k][i].x = 0.0f; - pMP3Stream->sample[j][k][i].s = 0; - } - } - } +int L3audio_decode_init(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit) { + int i, j, k; + // static int first_pass = 1; + int samprate; + int limit; + int bit_code; + int out_chans; + + pMP3Stream->buf_ptr0 = 0; + pMP3Stream->buf_ptr1 = 0; + + /* check if code handles */ + if (h->option != 1) + return 0; /* layer III only */ + + if (h->id) + pMP3Stream->ncbl_mixed = 8; /* mpeg-1 */ + else + pMP3Stream->ncbl_mixed = 6; /* mpeg-2 */ + + pMP3Stream->framebytes = framebytes_arg; + + bit_code = 0; + if (convert_code & 8) + bit_code = 1; + convert_code = convert_code & 3; /* higher bits used by dec8 freq cvt */ + if (reduction_code < 0) + reduction_code = 0; + if (reduction_code > 2) + reduction_code = 2; + if (freq_limit < 1000) + freq_limit = 1000; + + samprate = sr_table[4 * h->id + h->sr_index]; + if ((h->sync & 1) == 0) + samprate = samprate / 2; // mpeg 2.5 + /*----- compute pMP3Stream->nsb_limit --------*/ + pMP3Stream->nsb_limit = (freq_limit * 64L + samprate / 2) / samprate; + /*- caller limit -*/ + limit = (32 >> reduction_code); + if (limit > 8) + limit--; + if (pMP3Stream->nsb_limit > limit) + pMP3Stream->nsb_limit = limit; + limit = 18 * pMP3Stream->nsb_limit; + + k = h->id; + if ((h->sync & 1) == 0) + k = 2; // mpeg 2.5 + + if (k == 1) { + pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[13]; + pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[22]; + } else { + pMP3Stream->band_limit12 = 3 * sfBandIndexTable[k][h->sr_index].s[12]; + pMP3Stream->band_limit = pMP3Stream->band_limit21 = sfBandIndexTable[k][h->sr_index].l[21]; + } + pMP3Stream->band_limit += 8; /* allow for antialias */ + if (pMP3Stream->band_limit > limit) + pMP3Stream->band_limit = limit; + + if (pMP3Stream->band_limit21 > pMP3Stream->band_limit) + pMP3Stream->band_limit21 = pMP3Stream->band_limit; + if (pMP3Stream->band_limit12 > pMP3Stream->band_limit) + pMP3Stream->band_limit12 = pMP3Stream->band_limit; + + pMP3Stream->band_limit_nsb = (pMP3Stream->band_limit + 17) / 18; /* limit nsb's rounded up */ + /*----------------------------------------------*/ + pMP3Stream->gain_adjust = 0; /* adjust gain e.g. cvt to mono sum channel */ + if ((h->mode != 3) && (convert_code == 1)) + pMP3Stream->gain_adjust = -4; + + pMP3Stream->outvalues = 1152 >> reduction_code; + if (h->id == 0) + pMP3Stream->outvalues /= 2; + + out_chans = 2; + if (h->mode == 3) + out_chans = 1; + if (convert_code) + out_chans = 1; + + pMP3Stream->sbt_L3 = sbt_table[bit_code][reduction_code][out_chans - 1]; + k = 1 + convert_code; + if (h->mode == 3) + k = 0; + pMP3Stream->Xform = xform_table[k]; + + pMP3Stream->outvalues *= out_chans; + + if (bit_code) + pMP3Stream->outbytes = pMP3Stream->outvalues; + else + pMP3Stream->outbytes = sizeof(short) * pMP3Stream->outvalues; + + if (bit_code) + pMP3Stream->zero_level_pcm = 128; /* 8 bit output */ + else + pMP3Stream->zero_level_pcm = 0; + + decinfo.channels = out_chans; + decinfo.outvalues = pMP3Stream->outvalues; + decinfo.samprate = samprate >> reduction_code; + if (bit_code) + decinfo.bits = 8; + else + decinfo.bits = sizeof(short) * 8; + + decinfo.framebytes = pMP3Stream->framebytes; + decinfo.type = 0; + + pMP3Stream->half_outbytes = pMP3Stream->outbytes / 2; + /*------------------------------------------*/ + + /*- init band tables --*/ + + k = h->id; + if ((h->sync & 1) == 0) + k = 2; // mpeg 2.5 + + for (i = 0; i < 22; i++) + pMP3Stream->sfBandIndex[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1]; + for (i = 0; i < 13; i++) + pMP3Stream->sfBandIndex[1][i] = 3 * sfBandIndexTable[k][h->sr_index].s[i + 1]; + for (i = 0; i < 22; i++) + pMP3Stream->nBand[0][i] = sfBandIndexTable[k][h->sr_index].l[i + 1] - sfBandIndexTable[k][h->sr_index].l[i]; + for (i = 0; i < 13; i++) + pMP3Stream->nBand[1][i] = sfBandIndexTable[k][h->sr_index].s[i + 1] - sfBandIndexTable[k][h->sr_index].s[i]; + + /* init tables */ + L3table_init(); + /* init ms and is stereo modes */ + msis_init(); + + /*----- init sbt ---*/ + sbt_init(); + + /*--- clear buffers --*/ + for (i = 0; i < 576; i++) + yout[i] = 0.0f; + for (j = 0; j < 2; j++) { + for (k = 0; k < 2; k++) { + for (i = 0; i < 576; i++) { + pMP3Stream->sample[j][k][i].x = 0.0f; + pMP3Stream->sample[j][k][i].s = 0; + } + } + } - if (h->id == 1) - pMP3Stream->decode_function = L3audio_decode_MPEG1; - else - pMP3Stream->decode_function = L3audio_decode_MPEG2; + if (h->id == 1) + pMP3Stream->decode_function = L3audio_decode_MPEG1; + else + pMP3Stream->decode_function = L3audio_decode_MPEG2; - return 1; + return 1; } /*---------------------------------------------------------*/ /*==========================================================*/ diff --git a/codemp/mp3code/cwin.c b/codemp/mp3code/cwin.c index b1714055de..633fb9b2f6 100644 --- a/codemp/mp3code/cwin.c +++ b/codemp/mp3code/cwin.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,433 +37,395 @@ portable C #include "config.h" /*-------------------------------------------------------------------------*/ -void window(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } - - /*------------------------------------------------------------*/ -void window_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; /* dual window interleaves output */ - int si, bx; - const float *coef; - float sum; - long tmp; +void window_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; /* dual window interleaves output */ + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ -void window16(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void window16(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ -void window16_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void window16_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------- 8 pt window ------------------------------*/ -void window8(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window8(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = (short)tmp; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = (short)tmp; + } } /*--------------- 8 pt dual window (interleaved output) -----------------*/ -void window8_dual(float *vbuf, int vb_ptr, short *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void window8_dual(float *vbuf, int vb_ptr, short *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = (short)tmp; - pcm += 2; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = (short)tmp; + pcm += 2; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/cwinb.c b/codemp/mp3code/cwinb.c index 2b78f1e43b..a4604401ce 100644 --- a/codemp/mp3code/cwinb.c +++ b/codemp/mp3code/cwinb.c @@ -3,8 +3,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -35,430 +35,394 @@ portable C ******************************************************************/ /*-------------------------------------------------------------------------*/ -void windowB(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*------------------------------------------------------------*/ -void windowB_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; /* dual window interleaves output */ - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; /* dual window interleaves output */ + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 16; - bx = (si + 32) & 511; - coef = wincoef; + si = vb_ptr + 16; + bx = (si + 32) & 511; + coef = wincoef; -/*-- first 16 --*/ - for (i = 0; i < 16; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 64) & 511; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - si++; - bx--; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 15 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 15; i++) - { - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 64) & 511; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 64) & 511; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 16 --*/ + for (i = 0; i < 16; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 64) & 511; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + si++; + bx--; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 15 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 15; i++) { + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 64) & 511; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 64) & 511; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------------------------------------------------*/ /*------------------- 16 pt window ------------------------------*/ -void windowB16(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void windowB16(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*--------------- 16 pt dual window (interleaved output) -----------------*/ -void windowB16_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - unsigned char si, bx; - const float *coef; - float sum; - long tmp; +void windowB16_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + unsigned char si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 8; - bx = si + 16; - coef = wincoef; + si = vb_ptr + 8; + bx = si + 16; + coef = wincoef; -/*-- first 8 --*/ - for (i = 0; i < 8; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si += 32; - sum -= (*coef++) * vbuf[bx]; - bx += 32; - } - si++; - bx--; - coef += 16; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 7 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 7; i++) - { - coef -= 16; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si += 32; - sum += (*coef--) * vbuf[bx]; - bx += 32; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 8 --*/ + for (i = 0; i < 8; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si += 32; + sum -= (*coef++) * vbuf[bx]; + bx += 32; + } + si++; + bx--; + coef += 16; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 7 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 7; i++) { + coef -= 16; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si += 32; + sum += (*coef--) * vbuf[bx]; + bx += 32; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------- 8 pt window ------------------------------*/ -void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB8(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm++ = ((unsigned char) (tmp >> 8)) ^ 0x80; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm++ = ((unsigned char)(tmp >> 8)) ^ 0x80; + } } /*--------------- 8 pt dual window (interleaved output) -----------------*/ -void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm) -{ - int i, j; - int si, bx; - const float *coef; - float sum; - long tmp; +void windowB8_dual(float *vbuf, int vb_ptr, unsigned char *pcm) { + int i, j; + int si, bx; + const float *coef; + float sum; + long tmp; - si = vb_ptr + 4; - bx = (si + 8) & 127; - coef = wincoef; + si = vb_ptr + 4; + bx = (si + 8) & 127; + coef = wincoef; -/*-- first 4 --*/ - for (i = 0; i < 4; i++) - { - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[si]; - si = (si + 16) & 127; - sum -= (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - si++; - bx--; - coef += 48; - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } -/*-- special case --*/ - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef++) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; -/*-- last 3 --*/ - coef = wincoef + 255; /* back pass through coefs */ - for (i = 0; i < 3; i++) - { - coef -= 48; - si--; - bx++; - sum = 0.0F; - for (j = 0; j < 8; j++) - { - sum += (*coef--) * vbuf[si]; - si = (si + 16) & 127; - sum += (*coef--) * vbuf[bx]; - bx = (bx + 16) & 127; - } - tmp = (long) sum; - if (tmp > 32767) - tmp = 32767; - else if (tmp < -32768) - tmp = -32768; - *pcm = ((unsigned char) (tmp >> 8)) ^ 0x80; - pcm += 2; - } + /*-- first 4 --*/ + for (i = 0; i < 4; i++) { + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[si]; + si = (si + 16) & 127; + sum -= (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + si++; + bx--; + coef += 48; + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } + /*-- special case --*/ + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef++) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + /*-- last 3 --*/ + coef = wincoef + 255; /* back pass through coefs */ + for (i = 0; i < 3; i++) { + coef -= 48; + si--; + bx++; + sum = 0.0F; + for (j = 0; j < 8; j++) { + sum += (*coef--) * vbuf[si]; + si = (si + 16) & 127; + sum += (*coef--) * vbuf[bx]; + bx = (bx + 16) & 127; + } + tmp = (long)sum; + if (tmp > 32767) + tmp = 32767; + else if (tmp < -32768) + tmp = -32768; + *pcm = ((unsigned char)(tmp >> 8)) ^ 0x80; + pcm += 2; + } } /*------------------------------------------------------------*/ -#endif // #ifdef COMPILE_ME +#endif // #ifdef COMPILE_ME diff --git a/codemp/mp3code/cwinm.c b/codemp/mp3code/cwinm.c index d1a292e11f..345003bdb0 100644 --- a/codemp/mp3code/cwinm.c +++ b/codemp/mp3code/cwinm.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -37,8 +37,8 @@ portable C #include #include -const float wincoef[264] = -{ /* window coefs */ +const float wincoef[264] = { + /* window coefs */ #include "tableawd.h" }; diff --git a/codemp/mp3code/hwin.c b/codemp/mp3code/hwin.c index 8f04280c15..f0fb8e18e7 100644 --- a/codemp/mp3code/hwin.c +++ b/codemp/mp3code/hwin.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -42,223 +42,188 @@ hybrid window/filter typedef float ARRAY36[36]; /*-- windows by block type --*/ -static float win[4][36]; // effectively a constant - +static float win[4][36]; // effectively a constant /*====================================================================*/ -void imdct18(float f[]); /* 18 point */ -void imdct6_3(float f[]); /* 6 point */ +void imdct18(float f[]); /* 18 point */ +void imdct6_3(float f[]); /* 6 point */ /*====================================================================*/ -ARRAY36 *hwin_init_addr() -{ - return win; -} - +ARRAY36 *hwin_init_addr() { return win; } /*====================================================================*/ -int hybrid(float xin[], float xprev[], float y[18][32], - int btype, int nlong, int ntot, int nprev) -{ - int i, j; - float *x, *x0; - float xa, xb; - int n; - int nout; - - - - if (btype == 2) - btype = 0; - x = xin; - x0 = xprev; - -/*-- do long blocks (if any) --*/ - n = (nlong + 17) / 18; /* number of dct's to do */ - for (i = 0; i < n; i++) - { - imdct18(x); - for (j = 0; j < 9; j++) - { - y[j][i] = x0[j] + win[btype][j] * x[9 + j]; - y[9 + j][i] = x0[9 + j] + win[btype][9 + j] * x[17 - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 4; j++) - { - xa = x[j]; - xb = x[8 - j]; - x[j] = win[btype][18 + j] * xb; - x[8 - j] = win[btype][(18 + 8) - j] * xa; - x[9 + j] = win[btype][(18 + 9) + j] * xa; - x[17 - j] = win[btype][(18 + 17) - j] * xb; - } - xa = x[j]; - x[j] = win[btype][18 + j] * xa; - x[9 + j] = win[btype][(18 + 9) + j] * xa; - - x += 18; - x0 += 18; - } - -/*-- do short blocks (if any) --*/ - n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ - for (; i < n; i++) - { - imdct6_3(x); - for (j = 0; j < 3; j++) - { - y[j][i] = x0[j]; - y[3 + j][i] = x0[3 + j]; - - y[6 + j][i] = x0[6 + j] + win[2][j] * x[3 + j]; - y[9 + j][i] = x0[9 + j] + win[2][3 + j] * x[5 - j]; - - y[12 + j][i] = x0[12 + j] + win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; - y[15 + j][i] = x0[15 + j] + win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 3; j++) - { - x[j] = win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; - x[3 + j] = win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; - } - for (j = 0; j < 3; j++) - { - x[6 + j] = win[2][6 + j] * x[(12 + 2) - j]; - x[9 + j] = win[2][9 + j] * x[12 + j]; - } - for (j = 0; j < 3; j++) - { - x[12 + j] = 0.0f; - x[15 + j] = 0.0f; - } - x += 18; - x0 += 18; - } - -/*--- overlap prev if prev longer that current --*/ - n = (nprev + 17) / 18; - for (; i < n; i++) - { - for (j = 0; j < 18; j++) - y[j][i] = x0[j]; - x0 += 18; - } - nout = 18 * i; - -/*--- clear remaining only to band limit --*/ - for (; i < pMP3Stream->band_limit_nsb; i++) - { - for (j = 0; j < 18; j++) - y[j][i] = 0.0f; - } - - return nout; +int hybrid(float xin[], float xprev[], float y[18][32], int btype, int nlong, int ntot, int nprev) { + int i, j; + float *x, *x0; + float xa, xb; + int n; + int nout; + + if (btype == 2) + btype = 0; + x = xin; + x0 = xprev; + + /*-- do long blocks (if any) --*/ + n = (nlong + 17) / 18; /* number of dct's to do */ + for (i = 0; i < n; i++) { + imdct18(x); + for (j = 0; j < 9; j++) { + y[j][i] = x0[j] + win[btype][j] * x[9 + j]; + y[9 + j][i] = x0[9 + j] + win[btype][9 + j] * x[17 - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 4; j++) { + xa = x[j]; + xb = x[8 - j]; + x[j] = win[btype][18 + j] * xb; + x[8 - j] = win[btype][(18 + 8) - j] * xa; + x[9 + j] = win[btype][(18 + 9) + j] * xa; + x[17 - j] = win[btype][(18 + 17) - j] * xb; + } + xa = x[j]; + x[j] = win[btype][18 + j] * xa; + x[9 + j] = win[btype][(18 + 9) + j] * xa; + + x += 18; + x0 += 18; + } + + /*-- do short blocks (if any) --*/ + n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ + for (; i < n; i++) { + imdct6_3(x); + for (j = 0; j < 3; j++) { + y[j][i] = x0[j]; + y[3 + j][i] = x0[3 + j]; + + y[6 + j][i] = x0[6 + j] + win[2][j] * x[3 + j]; + y[9 + j][i] = x0[9 + j] + win[2][3 + j] * x[5 - j]; + + y[12 + j][i] = x0[12 + j] + win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; + y[15 + j][i] = x0[15 + j] + win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 3; j++) { + x[j] = win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; + x[3 + j] = win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; + } + for (j = 0; j < 3; j++) { + x[6 + j] = win[2][6 + j] * x[(12 + 2) - j]; + x[9 + j] = win[2][9 + j] * x[12 + j]; + } + for (j = 0; j < 3; j++) { + x[12 + j] = 0.0f; + x[15 + j] = 0.0f; + } + x += 18; + x0 += 18; + } + + /*--- overlap prev if prev longer that current --*/ + n = (nprev + 17) / 18; + for (; i < n; i++) { + for (j = 0; j < 18; j++) + y[j][i] = x0[j]; + x0 += 18; + } + nout = 18 * i; + + /*--- clear remaining only to band limit --*/ + for (; i < pMP3Stream->band_limit_nsb; i++) { + for (j = 0; j < 18; j++) + y[j][i] = 0.0f; + } + + return nout; } - /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*-- convert to mono, add curr result to y, - window and add next time to current left */ -int hybrid_sum(float xin[], float xin_left[], float y[18][32], - int btype, int nlong, int ntot) -{ - int i, j; - float *x, *x0; - float xa, xb; - int n; - int nout; - - - - if (btype == 2) - btype = 0; - x = xin; - x0 = xin_left; - -/*-- do long blocks (if any) --*/ - n = (nlong + 17) / 18; /* number of dct's to do */ - for (i = 0; i < n; i++) - { - imdct18(x); - for (j = 0; j < 9; j++) - { - y[j][i] += win[btype][j] * x[9 + j]; - y[9 + j][i] += win[btype][9 + j] * x[17 - j]; - } - /* window x for next time x0 */ - for (j = 0; j < 4; j++) - { - xa = x[j]; - xb = x[8 - j]; - x0[j] += win[btype][18 + j] * xb; - x0[8 - j] += win[btype][(18 + 8) - j] * xa; - x0[9 + j] += win[btype][(18 + 9) + j] * xa; - x0[17 - j] += win[btype][(18 + 17) - j] * xb; - } - xa = x[j]; - x0[j] += win[btype][18 + j] * xa; - x0[9 + j] += win[btype][(18 + 9) + j] * xa; - - x += 18; - x0 += 18; - } - -/*-- do short blocks (if any) --*/ - n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ - for (; i < n; i++) - { - imdct6_3(x); - for (j = 0; j < 3; j++) - { - y[6 + j][i] += win[2][j] * x[3 + j]; - y[9 + j][i] += win[2][3 + j] * x[5 - j]; - - y[12 + j][i] += win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; - y[15 + j][i] += win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; - } - /* window x for next time */ - for (j = 0; j < 3; j++) - { - x0[j] += win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; - x0[3 + j] += win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; - } - for (j = 0; j < 3; j++) - { - x0[6 + j] += win[2][6 + j] * x[(12 + 2) - j]; - x0[9 + j] += win[2][9 + j] * x[12 + j]; - } - x += 18; - x0 += 18; - } - - nout = 18 * i; - - return nout; + window and add next time to current left */ +int hybrid_sum(float xin[], float xin_left[], float y[18][32], int btype, int nlong, int ntot) { + int i, j; + float *x, *x0; + float xa, xb; + int n; + int nout; + + if (btype == 2) + btype = 0; + x = xin; + x0 = xin_left; + + /*-- do long blocks (if any) --*/ + n = (nlong + 17) / 18; /* number of dct's to do */ + for (i = 0; i < n; i++) { + imdct18(x); + for (j = 0; j < 9; j++) { + y[j][i] += win[btype][j] * x[9 + j]; + y[9 + j][i] += win[btype][9 + j] * x[17 - j]; + } + /* window x for next time x0 */ + for (j = 0; j < 4; j++) { + xa = x[j]; + xb = x[8 - j]; + x0[j] += win[btype][18 + j] * xb; + x0[8 - j] += win[btype][(18 + 8) - j] * xa; + x0[9 + j] += win[btype][(18 + 9) + j] * xa; + x0[17 - j] += win[btype][(18 + 17) - j] * xb; + } + xa = x[j]; + x0[j] += win[btype][18 + j] * xa; + x0[9 + j] += win[btype][(18 + 9) + j] * xa; + + x += 18; + x0 += 18; + } + + /*-- do short blocks (if any) --*/ + n = (ntot + 17) / 18; /* number of 6 pt dct's triples to do */ + for (; i < n; i++) { + imdct6_3(x); + for (j = 0; j < 3; j++) { + y[6 + j][i] += win[2][j] * x[3 + j]; + y[9 + j][i] += win[2][3 + j] * x[5 - j]; + + y[12 + j][i] += win[2][6 + j] * x[2 - j] + win[2][j] * x[(6 + 3) + j]; + y[15 + j][i] += win[2][9 + j] * x[j] + win[2][3 + j] * x[(6 + 5) - j]; + } + /* window x for next time */ + for (j = 0; j < 3; j++) { + x0[j] += win[2][6 + j] * x[(6 + 2) - j] + win[2][j] * x[(12 + 3) + j]; + x0[3 + j] += win[2][9 + j] * x[6 + j] + win[2][3 + j] * x[(12 + 5) - j]; + } + for (j = 0; j < 3; j++) { + x0[6 + j] += win[2][6 + j] * x[(12 + 2) - j]; + x0[9 + j] += win[2][9 + j] * x[12 + j]; + } + x += 18; + x0 += 18; + } + + nout = 18 * i; + + return nout; } /*--------------------------------------------------------------------*/ -void sum_f_bands(float a[], float b[], int n) -{ - int i; +void sum_f_bands(float a[], float b[], int n) { + int i; - for (i = 0; i < n; i++) - a[i] += b[i]; + for (i = 0; i < n; i++) + a[i] += b[i]; } /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ -void FreqInvert(float y[18][32], int n) -{ - int i, j; - - n = (n + 17) / 18; - for (j = 0; j < 18; j += 2) - { - for (i = 0; i < n; i += 2) - { - y[1 + j][1 + i] = -y[1 + j][1 + i]; - } - } +void FreqInvert(float y[18][32], int n) { + int i, j; + + n = (n + 17) / 18; + for (j = 0; j < 18; j += 2) { + for (i = 0; i < n; i += 2) { + y[1 + j][1 + i] = -y[1 + j][1 + i]; + } + } } /*--------------------------------------------------------------------*/ diff --git a/codemp/mp3code/l3dq.c b/codemp/mp3code/l3dq.c index a5a56d3bc6..a616650d36 100644 --- a/codemp/mp3code/l3dq.c +++ b/codemp/mp3code/l3dq.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -55,200 +55,166 @@ int s[14];} sfBandTable[3] = ----------*/ /*--------------------------------*/ -static const int pretab[2][22] = -{ - {0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 2, 2, 3, 3, 3, 2, 0}, +static const int pretab[2][22] = { + {0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 2, 2, 3, 3, 3, 2, 0}, }; - ////@@@@extern int nBand[2][22]; /* long = nBand[0][i], short = nBand[1][i] */ /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ /* two extra slots to do 1/sqrt(2) scaling for ms */ /* 4 extra slots to do 1/2 scaling for cvt to mono */ -static float look_global[256 + 2 + 4]; // effectively constant +static float look_global[256 + 2 + 4]; // effectively constant /*-------- scaling lookup x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) look_scale[scalefact_scale][preemp][scalefac] -----------------------*/ -static float look_scale[2][4][32]; // effectively constant +static float look_scale[2][4][32]; // effectively constant typedef float LS[4][32]; - /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ #define ISMAX 32 -static float look_pow[2 * ISMAX]; // effectively constant +static float look_pow[2 * ISMAX]; // effectively constant /*-- pow(2.0, -0.25*8.0*subblock_gain) --*/ -static float look_subblock[8]; // effectively constant +static float look_subblock[8]; // effectively constant /*-- reorder buffer ---*/ -static float re_buf[192][3]; // used by dequant() below, but only during func (as workspace) +static float re_buf[192][3]; // used by dequant() below, but only during func (as workspace) typedef float ARRAY3[3]; - /*=============================================================*/ -float *quant_init_global_addr() -{ - return look_global; -} +float *quant_init_global_addr() { return look_global; } /*-------------------------------------------------------------*/ -LS *quant_init_scale_addr() -{ - return look_scale; -} +LS *quant_init_scale_addr() { return look_scale; } /*-------------------------------------------------------------*/ -float *quant_init_pow_addr() -{ - return look_pow; -} +float *quant_init_pow_addr() { return look_pow; } /*-------------------------------------------------------------*/ -float *quant_init_subblock_addr() -{ - return look_subblock; -} +float *quant_init_subblock_addr() { return look_subblock; } /*=============================================================*/ -void dequant(SAMPLE Sample[], int *nsamp, - SCALEFACT * sf, - GR * gr, - CB_INFO * cb_info, int ncbl_mixed) -{ - int i, j; - int cb, n, w; - float x0, xs; - float xsb[3]; - double tmp; - int ncbl; - int cbs0; - ARRAY3 *buf; /* short block reorder */ - int nbands; - int i0; - int non_zero; - int cbmax[3]; - - nbands = *nsamp; - - - ncbl = 22; /* long block cb end */ - cbs0 = 12; /* short block cb start */ -/* ncbl_mixed = 8 or 6 mpeg1 or 2 */ - if (gr->block_type == 2) - { - ncbl = 0; - cbs0 = 0; - if (gr->mixed_block_flag) - { - ncbl = ncbl_mixed; - cbs0 = 3; - } - } -/* fill in cb_info -- */ - /* This doesn't seem used anywhere... - cb_info->lb_type = gr->block_type; - if (gr->block_type == 2) - cb_info->lb_type; - */ - cb_info->cbs0 = cbs0; - cb_info->ncbl = ncbl; - - cbmax[2] = cbmax[1] = cbmax[0] = 0; -/* global gain pre-adjusted by 2 if ms_mode, 0 otherwise */ - x0 = look_global[(2 + 4) + gr->global_gain]; - i = 0; -/*----- long blocks ---*/ - for (cb = 0; cb < ncbl; cb++) - { - non_zero = 0; - xs = x0 * look_scale[gr->scalefac_scale][pretab[gr->preflag][cb]][sf->l[cb]]; - n = pMP3Stream->nBand[0][cb]; - for (j = 0; j < n; j++, i++) - { - if (Sample[i].s == 0) - Sample[i].x = 0.0F; - else - { - non_zero = 1; - if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) - Sample[i].x = xs * look_pow[ISMAX + Sample[i].s]; - else - { - float tmpConst = (float)(1.0/3.0); - tmp = (double) Sample[i].s; - Sample[i].x = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); - } - } - } - if (non_zero) - cbmax[0] = cb; - if (i >= nbands) - break; - } - - cb_info->cbmax = cbmax[0]; - cb_info->cbtype = 0; // type = long - - if (cbs0 >= 12) - return; -/*--------------------------- -block type = 2 short blocks -----------------------------*/ - cbmax[2] = cbmax[1] = cbmax[0] = cbs0; - i0 = i; /* save for reorder */ - buf = re_buf; - for (w = 0; w < 3; w++) - xsb[w] = x0 * look_subblock[gr->subblock_gain[w]]; - for (cb = cbs0; cb < 13; cb++) - { - n = pMP3Stream->nBand[1][cb]; - for (w = 0; w < 3; w++) - { - non_zero = 0; - xs = xsb[w] * look_scale[gr->scalefac_scale][0][sf->s[w][cb]]; - for (j = 0; j < n; j++, i++) - { - if (Sample[i].s == 0) - buf[j][w] = 0.0F; - else - { - non_zero = 1; - if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) - buf[j][w] = xs * look_pow[ISMAX + Sample[i].s]; - else - { - float tmpConst = (float)(1.0/3.0); - tmp = (double) Sample[i].s; - buf[j][w] = (float) (xs * tmp * pow(fabs(tmp), tmpConst)); - } - } - } - if (non_zero) - cbmax[w] = cb; - } - if (i >= nbands) - break; - buf += n; - } - - - memmove(&Sample[i0].x, &re_buf[0][0], sizeof(float) * (i - i0)); - - *nsamp = i; /* update nsamp */ - cb_info->cbmax_s[0] = cbmax[0]; - cb_info->cbmax_s[1] = cbmax[1]; - cb_info->cbmax_s[2] = cbmax[2]; - if (cbmax[1] > cbmax[0]) - cbmax[0] = cbmax[1]; - if (cbmax[2] > cbmax[0]) - cbmax[0] = cbmax[2]; - - cb_info->cbmax = cbmax[0]; - cb_info->cbtype = 1; /* type = short */ - - - return; +void dequant(SAMPLE Sample[], int *nsamp, SCALEFACT *sf, GR *gr, CB_INFO *cb_info, int ncbl_mixed) { + int i, j; + int cb, n, w; + float x0, xs; + float xsb[3]; + double tmp; + int ncbl; + int cbs0; + ARRAY3 *buf; /* short block reorder */ + int nbands; + int i0; + int non_zero; + int cbmax[3]; + + nbands = *nsamp; + + ncbl = 22; /* long block cb end */ + cbs0 = 12; /* short block cb start */ + /* ncbl_mixed = 8 or 6 mpeg1 or 2 */ + if (gr->block_type == 2) { + ncbl = 0; + cbs0 = 0; + if (gr->mixed_block_flag) { + ncbl = ncbl_mixed; + cbs0 = 3; + } + } + /* fill in cb_info -- */ + /* This doesn't seem used anywhere... + cb_info->lb_type = gr->block_type; + if (gr->block_type == 2) + cb_info->lb_type; + */ + cb_info->cbs0 = cbs0; + cb_info->ncbl = ncbl; + + cbmax[2] = cbmax[1] = cbmax[0] = 0; + /* global gain pre-adjusted by 2 if ms_mode, 0 otherwise */ + x0 = look_global[(2 + 4) + gr->global_gain]; + i = 0; + /*----- long blocks ---*/ + for (cb = 0; cb < ncbl; cb++) { + non_zero = 0; + xs = x0 * look_scale[gr->scalefac_scale][pretab[gr->preflag][cb]][sf->l[cb]]; + n = pMP3Stream->nBand[0][cb]; + for (j = 0; j < n; j++, i++) { + if (Sample[i].s == 0) + Sample[i].x = 0.0F; + else { + non_zero = 1; + if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) + Sample[i].x = xs * look_pow[ISMAX + Sample[i].s]; + else { + float tmpConst = (float)(1.0 / 3.0); + tmp = (double)Sample[i].s; + Sample[i].x = (float)(xs * tmp * pow(fabs(tmp), tmpConst)); + } + } + } + if (non_zero) + cbmax[0] = cb; + if (i >= nbands) + break; + } + + cb_info->cbmax = cbmax[0]; + cb_info->cbtype = 0; // type = long + + if (cbs0 >= 12) + return; + /*--------------------------- + block type = 2 short blocks + ----------------------------*/ + cbmax[2] = cbmax[1] = cbmax[0] = cbs0; + i0 = i; /* save for reorder */ + buf = re_buf; + for (w = 0; w < 3; w++) + xsb[w] = x0 * look_subblock[gr->subblock_gain[w]]; + for (cb = cbs0; cb < 13; cb++) { + n = pMP3Stream->nBand[1][cb]; + for (w = 0; w < 3; w++) { + non_zero = 0; + xs = xsb[w] * look_scale[gr->scalefac_scale][0][sf->s[w][cb]]; + for (j = 0; j < n; j++, i++) { + if (Sample[i].s == 0) + buf[j][w] = 0.0F; + else { + non_zero = 1; + if ((Sample[i].s >= (-ISMAX)) && (Sample[i].s < ISMAX)) + buf[j][w] = xs * look_pow[ISMAX + Sample[i].s]; + else { + float tmpConst = (float)(1.0 / 3.0); + tmp = (double)Sample[i].s; + buf[j][w] = (float)(xs * tmp * pow(fabs(tmp), tmpConst)); + } + } + } + if (non_zero) + cbmax[w] = cb; + } + if (i >= nbands) + break; + buf += n; + } + + memmove(&Sample[i0].x, &re_buf[0][0], sizeof(float) * (i - i0)); + + *nsamp = i; /* update nsamp */ + cb_info->cbmax_s[0] = cbmax[0]; + cb_info->cbmax_s[1] = cbmax[1]; + cb_info->cbmax_s[2] = cbmax[2]; + if (cbmax[1] > cbmax[0]) + cbmax[0] = cbmax[1]; + if (cbmax[2] > cbmax[0]) + cbmax[0] = cbmax[2]; + + cb_info->cbmax = cbmax[0]; + cb_info->cbtype = 1; /* type = short */ + + return; } /*-------------------------------------------------------------*/ diff --git a/codemp/mp3code/l3init.c b/codemp/mp3code/l3init.c index 174bb39deb..3a6af45a92 100644 --- a/codemp/mp3code/l3init.c +++ b/codemp/mp3code/l3init.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.com @@ -40,12 +40,10 @@ ____________________________________________________________________________*/ /* 8 bit lookup x = pow(2.0, 0.25*(global_gain-210)) */ float *quant_init_global_addr(); - /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ typedef float LS[4][32]; LS *quant_init_scale_addr(); - float *quant_init_pow_addr(); float *quant_init_subblock_addr(); @@ -56,169 +54,148 @@ iARRAY22 *quant_init_band_addr(); typedef float PAIR[2]; PAIR *alias_init_addr(); -static const float Ci[8] = -{ - -0.6f, -0.535f, -0.33f, -0.185f, -0.095f, -0.041f, -0.0142f, -0.0037f}; - +static const float Ci[8] = {-0.6f, -0.535f, -0.33f, -0.185f, -0.095f, -0.041f, -0.0142f, -0.0037f}; -void hwin_init(); /* hybrid windows -- */ +void hwin_init(); /* hybrid windows -- */ void imdct_init(); -typedef struct -{ - float *w; - float *w2; - void *coef; -} -IMDCT_INIT_BLOCK; +typedef struct { + float *w; + float *w2; + void *coef; +} IMDCT_INIT_BLOCK; void msis_init(); void msis_init_MPEG2(); /*=============================================================*/ -int L3table_init() -{ - int i; - float *x; - LS *ls; - int scalefact_scale, preemp, scalefac; - double tmp; - PAIR *csa; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { -/*================ quant ===============================*/ - - /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ - /* extra 2 for ms scaling by 1/sqrt(2) */ - /* extra 4 for cvt to mono scaling by 1/2 */ - x = quant_init_global_addr(); - for (i = 0; i < 256 + 2 + 4; i++) - x[i] = (float) pow(2.0, 0.25 * ((i - (2 + 4)) - 210 + GLOBAL_GAIN_SCALE)); - - - - /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ - ls = quant_init_scale_addr(); - for (scalefact_scale = 0; scalefact_scale < 2; scalefact_scale++) - { - for (preemp = 0; preemp < 4; preemp++) - { - for (scalefac = 0; scalefac < 32; scalefac++) - { - ls[scalefact_scale][preemp][scalefac] = - (float) pow(2.0, -0.5 * (1 + scalefact_scale) * (scalefac + preemp)); - } - } - } - - /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ - x = quant_init_pow_addr(); - for (i = 0; i < 64; i++) - { - tmp = i - 32; - x[i] = (float) (tmp * pow(fabs(tmp), (1.0 / 3.0))); - } - - - /*-- pow(2.0, -0.25*8.0*subblock_gain) 3 bits --*/ - x = quant_init_subblock_addr(); - for (i = 0; i < 8; i++) - { - x[i] = (float) pow(2.0, 0.25 * -8.0 * i); - } - - /*-------------------------*/ - // quant_init_sf_band(sr_index); replaced by code in sup.c - - -/*================ antialias ===============================*/ - // onceonly!!!!!!!!!!!!!!!!!!!!! - csa = alias_init_addr(); - for (i = 0; i < 8; i++) - { - csa[i][0] = (float) (1.0 / sqrt(1.0 + Ci[i] * Ci[i])); - csa[i][1] = (float) (Ci[i] / sqrt(1.0 + Ci[i] * Ci[i])); - } - } - - // these 4 are iOnceOnly-protected inside... - -/*================ msis ===============================*/ - msis_init(); - msis_init_MPEG2(); - -/*================ imdct ===============================*/ - imdct_init(); - -/*--- hybrid windows ------------*/ - hwin_init(); - - return 0; +int L3table_init() { + int i; + float *x; + LS *ls; + int scalefact_scale, preemp, scalefac; + double tmp; + PAIR *csa; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*================ quant ===============================*/ + + /* 8 bit plus 2 lookup x = pow(2.0, 0.25*(global_gain-210)) */ + /* extra 2 for ms scaling by 1/sqrt(2) */ + /* extra 4 for cvt to mono scaling by 1/2 */ + x = quant_init_global_addr(); + for (i = 0; i < 256 + 2 + 4; i++) + x[i] = (float)pow(2.0, 0.25 * ((i - (2 + 4)) - 210 + GLOBAL_GAIN_SCALE)); + + /* x = pow(2.0, -0.5*(1+scalefact_scale)*scalefac + preemp) */ + ls = quant_init_scale_addr(); + for (scalefact_scale = 0; scalefact_scale < 2; scalefact_scale++) { + for (preemp = 0; preemp < 4; preemp++) { + for (scalefac = 0; scalefac < 32; scalefac++) { + ls[scalefact_scale][preemp][scalefac] = (float)pow(2.0, -0.5 * (1 + scalefact_scale) * (scalefac + preemp)); + } + } + } + + /*--- iSample**(4/3) lookup, -32<=i<=31 ---*/ + x = quant_init_pow_addr(); + for (i = 0; i < 64; i++) { + tmp = i - 32; + x[i] = (float)(tmp * pow(fabs(tmp), (1.0 / 3.0))); + } + + /*-- pow(2.0, -0.25*8.0*subblock_gain) 3 bits --*/ + x = quant_init_subblock_addr(); + for (i = 0; i < 8; i++) { + x[i] = (float)pow(2.0, 0.25 * -8.0 * i); + } + + /*-------------------------*/ + // quant_init_sf_band(sr_index); replaced by code in sup.c + + /*================ antialias ===============================*/ + // onceonly!!!!!!!!!!!!!!!!!!!!! + csa = alias_init_addr(); + for (i = 0; i < 8; i++) { + csa[i][0] = (float)(1.0 / sqrt(1.0 + Ci[i] * Ci[i])); + csa[i][1] = (float)(Ci[i] / sqrt(1.0 + Ci[i] * Ci[i])); + } + } + + // these 4 are iOnceOnly-protected inside... + + /*================ msis ===============================*/ + msis_init(); + msis_init_MPEG2(); + + /*================ imdct ===============================*/ + imdct_init(); + + /*--- hybrid windows ------------*/ + hwin_init(); + + return 0; } /*====================================================================*/ typedef float ARRAY36[36]; ARRAY36 *hwin_init_addr(); /*--------------------------------------------------------------------*/ -void hwin_init() -{ - int i, j; - double pi; - ARRAY36 *win; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - win = hwin_init_addr(); - - pi = 4.0 * atan(1.0); - - /* type 0 */ - for (i = 0; i < 36; i++) - win[0][i] = (float) sin(pi / 36 * (i + 0.5)); - - /* type 1 */ - for (i = 0; i < 18; i++) - win[1][i] = (float) sin(pi / 36 * (i + 0.5)); - for (i = 18; i < 24; i++) - win[1][i] = 1.0F; - for (i = 24; i < 30; i++) - win[1][i] = (float) sin(pi / 12 * (i + 0.5 - 18)); - for (i = 30; i < 36; i++) - win[1][i] = 0.0F; - - /* type 3 */ - for (i = 0; i < 6; i++) - win[3][i] = 0.0F; - for (i = 6; i < 12; i++) - win[3][i] = (float) sin(pi / 12 * (i + 0.5 - 6)); - for (i = 12; i < 18; i++) - win[3][i] = 1.0F; - for (i = 18; i < 36; i++) - win[3][i] = (float) sin(pi / 36 * (i + 0.5)); - - /* type 2 */ - for (i = 0; i < 12; i++) - win[2][i] = (float) sin(pi / 12 * (i + 0.5)); - for (i = 12; i < 36; i++) - win[2][i] = 0.0F; - - /*--- invert signs by region to match mdct 18pt --> 36pt mapping */ - for (j = 0; j < 4; j++) - { - if (j == 2) - continue; - for (i = 9; i < 36; i++) - win[j][i] = -win[j][i]; - } - - /*-- invert signs for short blocks --*/ - for (i = 3; i < 12; i++) - win[2][i] = -win[2][i]; - } +void hwin_init() { + int i, j; + double pi; + ARRAY36 *win; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + win = hwin_init_addr(); + + pi = 4.0 * atan(1.0); + + /* type 0 */ + for (i = 0; i < 36; i++) + win[0][i] = (float)sin(pi / 36 * (i + 0.5)); + + /* type 1 */ + for (i = 0; i < 18; i++) + win[1][i] = (float)sin(pi / 36 * (i + 0.5)); + for (i = 18; i < 24; i++) + win[1][i] = 1.0F; + for (i = 24; i < 30; i++) + win[1][i] = (float)sin(pi / 12 * (i + 0.5 - 18)); + for (i = 30; i < 36; i++) + win[1][i] = 0.0F; + + /* type 3 */ + for (i = 0; i < 6; i++) + win[3][i] = 0.0F; + for (i = 6; i < 12; i++) + win[3][i] = (float)sin(pi / 12 * (i + 0.5 - 6)); + for (i = 12; i < 18; i++) + win[3][i] = 1.0F; + for (i = 18; i < 36; i++) + win[3][i] = (float)sin(pi / 36 * (i + 0.5)); + + /* type 2 */ + for (i = 0; i < 12; i++) + win[2][i] = (float)sin(pi / 12 * (i + 0.5)); + for (i = 12; i < 36; i++) + win[2][i] = 0.0F; + + /*--- invert signs by region to match mdct 18pt --> 36pt mapping */ + for (j = 0; j < 4; j++) { + if (j == 2) + continue; + for (i = 9; i < 36; i++) + win[j][i] = -win[j][i]; + } + + /*-- invert signs for short blocks --*/ + for (i = 3; i < 12; i++) + win[2][i] = -win[2][i]; + } } /*=============================================================*/ typedef float ARRAY4[4]; @@ -226,115 +203,106 @@ const IMDCT_INIT_BLOCK *imdct_init_addr_18(); const IMDCT_INIT_BLOCK *imdct_init_addr_6(); /*-------------------------------------------------------------*/ -void imdct_init() -{ - int k, p, n; - double t, pi; - const IMDCT_INIT_BLOCK *addr; - float *w, *w2; - float *v, *v2, *coef87; - ARRAY4 *coef; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - /*--- 18 point --*/ - addr = imdct_init_addr_18(); - w = addr->w; - w2 = addr->w2; - coef = addr->coef; - /*----*/ - n = 18; - pi = 4.0 * atan(1.0); - t = pi / (4 * n); - for (p = 0; p < n; p++) - w[p] = (float) (2.0 * cos(t * (2 * p + 1))); - for (p = 0; p < 9; p++) - w2[p] = (float) (2.0 *cos(2 * t * (2 * p + 1))); - - t = pi / (2 * n); - for (k = 0; k < 9; k++) - { - for (p = 0; p < 4; p++) - coef[k][p] = (float) cos(t * (2 * k) * (2 * p + 1)); - } - - /*--- 6 point */ - addr = imdct_init_addr_6(); - v = addr->w; - v2 = addr->w2; - coef87 = addr->coef; - /*----*/ - n = 6; - pi = 4.0 * atan(1.0); - t = pi / (4 * n); - for (p = 0; p < n; p++) - v[p] = (float) (2.0 *cos(t * (2 * p + 1))); - - for (p = 0; p < 3; p++) - v2[p] = (float) (2.0 *cos(2 * t * (2 * p + 1))); - - t = pi / (2 * n); - k = 1; - p = 0; - *coef87 = (float) cos(t * (2 * k) * (2 * p + 1)); - /* adjust scaling to save a few mults */ - for (p = 0; p < 6; p++) - v[p] = v[p] / 2.0f; - *coef87 = (float) (2.0 *(*coef87)); - - } +void imdct_init() { + int k, p, n; + double t, pi; + const IMDCT_INIT_BLOCK *addr; + float *w, *w2; + float *v, *v2, *coef87; + ARRAY4 *coef; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + /*--- 18 point --*/ + addr = imdct_init_addr_18(); + w = addr->w; + w2 = addr->w2; + coef = addr->coef; + /*----*/ + n = 18; + pi = 4.0 * atan(1.0); + t = pi / (4 * n); + for (p = 0; p < n; p++) + w[p] = (float)(2.0 * cos(t * (2 * p + 1))); + for (p = 0; p < 9; p++) + w2[p] = (float)(2.0 * cos(2 * t * (2 * p + 1))); + + t = pi / (2 * n); + for (k = 0; k < 9; k++) { + for (p = 0; p < 4; p++) + coef[k][p] = (float)cos(t * (2 * k) * (2 * p + 1)); + } + + /*--- 6 point */ + addr = imdct_init_addr_6(); + v = addr->w; + v2 = addr->w2; + coef87 = addr->coef; + /*----*/ + n = 6; + pi = 4.0 * atan(1.0); + t = pi / (4 * n); + for (p = 0; p < n; p++) + v[p] = (float)(2.0 * cos(t * (2 * p + 1))); + + for (p = 0; p < 3; p++) + v2[p] = (float)(2.0 * cos(2 * t * (2 * p + 1))); + + t = pi / (2 * n); + k = 1; + p = 0; + *coef87 = (float)cos(t * (2 * k) * (2 * p + 1)); + /* adjust scaling to save a few mults */ + for (p = 0; p < 6; p++) + v[p] = v[p] / 2.0f; + *coef87 = (float)(2.0 * (*coef87)); + } } /*===============================================================*/ typedef float ARRAY8_2[8][2]; ARRAY8_2 *msis_init_addr(); /*-------------------------------------------------------------*/ -void msis_init() -{ - int i; - double s, c; - double pi; - double t; - ARRAY8_2 *lr; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - lr = msis_init_addr(); - - - pi = 4.0 * atan(1.0); - t = pi / 12.0; - for (i = 0; i < 7; i++) - { - s = sin(i * t); - c = cos(i * t); +void msis_init() { + int i; + double s, c; + double pi; + double t; + ARRAY8_2 *lr; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + lr = msis_init_addr(); + + pi = 4.0 * atan(1.0); + t = pi / 12.0; + for (i = 0; i < 7; i++) { + s = sin(i * t); + c = cos(i * t); + /* ms_mode = 0 */ + lr[0][i][0] = (float)(s / (s + c)); + lr[0][i][1] = (float)(c / (s + c)); + /* ms_mode = 1 */ + lr[1][i][0] = (float)(sqrt(2.0) * (s / (s + c))); + lr[1][i][1] = (float)(sqrt(2.0) * (c / (s + c))); + } + /* sf = 7 */ /* ms_mode = 0 */ - lr[0][i][0] = (float) (s / (s + c)); - lr[0][i][1] = (float) (c / (s + c)); - /* ms_mode = 1 */ - lr[1][i][0] = (float) (sqrt(2.0) * (s / (s + c))); - lr[1][i][1] = (float) (sqrt(2.0) * (c / (s + c))); - } - /* sf = 7 */ - /* ms_mode = 0 */ - lr[0][i][0] = 1.0f; - lr[0][i][1] = 0.0f; - /* ms_mode = 1, in is bands is routine does ms processing */ - lr[1][i][0] = 1.0f; - lr[1][i][1] = 1.0f; - - - /*------- - for(i=0;i<21;i++) nBand[0][i] = - sfBandTable[sr_index].l[i+1] - sfBandTable[sr_index].l[i]; - for(i=0;i<12;i++) nBand[1][i] = - sfBandTable[sr_index].s[i+1] - sfBandTable[sr_index].s[i]; - -------------*/ - } + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + /* ms_mode = 1, in is bands is routine does ms processing */ + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; + + /*------- + for(i=0;i<21;i++) nBand[0][i] = + sfBandTable[sr_index].l[i+1] - sfBandTable[sr_index].l[i]; + for(i=0;i<12;i++) nBand[1][i] = + sfBandTable[sr_index].s[i+1] - sfBandTable[sr_index].s[i]; + -------------*/ + } } /*-------------------------------------------------------------*/ /*===============================================================*/ @@ -342,75 +310,58 @@ typedef float ARRAY2_64_2[2][64][2]; ARRAY2_64_2 *msis_init_addr_MPEG2(); /*-------------------------------------------------------------*/ -void msis_init_MPEG2() -{ - int k, n; - double t; - ARRAY2_64_2 *lr2; - int intensity_scale, ms_mode, sf, sflen; - float ms_factor[2]; - - static int iOnceOnly = 0; - - if (!iOnceOnly++) - { - ms_factor[0] = 1.0; - ms_factor[1] = (float) sqrt(2.0); - - lr2 = msis_init_addr_MPEG2(); - - /* intensity stereo MPEG2 */ - /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ - - for (intensity_scale = 0; intensity_scale < 2; intensity_scale++) - { - t = pow(2.0, -0.25 * (1 + intensity_scale)); - for (ms_mode = 0; ms_mode < 2; ms_mode++) - { - - n = 1; - k = 0; - for (sflen = 0; sflen < 6; sflen++) - { - for (sf = 0; sf < (n - 1); sf++, k++) - { - if (sf == 0) - { - lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; - lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; - } - else if ((sf & 1)) - { - lr2[intensity_scale][ms_mode][k][0] = - (float) (ms_factor[ms_mode] * pow(t, (sf + 1) / 2)); - lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; - } - else - { - lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; - lr2[intensity_scale][ms_mode][k][1] = - (float) (ms_factor[ms_mode] * pow(t, sf / 2)); - } +void msis_init_MPEG2() { + int k, n; + double t; + ARRAY2_64_2 *lr2; + int intensity_scale, ms_mode, sf, sflen; + float ms_factor[2]; + + static int iOnceOnly = 0; + + if (!iOnceOnly++) { + ms_factor[0] = 1.0; + ms_factor[1] = (float)sqrt(2.0); + + lr2 = msis_init_addr_MPEG2(); + + /* intensity stereo MPEG2 */ + /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ + + for (intensity_scale = 0; intensity_scale < 2; intensity_scale++) { + t = pow(2.0, -0.25 * (1 + intensity_scale)); + for (ms_mode = 0; ms_mode < 2; ms_mode++) { + + n = 1; + k = 0; + for (sflen = 0; sflen < 6; sflen++) { + for (sf = 0; sf < (n - 1); sf++, k++) { + if (sf == 0) { + lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; + lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; + } else if ((sf & 1)) { + lr2[intensity_scale][ms_mode][k][0] = (float)(ms_factor[ms_mode] * pow(t, (sf + 1) / 2)); + lr2[intensity_scale][ms_mode][k][1] = ms_factor[ms_mode] * 1.0f; + } else { + lr2[intensity_scale][ms_mode][k][0] = ms_factor[ms_mode] * 1.0f; + lr2[intensity_scale][ms_mode][k][1] = (float)(ms_factor[ms_mode] * pow(t, sf / 2)); + } + } + + /* illegal is_pos used to do ms processing */ + if (ms_mode == 0) { /* ms_mode = 0 */ + lr2[intensity_scale][ms_mode][k][0] = 1.0f; + lr2[intensity_scale][ms_mode][k][1] = 0.0f; + } else { + /* ms_mode = 1, in is bands is routine does ms processing */ + lr2[intensity_scale][ms_mode][k][0] = 1.0f; + lr2[intensity_scale][ms_mode][k][1] = 1.0f; + } + k++; + n = n + n; + } } - - /* illegal is_pos used to do ms processing */ - if (ms_mode == 0) - { /* ms_mode = 0 */ - lr2[intensity_scale][ms_mode][k][0] = 1.0f; - lr2[intensity_scale][ms_mode][k][1] = 0.0f; - } - else - { - /* ms_mode = 1, in is bands is routine does ms processing */ - lr2[intensity_scale][ms_mode][k][0] = 1.0f; - lr2[intensity_scale][ms_mode][k][1] = 1.0f; - } - k++; - n = n + n; - } - } - } - } - + } + } } /*-------------------------------------------------------------*/ diff --git a/codemp/mp3code/mdct.c b/codemp/mp3code/mdct.c index 59b5d19bc9..e66e7303ce 100644 --- a/codemp/mp3code/mdct.c +++ b/codemp/mp3code/mdct.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -31,7 +31,7 @@ Layer III cos transform for n=18, n=6 computes c[k] = Sum( cos((pi/4*n)*(2*k+1)*(2*p+1))*f[p] ) - k = 0, ...n-1, p = 0...n-1 + k = 0, ...n-1, p = 0...n-1 inplace ok. @@ -43,187 +43,156 @@ inplace ok. #include #include - /*------ 18 point xform -------*/ -float mdct18w[18]; // effectively constant -float mdct18w2[9]; // " " -float coef[9][4]; // " " - -float mdct6_3v[6]; // " " -float mdct6_3v2[3]; // " " -float coef87; // " " - -typedef struct -{ - float *w; - float *w2; - void *coef; -} -IMDCT_INIT_BLOCK; +float mdct18w[18]; // effectively constant +float mdct18w2[9]; // " " +float coef[9][4]; // " " -static const IMDCT_INIT_BLOCK imdct_info_18 = -{mdct18w, mdct18w2, coef}; -static const IMDCT_INIT_BLOCK imdct_info_6 = -{mdct6_3v, mdct6_3v2, &coef87}; +float mdct6_3v[6]; // " " +float mdct6_3v2[3]; // " " +float coef87; // " " +typedef struct { + float *w; + float *w2; + void *coef; +} IMDCT_INIT_BLOCK; +static const IMDCT_INIT_BLOCK imdct_info_18 = {mdct18w, mdct18w2, coef}; +static const IMDCT_INIT_BLOCK imdct_info_6 = {mdct6_3v, mdct6_3v2, &coef87}; /*====================================================================*/ -const IMDCT_INIT_BLOCK *imdct_init_addr_18() -{ - return &imdct_info_18; -} -const IMDCT_INIT_BLOCK *imdct_init_addr_6() -{ - return &imdct_info_6; -} +const IMDCT_INIT_BLOCK *imdct_init_addr_18() { return &imdct_info_18; } +const IMDCT_INIT_BLOCK *imdct_init_addr_6() { return &imdct_info_6; } /*--------------------------------------------------------------------*/ -void imdct18(float f[18]) /* 18 point */ +void imdct18(float f[18]) /* 18 point */ { - int p; - float a[9], b[9]; - float ap, bp, a8p, b8p; - float g1, g2; - - - for (p = 0; p < 4; p++) - { - g1 = mdct18w[p] * f[p]; - g2 = mdct18w[17 - p] * f[17 - p]; - ap = g1 + g2; // a[p] - - bp = mdct18w2[p] * (g1 - g2); // b[p] - - g1 = mdct18w[8 - p] * f[8 - p]; - g2 = mdct18w[9 + p] * f[9 + p]; - a8p = g1 + g2; // a[8-p] - - b8p = mdct18w2[8 - p] * (g1 - g2); // b[8-p] - - a[p] = ap + a8p; - a[5 + p] = ap - a8p; - b[p] = bp + b8p; - b[5 + p] = bp - b8p; - } - g1 = mdct18w[p] * f[p]; - g2 = mdct18w[17 - p] * f[17 - p]; - a[p] = g1 + g2; - b[p] = mdct18w2[p] * (g1 - g2); - - - f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); - f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); - - f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] - + coef[1][3] * a[8]; - f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] - + coef[1][3] * b[8] - f[1]; - f[1] = f[1] - f[0]; - f[2] = f[2] - f[1]; - - f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] - + coef[2][3] * a[3] - a[4]; - f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] - + coef[2][3] * b[3] - b[4] - f[3]; - f[3] = f[3] - f[2]; - f[4] = f[4] - f[3]; - - f[6] = coef[3][0] * (a[5] - a[7] - a[8]); - f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; - f[5] = f[5] - f[4]; - f[6] = f[6] - f[5]; - - f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] - + coef[4][3] * a[3] + a[4]; - f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] - + coef[4][3] * b[3] + b[4] - f[7]; - f[7] = f[7] - f[6]; - f[8] = f[8] - f[7]; - - f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] - + coef[5][3] * a[8]; - f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] - + coef[5][3] * b[8] - f[9]; - f[9] = f[9] - f[8]; - f[10] = f[10] - f[9]; - - f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; - f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; - f[11] = f[11] - f[10]; - f[12] = f[12] - f[11]; - - f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] - + coef[7][3] * a[8]; - f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] - + coef[7][3] * b[8] - f[13]; - f[13] = f[13] - f[12]; - f[14] = f[14] - f[13]; - - f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] - + coef[8][3] * a[3] + a[4]; - f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] - + coef[8][3] * b[3] + b[4] - f[15]; - f[15] = f[15] - f[14]; - f[16] = f[16] - f[15]; - f[17] = f[17] - f[16]; - - - return; + int p; + float a[9], b[9]; + float ap, bp, a8p, b8p; + float g1, g2; + + for (p = 0; p < 4; p++) { + g1 = mdct18w[p] * f[p]; + g2 = mdct18w[17 - p] * f[17 - p]; + ap = g1 + g2; // a[p] + + bp = mdct18w2[p] * (g1 - g2); // b[p] + + g1 = mdct18w[8 - p] * f[8 - p]; + g2 = mdct18w[9 + p] * f[9 + p]; + a8p = g1 + g2; // a[8-p] + + b8p = mdct18w2[8 - p] * (g1 - g2); // b[8-p] + + a[p] = ap + a8p; + a[5 + p] = ap - a8p; + b[p] = bp + b8p; + b[5 + p] = bp - b8p; + } + g1 = mdct18w[p] * f[p]; + g2 = mdct18w[17 - p] * f[17 - p]; + a[p] = g1 + g2; + b[p] = mdct18w2[p] * (g1 - g2); + + f[0] = 0.5f * (a[0] + a[1] + a[2] + a[3] + a[4]); + f[1] = 0.5f * (b[0] + b[1] + b[2] + b[3] + b[4]); + + f[2] = coef[1][0] * a[5] + coef[1][1] * a[6] + coef[1][2] * a[7] + coef[1][3] * a[8]; + f[3] = coef[1][0] * b[5] + coef[1][1] * b[6] + coef[1][2] * b[7] + coef[1][3] * b[8] - f[1]; + f[1] = f[1] - f[0]; + f[2] = f[2] - f[1]; + + f[4] = coef[2][0] * a[0] + coef[2][1] * a[1] + coef[2][2] * a[2] + coef[2][3] * a[3] - a[4]; + f[5] = coef[2][0] * b[0] + coef[2][1] * b[1] + coef[2][2] * b[2] + coef[2][3] * b[3] - b[4] - f[3]; + f[3] = f[3] - f[2]; + f[4] = f[4] - f[3]; + + f[6] = coef[3][0] * (a[5] - a[7] - a[8]); + f[7] = coef[3][0] * (b[5] - b[7] - b[8]) - f[5]; + f[5] = f[5] - f[4]; + f[6] = f[6] - f[5]; + + f[8] = coef[4][0] * a[0] + coef[4][1] * a[1] + coef[4][2] * a[2] + coef[4][3] * a[3] + a[4]; + f[9] = coef[4][0] * b[0] + coef[4][1] * b[1] + coef[4][2] * b[2] + coef[4][3] * b[3] + b[4] - f[7]; + f[7] = f[7] - f[6]; + f[8] = f[8] - f[7]; + + f[10] = coef[5][0] * a[5] + coef[5][1] * a[6] + coef[5][2] * a[7] + coef[5][3] * a[8]; + f[11] = coef[5][0] * b[5] + coef[5][1] * b[6] + coef[5][2] * b[7] + coef[5][3] * b[8] - f[9]; + f[9] = f[9] - f[8]; + f[10] = f[10] - f[9]; + + f[12] = 0.5f * (a[0] + a[2] + a[3]) - a[1] - a[4]; + f[13] = 0.5f * (b[0] + b[2] + b[3]) - b[1] - b[4] - f[11]; + f[11] = f[11] - f[10]; + f[12] = f[12] - f[11]; + + f[14] = coef[7][0] * a[5] + coef[7][1] * a[6] + coef[7][2] * a[7] + coef[7][3] * a[8]; + f[15] = coef[7][0] * b[5] + coef[7][1] * b[6] + coef[7][2] * b[7] + coef[7][3] * b[8] - f[13]; + f[13] = f[13] - f[12]; + f[14] = f[14] - f[13]; + + f[16] = coef[8][0] * a[0] + coef[8][1] * a[1] + coef[8][2] * a[2] + coef[8][3] * a[3] + a[4]; + f[17] = coef[8][0] * b[0] + coef[8][1] * b[1] + coef[8][2] * b[2] + coef[8][3] * b[3] + b[4] - f[15]; + f[15] = f[15] - f[14]; + f[16] = f[16] - f[15]; + f[17] = f[17] - f[16]; + + return; } /*--------------------------------------------------------------------*/ /* does 3, 6 pt dct. changes order from f[i][window] c[window][i] */ -void imdct6_3(float f[]) /* 6 point */ +void imdct6_3(float f[]) /* 6 point */ { - int w; - float buf[18]; - float *a, *c; // b[i] = a[3+i] - - float g1, g2; - float a02, b02; - - c = f; - a = buf; - for (w = 0; w < 3; w++) - { - g1 = mdct6_3v[0] * f[3 * 0]; - g2 = mdct6_3v[5] * f[3 * 5]; - a[0] = g1 + g2; - a[3 + 0] = mdct6_3v2[0] * (g1 - g2); - - g1 = mdct6_3v[1] * f[3 * 1]; - g2 = mdct6_3v[4] * f[3 * 4]; - a[1] = g1 + g2; - a[3 + 1] = mdct6_3v2[1] * (g1 - g2); - - g1 = mdct6_3v[2] * f[3 * 2]; - g2 = mdct6_3v[3] * f[3 * 3]; - a[2] = g1 + g2; - a[3 + 2] = mdct6_3v2[2] * (g1 - g2); - - a += 6; - f++; - } - - a = buf; - for (w = 0; w < 3; w++) - { - a02 = (a[0] + a[2]); - b02 = (a[3 + 0] + a[3 + 2]); - c[0] = a02 + a[1]; - c[1] = b02 + a[3 + 1]; - c[2] = coef87 * (a[0] - a[2]); - c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; - c[1] = c[1] - c[0]; - c[2] = c[2] - c[1]; - c[4] = a02 - a[1] - a[1]; - c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; - c[3] = c[3] - c[2]; - c[4] = c[4] - c[3]; - c[5] = c[5] - c[4]; - a += 6; - c += 6; - } - - return; + int w; + float buf[18]; + float *a, *c; // b[i] = a[3+i] + + float g1, g2; + float a02, b02; + + c = f; + a = buf; + for (w = 0; w < 3; w++) { + g1 = mdct6_3v[0] * f[3 * 0]; + g2 = mdct6_3v[5] * f[3 * 5]; + a[0] = g1 + g2; + a[3 + 0] = mdct6_3v2[0] * (g1 - g2); + + g1 = mdct6_3v[1] * f[3 * 1]; + g2 = mdct6_3v[4] * f[3 * 4]; + a[1] = g1 + g2; + a[3 + 1] = mdct6_3v2[1] * (g1 - g2); + + g1 = mdct6_3v[2] * f[3 * 2]; + g2 = mdct6_3v[3] * f[3 * 3]; + a[2] = g1 + g2; + a[3 + 2] = mdct6_3v2[2] * (g1 - g2); + + a += 6; + f++; + } + + a = buf; + for (w = 0; w < 3; w++) { + a02 = (a[0] + a[2]); + b02 = (a[3 + 0] + a[3 + 2]); + c[0] = a02 + a[1]; + c[1] = b02 + a[3 + 1]; + c[2] = coef87 * (a[0] - a[2]); + c[3] = coef87 * (a[3 + 0] - a[3 + 2]) - c[1]; + c[1] = c[1] - c[0]; + c[2] = c[2] - c[1]; + c[4] = a02 - a[1] - a[1]; + c[5] = b02 - a[3 + 1] - a[3 + 1] - c[3]; + c[3] = c[3] - c[2]; + c[4] = c[4] - c[3]; + c[5] = c[5] - c[4]; + a += 6; + c += 6; + } + + return; } /*--------------------------------------------------------------------*/ diff --git a/codemp/mp3code/mhead.c b/codemp/mp3code/mhead.c index 61340a93e8..4920f2a8ea 100644 --- a/codemp/mp3code/mhead.c +++ b/codemp/mp3code/mhead.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -40,155 +40,114 @@ ____________________________________________________________________________*/ #include #include #include -#include "mhead.h" /* mpeg header structure */ +#include "mhead.h" /* mpeg header structure */ -static const int mp_br_table[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, - {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0}}; -static const int mp_sr20_table[2][4] = -{{441, 480, 320, -999}, {882, 960, 640, -999}}; - -static const int mp_br_tableL1[2][16] = -{{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0},/* mpeg2 */ - {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0}}; - -static const int mp_br_tableL3[2][16] = -{{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ - {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; +static const int mp_br_table[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, + {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0}}; +static const int mp_sr20_table[2][4] = {{441, 480, 320, -999}, {882, 960, 640, -999}}; +static const int mp_br_tableL1[2][16] = {{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0}, /* mpeg2 */ + {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0}}; +static const int mp_br_tableL3[2][16] = {{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, /* mpeg 2 */ + {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}}; static int find_sync(unsigned char *buf, int n); static int sync_scan(unsigned char *buf, int n, int i0); static int sync_test(unsigned char *buf, int n, int isync, int padbytes); - /*--------------------------------------------------------------*/ -int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD * h) -{ - int framebytes; - int mpeg25_flag; - - if (n > 10000) - n = 10000; /* limit scan for free format */ - - - - h->sync = 0; - //if ((buf[0] == 0xFF) && ((buf[1] & 0xF0) == 0xF0)) - if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xF0)) - { - mpeg25_flag = 0; // mpeg 1 & 2 - - } - else if ((buf[0] == 0xFF) && ((buf[0+1] & 0xF0) == 0xE0)) - { - mpeg25_flag = 1; // mpeg 2.5 - - } - else - return 0; // sync fail - - h->sync = 1; - if (mpeg25_flag) - h->sync = 2; //low bit clear signals mpeg25 (as in 0xFFE) - - h->id = (buf[0+1] & 0x08) >> 3; - h->option = (buf[0+1] & 0x06) >> 1; - h->prot = (buf[0+1] & 0x01); - - h->br_index = (buf[0+2] & 0xf0) >> 4; - h->sr_index = (buf[0+2] & 0x0c) >> 2; - h->pad = (buf[0+2] & 0x02) >> 1; - h->private_bit = (buf[0+2] & 0x01); - h->mode = (buf[0+3] & 0xc0) >> 6; - h->mode_ext = (buf[0+3] & 0x30) >> 4; - h->cr = (buf[0+3] & 0x08) >> 3; - h->original = (buf[0+3] & 0x04) >> 2; - h->emphasis = (buf[0+3] & 0x03); - - -// if( mpeg25_flag ) { - // if( h->sr_index == 2 ) return 0; // fail 8khz - //} - - -/* compute framebytes for Layer I, II, III */ - if (h->option < 1) - return 0; - if (h->option > 3) - return 0; - - framebytes = 0; - - if (h->br_index > 0) - { - if (h->option == 3) - { /* layer I */ - framebytes = - 240 * mp_br_tableL1[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - framebytes = 4 * framebytes; - } - else if (h->option == 2) - { /* layer II */ - framebytes = - 2880 * mp_br_table[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else if (h->option == 1) - { /* layer III */ - if (h->id) - { // mpeg1 - - framebytes = - 2880 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else - { // mpeg2 - - if (mpeg25_flag) - { // mpeg2.2 - - framebytes = - 2880 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - else - { - framebytes = - 1440 * mp_br_tableL3[h->id][h->br_index] - / mp_sr20_table[h->id][h->sr_index]; - } - } - } - } - else - framebytes = find_sync(buf, n); /* free format */ - - return framebytes; +int head_info(unsigned char *buf, unsigned int n, MPEG_HEAD *h) { + int framebytes; + int mpeg25_flag; + + if (n > 10000) + n = 10000; /* limit scan for free format */ + + h->sync = 0; + // if ((buf[0] == 0xFF) && ((buf[1] & 0xF0) == 0xF0)) + if ((buf[0] == 0xFF) && ((buf[0 + 1] & 0xF0) == 0xF0)) { + mpeg25_flag = 0; // mpeg 1 & 2 + + } else if ((buf[0] == 0xFF) && ((buf[0 + 1] & 0xF0) == 0xE0)) { + mpeg25_flag = 1; // mpeg 2.5 + + } else + return 0; // sync fail + + h->sync = 1; + if (mpeg25_flag) + h->sync = 2; // low bit clear signals mpeg25 (as in 0xFFE) + + h->id = (buf[0 + 1] & 0x08) >> 3; + h->option = (buf[0 + 1] & 0x06) >> 1; + h->prot = (buf[0 + 1] & 0x01); + + h->br_index = (buf[0 + 2] & 0xf0) >> 4; + h->sr_index = (buf[0 + 2] & 0x0c) >> 2; + h->pad = (buf[0 + 2] & 0x02) >> 1; + h->private_bit = (buf[0 + 2] & 0x01); + h->mode = (buf[0 + 3] & 0xc0) >> 6; + h->mode_ext = (buf[0 + 3] & 0x30) >> 4; + h->cr = (buf[0 + 3] & 0x08) >> 3; + h->original = (buf[0 + 3] & 0x04) >> 2; + h->emphasis = (buf[0 + 3] & 0x03); + + // if( mpeg25_flag ) { + // if( h->sr_index == 2 ) return 0; // fail 8khz + //} + + /* compute framebytes for Layer I, II, III */ + if (h->option < 1) + return 0; + if (h->option > 3) + return 0; + + framebytes = 0; + + if (h->br_index > 0) { + if (h->option == 3) { /* layer I */ + framebytes = 240 * mp_br_tableL1[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + framebytes = 4 * framebytes; + } else if (h->option == 2) { /* layer II */ + framebytes = 2880 * mp_br_table[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else if (h->option == 1) { /* layer III */ + if (h->id) { // mpeg1 + + framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else { // mpeg2 + + if (mpeg25_flag) { // mpeg2.2 + + framebytes = 2880 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } else { + framebytes = 1440 * mp_br_tableL3[h->id][h->br_index] / mp_sr20_table[h->id][h->sr_index]; + } + } + } + } else + framebytes = find_sync(buf, n); /* free format */ + + return framebytes; } int head_info3(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int *br, unsigned int *searchForward) { unsigned int pBuf = 0; // jdw insertion... - while ((pBuf < n) && !((buf[pBuf] == 0xFF) && - ((buf[pBuf+1] & 0xF0) == 0xF0 || (buf[pBuf+1] & 0xF0) == 0xE0))) - { + while ((pBuf < n) && !((buf[pBuf] == 0xFF) && ((buf[pBuf + 1] & 0xF0) == 0xF0 || (buf[pBuf + 1] & 0xF0) == 0xE0))) { pBuf++; - } + } - if (pBuf == n) return 0; + if (pBuf == n) + return 0; - *searchForward = pBuf; - return head_info2(&(buf[pBuf]),n,h,br); + *searchForward = pBuf; + return head_info2(&(buf[pBuf]), n, h, br); } /*--------------------------------------------------------------*/ -int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br) -{ +int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD *h, int *br) { int framebytes; /*--- return br (in bits/sec) in addition to frame bytes ---*/ @@ -200,129 +159,115 @@ int head_info2(unsigned char *buf, unsigned int n, MPEG_HEAD * h, int *br) if (framebytes == 0) return 0; - switch (h->option) + switch (h->option) { + case 1: /* layer III */ { - case 1: /* layer III */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_tableL3[h->id][h->br_index]; - else - { - if (h->id) // mpeg1 - - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); - else - { // mpeg2 + if (h->br_index > 0) + *br = 1000 * mp_br_tableL3[h->id][h->br_index]; + else { + if (h->id) // mpeg1 - if ((h->sync & 1) == 0) // flags mpeg25 + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); + else { // mpeg2 - *br = 500 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); - } + if ((h->sync & 1) == 0) // flags mpeg25 + + *br = 500 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (72 * 20); } } - break; - - case 2: /* layer II */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_table[h->id][h->br_index]; - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); - } - break; - - case 3: /* layer I */ - { - if (h->br_index > 0) - *br = 1000 * mp_br_tableL1[h->id][h->br_index]; - else - *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (48 * 20); - } - break; + } break; - default: + case 2: /* layer II */ + { + if (h->br_index > 0) + *br = 1000 * mp_br_table[h->id][h->br_index]; + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (144 * 20); + } break; - return 0; // fuck knows what this is, but it ain't one of ours... - } + case 3: /* layer I */ + { + if (h->br_index > 0) + *br = 1000 * mp_br_tableL1[h->id][h->br_index]; + else + *br = 1000 * framebytes * mp_sr20_table[h->id][h->sr_index] / (48 * 20); + } break; + default: + + return 0; // fuck knows what this is, but it ain't one of ours... + } return framebytes; } /*--------------------------------------------------------------*/ -static int compare(unsigned char *buf, unsigned char *buf2) -{ - if (buf[0] != buf2[0]) - return 0; - if (buf[1] != buf2[1]) - return 0; - return 1; +static int compare(unsigned char *buf, unsigned char *buf2) { + if (buf[0] != buf2[0]) + return 0; + if (buf[1] != buf2[1]) + return 0; + return 1; } /*----------------------------------------------------------*/ /*-- does not scan for initial sync, initial sync assumed --*/ -static int find_sync(unsigned char *buf, int n) -{ - int i0, isync, nmatch, pad; - int padbytes, option; - -/* mod 4/12/95 i0 change from 72, allows as low as 8kbits for mpeg1 */ - i0 = 24; - padbytes = 1; - option = (buf[1] & 0x06) >> 1; - if (option == 3) - { - padbytes = 4; - i0 = 24; /* for shorter layer I frames */ - } - - pad = (buf[2] & 0x02) >> 1; - - n -= 3; /* need 3 bytes of header */ - - while (i0 < 2000) - { - isync = sync_scan(buf, n, i0); - i0 = isync + 1; - isync -= pad; - if (isync <= 0) - return 0; - nmatch = sync_test(buf, n, isync, padbytes); - if (nmatch > 0) - return isync; - } - - return 0; +static int find_sync(unsigned char *buf, int n) { + int i0, isync, nmatch, pad; + int padbytes, option; + + /* mod 4/12/95 i0 change from 72, allows as low as 8kbits for mpeg1 */ + i0 = 24; + padbytes = 1; + option = (buf[1] & 0x06) >> 1; + if (option == 3) { + padbytes = 4; + i0 = 24; /* for shorter layer I frames */ + } + + pad = (buf[2] & 0x02) >> 1; + + n -= 3; /* need 3 bytes of header */ + + while (i0 < 2000) { + isync = sync_scan(buf, n, i0); + i0 = isync + 1; + isync -= pad; + if (isync <= 0) + return 0; + nmatch = sync_test(buf, n, isync, padbytes); + if (nmatch > 0) + return isync; + } + + return 0; } /*------------------------------------------------------*/ /*---- scan for next sync, assume start is valid -------*/ /*---- return number bytes to next sync ----------------*/ -static int sync_scan(unsigned char *buf, int n, int i0) -{ - int i; +static int sync_scan(unsigned char *buf, int n, int i0) { + int i; - for (i = i0; i < n; i++) - if (compare(buf, buf + i)) - return i; + for (i = i0; i < n; i++) + if (compare(buf, buf + i)) + return i; - return 0; + return 0; } /*------------------------------------------------------*/ /*- test consecutative syncs, input isync without pad --*/ -static int sync_test(unsigned char *buf, int n, int isync, int padbytes) -{ - int i, nmatch, pad; - - nmatch = 0; - for (i = 0;;) - { - pad = padbytes * ((buf[i + 2] & 0x02) >> 1); - i += (pad + isync); - if (i > n) - break; - if (!compare(buf, buf + i)) - return -nmatch; - nmatch++; - } - return nmatch; +static int sync_test(unsigned char *buf, int n, int isync, int padbytes) { + int i, nmatch, pad; + + nmatch = 0; + for (i = 0;;) { + pad = padbytes * ((buf[i + 2] & 0x02) >> 1); + i += (pad + isync); + if (i > n) + break; + if (!compare(buf, buf + i)) + return -nmatch; + nmatch++; + } + return nmatch; } diff --git a/codemp/mp3code/msis.c b/codemp/mp3code/msis.c index f0e11f51a7..770ccafae2 100644 --- a/codemp/mp3code/msis.c +++ b/codemp/mp3code/msis.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -29,15 +29,15 @@ ____________________________________________________________________________*/ antialias, ms and is stereo precessing **** is_process assumes never switch - from short to long in is region ***** + from short to long in is region ***** is_process does ms or stereo in "forbidded sf regions" - //ms_mode = 0 - lr[0][i][0] = 1.0f; - lr[0][i][1] = 0.0f; - // ms_mode = 1, in is bands is routine does ms processing - lr[1][i][0] = 1.0f; - lr[1][i][1] = 1.0f; + //ms_mode = 0 + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + // ms_mode = 1, in is bands is routine does ms processing + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; ******************************************************************/ @@ -52,7 +52,7 @@ is_process does ms or stereo in "forbidded sf regions" typedef float ARRAY2[2]; typedef float ARRAY8_2[8][2]; -float csa[8][2]; /* antialias */ // effectively constant +float csa[8][2]; /* antialias */ // effectively constant /* pMP3Stream->nBand[0] = long, pMP3Stream->nBand[1] = short */ ////@@@@extern int pMP3Stream->nBand[2][22]; @@ -61,236 +61,204 @@ float csa[8][2]; /* antialias */ // effectively constant /* intensity stereo */ /* if ms mode quant pre-scales all values by 1.0/sqrt(2.0) ms_mode in table compensates */ -static float lr[2][8][2]; /* [ms_mode 0/1][sf][left/right] */ // effectively constant - +static float lr[2][8][2]; /* [ms_mode 0/1][sf][left/right] */ // effectively constant /* intensity stereo MPEG2 */ /* lr2[intensity_scale][ms_mode][sflen_offset+sf][left/right] */ typedef float ARRAY2_64_2[2][64][2]; typedef float ARRAY64_2[64][2]; -static float lr2[2][2][64][2]; // effectively constant - +static float lr2[2][2][64][2]; // effectively constant /*===============================================================*/ -ARRAY2 *alias_init_addr() -{ - return csa; -} +ARRAY2 *alias_init_addr() { return csa; } /*-----------------------------------------------------------*/ -ARRAY8_2 *msis_init_addr() -{ -/*------- -pi = 4.0*atan(1.0); -t = pi/12.0; -for(i=0;i<7;i++) { - s = sin(i*t); - c = cos(i*t); - // ms_mode = 0 - lr[0][i][0] = (float)(s/(s+c)); - lr[0][i][1] = (float)(c/(s+c)); - // ms_mode = 1 - lr[1][i][0] = (float)(sqrt(2.0)*(s/(s+c))); - lr[1][i][1] = (float)(sqrt(2.0)*(c/(s+c))); -} -//sf = 7 -//ms_mode = 0 -lr[0][i][0] = 1.0f; -lr[0][i][1] = 0.0f; -// ms_mode = 1, in is bands is routine does ms processing -lr[1][i][0] = 1.0f; -lr[1][i][1] = 1.0f; -------------*/ - - return lr; +ARRAY8_2 *msis_init_addr() { + /*------- + pi = 4.0*atan(1.0); + t = pi/12.0; + for(i=0;i<7;i++) { + s = sin(i*t); + c = cos(i*t); + // ms_mode = 0 + lr[0][i][0] = (float)(s/(s+c)); + lr[0][i][1] = (float)(c/(s+c)); + // ms_mode = 1 + lr[1][i][0] = (float)(sqrt(2.0)*(s/(s+c))); + lr[1][i][1] = (float)(sqrt(2.0)*(c/(s+c))); + } + //sf = 7 + //ms_mode = 0 + lr[0][i][0] = 1.0f; + lr[0][i][1] = 0.0f; + // ms_mode = 1, in is bands is routine does ms processing + lr[1][i][0] = 1.0f; + lr[1][i][1] = 1.0f; + ------------*/ + + return lr; } /*-------------------------------------------------------------*/ -ARRAY2_64_2 *msis_init_addr_MPEG2() -{ - return lr2; -} +ARRAY2_64_2 *msis_init_addr_MPEG2() { return lr2; } /*===============================================================*/ -void antialias(float x[], int n) -{ - int i, k; - float a, b; - - for (k = 0; k < n; k++) - { - for (i = 0; i < 8; i++) - { - a = x[17 - i]; - b = x[18 + i]; - x[17 - i] = a * csa[i][0] - b * csa[i][1]; - x[18 + i] = b * csa[i][0] + a * csa[i][1]; - } - x += 18; - } +void antialias(float x[], int n) { + int i, k; + float a, b; + + for (k = 0; k < n; k++) { + for (i = 0; i < 8; i++) { + a = x[17 - i]; + b = x[18 + i]; + x[17 - i] = a * csa[i][0] - b * csa[i][1]; + x[18 + i] = b * csa[i][0] + a * csa[i][1]; + } + x += 18; + } } /*===============================================================*/ -void ms_process(float x[][1152], int n) /* sum-difference stereo */ +void ms_process(float x[][1152], int n) /* sum-difference stereo */ { - int i; - float xl, xr; - -/*-- note: sqrt(2) done scaling by dequant ---*/ - for (i = 0; i < n; i++) - { - xl = x[0][i] + x[1][i]; - xr = x[0][i] - x[1][i]; - x[0][i] = xl; - x[1][i] = xr; - } - return; + int i; + float xl, xr; + + /*-- note: sqrt(2) done scaling by dequant ---*/ + for (i = 0; i < n; i++) { + xl = x[0][i] + x[1][i]; + xr = x[0][i] - x[1][i]; + x[0][i] = xl; + x[1][i] = xr; + } + return; } /*===============================================================*/ -void is_process_MPEG1(float x[][1152], /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - int nsamp, int ms_mode) -{ - int i, j, n, cb, w; - float fl, fr; - int m; - int isf; - float fls[3], frs[3]; - int cb0; - - - cb0 = cb_info[1].cbmax; /* start at end of right */ - i = pMP3Stream->sfBandIndex[cb_info[1].cbtype][cb0]; - cb0++; - m = nsamp - i; /* process to len of left */ - - if (cb_info[1].cbtype) - goto short_blocks; -/*------------------------*/ -/* long_blocks: */ - for (cb = cb0; cb < 21; cb++) - { - isf = sf->l[cb]; - n = pMP3Stream->nBand[0][cb]; - fl = lr[ms_mode][isf][0]; - fr = lr[ms_mode][isf][1]; - for (j = 0; j < n; j++, i++) - { - if (--m < 0) - goto exit; - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - } - } - return; -/*------------------------*/ - short_blocks: - for (cb = cb0; cb < 12; cb++) - { - for (w = 0; w < 3; w++) - { - isf = sf->s[w][cb]; - fls[w] = lr[ms_mode][isf][0]; - frs[w] = lr[ms_mode][isf][1]; - } - n = pMP3Stream->nBand[1][cb]; - for (j = 0; j < n; j++) - { - m -= 3; - if (m < 0) - goto exit; - x[1][i] = frs[0] * x[0][i]; - x[0][i] = fls[0] * x[0][i]; - x[1][1 + i] = frs[1] * x[0][1 + i]; - x[0][1 + i] = fls[1] * x[0][1 + i]; - x[1][2 + i] = frs[2] * x[0][2 + i]; - x[0][2 + i] = fls[2] * x[0][2 + i]; - i += 3; - } - } - - exit: - return; +void is_process_MPEG1(float x[][1152], /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + int nsamp, int ms_mode) { + int i, j, n, cb, w; + float fl, fr; + int m; + int isf; + float fls[3], frs[3]; + int cb0; + + cb0 = cb_info[1].cbmax; /* start at end of right */ + i = pMP3Stream->sfBandIndex[cb_info[1].cbtype][cb0]; + cb0++; + m = nsamp - i; /* process to len of left */ + + if (cb_info[1].cbtype) + goto short_blocks; + /*------------------------*/ + /* long_blocks: */ + for (cb = cb0; cb < 21; cb++) { + isf = sf->l[cb]; + n = pMP3Stream->nBand[0][cb]; + fl = lr[ms_mode][isf][0]; + fr = lr[ms_mode][isf][1]; + for (j = 0; j < n; j++, i++) { + if (--m < 0) + goto exit; + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + } + } + return; + /*------------------------*/ +short_blocks: + for (cb = cb0; cb < 12; cb++) { + for (w = 0; w < 3; w++) { + isf = sf->s[w][cb]; + fls[w] = lr[ms_mode][isf][0]; + frs[w] = lr[ms_mode][isf][1]; + } + n = pMP3Stream->nBand[1][cb]; + for (j = 0; j < n; j++) { + m -= 3; + if (m < 0) + goto exit; + x[1][i] = frs[0] * x[0][i]; + x[0][i] = fls[0] * x[0][i]; + x[1][1 + i] = frs[1] * x[0][1 + i]; + x[0][1 + i] = fls[1] * x[0][1 + i]; + x[1][2 + i] = frs[2] * x[0][2 + i]; + x[0][2 + i] = fls[2] * x[0][2 + i]; + i += 3; + } + } + +exit: + return; } /*===============================================================*/ -void is_process_MPEG2(float x[][1152], /* intensity stereo */ - SCALEFACT * sf, - CB_INFO cb_info[2], /* [ch] */ - IS_SF_INFO * is_sf_info, - int nsamp, int ms_mode) -{ - int i, j, k, n, cb, w; - float fl, fr; - int m; - int isf; - int il[21]; - int tmp; - int r; - ARRAY2 *lr; - int cb0, cb1; - - lr = lr2[is_sf_info->intensity_scale][ms_mode]; - - if (cb_info[1].cbtype) - goto short_blocks; - -/*------------------------*/ -/* long_blocks: */ - cb0 = cb_info[1].cbmax; /* start at end of right */ - i = pMP3Stream->sfBandIndex[0][cb0]; - m = nsamp - i; /* process to len of left */ -/* gen sf info */ - for (k = r = 0; r < 3; r++) - { - tmp = (1 << is_sf_info->slen[r]) - 1; - for (j = 0; j < is_sf_info->nr[r]; j++, k++) - il[k] = tmp; - } - for (cb = cb0 + 1; cb < 21; cb++) - { - isf = il[cb] + sf->l[cb]; - fl = lr[isf][0]; - fr = lr[isf][1]; - n = pMP3Stream->nBand[0][cb]; - for (j = 0; j < n; j++, i++) - { - if (--m < 0) - goto exit; - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - } - } - return; -/*------------------------*/ - short_blocks: - - for (k = r = 0; r < 3; r++) - { - tmp = (1 << is_sf_info->slen[r]) - 1; - for (j = 0; j < is_sf_info->nr[r]; j++, k++) - il[k] = tmp; - } - - for (w = 0; w < 3; w++) - { - cb0 = cb_info[1].cbmax_s[w]; /* start at end of right */ - i = pMP3Stream->sfBandIndex[1][cb0] + w; - cb1 = cb_info[0].cbmax_s[w]; /* process to end of left */ - - for (cb = cb0 + 1; cb <= cb1; cb++) - { - isf = il[cb] + sf->s[w][cb]; - fl = lr[isf][0]; - fr = lr[isf][1]; - n = pMP3Stream->nBand[1][cb]; - for (j = 0; j < n; j++) - { - x[1][i] = fr * x[0][i]; - x[0][i] = fl * x[0][i]; - i += 3; - } - } - - } - - exit: - return; +void is_process_MPEG2(float x[][1152], /* intensity stereo */ + SCALEFACT *sf, CB_INFO cb_info[2], /* [ch] */ + IS_SF_INFO *is_sf_info, int nsamp, int ms_mode) { + int i, j, k, n, cb, w; + float fl, fr; + int m; + int isf; + int il[21]; + int tmp; + int r; + ARRAY2 *lr; + int cb0, cb1; + + lr = lr2[is_sf_info->intensity_scale][ms_mode]; + + if (cb_info[1].cbtype) + goto short_blocks; + + /*------------------------*/ + /* long_blocks: */ + cb0 = cb_info[1].cbmax; /* start at end of right */ + i = pMP3Stream->sfBandIndex[0][cb0]; + m = nsamp - i; /* process to len of left */ + /* gen sf info */ + for (k = r = 0; r < 3; r++) { + tmp = (1 << is_sf_info->slen[r]) - 1; + for (j = 0; j < is_sf_info->nr[r]; j++, k++) + il[k] = tmp; + } + for (cb = cb0 + 1; cb < 21; cb++) { + isf = il[cb] + sf->l[cb]; + fl = lr[isf][0]; + fr = lr[isf][1]; + n = pMP3Stream->nBand[0][cb]; + for (j = 0; j < n; j++, i++) { + if (--m < 0) + goto exit; + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + } + } + return; + /*------------------------*/ +short_blocks: + + for (k = r = 0; r < 3; r++) { + tmp = (1 << is_sf_info->slen[r]) - 1; + for (j = 0; j < is_sf_info->nr[r]; j++, k++) + il[k] = tmp; + } + + for (w = 0; w < 3; w++) { + cb0 = cb_info[1].cbmax_s[w]; /* start at end of right */ + i = pMP3Stream->sfBandIndex[1][cb0] + w; + cb1 = cb_info[0].cbmax_s[w]; /* process to end of left */ + + for (cb = cb0 + 1; cb <= cb1; cb++) { + isf = il[cb] + sf->s[w][cb]; + fl = lr[isf][0]; + fr = lr[isf][1]; + n = pMP3Stream->nBand[1][cb]; + for (j = 0; j < n; j++) { + x[1][i] = fr * x[0][i]; + x[0][i] = fl * x[0][i]; + i += 3; + } + } + } + +exit: + return; } /*===============================================================*/ diff --git a/codemp/mp3code/towave.c b/codemp/mp3code/towave.c index 98d09c0037..eaea189460 100644 --- a/codemp/mp3code/towave.c +++ b/codemp/mp3code/towave.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -26,13 +26,13 @@ ____________________________________________________________________________*/ /* ------------------------------------------------------------------------ - NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE - This file exists for reference only. It is not actually used - in the FreeAmp project. There is no need to mess with this - file. There is no need to flatten the beavers, either. + This file exists for reference only. It is not actually used + in the FreeAmp project. There is no need to mess with this + file. There is no need to flatten the beavers, either. - NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE /*---- towave.c -------------------------------------------- 32 bit version only @@ -45,7 +45,7 @@ mod 8/19/98 decode 22 sf bands mod 5/14/98 allow mpeg25 (dec8 not supported for mpeg25 samp rate) mod 3/4/98 bs_trigger bs_bufbytes made signed, unsigned may - not terminate properly. Also extra test in bs_fill. + not terminate properly. Also extra test in bs_fill. mod 8/6/96 add 8 bit output to standard decoder @@ -54,9 +54,9 @@ ver 1.4 mods 7/18/96 32 bit and add asm option mods 6/29/95 allow MS wave file for u-law. bugfix u-law table dec8.c mods 2/95 add sample rate reduction, freq_limit and conversions. - add _decode8 for 8Ks output, 16bit 8bit, u-law output. - add additional control parameters to init. - add _info function + add _decode8 for 8Ks output, 16bit 8bit, u-law output. + add additional control parameters to init. + add _info function mod 5/12/95 add quick window cwinq.c @@ -68,11 +68,11 @@ mod 1/5/95 integer overflow mod iup.c ver 1.3 mod 2/5/96 portability mods - drop Tom and Gloria pcm file types + drop Tom and Gloria pcm file types ver 2.0 mod 1/7/97 Layer 3 (float mpeg-1 only) - 2/6/97 Layer 3 MPEG-2 + 2/6/97 Layer 3 MPEG-2 ver 3.01 Layer III bugfix crc problem 8/18/97 ver 3.02 Layer III fix wannabe.mp3 problem 10/9/97 @@ -102,26 +102,26 @@ mod 8/6/96 standard decoder adds 8 bit output decode8 (8Ks output) convert_code: convert_code = 4*bit_code + chan_code - bit_code: 1 = 16 bit linear pcm - 2 = 8 bit (unsigned) linear pcm - 3 = u-law (8 bits unsigned) - chan_code: 0 = convert two chan to mono - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan + bit_code: 1 = 16 bit linear pcm + 2 = 8 bit (unsigned) linear pcm + 3 = u-law (8 bits unsigned) + chan_code: 0 = convert two chan to mono + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan decode (standard decoder) convert_code: - 0 = two chan output - 1 = convert two chan to mono - 2 = convert two chan to left chan - 3 = convert two chan to right chan - or with 8 = 8 bit output - (other bits ignored) + 0 = two chan output + 1 = convert two chan to mono + 2 = convert two chan to left chan + 3 = convert two chan to right chan + or with 8 = 8 bit output + (other bits ignored) decode (standard decoder) reduction_code: - 0 = full sample rate output - 1 = half rate - 2 = quarter rate + 0 = full sample rate output + 1 = half rate + 2 = quarter rate -----------------------------------------------------------*/ #include @@ -132,10 +132,10 @@ decode (standard decoder) reduction_code: #ifdef WIN32 #include #endif -#include /* file open flags */ -#include /* someone wants for port */ -#include /* forward slash for portability */ -#include "mhead.h" /* mpeg header structure, decode protos */ +#include /* file open flags */ +#include /* someone wants for port */ +#include /* forward slash for portability */ +#include "mhead.h" /* mpeg header structure, decode protos */ #include "port.h" @@ -151,53 +151,41 @@ decode (standard decoder) reduction_code: #include "mp3struct.h" #include - -#if !defined(MACOS_X) && !defined(byte) && !defined (__linux__) +#if !defined(MACOS_X) && !defined(byte) && !defined(__linux__) typedef unsigned char byte; #endif - - typedef struct id3v1_1 { - char id[3]; - char title[30]; // - char artist[30]; // "Raven Software" - char album[30]; // "#UNCOMP %d" // needed - char year[4]; // "2000" - char comment[28]; // "#MAXVOL %g" // needed - char zero; - char track; - char genre; -} id3v1_1; // 128 bytes in size + char id[3]; + char title[30]; // + char artist[30]; // "Raven Software" + char album[30]; // "#UNCOMP %d" // needed + char year[4]; // "2000" + char comment[28]; // "#MAXVOL %g" // needed + char zero; + char track; + char genre; +} id3v1_1; // 128 bytes in size id3v1_1 *gpTAG; -#define BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(_pvData, _iBytesRemaining) \ - \ - /* account for trailing ID3 tag in _iBytesRemaining */ \ - gpTAG = (id3v1_1*) (((byte *)_pvData + _iBytesRemaining)-sizeof(id3v1_1)); /* sizeof = 128 */ \ - if (!strncmp(gpTAG->id, "TAG", 3)) \ - { \ - _iBytesRemaining -= sizeof(id3v1_1); \ +#define BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(_pvData, _iBytesRemaining) \ + \ + /* account for trailing ID3 tag in _iBytesRemaining */ \ + gpTAG = (id3v1_1 *)(((byte *)_pvData + _iBytesRemaining) - sizeof(id3v1_1)); /* sizeof = 128 */ \ + if (!strncmp(gpTAG->id, "TAG", 3)) { \ + _iBytesRemaining -= sizeof(id3v1_1); \ } - - - - /******** pcm buffer ********/ -#define PCM_BUFBYTES 60000U // more than enough to cover the largest that one packet will ever expand to -char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mallocs in this module (MAC reasons) +#define PCM_BUFBYTES 60000U // more than enough to cover the largest that one packet will ever expand to +char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mallocs in this module (MAC reasons) - typedef struct - { - int (*decode_init) (MPEG_HEAD * h, int framebytes_arg, - int reduction_code, int transform_code, - int convert_code, int freq_limit); - void (*decode_info) (DEC_INFO * info); - IN_OUT(*decode) (unsigned char *bs, short *pcm, unsigned char *pNextByteAfterData); - } - AUDIO; +typedef struct { + int (*decode_init)(MPEG_HEAD *h, int framebytes_arg, int reduction_code, int transform_code, int convert_code, int freq_limit); + void (*decode_info)(DEC_INFO *info); + IN_OUT (*decode)(unsigned char *bs, short *pcm, unsigned char *pNextByteAfterData); +} AUDIO; #if 0 // stuff this... @@ -225,44 +213,40 @@ char PCM_Buffer[PCM_BUFBYTES]; // better off being declared, so we don't do mall }; #endif - static const AUDIO audio = {audio_decode_init, audio_decode_info, audio_decode}; //audio_table[0][0]; - +static const AUDIO audio = {audio_decode_init, audio_decode_info, audio_decode}; // audio_table[0][0]; // Do NOT change these, ever!!!!!!!!!!!!!!!!!! // -const int reduction_code = 0; // unpack at full sample rate output -const int convert_code_mono = 1; +const int reduction_code = 0; // unpack at full sample rate output +const int convert_code_mono = 1; const int convert_code_stereo = 0; -const int freq_limit = 24000; // no idea what this is about, but it's always this value so... +const int freq_limit = 24000; // no idea what this is about, but it's always this value so... // the entire decode mechanism uses this now... // MP3STREAM _MP3Stream; LP_MP3STREAM pMP3Stream = &_MP3Stream; -int bFastEstimateOnly = 0; // MUST DEFAULT TO THIS VALUE!!!!!!!!! - +int bFastEstimateOnly = 0; // MUST DEFAULT TO THIS VALUE!!!!!!!!! // char *return is NZ for any errors (no trailing CR!) // -char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) -{ -// char sTemp[1024]; ///////////////////////////////////////////////// +char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) { + // char sTemp[1024]; ///////////////////////////////////////////////// unsigned int iRealDataStart; MPEG_HEAD head; - DEC_INFO decinfo; + DEC_INFO decinfo; int iBitRate; int iFrameBytes; -//#ifdef _DEBUG -// int iIgnoreThisForNowIJustNeedItToBreakpointOnToReadAValue = sizeof(MP3STREAM); -//#endif + //#ifdef _DEBUG + // int iIgnoreThisForNowIJustNeedItToBreakpointOnToReadAValue = sizeof(MP3STREAM); + //#endif - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - iFrameBytes = head_info3( pvData, iDataLen/2, &head, &iBitRate, &iRealDataStart); - if (iFrameBytes == 0) - { + iFrameBytes = head_info3(pvData, iDataLen / 2, &head, &iBitRate, &iRealDataStart); + if (iFrameBytes == 0) { return "MP3ERR: Bad or unsupported file!"; } @@ -271,42 +255,31 @@ char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) // although the decoder can convert stereo to mono (apparently), we want to know about stereo files // because they're a waste of source space... (all FX are mono, and moved via panning) // - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { - if (bStereoDesired) - { - if (pMP3Stream->outbytes > 4608) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { + if (bStereoDesired) { + if (pMP3Stream->outbytes > 4608) { return "MP3ERR: Source file has output packet size > 2304 (*2 for stereo) bytes!"; } - } - else - { - if (pMP3Stream->outbytes > 2304) - { + } else { + if (pMP3Stream->outbytes > 2304) { return "MP3ERR: Source file has output packet size > 2304 bytes!"; } } audio.decode_info(&decinfo); - if (decinfo.bits != 16) - { - return "MP3ERR: Source file is not 16bit!"; // will this ever happen? oh well... + if (decinfo.bits != 16) { + return "MP3ERR: Source file is not 16bit!"; // will this ever happen? oh well... } - if (decinfo.samprate != 44100) - { + if (decinfo.samprate != 44100) { return "MP3ERR: Source file is not sampled @ 44100!"; } - if (bStereoDesired && decinfo.channels != 2) - { - return "MP3ERR: Source file is not stereo!"; // sod it, I'm going to count this as an error now + if (bStereoDesired && decinfo.channels != 2) { + return "MP3ERR: Source file is not stereo!"; // sod it, I'm going to count this as an error now } - } - else - { + } else { return "MP3ERR: Decoder failed to initialise"; } @@ -315,37 +288,30 @@ char *C_MP3_IsValid(void *pvData, int iDataLen, int bStereoDesired) return NULL; } - - // char *return is NZ for any errors (no trailing CR!) // -char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, int *piChannels, int bStereoDesired) -{ +char *C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, int *piChannels, int bStereoDesired) { unsigned int iRealDataStart; MPEG_HEAD head; - DEC_INFO decinfo; + DEC_INFO decinfo; int iBitRate; int iFrameBytes; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - iFrameBytes = head_info3( pvData, iDataLen/2, &head, &iBitRate, &iRealDataStart); - if (iFrameBytes == 0) - { + iFrameBytes = head_info3(pvData, iDataLen / 2, &head, &iBitRate, &iRealDataStart); + if (iFrameBytes == 0) { return "MP3ERR: Bad or unsupported file!"; } - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); - *piRate = decinfo.samprate; // rate (eg 22050, 44100 etc) - *piWidth = decinfo.bits/8; // 1 for 8bit, 2 for 16 bit - *piChannels = decinfo.channels; // 1 for mono, 2 for stereo - } - else - { + *piRate = decinfo.samprate; // rate (eg 22050, 44100 etc) + *piWidth = decinfo.bits / 8; // 1 for 8bit, 2 for 16 bit + *piChannels = decinfo.channels; // 1 for mono, 2 for stereo + } else { return "MP3ERR: Decoder failed to initialise"; } @@ -354,9 +320,6 @@ char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, return NULL; } - - - // this duplicates work done in C_MP3_IsValid(), but it avoids global structs, and means that you can call this anytime // if you just want info for some reason // @@ -364,8 +327,7 @@ char* C_MP3_GetHeaderData(void *pvData, int iDataLen, int *piRate, int *piWidth, // // char *return is NZ for any errors (no trailing CR!) // -char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, int bStereoDesired ) -{ +char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, int bStereoDesired) { int iReadLimit; unsigned int iRealDataStart; MPEG_HEAD head; @@ -373,177 +335,155 @@ char *C_MP3_GetUnpackedSize(void *pvData, int iSourceBytesRemaining, int *piUnpa char *pPCM_Buffer = PCM_Buffer; char *psReturn = NULL; -// int iSourceReadIndex = 0; - int iDestWriteIndex = 0; + // int iSourceReadIndex = 0; + int iDestWriteIndex = 0; int iFrameBytes; int iFrameCounter; DEC_INFO decinfo; - IN_OUT x; + IN_OUT x; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); #define iSourceReadIndex iRealDataStart -// iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); - iFrameBytes = head_info3( pvData, iSourceBytesRemaining/2, &head, &iBitRate, &iRealDataStart); + // iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); + iFrameBytes = head_info3(pvData, iSourceBytesRemaining / 2, &head, &iBitRate, &iRealDataStart); BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvData, iSourceBytesRemaining) iSourceBytesRemaining -= iRealDataStart; iReadLimit = iSourceReadIndex + iSourceBytesRemaining; - if (iFrameBytes) - { - //pPCM_Buffer = malloc(PCM_BUFBYTES); + if (iFrameBytes) { + // pPCM_Buffer = malloc(PCM_BUFBYTES); - //if (pPCM_Buffer) + // if (pPCM_Buffer) { // init decoder... - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); // decode... // - for (iFrameCounter = 0;;iFrameCounter++) - { - if ( iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) - break; // end of file + for (iFrameCounter = 0;; iFrameCounter++) { + if (iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) + break; // end of file - bFastEstimateOnly = 1; /////////////////////////////// + bFastEstimateOnly = 1; /////////////////////////////// - x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *) ((char *)pPCM_Buffer - //+ iDestWriteIndex // keep decoding over the same spot since we're only counting bytes in this function - ), - (unsigned char *)pvData + iReadLimit - ); + x = audio.decode((unsigned char *)pvData + iSourceReadIndex, + (short *)((char *)pPCM_Buffer + //+ iDestWriteIndex // keep decoding over the same spot since we're only counting bytes in this function + ), + (unsigned char *)pvData + iReadLimit); - bFastEstimateOnly = 0; /////////////////////////////// + bFastEstimateOnly = 0; /////////////////////////////// - iSourceReadIndex += x.in_bytes; - iSourceBytesRemaining -= x.in_bytes; - iDestWriteIndex += x.out_bytes; + iSourceReadIndex += x.in_bytes; + iSourceBytesRemaining -= x.in_bytes; + iDestWriteIndex += x.out_bytes; - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; break; } } - *piUnpackedSize = iDestWriteIndex; // yeeehaaa! - } - else - { + *piUnpackedSize = iDestWriteIndex; // yeeehaaa! + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } } -// else -// { -// psReturn = "MP3ERR: Unable to alloc temp decomp buffer"; -// } - } - else - { + // else + // { + // psReturn = "MP3ERR: Unable to alloc temp decomp buffer"; + // } + } else { psReturn = "MP3ERR: Bad or Unsupported MP3 file!"; } - -// if (pPCM_Buffer) -// { -// free(pPCM_Buffer); -// pPCM_Buffer = NULL; // I know, I know... -// } + // if (pPCM_Buffer) + // { + // free(pPCM_Buffer); + // pPCM_Buffer = NULL; // I know, I know... + // } return psReturn; #undef iSourceReadIndex } - - - -char *C_MP3_UnpackRawPCM( void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, void *pbUnpackBuffer, int bStereoDesired) -{ +char *C_MP3_UnpackRawPCM(void *pvData, int iSourceBytesRemaining, int *piUnpackedSize, void *pbUnpackBuffer, int bStereoDesired) { int iReadLimit; unsigned int iRealDataStart; MPEG_HEAD head; int iBitRate; char *psReturn = NULL; -// int iSourceReadIndex = 0; - int iDestWriteIndex = 0; + // int iSourceReadIndex = 0; + int iDestWriteIndex = 0; int iFrameBytes; int iFrameCounter; DEC_INFO decinfo; - IN_OUT x; + IN_OUT x; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); #define iSourceReadIndex iRealDataStart -// iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); - iFrameBytes = head_info3( pvData, iSourceBytesRemaining/2, &head, &iBitRate, &iRealDataStart); + // iFrameBytes = head_info2( pvData, 0, &head, &iBitRate); + iFrameBytes = head_info3(pvData, iSourceBytesRemaining / 2, &head, &iBitRate, &iRealDataStart); BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvData, iSourceBytesRemaining) iSourceBytesRemaining -= iRealDataStart; iReadLimit = iSourceReadIndex + iSourceBytesRemaining; - if (iFrameBytes) - { -// if (1)////////////////////////pPCM_Buffer) + if (iFrameBytes) { + // if (1)////////////////////////pPCM_Buffer) { // init decoder... - if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { + if (audio.decode_init(&head, iFrameBytes, reduction_code, iRealDataStart, bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { audio.decode_info(&decinfo); -// printf("\n output samprate = %6ld",decinfo.samprate); -// printf("\n output channels = %6d", decinfo.channels); -// printf("\n output bits = %6d", decinfo.bits); -// printf("\n output type = %6d", decinfo.type); + // printf("\n output samprate = %6ld",decinfo.samprate); + // printf("\n output channels = %6d", decinfo.channels); + // printf("\n output bits = %6d", decinfo.bits); + // printf("\n output type = %6d", decinfo.type); -//=============== + //=============== // decode... // - for (iFrameCounter = 0;;iFrameCounter++) - { - if ( iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) - break; // end of file - - x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *) ((char *)pbUnpackBuffer + iDestWriteIndex), - (unsigned char *)pvData + iReadLimit - ); - - iSourceReadIndex += x.in_bytes; - iSourceBytesRemaining -= x.in_bytes; - iDestWriteIndex += x.out_bytes; - - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; + for (iFrameCounter = 0;; iFrameCounter++) { + if (iSourceBytesRemaining == 0 || iSourceBytesRemaining < iFrameBytes) + break; // end of file + + x = audio.decode((unsigned char *)pvData + iSourceReadIndex, (short *)((char *)pbUnpackBuffer + iDestWriteIndex), + (unsigned char *)pvData + iReadLimit); + + iSourceReadIndex += x.in_bytes; + iSourceBytesRemaining -= x.in_bytes; + iDestWriteIndex += x.out_bytes; + + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; break; } } - *piUnpackedSize = iDestWriteIndex; // yeeehaaa! - } - else - { + *piUnpackedSize = iDestWriteIndex; // yeeehaaa! + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } } - } - else - { + } else { psReturn = "MP3ERR: Bad or Unsupported MP3 file!"; } @@ -552,7 +492,6 @@ char *C_MP3_UnpackRawPCM( void *pvData, int iSourceBytesRemaining, int *piUnpack #undef iSourceReadIndex } - // called once, after we've decided to keep something as MP3. This just sets up the decoder for subsequent stream-calls. // // (the struct pSFX_MP3Stream is cleared internally, so pass as args anything you want stored in it) @@ -563,94 +502,84 @@ char *C_MP3_UnpackRawPCM( void *pvData, int iSourceBytesRemaining, int *piUnpack // chunk format for SOF2 instead of just one alloc then you must re-init pMP3Stream->pbSourceData after you've called // this, or it'll be pointing at the deallocated original raw data, not the first chunk of the link list // -char *C_MP3Stream_DecodeInit( LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, int iSourceBytesRemaining, - int iGameAudioSampleRate, int iGameAudioSampleBits, int bStereoDesired ) -{ - char *psReturn = NULL; - MPEG_HEAD head; // only relevant within this function during init - DEC_INFO decinfo; // " " - int iBitRate; // not used after being filled in by head_info3() +char *C_MP3Stream_DecodeInit(LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, int iSourceBytesRemaining, int iGameAudioSampleRate, int iGameAudioSampleBits, + int bStereoDesired) { + char *psReturn = NULL; + MPEG_HEAD head; // only relevant within this function during init + DEC_INFO decinfo; // " " + int iBitRate; // not used after being filled in by head_info3() pMP3Stream = pSFX_MP3Stream; - memset(pMP3Stream,0,sizeof(*pMP3Stream)); + memset(pMP3Stream, 0, sizeof(*pMP3Stream)); - pMP3Stream->pbSourceData = (byte *) pvSourceData; // this MUST be re-initialised to link-mem outside here for SOF2, since raw data is now link-listed - pMP3Stream->iSourceBytesRemaining = iSourceBytesRemaining; - pMP3Stream->iSourceFrameBytes = head_info3( (byte *) pvSourceData, iSourceBytesRemaining/2, &head, &iBitRate, (unsigned int*)&pMP3Stream->iSourceReadIndex ); + pMP3Stream->pbSourceData = (byte *)pvSourceData; // this MUST be re-initialised to link-mem outside here for SOF2, since raw data is now link-listed + pMP3Stream->iSourceBytesRemaining = iSourceBytesRemaining; + pMP3Stream->iSourceFrameBytes = + head_info3((byte *)pvSourceData, iSourceBytesRemaining / 2, &head, &iBitRate, (unsigned int *)&pMP3Stream->iSourceReadIndex); // hack, do NOT do this for stereo, since music files are now streamed and therefore the data isn't actually fully // loaded at this point, only about 4k or so for the header is actually in memory!!!... // - if (!bStereoDesired) - { + if (!bStereoDesired) { BYTESREMAINING_ACCOUNT_FOR_REAR_TAG(pvSourceData, pMP3Stream->iSourceBytesRemaining); - pMP3Stream->iSourceBytesRemaining -= pMP3Stream->iSourceReadIndex; + pMP3Stream->iSourceBytesRemaining -= pMP3Stream->iSourceReadIndex; } // backup a couple of fields so we can play this again later... // - pMP3Stream->iRewind_SourceReadIndex = pMP3Stream->iSourceReadIndex; - pMP3Stream->iRewind_SourceBytesRemaining= pMP3Stream->iSourceBytesRemaining; + pMP3Stream->iRewind_SourceReadIndex = pMP3Stream->iSourceReadIndex; + pMP3Stream->iRewind_SourceBytesRemaining = pMP3Stream->iSourceBytesRemaining; assert(pMP3Stream->iSourceFrameBytes); - if (pMP3Stream->iSourceFrameBytes) - { - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, reduction_code, pMP3Stream->iSourceReadIndex, bStereoDesired?convert_code_stereo:convert_code_mono, freq_limit)) - { - pMP3Stream->iRewind_FinalReductionCode = reduction_code; // default = 0 (no reduction), 1=half, 2 = quarter + if (pMP3Stream->iSourceFrameBytes) { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, reduction_code, pMP3Stream->iSourceReadIndex, + bStereoDesired ? convert_code_stereo : convert_code_mono, freq_limit)) { + pMP3Stream->iRewind_FinalReductionCode = reduction_code; // default = 0 (no reduction), 1=half, 2 = quarter - pMP3Stream->iRewind_FinalConvertCode = bStereoDesired?convert_code_stereo:convert_code_mono; - // default = 1 (mono), OR with 8 for 8-bit output + pMP3Stream->iRewind_FinalConvertCode = bStereoDesired ? convert_code_stereo : convert_code_mono; + // default = 1 (mono), OR with 8 for 8-bit output // only now can we ask what kind of properties this file has, and then adjust to fit what the game wants... // audio.decode_info(&decinfo); -// printf("\n output samprate = %6ld",decinfo.samprate); -// printf("\n output channels = %6d", decinfo.channels); -// printf("\n output bits = %6d", decinfo.bits); -// printf("\n output type = %6d", decinfo.type); + // printf("\n output samprate = %6ld",decinfo.samprate); + // printf("\n output channels = %6d", decinfo.channels); + // printf("\n output bits = %6d", decinfo.bits); + // printf("\n output type = %6d", decinfo.type); // decoder offers half or quarter rate adjustement only... // - if (iGameAudioSampleRate == decinfo.samprate>>1) + if (iGameAudioSampleRate == decinfo.samprate >> 1) pMP3Stream->iRewind_FinalReductionCode = 1; - else - if (iGameAudioSampleRate == decinfo.samprate>>2) + else if (iGameAudioSampleRate == decinfo.samprate >> 2) pMP3Stream->iRewind_FinalReductionCode = 2; - if (iGameAudioSampleBits == decinfo.bits>>1) // if game wants 8 bit sounds, then setup for that + if (iGameAudioSampleBits == decinfo.bits >> 1) // if game wants 8 bit sounds, then setup for that pMP3Stream->iRewind_FinalConvertCode |= 8; - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, pMP3Stream->iRewind_FinalConvertCode, freq_limit)) - { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, + pMP3Stream->iRewind_FinalConvertCode, freq_limit)) { audio.decode_info(&decinfo); #ifdef _DEBUG - assert( iGameAudioSampleRate == decinfo.samprate ); - assert( iGameAudioSampleBits == decinfo.bits ); + assert(iGameAudioSampleRate == decinfo.samprate); + assert(iGameAudioSampleBits == decinfo.bits); #endif // sod it, no harm in one last check... (should never happen) // - if ( iGameAudioSampleRate != decinfo.samprate || iGameAudioSampleBits != decinfo.bits ) - { + if (iGameAudioSampleRate != decinfo.samprate || iGameAudioSampleBits != decinfo.bits) { psReturn = "MP3ERR: Decoder unable to convert to current game audio settings"; } - } - else - { + } else { psReturn = "MP3ERR: Decoder failed to initialise for pass 2 sample adjust"; } - } - else - { + } else { psReturn = "MP3ERR: Decoder failed to initialise"; } - } - else - { - psReturn = "MP3ERR: Errr.... something's broken with this MP3 file"; // should never happen by this point + } else { + psReturn = "MP3ERR: Errr.... something's broken with this MP3 file"; // should never happen by this point } // restore global stream ptr before returning to normal functions (so the rest of the MP3 code still works)... @@ -662,39 +591,36 @@ char *C_MP3Stream_DecodeInit( LP_MP3STREAM pSFX_MP3Stream, void *pvSourceData, i // return value is decoded bytes for this packet, which is effectively a BOOL, NZ for not finished decoding yet... // -unsigned int C_MP3Stream_Decode( LP_MP3STREAM pSFX_MP3Stream ) -{ - unsigned int uiDecoded = 0; // default to "finished" - IN_OUT x; +unsigned int C_MP3Stream_Decode(LP_MP3STREAM pSFX_MP3Stream) { + unsigned int uiDecoded = 0; // default to "finished" + IN_OUT x; pMP3Stream = pSFX_MP3Stream; - if ( pSFX_MP3Stream->iSourceBytesRemaining == 0)// || pSFX_MP3Stream->iSourceBytesRemaining < pSFX_MP3Stream->iSourceFrameBytes) + if (pSFX_MP3Stream->iSourceBytesRemaining == 0) // || pSFX_MP3Stream->iSourceBytesRemaining < pSFX_MP3Stream->iSourceFrameBytes) { - uiDecoded = 0; // finished + uiDecoded = 0; // finished pMP3Stream = &_MP3Stream; return uiDecoded; } - x = audio.decode(pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iSourceReadIndex, (short *) (pSFX_MP3Stream->bDecodeBuffer), - pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iRewind_SourceReadIndex + pSFX_MP3Stream->iRewind_SourceBytesRemaining - ); + x = audio.decode(pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iSourceReadIndex, (short *)(pSFX_MP3Stream->bDecodeBuffer), + pSFX_MP3Stream->pbSourceData + pSFX_MP3Stream->iRewind_SourceReadIndex + pSFX_MP3Stream->iRewind_SourceBytesRemaining); #ifdef _DEBUG pSFX_MP3Stream->iSourceFrameCounter++; #endif - pSFX_MP3Stream->iSourceReadIndex += x.in_bytes; - pSFX_MP3Stream->iSourceBytesRemaining -= x.in_bytes; - pSFX_MP3Stream->iBytesDecodedTotal += x.out_bytes; - pSFX_MP3Stream->iBytesDecodedThisPacket = x.out_bytes; + pSFX_MP3Stream->iSourceReadIndex += x.in_bytes; + pSFX_MP3Stream->iSourceBytesRemaining -= x.in_bytes; + pSFX_MP3Stream->iBytesDecodedTotal += x.out_bytes; + pSFX_MP3Stream->iBytesDecodedThisPacket = x.out_bytes; uiDecoded = x.out_bytes; - if (x.in_bytes <= 0) - { - //psReturn = "MP3ERR: Bad sync in file"; - uiDecoded= 0; // finished + if (x.in_bytes <= 0) { + // psReturn = "MP3ERR: Bad sync in file"; + uiDecoded = 0; // finished pMP3Stream = &_MP3Stream; return uiDecoded; } @@ -706,37 +632,31 @@ unsigned int C_MP3Stream_Decode( LP_MP3STREAM pSFX_MP3Stream ) return uiDecoded; } - // ret is char* errstring, else NULL for ok // -char *C_MP3Stream_Rewind( LP_MP3STREAM pSFX_MP3Stream ) -{ - char* psReturn = NULL; - MPEG_HEAD head; // only relevant within this function during init - int iBitRate; // ditto - int iNULL; +char *C_MP3Stream_Rewind(LP_MP3STREAM pSFX_MP3Stream) { + char *psReturn = NULL; + MPEG_HEAD head; // only relevant within this function during init + int iBitRate; // ditto + int iNULL; pMP3Stream = pSFX_MP3Stream; - pMP3Stream->iSourceReadIndex = pMP3Stream->iRewind_SourceReadIndex; - pMP3Stream->iSourceBytesRemaining = pMP3Stream->iRewind_SourceBytesRemaining; // already adjusted for tags etc + pMP3Stream->iSourceReadIndex = pMP3Stream->iRewind_SourceReadIndex; + pMP3Stream->iSourceBytesRemaining = pMP3Stream->iRewind_SourceBytesRemaining; // already adjusted for tags etc // I'm not sure that this is needed, but where else does decode_init get passed useful data ptrs?... // - if (pMP3Stream->iSourceFrameBytes == head_info3( pMP3Stream->pbSourceData, pMP3Stream->iSourceBytesRemaining/2, &head, &iBitRate, (unsigned int*)&iNULL ) ) - { - if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, pMP3Stream->iRewind_FinalConvertCode, freq_limit)) - { + if (pMP3Stream->iSourceFrameBytes == + head_info3(pMP3Stream->pbSourceData, pMP3Stream->iSourceBytesRemaining / 2, &head, &iBitRate, (unsigned int *)&iNULL)) { + if (audio.decode_init(&head, pMP3Stream->iSourceFrameBytes, pMP3Stream->iRewind_FinalReductionCode, pMP3Stream->iSourceReadIndex, + pMP3Stream->iRewind_FinalConvertCode, freq_limit)) { // we should always get here... // - } - else - { + } else { psReturn = "MP3ERR: Failed to re-init decoder for rewind!"; } - } - else - { + } else { psReturn = "MP3ERR: Frame bytes mismatch during rewind header-read!"; } @@ -746,4 +666,3 @@ char *C_MP3Stream_Rewind( LP_MP3STREAM pSFX_MP3Stream ) return psReturn; } - diff --git a/codemp/mp3code/uph.c b/codemp/mp3code/uph.c index aec373f8cb..ec3eee4ae0 100644 --- a/codemp/mp3code/uph.c +++ b/codemp/mp3code/uph.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -44,79 +44,41 @@ Layer 3 audio /* quad required 10 bit w/signs must have (MAXBITS+2) >= 10 */ #define MAXBITS 9 -static const HUFF_ELEMENT huff_table_0[4] = -{{0}, {0}, {0}, {64}}; /* dummy must not use */ +static const HUFF_ELEMENT huff_table_0[4] = {{0}, {0}, {0}, {64}}; /* dummy must not use */ #include "htable.h" /*-- 6 bit lookup (purgebits, value) --*/ -static const unsigned char quad_table_a[][2] = -{ - {6, 11}, {6, 15}, {6, 13}, {6, 14}, {6, 7}, {6, 5}, {5, 9}, - {5, 9}, {5, 6}, {5, 6}, {5, 3}, {5, 3}, {5, 10}, {5, 10}, - {5, 12}, {5, 12}, {4, 2}, {4, 2}, {4, 2}, {4, 2}, {4, 1}, - {4, 1}, {4, 1}, {4, 1}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, - {4, 8}, {4, 8}, {4, 8}, {4, 8}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, - {1, 0}, +static const unsigned char quad_table_a[][2] = { + {6, 11}, {6, 15}, {6, 13}, {6, 14}, {6, 7}, {6, 5}, {5, 9}, {5, 9}, {5, 6}, {5, 6}, {5, 3}, {5, 3}, {5, 10}, {5, 10}, {5, 12}, {5, 12}, + {4, 2}, {4, 2}, {4, 2}, {4, 2}, {4, 1}, {4, 1}, {4, 1}, {4, 1}, {4, 4}, {4, 4}, {4, 4}, {4, 4}, {4, 8}, {4, 8}, {4, 8}, {4, 8}, + {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, + {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, {1, 0}, }; - -typedef struct -{ - const HUFF_ELEMENT *table; - int linbits; - int ncase; -} -HUFF_SETUP; - -#define no_bits 0 -#define one_shot 1 -#define no_linbits 2 -#define have_linbits 3 -#define quad_a 4 -#define quad_b 5 - - -static const HUFF_SETUP table_look[] = -{ - {huff_table_0, 0, no_bits}, - {huff_table_1, 0, one_shot}, - {huff_table_2, 0, one_shot}, - {huff_table_3, 0, one_shot}, - {huff_table_0, 0, no_bits}, - {huff_table_5, 0, one_shot}, - {huff_table_6, 0, one_shot}, - {huff_table_7, 0, no_linbits}, - {huff_table_8, 0, no_linbits}, - {huff_table_9, 0, no_linbits}, - {huff_table_10, 0, no_linbits}, - {huff_table_11, 0, no_linbits}, - {huff_table_12, 0, no_linbits}, - {huff_table_13, 0, no_linbits}, - {huff_table_0, 0, no_bits}, - {huff_table_15, 0, no_linbits}, - {huff_table_16, 1, have_linbits}, - {huff_table_16, 2, have_linbits}, - {huff_table_16, 3, have_linbits}, - {huff_table_16, 4, have_linbits}, - {huff_table_16, 6, have_linbits}, - {huff_table_16, 8, have_linbits}, - {huff_table_16, 10, have_linbits}, - {huff_table_16, 13, have_linbits}, - {huff_table_24, 4, have_linbits}, - {huff_table_24, 5, have_linbits}, - {huff_table_24, 6, have_linbits}, - {huff_table_24, 7, have_linbits}, - {huff_table_24, 8, have_linbits}, - {huff_table_24, 9, have_linbits}, - {huff_table_24, 11, have_linbits}, - {huff_table_24, 13, have_linbits}, - {huff_table_0, 0, quad_a}, - {huff_table_0, 0, quad_b}, +typedef struct { + const HUFF_ELEMENT *table; + int linbits; + int ncase; +} HUFF_SETUP; + +#define no_bits 0 +#define one_shot 1 +#define no_linbits 2 +#define have_linbits 3 +#define quad_a 4 +#define quad_b 5 + +static const HUFF_SETUP table_look[] = { + {huff_table_0, 0, no_bits}, {huff_table_1, 0, one_shot}, {huff_table_2, 0, one_shot}, {huff_table_3, 0, one_shot}, + {huff_table_0, 0, no_bits}, {huff_table_5, 0, one_shot}, {huff_table_6, 0, one_shot}, {huff_table_7, 0, no_linbits}, + {huff_table_8, 0, no_linbits}, {huff_table_9, 0, no_linbits}, {huff_table_10, 0, no_linbits}, {huff_table_11, 0, no_linbits}, + {huff_table_12, 0, no_linbits}, {huff_table_13, 0, no_linbits}, {huff_table_0, 0, no_bits}, {huff_table_15, 0, no_linbits}, + {huff_table_16, 1, have_linbits}, {huff_table_16, 2, have_linbits}, {huff_table_16, 3, have_linbits}, {huff_table_16, 4, have_linbits}, + {huff_table_16, 6, have_linbits}, {huff_table_16, 8, have_linbits}, {huff_table_16, 10, have_linbits}, {huff_table_16, 13, have_linbits}, + {huff_table_24, 4, have_linbits}, {huff_table_24, 5, have_linbits}, {huff_table_24, 6, have_linbits}, {huff_table_24, 7, have_linbits}, + {huff_table_24, 8, have_linbits}, {huff_table_24, 9, have_linbits}, {huff_table_24, 11, have_linbits}, {huff_table_24, 13, have_linbits}, + {huff_table_0, 0, quad_a}, {huff_table_0, 0, quad_b}, }; /*========================================================*/ @@ -131,10 +93,10 @@ static unsigned int bitget(int n) if (bitdat.bits < n) { */ /* refill bit buf if necessary */ /* while (bitdat.bits <= 24) - { + { bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; bitdat.bits += 8; - } + } } bitdat.bits -= n; x = bitdat.bitbuf >> bitdat.bits; @@ -143,42 +105,33 @@ static unsigned int bitget(int n) } */ /*----- get n bits - checks for n+2 avail bits (linbits+sign) -----*/ -static unsigned int bitget_lb(int n) -{ - unsigned int x; - - if (bitdat.bits < (n + 2)) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - bitdat.bits -= n; - x = bitdat.bitbuf >> bitdat.bits; - bitdat.bitbuf -= x << bitdat.bits; - return x; +static unsigned int bitget_lb(int n) { + unsigned int x; + + if (bitdat.bits < (n + 2)) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + bitdat.bits -= n; + x = bitdat.bitbuf >> bitdat.bits; + bitdat.bitbuf -= x << bitdat.bits; + return x; } - - - /*------------- get n bits but DO NOT remove from bitstream --*/ -static unsigned int bitget2(int n) -{ - unsigned int x; - - if (bitdat.bits < (MAXBITS + 2)) - { /* refill bit buf if necessary */ - while (bitdat.bits <= 24) - { - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; - bitdat.bits += 8; - } - } - x = bitdat.bitbuf >> (bitdat.bits - n); - return x; +static unsigned int bitget2(int n) { + unsigned int x; + + if (bitdat.bits < (MAXBITS + 2)) { /* refill bit buf if necessary */ + while (bitdat.bits <= 24) { + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; + bitdat.bits += 8; + } + } + x = bitdat.bitbuf >> (bitdat.bits - n); + return x; } /*------------- remove n bits from bitstream ---------*/ /* unused @@ -202,299 +155,263 @@ static unsigned int bitget_1bit() */ /*========================================================*/ /*========================================================*/ -#define mac_bitget_check(n) if( bitdat.bits < (n) ) { \ - while( bitdat.bits <= 24 ) { \ - bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; \ - bitdat.bits += 8; \ - } \ -} +#define mac_bitget_check(n) \ + if (bitdat.bits < (n)) { \ + while (bitdat.bits <= 24) { \ + bitdat.bitbuf = (bitdat.bitbuf << 8) | *bitdat.bs_ptr++; \ + bitdat.bits += 8; \ + } \ + } /*---------------------------------------------------------*/ -#define mac_bitget2(n) (bitdat.bitbuf >> (bitdat.bits-n)); +#define mac_bitget2(n) (bitdat.bitbuf >> (bitdat.bits - n)); /*---------------------------------------------------------*/ -#define mac_bitget(n) ( bitdat.bits -= n, \ - code = bitdat.bitbuf >> bitdat.bits, \ - bitdat.bitbuf -= code << bitdat.bits, \ - code ) +#define mac_bitget(n) (bitdat.bits -= n, code = bitdat.bitbuf >> bitdat.bits, bitdat.bitbuf -= code << bitdat.bits, code) /*---------------------------------------------------------*/ -#define mac_bitget_purge(n) bitdat.bits -= n, \ - bitdat.bitbuf -= (bitdat.bitbuf >> bitdat.bits) << bitdat.bits; +#define mac_bitget_purge(n) bitdat.bits -= n, bitdat.bitbuf -= (bitdat.bitbuf >> bitdat.bits) << bitdat.bits; /*---------------------------------------------------------*/ -#define mac_bitget_1bit() ( bitdat.bits--, \ - code = bitdat.bitbuf >> bitdat.bits, \ - bitdat.bitbuf -= code << bitdat.bits, \ - code ) +#define mac_bitget_1bit() (bitdat.bits--, code = bitdat.bitbuf >> bitdat.bits, bitdat.bitbuf -= code << bitdat.bits, code) /*========================================================*/ /*========================================================*/ -void unpack_huff(int xy[][2], int n, int ntable) -{ - int i; - const HUFF_ELEMENT *t; - const HUFF_ELEMENT *t0; - int linbits; - int bits; - int code; - int x, y; - - if (n <= 0) - return; - n = n >> 1; /* huff in pairs */ -/*-------------*/ - t0 = table_look[ntable].table; - linbits = table_look[ntable].linbits; - switch (table_look[ntable].ncase) - { - default: -/*------------------------------------------*/ - case no_bits: -/*- table 0, no data, x=y=0--*/ - for (i = 0; i < n; i++) - { - xy[i][0] = 0; - xy[i][1] = 0; - } - return; -/*------------------------------------------*/ - case one_shot: -/*- single lookup, no escapes -*/ - for (i = 0; i < n; i++) - { - mac_bitget_check((MAXBITS + 2)); - bits = t0[0].b.signbits; - code = mac_bitget2(bits); - mac_bitget_purge(t0[1 + code].b.purgebits); - x = t0[1 + code].b.x; - y = t0[1 + code].b.y; - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; -/*------------------------------------------*/ - case no_linbits: - for (i = 0; i < n; i++) - { - t = t0; - for (;;) - { - mac_bitget_check((MAXBITS + 2)); - bits = t[0].b.signbits; - code = mac_bitget2(bits); - if (t[1 + code].b.purgebits) - break; - t += t[1 + code].ptr; /* ptr include 1+code */ - mac_bitget_purge(bits); - } - mac_bitget_purge(t[1 + code].b.purgebits); - x = t[1 + code].b.x; - y = t[1 + code].b.y; - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; -/*------------------------------------------*/ - case have_linbits: - for (i = 0; i < n; i++) - { - t = t0; - for (;;) - { - bits = t[0].b.signbits; - code = bitget2(bits); - if (t[1 + code].b.purgebits) - break; - t += t[1 + code].ptr; /* ptr includes 1+code */ - mac_bitget_purge(bits); - } - mac_bitget_purge(t[1 + code].b.purgebits); - x = t[1 + code].b.x; - y = t[1 + code].b.y; - if (x == 15) - x += bitget_lb(linbits); - if (x) - if (mac_bitget_1bit()) - x = -x; - if (y == 15) - y += bitget_lb(linbits); - if (y) - if (mac_bitget_1bit()) - y = -y; - xy[i][0] = x; - xy[i][1] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - return; - } -/*--- end switch ---*/ - +void unpack_huff(int xy[][2], int n, int ntable) { + int i; + const HUFF_ELEMENT *t; + const HUFF_ELEMENT *t0; + int linbits; + int bits; + int code; + int x, y; + + if (n <= 0) + return; + n = n >> 1; /* huff in pairs */ + /*-------------*/ + t0 = table_look[ntable].table; + linbits = table_look[ntable].linbits; + switch (table_look[ntable].ncase) { + default: + /*------------------------------------------*/ + case no_bits: + /*- table 0, no data, x=y=0--*/ + for (i = 0; i < n; i++) { + xy[i][0] = 0; + xy[i][1] = 0; + } + return; + /*------------------------------------------*/ + case one_shot: + /*- single lookup, no escapes -*/ + for (i = 0; i < n; i++) { + mac_bitget_check((MAXBITS + 2)); + bits = t0[0].b.signbits; + code = mac_bitget2(bits); + mac_bitget_purge(t0[1 + code].b.purgebits); + x = t0[1 + code].b.x; + y = t0[1 + code].b.y; + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + /*------------------------------------------*/ + case no_linbits: + for (i = 0; i < n; i++) { + t = t0; + for (;;) { + mac_bitget_check((MAXBITS + 2)); + bits = t[0].b.signbits; + code = mac_bitget2(bits); + if (t[1 + code].b.purgebits) + break; + t += t[1 + code].ptr; /* ptr include 1+code */ + mac_bitget_purge(bits); + } + mac_bitget_purge(t[1 + code].b.purgebits); + x = t[1 + code].b.x; + y = t[1 + code].b.y; + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + /*------------------------------------------*/ + case have_linbits: + for (i = 0; i < n; i++) { + t = t0; + for (;;) { + bits = t[0].b.signbits; + code = bitget2(bits); + if (t[1 + code].b.purgebits) + break; + t += t[1 + code].ptr; /* ptr includes 1+code */ + mac_bitget_purge(bits); + } + mac_bitget_purge(t[1 + code].b.purgebits); + x = t[1 + code].b.x; + y = t[1 + code].b.y; + if (x == 15) + x += bitget_lb(linbits); + if (x) + if (mac_bitget_1bit()) + x = -x; + if (y == 15) + y += bitget_lb(linbits); + if (y) + if (mac_bitget_1bit()) + y = -y; + xy[i][0] = x; + xy[i][1] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + return; + } + /*--- end switch ---*/ } /*==========================================================*/ -int unpack_huff_quad(int vwxy[][4], int n, int nbits, int ntable) -{ - int i; - int code; - int x, y, v, w; - int tmp; - int i_non_zero, tmp_nz; - - tmp_nz = 15; - i_non_zero = -1; - - n = n >> 2; /* huff in quads */ - - if (ntable) - goto case_quad_b; - -/* case_quad_a: */ - for (i = 0; i < n; i++) - { - if (nbits <= 0) - break; - mac_bitget_check(10); - code = mac_bitget2(6); - nbits -= quad_table_a[code][0]; - mac_bitget_purge(quad_table_a[code][0]); - tmp = quad_table_a[code][1]; - if (tmp) - { - i_non_zero = i; - tmp_nz = tmp; - } - v = (tmp >> 3) & 1; - w = (tmp >> 2) & 1; - x = (tmp >> 1) & 1; - y = tmp & 1; - if (v) - { - if (mac_bitget_1bit()) - v = -v; - nbits--; - } - if (w) - { - if (mac_bitget_1bit()) - w = -w; - nbits--; - } - if (x) - { - if (mac_bitget_1bit()) - x = -x; - nbits--; - } - if (y) - { - if (mac_bitget_1bit()) - y = -y; - nbits--; - } - vwxy[i][0] = v; - vwxy[i][1] = w; - vwxy[i][2] = x; - vwxy[i][3] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - if (i && nbits < 0) - { - i--; - vwxy[i][0] = 0; - vwxy[i][1] = 0; - vwxy[i][2] = 0; - vwxy[i][3] = 0; - } - - i_non_zero = (i_non_zero + 1) << 2; - - if ((tmp_nz & 3) == 0) - i_non_zero -= 2; - - return i_non_zero; - -/*--------------------*/ - case_quad_b: - for (i = 0; i < n; i++) - { - if (nbits < 4) - break; - nbits -= 4; - mac_bitget_check(8); - tmp = mac_bitget(4) ^ 15; /* one's complement of bitstream */ - if (tmp) - { - i_non_zero = i; - tmp_nz = tmp; - } - v = (tmp >> 3) & 1; - w = (tmp >> 2) & 1; - x = (tmp >> 1) & 1; - y = tmp & 1; - if (v) - { - if (mac_bitget_1bit()) - v = -v; - nbits--; - } - if (w) - { - if (mac_bitget_1bit()) - w = -w; - nbits--; - } - if (x) - { - if (mac_bitget_1bit()) - x = -x; - nbits--; - } - if (y) - { - if (mac_bitget_1bit()) - y = -y; - nbits--; - } - vwxy[i][0] = v; - vwxy[i][1] = w; - vwxy[i][2] = x; - vwxy[i][3] = y; - if (bitdat.bs_ptr > bitdat.bs_ptr_end) - break; // bad data protect - - } - if (nbits < 0) - { - i--; - vwxy[i][0] = 0; - vwxy[i][1] = 0; - vwxy[i][2] = 0; - vwxy[i][3] = 0; - } - - i_non_zero = (i_non_zero + 1) << 2; - - if ((tmp_nz & 3) == 0) - i_non_zero -= 2; - - return i_non_zero; /* return non-zero sample (to nearest pair) */ - +int unpack_huff_quad(int vwxy[][4], int n, int nbits, int ntable) { + int i; + int code; + int x, y, v, w; + int tmp; + int i_non_zero, tmp_nz; + + tmp_nz = 15; + i_non_zero = -1; + + n = n >> 2; /* huff in quads */ + + if (ntable) + goto case_quad_b; + + /* case_quad_a: */ + for (i = 0; i < n; i++) { + if (nbits <= 0) + break; + mac_bitget_check(10); + code = mac_bitget2(6); + nbits -= quad_table_a[code][0]; + mac_bitget_purge(quad_table_a[code][0]); + tmp = quad_table_a[code][1]; + if (tmp) { + i_non_zero = i; + tmp_nz = tmp; + } + v = (tmp >> 3) & 1; + w = (tmp >> 2) & 1; + x = (tmp >> 1) & 1; + y = tmp & 1; + if (v) { + if (mac_bitget_1bit()) + v = -v; + nbits--; + } + if (w) { + if (mac_bitget_1bit()) + w = -w; + nbits--; + } + if (x) { + if (mac_bitget_1bit()) + x = -x; + nbits--; + } + if (y) { + if (mac_bitget_1bit()) + y = -y; + nbits--; + } + vwxy[i][0] = v; + vwxy[i][1] = w; + vwxy[i][2] = x; + vwxy[i][3] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + if (i && nbits < 0) { + i--; + vwxy[i][0] = 0; + vwxy[i][1] = 0; + vwxy[i][2] = 0; + vwxy[i][3] = 0; + } + + i_non_zero = (i_non_zero + 1) << 2; + + if ((tmp_nz & 3) == 0) + i_non_zero -= 2; + + return i_non_zero; + + /*--------------------*/ +case_quad_b: + for (i = 0; i < n; i++) { + if (nbits < 4) + break; + nbits -= 4; + mac_bitget_check(8); + tmp = mac_bitget(4) ^ 15; /* one's complement of bitstream */ + if (tmp) { + i_non_zero = i; + tmp_nz = tmp; + } + v = (tmp >> 3) & 1; + w = (tmp >> 2) & 1; + x = (tmp >> 1) & 1; + y = tmp & 1; + if (v) { + if (mac_bitget_1bit()) + v = -v; + nbits--; + } + if (w) { + if (mac_bitget_1bit()) + w = -w; + nbits--; + } + if (x) { + if (mac_bitget_1bit()) + x = -x; + nbits--; + } + if (y) { + if (mac_bitget_1bit()) + y = -y; + nbits--; + } + vwxy[i][0] = v; + vwxy[i][1] = w; + vwxy[i][2] = x; + vwxy[i][3] = y; + if (bitdat.bs_ptr > bitdat.bs_ptr_end) + break; // bad data protect + } + if (nbits < 0) { + i--; + vwxy[i][0] = 0; + vwxy[i][1] = 0; + vwxy[i][2] = 0; + vwxy[i][3] = 0; + } + + i_non_zero = (i_non_zero + 1) << 2; + + if ((tmp_nz & 3) == 0) + i_non_zero -= 2; + + return i_non_zero; /* return non-zero sample (to nearest pair) */ } /*-----------------------------------------------------*/ diff --git a/codemp/mp3code/upsf.c b/codemp/mp3code/upsf.c index da3d311ae4..4e05115667 100644 --- a/codemp/mp3code/upsf.c +++ b/codemp/mp3code/upsf.c @@ -2,8 +2,8 @@ FreeAmp - The Free MP3 Player - MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology - Corp. http://www.xingtech.com + MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology + Corp. http://www.xingtech.com Portions Copyright (C) 1998-1999 EMusic.com @@ -27,7 +27,7 @@ ____________________________________________________________________________*/ /**** upsf.c *************************************************** Layer III - unpack scale factors + unpack scale factors @@ -42,361 +42,292 @@ Layer III unsigned int bitget(int n); /*------------------------------------------------------------*/ -static const int slen_table[16][2] = -{ - {0, 0}, {0, 1}, - {0, 2}, {0, 3}, - {3, 0}, {1, 1}, - {1, 2}, {1, 3}, - {2, 1}, {2, 2}, - {2, 3}, {3, 1}, - {3, 2}, {3, 3}, - {4, 2}, {4, 3}, +static const int slen_table[16][2] = { + {0, 0}, {0, 1}, {0, 2}, {0, 3}, {3, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 2}, {4, 3}, }; /* nr_table[size+3*is_right][block type 0,1,3 2, 2+mixed][4] */ /* for bt=2 nr is count for group of 3 */ -static const int nr_table[6][3][4] = -{ - {{6, 5, 5, 5}, - {3, 3, 3, 3}, - {6, 3, 3, 3}}, - - {{6, 5, 7, 3}, - {3, 3, 4, 2}, - {6, 3, 4, 2}}, - - {{11, 10, 0, 0}, - {6, 6, 0, 0}, - {6, 3, 6, 0}}, /* adjusted *//* 15, 18, 0, 0, */ -/*-intensity stereo right chan--*/ - {{7, 7, 7, 0}, - {4, 4, 4, 0}, - {6, 5, 4, 0}}, - - {{6, 6, 6, 3}, - {4, 3, 3, 2}, - {6, 4, 3, 2}}, - - {{8, 8, 5, 0}, - {5, 4, 3, 0}, - {6, 6, 3, 0}}, +static const int nr_table[6][3][4] = { + {{6, 5, 5, 5}, {3, 3, 3, 3}, {6, 3, 3, 3}}, + + {{6, 5, 7, 3}, {3, 3, 4, 2}, {6, 3, 4, 2}}, + + {{11, 10, 0, 0}, {6, 6, 0, 0}, {6, 3, 6, 0}}, + /* adjusted */ /* 15, 18, 0, 0, */ + /*-intensity stereo right chan--*/ + {{7, 7, 7, 0}, {4, 4, 4, 0}, {6, 5, 4, 0}}, + + {{6, 6, 6, 3}, {4, 3, 3, 2}, {6, 4, 3, 2}}, + + {{8, 8, 5, 0}, {5, 4, 3, 0}, {6, 6, 3, 0}}, }; /*=============================================================*/ -void unpack_sf_sub_MPEG1(SCALEFACT sf[], - GR * grdat, - int scfsi, /* bit flag */ - int gr) -{ - int sfb; - int slen0, slen1; - int block_type, mixed_block_flag, scalefac_compress; - - - block_type = grdat->block_type; - mixed_block_flag = grdat->mixed_block_flag; - scalefac_compress = grdat->scalefac_compress; - - slen0 = slen_table[scalefac_compress][0]; - slen1 = slen_table[scalefac_compress][1]; - - - if (block_type == 2) - { - if (mixed_block_flag) - { /* mixed */ - for (sfb = 0; sfb < 8; sfb++) - sf[0].l[sfb] = bitget(slen0); - for (sfb = 3; sfb < 6; sfb++) - { - sf[0].s[0][sfb] = bitget(slen0); - sf[0].s[1][sfb] = bitget(slen0); - sf[0].s[2][sfb] = bitget(slen0); - } - for (sfb = 6; sfb < 12; sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - return; - } - for (sfb = 0; sfb < 6; sfb++) - { - sf[0].s[0][sfb] = bitget(slen0); - sf[0].s[1][sfb] = bitget(slen0); - sf[0].s[2][sfb] = bitget(slen0); - } - for (; sfb < 12; sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - return; - } - -/* long blocks types 0 1 3, first granule */ - if (gr == 0) - { - for (sfb = 0; sfb < 11; sfb++) - sf[0].l[sfb] = bitget(slen0); - for (; sfb < 21; sfb++) - sf[0].l[sfb] = bitget(slen1); - return; - } - -/* long blocks 0, 1, 3, second granule */ - sfb = 0; - if (scfsi & 8) - for (; sfb < 6; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 6; sfb++) - sf[0].l[sfb] = bitget(slen0); - if (scfsi & 4) - for (; sfb < 11; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 11; sfb++) - sf[0].l[sfb] = bitget(slen0); - if (scfsi & 2) - for (; sfb < 16; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 16; sfb++) - sf[0].l[sfb] = bitget(slen1); - if (scfsi & 1) - for (; sfb < 21; sfb++) - sf[0].l[sfb] = sf[-2].l[sfb]; - else - for (; sfb < 21; sfb++) - sf[0].l[sfb] = bitget(slen1); - - - - return; +void unpack_sf_sub_MPEG1(SCALEFACT sf[], GR *grdat, int scfsi, /* bit flag */ + int gr) { + int sfb; + int slen0, slen1; + int block_type, mixed_block_flag, scalefac_compress; + + block_type = grdat->block_type; + mixed_block_flag = grdat->mixed_block_flag; + scalefac_compress = grdat->scalefac_compress; + + slen0 = slen_table[scalefac_compress][0]; + slen1 = slen_table[scalefac_compress][1]; + + if (block_type == 2) { + if (mixed_block_flag) { /* mixed */ + for (sfb = 0; sfb < 8; sfb++) + sf[0].l[sfb] = bitget(slen0); + for (sfb = 3; sfb < 6; sfb++) { + sf[0].s[0][sfb] = bitget(slen0); + sf[0].s[1][sfb] = bitget(slen0); + sf[0].s[2][sfb] = bitget(slen0); + } + for (sfb = 6; sfb < 12; sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + return; + } + for (sfb = 0; sfb < 6; sfb++) { + sf[0].s[0][sfb] = bitget(slen0); + sf[0].s[1][sfb] = bitget(slen0); + sf[0].s[2][sfb] = bitget(slen0); + } + for (; sfb < 12; sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + return; + } + + /* long blocks types 0 1 3, first granule */ + if (gr == 0) { + for (sfb = 0; sfb < 11; sfb++) + sf[0].l[sfb] = bitget(slen0); + for (; sfb < 21; sfb++) + sf[0].l[sfb] = bitget(slen1); + return; + } + + /* long blocks 0, 1, 3, second granule */ + sfb = 0; + if (scfsi & 8) + for (; sfb < 6; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 6; sfb++) + sf[0].l[sfb] = bitget(slen0); + if (scfsi & 4) + for (; sfb < 11; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 11; sfb++) + sf[0].l[sfb] = bitget(slen0); + if (scfsi & 2) + for (; sfb < 16; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 16; sfb++) + sf[0].l[sfb] = bitget(slen1); + if (scfsi & 1) + for (; sfb < 21; sfb++) + sf[0].l[sfb] = sf[-2].l[sfb]; + else + for (; sfb < 21; sfb++) + sf[0].l[sfb] = bitget(slen1); + + return; } /*=============================================================*/ -void unpack_sf_sub_MPEG2(SCALEFACT sf[], - GR * grdat, - int is_and_ch, IS_SF_INFO * sf_info) -{ - int sfb; - int slen1, slen2, slen3, slen4; - int nr1, nr2, nr3, nr4; - int i, k; - int preflag, intensity_scale; - int block_type, mixed_block_flag, scalefac_compress; - - - block_type = grdat->block_type; - mixed_block_flag = grdat->mixed_block_flag; - scalefac_compress = grdat->scalefac_compress; - - preflag = 0; - intensity_scale = 0; /* to avoid compiler warning */ - if (is_and_ch == 0) - { - if (scalefac_compress < 400) - { - slen2 = scalefac_compress >> 4; - slen1 = slen2 / 5; - slen2 = slen2 % 5; - slen4 = scalefac_compress & 15; - slen3 = slen4 >> 2; - slen4 = slen4 & 3; - k = 0; - } - else if (scalefac_compress < 500) - { - scalefac_compress -= 400; - slen2 = scalefac_compress >> 2; - slen1 = slen2 / 5; - slen2 = slen2 % 5; - slen3 = scalefac_compress & 3; - slen4 = 0; - k = 1; - } - else - { - scalefac_compress -= 500; - slen1 = scalefac_compress / 3; - slen2 = scalefac_compress % 3; - slen3 = slen4 = 0; - if (mixed_block_flag) - { - slen3 = slen2; /* adjust for long/short mix logic */ - slen2 = slen1; - } - preflag = 1; - k = 2; - } - } - else - { /* intensity stereo ch = 1 (right) */ - intensity_scale = scalefac_compress & 1; - scalefac_compress >>= 1; - if (scalefac_compress < 180) - { - slen1 = scalefac_compress / 36; - slen2 = scalefac_compress % 36; - slen3 = slen2 % 6; - slen2 = slen2 / 6; - slen4 = 0; - k = 3 + 0; - } - else if (scalefac_compress < 244) - { - scalefac_compress -= 180; - slen3 = scalefac_compress & 3; - scalefac_compress >>= 2; - slen2 = scalefac_compress & 3; - slen1 = scalefac_compress >> 2; - slen4 = 0; - k = 3 + 1; - } - else - { - scalefac_compress -= 244; - slen1 = scalefac_compress / 3; - slen2 = scalefac_compress % 3; - slen3 = slen4 = 0; - k = 3 + 2; - } - } - - i = 0; - if (block_type == 2) - i = (mixed_block_flag & 1) + 1; - nr1 = nr_table[k][i][0]; - nr2 = nr_table[k][i][1]; - nr3 = nr_table[k][i][2]; - nr4 = nr_table[k][i][3]; - - -/* return is scale factor info (for right chan is mode) */ - if (is_and_ch) - { - sf_info->nr[0] = nr1; - sf_info->nr[1] = nr2; - sf_info->nr[2] = nr3; - sf_info->slen[0] = slen1; - sf_info->slen[1] = slen2; - sf_info->slen[2] = slen3; - sf_info->intensity_scale = intensity_scale; - } - grdat->preflag = preflag; /* return preflag */ - -/*--------------------------------------*/ - if (block_type == 2) - { - if (mixed_block_flag) - { /* mixed */ - if (slen1 != 0) /* long block portion */ - for (sfb = 0; sfb < 6; sfb++) - sf[0].l[sfb] = bitget(slen1); - else - for (sfb = 0; sfb < 6; sfb++) - sf[0].l[sfb] = 0; - sfb = 3; /* start sfb for short */ - } - else - { /* all short, initial short blocks */ - sfb = 0; - if (slen1 != 0) - for (i = 0; i < nr1; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen1); - sf[0].s[1][sfb] = bitget(slen1); - sf[0].s[2][sfb] = bitget(slen1); - } - else - for (i = 0; i < nr1; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - } -/* remaining short blocks */ - if (slen2 != 0) - for (i = 0; i < nr2; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen2); - sf[0].s[1][sfb] = bitget(slen2); - sf[0].s[2][sfb] = bitget(slen2); - } - else - for (i = 0; i < nr2; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - if (slen3 != 0) - for (i = 0; i < nr3; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen3); - sf[0].s[1][sfb] = bitget(slen3); - sf[0].s[2][sfb] = bitget(slen3); - } - else - for (i = 0; i < nr3; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - if (slen4 != 0) - for (i = 0; i < nr4; i++, sfb++) - { - sf[0].s[0][sfb] = bitget(slen4); - sf[0].s[1][sfb] = bitget(slen4); - sf[0].s[2][sfb] = bitget(slen4); - } - else - for (i = 0; i < nr4; i++, sfb++) - { - sf[0].s[0][sfb] = 0; - sf[0].s[1][sfb] = 0; - sf[0].s[2][sfb] = 0; - } - return; - } - - -/* long blocks types 0 1 3 */ - sfb = 0; - if (slen1 != 0) - for (i = 0; i < nr1; i++, sfb++) - sf[0].l[sfb] = bitget(slen1); - else - for (i = 0; i < nr1; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen2 != 0) - for (i = 0; i < nr2; i++, sfb++) - sf[0].l[sfb] = bitget(slen2); - else - for (i = 0; i < nr2; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen3 != 0) - for (i = 0; i < nr3; i++, sfb++) - sf[0].l[sfb] = bitget(slen3); - else - for (i = 0; i < nr3; i++, sfb++) - sf[0].l[sfb] = 0; - - if (slen4 != 0) - for (i = 0; i < nr4; i++, sfb++) - sf[0].l[sfb] = bitget(slen4); - else - for (i = 0; i < nr4; i++, sfb++) - sf[0].l[sfb] = 0; - - +void unpack_sf_sub_MPEG2(SCALEFACT sf[], GR *grdat, int is_and_ch, IS_SF_INFO *sf_info) { + int sfb; + int slen1, slen2, slen3, slen4; + int nr1, nr2, nr3, nr4; + int i, k; + int preflag, intensity_scale; + int block_type, mixed_block_flag, scalefac_compress; + + block_type = grdat->block_type; + mixed_block_flag = grdat->mixed_block_flag; + scalefac_compress = grdat->scalefac_compress; + + preflag = 0; + intensity_scale = 0; /* to avoid compiler warning */ + if (is_and_ch == 0) { + if (scalefac_compress < 400) { + slen2 = scalefac_compress >> 4; + slen1 = slen2 / 5; + slen2 = slen2 % 5; + slen4 = scalefac_compress & 15; + slen3 = slen4 >> 2; + slen4 = slen4 & 3; + k = 0; + } else if (scalefac_compress < 500) { + scalefac_compress -= 400; + slen2 = scalefac_compress >> 2; + slen1 = slen2 / 5; + slen2 = slen2 % 5; + slen3 = scalefac_compress & 3; + slen4 = 0; + k = 1; + } else { + scalefac_compress -= 500; + slen1 = scalefac_compress / 3; + slen2 = scalefac_compress % 3; + slen3 = slen4 = 0; + if (mixed_block_flag) { + slen3 = slen2; /* adjust for long/short mix logic */ + slen2 = slen1; + } + preflag = 1; + k = 2; + } + } else { /* intensity stereo ch = 1 (right) */ + intensity_scale = scalefac_compress & 1; + scalefac_compress >>= 1; + if (scalefac_compress < 180) { + slen1 = scalefac_compress / 36; + slen2 = scalefac_compress % 36; + slen3 = slen2 % 6; + slen2 = slen2 / 6; + slen4 = 0; + k = 3 + 0; + } else if (scalefac_compress < 244) { + scalefac_compress -= 180; + slen3 = scalefac_compress & 3; + scalefac_compress >>= 2; + slen2 = scalefac_compress & 3; + slen1 = scalefac_compress >> 2; + slen4 = 0; + k = 3 + 1; + } else { + scalefac_compress -= 244; + slen1 = scalefac_compress / 3; + slen2 = scalefac_compress % 3; + slen3 = slen4 = 0; + k = 3 + 2; + } + } + + i = 0; + if (block_type == 2) + i = (mixed_block_flag & 1) + 1; + nr1 = nr_table[k][i][0]; + nr2 = nr_table[k][i][1]; + nr3 = nr_table[k][i][2]; + nr4 = nr_table[k][i][3]; + + /* return is scale factor info (for right chan is mode) */ + if (is_and_ch) { + sf_info->nr[0] = nr1; + sf_info->nr[1] = nr2; + sf_info->nr[2] = nr3; + sf_info->slen[0] = slen1; + sf_info->slen[1] = slen2; + sf_info->slen[2] = slen3; + sf_info->intensity_scale = intensity_scale; + } + grdat->preflag = preflag; /* return preflag */ + + /*--------------------------------------*/ + if (block_type == 2) { + if (mixed_block_flag) { /* mixed */ + if (slen1 != 0) /* long block portion */ + for (sfb = 0; sfb < 6; sfb++) + sf[0].l[sfb] = bitget(slen1); + else + for (sfb = 0; sfb < 6; sfb++) + sf[0].l[sfb] = 0; + sfb = 3; /* start sfb for short */ + } else { /* all short, initial short blocks */ + sfb = 0; + if (slen1 != 0) + for (i = 0; i < nr1; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen1); + sf[0].s[1][sfb] = bitget(slen1); + sf[0].s[2][sfb] = bitget(slen1); + } + else + for (i = 0; i < nr1; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + } + /* remaining short blocks */ + if (slen2 != 0) + for (i = 0; i < nr2; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen2); + sf[0].s[1][sfb] = bitget(slen2); + sf[0].s[2][sfb] = bitget(slen2); + } + else + for (i = 0; i < nr2; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + if (slen3 != 0) + for (i = 0; i < nr3; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen3); + sf[0].s[1][sfb] = bitget(slen3); + sf[0].s[2][sfb] = bitget(slen3); + } + else + for (i = 0; i < nr3; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + if (slen4 != 0) + for (i = 0; i < nr4; i++, sfb++) { + sf[0].s[0][sfb] = bitget(slen4); + sf[0].s[1][sfb] = bitget(slen4); + sf[0].s[2][sfb] = bitget(slen4); + } + else + for (i = 0; i < nr4; i++, sfb++) { + sf[0].s[0][sfb] = 0; + sf[0].s[1][sfb] = 0; + sf[0].s[2][sfb] = 0; + } + return; + } + + /* long blocks types 0 1 3 */ + sfb = 0; + if (slen1 != 0) + for (i = 0; i < nr1; i++, sfb++) + sf[0].l[sfb] = bitget(slen1); + else + for (i = 0; i < nr1; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen2 != 0) + for (i = 0; i < nr2; i++, sfb++) + sf[0].l[sfb] = bitget(slen2); + else + for (i = 0; i < nr2; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen3 != 0) + for (i = 0; i < nr3; i++, sfb++) + sf[0].l[sfb] = bitget(slen3); + else + for (i = 0; i < nr3; i++, sfb++) + sf[0].l[sfb] = 0; + + if (slen4 != 0) + for (i = 0; i < nr4; i++, sfb++) + sf[0].l[sfb] = bitget(slen4); + else + for (i = 0; i < nr4; i++, sfb++) + sf[0].l[sfb] = 0; } /*-------------------------------------------------*/ diff --git a/codemp/null/null_client.cpp b/codemp/null/null_client.cpp index a0bafab5fa..6e924dc236 100644 --- a/codemp/null/null_client.cpp +++ b/codemp/null/null_client.cpp @@ -25,63 +25,40 @@ along with this program; if not, see . cvar_t *cl_shownet; -void CL_Shutdown( void ) { -} +void CL_Shutdown(void) {} -void CL_Init( void ) { - cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); -} +void CL_Init(void) { cl_shownet = Cvar_Get("cl_shownet", "0", CVAR_TEMP); } -void CL_MouseEvent( int dx, int dy, int time ) { -} +void CL_MouseEvent(int dx, int dy, int time) {} -void Key_WriteBindings( fileHandle_t f ) { -} +void Key_WriteBindings(fileHandle_t f) {} -void CL_Frame ( int msec ) { -} +void CL_Frame(int msec) {} -void CL_PacketEvent( netadr_t from, msg_t *msg ) { -} +void CL_PacketEvent(netadr_t from, msg_t *msg) {} -void CL_CharEvent( int key ) { -} +void CL_CharEvent(int key) {} -void CL_Disconnect( qboolean showMainMenu ) { -} +void CL_Disconnect(qboolean showMainMenu) {} -void CL_MapLoading( void ) { -} +void CL_MapLoading(void) {} -qboolean CL_GameCommand( void ) { - return qfalse; -} +qboolean CL_GameCommand(void) { return qfalse; } -void CL_KeyEvent (int key, qboolean down, unsigned time) { -} +void CL_KeyEvent(int key, qboolean down, unsigned time) {} -qboolean UI_GameCommand( void ) { - return qfalse; -} +qboolean UI_GameCommand(void) { return qfalse; } -void CL_ForwardCommandToServer( const char *string ) { -} +void CL_ForwardCommandToServer(const char *string) {} -void CL_ConsolePrint( const char *txt ) { -} +void CL_ConsolePrint(const char *txt) {} -void CL_JoystickEvent( int axis, int value, int time ) { -} +void CL_JoystickEvent(int axis, int value, int time) {} -void CL_InitKeyCommands( void ) { -} +void CL_InitKeyCommands(void) {} -void CL_FlushMemory( void ) { -} +void CL_FlushMemory(void) {} -void CL_StartHunkUsers( void ) { -} +void CL_StartHunkUsers(void) {} -qboolean CL_ConnectedToRemoteServer( void ) { - return qfalse; -} +qboolean CL_ConnectedToRemoteServer(void) { return qfalse; } diff --git a/codemp/null/null_input.cpp b/codemp/null/null_input.cpp index 855d915650..90d653a307 100644 --- a/codemp/null/null_input.cpp +++ b/codemp/null/null_input.cpp @@ -21,14 +21,10 @@ along with this program; if not, see . =========================================================================== */ -void IN_Init( void ) { -} +void IN_Init(void) {} -void IN_Frame (void) { -} +void IN_Frame(void) {} -void IN_Shutdown( void ) { -} +void IN_Shutdown(void) {} -void IN_Restart( void ) { -} +void IN_Restart(void) {} diff --git a/codemp/null/null_renderer.cpp b/codemp/null/null_renderer.cpp index 0e825399ab..7f8b69812b 100644 --- a/codemp/null/null_renderer.cpp +++ b/codemp/null/null_renderer.cpp @@ -23,14 +23,8 @@ along with this program; if not, see . /* Null renderer functions */ -void RB_StageIteratorGeneric(void) -{ -} +void RB_StageIteratorGeneric(void) {} -void RB_StageIteratorSky(void) -{ -} +void RB_StageIteratorSky(void) {} -void R_IssuePendingRenderCommands(void) -{ -} +void R_IssuePendingRenderCommands(void) {} diff --git a/codemp/null/null_snddma.cpp b/codemp/null/null_snddma.cpp index a13533e35b..cdf57c85ec 100644 --- a/codemp/null/null_snddma.cpp +++ b/codemp/null/null_snddma.cpp @@ -28,44 +28,22 @@ along with this program; if not, see . qboolean gbInsideLoadSound = qfalse; // important to default to this!!! -qboolean SNDDMA_Init(void) -{ - return qfalse; -} - -int SNDDMA_GetDMAPos(void) -{ - return 0; -} - -void SNDDMA_Shutdown(void) -{ -} - -void SNDDMA_BeginPainting (void) -{ -} - -void SNDDMA_Submit(void) -{ -} - -sfxHandle_t S_RegisterSound( const char *name ) { - return 0; -} - -void S_StartLocalSound( sfxHandle_t sfxHandle, int channelNum ) { -} - -void S_ClearSoundBuffer( void ) { -} - -qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel) -{ - return qfalse; -} - -int SND_FreeOldestSound(void) -{ - return 0; -} +qboolean SNDDMA_Init(void) { return qfalse; } + +int SNDDMA_GetDMAPos(void) { return 0; } + +void SNDDMA_Shutdown(void) {} + +void SNDDMA_BeginPainting(void) {} + +void SNDDMA_Submit(void) {} + +sfxHandle_t S_RegisterSound(const char *name) { return 0; } + +void S_StartLocalSound(sfxHandle_t sfxHandle, int channelNum) {} + +void S_ClearSoundBuffer(void) {} + +qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel) { return qfalse; } + +int SND_FreeOldestSound(void) { return 0; } diff --git a/codemp/qcommon/GenericParser2.cpp b/codemp/qcommon/GenericParser2.cpp index 37f7916bf4..2844d2bbd9 100644 --- a/codemp/qcommon/GenericParser2.cpp +++ b/codemp/qcommon/GenericParser2.cpp @@ -25,45 +25,37 @@ along with this program; if not, see . #include #include "qcommon/qcommon.h" -#define MAX_TOKEN_SIZE 1024 -static char token[MAX_TOKEN_SIZE]; +#define MAX_TOKEN_SIZE 1024 +static char token[MAX_TOKEN_SIZE]; -static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = false) -{ - char *pointer = *text; - int length = 0; - int c = 0; - bool foundLineBreak; +static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = false) { + char *pointer = *text; + int length = 0; + int c = 0; + bool foundLineBreak; token[0] = 0; - if (!pointer) - { + if (!pointer) { return token; } - while(1) - { + while (1) { foundLineBreak = false; - while(1) - { + while (1) { c = *pointer; - if (c > ' ') - { + if (c > ' ') { break; } - if (!c) - { + if (!c) { *text = 0; return token; } - if (c == '\n') - { + if (c == '\n') { foundLineBreak = true; } pointer++; } - if (foundLineBreak && !allowLineBreaks) - { + if (foundLineBreak && !allowLineBreaks) { *text = pointer; return token; } @@ -71,83 +63,59 @@ static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = fal c = *pointer; // skip single line comment - if (c == '/' && pointer[1] == '/') - { + if (c == '/' && pointer[1] == '/') { pointer += 2; - while (*pointer && *pointer != '\n') - { + while (*pointer && *pointer != '\n') { pointer++; } } // skip multi line comments - else if (c == '/' && pointer[1] == '*') - { + else if (c == '/' && pointer[1] == '*') { pointer += 2; - while (*pointer && (*pointer != '*' || pointer[1] != '/')) - { + while (*pointer && (*pointer != '*' || pointer[1] != '/')) { pointer++; } - if (*pointer) - { + if (*pointer) { pointer += 2; } - } - else - { // found the start of a token + } else { // found the start of a token break; } } - if (c == '\"') - { // handle a string + if (c == '\"') { // handle a string pointer++; - while (1) - { + while (1) { c = *pointer++; - if (c == '\"') - { -// token[length++] = c; + if (c == '\"') { + // token[length++] = c; break; - } - else if (!c) - { + } else if (!c) { break; - } - else if (length < MAX_TOKEN_SIZE) - { + } else if (length < MAX_TOKEN_SIZE) { token[length++] = c; } } - } - else if (readUntilEOL) - { + } else if (readUntilEOL) { // absorb all characters until EOL - while(c != '\n' && c != '\r') - { - if (c == '/' && ((*(pointer+1)) == '/' || (*(pointer+1)) == '*')) - { + while (c != '\n' && c != '\r') { + if (c == '/' && ((*(pointer + 1)) == '/' || (*(pointer + 1)) == '*')) { break; } - if (length < MAX_TOKEN_SIZE) - { + if (length < MAX_TOKEN_SIZE) { token[length++] = c; } pointer++; c = *pointer; } // remove trailing white space - while(length && token[length-1] < ' ') - { + while (length && token[length - 1] < ' ') { length--; } - } - else - { - while(c > ' ') - { - if (length < MAX_TOKEN_SIZE) - { + } else { + while (c > ' ') { + if (length < MAX_TOKEN_SIZE) { token[length++] = c; } pointer++; @@ -155,19 +123,16 @@ static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = fal } } - if (token[0] == '\"') - { // remove start quote + if (token[0] == '\"') { // remove start quote length--; - memmove(token, token+1, length); + memmove(token, token + 1, length); - if (length && token[length-1] == '\"') - { // remove end quote + if (length && token[length - 1] == '\"') { // remove end quote length--; } } - if (length >= MAX_TOKEN_SIZE) - { + if (length >= MAX_TOKEN_SIZE) { length = 0; } token[length] = 0; @@ -176,28 +141,18 @@ static char *GetToken(char **text, bool allowLineBreaks, bool readUntilEOL = fal return token; } -CTextPool::CTextPool(int initSize) : - mNext(0), - mSize(initSize), - mUsed(0) -{ -// mPool = (char *)Z_Malloc(mSize, TAG_GP2); +CTextPool::CTextPool(int initSize) : mNext(0), mSize(initSize), mUsed(0) { + // mPool = (char *)Z_Malloc(mSize, TAG_GP2); mPool = (char *)Z_Malloc(mSize, TAG_TEXTPOOL, qtrue); } -CTextPool::~CTextPool(void) -{ - Z_Free(mPool); -} +CTextPool::~CTextPool(void) { Z_Free(mPool); } -char *CTextPool::AllocText(char *text, bool addNULL, CTextPool **poolPtr) -{ - int length = strlen(text) + (addNULL ? 1 : 0); +char *CTextPool::AllocText(char *text, bool addNULL, CTextPool **poolPtr) { + int length = strlen(text) + (addNULL ? 1 : 0); - if (mUsed + length + 1> mSize) - { // extra 1 to put a null on the end - if (poolPtr) - { + if (mUsed + length + 1 > mSize) { // extra 1 to put a null on the end + if (poolPtr) { (*poolPtr)->SetNext(new CTextPool(mSize)); *poolPtr = (*poolPtr)->GetNext(); @@ -214,108 +169,63 @@ char *CTextPool::AllocText(char *text, bool addNULL, CTextPool **poolPtr) return mPool + mUsed - length; } -void CleanTextPool(CTextPool *pool) -{ +void CleanTextPool(CTextPool *pool) { CTextPool *next; - while(pool) - { + while (pool) { next = pool->GetNext(); delete pool; pool = next; } } +CGPObject::CGPObject(const char *initName) : mName(initName), mNext(0), mInOrderNext(0), mInOrderPrevious(0) {} +bool CGPObject::WriteText(CTextPool **textPool, const char *text) { + if (strchr(text, ' ') || !text[0]) { + (*textPool)->AllocText("\"", false, textPool); + (*textPool)->AllocText((char *)text, false, textPool); + (*textPool)->AllocText("\"", false, textPool); + } else { + (*textPool)->AllocText((char *)text, false, textPool); + } - - - - -CGPObject::CGPObject(const char *initName) : - mName(initName), - mNext(0), - mInOrderNext(0), - mInOrderPrevious(0) -{ -} - -bool CGPObject::WriteText(CTextPool **textPool, const char *text) -{ - if (strchr(text, ' ') || !text[0]) - { - (*textPool)->AllocText("\"", false, textPool); - (*textPool)->AllocText((char *)text, false, textPool); - (*textPool)->AllocText("\"", false, textPool); - } - else - { - (*textPool)->AllocText((char *)text, false, textPool); - } - - return true; + return true; } - - - - - - - - - - - - - -CGPValue::CGPValue(const char *initName, const char *initValue) : - CGPObject(initName), - mList(0) -{ - if (initValue) - { +CGPValue::CGPValue(const char *initName, const char *initValue) : CGPObject(initName), mList(0) { + if (initValue) { AddValue(initValue); } } -CGPValue::~CGPValue(void) -{ - CGPObject *next; +CGPValue::~CGPValue(void) { + CGPObject *next; - while(mList) - { + while (mList) { next = mList->GetNext(); delete mList; mList = next; } } -CGPValue *CGPValue::Duplicate(CTextPool **textPool) -{ - CGPValue *newValue; - CGPObject *iterator; - char *name; +CGPValue *CGPValue::Duplicate(CTextPool **textPool) { + CGPValue *newValue; + CGPObject *iterator; + char *name; - if (textPool) - { + if (textPool) { name = (*textPool)->AllocText((char *)mName, true, textPool); - } - else - { + } else { name = (char *)mName; } newValue = new CGPValue(name); iterator = mList; - while(iterator) - { - if (textPool) - { + while (iterator) { + if (textPool) { name = (*textPool)->AllocText((char *)iterator->GetName(), true, textPool); - } - else - { + } else { name = (char *)iterator->GetName(); } newValue->AddValue(name); @@ -325,60 +235,46 @@ CGPValue *CGPValue::Duplicate(CTextPool **textPool) return newValue; } -bool CGPValue::IsList(void) -{ - if (!mList || !mList->GetNext()) - { +bool CGPValue::IsList(void) { + if (!mList || !mList->GetNext()) { return false; } return true; } -const char *CGPValue::GetTopValue(void) -{ - if (mList) - { +const char *CGPValue::GetTopValue(void) { + if (mList) { return mList->GetName(); } return 0; } -void CGPValue::AddValue(const char *newValue, CTextPool **textPool) -{ - if (textPool) - { +void CGPValue::AddValue(const char *newValue, CTextPool **textPool) { + if (textPool) { newValue = (*textPool)->AllocText((char *)newValue, true, textPool); } - if (mList == 0) - { + if (mList == 0) { mList = new CGPObject(newValue); mList->SetInOrderNext(mList); - } - else - { + } else { mList->GetInOrderNext()->SetNext(new CGPObject(newValue)); mList->SetInOrderNext(mList->GetInOrderNext()->GetNext()); } } -bool CGPValue::Parse(char **dataPtr, CTextPool **textPool) -{ - char *token; - char *value; +bool CGPValue::Parse(char **dataPtr, CTextPool **textPool) { + char *token; + char *value; - while(1) - { + while (1) { token = GetToken(dataPtr, true, true); - if (!token[0]) - { // end of data - error! + if (!token[0]) { // end of data - error! return false; - } - else if (Q_stricmp(token, "]") == 0) - { // ending brace for this list + } else if (Q_stricmp(token, "]") == 0) { // ending brace for this list break; } @@ -389,44 +285,35 @@ bool CGPValue::Parse(char **dataPtr, CTextPool **textPool) return true; } -bool CGPValue::Write(CTextPool **textPool, int depth) -{ - int i; - CGPObject *next; +bool CGPValue::Write(CTextPool **textPool, int depth) { + int i; + CGPObject *next; - if (!mList) - { + if (!mList) { return true; } - for(i=0;iAllocText("\t", false, textPool); } WriteText(textPool, mName); - if (!mList->GetNext()) - { + if (!mList->GetNext()) { (*textPool)->AllocText("\t\t", false, textPool); mList->WriteText(textPool, mList->GetName()); (*textPool)->AllocText("\r\n", false, textPool); - } - else - { + } else { (*textPool)->AllocText("\r\n", false, textPool); - for(i=0;iAllocText("\t", false, textPool); } (*textPool)->AllocText("[\r\n", false, textPool); next = mList; - while(next) - { - for(i=0;iAllocText("\t", false, textPool); } mList->WriteText(textPool, next->GetName()); @@ -435,8 +322,7 @@ bool CGPValue::Write(CTextPool **textPool, int depth) next = next->GetNext(); } - for(i=0;iAllocText("\t", false, textPool); } (*textPool)->AllocText("]\r\n", false, textPool); @@ -445,84 +331,48 @@ bool CGPValue::Write(CTextPool **textPool, int depth) return true; } +CGPGroup::CGPGroup(const char *initName, CGPGroup *initParent) + : CGPObject(initName), mPairs(0), mInOrderPairs(0), mCurrentPair(0), mSubGroups(0), mInOrderSubGroups(0), mCurrentSubGroup(0), mParent(initParent), + mWriteable(false) {} +CGPGroup::~CGPGroup(void) { Clean(); } - - - - - - - - - - - - - -CGPGroup::CGPGroup(const char *initName, CGPGroup *initParent) : - CGPObject(initName), - mPairs(0), - mInOrderPairs(0), - mCurrentPair(0), - mSubGroups(0), - mInOrderSubGroups(0), - mCurrentSubGroup(0), - mParent(initParent), - mWriteable(false) -{ -} - -CGPGroup::~CGPGroup(void) -{ - Clean(); -} - -int CGPGroup::GetNumSubGroups(void) -{ - int count; - CGPGroup *group; +int CGPGroup::GetNumSubGroups(void) { + int count; + CGPGroup *group; count = 0; group = mSubGroups; - do - { + do { count++; group = (CGPGroup *)group->GetNext(); - } - while(group); + } while (group); - return(count); + return (count); } -int CGPGroup::GetNumPairs(void) -{ - int count; - CGPValue *pair; +int CGPGroup::GetNumPairs(void) { + int count; + CGPValue *pair; count = 0; pair = mPairs; - do - { + do { count++; pair = (CGPValue *)pair->GetNext(); - } - while(pair); + } while (pair); - return(count); + return (count); } -void CGPGroup::Clean(void) -{ - while(mPairs) - { +void CGPGroup::Clean(void) { + while (mPairs) { mCurrentPair = (CGPValue *)mPairs->GetNext(); delete mPairs; mPairs = mCurrentPair; } - while(mSubGroups) - { + while (mSubGroups) { mCurrentSubGroup = (CGPGroup *)mSubGroups->GetNext(); delete mSubGroups; mSubGroups = mCurrentSubGroup; @@ -534,26 +384,21 @@ void CGPGroup::Clean(void) mWriteable = false; } -CGPGroup *CGPGroup::Duplicate(CTextPool **textPool, CGPGroup *initParent) -{ - CGPGroup *newGroup, *subSub, *newSub; - CGPValue *newPair, *subPair; - char *name; +CGPGroup *CGPGroup::Duplicate(CTextPool **textPool, CGPGroup *initParent) { + CGPGroup *newGroup, *subSub, *newSub; + CGPValue *newPair, *subPair; + char *name; - if (textPool) - { + if (textPool) { name = (*textPool)->AllocText((char *)mName, true, textPool); - } - else - { + } else { name = (char *)mName; } newGroup = new CGPGroup(name); subSub = mSubGroups; - while(subSub) - { + while (subSub) { newSub = subSub->Duplicate(textPool, newGroup); newGroup->AddGroup(newSub); @@ -561,8 +406,7 @@ CGPGroup *CGPGroup::Duplicate(CTextPool **textPool, CGPGroup *initParent) } subPair = mPairs; - while(subPair) - { + while (subPair) { newPair = subPair->Duplicate(textPool); newGroup->AddPair(newPair); @@ -572,25 +416,18 @@ CGPGroup *CGPGroup::Duplicate(CTextPool **textPool, CGPGroup *initParent) return newGroup; } -void CGPGroup::SortObject(CGPObject *object, CGPObject **unsortedList, CGPObject **sortedList, - CGPObject **lastObject) -{ - CGPObject *test, *last; +void CGPGroup::SortObject(CGPObject *object, CGPObject **unsortedList, CGPObject **sortedList, CGPObject **lastObject) { + CGPObject *test, *last; - if (!*unsortedList) - { + if (!*unsortedList) { *unsortedList = *sortedList = object; - } - else - { + } else { (*lastObject)->SetNext(object); test = *sortedList; last = 0; - while(test) - { - if (Q_stricmp(object->GetName(), test->GetName()) < 0) - { + while (test) { + if (Q_stricmp(object->GetName(), test->GetName()) < 0) { break; } @@ -598,18 +435,14 @@ void CGPGroup::SortObject(CGPObject *object, CGPObject **unsortedList, CGPObject test = test->GetInOrderNext(); } - if (test) - { + if (test) { test->SetInOrderPrevious(object); object->SetInOrderNext(test); } - if (last) - { + if (last) { last->SetInOrderNext(object); object->SetInOrderPrevious(last); - } - else - { + } else { *sortedList = object; } } @@ -617,15 +450,12 @@ void CGPGroup::SortObject(CGPObject *object, CGPObject **unsortedList, CGPObject *lastObject = object; } -CGPValue *CGPGroup::AddPair(const char *name, const char *value, CTextPool **textPool) -{ - CGPValue *newPair; +CGPValue *CGPGroup::AddPair(const char *name, const char *value, CTextPool **textPool) { + CGPValue *newPair; - if (textPool) - { + if (textPool) { name = (*textPool)->AllocText((char *)name, true, textPool); - if (value) - { + if (value) { value = (*textPool)->AllocText((char *)value, true, textPool); } } @@ -637,18 +467,12 @@ CGPValue *CGPGroup::AddPair(const char *name, const char *value, CTextPool **tex return newPair; } -void CGPGroup::AddPair(CGPValue *NewPair) -{ - SortObject(NewPair, (CGPObject **)&mPairs, (CGPObject **)&mInOrderPairs, - (CGPObject **)&mCurrentPair); -} +void CGPGroup::AddPair(CGPValue *NewPair) { SortObject(NewPair, (CGPObject **)&mPairs, (CGPObject **)&mInOrderPairs, (CGPObject **)&mCurrentPair); } -CGPGroup *CGPGroup::AddGroup(const char *name, CTextPool **textPool) -{ - CGPGroup *newGroup; +CGPGroup *CGPGroup::AddGroup(const char *name, CTextPool **textPool) { + CGPGroup *newGroup; - if (textPool) - { + if (textPool) { name = (*textPool)->AllocText((char *)name, true, textPool); } @@ -659,52 +483,39 @@ CGPGroup *CGPGroup::AddGroup(const char *name, CTextPool **textPool) return newGroup; } -void CGPGroup::AddGroup(CGPGroup *NewGroup) -{ - SortObject(NewGroup, (CGPObject **)&mSubGroups, (CGPObject **)&mInOrderSubGroups, - (CGPObject **)&mCurrentSubGroup); +void CGPGroup::AddGroup(CGPGroup *NewGroup) { + SortObject(NewGroup, (CGPObject **)&mSubGroups, (CGPObject **)&mInOrderSubGroups, (CGPObject **)&mCurrentSubGroup); } -CGPGroup *CGPGroup::FindSubGroup(const char *name) -{ - CGPGroup *group; +CGPGroup *CGPGroup::FindSubGroup(const char *name) { + CGPGroup *group; group = mSubGroups; - while(group) - { - if(!Q_stricmp(name, group->GetName())) - { - return(group); + while (group) { + if (!Q_stricmp(name, group->GetName())) { + return (group); } group = (CGPGroup *)group->GetNext(); } - return(NULL); + return (NULL); } -bool CGPGroup::Parse(char **dataPtr, CTextPool **textPool) -{ - char *token; - char lastToken[MAX_TOKEN_SIZE]; - CGPGroup *newSubGroup; - CGPValue *newPair; +bool CGPGroup::Parse(char **dataPtr, CTextPool **textPool) { + char *token; + char lastToken[MAX_TOKEN_SIZE]; + CGPGroup *newSubGroup; + CGPValue *newPair; - while(1) - { + while (1) { token = GetToken(dataPtr, true); - if (!token[0]) - { // end of data - error! - if (mParent) - { + if (!token[0]) { // end of data - error! + if (mParent) { return false; - } - else - { + } else { break; } - } - else if (Q_stricmp(token, "}") == 0) - { // ending brace for this group + } else if (Q_stricmp(token, "}") == 0) { // ending brace for this group break; } @@ -712,25 +523,18 @@ bool CGPGroup::Parse(char **dataPtr, CTextPool **textPool) // read ahead to see what we are doing token = GetToken(dataPtr, true, true); - if (Q_stricmp(token, "{") == 0) - { // new sub group + if (Q_stricmp(token, "{") == 0) { // new sub group newSubGroup = AddGroup(lastToken, textPool); newSubGroup->SetWriteable(mWriteable); - if (!newSubGroup->Parse(dataPtr, textPool)) - { + if (!newSubGroup->Parse(dataPtr, textPool)) { return false; } - } - else if (Q_stricmp(token, "[") == 0) - { // new pair list + } else if (Q_stricmp(token, "[") == 0) { // new pair list newPair = AddPair(lastToken, 0, textPool); - if (!newPair->Parse(dataPtr, textPool)) - { + if (!newPair->Parse(dataPtr, textPool)) { return false; } - } - else - { // new pair + } else { // new pair AddPair(lastToken, token, textPool); } } @@ -738,44 +542,36 @@ bool CGPGroup::Parse(char **dataPtr, CTextPool **textPool) return true; } -bool CGPGroup::Write(CTextPool **textPool, int depth) -{ - int i; - CGPValue *mPair = mPairs; - CGPGroup *mSubGroup = mSubGroups; +bool CGPGroup::Write(CTextPool **textPool, int depth) { + int i; + CGPValue *mPair = mPairs; + CGPGroup *mSubGroup = mSubGroups; - if (depth >= 0) - { - for(i=0;i= 0) { + for (i = 0; i < depth; i++) { (*textPool)->AllocText("\t", false, textPool); } WriteText(textPool, mName); (*textPool)->AllocText("\r\n", false, textPool); - for(i=0;iAllocText("\t", false, textPool); } (*textPool)->AllocText("{\r\n", false, textPool); } - while(mPair) - { - mPair->Write(textPool, depth+1); + while (mPair) { + mPair->Write(textPool, depth + 1); mPair = (CGPValue *)mPair->GetNext(); } - while(mSubGroup) - { - mSubGroup->Write(textPool, depth+1); + while (mSubGroup) { + mSubGroup->Write(textPool, depth + 1); mSubGroup = (CGPGroup *)mSubGroup->GetNext(); } - if (depth >= 0) - { - for(i=0;i= 0) { + for (i = 0; i < depth; i++) { (*textPool)->AllocText("\t", false, textPool); } (*textPool)->AllocText("}\r\n", false, textPool); @@ -797,33 +593,25 @@ bool CGPGroup::Write(CTextPool **textPool, int depth) * the group belonging to the first key found or 0 if no group was found. * ************************************************************************************************/ -CGPValue *CGPGroup::FindPair(const char *key) -{ - CGPValue *pair; - size_t length; - const char *pos, *separator, *next; +CGPValue *CGPGroup::FindPair(const char *key) { + CGPValue *pair; + size_t length; + const char *pos, *separator, *next; pos = key; - while(pos[0]) - { + while (pos[0]) { separator = strstr(pos, "||"); - if (separator) - { + if (separator) { length = separator - pos; next = separator + 2; - } - else - { + } else { length = strlen(pos); next = pos + length; } pair = mPairs; - while(pair) - { - if (strlen(pair->GetName()) == length && - Q_stricmpn(pair->GetName(), pos, length) == 0) - { + while (pair) { + if (strlen(pair->GetName()) == length && Q_stricmpn(pair->GetName(), pos, length) == 0) { return pair; } @@ -836,54 +624,28 @@ CGPValue *CGPGroup::FindPair(const char *key) return 0; } -const char *CGPGroup::FindPairValue(const char *key, const char *defaultVal) -{ - CGPValue *pair = FindPair(key); +const char *CGPGroup::FindPairValue(const char *key, const char *defaultVal) { + CGPValue *pair = FindPair(key); - if (pair) - { + if (pair) { return pair->GetTopValue(); } return defaultVal; } +CGenericParser2::CGenericParser2(void) : mTextPool(0), mWriteable(false) {} +CGenericParser2::~CGenericParser2(void) { Clean(); } +bool CGenericParser2::Parse(char **dataPtr, bool cleanFirst, bool writeable) { + CTextPool *topPool; - - - - - - - - - - - -CGenericParser2::CGenericParser2(void) : - mTextPool(0), - mWriteable(false) -{ -} - -CGenericParser2::~CGenericParser2(void) -{ - Clean(); -} - -bool CGenericParser2::Parse(char **dataPtr, bool cleanFirst, bool writeable) -{ - CTextPool *topPool; - - if (cleanFirst) - { + if (cleanFirst) { Clean(); } - if (!mTextPool) - { + if (!mTextPool) { mTextPool = new CTextPool; } @@ -895,38 +657,24 @@ bool CGenericParser2::Parse(char **dataPtr, bool cleanFirst, bool writeable) return ret; } -void CGenericParser2::Clean(void) -{ +void CGenericParser2::Clean(void) { mTopLevel.Clean(); CleanTextPool(mTextPool); mTextPool = 0; } -bool CGenericParser2::Write(CTextPool *textPool) -{ - return mTopLevel.Write(&textPool, -1); -} - - - - - - - - +bool CGenericParser2::Write(CTextPool *textPool) { return mTopLevel.Write(&textPool, -1); } // The following groups of routines are used for a C interface into GP2. // C++ users should just use the objects as normally and not call these routines below // // CGenericParser2 (void *) routines -TGenericParser2 GP_Parse(char **dataPtr, bool cleanFirst, bool writeable) -{ - CGenericParser2 *parse; +TGenericParser2 GP_Parse(char **dataPtr, bool cleanFirst, bool writeable) { + CGenericParser2 *parse; parse = new CGenericParser2; - if (parse->Parse(dataPtr, cleanFirst, writeable)) - { + if (parse->Parse(dataPtr, cleanFirst, writeable)) { return parse; } @@ -934,20 +682,16 @@ TGenericParser2 GP_Parse(char **dataPtr, bool cleanFirst, bool writeable) return 0; } -void GP_Clean(TGenericParser2 GP2) -{ - if (!GP2) - { +void GP_Clean(TGenericParser2 GP2) { + if (!GP2) { return; } ((CGenericParser2 *)GP2)->Clean(); } -void GP_Delete(TGenericParser2 *GP2) -{ - if (!GP2 || !(*GP2)) - { +void GP_Delete(TGenericParser2 *GP2) { + if (!GP2 || !(*GP2)) { return; } @@ -955,34 +699,25 @@ void GP_Delete(TGenericParser2 *GP2) (*GP2) = 0; } -TGPGroup GP_GetBaseParseGroup(TGenericParser2 GP2) -{ - if (!GP2) - { +TGPGroup GP_GetBaseParseGroup(TGenericParser2 GP2) { + if (!GP2) { return 0; } return ((CGenericParser2 *)GP2)->GetBaseParseGroup(); } - - - // CGPGroup (void *) routines -const char *GPG_GetName(TGPGroup GPG) -{ - if (!GPG) - { +const char *GPG_GetName(TGPGroup GPG) { + if (!GPG) { return ""; } return ((CGPGroup *)GPG)->GetName(); } -bool GPG_GetName(TGPGroup GPG, char *Value) -{ - if (!GPG) - { +bool GPG_GetName(TGPGroup GPG, char *Value) { + if (!GPG) { Value[0] = 0; return false; } @@ -991,131 +726,103 @@ bool GPG_GetName(TGPGroup GPG, char *Value) return true; } -TGPGroup GPG_GetNext(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetNext(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetNext(); } -TGPGroup GPG_GetInOrderNext(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetInOrderNext(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetInOrderNext(); } -TGPGroup GPG_GetInOrderPrevious(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetInOrderPrevious(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetInOrderPrevious(); } -TGPGroup GPG_GetPairs(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetPairs(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetPairs(); } -TGPGroup GPG_GetInOrderPairs(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetInOrderPairs(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetInOrderPairs(); } -TGPGroup GPG_GetSubGroups(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetSubGroups(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetSubGroups(); } -TGPGroup GPG_GetInOrderSubGroups(TGPGroup GPG) -{ - if (!GPG) - { +TGPGroup GPG_GetInOrderSubGroups(TGPGroup GPG) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->GetInOrderSubGroups(); } -TGPGroup GPG_FindSubGroup(TGPGroup GPG, const char *name) -{ - if (!GPG) - { +TGPGroup GPG_FindSubGroup(TGPGroup GPG, const char *name) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->FindSubGroup(name); } -TGPValue GPG_FindPair(TGPGroup GPG, const char *key) -{ - if (!GPG) - { +TGPValue GPG_FindPair(TGPGroup GPG, const char *key) { + if (!GPG) { return 0; } return ((CGPGroup *)GPG)->FindPair(key); } -const char *GPG_FindPairValue(TGPGroup GPG, const char *key, const char *defaultVal) -{ - if (!GPG) - { +const char *GPG_FindPairValue(TGPGroup GPG, const char *key, const char *defaultVal) { + if (!GPG) { return defaultVal; } return ((CGPGroup *)GPG)->FindPairValue(key, defaultVal); } -bool GPG_FindPairValue(TGPGroup GPG, const char *key, const char *defaultVal, char *Value) -{ +bool GPG_FindPairValue(TGPGroup GPG, const char *key, const char *defaultVal, char *Value) { strcpy(Value, GPG_FindPairValue(GPG, key, defaultVal)); return true; } - - - // CGPValue (void *) routines -const char *GPV_GetName(TGPValue GPV) -{ - if (!GPV) - { +const char *GPV_GetName(TGPValue GPV) { + if (!GPV) { return ""; } return ((CGPValue *)GPV)->GetName(); } -bool GPV_GetName(TGPValue GPV, char *Value) -{ - if (!GPV) - { +bool GPV_GetName(TGPValue GPV, char *Value) { + if (!GPV) { Value[0] = 0; return false; } @@ -1124,60 +831,48 @@ bool GPV_GetName(TGPValue GPV, char *Value) return true; } -TGPValue GPV_GetNext(TGPValue GPV) -{ - if (!GPV) - { +TGPValue GPV_GetNext(TGPValue GPV) { + if (!GPV) { return 0; } return ((CGPValue *)GPV)->GetNext(); } -TGPValue GPV_GetInOrderNext(TGPValue GPV) -{ - if (!GPV) - { +TGPValue GPV_GetInOrderNext(TGPValue GPV) { + if (!GPV) { return 0; } return ((CGPValue *)GPV)->GetInOrderNext(); } -TGPValue GPV_GetInOrderPrevious(TGPValue GPV) -{ - if (!GPV) - { +TGPValue GPV_GetInOrderPrevious(TGPValue GPV) { + if (!GPV) { return 0; } return ((CGPValue *)GPV)->GetInOrderPrevious(); } -bool GPV_IsList(TGPValue GPV) -{ - if (!GPV) - { +bool GPV_IsList(TGPValue GPV) { + if (!GPV) { return 0; } return ((CGPValue *)GPV)->IsList(); } -const char *GPV_GetTopValue(TGPValue GPV) -{ - if (!GPV) - { +const char *GPV_GetTopValue(TGPValue GPV) { + if (!GPV) { return ""; } return ((CGPValue *)GPV)->GetTopValue(); } -bool GPV_GetTopValue(TGPValue GPV, char *Value) -{ - if (!GPV) - { +bool GPV_GetTopValue(TGPValue GPV, char *Value) { + if (!GPV) { Value[0] = 0; return false; } @@ -1187,10 +882,8 @@ bool GPV_GetTopValue(TGPValue GPV, char *Value) return true; } -TGPValue GPV_GetList(TGPValue GPV) -{ - if (!GPV) - { +TGPValue GPV_GetList(TGPValue GPV) { + if (!GPV) { return 0; } diff --git a/codemp/qcommon/RoffSystem.cpp b/codemp/qcommon/RoffSystem.cpp index 753eb75c84..c34ae0ebad 100644 --- a/codemp/qcommon/RoffSystem.cpp +++ b/codemp/qcommon/RoffSystem.cpp @@ -41,17 +41,15 @@ CROFFSystem theROFFSystem; // RETURN: // none //--------------------------------------------------------------------------- -CROFFSystem::CROFF::CROFF( const char *file, int id ) -{ - strcpy( mROFFFilePath, file ); +CROFFSystem::CROFF::CROFF(const char *file, int id) { + strcpy(mROFFFilePath, file); - mID = id; + mID = id; mMoveRotateList = NULL; mNoteTrackIndexes = 0; mUsedByClient = mUsedByServer = qfalse; } - //--------------------------------------------------------------------------- // CROFFSystem::CROFF::~CROFF() // Frees any resources when the CROFF object dies @@ -62,21 +60,17 @@ CROFFSystem::CROFF::CROFF( const char *file, int id ) // RETURN: // none //--------------------------------------------------------------------------- -CROFFSystem::CROFF::~CROFF() -{ - if ( mMoveRotateList ) - { - delete [] mMoveRotateList; +CROFFSystem::CROFF::~CROFF() { + if (mMoveRotateList) { + delete[] mMoveRotateList; } - if (mNoteTrackIndexes) - { + if (mNoteTrackIndexes) { delete mNoteTrackIndexes[0]; - delete [] mNoteTrackIndexes; + delete[] mNoteTrackIndexes; } } - //--------------------------------------------------------------------------- // CROFFSystem::Restart // Cleans up the roff system, not sure how useful this really is @@ -87,16 +81,14 @@ CROFFSystem::CROFF::~CROFF() // RETURN: // success or failure //--------------------------------------------------------------------------- -qboolean CROFFSystem::Restart() -{ +qboolean CROFFSystem::Restart() { TROFFList::iterator itr = mROFFList.begin(); // remove everything from the list - while( itr != mROFFList.end() ) - { + while (itr != mROFFList.end()) { delete ((CROFF *)(*itr).second); - mROFFList.erase( itr ); + mROFFList.erase(itr); itr = mROFFList.begin(); } @@ -106,7 +98,6 @@ qboolean CROFFSystem::Restart() return qtrue; } - //--------------------------------------------------------------------------- // CROFFSystem::IsROFF // Makes sure that the requested file is actually a ROFF @@ -117,35 +108,29 @@ qboolean CROFFSystem::Restart() // RETURN: // returns test success or failure //--------------------------------------------------------------------------- -qboolean CROFFSystem::IsROFF( unsigned char *data ) -{ - TROFFHeader *hdr = (TROFFHeader *)data; - TROFF2Header *hdr2 = (TROFF2Header *)data; +qboolean CROFFSystem::IsROFF(unsigned char *data) { + TROFFHeader *hdr = (TROFFHeader *)data; + TROFF2Header *hdr2 = (TROFF2Header *)data; - if ( !strcmp( hdr->mHeader, ROFF_STRING )) - { // bad header + if (!strcmp(hdr->mHeader, ROFF_STRING)) { // bad header return qfalse; } - if (LittleLong(hdr->mVersion) != ROFF_VERSION && LittleLong(hdr->mVersion) != ROFF_NEW_VERSION) - { // bad version + if (LittleLong(hdr->mVersion) != ROFF_VERSION && LittleLong(hdr->mVersion) != ROFF_NEW_VERSION) { // bad version return qfalse; } - if (LittleLong(hdr->mVersion) == ROFF_VERSION && LittleFloat(hdr->mCount) <= 0.0) - { // bad count + if (LittleLong(hdr->mVersion) == ROFF_VERSION && LittleFloat(hdr->mCount) <= 0.0) { // bad count return qfalse; } - if (LittleLong(hdr->mVersion) == ROFF_NEW_VERSION && LittleLong(hdr2->mCount) <= 0) - { // bad count + if (LittleLong(hdr->mVersion) == ROFF_NEW_VERSION && LittleLong(hdr2->mCount) <= 0) { // bad count return qfalse; } return qtrue; } - //--------------------------------------------------------------------------- // CROFFSystem::InitROFF // Handles stuffing the roff data in the CROFF object @@ -156,31 +141,27 @@ qboolean CROFFSystem::IsROFF( unsigned char *data ) // RETURN: // returns initialization success or failure //--------------------------------------------------------------------------- -qboolean CROFFSystem::InitROFF( unsigned char *data, CROFF *obj ) -{ - int i; +qboolean CROFFSystem::InitROFF(unsigned char *data, CROFF *obj) { + int i; TROFFHeader *hdr = (TROFFHeader *)data; - if (LittleLong(hdr->mVersion) == ROFF_NEW_VERSION) - { + if (LittleLong(hdr->mVersion) == ROFF_NEW_VERSION) { return InitROFF2(data, obj); } - obj->mROFFEntries = LittleLong(hdr->mCount); - obj->mMoveRotateList = new TROFF2Entry[((int)LittleFloat(hdr->mCount))]; - obj->mFrameTime = 1000 / ROFF_SAMPLE_RATE; // default 10 hz - obj->mLerp = ROFF_SAMPLE_RATE; - obj->mNumNoteTracks = 0; - obj->mNoteTrackIndexes = 0; + obj->mROFFEntries = LittleLong(hdr->mCount); + obj->mMoveRotateList = new TROFF2Entry[((int)LittleFloat(hdr->mCount))]; + obj->mFrameTime = 1000 / ROFF_SAMPLE_RATE; // default 10 hz + obj->mLerp = ROFF_SAMPLE_RATE; + obj->mNumNoteTracks = 0; + obj->mNoteTrackIndexes = 0; - if ( obj->mMoveRotateList != 0 ) - { // Step past the header to get to the goods - TROFFEntry *roff_data = ( TROFFEntry *)&hdr[1]; + if (obj->mMoveRotateList != 0) { // Step past the header to get to the goods + TROFFEntry *roff_data = (TROFFEntry *)&hdr[1]; // Copy all of the goods into our ROFF cache - for ( i = 0; i < LittleLong(hdr->mCount); i++ ) - { + for (i = 0; i < LittleLong(hdr->mCount); i++) { #ifdef Q3_BIG_ENDIAN obj->mMoveRotateList[i].mOriginOffset[0] = LittleFloat(roff_data[i].mOriginOffset[0]); obj->mMoveRotateList[i].mOriginOffset[1] = LittleFloat(roff_data[i].mOriginOffset[1]); @@ -189,24 +170,21 @@ qboolean CROFFSystem::InitROFF( unsigned char *data, CROFF *obj ) obj->mMoveRotateList[i].mRotateOffset[1] = LittleFloat(roff_data[i].mRotateOffset[1]); obj->mMoveRotateList[i].mRotateOffset[2] = LittleFloat(roff_data[i].mRotateOffset[2]); #else - VectorCopy( roff_data[i].mOriginOffset, obj->mMoveRotateList[i].mOriginOffset ); - VectorCopy( roff_data[i].mRotateOffset, obj->mMoveRotateList[i].mRotateOffset ); + VectorCopy(roff_data[i].mOriginOffset, obj->mMoveRotateList[i].mOriginOffset); + VectorCopy(roff_data[i].mRotateOffset, obj->mMoveRotateList[i].mRotateOffset); #endif obj->mMoveRotateList[i].mStartNote = -1; obj->mMoveRotateList[i].mNumNotes = 0; } FixBadAngles(obj); - } - else - { + } else { return qfalse; } return qtrue; } - //--------------------------------------------------------------------------- // CROFFSystem::InitROFF2 // Handles stuffing the roff data in the CROFF object for version 2 @@ -217,25 +195,22 @@ qboolean CROFFSystem::InitROFF( unsigned char *data, CROFF *obj ) // RETURN: // returns initialization success or failure //--------------------------------------------------------------------------- -qboolean CROFFSystem::InitROFF2( unsigned char *data, CROFF *obj ) -{ - int i; +qboolean CROFFSystem::InitROFF2(unsigned char *data, CROFF *obj) { + int i; TROFF2Header *hdr = (TROFF2Header *)data; - obj->mROFFEntries = LittleLong(hdr->mCount); - obj->mMoveRotateList = new TROFF2Entry[LittleLong(hdr->mCount)]; - obj->mFrameTime = LittleLong(hdr->mFrameRate); - obj->mLerp = 1000 / LittleLong(hdr->mFrameRate); - obj->mNumNoteTracks = LittleLong(hdr->mNumNotes); + obj->mROFFEntries = LittleLong(hdr->mCount); + obj->mMoveRotateList = new TROFF2Entry[LittleLong(hdr->mCount)]; + obj->mFrameTime = LittleLong(hdr->mFrameRate); + obj->mLerp = 1000 / LittleLong(hdr->mFrameRate); + obj->mNumNoteTracks = LittleLong(hdr->mNumNotes); - if ( obj->mMoveRotateList != 0 ) - { // Step past the header to get to the goods - TROFF2Entry *roff_data = ( TROFF2Entry *)&hdr[1]; + if (obj->mMoveRotateList != 0) { // Step past the header to get to the goods + TROFF2Entry *roff_data = (TROFF2Entry *)&hdr[1]; // Copy all of the goods into our ROFF cache - for ( i = 0; i < LittleLong(hdr->mCount); i++ ) - { + for (i = 0; i < LittleLong(hdr->mCount); i++) { #ifdef Q3_BIG_ENDIAN obj->mMoveRotateList[i].mOriginOffset[0] = LittleFloat(roff_data[i].mOriginOffset[0]); obj->mMoveRotateList[i].mOriginOffset[1] = LittleFloat(roff_data[i].mOriginOffset[1]); @@ -244,8 +219,8 @@ qboolean CROFFSystem::InitROFF2( unsigned char *data, CROFF *obj ) obj->mMoveRotateList[i].mRotateOffset[1] = LittleFloat(roff_data[i].mRotateOffset[1]); obj->mMoveRotateList[i].mRotateOffset[2] = LittleFloat(roff_data[i].mRotateOffset[2]); #else - VectorCopy( roff_data[i].mOriginOffset, obj->mMoveRotateList[i].mOriginOffset ); - VectorCopy( roff_data[i].mRotateOffset, obj->mMoveRotateList[i].mRotateOffset ); + VectorCopy(roff_data[i].mOriginOffset, obj->mMoveRotateList[i].mOriginOffset); + VectorCopy(roff_data[i].mRotateOffset, obj->mMoveRotateList[i].mRotateOffset); #endif obj->mMoveRotateList[i].mStartNote = LittleLong(roff_data[i].mStartNote); obj->mMoveRotateList[i].mNumNotes = LittleLong(roff_data[i].mNumNotes); @@ -253,15 +228,13 @@ qboolean CROFFSystem::InitROFF2( unsigned char *data, CROFF *obj ) FixBadAngles(obj); - if (obj->mNumNoteTracks) - { - size_t size = 0; - char *ptr, *start; + if (obj->mNumNoteTracks) { + size_t size = 0; + char *ptr, *start; ptr = start = (char *)&roff_data[i]; - for(i=0;imNumNoteTracks;i++) - { + for (i = 0; i < obj->mNumNoteTracks; i++) { size += strlen(ptr) + 1; ptr += strlen(ptr) + 1; } @@ -270,15 +243,12 @@ qboolean CROFFSystem::InitROFF2( unsigned char *data, CROFF *obj ) ptr = obj->mNoteTrackIndexes[0] = new char[size]; memcpy(obj->mNoteTrackIndexes[0], start, size); - for(i=1;imNumNoteTracks;i++) - { + for (i = 1; i < obj->mNumNoteTracks; i++) { ptr += strlen(ptr) + 1; obj->mNoteTrackIndexes[i] = ptr; } } - } - else - { + } else { return qfalse; } @@ -296,28 +266,22 @@ qboolean CROFFSystem::InitROFF2( unsigned char *data, CROFF *obj ) * none * * * ************************************************************************************************/ -void CROFFSystem::FixBadAngles(CROFF *obj) -{ +void CROFFSystem::FixBadAngles(CROFF *obj) { // Ideally we would fix the ROFF exporter, if that doesn't happen, this may be an adequate solution #ifdef ROFF_AUTO_FIX_BAD_ANGLES - int index, t; + int index, t; // Attempt to fix bad angles - for(index=0;indexmROFFEntries;index++) - { - for ( t = 0; t < 3; t++ ) - { - if ( obj->mMoveRotateList[index].mRotateOffset[t] > 180.0f ) - { // found a bad angle - // Com_Printf( S_COLOR_YELLOW"Fixing bad roff angle\n <%6.2f> changed to <%6.2f>.\n", - // roff_data[i].mRotateOffset[t], roff_data[i].mRotateOffset[t] - 360.0f ); + for (index = 0; index < obj->mROFFEntries; index++) { + for (t = 0; t < 3; t++) { + if (obj->mMoveRotateList[index].mRotateOffset[t] > 180.0f) { // found a bad angle + // Com_Printf( S_COLOR_YELLOW"Fixing bad roff angle\n <%6.2f> changed to <%6.2f>.\n", + // roff_data[i].mRotateOffset[t], roff_data[i].mRotateOffset[t] - 360.0f ); obj->mMoveRotateList[index].mRotateOffset[t] -= 360.0f; - } - else if ( obj->mMoveRotateList[index].mRotateOffset[t] < -180.0f ) - { // found a bad angle - // Com_Printf( S_COLOR_YELLOW"Fixing bad roff angle\n <%6.2f> changed to <%6.2f>.\n", - // roff_data[i].mRotateOffset[t], roff_data[i].mRotateOffset[t] + 360.0f ); + } else if (obj->mMoveRotateList[index].mRotateOffset[t] < -180.0f) { // found a bad angle + // Com_Printf( S_COLOR_YELLOW"Fixing bad roff angle\n <%6.2f> changed to <%6.2f>.\n", + // roff_data[i].mRotateOffset[t], roff_data[i].mRotateOffset[t] + 360.0f ); obj->mMoveRotateList[index].mRotateOffset[t] += 360.0f; } } @@ -336,41 +300,34 @@ void CROFFSystem::FixBadAngles(CROFF *obj) // RETURN: // returns ID of the roff, whether its an existing one or new one. //--------------------------------------------------------------------------- -int CROFFSystem::Cache( const char *file, qboolean isClient ) -{ +int CROFFSystem::Cache(const char *file, qboolean isClient) { // See if this item is already cached - int len; - int id = GetID( file ); - unsigned char *data; - CROFF *cROFF; + int len; + int id = GetID(file); + unsigned char *data; + CROFF *cROFF; - if ( id ) - { + if (id) { #ifdef _DEBUG - Com_Printf( S_COLOR_YELLOW"Ignoring. File '%s' already cached.\n", file ); + Com_Printf(S_COLOR_YELLOW "Ignoring. File '%s' already cached.\n", file); #endif - } - else - { // Read the file in one fell swoop - len = FS_ReadFile( file, (void**) &data); + } else { // Read the file in one fell swoop + len = FS_ReadFile(file, (void **)&data); - if ( len <= 0 ) - { + if (len <= 0) { char otherPath[1024]; - COM_StripExtension(file, otherPath, sizeof( otherPath )); - len = FS_ReadFile( va("scripts/%s.rof", otherPath), (void**) &data); - if (len <= 0) - { - Com_Printf( S_COLOR_RED"Could not open .ROF file '%s'\n", file ); + COM_StripExtension(file, otherPath, sizeof(otherPath)); + len = FS_ReadFile(va("scripts/%s.rof", otherPath), (void **)&data); + if (len <= 0) { + Com_Printf(S_COLOR_RED "Could not open .ROF file '%s'\n", file); return 0; } } // Make sure that the file is roff - if ( !IsROFF( data ) ) - { - Com_Printf( S_COLOR_RED"cache failed: roff <%s> does not exist or is not a valid roff\n", file ); - FS_FreeFile( data ); + if (!IsROFF(data)) { + Com_Printf(S_COLOR_RED "cache failed: roff <%s> does not exist or is not a valid roff\n", file); + FS_FreeFile(data); return 0; } @@ -378,26 +335,22 @@ int CROFFSystem::Cache( const char *file, qboolean isClient ) // Things are looking good so far, so create a new CROFF object id = NewID(); - cROFF = new CROFF( file, id ); + cROFF = new CROFF(file, id); mROFFList[id] = cROFF; - if ( !InitROFF( data, cROFF ) ) - { // something failed, so get rid of the object - Unload( id ); + if (!InitROFF(data, cROFF)) { // something failed, so get rid of the object + Unload(id); id = 0; } - FS_FreeFile( data ); + FS_FreeFile(data); } - cROFF = (*mROFFList.find( id )).second; - if (isClient) - { + cROFF = (*mROFFList.find(id)).second; + if (isClient) { cROFF->mUsedByClient = qtrue; - } - else - { + } else { cROFF->mUsedByServer = qtrue; } @@ -405,7 +358,6 @@ int CROFFSystem::Cache( const char *file, qboolean isClient ) return id; } - //--------------------------------------------------------------------------- // CROFFSystem::GetID // Finds the associated (internal) ID of the specified roff file @@ -416,15 +368,12 @@ int CROFFSystem::Cache( const char *file, qboolean isClient ) // RETURN: // returns ID if there is one, zero if nothing was found //--------------------------------------------------------------------------- -int CROFFSystem::GetID( const char *file ) -{ +int CROFFSystem::GetID(const char *file) { TROFFList::iterator itr; // Attempt to find the requested roff - for ( itr = mROFFList.begin(); itr != mROFFList.end(); ++itr ) - { - if ( !strcmp( ((CROFF *)((*itr).second))->mROFFFilePath, file ) ) - { // return the ID to this roff + for (itr = mROFFList.begin(); itr != mROFFList.end(); ++itr) { + if (!strcmp(((CROFF *)((*itr).second))->mROFFFilePath, file)) { // return the ID to this roff return (*itr).first; } } @@ -433,7 +382,6 @@ int CROFFSystem::GetID( const char *file ) return 0; } - //--------------------------------------------------------------------------- // CROFFSystem::Unload // Removes the roff from the list, deleting it to free up any used resources @@ -445,29 +393,25 @@ int CROFFSystem::GetID( const char *file ) // RETURN: // qtrue if item was in the list, qfalse otherwise //--------------------------------------------------------------------------- -qboolean CROFFSystem::Unload( int id ) -{ +qboolean CROFFSystem::Unload(int id) { TROFFList::iterator itr; - itr = mROFFList.find( id ); + itr = mROFFList.find(id); - if ( itr != mROFFList.end() ) - { // requested item found in the list, free mem, then remove from list + if (itr != mROFFList.end()) { // requested item found in the list, free mem, then remove from list delete itr->second; - mROFFList.erase( itr++ ); + mROFFList.erase(itr++); #ifdef _DEBUG - Com_Printf( S_COLOR_GREEN "roff unloaded\n" ); + Com_Printf(S_COLOR_GREEN "roff unloaded\n"); #endif return qtrue; - } - else - { // not found + } else { // not found #ifdef _DEBUG - Com_Printf( S_COLOR_RED "unload failed: roff <%i> does not exist\n", id ); + Com_Printf(S_COLOR_RED "unload failed: roff <%i> does not exist\n", id); #endif return qfalse; } @@ -483,8 +427,7 @@ qboolean CROFFSystem::Unload( int id ) // RETURN: // success of operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::Clean(qboolean isClient) -{ +qboolean CROFFSystem::Clean(qboolean isClient) { #if 0 TROFFList::iterator itr, next; TROFFEntList::iterator entI, nextEnt; @@ -532,9 +475,8 @@ qboolean CROFFSystem::Clean(qboolean isClient) itr = mROFFList.begin(); - while ( itr != mROFFList.end() ) - { - Unload( (*itr).first ); + while (itr != mROFFList.end()) { + Unload((*itr).first); itr = mROFFList.begin(); } @@ -552,22 +494,19 @@ qboolean CROFFSystem::Clean(qboolean isClient) // RETURN: // none //--------------------------------------------------------------------------- -void CROFFSystem::List() -{ +void CROFFSystem::List() { TROFFList::iterator itr; - Com_Printf( S_COLOR_GREEN"\n--Cached ROFF files--\n" ); - Com_Printf( S_COLOR_GREEN"ID FILE\n" ); + Com_Printf(S_COLOR_GREEN "\n--Cached ROFF files--\n"); + Com_Printf(S_COLOR_GREEN "ID FILE\n"); - for ( itr = mROFFList.begin(); itr != mROFFList.end(); ++itr ) - { - Com_Printf( S_COLOR_GREEN"%2i - %s\n", (*itr).first, ((CROFF *)((*itr).second))->mROFFFilePath ); + for (itr = mROFFList.begin(); itr != mROFFList.end(); ++itr) { + Com_Printf(S_COLOR_GREEN "%2i - %s\n", (*itr).first, ((CROFF *)((*itr).second))->mROFFFilePath); } - Com_Printf( S_COLOR_GREEN"\nFiles: %i\n", mROFFList.size() ); + Com_Printf(S_COLOR_GREEN "\nFiles: %i\n", mROFFList.size()); } - //--------------------------------------------------------------------------- // CROFFSystem::List // Overloaded version of List, dumps the specified roff data to the console @@ -578,39 +517,34 @@ void CROFFSystem::List() // RETURN: // success or failure of operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::List( int id ) -{ +qboolean CROFFSystem::List(int id) { TROFFList::iterator itr; - itr = mROFFList.find( id ); + itr = mROFFList.find(id); - if ( itr != mROFFList.end() ) - { // requested item found in the list - CROFF *obj = ((CROFF *)((*itr).second)); - TROFF2Entry *dat = obj->mMoveRotateList; + if (itr != mROFFList.end()) { // requested item found in the list + CROFF *obj = ((CROFF *)((*itr).second)); + TROFF2Entry *dat = obj->mMoveRotateList; - Com_Printf( S_COLOR_GREEN"File: %s\n", obj->mROFFFilePath ); - Com_Printf( S_COLOR_GREEN"ID: %i\n", id ); - Com_Printf( S_COLOR_GREEN"Entries: %i\n\n", obj->mROFFEntries ); + Com_Printf(S_COLOR_GREEN "File: %s\n", obj->mROFFFilePath); + Com_Printf(S_COLOR_GREEN "ID: %i\n", id); + Com_Printf(S_COLOR_GREEN "Entries: %i\n\n", obj->mROFFEntries); - Com_Printf( S_COLOR_GREEN"MOVE ROTATE\n" ); + Com_Printf(S_COLOR_GREEN "MOVE ROTATE\n"); - for ( int i = 0; i < obj->mROFFEntries; i++ ) - { - Com_Printf( S_COLOR_GREEN"%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", - dat[i].mOriginOffset[0], dat[i].mOriginOffset[1], dat[i].mOriginOffset[2], - dat[i].mRotateOffset[0], dat[i].mRotateOffset[1], dat[i].mRotateOffset[2] ); + for (int i = 0; i < obj->mROFFEntries; i++) { + Com_Printf(S_COLOR_GREEN "%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\n", dat[i].mOriginOffset[0], dat[i].mOriginOffset[1], dat[i].mOriginOffset[2], + dat[i].mRotateOffset[0], dat[i].mRotateOffset[1], dat[i].mRotateOffset[2]); } return qtrue; } - Com_Printf( S_COLOR_YELLOW"ROFF not found: id <%d>\n", id ); + Com_Printf(S_COLOR_YELLOW "ROFF not found: id <%d>\n", id); return qfalse; } - //--------------------------------------------------------------------------- // CROFFSystem::Play // Start roff playback on an entity @@ -622,16 +556,13 @@ qboolean CROFFSystem::List( int id ) // RETURN: // success or failure of add operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::Play( int entID, int id, qboolean doTranslation, qboolean isClient ) -{ +qboolean CROFFSystem::Play(int entID, int id, qboolean doTranslation, qboolean isClient) { sharedEntity_t *ent = NULL; - if ( !isClient ) - { - ent = SV_GentityNum( entID ); + if (!isClient) { + ent = SV_GentityNum(entID); - if ( ent == NULL ) - { // shame on you.. + if (ent == NULL) { // shame on you.. return qfalse; } ent->r.mIsRoffing = qtrue; @@ -640,29 +571,28 @@ qboolean CROFFSystem::Play( int entID, int id, qboolean doTranslation, qboolean { ent->SetPhysics(PHYSICS_TYPE_BRUSHMODEL); }*/ - //bjg TODO: reset this latter? + // bjg TODO: reset this latter? } SROFFEntity *roffing_ent = new SROFFEntity; - roffing_ent->mEntID = entID; - roffing_ent->mROFFID = id; - roffing_ent->mNextROFFTime = sv.time; - roffing_ent->mROFFFrame = 0; - roffing_ent->mKill = qfalse; - roffing_ent->mSignal = qtrue; // TODO: hook up the real signal code - roffing_ent->mTranslated = doTranslation; - roffing_ent->mIsClient = isClient; + roffing_ent->mEntID = entID; + roffing_ent->mROFFID = id; + roffing_ent->mNextROFFTime = sv.time; + roffing_ent->mROFFFrame = 0; + roffing_ent->mKill = qfalse; + roffing_ent->mSignal = qtrue; // TODO: hook up the real signal code + roffing_ent->mTranslated = doTranslation; + roffing_ent->mIsClient = isClient; - if ( !isClient ) + if (!isClient) VectorCopy(ent->s.apos.trBase, roffing_ent->mStartAngles); - mROFFEntList.push_back( roffing_ent ); + mROFFEntList.push_back(roffing_ent); return qtrue; } - //--------------------------------------------------------------------------- // CROFFSystem::ListEnts // List all of the ents in the roff system @@ -673,43 +603,41 @@ qboolean CROFFSystem::Play( int entID, int id, qboolean doTranslation, qboolean // RETURN: // none //--------------------------------------------------------------------------- -void CROFFSystem::ListEnts() -{ -/* char *name, *file; - int id; +void CROFFSystem::ListEnts() { + /* char *name, *file; + int id; - TROFFEntList::iterator itr = mROFFEntList.begin(); - TROFFList::iterator itrRoff; + TROFFEntList::iterator itr = mROFFEntList.begin(); + TROFFList::iterator itrRoff; - Com_Printf( S_COLOR_GREEN"\n--ROFFing Entities--\n" ); - Com_Printf( S_COLOR_GREEN"EntID EntName RoffFile\n" ); + Com_Printf( S_COLOR_GREEN"\n--ROFFing Entities--\n" ); + Com_Printf( S_COLOR_GREEN"EntID EntName RoffFile\n" ); - // display everything in the end list - for ( itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr ) - { - // Entity ID - id = ((SROFFEntity *)(*itr))->mEntID; - // Entity Name - name = entitySystem->GetEntityFromID( id )->GetName(); - // ROFF object that will contain the roff file name - itrRoff = mROFFList.find( ((SROFFEntity *)(*itr))->mROFFID ); - - if ( itrRoff != mROFFList.end() ) - { // grab our filename - file = ((CROFF *)((*itrRoff).second ))->mROFFFilePath; - } - else - { // roff filename not found == bad - file = "Error: Unknown"; - } + // display everything in the end list + for ( itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr ) + { + // Entity ID + id = ((SROFFEntity *)(*itr))->mEntID; + // Entity Name + name = entitySystem->GetEntityFromID( id )->GetName(); + // ROFF object that will contain the roff file name + itrRoff = mROFFList.find( ((SROFFEntity *)(*itr))->mROFFID ); + + if ( itrRoff != mROFFList.end() ) + { // grab our filename + file = ((CROFF *)((*itrRoff).second ))->mROFFFilePath; + } + else + { // roff filename not found == bad + file = "Error: Unknown"; + } - Com_Printf( S_COLOR_GREEN"%3i %s %s\n", id, name, file ); - } + Com_Printf( S_COLOR_GREEN"%3i %s %s\n", id, name, file ); + } - Com_Printf( S_COLOR_GREEN"\nEntities: %i\n", mROFFEntList.size() );*/ + Com_Printf( S_COLOR_GREEN"\nEntities: %i\n", mROFFEntList.size() );*/ } - //--------------------------------------------------------------------------- // CROFFSystem::PurgeEnt // Prematurely purge an entity from the roff system @@ -720,31 +648,26 @@ void CROFFSystem::ListEnts() // RETURN: // success or failure of purge operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::PurgeEnt( int entID, qboolean isClient ) -{ +qboolean CROFFSystem::PurgeEnt(int entID, qboolean isClient) { TROFFEntList::iterator itr = mROFFEntList.begin(); - for ( itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr ) - { - if ( (*itr)->mIsClient == isClient && (*itr)->mEntID == entID) - { + for (itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr) { + if ((*itr)->mIsClient == isClient && (*itr)->mEntID == entID) { // Make sure it won't stay lerping - ClearLerp( (*itr) ); + ClearLerp((*itr)); delete (*itr); - mROFFEntList.erase( itr ); + mROFFEntList.erase(itr); return qtrue; } } - Com_Printf( S_COLOR_RED"Purge failed: Entity <%i> not found\n", entID ); + Com_Printf(S_COLOR_RED "Purge failed: Entity <%i> not found\n", entID); return qfalse; } - - //--------------------------------------------------------------------------- // CROFFSystem::PurgeEnt // Prematurely purge an entity from the roff system @@ -755,19 +678,18 @@ qboolean CROFFSystem::PurgeEnt( int entID, qboolean isClient ) // RETURN: // success or failure of purge operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::PurgeEnt( char *name ) -{ -/* rjr CEntity *ent = entitySystem->GetEntityFromName( NULL, name ); +qboolean CROFFSystem::PurgeEnt(char *name) { + /* rjr CEntity *ent = entitySystem->GetEntityFromName( NULL, name ); - if ( ent && ent->GetInUse() == qtrue ) - { - return PurgeEnt( ent->GetID() ); - } - else - { - Com_Printf( S_COLOR_RED"Entity <%s> not found or not in use\n", name ); - return qfalse; - }*/ + if ( ent && ent->GetInUse() == qtrue ) + { + return PurgeEnt( ent->GetID() ); + } + else + { + Com_Printf( S_COLOR_RED"Entity <%s> not found or not in use\n", name ); + return qfalse; + }*/ return qfalse; } @@ -782,38 +704,31 @@ qboolean CROFFSystem::PurgeEnt( char *name ) // RETURN: // none //--------------------------------------------------------------------------- -void CROFFSystem::UpdateEntities(qboolean isClient) -{ +void CROFFSystem::UpdateEntities(qboolean isClient) { TROFFEntList::iterator itr = mROFFEntList.begin(); TROFFList::iterator itrRoff; // display everything in the entity list - for ( itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr ) - { - if ((*itr)->mIsClient != isClient) - { + for (itr = mROFFEntList.begin(); itr != mROFFEntList.end(); ++itr) { + if ((*itr)->mIsClient != isClient) { continue; } // Get this entities ROFF object - itrRoff = mROFFList.find( ((SROFFEntity *)(*itr))->mROFFID ); + itrRoff = mROFFList.find(((SROFFEntity *)(*itr))->mROFFID); - if ( itrRoff != mROFFList.end() ) - { // roff that baby! - if ( !ApplyROFF( ((SROFFEntity *)(*itr)), ((CROFF *)((*itrRoff).second )))) - { // done roffing, mark for death + if (itrRoff != mROFFList.end()) { // roff that baby! + if (!ApplyROFF(((SROFFEntity *)(*itr)), ((CROFF *)((*itrRoff).second)))) { // done roffing, mark for death ((SROFFEntity *)(*itr))->mKill = qtrue; } - } - else - { // roff not found == bad, dump an error message and purge this ent - Com_Printf( S_COLOR_RED"ROFF System Error:\n" ); -// Com_Printf( S_COLOR_RED" -ROFF not found for entity <%s>\n", -// entitySystem->GetEntityFromID(((SROFFEntity *)(*itr))->mEntID)->GetName() ); + } else { // roff not found == bad, dump an error message and purge this ent + Com_Printf(S_COLOR_RED "ROFF System Error:\n"); + // Com_Printf( S_COLOR_RED" -ROFF not found for entity <%s>\n", + // entitySystem->GetEntityFromID(((SROFFEntity *)(*itr))->mEntID)->GetName() ); ((SROFFEntity *)(*itr))->mKill = qtrue; - ClearLerp( (*itr) ); + ClearLerp((*itr)); } } @@ -821,26 +736,21 @@ void CROFFSystem::UpdateEntities(qboolean isClient) // Delete killed ROFFers from the list // Man, there just has to be a better way to do this - while ( itr != mROFFEntList.end() ) - { - if ((*itr)->mIsClient != isClient) - { + while (itr != mROFFEntList.end()) { + if ((*itr)->mIsClient != isClient) { itr++; continue; } - if ( ((SROFFEntity *)(*itr))->mKill == qtrue ) - { - //make sure ICARUS knows ROFF is stopped -// CICARUSGameInterface::TaskIDComplete( -// entitySystem->GetEntityFromID(((SROFFEntity *)(*itr))->mEntID), TID_MOVE); + if (((SROFFEntity *)(*itr))->mKill == qtrue) { + // make sure ICARUS knows ROFF is stopped + // CICARUSGameInterface::TaskIDComplete( + // entitySystem->GetEntityFromID(((SROFFEntity *)(*itr))->mEntID), TID_MOVE); // trash this guy from the list delete (*itr); - mROFFEntList.erase( itr ); + mROFFEntList.erase(itr); itr = mROFFEntList.begin(); - } - else - { + } else { itr++; } } @@ -856,38 +766,32 @@ void CROFFSystem::UpdateEntities(qboolean isClient) // RETURN: // True == success; False == roff playback complete or failure //--------------------------------------------------------------------------- -qboolean CROFFSystem::ApplyROFF( SROFFEntity *roff_ent, CROFFSystem::CROFF *roff ) -{ - vec3_t f, r, u, result; - sharedEntity_t *ent = NULL; - trajectory_t *originTrajectory = NULL, *angleTrajectory = NULL; - float *origin = NULL, *angle = NULL; - +qboolean CROFFSystem::ApplyROFF(SROFFEntity *roff_ent, CROFFSystem::CROFF *roff) { + vec3_t f, r, u, result; + sharedEntity_t *ent = NULL; + trajectory_t *originTrajectory = NULL, *angleTrajectory = NULL; + float *origin = NULL, *angle = NULL; - if ( sv.time < roff_ent->mNextROFFTime ) - { // Not time to roff yet + if (sv.time < roff_ent->mNextROFFTime) { // Not time to roff yet return qtrue; } #ifndef DEDICATED - vec3_t originTemp, angleTemp; - if (roff_ent->mIsClient) - { - originTrajectory = CGVM_GetOriginTrajectory( roff_ent->mEntID ); - angleTrajectory = CGVM_GetAngleTrajectory( roff_ent->mEntID ); - CGVM_GetOrigin( roff_ent->mEntID, originTemp ); + vec3_t originTemp, angleTemp; + if (roff_ent->mIsClient) { + originTrajectory = CGVM_GetOriginTrajectory(roff_ent->mEntID); + angleTrajectory = CGVM_GetAngleTrajectory(roff_ent->mEntID); + CGVM_GetOrigin(roff_ent->mEntID, originTemp); origin = originTemp; - CGVM_GetAngles( roff_ent->mEntID, angleTemp ); + CGVM_GetAngles(roff_ent->mEntID, angleTemp); angle = angleTemp; - } - else + } else #endif { // Find the entity to apply the roff to - ent = SV_GentityNum( roff_ent->mEntID ); + ent = SV_GentityNum(roff_ent->mEntID); - if ( ent == 0 ) - { // bad stuff + if (ent == 0) { // bad stuff return qfalse; } @@ -897,43 +801,34 @@ qboolean CROFFSystem::ApplyROFF( SROFFEntity *roff_ent, CROFFSystem::CROFF *roff angle = ent->r.currentAngles; } - - if ( roff_ent->mROFFFrame >= roff->mROFFEntries ) - { // we are done roffing, so stop moving and flag this ent to be removed - SetLerp( originTrajectory, TR_STATIONARY, origin, NULL, sv.time, roff->mLerp ); - SetLerp( angleTrajectory, TR_STATIONARY, angle, NULL, sv.time, roff->mLerp ); - if (!roff_ent->mIsClient) - { + if (roff_ent->mROFFFrame >= roff->mROFFEntries) { // we are done roffing, so stop moving and flag this ent to be removed + SetLerp(originTrajectory, TR_STATIONARY, origin, NULL, sv.time, roff->mLerp); + SetLerp(angleTrajectory, TR_STATIONARY, angle, NULL, sv.time, roff->mLerp); + if (!roff_ent->mIsClient) { ent->r.mIsRoffing = qfalse; } return qfalse; } - if (roff_ent->mTranslated) - { - AngleVectors(roff_ent->mStartAngles, f, r, u ); + if (roff_ent->mTranslated) { + AngleVectors(roff_ent->mStartAngles, f, r, u); VectorScale(f, roff->mMoveRotateList[roff_ent->mROFFFrame].mOriginOffset[0], result); VectorMA(result, -roff->mMoveRotateList[roff_ent->mROFFFrame].mOriginOffset[1], r, result); VectorMA(result, roff->mMoveRotateList[roff_ent->mROFFFrame].mOriginOffset[2], u, result); - } - else - { + } else { VectorCopy(roff->mMoveRotateList[roff_ent->mROFFFrame].mOriginOffset, result); } // Set up our origin interpolation - SetLerp( originTrajectory, TR_LINEAR, origin, result, sv.time, roff->mLerp ); + SetLerp(originTrajectory, TR_LINEAR, origin, result, sv.time, roff->mLerp); // Set up our angle interpolation - SetLerp( angleTrajectory, TR_LINEAR, angle, - roff->mMoveRotateList[roff_ent->mROFFFrame].mRotateOffset, sv.time, roff->mLerp ); + SetLerp(angleTrajectory, TR_LINEAR, angle, roff->mMoveRotateList[roff_ent->mROFFFrame].mRotateOffset, sv.time, roff->mLerp); - if (roff->mMoveRotateList[roff_ent->mROFFFrame].mStartNote >= 0) - { - int i; + if (roff->mMoveRotateList[roff_ent->mROFFFrame].mStartNote >= 0) { + int i; - for(i=0;imMoveRotateList[roff_ent->mROFFFrame].mNumNotes;i++) - { + for (i = 0; i < roff->mMoveRotateList[roff_ent->mROFFFrame].mNumNotes; i++) { ProcessNote(roff_ent, roff->mNoteTrackIndexes[roff->mMoveRotateList[roff_ent->mROFFFrame].mStartNote + i]); } } @@ -942,15 +837,13 @@ qboolean CROFFSystem::ApplyROFF( SROFFEntity *roff_ent, CROFFSystem::CROFF *roff roff_ent->mROFFFrame++; roff_ent->mNextROFFTime = sv.time + roff->mFrameTime; - //rww - npcs need to know when they're getting roff'd - if ( !roff_ent->mIsClient ) + // rww - npcs need to know when they're getting roff'd + if (!roff_ent->mIsClient) ent->next_roff_time = roff_ent->mNextROFFTime; - return qtrue; } - /************************************************************************************************ * CROFFSystem::ProcessNote * * This function will send the note to the client. It will parse through the note for * @@ -964,37 +857,29 @@ qboolean CROFFSystem::ApplyROFF( SROFFEntity *roff_ent, CROFFSystem::CROFF *roff * none * * * ************************************************************************************************/ -void CROFFSystem::ProcessNote(SROFFEntity *roff_ent, char *note) -{ - char temp[1024]; - int pos, size; +void CROFFSystem::ProcessNote(SROFFEntity *roff_ent, char *note) { + char temp[1024]; + int pos, size; pos = 0; - while(note[pos]) - { + while (note[pos]) { size = 0; - while(note[pos] && note[pos] < ' ') - { + while (note[pos] && note[pos] < ' ') { pos++; } - while(note[pos] && note[pos] >= ' ') - { + while (note[pos] && note[pos] >= ' ') { temp[size++] = note[pos++]; } temp[size] = '\0'; - if (size) - { - if (roff_ent->mIsClient) - { + if (size) { + if (roff_ent->mIsClient) { #ifndef DEDICATED - CGVM_ROFF_NotetrackCallback( roff_ent->mEntID, temp ); + CGVM_ROFF_NotetrackCallback(roff_ent->mEntID, temp); #endif - } - else - { - GVM_ROFF_NotetrackCallback( roff_ent->mEntID, temp ); + } else { + GVM_ROFF_NotetrackCallback(roff_ent->mEntID, temp); } } } @@ -1010,31 +895,27 @@ void CROFFSystem::ProcessNote(SROFFEntity *roff_ent, char *note) // RETURN: // success or failure of the operation //--------------------------------------------------------------------------- -qboolean CROFFSystem::ClearLerp( SROFFEntity *roff_ent ) -{ - sharedEntity_t *ent = NULL; - trajectory_t *originTrajectory = NULL, *angleTrajectory = NULL; - float *origin = NULL, *angle = NULL; +qboolean CROFFSystem::ClearLerp(SROFFEntity *roff_ent) { + sharedEntity_t *ent = NULL; + trajectory_t *originTrajectory = NULL, *angleTrajectory = NULL; + float *origin = NULL, *angle = NULL; #ifndef DEDICATED - vec3_t originTemp, angleTemp; - if (roff_ent->mIsClient) - { - originTrajectory = CGVM_GetOriginTrajectory( roff_ent->mEntID ); - angleTrajectory = CGVM_GetAngleTrajectory( roff_ent->mEntID ); - CGVM_GetOrigin( roff_ent->mEntID, originTemp ); + vec3_t originTemp, angleTemp; + if (roff_ent->mIsClient) { + originTrajectory = CGVM_GetOriginTrajectory(roff_ent->mEntID); + angleTrajectory = CGVM_GetAngleTrajectory(roff_ent->mEntID); + CGVM_GetOrigin(roff_ent->mEntID, originTemp); origin = originTemp; - CGVM_GetAngles( roff_ent->mEntID, angleTemp ); + CGVM_GetAngles(roff_ent->mEntID, angleTemp); angle = angleTemp; - } - else + } else #endif { // Find the entity to apply the roff to - ent = SV_GentityNum( roff_ent->mEntID ); + ent = SV_GentityNum(roff_ent->mEntID); - if ( ent == 0 ) - { // bad stuff + if (ent == 0) { // bad stuff return qfalse; } @@ -1044,8 +925,8 @@ qboolean CROFFSystem::ClearLerp( SROFFEntity *roff_ent ) angle = ent->r.currentAngles; } - SetLerp( originTrajectory, TR_STATIONARY, origin, NULL, sv.time, ROFF_SAMPLE_RATE ); - SetLerp( angleTrajectory, TR_STATIONARY, angle, NULL, sv.time, ROFF_SAMPLE_RATE ); + SetLerp(originTrajectory, TR_STATIONARY, origin, NULL, sv.time, ROFF_SAMPLE_RATE); + SetLerp(angleTrajectory, TR_STATIONARY, angle, NULL, sv.time, ROFF_SAMPLE_RATE); return qtrue; } @@ -1061,20 +942,15 @@ qboolean CROFFSystem::ClearLerp( SROFFEntity *roff_ent ) // RETURN: // none //--------------------------------------------------------------------------- -void CROFFSystem::SetLerp( trajectory_t *tr, trType_t type, vec3_t origin, vec3_t delta, int time, int rate) -{ +void CROFFSystem::SetLerp(trajectory_t *tr, trType_t type, vec3_t origin, vec3_t delta, int time, int rate) { tr->trType = type; tr->trTime = time; - VectorCopy( origin, tr->trBase ); + VectorCopy(origin, tr->trBase); // Check for a NULL delta - if ( delta ) - { - VectorScale( delta, rate, tr->trDelta ); - } - else - { - VectorClear( tr->trDelta ); + if (delta) { + VectorScale(delta, rate, tr->trDelta); + } else { + VectorClear(tr->trDelta); } } - diff --git a/codemp/qcommon/cm_load.cpp b/codemp/qcommon/cm_load.cpp index 2ae8a08980..1e178710a2 100644 --- a/codemp/qcommon/cm_load.cpp +++ b/codemp/qcommon/cm_load.cpp @@ -29,56 +29,52 @@ along with this program; if not, see . #include "../bspc/l_qfiles.h" -void SetPlaneSignbits (cplane_t *out) { - int bits, j; +void SetPlaneSignbits(cplane_t *out) { + int bits, j; // for fast box on planeside test bits = 0; - for (j=0 ; j<3 ; j++) { + for (j = 0; j < 3; j++) { if (out->normal[j] < 0) { - bits |= 1<signbits = bits; } -#endif //BSPC +#endif // BSPC // to allow boxes to be treated as brush models, we allocate // some extra indexes along with those needed by the map -#define BOX_BRUSHES 1 -#define BOX_SIDES 6 -#define BOX_LEAFS 2 -#define BOX_PLANES 12 +#define BOX_BRUSHES 1 +#define BOX_SIDES 6 +#define BOX_LEAFS 2 +#define BOX_PLANES 12 -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) +clipMap_t cmg; // rwwRMG - changed from cm +int c_pointcontents; +int c_traces, c_brush_traces, c_patch_traces; -clipMap_t cmg; //rwwRMG - changed from cm -int c_pointcontents; -int c_traces, c_brush_traces, c_patch_traces; - - -byte *cmod_base; +byte *cmod_base; #ifndef BSPC -cvar_t *cm_noAreas; -cvar_t *cm_noCurves; -cvar_t *cm_playerCurveClip; -cvar_t *cm_extraVerbose; +cvar_t *cm_noAreas; +cvar_t *cm_noCurves; +cvar_t *cm_playerCurveClip; +cvar_t *cm_extraVerbose; #endif -cmodel_t box_model; -cplane_t *box_planes; -cbrush_t *box_brush; - - +cmodel_t box_model; +cplane_t *box_planes; +cbrush_t *box_brush; -void CM_InitBoxHull (void); -void CM_FloodAreaConnections (clipMap_t &cm); +void CM_InitBoxHull(void); +void CM_FloodAreaConnections(clipMap_t &cm); -//rwwRMG - added: -clipMap_t SubBSP[MAX_SUB_BSP]; -int NumSubBSP, TotalSubModels; +// rwwRMG - added: +clipMap_t SubBSP[MAX_SUB_BSP]; +int NumSubBSP, TotalSubModels; /* =============================================================================== @@ -93,133 +89,124 @@ int NumSubBSP, TotalSubModels; CMod_LoadShaders ================= */ -static void CMod_LoadShaders( const lump_t *l, clipMap_t &cm ) -{ - dshader_t *in; - int i, count; - CCMShader *out; +static void CMod_LoadShaders(const lump_t *l, clipMap_t &cm) { + dshader_t *in; + int i, count; + CCMShader *out; in = (dshader_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) { - Com_Error (ERR_DROP, "CMod_LoadShaders: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadShaders: funny lump size"); } count = l->filelen / sizeof(*in); if (count < 1) { - Com_Error (ERR_DROP, "Map with no shaders"); + Com_Error(ERR_DROP, "Map with no shaders"); } - cm.shaders = (CCMShader *)Hunk_Alloc( (1+count) * sizeof( *cm.shaders ), h_high ); + cm.shaders = (CCMShader *)Hunk_Alloc((1 + count) * sizeof(*cm.shaders), h_high); cm.numShaders = count; out = cm.shaders; - for ( i = 0; i < count; i++, in++, out++ ) - { + for (i = 0; i < count; i++, in++, out++) { Q_strncpyz(out->shader, in->shader, MAX_QPATH); - out->contentFlags = LittleLong( in->contentFlags ); - out->surfaceFlags = LittleLong( in->surfaceFlags ); + out->contentFlags = LittleLong(in->contentFlags); + out->surfaceFlags = LittleLong(in->surfaceFlags); } } - /* ================= CMod_LoadSubmodels ================= */ -static void CMod_LoadSubmodels( const lump_t *l, clipMap_t &cm ) { - dmodel_t *in; - cmodel_t *out; - int i, j, count; - int *indexes; +static void CMod_LoadSubmodels(const lump_t *l, clipMap_t &cm) { + dmodel_t *in; + cmodel_t *out; + int i, j, count; + int *indexes; in = (dmodel_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadSubmodels: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadSubmodels: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map with no models"); - cm.cmodels = (struct cmodel_s *)Hunk_Alloc( count * sizeof( *cm.cmodels ), h_high ); + Com_Error(ERR_DROP, "Map with no models"); + cm.cmodels = (struct cmodel_s *)Hunk_Alloc(count * sizeof(*cm.cmodels), h_high); cm.numSubModels = count; - if ( count > MAX_SUBMODELS ) { - Com_Error( ERR_DROP, "MAX_SUBMODELS exceeded" ); + if (count > MAX_SUBMODELS) { + Com_Error(ERR_DROP, "MAX_SUBMODELS exceeded"); } - for ( i=0 ; imins[j] = LittleFloat (in->mins[j]) - 1; - out->maxs[j] = LittleFloat (in->maxs[j]) + 1; + for (j = 0; j < 3; j++) { // spread the mins / maxs by a pixel + out->mins[j] = LittleFloat(in->mins[j]) - 1; + out->maxs[j] = LittleFloat(in->maxs[j]) + 1; } - //rwwRMG - sof2 doesn't have to add this &cm == &cmg check. - //Are they getting leaf data elsewhere? (the reason this needs to be done is - //in sub bsp instances the first brush model isn't necessary a world model and might be - //real architecture) - if ( i == 0 && &cm == &cmg ) { + // rwwRMG - sof2 doesn't have to add this &cm == &cmg check. + // Are they getting leaf data elsewhere? (the reason this needs to be done is + // in sub bsp instances the first brush model isn't necessary a world model and might be + // real architecture) + if (i == 0 && &cm == &cmg) { out->firstNode = 0; - continue; // world model doesn't need other info + continue; // world model doesn't need other info } // make a "leaf" just to hold the model's brushes and surfaces out->firstNode = -1; // make a "leaf" just to hold the model's brushes and surfaces - out->leaf.numLeafBrushes = LittleLong( in->numBrushes ); - indexes = (int *)Hunk_Alloc( out->leaf.numLeafBrushes * 4, h_high ); + out->leaf.numLeafBrushes = LittleLong(in->numBrushes); + indexes = (int *)Hunk_Alloc(out->leaf.numLeafBrushes * 4, h_high); out->leaf.firstLeafBrush = indexes - cm.leafbrushes; - for ( j = 0 ; j < out->leaf.numLeafBrushes ; j++ ) { - indexes[j] = LittleLong( in->firstBrush ) + j; + for (j = 0; j < out->leaf.numLeafBrushes; j++) { + indexes[j] = LittleLong(in->firstBrush) + j; } - out->leaf.numLeafSurfaces = LittleLong( in->numSurfaces ); - indexes = (int *)Hunk_Alloc( out->leaf.numLeafSurfaces * 4, h_high ); + out->leaf.numLeafSurfaces = LittleLong(in->numSurfaces); + indexes = (int *)Hunk_Alloc(out->leaf.numLeafSurfaces * 4, h_high); out->leaf.firstLeafSurface = indexes - cm.leafsurfaces; - for ( j = 0 ; j < out->leaf.numLeafSurfaces ; j++ ) { - indexes[j] = LittleLong( in->firstSurface ) + j; + for (j = 0; j < out->leaf.numLeafSurfaces; j++) { + indexes[j] = LittleLong(in->firstSurface) + j; } } } - /* ================= CMod_LoadNodes ================= */ -static void CMod_LoadNodes( const lump_t *l, clipMap_t &cm ) { - dnode_t *in; - int child; - cNode_t *out; - int i, j, count; +static void CMod_LoadNodes(const lump_t *l, clipMap_t &cm) { + dnode_t *in; + int child; + cNode_t *out; + int i, j, count; in = (dnode_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadNodes: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadNodes: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map has no nodes"); - cm.nodes = (cNode_t *)Hunk_Alloc( count * sizeof( *cm.nodes ), h_high ); + Com_Error(ERR_DROP, "Map has no nodes"); + cm.nodes = (cNode_t *)Hunk_Alloc(count * sizeof(*cm.nodes), h_high); cm.numNodes = count; out = cm.nodes; - for (i=0 ; iplane = cm.planes + LittleLong( in->planeNum ); - for (j=0 ; j<2 ; j++) - { - child = LittleLong (in->children[j]); + for (i = 0; i < count; i++, out++, in++) { + out->plane = cm.planes + LittleLong(in->planeNum); + for (j = 0; j < 2; j++) { + child = LittleLong(in->children[j]); out->children[j] = child; } } - } /* @@ -228,7 +215,7 @@ CM_BoundBrush ================= */ -void CM_BoundBrush( cbrush_t *b ) { +void CM_BoundBrush(cbrush_t *b) { b->bounds[0][0] = -b->sides[0].plane->dist; b->bounds[1][0] = b->sides[1].plane->dist; @@ -239,42 +226,40 @@ void CM_BoundBrush( cbrush_t *b ) { b->bounds[1][2] = b->sides[5].plane->dist; } - /* ================= CMod_LoadBrushes ================= */ -void CMod_LoadBrushes( const lump_t *l, clipMap_t &cm ) { - dbrush_t *in; - cbrush_t *out; - int i, count; +void CMod_LoadBrushes(const lump_t *l, clipMap_t &cm) { + dbrush_t *in; + cbrush_t *out; + int i, count; in = (dbrush_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) { - Com_Error (ERR_DROP, "CMod_LoadBrushes: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadBrushes: funny lump size"); } count = l->filelen / sizeof(*in); - cm.brushes = (cbrush_t *)Hunk_Alloc( ( BOX_BRUSHES + count ) * sizeof( *cm.brushes ), h_high ); + cm.brushes = (cbrush_t *)Hunk_Alloc((BOX_BRUSHES + count) * sizeof(*cm.brushes), h_high); cm.numBrushes = count; out = cm.brushes; - for ( i=0 ; isides = cm.brushsides + LittleLong(in->firstSide); out->numsides = LittleLong(in->numSides); - out->shaderNum = LittleLong( in->shaderNum ); - if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) { - Com_Error( ERR_DROP, "CMod_LoadBrushes: bad shaderNum: %i", out->shaderNum ); + out->shaderNum = LittleLong(in->shaderNum); + if (out->shaderNum < 0 || out->shaderNum >= cm.numShaders) { + Com_Error(ERR_DROP, "CMod_LoadBrushes: bad shaderNum: %i", out->shaderNum); } out->contents = cm.shaders[out->shaderNum].contentFlags; - CM_BoundBrush( out ); + CM_BoundBrush(out); } - } /* @@ -282,33 +267,31 @@ void CMod_LoadBrushes( const lump_t *l, clipMap_t &cm ) { CMod_LoadLeafs ================= */ -static void CMod_LoadLeafs (const lump_t *l, clipMap_t &cm) -{ - int i; - cLeaf_t *out; - dleaf_t *in; - int count; +static void CMod_LoadLeafs(const lump_t *l, clipMap_t &cm) { + int i; + cLeaf_t *out; + dleaf_t *in; + int count; in = (dleaf_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadLeafs: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadLeafs: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map with no leafs"); + Com_Error(ERR_DROP, "Map with no leafs"); - cm.leafs = (cLeaf_t *)Hunk_Alloc( ( BOX_LEAFS + count ) * sizeof( *cm.leafs ), h_high ); + cm.leafs = (cLeaf_t *)Hunk_Alloc((BOX_LEAFS + count) * sizeof(*cm.leafs), h_high); cm.numLeafs = count; out = cm.leafs; - for ( i=0 ; icluster = LittleLong (in->cluster); - out->area = LittleLong (in->area); - out->firstLeafBrush = LittleLong (in->firstLeafBrush); - out->numLeafBrushes = LittleLong (in->numLeafBrushes); - out->firstLeafSurface = LittleLong (in->firstLeafSurface); - out->numLeafSurfaces = LittleLong (in->numLeafSurfaces); + for (i = 0; i < count; i++, in++, out++) { + out->cluster = LittleLong(in->cluster); + out->area = LittleLong(in->area); + out->firstLeafBrush = LittleLong(in->firstLeafBrush); + out->numLeafBrushes = LittleLong(in->numLeafBrushes); + out->firstLeafSurface = LittleLong(in->firstLeafSurface); + out->numLeafSurfaces = LittleLong(in->numLeafSurfaces); if (out->cluster >= cm.numClusters) cm.numClusters = out->cluster + 1; @@ -316,8 +299,8 @@ static void CMod_LoadLeafs (const lump_t *l, clipMap_t &cm) cm.numAreas = out->area + 1; } - cm.areas = (cArea_t *)Hunk_Alloc( cm.numAreas * sizeof( *cm.areas ), h_high ); - cm.areaPortals = (int *)Hunk_Alloc( cm.numAreas * cm.numAreas * sizeof( *cm.areaPortals ), h_high ); + cm.areas = (cArea_t *)Hunk_Alloc(cm.numAreas * sizeof(*cm.areas), h_high); + cm.areaPortals = (int *)Hunk_Alloc(cm.numAreas * cm.numAreas * sizeof(*cm.areaPortals), h_high); } /* @@ -325,38 +308,35 @@ static void CMod_LoadLeafs (const lump_t *l, clipMap_t &cm) CMod_LoadPlanes ================= */ -static void CMod_LoadPlanes (const lump_t *l, clipMap_t &cm) -{ - int i, j; - cplane_t *out; - dplane_t *in; - int count; - int bits; +static void CMod_LoadPlanes(const lump_t *l, clipMap_t &cm) { + int i, j; + cplane_t *out; + dplane_t *in; + int count; + int bits; in = (dplane_t *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadPlanes: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadPlanes: funny lump size"); count = l->filelen / sizeof(*in); if (count < 1) - Com_Error (ERR_DROP, "Map with no planes"); - cm.planes = (struct cplane_s *)Hunk_Alloc( ( BOX_PLANES + count ) * sizeof( *cm.planes ), h_high ); + Com_Error(ERR_DROP, "Map with no planes"); + cm.planes = (struct cplane_s *)Hunk_Alloc((BOX_PLANES + count) * sizeof(*cm.planes), h_high); cm.numPlanes = count; out = cm.planes; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + for (j = 0; j < 3; j++) { + out->normal[j] = LittleFloat(in->normal[j]); if (out->normal[j] < 0) - bits |= 1<dist = LittleFloat (in->dist); - out->type = PlaneTypeForNormal( out->normal ); + out->dist = LittleFloat(in->dist); + out->type = PlaneTypeForNormal(out->normal); out->signbits = bits; } } @@ -366,25 +346,24 @@ static void CMod_LoadPlanes (const lump_t *l, clipMap_t &cm) CMod_LoadLeafBrushes ================= */ -static void CMod_LoadLeafBrushes (const lump_t *l, clipMap_t &cm) -{ - int i; - int *out; - int *in; - int count; +static void CMod_LoadLeafBrushes(const lump_t *l, clipMap_t &cm) { + int i; + int *out; + int *in; + int count; in = (int *)(cmod_base + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadLeafBrushes: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadLeafBrushes: funny lump size"); count = l->filelen / sizeof(*in); - cm.leafbrushes = (int *)Hunk_Alloc( (count + BOX_BRUSHES) * sizeof( *cm.leafbrushes ), h_high ); + cm.leafbrushes = (int *)Hunk_Alloc((count + BOX_BRUSHES) * sizeof(*cm.leafbrushes), h_high); cm.numLeafBrushes = count; out = cm.leafbrushes; - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "CMod_LoadLeafSurfaces: funny lump size"); + Com_Error(ERR_DROP, "CMod_LoadLeafSurfaces: funny lump size"); count = l->filelen / sizeof(*in); - cm.leafsurfaces = (int *)Hunk_Alloc( count * sizeof( *cm.leafsurfaces ), h_high ); + cm.leafsurfaces = (int *)Hunk_Alloc(count * sizeof(*cm.leafsurfaces), h_high); cm.numLeafSurfaces = count; out = cm.leafsurfaces; - for ( i=0 ; ifileofs); - if ( l->filelen % sizeof(*in) ) { - Com_Error (ERR_DROP, "CMod_LoadBrushSides: funny lump size"); + if (l->filelen % sizeof(*in)) { + Com_Error(ERR_DROP, "CMod_LoadBrushSides: funny lump size"); } count = l->filelen / sizeof(*in); - cm.brushsides = (cbrushside_t *)Hunk_Alloc( ( BOX_SIDES + count ) * sizeof( *cm.brushsides ), h_high ); + cm.brushsides = (cbrushside_t *)Hunk_Alloc((BOX_SIDES + count) * sizeof(*cm.brushsides), h_high); cm.numBrushSides = count; out = cm.brushsides; - for ( i=0 ; iplaneNum ); + for (i = 0; i < count; i++, in++, out++) { + num = LittleLong(in->planeNum); out->plane = &cm.planes[num]; - out->shaderNum = LittleLong( in->shaderNum ); - if ( out->shaderNum < 0 || out->shaderNum >= cm.numShaders ) { - Com_Error( ERR_DROP, "CMod_LoadBrushSides: bad shaderNum: %i", out->shaderNum ); + out->shaderNum = LittleLong(in->shaderNum); + if (out->shaderNum < 0 || out->shaderNum >= cm.numShaders) { + Com_Error(ERR_DROP, "CMod_LoadBrushSides: bad shaderNum: %i", out->shaderNum); } } } - /* ================= CMod_LoadEntityString ================= */ -static void CMod_LoadEntityString( const lump_t *l, clipMap_t &cm, const char* name ) { +static void CMod_LoadEntityString(const lump_t *l, clipMap_t &cm, const char *name) { fileHandle_t h; char entName[MAX_QPATH]; @@ -466,8 +442,7 @@ static void CMod_LoadEntityString( const lump_t *l, clipMap_t &cm, const char* n entName[entNameLen - 2] = 'n'; entName[entNameLen - 1] = 't'; const int iEntityFileLen = FS_FOpenFileRead(entName, &h, qfalse); - if (h) - { + if (h) { cm.entityString = (char *)Hunk_Alloc(iEntityFileLen + 1, h_high); cm.numEntityChars = iEntityFileLen + 1; FS_Read(cm.entityString, iEntityFileLen, h); @@ -477,9 +452,9 @@ static void CMod_LoadEntityString( const lump_t *l, clipMap_t &cm, const char* n return; } - cm.entityString = (char *)Hunk_Alloc( l->filelen, h_high ); + cm.entityString = (char *)Hunk_Alloc(l->filelen, h_high); cm.numEntityChars = l->filelen; - Com_Memcpy (cm.entityString, cmod_base + l->fileofs, l->filelen); + Com_Memcpy(cm.entityString, cmod_base + l->fileofs, l->filelen); } /* @@ -487,88 +462,87 @@ static void CMod_LoadEntityString( const lump_t *l, clipMap_t &cm, const char* n CMod_LoadVisibility ================= */ -#define VIS_HEADER 8 -static void CMod_LoadVisibility( const lump_t *l, clipMap_t &cm ) { - int len; - byte *buf; - - len = l->filelen; - if ( !len ) { - cm.clusterBytes = ( cm.numClusters + 31 ) & ~31; - cm.visibility = (unsigned char *)Hunk_Alloc( cm.clusterBytes, h_high ); - Com_Memset( cm.visibility, 255, cm.clusterBytes ); +#define VIS_HEADER 8 +static void CMod_LoadVisibility(const lump_t *l, clipMap_t &cm) { + int len; + byte *buf; + + len = l->filelen; + if (!len) { + cm.clusterBytes = (cm.numClusters + 31) & ~31; + cm.visibility = (unsigned char *)Hunk_Alloc(cm.clusterBytes, h_high); + Com_Memset(cm.visibility, 255, cm.clusterBytes); return; } buf = cmod_base + l->fileofs; cm.vised = qtrue; - cm.visibility = (unsigned char *)Hunk_Alloc( len, h_high ); - cm.numClusters = LittleLong( ((int *)buf)[0] ); - cm.clusterBytes = LittleLong( ((int *)buf)[1] ); - Com_Memcpy (cm.visibility, buf + VIS_HEADER, len - VIS_HEADER ); + cm.visibility = (unsigned char *)Hunk_Alloc(len, h_high); + cm.numClusters = LittleLong(((int *)buf)[0]); + cm.clusterBytes = LittleLong(((int *)buf)[1]); + Com_Memcpy(cm.visibility, buf + VIS_HEADER, len - VIS_HEADER); } //================================================================== - /* ================= CMod_LoadPatches ================= */ -#define MAX_PATCH_VERTS 1024 -static void CMod_LoadPatches( const lump_t *surfs, const lump_t *verts, clipMap_t &cm ) { - drawVert_t *dv, *dv_p; - dsurface_t *in; - int count; - int i, j; - int c; - cPatch_t *patch; - vec3_t points[MAX_PATCH_VERTS]; - int width, height; - int shaderNum; +#define MAX_PATCH_VERTS 1024 +static void CMod_LoadPatches(const lump_t *surfs, const lump_t *verts, clipMap_t &cm) { + drawVert_t *dv, *dv_p; + dsurface_t *in; + int count; + int i, j; + int c; + cPatch_t *patch; + vec3_t points[MAX_PATCH_VERTS]; + int width, height; + int shaderNum; in = (dsurface_t *)(cmod_base + surfs->fileofs); if (surfs->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); cm.numSurfaces = count = surfs->filelen / sizeof(*in); - cm.surfaces = (cPatch_t ** )Hunk_Alloc( cm.numSurfaces * sizeof( cm.surfaces[0] ), h_high ); + cm.surfaces = (cPatch_t **)Hunk_Alloc(cm.numSurfaces * sizeof(cm.surfaces[0]), h_high); dv = (drawVert_t *)(cmod_base + verts->fileofs); if (verts->filelen % sizeof(*dv)) - Com_Error (ERR_DROP, "MOD_LoadBmodel: funny lump size"); + Com_Error(ERR_DROP, "MOD_LoadBmodel: funny lump size"); // scan through all the surfaces, but only load patches, // not planar faces - for ( i = 0 ; i < count ; i++, in++ ) { - if ( LittleLong( in->surfaceType ) != MST_PATCH ) { - continue; // ignore other surfaces + for (i = 0; i < count; i++, in++) { + if (LittleLong(in->surfaceType) != MST_PATCH) { + continue; // ignore other surfaces } // FIXME: check for non-colliding patches - cm.surfaces[ i ] = patch = (cPatch_t *)Hunk_Alloc( sizeof( *patch ), h_high ); + cm.surfaces[i] = patch = (cPatch_t *)Hunk_Alloc(sizeof(*patch), h_high); // load the full drawverts onto the stack - width = LittleLong( in->patchWidth ); - height = LittleLong( in->patchHeight ); + width = LittleLong(in->patchWidth); + height = LittleLong(in->patchHeight); c = width * height; - if ( c > MAX_PATCH_VERTS ) { - Com_Error( ERR_DROP, "ParseMesh: MAX_PATCH_VERTS" ); + if (c > MAX_PATCH_VERTS) { + Com_Error(ERR_DROP, "ParseMesh: MAX_PATCH_VERTS"); } - dv_p = dv + LittleLong( in->firstVert ); - for ( j = 0 ; j < c ; j++, dv_p++ ) { - points[j][0] = LittleFloat( dv_p->xyz[0] ); - points[j][1] = LittleFloat( dv_p->xyz[1] ); - points[j][2] = LittleFloat( dv_p->xyz[2] ); + dv_p = dv + LittleLong(in->firstVert); + for (j = 0; j < c; j++, dv_p++) { + points[j][0] = LittleFloat(dv_p->xyz[0]); + points[j][1] = LittleFloat(dv_p->xyz[1]); + points[j][2] = LittleFloat(dv_p->xyz[2]); } - shaderNum = LittleLong( in->shaderNum ); + shaderNum = LittleLong(in->shaderNum); patch->contents = cm.shaders[shaderNum].contentFlags; patch->surfaceFlags = cm.shaders[shaderNum].surfaceFlags; // create the internal facet structure - patch->pc = CM_GeneratePatchCollide( width, height, points ); + patch->pc = CM_GeneratePatchCollide(width, height, points); } } @@ -582,25 +556,22 @@ Loads in the map and all submodels ================== */ void *gpvCachedMapDiskImage = NULL; -char gsCachedMapDiskImage[MAX_QPATH]; -qboolean gbUsingCachedMapDataRightNow = qfalse; // if true, signifies that you can't delete this at the moment!! (used during z_malloc()-fail recovery attempt) +char gsCachedMapDiskImage[MAX_QPATH]; +qboolean gbUsingCachedMapDataRightNow = qfalse; // if true, signifies that you can't delete this at the moment!! (used during z_malloc()-fail recovery attempt) // called in response to a "devmapbsp blah" or "devmapall blah" command, do NOT use inside CM_Load unless you pass in qtrue // // new bool return used to see if anything was freed, used during z_malloc failure re-try // -qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) -{ +qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) { qboolean bActuallyFreedSomething = qfalse; - if (bGuaranteedOkToDelete || !gbUsingCachedMapDataRightNow) - { + if (bGuaranteedOkToDelete || !gbUsingCachedMapDataRightNow) { // dump cached disk image... // - if (gpvCachedMapDiskImage) - { - Z_Free( gpvCachedMapDiskImage ); - gpvCachedMapDiskImage = NULL; + if (gpvCachedMapDiskImage) { + Z_Free(gpvCachedMapDiskImage); + gpvCachedMapDiskImage = NULL; bActuallyFreedSomething = qtrue; } @@ -614,54 +585,48 @@ qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete) return bActuallyFreedSomething; } +static void CM_LoadMap_Actual(const char *name, qboolean clientload, int *checksum, clipMap_t &cm) { // rwwRMG - function needs heavy modification + int *buf; + dheader_t header; + static unsigned last_checksum; + char origName[MAX_OSPATH]; + void *newBuff = 0; - - - -static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *checksum, clipMap_t &cm ) -{ //rwwRMG - function needs heavy modification - int *buf; - dheader_t header; - static unsigned last_checksum; - char origName[MAX_OSPATH]; - void *newBuff = 0; - - if ( !name || !name[0] ) { - Com_Error( ERR_DROP, "CM_LoadMap: NULL name" ); + if (!name || !name[0]) { + Com_Error(ERR_DROP, "CM_LoadMap: NULL name"); } #ifndef BSPC - cm_noAreas = Cvar_Get ("cm_noAreas", "0", CVAR_CHEAT); - cm_noCurves = Cvar_Get ("cm_noCurves", "0", CVAR_CHEAT); - cm_playerCurveClip = Cvar_Get ("cm_playerCurveClip", "1", CVAR_ARCHIVE_ND|CVAR_CHEAT ); - cm_extraVerbose = Cvar_Get ("cm_extraVerbose", "0", CVAR_TEMP ); + cm_noAreas = Cvar_Get("cm_noAreas", "0", CVAR_CHEAT); + cm_noCurves = Cvar_Get("cm_noCurves", "0", CVAR_CHEAT); + cm_playerCurveClip = Cvar_Get("cm_playerCurveClip", "1", CVAR_ARCHIVE_ND | CVAR_CHEAT); + cm_extraVerbose = Cvar_Get("cm_extraVerbose", "0", CVAR_TEMP); #endif - Com_DPrintf( "CM_LoadMap( %s, %i )\n", name, clientload ); + Com_DPrintf("CM_LoadMap( %s, %i )\n", name, clientload); - if ( !strcmp( cm.name, name ) && clientload ) { - if ( checksum ) + if (!strcmp(cm.name, name) && clientload) { + if (checksum) *checksum = last_checksum; return; } strcpy(origName, name); - if (&cm == &cmg) - { + if (&cm == &cmg) { // free old stuff CM_ClearMap(); CM_ClearLevelPatches(); } // free old stuff - Com_Memset( &cm, 0, sizeof( cm ) ); + Com_Memset(&cm, 0, sizeof(cm)); - if ( !name[0] ) { + if (!name[0]) { cm.numLeafs = 1; cm.numClusters = 1; cm.numAreas = 1; - cm.cmodels = (struct cmodel_s *)Hunk_Alloc( sizeof( *cm.cmodels ), h_high ); - if ( checksum ) + cm.cmodels = (struct cmodel_s *)Hunk_Alloc(sizeof(*cm.cmodels), h_high); + if (checksum) *checksum = 0; return; } @@ -669,12 +634,12 @@ static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *check // // load the file // - //rww - Doesn't this sort of defeat the purpose? We're clearing it even if the map is the same as the last one! - //Not touching it though in case I'm just overlooking something. - if (gpvCachedMapDiskImage && &cm == &cmg) // MP code: this'll only be NZ if we got an ERR_DROP during last map load, - { // so it's really just a safety measure. - Z_Free( gpvCachedMapDiskImage); - gpvCachedMapDiskImage = NULL; + // rww - Doesn't this sort of defeat the purpose? We're clearing it even if the map is the same as the last one! + // Not touching it though in case I'm just overlooking something. + if (gpvCachedMapDiskImage && &cm == &cmg) // MP code: this'll only be NZ if we got an ERR_DROP during last map load, + { // so it's really just a safety measure. + Z_Free(gpvCachedMapDiskImage); + gpvCachedMapDiskImage = NULL; } #ifndef BSPC @@ -685,16 +650,14 @@ static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *check // buf = NULL; fileHandle_t h; - const int iBSPLen = FS_FOpenFileRead( name, &h, qfalse ); - if (h) - { - newBuff = Z_Malloc( iBSPLen, TAG_BSP_DISKIMAGE ); - FS_Read( newBuff, iBSPLen, h); - FS_FCloseFile( h ); - - buf = (int*) newBuff; // so the rest of the code works as normal - if (&cm == &cmg) - { + const int iBSPLen = FS_FOpenFileRead(name, &h, qfalse); + if (h) { + newBuff = Z_Malloc(iBSPLen, TAG_BSP_DISKIMAGE); + FS_Read(newBuff, iBSPLen, h); + FS_FCloseFile(h); + + buf = (int *)newBuff; // so the rest of the code works as normal + if (&cm == &cmg) { gpvCachedMapDiskImage = newBuff; newBuff = 0; } @@ -703,113 +666,101 @@ static void CM_LoadMap_Actual( const char *name, qboolean clientload, int *check // } #else - const int iBSPLen = LoadQuakeFile((quakefile_t *) name, (void **)&buf); + const int iBSPLen = LoadQuakeFile((quakefile_t *)name, (void **)&buf); #endif - if ( !buf ) { - Com_Error (ERR_DROP, "Couldn't load %s", name); + if (!buf) { + Com_Error(ERR_DROP, "Couldn't load %s", name); } - last_checksum = LittleLong (Com_BlockChecksum (buf, iBSPLen)); - if ( checksum ) + last_checksum = LittleLong(Com_BlockChecksum(buf, iBSPLen)); + if (checksum) *checksum = last_checksum; header = *(dheader_t *)buf; - for (size_t i=0 ; iinteger -// || we're on a big-endian machine - ) - { - Z_Free( gpvCachedMapDiskImage ); - gpvCachedMapDiskImage = NULL; - } - else - { + if (Sys_LowPhysicalMemory() || com_dedicated->integer + // || we're on a big-endian machine + ) { + Z_Free(gpvCachedMapDiskImage); + gpvCachedMapDiskImage = NULL; + } else { // ... do nothing, and let the renderer free it after it's finished playing with it... // } #else - FS_FreeFile (buf); + FS_FreeFile(buf); #endif - CM_FloodAreaConnections (cm); + CM_FloodAreaConnections(cm); // allow this to be cached if it is loaded by the server - if ( !clientload ) { - Q_strncpyz( cm.name, origName, sizeof( cm.name ) ); + if (!clientload) { + Q_strncpyz(cm.name, origName, sizeof(cm.name)); } } - // need a wrapper function around this because of multiple returns, need to ensure bool is correct... // -void CM_LoadMap( const char *name, qboolean clientload, int *checksum ) -{ - gbUsingCachedMapDataRightNow = qtrue; // !!!!!!!!!!!!!!!!!! +void CM_LoadMap(const char *name, qboolean clientload, int *checksum) { + gbUsingCachedMapDataRightNow = qtrue; // !!!!!!!!!!!!!!!!!! - CM_LoadMap_Actual( name, clientload, checksum, cmg ); + CM_LoadMap_Actual(name, clientload, checksum, cmg); - gbUsingCachedMapDataRightNow = qfalse; // !!!!!!!!!!!!!!!!!! + gbUsingCachedMapDataRightNow = qfalse; // !!!!!!!!!!!!!!!!!! } - - /* ================== CM_ClearMap ================== */ -void CM_ClearMap( void ) -{ - int i; +void CM_ClearMap(void) { + int i; - Com_Memset( &cmg, 0, sizeof( cmg ) ); + Com_Memset(&cmg, 0, sizeof(cmg)); CM_ClearLevelPatches(); - for(i = 0; i < NumSubBSP; i++) - { + for (i = 0; i < NumSubBSP; i++) { memset(&SubBSP[i], 0, sizeof(SubBSP[0])); } NumSubBSP = 0; @@ -821,38 +772,30 @@ void CM_ClearMap( void ) CM_ClipHandleToModel ================== */ -cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) { - int i; - int count; +cmodel_t *CM_ClipHandleToModel(clipHandle_t handle, clipMap_t **clipMap) { + int i; + int count; - if ( handle < 0 ) - { - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle ); + if (handle < 0) { + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle); } - if ( handle < cmg.numSubModels ) - { - if (clipMap) - { + if (handle < cmg.numSubModels) { + if (clipMap) { *clipMap = &cmg; } return &cmg.cmodels[handle]; } - if ( handle == BOX_MODEL_HANDLE ) - { - if (clipMap) - { + if (handle == BOX_MODEL_HANDLE) { + if (clipMap) { *clipMap = &cmg; } return &box_model; } count = cmg.numSubModels; - for(i = 0; i < NumSubBSP; i++) - { - if (handle < count + SubBSP[i].numSubModels) - { - if (clipMap) - { + for (i = 0; i < NumSubBSP; i++) { + if (handle < count + SubBSP[i].numSubModels) { + if (clipMap) { *clipMap = &SubBSP[i]; } return &SubBSP[i].cmodels[handle - count]; @@ -860,12 +803,10 @@ cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) { count += SubBSP[i].numSubModels; } - if ( handle < MAX_SUBMODELS ) - { - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle (count: %i) < (handle: %i) < (max: %i)", - cmg.numSubModels, handle, MAX_SUBMODELS ); + if (handle < MAX_SUBMODELS) { + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle (count: %i) < (handle: %i) < (max: %i)", cmg.numSubModels, handle, MAX_SUBMODELS); } - Com_Error( ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle + MAX_SUBMODELS ); + Com_Error(ERR_DROP, "CM_ClipHandleToModel: bad handle %i", handle + MAX_SUBMODELS); return NULL; } @@ -875,43 +816,35 @@ cmodel_t *CM_ClipHandleToModel( clipHandle_t handle, clipMap_t **clipMap ) { CM_InlineModel ================== */ -clipHandle_t CM_InlineModel( int index ) { - if ( index < 0 || index >= TotalSubModels ) { - Com_Error( ERR_DROP, "CM_InlineModel: bad number: %d >= %d (may need to re-BSP map?)", index, TotalSubModels ); +clipHandle_t CM_InlineModel(int index) { + if (index < 0 || index >= TotalSubModels) { + Com_Error(ERR_DROP, "CM_InlineModel: bad number: %d >= %d (may need to re-BSP map?)", index, TotalSubModels); } return index; } -int CM_NumInlineModels( void ) { - return cmg.numSubModels; -} +int CM_NumInlineModels(void) { return cmg.numSubModels; } -char *CM_EntityString( void ) { - return cmg.entityString; -} +char *CM_EntityString(void) { return cmg.entityString; } -char *CM_SubBSPEntityString( int index ) -{ - return SubBSP[index].entityString; -} +char *CM_SubBSPEntityString(int index) { return SubBSP[index].entityString; } -int CM_LeafCluster( int leafnum ) { +int CM_LeafCluster(int leafnum) { if (leafnum < 0 || leafnum >= cmg.numLeafs) { - Com_Error (ERR_DROP, "CM_LeafCluster: bad number"); + Com_Error(ERR_DROP, "CM_LeafCluster: bad number"); } return cmg.leafs[leafnum].cluster; } -int CM_LeafArea( int leafnum ) { - if ( leafnum < 0 || leafnum >= cmg.numLeafs ) { - Com_Error (ERR_DROP, "CM_LeafArea: bad number"); +int CM_LeafArea(int leafnum) { + if (leafnum < 0 || leafnum >= cmg.numLeafs) { + Com_Error(ERR_DROP, "CM_LeafArea: bad number"); } return cmg.leafs[leafnum].area; } //======================================================================= - /* =================== CM_InitBoxHull @@ -920,12 +853,11 @@ Set up the planes and nodes so that the six floats of a bounding box can just be stored out and get a proper clipping hull structure. =================== */ -void CM_InitBoxHull (void) -{ - int i; - int side; - cplane_t *p; - cbrushside_t *s; +void CM_InitBoxHull(void) { + int i; + int side; + cplane_t *p; + cbrushside_t *s; box_planes = &cmg.planes[cmg.numPlanes]; @@ -936,33 +868,32 @@ void CM_InitBoxHull (void) box_model.firstNode = -1; box_model.leaf.numLeafBrushes = 1; -// box_model.leaf.firstLeafBrush = cmg.numBrushes; + // box_model.leaf.firstLeafBrush = cmg.numBrushes; box_model.leaf.firstLeafBrush = cmg.numLeafBrushes; cmg.leafbrushes[cmg.numLeafBrushes] = cmg.numBrushes; - for (i=0 ; i<6 ; i++) - { - side = i&1; + for (i = 0; i < 6; i++) { + side = i & 1; // brush sides - s = &cmg.brushsides[cmg.numBrushSides+i]; - s->plane = cmg.planes + (cmg.numPlanes+i*2+side); + s = &cmg.brushsides[cmg.numBrushSides + i]; + s->plane = cmg.planes + (cmg.numPlanes + i * 2 + side); s->shaderNum = cmg.numShaders; // planes - p = &box_planes[i*2]; - p->type = i>>1; + p = &box_planes[i * 2]; + p->type = i >> 1; p->signbits = 0; - VectorClear (p->normal); - p->normal[i>>1] = 1; + VectorClear(p->normal); + p->normal[i >> 1] = 1; - p = &box_planes[i*2+1]; - p->type = 3 + (i>>1); + p = &box_planes[i * 2 + 1]; + p->type = 3 + (i >> 1); p->signbits = 0; - VectorClear (p->normal); - p->normal[i>>1] = -1; + VectorClear(p->normal); + p->normal[i >> 1] = -1; - SetPlaneSignbits( p ); + SetPlaneSignbits(p); } } @@ -975,12 +906,12 @@ BSP trees instead of being compared directly. Capsules are handled differently though. =================== */ -clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs, int capsule ) { +clipHandle_t CM_TempBoxModel(const vec3_t mins, const vec3_t maxs, int capsule) { - VectorCopy( mins, box_model.mins ); - VectorCopy( maxs, box_model.maxs ); + VectorCopy(mins, box_model.mins); + VectorCopy(maxs, box_model.maxs); - if ( capsule ) { + if (capsule) { return CAPSULE_MODEL_HANDLE; } @@ -997,8 +928,8 @@ clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs, int capsule box_planes[10].dist = mins[2]; box_planes[11].dist = -mins[2]; - VectorCopy( mins, box_brush->bounds[0] ); - VectorCopy( maxs, box_brush->bounds[1] ); + VectorCopy(mins, box_brush->bounds[0]); + VectorCopy(maxs, box_brush->bounds[1]); return BOX_MODEL_HANDLE; } @@ -1008,95 +939,81 @@ clipHandle_t CM_TempBoxModel( const vec3_t mins, const vec3_t maxs, int capsule CM_ModelBounds =================== */ -void CM_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) { - cmodel_t *cmod; +void CM_ModelBounds(clipHandle_t model, vec3_t mins, vec3_t maxs) { + cmodel_t *cmod; - cmod = CM_ClipHandleToModel( model ); - VectorCopy( cmod->mins, mins ); - VectorCopy( cmod->maxs, maxs ); + cmod = CM_ClipHandleToModel(model); + VectorCopy(cmod->mins, mins); + VectorCopy(cmod->maxs, maxs); } -int CM_LoadSubBSP(const char *name, qboolean clientload) -{ - int i; - int checksum; - int count; +int CM_LoadSubBSP(const char *name, qboolean clientload) { + int i; + int checksum; + int count; count = cmg.numSubModels; - for(i = 0; i < NumSubBSP; i++) - { - if (!Q_stricmp(name, SubBSP[i].name)) - { + for (i = 0; i < NumSubBSP; i++) { + if (!Q_stricmp(name, SubBSP[i].name)) { return count; } count += SubBSP[i].numSubModels; } - if (NumSubBSP == MAX_SUB_BSP) - { - Com_Error (ERR_DROP, "CM_LoadSubBSP: too many unique sub BSPs"); + if (NumSubBSP == MAX_SUB_BSP) { + Com_Error(ERR_DROP, "CM_LoadSubBSP: too many unique sub BSPs"); } - CM_LoadMap_Actual(name, clientload, &checksum, SubBSP[NumSubBSP] ); + CM_LoadMap_Actual(name, clientload, &checksum, SubBSP[NumSubBSP]); NumSubBSP++; return count; } -int CM_FindSubBSP(int modelIndex) -{ - int i; - int count; +int CM_FindSubBSP(int modelIndex) { + int i; + int count; count = cmg.numSubModels; - if (modelIndex < count) - { // belongs to the main bsp + if (modelIndex < count) { // belongs to the main bsp return -1; } - for(i = 0; i < NumSubBSP; i++) - { + for (i = 0; i < NumSubBSP; i++) { count += SubBSP[i].numSubModels; - if (modelIndex < count) - { + if (modelIndex < count) { return i; } } return -1; } -void CM_GetWorldBounds ( vec3_t mins, vec3_t maxs ) -{ - VectorCopy ( cmg.cmodels[0].mins, mins ); - VectorCopy ( cmg.cmodels[0].maxs, maxs ); +void CM_GetWorldBounds(vec3_t mins, vec3_t maxs) { + VectorCopy(cmg.cmodels[0].mins, mins); + VectorCopy(cmg.cmodels[0].maxs, maxs); } -int CM_ModelContents_Actual( clipHandle_t model, clipMap_t *cm ) -{ - cmodel_t *cmod; - int contents = 0; - int i; +int CM_ModelContents_Actual(clipHandle_t model, clipMap_t *cm) { + cmodel_t *cmod; + int contents = 0; + int i; - if (!cm) - { + if (!cm) { cm = &cmg; } - cmod = CM_ClipHandleToModel( model, &cm ); + cmod = CM_ClipHandleToModel(model, &cm); - //MCG ADDED - return the contents, too + // MCG ADDED - return the contents, too - for ( i = 0; i < cmod->leaf.numLeafBrushes; i++ ) - { + for (i = 0; i < cmod->leaf.numLeafBrushes; i++) { int brushNum = cm->leafbrushes[cmod->leaf.firstLeafBrush + i]; contents |= cm->brushes[brushNum].contents; } - for ( i = 0; i < cmod->leaf.numLeafSurfaces; i++ ) - { + for (i = 0; i < cmod->leaf.numLeafSurfaces; i++) { int surfaceNum = cm->leafsurfaces[cmod->leaf.firstLeafSurface + i]; - if ( cm->surfaces[surfaceNum] != NULL ) - {//HERNH? How could we have a null surf within our cmod->leaf.numLeafSurfaces? + if (cm->surfaces[surfaceNum] != NULL) { // HERNH? How could we have a null surf within our cmod->leaf.numLeafSurfaces? contents |= cm->surfaces[surfaceNum]->contents; } } @@ -1104,10 +1021,8 @@ int CM_ModelContents_Actual( clipHandle_t model, clipMap_t *cm ) return contents; } -int CM_ModelContents( clipHandle_t model, int subBSPIndex ) -{ - if (subBSPIndex < 0) - { +int CM_ModelContents(clipHandle_t model, int subBSPIndex) { + if (subBSPIndex < 0) { return CM_ModelContents_Actual(model, NULL); } diff --git a/codemp/qcommon/cm_patch.cpp b/codemp/qcommon/cm_patch.cpp index cbb8074f73..5b344794fd 100644 --- a/codemp/qcommon/cm_patch.cpp +++ b/codemp/qcommon/cm_patch.cpp @@ -62,22 +62,19 @@ degenerate a few triangles. Completely degenerate rows and columns are handled properly. */ -int c_totalPatchBlocks; -int c_totalPatchSurfaces; -int c_totalPatchEdges; +int c_totalPatchBlocks; +int c_totalPatchSurfaces; +int c_totalPatchEdges; -static const patchCollide_t *debugPatchCollide; -static const facet_t *debugFacet; -static qboolean debugBlock; -static vec3_t debugBlockPoints[4]; +static const patchCollide_t *debugPatchCollide; +static const facet_t *debugFacet; +static qboolean debugBlock; +static vec3_t debugBlockPoints[4]; #if defined(BSPC) -extern void *Hunk_Alloc( int size ); +extern void *Hunk_Alloc(int size); -static void *Hunk_Alloc( int size, ha_pref preference ) -{ - return Hunk_Alloc( size ); -} +static void *Hunk_Alloc(int size, ha_pref preference) { return Hunk_Alloc(size); } #endif /* @@ -85,7 +82,7 @@ static void *Hunk_Alloc( int size, ha_pref preference ) CM_ClearLevelPatches ================= */ -void CM_ClearLevelPatches( void ) { +void CM_ClearLevelPatches(void) { debugPatchCollide = NULL; debugFacet = NULL; } @@ -95,13 +92,13 @@ void CM_ClearLevelPatches( void ) { CM_SignbitsForNormal ================= */ -static inline int CM_SignbitsForNormal( vec3_t normal ) { - int bits, j; +static inline int CM_SignbitsForNormal(vec3_t normal) { + int bits, j; bits = 0; - for (j=0 ; j<3 ; j++) { - if ( normal[j] < 0 ) { - bits |= 1<= SUBDIVIDE_DISTANCE * SUBDIVIDE_DISTANCE); } @@ -178,10 +174,10 @@ a, b, and c are control points. the subdivided sequence will be: a, out1, out2, out3, c =============== */ -static void CM_Subdivide( vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3 ) { - int i; +static void CM_Subdivide(vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { + for (i = 0; i < 3; i++) { out1[i] = 0.5 * (a[i] + b[i]); out3[i] = 0.5 * (b[i] + c[i]); out2[i] = 0.5 * (out1[i] + out3[i]); @@ -195,36 +191,36 @@ CM_TransposeGrid Swaps the rows and columns in place ================= */ -static void CM_TransposeGrid( cGrid_t *grid ) { - int i, j, l; - vec3_t temp; - qboolean tempWrap; - - if ( grid->width > grid->height ) { - for ( i = 0 ; i < grid->height ; i++ ) { - for ( j = i + 1 ; j < grid->width ; j++ ) { - if ( j < grid->height ) { +static void CM_TransposeGrid(cGrid_t *grid) { + int i, j, l; + vec3_t temp; + qboolean tempWrap; + + if (grid->width > grid->height) { + for (i = 0; i < grid->height; i++) { + for (j = i + 1; j < grid->width; j++) { + if (j < grid->height) { // swap the value - VectorCopy( grid->points[i][j], temp ); - VectorCopy( grid->points[j][i], grid->points[i][j] ); - VectorCopy( temp, grid->points[j][i] ); + VectorCopy(grid->points[i][j], temp); + VectorCopy(grid->points[j][i], grid->points[i][j]); + VectorCopy(temp, grid->points[j][i]); } else { // just copy - VectorCopy( grid->points[j][i], grid->points[i][j] ); + VectorCopy(grid->points[j][i], grid->points[i][j]); } } } } else { - for ( i = 0 ; i < grid->width ; i++ ) { - for ( j = i + 1 ; j < grid->height ; j++ ) { - if ( j < grid->width ) { + for (i = 0; i < grid->width; i++) { + for (j = i + 1; j < grid->height; j++) { + if (j < grid->width) { // swap the value - VectorCopy( grid->points[j][i], temp ); - VectorCopy( grid->points[i][j], grid->points[j][i] ); - VectorCopy( temp, grid->points[i][j] ); + VectorCopy(grid->points[j][i], temp); + VectorCopy(grid->points[i][j], grid->points[j][i]); + VectorCopy(temp, grid->points[i][j]); } else { // just copy - VectorCopy( grid->points[i][j], grid->points[j][i] ); + VectorCopy(grid->points[i][j], grid->points[j][i]); } } } @@ -246,29 +242,28 @@ CM_SetGridWrapWidth If the left and right columns are exactly equal, set grid->wrapWidth qtrue =================== */ -static void CM_SetGridWrapWidth( cGrid_t *grid ) { - int i, j; - float d; - - for ( i = 0 ; i < grid->height ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - d = grid->points[0][i][j] - grid->points[grid->width-1][i][j]; - if ( d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON ) { +static void CM_SetGridWrapWidth(cGrid_t *grid) { + int i, j; + float d; + + for (i = 0; i < grid->height; i++) { + for (j = 0; j < 3; j++) { + d = grid->points[0][i][j] - grid->points[grid->width - 1][i][j]; + if (d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON) { break; } } - if ( j != 3 ) { + if (j != 3) { break; } } - if ( i == grid->height ) { + if (i == grid->height) { grid->wrapWidth = qtrue; } else { grid->wrapWidth = qfalse; } } - /* ================= CM_SubdivideGridColumns @@ -278,10 +273,10 @@ all the aproximating points are within SUBDIVIDE_DISTANCE from the true curve ================= */ -static void CM_SubdivideGridColumns( cGrid_t *grid ) { - int i, j, k; +static void CM_SubdivideGridColumns(cGrid_t *grid) { + int i, j, k; - for ( i = 0 ; i < grid->width - 2 ; ) { + for (i = 0; i < grid->width - 2;) { // grid->points[i][x] is an interpolating control point // grid->points[i+1][x] is an aproximating control point // grid->points[i+2][x] is an interpolating control point @@ -289,18 +284,18 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { // // first see if we can collapse the aproximating collumn away // - for ( j = 0 ; j < grid->height ; j++ ) { - if ( CM_NeedsSubdivision( grid->points[i][j], grid->points[i+1][j], grid->points[i+2][j] ) ) { + for (j = 0; j < grid->height; j++) { + if (CM_NeedsSubdivision(grid->points[i][j], grid->points[i + 1][j], grid->points[i + 2][j])) { break; } } - if ( j == grid->height ) { + if (j == grid->height) { // all of the points were close enough to the linear midpoints // that we can collapse the entire column away - for ( j = 0 ; j < grid->height ; j++ ) { + for (j = 0; j < grid->height; j++) { // remove the column - for ( k = i + 2 ; k < grid->width ; k++ ) { - VectorCopy( grid->points[k][j], grid->points[k-1][j] ); + for (k = i + 2; k < grid->width; k++) { + VectorCopy(grid->points[k][j], grid->points[k - 1][j]); } } @@ -314,23 +309,23 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { // // we need to subdivide the curve // - for ( j = 0 ; j < grid->height ; j++ ) { - vec3_t prev, mid, next; + for (j = 0; j < grid->height; j++) { + vec3_t prev, mid, next; // save the control points now - VectorCopy( grid->points[i][j], prev ); - VectorCopy( grid->points[i+1][j], mid ); - VectorCopy( grid->points[i+2][j], next ); + VectorCopy(grid->points[i][j], prev); + VectorCopy(grid->points[i + 1][j], mid); + VectorCopy(grid->points[i + 2][j], next); // make room for two additional columns in the grid // columns i+1 will be replaced, column i+2 will become i+4 // i+1, i+2, and i+3 will be generated - for ( k = grid->width - 1 ; k > i + 1 ; k-- ) { - VectorCopy( grid->points[k][j], grid->points[k+2][j] ); + for (k = grid->width - 1; k > i + 1; k--) { + VectorCopy(grid->points[k][j], grid->points[k + 2][j]); } // generate the subdivided points - CM_Subdivide( prev, mid, next, grid->points[i+1][j], grid->points[i+2][j], grid->points[i+3][j] ); + CM_Subdivide(prev, mid, next, grid->points[i + 1][j], grid->points[i + 2][j], grid->points[i + 3][j]); } grid->width += 2; @@ -340,26 +335,25 @@ static void CM_SubdivideGridColumns( cGrid_t *grid ) { } } - /* ====================== CM_ComparePoints ====================== */ -#define POINT_EPSILON 0.1 -static qboolean CM_ComparePoints( float *a, float *b ) { - float d; +#define POINT_EPSILON 0.1 +static qboolean CM_ComparePoints(float *a, float *b) { + float d; d = a[0] - b[0]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } d = a[1] - b[1]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } d = a[2] - b[2]; - if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { + if (d < -POINT_EPSILON || d > POINT_EPSILON) { return qfalse; } return qtrue; @@ -372,24 +366,24 @@ CM_RemoveDegenerateColumns If there are any identical columns, remove them ================= */ -static void CM_RemoveDegenerateColumns( cGrid_t *grid ) { - int i, j, k; +static void CM_RemoveDegenerateColumns(cGrid_t *grid) { + int i, j, k; - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height ; j++ ) { - if ( !CM_ComparePoints( grid->points[i][j], grid->points[i+1][j] ) ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height; j++) { + if (!CM_ComparePoints(grid->points[i][j], grid->points[i + 1][j])) { break; } } - if ( j != grid->height ) { - continue; // not degenerate + if (j != grid->height) { + continue; // not degenerate } - for ( j = 0 ; j < grid->height ; j++ ) { + for (j = 0; j < grid->height; j++) { // remove the column - for ( k = i + 2 ; k < grid->width ; k++ ) { - VectorCopy( grid->points[k][j], grid->points[k-1][j] ); + for (k = i + 2; k < grid->width; k++) { + VectorCopy(grid->points[k][j], grid->points[k - 1][j]); } } grid->width--; @@ -407,25 +401,21 @@ PATCH COLLIDE GENERATION ================================================================================ */ -static int numPlanes; -static patchPlane_t planes[MAX_PATCH_PLANES]; +static int numPlanes; +static patchPlane_t planes[MAX_PATCH_PLANES]; -//static int numFacets; -//static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ?? -static facet_t *facets = NULL; +// static int numFacets; +// static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ?? +static facet_t *facets = NULL; -#define NORMAL_EPSILON 0.00015 -#define DIST_EPSILON 0.0235 +#define NORMAL_EPSILON 0.00015 +#define DIST_EPSILON 0.0235 static inline int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { float invplane[4]; - if ( - Q_fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON - && Q_fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON - && Q_fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON - && Q_fabs(p->plane[3] - plane[3]) < DIST_EPSILON ) - { + if (Q_fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON && Q_fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON && + Q_fabs(p->plane[3] - plane[3]) < DIST_EPSILON) { *flipped = qfalse; return qtrue; } @@ -433,12 +423,8 @@ static inline int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { VectorNegate(plane, invplane); invplane[3] = -plane[3]; - if ( - Q_fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON - && Q_fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON - && Q_fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON - && Q_fabs(p->plane[3] - invplane[3]) < DIST_EPSILON ) - { + if (Q_fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON && + Q_fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON && Q_fabs(p->plane[3] - invplane[3]) < DIST_EPSILON) { *flipped = qtrue; return qtrue; } @@ -447,19 +433,16 @@ static inline int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { } static inline void CM_SnapVector(vec3_t normal) { - int i; + int i; - for (i=0 ; i<3 ; i++) - { - if ( Q_fabs(normal[i] - 1) < NORMAL_EPSILON ) - { - VectorClear (normal); + for (i = 0; i < 3; i++) { + if (Q_fabs(normal[i] - 1) < NORMAL_EPSILON) { + VectorClear(normal); normal[i] = 1; break; } - if ( Q_fabs(normal[i] - -1) < NORMAL_EPSILON ) - { - VectorClear (normal); + if (Q_fabs(normal[i] - -1) < NORMAL_EPSILON) { + VectorClear(normal); normal[i] = -1; break; } @@ -470,23 +453,24 @@ static inline int CM_FindPlane2(float plane[4], int *flipped) { int i; // see if the points are close enough to an existing plane - for ( i = 0 ; i < numPlanes ; i++ ) { - if (CM_PlaneEqual(&planes[i], plane, flipped)) return i; + for (i = 0; i < numPlanes; i++) { + if (CM_PlaneEqual(&planes[i], plane, flipped)) + return i; } // add a new plane - if ( numPlanes == MAX_PATCH_PLANES ) { - Com_Error( ERR_DROP, "CM_FindPlane2: MAX_PATCH_PLANES (%d)", MAX_PATCH_PLANES ); + if (numPlanes == MAX_PATCH_PLANES) { + Com_Error(ERR_DROP, "CM_FindPlane2: MAX_PATCH_PLANES (%d)", MAX_PATCH_PLANES); } - VectorCopy4( plane, planes[numPlanes].plane ); - planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); + VectorCopy4(plane, planes[numPlanes].plane); + planes[numPlanes].signbits = CM_SignbitsForNormal(plane); numPlanes++; *flipped = qfalse; - return numPlanes-1; + return numPlanes - 1; } /* @@ -494,33 +478,33 @@ static inline int CM_FindPlane2(float plane[4], int *flipped) { CM_FindPlane ================== */ -static inline int CM_FindPlane( float *p1, float *p2, float *p3 ) { - float plane[4]; - int i; - float d; +static inline int CM_FindPlane(float *p1, float *p2, float *p3) { + float plane[4]; + int i; + float d; - if ( !CM_PlaneFromPoints( plane, p1, p2, p3 ) ) { + if (!CM_PlaneFromPoints(plane, p1, p2, p3)) { return -1; } // see if the points are close enough to an existing plane - for ( i = 0 ; i < numPlanes ; i++ ) { - if ( DotProduct( plane, planes[i].plane ) < 0 ) { - continue; // allow backwards planes? + for (i = 0; i < numPlanes; i++) { + if (DotProduct(plane, planes[i].plane) < 0) { + continue; // allow backwards planes? } - d = DotProduct( p1, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p1, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } - d = DotProduct( p2, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p2, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } - d = DotProduct( p3, planes[i].plane ) - planes[i].plane[3]; - if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { + d = DotProduct(p3, planes[i].plane) - planes[i].plane[3]; + if (d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON) { continue; } @@ -529,216 +513,212 @@ static inline int CM_FindPlane( float *p1, float *p2, float *p3 ) { } // add a new plane - if ( numPlanes == MAX_PATCH_PLANES ) { - Com_Error( ERR_DROP, "CM_FindPlane: MAX_PATCH_PLANES (%d)", MAX_PATCH_PLANES ); + if (numPlanes == MAX_PATCH_PLANES) { + Com_Error(ERR_DROP, "CM_FindPlane: MAX_PATCH_PLANES (%d)", MAX_PATCH_PLANES); } - VectorCopy4( plane, planes[numPlanes].plane ); - planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); + VectorCopy4(plane, planes[numPlanes].plane); + planes[numPlanes].signbits = CM_SignbitsForNormal(plane); numPlanes++; - return numPlanes-1; + return numPlanes - 1; } - /* ================== CM_PointOnPlaneSide ================== */ -static inline int CM_PointOnPlaneSide( float *p, int planeNum ) { - float *plane; - float d; +static inline int CM_PointOnPlaneSide(float *p, int planeNum) { + float *plane; + float d; - if ( planeNum == -1 ) { + if (planeNum == -1) { return SIDE_ON; } - plane = planes[ planeNum ].plane; + plane = planes[planeNum].plane; - d = DotProduct( p, plane ) - plane[3]; + d = DotProduct(p, plane) - plane[3]; - if ( d > PLANE_TRI_EPSILON ) { + if (d > PLANE_TRI_EPSILON) { return SIDE_FRONT; } - if ( d < -PLANE_TRI_EPSILON ) { + if (d < -PLANE_TRI_EPSILON) { return SIDE_BACK; } return SIDE_ON; } -static inline int CM_GridPlane( int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int tri ) { - int p; +static inline int CM_GridPlane(int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int tri) { + int p; p = gridPlanes[i][j][tri]; - if ( p != -1 ) { + if (p != -1) { return p; } p = gridPlanes[i][j][!tri]; - if ( p != -1 ) { + if (p != -1) { return p; } // should never happen - if ( cm_extraVerbose->integer ) - Com_Printf( "WARNING: CM_GridPlane unresolvable\n" ); + if (cm_extraVerbose->integer) + Com_Printf("WARNING: CM_GridPlane unresolvable\n"); return -1; } - /* ================== CM_EdgePlaneNum ================== */ -static inline int CM_EdgePlaneNum( cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int k ) { - float *p1, *p2; - vec3_t up; - int p; +static inline int CM_EdgePlaneNum(cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int k) { + float *p1, *p2; + vec3_t up; + int p; - switch ( k ) { - case 0: // top border + switch (k) { + case 0: // top border p1 = grid->points[i][j]; - p2 = grid->points[i+1][j]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + p2 = grid->points[i + 1][j]; + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); - - case 2: // bottom border - p1 = grid->points[i][j+1]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); + + case 2: // bottom border + p1 = grid->points[i][j + 1]; + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p2, p1, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p2, p1, up); case 3: // left border p1 = grid->points[i][j]; - p2 = grid->points[i][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + p2 = grid->points[i][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p2, p1, up ); - - case 1: // right border - p1 = grid->points[i+1][j]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p2, p1, up); + + case 1: // right border + p1 = grid->points[i + 1][j]; + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); - case 4: // diagonal out of triangle 0 - p1 = grid->points[i+1][j+1]; + case 4: // diagonal out of triangle 0 + p1 = grid->points[i + 1][j + 1]; p2 = grid->points[i][j]; - p = CM_GridPlane( gridPlanes, i, j, 0 ); - if ( p == -1 ) { + p = CM_GridPlane(gridPlanes, i, j, 0); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); - case 5: // diagonal out of triangle 1 + case 5: // diagonal out of triangle 1 p1 = grid->points[i][j]; - p2 = grid->points[i+1][j+1]; - p = CM_GridPlane( gridPlanes, i, j, 1 ); - if ( p == -1 ) { + p2 = grid->points[i + 1][j + 1]; + p = CM_GridPlane(gridPlanes, i, j, 1); + if (p == -1) { return -1; } - VectorMA( p1, 4, planes[ p ].plane, up ); - return CM_FindPlane( p1, p2, up ); - + VectorMA(p1, 4, planes[p].plane, up); + return CM_FindPlane(p1, p2, up); } - Com_Error( ERR_DROP, "CM_EdgePlaneNum: bad k" ); + Com_Error(ERR_DROP, "CM_EdgePlaneNum: bad k"); return -1; } - /* =================== CM_SetBorderInward =================== */ -static inline void CM_SetBorderInward( facet_t *facet, cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], - int i, int j, int which ) { - int k, l; - float *points[4]; - int numPoints; +static inline void CM_SetBorderInward(facet_t *facet, cGrid_t *grid, int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2], int i, int j, int which) { + int k, l; + float *points[4]; + int numPoints; - switch ( which ) { + switch (which) { case -1: points[0] = grid->points[i][j]; - points[1] = grid->points[i+1][j]; - points[2] = grid->points[i+1][j+1]; - points[3] = grid->points[i][j+1]; + points[1] = grid->points[i + 1][j]; + points[2] = grid->points[i + 1][j + 1]; + points[3] = grid->points[i][j + 1]; numPoints = 4; break; case 0: points[0] = grid->points[i][j]; - points[1] = grid->points[i+1][j]; - points[2] = grid->points[i+1][j+1]; + points[1] = grid->points[i + 1][j]; + points[2] = grid->points[i + 1][j + 1]; numPoints = 3; break; case 1: - points[0] = grid->points[i+1][j+1]; - points[1] = grid->points[i][j+1]; + points[0] = grid->points[i + 1][j + 1]; + points[1] = grid->points[i][j + 1]; points[2] = grid->points[i][j]; numPoints = 3; break; default: - Com_Error( ERR_FATAL, "CM_SetBorderInward: bad parameter" ); + Com_Error(ERR_FATAL, "CM_SetBorderInward: bad parameter"); numPoints = 0; break; } - for ( k = 0 ; k < facet->numBorders ; k++ ) { - int front, back; + for (k = 0; k < facet->numBorders; k++) { + int front, back; front = 0; back = 0; - for ( l = 0 ; l < numPoints ; l++ ) { - int side; + for (l = 0; l < numPoints; l++) { + int side; - side = CM_PointOnPlaneSide( points[l], facet->borderPlanes[k] ); - if ( side == SIDE_FRONT ) { + side = CM_PointOnPlaneSide(points[l], facet->borderPlanes[k]); + if (side == SIDE_FRONT) { front++; - } if ( side == SIDE_BACK ) { + } + if (side == SIDE_BACK) { back++; } } - if ( front && !back ) { + if (front && !back) { facet->borderInward[k] = qtrue; - } else if ( back && !front ) { + } else if (back && !front) { facet->borderInward[k] = qfalse; - } else if ( !front && !back ) { + } else if (!front && !back) { // flat side border facet->borderPlanes[k] = -1; } else { // bisecting side border #ifndef BSPC - Com_DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" ); + Com_DPrintf("WARNING: CM_SetBorderInward: mixed plane sides\n"); #endif facet->borderInward[k] = qfalse; - if ( !debugBlock ) { + if (!debugBlock) { debugBlock = qtrue; - VectorCopy( grid->points[i][j], debugBlockPoints[0] ); - VectorCopy( grid->points[i+1][j], debugBlockPoints[1] ); - VectorCopy( grid->points[i+1][j+1], debugBlockPoints[2] ); - VectorCopy( grid->points[i][j+1], debugBlockPoints[3] ); + VectorCopy(grid->points[i][j], debugBlockPoints[0]); + VectorCopy(grid->points[i + 1][j], debugBlockPoints[1]); + VectorCopy(grid->points[i + 1][j + 1], debugBlockPoints[2]); + VectorCopy(grid->points[i][j + 1], debugBlockPoints[3]); } } } @@ -751,51 +731,51 @@ CM_ValidateFacet If the facet isn't bounded by its borders, we screwed up. ================== */ -static inline qboolean CM_ValidateFacet( facet_t *facet ) { - float plane[4]; - int j; - winding_t *w; - vec3_t bounds[2]; +static inline qboolean CM_ValidateFacet(facet_t *facet) { + float plane[4]; + int j; + winding_t *w; + vec3_t bounds[2]; - if ( facet->surfacePlane == -1 ) { + if (facet->surfacePlane == -1) { return qfalse; } - VectorCopy4( planes[ facet->surfacePlane ].plane, plane ); - w = BaseWindingForPlane( plane, plane[3] ); - for ( j = 0 ; j < facet->numBorders && w ; j++ ) { - if ( facet->borderPlanes[j] == -1 ) { + VectorCopy4(planes[facet->surfacePlane].plane, plane); + w = BaseWindingForPlane(plane, plane[3]); + for (j = 0; j < facet->numBorders && w; j++) { + if (facet->borderPlanes[j] == -1) { FreeWinding(w); return qfalse; } - VectorCopy4( planes[ facet->borderPlanes[j] ].plane, plane ); - if ( !facet->borderInward[j] ) { - VectorSubtract( vec3_origin, plane, plane ); + VectorCopy4(planes[facet->borderPlanes[j]].plane, plane); + if (!facet->borderInward[j]) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } - ChopWindingInPlace( &w, plane, plane[3], 0.1f ); + ChopWindingInPlace(&w, plane, plane[3], 0.1f); } - if ( !w ) { - return qfalse; // winding was completely chopped away + if (!w) { + return qfalse; // winding was completely chopped away } // see if the facet is unreasonably large - WindingBounds( w, bounds[0], bounds[1] ); - FreeWinding( w ); + WindingBounds(w, bounds[0], bounds[1]); + FreeWinding(w); - for ( j = 0 ; j < 3 ; j++ ) { - if ( bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS ) { - return qfalse; // we must be missing a plane + for (j = 0; j < 3; j++) { + if (bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS) { + return qfalse; // we must be missing a plane } - if ( bounds[0][j] >= MAX_MAP_BOUNDS ) { + if (bounds[0][j] >= MAX_MAP_BOUNDS) { return qfalse; } - if ( bounds[1][j] <= -MAX_MAP_BOUNDS ) { + if (bounds[1][j] <= -MAX_MAP_BOUNDS) { return qfalse; } } - return qtrue; // winding is fine + return qtrue; // winding is fine } /* @@ -803,7 +783,7 @@ static inline qboolean CM_ValidateFacet( facet_t *facet ) { CM_AddFacetBevels ================== */ -static inline void CM_AddFacetBevels( facet_t *facet ) { +static inline void CM_AddFacetBevels(facet_t *facet) { int i, j, k, l; int axis, dir, order, flipped; @@ -811,21 +791,22 @@ static inline void CM_AddFacetBevels( facet_t *facet ) { winding_t *w, *w2; vec3_t mins, maxs, vec, vec2; - VectorCopy4( planes[ facet->surfacePlane ].plane, plane ); + VectorCopy4(planes[facet->surfacePlane].plane, plane); - w = BaseWindingForPlane( plane, plane[3] ); - for ( j = 0 ; j < facet->numBorders && w ; j++ ) { - if (facet->borderPlanes[j] == facet->surfacePlane) continue; - VectorCopy4( planes[ facet->borderPlanes[j] ].plane, plane ); + w = BaseWindingForPlane(plane, plane[3]); + for (j = 0; j < facet->numBorders && w; j++) { + if (facet->borderPlanes[j] == facet->surfacePlane) + continue; + VectorCopy4(planes[facet->borderPlanes[j]].plane, plane); - if ( !facet->borderInward[j] ) { - VectorSubtract( vec3_origin, plane, plane ); + if (!facet->borderInward[j]) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } - ChopWindingInPlace( &w, plane, plane[3], 0.1f ); + ChopWindingInPlace(&w, plane, plane[3], 0.1f); } - if ( !w ) { + if (!w) { return; } @@ -833,30 +814,28 @@ static inline void CM_AddFacetBevels( facet_t *facet ) { // add the axial planes order = 0; - for ( axis = 0 ; axis < 3 ; axis++ ) - { - for ( dir = -1 ; dir <= 1 ; dir += 2, order++ ) - { + for (axis = 0; axis < 3; axis++) { + for (dir = -1; dir <= 1; dir += 2, order++) { VectorClear(plane); plane[axis] = dir; if (dir == 1) { plane[3] = maxs[axis]; - } - else { + } else { plane[3] = -mins[axis]; } - //if it's the surface plane + // if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present - for ( i = 0 ; i < facet->numBorders ; i++ ) { + for (i = 0; i < facet->numBorders; i++) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) break; } - if ( i == facet->numBorders ) { - if (facet->numBorders > 4 + 6 + 16) Com_Printf("ERROR: too many bevels\n"); + if (i == facet->numBorders) { + if (facet->numBorders > 4 + 6 + 16) + Com_Printf("ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); facet->borderNoAdjust[facet->numBorders] = (qboolean)0; facet->borderInward[facet->numBorders] = flipped; @@ -868,62 +847,59 @@ static inline void CM_AddFacetBevels( facet_t *facet ) { // add the edge bevels // // test the non-axial plane edges - for ( j = 0 ; j < w->numpoints ; j++ ) - { - k = (j+1)%w->numpoints; - VectorSubtract (w->p[j], w->p[k], vec); - //if it's a degenerate edge - if (VectorNormalize (vec) < 0.5) + for (j = 0; j < w->numpoints; j++) { + k = (j + 1) % w->numpoints; + VectorSubtract(w->p[j], w->p[k], vec); + // if it's a degenerate edge + if (VectorNormalize(vec) < 0.5) continue; CM_SnapVector(vec); - for ( k = 0; k < 3 ; k++ ) - if ( vec[k] == -1 || vec[k] == 1 ) - break; // axial - if ( k < 3 ) - continue; // only test non-axial edges + for (k = 0; k < 3; k++) + if (vec[k] == -1 || vec[k] == 1) + break; // axial + if (k < 3) + continue; // only test non-axial edges // try the six possible slanted axials from this edge - for ( axis = 0 ; axis < 3 ; axis++ ) - { - for ( dir = -1 ; dir <= 1 ; dir += 2 ) - { + for (axis = 0; axis < 3; axis++) { + for (dir = -1; dir <= 1; dir += 2) { // construct a plane - VectorClear (vec2); + VectorClear(vec2); vec2[axis] = dir; - CrossProduct (vec, vec2, plane); - if (VectorNormalize (plane) < 0.5) + CrossProduct(vec, vec2, plane); + if (VectorNormalize(plane) < 0.5) continue; - plane[3] = DotProduct (w->p[j], plane); + plane[3] = DotProduct(w->p[j], plane); // if all the points of the facet winding are // behind this plane, it is a proper edge bevel - for ( l = 0 ; l < w->numpoints ; l++ ) - { - d = DotProduct (w->p[l], plane) - plane[3]; + for (l = 0; l < w->numpoints; l++) { + d = DotProduct(w->p[l], plane) - plane[3]; if (d > 0.1) - break; // point in front + break; // point in front } - if ( l < w->numpoints ) + if (l < w->numpoints) continue; - //if it's the surface plane + // if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present - for ( i = 0 ; i < facet->numBorders ; i++ ) { + for (i = 0; i < facet->numBorders; i++) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) { - break; + break; } } - if ( i == facet->numBorders ) { - if (facet->numBorders > 4 + 6 + 16) Com_Printf("ERROR: too many bevels\n"); + if (i == facet->numBorders) { + if (facet->numBorders > 4 + 6 + 16) + Com_Printf("ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); - for ( k = 0 ; k < facet->numBorders ; k++ ) { - if (facet->borderPlanes[facet->numBorders] == - facet->borderPlanes[k]) Com_Printf("WARNING: bevel plane already used\n"); + for (k = 0; k < facet->numBorders; k++) { + if (facet->borderPlanes[facet->numBorders] == facet->borderPlanes[k]) + Com_Printf("WARNING: bevel plane already used\n"); } facet->borderNoAdjust[facet->numBorders] = (qboolean)0; @@ -931,140 +907,131 @@ static inline void CM_AddFacetBevels( facet_t *facet ) { // w2 = CopyWinding(w); VectorCopy4(planes[facet->borderPlanes[facet->numBorders]].plane, newplane); - if (!facet->borderInward[facet->numBorders]) - { + if (!facet->borderInward[facet->numBorders]) { VectorNegate(newplane, newplane); newplane[3] = -newplane[3]; - } //end if - ChopWindingInPlace( &w2, newplane, newplane[3], 0.1f ); + } // end if + ChopWindingInPlace(&w2, newplane, newplane[3], 0.1f); if (!w2) { #ifndef BSPC Com_DPrintf("WARNING: CM_AddFacetBevels... invalid bevel\n"); #endif continue; - } - else { + } else { FreeWinding(w2); } // facet->numBorders++; - //already got a bevel -// break; + // already got a bevel + // break; } } } } - FreeWinding( w ); + FreeWinding(w); #ifndef BSPC - //add opposite plane + // add opposite plane facet->borderPlanes[facet->numBorders] = facet->surfacePlane; facet->borderNoAdjust[facet->numBorders] = (qboolean)0; facet->borderInward[facet->numBorders] = qtrue; facet->numBorders++; -#endif //BSPC - +#endif // BSPC } - -typedef enum { - EN_TOP, - EN_RIGHT, - EN_BOTTOM, - EN_LEFT -} edgeName_t; +typedef enum { EN_TOP, EN_RIGHT, EN_BOTTOM, EN_LEFT } edgeName_t; /* ================== CM_PatchCollideFromGrid ================== */ -static inline void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { - int i, j; - float *p1, *p2, *p3; - int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2]; - facet_t *facet; - int borders[4]; - int noAdjust[4]; +static inline void CM_PatchCollideFromGrid(cGrid_t *grid, patchCollide_t *pf) { + int i, j; + float *p1, *p2, *p3; + int gridPlanes[MAX_GRID_SIZE][MAX_GRID_SIZE][2]; + facet_t *facet; + int borders[4]; + int noAdjust[4]; int numFacets; - facets = (facet_t*) Z_Malloc(MAX_FACETS*sizeof(facet_t), TAG_TEMP_WORKSPACE, qfalse, 4); + facets = (facet_t *)Z_Malloc(MAX_FACETS * sizeof(facet_t), TAG_TEMP_WORKSPACE, qfalse, 4); numPlanes = 0; numFacets = 0; // find the planes for each triangle of the grid - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height - 1 ; j++ ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height - 1; j++) { p1 = grid->points[i][j]; - p2 = grid->points[i+1][j]; - p3 = grid->points[i+1][j+1]; - gridPlanes[i][j][0] = CM_FindPlane( p1, p2, p3 ); + p2 = grid->points[i + 1][j]; + p3 = grid->points[i + 1][j + 1]; + gridPlanes[i][j][0] = CM_FindPlane(p1, p2, p3); - p1 = grid->points[i+1][j+1]; - p2 = grid->points[i][j+1]; + p1 = grid->points[i + 1][j + 1]; + p2 = grid->points[i][j + 1]; p3 = grid->points[i][j]; - gridPlanes[i][j][1] = CM_FindPlane( p1, p2, p3 ); + gridPlanes[i][j][1] = CM_FindPlane(p1, p2, p3); } } // create the borders for each facet - for ( i = 0 ; i < grid->width - 1 ; i++ ) { - for ( j = 0 ; j < grid->height - 1 ; j++ ) { + for (i = 0; i < grid->width - 1; i++) { + for (j = 0; j < grid->height - 1; j++) { borders[EN_TOP] = -1; - if ( j > 0 ) { - borders[EN_TOP] = gridPlanes[i][j-1][1]; - } else if ( grid->wrapHeight ) { - borders[EN_TOP] = gridPlanes[i][grid->height-2][1]; + if (j > 0) { + borders[EN_TOP] = gridPlanes[i][j - 1][1]; + } else if (grid->wrapHeight) { + borders[EN_TOP] = gridPlanes[i][grid->height - 2][1]; } - noAdjust[EN_TOP] = ( borders[EN_TOP] == gridPlanes[i][j][0] ); - if ( borders[EN_TOP] == -1 || noAdjust[EN_TOP] ) { - borders[EN_TOP] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 0 ); + noAdjust[EN_TOP] = (borders[EN_TOP] == gridPlanes[i][j][0]); + if (borders[EN_TOP] == -1 || noAdjust[EN_TOP]) { + borders[EN_TOP] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 0); } borders[EN_BOTTOM] = -1; - if ( j < grid->height - 2 ) { - borders[EN_BOTTOM] = gridPlanes[i][j+1][0]; - } else if ( grid->wrapHeight ) { + if (j < grid->height - 2) { + borders[EN_BOTTOM] = gridPlanes[i][j + 1][0]; + } else if (grid->wrapHeight) { borders[EN_BOTTOM] = gridPlanes[i][0][0]; } - noAdjust[EN_BOTTOM] = ( borders[EN_BOTTOM] == gridPlanes[i][j][1] ); - if ( borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM] ) { - borders[EN_BOTTOM] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 2 ); + noAdjust[EN_BOTTOM] = (borders[EN_BOTTOM] == gridPlanes[i][j][1]); + if (borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM]) { + borders[EN_BOTTOM] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 2); } borders[EN_LEFT] = -1; - if ( i > 0 ) { - borders[EN_LEFT] = gridPlanes[i-1][j][0]; - } else if ( grid->wrapWidth ) { - borders[EN_LEFT] = gridPlanes[grid->width-2][j][0]; + if (i > 0) { + borders[EN_LEFT] = gridPlanes[i - 1][j][0]; + } else if (grid->wrapWidth) { + borders[EN_LEFT] = gridPlanes[grid->width - 2][j][0]; } - noAdjust[EN_LEFT] = ( borders[EN_LEFT] == gridPlanes[i][j][1] ); - if ( borders[EN_LEFT] == -1 || noAdjust[EN_LEFT] ) { - borders[EN_LEFT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 3 ); + noAdjust[EN_LEFT] = (borders[EN_LEFT] == gridPlanes[i][j][1]); + if (borders[EN_LEFT] == -1 || noAdjust[EN_LEFT]) { + borders[EN_LEFT] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 3); } borders[EN_RIGHT] = -1; - if ( i < grid->width - 2 ) { - borders[EN_RIGHT] = gridPlanes[i+1][j][1]; - } else if ( grid->wrapWidth ) { + if (i < grid->width - 2) { + borders[EN_RIGHT] = gridPlanes[i + 1][j][1]; + } else if (grid->wrapWidth) { borders[EN_RIGHT] = gridPlanes[0][j][1]; } - noAdjust[EN_RIGHT] = ( borders[EN_RIGHT] == gridPlanes[i][j][0] ); - if ( borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT] ) { - borders[EN_RIGHT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 1 ); + noAdjust[EN_RIGHT] = (borders[EN_RIGHT] == gridPlanes[i][j][0]); + if (borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT]) { + borders[EN_RIGHT] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 1); } - if ( numFacets == MAX_FACETS ) { - Com_Error( ERR_DROP, "MAX_FACETS" ); + if (numFacets == MAX_FACETS) { + Com_Error(ERR_DROP, "MAX_FACETS"); } facet = &facets[numFacets]; - Com_Memset( facet, 0, sizeof( *facet ) ); + Com_Memset(facet, 0, sizeof(*facet)); - if ( gridPlanes[i][j][0] == gridPlanes[i][j][1] ) { - if ( gridPlanes[i][j][0] == -1 ) { - continue; // degenrate + if (gridPlanes[i][j][0] == gridPlanes[i][j][1]) { + if (gridPlanes[i][j][0] == -1) { + continue; // degenrate } facet->surfacePlane = gridPlanes[i][j][0]; facet->numBorders = 4; @@ -1076,9 +1043,9 @@ static inline void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) facet->borderNoAdjust[2] = (qboolean)noAdjust[EN_BOTTOM]; facet->borderPlanes[3] = borders[EN_LEFT]; facet->borderNoAdjust[3] = (qboolean)noAdjust[EN_LEFT]; - CM_SetBorderInward( facet, grid, gridPlanes, i, j, -1 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, -1); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } } else { @@ -1090,23 +1057,23 @@ static inline void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) facet->borderPlanes[1] = borders[EN_RIGHT]; facet->borderNoAdjust[1] = (qboolean)noAdjust[EN_RIGHT]; facet->borderPlanes[2] = gridPlanes[i][j][1]; - if ( facet->borderPlanes[2] == -1 ) { + if (facet->borderPlanes[2] == -1) { facet->borderPlanes[2] = borders[EN_BOTTOM]; - if ( facet->borderPlanes[2] == -1 ) { - facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 4 ); + if (facet->borderPlanes[2] == -1) { + facet->borderPlanes[2] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 4); } } - CM_SetBorderInward( facet, grid, gridPlanes, i, j, 0 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, 0); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } - if ( numFacets == MAX_FACETS ) { - Com_Error( ERR_DROP, "MAX_FACETS" ); + if (numFacets == MAX_FACETS) { + Com_Error(ERR_DROP, "MAX_FACETS"); } facet = &facets[numFacets]; - Com_Memset( facet, 0, sizeof( *facet ) ); + Com_Memset(facet, 0, sizeof(*facet)); facet->surfacePlane = gridPlanes[i][j][1]; facet->numBorders = 3; @@ -1115,15 +1082,15 @@ static inline void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) facet->borderPlanes[1] = borders[EN_LEFT]; facet->borderNoAdjust[1] = (qboolean)noAdjust[EN_LEFT]; facet->borderPlanes[2] = gridPlanes[i][j][0]; - if ( facet->borderPlanes[2] == -1 ) { + if (facet->borderPlanes[2] == -1) { facet->borderPlanes[2] = borders[EN_TOP]; - if ( facet->borderPlanes[2] == -1 ) { - facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 5 ); + if (facet->borderPlanes[2] == -1) { + facet->borderPlanes[2] = CM_EdgePlaneNum(grid, gridPlanes, i, j, 5); } } - CM_SetBorderInward( facet, grid, gridPlanes, i, j, 1 ); - if ( CM_ValidateFacet( facet ) ) { - CM_AddFacetBevels( facet ); + CM_SetBorderInward(facet, grid, gridPlanes, i, j, 1); + if (CM_ValidateFacet(facet)) { + CM_AddFacetBevels(facet); numFacets++; } } @@ -1133,22 +1100,18 @@ static inline void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) // copy the results out pf->numPlanes = numPlanes; pf->numFacets = numFacets; - if (numFacets) - { - pf->facets = (facet_t *)Hunk_Alloc( numFacets * sizeof( *pf->facets ), h_high ); - Com_Memcpy( pf->facets, facets, numFacets * sizeof( *pf->facets ) ); - } - else - { + if (numFacets) { + pf->facets = (facet_t *)Hunk_Alloc(numFacets * sizeof(*pf->facets), h_high); + Com_Memcpy(pf->facets, facets, numFacets * sizeof(*pf->facets)); + } else { pf->facets = 0; } - pf->planes = (patchPlane_t *)Hunk_Alloc( numPlanes * sizeof( *pf->planes ), h_high ); - Com_Memcpy( pf->planes, planes, numPlanes * sizeof( *pf->planes ) ); + pf->planes = (patchPlane_t *)Hunk_Alloc(numPlanes * sizeof(*pf->planes), h_high); + Com_Memcpy(pf->planes, planes, numPlanes * sizeof(*pf->planes)); Z_Free(facets); } - /* =================== CM_GeneratePatchCollide @@ -1159,22 +1122,21 @@ collision detection with a patch mesh. Points is packed as concatenated rows. =================== */ -struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points ) { - patchCollide_t *pf; - cGrid_t grid; - int i, j; - - if ( width <= 2 || height <= 2 || !points ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", - width, height, points ); +struct patchCollide_s *CM_GeneratePatchCollide(int width, int height, vec3_t *points) { + patchCollide_t *pf; + cGrid_t grid; + int i, j; + + if (width <= 2 || height <= 2 || !points) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", width, height, points); } - if ( !(width & 1) || !(height & 1) ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" ); + if (!(width & 1) || !(height & 1)) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes"); } - if ( width > MAX_GRID_SIZE || height > MAX_GRID_SIZE ) { - Com_Error( ERR_DROP, "CM_GeneratePatchFacets: source is > MAX_GRID_SIZE" ); + if (width > MAX_GRID_SIZE || height > MAX_GRID_SIZE) { + Com_Error(ERR_DROP, "CM_GeneratePatchFacets: source is > MAX_GRID_SIZE"); } // build a grid @@ -1182,38 +1144,38 @@ struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *p grid.height = height; grid.wrapWidth = qfalse; grid.wrapHeight = qfalse; - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - VectorCopy( points[j*width + i], grid.points[i][j] ); + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + VectorCopy(points[j * width + i], grid.points[i][j]); } } // subdivide the grid - CM_SetGridWrapWidth( &grid ); - CM_SubdivideGridColumns( &grid ); - CM_RemoveDegenerateColumns( &grid ); + CM_SetGridWrapWidth(&grid); + CM_SubdivideGridColumns(&grid); + CM_RemoveDegenerateColumns(&grid); - CM_TransposeGrid( &grid ); + CM_TransposeGrid(&grid); - CM_SetGridWrapWidth( &grid ); - CM_SubdivideGridColumns( &grid ); - CM_RemoveDegenerateColumns( &grid ); + CM_SetGridWrapWidth(&grid); + CM_SubdivideGridColumns(&grid); + CM_RemoveDegenerateColumns(&grid); // we now have a grid of points exactly on the curve // the approximate surface defined by these points will be // collided against - pf = (struct patchCollide_s *)Hunk_Alloc( sizeof( *pf ), h_high ); - ClearBounds( pf->bounds[0], pf->bounds[1] ); - for ( i = 0 ; i < grid.width ; i++ ) { - for ( j = 0 ; j < grid.height ; j++ ) { - AddPointToBounds( grid.points[i][j], pf->bounds[0], pf->bounds[1] ); + pf = (struct patchCollide_s *)Hunk_Alloc(sizeof(*pf), h_high); + ClearBounds(pf->bounds[0], pf->bounds[1]); + for (i = 0; i < grid.width; i++) { + for (j = 0; j < grid.height; j++) { + AddPointToBounds(grid.points[i][j], pf->bounds[0], pf->bounds[1]); } } - c_totalPatchBlocks += ( grid.width - 1 ) * ( grid.height - 1 ); + c_totalPatchBlocks += (grid.width - 1) * (grid.height - 1); // generate a bsp tree for the surface - CM_PatchCollideFromGrid( &grid, pf ); + CM_PatchCollideFromGrid(&grid, pf); // expand by one unit for epsilon purposes pf->bounds[0][0] -= 1; @@ -1242,96 +1204,95 @@ CM_TracePointThroughPatchCollide special case for point traces because the patch collide "brushes" have no volume ==================== */ -static inline void CM_TracePointThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct patchCollide_s *pc ) { - qboolean frontFacing[MAX_PATCH_PLANES]; - float intersection[MAX_PATCH_PLANES]; - float intersect; - const patchPlane_t *planes; - const facet_t *facet; - int i, j, k; - float offset; - float d1, d2; +static inline void CM_TracePointThroughPatchCollide(traceWork_t *tw, trace_t &trace, const struct patchCollide_s *pc) { + qboolean frontFacing[MAX_PATCH_PLANES]; + float intersection[MAX_PATCH_PLANES]; + float intersect; + const patchPlane_t *planes; + const facet_t *facet; + int i, j, k; + float offset; + float d1, d2; #ifndef BSPC static cvar_t *cv; -#endif //BSPC +#endif // BSPC #ifndef BSPC - if ( !cm_playerCurveClip->integer || !tw->isPoint ) { + if (!cm_playerCurveClip->integer || !tw->isPoint) { return; } #endif // determine the trace's relationship to all planes planes = pc->planes; - for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { - offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); - d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; - d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; - if ( d1 <= 0 ) { + for (i = 0; i < pc->numPlanes; i++, planes++) { + offset = DotProduct(tw->offsets[planes->signbits], planes->plane); + d1 = DotProduct(tw->start, planes->plane) - planes->plane[3] + offset; + d2 = DotProduct(tw->end, planes->plane) - planes->plane[3] + offset; + if (d1 <= 0) { frontFacing[i] = qfalse; } else { frontFacing[i] = qtrue; } - if ( d1 == d2 ) { + if (d1 == d2) { intersection[i] = 99999; } else { - intersection[i] = d1 / ( d1 - d2 ); - if ( intersection[i] <= 0 ) { + intersection[i] = d1 / (d1 - d2); + if (intersection[i] <= 0) { intersection[i] = 99999; } } } - // see if any of the surface planes are intersected facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { - if ( !frontFacing[facet->surfacePlane] ) { + for (i = 0; i < pc->numFacets; i++, facet++) { + if (!frontFacing[facet->surfacePlane]) { continue; } intersect = intersection[facet->surfacePlane]; - if ( intersect < 0 ) { - continue; // surface is behind the starting point + if (intersect < 0) { + continue; // surface is behind the starting point } - if ( intersect > trace.fraction ) { - continue; // already hit something closer + if (intersect > trace.fraction) { + continue; // already hit something closer } - for ( j = 0 ; j < facet->numBorders ; j++ ) { + for (j = 0; j < facet->numBorders; j++) { k = facet->borderPlanes[j]; - if ( frontFacing[k] ^ facet->borderInward[j] ) { - if ( intersection[k] > intersect ) { + if (frontFacing[k] ^ facet->borderInward[j]) { + if (intersection[k] > intersect) { break; } } else { - if ( intersection[k] < intersect ) { + if (intersection[k] < intersect) { break; } } } - if ( j == facet->numBorders ) { + if (j == facet->numBorders) { // we hit this facet #ifndef BSPC if (!cv) { - cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); + cv = Cvar_Get("r_debugSurfaceUpdate", "1", 0); } if (cv->integer) { debugPatchCollide = pc; debugFacet = facet; } -#endif //BSPC +#endif // BSPC planes = &pc->planes[facet->surfacePlane]; // calculate intersection with a slight pushoff - offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); - d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; - d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; - trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); + offset = DotProduct(tw->offsets[planes->signbits], planes->plane); + d1 = DotProduct(tw->start, planes->plane) - planes->plane[3] + offset; + d2 = DotProduct(tw->end, planes->plane) - planes->plane[3] + offset; + trace.fraction = (d1 - SURFACE_CLIP_EPSILON) / (d1 - d2); - if ( trace.fraction < 0 ) { + if (trace.fraction < 0) { trace.fraction = 0; } - VectorCopy( planes->plane, trace.plane.normal ); + VectorCopy(planes->plane, trace.plane.normal); trace.plane.dist = planes->plane[3]; } } @@ -1347,33 +1308,33 @@ static inline int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, flo *hit = qfalse; - d1 = DotProduct( start, plane ) - plane[3]; - d2 = DotProduct( end, plane ) - plane[3]; + d1 = DotProduct(start, plane) - plane[3]; + d2 = DotProduct(end, plane) - plane[3]; // if completely in front of face, no intersection with the entire facet - if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { + if (d1 > 0 && (d2 >= SURFACE_CLIP_EPSILON || d2 >= d1)) { return qfalse; } // if it doesn't cross the plane, the plane isn't relevent - if (d1 <= 0 && d2 <= 0 ) { + if (d1 <= 0 && d2 <= 0) { return qtrue; } // crosses face - if (d1 > d2) { // enter - f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f < 0 ) { + if (d1 > d2) { // enter + f = (d1 - SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f < 0) { f = 0; } - //always favor previous plane hits and thus also the surface plane hit + // always favor previous plane hits and thus also the surface plane hit if (f > *enterFrac) { *enterFrac = f; *hit = qtrue; } - } else { // leave - f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2); - if ( f > 1 ) { + } else { // leave + f = (d1 + SURFACE_CLIP_EPSILON) / (d1 - d2); + if (f > 1) { f = 1; } if (f < *leaveFrac) { @@ -1388,66 +1349,60 @@ static inline int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, flo CM_TraceThroughPatchCollide ==================== */ -void CM_TraceThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct patchCollide_s *pc ) -{ +void CM_TraceThroughPatchCollide(traceWork_t *tw, trace_t &trace, const struct patchCollide_s *pc) { int i, j, hit, hitnum; float offset, enterFrac, leaveFrac, t; patchPlane_t *planes; - facet_t *facet; - float plane[4] = { 0.0f }, bestplane[4] = { 0.0f }; + facet_t *facet; + float plane[4] = {0.0f}, bestplane[4] = {0.0f}; vec3_t startp, endp; #ifndef BSPC static cvar_t *cv; -#endif //BSPC +#endif // BSPC #ifndef CULL_BBOX // I'm not sure if test is strictly correct. Are all // bboxes axis aligned? Do I care? It seems to work // good enough... - for ( i = 0 ; i < 3 ; i++ ) { - if ( tw->bounds[0][i] > pc->bounds[1][i] - || tw->bounds[1][i] < pc->bounds[0][i] ) { + for (i = 0; i < 3; i++) { + if (tw->bounds[0][i] > pc->bounds[1][i] || tw->bounds[1][i] < pc->bounds[0][i]) { return; } } #endif if (tw->isPoint) { - CM_TracePointThroughPatchCollide( tw, trace, pc ); + CM_TracePointThroughPatchCollide(tw, trace, pc); return; } // facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { + for (i = 0; i < pc->numFacets; i++, facet++) { enterFrac = -1.0; leaveFrac = 1.0; hitnum = -1; // - planes = &pc->planes[ facet->surfacePlane ]; + planes = &pc->planes[facet->surfacePlane]; VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance appropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0.0f ) - { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - VectorSubtract( tw->end, tw->sphere.offset, endp ); - } - else - { - VectorAdd( tw->start, tw->sphere.offset, startp ); - VectorAdd( tw->end, tw->sphere.offset, endp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0.0f) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + VectorSubtract(tw->end, tw->sphere.offset, endp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); + VectorAdd(tw->end, tw->sphere.offset, endp); } - } - else { - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + } else { + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] -= offset; - VectorCopy( tw->start, startp ); - VectorCopy( tw->end, endp ); + VectorCopy(tw->start, startp); + VectorCopy(tw->end, endp); } // if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) @@ -1456,39 +1411,34 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct VectorCopy4(plane, bestplane); } // - for ( j = 0 ; j < facet->numBorders ; j++ ) { - planes = &pc->planes[ facet->borderPlanes[j] ]; + for (j = 0; j < facet->numBorders; j++) { + planes = &pc->planes[facet->borderPlanes[j]]; if (facet->borderInward[j]) { VectorNegate(planes->plane, plane); plane[3] = -planes->plane[3]; - } - else { + } else { VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; } - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance appropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0.0f ) - { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - VectorSubtract( tw->end, tw->sphere.offset, endp ); - } - else - { - VectorAdd( tw->start, tw->sphere.offset, startp ); - VectorAdd( tw->end, tw->sphere.offset, endp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0.0f) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + VectorSubtract(tw->end, tw->sphere.offset, endp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); + VectorAdd(tw->end, tw->sphere.offset, endp); } - } - else { + } else { // NOTE: this works even though the plane might be flipped because the bbox is centered - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] += fabs(offset); - VectorCopy( tw->start, startp ); - VectorCopy( tw->end, endp ); + VectorCopy(tw->start, startp); + VectorCopy(tw->end, endp); } // if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) @@ -1498,9 +1448,11 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct VectorCopy4(plane, bestplane); } } - if (j < facet->numBorders) continue; - //never clip against the back side - if (hitnum == facet->numBorders - 1) continue; + if (j < facet->numBorders) + continue; + // never clip against the back side + if (hitnum == facet->numBorders - 1) + continue; // if (enterFrac < leaveFrac && enterFrac >= 0) { if (enterFrac < trace.fraction) { @@ -1509,7 +1461,7 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct } #ifndef BSPC if (!cv) { - cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); + cv = Cvar_Get("r_debugSurfaceUpdate", "1", 0); } if (cv && cv->integer) { debugPatchCollide = pc; @@ -1518,14 +1470,13 @@ void CM_TraceThroughPatchCollide( traceWork_t *tw, trace_t &trace, const struct #endif // BSPC trace.fraction = enterFrac; - VectorCopy( bestplane, trace.plane.normal ); + VectorCopy(bestplane, trace.plane.normal); trace.plane.dist = bestplane[3]; } } } } - /* ======================================================================= @@ -1541,11 +1492,11 @@ CM_PositionTestInPatchCollide Modifies tr->tr if any of the facets effect the trace ==================== */ -qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { +qboolean CM_PositionTestInPatchCollide(traceWork_t *tw, const struct patchCollide_s *pc) { int i, j; float offset, t; patchPlane_t *planes; - facet_t *facet; + facet_t *facet; float plane[4]; vec3_t startp; @@ -1554,70 +1505,64 @@ qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchColli } // facet = pc->facets; - for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { - planes = &pc->planes[ facet->surfacePlane ]; + for (i = 0; i < pc->numFacets; i++, facet++) { + planes = &pc->planes[facet->surfacePlane]; VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance appropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0 ) { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - } - else { - VectorAdd( tw->start, tw->sphere.offset, startp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); } - } - else { - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + } else { + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] -= offset; - VectorCopy( tw->start, startp ); + VectorCopy(tw->start, startp); } - if ( DotProduct( plane, startp ) - plane[3] > 0.0f ) { + if (DotProduct(plane, startp) - plane[3] > 0.0f) { continue; } - for ( j = 0; j < facet->numBorders; j++ ) { - planes = &pc->planes[ facet->borderPlanes[j] ]; + for (j = 0; j < facet->numBorders; j++) { + planes = &pc->planes[facet->borderPlanes[j]]; if (facet->borderInward[j]) { VectorNegate(planes->plane, plane); plane[3] = -planes->plane[3]; - } - else { + } else { VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; } - if ( tw->sphere.use ) { + if (tw->sphere.use) { // adjust the plane distance appropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane, tw->sphere.offset ); - if ( t > 0.0f ) { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - } - else { - VectorAdd( tw->start, tw->sphere.offset, startp ); + t = DotProduct(plane, tw->sphere.offset); + if (t > 0.0f) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); } - } - else { + } else { // NOTE: this works even though the plane might be flipped because the bbox is centered - offset = DotProduct( tw->offsets[ planes->signbits ], plane); + offset = DotProduct(tw->offsets[planes->signbits], plane); plane[3] += fabs(offset); - VectorCopy( tw->start, startp ); + VectorCopy(tw->start, startp); } - if ( DotProduct( plane, startp ) - plane[3] > 0.0f ) { + if (DotProduct(plane, startp) - plane[3] > 0.0f) { break; } } if (j < facet->numBorders) { continue; - } // inside this patch facet return qtrue; @@ -1626,7 +1571,6 @@ qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchColli return qfalse; } - /* ======================================================================= @@ -1635,7 +1579,6 @@ DEBUGGING ======================================================================= */ - /* ================== CM_DrawDebugSurface @@ -1647,121 +1590,119 @@ Called from the renderer void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *points), int value); #endif -void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *points) ) { - static cvar_t *cv; +void CM_DrawDebugSurface(void (*drawPoly)(int color, int numPoints, float *points)) { + static cvar_t *cv; #ifndef BSPC - static cvar_t *cv2; + static cvar_t *cv2; #endif - const patchCollide_t *pc; - facet_t *facet; - winding_t *w; - int i, j, k, n; - int curplanenum, planenum, curinward, inward; - float plane[4]; + const patchCollide_t *pc; + facet_t *facet; + winding_t *w; + int i, j, k, n; + int curplanenum, planenum, curinward, inward; + float plane[4]; vec3_t mins = {-15, -15, -28}, maxs = {15, 15, 28}; - //vec3_t mins = {0, 0, 0}, maxs = {0, 0, 0}; + // vec3_t mins = {0, 0, 0}, maxs = {0, 0, 0}; vec3_t v1, v2; #ifndef BSPC - if ( !cv2 ) - { - cv2 = Cvar_Get( "r_debugSurface", "0", 0 ); + if (!cv2) { + cv2 = Cvar_Get("r_debugSurface", "0", 0); } - if (cv2->integer != 1) - { + if (cv2->integer != 1) { BotDrawDebugPolygons(drawPoly, cv2->integer); return; } #endif - if ( !debugPatchCollide ) { + if (!debugPatchCollide) { return; } #ifndef BSPC - if ( !cv ) { - cv = Cvar_Get( "cm_debugSize", "2", 0 ); + if (!cv) { + cv = Cvar_Get("cm_debugSize", "2", 0); } #endif pc = debugPatchCollide; - for ( i = 0, facet = pc->facets ; i < pc->numFacets ; i++, facet++ ) { + for (i = 0, facet = pc->facets; i < pc->numFacets; i++, facet++) { - for ( k = 0 ; k < facet->numBorders + 1; k++ ) { + for (k = 0; k < facet->numBorders + 1; k++) { // if (k < facet->numBorders) { planenum = facet->borderPlanes[k]; inward = facet->borderInward[k]; - } - else { + } else { planenum = facet->surfacePlane; inward = qfalse; - //continue; + // continue; } - VectorCopy4( pc->planes[ planenum ].plane, plane ); + VectorCopy4(pc->planes[planenum].plane, plane); - //planenum = facet->surfacePlane; - if ( inward ) { - VectorSubtract( vec3_origin, plane, plane ); + // planenum = facet->surfacePlane; + if (inward) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } plane[3] += cv->value; //* - for (n = 0; n < 3; n++) - { - if (plane[n] > 0) v1[n] = maxs[n]; - else v1[n] = mins[n]; - } //end for + for (n = 0; n < 3; n++) { + if (plane[n] > 0) + v1[n] = maxs[n]; + else + v1[n] = mins[n]; + } // end for VectorNegate(plane, v2); plane[3] += fabs(DotProduct(v1, v2)); //*/ - w = BaseWindingForPlane( plane, plane[3] ); - for ( j = 0 ; j < facet->numBorders + 1 && w; j++ ) { + w = BaseWindingForPlane(plane, plane[3]); + for (j = 0; j < facet->numBorders + 1 && w; j++) { // if (j < facet->numBorders) { curplanenum = facet->borderPlanes[j]; curinward = facet->borderInward[j]; - } - else { + } else { curplanenum = facet->surfacePlane; curinward = qfalse; - //continue; + // continue; } // - if (curplanenum == planenum) continue; + if (curplanenum == planenum) + continue; - VectorCopy4( pc->planes[ curplanenum ].plane, plane ); - if ( !curinward ) { - VectorSubtract( vec3_origin, plane, plane ); + VectorCopy4(pc->planes[curplanenum].plane, plane); + if (!curinward) { + VectorSubtract(vec3_origin, plane, plane); plane[3] = -plane[3]; } - // if ( !facet->borderNoAdjust[j] ) { - plane[3] -= cv->value; - // } - for (n = 0; n < 3; n++) - { - if (plane[n] > 0) v1[n] = maxs[n]; - else v1[n] = mins[n]; - } //end for + // if ( !facet->borderNoAdjust[j] ) { + plane[3] -= cv->value; + // } + for (n = 0; n < 3; n++) { + if (plane[n] > 0) + v1[n] = maxs[n]; + else + v1[n] = mins[n]; + } // end for VectorNegate(plane, v2); plane[3] -= fabs(DotProduct(v1, v2)); - ChopWindingInPlace( &w, plane, plane[3], 0.1f ); + ChopWindingInPlace(&w, plane, plane[3], 0.1f); } - if ( w ) { - if ( facet == debugFacet ) { - drawPoly( 4, w->numpoints, w->p[0] ); - //Com_Printf("blue facet has %d border planes\n", facet->numBorders); + if (w) { + if (facet == debugFacet) { + drawPoly(4, w->numpoints, w->p[0]); + // Com_Printf("blue facet has %d border planes\n", facet->numBorders); } else { - drawPoly( 1, w->numpoints, w->p[0] ); + drawPoly(1, w->numpoints, w->p[0]); } - FreeWinding( w ); - } - else + FreeWinding(w); + } else Com_Printf("winding chopped away by border planes\n"); } } @@ -1770,15 +1711,15 @@ void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *poin { matrix3_t v; - VectorCopy( debugBlockPoints[0], v[0] ); - VectorCopy( debugBlockPoints[1], v[1] ); - VectorCopy( debugBlockPoints[2], v[2] ); - drawPoly( 2, 3, v[0] ); + VectorCopy(debugBlockPoints[0], v[0]); + VectorCopy(debugBlockPoints[1], v[1]); + VectorCopy(debugBlockPoints[2], v[2]); + drawPoly(2, 3, v[0]); - VectorCopy( debugBlockPoints[2], v[0] ); - VectorCopy( debugBlockPoints[3], v[1] ); - VectorCopy( debugBlockPoints[0], v[2] ); - drawPoly( 2, 3, v[0] ); + VectorCopy(debugBlockPoints[2], v[0]); + VectorCopy(debugBlockPoints[3], v[1]); + VectorCopy(debugBlockPoints[0], v[2]); + drawPoly(2, 3, v[0]); } #if 0 @@ -1803,6 +1744,3 @@ void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *poin drawPoly( 4, v[0] ); #endif } - - - diff --git a/codemp/qcommon/cm_polylib.cpp b/codemp/qcommon/cm_polylib.cpp index 89dc86cf2d..82071bd859 100644 --- a/codemp/qcommon/cm_polylib.cpp +++ b/codemp/qcommon/cm_polylib.cpp @@ -25,31 +25,27 @@ along with this program; if not, see . #include "cm_local.h" #include "qcommon/qcommon.h" - // counters are only bumped when running single threaded, // because they are an awefull coherence problem -int c_active_windings; -int c_peak_windings; -int c_winding_allocs; -int c_winding_points; - -void pw(winding_t *w) -{ - int i; - for (i=0 ; inumpoints ; i++) - printf ("(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2]); +int c_active_windings; +int c_peak_windings; +int c_winding_allocs; +int c_winding_points; + +void pw(winding_t *w) { + int i; + for (i = 0; i < w->numpoints; i++) + printf("(%5.1f, %5.1f, %5.1f)\n", w->p[i][0], w->p[i][1], w->p[i][2]); } - /* ============= AllocWinding ============= */ -winding_t *AllocWinding (int points) -{ - winding_t *w; - int s; +winding_t *AllocWinding(int points) { + winding_t *w; + int s; c_winding_allocs++; c_winding_points += points; @@ -57,34 +53,30 @@ winding_t *AllocWinding (int points) if (c_active_windings > c_peak_windings) c_peak_windings = c_active_windings; - s = sizeof(float)*3*points + sizeof(int); - w = (winding_t *)Z_Malloc (s, TAG_BSP, qtrue); -// Com_Memset (w, 0, s); // qtrue param in Z_Malloc does this + s = sizeof(float) * 3 * points + sizeof(int); + w = (winding_t *)Z_Malloc(s, TAG_BSP, qtrue); + // Com_Memset (w, 0, s); // qtrue param in Z_Malloc does this return w; } -void FreeWinding (winding_t *w) -{ +void FreeWinding(winding_t *w) { if (*(unsigned *)w == 0xdeaddead) - Com_Error (ERR_FATAL, "FreeWinding: freed a freed winding"); + Com_Error(ERR_FATAL, "FreeWinding: freed a freed winding"); *(unsigned *)w = 0xdeaddead; c_active_windings--; - Z_Free (w); + Z_Free(w); } -void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs) -{ - float v; - int i,j; +void WindingBounds(winding_t *w, vec3_t mins, vec3_t maxs) { + float v; + int i, j; mins[0] = mins[1] = mins[2] = MAX_MAP_BOUNDS; maxs[0] = maxs[1] = maxs[2] = -MAX_MAP_BOUNDS; - for (i=0 ; inumpoints ; i++) - { - for (j=0 ; j<3 ; j++) - { + for (i = 0; i < w->numpoints; i++) { + for (j = 0; j < 3; j++) { v = w->p[i][j]; if (v < mins[j]) mins[j] = v; @@ -99,32 +91,28 @@ void WindingBounds (winding_t *w, vec3_t mins, vec3_t maxs) BaseWindingForPlane ================= */ -winding_t *BaseWindingForPlane (vec3_t normal, float dist) -{ - int i, x; - float max, v; - vec3_t org, vright, vup; - winding_t *w; +winding_t *BaseWindingForPlane(vec3_t normal, float dist) { + int i, x; + float max, v; + vec3_t org, vright, vup; + winding_t *w; -// find the major axis + // find the major axis max = -MAX_MAP_BOUNDS; x = -1; - for (i=0 ; i<3; i++) - { + for (i = 0; i < 3; i++) { v = fabs(normal[i]); - if (v > max) - { + if (v > max) { x = i; max = v; } } - if (x==-1) - Com_Error (ERR_DROP, "BaseWindingForPlane: no axis found"); + if (x == -1) + Com_Error(ERR_DROP, "BaseWindingForPlane: no axis found"); - VectorCopy (vec3_origin, vup); - switch (x) - { + VectorCopy(vec3_origin, vup); + switch (x) { case 0: case 1: vup[2] = 1; @@ -134,31 +122,31 @@ winding_t *BaseWindingForPlane (vec3_t normal, float dist) break; } - v = DotProduct (vup, normal); - VectorMA (vup, -v, normal, vup); + v = DotProduct(vup, normal); + VectorMA(vup, -v, normal, vup); VectorNormalize2(vup, vup); - VectorScale (normal, dist, org); + VectorScale(normal, dist, org); - CrossProduct (vup, normal, vright); + CrossProduct(vup, normal, vright); - VectorScale (vup, MAX_MAP_BOUNDS, vup); - VectorScale (vright, MAX_MAP_BOUNDS, vright); + VectorScale(vup, MAX_MAP_BOUNDS, vup); + VectorScale(vright, MAX_MAP_BOUNDS, vright); -// project a really big axis aligned box onto the plane - w = AllocWinding (4); + // project a really big axis aligned box onto the plane + w = AllocWinding(4); - VectorSubtract (org, vright, w->p[0]); - VectorAdd (w->p[0], vup, w->p[0]); + VectorSubtract(org, vright, w->p[0]); + VectorAdd(w->p[0], vup, w->p[0]); - VectorAdd (org, vright, w->p[1]); - VectorAdd (w->p[1], vup, w->p[1]); + VectorAdd(org, vright, w->p[1]); + VectorAdd(w->p[1], vup, w->p[1]); - VectorAdd (org, vright, w->p[2]); - VectorSubtract (w->p[2], vup, w->p[2]); + VectorAdd(org, vright, w->p[2]); + VectorSubtract(w->p[2], vup, w->p[2]); - VectorSubtract (org, vright, w->p[3]); - VectorSubtract (w->p[3], vup, w->p[3]); + VectorSubtract(org, vright, w->p[3]); + VectorSubtract(w->p[3], vup, w->p[3]); w->numpoints = 4; @@ -170,14 +158,13 @@ winding_t *BaseWindingForPlane (vec3_t normal, float dist) CopyWinding ================== */ -winding_t *CopyWinding (winding_t *w) -{ - intptr_t size; - winding_t *c; - - c = AllocWinding (w->numpoints); - size = (intptr_t) ((winding_t *)0)->p[w->numpoints]; - Com_Memcpy (c, w, size); +winding_t *CopyWinding(winding_t *w) { + intptr_t size; + winding_t *c; + + c = AllocWinding(w->numpoints); + size = (intptr_t)((winding_t *)0)->p[w->numpoints]; + Com_Memcpy(c, w, size); return c; } @@ -186,34 +173,31 @@ winding_t *CopyWinding (winding_t *w) ChopWindingInPlace ============= */ -void ChopWindingInPlace (winding_t **inout, vec3_t normal, float dist, float epsilon) -{ - winding_t *in; - float dists[MAX_POINTS_ON_WINDING+4] = { 0 }; - int sides[MAX_POINTS_ON_WINDING+4] = { 0 }; - int counts[3]; - static float dot; // VC 4.2 optimizer bug if not static - int i, j; - float *p1, *p2; - vec3_t mid; - winding_t *f; - int maxpts; +void ChopWindingInPlace(winding_t **inout, vec3_t normal, float dist, float epsilon) { + winding_t *in; + float dists[MAX_POINTS_ON_WINDING + 4] = {0}; + int sides[MAX_POINTS_ON_WINDING + 4] = {0}; + int counts[3]; + static float dot; // VC 4.2 optimizer bug if not static + int i, j; + float *p1, *p2; + vec3_t mid; + winding_t *f; + int maxpts; in = *inout; counts[0] = counts[1] = counts[2] = 0; -// determine sides for each point - for (i=0 ; inumpoints ; i++) - { - dot = DotProduct (in->p[i], normal); + // determine sides for each point + for (i = 0; i < in->numpoints; i++) { + dot = DotProduct(in->p[i], normal); dot -= dist; dists[i] = dot; if (dot > epsilon) sides[i] = SIDE_FRONT; else if (dot < -epsilon) sides[i] = SIDE_BACK; - else - { + else { sides[i] = SIDE_ON; } counts[sides[i]]++; @@ -221,63 +205,58 @@ void ChopWindingInPlace (winding_t **inout, vec3_t normal, float dist, float eps sides[i] = sides[0]; dists[i] = dists[0]; - if (!counts[0]) - { - FreeWinding (in); + if (!counts[0]) { + FreeWinding(in); *inout = NULL; return; } if (!counts[1]) - return; // inout stays the same + return; // inout stays the same - maxpts = in->numpoints+4; // cant use counts[0]+2 because + maxpts = in->numpoints + 4; // cant use counts[0]+2 because // of fp grouping errors - f = AllocWinding (maxpts); + f = AllocWinding(maxpts); - for (i=0 ; inumpoints ; i++) - { + for (i = 0; i < in->numpoints; i++) { p1 = in->p[i]; - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, f->p[f->numpoints]); + if (sides[i] == SIDE_ON) { + VectorCopy(p1, f->p[f->numpoints]); f->numpoints++; continue; } - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, f->p[f->numpoints]); + if (sides[i] == SIDE_FRONT) { + VectorCopy(p1, f->p[f->numpoints]); f->numpoints++; } - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) continue; - // generate a split point - p2 = in->p[(i+1)%in->numpoints]; + // generate a split point + p2 = in->p[(i + 1) % in->numpoints]; - dot = dists[i] / (dists[i]-dists[i+1]); - for (j=0 ; j<3 ; j++) - { // avoid round off error when possible + dot = dists[i] / (dists[i] - dists[i + 1]); + for (j = 0; j < 3; j++) { // avoid round off error when possible if (normal[j] == 1) mid[j] = dist; else if (normal[j] == -1) mid[j] = -dist; else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); + mid[j] = p1[j] + dot * (p2[j] - p1[j]); } - VectorCopy (mid, f->p[f->numpoints]); + VectorCopy(mid, f->p[f->numpoints]); f->numpoints++; } if (f->numpoints > maxpts) - Com_Error (ERR_DROP, "ClipWinding: points exceeded estimate"); + Com_Error(ERR_DROP, "ClipWinding: points exceeded estimate"); if (f->numpoints > MAX_POINTS_ON_WINDING) - Com_Error (ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING"); + Com_Error(ERR_DROP, "ClipWinding: MAX_POINTS_ON_WINDING"); - FreeWinding (in); + FreeWinding(in); *inout = f; } diff --git a/codemp/qcommon/cm_test.cpp b/codemp/qcommon/cm_test.cpp index ab5fe36146..e4e9172510 100644 --- a/codemp/qcommon/cm_test.cpp +++ b/codemp/qcommon/cm_test.cpp @@ -29,39 +29,37 @@ CM_PointLeafnum_r ================== */ -int CM_PointLeafnum_r( const vec3_t p, int num, clipMap_t *local ) { - float d; - cNode_t *node; - cplane_t *plane; +int CM_PointLeafnum_r(const vec3_t p, int num, clipMap_t *local) { + float d; + cNode_t *node; + cplane_t *plane; - while (num >= 0) - { + while (num >= 0) { node = local->nodes + num; plane = node->plane; if (plane->type < 3) d = p[plane->type] - plane->dist; else - d = DotProduct (plane->normal, p) - plane->dist; + d = DotProduct(plane->normal, p) - plane->dist; if (d < 0) num = node->children[1]; else num = node->children[0]; } - c_pointcontents++; // optimize counter + c_pointcontents++; // optimize counter return -1 - num; } -int CM_PointLeafnum( const vec3_t p ) { - if ( !cmg.numNodes ) { // map not loaded +int CM_PointLeafnum(const vec3_t p) { + if (!cmg.numNodes) { // map not loaded return 0; } - return CM_PointLeafnum_r (p, 0, &cmg); + return CM_PointLeafnum_r(p, 0, &cmg); } - /* ====================================================================== @@ -70,55 +68,54 @@ LEAF LISTING ====================================================================== */ - -void CM_StoreLeafs( leafList_t *ll, int nodenum ) { - int leafNum; +void CM_StoreLeafs(leafList_t *ll, int nodenum) { + int leafNum; leafNum = -1 - nodenum; // store the lastLeaf even if the list is overflowed - if ( cmg.leafs[ leafNum ].cluster != -1 ) { + if (cmg.leafs[leafNum].cluster != -1) { ll->lastLeaf = leafNum; } - if ( ll->count >= ll->maxcount) { + if (ll->count >= ll->maxcount) { ll->overflowed = qtrue; return; } - ll->list[ ll->count++ ] = leafNum; + ll->list[ll->count++] = leafNum; } -void CM_StoreBrushes( leafList_t *ll, int nodenum ) { - int i, k; - int leafnum; - int brushnum; - cLeaf_t *leaf; - cbrush_t *b; +void CM_StoreBrushes(leafList_t *ll, int nodenum) { + int i, k; + int leafnum; + int brushnum; + cLeaf_t *leaf; + cbrush_t *b; leafnum = -1 - nodenum; leaf = &cmg.leafs[leafnum]; - for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) { - brushnum = cmg.leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = cmg.leafbrushes[leaf->firstLeafBrush + k]; b = &cmg.brushes[brushnum]; - if ( b->checkcount == cmg.checkcount ) { - continue; // already checked this brush in another leaf + if (b->checkcount == cmg.checkcount) { + continue; // already checked this brush in another leaf } b->checkcount = cmg.checkcount; - for ( i = 0 ; i < 3 ; i++ ) { - if ( b->bounds[0][i] >= ll->bounds[1][i] || b->bounds[1][i] <= ll->bounds[0][i] ) { + for (i = 0; i < 3; i++) { + if (b->bounds[0][i] >= ll->bounds[1][i] || b->bounds[1][i] <= ll->bounds[0][i]) { break; } } - if ( i != 3 ) { + if (i != 3) { continue; } - if ( ll->count >= ll->maxcount) { + if (ll->count >= ll->maxcount) { ll->overflowed = qtrue; return; } - ((cbrush_t **)ll->list)[ ll->count++ ] = b; + ((cbrush_t **)ll->list)[ll->count++] = b; } #if 0 // store patches? @@ -138,31 +135,30 @@ CM_BoxLeafnums Fills in a list of all the leafs touched ============= */ -void CM_BoxLeafnums_r( leafList_t *ll, int nodenum ) { - cplane_t *plane; - cNode_t *node; - int s; +void CM_BoxLeafnums_r(leafList_t *ll, int nodenum) { + cplane_t *plane; + cNode_t *node; + int s; while (1) { if (nodenum < 0) { - ll->storeLeafs( ll, nodenum ); + ll->storeLeafs(ll, nodenum); return; } node = &cmg.nodes[nodenum]; plane = node->plane; - s = BoxOnPlaneSide( ll->bounds[0], ll->bounds[1], plane ); + s = BoxOnPlaneSide(ll->bounds[0], ll->bounds[1], plane); if (s == 1) { nodenum = node->children[0]; } else if (s == 2) { nodenum = node->children[1]; } else { // go down both - CM_BoxLeafnums_r( ll, node->children[0] ); + CM_BoxLeafnums_r(ll, node->children[0]); nodenum = node->children[1]; } - } } @@ -171,14 +167,14 @@ void CM_BoxLeafnums_r( leafList_t *ll, int nodenum ) { CM_BoxLeafnums ================== */ -int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *boxList, int listsize, int *lastLeaf) { - //rwwRMG - changed to boxList to not conflict with list type - leafList_t ll; +int CM_BoxLeafnums(const vec3_t mins, const vec3_t maxs, int *boxList, int listsize, int *lastLeaf) { + // rwwRMG - changed to boxList to not conflict with list type + leafList_t ll; cmg.checkcount++; - VectorCopy( mins, ll.bounds[0] ); - VectorCopy( maxs, ll.bounds[1] ); + VectorCopy(mins, ll.bounds[0]); + VectorCopy(maxs, ll.bounds[1]); ll.count = 0; ll.maxcount = listsize; ll.list = boxList; @@ -186,74 +182,65 @@ int CM_BoxLeafnums( const vec3_t mins, const vec3_t maxs, int *boxList, int list ll.lastLeaf = 0; ll.overflowed = qfalse; - CM_BoxLeafnums_r( &ll, 0 ); + CM_BoxLeafnums_r(&ll, 0); *lastLeaf = ll.lastLeaf; return ll.count; } - //==================================================================== - /* ================== CM_PointContents ================== */ -int CM_PointContents( const vec3_t p, clipHandle_t model ) { - int leafnum; - int i, k; - int brushnum; - cLeaf_t *leaf; - cbrush_t *b; - int contents; - float d; - cmodel_t *clipm; - clipMap_t *local; - - if (!cmg.numNodes) { // map not loaded +int CM_PointContents(const vec3_t p, clipHandle_t model) { + int leafnum; + int i, k; + int brushnum; + cLeaf_t *leaf; + cbrush_t *b; + int contents; + float d; + cmodel_t *clipm; + clipMap_t *local; + + if (!cmg.numNodes) { // map not loaded return 0; } - if ( model ) - { - clipm = CM_ClipHandleToModel( model, &local ); - if (clipm->firstNode != -1) - { - leafnum = CM_PointLeafnum_r (p, 0, local); + if (model) { + clipm = CM_ClipHandleToModel(model, &local); + if (clipm->firstNode != -1) { + leafnum = CM_PointLeafnum_r(p, 0, local); leaf = &local->leafs[leafnum]; - } - else - { + } else { leaf = &clipm->leaf; } - } - else - { + } else { local = &cmg; - leafnum = CM_PointLeafnum_r (p, 0, &cmg); + leafnum = CM_PointLeafnum_r(p, 0, &cmg); leaf = &local->leafs[leafnum]; } contents = 0; - for (k=0 ; knumLeafBrushes ; k++) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; // see if the point is in the brush - for ( i = 0 ; i < b->numsides ; i++ ) { - d = DotProduct( p, b->sides[i].plane->normal ); -// FIXME test for Cash -// if ( d >= b->sides[i].plane->dist ) { - if ( d > b->sides[i].plane->dist ) { + for (i = 0; i < b->numsides; i++) { + d = DotProduct(p, b->sides[i].plane->normal); + // FIXME test for Cash + // if ( d >= b->sides[i].plane->dist ) { + if (d > b->sides[i].plane->dist) { break; } } - if ( i == b->numsides ) - { + if (i == b->numsides) { contents |= b->contents; } } @@ -269,31 +256,27 @@ Handles offseting and rotation of the end points for moving and rotating entities ================== */ -int CM_TransformedPointContents( const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { - vec3_t p_l; - vec3_t temp; - vec3_t forward, right, up; +int CM_TransformedPointContents(const vec3_t p, clipHandle_t model, const vec3_t origin, const vec3_t angles) { + vec3_t p_l; + vec3_t temp; + vec3_t forward, right, up; // subtract origin offset - VectorSubtract (p, origin, p_l); + VectorSubtract(p, origin, p_l); // rotate start and end into the models frame of reference - if ( model != BOX_MODEL_HANDLE && - (angles[0] || angles[1] || angles[2]) ) - { - AngleVectors (angles, forward, right, up); - - VectorCopy (p_l, temp); - p_l[0] = DotProduct (temp, forward); - p_l[1] = -DotProduct (temp, right); - p_l[2] = DotProduct (temp, up); + if (model != BOX_MODEL_HANDLE && (angles[0] || angles[1] || angles[2])) { + AngleVectors(angles, forward, right, up); + + VectorCopy(p_l, temp); + p_l[0] = DotProduct(temp, forward); + p_l[1] = -DotProduct(temp, right); + p_l[2] = DotProduct(temp, up); } - return CM_PointContents( p_l, model ); + return CM_PointContents(p_l, model); } - - /* =============================================================================== @@ -301,8 +284,8 @@ PVS =============================================================================== */ -byte *CM_ClusterPVS (int cluster) { - if (cluster < 0 || cluster >= cmg.numClusters || !cmg.vised ) { +byte *CM_ClusterPVS(int cluster) { + if (cluster < 0 || cluster >= cmg.numClusters || !cmg.vised) { return cmg.visibility; } @@ -316,25 +299,25 @@ AREAPORTALS =============================================================================== */ -void CM_FloodArea_r( int areaNum, int floodnum, clipMap_t &cm ) { - int i; +void CM_FloodArea_r(int areaNum, int floodnum, clipMap_t &cm) { + int i; cArea_t *area; - int *con; + int *con; - area = &cm.areas[ areaNum ]; + area = &cm.areas[areaNum]; - if ( area->floodvalid == cm.floodvalid ) { + if (area->floodvalid == cm.floodvalid) { if (area->floodnum == floodnum) return; - Com_Error (ERR_DROP, "FloodArea_r: reflooded"); + Com_Error(ERR_DROP, "FloodArea_r: reflooded"); } area->floodnum = floodnum; area->floodvalid = cm.floodvalid; con = cm.areaPortals + areaNum * cm.numAreas; - for ( i=0 ; i < cm.numAreas ; i++ ) { - if ( con[i] > 0 ) { - CM_FloodArea_r( i, floodnum, cm ); + for (i = 0; i < cm.numAreas; i++) { + if (con[i] > 0) { + CM_FloodArea_r(i, floodnum, cm); } } } @@ -345,24 +328,23 @@ CM_FloodAreaConnections ==================== */ -void CM_FloodAreaConnections( clipMap_t &cm ) { - int i; - cArea_t *area; - int floodnum; +void CM_FloodAreaConnections(clipMap_t &cm) { + int i; + cArea_t *area; + int floodnum; // all current floods are now invalid cm.floodvalid++; floodnum = 0; - for (i = 0 ; i < cm.numAreas ; i++) { + for (i = 0; i < cm.numAreas; i++) { area = &cm.areas[i]; if (area->floodvalid == cm.floodvalid) { - continue; // already flooded into + continue; // already flooded into } floodnum++; - CM_FloodArea_r (i, floodnum, cm); + CM_FloodArea_r(i, floodnum, cm); } - } /* @@ -371,27 +353,27 @@ CM_AdjustAreaPortalState ==================== */ -void CM_AdjustAreaPortalState( int area1, int area2, qboolean open ) { - if ( area1 < 0 || area2 < 0 ) { +void CM_AdjustAreaPortalState(int area1, int area2, qboolean open) { + if (area1 < 0 || area2 < 0) { return; } - if ( area1 >= cmg.numAreas || area2 >= cmg.numAreas ) { - Com_Error (ERR_DROP, "CM_ChangeAreaPortalState: bad area number"); + if (area1 >= cmg.numAreas || area2 >= cmg.numAreas) { + Com_Error(ERR_DROP, "CM_ChangeAreaPortalState: bad area number"); } - if ( open ) { - cmg.areaPortals[ area1 * cmg.numAreas + area2 ]++; - cmg.areaPortals[ area2 * cmg.numAreas + area1 ]++; + if (open) { + cmg.areaPortals[area1 * cmg.numAreas + area2]++; + cmg.areaPortals[area2 * cmg.numAreas + area1]++; } else { - cmg.areaPortals[ area1 * cmg.numAreas + area2 ]--; - cmg.areaPortals[ area2 * cmg.numAreas + area1 ]--; - if ( cmg.areaPortals[ area2 * cmg.numAreas + area1 ] < 0 ) { - Com_Error (ERR_DROP, "CM_AdjustAreaPortalState: negative reference count"); + cmg.areaPortals[area1 * cmg.numAreas + area2]--; + cmg.areaPortals[area2 * cmg.numAreas + area1]--; + if (cmg.areaPortals[area2 * cmg.numAreas + area1] < 0) { + Com_Error(ERR_DROP, "CM_AdjustAreaPortalState: negative reference count"); } } - CM_FloodAreaConnections (cmg); + CM_FloodAreaConnections(cmg); } /* @@ -400,19 +382,19 @@ CM_AreasConnected ==================== */ -qboolean CM_AreasConnected( int area1, int area2 ) { +qboolean CM_AreasConnected(int area1, int area2) { #ifndef BSPC - if ( cm_noAreas->integer ) { + if (cm_noAreas->integer) { return qtrue; } #endif - if ( area1 < 0 || area2 < 0 ) { + if (area1 < 0 || area2 < 0) { return qfalse; } if (area1 >= cmg.numAreas || area2 >= cmg.numAreas) { - Com_Error (ERR_DROP, "area >= cmg.numAreas"); + Com_Error(ERR_DROP, "area >= cmg.numAreas"); } if (cmg.areas[area1].floodnum == cmg.areas[area2].floodnum) { @@ -421,7 +403,6 @@ qboolean CM_AreasConnected( int area1, int area2 ) { return qfalse; } - /* ================= CM_WriteAreaBits @@ -436,32 +417,27 @@ viewpoints and get the union of all visible areas. This is used to cull non-visible entities from snapshots ================= */ -int CM_WriteAreaBits (byte *buffer, int area) -{ - int i; - int floodnum; - int bytes; +int CM_WriteAreaBits(byte *buffer, int area) { + int i; + int floodnum; + int bytes; - bytes = (cmg.numAreas+7)>>3; + bytes = (cmg.numAreas + 7) >> 3; #ifndef BSPC if (cm_noAreas->integer || area == -1) #else - if ( area == -1) + if (area == -1) #endif - { // for debugging, send everything - Com_Memset (buffer, 255, bytes); - } - else - { + { // for debugging, send everything + Com_Memset(buffer, 255, bytes); + } else { floodnum = cmg.areas[area].floodnum; - for (i=0 ; i>3] |= 1<<(i&7); + buffer[i >> 3] |= 1 << (i & 7); } } return bytes; } - diff --git a/codemp/qcommon/cm_trace.cpp b/codemp/qcommon/cm_trace.cpp index 36fd04a361..32cabb6420 100644 --- a/codemp/qcommon/cm_trace.cpp +++ b/codemp/qcommon/cm_trace.cpp @@ -81,13 +81,12 @@ void CreateRotationMatrix(const vec3_t angles, matrix3_t matrix) { CM_ProjectPointOntoVector ================ */ -void CM_ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vDir, vec3_t vProj ) -{ +void CM_ProjectPointOntoVector(vec3_t point, vec3_t vStart, vec3_t vDir, vec3_t vProj) { vec3_t pVec; - VectorSubtract( point, vStart, pVec ); + VectorSubtract(point, vStart, pVec); // project onto the directional vector for this segment - VectorMA( vStart, DotProduct( pVec, vDir ), vDir, vProj ); + VectorMA(vStart, DotProduct(pVec, vDir), vDir, vProj); } /* @@ -101,8 +100,7 @@ float CM_DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2, vec3_t dir) { CM_ProjectPointOntoVector(p, lp1, dir, proj); for (j = 0; j < 3; j++) - if ((proj[j] > lp1[j] && proj[j] > lp2[j]) || - (proj[j] < lp1[j] && proj[j] < lp2[j])) + if ((proj[j] > lp1[j] && proj[j] > lp2[j]) || (proj[j] < lp1[j] && proj[j] < lp2[j])) break; if (j < 3) { if (fabs(proj[j] - lp1[j]) < fabs(proj[j] - lp2[j])) @@ -115,7 +113,6 @@ float CM_DistanceFromLineSquared(vec3_t p, vec3_t lp1, vec3_t lp2, vec3_t dir) { return VectorLengthSquared(t); } - /* =============================================================================== @@ -129,69 +126,61 @@ POSITION TESTING CM_TestBoxInBrush ================ */ -void CM_TestBoxInBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush ) { - int i; - cplane_t *plane; - float dist; - float d1; - cbrushside_t *side; - float t; - vec3_t startp; +void CM_TestBoxInBrush(traceWork_t *tw, trace_t &trace, cbrush_t *brush) { + int i; + cplane_t *plane; + float dist; + float d1; + cbrushside_t *side; + float t; + vec3_t startp; if (!brush->numsides) { return; } // special test for axial - if ( tw->bounds[0][0] > brush->bounds[1][0] - || tw->bounds[0][1] > brush->bounds[1][1] - || tw->bounds[0][2] > brush->bounds[1][2] - || tw->bounds[1][0] < brush->bounds[0][0] - || tw->bounds[1][1] < brush->bounds[0][1] - || tw->bounds[1][2] < brush->bounds[0][2] - ) { + if (tw->bounds[0][0] > brush->bounds[1][0] || tw->bounds[0][1] > brush->bounds[1][1] || tw->bounds[0][2] > brush->bounds[1][2] || + tw->bounds[1][0] < brush->bounds[0][0] || tw->bounds[1][1] < brush->bounds[0][1] || tw->bounds[1][2] < brush->bounds[0][2]) { return; } - if ( tw->sphere.use ) { + if (tw->sphere.use) { // the first six planes are the axial planes, so we only // need to test the remainder - for ( i = 6 ; i < brush->numsides ; i++ ) { + for (i = 6; i < brush->numsides; i++) { side = brush->sides + i; plane = side->plane; // adjust the plane distance appropriately for radius dist = plane->dist + tw->sphere.radius; // find the closest point on the capsule to the plane - t = DotProduct( plane->normal, tw->sphere.offset ); - if ( t > 0 ) - { - VectorSubtract( tw->start, tw->sphere.offset, startp ); - } - else - { - VectorAdd( tw->start, tw->sphere.offset, startp ); + t = DotProduct(plane->normal, tw->sphere.offset); + if (t > 0) { + VectorSubtract(tw->start, tw->sphere.offset, startp); + } else { + VectorAdd(tw->start, tw->sphere.offset, startp); } - d1 = DotProduct( startp, plane->normal ) - dist; + d1 = DotProduct(startp, plane->normal) - dist; // if completely in front of face, no intersection - if ( d1 > 0 ) { + if (d1 > 0) { return; } } } else { // the first six planes are the axial planes, so we only // need to test the remainder - for ( i = 6 ; i < brush->numsides ; i++ ) { + for (i = 6; i < brush->numsides; i++) { side = brush->sides + i; plane = side->plane; // adjust the plane distance appropriately for mins/maxs - dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal ); + dist = plane->dist - DotProduct(tw->offsets[plane->signbits], plane->normal); - d1 = DotProduct( tw->start, plane->normal ) - dist; + d1 = DotProduct(tw->start, plane->normal) - dist; // if completely in front of face, no intersection - if ( d1 > 0 ) { + if (d1 > 0) { return; } } @@ -203,34 +192,32 @@ void CM_TestBoxInBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush ) { trace.contents = brush->contents; } - /* ================ CM_TestInLeaf ================ */ -void CM_TestInLeaf( traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t *local ) -{ - int k; - int brushnum; - cbrush_t *b; - cPatch_t *patch; +void CM_TestInLeaf(traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t *local) { + int k; + int brushnum; + cbrush_t *b; + cPatch_t *patch; // test box position against all brushes in the leaf - for (k=0 ; knumLeafBrushes ; k++) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; if (b->checkcount == local->checkcount) { - continue; // already checked this brush in another leaf + continue; // already checked this brush in another leaf } b->checkcount = local->checkcount; - if ( !(b->contents & tw->contents)) { + if (!(b->contents & tw->contents)) { continue; } - CM_TestBoxInBrush( tw, trace, b ); - if ( trace.allsolid ) { + CM_TestBoxInBrush(tw, trace, b); + if (trace.allsolid) { return; } } @@ -239,23 +226,23 @@ void CM_TestInLeaf( traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t *l #ifdef BSPC if (1) { #else - if ( !cm_noCurves->integer ) { -#endif //BSPC - for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) { - patch = local->surfaces[ local->leafsurfaces[ leaf->firstLeafSurface + k ] ]; - if ( !patch ) { + if (!cm_noCurves->integer) { +#endif // BSPC + for (k = 0; k < leaf->numLeafSurfaces; k++) { + patch = local->surfaces[local->leafsurfaces[leaf->firstLeafSurface + k]]; + if (!patch) { continue; } - if ( patch->checkcount == local->checkcount ) { - continue; // already checked this brush in another leaf + if (patch->checkcount == local->checkcount) { + continue; // already checked this brush in another leaf } patch->checkcount = local->checkcount; - if ( !(patch->contents & tw->contents)) { + if (!(patch->contents & tw->contents)) { continue; } - if ( CM_PositionTestInPatchCollide( tw, patch->pc ) ) { + if (CM_PositionTestInPatchCollide(tw, patch->pc)) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; trace.contents = patch->contents; @@ -272,7 +259,7 @@ CM_TestCapsuleInCapsule capsule inside capsule check ================== */ -void CM_TestCapsuleInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t model ) { +void CM_TestCapsuleInCapsule(traceWork_t *tw, trace_t &trace, clipHandle_t model) { int i; vec3_t mins, maxs; vec3_t top, bottom; @@ -284,14 +271,14 @@ void CM_TestCapsuleInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t mode VectorAdd(tw->start, tw->sphere.offset, top); VectorSubtract(tw->start, tw->sphere.offset, bottom); - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; symetricSize[0][i] = mins[i] - offset[i]; symetricSize[1][i] = maxs[i] - offset[i]; } - halfwidth = symetricSize[ 1 ][ 0 ]; - halfheight = symetricSize[ 1 ][ 2 ]; - radius = ( halfwidth > halfheight ) ? halfheight : halfwidth; + halfwidth = symetricSize[1][0]; + halfheight = symetricSize[1][2]; + radius = (halfwidth > halfheight) ? halfheight : halfwidth; offs = halfheight - radius; r = Square(tw->sphere.radius + radius); @@ -299,35 +286,34 @@ void CM_TestCapsuleInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t mode VectorCopy(offset, p1); p1[2] += offs; VectorSubtract(p1, top, tmp); - if ( VectorLengthSquared(tmp) < r ) { + if (VectorLengthSquared(tmp) < r) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; } VectorSubtract(p1, bottom, tmp); - if ( VectorLengthSquared(tmp) < r ) { + if (VectorLengthSquared(tmp) < r) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; } VectorCopy(offset, p2); p2[2] -= offs; VectorSubtract(p2, top, tmp); - if ( VectorLengthSquared(tmp) < r ) { + if (VectorLengthSquared(tmp) < r) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; } VectorSubtract(p2, bottom, tmp); - if ( VectorLengthSquared(tmp) < r ) { + if (VectorLengthSquared(tmp) < r) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; } // if between cylinder up and lower bounds - if ( (top[2] >= p1[2] && top[2] <= p2[2]) || - (bottom[2] >= p1[2] && bottom[2] <= p2[2]) ) { + if ((top[2] >= p1[2] && top[2] <= p2[2]) || (bottom[2] >= p1[2] && bottom[2] <= p2[2])) { // 2d coordinates top[2] = p1[2] = 0; // if the cylinders overlap VectorSubtract(top, p1, tmp); - if ( VectorLengthSquared(tmp) < r ) { + if (VectorLengthSquared(tmp) < r) { trace.startsolid = trace.allsolid = qtrue; trace.fraction = 0; } @@ -341,7 +327,7 @@ CM_TestBoundingBoxInCapsule bounding box inside capsule check ================== */ -void CM_TestBoundingBoxInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t model ) { +void CM_TestBoundingBoxInCapsule(traceWork_t *tw, trace_t &trace, clipHandle_t model) { vec3_t mins, maxs, offset, size[2]; clipHandle_t h; cmodel_t *cmod; @@ -351,8 +337,8 @@ void CM_TestBoundingBoxInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t CM_ModelBounds(model, mins, maxs); // offset for capsule center - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; size[0][i] = mins[i] - offset[i]; size[1][i] = maxs[i] - offset[i]; tw->start[i] -= offset[i]; @@ -361,15 +347,15 @@ void CM_TestBoundingBoxInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t // replace the bounding box with the capsule tw->sphere.use = qtrue; - tw->sphere.radius = ( size[1][0] > size[1][2] ) ? size[1][2]: size[1][0]; + tw->sphere.radius = (size[1][0] > size[1][2]) ? size[1][2] : size[1][0]; tw->sphere.halfheight = size[1][2]; - VectorSet( tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius ); + VectorSet(tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius); // replace the capsule with the bounding box h = CM_TempBoxModel(tw->size[0], tw->size[1], qfalse); // calculate collision - cmod = CM_ClipHandleToModel( h ); - CM_TestInLeaf( tw, trace, &cmod->leaf, &cmg ); + cmod = CM_ClipHandleToModel(h); + CM_TestInLeaf(tw, trace, &cmod->leaf, &cmg); } /* @@ -377,17 +363,17 @@ void CM_TestBoundingBoxInCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t CM_PositionTest ================== */ -#define MAX_POSITION_LEAFS 1024 -void CM_PositionTest( traceWork_t *tw, trace_t &trace ) { - int leafs[MAX_POSITION_LEAFS]; - int i; - leafList_t ll; +#define MAX_POSITION_LEAFS 1024 +void CM_PositionTest(traceWork_t *tw, trace_t &trace) { + int leafs[MAX_POSITION_LEAFS]; + int i; + leafList_t ll; // identify the leafs we are touching - VectorAdd( tw->start, tw->size[0], ll.bounds[0] ); - VectorAdd( tw->start, tw->size[1], ll.bounds[1] ); + VectorAdd(tw->start, tw->size[0], ll.bounds[0]); + VectorAdd(tw->start, tw->size[1], ll.bounds[1]); - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { ll.bounds[0][i] -= 1; ll.bounds[1][i] += 1; } @@ -401,15 +387,14 @@ void CM_PositionTest( traceWork_t *tw, trace_t &trace ) { cmg.checkcount++; - CM_BoxLeafnums_r( &ll, 0 ); - + CM_BoxLeafnums_r(&ll, 0); cmg.checkcount++; // test the contents of the leafs - for (i=0 ; i < ll.count ; i++) { - CM_TestInLeaf( tw, trace, &cmg.leafs[leafs[i]], &cmg ); - if ( trace.allsolid ) { + for (i = 0; i < ll.count; i++) { + CM_TestInLeaf(tw, trace, &cmg.leafs[leafs[i]], &cmg); + if (trace.allsolid) { break; } } @@ -423,23 +408,22 @@ TRACING =============================================================================== */ - /* ================ CM_TraceThroughPatch ================ */ -void CM_TraceThroughPatch( traceWork_t *tw, trace_t &trace, cPatch_t *patch ) { - float oldFrac; +void CM_TraceThroughPatch(traceWork_t *tw, trace_t &trace, cPatch_t *patch) { + float oldFrac; c_patch_traces++; oldFrac = trace.fraction; - CM_TraceThroughPatchCollide( tw, trace, patch->pc ); + CM_TraceThroughPatchCollide(tw, trace, patch->pc); - if ( trace.fraction < oldFrac ) { + if (trace.fraction < oldFrac) { trace.surfaceFlags = patch->surfaceFlags; trace.contents = patch->contents; } @@ -453,79 +437,63 @@ CM_PlaneCollision ================ */ -bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) -{ - float dist, f; - float d1, d2; +bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) { + float dist, f; + float d1, d2; - cplane_t *plane = side->plane; + cplane_t *plane = side->plane; // adjust the plane distance appropriately for mins/maxs - dist = plane->dist - DotProduct( tw->offsets[ plane->signbits ], plane->normal ); + dist = plane->dist - DotProduct(tw->offsets[plane->signbits], plane->normal); - d1 = DotProduct( tw->start, plane->normal ) - dist; - d2 = DotProduct( tw->end, plane->normal ) - dist; + d1 = DotProduct(tw->start, plane->normal) - dist; + d2 = DotProduct(tw->end, plane->normal) - dist; - if (d2 > 0.0f) - { + if (d2 > 0.0f) { // endpoint is not in solid tw->getout = true; } - if (d1 > 0.0f) - { + if (d1 > 0.0f) { // startpoint is not in solid tw->startout = true; } // if completely in front of face, no intersection with the entire brush - if ((d1 > 0.0f) && ( (d2 >= SURFACE_CLIP_EPSILON) || (d2 >= d1) ) ) - { - return(false); + if ((d1 > 0.0f) && ((d2 >= SURFACE_CLIP_EPSILON) || (d2 >= d1))) { + return (false); } // if it doesn't cross the plane, the plane isn't relevent - if ((d1 <= 0.0f) && (d2 <= 0.0f)) - { - return(true); + if ((d1 <= 0.0f) && (d2 <= 0.0f)) { + return (true); } // crosses face - if (d1 > d2) - { // enter + if (d1 > d2) { // enter f = (d1 - SURFACE_CLIP_EPSILON); - if ( f < 0.0f ) - { + if (f < 0.0f) { f = 0.0f; - if (f > tw->enterFrac) - { + if (f > tw->enterFrac) { tw->enterFrac = f; tw->clipplane = plane; tw->leadside = side; } - } - else if (f > tw->enterFrac * (d1 - d2) ) - { + } else if (f > tw->enterFrac * (d1 - d2)) { tw->enterFrac = f / (d1 - d2); tw->clipplane = plane; tw->leadside = side; } - } - else - { // leave + } else { // leave f = (d1 + SURFACE_CLIP_EPSILON); - if ( f < (d1 - d2) ) - { + if (f < (d1 - d2)) { f = 1.0f; - if (f < tw->leaveFrac) - { + if (f < tw->leaveFrac) { tw->leaveFrac = f; } - } - else if (f > tw->leaveFrac * (d1 - d2) ) - { + } else if (f > tw->leaveFrac * (d1 - d2)) { tw->leaveFrac = f / (d1 - d2); } } - return(true); + return (true); } /* @@ -533,30 +501,23 @@ bool CM_PlaneCollision(traceWork_t *tw, cbrushside_t *side) CM_TraceThroughBrush ================ */ -void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, bool infoOnly ) -{ - int i; - cbrushside_t *side; +void CM_TraceThroughBrush(traceWork_t *tw, trace_t &trace, cbrush_t *brush, bool infoOnly) { + int i; + cbrushside_t *side; tw->enterFrac = -1.0f; tw->leaveFrac = 1.0f; tw->clipplane = NULL; - if ( !brush->numsides ) - { + if (!brush->numsides) { return; } // I'm not sure if test is strictly correct. Are all // bboxes axis aligned? Do I care? It seems to work // good enough... - if ( tw->bounds[0][0] > brush->bounds[1][0] - || tw->bounds[0][1] > brush->bounds[1][1] - || tw->bounds[0][2] > brush->bounds[1][2] - || tw->bounds[1][0] < brush->bounds[0][0] - || tw->bounds[1][1] < brush->bounds[0][1] - || tw->bounds[1][2] < brush->bounds[0][2] - ) { + if (tw->bounds[0][0] > brush->bounds[1][0] || tw->bounds[0][1] > brush->bounds[1][1] || tw->bounds[0][2] > brush->bounds[1][2] || + tw->bounds[1][0] < brush->bounds[0][0] || tw->bounds[1][1] < brush->bounds[0][1] || tw->bounds[1][2] < brush->bounds[0][2]) { return; } @@ -569,12 +530,10 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo // find the latest time the trace crosses a plane towards the interior // and the earliest time the trace crosses a plane towards the exterior // - for (i = 0; i < brush->numsides; i++) - { + for (i = 0; i < brush->numsides; i++) { side = brush->sides + i; - if(!CM_PlaneCollision(tw, side)) - { + if (!CM_PlaneCollision(tw, side)) { return; } } @@ -583,14 +542,11 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo // all planes have been checked, and the trace was not // completely outside the brush // - if (!tw->startout) - { - if(!infoOnly) - { + if (!tw->startout) { + if (!infoOnly) { // original point was inside brush trace.startsolid = qtrue; - if (!tw->getout) - { + if (!tw->getout) { trace.allsolid = qtrue; trace.fraction = 0.0f; } @@ -599,16 +555,12 @@ void CM_TraceThroughBrush( traceWork_t *tw, trace_t &trace, cbrush_t *brush, boo return; } - if (tw->enterFrac < tw->leaveFrac) - { - if ((tw->enterFrac > -1.0f) && (tw->enterFrac < trace.fraction)) - { - if (tw->enterFrac < 0.0f) - { + if (tw->enterFrac < tw->leaveFrac) { + if ((tw->enterFrac > -1.0f) && (tw->enterFrac < trace.fraction)) { + if (tw->enterFrac < 0.0f) { tw->enterFrac = 0.0f; } - if(!infoOnly) - { + if (!infoOnly) { trace.fraction = tw->enterFrac; trace.plane = *tw->clipplane; trace.surfaceFlags = cmg.shaders[tw->leadside->shaderNum].surfaceFlags; @@ -624,23 +576,19 @@ CM_GenericBoxCollide ================ */ -bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) -{ - int i; +bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) { + int i; // Check for completely no intersection - for(i = 0; i < 3; i++) - { - if(abounds[1][i] < bbounds[0][i]) - { - return(false); + for (i = 0; i < 3; i++) { + if (abounds[1][i] < bbounds[0][i]) { + return (false); } - if(abounds[0][i] > bbounds[1][i]) - { - return(false); + if (abounds[0][i] > bbounds[1][i]) { + return (false); } } - return(true); + return (true); } /* @@ -648,29 +596,29 @@ bool CM_GenericBoxCollide(const vec3pair_t abounds, const vec3pair_t bbounds) CM_TraceThroughLeaf ================ */ -void CM_TraceThroughLeaf( traceWork_t *tw, trace_t &trace, clipMap_t *local, cLeaf_t *leaf ) { - int k; - int brushnum; - cbrush_t *b; - cPatch_t *patch; +void CM_TraceThroughLeaf(traceWork_t *tw, trace_t &trace, clipMap_t *local, cLeaf_t *leaf) { + int k; + int brushnum; + cbrush_t *b; + cPatch_t *patch; // trace line against all brushes in the leaf - for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) { - brushnum = local->leafbrushes[leaf->firstLeafBrush+k]; + for (k = 0; k < leaf->numLeafBrushes; k++) { + brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; - if ( b->checkcount == local->checkcount ) { - continue; // already checked this brush in another leaf + if (b->checkcount == local->checkcount) { + continue; // already checked this brush in another leaf } b->checkcount = local->checkcount; - if ( !(b->contents & tw->contents) ) { + if (!(b->contents & tw->contents)) { continue; } - CM_TraceThroughBrush( tw, trace, b, false ); + CM_TraceThroughBrush(tw, trace, b, false); - if ( !trace.fraction ) { + if (!trace.fraction) { return; } } @@ -679,31 +627,31 @@ void CM_TraceThroughLeaf( traceWork_t *tw, trace_t &trace, clipMap_t *local, cLe #ifdef BSPC if (1) { #else - if ( !cm_noCurves->integer ) { + if (!cm_noCurves->integer) { #endif - for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) { - patch = local->surfaces[ local->leafsurfaces[ leaf->firstLeafSurface + k ] ]; - if ( !patch ) { + for (k = 0; k < leaf->numLeafSurfaces; k++) { + patch = local->surfaces[local->leafsurfaces[leaf->firstLeafSurface + k]]; + if (!patch) { continue; } - if ( patch->checkcount == local->checkcount ) { - continue; // already checked this patch in another leaf + if (patch->checkcount == local->checkcount) { + continue; // already checked this patch in another leaf } patch->checkcount = local->checkcount; - if ( !(patch->contents & tw->contents) ) { + if (!(patch->contents & tw->contents)) { continue; } - CM_TraceThroughPatch( tw, trace, patch ); - if ( !trace.fraction ) { + CM_TraceThroughPatch(tw, trace, patch); + if (!trace.fraction) { return; } } } } -#define RADIUS_EPSILON 1.0f +#define RADIUS_EPSILON 1.0f /* ================ @@ -712,9 +660,9 @@ CM_TraceThroughSphere get the first intersection of the ray with the sphere ================ */ -void CM_TraceThroughSphere( traceWork_t *tw, trace_t &trace, vec3_t origin, float radius, vec3_t start, vec3_t end ) { +void CM_TraceThroughSphere(traceWork_t *tw, trace_t &trace, vec3_t origin, float radius, vec3_t start, vec3_t end) { float l1, l2, length, scale, fraction; - float /*a, */b, c, d, sqrtd; + float /*a, */ b, c, d, sqrtd; vec3_t v1, dir, intersection; // if inside the sphere @@ -739,7 +687,7 @@ void CM_TraceThroughSphere( traceWork_t *tw, trace_t &trace, vec3_t origin, floa VectorSubtract(end, origin, v1); l2 = VectorLengthSquared(v1); // if no intersection with the sphere and the end point is at least an epsilon away - if (l1 >= Square(radius) && l2 > Square(radius+SURFACE_CLIP_EPSILON)) { + if (l1 >= Square(radius) && l2 > Square(radius + SURFACE_CLIP_EPSILON)) { return; } // @@ -750,44 +698,42 @@ void CM_TraceThroughSphere( traceWork_t *tw, trace_t &trace, vec3_t origin, floa // VectorSubtract(start, origin, v1); // dir is normalized so a = 1 - //a = 1.0f;//dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; + // a = 1.0f;//dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]; b = 2.0f * (dir[0] * v1[0] + dir[1] * v1[1] + dir[2] * v1[2]); - c = v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] - (radius+RADIUS_EPSILON) * (radius+RADIUS_EPSILON); + c = v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] - (radius + RADIUS_EPSILON) * (radius + RADIUS_EPSILON); - d = b * b - 4.0f * c;// * a; + d = b * b - 4.0f * c; // * a; if (d > 0) { sqrtd = sqrtf(d); // = (- b + sqrtd) * 0.5f; // / (2.0f * a); - fraction = (- b - sqrtd) * 0.5f; // / (2.0f * a); + fraction = (-b - sqrtd) * 0.5f; // / (2.0f * a); // if (fraction < 0) { fraction = 0; - } - else { + } else { fraction /= length; } - if ( fraction < trace.fraction ) { + if (fraction < trace.fraction) { trace.fraction = fraction; VectorSubtract(end, start, dir); VectorMA(start, fraction, dir, intersection); VectorSubtract(intersection, origin, dir); - #ifdef CAPSULE_DEBUG - l2 = VectorLength(dir); - if (l2 < radius) { - int bah = 1; - } - #endif - scale = 1 / (radius+RADIUS_EPSILON); +#ifdef CAPSULE_DEBUG + l2 = VectorLength(dir); + if (l2 < radius) { + int bah = 1; + } +#endif + scale = 1 / (radius + RADIUS_EPSILON); VectorScale(dir, scale, dir); VectorCopy(dir, trace.plane.normal); - VectorAdd( tw->modelOrigin, intersection, intersection); + VectorAdd(tw->modelOrigin, intersection, intersection); trace.plane.dist = DotProduct(trace.plane.normal, intersection); trace.contents = CONTENTS_BODY; } - } - else if (d == 0) { - //t1 = (- b ) / 2; - // slide along the sphere + } else if (d == 0) { + // t1 = (- b ) / 2; + // slide along the sphere } // no intersection at all } @@ -800,9 +746,9 @@ get the first intersection of the ray with the cylinder the cylinder extends halfheight above and below the origin ================ */ -void CM_TraceThroughVerticalCylinder( traceWork_t *tw, trace_t &trace, vec3_t origin, float radius, float halfheight, vec3_t start, vec3_t end) { +void CM_TraceThroughVerticalCylinder(traceWork_t *tw, trace_t &trace, vec3_t origin, float radius, float halfheight, vec3_t start, vec3_t end) { float length, scale, fraction, l1, l2; - float /*a, */b, c, d, sqrtd; + float /*a, */ b, c, d, sqrtd; vec3_t v1, dir, start2d, end2d, org2d, intersection; // 2d coordinates @@ -810,8 +756,7 @@ void CM_TraceThroughVerticalCylinder( traceWork_t *tw, trace_t &trace, vec3_t or VectorSet(end2d, end[0], end[1], 0); VectorSet(org2d, origin[0], origin[1], 0); // if between lower and upper cylinder bounds - if (start[2] <= origin[2] + halfheight && - start[2] >= origin[2] - halfheight) { + if (start[2] <= origin[2] + halfheight && start[2] >= origin[2] - halfheight) { // if inside the cylinder VectorSubtract(start2d, org2d, dir); l1 = VectorLengthSquared(dir); @@ -834,7 +779,7 @@ void CM_TraceThroughVerticalCylinder( traceWork_t *tw, trace_t &trace, vec3_t or VectorSubtract(end2d, org2d, v1); l2 = VectorLengthSquared(v1); // if no intersection with the cylinder and the end point is at least an epsilon away - if (l1 >= Square(radius) && l2 > Square(radius+SURFACE_CLIP_EPSILON)) { + if (l1 >= Square(radius) && l2 > Square(radius + SURFACE_CLIP_EPSILON)) { return; } // @@ -848,50 +793,47 @@ void CM_TraceThroughVerticalCylinder( traceWork_t *tw, trace_t &trace, vec3_t or // VectorSubtract(start, origin, v1); // dir is normalized so we can use a = 1 - //a = 1.0f;// * (dir[0] * dir[0] + dir[1] * dir[1]); + // a = 1.0f;// * (dir[0] * dir[0] + dir[1] * dir[1]); b = 2.0f * (v1[0] * dir[0] + v1[1] * dir[1]); - c = v1[0] * v1[0] + v1[1] * v1[1] - (radius+RADIUS_EPSILON) * (radius+RADIUS_EPSILON); + c = v1[0] * v1[0] + v1[1] * v1[1] - (radius + RADIUS_EPSILON) * (radius + RADIUS_EPSILON); - d = b * b - 4.0f * c;// * a; + d = b * b - 4.0f * c; // * a; if (d > 0) { sqrtd = sqrtf(d); // = (- b + sqrtd) * 0.5f;// / (2.0f * a); - fraction = (- b - sqrtd) * 0.5f;// / (2.0f * a); + fraction = (-b - sqrtd) * 0.5f; // / (2.0f * a); // if (fraction < 0) { fraction = 0; - } - else { + } else { fraction /= length; } - if ( fraction < trace.fraction ) { + if (fraction < trace.fraction) { VectorSubtract(end, start, dir); VectorMA(start, fraction, dir, intersection); // if the intersection is between the cylinder lower and upper bound - if (intersection[2] <= origin[2] + halfheight && - intersection[2] >= origin[2] - halfheight) { + if (intersection[2] <= origin[2] + halfheight && intersection[2] >= origin[2] - halfheight) { // trace.fraction = fraction; VectorSubtract(intersection, origin, dir); dir[2] = 0; - #ifdef CAPSULE_DEBUG - l2 = VectorLength(dir); - if (l2 <= radius) { - int bah = 1; - } - #endif - scale = 1 / (radius+RADIUS_EPSILON); +#ifdef CAPSULE_DEBUG + l2 = VectorLength(dir); + if (l2 <= radius) { + int bah = 1; + } +#endif + scale = 1 / (radius + RADIUS_EPSILON); VectorScale(dir, scale, dir); VectorCopy(dir, trace.plane.normal); - VectorAdd( tw->modelOrigin, intersection, intersection); + VectorAdd(tw->modelOrigin, intersection, intersection); trace.plane.dist = DotProduct(trace.plane.normal, intersection); trace.contents = CONTENTS_BODY; } } - } - else if (d == 0) { - //t[0] = (- b ) / 2 * a; - // slide along the cylinder + } else if (d == 0) { + // t[0] = (- b ) / 2 * a; + // slide along the cylinder } // no intersection at all } @@ -903,7 +845,7 @@ CM_TraceCapsuleThroughCapsule capsule vs. capsule collision (not rotated) ================ */ -void CM_TraceCapsuleThroughCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t model ) { +void CM_TraceCapsuleThroughCapsule(traceWork_t *tw, trace_t &trace, clipHandle_t model) { int i; vec3_t mins, maxs; vec3_t top, bottom, starttop, startbottom, endtop, endbottom; @@ -912,13 +854,8 @@ void CM_TraceCapsuleThroughCapsule( traceWork_t *tw, trace_t &trace, clipHandle_ CM_ModelBounds(model, mins, maxs); // test trace bounds vs. capsule bounds - if ( tw->bounds[0][0] > maxs[0] + RADIUS_EPSILON - || tw->bounds[0][1] > maxs[1] + RADIUS_EPSILON - || tw->bounds[0][2] > maxs[2] + RADIUS_EPSILON - || tw->bounds[1][0] < mins[0] - RADIUS_EPSILON - || tw->bounds[1][1] < mins[1] - RADIUS_EPSILON - || tw->bounds[1][2] < mins[2] - RADIUS_EPSILON - ) { + if (tw->bounds[0][0] > maxs[0] + RADIUS_EPSILON || tw->bounds[0][1] > maxs[1] + RADIUS_EPSILON || tw->bounds[0][2] > maxs[2] + RADIUS_EPSILON || + tw->bounds[1][0] < mins[0] - RADIUS_EPSILON || tw->bounds[1][1] < mins[1] - RADIUS_EPSILON || tw->bounds[1][2] < mins[2] - RADIUS_EPSILON) { return; } // top origin and bottom origin of each sphere at start and end of trace @@ -928,14 +865,14 @@ void CM_TraceCapsuleThroughCapsule( traceWork_t *tw, trace_t &trace, clipHandle_ VectorSubtract(tw->end, tw->sphere.offset, endbottom); // calculate top and bottom of the capsule spheres to collide with - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; symetricSize[0][i] = mins[i] - offset[i]; symetricSize[1][i] = maxs[i] - offset[i]; } - halfwidth = symetricSize[ 1 ][ 0 ]; - halfheight = symetricSize[ 1 ][ 2 ]; - radius = ( halfwidth > halfheight ) ? halfheight : halfwidth; + halfwidth = symetricSize[1][0]; + halfheight = symetricSize[1][2]; + radius = (halfwidth > halfheight) ? halfheight : halfwidth; offs = halfheight - radius; VectorCopy(offset, top); top[2] += offs; @@ -944,11 +881,11 @@ void CM_TraceCapsuleThroughCapsule( traceWork_t *tw, trace_t &trace, clipHandle_ // expand radius of spheres radius += tw->sphere.radius; // if there is horizontal movement - if ( tw->start[0] != tw->end[0] || tw->start[1] != tw->end[1] ) { + if (tw->start[0] != tw->end[0] || tw->start[1] != tw->end[1]) { // height of the expanded cylinder is the height of both cylinders minus the radius of both spheres h = halfheight + tw->sphere.halfheight - radius; // if the cylinder has a height - if ( h > 0 ) { + if (h > 0) { // test for collisions between the cylinders CM_TraceThroughVerticalCylinder(tw, trace, offset, radius, h, tw->start, tw->end); } @@ -965,7 +902,7 @@ CM_TraceBoundingBoxThroughCapsule bounding box vs. capsule collision ================ */ -void CM_TraceBoundingBoxThroughCapsule( traceWork_t *tw, trace_t &trace, clipHandle_t model ) { +void CM_TraceBoundingBoxThroughCapsule(traceWork_t *tw, trace_t &trace, clipHandle_t model) { vec3_t mins, maxs, offset, size[2]; clipHandle_t h; cmodel_t *cmod; @@ -975,8 +912,8 @@ void CM_TraceBoundingBoxThroughCapsule( traceWork_t *tw, trace_t &trace, clipHan CM_ModelBounds(model, mins, maxs); // offset for capsule center - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; size[0][i] = mins[i] - offset[i]; size[1][i] = maxs[i] - offset[i]; tw->start[i] -= offset[i]; @@ -985,15 +922,15 @@ void CM_TraceBoundingBoxThroughCapsule( traceWork_t *tw, trace_t &trace, clipHan // replace the bounding box with the capsule tw->sphere.use = qtrue; - tw->sphere.radius = ( size[1][0] > size[1][2] ) ? size[1][2]: size[1][0]; + tw->sphere.radius = (size[1][0] > size[1][2]) ? size[1][2] : size[1][0]; tw->sphere.halfheight = size[1][2]; - VectorSet( tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius ); + VectorSet(tw->sphere.offset, 0, 0, size[1][2] - tw->sphere.radius); // replace the capsule with the bounding box h = CM_TempBoxModel(tw->size[0], tw->size[1], qfalse); // calculate collision - cmod = CM_ClipHandleToModel( h ); - CM_TraceThroughLeaf( tw, trace, &cmg, &cmod->leaf ); + cmod = CM_ClipHandleToModel(h); + CM_TraceThroughLeaf(tw, trace, &cmg, &cmod->leaf); } //========================================================================================= @@ -1003,33 +940,28 @@ void CM_TraceBoundingBoxThroughCapsule( traceWork_t *tw, trace_t &trace, clipHan CM_TraceToLeaf ================ */ -void CM_TraceToLeaf( traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t *local ) -{ - int k; - int brushnum; - cbrush_t *b; - cPatch_t *patch; +void CM_TraceToLeaf(traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t *local) { + int k; + int brushnum; + cbrush_t *b; + cPatch_t *patch; // trace line against all brushes in the leaf - for ( k = 0 ; k < leaf->numLeafBrushes ; k++ ) - { + for (k = 0; k < leaf->numLeafBrushes; k++) { brushnum = local->leafbrushes[leaf->firstLeafBrush + k]; b = &local->brushes[brushnum]; - if ( b->checkcount == local->checkcount ) - { - continue; // already checked this brush in another leaf + if (b->checkcount == local->checkcount) { + continue; // already checked this brush in another leaf } b->checkcount = local->checkcount; - if ( !(b->contents & tw->contents) ) - { + if (!(b->contents & tw->contents)) { continue; } - CM_TraceThroughBrush( tw, trace, b, false); - if ( !trace.fraction ) - { + CM_TraceThroughBrush(tw, trace, b, false); + if (!trace.fraction) { return; } } @@ -1038,24 +970,24 @@ void CM_TraceToLeaf( traceWork_t *tw, trace_t &trace, cLeaf_t *leaf, clipMap_t * #ifdef BSPC if (1) { #else - if ( !cm_noCurves->integer ) { + if (!cm_noCurves->integer) { #endif - for ( k = 0 ; k < leaf->numLeafSurfaces ; k++ ) { - patch = local->surfaces[ local->leafsurfaces[ leaf->firstLeafSurface + k ] ]; - if ( !patch ) { + for (k = 0; k < leaf->numLeafSurfaces; k++) { + patch = local->surfaces[local->leafsurfaces[leaf->firstLeafSurface + k]]; + if (!patch) { continue; } - if ( patch->checkcount == local->checkcount ) { - continue; // already checked this patch in another leaf + if (patch->checkcount == local->checkcount) { + continue; // already checked this patch in another leaf } patch->checkcount = local->checkcount; - if ( !(patch->contents & tw->contents) ) { + if (!(patch->contents & tw->contents)) { continue; } - CM_TraceThroughPatch( tw, trace, patch ); - if ( !trace.fraction ) { + CM_TraceThroughPatch(tw, trace, patch); + if (!trace.fraction) { return; } } @@ -1072,23 +1004,23 @@ trace volumes it is possible to hit something in a later leaf with a smaller intercept fraction. ================== */ -void CM_TraceThroughTree( traceWork_t *tw, trace_t &trace, clipMap_t *local, int num, float p1f, float p2f, vec3_t p1, vec3_t p2) { - cNode_t *node; - cplane_t *plane; - float t1, t2, offset; - float frac, frac2; - float idist; - vec3_t mid; - int side; - float midf; +void CM_TraceThroughTree(traceWork_t *tw, trace_t &trace, clipMap_t *local, int num, float p1f, float p2f, vec3_t p1, vec3_t p2) { + cNode_t *node; + cplane_t *plane; + float t1, t2, offset; + float frac, frac2; + float idist; + vec3_t mid; + int side; + float midf; if (trace.fraction <= p1f) { - return; // already hit something nearer + return; // already hit something nearer } // if < 0, we are in a leaf node if (num < 0) { - CM_TraceThroughLeaf( tw, trace, local, &local->leafs[-1-num] ); + CM_TraceThroughLeaf(tw, trace, local, &local->leafs[-1 - num]); return; } @@ -1100,20 +1032,20 @@ void CM_TraceThroughTree( traceWork_t *tw, trace_t &trace, clipMap_t *local, int plane = node->plane; // adjust the plane distance appropriately for mins/maxs - if ( plane->type < 3 ) { + if (plane->type < 3) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; offset = tw->extents[plane->type]; } else { - t1 = DotProduct (plane->normal, p1) - plane->dist; - t2 = DotProduct (plane->normal, p2) - plane->dist; - if ( tw->isPoint ) { + t1 = DotProduct(plane->normal, p1) - plane->dist; + t2 = DotProduct(plane->normal, p2) - plane->dist; + if (tw->isPoint) { offset = 0; } else { #if 0 // bk010201 - DEAD - // an axial brush right behind a slanted bsp plane - // will poke through when expanded, so adjust - // by sqrt(3) + // an axial brush right behind a slanted bsp plane + // will poke through when expanded, so adjust + // by sqrt(3) offset = fabs(tw->extents[0]*plane->normal[0]) + fabs(tw->extents[1]*plane->normal[1]) + fabs(tw->extents[2]*plane->normal[2]); @@ -1127,26 +1059,26 @@ void CM_TraceThroughTree( traceWork_t *tw, trace_t &trace, clipMap_t *local, int } // see which sides we need to consider - if ( t1 >= offset + 1 && t2 >= offset + 1 ) { - CM_TraceThroughTree( tw, trace, local, node->children[0], p1f, p2f, p1, p2 ); + if (t1 >= offset + 1 && t2 >= offset + 1) { + CM_TraceThroughTree(tw, trace, local, node->children[0], p1f, p2f, p1, p2); return; } - if ( t1 < -offset - 1 && t2 < -offset - 1 ) { - CM_TraceThroughTree( tw, trace, local, node->children[1], p1f, p2f, p1, p2 ); + if (t1 < -offset - 1 && t2 < -offset - 1) { + CM_TraceThroughTree(tw, trace, local, node->children[1], p1f, p2f, p1, p2); return; } // put the crosspoint SURFACE_CLIP_EPSILON pixels on the near side - if ( t1 < t2 ) { - idist = 1.0/(t1-t2); + if (t1 < t2) { + idist = 1.0 / (t1 - t2); side = 1; - frac2 = (t1 + offset + SURFACE_CLIP_EPSILON)*idist; - frac = (t1 - offset + SURFACE_CLIP_EPSILON)*idist; + frac2 = (t1 + offset + SURFACE_CLIP_EPSILON) * idist; + frac = (t1 - offset + SURFACE_CLIP_EPSILON) * idist; } else if (t1 > t2) { - idist = 1.0/(t1-t2); + idist = 1.0 / (t1 - t2); side = 0; - frac2 = (t1 - offset - SURFACE_CLIP_EPSILON)*idist; - frac = (t1 + offset + SURFACE_CLIP_EPSILON)*idist; + frac2 = (t1 - offset - SURFACE_CLIP_EPSILON) * idist; + frac = (t1 + offset + SURFACE_CLIP_EPSILON) * idist; } else { side = 0; frac = 1; @@ -1154,52 +1086,46 @@ void CM_TraceThroughTree( traceWork_t *tw, trace_t &trace, clipMap_t *local, int } // move up to the node - if ( frac < 0 ) { + if (frac < 0) { frac = 0; } - if ( frac > 1 ) { + if (frac > 1) { frac = 1; } - midf = p1f + (p2f - p1f)*frac; + midf = p1f + (p2f - p1f) * frac; - mid[0] = p1[0] + frac*(p2[0] - p1[0]); - mid[1] = p1[1] + frac*(p2[1] - p1[1]); - mid[2] = p1[2] + frac*(p2[2] - p1[2]); - - CM_TraceThroughTree( tw, trace, local, node->children[side], p1f, midf, p1, mid ); + mid[0] = p1[0] + frac * (p2[0] - p1[0]); + mid[1] = p1[1] + frac * (p2[1] - p1[1]); + mid[2] = p1[2] + frac * (p2[2] - p1[2]); + CM_TraceThroughTree(tw, trace, local, node->children[side], p1f, midf, p1, mid); // go past the node - if ( frac2 < 0 ) { + if (frac2 < 0) { frac2 = 0; } - if ( frac2 > 1 ) { + if (frac2 > 1) { frac2 = 1; } - midf = p1f + (p2f - p1f)*frac2; + midf = p1f + (p2f - p1f) * frac2; - mid[0] = p1[0] + frac2*(p2[0] - p1[0]); - mid[1] = p1[1] + frac2*(p2[1] - p1[1]); - mid[2] = p1[2] + frac2*(p2[2] - p1[2]); + mid[0] = p1[0] + frac2 * (p2[0] - p1[0]); + mid[1] = p1[1] + frac2 * (p2[1] - p1[1]); + mid[2] = p1[2] + frac2 * (p2[2] - p1[2]); - CM_TraceThroughTree( tw, trace, local, node->children[side^1], midf, p2f, mid, p2 ); + CM_TraceThroughTree(tw, trace, local, node->children[side ^ 1], midf, p2f, mid, p2); } -void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, vec3pair_t bounds) -{ - int i; +void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, vec3pair_t bounds) { + int i; - for ( i = 0 ; i < 3 ; i++ ) - { - if ( start[i] < end[i] ) - { + for (i = 0; i < 3; i++) { + if (start[i] < end[i]) { bounds[0][i] = start[i] + tw->size[0][i]; bounds[1][i] = end[i] + tw->size[1][i]; - } - else - { + } else { bounds[0][i] = end[i] + tw->size[0][i]; bounds[1][i] = start[i] + tw->size[1][i]; } @@ -1208,42 +1134,40 @@ void CM_CalcExtents(const vec3_t start, const vec3_t end, const traceWork_t *tw, //====================================================================== - /* ================== CM_Trace ================== */ -void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, const vec3_t origin, int brushmask, int capsule, sphere_t *sphere ) { - int i; - traceWork_t tw; - vec3_t offset; - cmodel_t *cmod; - clipMap_t *local = 0; +void CM_Trace(trace_t *trace, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, const vec3_t origin, + int brushmask, int capsule, sphere_t *sphere) { + int i; + traceWork_t tw; + vec3_t offset; + cmodel_t *cmod; + clipMap_t *local = 0; - cmod = CM_ClipHandleToModel( model, &local ); + cmod = CM_ClipHandleToModel(model, &local); - local->checkcount++; // for multi-check avoidance + local->checkcount++; // for multi-check avoidance - c_traces++; // for statistics, may be zeroed + c_traces++; // for statistics, may be zeroed // fill in a default trace - Com_Memset( &tw, 0, sizeof(tw) ); + Com_Memset(&tw, 0, sizeof(tw)); memset(trace, 0, sizeof(*trace)); - trace->fraction = 1; // assume it goes the entire distance until shown otherwise + trace->fraction = 1; // assume it goes the entire distance until shown otherwise VectorCopy(origin, tw.modelOrigin); if (!local->numNodes) { - return; // map not loaded, shouldn't happen + return; // map not loaded, shouldn't happen } // allow NULL to be passed in for 0,0,0 - if ( !mins ) { + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } @@ -1253,8 +1177,8 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, // adjust so that mins and maxs are always symetric, which // avoids some complications with plane expanding of rotated // bmodels - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; tw.size[0][i] = mins[i] - offset[i]; tw.size[1][i] = maxs[i] - offset[i]; tw.start[i] = start[i] + offset[i]; @@ -1262,14 +1186,13 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, } // if a sphere is already specified - if ( sphere ) { + if (sphere) { tw.sphere = *sphere; - } - else { + } else { tw.sphere.use = (qboolean)capsule; - tw.sphere.radius = ( tw.size[1][0] > tw.size[1][2] ) ? tw.size[1][2]: tw.size[1][0]; + tw.sphere.radius = (tw.size[1][0] > tw.size[1][2]) ? tw.size[1][2] : tw.size[1][0]; tw.sphere.halfheight = tw.size[1][2]; - VectorSet( tw.sphere.offset, 0, 0, tw.size[1][2] - tw.sphere.radius ); + VectorSet(tw.sphere.offset, 0, 0, tw.size[1][2] - tw.sphere.radius); } tw.maxOffset = tw.size[1][0] + tw.size[1][1] + tw.size[1][2]; @@ -1310,9 +1233,9 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, // // calculate bounds // - if ( tw.sphere.use ) { - for ( i = 0 ; i < 3 ; i++ ) { - if ( tw.start[i] < tw.end[i] ) { + if (tw.sphere.use) { + for (i = 0; i < 3; i++) { + if (tw.start[i] < tw.end[i]) { tw.bounds[0][i] = tw.start[i] - fabs(tw.sphere.offset[i]) - tw.sphere.radius; tw.bounds[1][i] = tw.end[i] + fabs(tw.sphere.offset[i]) + tw.sphere.radius; } else { @@ -1320,10 +1243,9 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, tw.bounds[1][i] = tw.start[i] + fabs(tw.sphere.offset[i]) + tw.sphere.radius; } } - } - else { - for ( i = 0 ; i < 3 ; i++ ) { - if ( tw.start[i] < tw.end[i] ) { + } else { + for (i = 0; i < 3; i++) { + if (tw.start[i] < tw.end[i]) { tw.bounds[0][i] = tw.start[i] + tw.size[0][i]; tw.bounds[1][i] = tw.end[i] + tw.size[1][i]; } else { @@ -1336,62 +1258,40 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, // // check for position test special case // - if (start[0] == end[0] && start[1] == end[1] && start[2] == end[2] && - tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0) - { - if ( model && cmod->firstNode == -1) - { + if (start[0] == end[0] && start[1] == end[1] && start[2] == end[2] && tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0) { + if (model && cmod->firstNode == -1) { #ifdef ALWAYS_BBOX_VS_BBOX // bk010201 - FIXME - compile time flag? - if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) - { + if (model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) { tw.sphere.use = qfalse; - CM_TestInLeaf( &tw, &cmod->leaf ); - } - else + CM_TestInLeaf(&tw, &cmod->leaf); + } else #elif defined(ALWAYS_CAPSULE_VS_CAPSULE) - if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) - { - CM_TestCapsuleInCapsule( &tw, model ); - } - else + if (model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) { + CM_TestCapsuleInCapsule(&tw, model); + } else #endif - if ( model == CAPSULE_MODEL_HANDLE ) - { - if ( tw.sphere.use ) - { - CM_TestCapsuleInCapsule( &tw, *trace, model ); + if (model == CAPSULE_MODEL_HANDLE) { + if (tw.sphere.use) { + CM_TestCapsuleInCapsule(&tw, *trace, model); + } else { + CM_TestBoundingBoxInCapsule(&tw, *trace, model); } - else - { - CM_TestBoundingBoxInCapsule( &tw, *trace, model ); - } - } - else - { - CM_TestInLeaf( &tw, *trace, &cmod->leaf, local ); + } else { + CM_TestInLeaf(&tw, *trace, &cmod->leaf, local); } + } else if (cmod->firstNode == -1) { + CM_PositionTest(&tw, *trace); + } else { + CM_TraceThroughTree(&tw, *trace, local, cmod->firstNode, 0, 1, tw.start, tw.end); } - else if (cmod->firstNode == -1) - { - CM_PositionTest( &tw, *trace ); - } - else - { - CM_TraceThroughTree( &tw, *trace, local, cmod->firstNode, 0, 1, tw.start, tw.end ); - } - } - else - { + } else { // // check for point special case // - if ( tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0 ) - { + if (tw.size[0][0] == 0 && tw.size[0][1] == 0 && tw.size[0][2] == 0) { tw.isPoint = qtrue; - VectorClear( tw.extents ); - } - else - { + VectorClear(tw.extents); + } else { tw.isPoint = qfalse; tw.extents[0] = tw.size[1][0]; tw.extents[1] = tw.size[1][1]; @@ -1401,59 +1301,44 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, // // general sweeping through world // - if ( model && cmod->firstNode == -1) - { + if (model && cmod->firstNode == -1) { #ifdef ALWAYS_BBOX_VS_BBOX - if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) - { + if (model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) { tw.sphere.use = qfalse; - CM_TraceThroughLeaf( &tw, &cmod->leaf ); - } - else + CM_TraceThroughLeaf(&tw, &cmod->leaf); + } else #elif defined(ALWAYS_CAPSULE_VS_CAPSULE) - if ( model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) - { - CM_TraceCapsuleThroughCapsule( &tw, model ); - } - else + if (model == BOX_MODEL_HANDLE || model == CAPSULE_MODEL_HANDLE) { + CM_TraceCapsuleThroughCapsule(&tw, model); + } else #endif - if ( model == CAPSULE_MODEL_HANDLE ) - { - if ( tw.sphere.use ) - { - CM_TraceCapsuleThroughCapsule( &tw, *trace, model ); - } - else - { - CM_TraceBoundingBoxThroughCapsule( &tw, *trace, model ); + if (model == CAPSULE_MODEL_HANDLE) { + if (tw.sphere.use) { + CM_TraceCapsuleThroughCapsule(&tw, *trace, model); + } else { + CM_TraceBoundingBoxThroughCapsule(&tw, *trace, model); } + } else { + CM_TraceThroughLeaf(&tw, *trace, local, &cmod->leaf); } - else - { - CM_TraceThroughLeaf( &tw, *trace, local, &cmod->leaf ); - } - } - else - { - CM_TraceThroughTree( &tw, *trace, local, cmod->firstNode, 0, 1, tw.start, tw.end ); + } else { + CM_TraceThroughTree(&tw, *trace, local, cmod->firstNode, 0, 1, tw.start, tw.end); } } // generate endpos from the original, unmodified start/end - if ( trace->fraction == 1 ) { - VectorCopy (end, trace->endpos); + if (trace->fraction == 1) { + VectorCopy(end, trace->endpos); } else { - for ( i=0 ; i<3 ; i++ ) { + for (i = 0; i < 3; i++) { trace->endpos[i] = start[i] + trace->fraction * (end[i] - start[i]); } } - // If allsolid is set (was entirely inside something solid), the plane is not valid. - // If fraction == 1.0, we never hit anything, and thus the plane is not valid. - // Otherwise, the normal on the plane should have unit length - assert(trace->allsolid || - trace->fraction == 1.0 || - VectorLengthSquared(trace->plane.normal) > 0.9999); + // If allsolid is set (was entirely inside something solid), the plane is not valid. + // If fraction == 1.0, we never hit anything, and thus the plane is not valid. + // Otherwise, the normal on the plane should have unit length + assert(trace->allsolid || trace->fraction == 1.0 || VectorLengthSquared(trace->plane.normal) > 0.9999); } /* @@ -1461,10 +1346,8 @@ void CM_Trace( trace_t *trace, const vec3_t start, const vec3_t end, CM_BoxTrace ================== */ -void CM_BoxTrace( trace_t *results, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask, int capsule ) { - CM_Trace( results, start, end, mins, maxs, model, vec3_origin, brushmask, capsule, NULL ); +void CM_BoxTrace(trace_t *results, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, int capsule) { + CM_Trace(results, start, end, mins, maxs, model, vec3_origin, brushmask, capsule, NULL); } /* @@ -1475,33 +1358,31 @@ Handles offseting and rotation of the end points for moving and rotating entities ================== */ -void CM_TransformedBoxTrace( trace_t *trace, const vec3_t start, const vec3_t end, - const vec3_t mins, const vec3_t maxs, - clipHandle_t model, int brushmask, - const vec3_t origin, const vec3_t angles, int capsule ) { - vec3_t start_l, end_l; - qboolean rotated; - vec3_t offset; - vec3_t symetricSize[2]; - matrix3_t matrix, transpose; - int i; - float halfwidth; - float halfheight; - float t; - sphere_t sphere; - - if ( !mins ) { +void CM_TransformedBoxTrace(trace_t *trace, const vec3_t start, const vec3_t end, const vec3_t mins, const vec3_t maxs, clipHandle_t model, int brushmask, + const vec3_t origin, const vec3_t angles, int capsule) { + vec3_t start_l, end_l; + qboolean rotated; + vec3_t offset; + vec3_t symetricSize[2]; + matrix3_t matrix, transpose; + int i; + float halfwidth; + float halfheight; + float t; + sphere_t sphere; + + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } // adjust so that mins and maxs are always symetric, which // avoids some complications with plane expanding of rotated // bmodels - for ( i = 0 ; i < 3 ; i++ ) { - offset[i] = ( mins[i] + maxs[i] ) * 0.5; + for (i = 0; i < 3; i++) { + offset[i] = (mins[i] + maxs[i]) * 0.5; symetricSize[0][i] = mins[i] - offset[i]; symetricSize[1][i] = maxs[i] - offset[i]; start_l[i] = start[i] + offset[i]; @@ -1509,22 +1390,21 @@ void CM_TransformedBoxTrace( trace_t *trace, const vec3_t start, const vec3_t en } // subtract origin offset - VectorSubtract( start_l, origin, start_l ); - VectorSubtract( end_l, origin, end_l ); + VectorSubtract(start_l, origin, start_l); + VectorSubtract(end_l, origin, end_l); // rotate start and end into the models frame of reference - if ( model != BOX_MODEL_HANDLE && - (angles[0] || angles[1] || angles[2]) ) { + if (model != BOX_MODEL_HANDLE && (angles[0] || angles[1] || angles[2])) { rotated = qtrue; } else { rotated = qfalse; } - halfwidth = symetricSize[ 1 ][ 0 ]; - halfheight = symetricSize[ 1 ][ 2 ]; + halfwidth = symetricSize[1][0]; + halfheight = symetricSize[1][2]; sphere.use = (qboolean)capsule; - sphere.radius = ( halfwidth > halfheight ) ? halfheight : halfwidth; + sphere.radius = (halfwidth > halfheight) ? halfheight : halfwidth; sphere.halfheight = halfheight; t = halfheight - sphere.radius; @@ -1539,19 +1419,18 @@ void CM_TransformedBoxTrace( trace_t *trace, const vec3_t start, const vec3_t en RotatePoint(start_l, matrix); RotatePoint(end_l, matrix); // rotated sphere offset for capsule - sphere.offset[0] = matrix[0][ 2 ] * t; - sphere.offset[1] = -matrix[1][ 2 ] * t; - sphere.offset[2] = matrix[2][ 2 ] * t; - } - else { - VectorSet( sphere.offset, 0, 0, t ); + sphere.offset[0] = matrix[0][2] * t; + sphere.offset[1] = -matrix[1][2] * t; + sphere.offset[2] = matrix[2][2] * t; + } else { + VectorSet(sphere.offset, 0, 0, t); } // sweep the box through the model - CM_Trace( trace, start_l, end_l, symetricSize[0], symetricSize[1], model, origin, brushmask, capsule, &sphere ); + CM_Trace(trace, start_l, end_l, symetricSize[0], symetricSize[1], model, origin, brushmask, capsule, &sphere); // if the bmodel was rotated and there was a collision - if ( rotated && trace->fraction != 1.0 ) { + if (rotated && trace->fraction != 1.0) { // rotation of bmodel collision plane TransposeMatrix(matrix, transpose); RotatePoint(trace->plane.normal, transpose); @@ -1572,24 +1451,19 @@ Returns true if culled out ================= */ -bool CM_CullBox(const cplane_t *frustum, const vec3_t transformed[8]) -{ - int i, j; - const cplane_t *frust; +bool CM_CullBox(const cplane_t *frustum, const vec3_t transformed[8]) { + int i, j; + const cplane_t *frust; // check against frustum planes - for (i=0, frust=frustum; i<4 ; i++, frust++) - { - for (j=0 ; j<8 ; j++) - { - if (DotProduct(transformed[j], frust->normal) > frust->dist) - { // a point is in front + for (i = 0, frust = frustum; i < 4; i++, frust++) { + for (j = 0; j < 8; j++) { + if (DotProduct(transformed[j], frust->normal) > frust->dist) { // a point is in front break; } } - if (j == 8) - { // all points were behind one of the planes + if (j == 8) { // all points were behind one of the planes return true; } } @@ -1604,17 +1478,15 @@ Returns true if culled out ================= */ -bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds) -{ - int i; - vec3_t transformed[8]; +bool CM_CullWorldBox(const cplane_t *frustum, const vec3pair_t bounds) { + int i; + vec3_t transformed[8]; - for (i = 0 ; i < 8 ; i++) - { + for (i = 0; i < 8; i++) { transformed[i][0] = bounds[i & 1][0]; transformed[i][1] = bounds[(i >> 1) & 1][1]; transformed[i][2] = bounds[(i >> 2) & 1][2]; } - return(CM_CullBox(frustum, transformed)); + return (CM_CullBox(frustum, transformed)); } diff --git a/codemp/qcommon/cmd.cpp b/codemp/qcommon/cmd.cpp index 102adf3139..ad65cb4320 100644 --- a/codemp/qcommon/cmd.cpp +++ b/codemp/qcommon/cmd.cpp @@ -29,18 +29,18 @@ along with this program; if not, see . #include #include -#define MAX_CMD_BUFFER 128*1024 -#define MAX_CMD_LINE 1024 +#define MAX_CMD_BUFFER 128 * 1024 +#define MAX_CMD_LINE 1024 typedef struct cmd_s { - byte *data; - int maxsize; - int cursize; + byte *data; + int maxsize; + int cursize; } cmd_t; -int cmd_wait; -cmd_t cmd_text; -byte cmd_text_buf[MAX_CMD_BUFFER]; +int cmd_wait; +cmd_t cmd_text; +byte cmd_text_buf[MAX_CMD_BUFFER]; //============================================================================= @@ -53,17 +53,16 @@ next frame. This allows commands like: bind g "cmd use rocket ; +attack ; wait ; -attack ; cmd use blaster" ============ */ -static void Cmd_Wait_f( void ) { - if ( Cmd_Argc() == 2 ) { - cmd_wait = atoi( Cmd_Argv( 1 ) ); - if ( cmd_wait < 0 ) +static void Cmd_Wait_f(void) { + if (Cmd_Argc() == 2) { + cmd_wait = atoi(Cmd_Argv(1)); + if (cmd_wait < 0) cmd_wait = 1; // ignore the argument } else { cmd_wait = 1; } } - /* ============================================================================= @@ -77,8 +76,7 @@ static void Cmd_Wait_f( void ) { Cbuf_Init ============ */ -void Cbuf_Init (void) -{ +void Cbuf_Init(void) { cmd_text.data = cmd_text_buf; cmd_text.maxsize = MAX_CMD_BUFFER; cmd_text.cursize = 0; @@ -91,21 +89,19 @@ Cbuf_AddText Adds command text at the end of the buffer, does NOT add a final \n ============ */ -void Cbuf_AddText( const char *text ) { - int l; +void Cbuf_AddText(const char *text) { + int l; - l = strlen (text); + l = strlen(text); - if (cmd_text.cursize + l >= cmd_text.maxsize) - { - Com_Printf ("Cbuf_AddText: overflow\n"); + if (cmd_text.cursize + l >= cmd_text.maxsize) { + Com_Printf("Cbuf_AddText: overflow\n"); return; } Com_Memcpy(&cmd_text.data[cmd_text.cursize], text, l); cmd_text.cursize += l; } - /* ============ Cbuf_InsertText @@ -114,57 +110,54 @@ Adds command text immediately after the current command Adds a \n to the text ============ */ -void Cbuf_InsertText( const char *text ) { - int len; - int i; +void Cbuf_InsertText(const char *text) { + int len; + int i; - len = strlen( text ) + 1; - if ( len + cmd_text.cursize > cmd_text.maxsize ) { - Com_Printf( "Cbuf_InsertText overflowed\n" ); + len = strlen(text) + 1; + if (len + cmd_text.cursize > cmd_text.maxsize) { + Com_Printf("Cbuf_InsertText overflowed\n"); return; } // move the existing command text - for ( i = cmd_text.cursize - 1 ; i >= 0 ; i-- ) { - cmd_text.data[ i + len ] = cmd_text.data[ i ]; + for (i = cmd_text.cursize - 1; i >= 0; i--) { + cmd_text.data[i + len] = cmd_text.data[i]; } // copy the new text in - Com_Memcpy( cmd_text.data, text, len - 1 ); + Com_Memcpy(cmd_text.data, text, len - 1); // add a \n - cmd_text.data[ len - 1 ] = '\n'; + cmd_text.data[len - 1] = '\n'; cmd_text.cursize += len; } - /* ============ Cbuf_ExecuteText ============ */ -void Cbuf_ExecuteText (int exec_when, const char *text) -{ - switch (exec_when) - { +void Cbuf_ExecuteText(int exec_when, const char *text) { + switch (exec_when) { case EXEC_NOW: if (text && strlen(text) > 0) { Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", text); - Cmd_ExecuteString (text); + Cmd_ExecuteString(text); } else { Cbuf_Execute(); Com_DPrintf(S_COLOR_YELLOW "EXEC_NOW %s\n", cmd_text.data); } break; case EXEC_INSERT: - Cbuf_InsertText (text); + Cbuf_InsertText(text); break; case EXEC_APPEND: - Cbuf_AddText (text); + Cbuf_AddText(text); break; default: - Com_Error (ERR_FATAL, "Cbuf_ExecuteText: bad exec_when"); + Com_Error(ERR_FATAL, "Cbuf_ExecuteText: bad exec_when"); } } @@ -173,12 +166,11 @@ void Cbuf_ExecuteText (int exec_when, const char *text) Cbuf_Execute ============ */ -void Cbuf_Execute (void) -{ - int i; - char *text; - char line[MAX_CMD_LINE]; - int quotes; +void Cbuf_Execute(void) { + int i; + char *text; + char line[MAX_CMD_LINE]; + int quotes; // This will keep // style comments all on one line by not breaking on // a semicolon. It will keep /* ... */ style comments all on one line by not @@ -186,9 +178,8 @@ void Cbuf_Execute (void) qboolean in_star_comment = qfalse; qboolean in_slash_comment = qfalse; - while (cmd_text.cursize) - { - if ( cmd_wait > 0 ) { + while (cmd_text.cursize) { + if (cmd_wait > 0) { // skip out while text still remains in buffer, leaving it // for next frame cmd_wait--; @@ -199,18 +190,17 @@ void Cbuf_Execute (void) text = (char *)cmd_text.data; quotes = 0; - for (i=0 ; i< cmd_text.cursize ; i++) - { + for (i = 0; i < cmd_text.cursize; i++) { if (text[i] == '"') quotes++; - if ( !(quotes&1)) { + if (!(quotes & 1)) { if (i < cmd_text.cursize - 1) { - if (! in_star_comment && text[i] == '/' && text[i+1] == '/') + if (!in_star_comment && text[i] == '/' && text[i + 1] == '/') in_slash_comment = qtrue; - else if (! in_slash_comment && text[i] == '/' && text[i+1] == '*') + else if (!in_slash_comment && text[i] == '/' && text[i + 1] == '*') in_star_comment = qtrue; - else if (in_star_comment && text[i] == '*' && text[i+1] == '/') { + else if (in_star_comment && text[i] == '*' && text[i + 1] == '/') { in_star_comment = qfalse; // If we are in a star comment, then the part after it is valid // Note: This will cause it to NUL out the terminating '/' @@ -219,42 +209,40 @@ void Cbuf_Execute (void) break; } } - if (! in_slash_comment && ! in_star_comment && text[i] == ';') + if (!in_slash_comment && !in_star_comment && text[i] == ';') break; } - if (! in_star_comment && (text[i] == '\n' || text[i] == '\r')) { + if (!in_star_comment && (text[i] == '\n' || text[i] == '\r')) { in_slash_comment = qfalse; break; } } - if( i >= (MAX_CMD_LINE - 1)) { + if (i >= (MAX_CMD_LINE - 1)) { i = MAX_CMD_LINE - 1; } - Com_Memcpy (line, text, i); + Com_Memcpy(line, text, i); line[i] = 0; -// delete the text from the command buffer and move remaining commands down -// this is necessary because commands (exec) can insert data at the -// beginning of the text buffer + // delete the text from the command buffer and move remaining commands down + // this is necessary because commands (exec) can insert data at the + // beginning of the text buffer if (i == cmd_text.cursize) cmd_text.cursize = 0; - else - { + else { i++; cmd_text.cursize -= i; - memmove (text, text+i, cmd_text.cursize); + memmove(text, text + i, cmd_text.cursize); } -// execute the command line + // execute the command line - Cmd_ExecuteString (line); + Cmd_ExecuteString(line); } } - /* ============================================================================== @@ -263,41 +251,38 @@ void Cbuf_Execute (void) ============================================================================== */ - /* =============== Cmd_Exec_f =============== */ -static void Cmd_Exec_f( void ) { +static void Cmd_Exec_f(void) { bool quiet; fileBuffer_t f; - char filename[MAX_QPATH]; + char filename[MAX_QPATH]; quiet = !Q_stricmp(Cmd_Argv(0), "execq"); - if (Cmd_Argc () != 2) { - Com_Printf ("exec%s : execute a script file%s\n", - quiet ? "q" : "", quiet ? " without notification" : ""); + if (Cmd_Argc() != 2) { + Com_Printf("exec%s : execute a script file%s\n", quiet ? "q" : "", quiet ? " without notification" : ""); return; } - Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); - FS_ReadFile( filename, &f.v); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".cfg"); + FS_ReadFile(filename, &f.v); if (!f.c) { - Com_Printf ("couldn't exec %s\n", filename); + Com_Printf("couldn't exec %s\n", filename); return; } if (!quiet) - Com_Printf ("execing %s\n", filename); + Com_Printf("execing %s\n", filename); - Cbuf_InsertText (f.c); + Cbuf_InsertText(f.c); - FS_FreeFile (f.v); + FS_FreeFile(f.v); } - /* =============== Cmd_Vstr_f @@ -305,19 +290,18 @@ Cmd_Vstr_f Inserts the current value of a variable as command text =============== */ -static void Cmd_Vstr_f( void ) { - char *v; +static void Cmd_Vstr_f(void) { + char *v; - if (Cmd_Argc () != 2) { - Com_Printf ("vstr : execute a variable command\n"); + if (Cmd_Argc() != 2) { + Com_Printf("vstr : execute a variable command\n"); return; } - v = Cvar_VariableString( Cmd_Argv( 1 ) ); - Cbuf_InsertText( va("%s\n", v ) ); + v = Cvar_VariableString(Cmd_Argv(1)); + Cbuf_InsertText(va("%s\n", v)); } - /* =============== Cmd_Echo_f @@ -325,11 +309,7 @@ Cmd_Echo_f Just prints the rest of the line to the console =============== */ -static void Cmd_Echo_f (void) -{ - Com_Printf ("%s\n", Cmd_Args()); -} - +static void Cmd_Echo_f(void) { Com_Printf("%s\n", Cmd_Args()); } /* ============================================================================= @@ -339,41 +319,35 @@ static void Cmd_Echo_f (void) ============================================================================= */ -typedef struct cmd_function_s -{ - struct cmd_function_s *next; - char *name; - char *description; - xcommand_t function; - completionFunc_t complete; +typedef struct cmd_function_s { + struct cmd_function_s *next; + char *name; + char *description; + xcommand_t function; + completionFunc_t complete; } cmd_function_t; +static int cmd_argc; +static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized +static char cmd_tokenized[BIG_INFO_STRING + MAX_STRING_TOKENS]; // will have 0 bytes inserted +static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing) - -static int cmd_argc; -static char *cmd_argv[MAX_STRING_TOKENS]; // points into cmd_tokenized -static char cmd_tokenized[BIG_INFO_STRING+MAX_STRING_TOKENS]; // will have 0 bytes inserted -static char cmd_cmd[BIG_INFO_STRING]; // the original command we received (no token processing) - -static cmd_function_t *cmd_functions; // possible commands to execute - +static cmd_function_t *cmd_functions; // possible commands to execute /* ============ Cmd_Argc ============ */ -int Cmd_Argc( void ) { - return cmd_argc; -} +int Cmd_Argc(void) { return cmd_argc; } /* ============ Cmd_Argv ============ */ -char *Cmd_Argv( int arg ) { - if ( (unsigned)arg >= (unsigned)cmd_argc ) +char *Cmd_Argv(int arg) { + if ((unsigned)arg >= (unsigned)cmd_argc) return ""; return cmd_argv[arg]; @@ -387,9 +361,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgvBuffer( int arg, char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_Argv( arg ), bufferLength ); -} +void Cmd_ArgvBuffer(int arg, char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_Argv(arg), bufferLength); } /* ============ @@ -398,17 +370,17 @@ Cmd_ArgsFrom Returns a single string containing argv(arg) to argv(argc()-1) ============ */ -char *Cmd_ArgsFrom( int arg ) { - static char cmd_args[BIG_INFO_STRING]; - int i; +char *Cmd_ArgsFrom(int arg) { + static char cmd_args[BIG_INFO_STRING]; + int i; cmd_args[0] = '\0'; if (arg < 0) arg = 0; - for ( i = arg ; i < cmd_argc ; i++ ) { - Q_strcat( cmd_args, sizeof( cmd_args ), cmd_argv[i] ); - if ( i != cmd_argc-1 ) { - Q_strcat( cmd_args, sizeof( cmd_args ), " " ); + for (i = arg; i < cmd_argc; i++) { + Q_strcat(cmd_args, sizeof(cmd_args), cmd_argv[i]); + if (i != cmd_argc - 1) { + Q_strcat(cmd_args, sizeof(cmd_args), " "); } } @@ -422,9 +394,7 @@ Cmd_Args Returns a single string containing argv(1) to argv(argc()-1) ============ */ -char *Cmd_Args( void ) { - return Cmd_ArgsFrom( 1 ); -} +char *Cmd_Args(void) { return Cmd_ArgsFrom(1); } /* ============ @@ -434,9 +404,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgsBuffer( char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_ArgsFrom( 1 ), bufferLength ); -} +void Cmd_ArgsBuffer(char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_ArgsFrom(1), bufferLength); } /* ============ @@ -446,9 +414,7 @@ The interpreted versions use this because they can't have pointers returned to them ============ */ -void Cmd_ArgsFromBuffer( int arg, char *buffer, int bufferLength ) { - Q_strncpyz( buffer, Cmd_ArgsFrom( arg ), bufferLength ); -} +void Cmd_ArgsFromBuffer(int arg, char *buffer, int bufferLength) { Q_strncpyz(buffer, Cmd_ArgsFrom(arg), bufferLength); } /* ============ @@ -459,10 +425,7 @@ For rcon use when you want to transmit without altering quoting https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543 ============ */ -char *Cmd_Cmd(void) -{ - return cmd_cmd; -} +char *Cmd_Cmd(void) { return cmd_cmd; } /* Replace command separators with space to prevent interpretation @@ -486,17 +449,15 @@ char *Cmd_Cmd(void) } }*/ -void Cmd_Args_Sanitize( size_t length, const char *strip, const char *repl ) -{ - for ( int i = 1; i < cmd_argc; i++ ) - { +void Cmd_Args_Sanitize(size_t length, const char *strip, const char *repl) { + for (int i = 1; i < cmd_argc; i++) { char *c = cmd_argv[i]; - if ( length > 0 && strlen( c ) >= length ) + if (length > 0 && strlen(c) >= length) c[length - 1] = '\0'; - if ( VALIDSTRING( strip ) && VALIDSTRING( repl ) ) - Q_strstrip( c, strip, repl ); + if (VALIDSTRING(strip) && VALIDSTRING(repl)) + Q_strstrip(c, strip, repl); } } @@ -512,72 +473,72 @@ will point into this temporary buffer. */ // NOTE TTimo define that to track tokenization issues //#define TKN_DBG -static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { - const char *text; - char *textOut; +static void Cmd_TokenizeString2(const char *text_in, qboolean ignoreQuotes) { + const char *text; + char *textOut; #ifdef TKN_DBG - // FIXME TTimo blunt hook to try to find the tokenization of userinfo - Com_DPrintf("Cmd_TokenizeString: %s\n", text_in); + // FIXME TTimo blunt hook to try to find the tokenization of userinfo + Com_DPrintf("Cmd_TokenizeString: %s\n", text_in); #endif // clear previous args cmd_argc = 0; - if ( !text_in ) { + if (!text_in) { return; } - Q_strncpyz( cmd_cmd, text_in, sizeof(cmd_cmd) ); + Q_strncpyz(cmd_cmd, text_in, sizeof(cmd_cmd)); text = text_in; textOut = cmd_tokenized; - while ( 1 ) { - if ( cmd_argc == MAX_STRING_TOKENS ) { - return; // this is usually something malicious + while (1) { + if (cmd_argc == MAX_STRING_TOKENS) { + return; // this is usually something malicious } - while ( 1 ) { + while (1) { // skip whitespace - while ( *text && *(const unsigned char* /*eurofix*/)text <= ' ' ) { + while (*text && *(const unsigned char * /*eurofix*/)text <= ' ') { text++; } - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } // skip // comments - if ( text[0] == '/' && text[1] == '/' ) { - return; // all tokens parsed + if (text[0] == '/' && text[1] == '/') { + return; // all tokens parsed } // skip /* */ comments - if ( text[0] == '/' && text[1] =='*' ) { - while ( *text && ( text[0] != '*' || text[1] != '/' ) ) { + if (text[0] == '/' && text[1] == '*') { + while (*text && (text[0] != '*' || text[1] != '/')) { text++; } - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } text += 2; } else { - break; // we are ready to parse a token + break; // we are ready to parse a token } } // handle quoted strings - // NOTE TTimo this doesn't handle \" escaping - if ( !ignoreQuotes && *text == '"' ) { + // NOTE TTimo this doesn't handle \" escaping + if (!ignoreQuotes && *text == '"') { cmd_argv[cmd_argc] = textOut; cmd_argc++; text++; - while ( *text && *text != '"' ) { + while (*text && *text != '"') { *textOut++ = *text++; } *textOut++ = 0; - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } text++; continue; @@ -588,17 +549,17 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { cmd_argc++; // skip until whitespace, quote, or command - while ( *(const unsigned char* /*eurofix*/)text > ' ' ) { - if ( !ignoreQuotes && text[0] == '"' ) { + while (*(const unsigned char * /*eurofix*/)text > ' ') { + if (!ignoreQuotes && text[0] == '"') { break; } - if ( text[0] == '/' && text[1] == '/' ) { + if (text[0] == '/' && text[1] == '/') { break; } // skip /* */ comments - if ( text[0] == '/' && text[1] =='*' ) { + if (text[0] == '/' && text[1] == '*') { break; } @@ -607,11 +568,10 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { *textOut++ = 0; - if ( !*text ) { - return; // all tokens parsed + if (!*text) { + return; // all tokens parsed } } - } /* @@ -619,29 +579,24 @@ static void Cmd_TokenizeString2( const char *text_in, qboolean ignoreQuotes ) { Cmd_TokenizeString ============ */ -void Cmd_TokenizeString( const char *text_in ) { - Cmd_TokenizeString2( text_in, qfalse ); -} +void Cmd_TokenizeString(const char *text_in) { Cmd_TokenizeString2(text_in, qfalse); } /* ============ Cmd_TokenizeStringIgnoreQuotes ============ */ -void Cmd_TokenizeStringIgnoreQuotes( const char *text_in ) { - Cmd_TokenizeString2( text_in, qtrue ); -} +void Cmd_TokenizeStringIgnoreQuotes(const char *text_in) { Cmd_TokenizeString2(text_in, qtrue); } /* ============ Cmd_FindCommand ============ */ -cmd_function_t *Cmd_FindCommand( const char *cmd_name ) -{ +cmd_function_t *Cmd_FindCommand(const char *cmd_name) { cmd_function_t *cmd; - for( cmd = cmd_functions; cmd; cmd = cmd->next ) - if( !Q_stricmp( cmd_name, cmd->name ) ) + for (cmd = cmd_functions; cmd; cmd = cmd->next) + if (!Q_stricmp(cmd_name, cmd->name)) return cmd; return NULL; } @@ -651,24 +606,23 @@ cmd_function_t *Cmd_FindCommand( const char *cmd_name ) Cmd_AddCommand ============ */ -void Cmd_AddCommand( const char *cmd_name, xcommand_t function, const char *cmd_desc ) { - cmd_function_t *cmd; +void Cmd_AddCommand(const char *cmd_name, xcommand_t function, const char *cmd_desc) { + cmd_function_t *cmd; // fail if the command already exists - if( Cmd_FindCommand( cmd_name ) ) - { + if (Cmd_FindCommand(cmd_name)) { // allow completion-only commands to be silently doubled - if ( function != NULL ) { - Com_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name); + if (function != NULL) { + Com_Printf("Cmd_AddCommand: %s already defined\n", cmd_name); } return; } // use a small malloc to avoid zone fragmentation - cmd = (struct cmd_function_s *)S_Malloc (sizeof(cmd_function_t)); - cmd->name = CopyString( cmd_name ); - if ( VALIDSTRING( cmd_desc ) ) - cmd->description = CopyString( cmd_desc ); + cmd = (struct cmd_function_s *)S_Malloc(sizeof(cmd_function_t)); + cmd->name = CopyString(cmd_name); + if (VALIDSTRING(cmd_desc)) + cmd->description = CopyString(cmd_desc); else cmd->description = NULL; cmd->function = function; @@ -677,21 +631,17 @@ void Cmd_AddCommand( const char *cmd_name, xcommand_t function, const char *cmd_ cmd_functions = cmd; } -void Cmd_AddCommandList( const cmdList_t *cmdList ) -{ - for ( const cmdList_t *cmd = cmdList; cmd && cmd->name; cmd++ ) - { - Cmd_AddCommand( cmd->name, cmd->func, cmd->description ); - if ( cmd->complete ) - Cmd_SetCommandCompletionFunc( cmd->name, cmd->complete ); +void Cmd_AddCommandList(const cmdList_t *cmdList) { + for (const cmdList_t *cmd = cmdList; cmd && cmd->name; cmd++) { + Cmd_AddCommand(cmd->name, cmd->func, cmd->description); + if (cmd->complete) + Cmd_SetCommandCompletionFunc(cmd->name, cmd->complete); } } -void Cmd_RemoveCommandList( const cmdList_t *cmdList ) -{ - for ( const cmdList_t *cmd = cmdList; cmd && cmd->name; cmd++ ) - { - Cmd_RemoveCommand( cmd->name ); +void Cmd_RemoveCommandList(const cmdList_t *cmdList) { + for (const cmdList_t *cmd = cmdList; cmd && cmd->name; cmd++) { + Cmd_RemoveCommand(cmd->name); } } @@ -700,9 +650,9 @@ void Cmd_RemoveCommandList( const cmdList_t *cmdList ) Cmd_SetCommandCompletionFunc ============ */ -void Cmd_SetCommandCompletionFunc( const char *command, completionFunc_t complete ) { - for ( cmd_function_t *cmd=cmd_functions; cmd; cmd=cmd->next ) { - if ( !Q_stricmp( command, cmd->name ) ) +void Cmd_SetCommandCompletionFunc(const char *command, completionFunc_t complete) { + for (cmd_function_t *cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!Q_stricmp(command, cmd->name)) cmd->complete = complete; } } @@ -712,21 +662,21 @@ void Cmd_SetCommandCompletionFunc( const char *command, completionFunc_t complet Cmd_RemoveCommand ============ */ -void Cmd_RemoveCommand( const char *cmd_name ) { - cmd_function_t *cmd, **back; +void Cmd_RemoveCommand(const char *cmd_name) { + cmd_function_t *cmd, **back; back = &cmd_functions; - while( 1 ) { + while (1) { cmd = *back; - if ( !cmd ) { + if (!cmd) { // command wasn't active return; } - if ( !strcmp( cmd_name, cmd->name ) ) { + if (!strcmp(cmd_name, cmd->name)) { *back = cmd->next; Z_Free(cmd->name); Z_Free(cmd->description); - Z_Free (cmd); + Z_Free(cmd); return; } back = &cmd->next; @@ -740,19 +690,18 @@ Cmd_VM_RemoveCommand Only remove commands with no associated function ============ */ -void Cmd_VM_RemoveCommand( const char *cmd_name, vmSlots_t vmslot ) { - cmd_function_t *cmd = Cmd_FindCommand( cmd_name ); +void Cmd_VM_RemoveCommand(const char *cmd_name, vmSlots_t vmslot) { + cmd_function_t *cmd = Cmd_FindCommand(cmd_name); - if( !cmd ) + if (!cmd) return; - if( cmd->function ) - { - Com_Printf( "%s tried to remove system command \"%s\"", vmStrs[vmslot], cmd_name ); + if (cmd->function) { + Com_Printf("%s tried to remove system command \"%s\"", vmStrs[vmslot], cmd_name); return; } - Cmd_RemoveCommand( cmd_name ); + Cmd_RemoveCommand(cmd_name); } /* @@ -760,11 +709,10 @@ void Cmd_VM_RemoveCommand( const char *cmd_name, vmSlots_t vmslot ) { Cmd_DescriptionString ============ */ -char *Cmd_DescriptionString( const char *cmd_name ) -{ - const cmd_function_t *cmd = Cmd_FindCommand( cmd_name ); +char *Cmd_DescriptionString(const char *cmd_name) { + const cmd_function_t *cmd = Cmd_FindCommand(cmd_name); - if ( !cmd || !VALIDSTRING( cmd->description ) ) + if (!cmd || !VALIDSTRING(cmd->description)) return ""; return cmd->description; } @@ -775,16 +723,14 @@ Cmd_Print ============ */ -void Cmd_Print( const cmd_function_t *cmd ) -{ - Com_Printf( S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s", cmd->name ); +void Cmd_Print(const cmd_function_t *cmd) { + Com_Printf(S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s", cmd->name); - if ( VALIDSTRING( cmd->description ) ) - { - Com_Printf( S_COLOR_GREEN " - %s" S_COLOR_WHITE, cmd->description ); + if (VALIDSTRING(cmd->description)) { + Com_Printf(S_COLOR_GREEN " - %s" S_COLOR_WHITE, cmd->description); } - Com_Printf( "\n" ); + Com_Printf("\n"); } /* @@ -792,11 +738,11 @@ void Cmd_Print( const cmd_function_t *cmd ) Cmd_CommandCompletion ============ */ -void Cmd_CommandCompletion( callbackFunc_t callback ) { - cmd_function_t *cmd; +void Cmd_CommandCompletion(callbackFunc_t callback) { + cmd_function_t *cmd; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) { - callback( cmd->name ); + for (cmd = cmd_functions; cmd; cmd = cmd->next) { + callback(cmd->name); } } @@ -805,10 +751,10 @@ void Cmd_CommandCompletion( callbackFunc_t callback ) { Cmd_CompleteArgument ============ */ -void Cmd_CompleteArgument( const char *command, char *args, int argNum ) { - for ( cmd_function_t *cmd=cmd_functions; cmd; cmd=cmd->next ) { - if ( !Q_stricmp( command, cmd->name ) && cmd->complete ) - cmd->complete( args, argNum ); +void Cmd_CompleteArgument(const char *command, char *args, int argNum) { + for (cmd_function_t *cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!Q_stricmp(command, cmd->name) && cmd->complete) + cmd->complete(args, argNum); } } @@ -819,19 +765,19 @@ Cmd_ExecuteString A complete command line has been parsed, so try to execute it ============ */ -void Cmd_ExecuteString( const char *text ) { - cmd_function_t *cmd, **prev; +void Cmd_ExecuteString(const char *text) { + cmd_function_t *cmd, **prev; // execute the command line - Cmd_TokenizeString( text ); - if ( !Cmd_Argc() ) { - return; // no tokens + Cmd_TokenizeString(text); + if (!Cmd_Argc()) { + return; // no tokens } // check registered command functions - for ( prev = &cmd_functions ; *prev ; prev = &cmd->next ) { + for (prev = &cmd_functions; *prev; prev = &cmd->next) { cmd = *prev; - if ( !Q_stricmp( Cmd_Argv(0), cmd->name ) ) { + if (!Q_stricmp(Cmd_Argv(0), cmd->name)) { // rearrange the links so that the command will be // near the head of the list next time it is used *prev = cmd->next; @@ -839,111 +785,99 @@ void Cmd_ExecuteString( const char *text ) { cmd_functions = cmd; // perform the action - if ( !cmd->function ) { + if (!cmd->function) { // let the cgame or game handle it break; } else { - cmd->function (); + cmd->function(); } return; } } // check cvars - if ( Cvar_Command() ) { + if (Cvar_Command()) { return; } // check client game commands - if ( com_cl_running && com_cl_running->integer && CL_GameCommand() ) { + if (com_cl_running && com_cl_running->integer && CL_GameCommand()) { return; } // check server game commands - if ( com_sv_running && com_sv_running->integer && SV_GameCommand() ) { + if (com_sv_running && com_sv_running->integer && SV_GameCommand()) { return; } // check ui commands - if ( com_cl_running && com_cl_running->integer && UI_GameCommand() ) { + if (com_cl_running && com_cl_running->integer && UI_GameCommand()) { return; } // send it as a server command if we are connected // this will usually result in a chat message - //CL_ForwardCommandToServer ( text ); - CL_ForwardCommandToServer ( text ); + // CL_ForwardCommandToServer ( text ); + CL_ForwardCommandToServer(text); } typedef std::vector CmdFuncVector; -bool CmdSort( const cmd_function_t *cmd1, const cmd_function_t *cmd2 ) -{ - return Q_stricmp( cmd1->name, cmd2->name ) < 0; -} +bool CmdSort(const cmd_function_t *cmd1, const cmd_function_t *cmd2) { return Q_stricmp(cmd1->name, cmd2->name) < 0; } /* ============ Cmd_List_f ============ */ -static void Cmd_List_f (void) -{ - const cmd_function_t *cmd = NULL; - int i, j; - char *match = NULL; - CmdFuncVector cmds; +static void Cmd_List_f(void) { + const cmd_function_t *cmd = NULL; + int i, j; + char *match = NULL; + CmdFuncVector cmds; - if ( Cmd_Argc() > 1 ) { - match = Cmd_Argv( 1 ); + if (Cmd_Argc() > 1) { + match = Cmd_Argv(1); } - for ( cmd=cmd_functions, i=0, j=0; - cmd; - cmd=cmd->next, i++ ) - { - if ( !cmd->name || (match && !Com_Filter( match, cmd->name, qfalse )) ) + for (cmd = cmd_functions, i = 0, j = 0; cmd; cmd = cmd->next, i++) { + if (!cmd->name || (match && !Com_Filter(match, cmd->name, qfalse))) continue; - cmds.push_back( cmd ); + cmds.push_back(cmd); j++; } // sort list alphabetically - std::sort( cmds.begin(), cmds.end(), CmdSort ); + std::sort(cmds.begin(), cmds.end(), CmdSort); CmdFuncVector::const_iterator itr; - for ( itr = cmds.begin(); - itr != cmds.end(); - ++itr ) - { + for (itr = cmds.begin(); itr != cmds.end(); ++itr) { cmd = (*itr); - if ( VALIDSTRING( cmd->description ) ) - Com_Printf( " %s" S_COLOR_GREEN " - %s" S_COLOR_WHITE "\n", cmd->name, cmd->description ); + if (VALIDSTRING(cmd->description)) + Com_Printf(" %s" S_COLOR_GREEN " - %s" S_COLOR_WHITE "\n", cmd->name, cmd->description); else - Com_Printf( " %s\n", cmd->name ); + Com_Printf(" %s\n", cmd->name); } - Com_Printf ("\n%i total commands\n", i); - if ( i != j ) - Com_Printf( "%i matching commands\n", j ); + Com_Printf("\n%i total commands\n", i); + if (i != j) + Com_Printf("%i matching commands\n", j); } -static void Cmd_PrintHelp_f( void ) -{ - if ( Cmd_Argc() != 2 ) - { - Com_Printf( "usage: help \n" ); +static void Cmd_PrintHelp_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf("usage: help \n"); return; } - const char *name = Cmd_Argv( 1 ); - const cmd_function_t *cmd = Cmd_FindCommand( name ); + const char *name = Cmd_Argv(1); + const cmd_function_t *cmd = Cmd_FindCommand(name); - if ( cmd ) - Cmd_Print( cmd ); + if (cmd) + Cmd_Print(cmd); else - Com_Printf( "Command %s does not exist.\n", name ); + Com_Printf("Command %s does not exist.\n", name); } /* @@ -951,15 +885,13 @@ static void Cmd_PrintHelp_f( void ) Cmd_CompleteCmdName ================== */ -void Cmd_CompleteCmdName( char *args, int argNum ) -{ - if ( argNum == 2 ) - { +void Cmd_CompleteCmdName(char *args, int argNum) { + if (argNum == 2) { // Skip " " - char *p = Com_SkipTokens( args, 1, " " ); + char *p = Com_SkipTokens(args, 1, " "); - if ( p > args ) - Field_CompleteCommand( p, qtrue, qfalse ); + if (p > args) + Field_CompleteCommand(p, qtrue, qfalse); } } @@ -968,9 +900,9 @@ void Cmd_CompleteCmdName( char *args, int argNum ) Cmd_CompleteCfgName ================== */ -void Cmd_CompleteCfgName( char *args, int argNum ) { - if( argNum == 2 ) { - Field_CompleteFilename( "", "cfg", qfalse, qtrue ); +void Cmd_CompleteCfgName(char *args, int argNum) { + if (argNum == 2) { + Field_CompleteFilename("", "cfg", qfalse, qtrue); } } @@ -979,17 +911,16 @@ void Cmd_CompleteCfgName( char *args, int argNum ) { Cmd_Init ============ */ -void Cmd_Init (void) { - Cmd_AddCommand( "cmdlist", Cmd_List_f, "List all commands to console" ); - Cmd_AddCommand( "help", Cmd_PrintHelp_f, "Print command help" ); - Cmd_SetCommandCompletionFunc( "help", Cmd_CompleteCmdName ); - Cmd_AddCommand( "echo", Cmd_Echo_f, "Print message to console" ); - Cmd_AddCommand( "exec", Cmd_Exec_f, "Execute a script file" ); - Cmd_AddCommand( "execq", Cmd_Exec_f, "Execute a script file without displaying a message" ); - Cmd_SetCommandCompletionFunc( "exec", Cmd_CompleteCfgName ); - Cmd_SetCommandCompletionFunc( "execq", Cmd_CompleteCfgName ); - Cmd_AddCommand( "vstr", Cmd_Vstr_f, "Execute the value of a cvar" ); - Cmd_SetCommandCompletionFunc( "vstr", Cvar_CompleteCvarName ); - Cmd_AddCommand( "wait", Cmd_Wait_f, "Pause command buffer execution" ); +void Cmd_Init(void) { + Cmd_AddCommand("cmdlist", Cmd_List_f, "List all commands to console"); + Cmd_AddCommand("help", Cmd_PrintHelp_f, "Print command help"); + Cmd_SetCommandCompletionFunc("help", Cmd_CompleteCmdName); + Cmd_AddCommand("echo", Cmd_Echo_f, "Print message to console"); + Cmd_AddCommand("exec", Cmd_Exec_f, "Execute a script file"); + Cmd_AddCommand("execq", Cmd_Exec_f, "Execute a script file without displaying a message"); + Cmd_SetCommandCompletionFunc("exec", Cmd_CompleteCfgName); + Cmd_SetCommandCompletionFunc("execq", Cmd_CompleteCfgName); + Cmd_AddCommand("vstr", Cmd_Vstr_f, "Execute the value of a cvar"); + Cmd_SetCommandCompletionFunc("vstr", Cvar_CompleteCvarName); + Cmd_AddCommand("wait", Cmd_Wait_f, "Pause command buffer execution"); } - diff --git a/codemp/qcommon/common.cpp b/codemp/qcommon/common.cpp index 69061d16de..9c8f8d892f 100644 --- a/codemp/qcommon/common.cpp +++ b/codemp/qcommon/common.cpp @@ -37,66 +37,65 @@ along with this program; if not, see . FILE *debuglogfile; fileHandle_t logfile; -fileHandle_t com_journalFile; // events are written here -fileHandle_t com_journalDataFile; // config files are written here - -cvar_t *com_speeds; -cvar_t *com_developer; -cvar_t *com_dedicated; -cvar_t *com_timescale; -cvar_t *com_fixedtime; -cvar_t *com_journal; -cvar_t *com_timedemo; -cvar_t *com_sv_running; -cvar_t *com_cl_running; -cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print -cvar_t *com_showtrace; - -cvar_t *com_optvehtrace; +fileHandle_t com_journalFile; // events are written here +fileHandle_t com_journalDataFile; // config files are written here + +cvar_t *com_speeds; +cvar_t *com_developer; +cvar_t *com_dedicated; +cvar_t *com_timescale; +cvar_t *com_fixedtime; +cvar_t *com_journal; +cvar_t *com_timedemo; +cvar_t *com_sv_running; +cvar_t *com_cl_running; +cvar_t *com_logfile; // 1 = buffer log, 2 = flush after each print +cvar_t *com_showtrace; + +cvar_t *com_optvehtrace; #ifdef G2_PERFORMANCE_ANALYSIS -cvar_t *com_G2Report; +cvar_t *com_G2Report; #endif -cvar_t *com_version; -cvar_t *com_buildScript; // for automated data building scripts -cvar_t *com_bootlogo; -cvar_t *cl_paused; -cvar_t *sv_paused; -cvar_t *com_cameraMode; -cvar_t *com_homepath; +cvar_t *com_version; +cvar_t *com_buildScript; // for automated data building scripts +cvar_t *com_bootlogo; +cvar_t *cl_paused; +cvar_t *sv_paused; +cvar_t *com_cameraMode; +cvar_t *com_homepath; #ifndef _WIN32 -cvar_t *com_ansiColor = NULL; +cvar_t *com_ansiColor = NULL; #endif -cvar_t *com_busyWait; +cvar_t *com_busyWait; cvar_t *com_affinity; -cvar_t *com_timestamps; +cvar_t *com_timestamps; // com_speeds times -int time_game; -int time_frontend; // renderer frontend time -int time_backend; // renderer backend time +int time_game; +int time_frontend; // renderer frontend time +int time_backend; // renderer backend time -int com_frameTime; -int com_frameNumber; +int com_frameTime; +int com_frameNumber; -qboolean com_errorEntered = qfalse; -qboolean com_fullyInitialized = qfalse; +qboolean com_errorEntered = qfalse; +qboolean com_fullyInitialized = qfalse; -char com_errorMessage[MAXPRINTMSG] = {0}; +char com_errorMessage[MAXPRINTMSG] = {0}; -void Com_WriteConfig_f( void ); +void Com_WriteConfig_f(void); //============================================================================ -static char *rd_buffer; -static int rd_buffersize; -static void (*rd_flush)( char *buffer ); +static char *rd_buffer; +static int rd_buffersize; +static void (*rd_flush)(char *buffer); -void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) ) -{ +void Com_BeginRedirect(char *buffer, int buffersize, void (*flush)(char *)) { if (!buffer || !buffersize || !flush) return; rd_buffer = buffer; @@ -106,9 +105,8 @@ void Com_BeginRedirect (char *buffer, int buffersize, void (*flush)( char *) ) *rd_buffer = 0; } -void Com_EndRedirect (void) -{ - if ( rd_flush ) { +void Com_EndRedirect(void) { + if (rd_flush) { rd_flush(rd_buffer); } @@ -127,43 +125,43 @@ to the appropriate place. A raw string should NEVER be passed as fmt, because of "%f" type crashers. ============= */ -void QDECL Com_Printf( const char *fmt, ... ) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL Com_Printf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; static qboolean opening_qconsole = qfalse; const char *p; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - if ( rd_buffer ) { - if ((strlen (msg) + strlen(rd_buffer)) > (size_t)(rd_buffersize - 1)) { + if (rd_buffer) { + if ((strlen(msg) + strlen(rd_buffer)) > (size_t)(rd_buffersize - 1)) { rd_flush(rd_buffer); *rd_buffer = 0; } Q_strcat(rd_buffer, rd_buffersize, msg); - // TTimo nooo .. that would defeat the purpose - //rd_flush(rd_buffer); + // TTimo nooo .. that would defeat the purpose + // rd_flush(rd_buffer); //*rd_buffer = 0; return; } #ifndef DEDICATED - CL_ConsolePrint( msg ); + CL_ConsolePrint(msg); #endif p = msg; while (*p) { - static qboolean newLine = qtrue; - char line[MAXPRINTMSG]; - size_t lineLen; + static qboolean newLine = qtrue; + char line[MAXPRINTMSG]; + size_t lineLen; if (newLine && com_timestamps && com_timestamps->integer) { - time_t t = time( NULL ); - struct tm *tms = localtime( &t ); - Com_sprintf(line, sizeof(line), "%04i-%02i-%02i %02i:%02i:%02i ", - 1900 + tms->tm_year, 1 + tms->tm_mon, tms->tm_mday, tms->tm_hour, tms->tm_min, tms->tm_sec); + time_t t = time(NULL); + struct tm *tms = localtime(&t); + Com_sprintf(line, sizeof(line), "%04i-%02i-%02i %02i:%02i:%02i ", 1900 + tms->tm_year, 1 + tms->tm_mon, tms->tm_mday, tms->tm_hour, tms->tm_min, + tms->tm_sec); lineLen = strlen(line); newLine = qfalse; } else { @@ -180,54 +178,50 @@ void QDECL Com_Printf( const char *fmt, ... ) { } // echo to dedicated console and early console - Sys_Print( line ); + Sys_Print(line); // logfile - if ( com_logfile && com_logfile->integer ) { - // TTimo: only open the qconsole.log if the filesystem is in an initialized state - // also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on) - if ( !logfile && FS_Initialized() && !opening_qconsole ) { + if (com_logfile && com_logfile->integer) { + // TTimo: only open the qconsole.log if the filesystem is in an initialized state + // also, avoid recursing in the qconsole.log opening (i.e. if fs_debug is on) + if (!logfile && FS_Initialized() && !opening_qconsole) { struct tm *newtime; time_t aclock; opening_qconsole = qtrue; - time( &aclock ); - newtime = localtime( &aclock ); + time(&aclock); + newtime = localtime(&aclock); - logfile = FS_FOpenFileWrite( "qconsole.log" ); + logfile = FS_FOpenFileWrite("qconsole.log"); - if ( logfile ) { - Com_Printf( "logfile opened on %s\n", asctime( newtime ) ); - if ( com_logfile->integer > 1 ) { + if (logfile) { + Com_Printf("logfile opened on %s\n", asctime(newtime)); + if (com_logfile->integer > 1) { // force it to not buffer so we get valid // data even if we are crashing FS_ForceFlush(logfile); } - } - else { - Com_Printf( "Opening qconsole.log failed!\n" ); - Cvar_SetValue( "logfile", 0 ); + } else { + Com_Printf("Opening qconsole.log failed!\n"); + Cvar_SetValue("logfile", 0); } } opening_qconsole = qfalse; - if ( logfile && FS_Initialized()) { + if (logfile && FS_Initialized()) { FS_Write(line, strlen(line), logfile); } } } - #if defined(_WIN32) && defined(_DEBUG) - if ( *msg ) - { - OutputDebugString ( Q_CleanStr(msg) ); - OutputDebugString ("\n"); + if (*msg) { + OutputDebugString(Q_CleanStr(msg)); + OutputDebugString("\n"); } #endif } - /* ================ Com_DPrintf @@ -235,30 +229,29 @@ Com_DPrintf A Com_Printf that only shows up if the "developer" cvar is set ================ */ -void QDECL Com_DPrintf( const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL Com_DPrintf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - if ( !com_developer || !com_developer->integer ) { - return; // don't confuse non-developers with techie stuff... + if (!com_developer || !com_developer->integer) { + return; // don't confuse non-developers with techie stuff... } - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); - Com_Printf ("%s", msg); + Com_Printf("%s", msg); } // Outputs to the VC / Windows Debug window (only in debug compile) -void QDECL Com_OPrintf( const char *fmt, ...) -{ - va_list argptr; - char msg[MAXPRINTMSG]; - - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); +void QDECL Com_OPrintf(const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; + + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); #ifdef _WIN32 OutputDebugString(msg); #else @@ -274,34 +267,34 @@ Both client and server can use this, and it will do the appropriate things. ============= */ -void NORETURN QDECL Com_Error( int code, const char *fmt, ... ) { - va_list argptr; - static int lastErrorTime; - static int errorCount; - int currentTime; +void NORETURN QDECL Com_Error(int code, const char *fmt, ...) { + va_list argptr; + static int lastErrorTime; + static int errorCount; + int currentTime; - if ( com_errorEntered ) { - Sys_Error( "recursive error after: %s", com_errorMessage ); + if (com_errorEntered) { + Sys_Error("recursive error after: %s", com_errorMessage); } com_errorEntered = qtrue; // when we are running automated scripts, make sure we // know if anything failed - if ( com_buildScript && com_buildScript->integer ) { + if (com_buildScript && com_buildScript->integer) { code = ERR_FATAL; } // ERR_DROPs on dedicated drop to an interactive console // which doesn't make sense for dedicated as it's generally // run unattended - if ( com_dedicated && com_dedicated->integer ) { + if (com_dedicated && com_dedicated->integer) { code = ERR_FATAL; } // if we are getting a solid stream of ERR_DROP, do an ERR_FATAL currentTime = Sys_Milliseconds(); - if ( currentTime - lastErrorTime < 100 ) { - if ( ++errorCount > 3 ) { + if (currentTime - lastErrorTime < 100) { + if (++errorCount > 3) { code = ERR_FATAL; } } else { @@ -309,28 +302,27 @@ void NORETURN QDECL Com_Error( int code, const char *fmt, ... ) { } lastErrorTime = currentTime; - va_start (argptr,fmt); - Q_vsnprintf (com_errorMessage,sizeof(com_errorMessage), fmt,argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(com_errorMessage, sizeof(com_errorMessage), fmt, argptr); + va_end(argptr); - if ( code != ERR_DISCONNECT && code != ERR_NEED_CD ) { - Cvar_Get("com_errorMessage", "", CVAR_ROM); //give com_errorMessage a default so it won't come back to life after a resetDefaults + if (code != ERR_DISCONNECT && code != ERR_NEED_CD) { + Cvar_Get("com_errorMessage", "", CVAR_ROM); // give com_errorMessage a default so it won't come back to life after a resetDefaults Cvar_Set("com_errorMessage", com_errorMessage); } - if ( code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT || code == ERR_DROP || code == ERR_NEED_CD ) { + if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT || code == ERR_DROP || code == ERR_NEED_CD) { throw code; } else { - CL_Shutdown (); - SV_Shutdown (va("Server fatal crashed: %s\n", com_errorMessage)); + CL_Shutdown(); + SV_Shutdown(va("Server fatal crashed: %s\n", com_errorMessage)); } - Com_Shutdown (); + Com_Shutdown(); - Sys_Error ("%s", com_errorMessage); + Sys_Error("%s", com_errorMessage); } - /* ============= Com_Quit_f @@ -339,19 +331,17 @@ Both client and server can use this, and it will do the appropriate things. ============= */ -void Com_Quit_f( void ) { +void Com_Quit_f(void) { // don't try to shutdown if we are in a recursive error - if ( !com_errorEntered ) { - SV_Shutdown ("Server quit\n"); - CL_Shutdown (); - Com_Shutdown (); + if (!com_errorEntered) { + SV_Shutdown("Server quit\n"); + CL_Shutdown(); + Com_Shutdown(); FS_Shutdown(qtrue); } - Sys_Quit (); + Sys_Quit(); } - - /* ============================================================================ @@ -369,9 +359,9 @@ quake3 set test blah + map test ============================================================================ */ -#define MAX_CONSOLE_LINES 32 -int com_numConsoleLines; -char *com_consoleLines[MAX_CONSOLE_LINES]; +#define MAX_CONSOLE_LINES 32 +int com_numConsoleLines; +char *com_consoleLines[MAX_CONSOLE_LINES]; /* ================== @@ -380,19 +370,19 @@ Com_ParseCommandLine Break it up into multiple console lines ================== */ -void Com_ParseCommandLine( char *commandLine ) { +void Com_ParseCommandLine(char *commandLine) { int inq = 0; com_consoleLines[0] = commandLine; com_numConsoleLines = 1; - while ( *commandLine ) { + while (*commandLine) { if (*commandLine == '"') { inq = !inq; } // look for a + seperating character // if commandLine came from a file, we might have real line seperators - if ( (*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r' ) { - if ( com_numConsoleLines == MAX_CONSOLE_LINES ) { + if ((*commandLine == '+' && !inq) || *commandLine == '\n' || *commandLine == '\r') { + if (com_numConsoleLines == MAX_CONSOLE_LINES) { return; } com_consoleLines[com_numConsoleLines] = commandLine + 1; @@ -403,7 +393,6 @@ void Com_ParseCommandLine( char *commandLine ) { } } - /* =================== Com_SafeMode @@ -412,13 +401,12 @@ Check for "safe" on the command line, which will skip loading of jampconfig.cfg =================== */ -qboolean Com_SafeMode( void ) { - int i; +qboolean Com_SafeMode(void) { + int i; - for ( i = 0 ; i < com_numConsoleLines ; i++ ) { - Cmd_TokenizeString( com_consoleLines[i] ); - if ( !Q_stricmp( Cmd_Argv(0), "safe" ) - || !Q_stricmp( Cmd_Argv(0), "cvar_restart" ) ) { + for (i = 0; i < com_numConsoleLines; i++) { + Cmd_TokenizeString(com_consoleLines[i]); + if (!Q_stricmp(Cmd_Argv(0), "safe") || !Q_stricmp(Cmd_Argv(0), "cvar_restart")) { com_consoleLines[i][0] = 0; return qtrue; } @@ -426,7 +414,6 @@ qboolean Com_SafeMode( void ) { return qfalse; } - /* =============== Com_StartupVariable @@ -438,21 +425,20 @@ before the filesystem is started, but all other sets shouls be after execing the config and default. =============== */ -void Com_StartupVariable( const char *match ) { - for (int i=0 ; i < com_numConsoleLines ; i++) { - Cmd_TokenizeString( com_consoleLines[i] ); - if ( strcmp( Cmd_Argv(0), "set" ) ) { +void Com_StartupVariable(const char *match) { + for (int i = 0; i < com_numConsoleLines; i++) { + Cmd_TokenizeString(com_consoleLines[i]); + if (strcmp(Cmd_Argv(0), "set")) { continue; } char *s = Cmd_Argv(1); - if ( !match || !strcmp( s, match ) ) - Cvar_User_Set( s, Cmd_ArgsFrom( 2 ) ); + if (!match || !strcmp(s, match)) + Cvar_User_Set(s, Cmd_ArgsFrom(2)); } } - /* ================= Com_AddStartupCommands @@ -464,58 +450,53 @@ Returns qtrue if any late commands were added, which will keep the demoloop from immediately starting ================= */ -qboolean Com_AddStartupCommands( void ) { - int i; - qboolean added; +qboolean Com_AddStartupCommands(void) { + int i; + qboolean added; added = qfalse; // quote every token, so args with semicolons can work - for (i=0 ; i < com_numConsoleLines ; i++) { - if ( !com_consoleLines[i] || !com_consoleLines[i][0] ) { + for (i = 0; i < com_numConsoleLines; i++) { + if (!com_consoleLines[i] || !com_consoleLines[i][0]) { continue; } // set commands won't override menu startup - if ( Q_stricmpn( com_consoleLines[i], "set", 3 ) ) { + if (Q_stricmpn(com_consoleLines[i], "set", 3)) { added = qtrue; } - Cbuf_AddText( com_consoleLines[i] ); - Cbuf_AddText( "\n" ); + Cbuf_AddText(com_consoleLines[i]); + Cbuf_AddText("\n"); } return added; } - //============================================================================ -void Info_Print( const char *s ) { - char key[BIG_INFO_KEY]; - char value[BIG_INFO_VALUE]; - char *o; - int l; +void Info_Print(const char *s) { + char key[BIG_INFO_KEY]; + char value[BIG_INFO_VALUE]; + char *o; + int l; if (*s == '\\') s++; - while (*s) - { + while (*s) { o = key; while (*s && *s != '\\') *o++ = *s++; l = o - key; - if (l < 20) - { - Com_Memset (o, ' ', 20-l); + if (l < 20) { + Com_Memset(o, ' ', 20 - l); key[20] = 0; - } - else + } else *o = 0; - Com_Printf ("%s ", key); + Com_Printf("%s ", key); - if (!*s) - { - Com_Printf ("MISSING VALUE\n"); + if (!*s) { + Com_Printf("MISSING VALUE\n"); return; } @@ -527,7 +508,7 @@ void Info_Print( const char *s ) { if (*s) s++; - Com_Printf ("%s\n", value); + Com_Printf("%s\n", value); } } @@ -546,8 +527,7 @@ char *Com_StringContains(char *str1, char *str2, int casesensitive) { if (str1[j] != str2[j]) { break; } - } - else { + } else { if (toupper(str1[j]) != toupper(str2[j])) { break; } @@ -565,73 +545,74 @@ char *Com_StringContains(char *str1, char *str2, int casesensitive) { Com_Filter ============ */ -int Com_Filter(char *filter, char *name, int casesensitive) -{ +int Com_Filter(char *filter, char *name, int casesensitive) { char buf[MAX_TOKEN_CHARS]; char *ptr; int i, found; - while(*filter) { + while (*filter) { if (*filter == '*') { filter++; for (i = 0; *filter; i++) { - if (*filter == '*' || *filter == '?') break; + if (*filter == '*' || *filter == '?') + break; buf[i] = *filter; filter++; } buf[i] = '\0'; if (strlen(buf)) { ptr = Com_StringContains(name, buf, casesensitive); - if (!ptr) return qfalse; + if (!ptr) + return qfalse; name = ptr + strlen(buf); } - } - else if (*filter == '?') { + } else if (*filter == '?') { filter++; name++; - } - else if (*filter == '[' && *(filter+1) == '[') { + } else if (*filter == '[' && *(filter + 1) == '[') { filter++; - } - else if (*filter == '[') { + } else if (*filter == '[') { filter++; found = qfalse; - while(*filter && !found) { - if (*filter == ']' && *(filter+1) != ']') break; - if (*(filter+1) == '-' && *(filter+2) && (*(filter+2) != ']' || *(filter+3) == ']')) { + while (*filter && !found) { + if (*filter == ']' && *(filter + 1) != ']') + break; + if (*(filter + 1) == '-' && *(filter + 2) && (*(filter + 2) != ']' || *(filter + 3) == ']')) { if (casesensitive) { - if (*name >= *filter && *name <= *(filter+2)) found = qtrue; - } - else { - if (toupper(*name) >= toupper(*filter) && - toupper(*name) <= toupper(*(filter+2))) found = qtrue; + if (*name >= *filter && *name <= *(filter + 2)) + found = qtrue; + } else { + if (toupper(*name) >= toupper(*filter) && toupper(*name) <= toupper(*(filter + 2))) + found = qtrue; } filter += 3; - } - else { + } else { if (casesensitive) { - if (*filter == *name) found = qtrue; - } - else { - if (toupper(*filter) == toupper(*name)) found = qtrue; + if (*filter == *name) + found = qtrue; + } else { + if (toupper(*filter) == toupper(*name)) + found = qtrue; } filter++; } } - if (!found) return qfalse; - while(*filter) { - if (*filter == ']' && *(filter+1) != ']') break; + if (!found) + return qfalse; + while (*filter) { + if (*filter == ']' && *(filter + 1) != ']') + break; filter++; } filter++; name++; - } - else { + } else { if (casesensitive) { - if (*filter != *name) return qfalse; - } - else { - if (toupper(*filter) != toupper(*name)) return qfalse; + if (*filter != *name) + return qfalse; + } else { + if (toupper(*filter) != toupper(*name)) + return qfalse; } filter++; name++; @@ -645,26 +626,23 @@ int Com_Filter(char *filter, char *name, int casesensitive) Com_FilterPath ============ */ -int Com_FilterPath(char *filter, char *name, int casesensitive) -{ +int Com_FilterPath(char *filter, char *name, int casesensitive) { int i; char new_filter[MAX_QPATH]; char new_name[MAX_QPATH]; - for (i = 0; i < MAX_QPATH-1 && filter[i]; i++) { - if ( filter[i] == '\\' || filter[i] == ':' ) { + for (i = 0; i < MAX_QPATH - 1 && filter[i]; i++) { + if (filter[i] == '\\' || filter[i] == ':') { new_filter[i] = '/'; - } - else { + } else { new_filter[i] = filter[i]; } } new_filter[i] = '\0'; - for (i = 0; i < MAX_QPATH-1 && name[i]; i++) { - if ( name[i] == '\\' || name[i] == ':' ) { + for (i = 0; i < MAX_QPATH - 1 && name[i]; i++) { + if (name[i] == '\\' || name[i] == ':') { new_name[i] = '/'; - } - else { + } else { new_name[i] = name[i]; } } @@ -715,7 +693,6 @@ int Com_RealTime(qtime_t *qtime) { return t; } - /* =================================================================== @@ -726,38 +703,38 @@ journaled file =================================================================== */ -#define MAX_PUSHED_EVENTS 1024 -static int com_pushedEventsHead = 0; -static int com_pushedEventsTail = 0; -static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS]; +#define MAX_PUSHED_EVENTS 1024 +static int com_pushedEventsHead = 0; +static int com_pushedEventsTail = 0; +static sysEvent_t com_pushedEvents[MAX_PUSHED_EVENTS]; /* ================= Com_InitJournaling ================= */ -void Com_InitJournaling( void ) { - Com_StartupVariable( "journal" ); - com_journal = Cvar_Get ("journal", "0", CVAR_INIT); - if ( !com_journal->integer ) { +void Com_InitJournaling(void) { + Com_StartupVariable("journal"); + com_journal = Cvar_Get("journal", "0", CVAR_INIT); + if (!com_journal->integer) { return; } - if ( com_journal->integer == 1 ) { - Com_Printf( "Journaling events\n"); - com_journalFile = FS_FOpenFileWrite( "journal.dat" ); - com_journalDataFile = FS_FOpenFileWrite( "journaldata.dat" ); - } else if ( com_journal->integer == 2 ) { - Com_Printf( "Replaying journaled events\n"); - FS_FOpenFileRead( "journal.dat", &com_journalFile, qtrue ); - FS_FOpenFileRead( "journaldata.dat", &com_journalDataFile, qtrue ); + if (com_journal->integer == 1) { + Com_Printf("Journaling events\n"); + com_journalFile = FS_FOpenFileWrite("journal.dat"); + com_journalDataFile = FS_FOpenFileWrite("journaldata.dat"); + } else if (com_journal->integer == 2) { + Com_Printf("Replaying journaled events\n"); + FS_FOpenFileRead("journal.dat", &com_journalFile, qtrue); + FS_FOpenFileRead("journaldata.dat", &com_journalDataFile, qtrue); } - if ( !com_journalFile || !com_journalDataFile ) { - Cvar_Set( "com_journal", "0" ); + if (!com_journalFile || !com_journalDataFile) { + Cvar_Set("com_journal", "0"); com_journalFile = 0; com_journalDataFile = 0; - Com_Printf( "Couldn't open journal files\n" ); + Com_Printf("Couldn't open journal files\n"); } } @@ -766,36 +743,36 @@ void Com_InitJournaling( void ) { Com_GetRealEvent ================= */ -sysEvent_t Com_GetRealEvent( void ) { - int r; - sysEvent_t ev; +sysEvent_t Com_GetRealEvent(void) { + int r; + sysEvent_t ev; // either get an event from the system or the journal file - if ( com_journal->integer == 2 ) { - r = FS_Read( &ev, sizeof(ev), com_journalFile ); - if ( r != sizeof(ev) ) { - Com_Error( ERR_FATAL, "Error reading from journal file" ); + if (com_journal->integer == 2) { + r = FS_Read(&ev, sizeof(ev), com_journalFile); + if (r != sizeof(ev)) { + Com_Error(ERR_FATAL, "Error reading from journal file"); } - if ( ev.evPtrLength ) { - ev.evPtr = Z_Malloc( ev.evPtrLength, TAG_EVENT, qtrue ); - r = FS_Read( ev.evPtr, ev.evPtrLength, com_journalFile ); - if ( r != ev.evPtrLength ) { - Com_Error( ERR_FATAL, "Error reading from journal file" ); + if (ev.evPtrLength) { + ev.evPtr = Z_Malloc(ev.evPtrLength, TAG_EVENT, qtrue); + r = FS_Read(ev.evPtr, ev.evPtrLength, com_journalFile); + if (r != ev.evPtrLength) { + Com_Error(ERR_FATAL, "Error reading from journal file"); } } } else { ev = Sys_GetEvent(); // write the journal value out if needed - if ( com_journal->integer == 1 ) { - r = FS_Write( &ev, sizeof(ev), com_journalFile ); - if ( r != sizeof(ev) ) { - Com_Error( ERR_FATAL, "Error writing to journal file" ); + if (com_journal->integer == 1) { + r = FS_Write(&ev, sizeof(ev), com_journalFile); + if (r != sizeof(ev)) { + Com_Error(ERR_FATAL, "Error writing to journal file"); } - if ( ev.evPtrLength ) { - r = FS_Write( ev.evPtr, ev.evPtrLength, com_journalFile ); - if ( r != ev.evPtrLength ) { - Com_Error( ERR_FATAL, "Error writing to journal file" ); + if (ev.evPtrLength) { + r = FS_Write(ev.evPtr, ev.evPtrLength, com_journalFile); + if (r != ev.evPtrLength) { + Com_Error(ERR_FATAL, "Error writing to journal file"); } } } @@ -809,10 +786,10 @@ sysEvent_t Com_GetRealEvent( void ) { Com_InitPushEvent ================= */ -void Com_InitPushEvent( void ) { +void Com_InitPushEvent(void) { // clear the static buffer array // this requires SE_NONE to be accepted as a valid but NOP event - memset( com_pushedEvents, 0, sizeof(com_pushedEvents) ); + memset(com_pushedEvents, 0, sizeof(com_pushedEvents)); // reset counters while we are at it // beware: GetEvent might still return an SE_NONE from the buffer com_pushedEventsHead = 0; @@ -824,22 +801,22 @@ void Com_InitPushEvent( void ) { Com_PushEvent ================= */ -void Com_PushEvent( sysEvent_t *event ) { - sysEvent_t *ev; +void Com_PushEvent(sysEvent_t *event) { + sysEvent_t *ev; static int printedWarning = 0; - ev = &com_pushedEvents[ com_pushedEventsHead & (MAX_PUSHED_EVENTS-1) ]; + ev = &com_pushedEvents[com_pushedEventsHead & (MAX_PUSHED_EVENTS - 1)]; - if ( com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS ) { + if (com_pushedEventsHead - com_pushedEventsTail >= MAX_PUSHED_EVENTS) { // don't print the warning constantly, or it can give time for more... - if ( !printedWarning ) { + if (!printedWarning) { printedWarning = qtrue; - Com_Printf( "WARNING: Com_PushEvent overflow\n" ); + Com_Printf("WARNING: Com_PushEvent overflow\n"); } - if ( ev->evPtr ) { - Z_Free( ev->evPtr ); + if (ev->evPtr) { + Z_Free(ev->evPtr); } com_pushedEventsTail++; } else { @@ -855,10 +832,10 @@ void Com_PushEvent( sysEvent_t *event ) { Com_GetEvent ================= */ -sysEvent_t Com_GetEvent( void ) { - if ( com_pushedEventsHead > com_pushedEventsTail ) { +sysEvent_t Com_GetEvent(void) { + if (com_pushedEventsHead > com_pushedEventsTail) { com_pushedEventsTail++; - return com_pushedEvents[ (com_pushedEventsTail-1) & (MAX_PUSHED_EVENTS-1) ]; + return com_pushedEvents[(com_pushedEventsTail - 1) & (MAX_PUSHED_EVENTS - 1)]; } return Com_GetRealEvent(); } @@ -868,22 +845,22 @@ sysEvent_t Com_GetEvent( void ) { Com_RunAndTimeServerPacket ================= */ -void Com_RunAndTimeServerPacket( netadr_t *evFrom, msg_t *buf ) { - int t1, t2, msec; +void Com_RunAndTimeServerPacket(netadr_t *evFrom, msg_t *buf) { + int t1, t2, msec; t1 = 0; - if ( com_speeds->integer ) { - t1 = Sys_Milliseconds (); + if (com_speeds->integer) { + t1 = Sys_Milliseconds(); } - SV_PacketEvent( *evFrom, buf ); + SV_PacketEvent(*evFrom, buf); - if ( com_speeds->integer ) { - t2 = Sys_Milliseconds (); + if (com_speeds->integer) { + t2 = Sys_Milliseconds(); msec = t2 - t1; - if ( com_speeds->integer == 3 ) { - Com_Printf( "SV_PacketEvent time: %i\n", msec ); + if (com_speeds->integer == 3) { + Com_Printf("SV_PacketEvent time: %i\n", msec); } } } @@ -895,73 +872,69 @@ Com_EventLoop Returns last event time ================= */ -int Com_EventLoop( void ) { - sysEvent_t ev; - netadr_t evFrom; - byte bufData[MAX_MSGLEN]; - msg_t buf; +int Com_EventLoop(void) { + sysEvent_t ev; + netadr_t evFrom; + byte bufData[MAX_MSGLEN]; + msg_t buf; - MSG_Init( &buf, bufData, sizeof( bufData ) ); + MSG_Init(&buf, bufData, sizeof(bufData)); - while ( 1 ) { + while (1) { ev = Com_GetEvent(); // if no more events are available - if ( ev.evType == SE_NONE ) { + if (ev.evType == SE_NONE) { // manually send packet events for the loopback channel - while ( NET_GetLoopPacket( NS_CLIENT, &evFrom, &buf ) ) { - CL_PacketEvent( evFrom, &buf ); + while (NET_GetLoopPacket(NS_CLIENT, &evFrom, &buf)) { + CL_PacketEvent(evFrom, &buf); } - while ( NET_GetLoopPacket( NS_SERVER, &evFrom, &buf ) ) { + while (NET_GetLoopPacket(NS_SERVER, &evFrom, &buf)) { // if the server just shut down, flush the events - if ( com_sv_running->integer ) { - Com_RunAndTimeServerPacket( &evFrom, &buf ); + if (com_sv_running->integer) { + Com_RunAndTimeServerPacket(&evFrom, &buf); } } return ev.evTime; } - - switch ( ev.evType ) { + switch (ev.evType) { default: - Com_Error( ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType ); + Com_Error(ERR_FATAL, "Com_EventLoop: bad event type %i", ev.evType); + break; + case SE_NONE: break; - case SE_NONE: - break; case SE_KEY: - CL_KeyEvent( ev.evValue, (qboolean)ev.evValue2, ev.evTime ); + CL_KeyEvent(ev.evValue, (qboolean)ev.evValue2, ev.evTime); break; case SE_CHAR: - CL_CharEvent( ev.evValue ); + CL_CharEvent(ev.evValue); break; case SE_MOUSE: - CL_MouseEvent( ev.evValue, ev.evValue2, ev.evTime ); + CL_MouseEvent(ev.evValue, ev.evValue2, ev.evTime); break; case SE_JOYSTICK_AXIS: - CL_JoystickEvent( ev.evValue, ev.evValue2, ev.evTime ); + CL_JoystickEvent(ev.evValue, ev.evValue2, ev.evTime); break; case SE_CONSOLE: - if ( ((char *)ev.evPtr)[0] == '\\' || ((char *)ev.evPtr)[0] == '/' ) - { - Cbuf_AddText( (char *)ev.evPtr+1 ); - } - else - { - Cbuf_AddText( (char *)ev.evPtr ); + if (((char *)ev.evPtr)[0] == '\\' || ((char *)ev.evPtr)[0] == '/') { + Cbuf_AddText((char *)ev.evPtr + 1); + } else { + Cbuf_AddText((char *)ev.evPtr); } - Cbuf_AddText( "\n" ); + Cbuf_AddText("\n"); break; } // free any block data - if ( ev.evPtr ) { - Z_Free( ev.evPtr ); + if (ev.evPtr) { + Z_Free(ev.evPtr); } } - return 0; // never reached + return 0; // never reached } /* @@ -971,17 +944,17 @@ Com_Milliseconds Can be used for profiling, but will be journaled accurately ================ */ -int Com_Milliseconds (void) { - sysEvent_t ev; +int Com_Milliseconds(void) { + sysEvent_t ev; // get events and push them until we get a null event with the current time do { ev = Com_GetRealEvent(); - if ( ev.evType != SE_NONE ) { - Com_PushEvent( &ev ); + if (ev.evType != SE_NONE) { + Com_PushEvent(&ev); } - } while ( ev.evType != SE_NONE ); + } while (ev.evType != SE_NONE); return ev.evTime; } @@ -996,15 +969,14 @@ Just throw a fatal error to test error shutdown procedures ============= */ -static void NORETURN Com_Error_f (void) { - if ( Cmd_Argc() > 1 ) { - Com_Error( ERR_DROP, "Testing drop error" ); +static void NORETURN Com_Error_f(void) { + if (Cmd_Argc() > 1) { + Com_Error(ERR_DROP, "Testing drop error"); } else { - Com_Error( ERR_FATAL, "Testing fatal error" ); + Com_Error(ERR_FATAL, "Testing fatal error"); } } - /* ============= Com_Freeze_f @@ -1013,21 +985,21 @@ Just freeze in place for a given number of seconds to test error recovery ============= */ -static void Com_Freeze_f (void) { - float s; - int start, now; +static void Com_Freeze_f(void) { + float s; + int start, now; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "freeze \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("freeze \n"); return; } - s = atof( Cmd_Argv(1) ); + s = atof(Cmd_Argv(1)); start = Com_Milliseconds(); - while ( 1 ) { + while (1) { now = Com_Milliseconds(); - if ( ( now - start ) * 0.001 > s ) { + if ((now - start) * 0.001 > s) { break; } } @@ -1040,8 +1012,8 @@ Com_Crash_f A way to force a bus error for development reasons ================= */ -static void NORETURN Com_Crash_f( void ) { - * ( volatile int * ) 0 = 0x12345678; +static void NORETURN Com_Crash_f(void) { + *(volatile int *)0 = 0x12345678; /* that should crash already, but to reassure the compiler: */ abort(); } @@ -1052,13 +1024,11 @@ Com_ExecuteCfg ================== */ -void Com_ExecuteCfg(void) -{ +void Com_ExecuteCfg(void) { Cbuf_ExecuteText(EXEC_NOW, "exec mpdefault.cfg\n"); Cbuf_Execute(); // Always execute after exec to prevent text buffer overflowing - if(!Com_SafeMode()) - { + if (!Com_SafeMode()) { // skip the q3config.cfg and autoexec.cfg if "safe" is on the command line Cbuf_ExecuteText(EXEC_NOW, "exec " Q3CONFIG_CFG "\n"); Cbuf_Execute(); @@ -1073,11 +1043,10 @@ Com_InitRand Seed the random number generator, if possible with an OS supplied random seed. ================= */ -static void Com_InitRand(void) -{ +static void Com_InitRand(void) { unsigned int seed; - if(Sys_RandomBytes((byte *) &seed, sizeof(seed))) + if (Sys_RandomBytes((byte *)&seed, sizeof(seed))) srand(seed); else srand(time(NULL)); @@ -1089,23 +1058,21 @@ Com_ErrorString Error string for the given error code (from Com_Error). ================= */ -static const char *Com_ErrorString ( int code ) -{ - switch ( code ) - { - case ERR_DISCONNECT: - // fallthrough - case ERR_SERVERDISCONNECT: - return "DISCONNECTED"; +static const char *Com_ErrorString(int code) { + switch (code) { + case ERR_DISCONNECT: + // fallthrough + case ERR_SERVERDISCONNECT: + return "DISCONNECTED"; - case ERR_DROP: - return "DROPPED"; + case ERR_DROP: + return "DROPPED"; - case ERR_NEED_CD: - return "NEED CD"; + case ERR_NEED_CD: + return "NEED CD"; - default: - return "UNKNOWN"; + default: + return "UNKNOWN"; } } @@ -1115,35 +1082,35 @@ Com_CatchError Handles freeing up of resources when Com_Error is called. ================= */ -static void Com_CatchError ( int code ) -{ - if ( code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT ) { - SV_Shutdown( "Server disconnected" ); - CL_Disconnect( qtrue ); - CL_FlushMemory( ); +static void Com_CatchError(int code) { + if (code == ERR_DISCONNECT || code == ERR_SERVERDISCONNECT) { + SV_Shutdown("Server disconnected"); + CL_Disconnect(qtrue); + CL_FlushMemory(); // make sure we can get at our local stuff - FS_PureServerSetLoadedPaks( "", "" ); + FS_PureServerSetLoadedPaks("", ""); com_errorEntered = qfalse; - } else if ( code == ERR_DROP ) { - Com_Printf ("********************\n" - "ERROR: %s\n" - "********************\n", com_errorMessage); - SV_Shutdown (va("Server crashed: %s\n", com_errorMessage)); - CL_Disconnect( qtrue ); - CL_FlushMemory( ); + } else if (code == ERR_DROP) { + Com_Printf("********************\n" + "ERROR: %s\n" + "********************\n", + com_errorMessage); + SV_Shutdown(va("Server crashed: %s\n", com_errorMessage)); + CL_Disconnect(qtrue); + CL_FlushMemory(); // make sure we can get at our local stuff - FS_PureServerSetLoadedPaks( "", "" ); + FS_PureServerSetLoadedPaks("", ""); com_errorEntered = qfalse; - } else if ( code == ERR_NEED_CD ) { - SV_Shutdown( "Server didn't have CD" ); - if ( com_cl_running && com_cl_running->integer ) { - CL_Disconnect( qtrue ); - CL_FlushMemory( ); + } else if (code == ERR_NEED_CD) { + SV_Shutdown("Server didn't have CD"); + if (com_cl_running && com_cl_running->integer) { + CL_Disconnect(qtrue); + CL_FlushMemory(); } else { - Com_Printf("Server didn't have CD\n" ); + Com_Printf("Server didn't have CD\n"); } // make sure we can get at our local stuff - FS_PureServerSetLoadedPaks( "", "" ); + FS_PureServerSetLoadedPaks("", ""); com_errorEntered = qfalse; } } @@ -1153,14 +1120,13 @@ static void Com_CatchError ( int code ) Com_Init ================= */ -void Com_Init( char *commandLine ) { - char *s; - int qport; +void Com_Init(char *commandLine) { + char *s; + int qport; - Com_Printf( "%s %s %s\n", JK_VERSION, PLATFORM_STRING, SOURCE_DATE ); + Com_Printf("%s %s %s\n", JK_VERSION, PLATFORM_STRING, SOURCE_DATE); - try - { + try { // initialize the weak pseudo-random number generator for use later. Com_InitRand(); @@ -1168,70 +1134,70 @@ void Com_Init( char *commandLine ) { Com_InitPushEvent(); Com_InitZoneMemory(); - Cvar_Init (); + Cvar_Init(); navigator.Init(); // prepare enough of the subsystems to handle // cvar and command buffer management - Com_ParseCommandLine( commandLine ); + Com_ParseCommandLine(commandLine); - // Swap_Init (); - Cbuf_Init (); + // Swap_Init (); + Cbuf_Init(); // override anything from the config files with command line args - Com_StartupVariable( NULL ); + Com_StartupVariable(NULL); Com_InitZoneMemoryVars(); - Cmd_Init (); + Cmd_Init(); // Seed the random number generator Rand_Init(Sys_Milliseconds(true)); // get the developer cvar set as early as possible - com_developer = Cvar_Get("developer", "0", CVAR_TEMP, "Developer mode" ); + com_developer = Cvar_Get("developer", "0", CVAR_TEMP, "Developer mode"); // done early so bind command exists CL_InitKeyCommands(); com_homepath = Cvar_Get("com_homepath", "", CVAR_INIT); - FS_InitFilesystem (); + FS_InitFilesystem(); Com_InitJournaling(); // Add some commands here already so users can use them from config files - if ( com_developer && com_developer->integer ) { - Cmd_AddCommand ("error", Com_Error_f); - Cmd_AddCommand ("crash", Com_Crash_f ); - Cmd_AddCommand ("freeze", Com_Freeze_f); + if (com_developer && com_developer->integer) { + Cmd_AddCommand("error", Com_Error_f); + Cmd_AddCommand("crash", Com_Crash_f); + Cmd_AddCommand("freeze", Com_Freeze_f); } - Cmd_AddCommand ("quit", Com_Quit_f, "Quits the game" ); + Cmd_AddCommand("quit", Com_Quit_f, "Quits the game"); #ifndef FINAL_BUILD - Cmd_AddCommand ("changeVectors", MSG_ReportChangeVectors_f ); + Cmd_AddCommand("changeVectors", MSG_ReportChangeVectors_f); #endif - Cmd_AddCommand ("writeconfig", Com_WriteConfig_f, "Write the configuration to file" ); - Cmd_SetCommandCompletionFunc( "writeconfig", Cmd_CompleteCfgName ); + Cmd_AddCommand("writeconfig", Com_WriteConfig_f, "Write the configuration to file"); + Cmd_SetCommandCompletionFunc("writeconfig", Cmd_CompleteCfgName); Com_ExecuteCfg(); // override anything from the config files with command line args - Com_StartupVariable( NULL ); - - // get dedicated here for proper hunk megs initialization - #ifdef DEDICATED - com_dedicated = Cvar_Get ("dedicated", "2", CVAR_INIT); - Cvar_CheckRange( com_dedicated, 1, 2, qtrue ); - #else - //OJKFIXME: Temporarily disabled dedicated server when not using the dedicated server binary. + Com_StartupVariable(NULL); + + // get dedicated here for proper hunk megs initialization +#ifdef DEDICATED + com_dedicated = Cvar_Get("dedicated", "2", CVAR_INIT); + Cvar_CheckRange(com_dedicated, 1, 2, qtrue); +#else + // OJKFIXME: Temporarily disabled dedicated server when not using the dedicated server binary. // Issue is the server not having a renderer when not using ^^^^^ // and crashing in SV_SpawnServer calling re.RegisterMedia_LevelLoadBegin // Until we fully remove the renderer from the server, the client executable // will not have dedicated support capabilities. // Use the dedicated server package. - com_dedicated = Cvar_Get ("_dedicated", "0", CVAR_ROM|CVAR_INIT|CVAR_PROTECTED); - // Cvar_CheckRange( com_dedicated, 0, 2, qtrue ); - #endif + com_dedicated = Cvar_Get("_dedicated", "0", CVAR_ROM | CVAR_INIT | CVAR_PROTECTED); +// Cvar_CheckRange( com_dedicated, 0, 2, qtrue ); +#endif // allocate the stack based hunk allocator Com_InitHunkMemory(); @@ -1242,40 +1208,40 @@ void Com_Init( char *commandLine ) { // // init commands and vars // - com_logfile = Cvar_Get ("logfile", "0", CVAR_TEMP ); + com_logfile = Cvar_Get("logfile", "0", CVAR_TEMP); - com_timescale = Cvar_Get ("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO ); - com_fixedtime = Cvar_Get ("fixedtime", "0", CVAR_CHEAT); - com_showtrace = Cvar_Get ("com_showtrace", "0", CVAR_CHEAT); + com_timescale = Cvar_Get("timescale", "1", CVAR_CHEAT | CVAR_SYSTEMINFO); + com_fixedtime = Cvar_Get("fixedtime", "0", CVAR_CHEAT); + com_showtrace = Cvar_Get("com_showtrace", "0", CVAR_CHEAT); - com_speeds = Cvar_Get ("com_speeds", "0", 0); - com_timedemo = Cvar_Get ("timedemo", "0", 0); - com_cameraMode = Cvar_Get ("com_cameraMode", "0", CVAR_CHEAT); + com_speeds = Cvar_Get("com_speeds", "0", 0); + com_timedemo = Cvar_Get("timedemo", "0", 0); + com_cameraMode = Cvar_Get("com_cameraMode", "0", CVAR_CHEAT); com_optvehtrace = Cvar_Get("com_optvehtrace", "0", 0); - cl_paused = Cvar_Get ("cl_paused", "0", CVAR_ROM); - sv_paused = Cvar_Get ("sv_paused", "0", CVAR_ROM); - com_sv_running = Cvar_Get ("sv_running", "0", CVAR_ROM, "Is a server running?" ); - com_cl_running = Cvar_Get ("cl_running", "0", CVAR_ROM, "Is the client running?" ); - com_buildScript = Cvar_Get( "com_buildScript", "0", 0 ); + cl_paused = Cvar_Get("cl_paused", "0", CVAR_ROM); + sv_paused = Cvar_Get("sv_paused", "0", CVAR_ROM); + com_sv_running = Cvar_Get("sv_running", "0", CVAR_ROM, "Is a server running?"); + com_cl_running = Cvar_Get("cl_running", "0", CVAR_ROM, "Is the client running?"); + com_buildScript = Cvar_Get("com_buildScript", "0", 0); #ifndef _WIN32 - com_ansiColor = Cvar_Get( "com_ansiColor", "0", CVAR_ARCHIVE_ND ); + com_ansiColor = Cvar_Get("com_ansiColor", "0", CVAR_ARCHIVE_ND); #endif #ifdef G2_PERFORMANCE_ANALYSIS com_G2Report = Cvar_Get("com_G2Report", "0", 0); #endif - com_affinity = Cvar_Get( "com_affinity", "0", CVAR_ARCHIVE_ND ); - com_busyWait = Cvar_Get( "com_busyWait", "0", CVAR_ARCHIVE_ND ); + com_affinity = Cvar_Get("com_affinity", "0", CVAR_ARCHIVE_ND); + com_busyWait = Cvar_Get("com_busyWait", "0", CVAR_ARCHIVE_ND); - com_bootlogo = Cvar_Get( "com_bootlogo", "1", CVAR_ARCHIVE_ND, "Show intro movies" ); + com_bootlogo = Cvar_Get("com_bootlogo", "1", CVAR_ARCHIVE_ND, "Show intro movies"); - com_timestamps = Cvar_Get( "com_timestamps", "1", CVAR_ARCHIVE_ND, "Show timestamps in terminal and qconsole.log" ); + com_timestamps = Cvar_Get("com_timestamps", "1", CVAR_ARCHIVE_ND, "Show timestamps in terminal and qconsole.log"); - s = va("%s %s %s", JK_VERSION_OLD, PLATFORM_STRING, SOURCE_DATE ); - com_version = Cvar_Get ("version", s, CVAR_ROM | CVAR_SERVERINFO ); + s = va("%s %s %s", JK_VERSION_OLD, PLATFORM_STRING, SOURCE_DATE); + com_version = Cvar_Get("version", s, CVAR_ROM | CVAR_SERVERINFO); SE_Init(); @@ -1284,14 +1250,14 @@ void Com_Init( char *commandLine ) { Sys_SetProcessorAffinity(); // Pick a random port value - Com_RandomBytes( (byte*)&qport, sizeof(int) ); - Netchan_Init( qport & 0xffff ); // pick a port value that should be nice and random + Com_RandomBytes((byte *)&qport, sizeof(int)); + Netchan_Init(qport & 0xffff); // pick a port value that should be nice and random VM_Init(); SV_Init(); com_dedicated->modified = qfalse; - if ( !com_dedicated->integer ) { + if (!com_dedicated->integer) { CL_Init(); } @@ -1300,16 +1266,12 @@ void Com_Init( char *commandLine ) { // being random enough for a serverid com_frameTime = Com_Milliseconds(); - // add + commands from command line - if ( !Com_AddStartupCommands() ) - { + if (!Com_AddStartupCommands()) { // if the user didn't give any commands, run default action - if ( !com_dedicated->integer ) - { - if ( com_bootlogo->integer ) - { - Cbuf_AddText ("cinematic openinglogos.roq\n"); + if (!com_dedicated->integer) { + if (com_bootlogo->integer) { + Cbuf_AddText("cinematic openinglogos.roq\n"); } } } @@ -1323,33 +1285,30 @@ void Com_Init( char *commandLine ) { Cvar_Set("ui_singlePlayerActive", "0"); com_fullyInitialized = qtrue; - Com_Printf ("--- Common Initialization Complete ---\n"); - } - catch ( int code ) - { - Com_CatchError (code); - Sys_Error ("Error during initialization: %s", Com_ErrorString (code)); + Com_Printf("--- Common Initialization Complete ---\n"); + } catch (int code) { + Com_CatchError(code); + Sys_Error("Error during initialization: %s", Com_ErrorString(code)); } } //================================================================== -void Com_WriteConfigToFile( const char *filename ) { - fileHandle_t f; +void Com_WriteConfigToFile(const char *filename) { + fileHandle_t f; - f = FS_FOpenFileWrite( filename ); - if ( !f ) { - Com_Printf ("Couldn't write %s.\n", filename ); + f = FS_FOpenFileWrite(filename); + if (!f) { + Com_Printf("Couldn't write %s.\n", filename); return; } - FS_Printf (f, "// generated by OpenJK MP, do not modify\n"); - Key_WriteBindings (f); - Cvar_WriteVariables (f); - FS_FCloseFile( f ); + FS_Printf(f, "// generated by OpenJK MP, do not modify\n"); + Key_WriteBindings(f); + Cvar_WriteVariables(f); + FS_FCloseFile(f); } - /* =============== Com_WriteConfiguration @@ -1357,22 +1316,21 @@ Com_WriteConfiguration Writes key bindings and archived cvars to config file if modified =============== */ -void Com_WriteConfiguration( void ) { +void Com_WriteConfiguration(void) { // if we are quiting without fully initializing, make sure // we don't write out anything - if ( !com_fullyInitialized ) { + if (!com_fullyInitialized) { return; } - if ( !(cvar_modifiedFlags & CVAR_ARCHIVE ) ) { + if (!(cvar_modifiedFlags & CVAR_ARCHIVE)) { return; } cvar_modifiedFlags &= ~CVAR_ARCHIVE; - Com_WriteConfigToFile( Q3CONFIG_CFG ); + Com_WriteConfigToFile(Q3CONFIG_CFG); } - /* =============== Com_WriteConfig_f @@ -1380,31 +1338,29 @@ Com_WriteConfig_f Write the config file to a specific name =============== */ -void Com_WriteConfig_f( void ) { - char filename[MAX_QPATH]; +void Com_WriteConfig_f(void) { + char filename[MAX_QPATH]; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "Usage: writeconfig \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: writeconfig \n"); return; } - Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); - COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); + Q_strncpyz(filename, Cmd_Argv(1), sizeof(filename)); + COM_DefaultExtension(filename, sizeof(filename), ".cfg"); - if(!COM_CompareExtension(filename, ".cfg")) - { - Com_Printf( "Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n" ); + if (!COM_CompareExtension(filename, ".cfg")) { + Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n"); return; } - if(!FS_FilenameCompare(filename, "mpdefault.cfg") || !FS_FilenameCompare(filename, "default.cfg")) - { - Com_Printf( S_COLOR_YELLOW "Com_WriteConfig_f: The filename \"%s\" is reserved! Please choose another name.\n", filename ); + if (!FS_FilenameCompare(filename, "mpdefault.cfg") || !FS_FilenameCompare(filename, "default.cfg")) { + Com_Printf(S_COLOR_YELLOW "Com_WriteConfig_f: The filename \"%s\" is reserved! Please choose another name.\n", filename); return; } - Com_Printf( "Writing %s.\n", filename ); - Com_WriteConfigToFile( filename ); + Com_Printf("Writing %s.\n", filename); + Com_WriteConfigToFile(filename); } /* @@ -1412,35 +1368,34 @@ void Com_WriteConfig_f( void ) { Com_ModifyMsec ================ */ -int Com_ModifyMsec( int msec ) { - int clampTime; +int Com_ModifyMsec(int msec) { + int clampTime; // // modify time for debugging values // - if ( com_fixedtime->integer ) { + if (com_fixedtime->integer) { msec = com_fixedtime->integer; - } else if ( com_timescale->value ) { + } else if (com_timescale->value) { msec *= com_timescale->value; } else if (com_cameraMode->integer) { msec *= com_timescale->value; } // don't let it scale below 1 msec - if ( msec < 1 && com_timescale->value) { + if (msec < 1 && com_timescale->value) { msec = 1; } - if ( com_dedicated->integer ) { + if (com_dedicated->integer) { // dedicated servers don't want to clamp for a much longer // period, because it would mess up all the client's views // of time. - if ( com_sv_running->integer && msec > 500 ) { - Com_Printf( "Hitch warning: %i msec frame time\n", msec ); + if (com_sv_running->integer && msec > 500) { + Com_Printf("Hitch warning: %i msec frame time\n", msec); } clampTime = 5000; - } else - if ( !com_sv_running->integer ) { + } else if (!com_sv_running->integer) { // clients of remote servers do not want to clamp time, because // it would skew their view of the server's time temporarily clampTime = 5000; @@ -1451,7 +1406,7 @@ int Com_ModifyMsec( int msec ) { clampTime = 200; } - if ( msec > clampTime ) { + if (msec > clampTime) { msec = clampTime; } @@ -1472,13 +1427,12 @@ Com_TimeVal ================= */ -int Com_TimeVal(int minMsec) -{ +int Com_TimeVal(int minMsec) { int timeVal; timeVal = Sys_Milliseconds() - com_frameTime; - if(timeVal >= minMsec) + if (timeVal >= minMsec) timeVal = 0; else timeVal = minMsec - timeVal; @@ -1491,22 +1445,21 @@ int Com_TimeVal(int minMsec) Com_Frame ================= */ -void Com_Frame( void ) { +void Com_Frame(void) { - try - { + try { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_PreciseFrame.Start(); #endif - int msec, minMsec; - int timeVal; - static int lastTime = 0, bias = 0; + int msec, minMsec; + int timeVal; + static int lastTime = 0, bias = 0; - int timeBeforeFirstEvents = 0; - int timeBeforeServer = 0; - int timeBeforeEvents = 0; - int timeBeforeClient = 0; - int timeAfter = 0; + int timeBeforeFirstEvents = 0; + int timeBeforeServer = 0; + int timeBeforeEvents = 0; + int timeBeforeClient = 0; + int timeAfter = 0; // write config file if anything changed Com_WriteConfiguration(); @@ -1514,22 +1467,20 @@ void Com_Frame( void ) { // // main event loop // - if ( com_speeds->integer ) { - timeBeforeFirstEvents = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeFirstEvents = Sys_Milliseconds(); } // Figure out how much time we have - if(!com_timedemo->integer) - { - if(com_dedicated->integer) + if (!com_timedemo->integer) { + if (com_dedicated->integer) minMsec = SV_FrameMsec(); - else - { - if(com_minimized->integer && com_maxfpsMinimized->integer > 0) + else { + if (com_minimized->integer && com_maxfpsMinimized->integer > 0) minMsec = 1000 / com_maxfpsMinimized->integer; - else if(com_unfocused->integer && com_maxfpsUnfocused->integer > 0) + else if (com_unfocused->integer && com_maxfpsUnfocused->integer > 0) minMsec = 1000 / com_maxfpsUnfocused->integer; - else if(com_maxfps->integer > 0) + else if (com_maxfps->integer > 0) minMsec = 1000 / com_maxfps->integer; else minMsec = 1; @@ -1544,18 +1495,17 @@ void Com_Frame( void ) { // that framerate is stable at the requested value. minMsec -= bias; } - } - else + } else minMsec = 1; timeVal = Com_TimeVal(minMsec); do { // Busy sleep the last millisecond for better timeout precision - if(com_busyWait->integer || timeVal < 1) + if (com_busyWait->integer || timeVal < 1) NET_Sleep(0); else NET_Sleep(timeVal - 1); - } while( (timeVal = Com_TimeVal(minMsec)) != 0 ); + } while ((timeVal = Com_TimeVal(minMsec)) != 0); IN_Frame(); lastTime = com_frameTime; @@ -1563,31 +1513,31 @@ void Com_Frame( void ) { msec = com_frameTime - lastTime; - Cbuf_Execute (); + Cbuf_Execute(); // mess with msec if needed - msec = Com_ModifyMsec( msec ); + msec = Com_ModifyMsec(msec); // // server side // - if ( com_speeds->integer ) { - timeBeforeServer = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeServer = Sys_Milliseconds(); } - SV_Frame( msec ); + SV_Frame(msec); // if "dedicated" has been modified, start up // or shut down the client system. // Do this after the server may have started, // but before the client tries to auto-connect - if ( com_dedicated->modified ) { + if (com_dedicated->modified) { // get the latched value - Cvar_Get( "_dedicated", "0", 0 ); + Cvar_Get("_dedicated", "0", 0); com_dedicated->modified = qfalse; - if ( !com_dedicated->integer ) { + if (!com_dedicated->integer) { CL_Init(); - CL_StartHunkUsers(); //fire up the UI! + CL_StartHunkUsers(); // fire up the UI! } else { CL_Shutdown(); } @@ -1596,44 +1546,40 @@ void Com_Frame( void ) { // // client system // - if ( !com_dedicated->integer ) { + if (!com_dedicated->integer) { // // run event loop a second time to get server to client packets // without a frame of latency // - if ( com_speeds->integer ) { - timeBeforeEvents = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeEvents = Sys_Milliseconds(); } Com_EventLoop(); - Cbuf_Execute (); - + Cbuf_Execute(); // // client side // - if ( com_speeds->integer ) { - timeBeforeClient = Sys_Milliseconds (); + if (com_speeds->integer) { + timeBeforeClient = Sys_Milliseconds(); } - CL_Frame( msec ); + CL_Frame(msec); - if ( com_speeds->integer ) { - timeAfter = Sys_Milliseconds (); + if (com_speeds->integer) { + timeAfter = Sys_Milliseconds(); } - } - else - { - if ( com_speeds->integer ) - { - timeBeforeEvents = timeBeforeClient = timeAfter = Sys_Milliseconds (); + } else { + if (com_speeds->integer) { + timeBeforeEvents = timeBeforeClient = timeAfter = Sys_Milliseconds(); } } // // report timing information // - if ( com_speeds->integer ) { - int all, sv, ev, cl; + if (com_speeds->integer) { + int all, sv, ev, cl; all = timeAfter - timeBeforeServer; sv = timeBeforeEvents - timeBeforeServer; @@ -1642,45 +1588,41 @@ void Com_Frame( void ) { sv -= time_game; cl -= time_frontend + time_backend; - Com_Printf ("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n", - com_frameNumber, all, sv, ev, cl, time_game, time_frontend, time_backend ); + Com_Printf("frame:%i all:%3i sv:%3i ev:%3i cl:%3i gm:%3i rf:%3i bk:%3i\n", com_frameNumber, all, sv, ev, cl, time_game, time_frontend, + time_backend); } // // trace optimization tracking // - if ( com_showtrace->integer ) { + if (com_showtrace->integer) { - extern int c_traces, c_brush_traces, c_patch_traces; - extern int c_pointcontents; + extern int c_traces, c_brush_traces, c_patch_traces; + extern int c_pointcontents; - Com_Printf ("%4i traces (%ib %ip) %4i points\n", c_traces, - c_brush_traces, c_patch_traces, c_pointcontents); + Com_Printf("%4i traces (%ib %ip) %4i points\n", c_traces, c_brush_traces, c_patch_traces, c_pointcontents); c_traces = 0; c_brush_traces = 0; c_patch_traces = 0; c_pointcontents = 0; } - if ( com_affinity->modified ) - { + if (com_affinity->modified) { com_affinity->modified = qfalse; Sys_SetProcessorAffinity(); } com_frameNumber++; - } - catch (int code) { - Com_CatchError (code); - Com_Printf ("%s\n", Com_ErrorString (code)); + } catch (int code) { + Com_CatchError(code); + Com_Printf("%s\n", Com_ErrorString(code)); return; } #ifdef G2_PERFORMANCE_ANALYSIS G2Time_PreciseFrame += G2PerformanceTimer_PreciseFrame.End(); - if (com_G2Report && com_G2Report->integer) - { + if (com_G2Report && com_G2Report->integer) { G2Time_ReportTimers(); } @@ -1694,31 +1636,30 @@ Com_Shutdown ================= */ void MSG_shutdownHuffman(); -void Com_Shutdown (void) -{ +void Com_Shutdown(void) { CM_ClearMap(); if (logfile) { - FS_FCloseFile (logfile); + FS_FCloseFile(logfile); logfile = 0; - com_logfile->integer = 0;//don't open up the log file again!! + com_logfile->integer = 0; // don't open up the log file again!! } - if ( com_journalFile ) { - FS_FCloseFile( com_journalFile ); + if (com_journalFile) { + FS_FCloseFile(com_journalFile); com_journalFile = 0; } MSG_shutdownHuffman(); -/* - // Only used for testing changes to huffman frequency table when tuning. - { - extern float Huff_GetCR(void); - char mess[256]; - sprintf(mess,"Eff. CR = %f\n",Huff_GetCR()); - OutputDebugString(mess); - } -*/ + /* + // Only used for testing changes to huffman frequency table when tuning. + { + extern float Huff_GetCR(void); + char mess[256]; + sprintf(mess,"Eff. CR = %f\n",Huff_GetCR()); + OutputDebugString(mess); + } + */ } /* @@ -1726,7 +1667,7 @@ void Com_Shutdown (void) Field_Clear ================== */ -void Field_Clear( field_t *edit ) { +void Field_Clear(field_t *edit) { memset(edit->buffer, 0, MAX_EDIT_LINE); edit->cursor = 0; edit->scroll = 0; @@ -1742,7 +1683,7 @@ CONSOLE LINE EDITING static const char *completionString; static char shortestMatch[MAX_TOKEN_CHARS]; -static int matchCount; +static int matchCount; // field we are working on, passed to Field_AutoComplete(&g_consoleCommand for instance) static field_t *completionField; @@ -1752,27 +1693,26 @@ FindMatches =============== */ -static void FindMatches( const char *s ) { - int i; +static void FindMatches(const char *s) { + int i; - if ( Q_stricmpn( s, completionString, strlen( completionString ) ) ) { + if (Q_stricmpn(s, completionString, strlen(completionString))) { return; } matchCount++; - if ( matchCount == 1 ) { - Q_strncpyz( shortestMatch, s, sizeof( shortestMatch ) ); + if (matchCount == 1) { + Q_strncpyz(shortestMatch, s, sizeof(shortestMatch)); return; } // cut shortestMatch to the amount common with s - for ( i = 0 ; s[i] ; i++ ) { - if ( tolower(shortestMatch[i]) != tolower(s[i]) ) { + for (i = 0; s[i]; i++) { + if (tolower(shortestMatch[i]) != tolower(s[i])) { shortestMatch[i] = 0; break; } } - if (!s[i]) - { + if (!s[i]) { shortestMatch[i] = 0; } } @@ -1783,13 +1723,13 @@ PrintMatches =============== */ -char *Cmd_DescriptionString( const char *cmd_name ); -static void PrintMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, (int)strlen( shortestMatch ) ) ) { - const char *description = Cmd_DescriptionString( s ); - Com_Printf( S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s\n", s ); - if ( VALIDSTRING( description ) ) - Com_Printf( S_COLOR_GREEN " %s" S_COLOR_WHITE "\n", description ); +char *Cmd_DescriptionString(const char *cmd_name); +static void PrintMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, (int)strlen(shortestMatch))) { + const char *description = Cmd_DescriptionString(s); + Com_Printf(S_COLOR_GREY "Cmd " S_COLOR_WHITE "%s\n", s); + if (VALIDSTRING(description)) + Com_Printf(S_COLOR_GREEN " %s" S_COLOR_WHITE "\n", description); } } @@ -1815,9 +1755,9 @@ PrintKeyMatches =============== */ -static void PrintKeyMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) { - Com_Printf( S_COLOR_GREY "Key " S_COLOR_WHITE "%s\n", s ); +static void PrintKeyMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, strlen(shortestMatch))) { + Com_Printf(S_COLOR_GREY "Key " S_COLOR_WHITE "%s\n", s); } } #endif @@ -1828,9 +1768,9 @@ PrintFileMatches =============== */ -static void PrintFileMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, strlen( shortestMatch ) ) ) { - Com_Printf( S_COLOR_GREY "File " S_COLOR_WHITE "%s\n", s ); +static void PrintFileMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, strlen(shortestMatch))) { + Com_Printf(S_COLOR_GREY "File " S_COLOR_WHITE "%s\n", s); } } @@ -1840,15 +1780,15 @@ PrintCvarMatches =============== */ -char *Cvar_DescriptionString( const char *var_name ); -static void PrintCvarMatches( const char *s ) { - if ( !Q_stricmpn( s, shortestMatch, (int)strlen( shortestMatch ) ) ) { +char *Cvar_DescriptionString(const char *var_name); +static void PrintCvarMatches(const char *s) { + if (!Q_stricmpn(s, shortestMatch, (int)strlen(shortestMatch))) { char value[TRUNCATE_LENGTH] = {0}; - const char *description = Cvar_DescriptionString( s ); - Com_TruncateLongString( value, Cvar_VariableString( s ) ); - Com_Printf( S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", s, value ); - if ( VALIDSTRING( description ) ) - Com_Printf( S_COLOR_GREEN " %s" S_COLOR_WHITE "\n", description ); + const char *description = Cvar_DescriptionString(s); + Com_TruncateLongString(value, Cvar_VariableString(s)); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", s, value); + if (VALIDSTRING(description)) + Com_Printf(S_COLOR_GREEN " %s" S_COLOR_WHITE "\n", description); } } @@ -1857,10 +1797,10 @@ static void PrintCvarMatches( const char *s ) { Field_FindFirstSeparator =============== */ -static char *Field_FindFirstSeparator( char *s ) { - for ( size_t i=0; ibuffer ) - strlen( completionString ); + completionOffset = strlen(completionField->buffer) - strlen(completionString); - Q_strncpyz( &completionField->buffer[completionOffset], shortestMatch, sizeof( completionField->buffer ) - completionOffset ); + Q_strncpyz(&completionField->buffer[completionOffset], shortestMatch, sizeof(completionField->buffer) - completionOffset); - completionField->cursor = strlen( completionField->buffer ); + completionField->cursor = strlen(completionField->buffer); - if ( matchCount == 1 ) { - Q_strcat( completionField->buffer, sizeof( completionField->buffer ), " " ); + if (matchCount == 1) { + Q_strcat(completionField->buffer, sizeof(completionField->buffer), " "); completionField->cursor++; return qtrue; } - Com_Printf( "%c%s\n", CONSOLE_PROMPT_CHAR, completionField->buffer ); + Com_Printf("%c%s\n", CONSOLE_PROMPT_CHAR, completionField->buffer); return qfalse; } @@ -1900,15 +1840,14 @@ static qboolean Field_Complete( void ) { Field_CompleteKeyname =============== */ -void Field_CompleteKeyname( void ) -{ +void Field_CompleteKeyname(void) { matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - Key_KeynameCompletion( FindMatches ); + Key_KeynameCompletion(FindMatches); - if( !Field_Complete( ) ) - Key_KeynameCompletion( PrintKeyMatches ); + if (!Field_Complete()) + Key_KeynameCompletion(PrintKeyMatches); } #endif @@ -1917,15 +1856,14 @@ void Field_CompleteKeyname( void ) Field_CompleteFilename =============== */ -void Field_CompleteFilename( const char *dir, const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk ) -{ +void Field_CompleteFilename(const char *dir, const char *ext, qboolean stripExt, qboolean allowNonPureFilesOnDisk) { matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - FS_FilenameCompletion( dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk ); + FS_FilenameCompletion(dir, ext, stripExt, FindMatches, allowNonPureFilesOnDisk); - if ( !Field_Complete() ) - FS_FilenameCompletion( dir, ext, stripExt, PrintFileMatches, allowNonPureFilesOnDisk ); + if (!Field_Complete()) + FS_FilenameCompletion(dir, ext, stripExt, PrintFileMatches, allowNonPureFilesOnDisk); } /* @@ -1933,61 +1871,58 @@ void Field_CompleteFilename( const char *dir, const char *ext, qboolean stripExt Field_CompleteCommand =============== */ -void Field_CompleteCommand( char *cmd, qboolean doCommands, qboolean doCvars ) -{ +void Field_CompleteCommand(char *cmd, qboolean doCommands, qboolean doCvars) { int completionArgument = 0; // Skip leading whitespace and quotes - cmd = Com_SkipCharset( cmd, " \"" ); + cmd = Com_SkipCharset(cmd, " \""); - Cmd_TokenizeStringIgnoreQuotes( cmd ); + Cmd_TokenizeStringIgnoreQuotes(cmd); completionArgument = Cmd_Argc(); // If there is trailing whitespace on the cmd - if ( *(cmd + strlen( cmd )-1) == ' ' ) { + if (*(cmd + strlen(cmd) - 1) == ' ') { completionString = ""; completionArgument++; - } - else - completionString = Cmd_Argv( completionArgument - 1 ); + } else + completionString = Cmd_Argv(completionArgument - 1); - if ( completionArgument > 1 ) { - const char *baseCmd = Cmd_Argv( 0 ); + if (completionArgument > 1) { + const char *baseCmd = Cmd_Argv(0); char *p; #ifndef DEDICATED - if ( baseCmd[0] == '\\' || baseCmd[0] == '/' ) + if (baseCmd[0] == '\\' || baseCmd[0] == '/') baseCmd++; #endif - if( ( p = Field_FindFirstSeparator( cmd ) ) ) - Field_CompleteCommand( p + 1, qtrue, qtrue ); // Compound command + if ((p = Field_FindFirstSeparator(cmd))) + Field_CompleteCommand(p + 1, qtrue, qtrue); // Compound command else - Cmd_CompleteArgument( baseCmd, cmd, completionArgument ); - } - else { - if ( completionString[0] == '\\' || completionString[0] == '/' ) + Cmd_CompleteArgument(baseCmd, cmd, completionArgument); + } else { + if (completionString[0] == '\\' || completionString[0] == '/') completionString++; matchCount = 0; - shortestMatch[ 0 ] = 0; + shortestMatch[0] = 0; - if ( strlen( completionString ) == 0 ) + if (strlen(completionString) == 0) return; - if ( doCommands ) - Cmd_CommandCompletion( FindMatches ); + if (doCommands) + Cmd_CommandCompletion(FindMatches); - if ( doCvars ) - Cvar_CommandCompletion( FindMatches ); + if (doCvars) + Cvar_CommandCompletion(FindMatches); - if ( !Field_Complete() ) { + if (!Field_Complete()) { // run through again, printing matches - if ( doCommands ) - Cmd_CommandCompletion( PrintMatches ); + if (doCommands) + Cmd_CommandCompletion(PrintMatches); - if ( doCvars ) - Cvar_CommandCompletion( PrintCvarMatches ); + if (doCvars) + Cvar_CommandCompletion(PrintCvarMatches); } } } @@ -1999,13 +1934,13 @@ Field_AutoComplete Perform Tab expansion =============== */ -void Field_AutoComplete( field_t *field ) { - if ( !field || !field->buffer[0] ) +void Field_AutoComplete(field_t *field) { + if (!field || !field->buffer[0]) return; completionField = field; - Field_CompleteCommand( completionField->buffer, qtrue, qtrue ); + Field_CompleteCommand(completionField->buffer, qtrue, qtrue); } /* @@ -2015,16 +1950,15 @@ Com_RandomBytes fills string array with len radom bytes, peferably from the OS randomizer ================== */ -void Com_RandomBytes( byte *string, int len ) -{ +void Com_RandomBytes(byte *string, int len) { int i; - if( Sys_RandomBytes( string, len ) ) + if (Sys_RandomBytes(string, len)) return; - Com_Printf( "Com_RandomBytes: using weak randomization\n" ); - for( i = 0; i < len; i++ ) - string[i] = (unsigned char)( rand() % 256 ); + Com_Printf("Com_RandomBytes: using weak randomization\n"); + for (i = 0; i < len; i++) + string[i] = (unsigned char)(rand() % 256); } /* @@ -2032,34 +1966,29 @@ void Com_RandomBytes( byte *string, int len ) Converts a UTF-8 character to UTF-32. =============== */ -uint32_t ConvertUTF8ToUTF32( char *utf8CurrentChar, char **utf8NextChar ) -{ +uint32_t ConvertUTF8ToUTF32(char *utf8CurrentChar, char **utf8NextChar) { uint32_t utf32 = 0; char *c = utf8CurrentChar; - if( ( *c & 0x80 ) == 0 ) + if ((*c & 0x80) == 0) utf32 = *c++; - else if( ( *c & 0xE0 ) == 0xC0 ) // 110x xxxx + else if ((*c & 0xE0) == 0xC0) // 110x xxxx { - utf32 |= ( *c++ & 0x1F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else if( ( *c & 0xF0 ) == 0xE0 ) // 1110 xxxx - { - utf32 |= ( *c++ & 0x0F ) << 12; - utf32 |= ( *c++ & 0x3F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else if( ( *c & 0xF8 ) == 0xF0 ) // 1111 0xxx + utf32 |= (*c++ & 0x1F) << 6; + utf32 |= (*c++ & 0x3F); + } else if ((*c & 0xF0) == 0xE0) // 1110 xxxx { - utf32 |= ( *c++ & 0x07 ) << 18; - utf32 |= ( *c++ & 0x3F ) << 12; - utf32 |= ( *c++ & 0x3F ) << 6; - utf32 |= ( *c++ & 0x3F ); - } - else + utf32 |= (*c++ & 0x0F) << 12; + utf32 |= (*c++ & 0x3F) << 6; + utf32 |= (*c++ & 0x3F); + } else if ((*c & 0xF8) == 0xF0) // 1111 0xxx { - Com_DPrintf( "Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c ); + utf32 |= (*c++ & 0x07) << 18; + utf32 |= (*c++ & 0x3F) << 12; + utf32 |= (*c++ & 0x3F) << 6; + utf32 |= (*c++ & 0x3F); + } else { + Com_DPrintf("Unrecognised UTF-8 lead byte: 0x%x\n", (unsigned int)*c); c++; } diff --git a/codemp/qcommon/cvar.cpp b/codemp/qcommon/cvar.cpp index 157cddeb2e..dbab9dd990 100644 --- a/codemp/qcommon/cvar.cpp +++ b/codemp/qcommon/cvar.cpp @@ -26,27 +26,25 @@ along with this program; if not, see . #include "qcommon/qcommon.h" -cvar_t *cvar_vars = NULL; -cvar_t *cvar_cheats; -uint32_t cvar_modifiedFlags; +cvar_t *cvar_vars = NULL; +cvar_t *cvar_cheats; +uint32_t cvar_modifiedFlags; -#define MAX_CVARS 8192 -cvar_t cvar_indexes[MAX_CVARS]; -int cvar_numIndexes; +#define MAX_CVARS 8192 +cvar_t cvar_indexes[MAX_CVARS]; +int cvar_numIndexes; -#define FILE_HASH_SIZE 512 -static cvar_t* hashTable[FILE_HASH_SIZE]; -static qboolean cvar_sort = qfalse; +#define FILE_HASH_SIZE 512 +static cvar_t *hashTable[FILE_HASH_SIZE]; +static qboolean cvar_sort = qfalse; static char *lastMemPool = NULL; static int memPoolSize; -//If the string came from the memory pool, don't really free it. The entire -//memory pool will be wiped during the next level load. -static void Cvar_FreeString(char *string) -{ - if(!lastMemPool || string < lastMemPool || - string >= lastMemPool + memPoolSize) { +// If the string came from the memory pool, don't really free it. The entire +// memory pool will be wiped during the next level load. +static void Cvar_FreeString(char *string) { + if (!lastMemPool || string < lastMemPool || string >= lastMemPool + memPoolSize) { Z_Free(string); } } @@ -56,19 +54,19 @@ static void Cvar_FreeString(char *string) return a hash value for the filename ================ */ -static long generateHashValue( const char *fname ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - hash+=(long)(letter)*(i+119); + hash += (long)(letter) * (i + 119); i++; } - hash &= (FILE_HASH_SIZE-1); + hash &= (FILE_HASH_SIZE - 1); return hash; } @@ -77,17 +75,17 @@ static long generateHashValue( const char *fname ) { Cvar_ValidateString ============ */ -static qboolean Cvar_ValidateString( const char *s ) { - if ( !s ) { +static qboolean Cvar_ValidateString(const char *s) { + if (!s) { return qfalse; } - if ( strchr( s, '\\' ) ) { + if (strchr(s, '\\')) { return qfalse; } - if ( strchr( s, '\"' ) ) { + if (strchr(s, '\"')) { return qfalse; } - if ( strchr( s, ';' ) ) { + if (strchr(s, ';')) { return qfalse; } return qtrue; @@ -98,13 +96,13 @@ static qboolean Cvar_ValidateString( const char *s ) { Cvar_FindVar ============ */ -static cvar_t *Cvar_FindVar( const char *var_name ) { - cvar_t *var; +static cvar_t *Cvar_FindVar(const char *var_name) { + cvar_t *var; long hash; hash = generateHashValue(var_name); - for (var=hashTable[hash] ; var ; var=var->hashNext) { + for (var = hashTable[hash]; var; var = var->hashNext) { if (!Q_stricmp(var_name, var->name)) { return var; } @@ -118,25 +116,24 @@ static cvar_t *Cvar_FindVar( const char *var_name ) { Cvar_VariableValue ============ */ -float Cvar_VariableValue( const char *var_name ) { - cvar_t *var; +float Cvar_VariableValue(const char *var_name) { + cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return 0; return var->value; } - /* ============ Cvar_VariableIntegerValue ============ */ -int Cvar_VariableIntegerValue( const char *var_name ) { - cvar_t *var; +int Cvar_VariableIntegerValue(const char *var_name) { + cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return 0; return var->integer; @@ -147,10 +144,10 @@ int Cvar_VariableIntegerValue( const char *var_name ) { Cvar_VariableString ============ */ -char *Cvar_VariableString( const char *var_name ) { +char *Cvar_VariableString(const char *var_name) { cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) return ""; return var->string; @@ -161,15 +158,14 @@ char *Cvar_VariableString( const char *var_name ) { Cvar_VariableStringBuffer ============ */ -void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { +void Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize) { cvar_t *var; - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) { *buffer = 0; - } - else { - Q_strncpyz( buffer, var->string, bufsize ); + } else { + Q_strncpyz(buffer, var->string, bufsize); } } @@ -178,12 +174,11 @@ void Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize Cvar_DescriptionString ============ */ -char *Cvar_DescriptionString( const char *var_name ) -{ +char *Cvar_DescriptionString(const char *var_name) { cvar_t *var; - var = Cvar_FindVar( var_name ); - if ( !var || !VALIDSTRING( var->description ) ) + var = Cvar_FindVar(var_name); + if (!var || !VALIDSTRING(var->description)) return ""; return var->description; } @@ -193,13 +188,13 @@ char *Cvar_DescriptionString( const char *var_name ) Cvar_Flags ============ */ -uint32_t Cvar_Flags( const char *var_name ) { +uint32_t Cvar_Flags(const char *var_name) { cvar_t *var; - if ( !(var = Cvar_FindVar( var_name )) ) + if (!(var = Cvar_FindVar(var_name))) return CVAR_NONEXISTENT; else { - if ( var->modified ) + if (var->modified) return var->flags | CVAR_MODIFIED; else return var->flags; @@ -211,16 +206,15 @@ uint32_t Cvar_Flags( const char *var_name ) { Cvar_CommandCompletion ============ */ -void Cvar_CommandCompletion( callbackFunc_t callback ) { - cvar_t *cvar; +void Cvar_CommandCompletion(callbackFunc_t callback) { + cvar_t *cvar; - for ( cvar = cvar_vars ; cvar ; cvar = cvar->next ) { + for (cvar = cvar_vars; cvar; cvar = cvar->next) { // Don't show internal cvars - if ( cvar->flags & CVAR_INTERNAL ) - { + if (cvar->flags & CVAR_INTERNAL) { continue; } - callback( cvar->name ); + callback(cvar->name); } } @@ -229,100 +223,84 @@ void Cvar_CommandCompletion( callbackFunc_t callback ) { Cvar_Validate ============ */ -static const char *Cvar_Validate( cvar_t *var, const char *value, qboolean warn ) -{ +static const char *Cvar_Validate(cvar_t *var, const char *value, qboolean warn) { static char s[MAX_CVAR_VALUE_STRING]; float valuef; qboolean changed = qfalse; - if( !var->validate ) + if (!var->validate) return value; - if( !value ) + if (!value) return value; - if( Q_isanumber( value ) ) - { - valuef = atof( value ); + if (Q_isanumber(value)) { + valuef = atof(value); - if( var->integral ) - { - if( !Q_isintegral( valuef ) ) - { - if( warn ) - Com_Printf( "WARNING: cvar '%s' must be integral", var->name ); + if (var->integral) { + if (!Q_isintegral(valuef)) { + if (warn) + Com_Printf("WARNING: cvar '%s' must be integral", var->name); valuef = (int)valuef; changed = qtrue; } } - } - else - { - if( warn ) - Com_Printf( "WARNING: cvar '%s' must be numeric", var->name ); + } else { + if (warn) + Com_Printf("WARNING: cvar '%s' must be numeric", var->name); - valuef = atof( var->resetString ); + valuef = atof(var->resetString); changed = qtrue; } - if( valuef < var->min ) - { - if( warn ) - { - if( changed ) - Com_Printf( " and is" ); + if (valuef < var->min) { + if (warn) { + if (changed) + Com_Printf(" and is"); else - Com_Printf( "WARNING: cvar '%s'", var->name ); + Com_Printf("WARNING: cvar '%s'", var->name); - if( Q_isintegral( var->min ) ) - Com_Printf( " out of range (min %d)", (int)var->min ); + if (Q_isintegral(var->min)) + Com_Printf(" out of range (min %d)", (int)var->min); else - Com_Printf( " out of range (min %f)", var->min ); + Com_Printf(" out of range (min %f)", var->min); } valuef = var->min; changed = qtrue; - } - else if( valuef > var->max ) - { - if( warn ) - { - if( changed ) - Com_Printf( " and is" ); + } else if (valuef > var->max) { + if (warn) { + if (changed) + Com_Printf(" and is"); else - Com_Printf( "WARNING: cvar '%s'", var->name ); + Com_Printf("WARNING: cvar '%s'", var->name); - if( Q_isintegral( var->max ) ) - Com_Printf( " out of range (max %d)", (int)var->max ); + if (Q_isintegral(var->max)) + Com_Printf(" out of range (max %d)", (int)var->max); else - Com_Printf( " out of range (max %f)", var->max ); + Com_Printf(" out of range (max %f)", var->max); } valuef = var->max; changed = qtrue; } - if( changed ) - { - if( Q_isintegral( valuef ) ) - { - Com_sprintf( s, sizeof( s ), "%d", (int)valuef ); + if (changed) { + if (Q_isintegral(valuef)) { + Com_sprintf(s, sizeof(s), "%d", (int)valuef); - if( warn ) - Com_Printf( ", setting to %d\n", (int)valuef ); - } - else - { - Com_sprintf( s, sizeof( s ), "%f", valuef ); + if (warn) + Com_Printf(", setting to %d\n", (int)valuef); + } else { + Com_sprintf(s, sizeof(s), "%f", valuef); - if( warn ) - Com_Printf( ", setting to %f\n", valuef ); + if (warn) + Com_Printf(", setting to %f\n", valuef); } return s; - } - else + } else return value; } @@ -334,57 +312,52 @@ If the variable already exists, the value will not be set unless CVAR_ROM The flags will be or'ed in if the variable exists. ============ */ -cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, const char *var_desc ) { - cvar_t *var; - long hash; - int index; +cvar_t *Cvar_Get(const char *var_name, const char *var_value, uint32_t flags, const char *var_desc) { + cvar_t *var; + long hash; + int index; - if ( !var_name || ! var_value ) { - Com_Error( ERR_FATAL, "Cvar_Get: NULL parameter" ); - } + if (!var_name || !var_value) { + Com_Error(ERR_FATAL, "Cvar_Get: NULL parameter"); + } - if ( !Cvar_ValidateString( var_name ) ) { - Com_Printf("invalid cvar name string: %s\n", var_name ); + if (!Cvar_ValidateString(var_name)) { + Com_Printf("invalid cvar name string: %s\n", var_name); var_name = "BADNAME"; } -#if 0 // FIXME: values with backslash happen +#if 0 // FIXME: values with backslash happen if ( !Cvar_ValidateString( var_value ) ) { Com_Printf("invalid cvar value string: %s\n", var_value ); var_value = "BADVALUE"; } #endif - var = Cvar_FindVar (var_name); - if ( var ) { + var = Cvar_FindVar(var_name); + if (var) { var_value = Cvar_Validate(var, var_value, qfalse); // Make sure the game code cannot mark engine-added variables as gamecode vars - if(var->flags & CVAR_VM_CREATED) - { - if(!(flags & CVAR_VM_CREATED)) + if (var->flags & CVAR_VM_CREATED) { + if (!(flags & CVAR_VM_CREATED)) var->flags &= ~CVAR_VM_CREATED; - } - else if (!(var->flags & CVAR_USER_CREATED)) - { - if(flags & CVAR_VM_CREATED) + } else if (!(var->flags & CVAR_USER_CREATED)) { + if (flags & CVAR_VM_CREATED) flags &= ~CVAR_VM_CREATED; } // if the C code is now specifying a variable that the user already // set a value for, take the new value as the reset value - if ( var->flags & CVAR_USER_CREATED ) - { + if (var->flags & CVAR_USER_CREATED) { var->flags &= ~CVAR_USER_CREATED; - Cvar_FreeString( var->resetString ); - var->resetString = CopyString( var_value ); + Cvar_FreeString(var->resetString); + var->resetString = CopyString(var_value); - if(flags & CVAR_ROM) - { + if (flags & CVAR_ROM) { // this variable was set by the user, // so force it to value given by the engine. - if(var->latchedString) + if (var->latchedString) Cvar_FreeString(var->latchedString); var->latchedString = CopyString(var_value); @@ -392,43 +365,38 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, c } // Make sure servers cannot mark engine-added variables as SERVER_CREATED - if(var->flags & CVAR_SERVER_CREATED) - { - if(!(flags & CVAR_SERVER_CREATED)) + if (var->flags & CVAR_SERVER_CREATED) { + if (!(flags & CVAR_SERVER_CREATED)) var->flags &= ~CVAR_SERVER_CREATED; - } - else - { - if(flags & CVAR_SERVER_CREATED) + } else { + if (flags & CVAR_SERVER_CREATED) flags &= ~CVAR_SERVER_CREATED; } var->flags |= flags; // only allow one non-empty reset string without a warning - if ( !var->resetString[0] ) { + if (!var->resetString[0]) { // we don't have a reset string yet - Cvar_FreeString( var->resetString ); - var->resetString = CopyString( var_value ); - } else if ( var_value[0] && strcmp( var->resetString, var_value ) ) { - Com_DPrintf( S_COLOR_YELLOW "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n", - var_name, var->resetString, var_value ); + Cvar_FreeString(var->resetString); + var->resetString = CopyString(var_value); + } else if (var_value[0] && strcmp(var->resetString, var_value)) { + Com_DPrintf(S_COLOR_YELLOW "Warning: cvar \"%s\" given initial values: \"%s\" and \"%s\"\n", var_name, var->resetString, var_value); } // if we have a latched string, take that value now - if ( var->latchedString ) { + if (var->latchedString) { char *s; s = var->latchedString; - var->latchedString = NULL; // otherwise cvar_set2 would free it - Cvar_Set2( var_name, s, 0, qtrue ); - Cvar_FreeString( s ); + var->latchedString = NULL; // otherwise cvar_set2 would free it + Cvar_Set2(var_name, s, 0, qtrue); + Cvar_FreeString(s); } - if ( var_desc && var_desc[0] != '\0' ) - { - if(var->description ) - Cvar_FreeString( var->description ); - var->description = CopyString( var_desc ); + if (var_desc && var_desc[0] != '\0') { + if (var->description) + Cvar_FreeString(var->description); + var->description = CopyString(var_desc); } // ZOID--needs to be set so that cvars the game sets as @@ -443,15 +411,13 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, c // // find a free cvar - for(index = 0; index < MAX_CVARS; index++) - { - if(!cvar_indexes[index].name) + for (index = 0; index < MAX_CVARS; index++) { + if (!cvar_indexes[index].name) break; } - if(index >= MAX_CVARS) - { - if(!com_errorEntered) + if (index >= MAX_CVARS) { + if (!com_errorEntered) Com_Error(ERR_FATAL, "Error: Too many cvars, cannot create a new one!"); return NULL; @@ -459,25 +425,25 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, c var = &cvar_indexes[index]; - if(index >= cvar_numIndexes) + if (index >= cvar_numIndexes) cvar_numIndexes = index + 1; - var->name = CopyString (var_name); - var->string = CopyString (var_value); - if ( var_desc && var_desc[0] != '\0' ) - var->description = CopyString( var_desc ); + var->name = CopyString(var_name); + var->string = CopyString(var_value); + if (var_desc && var_desc[0] != '\0') + var->description = CopyString(var_desc); else var->description = NULL; var->modified = qtrue; var->modificationCount = 1; - var->value = atof (var->string); + var->value = atof(var->string); var->integer = atoi(var->string); - var->resetString = CopyString( var_value ); + var->resetString = CopyString(var_value); var->validate = qfalse; // link the variable in var->next = cvar_vars; - if(cvar_vars) + if (cvar_vars) cvar_vars->prev = var; var->prev = NULL; @@ -491,7 +457,7 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, c var->hashIndex = hash; var->hashNext = hashTable[hash]; - if(hashTable[hash]) + if (hashTable[hash]) hashTable[hash]->hashPrev = var; var->hashPrev = NULL; @@ -503,63 +469,64 @@ cvar_t *Cvar_Get( const char *var_name, const char *var_value, uint32_t flags, c return var; } -static void Cvar_QSortByName( cvar_t **a, int n ) -{ +static void Cvar_QSortByName(cvar_t **a, int n) { cvar_t *temp; cvar_t *m; - int i, j; + int i, j; i = 0; j = n; - m = a[ n>>1 ]; + m = a[n >> 1]; do { // sort in descending order - while ( strcmp( a[i]->name, m->name ) > 0 ) i++; - while ( strcmp( a[j]->name, m->name ) < 0 ) j--; + while (strcmp(a[i]->name, m->name) > 0) + i++; + while (strcmp(a[j]->name, m->name) < 0) + j--; - if ( i <= j ) { - temp = a[i]; - a[i] = a[j]; + if (i <= j) { + temp = a[i]; + a[i] = a[j]; a[j] = temp; - i++; + i++; j--; } - } while ( i <= j ); + } while (i <= j); - if ( j > 0 ) Cvar_QSortByName( a, j ); - if ( n > i ) Cvar_QSortByName( a+i, n-i ); + if (j > 0) + Cvar_QSortByName(a, j); + if (n > i) + Cvar_QSortByName(a + i, n - i); } - -static void Cvar_Sort( void ) -{ - cvar_t *list[ MAX_CVARS ], *var; +static void Cvar_Sort(void) { + cvar_t *list[MAX_CVARS], *var; int count; int i; - for ( count = 0, var = cvar_vars; var; var = var->next ) { - if ( var->name ) { - list[ count++ ] = var; + for (count = 0, var = cvar_vars; var; var = var->next) { + if (var->name) { + list[count++] = var; } else { - Com_Error( ERR_FATAL, "Cvar_Sort: NULL cvar name" ); + Com_Error(ERR_FATAL, "Cvar_Sort: NULL cvar name"); } } - if ( count < 2 ) { + if (count < 2) { return; // nothing to sort } - Cvar_QSortByName( &list[0], count-1 ); - + Cvar_QSortByName(&list[0], count - 1); + cvar_vars = NULL; // relink cvars - for ( i = 0; i < count; i++ ) { - var = list[ i ]; + for (i = 0; i < count; i++) { + var = list[i]; // link the variable in var->next = cvar_vars; - if ( cvar_vars ) + if (cvar_vars) cvar_vars->prev = var; var->prev = NULL; cvar_vars = var; @@ -573,23 +540,23 @@ Cvar_Print Prints the value, default, and latched string of the given variable ============ */ -void Cvar_Print( cvar_t *v ) { - Com_Printf( S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->name, v->string ); +void Cvar_Print(cvar_t *v) { + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->name, v->string); - if ( !(v->flags & CVAR_ROM) ) { - if ( !Q_stricmp( v->string, v->resetString ) ) - Com_Printf( ", " S_COLOR_WHITE "the default" ); + if (!(v->flags & CVAR_ROM)) { + if (!Q_stricmp(v->string, v->resetString)) + Com_Printf(", " S_COLOR_WHITE "the default"); else - Com_Printf( ", " S_COLOR_WHITE "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->resetString ); + Com_Printf(", " S_COLOR_WHITE "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, v->resetString); } - Com_Printf( "\n" ); + Com_Printf("\n"); - if ( v->latchedString ) - Com_Printf( " latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"\n", v->latchedString ); + if (v->latchedString) + Com_Printf(" latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"\n", v->latchedString); - if ( v->description ) - Com_Printf( "%s\n", v->description ); + if (v->description) + Com_Printf("%s\n", v->description); } /* @@ -597,121 +564,106 @@ void Cvar_Print( cvar_t *v ) { Cvar_Set2 ============ */ -cvar_t *Cvar_Set2( const char *var_name, const char *value, uint32_t defaultFlags, qboolean force ) { - cvar_t *var; +cvar_t *Cvar_Set2(const char *var_name, const char *value, uint32_t defaultFlags, qboolean force) { + cvar_t *var; - if ( !Cvar_ValidateString( var_name ) ) { - Com_Printf("invalid cvar name string: %s\n", var_name ); + if (!Cvar_ValidateString(var_name)) { + Com_Printf("invalid cvar name string: %s\n", var_name); var_name = "BADNAME"; } -#if 0 // FIXME +#if 0 // FIXME if ( value && !Cvar_ValidateString( value ) ) { Com_Printf("invalid cvar value string: %s\n", value ); var_value = "BADVALUE"; } #endif - var = Cvar_FindVar (var_name); + var = Cvar_FindVar(var_name); if (!var) { - if ( !value ) { + if (!value) { return NULL; } // create it - return Cvar_Get( var_name, value, defaultFlags ); + return Cvar_Get(var_name, value, defaultFlags); } - if (!value ) { + if (!value) { value = var->resetString; } value = Cvar_Validate(var, value, qtrue); - if((var->flags & CVAR_LATCH) && var->latchedString) - { - if(!strcmp(value, var->string)) - { + if ((var->flags & CVAR_LATCH) && var->latchedString) { + if (!strcmp(value, var->string)) { Cvar_FreeString(var->latchedString); var->latchedString = NULL; return var; } - if(!strcmp(value, var->latchedString)) + if (!strcmp(value, var->latchedString)) return var; - } - else if(!strcmp(value, var->string)) + } else if (!strcmp(value, var->string)) return var; // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) cvar_modifiedFlags |= var->flags; - if (!force) - { - if ( (var->flags & (CVAR_SYSTEMINFO|CVAR_SERVER_CREATED)) && CL_ConnectedToRemoteServer() ) - { - Com_Printf ("%s can only be set by server.\n", var_name); + if (!force) { + if ((var->flags & (CVAR_SYSTEMINFO | CVAR_SERVER_CREATED)) && CL_ConnectedToRemoteServer()) { + Com_Printf("%s can only be set by server.\n", var_name); return var; } - if (var->flags & CVAR_ROM) - { - Com_Printf ("%s is read only.\n", var_name); + if (var->flags & CVAR_ROM) { + Com_Printf("%s is read only.\n", var_name); return var; } - if (var->flags & CVAR_INIT) - { - Com_Printf ("%s is write protected.\n", var_name); + if (var->flags & CVAR_INIT) { + Com_Printf("%s is write protected.\n", var_name); return var; } - if (var->flags & CVAR_LATCH) - { - if (var->latchedString) - { + if (var->flags & CVAR_LATCH) { + if (var->latchedString) { if (strcmp(value, var->latchedString) == 0) return var; - Cvar_FreeString (var->latchedString); - } - else - { + Cvar_FreeString(var->latchedString); + } else { if (strcmp(value, var->string) == 0) return var; } - Com_Printf ("%s will be changed upon restarting.\n", var_name); + Com_Printf("%s will be changed upon restarting.\n", var_name); var->latchedString = CopyString(value); var->modified = qtrue; var->modificationCount++; return var; } - if ( (var->flags & CVAR_CHEAT) && !cvar_cheats->integer ) - { - Com_Printf ("%s is cheat protected.\n", var_name); + if ((var->flags & CVAR_CHEAT) && !cvar_cheats->integer) { + Com_Printf("%s is cheat protected.\n", var_name); return var; } - } - else - { - if (var->latchedString) - { - Cvar_FreeString (var->latchedString); + } else { + if (var->latchedString) { + Cvar_FreeString(var->latchedString); var->latchedString = NULL; } } if (!strcmp(value, var->string)) - return var; // not changed + return var; // not changed var->modified = qtrue; var->modificationCount++; - Cvar_FreeString (var->string); // free the old value string + Cvar_FreeString(var->string); // free the old value string var->string = CopyString(value); - var->value = atof (var->string); - var->integer = atoi (var->string); + var->value = atof(var->string); + var->integer = atoi(var->string); return var; } @@ -723,9 +675,7 @@ Cvar_Set Force cvar to a value ============ */ -cvar_t *Cvar_Set( const char *var_name, const char *value) { - return Cvar_Set2 (var_name, value, 0, qtrue); -} +cvar_t *Cvar_Set(const char *var_name, const char *value) { return Cvar_Set2(var_name, value, 0, qtrue); } /* ============ @@ -734,9 +684,7 @@ Cvar_SetSafe Try to set cvar to a value. respects CVAR_ROM, etc. ============ */ -cvar_t *Cvar_SetSafe( const char *var_name, const char *value) { - return Cvar_Set2 (var_name, value, 0, qfalse); -} +cvar_t *Cvar_SetSafe(const char *var_name, const char *value) { return Cvar_Set2(var_name, value, 0, qfalse); } /* ============ @@ -745,28 +693,16 @@ Cvar_User_Set Same as Cvar_SetSafe, but have new cvars have user created flag. ============ */ -cvar_t *Cvar_User_Set( const char *var_name, const char *value) { - return Cvar_Set2 (var_name, value, CVAR_USER_CREATED, qfalse); -} +cvar_t *Cvar_User_Set(const char *var_name, const char *value) { return Cvar_Set2(var_name, value, CVAR_USER_CREATED, qfalse); } static const char *legacyCvars[] = { - "bg_fighterAltControl", - "g_dlURL", - "g_synchronousClients", - "jp_DlBaseURL", - "pmove_fixed", - "pmove_float", - "pmove_msec", - "vm_cgame", - "vm_game", - "vm_ui" -}; - -static const size_t numLegacyCvars = ARRAY_LEN( legacyCvars ); - -static bool FindLegacyCvar( const char *var_name ) { - for ( size_t i=0; inext ) { - if ( var->flags & CVAR_CHEAT ) { + for (var = cvar_vars; var; var = var->next) { + if (var->flags & CVAR_CHEAT) { // the CVAR_LATCHED|CVAR_CHEAT vars might escape the reset here // because of a different var->latchedString - if (var->latchedString) - { + if (var->latchedString) { Cvar_FreeString(var->latchedString); var->latchedString = NULL; } - if (strcmp(var->resetString,var->string)) { - Cvar_Set( var->name, var->resetString ); + if (strcmp(var->resetString, var->string)) { + Cvar_Set(var->name, var->resetString); } } } @@ -936,32 +861,30 @@ Cvar_Command Handles variable inspection and changing from the console ============ */ -qboolean Cvar_Command( void ) { - cvar_t *v; +qboolean Cvar_Command(void) { + cvar_t *v; // check variables - v = Cvar_FindVar (Cmd_Argv(0)); + v = Cvar_FindVar(Cmd_Argv(0)); if (!v) { return qfalse; } // perform a variable print or set - if ( Cmd_Argc() == 1 ) - { - Cvar_Print( v ); + if (Cmd_Argc() == 1) { + Cvar_Print(v); return qtrue; } // toggle - if( !strcmp( Cmd_Argv(1), "!" ) ) - { + if (!strcmp(Cmd_Argv(1), "!")) { // Swap the value if our command has ! in it (bind p "cg_thirdPeson !") - Cvar_User_SetValue( v->name, !v->value ); + Cvar_User_SetValue(v->name, !v->value); return qtrue; } // set the value if forcing isn't required - Cvar_User_Set (v->name, Cmd_Args()); + Cvar_User_Set(v->name, Cmd_Args()); return qtrue; } @@ -973,14 +896,12 @@ Prints the contents of a cvar (preferred over Cvar_Command where cvar names and commands conflict) ============ */ -void Cvar_Print_f(void) -{ +void Cvar_Print_f(void) { char *name; cvar_t *cv; - if(Cmd_Argc() != 2) - { - Com_Printf ("usage: print \n"); + if (Cmd_Argc() != 2) { + Com_Printf("usage: print \n"); return; } @@ -988,10 +909,10 @@ void Cvar_Print_f(void) cv = Cvar_FindVar(name); - if(cv) + if (cv) Cvar_Print(cv); else - Com_Printf ("Cvar %s does not exist.\n", name); + Com_Printf("Cvar %s does not exist.\n", name); } /* @@ -1002,21 +923,21 @@ Toggles a cvar for easy single key binding, optionally through a list of given values ============ */ -void Cvar_Toggle_f( void ) { - int i, c = Cmd_Argc(); - char *curval; +void Cvar_Toggle_f(void) { + int i, c = Cmd_Argc(); + char *curval; - if(c < 2) { + if (c < 2) { Com_Printf("usage: toggle [value1, value2, ...]\n"); return; } - if(c == 2) { + if (c == 2) { Cvar_User_SetValue(Cmd_Argv(1), !Cvar_VariableValue(Cmd_Argv(1))); return; } - if(c == 3) { + if (c == 3) { Com_Printf("toggle: nothing to toggle to\n"); return; } @@ -1025,8 +946,8 @@ void Cvar_Toggle_f( void ) { // don't bother checking the last arg for a match since the desired // behaviour is the same as no match (set to the first argument) - for(i = 2; i + 1 < c; i++) { - if(strcmp(curval, Cmd_Argv(i)) == 0) { + for (i = 2; i + 1 < c; i++) { + if (strcmp(curval, Cmd_Argv(i)) == 0) { Cvar_User_Set(Cmd_Argv(1), Cmd_Argv(i + 1)); return; } @@ -1044,46 +965,46 @@ Allows setting and defining of arbitrary cvars from console, even if they weren't declared in C code. ============ */ -void Cvar_Set_f( void ) { - int c; - char *cmd; - cvar_t *v; +void Cvar_Set_f(void) { + int c; + char *cmd; + cvar_t *v; c = Cmd_Argc(); cmd = Cmd_Argv(0); - if ( c < 2 ) { - Com_Printf ("usage: %s \n", cmd); + if (c < 2) { + Com_Printf("usage: %s \n", cmd); return; } - if ( c == 2 ) { + if (c == 2) { Cvar_Print_f(); return; } - v = Cvar_User_Set (Cmd_Argv(1), Cmd_ArgsFrom(2)); - if( !v ) { + v = Cvar_User_Set(Cmd_Argv(1), Cmd_ArgsFrom(2)); + if (!v) { return; } - switch( cmd[3] ) { - case 'a': - if( !( v->flags & CVAR_ARCHIVE ) ) { - v->flags |= CVAR_ARCHIVE; - cvar_modifiedFlags |= CVAR_ARCHIVE; - } - break; - case 'u': - if( !( v->flags & CVAR_USERINFO ) ) { - v->flags |= CVAR_USERINFO; - cvar_modifiedFlags |= CVAR_USERINFO; - } - break; - case 's': - if( !( v->flags & CVAR_SERVERINFO ) ) { - v->flags |= CVAR_SERVERINFO; - cvar_modifiedFlags |= CVAR_SERVERINFO; - } - break; + switch (cmd[3]) { + case 'a': + if (!(v->flags & CVAR_ARCHIVE)) { + v->flags |= CVAR_ARCHIVE; + cvar_modifiedFlags |= CVAR_ARCHIVE; + } + break; + case 'u': + if (!(v->flags & CVAR_USERINFO)) { + v->flags |= CVAR_USERINFO; + cvar_modifiedFlags |= CVAR_USERINFO; + } + break; + case 's': + if (!(v->flags & CVAR_SERVERINFO)) { + v->flags |= CVAR_SERVERINFO; + cvar_modifiedFlags |= CVAR_SERVERINFO; + } + break; } } @@ -1092,43 +1013,32 @@ void Cvar_Set_f( void ) { Cvar_Math_f ============ */ -void Cvar_Math_f( void ) -{ - int c; - char *cmd; +void Cvar_Math_f(void) { + int c; + char *cmd; c = Cmd_Argc(); - cmd = Cmd_Argv( 0 ); + cmd = Cmd_Argv(0); - if ( c != 3 ) - { - Com_Printf( "usage: %s \n", cmd ); + if (c != 3) { + Com_Printf("usage: %s \n", cmd); return; } - if ( !Q_stricmp( cmd, "cvarAdd" ) ) - { - Cvar_User_SetValue( Cmd_Argv( 1 ), Cvar_VariableValue( Cmd_Argv( 1 ) ) + atof( Cmd_Argv( 2 ) ) ); - } - else if ( !Q_stricmp( cmd, "cvarSub" ) ) - { - Cvar_User_SetValue( Cmd_Argv( 1 ), Cvar_VariableValue( Cmd_Argv( 1 ) ) - atof( Cmd_Argv( 2 ) ) ); - } - else if ( !Q_stricmp( cmd, "cvarMult" ) ) - { - Cvar_User_SetValue( Cmd_Argv( 1 ), Cvar_VariableValue( Cmd_Argv( 1 ) ) * atof( Cmd_Argv( 2 ) ) ); - } - else if ( !Q_stricmp( cmd, "cvarDiv" ) ) - { - float value = atof( Cmd_Argv( 2 ) ); - if ( value != 0 ) - Cvar_User_SetValue( Cmd_Argv( 1 ), Cvar_VariableValue( Cmd_Argv( 1 ) ) / value ); + if (!Q_stricmp(cmd, "cvarAdd")) { + Cvar_User_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) + atof(Cmd_Argv(2))); + } else if (!Q_stricmp(cmd, "cvarSub")) { + Cvar_User_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) - atof(Cmd_Argv(2))); + } else if (!Q_stricmp(cmd, "cvarMult")) { + Cvar_User_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) * atof(Cmd_Argv(2))); + } else if (!Q_stricmp(cmd, "cvarDiv")) { + float value = atof(Cmd_Argv(2)); + if (value != 0) + Cvar_User_SetValue(Cmd_Argv(1), Cvar_VariableValue(Cmd_Argv(1)) / value); else - Com_Printf( "Cannot divide by zero!\n" ); - } - else if ( !Q_stricmp( cmd, "cvarMod" ) ) - { - Cvar_User_SetValue( Cmd_Argv( 1 ), Cvar_VariableIntegerValue( Cmd_Argv( 1 ) ) % atoi( Cmd_Argv( 2 ) ) ); + Com_Printf("Cannot divide by zero!\n"); + } else if (!Q_stricmp(cmd, "cvarMod")) { + Cvar_User_SetValue(Cmd_Argv(1), Cvar_VariableIntegerValue(Cmd_Argv(1)) % atoi(Cmd_Argv(2))); } } @@ -1137,12 +1047,12 @@ void Cvar_Math_f( void ) Cvar_Reset_f ============ */ -void Cvar_Reset_f( void ) { - if ( Cmd_Argc() != 2 ) { - Com_Printf ("usage: reset \n"); +void Cvar_Reset_f(void) { + if (Cmd_Argc() != 2) { + Com_Printf("usage: reset \n"); return; } - Cvar_Reset( Cmd_Argv( 1 ) ); + Cvar_Reset(Cmd_Argv(1)); } /* @@ -1153,45 +1063,46 @@ Appends lines containing "set variable value" for all variables with the archive flag set to qtrue. ============ */ -void Cvar_WriteVariables( fileHandle_t f ) { - cvar_t *var; +void Cvar_WriteVariables(fileHandle_t f) { + cvar_t *var; char buffer[1024]; - if ( cvar_sort ) { - Com_DPrintf( "Cvar_Sort: sort cvars\n" ); + if (cvar_sort) { + Com_DPrintf("Cvar_Sort: sort cvars\n"); cvar_sort = qfalse; Cvar_Sort(); } - for ( var = cvar_vars; var; var = var->next ) - { - if ( !var->name || Q_stricmp( var->name, "cl_cdkey" ) == 0 ) + for (var = cvar_vars; var; var = var->next) { + if (!var->name || Q_stricmp(var->name, "cl_cdkey") == 0) continue; - if ( var->flags & CVAR_ARCHIVE ) { + if (var->flags & CVAR_ARCHIVE) { // write the latched value, even if it hasn't taken effect yet - if ( var->latchedString ) { - if( strlen( var->name ) + strlen( var->latchedString ) + 10 > sizeof( buffer ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: value of variable " - "\"%s\" too long to write to file\n", var->name ); + if (var->latchedString) { + if (strlen(var->name) + strlen(var->latchedString) + 10 > sizeof(buffer)) { + Com_Printf(S_COLOR_YELLOW "WARNING: value of variable " + "\"%s\" too long to write to file\n", + var->name); continue; } - if ( (var->flags & CVAR_NODEFAULT) && !strcmp( var->latchedString, var->resetString ) ) { + if ((var->flags & CVAR_NODEFAULT) && !strcmp(var->latchedString, var->resetString)) { continue; } - Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString); + Com_sprintf(buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->latchedString); } else { - if( strlen( var->name ) + strlen( var->string ) + 10 > sizeof( buffer ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: value of variable " - "\"%s\" too long to write to file\n", var->name ); + if (strlen(var->name) + strlen(var->string) + 10 > sizeof(buffer)) { + Com_Printf(S_COLOR_YELLOW "WARNING: value of variable " + "\"%s\" too long to write to file\n", + var->name); continue; } - if ( (var->flags & CVAR_NODEFAULT) && !strcmp( var->string, var->resetString ) ) { + if ((var->flags & CVAR_NODEFAULT) && !strcmp(var->string, var->resetString)) { continue; } - Com_sprintf (buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string); + Com_sprintf(buffer, sizeof(buffer), "seta %s \"%s\"\n", var->name, var->string); } - FS_Write( buffer, strlen( buffer ), f ); + FS_Write(buffer, strlen(buffer), f); } } } @@ -1201,84 +1112,99 @@ void Cvar_WriteVariables( fileHandle_t f ) { Cvar_List_f ============ */ -void Cvar_List_f( void ) { +void Cvar_List_f(void) { cvar_t *var = NULL; int i = 0; char *match = NULL; - if ( Cmd_Argc() > 1 ) - match = Cmd_Argv( 1 ); + if (Cmd_Argc() > 1) + match = Cmd_Argv(1); - for ( var=cvar_vars, i=0; - var; - var=var->next, i++ ) - { - if ( !var->name || (match && !Com_Filter( match, var->name, qfalse )) ) + for (var = cvar_vars, i = 0; var; var = var->next, i++) { + if (!var->name || (match && !Com_Filter(match, var->name, qfalse))) continue; - if (var->flags & CVAR_SERVERINFO) Com_Printf( "S" ); else Com_Printf( " " ); - if (var->flags & CVAR_SYSTEMINFO) Com_Printf( "s" ); else Com_Printf( " " ); - if (var->flags & CVAR_USERINFO) Com_Printf( "U" ); else Com_Printf( " " ); - if (var->flags & CVAR_ROM) Com_Printf( "R" ); else Com_Printf( " " ); - if (var->flags & CVAR_INIT) Com_Printf( "I" ); else Com_Printf( " " ); - if (var->flags & CVAR_ARCHIVE) Com_Printf( "A" ); else Com_Printf( " " ); - if (var->flags & CVAR_LATCH) Com_Printf( "L" ); else Com_Printf( " " ); - if (var->flags & CVAR_CHEAT) Com_Printf( "C" ); else Com_Printf( " " ); - if (var->flags & CVAR_USER_CREATED) Com_Printf( "?" ); else Com_Printf( " " ); - - Com_Printf( S_COLOR_WHITE " %s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->name, var->string ); - if ( var->latchedString ) - Com_Printf( ", latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->latchedString ); - Com_Printf( "\n" ); - } - - Com_Printf( "\n%i total cvars\n", i ); - if ( i != cvar_numIndexes ) - Com_Printf( "%i cvar indexes\n", cvar_numIndexes ); + if (var->flags & CVAR_SERVERINFO) + Com_Printf("S"); + else + Com_Printf(" "); + if (var->flags & CVAR_SYSTEMINFO) + Com_Printf("s"); + else + Com_Printf(" "); + if (var->flags & CVAR_USERINFO) + Com_Printf("U"); + else + Com_Printf(" "); + if (var->flags & CVAR_ROM) + Com_Printf("R"); + else + Com_Printf(" "); + if (var->flags & CVAR_INIT) + Com_Printf("I"); + else + Com_Printf(" "); + if (var->flags & CVAR_ARCHIVE) + Com_Printf("A"); + else + Com_Printf(" "); + if (var->flags & CVAR_LATCH) + Com_Printf("L"); + else + Com_Printf(" "); + if (var->flags & CVAR_CHEAT) + Com_Printf("C"); + else + Com_Printf(" "); + if (var->flags & CVAR_USER_CREATED) + Com_Printf("?"); + else + Com_Printf(" "); + + Com_Printf(S_COLOR_WHITE " %s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->name, var->string); + if (var->latchedString) + Com_Printf(", latched = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE, var->latchedString); + Com_Printf("\n"); + } + + Com_Printf("\n%i total cvars\n", i); + if (i != cvar_numIndexes) + Com_Printf("%i cvar indexes\n", cvar_numIndexes); } -void Cvar_ListModified_f( void ) { +void Cvar_ListModified_f(void) { cvar_t *var = NULL; // build a list of cvars that are modified - for ( var=cvar_vars; - var; - var=var->next ) - { + for (var = cvar_vars; var; var = var->next) { char *value = var->latchedString ? var->latchedString : var->string; - if ( !var->name || !var->modificationCount || !strcmp( value, var->resetString ) ) + if (!var->name || !var->modificationCount || !strcmp(value, var->resetString)) continue; - Com_Printf( S_COLOR_GREY "Cvar " - S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE ", " - S_COLOR_WHITE "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", - var->name, value, var->resetString ); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE ", " S_COLOR_WHITE + "default = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", + var->name, value, var->resetString); } } -void Cvar_ListUserCreated_f( void ) { +void Cvar_ListUserCreated_f(void) { cvar_t *var = NULL; uint32_t count = 0; // build a list of cvars that are modified - for ( var=cvar_vars; - var; - var=var->next ) - { + for (var = cvar_vars; var; var = var->next) { char *value = var->latchedString ? var->latchedString : var->string; - if ( !(var->flags & CVAR_USER_CREATED) ) + if (!(var->flags & CVAR_USER_CREATED)) continue; - Com_Printf( S_COLOR_GREY "Cvar " - S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", - var->name, value ); + Com_Printf(S_COLOR_GREY "Cvar " S_COLOR_WHITE "%s = " S_COLOR_GREY "\"" S_COLOR_WHITE "%s" S_COLOR_GREY "\"" S_COLOR_WHITE "\n", var->name, value); count++; } - if ( count > 0 ) - Com_Printf( S_COLOR_GREY "Showing " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count ); + if (count > 0) + Com_Printf(S_COLOR_GREY "Showing " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count); else - Com_Printf( S_COLOR_GREY "No user created cvars" S_COLOR_WHITE "\n" ); + Com_Printf(S_COLOR_GREY "No user created cvars" S_COLOR_WHITE "\n"); } /* @@ -1289,36 +1215,35 @@ Unsets a cvar ============ */ -cvar_t *Cvar_Unset(cvar_t *cv) -{ +cvar_t *Cvar_Unset(cvar_t *cv) { cvar_t *next = cv->next; // note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) cvar_modifiedFlags |= cv->flags; - if(cv->name) + if (cv->name) Cvar_FreeString(cv->name); - if(cv->description) + if (cv->description) Cvar_FreeString(cv->description); - if(cv->string) + if (cv->string) Cvar_FreeString(cv->string); - if(cv->latchedString) + if (cv->latchedString) Cvar_FreeString(cv->latchedString); - if(cv->resetString) + if (cv->resetString) Cvar_FreeString(cv->resetString); - if(cv->prev) + if (cv->prev) cv->prev->next = cv->next; else cvar_vars = cv->next; - if(cv->next) + if (cv->next) cv->next->prev = cv->prev; - if(cv->hashPrev) + if (cv->hashPrev) cv->hashPrev->hashNext = cv->hashNext; else hashTable[cv->hashIndex] = cv->hashNext; - if(cv->hashNext) + if (cv->hashNext) cv->hashNext->hashPrev = cv->hashPrev; memset(cv, 0, sizeof(*cv)); @@ -1334,48 +1259,43 @@ Unsets a userdefined cvar ============ */ -void Cvar_Unset_f(void) -{ +void Cvar_Unset_f(void) { cvar_t *cv; - if(Cmd_Argc() != 2) - { + if (Cmd_Argc() != 2) { Com_Printf("Usage: %s \n", Cmd_Argv(0)); return; } cv = Cvar_FindVar(Cmd_Argv(1)); - if(!cv) + if (!cv) return; - if(cv->flags & CVAR_USER_CREATED) + if (cv->flags & CVAR_USER_CREATED) Cvar_Unset(cv); else Com_Printf("Error: %s: Variable %s is not user created.\n", Cmd_Argv(0), cv->name); } -void Cvar_UnsetUserCreated_f(void) -{ - cvar_t *curvar = cvar_vars; +void Cvar_UnsetUserCreated_f(void) { + cvar_t *curvar = cvar_vars; uint32_t count = 0; - while ( curvar ) - { - if ( ( curvar->flags & CVAR_USER_CREATED ) ) - { + while (curvar) { + if ((curvar->flags & CVAR_USER_CREATED)) { // throw out any variables the user created - curvar = Cvar_Unset( curvar ); + curvar = Cvar_Unset(curvar); count++; continue; } curvar = curvar->next; } - if ( count > 0 ) - Com_Printf( S_COLOR_GREY "Removed " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count ); + if (count > 0) + Com_Printf(S_COLOR_GREY "Removed " S_COLOR_WHITE "%u" S_COLOR_GREY " user created cvars" S_COLOR_WHITE "\n", count); else - Com_Printf( S_COLOR_GREY "No user created cvars to remove" S_COLOR_WHITE "\n" ); + Com_Printf(S_COLOR_GREY "No user created cvars to remove" S_COLOR_WHITE "\n"); } /* @@ -1387,24 +1307,19 @@ and variables added via the VMs if requested. ============ */ -void Cvar_Restart(qboolean unsetVM) -{ - cvar_t *curvar; +void Cvar_Restart(qboolean unsetVM) { + cvar_t *curvar; curvar = cvar_vars; - while(curvar) - { - if((curvar->flags & CVAR_USER_CREATED) || - (unsetVM && (curvar->flags & CVAR_VM_CREATED))) - { + while (curvar) { + if ((curvar->flags & CVAR_USER_CREATED) || (unsetVM && (curvar->flags & CVAR_VM_CREATED))) { // throw out any variables the user/vm created curvar = Cvar_Unset(curvar); continue; } - if(!(curvar->flags & (CVAR_ROM | CVAR_INIT | CVAR_NORESTART))) - { + if (!(curvar->flags & (CVAR_ROM | CVAR_INIT | CVAR_NORESTART))) { // Just reset the rest to their default values. Cvar_SetSafe(curvar->name, curvar->resetString); } @@ -1420,27 +1335,22 @@ Cvar_Restart_f Resets all cvars to their hardcoded values ============ */ -void Cvar_Restart_f( void ) { - Cvar_Restart(qfalse); -} +void Cvar_Restart_f(void) { Cvar_Restart(qfalse); } /* ===================== Cvar_InfoString ===================== */ -char *Cvar_InfoString( int bit ) { - static char info[MAX_INFO_STRING]; - cvar_t *var; +char *Cvar_InfoString(int bit) { + static char info[MAX_INFO_STRING]; + cvar_t *var; info[0] = 0; - for (var = cvar_vars ; var ; var = var->next) - { - if (!(var->flags & CVAR_INTERNAL) && var->name && - (var->flags & bit)) - { - Info_SetValueForKey (info, var->name, var->string); + for (var = cvar_vars; var; var = var->next) { + if (!(var->flags & CVAR_INTERNAL) && var->name && (var->flags & bit)) { + Info_SetValueForKey(info, var->name, var->string); } } @@ -1454,18 +1364,15 @@ Cvar_InfoString_Big handles large info strings ( CS_SYSTEMINFO ) ===================== */ -char *Cvar_InfoString_Big( int bit ) { - static char info[BIG_INFO_STRING]; - cvar_t *var; +char *Cvar_InfoString_Big(int bit) { + static char info[BIG_INFO_STRING]; + cvar_t *var; info[0] = 0; - for (var = cvar_vars ; var ; var = var->next) - { - if (!(var->flags & CVAR_INTERNAL) && var->name && - (var->flags & bit)) - { - Info_SetValueForKey_Big (info, var->name, var->string); + for (var = cvar_vars; var; var = var->next) { + if (!(var->flags & CVAR_INTERNAL) && var->name && (var->flags & bit)) { + Info_SetValueForKey_Big(info, var->name, var->string); } } return info; @@ -1476,24 +1383,21 @@ char *Cvar_InfoString_Big( int bit ) { Cvar_InfoStringBuffer ===================== */ -void Cvar_InfoStringBuffer( int bit, char* buff, int buffsize ) { - Q_strncpyz(buff,Cvar_InfoString(bit),buffsize); -} +void Cvar_InfoStringBuffer(int bit, char *buff, int buffsize) { Q_strncpyz(buff, Cvar_InfoString(bit), buffsize); } /* ===================== Cvar_CheckRange ===================== */ -void Cvar_CheckRange( cvar_t *var, float min, float max, qboolean integral ) -{ +void Cvar_CheckRange(cvar_t *var, float min, float max, qboolean integral) { var->validate = qtrue; var->min = min; var->max = max; var->integral = integral; // Force an initial range check - Cvar_Set( var->name, var->string ); + Cvar_Set(var->name, var->string); } /* @@ -1503,27 +1407,26 @@ Cvar_Register basically a slightly modified Cvar_Get for the interpreted modules ===================== */ -void Cvar_Register( vmCvar_t *vmCvar, const char *varName, const char *defaultValue, uint32_t flags ) { - cvar_t *cv; +void Cvar_Register(vmCvar_t *vmCvar, const char *varName, const char *defaultValue, uint32_t flags) { + cvar_t *cv; // There is code in Cvar_Get to prevent CVAR_ROM cvars being changed by the user. In other words CVAR_ARCHIVE and // CVAR_ROM are mutually exclusive flags. Unfortunately some historical game code (including single player baseq3) // sets both flags. We unset CVAR_ROM for such cvars. if ((flags & (CVAR_ARCHIVE | CVAR_ROM)) == (CVAR_ARCHIVE | CVAR_ROM)) { - Com_DPrintf( S_COLOR_YELLOW "WARNING: Unsetting CVAR_ROM cvar '%s', since it is also CVAR_ARCHIVE\n", varName ); + Com_DPrintf(S_COLOR_YELLOW "WARNING: Unsetting CVAR_ROM cvar '%s', since it is also CVAR_ARCHIVE\n", varName); flags &= ~CVAR_ROM; } - cv = Cvar_Get( varName, defaultValue, flags | CVAR_VM_CREATED ); - if ( !vmCvar ) { + cv = Cvar_Get(varName, defaultValue, flags | CVAR_VM_CREATED); + if (!vmCvar) { return; } vmCvar->handle = cv - cvar_indexes; vmCvar->modificationCount = -1; - Cvar_Update( vmCvar ); + Cvar_Update(vmCvar); } - /* ===================== Cvar_Update @@ -1531,26 +1434,26 @@ Cvar_Update updates an interpreted modules' version of a cvar ===================== */ -void Cvar_Update( vmCvar_t *vmCvar ) { - cvar_t *cv = NULL; +void Cvar_Update(vmCvar_t *vmCvar) { + cvar_t *cv = NULL; assert(vmCvar); - if ( (unsigned)vmCvar->handle >= (unsigned)cvar_numIndexes ) { - Com_Error( ERR_DROP, "Cvar_Update: handle %u out of range", (unsigned)vmCvar->handle ); + if ((unsigned)vmCvar->handle >= (unsigned)cvar_numIndexes) { + Com_Error(ERR_DROP, "Cvar_Update: handle %u out of range", (unsigned)vmCvar->handle); } cv = cvar_indexes + vmCvar->handle; - if ( cv->modificationCount == vmCvar->modificationCount ) { + if (cv->modificationCount == vmCvar->modificationCount) { return; } - if ( !cv->string ) { - return; // variable might have been cleared by a cvar_restart + if (!cv->string) { + return; // variable might have been cleared by a cvar_restart } vmCvar->modificationCount = cv->modificationCount; - if ( strlen(cv->string)+1 > MAX_CVAR_VALUE_STRING ) - Com_Error( ERR_DROP, "Cvar_Update: src %s length %u exceeds MAX_CVAR_VALUE_STRING", cv->string, (unsigned int) strlen(cv->string)); - Q_strncpyz( vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING ); + if (strlen(cv->string) + 1 > MAX_CVAR_VALUE_STRING) + Com_Error(ERR_DROP, "Cvar_Update: src %s length %u exceeds MAX_CVAR_VALUE_STRING", cv->string, (unsigned int)strlen(cv->string)); + Q_strncpyz(vmCvar->string, cv->string, MAX_CVAR_VALUE_STRING); vmCvar->value = cv->value; vmCvar->integer = cv->integer; @@ -1561,15 +1464,13 @@ void Cvar_Update( vmCvar_t *vmCvar ) { Cvar_CompleteCvarName ================== */ -void Cvar_CompleteCvarName( char *args, int argNum ) -{ - if( argNum == 2 ) - { +void Cvar_CompleteCvarName(char *args, int argNum) { + if (argNum == 2) { // Skip " " - char *p = Com_SkipTokens( args, 1, " " ); + char *p = Com_SkipTokens(args, 1, " "); - if( p > args ) - Field_CompleteCommand( p, qfalse, qtrue ); + if (p > args) + Field_CompleteCommand(p, qfalse, qtrue); } } @@ -1580,49 +1481,47 @@ Cvar_Init Reads in all archived cvars ============ */ -void Cvar_Init (void) { - memset( cvar_indexes, 0, sizeof( cvar_indexes ) ); - memset( hashTable, 0, sizeof( hashTable ) ); - - cvar_cheats = Cvar_Get( "sv_cheats", "1", CVAR_ROM|CVAR_SYSTEMINFO, "Allow cheats on server if set to 1" ); - - Cmd_AddCommand( "print", Cvar_Print_f, "Print cvar help" ); - Cmd_SetCommandCompletionFunc( "print", Cvar_CompleteCvarName ); - Cmd_AddCommand( "toggle", Cvar_Toggle_f, "Toggle a cvar between values" ); - Cmd_SetCommandCompletionFunc( "toggle", Cvar_CompleteCvarName ); - Cmd_AddCommand( "set", Cvar_Set_f, "Set a cvar" ); - Cmd_SetCommandCompletionFunc( "set", Cvar_CompleteCvarName ); - Cmd_AddCommand( "sets", Cvar_Set_f, "Set a cvar and apply serverinfo flag" ); - Cmd_SetCommandCompletionFunc( "sets", Cvar_CompleteCvarName ); - Cmd_AddCommand( "setu", Cvar_Set_f, "Set a cvar and apply userinfo flag" ); - Cmd_SetCommandCompletionFunc( "setu", Cvar_CompleteCvarName ); - Cmd_AddCommand( "seta", Cvar_Set_f, "Set a cvar and apply archive flag" ); - Cmd_SetCommandCompletionFunc( "seta", Cvar_CompleteCvarName ); - Cmd_AddCommand( "cvarAdd", Cvar_Math_f, "Add a value to a cvar" ); - Cmd_SetCommandCompletionFunc( "cvarAdd", Cvar_CompleteCvarName ); - Cmd_AddCommand( "cvarSub", Cvar_Math_f, "Subtract a value from a cvar" ); - Cmd_SetCommandCompletionFunc( "cvarSub", Cvar_CompleteCvarName ); - Cmd_AddCommand( "cvarMult", Cvar_Math_f, "Multiply a value to a cvar" ); - Cmd_SetCommandCompletionFunc( "cvarMult", Cvar_CompleteCvarName ); - Cmd_AddCommand( "cvarDiv", Cvar_Math_f, "Divide a value from a cvar" ); - Cmd_SetCommandCompletionFunc( "cvarDiv", Cvar_CompleteCvarName ); - Cmd_AddCommand( "cvarMod", Cvar_Math_f, "Apply a modulo on a cvar" ); - Cmd_SetCommandCompletionFunc( "cvarMod", Cvar_CompleteCvarName ); - Cmd_AddCommand( "reset", Cvar_Reset_f, "Reset a cvar to default" ); - Cmd_SetCommandCompletionFunc( "reset", Cvar_CompleteCvarName ); - Cmd_AddCommand( "unset", Cvar_Unset_f, "Unset a user generated cvar" ); - Cmd_SetCommandCompletionFunc( "unset", Cvar_CompleteCvarName ); - Cmd_AddCommand( "unset_usercreated", Cvar_UnsetUserCreated_f, "Unset all user generated cvars " S_COLOR_RED "Use with caution!" S_COLOR_WHITE ); - Cmd_AddCommand( "cvarlist", Cvar_List_f, "Show all cvars" ); - Cmd_AddCommand( "cvar_usercreated", Cvar_ListUserCreated_f, "Show all user created cvars" ); - Cmd_AddCommand( "cvar_modified", Cvar_ListModified_f, "Show all modified cvars" ); - Cmd_AddCommand( "cvar_restart", Cvar_Restart_f, "Resetart the cvar sub-system" ); +void Cvar_Init(void) { + memset(cvar_indexes, 0, sizeof(cvar_indexes)); + memset(hashTable, 0, sizeof(hashTable)); + + cvar_cheats = Cvar_Get("sv_cheats", "1", CVAR_ROM | CVAR_SYSTEMINFO, "Allow cheats on server if set to 1"); + + Cmd_AddCommand("print", Cvar_Print_f, "Print cvar help"); + Cmd_SetCommandCompletionFunc("print", Cvar_CompleteCvarName); + Cmd_AddCommand("toggle", Cvar_Toggle_f, "Toggle a cvar between values"); + Cmd_SetCommandCompletionFunc("toggle", Cvar_CompleteCvarName); + Cmd_AddCommand("set", Cvar_Set_f, "Set a cvar"); + Cmd_SetCommandCompletionFunc("set", Cvar_CompleteCvarName); + Cmd_AddCommand("sets", Cvar_Set_f, "Set a cvar and apply serverinfo flag"); + Cmd_SetCommandCompletionFunc("sets", Cvar_CompleteCvarName); + Cmd_AddCommand("setu", Cvar_Set_f, "Set a cvar and apply userinfo flag"); + Cmd_SetCommandCompletionFunc("setu", Cvar_CompleteCvarName); + Cmd_AddCommand("seta", Cvar_Set_f, "Set a cvar and apply archive flag"); + Cmd_SetCommandCompletionFunc("seta", Cvar_CompleteCvarName); + Cmd_AddCommand("cvarAdd", Cvar_Math_f, "Add a value to a cvar"); + Cmd_SetCommandCompletionFunc("cvarAdd", Cvar_CompleteCvarName); + Cmd_AddCommand("cvarSub", Cvar_Math_f, "Subtract a value from a cvar"); + Cmd_SetCommandCompletionFunc("cvarSub", Cvar_CompleteCvarName); + Cmd_AddCommand("cvarMult", Cvar_Math_f, "Multiply a value to a cvar"); + Cmd_SetCommandCompletionFunc("cvarMult", Cvar_CompleteCvarName); + Cmd_AddCommand("cvarDiv", Cvar_Math_f, "Divide a value from a cvar"); + Cmd_SetCommandCompletionFunc("cvarDiv", Cvar_CompleteCvarName); + Cmd_AddCommand("cvarMod", Cvar_Math_f, "Apply a modulo on a cvar"); + Cmd_SetCommandCompletionFunc("cvarMod", Cvar_CompleteCvarName); + Cmd_AddCommand("reset", Cvar_Reset_f, "Reset a cvar to default"); + Cmd_SetCommandCompletionFunc("reset", Cvar_CompleteCvarName); + Cmd_AddCommand("unset", Cvar_Unset_f, "Unset a user generated cvar"); + Cmd_SetCommandCompletionFunc("unset", Cvar_CompleteCvarName); + Cmd_AddCommand("unset_usercreated", Cvar_UnsetUserCreated_f, "Unset all user generated cvars " S_COLOR_RED "Use with caution!" S_COLOR_WHITE); + Cmd_AddCommand("cvarlist", Cvar_List_f, "Show all cvars"); + Cmd_AddCommand("cvar_usercreated", Cvar_ListUserCreated_f, "Show all user created cvars"); + Cmd_AddCommand("cvar_modified", Cvar_ListModified_f, "Show all modified cvars"); + Cmd_AddCommand("cvar_restart", Cvar_Restart_f, "Resetart the cvar sub-system"); } -static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) -{ - if(string && *string) - { +static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) { + if (string && *string) { char *temp = memPool + memPoolUsed; strcpy(temp, *string); memPoolUsed += strlen(*string) + 1; @@ -1631,16 +1530,13 @@ static void Cvar_Realloc(char **string, char *memPool, int &memPoolUsed) } } - -//Turns many small allocation blocks into one big one. -void Cvar_Defrag(void) -{ - cvar_t *var; +// Turns many small allocation blocks into one big one. +void Cvar_Defrag(void) { + cvar_t *var; int totalMem = 0; int nextMemPoolSize; - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { if (var->name) { totalMem += strlen(var->name) + 1; } @@ -1658,12 +1554,11 @@ void Cvar_Defrag(void) } } - char *mem = (char*)Z_Malloc(totalMem, TAG_SMALL, qfalse); + char *mem = (char *)Z_Malloc(totalMem, TAG_SMALL, qfalse); nextMemPoolSize = totalMem; totalMem = 0; - for (var = cvar_vars; var; var = var->next) - { + for (var = cvar_vars; var; var = var->next) { Cvar_Realloc(&var->name, mem, totalMem); Cvar_Realloc(&var->string, mem, totalMem); Cvar_Realloc(&var->resetString, mem, totalMem); @@ -1671,10 +1566,9 @@ void Cvar_Defrag(void) Cvar_Realloc(&var->description, mem, totalMem); } - if(lastMemPool) { + if (lastMemPool) { Z_Free(lastMemPool); } lastMemPool = mem; memPoolSize = nextMemPoolSize; } - diff --git a/codemp/qcommon/files.cpp b/codemp/qcommon/files.cpp index 7077b2d4c3..6c9480cdba 100644 --- a/codemp/qcommon/files.cpp +++ b/codemp/qcommon/files.cpp @@ -44,10 +44,10 @@ along with this program; if not, see . #endif // for rmdir -#if defined (_MSC_VER) - #include +#if defined(_MSC_VER) +#include #else - #include +#include #endif /* @@ -189,110 +189,110 @@ or configs will never get loaded from disk! */ -#define MAX_ZPATH 256 -#define MAX_SEARCH_PATHS 4096 -#define MAX_FILEHASH_SIZE 1024 +#define MAX_ZPATH 256 +#define MAX_SEARCH_PATHS 4096 +#define MAX_FILEHASH_SIZE 1024 typedef struct fileInPack_s { - char *name; // name of the file - unsigned long pos; // file info position in zip - unsigned long len; // uncompress file size - struct fileInPack_s* next; // next file in the hash + char *name; // name of the file + unsigned long pos; // file info position in zip + unsigned long len; // uncompress file size + struct fileInPack_s *next; // next file in the hash } fileInPack_t; typedef struct pack_s { - char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base - char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3 - char pakBasename[MAX_OSPATH]; // assets0 - char pakGamename[MAX_OSPATH]; // base - unzFile handle; // handle to zip file - int checksum; // regular checksum - int pure_checksum; // checksum for pure - int numfiles; // number of files in pk3 - int referenced; // referenced file flags - int hashSize; // hash table size (power of 2) - fileInPack_t* *hashTable; // hash table - fileInPack_t* buildBuffer; // buffer with the filenames etc. + char pakPathname[MAX_OSPATH]; // c:\jediacademy\gamedata\base + char pakFilename[MAX_OSPATH]; // c:\jediacademy\gamedata\base\assets0.pk3 + char pakBasename[MAX_OSPATH]; // assets0 + char pakGamename[MAX_OSPATH]; // base + unzFile handle; // handle to zip file + int checksum; // regular checksum + int pure_checksum; // checksum for pure + int numfiles; // number of files in pk3 + int referenced; // referenced file flags + int hashSize; // hash table size (power of 2) + fileInPack_t **hashTable; // hash table + fileInPack_t *buildBuffer; // buffer with the filenames etc. } pack_t; typedef struct directory_s { - char path[MAX_OSPATH]; // c:\jediacademy\gamedata - char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base - char gamedir[MAX_OSPATH]; // base + char path[MAX_OSPATH]; // c:\jediacademy\gamedata + char fullpath[MAX_OSPATH]; // c:\jediacademy\gamedata\base + char gamedir[MAX_OSPATH]; // base } directory_t; typedef struct searchpath_s { struct searchpath_s *next; - pack_t *pack; // only one of pack / dir will be non NULL - directory_t *dir; + pack_t *pack; // only one of pack / dir will be non NULL + directory_t *dir; } searchpath_t; -static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators -static cvar_t *fs_debug; -static cvar_t *fs_homepath; +static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators +static cvar_t *fs_debug; +static cvar_t *fs_homepath; #ifdef MACOS_X // Also search the .app bundle for .pk3 files -static cvar_t *fs_apppath; +static cvar_t *fs_apppath; #endif -static cvar_t *fs_basepath; -static cvar_t *fs_basegame; -static cvar_t *fs_cdpath; -static cvar_t *fs_copyfiles; -static cvar_t *fs_gamedirvar; -static cvar_t *fs_dirbeforepak; //rww - when building search path, keep directories at top and insert pk3's under them -static searchpath_t *fs_searchpaths; -static int fs_readCount; // total bytes read -static int fs_loadCount; // total files read -static int fs_packFiles = 0; // total number of files in packs +static cvar_t *fs_basepath; +static cvar_t *fs_basegame; +static cvar_t *fs_cdpath; +static cvar_t *fs_copyfiles; +static cvar_t *fs_gamedirvar; +static cvar_t *fs_dirbeforepak; // rww - when building search path, keep directories at top and insert pk3's under them +static searchpath_t *fs_searchpaths; +static int fs_readCount; // total bytes read +static int fs_loadCount; // total files read +static int fs_packFiles = 0; // total number of files in packs -static int fs_fakeChkSum; -static int fs_checksumFeed; +static int fs_fakeChkSum; +static int fs_checksumFeed; typedef union qfile_gus { - FILE* o; - unzFile z; + FILE *o; + unzFile z; } qfile_gut; typedef struct qfile_us { - qfile_gut file; - qboolean unique; + qfile_gut file; + qboolean unique; } qfile_ut; typedef struct fileHandleData_s { - qfile_ut handleFiles; - qboolean handleSync; - int fileSize; - int zipFilePos; - int zipFileLen; - qboolean zipFile; - char name[MAX_ZPATH]; + qfile_ut handleFiles; + qboolean handleSync; + int fileSize; + int zipFilePos; + int zipFileLen; + qboolean zipFile; + char name[MAX_ZPATH]; } fileHandleData_t; -static fileHandleData_t fsh[MAX_FILE_HANDLES]; +static fileHandleData_t fsh[MAX_FILE_HANDLES]; // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 // wether we did a reorder on the current search path when joining the server static qboolean fs_reordered = qfalse; // never load anything from pk3 files that are not present at the server when pure -static int fs_numServerPaks = 0; -static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums -static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names +static int fs_numServerPaks = 0; +static int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums +static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names // only used for autodownload, to make sure the client has at least // all the pk3 files that are referenced at the server side -static int fs_numServerReferencedPaks; -static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums -static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names +static int fs_numServerReferencedPaks; +static int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums +static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names #if defined(_WIN32) // temporary files - store them in a circular buffer. We're pretty // much guaranteed to not need more than 8 temp files at a time. -static int fs_temporaryFileWriteIdx = 0; -static char fs_temporaryFileNames[8][MAX_OSPATH]; +static int fs_temporaryFileWriteIdx = 0; +static char fs_temporaryFileNames[8][MAX_OSPATH]; #endif // last valid game folder used @@ -300,16 +300,16 @@ char lastValidBase[MAX_OSPATH]; char lastValidGame[MAX_OSPATH]; #ifdef FS_MISSING -FILE* missingFiles = NULL; +FILE *missingFiles = NULL; #endif /* C99 defines __func__ */ #if __STDC_VERSION__ < 199901L -# if __GNUC__ >= 2 || _MSC_VER >= 1300 -# define __func__ __FUNCTION__ -# else -# define __func__ "(unknown)" -# endif +#if __GNUC__ >= 2 || _MSC_VER >= 1300 +#define __func__ __FUNCTION__ +#else +#define __func__ "(unknown)" +#endif #endif /* @@ -318,13 +318,11 @@ FS_Initialized ============== */ -qboolean FS_Initialized( void ) { - return (qboolean)(fs_searchpaths != NULL); -} +qboolean FS_Initialized(void) { return (qboolean)(fs_searchpaths != NULL); } -static void FS_AssertInitialised( void ) { - if ( !fs_searchpaths ) { - Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" ); +static void FS_AssertInitialised(void) { + if (!fs_searchpaths) { + Com_Error(ERR_FATAL, "Filesystem call made without initialization\n"); } } @@ -333,21 +331,21 @@ static void FS_AssertInitialised( void ) { FS_PakIsPure ================= */ -qboolean FS_PakIsPure( pack_t *pack ) { +qboolean FS_PakIsPure(pack_t *pack) { int i; - if ( fs_numServerPaks ) { - // NOTE TTimo we are matching checksums without checking the pak names - // this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation - // (what happens when two pk3's have the same checkums? is it a likely situation?) - // also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name - for ( i = 0 ; i < fs_numServerPaks ; i++ ) { + if (fs_numServerPaks) { + // NOTE TTimo we are matching checksums without checking the pak names + // this means you can have the same pk3 as the server under a different name, you will still get through sv_pure validation + // (what happens when two pk3's have the same checkums? is it a likely situation?) + // also, if there's a wrong checksumed pk3 and autodownload is enabled, the checksum will be appended to the downloaded pk3 name + for (i = 0; i < fs_numServerPaks; i++) { // FIXME: also use hashed file names - if ( pack->checksum == fs_serverPaks[i] ) { - return qtrue; // on the aproved list + if (pack->checksum == fs_serverPaks[i]) { + return qtrue; // on the aproved list } } - return qfalse; // not on the pure server pak list + return qfalse; // not on the pure server pak list } return qtrue; } @@ -357,57 +355,60 @@ qboolean FS_PakIsPure( pack_t *pack ) { return a hash value for the filename ================ */ -static long FS_HashFileName( const char *fname, int hashSize ) { - int i; - long hash; - char letter; +static long FS_HashFileName(const char *fname, int hashSize) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); - hash &= (hashSize-1); + hash &= (hashSize - 1); return hash; } static fileHandle_t FS_HandleForFile(void) { - int i; + int i; - for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { - if ( fsh[i].handleFiles.file.o == NULL ) { + for (i = 1; i < MAX_FILE_HANDLES; i++) { + if (fsh[i].handleFiles.file.o == NULL) { return i; } } - Com_Error( ERR_DROP, "FS_HandleForFile: none free" ); + Com_Error(ERR_DROP, "FS_HandleForFile: none free"); return 0; } -static FILE *FS_FileForHandle( fileHandle_t f ) { - if ( f < 1 || f >= MAX_FILE_HANDLES ) { - Com_Error( ERR_DROP, "FS_FileForHandle: out of range" ); +static FILE *FS_FileForHandle(fileHandle_t f) { + if (f < 1 || f >= MAX_FILE_HANDLES) { + Com_Error(ERR_DROP, "FS_FileForHandle: out of range"); } if (fsh[f].zipFile == qtrue) { - Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" ); + Com_Error(ERR_DROP, "FS_FileForHandle: can't get FILE on zip file"); } - if ( ! fsh[f].handleFiles.file.o ) { - Com_Error( ERR_DROP, "FS_FileForHandle: NULL" ); + if (!fsh[f].handleFiles.file.o) { + Com_Error(ERR_DROP, "FS_FileForHandle: NULL"); } return fsh[f].handleFiles.file.o; } -void FS_ForceFlush( fileHandle_t f ) { +void FS_ForceFlush(fileHandle_t f) { FILE *file; file = FS_FileForHandle(f); - setvbuf( file, NULL, _IONBF, 0 ); + setvbuf(file, NULL, _IONBF, 0); } /* @@ -416,13 +417,12 @@ FS_fplength ================ */ -long FS_fplength(FILE *h) -{ - long pos; - long end; +long FS_fplength(FILE *h) { + long pos; + long end; pos = ftell(h); - if ( pos == EOF ) + if (pos == EOF) return EOF; fseek(h, 0, SEEK_END); @@ -441,12 +441,12 @@ it will return the size of the pak file, not the expected size of the file. ================ */ -int FS_filelength( fileHandle_t f ) { - FILE *h; +int FS_filelength(fileHandle_t f) { + FILE *h; h = FS_FileForHandle(f); - if(h == NULL) + if (h == NULL) return EOF; else return FS_fplength(h); @@ -459,17 +459,17 @@ FS_ReplaceSeparators Fix things up differently for win/unix/mac ==================== */ -void FS_ReplaceSeparators( char *path ) { - char *s; +void FS_ReplaceSeparators(char *path) { + char *s; qboolean lastCharWasSep = qfalse; - for ( s = path ; *s ; s++ ) { - if ( *s == '/' || *s == '\\' ) { - if ( !lastCharWasSep ) { + for (s = path; *s; s++) { + if (*s == '/' || *s == '\\') { + if (!lastCharWasSep) { *s = PATH_SEP; lastCharWasSep = qtrue; } else { - memmove (s, s + 1, strlen (s)); + memmove(s, s + 1, strlen(s)); } } else { lastCharWasSep = qfalse; @@ -484,40 +484,40 @@ FS_BuildOSPath Qpath may have either forward or backwards slashes =================== */ -char *FS_BuildOSPath( const char *qpath ) { - char temp[MAX_OSPATH]; +char *FS_BuildOSPath(const char *qpath) { + char temp[MAX_OSPATH]; static char ospath[4][MAX_OSPATH]; static int toggle; - int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) + int nextToggle = (toggle + 1) & 3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) toggle = nextToggle; // Fix for filenames that are given to FS with a leading "/" (/botfiles/Foo) if (qpath[0] == '\\' || qpath[0] == '/') qpath++; - Com_sprintf( temp, sizeof(temp), "/base/%s", qpath ); - FS_ReplaceSeparators( temp ); - Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", fs_basepath->string, temp ); + Com_sprintf(temp, sizeof(temp), "/base/%s", qpath); + FS_ReplaceSeparators(temp); + Com_sprintf(ospath[toggle], sizeof(ospath[0]), "%s%s", fs_basepath->string, temp); return ospath[toggle]; } -char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) { - char temp[MAX_OSPATH]; +char *FS_BuildOSPath(const char *base, const char *game, const char *qpath) { + char temp[MAX_OSPATH]; static char ospath[4][MAX_OSPATH]; static int toggle; - int nextToggle = (toggle + 1)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) + int nextToggle = (toggle + 1) & 3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement) toggle = nextToggle; - if( !game || !game[0] ) { + if (!game || !game[0]) { game = fs_gamedir; } - Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath ); - FS_ReplaceSeparators( temp ); - Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp ); + Com_sprintf(temp, sizeof(temp), "/%s/%s", game, qpath); + FS_ReplaceSeparators(temp); + Com_sprintf(ospath[toggle], sizeof(ospath[0]), "%s%s", base, temp); return ospath[toggle]; } @@ -529,33 +529,32 @@ FS_CreatePath Creates any directories needed to store the given filename ============ */ -qboolean FS_CreatePath (char *OSPath) { - char *ofs; - char path[MAX_OSPATH]; +qboolean FS_CreatePath(char *OSPath) { + char *ofs; + char path[MAX_OSPATH]; // make absolutely sure that it can't back up the path // FIXME: is c: allowed??? - if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) { - Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath ); + if (strstr(OSPath, "..") || strstr(OSPath, "::")) { + Com_Printf("WARNING: refusing to create relative path \"%s\"\n", OSPath); return qtrue; } - Q_strncpyz( path, OSPath, sizeof( path ) ); - FS_ReplaceSeparators( path ); + Q_strncpyz(path, OSPath, sizeof(path)); + FS_ReplaceSeparators(path); // Skip creation of the root directory as it will always be there - ofs = strchr( path, PATH_SEP ); - if ( ofs ) { + ofs = strchr(path, PATH_SEP); + if (ofs) { ofs++; } - for (; ofs != NULL && *ofs ; ofs++) { + for (; ofs != NULL && *ofs; ofs++) { if (*ofs == PATH_SEP) { // create the directory *ofs = 0; - if (!Sys_Mkdir (path)) { - Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", - path ); + if (!Sys_Mkdir(path)) { + Com_Error(ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", path); } *ofs = PATH_SEP; } @@ -570,14 +569,13 @@ FS_CheckFilenameIsMutable ERR_FATAL if trying to maniuplate a file with the platform library, or pk3 extension ================= */ -static void FS_CheckFilenameIsMutable( const char *filename, const char *function ) -{ +static void FS_CheckFilenameIsMutable(const char *filename, const char *function) { // Check if the filename ends with the library, or pk3 extension - if( COM_CompareExtension( filename, DLL_EXT ) - || COM_CompareExtension( filename, ".pk3" ) ) - { - Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due " - "to %s extension", function, filename, COM_GetExtension( filename ) ); + if (COM_CompareExtension(filename, DLL_EXT) || COM_CompareExtension(filename, ".pk3")) { + Com_Error(ERR_FATAL, + "%s: Not allowed to manipulate '%s' due " + "to %s extension", + function, filename, COM_GetExtension(filename)); } } @@ -588,63 +586,60 @@ FS_CopyFile Copy a fully specified file from one place to another ================= */ -void FS_CopyFile( char *fromOSPath, char *toOSPath ) { - FILE *f; - int len; - byte *buf; +void FS_CopyFile(char *fromOSPath, char *toOSPath) { + FILE *f; + int len; + byte *buf; - FS_CheckFilenameIsMutable( fromOSPath, __func__ ); + FS_CheckFilenameIsMutable(fromOSPath, __func__); - Com_Printf( "copy %s to %s\n", fromOSPath, toOSPath ); + Com_Printf("copy %s to %s\n", fromOSPath, toOSPath); if (strstr(fromOSPath, "journal.dat") || strstr(fromOSPath, "journaldata.dat")) { - Com_Printf( "Ignoring journal files\n"); + Com_Printf("Ignoring journal files\n"); return; } - f = fopen( fromOSPath, "rb" ); - if ( !f ) { + f = fopen(fromOSPath, "rb"); + if (!f) { return; } - fseek (f, 0, SEEK_END); - len = ftell (f); - fseek (f, 0, SEEK_SET); + fseek(f, 0, SEEK_END); + len = ftell(f); + fseek(f, 0, SEEK_SET); - if ( len == EOF ) - { - fclose( f ); - Com_Error( ERR_FATAL, "Bad file length in FS_CopyFile()" ); + if (len == EOF) { + fclose(f); + Com_Error(ERR_FATAL, "Bad file length in FS_CopyFile()"); } // we are using direct malloc instead of Z_Malloc here, so it // probably won't work on a mac... Its only for developers anyway... - buf = (unsigned char *)malloc( len ); - if (fread( buf, 1, len, f ) != (unsigned)len) - { - fclose( f ); - free ( buf ); - Com_Error( ERR_FATAL, "Short read in FS_Copyfiles()\n" ); + buf = (unsigned char *)malloc(len); + if (fread(buf, 1, len, f) != (unsigned)len) { + fclose(f); + free(buf); + Com_Error(ERR_FATAL, "Short read in FS_Copyfiles()\n"); } - fclose( f ); + fclose(f); - if( FS_CreatePath( toOSPath ) ) { - free ( buf ); + if (FS_CreatePath(toOSPath)) { + free(buf); return; } - f = fopen( toOSPath, "wb" ); - if ( !f ) { - free ( buf ); + f = fopen(toOSPath, "wb"); + if (!f) { + free(buf); return; } - if (fwrite( buf, 1, len, f ) != (unsigned)len) - { - fclose( f ); - free ( buf ); - Com_Error( ERR_FATAL, "Short write in FS_Copyfiles()\n" ); + if (fwrite(buf, 1, len, f) != (unsigned)len) { + fclose(f); + free(buf); + Com_Error(ERR_FATAL, "Short write in FS_Copyfiles()\n"); } - fclose( f ); - free( buf ); + fclose(f); + free(buf); } /* @@ -653,10 +648,10 @@ FS_Remove =========== */ -void FS_Remove( const char *osPath ) { - FS_CheckFilenameIsMutable( osPath, __func__ ); +void FS_Remove(const char *osPath) { + FS_CheckFilenameIsMutable(osPath, __func__); - remove( osPath ); + remove(osPath); } /* @@ -665,11 +660,10 @@ FS_HomeRemove =========== */ -void FS_HomeRemove( const char *homePath ) { - FS_CheckFilenameIsMutable( homePath, __func__ ); +void FS_HomeRemove(const char *homePath) { + FS_CheckFilenameIsMutable(homePath, __func__); - remove( FS_BuildOSPath( fs_homepath->string, - fs_gamedir, homePath ) ); + remove(FS_BuildOSPath(fs_homepath->string, fs_gamedir, homePath)); } /* @@ -679,33 +673,33 @@ FS_Rmdir Removes a directory, optionally deleting all files under it =========== */ -void FS_Rmdir( const char *osPath, qboolean recursive ) { - FS_CheckFilenameIsMutable( osPath, __func__ ); +void FS_Rmdir(const char *osPath, qboolean recursive) { + FS_CheckFilenameIsMutable(osPath, __func__); - if ( recursive ) { + if (recursive) { int numfiles; int i; - char **filesToRemove = Sys_ListFiles( osPath, "", NULL, &numfiles, qfalse ); - for ( i = 0; i < numfiles; i++ ) { + char **filesToRemove = Sys_ListFiles(osPath, "", NULL, &numfiles, qfalse); + for (i = 0; i < numfiles; i++) { char fileOsPath[MAX_OSPATH]; - Com_sprintf( fileOsPath, sizeof( fileOsPath ), "%s/%s", osPath, filesToRemove[i] ); - FS_Remove( fileOsPath ); + Com_sprintf(fileOsPath, sizeof(fileOsPath), "%s/%s", osPath, filesToRemove[i]); + FS_Remove(fileOsPath); } - FS_FreeFileList( filesToRemove ); + FS_FreeFileList(filesToRemove); - char **directoriesToRemove = Sys_ListFiles( osPath, "/", NULL, &numfiles, qfalse ); - for ( i = 0; i < numfiles; i++ ) { - if ( !Q_stricmp( directoriesToRemove[i], "." ) || !Q_stricmp( directoriesToRemove[i], ".." ) ) { + char **directoriesToRemove = Sys_ListFiles(osPath, "/", NULL, &numfiles, qfalse); + for (i = 0; i < numfiles; i++) { + if (!Q_stricmp(directoriesToRemove[i], ".") || !Q_stricmp(directoriesToRemove[i], "..")) { continue; } char directoryOsPath[MAX_OSPATH]; - Com_sprintf( directoryOsPath, sizeof( directoryOsPath ), "%s/%s", osPath, directoriesToRemove[i] ); - FS_Rmdir( directoryOsPath, qtrue ); + Com_sprintf(directoryOsPath, sizeof(directoryOsPath), "%s/%s", osPath, directoriesToRemove[i]); + FS_Rmdir(directoryOsPath, qtrue); } - FS_FreeFileList( directoriesToRemove ); + FS_FreeFileList(directoriesToRemove); } - rmdir( osPath ); + rmdir(osPath); } /* @@ -715,11 +709,10 @@ FS_HomeRmdir Removes a directory, optionally deleting all files under it =========== */ -void FS_HomeRmdir( const char *homePath, qboolean recursive ) { - FS_CheckFilenameIsMutable( homePath, __func__ ); +void FS_HomeRmdir(const char *homePath, qboolean recursive) { + FS_CheckFilenameIsMutable(homePath, __func__); - FS_Rmdir( FS_BuildOSPath( fs_homepath->string, - fs_gamedir, homePath ), recursive ); + FS_Rmdir(FS_BuildOSPath(fs_homepath->string, fs_gamedir, homePath), recursive); } /* @@ -729,14 +722,12 @@ FS_FileInPathExists Tests if path and file exists ================ */ -qboolean FS_FileInPathExists(const char *testpath) -{ +qboolean FS_FileInPathExists(const char *testpath) { FILE *filep; filep = fopen(testpath, "rb"); - if(filep) - { + if (filep) { fclose(filep); return qtrue; } @@ -754,10 +745,7 @@ search the paths. This is to determine if opening a file to write NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards ================ */ -qboolean FS_FileExists( const char *file ) -{ - return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file)); -} +qboolean FS_FileExists(const char *file) { return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file)); } /* ================ @@ -766,12 +754,11 @@ FS_SV_FileExists Tests if the file exists ================ */ -qboolean FS_SV_FileExists( const char *file ) -{ +qboolean FS_SV_FileExists(const char *file) { char *testpath; - testpath = FS_BuildOSPath( fs_homepath->string, file, ""); - testpath[strlen(testpath)-1] = '\0'; + testpath = FS_BuildOSPath(fs_homepath->string, file, ""); + testpath[strlen(testpath) - 1] = '\0'; return FS_FileInPathExists(testpath); } @@ -782,32 +769,32 @@ FS_SV_FOpenFileWrite =========== */ -fileHandle_t FS_SV_FOpenFileWrite( const char *filename ) { +fileHandle_t FS_SV_FOpenFileWrite(const char *filename) { char *ospath; - fileHandle_t f; + fileHandle_t f; FS_AssertInitialised(); - ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_homepath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_FOpenFileWrite: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileWrite: %s\n", ospath); } - FS_CheckFilenameIsMutable( ospath, __func__ ); + FS_CheckFilenameIsMutable(ospath, __func__); - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } - Com_DPrintf( "writing to: %s\n", ospath ); - fsh[f].handleFiles.file.o = fopen( ospath, "wb" ); + Com_DPrintf("writing to: %s\n", ospath); + fsh[f].handleFiles.file.o = fopen(ospath, "wb"); - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { @@ -822,31 +809,31 @@ FS_SV_FOpenFileAppend =========== */ -fileHandle_t FS_SV_FOpenFileAppend( const char *filename ) { - char *ospath; - fileHandle_t f; +fileHandle_t FS_SV_FOpenFileAppend(const char *filename) { + char *ospath; + fileHandle_t f; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); - ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_homepath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_FOpenFileAppend: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileAppend: %s\n", ospath); } - FS_CheckFilenameIsMutable( ospath, __func__ ); + FS_CheckFilenameIsMutable(ospath, __func__); - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } - fsh[f].handleFiles.file.o = fopen( ospath, "ab" ); + fsh[f].handleFiles.file.o = fopen(ospath, "ab"); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { @@ -863,71 +850,64 @@ search for a file somewhere below the home path, base path or cd path we search in that order, matching FS_SV_FOpenFileRead order =========== */ -int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) { +int FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp) { char *ospath; - fileHandle_t f = 0; + fileHandle_t f = 0; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); // don't let sound stutter S_ClearSoundBuffer(); // search homepath - ospath = FS_BuildOSPath( fs_homepath->string, filename, "" ); + ospath = FS_BuildOSPath(fs_homepath->string, filename, ""); // remove trailing slash - ospath[strlen(ospath)-1] = '\0'; + ospath[strlen(ospath) - 1] = '\0'; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; - if (!fsh[f].handleFiles.file.o) - { + if (!fsh[f].handleFiles.file.o) { // NOTE TTimo on non *nix systems, fs_homepath == fs_basepath, might want to avoid - if (Q_stricmp(fs_homepath->string,fs_basepath->string)) - { + if (Q_stricmp(fs_homepath->string, fs_basepath->string)) { // search basepath - ospath = FS_BuildOSPath( fs_basepath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_basepath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; - if ( fs_debug->integer ) - { - Com_Printf( "FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; } - if ( !fsh[f].handleFiles.file.o ) - { + if (!fsh[f].handleFiles.file.o) { f = 0; } } - if (!fsh[f].handleFiles.file.o) - { + if (!fsh[f].handleFiles.file.o) { // search cd path - ospath = FS_BuildOSPath( fs_cdpath->string, filename, "" ); - ospath[strlen(ospath)-1] = '\0'; + ospath = FS_BuildOSPath(fs_cdpath->string, filename, ""); + ospath[strlen(ospath) - 1] = '\0'; - if (fs_debug->integer) - { - Com_Printf( "FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_FOpenFileRead (fs_cdpath) : %s\n", ospath); } - fsh[f].handleFiles.file.o = fopen( ospath, "rb" ); + fsh[f].handleFiles.file.o = fopen(ospath, "rb"); fsh[f].handleSync = qfalse; - if ( !fsh[f].handleFiles.file.o ) - { + if (!fsh[f].handleFiles.file.o) { f = 0; } } @@ -945,31 +925,31 @@ FS_SV_Rename =========== */ -void FS_SV_Rename( const char *from, const char *to, qboolean safe ) { - char *from_ospath, *to_ospath; +void FS_SV_Rename(const char *from, const char *to, qboolean safe) { + char *from_ospath, *to_ospath; FS_AssertInitialised(); // don't let sound stutter S_ClearSoundBuffer(); - from_ospath = FS_BuildOSPath( fs_homepath->string, from, "" ); - to_ospath = FS_BuildOSPath( fs_homepath->string, to, "" ); - from_ospath[strlen(from_ospath)-1] = '\0'; - to_ospath[strlen(to_ospath)-1] = '\0'; + from_ospath = FS_BuildOSPath(fs_homepath->string, from, ""); + to_ospath = FS_BuildOSPath(fs_homepath->string, to, ""); + from_ospath[strlen(from_ospath) - 1] = '\0'; + to_ospath[strlen(to_ospath) - 1] = '\0'; - if ( fs_debug->integer ) { - Com_Printf( "FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath ); + if (fs_debug->integer) { + Com_Printf("FS_SV_Rename: %s --> %s\n", from_ospath, to_ospath); } - if ( safe ) { - FS_CheckFilenameIsMutable( to_ospath, __func__ ); + if (safe) { + FS_CheckFilenameIsMutable(to_ospath, __func__); } - if (rename( from_ospath, to_ospath )) { + if (rename(from_ospath, to_ospath)) { // Failed, try copying it and deleting the original - FS_CopyFile ( from_ospath, to_ospath ); - FS_Remove ( from_ospath ); + FS_CopyFile(from_ospath, to_ospath); + FS_Remove(from_ospath); } } @@ -979,27 +959,27 @@ FS_Rename =========== */ -void FS_Rename( const char *from, const char *to ) { - char *from_ospath, *to_ospath; +void FS_Rename(const char *from, const char *to) { + char *from_ospath, *to_ospath; FS_AssertInitialised(); // don't let sound stutter S_ClearSoundBuffer(); - from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from ); - to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to ); + from_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, from); + to_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, to); - if ( fs_debug->integer ) { - Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath ); + if (fs_debug->integer) { + Com_Printf("FS_Rename: %s --> %s\n", from_ospath, to_ospath); } - FS_CheckFilenameIsMutable( to_ospath, __func__ ); + FS_CheckFilenameIsMutable(to_ospath, __func__); - if (rename( from_ospath, to_ospath )) { + if (rename(from_ospath, to_ospath)) { // Failed, try copying it and deleting the original - FS_CopyFile ( from_ospath, to_ospath ); - FS_Remove ( from_ospath ); + FS_CopyFile(from_ospath, to_ospath); + FS_Remove(from_ospath); } } @@ -1014,31 +994,31 @@ There are three cases handled: * normal file: closed with fclose. * file in pak3 archive: subfile is closed with unzCloseCurrentFile, but the - minizip handle to the pak3 remains open. + minizip handle to the pak3 remains open. * file in pak3 archive, opened with "unique" flag: This file did not use - the system minizip handle to the pak3 file, but its own dedicated one. - The dedicated handle is closed with unzClose. + the system minizip handle to the pak3 file, but its own dedicated one. + The dedicated handle is closed with unzClose. =========== */ -void FS_FCloseFile( fileHandle_t f ) { +void FS_FCloseFile(fileHandle_t f) { FS_AssertInitialised(); if (fsh[f].zipFile == qtrue) { - unzCloseCurrentFile( fsh[f].handleFiles.file.z ); - if ( fsh[f].handleFiles.unique ) { - unzClose( fsh[f].handleFiles.file.z ); + unzCloseCurrentFile(fsh[f].handleFiles.file.z); + if (fsh[f].handleFiles.unique) { + unzClose(fsh[f].handleFiles.file.z); } - Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); + Com_Memset(&fsh[f], 0, sizeof(fsh[f])); return; } // we didn't find it as a pak, so close it as a unique file if (fsh[f].handleFiles.file.o) { - fclose (fsh[f].handleFiles.file.o); + fclose(fsh[f].handleFiles.file.o); } - Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) ); + Com_Memset(&fsh[f], 0, sizeof(fsh[f])); } /* @@ -1047,35 +1027,35 @@ FS_FOpenFileWrite =========== */ -fileHandle_t FS_FOpenFileWrite( const char *filename, qboolean safe ) { - char *ospath; - fileHandle_t f; +fileHandle_t FS_FOpenFileWrite(const char *filename, qboolean safe) { + char *ospath; + fileHandle_t f; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); + ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename); - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileWrite: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileWrite: %s\n", ospath); } - if ( safe ) { - FS_CheckFilenameIsMutable( ospath, __func__ ); + if (safe) { + FS_CheckFilenameIsMutable(ospath, __func__); } - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } // enabling the following line causes a recursive function call loop // when running with +set logfile 1 +set developer 1 - //Com_DPrintf( "writing to: %s\n", ospath ); - fsh[f].handleFiles.file.o = fopen( ospath, "wb" ); + // Com_DPrintf( "writing to: %s\n", ospath ); + fsh[f].handleFiles.file.o = fopen(ospath, "wb"); - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { @@ -1090,33 +1070,33 @@ FS_FOpenFileAppend =========== */ -fileHandle_t FS_FOpenFileAppend( const char *filename ) { - char *ospath; - fileHandle_t f; +fileHandle_t FS_FOpenFileAppend(const char *filename) { + char *ospath; + fileHandle_t f; FS_AssertInitialised(); f = FS_HandleForFile(); fsh[f].zipFile = qfalse; - Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) ); + Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name)); // don't let sound stutter S_ClearSoundBuffer(); - ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, filename ); + ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename); - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileAppend: %s\n", ospath ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileAppend: %s\n", ospath); } - FS_CheckFilenameIsMutable( ospath, __func__ ); + FS_CheckFilenameIsMutable(ospath, __func__); - if( FS_CreatePath( ospath ) ) { + if (FS_CreatePath(ospath)) { return 0; } - fsh[f].handleFiles.file.o = fopen( ospath, "ab" ); + fsh[f].handleFiles.file.o = fopen(ospath, "ab"); fsh[f].handleSync = qfalse; if (!fsh[f].handleFiles.file.o) { f = 0; @@ -1131,8 +1111,8 @@ FS_FilenameCompare Ignore case and separator char distinctions =========== */ -qboolean FS_FilenameCompare( const char *s1, const char *s2 ) { - int c1, c2; +qboolean FS_FilenameCompare(const char *s1, const char *s2) { + int c1, c2; do { c1 = *s1++; @@ -1145,19 +1125,19 @@ qboolean FS_FilenameCompare( const char *s1, const char *s2 ) { c2 -= ('a' - 'A'); } - if ( c1 == '\\' || c1 == ':' ) { + if (c1 == '\\' || c1 == ':') { c1 = '/'; } - if ( c2 == '\\' || c2 == ':' ) { + if (c2 == '\\' || c2 == ':') { c2 = '/'; } if (c1 != c2) { - return qtrue; // strings not equal + return qtrue; // strings not equal } } while (c1); - return qfalse; // strings are equal + return qfalse; // strings are equal } /* @@ -1168,13 +1148,12 @@ Return qtrue if ext matches file extension filename =========== */ -qboolean FS_IsExt(const char *filename, const char *ext, int namelen) -{ +qboolean FS_IsExt(const char *filename, const char *ext, int namelen) { int extlen; extlen = strlen(ext); - if(extlen > namelen) + if (extlen > namelen) return qfalse; filename += namelen - extlen; @@ -1191,16 +1170,14 @@ Return qtrue if filename has a demo extension */ #define DEMO_EXTENSION "dm_" -qboolean FS_IsDemoExt(const char *filename, int namelen) -{ +qboolean FS_IsDemoExt(const char *filename, int namelen) { const char *ext_test; ext_test = strrchr(filename, '.'); - if(ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1)) - { + if (ext_test && !Q_stricmpn(ext_test + 1, DEMO_EXTENSION, ARRAY_LEN(DEMO_EXTENSION) - 1)) { int protocol = atoi(ext_test + ARRAY_LEN(DEMO_EXTENSION)); - if(protocol == PROTOCOL_VERSION) + if (protocol == PROTOCOL_VERSION) return qtrue; } @@ -1209,29 +1186,25 @@ qboolean FS_IsDemoExt(const char *filename, int namelen) #ifdef _WIN32 -bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) -{ +bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) { bool bSuccess = false; HANDLE hFile = INVALID_HANDLE_VALUE; - hFile = CreateFile( psFileName, // LPCTSTR lpFileName, // pointer to name of the file - GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode - FILE_SHARE_READ, // DWORD dwShareMode, // share mode - NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes - OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create - FILE_FLAG_NO_BUFFERING,// DWORD dwFlagsAndAttributes, // file attributes - NULL // HANDLE hTemplateFile // handle to file with attributes to - ); - - if (hFile != INVALID_HANDLE_VALUE) - { - if (GetFileTime(hFile, // handle to file - NULL, // LPFILETIME lpCreationTime - NULL, // LPFILETIME lpLastAccessTime - &ft // LPFILETIME lpLastWriteTime - ) - ) - { + hFile = CreateFile(psFileName, // LPCTSTR lpFileName, // pointer to name of the file + GENERIC_READ, // DWORD dwDesiredAccess, // access (read-write) mode + FILE_SHARE_READ, // DWORD dwShareMode, // share mode + NULL, // LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes + OPEN_EXISTING, // DWORD dwCreationDisposition, // how to create + FILE_FLAG_NO_BUFFERING, // DWORD dwFlagsAndAttributes, // file attributes + NULL // HANDLE hTemplateFile // handle to file with attributes to + ); + + if (hFile != INVALID_HANDLE_VALUE) { + if (GetFileTime(hFile, // handle to file + NULL, // LPFILETIME lpCreationTime + NULL, // LPFILETIME lpLastAccessTime + &ft // LPFILETIME lpLastWriteTime + )) { bSuccess = true; } @@ -1241,32 +1214,24 @@ bool Sys_GetFileTime(LPCSTR psFileName, FILETIME &ft) return bSuccess; } -bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */ ) -{ +bool Sys_FileOutOfDate(LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName /* src */) { FILETIME ftFinalFile, ftDataFile; - if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile)) - { + if (Sys_GetFileTime(psFinalFileName, ftFinalFile) && Sys_GetFileTime(psDataFileName, ftDataFile)) { // timer res only accurate to within 2 seconds on FAT, so can't do exact compare... // - //LONG l = CompareFileTime( &ftFinalFile, &ftDataFile ); - if ( (fabs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000 ) && - ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime - ) - { - return false; // file not out of date, ie use it. + // LONG l = CompareFileTime( &ftFinalFile, &ftDataFile ); + if ((fabs((double)(ftFinalFile.dwLowDateTime - ftDataFile.dwLowDateTime)) <= 20000000) && ftFinalFile.dwHighDateTime == ftDataFile.dwHighDateTime) { + return false; // file not out of date, ie use it. } - return true; // flag return code to copy over a replacement version of this file + return true; // flag return code to copy over a replacement version of this file } - // extra error check, report as suspicious if you find a file locally but not out on the net.,. // - if (com_developer->integer) - { - if (!Sys_GetFileTime(psDataFileName, ftDataFile)) - { - Com_Printf( "Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName); + if (com_developer->integer) { + if (!Sys_GetFileTime(psDataFileName, ftDataFile)) { + Com_Printf("Sys_FileOutOfDate: reading %s but it's not on the net!\n", psFinalFileName); } } @@ -1275,14 +1240,12 @@ bool Sys_FileOutOfDate( LPCSTR psFinalFileName /* dest */, LPCSTR psDataFileName #endif // _WIN32 -bool FS_FileCacheable(const char* const filename) -{ - extern cvar_t *com_buildScript; - if (com_buildScript && com_buildScript->integer) - { +bool FS_FileCacheable(const char *const filename) { + extern cvar_t *com_buildScript; + if (com_buildScript && com_buildScript->integer) { return true; } - return( strchr(filename, '/') != 0 ); + return (strchr(filename, '/') != 0); } /* @@ -1295,53 +1258,53 @@ Used for streaming data out of either a separate file or a ZIP file. =========== */ -extern qboolean com_fullyInitialized; - -long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean uniqueFILE ) { - searchpath_t *search; - char *netpath; - pack_t *pak; - fileInPack_t *pakFile; - directory_t *dir; - long hash; - //unz_s *zfi; - //void *temp; - int l; - bool isUserConfig = false; +extern qboolean com_fullyInitialized; + +long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { + searchpath_t *search; + char *netpath; + pack_t *pak; + fileInPack_t *pakFile; + directory_t *dir; + long hash; + // unz_s *zfi; + // void *temp; + int l; + bool isUserConfig = false; hash = 0; FS_AssertInitialised(); - if ( file == NULL ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n" ); + if (file == NULL) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'file' parameter passed\n"); } - if ( !filename ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" ); + if (!filename) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n"); } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { *file = 0; return -1; } // make sure the q3key file is only readable by the quake3.exe at initialization // any other time the key should only be accessed in memory using the provided functions - if( com_fullyInitialized && strstr( filename, "q3key" ) ) { + if (com_fullyInitialized && strstr(filename, "q3key")) { *file = 0; return -1; } - isUserConfig = !Q_stricmp( filename, "autoexec.cfg" ) || !Q_stricmp( filename, Q3CONFIG_CFG ); + isUserConfig = !Q_stricmp(filename, "autoexec.cfg") || !Q_stricmp(filename, Q3CONFIG_CFG); // // search through the path, one element at a time @@ -1357,24 +1320,23 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // qboolean bFasterToReOpenUsingNewLocalFile = qfalse; - do - { + do { bFasterToReOpenUsingNewLocalFile = qfalse; - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // - if ( search->pack ) { + if (search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); } // is the element a pak file? - if ( search->pack && search->pack->hashTable[hash] ) { + if (search->pack && search->pack->hashTable[hash]) { // disregard if it doesn't match one of the allowed pure pak files - if ( !FS_PakIsPure(search->pack) ) { + if (!FS_PakIsPure(search->pack)) { continue; } // autoexec.cfg and openjk.cfg can only be loaded outside of pk3 files. - if ( isUserConfig ) { + if (isUserConfig) { continue; } @@ -1383,7 +1345,7 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { // found it! // mark the pak as having been referenced and mark specifics on cgame and ui @@ -1394,53 +1356,40 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // The x86.dll suffixes are needed in order for sv_pure to continue to // work on non-x86/windows systems... - l = strlen( filename ); - if ( !(pak->referenced & FS_GENERAL_REF)) { - if( !FS_IsExt(filename, ".shader", l) && - !FS_IsExt(filename, ".txt", l) && - !FS_IsExt(filename, ".str", l) && - !FS_IsExt(filename, ".cfg", l) && - !FS_IsExt(filename, ".config", l) && - !FS_IsExt(filename, ".bot", l) && - !FS_IsExt(filename, ".arena", l) && - !FS_IsExt(filename, ".menu", l) && - !FS_IsExt(filename, ".fcf", l) && - Q_stricmp(filename, "jampgamex86.dll") != 0 && - //Q_stricmp(filename, "vm/qagame.qvm") != 0 && - !strstr(filename, "levelshots")) - { + l = strlen(filename); + if (!(pak->referenced & FS_GENERAL_REF)) { + if (!FS_IsExt(filename, ".shader", l) && !FS_IsExt(filename, ".txt", l) && !FS_IsExt(filename, ".str", l) && + !FS_IsExt(filename, ".cfg", l) && !FS_IsExt(filename, ".config", l) && !FS_IsExt(filename, ".bot", l) && + !FS_IsExt(filename, ".arena", l) && !FS_IsExt(filename, ".menu", l) && !FS_IsExt(filename, ".fcf", l) && + Q_stricmp(filename, "jampgamex86.dll") != 0 && + // Q_stricmp(filename, "vm/qagame.qvm") != 0 && + !strstr(filename, "levelshots")) { pak->referenced |= FS_GENERAL_REF; } } - if (!(pak->referenced & FS_CGAME_REF)) - { - if ( Q_stricmp( filename, "cgame.qvm" ) == 0 || - Q_stricmp( filename, "cgamex86.dll" ) == 0 ) - { + if (!(pak->referenced & FS_CGAME_REF)) { + if (Q_stricmp(filename, "cgame.qvm") == 0 || Q_stricmp(filename, "cgamex86.dll") == 0) { pak->referenced |= FS_CGAME_REF; } } - if (!(pak->referenced & FS_UI_REF)) - { - if ( Q_stricmp( filename, "ui.qvm" ) == 0 || - Q_stricmp( filename, "uix86.dll" ) == 0 ) - { + if (!(pak->referenced & FS_UI_REF)) { + if (Q_stricmp(filename, "ui.qvm") == 0 || Q_stricmp(filename, "uix86.dll") == 0) { pak->referenced |= FS_UI_REF; } } - if ( uniqueFILE ) { + if (uniqueFILE) { // open a new file on the pakfile - fsh[*file].handleFiles.file.z = unzOpen (pak->pakFilename); + fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename); if (fsh[*file].handleFiles.file.z == NULL) { - Com_Error (ERR_FATAL, "Couldn't open %s", pak->pakFilename); + Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename); } } else { fsh[*file].handleFiles.file.z = pak->handle; } - Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) ); + Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qtrue; // set the file position in the zip file (also sets the current file info) @@ -1465,59 +1414,57 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique fsh[*file].zipFilePos = pakFile->pos; fsh[*file].zipFileLen = pakFile->len; - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n", - filename, pak->pakFilename ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n", filename, pak->pakFilename); } - #ifndef DEDICATED - #ifndef FINAL_BUILD +#ifndef DEDICATED +#ifndef FINAL_BUILD // Check for unprecached files when in game but not in the menus - if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI)) - { + if ((cls.state == CA_ACTIVE) && !(Key_GetCatcher() & KEYCATCH_UI)) { Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename); } - #endif - #endif // DEDICATED +#endif +#endif // DEDICATED return pakFile->len; } pakFile = pakFile->next; - } while(pakFile != NULL); - } else if ( search->dir ) { + } while (pakFile != NULL); + } else if (search->dir) { // check a file in the directory tree // if we are running restricted, the only files we // will allow to come from the directory are .cfg files - l = strlen( filename ); - // FIXME TTimo I'm not sure about the fs_numServerPaks test - // if you are using FS_ReadFile to find out if a file exists, - // this test can make the search fail although the file is in the directory - // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8 - // turned out I used FS_FileExists instead - if ( fs_numServerPaks ) { - if ( !FS_IsExt( filename, ".cfg", l ) && // for config files - !FS_IsExt( filename, ".fcf", l ) && // force configuration files - !FS_IsExt( filename, ".menu", l ) && // menu files - !FS_IsExt( filename, ".game", l ) && // menu files - !FS_IsExt( filename, ".dat", l ) && // for journal files - !FS_IsDemoExt( filename, l ) ) { // demos + l = strlen(filename); + // FIXME TTimo I'm not sure about the fs_numServerPaks test + // if you are using FS_ReadFile to find out if a file exists, + // this test can make the search fail although the file is in the directory + // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8 + // turned out I used FS_FileExists instead + if (fs_numServerPaks) { + if (!FS_IsExt(filename, ".cfg", l) && // for config files + !FS_IsExt(filename, ".fcf", l) && // force configuration files + !FS_IsExt(filename, ".menu", l) && // menu files + !FS_IsExt(filename, ".game", l) && // menu files + !FS_IsExt(filename, ".dat", l) && // for journal files + !FS_IsDemoExt(filename, l)) { // demos continue; } } dir = search->dir; - netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename ); - fsh[*file].handleFiles.file.o = fopen (netpath, "rb"); - if ( !fsh[*file].handleFiles.file.o ) { + netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); + fsh[*file].handleFiles.file.o = fopen(netpath, "rb"); + if (!fsh[*file].handleFiles.file.o) { continue; } - if ( !FS_IsExt( filename, ".cfg", l ) && // for config files - !FS_IsExt( filename, ".fcf", l ) && // force configuration files - !FS_IsExt( filename, ".menu", l ) && // menu files - !FS_IsExt( filename, ".game", l ) && // menu files - !FS_IsExt( filename, ".dat", l ) && // for journal files - !FS_IsDemoExt( filename, l ) ) { // demos + if (!FS_IsExt(filename, ".cfg", l) && // for config files + !FS_IsExt(filename, ".fcf", l) && // force configuration files + !FS_IsExt(filename, ".menu", l) && // menu files + !FS_IsExt(filename, ".game", l) && // menu files + !FS_IsExt(filename, ".dat", l) && // for journal files + !FS_IsDemoExt(filename, l)) { // demos fs_fakeChkSum = Q_flrand(0.0f, 1.0f); } #ifdef _WIN32 @@ -1525,94 +1472,79 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // if the time/date stamp != the network version (so it'll loop round again and use the network path, // which comes later in the search order) // - if ( fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp( dir->path, fs_basepath->string ) - && FS_FileCacheable(filename) ) - { - if ( Sys_FileOutOfDate( netpath, FS_BuildOSPath( fs_cdpath->string, dir->gamedir, filename ) )) - { + if (fs_copyfiles->integer == 2 && fs_cdpath->string[0] && !Q_stricmp(dir->path, fs_basepath->string) && FS_FileCacheable(filename)) { + if (Sys_FileOutOfDate(netpath, FS_BuildOSPath(fs_cdpath->string, dir->gamedir, filename))) { fclose(fsh[*file].handleFiles.file.o); fsh[*file].handleFiles.file.o = 0; - continue; //carry on to find the cdpath version. + continue; // carry on to find the cdpath version. } } #endif - Q_strncpyz( fsh[*file].name, filename, sizeof( fsh[*file].name ) ); + Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name)); fsh[*file].zipFile = qfalse; - if ( fs_debug->integer ) { - Com_Printf( "FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename, - dir->path, PATH_SEP, dir->gamedir ); + if (fs_debug->integer) { + Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename, dir->path, PATH_SEP, dir->gamedir); } #ifdef _WIN32 // if we are getting it from the cdpath, optionally copy it // to the basepath - if ( fs_copyfiles->integer && !Q_stricmp( dir->path, fs_cdpath->string ) ) { - char *copypath; - - copypath = FS_BuildOSPath( fs_basepath->string, dir->gamedir, filename ); - switch ( fs_copyfiles->integer ) - { - default: - case 1: - { - FS_CopyFile( netpath, copypath ); - } - break; - - case 2: - { + if (fs_copyfiles->integer && !Q_stricmp(dir->path, fs_cdpath->string)) { + char *copypath; + + copypath = FS_BuildOSPath(fs_basepath->string, dir->gamedir, filename); + switch (fs_copyfiles->integer) { + default: + case 1: { + FS_CopyFile(netpath, copypath); + } break; + + case 2: { + + if (FS_FileCacheable(filename)) { + // maybe change this to Com_DPrintf? On the other hand... + // + Com_Printf("fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath); + + FS_CreatePath(copypath); + + bool bOk = true; + if (!CopyFile(netpath, copypath, FALSE)) { + DWORD dwAttrs = GetFileAttributes(copypath); + SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY); + bOk = !!CopyFile(netpath, copypath, FALSE); + } - if (FS_FileCacheable(filename) ) - { - // maybe change this to Com_DPrintf? On the other hand... + if (bOk) { + // clear this handle and setup for re-opening of the new local copy... // - Com_Printf( "fs_copyfiles(2), Copying: %s to %s\n", netpath, copypath ); - - FS_CreatePath( copypath ); - - bool bOk = true; - if (!CopyFile( netpath, copypath, FALSE )) - { - DWORD dwAttrs = GetFileAttributes(copypath); - SetFileAttributes(copypath, dwAttrs & ~FILE_ATTRIBUTE_READONLY); - bOk = !!CopyFile( netpath, copypath, FALSE ); - } - - if (bOk) - { - // clear this handle and setup for re-opening of the new local copy... - // - bFasterToReOpenUsingNewLocalFile = qtrue; - fclose(fsh[*file].handleFiles.file.o); - fsh[*file].handleFiles.file.o = NULL; - } + bFasterToReOpenUsingNewLocalFile = qtrue; + fclose(fsh[*file].handleFiles.file.o); + fsh[*file].handleFiles.file.o = NULL; } } - break; + } break; } } #endif - if (bFasterToReOpenUsingNewLocalFile) - { - break; // and re-read the local copy, not the net version + if (bFasterToReOpenUsingNewLocalFile) { + break; // and re-read the local copy, not the net version } - #ifndef DEDICATED - #ifndef FINAL_BUILD +#ifndef DEDICATED +#ifndef FINAL_BUILD // Check for unprecached files when in game but not in the menus - if((cls.state == CA_ACTIVE) && !(Key_GetCatcher( ) & KEYCATCH_UI)) - { + if ((cls.state == CA_ACTIVE) && !(Key_GetCatcher() & KEYCATCH_UI)) { Com_Printf(S_COLOR_YELLOW "WARNING: File %s not precached\n", filename); } - #endif - #endif // dedicated +#endif +#endif // dedicated return FS_fplength(fsh[*file].handleFiles.file.o); } } - } - while ( bFasterToReOpenUsingNewLocalFile ); + } while (bFasterToReOpenUsingNewLocalFile); - Com_DPrintf ("Can't find %s\n", filename); + Com_DPrintf("Can't find %s\n", filename); #ifdef FS_MISSING if (missingFiles) { fprintf(missingFiles, "%s\n", filename); @@ -1624,22 +1556,20 @@ long FS_FOpenFileRead( const char *filename, fileHandle_t *file, qboolean unique // This is a bit of a hack but it is used for other OS'/arch to still be acceptable with pure servers. // Intentionally looking for x86.dll because this is all that exists in pk3s. -qboolean FS_FindPureDLL(const char *name) -{ +qboolean FS_FindPureDLL(const char *name) { char dllName[MAX_OSPATH]; fileHandle_t h; - if(!fs_searchpaths) + if (!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); - if ( !Cvar_VariableValue( "sv_pure" ) ) + if (!Cvar_VariableValue("sv_pure")) return qtrue; Com_sprintf(dllName, sizeof(dllName), "%sx86.dll", name); - if(FS_FOpenFileRead(dllName, &h, qtrue) > 0) - { - FS_FCloseFile( h ); + if (FS_FOpenFileRead(dllName, &h, qtrue) > 0) { + FS_FCloseFile(h); return qtrue; } return qfalse; @@ -1652,15 +1582,15 @@ FS_Read Properly handles partial reads ================= */ -int FS_Read( void *buffer, int len, fileHandle_t f ) { - int block, remaining; - int read; - byte *buf; - int tries; +int FS_Read(void *buffer, int len, fileHandle_t f) { + int block, remaining; + int read; + byte *buf; + int tries; FS_AssertInitialised(); - if ( !f ) { + if (!f) { return 0; } @@ -1672,19 +1602,19 @@ int FS_Read( void *buffer, int len, fileHandle_t f ) { tries = 0; while (remaining) { block = remaining; - read = fread (buf, 1, block, fsh[f].handleFiles.file.o); + read = fread(buf, 1, block, fsh[f].handleFiles.file.o); if (read == 0) { // we might have been trying to read from a CD, which // sometimes returns a 0 read on windows if (!tries) { tries = 1; } else { - return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read"); + return len - remaining; // Com_Error (ERR_FATAL, "FS_Read: 0 bytes read"); } } if (read == -1) { - Com_Error (ERR_FATAL, "FS_Read: -1 bytes read"); + Com_Error(ERR_FATAL, "FS_Read: -1 bytes read"); } remaining -= read; @@ -1703,16 +1633,16 @@ FS_Write Properly handles partial writes ================= */ -int FS_Write( const void *buffer, int len, fileHandle_t h ) { - int block, remaining; - int written; - byte *buf; - int tries; - FILE *f; +int FS_Write(const void *buffer, int len, fileHandle_t h) { + int block, remaining; + int written; + byte *buf; + int tries; + FILE *f; FS_AssertInitialised(); - if ( !h ) { + if (!h) { return 0; } @@ -1723,37 +1653,37 @@ int FS_Write( const void *buffer, int len, fileHandle_t h ) { tries = 0; while (remaining) { block = remaining; - written = fwrite (buf, 1, block, f); + written = fwrite(buf, 1, block, f); if (written == 0) { if (!tries) { tries = 1; } else { - Com_Printf( "FS_Write: 0 bytes written\n" ); + Com_Printf("FS_Write: 0 bytes written\n"); return 0; } } if (written == -1) { - Com_Printf( "FS_Write: -1 bytes written\n" ); + Com_Printf("FS_Write: -1 bytes written\n"); return 0; } remaining -= written; buf += written; } - if ( fsh[h].handleSync ) { - fflush( f ); + if (fsh[h].handleSync) { + fflush(f); } return len; } -void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL FS_Printf(fileHandle_t h, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr,fmt); - Q_vsnprintf (msg, sizeof(msg), fmt, argptr); - va_end (argptr); + va_start(argptr, fmt); + Q_vsnprintf(msg, sizeof(msg), fmt, argptr); + va_end(argptr); FS_Write(msg, strlen(msg), h); } @@ -1765,74 +1695,74 @@ FS_Seek ================= */ -int FS_Seek( fileHandle_t f, long offset, int origin ) { - int _origin; +int FS_Seek(fileHandle_t f, long offset, int origin) { + int _origin; FS_AssertInitialised(); if (fsh[f].zipFile == qtrue) { - //FIXME: this is really, really crappy + // FIXME: this is really, really crappy //(but better than what was here before) - byte buffer[PK3_SEEK_BUFFER_SIZE]; - int remainder; - int currentPosition = FS_FTell( f ); + byte buffer[PK3_SEEK_BUFFER_SIZE]; + int remainder; + int currentPosition = FS_FTell(f); // change negative offsets into FS_SEEK_SET - if ( offset < 0 ) { - switch( origin ) { - case FS_SEEK_END: - remainder = fsh[f].zipFileLen + offset; - break; + if (offset < 0) { + switch (origin) { + case FS_SEEK_END: + remainder = fsh[f].zipFileLen + offset; + break; - case FS_SEEK_CUR: - remainder = currentPosition + offset; - break; + case FS_SEEK_CUR: + remainder = currentPosition + offset; + break; - case FS_SEEK_SET: - default: - remainder = 0; - break; + case FS_SEEK_SET: + default: + remainder = 0; + break; } - if ( remainder < 0 ) { + if (remainder < 0) { remainder = 0; } origin = FS_SEEK_SET; } else { - if ( origin == FS_SEEK_END ) { + if (origin == FS_SEEK_END) { remainder = fsh[f].zipFileLen - currentPosition + offset; } else { remainder = offset; } } - switch( origin ) { - case FS_SEEK_SET: - if ( remainder == currentPosition ) { - return offset; - } - unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos); - unzOpenCurrentFile(fsh[f].handleFiles.file.z); - //fallthrough - - case FS_SEEK_END: - case FS_SEEK_CUR: - while( remainder > PK3_SEEK_BUFFER_SIZE ) { - FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f ); - remainder -= PK3_SEEK_BUFFER_SIZE; - } - FS_Read( buffer, remainder, f ); + switch (origin) { + case FS_SEEK_SET: + if (remainder == currentPosition) { return offset; + } + unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos); + unzOpenCurrentFile(fsh[f].handleFiles.file.z); + // fallthrough - default: - Com_Error( ERR_FATAL, "Bad origin in FS_Seek" ); - return -1; + case FS_SEEK_END: + case FS_SEEK_CUR: + while (remainder > PK3_SEEK_BUFFER_SIZE) { + FS_Read(buffer, PK3_SEEK_BUFFER_SIZE, f); + remainder -= PK3_SEEK_BUFFER_SIZE; + } + FS_Read(buffer, remainder, f); + return offset; + + default: + Com_Error(ERR_FATAL, "Bad origin in FS_Seek"); + return -1; } } else { FILE *file; file = FS_FileForHandle(f); - switch( origin ) { + switch (origin) { case FS_SEEK_CUR: _origin = SEEK_CUR; break; @@ -1844,11 +1774,11 @@ int FS_Seek( fileHandle_t f, long offset, int origin ) { break; default: _origin = SEEK_CUR; - Com_Error( ERR_FATAL, "Bad origin in FS_Seek\n" ); + Com_Error(ERR_FATAL, "Bad origin in FS_Seek\n"); break; } - return fseek( file, offset, _origin ); + return fseek(file, offset, _origin); } } @@ -1860,27 +1790,27 @@ CONVENIENCE FUNCTIONS FOR ENTIRE FILES ====================================================================================== */ -int FS_FileIsInPAK(const char *filename, int *pChecksum ) { - searchpath_t *search; - pack_t *pak; - fileInPack_t *pakFile; - long hash = 0; +int FS_FileIsInPAK(const char *filename, int *pChecksum) { + searchpath_t *search; + pack_t *pak; + fileInPack_t *pakFile; + long hash = 0; FS_AssertInitialised(); - if ( !filename ) { - Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n" ); + if (!filename) { + Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed\n"); } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { return -1; } @@ -1888,15 +1818,15 @@ int FS_FileIsInPAK(const char *filename, int *pChecksum ) { // search through the path, one element at a time // - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // if (search->pack) { hash = FS_HashFileName(filename, search->pack->hashSize); } // is the element a pak file? - if ( search->pack && search->pack->hashTable[hash] ) { + if (search->pack && search->pack->hashTable[hash]) { // disregard if it doesn't match one of the allowed pure pak files - if ( !FS_PakIsPure(search->pack) ) { + if (!FS_PakIsPure(search->pack)) { continue; } @@ -1905,14 +1835,14 @@ int FS_FileIsInPAK(const char *filename, int *pChecksum ) { pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { if (pChecksum) { *pChecksum = pak->pure_checksum; } return 1; } pakFile = pakFile->next; - } while(pakFile != NULL); + } while (pakFile != NULL); } } return -1; @@ -1926,37 +1856,38 @@ Filename are relative to the quake search path a null buffer will just return the file length without loading ============ */ -long FS_ReadFile( const char *qpath, void **buffer ) { - fileHandle_t h; - byte* buf; - qboolean isConfig; - long len; +long FS_ReadFile(const char *qpath, void **buffer) { + fileHandle_t h; + byte *buf; + qboolean isConfig; + long len; FS_AssertInitialised(); - if ( !qpath || !qpath[0] ) { - Com_Error( ERR_FATAL, "FS_ReadFile with empty name\n" ); + if (!qpath || !qpath[0]) { + Com_Error(ERR_FATAL, "FS_ReadFile with empty name\n"); } - buf = NULL; // quiet compiler warning + buf = NULL; // quiet compiler warning // if this is a .cfg file and we are playing back a journal, read // it from the journal file - if ( strstr( qpath, ".cfg" ) ) { + if (strstr(qpath, ".cfg")) { isConfig = qtrue; - if ( com_journal && com_journal->integer == 2 ) { - int r; - - Com_DPrintf( "Loading %s from journal file.\n", qpath ); - r = FS_Read( &len, sizeof( len ), com_journalDataFile ); - if ( r != sizeof( len ) ) { - if (buffer != NULL) *buffer = NULL; + if (com_journal && com_journal->integer == 2) { + int r; + + Com_DPrintf("Loading %s from journal file.\n", qpath); + r = FS_Read(&len, sizeof(len), com_journalDataFile); + if (r != sizeof(len)) { + if (buffer != NULL) + *buffer = NULL; return -1; } // if the file didn't exist when the journal was created if (!len) { if (buffer == NULL) { - return 1; // hack for old journal files + return 1; // hack for old journal files } *buffer = NULL; return -1; @@ -1965,12 +1896,12 @@ long FS_ReadFile( const char *qpath, void **buffer ) { return len; } - buf = (unsigned char *)Hunk_AllocateTempMemory(len+1); + buf = (unsigned char *)Hunk_AllocateTempMemory(len + 1); *buffer = buf; - r = FS_Read( buf, len, com_journalDataFile ); - if ( r != len ) { - Com_Error( ERR_FATAL, "Read from journalDataFile failed" ); + r = FS_Read(buf, len, com_journalDataFile); + if (r != len) { + Com_Error(ERR_FATAL, "Read from journalDataFile failed"); } fs_loadCount++; @@ -1985,51 +1916,51 @@ long FS_ReadFile( const char *qpath, void **buffer ) { } // look for it in the filesystem or pack files - len = FS_FOpenFileRead( qpath, &h, qfalse ); - if ( h == 0 ) { - if ( buffer ) { + len = FS_FOpenFileRead(qpath, &h, qfalse); + if (h == 0) { + if (buffer) { *buffer = NULL; } // if we are journalling and it is a config file, write a zero to the journal file - if ( isConfig && com_journal && com_journal->integer == 1 ) { - Com_DPrintf( "Writing zero for %s to journal file.\n", qpath ); + if (isConfig && com_journal && com_journal->integer == 1) { + Com_DPrintf("Writing zero for %s to journal file.\n", qpath); len = 0; - FS_Write( &len, sizeof( len ), com_journalDataFile ); - FS_Flush( com_journalDataFile ); + FS_Write(&len, sizeof(len), com_journalDataFile); + FS_Flush(com_journalDataFile); } return -1; } - if ( !buffer ) { - if ( isConfig && com_journal && com_journal->integer == 1 ) { - Com_DPrintf( "Writing len for %s to journal file.\n", qpath ); - FS_Write( &len, sizeof( len ), com_journalDataFile ); - FS_Flush( com_journalDataFile ); + if (!buffer) { + if (isConfig && com_journal && com_journal->integer == 1) { + Com_DPrintf("Writing len for %s to journal file.\n", qpath); + FS_Write(&len, sizeof(len), com_journalDataFile); + FS_Flush(com_journalDataFile); } - FS_FCloseFile( h); + FS_FCloseFile(h); return len; } fs_loadCount++; - buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse); - buf[len]='\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool + buf = (byte *)Z_Malloc(len + 1, TAG_FILESYS, qfalse); + buf[len] = '\0'; // because we're not calling Z_Malloc with optional trailing 'bZeroIt' bool *buffer = buf; -// Z_Label(buf, qpath); + // Z_Label(buf, qpath); - FS_Read (buf, len, h); + FS_Read(buf, len, h); // guarantee that it will have a trailing 0 for string operations buf[len] = 0; - FS_FCloseFile( h ); + FS_FCloseFile(h); // if we are journalling and it is a config file, write it to the journal file - if ( isConfig && com_journal && com_journal->integer == 1 ) { - Com_DPrintf( "Writing %s to journal file.\n", qpath ); - FS_Write( &len, sizeof( len ), com_journalDataFile ); - FS_Write( buf, len, com_journalDataFile ); - FS_Flush( com_journalDataFile ); + if (isConfig && com_journal && com_journal->integer == 1) { + Com_DPrintf("Writing %s to journal file.\n", qpath); + FS_Write(&len, sizeof(len), com_journalDataFile); + FS_Write(buf, len, com_journalDataFile); + FS_Flush(com_journalDataFile); } return len; } @@ -2039,13 +1970,13 @@ long FS_ReadFile( const char *qpath, void **buffer ) { FS_FreeFile ============= */ -void FS_FreeFile( void *buffer ) { +void FS_FreeFile(void *buffer) { FS_AssertInitialised(); - if ( !buffer ) { - Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" ); + if (!buffer) { + Com_Error(ERR_FATAL, "FS_FreeFile( NULL )"); } - Z_Free( buffer ); + Z_Free(buffer); } /* @@ -2055,24 +1986,24 @@ FS_WriteFile Filename are reletive to the quake search path ============ */ -void FS_WriteFile( const char *qpath, const void *buffer, int size ) { +void FS_WriteFile(const char *qpath, const void *buffer, int size) { fileHandle_t f; FS_AssertInitialised(); - if ( !qpath || !buffer ) { - Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" ); + if (!qpath || !buffer) { + Com_Error(ERR_FATAL, "FS_WriteFile: NULL parameter"); } - f = FS_FOpenFileWrite( qpath ); - if ( !f ) { - Com_Printf( "Failed to open %s\n", qpath ); + f = FS_FOpenFileWrite(qpath); + if (!f) { + Com_Printf("Failed to open %s\n", qpath); return; } - FS_Write( buffer, size, f ); + FS_Write(buffer, size, f); - FS_FCloseFile( f ); + FS_FCloseFile(f); } /* @@ -2091,34 +2022,32 @@ Creates a new pak_t in the search chain for the contents of a zip file. ================= */ -static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) -{ - fileInPack_t *buildBuffer; - pack_t *pack; - unzFile uf; - int err; +static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename) { + fileInPack_t *buildBuffer; + pack_t *pack; + unzFile uf; + int err; unz_global_info gi; - char filename_inzip[MAX_ZPATH]; - unz_file_info file_info; - int len; - size_t i; - long hash; - int fs_numHeaderLongs; - int *fs_headerLongs; - char *namePtr; + char filename_inzip[MAX_ZPATH]; + unz_file_info file_info; + int len; + size_t i; + long hash; + int fs_numHeaderLongs; + int *fs_headerLongs; + char *namePtr; fs_numHeaderLongs = 0; uf = unzOpen(zipfile); - err = unzGetGlobalInfo (uf,&gi); + err = unzGetGlobalInfo(uf, &gi); if (err != UNZ_OK) return NULL; len = 0; unzGoToFirstFile(uf); - for (i = 0; i < gi.number_entry; i++) - { + for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; @@ -2127,10 +2056,10 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) unzGoToNextFile(uf); } - buildBuffer = (struct fileInPack_s *)Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len, TAG_FILESYS, qtrue ); - namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t ); - fs_headerLongs = (int *)Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int), TAG_FILESYS, qtrue ); - fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed ); + buildBuffer = (struct fileInPack_s *)Z_Malloc((gi.number_entry * sizeof(fileInPack_t)) + len, TAG_FILESYS, qtrue); + namePtr = ((char *)buildBuffer) + gi.number_entry * sizeof(fileInPack_t); + fs_headerLongs = (int *)Z_Malloc((gi.number_entry + 1) * sizeof(int), TAG_FILESYS, qtrue); + fs_headerLongs[fs_numHeaderLongs++] = LittleLong(fs_checksumFeed); // get the hash table size from the number of files in the zip // because lots of custom pk3 files have less than 32 or 64 files @@ -2140,27 +2069,26 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) } } - pack = (pack_t *)Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue ); + pack = (pack_t *)Z_Malloc(sizeof(pack_t) + i * sizeof(fileInPack_t *), TAG_FILESYS, qtrue); pack->hashSize = i; - pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t )); - for(int j = 0; j < pack->hashSize; j++) { + pack->hashTable = (fileInPack_t **)(((char *)pack) + sizeof(pack_t)); + for (int j = 0; j < pack->hashSize; j++) { pack->hashTable[j] = NULL; } - Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) ); - Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) ); + Q_strncpyz(pack->pakFilename, zipfile, sizeof(pack->pakFilename)); + Q_strncpyz(pack->pakBasename, basename, sizeof(pack->pakBasename)); // strip .pk3 if needed - if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) { - pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0; + if (strlen(pack->pakBasename) > 4 && !Q_stricmp(pack->pakBasename + strlen(pack->pakBasename) - 4, ".pk3")) { + pack->pakBasename[strlen(pack->pakBasename) - 4] = 0; } pack->handle = uf; pack->numfiles = gi.number_entry; unzGoToFirstFile(uf); - for (i = 0; i < gi.number_entry; i++) - { + for (i = 0; i < gi.number_entry; i++) { err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { break; @@ -2168,10 +2096,10 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) if (file_info.uncompressed_size > 0) { fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc); } - Q_strlwr( filename_inzip ); + Q_strlwr(filename_inzip); hash = FS_HashFileName(filename_inzip, pack->hashSize); buildBuffer[i].name = namePtr; - strcpy( buildBuffer[i].name, filename_inzip ); + strcpy(buildBuffer[i].name, filename_inzip); namePtr += strlen(filename_inzip) + 1; // store the file position in the zip buildBuffer[i].pos = unzGetOffset(uf); @@ -2181,10 +2109,10 @@ static pack_t *FS_LoadZipFile( const char *zipfile, const char *basename ) unzGoToNextFile(uf); } - pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) ); - pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs ); - pack->checksum = LittleLong( pack->checksum ); - pack->pure_checksum = LittleLong( pack->pure_checksum ); + pack->checksum = Com_BlockChecksum(&fs_headerLongs[1], sizeof(*fs_headerLongs) * (fs_numHeaderLongs - 1)); + pack->pure_checksum = Com_BlockChecksum(fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs); + pack->checksum = LittleLong(pack->checksum); + pack->pure_checksum = LittleLong(pack->pure_checksum); Z_Free(fs_headerLongs); @@ -2200,8 +2128,7 @@ Frees a pak structure and releases all associated resources ================= */ -void FS_FreePak(pack_t *thepak) -{ +void FS_FreePak(pack_t *thepak) { unzClose(thepak->handle); Z_Free(thepak->buildBuffer); Z_Free(thepak); @@ -2214,22 +2141,20 @@ FS_GetZipChecksum Compares whether the given pak file matches a referenced checksum ================= */ -qboolean FS_CompareZipChecksum(const char *zipfile) -{ +qboolean FS_CompareZipChecksum(const char *zipfile) { pack_t *thepak; int index, checksum; thepak = FS_LoadZipFile(zipfile, ""); - if(!thepak) + if (!thepak) return qfalse; checksum = thepak->checksum; FS_FreePak(thepak); - for(index = 0; index < fs_numServerReferencedPaks; index++) - { - if(checksum == fs_serverReferencedPaks[index]) + for (index = 0; index < fs_numServerReferencedPaks; index++) { + if (checksum == fs_serverReferencedPaks[index]) return qtrue; } @@ -2244,9 +2169,9 @@ DIRECTORY SCANNING FUNCTIONS ================================================================================= */ -#define MAX_FOUND_FILES 0x1000 +#define MAX_FOUND_FILES 0x1000 -static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { +static int FS_ReturnPath(const char *zname, char *zpath, int *depth) { int len, at, newdep; newdep = 0; @@ -2254,9 +2179,8 @@ static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { len = 0; at = 0; - while(zname[at] != 0) - { - if (zname[at]=='/' || zname[at]=='\\') { + while (zname[at] != 0) { + if (zname[at] == '/' || zname[at] == '\\') { len = at; newdep++; } @@ -2274,18 +2198,18 @@ static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { FS_AddFileToList ================== */ -static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) { - int i; +static int FS_AddFileToList(char *name, char *list[MAX_FOUND_FILES], int nfiles) { + int i; - if ( nfiles == MAX_FOUND_FILES - 1 ) { + if (nfiles == MAX_FOUND_FILES - 1) { return nfiles; } - for ( i = 0 ; i < nfiles ; i++ ) { - if ( !Q_stricmp( name, list[i] ) ) { - return nfiles; // allready in list + for (i = 0; i < nfiles; i++) { + if (!Q_stricmp(name, list[i])) { + return nfiles; // allready in list } } - list[nfiles] = CopyString( name ); + list[nfiles] = CopyString(name); nfiles++; return nfiles; @@ -2299,49 +2223,49 @@ Returns a uniqued list of files that match the given criteria from all search paths =============== */ -char **FS_ListFilteredFiles( const char *path, const char *extension, char *filter, int *numfiles ) { - int nfiles; - char **listCopy; - char *list[MAX_FOUND_FILES]; - searchpath_t *search; - int i; - int pathLength; - int extensionLength; - int length, pathDepth, temp; - pack_t *pak; - fileInPack_t *buildBuffer; - char zpath[MAX_ZPATH]; - - if ( !fs_searchpaths ) { - Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" ); - } - - if ( !path ) { +char **FS_ListFilteredFiles(const char *path, const char *extension, char *filter, int *numfiles) { + int nfiles; + char **listCopy; + char *list[MAX_FOUND_FILES]; + searchpath_t *search; + int i; + int pathLength; + int extensionLength; + int length, pathDepth, temp; + pack_t *pak; + fileInPack_t *buildBuffer; + char zpath[MAX_ZPATH]; + + if (!fs_searchpaths) { + Com_Error(ERR_FATAL, "Filesystem call made without initialization\n"); + } + + if (!path) { *numfiles = 0; return NULL; } - if ( !extension ) { + if (!extension) { extension = ""; } - pathLength = strlen( path ); - if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) { + pathLength = strlen(path); + if (path[pathLength - 1] == '\\' || path[pathLength - 1] == '/') { pathLength--; } - extensionLength = strlen( extension ); + extensionLength = strlen(extension); nfiles = 0; FS_ReturnPath(path, zpath, &pathDepth); // // search through the path, one element at a time, adding to list // - for (search = fs_searchpaths ; search ; search = search->next) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? if (search->pack) { - //ZOID: If we are pure, don't search for files on paks that - // aren't on the pure list - if ( !FS_PakIsPure(search->pack) ) { + // ZOID: If we are pure, don't search for files on paks that + // aren't on the pure list + if (!FS_PakIsPure(search->pack)) { continue; } @@ -2349,68 +2273,63 @@ char **FS_ListFilteredFiles( const char *path, const char *extension, char *filt pak = search->pack; buildBuffer = pak->buildBuffer; for (i = 0; i < pak->numfiles; i++) { - char *name; - int zpathLen, depth; + char *name; + int zpathLen, depth; // check for directory match name = buildBuffer[i].name; // if (filter) { // case insensitive - if (!Com_FilterPath( filter, name, qfalse )) + if (!Com_FilterPath(filter, name, qfalse)) continue; // unique the match - nfiles = FS_AddFileToList( name, list, nfiles ); - } - else { + nfiles = FS_AddFileToList(name, list, nfiles); + } else { zpathLen = FS_ReturnPath(name, zpath, &depth); - if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) { + if ((depth - pathDepth) > 2 || pathLength > zpathLen || Q_stricmpn(name, path, pathLength)) { continue; } // check for extension match - length = strlen( name ); - if ( length < extensionLength ) { + length = strlen(name); + if (length < extensionLength) { continue; } - if ( Q_stricmp( name + length - extensionLength, extension ) ) { + if (Q_stricmp(name + length - extensionLength, extension)) { continue; } // unique the match temp = pathLength; if (pathLength) { - temp++; // include the '/' + temp++; // include the '/' } - nfiles = FS_AddFileToList( name + temp, list, nfiles ); + nfiles = FS_AddFileToList(name + temp, list, nfiles); } } } else if (search->dir) { // scan for files in the filesystem - char *netpath; - int numSysFiles; - char **sysFiles; - char *name; + char *netpath; + int numSysFiles; + char **sysFiles; + char *name; // don't scan directories for files if we are pure or restricted - if ( fs_numServerPaks && - (!extension || Q_stricmp(extension, "fcf")) ) - { - //rww - allow scanning for fcf files outside of pak even if pure - continue; - } - else - { - netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path ); - sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse ); - for ( i = 0 ; i < numSysFiles ; i++ ) { + if (fs_numServerPaks && (!extension || Q_stricmp(extension, "fcf"))) { + // rww - allow scanning for fcf files outside of pak even if pure + continue; + } else { + netpath = FS_BuildOSPath(search->dir->path, search->dir->gamedir, path); + sysFiles = Sys_ListFiles(netpath, extension, filter, &numSysFiles, qfalse); + for (i = 0; i < numSysFiles; i++) { // unique the match name = sysFiles[i]; - nfiles = FS_AddFileToList( name, list, nfiles ); + nfiles = FS_AddFileToList(name, list, nfiles); } - Sys_FreeFileList( sysFiles ); + Sys_FreeFileList(sysFiles); } } } @@ -2418,12 +2337,12 @@ char **FS_ListFilteredFiles( const char *path, const char *extension, char *filt // return a copy of the list *numfiles = nfiles; - if ( !nfiles ) { + if (!nfiles) { return NULL; } - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_FILESYS ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_FILESYS); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; @@ -2436,42 +2355,39 @@ char **FS_ListFilteredFiles( const char *path, const char *extension, char *filt FS_ListFiles ================= */ -char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) { - return FS_ListFilteredFiles( path, extension, NULL, numfiles ); -} +char **FS_ListFiles(const char *path, const char *extension, int *numfiles) { return FS_ListFilteredFiles(path, extension, NULL, numfiles); } /* ================= FS_FreeFileList ================= */ -void FS_FreeFileList( char **fileList ) { - //rwwRMG - changed to fileList to not conflict with list type - int i; +void FS_FreeFileList(char **fileList) { + // rwwRMG - changed to fileList to not conflict with list type + int i; - if ( !fs_searchpaths ) { - Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" ); + if (!fs_searchpaths) { + Com_Error(ERR_FATAL, "Filesystem call made without initialization\n"); } - if ( !fileList ) { + if (!fileList) { return; } - for ( i = 0 ; fileList[i] ; i++ ) { - Z_Free( fileList[i] ); + for (i = 0; fileList[i]; i++) { + Z_Free(fileList[i]); } - Z_Free( fileList ); + Z_Free(fileList); } - /* ================ FS_GetFileList ================ */ -int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { - int nFiles, i, nTotal, nLen; +int FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize) { + int nFiles, i, nTotal, nLen; char **pFiles = NULL; *listbuf = 0; @@ -2484,14 +2400,13 @@ int FS_GetFileList( const char *path, const char *extension, char *listbuf, int pFiles = FS_ListFiles(path, extension, &nFiles); - for (i =0; i < nFiles; i++) { + for (i = 0; i < nFiles; i++) { nLen = strlen(pFiles[i]) + 1; if (nTotal + nLen + 1 < bufsize) { strcpy(listbuf, pFiles[i]); listbuf += nLen; nTotal += nLen; - } - else { + } else { nFiles = i; break; } @@ -2507,20 +2422,17 @@ int FS_GetFileList( const char *path, const char *extension, char *listbuf, int Sys_ConcatenateFileLists mkv: Naive implementation. Concatenates three lists into a - new list, and frees the old lists from the heap. + new list, and frees the old lists from the heap. bk001129 - from cvs1.17 (mkv) FIXME TTimo those two should move to common.c next to Sys_ListFiles ======================= */ -static unsigned int Sys_CountFileList(char **fileList) -{ +static unsigned int Sys_CountFileList(char **fileList) { int i = 0; - if (fileList) - { - while (*fileList) - { + if (fileList) { + while (*fileList) { fileList++; i++; } @@ -2528,17 +2440,16 @@ static unsigned int Sys_CountFileList(char **fileList) return i; } -static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 ) -{ +static char **Sys_ConcatenateFileLists(char **list0, char **list1, char **list2) { int totalLength = 0; - char** cat = NULL, **dst, **src; + char **cat = NULL, **dst, **src; totalLength += Sys_CountFileList(list0); totalLength += Sys_CountFileList(list1); totalLength += Sys_CountFileList(list2); /* Create new list. */ - dst = cat = (char **)Z_Malloc( ( totalLength + 1 ) * sizeof( char* ), TAG_FILESYS, qtrue ); + dst = cat = (char **)Z_Malloc((totalLength + 1) * sizeof(char *), TAG_FILESYS, qtrue); /* Copy over lists. */ if (list0) { @@ -2559,16 +2470,19 @@ static char** Sys_ConcatenateFileLists( char **list0, char **list1, char **list2 // Free our old lists. // NOTE: not freeing their content, it's been merged in dst and still being used - if (list0) Z_Free( list0 ); - if (list1) Z_Free( list1 ); - if (list2) Z_Free( list2 ); + if (list0) + Z_Free(list0); + if (list1) + Z_Free(list1); + if (list2) + Z_Free(list2); return cat; } //#endif // For base game mod listing -const char *SE_GetString( const char *psPackageAndStringReference ); +const char *SE_GetString(const char *psPackageAndStringReference); /* ================ @@ -2579,8 +2493,8 @@ A mod directory is a peer to base with a pk3 in it The directories are searched in base path, cd path and home path ================ */ -int FS_GetModList( char *listbuf, int bufsize ) { - int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen; +int FS_GetModList(char *listbuf, int bufsize) { + int nMods, i, j, nTotal, nLen, nPaks, nPotential, nDescLen; char **pFiles = NULL; char **pPaks = NULL; char *name, *path; @@ -2596,23 +2510,22 @@ int FS_GetModList( char *listbuf, int bufsize ) { *listbuf = 0; nMods = nPotential = nTotal = 0; - pFiles0 = Sys_ListFiles( fs_homepath->string, NULL, NULL, &dummy, qtrue ); - pFiles1 = Sys_ListFiles( fs_basepath->string, NULL, NULL, &dummy, qtrue ); - pFiles2 = Sys_ListFiles( fs_cdpath->string, NULL, NULL, &dummy, qtrue ); + pFiles0 = Sys_ListFiles(fs_homepath->string, NULL, NULL, &dummy, qtrue); + pFiles1 = Sys_ListFiles(fs_basepath->string, NULL, NULL, &dummy, qtrue); + pFiles2 = Sys_ListFiles(fs_cdpath->string, NULL, NULL, &dummy, qtrue); // we searched for mods in the three paths // it is likely that we have duplicate names now, which we will cleanup below - pFiles = Sys_ConcatenateFileLists( pFiles0, pFiles1, pFiles2 ); + pFiles = Sys_ConcatenateFileLists(pFiles0, pFiles1, pFiles2); nPotential = Sys_CountFileList(pFiles); - for ( i = 0 ; i < nPotential ; i++ ) { + for (i = 0; i < nPotential; i++) { name = pFiles[i]; // NOTE: cleaner would involve more changes // ignore duplicate mod directories - if (i!=0) { + if (i != 0) { bDrop = qfalse; - for(j=0; jstring, name, "" ); + path = FS_BuildOSPath(fs_basepath->string, name, ""); nPaks = 0; pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); - Sys_FreeFileList( pPaks ); // we only use Sys_ListFiles to check wether .pk3 files are present + Sys_FreeFileList(pPaks); // we only use Sys_ListFiles to check wether .pk3 files are present /* Try on cd path */ - if( nPaks <= 0 ) { - path = FS_BuildOSPath( fs_cdpath->string, name, "" ); + if (nPaks <= 0) { + path = FS_BuildOSPath(fs_cdpath->string, name, ""); nPaks = 0; - pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse ); - Sys_FreeFileList( pPaks ); + pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); + Sys_FreeFileList(pPaks); } /* try on home path */ - if ( nPaks <= 0 ) - { - path = FS_BuildOSPath( fs_homepath->string, name, "" ); + if (nPaks <= 0) { + path = FS_BuildOSPath(fs_homepath->string, name, ""); nPaks = 0; - pPaks = Sys_ListFiles( path, ".pk3", NULL, &nPaks, qfalse ); - Sys_FreeFileList( pPaks ); + pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse); + Sys_FreeFileList(pPaks); } if (nPaks > 0) { - bool isBase = !Q_stricmp( name, BASEGAME ); + bool isBase = !Q_stricmp(name, BASEGAME); nLen = isBase ? 1 : strlen(name) + 1; // nLen is the length of the mod path // we need to see if there is a description available descPath[0] = '\0'; strcpy(descPath, name); strcat(descPath, "/description.txt"); - nDescLen = FS_SV_FOpenFileRead( descPath, &descHandle ); - if ( nDescLen > 0 && descHandle) { + nDescLen = FS_SV_FOpenFileRead(descPath, &descHandle); + if (nDescLen > 0 && descHandle) { FILE *file; file = FS_FileForHandle(descHandle); - Com_Memset( descPath, 0, sizeof( descPath ) ); + Com_Memset(descPath, 0, sizeof(descPath)); nDescLen = fread(descPath, 1, 48, file); if (nDescLen >= 0) { descPath[nDescLen] = '\0'; } FS_FCloseFile(descHandle); - } else if ( isBase ) { + } else if (isBase) { strcpy(descPath, SE_GetString("MENUS_JEDI_ACADEMY")); } else { strcpy(descPath, name); @@ -2677,7 +2589,7 @@ int FS_GetModList( char *listbuf, int bufsize ) { nDescLen = strlen(descPath) + 1; if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) { - if ( isBase ) + if (isBase) strcpy(listbuf, ""); else strcpy(listbuf, name); @@ -2686,14 +2598,13 @@ int FS_GetModList( char *listbuf, int bufsize ) { listbuf += nDescLen; nTotal += nLen + nDescLen; nMods++; - } - else { + } else { break; } } } } - Sys_FreeFileList( pFiles ); + Sys_FreeFileList(pFiles); return nMods; } @@ -2705,35 +2616,35 @@ int FS_GetModList( char *listbuf, int bufsize ) { FS_Dir_f ================ */ -void FS_Dir_f( void ) { - char *path; - char *extension; - char **dirnames; - int ndirs; - int i; - - if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) { - Com_Printf( "usage: dir [extension]\n" ); +void FS_Dir_f(void) { + char *path; + char *extension; + char **dirnames; + int ndirs; + int i; + + if (Cmd_Argc() < 2 || Cmd_Argc() > 3) { + Com_Printf("usage: dir [extension]\n"); return; } - if ( Cmd_Argc() == 2 ) { - path = Cmd_Argv( 1 ); + if (Cmd_Argc() == 2) { + path = Cmd_Argv(1); extension = ""; } else { - path = Cmd_Argv( 1 ); - extension = Cmd_Argv( 2 ); + path = Cmd_Argv(1); + extension = Cmd_Argv(2); } - Com_Printf( "Directory of %s %s\n", path, extension ); - Com_Printf( "---------------\n" ); + Com_Printf("Directory of %s %s\n", path, extension); + Com_Printf("---------------\n"); - dirnames = FS_ListFiles( path, extension, &ndirs ); + dirnames = FS_ListFiles(path, extension, &ndirs); - for ( i = 0; i < ndirs; i++ ) { - Com_Printf( "%s\n", dirnames[i] ); + for (i = 0; i < ndirs; i++) { + Com_Printf("%s\n", dirnames[i]); } - FS_FreeFileList( dirnames ); + FS_FreeFileList(dirnames); } /* @@ -2741,9 +2652,9 @@ void FS_Dir_f( void ) { FS_ConvertPath =========== */ -void FS_ConvertPath( char *s ) { +void FS_ConvertPath(char *s) { while (*s) { - if ( *s == '\\' || *s == ':' ) { + if (*s == '\\' || *s == ':') { *s = '/'; } s++; @@ -2757,8 +2668,8 @@ FS_PathCmp Ignore case and separator char distinctions =========== */ -int FS_PathCmp( const char *s1, const char *s2 ) { - int c1, c2; +int FS_PathCmp(const char *s1, const char *s2) { + int c1, c2; do { c1 = *s1++; @@ -2771,22 +2682,22 @@ int FS_PathCmp( const char *s1, const char *s2 ) { c2 -= ('a' - 'A'); } - if ( c1 == '\\' || c1 == ':' ) { + if (c1 == '\\' || c1 == ':') { c1 = '/'; } - if ( c2 == '\\' || c2 == ':' ) { + if (c2 == '\\' || c2 == ':') { c2 = '/'; } if (c1 < c2) { - return -1; // strings not equal + return -1; // strings not equal } if (c1 > c2) { return 1; } } while (c1); - return 0; // strings are equal + return 0; // strings are equal } /* @@ -2798,7 +2709,7 @@ void FS_SortFileList(char **filelist, int numfiles) { int i, j, k, numsortedfiles; char **sortedlist; - sortedlist = (char **)Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ), TAG_FILESYS, qtrue ); + sortedlist = (char **)Z_Malloc((numfiles + 1) * sizeof(*sortedlist), TAG_FILESYS, qtrue); sortedlist[0] = NULL; numsortedfiles = 0; for (i = 0; i < numfiles; i++) { @@ -2808,12 +2719,12 @@ void FS_SortFileList(char **filelist, int numfiles) { } } for (k = numsortedfiles; k > j; k--) { - sortedlist[k] = sortedlist[k-1]; + sortedlist[k] = sortedlist[k - 1]; } sortedlist[j] = filelist[i]; numsortedfiles++; } - Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) ); + Com_Memcpy(filelist, sortedlist, numfiles * sizeof(*filelist)); Z_Free(sortedlist); } @@ -2822,32 +2733,32 @@ void FS_SortFileList(char **filelist, int numfiles) { FS_NewDir_f ================ */ -void FS_NewDir_f( void ) { - char *filter; - char **dirnames; - int ndirs; - int i; - - if ( Cmd_Argc() < 2 ) { - Com_Printf( "usage: fdir \n" ); - Com_Printf( "example: fdir *ffa*.bsp\n"); +void FS_NewDir_f(void) { + char *filter; + char **dirnames; + int ndirs; + int i; + + if (Cmd_Argc() < 2) { + Com_Printf("usage: fdir \n"); + Com_Printf("example: fdir *ffa*.bsp\n"); return; } - filter = Cmd_Argv( 1 ); + filter = Cmd_Argv(1); - Com_Printf( "---------------\n" ); + Com_Printf("---------------\n"); - dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs ); + dirnames = FS_ListFilteredFiles("", "", filter, &ndirs); FS_SortFileList(dirnames, ndirs); - for ( i = 0; i < ndirs; i++ ) { + for (i = 0; i < ndirs; i++) { FS_ConvertPath(dirnames[i]); - Com_Printf( "%s\n", dirnames[i] ); + Com_Printf("%s\n", dirnames[i]); } - Com_Printf( "%d files listed\n", ndirs ); - FS_FreeFileList( dirnames ); + Com_Printf("%d files listed\n", ndirs); + FS_FreeFileList(dirnames); } /* @@ -2856,30 +2767,30 @@ FS_Path_f ============ */ -void FS_Path_f( void ) { - searchpath_t *s; - int i; +void FS_Path_f(void) { + searchpath_t *s; + int i; - Com_Printf ("Current search path:\n"); + Com_Printf("Current search path:\n"); for (s = fs_searchpaths; s; s = s->next) { if (s->pack) { - Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles); - if ( fs_numServerPaks ) { - if ( !FS_PakIsPure(s->pack) ) { - Com_Printf( " not on the pure list\n" ); + Com_Printf("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles); + if (fs_numServerPaks) { + if (!FS_PakIsPure(s->pack)) { + Com_Printf(" not on the pure list\n"); } else { - Com_Printf( " on the pure list\n" ); + Com_Printf(" on the pure list\n"); } } } else { - Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir ); + Com_Printf("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir); } } - Com_Printf( "\n" ); - for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { - if ( fsh[i].handleFiles.file.o ) { - Com_Printf( "handle %i: %s\n", i, fsh[i].name ); + Com_Printf("\n"); + for (i = 1; i < MAX_FILE_HANDLES; i++) { + if (fsh[i].handleFiles.file.o) { + Com_Printf("handle %i: %s\n", i, fsh[i].name); } } } @@ -2892,17 +2803,17 @@ The only purpose of this function is to allow game script files to copy arbitrary files furing an "fs_copyfiles 1" run. ============ */ -void FS_TouchFile_f( void ) { - fileHandle_t f; +void FS_TouchFile_f(void) { + fileHandle_t f; - if ( Cmd_Argc() != 2 ) { - Com_Printf( "Usage: touchFile \n" ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: touchFile \n"); return; } - FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse ); - if ( f ) { - FS_FCloseFile( f ); + FS_FOpenFileRead(Cmd_Argv(1), &f, qfalse); + if (f) { + FS_FCloseFile(f); } } @@ -2911,81 +2822,81 @@ void FS_TouchFile_f( void ) { FS_Which_f ============ */ -void FS_Which_f( void ) { - searchpath_t *search; - char *filename; +void FS_Which_f(void) { + searchpath_t *search; + char *filename; filename = Cmd_Argv(1); - if ( !filename[0] ) { - Com_Printf( "Usage: which \n" ); + if (!filename[0]) { + Com_Printf("Usage: which \n"); return; } // qpaths are not supposed to have a leading slash - if ( filename[0] == '/' || filename[0] == '\\' ) { + if (filename[0] == '/' || filename[0] == '\\') { filename++; } // make absolutely sure that it can't back up the path. // The searchpaths do guarantee that something will always // be prepended, so we don't need to worry about "c:" or "//limbo" - if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) { + if (strstr(filename, "..") || strstr(filename, "::")) { return; } // just wants to see if file is there - for ( search=fs_searchpaths; search; search=search->next ) { - if ( search->pack ) { - long hash = FS_HashFileName( filename, search->pack->hashSize ); + for (search = fs_searchpaths; search; search = search->next) { + if (search->pack) { + long hash = FS_HashFileName(filename, search->pack->hashSize); // is the element a pak file? - if ( search->pack->hashTable[hash]) { + if (search->pack->hashTable[hash]) { // look through all the pak file elements - pack_t* pak = search->pack; - fileInPack_t* pakFile = pak->hashTable[hash]; + pack_t *pak = search->pack; + fileInPack_t *pakFile = pak->hashTable[hash]; do { // case and separator insensitive comparisons - if ( !FS_FilenameCompare( pakFile->name, filename ) ) { + if (!FS_FilenameCompare(pakFile->name, filename)) { // found it! - Com_Printf( "File \"%s\" found in \"%s\"\n", filename, pak->pakFilename ); + Com_Printf("File \"%s\" found in \"%s\"\n", filename, pak->pakFilename); return; } pakFile = pakFile->next; - } while ( pakFile != NULL ); + } while (pakFile != NULL); } } else if (search->dir) { - directory_t* dir = search->dir; + directory_t *dir = search->dir; - char* netpath = FS_BuildOSPath( dir->path, dir->gamedir, filename ); - FILE* filep = fopen(netpath, "rb"); + char *netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename); + FILE *filep = fopen(netpath, "rb"); - if ( filep ) { - fclose( filep ); + if (filep) { + fclose(filep); char buf[MAX_OSPATH]; - Com_sprintf( buf, sizeof( buf ), "%s%c%s", dir->path, PATH_SEP, dir->gamedir ); - FS_ReplaceSeparators( buf ); - Com_Printf( "File \"%s\" found at \"%s\"\n", filename, buf ); + Com_sprintf(buf, sizeof(buf), "%s%c%s", dir->path, PATH_SEP, dir->gamedir); + FS_ReplaceSeparators(buf); + Com_Printf("File \"%s\" found at \"%s\"\n", filename, buf); return; } } } - Com_Printf( "File not found: \"%s\"\n", filename ); + Com_Printf("File not found: \"%s\"\n", filename); } //=========================================================================== -static int QDECL paksort( const void *a, const void *b ) { - char *aa, *bb; +static int QDECL paksort(const void *a, const void *b) { + char *aa, *bb; aa = *(char **)a; bb = *(char **)b; - return FS_PathCmp( aa, bb ); + return FS_PathCmp(aa, bb); } /* @@ -2996,62 +2907,62 @@ Sets fs_gamedir, adds the directory to the head of the path, then loads the zip headers ================ */ -#define MAX_PAKFILES 1024 -static void FS_AddGameDirectory( const char *path, const char *dir ) { - searchpath_t *sp; - int i; - searchpath_t *search; - searchpath_t *thedir; - pack_t *pak; - char curpath[MAX_OSPATH + 1], *pakfile; - int numfiles; - char **pakfiles; - char *sorted[MAX_PAKFILES]; +#define MAX_PAKFILES 1024 +static void FS_AddGameDirectory(const char *path, const char *dir) { + searchpath_t *sp; + int i; + searchpath_t *search; + searchpath_t *thedir; + pack_t *pak; + char curpath[MAX_OSPATH + 1], *pakfile; + int numfiles; + char **pakfiles; + char *sorted[MAX_PAKFILES]; // this fixes the case where fs_basepath is the same as fs_cdpath // which happens on full installs - for ( sp = fs_searchpaths ; sp ; sp = sp->next ) { - if ( sp->dir && Sys_PathCmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) { - return; // we've already got this one + for (sp = fs_searchpaths; sp; sp = sp->next) { + if (sp->dir && Sys_PathCmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) { + return; // we've already got this one } } - Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) ); + Q_strncpyz(fs_gamedir, dir, sizeof(fs_gamedir)); // find all pak files in this directory Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath)); - curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash + curpath[strlen(curpath) - 1] = '\0'; // strip the trailing slash // // add the directory to the search path // - search = (struct searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue); - search->dir = (directory_t *)Z_Malloc( sizeof( *search->dir ), TAG_FILESYS, qtrue ); + search = (struct searchpath_s *)Z_Malloc(sizeof(searchpath_t), TAG_FILESYS, qtrue); + search->dir = (directory_t *)Z_Malloc(sizeof(*search->dir), TAG_FILESYS, qtrue); - Q_strncpyz( search->dir->path, path, sizeof( search->dir->path ) ); - Q_strncpyz( search->dir->fullpath, curpath, sizeof( search->dir->fullpath ) ); - Q_strncpyz( search->dir->gamedir, dir, sizeof( search->dir->gamedir ) ); + Q_strncpyz(search->dir->path, path, sizeof(search->dir->path)); + Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath)); + Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir)); search->next = fs_searchpaths; fs_searchpaths = search; thedir = search; - pakfiles = Sys_ListFiles( curpath, ".pk3", NULL, &numfiles, qfalse ); + pakfiles = Sys_ListFiles(curpath, ".pk3", NULL, &numfiles, qfalse); // sort them so that later alphabetic matches override // earlier ones. This makes pak1.pk3 override pak0.pk3 - if ( numfiles > MAX_PAKFILES ) { + if (numfiles > MAX_PAKFILES) { numfiles = MAX_PAKFILES; } - for ( i = 0 ; i < numfiles ; i++ ) { + for (i = 0; i < numfiles; i++) { sorted[i] = pakfiles[i]; } - qsort( sorted, numfiles, sizeof(char*), paksort ); + qsort(sorted, numfiles, sizeof(char *), paksort); - for ( i = 0 ; i < numfiles ; i++ ) { - pakfile = FS_BuildOSPath( path, dir, sorted[i] ); - if ( ( pak = FS_LoadZipFile( pakfile, sorted[i] ) ) == 0 ) + for (i = 0; i < numfiles; i++) { + pakfile = FS_BuildOSPath(path, dir, sorted[i]); + if ((pak = FS_LoadZipFile(pakfile, sorted[i])) == 0) continue; Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname)); // store the game name for downloading @@ -3059,30 +2970,26 @@ static void FS_AddGameDirectory( const char *path, const char *dir ) { fs_packFiles += pak->numfiles; - search = (searchpath_s *)Z_Malloc (sizeof(searchpath_t), TAG_FILESYS, qtrue); + search = (searchpath_s *)Z_Malloc(sizeof(searchpath_t), TAG_FILESYS, qtrue); search->pack = pak; - if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir) - { + if (fs_dirbeforepak && fs_dirbeforepak->integer && thedir) { searchpath_t *oldnext = thedir->next; thedir->next = search; - while (oldnext) - { + while (oldnext) { search->next = oldnext; search = search->next; oldnext = oldnext->next; } - } - else - { + } else { search->next = fs_searchpaths; fs_searchpaths = search; } } // done - Sys_FreeFileList( pakfiles ); + Sys_FreeFileList(pakfiles); } /* @@ -3090,11 +2997,11 @@ static void FS_AddGameDirectory( const char *path, const char *dir ) { FS_idPak ================ */ -qboolean FS_idPak( char *pak, char *base ) { +qboolean FS_idPak(char *pak, char *base) { int i; for (i = 0; i < NUM_ID_PAKS; i++) { - if ( !FS_FilenameCompare(pak, va("%s/assets%d", base, i)) ) { + if (!FS_FilenameCompare(pak, va("%s/assets%d", base, i))) { break; } } @@ -3113,9 +3020,8 @@ and return qtrue if it does. ================ */ -qboolean FS_CheckDirTraversal(const char *checkdir) -{ - if(strstr(checkdir, "../") || strstr(checkdir, "..\\")) +qboolean FS_CheckDirTraversal(const char *checkdir) { + if (strstr(checkdir, "../") || strstr(checkdir, "..\\")) return qtrue; return qfalse; @@ -3145,46 +3051,44 @@ we are not interested in a download string format, we want something human-reada (this is used for diagnostics while connecting to a pure server) ================ */ -qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) { - searchpath_t *sp; +qboolean FS_ComparePaks(char *neededpaks, int len, qboolean dlstring) { + searchpath_t *sp; qboolean havepak; char *origpos = neededpaks; int i; - if ( !fs_numServerReferencedPaks ) { + if (!fs_numServerReferencedPaks) { return qfalse; // Server didn't send any pack information along } *neededpaks = 0; - for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ ) { + for (i = 0; i < fs_numServerReferencedPaks; i++) { // Ok, see if we have this pak file havepak = qfalse; // never autodownload any of the id paks - if ( FS_idPak(fs_serverReferencedPakNames[i], "base") || FS_idPak(fs_serverReferencedPakNames[i], "missionpack") ) { + if (FS_idPak(fs_serverReferencedPakNames[i], "base") || FS_idPak(fs_serverReferencedPakNames[i], "missionpack")) { continue; } // Make sure the server cannot make us write to non-quake3 directories. - if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i])) - { + if (FS_CheckDirTraversal(fs_serverReferencedPakNames[i])) { Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]); continue; } - for ( sp = fs_searchpaths ; sp ; sp = sp->next ) { - if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) { + for (sp = fs_searchpaths; sp; sp = sp->next) { + if (sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i]) { havepak = qtrue; // This is it! break; } } - if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) { + if (!havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i]) { // Don't got it - if (dlstring) - { + if (dlstring) { // We need this to make sure we won't hit the end of the buffer or the server could // overwrite non-pk3 files on clients by writing so much crap into neededpaks that // Q_strcat cuts off the .pk3 extension. @@ -3192,46 +3096,42 @@ qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) { origpos += strlen(origpos); // Remote name - Q_strcat( neededpaks, len, "@"); - Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); - Q_strcat( neededpaks, len, ".pk3" ); + Q_strcat(neededpaks, len, "@"); + Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]); + Q_strcat(neededpaks, len, ".pk3"); // Local name - Q_strcat( neededpaks, len, "@"); + Q_strcat(neededpaks, len, "@"); // Do we have one with the same name? - if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) { + if (FS_SV_FileExists(va("%s.pk3", fs_serverReferencedPakNames[i]))) { char st[MAX_ZPATH]; // We already have one called this, we need to download it to another name // Make something up with the checksum in it - Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] ); - Q_strcat( neededpaks, len, st ); + Com_sprintf(st, sizeof(st), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i]); + Q_strcat(neededpaks, len, st); } else { - Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); - Q_strcat( neededpaks, len, ".pk3" ); + Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]); + Q_strcat(neededpaks, len, ".pk3"); } // Find out whether it might have overflowed the buffer and don't add this file to the // list if that is the case. - if(strlen(origpos) + (origpos - neededpaks) >= (unsigned)(len - 1)) - { + if (strlen(origpos) + (origpos - neededpaks) >= (unsigned)(len - 1)) { *origpos = '\0'; break; } - } - else - { - Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] ); - Q_strcat( neededpaks, len, ".pk3" ); + } else { + Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]); + Q_strcat(neededpaks, len, ".pk3"); // Do we have one with the same name? - if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) ) - { - Q_strcat( neededpaks, len, " (local file exists with wrong checksum)"); + if (FS_SV_FileExists(va("%s.pk3", fs_serverReferencedPakNames[i]))) { + Q_strcat(neededpaks, len, " (local file exists with wrong checksum)"); } - Q_strcat( neededpaks, len, "\n"); + Q_strcat(neededpaks, len, "\n"); } } } - if ( *neededpaks ) { + if (*neededpaks) { return qtrue; } @@ -3245,24 +3145,20 @@ FS_Shutdown Frees all resources and closes all files ================ */ -void FS_Shutdown( qboolean closemfp ) { - searchpath_t *p, *next; - int i; +void FS_Shutdown(qboolean closemfp) { + searchpath_t *p, *next; + int i; #if defined(_WIN32) // Delete temporary files fs_temporaryFileWriteIdx = 0; - for ( size_t i = 0; i < ARRAY_LEN(fs_temporaryFileNames); i++ ) - { - if (fs_temporaryFileNames[i][0] != '\0') - { - if ( !DeleteFile(fs_temporaryFileNames[i]) ) - { + for (size_t i = 0; i < ARRAY_LEN(fs_temporaryFileNames); i++) { + if (fs_temporaryFileNames[i][0] != '\0') { + if (!DeleteFile(fs_temporaryFileNames[i])) { DWORD error = GetLastError(); Com_DPrintf("FS_Shutdown: failed to delete '%s'. " "Win32 error code: 0x08x", - fs_temporaryFileNames[i], - error); + fs_temporaryFileNames[i], error); } fs_temporaryFileNames[i][0] = '\0'; @@ -3270,33 +3166,33 @@ void FS_Shutdown( qboolean closemfp ) { } #endif - for(i = 0; i < MAX_FILE_HANDLES; i++) { + for (i = 0; i < MAX_FILE_HANDLES; i++) { if (fsh[i].fileSize) { FS_FCloseFile(i); } } // free everything - for ( p = fs_searchpaths ; p ; p = next ) { + for (p = fs_searchpaths; p; p = next) { next = p->next; - if ( p->pack ) { - FS_FreePak( p->pack ); + if (p->pack) { + FS_FreePak(p->pack); } - if ( p->dir ) { - Z_Free( p->dir ); + if (p->dir) { + Z_Free(p->dir); } - Z_Free( p ); + Z_Free(p); } // any FS_ calls will now be an error until reinitialized fs_searchpaths = NULL; - Cmd_RemoveCommand( "path" ); - Cmd_RemoveCommand( "dir" ); - Cmd_RemoveCommand( "fdir" ); - Cmd_RemoveCommand( "touchFile" ); - Cmd_RemoveCommand( "which" ); + Cmd_RemoveCommand("path"); + Cmd_RemoveCommand("dir"); + Cmd_RemoveCommand("fdir"); + Cmd_RemoveCommand("touchFile"); + Cmd_RemoveCommand("which"); #ifdef FS_MISSING if (closemfp) { @@ -3305,22 +3201,17 @@ void FS_Shutdown( qboolean closemfp ) { #endif } -//rww - add search paths in for received svc_setgame -//Ensiform - this is so wrong rww -void FS_UpdateGamedir(void) -{ - if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, BASEGAME ) ) - { - if (fs_cdpath->string[0]) - { +// rww - add search paths in for received svc_setgame +// Ensiform - this is so wrong rww +void FS_UpdateGamedir(void) { + if (fs_gamedirvar->string[0] && Q_stricmp(fs_gamedirvar->string, BASEGAME)) { + if (fs_cdpath->string[0]) { FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string); } - if (fs_basepath->string[0]) - { + if (fs_basepath->string[0]) { FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string); } - if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) - { + if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) { FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string); } } @@ -3333,21 +3224,20 @@ NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cva this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 ================ */ -static void FS_ReorderPurePaks() -{ +static void FS_ReorderPurePaks() { searchpath_t *s; int i; searchpath_t **p_insert_index, // for linked list reordering - **p_previous; // when doing the scan + **p_previous; // when doing the scan // only relevant when connected to pure server - if ( !fs_numServerPaks ) + if (!fs_numServerPaks) return; fs_reordered = qfalse; p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list - for ( i = 0 ; i < fs_numServerPaks ; i++ ) { + for (i = 0; i < fs_numServerPaks; i++) { p_previous = p_insert_index; // track the pointer-to-current-item for (s = *p_insert_index; s; s = s->next) { // the part of the list before p_insert_index has been sorted already @@ -3384,52 +3274,52 @@ static void FS_ReorderPurePaks() @param gameName Name of the default folder (i.e. always BASEGAME = "base" in OpenJK) */ -void FS_Startup( const char *gameName ) { +void FS_Startup(const char *gameName) { const char *homePath; - Com_Printf( "----- FS_Startup -----\n" ); + Com_Printf("----- FS_Startup -----\n"); fs_packFiles = 0; - fs_debug = Cvar_Get( "fs_debug", "0", 0 ); - fs_copyfiles = Cvar_Get( "fs_copyfiles", "0", CVAR_INIT ); - fs_cdpath = Cvar_Get ("fs_cdpath", "", CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for development files" ); - fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location for game files" ); - fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT ); + fs_debug = Cvar_Get("fs_debug", "0", 0); + fs_copyfiles = Cvar_Get("fs_copyfiles", "0", CVAR_INIT); + fs_cdpath = Cvar_Get("fs_cdpath", "", CVAR_INIT | CVAR_PROTECTED, "(Read Only) Location for development files"); + fs_basepath = Cvar_Get("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT | CVAR_PROTECTED, "(Read Only) Location for game files"); + fs_basegame = Cvar_Get("fs_basegame", "", CVAR_INIT); homePath = Sys_DefaultHomePath(); if (!homePath || !homePath[0]) { homePath = fs_basepath->string; } - fs_homepath = Cvar_Get ("fs_homepath", homePath, CVAR_INIT|CVAR_PROTECTED, "(Read/Write) Location for user generated files" ); - fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO, "Mod directory" ); + fs_homepath = Cvar_Get("fs_homepath", homePath, CVAR_INIT | CVAR_PROTECTED, "(Read/Write) Location for user generated files"); + fs_gamedirvar = Cvar_Get("fs_game", "", CVAR_INIT | CVAR_SYSTEMINFO, "Mod directory"); - fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT|CVAR_PROTECTED, "Prioritize directories before paks if not pure" ); + fs_dirbeforepak = Cvar_Get("fs_dirbeforepak", "0", CVAR_INIT | CVAR_PROTECTED, "Prioritize directories before paks if not pure"); // add search path elements in reverse priority order (lowest priority first) if (fs_cdpath->string[0]) { - FS_AddGameDirectory( fs_cdpath->string, gameName ); + FS_AddGameDirectory(fs_cdpath->string, gameName); } if (fs_basepath->string[0]) { - FS_AddGameDirectory( fs_basepath->string, gameName ); + FS_AddGameDirectory(fs_basepath->string, gameName); } #ifdef MACOS_X - fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED, "(Read Only) Location of OSX .app bundle" ); + fs_apppath = Cvar_Get("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT | CVAR_PROTECTED, "(Read Only) Location of OSX .app bundle"); // Make MacOSX also include the base path included with the .app bundle if (fs_apppath->string[0]) { - FS_AddGameDirectory( fs_apppath->string, gameName ); + FS_AddGameDirectory(fs_apppath->string, gameName); } #endif // fs_homepath is somewhat particular to *nix systems, only add if relevant // NOTE: same filtering below for mods and basegame if (fs_homepath->string[0] && !Sys_PathCmp(fs_homepath->string, fs_basepath->string)) { - FS_CreatePath ( fs_homepath->string ); - FS_AddGameDirectory ( fs_homepath->string, gameName ); + FS_CreatePath(fs_homepath->string); + FS_AddGameDirectory(fs_homepath->string, gameName); } // check for additional base game so mods can be based upon other mods - if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) { + if (fs_basegame->string[0] && Q_stricmp(fs_basegame->string, gameName)) { if (fs_cdpath->string[0]) { FS_AddGameDirectory(fs_cdpath->string, fs_basegame->string); } @@ -3442,7 +3332,7 @@ void FS_Startup( const char *gameName ) { } // check for additional game folder for mods - if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) { + if (fs_gamedirvar->string[0] && Q_stricmp(fs_gamedirvar->string, gameName)) { if (fs_cdpath->string[0]) { FS_AddGameDirectory(fs_cdpath->string, fs_gamedirvar->string); } @@ -3455,11 +3345,11 @@ void FS_Startup( const char *gameName ) { } // add our commands - Cmd_AddCommand ("path", FS_Path_f, "Lists search paths" ); - Cmd_AddCommand ("dir", FS_Dir_f, "Lists a folder" ); - Cmd_AddCommand ("fdir", FS_NewDir_f, "Lists a folder with filters" ); - Cmd_AddCommand ("touchFile", FS_TouchFile_f, "Touches a file" ); - Cmd_AddCommand ("which", FS_Which_f, "Determines which search path a file was loaded from" ); + Cmd_AddCommand("path", FS_Path_f, "Lists search paths"); + Cmd_AddCommand("dir", FS_Dir_f, "Lists a folder"); + Cmd_AddCommand("fdir", FS_NewDir_f, "Lists a folder with filters"); + Cmd_AddCommand("touchFile", FS_TouchFile_f, "Touches a file"); + Cmd_AddCommand("which", FS_Which_f, "Determines which search path a file was loaded from"); // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506 // reorder the pure pk3 files according to server order @@ -3470,14 +3360,14 @@ void FS_Startup( const char *gameName ) { fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified - Com_Printf( "----------------------\n" ); + Com_Printf("----------------------\n"); #ifdef FS_MISSING if (missingFiles == NULL) { - missingFiles = fopen( "\\missing.txt", "ab" ); + missingFiles = fopen("\\missing.txt", "ab"); } #endif - Com_Printf( "%d files in pk3 files\n", fs_packFiles ); + Com_Printf("%d files in pk3 files\n", fs_packFiles); } /* @@ -3488,19 +3378,19 @@ Returns a space separated string containing the checksums of all loaded pk3 file Servers with sv_pure set will get this string and pass it to clients. ===================== */ -const char *FS_LoadedPakChecksums( void ) { - static char info[BIG_INFO_STRING]; - searchpath_t *search; +const char *FS_LoadedPakChecksums(void) { + static char info[BIG_INFO_STRING]; + searchpath_t *search; info[0] = 0; - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? - if ( !search->pack ) { + if (!search->pack) { continue; } - Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) ); + Q_strcat(info, sizeof(info), va("%i ", search->pack->checksum)); } return info; @@ -3514,22 +3404,22 @@ Returns a space separated string containing the names of all loaded pk3 files. Servers with sv_pure set will get this string and pass it to clients. ===================== */ -const char *FS_LoadedPakNames( void ) { - static char info[BIG_INFO_STRING]; - searchpath_t *search; +const char *FS_LoadedPakNames(void) { + static char info[BIG_INFO_STRING]; + searchpath_t *search; info[0] = 0; - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? - if ( !search->pack ) { + if (!search->pack) { continue; } if (*info) { - Q_strcat(info, sizeof( info ), " " ); + Q_strcat(info, sizeof(info), " "); } - Q_strcat( info, sizeof( info ), search->pack->pakBasename ); + Q_strcat(info, sizeof(info), search->pack->pakBasename); } return info; @@ -3544,19 +3434,19 @@ Servers with sv_pure use these checksums to compare with the checksums the clien back to the server. ===================== */ -const char *FS_LoadedPakPureChecksums( void ) { - static char info[BIG_INFO_STRING]; - searchpath_t *search; +const char *FS_LoadedPakPureChecksums(void) { + static char info[BIG_INFO_STRING]; + searchpath_t *search; info[0] = 0; - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? - if ( !search->pack ) { + if (!search->pack) { continue; } - Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) ); + Q_strcat(info, sizeof(info), va("%i ", search->pack->pure_checksum)); } return info; @@ -3570,18 +3460,17 @@ Returns a space separated string containing the checksums of all referenced pk3 The server will send this to the clients so they can check which files should be auto-downloaded. ===================== */ -const char *FS_ReferencedPakChecksums( void ) { - static char info[BIG_INFO_STRING]; +const char *FS_ReferencedPakChecksums(void) { + static char info[BIG_INFO_STRING]; searchpath_t *search; info[0] = 0; - - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? - if ( search->pack ) { + if (search->pack) { if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) { - Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) ); + Q_strcat(info, sizeof(info), va("%i ", search->pack->checksum)); } } } @@ -3599,9 +3488,9 @@ Servers with sv_pure set will get this string back from clients for pure validat The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..." ===================== */ -const char *FS_ReferencedPakPureChecksums( void ) { - static char info[BIG_INFO_STRING]; - searchpath_t *search; +const char *FS_ReferencedPakPureChecksums(void) { + static char info[BIG_INFO_STRING]; + searchpath_t *search; int nFlags, numPaks, checksum; info[0] = 0; @@ -3611,16 +3500,16 @@ const char *FS_ReferencedPakPureChecksums( void ) { for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) { if (nFlags & FS_GENERAL_REF) { // add a delimter between must haves and general refs - //Q_strcat(info, sizeof(info), "@ "); - info[strlen(info)+1] = '\0'; - info[strlen(info)+2] = '\0'; + // Q_strcat(info, sizeof(info), "@ "); + info[strlen(info) + 1] = '\0'; + info[strlen(info) + 2] = '\0'; info[strlen(info)] = '@'; info[strlen(info)] = ' '; } - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file and has it been referenced based on flag? - if ( search->pack && (search->pack->referenced & nFlags)) { - Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) ); + if (search->pack && (search->pack->referenced & nFlags)) { + Q_strcat(info, sizeof(info), va("%i ", search->pack->pure_checksum)); if (nFlags & (FS_CGAME_REF | FS_UI_REF)) { break; } @@ -3630,12 +3519,12 @@ const char *FS_ReferencedPakPureChecksums( void ) { } if (fs_fakeChkSum != 0) { // only added if a non-pure file is referenced - Q_strcat( info, sizeof( info ), va("%i ", fs_fakeChkSum ) ); + Q_strcat(info, sizeof(info), va("%i ", fs_fakeChkSum)); } } // last checksum is the encoded number of referenced pk3s checksum ^= numPaks; - Q_strcat( info, sizeof( info ), va("%i ", checksum ) ); + Q_strcat(info, sizeof(info), va("%i ", checksum)); return info; } @@ -3648,24 +3537,24 @@ Returns a space separated string containing the names of all referenced pk3 file The server will send this to the clients so they can check which files should be auto-downloaded. ===================== */ -const char *FS_ReferencedPakNames( void ) { - static char info[BIG_INFO_STRING]; - searchpath_t *search; +const char *FS_ReferencedPakNames(void) { + static char info[BIG_INFO_STRING]; + searchpath_t *search; info[0] = 0; // we want to return ALL pk3's from the fs_game path // and referenced one's from base - for ( search = fs_searchpaths ; search ; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file? - if ( search->pack ) { + if (search->pack) { if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, BASEGAME, strlen(BASEGAME))) { if (*info) { - Q_strcat(info, sizeof( info ), " " ); + Q_strcat(info, sizeof(info), " "); } - Q_strcat( info, sizeof( info ), search->pack->pakGamename ); - Q_strcat( info, sizeof( info ), "/" ); - Q_strcat( info, sizeof( info ), search->pack->pakBasename ); + Q_strcat(info, sizeof(info), search->pack->pakGamename); + Q_strcat(info, sizeof(info), "/"); + Q_strcat(info, sizeof(info), search->pack->pakBasename); } } } @@ -3678,21 +3567,20 @@ const char *FS_ReferencedPakNames( void ) { FS_ClearPakReferences ===================== */ -void FS_ClearPakReferences( int flags ) { +void FS_ClearPakReferences(int flags) { searchpath_t *search; - if ( !flags ) { + if (!flags) { flags = -1; } - for ( search = fs_searchpaths; search; search = search->next ) { + for (search = fs_searchpaths; search; search = search->next) { // is the element a pak file and has it been referenced? - if ( search->pack ) { + if (search->pack) { search->pack->referenced &= ~flags; } } } - /* ===================== FS_PureServerSetLoadedPaks @@ -3703,53 +3591,50 @@ separated checksums will be checked for files, with the exception of .cfg and .dat files. ===================== */ -void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) { - int i, c, d; +void FS_PureServerSetLoadedPaks(const char *pakSums, const char *pakNames) { + int i, c, d; - Cmd_TokenizeString( pakSums ); + Cmd_TokenizeString(pakSums); c = Cmd_Argc(); - if ( c > MAX_SEARCH_PATHS ) { + if (c > MAX_SEARCH_PATHS) { c = MAX_SEARCH_PATHS; } fs_numServerPaks = c; - for ( i = 0 ; i < c ; i++ ) { - fs_serverPaks[i] = atoi( Cmd_Argv( i ) ); + for (i = 0; i < c; i++) { + fs_serverPaks[i] = atoi(Cmd_Argv(i)); } if (fs_numServerPaks) { - Com_DPrintf( "Connected to a pure server.\n" ); - } - else - { - if (fs_reordered) - { + Com_DPrintf("Connected to a pure server.\n"); + } else { + if (fs_reordered) { // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 // force a restart to make sure the search order will be correct - Com_DPrintf( "FS search reorder is required\n" ); + Com_DPrintf("FS search reorder is required\n"); FS_Restart(fs_checksumFeed); return; } } - for ( i = 0 ; i < c ; i++ ) { + for (i = 0; i < c; i++) { if (fs_serverPakNames[i]) { Z_Free(fs_serverPakNames[i]); } fs_serverPakNames[i] = NULL; } - if ( pakNames && *pakNames ) { - Cmd_TokenizeString( pakNames ); + if (pakNames && *pakNames) { + Cmd_TokenizeString(pakNames); d = Cmd_Argc(); - if ( d > MAX_SEARCH_PATHS ) { + if (d > MAX_SEARCH_PATHS) { d = MAX_SEARCH_PATHS; } - for ( i = 0 ; i < d ; i++ ) { - fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) ); + for (i = 0; i < d; i++) { + fs_serverPakNames[i] = CopyString(Cmd_Argv(i)); } } } @@ -3763,43 +3648,42 @@ are sent to the client and stored here. The client will use these checksums to see if any pk3 files need to be auto-downloaded. ===================== */ -void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) { - int i, c, d = 0; +void FS_PureServerSetReferencedPaks(const char *pakSums, const char *pakNames) { + int i, c, d = 0; - Cmd_TokenizeString( pakSums ); + Cmd_TokenizeString(pakSums); c = Cmd_Argc(); - if ( c > MAX_SEARCH_PATHS ) { + if (c > MAX_SEARCH_PATHS) { c = MAX_SEARCH_PATHS; } - for ( i = 0 ; i < c ; i++ ) { - fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) ); + for (i = 0; i < c; i++) { + fs_serverReferencedPaks[i] = atoi(Cmd_Argv(i)); } - for (i = 0 ; i < (int)ARRAY_LEN(fs_serverReferencedPakNames); i++) - { - if(fs_serverReferencedPakNames[i]) + for (i = 0; i < (int)ARRAY_LEN(fs_serverReferencedPakNames); i++) { + if (fs_serverReferencedPakNames[i]) Z_Free(fs_serverReferencedPakNames[i]); fs_serverReferencedPakNames[i] = NULL; } - if ( pakNames && *pakNames ) { - Cmd_TokenizeString( pakNames ); + if (pakNames && *pakNames) { + Cmd_TokenizeString(pakNames); d = Cmd_Argc(); - if ( d > c ) { + if (d > c) { d = c; } - for ( i = 0 ; i < d ; i++ ) { - fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) ); + for (i = 0; i < d; i++) { + fs_serverReferencedPakNames[i] = CopyString(Cmd_Argv(i)); } } // ensure that there are as many checksums as there are pak names. - if(d < c) + if (d < c) c = d; fs_numServerReferencedPaks = c; @@ -3813,32 +3697,32 @@ Called only at inital startup, not when the filesystem is resetting due to a game change ================ */ -void FS_InitFilesystem( void ) { +void FS_InitFilesystem(void) { // allow command line parms to override our defaults // we have to specially handle this, because normal command // line variable sets don't happen until after the filesystem // has already been initialized - Com_StartupVariable( "fs_cdpath" ); - Com_StartupVariable( "fs_basepath" ); - Com_StartupVariable( "fs_homepath" ); - Com_StartupVariable( "fs_game" ); - Com_StartupVariable( "fs_copyfiles" ); - Com_StartupVariable( "fs_dirbeforepak" ); + Com_StartupVariable("fs_cdpath"); + Com_StartupVariable("fs_basepath"); + Com_StartupVariable("fs_homepath"); + Com_StartupVariable("fs_game"); + Com_StartupVariable("fs_copyfiles"); + Com_StartupVariable("fs_dirbeforepak"); #ifdef MACOS_X - Com_StartupVariable( "fs_apppath" ); + Com_StartupVariable("fs_apppath"); #endif - if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), BASEGAME)) + if (!FS_FilenameCompare(Cvar_VariableString("fs_game"), BASEGAME)) Cvar_Set("fs_game", ""); // try to start up normally - FS_Startup( BASEGAME ); + FS_Startup(BASEGAME); // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load - if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) { - Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" ); + if (FS_ReadFile("mpdefault.cfg", NULL) <= 0) { + Com_Error(ERR_FATAL, "Couldn't load mpdefault.cfg"); // bk001208 - SafeMode see below, FIXME? } @@ -3849,7 +3733,7 @@ void FS_InitFilesystem( void ) { Com_Memset(fs_temporaryFileNames, 0, sizeof(fs_temporaryFileNames)); #endif - // bk001208 - SafeMode see below, FIXME? + // bk001208 - SafeMode see below, FIXME? } /* @@ -3857,7 +3741,7 @@ void FS_InitFilesystem( void ) { FS_Restart ================ */ -void FS_Restart( int checksumFeed ) { +void FS_Restart(int checksumFeed) { // free anything we currently have loaded FS_Shutdown(qfalse); @@ -3869,12 +3753,12 @@ void FS_Restart( int checksumFeed ) { FS_ClearPakReferences(0); // try to start up normally - FS_Startup( BASEGAME ); + FS_Startup(BASEGAME); // if we can't find default.cfg, assume that the paths are // busted and error out now, rather than getting an unreadable // graphics screen when the font fails to load - if ( FS_ReadFile( "mpdefault.cfg", NULL ) <= 0 ) { + if (FS_ReadFile("mpdefault.cfg", NULL) <= 0) { // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3 // (for instance a TA demo server) if (lastValidBase[0]) { @@ -3884,22 +3768,21 @@ void FS_Restart( int checksumFeed ) { lastValidBase[0] = '\0'; lastValidGame[0] = '\0'; FS_Restart(checksumFeed); - Com_Error( ERR_DROP, "Invalid game folder\n" ); + Com_Error(ERR_DROP, "Invalid game folder\n"); return; } - Com_Error( ERR_FATAL, "Couldn't load mpdefault.cfg" ); + Com_Error(ERR_FATAL, "Couldn't load mpdefault.cfg"); } - if ( Q_stricmp(fs_gamedirvar->string, lastValidGame) ) { + if (Q_stricmp(fs_gamedirvar->string, lastValidGame)) { // skip the jampconfig.cfg if "safe" is on the command line - if ( !Com_SafeMode() ) { - Cbuf_AddText ("exec " Q3CONFIG_CFG "\n"); + if (!Com_SafeMode()) { + Cbuf_AddText("exec " Q3CONFIG_CFG "\n"); } } Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase)); Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame)); - } /* @@ -3908,9 +3791,9 @@ FS_ConditionalRestart restart if necessary ================= */ -qboolean FS_ConditionalRestart( int checksumFeed ) { - if( fs_gamedirvar->modified || checksumFeed != fs_checksumFeed ) { - FS_Restart( checksumFeed ); +qboolean FS_ConditionalRestart(int checksumFeed) { + if (fs_gamedirvar->modified || checksumFeed != fs_checksumFeed) { + FS_Restart(checksumFeed); return qtrue; } #if 0 @@ -3944,18 +3827,18 @@ Handle based file calls for virtual machines ======================================================================================== */ -int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - int r; - qboolean sync; +int FS_FOpenFileByMode(const char *qpath, fileHandle_t *f, fsMode_t mode) { + int r; + qboolean sync; sync = qfalse; - switch( mode ) { + switch (mode) { case FS_READ: - r = FS_FOpenFileRead( qpath, f, qtrue ); + r = FS_FOpenFileRead(qpath, f, qtrue); break; case FS_WRITE: - *f = FS_FOpenFileWrite( qpath ); + *f = FS_FOpenFileWrite(qpath); r = 0; if (*f == 0) { r = -1; @@ -3964,14 +3847,14 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { case FS_APPEND_SYNC: sync = qtrue; case FS_APPEND: - *f = FS_FOpenFileAppend( qpath ); + *f = FS_FOpenFileAppend(qpath); r = 0; if (*f == 0) { r = -1; } break; default: - Com_Error( ERR_FATAL, "FSH_FOpenFile: bad mode" ); + Com_Error(ERR_FATAL, "FSH_FOpenFile: bad mode"); return -1; } @@ -3979,7 +3862,7 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { return r; } - if ( *f ) { + if (*f) { fsh[*f].fileSize = r; } fsh[*f].handleSync = sync; @@ -3987,7 +3870,7 @@ int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { return r; } -int FS_FTell( fileHandle_t f ) { +int FS_FTell(fileHandle_t f) { int pos; if (fsh[f].zipFile == qtrue) { pos = unztell(fsh[f].handleFiles.file.z); @@ -3997,188 +3880,166 @@ int FS_FTell( fileHandle_t f ) { return pos; } -void FS_Flush( fileHandle_t f ) { - fflush(fsh[f].handleFiles.file.o); -} +void FS_Flush(fileHandle_t f) { fflush(fsh[f].handleFiles.file.o); } -void FS_FilenameCompletion( const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk ) { +void FS_FilenameCompletion(const char *dir, const char *ext, qboolean stripExt, callbackFunc_t callback, qboolean allowNonPureFilesOnDisk) { int nfiles; char **filenames, filename[MAX_STRING_CHARS]; - filenames = FS_ListFilteredFiles( dir, ext, NULL, &nfiles ); + filenames = FS_ListFilteredFiles(dir, ext, NULL, &nfiles); - FS_SortFileList( filenames, nfiles ); + FS_SortFileList(filenames, nfiles); // pass all the files to callback (FindMatches) - for ( int i=0; istring[0]) +const char *FS_GetCurrentGameDir(bool emptybase) { + if (fs_gamedirvar->string[0]) return fs_gamedirvar->string; return emptybase ? "" : BASEGAME; } #ifdef MACOS_X -bool FS_LoadMachOBundle( const char *name ) -{ - int len; - void *data; - fileHandle_t f; - char *fn; +bool FS_LoadMachOBundle(const char *name) { + int len; + void *data; + fileHandle_t f; + char *fn; unzFile dll; - byte* buf; - char dllName[MAX_QPATH]; - char *tempName; - unz_file_info zfi; + byte *buf; + char dllName[MAX_QPATH]; + char *tempName; + unz_file_info zfi; - //read zipped bundle from pk3 + // read zipped bundle from pk3 len = FS_ReadFile(name, &data); if (len < 1) { return false; } - //write temporary file of zipped bundle to e.g. uixxxxxx - //unique filename to avoid any clashes - Com_sprintf( dllName, sizeof(dllName), "%sXXXXXX", name ); + // write temporary file of zipped bundle to e.g. uixxxxxx + // unique filename to avoid any clashes + Com_sprintf(dllName, sizeof(dllName), "%sXXXXXX", name); - tempName = mktemp( dllName ); + tempName = mktemp(dllName); - f = FS_FOpenFileWrite( dllName ); + f = FS_FOpenFileWrite(dllName); - if ( !f ) - { + if (!f) { FS_FreeFile(data); return false; } - if (FS_Write( data, len, f ) < len) - { + if (FS_Write(data, len, f) < len) { FS_FreeFile(data); return false; } - FS_FCloseFile( f ); + FS_FCloseFile(f); FS_FreeFile(data); - //unzOpen zipped bundle, find the dylib, and try to write it - fn = FS_BuildOSPath( fs_homepath->string, fs_gamedir, dllName ); + // unzOpen zipped bundle, find the dylib, and try to write it + fn = FS_BuildOSPath(fs_homepath->string, fs_gamedir, dllName); - dll = unzOpen( fn ); + dll = unzOpen(fn); - Com_sprintf (dllName, sizeof(dllName), "%s.bundle/Contents/MacOS/%s", name, name); + Com_sprintf(dllName, sizeof(dllName), "%s.bundle/Contents/MacOS/%s", name, name); - if (unzLocateFile(dll, dllName, 0) != UNZ_OK) - { + if (unzLocateFile(dll, dllName, 0) != UNZ_OK) { unzClose(dll); - remove( fn ); + remove(fn); return false; } - unzOpenCurrentFile( dll ); + unzOpenCurrentFile(dll); - Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name ); + Com_sprintf(dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name); - f = FS_FOpenFileWrite( dllName, qfalse ); + f = FS_FOpenFileWrite(dllName, qfalse); - if ( !f ) - { - unzCloseCurrentFile( dll ); - unzClose( dll ); - remove( fn ); + if (!f) { + unzCloseCurrentFile(dll); + unzClose(dll); + remove(fn); return false; } - unzGetCurrentFileInfo( dll, &zfi, NULL, 0, NULL, 0, NULL, 0 ); + unzGetCurrentFileInfo(dll, &zfi, NULL, 0, NULL, 0, NULL, 0); len = zfi.uncompressed_size; - buf = (byte*)Z_Malloc( len+1, TAG_FILESYS, qfalse); + buf = (byte *)Z_Malloc(len + 1, TAG_FILESYS, qfalse); - if (unzReadCurrentFile( dll, buf, len ) < len) - { - FS_FCloseFile( f ); - unzCloseCurrentFile( dll ); - unzClose( dll ); + if (unzReadCurrentFile(dll, buf, len) < len) { + FS_FCloseFile(f); + unzCloseCurrentFile(dll); + unzClose(dll); return false; } - if (FS_Write(buf, len, f) < len) - { - FS_FCloseFile( f ); - unzCloseCurrentFile( dll ); - unzClose( dll ); + if (FS_Write(buf, len, f) < len) { + FS_FCloseFile(f); + unzCloseCurrentFile(dll); + unzClose(dll); return false; } - FS_FCloseFile( f ); - unzCloseCurrentFile( dll ); - unzClose( dll ); - Z_Free( buf ); + FS_FCloseFile(f); + unzCloseCurrentFile(dll); + unzClose(dll); + Z_Free(buf); - //remove temporary zipped bundle - remove( fn ); + // remove temporary zipped bundle + remove(fn); return true; } #endif -qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **tempFilePath ) -{ +qboolean FS_WriteToTemporaryFile(const void *data, size_t dataLength, char **tempFilePath) { #if defined(_WIN32) DWORD error; TCHAR tempPath[MAX_PATH]; DWORD tempPathResult = GetTempPath(MAX_PATH, tempPath); - if ( tempPathResult ) - { + if (tempPathResult) { TCHAR tempFileName[MAX_PATH]; UINT tempFileNameResult = GetTempFileName(tempPath, "OJK", 0, tempFileName); - if ( tempFileNameResult ) - { - HANDLE file = CreateFile( - tempFileName, GENERIC_WRITE, 0, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); - if ( file != INVALID_HANDLE_VALUE ) - { + if (tempFileNameResult) { + HANDLE file = CreateFile(tempFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (file != INVALID_HANDLE_VALUE) { DWORD bytesWritten = 0; - if (WriteFile(file, data, dataLength, &bytesWritten, NULL)) - { + if (WriteFile(file, data, dataLength, &bytesWritten, NULL)) { int deletesRemaining = ARRAY_LEN(fs_temporaryFileNames); CloseHandle(file); - while ( deletesRemaining > 0 && - fs_temporaryFileNames[fs_temporaryFileWriteIdx][0] != '\0' ) - { + while (deletesRemaining > 0 && fs_temporaryFileNames[fs_temporaryFileWriteIdx][0] != '\0') { // Delete old temporary file as we need to - if ( DeleteFile(fs_temporaryFileNames[fs_temporaryFileWriteIdx]) ) - { + if (DeleteFile(fs_temporaryFileNames[fs_temporaryFileWriteIdx])) { break; } error = GetLastError(); Com_DPrintf("FS_WriteToTemporaryFile failed for '%s'. " "Win32 error code: 0x%08x\n", - fs_temporaryFileNames[fs_temporaryFileWriteIdx], - error); + fs_temporaryFileNames[fs_temporaryFileWriteIdx], error); // Failed to delete, possibly because DLL was still in use. This can // happen when running a listen server and you continually restart // the map. The game DLL is reloaded, but cgame and ui DLLs are not. - fs_temporaryFileWriteIdx = - (fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames); + fs_temporaryFileWriteIdx = (fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames); deletesRemaining--; } @@ -4186,48 +4047,39 @@ qboolean FS_WriteToTemporaryFile( const void *data, size_t dataLength, char **te // loaded at once?! assert(deletesRemaining > 0); - Q_strncpyz(fs_temporaryFileNames[fs_temporaryFileWriteIdx], - tempFileName, sizeof(fs_temporaryFileNames[0])); - fs_temporaryFileWriteIdx = - (fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames); + Q_strncpyz(fs_temporaryFileNames[fs_temporaryFileWriteIdx], tempFileName, sizeof(fs_temporaryFileNames[0])); + fs_temporaryFileWriteIdx = (fs_temporaryFileWriteIdx + 1) % ARRAY_LEN(fs_temporaryFileNames); - if ( tempFilePath ) - { + if (tempFilePath) { size_t fileNameLen = strlen(tempFileName); *tempFilePath = (char *)Z_Malloc(fileNameLen + 1, TAG_FILESYS); Q_strncpyz(*tempFilePath, tempFileName, fileNameLen + 1); } return qtrue; - } - else - { + } else { error = GetLastError(); Com_DPrintf("FS_WriteToTemporaryFile failed to write '%s'. " "Win32 error code: 0x%08x\n", tempFileName, error); } - } - else - { + } else { error = GetLastError(); Com_DPrintf("FS_WriteToTemporaryFile failed to create '%s'. " "Win32 error code: 0x%08x\n", tempFileName, error); } - } - else - { + } else { error = GetLastError(); Com_DPrintf("FS_WriteToTemporaryFile failed to generate temporary file name. " - "Win32 error code: 0x%08x\n", error); + "Win32 error code: 0x%08x\n", + error); } - } - else - { + } else { error = GetLastError(); Com_DPrintf("FS_WriteToTemporaryFile failed to get temporary file folder. " - "Win32 error code: 0x%08x\n", error); + "Win32 error code: 0x%08x\n", + error); } #endif diff --git a/codemp/qcommon/huffman.cpp b/codemp/qcommon/huffman.cpp index 9745a99acb..0d3c149d3b 100644 --- a/codemp/qcommon/huffman.cpp +++ b/codemp/qcommon/huffman.cpp @@ -27,45 +27,45 @@ along with this program; if not, see . #include "qcommon/qcommon.h" -static int bloc = 0; +static int bloc = 0; -void Huff_putBit( int bit, byte *fout, int *offset) { +void Huff_putBit(int bit, byte *fout, int *offset) { bloc = *offset; - if ((bloc&7) == 0) { - fout[(bloc>>3)] = 0; + if ((bloc & 7) == 0) { + fout[(bloc >> 3)] = 0; } - fout[(bloc>>3)] |= bit << (bloc&7); + fout[(bloc >> 3)] |= bit << (bloc & 7); bloc++; *offset = bloc; } -int Huff_getBit( byte *fin, int *offset) { +int Huff_getBit(byte *fin, int *offset) { int t; bloc = *offset; - t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1; + t = (fin[(bloc >> 3)] >> (bloc & 7)) & 0x1; bloc++; *offset = bloc; return t; } /* Add a bit to the output file (buffered) */ -static void add_bit (char bit, byte *fout) { - if ((bloc&7) == 0) { - fout[(bloc>>3)] = 0; +static void add_bit(char bit, byte *fout) { + if ((bloc & 7) == 0) { + fout[(bloc >> 3)] = 0; } - fout[(bloc>>3)] |= bit << (bloc&7); + fout[(bloc >> 3)] |= bit << (bloc & 7); bloc++; } /* Receive one bit from the input file (buffered) */ -static int get_bit (byte *fin) { +static int get_bit(byte *fin) { int t; - t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1; + t = (fin[(bloc >> 3)] >> (bloc & 7)) & 0x1; bloc++; return t; } -static node_t **get_ppnode(huff_t* huff) { +static node_t **get_ppnode(huff_t *huff) { node_t **tppnode; if (!huff->freelist) { return &(huff->nodePtrs[huff->blocPtrs++]); @@ -76,13 +76,13 @@ static node_t **get_ppnode(huff_t* huff) { } } -static void free_ppnode(huff_t* huff, node_t **ppnode) { +static void free_ppnode(huff_t *huff, node_t **ppnode) { *ppnode = (node_t *)huff->freelist; huff->freelist = ppnode; } /* Swap the location of these two nodes in the tree */ -static void swap (huff_t* huff, node_t *node1, node_t *node2) { +static void swap(huff_t *huff, node_t *node1, node_t *node2) { node_t *par1, *par2; par1 = node1->parent; @@ -92,7 +92,7 @@ static void swap (huff_t* huff, node_t *node1, node_t *node2) { if (par1->left == node1) { par1->left = node2; } else { - par1->right = node2; + par1->right = node2; } } else { huff->tree = node2; @@ -145,7 +145,7 @@ static void swaplist(node_t *node1, node_t *node2) { } /* Do the increments */ -static void increment(huff_t* huff, node_t *node) { +static void increment(huff_t *huff, node_t *node) { node_t *lnode; if (!node) { @@ -153,7 +153,7 @@ static void increment(huff_t* huff, node_t *node) { } if (node->next != NULL && node->next->weight == node->weight) { - lnode = *node->head; + lnode = *node->head; if (lnode != node->parent) { swap(huff, lnode, node); } @@ -162,7 +162,7 @@ static void increment(huff_t* huff, node_t *node) { if (node->prev && node->prev->weight == node->weight) { *node->head = node->prev; } else { - *node->head = NULL; + *node->head = NULL; free_ppnode(huff, node->head); } node->weight++; @@ -183,7 +183,7 @@ static void increment(huff_t* huff, node_t *node) { } } -void Huff_addRef(huff_t* huff, byte ch) { +void Huff_addRef(huff_t *huff, byte ch) { node_t *tnode, *tnode2; if (huff->loc[ch] == NULL) { /* if this is the first transmission of this node */ tnode = &(huff->nodeList[huff->blocNode++]); @@ -218,7 +218,7 @@ void Huff_addRef(huff_t* huff, byte ch) { /* this should never happen */ tnode->head = get_ppnode(huff); *tnode->head = tnode2; - } + } } else { /* this should never happen */ tnode->head = get_ppnode(huff); @@ -253,7 +253,7 @@ void Huff_addRef(huff_t* huff, byte ch) { } /* Get a symbol */ -int Huff_Receive (node_t *node, int *ch, byte *fin) { +int Huff_Receive(node_t *node, int *ch, byte *fin) { while (node && node->symbol == INTERNAL_NODE) { if (get_bit(fin)) { node = node->right; @@ -263,13 +263,13 @@ int Huff_Receive (node_t *node, int *ch, byte *fin) { } if (!node) { return 0; -// Com_Error(ERR_DROP, "Illegal tree!\n"); + // Com_Error(ERR_DROP, "Illegal tree!\n"); } return (*ch = node->symbol); } /* Get a symbol */ -void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset, int maxoffset) { +void Huff_offsetReceive(node_t *node, int *ch, byte *fin, int *offset, int maxoffset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (bloc >= maxoffset) { @@ -286,7 +286,7 @@ void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset, int maxo if (!node) { *ch = 0; return; -// Com_Error(ERR_DROP, "Illegal tree!\n"); + // Com_Error(ERR_DROP, "Illegal tree!\n"); } *ch = node->symbol; *offset = bloc; @@ -311,7 +311,7 @@ static void send(node_t *node, node_t *child, byte *fout, int maxoffset) { } /* Send a symbol */ -void Huff_transmit (huff_t *huff, int ch, byte *fout, int maxoffset) { +void Huff_transmit(huff_t *huff, int ch, byte *fout, int maxoffset) { int i; if (huff->loc[ch] == NULL) { /* node_t hasn't been transmitted, send a NYT, then the symbol */ @@ -324,22 +324,22 @@ void Huff_transmit (huff_t *huff, int ch, byte *fout, int maxoffset) { } } -void Huff_offsetTransmit (huff_t *huff, int ch, byte *fout, int *offset, int maxoffset) { +void Huff_offsetTransmit(huff_t *huff, int ch, byte *fout, int *offset, int maxoffset) { bloc = *offset; send(huff->loc[ch], NULL, fout, maxoffset); *offset = bloc; } void Huff_Decompress(msg_t *mbuf, int offset) { - int ch, cch, i, j, size; - byte seq[65536]; - byte* buffer; - huff_t huff; + int ch, cch, i, j, size; + byte seq[65536]; + byte *buffer; + huff_t huff; size = mbuf->cursize - offset; buffer = mbuf->data + offset; - if ( size <= 0 ) { + if (size <= 0) { return; } @@ -351,76 +351,76 @@ void Huff_Decompress(msg_t *mbuf, int offset) { huff.lhead->next = huff.lhead->prev = NULL; huff.tree->parent = huff.tree->left = huff.tree->right = NULL; - cch = buffer[0]*256 + buffer[1]; + cch = buffer[0] * 256 + buffer[1]; // don't overflow with bad messages - if ( cch > mbuf->maxsize - offset ) { + if (cch > mbuf->maxsize - offset) { cch = mbuf->maxsize - offset; } bloc = 16; - for ( j = 0; j < cch; j++ ) { + for (j = 0; j < cch; j++) { ch = 0; // don't overflow reading from the messages // FIXME: would it be better to have a overflow check in get_bit ? - if ( (bloc >> 3) > size ) { + if ((bloc >> 3) > size) { seq[j] = 0; break; } - Huff_Receive(huff.tree, &ch, buffer); /* Get a character */ - if ( ch == NYT ) { /* We got a NYT, get the symbol associated with it */ + Huff_Receive(huff.tree, &ch, buffer); /* Get a character */ + if (ch == NYT) { /* We got a NYT, get the symbol associated with it */ ch = 0; - for ( i = 0; i < 8; i++ ) { - ch = (ch<<1) + get_bit(buffer); + for (i = 0; i < 8; i++) { + ch = (ch << 1) + get_bit(buffer); } } - seq[j] = ch; /* Write symbol */ + seq[j] = ch; /* Write symbol */ - Huff_addRef(&huff, (byte)ch); /* Increment node */ + Huff_addRef(&huff, (byte)ch); /* Increment node */ } mbuf->cursize = cch + offset; Com_Memcpy(mbuf->data + offset, seq, cch); } -extern int oldsize; +extern int oldsize; void Huff_Compress(msg_t *mbuf, int offset) { - int i, ch, size; - byte seq[65536]; - byte* buffer; - huff_t huff; + int i, ch, size; + byte seq[65536]; + byte *buffer; + huff_t huff; size = mbuf->cursize - offset; - buffer = mbuf->data+ + offset; + buffer = mbuf->data + +offset; - if (size<=0) { + if (size <= 0) { return; } Com_Memset(&huff, 0, sizeof(huff_t)); // Add the NYT (not yet transmitted) node into the tree/list */ - huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]); + huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]); huff.tree->symbol = NYT; huff.tree->weight = 0; huff.lhead->next = huff.lhead->prev = NULL; huff.tree->parent = huff.tree->left = huff.tree->right = NULL; huff.loc[NYT] = huff.tree; - seq[0] = (size>>8); - seq[1] = size&0xff; + seq[0] = (size >> 8); + seq[1] = size & 0xff; bloc = 16; - for (i=0; icursize = (bloc>>3) + offset; - Com_Memcpy(mbuf->data+offset, seq, (bloc>>3)); + mbuf->cursize = (bloc >> 3) + offset; + Com_Memcpy(mbuf->data + offset, seq, (bloc >> 3)); } void Huff_Init(huffman_t *huff) { @@ -429,18 +429,18 @@ void Huff_Init(huffman_t *huff) { Com_Memset(&huff->decompressor, 0, sizeof(huff_t)); // Initialize the tree & list with the NYT node - huff->decompressor.tree = huff->decompressor.lhead = huff->decompressor.ltail = huff->decompressor.loc[NYT] = &(huff->decompressor.nodeList[huff->decompressor.blocNode++]); + huff->decompressor.tree = huff->decompressor.lhead = huff->decompressor.ltail = huff->decompressor.loc[NYT] = + &(huff->decompressor.nodeList[huff->decompressor.blocNode++]); huff->decompressor.tree->symbol = NYT; huff->decompressor.tree->weight = 0; huff->decompressor.lhead->next = huff->decompressor.lhead->prev = NULL; huff->decompressor.tree->parent = huff->decompressor.tree->left = huff->decompressor.tree->right = NULL; // Add the NYT (not yet transmitted) node into the tree/list */ - huff->compressor.tree = huff->compressor.lhead = huff->compressor.loc[NYT] = &(huff->compressor.nodeList[huff->compressor.blocNode++]); + huff->compressor.tree = huff->compressor.lhead = huff->compressor.loc[NYT] = &(huff->compressor.nodeList[huff->compressor.blocNode++]); huff->compressor.tree->symbol = NYT; huff->compressor.tree->weight = 0; huff->compressor.lhead->next = huff->compressor.lhead->prev = NULL; huff->compressor.tree->parent = huff->compressor.tree->left = huff->compressor.tree->right = NULL; huff->compressor.loc[NYT] = huff->compressor.tree; } - diff --git a/codemp/qcommon/matcomp.cpp b/codemp/qcommon/matcomp.cpp index b73007685c..2a83b22d6c 100644 --- a/codemp/qcommon/matcomp.cpp +++ b/codemp/qcommon/matcomp.cpp @@ -25,164 +25,163 @@ along with this program; if not, see . #include #include #include -#include // for memcpy +#include // for memcpy -#define MC_MASK_X ((1<<(MC_BITS_X))-1) -#define MC_MASK_Y ((1<<(MC_BITS_Y))-1) -#define MC_MASK_Z ((1<<(MC_BITS_Z))-1) -#define MC_MASK_VECT ((1<<(MC_BITS_VECT))-1) +#define MC_MASK_X ((1 << (MC_BITS_X)) - 1) +#define MC_MASK_Y ((1 << (MC_BITS_Y)) - 1) +#define MC_MASK_Z ((1 << (MC_BITS_Z)) - 1) +#define MC_MASK_VECT ((1 << (MC_BITS_VECT)) - 1) -#define MC_SCALE_VECT (1.0f/(float)((1<<(MC_BITS_VECT-1))-2)) +#define MC_SCALE_VECT (1.0f / (float)((1 << (MC_BITS_VECT - 1)) - 2)) #define MC_POS_X (0) #define MC_SHIFT_X (0) -#define MC_POS_Y ((((MC_BITS_X))/8)) -#define MC_SHIFT_Y ((((MC_BITS_X)%8))) +#define MC_POS_Y ((((MC_BITS_X)) / 8)) +#define MC_SHIFT_Y ((((MC_BITS_X) % 8))) -#define MC_POS_Z ((((MC_BITS_X+MC_BITS_Y))/8)) -#define MC_SHIFT_Z ((((MC_BITS_X+MC_BITS_Y)%8))) +#define MC_POS_Z ((((MC_BITS_X + MC_BITS_Y)) / 8)) +#define MC_SHIFT_Z ((((MC_BITS_X + MC_BITS_Y) % 8))) -#define MC_POS_V11 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z))/8)) -#define MC_SHIFT_V11 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z)%8))) +#define MC_POS_V11 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z)) / 8)) +#define MC_SHIFT_V11 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z) % 8))) -#define MC_POS_V12 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT))/8)) -#define MC_SHIFT_V12 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT)%8))) +#define MC_POS_V12 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT)) / 8)) +#define MC_SHIFT_V12 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT) % 8))) -#define MC_POS_V13 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*2))/8)) -#define MC_SHIFT_V13 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*2)%8))) +#define MC_POS_V13 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 2)) / 8)) +#define MC_SHIFT_V13 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 2) % 8))) -#define MC_POS_V21 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*3))/8)) -#define MC_SHIFT_V21 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*3)%8))) +#define MC_POS_V21 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 3)) / 8)) +#define MC_SHIFT_V21 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 3) % 8))) -#define MC_POS_V22 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*4))/8)) -#define MC_SHIFT_V22 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*4)%8))) +#define MC_POS_V22 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 4)) / 8)) +#define MC_SHIFT_V22 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 4) % 8))) -#define MC_POS_V23 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*5))/8)) -#define MC_SHIFT_V23 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*5)%8))) +#define MC_POS_V23 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 5)) / 8)) +#define MC_SHIFT_V23 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 5) % 8))) -#define MC_POS_V31 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*6))/8)) -#define MC_SHIFT_V31 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*6)%8))) +#define MC_POS_V31 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 6)) / 8)) +#define MC_SHIFT_V31 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 6) % 8))) -#define MC_POS_V32 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*7))/8)) -#define MC_SHIFT_V32 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*7)%8))) +#define MC_POS_V32 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 7)) / 8)) +#define MC_SHIFT_V32 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 7) % 8))) -#define MC_POS_V33 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*8))/8)) -#define MC_SHIFT_V33 ((((MC_BITS_X+MC_BITS_Y+MC_BITS_Z+MC_BITS_VECT*8)%8))) +#define MC_POS_V33 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 8)) / 8)) +#define MC_SHIFT_V33 ((((MC_BITS_X + MC_BITS_Y + MC_BITS_Z + MC_BITS_VECT * 8) % 8))) -void MC_Compress(const float mat[3][4],unsigned char * _comp) -{ - char comp[MC_COMP_BYTES*2]; +void MC_Compress(const float mat[3][4], unsigned char *_comp) { + char comp[MC_COMP_BYTES * 2]; - int i,val; - for (i=0;i=(1<= (1 << MC_BITS_X)) + val = (1 << MC_BITS_X) - 1; + if (val < 0) + val = 0; byteAlias_t *ba = (byteAlias_t *)&comp[MC_POS_X]; ba->ui |= ((uint32_t)val) << MC_SHIFT_X; - val=(int)(mat[1][3]/MC_SCALE_Y); - val+=1<<(MC_BITS_Y-1); - if (val>=(1<= (1 << MC_BITS_Y)) + val = (1 << MC_BITS_Y) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_Y]; ba->ui |= ((uint32_t)val) << MC_SHIFT_Y; - val=(int)(mat[2][3]/MC_SCALE_Z); - val+=1<<(MC_BITS_Z-1); - if (val>=(1<= (1 << MC_BITS_Z)) + val = (1 << MC_BITS_Z) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_Z]; ba->ui |= ((uint32_t)val) << MC_SHIFT_Z; - val=(int)(mat[0][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V11]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V11; - val=(int)(mat[0][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V12]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V12; - val=(int)(mat[0][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V13]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V13; - val=(int)(mat[1][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V21]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V21; - val=(int)(mat[1][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V22]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V22; - val=(int)(mat[1][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V23]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V23; - val=(int)(mat[2][0]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V31]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V31; - val=(int)(mat[2][1]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V32]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V32; - val=(int)(mat[2][2]/MC_SCALE_VECT); - val+=1<<(MC_BITS_VECT-1); - if (val>=(1<= (1 << MC_BITS_VECT)) + val = (1 << MC_BITS_VECT) - 1; + if (val < 0) + val = 0; ba = (byteAlias_t *)&comp[MC_POS_V33]; ba->ui |= ((uint32_t)val) << MC_SHIFT_V33; @@ -190,137 +189,130 @@ void MC_Compress(const float mat[3][4],unsigned char * _comp) // is writing beyond the 24th byte of the output array. This *should** be harmless if the OR'd-in value doesn't change // those bytes, but BoundsChecker says that it's accessing undefined memory (which it does, sometimes). This is probably // bad, so... - memcpy(_comp,comp,MC_COMP_BYTES); + memcpy(_comp, comp, MC_COMP_BYTES); } -void MC_UnCompress(float mat[3][4],const unsigned char * comp) -{ +void MC_UnCompress(float mat[3][4], const unsigned char *comp) { int val; - val=(int)((unsigned short *)(comp))[0]; - val-=1<<(MC_BITS_X-1); - mat[0][3]=((float)(val))*MC_SCALE_X; + val = (int)((unsigned short *)(comp))[0]; + val -= 1 << (MC_BITS_X - 1); + mat[0][3] = ((float)(val)) * MC_SCALE_X; - val=(int)((unsigned short *)(comp))[1]; - val-=1<<(MC_BITS_Y-1); - mat[1][3]=((float)(val))*MC_SCALE_Y; + val = (int)((unsigned short *)(comp))[1]; + val -= 1 << (MC_BITS_Y - 1); + mat[1][3] = ((float)(val)) * MC_SCALE_Y; - val=(int)((unsigned short *)(comp))[2]; - val-=1<<(MC_BITS_Z-1); - mat[2][3]=((float)(val))*MC_SCALE_Z; + val = (int)((unsigned short *)(comp))[2]; + val -= 1 << (MC_BITS_Z - 1); + mat[2][3] = ((float)(val)) * MC_SCALE_Z; - val=(int)((unsigned short *)(comp))[3]; - val-=1<<(MC_BITS_VECT-1); - mat[0][0]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[3]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][0] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[4]; - val-=1<<(MC_BITS_VECT-1); - mat[0][1]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[4]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[5]; - val-=1<<(MC_BITS_VECT-1); - mat[0][2]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[5]; + val -= 1 << (MC_BITS_VECT - 1); + mat[0][2] = ((float)(val)) * MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[6]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][0] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[6]; - val-=1<<(MC_BITS_VECT-1); - mat[1][0]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[7]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[7]; - val-=1<<(MC_BITS_VECT-1); - mat[1][1]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[8]; + val -= 1 << (MC_BITS_VECT - 1); + mat[1][2] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[8]; - val-=1<<(MC_BITS_VECT-1); - mat[1][2]=((float)(val))*MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[9]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][0] = ((float)(val)) * MC_SCALE_VECT; + val = (int)((unsigned short *)(comp))[10]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][1] = ((float)(val)) * MC_SCALE_VECT; - val=(int)((unsigned short *)(comp))[9]; - val-=1<<(MC_BITS_VECT-1); - mat[2][0]=((float)(val))*MC_SCALE_VECT; - - val=(int)((unsigned short *)(comp))[10]; - val-=1<<(MC_BITS_VECT-1); - mat[2][1]=((float)(val))*MC_SCALE_VECT; - - val=(int)((unsigned short *)(comp))[11]; - val-=1<<(MC_BITS_VECT-1); - mat[2][2]=((float)(val))*MC_SCALE_VECT; - + val = (int)((unsigned short *)(comp))[11]; + val -= 1 << (MC_BITS_VECT - 1); + mat[2][2] = ((float)(val)) * MC_SCALE_VECT; } -void MC_UnCompressQuat(float mat[3][4],const unsigned char * comp) -{ - float w,x,y,z,f; - float fTx; - float fTy; - float fTz; - float fTwx; - float fTwy; - float fTwz; - float fTxx; - float fTxy; - float fTxz; - float fTyy; - float fTyz; - float fTzz; - - const unsigned short *pwIn = (unsigned short *) comp; +void MC_UnCompressQuat(float mat[3][4], const unsigned char *comp) { + float w, x, y, z, f; + float fTx; + float fTy; + float fTz; + float fTwx; + float fTwy; + float fTwz; + float fTxx; + float fTxy; + float fTxz; + float fTyy; + float fTyz; + float fTzz; + + const unsigned short *pwIn = (unsigned short *)comp; w = *pwIn++; - w/=16383.0f; - w-=2.0f; + w /= 16383.0f; + w -= 2.0f; x = *pwIn++; - x/=16383.0f; - x-=2.0f; + x /= 16383.0f; + x -= 2.0f; y = *pwIn++; - y/=16383.0f; - y-=2.0f; + y /= 16383.0f; + y -= 2.0f; z = *pwIn++; - z/=16383.0f; - z-=2.0f; - - fTx = 2.0f*x; - fTy = 2.0f*y; - fTz = 2.0f*z; - fTwx = fTx*w; - fTwy = fTy*w; - fTwz = fTz*w; - fTxx = fTx*x; - fTxy = fTy*x; - fTxz = fTz*x; - fTyy = fTy*y; - fTyz = fTz*y; - fTzz = fTz*z; + z /= 16383.0f; + z -= 2.0f; + + fTx = 2.0f * x; + fTy = 2.0f * y; + fTz = 2.0f * z; + fTwx = fTx * w; + fTwy = fTy * w; + fTwz = fTz * w; + fTxx = fTx * x; + fTxy = fTy * x; + fTxz = fTz * x; + fTyy = fTy * y; + fTyz = fTz * y; + fTzz = fTz * z; // rot... // - mat[0][0] = 1.0f-(fTyy+fTzz); - mat[0][1] = fTxy-fTwz; - mat[0][2] = fTxz+fTwy; - mat[1][0] = fTxy+fTwz; - mat[1][1] = 1.0f-(fTxx+fTzz); - mat[1][2] = fTyz-fTwx; - mat[2][0] = fTxz-fTwy; - mat[2][1] = fTyz+fTwx; - mat[2][2] = 1.0f-(fTxx+fTyy); + mat[0][0] = 1.0f - (fTyy + fTzz); + mat[0][1] = fTxy - fTwz; + mat[0][2] = fTxz + fTwy; + mat[1][0] = fTxy + fTwz; + mat[1][1] = 1.0f - (fTxx + fTzz); + mat[1][2] = fTyz - fTwx; + mat[2][0] = fTxz - fTwy; + mat[2][1] = fTyz + fTwx; + mat[2][2] = 1.0f - (fTxx + fTyy); // xlat... // f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[0][3] = f; f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[1][3] = f; f = *pwIn++; - f/=64; - f-=512; + f /= 64; + f -= 512; mat[2][3] = f; } - - diff --git a/codemp/qcommon/md4.cpp b/codemp/qcommon/md4.cpp index 0f34c8d6a5..a90b132ecd 100644 --- a/codemp/qcommon/md4.cpp +++ b/codemp/qcommon/md4.cpp @@ -35,91 +35,121 @@ typedef struct mdfour_s { uint32_t totalN; } mdfour_ctx; - /* NOTE: This code makes no attempt to be fast! It assumes that an int is at least 32 bits long */ -static mdfour_ctx *m; +static mdfour_ctx *m; -#define F(X,Y,Z) (((X)&(Y)) | ((~(X))&(Z))) -#define G(X,Y,Z) (((X)&(Y)) | ((X)&(Z)) | ((Y)&(Z))) -#define H(X,Y,Z) ((X)^(Y)^(Z)) -#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) +#define F(X, Y, Z) (((X) & (Y)) | ((~(X)) & (Z))) +#define G(X, Y, Z) (((X) & (Y)) | ((X) & (Z)) | ((Y) & (Z))) +#define H(X, Y, Z) ((X) ^ (Y) ^ (Z)) +#define lshift(x, s) (((x) << (s)) | ((x) >> (32 - (s)))) -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) +#define ROUND1(a, b, c, d, k, s) a = lshift(a + F(b, c, d) + X[k], s) +#define ROUND2(a, b, c, d, k, s) a = lshift(a + G(b, c, d) + X[k] + 0x5A827999, s) +#define ROUND3(a, b, c, d, k, s) a = lshift(a + H(b, c, d) + X[k] + 0x6ED9EBA1, s) /* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32_t *M) -{ +static void mdfour64(uint32_t *M) { int j; uint32_t AA, BB, CC, DD; uint32_t X[16]; - uint32_t A,B,C,D; + uint32_t A, B, C, D; - for (j=0;j<16;j++) + for (j = 0; j < 16; j++) X[j] = M[j]; - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; - - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); - - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); - - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); - - A += AA; B += BB; C += CC; D += DD; - - for (j=0;j<16;j++) + A = m->A; + B = m->B; + C = m->C; + D = m->D; + AA = A; + BB = B; + CC = C; + DD = D; + + ROUND1(A, B, C, D, 0, 3); + ROUND1(D, A, B, C, 1, 7); + ROUND1(C, D, A, B, 2, 11); + ROUND1(B, C, D, A, 3, 19); + ROUND1(A, B, C, D, 4, 3); + ROUND1(D, A, B, C, 5, 7); + ROUND1(C, D, A, B, 6, 11); + ROUND1(B, C, D, A, 7, 19); + ROUND1(A, B, C, D, 8, 3); + ROUND1(D, A, B, C, 9, 7); + ROUND1(C, D, A, B, 10, 11); + ROUND1(B, C, D, A, 11, 19); + ROUND1(A, B, C, D, 12, 3); + ROUND1(D, A, B, C, 13, 7); + ROUND1(C, D, A, B, 14, 11); + ROUND1(B, C, D, A, 15, 19); + + ROUND2(A, B, C, D, 0, 3); + ROUND2(D, A, B, C, 4, 5); + ROUND2(C, D, A, B, 8, 9); + ROUND2(B, C, D, A, 12, 13); + ROUND2(A, B, C, D, 1, 3); + ROUND2(D, A, B, C, 5, 5); + ROUND2(C, D, A, B, 9, 9); + ROUND2(B, C, D, A, 13, 13); + ROUND2(A, B, C, D, 2, 3); + ROUND2(D, A, B, C, 6, 5); + ROUND2(C, D, A, B, 10, 9); + ROUND2(B, C, D, A, 14, 13); + ROUND2(A, B, C, D, 3, 3); + ROUND2(D, A, B, C, 7, 5); + ROUND2(C, D, A, B, 11, 9); + ROUND2(B, C, D, A, 15, 13); + + ROUND3(A, B, C, D, 0, 3); + ROUND3(D, A, B, C, 8, 9); + ROUND3(C, D, A, B, 4, 11); + ROUND3(B, C, D, A, 12, 15); + ROUND3(A, B, C, D, 2, 3); + ROUND3(D, A, B, C, 10, 9); + ROUND3(C, D, A, B, 6, 11); + ROUND3(B, C, D, A, 14, 15); + ROUND3(A, B, C, D, 1, 3); + ROUND3(D, A, B, C, 9, 9); + ROUND3(C, D, A, B, 5, 11); + ROUND3(B, C, D, A, 13, 15); + ROUND3(A, B, C, D, 3, 3); + ROUND3(D, A, B, C, 11, 9); + ROUND3(C, D, A, B, 7, 11); + ROUND3(B, C, D, A, 15, 15); + + A += AA; + B += BB; + C += CC; + D += DD; + + for (j = 0; j < 16; j++) X[j] = 0; - m->A = A; m->B = B; m->C = C; m->D = D; + m->A = A; + m->B = B; + m->C = C; + m->D = D; } -static void copy64(uint32_t *M, byte *in) -{ +static void copy64(uint32_t *M, byte *in) { int i; - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); + for (i = 0; i < 16; i++) + M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); } -static void copy4(byte *out,uint32_t x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; +static void copy4(byte *out, uint32_t x) { + out[0] = x & 0xFF; + out[1] = (x >> 8) & 0xFF; + out[2] = (x >> 16) & 0xFF; + out[3] = (x >> 24) & 0xFF; } -void mdfour_begin(mdfour_ctx *md) -{ +void mdfour_begin(mdfour_ctx *md) { md->A = 0x67452301; md->B = 0xefcdab89; md->C = 0x98badcfe; @@ -127,9 +157,7 @@ void mdfour_begin(mdfour_ctx *md) md->totalN = 0; } - -static void mdfour_tail(byte *in, int n) -{ +static void mdfour_tail(byte *in, int n) { byte buf[128]; uint32_t M[16]; uint32_t b; @@ -139,29 +167,30 @@ static void mdfour_tail(byte *in, int n) b = m->totalN * 8; Com_Memset(buf, 0, 128); - if (n) Com_Memcpy(buf, in, n); + if (n) + Com_Memcpy(buf, in, n); buf[n] = 0x80; if (n <= 55) { - copy4(buf+56, b); + copy4(buf + 56, b); copy64(M, buf); mdfour64(M); } else { - copy4(buf+120, b); + copy4(buf + 120, b); copy64(M, buf); mdfour64(M); - copy64(M, buf+64); + copy64(M, buf + 64); mdfour64(M); } } -static void mdfour_update(mdfour_ctx *md, byte *in, int n) -{ +static void mdfour_update(mdfour_ctx *md, byte *in, int n) { uint32_t M[16]; m = md; - if (n == 0) mdfour_tail(in, n); + if (n == 0) + mdfour_tail(in, n); while (n >= 64) { copy64(M, in); @@ -174,19 +203,16 @@ static void mdfour_update(mdfour_ctx *md, byte *in, int n) mdfour_tail(in, n); } - -static void mdfour_result(mdfour_ctx *md, byte *out) -{ +static void mdfour_result(mdfour_ctx *md, byte *out) { m = md; copy4(out, m->A); - copy4(out+4, m->B); - copy4(out+8, m->C); - copy4(out+12, m->D); + copy4(out + 4, m->B); + copy4(out + 8, m->C); + copy4(out + 12, m->D); } -static void mdfour(byte *out, byte *in, int n) -{ +static void mdfour(byte *out, byte *in, int n) { mdfour_ctx md; mdfour_begin(&md); mdfour_update(&md, in, n); @@ -195,12 +221,11 @@ static void mdfour(byte *out, byte *in, int n) //=================================================================== -uint32_t Com_BlockChecksum (const void *buffer, int length) -{ - int digest[4]; - uint32_t val; +uint32_t Com_BlockChecksum(const void *buffer, int length) { + int digest[4]; + uint32_t val; - mdfour( (byte *)digest, (byte *)buffer, length ); + mdfour((byte *)digest, (byte *)buffer, length); val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; diff --git a/codemp/qcommon/md5.cpp b/codemp/qcommon/md5.cpp index 8bb307d0f0..cf0d1572b2 100644 --- a/codemp/qcommon/md5.cpp +++ b/codemp/qcommon/md5.cpp @@ -22,39 +22,35 @@ #include "qcommon.h" #ifndef Q3_BIG_ENDIAN - #define byteReverse(buf, len) /* Nothing */ +#define byteReverse(buf, len) /* Nothing */ #else - static void byteReverse(unsigned char *buf, unsigned longs); - - /* - * Note: this code is harmless on little-endian machines. - */ - static void byteReverse(unsigned char *buf, unsigned longs) - { - uint32_t t; - do { - t = (uint32_t) - ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(uint32_t *) buf = t; - buf += 4; - } while (--longs); - } +static void byteReverse(unsigned char *buf, unsigned longs); + +/* + * Note: this code is harmless on little-endian machines. + */ +static void byteReverse(unsigned char *buf, unsigned longs) { + uint32_t t; + do { + t = (uint32_t)((unsigned)buf[3] << 8 | buf[2]) << 16 | ((unsigned)buf[1] << 8 | buf[0]); + *(uint32_t *)buf = t; + buf += 4; + } while (--longs); +} #endif // Q3_BIG_ENDIAN /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ -void MD5Init(struct MD5Context *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; +void MD5Init(struct MD5Context *ctx) { + ctx->buf[0] = 0x67452301; + ctx->buf[1] = 0xefcdab89; + ctx->buf[2] = 0x98badcfe; + ctx->buf[3] = 0x10325476; + + ctx->bits[0] = 0; + ctx->bits[1] = 0; } /* The four core functions - F1 is optimized somewhat */ @@ -66,118 +62,115 @@ void MD5Init(struct MD5Context *ctx) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) +#define MD5STEP(f, w, x, y, z, data, s) (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ -static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) -{ - uint32_t a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; +static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) { + uint32_t a, b, c, d; + + a = buf[0]; + b = buf[1]; + c = buf[2]; + d = buf[3]; + + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); + MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); + MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); + MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); + MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); + + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); + MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); + + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); + MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); + MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); + MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); + MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); + MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); + + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); + MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); + MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); + MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); + MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); + MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ -void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) -{ - uint32_t t; +void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) { + uint32_t t; - /* Update bitcount */ + /* Update bitcount */ - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ - ctx->bits[1] += len >> 29; + t = ctx->bits[0]; + if ((ctx->bits[0] = t + ((uint32_t)len << 3)) < t) + ctx->bits[1]++; /* Carry from low to high */ + ctx->bits[1] += len >> 29; - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ + t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - /* Handle any leading odd-sized chunks */ + /* Handle any leading odd-sized chunks */ - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; + if (t) { + unsigned char *p = (unsigned char *)ctx->in + t; t = 64 - t; if (len < t) { @@ -186,74 +179,72 @@ void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) } memcpy(p, buf, t); byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); + MD5Transform(ctx->buf, (uint32_t *)ctx->in); buf += t; len -= t; - } - /* Process data in 64-byte chunks */ + } + /* Process data in 64-byte chunks */ - while (len >= 64) { + while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); + MD5Transform(ctx->buf, (uint32_t *)ctx->in); buf += 64; len -= 64; - } + } - /* Handle any remaining bytes of data. */ + /* Handle any remaining bytes of data. */ - memcpy(ctx->in, buf, len); + memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ -void MD5Final(struct MD5Context *ctx, unsigned char *digest) -{ - unsigned count; - unsigned char *p; +void MD5Final(struct MD5Context *ctx, unsigned char *digest) { + unsigned count; + unsigned char *p; - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; + /* Compute number of bytes mod 64 */ + count = (ctx->bits[0] >> 3) & 0x3F; - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + p = ctx->in + count; + *p++ = 0x80; - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; + /* Bytes of padding needed to make 64 bytes */ + count = 64 - 1 - count; - /* Pad out to 56 mod 64 */ - if (count < 8) { + /* Pad out to 56 mod 64 */ + if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (uint32_t *) ctx->in); + MD5Transform(ctx->buf, (uint32_t *)ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); - } else { + } else { /* Pad block to 56 bytes */ memset(p, 0, count - 8); - } - byteReverse(ctx->in, 14); + } + byteReverse(ctx->in, 14); - /* Append length in bits and transform */ - ((uint32_t *) ctx->in)[14] = ctx->bits[0]; - ((uint32_t *) ctx->in)[15] = ctx->bits[1]; + /* Append length in bits and transform */ + ((uint32_t *)ctx->in)[14] = ctx->bits[0]; + ((uint32_t *)ctx->in)[15] = ctx->bits[1]; - MD5Transform(ctx->buf, (uint32_t *) ctx->in); - byteReverse((unsigned char *) ctx->buf, 4); + MD5Transform(ctx->buf, (uint32_t *)ctx->in); + byteReverse((unsigned char *)ctx->buf, 4); - if (digest!=NULL) - memcpy(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ + if (digest != NULL) + memcpy(digest, ctx->buf, 16); + memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ } -char *Com_MD5File( const char *fn, int length, const char *prefix, int prefix_len ) -{ +char *Com_MD5File(const char *fn, int length, const char *prefix, int prefix_len) { static char final[33] = {""}; unsigned char digest[16] = {""}; fileHandle_t f; @@ -264,41 +255,41 @@ char *Com_MD5File( const char *fn, int length, const char *prefix, int prefix_le int r = 0; int total = 0; - Q_strncpyz( final, "", sizeof( final ) ); + Q_strncpyz(final, "", sizeof(final)); - filelen = FS_SV_FOpenFileRead( fn, &f ); + filelen = FS_SV_FOpenFileRead(fn, &f); - if( !f ) { + if (!f) { return final; } - if( filelen < 1 ) { - FS_FCloseFile( f ); + if (filelen < 1) { + FS_FCloseFile(f); return final; } - if(filelen < length || !length) { + if (filelen < length || !length) { length = filelen; } MD5Init(&md5); - if( prefix_len && *prefix ) - MD5Update(&md5 , (unsigned char *)prefix, prefix_len); + if (prefix_len && *prefix) + MD5Update(&md5, (unsigned char *)prefix, prefix_len); - for(;;) { + for (;;) { r = FS_Read(buffer, sizeof(buffer), f); - if(r < 1) + if (r < 1) break; - if(r + total > length) + if (r + total > length) r = length - total; total += r; - MD5Update(&md5 , buffer, r); - if(r < (int)sizeof(buffer) || total >= length) + MD5Update(&md5, buffer, r); + if (r < (int)sizeof(buffer) || total >= length) break; } FS_FCloseFile(f); MD5Final(&md5, digest); final[0] = '\0'; - for(i = 0; i < 16; i++) { + for (i = 0; i < 16; i++) { Q_strcat(final, sizeof(final), va("%02X", digest[i])); } return final; @@ -309,8 +300,7 @@ char *Com_MD5File( const char *fn, int length, const char *prefix, int prefix_le * This code (originally for OpenJK) is also released into the public domain. */ -void HMAC_MD5_Init(hmacMD5Context_t *ctx, unsigned char const *key, unsigned int keylen) -{ +void HMAC_MD5_Init(hmacMD5Context_t *ctx, unsigned char const *key, unsigned int keylen) { unsigned char shortenedKey[MD5_DIGEST_SIZE]; if (keylen > MD5_BLOCK_SIZE) { MD5Init(&ctx->md5Context); @@ -331,13 +321,9 @@ void HMAC_MD5_Init(hmacMD5Context_t *ctx, unsigned char const *key, unsigned int MD5Update(&ctx->md5Context, ctx->iKeyPad, sizeof(ctx->iKeyPad)); } -void HMAC_MD5_Update(hmacMD5Context_t *ctx, unsigned char const *buf, unsigned int len) -{ - MD5Update(&ctx->md5Context, buf, len); -} +void HMAC_MD5_Update(hmacMD5Context_t *ctx, unsigned char const *buf, unsigned int len) { MD5Update(&ctx->md5Context, buf, len); } -void HMAC_MD5_Final(hmacMD5Context_t *ctx, unsigned char *digest) -{ +void HMAC_MD5_Final(hmacMD5Context_t *ctx, unsigned char *digest) { unsigned char hashSum1[MD5_DIGEST_SIZE]; MD5Final(&ctx->md5Context, hashSum1); @@ -347,8 +333,7 @@ void HMAC_MD5_Final(hmacMD5Context_t *ctx, unsigned char *digest) MD5Final(&ctx->md5Context, digest); } -void HMAC_MD5_Reset(hmacMD5Context_t *ctx) -{ +void HMAC_MD5_Reset(hmacMD5Context_t *ctx) { MD5Init(&ctx->md5Context); MD5Update(&ctx->md5Context, ctx->iKeyPad, sizeof(ctx->iKeyPad)); } \ No newline at end of file diff --git a/codemp/qcommon/msg.cpp b/codemp/qcommon/msg.cpp index 79d511e00e..9d03ee6fe4 100644 --- a/codemp/qcommon/msg.cpp +++ b/codemp/qcommon/msg.cpp @@ -29,11 +29,11 @@ along with this program; if not, see . //#define _NEWHUFFTABLE_ // Build "c:\\netchan.bin" //#define _USINGNEWHUFFTABLE_ // Build a new frequency table to cut and paste. -static huffman_t msgHuff; +static huffman_t msgHuff; -static qboolean msgInit = qfalse; +static qboolean msgInit = qfalse; #ifdef _NEWHUFFTABLE_ -static FILE *fp=0; +static FILE *fp = 0; #endif /* @@ -46,7 +46,7 @@ Handles byte ordering and avoids alignment errors */ #ifndef FINAL_BUILD - int gLastBitIndex = 0; +int gLastBitIndex = 0; #endif int oldsize = 0; @@ -56,68 +56,61 @@ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides); void MSG_initHuffman(); -void MSG_Init( msg_t *buf, byte *data, int length ) { - if (!g_nOverrideChecked) - { - //Check for netf overrides +void MSG_Init(msg_t *buf, byte *data, int length) { + if (!g_nOverrideChecked) { + // Check for netf overrides MSG_CheckNETFPSFOverrides(qfalse); - //Then for psf overrides + // Then for psf overrides MSG_CheckNETFPSFOverrides(qtrue); g_nOverrideChecked = true; } - if (!msgInit) - { + if (!msgInit) { MSG_initHuffman(); } - Com_Memset (buf, 0, sizeof(*buf)); + Com_Memset(buf, 0, sizeof(*buf)); buf->data = data; buf->maxsize = length; } -void MSG_InitOOB( msg_t *buf, byte *data, int length ) { - if (!g_nOverrideChecked) - { - //Check for netf overrides +void MSG_InitOOB(msg_t *buf, byte *data, int length) { + if (!g_nOverrideChecked) { + // Check for netf overrides MSG_CheckNETFPSFOverrides(qfalse); - //Then for psf overrides + // Then for psf overrides MSG_CheckNETFPSFOverrides(qtrue); g_nOverrideChecked = true; } - if (!msgInit) - { + if (!msgInit) { MSG_initHuffman(); } - Com_Memset (buf, 0, sizeof(*buf)); + Com_Memset(buf, 0, sizeof(*buf)); buf->data = data; buf->maxsize = length; buf->oob = qtrue; } -void MSG_Clear( msg_t *buf ) { +void MSG_Clear(msg_t *buf) { buf->cursize = 0; buf->overflowed = qfalse; - buf->bit = 0; //<- in bits + buf->bit = 0; //<- in bits } +void MSG_Bitstream(msg_t *buf) { buf->oob = qfalse; } -void MSG_Bitstream( msg_t *buf ) { - buf->oob = qfalse; -} - -void MSG_BeginReading( msg_t *msg ) { +void MSG_BeginReading(msg_t *msg) { msg->readcount = 0; msg->bit = 0; msg->oob = qfalse; } -void MSG_BeginReadingOOB( msg_t *msg ) { +void MSG_BeginReadingOOB(msg_t *msg) { msg->readcount = 0; msg->bit = 0; msg->oob = qtrue; @@ -131,37 +124,37 @@ bit functions ============================================================================= */ -int overflows; +int overflows; // negative bit values include signs -void MSG_WriteBits( msg_t *msg, int value, int bits ) { - int i; +void MSG_WriteBits(msg_t *msg, int value, int bits) { + int i; oldsize += bits; - if ( msg->overflowed ) { + if (msg->overflowed) { return; } - if ( bits == 0 || bits < -31 || bits > 32 ) { - Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits ); + if (bits == 0 || bits < -31 || bits > 32) { + Com_Error(ERR_DROP, "MSG_WriteBits: bad bits %i", bits); } // check for overflows - if ( bits != 32 ) { - if ( bits > 0 ) { - if ( value > ( ( 1 << bits ) - 1 ) || value < 0 ) { + if (bits != 32) { + if (bits > 0) { + if (value > ((1 << bits) - 1) || value < 0) { overflows++; #ifndef FINAL_BUILD // Com_Printf ("MSG_WriteBits: overflow writing %d in %d bits [index %i]\n", value, bits, gLastBitIndex); #endif } } else { - int r; + int r; - r = 1 << (bits-1); + r = 1 << (bits - 1); - if ( value > r - 1 || value < -r ) { + if (value > r - 1 || value < -r) { overflows++; #ifndef FINAL_BUILD // Com_Printf ("MSG_WriteBits: overflow writing %d in %d bits [index %i]\n", value, bits, gLastBitIndex); @@ -169,26 +162,26 @@ void MSG_WriteBits( msg_t *msg, int value, int bits ) { } } } - if ( bits < 0 ) { + if (bits < 0) { bits = -bits; } if (msg->oob) { - if ( msg->cursize + ( bits >> 3 ) > msg->maxsize ) { + if (msg->cursize + (bits >> 3) > msg->maxsize) { msg->overflowed = qtrue; return; } - if (bits==8) { + if (bits == 8) { msg->data[msg->cursize] = value; msg->cursize += 1; msg->bit += 8; - } else if (bits==16) { + } else if (bits == 16) { short temp = value; CopyLittleShort(&msg->data[msg->cursize], &temp); msg->cursize += 2; msg->bit += 16; - } else if (bits==32) { + } else if (bits == 32) { CopyLittleLong(&msg->data[msg->cursize], &value); msg->cursize += 4; msg->bit += 32; @@ -196,51 +189,51 @@ void MSG_WriteBits( msg_t *msg, int value, int bits ) { Com_Error(ERR_DROP, "can't write %d bits\n", bits); } } else { - value &= (0xffffffff>>(32-bits)); - if (bits&7) { + value &= (0xffffffff >> (32 - bits)); + if (bits & 7) { int nbits; - nbits = bits&7; - if ( msg->bit + nbits > msg->maxsize << 3 ) { + nbits = bits & 7; + if (msg->bit + nbits > msg->maxsize << 3) { msg->overflowed = qtrue; return; } - for(i=0;idata, &msg->bit); - value = (value>>1); + for (i = 0; i < nbits; i++) { + Huff_putBit((value & 1), msg->data, &msg->bit); + value = (value >> 1); } bits = bits - nbits; } if (bits) { - for(i=0;idata, &msg->bit, msg->maxsize << 3); - value = (value>>8); + Huff_offsetTransmit(&msgHuff.compressor, (value & 0xff), msg->data, &msg->bit, msg->maxsize << 3); + value = (value >> 8); - if ( msg->bit > msg->maxsize << 3 ) { + if (msg->bit > msg->maxsize << 3) { msg->overflowed = qtrue; return; } } } - msg->cursize = (msg->bit>>3)+1; + msg->cursize = (msg->bit >> 3) + 1; } } -int MSG_ReadBits( msg_t *msg, int bits ) { - int value; - int get; - qboolean sgn; - int i, nbits; +int MSG_ReadBits(msg_t *msg, int bits) { + int value; + int get; + qboolean sgn; + int i, nbits; - if ( msg->readcount > msg->cursize ) { + if (msg->readcount > msg->cursize) { return 0; } value = 0; - if ( bits < 0 ) { + if (bits < 0) { bits = -bits; sgn = qtrue; } else { @@ -248,23 +241,23 @@ int MSG_ReadBits( msg_t *msg, int bits ) { } if (msg->oob) { - if (msg->readcount + (bits>>3) > msg->cursize) { + if (msg->readcount + (bits >> 3) > msg->cursize) { msg->readcount = msg->cursize + 1; return 0; } - if (bits==8) { + if (bits == 8) { value = msg->data[msg->readcount]; msg->readcount += 1; msg->bit += 8; - } else if (bits==16) { + } else if (bits == 16) { short temp; CopyLittleShort(&temp, &msg->data[msg->readcount]); value = temp; msg->readcount += 2; msg->bit += 16; - } else if (bits==32) { + } else if (bits == 32) { CopyLittleLong(&value, &msg->data[msg->readcount]); msg->readcount += 4; msg->bit += 32; @@ -273,159 +266,150 @@ int MSG_ReadBits( msg_t *msg, int bits ) { } } else { nbits = 0; - if (bits&7) { - nbits = bits&7; + if (bits & 7) { + nbits = bits & 7; if (msg->bit + nbits > msg->cursize << 3) { msg->readcount = msg->cursize + 1; return 0; } - for(i=0;idata, &msg->bit)<data, &msg->bit) << i); } bits = bits - nbits; } if (bits) { - for(i=0;idata, &msg->bit, msg->cursize<<3); + for (i = 0; i < bits; i += 8) { + Huff_offsetReceive(msgHuff.decompressor.tree, &get, msg->data, &msg->bit, msg->cursize << 3); #ifdef _NEWHUFFTABLE_ fwrite(&get, 1, 1, fp); #endif // _NEWHUFFTABLE_ - value |= (get<<(i+nbits)); + value |= (get << (i + nbits)); - if (msg->bit > msg->cursize<<3) { + if (msg->bit > msg->cursize << 3) { msg->readcount = msg->cursize + 1; return 0; } } } - msg->readcount = (msg->bit>>3)+1; + msg->readcount = (msg->bit >> 3) + 1; } - if ( sgn && bits > 0 && bits < 32 ) { - if ( value & ( 1 << ( bits - 1 ) ) ) { - value |= -1 ^ ( ( 1 << bits ) - 1 ); + if (sgn && bits > 0 && bits < 32) { + if (value & (1 << (bits - 1))) { + value |= -1 ^ ((1 << bits) - 1); } } return value; } - - //================================================================================ // // writing functions // -void MSG_WriteChar( msg_t *sb, int c ) { +void MSG_WriteChar(msg_t *sb, int c) { #ifdef PARANOID if (c < -128 || c > 127) - Com_Error (ERR_FATAL, "MSG_WriteChar: range error"); + Com_Error(ERR_FATAL, "MSG_WriteChar: range error"); #endif - MSG_WriteBits( sb, c, 8 ); + MSG_WriteBits(sb, c, 8); } -void MSG_WriteByte( msg_t *sb, int c ) { +void MSG_WriteByte(msg_t *sb, int c) { #ifdef PARANOID if (c < 0 || c > 255) - Com_Error (ERR_FATAL, "MSG_WriteByte: range error"); + Com_Error(ERR_FATAL, "MSG_WriteByte: range error"); #endif - MSG_WriteBits( sb, c, 8 ); + MSG_WriteBits(sb, c, 8); } -void MSG_WriteData( msg_t *buf, const void *data, int length ) { +void MSG_WriteData(msg_t *buf, const void *data, int length) { int i; - for(i=0;i (short)0x7fff) - Com_Error (ERR_FATAL, "MSG_WriteShort: range error"); + Com_Error(ERR_FATAL, "MSG_WriteShort: range error"); #endif - MSG_WriteBits( sb, c, 16 ); + MSG_WriteBits(sb, c, 16); } -void MSG_WriteLong( msg_t *sb, int c ) { - MSG_WriteBits( sb, c, 32 ); -} +void MSG_WriteLong(msg_t *sb, int c) { MSG_WriteBits(sb, c, 32); } -void MSG_WriteFloat( msg_t *sb, float f ) { +void MSG_WriteFloat(msg_t *sb, float f) { byteAlias_t dat; dat.f = f; - MSG_WriteBits( sb, dat.i, 32 ); + MSG_WriteBits(sb, dat.i, 32); } -void MSG_WriteString( msg_t *sb, const char *s ) { - if ( !s ) { - MSG_WriteData (sb, "", 1); +void MSG_WriteString(msg_t *sb, const char *s) { + if (!s) { + MSG_WriteData(sb, "", 1); } else { - int l; - char string[MAX_STRING_CHARS]; + int l; + char string[MAX_STRING_CHARS]; - l = strlen( s ); - if ( l >= MAX_STRING_CHARS ) { - Com_Printf( "MSG_WriteString: MAX_STRING_CHARS" ); - MSG_WriteData (sb, "", 1); + l = strlen(s); + if (l >= MAX_STRING_CHARS) { + Com_Printf("MSG_WriteString: MAX_STRING_CHARS"); + MSG_WriteData(sb, "", 1); return; } - Q_strncpyz( string, s, sizeof( string ) ); + Q_strncpyz(string, s, sizeof(string)); -// eurofix: eliminating this means you can chat in european languages. WTF are "old clients" anyway? -ste -// -// // get rid of 0xff chars, because old clients don't like them -// for ( int i = 0 ; i < l ; i++ ) { -// if ( ((byte *)string)[i] > 127 ) { -// string[i] = '.'; -// } -// } + // eurofix: eliminating this means you can chat in european languages. WTF are "old clients" anyway? -ste + // + // // get rid of 0xff chars, because old clients don't like them + // for ( int i = 0 ; i < l ; i++ ) { + // if ( ((byte *)string)[i] > 127 ) { + // string[i] = '.'; + // } + // } - MSG_WriteData (sb, string, l+1); + MSG_WriteData(sb, string, l + 1); } } -void MSG_WriteBigString( msg_t *sb, const char *s ) { - if ( !s ) { - MSG_WriteData (sb, "", 1); +void MSG_WriteBigString(msg_t *sb, const char *s) { + if (!s) { + MSG_WriteData(sb, "", 1); } else { - int l; - char string[BIG_INFO_STRING]; + int l; + char string[BIG_INFO_STRING]; - l = strlen( s ); - if ( l >= BIG_INFO_STRING ) { - Com_Printf( "MSG_WriteString: BIG_INFO_STRING" ); - MSG_WriteData (sb, "", 1); + l = strlen(s); + if (l >= BIG_INFO_STRING) { + Com_Printf("MSG_WriteString: BIG_INFO_STRING"); + MSG_WriteData(sb, "", 1); return; } - Q_strncpyz( string, s, sizeof( string ) ); - -// eurofix: remove this so we can chat in european languages... -ste -/* - // get rid of 0xff chars, because old clients don't like them - for ( int i = 0 ; i < l ; i++ ) { - if ( ((byte *)string)[i] > 127 ) { - string[i] = '.'; - } - } -*/ + Q_strncpyz(string, s, sizeof(string)); + + // eurofix: remove this so we can chat in european languages... -ste + /* + // get rid of 0xff chars, because old clients don't like them + for ( int i = 0 ; i < l ; i++ ) { + if ( ((byte *)string)[i] > 127 ) { + string[i] = '.'; + } + } + */ - MSG_WriteData (sb, string, l+1); + MSG_WriteData(sb, string, l + 1); } } -void MSG_WriteAngle( msg_t *sb, float f ) { - MSG_WriteByte (sb, (int)(f*256/360) & 255); -} - -void MSG_WriteAngle16( msg_t *sb, float f ) { - MSG_WriteShort (sb, ANGLE2SHORT(f)); -} +void MSG_WriteAngle(msg_t *sb, float f) { MSG_WriteByte(sb, (int)(f * 256 / 360) & 255); } +void MSG_WriteAngle16(msg_t *sb, float f) { MSG_WriteShort(sb, ANGLE2SHORT(f)); } //============================================================ @@ -434,161 +418,155 @@ void MSG_WriteAngle16( msg_t *sb, float f ) { // // returns -1 if no more characters are available -int MSG_ReadChar (msg_t *msg ) { - int c; +int MSG_ReadChar(msg_t *msg) { + int c; - c = (signed char)MSG_ReadBits( msg, 8 ); - if ( msg->readcount > msg->cursize ) { + c = (signed char)MSG_ReadBits(msg, 8); + if (msg->readcount > msg->cursize) { c = -1; } return c; } -int MSG_ReadByte( msg_t *msg ) { - int c; +int MSG_ReadByte(msg_t *msg) { + int c; - c = (unsigned char)MSG_ReadBits( msg, 8 ); - if ( msg->readcount > msg->cursize ) { + c = (unsigned char)MSG_ReadBits(msg, 8); + if (msg->readcount > msg->cursize) { c = -1; } return c; } -int MSG_ReadShort( msg_t *msg ) { - int c; +int MSG_ReadShort(msg_t *msg) { + int c; - c = (short)MSG_ReadBits( msg, 16 ); - if ( msg->readcount > msg->cursize ) { + c = (short)MSG_ReadBits(msg, 16); + if (msg->readcount > msg->cursize) { c = -1; } return c; } -int MSG_ReadLong( msg_t *msg ) { - int c; +int MSG_ReadLong(msg_t *msg) { + int c; - c = MSG_ReadBits( msg, 32 ); - if ( msg->readcount > msg->cursize ) { + c = MSG_ReadBits(msg, 32); + if (msg->readcount > msg->cursize) { c = -1; } return c; } -float MSG_ReadFloat( msg_t *msg ) { +float MSG_ReadFloat(msg_t *msg) { byteAlias_t dat; - dat.i = MSG_ReadBits( msg, 32 ); - if ( msg->readcount > msg->cursize ) { + dat.i = MSG_ReadBits(msg, 32); + if (msg->readcount > msg->cursize) { dat.f = -1; } return dat.f; } -char *MSG_ReadString( msg_t *msg ) { - static char string[MAX_STRING_CHARS]; - int c; +char *MSG_ReadString(msg_t *msg) { + static char string[MAX_STRING_CHARS]; + int c; unsigned int l; l = 0; do { - c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds - if ( c == -1 || c == 0 ) { + c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds + if (c == -1 || c == 0) { break; } // translate all fmt spec to avoid crash bugs - if ( c == '%' ) { + if (c == '%') { c = '.'; } -// eurofix: remove this so we can chat in european languages... -ste -// -// // don't allow higher ascii values -// if ( c > 127 ) { -// c = '.'; -// } + // eurofix: remove this so we can chat in european languages... -ste + // + // // don't allow higher ascii values + // if ( c > 127 ) { + // c = '.'; + // } string[l] = c; l++; - } while (l <= sizeof(string)-1); + } while (l <= sizeof(string) - 1); // some bonus protection, shouldn't occur cause server doesn't write such things - if (l <= sizeof(string)-1) - { + if (l <= sizeof(string) - 1) { string[l] = 0; - } - else - { - string[sizeof(string)-1] = 0; + } else { + string[sizeof(string) - 1] = 0; } return string; } -char *MSG_ReadBigString( msg_t *msg ) { - static char string[BIG_INFO_STRING]; - int c; +char *MSG_ReadBigString(msg_t *msg) { + static char string[BIG_INFO_STRING]; + int c; unsigned int l; l = 0; do { - c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds - if ( c == -1 || c == 0 ) { + c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds + if (c == -1 || c == 0) { break; } // translate all fmt spec to avoid crash bugs - if ( c == '%' ) { + if (c == '%') { c = '.'; } string[l] = c; l++; - } while (l < sizeof(string)-1); + } while (l < sizeof(string) - 1); string[l] = 0; return string; } -char *MSG_ReadStringLine( msg_t *msg ) { - static char string[MAX_STRING_CHARS]; - int c; +char *MSG_ReadStringLine(msg_t *msg) { + static char string[MAX_STRING_CHARS]; + int c; unsigned int l; l = 0; do { - c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds + c = MSG_ReadByte(msg); // use ReadByte so -1 is out of bounds if (c == -1 || c == 0 || c == '\n') { break; } // translate all fmt spec to avoid crash bugs - if ( c == '%' ) { + if (c == '%') { c = '.'; } string[l] = c; l++; - } while (l < sizeof(string)-1); + } while (l < sizeof(string) - 1); string[l] = 0; return string; } -float MSG_ReadAngle16( msg_t *msg ) { - return SHORT2ANGLE(MSG_ReadShort(msg)); -} +float MSG_ReadAngle16(msg_t *msg) { return SHORT2ANGLE(MSG_ReadShort(msg)); } -void MSG_ReadData( msg_t *msg, void *data, int len ) { - int i; +void MSG_ReadData(msg_t *msg, void *data, int len) { + int i; - for (i=0 ; iinteger == 4 ) { Com_Printf("%s ", x ); }; +#define LOG(x) \ + if (cl_shownet && cl_shownet->integer == 4) { \ + Com_Printf("%s ", x); \ + }; -void MSG_WriteDelta( msg_t *msg, int oldV, int newV, int bits ) { - if ( oldV == newV ) { - MSG_WriteBits( msg, 0, 1 ); +void MSG_WriteDelta(msg_t *msg, int oldV, int newV, int bits) { + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, newV, bits ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, newV, bits); } -int MSG_ReadDelta( msg_t *msg, int oldV, int bits ) { - if ( MSG_ReadBits( msg, 1 ) ) { - return MSG_ReadBits( msg, bits ); +int MSG_ReadDelta(msg_t *msg, int oldV, int bits) { + if (MSG_ReadBits(msg, 1)) { + return MSG_ReadBits(msg, bits); } return oldV; } -void MSG_WriteDeltaFloat( msg_t *msg, float oldV, float newV ) { +void MSG_WriteDeltaFloat(msg_t *msg, float oldV, float newV) { byteAlias_t fi; - if ( oldV == newV ) { - MSG_WriteBits( msg, 0, 1 ); + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } fi.f = newV; - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, fi.i, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, fi.i, 32); } -float MSG_ReadDeltaFloat( msg_t *msg, float oldV ) { - if ( MSG_ReadBits( msg, 1 ) ) { +float MSG_ReadDeltaFloat(msg_t *msg, float oldV) { + if (MSG_ReadBits(msg, 1)) { byteAlias_t fi; - fi.i = MSG_ReadBits( msg, 32 ); + fi.i = MSG_ReadBits(msg, 32); return fi.f; } return oldV; @@ -647,62 +628,54 @@ delta functions with keys */ uint32_t kbitmask[32] = { - 0x00000001, 0x00000003, 0x00000007, 0x0000000F, - 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, - 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, - 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, - 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, - 0x001FFFFf, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, - 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, - 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, + 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, + 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFf, 0x003FFFFF, + 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, }; -void MSG_WriteDeltaKey( msg_t *msg, int key, int oldV, int newV, int bits ) -{ - if ( oldV == newV ) - { - MSG_WriteBits( msg, 0, 1 ); +void MSG_WriteDeltaKey(msg_t *msg, int key, int oldV, int newV, int bits) { + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, (newV ^ key) & ((1 << bits) - 1), bits ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, (newV ^ key) & ((1 << bits) - 1), bits); } -int MSG_ReadDeltaKey( msg_t *msg, int key, int oldV, int bits ) { - if ( MSG_ReadBits( msg, 1 ) ) { +int MSG_ReadDeltaKey(msg_t *msg, int key, int oldV, int bits) { + if (MSG_ReadBits(msg, 1)) { #if 0 // Old technically wrong for angles & buttons return MSG_ReadBits( msg, bits ) ^ (key & kbitmask[bits]); #else // Correct, not going out of bounds - return MSG_ReadBits( msg, bits ) ^ (key & kbitmask[ bits - 1 ]); + return MSG_ReadBits(msg, bits) ^ (key & kbitmask[bits - 1]); #endif } return oldV; } -void MSG_WriteDeltaKeyFloat( msg_t *msg, int key, float oldV, float newV ) { +void MSG_WriteDeltaKeyFloat(msg_t *msg, int key, float oldV, float newV) { byteAlias_t fi; - if ( oldV == newV ) { - MSG_WriteBits( msg, 0, 1 ); + if (oldV == newV) { + MSG_WriteBits(msg, 0, 1); return; } fi.f = newV; - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, fi.i ^ key, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, fi.i ^ key, 32); } -float MSG_ReadDeltaKeyFloat( msg_t *msg, int key, float oldV ) { - if ( MSG_ReadBits( msg, 1 ) ) { +float MSG_ReadDeltaKeyFloat(msg_t *msg, int key, float oldV) { + if (MSG_ReadBits(msg, 1)) { byteAlias_t fi; - fi.i = MSG_ReadBits( msg, 32 ) ^ key; + fi.i = MSG_ReadBits(msg, 32) ^ key; return fi.f; } return oldV; } - /* ============================================================================ @@ -716,44 +689,36 @@ usercmd_t communication MSG_WriteDeltaUsercmdKey ===================== */ -void MSG_WriteDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to ) { - if ( to->serverTime - from->serverTime < 256 ) { - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, to->serverTime - from->serverTime, 8 ); +void MSG_WriteDeltaUsercmdKey(msg_t *msg, int key, usercmd_t *from, usercmd_t *to) { + if (to->serverTime - from->serverTime < 256) { + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, to->serverTime - from->serverTime, 8); } else { - MSG_WriteBits( msg, 0, 1 ); - MSG_WriteBits( msg, to->serverTime, 32 ); - } - if (from->angles[0] == to->angles[0] && - from->angles[1] == to->angles[1] && - from->angles[2] == to->angles[2] && - from->forwardmove == to->forwardmove && - from->rightmove == to->rightmove && - from->upmove == to->upmove && - from->buttons == to->buttons && - from->weapon == to->weapon && - from->forcesel == to->forcesel && - from->invensel == to->invensel && - from->generic_cmd == to->generic_cmd) { - MSG_WriteBits( msg, 0, 1 ); // no change - oldsize += 7; - return; + MSG_WriteBits(msg, 0, 1); + MSG_WriteBits(msg, to->serverTime, 32); + } + if (from->angles[0] == to->angles[0] && from->angles[1] == to->angles[1] && from->angles[2] == to->angles[2] && from->forwardmove == to->forwardmove && + from->rightmove == to->rightmove && from->upmove == to->upmove && from->buttons == to->buttons && from->weapon == to->weapon && + from->forcesel == to->forcesel && from->invensel == to->invensel && from->generic_cmd == to->generic_cmd) { + MSG_WriteBits(msg, 0, 1); // no change + oldsize += 7; + return; } key ^= to->serverTime; - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteDeltaKey( msg, key, from->angles[0], to->angles[0], 16 ); - MSG_WriteDeltaKey( msg, key, from->angles[1], to->angles[1], 16 ); - MSG_WriteDeltaKey( msg, key, from->angles[2], to->angles[2], 16 ); - MSG_WriteDeltaKey( msg, key, from->forwardmove, to->forwardmove, 8 ); - MSG_WriteDeltaKey( msg, key, from->rightmove, to->rightmove, 8 ); - MSG_WriteDeltaKey( msg, key, from->upmove, to->upmove, 8 ); - MSG_WriteDeltaKey( msg, key, from->buttons, to->buttons, 16 ); - MSG_WriteDeltaKey( msg, key, from->weapon, to->weapon, 8 ); - - MSG_WriteDeltaKey( msg, key, from->forcesel, to->forcesel, 8 ); - MSG_WriteDeltaKey( msg, key, from->invensel, to->invensel, 8 ); - - MSG_WriteDeltaKey( msg, key, from->generic_cmd, to->generic_cmd, 8 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteDeltaKey(msg, key, from->angles[0], to->angles[0], 16); + MSG_WriteDeltaKey(msg, key, from->angles[1], to->angles[1], 16); + MSG_WriteDeltaKey(msg, key, from->angles[2], to->angles[2], 16); + MSG_WriteDeltaKey(msg, key, from->forwardmove, to->forwardmove, 8); + MSG_WriteDeltaKey(msg, key, from->rightmove, to->rightmove, 8); + MSG_WriteDeltaKey(msg, key, from->upmove, to->upmove, 8); + MSG_WriteDeltaKey(msg, key, from->buttons, to->buttons, 16); + MSG_WriteDeltaKey(msg, key, from->weapon, to->weapon, 8); + + MSG_WriteDeltaKey(msg, key, from->forcesel, to->forcesel, 8); + MSG_WriteDeltaKey(msg, key, from->invensel, to->invensel, 8); + + MSG_WriteDeltaKey(msg, key, from->generic_cmd, to->generic_cmd, 8); } /* @@ -761,33 +726,33 @@ void MSG_WriteDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t * MSG_ReadDeltaUsercmdKey ===================== */ -void MSG_ReadDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to ) { - if ( MSG_ReadBits( msg, 1 ) ) { - to->serverTime = from->serverTime + MSG_ReadBits( msg, 8 ); +void MSG_ReadDeltaUsercmdKey(msg_t *msg, int key, usercmd_t *from, usercmd_t *to) { + if (MSG_ReadBits(msg, 1)) { + to->serverTime = from->serverTime + MSG_ReadBits(msg, 8); } else { - to->serverTime = MSG_ReadBits( msg, 32 ); + to->serverTime = MSG_ReadBits(msg, 32); } - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { key ^= to->serverTime; - to->angles[0] = MSG_ReadDeltaKey( msg, key, from->angles[0], 16); - to->angles[1] = MSG_ReadDeltaKey( msg, key, from->angles[1], 16); - to->angles[2] = MSG_ReadDeltaKey( msg, key, from->angles[2], 16); - to->forwardmove = MSG_ReadDeltaKey( msg, key, from->forwardmove, 8); - if( to->forwardmove == -128 ) + to->angles[0] = MSG_ReadDeltaKey(msg, key, from->angles[0], 16); + to->angles[1] = MSG_ReadDeltaKey(msg, key, from->angles[1], 16); + to->angles[2] = MSG_ReadDeltaKey(msg, key, from->angles[2], 16); + to->forwardmove = MSG_ReadDeltaKey(msg, key, from->forwardmove, 8); + if (to->forwardmove == -128) to->forwardmove = -127; - to->rightmove = MSG_ReadDeltaKey( msg, key, from->rightmove, 8); - if( to->rightmove == -128 ) + to->rightmove = MSG_ReadDeltaKey(msg, key, from->rightmove, 8); + if (to->rightmove == -128) to->rightmove = -127; - to->upmove = MSG_ReadDeltaKey( msg, key, from->upmove, 8); - if( to->upmove == -128 ) + to->upmove = MSG_ReadDeltaKey(msg, key, from->upmove, 8); + if (to->upmove == -128) to->upmove = -127; - to->buttons = MSG_ReadDeltaKey( msg, key, from->buttons, 16); - to->weapon = MSG_ReadDeltaKey( msg, key, from->weapon, 8); + to->buttons = MSG_ReadDeltaKey(msg, key, from->buttons, 16); + to->weapon = MSG_ReadDeltaKey(msg, key, from->weapon, 8); - to->forcesel = MSG_ReadDeltaKey( msg, key, from->forcesel, 8); - to->invensel = MSG_ReadDeltaKey( msg, key, from->invensel, 8); + to->forcesel = MSG_ReadDeltaKey(msg, key, from->forcesel, 8); + to->invensel = MSG_ReadDeltaKey(msg, key, from->invensel, 8); - to->generic_cmd = MSG_ReadDeltaKey( msg, key, from->generic_cmd, 8); + to->generic_cmd = MSG_ReadDeltaKey(msg, key, from->generic_cmd, 8); } else { to->angles[0] = from->angles[0]; to->angles[1] = from->angles[1]; @@ -813,218 +778,216 @@ entityState_t communication ============================================================================= */ - typedef struct netField_s { - const char *name; - size_t offset; - int bits; // 0 = float + const char *name; + size_t offset; + int bits; // 0 = float #ifndef FINAL_BUILD - unsigned mCount; + unsigned mCount; #endif } netField_t; // using the stringizing operator to save typing... -#define NETF(x) #x,offsetof(entityState_t, x) +#define NETF(x) #x, offsetof(entityState_t, x) -//rww - Remember to update ext_data/MP/netf_overrides.txt if you change any of this! +// rww - Remember to update ext_data/MP/netf_overrides.txt if you change any of this! //(for the sake of being consistent) -netField_t entityStateFields[] = -{ -{ NETF(pos.trTime), 32 }, -{ NETF(pos.trBase[1]), 0 }, -{ NETF(pos.trBase[0]), 0 }, -{ NETF(apos.trBase[1]), 0 }, -{ NETF(pos.trBase[2]), 0 }, -{ NETF(apos.trBase[0]), 0 }, -{ NETF(pos.trDelta[0]), 0 }, -{ NETF(pos.trDelta[1]), 0 }, -{ NETF(eType), 8 }, -{ NETF(angles[1]), 0 }, -{ NETF(pos.trDelta[2]), 0 }, -{ NETF(origin[0]), 0 }, -{ NETF(origin[1]), 0 }, -{ NETF(origin[2]), 0 }, -// does this need to be 8 bits? -{ NETF(weapon), 8 }, -{ NETF(apos.trType), 8 }, -// changed from 12 to 16 -{ NETF(legsAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -// suspicious -{ NETF(torsoAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -// large use beyond GENTITYNUM_BITS - should use generic1 insead -{ NETF(genericenemyindex), 32 }, //Do not change to GENTITYNUM_BITS, used as a time offset for seeker -{ NETF(eFlags), 32 }, -{ NETF(pos.trDuration), 32 }, -// might be able to reduce -{ NETF(teamowner), 8 }, -{ NETF(groundEntityNum), GENTITYNUM_BITS }, -{ NETF(pos.trType), 8 }, -{ NETF(angles[2]), 0 }, -{ NETF(angles[0]), 0 }, -{ NETF(solid), 24 }, -// flag states barely used - could be moved elsewhere -{ NETF(fireflag), 2 }, -{ NETF(event), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -// used mostly for players and npcs - appears to be static / never changing -{ NETF(customRGBA[3]), 8 }, //0-255 -// used mostly for players and npcs - appears to be static / never changing -{ NETF(customRGBA[0]), 8 }, //0-255 -// only used in fx system (which rick did) and chunks -{ NETF(speed), 0 }, -// why are npc's clientnum's that big? -{ NETF(clientNum), GENTITYNUM_BITS }, //with npc's clientnum can be > MAX_CLIENTS so use entnum bits now instead. -{ NETF(apos.trBase[2]), 0 }, -{ NETF(apos.trTime), 32 }, -// used mostly for players and npcs - appears to be static / never changing -{ NETF(customRGBA[1]), 8 }, //0-255 -// used mostly for players and npcs - appears to be static / never changing -{ NETF(customRGBA[2]), 8 }, //0-255 -// multiple meanings -{ NETF(saberEntityNum), GENTITYNUM_BITS }, -// could probably just eliminate and assume a big number -{ NETF(g2radius), 8 }, -{ NETF(otherEntityNum2), GENTITYNUM_BITS }, -// used all over the place -{ NETF(owner), GENTITYNUM_BITS }, -{ NETF(modelindex2), 8 }, -// why was this changed from 0 to 8 ? -{ NETF(eventParm), 8 }, -// unknown about size? -{ NETF(saberMove), 8 }, -{ NETF(apos.trDelta[1]), 0 }, -{ NETF(boneAngles1[1]), 0 }, -// why raised from 8 to -16? -{ NETF(modelindex), -16 }, -// barely used, could probably be replaced -{ NETF(emplacedOwner), 32 }, //As above, also used as a time value (for electricity render time) -{ NETF(apos.trDelta[0]), 0 }, -{ NETF(apos.trDelta[2]), 0 }, -// shouldn't these be better off as flags? otherwise, they may consume more bits this way -{ NETF(torsoFlip), 1 }, -{ NETF(angles2[1]), 0 }, -// used mostly in saber and npc -{ NETF(lookTarget), GENTITYNUM_BITS }, -{ NETF(origin2[2]), 0 }, -// randomly used, not sure why this was used instead of svc_noclient -// if (cent->currentState.modelGhoul2 == 127) -// { //not ready to be drawn or initialized.. -// return; -// } -{ NETF(modelGhoul2), 8 }, -{ NETF(loopSound), 8 }, -{ NETF(origin2[0]), 0 }, -// multiple purpose bit flag -{ NETF(shouldtarget), 1 }, -// widely used, does not appear that they have to be 16 bits -{ NETF(trickedentindex), 16 }, //See note in PSF -{ NETF(otherEntityNum), GENTITYNUM_BITS }, -{ NETF(origin2[1]), 0 }, -{ NETF(time2), 32 }, -{ NETF(legsFlip), 1 }, -// fully used -{ NETF(bolt2), GENTITYNUM_BITS }, -{ NETF(constantLight), 32 }, -{ NETF(time), 32 }, -// why doesn't lookTarget just indicate this? -{ NETF(hasLookTarget), 1 }, -{ NETF(boneAngles1[2]), 0 }, -// used for both force pass and an emplaced gun - gun is just a flag indicator -{ NETF(activeForcePass), 6 }, -// used to indicate health -{ NETF(health), 10 }, //if something's health exceeds 1024, then.. too bad! -// appears to have multiple means, could be eliminated by indicating a sound set differently -{ NETF(loopIsSoundset), 1 }, -{ NETF(saberHolstered), 2 }, -//NPC-SPECIFIC: -// both are used for NPCs sabers, though limited -{ NETF(npcSaber1), 9 }, -{ NETF(maxhealth), 10 }, -{ NETF(trickedentindex2), 16 }, -// appear to only be 18 powers? -{ NETF(forcePowersActive), 32 }, -// used, doesn't appear to be flexible -{ NETF(iModelScale), 10 }, //0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) -// full bits used -{ NETF(powerups), MAX_POWERUPS }, -// can this be reduced? -{ NETF(soundSetIndex), 8 }, //rww - if MAX_AMBIENT_SETS is changed from 256, REMEMBER TO CHANGE THIS -// looks like this can be reduced to 4? (ship parts = 4, people parts = 2) -{ NETF(brokenLimbs), 8 }, //up to 8 limbs at once (not that that many are used) -{ NETF(csSounds_Std), 8 }, //soundindex must be 8 unless max sounds is changed -// used extensively -{ NETF(saberInFlight), 1 }, -{ NETF(angles2[0]), 0 }, -{ NETF(frame), 16 }, -{ NETF(angles2[2]), 0 }, -// why not use torsoAnim and set a flag to do the same thing as forceFrame (saberLockFrame) -{ NETF(forceFrame), 16 }, //if you have over 65536 frames, then this will explode. Of course if you have that many things then lots of things will probably explode. -{ NETF(generic1), 8 }, -// do we really need 4 indexes? -{ NETF(boneIndex1), 6 }, //up to 64 bones can be accessed by this indexing method -// only 54 classes, could cut down 2 bits -{ NETF(NPC_class), 8 }, -{ NETF(apos.trDuration), 32 }, -// there appears to be only 2 different version of parms passed - a flag would better be suited -{ NETF(boneOrient), 9 }, //3 bits per orientation dir -// this looks to be a single bit flag -{ NETF(bolt1), 8 }, -{ NETF(trickedentindex3), 16 }, -// in use for vehicles -{ NETF(m_iVehicleNum), GENTITYNUM_BITS }, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis -{ NETF(trickedentindex4), 16 }, -// but why is there an opposite state of surfaces field? -{ NETF(surfacesOff), 32 }, -{ NETF(eFlags2), 10 }, -// should be bit field -{ NETF(isJediMaster), 1 }, -// should be bit field -{ NETF(isPortalEnt), 1 }, -// possible multiple definitions -{ NETF(heldByClient), 6 }, -// this does not appear to be used in any production or non-cheat fashion - REMOVE -{ NETF(ragAttach), GENTITYNUM_BITS }, -// used only in one spot for seige -{ NETF(boltToPlayer), 6 }, -{ NETF(npcSaber2), 9 }, -{ NETF(csSounds_Combat), 8 }, -{ NETF(csSounds_Extra), 8 }, -{ NETF(csSounds_Jedi), 8 }, -// used only for surfaces on NPCs -{ NETF(surfacesOn), 32 }, //allow up to 32 surfaces in the bitflag -{ NETF(boneIndex2), 6 }, -{ NETF(boneIndex3), 6 }, -{ NETF(boneIndex4), 6 }, -{ NETF(boneAngles1[0]), 0 }, -{ NETF(boneAngles2[0]), 0 }, -{ NETF(boneAngles2[1]), 0 }, -{ NETF(boneAngles2[2]), 0 }, -{ NETF(boneAngles3[0]), 0 }, -{ NETF(boneAngles3[1]), 0 }, -{ NETF(boneAngles3[2]), 0 }, -{ NETF(boneAngles4[0]), 0 }, -{ NETF(boneAngles4[1]), 0 }, -{ NETF(boneAngles4[2]), 0 }, - -//rww - for use by mod authors only -{ NETF(userInt1), 1 }, -{ NETF(userInt2), 1 }, -{ NETF(userInt3), 1 }, -{ NETF(userFloat1), 1 }, -{ NETF(userFloat2), 1 }, -{ NETF(userFloat3), 1 }, -{ NETF(userVec1[0]), 1 }, -{ NETF(userVec1[1]), 1 }, -{ NETF(userVec1[2]), 1 }, -{ NETF(userVec2[0]), 1 }, -{ NETF(userVec2[1]), 1 }, -{ NETF(userVec2[2]), 1 } -}; +netField_t entityStateFields[] = { + {NETF(pos.trTime), 32}, + {NETF(pos.trBase[1]), 0}, + {NETF(pos.trBase[0]), 0}, + {NETF(apos.trBase[1]), 0}, + {NETF(pos.trBase[2]), 0}, + {NETF(apos.trBase[0]), 0}, + {NETF(pos.trDelta[0]), 0}, + {NETF(pos.trDelta[1]), 0}, + {NETF(eType), 8}, + {NETF(angles[1]), 0}, + {NETF(pos.trDelta[2]), 0}, + {NETF(origin[0]), 0}, + {NETF(origin[1]), 0}, + {NETF(origin[2]), 0}, + // does this need to be 8 bits? + {NETF(weapon), 8}, + {NETF(apos.trType), 8}, + // changed from 12 to 16 + {NETF(legsAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + // suspicious + {NETF(torsoAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + // large use beyond GENTITYNUM_BITS - should use generic1 insead + {NETF(genericenemyindex), 32}, // Do not change to GENTITYNUM_BITS, used as a time offset for seeker + {NETF(eFlags), 32}, + {NETF(pos.trDuration), 32}, + // might be able to reduce + {NETF(teamowner), 8}, + {NETF(groundEntityNum), GENTITYNUM_BITS}, + {NETF(pos.trType), 8}, + {NETF(angles[2]), 0}, + {NETF(angles[0]), 0}, + {NETF(solid), 24}, + // flag states barely used - could be moved elsewhere + {NETF(fireflag), 2}, + {NETF(event), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + // used mostly for players and npcs - appears to be static / never changing + {NETF(customRGBA[3]), 8}, // 0-255 + // used mostly for players and npcs - appears to be static / never changing + {NETF(customRGBA[0]), 8}, // 0-255 + // only used in fx system (which rick did) and chunks + {NETF(speed), 0}, + // why are npc's clientnum's that big? + {NETF(clientNum), GENTITYNUM_BITS}, // with npc's clientnum can be > MAX_CLIENTS so use entnum bits now instead. + {NETF(apos.trBase[2]), 0}, + {NETF(apos.trTime), 32}, + // used mostly for players and npcs - appears to be static / never changing + {NETF(customRGBA[1]), 8}, // 0-255 + // used mostly for players and npcs - appears to be static / never changing + {NETF(customRGBA[2]), 8}, // 0-255 + // multiple meanings + {NETF(saberEntityNum), GENTITYNUM_BITS}, + // could probably just eliminate and assume a big number + {NETF(g2radius), 8}, + {NETF(otherEntityNum2), GENTITYNUM_BITS}, + // used all over the place + {NETF(owner), GENTITYNUM_BITS}, + {NETF(modelindex2), 8}, + // why was this changed from 0 to 8 ? + {NETF(eventParm), 8}, + // unknown about size? + {NETF(saberMove), 8}, + {NETF(apos.trDelta[1]), 0}, + {NETF(boneAngles1[1]), 0}, + // why raised from 8 to -16? + {NETF(modelindex), -16}, + // barely used, could probably be replaced + {NETF(emplacedOwner), 32}, // As above, also used as a time value (for electricity render time) + {NETF(apos.trDelta[0]), 0}, + {NETF(apos.trDelta[2]), 0}, + // shouldn't these be better off as flags? otherwise, they may consume more bits this way + {NETF(torsoFlip), 1}, + {NETF(angles2[1]), 0}, + // used mostly in saber and npc + {NETF(lookTarget), GENTITYNUM_BITS}, + {NETF(origin2[2]), 0}, + // randomly used, not sure why this was used instead of svc_noclient + // if (cent->currentState.modelGhoul2 == 127) + // { //not ready to be drawn or initialized.. + // return; + // } + {NETF(modelGhoul2), 8}, + {NETF(loopSound), 8}, + {NETF(origin2[0]), 0}, + // multiple purpose bit flag + {NETF(shouldtarget), 1}, + // widely used, does not appear that they have to be 16 bits + {NETF(trickedentindex), 16}, // See note in PSF + {NETF(otherEntityNum), GENTITYNUM_BITS}, + {NETF(origin2[1]), 0}, + {NETF(time2), 32}, + {NETF(legsFlip), 1}, + // fully used + {NETF(bolt2), GENTITYNUM_BITS}, + {NETF(constantLight), 32}, + {NETF(time), 32}, + // why doesn't lookTarget just indicate this? + {NETF(hasLookTarget), 1}, + {NETF(boneAngles1[2]), 0}, + // used for both force pass and an emplaced gun - gun is just a flag indicator + {NETF(activeForcePass), 6}, + // used to indicate health + {NETF(health), 10}, // if something's health exceeds 1024, then.. too bad! + // appears to have multiple means, could be eliminated by indicating a sound set differently + {NETF(loopIsSoundset), 1}, + {NETF(saberHolstered), 2}, + // NPC-SPECIFIC: + // both are used for NPCs sabers, though limited + {NETF(npcSaber1), 9}, + {NETF(maxhealth), 10}, + {NETF(trickedentindex2), 16}, + // appear to only be 18 powers? + {NETF(forcePowersActive), 32}, + // used, doesn't appear to be flexible + {NETF(iModelScale), 10}, // 0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) + // full bits used + {NETF(powerups), MAX_POWERUPS}, + // can this be reduced? + {NETF(soundSetIndex), 8}, // rww - if MAX_AMBIENT_SETS is changed from 256, REMEMBER TO CHANGE THIS + // looks like this can be reduced to 4? (ship parts = 4, people parts = 2) + {NETF(brokenLimbs), 8}, // up to 8 limbs at once (not that that many are used) + {NETF(csSounds_Std), 8}, // soundindex must be 8 unless max sounds is changed + // used extensively + {NETF(saberInFlight), 1}, + {NETF(angles2[0]), 0}, + {NETF(frame), 16}, + {NETF(angles2[2]), 0}, + // why not use torsoAnim and set a flag to do the same thing as forceFrame (saberLockFrame) + {NETF(forceFrame), + 16}, // if you have over 65536 frames, then this will explode. Of course if you have that many things then lots of things will probably explode. + {NETF(generic1), 8}, + // do we really need 4 indexes? + {NETF(boneIndex1), 6}, // up to 64 bones can be accessed by this indexing method + // only 54 classes, could cut down 2 bits + {NETF(NPC_class), 8}, + {NETF(apos.trDuration), 32}, + // there appears to be only 2 different version of parms passed - a flag would better be suited + {NETF(boneOrient), 9}, // 3 bits per orientation dir + // this looks to be a single bit flag + {NETF(bolt1), 8}, + {NETF(trickedentindex3), 16}, + // in use for vehicles + {NETF(m_iVehicleNum), GENTITYNUM_BITS}, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis + {NETF(trickedentindex4), 16}, + // but why is there an opposite state of surfaces field? + {NETF(surfacesOff), 32}, + {NETF(eFlags2), 10}, + // should be bit field + {NETF(isJediMaster), 1}, + // should be bit field + {NETF(isPortalEnt), 1}, + // possible multiple definitions + {NETF(heldByClient), 6}, + // this does not appear to be used in any production or non-cheat fashion - REMOVE + {NETF(ragAttach), GENTITYNUM_BITS}, + // used only in one spot for seige + {NETF(boltToPlayer), 6}, + {NETF(npcSaber2), 9}, + {NETF(csSounds_Combat), 8}, + {NETF(csSounds_Extra), 8}, + {NETF(csSounds_Jedi), 8}, + // used only for surfaces on NPCs + {NETF(surfacesOn), 32}, // allow up to 32 surfaces in the bitflag + {NETF(boneIndex2), 6}, + {NETF(boneIndex3), 6}, + {NETF(boneIndex4), 6}, + {NETF(boneAngles1[0]), 0}, + {NETF(boneAngles2[0]), 0}, + {NETF(boneAngles2[1]), 0}, + {NETF(boneAngles2[2]), 0}, + {NETF(boneAngles3[0]), 0}, + {NETF(boneAngles3[1]), 0}, + {NETF(boneAngles3[2]), 0}, + {NETF(boneAngles4[0]), 0}, + {NETF(boneAngles4[1]), 0}, + {NETF(boneAngles4[2]), 0}, + + // rww - for use by mod authors only + {NETF(userInt1), 1}, + {NETF(userInt2), 1}, + {NETF(userInt3), 1}, + {NETF(userFloat1), 1}, + {NETF(userFloat2), 1}, + {NETF(userFloat3), 1}, + {NETF(userVec1[0]), 1}, + {NETF(userVec1[1]), 1}, + {NETF(userVec1[2]), 1}, + {NETF(userVec2[0]), 1}, + {NETF(userVec2[1]), 1}, + {NETF(userVec2[2]), 1}}; // if (int)f == f and (int)f + ( 1<<(FLOAT_INT_BITS-1) ) < ( 1 << FLOAT_INT_BITS ) // the float will be sent with FLOAT_INT_BITS, otherwise all 32 bits will be sent -#define FLOAT_INT_BITS 13 -#define FLOAT_INT_BIAS (1<<(FLOAT_INT_BITS-1)) +#define FLOAT_INT_BITS 13 +#define FLOAT_INT_BIAS (1 << (FLOAT_INT_BITS - 1)) /* ================== @@ -1037,109 +1000,107 @@ If force is not set, then nothing at all will be generated if the entity is identical, under the assumption that the in-order delta code will catch it. ================== */ -void MSG_WriteDeltaEntity( msg_t *msg, struct entityState_s *from, struct entityState_s *to, - qboolean force ) { - int i, lc; - int numFields; - netField_t *field; - int trunc; - float fullFloat; - int *fromF, *toF; +void MSG_WriteDeltaEntity(msg_t *msg, struct entityState_s *from, struct entityState_s *to, qboolean force) { + int i, lc; + int numFields; + netField_t *field; + int trunc; + float fullFloat; + int *fromF, *toF; - numFields = (int)ARRAY_LEN( entityStateFields ); + numFields = (int)ARRAY_LEN(entityStateFields); // all fields should be 32 bits to avoid any compiler packing issues // the "number" field is not part of the field list // if this assert fails, someone added a field to the entityState_t // struct without updating the message fields - assert( numFields + 1 == sizeof( *from )/4 ); + assert(numFields + 1 == sizeof(*from) / 4); // a NULL to is a delta remove message - if ( to == NULL ) { - if ( from == NULL ) { + if (to == NULL) { + if (from == NULL) { return; } - MSG_WriteBits( msg, from->number, GENTITYNUM_BITS ); - MSG_WriteBits( msg, 1, 1 ); + MSG_WriteBits(msg, from->number, GENTITYNUM_BITS); + MSG_WriteBits(msg, 1, 1); return; } - if ( to->number < 0 || to->number >= MAX_GENTITIES ) { - Com_Error (ERR_FATAL, "MSG_WriteDeltaEntity: Bad entity number: %i", to->number ); + if (to->number < 0 || to->number >= MAX_GENTITIES) { + Com_Error(ERR_FATAL, "MSG_WriteDeltaEntity: Bad entity number: %i", to->number); } lc = 0; // build the change vector as bytes so it is endian independent - for ( i = 0, field = entityStateFields ; i < numFields ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); - if ( *fromF != *toF ) { - lc = i+1; + for (i = 0, field = entityStateFields; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); + if (*fromF != *toF) { + lc = i + 1; #ifndef FINAL_BUILD field->mCount++; #endif } } - if ( lc == 0 ) { + if (lc == 0) { // nothing at all changed - if ( !force ) { - return; // nothing at all + if (!force) { + return; // nothing at all } // write two bits for no change - MSG_WriteBits( msg, to->number, GENTITYNUM_BITS ); - MSG_WriteBits( msg, 0, 1 ); // not removed - MSG_WriteBits( msg, 0, 1 ); // no delta + MSG_WriteBits(msg, to->number, GENTITYNUM_BITS); + MSG_WriteBits(msg, 0, 1); // not removed + MSG_WriteBits(msg, 0, 1); // no delta return; } - MSG_WriteBits( msg, to->number, GENTITYNUM_BITS ); - MSG_WriteBits( msg, 0, 1 ); // not removed - MSG_WriteBits( msg, 1, 1 ); // we have a delta + MSG_WriteBits(msg, to->number, GENTITYNUM_BITS); + MSG_WriteBits(msg, 0, 1); // not removed + MSG_WriteBits(msg, 1, 1); // we have a delta - MSG_WriteByte( msg, lc ); // # of changes + MSG_WriteByte(msg, lc); // # of changes oldsize += numFields; - for ( i = 0, field = entityStateFields ; i < lc ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = 0, field = entityStateFields; i < lc; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); - if ( *fromF == *toF ) { - MSG_WriteBits( msg, 0, 1 ); // no change + if (*fromF == *toF) { + MSG_WriteBits(msg, 0, 1); // no change continue; } - MSG_WriteBits( msg, 1, 1 ); // changed + MSG_WriteBits(msg, 1, 1); // changed - if ( field->bits == 0 ) { + if (field->bits == 0) { // float fullFloat = *(float *)toF; trunc = (int)fullFloat; if (fullFloat == 0.0f) { - MSG_WriteBits( msg, 0, 1 ); - oldsize += FLOAT_INT_BITS; + MSG_WriteBits(msg, 0, 1); + oldsize += FLOAT_INT_BITS; } else { - MSG_WriteBits( msg, 1, 1 ); - if ( trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && - trunc + FLOAT_INT_BIAS < ( 1 << FLOAT_INT_BITS ) ) { + MSG_WriteBits(msg, 1, 1); + if (trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && trunc + FLOAT_INT_BIAS < (1 << FLOAT_INT_BITS)) { // send as small integer - MSG_WriteBits( msg, 0, 1 ); - MSG_WriteBits( msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS ); + MSG_WriteBits(msg, 0, 1); + MSG_WriteBits(msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS); } else { // send as full floating point value - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, *toF, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, *toF, 32); } } } else { if (*toF == 0) { - MSG_WriteBits( msg, 0, 1 ); + MSG_WriteBits(msg, 0, 1); } else { - MSG_WriteBits( msg, 1, 1 ); + MSG_WriteBits(msg, 1, 1); // integer - MSG_WriteBits( msg, *toF, field->bits ); + MSG_WriteBits(msg, *toF, field->bits); } } } @@ -1158,38 +1119,37 @@ Can go from either a baseline or a previous packet_entity ================== */ -void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to, - int number) { - int i, lc; - int numFields; - netField_t *field; - int *fromF, *toF; - int print; - int trunc; - int startBit, endBit; +void MSG_ReadDeltaEntity(msg_t *msg, entityState_t *from, entityState_t *to, int number) { + int i, lc; + int numFields; + netField_t *field; + int *fromF, *toF; + int print; + int trunc; + int startBit, endBit; - if ( number < 0 || number >= MAX_GENTITIES) { - Com_Error( ERR_DROP, "Bad delta entity number: %i", number ); + if (number < 0 || number >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "Bad delta entity number: %i", number); } - if ( msg->bit == 0 ) { + if (msg->bit == 0) { startBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - startBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + startBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } // check for a remove - if ( MSG_ReadBits( msg, 1 ) == 1 ) { - Com_Memset( to, 0, sizeof( *to ) ); + if (MSG_ReadBits(msg, 1) == 1) { + Com_Memset(to, 0, sizeof(*to)); to->number = MAX_GENTITIES - 1; - if ( cl_shownet && ( cl_shownet->integer >= 2 || cl_shownet->integer == -1 ) ) { - Com_Printf( "%3i: #%-3i remove\n", msg->readcount, number ); + if (cl_shownet && (cl_shownet->integer >= 2 || cl_shownet->integer == -1)) { + Com_Printf("%3i: #%-3i remove\n", msg->readcount, number); } return; } // check for no delta - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { *to = *from; to->number = number; return; @@ -1198,20 +1158,17 @@ void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to, numFields = (int)ARRAY_LEN(entityStateFields); lc = MSG_ReadByte(msg); - if ( lc > numFields || lc < 0 ) - Com_Error( ERR_DROP, "invalid entityState field count (got: %i, expecting: %i)", lc, numFields ); + if (lc > numFields || lc < 0) + Com_Error(ERR_DROP, "invalid entityState field count (got: %i, expecting: %i)", lc, numFields); // shownet 2/3 will interleave with other printed info, -1 will // just print the delta records` - if ( cl_shownet && ( cl_shownet->integer >= 2 || cl_shownet->integer == -1 ) ) { + if (cl_shownet && (cl_shownet->integer >= 2 || cl_shownet->integer == -1)) { print = 1; - if (sv.state) - { - Com_Printf( "%3i: #%-3i (%s) ", msg->readcount, number, SV_GentityNum(number)->classname ); - } - else - { - Com_Printf( "%3i: #%-3i ", msg->readcount, number ); + if (sv.state) { + Com_Printf("%3i: #%-3i (%s) ", msg->readcount, number, SV_GentityNum(number)->classname); + } else { + Com_Printf("%3i: #%-3i ", msg->readcount, number); } } else { print = 0; @@ -1219,63 +1176,63 @@ void MSG_ReadDeltaEntity( msg_t *msg, entityState_t *from, entityState_t *to, to->number = number; - for ( i = 0, field = entityStateFields ; i < lc ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = 0, field = entityStateFields; i < lc; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); - if ( ! MSG_ReadBits( msg, 1 ) ) { + if (!MSG_ReadBits(msg, 1)) { // no change *toF = *fromF; } else { - if ( field->bits == 0 ) { + if (field->bits == 0) { // float - if ( MSG_ReadBits( msg, 1 ) == 0 ) { - *(float *)toF = 0.0f; + if (MSG_ReadBits(msg, 1) == 0) { + *(float *)toF = 0.0f; } else { - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { // integral float - trunc = MSG_ReadBits( msg, FLOAT_INT_BITS ); + trunc = MSG_ReadBits(msg, FLOAT_INT_BITS); // bias to allow equal parts positive and negative trunc -= FLOAT_INT_BIAS; *(float *)toF = trunc; - if ( print ) { - Com_Printf( "%s:%i ", field->name, trunc ); + if (print) { + Com_Printf("%s:%i ", field->name, trunc); } } else { // full floating point value - *toF = MSG_ReadBits( msg, 32 ); - if ( print ) { - Com_Printf( "%s:%f ", field->name, *(float *)toF ); + *toF = MSG_ReadBits(msg, 32); + if (print) { + Com_Printf("%s:%f ", field->name, *(float *)toF); } } } } else { - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { *toF = 0; } else { // integer - *toF = MSG_ReadBits( msg, field->bits ); - if ( print ) { - Com_Printf( "%s:%i ", field->name, *toF ); + *toF = MSG_ReadBits(msg, field->bits); + if (print) { + Com_Printf("%s:%i ", field->name, *toF); } } } } } - for ( i = lc, field = &entityStateFields[lc] ; i < numFields ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = lc, field = &entityStateFields[lc]; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); // no change *toF = *fromF; } - if ( print ) { - if ( msg->bit == 0 ) { + if (print) { + if (msg->bit == 0) { endBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - endBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + endBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } - Com_Printf( " (%i bits)\n", endBit - startBit ); + Com_Printf(" (%i bits)\n", endBit - startBit); } } @@ -1288,607 +1245,601 @@ playerState_t communication */ // using the stringizing operator to save typing... -#define PSF(x) #x,offsetof(playerState_t, x) +#define PSF(x) #x, offsetof(playerState_t, x) -//rww - Remember to update ext_data/MP/psf_overrides.txt if you change any of this! +// rww - Remember to update ext_data/MP/psf_overrides.txt if you change any of this! //(for the sake of being consistent) //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= #ifdef _OPTIMIZED_VEHICLE_NETWORKING -//Instead of sending 2 full playerStates for the pilot and the vehicle, send a smaller, -//specialized pilot playerState and vehicle playerState. Also removes some vehicle -//fields from the normal playerState -mcg +// Instead of sending 2 full playerStates for the pilot and the vehicle, send a smaller, +// specialized pilot playerState and vehicle playerState. Also removes some vehicle +// fields from the normal playerState -mcg //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -netField_t playerStateFields[] = -{ -{ PSF(commandTime), 32 }, -{ PSF(origin[1]), 0 }, -{ PSF(origin[0]), 0 }, -{ PSF(viewangles[1]), 0 }, -{ PSF(viewangles[0]), 0 }, -{ PSF(origin[2]), 0 }, -{ PSF(velocity[0]), 0 }, -{ PSF(velocity[1]), 0 }, -{ PSF(velocity[2]), 0 }, -{ PSF(bobCycle), 8 }, -{ PSF(weaponTime), -16 }, -{ PSF(delta_angles[1]), 16 }, -{ PSF(speed), 0 }, //sadly, the vehicles require negative speed values, so.. -{ PSF(legsAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(delta_angles[0]), 16 }, -{ PSF(torsoAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(groundEntityNum), GENTITYNUM_BITS }, -{ PSF(eFlags), 32 }, -{ PSF(fd.forcePower), 8 }, -{ PSF(eventSequence), 16 }, -{ PSF(torsoTimer), 16 }, -{ PSF(legsTimer), 16 }, -{ PSF(viewheight), -8 }, -{ PSF(fd.saberAnimLevel), 4 }, -{ PSF(rocketLockIndex), GENTITYNUM_BITS }, -{ PSF(fd.saberDrawAnimLevel), 4 }, -{ PSF(genericEnemyIndex), 32 }, //NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits -{ PSF(events[0]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(events[1]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(customRGBA[0]), 8 }, //0-255 -{ PSF(movementDir), 4 }, -{ PSF(saberEntityNum), GENTITYNUM_BITS }, //Also used for channel tracker storage, but should never exceed entity number -{ PSF(customRGBA[3]), 8 }, //0-255 -{ PSF(weaponstate), 4 }, -{ PSF(saberMove), 32 }, //This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits -{ PSF(standheight), 10 }, -{ PSF(crouchheight), 10 }, -{ PSF(basespeed), -16 }, -{ PSF(pm_flags), 16 }, -{ PSF(jetpackFuel), 8 }, -{ PSF(cloakFuel), 8 }, -{ PSF(pm_time), -16 }, -{ PSF(customRGBA[1]), 8 }, //0-255 -{ PSF(clientNum), GENTITYNUM_BITS }, -{ PSF(duelIndex), GENTITYNUM_BITS }, -{ PSF(customRGBA[2]), 8 }, //0-255 -{ PSF(gravity), 16 }, -{ PSF(weapon), 8 }, -{ PSF(delta_angles[2]), 16 }, -{ PSF(saberCanThrow), 1 }, -{ PSF(viewangles[2]), 0 }, -{ PSF(fd.forcePowersKnown), 32 }, -{ PSF(fd.forcePowerLevel[FP_LEVITATION]), 2 }, //unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) -{ PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32 }, -{ PSF(fd.forcePowerSelected), 8 }, -{ PSF(torsoFlip), 1 }, -{ PSF(externalEvent), 10 }, -{ PSF(damageYaw), 8 }, -{ PSF(damageCount), 8 }, -{ PSF(inAirAnim), 1 }, //just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit -{ PSF(eventParms[1]), 8 }, -{ PSF(fd.forceSide), 2 }, //so we know if we should apply greyed out shaders to dark/light force enlightenment -{ PSF(saberAttackChainCount), 4 }, -{ PSF(pm_type), 8 }, -{ PSF(externalEventParm), 8 }, -{ PSF(eventParms[0]), -16 }, -{ PSF(lookTarget), GENTITYNUM_BITS }, -//{ PSF(vehOrientation[0]), 0 }, -{ PSF(weaponChargeSubtractTime), 32 }, //? really need 32 bits?? -//{ PSF(vehOrientation[1]), 0 }, -//{ PSF(moveDir[1]), 0 }, -//{ PSF(moveDir[0]), 0 }, -{ PSF(weaponChargeTime), 32 }, //? really need 32 bits?? -//{ PSF(vehOrientation[2]), 0 }, -{ PSF(legsFlip), 1 }, -{ PSF(damageEvent), 8 }, -//{ PSF(moveDir[2]), 0 }, -{ PSF(rocketTargetTime), 32 }, -{ PSF(activeForcePass), 6 }, -{ PSF(electrifyTime), 32 }, -{ PSF(fd.forceJumpZStart), 0 }, -{ PSF(loopSound), 16 }, //rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? -{ PSF(hasLookTarget), 1 }, -{ PSF(saberBlocked), 8 }, -{ PSF(damageType), 2 }, -{ PSF(rocketLockTime), 32 }, -{ PSF(forceHandExtend), 8 }, -{ PSF(saberHolstered), 2 }, -{ PSF(fd.forcePowersActive), 32 }, -{ PSF(damagePitch), 8 }, -{ PSF(m_iVehicleNum), GENTITYNUM_BITS }, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis -//{ PSF(vehTurnaroundTime), 32 },//only used by vehicle? -{ PSF(generic1), 8 }, -{ PSF(jumppad_ent), GENTITYNUM_BITS }, -{ PSF(hasDetPackPlanted), 1 }, -{ PSF(saberInFlight), 1 }, -{ PSF(forceDodgeAnim), 16 }, -{ PSF(zoomMode), 2 }, // NOTENOTE Are all of these necessary? -{ PSF(hackingTime), 32 }, -{ PSF(zoomTime), 32 }, // NOTENOTE Are all of these necessary? -{ PSF(brokenLimbs), 8 }, //up to 8 limbs at once (not that that many are used) -{ PSF(zoomLocked), 1 }, // NOTENOTE Are all of these necessary? -{ PSF(zoomFov), 0 }, // NOTENOTE Are all of these necessary? -{ PSF(fd.forceRageRecoveryTime), 32 }, -{ PSF(fallingToDeath), 32 }, -{ PSF(fd.forceMindtrickTargetIndex), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.forceMindtrickTargetIndex2), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -//{ PSF(vehWeaponsLinked), 1 },//only used by vehicle? -{ PSF(lastHitLoc[2]), 0 }, -//{ PSF(hyperSpaceTime), 32 },//only used by vehicle? -{ PSF(fd.forceMindtrickTargetIndex3), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(lastHitLoc[0]), 0 }, -{ PSF(eFlags2), 10 }, -{ PSF(fd.forceMindtrickTargetIndex4), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -//{ PSF(hyperSpaceAngles[1]), 0 },//only used by vehicle? -{ PSF(lastHitLoc[1]), 0 }, //currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. -//{ PSF(vehBoarding), 1 }, //only used by vehicle? not like the normal boarding value, this is a simple "1 or 0" value -{ PSF(fd.sentryDeployed), 1 }, -{ PSF(saberLockTime), 32 }, -{ PSF(saberLockFrame), 16 }, -//{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS },//only used by vehicle? -//{ PSF(vehSurfaces), 16 }, //only used by vehicle? allow up to 16 surfaces in the flag I guess -{ PSF(fd.forcePowerLevel[FP_SEE]), 2 }, //needed for knowing when to display players through walls -{ PSF(saberLockEnemy), GENTITYNUM_BITS }, -{ PSF(fd.forceGripCripple), 1 }, //should only be 0 or 1 ever -{ PSF(emplacedIndex), GENTITYNUM_BITS }, -{ PSF(holocronBits), 32 }, -{ PSF(isJediMaster), 1 }, -{ PSF(forceRestricted), 1 }, -{ PSF(trueJedi), 1 }, -{ PSF(trueNonJedi), 1 }, -{ PSF(duelTime), 32 }, -{ PSF(duelInProgress), 1 }, -{ PSF(saberLockAdvance), 1 }, -{ PSF(heldByClient), 6 }, -{ PSF(ragAttach), GENTITYNUM_BITS }, -{ PSF(iModelScale), 10 }, //0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) -{ PSF(hackingBaseTime), 16 }, //up to 65536ms, over 10 seconds would just be silly anyway -//{ PSF(hyperSpaceAngles[0]), 0 },//only used by vehicle? -//{ PSF(hyperSpaceAngles[2]), 0 },//only used by vehicle? - -//rww - for use by mod authors only -{ PSF(userInt1), 1 }, -{ PSF(userInt2), 1 }, -{ PSF(userInt3), 1 }, -{ PSF(userFloat1), 1 }, -{ PSF(userFloat2), 1 }, -{ PSF(userFloat3), 1 }, -{ PSF(userVec1[0]), 1 }, -{ PSF(userVec1[1]), 1 }, -{ PSF(userVec1[2]), 1 }, -{ PSF(userVec2[0]), 1 }, -{ PSF(userVec2[1]), 1 }, -{ PSF(userVec2[2]), 1 } -}; - -netField_t pilotPlayerStateFields[] = -{ -{ PSF(commandTime), 32 }, -{ PSF(origin[1]), 0 }, -{ PSF(origin[0]), 0 }, -{ PSF(viewangles[1]), 0 }, -{ PSF(viewangles[0]), 0 }, -{ PSF(origin[2]), 0 }, -{ PSF(weaponTime), -16 }, -{ PSF(delta_angles[1]), 16 }, -{ PSF(delta_angles[0]), 16 }, -{ PSF(eFlags), 32 }, -{ PSF(eventSequence), 16 }, -{ PSF(rocketLockIndex), GENTITYNUM_BITS }, -{ PSF(events[0]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(events[1]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(weaponstate), 4 }, -{ PSF(pm_flags), 16 }, -{ PSF(pm_time), -16 }, -{ PSF(clientNum), GENTITYNUM_BITS }, -{ PSF(weapon), 8 }, -{ PSF(delta_angles[2]), 16 }, -{ PSF(viewangles[2]), 0 }, -{ PSF(externalEvent), 10 }, -{ PSF(eventParms[1]), 8 }, -{ PSF(pm_type), 8 }, -{ PSF(externalEventParm), 8 }, -{ PSF(eventParms[0]), -16 }, -{ PSF(weaponChargeSubtractTime), 32 }, //? really need 32 bits?? -{ PSF(weaponChargeTime), 32 }, //? really need 32 bits?? -{ PSF(rocketTargetTime), 32 }, -{ PSF(fd.forceJumpZStart), 0 }, -{ PSF(rocketLockTime), 32 }, -{ PSF(m_iVehicleNum), GENTITYNUM_BITS }, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis -{ PSF(generic1), 8 },//used by passengers -{ PSF(eFlags2), 10 }, - -//===THESE SHOULD NOT BE CHANGING OFTEN==================================================================== -{ PSF(legsAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(torsoAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(torsoTimer), 16 }, -{ PSF(legsTimer), 16 }, -{ PSF(jetpackFuel), 8 }, -{ PSF(cloakFuel), 8 }, -{ PSF(saberCanThrow), 1 }, -{ PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32 }, -{ PSF(torsoFlip), 1 }, -{ PSF(legsFlip), 1 }, -{ PSF(fd.forcePowersActive), 32 }, -{ PSF(hasDetPackPlanted), 1 }, -{ PSF(fd.forceRageRecoveryTime), 32 }, -{ PSF(saberInFlight), 1 }, -{ PSF(fd.forceMindtrickTargetIndex), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.forceMindtrickTargetIndex2), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.forceMindtrickTargetIndex3), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.forceMindtrickTargetIndex4), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.sentryDeployed), 1 }, -{ PSF(fd.forcePowerLevel[FP_SEE]), 2 }, //needed for knowing when to display players through walls -{ PSF(holocronBits), 32 }, -{ PSF(fd.forcePower), 8 }, - -//===THE REST OF THESE SHOULD NOT BE RELEVANT, BUT, FOR SAFETY, INCLUDE THEM ANYWAY, JUST AT THE BOTTOM=============================================================== -{ PSF(velocity[0]), 0 }, -{ PSF(velocity[1]), 0 }, -{ PSF(velocity[2]), 0 }, -{ PSF(bobCycle), 8 }, -{ PSF(speed), 0 }, //sadly, the vehicles require negative speed values, so.. -{ PSF(groundEntityNum), GENTITYNUM_BITS }, -{ PSF(viewheight), -8 }, -{ PSF(fd.saberAnimLevel), 4 }, -{ PSF(fd.saberDrawAnimLevel), 4 }, -{ PSF(genericEnemyIndex), 32 }, //NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits -{ PSF(customRGBA[0]), 8 }, //0-255 -{ PSF(movementDir), 4 }, -{ PSF(saberEntityNum), GENTITYNUM_BITS }, //Also used for channel tracker storage, but should never exceed entity number -{ PSF(customRGBA[3]), 8 }, //0-255 -{ PSF(saberMove), 32 }, //This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits -{ PSF(standheight), 10 }, -{ PSF(crouchheight), 10 }, -{ PSF(basespeed), -16 }, -{ PSF(customRGBA[1]), 8 }, //0-255 -{ PSF(duelIndex), GENTITYNUM_BITS }, -{ PSF(customRGBA[2]), 8 }, //0-255 -{ PSF(gravity), 16 }, -{ PSF(fd.forcePowersKnown), 32 }, -{ PSF(fd.forcePowerLevel[FP_LEVITATION]), 2 }, //unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) -{ PSF(fd.forcePowerSelected), 8 }, -{ PSF(damageYaw), 8 }, -{ PSF(damageCount), 8 }, -{ PSF(inAirAnim), 1 }, //just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit -{ PSF(fd.forceSide), 2 }, //so we know if we should apply greyed out shaders to dark/light force enlightenment -{ PSF(saberAttackChainCount), 4 }, -{ PSF(lookTarget), GENTITYNUM_BITS }, -{ PSF(moveDir[1]), 0 }, -{ PSF(moveDir[0]), 0 }, -{ PSF(damageEvent), 8 }, -{ PSF(moveDir[2]), 0 }, -{ PSF(activeForcePass), 6 }, -{ PSF(electrifyTime), 32 }, -{ PSF(damageType), 2 }, -{ PSF(loopSound), 16 }, //rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? -{ PSF(hasLookTarget), 1 }, -{ PSF(saberBlocked), 8 }, -{ PSF(forceHandExtend), 8 }, -{ PSF(saberHolstered), 2 }, -{ PSF(damagePitch), 8 }, -{ PSF(jumppad_ent), GENTITYNUM_BITS }, -{ PSF(forceDodgeAnim), 16 }, -{ PSF(zoomMode), 2 }, // NOTENOTE Are all of these necessary? -{ PSF(hackingTime), 32 }, -{ PSF(zoomTime), 32 }, // NOTENOTE Are all of these necessary? -{ PSF(brokenLimbs), 8 }, //up to 8 limbs at once (not that that many are used) -{ PSF(zoomLocked), 1 }, // NOTENOTE Are all of these necessary? -{ PSF(zoomFov), 0 }, // NOTENOTE Are all of these necessary? -{ PSF(fallingToDeath), 32 }, -{ PSF(lastHitLoc[2]), 0 }, -{ PSF(lastHitLoc[0]), 0 }, -{ PSF(lastHitLoc[1]), 0 }, //currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. -{ PSF(saberLockTime), 32 }, -{ PSF(saberLockFrame), 16 }, -{ PSF(saberLockEnemy), GENTITYNUM_BITS }, -{ PSF(fd.forceGripCripple), 1 }, //should only be 0 or 1 ever -{ PSF(emplacedIndex), GENTITYNUM_BITS }, -{ PSF(isJediMaster), 1 }, -{ PSF(forceRestricted), 1 }, -{ PSF(trueJedi), 1 }, -{ PSF(trueNonJedi), 1 }, -{ PSF(duelTime), 32 }, -{ PSF(duelInProgress), 1 }, -{ PSF(saberLockAdvance), 1 }, -{ PSF(heldByClient), 6 }, -{ PSF(ragAttach), GENTITYNUM_BITS }, -{ PSF(iModelScale), 10 }, //0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) -{ PSF(hackingBaseTime), 16 }, //up to 65536ms, over 10 seconds would just be silly anyway -//===NEVER SEND THESE, ONLY USED BY VEHICLES============================================================== - -//{ PSF(vehOrientation[0]), 0 }, -//{ PSF(vehOrientation[1]), 0 }, -//{ PSF(vehOrientation[2]), 0 }, -//{ PSF(vehTurnaroundTime), 32 },//only used by vehicle? -//{ PSF(vehWeaponsLinked), 1 },//only used by vehicle? -//{ PSF(hyperSpaceTime), 32 },//only used by vehicle? -//{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS },//only used by vehicle? -//{ PSF(vehSurfaces), 16 }, //only used by vehicle? allow up to 16 surfaces in the flag I guess -//{ PSF(vehBoarding), 1 }, //only used by vehicle? not like the normal boarding value, this is a simple "1 or 0" value -//{ PSF(hyperSpaceAngles[1]), 0 },//only used by vehicle? -//{ PSF(hyperSpaceAngles[0]), 0 },//only used by vehicle? -//{ PSF(hyperSpaceAngles[2]), 0 },//only used by vehicle? - -//rww - for use by mod authors only -{ PSF(userInt1), 1 }, -{ PSF(userInt2), 1 }, -{ PSF(userInt3), 1 }, -{ PSF(userFloat1), 1 }, -{ PSF(userFloat2), 1 }, -{ PSF(userFloat3), 1 }, -{ PSF(userVec1[0]), 1 }, -{ PSF(userVec1[1]), 1 }, -{ PSF(userVec1[2]), 1 }, -{ PSF(userVec2[0]), 1 }, -{ PSF(userVec2[1]), 1 }, -{ PSF(userVec2[2]), 1 } -}; - -netField_t vehPlayerStateFields[] = -{ -{ PSF(commandTime), 32 }, -{ PSF(origin[1]), 0 }, -{ PSF(origin[0]), 0 }, -{ PSF(viewangles[1]), 0 }, -{ PSF(viewangles[0]), 0 }, -{ PSF(origin[2]), 0 }, -{ PSF(velocity[0]), 0 }, -{ PSF(velocity[1]), 0 }, -{ PSF(velocity[2]), 0 }, -{ PSF(weaponTime), -16 }, -{ PSF(delta_angles[1]), 16 }, -{ PSF(speed), 0 }, //sadly, the vehicles require negative speed values, so.. -{ PSF(legsAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(delta_angles[0]), 16 }, -{ PSF(groundEntityNum), GENTITYNUM_BITS }, -{ PSF(eFlags), 32 }, -{ PSF(eventSequence), 16 }, -{ PSF(legsTimer), 16 }, -{ PSF(rocketLockIndex), GENTITYNUM_BITS }, -//{ PSF(genericEnemyIndex), 32 }, //NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits -{ PSF(events[0]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(events[1]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -//{ PSF(customRGBA[0]), 8 }, //0-255 -//{ PSF(movementDir), 4 }, -//{ PSF(customRGBA[3]), 8 }, //0-255 -{ PSF(weaponstate), 4 }, -//{ PSF(basespeed), -16 }, -{ PSF(pm_flags), 16 }, -{ PSF(pm_time), -16 }, -//{ PSF(customRGBA[1]), 8 }, //0-255 -{ PSF(clientNum), GENTITYNUM_BITS }, -//{ PSF(duelIndex), GENTITYNUM_BITS }, -//{ PSF(customRGBA[2]), 8 }, //0-255 -{ PSF(gravity), 16 }, -{ PSF(weapon), 8 }, -{ PSF(delta_angles[2]), 16 }, -{ PSF(viewangles[2]), 0 }, -{ PSF(externalEvent), 10 }, -{ PSF(eventParms[1]), 8 }, -{ PSF(pm_type), 8 }, -{ PSF(externalEventParm), 8 }, -{ PSF(eventParms[0]), -16 }, -{ PSF(vehOrientation[0]), 0 }, -{ PSF(vehOrientation[1]), 0 }, -{ PSF(moveDir[1]), 0 }, -{ PSF(moveDir[0]), 0 }, -{ PSF(vehOrientation[2]), 0 }, -{ PSF(moveDir[2]), 0 }, -{ PSF(rocketTargetTime), 32 }, -//{ PSF(activeForcePass), 6 },//actually, you only need to know this for other vehicles, not your own -{ PSF(electrifyTime), 32 }, -//{ PSF(fd.forceJumpZStart), 0 },//set on rider by vehicle, but not used by vehicle -{ PSF(loopSound), 16 }, //rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? -{ PSF(rocketLockTime), 32 }, -{ PSF(m_iVehicleNum), GENTITYNUM_BITS }, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis -{ PSF(vehTurnaroundTime), 32 }, -//{ PSF(generic1), 8 },//used by passengers of vehicles, but not vehicles themselves -{ PSF(hackingTime), 32 }, -{ PSF(brokenLimbs), 8 }, //up to 8 limbs at once (not that that many are used) -{ PSF(vehWeaponsLinked), 1 }, -{ PSF(hyperSpaceTime), 32 }, -{ PSF(eFlags2), 10 }, -{ PSF(hyperSpaceAngles[1]), 0 }, -{ PSF(vehBoarding), 1 }, //not like the normal boarding value, this is a simple "1 or 0" value -{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS }, -{ PSF(vehSurfaces), 16 }, //allow up to 16 surfaces in the flag I guess -{ PSF(hyperSpaceAngles[0]), 0 }, -{ PSF(hyperSpaceAngles[2]), 0 }, - -//rww - for use by mod authors only -{ PSF(userInt1), 1 }, -{ PSF(userInt2), 1 }, -{ PSF(userInt3), 1 }, -{ PSF(userFloat1), 1 }, -{ PSF(userFloat2), 1 }, -{ PSF(userFloat3), 1 }, -{ PSF(userVec1[0]), 1 }, -{ PSF(userVec1[1]), 1 }, -{ PSF(userVec1[2]), 1 }, -{ PSF(userVec2[0]), 1 }, -{ PSF(userVec2[1]), 1 }, -{ PSF(userVec2[2]), 1 } -}; +netField_t playerStateFields[] = { + {PSF(commandTime), 32}, + {PSF(origin[1]), 0}, + {PSF(origin[0]), 0}, + {PSF(viewangles[1]), 0}, + {PSF(viewangles[0]), 0}, + {PSF(origin[2]), 0}, + {PSF(velocity[0]), 0}, + {PSF(velocity[1]), 0}, + {PSF(velocity[2]), 0}, + {PSF(bobCycle), 8}, + {PSF(weaponTime), -16}, + {PSF(delta_angles[1]), 16}, + {PSF(speed), 0}, // sadly, the vehicles require negative speed values, so.. + {PSF(legsAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(delta_angles[0]), 16}, + {PSF(torsoAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(groundEntityNum), GENTITYNUM_BITS}, + {PSF(eFlags), 32}, + {PSF(fd.forcePower), 8}, + {PSF(eventSequence), 16}, + {PSF(torsoTimer), 16}, + {PSF(legsTimer), 16}, + {PSF(viewheight), -8}, + {PSF(fd.saberAnimLevel), 4}, + {PSF(rocketLockIndex), GENTITYNUM_BITS}, + {PSF(fd.saberDrawAnimLevel), 4}, + {PSF(genericEnemyIndex), 32}, // NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits + {PSF(events[0]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(events[1]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(customRGBA[0]), 8}, // 0-255 + {PSF(movementDir), 4}, + {PSF(saberEntityNum), GENTITYNUM_BITS}, // Also used for channel tracker storage, but should never exceed entity number + {PSF(customRGBA[3]), 8}, // 0-255 + {PSF(weaponstate), 4}, + {PSF(saberMove), 32}, // This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits + {PSF(standheight), 10}, + {PSF(crouchheight), 10}, + {PSF(basespeed), -16}, + {PSF(pm_flags), 16}, + {PSF(jetpackFuel), 8}, + {PSF(cloakFuel), 8}, + {PSF(pm_time), -16}, + {PSF(customRGBA[1]), 8}, // 0-255 + {PSF(clientNum), GENTITYNUM_BITS}, + {PSF(duelIndex), GENTITYNUM_BITS}, + {PSF(customRGBA[2]), 8}, // 0-255 + {PSF(gravity), 16}, + {PSF(weapon), 8}, + {PSF(delta_angles[2]), 16}, + {PSF(saberCanThrow), 1}, + {PSF(viewangles[2]), 0}, + {PSF(fd.forcePowersKnown), 32}, + {PSF(fd.forcePowerLevel[FP_LEVITATION]), + 2}, // unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) + {PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32}, + {PSF(fd.forcePowerSelected), 8}, + {PSF(torsoFlip), 1}, + {PSF(externalEvent), 10}, + {PSF(damageYaw), 8}, + {PSF(damageCount), 8}, + {PSF(inAirAnim), 1}, // just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit + {PSF(eventParms[1]), 8}, + {PSF(fd.forceSide), 2}, // so we know if we should apply greyed out shaders to dark/light force enlightenment + {PSF(saberAttackChainCount), 4}, + {PSF(pm_type), 8}, + {PSF(externalEventParm), 8}, + {PSF(eventParms[0]), -16}, + {PSF(lookTarget), GENTITYNUM_BITS}, + //{ PSF(vehOrientation[0]), 0 }, + {PSF(weaponChargeSubtractTime), 32}, //? really need 32 bits?? + //{ PSF(vehOrientation[1]), 0 }, + //{ PSF(moveDir[1]), 0 }, + //{ PSF(moveDir[0]), 0 }, + {PSF(weaponChargeTime), 32}, //? really need 32 bits?? + //{ PSF(vehOrientation[2]), 0 }, + {PSF(legsFlip), 1}, + {PSF(damageEvent), 8}, + //{ PSF(moveDir[2]), 0 }, + {PSF(rocketTargetTime), 32}, + {PSF(activeForcePass), 6}, + {PSF(electrifyTime), 32}, + {PSF(fd.forceJumpZStart), 0}, + {PSF(loopSound), 16}, // rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? + {PSF(hasLookTarget), 1}, + {PSF(saberBlocked), 8}, + {PSF(damageType), 2}, + {PSF(rocketLockTime), 32}, + {PSF(forceHandExtend), 8}, + {PSF(saberHolstered), 2}, + {PSF(fd.forcePowersActive), 32}, + {PSF(damagePitch), 8}, + {PSF(m_iVehicleNum), GENTITYNUM_BITS}, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis + //{ PSF(vehTurnaroundTime), 32 },//only used by vehicle? + {PSF(generic1), 8}, + {PSF(jumppad_ent), GENTITYNUM_BITS}, + {PSF(hasDetPackPlanted), 1}, + {PSF(saberInFlight), 1}, + {PSF(forceDodgeAnim), 16}, + {PSF(zoomMode), 2}, // NOTENOTE Are all of these necessary? + {PSF(hackingTime), 32}, + {PSF(zoomTime), 32}, // NOTENOTE Are all of these necessary? + {PSF(brokenLimbs), 8}, // up to 8 limbs at once (not that that many are used) + {PSF(zoomLocked), 1}, // NOTENOTE Are all of these necessary? + {PSF(zoomFov), 0}, // NOTENOTE Are all of these necessary? + {PSF(fd.forceRageRecoveryTime), 32}, + {PSF(fallingToDeath), 32}, + {PSF(fd.forceMindtrickTargetIndex), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.forceMindtrickTargetIndex2), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + //{ PSF(vehWeaponsLinked), 1 },//only used by vehicle? + {PSF(lastHitLoc[2]), 0}, + //{ PSF(hyperSpaceTime), 32 },//only used by vehicle? + {PSF(fd.forceMindtrickTargetIndex3), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(lastHitLoc[0]), 0}, + {PSF(eFlags2), 10}, + {PSF(fd.forceMindtrickTargetIndex4), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + //{ PSF(hyperSpaceAngles[1]), 0 },//only used by vehicle? + {PSF(lastHitLoc[1]), 0}, // currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. + //{ PSF(vehBoarding), 1 }, //only used by vehicle? not like the normal boarding value, this is a simple "1 or 0" value + {PSF(fd.sentryDeployed), 1}, + {PSF(saberLockTime), 32}, + {PSF(saberLockFrame), 16}, + //{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS },//only used by vehicle? + //{ PSF(vehSurfaces), 16 }, //only used by vehicle? allow up to 16 surfaces in the flag I guess + {PSF(fd.forcePowerLevel[FP_SEE]), 2}, // needed for knowing when to display players through walls + {PSF(saberLockEnemy), GENTITYNUM_BITS}, + {PSF(fd.forceGripCripple), 1}, // should only be 0 or 1 ever + {PSF(emplacedIndex), GENTITYNUM_BITS}, + {PSF(holocronBits), 32}, + {PSF(isJediMaster), 1}, + {PSF(forceRestricted), 1}, + {PSF(trueJedi), 1}, + {PSF(trueNonJedi), 1}, + {PSF(duelTime), 32}, + {PSF(duelInProgress), 1}, + {PSF(saberLockAdvance), 1}, + {PSF(heldByClient), 6}, + {PSF(ragAttach), GENTITYNUM_BITS}, + {PSF(iModelScale), 10}, // 0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) + {PSF(hackingBaseTime), 16}, // up to 65536ms, over 10 seconds would just be silly anyway + //{ PSF(hyperSpaceAngles[0]), 0 },//only used by vehicle? + //{ PSF(hyperSpaceAngles[2]), 0 },//only used by vehicle? + + // rww - for use by mod authors only + {PSF(userInt1), 1}, + {PSF(userInt2), 1}, + {PSF(userInt3), 1}, + {PSF(userFloat1), 1}, + {PSF(userFloat2), 1}, + {PSF(userFloat3), 1}, + {PSF(userVec1[0]), 1}, + {PSF(userVec1[1]), 1}, + {PSF(userVec1[2]), 1}, + {PSF(userVec2[0]), 1}, + {PSF(userVec2[1]), 1}, + {PSF(userVec2[2]), 1}}; + +netField_t pilotPlayerStateFields[] = { + {PSF(commandTime), 32}, + {PSF(origin[1]), 0}, + {PSF(origin[0]), 0}, + {PSF(viewangles[1]), 0}, + {PSF(viewangles[0]), 0}, + {PSF(origin[2]), 0}, + {PSF(weaponTime), -16}, + {PSF(delta_angles[1]), 16}, + {PSF(delta_angles[0]), 16}, + {PSF(eFlags), 32}, + {PSF(eventSequence), 16}, + {PSF(rocketLockIndex), GENTITYNUM_BITS}, + {PSF(events[0]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(events[1]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(weaponstate), 4}, + {PSF(pm_flags), 16}, + {PSF(pm_time), -16}, + {PSF(clientNum), GENTITYNUM_BITS}, + {PSF(weapon), 8}, + {PSF(delta_angles[2]), 16}, + {PSF(viewangles[2]), 0}, + {PSF(externalEvent), 10}, + {PSF(eventParms[1]), 8}, + {PSF(pm_type), 8}, + {PSF(externalEventParm), 8}, + {PSF(eventParms[0]), -16}, + {PSF(weaponChargeSubtractTime), 32}, //? really need 32 bits?? + {PSF(weaponChargeTime), 32}, //? really need 32 bits?? + {PSF(rocketTargetTime), 32}, + {PSF(fd.forceJumpZStart), 0}, + {PSF(rocketLockTime), 32}, + {PSF(m_iVehicleNum), GENTITYNUM_BITS}, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis + {PSF(generic1), 8}, // used by passengers + {PSF(eFlags2), 10}, + + //===THESE SHOULD NOT BE CHANGING OFTEN==================================================================== + {PSF(legsAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(torsoAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(torsoTimer), 16}, + {PSF(legsTimer), 16}, + {PSF(jetpackFuel), 8}, + {PSF(cloakFuel), 8}, + {PSF(saberCanThrow), 1}, + {PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32}, + {PSF(torsoFlip), 1}, + {PSF(legsFlip), 1}, + {PSF(fd.forcePowersActive), 32}, + {PSF(hasDetPackPlanted), 1}, + {PSF(fd.forceRageRecoveryTime), 32}, + {PSF(saberInFlight), 1}, + {PSF(fd.forceMindtrickTargetIndex), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.forceMindtrickTargetIndex2), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.forceMindtrickTargetIndex3), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.forceMindtrickTargetIndex4), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.sentryDeployed), 1}, + {PSF(fd.forcePowerLevel[FP_SEE]), 2}, // needed for knowing when to display players through walls + {PSF(holocronBits), 32}, + {PSF(fd.forcePower), 8}, + + //===THE REST OF THESE SHOULD NOT BE RELEVANT, BUT, FOR SAFETY, INCLUDE THEM ANYWAY, JUST AT THE + //BOTTOM=============================================================== + {PSF(velocity[0]), 0}, + {PSF(velocity[1]), 0}, + {PSF(velocity[2]), 0}, + {PSF(bobCycle), 8}, + {PSF(speed), 0}, // sadly, the vehicles require negative speed values, so.. + {PSF(groundEntityNum), GENTITYNUM_BITS}, + {PSF(viewheight), -8}, + {PSF(fd.saberAnimLevel), 4}, + {PSF(fd.saberDrawAnimLevel), 4}, + {PSF(genericEnemyIndex), 32}, // NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits + {PSF(customRGBA[0]), 8}, // 0-255 + {PSF(movementDir), 4}, + {PSF(saberEntityNum), GENTITYNUM_BITS}, // Also used for channel tracker storage, but should never exceed entity number + {PSF(customRGBA[3]), 8}, // 0-255 + {PSF(saberMove), 32}, // This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits + {PSF(standheight), 10}, + {PSF(crouchheight), 10}, + {PSF(basespeed), -16}, + {PSF(customRGBA[1]), 8}, // 0-255 + {PSF(duelIndex), GENTITYNUM_BITS}, + {PSF(customRGBA[2]), 8}, // 0-255 + {PSF(gravity), 16}, + {PSF(fd.forcePowersKnown), 32}, + {PSF(fd.forcePowerLevel[FP_LEVITATION]), + 2}, // unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) + {PSF(fd.forcePowerSelected), 8}, + {PSF(damageYaw), 8}, + {PSF(damageCount), 8}, + {PSF(inAirAnim), 1}, // just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit + {PSF(fd.forceSide), 2}, // so we know if we should apply greyed out shaders to dark/light force enlightenment + {PSF(saberAttackChainCount), 4}, + {PSF(lookTarget), GENTITYNUM_BITS}, + {PSF(moveDir[1]), 0}, + {PSF(moveDir[0]), 0}, + {PSF(damageEvent), 8}, + {PSF(moveDir[2]), 0}, + {PSF(activeForcePass), 6}, + {PSF(electrifyTime), 32}, + {PSF(damageType), 2}, + {PSF(loopSound), 16}, // rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? + {PSF(hasLookTarget), 1}, + {PSF(saberBlocked), 8}, + {PSF(forceHandExtend), 8}, + {PSF(saberHolstered), 2}, + {PSF(damagePitch), 8}, + {PSF(jumppad_ent), GENTITYNUM_BITS}, + {PSF(forceDodgeAnim), 16}, + {PSF(zoomMode), 2}, // NOTENOTE Are all of these necessary? + {PSF(hackingTime), 32}, + {PSF(zoomTime), 32}, // NOTENOTE Are all of these necessary? + {PSF(brokenLimbs), 8}, // up to 8 limbs at once (not that that many are used) + {PSF(zoomLocked), 1}, // NOTENOTE Are all of these necessary? + {PSF(zoomFov), 0}, // NOTENOTE Are all of these necessary? + {PSF(fallingToDeath), 32}, + {PSF(lastHitLoc[2]), 0}, + {PSF(lastHitLoc[0]), 0}, + {PSF(lastHitLoc[1]), 0}, // currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. + {PSF(saberLockTime), 32}, + {PSF(saberLockFrame), 16}, + {PSF(saberLockEnemy), GENTITYNUM_BITS}, + {PSF(fd.forceGripCripple), 1}, // should only be 0 or 1 ever + {PSF(emplacedIndex), GENTITYNUM_BITS}, + {PSF(isJediMaster), 1}, + {PSF(forceRestricted), 1}, + {PSF(trueJedi), 1}, + {PSF(trueNonJedi), 1}, + {PSF(duelTime), 32}, + {PSF(duelInProgress), 1}, + {PSF(saberLockAdvance), 1}, + {PSF(heldByClient), 6}, + {PSF(ragAttach), GENTITYNUM_BITS}, + {PSF(iModelScale), 10}, // 0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) + {PSF(hackingBaseTime), 16}, // up to 65536ms, over 10 seconds would just be silly anyway + //===NEVER SEND THESE, ONLY USED BY VEHICLES============================================================== + + //{ PSF(vehOrientation[0]), 0 }, + //{ PSF(vehOrientation[1]), 0 }, + //{ PSF(vehOrientation[2]), 0 }, + //{ PSF(vehTurnaroundTime), 32 },//only used by vehicle? + //{ PSF(vehWeaponsLinked), 1 },//only used by vehicle? + //{ PSF(hyperSpaceTime), 32 },//only used by vehicle? + //{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS },//only used by vehicle? + //{ PSF(vehSurfaces), 16 }, //only used by vehicle? allow up to 16 surfaces in the flag I guess + //{ PSF(vehBoarding), 1 }, //only used by vehicle? not like the normal boarding value, this is a simple "1 or 0" value + //{ PSF(hyperSpaceAngles[1]), 0 },//only used by vehicle? + //{ PSF(hyperSpaceAngles[0]), 0 },//only used by vehicle? + //{ PSF(hyperSpaceAngles[2]), 0 },//only used by vehicle? + + // rww - for use by mod authors only + {PSF(userInt1), 1}, + {PSF(userInt2), 1}, + {PSF(userInt3), 1}, + {PSF(userFloat1), 1}, + {PSF(userFloat2), 1}, + {PSF(userFloat3), 1}, + {PSF(userVec1[0]), 1}, + {PSF(userVec1[1]), 1}, + {PSF(userVec1[2]), 1}, + {PSF(userVec2[0]), 1}, + {PSF(userVec2[1]), 1}, + {PSF(userVec2[2]), 1}}; + +netField_t vehPlayerStateFields[] = { + {PSF(commandTime), 32}, + {PSF(origin[1]), 0}, + {PSF(origin[0]), 0}, + {PSF(viewangles[1]), 0}, + {PSF(viewangles[0]), 0}, + {PSF(origin[2]), 0}, + {PSF(velocity[0]), 0}, + {PSF(velocity[1]), 0}, + {PSF(velocity[2]), 0}, + {PSF(weaponTime), -16}, + {PSF(delta_angles[1]), 16}, + {PSF(speed), 0}, // sadly, the vehicles require negative speed values, so.. + {PSF(legsAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(delta_angles[0]), 16}, + {PSF(groundEntityNum), GENTITYNUM_BITS}, + {PSF(eFlags), 32}, + {PSF(eventSequence), 16}, + {PSF(legsTimer), 16}, + {PSF(rocketLockIndex), GENTITYNUM_BITS}, + //{ PSF(genericEnemyIndex), 32 }, //NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits + {PSF(events[0]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(events[1]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + //{ PSF(customRGBA[0]), 8 }, //0-255 + //{ PSF(movementDir), 4 }, + //{ PSF(customRGBA[3]), 8 }, //0-255 + {PSF(weaponstate), 4}, + //{ PSF(basespeed), -16 }, + {PSF(pm_flags), 16}, + {PSF(pm_time), -16}, + //{ PSF(customRGBA[1]), 8 }, //0-255 + {PSF(clientNum), GENTITYNUM_BITS}, + //{ PSF(duelIndex), GENTITYNUM_BITS }, + //{ PSF(customRGBA[2]), 8 }, //0-255 + {PSF(gravity), 16}, + {PSF(weapon), 8}, + {PSF(delta_angles[2]), 16}, + {PSF(viewangles[2]), 0}, + {PSF(externalEvent), 10}, + {PSF(eventParms[1]), 8}, + {PSF(pm_type), 8}, + {PSF(externalEventParm), 8}, + {PSF(eventParms[0]), -16}, + {PSF(vehOrientation[0]), 0}, + {PSF(vehOrientation[1]), 0}, + {PSF(moveDir[1]), 0}, + {PSF(moveDir[0]), 0}, + {PSF(vehOrientation[2]), 0}, + {PSF(moveDir[2]), 0}, + {PSF(rocketTargetTime), 32}, + //{ PSF(activeForcePass), 6 },//actually, you only need to know this for other vehicles, not your own + {PSF(electrifyTime), 32}, + //{ PSF(fd.forceJumpZStart), 0 },//set on rider by vehicle, but not used by vehicle + {PSF(loopSound), 16}, // rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? + {PSF(rocketLockTime), 32}, + {PSF(m_iVehicleNum), GENTITYNUM_BITS}, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis + {PSF(vehTurnaroundTime), 32}, + //{ PSF(generic1), 8 },//used by passengers of vehicles, but not vehicles themselves + {PSF(hackingTime), 32}, + {PSF(brokenLimbs), 8}, // up to 8 limbs at once (not that that many are used) + {PSF(vehWeaponsLinked), 1}, + {PSF(hyperSpaceTime), 32}, + {PSF(eFlags2), 10}, + {PSF(hyperSpaceAngles[1]), 0}, + {PSF(vehBoarding), 1}, // not like the normal boarding value, this is a simple "1 or 0" value + {PSF(vehTurnaroundIndex), GENTITYNUM_BITS}, + {PSF(vehSurfaces), 16}, // allow up to 16 surfaces in the flag I guess + {PSF(hyperSpaceAngles[0]), 0}, + {PSF(hyperSpaceAngles[2]), 0}, + + // rww - for use by mod authors only + {PSF(userInt1), 1}, + {PSF(userInt2), 1}, + {PSF(userInt3), 1}, + {PSF(userFloat1), 1}, + {PSF(userFloat2), 1}, + {PSF(userFloat3), 1}, + {PSF(userVec1[0]), 1}, + {PSF(userVec1[1]), 1}, + {PSF(userVec1[2]), 1}, + {PSF(userVec2[0]), 1}, + {PSF(userVec2[1]), 1}, + {PSF(userVec2[2]), 1}}; //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -#else//_OPTIMIZED_VEHICLE_NETWORKING -//The unoptimized way, throw *all* the vehicle stuff into the playerState along with everything else... :( +#else //_OPTIMIZED_VEHICLE_NETWORKING +// The unoptimized way, throw *all* the vehicle stuff into the playerState along with everything else... :( //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -netField_t playerStateFields[] = -{ -{ PSF(commandTime), 32 }, -{ PSF(origin[1]), 0 }, -{ PSF(origin[0]), 0 }, -{ PSF(viewangles[1]), 0 }, -{ PSF(viewangles[0]), 0 }, -{ PSF(origin[2]), 0 }, -{ PSF(velocity[0]), 0 }, -{ PSF(velocity[1]), 0 }, -{ PSF(velocity[2]), 0 }, -{ PSF(bobCycle), 8 }, -{ PSF(weaponTime), -16 }, -{ PSF(delta_angles[1]), 16 }, -{ PSF(speed), 0 }, //sadly, the vehicles require negative speed values, so.. -{ PSF(legsAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(delta_angles[0]), 16 }, -{ PSF(torsoAnim), 16 }, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit -{ PSF(groundEntityNum), GENTITYNUM_BITS }, -{ PSF(eFlags), 32 }, -{ PSF(fd.forcePower), 8 }, -{ PSF(eventSequence), 16 }, -{ PSF(torsoTimer), 16 }, -{ PSF(legsTimer), 16 }, -{ PSF(viewheight), -8 }, -{ PSF(fd.saberAnimLevel), 4 }, -{ PSF(rocketLockIndex), GENTITYNUM_BITS }, -{ PSF(fd.saberDrawAnimLevel), 4 }, -{ PSF(genericEnemyIndex), 32 }, //NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits -{ PSF(events[0]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(events[1]), 10 }, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) -{ PSF(customRGBA[0]), 8 }, //0-255 -{ PSF(movementDir), 4 }, -{ PSF(saberEntityNum), GENTITYNUM_BITS }, //Also used for channel tracker storage, but should never exceed entity number -{ PSF(customRGBA[3]), 8 }, //0-255 -{ PSF(weaponstate), 4 }, -{ PSF(saberMove), 32 }, //This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits -{ PSF(standheight), 10 }, -{ PSF(crouchheight), 10 }, -{ PSF(basespeed), -16 }, -{ PSF(pm_flags), 16 }, -{ PSF(jetpackFuel), 8 }, -{ PSF(cloakFuel), 8 }, -{ PSF(pm_time), -16 }, -{ PSF(customRGBA[1]), 8 }, //0-255 -{ PSF(clientNum), GENTITYNUM_BITS }, -{ PSF(duelIndex), GENTITYNUM_BITS }, -{ PSF(customRGBA[2]), 8 }, //0-255 -{ PSF(gravity), 16 }, -{ PSF(weapon), 8 }, -{ PSF(delta_angles[2]), 16 }, -{ PSF(saberCanThrow), 1 }, -{ PSF(viewangles[2]), 0 }, -{ PSF(fd.forcePowersKnown), 32 }, -{ PSF(fd.forcePowerLevel[FP_LEVITATION]), 2 }, //unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) -{ PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32 }, -{ PSF(fd.forcePowerSelected), 8 }, -{ PSF(torsoFlip), 1 }, -{ PSF(externalEvent), 10 }, -{ PSF(damageYaw), 8 }, -{ PSF(damageCount), 8 }, -{ PSF(inAirAnim), 1 }, //just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit -{ PSF(eventParms[1]), 8 }, -{ PSF(fd.forceSide), 2 }, //so we know if we should apply greyed out shaders to dark/light force enlightenment -{ PSF(saberAttackChainCount), 4 }, -{ PSF(pm_type), 8 }, -{ PSF(externalEventParm), 8 }, -{ PSF(eventParms[0]), -16 }, -{ PSF(lookTarget), GENTITYNUM_BITS }, -{ PSF(vehOrientation[0]), 0 }, -{ PSF(weaponChargeSubtractTime), 32 }, //? really need 32 bits?? -{ PSF(vehOrientation[1]), 0 }, -{ PSF(moveDir[1]), 0 }, -{ PSF(moveDir[0]), 0 }, -{ PSF(weaponChargeTime), 32 }, //? really need 32 bits?? -{ PSF(vehOrientation[2]), 0 }, -{ PSF(legsFlip), 1 }, -{ PSF(damageEvent), 8 }, -{ PSF(moveDir[2]), 0 }, -{ PSF(rocketTargetTime), 32 }, -{ PSF(activeForcePass), 6 }, -{ PSF(electrifyTime), 32 }, -{ PSF(fd.forceJumpZStart), 0 }, -{ PSF(loopSound), 16 }, //rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? -{ PSF(hasLookTarget), 1 }, -{ PSF(saberBlocked), 8 }, -{ PSF(damageType), 2 }, -{ PSF(rocketLockTime), 32 }, -{ PSF(forceHandExtend), 8 }, -{ PSF(saberHolstered), 2 }, -{ PSF(fd.forcePowersActive), 32 }, -{ PSF(damagePitch), 8 }, -{ PSF(m_iVehicleNum), GENTITYNUM_BITS }, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis -{ PSF(vehTurnaroundTime), 32 }, -{ PSF(generic1), 8 }, -{ PSF(jumppad_ent), GENTITYNUM_BITS }, -{ PSF(hasDetPackPlanted), 1 }, -{ PSF(saberInFlight), 1 }, -{ PSF(forceDodgeAnim), 16 }, -{ PSF(zoomMode), 2 }, // NOTENOTE Are all of these necessary? -{ PSF(hackingTime), 32 }, -{ PSF(zoomTime), 32 }, // NOTENOTE Are all of these necessary? -{ PSF(brokenLimbs), 8 }, //up to 8 limbs at once (not that that many are used) -{ PSF(zoomLocked), 1 }, // NOTENOTE Are all of these necessary? -{ PSF(zoomFov), 0 }, // NOTENOTE Are all of these necessary? -{ PSF(fd.forceRageRecoveryTime), 32 }, -{ PSF(fallingToDeath), 32 }, -{ PSF(fd.forceMindtrickTargetIndex), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(fd.forceMindtrickTargetIndex2), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(vehWeaponsLinked), 1 }, -{ PSF(lastHitLoc[2]), 0 }, -{ PSF(hyperSpaceTime), 32 }, -{ PSF(fd.forceMindtrickTargetIndex3), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(lastHitLoc[0]), 0 }, -{ PSF(eFlags2), 10 }, -{ PSF(fd.forceMindtrickTargetIndex4), 16 }, //NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients -{ PSF(hyperSpaceAngles[1]), 0 }, -{ PSF(lastHitLoc[1]), 0 }, //currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. -{ PSF(vehBoarding), 1 }, //not like the normal boarding value, this is a simple "1 or 0" value -{ PSF(fd.sentryDeployed), 1 }, -{ PSF(saberLockTime), 32 }, -{ PSF(saberLockFrame), 16 }, -{ PSF(vehTurnaroundIndex), GENTITYNUM_BITS }, -{ PSF(vehSurfaces), 16 }, //allow up to 16 surfaces in the flag I guess -{ PSF(fd.forcePowerLevel[FP_SEE]), 2 }, //needed for knowing when to display players through walls -{ PSF(saberLockEnemy), GENTITYNUM_BITS }, -{ PSF(fd.forceGripCripple), 1 }, //should only be 0 or 1 ever -{ PSF(emplacedIndex), GENTITYNUM_BITS }, -{ PSF(holocronBits), 32 }, -{ PSF(isJediMaster), 1 }, -{ PSF(forceRestricted), 1 }, -{ PSF(trueJedi), 1 }, -{ PSF(trueNonJedi), 1 }, -{ PSF(duelTime), 32 }, -{ PSF(duelInProgress), 1 }, -{ PSF(saberLockAdvance), 1 }, -{ PSF(heldByClient), 6 }, -{ PSF(ragAttach), GENTITYNUM_BITS }, -{ PSF(iModelScale), 10 }, //0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) -{ PSF(hackingBaseTime), 16 }, //up to 65536ms, over 10 seconds would just be silly anyway -{ PSF(hyperSpaceAngles[0]), 0 }, -{ PSF(hyperSpaceAngles[2]), 0 }, - -//rww - for use by mod authors only -{ PSF(userInt1), 1 }, -{ PSF(userInt2), 1 }, -{ PSF(userInt3), 1 }, -{ PSF(userFloat1), 1 }, -{ PSF(userFloat2), 1 }, -{ PSF(userFloat3), 1 }, -{ PSF(userVec1[0]), 1 }, -{ PSF(userVec1[1]), 1 }, -{ PSF(userVec1[2]), 1 }, -{ PSF(userVec2[0]), 1 }, -{ PSF(userVec2[1]), 1 }, -{ PSF(userVec2[2]), 1 } -}; +netField_t playerStateFields[] = { + {PSF(commandTime), 32}, + {PSF(origin[1]), 0}, + {PSF(origin[0]), 0}, + {PSF(viewangles[1]), 0}, + {PSF(viewangles[0]), 0}, + {PSF(origin[2]), 0}, + {PSF(velocity[0]), 0}, + {PSF(velocity[1]), 0}, + {PSF(velocity[2]), 0}, + {PSF(bobCycle), 8}, + {PSF(weaponTime), -16}, + {PSF(delta_angles[1]), 16}, + {PSF(speed), 0}, // sadly, the vehicles require negative speed values, so.. + {PSF(legsAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(delta_angles[0]), 16}, + {PSF(torsoAnim), 16}, // Maximum number of animation sequences is 2048. Top bit is reserved for the togglebit + {PSF(groundEntityNum), GENTITYNUM_BITS}, + {PSF(eFlags), 32}, + {PSF(fd.forcePower), 8}, + {PSF(eventSequence), 16}, + {PSF(torsoTimer), 16}, + {PSF(legsTimer), 16}, + {PSF(viewheight), -8}, + {PSF(fd.saberAnimLevel), 4}, + {PSF(rocketLockIndex), GENTITYNUM_BITS}, + {PSF(fd.saberDrawAnimLevel), 4}, + {PSF(genericEnemyIndex), 32}, // NOTE: This isn't just an index all the time, it's often used as a time value, and thus needs 32 bits + {PSF(events[0]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(events[1]), 10}, // There is a maximum of 256 events (8 bits transmission, 2 high bits for uniqueness) + {PSF(customRGBA[0]), 8}, // 0-255 + {PSF(movementDir), 4}, + {PSF(saberEntityNum), GENTITYNUM_BITS}, // Also used for channel tracker storage, but should never exceed entity number + {PSF(customRGBA[3]), 8}, // 0-255 + {PSF(weaponstate), 4}, + {PSF(saberMove), 32}, // This value sometimes exceeds the max LS_ value and gets set to a crazy amount, so it needs 32 bits + {PSF(standheight), 10}, + {PSF(crouchheight), 10}, + {PSF(basespeed), -16}, + {PSF(pm_flags), 16}, + {PSF(jetpackFuel), 8}, + {PSF(cloakFuel), 8}, + {PSF(pm_time), -16}, + {PSF(customRGBA[1]), 8}, // 0-255 + {PSF(clientNum), GENTITYNUM_BITS}, + {PSF(duelIndex), GENTITYNUM_BITS}, + {PSF(customRGBA[2]), 8}, // 0-255 + {PSF(gravity), 16}, + {PSF(weapon), 8}, + {PSF(delta_angles[2]), 16}, + {PSF(saberCanThrow), 1}, + {PSF(viewangles[2]), 0}, + {PSF(fd.forcePowersKnown), 32}, + {PSF(fd.forcePowerLevel[FP_LEVITATION]), + 2}, // unfortunately we need this for fall damage calculation (client needs to know the distance for the fall noise) + {PSF(fd.forcePowerDebounce[FP_LEVITATION]), 32}, + {PSF(fd.forcePowerSelected), 8}, + {PSF(torsoFlip), 1}, + {PSF(externalEvent), 10}, + {PSF(damageYaw), 8}, + {PSF(damageCount), 8}, + {PSF(inAirAnim), 1}, // just transmit it for the sake of knowing right when on the client to play a land anim, it's only 1 bit + {PSF(eventParms[1]), 8}, + {PSF(fd.forceSide), 2}, // so we know if we should apply greyed out shaders to dark/light force enlightenment + {PSF(saberAttackChainCount), 4}, + {PSF(pm_type), 8}, + {PSF(externalEventParm), 8}, + {PSF(eventParms[0]), -16}, + {PSF(lookTarget), GENTITYNUM_BITS}, + {PSF(vehOrientation[0]), 0}, + {PSF(weaponChargeSubtractTime), 32}, //? really need 32 bits?? + {PSF(vehOrientation[1]), 0}, + {PSF(moveDir[1]), 0}, + {PSF(moveDir[0]), 0}, + {PSF(weaponChargeTime), 32}, //? really need 32 bits?? + {PSF(vehOrientation[2]), 0}, + {PSF(legsFlip), 1}, + {PSF(damageEvent), 8}, + {PSF(moveDir[2]), 0}, + {PSF(rocketTargetTime), 32}, + {PSF(activeForcePass), 6}, + {PSF(electrifyTime), 32}, + {PSF(fd.forceJumpZStart), 0}, + {PSF(loopSound), 16}, // rwwFIXMEFIXME: max sounds is 256, doesn't this only need to be 8? + {PSF(hasLookTarget), 1}, + {PSF(saberBlocked), 8}, + {PSF(damageType), 2}, + {PSF(rocketLockTime), 32}, + {PSF(forceHandExtend), 8}, + {PSF(saberHolstered), 2}, + {PSF(fd.forcePowersActive), 32}, + {PSF(damagePitch), 8}, + {PSF(m_iVehicleNum), GENTITYNUM_BITS}, // 10 bits fits all possible entity nums (2^10 = 1024). - AReis + {PSF(vehTurnaroundTime), 32}, + {PSF(generic1), 8}, + {PSF(jumppad_ent), GENTITYNUM_BITS}, + {PSF(hasDetPackPlanted), 1}, + {PSF(saberInFlight), 1}, + {PSF(forceDodgeAnim), 16}, + {PSF(zoomMode), 2}, // NOTENOTE Are all of these necessary? + {PSF(hackingTime), 32}, + {PSF(zoomTime), 32}, // NOTENOTE Are all of these necessary? + {PSF(brokenLimbs), 8}, // up to 8 limbs at once (not that that many are used) + {PSF(zoomLocked), 1}, // NOTENOTE Are all of these necessary? + {PSF(zoomFov), 0}, // NOTENOTE Are all of these necessary? + {PSF(fd.forceRageRecoveryTime), 32}, + {PSF(fallingToDeath), 32}, + {PSF(fd.forceMindtrickTargetIndex), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(fd.forceMindtrickTargetIndex2), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(vehWeaponsLinked), 1}, + {PSF(lastHitLoc[2]), 0}, + {PSF(hyperSpaceTime), 32}, + {PSF(fd.forceMindtrickTargetIndex3), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(lastHitLoc[0]), 0}, + {PSF(eFlags2), 10}, + {PSF(fd.forceMindtrickTargetIndex4), 16}, // NOTE: Not just an index, used as a (1 << val) bitflag for up to 16 clients + {PSF(hyperSpaceAngles[1]), 0}, + {PSF(lastHitLoc[1]), 0}, // currently only used so client knows to orient disruptor disintegration.. seems a bit much for just that though. + {PSF(vehBoarding), 1}, // not like the normal boarding value, this is a simple "1 or 0" value + {PSF(fd.sentryDeployed), 1}, + {PSF(saberLockTime), 32}, + {PSF(saberLockFrame), 16}, + {PSF(vehTurnaroundIndex), GENTITYNUM_BITS}, + {PSF(vehSurfaces), 16}, // allow up to 16 surfaces in the flag I guess + {PSF(fd.forcePowerLevel[FP_SEE]), 2}, // needed for knowing when to display players through walls + {PSF(saberLockEnemy), GENTITYNUM_BITS}, + {PSF(fd.forceGripCripple), 1}, // should only be 0 or 1 ever + {PSF(emplacedIndex), GENTITYNUM_BITS}, + {PSF(holocronBits), 32}, + {PSF(isJediMaster), 1}, + {PSF(forceRestricted), 1}, + {PSF(trueJedi), 1}, + {PSF(trueNonJedi), 1}, + {PSF(duelTime), 32}, + {PSF(duelInProgress), 1}, + {PSF(saberLockAdvance), 1}, + {PSF(heldByClient), 6}, + {PSF(ragAttach), GENTITYNUM_BITS}, + {PSF(iModelScale), 10}, // 0-1024 (guess it's gotta be increased if we want larger allowable scale.. but 1024% is pretty big) + {PSF(hackingBaseTime), 16}, // up to 65536ms, over 10 seconds would just be silly anyway + {PSF(hyperSpaceAngles[0]), 0}, + {PSF(hyperSpaceAngles[2]), 0}, + + // rww - for use by mod authors only + {PSF(userInt1), 1}, + {PSF(userInt2), 1}, + {PSF(userInt3), 1}, + {PSF(userFloat1), 1}, + {PSF(userFloat2), 1}, + {PSF(userFloat3), 1}, + {PSF(userVec1[0]), 1}, + {PSF(userVec1[1]), 1}, + {PSF(userVec1[2]), 1}, + {PSF(userVec2[0]), 1}, + {PSF(userVec2[1]), 1}, + {PSF(userVec2[2]), 1}}; //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -#endif//_OPTIMIZED_VEHICLE_NETWORKING +#endif //_OPTIMIZED_VEHICLE_NETWORKING //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= typedef struct bitStorage_s bitStorage_t; -struct bitStorage_s -{ - bitStorage_t *next; - int bits; +struct bitStorage_s { + bitStorage_t *next; + int bits; }; -static bitStorage_t *g_netfBitStorage = NULL; -static bitStorage_t *g_psfBitStorage = NULL; +static bitStorage_t *g_netfBitStorage = NULL; +static bitStorage_t *g_psfBitStorage = NULL; -//rww - Check the overrides files to see if the mod wants anything changed -void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) -{ +// rww - Check the overrides files to see if the mod wants anything changed +void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) { char overrideFile[4096]; char entryName[4096]; char bits[4096]; @@ -1901,33 +1852,25 @@ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) fileHandle_t f; bitStorage_t **bitStorage; - if (psfOverrides) - { //do PSF overrides instead of NETF + if (psfOverrides) { // do PSF overrides instead of NETF fileName = "psf_overrides.txt"; bitStorage = &g_psfBitStorage; - numFields = (int)ARRAY_LEN( playerStateFields ); - } - else - { + numFields = (int)ARRAY_LEN(playerStateFields); + } else { fileName = "netf_overrides.txt"; bitStorage = &g_netfBitStorage; - numFields = (int)ARRAY_LEN( entityStateFields ); + numFields = (int)ARRAY_LEN(entityStateFields); } - if (*bitStorage) - { //if we have saved off the defaults before we want to stuff them all back in now + if (*bitStorage) { // if we have saved off the defaults before we want to stuff them all back in now bitStorage_t *restore = *bitStorage; - while (i < numFields) - { + while (i < numFields) { assert(restore); - if (psfOverrides) - { + if (psfOverrides) { playerStateFields[i].bits = restore->bits; - } - else - { + } else { entityStateFields[i].bits = restore->bits; } @@ -1938,125 +1881,98 @@ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) len = FS_FOpenFileRead(va("ext_data/MP/%s", fileName), &f, qfalse); - if (!f || len < 0) - { //silently exit since this file is not needed to proceed. + if (!f || len < 0) { // silently exit since this file is not needed to proceed. return; } - if (len >= 4096) - { + if (len >= 4096) { Com_Printf("WARNING: %s is >= 4096 bytes and is being ignored\n", fileName); FS_FCloseFile(f); return; } - //Get contents of the file + // Get contents of the file FS_Read(overrideFile, len, f); FS_FCloseFile(f); - //because FS_Read does not do this for us. + // because FS_Read does not do this for us. overrideFile[len] = 0; - //If we haven't saved off the initial stuff yet then stuff it all into - //a list. - if (!*bitStorage) - { + // If we haven't saved off the initial stuff yet then stuff it all into + // a list. + if (!*bitStorage) { i = 0; - while (i < numFields) - { - //Alloc memory for this new ptr + while (i < numFields) { + // Alloc memory for this new ptr *bitStorage = (bitStorage_t *)Z_Malloc(sizeof(bitStorage_t), TAG_GENERAL, qtrue); - if (psfOverrides) - { + if (psfOverrides) { (*bitStorage)->bits = playerStateFields[i].bits; - } - else - { + } else { (*bitStorage)->bits = entityStateFields[i].bits; } - //Point to the ->next of the existing current ptr + // Point to the ->next of the existing current ptr bitStorage = &(*bitStorage)->next; i++; } } i = 0; - //Now parse through. Lines beginning with ; are disabled. - while (overrideFile[i]) - { - if (overrideFile[i] == ';') - { //parse to end of the line - while (overrideFile[i] != '\n') - { + // Now parse through. Lines beginning with ; are disabled. + while (overrideFile[i]) { + if (overrideFile[i] == ';') { // parse to end of the line + while (overrideFile[i] != '\n') { i++; } } - if (overrideFile[i] != ';' && - overrideFile[i] != '\n' && - overrideFile[i] != '\r') - { //on a valid char I guess, parse it + if (overrideFile[i] != ';' && overrideFile[i] != '\n' && overrideFile[i] != '\r') { // on a valid char I guess, parse it j = 0; - while (overrideFile[i] && overrideFile[i] != ',') - { + while (overrideFile[i] && overrideFile[i] != ',') { entryName[j] = overrideFile[i]; j++; i++; } entryName[j] = 0; - if (!overrideFile[i]) - { //just give up, this shouldn't happen + if (!overrideFile[i]) { // just give up, this shouldn't happen Com_Printf("WARNING: Parsing error for %s\n", fileName); return; } - while (overrideFile[i] == ',' || overrideFile[i] == ' ') - { //parse to the start of the value + while (overrideFile[i] == ',' || overrideFile[i] == ' ') { // parse to the start of the value i++; } j = 0; - while (overrideFile[i] != '\n' && overrideFile[i] != '\r') - { //now read the value in + while (overrideFile[i] != '\n' && overrideFile[i] != '\r') { // now read the value in bits[j] = overrideFile[i]; j++; i++; } bits[j] = 0; - if (bits[0]) - { - if (!strcmp(bits, "GENTITYNUM_BITS")) - { //special case + if (bits[0]) { + if (!strcmp(bits, "GENTITYNUM_BITS")) { // special case ibits = GENTITYNUM_BITS; - } - else - { - ibits = atoi(bits); + } else { + ibits = atoi(bits); } j = 0; - //Now go through all the fields and see if we can find a match - while (j < numFields) - { - if (psfOverrides) - { //check psf fields - if (!strcmp(playerStateFields[j].name, entryName)) - { //found it, set the bits + // Now go through all the fields and see if we can find a match + while (j < numFields) { + if (psfOverrides) { // check psf fields + if (!strcmp(playerStateFields[j].name, entryName)) { // found it, set the bits playerStateFields[j].bits = ibits; break; } - } - else - { //otherwise check netf fields - if (!strcmp(entityStateFields[j].name, entryName)) - { //found it, set the bits + } else { // otherwise check netf fields + if (!strcmp(entityStateFields[j].name, entryName)) { // found it, set the bits entityStateFields[j].bits = ibits; break; } @@ -2064,13 +1980,10 @@ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) j++; } - if (j == numFields) - { //failed to find the value + if (j == numFields) { // failed to find the value Com_Printf("WARNING: Value '%s' from %s is not valid\n", entryName, fileName); } - } - else - { //also should not happen + } else { // also should not happen Com_Printf("WARNING: Parsing error for %s\n", fileName); return; } @@ -2080,8 +1993,8 @@ void MSG_CheckNETFPSFOverrides(qboolean psfOverrides) } } -//MAKE SURE THIS MATCHES THE ENUM IN BG_PUBLIC.H!!! -//This is in caps, because it is important. +// MAKE SURE THIS MATCHES THE ENUM IN BG_PUBLIC.H!!! +// This is in caps, because it is important. #define STAT_WEAPONS 4 /* @@ -2091,72 +2004,65 @@ MSG_WriteDeltaPlayerstate ============= */ #ifdef _ONEBIT_COMBO -void MSG_WriteDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct playerState_s *to, int *bitComboDelta, int *bitNumDelta, qboolean isVehiclePS ) { +void MSG_WriteDeltaPlayerstate(msg_t *msg, struct playerState_s *from, struct playerState_s *to, int *bitComboDelta, int *bitNumDelta, qboolean isVehiclePS) { #else -void MSG_WriteDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct playerState_s *to, qboolean isVehiclePS ) { +void MSG_WriteDeltaPlayerstate(msg_t *msg, struct playerState_s *from, struct playerState_s *to, qboolean isVehiclePS) { #endif - int i; - playerState_t dummy; - int statsbits; - int persistantbits; - int ammobits; - int powerupbits; - int numFields; - netField_t *field; - netField_t *PSFields = playerStateFields; - int *fromF, *toF; - float fullFloat; - int trunc, lc; + int i; + playerState_t dummy; + int statsbits; + int persistantbits; + int ammobits; + int powerupbits; + int numFields; + netField_t *field; + netField_t *PSFields = playerStateFields; + int *fromF, *toF; + float fullFloat; + int trunc, lc; #ifdef _ONEBIT_COMBO - int bitComboMask = 0; - int numBitsInMask = 0; + int bitComboMask = 0; + int numBitsInMask = 0; #endif if (!from) { from = &dummy; - Com_Memset (&dummy, 0, sizeof(dummy)); + Com_Memset(&dummy, 0, sizeof(dummy)); } //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= #ifdef _OPTIMIZED_VEHICLE_NETWORKING - if ( isVehiclePS ) - {//a vehicle playerstate - numFields = (int)ARRAY_LEN( vehPlayerStateFields ); + if (isVehiclePS) { // a vehicle playerstate + numFields = (int)ARRAY_LEN(vehPlayerStateFields); PSFields = vehPlayerStateFields; - } - else - {//regular client playerstate - if ( to->m_iVehicleNum - && (to->eFlags&EF_NODRAW) ) - {//pilot riding *inside* a vehicle! - MSG_WriteBits( msg, 1, 1 ); // Pilot player state - numFields = (int)ARRAY_LEN( pilotPlayerStateFields ); + } else { // regular client playerstate + if (to->m_iVehicleNum && (to->eFlags & EF_NODRAW)) { // pilot riding *inside* a vehicle! + MSG_WriteBits(msg, 1, 1); // Pilot player state + numFields = (int)ARRAY_LEN(pilotPlayerStateFields); PSFields = pilotPlayerStateFields; - } - else - {//normal client - MSG_WriteBits( msg, 0, 1 ); // Normal player state - numFields = (int)ARRAY_LEN( playerStateFields ); + } else { // normal client + MSG_WriteBits(msg, 0, 1); // Normal player state + numFields = (int)ARRAY_LEN(playerStateFields); } } //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -#else// _OPTIMIZED_VEHICLE_NETWORKING - numFields = (int)ARRAY_LEN( playerStateFields ); -#endif// _OPTIMIZED_VEHICLE_NETWORKING +#else // _OPTIMIZED_VEHICLE_NETWORKING + numFields = (int)ARRAY_LEN(playerStateFields); +#endif // _OPTIMIZED_VEHICLE_NETWORKING lc = 0; - for ( i = 0, field = PSFields ; i < numFields ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); - if ( *fromF != *toF ) { - lc = i+1; + for (i = 0, field = PSFields; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); + if (*fromF != *toF) { + lc = i + 1; #ifndef FINAL_BUILD field->mCount++; #endif } } - MSG_WriteByte( msg, lc ); // # of changes + MSG_WriteByte(msg, lc); // # of changes #ifndef FINAL_BUILD gLastBitIndex = lc; @@ -2164,79 +2070,75 @@ void MSG_WriteDeltaPlayerstate( msg_t *msg, struct playerState_s *from, struct p oldsize += numFields - lc; - for ( i = 0, field = PSFields ; i < lc ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = 0, field = PSFields; i < lc; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); #ifdef _ONEBIT_COMBO - if (numBitsInMask < 32 && - field->bits == 1) - { - bitComboMask |= (*toF)<bits == 1) { + bitComboMask |= (*toF) << numBitsInMask; numBitsInMask++; continue; } #endif - if ( *fromF == *toF ) { - MSG_WriteBits( msg, 0, 1 ); // no change + if (*fromF == *toF) { + MSG_WriteBits(msg, 0, 1); // no change continue; } - MSG_WriteBits( msg, 1, 1 ); // changed + MSG_WriteBits(msg, 1, 1); // changed - if ( field->bits == 0 ) { + if (field->bits == 0) { // float fullFloat = *(float *)toF; trunc = (int)fullFloat; - if ( trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && - trunc + FLOAT_INT_BIAS < ( 1 << FLOAT_INT_BITS ) ) { + if (trunc == fullFloat && trunc + FLOAT_INT_BIAS >= 0 && trunc + FLOAT_INT_BIAS < (1 << FLOAT_INT_BITS)) { // send as small integer - MSG_WriteBits( msg, 0, 1 ); - MSG_WriteBits( msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS ); + MSG_WriteBits(msg, 0, 1); + MSG_WriteBits(msg, trunc + FLOAT_INT_BIAS, FLOAT_INT_BITS); } else { // send as full floating point value - MSG_WriteBits( msg, 1, 1 ); - MSG_WriteBits( msg, *toF, 32 ); + MSG_WriteBits(msg, 1, 1); + MSG_WriteBits(msg, *toF, 32); } } else { // integer - MSG_WriteBits( msg, *toF, field->bits ); + MSG_WriteBits(msg, *toF, field->bits); } } - // // send the arrays // statsbits = 0; - for (i=0 ; istats[i] != from->stats[i]) { - statsbits |= 1<persistant[i] != from->persistant[i]) { - persistantbits |= 1<ammo[i] != from->ammo[i]) { - ammobits |= 1<powerups[i] != from->powerups[i]) { - powerupbits |= 1<stats[i], MAX_WEAPONS); - } - else - { - MSG_WriteShort (msg, to->stats[i]); + } else { + MSG_WriteShort(msg, to->stats[i]); } } } } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - - if ( persistantbits ) { - MSG_WriteBits( msg, 1, 1 ); // changed - MSG_WriteBits( msg, persistantbits, MAX_PERSISTANT ); - for (i=0 ; ipersistant[i]); + if (persistantbits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteBits(msg, persistantbits, MAX_PERSISTANT); + for (i = 0; i < MAX_PERSISTANT; i++) + if (persistantbits & (1 << i)) + MSG_WriteShort(msg, to->persistant[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - - if ( ammobits ) { - MSG_WriteBits( msg, 1, 1 ); // changed - MSG_WriteBits( msg, ammobits, MAX_AMMO_TRANSMIT ); - for (i=0 ; iammo[i]); + if (ammobits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteBits(msg, ammobits, MAX_AMMO_TRANSMIT); + for (i = 0; i < MAX_AMMO_TRANSMIT; i++) + if (ammobits & (1 << i)) + MSG_WriteShort(msg, to->ammo[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } - - if ( powerupbits ) { - MSG_WriteBits( msg, 1, 1 ); // changed - MSG_WriteBits( msg, powerupbits, MAX_POWERUPS ); - for (i=0 ; ipowerups[i] ); + if (powerupbits) { + MSG_WriteBits(msg, 1, 1); // changed + MSG_WriteBits(msg, powerupbits, MAX_POWERUPS); + for (i = 0; i < MAX_POWERUPS; i++) + if (powerupbits & (1 << i)) + MSG_WriteLong(msg, to->powerups[i]); } else { - MSG_WriteBits( msg, 0, 1 ); // no change + MSG_WriteBits(msg, 0, 1); // no change } #ifdef _ONEBIT_COMBO sendBitMask: - if (numBitsInMask) - { //don't need to send at all if we didn't pass any 1bit values - if (!bitComboDelta || - bitComboMask != *bitComboDelta || - numBitsInMask != *bitNumDelta) - { //send the mask, it changed + if (numBitsInMask) { // don't need to send at all if we didn't pass any 1bit values + if (!bitComboDelta || bitComboMask != *bitComboDelta || numBitsInMask != *bitNumDelta) { // send the mask, it changed MSG_WriteBits(msg, 1, 1); MSG_WriteBits(msg, bitComboMask, numBitsInMask); - if (bitComboDelta) - { + if (bitComboDelta) { *bitComboDelta = bitComboMask; *bitNumDelta = numBitsInMask; } - } - else - { //send 1 bit 0 to indicate no change + } else { // send 1 bit 0 to indicate no change MSG_WriteBits(msg, 0, 1); } } #endif } - /* =================== MSG_ReadDeltaPlayerstate =================== */ -void MSG_ReadDeltaPlayerstate (msg_t *msg, playerState_t *from, playerState_t *to, qboolean isVehiclePS ) { - int i, lc; - int bits; - netField_t *field; - netField_t *PSFields = playerStateFields; - int numFields; - int startBit, endBit; - int print; - int *fromF, *toF; - int trunc; +void MSG_ReadDeltaPlayerstate(msg_t *msg, playerState_t *from, playerState_t *to, qboolean isVehiclePS) { + int i, lc; + int bits; + netField_t *field; + netField_t *PSFields = playerStateFields; + int numFields; + int startBit, endBit; + int print; + int *fromF, *toF; + int trunc; #ifdef _ONEBIT_COMBO - int numBitsInMask = 0; + int numBitsInMask = 0; #endif - playerState_t dummy; + playerState_t dummy; - if ( !from ) { + if (!from) { from = &dummy; - Com_Memset( &dummy, 0, sizeof( dummy ) ); + Com_Memset(&dummy, 0, sizeof(dummy)); } *to = *from; - if ( msg->bit == 0 ) { + if (msg->bit == 0) { startBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - startBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + startBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } // shownet 2/3 will interleave with other printed info, -2 will // just print the delta records - if ( cl_shownet && ( cl_shownet->integer >= 2 || cl_shownet->integer == -2 ) ) { + if (cl_shownet && (cl_shownet->integer >= 2 || cl_shownet->integer == -2)) { print = 1; - Com_Printf( "%3i: playerstate ", msg->readcount ); + Com_Printf("%3i: playerstate ", msg->readcount); } else { print = 0; } //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= #ifdef _OPTIMIZED_VEHICLE_NETWORKING - if ( isVehiclePS ) - {//a vehicle playerstate - numFields = (int)ARRAY_LEN( vehPlayerStateFields ); + if (isVehiclePS) { // a vehicle playerstate + numFields = (int)ARRAY_LEN(vehPlayerStateFields); PSFields = vehPlayerStateFields; - } - else - { - int isPilot = MSG_ReadBits( msg, 1 ); - if ( isPilot ) - {//pilot riding *inside* a vehicle! - numFields = (int)ARRAY_LEN( pilotPlayerStateFields ); + } else { + int isPilot = MSG_ReadBits(msg, 1); + if (isPilot) { // pilot riding *inside* a vehicle! + numFields = (int)ARRAY_LEN(pilotPlayerStateFields); PSFields = pilotPlayerStateFields; - } - else - {//normal client - numFields = (int)ARRAY_LEN( playerStateFields ); + } else { // normal client + numFields = (int)ARRAY_LEN(playerStateFields); } } //=====_OPTIMIZED_VEHICLE_NETWORKING======================================================================= -#else//_OPTIMIZED_VEHICLE_NETWORKING - numFields = (int)ARRAY_LEN( playerStateFields ); -#endif//_OPTIMIZED_VEHICLE_NETWORKING +#else //_OPTIMIZED_VEHICLE_NETWORKING + numFields = (int)ARRAY_LEN(playerStateFields); +#endif //_OPTIMIZED_VEHICLE_NETWORKING lc = MSG_ReadByte(msg); - if ( lc > numFields || lc < 0 ) - Com_Error( ERR_DROP, "invalid playerState field count (got: %i, expecting: %i)", lc, numFields ); + if (lc > numFields || lc < 0) + Com_Error(ERR_DROP, "invalid playerState field count (got: %i, expecting: %i)", lc, numFields); - for ( i = 0, field = PSFields ; i < lc ; i++, field++ ) { - fromF = (int *)( (byte *)from + field->offset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = 0, field = PSFields; i < lc; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); #ifdef _ONEBIT_COMBO - if (numBitsInMask < 32 && - field->bits == 1) - { + if (numBitsInMask < 32 && field->bits == 1) { *toF = *fromF; numBitsInMask++; continue; } #endif - if ( ! MSG_ReadBits( msg, 1 ) ) { + if (!MSG_ReadBits(msg, 1)) { // no change *toF = *fromF; } else { - if ( field->bits == 0 ) { + if (field->bits == 0) { // float - if ( MSG_ReadBits( msg, 1 ) == 0 ) { + if (MSG_ReadBits(msg, 1) == 0) { // integral float - trunc = MSG_ReadBits( msg, FLOAT_INT_BITS ); + trunc = MSG_ReadBits(msg, FLOAT_INT_BITS); // bias to allow equal parts positive and negative trunc -= FLOAT_INT_BIAS; *(float *)toF = trunc; - if ( print ) { - Com_Printf( "%s:%i ", field->name, trunc ); + if (print) { + Com_Printf("%s:%i ", field->name, trunc); } } else { // full floating point value - *toF = MSG_ReadBits( msg, 32 ); - if ( print ) { - Com_Printf( "%s:%f ", field->name, *(float *)toF ); + *toF = MSG_ReadBits(msg, 32); + if (print) { + Com_Printf("%s:%f ", field->name, *(float *)toF); } } } else { // integer - *toF = MSG_ReadBits( msg, field->bits ); - if ( print ) { - Com_Printf( "%s:%i ", field->name, *toF ); + *toF = MSG_ReadBits(msg, field->bits); + if (print) { + Com_Printf("%s:%i ", field->name, *toF); } } } } - for ( i=lc,field = &PSFields[lc];ioffset ); - toF = (int *)( (byte *)to + field->offset ); + for (i = lc, field = &PSFields[lc]; i < numFields; i++, field++) { + fromF = (int *)((byte *)from + field->offset); + toF = (int *)((byte *)to + field->offset); // no change *toF = *fromF; } // read the arrays - if (MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { // parse stats - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_STATS"); - bits = MSG_ReadBits (msg, MAX_STATS); - for (i=0 ; istats[i] = MSG_ReadBits(msg, MAX_WEAPONS); - } - else - { + } else { to->stats[i] = MSG_ReadShort(msg); } } @@ -2471,62 +2345,58 @@ void MSG_ReadDeltaPlayerstate (msg_t *msg, playerState_t *from, playerState_t *t } // parse persistant stats - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_PERSISTANT"); - bits = MSG_ReadBits (msg, MAX_PERSISTANT); - for (i=0 ; ipersistant[i] = MSG_ReadShort(msg); } } } // parse ammo - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_AMMO"); - bits = MSG_ReadBits (msg, MAX_AMMO_TRANSMIT); - for (i=0 ; iammo[i] = MSG_ReadShort(msg); } } } // parse powerups - if ( MSG_ReadBits( msg, 1 ) ) { + if (MSG_ReadBits(msg, 1)) { LOG("PS_POWERUPS"); - bits = MSG_ReadBits (msg, MAX_POWERUPS); - for (i=0 ; ipowerups[i] = MSG_ReadLong(msg); } } } } - if ( print ) { - if ( msg->bit == 0 ) { + if (print) { + if (msg->bit == 0) { endBit = msg->readcount * 8 - GENTITYNUM_BITS; } else { - endBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS; + endBit = (msg->readcount - 1) * 8 + msg->bit - GENTITYNUM_BITS; } - Com_Printf( " (%i bits)\n", endBit - startBit ); + Com_Printf(" (%i bits)\n", endBit - startBit); } #ifdef _ONEBIT_COMBO - if (numBitsInMask && - MSG_ReadBits( msg, 1 )) - { //mask changed... + if (numBitsInMask && MSG_ReadBits(msg, 1)) { // mask changed... int newBitMask = MSG_ReadBits(msg, numBitsInMask); int nOneBit = 0; - //we have to go through all the fields again now to match the values - for ( i = 0, field = PSFields ; i < lc ; i++, field++ ) - { - if (field->bits == 1) - { //a 1 bit value, get the sent value from the mask - toF = (int *)( (byte *)to + field->offset ); - *toF = (newBitMask>>nOneBit)&1; + // we have to go through all the fields again now to match the values + for (i = 0, field = PSFields; i < lc; i++, field++) { + if (field->bits == 1) { // a 1 bit value, get the sent value from the mask + toF = (int *)((byte *)to + field->offset); + *toF = (newBitMask >> nOneBit) & 1; nOneBit++; } } @@ -2799,279 +2669,279 @@ int msg_hData[256] = // Q3 TA freq. table. int msg_hData[256] = { -250315, // 0 -41193, // 1 -6292, // 2 -7106, // 3 -3730, // 4 -3750, // 5 -6110, // 6 -23283, // 7 -33317, // 8 -6950, // 9 -7838, // 10 -9714, // 11 -9257, // 12 -17259, // 13 -3949, // 14 -1778, // 15 -8288, // 16 -1604, // 17 -1590, // 18 -1663, // 19 -1100, // 20 -1213, // 21 -1238, // 22 -1134, // 23 -1749, // 24 -1059, // 25 -1246, // 26 -1149, // 27 -1273, // 28 -4486, // 29 -2805, // 30 -3472, // 31 -21819, // 32 -1159, // 33 -1670, // 34 -1066, // 35 -1043, // 36 -1012, // 37 -1053, // 38 -1070, // 39 -1726, // 40 -888, // 41 -1180, // 42 -850, // 43 -960, // 44 -780, // 45 -1752, // 46 -3296, // 47 -10630, // 48 -4514, // 49 -5881, // 50 -2685, // 51 -4650, // 52 -3837, // 53 -2093, // 54 -1867, // 55 -2584, // 56 -1949, // 57 -1972, // 58 -940, // 59 -1134, // 60 -1788, // 61 -1670, // 62 -1206, // 63 -5719, // 64 -6128, // 65 -7222, // 66 -6654, // 67 -3710, // 68 -3795, // 69 -1492, // 70 -1524, // 71 -2215, // 72 -1140, // 73 -1355, // 74 -971, // 75 -2180, // 76 -1248, // 77 -1328, // 78 -1195, // 79 -1770, // 80 -1078, // 81 -1264, // 82 -1266, // 83 -1168, // 84 -965, // 85 -1155, // 86 -1186, // 87 -1347, // 88 -1228, // 89 -1529, // 90 -1600, // 91 -2617, // 92 -2048, // 93 -2546, // 94 -3275, // 95 -2410, // 96 -3585, // 97 -2504, // 98 -2800, // 99 -2675, // 100 -6146, // 101 -3663, // 102 -2840, // 103 -14253, // 104 -3164, // 105 -2221, // 106 -1687, // 107 -3208, // 108 -2739, // 109 -3512, // 110 -4796, // 111 -4091, // 112 -3515, // 113 -5288, // 114 -4016, // 115 -7937, // 116 -6031, // 117 -5360, // 118 -3924, // 119 -4892, // 120 -3743, // 121 -4566, // 122 -4807, // 123 -5852, // 124 -6400, // 125 -6225, // 126 -8291, // 127 -23243, // 128 -7838, // 129 -7073, // 130 -8935, // 131 -5437, // 132 -4483, // 133 -3641, // 134 -5256, // 135 -5312, // 136 -5328, // 137 -5370, // 138 -3492, // 139 -2458, // 140 -1694, // 141 -1821, // 142 -2121, // 143 -1916, // 144 -1149, // 145 -1516, // 146 -1367, // 147 -1236, // 148 -1029, // 149 -1258, // 150 -1104, // 151 -1245, // 152 -1006, // 153 -1149, // 154 -1025, // 155 -1241, // 156 -952, // 157 -1287, // 158 -997, // 159 -1713, // 160 -1009, // 161 -1187, // 162 -879, // 163 -1099, // 164 -929, // 165 -1078, // 166 -951, // 167 -1656, // 168 -930, // 169 -1153, // 170 -1030, // 171 -1262, // 172 -1062, // 173 -1214, // 174 -1060, // 175 -1621, // 176 -930, // 177 -1106, // 178 -912, // 179 -1034, // 180 -892, // 181 -1158, // 182 -990, // 183 -1175, // 184 -850, // 185 -1121, // 186 -903, // 187 -1087, // 188 -920, // 189 -1144, // 190 -1056, // 191 -3462, // 192 -2240, // 193 -4397, // 194 -12136, // 195 -7758, // 196 -1345, // 197 -1307, // 198 -3278, // 199 -1950, // 200 -886, // 201 -1023, // 202 -1112, // 203 -1077, // 204 -1042, // 205 -1061, // 206 -1071, // 207 -1484, // 208 -1001, // 209 -1096, // 210 -915, // 211 -1052, // 212 -995, // 213 -1070, // 214 -876, // 215 -1111, // 216 -851, // 217 -1059, // 218 -805, // 219 -1112, // 220 -923, // 221 -1103, // 222 -817, // 223 -1899, // 224 -1872, // 225 -976, // 226 -841, // 227 -1127, // 228 -956, // 229 -1159, // 230 -950, // 231 -7791, // 232 -954, // 233 -1289, // 234 -933, // 235 -1127, // 236 -3207, // 237 -1020, // 238 -927, // 239 -1355, // 240 -768, // 241 -1040, // 242 -745, // 243 -952, // 244 -805, // 245 -1073, // 246 -740, // 247 -1013, // 248 -805, // 249 -1008, // 250 -796, // 251 -996, // 252 -1057, // 253 -11457, // 254 -13504, // 255 + 250315, // 0 + 41193, // 1 + 6292, // 2 + 7106, // 3 + 3730, // 4 + 3750, // 5 + 6110, // 6 + 23283, // 7 + 33317, // 8 + 6950, // 9 + 7838, // 10 + 9714, // 11 + 9257, // 12 + 17259, // 13 + 3949, // 14 + 1778, // 15 + 8288, // 16 + 1604, // 17 + 1590, // 18 + 1663, // 19 + 1100, // 20 + 1213, // 21 + 1238, // 22 + 1134, // 23 + 1749, // 24 + 1059, // 25 + 1246, // 26 + 1149, // 27 + 1273, // 28 + 4486, // 29 + 2805, // 30 + 3472, // 31 + 21819, // 32 + 1159, // 33 + 1670, // 34 + 1066, // 35 + 1043, // 36 + 1012, // 37 + 1053, // 38 + 1070, // 39 + 1726, // 40 + 888, // 41 + 1180, // 42 + 850, // 43 + 960, // 44 + 780, // 45 + 1752, // 46 + 3296, // 47 + 10630, // 48 + 4514, // 49 + 5881, // 50 + 2685, // 51 + 4650, // 52 + 3837, // 53 + 2093, // 54 + 1867, // 55 + 2584, // 56 + 1949, // 57 + 1972, // 58 + 940, // 59 + 1134, // 60 + 1788, // 61 + 1670, // 62 + 1206, // 63 + 5719, // 64 + 6128, // 65 + 7222, // 66 + 6654, // 67 + 3710, // 68 + 3795, // 69 + 1492, // 70 + 1524, // 71 + 2215, // 72 + 1140, // 73 + 1355, // 74 + 971, // 75 + 2180, // 76 + 1248, // 77 + 1328, // 78 + 1195, // 79 + 1770, // 80 + 1078, // 81 + 1264, // 82 + 1266, // 83 + 1168, // 84 + 965, // 85 + 1155, // 86 + 1186, // 87 + 1347, // 88 + 1228, // 89 + 1529, // 90 + 1600, // 91 + 2617, // 92 + 2048, // 93 + 2546, // 94 + 3275, // 95 + 2410, // 96 + 3585, // 97 + 2504, // 98 + 2800, // 99 + 2675, // 100 + 6146, // 101 + 3663, // 102 + 2840, // 103 + 14253, // 104 + 3164, // 105 + 2221, // 106 + 1687, // 107 + 3208, // 108 + 2739, // 109 + 3512, // 110 + 4796, // 111 + 4091, // 112 + 3515, // 113 + 5288, // 114 + 4016, // 115 + 7937, // 116 + 6031, // 117 + 5360, // 118 + 3924, // 119 + 4892, // 120 + 3743, // 121 + 4566, // 122 + 4807, // 123 + 5852, // 124 + 6400, // 125 + 6225, // 126 + 8291, // 127 + 23243, // 128 + 7838, // 129 + 7073, // 130 + 8935, // 131 + 5437, // 132 + 4483, // 133 + 3641, // 134 + 5256, // 135 + 5312, // 136 + 5328, // 137 + 5370, // 138 + 3492, // 139 + 2458, // 140 + 1694, // 141 + 1821, // 142 + 2121, // 143 + 1916, // 144 + 1149, // 145 + 1516, // 146 + 1367, // 147 + 1236, // 148 + 1029, // 149 + 1258, // 150 + 1104, // 151 + 1245, // 152 + 1006, // 153 + 1149, // 154 + 1025, // 155 + 1241, // 156 + 952, // 157 + 1287, // 158 + 997, // 159 + 1713, // 160 + 1009, // 161 + 1187, // 162 + 879, // 163 + 1099, // 164 + 929, // 165 + 1078, // 166 + 951, // 167 + 1656, // 168 + 930, // 169 + 1153, // 170 + 1030, // 171 + 1262, // 172 + 1062, // 173 + 1214, // 174 + 1060, // 175 + 1621, // 176 + 930, // 177 + 1106, // 178 + 912, // 179 + 1034, // 180 + 892, // 181 + 1158, // 182 + 990, // 183 + 1175, // 184 + 850, // 185 + 1121, // 186 + 903, // 187 + 1087, // 188 + 920, // 189 + 1144, // 190 + 1056, // 191 + 3462, // 192 + 2240, // 193 + 4397, // 194 + 12136, // 195 + 7758, // 196 + 1345, // 197 + 1307, // 198 + 3278, // 199 + 1950, // 200 + 886, // 201 + 1023, // 202 + 1112, // 203 + 1077, // 204 + 1042, // 205 + 1061, // 206 + 1071, // 207 + 1484, // 208 + 1001, // 209 + 1096, // 210 + 915, // 211 + 1052, // 212 + 995, // 213 + 1070, // 214 + 876, // 215 + 1111, // 216 + 851, // 217 + 1059, // 218 + 805, // 219 + 1112, // 220 + 923, // 221 + 1103, // 222 + 817, // 223 + 1899, // 224 + 1872, // 225 + 976, // 226 + 841, // 227 + 1127, // 228 + 956, // 229 + 1159, // 230 + 950, // 231 + 7791, // 232 + 954, // 233 + 1289, // 234 + 933, // 235 + 1127, // 236 + 3207, // 237 + 1020, // 238 + 927, // 239 + 1355, // 240 + 768, // 241 + 1040, // 242 + 745, // 243 + 952, // 244 + 805, // 245 + 1073, // 246 + 740, // 247 + 1013, // 248 + 805, // 249 + 1008, // 250 + 796, // 251 + 996, // 252 + 1057, // 253 + 11457, // 254 + 13504, // 255 }; #ifndef _USINGNEWHUFFTABLE_ void MSG_initHuffman() { - int i,j; + int i, j; #ifdef _NEWHUFFTABLE_ - fp=fopen("c:\\netchan.bin", "a"); + fp = fopen("c:\\netchan.bin", "a"); #endif // _NEWHUFFTABLE_ msgInit = qtrue; Huff_Init(&msgHuff); - for(i=0;i<256;i++) { - for (j=0;jname, field->mCount); field->mCount = 0; } Com_Printf("\nPlayer State Fields:\n"); - numFields = (int)ARRAY_LEN( playerStateFields ); - for ( i = 0, field = playerStateFields ; i < numFields ; i++, field++ ) - { + numFields = (int)ARRAY_LEN(playerStateFields); + for (i = 0, field = playerStateFields; i < numFields; i++, field++) { Com_Printf("%s\t\t%d\n", field->name, field->mCount); field->mCount = 0; } - } -#endif // FINAL_BUILD +#endif // FINAL_BUILD //=========================================================================== diff --git a/codemp/qcommon/net_chan.cpp b/codemp/qcommon/net_chan.cpp index 69ee3ed5cf..5e0be5ab07 100644 --- a/codemp/qcommon/net_chan.cpp +++ b/codemp/qcommon/net_chan.cpp @@ -47,20 +47,17 @@ to the new value before sending out any replies. #include "qcommon/qcommon.h" -#define MAX_PACKETLEN 1400 // max size of a network packet -#define FRAGMENT_SIZE (MAX_PACKETLEN - 100) -#define PACKET_HEADER 10 // two ints and a short +#define MAX_PACKETLEN 1400 // max size of a network packet +#define FRAGMENT_SIZE (MAX_PACKETLEN - 100) +#define PACKET_HEADER 10 // two ints and a short -#define FRAGMENT_BIT (1<<31) +#define FRAGMENT_BIT (1 << 31) -cvar_t *showpackets; -cvar_t *showdrop; -cvar_t *qport; +cvar_t *showpackets; +cvar_t *showdrop; +cvar_t *qport; -static char *netsrcString[2] = { - "client", - "server" -}; +static char *netsrcString[2] = {"client", "server"}; /* =============== @@ -68,11 +65,11 @@ Netchan_Init =============== */ -void Netchan_Init( int port ) { +void Netchan_Init(int port) { port &= 0xffff; - showpackets = Cvar_Get ("showpackets", "0", CVAR_TEMP ); - showdrop = Cvar_Get ("showdrop", "0", CVAR_TEMP ); - qport = Cvar_Get ("net_qport", va("%i", port), CVAR_INIT ); + showpackets = Cvar_Get("showpackets", "0", CVAR_TEMP); + showdrop = Cvar_Get("showdrop", "0", CVAR_TEMP); + qport = Cvar_Get("net_qport", va("%i", port), CVAR_INIT); } /* @@ -82,8 +79,8 @@ Netchan_Setup called to open a channel to a remote system ============== */ -void Netchan_Setup( netsrc_t sock, netchan_t *chan, netadr_t adr, int qport ) { - Com_Memset (chan, 0, sizeof(*chan)); +void Netchan_Setup(netsrc_t sock, netchan_t *chan, netadr_t adr, int qport) { + Com_Memset(chan, 0, sizeof(*chan)); chan->sock = sock; chan->remoteAddress = adr; @@ -99,40 +96,37 @@ Netchan_TransmitNextFragment Send one fragment of the current message ================= */ -void Netchan_TransmitNextFragment( netchan_t *chan ) { - msg_t send; - byte send_buf[MAX_PACKETLEN]; - int fragmentLength; +void Netchan_TransmitNextFragment(netchan_t *chan) { + msg_t send; + byte send_buf[MAX_PACKETLEN]; + int fragmentLength; // write the packet header - MSG_InitOOB (&send, send_buf, sizeof(send_buf)); // <-- only do the oob here + MSG_InitOOB(&send, send_buf, sizeof(send_buf)); // <-- only do the oob here - MSG_WriteLong( &send, chan->outgoingSequence | FRAGMENT_BIT ); + MSG_WriteLong(&send, chan->outgoingSequence | FRAGMENT_BIT); // send the qport if we are a client - if ( chan->sock == NS_CLIENT ) { - MSG_WriteShort( &send, qport->integer ); + if (chan->sock == NS_CLIENT) { + MSG_WriteShort(&send, qport->integer); } // copy the reliable message to the packet first fragmentLength = FRAGMENT_SIZE; - if ( chan->unsentFragmentStart + fragmentLength > chan->unsentLength ) { + if (chan->unsentFragmentStart + fragmentLength > chan->unsentLength) { fragmentLength = chan->unsentLength - chan->unsentFragmentStart; } - MSG_WriteShort( &send, chan->unsentFragmentStart ); - MSG_WriteShort( &send, fragmentLength ); - MSG_WriteData( &send, chan->unsentBuffer + chan->unsentFragmentStart, fragmentLength ); + MSG_WriteShort(&send, chan->unsentFragmentStart); + MSG_WriteShort(&send, fragmentLength); + MSG_WriteData(&send, chan->unsentBuffer + chan->unsentFragmentStart, fragmentLength); // send the datagram - NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress ); - - if ( showpackets->integer ) { - Com_Printf ("%s send %4i : s=%i fragment=%i,%i\n" - , netsrcString[ chan->sock ] - , send.cursize - , chan->outgoingSequence - 1 - , chan->unsentFragmentStart, fragmentLength); + NET_SendPacket(chan->sock, send.cursize, send.data, chan->remoteAddress); + + if (showpackets->integer) { + Com_Printf("%s send %4i : s=%i fragment=%i,%i\n", netsrcString[chan->sock], send.cursize, chan->outgoingSequence - 1, chan->unsentFragmentStart, + fragmentLength); } chan->unsentFragmentStart += fragmentLength; @@ -141,13 +135,12 @@ void Netchan_TransmitNextFragment( netchan_t *chan ) { // that is exactly the fragment length still needs to send // a second packet of zero length so that the other side // can tell there aren't more to follow - if ( chan->unsentFragmentStart == chan->unsentLength && fragmentLength != FRAGMENT_SIZE ) { + if (chan->unsentFragmentStart == chan->unsentLength && fragmentLength != FRAGMENT_SIZE) { chan->outgoingSequence++; chan->unsentFragments = qfalse; } } - /* =============== Netchan_Transmit @@ -156,54 +149,48 @@ Sends a message to a connection, fragmenting if necessary A 0 length will still generate a packet. ================ */ -void Netchan_Transmit( netchan_t *chan, int length, const byte *data ) { - msg_t send; - byte send_buf[MAX_PACKETLEN]; +void Netchan_Transmit(netchan_t *chan, int length, const byte *data) { + msg_t send; + byte send_buf[MAX_PACKETLEN]; - if ( length > MAX_MSGLEN ) { - Com_Error( ERR_DROP, "Netchan_Transmit: length = %i", length ); + if (length > MAX_MSGLEN) { + Com_Error(ERR_DROP, "Netchan_Transmit: length = %i", length); } chan->unsentFragmentStart = 0; - if (chan->unsentFragments) - { - Com_Printf("[ISM] Stomping Unsent Fragments %s\n",netsrcString[ chan->sock ]); + if (chan->unsentFragments) { + Com_Printf("[ISM] Stomping Unsent Fragments %s\n", netsrcString[chan->sock]); } // fragment large reliable messages - if ( length >= FRAGMENT_SIZE ) - { + if (length >= FRAGMENT_SIZE) { chan->unsentFragments = qtrue; chan->unsentLength = length; - Com_Memcpy( chan->unsentBuffer, data, length ); + Com_Memcpy(chan->unsentBuffer, data, length); // only send the first fragment now - Netchan_TransmitNextFragment( chan ); + Netchan_TransmitNextFragment(chan); return; } // write the packet header - MSG_InitOOB (&send, send_buf, sizeof(send_buf)); + MSG_InitOOB(&send, send_buf, sizeof(send_buf)); - MSG_WriteLong( &send, chan->outgoingSequence ); + MSG_WriteLong(&send, chan->outgoingSequence); chan->outgoingSequence++; // send the qport if we are a client - if ( chan->sock == NS_CLIENT ) { - MSG_WriteShort( &send, qport->integer ); + if (chan->sock == NS_CLIENT) { + MSG_WriteShort(&send, qport->integer); } - MSG_WriteData( &send, data, length ); + MSG_WriteData(&send, data, length); // send the datagram - NET_SendPacket( chan->sock, send.cursize, send.data, chan->remoteAddress ); - - if ( showpackets->integer ) { - Com_Printf( "%s send %4i : s=%i ack=%i\n" - , netsrcString[ chan->sock ] - , send.cursize - , chan->outgoingSequence - 1 - , chan->incomingSequence ); + NET_SendPacket(chan->sock, send.cursize, send.data, chan->remoteAddress); + + if (showpackets->integer) { + Com_Printf("%s send %4i : s=%i ack=%i\n", netsrcString[chan->sock], send.cursize, chan->outgoingSequence - 1, chan->incomingSequence); } } @@ -219,18 +206,18 @@ final fragment of a multi-part message, the entire thing will be copied out. ================= */ -qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { - int sequence; - //int qport; - int fragmentStart, fragmentLength; - qboolean fragmented; +qboolean Netchan_Process(netchan_t *chan, msg_t *msg) { + int sequence; + // int qport; + int fragmentStart, fragmentLength; + qboolean fragmented; // get sequence numbers - MSG_BeginReadingOOB( msg ); - sequence = MSG_ReadLong( msg ); + MSG_BeginReadingOOB(msg); + sequence = MSG_ReadLong(msg); // check for fragment information - if ( sequence & FRAGMENT_BIT ) { + if (sequence & FRAGMENT_BIT) { sequence &= ~FRAGMENT_BIT; fragmented = qtrue; } else { @@ -238,43 +225,33 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { } // read the qport if we are a server - if ( chan->sock == NS_SERVER ) { - /*qport = */MSG_ReadShort( msg ); + if (chan->sock == NS_SERVER) { + /*qport = */ MSG_ReadShort(msg); } // read the fragment information - if ( fragmented ) { - fragmentStart = (unsigned short)MSG_ReadShort( msg ); - fragmentLength = (unsigned short)MSG_ReadShort( msg ); + if (fragmented) { + fragmentStart = (unsigned short)MSG_ReadShort(msg); + fragmentLength = (unsigned short)MSG_ReadShort(msg); } else { - fragmentStart = 0; // stop warning message + fragmentStart = 0; // stop warning message fragmentLength = 0; } - if ( showpackets->integer ) { - if ( fragmented ) { - Com_Printf( "%s recv %4i : s=%i fragment=%i,%i\n" - , netsrcString[ chan->sock ] - , msg->cursize - , sequence - , fragmentStart, fragmentLength ); + if (showpackets->integer) { + if (fragmented) { + Com_Printf("%s recv %4i : s=%i fragment=%i,%i\n", netsrcString[chan->sock], msg->cursize, sequence, fragmentStart, fragmentLength); } else { - Com_Printf( "%s recv %4i : s=%i\n" - , netsrcString[ chan->sock ] - , msg->cursize - , sequence ); + Com_Printf("%s recv %4i : s=%i\n", netsrcString[chan->sock], msg->cursize, sequence); } } // // discard out of order or duplicated packets // - if ( sequence <= chan->incomingSequence ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Out of order packet %i at %i\n" - , NET_AdrToString( chan->remoteAddress ) - , sequence - , chan->incomingSequence ); + if (sequence <= chan->incomingSequence) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Out of order packet %i at %i\n", NET_AdrToString(chan->remoteAddress), sequence, chan->incomingSequence); } return qfalse; } @@ -282,41 +259,35 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { // // dropped packets don't keep the message from being used // - chan->dropped = sequence - (chan->incomingSequence+1); - if ( chan->dropped > 0 ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Dropped %i packets at %i\n" - , NET_AdrToString( chan->remoteAddress ) - , chan->dropped - , sequence ); + chan->dropped = sequence - (chan->incomingSequence + 1); + if (chan->dropped > 0) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Dropped %i packets at %i\n", NET_AdrToString(chan->remoteAddress), chan->dropped, sequence); } } - // // if this is the final framgent of a reliable message, // bump incoming_reliable_sequence // - if ( fragmented ) { + if (fragmented) { // make sure we - if ( sequence != chan->fragmentSequence ) { + if (sequence != chan->fragmentSequence) { chan->fragmentSequence = sequence; chan->fragmentLength = 0; } // if we missed a fragment, dump the message - if ( fragmentStart != chan->fragmentLength ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf( "%s:Dropped a message fragment\n" - , NET_AdrToString( chan->remoteAddress ) - , sequence); + if (fragmentStart != chan->fragmentLength) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:Dropped a message fragment\n", NET_AdrToString(chan->remoteAddress), sequence); } // we can still keep the part that we have so far, // so we don't need to clear chan->fragmentLength - //rww - not clearing this will allow us to piece together fragments belonging to other packets - //that happen to have the same sequence (or so it seems). I am just going to clear it and force - //the packet to be dropped. + // rww - not clearing this will allow us to piece together fragments belonging to other packets + // that happen to have the same sequence (or so it seems). I am just going to clear it and force + // the packet to be dropped. // hell yeah we have to dump the whole thing -gil // but I am scared - mw @@ -329,42 +300,37 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { } // copy the fragment to the fragment buffer - if ( fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize || - chan->fragmentLength + fragmentLength > (int)sizeof( chan->fragmentBuffer ) ) { - if ( showdrop->integer || showpackets->integer ) { - Com_Printf ("%s:illegal fragment length\n" - , NET_AdrToString (chan->remoteAddress ) ); + if (fragmentLength < 0 || msg->readcount + fragmentLength > msg->cursize || chan->fragmentLength + fragmentLength > (int)sizeof(chan->fragmentBuffer)) { + if (showdrop->integer || showpackets->integer) { + Com_Printf("%s:illegal fragment length\n", NET_AdrToString(chan->remoteAddress)); } return qfalse; } - Com_Memcpy( chan->fragmentBuffer + chan->fragmentLength, - msg->data + msg->readcount, fragmentLength ); + Com_Memcpy(chan->fragmentBuffer + chan->fragmentLength, msg->data + msg->readcount, fragmentLength); chan->fragmentLength += fragmentLength; // if this wasn't the last fragment, don't process anything - if ( fragmentLength == FRAGMENT_SIZE ) { + if (fragmentLength == FRAGMENT_SIZE) { return qfalse; } - if ( chan->fragmentLength+4 > msg->maxsize ) { - Com_Printf( "%s:fragmentLength %i > msg->maxsize\n" - , NET_AdrToString (chan->remoteAddress ), - chan->fragmentLength+4 ); + if (chan->fragmentLength + 4 > msg->maxsize) { + Com_Printf("%s:fragmentLength %i > msg->maxsize\n", NET_AdrToString(chan->remoteAddress), chan->fragmentLength + 4); return qfalse; } // copy the full message over the partial fragment // make sure the sequence number is still there - *(int *)msg->data = LittleLong( sequence ); + *(int *)msg->data = LittleLong(sequence); - Com_Memcpy( msg->data + 4, chan->fragmentBuffer, chan->fragmentLength ); + Com_Memcpy(msg->data + 4, chan->fragmentBuffer, chan->fragmentLength); msg->cursize = chan->fragmentLength + 4; chan->fragmentLength = 0; - msg->readcount = 4; // past the sequence number - msg->bit = 32; // past the sequence number + msg->readcount = 4; // past the sequence number + msg->bit = 32; // past the sequence number // but I am a wuss -mw // chan->incomingSequence = sequence; // lets not accept any more with this sequence number -gil @@ -379,7 +345,6 @@ qboolean Netchan_Process( netchan_t *chan, msg_t *msg ) { return qtrue; } - //============================================================================== /* @@ -389,46 +354,40 @@ NET_CompareBaseAdrMask Compare without port, and up to the bit number given in netmask. =================== */ -qboolean NET_CompareBaseAdrMask( netadr_t a, netadr_t b, int netmask ) -{ +qboolean NET_CompareBaseAdrMask(netadr_t a, netadr_t b, int netmask) { byte cmpmask, *addra, *addrb; int curbyte; - if ( a.type != b.type ) + if (a.type != b.type) return qfalse; - if ( a.type == NA_LOOPBACK ) + if (a.type == NA_LOOPBACK) return qtrue; - if ( a.type == NA_IP ) - { + if (a.type == NA_IP) { addra = (byte *)&a.ip; addrb = (byte *)&b.ip; - if ( netmask < 0 || netmask > 32 ) + if (netmask < 0 || netmask > 32) netmask = 32; - } - else - { - Com_Printf( "NET_CompareBaseAdr: bad address type\n" ); + } else { + Com_Printf("NET_CompareBaseAdr: bad address type\n"); return qfalse; } curbyte = netmask >> 3; - if ( curbyte && memcmp( addra, addrb, curbyte ) ) + if (curbyte && memcmp(addra, addrb, curbyte)) return qfalse; netmask &= 0x07; - if ( netmask ) - { + if (netmask) { cmpmask = (1 << netmask) - 1; cmpmask <<= 8 - netmask; - if ( (addra[curbyte] & cmpmask) == (addrb[curbyte] & cmpmask) ) + if ((addra[curbyte] & cmpmask) == (addrb[curbyte] & cmpmask)) return qtrue; - } - else + } else return qtrue; return qfalse; @@ -441,55 +400,42 @@ NET_CompareBaseAdr Compares without the port =================== */ -qboolean NET_CompareBaseAdr( netadr_t a, netadr_t b ) -{ - return NET_CompareBaseAdrMask( a, b, -1 ); -} +qboolean NET_CompareBaseAdr(netadr_t a, netadr_t b) { return NET_CompareBaseAdrMask(a, b, -1); } -const char *NET_AdrToString (netadr_t a) -{ - static char s[64]; +const char *NET_AdrToString(netadr_t a) { + static char s[64]; if (a.type == NA_LOOPBACK) { - Com_sprintf (s, sizeof(s), "loopback"); + Com_sprintf(s, sizeof(s), "loopback"); } else if (a.type == NA_BOT) { - Com_sprintf (s, sizeof(s), "bot"); + Com_sprintf(s, sizeof(s), "bot"); } else if (a.type == NA_IP) { - Com_sprintf (s, sizeof(s), "%i.%i.%i.%i:%hu", - a.ip[0], a.ip[1], a.ip[2], a.ip[3], BigShort(a.port)); + Com_sprintf(s, sizeof(s), "%i.%i.%i.%i:%hu", a.ip[0], a.ip[1], a.ip[2], a.ip[3], BigShort(a.port)); } else if (a.type == NA_BAD) { - Com_sprintf (s, sizeof(s), "BAD"); + Com_sprintf(s, sizeof(s), "BAD"); } return s; } - -qboolean NET_CompareAdr (netadr_t a, netadr_t b) -{ +qboolean NET_CompareAdr(netadr_t a, netadr_t b) { if (a.type != b.type) return qfalse; if (a.type == NA_LOOPBACK) return qtrue; - if (a.type == NA_IP) - { + if (a.type == NA_IP) { if ((memcmp(a.ip, b.ip, 4) == 0) && a.port == b.port) return qtrue; return qfalse; } - Com_Printf ("NET_CompareAdr: bad address type\n"); + Com_Printf("NET_CompareAdr: bad address type\n"); return qfalse; } - -qboolean NET_IsLocalAddress( netadr_t adr ) { - return (qboolean)(adr.type == NA_LOOPBACK); -} - - +qboolean NET_IsLocalAddress(netadr_t adr) { return (qboolean)(adr.type == NA_LOOPBACK); } /* ============================================================================= @@ -501,25 +447,23 @@ LOOPBACK BUFFERS FOR LOCAL PLAYER // there needs to be enough loopback messages to hold a complete // gamestate of maximum size -#define MAX_LOOPBACK 16 +#define MAX_LOOPBACK 16 typedef struct loopmsg_s { - byte data[MAX_PACKETLEN]; - int datalen; + byte data[MAX_PACKETLEN]; + int datalen; } loopmsg_t; typedef struct loopback_s { - loopmsg_t msgs[MAX_LOOPBACK]; - int get, send; + loopmsg_t msgs[MAX_LOOPBACK]; + int get, send; } loopback_t; -loopback_t loopbacks[2]; +loopback_t loopbacks[2]; - -qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_message) -{ - int i; - loopback_t *loop; +qboolean NET_GetLoopPacket(netsrc_t sock, netadr_t *net_from, msg_t *net_message) { + int i; + loopback_t *loop; loop = &loopbacks[sock]; @@ -529,54 +473,50 @@ qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, msg_t *net_messag if (loop->get >= loop->send) return qfalse; - i = loop->get & (MAX_LOOPBACK-1); + i = loop->get & (MAX_LOOPBACK - 1); loop->get++; - Com_Memcpy (net_message->data, loop->msgs[i].data, loop->msgs[i].datalen); + Com_Memcpy(net_message->data, loop->msgs[i].data, loop->msgs[i].datalen); net_message->cursize = loop->msgs[i].datalen; - Com_Memset (net_from, 0, sizeof(*net_from)); + Com_Memset(net_from, 0, sizeof(*net_from)); net_from->type = NA_LOOPBACK; return qtrue; - } +void NET_SendLoopPacket(netsrc_t sock, int length, const void *data, netadr_t to) { + int i; + loopback_t *loop; -void NET_SendLoopPacket (netsrc_t sock, int length, const void *data, netadr_t to) -{ - int i; - loopback_t *loop; - - loop = &loopbacks[sock^1]; + loop = &loopbacks[sock ^ 1]; - i = loop->send & (MAX_LOOPBACK-1); + i = loop->send & (MAX_LOOPBACK - 1); loop->send++; - Com_Memcpy (loop->msgs[i].data, data, length); + Com_Memcpy(loop->msgs[i].data, data, length); loop->msgs[i].datalen = length; } //============================================================================= - -void NET_SendPacket( netsrc_t sock, int length, const void *data, netadr_t to ) { +void NET_SendPacket(netsrc_t sock, int length, const void *data, netadr_t to) { // sequenced packets are shown in netchan, so just show oob - if ( showpackets->integer && *(int *)data == -1 ) { - Com_Printf ("send packet %4i\n", length); + if (showpackets->integer && *(int *)data == -1) { + Com_Printf("send packet %4i\n", length); } - if ( to.type == NA_LOOPBACK ) { - NET_SendLoopPacket (sock, length, data, to); + if (to.type == NA_LOOPBACK) { + NET_SendLoopPacket(sock, length, data, to); return; } - if ( to.type == NA_BOT ) { + if (to.type == NA_BOT) { return; } - if ( to.type == NA_BAD ) { + if (to.type == NA_BAD) { return; } - Sys_SendPacket( length, data, to ); + Sys_SendPacket(length, data, to); } /* @@ -586,10 +526,9 @@ NET_OutOfBandPrint Sends a text message in an out-of-band datagram ================ */ -void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, ... ) { - va_list argptr; - char string[MAX_MSGLEN]; - +void QDECL NET_OutOfBandPrint(netsrc_t sock, netadr_t adr, const char *format, ...) { + va_list argptr; + char string[MAX_MSGLEN]; // set the header string[0] = -1; @@ -597,12 +536,12 @@ void QDECL NET_OutOfBandPrint( netsrc_t sock, netadr_t adr, const char *format, string[2] = -1; string[3] = -1; - va_start( argptr, format ); - Q_vsnprintf( string+4, sizeof(string)-4, format, argptr ); - va_end( argptr ); + va_start(argptr, format); + Q_vsnprintf(string + 4, sizeof(string) - 4, format, argptr); + va_end(argptr); // send the datagram - NET_SendPacket( sock, strlen( string ), string, adr ); + NET_SendPacket(sock, strlen(string), string, adr); } /* @@ -612,10 +551,10 @@ NET_OutOfBandPrint Sends a data message in an out-of-band datagram (only used for "connect") ================ */ -void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len ) { - byte string[MAX_MSGLEN*2]; - int i; - msg_t mbuf; +void QDECL NET_OutOfBandData(netsrc_t sock, netadr_t adr, byte *format, int len) { + byte string[MAX_MSGLEN * 2]; + int i; + msg_t mbuf; // set the header string[0] = 0xff; @@ -623,20 +562,17 @@ void QDECL NET_OutOfBandData( netsrc_t sock, netadr_t adr, byte *format, int len string[2] = 0xff; string[3] = 0xff; - for(i=0;itype = NA_LOOPBACK; return qtrue; } // look for a port number - Q_strncpyz( base, s, sizeof( base ) ); - port = strchr( base, ':' ); - if ( port ) { + Q_strncpyz(base, s, sizeof(base)); + port = strchr(base, ':'); + if (port) { *port = '\0'; port++; } - if ( !Sys_StringToAdr( base, a ) ) { + if (!Sys_StringToAdr(base, a)) { a->type = NA_BAD; return qfalse; } // inet_addr returns this if out of range - if ( a->ip[0] == 255 && a->ip[1] == 255 && a->ip[2] == 255 && a->ip[3] == 255 ) { + if (a->ip[0] == 255 && a->ip[1] == 255 && a->ip[2] == 255 && a->ip[3] == 255) { a->type = NA_BAD; return qfalse; } - if ( port ) { - a->port = BigShort( (short)atoi( port ) ); + if (port) { + a->port = BigShort((short)atoi(port)); } else { - a->port = BigShort( PORT_SERVER ); + a->port = BigShort(PORT_SERVER); } return qtrue; } - diff --git a/codemp/qcommon/net_ip.cpp b/codemp/qcommon/net_ip.cpp index bf72ebcc9e..20ec089918 100644 --- a/codemp/qcommon/net_ip.cpp +++ b/codemp/qcommon/net_ip.cpp @@ -25,29 +25,29 @@ along with this program; if not, see . #include "qcommon/qcommon.h" #ifdef _WIN32 - #include +#include - typedef int socklen_t; +typedef int socklen_t; - #undef EAGAIN - #undef EADDRNOTAVAIL - #undef EAFNOSUPPORT - #undef ECONNRESET +#undef EAGAIN +#undef EADDRNOTAVAIL +#undef EAFNOSUPPORT +#undef ECONNRESET - #define EAGAIN WSAEWOULDBLOCK - #define EADDRNOTAVAIL WSAEADDRNOTAVAIL - #define EAFNOSUPPORT WSAEAFNOSUPPORT - #define ECONNRESET WSAECONNRESET +#define EAGAIN WSAEWOULDBLOCK +#define EADDRNOTAVAIL WSAEADDRNOTAVAIL +#define EAFNOSUPPORT WSAEAFNOSUPPORT +#define ECONNRESET WSAECONNRESET - #define socketError WSAGetLastError( ) +#define socketError WSAGetLastError() - static WSADATA winsockdata; - static qboolean winsockInitialized = qfalse; +static WSADATA winsockdata; +static qboolean winsockInitialized = qfalse; #else #if MAC_OS_X_VERSION_MIN_REQUIRED == 1020 - // needed for socklen_t on OSX 10.2 -# define _BSD_SOCKLEN_T_ +// needed for socklen_t on OSX 10.2 +#define _BSD_SOCKLEN_T_ #endif #include @@ -64,7 +64,7 @@ along with this program; if not, see . #include #include #include -#include // for 'struct sockaddr_dl' +#include // for 'struct sockaddr_dl' #endif #ifdef __sun @@ -72,39 +72,39 @@ along with this program; if not, see . #endif typedef int SOCKET; -#define INVALID_SOCKET -1 -#define SOCKET_ERROR -1 -#define closesocket close -#define ioctlsocket ioctl -#define socketError errno +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define closesocket close +#define ioctlsocket ioctl +#define socketError errno #endif static qboolean usingSocks = qfalse; static qboolean networkingEnabled = qfalse; -static cvar_t *net_enabled; -static cvar_t *net_forcenonlocal; +static cvar_t *net_enabled; +static cvar_t *net_forcenonlocal; -static cvar_t *net_socksEnabled; -static cvar_t *net_socksServer; -static cvar_t *net_socksPort; -static cvar_t *net_socksUsername; -static cvar_t *net_socksPassword; +static cvar_t *net_socksEnabled; +static cvar_t *net_socksServer; +static cvar_t *net_socksPort; +static cvar_t *net_socksUsername; +static cvar_t *net_socksPassword; -static cvar_t *net_ip; -static cvar_t *net_port; +static cvar_t *net_ip; +static cvar_t *net_port; -static cvar_t *net_dropsim; +static cvar_t *net_dropsim; -static struct sockaddr_in socksRelayAddr; +static struct sockaddr_in socksRelayAddr; -static SOCKET ip_socket = INVALID_SOCKET; -static SOCKET socks_socket = INVALID_SOCKET; +static SOCKET ip_socket = INVALID_SOCKET; +static SOCKET socks_socket = INVALID_SOCKET; -#define MAX_IPS 16 -static int numIP; -static byte localIP[MAX_IPS][4]; +#define MAX_IPS 16 +static int numIP; +static byte localIP[MAX_IPS][4]; //============================================================================= @@ -113,80 +113,125 @@ static byte localIP[MAX_IPS][4]; NET_ErrorString ==================== */ -char *NET_ErrorString( void ) { +char *NET_ErrorString(void) { #ifdef _WIN32 - switch( socketError ) { - case WSAEINTR: return "WSAEINTR"; - case WSAEBADF: return "WSAEBADF"; - case WSAEACCES: return "WSAEACCES"; - case WSAEDISCON: return "WSAEDISCON"; - case WSAEFAULT: return "WSAEFAULT"; - case WSAEINVAL: return "WSAEINVAL"; - case WSAEMFILE: return "WSAEMFILE"; - case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK"; - case WSAEINPROGRESS: return "WSAEINPROGRESS"; - case WSAEALREADY: return "WSAEALREADY"; - case WSAENOTSOCK: return "WSAENOTSOCK"; - case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ"; - case WSAEMSGSIZE: return "WSAEMSGSIZE"; - case WSAEPROTOTYPE: return "WSAEPROTOTYPE"; - case WSAENOPROTOOPT: return "WSAENOPROTOOPT"; - case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT"; - case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT"; - case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP"; - case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT"; - case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT"; - case WSAEADDRINUSE: return "WSAEADDRINUSE"; - case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL"; - case WSAENETDOWN: return "WSAENETDOWN"; - case WSAENETUNREACH: return "WSAENETUNREACH"; - case WSAENETRESET: return "WSAENETRESET"; - case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR"; - case WSAECONNRESET: return "WSAECONNRESET"; - case WSAENOBUFS: return "WSAENOBUFS"; - case WSAEISCONN: return "WSAEISCONN"; - case WSAENOTCONN: return "WSAENOTCONN"; - case WSAESHUTDOWN: return "WSAESHUTDOWN"; - case WSAETOOMANYREFS: return "WSAETOOMANYREFS"; - case WSAETIMEDOUT: return "WSAETIMEDOUT"; - case WSAECONNREFUSED: return "WSAECONNREFUSED"; - case WSAELOOP: return "WSAELOOP"; - case WSAENAMETOOLONG: return "WSAENAMETOOLONG"; - case WSAEHOSTDOWN: return "WSAEHOSTDOWN"; - case WSASYSNOTREADY: return "WSASYSNOTREADY"; - case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED"; - case WSANOTINITIALISED: return "WSANOTINITIALISED"; - case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND"; - case WSATRY_AGAIN: return "WSATRY_AGAIN"; - case WSANO_RECOVERY: return "WSANO_RECOVERY"; - case WSANO_DATA: return "WSANO_DATA"; - case WSAEHOSTUNREACH: return "WSAEHOSTUNREACH"; - default: return "NO ERROR"; + switch (socketError) { + case WSAEINTR: + return "WSAEINTR"; + case WSAEBADF: + return "WSAEBADF"; + case WSAEACCES: + return "WSAEACCES"; + case WSAEDISCON: + return "WSAEDISCON"; + case WSAEFAULT: + return "WSAEFAULT"; + case WSAEINVAL: + return "WSAEINVAL"; + case WSAEMFILE: + return "WSAEMFILE"; + case WSAEWOULDBLOCK: + return "WSAEWOULDBLOCK"; + case WSAEINPROGRESS: + return "WSAEINPROGRESS"; + case WSAEALREADY: + return "WSAEALREADY"; + case WSAENOTSOCK: + return "WSAENOTSOCK"; + case WSAEDESTADDRREQ: + return "WSAEDESTADDRREQ"; + case WSAEMSGSIZE: + return "WSAEMSGSIZE"; + case WSAEPROTOTYPE: + return "WSAEPROTOTYPE"; + case WSAENOPROTOOPT: + return "WSAENOPROTOOPT"; + case WSAEPROTONOSUPPORT: + return "WSAEPROTONOSUPPORT"; + case WSAESOCKTNOSUPPORT: + return "WSAESOCKTNOSUPPORT"; + case WSAEOPNOTSUPP: + return "WSAEOPNOTSUPP"; + case WSAEPFNOSUPPORT: + return "WSAEPFNOSUPPORT"; + case WSAEAFNOSUPPORT: + return "WSAEAFNOSUPPORT"; + case WSAEADDRINUSE: + return "WSAEADDRINUSE"; + case WSAEADDRNOTAVAIL: + return "WSAEADDRNOTAVAIL"; + case WSAENETDOWN: + return "WSAENETDOWN"; + case WSAENETUNREACH: + return "WSAENETUNREACH"; + case WSAENETRESET: + return "WSAENETRESET"; + case WSAECONNABORTED: + return "WSWSAECONNABORTEDAEINTR"; + case WSAECONNRESET: + return "WSAECONNRESET"; + case WSAENOBUFS: + return "WSAENOBUFS"; + case WSAEISCONN: + return "WSAEISCONN"; + case WSAENOTCONN: + return "WSAENOTCONN"; + case WSAESHUTDOWN: + return "WSAESHUTDOWN"; + case WSAETOOMANYREFS: + return "WSAETOOMANYREFS"; + case WSAETIMEDOUT: + return "WSAETIMEDOUT"; + case WSAECONNREFUSED: + return "WSAECONNREFUSED"; + case WSAELOOP: + return "WSAELOOP"; + case WSAENAMETOOLONG: + return "WSAENAMETOOLONG"; + case WSAEHOSTDOWN: + return "WSAEHOSTDOWN"; + case WSASYSNOTREADY: + return "WSASYSNOTREADY"; + case WSAVERNOTSUPPORTED: + return "WSAVERNOTSUPPORTED"; + case WSANOTINITIALISED: + return "WSANOTINITIALISED"; + case WSAHOST_NOT_FOUND: + return "WSAHOST_NOT_FOUND"; + case WSATRY_AGAIN: + return "WSATRY_AGAIN"; + case WSANO_RECOVERY: + return "WSANO_RECOVERY"; + case WSANO_DATA: + return "WSANO_DATA"; + case WSAEHOSTUNREACH: + return "WSAEHOSTUNREACH"; + default: + return "NO ERROR"; } #else - return strerror ( socketError ); + return strerror(socketError); #endif } -static void NetadrToSockadr( netadr_t *a, struct sockaddr_in *s ) { - memset( s, 0, sizeof(*s) ); +static void NetadrToSockadr(netadr_t *a, struct sockaddr_in *s) { + memset(s, 0, sizeof(*s)); - if( a->type == NA_BROADCAST ) { + if (a->type == NA_BROADCAST) { s->sin_family = AF_INET; s->sin_port = a->port; s->sin_addr.s_addr = INADDR_BROADCAST; - } - else if( a->type == NA_IP ) { + } else if (a->type == NA_IP) { s->sin_family = AF_INET; - memcpy( &s->sin_addr, a->ip, sizeof(s->sin_addr) ); + memcpy(&s->sin_addr, a->ip, sizeof(s->sin_addr)); s->sin_port = a->port; } } -static void SockadrToNetadr( struct sockaddr_in *s, netadr_t *a ) { +static void SockadrToNetadr(struct sockaddr_in *s, netadr_t *a) { assert(s->sin_family == AF_INET); a->type = NA_IP; - memcpy( a->ip, &s->sin_addr, sizeof(a->ip) ); + memcpy(a->ip, &s->sin_addr, sizeof(a->ip)); a->port = s->sin_port; } @@ -195,22 +240,18 @@ static void SockadrToNetadr( struct sockaddr_in *s, netadr_t *a ) { Sys_StringToSockaddr ============= */ -static qboolean Sys_StringToSockaddr( const char *s, struct sockaddr_in *sadr ) -{ - struct hostent *h; +static qboolean Sys_StringToSockaddr(const char *s, struct sockaddr_in *sadr) { + struct hostent *h; - memset( sadr, 0, sizeof( *sadr ) ); + memset(sadr, 0, sizeof(*sadr)); sadr->sin_family = AF_INET; sadr->sin_port = 0; - if( s[0] >= '0' && s[0] <= '9' ) - { + if (s[0] >= '0' && s[0] <= '9') { sadr->sin_addr.s_addr = inet_addr(s); - } - else - { - if( ( h = gethostbyname( s ) ) == 0 ) + } else { + if ((h = gethostbyname(s)) == 0) return qfalse; sadr->sin_addr.s_addr = *(uint32_t *)h->h_addr_list[0]; } @@ -223,14 +264,14 @@ static qboolean Sys_StringToSockaddr( const char *s, struct sockaddr_in *sadr ) Sys_StringToAdr ============= */ -qboolean Sys_StringToAdr( const char *s, netadr_t *a ) { +qboolean Sys_StringToAdr(const char *s, netadr_t *a) { struct sockaddr_in sadr; - if ( !Sys_StringToSockaddr( s, &sadr ) ) { + if (!Sys_StringToSockaddr(s, &sadr)) { return qfalse; } - SockadrToNetadr( &sadr, a ); + SockadrToNetadr(&sadr, a); return qtrue; } @@ -244,38 +285,38 @@ Receive one packet ================== */ #ifdef _DEBUG -int recvfromCount; +int recvfromCount; #endif -qboolean NET_GetPacket( netadr_t *net_from, msg_t *net_message, fd_set *fdr ) { +qboolean NET_GetPacket(netadr_t *net_from, msg_t *net_message, fd_set *fdr) { int ret, err; socklen_t fromlen; struct sockaddr_in from; - if ( ip_socket == INVALID_SOCKET || !FD_ISSET(ip_socket, fdr) ) { + if (ip_socket == INVALID_SOCKET || !FD_ISSET(ip_socket, fdr)) { return qfalse; } - fromlen = sizeof( from ); + fromlen = sizeof(from); #ifdef _DEBUG - recvfromCount++; // performance check + recvfromCount++; // performance check #endif - ret = recvfrom( ip_socket, (char *)net_message->data, net_message->maxsize, 0, (struct sockaddr *)&from, &fromlen ); + ret = recvfrom(ip_socket, (char *)net_message->data, net_message->maxsize, 0, (struct sockaddr *)&from, &fromlen); - if ( ret == SOCKET_ERROR ) { + if (ret == SOCKET_ERROR) { err = socketError; - if( err == EAGAIN || err == ECONNRESET ) + if (err == EAGAIN || err == ECONNRESET) return qfalse; - Com_Printf( "NET_GetPacket: %s\n", NET_ErrorString() ); + Com_Printf("NET_GetPacket: %s\n", NET_ErrorString()); return qfalse; } - memset( from.sin_zero, 0, 8 ); + memset(from.sin_zero, 0, 8); - if ( usingSocks && memcmp( &from, &socksRelayAddr, fromlen ) == 0 ) { - if ( ret < 10 || net_message->data[0] != 0 || net_message->data[1] != 0 || net_message->data[2] != 0 || net_message->data[3] != 1 ) { + if (usingSocks && memcmp(&from, &socksRelayAddr, fromlen) == 0) { + if (ret < 10 || net_message->data[0] != 0 || net_message->data[1] != 0 || net_message->data[2] != 0 || net_message->data[3] != 1) { return qfalse; } net_from->type = NA_IP; @@ -283,16 +324,15 @@ qboolean NET_GetPacket( netadr_t *net_from, msg_t *net_message, fd_set *fdr ) { net_from->ip[1] = net_message->data[5]; net_from->ip[2] = net_message->data[6]; net_from->ip[3] = net_message->data[7]; - memcpy( &net_from->port, &net_message->data[8], 2 ); + memcpy(&net_from->port, &net_message->data[8], 2); net_message->readcount = 10; - } - else { - SockadrToNetadr( &from, net_from ); + } else { + SockadrToNetadr(&from, net_from); net_message->readcount = 0; } - if( ret >= net_message->maxsize ) { - Com_Printf( "Oversize packet from %s\n", NET_AdrToString (*net_from) ); + if (ret >= net_message->maxsize) { + Com_Printf("Oversize packet from %s\n", NET_AdrToString(*net_from)); return qfalse; } @@ -309,48 +349,47 @@ static char socksBuf[4096]; Sys_SendPacket ================== */ -void Sys_SendPacket( int length, const void *data, netadr_t to ) { - int ret; - struct sockaddr_in addr; +void Sys_SendPacket(int length, const void *data, netadr_t to) { + int ret; + struct sockaddr_in addr; - if ( to.type != NA_BROADCAST && to.type != NA_IP ) { - Com_Error( ERR_FATAL, "Sys_SendPacket: bad address type" ); + if (to.type != NA_BROADCAST && to.type != NA_IP) { + Com_Error(ERR_FATAL, "Sys_SendPacket: bad address type"); return; } - if ( ip_socket == INVALID_SOCKET ) { + if (ip_socket == INVALID_SOCKET) { return; } - NetadrToSockadr( &to, &addr ); + NetadrToSockadr(&to, &addr); - if( usingSocks && to.type == NA_IP ) { - socksBuf[0] = 0; // reserved + if (usingSocks && to.type == NA_IP) { + socksBuf[0] = 0; // reserved socksBuf[1] = 0; - socksBuf[2] = 0; // fragment (not fragmented) - socksBuf[3] = 1; // address type: IPV4 - memcpy( &socksBuf[4], &addr.sin_addr, 4 ); - memcpy( &socksBuf[8], &addr.sin_port, 2 ); - memcpy( &socksBuf[10], data, length ); - ret = sendto( ip_socket, socksBuf, length+10, 0, (sockaddr *)&socksRelayAddr, sizeof(socksRelayAddr) ); - } - else { - ret = sendto( ip_socket, (const char *)data, length, 0, (sockaddr *)&addr, sizeof(addr) ); - } - if( ret == SOCKET_ERROR ) { + socksBuf[2] = 0; // fragment (not fragmented) + socksBuf[3] = 1; // address type: IPV4 + memcpy(&socksBuf[4], &addr.sin_addr, 4); + memcpy(&socksBuf[8], &addr.sin_port, 2); + memcpy(&socksBuf[10], data, length); + ret = sendto(ip_socket, socksBuf, length + 10, 0, (sockaddr *)&socksRelayAddr, sizeof(socksRelayAddr)); + } else { + ret = sendto(ip_socket, (const char *)data, length, 0, (sockaddr *)&addr, sizeof(addr)); + } + if (ret == SOCKET_ERROR) { int err = socketError; // wouldblock is silent - if( err == EAGAIN ) { + if (err == EAGAIN) { return; } // some PPP links do not allow broadcasts and return an error - if( err == EADDRNOTAVAIL && to.type == NA_BROADCAST ) { + if (err == EADDRNOTAVAIL && to.type == NA_BROADCAST) { return; } - Com_Printf( "NET_SendPacket: %s\n", NET_ErrorString() ); + Com_Printf("NET_SendPacket: %s\n", NET_ErrorString()); } } @@ -363,39 +402,39 @@ Sys_IsLANAddress LAN clients will have their rate var ignored ================== */ -qboolean Sys_IsLANAddress( netadr_t adr ) { - if ( !net_forcenonlocal ) - net_forcenonlocal = Cvar_Get( "net_forcenonlocal", "0", 0 ); +qboolean Sys_IsLANAddress(netadr_t adr) { + if (!net_forcenonlocal) + net_forcenonlocal = Cvar_Get("net_forcenonlocal", "0", 0); - if ( net_forcenonlocal && net_forcenonlocal->integer ) + if (net_forcenonlocal && net_forcenonlocal->integer) return qfalse; - if( adr.type == NA_LOOPBACK ) + if (adr.type == NA_LOOPBACK) return qtrue; - if( adr.type != NA_IP ) + if (adr.type != NA_IP) return qfalse; // RFC1918: // 10.0.0.0 - 10.255.255.255 (10/8 prefix) // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) - if ( adr.ip[0] == 10 ) + if (adr.ip[0] == 10) return qtrue; - if ( adr.ip[0] == 172 && (adr.ip[1]&0xf0) == 16 ) + if (adr.ip[0] == 172 && (adr.ip[1] & 0xf0) == 16) return qtrue; - if ( adr.ip[0] == 192 && adr.ip[1] == 168 ) + if (adr.ip[0] == 192 && adr.ip[1] == 168) return qtrue; - if ( adr.ip[0] == 127 ) + if (adr.ip[0] == 127) return qtrue; // choose which comparison to use based on the class of the address being tested // any local adresses of a different class than the address being tested will fail based on the first byte // Class C - for ( int i=0; istring ); - if ( h == NULL ) { - Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: %s\n", NET_ErrorString() ); + h = gethostbyname(net_socksServer->string); + if (h == NULL) { + Com_Printf("WARNING: NET_OpenSocks: gethostbyname: %s\n", NET_ErrorString()); return; } - if ( h->h_addrtype != AF_INET ) { - Com_Printf( "WARNING: NET_OpenSocks: gethostbyname: address type was not AF_INET\n" ); + if (h->h_addrtype != AF_INET) { + Com_Printf("WARNING: NET_OpenSocks: gethostbyname: address type was not AF_INET\n"); return; } - memset( &address, 0, sizeof( address ) ); + memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = *(uint32_t *)h->h_addr_list[0]; - address.sin_port = htons( net_socksPort->integer ); + address.sin_port = htons(net_socksPort->integer); - if ( connect( socks_socket, (struct sockaddr *)&address, sizeof( address ) ) == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: connect: %s\n", NET_ErrorString() ); + if (connect(socks_socket, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: connect: %s\n", NET_ErrorString()); return; } // send socks authentication handshake - if ( *net_socksUsername->string || *net_socksPassword->string ) { + if (*net_socksUsername->string || *net_socksPassword->string) { rfc1929 = qtrue; - } - else { + } else { rfc1929 = qfalse; } - buf[0] = 5; // SOCKS version + buf[0] = 5; // SOCKS version // method count - if ( rfc1929 ) { + if (rfc1929) { buf[1] = 2; len = 4; - } - else { + } else { buf[1] = 1; len = 3; } - buf[2] = 0; // method #1 - method id #00: no authentication - if ( rfc1929 ) { - buf[2] = 2; // method #2 - method id #02: username/password + buf[2] = 0; // method #1 - method id #00: no authentication + if (rfc1929) { + buf[2] = 2; // method #2 - method id #02: username/password } - if ( send( socks_socket, (const char *)buf, len, 0 ) == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); + if (send(socks_socket, (const char *)buf, len, 0) == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: send: %s\n", NET_ErrorString()); return; } // get the response - len = recv( socks_socket, (char *)buf, 64, 0 ); - if ( len == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); + len = recv(socks_socket, (char *)buf, 64, 0); + if (len == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: recv: %s\n", NET_ErrorString()); return; } - if ( len != 2 || buf[0] != 5 ) { - Com_Printf( "NET_OpenSocks: bad response\n" ); + if (len != 2 || buf[0] != 5) { + Com_Printf("NET_OpenSocks: bad response\n"); return; } - switch( buf[1] ) { - case 0: // no authentication + switch (buf[1]) { + case 0: // no authentication break; case 2: // username/password authentication break; default: - Com_Printf( "NET_OpenSocks: request denied\n" ); + Com_Printf("NET_OpenSocks: request denied\n"); return; } // do username/password authentication if needed - if ( buf[1] == 2 ) { - int ulen; - int plen; + if (buf[1] == 2) { + int ulen; + int plen; // build the request - ulen = strlen( net_socksUsername->string ); - plen = strlen( net_socksPassword->string ); + ulen = strlen(net_socksUsername->string); + plen = strlen(net_socksPassword->string); - buf[0] = 1; // username/password authentication version + buf[0] = 1; // username/password authentication version buf[1] = ulen; - if ( ulen ) { - memcpy( &buf[2], net_socksUsername->string, ulen ); + if (ulen) { + memcpy(&buf[2], net_socksUsername->string, ulen); } buf[2 + ulen] = plen; - if ( plen ) { - memcpy( &buf[3 + ulen], net_socksPassword->string, plen ); + if (plen) { + memcpy(&buf[3 + ulen], net_socksPassword->string, plen); } // send it - if ( send( socks_socket, (const char *)buf, 3 + ulen + plen, 0 ) == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); + if (send(socks_socket, (const char *)buf, 3 + ulen + plen, 0) == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: send: %s\n", NET_ErrorString()); return; } // get the response - len = recv( socks_socket, (char *)buf, 64, 0 ); - if ( len == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); + len = recv(socks_socket, (char *)buf, 64, 0); + if (len == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: recv: %s\n", NET_ErrorString()); return; } - if ( len != 2 || buf[0] != 1 ) { - Com_Printf( "NET_OpenSocks: bad response\n" ); + if (len != 2 || buf[0] != 1) { + Com_Printf("NET_OpenSocks: bad response\n"); return; } - if ( buf[1] != 0 ) { - Com_Printf( "NET_OpenSocks: authentication failed\n" ); + if (buf[1] != 0) { + Com_Printf("NET_OpenSocks: authentication failed\n"); return; } } // send the UDP associate request - buf[0] = 5; // SOCKS version - buf[1] = 3; // command: UDP associate - buf[2] = 0; // reserved - buf[3] = 1; // address type: IPV4 + buf[0] = 5; // SOCKS version + buf[1] = 3; // command: UDP associate + buf[2] = 0; // reserved + buf[3] = 1; // address type: IPV4 const uint32_t innadr = INADDR_ANY; // 0.0.0.0 - memcpy( &buf[4], &innadr, 4 ); - uint16_t networkOrderPort = htons( port ); // port - memcpy( &buf[8], &networkOrderPort, 2 ); - if ( send( socks_socket, (const char *)buf, 10, 0 ) == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: send: %s\n", NET_ErrorString() ); + memcpy(&buf[4], &innadr, 4); + uint16_t networkOrderPort = htons(port); // port + memcpy(&buf[8], &networkOrderPort, 2); + if (send(socks_socket, (const char *)buf, 10, 0) == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: send: %s\n", NET_ErrorString()); return; } // get the response - len = recv( socks_socket, (char *)buf, 64, 0 ); - if( len == SOCKET_ERROR ) { - Com_Printf( "NET_OpenSocks: recv: %s\n", NET_ErrorString() ); + len = recv(socks_socket, (char *)buf, 64, 0); + if (len == SOCKET_ERROR) { + Com_Printf("NET_OpenSocks: recv: %s\n", NET_ErrorString()); return; } - if( len < 2 || buf[0] != 5 ) { - Com_Printf( "NET_OpenSocks: bad response\n" ); + if (len < 2 || buf[0] != 5) { + Com_Printf("NET_OpenSocks: bad response\n"); return; } // check completion code - if( buf[1] != 0 ) { - Com_Printf( "NET_OpenSocks: request denied: %i\n", buf[1] ); + if (buf[1] != 0) { + Com_Printf("NET_OpenSocks: request denied: %i\n", buf[1]); return; } - if( buf[3] != 1 ) { - Com_Printf( "NET_OpenSocks: relay address is not IPV4: %i\n", buf[3] ); + if (buf[3] != 1) { + Com_Printf("NET_OpenSocks: relay address is not IPV4: %i\n", buf[3]); return; } socksRelayAddr.sin_family = AF_INET; - memcpy( &socksRelayAddr.sin_addr, &buf[4], 4 ); - memcpy( &socksRelayAddr.sin_port, &buf[8], 2 ); - memset( &socksRelayAddr.sin_zero, 0, 8 ); + memcpy(&socksRelayAddr.sin_addr, &buf[4], 4); + memcpy(&socksRelayAddr.sin_port, &buf[8], 2); + memset(&socksRelayAddr.sin_zero, 0, 8); usingSocks = qtrue; } @@ -656,22 +690,19 @@ NET_GetLocalAddress ===================== */ #ifdef MACOS_X -// Don't do a forward mapping from the hostname of the machine to the IP. The reason is that we might have obtained an IP address from DHCP and there might not be any name registered for the machine. On Mac OS X, the machine name defaults to 'localhost' and NetInfo has 127.0.0.1 listed for this name. Instead, we want to get a list of all the IP network interfaces on the machine. -// This code adapted from OmniNetworking. +// Don't do a forward mapping from the hostname of the machine to the IP. The reason is that we might have obtained an IP address from DHCP and there might not +// be any name registered for the machine. On Mac OS X, the machine name defaults to 'localhost' and NetInfo has 127.0.0.1 listed for this name. Instead, we +// want to get a list of all the IP network interfaces on the machine. This code adapted from OmniNetworking. #ifdef _SIZEOF_ADDR_IFREQ - // tjw: OSX 10.4 does not have sa_len - #define IFR_NEXT(ifr) \ - ((struct ifreq *) ((char *) ifr + _SIZEOF_ADDR_IFREQ(*ifr))) +// tjw: OSX 10.4 does not have sa_len +#define IFR_NEXT(ifr) ((struct ifreq *)((char *)ifr + _SIZEOF_ADDR_IFREQ(*ifr))) #else - // tjw: assume that once upon a time some version did have sa_len - #define IFR_NEXT(ifr) \ - ((struct ifreq *) ((char *) (ifr) + sizeof(*(ifr)) + \ - Q_max(0, (int) (ifr)->ifr_addr.sa_len - (int) sizeof((ifr)->ifr_addr)))) +// tjw: assume that once upon a time some version did have sa_len +#define IFR_NEXT(ifr) ((struct ifreq *)((char *)(ifr) + sizeof(*(ifr)) + Q_max(0, (int)(ifr)->ifr_addr.sa_len - (int)sizeof((ifr)->ifr_addr)))) #endif - -void NET_GetLocalAddress( void ) { +void NET_GetLocalAddress(void) { struct ifreq requestBuffer[MAX_IPS], *linkInterface, *inetInterface; struct ifconf ifc; struct ifreq ifr; @@ -700,8 +731,8 @@ void NET_GetLocalAddress( void ) { return; } - linkInterface = (struct ifreq *) ifc.ifc_buf; - while ((char *) linkInterface < &ifc.ifc_buf[ifc.ifc_len]) { + linkInterface = (struct ifreq *)ifc.ifc_buf; + while ((char *)linkInterface < &ifc.ifc_buf[ifc.ifc_len]) { unsigned int nameLength; // The ioctl returns both the entries having the address (AF_INET) @@ -716,11 +747,10 @@ void NET_GetLocalAddress( void ) { // For each AF_LINK entry... if (linkInterface->ifr_addr.sa_family == AF_LINK) { // if there is a matching AF_INET entry - inetInterface = (struct ifreq *) ifc.ifc_buf; - while ((char *) inetInterface < &ifc.ifc_buf[ifc.ifc_len]) { + inetInterface = (struct ifreq *)ifc.ifc_buf; + while ((char *)inetInterface < &ifc.ifc_buf[ifc.ifc_len]) { if (inetInterface->ifr_addr.sa_family == AF_INET && - !strncmp(inetInterface->ifr_name, linkInterface->ifr_name, - sizeof(linkInterface->ifr_name))) { + !strncmp(inetInterface->ifr_name, linkInterface->ifr_name, sizeof(linkInterface->ifr_name))) { for (nameLength = 0; nameLength < IFNAMSIZ; nameLength++) if (!linkInterface->ifr_name[nameLength]) @@ -733,7 +763,8 @@ void NET_GetLocalAddress( void ) { strncpy(ifr.ifr_name, inetInterface->ifr_name, sizeof(ifr.ifr_name)); if (ioctl(interfaceSocket, SIOCGIFADDR, (caddr_t)&ifr) < 0) { Com_Printf("NET_GetLocalAddress: Unable to get local address " - "for interface '%s', errno = %d\n", inetInterface->ifr_name, errno); + "for interface '%s', errno = %d\n", + inetInterface->ifr_name, errno); } else { struct sockaddr_in *sin; int ip; @@ -741,14 +772,12 @@ void NET_GetLocalAddress( void ) { sin = (struct sockaddr_in *)&ifr.ifr_addr; ip = ntohl(sin->sin_addr.s_addr); - localIP[ numIP ][0] = (ip >> 24) & 0xff; - localIP[ numIP ][1] = (ip >> 16) & 0xff; - localIP[ numIP ][2] = (ip >> 8) & 0xff; - localIP[ numIP ][3] = (ip >> 0) & 0xff; - Com_Printf( "IP: %i.%i.%i.%i (%s)\n", - localIP[ numIP ][0], localIP[ numIP ][1], - localIP[ numIP ][2], localIP[ numIP ][3], - inetInterface->ifr_name); + localIP[numIP][0] = (ip >> 24) & 0xff; + localIP[numIP][1] = (ip >> 16) & 0xff; + localIP[numIP][2] = (ip >> 8) & 0xff; + localIP[numIP][3] = (ip >> 0) & 0xff; + Com_Printf("IP: %i.%i.%i.%i (%s)\n", localIP[numIP][0], localIP[numIP][1], localIP[numIP][2], localIP[numIP][3], + inetInterface->ifr_name); numIP++; } } @@ -767,43 +796,42 @@ void NET_GetLocalAddress( void ) { close(interfaceSocket); } #else -void NET_GetLocalAddress( void ) -{ - char hostname[256]; - struct hostent *hostInfo; - char *p; - int ip; - int n; - - // Set this early so we can just return if there is an error +void NET_GetLocalAddress(void) { + char hostname[256]; + struct hostent *hostInfo; + char *p; + int ip; + int n; + + // Set this early so we can just return if there is an error numIP = 0; - if( gethostname( hostname, 256 ) == SOCKET_ERROR ) { + if (gethostname(hostname, 256) == SOCKET_ERROR) { return; } - hostInfo = gethostbyname( hostname ); - if( !hostInfo ) { + hostInfo = gethostbyname(hostname); + if (!hostInfo) { return; } - Com_Printf( "Hostname: %s\n", hostInfo->h_name ); + Com_Printf("Hostname: %s\n", hostInfo->h_name); n = 0; - while( ( p = hostInfo->h_aliases[n++] ) != NULL ) { - Com_Printf( "Alias: %s\n", p ); + while ((p = hostInfo->h_aliases[n++]) != NULL) { + Com_Printf("Alias: %s\n", p); } - if ( hostInfo->h_addrtype != AF_INET ) { + if (hostInfo->h_addrtype != AF_INET) { return; } - while( ( p = hostInfo->h_addr_list[numIP] ) != NULL && numIP < MAX_IPS ) { - ip = ntohl( *(uint32_t *)p ); - localIP[ numIP ][0] = p[0]; - localIP[ numIP ][1] = p[1]; - localIP[ numIP ][2] = p[2]; - localIP[ numIP ][3] = p[3]; - Com_Printf( "IP: %i.%i.%i.%i\n", ( ip >> 24 ) & 0xff, ( ip >> 16 ) & 0xff, ( ip >> 8 ) & 0xff, ip & 0xff ); + while ((p = hostInfo->h_addr_list[numIP]) != NULL && numIP < MAX_IPS) { + ip = ntohl(*(uint32_t *)p); + localIP[numIP][0] = p[0]; + localIP[numIP][1] = p[1]; + localIP[numIP][2] = p[2]; + localIP[numIP][3] = p[3]; + Com_Printf("IP: %i.%i.%i.%i\n", (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff); numIP++; } } @@ -814,8 +842,7 @@ void NET_GetLocalAddress( void ) NET_OpenIP ==================== */ -void NET_OpenIP( void ) -{ +void NET_OpenIP(void) { int port = net_port->integer; int err; @@ -825,23 +852,22 @@ void NET_OpenIP( void ) // dedicated servers can be started without requiring // a different net_port for each one - if ( net_enabled->integer & NET_ENABLEV4 ) { - for ( int i=0 ; i < 10 ; i++ ) { - ip_socket = NET_IPSocket( net_ip->string, port + i, &err ); - if ( ip_socket != INVALID_SOCKET ) { - Cvar_SetValue( "net_port", port + i ); + if (net_enabled->integer & NET_ENABLEV4) { + for (int i = 0; i < 10; i++) { + ip_socket = NET_IPSocket(net_ip->string, port + i, &err); + if (ip_socket != INVALID_SOCKET) { + Cvar_SetValue("net_port", port + i); - if ( net_socksEnabled->integer ) - NET_OpenSocks( port + i ); + if (net_socksEnabled->integer) + NET_OpenSocks(port + i); break; - } - else { - if ( err == EAFNOSUPPORT ) + } else { + if (err == EAFNOSUPPORT) break; } } - if ( ip_socket == INVALID_SOCKET ) - Com_Printf( "WARNING: Couldn't bind to a v4 ip address.\n"); + if (ip_socket == INVALID_SOCKET) + Com_Printf("WARNING: Couldn't bind to a v4 ip address.\n"); } } @@ -852,46 +878,46 @@ void NET_OpenIP( void ) NET_GetCvars ==================== */ -static qboolean NET_GetCvars( void ) { - int modified = 0; +static qboolean NET_GetCvars(void) { + int modified = 0; - net_enabled = Cvar_Get( "net_enabled", "1", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_enabled = Cvar_Get("net_enabled", "1", CVAR_LATCH | CVAR_ARCHIVE_ND); modified = net_enabled->modified; net_enabled->modified = qfalse; - net_forcenonlocal = Cvar_Get( "net_forcenonlocal", "0", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_forcenonlocal = Cvar_Get("net_forcenonlocal", "0", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_forcenonlocal->modified; net_forcenonlocal->modified = qfalse; - net_ip = Cvar_Get( "net_ip", "localhost", CVAR_LATCH ); + net_ip = Cvar_Get("net_ip", "localhost", CVAR_LATCH); modified += net_ip->modified; net_ip->modified = qfalse; - net_port = Cvar_Get( "net_port", XSTRING( PORT_SERVER ), CVAR_LATCH ); + net_port = Cvar_Get("net_port", XSTRING(PORT_SERVER), CVAR_LATCH); modified += net_port->modified; net_port->modified = qfalse; - net_socksEnabled = Cvar_Get( "net_socksEnabled", "0", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_socksEnabled = Cvar_Get("net_socksEnabled", "0", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_socksEnabled->modified; net_socksEnabled->modified = qfalse; - net_socksServer = Cvar_Get( "net_socksServer", "", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_socksServer = Cvar_Get("net_socksServer", "", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_socksServer->modified; net_socksServer->modified = qfalse; - net_socksPort = Cvar_Get( "net_socksPort", "1080", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_socksPort = Cvar_Get("net_socksPort", "1080", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_socksPort->modified; net_socksPort->modified = qfalse; - net_socksUsername = Cvar_Get( "net_socksUsername", "", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_socksUsername = Cvar_Get("net_socksUsername", "", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_socksUsername->modified; net_socksUsername->modified = qfalse; - net_socksPassword = Cvar_Get( "net_socksPassword", "", CVAR_LATCH | CVAR_ARCHIVE_ND ); + net_socksPassword = Cvar_Get("net_socksPassword", "", CVAR_LATCH | CVAR_ARCHIVE_ND); modified += net_socksPassword->modified; net_socksPassword->modified = qfalse; - net_dropsim = Cvar_Get( "net_dropsim", "", CVAR_TEMP); + net_dropsim = Cvar_Get("net_dropsim", "", CVAR_TEMP); return modified ? qtrue : qfalse; } @@ -901,57 +927,54 @@ static qboolean NET_GetCvars( void ) { NET_Config ==================== */ -void NET_Config( qboolean enableNetworking ) { - qboolean modified; - qboolean stop; - qboolean start; +void NET_Config(qboolean enableNetworking) { + qboolean modified; + qboolean stop; + qboolean start; // get any latched changes to cvars modified = NET_GetCvars(); - if ( !net_enabled->integer ) + if (!net_enabled->integer) enableNetworking = qfalse; // if enable state is the same and no cvars were modified, we have nothing to do - if ( enableNetworking == networkingEnabled && !modified ) + if (enableNetworking == networkingEnabled && !modified) return; - if ( enableNetworking == networkingEnabled ) { - if ( enableNetworking ) { + if (enableNetworking == networkingEnabled) { + if (enableNetworking) { stop = qtrue; start = qtrue; - } - else { + } else { stop = qfalse; start = qfalse; } - } - else { - if ( enableNetworking ) { + } else { + if (enableNetworking) { stop = qfalse; start = qtrue; - } - else { + } else { stop = qtrue; start = qfalse; } networkingEnabled = enableNetworking; } - if ( stop ) { - if ( ip_socket != INVALID_SOCKET ) { - closesocket( ip_socket ); + if (stop) { + if (ip_socket != INVALID_SOCKET) { + closesocket(ip_socket); ip_socket = INVALID_SOCKET; } - if ( socks_socket != INVALID_SOCKET ) { - closesocket( socks_socket ); + if (socks_socket != INVALID_SOCKET) { + closesocket(socks_socket); socks_socket = INVALID_SOCKET; } } - if ( start ) { - if ( net_enabled->integer ) + if (start) { + if (net_enabled->integer) NET_OpenIP(); } } @@ -961,21 +984,21 @@ void NET_Config( qboolean enableNetworking ) { NET_Init ==================== */ -void NET_Init( void ) { +void NET_Init(void) { #ifdef _WIN32 - int r = WSAStartup( MAKEWORD( 1, 1 ), &winsockdata ); - if( r ) { - Com_Printf( "WARNING: Winsock initialization failed, returned %d\n", r ); + int r = WSAStartup(MAKEWORD(1, 1), &winsockdata); + if (r) { + Com_Printf("WARNING: Winsock initialization failed, returned %d\n", r); return; } winsockInitialized = qtrue; - Com_Printf( "Winsock Initialized\n" ); + Com_Printf("Winsock Initialized\n"); #endif - NET_Config( qtrue ); + NET_Config(qtrue); - Cmd_AddCommand ("net_restart", NET_Restart_f, "Restart the networking sub-system" ); + Cmd_AddCommand("net_restart", NET_Restart_f, "Restart the networking sub-system"); } /* @@ -983,12 +1006,12 @@ void NET_Init( void ) { NET_Shutdown ==================== */ -void NET_Shutdown( void ) { - if ( !networkingEnabled ) { +void NET_Shutdown(void) { + if (!networkingEnabled) { return; } - NET_Config( qfalse ); + NET_Config(qfalse); #ifdef _WIN32 WSACleanup(); winsockInitialized = qfalse; @@ -1003,31 +1026,26 @@ Called from NET_Sleep which uses select() to determine which sockets have seen a ==================== */ -void NET_Event(fd_set *fdr) -{ +void NET_Event(fd_set *fdr) { byte bufData[MAX_MSGLEN + 1]; netadr_t from; msg_t netmsg; - while(1) - { + while (1) { MSG_Init(&netmsg, bufData, sizeof(bufData)); - if(NET_GetPacket(&from, &netmsg, fdr)) - { - if(net_dropsim->value > 0.0f && net_dropsim->value <= 100.0f) - { + if (NET_GetPacket(&from, &netmsg, fdr)) { + if (net_dropsim->value > 0.0f && net_dropsim->value <= 100.0f) { // com_dropsim->value percent of incoming packets get dropped. - if(rand() < (int) (((double) RAND_MAX) / 100.0 * (double) net_dropsim->value)) - continue; // drop this packet + if (rand() < (int)(((double)RAND_MAX) / 100.0 * (double)net_dropsim->value)) + continue; // drop this packet } - if(com_sv_running->integer) + if (com_sv_running->integer) Com_RunAndTimeServerPacket(&from, &netmsg); else CL_PacketEvent(from, &netmsg); - } - else + } else break; } } @@ -1039,9 +1057,9 @@ NET_Sleep sleeps msec or until net socket is ready ==================== */ -void NET_Sleep( int msec ) { +void NET_Sleep(int msec) { struct timeval timeout; - fd_set fdset; + fd_set fdset; int retval; SOCKET highestfd = INVALID_SOCKET; @@ -1055,8 +1073,7 @@ void NET_Sleep( int msec ) { } #ifdef _WIN32 - if(highestfd == INVALID_SOCKET) - { + if (highestfd == INVALID_SOCKET) { // windows ain't happy when select is called without valid FDs SleepEx(msec, 0); @@ -1064,14 +1081,14 @@ void NET_Sleep( int msec ) { } #endif - timeout.tv_sec = msec/1000; - timeout.tv_usec = (msec%1000)*1000; + timeout.tv_sec = msec / 1000; + timeout.tv_usec = (msec % 1000) * 1000; retval = select(highestfd + 1, &fdset, NULL, NULL, &timeout); - if(retval == SOCKET_ERROR) + if (retval == SOCKET_ERROR) Com_Printf("Warning: select() syscall failed: %s\n", NET_ErrorString()); - else if(retval > 0) + else if (retval > 0) NET_Event(&fdset); } @@ -1080,6 +1097,4 @@ void NET_Sleep( int msec ) { NET_Restart_f ==================== */ -void NET_Restart_f( void ) { - NET_Config( qtrue ); -} +void NET_Restart_f(void) { NET_Config(qtrue); } diff --git a/codemp/qcommon/persistence.cpp b/codemp/qcommon/persistence.cpp index f856af6bdd..2c8ba0bcfb 100644 --- a/codemp/qcommon/persistence.cpp +++ b/codemp/qcommon/persistence.cpp @@ -20,8 +20,7 @@ along with this program; if not, see . #include "qcommon/qcommon.h" -typedef struct persisentData_t -{ +typedef struct persisentData_t { const void *data; size_t size; @@ -31,12 +30,9 @@ typedef struct persisentData_t #define MAX_PERSISENT_DATA_STORES (16) static persisentData_t persistentData[MAX_PERSISENT_DATA_STORES]; -static persisentData_t *FindEmptyStore ( persisentData_t *stores, size_t count ) -{ - for ( size_t i = 0; i < count; i++ ) - { - if ( stores[i].data == NULL ) - { +static persisentData_t *FindEmptyStore(persisentData_t *stores, size_t count) { + for (size_t i = 0; i < count; i++) { + if (stores[i].data == NULL) { return &stores[i]; } } @@ -44,12 +40,9 @@ static persisentData_t *FindEmptyStore ( persisentData_t *stores, size_t count ) return NULL; } -static persisentData_t *FindStoreWithName ( persisentData_t *stores, size_t count, const char *name ) -{ - for ( size_t i = 0; i < count; i++ ) - { - if ( Q_stricmp (stores[i].name, name) == 0 ) - { +static persisentData_t *FindStoreWithName(persisentData_t *stores, size_t count, const char *name) { + for (size_t i = 0; i < count; i++) { + if (Q_stricmp(stores[i].name, name) == 0) { return &stores[i]; } } @@ -57,33 +50,28 @@ static persisentData_t *FindStoreWithName ( persisentData_t *stores, size_t coun return NULL; } -bool PD_Store ( const char *name, const void *data, size_t size ) -{ - persisentData_t *store = FindEmptyStore (persistentData, MAX_PERSISENT_DATA_STORES); - if ( store == NULL ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: No persistent data store found.\n"); +bool PD_Store(const char *name, const void *data, size_t size) { + persisentData_t *store = FindEmptyStore(persistentData, MAX_PERSISENT_DATA_STORES); + if (store == NULL) { + Com_Printf(S_COLOR_YELLOW "WARNING: No persistent data store found.\n"); return false; } store->data = data; store->size = size; - Q_strncpyz (store->name, name, sizeof (store->name)); + Q_strncpyz(store->name, name, sizeof(store->name)); return true; } -const void *PD_Load ( const char *name, size_t *size ) -{ - persisentData_t *store = FindStoreWithName (persistentData, MAX_PERSISENT_DATA_STORES, name); - if ( store == NULL ) - { +const void *PD_Load(const char *name, size_t *size) { + persisentData_t *store = FindStoreWithName(persistentData, MAX_PERSISENT_DATA_STORES, name); + if (store == NULL) { return NULL; } const void *data = store->data; - if ( size != NULL ) - { + if (size != NULL) { *size = store->size; } diff --git a/codemp/qcommon/q_shared.c b/codemp/qcommon/q_shared.c index 74e3ccaff4..2fb5979659 100644 --- a/codemp/qcommon/q_shared.c +++ b/codemp/qcommon/q_shared.c @@ -31,15 +31,11 @@ GetIDForString ------------------------- */ +int GetIDForString(stringID_table_t *table, const char *string) { + int index = 0; -int GetIDForString ( stringID_table_t *table, const char *string ) -{ - int index = 0; - - while ( ( table[index].name != NULL ) && - ( table[index].name[0] != 0 ) ) - { - if ( !Q_stricmp( table[index].name, string ) ) + while ((table[index].name != NULL) && (table[index].name[0] != 0)) { + if (!Q_stricmp(table[index].name, string)) return table[index].id; index++; @@ -54,14 +50,11 @@ GetStringForID ------------------------- */ -const char *GetStringForID( stringID_table_t *table, int id ) -{ - int index = 0; +const char *GetStringForID(stringID_table_t *table, int id) { + int index = 0; - while ( ( table[index].name != NULL ) && - ( table[index].name[0] != 0 ) ) - { - if ( table[index].id == id ) + while ((table[index].name != NULL) && (table[index].name[0] != 0)) { + if (table[index].id == id) return table[index].name; index++; @@ -75,15 +68,13 @@ const char *GetStringForID( stringID_table_t *table, int id ) COM_SkipPath ============ */ -char *COM_SkipPath (char *pathname) -{ - char *last; +char *COM_SkipPath(char *pathname) { + char *last; last = pathname; - while (*pathname) - { - if (*pathname=='/') - last = pathname+1; + while (*pathname) { + if (*pathname == '/') + last = pathname + 1; pathname++; } return last; @@ -94,8 +85,7 @@ char *COM_SkipPath (char *pathname) COM_GetExtension ============ */ -const char *COM_GetExtension( const char *name ) -{ +const char *COM_GetExtension(const char *name) { const char *dot = strrchr(name, '.'), *slash; if (dot && (!(slash = strrchr(name, '/')) || slash < dot)) return dot + 1; @@ -108,14 +98,13 @@ const char *COM_GetExtension( const char *name ) COM_StripExtension ============ */ -void COM_StripExtension( const char *in, char *out, int destsize ) -{ +void COM_StripExtension(const char *in, char *out, int destsize) { const char *dot = strrchr(in, '.'), *slash; if (dot && (!(slash = strrchr(in, '/')) || slash < dot)) - destsize = (destsize < dot-in+1 ? destsize : dot-in+1); + destsize = (destsize < dot - in + 1 ? destsize : dot - in + 1); - if ( in == out && destsize > 1 ) - out[destsize-1] = '\0'; + if (in == out && destsize > 1) + out[destsize - 1] = '\0'; else Q_strncpyz(out, in, destsize); } @@ -127,18 +116,16 @@ COM_CompareExtension string compare the end of the strings and return qtrue if strings match ============ */ -qboolean COM_CompareExtension(const char *in, const char *ext) -{ +qboolean COM_CompareExtension(const char *in, const char *ext) { int inlen, extlen; inlen = strlen(in); extlen = strlen(ext); - if(extlen <= inlen) - { + if (extlen <= inlen) { in += inlen - extlen; - if(!Q_stricmp(in, ext)) + if (!Q_stricmp(in, ext)) return qtrue; } @@ -150,8 +137,7 @@ qboolean COM_CompareExtension(const char *in, const char *ext) COM_DefaultExtension ================== */ -void COM_DefaultExtension( char *path, int maxSize, const char *extension ) -{ +void COM_DefaultExtension(char *path, int maxSize, const char *extension) { const char *dot = strrchr(path, '.'), *slash; if (dot && (!(slash = strrchr(path, '/')) || slash < dot)) return; @@ -167,53 +153,45 @@ PARSING ============================================================================ */ -static char com_token[MAX_TOKEN_CHARS]; -static char com_parsename[MAX_TOKEN_CHARS]; -static int com_lines; -static int com_tokenline; +static char com_token[MAX_TOKEN_CHARS]; +static char com_parsename[MAX_TOKEN_CHARS]; +static int com_lines; +static int com_tokenline; -void COM_BeginParseSession( const char *name ) -{ +void COM_BeginParseSession(const char *name) { com_lines = 1; com_tokenline = 0; Com_sprintf(com_parsename, sizeof(com_parsename), "%s", name); } -int COM_GetCurrentParseLine( void ) -{ - if ( com_tokenline ) - { +int COM_GetCurrentParseLine(void) { + if (com_tokenline) { return com_tokenline; } return com_lines; } -char *COM_Parse( const char **data_p ) -{ - return COM_ParseExt( data_p, qtrue ); -} +char *COM_Parse(const char **data_p) { return COM_ParseExt(data_p, qtrue); } -void COM_ParseError( char *format, ... ) -{ +void COM_ParseError(char *format, ...) { va_list argptr; static char string[4096]; - va_start (argptr, format); - Q_vsnprintf (string, sizeof( string ), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(string, sizeof(string), format, argptr); + va_end(argptr); Com_Printf("ERROR: %s, line %d: %s\n", com_parsename, COM_GetCurrentParseLine(), string); } -void COM_ParseWarning( char *format, ... ) -{ +void COM_ParseWarning(char *format, ...) { va_list argptr; static char string[4096]; - va_start (argptr, format); - Q_vsnprintf (string, sizeof(string), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(string, sizeof(string), format, argptr); + va_end(argptr); Com_Printf("WARNING: %s, line %d: %s\n", com_parsename, COM_GetCurrentParseLine(), string); } @@ -230,14 +208,14 @@ string will be returned if the next token is a newline. ============== */ -const char *SkipWhitespace( const char *data, qboolean *hasNewLines ) { +const char *SkipWhitespace(const char *data, qboolean *hasNewLines) { int c; - while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') { - if( !c ) { + while ((c = *(const unsigned char * /*eurofix*/)data) <= ' ') { + if (!c) { return NULL; } - if( c == '\n' ) { + if (c == '\n') { com_lines++; *hasNewLines = qtrue; } @@ -247,7 +225,7 @@ const char *SkipWhitespace( const char *data, qboolean *hasNewLines ) { return data; } -int COM_Compress( char *data_p ) { +int COM_Compress(char *data_p) { char *in, *out; int c; qboolean newline = qfalse, whitespace = qfalse; @@ -256,22 +234,22 @@ int COM_Compress( char *data_p ) { if (in) { while ((c = *in) != 0) { // skip double slash comments - if ( c == '/' && in[1] == '/' ) { + if (c == '/' && in[1] == '/') { while (*in && *in != '\n') { in++; } - // skip /* */ comments - } else if ( c == '/' && in[1] == '*' ) { - while ( *in && ( *in != '*' || in[1] != '/' ) ) + // skip /* */ comments + } else if (c == '/' && in[1] == '*') { + while (*in && (*in != '*' || in[1] != '/')) in++; - if ( *in ) + if (*in) in += 2; // record when we hit a newline - } else if ( c == '\n' || c == '\r' ) { + } else if (c == '\n' || c == '\r') { newline = qtrue; in++; // record when we hit whitespace - } else if ( c == ' ' || c == '\t') { + } else if (c == ' ' || c == '\t') { whitespace = qtrue; in++; // an actual token @@ -281,7 +259,8 @@ int COM_Compress( char *data_p ) { *out++ = '\n'; newline = qfalse; whitespace = qfalse; - } if (whitespace) { + } + if (whitespace) { *out++ = ' '; whitespace = qfalse; } @@ -316,8 +295,7 @@ int COM_Compress( char *data_p ) { return out - data_p; } -char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) -{ +char *COM_ParseExt(const char **data_p, qboolean allowLineBreaks) { int c = 0, len; qboolean hasNewLines = qfalse; const char *data; @@ -328,23 +306,19 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) com_tokenline = 0; // make sure incoming data is valid - if ( !data ) - { + if (!data) { *data_p = NULL; return com_token; } - while ( 1 ) - { + while (1) { // skip whitespace - data = SkipWhitespace( data, &hasNewLines ); - if ( !data ) - { + data = SkipWhitespace(data, &hasNewLines); + if (!data) { *data_p = NULL; return com_token; } - if ( hasNewLines && !allowLineBreaks ) - { + if (hasNewLines && !allowLineBreaks) { *data_p = data; return com_token; } @@ -352,32 +326,25 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { data += 2; while (*data && *data != '\n') { data++; } } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { + else if (c == '/' && data[1] == '*') { data += 2; - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { - if ( *data == '\n' ) - { + while (*data && (*data != '*' || data[1] != '/')) { + if (*data == '\n') { com_lines++; } data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } @@ -386,24 +353,19 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) com_tokenline = com_lines; // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if ( c == '\n' ) - { + if (c == '\n') { com_lines++; } - if (len < MAX_TOKEN_CHARS - 1) - { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } @@ -411,20 +373,18 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS - 1) - { + do { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32); + } while (c > 32); com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -433,13 +393,11 @@ char *COM_ParseExt( const char **data_p, qboolean allowLineBreaks ) COM_ParseString =============== */ -qboolean COM_ParseString( const char **data, const char **s ) -{ -// *s = COM_ParseExt( data, qtrue ); - *s = COM_ParseExt( data, qfalse ); - if ( s[0] == 0 ) - { - COM_ParseWarning( "COM_ParseString: unexpected EOF" ); +qboolean COM_ParseString(const char **data, const char **s) { + // *s = COM_ParseExt( data, qtrue ); + *s = COM_ParseExt(data, qfalse); + if (s[0] == 0) { + COM_ParseWarning("COM_ParseString: unexpected EOF"); return qtrue; } return qfalse; @@ -450,18 +408,16 @@ qboolean COM_ParseString( const char **data, const char **s ) COM_ParseInt =============== */ -qboolean COM_ParseInt( const char **data, int *i ) -{ - const char *token; - - token = COM_ParseExt( data, qfalse ); - if ( token[0] == 0 ) - { - COM_ParseWarning( "COM_ParseInt: unexpected EOF" ); +qboolean COM_ParseInt(const char **data, int *i) { + const char *token; + + token = COM_ParseExt(data, qfalse); + if (token[0] == 0) { + COM_ParseWarning("COM_ParseInt: unexpected EOF"); return qtrue; } - *i = atoi( token ); + *i = atoi(token); return qfalse; } @@ -470,18 +426,16 @@ qboolean COM_ParseInt( const char **data, int *i ) COM_ParseFloat =============== */ -qboolean COM_ParseFloat( const char **data, float *f ) -{ - const char *token; - - token = COM_ParseExt( data, qfalse ); - if ( token[0] == 0 ) - { - COM_ParseWarning( "COM_ParseFloat: unexpected EOF" ); +qboolean COM_ParseFloat(const char **data, float *f) { + const char *token; + + token = COM_ParseExt(data, qfalse); + if (token[0] == 0) { + COM_ParseWarning("COM_ParseFloat: unexpected EOF"); return qtrue; } - *f = atof( token ); + *f = atof(token); return qfalse; } @@ -490,15 +444,12 @@ qboolean COM_ParseFloat( const char **data, float *f ) COM_ParseVec4 =============== */ -qboolean COM_ParseVec4( const char **buffer, vec4_t *c) -{ +qboolean COM_ParseVec4(const char **buffer, vec4_t *c) { int i; float f; - for (i = 0; i < 4; i++) - { - if (COM_ParseFloat(buffer, &f)) - { + for (i = 0; i < 4; i++) { + if (COM_ParseFloat(buffer, &f)) { return qtrue; } (*c)[i] = f; @@ -511,16 +462,15 @@ qboolean COM_ParseVec4( const char **buffer, vec4_t *c) COM_MatchToken ================== */ -void COM_MatchToken( const char **buf_p, char *match ) { - char *token; +void COM_MatchToken(const char **buf_p, char *match) { + char *token; - token = COM_Parse( buf_p ); - if ( strcmp( token, match ) ) { - Com_Error( ERR_DROP, "MatchToken: %s != %s", token, match ); + token = COM_Parse(buf_p); + if (strcmp(token, match)) { + Com_Error(ERR_DROP, "MatchToken: %s != %s", token, match); } } - /* ================= SkipBracedSection @@ -530,22 +480,21 @@ Skips until a matching close brace is found. Internal brace depths are properly skipped. ================= */ -qboolean SkipBracedSection (const char **program, int depth) { - char *token; +qboolean SkipBracedSection(const char **program, int depth) { + char *token; do { - token = COM_ParseExt( program, qtrue ); - if( token[1] == 0 ) { - if( token[0] == '{' ) { + token = COM_ParseExt(program, qtrue); + if (token[1] == 0) { + if (token[0] == '{') { depth++; - } - else if( token[0] == '}' ) { + } else if (token[0] == '}') { depth--; } } - } while( depth && *program ); + } while (depth && *program); - return (qboolean)( depth == 0 ); + return (qboolean)(depth == 0); } /* @@ -553,17 +502,17 @@ qboolean SkipBracedSection (const char **program, int depth) { SkipRestOfLine ================= */ -void SkipRestOfLine ( const char **data ) { - const char *p; - int c; +void SkipRestOfLine(const char **data) { + const char *p; + int c; p = *data; - if ( !*p ) + if (!*p) return; - while ( (c = *p++) != 0 ) { - if ( c == '\n' ) { + while ((c = *p++) != 0) { + if (c == '\n') { com_lines++; break; } @@ -572,43 +521,42 @@ void SkipRestOfLine ( const char **data ) { *data = p; } +void Parse1DMatrix(const char **buf_p, int x, float *m) { + char *token; + int i; -void Parse1DMatrix (const char **buf_p, int x, float *m) { - char *token; - int i; - - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < x ; i++) { + for (i = 0; i < x; i++) { token = COM_Parse(buf_p); m[i] = atof(token); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } -void Parse2DMatrix (const char **buf_p, int y, int x, float *m) { - int i; +void Parse2DMatrix(const char **buf_p, int y, int x, float *m) { + int i; - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < y ; i++) { - Parse1DMatrix (buf_p, x, m + i * x); + for (i = 0; i < y; i++) { + Parse1DMatrix(buf_p, x, m + i * x); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } -void Parse3DMatrix (const char **buf_p, int z, int y, int x, float *m) { - int i; +void Parse3DMatrix(const char **buf_p, int z, int y, int x, float *m) { + int i; - COM_MatchToken( buf_p, "(" ); + COM_MatchToken(buf_p, "("); - for (i = 0 ; i < z ; i++) { - Parse2DMatrix (buf_p, y, x, m + i * x*y); + for (i = 0; i < z; i++) { + Parse2DMatrix(buf_p, y, x, m + i * x * y); } - COM_MatchToken( buf_p, ")" ); + COM_MatchToken(buf_p, ")"); } /* @@ -616,28 +564,25 @@ void Parse3DMatrix (const char **buf_p, int z, int y, int x, float *m) { Com_HexStrToInt =================== */ -int Com_HexStrToInt( const char *str ) -{ - if ( !str || !str[ 0 ] ) +int Com_HexStrToInt(const char *str) { + if (!str || !str[0]) return -1; // check for hex code - if( str[ 0 ] == '0' && str[ 1 ] == 'x' ) - { - int n = 0; + if (str[0] == '0' && str[1] == 'x') { + int n = 0; size_t i; - for( i = 2; i < strlen( str ); i++ ) - { + for (i = 2; i < strlen(str); i++) { char digit; n *= 16; - digit = tolower( str[ i ] ); + digit = tolower(str[i]); - if( digit >= '0' && digit <= '9' ) + if (digit >= '0' && digit <= '9') digit -= '0'; - else if( digit >= 'a' && digit <= 'f' ) + else if (digit >= 'a' && digit <= 'f') digit = digit - 'a' + 10; else return -1; @@ -659,21 +604,21 @@ int Com_HexStrToInt( const char *str ) ============================================================================ */ -int QDECL Com_sprintf( char *dest, int size, const char *fmt, ...) { - int len; - va_list argptr; +int QDECL Com_sprintf(char *dest, int size, const char *fmt, ...) { + int len; + va_list argptr; - va_start (argptr,fmt); + va_start(argptr, fmt); len = Q_vsnprintf(dest, size, fmt, argptr); - va_end (argptr); + va_end(argptr); - if(len >= size) + if (len >= size) Com_Printf("Com_sprintf: Output length %d too short, require %d bytes.\n", size, len + 1); return len; } -int FloatAsInt( float f ) { +int FloatAsInt(float f) { byteAlias_t fi; fi.f = f; return fi.i; @@ -688,20 +633,19 @@ varargs versions of all text functions. FIXME: make this buffer size safe someday ============ */ -#define MAX_VA_STRING 32000 +#define MAX_VA_STRING 32000 #define MAX_VA_BUFFERS 4 -char * QDECL va( const char *format, ... ) -{ - va_list argptr; - static char string[MAX_VA_BUFFERS][MAX_VA_STRING]; // in case va is called by nested functions - static int index = 0; - char *buf; +char *QDECL va(const char *format, ...) { + va_list argptr; + static char string[MAX_VA_BUFFERS][MAX_VA_STRING]; // in case va is called by nested functions + static int index = 0; + char *buf; - va_start( argptr, format ); + va_start(argptr, format); buf = (char *)&string[index++ & 3]; - Q_vsnprintf( buf, sizeof(*string), format, argptr ); - va_end( argptr ); + Q_vsnprintf(buf, sizeof(*string), format, argptr); + va_end(argptr); return buf; } @@ -713,15 +657,15 @@ Com_TruncateLongString Assumes buffer is atleast TRUNCATE_LENGTH big ============ */ -void Com_TruncateLongString( char *buffer, const char *s ) { - int length = strlen( s ); +void Com_TruncateLongString(char *buffer, const char *s) { + int length = strlen(s); - if ( length <= TRUNCATE_LENGTH ) - Q_strncpyz( buffer, s, TRUNCATE_LENGTH ); + if (length <= TRUNCATE_LENGTH) + Q_strncpyz(buffer, s, TRUNCATE_LENGTH); else { - Q_strncpyz( buffer, s, (TRUNCATE_LENGTH/2) - 3 ); - Q_strcat( buffer, TRUNCATE_LENGTH, " ... " ); - Q_strcat( buffer, TRUNCATE_LENGTH, s + length - (TRUNCATE_LENGTH/2) + 3 ); + Q_strncpyz(buffer, s, (TRUNCATE_LENGTH / 2) - 3); + Q_strcat(buffer, TRUNCATE_LENGTH, " ... "); + Q_strcat(buffer, TRUNCATE_LENGTH, s + length - (TRUNCATE_LENGTH / 2) + 3); } } @@ -742,29 +686,27 @@ key and returns the associated value, or an empty string. FIXME: overflow check? =============== */ -char *Info_ValueForKey( const char *s, const char *key ) { - char pkey[BIG_INFO_KEY]; - static char value[2][BIG_INFO_VALUE]; // use two buffers so compares - // work without stomping on each other - static int valueindex = 0; - char *o; - - if ( !s || !key ) { +char *Info_ValueForKey(const char *s, const char *key) { + char pkey[BIG_INFO_KEY]; + static char value[2][BIG_INFO_VALUE]; // use two buffers so compares + // work without stomping on each other + static int valueindex = 0; + char *o; + + if (!s || !key) { return ""; } - if ( strlen( s ) >= BIG_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" ); + if (strlen(s) >= BIG_INFO_STRING) { + Com_Error(ERR_DROP, "Info_ValueForKey: oversize infostring"); } valueindex ^= 1; if (*s == '\\') s++; - while (1) - { + while (1) { o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return ""; *o++ = *s++; @@ -774,13 +716,12 @@ char *Info_ValueForKey( const char *s, const char *key ) { o = value[valueindex]; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { *o++ = *s++; } *o = 0; - if (!Q_stricmp (key, pkey) ) + if (!Q_stricmp(key, pkey)) return value[valueindex]; if (!*s) @@ -799,20 +740,20 @@ Used to itterate through all the key/value pairs in an info string Return qfalse if we discover the infostring is invalid =================== */ -qboolean Info_NextPair( const char **head, char *key, char *value ) { +qboolean Info_NextPair(const char **head, char *key, char *value) { char *o; const char *s = *head; - if ( *s == '\\' ) + if (*s == '\\') s++; key[0] = 0; value[0] = 0; o = key; - while ( *s != '\\' ) { - if ( !*s ) { + while (*s != '\\') { + if (!*s) { key[0] = 0; - *head = s; + *head = s; return qtrue; } *o++ = *s++; @@ -822,11 +763,11 @@ qboolean Info_NextPair( const char **head, char *key, char *value ) { // If they key is empty at this point with a slash after it // then this is considered invalid, possibly an attempt at hacked userinfo strings - if ( !key[0] ) + if (!key[0]) return qfalse; o = value; - while ( *s != '\\' && *s ) { + while (*s != '\\' && *s) { *o++ = *s++; } *o = 0; @@ -841,28 +782,26 @@ qboolean Info_NextPair( const char **head, char *key, char *value ) { Info_RemoveKey =================== */ -void Info_RemoveKey( char *s, const char *key ) { - char *start = NULL, *o = NULL; - char pkey[MAX_INFO_KEY] = {0}; - char value[MAX_INFO_VALUE] = {0}; +void Info_RemoveKey(char *s, const char *key) { + char *start = NULL, *o = NULL; + char pkey[MAX_INFO_KEY] = {0}; + char value[MAX_INFO_VALUE] = {0}; - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" ); + if (strlen(s) >= MAX_INFO_STRING) { + Com_Error(ERR_DROP, "Info_RemoveKey: oversize infostring"); return; } - if (strchr (key, '\\')) { + if (strchr(key, '\\')) { return; } - while (1) - { + while (1) { start = s; if (*s == '\\') s++; o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return; *o++ = *s++; @@ -871,18 +810,16 @@ void Info_RemoveKey( char *s, const char *key ) { s++; o = value; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; - //OJKNOTE: static analysis pointed out pkey may not be null-terminated - if (!strcmp (key, pkey) ) - { - memmove(start, s, strlen(s) + 1); // remove this part + // OJKNOTE: static analysis pointed out pkey may not be null-terminated + if (!strcmp(key, pkey)) { + memmove(start, s, strlen(s) + 1); // remove this part return; } @@ -896,30 +833,28 @@ void Info_RemoveKey( char *s, const char *key ) { Info_RemoveKey_Big =================== */ -void Info_RemoveKey_Big( char *s, const char *key ) { - char *start; - static char pkey[BIG_INFO_KEY], value[BIG_INFO_VALUE]; - char *o; +void Info_RemoveKey_Big(char *s, const char *key) { + char *start; + static char pkey[BIG_INFO_KEY], value[BIG_INFO_VALUE]; + char *o; pkey[0] = value[0] = '\0'; - if ( strlen( s ) >= BIG_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_RemoveKey_Big: oversize infostring" ); + if (strlen(s) >= BIG_INFO_STRING) { + Com_Error(ERR_DROP, "Info_RemoveKey_Big: oversize infostring"); return; } - if (strchr (key, '\\')) { + if (strchr(key, '\\')) { return; } - while (1) - { + while (1) { start = s; if (*s == '\\') s++; o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return; *o++ = *s++; @@ -928,25 +863,22 @@ void Info_RemoveKey_Big( char *s, const char *key ) { s++; o = value; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; - //OJKNOTE: static analysis pointed out pkey may not be null-terminated - if (!strcmp (key, pkey) ) - { - memmove(start, s, strlen(s) + 1); // remove this part + // OJKNOTE: static analysis pointed out pkey may not be null-terminated + if (!strcmp(key, pkey)) { + memmove(start, s, strlen(s) + 1); // remove this part return; } if (!*s) return; } - } /* @@ -957,18 +889,17 @@ Some characters are illegal in info strings because they can mess up the server's parsing ================== */ -qboolean Info_Validate( const char *s ) { +qboolean Info_Validate(const char *s) { const char *c = s; - while ( *c != '\0' ) - { - if( !Q_isprint( *c ) ) + while (*c != '\0') { + if (!Q_isprint(*c)) return qfalse; - if( *c == '\"' ) + if (*c == '\"') return qfalse; - if( *c == ';' ) + if (*c == ';') return qfalse; ++c; @@ -984,37 +915,34 @@ Info_SetValueForKey Changes or adds a key/value pair ================== */ -void Info_SetValueForKey( char *s, const char *key, const char *value ) { - char newi[MAX_INFO_STRING]; - const char* blacklist = "\\;\""; +void Info_SetValueForKey(char *s, const char *key, const char *value) { + char newi[MAX_INFO_STRING]; + const char *blacklist = "\\;\""; - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" ); + if (strlen(s) >= MAX_INFO_STRING) { + Com_Error(ERR_DROP, "Info_SetValueForKey: oversize infostring"); } - for(; *blacklist; ++blacklist) - { - if (strchr (key, *blacklist) || strchr (value, *blacklist)) - { - Com_Printf (S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); + for (; *blacklist; ++blacklist) { + if (strchr(key, *blacklist) || strchr(value, *blacklist)) { + Com_Printf(S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); return; } } - Info_RemoveKey (s, key); + Info_RemoveKey(s, key); if (!value || !strlen(value)) return; - Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value); + Com_sprintf(newi, sizeof(newi), "\\%s\\%s", key, value); - if (strlen(newi) + strlen(s) >= MAX_INFO_STRING) - { - Com_Printf ("Info string length exceeded: %s\n", s); + if (strlen(newi) + strlen(s) >= MAX_INFO_STRING) { + Com_Printf("Info string length exceeded: %s\n", s); return; } - strcat (newi, s); - strcpy (s, newi); + strcat(newi, s); + strcpy(s, newi); } /* @@ -1025,36 +953,33 @@ Changes or adds a key/value pair Includes and retains zero-length values ================== */ -void Info_SetValueForKey_Big( char *s, const char *key, const char *value ) { - char newi[BIG_INFO_STRING]; - const char* blacklist = "\\;\""; +void Info_SetValueForKey_Big(char *s, const char *key, const char *value) { + char newi[BIG_INFO_STRING]; + const char *blacklist = "\\;\""; - if ( strlen( s ) >= BIG_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_SetValueForKey_Big: oversize infostring" ); + if (strlen(s) >= BIG_INFO_STRING) { + Com_Error(ERR_DROP, "Info_SetValueForKey_Big: oversize infostring"); } - for(; *blacklist; ++blacklist) - { - if (strchr (key, *blacklist) || strchr (value, *blacklist)) - { - Com_Printf (S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); + for (; *blacklist; ++blacklist) { + if (strchr(key, *blacklist) || strchr(value, *blacklist)) { + Com_Printf(S_COLOR_YELLOW "Can't use keys or values with a '%c': %s = %s\n", *blacklist, key, value); return; } } - Info_RemoveKey_Big (s, key); + Info_RemoveKey_Big(s, key); if (!value) return; - Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value); + Com_sprintf(newi, sizeof(newi), "\\%s\\%s", key, value); - if (strlen(newi) + strlen(s) >= BIG_INFO_STRING) - { - Com_Printf ("BIG Info string length exceeded\n"); + if (strlen(newi) + strlen(s) >= BIG_INFO_STRING) { + Com_Printf("BIG Info string length exceeded\n"); return; } - strcat (s, newi); + strcat(s, newi); } /* @@ -1062,11 +987,11 @@ void Info_SetValueForKey_Big( char *s, const char *key, const char *value ) { Com_CharIsOneOfCharset ================== */ -static qboolean Com_CharIsOneOfCharset( char c, char *set ) { +static qboolean Com_CharIsOneOfCharset(char c, char *set) { size_t i; - for ( i=0; i. #include #include -typedef std::vector vStrings_t; -typedef std::vector vInts_t; +typedef std::vector vStrings_t; +typedef std::vector vInts_t; // /////////////////////////////////////////////// -cvar_t *se_language = NULL; -cvar_t *se_debug = NULL; -cvar_t *sp_leet = NULL; // kept as 'sp_' for JK2 compat. +cvar_t *se_language = NULL; +cvar_t *se_debug = NULL; +cvar_t *sp_leet = NULL; // kept as 'sp_' for JK2 compat. -#define __DEBUGOUT(_string) Com_OPrintf("%s",_string) -#define __ASSERT(_blah) assert(_blah) +#define __DEBUGOUT(_string) Com_OPrintf("%s", _string) +#define __ASSERT(_blah) assert(_blah) -typedef struct SE_Entry_s -{ - std::string m_strString; - std::string m_strDebug; // english and/or "#same", used for debugging only. Also prefixed by "SE:" to show which strings go through StringEd (ie aren't hardwired) - int m_iFlags; +typedef struct SE_Entry_s { + std::string m_strString; + std::string + m_strDebug; // english and/or "#same", used for debugging only. Also prefixed by "SE:" to show which strings go through StringEd (ie aren't hardwired) + int m_iFlags; - SE_Entry_s() - { - m_iFlags = 0; - } + SE_Entry_s() { m_iFlags = 0; } } SE_Entry_t; +typedef std::map mapStringEntries_t; -typedef std::map mapStringEntries_t; - -class CStringEdPackage -{ -private: - - SE_BOOL m_bEndMarkerFound_ParseOnly; - std::string m_strCurrentEntryRef_ParseOnly; - std::string m_strCurrentEntryEnglish_ParseOnly; - std::string m_strCurrentFileRef_ParseOnly; - std::string m_strLoadingLanguage_ParseOnly; // eg "german" - SE_BOOL m_bLoadingEnglish_ParseOnly; - -public: +class CStringEdPackage { + private: + SE_BOOL m_bEndMarkerFound_ParseOnly; + std::string m_strCurrentEntryRef_ParseOnly; + std::string m_strCurrentEntryEnglish_ParseOnly; + std::string m_strCurrentFileRef_ParseOnly; + std::string m_strLoadingLanguage_ParseOnly; // eg "german" + SE_BOOL m_bLoadingEnglish_ParseOnly; - CStringEdPackage() - { - Clear( SE_FALSE ); - } + public: + CStringEdPackage() { Clear(SE_FALSE); } - ~CStringEdPackage() - { - Clear( SE_FALSE ); - } + ~CStringEdPackage() { Clear(SE_FALSE); } - mapStringEntries_t m_StringEntries; // needs to be in public space now - SE_BOOL m_bLoadDebug; // "" + mapStringEntries_t m_StringEntries; // needs to be in public space now + SE_BOOL m_bLoadDebug; // "" // // flag stuff... // - std::vector m_vstrFlagNames; - std::map m_mapFlagMasks; - - void Clear( SE_BOOL bChangingLanguages ); - void SetupNewFileParse( const char *psFileName, SE_BOOL bLoadDebug ); - SE_BOOL ReadLine( const char *&psParsePos, char *psDest ); - const char *ParseLine( const char *psLine ); - int GetFlagMask( const char *psFlagName ); - const char *ExtractLanguageFromPath( const char *psFileName ); - SE_BOOL EndMarkerFoundDuringParse( void ) - { - return m_bEndMarkerFound_ParseOnly; - } - -private: - - void AddEntry( const char *psLocalReference ); - int GetNumStrings(void); - void SetString( const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug ); - SE_BOOL SetReference( int iIndex, const char *psNewString ); - void AddFlagReference( const char *psLocalReference, const char *psFlagName ); + std::vector m_vstrFlagNames; + std::map m_mapFlagMasks; + + void Clear(SE_BOOL bChangingLanguages); + void SetupNewFileParse(const char *psFileName, SE_BOOL bLoadDebug); + SE_BOOL ReadLine(const char *&psParsePos, char *psDest); + const char *ParseLine(const char *psLine); + int GetFlagMask(const char *psFlagName); + const char *ExtractLanguageFromPath(const char *psFileName); + SE_BOOL EndMarkerFoundDuringParse(void) { return m_bEndMarkerFound_ParseOnly; } + + private: + void AddEntry(const char *psLocalReference); + int GetNumStrings(void); + void SetString(const char *psLocalReference, const char *psNewString, SE_BOOL bEnglishDebug); + SE_BOOL SetReference(int iIndex, const char *psNewString); + void AddFlagReference(const char *psLocalReference, const char *psFlagName); const char *GetCurrentFileName(void); - const char *GetCurrentReference_ParseOnly( void ); - SE_BOOL CheckLineForKeyword( const char *psKeyword, const char *&psLine); - const char *InsideQuotes( const char *psLine ); - const char *ConvertCRLiterals_Read( const char *psString ); - void REMKill( char *psBuffer ); - char *Filename_PathOnly( const char *psFilename ); - char *Filename_WithoutPath(const char *psFilename); - char *Filename_WithoutExt(const char *psFilename); + const char *GetCurrentReference_ParseOnly(void); + SE_BOOL CheckLineForKeyword(const char *psKeyword, const char *&psLine); + const char *InsideQuotes(const char *psLine); + const char *ConvertCRLiterals_Read(const char *psString); + void REMKill(char *psBuffer); + char *Filename_PathOnly(const char *psFilename); + char *Filename_WithoutPath(const char *psFilename); + char *Filename_WithoutExt(const char *psFilename); }; CStringEdPackage TheStringPackage; - -void CStringEdPackage::Clear( SE_BOOL bChangingLanguages ) -{ +void CStringEdPackage::Clear(SE_BOOL bChangingLanguages) { m_StringEntries.clear(); - if ( !bChangingLanguages ) - { + if (!bChangingLanguages) { // if we're changing languages, then I'm going to leave these alone. This is to do with any (potentially) cached // flag bitmasks on the game side. It shouldn't matter since all files are written out at once using the build // command in StringEd. But if ever someone changed a file by hand, or added one, or whatever, and it had a @@ -166,53 +146,45 @@ void CStringEdPackage::Clear( SE_BOOL bChangingLanguages ) // } - - // loses anything after the path (if any), (eg) "dir/name.bmp" becomes "dir" // (copes with either slash-scheme for names) // // (normally I'd call another function for this, but this is supposed to be engine-independent, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_PathOnly(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_PathOnly(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p1= strrchr(sString,'\\'); - char *p2= strrchr(sString,'/'); - char *p = (p1>p2)?p1:p2; + char *p1 = strrchr(sString, '\\'); + char *p2 = strrchr(sString, '/'); + char *p = (p1 > p2) ? p1 : p2; if (p) - *p=0; + *p = 0; return sString; } - // returns (eg) "dir/name" for "dir/name.bmp" // (copes with either slash-scheme for names) // // (normally I'd call another function for this, but this is supposed to be engine-independent, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; - strcpy(sString,psFilename); + strcpy(sString, psFilename); - char *p = strrchr(sString,'.'); - char *p2= strrchr(sString,'\\'); - char *p3= strrchr(sString,'/'); + char *p = strrchr(sString, '.'); + char *p2 = strrchr(sString, '\\'); + char *p3 = strrchr(sString, '/'); // special check, make sure the first suffix we found from the end wasn't just a directory suffix (eg on a path'd filename with no extension anyway) // - if (p && - (p2==0 || (p2 && p>p2)) && - (p3==0 || (p3 && p>p3)) - ) - *p=0; + if (p && (p2 == 0 || (p2 && p > p2)) && (p3 == 0 || (p3 && p > p3))) + *p = 0; return sString; } @@ -223,59 +195,47 @@ char *CStringEdPackage::Filename_WithoutExt(const char *psFilename) // (normally I'd call another function for this, but this is supposed to be engine-independent, // so a certain amount of re-invention of the wheel is to be expected...) // -char *CStringEdPackage::Filename_WithoutPath(const char *psFilename) -{ - static char sString[ iSE_MAX_FILENAME_LENGTH ]; +char *CStringEdPackage::Filename_WithoutPath(const char *psFilename) { + static char sString[iSE_MAX_FILENAME_LENGTH]; const char *psCopyPos = psFilename; - while (*psFilename) - { + while (*psFilename) { if (*psFilename == '/' || *psFilename == '\\') - psCopyPos = psFilename+1; + psCopyPos = psFilename + 1; psFilename++; } - strcpy(sString,psCopyPos); + strcpy(sString, psCopyPos); return sString; } +const char *CStringEdPackage::ExtractLanguageFromPath(const char *psFileName) { return Filename_WithoutPath(Filename_PathOnly(psFileName)); } -const char *CStringEdPackage::ExtractLanguageFromPath( const char *psFileName ) -{ - return Filename_WithoutPath( Filename_PathOnly( psFileName ) ); -} - - -void CStringEdPackage::SetupNewFileParse( const char *psFileName, SE_BOOL bLoadDebug ) -{ - char sString[ iSE_MAX_FILENAME_LENGTH ]; +void CStringEdPackage::SetupNewFileParse(const char *psFileName, SE_BOOL bLoadDebug) { + char sString[iSE_MAX_FILENAME_LENGTH]; - strcpy(sString, Filename_WithoutPath( Filename_WithoutExt( psFileName ) )); + strcpy(sString, Filename_WithoutPath(Filename_WithoutExt(psFileName))); Q_strupr(sString); - m_strCurrentFileRef_ParseOnly = sString; // eg "OBJECTIVES" - m_strLoadingLanguage_ParseOnly = ExtractLanguageFromPath( psFileName ); - m_bLoadingEnglish_ParseOnly = (!Q_stricmp( m_strLoadingLanguage_ParseOnly.c_str(), "english" )) ? SE_TRUE : SE_FALSE; + m_strCurrentFileRef_ParseOnly = sString; // eg "OBJECTIVES" + m_strLoadingLanguage_ParseOnly = ExtractLanguageFromPath(psFileName); + m_bLoadingEnglish_ParseOnly = (!Q_stricmp(m_strLoadingLanguage_ParseOnly.c_str(), "english")) ? SE_TRUE : SE_FALSE; m_bLoadDebug = bLoadDebug; } - // returns SE_TRUE if supplied keyword found at line start (and advances supplied ptr past any whitespace to next arg (or line end if none), // // else returns SE_FALSE... // -SE_BOOL CStringEdPackage::CheckLineForKeyword( const char *psKeyword, const char *&psLine) -{ - if (!Q_stricmpn(psKeyword, psLine, strlen(psKeyword)) ) - { +SE_BOOL CStringEdPackage::CheckLineForKeyword(const char *psKeyword, const char *&psLine) { + if (!Q_stricmpn(psKeyword, psLine, strlen(psKeyword))) { psLine += strlen(psKeyword); // skip whitespace to arrive at next item... // - while ( *psLine == '\t' || *psLine == ' ' ) - { + while (*psLine == '\t' || *psLine == ' ') { psLine++; } return SE_TRUE; @@ -287,68 +247,57 @@ SE_BOOL CStringEdPackage::CheckLineForKeyword( const char *psKeyword, const char // change "\n" to '\n' (i.e. 2-byte char-string to 1-byte ctrl-code)... // (or "\r\n" in editor) // -const char *CStringEdPackage::ConvertCRLiterals_Read( const char *psString ) -{ +const char *CStringEdPackage::ConvertCRLiterals_Read(const char *psString) { static std::string str; str = psString; int iLoc; - while ( (iLoc = str.find("\\n")) != -1 ) - { - str[iLoc ] = '\n'; - str.erase( iLoc+1,1 ); + while ((iLoc = str.find("\\n")) != -1) { + str[iLoc] = '\n'; + str.erase(iLoc + 1, 1); } return str.c_str(); } - // kill off any "//" onwards part in the line, but NOT if it's inside a quoted string... // -void CStringEdPackage::REMKill( char *psBuffer ) -{ +void CStringEdPackage::REMKill(char *psBuffer) { char *psScanPos = psBuffer; char *p; int iDoubleQuotesSoFar = 0; // scan forwards in case there are more than one (and the first is inside quotes)... // - while ( (p=strstr(psScanPos,"//")) != NULL) - { + while ((p = strstr(psScanPos, "//")) != NULL) { // count the number of double quotes before this point, if odd number, then we're inside quotes... // int iDoubleQuoteCount = iDoubleQuotesSoFar; - for (int i=0; i=0 && isspace(psScanPos[iWhiteSpaceScanPos])) - { + int iWhiteSpaceScanPos = strlen(psScanPos) - 1; + while (iWhiteSpaceScanPos >= 0 && isspace(psScanPos[iWhiteSpaceScanPos])) { psScanPos[iWhiteSpaceScanPos--] = '\0'; } } return; - } - else - { + } else { // inside quotes (blast), oh well, skip past and keep scanning... // - psScanPos = p+1; + psScanPos = p + 1; iDoubleQuotesSoFar = iDoubleQuoteCount; } } @@ -356,24 +305,18 @@ void CStringEdPackage::REMKill( char *psBuffer ) // returns true while new lines available to be read... // -SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) -{ - if (psParsePos[0]) - { +SE_BOOL CStringEdPackage::ReadLine(const char *&psParsePos, char *psDest) { + if (psParsePos[0]) { const char *psLineEnd = strchr(psParsePos, '\n'); - if (psLineEnd) - { + if (psLineEnd) { int iCharsToCopy = (psLineEnd - psParsePos); strncpy(psDest, psParsePos, iCharsToCopy); - psDest[iCharsToCopy] = '\0'; + psDest[iCharsToCopy] = '\0'; psParsePos += iCharsToCopy; - while (*psParsePos && strchr("\r\n",*psParsePos)) - { - psParsePos++; // skip over CR or CR/LF pairs + while (*psParsePos && strchr("\r\n", *psParsePos)) { + psParsePos++; // skip over CR or CR/LF pairs } - } - else - { + } else { // last line... // strcpy(psDest, psParsePos); @@ -382,15 +325,13 @@ SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) // clean up the line... // - if (psDest[0]) - { - int iWhiteSpaceScanPos = strlen(psDest)-1; - while (iWhiteSpaceScanPos>=0 && isspace(psDest[iWhiteSpaceScanPos])) - { + if (psDest[0]) { + int iWhiteSpaceScanPos = strlen(psDest) - 1; + while (iWhiteSpaceScanPos >= 0 && isspace(psDest[iWhiteSpaceScanPos])) { psDest[iWhiteSpaceScanPos--] = '\0'; } - REMKill( psDest ); + REMKill(psDest); } return SE_TRUE; } @@ -400,25 +341,22 @@ SE_BOOL CStringEdPackage::ReadLine( const char *&psParsePos, char *psDest ) // remove any outside quotes from this supplied line, plus any leading or trailing whitespace... // -const char *CStringEdPackage::InsideQuotes( const char *psLine ) -{ +const char *CStringEdPackage::InsideQuotes(const char *psLine) { // I *could* replace this string object with a declared array, but wasn't sure how big to leave it, and it'd have to // be static as well, hence permanent. (problem on consoles?) // - static std::string str; - str = ""; // do NOT join to above line + static std::string str; + str = ""; // do NOT join to above line // skip any leading whitespace... // - while (*psLine == ' ' || *psLine == '\t') - { + while (*psLine == ' ' || *psLine == '\t') { psLine++; } // skip any leading quote... // - if (*psLine == '"') - { + if (*psLine == '"') { psLine++; } @@ -426,22 +364,17 @@ const char *CStringEdPackage::InsideQuotes( const char *psLine ) // str = psLine; - if (psLine[0]) - { + if (psLine[0]) { // lose any trailing whitespace... // - while ( str.c_str()[ strlen(str.c_str()) -1 ] == ' ' || - str.c_str()[ strlen(str.c_str()) -1 ] == '\t' - ) - { - str.erase( strlen(str.c_str()) -1, 1); + while (str.c_str()[strlen(str.c_str()) - 1] == ' ' || str.c_str()[strlen(str.c_str()) - 1] == '\t') { + str.erase(strlen(str.c_str()) - 1, 1); } // lose any trailing quote... // - if (str.c_str()[ strlen(str.c_str()) -1 ] == '"') - { - str.erase( strlen(str.c_str()) -1, 1); + if (str.c_str()[strlen(str.c_str()) - 1] == '"') { + str.erase(strlen(str.c_str()) - 1, 1); } } @@ -450,14 +383,11 @@ const char *CStringEdPackage::InsideQuotes( const char *psLine ) return str.c_str(); } - // returns flag bitmask (eg 00000010b), else 0 for not found // -int CStringEdPackage::GetFlagMask( const char *psFlagName ) -{ - std::map ::iterator itFlag = m_mapFlagMasks.find( psFlagName ); - if ( itFlag != m_mapFlagMasks.end() ) - { +int CStringEdPackage::GetFlagMask(const char *psFlagName) { + std::map::iterator itFlag = m_mapFlagMasks.find(psFlagName); + if (itFlag != m_mapFlagMasks.end()) { int &iMask = (*itFlag).second; return iMask; } @@ -465,24 +395,20 @@ int CStringEdPackage::GetFlagMask( const char *psFlagName ) return 0; } - -void CStringEdPackage::AddFlagReference( const char *psLocalReference, const char *psFlagName ) -{ +void CStringEdPackage::AddFlagReference(const char *psLocalReference, const char *psFlagName) { // add the flag to the list of known ones... // - int iMask = GetFlagMask( psFlagName ); - if (iMask == 0) - { - m_vstrFlagNames.push_back( psFlagName ); - iMask = 1 << (m_vstrFlagNames.size()-1); - m_mapFlagMasks[ psFlagName ] = iMask; + int iMask = GetFlagMask(psFlagName); + if (iMask == 0) { + m_vstrFlagNames.push_back(psFlagName); + iMask = 1 << (m_vstrFlagNames.size() - 1); + m_mapFlagMasks[psFlagName] = iMask; } // // then add the reference to this flag to the currently-parsed reference... // - mapStringEntries_t::iterator itEntry = m_StringEntries.find( va("%s_%s",m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ); - if (itEntry != m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = m_StringEntries.find(va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)); + if (itEntry != m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; Entry.m_iFlags |= iMask; } @@ -495,10 +421,9 @@ void CStringEdPackage::AddFlagReference( const char *psLocalReference, const cha // New bit, instead of static buffer (since XBox guys are desperately short of mem) I return a malloc'd buffer now, // so remember to free it! // -static char *CopeWithDumbStringData( const char *psSentence, const char *psThisLanguage ) -{ - const int iBufferSize = strlen(psSentence)*3; // *3 to allow for expansion of anything even stupid string consisting entirely of elipsis chars - char *psNewString = (char *) Z_Malloc(iBufferSize, TAG_TEMP_WORKSPACE, qfalse); +static char *CopeWithDumbStringData(const char *psSentence, const char *psThisLanguage) { + const int iBufferSize = strlen(psSentence) * 3; // *3 to allow for expansion of anything even stupid string consisting entirely of elipsis chars + char *psNewString = (char *)Z_Malloc(iBufferSize, TAG_TEMP_WORKSPACE, qfalse); Q_strncpyz(psNewString, psSentence, iBufferSize); // this is annoying, I have to just guess at which languages to do it for (ie NOT ASIAN/MBCS!!!) since the @@ -508,78 +433,65 @@ static char *CopeWithDumbStringData( const char *psSentence, const char *psThisL // Ok, bollocks to it, this will have to do. Any other languages that come later and have bugs in their text can // get fixed by them typing it in properly in the first place... // - if ( !Q_stricmp( psThisLanguage, "ENGLISH" ) || - !Q_stricmp( psThisLanguage, "FRENCH" ) || - !Q_stricmp( psThisLanguage, "GERMAN" ) || - !Q_stricmp( psThisLanguage, "ITALIAN" ) || - !Q_stricmp( psThisLanguage, "SPANISH" ) || - !Q_stricmp( psThisLanguage, "POLISH" ) || - !Q_stricmp( psThisLanguage, "RUSSIAN" ) ) - { + if (!Q_stricmp(psThisLanguage, "ENGLISH") || !Q_stricmp(psThisLanguage, "FRENCH") || !Q_stricmp(psThisLanguage, "GERMAN") || + !Q_stricmp(psThisLanguage, "ITALIAN") || !Q_stricmp(psThisLanguage, "SPANISH") || !Q_stricmp(psThisLanguage, "POLISH") || + !Q_stricmp(psThisLanguage, "RUSSIAN")) { char *p; - // strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" - while ((p=strchr(psNewString,0x92))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x92),va("%c",0x27)); // "'" + while ((p = strchr(psNewString, 0x92)) != NULL) // "rich" (and illegal) apostrophe { *p = 0x27; } - // strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' - while ((p=strchr(psNewString,0x93))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x93),"\""); // smart quotes -> '"' + while ((p = strchr(psNewString, 0x93)) != NULL) { *p = '"'; } - // strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' - while ((p=strchr(psNewString,0x94))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x94),"\""); // smart quotes -> '"' + while ((p = strchr(psNewString, 0x94)) != NULL) { *p = '"'; } - // strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop - while ((p=strchr(psNewString,0x0B))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x0B),"."); // full stop + while ((p = strchr(psNewString, 0x0B)) != NULL) { *p = '.'; } - // strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." - while ((p=strchr(psNewString,0x85))!=NULL) // "rich" (and illegal) apostrophe + // strXLS_Speech.Replace(va("%c",0x85),"..."); // "..."-char -> 3-char "..." + while ((p = strchr(psNewString, 0x85)) != NULL) // "rich" (and illegal) apostrophe { - memmove(p+2,p,strlen(p)); + memmove(p + 2, p, strlen(p)); *p++ = '.'; *p++ = '.'; - *p = '.'; + *p = '.'; } - // strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" - while ((p=strchr(psNewString,0x91))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x91),va("%c",0x27)); // "'" + while ((p = strchr(psNewString, 0x91)) != NULL) { *p = 0x27; } - // strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" - while ((p=strchr(psNewString,0x96))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x96),va("%c",0x2D)); // "-" + while ((p = strchr(psNewString, 0x96)) != NULL) { *p = 0x2D; } - // strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" - while ((p=strchr(psNewString,0x97))!=NULL) - { + // strXLS_Speech.Replace(va("%c",0x97),va("%c",0x2D)); // "-" + while ((p = strchr(psNewString, 0x97)) != NULL) { *p = 0x2D; } // bug fix for picky grammatical errors, replace "?." with "? " // - while ((p=strstr(psNewString,"?."))!=NULL) - { + while ((p = strstr(psNewString, "?.")) != NULL) { p[1] = ' '; } // StripEd and our print code don't support tabs... // - while ((p=strchr(psNewString,0x09))!=NULL) - { + while ((p = strchr(psNewString, 0x09)) != NULL) { *p = ' '; } } @@ -589,150 +501,112 @@ static char *CopeWithDumbStringData( const char *psSentence, const char *psThisL // return is either NULL for good else error message to display... // -const char *CStringEdPackage::ParseLine( const char *psLine ) -{ +const char *CStringEdPackage::ParseLine(const char *psLine) { const char *psErrorMessage = NULL; - if (psLine) - { - if (CheckLineForKeyword( sSE_KEYWORD_VERSION, psLine )) - { + if (psLine) { + if (CheckLineForKeyword(sSE_KEYWORD_VERSION, psLine)) { // VERSION "1" // - const char *psVersionNumber = InsideQuotes( psLine ); - int iVersionNumber = atoi( psVersionNumber ); + const char *psVersionNumber = InsideQuotes(psLine); + int iVersionNumber = atoi(psVersionNumber); - if (iVersionNumber != iSE_VERSION) - { + if (iVersionNumber != iSE_VERSION) { psErrorMessage = va("Unexpected version number %d, expecting %d!\n", iVersionNumber, iSE_VERSION); } - } - else - if ( CheckLineForKeyword(sSE_KEYWORD_CONFIG, psLine) - || CheckLineForKeyword(sSE_KEYWORD_FILENOTES, psLine) - || CheckLineForKeyword(sSE_KEYWORD_NOTES, psLine) - ) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_CONFIG, psLine) || CheckLineForKeyword(sSE_KEYWORD_FILENOTES, psLine) || + CheckLineForKeyword(sSE_KEYWORD_NOTES, psLine)) { // not used ingame, but need to absorb the token - } - else - if (CheckLineForKeyword(sSE_KEYWORD_REFERENCE, psLine)) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_REFERENCE, psLine)) { // REFERENCE GUARD_GOOD_TO_SEE_YOU // - const char *psLocalReference = InsideQuotes( psLine ); - AddEntry( psLocalReference ); - } - else - if (CheckLineForKeyword(sSE_KEYWORD_FLAGS, psLine)) - { + const char *psLocalReference = InsideQuotes(psLine); + AddEntry(psLocalReference); + } else if (CheckLineForKeyword(sSE_KEYWORD_FLAGS, psLine)) { // FLAGS FLAG_CAPTION FLAG_TYPEMATIC // const char *psReference = GetCurrentReference_ParseOnly(); - if (psReference[0]) - { + if (psReference[0]) { static const char sSeperators[] = " \t"; - char sFlags[1024]={0}; // 1024 chars should be enough to store 8 flag names - strncpy(sFlags, psLine, sizeof(sFlags)-1); - char *psToken = strtok( sFlags, sSeperators ); - while( psToken != NULL ) - { + char sFlags[1024] = {0}; // 1024 chars should be enough to store 8 flag names + strncpy(sFlags, psLine, sizeof(sFlags) - 1); + char *psToken = strtok(sFlags, sSeperators); + while (psToken != NULL) { // psToken = flag name (in caps) // - Q_strupr(psToken); // jic - AddFlagReference( psReference, psToken ); + Q_strupr(psToken); // jic + AddFlagReference(psReference, psToken); // read next flag for this string... // - psToken = strtok( NULL, sSeperators ); + psToken = strtok(NULL, sSeperators); } - } - else - { + } else { psErrorMessage = "Error parsing file: Unexpected \"" sSE_KEYWORD_FLAGS "\"\n"; } - } - else - if (CheckLineForKeyword(sSE_KEYWORD_ENDMARKER, psLine)) - { + } else if (CheckLineForKeyword(sSE_KEYWORD_ENDMARKER, psLine)) { // ENDMARKER // - m_bEndMarkerFound_ParseOnly = SE_TRUE; // the only major error checking I bother to do (for file truncation) - } - else - if (!Q_stricmpn(sSE_KEYWORD_LANG, psLine, strlen(sSE_KEYWORD_LANG))) - { + m_bEndMarkerFound_ParseOnly = SE_TRUE; // the only major error checking I bother to do (for file truncation) + } else if (!Q_stricmpn(sSE_KEYWORD_LANG, psLine, strlen(sSE_KEYWORD_LANG))) { // LANG_ENGLISH "GUARD: Good to see you, sir. Taylor is waiting for you in the clean tent. We need to get you suited up. " // const char *psReference = GetCurrentReference_ParseOnly(); - if ( psReference[0] ) - { + if (psReference[0]) { psLine += strlen(sSE_KEYWORD_LANG); // what language is this?... // const char *psWordEnd = psLine; - while (*psWordEnd && *psWordEnd != ' ' && *psWordEnd != '\t') - { + while (*psWordEnd && *psWordEnd != ' ' && *psWordEnd != '\t') { psWordEnd++; } - char sThisLanguage[1024]={0}; + char sThisLanguage[1024] = {0}; size_t iCharsToCopy = psWordEnd - psLine; - if (iCharsToCopy > sizeof(sThisLanguage)-1) - { - iCharsToCopy = sizeof(sThisLanguage)-1; + if (iCharsToCopy > sizeof(sThisLanguage) - 1) { + iCharsToCopy = sizeof(sThisLanguage) - 1; } - strncpy(sThisLanguage, psLine, iCharsToCopy); // already declared as {0} so no need to zero-cap dest buffer + strncpy(sThisLanguage, psLine, iCharsToCopy); // already declared as {0} so no need to zero-cap dest buffer psLine += strlen(sThisLanguage); - const char *_psSentence = ConvertCRLiterals_Read( InsideQuotes( psLine ) ); + const char *_psSentence = ConvertCRLiterals_Read(InsideQuotes(psLine)); // Dammit, I hate having to do crap like this just because other people mess up and put // stupid data in their text, so I have to cope with it. // // note hackery with _psSentence and psSentence because of const-ness. bleurgh. Just don't ask. // - char *psSentence = CopeWithDumbStringData( _psSentence, sThisLanguage ); + char *psSentence = CopeWithDumbStringData(_psSentence, sThisLanguage); - if ( m_bLoadingEnglish_ParseOnly ) - { + if (m_bLoadingEnglish_ParseOnly) { // if loading just "english", then go ahead and store it... // - SetString( psReference, psSentence, SE_FALSE ); - } - else - { + SetString(psReference, psSentence, SE_FALSE); + } else { // if loading a foreign language... // - SE_BOOL bSentenceIsEnglish = (!Q_stricmp(sThisLanguage,"english")) ? SE_TRUE: SE_FALSE; // see whether this is the english master or not + SE_BOOL bSentenceIsEnglish = (!Q_stricmp(sThisLanguage, "english")) ? SE_TRUE : SE_FALSE; // see whether this is the english master or not // this check can be omitted, I'm just being extra careful here... // - if ( !bSentenceIsEnglish ) - { + if (!bSentenceIsEnglish) { // basically this is just checking that an .STE file override is the same language as the .STR... // - if (Q_stricmp( m_strLoadingLanguage_ParseOnly.c_str(), sThisLanguage )) - { + if (Q_stricmp(m_strLoadingLanguage_ParseOnly.c_str(), sThisLanguage)) { psErrorMessage = va("Language \"%s\" found when expecting \"%s\"!\n", sThisLanguage, m_strLoadingLanguage_ParseOnly.c_str()); } } - if (!psErrorMessage) - { - SetString( psReference, psSentence, bSentenceIsEnglish ); + if (!psErrorMessage) { + SetString(psReference, psSentence, bSentenceIsEnglish); } } - Z_Free( psSentence ); - } - else - { + Z_Free(psSentence); + } else { psErrorMessage = "Error parsing file: Unexpected \"" sSE_KEYWORD_LANG "\"\n"; } - } - else - { + } else { psErrorMessage = va("Unknown keyword at linestart: \"%s\"\n", psLine); } } @@ -742,143 +616,111 @@ const char *CStringEdPackage::ParseLine( const char *psLine ) // returns reference of string being parsed, else "" for none. // -const char *CStringEdPackage::GetCurrentReference_ParseOnly( void ) -{ - return m_strCurrentEntryRef_ParseOnly.c_str(); -} +const char *CStringEdPackage::GetCurrentReference_ParseOnly(void) { return m_strCurrentEntryRef_ParseOnly.c_str(); } // add new string entry (during parse) // -void CStringEdPackage::AddEntry( const char *psLocalReference ) -{ +void CStringEdPackage::AddEntry(const char *psLocalReference) { // the reason I don't just assign it anyway is because the optional .STE override files don't contain flags, // and therefore would wipe out the parsed flags of the .STR file... // - mapStringEntries_t::iterator itEntry = m_StringEntries.find( va("%s_%s",m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ); - if (itEntry == m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = m_StringEntries.find(va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)); + if (itEntry == m_StringEntries.end()) { SE_Entry_t SE_Entry; - m_StringEntries[ va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference) ] = SE_Entry; + m_StringEntries[va("%s_%s", m_strCurrentFileRef_ParseOnly.c_str(), psLocalReference)] = SE_Entry; } m_strCurrentEntryRef_ParseOnly = psLocalReference; } -const char *Leetify( const char *psString ) -{ +const char *Leetify(const char *psString) { static std::string str; str = psString; - if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally + if (sp_leet->integer == 42) // very specific test, so you won't hit it accidentally { - static const - char cReplace[]={ 'o','0','l','1','e','3','a','4','s','5','t','7','i','!','h','#', - 'O','0','L','1','E','3','A','4','S','5','T','7','I','!','H','#' // laziness because of strchr() - }; + static const char cReplace[] = { + 'o', '0', 'l', '1', 'e', '3', 'a', '4', 's', '5', 't', '7', 'i', '!', 'h', '#', + 'O', '0', 'L', '1', 'E', '3', 'A', '4', 'S', '5', 'T', '7', 'I', '!', 'H', '#' // laziness because of strchr() + }; char *p; - for (size_t i=0; i -> set<> erasure checking etc + // strlwr(sTemp); // just for consistancy and set<> -> set<> erasure checking etc return sTemp; } @@ -921,122 +759,100 @@ static const char *SE_GetFoundFile( std::string &strResult ) // // return is either NULL for good else error message to display... // -const char *SE_Load( const char *psFileName, SE_BOOL bLoadDebug = SE_TRUE, SE_BOOL bFailIsCritical = SE_TRUE ) -{ +const char *SE_Load(const char *psFileName, SE_BOOL bLoadDebug = SE_TRUE, SE_BOOL bFailIsCritical = SE_TRUE) { //////////////////////////////////////////////////// // // ingame here tends to pass in names without paths, but I expect them when doing a language load, so... // - char sTemp[1000]={0}; - if (!strchr(psFileName,'/')) - { - strcpy(sTemp,sSE_STRINGS_DIR); - strcat(sTemp,"/"); - if (se_language) - { - strcat(sTemp,se_language->string); - strcat(sTemp,"/"); + char sTemp[1000] = {0}; + if (!strchr(psFileName, '/')) { + strcpy(sTemp, sSE_STRINGS_DIR); + strcat(sTemp, "/"); + if (se_language) { + strcat(sTemp, se_language->string); + strcat(sTemp, "/"); } } - strcat(sTemp,psFileName); - COM_DefaultExtension( sTemp, sizeof(sTemp), sSE_INGAME_FILE_EXTENSION); + strcat(sTemp, psFileName); + COM_DefaultExtension(sTemp, sizeof(sTemp), sSE_INGAME_FILE_EXTENSION); psFileName = &sTemp[0]; // //////////////////////////////////////////////////// - - const char *psErrorMessage = SE_Load_Actual( psFileName, bLoadDebug, SE_FALSE ); + const char *psErrorMessage = SE_Load_Actual(psFileName, bLoadDebug, SE_FALSE); // check for any corresponding / overriding .STE files and load them afterwards... // - if ( !psErrorMessage ) - { - char sFileName[ iSE_MAX_FILENAME_LENGTH ]; - strncpy( sFileName, psFileName, sizeof(sFileName)-1 ); - sFileName[ sizeof(sFileName)-1 ] = '\0'; - char *p = strrchr( sFileName, '.' ); - if (p && strlen(p) == strlen(sSE_EXPORT_FILE_EXTENSION)) - { - strcpy( p, sSE_EXPORT_FILE_EXTENSION ); - - psErrorMessage = SE_Load_Actual( sFileName, bLoadDebug, SE_TRUE ); + if (!psErrorMessage) { + char sFileName[iSE_MAX_FILENAME_LENGTH]; + strncpy(sFileName, psFileName, sizeof(sFileName) - 1); + sFileName[sizeof(sFileName) - 1] = '\0'; + char *p = strrchr(sFileName, '.'); + if (p && strlen(p) == strlen(sSE_EXPORT_FILE_EXTENSION)) { + strcpy(p, sSE_EXPORT_FILE_EXTENSION); + + psErrorMessage = SE_Load_Actual(sFileName, bLoadDebug, SE_TRUE); } } - if (psErrorMessage) - { - if (bFailIsCritical) - { - // TheStringPackage.Clear(TRUE); // Will we want to do this? Any errors that arise should be fixed immediately - Com_Error( ERR_DROP, "SE_Load(): Couldn't load \"%s\"!\n\nError: \"%s\"\n", psFileName, psErrorMessage ); - } - else - { - Com_DPrintf(S_COLOR_YELLOW "SE_Load(): Couldn't load \"%s\"!\n", psFileName ); + if (psErrorMessage) { + if (bFailIsCritical) { + // TheStringPackage.Clear(TRUE); // Will we want to do this? Any errors that arise should be fixed immediately + Com_Error(ERR_DROP, "SE_Load(): Couldn't load \"%s\"!\n\nError: \"%s\"\n", psFileName, psErrorMessage); + } else { + Com_DPrintf(S_COLOR_YELLOW "SE_Load(): Couldn't load \"%s\"!\n", psFileName); } } return psErrorMessage; } - // convenience-function for the main GetString call... // -const char *SE_GetString( const char *psPackageReference, const char *psStringReference) -{ - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long +const char *SE_GetString(const char *psPackageReference, const char *psStringReference) { + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - Com_sprintf(sReference,sizeof(sReference),"%s_%s", psPackageReference, psStringReference); + Com_sprintf(sReference, sizeof(sReference), "%s_%s", psPackageReference, psStringReference); - return SE_GetString( Q_strupr(sReference) ); + return SE_GetString(Q_strupr(sReference)); } - -const char *SE_GetString( const char *psPackageAndStringReference ) -{ - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - assert(strlen(psPackageAndStringReference) < sizeof(sReference) ); - Q_strncpyz(sReference, psPackageAndStringReference, sizeof(sReference) ); +const char *SE_GetString(const char *psPackageAndStringReference) { + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long + assert(strlen(psPackageAndStringReference) < sizeof(sReference)); + Q_strncpyz(sReference, psPackageAndStringReference, sizeof(sReference)); Q_strupr(sReference); - mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find( sReference ); - if (itEntry != TheStringPackage.m_StringEntries.end()) - { + mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find(sReference); + if (itEntry != TheStringPackage.m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; - if ( se_debug->integer && TheStringPackage.m_bLoadDebug ) - { + if (se_debug->integer && TheStringPackage.m_bLoadDebug) { return Entry.m_strDebug.c_str(); - } - else - { + } else { return Entry.m_strString.c_str(); } } // should never get here, but fall back anyway... (except we DO use this to see if there's a debug-friendly key bind, which may not exist) // -// __ASSERT(0); - return ""; // you may want to replace this with something based on _DEBUG or not? + // __ASSERT(0); + return ""; // you may want to replace this with something based on _DEBUG or not? } - // convenience-function for the main GetFlags call... // -int SE_GetFlags ( const char *psPackageReference, const char *psStringReference ) -{ - char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long +int SE_GetFlags(const char *psPackageReference, const char *psStringReference) { + char sReference[256]; // will always be enough, I've never seen one more than about 30 chars long - Com_sprintf(sReference,sizeof(sReference),"%s_%s", psPackageReference, psStringReference); + Com_sprintf(sReference, sizeof(sReference), "%s_%s", psPackageReference, psStringReference); - return SE_GetFlags( sReference ); + return SE_GetFlags(sReference); } -int SE_GetFlags ( const char *psPackageAndStringReference ) -{ - mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find( psPackageAndStringReference ); - if (itEntry != TheStringPackage.m_StringEntries.end()) - { +int SE_GetFlags(const char *psPackageAndStringReference) { + mapStringEntries_t::iterator itEntry = TheStringPackage.m_StringEntries.find(psPackageAndStringReference); + if (itEntry != TheStringPackage.m_StringEntries.end()) { SE_Entry_t &Entry = (*itEntry).second; return Entry.m_iFlags; @@ -1049,17 +865,11 @@ int SE_GetFlags ( const char *psPackageAndStringReference ) return 0; } +int SE_GetNumFlags(void) { return TheStringPackage.m_vstrFlagNames.size(); } -int SE_GetNumFlags( void ) -{ - return TheStringPackage.m_vstrFlagNames.size(); -} - -const char *SE_GetFlagName( int iFlagIndex ) -{ - if ( iFlagIndex < (int)TheStringPackage.m_vstrFlagNames.size()) - { - return TheStringPackage.m_vstrFlagNames[ iFlagIndex ].c_str(); +const char *SE_GetFlagName(int iFlagIndex) { + if (iFlagIndex < (int)TheStringPackage.m_vstrFlagNames.size()) { + return TheStringPackage.m_vstrFlagNames[iFlagIndex].c_str(); } __ASSERT(0); @@ -1068,10 +878,7 @@ const char *SE_GetFlagName( int iFlagIndex ) // returns flag bitmask (eg 00000010b), else 0 for not found // -int SE_GetFlagMask( const char *psFlagName ) -{ - return TheStringPackage.GetFlagMask( psFlagName ); -} +int SE_GetFlagMask(const char *psFlagName) { return TheStringPackage.GetFlagMask(psFlagName); } // I could cache the result of this since it won't change during app lifetime unless someone does a build-publish // while you're still ingame. Cacheing would make sense since it can take a while to scan, but I'll leave it and @@ -1082,45 +889,38 @@ int SE_GetFlagMask( const char *psFlagName ) // Groan, except for Bob. I mentioned that this was slow and only call it once, but he's calling it from // every level-load... Ok, cacheing it is... // -std::vector gvLanguagesAvailable; -int SE_GetNumLanguages(void) -{ - if ( gvLanguagesAvailable.empty() ) - { +std::vector gvLanguagesAvailable; +int SE_GetNumLanguages(void) { + if (gvLanguagesAvailable.empty()) { std::string strResults; - /*int iFilesFound = */SE_BuildFileList( - #ifdef _STRINGED - va("C:\\Source\\Tools\\StringEd\\test_data\\%s",sSE_STRINGS_DIR) - #else - sSE_STRINGS_DIR - #endif - , strResults - ); - - std::set strUniqueStrings; // laziness + /*int iFilesFound = */ SE_BuildFileList( +#ifdef _STRINGED + va("C:\\Source\\Tools\\StringEd\\test_data\\%s", sSE_STRINGS_DIR) +#else + sSE_STRINGS_DIR +#endif + , + strResults); + + std::set strUniqueStrings; // laziness const char *p; - while ((p=SE_GetFoundFile (strResults)) != NULL) - { - const char *psLanguage = TheStringPackage.ExtractLanguageFromPath( p ); + while ((p = SE_GetFoundFile(strResults)) != NULL) { + const char *psLanguage = TheStringPackage.ExtractLanguageFromPath(p); - // __DEBUGOUT( p ); - // __DEBUGOUT( "\n" ); - // __DEBUGOUT( psLanguage ); - // __DEBUGOUT( "\n" ); + // __DEBUGOUT( p ); + // __DEBUGOUT( "\n" ); + // __DEBUGOUT( psLanguage ); + // __DEBUGOUT( "\n" ); - if (!strUniqueStrings.count( psLanguage )) - { - strUniqueStrings.insert( psLanguage ); + if (!strUniqueStrings.count(psLanguage)) { + strUniqueStrings.insert(psLanguage); // if english is available, it should always be first... ( I suppose ) // - if (!Q_stricmp(psLanguage,"english")) - { - gvLanguagesAvailable.insert( gvLanguagesAvailable.begin(), psLanguage ); - } - else - { - gvLanguagesAvailable.push_back( psLanguage ); + if (!Q_stricmp(psLanguage, "english")) { + gvLanguagesAvailable.insert(gvLanguagesAvailable.begin(), psLanguage); + } else { + gvLanguagesAvailable.push_back(psLanguage); } } } @@ -1131,11 +931,9 @@ int SE_GetNumLanguages(void) // SE_GetNumLanguages() must have been called before this... // -const char *SE_GetLanguageName( int iLangIndex ) -{ - if ( iLangIndex < (int)gvLanguagesAvailable.size() ) - { - return gvLanguagesAvailable[ iLangIndex ].c_str(); +const char *SE_GetLanguageName(int iLangIndex) { + if (iLangIndex < (int)gvLanguagesAvailable.size()) { + return gvLanguagesAvailable[iLangIndex].c_str(); } __ASSERT(0); @@ -1144,32 +942,24 @@ const char *SE_GetLanguageName( int iLangIndex ) // SE_GetNumLanguages() must have been called before this... // -const char *SE_GetLanguageDir( int iLangIndex ) -{ - if ( iLangIndex < (int)gvLanguagesAvailable.size() ) - { - return va("%s/%s", sSE_STRINGS_DIR, gvLanguagesAvailable[ iLangIndex ].c_str() ); +const char *SE_GetLanguageDir(int iLangIndex) { + if (iLangIndex < (int)gvLanguagesAvailable.size()) { + return va("%s/%s", sSE_STRINGS_DIR, gvLanguagesAvailable[iLangIndex].c_str()); } __ASSERT(0); return ""; } -void SE_NewLanguage(void) -{ - TheStringPackage.Clear( SE_TRUE ); -} - - +void SE_NewLanguage(void) { TheStringPackage.Clear(SE_TRUE); } // these two functions aren't needed other than to make Quake-type games happy and/or stop memory managers // complaining about leaks if they report them before the global StringEd package object calls it's own dtor. // // but here they are for completeness's sake I guess... // -void SE_Init(void) -{ - TheStringPackage.Clear( SE_FALSE ); +void SE_Init(void) { + TheStringPackage.Clear(SE_FALSE); #ifdef _DEBUG // int iNumLanguages = SE_GetNumLanguages(); @@ -1177,94 +967,75 @@ void SE_Init(void) se_language = Cvar_Get("se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART); se_debug = Cvar_Get("se_debug", "0", 0); - sp_leet = Cvar_Get("sp_leet", "0", CVAR_ROM ); + sp_leet = Cvar_Get("sp_leet", "0", CVAR_ROM); // if doing a buildscript, load all languages... // extern cvar_t *com_buildScript; - if (com_buildScript->integer == 2) - { + if (com_buildScript->integer == 2) { int iLanguages = SE_GetNumLanguages(); - for (int iLang = 0; iLang < iLanguages; iLang++) - { - const char *psLanguage = SE_GetLanguageName( iLang ); // eg "german" - Com_Printf( "com_buildScript(2): Loading language \"%s\"...\n", psLanguage ); - SE_LoadLanguage( psLanguage ); + for (int iLang = 0; iLang < iLanguages; iLang++) { + const char *psLanguage = SE_GetLanguageName(iLang); // eg "german" + Com_Printf("com_buildScript(2): Loading language \"%s\"...\n", psLanguage); + SE_LoadLanguage(psLanguage); } } - const char *psErrorMessage = SE_LoadLanguage( se_language->string ); - if (psErrorMessage) - { - Com_Error( ERR_DROP, "SE_Init() Unable to load language: \"%s\"!\nError: \"%s\"\n", se_language->string,psErrorMessage ); + const char *psErrorMessage = SE_LoadLanguage(se_language->string); + if (psErrorMessage) { + Com_Error(ERR_DROP, "SE_Init() Unable to load language: \"%s\"!\nError: \"%s\"\n", se_language->string, psErrorMessage); } - -} - -void SE_ShutDown(void) -{ - TheStringPackage.Clear( SE_FALSE ); } +void SE_ShutDown(void) { TheStringPackage.Clear(SE_FALSE); } // returns error message else NULL for ok. // // Any errors that result from this should probably be treated as game-fatal, since an asset file is fuxored. // -const char *SE_LoadLanguage( const char *psLanguage, SE_BOOL bLoadDebug /* = SE_TRUE */ ) -{ +const char *SE_LoadLanguage(const char *psLanguage, SE_BOOL bLoadDebug /* = SE_TRUE */) { const char *psErrorMessage = NULL; - if (psLanguage && psLanguage[0]) - { + if (psLanguage && psLanguage[0]) { SE_NewLanguage(); std::string strResults; - /*int iFilesFound = */SE_BuildFileList( - #ifdef _STRINGED - va("C:\\Source\\Tools\\StringEd\\test_data\\%s",sSE_STRINGS_DIR) - #else - sSE_STRINGS_DIR - #endif - , strResults - ); + /*int iFilesFound = */ SE_BuildFileList( +#ifdef _STRINGED + va("C:\\Source\\Tools\\StringEd\\test_data\\%s", sSE_STRINGS_DIR) +#else + sSE_STRINGS_DIR +#endif + , + strResults); const char *p; - while ( (p=SE_GetFoundFile (strResults)) != NULL && !psErrorMessage ) - { - const char *psThisLang = TheStringPackage.ExtractLanguageFromPath( p ); + while ((p = SE_GetFoundFile(strResults)) != NULL && !psErrorMessage) { + const char *psThisLang = TheStringPackage.ExtractLanguageFromPath(p); - if ( !Q_stricmp( psLanguage, psThisLang ) ) - { - psErrorMessage = SE_Load( p, bLoadDebug ); + if (!Q_stricmp(psLanguage, psThisLang)) { + psErrorMessage = SE_Load(p, bLoadDebug); } } - } - else - { - __ASSERT( 0 && "SE_LoadLanguage(): Bad language name!" ); + } else { + __ASSERT(0 && "SE_LoadLanguage(): Bad language name!"); } return psErrorMessage; } - // called in Com_Frame, so don't take up any time! (can also be called during dedicated) // // instead of re-loading just the files we've already loaded I'm going to load the whole language (simpler) // -void SE_CheckForLanguageUpdates(void) -{ - if (se_language && se_language->modified) - { - const char *psErrorMessage = SE_LoadLanguage( se_language->string, SE_TRUE ); - if ( psErrorMessage ) - { - Com_Error( ERR_DROP, psErrorMessage ); +void SE_CheckForLanguageUpdates(void) { + if (se_language && se_language->modified) { + const char *psErrorMessage = SE_LoadLanguage(se_language->string, SE_TRUE); + if (psErrorMessage) { + Com_Error(ERR_DROP, psErrorMessage); } se_language->modified = SE_FALSE; } } - ///////////////////////// eof ////////////////////////// diff --git a/codemp/qcommon/stringed_interface.cpp b/codemp/qcommon/stringed_interface.cpp index 78c9e1faf6..5aef257b48 100644 --- a/codemp/qcommon/stringed_interface.cpp +++ b/codemp/qcommon/stringed_interface.cpp @@ -29,7 +29,6 @@ along with this program; if not, see . // into each project. // - ////////////////////////////////////////////////// // // stuff common to all qcommon files... @@ -50,47 +49,36 @@ along with this program; if not, see . #include "generic.h" #endif - // this just gets the binary of the file into memory, so I can parse it. Called by main SGE loader // // returns either char * of loaded file, else NULL for failed-to-open... // -unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = 0 */) -{ +unsigned char *SE_LoadFileData(const char *psFileName, int *piLoadedLength /* = 0 */) { unsigned char *psReturn = NULL; - if ( piLoadedLength ) - { + if (piLoadedLength) { *piLoadedLength = 0; } #ifdef _STRINGED - if (psFileName[1] == ':') - { + if (psFileName[1] == ':') { // full-path filename... // - FILE *fh = fopen( psFileName, "rb" ); - if (fh) - { + FILE *fh = fopen(psFileName, "rb"); + if (fh) { long lLength = filesize(fh); - if (lLength > 0) - { - psReturn = (unsigned char *) malloc( lLength + 1); - if (psReturn) - { - int iBytesRead = fread( psReturn, 1, lLength, fh ); - if (iBytesRead != lLength) - { + if (lLength > 0) { + psReturn = (unsigned char *)malloc(lLength + 1); + if (psReturn) { + int iBytesRead = fread(psReturn, 1, lLength, fh); + if (iBytesRead != lLength) { // error reading file!!!... // free(psReturn); - psReturn = NULL; - } - else - { - psReturn[ lLength ] = '\0'; - if ( piLoadedLength ) - { + psReturn = NULL; + } else { + psReturn[lLength] = '\0'; + if (piLoadedLength) { *piLoadedLength = iBytesRead; } } @@ -98,20 +86,17 @@ unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = } } } - } - else + } else #endif { // local filename, so prepend the base dir etc according to game and load it however (from PAK?) // unsigned char *pvLoadedData; - int iLen = FS_ReadFile( psFileName, (void **)&pvLoadedData ); + int iLen = FS_ReadFile(psFileName, (void **)&pvLoadedData); - if (iLen>0) - { + if (iLen > 0) { psReturn = pvLoadedData; - if ( piLoadedLength ) - { + if (piLoadedLength) { *piLoadedLength = iLen; } } @@ -120,65 +105,53 @@ unsigned char *SE_LoadFileData( const char *psFileName, int *piLoadedLength /* = return psReturn; } - // called by main SGE code after loaded data has been parsedinto internal structures... // -void SE_FreeFileDataAfterLoad( unsigned char *psLoadedFile ) -{ +void SE_FreeFileDataAfterLoad(unsigned char *psLoadedFile) { #ifdef _STRINGED - if ( psLoadedFile ) - { - free( psLoadedFile ); + if (psLoadedFile) { + free(psLoadedFile); } #else - if ( psLoadedFile ) - { - FS_FreeFile( psLoadedFile ); + if (psLoadedFile) { + FS_FreeFile(psLoadedFile); } #endif } - - - - #ifndef _STRINGED // quake-style method of doing things since their file-list code doesn't have a 'recursive' flag... // int giFilesFound; -static void SE_R_ListFiles( const char *psExtension, const char *psDir, std::string &strResults ) -{ -// Com_Printf(va("Scanning Dir: %s\n",psDir)); +static void SE_R_ListFiles(const char *psExtension, const char *psDir, std::string &strResults) { + // Com_Printf(va("Scanning Dir: %s\n",psDir)); - char **sysFiles, **dirFiles; - int numSysFiles, i, numdirs; + char **sysFiles, **dirFiles; + int numSysFiles, i, numdirs; - dirFiles = FS_ListFiles( psDir, "/", &numdirs); - for (i=0;i. vm_t *currentVM = NULL; -static const char *vmNames[MAX_VM] = { - "jampgame", - "cgame", - "ui" -}; +static const char *vmNames[MAX_VM] = {"jampgame", "cgame", "ui"}; const char *vmStrs[MAX_VM] = { "GameVM", @@ -56,12 +52,12 @@ static vm_t *vmTable[MAX_VM]; cvar_t *vm_legacy; #endif -void VM_Init( void ) { +void VM_Init(void) { #ifdef _DEBUG - vm_legacy = Cvar_Get( "vm_legacy", "0", 0 ); + vm_legacy = Cvar_Get("vm_legacy", "0", 0); #endif - memset( vmTable, 0, sizeof(vmTable) ); + memset(vmTable, 0, sizeof(vmTable)); } // The syscall mechanism relies on stack manipulation to get it's args. @@ -79,7 +75,7 @@ void VM_Init( void ) { // works on. Rather than add the performance hit for those platforms, the original code is still in use there. // For speed, we just grab 15 arguments, and don't worry about exactly how many the syscall actually needs; the extra is // thrown away. -intptr_t QDECL VM_DllSyscall( intptr_t arg, ... ) { +intptr_t QDECL VM_DllSyscall(intptr_t arg, ...) { #if !id386 || defined __clang__ || defined MACOS_X // rcg010206 - see commentary above intptr_t args[16]; @@ -87,208 +83,208 @@ intptr_t QDECL VM_DllSyscall( intptr_t arg, ... ) { args[0] = arg; - va_start( ap, arg ); - for (size_t i = 1; i < ARRAY_LEN (args); i++) - args[i] = va_arg( ap, intptr_t ); - va_end( ap ); + va_start(ap, arg); + for (size_t i = 1; i < ARRAY_LEN(args); i++) + args[i] = va_arg(ap, intptr_t); + va_end(ap); - return currentVM->legacy.syscall( args ); + return currentVM->legacy.syscall(args); #else // original id code - return currentVM->legacy.syscall( &arg ); + return currentVM->legacy.syscall(&arg); #endif } // Reload the data, but leave everything else in place // This allows a server to do a map_restart without changing memory allocation -vm_t *VM_Restart( vm_t *vm ) { +vm_t *VM_Restart(vm_t *vm) { const vm_t saved = *vm; - VM_Free( vm ); + VM_Free(vm); - if ( saved.isLegacy ) - return VM_CreateLegacy( saved.slot, saved.legacy.syscall ); + if (saved.isLegacy) + return VM_CreateLegacy(saved.slot, saved.legacy.syscall); else - return VM_Create( saved.slot ); + return VM_Create(saved.slot); } -vm_t *VM_CreateLegacy( vmSlots_t vmSlot, intptr_t( *systemCalls )(intptr_t *) ) { +vm_t *VM_CreateLegacy(vmSlots_t vmSlot, intptr_t (*systemCalls)(intptr_t *)) { vm_t *vm = NULL; - if ( !systemCalls ) { - Com_Error( ERR_FATAL, "VM_CreateLegacy: bad parms" ); + if (!systemCalls) { + Com_Error(ERR_FATAL, "VM_CreateLegacy: bad parms"); return NULL; } // see if we already have the VM - if ( vmTable[vmSlot] ) + if (vmTable[vmSlot]) return vmTable[vmSlot]; // find a free vm - vmTable[vmSlot] = (vm_t *)Z_Malloc( sizeof(*vm), TAG_VM, qtrue ); + vmTable[vmSlot] = (vm_t *)Z_Malloc(sizeof(*vm), TAG_VM, qtrue); vm = vmTable[vmSlot]; // initialise it vm->isLegacy = qtrue; vm->slot = vmSlot; - Q_strncpyz( vm->name, vmNames[vmSlot], sizeof(vm->name) ); + Q_strncpyz(vm->name, vmNames[vmSlot], sizeof(vm->name)); vm->legacy.syscall = systemCalls; // find the legacy syscall api - FS_FindPureDLL( vm->name ); - vm->dllHandle = Sys_LoadLegacyGameDll( vm->name, &vm->legacy.main, VM_DllSyscall ); + FS_FindPureDLL(vm->name); + vm->dllHandle = Sys_LoadLegacyGameDll(vm->name, &vm->legacy.main, VM_DllSyscall); - Com_Printf( "VM_CreateLegacy: %s" ARCH_STRING DLL_EXT, vm->name ); - if ( vm->dllHandle ) { - if ( com_developer->integer ) - Com_Printf( " succeeded [0x%" PRIxPTR "]\n", (uintptr_t)vm->dllHandle ); + Com_Printf("VM_CreateLegacy: %s" ARCH_STRING DLL_EXT, vm->name); + if (vm->dllHandle) { + if (com_developer->integer) + Com_Printf(" succeeded [0x%" PRIxPTR "]\n", (uintptr_t)vm->dllHandle); else - Com_Printf( " succeeded\n" ); + Com_Printf(" succeeded\n"); return vm; } - VM_Free( vm ); - Com_Printf( " failed!\n" ); + VM_Free(vm); + Com_Printf(" failed!\n"); return NULL; } -vm_t *VM_Create( vmSlots_t vmSlot ) { +vm_t *VM_Create(vmSlots_t vmSlot) { vm_t *vm = NULL; #ifdef _DEBUG - if ( (vm_legacy->integer & (1<integer & (1 << vmSlot))) return NULL; #endif // see if we already have the VM - if ( vmTable[vmSlot] ) + if (vmTable[vmSlot]) return vmTable[vmSlot]; // find a free vm - vmTable[vmSlot] = (vm_t *)Z_Malloc( sizeof(*vm), TAG_VM, qtrue ); + vmTable[vmSlot] = (vm_t *)Z_Malloc(sizeof(*vm), TAG_VM, qtrue); vm = vmTable[vmSlot]; // initialise it vm->isLegacy = qfalse; vm->slot = vmSlot; - Q_strncpyz( vm->name, vmNames[vmSlot], sizeof(vm->name) ); + Q_strncpyz(vm->name, vmNames[vmSlot], sizeof(vm->name)); // find the module api - FS_FindPureDLL( vm->name ); - vm->dllHandle = Sys_LoadGameDll( vm->name, &vm->GetModuleAPI ); + FS_FindPureDLL(vm->name); + vm->dllHandle = Sys_LoadGameDll(vm->name, &vm->GetModuleAPI); - Com_Printf( "VM_Create: %s" ARCH_STRING DLL_EXT, vm->name ); - if ( vm->dllHandle ) { - if ( com_developer->integer ) - Com_Printf( " succeeded [0x%" PRIxPTR "+0x%" PRIxPTR "]\n", vm->dllHandle, (intptr_t)vm->GetModuleAPI - (intptr_t)vm->dllHandle ); + Com_Printf("VM_Create: %s" ARCH_STRING DLL_EXT, vm->name); + if (vm->dllHandle) { + if (com_developer->integer) + Com_Printf(" succeeded [0x%" PRIxPTR "+0x%" PRIxPTR "]\n", vm->dllHandle, (intptr_t)vm->GetModuleAPI - (intptr_t)vm->dllHandle); else - Com_Printf( " succeeded\n" ); + Com_Printf(" succeeded\n"); return vm; } - VM_Free( vm ); - Com_Printf( " failed!\n" ); + VM_Free(vm); + Com_Printf(" failed!\n"); return NULL; } -void VM_Free( vm_t *vm ) { - if ( !vm ) +void VM_Free(vm_t *vm) { + if (!vm) return; // mark the slot as free vmTable[vm->slot] = NULL; - if ( vm->dllHandle ) - Sys_UnloadDll( vm->dllHandle ); + if (vm->dllHandle) + Sys_UnloadDll(vm->dllHandle); - memset( vm, 0, sizeof(*vm) ); + memset(vm, 0, sizeof(*vm)); - Z_Free( vm ); + Z_Free(vm); currentVM = NULL; } -void VM_Clear( void ) { - for ( int i = 0; i < MAX_VM; i++ ) - VM_Free( vmTable[i] ); +void VM_Clear(void) { + for (int i = 0; i < MAX_VM; i++) + VM_Free(vmTable[i]); currentVM = NULL; } -void VM_Shifted_Alloc( void **ptr, int size ) { +void VM_Shifted_Alloc(void **ptr, int size) { void *mem = NULL; - if ( !currentVM ) { - assert( 0 ); + if (!currentVM) { + assert(0); *ptr = NULL; return; } - mem = Z_Malloc( size + 1, TAG_VM_ALLOCATED, qfalse ); - if ( !mem ) { - assert( 0 ); + mem = Z_Malloc(size + 1, TAG_VM_ALLOCATED, qfalse); + if (!mem) { + assert(0); *ptr = NULL; return; } - memset( mem, 0, size + 1 ); + memset(mem, 0, size + 1); *ptr = mem; } -void VM_Shifted_Free( void **ptr ) { +void VM_Shifted_Free(void **ptr) { void *mem = NULL; - if ( !currentVM ) { - assert( 0 ); + if (!currentVM) { + assert(0); return; } mem = (void *)*ptr; - if ( !mem ) { - assert( 0 ); + if (!mem) { + assert(0); return; } - Z_Free( mem ); + Z_Free(mem); *ptr = NULL; } -void *VM_ArgPtr( intptr_t intValue ) { - if ( !intValue ) +void *VM_ArgPtr(intptr_t intValue) { + if (!intValue) return NULL; // currentVM is missing on reconnect - if ( !currentVM ) + if (!currentVM) return NULL; return (void *)intValue; } -void *VM_ExplicitArgPtr( vm_t *vm, intptr_t intValue ) { - if ( !intValue ) +void *VM_ExplicitArgPtr(vm_t *vm, intptr_t intValue) { + if (!intValue) return NULL; // currentVM is missing on reconnect here as well? - if ( !currentVM ) + if (!currentVM) return NULL; return (void *)intValue; } -float _vmf( intptr_t x ) { +float _vmf(intptr_t x) { byteAlias_t fi; fi.i = (int)x; return fi.f; } -intptr_t QDECL VM_Call( vm_t *vm, int callnum, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7, intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11 ) { - if ( !vm || !vm->name[0] ) { - Com_Error( ERR_FATAL, "VM_Call with NULL vm" ); +intptr_t QDECL VM_Call(vm_t *vm, int callnum, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, + intptr_t arg7, intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11) { + if (!vm || !vm->name[0]) { + Com_Error(ERR_FATAL, "VM_Call with NULL vm"); return 0; } - VMSwap v( vm ); + VMSwap v(vm); - return vm->legacy.main( callnum, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, - arg9, arg10, arg11 ); + return vm->legacy.main(callnum, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } diff --git a/codemp/qcommon/z_memman_pc.cpp b/codemp/qcommon/z_memman_pc.cpp index dff480cf0b..eca3c2cbe6 100644 --- a/codemp/qcommon/z_memman_pc.cpp +++ b/codemp/qcommon/z_memman_pc.cpp @@ -26,13 +26,13 @@ along with this program; if not, see . //////////////////////////////////////////////// // -#ifdef TAGDEF // itu? +#ifdef TAGDEF // itu? #undef TAGDEF #endif #define TAGDEF(blah) #blah -const static char *psTagStrings[TAG_COUNT+1]= // +1 because TAG_COUNT will itself become a string here. Oh well. -{ - #include "qcommon/tags.h" +const static char *psTagStrings[TAG_COUNT + 1] = // +1 because TAG_COUNT will itself become a string here. Oh well. + { +#include "qcommon/tags.h" }; // //////////////////////////////////////////////// @@ -40,92 +40,76 @@ const static char *psTagStrings[TAG_COUNT+1]= // +1 because TAG_COUNT will itsel static void Z_Details_f(void); void CIN_CloseAllVideos(); - // This handles zone memory allocation. // It is a wrapper around malloc with a tag id and a magic number at the start -#define ZONE_MAGIC 0x21436587 +#define ZONE_MAGIC 0x21436587 -typedef struct zoneHeader_s -{ - int iMagic; - memtag_t eTag; - int iSize; -struct zoneHeader_s *pNext; -struct zoneHeader_s *pPrev; +typedef struct zoneHeader_s { + int iMagic; + memtag_t eTag; + int iSize; + struct zoneHeader_s *pNext; + struct zoneHeader_s *pPrev; } zoneHeader_t; -typedef struct -{ +typedef struct { int iMagic; } zoneTail_t; -static inline zoneTail_t *ZoneTailFromHeader(zoneHeader_t *pHeader) -{ - return (zoneTail_t*) ( (char*)pHeader + sizeof(*pHeader) + pHeader->iSize ); -} +static inline zoneTail_t *ZoneTailFromHeader(zoneHeader_t *pHeader) { return (zoneTail_t *)((char *)pHeader + sizeof(*pHeader) + pHeader->iSize); } #ifdef DETAILED_ZONE_DEBUG_CODE -map mapAllocatedZones; +map mapAllocatedZones; #endif - -typedef struct zoneStats_s -{ - int iCount; - int iCurrent; - int iPeak; +typedef struct zoneStats_s { + int iCount; + int iCurrent; + int iPeak; // I'm keeping these updated on the fly, since it's quicker for cache-pool // purposes rather than recalculating each time... // - int iSizesPerTag [TAG_COUNT]; - int iCountsPerTag[TAG_COUNT]; + int iSizesPerTag[TAG_COUNT]; + int iCountsPerTag[TAG_COUNT]; } zoneStats_t; -typedef struct zone_s -{ - zoneStats_t Stats; - zoneHeader_t Header; +typedef struct zone_s { + zoneStats_t Stats; + zoneHeader_t Header; } zone_t; -cvar_t *com_validateZone; - -zone_t TheZone = {}; +cvar_t *com_validateZone; +zone_t TheZone = {}; // Scans through the linked list of mallocs and makes sure no data has been overwritten -void Z_Validate(void) -{ - if(!com_validateZone || !com_validateZone->integer) - { +void Z_Validate(void) { + if (!com_validateZone || !com_validateZone->integer) { return; } zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - #ifdef DETAILED_ZONE_DEBUG_CODE + while (pMemory) { +#ifdef DETAILED_ZONE_DEBUG_CODE // this won't happen here, but wtf? - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount <= 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount <= 0) { Com_Error(ERR_FATAL, "Z_Validate(): Bad block allocation count!"); return; } - #endif +#endif - if(pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Validate(): Corrupt zone header!"); return; } - if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) - { + if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Validate(): Corrupt zone tail!"); return; } @@ -134,50 +118,39 @@ void Z_Validate(void) } } - - // static mem blocks to reduce a lot of small zone overhead // #pragma pack(push) #pragma pack(1) typedef struct StaticZeroMem_s { - zoneHeader_t Header; -// byte mem[0]; - zoneTail_t Tail; + zoneHeader_t Header; + // byte mem[0]; + zoneTail_t Tail; } StaticZeroMem_t; typedef struct StaticMem_s { - zoneHeader_t Header; + zoneHeader_t Header; byte mem[2]; - zoneTail_t Tail; + zoneTail_t Tail; } StaticMem_t; #pragma pack(pop) -StaticZeroMem_t gZeroMalloc = - { {ZONE_MAGIC, TAG_STATIC,0,NULL,NULL},{ZONE_MAGIC}}; -StaticMem_t gEmptyString = - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'\0','\0'},{ZONE_MAGIC}}; +StaticZeroMem_t gZeroMalloc = {{ZONE_MAGIC, TAG_STATIC, 0, NULL, NULL}, {ZONE_MAGIC}}; +StaticMem_t gEmptyString = {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'\0', '\0'}, {ZONE_MAGIC}}; StaticMem_t gNumberString[] = { - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'0','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'1','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'2','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'3','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'4','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'5','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'6','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'7','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'8','\0'},{ZONE_MAGIC}}, - { {ZONE_MAGIC, TAG_STATIC,2,NULL,NULL},{'9','\0'},{ZONE_MAGIC}}, + {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'0', '\0'}, {ZONE_MAGIC}}, {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'1', '\0'}, {ZONE_MAGIC}}, + {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'2', '\0'}, {ZONE_MAGIC}}, {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'3', '\0'}, {ZONE_MAGIC}}, + {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'4', '\0'}, {ZONE_MAGIC}}, {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'5', '\0'}, {ZONE_MAGIC}}, + {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'6', '\0'}, {ZONE_MAGIC}}, {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'7', '\0'}, {ZONE_MAGIC}}, + {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'8', '\0'}, {ZONE_MAGIC}}, {{ZONE_MAGIC, TAG_STATIC, 2, NULL, NULL}, {'9', '\0'}, {ZONE_MAGIC}}, }; qboolean gbMemFreeupOccured = qfalse; -void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iUnusedAlign /* = 4 */) -{ +void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iUnusedAlign /* = 4 */) { gbMemFreeupOccured = qfalse; - if (iSize == 0) - { - zoneHeader_t *pMemory = (zoneHeader_t *) &gZeroMalloc; + if (iSize == 0) { + zoneHeader_t *pMemory = (zoneHeader_t *)&gZeroMalloc; return &pMemory[1]; } @@ -188,56 +161,48 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iU // Allocate a chunk... // zoneHeader_t *pMemory = NULL; - while (pMemory == NULL) - { - if (gbMemFreeupOccured) - { - Sys_Sleep(1000); // sleep for a second, so Windows has a chance to shuffle mem to de-swiss-cheese it + while (pMemory == NULL) { + if (gbMemFreeupOccured) { + Sys_Sleep(1000); // sleep for a second, so Windows has a chance to shuffle mem to de-swiss-cheese it } if (bZeroit) { - pMemory = (zoneHeader_t *) calloc ( iRealSize, 1 ); + pMemory = (zoneHeader_t *)calloc(iRealSize, 1); } else { - pMemory = (zoneHeader_t *) malloc ( iRealSize ); + pMemory = (zoneHeader_t *)malloc(iRealSize); } - if (!pMemory) - { + if (!pMemory) { // new bit, if we fail to malloc memory, try dumping some of the cached stuff that's non-vital and try again... // // ditch the BSP cache... // extern qboolean CM_DeleteCachedMap(qboolean bGuaranteedOkToDelete); - if (CM_DeleteCachedMap(qfalse)) - { + if (CM_DeleteCachedMap(qfalse)) { gbMemFreeupOccured = qtrue; - continue; // we've just ditched a whole load of memory, so try again with the malloc + continue; // we've just ditched a whole load of memory, so try again with the malloc } - // ditch any sounds not used on this level... // extern qboolean SND_RegisterAudio_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel); - if (SND_RegisterAudio_LevelLoadEnd(qtrue)) - { + if (SND_RegisterAudio_LevelLoadEnd(qtrue)) { gbMemFreeupOccured = qtrue; - continue; // we've dropped at least one sound, so try again with the malloc + continue; // we've dropped at least one sound, so try again with the malloc } #ifndef DEDICATED // ditch any image_t's (and associated GL memory) not used on this level... // - if (re->RegisterImages_LevelLoadEnd()) - { + if (re->RegisterImages_LevelLoadEnd()) { gbMemFreeupOccured = qtrue; - continue; // we've dropped at least one image, so try again with the malloc + continue; // we've dropped at least one image, so try again with the malloc } #endif // ditch the model-binaries cache... (must be getting desperate here!) // - if ( re->RegisterModels_LevelLoadEnd(qtrue) ) - { + if (re->RegisterModels_LevelLoadEnd(qtrue)) { gbMemFreeupOccured = qtrue; continue; } @@ -254,17 +219,14 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iU // extern qboolean gbInsideLoadSound; extern int SND_FreeOldestSound(); - if (!gbInsideLoadSound) - { + if (!gbInsideLoadSound) { int iBytesFreed = SND_FreeOldestSound(); - if (iBytesFreed) - { + if (iBytesFreed) { int iTheseBytesFreed = 0; - while ( (iTheseBytesFreed = SND_FreeOldestSound()) != 0) - { + while ((iTheseBytesFreed = SND_FreeOldestSound()) != 0) { iBytesFreed += iTheseBytesFreed; if (iBytesFreed >= iRealSize) - break; // early opt-out since we've managed to recover enough (mem-contiguity issues aside) + break; // early opt-out since we've managed to recover enough (mem-contiguity issues aside) } gbMemFreeupOccured = qtrue; continue; @@ -275,21 +237,20 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iU // // findlabel: "recovermem" - Com_Printf(S_COLOR_RED"Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); + Com_Printf(S_COLOR_RED "Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); Z_Details_f(); - Com_Error(ERR_FATAL,"(Repeat): Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); + Com_Error(ERR_FATAL, "(Repeat): Z_Malloc(): Failed to alloc %d bytes (TAG_%s) !!!!!\n", iSize, psTagStrings[eTag]); return NULL; } } // Link in - pMemory->iMagic = ZONE_MAGIC; - pMemory->eTag = eTag; - pMemory->iSize = iSize; - pMemory->pNext = TheZone.Header.pNext; + pMemory->iMagic = ZONE_MAGIC; + pMemory->eTag = eTag; + pMemory->iSize = iSize; + pMemory->pNext = TheZone.Header.pNext; TheZone.Header.pNext = pMemory; - if (pMemory->pNext) - { + if (pMemory->pNext) { pMemory->pNext->pPrev = pMemory; } pMemory->pPrev = &TheZone.Header; @@ -302,19 +263,18 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iU // TheZone.Stats.iCurrent += iSize; TheZone.Stats.iCount++; - TheZone.Stats.iSizesPerTag [eTag] += iSize; - TheZone.Stats.iCountsPerTag [eTag]++; + TheZone.Stats.iSizesPerTag[eTag] += iSize; + TheZone.Stats.iCountsPerTag[eTag]++; - if (TheZone.Stats.iCurrent > TheZone.Stats.iPeak) - { - TheZone.Stats.iPeak = TheZone.Stats.iCurrent; + if (TheZone.Stats.iCurrent > TheZone.Stats.iPeak) { + TheZone.Stats.iPeak = TheZone.Stats.iCurrent; } #ifdef DETAILED_ZONE_DEBUG_CODE mapAllocatedZones[pMemory]++; #endif - Z_Validate(); // check for corruption + Z_Validate(); // check for corruption void *pvReturnMem = &pMemory[1]; return pvReturnMem; @@ -323,38 +283,30 @@ void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit /* = qfalse */, int iU // Special wrapper around Z_Malloc for better separation between the main engine // code and the bundled minizip library. -extern "C" Q_EXPORT void* openjk_minizip_malloc(int size); -extern "C" Q_EXPORT void openjk_minizip_free(void* to_free); +extern "C" Q_EXPORT void *openjk_minizip_malloc(int size); +extern "C" Q_EXPORT void openjk_minizip_free(void *to_free); -void* openjk_minizip_malloc(int size) -{ - return Z_Malloc(size, TAG_MINIZIP, qfalse, 0); -} +void *openjk_minizip_malloc(int size) { return Z_Malloc(size, TAG_MINIZIP, qfalse, 0); } -void openjk_minizip_free(void *to_free) -{ - Z_Free(to_free); -} +void openjk_minizip_free(void *to_free) { Z_Free(to_free); } // used during model cacheing to save an extra malloc, lets us morph the disk-load buffer then // just not fs_freefile() it afterwards. // -void Z_MorphMallocTag( void *pvAddress, memtag_t eDesiredTag ) -{ +void Z_MorphMallocTag(void *pvAddress, memtag_t eDesiredTag) { zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_MorphMallocTag(): Not a valid zone header!"); - return; // won't get here + return; // won't get here } // DEC existing tag stats... // -// TheZone.Stats.iCurrent - unchanged -// TheZone.Stats.iCount - unchanged - TheZone.Stats.iSizesPerTag [pMemory->eTag] -= pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]--; + // TheZone.Stats.iCurrent - unchanged + // TheZone.Stats.iCount - unchanged + TheZone.Stats.iSizesPerTag[pMemory->eTag] -= pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]--; // morph... // @@ -362,22 +314,21 @@ void Z_MorphMallocTag( void *pvAddress, memtag_t eDesiredTag ) // INC new tag stats... // -// TheZone.Stats.iCurrent - unchanged -// TheZone.Stats.iCount - unchanged - TheZone.Stats.iSizesPerTag [pMemory->eTag] += pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]++; + // TheZone.Stats.iCurrent - unchanged + // TheZone.Stats.iCount - unchanged + TheZone.Stats.iSizesPerTag[pMemory->eTag] += pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]++; } -static void Zone_FreeBlock(zoneHeader_t *pMemory) -{ - if (pMemory->eTag != TAG_STATIC) // belt and braces, should never hit this though +static void Zone_FreeBlock(zoneHeader_t *pMemory) { + if (pMemory->eTag != TAG_STATIC) // belt and braces, should never hit this though { // Update stats... // TheZone.Stats.iCount--; TheZone.Stats.iCurrent -= pMemory->iSize; - TheZone.Stats.iSizesPerTag [pMemory->eTag] -= pMemory->iSize; - TheZone.Stats.iCountsPerTag [pMemory->eTag]--; + TheZone.Stats.iSizesPerTag[pMemory->eTag] -= pMemory->iSize; + TheZone.Stats.iCountsPerTag[pMemory->eTag]--; // Sanity checks... // @@ -387,83 +338,71 @@ static void Zone_FreeBlock(zoneHeader_t *pMemory) // Unlink and free... // pMemory->pPrev->pNext = pMemory->pNext; - if(pMemory->pNext) - { + if (pMemory->pNext) { pMemory->pNext->pPrev = pMemory->pPrev; } - free (pMemory); - + free(pMemory); - #ifdef DETAILED_ZONE_DEBUG_CODE +#ifdef DETAILED_ZONE_DEBUG_CODE // this has already been checked for in execution order, but wtf? - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount == 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount == 0) { Com_Error(ERR_FATAL, "Zone_FreeBlock(): Double-freeing block!"); return; } iAllocCount--; - #endif +#endif } } // stats-query function to ask how big a malloc is... // -int Z_Size(void *pvAddress) -{ +int Z_Size(void *pvAddress) { zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->eTag == TAG_STATIC) - { - return 0; // kind of + if (pMemory->eTag == TAG_STATIC) { + return 0; // kind of } - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Size(): Not a valid zone header!"); - return 0; // won't get here + return 0; // won't get here } return pMemory->iSize; } - // Frees a block of memory... // -void Z_Free(void *pvAddress) -{ - if (pvAddress == NULL) // I've put this in as a safety measure because of some bits of #ifdef BSPC stuff -Ste. +void Z_Free(void *pvAddress) { + if (pvAddress == NULL) // I've put this in as a safety measure because of some bits of #ifdef BSPC stuff -Ste. { - //Com_Error(ERR_FATAL, "Z_Free(): NULL arg"); + // Com_Error(ERR_FATAL, "Z_Free(): NULL arg"); return; } zoneHeader_t *pMemory = ((zoneHeader_t *)pvAddress) - 1; - if (pMemory->eTag == TAG_STATIC) - { + if (pMemory->eTag == TAG_STATIC) { return; } - #ifdef DETAILED_ZONE_DEBUG_CODE +#ifdef DETAILED_ZONE_DEBUG_CODE // // check this error *before* barfing on bad magics... // - int& iAllocCount = mapAllocatedZones[pMemory]; - if (iAllocCount <= 0) - { + int &iAllocCount = mapAllocatedZones[pMemory]; + if (iAllocCount <= 0) { Com_Error(ERR_FATAL, "Z_Free(): Block already-freed, or not allocated through Z_Malloc!"); return; } - #endif +#endif - if (pMemory->iMagic != ZONE_MAGIC) - { + if (pMemory->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone header!"); return; } - if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) - { + if (ZoneTailFromHeader(pMemory)->iMagic != ZONE_MAGIC) { Com_Error(ERR_FATAL, "Z_Free(): Corrupt zone tail!"); return; } @@ -471,57 +410,44 @@ void Z_Free(void *pvAddress) Zone_FreeBlock(pMemory); } - -int Z_MemSize(memtag_t eTag) -{ - return TheZone.Stats.iSizesPerTag[eTag]; -} +int Z_MemSize(memtag_t eTag) { return TheZone.Stats.iSizesPerTag[eTag]; } // Frees all blocks with the specified tag... // -void Z_TagFree(memtag_t eTag) -{ -//#ifdef _DEBUG -// int iZoneBlocks = TheZone.Stats.iCount; -//#endif +void Z_TagFree(memtag_t eTag) { + //#ifdef _DEBUG + // int iZoneBlocks = TheZone.Stats.iCount; + //#endif zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { + while (pMemory) { zoneHeader_t *pNext = pMemory->pNext; - if ( (eTag == TAG_ALL) || (pMemory->eTag == eTag)) - { + if ((eTag == TAG_ALL) || (pMemory->eTag == eTag)) { Zone_FreeBlock(pMemory); } pMemory = pNext; } -// these stupid pragmas don't work here???!?!?! -// -//#ifdef _DEBUG -//#pragma warning( disable : 4189) -// int iBlocksFreed = iZoneBlocks - TheZone.Stats.iCount; -//#pragma warning( default : 4189) -//#endif -} - - -void *S_Malloc( int iSize ) { - return Z_Malloc( iSize, TAG_SMALL ); + // these stupid pragmas don't work here???!?!?! + // + //#ifdef _DEBUG + //#pragma warning( disable : 4189) + // int iBlocksFreed = iZoneBlocks - TheZone.Stats.iCount; + //#pragma warning( default : 4189) + //#endif } +void *S_Malloc(int iSize) { return Z_Malloc(iSize, TAG_SMALL); } #ifdef _DEBUG -static void Z_MemRecoverTest_f(void) -{ +static void Z_MemRecoverTest_f(void) { // needs to be in _DEBUG only, not good for final game! // fixme: findmeste: Remove this sometime // int iTotalMalloc = 0; - while (1) - { - int iThisMalloc = 5* (1024 * 1024); - Z_Malloc(iThisMalloc, TAG_SPECIAL_MEM_TEST, qfalse); // and lose, just to consume memory + while (1) { + int iThisMalloc = 5 * (1024 * 1024); + Z_Malloc(iThisMalloc, TAG_SPECIAL_MEM_TEST, qfalse); // and lose, just to consume memory iTotalMalloc += iThisMalloc; if (gbMemFreeupOccured) @@ -532,50 +458,34 @@ static void Z_MemRecoverTest_f(void) } #endif - - // Gives a summary of the zone memory usage -static void Z_Stats_f(void) -{ - Com_Printf("\nThe zone is using %d bytes (%.2fMB) in %d memory blocks\n", - TheZone.Stats.iCurrent, - (float)TheZone.Stats.iCurrent / 1024.0f / 1024.0f, - TheZone.Stats.iCount - ); - - Com_Printf("The zone peaked at %d bytes (%.2fMB)\n", - TheZone.Stats.iPeak, - (float)TheZone.Stats.iPeak / 1024.0f / 1024.0f - ); +static void Z_Stats_f(void) { + Com_Printf("\nThe zone is using %d bytes (%.2fMB) in %d memory blocks\n", TheZone.Stats.iCurrent, (float)TheZone.Stats.iCurrent / 1024.0f / 1024.0f, + TheZone.Stats.iCount); + + Com_Printf("The zone peaked at %d bytes (%.2fMB)\n", TheZone.Stats.iPeak, (float)TheZone.Stats.iPeak / 1024.0f / 1024.0f); } // Gives a detailed breakdown of the memory blocks in the zone -static void Z_Details_f(void) -{ +static void Z_Details_f(void) { Com_Printf("---------------------------------------------------------------------------\n"); - Com_Printf("%20s %9s\n","Zone Tag","Bytes"); - Com_Printf("%20s %9s\n","--------","-----"); - for (int i=0; i= '0' && in[0] <= '9') { - return ((char *)&gNumberString[in[0]-'0']) + sizeof(zoneHeader_t); + return ((char *)&gNumberString[in[0] - '0']) + sizeof(zoneHeader_t); } } - out = (char *) S_Malloc (strlen(in)+1); - strcpy (out, in); + out = (char *)S_Malloc(strlen(in) + 1); + strcpy(out, in); return out; } - - static memtag_t hunk_tag; - /* =============== Com_TouchMemory @@ -663,38 +564,33 @@ Com_TouchMemory Touch all known used data to make sure it is paged in =============== */ -void Com_TouchMemory( void ) { -// int start, end; - int i, j; - unsigned int sum; +void Com_TouchMemory(void) { + // int start, end; + int i, j; + unsigned int sum; -// start = Sys_Milliseconds(); + // start = Sys_Milliseconds(); Z_Validate(); sum = 0; zoneHeader_t *pMemory = TheZone.Header.pNext; - while (pMemory) - { - byte *pMem = (byte *) &pMemory[1]; + while (pMemory) { + byte *pMem = (byte *)&pMemory[1]; j = pMemory->iSize >> 2; - for (i=0; ipNext; } -// end = Sys_Milliseconds(); -// Com_Printf( "Com_TouchMemory: %i msec\n", end - start ); + // end = Sys_Milliseconds(); + // Com_Printf( "Com_TouchMemory: %i msec\n", end - start ); } - - -qboolean Com_TheHunkMarkHasBeenMade(void) -{ - if (hunk_tag == TAG_HUNK_MARK2) - { +qboolean Com_TheHunkMarkHasBeenMade(void) { + if (hunk_tag == TAG_HUNK_MARK2) { return qtrue; } return qfalse; @@ -705,14 +601,13 @@ qboolean Com_TheHunkMarkHasBeenMade(void) Com_InitHunkMemory ================= */ -void Com_InitHunkMemory( void ) { +void Com_InitHunkMemory(void) { hunk_tag = TAG_HUNK_MARK1; Hunk_Clear(); } -void Com_ShutdownHunkMemory(void) -{ - //Er, ok. Clear it then I guess. +void Com_ShutdownHunkMemory(void) { + // Er, ok. Clear it then I guess. Z_TagFree(TAG_HUNK_MARK1); Z_TagFree(TAG_HUNK_MARK2); } @@ -722,8 +617,8 @@ void Com_ShutdownHunkMemory(void) Hunk_MemoryRemaining ==================== */ -int Hunk_MemoryRemaining( void ) { - return (64*1024*1024) - (Z_MemSize(TAG_HUNK_MARK1)+Z_MemSize(TAG_HUNK_MARK2)); //Yeah. Whatever. We've got no size now. +int Hunk_MemoryRemaining(void) { + return (64 * 1024 * 1024) - (Z_MemSize(TAG_HUNK_MARK1) + Z_MemSize(TAG_HUNK_MARK2)); // Yeah. Whatever. We've got no size now. } /* @@ -733,9 +628,7 @@ Hunk_SetMark The server calls this after the level and game VM have been loaded =================== */ -void Hunk_SetMark( void ) { - hunk_tag = TAG_HUNK_MARK2; -} +void Hunk_SetMark(void) { hunk_tag = TAG_HUNK_MARK2; } /* ================= @@ -744,8 +637,8 @@ Hunk_ClearToMark The client calls this before starting a vid_restart or snd_restart ================= */ -void Hunk_ClearToMark( void ) { - assert(hunk_tag == TAG_HUNK_MARK2); //if this is not true then no mark has been made +void Hunk_ClearToMark(void) { + assert(hunk_tag == TAG_HUNK_MARK2); // if this is not true then no mark has been made Z_TagFree(TAG_HUNK_MARK2); } @@ -754,18 +647,17 @@ void Hunk_ClearToMark( void ) { Hunk_CheckMark ================= */ -qboolean Hunk_CheckMark( void ) { - //if( hunk_low.mark || hunk_high.mark ) { - if (hunk_tag != TAG_HUNK_MARK1) - { +qboolean Hunk_CheckMark(void) { + // if( hunk_low.mark || hunk_high.mark ) { + if (hunk_tag != TAG_HUNK_MARK1) { return qtrue; } return qfalse; } -void CL_ShutdownCGame( void ); -void CL_ShutdownUI( void ); -void SV_ShutdownGameProgs( void ); +void CL_ShutdownCGame(void); +void CL_ShutdownUI(void); +void SV_ShutdownGameProgs(void); /* ================= @@ -779,7 +671,7 @@ void R_HunkClearCrap(void); void G2_DEBUG_ReportLeaks(void); #endif -void Hunk_Clear( void ) { +void Hunk_Clear(void) { #ifndef DEDICATED CL_ShutdownCGame(); @@ -795,18 +687,17 @@ void Hunk_Clear( void ) { Z_TagFree(TAG_HUNK_MARK1); Z_TagFree(TAG_HUNK_MARK2); - if ( re && re->HunkClearCrap ) { + if (re && re->HunkClearCrap) { re->HunkClearCrap(); } -// Com_Printf( "Hunk_Clear: reset the hunk ok\n" ); + // Com_Printf( "Hunk_Clear: reset the hunk ok\n" ); VM_Clear(); -//See if any ghoul2 stuff was leaked, at this point it should be all cleaned up. +// See if any ghoul2 stuff was leaked, at this point it should be all cleaned up. #ifdef _FULL_G2_LEAK_CHECKING assert(g_Ghoul2Allocations == 0 && g_G2ClientAlloc == 0 && g_G2ServerAlloc == 0); - if (g_Ghoul2Allocations) - { + if (g_Ghoul2Allocations) { Com_Printf("%i bytes leaked by ghoul2 routines (%i client, %i server)\n", g_Ghoul2Allocations, g_G2ClientAlloc, g_G2ServerAlloc); G2_DEBUG_ReportLeaks(); } @@ -820,9 +711,7 @@ Hunk_Alloc Allocate permanent (until the hunk is cleared) memory ================= */ -void *Hunk_Alloc( int size, ha_pref preference ) { - return Z_Malloc(size, hunk_tag, qtrue); -} +void *Hunk_Alloc(int size, ha_pref preference) { return Z_Malloc(size, hunk_tag, qtrue); } /* ================= @@ -833,22 +722,17 @@ Multiple files can be loaded in temporary memory. When the files-in-use count reaches zero, all temp memory will be deleted ================= */ -void *Hunk_AllocateTempMemory( int size ) { +void *Hunk_AllocateTempMemory(int size) { // don't bother clearing, because we are going to load a file over it return Z_Malloc(size, TAG_TEMP_HUNKALLOC, qfalse); } - /* ================== Hunk_FreeTempMemory ================== */ -void Hunk_FreeTempMemory( void *buf ) -{ - Z_Free(buf); -} - +void Hunk_FreeTempMemory(void *buf) { Z_Free(buf); } /* ================= @@ -859,6 +743,4 @@ touched but unused memory on this side, have future permanent allocs use this side. ================= */ -void Hunk_ClearTempMemory( void ) { - Z_TagFree(TAG_TEMP_HUNKALLOC); -} +void Hunk_ClearTempMemory(void) { Z_TagFree(TAG_TEMP_HUNKALLOC); } diff --git a/codemp/rd-common/tr_font.cpp b/codemp/rd-common/tr_font.cpp index 956e182f75..a21b579dfa 100644 --- a/codemp/rd-common/tr_font.cpp +++ b/codemp/rd-common/tr_font.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -#include "qcommon/sstring.h" // stl string class won't compile in here (MS shite), so use Gil's. +#include "qcommon/sstring.h" // stl string class won't compile in here (MS shite), so use Gil's. #include "tr_local.h" #include "tr_font.h" @@ -34,13 +34,12 @@ cvar_t *r_fontSharpness; // ///////////////////////////////////////////////////////////////////////////////////////////////////////// -typedef enum -{ - eWestern, // ( I only care about asian languages in here at the moment ) - eRussian, // .. but now I need to care about this, since it uses a different TP - ePolish, // ditto +typedef enum { + eWestern, // ( I only care about asian languages in here at the moment ) + eRussian, // .. but now I need to care about this, since it uses a different TP + ePolish, // ditto eKorean, - eTaiwanese, // 15x15 glyphs tucked against BR of 16x16 space + eTaiwanese, // 15x15 glyphs tucked against BR of 16x16 space eJapanese, // 15x15 glyphs tucked against TL of 16x16 space eChinese, // 15x15 glyphs tucked against TL of 16x16 space eThai, // 16x16 cells with glyphs against left edge, special file (tha_widths.dat) for variable widths @@ -48,89 +47,78 @@ typedef enum // this is to cut down on all the stupid string compares I've been doing, and convert asian stuff to switch-case // -Language_e GetLanguageEnum() -{ - static int iSE_Language_ModificationCount = -1234; // any old silly value that won't match the cvar mod count - static Language_e eLanguage = eWestern; +Language_e GetLanguageEnum() { + static int iSE_Language_ModificationCount = -1234; // any old silly value that won't match the cvar mod count + static Language_e eLanguage = eWestern; // only re-strcmp() when language string has changed from what we knew it as... // - if (iSE_Language_ModificationCount != se_language->modificationCount ) - { - iSE_Language_ModificationCount = se_language->modificationCount; - - if ( Language_IsRussian() ) eLanguage = eRussian; - else if ( Language_IsPolish() ) eLanguage = ePolish; - else if ( Language_IsKorean() ) eLanguage = eKorean; - else if ( Language_IsTaiwanese() ) eLanguage = eTaiwanese; - else if ( Language_IsJapanese() ) eLanguage = eJapanese; - else if ( Language_IsChinese() ) eLanguage = eChinese; - else if ( Language_IsThai() ) eLanguage = eThai; - else eLanguage = eWestern; + if (iSE_Language_ModificationCount != se_language->modificationCount) { + iSE_Language_ModificationCount = se_language->modificationCount; + + if (Language_IsRussian()) + eLanguage = eRussian; + else if (Language_IsPolish()) + eLanguage = ePolish; + else if (Language_IsKorean()) + eLanguage = eKorean; + else if (Language_IsTaiwanese()) + eLanguage = eTaiwanese; + else if (Language_IsJapanese()) + eLanguage = eJapanese; + else if (Language_IsChinese()) + eLanguage = eChinese; + else if (Language_IsThai()) + eLanguage = eThai; + else + eLanguage = eWestern; } return eLanguage; } -struct SBCSOverrideLanguages_t -{ +struct SBCSOverrideLanguages_t { const char *m_psName; - Language_e m_eLanguage; + Language_e m_eLanguage; }; // so I can do some stuff with for-next loops when I add polish etc... // -SBCSOverrideLanguages_t g_SBCSOverrideLanguages[]= -{ - {"russian", eRussian}, - {"polish", ePolish}, - {NULL, eWestern} -}; - - +SBCSOverrideLanguages_t g_SBCSOverrideLanguages[] = {{"russian", eRussian}, {"polish", ePolish}, {NULL, eWestern}}; //================================================ // -#define sFILENAME_THAI_WIDTHS "fonts/tha_widths.dat" -#define sFILENAME_THAI_CODES "fonts/tha_codes.dat" +#define sFILENAME_THAI_WIDTHS "fonts/tha_widths.dat" +#define sFILENAME_THAI_CODES "fonts/tha_codes.dat" -struct ThaiCodes_t -{ - std::map m_mapValidCodes; - std::vector m_viGlyphWidths; - sstring_t m_strInitFailureReason; // so we don't have to keep retrying to work this out +struct ThaiCodes_t { + std::map m_mapValidCodes; + std::vector m_viGlyphWidths; + sstring_t m_strInitFailureReason; // so we don't have to keep retrying to work this out - void Clear( void ) - { + void Clear(void) { m_mapValidCodes.clear(); m_viGlyphWidths.clear(); - m_strInitFailureReason = ""; // if blank, never failed, else says don't bother re-trying + m_strInitFailureReason = ""; // if blank, never failed, else says don't bother re-trying } - ThaiCodes_t() - { - Clear(); - } + ThaiCodes_t() { Clear(); } // convert a supplied 1,2 or 3-byte multiplied-up integer into a valid 0..n index, else -1... // - int GetValidIndex( int iCode ) - { - std::map ::iterator it = m_mapValidCodes.find( iCode ); - if (it != m_mapValidCodes.end()) - { - return (*it).second; + int GetValidIndex(int iCode) { + std::map::iterator it = m_mapValidCodes.find(iCode); + if (it != m_mapValidCodes.end()) { + return (*it).second; } return -1; } - int GetWidth( int iGlyphIndex ) - { - if (iGlyphIndex < (int)m_viGlyphWidths.size()) - { - return m_viGlyphWidths[ iGlyphIndex ]; + int GetWidth(int iGlyphIndex) { + if (iGlyphIndex < (int)m_viGlyphWidths.size()) { + return m_viGlyphWidths[iGlyphIndex]; } assert(0); @@ -138,45 +126,36 @@ struct ThaiCodes_t } // return is error message to display, or NULL for success - const char *Init(void) - { - if (m_mapValidCodes.empty() && m_viGlyphWidths.empty()) - { - if (m_strInitFailureReason.empty()) // never tried and failed already? + const char *Init(void) { + if (m_mapValidCodes.empty() && m_viGlyphWidths.empty()) { + if (m_strInitFailureReason.empty()) // never tried and failed already? { - int *piData = NULL; // note , not , for []-access + int *piData = NULL; // note , not , for []-access // // read the valid-codes table in... // - int iBytesRead = ri.FS_ReadFile( sFILENAME_THAI_CODES, (void **) &piData ); - if (iBytesRead > 0 && !(iBytesRead&3)) // valid length and multiple of 4 bytes long + int iBytesRead = ri.FS_ReadFile(sFILENAME_THAI_CODES, (void **)&piData); + if (iBytesRead > 0 && !(iBytesRead & 3)) // valid length and multiple of 4 bytes long { int iTableEntries = iBytesRead / sizeof(int); - for (int i=0; i < iTableEntries; i++) - { - m_mapValidCodes[ piData[i] ] = i; // convert MBCS code to sequential index... + for (int i = 0; i < iTableEntries; i++) { + m_mapValidCodes[piData[i]] = i; // convert MBCS code to sequential index... } - ri.FS_FreeFile( piData ); // dispose of original + ri.FS_FreeFile(piData); // dispose of original // now read in the widths... (I'll keep these in a simple STL vector, so they'all disappear when the entries do... // - iBytesRead = ri.FS_ReadFile( sFILENAME_THAI_WIDTHS, (void **) &piData ); - if (iBytesRead > 0 && !(iBytesRead&3) && iBytesRead>>2/*sizeof(int)*/ == iTableEntries) - { - for (int i=0; i 0 && !(iBytesRead & 3) && iBytesRead >> 2 /*sizeof(int)*/ == iTableEntries) { + for (int i = 0; i < iTableEntries; i++) { + m_viGlyphWidths.push_back(piData[i]); } - ri.FS_FreeFile( piData ); // dispose of original - } - else - { + ri.FS_FreeFile(piData); // dispose of original + } else { m_strInitFailureReason = va("Error with file \"%s\", size = %d!\n", sFILENAME_THAI_WIDTHS, iBytesRead); } - } - else - { + } else { m_strInitFailureReason = va("Error with file \"%s\", size = %d!\n", sFILENAME_THAI_CODES, iBytesRead); } } @@ -186,75 +165,76 @@ struct ThaiCodes_t } }; - -#define GLYPH_MAX_KOREAN_SHADERS 3 +#define GLYPH_MAX_KOREAN_SHADERS 3 #define GLYPH_MAX_TAIWANESE_SHADERS 4 -#define GLYPH_MAX_JAPANESE_SHADERS 3 -#define GLYPH_MAX_CHINESE_SHADERS 3 -#define GLYPH_MAX_THAI_SHADERS 3 -#define GLYPH_MAX_ASIAN_SHADERS 4 // this MUST equal the larger of the above defines +#define GLYPH_MAX_JAPANESE_SHADERS 3 +#define GLYPH_MAX_CHINESE_SHADERS 3 +#define GLYPH_MAX_THAI_SHADERS 3 +#define GLYPH_MAX_ASIAN_SHADERS 4 // this MUST equal the larger of the above defines #define MAX_FONT_VARIANTS 8 -class CFontInfo -{ -private: +class CFontInfo { + private: // From the fontdat file - glyphInfo_t mGlyphs[GLYPH_COUNT]; + glyphInfo_t mGlyphs[GLYPH_COUNT]; -// int mAsianHack; // unused junk from John's fontdat file format. + // int mAsianHack; // unused junk from John's fontdat file format. // end of fontdat data - int mShader; // handle to the shader with the glyph + int mShader; // handle to the shader with the glyph - int m_hAsianShaders[GLYPH_MAX_ASIAN_SHADERS]; // shaders for Korean glyphs where applicable - glyphInfo_t m_AsianGlyph; // special glyph containing asian->western scaling info for all glyphs - int m_iAsianGlyphsAcross; // needed to dynamically calculate S,T coords - int m_iAsianPagesLoaded; - bool m_bAsianLastPageHalfHeight; - int m_iLanguageModificationCount; // doesn't matter what this is, so long as it's comparable as being changed + int m_hAsianShaders[GLYPH_MAX_ASIAN_SHADERS]; // shaders for Korean glyphs where applicable + glyphInfo_t m_AsianGlyph; // special glyph containing asian->western scaling info for all glyphs + int m_iAsianGlyphsAcross; // needed to dynamically calculate S,T coords + int m_iAsianPagesLoaded; + bool m_bAsianLastPageHalfHeight; + int m_iLanguageModificationCount; // doesn't matter what this is, so long as it's comparable as being changed - ThaiCodes_t *m_pThaiData; + ThaiCodes_t *m_pThaiData; -public: - char m_sFontName[MAX_QPATH]; // eg "fonts/lcd" // needed for korean font-hint if we need >1 hangul set - int mPointSize; - int mHeight; - int mAscender; - int mDescender; + public: + char m_sFontName[MAX_QPATH]; // eg "fonts/lcd" // needed for korean font-hint if we need >1 hangul set + int mPointSize; + int mHeight; + int mAscender; + int mDescender; - bool mbRoundCalcs; // trying to make this !@#$%^ thing work with scaling - int m_iThisFont; // handle to itself - int m_iAltSBCSFont; // -1 == NULL // alternative single-byte font for languages like russian/polish etc that need to override high characters ? - int m_iOriginalFontWhenSBCSOverriden; - float m_fAltSBCSFontScaleFactor; // -1, else amount to adjust returned values by to make them fit the master western font they're substituting for - bool m_bIsFakeAlienLanguage; // ... if true, don't process as MBCS or override as SBCS etc + bool mbRoundCalcs; // trying to make this !@#$%^ thing work with scaling + int m_iThisFont; // handle to itself + int m_iAltSBCSFont; // -1 == NULL // alternative single-byte font for languages like russian/polish etc that need to override high characters ? + int m_iOriginalFontWhenSBCSOverriden; + float m_fAltSBCSFontScaleFactor; // -1, else amount to adjust returned values by to make them fit the master western font they're substituting for + bool m_bIsFakeAlienLanguage; // ... if true, don't process as MBCS or override as SBCS etc - CFontInfo *m_variants[MAX_FONT_VARIANTS]; - int m_numVariants; - int m_handle; - qboolean m_isVariant; + CFontInfo *m_variants[MAX_FONT_VARIANTS]; + int m_numVariants; + int m_handle; + qboolean m_isVariant; CFontInfo(const char *fontName); -// CFontInfo(int fill) { memset(this, fill, sizeof(*this)); } // wtf? + // CFontInfo(int fill) { memset(this, fill, sizeof(*this)); } // wtf? ~CFontInfo(void) {} - const int GetPointSize(void) const { return(mPointSize); } - const int GetHeight(void) const { return(mHeight); } - const int GetAscender(void) const { return(mAscender); } - const int GetDescender(void) const { return(mDescender); } + const int GetPointSize(void) const { return (mPointSize); } + const int GetHeight(void) const { return (mHeight); } + const int GetAscender(void) const { return (mAscender); } + const int GetDescender(void) const { return (mDescender); } const glyphInfo_t *GetLetter(const unsigned int uiLetter, int *piShader = NULL); const int GetCollapsedAsianCode(ulong uiLetter) const; const int GetLetterWidth(const unsigned int uiLetter); const int GetLetterHorizAdvance(const unsigned int uiLetter); - const int GetShader(void) const { return(mShader); } + const int GetShader(void) const { return (mShader); } - void FlagNoAsianGlyphs(void) { m_hAsianShaders[0] = 0; m_iLanguageModificationCount = -1; } // used during constructor + void FlagNoAsianGlyphs(void) { + m_hAsianShaders[0] = 0; + m_iLanguageModificationCount = -1; + } // used during constructor bool AsianGlyphsAvailable(void) const { return !!(m_hAsianShaders[0]); } - void UpdateAsianIfNeeded( bool bForceReEval = false); + void UpdateAsianIfNeeded(bool bForceReEval = false); int GetHandle(); @@ -265,103 +245,79 @@ class CFontInfo //================================================ - - - // round float to one decimal place... // -float RoundTenth( float fValue ) -{ - return ( floorf( (fValue*10.0f) + 0.5f) ) / 10.0f; -} - +float RoundTenth(float fValue) { return (floorf((fValue * 10.0f) + 0.5f)) / 10.0f; } -int g_iCurrentFontIndex; // entry 0 is reserved index for missing/invalid, else ++ with each new font registered -std::vector g_vFontArray; -typedef std::map FontIndexMap_t; - FontIndexMap_t g_mapFontIndexes; -int g_iNonScaledCharRange; // this is used with auto-scaling of asian fonts, anything below this number is preserved in scale, anything above is scaled down by 0.75f +int g_iCurrentFontIndex; // entry 0 is reserved index for missing/invalid, else ++ with each new font registered +std::vector g_vFontArray; +typedef std::map FontIndexMap_t; +FontIndexMap_t g_mapFontIndexes; +int g_iNonScaledCharRange; // this is used with auto-scaling of asian fonts, anything below this number is preserved in scale, anything above is scaled down by + // 0.75f -//paletteRGBA_c lastcolour; +// paletteRGBA_c lastcolour; // =============================== some korean stuff ======================================= -#define KSC5601_HANGUL_HIBYTE_START 0xB0 // range is... -#define KSC5601_HANGUL_HIBYTE_STOP 0xC8 // ... inclusive -#define KSC5601_HANGUL_LOBYTE_LOBOUND 0xA0 // range is... -#define KSC5601_HANGUL_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) -#define KSC5601_HANGUL_CODES_PER_ROW 96 // 2 more than the number of glyphs +#define KSC5601_HANGUL_HIBYTE_START 0xB0 // range is... +#define KSC5601_HANGUL_HIBYTE_STOP 0xC8 // ... inclusive +#define KSC5601_HANGUL_LOBYTE_LOBOUND 0xA0 // range is... +#define KSC5601_HANGUL_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) +#define KSC5601_HANGUL_CODES_PER_ROW 96 // 2 more than the number of glyphs -extern qboolean Language_IsKorean( void ); +extern qboolean Language_IsKorean(void); -static inline bool Korean_ValidKSC5601Hangul( byte _iHi, byte _iLo ) -{ - return (_iHi >=KSC5601_HANGUL_HIBYTE_START && - _iHi <=KSC5601_HANGUL_HIBYTE_STOP && - _iLo > KSC5601_HANGUL_LOBYTE_LOBOUND && - _iLo < KSC5601_HANGUL_LOBYTE_HIBOUND - ); -} - -static inline bool Korean_ValidKSC5601Hangul( unsigned int uiCode ) -{ - return Korean_ValidKSC5601Hangul( uiCode >> 8, uiCode & 0xFF ); +static inline bool Korean_ValidKSC5601Hangul(byte _iHi, byte _iLo) { + return (_iHi >= KSC5601_HANGUL_HIBYTE_START && _iHi <= KSC5601_HANGUL_HIBYTE_STOP && _iLo > KSC5601_HANGUL_LOBYTE_LOBOUND && + _iLo < KSC5601_HANGUL_LOBYTE_HIBOUND); } +static inline bool Korean_ValidKSC5601Hangul(unsigned int uiCode) { return Korean_ValidKSC5601Hangul(uiCode >> 8, uiCode & 0xFF); } // takes a KSC5601 double-byte hangul code and collapses down to a 0..n glyph index... // Assumes rows are 96 wide (glyph slots), not 94 wide (actual glyphs), so I can ignore boundary markers // // (invalid hangul codes will return 0) // -static int Korean_CollapseKSC5601HangulCode(unsigned int uiCode) -{ - if (Korean_ValidKSC5601Hangul( uiCode )) - { - uiCode -= (KSC5601_HANGUL_HIBYTE_START * 256) + KSC5601_HANGUL_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards - uiCode = ((uiCode >> 8) * KSC5601_HANGUL_CODES_PER_ROW) + (uiCode & 0xFF); +static int Korean_CollapseKSC5601HangulCode(unsigned int uiCode) { + if (Korean_ValidKSC5601Hangul(uiCode)) { + uiCode -= (KSC5601_HANGUL_HIBYTE_START * 256) + KSC5601_HANGUL_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards + uiCode = ((uiCode >> 8) * KSC5601_HANGUL_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; } return 0; } -static int Korean_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "kor"; - iGlyphTPs = GLYPH_MAX_KOREAN_SHADERS; +static int Korean_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "kor"; + iGlyphTPs = GLYPH_MAX_KOREAN_SHADERS; g_iNonScaledCharRange = 255; - return 32; // m_iAsianGlyphsAcross + return 32; // m_iAsianGlyphsAcross } // ======================== some taiwanese stuff ============================== // (all ranges inclusive for Big5)... // -#define BIG5_HIBYTE_START0 0xA1 // (misc chars + level 1 hanzi) -#define BIG5_HIBYTE_STOP0 0xC6 // -#define BIG5_HIBYTE_START1 0xC9 // (level 2 hanzi) -#define BIG5_HIBYTE_STOP1 0xF9 // -#define BIG5_LOBYTE_LOBOUND0 0x40 // -#define BIG5_LOBYTE_HIBOUND0 0x7E // -#define BIG5_LOBYTE_LOBOUND1 0xA1 // -#define BIG5_LOBYTE_HIBOUND1 0xFE // -#define BIG5_CODES_PER_ROW 160 // 3 more than the number of glyphs - -extern qboolean Language_IsTaiwanese( void ); - -static bool Taiwanese_ValidBig5Code( unsigned int uiCode ) -{ - const byte _iHi = (uiCode >> 8)&0xFF; - if ( (_iHi >= BIG5_HIBYTE_START0 && _iHi <= BIG5_HIBYTE_STOP0) - || (_iHi >= BIG5_HIBYTE_START1 && _iHi <= BIG5_HIBYTE_STOP1) - ) - { +#define BIG5_HIBYTE_START0 0xA1 // (misc chars + level 1 hanzi) +#define BIG5_HIBYTE_STOP0 0xC6 // +#define BIG5_HIBYTE_START1 0xC9 // (level 2 hanzi) +#define BIG5_HIBYTE_STOP1 0xF9 // +#define BIG5_LOBYTE_LOBOUND0 0x40 // +#define BIG5_LOBYTE_HIBOUND0 0x7E // +#define BIG5_LOBYTE_LOBOUND1 0xA1 // +#define BIG5_LOBYTE_HIBOUND1 0xFE // +#define BIG5_CODES_PER_ROW 160 // 3 more than the number of glyphs + +extern qboolean Language_IsTaiwanese(void); + +static bool Taiwanese_ValidBig5Code(unsigned int uiCode) { + const byte _iHi = (uiCode >> 8) & 0xFF; + if ((_iHi >= BIG5_HIBYTE_START0 && _iHi <= BIG5_HIBYTE_STOP0) || (_iHi >= BIG5_HIBYTE_START1 && _iHi <= BIG5_HIBYTE_STOP1)) { const byte _iLo = uiCode & 0xFF; - if ( (_iLo >= BIG5_LOBYTE_LOBOUND0 && _iLo <= BIG5_LOBYTE_HIBOUND0) || - (_iLo >= BIG5_LOBYTE_LOBOUND1 && _iLo <= BIG5_LOBYTE_HIBOUND1) - ) - { + if ((_iLo >= BIG5_LOBYTE_LOBOUND0 && _iLo <= BIG5_LOBYTE_HIBOUND0) || (_iLo >= BIG5_LOBYTE_LOBOUND1 && _iLo <= BIG5_LOBYTE_HIBOUND1)) { return true; } } @@ -369,37 +325,28 @@ static bool Taiwanese_ValidBig5Code( unsigned int uiCode ) return false; } - // only call this when Taiwanese_ValidBig5Code() has already returned true... // -static bool Taiwanese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static bool Taiwanese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 21 chars, those seem to be all the basic punctuation... // - if ( uiCode >= ((BIG5_HIBYTE_START0<<8)|BIG5_LOBYTE_LOBOUND0) && - uiCode < (((BIG5_HIBYTE_START0<<8)|BIG5_LOBYTE_LOBOUND0)+20) - ) - { + if (uiCode >= ((BIG5_HIBYTE_START0 << 8) | BIG5_LOBYTE_LOBOUND0) && uiCode < (((BIG5_HIBYTE_START0 << 8) | BIG5_LOBYTE_LOBOUND0) + 20)) { return true; } return false; } - // takes a BIG5 double-byte code (including level 2 hanzi) and collapses down to a 0..n glyph index... // Assumes rows are 160 wide (glyph slots), not 157 wide (actual glyphs), so I can ignore boundary markers // // (invalid big5 codes will return 0) // -static int Taiwanese_CollapseBig5Code( unsigned int uiCode ) -{ - if (Taiwanese_ValidBig5Code( uiCode )) - { - uiCode -= (BIG5_HIBYTE_START0 * 256) + BIG5_LOBYTE_LOBOUND0; // sneaky maths on both bytes, reduce to 0x0000 onwards - if ( (uiCode & 0xFF) >= (BIG5_LOBYTE_LOBOUND1-1)-BIG5_LOBYTE_LOBOUND0) - { - uiCode -= ((BIG5_LOBYTE_LOBOUND1-1) - (BIG5_LOBYTE_HIBOUND0+1)) -1; +static int Taiwanese_CollapseBig5Code(unsigned int uiCode) { + if (Taiwanese_ValidBig5Code(uiCode)) { + uiCode -= (BIG5_HIBYTE_START0 * 256) + BIG5_LOBYTE_LOBOUND0; // sneaky maths on both bytes, reduce to 0x0000 onwards + if ((uiCode & 0xFF) >= (BIG5_LOBYTE_LOBOUND1 - 1) - BIG5_LOBYTE_LOBOUND0) { + uiCode -= ((BIG5_LOBYTE_LOBOUND1 - 1) - (BIG5_LOBYTE_HIBOUND0 + 1)) - 1; } uiCode = ((uiCode >> 8) * BIG5_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; @@ -407,43 +354,33 @@ static int Taiwanese_CollapseBig5Code( unsigned int uiCode ) return 0; } -static int Taiwanese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "tai"; - iGlyphTPs = GLYPH_MAX_TAIWANESE_SHADERS; +static int Taiwanese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "tai"; + iGlyphTPs = GLYPH_MAX_TAIWANESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } // ======================== some Japanese stuff ============================== - // ( all ranges inclusive for Shift-JIS ) // -#define SHIFTJIS_HIBYTE_START0 0x81 -#define SHIFTJIS_HIBYTE_STOP0 0x9F -#define SHIFTJIS_HIBYTE_START1 0xE0 -#define SHIFTJIS_HIBYTE_STOP1 0xEF +#define SHIFTJIS_HIBYTE_START0 0x81 +#define SHIFTJIS_HIBYTE_STOP0 0x9F +#define SHIFTJIS_HIBYTE_START1 0xE0 +#define SHIFTJIS_HIBYTE_STOP1 0xEF // -#define SHIFTJIS_LOBYTE_START0 0x40 -#define SHIFTJIS_LOBYTE_STOP0 0x7E -#define SHIFTJIS_LOBYTE_START1 0x80 -#define SHIFTJIS_LOBYTE_STOP1 0xFC -#define SHIFTJIS_CODES_PER_ROW (((SHIFTJIS_LOBYTE_STOP0-SHIFTJIS_LOBYTE_START0)+1)+((SHIFTJIS_LOBYTE_STOP1-SHIFTJIS_LOBYTE_START1)+1)) - +#define SHIFTJIS_LOBYTE_START0 0x40 +#define SHIFTJIS_LOBYTE_STOP0 0x7E +#define SHIFTJIS_LOBYTE_START1 0x80 +#define SHIFTJIS_LOBYTE_STOP1 0xFC +#define SHIFTJIS_CODES_PER_ROW (((SHIFTJIS_LOBYTE_STOP0 - SHIFTJIS_LOBYTE_START0) + 1) + ((SHIFTJIS_LOBYTE_STOP1 - SHIFTJIS_LOBYTE_START1) + 1)) -extern qboolean Language_IsJapanese( void ); +extern qboolean Language_IsJapanese(void); -static bool Japanese_ValidShiftJISCode( byte _iHi, byte _iLo ) -{ - if ( (_iHi >= SHIFTJIS_HIBYTE_START0 && _iHi <= SHIFTJIS_HIBYTE_STOP0) - || (_iHi >= SHIFTJIS_HIBYTE_START1 && _iHi <= SHIFTJIS_HIBYTE_STOP1) - ) - { - if ( (_iLo >= SHIFTJIS_LOBYTE_START0 && _iLo <= SHIFTJIS_LOBYTE_STOP0) || - (_iLo >= SHIFTJIS_LOBYTE_START1 && _iLo <= SHIFTJIS_LOBYTE_STOP1) - ) - { +static bool Japanese_ValidShiftJISCode(byte _iHi, byte _iLo) { + if ((_iHi >= SHIFTJIS_HIBYTE_START0 && _iHi <= SHIFTJIS_HIBYTE_STOP0) || (_iHi >= SHIFTJIS_HIBYTE_START1 && _iHi <= SHIFTJIS_HIBYTE_STOP1)) { + if ((_iLo >= SHIFTJIS_LOBYTE_START0 && _iLo <= SHIFTJIS_LOBYTE_STOP0) || (_iLo >= SHIFTJIS_LOBYTE_START1 && _iLo <= SHIFTJIS_LOBYTE_STOP1)) { return true; } } @@ -451,47 +388,34 @@ static bool Japanese_ValidShiftJISCode( byte _iHi, byte _iLo ) return false; } -static inline bool Japanese_ValidShiftJISCode( unsigned int uiCode ) -{ - return Japanese_ValidShiftJISCode( uiCode >> 8, uiCode & 0xFF ); -} - +static inline bool Japanese_ValidShiftJISCode(unsigned int uiCode) { return Japanese_ValidShiftJISCode(uiCode >> 8, uiCode & 0xFF); } // only call this when Japanese_ValidShiftJISCode() has already returned true... // -static bool Japanese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static bool Japanese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 18 chars, those seem to be all the basic punctuation... // - if ( uiCode >= ((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0) && - uiCode < (((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0)+18) - ) - { + if (uiCode >= ((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0) && uiCode < (((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0) + 18)) { return true; } return false; } - // takes a ShiftJIS double-byte code and collapse down to a 0..n glyph index... // // (invalid codes will return 0) // -static int Japanese_CollapseShiftJISCode( unsigned int uiCode ) -{ - if (Japanese_ValidShiftJISCode( uiCode )) - { - uiCode -= ((SHIFTJIS_HIBYTE_START0<<8)|SHIFTJIS_LOBYTE_START0); // sneaky maths on both bytes, reduce to 0x0000 onwards +static int Japanese_CollapseShiftJISCode(unsigned int uiCode) { + if (Japanese_ValidShiftJISCode(uiCode)) { + uiCode -= ((SHIFTJIS_HIBYTE_START0 << 8) | SHIFTJIS_LOBYTE_START0); // sneaky maths on both bytes, reduce to 0x0000 onwards - if ( (uiCode & 0xFF) >= (SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_START0) - { - uiCode -= ((SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_STOP0)-1; + if ((uiCode & 0xFF) >= (SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_START0) { + uiCode -= ((SHIFTJIS_LOBYTE_START1)-SHIFTJIS_LOBYTE_STOP0) - 1; } - if ( ((uiCode>>8)&0xFF) >= (SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_START0) - { - uiCode -= (((SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_STOP0)-1) << 8; + if (((uiCode >> 8) & 0xFF) >= (SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_START0) { + uiCode -= (((SHIFTJIS_HIBYTE_START1)-SHIFTJIS_HIBYTE_STOP0) - 1) << 8; } uiCode = ((uiCode >> 8) * SHIFTJIS_CODES_PER_ROW) + (uiCode & 0xFF); @@ -501,91 +425,72 @@ static int Japanese_CollapseShiftJISCode( unsigned int uiCode ) return 0; } - -static int Japanese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "jap"; - iGlyphTPs = GLYPH_MAX_JAPANESE_SHADERS; +static int Japanese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "jap"; + iGlyphTPs = GLYPH_MAX_JAPANESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } // ======================== some Chinese stuff ============================== -#define GB_HIBYTE_START 0xA1 // range is... -#define GB_HIBYTE_STOP 0xF7 // ... inclusive -#define GB_LOBYTE_LOBOUND 0xA0 // range is... -#define GB_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) -#define GB_CODES_PER_ROW 95 // 1 more than the number of glyphs - -extern qboolean Language_IsChinese( void ); +#define GB_HIBYTE_START 0xA1 // range is... +#define GB_HIBYTE_STOP 0xF7 // ... inclusive +#define GB_LOBYTE_LOBOUND 0xA0 // range is... +#define GB_LOBYTE_HIBOUND 0xFF // ...bounding (ie only valid in between these points, but NULLs in charsets for these codes) +#define GB_CODES_PER_ROW 95 // 1 more than the number of glyphs -static inline bool Chinese_ValidGBCode( byte _iHi, byte _iLo ) -{ - return (_iHi >=GB_HIBYTE_START && - _iHi <=GB_HIBYTE_STOP && - _iLo > GB_LOBYTE_LOBOUND && - _iLo < GB_LOBYTE_HIBOUND - ); -} +extern qboolean Language_IsChinese(void); -static inline bool Chinese_ValidGBCode( unsigned int uiCode) -{ - return Chinese_ValidGBCode( uiCode >> 8, uiCode & 0xFF ); +static inline bool Chinese_ValidGBCode(byte _iHi, byte _iLo) { + return (_iHi >= GB_HIBYTE_START && _iHi <= GB_HIBYTE_STOP && _iLo > GB_LOBYTE_LOBOUND && _iLo < GB_LOBYTE_HIBOUND); } +static inline bool Chinese_ValidGBCode(unsigned int uiCode) { return Chinese_ValidGBCode(uiCode >> 8, uiCode & 0xFF); } // only call this when Chinese_ValidGBCode() has already returned true... // -static bool Chinese_IsTrailingPunctuation( unsigned int uiCode ) -{ +static bool Chinese_IsTrailingPunctuation(unsigned int uiCode) { // so far I'm just counting the first 13 chars, those seem to be all the basic punctuation... // - if ( uiCode > ((GB_HIBYTE_START<<8)|GB_LOBYTE_LOBOUND) && - uiCode < (((GB_HIBYTE_START<<8)|GB_LOBYTE_LOBOUND)+14) - ) - { + if (uiCode > ((GB_HIBYTE_START << 8) | GB_LOBYTE_LOBOUND) && uiCode < (((GB_HIBYTE_START << 8) | GB_LOBYTE_LOBOUND) + 14)) { return true; } return false; } - // takes a GB double-byte code and collapses down to a 0..n glyph index... // Assumes rows are 96 wide (glyph slots), not 94 wide (actual glyphs), so I can ignore boundary markers // // (invalid GB codes will return 0) // -static int Chinese_CollapseGBCode( unsigned int uiCode ) -{ - if (Chinese_ValidGBCode( uiCode )) - { - uiCode -= (GB_HIBYTE_START * 256) + GB_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards - uiCode = ((uiCode >> 8) * GB_CODES_PER_ROW) + (uiCode & 0xFF); +static int Chinese_CollapseGBCode(unsigned int uiCode) { + if (Chinese_ValidGBCode(uiCode)) { + uiCode -= (GB_HIBYTE_START * 256) + GB_LOBYTE_LOBOUND; // sneaky maths on both bytes, reduce to 0x0000 onwards + uiCode = ((uiCode >> 8) * GB_CODES_PER_ROW) + (uiCode & 0xFF); return uiCode; } return 0; } -static int Chinese_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "chi"; - iGlyphTPs = GLYPH_MAX_CHINESE_SHADERS; +static int Chinese_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "chi"; + iGlyphTPs = GLYPH_MAX_CHINESE_SHADERS; g_iNonScaledCharRange = 255; - return 64; // m_iAsianGlyphsAcross + return 64; // m_iAsianGlyphsAcross } // ======================== some Thai stuff ============================== -//TIS 620-2533 +// TIS 620-2533 -#define TIS_GLYPHS_START 160 -#define TIS_SARA_AM 0xD3 // special case letter, both a new letter and a trailing accent for the prev one -ThaiCodes_t g_ThaiCodes; // the one and only instance of this object +#define TIS_GLYPHS_START 160 +#define TIS_SARA_AM 0xD3 // special case letter, both a new letter and a trailing accent for the prev one +ThaiCodes_t g_ThaiCodes; // the one and only instance of this object -extern qboolean Language_IsThai( void ); +extern qboolean Language_IsThai(void); /* static int Thai_IsAccentChar( unsigned int uiCode ) @@ -604,33 +509,29 @@ static int Thai_IsAccentChar( unsigned int uiCode ) // returns a valid Thai code (or 0), based on taking 1,2 or 3 bytes from the supplied byte stream // Fills in with 1,2 or 3 -static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) -{ +static int Thai_ValidTISCode(const byte *psString, int &iThaiBytes) { // try a 1-byte code first... // - if (psString[0] >= 160) // so western letters drop through and use normal font + if (psString[0] >= 160) // so western letters drop through and use normal font { // this code is heavily little-endian, so someone else will need to port for Mac etc... (not my problem ;-) // - union CodeToTry_t - { - char sChars[4]; + union CodeToTry_t { + char sChars[4]; unsigned int uiCode; }; CodeToTry_t CodeToTry; - CodeToTry.uiCode = 0; // important that we clear all 4 bytes in sChars here + CodeToTry.uiCode = 0; // important that we clear all 4 bytes in sChars here // thai codes can be up to 3 bytes long, so see how high we can get... // int i; - for (i=0; i<3; i++) - { + for (i = 0; i < 3; i++) { CodeToTry.sChars[i] = psString[i]; - int iIndex = g_ThaiCodes.GetValidIndex( CodeToTry.uiCode ); - if (iIndex == -1) - { + int iIndex = g_ThaiCodes.GetValidIndex(CodeToTry.uiCode); + if (iIndex == -1) { // failed, so return previous-longest code... // CodeToTry.sChars[i] = 0; @@ -638,7 +539,7 @@ static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) } } iThaiBytes = i; - assert(i); // if 'i' was 0, then this may be an error, trying to get a thai accent as standalone char? + assert(i); // if 'i' was 0, then this may be an error, trying to get a thai accent as standalone char? return CodeToTry.uiCode; } @@ -649,22 +550,17 @@ static int Thai_ValidTISCode( const byte *psString, int &iThaiBytes ) // we tell the translators to put an underscore ('_') between each word even though in Thai they're // all jammed together at final output onscreen... // -static inline bool Thai_IsTrailingPunctuation( unsigned int uiCode ) -{ - return uiCode == '_'; -} +static inline bool Thai_IsTrailingPunctuation(unsigned int uiCode) { return uiCode == '_'; } // takes a TIS 1,2 or 3 byte code and collapse down to a 0..n glyph index... // // (invalid codes will return 0) // -static int Thai_CollapseTISCode( unsigned int uiCode ) -{ - if (uiCode >= TIS_GLYPHS_START) // so western letters drop through as invalid +static int Thai_CollapseTISCode(unsigned int uiCode) { + if (uiCode >= TIS_GLYPHS_START) // so western letters drop through as invalid { - int iCollapsedIndex = g_ThaiCodes.GetValidIndex( uiCode ); - if (iCollapsedIndex != -1) - { + int iCollapsedIndex = g_ThaiCodes.GetValidIndex(uiCode); + if (iCollapsedIndex != -1) { return iCollapsedIndex; } } @@ -672,15 +568,13 @@ static int Thai_CollapseTISCode( unsigned int uiCode ) return 0; } -static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) -{ - psLang = "tha"; - iGlyphTPs = GLYPH_MAX_THAI_SHADERS; - g_iNonScaledCharRange = INT_MAX; // in other words, don't scale any thai chars down - return 32; // m_iAsianGlyphsAcross +static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) { + psLang = "tha"; + iGlyphTPs = GLYPH_MAX_THAI_SHADERS; + g_iNonScaledCharRange = INT_MAX; // in other words, don't scale any thai chars down + return 32; // m_iAsianGlyphsAcross } - // ============================================================================ // takes char *, returns integer char at that point, and advances char * on by enough bytes to move @@ -688,111 +582,90 @@ static int Thai_InitFields(int &iGlyphTPs, const char *&psLang) // // looks messy, but the actual execution route is quite short, so it's fast... // -// Note that I have to have this 3-param form instead of advancing a passed-in "const char **psText" because of VM-crap where you can only change ptr-contents, not ptrs themselves. Bleurgh. Ditto the qtrue:qfalse crap instead of just returning stuff straight through. +// Note that I have to have this 3-param form instead of advancing a passed-in "const char **psText" because of VM-crap where you can only change ptr-contents, +// not ptrs themselves. Bleurgh. Ditto the qtrue:qfalse crap instead of just returning stuff straight through. // -unsigned int AnyLanguage_ReadCharFromString( const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */) -{ - const byte *psString = (const byte *) psText; // avoid sign-promote bug +unsigned int AnyLanguage_ReadCharFromString(const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation /* = NULL */) { + const byte *psString = (const byte *)psText; // avoid sign-promote bug unsigned int uiLetter; - switch ( GetLanguageEnum() ) - { - case eKorean: - { - if ( Korean_ValidKSC5601Hangul( psString[0], psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; - - // not going to bother testing for korean punctuation here, since korean already - // uses spaces, and I don't have the punctuation glyphs defined, only the basic 2350 hanguls - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = qfalse; - } + switch (GetLanguageEnum()) { + case eKorean: { + if (Korean_ValidKSC5601Hangul(psString[0], psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // not going to bother testing for korean punctuation here, since korean already + // uses spaces, and I don't have the punctuation glyphs defined, only the basic 2350 hanguls + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = qfalse; } - } - break; - case eTaiwanese: - { - if ( Taiwanese_ValidBig5Code( (psString[0] * 256) + psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eTaiwanese: { + if (Taiwanese_ValidBig5Code((psString[0] * 256) + psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Taiwanese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eJapanese: - { - if ( Japanese_ValidShiftJISCode( psString[0], psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eJapanese: { + if (Japanese_ValidShiftJISCode(psString[0], psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Japanese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eChinese: - { - if ( Chinese_ValidGBCode( (psString[0] * 256) + psString[1] )) - { - uiLetter = (psString[0] * 256) + psString[1]; - *piAdvanceCount = 2; + return uiLetter; + } + } break; - // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... - // - if ( pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = Chinese_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eChinese: { + if (Chinese_ValidGBCode((psString[0] * 256) + psString[1])) { + uiLetter = (psString[0] * 256) + psString[1]; + *piAdvanceCount = 2; - return uiLetter; + // need to ask if this is a trailing (ie like a comma or full-stop) punctuation?... + // + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Chinese_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } - } - break; - case eThai: - { - int iThaiBytes; - uiLetter = Thai_ValidTISCode( psString, iThaiBytes ); - if ( uiLetter ) - { - *piAdvanceCount = iThaiBytes; + return uiLetter; + } + } break; - if ( pbIsTrailingPunctuation ) - { - *pbIsTrailingPunctuation = Thai_IsTrailingPunctuation( uiLetter ) ? qtrue : qfalse; - } + case eThai: { + int iThaiBytes; + uiLetter = Thai_ValidTISCode(psString, iThaiBytes); + if (uiLetter) { + *piAdvanceCount = iThaiBytes; - return uiLetter; + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = Thai_IsTrailingPunctuation(uiLetter) ? qtrue : qfalse; } + + return uiLetter; } - break; + } break; - default: + default: break; } @@ -801,53 +674,42 @@ unsigned int AnyLanguage_ReadCharFromString( const char *psText, int *piAdvanceC uiLetter = psString[0]; *piAdvanceCount = 1; - if (pbIsTrailingPunctuation) - { - *pbIsTrailingPunctuation = (uiLetter == '!' || - uiLetter == '?' || - uiLetter == ',' || - uiLetter == '.' || - uiLetter == ';' || - uiLetter == ':' - ) ? qtrue : qfalse; + if (pbIsTrailingPunctuation) { + *pbIsTrailingPunctuation = + (uiLetter == '!' || uiLetter == '?' || uiLetter == ',' || uiLetter == '.' || uiLetter == ';' || uiLetter == ':') ? qtrue : qfalse; } return uiLetter; } - // needed for subtitle printing since original code no longer worked once camera bar height was changed to 480/10 // rather than refdef height / 10. I now need to bodge the coords to come out right. // -qboolean Language_IsAsian(void) -{ - switch ( GetLanguageEnum() ) - { - case eKorean: - case eTaiwanese: - case eJapanese: - case eChinese: - case eThai: // this is asian, but the query is normally used for scaling - return qtrue; - default: - break; +qboolean Language_IsAsian(void) { + switch (GetLanguageEnum()) { + case eKorean: + case eTaiwanese: + case eJapanese: + case eChinese: + case eThai: // this is asian, but the query is normally used for scaling + return qtrue; + default: + break; } return qfalse; } -qboolean Language_UsesSpaces(void) -{ +qboolean Language_UsesSpaces(void) { // ( korean uses spaces ) - switch ( GetLanguageEnum() ) - { - case eTaiwanese: - case eJapanese: - case eChinese: - case eThai: - return qfalse; - default: - break; + switch (GetLanguageEnum()) { + case eTaiwanese: + case eJapanese: + case eChinese: + case eThai: + return qfalse; + default: + break; } return qtrue; @@ -859,20 +721,21 @@ qboolean Language_UsesSpaces(void) // If path present, it's a special language hack for SBCS override languages, eg: "lcd/russian", which means // just treat the file as "russian", but with the "lcd" part ensuring we don't find a different registered russian font // -static const char *FontDatPath( const char *_fontName ) { +static const char *FontDatPath(const char *_fontName) { static char fontName[MAX_QPATH]; - sprintf( fontName,"fonts/%s.fontdat",COM_SkipPath(const_cast(_fontName)) ); // COM_SkipPath should take a const char *, but it's just possible people use it as a char * I guess, so I have to hack around like this + sprintf(fontName, "fonts/%s.fontdat", + COM_SkipPath(const_cast(_fontName))); // COM_SkipPath should take a const char *, but it's just possible people use it as a char * I guess, + // so I have to hack around like this return fontName; } -CFontInfo::CFontInfo(const char *_fontName) -{ - int len, i; - void *buff; - dfontdat_t *fontdat; +CFontInfo::CFontInfo(const char *_fontName) { + int len, i; + void *buff; + dfontdat_t *fontdat; // remove any special hack name insertions... // - const char *fontName = FontDatPath( _fontName ); + const char *fontName = FontDatPath(_fontName); // clear some general things... // @@ -881,16 +744,14 @@ CFontInfo::CFontInfo(const char *_fontName) m_iThisFont = -1; m_iOriginalFontWhenSBCSOverriden = -1; m_fAltSBCSFontScaleFactor = -1; - m_bIsFakeAlienLanguage = !strcmp(_fontName,"aurabesh"); // dont try and make SBCS or asian overrides for this + m_bIsFakeAlienLanguage = !strcmp(_fontName, "aurabesh"); // dont try and make SBCS or asian overrides for this len = ri.FS_ReadFile(fontName, NULL); - if (len == sizeof(dfontdat_t)) - { + if (len == sizeof(dfontdat_t)) { ri.FS_ReadFile(fontName, &buff); fontdat = (dfontdat_t *)buff; - for(i = 0; i < GLYPH_COUNT; i++) - { + for (i = 0; i < GLYPH_COUNT; i++) { #ifdef Q3_BIG_ENDIAN mGlyphs[i].width = LittleShort(fontdat->mGlyphs[i].width); mGlyphs[i].height = LittleShort(fontdat->mGlyphs[i].height); @@ -909,28 +770,25 @@ CFontInfo::CFontInfo(const char *_fontName) mHeight = LittleShort(fontdat->mHeight); mAscender = LittleShort(fontdat->mAscender); mDescender = LittleShort(fontdat->mDescender); -// mAsianHack = LittleShort(fontdat->mKoreanHack); // ignore this crap, it's some junk in the fontdat file that no-one uses + // mAsianHack = LittleShort(fontdat->mKoreanHack); // ignore this crap, it's some junk in the fontdat file that no-one uses mbRoundCalcs = false /*!!strstr(fontName,"ergo")*/; // cope with bad fontdat headers... // - if (mHeight == 0) - { + if (mHeight == 0) { mHeight = mPointSize; - mAscender = mPointSize - Round( ((float)mPointSize/10.0f)+2 ); // have to completely guess at the baseline... sigh. - mDescender = mHeight - mAscender; + mAscender = mPointSize - Round(((float)mPointSize / 10.0f) + 2); // have to completely guess at the baseline... sigh. + mDescender = mHeight - mAscender; } ri.FS_FreeFile(buff); - } - else - { + } else { mHeight = 0; mShader = 0; } Q_strncpyz(m_sFontName, fontName, sizeof(m_sFontName)); - COM_StripExtension( m_sFontName, m_sFontName, sizeof( m_sFontName ) ); // so we get better error printing if failed to load shader (ie lose ".fontdat") + COM_StripExtension(m_sFontName, m_sFontName, sizeof(m_sFontName)); // so we get better error printing if failed to load shader (ie lose ".fontdat") mShader = RE_RegisterShaderNoMip(m_sFontName); FlagNoAsianGlyphs(); @@ -941,13 +799,10 @@ CFontInfo::CFontInfo(const char *_fontName) m_handle = g_iCurrentFontIndex; g_vFontArray[g_iCurrentFontIndex++] = this; - - if ( ri.Cvar_VariableIntegerValue( "com_buildScript" ) == 2) - { - Com_Printf( "com_buildScript(2): Registering foreign fonts...\n" ); - static qboolean bDone = qfalse; // Do this once only (for speed)... - if (!bDone) - { + if (ri.Cvar_VariableIntegerValue("com_buildScript") == 2) { + Com_Printf("com_buildScript(2): Registering foreign fonts...\n"); + static qboolean bDone = qfalse; // Do this once only (for speed)... + if (!bDone) { bDone = qtrue; char sTemp[MAX_QPATH]; @@ -957,54 +812,61 @@ CFontInfo::CFontInfo(const char *_fontName) // SBCS override languages... // fileHandle_t f; - for (int i=0; g_SBCSOverrideLanguages[i].m_psName ;i++) - { + for (int i = 0; g_SBCSOverrideLanguages[i].m_psName; i++) { char sTemp[MAX_QPATH]; - sprintf(sTemp,"fonts/%s.tga", g_SBCSOverrideLanguages[i].m_psName ); - ri.FS_FOpenFileRead( sTemp, &f, qfalse ); - if (f) ri.FS_FCloseFile( f ); + sprintf(sTemp, "fonts/%s.tga", g_SBCSOverrideLanguages[i].m_psName); + ri.FS_FOpenFileRead(sTemp, &f, qfalse); + if (f) + ri.FS_FCloseFile(f); - sprintf(sTemp,"fonts/%s.fontdat", g_SBCSOverrideLanguages[i].m_psName ); - ri.FS_FOpenFileRead( sTemp, &f, qfalse ); - if (f) ri.FS_FCloseFile( f ); + sprintf(sTemp, "fonts/%s.fontdat", g_SBCSOverrideLanguages[i].m_psName); + ri.FS_FOpenFileRead(sTemp, &f, qfalse); + if (f) + ri.FS_FCloseFile(f); } // asian MBCS override languages... // - for (int iLang=0; iLang<5; iLang++) - { - switch (iLang) - { - case 0: m_iAsianGlyphsAcross = Korean_InitFields (iGlyphTPs, psLang); break; - case 1: m_iAsianGlyphsAcross = Taiwanese_InitFields (iGlyphTPs, psLang); break; - case 2: m_iAsianGlyphsAcross = Japanese_InitFields (iGlyphTPs, psLang); break; - case 3: m_iAsianGlyphsAcross = Chinese_InitFields (iGlyphTPs, psLang); break; - case 4: m_iAsianGlyphsAcross = Thai_InitFields (iGlyphTPs, psLang); + for (int iLang = 0; iLang < 5; iLang++) { + switch (iLang) { + case 0: + m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); + break; + case 1: + m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); + break; + case 2: + m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); + break; + case 3: + m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); + break; + case 4: + m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); { // additional files needed for Thai language... // - ri.FS_FOpenFileRead( sFILENAME_THAI_WIDTHS , &f, qfalse ); + ri.FS_FOpenFileRead(sFILENAME_THAI_WIDTHS, &f, qfalse); if (f) { - ri.FS_FCloseFile( f ); + ri.FS_FCloseFile(f); } - ri.FS_FOpenFileRead( sFILENAME_THAI_CODES, &f, qfalse ); + ri.FS_FOpenFileRead(sFILENAME_THAI_CODES, &f, qfalse); if (f) { - ri.FS_FCloseFile( f ); + ri.FS_FCloseFile(f); } } - break; + break; } - for (int i=0; imodificationCount || !AsianGlyphsAvailable() || bForceReEval) - { - m_iLanguageModificationCount = se_language->modificationCount; + if (m_iLanguageModificationCount != se_language->modificationCount || !AsianGlyphsAvailable() || bForceReEval) { + m_iLanguageModificationCount = se_language->modificationCount; int iGlyphTPs = 0; const char *psLang = NULL; - switch ( eLanguage ) - { - case eKorean: m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); break; - case eTaiwanese: m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); break; - case eJapanese: m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); break; - case eChinese: m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); break; - case eThai: - { - m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); - - if (!m_pThaiData) - { - const char *psFailureReason = g_ThaiCodes.Init(); - if (!psFailureReason[0]) - { - m_pThaiData = &g_ThaiCodes; - } - else - { - // failed to load a needed file, reset to English... - // - ri.Cvar_Set("se_language", "english"); - Com_Error( ERR_DROP, psFailureReason ); - } + switch (eLanguage) { + case eKorean: + m_iAsianGlyphsAcross = Korean_InitFields(iGlyphTPs, psLang); + break; + case eTaiwanese: + m_iAsianGlyphsAcross = Taiwanese_InitFields(iGlyphTPs, psLang); + break; + case eJapanese: + m_iAsianGlyphsAcross = Japanese_InitFields(iGlyphTPs, psLang); + break; + case eChinese: + m_iAsianGlyphsAcross = Chinese_InitFields(iGlyphTPs, psLang); + break; + case eThai: { + m_iAsianGlyphsAcross = Thai_InitFields(iGlyphTPs, psLang); + + if (!m_pThaiData) { + const char *psFailureReason = g_ThaiCodes.Init(); + if (!psFailureReason[0]) { + m_pThaiData = &g_ThaiCodes; + } else { + // failed to load a needed file, reset to English... + // + ri.Cvar_Set("se_language", "english"); + Com_Error(ERR_DROP, psFailureReason); } } + } break; + default: break; - default: break; } // textures need loading... // - if (m_sFontName[0]) - { + if (m_sFontName[0]) { // Use this sometime if we need to do logic to load alternate-height glyphs to better fit other fonts. // (but for now, we just use the one glyph set) // } - for (int i = 0; i < iGlyphTPs; i++) - { + for (int i = 0; i < iGlyphTPs; i++) { // (Note!! assumption for S,T calculations: all Asian glyph textures pages are square except for last one) // char sTemp[MAX_QPATH]; - Com_sprintf(sTemp,sizeof(sTemp), "fonts/%s_%d_1024_%d", psLang, 1024/m_iAsianGlyphsAcross, i); + Com_sprintf(sTemp, sizeof(sTemp), "fonts/%s_%d_1024_%d", psLang, 1024 / m_iAsianGlyphsAcross, i); // // returning 0 here will automatically inhibit Asian glyph calculations at runtime... // - m_hAsianShaders[i] = RE_RegisterShaderNoMip( sTemp ); + m_hAsianShaders[i] = RE_RegisterShaderNoMip(sTemp); } // for now I'm hardwiring these, but if we ever have more than one glyph set per language then they'll be changed... // - m_iAsianPagesLoaded = iGlyphTPs; // not necessarily true, but will be safe, and show up obvious if something missing + m_iAsianPagesLoaded = iGlyphTPs; // not necessarily true, but will be safe, and show up obvious if something missing m_bAsianLastPageHalfHeight = true; bForceReEval = true; } - if (bForceReEval) - { + if (bForceReEval) { // now init the Asian member glyph fields to make them come out the same size as the western ones // that they serve as an alternative for... // - m_AsianGlyph.width = iCappedHeight; // square Asian chars same size as height of western set - m_AsianGlyph.height = iCappedHeight; // "" - switch (eLanguage) - { - default: m_AsianGlyph.horizAdvance = iCappedHeight; break; - case eKorean: m_AsianGlyph.horizAdvance = iCappedHeight - 1;break; // korean has a small amount of space at the edge of the glyph - - case eTaiwanese: - case eJapanese: - case eChinese: m_AsianGlyph.horizAdvance = iCappedHeight + 3; // need to force some spacing for these -// case eThai: // this is done dynamically elsewhere, since Thai glyphs are variable width + m_AsianGlyph.width = iCappedHeight; // square Asian chars same size as height of western set + m_AsianGlyph.height = iCappedHeight; // "" + switch (eLanguage) { + default: + m_AsianGlyph.horizAdvance = iCappedHeight; + break; + case eKorean: + m_AsianGlyph.horizAdvance = iCappedHeight - 1; + break; // korean has a small amount of space at the edge of the glyph + + case eTaiwanese: + case eJapanese: + case eChinese: + m_AsianGlyph.horizAdvance = iCappedHeight + 3; // need to force some spacing for these + // case eThai: // this is done dynamically elsewhere, since Thai glyphs are variable width } - m_AsianGlyph.horizOffset = 0; // "" - m_AsianGlyph.baseline = mAscender + ((iCappedHeight - mHeight) >> 1); + m_AsianGlyph.horizOffset = 0; // "" + m_AsianGlyph.baseline = mAscender + ((iCappedHeight - mHeight) >> 1); } - } - else - { + } else { // not using Asian... // FlagNoAsianGlyphs(); } - } - else - { + } else { // no western glyphs available, so don't attempt to match asian... // FlagNoAsianGlyphs(); } } -static CFontInfo *GetFont_Actual(int index) -{ +static CFontInfo *GetFont_Actual(int index) { index &= SET_MASK; - if((index >= 1) && (index < g_iCurrentFontIndex)) - { + if ((index >= 1) && (index < g_iCurrentFontIndex)) { CFontInfo *pFont = g_vFontArray[index]; - if (pFont) - { + if (pFont) { pFont->UpdateAsianIfNeeded(); } return pFont; } - return(NULL); + return (NULL); } static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { @@ -1166,8 +1013,7 @@ static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { if (variants > 0) { CFontInfo *variant; - int requestedSize = font->GetPointSize() * *scale * - r_fontSharpness->value * (glConfig.vidHeight / SCREEN_HEIGHT); + int requestedSize = font->GetPointSize() * *scale * r_fontSharpness->value * (glConfig.vidHeight / SCREEN_HEIGHT); if (requestedSize <= font->GetPointSize()) return font; @@ -1189,124 +1035,107 @@ static CFontInfo *RE_Font_GetVariant(CFontInfo *font, float *scale) { // needed to add *piShader param because of multiple TPs, // if not passed in, then I also skip S,T calculations for re-usable static asian glyphinfo struct... // -const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShader /* = NULL */) -{ - if ( AsianGlyphsAvailable() ) - { - int iCollapsedAsianCode = GetCollapsedAsianCode( uiLetter ); - if (iCollapsedAsianCode) - { - if (piShader) - { +const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShader /* = NULL */) { + if (AsianGlyphsAvailable()) { + int iCollapsedAsianCode = GetCollapsedAsianCode(uiLetter); + if (iCollapsedAsianCode) { + if (piShader) { // (Note!! assumption for S,T calculations: all asian glyph textures pages are square except for last one // which may or may not be half height) - but not for Thai // int iTexturePageIndex = iCollapsedAsianCode / (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); - if (iTexturePageIndex > m_iAsianPagesLoaded) - { - assert(0); // should never happen + if (iTexturePageIndex > m_iAsianPagesLoaded) { + assert(0); // should never happen iTexturePageIndex = 0; } - int iOriginalCollapsedAsianCode = iCollapsedAsianCode; // need to back this up (if Thai) for later - iCollapsedAsianCode -= iTexturePageIndex * (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); + int iOriginalCollapsedAsianCode = iCollapsedAsianCode; // need to back this up (if Thai) for later + iCollapsedAsianCode -= iTexturePageIndex * (m_iAsianGlyphsAcross * m_iAsianGlyphsAcross); - const int iColumn = iCollapsedAsianCode % m_iAsianGlyphsAcross; - const int iRow = iCollapsedAsianCode / m_iAsianGlyphsAcross; - const bool bHalfT = (iTexturePageIndex == (m_iAsianPagesLoaded - 1) && m_bAsianLastPageHalfHeight); + const int iColumn = iCollapsedAsianCode % m_iAsianGlyphsAcross; + const int iRow = iCollapsedAsianCode / m_iAsianGlyphsAcross; + const bool bHalfT = (iTexturePageIndex == (m_iAsianPagesLoaded - 1) && m_bAsianLastPageHalfHeight); const int iAsianGlyphsDown = (bHalfT) ? m_iAsianGlyphsAcross / 2 : m_iAsianGlyphsAcross; - switch ( GetLanguageEnum() ) - { - case eKorean: - default: - { - m_AsianGlyph.s = (float)( iColumn ) / (float)m_iAsianGlyphsAcross; - m_AsianGlyph.t = (float)( iRow ) / (float) iAsianGlyphsDown; - m_AsianGlyph.s2 = (float)( iColumn + 1) / (float)m_iAsianGlyphsAcross; - m_AsianGlyph.t2 = (float)( iRow + 1 ) / (float) iAsianGlyphsDown; - } - break; - - case eTaiwanese: - { - m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn ))+1) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow ))+1) / 1024.0f; - m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn+1 )) ) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 )) ) / 1024.0f; - } - break; - - case eJapanese: - case eChinese: - { - m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn )) ) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow )) ) / 1024.0f; - m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * ( iColumn+1 ))-1) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 ))-1) / 1024.0f; + switch (GetLanguageEnum()) { + case eKorean: + default: { + m_AsianGlyph.s = (float)(iColumn) / (float)m_iAsianGlyphsAcross; + m_AsianGlyph.t = (float)(iRow) / (float)iAsianGlyphsDown; + m_AsianGlyph.s2 = (float)(iColumn + 1) / (float)m_iAsianGlyphsAcross; + m_AsianGlyph.t2 = (float)(iRow + 1) / (float)iAsianGlyphsDown; + } break; + + case eTaiwanese: { + m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn)) + 1) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow)) + 1) / 1024.0f; + m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn + 1))) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1))) / 1024.0f; + } break; + + case eJapanese: + case eChinese: { + m_AsianGlyph.s = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn))) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow))) / 1024.0f; + m_AsianGlyph.s2 = (float)(((1024 / m_iAsianGlyphsAcross) * (iColumn + 1)) - 1) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1)) - 1) / 1024.0f; + } break; + + case eThai: { + int iGlyphXpos = (1024 / m_iAsianGlyphsAcross) * (iColumn); + int iGlyphWidth = g_ThaiCodes.GetWidth(iOriginalCollapsedAsianCode); + + // very thai-specific language-code... + // + if (uiLetter == TIS_SARA_AM) { + iGlyphXpos += 9; // these are pixel coords on the source TP, so don't affect scaled output + iGlyphWidth = 20; // } - break; - - case eThai: - { - int iGlyphXpos = (1024 / m_iAsianGlyphsAcross) * ( iColumn ); - int iGlyphWidth = g_ThaiCodes.GetWidth( iOriginalCollapsedAsianCode ); - - // very thai-specific language-code... - // - if (uiLetter == TIS_SARA_AM) - { - iGlyphXpos += 9; // these are pixel coords on the source TP, so don't affect scaled output - iGlyphWidth= 20; // - } - m_AsianGlyph.s = (float)(iGlyphXpos) / 1024.0f; - m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown ) * ( iRow )) ) / 1024.0f; - // technically this .s2 line should be modified to blit only the correct width, but since - // all Thai glyphs are up against the left edge of their cells and have blank to the cell - // boundary then it's better to keep these calculations simpler... + m_AsianGlyph.s = (float)(iGlyphXpos) / 1024.0f; + m_AsianGlyph.t = (float)(((1024 / iAsianGlyphsDown) * (iRow))) / 1024.0f; + // technically this .s2 line should be modified to blit only the correct width, but since + // all Thai glyphs are up against the left edge of their cells and have blank to the cell + // boundary then it's better to keep these calculations simpler... - m_AsianGlyph.s2 = (float)(iGlyphXpos+iGlyphWidth) / 1024.0f; - m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown ) * ( iRow+1 ))-1) / 1024.0f; + m_AsianGlyph.s2 = (float)(iGlyphXpos + iGlyphWidth) / 1024.0f; + m_AsianGlyph.t2 = (float)(((1024 / iAsianGlyphsDown) * (iRow + 1)) - 1) / 1024.0f; - // special addition for Thai, need to bodge up the width and advance fields... - // - m_AsianGlyph.width = iGlyphWidth; - m_AsianGlyph.horizAdvance = iGlyphWidth + 1; - } - break; + // special addition for Thai, need to bodge up the width and advance fields... + // + m_AsianGlyph.width = iGlyphWidth; + m_AsianGlyph.horizAdvance = iGlyphWidth + 1; + } break; } - *piShader = m_hAsianShaders[ iTexturePageIndex ]; + *piShader = m_hAsianShaders[iTexturePageIndex]; } return &m_AsianGlyph; } } - if (piShader) - { + if (piShader) { *piShader = GetShader(); } - const glyphInfo_t *pGlyph = &mGlyphs[ uiLetter & 0xff ]; + const glyphInfo_t *pGlyph = &mGlyphs[uiLetter & 0xff]; // // SBCS language substitution?... // - if ( m_fAltSBCSFontScaleFactor != -1 ) - { + if (m_fAltSBCSFontScaleFactor != -1) { // sod it, use the asian glyph, that's fine... // - memcpy(&m_AsianGlyph,pGlyph,sizeof(m_AsianGlyph)); // *before* changin pGlyph! + memcpy(&m_AsianGlyph, pGlyph, sizeof(m_AsianGlyph)); // *before* changin pGlyph! -// CFontInfo *pOriginalFont = GetFont_Actual( this->m_iOriginalFontWhenSBCSOverriden ); -// pGlyph = &pOriginalFont->mGlyphs[ uiLetter & 0xff ]; + // CFontInfo *pOriginalFont = GetFont_Actual( this->m_iOriginalFontWhenSBCSOverriden ); + // pGlyph = &pOriginalFont->mGlyphs[ uiLetter & 0xff ]; - #define ASSIGN_WITH_ROUNDING(_dst,_src) _dst = mbRoundCalcs ? Round( m_fAltSBCSFontScaleFactor * _src ) : m_fAltSBCSFontScaleFactor * (float)_src; +#define ASSIGN_WITH_ROUNDING(_dst, _src) _dst = mbRoundCalcs ? Round(m_fAltSBCSFontScaleFactor * _src) : m_fAltSBCSFontScaleFactor * (float)_src; - ASSIGN_WITH_ROUNDING( m_AsianGlyph.baseline, pGlyph->baseline ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.height, pGlyph->height ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.horizAdvance,pGlyph->horizAdvance ); -// m_AsianGlyph.horizOffset = /*Round*/( m_fAltSBCSFontScaleFactor * pGlyph->horizOffset ); - ASSIGN_WITH_ROUNDING( m_AsianGlyph.width, pGlyph->width ); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.baseline, pGlyph->baseline); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.height, pGlyph->height); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.horizAdvance, pGlyph->horizAdvance); + // m_AsianGlyph.horizOffset = /*Round*/( m_fAltSBCSFontScaleFactor * pGlyph->horizOffset ); + ASSIGN_WITH_ROUNDING(m_AsianGlyph.width, pGlyph->width); pGlyph = &m_AsianGlyph; } @@ -1314,69 +1143,73 @@ const glyphInfo_t *CFontInfo::GetLetter(const unsigned int uiLetter, int *piShad return pGlyph; } -const int CFontInfo::GetCollapsedAsianCode(ulong uiLetter) const -{ +const int CFontInfo::GetCollapsedAsianCode(ulong uiLetter) const { int iCollapsedAsianCode = 0; - if (AsianGlyphsAvailable()) - { - switch ( GetLanguageEnum() ) - { - case eKorean: iCollapsedAsianCode = Korean_CollapseKSC5601HangulCode( uiLetter ); break; - case eTaiwanese: iCollapsedAsianCode = Taiwanese_CollapseBig5Code( uiLetter ); break; - case eJapanese: iCollapsedAsianCode = Japanese_CollapseShiftJISCode( uiLetter ); break; - case eChinese: iCollapsedAsianCode = Chinese_CollapseGBCode( uiLetter ); break; - case eThai: iCollapsedAsianCode = Thai_CollapseTISCode( uiLetter ); break; - default: assert(0); /* unhandled asian language */ break; + if (AsianGlyphsAvailable()) { + switch (GetLanguageEnum()) { + case eKorean: + iCollapsedAsianCode = Korean_CollapseKSC5601HangulCode(uiLetter); + break; + case eTaiwanese: + iCollapsedAsianCode = Taiwanese_CollapseBig5Code(uiLetter); + break; + case eJapanese: + iCollapsedAsianCode = Japanese_CollapseShiftJISCode(uiLetter); + break; + case eChinese: + iCollapsedAsianCode = Chinese_CollapseGBCode(uiLetter); + break; + case eThai: + iCollapsedAsianCode = Thai_CollapseTISCode(uiLetter); + break; + default: + assert(0); /* unhandled asian language */ + break; } } return iCollapsedAsianCode; } -const int CFontInfo::GetLetterWidth(unsigned int uiLetter) -{ - const glyphInfo_t *pGlyph = GetLetter( uiLetter ); +const int CFontInfo::GetLetterWidth(unsigned int uiLetter) { + const glyphInfo_t *pGlyph = GetLetter(uiLetter); return pGlyph->width ? pGlyph->width : mGlyphs[(unsigned)'.'].width; } -const int CFontInfo::GetLetterHorizAdvance(unsigned int uiLetter) -{ - const glyphInfo_t *pGlyph = GetLetter( uiLetter ); +const int CFontInfo::GetLetterHorizAdvance(unsigned int uiLetter) { + const glyphInfo_t *pGlyph = GetLetter(uiLetter); return pGlyph->horizAdvance ? pGlyph->horizAdvance : mGlyphs[(unsigned)'.'].horizAdvance; } // ensure any GetFont calls that need SBCS overriding (such as when playing in Russian) have the appropriate stuff done... // -static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBCS, const char *psLanguageNameSBCS ) -{ - if ( !pFont->m_bIsFakeAlienLanguage ) - { - if ( GetLanguageEnum() == eLanguageSBCS ) - { - if ( pFont->m_iAltSBCSFont == -1 ) // no reg attempted yet? +static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBCS, const char *psLanguageNameSBCS) { + if (!pFont->m_bIsFakeAlienLanguage) { + if (GetLanguageEnum() == eLanguageSBCS) { + if (pFont->m_iAltSBCSFont == -1) // no reg attempted yet? { // need to register this alternative SBCS font... // - int iAltFontIndex = RE_RegisterFont( va("%s/%s",COM_SkipPath(pFont->m_sFontName),psLanguageNameSBCS) ); // ensure unique name (eg: "lcd/russian") - CFontInfo *pAltFont = GetFont_Actual( iAltFontIndex ); - if ( pAltFont ) - { + int iAltFontIndex = + RE_RegisterFont(va("%s/%s", COM_SkipPath(pFont->m_sFontName), psLanguageNameSBCS)); // ensure unique name (eg: "lcd/russian") + CFontInfo *pAltFont = GetFont_Actual(iAltFontIndex); + if (pAltFont) { // work out the scaling factor for this font's glyphs...( round it to 1 decimal place to cut down on silly scale factors like 0.53125 ) // pAltFont->m_fAltSBCSFontScaleFactor = RoundTenth((float)pFont->GetPointSize() / (float)pAltFont->GetPointSize()); // // then override with the main properties of the original font... // - pAltFont->mPointSize = pFont->GetPointSize();//(float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mHeight = pFont->GetHeight();//(float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mAscender = pFont->GetAscender();//(float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; - pAltFont->mDescender = pFont->GetDescender();//(float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mPointSize = pFont->GetPointSize(); //(float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mHeight = pFont->GetHeight(); //(float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mAscender = pFont->GetAscender(); //(float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; + pAltFont->mDescender = pFont->GetDescender(); //(float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mPointSize = (float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mHeight = (float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mAscender = (float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; -// pAltFont->mDescender = (float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mPointSize = (float) pAltFont->GetPointSize() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mHeight = (float) pAltFont->GetHeight() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mAscender = (float) pAltFont->GetAscender() * pAltFont->m_fAltSBCSFontScaleFactor; + // pAltFont->mDescender = (float) pAltFont->GetDescender() * pAltFont->m_fAltSBCSFontScaleFactor; pAltFont->mbRoundCalcs = true; pAltFont->m_iOriginalFontWhenSBCSOverriden = pFont->m_iThisFont; @@ -1384,9 +1217,8 @@ static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBC pFont->m_iAltSBCSFont = iAltFontIndex; } - if ( pFont->m_iAltSBCSFont > 0) - { - return GetFont_Actual( pFont->m_iAltSBCSFont ); + if (pFont->m_iAltSBCSFont > 0) { + return GetFont_Actual(pFont->m_iAltSBCSFont); } } } @@ -1394,21 +1226,15 @@ static CFontInfo *GetFont_SBCSOverride(CFontInfo *pFont, Language_e eLanguageSBC return NULL; } +CFontInfo *GetFont(int index) { + CFontInfo *pFont = GetFont_Actual(index); - -CFontInfo *GetFont(int index) -{ - CFontInfo *pFont = GetFont_Actual( index ); - - if (pFont) - { + if (pFont) { // any SBCS overrides? (this has to be pretty quick, and is (sort of))... // - for (int i=0; g_SBCSOverrideLanguages[i].m_psName; i++) - { - CFontInfo *pAltFont = GetFont_SBCSOverride( pFont, g_SBCSOverrideLanguages[i].m_eLanguage, g_SBCSOverrideLanguages[i].m_psName ); - if (pAltFont) - { + for (int i = 0; g_SBCSOverrideLanguages[i].m_psName; i++) { + CFontInfo *pAltFont = GetFont_SBCSOverride(pFont, g_SBCSOverrideLanguages[i].m_eLanguage, g_SBCSOverrideLanguages[i].m_psName); + if (pAltFont) { return pAltFont; } } @@ -1417,57 +1243,48 @@ CFontInfo *GetFont(int index) return pFont; } -float RE_Font_StrLenPixelsNew( const char *psText, const int iFontHandle, const float fScaleIn ) { +float RE_Font_StrLenPixelsNew(const char *psText, const int iFontHandle, const float fScaleIn) { float fScale = fScaleIn; CFontInfo *curfont = GetFont(iFontHandle); - if ( !curfont ) { + if (!curfont) { return 0.0f; } curfont = RE_Font_GetVariant(curfont, &fScale); float fScaleAsian = fScale; - if (Language_IsAsian() && fScale > 0.7f ) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; } float maxLineWidth = 0.0f; float thisLineWidth = 0.0f; - while ( *psText ) { + while (*psText) { int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - if ( uiLetter == '^' ) { - if ( *psText >= '0' && *psText <= '9' ) { - uiLetter = AnyLanguage_ReadCharFromString( psText, &iAdvanceCount, NULL ); + if (uiLetter == '^') { + if (*psText >= '0' && *psText <= '9') { + uiLetter = AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, NULL); psText += iAdvanceCount; continue; } } - if ( uiLetter == '\n' ) { + if (uiLetter == '\n') { thisLineWidth = 0.0f; - } - else { - float iPixelAdvance = (float)curfont->GetLetterHorizAdvance( uiLetter ); + } else { + float iPixelAdvance = (float)curfont->GetLetterHorizAdvance(uiLetter); float fValue = iPixelAdvance * ((uiLetter > (unsigned)g_iNonScaledCharRange) ? fScaleAsian : fScale); - if ( r_aspectCorrectFonts->integer == 1 ) { + if (r_aspectCorrectFonts->integer == 1) { fValue *= ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)); + } else if (r_aspectCorrectFonts->integer == 2) { + fValue = ceilf(fValue * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth))); } - else if ( r_aspectCorrectFonts->integer == 2 ) { - fValue = ceilf( - fValue * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)) - ); - } - thisLineWidth += curfont->mbRoundCalcs - ? roundf( fValue ) - : (r_aspectCorrectFonts->integer == 2) - ? ceilf( fValue ) - : fValue; - if ( thisLineWidth > maxLineWidth ) { + thisLineWidth += curfont->mbRoundCalcs ? roundf(fValue) : (r_aspectCorrectFonts->integer == 2) ? ceilf(fValue) : fValue; + if (thisLineWidth > maxLineWidth) { maxLineWidth = thisLineWidth; } } @@ -1475,135 +1292,127 @@ float RE_Font_StrLenPixelsNew( const char *psText, const int iFontHandle, const return maxLineWidth; } -int RE_Font_StrLenPixels( const char *psText, const int iFontHandle, const float fScale ) { - return (int)ceilf( RE_Font_StrLenPixelsNew( psText, iFontHandle, fScale ) ); +int RE_Font_StrLenPixels(const char *psText, const int iFontHandle, const float fScale) { + return (int)ceilf(RE_Font_StrLenPixelsNew(psText, iFontHandle, fScale)); } // not really a font function, but keeps naming consistant... // -int RE_Font_StrLenChars(const char *psText) -{ +int RE_Font_StrLenChars(const char *psText) { // logic for this function's letter counting must be kept same in this function and RE_Font_DrawString() // int iCharCount = 0; - while ( *psText ) - { + while (*psText) { // in other words, colour codes and CR/LF don't count as chars, all else does... // int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - switch (uiLetter) - { - case '^': - if (*psText >= '0' && - *psText <= '9') - { - psText++; - } - else - { - iCharCount++; - } - break; // colour code (note next-char skip) - case 10: break; // linefeed - case 13: break; // return - case '_': iCharCount += (GetLanguageEnum() == eThai && (((unsigned char *)psText)[0] >= TIS_GLYPHS_START))?0:1; break; // special word-break hack - default: iCharCount++; break; + switch (uiLetter) { + case '^': + if (*psText >= '0' && *psText <= '9') { + psText++; + } else { + iCharCount++; + } + break; // colour code (note next-char skip) + case 10: + break; // linefeed + case 13: + break; // return + case '_': + iCharCount += (GetLanguageEnum() == eThai && (((unsigned char *)psText)[0] >= TIS_GLYPHS_START)) ? 0 : 1; + break; // special word-break hack + default: + iCharCount++; + break; } } return iCharCount; } -int RE_Font_HeightPixels(const int iFontHandle, const float fScaleIn) -{ +int RE_Font_HeightPixels(const int iFontHandle, const float fScaleIn) { float fScale = fScaleIn; - CFontInfo *curfont; + CFontInfo *curfont; curfont = GetFont(iFontHandle); - if(curfont) - { + if (curfont) { float fValue; curfont = RE_Font_GetVariant(curfont, &fScale); fValue = curfont->GetPointSize() * fScale; return curfont->mbRoundCalcs ? Round(fValue) : fValue; } - return(0); + return (0); } // iMaxPixelWidth is -1 for "all of string", else pixel display count... // -void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, const int iFontHandleIn, int iMaxPixelWidth, const float fScaleIn) -{ - static qboolean gbInShadow = qfalse; // MUST default to this - float fox, foy, fx, fy; - int colour, offset; - const glyphInfo_t *pLetter; - qhandle_t hShader; - float fScale = fScaleIn; - int iFontHandle = iFontHandleIn; +void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, const int iFontHandleIn, int iMaxPixelWidth, const float fScaleIn) { + static qboolean gbInShadow = qfalse; // MUST default to this + float fox, foy, fx, fy; + int colour, offset; + const glyphInfo_t *pLetter; + qhandle_t hShader; + float fScale = fScaleIn; + int iFontHandle = iFontHandleIn; - assert (psText); + assert(psText); - if(iFontHandle & STYLE_BLINK) - { - if((ri.Milliseconds() >> 7) & 1) - { + if (iFontHandle & STYLE_BLINK) { + if ((ri.Milliseconds() >> 7) & 1) { return; } } -// // test code only -// if (GetLanguageEnum() == eTaiwanese) -// { -// psText = "Wp:¶}·F§a ¿p·G´µ¡A§Æ±æ§A¹³¥L­Ì»¡ªº¤@¼Ë¦æ¡C"; -// } -// else -// if (GetLanguageEnum() == eChinese) -// { -// //psText = "Ó¶±øÕ½³¡II Ô¼º²?ĪÁÖ˹ ÈÎÎñʧ°Ü ÄãÒªÌ×Óû­ÃæÉ趨µÄ±ä¸üÂ𣿠ԤÉè,S3 ѹËõ,DXT1 ѹËõ,DXT5 ѹËõ,16 Bit,32 Bit"; -// psText = "Ó¶±øÕ½³¡II"; -// } -// else -// if (GetLanguageEnum() == eThai) -// { -// //psText = "Áҵðҹ¼ÅÔµÀѳ±ìÍصÊÒË¡ÃÃÁÃËÑÊÊÓËÃѺÍÑ¡¢ÃÐä·Â·Õèãªé¡Ñº¤ÍÁ¾ÔÇàµÍÃì"; -// psText = "Áҵðҹ¼ÅÔµ"; -// psText = "ÃËÑÊÊÓËÃѺ"; -// psText = "ÃËÑÊÊÓËÃѺ ÍÒ_¡Ô¹_¤ÍÃì·_1415"; -// } -// else -// if (GetLanguageEnum() == eKorean) -// { -// psText = "Wp:¼îŸÀÓÀÌ´Ù ¸Ö¸°. ±×µéÀÌ ¸»ÇÑ´ë·Î ³×°¡ ÀßÇÒÁö ±â´ëÇÏ°Ú´Ù."; -// } -// else -// if (GetLanguageEnum() == eJapanese) -// { -// static char sBlah[200]; -// sprintf(sBlah,va("%c%c%c%c%c%c%c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); -// psText = &sBlah[0]; -// } -// else -// if (GetLanguageEnum() == eRussian) -// { -//// //psText = "Íà âåðøèíå õîëìà ñòîèò ñòàðûé äîì ñ ïðèâèäåíèÿìè è áàøíÿ ñ âîëøåáíûìè ÷àñàìè." -// psText = "Íà âåðøèíå õîëìà ñòîèò"; -// } -// else -// if (GetLanguageEnum() == ePolish) -// { -// psText = "za³o¿ony w 1364 roku, jest najstarsz¹ polsk¹ uczelni¹ i nale¿y..."; -// psText = "za³o¿ony nale¿y"; -// } - + // // test code only + // if (GetLanguageEnum() == eTaiwanese) + // { + // psText = "Wp:¶}·F§a ¿p·G´µ¡A§Æ±æ§A¹³¥L­Ì»¡ªº¤@¼Ë¦æ¡C"; + // } + // else + // if (GetLanguageEnum() == eChinese) + // { + // //psText = "Ó¶±øÕ½³¡II Ô¼º²?ĪÁÖ˹ ÈÎÎñʧ°Ü ÄãÒªÌ×Óû­ÃæÉ趨µÄ±ä¸üÂ𣿠ԤÉè,S3 ѹËõ,DXT1 ѹËõ,DXT5 ѹËõ,16 Bit,32 Bit"; + // psText = "Ó¶±øÕ½³¡II"; + // } + // else + // if (GetLanguageEnum() == eThai) + // { + // //psText = "Áҵðҹ¼ÅÔµÀѳ±ìÍصÊÒË¡ÃÃÁÃËÑÊÊÓËÃѺÍÑ¡¢ÃÐä·Â·Õèãªé¡Ñº¤ÍÁ¾ÔÇàµÍÃì"; + // psText = "Áҵðҹ¼ÅÔµ"; + // psText = "ÃËÑÊÊÓËÃѺ"; + // psText = "ÃËÑÊÊÓËÃѺ ÍÒ_¡Ô¹_¤ÍÃì·_1415"; + // } + // else + // if (GetLanguageEnum() == eKorean) + // { + // psText = "Wp:¼îŸÀÓÀÌ´Ù ¸Ö¸°. ±×µéÀÌ ¸»ÇÑ´ë·Î ³×°¡ ÀßÇÒÁö ±â´ëÇÏ°Ú´Ù."; + // } + // else + // if (GetLanguageEnum() == eJapanese) + // { + // static char sBlah[200]; + // sprintf(sBlah,va("%c%c%c%c%c%c%c%c",0x82,0xA9,0x82,0xC8,0x8A,0xBF,0x8E,0x9A)); + // psText = &sBlah[0]; + // } + // else + // if (GetLanguageEnum() == eRussian) + // { + //// //psText = "Íà âåðøèíå õîëìà ñòîèò ñòàðûé äîì ñ ïðèâèäåíèÿìè è áàøíÿ ñ âîëøåáíûìè ÷àñàìè." + // psText = "Íà âåðøèíå õîëìà ñòîèò"; + // } + // else + // if (GetLanguageEnum() == ePolish) + // { + // psText = "za³o¿ony w 1364 roku, jest najstarsz¹ polsk¹ uczelni¹ i nale¿y..."; + // psText = "za³o¿ony nale¿y"; + // } CFontInfo *curfont = GetFont(iFontHandle); - if(!curfont || !psText) - { + if (!curfont || !psText) { return; } curfont = RE_Font_GetVariant(curfont, &fScale); @@ -1611,25 +1420,23 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c float fScaleAsian = fScale; float fAsianYAdjust = 0.0f; - if (Language_IsAsian() && fScale > 0.7f) - { + if (Language_IsAsian() && fScale > 0.7f) { fScaleAsian = fScale * 0.75f; fAsianYAdjust = ((curfont->GetPointSize() * fScale) - (curfont->GetPointSize() * fScaleAsian)) / 2.0f; } // Draw a dropshadow if required - if(iFontHandle & STYLE_DROPSHADOW) - { + if (iFontHandle & STYLE_DROPSHADOW) { offset = Round(curfont->GetPointSize() * fScale * 0.075f); - const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba?rgba[3]:1.0f}; + const vec4_t v4DKGREY2 = {0.15f, 0.15f, 0.15f, rgba ? rgba[3] : 1.0f}; gbInShadow = qtrue; RE_Font_DrawString(ox + offset, oy + offset, psText, v4DKGREY2, iFontHandle & SET_MASK, iMaxPixelWidth, fScale); gbInShadow = qfalse; } - RE_SetColor( rgba ); + RE_SetColor(rgba); // Now we take off the training wheels and become a big font renderer // It's all floats from here on out @@ -1637,60 +1444,54 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c foy = oy; fx = fox; - foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; + foy += curfont->mbRoundCalcs ? Round((curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale) + : (curfont->GetHeight() - (curfont->GetDescender() >> 1)) * fScale; qboolean bNextTextWouldOverflow = qfalse; - while (*psText && !bNextTextWouldOverflow) - { + while (*psText && !bNextTextWouldOverflow) { int iAdvanceCount; - unsigned int uiLetter = AnyLanguage_ReadCharFromString( psText, &iAdvanceCount, NULL ); + unsigned int uiLetter = AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - switch( uiLetter ) - { - case 10: //linefeed + switch (uiLetter) { + case 10: // linefeed fx = fox; foy += curfont->mbRoundCalcs ? Round(curfont->GetPointSize() * fScale) : curfont->GetPointSize() * fScale; - if (Language_IsAsian()) - { - foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder functions + if (Language_IsAsian()) { + foy += 4.0f; // this only comes into effect when playing in asian for "A long time ago in a galaxy" etc, all other text is line-broken in feeder + // functions } break; - case 13: // Return + case 13: // Return break; - case 32: // Space + case 32: // Space pLetter = curfont->GetLetter(' '); fx += curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fScale) : pLetter->horizAdvance * fScale; - bNextTextWouldOverflow = ( iMaxPixelWidth != -1 && ((fx-fox) > (float)iMaxPixelWidth) ) ? qtrue : qfalse; // yeuch + bNextTextWouldOverflow = (iMaxPixelWidth != -1 && ((fx - fox) > (float)iMaxPixelWidth)) ? qtrue : qfalse; // yeuch break; - case '_': // has a special word-break usage if in Thai (and followed by a thai char), and should not be displayed, else treat as normal - if (GetLanguageEnum()== eThai && ((unsigned char *)psText)[0] >= TIS_GLYPHS_START) - { + case '_': // has a special word-break usage if in Thai (and followed by a thai char), and should not be displayed, else treat as normal + if (GetLanguageEnum() == eThai && ((unsigned char *)psText)[0] >= TIS_GLYPHS_START) { break; } // else drop through and display as normal... case '^': - if (uiLetter != '_') // necessary because of fallthrough above + if (uiLetter != '_') // necessary because of fallthrough above { - if (*psText >= '0' && - *psText <= '9') - { + if (*psText >= '0' && *psText <= '9') { colour = ColorIndex(*psText++); - if (!gbInShadow) - { + if (!gbInShadow) { vec4_t color; - Com_Memcpy( color, g_color_table[colour], sizeof( color ) ); + Com_Memcpy(color, g_color_table[colour], sizeof(color)); color[3] = rgba ? rgba[3] : 1.0f; - RE_SetColor( color ); + RE_SetColor(color); } break; } } - //purposely falls thrugh + // purposely falls thrugh default: - pLetter = curfont->GetLetter( uiLetter, &hShader ); // Description of pLetter - if(!pLetter->width) - { + pLetter = curfont->GetLetter(uiLetter, &hShader); // Description of pLetter + if (!pLetter->width) { pLetter = curfont->GetLetter('.'); } @@ -1698,57 +1499,48 @@ void RE_Font_DrawString(int ox, int oy, const char *psText, const float *rgba, c // sigh, super-language-specific hack... // - if (uiLetter == TIS_SARA_AM && GetLanguageEnum() == eThai) - { + if (uiLetter == TIS_SARA_AM && GetLanguageEnum() == eThai) { fx -= curfont->mbRoundCalcs ? Round(7.0f * fThisScale) : 7.0f * fThisScale; } float fAdvancePixels = curfont->mbRoundCalcs ? Round(pLetter->horizAdvance * fThisScale) : pLetter->horizAdvance * fThisScale; - bNextTextWouldOverflow = ( iMaxPixelWidth != -1 && (((fx+fAdvancePixels)-fox) > (float)iMaxPixelWidth) ) ? qtrue : qfalse; // yeuch - if (!bNextTextWouldOverflow) - { + bNextTextWouldOverflow = (iMaxPixelWidth != -1 && (((fx + fAdvancePixels) - fox) > (float)iMaxPixelWidth)) ? qtrue : qfalse; // yeuch + if (!bNextTextWouldOverflow) { // this 'mbRoundCalcs' stuff is crap, but the only way to make the font code work. Sigh... // fy = foy - (curfont->mbRoundCalcs ? Round(pLetter->baseline * fThisScale) : pLetter->baseline * fThisScale); - if (curfont->m_fAltSBCSFontScaleFactor != -1) - { + if (curfont->m_fAltSBCSFontScaleFactor != -1) { fy += 3.0f; // I'm sick and tired of going round in circles trying to do this legally, so bollocks to it } RE_StretchPic(curfont->mbRoundCalcs ? fx + Round(pLetter->horizOffset * fThisScale) : fx + pLetter->horizOffset * fThisScale, // float x - (uiLetter > (unsigned)g_iNonScaledCharRange) ? fy - fAsianYAdjust : fy, // float y - curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w - curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h - pLetter->s, // float s1 - pLetter->t, // float t1 - pLetter->s2, // float s2 - pLetter->t2, // float t2 - //lastcolour.c, - hShader // qhandle_t hShader - ); - if ( r_aspectCorrectFonts->integer == 1 ) { - fx += fAdvancePixels - * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)); - } - else if ( r_aspectCorrectFonts->integer == 2 ) { - fx += ceilf( fAdvancePixels - * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)) ); - } - else { + (uiLetter > (unsigned)g_iNonScaledCharRange) ? fy - fAsianYAdjust : fy, // float y + curfont->mbRoundCalcs ? Round(pLetter->width * fThisScale) : pLetter->width * fThisScale, // float w + curfont->mbRoundCalcs ? Round(pLetter->height * fThisScale) : pLetter->height * fThisScale, // float h + pLetter->s, // float s1 + pLetter->t, // float t1 + pLetter->s2, // float s2 + pLetter->t2, // float t2 + // lastcolour.c, + hShader // qhandle_t hShader + ); + if (r_aspectCorrectFonts->integer == 1) { + fx += fAdvancePixels * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)); + } else if (r_aspectCorrectFonts->integer == 2) { + fx += ceilf(fAdvancePixels * ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth))); + } else { fx += fAdvancePixels; } } break; } } - //let it remember the old color //RE_SetColor(NULL); + // let it remember the old color //RE_SetColor(NULL); } -static int RE_RegisterFont_Real(const char *psName) -{ +static int RE_RegisterFont_Real(const char *psName) { FontIndexMap_t::iterator it = g_mapFontIndexes.find(psName); - if (it != g_mapFontIndexes.end() ) - { + if (it != g_mapFontIndexes.end()) { int iFontIndex = (*it).second; return iFontIndex; } @@ -1757,16 +1549,13 @@ static int RE_RegisterFont_Real(const char *psName) // { CFontInfo *pFont = new CFontInfo(psName); - if (pFont->GetPointSize() > 0) - { + if (pFont->GetPointSize() > 0) { int iFontIndex = g_iCurrentFontIndex - 1; g_mapFontIndexes[psName] = iFontIndex; pFont->m_iThisFont = iFontIndex; return iFontIndex; - } - else - { - g_mapFontIndexes[psName] = 0; // missing/invalid + } else { + g_mapFontIndexes[psName] = 0; // missing/invalid } } @@ -1780,9 +1569,9 @@ int RE_RegisterFont(const char *psName) { if (oriFont->GetNumVariants() == 0) { for (int i = 0; i < MAX_FONT_VARIANTS; i++) { - const char *variantName = va( "%s_sharp%i", psName, i + 1 ); - const char *fontDatPath = FontDatPath( variantName ); - if ( ri.FS_ReadFile(fontDatPath, NULL) > 0 ) { + const char *variantName = va("%s_sharp%i", psName, i + 1); + const char *fontDatPath = FontDatPath(variantName); + if (ri.FS_ReadFile(fontDatPath, NULL) > 0) { int replacerFontHandle = RE_RegisterFont_Real(variantName); if (replacerFontHandle) { CFontInfo *replacerFont = GetFont_Actual(replacerFontHandle); @@ -1797,18 +1586,17 @@ int RE_RegisterFont(const char *psName) { } } } else { - ri.Printf( PRINT_WARNING, "RE_RegisterFont: Couldn't find font %s\n", psName ); + ri.Printf(PRINT_WARNING, "RE_RegisterFont: Couldn't find font %s\n", psName); } return oriFontHandle; } -void R_InitFonts(void) -{ - g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" - g_iNonScaledCharRange = INT_MAX; // default all chars to have no special scaling (other than user supplied) +void R_InitFonts(void) { + g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" + g_iNonScaledCharRange = INT_MAX; // default all chars to have no special scaling (other than user supplied) - r_fontSharpness = ri.Cvar_Get( "r_fontSharpness", "1", CVAR_ARCHIVE_ND, "" ); + r_fontSharpness = ri.Cvar_Get("r_fontSharpness", "1", CVAR_ARCHIVE_ND, ""); } /* @@ -1816,87 +1604,77 @@ void R_InitFonts(void) R_FontList_f =============== */ -void R_FontList_f( void ) { - Com_Printf ("------------------------------------\n"); +void R_FontList_f(void) { + Com_Printf("------------------------------------\n"); FontIndexMap_t::iterator it; - for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) - { + for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) { CFontInfo *font = GetFont((*it).second); - if( font ) - { - Com_Printf("%3i:%s ps:%hi h:%hi a:%hi d:%hi\n", (*it).second, font->m_sFontName, - font->mPointSize, font->mHeight, font->mAscender, font->mDescender); + if (font) { + Com_Printf("%3i:%s ps:%hi h:%hi a:%hi d:%hi\n", (*it).second, font->m_sFontName, font->mPointSize, font->mHeight, font->mAscender, + font->mDescender); } } - Com_Printf ("------------------------------------\n"); + Com_Printf("------------------------------------\n"); } -void R_ShutdownFonts(void) -{ - for(int i = 1; i < g_iCurrentFontIndex; i++) // entry 0 is reserved for "missing/invalid" +void R_ShutdownFonts(void) { + for (int i = 1; i < g_iCurrentFontIndex; i++) // entry 0 is reserved for "missing/invalid" { delete g_vFontArray[i]; } g_mapFontIndexes.clear(); g_vFontArray.clear(); - g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" + g_iCurrentFontIndex = 1; // entry 0 is reserved for "missing/invalid" g_ThaiCodes.Clear(); } // this is only really for debugging while tinkering with fonts, but harmless to leave in... // -void R_ReloadFonts_f(void) -{ +void R_ReloadFonts_f(void) { // first, grab all the currently-registered fonts IN THE ORDER THEY WERE REGISTERED... // - std::vector vstrFonts; + std::vector vstrFonts; int iFontToFind; - for (iFontToFind = 1; iFontToFind < g_iCurrentFontIndex; iFontToFind++) - { + for (iFontToFind = 1; iFontToFind < g_iCurrentFontIndex; iFontToFind++) { FontIndexMap_t::iterator it; - CFontInfo *font = GetFont( iFontToFind ); - if ( font && font->m_isVariant ) continue; - for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) - { - if (iFontToFind == (*it).second) - { - vstrFonts.push_back( (*it).first ); + CFontInfo *font = GetFont(iFontToFind); + if (font && font->m_isVariant) + continue; + for (it = g_mapFontIndexes.begin(); it != g_mapFontIndexes.end(); ++it) { + if (iFontToFind == (*it).second) { + vstrFonts.push_back((*it).first); break; } } - if (it == g_mapFontIndexes.end() ) - { - break; // couldn't find this font + if (it == g_mapFontIndexes.end()) { + break; // couldn't find this font } } - if ( iFontToFind == g_iCurrentFontIndex ) // found all of them? + if (iFontToFind == g_iCurrentFontIndex) // found all of them? { // now restart the font system... // R_ShutdownFonts(); R_InitFonts(); // - // and re-register our fonts in the same order as before (note that some menu items etc cache the string lengths so really a vid_restart is better, but this is just for my testing) + // and re-register our fonts in the same order as before (note that some menu items etc cache the string lengths so really a vid_restart is better, but + // this is just for my testing) // - for (size_t iFont = 0; iFont < vstrFonts.size(); iFont++) - { + for (size_t iFont = 0; iFont < vstrFonts.size(); iFont++) { #ifdef _DEBUG - int iNewFontHandle = RE_RegisterFont( vstrFonts[iFont].c_str() ); - assert( iNewFontHandle == (int)(iFont+1) ); + int iNewFontHandle = RE_RegisterFont(vstrFonts[iFont].c_str()); + assert(iNewFontHandle == (int)(iFont + 1)); #else - RE_RegisterFont( vstrFonts[iFont].c_str() ); + RE_RegisterFont(vstrFonts[iFont].c_str()); #endif } - Com_Printf( "Done.\n" ); - } - else - { - Com_Printf( "Problem encountered finding current fonts, ignoring.\n" ); // poo. Oh well, forget it. + Com_Printf("Done.\n"); + } else { + Com_Printf("Problem encountered finding current fonts, ignoring.\n"); // poo. Oh well, forget it. } } - // end diff --git a/codemp/rd-common/tr_image_jpg.cpp b/codemp/rd-common/tr_image_jpg.cpp index e94d0edc93..53cd3a6d03 100644 --- a/codemp/rd-common/tr_image_jpg.cpp +++ b/codemp/rd-common/tr_image_jpg.cpp @@ -34,11 +34,10 @@ along with this program; if not, see . #include -static void R_JPGErrorExit(j_common_ptr cinfo) -{ +static void R_JPGErrorExit(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; - (*cinfo->err->format_message) (cinfo, buffer); + (*cinfo->err->format_message)(cinfo, buffer); /* Let the memory manager delete any temp files before we die */ jpeg_destroy(cinfo); @@ -46,50 +45,49 @@ static void R_JPGErrorExit(j_common_ptr cinfo) Com_Printf("%s", buffer); } -static void R_JPGOutputMessage(j_common_ptr cinfo) -{ +static void R_JPGOutputMessage(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; /* Create the message */ - (*cinfo->err->format_message) (cinfo, buffer); + (*cinfo->err->format_message)(cinfo, buffer); /* Send it to stderr, adding a newline */ Com_Printf("%s\n", buffer); } -void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height ) { +void LoadJPG(const char *filename, unsigned char **pic, int *width, int *height) { /* This struct contains the JPEG decompression parameters and pointers to - * working space (which is allocated as needed by the JPEG library). - */ - struct jpeg_decompress_struct cinfo = { NULL }; + * working space (which is allocated as needed by the JPEG library). + */ + struct jpeg_decompress_struct cinfo = {NULL}; /* We use our private extension JPEG error handler. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ + * Note that this struct must live as long as the main JPEG parameter + * struct, to avoid dangling-pointer problems. + */ /* This struct represents a JPEG error handler. It is declared separately - * because applications often want to supply a specialized error handler - * (see the second half of this file for an example). But here we just - * take the easy way out and use the standard error handler, which will - * print a message on stderr and call exit() if compression fails. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ + * because applications often want to supply a specialized error handler + * (see the second half of this file for an example). But here we just + * take the easy way out and use the standard error handler, which will + * print a message on stderr and call exit() if compression fails. + * Note that this struct must live as long as the main JPEG parameter + * struct, to avoid dangling-pointer problems. + */ struct jpeg_error_mgr jerr; /* More stuff */ - JSAMPARRAY buffer; /* Output row buffer */ - unsigned int row_stride; /* physical row width in output buffer */ + JSAMPARRAY buffer; /* Output row buffer */ + unsigned int row_stride; /* physical row width in output buffer */ unsigned int pixelcount, memcount; unsigned int sindex, dindex; byte *out; fileBuffer_t fbuffer; - byte *buf; + byte *buf; /* In this example we want to open the input file before doing anything else, - * so that the setjmp() error recovery below can assume the file is open. - * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that - * requires it in order to read binary files. - */ + * so that the setjmp() error recovery below can assume the file is open. + * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that + * requires it in order to read binary files. + */ - int len = ri.FS_ReadFile ( ( char * ) filename, &fbuffer.v); + int len = ri.FS_ReadFile((char *)filename, &fbuffer.v); if (!fbuffer.b || len < 0) { return; } @@ -97,10 +95,10 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* Step 1: allocate and initialize JPEG decompression object */ /* We have to set up the error handler first, in case the initialization - * step fails. (Unlikely, but it could happen if you are out of memory.) - * This routine fills in the contents of struct jerr, and returns jerr's - * address which we place into the link field in cinfo. - */ + * step fails. (Unlikely, but it could happen if you are out of memory.) + * This routine fills in the contents of struct jerr, and returns jerr's + * address which we place into the link field in cinfo. + */ cinfo.err = jpeg_std_error(&jerr); cinfo.err->error_exit = R_JPGErrorExit; cinfo.err->output_message = R_JPGOutputMessage; @@ -114,47 +112,43 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* Step 3: read file parameters with jpeg_read_header() */ - (void) jpeg_read_header(&cinfo, TRUE); + (void)jpeg_read_header(&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since - * (a) suspension is not possible with the stdio data source, and - * (b) we passed TRUE to reject a tables-only JPEG file as an error. - * See libjpeg.doc for more info. - */ + * (a) suspension is not possible with the stdio data source, and + * (b) we passed TRUE to reject a tables-only JPEG file as an error. + * See libjpeg.doc for more info. + */ /* Step 4: set parameters for decompression */ - /* Make sure it always converts images to RGB color space. This will - * automatically convert 8-bit greyscale images to RGB as well. */ + * automatically convert 8-bit greyscale images to RGB as well. */ cinfo.out_color_space = JCS_RGB; /* Step 5: Start decompressor */ - (void) jpeg_start_decompress(&cinfo); + (void)jpeg_start_decompress(&cinfo); /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ + * with the stdio data source. + */ /* We may need to do some setup of our own at this point before reading - * the data. After jpeg_start_decompress() we have the correct scaled - * output image dimensions available, as well as the output colormap - * if we asked for color quantization. - * In this example, we need to make an output work buffer of the right size. - */ + * the data. After jpeg_start_decompress() we have the correct scaled + * output image dimensions available, as well as the output colormap + * if we asked for color quantization. + * In this example, we need to make an output work buffer of the right size. + */ /* JSAMPLEs per row in output buffer */ pixelcount = cinfo.output_width * cinfo.output_height; - if(!cinfo.output_width || !cinfo.output_height - || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height - || pixelcount > 0x1FFFFFFF || cinfo.output_components != 3 - ) - { + if (!cinfo.output_width || !cinfo.output_height || ((pixelcount * 4) / cinfo.output_width) / 4 != cinfo.output_height || pixelcount > 0x1FFFFFFF || + cinfo.output_components != 3) { // Free the memory to make sure we don't leak memory - ri.FS_FreeFile (fbuffer.v); + ri.FS_FreeFile(fbuffer.v); jpeg_destroy_decompress(&cinfo); - Com_Printf("LoadJPG: %s has an invalid image format: %dx%d*4=%d, components: %d", filename, - cinfo.output_width, cinfo.output_height, pixelcount * 4, cinfo.output_components); + Com_Printf("LoadJPG: %s has an invalid image format: %dx%d*4=%d, components: %d", filename, cinfo.output_width, cinfo.output_height, pixelcount * 4, + cinfo.output_components); return; } @@ -170,16 +164,16 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height /* jpeg_read_scanlines(...); */ /* Here we use the library's state variable cinfo.output_scanline as the - * loop counter, so that we don't have to keep track ourselves. - */ + * loop counter, so that we don't have to keep track ourselves. + */ while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. - * Here the array is only one element long, but you could ask for - * more than one scanline at a time if that's more convenient. - */ - buf = ((out+(row_stride*cinfo.output_scanline))); + * Here the array is only one element long, but you could ask for + * more than one scanline at a time if that's more convenient. + */ + buf = ((out + (row_stride * cinfo.output_scanline))); buffer = &buf; - (void) jpeg_read_scanlines(&cinfo, buffer, 1); + (void)jpeg_read_scanlines(&cinfo, buffer, 1); } buf = out; @@ -192,16 +186,16 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; buf[--dindex] = buf[--sindex]; - } while(sindex); + } while (sindex); *pic = out; /* Step 7: Finish decompression */ - (void) jpeg_finish_decompress(&cinfo); + (void)jpeg_finish_decompress(&cinfo); /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ + * with the stdio data source. + */ /* Step 8: Release JPEG decompression object */ @@ -209,71 +203,66 @@ void LoadJPG( const char *filename, unsigned char **pic, int *width, int *height jpeg_destroy_decompress(&cinfo); /* After finish_decompress, we can close the input file. - * Here we postpone it until after no more JPEG errors are possible, - * so as to simplify the setjmp error logic above. (Actually, I don't - * think that jpeg_destroy can do an error exit, but why assume anything...) - */ - ri.FS_FreeFile (fbuffer.v); + * Here we postpone it until after no more JPEG errors are possible, + * so as to simplify the setjmp error logic above. (Actually, I don't + * think that jpeg_destroy can do an error exit, but why assume anything...) + */ + ri.FS_FreeFile(fbuffer.v); /* At this point you may want to check to see whether any corrupt-data - * warnings occurred (test whether jerr.pub.num_warnings is nonzero). - */ + * warnings occurred (test whether jerr.pub.num_warnings is nonzero). + */ /* And we're done! */ } - /* Expanded data destination object for stdio output */ typedef struct my_destination_mgr_s { struct jpeg_destination_mgr pub; /* public fields */ - byte* outfile; /* target stream */ - int size; + byte *outfile; /* target stream */ + int size; } my_destination_mgr; -typedef my_destination_mgr * my_dest_ptr; - +typedef my_destination_mgr *my_dest_ptr; /* -* Initialize destination --- called by jpeg_start_compress -* before any data is actually written. -*/ + * Initialize destination --- called by jpeg_start_compress + * before any data is actually written. + */ -static void init_destination (j_compress_ptr cinfo) -{ - my_dest_ptr dest = (my_dest_ptr) cinfo->dest; +static void init_destination(j_compress_ptr cinfo) { + my_dest_ptr dest = (my_dest_ptr)cinfo->dest; dest->pub.next_output_byte = dest->outfile; dest->pub.free_in_buffer = dest->size; } - /* -* Empty the output buffer --- called whenever buffer fills up. -* -* In typical applications, this should write the entire output buffer -* (ignoring the current state of next_output_byte & free_in_buffer), -* reset the pointer & count to the start of the buffer, and return TRUE -* indicating that the buffer has been dumped. -* -* In applications that need to be able to suspend compression due to output -* overrun, a FALSE return indicates that the buffer cannot be emptied now. -* In this situation, the compressor will return to its caller (possibly with -* an indication that it has not accepted all the supplied scanlines). The -* application should resume compression after it has made more room in the -* output buffer. Note that there are substantial restrictions on the use of -* suspension --- see the documentation. -* -* When suspending, the compressor will back up to a convenient restart point -* (typically the start of the current MCU). next_output_byte & free_in_buffer -* indicate where the restart point will be if the current call returns FALSE. -* Data beyond this point will be regenerated after resumption, so do not -* write it out when emptying the buffer externally. -*/ + * Empty the output buffer --- called whenever buffer fills up. + * + * In typical applications, this should write the entire output buffer + * (ignoring the current state of next_output_byte & free_in_buffer), + * reset the pointer & count to the start of the buffer, and return TRUE + * indicating that the buffer has been dumped. + * + * In applications that need to be able to suspend compression due to output + * overrun, a FALSE return indicates that the buffer cannot be emptied now. + * In this situation, the compressor will return to its caller (possibly with + * an indication that it has not accepted all the supplied scanlines). The + * application should resume compression after it has made more room in the + * output buffer. Note that there are substantial restrictions on the use of + * suspension --- see the documentation. + * + * When suspending, the compressor will back up to a convenient restart point + * (typically the start of the current MCU). next_output_byte & free_in_buffer + * indicate where the restart point will be if the current call returns FALSE. + * Data beyond this point will be regenerated after resumption, so do not + * write it out when emptying the buffer externally. + */ -static boolean empty_output_buffer (j_compress_ptr cinfo) -{ - my_dest_ptr dest = (my_dest_ptr) cinfo->dest; +static boolean empty_output_buffer(j_compress_ptr cinfo) { + my_dest_ptr dest = (my_dest_ptr)cinfo->dest; jpeg_destroy_compress(cinfo); @@ -284,42 +273,36 @@ static boolean empty_output_buffer (j_compress_ptr cinfo) } /* -* Terminate destination --- called by jpeg_finish_compress -* after all data has been written. Usually needs to flush buffer. -* -* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding -* application must deal with any cleanup that should happen even -* for error exit. -*/ - -static void term_destination(j_compress_ptr cinfo) -{ -} + * Terminate destination --- called by jpeg_finish_compress + * after all data has been written. Usually needs to flush buffer. + * + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding + * application must deal with any cleanup that should happen even + * for error exit. + */ +static void term_destination(j_compress_ptr cinfo) {} /* -* Prepare for output to a stdio stream. -* The caller must have already opened the stream, and is responsible -* for closing it after finishing compression. -*/ + * Prepare for output to a stdio stream. + * The caller must have already opened the stream, and is responsible + * for closing it after finishing compression. + */ -static void jpegDest (j_compress_ptr cinfo, byte* outfile, int size) -{ +static void jpegDest(j_compress_ptr cinfo, byte *outfile, int size) { my_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images - * can be written to the same file without re-executing jpeg_stdio_dest. - * This makes it dangerous to use this manager and a different destination - * manager serially with the same JPEG object, because their private object - * sizes may be different. Caveat programmer. - */ - if (cinfo->dest == NULL) { /* first time for this JPEG object? */ - cinfo->dest = (struct jpeg_destination_mgr *) - (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, - sizeof(my_destination_mgr)); + * can be written to the same file without re-executing jpeg_stdio_dest. + * This makes it dangerous to use this manager and a different destination + * manager serially with the same JPEG object, because their private object + * sizes may be different. Caveat programmer. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr)); } - dest = (my_dest_ptr) cinfo->dest; + dest = (my_dest_ptr)cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; @@ -335,14 +318,12 @@ Encodes JPEG from image in image_buffer and writes to buffer. Expects RGB input data ================= */ -size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, - int image_width, int image_height, byte *image_buffer, int padding) -{ +size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, int image_width, int image_height, byte *image_buffer, int padding) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; - JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ + JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ my_dest_ptr dest; - int row_stride; /* physical row width in image buffer */ + int row_stride; /* physical row width in image buffer */ size_t outcount; /* Step 1: allocate and initialize JPEG compression object */ @@ -360,10 +341,10 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, jpegDest(&cinfo, buffer, bufSize); /* Step 3: set parameters for compression */ - cinfo.image_width = image_width; /* image width and height, in pixels */ + cinfo.image_width = image_width; /* image width and height, in pixels */ cinfo.image_height = image_height; cinfo.input_components = 3; /* # of color components per pixel */ - cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ + cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); @@ -384,17 +365,17 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, while (cinfo.next_scanline < cinfo.image_height) { /* jpeg_write_scanlines expects an array of pointers to scanlines. - * Here the array is only one element long, but you could pass - * more than one scanline at a time if that's more convenient. - */ - row_pointer[0] = &image_buffer[((cinfo.image_height-1)*row_stride)-cinfo.next_scanline * row_stride]; - (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); + * Here the array is only one element long, but you could pass + * more than one scanline at a time if that's more convenient. + */ + row_pointer[0] = &image_buffer[((cinfo.image_height - 1) * row_stride) - cinfo.next_scanline * row_stride]; + (void)jpeg_write_scanlines(&cinfo, row_pointer, 1); } /* Step 6: Finish compression */ jpeg_finish_compress(&cinfo); - dest = (my_dest_ptr) cinfo.dest; + dest = (my_dest_ptr)cinfo.dest; outcount = dest->size - dest->pub.free_in_buffer; /* Step 7: release JPEG compression object */ @@ -404,9 +385,7 @@ size_t RE_SaveJPGToBuffer(byte *buffer, size_t bufSize, int quality, return outcount; } - -void RE_SaveJPG(const char * filename, int quality, int image_width, int image_height, byte *image_buffer, int padding) -{ +void RE_SaveJPG(const char *filename, int quality, int image_width, int image_height, byte *image_buffer, int padding) { byte *out; size_t bufSize; @@ -418,4 +397,3 @@ void RE_SaveJPG(const char * filename, int quality, int image_width, int image_h Hunk_FreeTempMemory(out); } - diff --git a/codemp/rd-common/tr_image_load.cpp b/codemp/rd-common/tr_image_load.cpp index 05b205436a..965ce583bf 100644 --- a/codemp/rd-common/tr_image_load.cpp +++ b/codemp/rd-common/tr_image_load.cpp @@ -25,8 +25,7 @@ along with this program; if not, see . #include "tr_common.h" const int MAX_IMAGE_LOADERS = 10; -struct ImageLoaderMap -{ +struct ImageLoaderMap { const char *extension; ImageLoaderFn loader; } imageLoaders[MAX_IMAGE_LOADERS]; @@ -37,12 +36,9 @@ int numImageLoaders; Finds the image loader associated with the given extension. ================= */ -const ImageLoaderMap *FindImageLoader ( const char *extension ) -{ - for ( int i = 0; i < numImageLoaders; i++ ) - { - if ( Q_stricmp (extension, imageLoaders[i].extension) == 0 ) - { +const ImageLoaderMap *FindImageLoader(const char *extension) { + for (int i = 0; i < numImageLoaders; i++) { + if (Q_stricmp(extension, imageLoaders[i].extension) == 0) { return &imageLoaders[i]; } } @@ -56,17 +52,14 @@ Adds a new image loader to load the specified image file extension. The 'extension' string should not begin with a period (full stop). ================= */ -qboolean R_ImageLoader_Add ( const char *extension, ImageLoaderFn imageLoader ) -{ - if ( numImageLoaders >= MAX_IMAGE_LOADERS ) - { - ri.Printf (PRINT_DEVELOPER, "R_AddImageLoader: Cannot add any more image loaders (maximum %d).\n", MAX_IMAGE_LOADERS); +qboolean R_ImageLoader_Add(const char *extension, ImageLoaderFn imageLoader) { + if (numImageLoaders >= MAX_IMAGE_LOADERS) { + ri.Printf(PRINT_DEVELOPER, "R_AddImageLoader: Cannot add any more image loaders (maximum %d).\n", MAX_IMAGE_LOADERS); return qfalse; } - if ( FindImageLoader (extension) != NULL ) - { - ri.Printf (PRINT_DEVELOPER, "R_AddImageLoader: Image loader already exists for extension \"%s\".\n", extension); + if (FindImageLoader(extension) != NULL) { + ri.Printf(PRINT_DEVELOPER, "R_AddImageLoader: Image loader already exists for extension \"%s\".\n", extension); return qfalse; } @@ -85,14 +78,13 @@ Initializes the image loader, and adds the built-in image loaders ================= */ -void R_ImageLoader_Init() -{ - Com_Memset (imageLoaders, 0, sizeof (imageLoaders)); +void R_ImageLoader_Init() { + Com_Memset(imageLoaders, 0, sizeof(imageLoaders)); numImageLoaders = 0; - R_ImageLoader_Add ("jpg", LoadJPG); - R_ImageLoader_Add ("png", LoadPNG); - R_ImageLoader_Add ("tga", LoadTGA); + R_ImageLoader_Add("jpg", LoadJPG); + R_ImageLoader_Add("png", LoadPNG); + R_ImageLoader_Add("tga", LoadTGA); } /* @@ -101,39 +93,34 @@ Loads any of the supported image types into a cannonical 32 bit format. ================= */ -void R_LoadImage( const char *shortname, byte **pic, int *width, int *height ) { +void R_LoadImage(const char *shortname, byte **pic, int *width, int *height) { *pic = NULL; *width = 0; *height = 0; // Try loading the image with the original extension (if possible). - const char *extension = COM_GetExtension (shortname); - const ImageLoaderMap *imageLoader = FindImageLoader (extension); - if ( imageLoader != NULL ) - { - imageLoader->loader (shortname, pic, width, height); - if ( *pic ) - { + const char *extension = COM_GetExtension(shortname); + const ImageLoaderMap *imageLoader = FindImageLoader(extension); + if (imageLoader != NULL) { + imageLoader->loader(shortname, pic, width, height); + if (*pic) { return; } } // Loop through all the image loaders trying to load this image. char extensionlessName[MAX_QPATH]; - COM_StripExtension(shortname, extensionlessName, sizeof( extensionlessName )); - for ( int i = 0; i < numImageLoaders; i++ ) - { + COM_StripExtension(shortname, extensionlessName, sizeof(extensionlessName)); + for (int i = 0; i < numImageLoaders; i++) { const ImageLoaderMap *tryLoader = &imageLoaders[i]; - if ( tryLoader == imageLoader ) - { + if (tryLoader == imageLoader) { // Already tried this one. continue; } - const char *name = va ("%s.%s", extensionlessName, tryLoader->extension); - tryLoader->loader (name, pic, width, height); - if ( *pic ) - { + const char *name = va("%s.%s", extensionlessName, tryLoader->extension); + tryLoader->loader(name, pic, width, height); + if (*pic) { return; } } diff --git a/codemp/rd-common/tr_image_png.cpp b/codemp/rd-common/tr_image_png.cpp index 0bb6ecf89d..7cb1004902 100644 --- a/codemp/rd-common/tr_image_png.cpp +++ b/codemp/rd-common/tr_image_png.cpp @@ -25,20 +25,20 @@ along with this program; if not, see . #include "tr_common.h" #include -void user_write_data( png_structp png_ptr, png_bytep data, png_size_t length ) { - fileHandle_t fp = *(fileHandle_t*)png_get_io_ptr( png_ptr ); - ri.FS_Write( data, length, fp ); +void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { + fileHandle_t fp = *(fileHandle_t *)png_get_io_ptr(png_ptr); + ri.FS_Write(data, length, fp); } -void user_flush_data( png_structp png_ptr ) { - //TODO: ri.FS_Flush? +void user_flush_data(png_structp png_ptr) { + // TODO: ri.FS_Flush? } -int RE_SavePNG( const char *filename, byte *buf, size_t width, size_t height, int byteDepth ) { +int RE_SavePNG(const char *filename, byte *buf, size_t width, size_t height, int byteDepth) { fileHandle_t fp; png_structp png_ptr = NULL; png_infop info_ptr = NULL; unsigned int x, y; - png_byte ** row_pointers = NULL; + png_byte **row_pointers = NULL; /* "status" contains the return value of this function. At first it is set to a value which means 'failure'. When the routine has finished its work, it is set to a value which means @@ -49,47 +49,39 @@ int RE_SavePNG( const char *filename, byte *buf, size_t width, size_t height, in */ int depth = 8; - fp = ri.FS_FOpenFileWrite( filename, qtrue ); - if ( !fp ) { + fp = ri.FS_FOpenFileWrite(filename, qtrue); + if (!fp) { goto fopen_failed; } - png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { goto png_create_write_struct_failed; } - info_ptr = png_create_info_struct (png_ptr); + info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { goto png_create_info_struct_failed; } /* Set up error handling. */ - if (setjmp (png_jmpbuf (png_ptr))) { + if (setjmp(png_jmpbuf(png_ptr))) { goto png_failure; } /* Set image attributes. */ - png_set_IHDR (png_ptr, - info_ptr, - width, - height, - depth, - PNG_COLOR_TYPE_RGB, - PNG_INTERLACE_NONE, - PNG_COMPRESSION_TYPE_DEFAULT, - PNG_FILTER_TYPE_DEFAULT); + png_set_IHDR(png_ptr, info_ptr, width, height, depth, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); /* Initialize rows of PNG. */ - row_pointers = (png_byte **)png_malloc (png_ptr, height * sizeof (png_byte *)); - for ( y=0; y RGBA - png_set_add_alpha (png_ptr, 0xff, PNG_FILLER_AFTER); + png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); } - png_read_update_info (png_ptr, info_ptr); + png_read_update_info(png_ptr, info_ptr); // We always assume there are 4 channels. RGB channels are expanded to RGBA when read. - byte *tempData = (byte *)ri.Z_Malloc (width_ * height_ * 4, TAG_TEMP_PNG, qfalse, 4); - if ( !tempData ) - { - ri.Printf (PRINT_ERROR, "Could not allocate enough memory to load the image."); + byte *tempData = (byte *)ri.Z_Malloc(width_ * height_ * 4, TAG_TEMP_PNG, qfalse, 4); + if (!tempData) { + ri.Printf(PRINT_ERROR, "Could not allocate enough memory to load the image."); return 0; } // Dynamic array of row pointers, with 'height' elements, initialized to NULL. - byte **row_pointers = (byte **)ri.Hunk_AllocateTempMemory (sizeof (byte *) * height_); - if ( !row_pointers ) - { - ri.Printf (PRINT_ERROR, "Could not allocate enough memory to load the image."); + byte **row_pointers = (byte **)ri.Hunk_AllocateTempMemory(sizeof(byte *) * height_); + if (!row_pointers) { + ri.Printf(PRINT_ERROR, "Could not allocate enough memory to load the image."); - ri.Z_Free (tempData); + ri.Z_Free(tempData); return 0; } // Re-set the jmp so that these new memory allocations can be reclaimed - if ( setjmp (png_jmpbuf (png_ptr)) ) - { - ri.Hunk_FreeTempMemory (row_pointers); - ri.Z_Free (tempData); + if (setjmp(png_jmpbuf(png_ptr))) { + ri.Hunk_FreeTempMemory(row_pointers); + ri.Z_Free(tempData); return 0; } - for ( unsigned int i = 0, j = 0; i < height_; i++, j += 4 ) - { + for (unsigned int i = 0, j = 0; i < height_; i++, j += 4) { row_pointers[i] = tempData + j * width_; } - png_read_image (png_ptr, row_pointers); + png_read_image(png_ptr, row_pointers); // Finish reading - png_read_end (png_ptr, NULL); + png_read_end(png_ptr, NULL); - ri.Hunk_FreeTempMemory (row_pointers); + ri.Hunk_FreeTempMemory(row_pointers); // Finally assign all the parameters *data = tempData; @@ -269,36 +242,32 @@ struct PNGFileReader return 1; } - void ReadBytes ( void *dest, size_t len ) - { - memcpy (dest, buf + offset, len); + void ReadBytes(void *dest, size_t len) { + memcpy(dest, buf + offset, len); offset += len; } -private: + private: char *buf; size_t offset; png_structp png_ptr; png_infop info_ptr; }; -void user_read_data( png_structp png_ptr, png_bytep data, png_size_t length ) { - png_voidp r = png_get_io_ptr (png_ptr); +void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { + png_voidp r = png_get_io_ptr(png_ptr); PNGFileReader *reader = (PNGFileReader *)r; - reader->ReadBytes (data, length); + reader->ReadBytes(data, length); } // Loads a PNG image from file. -void LoadPNG ( const char *filename, byte **data, int *width, int *height ) -{ +void LoadPNG(const char *filename, byte **data, int *width, int *height) { char *buf = NULL; - int len = ri.FS_ReadFile (filename, (void **)&buf); - if ( len < 0 || buf == NULL ) - { + int len = ri.FS_ReadFile(filename, (void **)&buf); + if (len < 0 || buf == NULL) { return; } - PNGFileReader reader (buf); - reader.Read (data, width, height); + PNGFileReader reader(buf); + reader.Read(data, width, height); } - diff --git a/codemp/rd-common/tr_image_tga.cpp b/codemp/rd-common/tr_image_tga.cpp index 58dbb7fc05..19e461f5fe 100644 --- a/codemp/rd-common/tr_image_tga.cpp +++ b/codemp/rd-common/tr_image_tga.cpp @@ -27,114 +27,102 @@ along with this program; if not, see . // My TGA loader... // //--------------------------------------------------- -#pragma pack(push,1) +#pragma pack(push, 1) typedef struct TGAHeader_s { - byte byIDFieldLength; // must be 0 - byte byColourmapType; // 0 = truecolour, 1 = paletted, else bad - byte byImageType; // 1 = colour mapped (palette), uncompressed, 2 = truecolour, uncompressed, else bad - word w1stColourMapEntry; // must be 0 - word wColourMapLength; // 256 for 8-bit palettes, else 0 for true-colour - byte byColourMapEntrySize; // 24 for 8-bit palettes, else 0 for true-colour - word wImageXOrigin; // ignored - word wImageYOrigin; // ignored - word wImageWidth; // in pixels - word wImageHeight; // in pixels - byte byImagePlanes; // bits per pixel (8 for paletted, else 24 for true-colour) - byte byScanLineOrder; // Image descriptor bytes - // bits 0-3 = # attr bits (alpha chan) - // bits 4-5 = pixel order/dir - // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) + byte byIDFieldLength; // must be 0 + byte byColourmapType; // 0 = truecolour, 1 = paletted, else bad + byte byImageType; // 1 = colour mapped (palette), uncompressed, 2 = truecolour, uncompressed, else bad + word w1stColourMapEntry; // must be 0 + word wColourMapLength; // 256 for 8-bit palettes, else 0 for true-colour + byte byColourMapEntrySize; // 24 for 8-bit palettes, else 0 for true-colour + word wImageXOrigin; // ignored + word wImageYOrigin; // ignored + word wImageWidth; // in pixels + word wImageHeight; // in pixels + byte byImagePlanes; // bits per pixel (8 for paletted, else 24 for true-colour) + byte byScanLineOrder; // Image descriptor bytes + // bits 0-3 = # attr bits (alpha chan) + // bits 4-5 = pixel order/dir + // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) } TGAHeader_t; #pragma pack(pop) - // *pic == pic, else NULL for failed. // // returns false if found but had a format error, else true for either OK or not-found (there's a reason for this) // -void LoadTGA ( const char *name, byte **pic, int *width, int *height) -{ +void LoadTGA(const char *name, byte **pic, int *width, int *height) { char sErrorString[1024]; bool bFormatErrors = false; // these don't need to be declared or initialised until later, but the compiler whines that 'goto' skips them. // byte *pRGBA = NULL; - byte *pOut = NULL; - byte *pIn = NULL; - + byte *pOut = NULL; + byte *pIn = NULL; *pic = NULL; -#define TGA_FORMAT_ERROR(blah) {sprintf(sErrorString,blah); bFormatErrors = true; goto TGADone;} -//#define TGA_FORMAT_ERROR(blah) Com_Error( ERR_DROP, blah ); +#define TGA_FORMAT_ERROR(blah) \ + { \ + sprintf(sErrorString, blah); \ + bFormatErrors = true; \ + goto TGADone; \ + } + //#define TGA_FORMAT_ERROR(blah) Com_Error( ERR_DROP, blah ); // // load the file // byte *pTempLoadedBuffer = 0; - ri.FS_ReadFile ( ( char * ) name, (void **)&pTempLoadedBuffer); + ri.FS_ReadFile((char *)name, (void **)&pTempLoadedBuffer); if (!pTempLoadedBuffer) { return; } - TGAHeader_t *pHeader = (TGAHeader_t *) pTempLoadedBuffer; + TGAHeader_t *pHeader = (TGAHeader_t *)pTempLoadedBuffer; pHeader->wColourMapLength = LittleShort(pHeader->wColourMapLength); pHeader->wImageWidth = LittleShort(pHeader->wImageWidth); pHeader->wImageHeight = LittleShort(pHeader->wImageHeight); - if (pHeader->byColourmapType!=0) - { - TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n" ); + if (pHeader->byColourmapType != 0) { + TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n"); } - if (pHeader->byImageType != 2 && pHeader->byImageType != 3 && pHeader->byImageType != 10) - { + if (pHeader->byImageType != 2 && pHeader->byImageType != 3 && pHeader->byImageType != 10) { TGA_FORMAT_ERROR("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RLE-RGB) images supported\n"); } - if (pHeader->w1stColourMapEntry != 0) - { - TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n" ); + if (pHeader->w1stColourMapEntry != 0) { + TGA_FORMAT_ERROR("LoadTGA: colourmaps not supported\n"); } - if (pHeader->wColourMapLength !=0 && pHeader->wColourMapLength != 256) - { - TGA_FORMAT_ERROR("LoadTGA: ColourMapLength must be either 0 or 256\n" ); + if (pHeader->wColourMapLength != 0 && pHeader->wColourMapLength != 256) { + TGA_FORMAT_ERROR("LoadTGA: ColourMapLength must be either 0 or 256\n"); } - if (pHeader->byColourMapEntrySize != 0 && pHeader->byColourMapEntrySize != 24) - { - TGA_FORMAT_ERROR("LoadTGA: ColourMapEntrySize must be either 0 or 24\n" ); + if (pHeader->byColourMapEntrySize != 0 && pHeader->byColourMapEntrySize != 24) { + TGA_FORMAT_ERROR("LoadTGA: ColourMapEntrySize must be either 0 or 24\n"); } - if ( ( pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) && (pHeader->byImagePlanes != 8 && pHeader->byImageType != 3)) - { + if ((pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) && (pHeader->byImagePlanes != 8 && pHeader->byImageType != 3)) { TGA_FORMAT_ERROR("LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n"); } - if ((pHeader->byScanLineOrder&0x30)!=0x00 && - (pHeader->byScanLineOrder&0x30)!=0x10 && - (pHeader->byScanLineOrder&0x30)!=0x20 && - (pHeader->byScanLineOrder&0x30)!=0x30 - ) - { + if ((pHeader->byScanLineOrder & 0x30) != 0x00 && (pHeader->byScanLineOrder & 0x30) != 0x10 && (pHeader->byScanLineOrder & 0x30) != 0x20 && + (pHeader->byScanLineOrder & 0x30) != 0x30) { TGA_FORMAT_ERROR("LoadTGA: ScanLineOrder must be either 0x00,0x10,0x20, or 0x30\n"); } - - // these last checks are so i can use ID's RLE-code. I don't dare fiddle with it or it'll probably break... // - if ( pHeader->byImageType == 10) - { - if ((pHeader->byScanLineOrder & 0x30) != 0x00) - { + if (pHeader->byImageType == 10) { + if ((pHeader->byScanLineOrder & 0x30) != 0x00) { TGA_FORMAT_ERROR("LoadTGA: RLE-RGB Images (type 10) must be in bottom-to-top format\n"); } - if (pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) // probably won't happen, but avoids compressed greyscales? + if (pHeader->byImagePlanes != 24 && pHeader->byImagePlanes != 32) // probably won't happen, but avoids compressed greyscales? { TGA_FORMAT_ERROR("LoadTGA: RLE-RGB Images (type 10) must be 24 or 32 bit\n"); } @@ -147,50 +135,49 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) // bits 4-5 = pixel order/dir // bits 6-7 scan line interleave (00b=none,01b=2way interleave,10b=4way) // - int iYStart,iXStart,iYStep,iXStep; + int iYStart, iXStart, iYStep, iXStep; - switch(pHeader->byScanLineOrder & 0x30) - { - default: // default case stops the compiler complaining about using uninitialised vars - case 0x00: // left to right, bottom to top + switch (pHeader->byScanLineOrder & 0x30) { + default: // default case stops the compiler complaining about using uninitialised vars + case 0x00: // left to right, bottom to top - iXStart = 0; - iXStep = 1; + iXStart = 0; + iXStep = 1; - iYStart = pHeader->wImageHeight-1; - iYStep = -1; + iYStart = pHeader->wImageHeight - 1; + iYStep = -1; - break; + break; - case 0x10: // right to left, bottom to top + case 0x10: // right to left, bottom to top - iXStart = pHeader->wImageWidth-1; - iXStep = -1; + iXStart = pHeader->wImageWidth - 1; + iXStep = -1; - iYStart = pHeader->wImageHeight-1; - iYStep = -1; + iYStart = pHeader->wImageHeight - 1; + iYStep = -1; - break; + break; - case 0x20: // left to right, top to bottom + case 0x20: // left to right, top to bottom - iXStart = 0; - iXStep = 1; + iXStart = 0; + iXStep = 1; - iYStart = 0; - iYStep = 1; + iYStart = 0; + iYStep = 1; - break; + break; - case 0x30: // right to left, top to bottom + case 0x30: // right to left, top to bottom - iXStart = pHeader->wImageWidth-1; - iXStep = -1; + iXStart = pHeader->wImageWidth - 1; + iXStep = -1; - iYStart = 0; - iYStep = 1; + iYStart = 0; + iYStep = 1; - break; + break; } // feed back the results... @@ -200,116 +187,107 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) if (height) *height = pHeader->wImageHeight; - pRGBA = (byte *) Z_Malloc (pHeader->wImageWidth * pHeader->wImageHeight * 4, TAG_TEMP_WORKSPACE, qfalse); - *pic = pRGBA; - pOut = pRGBA; - pIn = pTempLoadedBuffer + sizeof(*pHeader); + pRGBA = (byte *)Z_Malloc(pHeader->wImageWidth * pHeader->wImageHeight * 4, TAG_TEMP_WORKSPACE, qfalse); + *pic = pRGBA; + pOut = pRGBA; + pIn = pTempLoadedBuffer + sizeof(*pHeader); // I don't know if this ID-thing here is right, since comments that I've seen are at the end of the file, // with a zero in this field. However, may as well... // if (pHeader->byIDFieldLength != 0) - pIn += pHeader->byIDFieldLength; // skip TARGA image comment + pIn += pHeader->byIDFieldLength; // skip TARGA image comment - byte red,green,blue,alpha; + byte red, green, blue, alpha; - if ( pHeader->byImageType == 2 || pHeader->byImageType == 3 ) // RGB or greyscale + if (pHeader->byImageType == 2 || pHeader->byImageType == 3) // RGB or greyscale { - for (int y=iYStart, iYCount=0; iYCountwImageHeight; y+=iYStep, iYCount++) - { - pOut = pRGBA + y * pHeader->wImageWidth *4; - for (int x=iXStart, iXCount=0; iXCountwImageWidth; x+=iXStep, iXCount++) - { - switch (pHeader->byImagePlanes) - { - case 8: - blue = *pIn++; - green = blue; - red = blue; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 24: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = alpha; - break; - - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: Image can only have 8, 24 or 32 planes for RGB/greyscale\n"); - break; + for (int y = iYStart, iYCount = 0; iYCount < pHeader->wImageHeight; y += iYStep, iYCount++) { + pOut = pRGBA + y * pHeader->wImageWidth * 4; + for (int x = iXStart, iXCount = 0; iXCount < pHeader->wImageWidth; x += iXStep, iXCount++) { + switch (pHeader->byImagePlanes) { + case 8: + blue = *pIn++; + green = blue; + red = blue; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 24: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 32: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = alpha; + break; + + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: Image can only have 8, 24 or 32 planes for RGB/greyscale\n"); + break; } } } - } - else - if (pHeader->byImageType == 10) // RLE-RGB + } else if (pHeader->byImageType == 10) // RLE-RGB { // I've no idea if this stuff works, I normally reject RLE targas, but this is from ID's code // so maybe I should try and support it... // byte packetHeader, packetSize, j; - for (int y = pHeader->wImageHeight-1; y >= 0; y--) - { - pOut = pRGBA + y * pHeader->wImageWidth *4; - for (int x=0; xwImageWidth;) - { + for (int y = pHeader->wImageHeight - 1; y >= 0; y--) { + pOut = pRGBA + y * pHeader->wImageWidth * 4; + for (int x = 0; x < pHeader->wImageWidth;) { packetHeader = *pIn++; - packetSize = 1 + (packetHeader & 0x7f); - if (packetHeader & 0x80) // run-length packet + packetSize = 1 + (packetHeader & 0x7f); + if (packetHeader & 0x80) // run-length packet { - switch (pHeader->byImagePlanes) - { - case 24: + switch (pHeader->byImagePlanes) { + case 24: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = 255; - break; + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = 255; + break; - case 32: + case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - break; + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + break; - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); - break; + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); + break; } - for (j=0; jwImageWidth) // run spans across rows + if (x == pHeader->wImageWidth) // run spans across rows { x = 0; if (y > 0) @@ -319,43 +297,39 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) pOut = pRGBA + y * pHeader->wImageWidth * 4; } } - } - else - { // non run-length packet + } else { // non run-length packet - for (j=0; jbyImagePlanes) - { - case 24: - - blue = *pIn++; - green = *pIn++; - red = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = 255; - break; - - case 32: - blue = *pIn++; - green = *pIn++; - red = *pIn++; - alpha = *pIn++; - *pOut++ = red; - *pOut++ = green; - *pOut++ = blue; - *pOut++ = alpha; - break; - - default: - assert(0); // if we ever hit this, someone deleted a header check higher up - TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); - break; + for (j = 0; j < packetSize; j++) { + switch (pHeader->byImagePlanes) { + case 24: + + blue = *pIn++; + green = *pIn++; + red = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = 255; + break; + + case 32: + blue = *pIn++; + green = *pIn++; + red = *pIn++; + alpha = *pIn++; + *pOut++ = red; + *pOut++ = green; + *pOut++ = blue; + *pOut++ = alpha; + break; + + default: + assert(0); // if we ever hit this, someone deleted a header check higher up + TGA_FORMAT_ERROR("LoadTGA: RLE-RGB can only have 24 or 32 planes\n"); + break; } x++; - if (x == pHeader->wImageWidth) // pixel packet run spans across rows + if (x == pHeader->wImageWidth) // pixel packet run spans across rows { x = 0; if (y > 0) @@ -373,11 +347,9 @@ void LoadTGA ( const char *name, byte **pic, int *width, int *height) TGADone: - ri.FS_FreeFile (pTempLoadedBuffer); + ri.FS_FreeFile(pTempLoadedBuffer); - if (bFormatErrors) - { - Com_Error( ERR_DROP, "%s( File: \"%s\" )\n",sErrorString,name); + if (bFormatErrors) { + Com_Error(ERR_DROP, "%s( File: \"%s\" )\n", sErrorString, name); } } - diff --git a/codemp/rd-common/tr_noise.cpp b/codemp/rd-common/tr_noise.cpp index 8ec0b428a4..cad56cc655 100644 --- a/codemp/rd-common/tr_noise.cpp +++ b/codemp/rd-common/tr_noise.cpp @@ -26,45 +26,40 @@ along with this program; if not, see . #include "tr_common.h" #define NOISE_SIZE 256 -#define NOISE_MASK ( NOISE_SIZE - 1 ) +#define NOISE_MASK (NOISE_SIZE - 1) -#define VAL( a ) s_noise_perm[ ( a ) & ( NOISE_MASK )] -#define INDEX( x, y, z, t ) VAL( x + VAL( y + VAL( z + VAL( t ) ) ) ) +#define VAL(a) s_noise_perm[(a) & (NOISE_MASK)] +#define INDEX(x, y, z, t) VAL(x + VAL(y + VAL(z + VAL(t)))) static float s_noise_table[NOISE_SIZE]; static int s_noise_perm[NOISE_SIZE]; -#define LERP( a, b, w ) ( a * ( 1.0f - w ) + b * w ) +#define LERP(a, b, w) (a * (1.0f - w) + b * w) -static float GetNoiseValue( int x, int y, int z, int t ) -{ - int index = INDEX( ( int ) x, ( int ) y, ( int ) z, ( int ) t ); +static float GetNoiseValue(int x, int y, int z, int t) { + int index = INDEX((int)x, (int)y, (int)z, (int)t); return s_noise_table[index]; } -float GetNoiseTime( int t ) -{ - int index = VAL( t ); +float GetNoiseTime(int t) { + int index = VAL(t); return (1 + s_noise_table[index]); } -void R_NoiseInit( void ) -{ +void R_NoiseInit(void) { int i; - srand( 1001 ); + srand(1001); - for ( i = 0; i < NOISE_SIZE; i++ ) - { - s_noise_table[i] = ( float ) ( ( ( rand() / ( float ) RAND_MAX ) * 2.0 - 1.0 ) ); - s_noise_perm[i] = ( unsigned char ) ( rand() / ( float ) RAND_MAX * 255 ); + for (i = 0; i < NOISE_SIZE; i++) { + s_noise_table[i] = (float)(((rand() / (float)RAND_MAX) * 2.0 - 1.0)); + s_noise_perm[i] = (unsigned char)(rand() / (float)RAND_MAX * 255); } } -float R_NoiseGet4f( float x, float y, float z, float t ) -{ +float R_NoiseGet4f(float x, float y, float z, float t) { int i; int ix, iy, iz, it; float fx, fy, fz, ft; @@ -72,34 +67,33 @@ float R_NoiseGet4f( float x, float y, float z, float t ) float back[4]; float fvalue, bvalue, value[2], finalvalue; - ix = ( int ) floor( x ); + ix = (int)floor(x); fx = x - ix; - iy = ( int ) floor( y ); + iy = (int)floor(y); fy = y - iy; - iz = ( int ) floor( z ); + iz = (int)floor(z); fz = z - iz; - it = ( int ) floor( t ); + it = (int)floor(t); ft = t - it; - for ( i = 0; i < 2; i++ ) - { - front[0] = GetNoiseValue( ix, iy, iz, it + i ); - front[1] = GetNoiseValue( ix+1, iy, iz, it + i ); - front[2] = GetNoiseValue( ix, iy+1, iz, it + i ); - front[3] = GetNoiseValue( ix+1, iy+1, iz, it + i ); + for (i = 0; i < 2; i++) { + front[0] = GetNoiseValue(ix, iy, iz, it + i); + front[1] = GetNoiseValue(ix + 1, iy, iz, it + i); + front[2] = GetNoiseValue(ix, iy + 1, iz, it + i); + front[3] = GetNoiseValue(ix + 1, iy + 1, iz, it + i); - back[0] = GetNoiseValue( ix, iy, iz + 1, it + i ); - back[1] = GetNoiseValue( ix+1, iy, iz + 1, it + i ); - back[2] = GetNoiseValue( ix, iy+1, iz + 1, it + i ); - back[3] = GetNoiseValue( ix+1, iy+1, iz + 1, it + i ); + back[0] = GetNoiseValue(ix, iy, iz + 1, it + i); + back[1] = GetNoiseValue(ix + 1, iy, iz + 1, it + i); + back[2] = GetNoiseValue(ix, iy + 1, iz + 1, it + i); + back[3] = GetNoiseValue(ix + 1, iy + 1, iz + 1, it + i); - fvalue = LERP( LERP( front[0], front[1], fx ), LERP( front[2], front[3], fx ), fy ); - bvalue = LERP( LERP( back[0], back[1], fx ), LERP( back[2], back[3], fx ), fy ); + fvalue = LERP(LERP(front[0], front[1], fx), LERP(front[2], front[3], fx), fy); + bvalue = LERP(LERP(back[0], back[1], fx), LERP(back[2], back[3], fx), fy); - value[i] = LERP( fvalue, bvalue, fz ); + value[i] = LERP(fvalue, bvalue, fz); } - finalvalue = LERP( value[0], value[1], ft ); + finalvalue = LERP(value[0], value[1], ft); return finalvalue; } diff --git a/codemp/rd-dedicated/G2_API.cpp b/codemp/rd-dedicated/G2_API.cpp index 2555cf05f3..f8864ead8c 100644 --- a/codemp/rd-dedicated/G2_API.cpp +++ b/codemp/rd-dedicated/G2_API.cpp @@ -36,68 +36,55 @@ int g_G2ServerAlloc = 0; int g_G2ClientAlloc = 0; int g_G2AllocServer = 0; -//stupid debug crap to track leaks in case they happen. -//we used to shove everything into a map and delete it all and not care about -//leaks, but that was not the Right Thing. -rww -#define MAX_TRACKED_ALLOC 4096 -static bool g_G2AllocTrackInit = false; //want to keep this thing contained +// stupid debug crap to track leaks in case they happen. +// we used to shove everything into a map and delete it all and not care about +// leaks, but that was not the Right Thing. -rww +#define MAX_TRACKED_ALLOC 4096 +static bool g_G2AllocTrackInit = false; // want to keep this thing contained static CGhoul2Info_v *g_G2AllocTrack[MAX_TRACKED_ALLOC]; -void G2_DEBUG_InitPtrTracker(void) -{ +void G2_DEBUG_InitPtrTracker(void) { memset(g_G2AllocTrack, 0, sizeof(g_G2AllocTrack)); g_G2AllocTrackInit = true; } -void G2_DEBUG_ReportLeaks(void) -{ +void G2_DEBUG_ReportLeaks(void) { int i = 0; - if (!g_G2AllocTrackInit) - { - ri.Printf( PRINT_ALL, "g2 leak tracker was never initialized!\n"); + if (!g_G2AllocTrackInit) { + ri.Printf(PRINT_ALL, "g2 leak tracker was never initialized!\n"); return; } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i]) - { - ri.Printf( PRINT_ALL, "Bad guy found in slot %i, attempting to access...", i); + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i]) { + ri.Printf(PRINT_ALL, "Bad guy found in slot %i, attempting to access...", i); CGhoul2Info_v &g2v = *g_G2AllocTrack[i]; CGhoul2Info &g2 = g2v[0]; - if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) - { - ri.Printf( PRINT_ALL, "Bad guy's filename is %s\n", g2.mFileName); - } - else - { - ri.Printf( PRINT_ALL, "He's not valid! BURN HIM!\n"); + if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) { + ri.Printf(PRINT_ALL, "Bad guy's filename is %s\n", g2.mFileName); + } else { + ri.Printf(PRINT_ALL, "He's not valid! BURN HIM!\n"); } } i++; } } -void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (!g_G2AllocTrack[i]) - { + while (i < MAX_TRACKED_ALLOC) { + if (!g_G2AllocTrack[i]) { g_G2AllocTrack[i] = g2; return; } @@ -106,29 +93,22 @@ void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { - ri.Printf( PRINT_ALL, "%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { - ri.Printf( PRINT_ALL, "Crap g2 instance passed to instance tracker (in).\n"); + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { + ri.Printf(PRINT_ALL, "%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); + } else { + ri.Printf(PRINT_ALL, "Crap g2 instance passed to instance tracker (in).\n"); } } -void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i] == g2) - { + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i] == g2) { g_G2AllocTrack[i] = NULL; return; } @@ -137,13 +117,10 @@ void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { - ri.Printf( PRINT_ALL, "%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { - ri.Printf( PRINT_ALL, "Crap g2 instance passed to instance tracker (out).\n"); + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { + ri.Printf(PRINT_ALL, "%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); + } else { + ri.Printf(PRINT_ALL, "Crap g2 instance passed to instance tracker (out).\n"); } } #endif @@ -152,76 +129,66 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo); -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #define NUM_G2T_TIME (2) static int G2TimeBases[NUM_G2T_TIME]; -void G2API_SetTime(int currentTime,int clock) -{ - assert(clock>=0&&clock= 0 && clock < NUM_G2T_TIME); #if G2_DEBUG_TIME - ri.Printf( PRINT_ALL, "Set Time: before c%6d s%6d",G2TimeBases[1],G2TimeBases[0]); + ri.Printf(PRINT_ALL, "Set Time: before c%6d s%6d", G2TimeBases[1], G2TimeBases[0]); #endif - G2TimeBases[clock]=currentTime; - if (G2TimeBases[1]>G2TimeBases[0]+200) - { - G2TimeBases[1]=0; // use server time instead + G2TimeBases[clock] = currentTime; + if (G2TimeBases[1] > G2TimeBases[0] + 200) { + G2TimeBases[1] = 0; // use server time instead return; } #if G2_DEBUG_TIME - ri.Printf( PRINT_ALL, " after c%6d s%6d\n",G2TimeBases[1],G2TimeBases[0]); + ri.Printf(PRINT_ALL, " after c%6d s%6d\n", G2TimeBases[1], G2TimeBases[0]); #endif } -int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar +int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar { - int ret=G2TimeBases[1]; - if ( !ret ) - { + int ret = G2TimeBases[1]; + if (!ret) { ret = G2TimeBases[0]; } return ret; } -//rww - RAGDOLL_END +// rww - RAGDOLL_END -//rww - Stuff to allow association of ghoul2 instances to entity numbers. -//This way, on listen servers when both the client and server are doing -//ghoul2 operations, we can copy relevant data off the client instance -//directly onto the server instance and slash the transforms and whatnot -//right in half. +// rww - Stuff to allow association of ghoul2 instances to entity numbers. +// This way, on listen servers when both the client and server are doing +// ghoul2 operations, we can copy relevant data off the client instance +// directly onto the server instance and slash the transforms and whatnot +// right in half. #ifdef _G2_LISTEN_SERVER_OPT CGhoul2Info_v *g2ClientAttachments[MAX_GENTITIES]; #endif -void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) -{ //Assign the pointers in the arrays +void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) { // Assign the pointers in the arrays #ifdef _G2_LISTEN_SERVER_OPT - if (server) - { + if (server) { ghoul2[0].entityNum = entityNum; - } - else - { + } else { g2ClientAttachments[entityNum] = &ghoul2; } #endif } -void G2API_ClearAttachedInstance(int entityNum) -{ +void G2API_ClearAttachedInstance(int entityNum) { #ifdef _G2_LISTEN_SERVER_OPT g2ClientAttachments[entityNum] = NULL; #endif } -void G2API_CleanEntAttachments(void) -{ +void G2API_CleanEntAttachments(void) { #ifdef _G2_LISTEN_SERVER_OPT int i = 0; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { g2ClientAttachments[i] = NULL; i++; } @@ -232,21 +199,18 @@ void G2API_CleanEntAttachments(void) void CopyBoneCache(CBoneCache *to, CBoneCache *from); #endif -qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelIndex) -{ +qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v &ghoul2, int modelIndex) { #ifndef _G2_LISTEN_SERVER_OPT return qfalse; #else CGhoul2Info *serverInstance = &ghoul2[modelIndex]; CGhoul2Info *clientInstance; - if (ri.Cvar_VariableIntegerValue( "dedicated" )) - { //No client to get from! + if (ri.Cvar_VariableIntegerValue("dedicated")) { // No client to get from! return qfalse; } - if (!g2ClientAttachments[serverInstance->entityNum]) - { //No clientside instance is attached to this entity + if (!g2ClientAttachments[serverInstance->entityNum]) { // No clientside instance is attached to this entity return qfalse; } @@ -255,17 +219,15 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde int frameNum = G2API_GetTime(0); - if (clientInstance->mSkelFrameNum != frameNum) - { //it has to be constructed already + if (clientInstance->mSkelFrameNum != frameNum) { // it has to be constructed already return qfalse; } - if (!clientInstance->mBoneCache) - { //that just won't do + if (!clientInstance->mBoneCache) { // that just won't do return qfalse; } - //Just copy over the essentials + // Just copy over the essentials serverInstance->aHeader = clientInstance->aHeader; serverInstance->animModel = clientInstance->animModel; serverInstance->currentAnimModelSize = clientInstance->currentAnimModelSize; @@ -277,14 +239,12 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde serverInstance->mSurfaceRoot = clientInstance->mSurfaceRoot; serverInstance->mTransformedVertsArray = clientInstance->mTransformedVertsArray; - if (!serverInstance->mBoneCache) - { //if this is the case.. I guess we can use the client one instead + if (!serverInstance->mBoneCache) { // if this is the case.. I guess we can use the client one instead serverInstance->mBoneCache = clientInstance->mBoneCache; } - //Copy the contents of the client cache over the contents of the server cache - if (serverInstance->mBoneCache != clientInstance->mBoneCache) - { + // Copy the contents of the client cache over the contents of the server cache + if (serverInstance->mBoneCache != clientInstance->mBoneCache) { CopyBoneCache(serverInstance->mBoneCache, clientInstance->mBoneCache); } @@ -297,155 +257,123 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde #define MAX_G2_MODELS (1024) #define G2_MODEL_BITS (10) -#define G2_INDEX_MASK (MAX_G2_MODELS-1) +#define G2_INDEX_MASK (MAX_G2_MODELS - 1) -class Ghoul2InfoArray : public IGhoul2InfoArray -{ - std::vector mInfos[MAX_G2_MODELS]; - int mIds[MAX_G2_MODELS]; - std::list mFreeIndecies; - void DeleteLow(int idx) - { - for (size_t model=0; model< mInfos[idx].size(); model++) - { - if (mInfos[idx][model].mBoneCache) - { +class Ghoul2InfoArray : public IGhoul2InfoArray { + std::vector mInfos[MAX_G2_MODELS]; + int mIds[MAX_G2_MODELS]; + std::list mFreeIndecies; + void DeleteLow(int idx) { + for (size_t model = 0; model < mInfos[idx].size(); model++) { + if (mInfos[idx][model].mBoneCache) { RemoveBoneCache(mInfos[idx][model].mBoneCache); - mInfos[idx][model].mBoneCache=0; + mInfos[idx][model].mBoneCache = 0; } } mInfos[idx].clear(); - if ((mIds[idx]>>G2_MODEL_BITS)>(1<<(31-G2_MODEL_BITS))) - { - mIds[idx]=MAX_G2_MODELS+idx; //rollover reset id to minimum value + if ((mIds[idx] >> G2_MODEL_BITS) > (1 << (31 - G2_MODEL_BITS))) { + mIds[idx] = MAX_G2_MODELS + idx; // rollover reset id to minimum value mFreeIndecies.push_back(idx); - } - else - { - mIds[idx]+=MAX_G2_MODELS; + } else { + mIds[idx] += MAX_G2_MODELS; mFreeIndecies.push_front(idx); } } -public: - Ghoul2InfoArray() - { + + public: + Ghoul2InfoArray() { int i; - for (i=0;i::iterator j; - for (j=mFreeIndecies.begin();j!=mFreeIndecies.end();++j) - { - if (*j==i) + for (j = mFreeIndecies.begin(); j != mFreeIndecies.end(); ++j) { + if (*j == i) break; } - if (j==mFreeIndecies.end()) - { + if (j == mFreeIndecies.end()) { Com_OPrintf("Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); - if (mInfos[i].size()) - { + if (mInfos[i].size()) { Com_OPrintf("%s\n", mInfos[i][0].mFileName); } } } - } - else - { + } else { Com_OPrintf("No ghoul2 info slots leaked\n"); } } #endif - int New() - { - if (mFreeIndecies.empty()) - { + int New() { + if (mFreeIndecies.empty()) { assert(0); Com_Error(ERR_FATAL, "Out of ghoul2 info slots"); - } // gonna pull from the front, doing a - int idx=*mFreeIndecies.begin(); + int idx = *mFreeIndecies.begin(); mFreeIndecies.erase(mFreeIndecies.begin()); return mIds[idx]; } - bool IsValid(int handle) const - { - if ( handle <= 0 ) - { + bool IsValid(int handle) const { + if (handle <= 0) { return false; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + if (mIds[handle & G2_INDEX_MASK] != handle) // not a valid handle, could be old { return false; } return true; } - void Delete(int handle) - { - if (handle <= 0) - { + void Delete(int handle) { + if (handle <= 0) { return; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + if (mIds[handle & G2_INDEX_MASK] == handle) { + DeleteLow(handle & G2_INDEX_MASK); } } - std::vector &Get(int handle) - { - assert(handle>0); //null handle - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); + std::vector &Get(int handle) { + assert(handle > 0); // null handle + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + assert(!(handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle)); - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - const std::vector &Get(int handle) const - { - assert(handle>0); - assert(mIds[handle&G2_INDEX_MASK]==handle); // not a valid handle, could be old or garbage - return mInfos[handle&G2_INDEX_MASK]; + const std::vector &Get(int handle) const { + assert(handle > 0); + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + return mInfos[handle & G2_INDEX_MASK]; } #if G2API_DEBUG - vector &GetDebug(int handle) - { + vector &GetDebug(int handle) { static vector null; - if (handle<=0||(handle&G2_INDEX_MASK)<0||(handle&G2_INDEX_MASK)>=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle) - { + if (handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle) { return *(vector *)0; // null reference, intentional } - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - void TestAllAnims() - { + void TestAllAnims() { int j; - for (j=0;j &ghoul2=mInfos[j]; + for (j = 0; j < MAX_G2_MODELS; j++) { + vector &ghoul2 = mInfos[j]; int i; - for (i=0; islot == VM_GAME ) - { - if ( ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && ShaderHashTableExists()) - { //if the hunk has been marked then we are now loading client assets so don't load on server. + if (currentVM && currentVM->slot == VM_GAME) { + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // if the hunk has been marked then we are now loading client assets so don't load on server. return qfalse; } @@ -563,37 +480,30 @@ qboolean G2_ShouldRegisterServer(void) return qfalse; } -qhandle_t G2API_PrecacheGhoul2Model( const char *fileName ) -{ - if ( G2_ShouldRegisterServer() ) - return RE_RegisterServerModel( fileName ); +qhandle_t G2API_PrecacheGhoul2Model(const char *fileName) { + if (G2_ShouldRegisterServer()) + return RE_RegisterServerModel(fileName); else - return RE_RegisterModel( fileName ); + return RE_RegisterModel(fileName); } // initialise all that needs to be on a new Ghoul II model -int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, - qhandle_t customShader, int modelFlags, int lodBias) -{ - int model; +int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { + int model; // are we actually asking for a model to be loaded. - if (!fileName || !fileName[0]) - { + if (!fileName || !fileName[0]) { assert(0); return -1; } - if (!(*ghoul2Ptr)) - { + if (!(*ghoul2Ptr)) { *ghoul2Ptr = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -604,29 +514,23 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); // find a free spot in the list - for (model=0; model< ghoul2.size(); model++) - { - if (ghoul2[model].mModelindex == -1) - { - ghoul2[model]=CGhoul2Info(); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModelindex == -1) { + ghoul2[model] = CGhoul2Info(); break; } } - if (model==ghoul2.size()) - { //init should not be used to create additional models, only the first one - assert(ghoul2.size() < 4); //use G2API_CopySpecificG2Model to add models + if (model == ghoul2.size()) { // init should not be used to create additional models, only the first one + assert(ghoul2.size() < 4); // use G2API_CopySpecificG2Model to add models ghoul2.push_back(CGhoul2Info()); } strcpy(ghoul2[model].mFileName, fileName); ghoul2[model].mModelindex = model; - if (!G2_TestModelPointers(&ghoul2[model])) - { - ghoul2[model].mFileName[0]=0; + if (!G2_TestModelPointers(&ghoul2[model])) { + ghoul2[model].mFileName[0] = 0; ghoul2[model].mModelindex = -1; - } - else - { + } else { G2_Init_Bone_List(ghoul2[model].mBlist, ghoul2[model].aHeader->numBones); G2_Init_Bolt_List(ghoul2[model].mBltlist); ghoul2[model].mCustomShader = customShader; @@ -640,27 +544,22 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m return ghoul2[model].mModelindex; } -qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mLodBias = lodBias; return qtrue; } return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin); -qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin); +qboolean G2API_SetSkin(CGhoul2Info_v &ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomSkin = customSkin; - if (renderSkin) - {//this is going to set the surfs on/off matching the skin file - G2_SetSurfaceOnOffFromSkin( ghlInfo, renderSkin ); + if (renderSkin) { // this is going to set the surfs on/off matching the skin file + G2_SetSurfaceOnOffFromSkin(ghlInfo, renderSkin); } return qtrue; @@ -668,27 +567,22 @@ qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSk return qfalse; } -qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomShader = customShader; return qtrue; } return qfalse; } -qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) -{ +qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, surfaceName, flags); @@ -696,29 +590,23 @@ qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, c return qfalse; } -int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceOff(ghlInfo, ghlInfo->mSlist, surfaceName); } return -1; } -qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghoul2)) - { +qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) { + if (G2_SetupModelPointers(ghoul2)) { return G2_SetRootSurface(ghoul2, modelIndex, surfaceName); } return qfalse; } -int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); @@ -726,10 +614,8 @@ int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, fl return -1; } -qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_RemoveSurface(ghlInfo->mSlist, index); @@ -737,66 +623,55 @@ qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) return qfalse; } -int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetParentSurface(ghlInfo, index); } return -1; } -int G2API_GetSurfaceRenderStatus(CGhoul2Info_v& ghoul2, int modelIndex, const char *surfaceName) -{ +int G2API_GetSurfaceRenderStatus(CGhoul2Info_v &ghoul2, int modelIndex, const char *surfaceName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceRendered(ghlInfo, surfaceName, ghlInfo->mSlist); } return -1; } -qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { return qfalse; } return qtrue; } -qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; // sanity check - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { // if we hit this assert then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. assert(0); return qfalse; } - if (ghlInfo.size() > modelIndex) - { + if (ghlInfo.size() > modelIndex) { #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -804,40 +679,32 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; int newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (int i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -847,43 +714,36 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex } } - return qtrue; } -qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) -{//remove 'em ALL! +qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) { // remove 'em ALL! CGhoul2Info_v &ghlInfo = **ghlRemove; - int modelIndex = 0; + int modelIndex = 0; int newSize = 0; int i; // sanity check - if ( !ghlInfo.size() ) - {// if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that + if (!ghlInfo.size()) { // if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. return qfalse; } - for ( modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++ ) - { - if ( ghlInfo[modelIndex].mModelindex == -1 ) - { + for (modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++) { + if (ghlInfo[modelIndex].mModelindex == -1) { continue; } #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -891,41 +751,33 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; } newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -936,201 +788,172 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) return qtrue; } -//check if a bone exists on skeleton without actually adding to the bone list -rww -qboolean G2API_DoesBoneExist(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +// check if a bone exists on skeleton without actually adding to the bone list -rww +qboolean G2API_DoesBoneExist(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { //model is valid + if (G2_SetupModelPointers(ghlInfo)) { // model is valid mdxaHeader_t *mdxa = ghlInfo->currentModel->mdxa; - if (mdxa) - { //get the skeleton data and iterate through the bones + if (mdxa) { // get the skeleton data and iterate through the bones int i; mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for (i = 0; i < mdxa->numBones; i++) - { - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (!Q_stricmp(skel->name, boneName)) - { //got it + for (i = 0; i < mdxa->numBones; i++) { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + if (!Q_stricmp(skel->name, boneName)) { // got it return qtrue; } } } } - //guess it doesn't exist + // guess it doesn't exist return qfalse; } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled -//rww - RAGDOLL_END +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +// rww - RAGDOLL_END -qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ +qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, + const int currentTime, const float AsetFrame, const int blendTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); - if (endFrame<=0) - { - endFrame=1; + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); + return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, + ghlInfo->aHeader->numFrames); } return qfalse; } #define _PLEASE_SHUT_THE_HELL_UP -qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; +qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, + const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) { + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; #ifndef _PLEASE_SHUT_THE_HELL_UP - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); #endif - if (endFrame<=0) - { - endFrame=1; + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (ghoul2.size()>modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); + return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } } return qfalse; } -qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, - int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList) -{ - assert(startFrame!=endFrame); //this is bad - assert(startFrame!=flags); //this is bad - assert(endFrame!=flags); //this is bad - assert(currentFrame!=animSpeed); //this is bad +qboolean G2API_GetBoneAnim(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *animSpeed, int *modelList) { + assert(startFrame != endFrame); // this is bad + assert(startFrame != flags); // this is bad + assert(endFrame != flags); // this is bad + assert(currentFrame != animSpeed); // this is bad CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - int aCurrentTime=G2API_GetTime(currentTime); - qboolean ret=G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, - startFrame, endFrame, flags, animSpeed, modelList, ghlInfo->mModelindex); + if (G2_SetupModelPointers(ghlInfo)) { + int aCurrentTime = G2API_GetTime(currentTime); + qboolean ret = G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, + ghlInfo->mModelindex); #ifdef _DEBUG /* assert(*endFrame>0); @@ -1140,29 +963,23 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo assert(*currentFrame>=0.0f); assert(*currentFrame<100000.0f); */ - if (*endFrame<1) - { - *endFrame=1; + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } - if (*currentFrame<0.0f) - { - *currentFrame=0.0f; + if (*currentFrame < 0.0f) { + *currentFrame = 0.0f; } - if (*currentFrame>100000) - { - *currentFrame=1; + if (*currentFrame > 100000) { + *currentFrame = 1; } #endif return ret; @@ -1170,32 +987,26 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo return qfalse; } -qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) -{ - assert(startFrame!=endFrame); //this is bad - if (G2_SetupModelPointers(ghlInfo)) - { - qboolean ret=G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); +qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) { + assert(startFrame != endFrame); // this is bad + if (G2_SetupModelPointers(ghlInfo)) { + qboolean ret = G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); #ifdef _DEBUG - assert(*endFrame>0); - assert(*endFrame<100000); - assert(*startFrame>=0); - assert(*startFrame<100000); - if (*endFrame<1) - { - *endFrame=1; + assert(*endFrame > 0); + assert(*endFrame < 100000); + assert(*startFrame >= 0); + assert(*startFrame < 100000); + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } #endif return ret; @@ -1203,126 +1014,101 @@ qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *sta return qfalse; } - -qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); +qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); } return qfalse; } -qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); +qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); } return qfalse; } -qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, - const Eorientations yaw, const Eorientations pitch, const Eorientations roll, - qhandle_t *modelList, int blendTime, int currentTime) -{ +qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, int blendTime, int currentTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles_Index( ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, modelList, ghlInfo->mModelindex, blendTime, currentTime); + return G2_Set_Bone_Angles_Index(ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, modelList, ghlInfo->mModelindex, blendTime, currentTime); } return qfalse; } -qboolean G2API_SetBoneAngles(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *modelList, int blendTime, int currentTime ) -{ - if (ghoul2.size()>modelIndex) - { +qboolean G2API_SetBoneAngles(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghoul2); } - if (res) - { - // ensure we flush the cache + if (res) { + // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, modelList, ghlInfo->mModelindex, blendTime, currentTime); + return G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, modelList, ghlInfo->mModelindex, blendTime, + currentTime); } } return qfalse; } -qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; return G2_Set_Bone_Angles_Matrix_Index(ghlInfo->mBlist, index, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); @@ -1330,11 +1116,9 @@ qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, c return qfalse; } -qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; return G2_Set_Bone_Angles_Matrix(ghlInfo->mFileName, ghlInfo->mBlist, boneName, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); @@ -1342,83 +1126,65 @@ qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, c return qfalse; } -qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); + return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); } return qfalse; } -qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Stop_Bone_Angles(ghlInfo->mFileName, ghlInfo->mBlist, boneName); + return G2_Stop_Bone_Angles(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } - -void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) -{ +void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (status) - { //turn it on + if (status) { // turn it on ghlInfo->mFlags |= GHOUL2_CRAZY_SMOOTH; - } - else - { //off + } else { // off ghlInfo->mFlags &= ~GHOUL2_CRAZY_SMOOTH; } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN class CRagDollParams; -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms); -void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms) -{ - G2_SetRagDoll(ghoul2,parms); -} +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms); +void G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms) { G2_SetRagDoll(ghoul2, parms); } void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V); -void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) -{ - G2_ResetRagDoll(ghoul2); -} -//rww - RAGDOLL_END +void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) { G2_ResetRagDoll(ghoul2); } +// rww - RAGDOLL_END -qboolean G2API_RemoveBone(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +qboolean G2API_RemoveBone(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); + return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); } return qfalse; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef _DEBUG extern int ragTraceTime; extern int ragSSCount; extern int ragTraceCount; #endif -void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUpdateParams *params) -{ +void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) { int model; - int currentTime=G2API_GetTime(AcurrentTime); + int currentTime = G2API_GetTime(AcurrentTime); #ifdef _DEBUG ragTraceTime = 0; @@ -1427,11 +1193,9 @@ void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUp #endif // Walk the list and find all models that are active - for (model = 0; model < ghoul2.size(); model++) - { - if (ghoul2[model].mModel) - { - G2_Animate_Bone_List(ghoul2,currentTime,model,params); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModel) { + G2_Animate_Bone_List(ghoul2, currentTime, model, params); } } #ifdef _DEBUG @@ -1442,55 +1206,48 @@ void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUp } */ - //keep sane limits here, if it gets too slow an assert is proper. + // keep sane limits here, if it gets too slow an assert is proper. // assert(ragTraceTime < 150); // assert(ragTraceCount < 1500); #endif } -//rww - RAGDOLL_END +// rww - RAGDOLL_END int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); -#define RAG_PCJ (0x00001) -#define RAG_EFFECTOR (0x00100) +#define RAG_PCJ (0x00001) +#define RAG_EFFECTOR (0x00100) -static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) -{ +static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return NULL; } int boneIndex = G2_Find_Bone_Rag(ghlInfo, ghlInfo->mBlist, boneName); - if (boneIndex < 0) - { //bad bone specification + if (boneIndex < 0) { // bad bone specification return NULL; } boneInfo_t *bone = &ghlInfo->mBlist[boneIndex]; - if (!(bone->flags & BONE_ANGLES_RAGDOLL)) - { //only want to return rag bones + if (!(bone->flags & BONE_ANGLES_RAGDOLL)) { // only want to return rag bones return NULL; } return bone; } -qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) -{ +qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1500,17 +1257,14 @@ qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec return qtrue; } -qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) -{ +qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1519,48 +1273,38 @@ qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, return qtrue; } -qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) -{ +qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } - if (!pos) - { //go back to none in case we have one then + if (!pos) { // go back to none in case we have one then bone->hasOverGoal = false; - } - else - { + } else { VectorCopy(pos, bone->overGoalSpot); bone->hasOverGoal = true; } return qtrue; } -qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) -{ //do something? +qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { // do something? return qfalse; } -qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) -{ +qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } @@ -1571,22 +1315,17 @@ qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3 return qtrue; } -qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) -{ +qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return qfalse; } - if (force) - { + if (force) { ghlInfo->mFlags |= GHOUL2_RAG_FORCESOLVE; - } - else - { + } else { ghlInfo->mFlags &= ~GHOUL2_RAG_FORCESOLVE; } @@ -1594,133 +1333,104 @@ qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) } qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params); -qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ +qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return G2_SetBoneIKState(ghoul2, time, boneName, ikState, params); } qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params); -qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ - return G2_IKMove(ghoul2, time, params); -} +qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { return G2_IKMove(ghoul2, time, params); } -qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Remove_Bolt( ghlInfo->mBltlist, index); +qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Remove_Bolt(ghlInfo->mBltlist, index); } return qfalse; } -int G2API_AddBolt(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) -{ -// assert(ghoul2.size()>modelIndex); +int G2API_AddBolt(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) { + // assert(ghoul2.size()>modelIndex); - if (ghoul2.size()>modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Add_Bolt(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); } } return -1; } -int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Add_Bolt_Surf_Num(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); } return -1; } - -qboolean G2API_AttachG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int toBoltIndex, int toModel) -{ - assert( toBoltIndex >= 0 ); - if ( toBoltIndex < 0 ) - { +qboolean G2API_AttachG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int toBoltIndex, int toModel) { + assert(toBoltIndex >= 0); + if (toBoltIndex < 0) { return qfalse; } - if (G2_SetupModelPointers(ghoul2From)&&G2_SetupModelPointers(ghoul2To)) - { + if (G2_SetupModelPointers(ghoul2From) && G2_SetupModelPointers(ghoul2To)) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if ((ghoul2From.size() > modelFrom) && - (ghoul2To.size() > toModel) && - ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if ((ghoul2From.size() > modelFrom) && (ghoul2To.size() > toModel) && + ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModel &= MODEL_AND; - toBoltIndex &= BOLT_AND; - ghoul2From[modelFrom].mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); - return qtrue; + toModel &= MODEL_AND; + toBoltIndex &= BOLT_AND; + ghoul2From[modelFrom].mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); + return qtrue; } } return qfalse; } -void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) -{ - if (ghoul2.size() > modelIndex) - { +void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) { + if (ghoul2.size() > modelIndex) { ghoul2[modelIndex].mModelBoltLink = boltInfo; } } -qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - ghlInfo->mModelBoltLink = -1; - return qtrue; +qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { + ghlInfo->mModelBoltLink = -1; + return qtrue; } return qfalse; } -qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info_v& ghoul2, int modelIndex, int toBoltIndex, int entNum, int toModelNum) -{ +qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info_v &ghoul2, int modelIndex, int toBoltIndex, int entNum, int toModelNum) { CGhoul2Info *ghlInfoTo = &ghoul2[modelIndex]; - if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) - { + if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if ( ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if (ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModelNum &= MODEL_AND; - toBoltIndex &= BOLT_AND; - entNum &= ENTITY_AND; - *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); - return qtrue; + toModelNum &= MODEL_AND; + toBoltIndex &= BOLT_AND; + entNum &= ENTITY_AND; + *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); + return qtrue; } } return qfalse; - } qboolean gG2_GBMNoReconstruct; qboolean gG2_GBMUseSPMethod; qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int frameNum, qhandle_t *modelList, const vec3_t scale ) -{ + const vec3_t position, const int frameNum, qhandle_t *modelList, const vec3_t scale) { assert(ghoul2.size() > modelIndex); - if ((ghoul2.size() > modelIndex)) - { + if ((ghoul2.size() > modelIndex)) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - //assert(boltIndex < ghlInfo->mBltlist.size()); + // assert(boltIndex < ghlInfo->mBltlist.size()); - if (ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) && boltIndex >= 0 ) - { + if (ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) && boltIndex >= 0) { // make sure we have transformed the skeleton - if (!gG2_GBMNoReconstruct) - { + if (!gG2_GBMNoReconstruct) { G2_ConstructGhoulSkeleton(ghoul2, frameNum, true, scale); } @@ -1728,33 +1438,29 @@ qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelInde mdxaBone_t scaled; mdxaBone_t *use; - use=&ghlInfo->mBltlist[boltIndex].position; + use = &ghlInfo->mBltlist[boltIndex].position; - if (scale[0]||scale[1]||scale[2]) - { - scaled=*use; - use=&scaled; + if (scale[0] || scale[1] || scale[2]) { + scaled = *use; + use = &scaled; // scale the bolt position by the scale factor for this model since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { scaled.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { scaled.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { scaled.matrix[2][3] *= scale[2]; } } // pre generate the world matrix G2_GenerateWorldMatrix(angles, position); - VectorNormalize((float*)use->matrix[0]); - VectorNormalize((float*)use->matrix[1]); - VectorNormalize((float*)use->matrix[2]); + VectorNormalize((float *)use->matrix[0]); + VectorNormalize((float *)use->matrix[1]); + VectorNormalize((float *)use->matrix[2]); Multiply_3x4Matrix(matrix, &worldMatrix, use); return qtrue; @@ -1763,44 +1469,33 @@ qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelInde return qfalse; } -#define G2ERROR(exp,m) ((void)0) //rwwFIXMEFIXME: This is because I'm lazy. -#define G2WARNING(exp,m) ((void)0) -#define G2NOTE(exp,m) ((void)0) -#define G2ANIM(ghlInfo,m) ((void)0) -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum); -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); +#define G2ERROR(exp, m) ((void)0) // rwwFIXMEFIXME: This is because I'm lazy. +#define G2WARNING(exp, m) ((void)0) +#define G2NOTE(exp, m) ((void)0) +#define G2ANIM(ghlInfo, m) ((void)0) +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum); +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); -//qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, +// qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, // const vec3_t position, const int AframeNum, qhandle_t *modelList, const vec3_t scale ) -qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) -{ -// G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo"); - G2ERROR(matrix,"NULL matrix"); - G2ERROR(modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size(), "Invalid ModelIndex"); + const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; G2_GenerateWorldMatrix(angles, position); - if (G2_SetupModelPointers(ghoul2)) - { - if (matrix&&modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size()) { + int tframeNum = G2API_GetTime(frameNum); CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - G2ERROR(boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()),va("Invalid Bolt Index (%d:%s)",boltIndex,ghlInfo->mFileName)); + G2ERROR(boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()), va("Invalid Bolt Index (%d:%s)", boltIndex, ghlInfo->mFileName)); - if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) ) - { + if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size())) { mdxaBone_t bolt; -#if 0 //yeah, screw it +#if 0 // yeah, screw it if (!gG2_GBMNoReconstruct) { //This should only be used when you know what you're doing. if (G2_NeedsRecalc(ghlInfo,tframeNum)) @@ -1813,44 +1508,37 @@ qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const gG2_GBMNoReconstruct = qfalse; } #else - if (G2_NeedsRecalc(ghlInfo,tframeNum)) - { - G2_ConstructGhoulSkeleton(ghoul2,tframeNum,true,scale); + if (G2_NeedsRecalc(ghlInfo, tframeNum)) { + G2_ConstructGhoulSkeleton(ghoul2, tframeNum, true, scale); } #endif - G2_GetBoltMatrixLow(*ghlInfo,boltIndex,scale,bolt); + G2_GetBoltMatrixLow(*ghlInfo, boltIndex, scale, bolt); // scale the bolt position by the scale factor for this model since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); Multiply_3x4Matrix(matrix, &worldMatrix, &bolt); #if G2API_DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !_isnan(matrix->matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!_isnan(matrix->matrix[i][j])); } } -#endif// _DEBUG - G2ANIM(ghlInfo,"G2API_GetBoltMatrix"); +#endif // _DEBUG + G2ANIM(ghlInfo, "G2API_GetBoltMatrix"); - if (!gG2_GBMUseSPMethod) - { //this is horribly stupid and I hate it. But lots of game code is written to assume this 90 degree offset thing. + if (!gG2_GBMUseSPMethod) { // this is horribly stupid and I hate it. But lots of game code is written to assume this 90 degree offset thing. float ftemp; ftemp = matrix->matrix[0][0]; matrix->matrix[0][0] = -matrix->matrix[0][1]; @@ -1863,47 +1551,36 @@ qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const ftemp = matrix->matrix[2][0]; matrix->matrix[2][0] = -matrix->matrix[2][1]; matrix->matrix[2][1] = ftemp; - } - else - { //reset it + } else { // reset it gG2_GBMUseSPMethod = qfalse; } return qtrue; } } - } - else - { - G2WARNING(0,"G2API_GetBoltMatrix Failed on empty or bad model"); + } else { + G2WARNING(0, "G2API_GetBoltMatrix Failed on empty or bad model"); } Multiply_3x4Matrix(matrix, &worldMatrix, (mdxaBone_t *)&identityMatrix); return qfalse; } -void G2API_ListSurfaces(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListSurfaces(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Surfaces(ghlInfo->mFileName); } } -void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Bones(ghlInfo->mFileName, frame); } } // decide if we have Ghoul2 models associated with this ghoul list or not -qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) -{ - for (int i=0; imdxm->animName; } @@ -1934,10 +1607,8 @@ char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) * true if a good filename was obtained, false otherwise * ************************************************************************************************/ -qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetAnimFileName(ghlInfo->mFileName, filename); } return qfalse; @@ -1948,39 +1619,32 @@ qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) SV_QsortEntityNumbers ======================= */ -static int QDECL QsortDistance( const void *a, const void *b ) { - const float &ea = ((CollisionRecord_t*)a)->mDistance; - const float &eb = ((CollisionRecord_t*)b)->mDistance; +static int QDECL QsortDistance(const void *a, const void *b) { + const float &ea = ((CollisionRecord_t *)a)->mDistance; + const float &eb = ((CollisionRecord_t *)b)->mDistance; - if ( ea < eb ) { + if (ea < eb) { return -1; } return 1; } -static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) -{ //see if we need to do another transform +static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) { // see if we need to do another transform size_t i = 0; bool needTrans = false; - while (i < g2->mBlist.size()) - { - float time; + while (i < g2->mBlist.size()) { + float time; boneInfo_t &bone = g2->mBlist[i]; - if (bone.pauseTime) - { + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (frameNum - bone.startTime) / 50.0f; } int newFrame = bone.startFrame + (time * bone.animSpeed); - if (newFrame < bone.endFrame || - (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || - (bone.flags & BONE_NEED_TRANSFORM)) - { //ok, we're gonna have to do it. bone is apparently animating. + if (newFrame < bone.endFrame || (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || + (bone.flags & BONE_NEED_TRANSFORM)) { // ok, we're gonna have to do it. bone is apparently animating. bone.flags &= ~BONE_NEED_TRANSFORM; needTrans = true; } @@ -1990,25 +1654,23 @@ static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) return needTrans; } -void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) -{ //this will store off the transformed verts for the next trace - this is slower, but for models that do not animate - //frequently it is much much faster. -rww +void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, + float fRadius) { // this will store off the transformed verts for the next trace - this is slower, but for models that do not + // animate frequently it is much much faster. -rww #if 0 // UNUSED int *test = ghoul2[0].mTransformedVertsArray; #endif - if (G2_SetupModelPointers(ghoul2)) - { - vec3_t transRayStart, transRayEnd; + if (G2_SetupModelPointers(ghoul2)) { + vec3_t transRayStart, transRayEnd; - int tframeNum=G2API_GetTime(frameNumber); + int tframeNum = G2API_GetTime(frameNumber); // make sure we have transformed the whole skeletons for each model - if (G2_NeedRetransform(&ghoul2[0], tframeNum) || !ghoul2[0].mTransformedVertsArray) - { //optimization, only create new transform space if we need to, otherwise - //store it off! + if (G2_NeedRetransform(&ghoul2[0], tframeNum) || + !ghoul2[0].mTransformedVertsArray) { // optimization, only create new transform space if we need to, otherwise + // store it off! int i = 0; - while (i < ghoul2.size()) - { + while (i < ghoul2.size()) { CGhoul2Info &g2 = ghoul2[i]; /* @@ -2018,10 +1680,9 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh g2.mTransformedVertsArray = 0; } */ - if (!g2.mTransformedVertsArray || !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) - { //reworked so we only alloc once! - //if we have a pointer, but not a ghoul2_zonetransalloc flag, then that means - //it is a miniheap pointer. Just stomp over it. + if (!g2.mTransformedVertsArray || !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) { // reworked so we only alloc once! + // if we have a pointer, but not a ghoul2_zonetransalloc flag, then that means + // it is a miniheap pointer. Just stomp over it. int iSize = g2.currentModel->mdxm->numSurfaces * 4; g2.mTransformedVertsArray = (size_t *)Z_Malloc(iSize, TAG_GHOUL2, qtrue); } @@ -2040,7 +1701,7 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); #endif - //don't need to do this anymore now that I am using a flag for zone alloc. + // don't need to do this anymore now that I am using a flag for zone alloc. /* i = 0; while (i < ghoul2.size()) @@ -2067,23 +1728,21 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh // now walk each model and check the ray against each poly - sigh, this is SO expensive. I wish there was a better way to do this. #ifdef _G2_GORE - G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius,0,0,0,0,0,qfalse); + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius, 0, 0, 0, 0, 0, qfalse); #else G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius); #endif int i; - for ( i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i ++ ); + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) + ; // now sort the resulting array of collision records so they are distance ordered - qsort( collRecMap, i, - sizeof( CollisionRecord_t ), QsortDistance ); + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); } } - -void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) -{ +void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) { /* if (1) { @@ -2093,9 +1752,8 @@ void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, } */ - if (G2_SetupModelPointers(ghoul2)) - { - vec3_t transRayStart, transRayEnd; + if (G2_SetupModelPointers(ghoul2)) { + vec3_t transRayStart, transRayEnd; // make sure we have transformed the whole skeletons for each model G2_ConstructGhoulSkeleton(ghoul2, frameNumber, true, scale); @@ -2119,23 +1777,21 @@ void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, // now walk each model and check the ray against each poly - sigh, this is SO expensive. I wish there was a better way to do this. #ifdef _G2_GORE - G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius,0,0,0,0,0,qfalse); + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius, 0, 0, 0, 0, 0, qfalse); #else G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius); #endif int i; - for ( i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i ++ ); + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) + ; // now sort the resulting array of collision records so they are distance ordered - qsort( collRecMap, i, - sizeof( CollisionRecord_t ), QsortDistance ); + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); } } -qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mFlags &= GHOUL2_NEWORIGIN; ghlInfo->mFlags |= flags; return qtrue; @@ -2143,20 +1799,16 @@ qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) return qfalse; } -int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { return (ghlInfo->mFlags & ~GHOUL2_NEWORIGIN); } return 0; } // given a boltmatrix, return in vec a normalised vector for the axis requested in flags -void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) -{ - switch (flags) - { +void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) { + switch (flags) { case ORIGIN: vec[0] = boltMatrix->matrix[0][3]; vec[1] = boltMatrix->matrix[1][3]; @@ -2166,7 +1818,7 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v vec[0] = boltMatrix->matrix[0][1]; vec[1] = boltMatrix->matrix[1][1]; vec[2] = boltMatrix->matrix[2][1]; - break; + break; case POSITIVE_X: vec[0] = boltMatrix->matrix[0][0]; vec[1] = boltMatrix->matrix[1][0]; @@ -2195,36 +1847,29 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v } } +int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) { + assert(modelIndex == -1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it + // if ya want it, we will add it back correctly -int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) -{ - assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it - // if ya want it, we will add it back correctly - - //G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); - if (g2From.IsValid()) - { + // G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); + if (g2From.IsValid()) { #ifdef _DEBUG - if (g2To.IsValid()) - { + if (g2To.IsValid()) { assert(!"Copying to a valid g2 instance?!"); - if (g2To[0].mBoneCache) - { + if (g2To[0].mBoneCache) { assert(!"Instance has a bonecache too.. it's gonna get stomped"); } } #endif g2To.DeepCopy(g2From); -#ifdef _G2_GORE //check through gore stuff then, as well. +#ifdef _G2_GORE // check through gore stuff then, as well. int model = 0; - while (model < g2To.size()) - { - if ( g2To[model].mGoreSetTag ) - { - CGoreSet* gore = FindGoreSet ( g2To[model].mGoreSetTag ); + while (model < g2To.size()) { + if (g2To[model].mGoreSetTag) { + CGoreSet *gore = FindGoreSet(g2To[model].mGoreSetTag); assert(gore); gore->mRefCount++; } @@ -2232,28 +1877,25 @@ int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int mod model++; } #endif - //G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); - //G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); + // G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); + // G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); } return -1; } -void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) -{ +void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) { #if 0 qboolean forceReconstruct = qtrue; -#endif //model1 was not getting reconstructed like it should for thrown sabers? - //might have been a bug in the reconstruct checking which has since been - //mangled and probably fixed. -rww +#endif // model1 was not getting reconstructed like it should for thrown sabers? + // might have been a bug in the reconstruct checking which has since been + // mangled and probably fixed. -rww // assume we actually have a model to copy from - if (ghoul2From.size() > modelFrom) - { + if (ghoul2From.size() > modelFrom) { // if we don't have enough models on the to side, resize us so we do - if (ghoul2To.size() <= modelTo) - { - assert (modelTo < 5); + if (ghoul2To.size() <= modelTo) { + assert(modelTo < 5); ghoul2To.resize(modelTo + 1); #if 0 forceReconstruct = qtrue; @@ -2261,10 +1903,8 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // do the copy - if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) - { //remove the bonecache before we stomp over this instance. - if (ghoul2To[modelTo].mBoneCache) - { + if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) { // remove the bonecache before we stomp over this instance. + if (ghoul2To[modelTo].mBoneCache) { RemoveBoneCache(ghoul2To[modelTo].mBoneCache); ghoul2To[modelTo].mBoneCache = 0; } @@ -2283,24 +1923,19 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // This version will automatically copy everything about this model, and make a new one if necessary. -void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) -{ - //int ignore; +void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) { + // int ignore; - if (*g2To) - { // This is bad. We only want to do this if there is not yet a to declared. + if (*g2To) { // This is bad. We only want to do this if there is not yet a to declared. assert(0); return; } *g2To = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -2308,48 +1943,41 @@ void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) #endif CGhoul2Info_v &ghoul2 = *(*g2To); - /*ignore = */G2API_CopyGhoul2Instance(g2From, ghoul2, -1); + /*ignore = */ G2API_CopyGhoul2Instance(g2From, ghoul2, -1); return; } -char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber) -{ +char *G2API_GetSurfaceName(CGhoul2Info_v &ghoul2, int modelIndex, int surfNumber) { static char noSurface[1] = ""; CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmSurfHierarchy_t *surfInfo = 0; + if (G2_SetupModelPointers(ghlInfo)) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmSurfHierarchy_t *surfInfo = 0; #ifndef FINAL_BUILD - if (!mod || !mod->mdxm) - { + if (!mod || !mod->mdxm) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad model on instance %s.", ghlInfo->mFileName); } #endif - //ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model - //may have.. but how did they get that surf index to begin with? Oh well. - if (surfNumber < 0 || surfNumber >= mod->mdxm->numSurfaces) - { - ri.Printf( PRINT_ALL, "G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); + // ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model + // may have.. but how did they get that surf index to begin with? Oh well. + if (surfNumber < 0 || surfNumber >= mod->mdxm->numSurfaces) { + ri.Printf(PRINT_ALL, "G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); return noSurface; } - surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, 0); - if (surf) - { + if (surf) { #ifndef FINAL_BUILD - if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mod->mdxm->numSurfaces) - { + if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mod->mdxm->numSurfaces) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad surf num (%i) on surf for instance %s.", surf->thisSurfaceIndex, ghlInfo->mFileName); } #endif - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->name; } @@ -2357,24 +1985,18 @@ char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber return noSurface; } - -int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetSurfaceIndex(ghlInfo, surfaceName); } return -1; } -char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) -{ - if (G2_SetupModelPointers(ghoul2)) - { - if (ghoul2.size() > modelIndex) - { - //model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - //return mod->mdxm->animName; +char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) { + if (G2_SetupModelPointers(ghoul2)) { + if (ghoul2.size() > modelIndex) { + // model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + // return mod->mdxm->animName; assert(ghoul2[modelIndex].currentModel && ghoul2[modelIndex].currentModel->mdxm); return ghoul2[modelIndex].currentModel->mdxm->animName; @@ -2383,27 +2005,19 @@ char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) return NULL; } -qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) -{ +qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { - if (boltIndex < 0) - { - char modelName[MAX_QPATH]; - if (ghlInfo->currentModel && - ghlInfo->currentModel->name[0]) - { + if (G2_SetupModelPointers(ghlInfo)) { + if (boltIndex < 0) { + char modelName[MAX_QPATH]; + if (ghlInfo->currentModel && ghlInfo->currentModel->name[0]) { strcpy(modelName, ghlInfo->currentModel->name); - } - else - { + } else { strcpy(modelName, "None?!"); } @@ -2417,94 +2031,70 @@ qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) return qfalse; } -int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Get_Bone_Index(ghlInfo, boneName); } return -1; } -qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ - return G2_SaveGhoul2Models(ghoul2, buffer, size); -} +qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { return G2_SaveGhoul2Models(ghoul2, buffer, size); } -void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) -{ - G2_LoadGhoul2Model(ghoul2, buffer); -} +void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) { G2_LoadGhoul2Model(ghoul2, buffer); } -void G2API_FreeSaveBuffer(char *buffer) -{ - Z_Free(buffer); -} +void G2API_FreeSaveBuffer(char *buffer) { Z_Free(buffer); } // this is kinda sad, but I need to call the destructor in this module (exe), not the game.dll... // -void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) -{ +void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) { #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif - ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning + ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning } -//see if surfs have any shader info... -qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// see if surfs have any shader info... +qboolean G2API_SkinlessModel(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(g2)) - { - model_t *mod = (model_t *)g2->currentModel; + if (G2_SetupModelPointers(g2)) { + model_t *mod = (model_t *)g2->currentModel; - if (mod && - mod->mdxm) - { - mdxmSurfHierarchy_t *surf; + if (mod && mod->mdxm) { + mdxmSurfHierarchy_t *surf; int i; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy); - for (i = 0; i < mod->mdxm->numSurfaces; i++) - { - if (surf->shader[0]) - { //found a surface with a shader name, ok. - return qfalse; + for (i = 0; i < mod->mdxm->numSurfaces; i++) { + if (surf->shader[0]) { // found a surface with a shader name, ok. + return qfalse; } - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } } } - //found nothing. + // found nothing. return qtrue; } -int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) -{ - return ghoul2.size(); -} +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) { return ghoul2.size(); } //#ifdef _SOF2 #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling -//way of seeing how many marks are on a model currently -rww -int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// way of seeing how many marks are on a model currently -rww +int G2API_GetNumGoreMarks(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (g2->mGoreSetTag) - { + if (g2->mGoreSetTag) { CGoreSet *goreSet = FindGoreSet(g2->mGoreSetTag); - if (goreSet) - { + if (goreSet) { return goreSet->mGoreRecords.size(); } } @@ -2512,117 +2102,98 @@ int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) return 0; } -void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) -{ +void G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { int i; - for (i=0; inumLods,3); //limit to the number of lods the main model has - for(lod=lodbias;lodnumLods, 3); // limit to the number of lods the main model has + for (lod = lodbias; lod < maxLod; lod++) { // now having done that, time to build the model ri.GetG2VertSpaceServer()->ResetHeap(); - G2_TransformModel(ghoul2, gore.currentTime, gore.scale,ri.GetG2VertSpaceServer(),lod,true); + G2_TransformModel(ghoul2, gore.currentTime, gore.scale, ri.GetG2VertSpaceServer(), lod, true); // now walk each model and compute new texture coordinates - G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0,lod,0.0f,gore.SSize,gore.TSize,gore.theta,gore.shader,&gore,qtrue); + G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0, lod, 0.0f, gore.SSize, gore.TSize, gore.theta, gore.shader, &gore, + qtrue); } } #endif qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up { - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } - ghlInfo->mValid=false; - if (ghlInfo->mModelindex != -1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + ghlInfo->mValid = false; + if (ghlInfo->mModelindex != -1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); - if (ghlInfo->currentModel) - { - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + if (ghlInfo->currentModel) { + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } return (qboolean)ghlInfo->mValid; } @@ -2638,91 +2209,75 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_SetupModelPointers.Start(); #endif - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } -// if (ghlInfo->mValid && ghlInfo->currentModel) - if (0) - { //rww - Why are we bothering with all this? We can't change models like this anyway. - //This function goes over 200k on the precision timer (in debug, but still), so I'm - //cutting it off here because it gets called constantly. + // if (ghlInfo->mValid && ghlInfo->currentModel) + if (0) { // rww - Why are we bothering with all this? We can't change models like this anyway. + // This function goes over 200k on the precision timer (in debug, but still), so I'm + // cutting it off here because it gets called constantly. #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_SetupModelPointers += G2PerformanceTimer_G2_SetupModelPointers.End(); #endif return qtrue; } - ghlInfo->mValid=false; + ghlInfo->mValid = false; -// G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); - if (ghlInfo->mModelindex != -1) - { - G2ERROR(ghlInfo->mFileName[0],"empty ghlInfo->mFileName"); + // G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); + if (ghlInfo->mModelindex != -1) { + G2ERROR(ghlInfo->mFileName[0], "empty ghlInfo->mFileName"); // RJ - experimental optimization! - if (!ghlInfo->mModel || 1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + if (!ghlInfo->mModel || 1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); } - G2ERROR(ghlInfo->currentModel,va("NULL Model (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel) - { - G2ERROR(ghlInfo->currentModel->mdxm,va("Model has no mdxm (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + G2ERROR(ghlInfo->currentModel, va("NULL Model (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel) { + G2ERROR(ghlInfo->currentModel->mdxm, va("Model has no mdxm (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; - G2ERROR(ghlInfo->currentModelSize,va("Zero sized Model? (glm) %s",ghlInfo->mFileName)); + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; + G2ERROR(ghlInfo->currentModelSize, va("Zero sized Model? (glm) %s", ghlInfo->mFileName)); ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex); - G2ERROR(ghlInfo->animModel,va("NULL Model (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + G2ERROR(ghlInfo->animModel, va("NULL Model (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + G2ERROR(ghlInfo->aHeader, va("Model has no mdxa (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - G2ERROR(ghlInfo->currentAnimModelSize,va("Zero sized Model? (gla) %s",ghlInfo->mFileName)); - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + G2ERROR(ghlInfo->currentAnimModelSize, va("Zero sized Model? (gla) %s", ghlInfo->mFileName)); + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } #ifdef G2_PERFORMANCE_ANALYSIS @@ -2733,22 +2288,15 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2) // returns true if any model is properly set up { - bool ret=false; + bool ret = false; int i; - for (i=0; i. // Bolt List handling routines - so entities can attach themselves to any part of the model in question // Given a bone number, see if that bone is already in our bone list -int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) -{ +int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) { // look through entire list - for(size_t i=0; imValid); - boltInfo_t tempBolt; + boltInfo_t tempBolt; // first up, make sure have a surface first - if (surfNum >= (int)slist.size()) - { + if (surfNum >= (int)slist.size()) { return -1; } - // look through entire list - see if it's already there first - for(size_t i=0; imValid); - model_t *mod_m = (model_t *)ghlInfo->currentModel; - model_t *mod_a = (model_t *)ghlInfo->animModel; - int x, surfNum = -1; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boltInfo_t tempBolt; - int flags; + model_t *mod_m = (model_t *)ghlInfo->currentModel; + model_t *mod_a = (model_t *)ghlInfo->animModel; + int x, surfNum = -1; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boltInfo_t tempBolt; + int flags; // first up, we'll search for that which this bolt names in all the surfaces - surfNum = G2_IsSurfaceLegal((void*)mod_m, boneName, &flags); + surfNum = G2_IsSurfaceLegal((void *)mod_m, boneName, &flags); // did we find it as a surface? - if (surfNum != -1) - { - // look through entire list - see if it's already there first - for(size_t i=0; imdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mod_a->mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mod_a->mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mod_a->mdxa->numBones) - { + if (x == mod_a->mdxa->numBones) { // didn't find it? Error - //assert(0&&x == mod_a->mdxa->numBones); + // assert(0&&x == mod_a->mdxa->numBones); #ifdef _DEBUG // Com_Printf("WARNING: %s not found on skeleton\n", boneName); #endif @@ -200,11 +176,9 @@ int G2_Add_Bolt(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, } // look through entire list - see if it's already there first - for(size_t i=0; i-1; i--) - { - if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) - { + for (int i = bltlist.size() - 1; i > -1; i--) { + if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != bltlist.size()) - { + if (newSize != bltlist.size()) { // yes, so lets do it bltlist.resize(newSize); } - } return qtrue; } @@ -280,29 +243,20 @@ qboolean G2_Remove_Bolt (boltInfo_v &bltlist, int index) } // set the bolt list to all unused so the bone transformation routine ignores it. -void G2_Init_Bolt_List(boltInfo_v &bltlist) -{ - bltlist.clear(); -} +void G2_Init_Bolt_List(boltInfo_v &bltlist) { bltlist.clear(); } // remove any bolts that reference original surfaces, generated surfaces, or bones that aren't active anymore -void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) -{ +void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) { // walk the bolt list - for (size_t i=0; i. #include "tr_local.h" -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifndef __linux__ #include #else @@ -38,26 +38,23 @@ along with this program; if not, see . //#define RAG_TRACE_DEBUG_LINES #include "client/client.h" //while this is all "shared" code, there are some places where we want to make cgame callbacks (for ragdoll) only if the cgvm exists -//rww - RAGDOLL_END +// rww - RAGDOLL_END //===================================================================================================================== // Bone List handling routines - so entities can override bone info on a bone by bone level, and also interrogate this info // Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the // gla file, not the glm file type. -int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); +int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; imdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -76,35 +72,31 @@ int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) } // we need to add a bone to the list - find a free one and see if we can find a corresponding bone in the gla file -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) -{ +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { int x; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boneInfo_t tempBone; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boneInfo_t tempBone; - //rww - RAGDOLL_BEGIN + // rww - RAGDOLL_BEGIN memset(&tempBone, 0, sizeof(tempBone)); - //rww - RAGDOLL_END + // rww - RAGDOLL_END - offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mod->mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mod->mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mod->mdxa->numBones) - { + if (x == mod->mdxa->numBones) { // didn't find it? Error - //assert(0); + // assert(0); #ifdef _DEBUG Com_Printf("WARNING: Failed to add bone %s\n", boneName); #endif @@ -116,24 +108,19 @@ int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) } // look through entire list - see if it's already there first - for(size_t i=0; imdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } - } - else - { + } else { // if we found an entry that had a -1 for the bonenumber, then we hit a bone slot that was empty blist[i].boneNumber = x; blist[i].flags = 0; - return i; + return i; } } @@ -144,48 +131,38 @@ int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) tempBone.boneNumber = x; tempBone.flags = 0; blist.push_back(tempBone); - return blist.size()-1; + return blist.size() - 1; } - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) -{ - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { +qboolean G2_Remove_Bone_Index(boneInfo_v &blist, int index) { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // check the flags first - if it's still being used Do NOT remove it - if (!blist[index].flags) - { + if (!blist[index].flags) { // set this bone to not used blist[index].boneNumber = -1; - unsigned int newSize = blist.size(); + unsigned int newSize = blist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=blist.size()-1; i>-1; i--) - { - if (blist[i].boneNumber == -1) - { + for (int i = blist.size() - 1; i > -1; i--) { + if (blist[i].boneNumber == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != blist.size()) - { + if (newSize != blist.size()) { // yes, so lets do it blist.resize(newSize); } @@ -194,19 +171,16 @@ qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) } } -// assert(0); + // assert(0); // no return qfalse; } // given a bone number, see if there is an override bone in the bone list -int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) -{ +int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) { // look through entire list - for(size_t i=0; imdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[index].boneNumber]); - Multiply_3x4Matrix(&temp1, boneOverride,&skel->BasePoseMatInv); - Multiply_3x4Matrix(boneOverride,&skel->BasePoseMat, &temp1); + Multiply_3x4Matrix(&temp1, boneOverride, &skel->BasePoseMatInv); + Multiply_3x4Matrix(boneOverride, &skel->BasePoseMat, &temp1); - } - else - { + } else { VectorCopy(angles, newAngles); // why I should need do this Fuck alone knows. But I do. - if (left == POSITIVE_Y) - { - newAngles[0] +=180; + if (left == POSITIVE_Y) { + newAngles[0] += 180; } Create_Matrix(newAngles, &temp1); @@ -347,13 +311,12 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[2][0] = permutation.matrix[2][1] = permutation.matrix[2][2] = permutation.matrix[2][3] = 0; // determine what axis newAngles Yaw should revolve around - switch (forward) - { + switch (forward) { case NEGATIVE_X: - permutation.matrix[0][0] = -1; // works + permutation.matrix[0][0] = -1; // works break; case POSITIVE_X: - permutation.matrix[0][0] = 1; // works + permutation.matrix[0][0] = 1; // works break; case NEGATIVE_Y: permutation.matrix[1][0] = -1; @@ -372,8 +335,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles pitch should revolve around - switch (left) - { + switch (left) { case NEGATIVE_X: permutation.matrix[0][1] = -1; break; @@ -381,10 +343,10 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[0][1] = 1; break; case NEGATIVE_Y: - permutation.matrix[1][1] = -1; // works + permutation.matrix[1][1] = -1; // works break; case POSITIVE_Y: - permutation.matrix[1][1] = 1; // works + permutation.matrix[1][1] = 1; // works break; case NEGATIVE_Z: permutation.matrix[2][1] = -1; @@ -397,8 +359,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles Roll should revolve around - switch (up) - { + switch (up) { case NEGATIVE_X: permutation.matrix[0][2] = -1; break; @@ -412,31 +373,27 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[1][2] = 1; break; case NEGATIVE_Z: - permutation.matrix[2][2] = -1; // works + permutation.matrix[2][2] = -1; // works break; case POSITIVE_Z: - permutation.matrix[2][2] = 1; // works + permutation.matrix[2][2] = 1; // works break; default: break; } - Multiply_3x4Matrix(boneOverride, &temp1,&permutation); - + Multiply_3x4Matrix(boneOverride, &temp1, &permutation); } // keep a copy of the matrix in the newmatrix which is actually what we use memcpy(&blist[index].newMatrix, &blist[index].matrix, sizeof(mdxaBone_t)); - } //========================================================================================= //// Public Bone Routines - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ +qboolean G2_Remove_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { int index; assert(ghlInfo->animModel); @@ -447,30 +404,22 @@ qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *bo #define DEBUG_PCJ (0) - // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles_Index( boneInfo_v &blist, const int index, - const float *angles, const int flags, const Eorientations yaw, - const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, - const int modelIndex, const int blendTime, const int currentTime) -{ - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { +qboolean G2_Set_Bone_Angles_Index(boneInfo_v &blist, const int index, const float *angles, const int flags, const Eorientations yaw, const Eorientations pitch, + const Eorientations roll, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } - if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) - { + if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) { // you CANNOT call this with an index with these kinds of bone overrides - we need the model details for these kinds of bone angle overrides assert(0); return qfalse; @@ -482,30 +431,26 @@ qboolean G2_Set_Bone_Angles_Index( boneInfo_v &blist, const int index, blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - OutputDebugString(va("PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],yaw,pitch,roll,flags)); + OutputDebugString(va("PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], yaw, pitch, roll, flags)); #endif G2_Generate_Matrix(NULL, blist, index, angles, flags, yaw, pitch, roll); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, - const int flags, const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_a; +qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, const int modelIndex, const int blendTime, + const int currentTime) { + model_t *mod_a; mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } @@ -515,7 +460,7 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - OutputDebugString(va("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags)); + OutputDebugString(va("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags)); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); @@ -526,43 +471,37 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - OutputDebugString(va("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags)); + OutputDebugString(va("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags)); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); return qtrue; } -// assert(0); - //Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. + // assert(0); + // Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. // no return qfalse; } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, - const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, - const int modelIndex, const int blendTime, const int currentTime) -{ +qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + const int modelIndex, const int blendTime, const int currentTime) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } @@ -575,36 +514,28 @@ qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_m; - if (!fileName[0]) - { +qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, const int flags, + qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + model_t *mod_m; + if (!fileName[0]) { mod_m = R_GetModelByHandle(modelList[modelIndex]); - } - else - { + } else { mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); } - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -618,8 +549,7 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -636,108 +566,76 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons #define DEBUG_G2_TIMING (0) -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim_Index( - boneInfo_v &blist, - const int index, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime, - const int numFrames) -{ - int modFlags = flags; +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int currentTime, const float setFrame, const int blendTime, const int numFrames) { + int modFlags = flags; - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } - //mark it for needing a transform for the cached trace transform stuff + // mark it for needing a transform for the cached trace transform stuff blist[index].flags |= BONE_NEED_TRANSFORM; } - if (setFrame != -1) - { + if (setFrame != -1) { assert((setFrame >= startFrame) && (setFrame <= endFrame)); } - if (flags & BONE_ANIM_BLEND) - { - float currentFrame, animSpeed; - int startFrame, endFrame, flags; + if (flags & BONE_ANIM_BLEND) { + float currentFrame, animSpeed; + int startFrame, endFrame, flags; // figure out where we are now - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) - { - if (blist[index].blendStart == currentTime) //we're replacing a blend in progress which hasn't started + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) { + if (blist[index].blendStart == currentTime) // we're replacing a blend in progress which hasn't started { // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; - } - else - { - if (animSpeed<0.0f) - { + } else { + if (animSpeed < 0.0f) { blist[index].blendFrame = floor(currentFrame); blist[index].blendLerpFrame = floor(currentFrame); - } - else - { + } else { blist[index].blendFrame = currentFrame; - blist[index].blendLerpFrame = currentFrame+1; + blist[index].blendLerpFrame = currentFrame + 1; // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendFrame >= endFrame ) - { + if (blist[index].blendFrame >= endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { - blist[index].blendFrame = endFrame -1; + } else { + blist[index].blendFrame = endFrame - 1; } } } // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendLerpFrame >= endFrame ) - { + if (blist[index].blendLerpFrame >= endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendLerpFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { + } else { blist[index].blendLerpFrame = endFrame - 1; } } @@ -746,19 +644,15 @@ qboolean G2_Set_Bone_Anim_Index( // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; blist[index].blendStart = currentTime; - } } // hmm, we weren't animating on this bone. In which case disable the blend - else - { + else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = 0; modFlags &= ~(BONE_ANIM_BLEND); } - } - else - { + } else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = blist[index].blendStart = 0; // we aren't blending, so remove the option to do so @@ -770,108 +664,66 @@ qboolean G2_Set_Bone_Anim_Index( blist[index].animSpeed = animSpeed; blist[index].pauseTime = 0; // start up the animation:) - if (setFrame != -1) - { - blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); - } - else - { + if (setFrame != -1) { + blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0) / animSpeed)); + } else { blist[index].lastTime = blist[index].startTime = currentTime; } blist[index].flags &= ~(BONE_ANIM_TOTAL); - if (blist[index].flags < 0) - { + if (blist[index].flags < 0) { blist[index].flags = 0; } blist[index].flags |= modFlags; #if DEBUG_G2_TIMING - if (index==2) - { - const boneInfo_t &bone=blist[index]; + if (index == 2) { + const boneInfo_t &bone = blist[index]; char mess[1000]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess,"sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); - } - else - { - sprintf(mess,"saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, "sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", index, currentTime, bone.startTime, bone.startFrame, + bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, "saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", index, currentTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, + bone.flags); } OutputDebugString(mess); } #endif return qtrue; - } -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, - boneInfo_v &blist, - const char *boneName, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - if (index == -1) - { + int index = G2_Find_Bone(mod_a, blist, boneName); + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } - if (index != -1) - { - return G2_Set_Bone_Anim_Index(blist,index,startFrame,endFrame,flags,animSpeed,currentTime,setFrame,blendTime,ghlInfo->aHeader->numFrames); + if (index != -1) { + return G2_Set_Bone_Anim_Index(blist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); } return qfalse; } -qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) { + model_t *mod_a = (model_t *)ghlInfo->animModel; + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; return qtrue; @@ -882,24 +734,21 @@ qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const c // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp); -qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int numFrames) -{ +qboolean G2_Get_Bone_Anim_Index(boneInfo_v &blist, const int index, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *retAnimSpeed, qhandle_t *modelList, int numFrames) { // did we find it? - if ((index>=0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) - { + if ((index >= 0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - int lcurrentFrame,newFrame; + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + int lcurrentFrame, newFrame; float lerp; - G2_TimingModel(blist[index],currentTime,numFrames,lcurrentFrame,newFrame,lerp); + G2_TimingModel(blist[index], currentTime, numFrames, lcurrentFrame, newFrame, lerp); - *currentFrame =float(lcurrentFrame)+lerp; + *currentFrame = float(lcurrentFrame) + lerp; *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; *flags = blist[index].flags; @@ -907,40 +756,36 @@ qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int c return qtrue; } } - *startFrame=0; - *endFrame=1; - *currentFrame=0.0f; - *flags=0; - *retAnimSpeed=0.0f; + *startFrame = 0; + *endFrame = 1; + *currentFrame = 0.0f; + *flags = 0; + *retAnimSpeed = 0.0f; return qfalse; } // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); - if (index==-1) - { + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); - if (index == -1) - { + if (index == -1) { return qfalse; } } assert(ghlInfo->aHeader); - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) - { - assert(*startFrame>=0&&*startFrameaHeader->numFrames); - assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); - assert(*currentFrame>=0.0f&&((int)(*currentFrame))aHeader->numFrames); + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) { + assert(*startFrame >= 0 && *startFrame < ghlInfo->aHeader->numFrames); + assert(*endFrame > 0 && *endFrame <= ghlInfo->aHeader->numFrames); + assert(*currentFrame >= 0.0f && ((int)(*currentFrame)) < ghlInfo->aHeader->numFrames); return qtrue; } @@ -948,20 +793,17 @@ qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *b } // given a model, bonelist and bonename, lets pause an anim if it's playing. -qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we pausing or un pausing? - if (blist[index].pauseTime) - { - int startFrame = 0, endFrame = 0, flags = 0; - float currentFrame = 0.0f, animSpeed = 1.0f; + if (blist[index].pauseTime) { + int startFrame = 0, endFrame = 0, flags = 0; + float currentFrame = 0.0f, animSpeed = 1.0f; // figure out what frame we are on now G2_Get_Bone_Anim(ghlInfo, blist, boneName, blist[index].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, 0); @@ -971,8 +813,7 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].pauseTime = 0; } // ahh, just pausing, the easy bit - else - { + else { blist[index].pauseTime = currentTime; } @@ -983,18 +824,15 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char return qfalse; } -qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we paused? - if (blist[index].pauseTime) - { + if (blist[index].pauseTime) { // yup. paused. return qtrue; } @@ -1005,11 +843,9 @@ qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneNa } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -1021,15 +857,13 @@ qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANIM_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1040,11 +874,9 @@ qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char * } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -1053,19 +885,16 @@ qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); - } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1075,76 +904,56 @@ qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char return qfalse; } - // actually walk the bone list and update each and every bone if we have ended an animation for them. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index ) -{ +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index) { boneInfo_v &blist = ghoul2[index].mBlist; // look through entire list - for(size_t i=0; i 0.0f) && (newFrame_g > endFrame-1 )) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1 ))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { - if (newFrame_g <= endFrame+1) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + if (animSpeed < 0.0f) { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } - } - else - { - if (newFrame_g >= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } } // figure out new start time - float frameTime = newFrame_g - blist[i].startFrame ; + float frameTime = newFrame_g - blist[i].startFrame; blist[i].startTime = currentTime - (int)((frameTime / animSpeed) * 50.0f); - if (blist[i].startTime>currentTime) - { - blist[i].startTime=currentTime; + if (blist[i].startTime > currentTime) { + blist[i].startTime = currentTime; } assert(blist[i].startTime <= currentTime); blist[i].lastTime = blist[i].startTime; - } - else - { - if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) - { + } else { + if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) { // nope, just stop it. And remove the bone if possible G2_Stop_Bone_Index(blist, i, (BONE_ANIM_TOTAL)); } @@ -1156,136 +965,127 @@ void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const in } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN /* rag stuff */ -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool LimitAngles,CRagDollUpdateParams *params = NULL); -static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale); -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V,const vec3_t currentOrg,CRagDollUpdateParams *params, int curTime); -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered); - -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum); +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool LimitAngles, + CRagDollUpdateParams *params = NULL); +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V, int g2Index, int frameNum, const vec3_t angles, const vec3_t position, const vec3_t scale); +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime); +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered); + +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv); +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum); #define MAX_BONES_RAG (256) -struct SRagEffector -{ - vec3_t currentOrigin; - vec3_t desiredDirection; - vec3_t desiredOrigin; - float radius; - float weight; +struct SRagEffector { + vec3_t currentOrigin; + vec3_t desiredDirection; + vec3_t desiredOrigin; + float radius; + float weight; }; -#define RAG_MASK (CONTENTS_SOLID|CONTENTS_TERRAIN)//|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) +#define RAG_MASK \ + (CONTENTS_SOLID | \ + CONTENTS_TERRAIN) //|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) -extern cvar_t *broadsword; -extern cvar_t *broadsword_kickbones; -extern cvar_t *broadsword_kickorigin; -extern cvar_t *broadsword_dontstopanim; -extern cvar_t *broadsword_waitforshot; -extern cvar_t *broadsword_playflop; +extern cvar_t *broadsword; +extern cvar_t *broadsword_kickbones; +extern cvar_t *broadsword_kickorigin; +extern cvar_t *broadsword_dontstopanim; +extern cvar_t *broadsword_waitforshot; +extern cvar_t *broadsword_playflop; -extern cvar_t *broadsword_effcorr; +extern cvar_t *broadsword_effcorr; -extern cvar_t *broadsword_ragtobase; +extern cvar_t *broadsword_ragtobase; -extern cvar_t *broadsword_dircap; +extern cvar_t *broadsword_dircap; -extern cvar_t *broadsword_extra1; -extern cvar_t *broadsword_extra2; +extern cvar_t *broadsword_extra1; +extern cvar_t *broadsword_extra2; -#define RAG_PCJ (0x00001) -#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well -#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well -#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well -#define RAG_EFFECTOR (0x00100) -#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint -#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint -#define RAG_BONE_LIGHTWEIGHT (0x04000) //used to indicate a bone's velocity treatment -#define RAG_PCJ_IK_CONTROLLED (0x08000) //controlled from IK move input -#define RAG_UNSNAPPABLE (0x10000) //cannot be broken out of constraints ever +#define RAG_PCJ (0x00001) +#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well +#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well +#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well +#define RAG_EFFECTOR (0x00100) +#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint +#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint +#define RAG_BONE_LIGHTWEIGHT (0x04000) // used to indicate a bone's velocity treatment +#define RAG_PCJ_IK_CONTROLLED (0x08000) // controlled from IK move input +#define RAG_UNSNAPPABLE (0x10000) // cannot be broken out of constraints ever // thiese flags are on the model and correspond to... //#define GHOUL2_RESERVED_FOR_RAGDOLL 0x0ff0 // these are not defined here for dependecies sake -#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll -#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim -#define GHOUL2_RAG_DONE 0x0200 // got end death anim -#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event -#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll +#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim +#define GHOUL2_RAG_DONE 0x0200 // got end death anim +#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event +#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled //#define flrand Q_flrand -static mdxaBone_t* ragBasepose[MAX_BONES_RAG]; -static mdxaBone_t* ragBaseposeInv[MAX_BONES_RAG]; -static mdxaBone_t ragBones[MAX_BONES_RAG]; -static SRagEffector ragEffectors[MAX_BONES_RAG]; -static boneInfo_t *ragBoneData[MAX_BONES_RAG]; -static int tempDependents[MAX_BONES_RAG]; -static int ragBlistIndex[MAX_BONES_RAG]; -static int numRags; -static vec3_t ragBoneMins; -static vec3_t ragBoneMaxs; -static vec3_t ragBoneCM; -static bool haveDesiredPelvisOffset=false; -static vec3_t desiredPelvisOffset; // this is for the root -static float ragOriginChange=0.0f; -static vec3_t ragOriginChangeDir; -//debug +static mdxaBone_t *ragBasepose[MAX_BONES_RAG]; +static mdxaBone_t *ragBaseposeInv[MAX_BONES_RAG]; +static mdxaBone_t ragBones[MAX_BONES_RAG]; +static SRagEffector ragEffectors[MAX_BONES_RAG]; +static boneInfo_t *ragBoneData[MAX_BONES_RAG]; +static int tempDependents[MAX_BONES_RAG]; +static int ragBlistIndex[MAX_BONES_RAG]; +static int numRags; +static vec3_t ragBoneMins; +static vec3_t ragBoneMaxs; +static vec3_t ragBoneCM; +static bool haveDesiredPelvisOffset = false; +static vec3_t desiredPelvisOffset; // this is for the root +static float ragOriginChange = 0.0f; +static vec3_t ragOriginChangeDir; +// debug #if 0 static vec3_t handPos={0,0,0}; static vec3_t handPos2={0,0,0}; #endif -enum ERagState -{ - ERS_DYNAMIC, - ERS_SETTLING, - ERS_SETTLED -}; -static int ragState; - -static std::vector rag; // once we get the dependents precomputed this can be local +enum ERagState { ERS_DYNAMIC, ERS_SETTLING, ERS_SETTLED }; +static int ragState; +static std::vector rag; // once we get the dependents precomputed this can be local static void G2_Generate_MatrixRag( - // caution this must not be called before the whole skeleton is "remembered" - boneInfo_v &blist, - int index) -{ - + // caution this must not be called before the whole skeleton is "remembered" + boneInfo_v &blist, int index) { - boneInfo_t &bone=blist[index];//.sent; + boneInfo_t &bone = blist[index]; //.sent; - memcpy(&bone.matrix,&bone.ragOverrideMatrix, sizeof(mdxaBone_t)); + memcpy(&bone.matrix, &bone.ragOverrideMatrix, sizeof(mdxaBone_t)); #ifdef _DEBUG - int i,j; - for (i = 0; i < 3; i++ ) - { - for (j = 0; j < 4; j++ ) - { - assert( !Q_isnan(bone.matrix.matrix[i][j])); + int i, j; + for (i = 0; i < 3; i++) { + for (j = 0; j < 4; j++) { + assert(!Q_isnan(bone.matrix.matrix[i][j])); } } -#endif// _DEBUG - memcpy(&blist[index].newMatrix,&bone.matrix, sizeof(mdxaBone_t)); +#endif // _DEBUG + memcpy(&blist[index].newMatrix, &bone.matrix, sizeof(mdxaBone_t)); } -int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); /* @@ -1300,26 +1100,23 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa aHeader = animModel->mdxa; assert(aHeader); - offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); */ // look through entire list - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); - //skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + // skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -1330,82 +1127,57 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa return -1; } -static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - CGhoul2Info &ghoul2, - const vec3_t scale, - const vec3_t origin) -{ +static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, CGhoul2Info &ghoul2, const vec3_t scale, const vec3_t origin) { // do not change the state of the skeleton here - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; - VectorCopy(origin,bone.extraVec1); + if (index != -1) { + boneInfo_t &bone = blist[index]; + VectorCopy(origin, bone.extraVec1); - G2_GetBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.originalTrueBoneMatrix,bone.basepose,bone.baseposeInv); -// bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); - bone.originalOrigin[0]=bone.originalTrueBoneMatrix.matrix[0][3]; - bone.originalOrigin[1]=bone.originalTrueBoneMatrix.matrix[1][3]; - bone.originalOrigin[2]=bone.originalTrueBoneMatrix.matrix[2][3]; + G2_GetBoneMatrixLow(ghoul2, bone.boneNumber, scale, bone.originalTrueBoneMatrix, bone.basepose, bone.baseposeInv); + // bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); + bone.originalOrigin[0] = bone.originalTrueBoneMatrix.matrix[0][3]; + bone.originalOrigin[1] = bone.originalTrueBoneMatrix.matrix[1][3]; + bone.originalOrigin[2] = bone.originalTrueBoneMatrix.matrix[2][3]; } return index; } -static int G2_Set_Bone_Angles_Rag( - CGhoul2Info &ghoul2, - const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - const int flags, - const float radius, - const vec3_t angleMin=0, - const vec3_t angleMax=0, - const int blendTime=500) -{ - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); +static int G2_Set_Bone_Angles_Rag(CGhoul2Info &ghoul2, const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, const int flags, const float radius, + const vec3_t angleMin = 0, const vec3_t angleMax = 0, const int blendTime = 500) { + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; + if (index != -1) { + boneInfo_t &bone = blist[index]; bone.flags &= ~(BONE_ANGLES_TOTAL); bone.flags |= BONE_ANGLES_RAGDOLL; - if (flags&RAG_PCJ) - { - if (flags&RAG_PCJ_POST_MULT) - { + if (flags & RAG_PCJ) { + if (flags & RAG_PCJ_POST_MULT) { bone.flags |= BONE_ANGLES_POSTMULT; - } - else if (flags&RAG_PCJ_MODEL_ROOT) - { + } else if (flags & RAG_PCJ_MODEL_ROOT) { bone.flags |= BONE_ANGLES_PREMULT; -// bone.flags |= BONE_ANGLES_POSTMULT; - } - else - { + // bone.flags |= BONE_ANGLES_POSTMULT; + } else { assert(!"Invalid RAG PCJ\n"); } } - bone.ragStartTime=G2API_GetTime(0); + bone.ragStartTime = G2API_GetTime(0); bone.boneBlendStart = bone.ragStartTime; bone.boneBlendTime = blendTime; - bone.radius=radius; - bone.weight=1.0f; + bone.radius = radius; + bone.weight = 1.0f; - //init the others to valid values + // init the others to valid values bone.epGravFactor = 0; VectorClear(bone.epVelocity); bone.solidCount = 0; @@ -1421,48 +1193,37 @@ static int G2_Set_Bone_Angles_Rag( bone.hasOverGoal = false; bone.hasAnimFrameMatrix = -1; -// bone.weight=pow(radius,1.7f); //cubed was too harsh -// bone.weight=radius*radius*radius; - if (angleMin&&angleMax) - { - VectorCopy(angleMin,bone.minAngles); - VectorCopy(angleMax,bone.maxAngles); - } - else - { - VectorCopy(bone.currentAngles,bone.minAngles); // I guess this isn't a rag pcj then - VectorCopy(bone.currentAngles,bone.maxAngles); - } - if (!bone.lastTimeUpdated) - { - static mdxaBone_t id = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - memcpy(&bone.ragOverrideMatrix,&id, sizeof(mdxaBone_t)); + // bone.weight=pow(radius,1.7f); //cubed was too harsh + // bone.weight=radius*radius*radius; + if (angleMin && angleMax) { + VectorCopy(angleMin, bone.minAngles); + VectorCopy(angleMax, bone.maxAngles); + } else { + VectorCopy(bone.currentAngles, bone.minAngles); // I guess this isn't a rag pcj then + VectorCopy(bone.currentAngles, bone.maxAngles); + } + if (!bone.lastTimeUpdated) { + static mdxaBone_t id = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + memcpy(&bone.ragOverrideMatrix, &id, sizeof(mdxaBone_t)); VectorClear(bone.anglesOffset); VectorClear(bone.positionOffset); - VectorClear(bone.velocityEffector); // this is actually a velocity now - VectorClear(bone.velocityRoot); // this is actually a velocity now + VectorClear(bone.velocityEffector); // this is actually a velocity now + VectorClear(bone.velocityRoot); // this is actually a velocity now VectorClear(bone.lastPosition); VectorClear(bone.lastShotDir); - bone.lastContents=0; + bone.lastContents = 0; // if this is non-zero, we are in a dynamic state - bone.firstCollisionTime=bone.ragStartTime; + bone.firstCollisionTime = bone.ragStartTime; // if this is non-zero, we are in a settling state - bone.restTime=0; + bone.restTime = 0; // if they are both zero, we are in a settled state - bone.firstTime=0; + bone.firstTime = 0; - bone.RagFlags=flags; - bone.DependentRagIndexMask=0; + bone.RagFlags = flags; + bone.DependentRagIndexMask = 0; - G2_Generate_MatrixRag(blist,index); // set everything to th id + G2_Generate_MatrixRag(blist, index); // set everything to th id #if 0 VectorClear(bone.currentAngles); @@ -1470,32 +1231,25 @@ static int G2_Set_Bone_Angles_Rag( // VectorScale(bone.currentAngles,0.5f,bone.currentAngles); #else { - if ( - (flags&RAG_PCJ_MODEL_ROOT) || - (flags&RAG_PCJ_PELVIS) || - !(flags&RAG_PCJ)) - { + if ((flags & RAG_PCJ_MODEL_ROOT) || (flags & RAG_PCJ_PELVIS) || !(flags & RAG_PCJ)) { VectorClear(bone.currentAngles); - } - else - { + } else { int k; - for (k=0;k<3;k++) - { - float scalar=flrand(-1.0f,1.0f); - scalar*=flrand(-1.0f,1.0f)*flrand(-1.0f,1.0f); + for (k = 0; k < 3; k++) { + float scalar = flrand(-1.0f, 1.0f); + scalar *= flrand(-1.0f, 1.0f) * flrand(-1.0f, 1.0f); // this is a heavily central distribution // center it on .5 (and make it small) - scalar*=0.5f; - scalar+=0.5f; + scalar *= 0.5f; + scalar += 0.5f; - bone.currentAngles[k]=(bone.minAngles[k]-bone.maxAngles[k])*scalar+bone.maxAngles[k]; + bone.currentAngles[k] = (bone.minAngles[k] - bone.maxAngles[k]) * scalar + bone.maxAngles[k]; } } } // VectorClear(bone.currentAngles); #endif - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); } } return index; @@ -1504,50 +1258,43 @@ static int G2_Set_Bone_Angles_Rag( class CRagDollParams; const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2); - -static void G2_RagDollMatchPosition() -{ - haveDesiredPelvisOffset=false; +static void G2_RagDollMatchPosition() { + haveDesiredPelvisOffset = false; int i; - for (i=0;inumBones); -#else //The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list - //and let them re-set their anims/angles gameside. +#else // The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list + // and let them re-set their anims/angles gameside. int i = 0; - while (i < blist.size()) - { + while (i < blist.size()) { boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) - { + if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -1633,41 +1372,33 @@ void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V) i++; } #endif - ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED); + ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED); } -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) -{ - if (parms) - { - parms->CallRagDollBegin=qfalse; +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms) { + if (parms) { + parms->CallRagDollBegin = qfalse; } - if (!broadsword||!broadsword->integer||!parms) - { + if (!broadsword || !broadsword->integer || !parms) { return; } int model; - for (model = 0; model < ghoul2V.size(); model++) - { - if (ghoul2V[model].mModelindex != -1) - { + for (model = 0; model < ghoul2V.size(); model++) { + if (ghoul2V[model].mModelindex != -1) { break; } } - if (model==ghoul2V.size()) - { + if (model == ghoul2V.size()) { return; } - CGhoul2Info &ghoul2=ghoul2V[model]; - const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); - if (!mod_a) - { + CGhoul2Info &ghoul2 = ghoul2V[model]; + const mdxaHeader_t *mod_a = G2_GetModA(ghoul2); + if (!mod_a) { return; } - int curTime=G2API_GetTime(0); + int curTime = G2API_GetTime(0); boneInfo_v &blist = ghoul2.mBlist; - if (ghoul2.mFlags&GHOUL2_RAG_STARTED) - { + if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { // only going to begin ragdoll once, everything else depends on what happens to the origin return; } @@ -1678,223 +1409,216 @@ if (index>=0) } #endif - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED; // well anyway we are going live - parms->CallRagDollBegin=qtrue; + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED; // well anyway we are going live + parms->CallRagDollBegin = qtrue; G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); - - G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"cranium",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); - - //int startFrame = 3665, endFrame = 3665+1; + G2_Set_Bone_Rag(mod_a, blist, "model_root", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "pelvis", ghoul2, parms->scale, parms->position); + + G2_Set_Bone_Rag(mod_a, blist, "lower_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "upper_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "thoracic", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "cranium", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhand", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhand", ghoul2, parms->scale, parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ceyebrow", ghoul2, parms->scale, parms->position); + + // int startFrame = 3665, endFrame = 3665+1; int startFrame = parms->startFrame, endFrame = parms->endFrame; - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"upper_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lower_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"Motion",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); -// G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, -// BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, -// 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - -// should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "upper_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lower_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "Motion", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + // G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, + // BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + // 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + // should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - static const float fRadScale = 0.3f;//0.5f; + static const float fRadScale = 0.3f; // 0.5f; - vec3_t pcjMin,pcjMax; - VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); - VectorSet(pcjMax,90.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + vec3_t pcjMin, pcjMax; + VectorSet(pcjMin, -90.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 90.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "model_root", RAG_PCJ_MODEL_ROOT | RAG_PCJ | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 100); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "pelvis", RAG_PCJ_PELVIS | RAG_PCJ | RAG_PCJ_POST_MULT | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, + 100); #if 1 // new base anim, unconscious flop - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT; //|RAG_EFFECTOR; - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,15.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); - VectorSet(pcjMax,25.0f,25.0f,25.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -25.0f, -25.0f, -25.0f); + VectorSet(pcjMax, 25.0f, 25.0f, 25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 12.0f * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, 6.0f * fRadScale, pcjMin, pcjMax, 500); static const float sFactLeg = 1.0f; static const float sFactArm = 1.0f; static const float sRadArm = 1.0f; static const float sRadLeg = 1.0f; - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); - VectorSet(pcjMax,15.0f,40.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); + VectorSet(pcjMin, -50.0f, -80.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 40.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,30.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - - VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); - VectorSet(pcjMax,30.0f,5.0f,20.0f); + VectorSet(pcjMin, -80.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 5.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -60.0f, -5.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); #else // old base anim - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,45.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags,10.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,60.0f,45.0f); - VectorSet(pcjMax,180.0f,180.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - //VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,90.0f,100.0f); - VectorSet(pcjMax,180.0f,180.0f,100.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 45.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags, 10.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,60.0f,45.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + // VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,90.0f,100.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 100.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); //-120/120 - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,5.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-90.0f,-50.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //120 - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 5.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -90.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // 120 + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); #endif - float sRadEArm = 1.2f; float sRadELeg = 1.2f; -// int rhand= - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,5.0f); -//match the currrent animation - if (!G2_RagDollSetup(ghoul2,curTime,true,parms->position,false)) - { + // int rhand= + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ceyebrow", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 5.0f); + // match the currrent animation + if (!G2_RagDollSetup(ghoul2, curTime, true, parms->position, false)) { assert(!"failed to add any rag bones"); return; } - G2_RagDollCurrentPosition(ghoul2V,model,curTime,parms->angles,parms->position,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, parms->position, parms->scale); #if 0 if (rhand>0) { @@ -1914,7 +1638,7 @@ if (index>=0) fparms.me = parms->me; fparms.settleFrame = parms->endFrame; - //Guess I don't need to do this, do I? + // Guess I don't need to do this, do I? G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); vec3_t dPos; @@ -1923,50 +1647,41 @@ if (index>=0) dPos[2] -= 6; #endif - for (k=0;kangles,dPos,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, dPos, parms->scale); G2_RagDollMatchPosition(); - G2_RagDollSolve(ghoul2V,model,1.0f*(1.0f-k/40.0f),curTime,dPos,false); + G2_RagDollSolve(ghoul2V, model, 1.0f * (1.0f - k / 40.0f), curTime, dPos, false); } } -void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t hit) -{ - if (!broadsword||!broadsword->integer) - { +void G2_SetRagDollBullet(CGhoul2Info &ghoul2, const vec3_t rayStart, const vec3_t hit) { + if (!broadsword || !broadsword->integer) { return; } vec3_t shotDir; - VectorSubtract(hit,rayStart,shotDir); - float len=VectorLength(shotDir); - if (len<1.0f) - { + VectorSubtract(hit, rayStart, shotDir); + float len = VectorLength(shotDir); + if (len < 1.0f) { return; } - float lenr=1.0f/len; - shotDir[0]*=lenr; - shotDir[1]*=lenr; - shotDir[2]*=lenr; + float lenr = 1.0f / len; + shotDir[0] *= lenr; + shotDir[1] *= lenr; + shotDir[2] *= lenr; - bool firstOne=false; - if (broadsword_kickbones&&broadsword_kickbones->integer) - { + bool firstOne = false; + if (broadsword_kickbones && broadsword_kickbones->integer) { int i; - int magicFactor13=150.0f; // squared radius multiplier for shot effects + int magicFactor13 = 150.0f; // squared radius multiplier for shot effects boneInfo_v &blist = ghoul2.mBlist; - for(i=blist.size()-1;i>=0;i--) - { - boneInfo_t &bone=blist[i]; - if ((bone.flags & BONE_ANGLES_TOTAL)) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (!firstOne) - { - firstOne=true; + for (i = blist.size() - 1; i >= 0; i--) { + boneInfo_t &bone = blist[i]; + if ((bone.flags & BONE_ANGLES_TOTAL)) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (!firstOne) { + firstOne = true; #if 0 int curTime=G2API_GetTime(0); const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); @@ -2009,229 +1724,174 @@ void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t #endif } - VectorCopy(shotDir,bone.lastShotDir); + VectorCopy(shotDir, bone.lastShotDir); vec3_t dir; - VectorSubtract(bone.lastPosition,hit,dir); - len=VectorLength(dir); - if (len<1.0f) - { - len=1.0f; + VectorSubtract(bone.lastPosition, hit, dir); + len = VectorLength(dir); + if (len < 1.0f) { + len = 1.0f; } - lenr=1.0f/len; - float effect=lenr; - effect*=magicFactor13*effect; // this is cubed, one of them is absorbed by the next calc - bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f)); -// bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); - assert( !Q_isnan(shotDir[2])); - // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + lenr = 1.0f / len; + float effect = lenr; + effect *= magicFactor13 * effect; // this is cubed, one of them is absorbed by the next calc + bone.velocityEffector[0] = shotDir[0] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[1] = shotDir[1] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[2] = fabs(shotDir[2]) * (effect + flrand(0.0f, 0.05f)); + // bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + assert(!Q_isnan(shotDir[2])); + // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); // go dynamic - bone.firstCollisionTime=G2API_GetTime(0); -// bone.firstCollisionTime=0; - bone.restTime=0; + bone.firstCollisionTime = G2API_GetTime(0); + // bone.firstCollisionTime=0; + bone.restTime = 0; } } } } } +static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone, int frameNum, const vec3_t origin, bool &resetOrigin) { + ragOriginChange = DistanceSquared(origin, bone.extraVec1); + VectorSubtract(origin, bone.extraVec1, ragOriginChangeDir); -static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone,int frameNum,const vec3_t origin,bool &resetOrigin) -{ - ragOriginChange=DistanceSquared(origin,bone.extraVec1); - VectorSubtract(origin,bone.extraVec1,ragOriginChangeDir); + float decay = 1.0f; - float decay=1.0f; + int dynamicTime = 1000; + int settleTime = 1000; - int dynamicTime=1000; - int settleTime=1000; - - if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; - } - } - } - else if (bone.firstCollisionTime>0) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; + } + } + } else if (bone.firstCollisionTime > 0) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; - } - } -//decay=0.0f; - } - else if (bone.restTime>0) - { - decay=1.0f-(frameNum-bone.restTime)/float(dynamicTime); - if (decay<0.0f) - { - decay=0.0f; - } - if (decay>1.0f) - { - decay=1.0f; - } - float magicFactor8=1.0f; // Power for decay - decay=pow(decay,magicFactor8); - ragState=ERS_SETTLING; - if (frameNum>bone.restTime+settleTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { - bone.restTime=frameNum; - } - else - { + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; + } + } + // decay=0.0f; + } else if (bone.restTime > 0) { + decay = 1.0f - (frameNum - bone.restTime) / float(dynamicTime); + if (decay < 0.0f) { + decay = 0.0f; + } + if (decay > 1.0f) { + decay = 1.0f; + } + float magicFactor8 = 1.0f; // Power for decay + decay = pow(decay, magicFactor8); + ragState = ERS_SETTLING; + if (frameNum > bone.restTime + settleTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { + bone.restTime = frameNum; + } else { // stop - bone.restTime=0; - ragState=ERS_SETTLED; + bone.restTime = 0; + ragState = ERS_SETTLED; } } -//decay=0.0f; - } - else - { - if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else if (ragOriginChange>15.0f) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else - { - ragState=ERS_SETTLED; + // decay=0.0f; + } else { + if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else if (ragOriginChange > 15.0f) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else { + ragState = ERS_SETTLED; } - decay=0.0f; + decay = 0.0f; } -// ragState=ERS_SETTLED; -// decay=0.0f; + // ragState=ERS_SETTLED; + // decay=0.0f; return decay; } -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered) -{ - int minSurvivingBone=10000; - //int minSurvivingBoneAt=-1; - int minSurvivingBoneAlt=10000; - //int minSurvivingBoneAtAlt=-1; +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered) { + int minSurvivingBone = 10000; + // int minSurvivingBoneAt=-1; + int minSurvivingBoneAlt = 10000; + // int minSurvivingBoneAtAlt=-1; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; rag.clear(); - int numRendered=0; - int numNotRendered=0; - //int pelvisAt=-1; - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if ((bone.flags & BONE_ANGLES_RAGDOLL) || (bone.flags & BONE_ANGLES_IK)) { + // rww - this was (!anyRendered) before. Isn't that wrong? (if anyRendered, then wasRendered should be true) + bool wasRendered = (!anyRendered) || // offscreeen or something + G2_WasBoneRendered(ghoul2, bone.boneNumber); + if (!wasRendered) { + bone.RagFlags |= RAG_WAS_NOT_RENDERED; numNotRendered++; - } - else - { - bone.RagFlags&=~RAG_WAS_NOT_RENDERED; - bone.RagFlags|=RAG_WAS_EVER_RENDERED; + } else { + bone.RagFlags &= ~RAG_WAS_NOT_RENDERED; + bone.RagFlags |= RAG_WAS_EVER_RENDERED; numRendered++; } - if (bone.RagFlags&RAG_PCJ_PELVIS) - { - //pelvisAt=i; - } - else if (bone.RagFlags&RAG_PCJ_MODEL_ROOT) - { - } - else if (wasRendered && (bone.RagFlags&RAG_PCJ)) - { - if (minSurvivingBone>bone.boneNumber) - { - minSurvivingBone=bone.boneNumber; - //minSurvivingBoneAt=i; + if (bone.RagFlags & RAG_PCJ_PELVIS) { + // pelvisAt=i; + } else if (bone.RagFlags & RAG_PCJ_MODEL_ROOT) { + } else if (wasRendered && (bone.RagFlags & RAG_PCJ)) { + if (minSurvivingBone > bone.boneNumber) { + minSurvivingBone = bone.boneNumber; + // minSurvivingBoneAt=i; } - } - else if (wasRendered) - { - if (minSurvivingBoneAlt>bone.boneNumber) - { - minSurvivingBoneAlt=bone.boneNumber; - //minSurvivingBoneAtAlt=i; + } else if (wasRendered) { + if (minSurvivingBoneAlt > bone.boneNumber) { + minSurvivingBoneAlt = bone.boneNumber; + // minSurvivingBoneAtAlt=i; } } - if ( - anyRendered && - (bone.RagFlags&RAG_WAS_EVER_RENDERED) && - !(bone.RagFlags&RAG_PCJ_MODEL_ROOT) && - !(bone.RagFlags&RAG_PCJ_PELVIS) && - !wasRendered && - (bone.RagFlags&RAG_EFFECTOR) - ) - { + if (anyRendered && (bone.RagFlags & RAG_WAS_EVER_RENDERED) && !(bone.RagFlags & RAG_PCJ_MODEL_ROOT) && !(bone.RagFlags & RAG_PCJ_PELVIS) && + !wasRendered && (bone.RagFlags & RAG_EFFECTOR)) { // this thing was rendered in the past, but wasn't now, although other bones were, lets get rid of it -// bone.flags &= ~BONE_ANGLES_RAGDOLL; -// bone.RagFlags = 0; -//OutputDebugString(va("Deleted Effector %d\n",i)); -// continue; + // bone.flags &= ~BONE_ANGLES_RAGDOLL; + // bone.RagFlags = 0; + // OutputDebugString(va("Deleted Effector %d\n",i)); + // continue; } - if ((int)rag.size()=0); - assert(numRags= 0); + assert(numRags < MAX_BONES_RAG); + + // ragStartTime=bone.ragStartTime; + + bone.ragIndex = numRags; + ragBoneData[numRags] = &bone; + ragEffectors[numRags].radius = bone.radius; + ragEffectors[numRags].weight = bone.weight; + G2_GetBoneBasepose(ghoul2, bone.boneNumber, bone.basepose, bone.baseposeInv); numRags++; } } - if (!numRags) - { + if (!numRags) { return false; } return true; } -static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params, int curTime) -{ - if (!broadsword||!broadsword->integer) - { +static void G2_RagDoll(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params, int curTime) { + if (!broadsword || !broadsword->integer) { return; } - if (!params) - { + if (!params) { assert(0); return; } @@ -2314,9 +1968,9 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * dPos[2] -= 6; #endif -// params->DebugLine(handPos,handPos2,false); - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + // params->DebugLine(handPos,handPos2,false); + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; @@ -2353,24 +2007,20 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; // this loop checks for settled - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if (bone.flags & BONE_ANGLES_RAGDOLL) { // check for state transitions - decay=G2_RagSetState(ghoul2,bone,frameNum,dPos,resetOrigin); // set the current state + decay = G2_RagSetState(ghoul2, bone, frameNum, dPos, resetOrigin); // set the current state - if (ragState==ERS_SETTLED) - { + if (ragState == ERS_SETTLED) { #if 0 bool noneInSolid = true; @@ -2400,37 +2050,31 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * return; #endif } - if (G2_WasBoneRendered(ghoul2,bone.boneNumber)) - { - anyRendered=true; + if (G2_WasBoneRendered(ghoul2, bone.boneNumber)) { + anyRendered = true; break; } } } } - //int iters=(ragState==ERS_DYNAMIC)?2:1; - int iters=(ragState==ERS_DYNAMIC)?4:2; - //bool kicked=false; - if (ragOriginChangeDir[2]<-100.0f) - { - //kicked=true; - //iters*=8; - iters*=2; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) + // int iters=(ragState==ERS_DYNAMIC)?2:1; + int iters = (ragState == ERS_DYNAMIC) ? 4 : 2; + // bool kicked=false; + if (ragOriginChangeDir[2] < -100.0f) { + // kicked=true; + // iters*=8; + iters *= 2; // rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) } - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,dPos,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, dPos, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (int i=0;iangles,dPos,params->scale); + for (int i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, dPos, params->scale); - if (G2_RagDollSettlePositionNumeroTrois(ghoul2V,dPos,params,curTime)) - { + if (G2_RagDollSettlePositionNumeroTrois(ghoul2V, dPos, params, curTime)) { #if 0 //effectors are start solid alot, so this was pretty extreme if (!kicked&&iters<4) @@ -2441,13 +2085,12 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif } - //params->position[2] += 16; - G2_RagDollSolve(ghoul2V,g2Index,decay*2.0f,frameNum,dPos,true,params); + // params->position[2] += 16; + G2_RagDollSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, dPos, true, params); } } - if (params->me != ENTITYNUM_NONE) - { + if (params->me != ENTITYNUM_NONE) { #if 0 vec3_t worldMins,worldMaxs; worldMins[0]=params->position[0]-17; @@ -2459,11 +2102,11 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * //OutputDebugString(va("%f \n",worldMins[2])); // params->DebugLine(worldMins,worldMaxs,true); #endif - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); -// SV_UnlinkEntity(params->me); -// params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); -// params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); -// SV_LinkEntity(params->me); + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); + // SV_UnlinkEntity(params->me); + // params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); + // params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); + // SV_LinkEntity(params->me); } } @@ -2472,19 +2115,16 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * #endif #ifdef _DEBUG_BONE_NAMES -static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); +static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; iragBoneMaxs[k]) - { - ragBoneMaxs[k]=ragEffectors[i].currentOrigin[k]; + // float cmweight=ragEffectors[numRags].weight; + float cmweight = 1.0f; + for (k = 0; k < 3; k++) { + ragEffectors[i].currentOrigin[k] = ragBones[i].matrix[k][3]; + assert(!Q_isnan(ragEffectors[i].currentOrigin[k])); + if (!i) { + // set mins, maxs and cm + ragBoneCM[k] = ragEffectors[i].currentOrigin[k] * cmweight; + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; + ragBoneMins[k] = ragEffectors[i].currentOrigin[k]; + } else { + ragBoneCM[k] += ragEffectors[i].currentOrigin[k] * ragEffectors[i].weight; + if (ragEffectors[i].currentOrigin[k] > ragBoneMaxs[k]) { + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; } - if (ragEffectors[i].currentOrigin[k]0.0f); + assert(totalWt > 0.0f); int k; { - float wtInv=1.0f/totalWt; - for (k=0;k<3;k++) - { - ragBoneMaxs[k]-=position[k]; - ragBoneMins[k]-=position[k]; - ragBoneMaxs[k]+=10.0f; - ragBoneMins[k]-=10.0f; - ragBoneCM[k]*=wtInv; + float wtInv = 1.0f / totalWt; + for (k = 0; k < 3; k++) { + ragBoneMaxs[k] -= position[k]; + ragBoneMins[k] -= position[k]; + ragBoneMaxs[k] += 10.0f; + ragBoneMins[k] -= 10.0f; + ragBoneCM[k] *= wtInv; - ragBoneCM[k]=ragEffectors[0].currentOrigin[k]; // use the pelvis + ragBoneCM[k] = ragEffectors[0].currentOrigin[k]; // use the pelvis } } } @@ -2575,14 +2206,14 @@ int ragSSCount = 0; int ragTraceCount = 0; #endif -void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) -{ +void Rag_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, + const EG2_Collision eG2TraceType, const int useLod) { #ifdef _DEBUG int ragPreTrace = ri.Milliseconds(); #endif { results->entityNum = ENTITYNUM_NONE; - //SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); + // SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); ri.CM_BoxTrace(results, start, end, mins, maxs, 0, contentmask, 0); results->entityNum = results->fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; } @@ -2591,39 +2222,35 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v int ragPostTrace = ri.Milliseconds(); ragTraceTime += (ragPostTrace - ragPreTrace); - if (results->startsolid) - { + if (results->startsolid) { ragSSCount++; } ragTraceCount++; #endif } -//run advanced physics on each bone indivudually -//an adaption of my "exphys" custom game physics model -#define MAX_GRAVITY_PULL 256//512 +// run advanced physics on each bone indivudually +// an adaption of my "exphys" custom game physics model +#define MAX_GRAVITY_PULL 256 // 512 -static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) -{ +static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) { trace_t tr; vec3_t gSpot; VectorCopy(org, gSpot); - gSpot[2] -= 1.0f; //seems reasonable to me + gSpot[2] -= 1.0f; // seems reasonable to me Rag_Trace(&tr, org, mins, maxs, gSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) - { //not in solid, and hit something. Guess it's ground. + if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) { // not in solid, and hit something. Guess it's ground. return true; } return false; } -static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, const vec3_t testMaxs, - const float gravity, const float mass, const float bounce) -{ +static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, + const vec3_t testMaxs, const float gravity, const float mass, const float bounce) { trace_t tr; vec3_t projectedOrigin; vec3_t vNorm; @@ -2634,68 +2261,54 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR assert(mass <= 1.0f && mass >= 0.01f); - if (bone.physicsSettled) - { //then we have no need to continue + if (bone.physicsSettled) { // then we have no need to continue return true; } - if (gravity) - { //factor it in before we do anything. + if (gravity) { // factor it in before we do anything. VectorCopy(e.currentOrigin, ground); ground[2] -= 1.0f; Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, ground, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.entityNum == ENTITYNUM_NONE) - { + if (tr.entityNum == ENTITYNUM_NONE) { boneOnGround = false; - } - else - { + } else { boneOnGround = true; } - if (!boneOnGround) - { - if (!params->velocity[2]) - { //only increase gravitational pull once the actual entity is still + if (!boneOnGround) { + if (!params->velocity[2]) { // only increase gravitational pull once the actual entity is still bone.epGravFactor += gravity; } - if (bone.epGravFactor > MAX_GRAVITY_PULL) - { //cap it off if needed + if (bone.epGravFactor > MAX_GRAVITY_PULL) { // cap it off if needed bone.epGravFactor = MAX_GRAVITY_PULL; } bone.epVelocity[2] -= bone.epGravFactor; - } - else - { //if we're sitting on something then reset the gravity factor. + } else { // if we're sitting on something then reset the gravity factor. bone.epGravFactor = 0; } - } - else - { + } else { boneOnGround = G2_BoneOnGround(e.currentOrigin, testMins, testMaxs, params->me); } - if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) - { //nothing to do if we have no velocity even after gravity. + if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) { // nothing to do if we have no velocity even after gravity. VectorCopy(e.currentOrigin, goalSpot); return true; } - //get the projected origin based on velocity. + // get the projected origin based on velocity. VectorMA(e.currentOrigin, velScaling, bone.epVelocity, projectedOrigin); - //scale it down based on mass - VectorScale(bone.epVelocity, 1.0f-mass, bone.epVelocity); + // scale it down based on mass + VectorScale(bone.epVelocity, 1.0f - mass, bone.epVelocity); VectorCopy(bone.epVelocity, vNorm); vTotal = VectorNormalize(vNorm); - if (vTotal < 1 && boneOnGround) - { //we've pretty much stopped moving anyway, just clear it out then. + if (vTotal < 1 && boneOnGround) { // we've pretty much stopped moving anyway, just clear it out then. VectorClear(bone.epVelocity); bone.epGravFactor = 0; VectorCopy(e.currentOrigin, goalSpot); @@ -2704,52 +2317,44 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, projectedOrigin, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.startsolid || tr.allsolid) - { //can't go anywhere from here + if (tr.startsolid || tr.allsolid) { // can't go anywhere from here return false; } - //Go ahead and set it to the trace endpoint regardless of what it hit + // Go ahead and set it to the trace endpoint regardless of what it hit VectorCopy(tr.endpos, goalSpot); - if (tr.fraction == 1.0f) - { //Nothing was in the way. + if (tr.fraction == 1.0f) { // Nothing was in the way. return true; } - if (bounce) - { - vTotal *= bounce; //scale it by bounce + if (bounce) { + vTotal *= bounce; // scale it by bounce - VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + VectorScale(tr.plane.normal, vTotal, vNorm); // scale the trace plane normal by the bounce factor - if (vNorm[2] > 0) - { - bone.epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. - if (bone.epGravFactor < 0) - { + if (vNorm[2] > 0) { + bone.epGravFactor -= vNorm[2] * (1.0f - mass); // The lighter it is the more gravity will be reduced by bouncing vertically. + if (bone.epGravFactor < 0) { bone.epGravFactor = 0; } } - VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); //add it into the existing velocity. + VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); // add it into the existing velocity. - //I suppose it could be sort of neat to make a game callback here to actual do stuff - //when bones slam into things. But it could be slow too. + // I suppose it could be sort of neat to make a game callback here to actual do stuff + // when bones slam into things. But it could be slow too. /* if (tr.entityNum != ENTITYNUM_NONE && ent->touch) { //then call the touch function ent->touch(ent, &g_entities[tr.entityNum], &tr); } */ - } - else - { //if no bounce, kill when it hits something. + } else { // if no bounce, kill when it hits something. bone.epVelocity[0] = 0; bone.epVelocity[1] = 0; - if (!gravity) - { + if (!gravity) { bone.epVelocity[2] = 0; } } @@ -2757,305 +2362,251 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR } #ifdef _DEBUG_BONE_NAMES -static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) -{ - return; -} +static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) { return; } -static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) -{ - return; -} +static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) { return; } #endif #ifdef _OLD_STYLE_SETTLE -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ - haveDesiredPelvisOffset=false; +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) { + haveDesiredPelvisOffset = false; vec3_t desiredPos; int i; assert(params); - //assert(params->me); //no longer valid, because me is an index! - int ignoreNum=params->me; + // assert(params->me); //no longer valid, because me is an index! + int ignoreNum = params->me; - bool anyStartSolid=false; + bool anyStartSolid = false; - vec3_t groundSpot={0,0,0}; + vec3_t groundSpot = {0, 0, 0}; // lets find the floor at our quake origin { vec3_t testStart; - VectorCopy(currentOrg,testStart); //last arg is dest + VectorCopy(currentOrg, testStart); // last arg is dest vec3_t testEnd; - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]-=200.0f; + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] -= 200.0f; vec3_t testMins; vec3_t testMaxs; - VectorSet(testMins,-10,-10,-10); - VectorSet(testMaxs,10,10,10); + VectorSet(testMins, -10, -10, -10); + VectorSet(testMaxs, 10, 10, 10); { - trace_t tr; - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0/*SV_TRACE_NO_PLAYER*/); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0 /*SV_TRACE_NO_PLAYER*/); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { - //hmmm, punt - VectorCopy(currentOrg,groundSpot); //last arg is dest - groundSpot[2]-=30.0f; - } - else - { - VectorCopy(tr.endpos,groundSpot); //last arg is dest + if (tr.startsolid) { + // hmmm, punt + VectorCopy(currentOrg, groundSpot); // last arg is dest + groundSpot[2] -= 30.0f; + } else { + VectorCopy(tr.endpos, groundSpot); // last arg is dest } } } - for (i=0;i groundSpot[2]) - { - testStart[2]=groundSpot[2]+(e.radius-10.0f); - } - else - { + if (e.currentOrigin[2] > groundSpot[2]) { + testStart[2] = groundSpot[2] + (e.radius - 10.0f); + } else { // lets try higher - testStart[2]=groundSpot[2]+8.0f; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + testStart[2] = groundSpot[2] + 8.0f; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } } - } - if (tr.startsolid) - { - iAmStartSolid=true; - anyStartSolid=true; + if (tr.startsolid) { + iAmStartSolid = true; + anyStartSolid = true; // above the origin, so lets slide away - if (e.currentOrigin[2] > groundSpot[2]) - { - if (params) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //params->EffectorCollision(args); + if (e.currentOrigin[2] > groundSpot[2]) { + if (params) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // params->EffectorCollision(args); } + } else { + // harumph, we are really screwed } - else - { - //harumph, we are really screwed - } - } - else - { - vertEffectorTraceFraction=tr.fraction; - if (params && - vertEffectorTraceFraction < .95f && - fabsf(tr.plane.normal[2]) < .707f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); + } else { + vertEffectorTraceFraction = tr.fraction; + if (params && vertEffectorTraceFraction < .95f && fabsf(tr.plane.normal[2]) < .707f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); } } } vec3_t effectorGroundSpot; - VectorAdvance(testStart,vertEffectorTraceFraction,testEnd,effectorGroundSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorAdvance(testStart, vertEffectorTraceFraction, testEnd, effectorGroundSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // trace from the quake origin horzontally to the effector // gonna choose the maximum of the ground spot or the effector location // and clamp it to be roughly in the bbox - VectorCopy(groundSpot,testStart); //last arg is dest - if (iAmStartSolid) - { + VectorCopy(groundSpot, testStart); // last arg is dest + if (iAmStartSolid) { // we don't have a meaningful ground spot - VectorCopy(e.currentOrigin,testEnd); //last arg is dest + VectorCopy(e.currentOrigin, testEnd); // last arg is dest bone.solidCount++; - } - else - { - VectorCopy(effectorGroundSpot,testEnd); //last arg is dest + } else { + VectorCopy(effectorGroundSpot, testEnd); // last arg is dest bone.solidCount = 0; } - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); float ztest; - if (testEnd[2]>testStart[2]) - { - ztest=testEnd[2]; + if (testEnd[2] > testStart[2]) { + ztest = testEnd[2]; + } else { + ztest = testStart[2]; } - else - { - ztest=testStart[2]; - } - if (ztest c := (1-t)a+tb + float magicFactor44 = 1.0f; // going to trace a bit longer, this also serves as an expansion parameter + VectorAdvance(testStart, magicFactor44, testEnd, testEnd); // VA(a,t,b,c)-> c := (1-t)a+tb - float horzontalTraceFraction=0.0f; - vec3_t HorizontalHitSpot={0,0,0}; + float horzontalTraceFraction = 0.0f; + vec3_t HorizontalHitSpot = {0, 0, 0}; { - trace_t tr; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (tr.startsolid) - { - horzontalTraceFraction=1.0f; + horzontalTraceFraction = tr.fraction; + if (tr.startsolid) { + horzontalTraceFraction = 1.0f; // punt - VectorCopy(e.currentOrigin,HorizontalHitSpot); - } - else - { - VectorCopy(tr.endpos,HorizontalHitSpot); - int magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //rww - An..int? - VectorAdvance(tr.endpos,magicFactor46,testStart,HorizontalHitSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(e.currentOrigin, HorizontalHitSpot); + } else { + VectorCopy(tr.endpos, HorizontalHitSpot); + int magicFactor46 = 0.98f; // shorten percetage to make sure we can go down along a wall + // float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + // rww - An..int? + VectorAdvance(tr.endpos, magicFactor46, testStart, HorizontalHitSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // roughly speaking this is a wall - if (horzontalTraceFraction<0.9f) - { + if (horzontalTraceFraction < 0.9f) { // roughly speaking this is a wall - if (fabsf(tr.plane.normal[2])<0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); + if (fabsf(tr.plane.normal[2]) < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); } - } - else if (!iAmStartSolid && - effectorGroundSpot[2] < groundSpot[2] - 8.0f) - { + } else if (!iAmStartSolid && effectorGroundSpot[2] < groundSpot[2] - 8.0f) { // this is a situation where we have something dangling below the pelvis, we want to find the plane going downhill away from the origin // for various reasons, without this correction the body will actually move away from places it can fall off. - //gotta run the trace backwards to get a plane + // gotta run the trace backwards to get a plane { - trace_t tr; - VectorCopy(effectorGroundSpot,testStart); - VectorCopy(groundSpot,testEnd); + trace_t tr; + VectorCopy(effectorGroundSpot, testStart); + VectorCopy(groundSpot, testEnd); // this can be a line trace, we just want the plane normal - Rag_Trace(&tr,testEnd,0,0,testStart,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + Rag_Trace(&tr, testEnd, 0, 0, testStart, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (!tr.startsolid && tr.fraction< 0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); + horzontalTraceFraction = tr.fraction; + if (!tr.startsolid && tr.fraction < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); } } } } } - vec3_t goalSpot={0,0,0}; + vec3_t goalSpot = {0, 0, 0}; // now lets trace down - VectorCopy(HorizontalHitSpot,testStart); - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]=e.currentOrigin[2]-30.0f; + VectorCopy(HorizontalHitSpot, testStart); + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] = e.currentOrigin[2] - 30.0f; { - trace_t tr; - Rag_Trace(&tr,testStart,NULL,NULL,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, NULL, NULL, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { + if (tr.startsolid) { // punt, go to the origin I guess - VectorCopy(currentOrg,goalSpot); - } - else - { - VectorCopy(tr.endpos,goalSpot); - int magicFactor47=0.5f; // shorten percentage to make sure we can go down along a wall - VectorAdvance(tr.endpos,magicFactor47,testStart,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(currentOrg, goalSpot); + } else { + VectorCopy(tr.endpos, goalSpot); + int magicFactor47 = 0.5f; // shorten percentage to make sure we can go down along a wall + VectorAdvance(tr.endpos, magicFactor47, testStart, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb } } // ok now as the horizontal trace fraction approaches zero, we want to head toward the horizontalHitSpot - //geeze I would like some reasonable trace fractions - assert(horzontalTraceFraction>=0.0f&&horzontalTraceFraction<=1.0f); - VectorAdvance(HorizontalHitSpot,horzontalTraceFraction*horzontalTraceFraction,goalSpot,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + // geeze I would like some reasonable trace fractions + assert(horzontalTraceFraction >= 0.0f && horzontalTraceFraction <= 1.0f); + VectorAdvance(HorizontalHitSpot, horzontalTraceFraction * horzontalTraceFraction, goalSpot, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb #if 0 if ((bone.RagFlags & RAG_EFFECTOR) && (bone.RagFlags & RAG_BONE_LIGHTWEIGHT)) { //new rule - don't even bother unless it's a lightweight effector @@ -3109,22 +2660,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif int k; - int magicFactor12=0.8f; // dampening of velocity applied - int magicFactor16=10.0f; // effect multiplier of velocity applied + int magicFactor12 = 0.8f; // dampening of velocity applied + int magicFactor16 = 10.0f; // effect multiplier of velocity applied - if (iAmStartSolid) - { + if (iAmStartSolid) { magicFactor16 = 30.0f; } - for (k=0;k<3;k++) - { - e.desiredDirection[k]=goalSpot[k]-e.currentOrigin[k]; - e.desiredDirection[k]+=magicFactor16*bone.velocityEffector[k]; - e.desiredDirection[k]+=flrand(-0.75f,0.75f)*flrand(-0.75f,0.75f); - bone.velocityEffector[k]*=magicFactor12; + for (k = 0; k < 3; k++) { + e.desiredDirection[k] = goalSpot[k] - e.currentOrigin[k]; + e.desiredDirection[k] += magicFactor16 * bone.velocityEffector[k]; + e.desiredDirection[k] += flrand(-0.75f, 0.75f) * flrand(-0.75f, 0.75f); + bone.velocityEffector[k] *= magicFactor12; } - VectorCopy(e.currentOrigin,bone.lastPosition); // last arg is dest + VectorCopy(e.currentOrigin, bone.lastPosition); // last arg is dest } return anyStartSolid; } @@ -3147,17 +2696,14 @@ static inline int G2_RagIndexForBoneNum(int boneNum) #endif #ifdef _RAG_PRINT_TEST -void G2_RagPrintMatrix(mdxaBone_t *mat) -{ +void G2_RagPrintMatrix(mdxaBone_t *mat) { char x[1024]; x[0] = 0; int n = 0; - while (n < 3) - { + while (n < 3) { int o = 0; - while (o < 4) - { - strcat(x, va("%f ", mat->matrix[n][o])); + while (o < 4) { + strcat(x, va("%f ", mat->matrix[n][o])); o++; } n++; @@ -3170,34 +2716,31 @@ void G2_RagPrintMatrix(mdxaBone_t *mat) void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale); void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame); -static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) -{ +static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) { static mdxaBone_t trueBaseMatrix, baseBoneMatrix; - //get matrix for the settleFrame to use as an ideal + // get matrix for the settleFrame to use as an ideal G2_RagGetAnimMatrix(ghoul2, bone.boneNumber, trueBaseMatrix, params->settleFrame); assert(bone.hasAnimFrameMatrix == params->settleFrame); - G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, - trueBaseMatrix, baseBoneMatrix, params->scale); + G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, trueBaseMatrix, baseBoneMatrix, params->scale); - //Use params to multiply world coordinate/dir matrix into the - //bone matrix and give us a useable world position + // Use params to multiply world coordinate/dir matrix into the + // bone matrix and give us a useable world position Multiply_3x4Matrix(&retMatrix, &worldMatrix, &baseBoneMatrix); assert(!Q_isnan(retMatrix.matrix[2][3])); } -//get the current pelvis Z direction and the base anim matrix Z direction -//so they can be compared and used to offset -rww +// get the current pelvis Z direction and the base anim matrix Z direction +// so they can be compared and used to offset -rww void G2_GetRagBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &retMatrix); -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); -static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) -{ +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) { static mdxaBone_t final; static mdxaBone_t x; - //static mdxaBone_t *unused1, *unused2; - //static vec3_t lumbarPos; + // static mdxaBone_t *unused1, *unused2; + // static vec3_t lumbarPos; assert(ghoul2.animModel); int boneIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, "pelvis"); @@ -3213,8 +2756,8 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd G2API_GiveMeVectorFromMatrix(&final, ORIGIN, pos); G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, dir); #else - //We have the anim matrix pelvis pos now, so get the normal one as well - //G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); + // We have the anim matrix pelvis pos now, so get the normal one as well + // G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); int bolt = G2_Add_Bolt(&ghoul2, ghoul2.mBltlist, ghoul2.mSlist, "pelvis"); G2_GetBoltMatrixLow(ghoul2, bolt, params->scale, x); Multiply_3x4Matrix(&final, &worldMatrix, &x); @@ -3242,8 +2785,8 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd */ } -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ //now returns true if any bone was in solid, otherwise false +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, + int curTime) { // now returns true if any bone was in solid, otherwise false int ignoreNum = params->me; static int i; static vec3_t goalSpot; @@ -3264,38 +2807,31 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve static bool hasBasePos; static vec3_t animPelvisDir, pelvisDir, animPelvisPos, pelvisPos; - //Maybe customize per-bone? + // Maybe customize per-bone? static const float gravity = 3.0f; static const float mass = 0.09f; - static const float bounce = 0.0f;//1.3f; - //Bouncing and stuff unfortunately does not work too well at the moment. - //Need to keep a seperate "physics origin" or make the filthy solve stuff - //better. + static const float bounce = 0.0f; // 1.3f; + // Bouncing and stuff unfortunately does not work too well at the moment. + // Need to keep a seperate "physics origin" or make the filthy solve stuff + // better. bool inAir = false; - if (params->velocity[0] || params->velocity[1] || params->velocity[2]) - { + if (params->velocity[0] || params->velocity[1] || params->velocity[2]) { inAir = true; } - if (!params->scale[0] && !params->scale[1] && !params->scale[2]) - { + if (!params->scale[0] && !params->scale[1] && !params->scale[2]) { VectorSet(entScale, 1.0f, 1.0f, 1.0f); - } - else - { + } else { VectorCopy(params->scale, entScale); } - if (broadsword_ragtobase && - broadsword_ragtobase->integer > 1) - { - //grab the pelvis directions to offset base positions for bones - G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, - animPelvisDir); + if (broadsword_ragtobase && broadsword_ragtobase->integer > 1) { + // grab the pelvis directions to offset base positions for bones + G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, animPelvisDir); - //don't care about the pitch offsets + // don't care about the pitch offsets pelvisDir[2] = 0; animPelvisDir[2] = 0; @@ -3313,24 +2849,21 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(uanimPelvisPos, blah, 50, 0xff0000, 1); */ - //just convert to angles now, that's all we'll ever use them for + // just convert to angles now, that's all we'll ever use them for vectoangles(pelvisDir, pelvisDir); vectoangles(animPelvisDir, animPelvisDir); } - for (i = 0; i < numRags; i++) - { + for (i = 0; i < numRags; i++) { boneInfo_t &bone = *ragBoneData[i]; SRagEffector &e = ragEffectors[i]; - if (inAir) - { + if (inAir) { bone.airTime = curTime + 30; } - if (bone.RagFlags & RAG_PCJ_PELVIS) - { - VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2]+DEFAULT_MINS_2)+((bone.radius*entScale[2])+2)); + if (bone.RagFlags & RAG_PCJ_PELVIS) { + VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2] + DEFAULT_MINS_2) + ((bone.radius * entScale[2]) + 2)); VectorSubtract(goalSpot, e.currentOrigin, desiredPelvisOffset); haveDesiredPelvisOffset = true; @@ -3338,17 +2871,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - if (!(bone.RagFlags & RAG_EFFECTOR)) - { + if (!(bone.RagFlags & RAG_EFFECTOR)) { continue; } - if (bone.hasOverGoal) - { //api call was made to override the goal spot + if (bone.hasOverGoal) { // api call was made to override the goal spot VectorCopy(bone.overGoalSpot, goalSpot); bone.solidCount = 0; - for (k = 0; k < 3; k++) - { + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); bone.velocityEffector[k] *= velocityDampening; @@ -3358,22 +2888,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - VectorSet(testMins, -e.radius*entScale[0], -e.radius*entScale[1], -e.radius*entScale[2]); - VectorSet(testMaxs, e.radius*entScale[0], e.radius*entScale[1], e.radius*entScale[2]); + VectorSet(testMins, -e.radius * entScale[0], -e.radius * entScale[1], -e.radius * entScale[2]); + VectorSet(testMaxs, e.radius * entScale[0], e.radius * entScale[1], e.radius * entScale[2]); assert(ghoul2V[0].mBoneCache); - //get the parent bone's position + // get the parent bone's position hasDaddy = false; - if (bone.boneNumber) - { + if (bone.boneNumber) { assert(ghoul2V[0].animModel); assert(ghoul2V[0].aHeader); - if (bone.parentBoneIndex == -1) - { - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; + if (bone.parentBoneIndex == -1) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; int bParentIndex, bParentListIndex = -1; offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); @@ -3381,66 +2909,54 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve bParentIndex = skel->parent; - while (bParentIndex > 0) - { //go upward through hierarchy searching for the first parent that is a rag bone + while (bParentIndex > 0) { // go upward through hierarchy searching for the first parent that is a rag bone skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bParentIndex]); bParentIndex = skel->parent; bParentListIndex = G2_Find_Bone(ghoul2V[0].animModel, ghoul2V[0].mBlist, skel->name); - if (bParentListIndex != -1) - { + if (bParentListIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bParentListIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //valid rag bone + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // valid rag bone break; } } - //didn't work out, reset to -1 again + // didn't work out, reset to -1 again bParentListIndex = -1; } bone.parentBoneIndex = bParentListIndex; } - if (bone.parentBoneIndex != -1) - { + if (bone.parentBoneIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bone.parentBoneIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //has origin calculated for us already + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // has origin calculated for us already VectorCopy(ragEffectors[pbone.ragIndex].currentOrigin, parentOrigin); hasDaddy = true; } } } - //get the position this bone would be in if we were in the desired frame + // get the position this bone would be in if we were in the desired frame hasBasePos = false; - if (broadsword_ragtobase && - broadsword_ragtobase->integer) - { + if (broadsword_ragtobase && broadsword_ragtobase->integer) { vec3_t v, a; float f; G2_RagGetWorldAnimMatrix(ghoul2V[0], bone, params, worldBaseMatrix); G2API_GiveMeVectorFromMatrix(&worldBaseMatrix, ORIGIN, basePos); - if (broadsword_ragtobase->integer > 1) - { - float fa = AngleNormalize180(animPelvisDir[YAW]-pelvisDir[YAW]); - float d = fa-bone.offsetRotation; + if (broadsword_ragtobase->integer > 1) { + float fa = AngleNormalize180(animPelvisDir[YAW] - pelvisDir[YAW]); + float d = fa - bone.offsetRotation; - if (d > 16.0f || - d < -16.0f) - { //don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates + if (d > 16.0f || d < -16.0f) { // don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates bone.offsetRotation = fa; - } - else - { + } else { fa = bone.offsetRotation; } - //Rotate the point around the pelvis based on the offsets between pelvis positions + // Rotate the point around the pelvis based on the offsets between pelvis positions VectorSubtract(basePos, animPelvisPos, v); f = VectorLength(v); vectoangles(v, a); @@ -3449,14 +2965,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve VectorNormalize(v); VectorMA(animPelvisPos, f, v, basePos); - //re-orient the position of the bone to the current position of the pelvis + // re-orient the position of the bone to the current position of the pelvis VectorSubtract(basePos, animPelvisPos, v); - //push the spots outward? (to stretch the skeleton more) - //v[0] *= 1.5f; - //v[1] *= 1.5f; + // push the spots outward? (to stretch the skeleton more) + // v[0] *= 1.5f; + // v[1] *= 1.5f; VectorAdd(pelvisPos, v, basePos); } -#if 0 //for debugging frame skeleton +#if 0 // for debugging frame skeleton mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; @@ -3486,27 +3002,23 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve hasBasePos = true; } - //Are we in solid? - if (hasDaddy) - { + // Are we in solid? + if (hasDaddy) { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, parentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - //Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - } - else - { + // Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } else { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, params->position, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); } - if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) - { //currently in solid, see what we can do about it + if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) { // currently in solid, see what we can do about it vec3_t vSub; startSolid = true; anySolid = true; - if (hasBasePos)// && bone.solidCount < 32) - { //only go to the base pos for slightly in solid bones -#if 0 //over-compensation + if (hasBasePos) // && bone.solidCount < 32) + { // only go to the base pos for slightly in solid bones +#if 0 // over-compensation float fl; float floorBase; @@ -3520,107 +3032,88 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve { goalSpot[2] = floorBase; } -#else //just use the spot directly +#else // just use the spot directly VectorCopy(basePos, goalSpot); - goalSpot[2] = (params->position[2]-23)-testMins[2]; + goalSpot[2] = (params->position[2] - 23) - testMins[2]; #endif - //Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); - } - else - { //if deep in solid want to try to rise up out of solid before hinting back to base + // Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); + } else { // if deep in solid want to try to rise up out of solid before hinting back to base VectorSubtract(e.currentOrigin, params->position, vSub); VectorNormalize(vSub); VectorMA(params->position, 40.0f, vSub, goalSpot); - //should be 1 unit above the ground taking bounding box sizes into account - goalSpot[2] = (params->position[2]-23)-testMins[2]; + // should be 1 unit above the ground taking bounding box sizes into account + goalSpot[2] = (params->position[2] - 23) - testMins[2]; } - //Trace from the entity origin in the direction between the origin and current bone position to - //find a good eventual goal position + // Trace from the entity origin in the direction between the origin and current bone position to + // find a good eventual goal position Rag_Trace(&tr, params->position, testMins, testMaxs, goalSpot, params->me, RAG_MASK, G2_NOCOLLIDE, 0); VectorCopy(tr.endpos, goalSpot); - } - else - { + } else { startSolid = false; -#if 1 //do hinting? - //Hint the bone back to the base origin - if (hasDaddy || hasBasePos) - { - if (hasBasePos) - { +#if 1 // do hinting? + // Hint the bone back to the base origin + if (hasDaddy || hasBasePos) { + if (hasBasePos) { VectorSubtract(basePos, e.currentOrigin, velDir); - } - else - { + } else { VectorSubtract(e.currentOrigin, parentOrigin, velDir); } - } - else - { + } else { VectorSubtract(e.currentOrigin, params->position, velDir); } - if (VectorLength(velDir) > 2.0f) - { //don't bother if already close + if (VectorLength(velDir) > 2.0f) { // don't bother if already close VectorNormalize(velDir); VectorScale(velDir, 8.0f, velDir); - velDir[2] = 0; //don't want to nudge on Z, the gravity will take care of things. + velDir[2] = 0; // don't want to nudge on Z, the gravity will take care of things. VectorAdd(bone.epVelocity, velDir, bone.epVelocity); } #endif - //Factor the object's velocity into the bone's velocity, by pushing the bone - //opposite the velocity to give the apperance the lighter limbs are being "dragged" - //behind those of greater mass. - if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) - { + // Factor the object's velocity into the bone's velocity, by pushing the bone + // opposite the velocity to give the apperance the lighter limbs are being "dragged" + // behind those of greater mass. + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) { vec3_t vel; float vellen; VectorCopy(params->velocity, vel); - //Scale down since our velocity scale is different from standard game physics + // Scale down since our velocity scale is different from standard game physics VectorScale(vel, 0.5f, vel); vellen = VectorLength(vel); - if (vellen > 64.0f) - { //cap it off - VectorScale(vel, 64.0f/vellen, vel); + if (vellen > 64.0f) { // cap it off + VectorScale(vel, 64.0f / vellen, vel); } - //Invert the velocity so we go opposite the heavier parts and drag behind + // Invert the velocity so we go opposite the heavier parts and drag behind VectorInverse(vel); - if (vel[2]) - { //want to override entirely instead then + if (vel[2]) { // want to override entirely instead then VectorCopy(vel, bone.epVelocity); - } - else - { + } else { VectorAdd(bone.epVelocity, vel, bone.epVelocity); } } - //We're not in solid so we can apply physics freely now. - if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, - gravity, mass, bounce)) - { //if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin + // We're not in solid so we can apply physics freely now. + if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, gravity, mass, + bounce)) { // if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin VectorCopy(params->position, goalSpot); } } - //Set this now so we know what to do for angle limiting - if (startSolid) - { + // Set this now so we know what to do for angle limiting + if (startSolid) { bone.solidCount++; #ifdef _DEBUG_BONE_NAMES - if (bone.solidCount > 64) - { + if (bone.solidCount > 64) { char *debugBoneName = G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber); vec3_t absmin, absmax; @@ -3635,14 +3128,12 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(e.currentOrigin, goalSpot, 50, 0x00ff00, 1); } #endif - } - else - { + } else { bone.solidCount = 0; } -#if 0 //standard goalSpot capping? - //unless we are really in solid, we should keep adjustments minimal +#if 0 // standard goalSpot capping? + // unless we are really in solid, we should keep adjustments minimal if (/*bone.epGravFactor < 64 &&*/ bone.solidCount < 2 && !inAir) { @@ -3661,22 +3152,17 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif - //Set the desired direction based on the goal position and other factors. - for (k = 0; k < 3; k++) - { + // Set the desired direction based on the goal position and other factors. + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); - if (broadsword_dircap && - broadsword_dircap->value) - { + if (broadsword_dircap && broadsword_dircap->value) { float cap = broadsword_dircap->value; - if (bone.solidCount > 5) - { - float solidFactor = bone.solidCount*0.2f; + if (bone.solidCount > 5) { + float solidFactor = bone.solidCount * 0.2f; - if (solidFactor > 16.0f) - { //don't go too high or something ugly might happen + if (solidFactor > 16.0f) { // don't go too high or something ugly might happen solidFactor = 16.0f; } @@ -3684,12 +3170,9 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve cap *= 8; } - if (e.desiredDirection[k] > cap) - { + if (e.desiredDirection[k] > cap) { e.desiredDirection[k] = cap; - } - else if (e.desiredDirection[k] < -cap) - { + } else if (e.desiredDirection[k] < -cap) { e.desiredDirection[k] = -cap; } } @@ -3706,32 +3189,25 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif -static float AngleNormZero(float theta) -{ - float ret=fmodf(theta,360.0f); - if (ret<-180.0f) - { - ret+=360.0f; - } - else if (ret>180.0f) - { - ret-=360.0f; +static float AngleNormZero(float theta) { + float ret = fmodf(theta, 360.0f); + if (ret < -180.0f) { + ret += 360.0f; + } else if (ret > 180.0f) { + ret -= 360.0f; } - assert(ret>=-180.0f&&ret<=180.0f); + assert(ret >= -180.0f && ret <= 180.0f); return ret; } -static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) -{ - return; -} +static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) { return; } -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool limitAngles,CRagDollUpdateParams *params) -{ +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool limitAngles, + CRagDollUpdateParams *params) { int i; - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; mdxaBone_t N; mdxaBone_t P; @@ -3745,96 +3221,88 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; - // END this is the objective function thing - for (i=0;i50.0f) { @@ -3845,193 +3313,168 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f bone.velocityRoot[k]=-50.0f; } */ - //No -rww - bone.ragOverrideMatrix.matrix[k][3]=bone.velocityRoot[k]; + // No -rww + bone.ragOverrideMatrix.matrix[k][3] = bone.velocityRoot[k]; } } - } - else - { + } else { vec3_t delAngles; VectorClear(delAngles); - for (k=0;k<3;k++) - { - tAngles[k]+=0.5f; - Create_Matrix(tAngles,&temp2); //dest 2nd arg - tAngles[k]-=0.5f; - Multiply_3x4Matrix(&temp1,&P,&temp2); //dest first arg - Multiply_3x4Matrix(&Gs[k],&temp1,&N); //dest first arg - + for (k = 0; k < 3; k++) { + tAngles[k] += 0.5f; + Create_Matrix(tAngles, &temp2); // dest 2nd arg + tAngles[k] -= 0.5f; + Multiply_3x4Matrix(&temp1, &P, &temp2); // dest first arg + Multiply_3x4Matrix(&Gs[k], &temp1, &N); // dest first arg } - int allSolidCount = 0;//bone.solidCount; + int allSolidCount = 0; // bone.solidCount; // fixme precompute this - int numDep=G2_GetBoneDependents(ghoul2,bone.boneNumber,tempDependents,MAX_BONES_RAG); + int numDep = G2_GetBoneDependents(ghoul2, bone.boneNumber, tempDependents, MAX_BONES_RAG); int j; - int numRagDep=0; - for (j=0;jragIndex; - assert(depIndex>i); // these are supposed to be topologically sorted + int depIndex = rag[tempDependents[j]]->ragIndex; + assert(depIndex > i); // these are supposed to be topologically sorted assert(ragBoneData[depIndex]); - boneInfo_t &depBone=*ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector + boneInfo_t &depBone = *ragBoneData[depIndex]; + if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } allSolidCount += depBone.solidCount; } } - //bone.solidCount = allSolidCount; + // bone.solidCount = allSolidCount; allSolidCount += bone.solidCount; - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9=0.75f; // dampfactor for angle changes - float magicFactor1=0.40f; //controls the speed of the gradient descent - float magicFactor32 = 1.5f; - float recip=0.0f; - if (numRagDep) - { - recip=sqrt(4.0f/float(numRagDep)); + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = 0.40f; // controls the speed of the gradient descent + float magicFactor32 = 1.5f; + float recip = 0.0f; + if (numRagDep) { + recip = sqrt(4.0f / float(numRagDep)); } - if (allSolidCount > 32) - { + if (allSolidCount > 32) { magicFactor1 = 0.6f; - } - else if (allSolidCount > 10) - { + } else if (allSolidCount > 10) { magicFactor1 = 0.5f; } - if (bone.overGradSpeed) - { //api call was made to specify a speed for this bone + if (bone.overGradSpeed) { // api call was made to specify a speed for this bone magicFactor1 = bone.overGradSpeed; } - float fac=decay*recip*magicFactor1; - assert(fac>=0.0f); + float fac = decay * recip * magicFactor1; + assert(fac >= 0.0f); #if 0 if (bone.RagFlags & RAG_PCJ_PELVIS) { magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable } #endif - if (ragState==ERS_DYNAMIC) - { - magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + if (ragState == ERS_DYNAMIC) { + magicFactor9 = .85f; // we don't want this swinging radically, make the whole thing kindof unstable } -#if 1 //constraint breaks? - if (bone.RagFlags & RAG_UNSNAPPABLE) - { +#if 1 // constraint breaks? + if (bone.RagFlags & RAG_UNSNAPPABLE) { magicFactor32 = 1.0f; } #endif - for (k=0;k<3;k++) - { - bone.currentAngles[k]+=delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k]=(bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; - bone.currentAngles[k]=AngleNormZero(bone.currentAngles[k]); + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); // bone.currentAngles[k]=flrand(bone.minAngles[k],bone.maxAngles[k]); -#if 1 //constraint breaks? - if (limitAngles && ( allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE) )) //32 tries and still in solid? Then we'll let you move freely +#if 1 // constraint breaks? + if (limitAngles && (allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE))) // 32 tries and still in solid? Then we'll let you move freely #else if (limitAngles) #endif { - if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) - { - //magicFactor32 += (allSolidCount/32); + if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) { + // magicFactor32 += (allSolidCount/32); - if (bone.currentAngles[k]>bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k]=bone.maxAngles[k]*magicFactor32; + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k]bone.maxAngles[k]*magicFactor32) - { + for (k = 0; k < 3; k++) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { isSnapped = true; break; } - if (bone.currentAngles[k]ragIndex; - if (!ragBoneData[depIndex]) - { + int depIndex = rag[tempDependents[j]]->ragIndex; + if (!ragBoneData[depIndex]) { continue; } - boneInfo_t &depBone=*ragBoneData[depIndex]; + boneInfo_t &depBone = *ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) - { + if (depBone.RagFlags & RAG_EFFECTOR) { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } } } @@ -4154,222 +3585,174 @@ static void G2_IKSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameN VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9 = 0.75f; // dampfactor for angle changes - float magicFactor1 = bone.ikSpeed; //controls the speed of the gradient descent - float magicFactor32 = 1.0f; - float recip = 0.0f; - bool freeThisBone = false; + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = bone.ikSpeed; // controls the speed of the gradient descent + float magicFactor32 = 1.0f; + float recip = 0.0f; + bool freeThisBone = false; - if (!magicFactor1) - { + if (!magicFactor1) { magicFactor1 = 0.40f; } - recip = sqrt(4.0f/1.0f); + recip = sqrt(4.0f / 1.0f); - float fac = (decay*recip*magicFactor1); + float fac = (decay * recip * magicFactor1); assert(fac >= 0.0f); - if (ragState == ERS_DYNAMIC) - { + if (ragState == ERS_DYNAMIC) { magicFactor9 = 0.85f; // we don't want this swinging radically, make the whole thing kindof unstable } - - if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && - !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) - { + if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) { freeThisBone = true; } - for (k = 0; k < 3; k++) - { - bone.currentAngles[k] += delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k] = (bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); - if (limitAngles && !freeThisBone) - { - if (bone.currentAngles[k] > bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.maxAngles[k]*magicFactor32; + if (limitAngles && !freeThisBone) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k] < bone.minAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.minAngles[k]*magicFactor32; + if (bone.currentAngles[k] < bone.minAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.minAngles[k] * magicFactor32; } } } Create_Matrix(bone.currentAngles, &temp1); Multiply_3x4Matrix(&temp2, &temp1, bone.baseposeInv); Multiply_3x4Matrix(&bone.ragOverrideMatrix, bone.basepose, &temp2); - assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + assert(!Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); G2_Generate_MatrixRag(blist, ragBlistIndex[bone.boneNumber]); } } -static void G2_DoIK(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params) -{ +static void G2_DoIK(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params) { int i; - if (!params) - { + if (!params) { assert(0); return; } - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; - int iters = 12; //since we don't trace or anything, we can afford this. + int iters = 12; // since we don't trace or anything, we can afford this. - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,params->position,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, params->position, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (i=0;iangles,params->position,params->scale); + for (i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); G2_IKReposition(params->position, params); - G2_IKSolve(ghoul2V,g2Index,decay*2.0f,frameNum,params->position,true); + G2_IKSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, params->position, true); } } - if (params->me != ENTITYNUM_NONE) - { - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); + if (params->me != ENTITYNUM_NONE) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); } } -//rww - cut out the entire non-ragdoll section of this.. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index,CRagDollUpdateParams *params) -{ - bool anyRagDoll=false; +// rww - cut out the entire non-ragdoll section of this.. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index, CRagDollUpdateParams *params) { + bool anyRagDoll = false; bool anyIK = false; - for(size_t i=0; iangles, parms->position); @@ -4402,27 +3785,26 @@ void G2_InitIK(CGhoul2Info_v &ghoul2V, sharedRagDollUpdateParams_t *parms, int t G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); #endif - //Only need the standard effectors for this. - pcjFlags = RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rhand",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lhand",pcjFlags,6.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ceyebrow",pcjFlags,10.0f); + // Only need the standard effectors for this. + pcjFlags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rhand", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lhand", pcjFlags, 6.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ceyebrow", pcjFlags, 10.0f); } -qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ - model_t *mod_a; +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + model_t *mod_a; int g2index = 0; int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; @@ -4431,19 +3813,15 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName boneInfo_v &blist = g2.mBlist; mod_a = (model_t *)g2.animModel; - if (!boneName) - { //null bonename param means it's time to init the ik stuff on this instance + if (!boneName) { // null bonename param means it's time to init the ik stuff on this instance sharedRagDollUpdateParams_t sRDUP; - if (ikState == IKS_NONE) - { //this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags + if (ikState == IKS_NONE) { // this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags size_t i = 0; - while (i < blist.size()) - { //we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ - //limb after they reset it gameside, it's reasonable for IK bones. + while (i < blist.size()) { // we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ + // limb after they reset it gameside, it's reasonable for IK bones. boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1) - { + if (bone.boneNumber != -1) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -4455,8 +3833,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName } assert(params); - if (!params) - { + if (!params) { return qfalse; } @@ -4469,53 +3846,47 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } - if (!rmod_a || !mod_a) - { + if (!rmod_a || !mod_a) { return qfalse; } int index = G2_Find_Bone(mod_a, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index == -1) - { //couldn't find or add the bone.. + if (index == -1) { // couldn't find or add the bone.. return qfalse; } boneInfo_t &bone = blist[index]; - if (ikState == IKS_NONE) - { //remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since - //we don't store bone index handles gameside anywhere. - if (!(bone.flags & BONE_ANGLES_RAGDOLL)) - { //you can't set the ik state to none if it's not a rag/ik bone. + if (ikState == IKS_NONE) { // remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since + // we don't store bone index handles gameside anywhere. + if (!(bone.flags & BONE_ANGLES_RAGDOLL)) { // you can't set the ik state to none if it's not a rag/ik bone. return qfalse; } - //bone.flags = 0; - //G2_Remove_Bone_Index(blist, index); - //actually, I want to keep it on the rag list, and remove it as an IK bone instead. + // bone.flags = 0; + // G2_Remove_Bone_Index(blist, index); + // actually, I want to keep it on the rag list, and remove it as an IK bone instead. bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags |= BONE_ANGLES_IK; bone.RagFlags &= ~RAG_PCJ_IK_CONTROLLED; return qtrue; } - //need params if we're not resetting. - if (!params) - { + // need params if we're not resetting. + if (!params) { assert(0); return qfalse; } - if (bone.flags & BONE_ANGLES_RAGDOLL) - { //otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be BONE_ANGLES_IK, active are considered rag) + if (bone.flags & BONE_ANGLES_RAGDOLL) { // otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be + // BONE_ANGLES_IK, active are considered rag) return qfalse; } -#if 0 //this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's +#if 0 // this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's if (!(bone.flags & BONE_ANGLES_IK) && !(bone.flags & BONE_ANGLES_RAGDOLL)) { //IK system has not been inited yet, because any bone that can be IK should be in the ragdoll list, not flagged as BONE_ANGLES_RAGDOLL but as BONE_ANGLES_IK sharedRagDollUpdateParams_t sRDUP; @@ -4538,10 +3909,9 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); #endif - int pcjFlags = RAG_PCJ|RAG_PCJ_IK_CONTROLLED|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + int pcjFlags = RAG_PCJ | RAG_PCJ_IK_CONTROLLED | RAG_PCJ_POST_MULT | RAG_EFFECTOR; - if (params->pcjOverrides) - { + if (params->pcjOverrides) { pcjFlags = params->pcjOverrides; } @@ -4552,11 +3922,10 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName int startFrame = params->startFrame, endFrame = params->endFrame; - if (bone.startFrame != startFrame || bone.endFrame != endFrame || params->forceAnimOnBone) - { //if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. - G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f, curTime, float(startFrame), 150, 0, true); + if (bone.startFrame != startFrame || bone.endFrame != endFrame || + params->forceAnimOnBone) { // if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. + G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); } G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); @@ -4564,8 +3933,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName bone.lastTimeUpdated = 0; G2_Set_Bone_Angles_Rag(g2, rmod_a, blist, boneName, pcjFlags, params->radius, params->pcjMins, params->pcjMaxs, params->blendTime); - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { assert(!"failed to add any rag bones"); return qfalse; } @@ -4573,8 +3941,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } -qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { #if 0 model_t *mod_a; int g2index = 0; @@ -4615,17 +3982,15 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; - //rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { //changed models, possibly. + // rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { // changed models, possibly. return qfalse; } - for (int i=0;idesiredOrigin, bone.ikPosition); bone.ikSpeed = params->movementSpeed; @@ -4636,21 +4001,16 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params } // set the bone list to all unused so the bone transformation routine ignores it. -void G2_Init_Bone_List(boneInfo_v &blist, int numBones) -{ +void G2_Init_Bone_List(boneInfo_v &blist, int numBones) { blist.clear(); blist.reserve(numBones); } -void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) -{ +void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; imFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); +int G2_Get_Bone_Index(CGhoul2Info *ghoul2, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2->mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); return (G2_Find_Bone(mod_a, ghoul2->mBlist, boneName)); } diff --git a/codemp/rd-dedicated/G2_misc.cpp b/codemp/rd-dedicated/G2_misc.cpp index 96a58fae32..ebd193c070 100644 --- a/codemp/rd-dedicated/G2_misc.cpp +++ b/codemp/rd-dedicated/G2_misc.cpp @@ -33,303 +33,236 @@ along with this program; if not, see . #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) -static int CurrentTag=GORE_TAG_UPPER+1; -static int CurrentTagUpper=GORE_TAG_UPPER; +static int CurrentTag = GORE_TAG_UPPER + 1; +static int CurrentTagUpper = GORE_TAG_UPPER; -static std::map GoreRecords; -static std::map,int> GoreTagsTemp; // this is a surface index to gore tag map used only - // temporarily during the generation phase so we reuse gore tags per LOD +static std::map GoreRecords; +static std::map, int> GoreTagsTemp; // this is a surface index to gore tag map used only + // temporarily during the generation phase so we reuse gore tags per LOD int goreModelIndex; -static cvar_t *cg_g2MarksAllModels=NULL; +static cvar_t *cg_g2MarksAllModels = NULL; GoreTextureCoordinates *FindGoreRecord(int tag); -static inline void DestroyGoreTexCoordinates(int tag) -{ +static inline void DestroyGoreTexCoordinates(int tag) { GoreTextureCoordinates *gTC = FindGoreRecord(tag); - if (!gTC) - { + if (!gTC) { return; } gTC->~GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } -//TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all +// TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all #define MAX_GORE_RECORDS (500) -int AllocGoreRecord() -{ - while (GoreRecords.size()>MAX_GORE_RECORDS) - { - int tagHigh=(*GoreRecords.begin()).first&GORE_TAG_MASK; - std::map::iterator it; +int AllocGoreRecord() { + while (GoreRecords.size() > MAX_GORE_RECORDS) { + int tagHigh = (*GoreRecords.begin()).first & GORE_TAG_MASK; + std::map::iterator it; GoreTextureCoordinates *gTC; it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); - while (GoreRecords.size()) - { - if (((*GoreRecords.begin()).first&GORE_TAG_MASK)!=tagHigh) - { + while (GoreRecords.size()) { + if (((*GoreRecords.begin()).first & GORE_TAG_MASK) != tagHigh) { break; } it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); } } - int ret=CurrentTag; - GoreRecords[CurrentTag]=GoreTextureCoordinates(); + int ret = CurrentTag; + GoreRecords[CurrentTag] = GoreTextureCoordinates(); CurrentTag++; return ret; } -void ResetGoreTag() -{ +void ResetGoreTag() { GoreTagsTemp.clear(); - CurrentTag=CurrentTagUpper; - CurrentTagUpper+=GORE_TAG_UPPER; + CurrentTag = CurrentTagUpper; + CurrentTagUpper += GORE_TAG_UPPER; } -GoreTextureCoordinates *FindGoreRecord(int tag) -{ - std::map::iterator i=GoreRecords.find(tag); - if (i!=GoreRecords.end()) - { +GoreTextureCoordinates *FindGoreRecord(int tag) { + std::map::iterator i = GoreRecords.find(tag); + if (i != GoreRecords.end()) { return &(*i).second; } return 0; } -void *G2_GetGoreRecord(int tag) -{ - return FindGoreRecord(tag); -} +void *G2_GetGoreRecord(int tag) { return FindGoreRecord(tag); } -void DeleteGoreRecord(int tag) -{ +void DeleteGoreRecord(int tag) { DestroyGoreTexCoordinates(tag); GoreRecords.erase(tag); } -static int CurrentGoreSet=1; // this is a UUID for gore sets -static std::map GoreSets; // map from uuid to goreset +static int CurrentGoreSet = 1; // this is a UUID for gore sets +static std::map GoreSets; // map from uuid to goreset -CGoreSet *FindGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { +CGoreSet *FindGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { return (*f).second; } return 0; } -CGoreSet *NewGoreSet() -{ - CGoreSet *ret=new CGoreSet(CurrentGoreSet++); - GoreSets[ret->mMyGoreSetTag]=ret; +CGoreSet *NewGoreSet() { + CGoreSet *ret = new CGoreSet(CurrentGoreSet++); + GoreSets[ret->mMyGoreSetTag] = ret; ret->mRefCount = 1; return ret; } -void DeleteGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { - if ( (*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0 ) - { +void DeleteGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { + if ((*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0) { delete (*f).second; GoreSets.erase(f); - } - else - { + } else { (*f).second->mRefCount--; } } } - -CGoreSet::~CGoreSet() -{ - std::multimap::iterator i; - for (i=mGoreRecords.begin();i!=mGoreRecords.end();++i) - { +CGoreSet::~CGoreSet() { + std::multimap::iterator i; + for (i = mGoreRecords.begin(); i != mGoreRecords.end(); ++i) { DeleteGoreRecord((*i).second.mGoreTag); } }; #endif // _SOF2 -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache); -class CTraceSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - model_t *currentModel; - int lod; - vec3_t rayStart; - vec3_t rayEnd; - CollisionRecord_t *collRecMap; - int entNum; - int modelIndex; - skin_t *skin; - shader_t *cust_shader; - size_t *TransformedVertsArray; - int traceFlags; - bool hitOne; - float m_fRadius; +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache); +class CTraceSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + model_t *currentModel; + int lod; + vec3_t rayStart; + vec3_t rayEnd; + CollisionRecord_t *collRecMap; + int entNum; + int modelIndex; + skin_t *skin; + shader_t *cust_shader; + size_t *TransformedVertsArray; + int traceFlags; + bool hitOne; + float m_fRadius; #ifdef _G2_GORE - //gore application thing - float ssize; - float tsize; - float theta; - int goreShader; - CGhoul2Info *ghoul2info; + // gore application thing + float ssize; + float tsize; + float theta; + int goreShader; + CGhoul2Info *ghoul2info; // Procedural-gore application things - SSkinGoreData *gore; + SSkinGoreData *gore; #endif - CTraceSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - int initlod, - vec3_t initrayStart, - vec3_t initrayEnd, - CollisionRecord_t *initcollRecMap, - int initentNum, - int initmodelIndex, - skin_t *initskin, - shader_t *initcust_shader, - size_t *initTransformedVertsArray, - int inittraceFlags, + CTraceSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, model_t *initcurrentModel, int initlod, vec3_t initrayStart, vec3_t initrayEnd, + CollisionRecord_t *initcollRecMap, int initentNum, int initmodelIndex, skin_t *initskin, shader_t *initcust_shader, + size_t *initTransformedVertsArray, int inittraceFlags, #ifdef _G2_GORE - float fRadius, - float initssize, - float inittsize, - float inittheta, - int initgoreShader, - CGhoul2Info *initghoul2info, - SSkinGoreData *initgore): + float fRadius, float initssize, float inittsize, float inittheta, int initgoreShader, CGhoul2Info *initghoul2info, SSkinGoreData *initgore) + : #else - float fRadius): + float fRadius) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - currentModel(initcurrentModel), - lod(initlod), - collRecMap(initcollRecMap), - entNum(initentNum), - modelIndex(initmodelIndex), - skin(initskin), - cust_shader(initcust_shader), - TransformedVertsArray(initTransformedVertsArray), - traceFlags(inittraceFlags), + surfaceNum(initsurfaceNum), rootSList(initrootSList), currentModel(initcurrentModel), lod(initlod), collRecMap(initcollRecMap), entNum(initentNum), + modelIndex(initmodelIndex), skin(initskin), cust_shader(initcust_shader), TransformedVertsArray(initTransformedVertsArray), + traceFlags(inittraceFlags), #ifdef _G2_GORE - m_fRadius(fRadius), - ssize(initssize), - tsize(inittsize), - theta(inittheta), - goreShader(initgoreShader), - ghoul2info(initghoul2info), - gore(initgore) + m_fRadius(fRadius), ssize(initssize), tsize(inittsize), theta(inittheta), goreShader(initgoreShader), ghoul2info(initghoul2info), gore(initgore) #else - m_fRadius(fRadius) + m_fRadius(fRadius) #endif { VectorCopy(initrayStart, rayStart); VectorCopy(initrayEnd, rayEnd); hitOne = false; } - }; // assorted Ghoul 2 functions. // list all surfaces associated with a model -void G2_List_Model_Surfaces(const char *fileName) -{ - int i, x; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - mdxmSurfHierarchy_t *surf; +void G2_List_Model_Surfaces(const char *fileName) { + int i, x; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + mdxmSurfHierarchy_t *surf; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); mdxmSurface_t *surface = (mdxmSurface_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsLODs + sizeof(mdxmLOD_t)); - for ( x = 0 ; x < mod_m->mdxm->numSurfaces ; x++) - { + for (x = 0; x < mod_m->mdxm->numSurfaces; x++) { Com_Printf("Surface %i Name %s\n", x, surf->name); - if ( r_verbose->integer ) - { - Com_Printf("Num Descendants %i\n", surf->numChildren); - for (i=0; inumChildren; i++) - { + if (r_verbose->integer) { + Com_Printf("Num Descendants %i\n", surf->numChildren); + for (i = 0; i < surf->numChildren; i++) { Com_Printf("Descendant %i\n", surf->childIndexes[i]); } } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); - surface =(mdxmSurface_t *)( (byte *)surface + surface->ofsEnd ); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); + surface = (mdxmSurface_t *)((byte *)surface + surface->ofsEnd); } - } // list all bones associated with a model -void G2_List_Model_Bones(const char *fileName, int frame) -{ - int x, i; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); -// mdxaFrame_t *aframe=0; -// int frameSize; - mdxaHeader_t *header = mod_a->mdxa; +void G2_List_Model_Bones(const char *fileName, int frame) { + int x, i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + // mdxaFrame_t *aframe=0; + // int frameSize; + mdxaHeader_t *header = mod_a->mdxa; // figure out where the offset list is offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); -// frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); + // frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); -// aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); + // aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); // walk each bone and list it's name - for (x=0; x< mod_a->mdxa->numBones; x++) - { + for (x = 0; x < mod_a->mdxa->numBones; x++) { skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[x]); Com_Printf("Bone %i Name %s\n", x, skel->name); Com_Printf("X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); // if we are in verbose mode give us more details - if ( r_verbose->integer ) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); - for (i=0; inumChildren; i++) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); + if (r_verbose->integer) { + Com_Printf("Num Descendants %i\n", skel->numChildren); + for (i = 0; i < skel->numChildren; i++) { + Com_Printf("Num Descendants %i\n", skel->numChildren); } } } } - /************************************************************************************************ * G2_GetAnimFileName * obtain the .gla filename for a model @@ -341,103 +274,92 @@ void G2_List_Model_Bones(const char *fileName, int frame) * true if we successfully obtained a filename, false otherwise * ************************************************************************************************/ -qboolean G2_GetAnimFileName(const char *fileName, char **filename) -{ +qboolean G2_GetAnimFileName(const char *fileName, char **filename) { // find the model we want - model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); - if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) - { + if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) { *filename = mod->mdxm->animName; return qtrue; } return qfalse; } - ///////////////////////////////////////////////////////////////////// // // Code for collision detection for models gameside // ///////////////////////////////////////////////////////////////////// -int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) -{ +int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) { int returnLod = useLod; - // if we are overriding the LOD at top level, then we can afford to only check this level of model - if (ghoul2.mLodBias > returnLod) - { - returnLod = ghoul2.mLodBias; - } -// assert(G2_MODEL_OK(&ghoul2)); + // if we are overriding the LOD at top level, then we can afford to only check this level of model + if (ghoul2.mLodBias > returnLod) { + returnLod = ghoul2.mLodBias; + } + // assert(G2_MODEL_OK(&ghoul2)); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - //what about r_lodBias? + // what about r_lodBias? // now ensure that we haven't selected a lod that doesn't exist for this model - if ( returnLod >= ghoul2.currentModel->mdxm->numLODs ) - { - returnLod = ghoul2.currentModel->mdxm->numLODs - 1; - } + if (returnLod >= ghoul2.currentModel->mdxm->numLODs) { + returnLod = ghoul2.currentModel->mdxm->numLODs - 1; + } return returnLod; } -void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray,CBoneCache *boneCache) -{ - int j, k; - mdxmVertex_t *v; - float *TransformedVerts; +void R_TransformEachSurface(const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray, CBoneCache *boneCache) { + int j, k; + mdxmVertex_t *v; + float *TransformedVerts; // // deform the vertexes by the lerped bones // - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); // alloc some space for the transformed verts to get put in TransformedVerts = (float *)G2VertSpace->MiniHeapAlloc(surface->numVerts * 5 * 4); TransformedVertsArray[surface->thisSurfaceIndex] = (size_t)TransformedVerts; - if (!TransformedVerts) - { + if (!TransformedVerts) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } // whip through and actually transform each vertex const int numVerts = surface->numVerts; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // optimisation issue - if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) - { - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// mdxmWeight_t *w; + if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) { + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } int pos = j * 5; @@ -449,38 +371,34 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } - } - else - { + } else { int pos = 0; - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// const mdxmWeight_t *w; + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // const mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } // copy tranformed verts into temp space @@ -491,48 +409,43 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos++] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } } } -void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) -{ - int i; +void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, + IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) { + int i; assert(currentModel); assert(currentModel->mdxm); // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void*)currentModel, surfaceNum, lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { + if (!offFlags) { R_TransformEachSurface(surface, scale, G2VertSpace, TransformedVertArray, boneCache); } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { G2_TransformSurfaces(surfInfo->childIndexes[i], rootSList, boneCache, currentModel, lod, scale, G2VertSpace, TransformedVertArray, secondTimeAround); } } @@ -544,72 +457,59 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, IHeapAllocator *G2VertSpace, int useLod) #endif { - int i, lod; - vec3_t correctScale; - qboolean firstModelOnly = qfalse; + int i, lod; + vec3_t correctScale; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, ""); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe - if (!scale[0]) - { + if (!scale[0]) { correctScale[0] = 1.0; } - if (!scale[1]) - { + if (!scale[1]) { correctScale[1] = 1.0; } - if (!scale[2]) - { + if (!scale[2]) { correctScale[2] = 1.0; } // walk each possible model for this entity and try rendering it out - for (i=0; i=g.currentModel->numLods) - { + if (lod >= g.currentModel->numLods) { g.mTransformedVertsArray = 0; - if ( firstModelOnly ) - { + if (firstModelOnly) { // we don't really need to do multiple models for gore. return; } - //do the rest + // do the rest continue; } - } - else - { + } else { #endif lod = G2_DecideTraceLod(g, useLod); #ifdef _G2_GORE @@ -617,25 +517,22 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, #endif // give us space for the transformed vertex array to be put in - if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) - { //do not stomp if we're using zone space - g.mTransformedVertsArray = (size_t*)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof (size_t)); - if (!g.mTransformedVertsArray) - { + if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) { // do not stomp if we're using zone space + g.mTransformedVertsArray = (size_t *)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof(size_t)); + if (!g.mTransformedVertsArray) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } } - memset(g.mTransformedVertsArray, 0, g.currentModel->mdxm->numSurfaces * sizeof (size_t)); + memset(g.mTransformedVertsArray, 0, g.currentModel->mdxm->numSurfaces * sizeof(size_t)); - G2_FindOverrideSurface(-1,g.mSlist); //reset the quick surface override lookup; + G2_FindOverrideSurface(-1, g.mSlist); // reset the quick surface override lookup; // recursively call the model surface transform - G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); + G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); #ifdef _G2_GORE - if (ApplyGore && firstModelOnly) - { + if (ApplyGore && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -643,11 +540,9 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, } } - // work out how much space a triangle takes -static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) -{ - vec3_t cross, ab, cb; +static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) { + vec3_t cross, ab, cb; VectorSubtract(A, B, ab); VectorSubtract(C, B, cb); @@ -657,43 +552,34 @@ static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) } // actually determine the S and T of the coordinate we hit in a given poly -static void G2_BuildHitPointST( const vec3_t A, const float SA, const float TA, - const vec3_t B, const float SB, const float TB, - const vec3_t C, const float SC, const float TC, - const vec3_t P, float *s, float *t,float &bary_i,float &bary_j) -{ - float areaABC = G2_AreaOfTri(A, B, C); +static void G2_BuildHitPointST(const vec3_t A, const float SA, const float TA, const vec3_t B, const float SB, const float TB, const vec3_t C, const float SC, + const float TC, const vec3_t P, float *s, float *t, float &bary_i, float &bary_j) { + float areaABC = G2_AreaOfTri(A, B, C); float i = G2_AreaOfTri(P, B, C) / areaABC; - bary_i=i; + bary_i = i; float j = G2_AreaOfTri(A, P, C) / areaABC; - bary_j=j; + bary_j = j; float k = G2_AreaOfTri(A, B, P) / areaABC; *s = SA * i + SB * j + SC * k; *t = TA * i + TB * j + TC * k; - *s=fmod(*s, 1); - if (*s< 0) - { - *s+= 1.0; + *s = fmod(*s, 1); + if (*s < 0) { + *s += 1.0; } - *t=fmod(*t, 1); - if (*t< 0) - { - *t+= 1.0; + *t = fmod(*t, 1); + if (*t < 0) { + *t += 1.0; } - } - // routine that works out given a ray whether or not it hits a poly -qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, - const vec3_t A, const vec3_t B, const vec3_t C, - qboolean backFaces,qboolean frontFaces,vec3_t returnedPoint,vec3_t returnedNormal, float *denom) -{ - static const float tiny=1E-10f; +qboolean G2_SegmentTriangleTest(const vec3_t start, const vec3_t end, const vec3_t A, const vec3_t B, const vec3_t C, qboolean backFaces, qboolean frontFaces, + vec3_t returnedPoint, vec3_t returnedNormal, float *denom) { + static const float tiny = 1E-10f; vec3_t returnedNormalT; vec3_t edgeAC; @@ -705,11 +591,11 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t ray; VectorSubtract(end, start, ray); - *denom=DotProduct(ray, returnedNormal); + *denom = DotProduct(ray, returnedNormal); - if (fabs(*denom)0)|| // not accepting back faces - (!frontFaces && *denom<0)) //not accepting front faces + if (fabs(*denom) < tiny || // triangle parallel to ray + (!backFaces && *denom > 0) || // not accepting back faces + (!frontFaces && *denom < 0)) // not accepting front faces { return qfalse; } @@ -717,10 +603,9 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t toPlane; VectorSubtract(A, start, toPlane); - float t=DotProduct(toPlane, returnedNormal)/ *denom; + float t = DotProduct(toPlane, returnedNormal) / *denom; - if (t<0.0f||t>1.0f) - { + if (t < 0.0f || t > 1.0f) { return qfalse; // off segment } @@ -740,323 +625,277 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t temp; CrossProduct(edgePA, edgePB, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePC, edgePA, temp); - if (DotProduct(temp,returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePB, edgePC, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } return qtrue; } #ifdef _G2_GORE -struct SVertexTemp -{ +struct SVertexTemp { int flags; int touch; int newindex; float tex[2]; - SVertexTemp() - { - touch=0; - } + SVertexTemp() { touch = 0; } }; #define MAX_GORE_VERTS (3000) static SVertexTemp GoreVerts[MAX_GORE_VERTS]; static int GoreIndexCopy[MAX_GORE_VERTS]; -static int GoreTouch=1; +static int GoreTouch = 1; #define MAX_GORE_INDECIES (6000) static int GoreIndecies[MAX_GORE_INDECIES]; #define GORE_MARGIN (0.0f) -int G2API_GetTime(int argTime); +int G2API_GetTime(int argTime); // now we at poly level, check each model space transformed poly against the model world transfomed ray -void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) -{ - int j; +void G2_GorePolys(const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + CrossProduct(TS.rayEnd, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(TS.rayEnd, basis2, basis1); } - CrossProduct(TS.rayEnd,basis1,basis2); + CrossProduct(TS.rayEnd, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil - assert(DotProduct(basis1,basis1)>.0001f); - assert(DotProduct(basis2,basis2)>.0001f); + assert(DotProduct(basis1, basis1) > .0001f); + assert(DotProduct(basis2, basis2) > .0001f); VectorNormalize(basis1); VectorNormalize(basis2); - float c=cos(TS.theta); - float s=sin(TS.theta); + float c = cos(TS.theta); + float s = sin(TS.theta); - VectorScale(basis1,.5f*c/TS.tsize,taxis); - VectorMA(taxis,.5f*s/TS.tsize,basis2,taxis); + VectorScale(basis1, .5f * c / TS.tsize, taxis); + VectorMA(taxis, .5f * s / TS.tsize, basis2, taxis); - VectorScale(basis1,-.5f*s/TS.ssize,saxis); - VectorMA(saxis,.5f*c/TS.ssize,basis2,saxis); + VectorScale(basis1, -.5f * s / TS.ssize, saxis); + VectorMA(saxis, .5f * c / TS.ssize, basis2, saxis); float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; int numVerts = surface->numVerts; - int flags=15; - assert(numVertsGORE_MARGIN) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + float s = DotProduct(delta, saxis) + 0.5f; + float t = DotProduct(delta, taxis) + 0.5f; + int vflags = 0; + if (s > GORE_MARGIN) { + vflags |= 1; } - if (s<1.0f-GORE_MARGIN) - { - vflags|=2; + if (s < 1.0f - GORE_MARGIN) { + vflags |= 2; } - if (t>GORE_MARGIN) - { - vflags|=4; + if (t > GORE_MARGIN) { + vflags |= 4; } - if (t<1.0f-GORE_MARGIN) - { - vflags|=8; + if (t < 1.0f - GORE_MARGIN) { + vflags |= 8; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; - GoreVerts[j].tex[0]=s; - GoreVerts[j].tex[1]=t; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; + GoreVerts[j].tex[0] = s; + GoreVerts[j].tex[1] = t; } - if (flags) - { + if (flags) { return; // completely off the gore splotch. } - int numTris,newNumTris,newNumVerts; + int numTris, newNumTris, newNumVerts; numTris = surface->numTriangles; - mdxmTriangle_t *tris; - tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + mdxmTriangle_t *tris; + tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; - newNumTris=0; - newNumVerts=0; + newNumTris = 0; + newNumVerts = 0; GoreTouch++; - if (!TS.gore) - { + if (!TS.gore) { return; } - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 15 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; + if (flags) { continue; } - if (!TS.gore->frontFaces || !TS.gore->backFaces) - { + if (!TS.gore->frontFaces || !TS.gore->backFaces) { // we need to back/front face cull - vec3_t e1,e2,n; + vec3_t e1, e2, n; - VectorSubtract(&verts[tris[j].indexes[1]*5],&verts[tris[j].indexes[0]*5],e1); - VectorSubtract(&verts[tris[j].indexes[2]*5],&verts[tris[j].indexes[0]*5],e2); - CrossProduct(e1,e2,n); - if (DotProduct(TS.rayEnd,n)>0.0f) - { - if (!TS.gore->frontFaces) - { + VectorSubtract(&verts[tris[j].indexes[1] * 5], &verts[tris[j].indexes[0] * 5], e1); + VectorSubtract(&verts[tris[j].indexes[2] * 5], &verts[tris[j].indexes[0] * 5], e2); + CrossProduct(e1, e2, n); + if (DotProduct(TS.rayEnd, n) > 0.0f) { + if (!TS.gore->frontFaces) { continue; } - } - else - { - if (!TS.gore->backFaces) - { + } else { + if (!TS.gore->backFaces) { continue; } } - } int k; - assert(newNumTris*3+3,int>::iterator f=GoreTagsTemp.find(std::make_pair(goreModelIndex,TS.surfaceNum)); - if (f==GoreTagsTemp.end()) // need to generate a record + std::map, int>::iterator f = GoreTagsTemp.find(std::make_pair(goreModelIndex, TS.surfaceNum)); + if (f == GoreTagsTemp.end()) // need to generate a record { - newTag=AllocGoreRecord(); - CGoreSet *goreSet=0; - if (TS.ghoul2info->mGoreSetTag) - { - goreSet=FindGoreSet(TS.ghoul2info->mGoreSetTag); + newTag = AllocGoreRecord(); + CGoreSet *goreSet = 0; + if (TS.ghoul2info->mGoreSetTag) { + goreSet = FindGoreSet(TS.ghoul2info->mGoreSetTag); } - if (!goreSet) - { - goreSet=NewGoreSet(); - TS.ghoul2info->mGoreSetTag=goreSet->mMyGoreSetTag; + if (!goreSet) { + goreSet = NewGoreSet(); + TS.ghoul2info->mGoreSetTag = goreSet->mMyGoreSetTag; } assert(goreSet); SGoreSurface add; - add.shader=TS.goreShader; - add.mDeleteTime=0; - if (TS.gore->lifeTime) - { - add.mDeleteTime=G2API_GetTime(0) + TS.gore->lifeTime; + add.shader = TS.goreShader; + add.mDeleteTime = 0; + if (TS.gore->lifeTime) { + add.mDeleteTime = G2API_GetTime(0) + TS.gore->lifeTime; } add.mFadeTime = TS.gore->fadeOutTime; add.mFadeRGB = !!(TS.gore->fadeRGB); add.mGoreTag = newTag; - add.mGoreGrowStartTime=G2API_GetTime(0); - if( TS.gore->growDuration == -1) - { - add.mGoreGrowEndTime = -1; // set this to -1 to disable growing - } - else - { + add.mGoreGrowStartTime = G2API_GetTime(0); + if (TS.gore->growDuration == -1) { + add.mGoreGrowEndTime = -1; // set this to -1 to disable growing + } else { add.mGoreGrowEndTime = G2API_GetTime(0) + TS.gore->growDuration; } assert(TS.gore->growDuration != 0); - add.mGoreGrowFactor = ( 1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); //curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; + add.mGoreGrowFactor = + (1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); // curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; - goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum,add)); - GoreTagsTemp[std::make_pair(goreModelIndex,TS.surfaceNum)]=newTag; + goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum, add)); + GoreTagsTemp[std::make_pair(goreModelIndex, TS.surfaceNum)] = newTag; + } else { + newTag = (*f).second; } - else - { - newTag=(*f).second; - } - GoreTextureCoordinates *gore=FindGoreRecord(newTag); - if (gore) - { - assert(sizeof(float)==sizeof(int)); + GoreTextureCoordinates *gore = FindGoreRecord(newTag); + if (gore) { + assert(sizeof(float) == sizeof(int)); // data block format: - unsigned int size= - sizeof(int)+ // num verts - sizeof(int)+ // num tris - sizeof(int)*newNumVerts+ // which verts to copy from original surface - sizeof(float)*4*newNumVerts+ // storgage for deformed verts - sizeof(float)*4*newNumVerts+ // storgage for deformed normal - sizeof(float)*2*newNumVerts+ // texture coordinates - sizeof(int)*newNumTris*3; // new indecies - - int *data=(int *)Z_Malloc ( sizeof(int)*size, TAG_GHOUL2_GORE, qtrue ); - - if ( gore->tex[TS.lod] ) - { + unsigned int size = sizeof(int) + // num verts + sizeof(int) + // num tris + sizeof(int) * newNumVerts + // which verts to copy from original surface + sizeof(float) * 4 * newNumVerts + // storgage for deformed verts + sizeof(float) * 4 * newNumVerts + // storgage for deformed normal + sizeof(float) * 2 * newNumVerts + // texture coordinates + sizeof(int) * newNumTris * 3; // new indecies + + int *data = (int *)Z_Malloc(sizeof(int) * size, TAG_GHOUL2_GORE, qtrue); + + if (gore->tex[TS.lod]) { Z_Free(gore->tex[TS.lod]); } - gore->tex[TS.lod]=(float *)data; - *data++=newNumVerts; - *data++=newNumTris; + gore->tex[TS.lod] = (float *)data; + *data++ = newNumVerts; + *data++ = newNumTris; - memcpy(data,GoreIndexCopy,sizeof(int)*newNumVerts); - data+=newNumVerts*9; // skip verts and normals - float *fdata=(float *)data; + memcpy(data, GoreIndexCopy, sizeof(int) * newNumVerts); + data += newNumVerts * 9; // skip verts and normals + float *fdata = (float *)data; - for (j=0;jtex[TS.lod])*sizeof(int)==size); + data = (int *)fdata; + memcpy(data, GoreIndecies, sizeof(int) * newNumTris * 3); + data += newNumTris * 3; + assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); fdata = (float *)data; // build the entity to gore matrix - VectorCopy(saxis,fdata+0); - VectorCopy(taxis,fdata+4); - VectorCopy(TS.rayEnd,fdata+8); - VectorNormalize(fdata+0); - VectorNormalize(fdata+4); - VectorNormalize(fdata+8); - fdata[3]=-0.5f; // subtract texture center - fdata[7]=-0.5f; - fdata[11]=0.0f; - vec3_t shotOriginInCurrentSpace; // unknown space - TransformPoint(TS.rayStart,shotOriginInCurrentSpace,(mdxaBone_t *)fdata); // dest middle arg + VectorCopy(saxis, fdata + 0); + VectorCopy(taxis, fdata + 4); + VectorCopy(TS.rayEnd, fdata + 8); + VectorNormalize(fdata + 0); + VectorNormalize(fdata + 4); + VectorNormalize(fdata + 8); + fdata[3] = -0.5f; // subtract texture center + fdata[7] = -0.5f; + fdata[11] = 0.0f; + vec3_t shotOriginInCurrentSpace; // unknown space + TransformPoint(TS.rayStart, shotOriginInCurrentSpace, (mdxaBone_t *)fdata); // dest middle arg // this will insure the shot origin in our unknown space is now the shot origin, making it a known space - fdata[3]-=shotOriginInCurrentSpace[0]; - fdata[7]-=shotOriginInCurrentSpace[1]; - fdata[11]-=shotOriginInCurrentSpace[2]; - Inverse_Matrix((mdxaBone_t *)fdata,(mdxaBone_t *)(fdata+12)); // dest 2nd arg - data+=24; + fdata[3] -= shotOriginInCurrentSpace[0]; + fdata[7] -= shotOriginInCurrentSpace[1]; + fdata[11] -= shotOriginInCurrentSpace[2]; + Inverse_Matrix((mdxaBone_t *)fdata, (mdxaBone_t *)(fdata + 12)); // dest 2nd arg + data += 24; -// assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); + // assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); } } #else -struct SVertexTemp -{ +struct SVertexTemp { int flags; -// int touch; -// int newindex; -// float tex[2]; - SVertexTemp() - { -// touch=0; + // int touch; + // int newindex; + // float tex[2]; + SVertexTemp() { + // touch=0; } }; @@ -1065,44 +904,37 @@ static SVertexTemp GoreVerts[MAX_GORE_VERTS]; #endif // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) -{ - int j, numTris; +static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) { + int j, numTris; // whip through and actually transform each vertex - const mdxmTriangle_t *tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); const float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; numTris = surface->numTriangles; - for ( j = 0; j < numTris; j++ ) - { - float face; - vec3_t hitPoint, normal; + for (j = 0; j < numTris; j++) { + float face; + vec3_t hitPoint, normal; // determine actual coords for this triangle const float *point1 = &verts[(tris[j].indexes[0] * 5)]; const float *point2 = &verts[(tris[j].indexes[1] * 5)]; const float *point3 = &verts[(tris[j].indexes[2] * 5)]; // did we hit it? int i; - if (G2_SegmentTriangleTest(TS.rayStart, TS.rayEnd, point1, point2, point3, qtrue, qtrue, hitPoint, normal, &face)) - { // find space in the collision records for this record - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; - if (face>0) - { + if (face > 0) { newCol.mFlags = G2_FRONTFACE; - } - else - { + } else { newCol.mFlags = G2_BACKFACE; } @@ -1119,62 +951,61 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ newCol.mMaterial = newCol.mLocation = 0; // Determine our location within the texture, and barycentric coordinates - G2_BuildHitPointST(point1, point1[3], point1[4], - point2, point2[3], point2[4], - point3, point3[3], point3[4], - hitPoint, &x_pos, &y_pos,newCol.mBarycentricI,newCol.mBarycentricJ); - -/* - const shader_t *shader = 0; - // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit location and hit material info - if ( cust_shader ) - { - shader = cust_shader; - } - else if ( skin ) - { - int j; - - // match the surface name to something in the skin file - shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { - // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = skin->surfaces[j]->shader; - break; - } - } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); - } - - // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little point - if ((shader->hitLocation) || (shader->hitMaterial)) - { - // ok, we have a floating point position. - determine location in data we need to look at - if (shader->hitLocation) - { - newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + - ((int)(y_pos * hitMatReg[shader->hitLocation].height) * hitMatReg[shader->hitLocation].width) + - ((int)(x_pos * hitMatReg[shader->hitLocation].width))); - Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); - } - - if (shader->hitMaterial) - { - newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + - ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * hitMatReg[shader->hitMaterial].width) + - ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); - } - } -*/ + G2_BuildHitPointST(point1, point1[3], point1[4], point2, point2[3], point2[4], point3, point3[3], point3[4], hitPoint, &x_pos, &y_pos, + newCol.mBarycentricI, newCol.mBarycentricJ); + + /* + const shader_t *shader = 0; + // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit + location and hit material info if ( cust_shader ) + { + shader = cust_shader; + } + else if ( skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little + point if ((shader->hitLocation) || (shader->hitMaterial)) + { + // ok, we have a floating point position. - determine location in data we need to look at + if (shader->hitLocation) + { + newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + + ((int)(y_pos * hitMatReg[shader->hitLocation].height) * + hitMatReg[shader->hitLocation].width) + + ((int)(x_pos * hitMatReg[shader->hitLocation].width))); + Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); + } + + if (shader->hitMaterial) + { + newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + + ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * + hitMatReg[shader->hitMaterial].width) + + ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); + } + } + */ // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } @@ -1182,12 +1013,11 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen - //It happens. And the assert is bugging me. - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen + // It happens. And the assert is bugging me. + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1195,148 +1025,126 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ } // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_RadiusTracePolys( - const mdxmSurface_t *surface, - CTraceSurface &TS - ) -{ - int j; +static bool G2_RadiusTracePolys(const mdxmSurface_t *surface, CTraceSurface &TS) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; vec3_t v3RayDir; VectorSubtract(TS.rayEnd, TS.rayStart, v3RayDir); - CrossProduct(v3RayDir,basis2,basis1); + CrossProduct(v3RayDir, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(v3RayDir,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(v3RayDir, basis2, basis1); } - CrossProduct(v3RayDir,basis1,basis2); + CrossProduct(v3RayDir, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil -// assert(DotProduct(basis1,basis1)>.0001f); -// assert(DotProduct(basis2,basis2)>.0001f); + // assert(DotProduct(basis1,basis1)>.0001f); + // assert(DotProduct(basis2,basis2)>.0001f); VectorNormalize(basis1); VectorNormalize(basis2); - const float c=cos(0.0f);//theta - const float s=sin(0.0f);//theta + const float c = cos(0.0f); // theta + const float s = sin(0.0f); // theta - VectorScale(basis1, 0.5f * c / TS.m_fRadius,taxis); - VectorMA(taxis, 0.5f * s / TS.m_fRadius,basis2,taxis); + VectorScale(basis1, 0.5f * c / TS.m_fRadius, taxis); + VectorMA(taxis, 0.5f * s / TS.m_fRadius, basis2, taxis); - VectorScale(basis1,-0.5f * s /TS.m_fRadius,saxis); - VectorMA( saxis, 0.5f * c /TS.m_fRadius,basis2,saxis); + VectorScale(basis1, -0.5f * s / TS.m_fRadius, saxis); + VectorMA(saxis, 0.5f * c / TS.m_fRadius, basis2, saxis); - const float * const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + const float *const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; const int numVerts = surface->numVerts; - int flags=63; - //rayDir/=lengthSquared(raydir); + int flags = 63; + // rayDir/=lengthSquared(raydir); const float f = VectorLengthSquared(v3RayDir); - v3RayDir[0]/=f; - v3RayDir[1]/=f; - v3RayDir[2]/=f; + v3RayDir[0] /= f; + v3RayDir[1] /= f; + v3RayDir[2] /= f; - for ( j = 0; j < numVerts; j++ ) - { - const int pos=j*5; + for (j = 0; j < numVerts; j++) { + const int pos = j * 5; vec3_t delta; - delta[0]=verts[pos+0]-TS.rayStart[0]; - delta[1]=verts[pos+1]-TS.rayStart[1]; - delta[2]=verts[pos+2]-TS.rayStart[2]; - const float s=DotProduct(delta,saxis)+0.5f; - const float t=DotProduct(delta,taxis)+0.5f; - const float u=DotProduct(delta,v3RayDir); - int vflags=0; - - if (s>0) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + const float s = DotProduct(delta, saxis) + 0.5f; + const float t = DotProduct(delta, taxis) + 0.5f; + const float u = DotProduct(delta, v3RayDir); + int vflags = 0; + + if (s > 0) { + vflags |= 1; } - if (s<1) - { - vflags|=2; + if (s < 1) { + vflags |= 2; } - if (t>0) - { - vflags|=4; + if (t > 0) { + vflags |= 4; } - if (t<1) - { - vflags|=8; + if (t < 1) { + vflags |= 8; } - if (u>0) - { - vflags|=16; + if (u > 0) { + vflags |= 16; } - if (u<1) - { - vflags|=32; + if (u < 1) { + vflags |= 32; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; } - if (flags) - { + if (flags) { return false; // completely off the gore splotch (so presumably hit nothing? -Ste) } const int numTris = surface->numTriangles; - const mdxmTriangle_t * const tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *const tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 63 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; int i; - if (flags) - { + if (flags) { continue; - } - else - { + } else { // we hit a triangle, so init a collision record... // - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; -// if (face>0) -// { - newCol.mFlags = G2_FRONTFACE; -// } -// else -// { -// newCol.mFlags = G2_BACKFACE; -// } - - //get normal from triangle + // if (face>0) + // { + newCol.mFlags = G2_FRONTFACE; + // } + // else + // { + // newCol.mFlags = G2_BACKFACE; + // } + + // get normal from triangle const float *A = &verts[(tris[j].indexes[0] * 5)]; const float *B = &verts[(tris[j].indexes[1] * 5)]; const float *C = &verts[(tris[j].indexes[2] * 5)]; @@ -1353,28 +1161,26 @@ static bool G2_RadiusTracePolys( newCol.mMaterial = newCol.mLocation = 0; // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } - - vec3_t distVect; + vec3_t distVect; #if 0 //i don't know the hitPoint, but let's just assume it's the first vert for now... float *hitPoint = (float *)A; #else - //yeah, I want the collision point. Let's work out the impact point on the triangle. -rww + // yeah, I want the collision point. Let's work out the impact point on the triangle. -rww vec3_t hitPoint; float side, side2; float dist; - float third = -(A[0]*(B[1]*C[2] - C[1]*B[2]) + B[0]*(C[1]*A[2] - A[1]*C[2]) + C[0]*(A[1]*B[2] - B[1]*A[2]) ); + float third = -(A[0] * (B[1] * C[2] - C[1] * B[2]) + B[0] * (C[1] * A[2] - A[1] * C[2]) + C[0] * (A[1] * B[2] - B[1] * A[2])); VectorSubtract(TS.rayEnd, TS.rayStart, distVect); - side = normal[0]*TS.rayStart[0] + normal[1]*TS.rayStart[1] + normal[2]*TS.rayStart[2] + third; - side2 = normal[0]*distVect[0] + normal[1]*distVect[1] + normal[2]*distVect[2]; - dist = side/side2; + side = normal[0] * TS.rayStart[0] + normal[1] * TS.rayStart[1] + normal[2] * TS.rayStart[2] + third; + side2 = normal[0] * distVect[0] + normal[1] * distVect[1] + normal[2] * distVect[2]; + dist = side / side2; VectorMA(TS.rayStart, -dist, distVect, hitPoint); #endif @@ -1387,11 +1193,10 @@ static bool G2_RadiusTracePolys( break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1399,24 +1204,21 @@ static bool G2_RadiusTracePolys( return false; } - // look at a surface and then do the trace on each poly -static void G2_TraceSurfaces(CTraceSurface &TS) -{ - int i; +static void G2_TraceSurfaces(CTraceSurface &TS) { + int i; // back track and get the surfinfo struct for this surface assert(TS.currentModel); assert(TS.currentModel->mdxm); - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); // don't allow recursion if we've already hit a polygon - if (TS.hitOne) - { + if (TS.hitOne) { return; } @@ -1424,39 +1226,28 @@ static void G2_TraceSurfaces(CTraceSurface &TS) int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, try to hit it - if (!offFlags) - { + if (!offFlags) { #ifdef _G2_GORE - if (TS.collRecMap) - { + if (TS.collRecMap) { #endif - if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace + if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace { // .. then use radius check // - if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, - TS - ) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, + TS) && + (TS.traceFlags == G2_RETURNONHIT)) { TS.hitOne = true; return; } - } - else - { + } else { // go away and trace the polys in this surface - if (G2_TracePolys(surface, surfInfo, TS) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_TracePolys(surface, surfInfo, TS) && (TS.traceFlags == G2_RETURNONHIT)) { // ok, we hit one, *and* we want to return instantly because the returnOnHit is set // so indicate we've hit one, so other surfaces don't get hit and return TS.hitOne = true; @@ -1464,124 +1255,108 @@ static void G2_TraceSurfaces(CTraceSurface &TS) } } #ifdef _G2_GORE - } - else - { + } else { G2_GorePolys(surface, TS, surfInfo); } #endif } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren && !TS.hitOne; i++) - { + for (i = 0; i < surfInfo->numChildren && !TS.hitOne; i++) { TS.surfaceNum = surfInfo->childIndexes[i]; G2_TraceSurfaces(TS); } } #ifdef _G2_GORE -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius, float ssize,float tsize,float theta,int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius, float ssize, float tsize, float theta, int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) #else -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius) #endif { - int i, lod; - skin_t *skin; - shader_t *cust_shader; - qboolean firstModelOnly = qfalse; + int i, lod; + skin_t *skin; + shader_t *cust_shader; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, ""); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif // walk each possible model for this entity and try tracing against it - for (i=0; i 0 && ghoul2[i].mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( ghoul2[i].mSkin ); - } - else - { + if (ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(ghoul2[i].mSkin); + } else { skin = NULL; } - lod = G2_DecideTraceLod(ghoul2[i],useLod); + lod = G2_DecideTraceLod(ghoul2[i], useLod); #ifdef _G2_GORE - if ( skipIfLODNotMatch ) - {//we only want to hit this SPECIFIC LOD... - if ( lod != useLod ) - {//doesn't match, skip this model + if (skipIfLODNotMatch) { // we only want to hit this SPECIFIC LOD... + if (lod != useLod) { // doesn't match, skip this model continue; } } #endif - //reset the quick surface override lookup + // reset the quick surface override lookup G2_FindOverrideSurface(-1, ghoul2[i].mSlist); #ifdef _G2_GORE - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); #else - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); #endif // start the surface recursion loop G2_TraceSurfaces(TS); // if we've hit one surface on one model, don't bother doing the rest - if (TS.hitOne) - { + if (TS.hitOne) { break; } #ifdef _G2_GORE - if (!collRecMap&&firstModelOnly) - { + if (!collRecMap && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -1589,29 +1364,25 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli } } -void TransformPoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2]; +void TransformPoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2]; } } -void TransformAndTranslatePoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { +void TransformAndTranslatePoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2] + mat->matrix[i][3]; + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2] + mat->matrix[i][3]; } } - // create a matrix using a set of angles -void Create_Matrix(const float *angle, mdxaBone_t *matrix) -{ - matrix3_t axis; +void Create_Matrix(const float *angle, mdxaBone_t *matrix) { + matrix3_t axis; // convert angles to axis - AnglesToAxis( angle, axis ); + AnglesToAxis(angle, axis); matrix->matrix[0][0] = axis[0][0]; matrix->matrix[1][0] = axis[0][1]; matrix->matrix[2][0] = axis[0][2]; @@ -1627,35 +1398,27 @@ void Create_Matrix(const float *angle, mdxaBone_t *matrix) matrix->matrix[0][3] = 0; matrix->matrix[1][3] = 0; matrix->matrix[2][3] = 0; - - } // given a matrix, generate the inverse of that matrix -void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) -{ +void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) { int i, j; - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - dest->matrix[i][j]=src->matrix[j][i]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + dest->matrix[i][j] = src->matrix[j][i]; } } - for (i = 0; i < 3; i++) - { - dest->matrix[i][3]=0; - for (j = 0; j < 3; j++) - { - dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + for (i = 0; i < 3; i++) { + dest->matrix[i][3] = 0; + for (j = 0; j < 3; j++) { + dest->matrix[i][3] -= dest->matrix[i][j] * src->matrix[j][3]; } } } // generate the world matrix for a given set of angles and origin - called from lots of places -void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) -{ +void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) { Create_Matrix(angles, &worldMatrix); worldMatrix.matrix[0][3] = origin[0]; worldMatrix.matrix[1][3] = origin[1]; @@ -1665,18 +1428,16 @@ void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) } // go away and determine what the pointer for a specific surface definition within the model definition is -void *G2_FindSurface(void *mod_t, int index, int lod) -{ +void *G2_FindSurface(void *mod_t, int index, int lod) { // damn include file dependancies - model_t *mod = (model_t *)mod_t; + model_t *mod = (model_t *)mod_t; // point at first lod list - byte *current = (byte*)((size_t)mod->mdxm + (size_t)mod->mdxm->ofsLODs); + byte *current = (byte *)((size_t)mod->mdxm + (size_t)mod->mdxm->ofsLODs); int i; - //walk the lods - for (i=0; iofsEnd; } @@ -1691,16 +1452,14 @@ void *G2_FindSurface(void *mod_t, int index, int lod) return (void *)current; } -#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) +#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) #define BOLT_SAVE_BLOCK_SIZE (sizeof(boltInfo_t) - sizeof(mdxaBone_t)) #define BONE_SAVE_BLOCK_SIZE sizeof(boneInfo_t) -qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ +qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { // is there anything to save? - if (!ghoul2.size()) - { + if (!ghoul2.size()) { *buffer = (char *)Z_Malloc(4, TAG_GHOUL2, qtrue); int *tempBuffer = (int *)*buffer; *tempBuffer = 0; @@ -1718,8 +1477,7 @@ qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) *size += 4; // start out working out the total size of the buffer we need to allocate int i; // Linux GCC is forcing new scoping rules - for (i=0; i i) && - (nextGhoul2[i].mModelindex != -1) && - (nextGhoul2[i].mBlist.size() > x) && - (nextGhoul2[i].mBlist[x].boneNumber != -1)) - { - boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; + if ((nextGhoul2.size() > i) && (nextGhoul2[i].mModelindex != -1) && (nextGhoul2[i].mBlist.size() > x) && + (nextGhoul2[i].mBlist[x].boneNumber != -1)) { + boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; // does this bone override actually have anything in it, and if it does, is it a bone angles override? - if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) - { - float *nowMatrix = (float*) &bone.matrix; - float *nextMatrix = (float*) &nextBone.matrix; - float *newMatrix = (float*) &bone.newMatrix; + if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) { + float *nowMatrix = (float *)&bone.matrix; + float *nextMatrix = (float *)&nextBone.matrix; + float *newMatrix = (float *)&bone.newMatrix; // now interpolate the matrix - for (int z=0; z < 12; z++) - { - newMatrix[z] = nowMatrix[z] + interpolation * ( nextMatrix[z] - nowMatrix[z] ); + for (int z = 0; z < 12; z++) { + newMatrix[z] = nowMatrix[z] + interpolation * (nextMatrix[z] - nowMatrix[z]); } } - } - else - { + } else { memcpy(&ghoul2[i].mBlist[x].newMatrix, &ghoul2[i].mBlist[x].matrix, sizeof(mdxaBone_t)); } } diff --git a/codemp/rd-dedicated/G2_surfaces.cpp b/codemp/rd-dedicated/G2_surfaces.cpp index 2019e09440..f7800642ab 100644 --- a/codemp/rd-dedicated/G2_surfaces.cpp +++ b/codemp/rd-dedicated/G2_surfaces.cpp @@ -25,43 +25,30 @@ along with this program; if not, see . #include "ghoul2/g2_local.h" #include "tr_local.h" -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - boneInfo_v &initboneList): - - surfaceNum(initsurfaceNum), - boneUsedList(initboneUsedList), - rootSList(initrootSList), - currentModel(initcurrentModel), - boneList(initboneList) { } +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; + + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : + + surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; extern void G2_ConstructUsedBoneList(CConstructBoneList &CBL); - //===================================================================================================================== // Surface List handling routines - so entities can determine what surfaces attached to a model are operational or not. // find a particular surface in the surface override list -surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) -{ +surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) { // look through entire list - for(size_t i=0; imdxm + mod_m->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mod_m->mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surf->name)) - { + for (int i = 0; i < mod_m->mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surf->name)) { *flags = surf->flags; return i; } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } return -1; } - /************************************************************************************************ * G2_FindSurface * find a surface in a ghoul2 surface override list based on it's name @@ -103,41 +86,33 @@ int G2_IsSurfaceLegal(void *mod, const char *surfaceName, int *flags) * pointer to surface if successful, false otherwise * ************************************************************************************************/ -mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, - int *surfIndex/*NULL*/) -{ - int i = 0; +mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, int *surfIndex /*NULL*/) { + int i = 0; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo; + mdxmSurfHierarchy_t *surfInfo; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { assert(0); - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } - // first find if we already have this surface in the list - for (i = slist.size() - 1; i >= 0; i--) - { - if ((slist[i].surface != 10000) && (slist[i].surface != -1)) - { - mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); + // first find if we already have this surface in the list + for (i = slist.size() - 1; i >= 0; i--) { + if ((slist[i].surface != 10000) && (slist[i].surface != -1)) { + mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); // back track and get the surfinfo struct for this surface surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); - // are these the droids we're looking for? - if (!Q_stricmp (surfInfo->name, surfaceName)) - { + // are these the droids we're looking for? + if (!Q_stricmp(surfInfo->name, surfaceName)) { // yup - if (surfIndex) - { + if (surfIndex) { *surfIndex = i; } return surf; @@ -145,33 +120,29 @@ mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const } } // didn't find it - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } // set a named surface offFlags - if it doesn't find a surface with this name in the list then it will add one. -qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) -{ - int surfIndex = -1; - surfaceInfo_t temp_slist_entry; - mdxmSurface_t *surf; +qboolean G2_SetSurfaceOnOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) { + int surfIndex = -1; + surfaceInfo_t temp_slist_entry; + mdxmSurface_t *surf; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { assert(0); return qfalse; } - // first find if we already have this surface in the list + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value // slist[surfIndex].offFlags = offFlags; @@ -180,21 +151,17 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c slist[surfIndex].offFlags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); slist[surfIndex].offFlags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); return qtrue; - } - else - { + } else { // ok, not in the list already - in that case, lets verify this surface exists in the model mesh - int flags; - int surfaceNum = G2_IsSurfaceLegal((void*)mod, surfaceName, &flags); - if (surfaceNum != -1) - { + int flags; + int surfaceNum = G2_IsSurfaceLegal((void *)mod, surfaceName, &flags); + if (surfaceNum != -1) { int newflags = flags; // the only bit we really care about in the incoming flags is the off bit newflags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); newflags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); - if (newflags != flags) - { // insert here then because it changed, no need to add an override otherwise + if (newflags != flags) { // insert here then because it changed, no need to add an override otherwise temp_slist_entry.offFlags = newflags; temp_slist_entry.surface = surfaceNum; @@ -206,26 +173,22 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin) { int j; - const skin_t *skin = R_GetSkinByHandle( renderSkin ); + const skin_t *skin = R_GetSkinByHandle(renderSkin); - ghlInfo->mSlist.clear(); //remove any overrides we had before. + ghlInfo->mSlist.clear(); // remove any overrides we had before. ghlInfo->mMeshFrameNum = 0; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - //FIXME: why is this using the shader name and not the surface name? - if ( !strcmp( ((shader_t *)skin->surfaces[j]->shader)->name, "*off") ) { + // FIXME: why is this using the shader name and not the surface name? + if (!strcmp(((shader_t *)skin->surfaces[j]->shader)->name, "*off")) { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, G2SURFACEFLAG_OFF); - } - else - { - int flags; + } else { + int flags; int surfaceNum = G2_IsSurfaceLegal((void *)ghlInfo->currentModel, skin->surfaces[j]->name, &flags); - if ( (surfaceNum != -1) && (!(flags&G2SURFACEFLAG_OFF)) ) //only turn on if it's not an "_off" surface + if ((surfaceNum != -1) && (!(flags & G2SURFACEFLAG_OFF))) // only turn on if it's not an "_off" surface { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, 0); } @@ -234,105 +197,86 @@ void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) } // return a named surfaces off flags - should tell you if this surface is on or off. -int G2_IsSurfaceOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int surfIndex = -1; - mdxmSurface_t *surf = 0; +int G2_IsSurfaceOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int surfIndex = -1; + mdxmSurface_t *surf = 0; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { return 0; } - // first find if we already have this surface in the list + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value return slist[surfIndex].offFlags; } // ok, we didn't find it in the surface list. Lets look at the original surface then. - mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *) ( (byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy ); + mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *)((byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mod->mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surface->name)) - { + for (int i = 0; i < mod->mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surface->name)) { return surface->flags; } // find the next surface - surface = (mdxmSurfHierarchy_t *)( (byte *)surface + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surface->numChildren ] )); + surface = (mdxmSurfHierarchy_t *)((byte *)surface + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surface->numChildren])); } assert(0); return 0; } -void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) -{ - int i; - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); +void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) { + int i; + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, indicate as such in the active surface list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { + if (!(offFlags & G2SURFACEFLAG_OFF)) { activeSurfaces[surfaceNum] = 1; - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { surfaceNum = surfInfo->childIndexes[i]; G2_FindRecursiveSurface(currentModel, surfaceNum, rootList, activeSurfaces); } - } -void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) -{ +void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; imdxm) - { + if (!mod_m->mdxm) { return qfalse; } // first find if we already have this surface in the list surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) - { + if (surf != -1) { // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) - { + if (ghoul2[modelIndex].mSurfaceRoot == surf) { return qtrue; } @@ -382,11 +322,7 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, activeBones, ghoul2[modelIndex].mSlist, mod_m, ghoul2[modelIndex].mBlist); G2_ConstructUsedBoneList(CBL); @@ -400,24 +336,20 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model if (((int)ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) - { + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) { CGhoul2Info_v *g2i = &ghoul2; G2API_RemoveGhoul2Model((CGhoul2Info_v **)&g2i, i); } } } - //No support for this, for now. + // No support for this, for now. // remember to free what we used Z_Free(activeSurfaces); @@ -425,97 +357,95 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch return (qtrue); } -/* -//g2r if (entstate->ghoul2) - { - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int surf; - int flags; - int *activeSurfaces, *activeBones; - - // did we find a ghoul 2 model or not? - if (!mod_m->mdxm) + /* + //g2r if (entstate->ghoul2) { - return qfalse; - } - - // first find if we already have this surface in the list - surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) - { - // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int surf; + int flags; + int *activeSurfaces, *activeBones; + + // did we find a ghoul 2 model or not? + if (!mod_m->mdxm) { - return qtrue; + return qfalse; } - // set the root surface - ghoul2[modelIndex].mSurfaceRoot = surf; + // first find if we already have this surface in the list + surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); + if (surf != -1) + { + // first see if this ghoul2 model already has this as a root surface + if (ghoul2[modelIndex].mSurfaceRoot == surf) + { + return qtrue; + } + + // set the root surface + ghoul2[modelIndex].mSurfaceRoot = surf; - // ok, now the tricky bits. - // firstly, generate a list of active / on surfaces below the root point + // ok, now the tricky bits. + // firstly, generate a list of active / on surfaces below the root point - // gimme some space to put this list into - activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); - memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); - activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); - memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); + // gimme some space to put this list into + activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); + memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); + activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); + memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); - G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); + G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); - // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + // now generate the used bone list + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, + activeBones, + ghoul2[modelIndex].mSlist, + mod_m, + ghoul2[modelIndex].mBlist); - G2_ConstructUsedBoneList(CBL); + G2_ConstructUsedBoneList(CBL); - // now remove all procedural or override surfaces that refer to surfaces that arent on this list - G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); + // now remove all procedural or override surfaces that refer to surfaces that arent on this list + G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); - // now remove all bones that are pointing at bones that aren't active - G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); + // now remove all bones that are pointing at bones that aren't active + G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); - // then remove all bolts that point at surfaces or bones that *arent* active. - G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); + // then remove all bolts that point at surfaces or bones that *arent* active. + G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); - // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; - // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model - if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + // are we even bolted to anything? + if (ghoul2[i].mModelBoltLink != -1) { - G2API_RemoveGhoul2Model(entstate, i); + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model + if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && + (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + { + G2API_RemoveGhoul2Model(entstate, i); + } } } - } - // remember to free what we used - Z_Free(activeSurfaces); - Z_Free(activeBones); + // remember to free what we used + Z_Free(activeSurfaces); + Z_Free(activeBones); - return (qtrue); + return (qtrue); + } } - } - assert(0);*/ + assert(0);*/ return qfalse; } - extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); -int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ +int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { surfaceInfo_t temp_slist_entry; @@ -523,13 +453,11 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float lod = G2_DecideTraceLod(*(CGhoul2Info *)(ghoul2), lod); // first up, see if we have a free one already set up - look only from the end of the constant surfaces onwards - for (size_t i=0; imSlist.size(); i++) - { + for (size_t i = 0; i < ghoul2->mSlist.size(); i++) { // is the surface count -1? That would indicate it's free - if (ghoul2->mSlist[i].surface == -1) - { + if (ghoul2->mSlist[i].surface == -1) { ghoul2->mSlist[i].offFlags = G2SURFACEFLAG_GENERATED; - ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces + ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces ghoul2->mSlist[i].genBarycentricI = BarycentricI; ghoul2->mSlist[i].genBarycentricJ = BarycentricJ; ghoul2->mSlist[i].genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); @@ -549,34 +477,28 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float ghoul2->mSlist.push_back(temp_slist_entry); - return (ghoul2->mSlist.size() -1 ); + return (ghoul2->mSlist.size() - 1); } -qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) -{ - // did we find it? - if (index != -1) - { - // set us to be the 'not active' state +qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) { + // did we find it? + if (index != -1) { + // set us to be the 'not active' state slist[index].surface = -1; unsigned int newSize = slist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=slist.size()-1; i>-1; i--) - { - if (slist[i].surface == -1) - { + for (int i = slist.size() - 1; i > -1; i--) { + if (slist[i].surface == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != slist.size()) - { + if (newSize != slist.size()) { // yes, so lets do it slist.resize(newSize); } @@ -590,38 +512,32 @@ qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) return qfalse; } - -int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = 0; +int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = 0; // walk each surface and see if this index is listed in it's children surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, index, 0); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->parentIndex; - } -int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int flags; +int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int flags; return G2_IsSurfaceLegal(mod, surfaceName, &flags); } -int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) -{ - int flags = 0;//, surfFlags = 0; - int surfIndex = 0; +int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) { + int flags = 0; //, surfFlags = 0; + int surfIndex = 0; assert(ghlInfo->currentModel); assert(ghlInfo->currentModel->mdxm); - if (!ghlInfo->currentModel->mdxm) - { + if (!ghlInfo->currentModel->mdxm) { return -1; } @@ -629,55 +545,47 @@ int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceI // find the original surface in the surface list int surfNum = G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, surfaceName, &flags); - if ( surfNum != -1 ) - {//must be legal - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); + if (surfNum != -1) { // must be legal + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); surfNum = surfInfo->parentIndex; // walk the surface hierarchy up until we hit the root - while (surfNum != -1) - { - const mdxmSurface_t *parentSurf; - int parentFlags = 0; - const mdxmSurfHierarchy_t *parentSurfInfo; + while (surfNum != -1) { + const mdxmSurface_t *parentSurf; + int parentFlags = 0; + const mdxmSurfHierarchy_t *parentSurfInfo; parentSurfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); // find the original surface in the surface list - //G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags + // G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, parentSurfInfo->name, &parentFlags); // now see if we already have overriden this surface in the slist parentSurf = G2_FindSurface(ghlInfo, slist, parentSurfInfo->name, &surfIndex); - if (parentSurf) - { + if (parentSurf) { // set descendants value parentFlags = slist[surfIndex].offFlags; } // now we have the parent flags, lets see if any have the 'no descendants' flag set - if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) { flags |= G2SURFACEFLAG_OFF; break; } // set up scan of next parent surfNum = parentSurfInfo->parentIndex; } - } - else - { + } else { return -1; } - if ( flags == 0 ) - {//it's not being overridden by a parent + if (flags == 0) { // it's not being overridden by a parent // now see if we already have overriden this surface in the slist const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value flags = slist[surfIndex].offFlags; } - // ok, at this point in flags we have what this surface is set to, and the index of the surface itself + // ok, at this point in flags we have what this surface is set to, and the index of the surface itself } return flags; } diff --git a/codemp/rd-dedicated/tr_backend.cpp b/codemp/rd-dedicated/tr_backend.cpp index 08bfa3cf93..9c0b5b4272 100644 --- a/codemp/rd-dedicated/tr_backend.cpp +++ b/codemp/rd-dedicated/tr_backend.cpp @@ -23,14 +23,14 @@ along with this program; if not, see . #include "tr_local.h" -backEndData_t *backEndData; -backEndState_t backEnd; +backEndData_t *backEndData; +backEndState_t backEnd; bool tr_stencilled = false; -extern qboolean tr_distortionPrePost; //tr_shadows.cpp -extern qboolean tr_distortionNegate; //tr_shadows.cpp -extern void RB_CaptureScreenImage(void); //tr_shadows.cpp -extern void RB_DistortionFill(void); //tr_shadows.cpp +extern qboolean tr_distortionPrePost; // tr_shadows.cpp +extern qboolean tr_distortionNegate; // tr_shadows.cpp +extern void RB_CaptureScreenImage(void); // tr_shadows.cpp +extern void RB_DistortionFill(void); // tr_shadows.cpp // Whether we are currently rendering only glowing objects or not. bool g_bRenderGlowingObjects = false; diff --git a/codemp/rd-dedicated/tr_ghoul2.cpp b/codemp/rd-dedicated/tr_ghoul2.cpp index 0797f76eed..e759326081 100644 --- a/codemp/rd-dedicated/tr_ghoul2.cpp +++ b/codemp/rd-dedicated/tr_ghoul2.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -#include "client/client.h" //FIXME!! EVIL - just include the definitions needed +#include "client/client.h" //FIXME!! EVIL - just include the definitions needed #include "tr_local.h" #include "qcommon/matcomp.h" #include "qcommon/qcommon.h" @@ -32,7 +32,7 @@ along with this program; if not, see . #include "qcommon/disablewarnings.h" -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) #ifdef G2_PERFORMANCE_ANALYSIS #include "qcommon/timing.h" @@ -59,8 +59,7 @@ int G2Time_RB_SurfaceGhoul = 0; int G2Time_G2_SetupModelPointers = 0; int G2Time_PreciseFrame = 0; -void G2Time_ResetTimers(void) -{ +void G2Time_ResetTimers(void) { G2Time_RenderSurfaces = 0; G2Time_R_AddGHOULSurfaces = 0; G2Time_G2_TransformGhoulBones = 0; @@ -73,39 +72,32 @@ void G2Time_ResetTimers(void) G2PerformanceCounter_G2_TransformGhoulBones = 0; } -void G2Time_ReportTimers(void) -{ - Com_Printf("\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: %i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: %i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", - G2Time_RenderSurfaces, - G2Time_R_AddGHOULSurfaces, - G2Time_G2_TransformGhoulBones, - G2Time_G2_ProcessGeneratedSurfaceBolts, - G2Time_ProcessModelBoltSurfaces, - G2Time_G2_ConstructGhoulSkeleton, - G2Time_RB_SurfaceGhoul, - G2Time_G2_SetupModelPointers, - G2Time_PreciseFrame, - G2PerformanceCounter_G2_TransformGhoulBones - ); +void G2Time_ReportTimers(void) { + Com_Printf("\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: " + "%i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: " + "%i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", + G2Time_RenderSurfaces, G2Time_R_AddGHOULSurfaces, G2Time_G2_TransformGhoulBones, G2Time_G2_ProcessGeneratedSurfaceBolts, + G2Time_ProcessModelBoltSurfaces, G2Time_G2_ConstructGhoulSkeleton, G2Time_RB_SurfaceGhoul, G2Time_G2_SetupModelPointers, G2Time_PreciseFrame, + G2PerformanceCounter_G2_TransformGhoulBones); } #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef __linux__ #include #else #include #endif -//rww - RAGDOLL_END +// rww - RAGDOLL_END -bool HackadelicOnClient=false; // means this is a render traversal +bool HackadelicOnClient = false; // means this is a render traversal qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); -extern cvar_t *r_Ghoul2AnimSmooth; -extern cvar_t *r_Ghoul2UnSqashAfterSmooth; +extern cvar_t *r_Ghoul2AnimSmooth; +extern cvar_t *r_Ghoul2UnSqashAfterSmooth; #if 0 static inline int G2_Find_Bone_ByNum(const model_t *mod, boneInfo_v &blist, const int boneNum) @@ -125,117 +117,89 @@ static inline int G2_Find_Bone_ByNum(const model_t *mod, boneInfo_v &blist, cons } #endif -const static mdxaBone_t identityMatrix = -{ - { - { 0.0f, -1.0f, 0.0f, 0.0f }, - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } -}; +const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; // I hate doing this, but this is the simplest way to get this into the routines it needs to be -mdxaBone_t worldMatrix; -mdxaBone_t worldMatrixInv; +mdxaBone_t worldMatrix; +mdxaBone_t worldMatrixInv; #ifdef _G2_GORE -qhandle_t goreShader=-1; +qhandle_t goreShader = -1; #endif -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - boneInfo_v &initboneList): +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; - surfaceNum(initsurfaceNum), - boneUsedList(initboneUsedList), - rootSList(initrootSList), - currentModel(initcurrentModel), - boneList(initboneList) { } + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : + surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; -class CTransformBone -{ -public: - int touch; // for minimal recalculation - //rww - RAGDOLL_BEGIN - int touchRender; - //rww - RAGDOLL_END - mdxaBone_t boneMatrix; //final matrix - int parent; // only set once - - CTransformBone() - { - touch=0; - //rww - RAGDOLL_BEGIN +class CTransformBone { + public: + int touch; // for minimal recalculation + // rww - RAGDOLL_BEGIN + int touchRender; + // rww - RAGDOLL_END + mdxaBone_t boneMatrix; // final matrix + int parent; // only set once + + CTransformBone() { + touch = 0; + // rww - RAGDOLL_BEGIN touchRender = 0; - //rww - RAGDOLL_END + // rww - RAGDOLL_END } - }; -struct SBoneCalc -{ - int newFrame; - int currentFrame; - float backlerp; - float blendFrame; - int blendOldFrame; - bool blendMode; - float blendLerp; +struct SBoneCalc { + int newFrame; + int currentFrame; + float backlerp; + float blendFrame; + int blendOldFrame; + bool blendMode; + float blendLerp; }; class CBoneCache; -void G2_TransformBone(int index,CBoneCache &CB); +void G2_TransformBone(int index, CBoneCache &CB); -class CBoneCache -{ - void SetRenderMatrix(CTransformBone *bone) { - } +class CBoneCache { + void SetRenderMatrix(CTransformBone *bone) {} - void EvalLow(int index) - { - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { + void EvalLow(int index) { + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { // need to evaluate the bone - assert((mFinalBones[index].parent>=0&&mFinalBones[index].parent<(int)mFinalBones.size())||(index==0&&mFinalBones[index].parent==-1)); - if (mFinalBones[index].parent>=0) - { + assert((mFinalBones[index].parent >= 0 && mFinalBones[index].parent < (int)mFinalBones.size()) || (index == 0 && mFinalBones[index].parent == -1)); + if (mFinalBones[index].parent >= 0) { EvalLow(mFinalBones[index].parent); // make sure parent is evaluated - SBoneCalc &par=mBones[mFinalBones[index].parent]; - mBones[index].newFrame=par.newFrame; - mBones[index].currentFrame=par.currentFrame; - mBones[index].backlerp=par.backlerp; - mBones[index].blendFrame=par.blendFrame; - mBones[index].blendOldFrame=par.blendOldFrame; - mBones[index].blendMode=par.blendMode; - mBones[index].blendLerp=par.blendLerp; + SBoneCalc &par = mBones[mFinalBones[index].parent]; + mBones[index].newFrame = par.newFrame; + mBones[index].currentFrame = par.currentFrame; + mBones[index].backlerp = par.backlerp; + mBones[index].blendFrame = par.blendFrame; + mBones[index].blendOldFrame = par.blendOldFrame; + mBones[index].blendMode = par.blendMode; + mBones[index].blendLerp = par.blendLerp; } - G2_TransformBone(index,*this); - mFinalBones[index].touch=mCurrentTouch; + G2_TransformBone(index, *this); + mFinalBones[index].touch = mCurrentTouch; } } -//rww - RAGDOLL_BEGIN - void SmoothLow(int index) - { - if (mSmoothBones[index].touch==mLastTouch) - { + // rww - RAGDOLL_BEGIN + void SmoothLow(int index) { + if (mSmoothBones[index].touch == mLastTouch) { int i; - float *oldM=&mSmoothBones[index].boneMatrix.matrix[0][0]; - float *newM=&mFinalBones[index].boneMatrix.matrix[0][0]; -#if 0 //this is just too slow. I need a better way. + float *oldM = &mSmoothBones[index].boneMatrix.matrix[0][0]; + float *newM = &mFinalBones[index].boneMatrix.matrix[0][0]; +#if 0 // this is just too slow. I need a better way. static float smoothFactor; smoothFactor = mSmoothFactor; @@ -275,120 +239,107 @@ class CBoneCache } #endif - for (i=0;i<12;i++,oldM++,newM++) - { - *oldM=mSmoothFactor*(*oldM-*newM)+*newM; + for (i = 0; i < 12; i++, oldM++, newM++) { + *oldM = mSmoothFactor * (*oldM - *newM) + *newM; } - } - else - { - memcpy(&mSmoothBones[index].boneMatrix,&mFinalBones[index].boneMatrix,sizeof(mdxaBone_t)); + } else { + memcpy(&mSmoothBones[index].boneMatrix, &mFinalBones[index].boneMatrix, sizeof(mdxaBone_t)); } mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[index]); mdxaBone_t tempMatrix; - Multiply_3x4Matrix(&tempMatrix,&mSmoothBones[index].boneMatrix, &skel->BasePoseMat); + Multiply_3x4Matrix(&tempMatrix, &mSmoothBones[index].boneMatrix, &skel->BasePoseMat); float maxl; - maxl=VectorLength(&skel->BasePoseMat.matrix[0][0]); + maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[1][0]); VectorNormalize(&tempMatrix.matrix[2][0]); - VectorScale(&tempMatrix.matrix[0][0],maxl,&tempMatrix.matrix[0][0]); - VectorScale(&tempMatrix.matrix[1][0],maxl,&tempMatrix.matrix[1][0]); - VectorScale(&tempMatrix.matrix[2][0],maxl,&tempMatrix.matrix[2][0]); - Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); - mSmoothBones[index].touch=mCurrentTouch; + VectorScale(&tempMatrix.matrix[0][0], maxl, &tempMatrix.matrix[0][0]); + VectorScale(&tempMatrix.matrix[1][0], maxl, &tempMatrix.matrix[1][0]); + VectorScale(&tempMatrix.matrix[2][0], maxl, &tempMatrix.matrix[2][0]); + Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix, &tempMatrix, &skel->BasePoseMatInv); + mSmoothBones[index].touch = mCurrentTouch; #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -//rww - RAGDOLL_END -public: - int frameSize; - const mdxaHeader_t *header; - const model_t *mod; + // rww - RAGDOLL_END + public: + int frameSize; + const mdxaHeader_t *header; + const model_t *mod; // these are split for better cpu cache behavior std::vector mBones; std::vector mFinalBones; std::vector mSmoothBones; // for render smoothing - //vector mSkels; + // vector mSkels; - boneInfo_v *rootBoneList; - mdxaBone_t rootMatrix; - int incomingTime; + boneInfo_v *rootBoneList; + mdxaBone_t rootMatrix; + int incomingTime; - int mCurrentTouch; - //rww - RAGDOLL_BEGIN - int mCurrentTouchRender; - int mLastTouch; - int mLastLastTouch; - //rww - RAGDOLL_END + int mCurrentTouch; + // rww - RAGDOLL_BEGIN + int mCurrentTouchRender; + int mLastTouch; + int mLastLastTouch; + // rww - RAGDOLL_END // for render smoothing - bool mSmoothingActive; - bool mUnsquash; - float mSmoothFactor; + bool mSmoothingActive; + bool mUnsquash; + float mSmoothFactor; - CBoneCache(const model_t *amod,const mdxaHeader_t *aheader) : - header(aheader), - mod(amod) - { + CBoneCache(const model_t *amod, const mdxaHeader_t *aheader) : header(aheader), mod(amod) { assert(amod); assert(aheader); - mSmoothingActive=false; - mUnsquash=false; - mSmoothFactor=0.0f; + mSmoothingActive = false; + mUnsquash = false; + mSmoothFactor = 0.0f; - int numBones=header->numBones; + int numBones = header->numBones; mBones.resize(numBones); mFinalBones.resize(numBones); mSmoothBones.resize(numBones); -// mSkels.resize(numBones); - //rww - removed mSkels + // mSkels.resize(numBones); + // rww - removed mSkels mdxaSkelOffsets_t *offsets; - mdxaSkel_t *skel; + mdxaSkel_t *skel; offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); int i; - for (i=0;ioffsets[i]); - //mSkels[i]=skel; - //ditto - mFinalBones[i].parent=skel->parent; + // mSkels[i]=skel; + // ditto + mFinalBones[i].parent = skel->parent; } - mCurrentTouch=3; -//rww - RAGDOLL_BEGIN - mLastTouch=2; - mLastLastTouch=1; -//rww - RAGDOLL_END + mCurrentTouch = 3; + // rww - RAGDOLL_BEGIN + mLastTouch = 2; + mLastLastTouch = 1; + // rww - RAGDOLL_END } - SBoneCalc &Root() - { + SBoneCalc &Root() { assert(mBones.size()); return mBones[0]; } - const mdxaBone_t &EvalUnsmooth(int index) - { + const mdxaBone_t &EvalUnsmooth(int index) { EvalLow(index); - if (mSmoothingActive&&mSmoothBones[index].touch) - { + if (mSmoothingActive && mSmoothBones[index].touch) { return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - const mdxaBone_t &Eval(int index) - { + const mdxaBone_t &Eval(int index) { /* bool wasEval=EvalLow(index); if (mSmoothingActive) @@ -443,54 +394,45 @@ class CBoneCache return mFinalBones[index].boneMatrix; */ - //Hey, this is what sof2 does. Let's try it out. - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { + // Hey, this is what sof2 does. Let's try it out. + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { EvalLow(index); } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_BEGIN - const inline mdxaBone_t &EvalRender(int index) - { - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { - mFinalBones[index].touchRender=mCurrentTouchRender; + // rww - RAGDOLL_BEGIN + const inline mdxaBone_t &EvalRender(int index) { + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { + mFinalBones[index].touchRender = mCurrentTouchRender; EvalLow(index); } - if (mSmoothingActive) - { - if (mSmoothBones[index].touch!=mCurrentTouch) - { + if (mSmoothingActive) { + if (mSmoothBones[index].touch != mCurrentTouch) { SmoothLow(index); } return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_END - //rww - RAGDOLL_BEGIN - bool WasRendered(int index) - { - assert(index>=0&&index<(int)mBones.size()); - return mFinalBones[index].touchRender==mCurrentTouchRender; + // rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + bool WasRendered(int index) { + assert(index >= 0 && index < (int)mBones.size()); + return mFinalBones[index].touchRender == mCurrentTouchRender; } - int GetParent(int index) - { - if (index==0) - { + int GetParent(int index) { + if (index == 0) { return -1; } - assert(index>=0&&index<(int)mBones.size()); + assert(index >= 0 && index < (int)mBones.size()); return mFinalBones[index].parent; } - //rww - RAGDOLL_END + // rww - RAGDOLL_END }; -void RemoveBoneCache(CBoneCache *boneCache) -{ +void RemoveBoneCache(CBoneCache *boneCache) { #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations -= sizeof(*boneCache); #endif @@ -499,116 +441,98 @@ void RemoveBoneCache(CBoneCache *boneCache) } #ifdef _G2_LISTEN_SERVER_OPT -void CopyBoneCache(CBoneCache *to, CBoneCache *from) -{ - memcpy(to, from, sizeof(CBoneCache)); -} +void CopyBoneCache(CBoneCache *to, CBoneCache *from) { memcpy(to, from, sizeof(CBoneCache)); } #endif -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache) -{ +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache) { assert(boneCache); return boneCache->Eval(index); } -//rww - RAGDOLL_BEGIN -const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) -{ - if (!ghoul2.mBoneCache) - { +// rww - RAGDOLL_BEGIN +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) { + if (!ghoul2.mBoneCache) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.header; } -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep) -{ +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep) { // fixme, these should be precomputed - if (!ghoul2.mBoneCache||!maxDep) - { + if (!ghoul2.mBoneCache || !maxDep) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; - mdxaSkel_t *skel; + CBoneCache &boneCache = *ghoul2.mBoneCache; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); int i; - int ret=0; - for (i=0;inumChildren;i++) - { - if (!maxDep) - { + int ret = 0; + for (i = 0; i < skel->numChildren; i++) { + if (!maxDep) { return i; // number added } - *tempDependents=skel->children[i]; - assert(*tempDependents>0&&*tempDependentsnumBones); + *tempDependents = skel->children[i]; + assert(*tempDependents > 0 && *tempDependents < boneCache.header->numBones); maxDep--; tempDependents++; ret++; } - for (i=0;inumChildren;i++) - { - int num=G2_GetBoneDependents(ghoul2,skel->children[i],tempDependents,maxDep); - tempDependents+=num; - ret+=num; - maxDep-=num; - assert(maxDep>=0); - if (!maxDep) - { + for (i = 0; i < skel->numChildren; i++) { + int num = G2_GetBoneDependents(ghoul2, skel->children[i], tempDependents, maxDep); + tempDependents += num; + ret += num; + maxDep -= num; + assert(maxDep >= 0); + if (!maxDep) { break; } } return ret; } -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) -{ - if (!ghoul2.mBoneCache) - { +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return false; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.WasRendered(boneNum); } -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; } -char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) -{ - if (!ghoul2.mBoneCache) - { +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return NULL; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); @@ -616,185 +540,150 @@ char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) return skel->name; } -void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) -{ +void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) { assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&retMatrix, &boneMatrix, &skel->BasePoseMat); - if (scale[0]) - { + if (scale[0]) { retMatrix.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { retMatrix.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { retMatrix.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&retMatrix.matrix[0]); - VectorNormalize((float*)&retMatrix.matrix[1]); - VectorNormalize((float*)&retMatrix.matrix[2]); + VectorNormalize((float *)&retMatrix.matrix[0]); + VectorNormalize((float *)&retMatrix.matrix[1]); + VectorNormalize((float *)&retMatrix.matrix[2]); } -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } mdxaBone_t bolt; assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&bolt, (mdxaBone_t *)&boneCache.Eval(boneNum), &skel->BasePoseMat); // DEST FIRST ARG - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); - Multiply_3x4Matrix(&retMatrix,&worldMatrix, &bolt); + Multiply_3x4Matrix(&retMatrix, &worldMatrix, &bolt); #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(retMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(retMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - int parent=-1; - if (ghoul2.mBoneCache) - { - CBoneCache &boneCache=*ghoul2.mBoneCache; +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) { + int parent = -1; + if (ghoul2.mBoneCache) { + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); - parent=boneCache.GetParent(boneNum); - if (parent<0||parent>=boneCache.header->numBones) - { - parent=-1; - retMatrix=identityMatrix; + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + parent = boneCache.GetParent(boneNum); + if (parent < 0 || parent >= boneCache.header->numBones) { + parent = -1; + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); - } - else - { - G2_GetBoneMatrixLow(ghoul2,parent,scale,retMatrix,retBasepose,retBaseposeInv); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + } else { + G2_GetBoneMatrixLow(ghoul2, parent, scale, retMatrix, retBasepose, retBaseposeInv); } } return parent; } -//rww - RAGDOLL_END - -class CRenderSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - shader_t *cust_shader; - int fogNum; - qboolean personalModel; - CBoneCache *boneCache; - int renderfx; - skin_t *skin; - model_t *currentModel; - int lod; - boltInfo_v &boltList; +// rww - RAGDOLL_END + +class CRenderSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + shader_t *cust_shader; + int fogNum; + qboolean personalModel; + CBoneCache *boneCache; + int renderfx; + skin_t *skin; + model_t *currentModel; + int lod; + boltInfo_v &boltList; #ifdef _G2_GORE - shader_t *gore_shader; - CGoreSet *gore_set; + shader_t *gore_shader; + CGoreSet *gore_set; #endif - CRenderSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - shader_t *initcust_shader, - int initfogNum, - qboolean initpersonalModel, - CBoneCache *initboneCache, - int initrenderfx, - skin_t *initskin, - model_t *initcurrentModel, - int initlod, + CRenderSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, shader_t *initcust_shader, int initfogNum, qboolean initpersonalModel, + CBoneCache *initboneCache, int initrenderfx, skin_t *initskin, model_t *initcurrentModel, int initlod, #ifdef _G2_GORE - boltInfo_v &initboltList, - shader_t *initgore_shader, - CGoreSet *initgore_set): + boltInfo_v &initboltList, shader_t *initgore_shader, CGoreSet *initgore_set) + : #else - boltInfo_v &initboltList): + boltInfo_v &initboltList) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - cust_shader(initcust_shader), - fogNum(initfogNum), - personalModel(initpersonalModel), - boneCache(initboneCache), - renderfx(initrenderfx), - skin(initskin), - currentModel(initcurrentModel), - lod(initlod), + surfaceNum(initsurfaceNum), rootSList(initrootSList), cust_shader(initcust_shader), fogNum(initfogNum), personalModel(initpersonalModel), + boneCache(initboneCache), renderfx(initrenderfx), skin(initskin), currentModel(initcurrentModel), lod(initlod), #ifdef _G2_GORE - boltList(initboltList), - gore_shader(initgore_shader), - gore_set(initgore_set) + boltList(initboltList), gore_shader(initgore_shader), gore_set(initgore_set) #else - boltList(initboltList) + boltList(initboltList) #endif - {} + { + } }; #ifdef _G2_GORE #define MAX_RENDER_SURFACES (2048) static CRenderableSurface RSStorage[MAX_RENDER_SURFACES]; -static unsigned int NextRS=0; +static unsigned int NextRS = 0; -CRenderableSurface *AllocRS() -{ - CRenderableSurface *ret=&RSStorage[NextRS]; +CRenderableSurface *AllocRS() { + CRenderableSurface *ret = &RSStorage[NextRS]; ret->Init(); NextRS++; - NextRS%=MAX_RENDER_SURFACES; + NextRS %= MAX_RENDER_SURFACES; return ret; } #endif @@ -814,277 +703,231 @@ frame. // // Bone Manipulation code - -void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) -{ +void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) { // this is revised for the 3x4 matrix we use in G2. - float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; + float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; float s; - //If the trace of the matrix is greater than zero, then - //perform an "instant" calculation. - //Important note wrt. rouning errors: - //Test if ( T > 0.00000001 ) to avoid large distortions! - if (t > 0.00000001) - { - s = sqrt(t) * 2; - quat[0] = ( mat->matrix[1][2] - mat->matrix[2][1] ) / s; - quat[1] = ( mat->matrix[2][0] - mat->matrix[0][2] ) / s; - quat[2] = ( mat->matrix[0][1] - mat->matrix[1][0] ) / s; - quat[3] = 0.25 * s; - } - else - { - //If the trace of the matrix is equal to zero then identify - //which major diagonal element has the greatest value. - - //Depending on this, calculate the following: - - if ( mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2] ) { // Column 0: - s = sqrt( 1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2])* 2; + // If the trace of the matrix is greater than zero, then + // perform an "instant" calculation. + // Important note wrt. rouning errors: + // Test if ( T > 0.00000001 ) to avoid large distortions! + if (t > 0.00000001) { + s = sqrt(t) * 2; + quat[0] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; + quat[1] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; + quat[2] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; + quat[3] = 0.25 * s; + } else { + // If the trace of the matrix is equal to zero then identify + // which major diagonal element has the greatest value. + + // Depending on this, calculate the following: + + if (mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2]) { // Column 0: + s = sqrt(1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2]) * 2; quat[0] = 0.25 * s; - quat[1] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; - quat[2] = (mat->matrix[2][0] + mat->matrix[0][2] ) / s; - quat[3] = (mat->matrix[1][2] - mat->matrix[2][1] ) / s; + quat[1] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; + quat[2] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[3] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; - } else if ( mat->matrix[1][1] > mat->matrix[2][2] ) { // Column 1: - s = sqrt( 1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2] ) * 2; - quat[0] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; + } else if (mat->matrix[1][1] > mat->matrix[2][2]) { // Column 1: + s = sqrt(1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2]) * 2; + quat[0] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; quat[1] = 0.25 * s; - quat[2] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; - quat[3] = (mat->matrix[2][0] - mat->matrix[0][2] ) / s; + quat[2] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; + quat[3] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; - } else { // Column 2: - s = sqrt( 1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1] ) * 2; - quat[0] = (mat->matrix[2][0]+ mat->matrix[0][2] ) / s; - quat[1] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; + } else { // Column 2: + s = sqrt(1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1]) * 2; + quat[0] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[1] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; quat[2] = 0.25 * s; - quat[3] = (mat->matrix[0][1] - mat->matrix[1][0] ) / s; + quat[3] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; } } } -void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) -{ +void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) { - float xx = quat[0] * quat[0]; - float xy = quat[0] * quat[1]; - float xz = quat[0] * quat[2]; - float xw = quat[0] * quat[3]; + float xx = quat[0] * quat[0]; + float xy = quat[0] * quat[1]; + float xz = quat[0] * quat[2]; + float xw = quat[0] * quat[3]; - float yy = quat[1] * quat[1]; - float yz = quat[1] * quat[2]; - float yw = quat[1] * quat[3]; + float yy = quat[1] * quat[1]; + float yz = quat[1] * quat[2]; + float yw = quat[1] * quat[3]; - float zz = quat[2] * quat[2]; - float zw = quat[2] * quat[3]; + float zz = quat[2] * quat[2]; + float zw = quat[2] * quat[3]; - mat->matrix[0][0] = 1 - 2 * ( yy + zz ); - mat->matrix[1][0] = 2 * ( xy - zw ); - mat->matrix[2][0] = 2 * ( xz + yw ); + mat->matrix[0][0] = 1 - 2 * (yy + zz); + mat->matrix[1][0] = 2 * (xy - zw); + mat->matrix[2][0] = 2 * (xz + yw); - mat->matrix[0][1] = 2 * ( xy + zw ); - mat->matrix[1][1] = 1 - 2 * ( xx + zz ); - mat->matrix[2][1] = 2 * ( yz - xw ); + mat->matrix[0][1] = 2 * (xy + zw); + mat->matrix[1][1] = 1 - 2 * (xx + zz); + mat->matrix[2][1] = 2 * (yz - xw); - mat->matrix[0][2] = 2 * ( xz - yw ); - mat->matrix[1][2] = 2 * ( yz + xw ); - mat->matrix[2][2] = 1 - 2 * ( xx + yy ); + mat->matrix[0][2] = 2 * (xz - yw); + mat->matrix[1][2] = 2 * (yz + xw); + mat->matrix[2][2] = 1 - 2 * (xx + yy); - mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; + mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; } // nasty little matrix multiply going on here.. -void Multiply_3x4Matrix(mdxaBone_t *out, mdxaBone_t *in2, mdxaBone_t *in) -{ +void Multiply_3x4Matrix(mdxaBone_t *out, mdxaBone_t *in2, mdxaBone_t *in) { // first row of out out->matrix[0][0] = (in2->matrix[0][0] * in->matrix[0][0]) + (in2->matrix[0][1] * in->matrix[1][0]) + (in2->matrix[0][2] * in->matrix[2][0]); out->matrix[0][1] = (in2->matrix[0][0] * in->matrix[0][1]) + (in2->matrix[0][1] * in->matrix[1][1]) + (in2->matrix[0][2] * in->matrix[2][1]); out->matrix[0][2] = (in2->matrix[0][0] * in->matrix[0][2]) + (in2->matrix[0][1] * in->matrix[1][2]) + (in2->matrix[0][2] * in->matrix[2][2]); - out->matrix[0][3] = (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; + out->matrix[0][3] = + (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; // second row of outf out out->matrix[1][0] = (in2->matrix[1][0] * in->matrix[0][0]) + (in2->matrix[1][1] * in->matrix[1][0]) + (in2->matrix[1][2] * in->matrix[2][0]); out->matrix[1][1] = (in2->matrix[1][0] * in->matrix[0][1]) + (in2->matrix[1][1] * in->matrix[1][1]) + (in2->matrix[1][2] * in->matrix[2][1]); out->matrix[1][2] = (in2->matrix[1][0] * in->matrix[0][2]) + (in2->matrix[1][1] * in->matrix[1][2]) + (in2->matrix[1][2] * in->matrix[2][2]); - out->matrix[1][3] = (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; + out->matrix[1][3] = + (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; // third row of out out out->matrix[2][0] = (in2->matrix[2][0] * in->matrix[0][0]) + (in2->matrix[2][1] * in->matrix[1][0]) + (in2->matrix[2][2] * in->matrix[2][0]); out->matrix[2][1] = (in2->matrix[2][0] * in->matrix[0][1]) + (in2->matrix[2][1] * in->matrix[1][1]) + (in2->matrix[2][2] * in->matrix[2][1]); out->matrix[2][2] = (in2->matrix[2][0] * in->matrix[0][2]) + (in2->matrix[2][1] * in->matrix[1][2]) + (in2->matrix[2][2] * in->matrix[2][2]); - out->matrix[2][3] = (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; + out->matrix[2][3] = + (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; } - -static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) -{ - const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); - mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte*)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); +static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) { + const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); + mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); return (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); } - -/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) -{ - mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); - MC_UnCompressQuat(mat, pCompBonePool[ G2_GetBonePoolIndex( pMDXAHeader, iFrame, iBoneIndex ) ].Comp); +/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) { + mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); + MC_UnCompressQuat(mat, pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); } #define DEBUG_G2_TIMING (0) #define DEBUG_G2_TIMING_RENDER_ONLY (1) -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp) -{ - assert(bone.startFrame>=0); - assert(bone.startFrame<=numFramesInFile); - assert(bone.endFrame>=0); - assert(bone.endFrame<=numFramesInFile); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp) { + assert(bone.startFrame >= 0); + assert(bone.startFrame <= numFramesInFile); + assert(bone.endFrame >= 0); + assert(bone.endFrame <= numFramesInFile); // yes - add in animation speed to current frame - float animSpeed = bone.animSpeed; - float time; - if (bone.pauseTime) - { + float animSpeed = bone.animSpeed; + float time; + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (currentTime - bone.startTime) / 50.0f; } - if (time<0.0f) - { - time=0.0f; + if (time < 0.0f) { + time = 0.0f; } - float newFrame_g = bone.startFrame + (time * animSpeed); + float newFrame_g = bone.startFrame + (time * animSpeed); - int animSize = bone.endFrame - bone.startFrame; - float endFrame = (float)bone.endFrame; + int animSize = bone.endFrame - bone.startFrame; + float endFrame = (float)bone.endFrame; // we are supposed to be animating right? - if (animSize) - { + if (animSize) { // did we run off the end? - if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { + if (animSpeed < 0.0f) { // we don't use this case, or so I am told // if we do, let me know, I need to insure the mod works // should we be creating a virtual frame? - if ((newFrame_g < endFrame+1) && (newFrame_g >= endFrame)) - { + if ((newFrame_g < endFrame + 1) && (newFrame_g >= endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = float(endFrame+1)-newFrame_g; + lerp = float(endFrame + 1) - newFrame_g; // frames are easy to calculate currentFrame = endFrame; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = (ceil(newFrame_g)-newFrame_g); + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (currentFrame <= endFrame+1 ) - { + if (currentFrame <= endFrame + 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame - 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - } - else - { + } else { // should we be creating a virtual frame? - if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) - { + if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + assert(newFrame >= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (newFrame_g >= endFrame - 1) - { + if (newFrame_g >= endFrame - 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame + 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } // sanity check - assert (((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); - } - else - { - if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) - { + assert(((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); + } else { + if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) { // if we are supposed to reset the default anim, then do so - if (animSpeed > 0.0f) - { + if (animSpeed > 0.0f) { currentFrame = bone.endFrame - 1; - assert(currentFrame>=0&¤tFrame=0&¤tFrame= 0 && currentFrame < numFramesInFile); + } else { + currentFrame = bone.endFrame + 1; + assert(currentFrame >= 0 && currentFrame < numFramesInFile); } newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } - else - { + } else { bone.flags &= ~(BONE_ANIM_TOTAL); } - } - } - else - { - if (animSpeed> 0.0) - { + } else { + if (animSpeed > 0.0) { // frames are easy to calculate currentFrame = (int)newFrame_g; @@ -1092,99 +935,80 @@ void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int &cu // frame we want to display lerp = (newFrame_g - currentFrame); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame + 1; // are we now on the end frame? - assert((int)endFrame<=numFramesInFile); - if (newFrame >= (int)endFrame) - { + assert((int)endFrame <= numFramesInFile); + if (newFrame >= (int)endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame-1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - if (currentFrame>bone.startFrame) - { - currentFrame=bone.startFrame; + if (currentFrame > bone.startFrame) { + currentFrame = bone.startFrame; newFrame = currentFrame; - lerp=0.0f; - } - else - { - newFrame=currentFrame-1; + lerp = 0.0f; + } else { + newFrame = currentFrame - 1; // are we now on the end frame? - if (newFrame < endFrame+1) - { + if (newFrame < endFrame + 1) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame+1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } - assert(currentFrame>=0&¤tFrame=0&&newFrame= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); } } - } - else - { - if (animSpeed<0.0) - { - currentFrame = bone.endFrame+1; - } - else - { - currentFrame = bone.endFrame-1; + } else { + if (animSpeed < 0.0) { + currentFrame = bone.endFrame + 1; + } else { + currentFrame = bone.endFrame - 1; } - if (currentFrame<0) - { - currentFrame=0; + if (currentFrame < 0) { + currentFrame = 0; } - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } - assert(currentFrame>=0&¤tFrame=0&&newFrame=0.0f&&lerp<=1.0f); + assert(currentFrame >= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); + assert(lerp >= 0.0f && lerp <= 1.0f); } #ifdef _RAG_PRINT_TEST void G2_RagPrintMatrix(mdxaBone_t *mat); #endif -//basically construct a seperate skeleton with full hierarchy to store a matrix -//off which will give us the desired settling position given the frame in the skeleton -//that should be used -rww -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName); +// basically construct a seperate skeleton with full hierarchy to store a matrix +// off which will give us the desired settling position given the frame in the skeleton +// that should be used -rww +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); -void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame) -{ +void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame) { mdxaBone_t animMatrix; mdxaSkel_t *skel; mdxaSkel_t *pskel; @@ -1202,16 +1026,12 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - //find/add the bone in the list - if (!skel->name[0]) - { + // find/add the bone in the list + if (!skel->name[0]) { bListIndex = -1; - } - else - { + } else { bListIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); - if (bListIndex == -1) - { + if (bListIndex == -1) { #ifdef _RAG_PRINT_TEST Com_Printf("Attempting to add %s\n", skel->name); #endif @@ -1223,34 +1043,28 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &bone = ghoul2.mBlist[bListIndex]; - if (bone.hasAnimFrameMatrix == frame) - { //already calculated so just grab it + if (bone.hasAnimFrameMatrix == frame) { // already calculated so just grab it matrix = bone.animFrameMatrix; return; } - //get the base matrix for the specified frame + // get the base matrix for the specified frame UnCompressBone(animMatrix.matrix, boneNum, ghoul2.mBoneCache->header, frame); parent = skel->parent; - if (boneNum > 0 && parent > -1) - { - //recursively call to assure all parent matrices are set up + if (boneNum > 0 && parent > -1) { + // recursively call to assure all parent matrices are set up G2_RagGetAnimMatrix(ghoul2, parent, matrix, frame); - //assign the new skel ptr for our parent + // assign the new skel ptr for our parent pskel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[parent]); - //taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix - if (!pskel->name[0]) - { + // taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix + if (!pskel->name[0]) { parentBlistIndex = -1; - } - else - { + } else { parentBlistIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); - if (parentBlistIndex == -1) - { + if (parentBlistIndex == -1) { parentBlistIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); } } @@ -1259,46 +1073,37 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &pbone = ghoul2.mBlist[parentBlistIndex]; - assert(pbone.hasAnimFrameMatrix == frame); //this should have been calc'd in the recursive call + assert(pbone.hasAnimFrameMatrix == frame); // this should have been calc'd in the recursive call Multiply_3x4Matrix(&bone.animFrameMatrix, &pbone.animFrameMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (parentBlistIndex != -1 && bListIndex != -1) - { + if (parentBlistIndex != -1 && bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); } #endif - } - else - { //root + } else { // root Multiply_3x4Matrix(&bone.animFrameMatrix, &ghoul2.mBoneCache->rootMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (bListIndex != -1) - { + if (bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s\n", skel->name); } #endif - //bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; - //Maybe use this for the root, so that the orientation is in sync with the current - //root matrix? However this would require constant recalculation of this base - //skeleton which I currently do not want. + // bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; + // Maybe use this for the root, so that the orientation is in sync with the current + // root matrix? However this would require constant recalculation of this base + // skeleton which I currently do not want. } - //never need to figure it out again + // never need to figure it out again bone.hasAnimFrameMatrix = frame; #ifdef _RAG_PRINT_TEST - if (!actuallySet) - { + if (!actuallySet) { Com_Printf("SET FAILURE\n"); G2_RagPrintMatrix(&bone.animFrameMatrix); } @@ -1307,65 +1112,57 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat matrix = bone.animFrameMatrix; } -void G2_TransformBone (int child,CBoneCache &BC) -{ - SBoneCalc &TB=BC.mBones[child]; - static mdxaBone_t tbone[6]; -// mdxaFrame_t *aFrame=0; -// mdxaFrame_t *bFrame=0; -// mdxaFrame_t *aoldFrame=0; -// mdxaFrame_t *boldFrame=0; - static mdxaSkel_t *skel; +void G2_TransformBone(int child, CBoneCache &BC) { + SBoneCalc &TB = BC.mBones[child]; + static mdxaBone_t tbone[6]; + // mdxaFrame_t *aFrame=0; + // mdxaFrame_t *bFrame=0; + // mdxaFrame_t *aoldFrame=0; + // mdxaFrame_t *boldFrame=0; + static mdxaSkel_t *skel; static mdxaSkelOffsets_t *offsets; - boneInfo_v &boneList = *BC.rootBoneList; - static int j, boneListIndex; - int angleOverride = 0; + boneInfo_v &boneList = *BC.rootBoneList; + static int j, boneListIndex; + int angleOverride = 0; #if DEBUG_G2_TIMING - bool printTiming=false; + bool printTiming = false; #endif // should this bone be overridden by a bone in the bone list? boneListIndex = G2_Find_Bone_In_List(boneList, child); - if (boneListIndex != -1) - { + if (boneListIndex != -1) { // we found a bone in the list - we need to override something here. // do we override the rotational angles? - if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) - { + if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) { angleOverride = (boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL); } // set blending stuff if we need to - if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) - { + if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) { float blendTime = BC.incomingTime - boneList[boneListIndex].blendStart; - // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the hiearchy - if (blendTime>=0.0f&&blendTime < boneList[boneListIndex].blendTime) - { - TB.blendFrame = boneList[boneListIndex].blendFrame; + // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the + // hiearchy + if (blendTime >= 0.0f && blendTime < boneList[boneListIndex].blendTime) { + TB.blendFrame = boneList[boneListIndex].blendFrame; TB.blendOldFrame = boneList[boneListIndex].blendLerpFrame; TB.blendLerp = (blendTime / boneList[boneListIndex].blendTime); TB.blendMode = true; - } - else - { + } else { TB.blendMode = false; } - } - else if (/*r_Ghoul2NoBlend->integer||*/((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) + } else if (/*r_Ghoul2NoBlend->integer||*/ ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) // turn off blending if we are just doing a straing animation override { TB.blendMode = false; } // should this animation be overridden by an animation in the bone list? - if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - G2_TimingModel(boneList[boneListIndex],BC.incomingTime,BC.header->numFrames,TB.currentFrame,TB.newFrame,TB.backlerp); + if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + G2_TimingModel(boneList[boneListIndex], BC.incomingTime, BC.header->numFrames, TB.currentFrame, TB.newFrame, TB.backlerp); } #if DEBUG_G2_TIMING - printTiming=true; + printTiming = true; #endif /* if ((r_Ghoul2NoLerp->integer)||((boneList[boneListIndex].flags) & (BONE_ANIM_NO_LERP))) @@ -1373,290 +1170,219 @@ void G2_TransformBone (int child,CBoneCache &BC) TB.backlerp = 0.0f; } */ - //rwwFIXMEFIXME: Use? + // rwwFIXMEFIXME: Use? } // figure out where the location of the bone animation data is - assert(TB.newFrame>=0&&TB.newFramenumFrames); - if (!(TB.newFrame>=0&&TB.newFramenumFrames)) - { - TB.newFrame=0; + assert(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames); + if (!(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames)) { + TB.newFrame = 0; } -// aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); - assert(TB.currentFrame>=0&&TB.currentFramenumFrames); - if (!(TB.currentFrame>=0&&TB.currentFramenumFrames)) - { - TB.currentFrame=0; + // aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); + assert(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames); + if (!(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames)) { + TB.currentFrame = 0; } -// aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); + // aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); // figure out where the location of the blended animation data is - assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1))); - if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1) ) - { - TB.blendFrame=0.0; + assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1))); + if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1)) { + TB.blendFrame = 0.0; } -// bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); - assert(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames); - if (!(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames)) - { - TB.blendOldFrame=0; + // bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); + assert(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames); + if (!(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames)) { + TB.blendOldFrame = 0; } #if DEBUG_G2_TIMING #if DEBUG_G2_TIMING_RENDER_ONLY - if (!HackadelicOnClient) - { - printTiming=false; + if (!HackadelicOnClient) { + printTiming = false; } #endif - if (printTiming) - { + if (printTiming) { char mess[1000]; - if (TB.blendMode) - { - sprintf(mess,"b %2d %5d %4d %4d %4d %4d %f %f\n",boneListIndex,BC.incomingTime,(int)TB.newFrame,(int)TB.currentFrame,(int)TB.blendFrame,(int)TB.blendOldFrame,TB.backlerp,TB.blendLerp); - } - else - { - sprintf(mess,"a %2d %5d %4d %4d %f\n",boneListIndex,BC.incomingTime,TB.newFrame,TB.currentFrame,TB.backlerp); + if (TB.blendMode) { + sprintf(mess, "b %2d %5d %4d %4d %4d %4d %f %f\n", boneListIndex, BC.incomingTime, (int)TB.newFrame, (int)TB.currentFrame, (int)TB.blendFrame, + (int)TB.blendOldFrame, TB.backlerp, TB.blendLerp); + } else { + sprintf(mess, "a %2d %5d %4d %4d %f\n", boneListIndex, BC.incomingTime, TB.newFrame, TB.currentFrame, TB.backlerp); } OutputDebugString(mess); - const boneInfo_t &bone=boneList[boneListIndex]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess," bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); - } - else - { - sprintf(mess," bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); - } -// OutputDebugString(mess); + const boneInfo_t &bone = boneList[boneListIndex]; + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, + " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + boneListIndex, BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, + bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, " bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", boneListIndex, + BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags); + } + // OutputDebugString(mess); } #endif -// boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); + // boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); -// mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); + // mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); - assert(child>=0&&childnumBones); -// assert(bFrame->boneIndexes[child]>=0); -// assert(boldFrame->boneIndexes[child]>=0); -// assert(aFrame->boneIndexes[child]>=0); -// assert(aoldFrame->boneIndexes[child]>=0); + assert(child >= 0 && child < BC.header->numBones); + // assert(bFrame->boneIndexes[child]>=0); + // assert(boldFrame->boneIndexes[child]>=0); + // assert(aFrame->boneIndexes[child]>=0); + // assert(aoldFrame->boneIndexes[child]>=0); // decide where the transformed bone is going // are we blending with another frame of anim? - if (TB.blendMode) - { + if (TB.blendMode) { float backlerp = TB.blendFrame - (int)TB.blendFrame; float frontlerp = 1.0 - backlerp; -// MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[3].matrix, child, BC.header, TB.blendFrame); UnCompressBone(tbone[4].matrix, child, BC.header, TB.blendOldFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) - + (frontlerp * ((float *)&tbone[4])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) + (frontlerp * ((float *)&tbone[4])[j]); } } - // - // lerp this bone - use the temp space on the ref entity to put the bone transforms into - // - if (!TB.backlerp) - { -// MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // + // lerp this bone - use the temp space on the ref entity to put the bone transforms into + // + if (!TB.backlerp) { + // MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[2].matrix, child, BC.header, TB.currentFrame); // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } - } - else - { + } + } else { float frontlerp = 1.0 - TB.backlerp; -// MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[0].matrix, child, BC.header, TB.newFrame); UnCompressBone(tbone[1].matrix, child, BC.header, TB.currentFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) - + (frontlerp * ((float *)&tbone[1])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) + (frontlerp * ((float *)&tbone[1])[j]); } // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } + } } // figure out where the bone hirearchy info is offsets = (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)BC.header + sizeof(mdxaHeader_t) + offsets->offsets[child]); -// skel = BC.mSkels[child]; - //rww - removed mSkels - - int parent=BC.mFinalBones[child].parent; - assert((parent==-1&&child==0)||(parent>=0&&parent<(int)BC.mBones.size())); - if (angleOverride & BONE_ANGLES_REPLACE) - { - bool isRag=!!(angleOverride & BONE_ANGLES_RAGDOLL); - if (!isRag) - { //do the same for ik.. I suppose. + // skel = BC.mSkels[child]; + // rww - removed mSkels + + int parent = BC.mFinalBones[child].parent; + assert((parent == -1 && child == 0) || (parent >= 0 && parent < (int)BC.mBones.size())); + if (angleOverride & BONE_ANGLES_REPLACE) { + bool isRag = !!(angleOverride & BONE_ANGLES_RAGDOLL); + if (!isRag) { // do the same for ik.. I suppose. isRag = !!(angleOverride & BONE_ANGLES_IK); } mdxaBone_t &bone = BC.mFinalBones[child].boneMatrix; boneInfo_t &boneOverride = boneList[boneListIndex]; - if (isRag) - { + if (isRag) { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // this is crazy, we are gonna drive the animation to ID while we are doing post mults to compensate. - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); - static mdxaBone_t toMatrix = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - toMatrix.matrix[0][0]=matrixScale; - toMatrix.matrix[1][1]=matrixScale; - toMatrix.matrix[2][2]=matrixScale; - toMatrix.matrix[0][3]=temp.matrix[0][3]; - toMatrix.matrix[1][3]=temp.matrix[1][3]; - toMatrix.matrix[2][3]=temp.matrix[2][3]; - - Multiply_3x4Matrix(&temp, &toMatrix,&skel->BasePoseMatInv); //dest first arg + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); + static mdxaBone_t toMatrix = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + toMatrix.matrix[0][0] = matrixScale; + toMatrix.matrix[1][1] = matrixScale; + toMatrix.matrix[2][2] = matrixScale; + toMatrix.matrix[0][3] = temp.matrix[0][3]; + toMatrix.matrix[1][3] = temp.matrix[1][3]; + toMatrix.matrix[2][3] = temp.matrix[2][3]; + + Multiply_3x4Matrix(&temp, &toMatrix, &skel->BasePoseMatInv); // dest first arg float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp>0.0f) - { + if (blendLerp > 0.0f) { // has started - if (blendLerp>1.0f) - { + if (blendLerp > 1.0f) { // done -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); - memcpy (&bone,&temp, sizeof(mdxaBone_t)); - } - else - { -// mdxaBone_t lerp; + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); + memcpy(&bone, &temp, sizeof(mdxaBone_t)); + } else { + // mdxaBone_t lerp; // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&tbone[2])[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&tbone[2])[j]); } -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); } } - } - else - { + } else { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // are we attempting to blend with the base animation? and still within blend time? - if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) - { + if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) { // ok, we are supposed to be blending. Work out lerp float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp <= 1) - { - if (blendLerp < 0) - { + if (blendLerp <= 1) { + if (blendLerp < 0) { assert(0); } // now work out the matrix we want to get *to* - firstPass is where we are coming *from* Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1665,51 +1391,39 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&temp, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&temp, &newMatrixTemp, &skel->BasePoseMatInv); // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&firstPass)[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&firstPass)[j]); } - } - else - { + } else { bone = firstPass; } } // no, so just override it directly - else - { + else { - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1718,86 +1432,57 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&bone, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&bone, &newMatrixTemp, &skel->BasePoseMatInv); } } - } - else if (angleOverride & BONE_ANGLES_PREMULT) - { - if ((angleOverride&BONE_ANGLES_RAGDOLL) || (angleOverride&BONE_ANGLES_IK)) - { - mdxaBone_t tmp; - if (!child) - { - if (HackadelicOnClient) - { + } else if (angleOverride & BONE_ANGLES_PREMULT) { + if ((angleOverride & BONE_ANGLES_RAGDOLL) || (angleOverride & BONE_ANGLES_IK)) { + mdxaBone_t tmp; + if (!child) { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { - if (HackadelicOnClient) - { + } else { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tmp, &tbone[2]); - } - else - { - if (!child) - { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tmp, &tbone[2]); + } else { + if (!child) { // use the in coming root matrix as our basis - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { + } else { // convert from 3x4 matrix to a 4x4 matrix - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } } - } - else - // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely - if (child) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); - } + } else + // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely + if (child) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); + } // now multiply our resulting bone by an override matrix should we need to - if (angleOverride & BONE_ANGLES_POSTMULT) - { - mdxaBone_t tempMatrix; - memcpy (&tempMatrix,&BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); - if (HackadelicOnClient) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); - } - else - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); + if (angleOverride & BONE_ANGLES_POSTMULT) { + mdxaBone_t tempMatrix; + memcpy(&tempMatrix, &BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); + if (HackadelicOnClient) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); + } else { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); } } /* @@ -1817,20 +1502,16 @@ void G2_TransformBone (int child,CBoneCache &BC) Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); } */ - //rwwFIXMEFIXME: Care? - + // rwwFIXMEFIXME: Care? } -void G2_SetUpBolts( mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, boltInfo_v &boltList) -{ - mdxaSkel_t *skel; +void G2_SetUpBolts(mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, boltInfo_v &boltList) { + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); - for (size_t i=0; ioffsets[boltList[i].boneNumber]); Multiply_3x4Matrix(&boltList[i].position, &bonePtr[boltList[i].boneNumber].second, &skel->BasePoseMat); @@ -1838,13 +1519,12 @@ void G2_SetUpBolts( mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &boneP } } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -//rww - RAGDOLL_END -//rwwFIXMEFIXME: Move this into the stupid header or something. +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +// rww - RAGDOLL_END +// rwwFIXMEFIXME: Move this into the stupid header or something. -void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time,bool smooth=true) -{ +void G2_TransformGhoulBones(boneInfo_v &rootBoneList, mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time, bool smooth = true) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_TransformGhoulBones.Start(); G2PerformanceCounter_G2_TransformGhoulBones++; @@ -1865,37 +1545,33 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh aHeader = animModel->mdxa; assert(aHeader); */ - model_t *currentModel = (model_t *)ghoul2.currentModel; - mdxaHeader_t *aHeader = (mdxaHeader_t *)ghoul2.aHeader; - + model_t *currentModel = (model_t *)ghoul2.currentModel; + mdxaHeader_t *aHeader = (mdxaHeader_t *)ghoul2.aHeader; assert(ghoul2.aHeader); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - if (!aHeader->numBones) - { + if (!aHeader->numBones) { assert(0); // this would be strange return; } - if (!ghoul2.mBoneCache) - { - ghoul2.mBoneCache=new CBoneCache(currentModel,aHeader); + if (!ghoul2.mBoneCache) { + ghoul2.mBoneCache = new CBoneCache(currentModel, aHeader); #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations += sizeof(*ghoul2.mBoneCache); #endif } - ghoul2.mBoneCache->mod=currentModel; - ghoul2.mBoneCache->header=aHeader; - assert((int)ghoul2.mBoneCache->mBones.size()==aHeader->numBones); + ghoul2.mBoneCache->mod = currentModel; + ghoul2.mBoneCache->header = aHeader; + assert((int)ghoul2.mBoneCache->mBones.size() == aHeader->numBones); - ghoul2.mBoneCache->mSmoothingActive=false; - ghoul2.mBoneCache->mUnsquash=false; + ghoul2.mBoneCache->mSmoothingActive = false; + ghoul2.mBoneCache->mUnsquash = false; // master smoothing control - if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue( "dedicated" )) - { - ghoul2.mBoneCache->mLastTouch=ghoul2.mBoneCache->mLastLastTouch; + if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue("dedicated")) { + ghoul2.mBoneCache->mLastTouch = ghoul2.mBoneCache->mLastLastTouch; /* float val=r_Ghoul2AnimSmooth->value; if (smooth&&val>0.0f&&val<1.0f) @@ -1919,34 +1595,21 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh */ // master smoothing control - float val=r_Ghoul2AnimSmooth->value; - if (val>0.0f&&val<1.0f) - { - //if (ghoul2.mFlags&GHOUL2_RESERVED_FOR_RAGDOLL) + float val = r_Ghoul2AnimSmooth->value; + if (val > 0.0f && val < 1.0f) { + // if (ghoul2.mFlags&GHOUL2_RESERVED_FOR_RAGDOLL) #if 1 - if(ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) - { + if (ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) { val = 0.9f; - } - else if(ghoul2.mFlags & GHOUL2_RAG_STARTED) - { - for (size_t k=0;ktime-250 && - bone.firstCollisionTime time) - { + } else if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { + for (size_t k = 0; k < rootBoneList.size(); k++) { + boneInfo_t &bone = rootBoneList[k]; + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (bone.firstCollisionTime && bone.firstCollisionTime > time - 250 && bone.firstCollisionTime < time) { + val = 0.9f; //(val+0.8f)/2.0f; + } else if (bone.airTime > time) { val = 0.2f; - } - else - { + } else { val = 0.8f; } break; @@ -1955,80 +1618,70 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh } #endif -// ghoul2.mBoneCache->mSmoothFactor=(val + 1.0f-pow(1.0f-val,50.0f/dif))/2.0f; // meaningless formula - ghoul2.mBoneCache->mSmoothFactor=val; // meaningless formula - ghoul2.mBoneCache->mSmoothingActive=true; + // ghoul2.mBoneCache->mSmoothFactor=(val + 1.0f-pow(1.0f-val,50.0f/dif))/2.0f; // meaningless formula + ghoul2.mBoneCache->mSmoothFactor = val; // meaningless formula + ghoul2.mBoneCache->mSmoothingActive = true; - if (r_Ghoul2UnSqashAfterSmooth->integer) - { - ghoul2.mBoneCache->mUnsquash=true; + if (r_Ghoul2UnSqashAfterSmooth->integer) { + ghoul2.mBoneCache->mUnsquash = true; } } - } - else - { - ghoul2.mBoneCache->mSmoothFactor=1.0f; + } else { + ghoul2.mBoneCache->mSmoothFactor = 1.0f; } ghoul2.mBoneCache->mCurrentTouch++; -//rww - RAGDOLL_BEGIN - if (HackadelicOnClient) - { - ghoul2.mBoneCache->mLastLastTouch=ghoul2.mBoneCache->mCurrentTouch; - ghoul2.mBoneCache->mCurrentTouchRender=ghoul2.mBoneCache->mCurrentTouch; - } - else - { - ghoul2.mBoneCache->mCurrentTouchRender=0; + // rww - RAGDOLL_BEGIN + if (HackadelicOnClient) { + ghoul2.mBoneCache->mLastLastTouch = ghoul2.mBoneCache->mCurrentTouch; + ghoul2.mBoneCache->mCurrentTouchRender = ghoul2.mBoneCache->mCurrentTouch; + } else { + ghoul2.mBoneCache->mCurrentTouchRender = 0; } -//rww - RAGDOLL_END + // rww - RAGDOLL_END - ghoul2.mBoneCache->frameSize = 0;// can be deleted in new G2 format //(size_t)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); + ghoul2.mBoneCache->frameSize = 0; // can be deleted in new G2 format //(size_t)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); - ghoul2.mBoneCache->rootBoneList=&rootBoneList; - ghoul2.mBoneCache->rootMatrix=rootMatrix; - ghoul2.mBoneCache->incomingTime=time; + ghoul2.mBoneCache->rootBoneList = &rootBoneList; + ghoul2.mBoneCache->rootMatrix = rootMatrix; + ghoul2.mBoneCache->incomingTime = time; - SBoneCalc &TB=ghoul2.mBoneCache->Root(); - TB.newFrame=0; - TB.currentFrame=0; - TB.backlerp=0.0f; - TB.blendFrame=0; - TB.blendOldFrame=0; - TB.blendMode=false; - TB.blendLerp=0; + SBoneCalc &TB = ghoul2.mBoneCache->Root(); + TB.newFrame = 0; + TB.currentFrame = 0; + TB.backlerp = 0.0f; + TB.blendFrame = 0; + TB.blendOldFrame = 0; + TB.blendMode = false; + TB.blendLerp = 0; #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_TransformGhoulBones += G2PerformanceTimer_G2_TransformGhoulBones.End(); #endif } - #define MDX_TAG_ORIGIN 2 //====================================================================== // // Surface Manipulation code - // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, surfaceInfo_t *surfInfo, model_t *mod) -{ - mdxmVertex_t *v, *vert0, *vert1, *vert2; - matrix3_t axes, sides; - float pTri[3][3], d; - int j, k; +void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, surfaceInfo_t *surfInfo, model_t *mod) { + mdxmVertex_t *v, *vert0, *vert1, *vert2; + matrix3_t axes, sides; + float pTri[3][3], d; + int j, k; // now there are two types of tag surface - model ones and procedural generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; - int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface((void*)mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -2037,63 +1690,69 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt // decide where the original verts are - vert0 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert0+= index0; + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; - vert1 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert1+= index1; + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; - vert2 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert2+= index2; + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; // clear out the triangle verts to be - VectorClear( pTri[0] ); - VectorClear( pTri[1] ); - VectorClear( pTri[2] ); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); -// mdxmWeight_t *w; + // mdxmWeight_t *w; - int *piBoneRefs = (int*) ((byte*)originalSurf + originalSurf->ofsBoneReferences); + int *piBoneRefs = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); // now go and transform just the points we need from the surface that was hit originally -// w = vert0->weights; + // w = vert0->weights; float fTotalWeight = 0.0f; - int iNumWeights = G2_GetVertWeights( vert0 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert0, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert0, k, fTotalWeight, iNumWeights ); - - pTri[0][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[0][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[0][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); - } -// w = vert1->weights; + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); + + pTri[0][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + // w = vert1->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert1 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert1, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert1, k, fTotalWeight, iNumWeights ); - - pTri[1][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[1][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[1][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); - } -// w = vert2->weights; + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); + + pTri[1][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + // w = vert2->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert2 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert2, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert2, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); - pTri[2][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[2][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[2][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); + pTri[2][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } - vec3_t normal; + vec3_t normal; vec3_t up; vec3_t right; vec3_t vec0, vec1; @@ -2101,9 +1760,12 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt float baryCentricK = 1.0 - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); // now we have the model transformed into model space, now generate an origin. - boltList[boltNum].position.matrix[0][3] = (pTri[0][0] * surfInfo->genBarycentricI) + (pTri[1][0] * surfInfo->genBarycentricJ) + (pTri[2][0] * baryCentricK); - boltList[boltNum].position.matrix[1][3] = (pTri[0][1] * surfInfo->genBarycentricI) + (pTri[1][1] * surfInfo->genBarycentricJ) + (pTri[2][1] * baryCentricK); - boltList[boltNum].position.matrix[2][3] = (pTri[0][2] * surfInfo->genBarycentricI) + (pTri[1][2] * surfInfo->genBarycentricJ) + (pTri[2][2] * baryCentricK); + boltList[boltNum].position.matrix[0][3] = + (pTri[0][0] * surfInfo->genBarycentricI) + (pTri[1][0] * surfInfo->genBarycentricJ) + (pTri[2][0] * baryCentricK); + boltList[boltNum].position.matrix[1][3] = + (pTri[0][1] * surfInfo->genBarycentricI) + (pTri[1][1] * surfInfo->genBarycentricJ) + (pTri[2][1] * baryCentricK); + boltList[boltNum].position.matrix[2][3] = + (pTri[0][2] * surfInfo->genBarycentricI) + (pTri[1][2] * surfInfo->genBarycentricJ) + (pTri[2][2] * baryCentricK); // generate a normal to this new triangle VectorSubtract(pTri[0], pTri[1], vec0); @@ -2133,74 +1795,72 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt // right is always straight - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector boltList[boltNum].position.matrix[0][2] = right[0]; boltList[boltNum].position.matrix[1][2] = right[1]; boltList[boltNum].position.matrix[2][2] = right[2]; - } // no, we are looking at a normal model tag - else - { - int *piBoneRefs = (int*) ((byte*)surface + surface->ofsBoneReferences); + else { + int *piBoneRefs = (int *)((byte *)surface + surface->ofsBoneReferences); - // whip through and actually transform each vertex - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - for ( j = 0; j < 3; j++ ) - { -// mdxmWeight_t *w; + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + for (j = 0; j < 3; j++) { + // mdxmWeight_t *w; - VectorClear( pTri[j] ); - // w = v->weights; + VectorClear(pTri[j]); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); - - //bone = bonePtr + piBoneRefs[w->boneIndex]; - pTri[j][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[j][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[j][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); - } - - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; - } - - // clear out used arrays - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); - - // work out actual sides of the tag triangle - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j+1)%3][0] - pTri[j][0]; - sides[j][1] = pTri[(j+1)%3][1] - pTri[j][1]; - sides[j][2] = pTri[(j+1)%3][2] - pTri[j][2]; - } - - // do math trig to work out what the matrix will be from this triangle's translated position - VectorNormalize2( sides[iG2_TRISIDE_LONGEST], axes[0] ); - VectorNormalize2( sides[iG2_TRISIDE_SHORTEST], axes[1] ); - - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize2( axes[0], axes[0] ); - - CrossProduct( sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2] ); - VectorNormalize2( axes[2], axes[2] ); - - // set up location in world space of the origin point in out going matrix - boltList[boltNum].position.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - boltList[boltNum].position.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - boltList[boltNum].position.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; - - // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + + // bone = bonePtr + piBoneRefs[w->boneIndex]; + pTri[j][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } + + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); + + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } + + // do math trig to work out what the matrix will be from this triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + + // project shortest side so that it is exactly 90 degrees to the longer side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); + + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); + + // set up location in world space of the origin point in out going matrix + boltList[boltNum].position.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + boltList[boltNum].position.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + boltList[boltNum].position.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + + // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly boltList[boltNum].position.matrix[0][0] = axes[1][0]; boltList[boltNum].position.matrix[0][1] = axes[0][0]; boltList[boltNum].position.matrix[0][2] = -axes[2][0]; @@ -2213,27 +1873,21 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt boltList[boltNum].position.matrix[2][1] = axes[0][2]; boltList[boltNum].position.matrix[2][2] = -axes[2][2]; } - } - // now go through all the generated surfaces that aren't included in the model surface hierarchy and create the correct bolt info for them -void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) -{ +void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.Start(); #endif // look through the surfaces off the end of the pre-defined model surfaces - for (size_t i=0; i< ghoul2.mSlist.size(); i++) - { + for (size_t i = 0; i < ghoul2.mSlist.size(); i++) { // only look for bolts if we are actually a generated surface, and not just an overriden one - if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) - { - // well alrighty then. Lets see if there is a bolt that is attempting to use it + if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) { + // well alrighty then. Lets see if there is a bolt that is attempting to use it int boltNum = G2_Find_Bolt_Surface_Num(ghoul2.mBltlist, i, G2SURFACEFLAG_GENERATED); // yes - ok, processing time. - if (boltNum != -1) - { + if (boltNum != -1) { G2_ProcessSurfaceBolt(bonePtr, NULL, boltNum, ghoul2.mBltlist, &ghoul2.mSlist[i], mod_t); } } @@ -2244,53 +1898,46 @@ void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, m } // Go through the model and deal with just the surfaces that are tagged as bolt on points - this is for the server side skeleton construction -void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - mdxaBone_v &bonePtr, model_t *currentModel, int lod, boltInfo_v &boltList) -{ +void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, mdxaBone_v &bonePtr, model_t *currentModel, int lod, boltInfo_v &boltList) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_ProcessModelBoltSurfaces.Start(); #endif - int i; - int offFlags = 0; + int i; + int offFlags = 0; // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // is this surface considered a bolt surface? - if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) - { + if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) { // well alrighty then. Lets see if there is a bolt that is attempting to use it int boltNum = G2_Find_Bolt_Surface_Num(boltList, surfaceNum, 0); // yes - ok, processing time. - if (boltNum != -1) - { + if (boltNum != -1) { G2_ProcessSurfaceBolt(bonePtr, surface, boltNum, boltList, surfOverride, currentModel); } } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { ProcessModelBoltSurfaces(surfInfo->childIndexes[i], rootSList, bonePtr, currentModel, lod, boltList); } @@ -2299,55 +1946,48 @@ void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, #endif } - // build the used bone list so when doing bone transforms we can determine if we need to do it or not -void G2_ConstructUsedBoneList(CConstructBoneList &CBL) -{ - int i, j; - int offFlags = 0; +void G2_ConstructUsedBoneList(CConstructBoneList &CBL) { + int i, j; + int offFlags = 0; // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)CBL.currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); - const model_t *mod_a = R_GetModelByHandle(CBL.currentModel->mdxm->animIndex); - const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); - const mdxaSkel_t *skel, *childSkel; + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)CBL.currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const model_t *mod_a = R_GetModelByHandle(CBL.currentModel->mdxm->animIndex); + const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel, *childSkel; // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { - int *bonesReferenced = (int *)((byte*)surface + surface->ofsBoneReferences); + if (!(offFlags & G2SURFACEFLAG_OFF)) { + int *bonesReferenced = (int *)((byte *)surface + surface->ofsBoneReferences); // now whip through the bones this surface uses - for (i=0; inumBoneReferences;i++) - { + for (i = 0; i < surface->numBoneReferences; i++) { int iBoneIndex = bonesReferenced[i]; CBL.boneUsedList[iBoneIndex] = 1; // now go and check all the descendant bones attached to this bone and see if any have the always flag on them. If so, activate them - skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); + skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); // for every child bone... - for (j=0; j< skel->numChildren; j++) - { + for (j = 0; j < skel->numChildren; j++) { // get the skel data struct for each child bone of the referenced bone - childSkel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); + childSkel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); // does it have the always on flag on? - if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) - { + if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) { // yes, make sure it's in the list of bones to be transformed. CBL.boneUsedList[skel->children[j]] = 1; } @@ -2356,94 +1996,77 @@ void G2_ConstructUsedBoneList(CConstructBoneList &CBL) // now we need to ensure that the parents of this bone are actually active... // int iParentBone = skel->parent; - while (iParentBone != -1) - { - if (CBL.boneUsedList[iParentBone]) // no need to go higher + while (iParentBone != -1) { + if (CBL.boneUsedList[iParentBone]) // no need to go higher break; CBL.boneUsedList[iParentBone] = 1; skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iParentBone]); iParentBone = skel->parent; } } - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { CBL.surfaceNum = surfInfo->childIndexes[i]; G2_ConstructUsedBoneList(CBL); } } - // sort all the ghoul models in this list so if they go in reference order. This will ensure the bolt on's are attached to the right place // on the previous model, since it ensures the model being attached to is built and rendered first. // NOTE!! This assumes at least one model will NOT have a parent. If it does - we are screwed -static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int * const modelList, int * const modelCount) -{ - int startPoint, endPoint; - int i, boltTo, j; +static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int *const modelList, int *const modelCount) { + int startPoint, endPoint; + int i, boltTo, j; *modelCount = 0; // first walk all the possible ghoul2 models, and stuff the out array with those with no parents - for (i=0; i> MODEL_SHIFT) & MODEL_AND; // is it any of the models we just added to the list? - for (j=startPoint; jmdxm); // point at first lod list - byte *current = (byte*)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); + byte *current = (byte *)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); int i; - //walk the lods - assert(lod>=0&&lodmdxm->numLODs); - for (i=0; i= 0 && lod < mod->mdxm->numLODs); + for (i = 0; i < lod; i++) { mdxmLOD_t *lodData = (mdxmLOD_t *)current; current += lodData->ofsEnd; } @@ -2479,7 +2100,7 @@ void *G2_FindSurface_BC(const model_s *mod, int index, int lod) mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; // we are now looking at the offset array - assert(index>=0&&indexmdxm->numSurfaces); + assert(index >= 0 && index < mod->mdxm->numSurfaces); current += indexes->offsets[index]; return (void *)current; @@ -2488,22 +2109,21 @@ void *G2_FindSurface_BC(const model_s *mod, int index, int lod) //#define G2EVALRENDER // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, const model_t *mod,mdxaBone_t &retMatrix) -{ - mdxmVertex_t *v, *vert0, *vert1, *vert2; - matrix3_t axes, sides; - float pTri[3][3], d; - int j, k; +void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, + const model_t *mod, mdxaBone_t &retMatrix) { + mdxmVertex_t *v, *vert0, *vert1, *vert2; + matrix3_t axes, sides; + float pTri[3][3], d; + int j, k; // now there are two types of tag surface - model ones and procedural generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; - int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -2511,82 +2131,79 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int index2 = originalTriangleIndexes[polyNumber].indexes[2]; // decide where the original verts are - vert0 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert0+=index0; + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; - vert1 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert1+=index1; + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; - vert2 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert2+=index2; + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; // clear out the triangle verts to be - VectorClear( pTri[0] ); - VectorClear( pTri[1] ); - VectorClear( pTri[2] ); - int *piBoneReferences = (int*) ((byte*)originalSurf + originalSurf->ofsBoneReferences); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + int *piBoneReferences = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); -// mdxmWeight_t *w; + // mdxmWeight_t *w; // now go and transform just the points we need from the surface that was hit originally -// w = vert0->weights; + // w = vert0->weights; float fTotalWeight = 0.0f; - int iNumWeights = G2_GetVertWeights( vert0 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert0, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert0, k, fTotalWeight, iNumWeights ); + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[0][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert0->vertCoords ) + bone.matrix[0][3] ); - pTri[0][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert0->vertCoords ) + bone.matrix[1][3] ); - pTri[0][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert0->vertCoords ) + bone.matrix[2][3] ); + pTri[0][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert0->vertCoords) + bone.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert0->vertCoords) + bone.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert0->vertCoords) + bone.matrix[2][3]); } -// w = vert1->weights; + // w = vert1->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert1 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert1, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert1, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[1][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert1->vertCoords ) + bone.matrix[0][3] ); - pTri[1][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert1->vertCoords ) + bone.matrix[1][3] ); - pTri[1][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert1->vertCoords ) + bone.matrix[2][3] ); + pTri[1][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert1->vertCoords) + bone.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert1->vertCoords) + bone.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert1->vertCoords) + bone.matrix[2][3]); } -// w = vert2->weights; + // w = vert2->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert2 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert2, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert2, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[2][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert2->vertCoords ) + bone.matrix[0][3] ); - pTri[2][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert2->vertCoords ) + bone.matrix[1][3] ); - pTri[2][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert2->vertCoords ) + bone.matrix[2][3] ); + pTri[2][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert2->vertCoords) + bone.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert2->vertCoords) + bone.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert2->vertCoords) + bone.matrix[2][3]); } - vec3_t normal; + vec3_t normal; vec3_t up; vec3_t right; vec3_t vec0, vec1; @@ -2626,79 +2243,74 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, // right is always straight - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector retMatrix.matrix[0][2] = right[0]; retMatrix.matrix[1][2] = right[1]; retMatrix.matrix[2][2] = right[2]; - } // no, we are looking at a normal model tag - else - { - // whip through and actually transform each vertex - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); - for ( j = 0; j < 3; j++ ) - { -// mdxmWeight_t *w; + else { + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); + for (j = 0; j < 3; j++) { + // mdxmWeight_t *w; - VectorClear( pTri[j] ); - // w = v->weights; + VectorClear(pTri[j]); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[j][0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - pTri[j][1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - pTri[j][2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); - } + pTri[j][0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); + } - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; - } + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } - // clear out used arrays - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); - // work out actual sides of the tag triangle - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j+1)%3][0] - pTri[j][0]; - sides[j][1] = pTri[(j+1)%3][1] - pTri[j][1]; - sides[j][2] = pTri[(j+1)%3][2] - pTri[j][2]; - } + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } - // do math trig to work out what the matrix will be from this triangle's translated position - VectorNormalize2( sides[iG2_TRISIDE_LONGEST], axes[0] ); - VectorNormalize2( sides[iG2_TRISIDE_SHORTEST], axes[1] ); + // do math trig to work out what the matrix will be from this triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize2( axes[0], axes[0] ); + // project shortest side so that it is exactly 90 degrees to the longer side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); - CrossProduct( sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2] ); - VectorNormalize2( axes[2], axes[2] ); + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); - // set up location in world space of the origin point in out going matrix - retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + // set up location in world space of the origin point in out going matrix + retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; - // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly + // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly retMatrix.matrix[0][0] = axes[1][0]; retMatrix.matrix[0][1] = axes[0][0]; retMatrix.matrix[0][2] = -axes[2][0]; @@ -2711,28 +2323,25 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, retMatrix.matrix[2][1] = axes[0][2]; retMatrix.matrix[2][2] = -axes[2][2]; } - } -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - boltInfo_v &boltList=ghoul2.mBltlist; + boltInfo_v &boltList = ghoul2.mBltlist; - if ( boltList.size() < 1 ) { - retMatrix=identityMatrix; + if (boltList.size() < 1) { + retMatrix = identityMatrix; return; } - assert(boltNum>=0&&boltNum<(int)boltList.size()); -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. + assert(boltNum >= 0 && boltNum < (int)boltList.size()); +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. if (boltNum < 0 || boltNum >= boltList.size()) { char fName[MAX_QPATH]; @@ -2760,78 +2369,65 @@ void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxa Com_Error(ERR_DROP, "Write down or save this error message, show it to Rich\nBad bolt index on model %s (filename %s), index %i boltlink %i\n", mName, fName, boltNum, bLink); } #endif - if (boltList[boltNum].boneNumber>=0) - { - mdxaSkel_t *skel; + if (boltList[boltNum].boneNumber >= 0) { + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boltList[boltNum].boneNumber]); Multiply_3x4Matrix(&retMatrix, (mdxaBone_t *)&boneCache.EvalUnsmooth(boltList[boltNum].boneNumber), &skel->BasePoseMat); - } - else if (boltList[boltNum].surfaceNumber>=0) - { - const surfaceInfo_t *surfInfo=0; + } else if (boltList[boltNum].surfaceNumber >= 0) { + const surfaceInfo_t *surfInfo = 0; { - for (size_t i=0;isurface<10000) - { - surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod,surfInfo->surface, 0); + if (!surface && surfInfo && surfInfo->surface < 10000) { + surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod, surfInfo->surface, 0); } - G2_ProcessSurfaceBolt2(boneCache,surface,boltNum,boltList,surfInfo,(model_t *)boneCache.mod,retMatrix); - } - else - { - // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix - retMatrix=identityMatrix; + G2_ProcessSurfaceBolt2(boneCache, surface, boltNum, boltList, surfInfo, (model_t *)boneCache.mod, retMatrix); + } else { + // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix + retMatrix = identityMatrix; } } -static void RootMatrix(CGhoul2Info_v &ghoul2,int time,const vec3_t scale,mdxaBone_t &retMatrix) -{ +static void RootMatrix(CGhoul2Info_v &ghoul2, int time, const vec3_t scale, mdxaBone_t &retMatrix) { int i; - for (i=0; imSkelFrameNum!=frameNum|| - !ghlInfo->mBoneCache|| - ghlInfo->mBoneCache->mod!=ghlInfo->currentModel) - { + if (ghlInfo->mSkelFrameNum != frameNum || !ghlInfo->mBoneCache || ghlInfo->mBoneCache->mod != ghlInfo->currentModel) { #ifdef _G2_LISTEN_SERVER_OPT - if (ghlInfo->entityNum != ENTITYNUM_NONE && - G2API_OverrideServerWithClientData(ghlInfo)) - { //if we can manage this, then we don't have to reconstruct + if (ghlInfo->entityNum != ENTITYNUM_NONE && G2API_OverrideServerWithClientData(ghlInfo)) { // if we can manage this, then we don't have to reconstruct return false; } #endif - ghlInfo->mSkelFrameNum=frameNum; + ghlInfo->mSkelFrameNum = frameNum; return true; } return false; @@ -2884,46 +2473,39 @@ bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) G2_ConstructGhoulSkeleton - builds a complete skeleton for all ghoul models in a CGhoul2Info_v class - using LOD 0 ============== */ -void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool checkForNewOrigin,const vec3_t scale) -{ +void G2_ConstructGhoulSkeleton(CGhoul2Info_v &ghoul2, const int frameNum, bool checkForNewOrigin, const vec3_t scale) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ConstructGhoulSkeleton.Start(); #endif - int i, j; - int modelCount; - mdxaBone_t rootMatrix; + int i, j; + int modelCount; + mdxaBone_t rootMatrix; int modelList[256]; - assert(ghoul2.size()<=255); - modelList[255]=548; + assert(ghoul2.size() <= 255); + modelList[255] = 548; - if (checkForNewOrigin) - { - RootMatrix(ghoul2,frameNum,scale,rootMatrix); - } - else - { + if (checkForNewOrigin) { + RootMatrix(ghoul2, frameNum, scale, rootMatrix); + } else { rootMatrix = identityMatrix; } G2_Sort_Models(ghoul2, modelList, &modelCount); - assert(modelList[255]==548); + assert(modelList[255] == 548); - for (j=0; j> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mValid) { + if (j && ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; - G2_GetBoltMatrixLow(ghoul2[boltMod],boltNum,scale,bolt); - G2_TransformGhoulBones(ghoul2[i].mBlist,bolt,ghoul2[i],frameNum,checkForNewOrigin); + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, scale, bolt); + G2_TransformGhoulBones(ghoul2[i].mBlist, bolt, ghoul2[i], frameNum, checkForNewOrigin); } #ifdef _G2_LISTEN_SERVER_OPT else if (ghoul2[i].entityNum == ENTITYNUM_NONE || ghoul2[i].mSkelFrameNum != frameNum) @@ -2931,7 +2513,7 @@ void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool ch else #endif { - G2_TransformGhoulBones(ghoul2[i].mBlist,rootMatrix,ghoul2[i],frameNum,checkForNewOrigin); + G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i], frameNum, checkForNewOrigin); } } } @@ -2956,360 +2538,358 @@ Complete list of all 72 bones: */ int OldToNewRemapTable[72] = { -0,// Bone 0: "model_root": Parent: "" (index -1) -1,// Bone 1: "pelvis": Parent: "model_root" (index 0) -2,// Bone 2: "Motion": Parent: "pelvis" (index 1) -3,// Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) -4,// Bone 4: "lfemurX": Parent: "pelvis" (index 1) -5,// Bone 5: "ltibia": Parent: "pelvis" (index 1) -6,// Bone 6: "ltalus": Parent: "pelvis" (index 1) -6,// Bone 7: "ltarsal": Parent: "pelvis" (index 1) -7,// Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) -8,// Bone 9: "rfemurX": Parent: "pelvis" (index 1) -9,// Bone10: "rtibia": Parent: "pelvis" (index 1) -10,// Bone11: "rtalus": Parent: "pelvis" (index 1) -10,// Bone12: "rtarsal": Parent: "pelvis" (index 1) -11,// Bone13: "lower_lumbar": Parent: "pelvis" (index 1) -12,// Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) -13,// Bone15: "thoracic": Parent: "upper_lumbar" (index 14) -14,// Bone16: "cervical": Parent: "thoracic" (index 15) -15,// Bone17: "cranium": Parent: "cervical" (index 16) -16,// Bone18: "ceyebrow": Parent: "face_always_" (index 71) -17,// Bone19: "jaw": Parent: "face_always_" (index 71) -18,// Bone20: "lblip2": Parent: "face_always_" (index 71) -19,// Bone21: "leye": Parent: "face_always_" (index 71) -20,// Bone22: "rblip2": Parent: "face_always_" (index 71) -21,// Bone23: "ltlip2": Parent: "face_always_" (index 71) -22,// Bone24: "rtlip2": Parent: "face_always_" (index 71) -23,// Bone25: "reye": Parent: "face_always_" (index 71) -24,// Bone26: "rclavical": Parent: "thoracic" (index 15) -25,// Bone27: "rhumerus": Parent: "thoracic" (index 15) -26,// Bone28: "rhumerusX": Parent: "thoracic" (index 15) -27,// Bone29: "rradius": Parent: "thoracic" (index 15) -28,// Bone30: "rradiusX": Parent: "thoracic" (index 15) -29,// Bone31: "rhand": Parent: "thoracic" (index 15) -29,// Bone32: "mc7": Parent: "thoracic" (index 15) -34,// Bone33: "r_d5_j1": Parent: "thoracic" (index 15) -35,// Bone34: "r_d5_j2": Parent: "thoracic" (index 15) -35,// Bone35: "r_d5_j3": Parent: "thoracic" (index 15) -30,// Bone36: "r_d1_j1": Parent: "thoracic" (index 15) -31,// Bone37: "r_d1_j2": Parent: "thoracic" (index 15) -31,// Bone38: "r_d1_j3": Parent: "thoracic" (index 15) -32,// Bone39: "r_d2_j1": Parent: "thoracic" (index 15) -33,// Bone40: "r_d2_j2": Parent: "thoracic" (index 15) -33,// Bone41: "r_d2_j3": Parent: "thoracic" (index 15) -32,// Bone42: "r_d3_j1": Parent: "thoracic" (index 15) -33,// Bone43: "r_d3_j2": Parent: "thoracic" (index 15) -33,// Bone44: "r_d3_j3": Parent: "thoracic" (index 15) -34,// Bone45: "r_d4_j1": Parent: "thoracic" (index 15) -35,// Bone46: "r_d4_j2": Parent: "thoracic" (index 15) -35,// Bone47: "r_d4_j3": Parent: "thoracic" (index 15) -36,// Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) -37,// Bone49: "lclavical": Parent: "thoracic" (index 15) -38,// Bone50: "lhumerus": Parent: "thoracic" (index 15) -39,// Bone51: "lhumerusX": Parent: "thoracic" (index 15) -40,// Bone52: "lradius": Parent: "thoracic" (index 15) -41,// Bone53: "lradiusX": Parent: "thoracic" (index 15) -42,// Bone54: "lhand": Parent: "thoracic" (index 15) -42,// Bone55: "mc5": Parent: "thoracic" (index 15) -43,// Bone56: "l_d5_j1": Parent: "thoracic" (index 15) -44,// Bone57: "l_d5_j2": Parent: "thoracic" (index 15) -44,// Bone58: "l_d5_j3": Parent: "thoracic" (index 15) -43,// Bone59: "l_d4_j1": Parent: "thoracic" (index 15) -44,// Bone60: "l_d4_j2": Parent: "thoracic" (index 15) -44,// Bone61: "l_d4_j3": Parent: "thoracic" (index 15) -45,// Bone62: "l_d3_j1": Parent: "thoracic" (index 15) -46,// Bone63: "l_d3_j2": Parent: "thoracic" (index 15) -46,// Bone64: "l_d3_j3": Parent: "thoracic" (index 15) -45,// Bone65: "l_d2_j1": Parent: "thoracic" (index 15) -46,// Bone66: "l_d2_j2": Parent: "thoracic" (index 15) -46,// Bone67: "l_d2_j3": Parent: "thoracic" (index 15) -47,// Bone68: "l_d1_j1": Parent: "thoracic" (index 15) -48,// Bone69: "l_d1_j2": Parent: "thoracic" (index 15) -48,// Bone70: "l_d1_j3": Parent: "thoracic" (index 15) -52// Bone71: "face_always_": Parent: "cranium" (index 17) + 0, // Bone 0: "model_root": Parent: "" (index -1) + 1, // Bone 1: "pelvis": Parent: "model_root" (index 0) + 2, // Bone 2: "Motion": Parent: "pelvis" (index 1) + 3, // Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) + 4, // Bone 4: "lfemurX": Parent: "pelvis" (index 1) + 5, // Bone 5: "ltibia": Parent: "pelvis" (index 1) + 6, // Bone 6: "ltalus": Parent: "pelvis" (index 1) + 6, // Bone 7: "ltarsal": Parent: "pelvis" (index 1) + 7, // Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) + 8, // Bone 9: "rfemurX": Parent: "pelvis" (index 1) + 9, // Bone10: "rtibia": Parent: "pelvis" (index 1) + 10, // Bone11: "rtalus": Parent: "pelvis" (index 1) + 10, // Bone12: "rtarsal": Parent: "pelvis" (index 1) + 11, // Bone13: "lower_lumbar": Parent: "pelvis" (index 1) + 12, // Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) + 13, // Bone15: "thoracic": Parent: "upper_lumbar" (index 14) + 14, // Bone16: "cervical": Parent: "thoracic" (index 15) + 15, // Bone17: "cranium": Parent: "cervical" (index 16) + 16, // Bone18: "ceyebrow": Parent: "face_always_" (index 71) + 17, // Bone19: "jaw": Parent: "face_always_" (index 71) + 18, // Bone20: "lblip2": Parent: "face_always_" (index 71) + 19, // Bone21: "leye": Parent: "face_always_" (index 71) + 20, // Bone22: "rblip2": Parent: "face_always_" (index 71) + 21, // Bone23: "ltlip2": Parent: "face_always_" (index 71) + 22, // Bone24: "rtlip2": Parent: "face_always_" (index 71) + 23, // Bone25: "reye": Parent: "face_always_" (index 71) + 24, // Bone26: "rclavical": Parent: "thoracic" (index 15) + 25, // Bone27: "rhumerus": Parent: "thoracic" (index 15) + 26, // Bone28: "rhumerusX": Parent: "thoracic" (index 15) + 27, // Bone29: "rradius": Parent: "thoracic" (index 15) + 28, // Bone30: "rradiusX": Parent: "thoracic" (index 15) + 29, // Bone31: "rhand": Parent: "thoracic" (index 15) + 29, // Bone32: "mc7": Parent: "thoracic" (index 15) + 34, // Bone33: "r_d5_j1": Parent: "thoracic" (index 15) + 35, // Bone34: "r_d5_j2": Parent: "thoracic" (index 15) + 35, // Bone35: "r_d5_j3": Parent: "thoracic" (index 15) + 30, // Bone36: "r_d1_j1": Parent: "thoracic" (index 15) + 31, // Bone37: "r_d1_j2": Parent: "thoracic" (index 15) + 31, // Bone38: "r_d1_j3": Parent: "thoracic" (index 15) + 32, // Bone39: "r_d2_j1": Parent: "thoracic" (index 15) + 33, // Bone40: "r_d2_j2": Parent: "thoracic" (index 15) + 33, // Bone41: "r_d2_j3": Parent: "thoracic" (index 15) + 32, // Bone42: "r_d3_j1": Parent: "thoracic" (index 15) + 33, // Bone43: "r_d3_j2": Parent: "thoracic" (index 15) + 33, // Bone44: "r_d3_j3": Parent: "thoracic" (index 15) + 34, // Bone45: "r_d4_j1": Parent: "thoracic" (index 15) + 35, // Bone46: "r_d4_j2": Parent: "thoracic" (index 15) + 35, // Bone47: "r_d4_j3": Parent: "thoracic" (index 15) + 36, // Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) + 37, // Bone49: "lclavical": Parent: "thoracic" (index 15) + 38, // Bone50: "lhumerus": Parent: "thoracic" (index 15) + 39, // Bone51: "lhumerusX": Parent: "thoracic" (index 15) + 40, // Bone52: "lradius": Parent: "thoracic" (index 15) + 41, // Bone53: "lradiusX": Parent: "thoracic" (index 15) + 42, // Bone54: "lhand": Parent: "thoracic" (index 15) + 42, // Bone55: "mc5": Parent: "thoracic" (index 15) + 43, // Bone56: "l_d5_j1": Parent: "thoracic" (index 15) + 44, // Bone57: "l_d5_j2": Parent: "thoracic" (index 15) + 44, // Bone58: "l_d5_j3": Parent: "thoracic" (index 15) + 43, // Bone59: "l_d4_j1": Parent: "thoracic" (index 15) + 44, // Bone60: "l_d4_j2": Parent: "thoracic" (index 15) + 44, // Bone61: "l_d4_j3": Parent: "thoracic" (index 15) + 45, // Bone62: "l_d3_j1": Parent: "thoracic" (index 15) + 46, // Bone63: "l_d3_j2": Parent: "thoracic" (index 15) + 46, // Bone64: "l_d3_j3": Parent: "thoracic" (index 15) + 45, // Bone65: "l_d2_j1": Parent: "thoracic" (index 15) + 46, // Bone66: "l_d2_j2": Parent: "thoracic" (index 15) + 46, // Bone67: "l_d2_j3": Parent: "thoracic" (index 15) + 47, // Bone68: "l_d1_j1": Parent: "thoracic" (index 15) + 48, // Bone69: "l_d1_j2": Parent: "thoracic" (index 15) + 48, // Bone70: "l_d1_j3": Parent: "thoracic" (index 15) + 52 // Bone71: "face_always_": Parent: "cranium" (index 17) }; - /* Bone 0: "model_root": - Parent: "" (index -1) - #Kids: 1 - Child 0: (index 1), name "pelvis" + Parent: "" (index -1) + #Kids: 1 + Child 0: (index 1), name "pelvis" Bone 1: "pelvis": - Parent: "model_root" (index 0) - #Kids: 4 - Child 0: (index 2), name "Motion" - Child 1: (index 3), name "lfemurYZ" - Child 2: (index 7), name "rfemurYZ" - Child 3: (index 11), name "lower_lumbar" + Parent: "model_root" (index 0) + #Kids: 4 + Child 0: (index 2), name "Motion" + Child 1: (index 3), name "lfemurYZ" + Child 2: (index 7), name "rfemurYZ" + Child 3: (index 11), name "lower_lumbar" Bone 2: "Motion": - Parent: "pelvis" (index 1) - #Kids: 0 + Parent: "pelvis" (index 1) + #Kids: 0 Bone 3: "lfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 4), name "lfemurX" - Child 1: (index 5), name "ltibia" - Child 2: (index 49), name "ltail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 4), name "lfemurX" + Child 1: (index 5), name "ltibia" + Child 2: (index 49), name "ltail" Bone 4: "lfemurX": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 5: "ltibia": - Parent: "lfemurYZ" (index 3) - #Kids: 1 - Child 0: (index 6), name "ltalus" + Parent: "lfemurYZ" (index 3) + #Kids: 1 + Child 0: (index 6), name "ltalus" Bone 6: "ltalus": - Parent: "ltibia" (index 5) - #Kids: 0 + Parent: "ltibia" (index 5) + #Kids: 0 Bone 7: "rfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 8), name "rfemurX" - Child 1: (index 9), name "rtibia" - Child 2: (index 50), name "rtail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 8), name "rfemurX" + Child 1: (index 9), name "rtibia" + Child 2: (index 50), name "rtail" Bone 8: "rfemurX": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 9: "rtibia": - Parent: "rfemurYZ" (index 7) - #Kids: 1 - Child 0: (index 10), name "rtalus" + Parent: "rfemurYZ" (index 7) + #Kids: 1 + Child 0: (index 10), name "rtalus" Bone 10: "rtalus": - Parent: "rtibia" (index 9) - #Kids: 0 + Parent: "rtibia" (index 9) + #Kids: 0 Bone 11: "lower_lumbar": - Parent: "pelvis" (index 1) - #Kids: 1 - Child 0: (index 12), name "upper_lumbar" + Parent: "pelvis" (index 1) + #Kids: 1 + Child 0: (index 12), name "upper_lumbar" Bone 12: "upper_lumbar": - Parent: "lower_lumbar" (index 11) - #Kids: 1 - Child 0: (index 13), name "thoracic" + Parent: "lower_lumbar" (index 11) + #Kids: 1 + Child 0: (index 13), name "thoracic" Bone 13: "thoracic": - Parent: "upper_lumbar" (index 12) - #Kids: 5 - Child 0: (index 14), name "cervical" - Child 1: (index 24), name "rclavical" - Child 2: (index 25), name "rhumerus" - Child 3: (index 37), name "lclavical" - Child 4: (index 38), name "lhumerus" + Parent: "upper_lumbar" (index 12) + #Kids: 5 + Child 0: (index 14), name "cervical" + Child 1: (index 24), name "rclavical" + Child 2: (index 25), name "rhumerus" + Child 3: (index 37), name "lclavical" + Child 4: (index 38), name "lhumerus" Bone 14: "cervical": - Parent: "thoracic" (index 13) - #Kids: 1 - Child 0: (index 15), name "cranium" + Parent: "thoracic" (index 13) + #Kids: 1 + Child 0: (index 15), name "cranium" Bone 15: "cranium": - Parent: "cervical" (index 14) - #Kids: 1 - Child 0: (index 52), name "face_always_" + Parent: "cervical" (index 14) + #Kids: 1 + Child 0: (index 52), name "face_always_" Bone 16: "ceyebrow": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 17: "jaw": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 18: "lblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 19: "leye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 20: "rblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 21: "ltlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 22: "rtlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 23: "reye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 24: "rclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 25: "rhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 26), name "rhumerusX" - Child 1: (index 27), name "rradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 26), name "rhumerusX" + Child 1: (index 27), name "rradius" Bone 26: "rhumerusX": - Parent: "rhumerus" (index 25) - #Kids: 0 + Parent: "rhumerus" (index 25) + #Kids: 0 Bone 27: "rradius": - Parent: "rhumerus" (index 25) - #Kids: 9 - Child 0: (index 28), name "rradiusX" - Child 1: (index 29), name "rhand" - Child 2: (index 30), name "r_d1_j1" - Child 3: (index 31), name "r_d1_j2" - Child 4: (index 32), name "r_d2_j1" - Child 5: (index 33), name "r_d2_j2" - Child 6: (index 34), name "r_d4_j1" - Child 7: (index 35), name "r_d4_j2" - Child 8: (index 36), name "rhang_tag_bone" + Parent: "rhumerus" (index 25) + #Kids: 9 + Child 0: (index 28), name "rradiusX" + Child 1: (index 29), name "rhand" + Child 2: (index 30), name "r_d1_j1" + Child 3: (index 31), name "r_d1_j2" + Child 4: (index 32), name "r_d2_j1" + Child 5: (index 33), name "r_d2_j2" + Child 6: (index 34), name "r_d4_j1" + Child 7: (index 35), name "r_d4_j2" + Child 8: (index 36), name "rhang_tag_bone" Bone 28: "rradiusX": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 29: "rhand": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 30: "r_d1_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 31: "r_d1_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 32: "r_d2_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 33: "r_d2_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 34: "r_d4_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 35: "r_d4_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 36: "rhang_tag_bone": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 37: "lclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 38: "lhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 39), name "lhumerusX" - Child 1: (index 40), name "lradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 39), name "lhumerusX" + Child 1: (index 40), name "lradius" Bone 39: "lhumerusX": - Parent: "lhumerus" (index 38) - #Kids: 0 + Parent: "lhumerus" (index 38) + #Kids: 0 Bone 40: "lradius": - Parent: "lhumerus" (index 38) - #Kids: 9 - Child 0: (index 41), name "lradiusX" - Child 1: (index 42), name "lhand" - Child 2: (index 43), name "l_d4_j1" - Child 3: (index 44), name "l_d4_j2" - Child 4: (index 45), name "l_d2_j1" - Child 5: (index 46), name "l_d2_j2" - Child 6: (index 47), name "l_d1_j1" - Child 7: (index 48), name "l_d1_j2" - Child 8: (index 51), name "lhang_tag_bone" + Parent: "lhumerus" (index 38) + #Kids: 9 + Child 0: (index 41), name "lradiusX" + Child 1: (index 42), name "lhand" + Child 2: (index 43), name "l_d4_j1" + Child 3: (index 44), name "l_d4_j2" + Child 4: (index 45), name "l_d2_j1" + Child 5: (index 46), name "l_d2_j2" + Child 6: (index 47), name "l_d1_j1" + Child 7: (index 48), name "l_d1_j2" + Child 8: (index 51), name "lhang_tag_bone" Bone 41: "lradiusX": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 42: "lhand": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 43: "l_d4_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 44: "l_d4_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 45: "l_d2_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 46: "l_d2_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 47: "l_d1_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 48: "l_d1_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 49: "ltail": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 50: "rtail": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 51: "lhang_tag_bone": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 52: "face_always_": - Parent: "cranium" (index 15) - #Kids: 8 - Child 0: (index 16), name "ceyebrow" - Child 1: (index 17), name "jaw" - Child 2: (index 18), name "lblip2" - Child 3: (index 19), name "leye" - Child 4: (index 20), name "rblip2" - Child 5: (index 21), name "ltlip2" - Child 6: (index 22), name "rtlip2" - Child 7: (index 23), name "reye" + Parent: "cranium" (index 15) + #Kids: 8 + Child 0: (index 16), name "ceyebrow" + Child 1: (index 17), name "jaw" + Child 2: (index 18), name "lblip2" + Child 3: (index 19), name "leye" + Child 4: (index 20), name "rblip2" + Child 5: (index 21), name "ltlip2" + Child 6: (index 22), name "rtlip2" + Child 7: (index 23), name "reye" */ - -qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - mdxmSurfHierarchy_t *surfInfo; +qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + mdxmSurfHierarchy_t *surfInfo; #if 0 //#ifndef _M_IX86 int k; @@ -3321,36 +2901,33 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean int *boneRef; #endif - pinmodel= (mdxmHeader_t *)buffer; + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXM_VERSION) { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXM_VERSION); + Com_Printf(S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); return qfalse; } - mod->type = MOD_MDXM; + mod->type = MOD_MDXM; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxm = mod->mdxm = (mdxmHeader_t*) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mdxm = mod->mdxm = (mdxmHeader_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -3358,8 +2935,8 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -3371,62 +2948,54 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean } // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterModel(va ("%s.gla",mdxm->animName)); + mdxm->animIndex = RE_RegisterModel(va("%s.gla", mdxm->animName)); - if (!mdxm->animIndex) - { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); + if (!mdxm->animIndex) { + Com_Printf(S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } bool isAnOldModelFile = false; - if (mdxm->numBones == 72 && strstr(mdxm->animName,"_humanoid") ) - { + if (mdxm->numBones == 72 && strstr(mdxm->animName, "_humanoid")) { isAnOldModelFile = true; } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->numChildren); LL(surfInfo->parentIndex); - Q_strlwr(surfInfo->name); //just in case - if ( !strcmp( &surfInfo->name[strlen(surfInfo->name)-4],"_off") ) - { - surfInfo->name[strlen(surfInfo->name)-4]=0; //remove "_off" from name + Q_strlwr(surfInfo->name); // just in case + if (!strcmp(&surfInfo->name[strlen(surfInfo->name) - 4], "_off")) { + surfInfo->name[strlen(surfInfo->name) - 4] = 0; // remove "_off" from name } // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } surfInfo->shaderIndex = 0; RE_RegisterModels_StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->numTriangles); LL(surf->ofsTriangles); LL(surf->numVerts); @@ -3435,17 +3004,15 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean LL(surf->ofsHeader); LL(surf->numBoneReferences); LL(surf->ofsBoneReferences); -// LL(surf->maxVertBoneWeights); + // LL(surf->maxVertBoneWeights); triCount += surf->numTriangles; - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", - mod_name, SHADER_MAX_VERTEXES, surf->numVerts ); + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", - mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles ); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } // change to surface identifier @@ -3497,27 +3064,22 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean } #endif - if (isAnOldModelFile) - { - int *boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { + if (isAnOldModelFile) { + int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { assert(boneRef[j] >= 0 && boneRef[j] < 72); - if (boneRef[j] >= 0 && boneRef[j] < 72) - { - boneRef[j]=OldToNewRemapTable[boneRef[j]]; - } - else - { - boneRef[j]=0; + if (boneRef[j] >= 0 && boneRef[j] < 72) { + boneRef[j] = OldToNewRemapTable[boneRef[j]]; + } else { + boneRef[j] = 0; } } } // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; } @@ -3526,52 +3088,24 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean #ifdef CREATE_LIMB_HIERARCHY -#define NUM_ROOTPARENTS 4 -#define NUM_OTHERPARENTS 12 -#define NUM_BOTTOMBONES 4 +#define NUM_ROOTPARENTS 4 +#define NUM_OTHERPARENTS 12 +#define NUM_BOTTOMBONES 4 -#define CHILD_PADDING 4 //I don't know, I guess this can be changed. +#define CHILD_PADDING 4 // I don't know, I guess this can be changed. -static const char *rootParents[NUM_ROOTPARENTS] = -{ - "rfemurYZ", - "rhumerus", - "lfemurYZ", - "lhumerus" -}; +static const char *rootParents[NUM_ROOTPARENTS] = {"rfemurYZ", "rhumerus", "lfemurYZ", "lhumerus"}; -static const char *otherParents[NUM_OTHERPARENTS] = -{ - "rhumerusX", - "rradius", - "rradiusX", - "lhumerusX", - "lradius", - "lradiusX", - "rfemurX", - "rtibia", - "rtalus", - "lfemurX", - "ltibia", - "ltalus" -}; +static const char *otherParents[NUM_OTHERPARENTS] = {"rhumerusX", "rradius", "rradiusX", "lhumerusX", "lradius", "lradiusX", + "rfemurX", "rtibia", "rtalus", "lfemurX", "ltibia", "ltalus"}; -static const char *bottomBones[NUM_BOTTOMBONES] = -{ - "rtarsal", - "rhand", - "ltarsal", - "lhand" -}; +static const char *bottomBones[NUM_BOTTOMBONES] = {"rtarsal", "rhand", "ltarsal", "lhand"}; -qboolean BoneIsRootParent(char *name) -{ +qboolean BoneIsRootParent(char *name) { int i = 0; - while (i < NUM_ROOTPARENTS) - { - if (!Q_stricmp(name, rootParents[i])) - { + while (i < NUM_ROOTPARENTS) { + if (!Q_stricmp(name, rootParents[i])) { return qtrue; } @@ -3581,14 +3115,11 @@ qboolean BoneIsRootParent(char *name) return qfalse; } -qboolean BoneIsOtherParent(char *name) -{ +qboolean BoneIsOtherParent(char *name) { int i = 0; - while (i < NUM_OTHERPARENTS) - { - if (!Q_stricmp(name, otherParents[i])) - { + while (i < NUM_OTHERPARENTS) { + if (!Q_stricmp(name, otherParents[i])) { return qtrue; } @@ -3598,14 +3129,11 @@ qboolean BoneIsOtherParent(char *name) return qfalse; } -qboolean BoneIsBottom(char *name) -{ +qboolean BoneIsBottom(char *name) { int i = 0; - while (i < NUM_BOTTOMBONES) - { - if (!Q_stricmp(name, bottomBones[i])) - { + while (i < NUM_BOTTOMBONES) { + if (!Q_stricmp(name, bottomBones[i])) { return qtrue; } @@ -3615,24 +3143,22 @@ qboolean BoneIsBottom(char *name) return qfalse; } -void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) -{ +void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) { int i = 0; - //where the next bone starts - byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex+1]); + // where the next bone starts + byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex + 1]); int size = (*endMarker - nextBone); - memmove((nextBone+CHILD_PADDING), nextBone, size); + memmove((nextBone + CHILD_PADDING), nextBone, size); memset(nextBone, 0, CHILD_PADDING); *endMarker += CHILD_PADDING; - //Move the whole thing down CHILD_PADDING amount in memory, clear the new preceding space, and increment the end pointer. + // Move the whole thing down CHILD_PADDING amount in memory, clear the new preceding space, and increment the end pointer. - i = boneIndex+1; + i = boneIndex + 1; - //Now add CHILD_PADDING amount to every offset beginning at the offset of the bone that was moved. - while (i < mdxa->numBones) - { + // Now add CHILD_PADDING amount to every offset beginning at the offset of the bone that was moved. + while (i < mdxa->numBones) { offsets->offsets[i] += CHILD_PADDING; i++; } @@ -3640,77 +3166,49 @@ void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneInd mdxa->ofsFrames += CHILD_PADDING; mdxa->ofsCompBonePool += CHILD_PADDING; mdxa->ofsEnd += CHILD_PADDING; - //ofsSkel does not need to be updated because we are only moving memory after that point. + // ofsSkel does not need to be updated because we are only moving memory after that point. } -//Proper/desired hierarchy list -static const char *BoneHierarchyList[] = -{ - "lfemurYZ", - "lfemurX", - "ltibia", - "ltalus", - "ltarsal", - - "rfemurYZ", - "rfemurX", - "rtibia", - "rtalus", - "rtarsal", - - "lhumerus", - "lhumerusX", - "lradius", - "lradiusX", - "lhand", - - "rhumerus", - "rhumerusX", - "rradius", - "rradiusX", - "rhand", - - 0 -}; +// Proper/desired hierarchy list +static const char *BoneHierarchyList[] = {"lfemurYZ", "lfemurX", "ltibia", "ltalus", "ltarsal", -//Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. -int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSkel_t *boneInfo, qboolean child) -{ + "rfemurYZ", "rfemurX", "rtibia", "rtalus", "rtarsal", + + "lhumerus", "lhumerusX", "lradius", "lradiusX", "lhand", + + "rhumerus", "rhumerusX", "rradius", "rradiusX", "rhand", + + 0}; + +// Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. +int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSkel_t *boneInfo, qboolean child) { int i = 0; int matchindex = -1; mdxaSkel_t *bone; const char *match = NULL; - while (BoneHierarchyList[i]) - { - if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) - { //we have a match, the slot above this will be our desired parent. (or below for child) - if (child) - { - match = BoneHierarchyList[i+1]; - } - else - { - match = BoneHierarchyList[i-1]; + while (BoneHierarchyList[i]) { + if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) { // we have a match, the slot above this will be our desired parent. (or below for child) + if (child) { + match = BoneHierarchyList[i + 1]; + } else { + match = BoneHierarchyList[i - 1]; } break; } i++; } - if (!match) - { //no good + if (!match) { // no good return -1; } i = 0; - while (i < mdxa->numBones) - { + while (i < mdxa->numBones) { bone = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (bone && !Q_stricmp(bone->name, match)) - { //this is the one + if (bone && !Q_stricmp(bone->name, match)) { // this is the one matchindex = i; break; } @@ -3720,21 +3218,21 @@ int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSke return matchindex; } -#endif //CREATE_LIMB_HIERARCHY +#endif // CREATE_LIMB_HIERARCHY /* ================= R_LoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; #ifdef CREATE_LIMB_HIERARCHY - int oSize = 0; - byte *sizeMarker; + int oSize = 0; + byte *sizeMarker; #endif #if 0 //#ifndef _M_IX86 @@ -3744,27 +3242,25 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean mdxaSkel_t *boneInfo; #endif - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXA_VERSION) { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXA_VERSION); + Com_Printf(S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", mod_name, version, MDXA_VERSION); return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; @@ -3772,24 +3268,23 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean oSize = size; int childNumber = (NUM_ROOTPARENTS + NUM_OTHERPARENTS); - size += (childNumber*(CHILD_PADDING*8)); //Allocate us some extra space so we can shift memory down. -#endif //CREATE_LIMB_HIERARCHY + size += (childNumber * (CHILD_PADDING * 8)); // Allocate us some extra space so we can shift memory down. +#endif // CREATE_LIMB_HIERARCHY - mdxa = mod->mdxa = (mdxaHeader_t*) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, - #ifdef CREATE_LIMB_HIERARCHY - NULL, // I think this'll work, can't really test on PC - #else - buffer, - #endif - mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = mod->mdxa = (mdxaHeader_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, +#ifdef CREATE_LIMB_HIERARCHY + NULL, // I think this'll work, can't really test on PC +#else + buffer, +#endif + mod_name, &bAlreadyFound, TAG_MODEL_GLA); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { #ifdef CREATE_LIMB_HIERARCHY - memcpy( mdxa, buffer, oSize ); + memcpy(mdxa, buffer, oSize); #else // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since @@ -3798,7 +3293,7 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); + assert(mdxa == buffer); // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing #endif LL(mdxa->ident); @@ -3810,9 +3305,8 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean } #ifdef CREATE_LIMB_HIERARCHY - if (!bAlreadyFound) - { - mdxaSkel_t *boneParent; + if (!bAlreadyFound) { + mdxaSkel_t *boneParent; #if 0 //#ifdef _M_IX86 mdxaSkel_t *boneInfo; int i, k; @@ -3820,84 +3314,65 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean sizeMarker = (byte *)mdxa + mdxa->ofsEnd; - //rww - This is probably temporary until we put actual hierarchy in for the models. - //It is necessary for the correct operation of ragdoll. - mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + // rww - This is probably temporary until we put actual hierarchy in for the models. + // It is necessary for the correct operation of ragdoll. + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for ( i = 0 ; i < mdxa->numBones ; i++) - { + for (i = 0; i < mdxa->numBones; i++) { boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (boneInfo) - { + if (boneInfo) { char *bname = boneInfo->name; - if (BoneIsRootParent(bname)) - { //These are the main parent bones. We don't want to change their parents, but we want to give them children. + if (BoneIsRootParent(bname)) { // These are the main parent bones. We don't want to change their parents, but we want to give them children. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; - boneInfo->children[boneInfo->numChildren-1] = newChild; - } - else - { + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } - } - else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) - { - if (!BoneIsBottom(bname)) - { //unless it's last in the chain it has the next bone as a child. + } else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) { + if (!BoneIsBottom(bname)) { // unless it's last in the chain it has the next bone as a child. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; - boneInfo->children[boneInfo->numChildren-1] = newChild; - } - else - { + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } } - //Before we set the parent we want to remove this as a child for whoever was parenting it. + // Before we set the parent we want to remove this as a child for whoever was parenting it. int oldParent = boneInfo->parent; - if (oldParent > -1) - { + if (oldParent > -1) { boneParent = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[oldParent]); - } - else - { + } else { boneParent = NULL; } - if (boneParent) - { + if (boneParent) { k = 0; - while (k < boneParent->numChildren) - { - if (boneParent->children[k] == i) - { //this bone is the child + while (k < boneParent->numChildren) { + if (boneParent->children[k] == i) { // this bone is the child k++; - while (k < boneParent->numChildren) - { - boneParent->children[k-1] = boneParent->children[k]; + while (k < boneParent->numChildren) { + boneParent->children[k - 1] = boneParent->children[k]; k++; } - boneParent->children[k-1] = 0; + boneParent->children[k - 1] = 0; boneParent->numChildren--; break; } @@ -3905,31 +3380,27 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean } } - //Now that we have cleared the original parent of ownership, mark the bone's new parent. + // Now that we have cleared the original parent of ownership, mark the bone's new parent. int newParent = BoneParentChildIndex(mdxa, offsets, boneInfo, qfalse); - if (newParent != -1) - { + if (newParent != -1) { boneInfo->parent = newParent; - } - else - { + } else { assert(!"Failed to find matching parent for bone in hierarchy creation"); } } } } } -#endif //CREATE_LIMB_HIERARCHY +#endif // CREATE_LIMB_HIERARCHY - if ( mdxa->numFrames < 1 ) { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name ); + if (mdxa->numFrames < 1) { + Com_Printf(S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } #if 0 //#ifndef _M_IX86 @@ -3974,10 +3445,3 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean #endif return qtrue; } - - - - - - - diff --git a/codemp/rd-dedicated/tr_init.cpp b/codemp/rd-dedicated/tr_init.cpp index 794c307989..971d00dcec 100644 --- a/codemp/rd-dedicated/tr_init.cpp +++ b/codemp/rd-dedicated/tr_init.cpp @@ -29,181 +29,180 @@ along with this program; if not, see . #include "ghoul2/g2_local.h" #include +cvar_t *r_verbose; +cvar_t *r_ignore; -cvar_t *r_verbose; -cvar_t *r_ignore; +cvar_t *r_displayRefresh; -cvar_t *r_displayRefresh; +cvar_t *r_detailTextures; -cvar_t *r_detailTextures; +cvar_t *r_znear; -cvar_t *r_znear; +cvar_t *r_skipBackEnd; -cvar_t *r_skipBackEnd; +cvar_t *r_ignorehwgamma; +cvar_t *r_measureOverdraw; -cvar_t *r_ignorehwgamma; -cvar_t *r_measureOverdraw; - -cvar_t *r_inGameVideo; -cvar_t *r_fastsky; -cvar_t *r_drawSun; -cvar_t *r_dynamiclight; +cvar_t *r_inGameVideo; +cvar_t *r_fastsky; +cvar_t *r_drawSun; +cvar_t *r_dynamiclight; // rjr - removed for hacking cvar_t *r_dlightBacks; -cvar_t *r_lodbias; -cvar_t *r_lodscale; -cvar_t *r_autolodscalevalue; - -cvar_t *r_norefresh; -cvar_t *r_drawentities; -cvar_t *r_drawworld; -cvar_t *r_drawfog; -cvar_t *r_speeds; -cvar_t *r_fullbright; -cvar_t *r_novis; -cvar_t *r_nocull; -cvar_t *r_facePlaneCull; -cvar_t *r_cullRoofFaces; //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww -cvar_t *r_roofCullCeilDist; //ceiling distance cull tolerance -rww -cvar_t *r_roofCullFloorDist; //floor distance cull tolerance -rww -cvar_t *r_showcluster; -cvar_t *r_nocurves; - -cvar_t *r_autoMap; //automap renderside toggle for debugging -rww -cvar_t *r_autoMapBackAlpha; //alpha of automap bg -rww -cvar_t *r_autoMapDisable; //don't calc it (since it's slow in debug) -rww - -cvar_t *r_dlightStyle; -cvar_t *r_surfaceSprites; -cvar_t *r_surfaceWeather; - -cvar_t *r_windSpeed; -cvar_t *r_windAngle; -cvar_t *r_windGust; -cvar_t *r_windDampFactor; -cvar_t *r_windPointForce; -cvar_t *r_windPointX; -cvar_t *r_windPointY; - -cvar_t *r_allowExtensions; - -cvar_t *r_ext_compressed_textures; -cvar_t *r_ext_compressed_lightmaps; -cvar_t *r_ext_preferred_tc_method; -cvar_t *r_ext_gamma_control; -cvar_t *r_ext_multitexture; -cvar_t *r_ext_compiled_vertex_array; -cvar_t *r_ext_texture_env_add; -cvar_t *r_ext_texture_filter_anisotropic; - -cvar_t *r_DynamicGlow; -cvar_t *r_DynamicGlowPasses; -cvar_t *r_DynamicGlowDelta; -cvar_t *r_DynamicGlowIntensity; -cvar_t *r_DynamicGlowSoft; -cvar_t *r_DynamicGlowWidth; -cvar_t *r_DynamicGlowHeight; - -cvar_t *r_ignoreGLErrors; -cvar_t *r_logFile; - -cvar_t *r_stencilbits; -cvar_t *r_depthbits; -cvar_t *r_colorbits; -cvar_t *r_stereo; -cvar_t *r_primitives; -cvar_t *r_texturebits; -cvar_t *r_texturebitslm; - -cvar_t *r_lightmap; -cvar_t *r_vertexLight; -cvar_t *r_uiFullScreen; -cvar_t *r_shadows; -cvar_t *r_shadowRange; -cvar_t *r_flares; -cvar_t *r_mode; -cvar_t *r_nobind; -cvar_t *r_singleShader; -cvar_t *r_colorMipLevels; -cvar_t *r_picmip; -cvar_t *r_showtris; -cvar_t *r_showsky; -cvar_t *r_shownormals; -cvar_t *r_finish; -cvar_t *r_clear; -cvar_t *r_swapInterval; -cvar_t *r_markcount; -cvar_t *r_textureMode; -cvar_t *r_offsetFactor; -cvar_t *r_offsetUnits; -cvar_t *r_gamma; -cvar_t *r_intensity; -cvar_t *r_lockpvs; -cvar_t *r_noportals; -cvar_t *r_portalOnly; - -cvar_t *r_subdivisions; -cvar_t *r_lodCurveError; - -cvar_t *r_fullscreen = 0; -cvar_t *r_noborder; -cvar_t *r_centerWindow; - -cvar_t *r_customwidth; -cvar_t *r_customheight; - -cvar_t *r_overBrightBits; - -cvar_t *r_debugSurface; -cvar_t *r_simpleMipMaps; - -cvar_t *r_showImages; - -cvar_t *r_ambientScale; -cvar_t *r_directedScale; -cvar_t *r_debugLight; -cvar_t *r_debugSort; +cvar_t *r_lodbias; +cvar_t *r_lodscale; +cvar_t *r_autolodscalevalue; + +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawworld; +cvar_t *r_drawfog; +cvar_t *r_speeds; +cvar_t *r_fullbright; +cvar_t *r_novis; +cvar_t *r_nocull; +cvar_t *r_facePlaneCull; +cvar_t *r_cullRoofFaces; // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww +cvar_t *r_roofCullCeilDist; // ceiling distance cull tolerance -rww +cvar_t *r_roofCullFloorDist; // floor distance cull tolerance -rww +cvar_t *r_showcluster; +cvar_t *r_nocurves; + +cvar_t *r_autoMap; // automap renderside toggle for debugging -rww +cvar_t *r_autoMapBackAlpha; // alpha of automap bg -rww +cvar_t *r_autoMapDisable; // don't calc it (since it's slow in debug) -rww + +cvar_t *r_dlightStyle; +cvar_t *r_surfaceSprites; +cvar_t *r_surfaceWeather; + +cvar_t *r_windSpeed; +cvar_t *r_windAngle; +cvar_t *r_windGust; +cvar_t *r_windDampFactor; +cvar_t *r_windPointForce; +cvar_t *r_windPointX; +cvar_t *r_windPointY; + +cvar_t *r_allowExtensions; + +cvar_t *r_ext_compressed_textures; +cvar_t *r_ext_compressed_lightmaps; +cvar_t *r_ext_preferred_tc_method; +cvar_t *r_ext_gamma_control; +cvar_t *r_ext_multitexture; +cvar_t *r_ext_compiled_vertex_array; +cvar_t *r_ext_texture_env_add; +cvar_t *r_ext_texture_filter_anisotropic; + +cvar_t *r_DynamicGlow; +cvar_t *r_DynamicGlowPasses; +cvar_t *r_DynamicGlowDelta; +cvar_t *r_DynamicGlowIntensity; +cvar_t *r_DynamicGlowSoft; +cvar_t *r_DynamicGlowWidth; +cvar_t *r_DynamicGlowHeight; + +cvar_t *r_ignoreGLErrors; +cvar_t *r_logFile; + +cvar_t *r_stencilbits; +cvar_t *r_depthbits; +cvar_t *r_colorbits; +cvar_t *r_stereo; +cvar_t *r_primitives; +cvar_t *r_texturebits; +cvar_t *r_texturebitslm; + +cvar_t *r_lightmap; +cvar_t *r_vertexLight; +cvar_t *r_uiFullScreen; +cvar_t *r_shadows; +cvar_t *r_shadowRange; +cvar_t *r_flares; +cvar_t *r_mode; +cvar_t *r_nobind; +cvar_t *r_singleShader; +cvar_t *r_colorMipLevels; +cvar_t *r_picmip; +cvar_t *r_showtris; +cvar_t *r_showsky; +cvar_t *r_shownormals; +cvar_t *r_finish; +cvar_t *r_clear; +cvar_t *r_swapInterval; +cvar_t *r_markcount; +cvar_t *r_textureMode; +cvar_t *r_offsetFactor; +cvar_t *r_offsetUnits; +cvar_t *r_gamma; +cvar_t *r_intensity; +cvar_t *r_lockpvs; +cvar_t *r_noportals; +cvar_t *r_portalOnly; + +cvar_t *r_subdivisions; +cvar_t *r_lodCurveError; + +cvar_t *r_fullscreen = 0; +cvar_t *r_noborder; +cvar_t *r_centerWindow; + +cvar_t *r_customwidth; +cvar_t *r_customheight; + +cvar_t *r_overBrightBits; + +cvar_t *r_debugSurface; +cvar_t *r_simpleMipMaps; + +cvar_t *r_showImages; + +cvar_t *r_ambientScale; +cvar_t *r_directedScale; +cvar_t *r_debugLight; +cvar_t *r_debugSort; // the limits apply to the sum of all scenes in a frame -- // the main view, all the 3D icons, etc -#define DEFAULT_MAX_POLYS 600 -#define DEFAULT_MAX_POLYVERTS 3000 -cvar_t *r_maxpolys; -cvar_t *r_maxpolyverts; -int max_polys; -int max_polyverts; +#define DEFAULT_MAX_POLYS 600 +#define DEFAULT_MAX_POLYVERTS 3000 +cvar_t *r_maxpolys; +cvar_t *r_maxpolyverts; +int max_polys; +int max_polyverts; -cvar_t *r_modelpoolmegs; +cvar_t *r_modelpoolmegs; /* Ghoul2 Insert Start */ #ifdef _DEBUG -cvar_t *r_noPrecacheGLA; +cvar_t *r_noPrecacheGLA; #endif -cvar_t *r_noServerGhoul2; -cvar_t *r_Ghoul2AnimSmooth=0; -cvar_t *r_Ghoul2UnSqashAfterSmooth=0; -//cvar_t *r_Ghoul2UnSqash; -//cvar_t *r_Ghoul2TimeBase=0; from single player -//cvar_t *r_Ghoul2NoLerp; -//cvar_t *r_Ghoul2NoBlend; -//cvar_t *r_Ghoul2BlendMultiplier=0; - -cvar_t *broadsword=0; -cvar_t *broadsword_kickbones=0; -cvar_t *broadsword_kickorigin=0; -cvar_t *broadsword_playflop=0; -cvar_t *broadsword_dontstopanim=0; -cvar_t *broadsword_waitforshot=0; -cvar_t *broadsword_smallbbox=0; -cvar_t *broadsword_extra1=0; -cvar_t *broadsword_extra2=0; - -cvar_t *broadsword_effcorr=0; -cvar_t *broadsword_ragtobase=0; -cvar_t *broadsword_dircap=0; +cvar_t *r_noServerGhoul2; +cvar_t *r_Ghoul2AnimSmooth = 0; +cvar_t *r_Ghoul2UnSqashAfterSmooth = 0; +// cvar_t *r_Ghoul2UnSqash; +// cvar_t *r_Ghoul2TimeBase=0; from single player +// cvar_t *r_Ghoul2NoLerp; +// cvar_t *r_Ghoul2NoBlend; +// cvar_t *r_Ghoul2BlendMultiplier=0; + +cvar_t *broadsword = 0; +cvar_t *broadsword_kickbones = 0; +cvar_t *broadsword_kickorigin = 0; +cvar_t *broadsword_playflop = 0; +cvar_t *broadsword_dontstopanim = 0; +cvar_t *broadsword_waitforshot = 0; +cvar_t *broadsword_smallbbox = 0; +cvar_t *broadsword_extra1 = 0; +cvar_t *broadsword_extra2 = 0; + +cvar_t *broadsword_effcorr = 0; +cvar_t *broadsword_ragtobase = 0; +cvar_t *broadsword_dircap = 0; /* Ghoul2 Insert End @@ -212,45 +211,42 @@ Ghoul2 Insert End cvar_t *r_aviMotionJpegQuality; cvar_t *r_screenshotJpegQuality; -cvar_t *r_patchStitching; +cvar_t *r_patchStitching; /* ** R_GetModeInfo */ -typedef struct vidmode_s -{ - const char *description; - int width, height; +typedef struct vidmode_s { + const char *description; + int width, height; } vidmode_t; -const vidmode_t r_vidModes[] = { - { "Mode 0: 320x240", 320, 240 }, - { "Mode 1: 400x300", 400, 300 }, - { "Mode 2: 512x384", 512, 384 }, - { "Mode 3: 640x480", 640, 480 }, - { "Mode 4: 800x600", 800, 600 }, - { "Mode 5: 960x720", 960, 720 }, - { "Mode 6: 1024x768", 1024, 768 }, - { "Mode 7: 1152x864", 1152, 864 }, - { "Mode 8: 1280x1024", 1280, 1024 }, - { "Mode 9: 1600x1200", 1600, 1200 }, - { "Mode 10: 2048x1536", 2048, 1536 }, - { "Mode 11: 856x480 (wide)", 856, 480 }, - { "Mode 12: 2400x600(surround)",2400,600 } -}; -static const int s_numVidModes = ( sizeof( r_vidModes ) / sizeof( r_vidModes[0] ) ); - -qboolean R_GetModeInfo( int *width, int *height, int mode ) { - const vidmode_t *vm; - - if ( mode < -1 ) { - return qfalse; +const vidmode_t r_vidModes[] = {{"Mode 0: 320x240", 320, 240}, + {"Mode 1: 400x300", 400, 300}, + {"Mode 2: 512x384", 512, 384}, + {"Mode 3: 640x480", 640, 480}, + {"Mode 4: 800x600", 800, 600}, + {"Mode 5: 960x720", 960, 720}, + {"Mode 6: 1024x768", 1024, 768}, + {"Mode 7: 1152x864", 1152, 864}, + {"Mode 8: 1280x1024", 1280, 1024}, + {"Mode 9: 1600x1200", 1600, 1200}, + {"Mode 10: 2048x1536", 2048, 1536}, + {"Mode 11: 856x480 (wide)", 856, 480}, + {"Mode 12: 2400x600(surround)", 2400, 600}}; +static const int s_numVidModes = (sizeof(r_vidModes) / sizeof(r_vidModes[0])); + +qboolean R_GetModeInfo(int *width, int *height, int mode) { + const vidmode_t *vm; + + if (mode < -1) { + return qfalse; } - if ( mode >= s_numVidModes ) { + if (mode >= s_numVidModes) { return qfalse; } - if ( mode == -1 ) { + if (mode == -1) { *width = r_customwidth->integer; *height = r_customheight->integer; return qtrue; @@ -258,39 +254,37 @@ qboolean R_GetModeInfo( int *width, int *height, int mode ) { vm = &r_vidModes[mode]; - *width = vm->width; - *height = vm->height; + *width = vm->width; + *height = vm->height; - return qtrue; + return qtrue; } /* ** R_ModeList_f */ -static void R_ModeList_f( void ) -{ +static void R_ModeList_f(void) { int i; - Com_Printf ("\n" ); - for ( i = 0; i < s_numVidModes; i++ ) - { - Com_Printf ("%s\n", r_vidModes[i].description ); + Com_Printf("\n"); + for (i = 0; i < s_numVidModes; i++) { + Com_Printf("%s\n", r_vidModes[i].description); } - Com_Printf ("\n" ); + Com_Printf("\n"); } typedef struct consoleCommand_s { - const char *cmd; - xcommand_t func; + const char *cmd; + xcommand_t func; } consoleCommand_t; -static consoleCommand_t commands[] = { - { "modellist", R_Modellist_f }, - { "modelist", R_ModeList_f }, - { "modelcacheinfo", RE_RegisterModels_Info_f }, +static consoleCommand_t commands[] = { + {"modellist", R_Modellist_f}, + {"modelist", R_ModeList_f}, + {"modelcacheinfo", RE_RegisterModels_Info_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); #ifdef _DEBUG #define MIN_PRIMITIVES -1 @@ -310,219 +304,213 @@ static const size_t numCommands = ARRAY_LEN( commands ); R_Register =============== */ -void R_Register( void ) -{ +void R_Register(void) { // // latched and archived variables // - r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compress_textures", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compressed_lightmaps = ri.Cvar_Get( "r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_preferred_tc_method = ri.Cvar_Get( "r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_gamma_control = ri.Cvar_Get( "r_ext_gamma_control", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_texture_filter_anisotropic = ri.Cvar_Get( "r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlow = ri.Cvar_Get( "r_DynamicGlow", "0", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowPasses = ri.Cvar_Get( "r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowDelta = ri.Cvar_Get( "r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowIntensity = ri.Cvar_Get( "r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowSoft = ri.Cvar_Get( "r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowWidth = ri.Cvar_Get( "r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_DynamicGlowHeight = ri.Cvar_Get( "r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_picmip = ri.Cvar_Get( "r_picmip", "1", CVAR_ARCHIVE|CVAR_LATCH, "" ); - ri.Cvar_CheckRange( r_picmip, 0, 16, qtrue ); - r_colorMipLevels = ri.Cvar_Get( "r_colorMipLevels", "0", CVAR_LATCH, "" ); - r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_texturebitslm = ri.Cvar_Get( "r_texturebitslm", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_colorbits = ri.Cvar_Get( "r_colorbits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_stereo = ri.Cvar_Get( "r_stereo", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_stencilbits = ri.Cvar_Get( "r_stencilbits", "8", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_depthbits = ri.Cvar_Get( "r_depthbits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_overBrightBits = ri.Cvar_Get( "r_overBrightBits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ignorehwgamma = ri.Cvar_Get( "r_ignorehwgamma", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_mode = ri.Cvar_Get( "r_mode", "4", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_fullscreen = ri.Cvar_Get( "r_fullscreen", "0", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_noborder = ri.Cvar_Get( "r_noborder", "0", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_centerWindow = ri.Cvar_Get( "r_centerWindow", "0", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_customwidth = ri.Cvar_Get( "r_customwidth", "1600", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_customheight = ri.Cvar_Get( "r_customheight", "1024", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_uiFullScreen = ri.Cvar_Get( "r_uifullscreen", "0", CVAR_NONE, "" ); - r_subdivisions = ri.Cvar_Get( "r_subdivisions", "4", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_displayRefresh = ri.Cvar_Get( "r_displayRefresh", "0", CVAR_LATCH, "" ); - ri.Cvar_CheckRange( r_displayRefresh, 0, 200, qtrue ); - r_fullbright = ri.Cvar_Get( "r_fullbright", "0", CVAR_CHEAT, "" ); - r_intensity = ri.Cvar_Get( "r_intensity", "1", CVAR_LATCH, "" ); - r_singleShader = ri.Cvar_Get( "r_singleShader", "0", CVAR_CHEAT|CVAR_LATCH, "" ); - r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE_ND, "" ); - r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE_ND, "" ); - r_autolodscalevalue = ri.Cvar_Get( "r_autolodscalevalue", "0", CVAR_ROM, "" ); - r_flares = ri.Cvar_Get( "r_flares", "1", CVAR_ARCHIVE_ND, "" ); - r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_ARCHIVE_ND, "" ); - ri.Cvar_CheckRange( r_znear, 0.001f, 10, qfalse ); - r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND, "" ); - r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE_ND, "" ); - r_inGameVideo = ri.Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE_ND, "" ); - r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE_ND, "" ); - r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE, "" ); + r_allowExtensions = ri.Cvar_Get("r_allowExtensions", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compressed_textures = ri.Cvar_Get("r_ext_compress_textures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compressed_lightmaps = ri.Cvar_Get("r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_preferred_tc_method = ri.Cvar_Get("r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_gamma_control = ri.Cvar_Get("r_ext_gamma_control", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_multitexture = ri.Cvar_Get("r_ext_multitexture", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compiled_vertex_array = ri.Cvar_Get("r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_texture_env_add = ri.Cvar_Get("r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_texture_filter_anisotropic = ri.Cvar_Get("r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND, ""); + r_DynamicGlow = ri.Cvar_Get("r_DynamicGlow", "0", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowPasses = ri.Cvar_Get("r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowDelta = ri.Cvar_Get("r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowIntensity = ri.Cvar_Get("r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowSoft = ri.Cvar_Get("r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowWidth = ri.Cvar_Get("r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_DynamicGlowHeight = ri.Cvar_Get("r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_picmip = ri.Cvar_Get("r_picmip", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_picmip, 0, 16, qtrue); + r_colorMipLevels = ri.Cvar_Get("r_colorMipLevels", "0", CVAR_LATCH, ""); + r_detailTextures = ri.Cvar_Get("r_detailtextures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_texturebits = ri.Cvar_Get("r_texturebits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_texturebitslm = ri.Cvar_Get("r_texturebitslm", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_colorbits = ri.Cvar_Get("r_colorbits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_stereo = ri.Cvar_Get("r_stereo", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_stencilbits = ri.Cvar_Get("r_stencilbits", "8", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_depthbits = ri.Cvar_Get("r_depthbits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_overBrightBits = ri.Cvar_Get("r_overBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ignorehwgamma = ri.Cvar_Get("r_ignorehwgamma", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_mode = ri.Cvar_Get("r_mode", "4", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_fullscreen = ri.Cvar_Get("r_fullscreen", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_noborder = ri.Cvar_Get("r_noborder", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_centerWindow = ri.Cvar_Get("r_centerWindow", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_customwidth = ri.Cvar_Get("r_customwidth", "1600", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_customheight = ri.Cvar_Get("r_customheight", "1024", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_simpleMipMaps = ri.Cvar_Get("r_simpleMipMaps", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_vertexLight = ri.Cvar_Get("r_vertexLight", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_uiFullScreen = ri.Cvar_Get("r_uifullscreen", "0", CVAR_NONE, ""); + r_subdivisions = ri.Cvar_Get("r_subdivisions", "4", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_displayRefresh = ri.Cvar_Get("r_displayRefresh", "0", CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_displayRefresh, 0, 200, qtrue); + r_fullbright = ri.Cvar_Get("r_fullbright", "0", CVAR_CHEAT, ""); + r_intensity = ri.Cvar_Get("r_intensity", "1", CVAR_LATCH, ""); + r_singleShader = ri.Cvar_Get("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH, ""); + r_lodCurveError = ri.Cvar_Get("r_lodCurveError", "250", CVAR_ARCHIVE_ND, ""); + r_lodbias = ri.Cvar_Get("r_lodbias", "0", CVAR_ARCHIVE_ND, ""); + r_autolodscalevalue = ri.Cvar_Get("r_autolodscalevalue", "0", CVAR_ROM, ""); + r_flares = ri.Cvar_Get("r_flares", "1", CVAR_ARCHIVE_ND, ""); + r_znear = ri.Cvar_Get("r_znear", "4", CVAR_ARCHIVE_ND, ""); + ri.Cvar_CheckRange(r_znear, 0.001f, 10, qfalse); + r_ignoreGLErrors = ri.Cvar_Get("r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND, ""); + r_fastsky = ri.Cvar_Get("r_fastsky", "0", CVAR_ARCHIVE_ND, ""); + r_inGameVideo = ri.Cvar_Get("r_inGameVideo", "1", CVAR_ARCHIVE_ND, ""); + r_drawSun = ri.Cvar_Get("r_drawSun", "0", CVAR_ARCHIVE_ND, ""); + r_dynamiclight = ri.Cvar_Get("r_dynamiclight", "1", CVAR_ARCHIVE, ""); // rjr - removed for hacking -// r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "1", CVAR_CHEAT, "" ); - r_finish = ri.Cvar_Get( "r_finish", "0", CVAR_ARCHIVE_ND, "" ); - r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, "" ); - r_swapInterval = ri.Cvar_Get( "r_swapInterval", "0", SWAPINTERVAL_FLAGS, "" ); - r_markcount = ri.Cvar_Get( "r_markcount", "100", CVAR_ARCHIVE_ND, "" ); - r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE_ND, "" ); - r_facePlaneCull = ri.Cvar_Get( "r_facePlaneCull", "1", CVAR_ARCHIVE_ND, "" ); - r_cullRoofFaces = ri.Cvar_Get( "r_cullRoofFaces", "0", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_roofCullCeilDist = ri.Cvar_Get( "r_roofCullCeilDist", "256", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_roofCullFloorDist = ri.Cvar_Get( "r_roofCeilFloorDist", "128", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_primitives = ri.Cvar_Get( "r_primitives", "0", CVAR_ARCHIVE_ND, "" ); - ri.Cvar_CheckRange( r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue ); - r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.6", CVAR_CHEAT, "" ); - r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT, "" ); - r_autoMap = ri.Cvar_Get( "r_autoMap", "0", CVAR_ARCHIVE_ND, "" ); //automap renderside toggle for debugging -rww - r_autoMapBackAlpha = ri.Cvar_Get( "r_autoMapBackAlpha", "0", CVAR_NONE, "" ); //alpha of automap bg -rww - r_autoMapDisable = ri.Cvar_Get( "r_autoMapDisable", "1", CVAR_NONE, "" ); - r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_CHEAT, "" ); - r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP, "" ); - r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT, "" ); - r_dlightStyle = ri.Cvar_Get( "r_dlightStyle", "1", CVAR_TEMP, "" ); - r_surfaceSprites = ri.Cvar_Get( "r_surfaceSprites", "1", CVAR_TEMP, "" ); - r_surfaceWeather = ri.Cvar_Get( "r_surfaceWeather", "0", CVAR_TEMP, "" ); - r_windSpeed = ri.Cvar_Get( "r_windSpeed", "0", CVAR_NONE, "" ); - r_windAngle = ri.Cvar_Get( "r_windAngle", "0", CVAR_NONE, "" ); - r_windGust = ri.Cvar_Get( "r_windGust", "0", CVAR_NONE, "" ); - r_windDampFactor = ri.Cvar_Get( "r_windDampFactor", "0.1", CVAR_NONE, "" ); - r_windPointForce = ri.Cvar_Get( "r_windPointForce", "0", CVAR_NONE, "" ); - r_windPointX = ri.Cvar_Get( "r_windPointX", "0", CVAR_NONE, "" ); - r_windPointY = ri.Cvar_Get( "r_windPointY", "0", CVAR_NONE, "" ); - r_nocurves = ri.Cvar_Get( "r_nocurves", "0", CVAR_CHEAT, "" ); - r_drawworld = ri.Cvar_Get( "r_drawworld", "1", CVAR_CHEAT, "" ); - r_drawfog = ri.Cvar_Get( "r_drawfog", "2", CVAR_CHEAT, "" ); - r_lightmap = ri.Cvar_Get( "r_lightmap", "0", CVAR_CHEAT, "" ); - r_portalOnly = ri.Cvar_Get( "r_portalOnly", "0", CVAR_CHEAT, "" ); - r_skipBackEnd = ri.Cvar_Get( "r_skipBackEnd", "0", CVAR_CHEAT, "" ); - r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT, "" ); - r_lodscale = ri.Cvar_Get( "r_lodscale", "5", CVAR_NONE, "" ); - r_norefresh = ri.Cvar_Get( "r_norefresh", "0", CVAR_CHEAT, "" ); - r_drawentities = ri.Cvar_Get( "r_drawentities", "1", CVAR_CHEAT, "" ); - r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_CHEAT, "" ); - r_nocull = ri.Cvar_Get( "r_nocull", "0", CVAR_CHEAT, "" ); - r_novis = ri.Cvar_Get( "r_novis", "0", CVAR_CHEAT, "" ); - r_showcluster = ri.Cvar_Get( "r_showcluster", "0", CVAR_CHEAT, "" ); - r_speeds = ri.Cvar_Get( "r_speeds", "0", CVAR_CHEAT, "" ); - r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT, "" ); - r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT, "" ); - r_debugSurface = ri.Cvar_Get( "r_debugSurface", "0", CVAR_CHEAT, "" ); - r_nobind = ri.Cvar_Get( "r_nobind", "0", CVAR_CHEAT, "" ); - r_showtris = ri.Cvar_Get( "r_showtris", "0", CVAR_CHEAT, "" ); - r_showsky = ri.Cvar_Get( "r_showsky", "0", CVAR_CHEAT, "" ); - r_shownormals = ri.Cvar_Get( "r_shownormals", "0", CVAR_CHEAT, "" ); - r_clear = ri.Cvar_Get( "r_clear", "0", CVAR_CHEAT, "" ); - r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT, "" ); - r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT, "" ); - r_lockpvs = ri.Cvar_Get( "r_lockpvs", "0", CVAR_CHEAT, "" ); - r_noportals = ri.Cvar_Get( "r_noportals", "0", CVAR_CHEAT, "" ); - r_shadows = ri.Cvar_Get( "cg_shadows", "1", CVAR_NONE, "" ); - r_shadowRange = ri.Cvar_Get( "r_shadowRange", "1000", CVAR_NONE, "" ); - r_maxpolys = ri.Cvar_Get( "r_maxpolys", XSTRING( DEFAULT_MAX_POLYS ), CVAR_NONE, "" ); - r_maxpolyverts = ri.Cvar_Get( "r_maxpolyverts", XSTRING( DEFAULT_MAX_POLYVERTS ), CVAR_NONE, "" ); + // r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "1", CVAR_CHEAT, "" ); + r_finish = ri.Cvar_Get("r_finish", "0", CVAR_ARCHIVE_ND, ""); + r_textureMode = ri.Cvar_Get("r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, ""); + r_swapInterval = ri.Cvar_Get("r_swapInterval", "0", SWAPINTERVAL_FLAGS, ""); + r_markcount = ri.Cvar_Get("r_markcount", "100", CVAR_ARCHIVE_ND, ""); + r_gamma = ri.Cvar_Get("r_gamma", "1", CVAR_ARCHIVE_ND, ""); + r_facePlaneCull = ri.Cvar_Get("r_facePlaneCull", "1", CVAR_ARCHIVE_ND, ""); + r_cullRoofFaces = + ri.Cvar_Get("r_cullRoofFaces", "0", CVAR_CHEAT, ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_roofCullCeilDist = ri.Cvar_Get("r_roofCullCeilDist", "256", CVAR_CHEAT, + ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_roofCullFloorDist = ri.Cvar_Get("r_roofCeilFloorDist", "128", CVAR_CHEAT, + ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_primitives = ri.Cvar_Get("r_primitives", "0", CVAR_ARCHIVE_ND, ""); + ri.Cvar_CheckRange(r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue); + r_ambientScale = ri.Cvar_Get("r_ambientScale", "0.6", CVAR_CHEAT, ""); + r_directedScale = ri.Cvar_Get("r_directedScale", "1", CVAR_CHEAT, ""); + r_autoMap = ri.Cvar_Get("r_autoMap", "0", CVAR_ARCHIVE_ND, ""); // automap renderside toggle for debugging -rww + r_autoMapBackAlpha = ri.Cvar_Get("r_autoMapBackAlpha", "0", CVAR_NONE, ""); // alpha of automap bg -rww + r_autoMapDisable = ri.Cvar_Get("r_autoMapDisable", "1", CVAR_NONE, ""); + r_showImages = ri.Cvar_Get("r_showImages", "0", CVAR_CHEAT, ""); + r_debugLight = ri.Cvar_Get("r_debuglight", "0", CVAR_TEMP, ""); + r_debugSort = ri.Cvar_Get("r_debugSort", "0", CVAR_CHEAT, ""); + r_dlightStyle = ri.Cvar_Get("r_dlightStyle", "1", CVAR_TEMP, ""); + r_surfaceSprites = ri.Cvar_Get("r_surfaceSprites", "1", CVAR_TEMP, ""); + r_surfaceWeather = ri.Cvar_Get("r_surfaceWeather", "0", CVAR_TEMP, ""); + r_windSpeed = ri.Cvar_Get("r_windSpeed", "0", CVAR_NONE, ""); + r_windAngle = ri.Cvar_Get("r_windAngle", "0", CVAR_NONE, ""); + r_windGust = ri.Cvar_Get("r_windGust", "0", CVAR_NONE, ""); + r_windDampFactor = ri.Cvar_Get("r_windDampFactor", "0.1", CVAR_NONE, ""); + r_windPointForce = ri.Cvar_Get("r_windPointForce", "0", CVAR_NONE, ""); + r_windPointX = ri.Cvar_Get("r_windPointX", "0", CVAR_NONE, ""); + r_windPointY = ri.Cvar_Get("r_windPointY", "0", CVAR_NONE, ""); + r_nocurves = ri.Cvar_Get("r_nocurves", "0", CVAR_CHEAT, ""); + r_drawworld = ri.Cvar_Get("r_drawworld", "1", CVAR_CHEAT, ""); + r_drawfog = ri.Cvar_Get("r_drawfog", "2", CVAR_CHEAT, ""); + r_lightmap = ri.Cvar_Get("r_lightmap", "0", CVAR_CHEAT, ""); + r_portalOnly = ri.Cvar_Get("r_portalOnly", "0", CVAR_CHEAT, ""); + r_skipBackEnd = ri.Cvar_Get("r_skipBackEnd", "0", CVAR_CHEAT, ""); + r_measureOverdraw = ri.Cvar_Get("r_measureOverdraw", "0", CVAR_CHEAT, ""); + r_lodscale = ri.Cvar_Get("r_lodscale", "5", CVAR_NONE, ""); + r_norefresh = ri.Cvar_Get("r_norefresh", "0", CVAR_CHEAT, ""); + r_drawentities = ri.Cvar_Get("r_drawentities", "1", CVAR_CHEAT, ""); + r_ignore = ri.Cvar_Get("r_ignore", "1", CVAR_CHEAT, ""); + r_nocull = ri.Cvar_Get("r_nocull", "0", CVAR_CHEAT, ""); + r_novis = ri.Cvar_Get("r_novis", "0", CVAR_CHEAT, ""); + r_showcluster = ri.Cvar_Get("r_showcluster", "0", CVAR_CHEAT, ""); + r_speeds = ri.Cvar_Get("r_speeds", "0", CVAR_CHEAT, ""); + r_verbose = ri.Cvar_Get("r_verbose", "0", CVAR_CHEAT, ""); + r_logFile = ri.Cvar_Get("r_logFile", "0", CVAR_CHEAT, ""); + r_debugSurface = ri.Cvar_Get("r_debugSurface", "0", CVAR_CHEAT, ""); + r_nobind = ri.Cvar_Get("r_nobind", "0", CVAR_CHEAT, ""); + r_showtris = ri.Cvar_Get("r_showtris", "0", CVAR_CHEAT, ""); + r_showsky = ri.Cvar_Get("r_showsky", "0", CVAR_CHEAT, ""); + r_shownormals = ri.Cvar_Get("r_shownormals", "0", CVAR_CHEAT, ""); + r_clear = ri.Cvar_Get("r_clear", "0", CVAR_CHEAT, ""); + r_offsetFactor = ri.Cvar_Get("r_offsetfactor", "-1", CVAR_CHEAT, ""); + r_offsetUnits = ri.Cvar_Get("r_offsetunits", "-2", CVAR_CHEAT, ""); + r_lockpvs = ri.Cvar_Get("r_lockpvs", "0", CVAR_CHEAT, ""); + r_noportals = ri.Cvar_Get("r_noportals", "0", CVAR_CHEAT, ""); + r_shadows = ri.Cvar_Get("cg_shadows", "1", CVAR_NONE, ""); + r_shadowRange = ri.Cvar_Get("r_shadowRange", "1000", CVAR_NONE, ""); + r_maxpolys = ri.Cvar_Get("r_maxpolys", XSTRING(DEFAULT_MAX_POLYS), CVAR_NONE, ""); + r_maxpolyverts = ri.Cvar_Get("r_maxpolyverts", XSTRING(DEFAULT_MAX_POLYVERTS), CVAR_NONE, ""); /* Ghoul2 Insert Start */ #ifdef _DEBUG - r_noPrecacheGLA = ri.Cvar_Get( "r_noPrecacheGLA", "0", CVAR_CHEAT, "" ); + r_noPrecacheGLA = ri.Cvar_Get("r_noPrecacheGLA", "0", CVAR_CHEAT, ""); #endif - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", CVAR_CHEAT, "" ); - r_Ghoul2AnimSmooth = ri.Cvar_Get( "r_ghoul2animsmooth", "0.3", CVAR_NONE, "" ); - r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get( "r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, "" ); - broadsword = ri.Cvar_Get( "broadsword", "0", CVAR_NONE, "" ); - broadsword_kickbones = ri.Cvar_Get( "broadsword_kickbones", "1", CVAR_NONE, "" ); - broadsword_kickorigin = ri.Cvar_Get( "broadsword_kickorigin", "1", CVAR_NONE, "" ); - broadsword_dontstopanim = ri.Cvar_Get( "broadsword_dontstopanim", "0", CVAR_NONE, "" ); - broadsword_waitforshot = ri.Cvar_Get( "broadsword_waitforshot", "0", CVAR_NONE, "" ); - broadsword_playflop = ri.Cvar_Get( "broadsword_playflop", "1", CVAR_NONE, "" ); - broadsword_smallbbox = ri.Cvar_Get( "broadsword_smallbbox", "0", CVAR_NONE, "" ); - broadsword_extra1 = ri.Cvar_Get( "broadsword_extra1", "0", CVAR_NONE, "" ); - broadsword_extra2 = ri.Cvar_Get( "broadsword_extra2", "0", CVAR_NONE, "" ); - broadsword_effcorr = ri.Cvar_Get( "broadsword_effcorr", "1", CVAR_NONE, "" ); - broadsword_ragtobase = ri.Cvar_Get( "broadsword_ragtobase", "2", CVAR_NONE, "" ); - broadsword_dircap = ri.Cvar_Get( "broadsword_dircap", "64", CVAR_NONE, "" ); -/* -Ghoul2 Insert End -*/ - - r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces" ); - - r_modelpoolmegs = ri.Cvar_Get("r_modelpoolmegs", "20", CVAR_ARCHIVE, "" ); - if (ri.Sys_LowPhysicalMemory() ) + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", CVAR_CHEAT, ""); + r_Ghoul2AnimSmooth = ri.Cvar_Get("r_ghoul2animsmooth", "0.3", CVAR_NONE, ""); + r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get("r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, ""); + broadsword = ri.Cvar_Get("broadsword", "0", CVAR_NONE, ""); + broadsword_kickbones = ri.Cvar_Get("broadsword_kickbones", "1", CVAR_NONE, ""); + broadsword_kickorigin = ri.Cvar_Get("broadsword_kickorigin", "1", CVAR_NONE, ""); + broadsword_dontstopanim = ri.Cvar_Get("broadsword_dontstopanim", "0", CVAR_NONE, ""); + broadsword_waitforshot = ri.Cvar_Get("broadsword_waitforshot", "0", CVAR_NONE, ""); + broadsword_playflop = ri.Cvar_Get("broadsword_playflop", "1", CVAR_NONE, ""); + broadsword_smallbbox = ri.Cvar_Get("broadsword_smallbbox", "0", CVAR_NONE, ""); + broadsword_extra1 = ri.Cvar_Get("broadsword_extra1", "0", CVAR_NONE, ""); + broadsword_extra2 = ri.Cvar_Get("broadsword_extra2", "0", CVAR_NONE, ""); + broadsword_effcorr = ri.Cvar_Get("broadsword_effcorr", "1", CVAR_NONE, ""); + broadsword_ragtobase = ri.Cvar_Get("broadsword_ragtobase", "2", CVAR_NONE, ""); + broadsword_dircap = ri.Cvar_Get("broadsword_dircap", "64", CVAR_NONE, ""); + /* + Ghoul2 Insert End + */ + + r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces"); + + r_modelpoolmegs = ri.Cvar_Get("r_modelpoolmegs", "20", CVAR_ARCHIVE, ""); + if (ri.Sys_LowPhysicalMemory()) ri.Cvar_Set("r_modelpoolmegs", "0"); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_AddCommand( commands[i].cmd, commands[i].func, "" ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_AddCommand(commands[i].cmd, commands[i].func, ""); } - /* =============== R_Init =============== */ -extern void R_InitWorldEffects(void); //tr_WorldEffects.cpp -void R_Init( void ) { +extern void R_InitWorldEffects(void); // tr_WorldEffects.cpp +void R_Init(void) { int i; byte *ptr; -// Com_Printf ("----- R_Init -----\n" ); + // Com_Printf ("----- R_Init -----\n" ); // clear all our internal state - memset( &tr, 0, sizeof( tr ) ); - memset( &backEnd, 0, sizeof( backEnd ) ); + memset(&tr, 0, sizeof(tr)); + memset(&backEnd, 0, sizeof(backEnd)); -// Swap_Init(); + // Swap_Init(); // // init function tables // - for ( i = 0; i < FUNCTABLE_SIZE; i++ ) - { - tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) ); - tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f; + for (i = 0; i < FUNCTABLE_SIZE; i++) { + tr.sinTable[i] = sin(DEG2RAD(i * 360.0f / ((float)(FUNCTABLE_SIZE - 1)))); + tr.squareTable[i] = (i < FUNCTABLE_SIZE / 2) ? 1.0f : -1.0f; tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE; tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i]; - if ( i < FUNCTABLE_SIZE / 2 ) - { - if ( i < FUNCTABLE_SIZE / 4 ) - { - tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 ); - } - else - { - tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4]; + if (i < FUNCTABLE_SIZE / 2) { + if (i < FUNCTABLE_SIZE / 4) { + tr.triangleTable[i] = (float)i / (FUNCTABLE_SIZE / 4); + } else { + tr.triangleTable[i] = 1.0f - tr.triangleTable[i - FUNCTABLE_SIZE / 4]; } - } - else - { - tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2]; + } else { + tr.triangleTable[i] = -tr.triangleTable[i - FUNCTABLE_SIZE / 2]; } } R_Register(); - max_polys = Q_min( r_maxpolys->integer, DEFAULT_MAX_POLYS ); - max_polyverts = Q_min( r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS ); + max_polys = Q_min(r_maxpolys->integer, DEFAULT_MAX_POLYS); + max_polyverts = Q_min(r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS); - ptr = (byte *)Hunk_Alloc( sizeof( *backEndData ) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low); - backEndData = (backEndData_t *) ptr; - backEndData->polys = (srfPoly_t *) ((char *) ptr + sizeof( *backEndData )); - backEndData->polyVerts = (polyVert_t *) ((char *) ptr + sizeof( *backEndData ) + sizeof(srfPoly_t) * max_polys); + ptr = (byte *)Hunk_Alloc(sizeof(*backEndData) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low); + backEndData = (backEndData_t *)ptr; + backEndData->polys = (srfPoly_t *)((char *)ptr + sizeof(*backEndData)); + backEndData->polyVerts = (polyVert_t *)((char *)ptr + sizeof(*backEndData) + sizeof(srfPoly_t) * max_polys); R_ModelInit(); -// Com_Printf ("----- finished R_Init -----\n" ); + // Com_Printf ("----- finished R_Init -----\n" ); } /* @@ -530,23 +518,23 @@ void R_Init( void ) { RE_Shutdown =============== */ -void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { +void RE_Shutdown(qboolean destroyWindow, qboolean restarting) { -// Com_Printf ("RE_Shutdown( %i )\n", destroyWindow ); + // Com_Printf ("RE_Shutdown( %i )\n", destroyWindow ); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_RemoveCommand( commands[i].cmd ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_RemoveCommand(commands[i].cmd); tr.registered = qfalse; } -static void G2API_BoltMatrixReconstruction( qboolean reconstruct ) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } -static void G2API_BoltMatrixSPMethod( qboolean spMethod ) { gG2_GBMUseSPMethod = spMethod; } +static void G2API_BoltMatrixReconstruction(qboolean reconstruct) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } +static void G2API_BoltMatrixSPMethod(qboolean spMethod) { gG2_GBMUseSPMethod = spMethod; } -extern void R_SVModelInit( void ); //tr_model.cpp +extern void R_SVModelInit(void); // tr_model.cpp extern qboolean gG2_GBMNoReconstruct; extern qboolean gG2_GBMUseSPMethod; -extern qhandle_t RE_RegisterServerSkin( const char *name ); +extern qhandle_t RE_RegisterServerSkin(const char *name); /* @@@@@@@@@@@@@@@@@@@@@ @@ -554,16 +542,16 @@ GetRefAPI @@@@@@@@@@@@@@@@@@@@@ */ -refexport_t *GetRefAPI ( int apiVersion, refimport_t *rimp ) { +refexport_t *GetRefAPI(int apiVersion, refimport_t *rimp) { static refexport_t re; - assert( rimp ); + assert(rimp); ri = *rimp; - memset( &re, 0, sizeof( re ) ); + memset(&re, 0, sizeof(re)); - if ( apiVersion != REF_API_VERSION ) { - Com_Printf ( "Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion ); + if (apiVersion != REF_API_VERSION) { + Com_Printf("Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion); return NULL; } @@ -571,113 +559,113 @@ refexport_t *GetRefAPI ( int apiVersion, refimport_t *rimp ) { re.Shutdown = RE_Shutdown; - re.RegisterMedia_LevelLoadBegin = RE_RegisterMedia_LevelLoadBegin; - re.RegisterMedia_LevelLoadEnd = RE_RegisterMedia_LevelLoadEnd; - re.RegisterMedia_GetLevel = RE_RegisterMedia_GetLevel; - re.RegisterModels_LevelLoadEnd = RE_RegisterModels_LevelLoadEnd; + re.RegisterMedia_LevelLoadBegin = RE_RegisterMedia_LevelLoadBegin; + re.RegisterMedia_LevelLoadEnd = RE_RegisterMedia_LevelLoadEnd; + re.RegisterMedia_GetLevel = RE_RegisterMedia_GetLevel; + re.RegisterModels_LevelLoadEnd = RE_RegisterModels_LevelLoadEnd; - re.RegisterServerSkin = RE_RegisterServerSkin; + re.RegisterServerSkin = RE_RegisterServerSkin; // G2 stuff - re.InitSkins = R_InitSkins; - re.InitShaders = R_InitShaders; - re.SVModelInit = R_SVModelInit; - re.HunkClearCrap = RE_HunkClearCrap; + re.InitSkins = R_InitSkins; + re.InitShaders = R_InitShaders; + re.SVModelInit = R_SVModelInit; + re.HunkClearCrap = RE_HunkClearCrap; // G2API - re.G2API_AddBolt = G2API_AddBolt; - re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; - re.G2API_AddSurface = G2API_AddSurface; - re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; - re.G2API_AttachEnt = G2API_AttachEnt; - re.G2API_AttachG2Model = G2API_AttachG2Model; - re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; - re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; - re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; - re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; - re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; - re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; - re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; - re.G2API_CollisionDetect = G2API_CollisionDetect; - re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; - re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; - re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; - re.G2API_DetachG2Model = G2API_DetachG2Model; - re.G2API_DoesBoneExist = G2API_DoesBoneExist; - re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; - re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; - re.G2API_GetAnimFileName = G2API_GetAnimFileName; - re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; - re.G2API_GetAnimRange = G2API_GetAnimRange; - re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; - re.G2API_GetBoneAnim = G2API_GetBoneAnim; - re.G2API_GetBoneIndex = G2API_GetBoneIndex; - re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; - re.G2API_GetGLAName = G2API_GetGLAName; - re.G2API_GetModelName = G2API_GetModelName; - re.G2API_GetParentSurface = G2API_GetParentSurface; - re.G2API_GetRagBonePos = G2API_GetRagBonePos; - re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; - re.G2API_GetSurfaceName = G2API_GetSurfaceName; - re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; - re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; - re.G2API_GetTime = G2API_GetTime; - re.G2API_Ghoul2Size = G2API_Ghoul2Size; - re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; - re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; - re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; - re.G2API_IKMove = G2API_IKMove; - re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; - re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; - re.G2API_IsPaused = G2API_IsPaused; - re.G2API_ListBones = G2API_ListBones; - re.G2API_ListSurfaces = G2API_ListSurfaces; - re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; - re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; - re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; - re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; - re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; - re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; - re.G2API_RagEffectorKick = G2API_RagEffectorKick; - re.G2API_RagForceSolve = G2API_RagForceSolve; - re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; - re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; - re.G2API_RemoveBolt = G2API_RemoveBolt; - re.G2API_RemoveBone = G2API_RemoveBone; - re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; - re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; - re.G2API_RemoveSurface = G2API_RemoveSurface; - re.G2API_ResetRagDoll = G2API_ResetRagDoll; - re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; - re.G2API_SetBoltInfo = G2API_SetBoltInfo; - re.G2API_SetBoneAngles = G2API_SetBoneAngles; - re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; - re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; - re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; - re.G2API_SetBoneAnim = G2API_SetBoneAnim; - re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; - re.G2API_SetBoneIKState = G2API_SetBoneIKState; - re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; - re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; - re.G2API_SetLodBias = G2API_SetLodBias; - re.G2API_SetNewOrigin = G2API_SetNewOrigin; - re.G2API_SetRagDoll = G2API_SetRagDoll; - re.G2API_SetRootSurface = G2API_SetRootSurface; - re.G2API_SetShader = G2API_SetShader; - re.G2API_SetSkin = G2API_SetSkin; - re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; - re.G2API_SetTime = G2API_SetTime; - re.G2API_SkinlessModel = G2API_SkinlessModel; - re.G2API_StopBoneAngles = G2API_StopBoneAngles; - re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; - re.G2API_StopBoneAnim = G2API_StopBoneAnim; - re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; - - #ifdef _G2_GORE - re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; - re.G2API_AddSkinGore = G2API_AddSkinGore; - re.G2API_ClearSkinGore = G2API_ClearSkinGore; - #endif // _SOF2 + re.G2API_AddBolt = G2API_AddBolt; + re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; + re.G2API_AddSurface = G2API_AddSurface; + re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; + re.G2API_AttachEnt = G2API_AttachEnt; + re.G2API_AttachG2Model = G2API_AttachG2Model; + re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; + re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; + re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; + re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; + re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; + re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; + re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; + re.G2API_CollisionDetect = G2API_CollisionDetect; + re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; + re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; + re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; + re.G2API_DetachG2Model = G2API_DetachG2Model; + re.G2API_DoesBoneExist = G2API_DoesBoneExist; + re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; + re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; + re.G2API_GetAnimFileName = G2API_GetAnimFileName; + re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; + re.G2API_GetAnimRange = G2API_GetAnimRange; + re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; + re.G2API_GetBoneAnim = G2API_GetBoneAnim; + re.G2API_GetBoneIndex = G2API_GetBoneIndex; + re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; + re.G2API_GetGLAName = G2API_GetGLAName; + re.G2API_GetModelName = G2API_GetModelName; + re.G2API_GetParentSurface = G2API_GetParentSurface; + re.G2API_GetRagBonePos = G2API_GetRagBonePos; + re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; + re.G2API_GetSurfaceName = G2API_GetSurfaceName; + re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; + re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; + re.G2API_GetTime = G2API_GetTime; + re.G2API_Ghoul2Size = G2API_Ghoul2Size; + re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; + re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; + re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; + re.G2API_IKMove = G2API_IKMove; + re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; + re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; + re.G2API_IsPaused = G2API_IsPaused; + re.G2API_ListBones = G2API_ListBones; + re.G2API_ListSurfaces = G2API_ListSurfaces; + re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; + re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; + re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; + re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; + re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; + re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; + re.G2API_RagEffectorKick = G2API_RagEffectorKick; + re.G2API_RagForceSolve = G2API_RagForceSolve; + re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; + re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; + re.G2API_RemoveBolt = G2API_RemoveBolt; + re.G2API_RemoveBone = G2API_RemoveBone; + re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; + re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; + re.G2API_RemoveSurface = G2API_RemoveSurface; + re.G2API_ResetRagDoll = G2API_ResetRagDoll; + re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; + re.G2API_SetBoltInfo = G2API_SetBoltInfo; + re.G2API_SetBoneAngles = G2API_SetBoneAngles; + re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; + re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; + re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; + re.G2API_SetBoneAnim = G2API_SetBoneAnim; + re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; + re.G2API_SetBoneIKState = G2API_SetBoneIKState; + re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; + re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; + re.G2API_SetLodBias = G2API_SetLodBias; + re.G2API_SetNewOrigin = G2API_SetNewOrigin; + re.G2API_SetRagDoll = G2API_SetRagDoll; + re.G2API_SetRootSurface = G2API_SetRootSurface; + re.G2API_SetShader = G2API_SetShader; + re.G2API_SetSkin = G2API_SetSkin; + re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; + re.G2API_SetTime = G2API_SetTime; + re.G2API_SkinlessModel = G2API_SkinlessModel; + re.G2API_StopBoneAngles = G2API_StopBoneAngles; + re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; + re.G2API_StopBoneAnim = G2API_StopBoneAnim; + re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; + +#ifdef _G2_GORE + re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; + re.G2API_AddSkinGore = G2API_AddSkinGore; + re.G2API_ClearSkinGore = G2API_ClearSkinGore; +#endif // _SOF2 return &re; } diff --git a/codemp/rd-dedicated/tr_main.cpp b/codemp/rd-dedicated/tr_main.cpp index 542183f936..e3d4740e43 100644 --- a/codemp/rd-dedicated/tr_main.cpp +++ b/codemp/rd-dedicated/tr_main.cpp @@ -25,60 +25,53 @@ along with this program; if not, see . #include "tr_local.h" #include "ghoul2/g2_local.h" -trGlobals_t tr; +trGlobals_t tr; -refimport_t ri; +refimport_t ri; void R_AddTerrainSurfaces(void); /* ** R_CullLocalPointAndRadius */ -int R_CullLocalPointAndRadius( const vec3_t pt, float radius ) -{ +int R_CullLocalPointAndRadius(const vec3_t pt, float radius) { vec3_t transformed; - R_LocalPointToWorld( pt, transformed ); + R_LocalPointToWorld(pt, transformed); - return R_CullPointAndRadius( transformed, radius ); + return R_CullPointAndRadius(transformed, radius); } /* ** R_CullPointAndRadius */ -int R_CullPointAndRadius( const vec3_t pt, float radius ) -{ - int i; - float dist; - cplane_t *frust; +int R_CullPointAndRadius(const vec3_t pt, float radius) { + int i; + float dist; + cplane_t *frust; qboolean mightBeClipped = qfalse; - if ( r_nocull->integer==1 ) { + if (r_nocull->integer == 1) { return CULL_CLIP; } // check against frustum planes - for (i = 0 ; i < 4 ; i++) - { + for (i = 0; i < 4; i++) { frust = &tr.viewParms.frustum[i]; - dist = DotProduct( pt, frust->normal) - frust->dist; - if ( dist < -radius ) - { + dist = DotProduct(pt, frust->normal) - frust->dist; + if (dist < -radius) { return CULL_OUT; - } - else if ( dist <= radius ) - { + } else if (dist <= radius) { mightBeClipped = qtrue; } } - if ( mightBeClipped ) - { + if (mightBeClipped) { return CULL_CLIP; } - return CULL_IN; // completely inside frustum + return CULL_IN; // completely inside frustum } /* @@ -87,7 +80,7 @@ R_LocalPointToWorld ================= */ -void R_LocalPointToWorld (const vec3_t local, vec3_t world) { +void R_LocalPointToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0] + tr.ori.origin[0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1] + tr.ori.origin[1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2] + tr.ori.origin[2]; diff --git a/codemp/rd-dedicated/tr_mesh.cpp b/codemp/rd-dedicated/tr_mesh.cpp index 84a5fb2826..900ea27739 100644 --- a/codemp/rd-dedicated/tr_mesh.cpp +++ b/codemp/rd-dedicated/tr_mesh.cpp @@ -25,39 +25,33 @@ along with this program; if not, see . #include "tr_local.h" - -float ProjectRadius( float r, vec3_t location ) -{ +float ProjectRadius(float r, vec3_t location) { float pr; float dist; float c; - vec3_t p; + vec3_t p; float width; float depth; - c = DotProduct( tr.viewParms.ori.axis[0], tr.viewParms.ori.origin ); - dist = DotProduct( tr.viewParms.ori.axis[0], location ) - c; + c = DotProduct(tr.viewParms.ori.axis[0], tr.viewParms.ori.origin); + dist = DotProduct(tr.viewParms.ori.axis[0], location) - c; - if ( dist <= 0 ) + if (dist <= 0) return 0; p[0] = 0; - p[1] = Q_fabs( r ); + p[1] = Q_fabs(r); p[2] = -dist; - width = p[0] * tr.viewParms.projectionMatrix[1] + - p[1] * tr.viewParms.projectionMatrix[5] + - p[2] * tr.viewParms.projectionMatrix[9] + - tr.viewParms.projectionMatrix[13]; + width = p[0] * tr.viewParms.projectionMatrix[1] + p[1] * tr.viewParms.projectionMatrix[5] + p[2] * tr.viewParms.projectionMatrix[9] + + tr.viewParms.projectionMatrix[13]; - depth = p[0] * tr.viewParms.projectionMatrix[3] + - p[1] * tr.viewParms.projectionMatrix[7] + - p[2] * tr.viewParms.projectionMatrix[11] + - tr.viewParms.projectionMatrix[15]; + depth = p[0] * tr.viewParms.projectionMatrix[3] + p[1] * tr.viewParms.projectionMatrix[7] + p[2] * tr.viewParms.projectionMatrix[11] + + tr.viewParms.projectionMatrix[15]; pr = width / depth; - if ( pr > 1.0f ) + if (pr > 1.0f) pr = 1.0f; return pr; diff --git a/codemp/rd-dedicated/tr_model.cpp b/codemp/rd-dedicated/tr_model.cpp index ff15e7dd97..c3cc65ccb5 100644 --- a/codemp/rd-dedicated/tr_model.cpp +++ b/codemp/rd-dedicated/tr_model.cpp @@ -25,182 +25,154 @@ along with this program; if not, see . #include "tr_local.h" #include "qcommon/disablewarnings.h" -#include "qcommon/sstring.h" // #include +#include "qcommon/sstring.h" // #include #include #include -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached ); +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached); /* Ghoul2 Insert Start */ -typedef struct modelHash_s -{ - char name[MAX_QPATH]; - qhandle_t handle; - struct modelHash_s *next; +typedef struct modelHash_s { + char name[MAX_QPATH]; + qhandle_t handle; + struct modelHash_s *next; -}modelHash_t; +} modelHash_t; -#define FILE_HASH_SIZE 1024 -static modelHash_t *mhHashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 +static modelHash_t *mhHashTable[FILE_HASH_SIZE]; /* Ghoul2 Insert End */ - // This stuff looks a bit messy, but it's kept here as black box, and nothing appears in any .H files for other // modules to worry about. I may make another module for this sometime. // -typedef std::pair StringOffsetAndShaderIndexDest_t; -typedef std::vector ShaderRegisterData_t; -struct CachedEndianedModelBinary_s -{ - void *pModelDiskImage; - int iAllocSize; // may be useful for mem-query, but I don't actually need it +typedef std::pair StringOffsetAndShaderIndexDest_t; +typedef std::vector ShaderRegisterData_t; +struct CachedEndianedModelBinary_s { + void *pModelDiskImage; + int iAllocSize; // may be useful for mem-query, but I don't actually need it ShaderRegisterData_t ShaderRegisterData; - int iLastLevelUsedOn; - int iPAKFileCheckSum; // else -1 if not from PAK - + int iLastLevelUsedOn; + int iPAKFileCheckSum; // else -1 if not from PAK - CachedEndianedModelBinary_s() - { - pModelDiskImage = 0; - iAllocSize = 0; + CachedEndianedModelBinary_s() { + pModelDiskImage = 0; + iAllocSize = 0; ShaderRegisterData.clear(); - iLastLevelUsedOn = -1; - iPAKFileCheckSum = -1; + iLastLevelUsedOn = -1; + iPAKFileCheckSum = -1; } }; typedef struct CachedEndianedModelBinary_s CachedEndianedModelBinary_t; -typedef std::map CachedModels_t; -CachedModels_t *CachedModels = NULL; // the important cache item. +typedef std::map CachedModels_t; +CachedModels_t *CachedModels = NULL; // the important cache item. -void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke) -{ +void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { - assert(0); // should never happen, means that we're being called on a model that wasn't loaded - } - else - { - int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; - int iPokeOffset = (char*) piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; + if (ModelBin.pModelDiskImage == NULL) { + assert(0); // should never happen, means that we're being called on a model that wasn't loaded + } else { + int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; + int iPokeOffset = (char *)piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; - ModelBin.ShaderRegisterData.push_back( StringOffsetAndShaderIndexDest_t( iNameOffset,iPokeOffset) ); + ModelBin.ShaderRegisterData.push_back(StringOffsetAndShaderIndexDest_t(iNameOffset, iPokeOffset)); } } - -static const byte FakeGLAFile[] = -{ -0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x01, 0x00, 0x00, 0x00, -0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, -0x26, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, -0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, -0x00, 0x80, 0x00, 0x80, 0x00, 0x80 -}; - -void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ); +static const byte FakeGLAFile[] = { + 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0x3F, 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x26, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6C, 0x74, 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, + 0xFF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80}; + +void RE_LoadWorldMap_Actual(const char *name, world_t &worldData, int index); // returns qtrue if loaded, and sets the supplied qbool to true if it was from cache (instead of disk) // (which we need to know to avoid LittleLong()ing everything again (well, the Mac needs to know anyway)... // // don't use ri->xxx functions in case running on dedicated... // -qboolean RE_RegisterModels_GetDiskFile( const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) -{ +qboolean RE_RegisterModels_GetDiskFile(const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // didn't have it cached, so try the disk... // - // special case intercept first... + // special case intercept first... + // + if (!strcmp(sDEFAULT_GLA_NAME ".gla", psModelFileName)) { + // return fake params as though it was found on disk... // - if (!strcmp(sDEFAULT_GLA_NAME ".gla" , psModelFileName)) - { - // return fake params as though it was found on disk... - // - void *pvFakeGLAFile = Z_Malloc( sizeof(FakeGLAFile), TAG_FILESYS, qfalse ); - memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); - *ppvBuffer = pvFakeGLAFile; - *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well - return qtrue; - } + void *pvFakeGLAFile = Z_Malloc(sizeof(FakeGLAFile), TAG_FILESYS, qfalse); + memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); + *ppvBuffer = pvFakeGLAFile; + *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well + return qtrue; + } - ri.FS_ReadFile( sModelName, ppvBuffer ); + ri.FS_ReadFile(sModelName, ppvBuffer); *pqbAlreadyCached = qfalse; - qboolean bSuccess = !!(*ppvBuffer)?qtrue:qfalse; + qboolean bSuccess = !!(*ppvBuffer) ? qtrue : qfalse; - if (bSuccess) - { - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_GetDiskFile(): Disk-loading \"%s\"\n",psModelFileName); + if (bSuccess) { + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_GetDiskFile(): Disk-loading \"%s\"\n", psModelFileName); } return bSuccess; - } - else - { + } else { *ppvBuffer = ModelBin.pModelDiskImage; *pqbAlreadyCached = qtrue; return qtrue; } } - // if return == true, no further action needed by the caller... // // don't use ri->xxx functions in case running on dedicated // -void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) -{ +void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // ... then this entry has only just been created, ie we need to load it fully... // // new, instead of doing a Z_Malloc and assigning that we just morph the disk buffer alloc @@ -208,29 +180,23 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const // // ... groan, but not if doing a limb hierarchy creation (some VV stuff?), in which case it's NULL // - if ( pvDiskBufferIfJustLoaded ) - { - Z_MorphMallocTag( pvDiskBufferIfJustLoaded, eTag ); - } - else - { - pvDiskBufferIfJustLoaded = Z_Malloc(iSize,eTag, qfalse ); + if (pvDiskBufferIfJustLoaded) { + Z_MorphMallocTag(pvDiskBufferIfJustLoaded, eTag); + } else { + pvDiskBufferIfJustLoaded = Z_Malloc(iSize, eTag, qfalse); } - ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; - ModelBin.iAllocSize = iSize; + ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; + ModelBin.iAllocSize = iSize; int iCheckSum; - if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) - { - ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 + if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) { + ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 } *pqbAlreadyFound = qfalse; - } - else - { - *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary + } else { + *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary } ModelBin.iLastLevelUsedOn = RE_RegisterMedia_GetLevel(); @@ -240,46 +206,38 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const // Unfortunately the dedicated server also hates shader loading. So we need an alternate of this func. // -void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) -{ +void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // new, instead of doing a Z_Malloc and assigning that we just morph the disk buffer alloc // then don't thrown it away on return - cuts down on mem overhead // // ... groan, but not if doing a limb hierarchy creation (some VV stuff?), in which case it's NULL // - if ( pvDiskBufferIfJustLoaded ) - { - Z_MorphMallocTag( pvDiskBufferIfJustLoaded, eTag ); - } - else - { - pvDiskBufferIfJustLoaded = Z_Malloc(iSize,eTag, qfalse ); + if (pvDiskBufferIfJustLoaded) { + Z_MorphMallocTag(pvDiskBufferIfJustLoaded, eTag); + } else { + pvDiskBufferIfJustLoaded = Z_Malloc(iSize, eTag, qfalse); } - ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; - ModelBin.iAllocSize = iSize; + ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; + ModelBin.iAllocSize = iSize; int iCheckSum; - if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) - { - ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 + if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) { + ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 } *pqbAlreadyFound = qfalse; - } - else - { + } else { // if we already had this model entry, then re-register all the shaders it wanted... // /* @@ -302,8 +260,8 @@ void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, } } */ - //No. Bad. - *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary + // No. Bad. + *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary } ModelBin.iLastLevelUsedOn = RE_RegisterMedia_GetLevel(); @@ -313,117 +271,98 @@ void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, // dump any models not being used by this level if we're running low on memory... // -static int GetModelDataAllocSize(void) -{ - return Z_MemSize( TAG_MODEL_MD3) + - Z_MemSize( TAG_MODEL_GLM) + - Z_MemSize( TAG_MODEL_GLA); -} +static int GetModelDataAllocSize(void) { return Z_MemSize(TAG_MODEL_MD3) + Z_MemSize(TAG_MODEL_GLM) + Z_MemSize(TAG_MODEL_GLA); } extern cvar_t *r_modelpoolmegs; // // return qtrue if at least one cached model was freed (which tells z_malloc()-fail recoveryt code to try again) // extern qboolean gbInsideRegisterModel; -qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) -{ +qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) { qboolean bAtLeastoneModelFreed = qfalse; assert(CachedModels); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd():\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd():\n"); - if (gbInsideRegisterModel) - { - ri.Printf( PRINT_DEVELOPER, "(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); - } - else - { - int iLoadedModelBytes = GetModelDataAllocSize(); - const int iMaxModelBytes= r_modelpoolmegs->integer * 1024 * 1024; + if (gbInsideRegisterModel) { + ri.Printf(PRINT_DEVELOPER, "(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); + } else { + int iLoadedModelBytes = GetModelDataAllocSize(); + const int iMaxModelBytes = r_modelpoolmegs->integer * 1024 * 1024; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end() && ( bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes ); /* empty */ ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); + itModel != CachedModels->end() && (bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes); + /* empty */) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; qboolean bDeleteThis = qfalse; - if (bDeleteEverythingNotUsedThisLevel) - { + if (bDeleteEverythingNotUsedThisLevel) { bDeleteThis = (CachedModel.iLastLevelUsedOn != RE_RegisterMedia_GetLevel()) ? qtrue : qfalse; - } - else - { + } else { bDeleteThis = (CachedModel.iLastLevelUsedOn < RE_RegisterMedia_GetLevel()) ? qtrue : qfalse; } // if it wasn't used on this level, dump it... // - if (bDeleteThis) - { + if (bDeleteThis) { const char *psModelName = (*itModel).first.c_str(); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Dumping \"%s\"", psModelName); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Dumping \"%s\"", psModelName); - #ifdef _DEBUG - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED ", used on lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif +#ifdef _DEBUG + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED ", used on lvl %d\n", CachedModel.iLastLevelUsedOn); +#endif if (CachedModel.pModelDiskImage) { Z_Free(CachedModel.pModelDiskImage); - //CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. + // CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. bAtLeastoneModelFreed = qtrue; } CachedModels->erase(itModel++); iLoadedModelBytes = GetModelDataAllocSize(); - } - else - { + } else { ++itModel; } } } - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd(): Ok\n"); return bAtLeastoneModelFreed; } - - // scan through all loaded models and see if their PAK checksums are still valid with the current pure PAK lists, // dump any that aren't (so people can't cheat by using models with huge spikes that show through walls etc) // // (avoid using ri->xxxx stuff here in case running on dedicated) // -static void RE_RegisterModels_DumpNonPure(void) -{ - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure():\n"); +static void RE_RegisterModels_DumpNonPure(void) { + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure():\n"); - if(!CachedModels) { + if (!CachedModels) { return; } - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); /* blank */) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); /* blank */) { qboolean bEraseOccured = qfalse; - const char *psModelName = (*itModel).first.c_str(); + const char *psModelName = (*itModel).first.c_str(); CachedEndianedModelBinary_t &CachedModel = (*itModel).second; int iCheckSum = -1; int iInPak = ri.FS_FileIsInPAK(psModelName, &iCheckSum); - if (iInPak == -1 || iCheckSum != CachedModel.iPAKFileCheckSum) - { - if (Q_stricmp(sDEFAULT_GLA_NAME ".gla" , psModelName)) // don't dump "*default.gla", that's program internal anyway + if (iInPak == -1 || iCheckSum != CachedModel.iPAKFileCheckSum) { + if (Q_stricmp(sDEFAULT_GLA_NAME ".gla", psModelName)) // don't dump "*default.gla", that's program internal anyway { // either this is not from a PAK, or it's from a non-pure one, so ditch it... // - ri.Printf( PRINT_DEVELOPER, "Dumping none pure model \"%s\"", psModelName); + ri.Printf(PRINT_DEVELOPER, "Dumping none pure model \"%s\"", psModelName); if (CachedModel.pModelDiskImage) { Z_Free(CachedModel.pModelDiskImage); - //CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. + // CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. } CachedModels->erase(itModel++); @@ -431,52 +370,46 @@ static void RE_RegisterModels_DumpNonPure(void) } } - if ( !bEraseOccured ) - { + if (!bEraseOccured) { ++itModel; } } - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure(): Ok\n"); } -void RE_RegisterModels_Info_f( void ) -{ +void RE_RegisterModels_Info_f(void) { int iTotalBytes = 0; - if(!CachedModels) { - Com_Printf ("%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + if (!CachedModels) { + Com_Printf("%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); return; } int iModels = CachedModels->size(); - int iModel = 0; + int iModel = 0; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel,iModel++) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel, iModel++) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; - Com_Printf ("%d/%d: \"%s\" (%d bytes)",iModel,iModels,(*itModel).first.c_str(),CachedModel.iAllocSize ); + Com_Printf("%d/%d: \"%s\" (%d bytes)", iModel, iModels, (*itModel).first.c_str(), CachedModel.iAllocSize); - #ifdef _DEBUG - Com_Printf (", lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif +#ifdef _DEBUG + Com_Printf(", lvl %d\n", CachedModel.iLastLevelUsedOn); +#endif iTotalBytes += CachedModel.iAllocSize; } - Com_Printf ("%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + Com_Printf("%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); } - // (don't use ri->xxx functions since the renderer may not be running here)... // -static void RE_RegisterModels_DeleteAll(void) -{ - if(!CachedModels) { - return; //argh! +static void RE_RegisterModels_DeleteAll(void) { + if (!CachedModels) { + return; // argh! } - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end();) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; if (CachedModel.pModelDiskImage) { @@ -487,25 +420,19 @@ static void RE_RegisterModels_DeleteAll(void) } } - // do not use ri->xxx functions in here, the renderer may not be running (ie. if on a dedicated server)... // -static int giRegisterMedia_CurrentLevel=0; -void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) -{ +static int giRegisterMedia_CurrentLevel = 0; +void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) { // for development purposes we may want to ditch certain media just before loading a map... // - bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; -// bool bDeleteBSP = eForceReload == eForceReload_BSP || eForceReload == eForceReload_ALL; + bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; + // bool bDeleteBSP = eForceReload == eForceReload_BSP || eForceReload == eForceReload_ALL; - if (bDeleteModels) - { + if (bDeleteModels) { RE_RegisterModels_DeleteAll(); - } - else - { - if ( ri.Cvar_VariableIntegerValue( "sv_pure" ) ) - { + } else { + if (ri.Cvar_VariableIntegerValue("sv_pure")) { RE_RegisterModels_DumpNonPure(); } } @@ -519,36 +446,27 @@ void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForce // only bump level number if we're not on the same level. // Note that this will hide uncached models, which is perhaps a bad thing?... // - static char sPrevMapName[MAX_QPATH]={0}; - if (Q_stricmp( psMapName,sPrevMapName )) - { - Q_strncpyz( sPrevMapName, psMapName, sizeof(sPrevMapName) ); + static char sPrevMapName[MAX_QPATH] = {0}; + if (Q_stricmp(psMapName, sPrevMapName)) { + Q_strncpyz(sPrevMapName, psMapName, sizeof(sPrevMapName)); giRegisterMedia_CurrentLevel++; } } -int RE_RegisterMedia_GetLevel(void) -{ - return giRegisterMedia_CurrentLevel; -} +int RE_RegisterMedia_GetLevel(void) { return giRegisterMedia_CurrentLevel; } // this is now only called by the client, so should be ok to dump media... // -void RE_RegisterMedia_LevelLoadEnd(void) -{ - RE_RegisterModels_LevelLoadEnd(qfalse); -} - - +void RE_RegisterMedia_LevelLoadEnd(void) { RE_RegisterModels_LevelLoadEnd(qfalse); } /* ** R_GetModelByHandle */ -model_t *R_GetModelByHandle( qhandle_t index ) { - model_t *mod; +model_t *R_GetModelByHandle(qhandle_t index) { + model_t *mod; // out of range gets the defualt model - if ( index < 1 || index >= tr.numModels ) { + if (index < 1 || index >= tr.numModels) { return tr.models[0]; } @@ -562,14 +480,14 @@ model_t *R_GetModelByHandle( qhandle_t index ) { /* ** R_AllocModel */ -model_t *R_AllocModel( void ) { - model_t *mod; +model_t *R_AllocModel(void) { + model_t *mod; - if ( tr.numModels == MAX_MOD_KNOWN ) { + if (tr.numModels == MAX_MOD_KNOWN) { return NULL; } - mod = (struct model_s *)Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), h_low ); + mod = (struct model_s *)Hunk_Alloc(sizeof(*tr.models[tr.numModels]), h_low); mod->index = tr.numModels; tr.models[tr.numModels] = mod; tr.numModels++; @@ -586,33 +504,34 @@ Ghoul2 Insert Start return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (size-1); + hash &= (size - 1); return hash; } -void RE_InsertModelIntoHash(const char *name, model_t *mod) -{ - int hash; - modelHash_t *mh; +void RE_InsertModelIntoHash(const char *name, model_t *mod) { + int hash; + modelHash_t *mh; hash = generateHashValue(name, FILE_HASH_SIZE); // insert this file into the hash table so we can look it up faster later - mh = (modelHash_t*)Hunk_Alloc( sizeof( modelHash_t ), h_low ); + mh = (modelHash_t *)Hunk_Alloc(sizeof(modelHash_t), h_low); mh->next = mhHashTable[hash]; mh->handle = mod->index; @@ -623,22 +542,22 @@ void RE_InsertModelIntoHash(const char *name, model_t *mod) Ghoul2 Insert End */ -//rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. -//You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated -//server is running, which is the entire point of having these seperate functions. If anything major -//is changed in the non-server-only versions of these functions it would be wise to incorporate it -//here as well. +// rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. +// You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated +// server is running, which is the entire point of having these seperate functions. If anything major +// is changed in the non-server-only versions of these functions it would be wise to incorporate it +// here as well. /* ================= ServerLoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean ServerLoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; #if 0 //#ifndef _M_IX86 int j, k, i; @@ -647,15 +566,14 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool mdxaSkel_t *boneInfo; #endif - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } @@ -664,17 +582,16 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxa = mod->mdxa = (mdxaHeader_t*) //Hunk_Alloc( size ); - RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = mod->mdxa = (mdxaHeader_t *) // Hunk_Alloc( size ); + RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -682,8 +599,8 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); -// memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxa == buffer); + // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing LL(mdxa->ident); LL(mdxa->version); @@ -693,13 +610,12 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool LL(mdxa->ofsEnd); } - if ( mdxa->numFrames < 1 ) { + if (mdxa->numFrames < 1) { return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } #if 0 //#ifndef _M_IX86 @@ -750,15 +666,15 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool ServerLoadMDXM - load a Ghoul 2 Mesh file ================= */ -qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - //shader_t *sh; - mdxmSurfHierarchy_t *surfInfo; +qboolean ServerLoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + // shader_t *sh; + mdxmSurfHierarchy_t *surfInfo; #if 0 //#ifndef _M_IX86 int k; @@ -770,15 +686,14 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool int *boneRef; #endif - pinmodel= (mdxmHeader_t *)buffer; + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } @@ -787,17 +702,16 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool return qfalse; } - mod->type = MOD_MDXM; + mod->type = MOD_MDXM; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxm = mod->mdxm = (mdxmHeader_t*) //Hunk_Alloc( size ); - RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mdxm = mod->mdxm = (mdxmHeader_t *) // Hunk_Alloc( size ); + RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -805,8 +719,8 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -818,33 +732,29 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool } // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterServerModel(va ("%s.gla",mdxm->animName)); - if (!mdxm->animIndex) - { + mdxm->animIndex = RE_RegisterServerModel(va("%s.gla", mdxm->animName)); + if (!mdxm->animIndex) { return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->numChildren); LL(surfInfo->parentIndex); // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } // We will not be using shaders on the server. - //sh = 0; + // sh = 0; // insert it in the surface list surfInfo->shaderIndex = 0; @@ -852,20 +762,18 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool RE_RegisterModels_StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->numTriangles); LL(surf->ofsTriangles); LL(surf->numVerts); @@ -874,14 +782,14 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool LL(surf->ofsHeader); LL(surf->numBoneReferences); LL(surf->ofsBoneReferences); -// LL(surf->maxVertBoneWeights); + // LL(surf->maxVertBoneWeights); triCount += surf->numTriangles; - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { + if (surf->numVerts > SHADER_MAX_VERTEXES) { return qfalse; } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { return qfalse; } @@ -937,11 +845,11 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool #endif // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; @@ -954,33 +862,33 @@ RE_RegisterServerModel Same as RE_RegisterModel, except used by the server to handle ghoul2 instance models. ==================== */ -qhandle_t RE_RegisterServerModel( const char *name ) { - model_t *mod; - unsigned *buf; - int lod; - int ident; - qboolean loaded; -// qhandle_t hModel; - int numLoaded; -/* -Ghoul2 Insert Start -*/ - int hash; - modelHash_t *mh; -/* -Ghoul2 Insert End -*/ - - if (!r_noServerGhoul2) - { //keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing though. - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", 0, ""); - } - - if ( !name || !name[0] ) { +qhandle_t RE_RegisterServerModel(const char *name) { + model_t *mod; + unsigned *buf; + int lod; + int ident; + qboolean loaded; + // qhandle_t hModel; + int numLoaded; + /* + Ghoul2 Insert Start + */ + int hash; + modelHash_t *mh; + /* + Ghoul2 Insert End + */ + + if (!r_noServerGhoul2) { // keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing + // though. + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", 0, ""); + } + + if (!name || !name[0]) { return 0; } - if ( strlen( name ) >= MAX_QPATH ) { + if (strlen(name) >= MAX_QPATH) { return 0; } @@ -989,22 +897,22 @@ Ghoul2 Insert End // // see if the model is already loaded // - for (mh=mhHashTable[hash]; mh; mh=mh->next) { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { if (Q_stricmp(mh->name, name) == 0) { return mh->handle; } } - if ( ( mod = R_AllocModel() ) == NULL ) { + if ((mod = R_AllocModel()) == NULL) { return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); int iLODStart = 0; - if (strstr (name, ".md3")) { - iLODStart = MD3_MAX_LODS-1; // this loads the md3s in reverse so they can be biased + if (strstr(name, ".md3")) { + iLODStart = MD3_MAX_LODS - 1; // this loads the md3s in reverse so they can be biased } mod->numLods = 0; @@ -1013,58 +921,55 @@ Ghoul2 Insert End // numLoaded = 0; - for ( lod = iLODStart; lod >= 0 ; lod-- ) { + for (lod = iLODStart; lod >= 0; lod--) { char filename[1024]; - strcpy( filename, name ); + strcpy(filename, name); - if ( lod != 0 ) { + if (lod != 0) { char namebuf[80]; - if ( strrchr( filename, '.' ) ) { - *strrchr( filename, '.' ) = 0; + if (strrchr(filename, '.')) { + *strrchr(filename, '.') = 0; } - sprintf( namebuf, "_%d.md3", lod ); - strcat( filename, namebuf ); + sprintf(namebuf, "_%d.md3", lod); + strcat(filename, namebuf); } qboolean bAlreadyCached = qfalse; - if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) - { + if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) { continue; } - //loadmodel = mod; // this seems to be fairly pointless + // loadmodel = mod; // this seems to be fairly pointless // important that from now on we pass 'filename' instead of 'name' to all model load functions, // because 'filename' accounts for any LOD mangling etc so guarantees unique lookups for yet more // internal caching... // ident = *(unsigned *)buf; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(ident); } - switch (ident) - { //if you're trying to register anything else as a model type on the server, you are out of luck + switch (ident) { // if you're trying to register anything else as a model type on the server, you are out of luck - case MDXA_IDENT: - loaded = ServerLoadMDXA( mod, buf, filename, bAlreadyCached ); - break; - case MDXM_IDENT: - loaded = ServerLoadMDXM( mod, buf, filename, bAlreadyCached ); - break; - default: - goto fail; + case MDXA_IDENT: + loaded = ServerLoadMDXA(mod, buf, filename, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = ServerLoadMDXM(mod, buf, filename, bAlreadyCached); + break; + default: + goto fail; } - if (!bAlreadyCached){ // important to check!! - ri.FS_FreeFile (buf); + if (!bAlreadyCached) { // important to check!! + ri.FS_FreeFile(buf); } - if ( !loaded ) { - if ( lod == 0 ) { + if (!loaded) { + if (lod == 0) { goto fail; } else { break; @@ -1075,23 +980,23 @@ Ghoul2 Insert End } } - if ( numLoaded ) { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for ( lod-- ; lod >= 0 ; lod-- ) { + for (lod--; lod >= 0; lod--) { mod->numLods++; - mod->md3[lod] = mod->md3[lod+1]; + mod->md3[lod] = mod->md3[lod + 1]; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - RE_InsertModelIntoHash(name, mod); - return mod->index; -/* -Ghoul2 Insert End -*/ + RE_InsertModelIntoHash(name, mod); + return mod->index; + /* + Ghoul2 Insert End + */ } fail: @@ -1102,7 +1007,6 @@ Ghoul2 Insert End return 0; } - /* ==================== RE_RegisterModel @@ -1115,40 +1019,40 @@ optimization to prevent disk rescanning if they are asked for again. ==================== */ -static qhandle_t RE_RegisterModel_Actual( const char *name ) { - model_t *mod; - unsigned *buf; - int lod; - int ident; - qboolean loaded; -// qhandle_t hModel; - int numLoaded; -/* -Ghoul2 Insert Start -*/ - int hash; - modelHash_t *mh; -/* -Ghoul2 Insert End -*/ - - if ( !name || !name[0] ) { - Com_Printf ("RE_RegisterModel: NULL name\n" ); +static qhandle_t RE_RegisterModel_Actual(const char *name) { + model_t *mod; + unsigned *buf; + int lod; + int ident; + qboolean loaded; + // qhandle_t hModel; + int numLoaded; + /* + Ghoul2 Insert Start + */ + int hash; + modelHash_t *mh; + /* + Ghoul2 Insert End + */ + + if (!name || !name[0]) { + Com_Printf("RE_RegisterModel: NULL name\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Model name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Model name exceeds MAX_QPATH\n"); return 0; } -/* -Ghoul2 Insert Start -*/ -// if (!tr.registered) { -// Com_Printf (S_COLOR_YELLOW "RE_RegisterModel (%s) called before ready!\n",name ); -// return 0; -// } + /* + Ghoul2 Insert Start + */ + // if (!tr.registered) { + // Com_Printf (S_COLOR_YELLOW "RE_RegisterModel (%s) called before ready!\n",name ); + // return 0; + // } // // search the currently loaded models // @@ -1157,33 +1061,30 @@ Ghoul2 Insert Start // // see if the model is already loaded // - for (mh=mhHashTable[hash]; mh; mh=mh->next) { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { if (Q_stricmp(mh->name, name) == 0) { return mh->handle; } } -// for ( hModel = 1 ; hModel < tr.numModels; hModel++ ) { -// mod = tr.models[hModel]; -// if ( !strcmp( mod->name, name ) ) { -// if( mod->type == MOD_BAD ) { -// return 0; -// } -// return hModel; -// } -// } + // for ( hModel = 1 ; hModel < tr.numModels; hModel++ ) { + // mod = tr.models[hModel]; + // if ( !strcmp( mod->name, name ) ) { + // if( mod->type == MOD_BAD ) { + // return 0; + // } + // return hModel; + // } + // } - if (name[0] == '#') - { - char temp[MAX_QPATH]; + if (name[0] == '#') { + char temp[MAX_QPATH]; tr.numBSPModels++; Com_sprintf(temp, MAX_QPATH, "*%d-0", tr.numBSPModels); hash = generateHashValue(temp, FILE_HASH_SIZE); - for (mh=mhHashTable[hash]; mh; mh=mh->next) - { - if (Q_stricmp(mh->name, temp) == 0) - { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { + if (Q_stricmp(mh->name, temp) == 0) { return mh->handle; } } @@ -1191,31 +1092,29 @@ Ghoul2 Insert Start return 0; } - if (name[0] == '*') - { // don't create a bad model for a bsp model - if (Q_stricmp(name, "*default.gla")) - { + if (name[0] == '*') { // don't create a bad model for a bsp model + if (Q_stricmp(name, "*default.gla")) { return 0; } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // allocate a new model_t - if ( ( mod = R_AllocModel() ) == NULL ) { - Com_Printf (S_COLOR_YELLOW "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + if ((mod = R_AllocModel()) == NULL) { + Com_Printf(S_COLOR_YELLOW "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); int iLODStart = 0; - if (strstr (name, ".md3")) { - iLODStart = MD3_MAX_LODS-1; // this loads the md3s in reverse so they can be biased + if (strstr(name, ".md3")) { + iLODStart = MD3_MAX_LODS - 1; // this loads the md3s in reverse so they can be biased } mod->numLods = 0; @@ -1224,67 +1123,64 @@ Ghoul2 Insert End // numLoaded = 0; - for ( lod = iLODStart; lod >= 0 ; lod-- ) { + for (lod = iLODStart; lod >= 0; lod--) { char filename[1024]; - strcpy( filename, name ); + strcpy(filename, name); - if ( lod != 0 ) { + if (lod != 0) { char namebuf[80]; - if ( strrchr( filename, '.' ) ) { - *strrchr( filename, '.' ) = 0; + if (strrchr(filename, '.')) { + *strrchr(filename, '.') = 0; } - sprintf( namebuf, "_%d.md3", lod ); - strcat( filename, namebuf ); + sprintf(namebuf, "_%d.md3", lod); + strcat(filename, namebuf); } qboolean bAlreadyCached = qfalse; - if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) - { + if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) { continue; } - //loadmodel = mod; // this seems to be fairly pointless + // loadmodel = mod; // this seems to be fairly pointless // important that from now on we pass 'filename' instead of 'name' to all model load functions, // because 'filename' accounts for any LOD mangling etc so guarantees unique lookups for yet more // internal caching... // ident = *(unsigned *)buf; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(ident); } - switch (ident) - { - // if you add any new types of model load in this switch-case, tell me, - // or copy what I've done with the cache scheme (-ste). - // - case MDXA_IDENT: - loaded = R_LoadMDXA( mod, buf, filename, bAlreadyCached ); - break; + switch (ident) { + // if you add any new types of model load in this switch-case, tell me, + // or copy what I've done with the cache scheme (-ste). + // + case MDXA_IDENT: + loaded = R_LoadMDXA(mod, buf, filename, bAlreadyCached); + break; - case MDXM_IDENT: - loaded = R_LoadMDXM( mod, buf, filename, bAlreadyCached ); - break; + case MDXM_IDENT: + loaded = R_LoadMDXM(mod, buf, filename, bAlreadyCached); + break; - case MD3_IDENT: - loaded = R_LoadMD3( mod, lod, buf, filename, bAlreadyCached ); - break; + case MD3_IDENT: + loaded = R_LoadMD3(mod, lod, buf, filename, bAlreadyCached); + break; - default: - Com_Printf (S_COLOR_YELLOW"RE_RegisterModel: unknown fileid for %s\n", filename); - goto fail; + default: + Com_Printf(S_COLOR_YELLOW "RE_RegisterModel: unknown fileid for %s\n", filename); + goto fail; } - if (!bAlreadyCached){ // important to check!! - ri.FS_FreeFile (buf); + if (!bAlreadyCached) { // important to check!! + ri.FS_FreeFile(buf); } - if ( !loaded ) { - if ( lod == 0 ) { + if (!loaded) { + if (lod == 0) { goto fail; } else { break; @@ -1295,40 +1191,40 @@ Ghoul2 Insert End // if we have a valid model and are biased // so that we won't see any higher detail ones, // stop loading them - if ( lod <= r_lodbias->integer ) { + if (lod <= r_lodbias->integer) { break; } } } - if ( numLoaded ) { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for ( lod-- ; lod >= 0 ; lod-- ) { + for (lod--; lod >= 0; lod--) { mod->numLods++; - mod->md3[lod] = mod->md3[lod+1]; + mod->md3[lod] = mod->md3[lod + 1]; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ #ifdef _DEBUG - if (r_noPrecacheGLA && r_noPrecacheGLA->integer && ident == MDXA_IDENT) - { //I expect this will cause leaks, but I don't care because it's a debugging utility. - return mod->index; - } + if (r_noPrecacheGLA && r_noPrecacheGLA->integer && + ident == MDXA_IDENT) { // I expect this will cause leaks, but I don't care because it's a debugging utility. + return mod->index; + } #endif - RE_InsertModelIntoHash(name, mod); - return mod->index; -/* -Ghoul2 Insert End -*/ + RE_InsertModelIntoHash(name, mod); + return mod->index; + /* + Ghoul2 Insert End + */ } #ifdef _DEBUG else { - Com_Printf (S_COLOR_YELLOW"RE_RegisterModel: couldn't load %s\n", name); + Com_Printf(S_COLOR_YELLOW "RE_RegisterModel: couldn't load %s\n", name); } #endif @@ -1340,37 +1236,32 @@ Ghoul2 Insert End return 0; } - // wrapper function needed to avoid problems with mid-function returns so I can safely use this bool to tell the // z_malloc-fail recovery code whether it's safe to ditch any model caches... // qboolean gbInsideRegisterModel = qfalse; -qhandle_t RE_RegisterModel( const char *name ) -{ +qhandle_t RE_RegisterModel(const char *name) { const qboolean bWhatitwas = gbInsideRegisterModel; - gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! + gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! - qhandle_t q = RE_RegisterModel_Actual( name ); + qhandle_t q = RE_RegisterModel_Actual(name); gbInsideRegisterModel = bWhatitwas; return q; } - - - /* ================= R_LoadMD3 ================= */ -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i, j; - md3Header_t *pinmodel; - md3Surface_t *surf; - int version; - int size; +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, j; + md3Header_t *pinmodel; + md3Surface_t *surf; + int version; + int size; #if 0 //#ifndef _M_IX86 md3Frame_t *frame; @@ -1380,37 +1271,33 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ md3Tag_t *tag; #endif - - pinmodel= (md3Header_t *)buffer; + pinmodel = (md3Header_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = pinmodel->version; - size = pinmodel->ofsEnd; + size = pinmodel->ofsEnd; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MD3_VERSION) { - Com_Printf (S_COLOR_YELLOW "R_LoadMD3: %s has wrong version (%i should be %i)\n", - mod_name, version, MD3_VERSION); + Com_Printf(S_COLOR_YELLOW "R_LoadMD3: %s has wrong version (%i should be %i)\n", mod_name, version, MD3_VERSION); return qfalse; } - mod->type = MOD_MESH; + mod->type = MOD_MESH; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mod->md3[lod] = (md3Header_t *) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); + mod->md3[lod] = (md3Header_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -1418,8 +1305,8 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mod->md3[lod] == buffer ); -// memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing + assert(mod->md3[lod] == buffer); + // memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing LL(mod->md3[lod]->ident); LL(mod->md3[lod]->version); @@ -1432,14 +1319,13 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ LL(mod->md3[lod]->ofsEnd); } - if ( mod->md3[lod]->numFrames < 1 ) { - Com_Printf (S_COLOR_YELLOW "R_LoadMD3: %s has no frames\n", mod_name ); + if (mod->md3[lod]->numFrames < 1) { + Com_Printf(S_COLOR_YELLOW "R_LoadMD3: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not pass Go... } #if 0 //#ifndef _M_IX86 @@ -1471,39 +1357,37 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // swap all the surfaces - surf = (md3Surface_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces ); - for ( i = 0 ; i < mod->md3[lod]->numSurfaces ; i++) { - LL(surf->flags); - LL(surf->numFrames); - LL(surf->numShaders); - LL(surf->numTriangles); - LL(surf->ofsTriangles); - LL(surf->numVerts); - LL(surf->ofsShaders); - LL(surf->ofsSt); - LL(surf->ofsXyzNormals); - LL(surf->ofsEnd); - - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)", - mod_name, SHADER_MAX_VERTEXES, surf->numVerts ); + surf = (md3Surface_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces); + for (i = 0; i < mod->md3[lod]->numSurfaces; i++) { + LL(surf->flags); + LL(surf->numFrames); + LL(surf->numShaders); + LL(surf->numTriangles); + LL(surf->ofsTriangles); + LL(surf->numVerts); + LL(surf->ofsShaders); + LL(surf->ofsSt); + LL(surf->ofsXyzNormals); + LL(surf->ofsEnd); + + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)", - mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles ); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } // change to surface identifier surf->ident = SF_MD3; // lowercase the surface name so skin compares are faster - Q_strlwr( surf->name ); + Q_strlwr(surf->name); // strip off a trailing _1 or _2 // this is a crutch for q3data being a mess - j = strlen( surf->name ); - if ( j > 2 && surf->name[j-2] == '_' ) { - surf->name[j-2] = 0; + j = strlen(surf->name); + if (j > 2 && surf->name[j - 2] == '_') { + surf->name[j - 2] = 0; } #if 0 //#ifndef _M_IX86 // @@ -1538,31 +1422,25 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // find the next surface - surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (md3Surface_t *)((byte *)surf + surf->ofsEnd); } return qtrue; } - //============================================================================= -void R_SVModelInit() -{ - R_ModelInit(); -} +void R_SVModelInit() { R_ModelInit(); } /* =============== R_ModelInit =============== */ -void R_ModelInit( void ) -{ - model_t *mod; +void R_ModelInit(void) { + model_t *mod; - if(!CachedModels) - { + if (!CachedModels) { CachedModels = new CachedModels_t; } @@ -1575,8 +1453,7 @@ void R_ModelInit( void ) } extern void KillTheShaderHashTable(void); -void RE_HunkClearCrap(void) -{ //get your dirty sticky assets off me, you damn dirty hunk! +void RE_HunkClearCrap(void) { // get your dirty sticky assets off me, you damn dirty hunk! KillTheShaderHashTable(); tr.numModels = 0; memset(mhHashTable, 0, sizeof(mhHashTable)); @@ -1584,71 +1461,66 @@ void RE_HunkClearCrap(void) tr.numSkins = 0; } -void R_ModelFree(void) -{ - if(CachedModels) { +void R_ModelFree(void) { + if (CachedModels) { RE_RegisterModels_DeleteAll(); delete CachedModels; CachedModels = NULL; } } - - /* ================ R_Modellist_f ================ */ -void R_Modellist_f( void ) { - int i, j; - model_t *mod; - int total; - int lods; +void R_Modellist_f(void) { + int i, j; + model_t *mod; + int total; + int lods; total = 0; - for ( i = 1 ; i < tr.numModels; i++ ) { + for (i = 1; i < tr.numModels; i++) { mod = tr.models[i]; lods = 1; - for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) { - if ( mod->md3[j] && mod->md3[j] != mod->md3[j-1] ) { + for (j = 1; j < MD3_MAX_LODS; j++) { + if (mod->md3[j] && mod->md3[j] != mod->md3[j - 1]) { lods++; } } - Com_Printf ("%8i : (%i) %s\n",mod->dataSize, lods, mod->name ); + Com_Printf("%8i : (%i) %s\n", mod->dataSize, lods, mod->name); total += mod->dataSize; } - Com_Printf ("%8i : Total models\n", total ); + Com_Printf("%8i : Total models\n", total); -#if 0 // not working right with new hunk +#if 0 // not working right with new hunk if ( tr.world ) { Com_Printf ("\n%8i : %s\n", tr.world->dataSize, tr.world->name ); } #endif } - //============================================================================= - /* ================ R_GetTag ================ */ -static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { - md3Tag_t *tag; - int i; +static md3Tag_t *R_GetTag(md3Header_t *mod, int frame, const char *tagName) { + md3Tag_t *tag; + int i; - if ( frame >= mod->numFrames ) { + if (frame >= mod->numFrames) { // it is possible to have a bad frame while changing models, so don't error frame = mod->numFrames - 1; } tag = (md3Tag_t *)((byte *)mod + mod->ofsTags) + frame * mod->numTags; - for ( i = 0 ; i < mod->numTags ; i++, tag++ ) { - if ( !strcmp( tag->name, tagName ) ) { - return tag; // found it + for (i = 0; i < mod->numTags; i++, tag++) { + if (!strcmp(tag->name, tagName)) { + return tag; // found it } } @@ -1660,74 +1532,70 @@ static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { R_LerpTag ================ */ -int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, - float frac, const char *tagName ) { - md3Tag_t *start, *end; - int i; - float frontLerp, backLerp; - model_t *model; - - model = R_GetModelByHandle( handle ); - if ( !model->md3[0] ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); +int R_LerpTag(orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, float frac, const char *tagName) { + md3Tag_t *start, *end; + int i; + float frontLerp, backLerp; + model_t *model; + + model = R_GetModelByHandle(handle); + if (!model->md3[0]) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } - start = R_GetTag( model->md3[0], startFrame, tagName ); - end = R_GetTag( model->md3[0], endFrame, tagName ); - if ( !start || !end ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + start = R_GetTag(model->md3[0], startFrame, tagName); + end = R_GetTag(model->md3[0], endFrame, tagName); + if (!start || !end) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } frontLerp = frac; backLerp = 1.0f - frac; - for ( i = 0 ; i < 3 ; i++ ) { - tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; - tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; - tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; - tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; + for (i = 0; i < 3; i++) { + tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; + tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; + tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; + tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; } - VectorNormalize( tag->axis[0] ); - VectorNormalize( tag->axis[1] ); - VectorNormalize( tag->axis[2] ); + VectorNormalize(tag->axis[0]); + VectorNormalize(tag->axis[1]); + VectorNormalize(tag->axis[2]); return qtrue; } - /* ==================== R_ModelBounds ==================== */ -void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) { - model_t *model; - md3Header_t *header; - md3Frame_t *frame; +void R_ModelBounds(qhandle_t handle, vec3_t mins, vec3_t maxs) { + model_t *model; + md3Header_t *header; + md3Frame_t *frame; - model = R_GetModelByHandle( handle ); + model = R_GetModelByHandle(handle); - if ( model->bmodel ) { - VectorCopy( model->bmodel->bounds[0], mins ); - VectorCopy( model->bmodel->bounds[1], maxs ); + if (model->bmodel) { + VectorCopy(model->bmodel->bounds[0], mins); + VectorCopy(model->bmodel->bounds[1], maxs); return; } - if ( !model->md3[0] ) { - VectorClear( mins ); - VectorClear( maxs ); + if (!model->md3[0]) { + VectorClear(mins); + VectorClear(maxs); return; } header = model->md3[0]; - frame = (md3Frame_t *)( (byte *)header + header->ofsFrames ); + frame = (md3Frame_t *)((byte *)header + header->ofsFrames); - VectorCopy( frame->bounds[0], mins ); - VectorCopy( frame->bounds[1], maxs ); + VectorCopy(frame->bounds[0], mins); + VectorCopy(frame->bounds[1], maxs); } - - diff --git a/codemp/rd-dedicated/tr_shader.cpp b/codemp/rd-dedicated/tr_shader.cpp index d8c49a5911..3cc7f1e40e 100644 --- a/codemp/rd-dedicated/tr_shader.cpp +++ b/codemp/rd-dedicated/tr_shader.cpp @@ -29,77 +29,41 @@ static char *s_shaderText; // the shader is parsed into these global variables, then copied into // dynamically allocated memory if it is valid. -static shaderStage_t stages[MAX_SHADER_STAGES]; -static shader_t shader; -static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; +static shaderStage_t stages[MAX_SHADER_STAGES]; +static shader_t shader; +static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; -#define FILE_HASH_SIZE 1024 -static shader_t* hashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 +static shader_t *hashTable[FILE_HASH_SIZE]; -#define MAX_SHADERTEXT_HASH 2048 -static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = { 0 }; +#define MAX_SHADERTEXT_HASH 2048 +static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = {0}; -void KillTheShaderHashTable(void) -{ - memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); -} +void KillTheShaderHashTable(void) { memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); } -qboolean ShaderHashTableExists(void) -{ - if (shaderTextHashTable[0]) - { +qboolean ShaderHashTableExists(void) { + if (shaderTextHashTable[0]) { return qtrue; } return qfalse; } -const int lightmapsNone[MAXLIGHTMAPS] = -{ - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE -}; +const int lightmapsNone[MAXLIGHTMAPS] = {LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE}; -const int lightmaps2d[MAXLIGHTMAPS] = -{ - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D -}; +const int lightmaps2d[MAXLIGHTMAPS] = {LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D}; -const int lightmapsVertex[MAXLIGHTMAPS] = -{ - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX -}; +const int lightmapsVertex[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX}; -const int lightmapsFullBright[MAXLIGHTMAPS] = -{ - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE -}; +const int lightmapsFullBright[MAXLIGHTMAPS] = {LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE}; -const byte stylesDefault[MAXLIGHTMAPS] = -{ - LS_NORMAL, - LS_LSNONE, - LS_LSNONE, - LS_LSNONE -}; +const byte stylesDefault[MAXLIGHTMAPS] = {LS_NORMAL, LS_LSNONE, LS_LSNONE, LS_LSNONE}; -static void ClearGlobalShader(void) -{ - int i; +static void ClearGlobalShader(void) { + int i; - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; } @@ -112,56 +76,59 @@ static void ClearGlobalShader(void) return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); - hash &= (size-1); + hash &= (size - 1); return hash; } void R_RemapShader(const char *shaderName, const char *newShaderName, const char *timeOffset) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh, *sh2; - qhandle_t h; + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh, *sh2; + qhandle_t h; - sh = R_FindShaderByName( shaderName ); + sh = R_FindShaderByName(shaderName); if (sh == NULL || sh == tr.defaultShader) { h = RE_RegisterShaderLightMap(shaderName, lightmapsNone, stylesDefault); sh = R_GetShaderByHandle(h); } if (sh == NULL || sh == tr.defaultShader) { - Com_Printf (S_COLOR_YELLOW "WARNING: R_RemapShader: shader %s not found\n", shaderName ); + Com_Printf(S_COLOR_YELLOW "WARNING: R_RemapShader: shader %s not found\n", shaderName); return; } - sh2 = R_FindShaderByName( newShaderName ); + sh2 = R_FindShaderByName(newShaderName); if (sh2 == NULL || sh2 == tr.defaultShader) { h = RE_RegisterShaderLightMap(newShaderName, lightmapsNone, stylesDefault); sh2 = R_GetShaderByHandle(h); } if (sh2 == NULL || sh2 == tr.defaultShader) { - Com_Printf (S_COLOR_YELLOW "WARNING: R_RemapShader: new shader %s not found\n", newShaderName ); + Com_Printf(S_COLOR_YELLOW "WARNING: R_RemapShader: new shader %s not found\n", newShaderName); return; } // remap all the shaders with the given name // even tho they might have different lightmaps - COM_StripExtension( shaderName, strippedName, sizeof( strippedName ) ); + COM_StripExtension(shaderName, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); for (sh = hashTable[hash]; sh; sh = sh->next) { if (Q_stricmp(sh->name, strippedName) == 0) { @@ -182,110 +149,82 @@ void R_RemapShader(const char *shaderName, const char *newShaderName, const char ParseVector =============== */ -qboolean ParseVector( const char **text, int count, float *v ) { - char *token; - int i; +qboolean ParseVector(const char **text, int count, float *v) { + char *token; + int i; // FIXME: spaces are currently required after parens, should change parseext... - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "(" ) ) { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "(")) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } - for ( i = 0 ; i < count ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { - Com_Printf (S_COLOR_YELLOW "WARNING: missing vector element in shader '%s'\n", shader.name ); + for (i = 0; i < count; i++) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing vector element in shader '%s'\n", shader.name); return qfalse; } - v[i] = atof( token ); + v[i] = atof(token); } - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, ")" ) ) { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, ")")) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } return qtrue; } - /* =============== NameToAFunc =============== */ -static unsigned NameToAFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "GT0" ) ) - { +static unsigned NameToAFunc(const char *funcname) { + if (!Q_stricmp(funcname, "GT0")) { return GLS_ATEST_GT_0; - } - else if ( !Q_stricmp( funcname, "LT128" ) ) - { + } else if (!Q_stricmp(funcname, "LT128")) { return GLS_ATEST_LT_80; - } - else if ( !Q_stricmp( funcname, "GE128" ) ) - { + } else if (!Q_stricmp(funcname, "GE128")) { return GLS_ATEST_GE_80; - } - else if ( !Q_stricmp( funcname, "GE192" ) ) - { + } else if (!Q_stricmp(funcname, "GE192")) { return GLS_ATEST_GE_C0; } - Com_Printf (S_COLOR_YELLOW "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name); return 0; } - /* =============== NameToSrcBlendMode =============== */ -static int NameToSrcBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToSrcBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_SRCBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_SRCBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_COLOR")) { return GLS_SRCBLEND_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_COLOR")) { return GLS_SRCBLEND_ONE_MINUS_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_SRCBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_SRCBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA_SATURATE")) { return GLS_SRCBLEND_ALPHA_SATURATE; } - Com_Printf (S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_SRCBLEND_ONE; } @@ -294,42 +233,26 @@ static int NameToSrcBlendMode( const char *name ) NameToDstBlendMode =============== */ -static int NameToDstBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToDstBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_DSTBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_DSTBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_DSTBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_DSTBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_COLOR")) { return GLS_DSTBLEND_SRC_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_COLOR")) { return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; } - Com_Printf (S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_DSTBLEND_ONE; } @@ -338,325 +261,271 @@ static int NameToDstBlendMode( const char *name ) NameToGenFunc =============== */ -static genFunc_t NameToGenFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "sin" ) ) - { +static genFunc_t NameToGenFunc(const char *funcname) { + if (!Q_stricmp(funcname, "sin")) { return GF_SIN; - } - else if ( !Q_stricmp( funcname, "square" ) ) - { + } else if (!Q_stricmp(funcname, "square")) { return GF_SQUARE; - } - else if ( !Q_stricmp( funcname, "triangle" ) ) - { + } else if (!Q_stricmp(funcname, "triangle")) { return GF_TRIANGLE; - } - else if ( !Q_stricmp( funcname, "sawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "sawtooth")) { return GF_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "inversesawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "inversesawtooth")) { return GF_INVERSE_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "noise" ) ) - { + } else if (!Q_stricmp(funcname, "noise")) { return GF_NOISE; - } - else if ( !Q_stricmp( funcname, "random" ) ) - { + } else if (!Q_stricmp(funcname, "random")) { return GF_RAND; } - Com_Printf (S_COLOR_YELLOW "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name); return GF_SIN; } - /* =================== ParseWaveForm =================== */ -static void ParseWaveForm( const char **text, waveForm_t *wave ) -{ +static void ParseWaveForm(const char **text, waveForm_t *wave) { char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->func = NameToGenFunc( token ); + wave->func = NameToGenFunc(token); // BASE, AMP, PHASE, FREQ - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->base = atof( token ); + wave->base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->amplitude = atof( token ); + wave->amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->phase = atof( token ); + wave->phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->frequency = atof( token ); + wave->frequency = atof(token); } - /* =================== ParseTexMod =================== */ -static void ParseTexMod( const char *_text, shaderStage_t *stage ) -{ +static void ParseTexMod(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; texModInfo_t *tmi; - if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) { - Com_Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name ); + if (stage->bundle[0].numTexMods == TR_MAX_TEXMODS) { + Com_Error(ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name); return; } tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods]; stage->bundle[0].numTexMods++; - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); // // turb // - if ( !Q_stricmp( token, "turb" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "turb")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.base = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.amplitude = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.phase = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_TURBULENT; } // // scale // - else if ( !Q_stricmp( token, "scale" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scale unioned + tmi->translate[0] = atof(token); // scale unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scale unioned + tmi->translate[1] = atof(token); // scale unioned tmi->type = TMOD_SCALE; } // // scroll // - else if ( !Q_stricmp( token, "scroll" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scroll")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scroll unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + tmi->translate[0] = atof(token); // scroll unioned + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scroll unioned + tmi->translate[1] = atof(token); // scroll unioned tmi->type = TMOD_SCROLL; } // // stretch // - else if ( !Q_stricmp( token, "stretch" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "stretch")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.func = NameToGenFunc( token ); + tmi->wave.func = NameToGenFunc(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); + tmi->wave.base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); + tmi->wave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); + tmi->wave.phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_STRETCH; } // // transform // - else if ( !Q_stricmp( token, "transform" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "transform")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][0] = atof( token ); + tmi->matrix[0][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][1] = atof( token ); + tmi->matrix[0][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][0] = atof( token ); + tmi->matrix[1][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][1] = atof( token ); + tmi->matrix[1][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); + tmi->translate[0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); + tmi->translate[1] = atof(token); tmi->type = TMOD_TRANSFORM; } // // rotate // - else if ( !Q_stricmp( token, "rotate" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rotate")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name); return; } - tmi->translate[0]= atof( token ); //rotateSpeed unioned + tmi->translate[0] = atof(token); // rotateSpeed unioned tmi->type = TMOD_ROTATE; } // // entityTranslate // - else if ( !Q_stricmp( token, "entityTranslate" ) ) - { + else if (!Q_stricmp(token, "entityTranslate")) { tmi->type = TMOD_ENTITY_TRANSLATE; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name); } } - - /* /////===== Part of the VERTIGON system =====///// =================== @@ -667,113 +536,93 @@ ParseSurfaceSprites // // NOTE: This parsing function used to be 12 pages long and very complex. The new version of surfacesprites // utilizes optional parameters parsed in ParseSurfaceSpriteOptional. -static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; float width, height, density, fadedist; - int sstype=SURFSPRITE_NONE; + int sstype = SURFSPRITE_NONE; // // spritetype // - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - if (!Q_stricmp(token, "vertical")) - { + if (!Q_stricmp(token, "vertical")) { sstype = SURFSPRITE_VERTICAL; - } - else if (!Q_stricmp(token, "oriented")) - { + } else if (!Q_stricmp(token, "oriented")) { sstype = SURFSPRITE_ORIENTED; - } - else if (!Q_stricmp(token, "effect")) - { + } else if (!Q_stricmp(token, "effect")) { sstype = SURFSPRITE_EFFECT; - } - else if (!Q_stricmp(token, "flattened")) - { + } else if (!Q_stricmp(token, "flattened")) { sstype = SURFSPRITE_FLATTENED; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", shader.name); return; } // // width // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - width=atof(token); - if (width <= 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", shader.name ); + width = atof(token); + if (width <= 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", shader.name); return; } // // height // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - height=atof(token); - if (height <= 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", shader.name ); + height = atof(token); + if (height <= 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", shader.name); return; } // // density // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - density=atof(token); - if (density <= 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", shader.name ); + density = atof(token); + if (density <= 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", shader.name); return; } // // fadedist // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - fadedist=atof(token); - if (fadedist < 32) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name ); + fadedist = atof(token); + if (fadedist < 32) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name); return; } - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // These are all set by the command lines. @@ -784,7 +633,7 @@ static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) stage->ss->fadeDist = fadedist; // These are defaults that can be overwritten. - stage->ss->fadeMax = fadedist*1.33; + stage->ss->fadeMax = fadedist * 1.33; stage->ss->fadeScale = 0.0; stage->ss->wind = 0.0; stage->ss->windIdle = 0.0; @@ -796,16 +645,13 @@ static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) stage->ss->vertSkew = 0.0f; // These are effect parameters that need defaults nonetheless. - stage->ss->fxDuration = 1000; // 1 second + stage->ss->fxDuration = 1000; // 1 second stage->ss->fxGrow[0] = 0.0; stage->ss->fxGrow[1] = 0.0; stage->ss->fxAlphaStart = 1.0; stage->ss->fxAlphaEnd = 0.0; } - - - /* /////===== Part of the VERTIGON system =====///// =========================== @@ -829,150 +675,129 @@ ParseSurfaceSpritesOptional // // Optional parameters that will override the defaults set in the surfacesprites command above. // -static void ParseSurfaceSpritesOptional( const char *param, const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSpritesOptional(const char *param, const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; - float value; + float value; - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // // fademax // - if (!Q_stricmp(param, "ssFademax")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFademax")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= stage->ss->fadeDist) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, shader.name ); + if (value <= stage->ss->fadeDist) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, + shader.name); return; } - stage->ss->fadeMax=value; + stage->ss->fadeMax = value; return; } // // fadescale // - if (!Q_stricmp(param, "ssFadescale")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFadescale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name); return; } value = atof(token); - stage->ss->fadeScale=value; + stage->ss->fadeScale = value; return; } // // variance // - if (!Q_stricmp(param, "ssVariance")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVariance")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name ); + if (value < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name); return; } - stage->ss->variance[0]=value; + stage->ss->variance[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name ); + if (value < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name); return; } - stage->ss->variance[1]=value; + stage->ss->variance[1] = value; return; } // // hangdown // - if (!Q_stricmp(param, "ssHangdown")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - Com_Printf (S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssHangdown")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + Com_Printf(S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_DOWN; + stage->ss->facing = SURFSPRITE_FACING_DOWN; return; } // // anyangle // - if (!Q_stricmp(param, "ssAnyangle")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - Com_Printf (S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssAnyangle")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + Com_Printf(S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_ANY; + stage->ss->facing = SURFSPRITE_FACING_ANY; return; } // // faceup // - if (!Q_stricmp(param, "ssFaceup")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - Com_Printf (S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFaceup")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + Com_Printf(S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_UP; + stage->ss->facing = SURFSPRITE_FACING_UP; return; } // // wind // - if (!Q_stricmp(param, "ssWind")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWind")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name ); + if (value < 0.0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name); return; } - stage->ss->wind=value; - if (stage->ss->windIdle <= 0) - { // Also override the windidle, it usually is the same as wind + stage->ss->wind = value; + if (stage->ss->windIdle <= 0) { // Also override the windidle, it usually is the same as wind stage->ss->windIdle = value; } return; @@ -981,144 +806,123 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // windidle // - if (!Q_stricmp(param, "ssWindidle")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWindidle")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name ); + if (value < 0.0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name); return; } - stage->ss->windIdle=value; + stage->ss->windIdle = value; return; } // // vertskew // - if (!Q_stricmp(param, "ssVertskew")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVertskew")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name ); + if (value < 0.0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name); return; } - stage->ss->vertSkew=value; + stage->ss->vertSkew = value; return; } // // fxduration // - if (!Q_stricmp(param, "ssFXDuration")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXDuration")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name ); + if (value <= 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name); return; } - stage->ss->fxDuration=value; + stage->ss->fxDuration = value; return; } // // fxgrow // - if (!Q_stricmp(param, "ssFXGrow")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXGrow")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name ); + if (value < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[0]=value; + stage->ss->fxGrow[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name ); + if (value < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[1]=value; + stage->ss->fxGrow[1] = value; return; } // // fxalpharange // - if (!Q_stricmp(param, "ssFXAlphaRange")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXAlphaRange")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaStart=value; + stage->ss->fxAlphaStart = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaEnd=value; + stage->ss->fxAlphaEnd = value; return; } // // fxweather // - if (!Q_stricmp(param, "ssFXWeather")) - { - if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) - { - Com_Printf (S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXWeather")) { + if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) { + Com_Printf(S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name); return; } stage->ss->surfaceSpriteType = SURFSPRITE_WEATHERFX; @@ -1128,72 +932,57 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // invalid ss command. // - Com_Printf (S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name); return; } - /* =================== ParseStage =================== */ -static qboolean ParseStage( shaderStage_t *stage, const char **text ) -{ +static qboolean ParseStage(shaderStage_t *stage, const char **text) { char *token; int depthMaskBits = GLS_DEPTHMASK_TRUE, blendSrcBits = 0, blendDstBits = 0, atestBits = 0, depthFuncBits = 0; qboolean depthMaskExplicit = qfalse; stage->active = qtrue; - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: no matching '}' found\n" ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: no matching '}' found\n"); return qfalse; } - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // // map // - else if ( !Q_stricmp( token, "map" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "map")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "$whiteimage" ) ) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[0].image = tr.whiteImage; continue; - } - else if ( !Q_stricmp( token, "$lightmap" ) ) - { + } else if (!Q_stricmp(token, "$lightmap")) { stage->bundle[0].isLightmap = qtrue; - if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) - { + if (shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps) { #ifndef FINAL_BUILD - Com_Printf(S_COLOR_RED"Lightmap requested but none available for shader %s\n", shader.name); + Com_Printf(S_COLOR_RED "Lightmap requested but none available for shader %s\n", shader.name); #endif stage->bundle[0].image = tr.whiteImage; - } - else - { + } else { stage->bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; } continue; - } - else - { + } else { stage->bundle[0].image = NULL; return qfalse; } @@ -1201,12 +990,10 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // clampmap // - else if ( !Q_stricmp( token, "clampmap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "clampmap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->bundle[0].image = NULL; @@ -1215,52 +1002,47 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // animMap .... // - else if ( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampanimMap" ) || !Q_stricmp( token, "oneshotanimMap" )) - { - #define MAX_IMAGE_ANIMATIONS 32 + else if (!Q_stricmp(token, "animMap") || !Q_stricmp(token, "clampanimMap") || !Q_stricmp(token, "oneshotanimMap")) { +#define MAX_IMAGE_ANIMATIONS 32 image_t *images[MAX_IMAGE_ANIMATIONS]; - bool bClamp = !Q_stricmp( token, "clampanimMap" ); - bool oneShot = !Q_stricmp( token, "oneshotanimMap" ); + bool bClamp = !Q_stricmp(token, "clampanimMap"); + bool oneShot = !Q_stricmp(token, "oneshotanimMap"); - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap":"clampanimMap"), shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap" : "clampanimMap"), shader.name); return qfalse; } - stage->bundle[0].imageAnimationSpeed = atof( token ); + stage->bundle[0].imageAnimationSpeed = atof(token); stage->bundle[0].oneShotAnimMap = oneShot; // parse up to MAX_IMAGE_ANIMATIONS animations - while ( 1 ) { - int num; + while (1) { + int num; - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { break; } num = stage->bundle[0].numImageAnimations; - if ( num < MAX_IMAGE_ANIMATIONS ) { + if (num < MAX_IMAGE_ANIMATIONS) { stage->bundle[0].image = NULL; return qfalse; } } // Copy image ptrs into an array of ptrs - stage->bundle[0].image = (image_t*) Hunk_Alloc( stage->bundle[0].numImageAnimations * sizeof( image_t* ), h_low ); - memcpy( stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof( image_t* ) ); - } - else if ( !Q_stricmp( token, "videoMap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name ); + stage->bundle[0].image = (image_t *)Hunk_Alloc(stage->bundle[0].numImageAnimations * sizeof(image_t *), h_low); + memcpy(stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof(image_t *)); + } else if (!Q_stricmp(token, "videoMap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->bundle[0].videoMapHandle = -1; if (stage->bundle[0].videoMapHandle != -1) { stage->bundle[0].isVideoMap = qtrue; - assert (stage->bundle[0].videoMapHandlebundle[0].videoMapHandle < NUM_SCRATCH_IMAGES); stage->bundle[0].image = tr.scratchImage[stage->bundle[0].videoMapHandle]; } } @@ -1268,320 +1050,235 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // alphafunc // - else if ( !Q_stricmp( token, "alphaFunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaFunc")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name); return qfalse; } - atestBits = NameToAFunc( token ); + atestBits = NameToAFunc(token); } // // depthFunc // - else if ( !Q_stricmp( token, "depthfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "depthfunc")) { + token = COM_ParseExt(text, qfalse); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name ); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "lequal" ) ) - { + if (!Q_stricmp(token, "lequal")) { depthFuncBits = 0; - } - else if ( !Q_stricmp( token, "equal" ) ) - { + } else if (!Q_stricmp(token, "equal")) { depthFuncBits = GLS_DEPTHFUNC_EQUAL; - } - else if ( !Q_stricmp( token, "disable" ) ) - { + } else if (!Q_stricmp(token, "disable")) { depthFuncBits = GLS_DEPTHTEST_DISABLE; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name); continue; } } // // detail // - else if ( !Q_stricmp( token, "detail" ) ) - { + else if (!Q_stricmp(token, "detail")) { stage->isDetail = qtrue; } // // blendfunc // or blendfunc // - else if ( !Q_stricmp( token, "blendfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "blendfunc")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } // check for "simple" blends first - if ( !Q_stricmp( token, "add" ) ) { + if (!Q_stricmp(token, "add")) { blendSrcBits = GLS_SRCBLEND_ONE; blendDstBits = GLS_DSTBLEND_ONE; - } else if ( !Q_stricmp( token, "filter" ) ) { + } else if (!Q_stricmp(token, "filter")) { blendSrcBits = GLS_SRCBLEND_DST_COLOR; blendDstBits = GLS_DSTBLEND_ZERO; - } else if ( !Q_stricmp( token, "blend" ) ) { + } else if (!Q_stricmp(token, "blend")) { blendSrcBits = GLS_SRCBLEND_SRC_ALPHA; blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } else { // complex double blends - blendSrcBits = NameToSrcBlendMode( token ); + blendSrcBits = NameToSrcBlendMode(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } - blendDstBits = NameToDstBlendMode( token ); + blendDstBits = NameToDstBlendMode(token); } // clear depth mask for blended surfaces - if ( !depthMaskExplicit ) - { + if (!depthMaskExplicit) { depthMaskBits = 0; } } // // rgbGen // - else if ( !Q_stricmp( token, "rgbGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rgbGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->rgbWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->rgbWave); stage->rgbGen = CGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - vec3_t color; + } else if (!Q_stricmp(token, "const")) { + vec3_t color; - ParseVector( text, 3, color ); + ParseVector(text, 3, color); stage->constantColor[0] = 255 * color[0]; stage->constantColor[1] = 255 * color[1]; stage->constantColor[2] = 255 * color[2]; stage->rgbGen = CGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->rgbGen = CGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "identityLighting" ) ) - { + } else if (!Q_stricmp(token, "identityLighting")) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->rgbGen = CGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->rgbGen = CGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->rgbGen = CGEN_VERTEX; - if ( stage->alphaGen == 0 ) { + if (stage->alphaGen == 0) { stage->alphaGen = AGEN_VERTEX; } - } - else if ( !Q_stricmp( token, "exactVertex" ) ) - { + } else if (!Q_stricmp(token, "exactVertex")) { stage->rgbGen = CGEN_EXACT_VERTEX; - } - else if ( !Q_stricmp( token, "lightingDiffuse" ) ) - { + } else if (!Q_stricmp(token, "lightingDiffuse")) { stage->rgbGen = CGEN_LIGHTING_DIFFUSE; - } - else if ( !Q_stricmp( token, "lightingDiffuseEntity" ) ) - { - if (shader.lightmapIndex[0] != LIGHTMAP_NONE) - { - Com_Printf( S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "lightingDiffuseEntity")) { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) { + Com_Printf(S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->rgbGen = CGEN_ONE_MINUS_VERTEX; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // alphaGen // - else if ( !Q_stricmp( token, "alphaGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->alphaWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->alphaWave); stage->alphaGen = AGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - token = COM_ParseExt( text, qfalse ); - stage->constantColor[3] = 255 * atof( token ); + } else if (!Q_stricmp(token, "const")) { + token = COM_ParseExt(text, qfalse); + stage->constantColor[3] = 255 * atof(token); stage->alphaGen = AGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->alphaGen = AGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->alphaGen = AGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->alphaGen = AGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->alphaGen = AGEN_VERTEX; - } - else if ( !Q_stricmp( token, "lightingSpecular" ) ) - { + } else if (!Q_stricmp(token, "lightingSpecular")) { stage->alphaGen = AGEN_LIGHTING_SPECULAR; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->alphaGen = AGEN_ONE_MINUS_VERTEX; - } - else if ( !Q_stricmp( token, "dot" ) ) - { + } else if (!Q_stricmp(token, "dot")) { stage->alphaGen = AGEN_DOT; - } - else if ( !Q_stricmp( token, "oneMinusDot" ) ) - { + } else if (!Q_stricmp(token, "oneMinusDot")) { stage->alphaGen = AGEN_ONE_MINUS_DOT; - } - else if ( !Q_stricmp( token, "portal" ) ) - { + } else if (!Q_stricmp(token, "portal")) { stage->alphaGen = AGEN_PORTAL; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { shader.portalRange = 256; - Com_Printf (S_COLOR_YELLOW "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name ); - } - else - { - shader.portalRange = atof( token ); + Com_Printf(S_COLOR_YELLOW "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name); + } else { + shader.portalRange = atof(token); } - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // tcGen // - else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing texgen parm in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "texgen") || !Q_stricmp(token, "tcGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing texgen parm in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "environment" ) ) - { + if (!Q_stricmp(token, "environment")) { stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED; - } - else if ( !Q_stricmp( token, "lightmap" ) ) - { + } else if (!Q_stricmp(token, "lightmap")) { stage->bundle[0].tcGen = TCGEN_LIGHTMAP; - } - else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) ) - { + } else if (!Q_stricmp(token, "texture") || !Q_stricmp(token, "base")) { stage->bundle[0].tcGen = TCGEN_TEXTURE; - } - else if ( !Q_stricmp( token, "vector" ) ) - { - stage->bundle[0].tcGenVectors = ( vec3_t *) Hunk_Alloc( 2 * sizeof( vec3_t ), h_low ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] ); + } else if (!Q_stricmp(token, "vector")) { + stage->bundle[0].tcGenVectors = (vec3_t *)Hunk_Alloc(2 * sizeof(vec3_t), h_low); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[0]); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[1]); stage->bundle[0].tcGen = TCGEN_VECTOR; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown texgen parm in shader '%s'\n", shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown texgen parm in shader '%s'\n", shader.name); } } // // tcMod <...> // - else if ( !Q_stricmp( token, "tcMod" ) ) - { + else if (!Q_stricmp(token, "tcMod")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseTexMod( buffer, stage ); + ParseTexMod(buffer, stage); continue; } // // depthmask // - else if ( !Q_stricmp( token, "depthwrite" ) ) - { + else if (!Q_stricmp(token, "depthwrite")) { depthMaskBits = GLS_DEPTHMASK_TRUE; depthMaskExplicit = qtrue; continue; } // If this stage has glow... GLOWXXX - else if ( Q_stricmp( token, "glow" ) == 0 ) - { + else if (Q_stricmp(token, "glow") == 0) { stage->glow = true; continue; @@ -1589,20 +1286,18 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // surfaceSprites ... // - else if ( !Q_stricmp( token, "surfaceSprites" ) ) - { + else if (!Q_stricmp(token, "surfaceSprites")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSprites( buffer, stage ); + ParseSurfaceSprites(buffer, stage); continue; } @@ -1619,28 +1314,25 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // ssGrow // ssWeather // - else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS + else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS { char buffer[1024] = ""; char param[128]; - strcpy(param,token); + strcpy(param, token); - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSpritesOptional( param, buffer, stage ); + ParseSurfaceSpritesOptional(param, buffer, stage); continue; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1648,31 +1340,26 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // if cgen isn't explicitly specified, use either identity or identitylighting // - if ( stage->rgbGen == CGEN_BAD ) { - if ( //blendSrcBits == 0 || - blendSrcBits == GLS_SRCBLEND_ONE || - blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) { + if (stage->rgbGen == CGEN_BAD) { + if ( // blendSrcBits == 0 || + blendSrcBits == GLS_SRCBLEND_ONE || blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; } else { stage->rgbGen = CGEN_IDENTITY; } } - // // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending // - if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && - ( blendDstBits == GLS_DSTBLEND_ZERO ) ) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ZERO)) { blendDstBits = blendSrcBits = 0; depthMaskBits = GLS_DEPTHMASK_TRUE; } // decide which agens we can skip - if ( stage->alphaGen == AGEN_IDENTITY ) { - if ( stage->rgbGen == CGEN_IDENTITY - || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) { + if (stage->alphaGen == AGEN_IDENTITY) { + if (stage->rgbGen == CGEN_IDENTITY || stage->rgbGen == CGEN_LIGHTING_DIFFUSE) { stage->alphaGen = AGEN_SKIP; } } @@ -1680,10 +1367,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // compute state bits // - stage->stateBits = depthMaskBits | - blendSrcBits | blendDstBits | - atestBits | - depthFuncBits; + stage->stateBits = depthMaskBits | blendSrcBits | blendDstBits | atestBits | depthFuncBits; return qtrue; } @@ -1702,149 +1386,136 @@ deformVertexes autoSprite2 deformVertexes text[0-7] =============== */ -static void ParseDeform( const char **text ) { - char *token; - deformStage_t *ds; +static void ParseDeform(const char **text) { + char *token; + deformStage_t *ds; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deform parm in shader '%s'\n", shader.name); return; } - if ( shader.numDeforms == MAX_SHADER_DEFORMS ) { - Com_Printf (S_COLOR_YELLOW "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name ); + if (shader.numDeforms == MAX_SHADER_DEFORMS) { + Com_Printf(S_COLOR_YELLOW "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name); return; } - shader.deforms[ shader.numDeforms ] = (deformStage_t *)Hunk_Alloc( sizeof( deformStage_t ), h_low ); + shader.deforms[shader.numDeforms] = (deformStage_t *)Hunk_Alloc(sizeof(deformStage_t), h_low); - ds = shader.deforms[ shader.numDeforms ]; + ds = shader.deforms[shader.numDeforms]; shader.numDeforms++; - if ( !Q_stricmp( token, "projectionShadow" ) ) { + if (!Q_stricmp(token, "projectionShadow")) { ds->deformation = DEFORM_PROJECTION_SHADOW; return; } - if ( !Q_stricmp( token, "autosprite" ) ) { + if (!Q_stricmp(token, "autosprite")) { ds->deformation = DEFORM_AUTOSPRITE; return; } - if ( !Q_stricmp( token, "autosprite2" ) ) { + if (!Q_stricmp(token, "autosprite2")) { ds->deformation = DEFORM_AUTOSPRITE2; return; } - if ( !Q_stricmpn( token, "text", 4 ) ) { - int n; + if (!Q_stricmpn(token, "text", 4)) { + int n; n = token[4] - '0'; - if ( n < 0 || n > 7 ) { + if (n < 0 || n > 7) { n = 0; } ds->deformation = (deform_t)(DEFORM_TEXT0 + n); return; } - if ( !Q_stricmp( token, "bulge" ) ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "bulge")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeWidth = atof( token ); + ds->bulgeWidth = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeHeight = atof( token ); + ds->bulgeHeight = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeSpeed = atof( token ); + ds->bulgeSpeed = atof(token); ds->deformation = DEFORM_BULGE; return; } - if ( !Q_stricmp( token, "wave" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "wave")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - if ( atof( token ) != 0 ) - { - ds->deformationSpread = 1.0f / atof( token ); - } - else - { + if (atof(token) != 0) { + ds->deformationSpread = 1.0f / atof(token); + } else { ds->deformationSpread = 100.0f; - Com_Printf (S_COLOR_YELLOW "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_WAVE; return; } - if ( !Q_stricmp( token, "normal" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "normal")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.amplitude = atof( token ); + ds->deformationWave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.frequency = atof( token ); + ds->deformationWave.frequency = atof(token); ds->deformation = DEFORM_NORMALS; return; } - if ( !Q_stricmp( token, "move" ) ) { - int i; + if (!Q_stricmp(token, "move")) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - Com_Printf (S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + for (i = 0; i < 3; i++) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->moveVector[i] = atof( token ); + ds->moveVector[i] = atof(token); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_MOVE; return; } - Com_Printf (S_COLOR_YELLOW "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name ); + Com_Printf(S_COLOR_YELLOW "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name); } - /* =============== ParseSkyParms @@ -1852,91 +1523,89 @@ ParseSkyParms skyParms =============== */ -static void ParseSkyParms( const char **text ) { - char *token; - const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; - char pathname[MAX_QPATH]; - int i; +static void ParseSkyParms(const char **text) { + char *token; + const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; + char pathname[MAX_QPATH]; + int i; - shader.sky = (skyParms_t *)Hunk_Alloc( sizeof( skyParms_t ), h_low ); + shader.sky = (skyParms_t *)Hunk_Alloc(sizeof(skyParms_t), h_low); // outerbox - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - Com_Printf (S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name); return; } - if ( strcmp( token, "-" ) ) { - for (i=0 ; i<6 ; i++) { - Com_sprintf( pathname, sizeof(pathname), "%s_%s", token, suf[i] ); + if (strcmp(token, "-")) { + for (i = 0; i < 6; i++) { + Com_sprintf(pathname, sizeof(pathname), "%s_%s", token, suf[i]); shader.sky->outerbox[i] = NULL; } } // cloudheight - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - Com_Printf (S_COLOR_YELLOW "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name); return; } - shader.sky->cloudHeight = atof( token ); - if ( !shader.sky->cloudHeight ) { + shader.sky->cloudHeight = atof(token); + if (!shader.sky->cloudHeight) { shader.sky->cloudHeight = 512; } // innerbox - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "-" ) ) { - Com_Printf (S_COLOR_YELLOW "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "-")) { + Com_Printf(S_COLOR_YELLOW "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); } } - /* ================= ParseSort ================= */ -static void ParseSort( const char **text ) { - char *token; +static void ParseSort(const char **text) { + char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - Com_Printf (S_COLOR_YELLOW "WARNING: missing sort parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing sort parameter in shader '%s'\n", shader.name); return; } - if ( !Q_stricmp( token, "portal" ) ) { + if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; - } else if ( !Q_stricmp( token, "sky" ) ) { + } else if (!Q_stricmp(token, "sky")) { shader.sort = SS_ENVIRONMENT; - } else if ( !Q_stricmp( token, "opaque" ) ) { + } else if (!Q_stricmp(token, "opaque")) { shader.sort = SS_OPAQUE; - } else if ( !Q_stricmp( token, "decal" ) ) { + } else if (!Q_stricmp(token, "decal")) { shader.sort = SS_DECAL; - } else if ( !Q_stricmp( token, "seeThrough" ) ) { + } else if (!Q_stricmp(token, "seeThrough")) { shader.sort = SS_SEE_THROUGH; - } else if ( !Q_stricmp( token, "banner" ) ) { + } else if (!Q_stricmp(token, "banner")) { shader.sort = SS_BANNER; - } else if ( !Q_stricmp( token, "additive" ) ) { + } else if (!Q_stricmp(token, "additive")) { shader.sort = SS_BLEND1; - } else if ( !Q_stricmp( token, "nearest" ) ) { + } else if (!Q_stricmp(token, "nearest")) { shader.sort = SS_NEAREST; - } else if ( !Q_stricmp( token, "underwater" ) ) { + } else if (!Q_stricmp(token, "underwater")) { shader.sort = SS_UNDERWATER; - } else if ( !Q_stricmp( token, "inside" ) ) { + } else if (!Q_stricmp(token, "inside")) { shader.sort = SS_INSIDE; - } else if ( !Q_stricmp( token, "mid_inside" ) ) { + } else if (!Q_stricmp(token, "mid_inside")) { shader.sort = SS_MID_INSIDE; - } else if ( !Q_stricmp( token, "middle" ) ) { + } else if (!Q_stricmp(token, "middle")) { shader.sort = SS_MIDDLE; - } else if ( !Q_stricmp( token, "mid_outside" ) ) { + } else if (!Q_stricmp(token, "mid_outside")) { shader.sort = SS_MID_OUTSIDE; - } else if ( !Q_stricmp( token, "outside" ) ) { + } else if (!Q_stricmp(token, "outside")) { shader.sort = SS_OUTSIDE; - } - else { - shader.sort = atof( token ); + } else { + shader.sort = atof(token); } } @@ -1945,80 +1614,71 @@ static void ParseSort( const char **text ) { ParseMaterial ================= */ -const char *materialNames[MATERIAL_LAST] = -{ - MATERIALS -}; +const char *materialNames[MATERIAL_LAST] = {MATERIALS}; -void ParseMaterial( const char **text ) -{ - char *token; - int i; +void ParseMaterial(const char **text) { + char *token; + int i; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name); return; } - for(i = 0; i < MATERIAL_LAST; i++) - { - if ( !Q_stricmp( token, materialNames[i] ) ) - { + for (i = 0; i < MATERIAL_LAST; i++) { + if (!Q_stricmp(token, materialNames[i])) { shader.surfaceFlags |= i; break; } } } - // this table is also present in q3map typedef struct infoParm_s { - const char *name; - uint32_t clearSolid, surfaceFlags, contents; + const char *name; + uint32_t clearSolid, surfaceFlags, contents; } infoParm_t; -infoParm_t infoParms[] = { +infoParm_t infoParms[] = { // Game content Flags - { "nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE }, // special hack to clear solid flag - { "nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE }, // special hack to clear opaque flag - { "lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA }, // very damaging - { "slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME }, // mildly damaging - { "water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER }, // - { "fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering - { "shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP }, // block shots, but not people - { "playerclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP }, // block only the player - { "monsterclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP }, // - { "botclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP }, // for bots - { "trigger", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER }, // - { "nodrop", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc) - { "terrain", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN }, // use special terrain collsion - { "ladder", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER }, // climb up in it like water - { "abseil", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL }, // can abseil down this brush - { "outside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE }, // volume is considered to be in the outside (i.e. not indoors) - { "inside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE }, // volume is considered to be inside (i.e. indoors) - - { "detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL }, // don't include in structural bsp - { "trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT }, // surface has an alpha component + {"nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE}, // special hack to clear solid flag + {"nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE}, // special hack to clear opaque flag + {"lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA}, // very damaging + {"slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME}, // mildly damaging + {"water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER}, // + {"fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering + {"shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP}, // block shots, but not people + {"playerclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP}, // block only the player + {"monsterclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP}, // + {"botclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP}, // for bots + {"trigger", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER}, // + {"nodrop", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP}, // don't drop items or leave bodies (death fog, lava, etc) + {"terrain", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN}, // use special terrain collsion + {"ladder", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER}, // climb up in it like water + {"abseil", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL}, // can abseil down this brush + {"outside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE}, // volume is considered to be in the outside (i.e. not indoors) + {"inside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE}, // volume is considered to be inside (i.e. indoors) + + {"detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL}, // don't include in structural bsp + {"trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT}, // surface has an alpha component /* Game surface flags */ - { "sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE }, // emit light from an environment map - { "slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE }, // - - { "nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE }, // - { "noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE }, // don't make impact explosions or marks - { "nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE }, // don't make impact marks, but still explode - { "nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE }, // don't generate a drawsurface (or a lightmap) - { "nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE }, // - { "nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE }, // don't ever add dynamic lights - { "metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE }, // - { "nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE }, // No misc ents on this surface - { "forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE }, // - { "forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE }, // only visible with force sight + {"sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE}, // emit light from an environment map + {"slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE}, // + + {"nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE}, // + {"noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE}, // don't make impact explosions or marks + {"nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE}, // don't make impact marks, but still explode + {"nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE}, // don't generate a drawsurface (or a lightmap) + {"nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE}, // + {"nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE}, // don't ever add dynamic lights + {"metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE}, // + {"nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE}, // No misc ents on this surface + {"forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE}, // + {"forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE}, // only visible with force sight }; - /* =============== ParseSurfaceParm @@ -2026,14 +1686,14 @@ ParseSurfaceParm surfaceparm =============== */ -static void ParseSurfaceParm( const char **text ) { - char *token; - int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); - int i; - - token = COM_ParseExt( text, qfalse ); - for ( i = 0 ; i < numInfoParms ; i++ ) { - if ( !Q_stricmp( token, infoParms[i].name ) ) { +static void ParseSurfaceParm(const char **text) { + char *token; + int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); + int i; + + token = COM_ParseExt(text, qfalse); + for (i = 0; i < numInfoParms; i++) { + if (!Q_stricmp(token, infoParms[i].name)) { shader.surfaceFlags |= infoParms[i].surfaceFlags; shader.contentFlags |= infoParms[i].contents; shader.contentFlags &= infoParms[i].clearSolid; @@ -2051,164 +1711,141 @@ shader. Parse it into the global shader variable. Later functions will optimize it. ================= */ -static qboolean ParseShader( const char **text ) -{ +static qboolean ParseShader(const char **text) { char *token; int s; s = 0; - token = COM_ParseExt( text, qtrue ); - if ( token[0] != '{' ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name ); + token = COM_ParseExt(text, qtrue); + if (token[0] != '{') { + Com_Printf(S_COLOR_YELLOW "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name); return qfalse; } - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: no concluding '}' in shader %s\n", shader.name ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: no concluding '}' in shader %s\n", shader.name); return qfalse; } // end of shader definition - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // stage definition - else if ( token[0] == '{' ) - { - if ( s >= MAX_SHADER_STAGES ) { - ri.Printf( PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES ); + else if (token[0] == '{') { + if (s >= MAX_SHADER_STAGES) { + ri.Printf(PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES); return qfalse; } - if ( !ParseStage( &stages[s], text ) ) - { + if (!ParseStage(&stages[s], text)) { return qfalse; } stages[s].active = qtrue; - if ( stages[s].glow ) - { + if (stages[s].glow) { shader.hasGlow = true; } s++; continue; } // skip stuff that only the QuakeEdRadient needs - else if ( !Q_stricmpn( token, "qer", 3 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "qer", 3)) { + SkipRestOfLine(text); continue; } // material deprecated as of 11 Jan 01 // material undeprecated as of 7 May 01 - q3map_material deprecated - else if ( !Q_stricmp( token, "material" ) || !Q_stricmp( token, "q3map_material" ) ) - { - ParseMaterial( text ); + else if (!Q_stricmp(token, "material") || !Q_stricmp(token, "q3map_material")) { + ParseMaterial(text); } // sun parms - else if ( !Q_stricmp( token, "sun" ) || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunLight[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[1] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[2] = atof( token ); - - VectorNormalize( tr.sunLight ); - - token = COM_ParseExt( text, qfalse ); - float a = atof( token ); - VectorScale( tr.sunLight, a, tr.sunLight); - - token = COM_ParseExt( text, qfalse ); - a = atof( token ); + else if (!Q_stricmp(token, "sun") || !Q_stricmp(token, "q3map_sun") || !Q_stricmp(token, "q3map_sunExt")) { + token = COM_ParseExt(text, qfalse); + tr.sunLight[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[1] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[2] = atof(token); + + VectorNormalize(tr.sunLight); + + token = COM_ParseExt(text, qfalse); + float a = atof(token); + VectorScale(tr.sunLight, a, tr.sunLight); + + token = COM_ParseExt(text, qfalse); + a = atof(token); a = a / 180 * M_PI; - token = COM_ParseExt( text, qfalse ); - float b = atof( token ); + token = COM_ParseExt(text, qfalse); + float b = atof(token); b = b / 180 * M_PI; - tr.sunDirection[0] = cos( a ) * cos( b ); - tr.sunDirection[1] = sin( a ) * cos( b ); - tr.sunDirection[2] = sin( b ); + tr.sunDirection[0] = cos(a) * cos(b); + tr.sunDirection[1] = sin(a) * cos(b); + tr.sunDirection[2] = sin(b); - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // q3map_surfacelight deprecated as of 16 Jul 01 - else if ( !Q_stricmp( token, "surfacelight" ) || !Q_stricmp( token, "q3map_surfacelight" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunSurfaceLight = atoi( token ); - } - else if ( !Q_stricmp( token, "lightColor" ) ) - { + else if (!Q_stricmp(token, "surfacelight") || !Q_stricmp(token, "q3map_surfacelight")) { + token = COM_ParseExt(text, qfalse); + tr.sunSurfaceLight = atoi(token); + } else if (!Q_stricmp(token, "lightColor")) { /* if ( !ParseVector( text, 3, tr.sunAmbient ) ) { return qfalse; } */ - //SP skips this so I'm skipping it here too. - SkipRestOfLine( text ); + // SP skips this so I'm skipping it here too. + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "deformvertexes" ) || !Q_stricmp( token, "deform" )) { - ParseDeform( text ); + } else if (!Q_stricmp(token, "deformvertexes") || !Q_stricmp(token, "deform")) { + ParseDeform(text); continue; - } - else if ( !Q_stricmp( token, "tesssize" ) ) { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "tesssize")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "clampTime" ) ) { - token = COM_ParseExt( text, qfalse ); + } else if (!Q_stricmp(token, "clampTime")) { + token = COM_ParseExt(text, qfalse); if (token[0]) { shader.clampTime = atof(token); } } // skip stuff that only the q3map needs - else if ( !Q_stricmpn( token, "q3map", 5 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "q3map", 5)) { + SkipRestOfLine(text); continue; } // skip stuff that only q3map or the server needs - else if ( !Q_stricmp( token, "surfaceParm" ) ) { - ParseSurfaceParm( text ); + else if (!Q_stricmp(token, "surfaceParm")) { + ParseSurfaceParm(text); continue; } // no mip maps - else if ( !Q_stricmp( token, "nomipmaps" ) ) - { + else if (!Q_stricmp(token, "nomipmaps")) { shader.noMipMaps = true; shader.noPicMip = true; continue; } // no picmip adjustment - else if ( !Q_stricmp( token, "nopicmip" ) ) - { + else if (!Q_stricmp(token, "nopicmip")) { shader.noPicMip = true; continue; - } - else if ( !Q_stricmp( token, "noglfog" ) ) - { + } else if (!Q_stricmp(token, "noglfog")) { shader.fogPass = FP_NONE; continue; } // polygonOffset - else if ( !Q_stricmp( token, "polygonOffset" ) ) - { + else if (!Q_stricmp(token, "polygonOffset")) { shader.polygonOffset = true; continue; - } - else if ( !Q_stricmp( token, "noTC" ) ) - { + } else if (!Q_stricmp(token, "noTC")) { shader.noTC = true; continue; } @@ -2216,82 +1853,66 @@ static qboolean ParseShader( const char **text ) // to be merged into one batch. This is a savings for smoke // puffs and blood, but can't be used for anything where the // shader calcs (not the surface function) reference the entity color or scroll - else if ( !Q_stricmp( token, "entityMergable" ) ) - { + else if (!Q_stricmp(token, "entityMergable")) { shader.entityMergable = true; continue; } // fogParms - else if ( !Q_stricmp( token, "fogParms" ) ) - { - shader.fogParms = (fogParms_t *)Hunk_Alloc( sizeof( fogParms_t ), h_low ); - if ( !ParseVector( text, 3, shader.fogParms->color ) ) { + else if (!Q_stricmp(token, "fogParms")) { + shader.fogParms = (fogParms_t *)Hunk_Alloc(sizeof(fogParms_t), h_low); + if (!ParseVector(text, 3, shader.fogParms->color)) { return qfalse; } - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name); continue; } - shader.fogParms->depthForOpaque = atof( token ); + shader.fogParms->depthForOpaque = atof(token); // skip any old gradient directions - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // portal - else if ( !Q_stricmp(token, "portal") ) - { + else if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; continue; } // skyparms - else if ( !Q_stricmp( token, "skyparms" ) ) - { - ParseSkyParms( text ); + else if (!Q_stricmp(token, "skyparms")) { + ParseSkyParms(text); continue; } // light determines flaring in q3map, not needed here - else if ( !Q_stricmp(token, "light") ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "light")) { + token = COM_ParseExt(text, qfalse); continue; } // cull - else if ( !Q_stricmp( token, "cull") ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing cull parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "cull")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing cull parms in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) ) - { + if (!Q_stricmp(token, "none") || !Q_stricmp(token, "twosided") || !Q_stricmp(token, "disable")) { shader.cullType = CT_TWO_SIDED; - } - else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) ) - { + } else if (!Q_stricmp(token, "back") || !Q_stricmp(token, "backside") || !Q_stricmp(token, "backsided")) { shader.cullType = CT_BACK_SIDED; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name); } continue; } // sort - else if ( !Q_stricmp( token, "sort" ) ) - { - ParseSort( text ); + else if (!Q_stricmp(token, "sort")) { + ParseSort(text); continue; - } - else - { - Com_Printf (S_COLOR_YELLOW "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name ); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name); return qfalse; } } @@ -2299,7 +1920,7 @@ static qboolean ParseShader( const char **text ) // // ignore shaders that don't have any stages, unless it is a sky or fog // - if ( s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG ) ) { + if (s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG)) { return qfalse; } @@ -2317,11 +1938,11 @@ SHADER OPTIMIZATION AND FOGGING */ typedef struct collapse_s { - int blendA; - int blendB; + int blendA; + int blendB; - int multitextureEnv; - int multitextureBlend; + int multitextureEnv; + int multitextureBlend; } collapse_t; /* @@ -2332,9 +1953,7 @@ Attempt to combine two stages into a single multitexture stage FIXME: I think modulated add + modulated add collapses incorrectly ================= */ -static qboolean CollapseMultitexture( void ) { - return qfalse; -} +static qboolean CollapseMultitexture(void) { return qfalse; } /* ============= @@ -2348,8 +1967,7 @@ sortedIndex. ============== */ extern bool gServerSkinHack; -static void FixRenderCommandList( int newShader ) { -} +static void FixRenderCommandList(int newShader) {} /* ============== @@ -2362,84 +1980,80 @@ shaders. Sets shader->sortedIndex ============== */ -static void SortNewShader( void ) { - int i; - float sort; - shader_t *newShader; +static void SortNewShader(void) { + int i; + float sort; + shader_t *newShader; - newShader = tr.shaders[ tr.numShaders - 1 ]; + newShader = tr.shaders[tr.numShaders - 1]; sort = newShader->sort; - for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) { - if ( tr.sortedShaders[ i ]->sort <= sort ) { + for (i = tr.numShaders - 2; i >= 0; i--) { + if (tr.sortedShaders[i]->sort <= sort) { break; } - tr.sortedShaders[i+1] = tr.sortedShaders[i]; - tr.sortedShaders[i+1]->sortedIndex++; + tr.sortedShaders[i + 1] = tr.sortedShaders[i]; + tr.sortedShaders[i + 1]->sortedIndex++; } // Arnout: fix rendercommandlist // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 - FixRenderCommandList( i+1 ); + FixRenderCommandList(i + 1); - newShader->sortedIndex = i+1; - tr.sortedShaders[i+1] = newShader; + newShader->sortedIndex = i + 1; + tr.sortedShaders[i + 1] = newShader; } - /* ==================== GeneratePermanentShader ==================== */ -static shader_t *GeneratePermanentShader( void ) { - shader_t *newShader; - int i, b; - int size; - - if ( tr.numShaders == MAX_SHADERS ) { - //Com_Printf (S_COLOR_YELLOW "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); - Com_Printf( "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); +static shader_t *GeneratePermanentShader(void) { + shader_t *newShader; + int i, b; + int size; + + if (tr.numShaders == MAX_SHADERS) { + // Com_Printf (S_COLOR_YELLOW "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); + Com_Printf("WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); return tr.defaultShader; } - newShader = (struct shader_s *)ri.Hunk_Alloc( sizeof( shader_t ), h_low ); + newShader = (struct shader_s *)ri.Hunk_Alloc(sizeof(shader_t), h_low); *newShader = shader; - if ( shader.sort <= /*SS_OPAQUE*/SS_SEE_THROUGH ) { + if (shader.sort <= /*SS_OPAQUE*/ SS_SEE_THROUGH) { newShader->fogPass = FP_EQUAL; - } else if ( shader.contentFlags & CONTENTS_FOG ) { + } else if (shader.contentFlags & CONTENTS_FOG) { newShader->fogPass = FP_LE; } - tr.shaders[ tr.numShaders ] = newShader; + tr.shaders[tr.numShaders] = newShader; newShader->index = tr.numShaders; - tr.sortedShaders[ tr.numShaders ] = newShader; + tr.sortedShaders[tr.numShaders] = newShader; newShader->sortedIndex = tr.numShaders; tr.numShaders++; - size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof( stages[0] ) : sizeof( stages[0] ); - newShader->stages = (shaderStage_t *) Hunk_Alloc( size, h_low ); + size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof(stages[0]) : sizeof(stages[0]); + newShader->stages = (shaderStage_t *)Hunk_Alloc(size, h_low); - for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) { - if ( !stages[i].active ) { + for (i = 0; i < newShader->numUnfoggedPasses; i++) { + if (!stages[i].active) { break; } newShader->stages[i] = stages[i]; - for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) { - if (newShader->stages[i].bundle[b].numTexMods) - { - size = newShader->stages[i].bundle[b].numTexMods * sizeof( texModInfo_t ); - newShader->stages[i].bundle[b].texMods = (texModInfo_t *)Hunk_Alloc( size, h_low ); - memcpy( newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size ); - } - else - { - newShader->stages[i].bundle[b].texMods = 0; //clear the globabl ptr jic + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { + if (newShader->stages[i].bundle[b].numTexMods) { + size = newShader->stages[i].bundle[b].numTexMods * sizeof(texModInfo_t); + newShader->stages[i].bundle[b].texMods = (texModInfo_t *)Hunk_Alloc(size, h_low); + memcpy(newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size); + } else { + newShader->stages[i].bundle[b].texMods = 0; // clear the globabl ptr jic } } } @@ -2464,7 +2078,7 @@ what it is supposed to look like. OUTPUT: Number of stages after the collapse (in the case of surfacesprites this isn't one). ================= */ -//rww - no longer used, at least for now. destroys alpha shaders completely. +// rww - no longer used, at least for now. destroys alpha shaders completely. #if 0 static int VertexLightingCollapse( void ) { int stage, nextopenstage; @@ -2577,10 +2191,10 @@ Returns a freshly allocated shader with all the needed info from the current global working shader ========================= */ -static shader_t *FinishShader( void ) { - int stage, lmStage, stageIndex; //rwwRMG - stageIndex for AGEN_BLEND - qboolean hasLightmapStage; - qboolean vertexLightmap; +static shader_t *FinishShader(void) { + int stage, lmStage, stageIndex; // rwwRMG - stageIndex for AGEN_BLEND + qboolean hasLightmapStage; + qboolean vertexLightmap; hasLightmapStage = qfalse; vertexLightmap = qfalse; @@ -2588,106 +2202,91 @@ static shader_t *FinishShader( void ) { // // set sky stuff appropriate // - if ( shader.sky ) { + if (shader.sky) { shader.sort = SS_ENVIRONMENT; } // // set polygon offset // - if ( shader.polygonOffset && !shader.sort ) { + if (shader.polygonOffset && !shader.sort) { shader.sort = SS_DECAL; } - for(lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) - { + for (lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) { shaderStage_t *pStage = &stages[lmStage]; - if (pStage->active && pStage->bundle[0].isLightmap) - { + if (pStage->active && pStage->bundle[0].isLightmap) { break; } } - if (lmStage < MAX_SHADER_STAGES) - { - if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) - { - if (lmStage == 0) //< MAX_SHADER_STAGES-1) - {//copy the rest down over the lightmap slot - memmove(&stages[lmStage], &stages[lmStage+1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES-lmStage-1)); - memset(&stages[MAX_SHADER_STAGES-1], 0, sizeof(shaderStage_t)); - //change blending on the moved down stage + if (lmStage < MAX_SHADER_STAGES) { + if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { + if (lmStage == 0) //< MAX_SHADER_STAGES-1) + { // copy the rest down over the lightmap slot + memmove(&stages[lmStage], &stages[lmStage + 1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES - lmStage - 1)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(shaderStage_t)); + // change blending on the moved down stage stages[lmStage].stateBits = GLS_DEFAULT; } - //change anything that was moved down (or the *white if LM is first) to use vertex color + // change anything that was moved down (or the *white if LM is first) to use vertex color stages[lmStage].rgbGen = CGEN_EXACT_VERTEX; stages[lmStage].alphaGen = AGEN_SKIP; - lmStage = MAX_SHADER_STAGES; //skip the style checking below + lmStage = MAX_SHADER_STAGES; // skip the style checking below } } - if (lmStage < MAX_SHADER_STAGES)// && !r_fullbright->value) + if (lmStage < MAX_SHADER_STAGES) // && !r_fullbright->value) { - int numStyles; - int i; + int numStyles; + int i; - for(numStyles=0;numStyles= LS_UNUSED) - { + for (numStyles = 0; numStyles < MAXLIGHTMAPS; numStyles++) { + if (shader.styles[numStyles] >= LS_UNUSED) { break; } } numStyles--; - if (numStyles > 0) - { - for(i=MAX_SHADER_STAGES-1;i>lmStage+numStyles;i--) - { - stages[i] = stages[i-numStyles]; - } - - for(i=0;i 0) { + for (i = MAX_SHADER_STAGES - 1; i > lmStage + numStyles; i--) { + stages[i] = stages[i - numStyles]; + } + + for (i = 0; i < numStyles; i++) { + stages[lmStage + i + 1] = stages[lmStage]; + if (shader.lightmapIndex[i + 1] == LIGHTMAP_BY_VERTEX) { + stages[lmStage + i + 1].bundle[0].image = tr.whiteImage; + } else if (shader.lightmapIndex[i + 1] < 0) { + Com_Error(ERR_DROP, "FinishShader: light style with no light map or vertex color for shader %s", shader.name); + } else { + stages[lmStage + i + 1].bundle[0].image = tr.lightmaps[shader.lightmapIndex[i + 1]]; + stages[lmStage + i + 1].bundle[0].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP + i + 1); } - else - { - stages[lmStage+i+1].bundle[0].image = tr.lightmaps[shader.lightmapIndex[i+1]]; - stages[lmStage+i+1].bundle[0].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP+i+1); - } - stages[lmStage+i+1].rgbGen = CGEN_LIGHTMAPSTYLE; - stages[lmStage+i+1].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); - stages[lmStage+i+1].stateBits |= GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + stages[lmStage + i + 1].rgbGen = CGEN_LIGHTMAPSTYLE; + stages[lmStage + i + 1].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); + stages[lmStage + i + 1].stateBits |= GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; } } - for(i=0;i<=numStyles;i++) - { - stages[lmStage+i].lightmapStyle = shader.styles[i]; + for (i = 0; i <= numStyles; i++) { + stages[lmStage + i].lightmapStyle = shader.styles[i]; } } // // set appropriate stage information // - stageIndex = 0; //rwwRMG - needed for AGEN_BLEND - for ( stage = 0; stage < MAX_SHADER_STAGES; ) { + stageIndex = 0; // rwwRMG - needed for AGEN_BLEND + for (stage = 0; stage < MAX_SHADER_STAGES;) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } - // check for a missing texture - if ( !pStage->bundle[0].image ) { - Com_Printf (S_COLOR_YELLOW "Shader %s has a stage with no image\n", shader.name ); + // check for a missing texture + if (!pStage->bundle[0].image) { + Com_Printf(S_COLOR_YELLOW "Shader %s has a stage with no image\n", shader.name); pStage->active = qfalse; stage++; continue; @@ -2696,56 +2295,52 @@ static shader_t *FinishShader( void ) { // // ditch this stage if it's detail and detail textures are disabled // - if ( pStage->isDetail && !r_detailTextures->integer ) { + if (pStage->isDetail && !r_detailTextures->integer) { int index; - for ( index = stage + 1; indexindex = stageIndex; //rwwRMG - needed for AGEN_BLEND + pStage->index = stageIndex; // rwwRMG - needed for AGEN_BLEND // // default texture coordinate generation // - if ( pStage->bundle[0].isLightmap ) { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].isLightmap) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_LIGHTMAP; } hasLightmapStage = qtrue; } else { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_TEXTURE; } } - - // not a true lightmap but we want to leave existing - // behaviour in place and not print out a warning - //if (pStage->rgbGen == CGEN_VERTEX) { - // vertexLightmap = qtrue; - //} - - + // not a true lightmap but we want to leave existing + // behaviour in place and not print out a warning + // if (pStage->rgbGen == CGEN_VERTEX) { + // vertexLightmap = qtrue; + //} // // determine sort order and fog color adjustment // - if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) && - ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) { + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) && (stages[0].stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS))) { int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS; int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS; @@ -2756,32 +2351,27 @@ static shader_t *FinishShader( void ) { // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA // modulate, additive - if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) || - ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) { + if (((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) || + ((blendSrcBits == GLS_SRCBLEND_ZERO) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR))) { pStage->adjustColorsForFog = ACFF_MODULATE_RGB; } // strict blend - else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA; } // premultiplied alpha - else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_RGBA; } else { // we can't adjust this one correctly, so it won't be exactly correct in fog } // don't screw with sort order if this is a portal or environment - if ( !shader.sort ) { + if (!shader.sort) { // see through item, like a grill or grate - if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) - { + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) { shader.sort = SS_SEE_THROUGH; - } - else - { + } else { /* if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) { @@ -2798,125 +2388,98 @@ static shader_t *FinishShader( void ) { shader.sort = SS_BLEND0; } */ - if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) { // GL_ONE GL_ONE needs to come a bit later shader.sort = SS_BLEND1; - } - else - { + } else { shader.sort = SS_BLEND0; } } } } - //rww - begin hw fog - if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) - { + // rww - begin hw fog + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_ONE) && - pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE) && + pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && stage) - { // + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && stage) { // pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES-1 && - stages[stage+1].bundle[0].isLightmap) - { // multiple light map blending + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES - 1 && + stages[stage + 1].bundle[0].isLightmap) { // multiple light map blending pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO) && pStage->bundle[0].isLightmap) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO) && + pStage->bundle[0].isLightmap) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else - { + } else { pStage->mGLFogColorOverride = GLFOGOVERRIDE_NONE; } - //rww - end hw fog + // rww - end hw fog - stageIndex++; //rwwRMG - needed for AGEN_BLEND + stageIndex++; // rwwRMG - needed for AGEN_BLEND stage++; } // there are times when you will need to manually apply a sort to // opaque alpha tested shaders that have later blend passes - if ( !shader.sort ) { + if (!shader.sort) { shader.sort = SS_OPAQUE; } // // if we are in r_vertexLight mode, never use a lightmap texture // - if ( stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer) ) { - //stage = VertexLightingCollapse(); - //rww - since this does bad things, I am commenting it out for now. If you want to attempt a fix, feel free. + if (stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer)) { + // stage = VertexLightingCollapse(); + // rww - since this does bad things, I am commenting it out for now. If you want to attempt a fix, feel free. hasLightmapStage = qfalse; } // // look for multitexture potential // - if ( stage > 1 && CollapseMultitexture() ) { + if (stage > 1 && CollapseMultitexture()) { stage--; } - if ( shader.lightmapIndex[0] >= 0 && !hasLightmapStage ) - { - if (vertexLightmap) - { -// ri.DPrintf( "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name ); - } - else - { - Com_DPrintf ( "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name ); + if (shader.lightmapIndex[0] >= 0 && !hasLightmapStage) { + if (vertexLightmap) { + // ri.DPrintf( "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name ); + } else { + Com_DPrintf("WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name); memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); memcpy(shader.styles, stylesDefault, sizeof(shader.styles)); } } - // // compute number of passes // shader.numUnfoggedPasses = stage; // fogonly shaders don't have any normal passes - if ( stage == 0 && !shader.sky ) { + if (stage == 0 && !shader.sky) { shader.sort = SS_FOG; } - for ( stage = 1; stage < shader.numUnfoggedPasses; stage++ ) - { + for (stage = 1; stage < shader.numUnfoggedPasses; stage++) { // Make sure stage is non detail and active - if(stages[stage].isDetail || !stages[stage].active) - { + if (stages[stage].isDetail || !stages[stage].active) { break; } // MT lightmaps are always in bundle 1 - if(stages[stage].bundle[0].isLightmap) - { + if (stages[stage].bundle[0].isLightmap) { continue; } } @@ -2938,7 +2501,7 @@ return NULL if not found If found, it will return a valid shader ===================== */ -static const char *FindShaderInShaderText( const char *shadername ) { +static const char *FindShaderInShaderText(const char *shadername) { char *token; const char *p; @@ -2946,41 +2509,39 @@ static const char *FindShaderInShaderText( const char *shadername ) { hash = generateHashValue(shadername, MAX_SHADERTEXT_HASH); - if ( shaderTextHashTable[hash] ) { + if (shaderTextHashTable[hash]) { for (i = 0; shaderTextHashTable[hash][i]; i++) { p = shaderTextHashTable[hash][i]; token = COM_ParseExt(&p, qtrue); - if ( !Q_stricmp( token, shadername ) ) + if (!Q_stricmp(token, shadername)) return p; } } p = s_shaderText; - if ( !p ) { + if (!p) { return NULL; } // look for label - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( !Q_stricmp( token, shadername ) ) { + if (!Q_stricmp(token, shadername)) { return p; - } - else { + } else { // skip the definition - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } } return NULL; } - /* ================== R_FindShaderByName @@ -2989,23 +2550,23 @@ Will always return a valid shader, but it might be the default shader if the real one can't be found. ================== */ -shader_t *R_FindShaderByName( const char *name ) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindShaderByName(const char *name) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( (name==NULL) || (name[0] == 0) ) { + if ((name == NULL) || (name[0] == 0)) { return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader @@ -3019,26 +2580,19 @@ shader_t *R_FindShaderByName( const char *name ) { return tr.defaultShader; } +inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) { + int i; -inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) -{ - int i; - - if (Q_stricmp(sh->name, name)) - { + if (Q_stricmp(sh->name, name)) { return qfalse; } - if (!sh->defaultShader) - { - for(i=0;ilightmapIndex[i] != lightmapIndex[i]) - { + if (!sh->defaultShader) { + for (i = 0; i < MAXLIGHTMAPS; i++) { + if (sh->lightmapIndex[i] != lightmapIndex[i]) { return qfalse; } - if (sh->styles[i] != styles[i]) - { + if (sh->styles[i] != styles[i]) { return qfalse; } } @@ -3075,32 +2629,28 @@ most world construction surfaces. =============== */ -shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ) -{ - char strippedName[MAX_QPATH]; - char fileName[MAX_QPATH]; - int hash; - const char *shaderText; - shader_t *sh; - - if ( name[0] == 0 ) { +shader_t *R_FindShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + char fileName[MAX_QPATH]; + int hash; + const char *shaderText; + shader_t *sh; + + if (name[0] == 0) { return tr.defaultShader; } // use (fullbright) vertex lighting if the bsp file doesn't have // lightmaps - if ( lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps ) - { + if (lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps) { lightmapIndex = lightmapsVertex; - } - else if ( lightmapIndex[0] < LIGHTMAP_2D ) - { + } else if (lightmapIndex[0] < LIGHTMAP_2D) { // negative lightmap indexes cause stray pointers (think tr.lightmaps[lightmapIndex]) - ri.Printf( PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndex[0] ); + ri.Printf(PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndex[0]); lightmapIndex = lightmapsVertex; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); @@ -3112,8 +2662,7 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, strippedName, lightmapIndex, styles)) - { + if (IsShader(sh, strippedName, lightmapIndex, styles)) { return sh; } } @@ -3127,9 +2676,9 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // // attempt to define shader from an explicit parameter file // - shaderText = FindShaderInShaderText( strippedName ); - if ( shaderText ) { - if ( !ParseShader( &shaderText ) ) { + shaderText = FindShaderInShaderText(strippedName); + if (shaderText) { + if (!ParseShader(&shaderText)) { // had errors, so use default shader shader.defaultShader = true; } @@ -3137,27 +2686,25 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * return sh; } - // // if not defined in the in-memory shader descriptions, // look for a single TGA, BMP, or PCX // - COM_StripExtension(name,fileName, sizeof( fileName )); + COM_StripExtension(name, fileName, sizeof(fileName)); shader.defaultShader = qtrue; return FinishShader(); } -shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ) -{ - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindServerShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( name[0] == 0 ) { + if (name[0] == 0) { return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); @@ -3169,8 +2716,7 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, strippedName, lightmapIndex, styles)) - { + if (IsShader(sh, strippedName, lightmapIndex, styles)) { return sh; } } @@ -3186,8 +2732,8 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const } qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte *styles, image_t *image, qboolean mipRawImage) { - int i, hash; - shader_t *sh; + int i, hash; + shader_t *sh; hash = generateHashValue(name, FILE_HASH_SIZE); @@ -3195,61 +2741,58 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte // only gets called from tr_font.c with lightmapIndex == LIGHTMAP_2D // but better safe than sorry. // Doesn't actually ever get called in JA at all - if ( lightmapIndex[0] >= tr.numLightmaps ) { + if (lightmapIndex[0] >= tr.numLightmaps) { lightmapIndex = (int *)lightmapsFullBright; } // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, name, lightmapIndex, styles)) - { + if (IsShader(sh, name, lightmapIndex, styles)) { return sh->index; } } // clear the global shader - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); Q_strncpyz(shader.name, name, sizeof(shader.name)); memcpy(shader.lightmapIndex, lightmapIndex, sizeof(shader.lightmapIndex)); memcpy(shader.styles, styles, sizeof(shader.styles)); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; } // // create the default shading commands // - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image = tr.whiteImage; stages[0].active = qtrue; @@ -3265,8 +2808,8 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte stages[0].bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; stages[0].bundle[0].isLightmap = qtrue; stages[0].active = qtrue; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image = image; @@ -3276,10 +2819,9 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte } sh = FinishShader(); - return sh->index; + return sh->index; } - /* ==================== RE_RegisterShader @@ -3291,30 +2833,28 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndex, const byte *styles ) -{ - shader_t *sh; +qhandle_t RE_RegisterShaderLightMap(const char *name, const int *lightmapIndex, const byte *styles) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmapIndex, styles, qtrue ); + sh = R_FindShader(name, lightmapIndex, styles, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShader @@ -3326,29 +2866,28 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShader( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShader(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qtrue ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShaderNoMip @@ -3356,37 +2895,34 @@ RE_RegisterShaderNoMip For menu graphics that should never be picmiped ==================== */ -qhandle_t RE_RegisterShaderNoMip( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShaderNoMip(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qfalse ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qfalse); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - -//added for ui -rww -const char *RE_ShaderNameFromIndex(int index) -{ +// added for ui -rww +const char *RE_ShaderNameFromIndex(int index) { assert(index >= 0 && index < tr.numShaders && tr.shaders[index]); return tr.shaders[index]->name; } - /* ==================== R_GetShaderByHandle @@ -3395,13 +2931,13 @@ When a handle is passed in by another module, this range checks it and returns a valid (possibly default) shader_t to be used internally. ==================== */ -shader_t *R_GetShaderByHandle( qhandle_t hShader ) { - if ( hShader < 0 ) { - Com_Printf (S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); +shader_t *R_GetShaderByHandle(qhandle_t hShader) { + if (hShader < 0) { + Com_Printf(S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } - if ( hShader >= tr.numShaders ) { - Com_Printf (S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + if (hShader >= tr.numShaders) { + Com_Printf(S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } return tr.shaders[hShader]; @@ -3412,9 +2948,8 @@ shader_t *R_GetShaderByHandle( qhandle_t hShader ) { R_InitShaders ================== */ -void R_InitShaders(qboolean server) -{ - //Com_Printf ("Initializing Shaders\n" ); +void R_InitShaders(qboolean server) { + // Com_Printf ("Initializing Shaders\n" ); memset(hashTable, 0, sizeof(hashTable)); } diff --git a/codemp/rd-dedicated/tr_skin.cpp b/codemp/rd-dedicated/tr_skin.cpp index ad179d0f35..c40aa78a9e 100644 --- a/codemp/rd-dedicated/tr_skin.cpp +++ b/codemp/rd-dedicated/tr_skin.cpp @@ -27,8 +27,8 @@ along with this program; if not, see . bool gServerSkinHack = false; -shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ); -static char *CommaParse( char **data_p ); +shader_t *R_FindServerShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage); +static char *CommaParse(char **data_p); /* =============== RE_SplitSkins @@ -37,49 +37,44 @@ return= true if three part skins found output= qualified names to three skins if return is true, undefined if false =============== */ -bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) -{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; - if (strchr(INname, '|')) - { +bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) { // INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; + if (strchr(INname, '|')) { char name[MAX_QPATH]; strcpy(name, INname); char *p = strchr(name, '|'); - *p=0; + *p = 0; p++; - //fill in the base path - strcpy (skinhead, name); - strcpy (skintorso, name); - strcpy (skinlower, name); + // fill in the base path + strcpy(skinhead, name); + strcpy(skintorso, name); + strcpy(skinlower, name); - //now get the the individual files + // now get the the individual files - //advance to second + // advance to second char *p2 = strchr(p, '|'); assert(p2); - if (!p2) - { + if (!p2) { return false; } - *p2=0; + *p2 = 0; p2++; - strcat (skinhead, p); - strcat (skinhead, ".skin"); + strcat(skinhead, p); + strcat(skinhead, ".skin"); - - //advance to third + // advance to third p = strchr(p2, '|'); assert(p); - if (!p) - { + if (!p) { return false; } - *p=0; + *p = 0; p++; - strcat (skintorso,p2); - strcat (skintorso, ".skin"); + strcat(skintorso, p2); + strcat(skintorso, ".skin"); - strcat (skinlower,p); - strcat (skinlower, ".skin"); + strcat(skinlower, p); + strcat(skinlower, ".skin"); return true; } @@ -87,157 +82,147 @@ bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *sk } // given a name, go get the skin we want and return -qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin) -{ - skin_t *skin; - skinSurface_t *surf; - char *text, *text_p; - char *token; - char surfName[MAX_QPATH]; +qhandle_t RE_RegisterIndividualSkin(const char *name, qhandle_t hSkin) { + skin_t *skin; + skinSurface_t *surf; + char *text, *text_p; + char *token; + char surfName[MAX_QPATH]; // load and parse the skin file - ri.FS_ReadFile( name, (void **)&text ); - if ( !text ) { + ri.FS_ReadFile(name, (void **)&text); + if (!text) { #ifndef FINAL_BUILD - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name ); + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name); #endif return 0; } - assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append + assert(tr.skins[hSkin]); // should already be setup, but might be an 3part append skin = tr.skins[hSkin]; text_p = text; - while ( text_p && *text_p ) { + while (text_p && *text_p) { // get surface name - token = CommaParse( &text_p ); - Q_strncpyz( surfName, token, sizeof( surfName ) ); + token = CommaParse(&text_p); + Q_strncpyz(surfName, token, sizeof(surfName)); - if ( !token[0] ) { + if (!token[0]) { break; } // lowercase the surface name so skin compares are faster - Q_strlwr( surfName ); + Q_strlwr(surfName); - if ( *text_p == ',' ) { + if (*text_p == ',') { text_p++; } - if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one... + if (!strncmp(token, "tag_", 4)) { // these aren't in there, but just in case you load an id style one... continue; } // parse the shader name - token = CommaParse( &text_p ); + token = CommaParse(&text_p); - if ( !strcmp( &surfName[strlen(surfName)-4], "_off") ) - { - if ( !strcmp( token ,"*off" ) ) - { - continue; //don't need these double offs + if (!strcmp(&surfName[strlen(surfName) - 4], "_off")) { + if (!strcmp(token, "*off")) { + continue; // don't need these double offs } - surfName[strlen(surfName)-4] = 0; //remove the "_off" + surfName[strlen(surfName) - 4] = 0; // remove the "_off" } - if ((int)(sizeof( skin->surfaces) / sizeof( skin->surfaces[0] )) <= skin->numSurfaces) - { - assert( (int)(sizeof( skin->surfaces) / sizeof( skin->surfaces[0] )) > skin->numSurfaces ); - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces) ); + if ((int)(sizeof(skin->surfaces) / sizeof(skin->surfaces[0])) <= skin->numSurfaces) { + assert((int)(sizeof(skin->surfaces) / sizeof(skin->surfaces[0])) > skin->numSurfaces); + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces)); break; } - surf = (skinSurface_t *) Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low ); + surf = (skinSurface_t *)Hunk_Alloc(sizeof(*skin->surfaces[0]), h_low); skin->surfaces[skin->numSurfaces] = (_skinSurface_t *)surf; - Q_strncpyz( surf->name, surfName, sizeof( surf->name ) ); + Q_strncpyz(surf->name, surfName, sizeof(surf->name)); - if (gServerSkinHack) surf->shader = R_FindServerShader( token, lightmapsNone, stylesDefault, qtrue ); - else surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue ); + if (gServerSkinHack) + surf->shader = R_FindServerShader(token, lightmapsNone, stylesDefault, qtrue); + else + surf->shader = R_FindShader(token, lightmapsNone, stylesDefault, qtrue); skin->numSurfaces++; } - ri.FS_FreeFile( text ); - + ri.FS_FreeFile(text); // never let a skin have 0 shaders - if ( skin->numSurfaces == 0 ) { - return 0; // use default skin + if (skin->numSurfaces == 0) { + return 0; // use default skin } return hSkin; } -qhandle_t RE_RegisterSkin( const char *name ) { - qhandle_t hSkin; - skin_t *skin; +qhandle_t RE_RegisterSkin(const char *name) { + qhandle_t hSkin; + skin_t *skin; - if ( !name || !name[0] ) { - Com_Printf( "Empty name passed to RE_RegisterSkin\n" ); + if (!name || !name[0]) { + Com_Printf("Empty name passed to RE_RegisterSkin\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Skin name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Skin name exceeds MAX_QPATH\n"); return 0; } // see if the skin is already loaded - for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) { + for (hSkin = 1; hSkin < tr.numSkins; hSkin++) { skin = tr.skins[hSkin]; - if ( !Q_stricmp( skin->name, name ) ) { - if( skin->numSurfaces == 0 ) { - return 0; // default skin + if (!Q_stricmp(skin->name, name)) { + if (skin->numSurfaces == 0) { + return 0; // default skin } return hSkin; } } // allocate a new skin - if ( tr.numSkins == MAX_SKINS ) { - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); + if (tr.numSkins == MAX_SKINS) { + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name); return 0; } tr.numSkins++; - skin = (struct skin_s *)Hunk_Alloc( sizeof( skin_t ), h_low ); + skin = (struct skin_s *)Hunk_Alloc(sizeof(skin_t), h_low); tr.skins[hSkin] = skin; - Q_strncpyz( skin->name, name, sizeof( skin->name ) ); + Q_strncpyz(skin->name, name, sizeof(skin->name)); skin->numSurfaces = 0; // make sure the render thread is stopped R_IssuePendingRenderCommands(); // If not a .skin file, load as a single shader - if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) { -/* skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); - skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); - return hSkin; -*/ + if (strcmp(name + strlen(name) - 5, ".skin")) { + /* skin->numSurfaces = 1; + skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); + skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + return hSkin; + */ } - char skinhead[MAX_QPATH]={0}; - char skintorso[MAX_QPATH]={0}; - char skinlower[MAX_QPATH]={0}; - if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) ) - {//three part + char skinhead[MAX_QPATH] = {0}; + char skintorso[MAX_QPATH] = {0}; + char skinlower[MAX_QPATH] = {0}; + if (RE_SplitSkins(name, (char *)&skinhead, (char *)&skintorso, (char *)&skinlower)) { // three part hSkin = RE_RegisterIndividualSkin(skinhead, hSkin); - if (hSkin) - { + if (hSkin) { hSkin = RE_RegisterIndividualSkin(skintorso, hSkin); - if (hSkin) - { + if (hSkin) { hSkin = RE_RegisterIndividualSkin(skinlower, hSkin); } } - } - else - {//single skin + } else { // single skin hSkin = RE_RegisterIndividualSkin(name, hSkin); } - return(hSkin); + return (hSkin); } - - /* ================== CommaParse @@ -246,76 +231,65 @@ This is unfortunate, but the skin files aren't compatible with our normal parsing rules. ================== */ -static char *CommaParse( char **data_p ) { +static char *CommaParse(char **data_p) { int c = 0, len; char *data; - static char com_token[MAX_TOKEN_CHARS]; + static char com_token[MAX_TOKEN_CHARS]; data = *data_p; len = 0; com_token[0] = 0; // make sure incoming data is valid - if ( !data ) { + if (!data) { *data_p = NULL; return com_token; } - while ( 1 ) { + while (1) { // skip whitespace - while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') { - if( !c ) { + while ((c = *(const unsigned char * /*eurofix*/)data) <= ' ') { + if (!c) { break; } data++; } - c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { while (*data && *data != '\n') data++; } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { + else if (c == '/' && data[1] == '*') { + while (*data && (*data != '*' || data[1] != '/')) { data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } - if ( c == 0 ) { + if (c == 0) { return ""; } // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if (len < MAX_TOKEN_CHARS - 1) - { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } @@ -323,20 +297,18 @@ static char *CommaParse( char **data_p ) { } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS - 1) - { + do { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32 && c != ',' ); + } while (c > 32 && c != ','); com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -347,13 +319,11 @@ RE_RegisterServerSkin Mangled version of the above function to load .skin files on the server. =============== */ -qhandle_t RE_RegisterServerSkin( const char *name ) { +qhandle_t RE_RegisterServerSkin(const char *name) { qhandle_t r; - if (ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && - ShaderHashTableExists()) - { //If the client is running then we can go straight into the normal registerskin func + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // If the client is running then we can go straight into the normal registerskin func return RE_RegisterSkin(name); } @@ -369,16 +339,16 @@ qhandle_t RE_RegisterServerSkin( const char *name ) { R_InitSkins =============== */ -void R_InitSkins( void ) { - skin_t *skin; +void R_InitSkins(void) { + skin_t *skin; tr.numSkins = 1; // make the default skin have all default shaders - skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc( sizeof( skin_t ), h_low ); - Q_strncpyz( skin->name, "", sizeof( skin->name ) ); + skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc(sizeof(skin_t), h_low); + Q_strncpyz(skin->name, "", sizeof(skin->name)); skin->numSurfaces = 1; - skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc( sizeof( skinSurface_t ), h_low ); + skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc(sizeof(skinSurface_t), h_low); skin->surfaces[0]->shader = tr.defaultShader; } @@ -387,9 +357,9 @@ void R_InitSkins( void ) { R_GetSkinByHandle =============== */ -skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { - if ( hSkin < 1 || hSkin >= tr.numSkins ) { +skin_t *R_GetSkinByHandle(qhandle_t hSkin) { + if (hSkin < 1 || hSkin >= tr.numSkins) { return tr.skins[0]; } - return tr.skins[ hSkin ]; + return tr.skins[hSkin]; } diff --git a/codemp/rd-rend2/G2_API.cpp b/codemp/rd-rend2/G2_API.cpp index aa152699c8..6406da931f 100644 --- a/codemp/rd-rend2/G2_API.cpp +++ b/codemp/rd-rend2/G2_API.cpp @@ -3,18 +3,18 @@ #include "qcommon/MiniHeap.h" #include "tr_local.h" -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #include "ghoul2/G2_gore.h" -//rww - RAGDOLL_END +// rww - RAGDOLL_END #include #ifdef _MSC_VER -#pragma warning (push, 3) //go back down to 3 for the stl include +#pragma warning(push, 3) // go back down to 3 for the stl include #endif #include #ifdef _MSC_VER -#pragma warning (pop) +#pragma warning(pop) #endif #ifdef _FULL_G2_LEAK_CHECKING @@ -23,43 +23,35 @@ int g_G2ServerAlloc = 0; int g_G2ClientAlloc = 0; int g_G2AllocServer = 0; -//stupid debug crap to track leaks in case they happen. -//we used to shove everything into a map and delete it all and not care about -//leaks, but that was not the Right Thing. -rww -#define MAX_TRACKED_ALLOC 4096 -static bool g_G2AllocTrackInit = false; //want to keep this thing contained +// stupid debug crap to track leaks in case they happen. +// we used to shove everything into a map and delete it all and not care about +// leaks, but that was not the Right Thing. -rww +#define MAX_TRACKED_ALLOC 4096 +static bool g_G2AllocTrackInit = false; // want to keep this thing contained static CGhoul2Info_v *g_G2AllocTrack[MAX_TRACKED_ALLOC]; -void G2_DEBUG_InitPtrTracker(void) -{ +void G2_DEBUG_InitPtrTracker(void) { memset(g_G2AllocTrack, 0, sizeof(g_G2AllocTrack)); g_G2AllocTrackInit = true; } -void G2_DEBUG_ReportLeaks(void) -{ +void G2_DEBUG_ReportLeaks(void) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { Com_Printf("g2 leak tracker was never initialized!\n"); return; } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i]) - { + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i]) { Com_Printf("Bad guy found in slot %i, attempting to access...", i); CGhoul2Info_v &g2v = *g_G2AllocTrack[i]; CGhoul2Info &g2 = g2v[0]; - if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) - { + if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) { Com_Printf("Bad guy's filename is %s\n", g2.mFileName); - } - else - { + } else { Com_Printf("He's not valid! BURN HIM!\n"); } } @@ -67,24 +59,19 @@ void G2_DEBUG_ReportLeaks(void) } } -void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (!g_G2AllocTrack[i]) - { + while (i < MAX_TRACKED_ALLOC) { + if (!g_G2AllocTrack[i]) { g_G2AllocTrack[i] = g2; return; } @@ -93,29 +80,22 @@ void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { Com_Printf("%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { + } else { Com_Printf("Crap g2 instance passed to instance tracker (in).\n"); } } -void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i] == g2) - { + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i] == g2) { g_G2AllocTrack[i] = NULL; return; } @@ -124,12 +104,9 @@ void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { Com_Printf("%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { + } else { Com_Printf("Crap g2 instance passed to instance tracker (out).\n"); } } @@ -139,76 +116,66 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo); -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #define NUM_G2T_TIME (2) static int G2TimeBases[NUM_G2T_TIME]; -void G2API_SetTime(int currentTime,int clock) -{ - assert(clock>=0&&clock= 0 && clock < NUM_G2T_TIME); #if G2_DEBUG_TIME - Com_Printf("Set Time: before c%6d s%6d",G2TimeBases[1],G2TimeBases[0]); + Com_Printf("Set Time: before c%6d s%6d", G2TimeBases[1], G2TimeBases[0]); #endif - G2TimeBases[clock]=currentTime; - if (G2TimeBases[1]>G2TimeBases[0]+200) - { - G2TimeBases[1]=0; // use server time instead + G2TimeBases[clock] = currentTime; + if (G2TimeBases[1] > G2TimeBases[0] + 200) { + G2TimeBases[1] = 0; // use server time instead return; } #if G2_DEBUG_TIME - Com_Printf(" after c%6d s%6d\n",G2TimeBases[1],G2TimeBases[0]); + Com_Printf(" after c%6d s%6d\n", G2TimeBases[1], G2TimeBases[0]); #endif } -int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar +int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar { - int ret=G2TimeBases[1]; - if ( !ret ) - { + int ret = G2TimeBases[1]; + if (!ret) { ret = G2TimeBases[0]; } return ret; } -//rww - RAGDOLL_END +// rww - RAGDOLL_END -//rww - Stuff to allow association of ghoul2 instances to entity numbers. -//This way, on listen servers when both the client and server are doing -//ghoul2 operations, we can copy relevant data off the client instance -//directly onto the server instance and slash the transforms and whatnot -//right in half. +// rww - Stuff to allow association of ghoul2 instances to entity numbers. +// This way, on listen servers when both the client and server are doing +// ghoul2 operations, we can copy relevant data off the client instance +// directly onto the server instance and slash the transforms and whatnot +// right in half. #ifdef _G2_LISTEN_SERVER_OPT CGhoul2Info_v *g2ClientAttachments[MAX_GENTITIES]; #endif -void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) -{ //Assign the pointers in the arrays +void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) { // Assign the pointers in the arrays #ifdef _G2_LISTEN_SERVER_OPT - if (server) - { + if (server) { ghoul2[0].entityNum = entityNum; - } - else - { + } else { g2ClientAttachments[entityNum] = &ghoul2; } #endif } -void G2API_ClearAttachedInstance(int entityNum) -{ +void G2API_ClearAttachedInstance(int entityNum) { #ifdef _G2_LISTEN_SERVER_OPT g2ClientAttachments[entityNum] = NULL; #endif } -void G2API_CleanEntAttachments(void) -{ +void G2API_CleanEntAttachments(void) { #ifdef _G2_LISTEN_SERVER_OPT int i = 0; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { g2ClientAttachments[i] = NULL; i++; } @@ -219,21 +186,18 @@ void G2API_CleanEntAttachments(void) void CopyBoneCache(CBoneCache *to, CBoneCache *from); #endif -qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelIndex) -{ +qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v &ghoul2, int modelIndex) { #ifndef _G2_LISTEN_SERVER_OPT return qfalse; #else CGhoul2Info *serverInstance = &ghoul2[modelIndex]; CGhoul2Info *clientInstance; - if (ri.Cvar_VariableIntegerValue( "dedicated" )) - { //No client to get from! + if (ri.Cvar_VariableIntegerValue("dedicated")) { // No client to get from! return qfalse; } - if (!g2ClientAttachments[serverInstance->entityNum]) - { //No clientside instance is attached to this entity + if (!g2ClientAttachments[serverInstance->entityNum]) { // No clientside instance is attached to this entity return qfalse; } @@ -242,17 +206,15 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde int frameNum = G2API_GetTime(0); - if (clientInstance->mSkelFrameNum != frameNum) - { //it has to be constructed already + if (clientInstance->mSkelFrameNum != frameNum) { // it has to be constructed already return qfalse; } - if (!clientInstance->mBoneCache) - { //that just won't do + if (!clientInstance->mBoneCache) { // that just won't do return qfalse; } - //Just copy over the essentials + // Just copy over the essentials serverInstance->aHeader = clientInstance->aHeader; serverInstance->animModel = clientInstance->animModel; serverInstance->currentAnimModelSize = clientInstance->currentAnimModelSize; @@ -264,14 +226,12 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde serverInstance->mSurfaceRoot = clientInstance->mSurfaceRoot; serverInstance->mTransformedVertsArray = clientInstance->mTransformedVertsArray; - if (!serverInstance->mBoneCache) - { //if this is the case.. I guess we can use the client one instead + if (!serverInstance->mBoneCache) { // if this is the case.. I guess we can use the client one instead serverInstance->mBoneCache = clientInstance->mBoneCache; } - //Copy the contents of the client cache over the contents of the server cache - if (serverInstance->mBoneCache != clientInstance->mBoneCache) - { + // Copy the contents of the client cache over the contents of the server cache + if (serverInstance->mBoneCache != clientInstance->mBoneCache) { CopyBoneCache(serverInstance->mBoneCache, clientInstance->mBoneCache); } @@ -284,221 +244,201 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde #define MAX_G2_MODELS (1024) #define G2_MODEL_BITS (10) -#define G2_INDEX_MASK (MAX_G2_MODELS-1) +#define G2_INDEX_MASK (MAX_G2_MODELS - 1) -static size_t GetSizeOfGhoul2Info ( const CGhoul2Info& g2Info ) -{ +static size_t GetSizeOfGhoul2Info(const CGhoul2Info &g2Info) { size_t size = 0; - + // This is pretty ugly, but we don't want to save everything in the CGhoul2Info object. - size += offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + size += offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); // Surface vector + size - size += sizeof (int); - size += g2Info.mSlist.size() * sizeof (surfaceInfo_t); + size += sizeof(int); + size += g2Info.mSlist.size() * sizeof(surfaceInfo_t); // Bone vector + size - size += sizeof (int); - size += g2Info.mBlist.size() * sizeof (boneInfo_t); + size += sizeof(int); + size += g2Info.mBlist.size() * sizeof(boneInfo_t); // Bolt vector + size - size += sizeof (int); - size += g2Info.mBltlist.size() * sizeof (boltInfo_t); + size += sizeof(int); + size += g2Info.mBltlist.size() * sizeof(boltInfo_t); return size; } -static size_t SerializeGhoul2Info ( char *buffer, const CGhoul2Info& g2Info ) -{ +static size_t SerializeGhoul2Info(char *buffer, const CGhoul2Info &g2Info) { char *base = buffer; size_t blockSize; - + // Oh the ugliness... - blockSize = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (buffer, &g2Info.mModelindex, blockSize); + blockSize = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(buffer, &g2Info.mModelindex, blockSize); buffer += blockSize; // Surfaces vector + size *(int *)buffer = g2Info.mSlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mSlist.size() * sizeof (surfaceInfo_t); - memcpy (buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof (surfaceInfo_t)); + blockSize = g2Info.mSlist.size() * sizeof(surfaceInfo_t); + memcpy(buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof(surfaceInfo_t)); buffer += blockSize; // Bones vector + size *(int *)buffer = g2Info.mBlist.size(); - buffer += sizeof (int); - - blockSize = g2Info.mBlist.size() * sizeof (boneInfo_t); - memcpy (buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof (boneInfo_t)); + buffer += sizeof(int); + + blockSize = g2Info.mBlist.size() * sizeof(boneInfo_t); + memcpy(buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof(boneInfo_t)); buffer += blockSize; // Bolts vector + size *(int *)buffer = g2Info.mBltlist.size(); - buffer += sizeof (int); - - blockSize = g2Info.mBltlist.size() * sizeof (boltInfo_t); - memcpy (buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof (boltInfo_t)); + buffer += sizeof(int); + + blockSize = g2Info.mBltlist.size() * sizeof(boltInfo_t); + memcpy(buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof(boltInfo_t)); buffer += blockSize; return static_cast(buffer - base); } -static size_t DeserializeGhoul2Info ( const char *buffer, CGhoul2Info& g2Info ) -{ +static size_t DeserializeGhoul2Info(const char *buffer, CGhoul2Info &g2Info) { const char *base = buffer; size_t size; - size = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (&g2Info.mModelindex, buffer, size); + size = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(&g2Info.mModelindex, buffer, size); buffer += size; // Surfaces vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mSlist.assign ((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); - buffer += sizeof (surfaceInfo_t) * size; + g2Info.mSlist.assign((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); + buffer += sizeof(surfaceInfo_t) * size; // Bones vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBlist.assign ((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); - buffer += sizeof (boneInfo_t) * size; + g2Info.mBlist.assign((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); + buffer += sizeof(boneInfo_t) * size; // Bolt vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBltlist.assign ((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); - buffer += sizeof (boltInfo_t) * size; + g2Info.mBltlist.assign((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); + buffer += sizeof(boltInfo_t) * size; return static_cast(buffer - base); } -class Ghoul2InfoArray : public IGhoul2InfoArray -{ - std::vector mInfos[MAX_G2_MODELS]; - int mIds[MAX_G2_MODELS]; - std::list mFreeIndecies; - void DeleteLow(int idx) - { - for (size_t model=0; model< mInfos[idx].size(); model++) - { - if (mInfos[idx][model].mBoneCache) - { +class Ghoul2InfoArray : public IGhoul2InfoArray { + std::vector mInfos[MAX_G2_MODELS]; + int mIds[MAX_G2_MODELS]; + std::list mFreeIndecies; + void DeleteLow(int idx) { + for (size_t model = 0; model < mInfos[idx].size(); model++) { + if (mInfos[idx][model].mBoneCache) { RemoveBoneCache(mInfos[idx][model].mBoneCache); - mInfos[idx][model].mBoneCache=0; + mInfos[idx][model].mBoneCache = 0; } } mInfos[idx].clear(); - if ((mIds[idx]>>G2_MODEL_BITS)>(1<<(31-G2_MODEL_BITS))) - { - mIds[idx]=MAX_G2_MODELS+idx; //rollover reset id to minimum value + if ((mIds[idx] >> G2_MODEL_BITS) > (1 << (31 - G2_MODEL_BITS))) { + mIds[idx] = MAX_G2_MODELS + idx; // rollover reset id to minimum value mFreeIndecies.push_back(idx); - } - else - { - mIds[idx]+=MAX_G2_MODELS; + } else { + mIds[idx] += MAX_G2_MODELS; mFreeIndecies.push_front(idx); } } -public: - Ghoul2InfoArray() - { + + public: + Ghoul2InfoArray() { int i; - for (i=0;i(buffer - base); } - size_t Deserialize ( const char *buffer, size_t size ) - { + size_t Deserialize(const char *buffer, size_t size) { const char *base = buffer; size_t count; // Free indices count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mFreeIndecies.assign ((int *)buffer, (int *)buffer + count); - buffer += sizeof (int) * count; + mFreeIndecies.assign((int *)buffer, (int *)buffer + count); + buffer += sizeof(int) * count; // IDs - memcpy (mIds, buffer, sizeof (mIds)); - buffer += sizeof (mIds); + memcpy(mIds, buffer, sizeof(mIds)); + buffer += sizeof(mIds); // Ghoul2 infos - for ( size_t i = 0; i < MAX_G2_MODELS; i++ ) - { + for (size_t i = 0; i < MAX_G2_MODELS; i++) { mInfos[i].clear(); count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mInfos[i].resize (count); - - for ( size_t j = 0; j < count; j++ ) - { - buffer += DeserializeGhoul2Info (buffer, mInfos[i][j]); + mInfos[i].resize(count); + + for (size_t j = 0; j < count; j++) { + buffer += DeserializeGhoul2Info(buffer, mInfos[i][j]); } } @@ -506,117 +446,93 @@ class Ghoul2InfoArray : public IGhoul2InfoArray } #if G2API_DEBUG - ~Ghoul2InfoArray() - { + ~Ghoul2InfoArray() { char mess[1000]; - if (mFreeIndecies.size()::iterator j; - for (j=mFreeIndecies.begin();j!=mFreeIndecies.end();j++) - { - if (*j==i) + for (j = mFreeIndecies.begin(); j != mFreeIndecies.end(); j++) { + if (*j == i) break; } - if (j==mFreeIndecies.end()) - { - sprintf(mess,"Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); + if (j == mFreeIndecies.end()) { + sprintf(mess, "Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); OutputDebugString(mess); - if (mInfos[i].size()) - { - sprintf(mess,"%s\n", mInfos[i][0].mFileName); + if (mInfos[i].size()) { + sprintf(mess, "%s\n", mInfos[i][0].mFileName); OutputDebugString(mess); } } } - } - else - { + } else { OutputDebugString("No ghoul2 info slots leaked\n"); } } #endif - int New() - { - if (mFreeIndecies.empty()) - { + int New() { + if (mFreeIndecies.empty()) { assert(0); Com_Error(ERR_FATAL, "Out of ghoul2 info slots"); - } - // gonna pull from the front, doing a - int idx=*mFreeIndecies.begin(); + // gonna pull from the front, doing a + int idx = *mFreeIndecies.begin(); mFreeIndecies.erase(mFreeIndecies.begin()); return mIds[idx]; } - bool IsValid(int handle) const - { - if ( handle <= 0 ) - { + bool IsValid(int handle) const { + if (handle <= 0) { return false; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + if (mIds[handle & G2_INDEX_MASK] != handle) // not a valid handle, could be old { return false; } return true; } - void Delete(int handle) - { - if (handle <= 0) - { + void Delete(int handle) { + if (handle <= 0) { return; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + if (mIds[handle & G2_INDEX_MASK] == handle) { + DeleteLow(handle & G2_INDEX_MASK); } } - std::vector &Get(int handle) - { - assert(handle>0); //null handle - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); - - return mInfos[handle&G2_INDEX_MASK]; - } - const std::vector &Get(int handle) const - { - assert(handle>0); - assert(mIds[handle&G2_INDEX_MASK]==handle); // not a valid handle, could be old or garbage - return mInfos[handle&G2_INDEX_MASK]; + std::vector &Get(int handle) { + assert(handle > 0); // null handle + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + assert(!(handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle)); + + return mInfos[handle & G2_INDEX_MASK]; + } + const std::vector &Get(int handle) const { + assert(handle > 0); + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + return mInfos[handle & G2_INDEX_MASK]; } #if G2API_DEBUG - vector &GetDebug(int handle) - { + vector &GetDebug(int handle) { static vector null; - if (handle<=0||(handle&G2_INDEX_MASK)<0||(handle&G2_INDEX_MASK)>=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle) - { + if (handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle) { return *(vector *)0; // null reference, intentional } - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - void TestAllAnims() - { + void TestAllAnims() { int j; - for (j=0;j &ghoul2=mInfos[j]; + for (j = 0; j < MAX_G2_MODELS; j++) { + vector &ghoul2 = mInfos[j]; int i; - for (i=0; iDeserialize ((const char *)data, size); - Z_Free ((void *)data); + size_t read = singleton->Deserialize((const char *)data, size); + Z_Free((void *)data); - assert (read == size); + assert(read == size); } } -void SaveGhoul2InfoArray() -{ +void SaveGhoul2InfoArray() { size_t size = singleton->GetSerializedSize(); - void *data = Z_Malloc (size, TAG_GHOUL2); - size_t written = singleton->Serialize ((char *)data); + void *data = Z_Malloc(size, TAG_GHOUL2); + size_t written = singleton->Serialize((char *)data); - assert (written == size); + assert(written == size); - if ( !ri.PD_Store (PERSISTENT_G2DATA, data, size) ) - { - Com_Printf (S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); + if (!ri.PD_Store(PERSISTENT_G2DATA, data, size)) { + Com_Printf(S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); } } -void Ghoul2InfoArray_Free(void) -{ - if(singleton) { +void Ghoul2InfoArray_Free(void) { + if (singleton) { delete singleton; singleton = NULL; } } // this is the ONLY function to read entity states directly -void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) -{ - if (*ghoul2Ptr) - { +void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) { + if (*ghoul2Ptr) { CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. extern int R_GetRNumEntities(void); extern void R_SetRNumEntities(int num); //check if this instance is actually on a refentity @@ -729,16 +636,13 @@ void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) #endif #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghoul2Ptr); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghoul2Ptr); } g_Ghoul2Allocations -= sizeof(*ghoul2Ptr); @@ -747,18 +651,15 @@ void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) delete *ghoul2Ptr; *ghoul2Ptr = NULL; - } + } } -qboolean G2_ShouldRegisterServer(void) -{ +qboolean G2_ShouldRegisterServer(void) { vm_t *currentVM = ri.GetCurrentVM(); - if ( currentVM && currentVM->slot == VM_GAME ) - { - if ( ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && ShaderHashTableExists()) - { //if the hunk has been marked then we are now loading client assets so don't load on server. + if (currentVM && currentVM->slot == VM_GAME) { + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // if the hunk has been marked then we are now loading client assets so don't load on server. return qfalse; } @@ -767,40 +668,33 @@ qboolean G2_ShouldRegisterServer(void) return qfalse; } -qhandle_t G2API_PrecacheGhoul2Model( const char *fileName ) -{ - if ( G2_ShouldRegisterServer() ) - return RE_RegisterServerModel( fileName ); +qhandle_t G2API_PrecacheGhoul2Model(const char *fileName) { + if (G2_ShouldRegisterServer()) + return RE_RegisterServerModel(fileName); else - return RE_RegisterModel( fileName ); + return RE_RegisterModel(fileName); } -void CL_InitRef( void ); +void CL_InitRef(void); // initialise all that needs to be on a new Ghoul II model -int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, - qhandle_t customShader, int modelFlags, int lodBias) -{ - int model; - CGhoul2Info newModel; +int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { + int model; + CGhoul2Info newModel; // are we actually asking for a model to be loaded. - if (!fileName || !fileName[0]) - { + if (!fileName || !fileName[0]) { assert(0); return -1; } - if (!(*ghoul2Ptr)) - { + if (!(*ghoul2Ptr)) { *ghoul2Ptr = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -811,29 +705,23 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); // find a free spot in the list - for (model=0; model< ghoul2.size(); model++) - { - if (ghoul2[model].mModelindex == -1) - { - ghoul2[model]=CGhoul2Info(); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModelindex == -1) { + ghoul2[model] = CGhoul2Info(); break; } } - if (model==ghoul2.size()) - { //init should not be used to create additional models, only the first one - assert(ghoul2.size() < 4); //use G2API_CopySpecificG2Model to add models - ghoul2.push_back(CGhoul2Info()); + if (model == ghoul2.size()) { // init should not be used to create additional models, only the first one + assert(ghoul2.size() < 4); // use G2API_CopySpecificG2Model to add models + ghoul2.push_back(CGhoul2Info()); } strcpy(ghoul2[model].mFileName, fileName); ghoul2[model].mModelindex = model; - if (!G2_TestModelPointers(&ghoul2[model])) - { - ghoul2[model].mFileName[0]=0; + if (!G2_TestModelPointers(&ghoul2[model])) { + ghoul2[model].mFileName[0] = 0; ghoul2[model].mModelindex = -1; - } - else - { + } else { G2_Init_Bone_List(ghoul2[model].mBlist, ghoul2[model].aHeader->numBones); G2_Init_Bolt_List(ghoul2[model].mBltlist); ghoul2[model].mCustomShader = customShader; @@ -847,27 +735,22 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m return ghoul2[model].mModelindex; } -qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) -{ - if (ghlInfo) - { +qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) { + if (ghlInfo) { ghlInfo->mLodBias = lodBias; return qtrue; } return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin); -qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin); +qboolean G2API_SetSkin(CGhoul2Info_v &ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (ghlInfo) - { + if (ghlInfo) { ghlInfo->mCustomSkin = customSkin; - if (renderSkin) - {//this is going to set the surfs on/off matching the skin file - G2_SetSurfaceOnOffFromSkin( ghlInfo, renderSkin ); + if (renderSkin) { // this is going to set the surfs on/off matching the skin file + G2_SetSurfaceOnOffFromSkin(ghlInfo, renderSkin); } return qtrue; @@ -875,27 +758,22 @@ qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSk return qfalse; } -qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) -{ - if (ghlInfo) - { +qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) { + if (ghlInfo) { ghlInfo->mCustomShader = customShader; return qtrue; } return qfalse; } -qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) -{ +qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, surfaceName, flags); @@ -903,29 +781,23 @@ qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, c return qfalse; } -int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (ghlInfo) - { +int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (ghlInfo) { return G2_IsSurfaceOff(ghlInfo, ghlInfo->mSlist, surfaceName); } return -1; } -qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghoul2)) - { +qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) { + if (G2_SetupModelPointers(ghoul2)) { return G2_SetRootSurface(ghoul2, modelIndex, surfaceName); } return qfalse; } -int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); @@ -933,10 +805,8 @@ int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, fl return -1; } -qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_RemoveSurface(ghlInfo->mSlist, index); @@ -944,66 +814,55 @@ qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) return qfalse; } -int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetParentSurface(ghlInfo, index); } return -1; } -int G2API_GetSurfaceRenderStatus(CGhoul2Info_v& ghoul2, int modelIndex, const char *surfaceName) -{ +int G2API_GetSurfaceRenderStatus(CGhoul2Info_v &ghoul2, int modelIndex, const char *surfaceName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceRendered(ghlInfo, surfaceName, ghlInfo->mSlist); } return -1; } -qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { return qfalse; } return qtrue; } -qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; // sanity check - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { // if we hit this assert then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. assert(0); return qfalse; } - if (ghlInfo.size() > modelIndex) - { + if (ghlInfo.size() > modelIndex) { #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -1011,40 +870,32 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; int newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (int i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -1054,43 +905,36 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex } } - return qtrue; } -qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) -{//remove 'em ALL! +qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) { // remove 'em ALL! CGhoul2Info_v &ghlInfo = **ghlRemove; - int modelIndex = 0; + int modelIndex = 0; int newSize = 0; int i; // sanity check - if ( !ghlInfo.size() ) - {// if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that + if (!ghlInfo.size()) { // if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. return qfalse; } - for ( modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++ ) - { - if ( ghlInfo[modelIndex].mModelindex == -1 ) - { + for (modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++) { + if (ghlInfo[modelIndex].mModelindex == -1) { continue; } #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -1098,41 +942,33 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; } newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -1143,201 +979,172 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) return qtrue; } -//check if a bone exists on skeleton without actually adding to the bone list -rww -qboolean G2API_DoesBoneExist(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +// check if a bone exists on skeleton without actually adding to the bone list -rww +qboolean G2API_DoesBoneExist(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { //model is valid + if (G2_SetupModelPointers(ghlInfo)) { // model is valid mdxaHeader_t *mdxa = ghlInfo->currentModel->data.gla; - if (mdxa) - { //get the skeleton data and iterate through the bones + if (mdxa) { // get the skeleton data and iterate through the bones int i; mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for (i = 0; i < mdxa->numBones; i++) - { - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (!Q_stricmp(skel->name, boneName)) - { //got it + for (i = 0; i < mdxa->numBones; i++) { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + if (!Q_stricmp(skel->name, boneName)) { // got it return qtrue; } } } } - //guess it doesn't exist + // guess it doesn't exist return qfalse; } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled -//rww - RAGDOLL_END +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +// rww - RAGDOLL_END -qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ +qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, + const int currentTime, const float AsetFrame, const int blendTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); - if (endFrame<=0) - { - endFrame=1; + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); + return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, + ghlInfo->aHeader->numFrames); } return qfalse; } #define _PLEASE_SHUT_THE_HELL_UP -qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; +qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, + const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) { + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; #ifndef _PLEASE_SHUT_THE_HELL_UP - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); #endif - if (endFrame<=0) - { - endFrame=1; + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (ghoul2.size()>modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; - - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); + return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } } return qfalse; } -qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, - int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList) -{ - assert(startFrame!=endFrame); //this is bad - assert(startFrame!=flags); //this is bad - assert(endFrame!=flags); //this is bad - assert(currentFrame!=animSpeed); //this is bad +qboolean G2API_GetBoneAnim(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *animSpeed, int *modelList) { + assert(startFrame != endFrame); // this is bad + assert(startFrame != flags); // this is bad + assert(endFrame != flags); // this is bad + assert(currentFrame != animSpeed); // this is bad CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - int aCurrentTime=G2API_GetTime(currentTime); - qboolean ret=G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, - startFrame, endFrame, flags, animSpeed, modelList, ghlInfo->mModelindex); + if (G2_SetupModelPointers(ghlInfo)) { + int aCurrentTime = G2API_GetTime(currentTime); + qboolean ret = G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, + ghlInfo->mModelindex); #ifdef _DEBUG /* assert(*endFrame>0); @@ -1347,29 +1154,23 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo assert(*currentFrame>=0.0f); assert(*currentFrame<100000.0f); */ - if (*endFrame<1) - { - *endFrame=1; + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } - if (*currentFrame<0.0f) - { - *currentFrame=0.0f; + if (*currentFrame < 0.0f) { + *currentFrame = 0.0f; } - if (*currentFrame>100000) - { - *currentFrame=1; + if (*currentFrame > 100000) { + *currentFrame = 1; } #endif return ret; @@ -1377,32 +1178,26 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo return qfalse; } -qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) -{ - assert(startFrame!=endFrame); //this is bad - if (G2_SetupModelPointers(ghlInfo)) - { - qboolean ret=G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); +qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) { + assert(startFrame != endFrame); // this is bad + if (G2_SetupModelPointers(ghlInfo)) { + qboolean ret = G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); #ifdef _DEBUG - assert(*endFrame>0); - assert(*endFrame<100000); - assert(*startFrame>=0); - assert(*startFrame<100000); - if (*endFrame<1) - { - *endFrame=1; + assert(*endFrame > 0); + assert(*endFrame < 100000); + assert(*startFrame >= 0); + assert(*startFrame < 100000); + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } #endif return ret; @@ -1410,217 +1205,119 @@ qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *sta return qfalse; } - -qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); +qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); } return qfalse; } -qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); +qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); } return qfalse; } -qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_SetBoneAnglesIndex( - CGhoul2Info *ghlInfo, - const int index, - const vec3_t angles, - const int flags, - const Eorientations yaw, - const Eorientations pitch, - const Eorientations roll, - qhandle_t *modelList, - int blendTime, - int currentTime) -{ +qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, int blendTime, int currentTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - if (ghlInfo) - { + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles_Index( - ghlInfo->mBlist, - index, - angles, - flags, - yaw, - pitch, - roll, - modelList, - ghlInfo->mModelindex, - blendTime, - currentTime); + return G2_Set_Bone_Angles_Index(ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, modelList, ghlInfo->mModelindex, blendTime, currentTime); } return qfalse; } -qboolean G2API_SetBoneAngles( - CGhoul2Info_v &ghoul2, - const int modelIndex, - const char *boneName, - const vec3_t angles, - const int flags, - const Eorientations up, - const Eorientations left, - const Eorientations forward, - qhandle_t *modelList, - int blendTime, - int currentTime) -{ - if (ghoul2.size() > modelIndex) - { +qboolean G2API_SetBoneAngles(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; // rww - RAGDOLL_BEGIN - if (ghlInfo) - { + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghoul2); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles( - ghlInfo, - ghlInfo->mBlist, - boneName, - angles, - flags, - up, - left, - forward, - modelList, - ghlInfo->mModelindex, - blendTime, - currentTime); + return G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, modelList, ghlInfo->mModelindex, blendTime, + currentTime); } } return qfalse; } -qboolean G2API_SetBoneAnglesMatrixIndex( - CGhoul2Info *ghlInfo, - const int index, - const mdxaBone_t &matrix, - const int flags, - qhandle_t *modelList, - int blendTime, - int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles_Matrix_Index( - ghlInfo->mBlist, - index, - matrix, - flags, - modelList, - ghlInfo->mModelindex, - blendTime, - currentTime); + return G2_Set_Bone_Angles_Matrix_Index(ghlInfo->mBlist, index, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); } return qfalse; } -qboolean G2API_SetBoneAnglesMatrix( - CGhoul2Info *ghlInfo, - const char *boneName, - const mdxaBone_t &matrix, - const int flags, - qhandle_t *modelList, - int blendTime, - int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles_Matrix( - ghlInfo->mFileName, - ghlInfo->mBlist, - boneName, - matrix, - flags, - modelList, - ghlInfo->mModelindex, - blendTime, - currentTime); + return G2_Set_Bone_Angles_Matrix(ghlInfo->mFileName, ghlInfo->mBlist, boneName, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); } return qfalse; } -qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); @@ -1628,71 +1325,54 @@ qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) return qfalse; } -qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Stop_Bone_Angles( - ghlInfo->mFileName, ghlInfo->mBlist, boneName); + return G2_Stop_Bone_Angles(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) -{ +void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (status) - { //turn it on + if (status) { // turn it on ghlInfo->mFlags |= GHOUL2_CRAZY_SMOOTH; - } - else - { //off + } else { // off ghlInfo->mFlags &= ~GHOUL2_CRAZY_SMOOTH; } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN class CRagDollParams; -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms); -void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms) -{ - G2_SetRagDoll(ghoul2,parms); -} +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms); +void G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms) { G2_SetRagDoll(ghoul2, parms); } void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V); -void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) -{ - G2_ResetRagDoll(ghoul2); -} -//rww - RAGDOLL_END +void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) { G2_ResetRagDoll(ghoul2); } +// rww - RAGDOLL_END -qboolean G2API_RemoveBone(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +qboolean G2API_RemoveBone(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); + return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); } return qfalse; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef _DEBUG extern int ragTraceTime; extern int ragSSCount; extern int ragTraceCount; #endif -void G2API_AnimateG2ModelsRag( - CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) -{ +void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) { int model; int currentTime = G2API_GetTime(AcurrentTime); @@ -1703,61 +1383,49 @@ void G2API_AnimateG2ModelsRag( #endif // Walk the list and find all models that are active - for (model = 0; model < ghoul2.size(); model++) - { - if (ghoul2[model].mModel) - { + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModel) { G2_Animate_Bone_List(ghoul2, currentTime, model, params); } } } // rww - RAGDOLL_END -int G2_Find_Bone_Rag( - CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); -#define RAG_PCJ (0x00001) -#define RAG_EFFECTOR (0x00100) +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); +#define RAG_PCJ (0x00001) +#define RAG_EFFECTOR (0x00100) -static boneInfo_t * -G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) -{ +static boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { // can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return NULL; } int boneIndex = G2_Find_Bone_Rag(ghlInfo, ghlInfo->mBlist, boneName); - if (boneIndex < 0) - { // bad bone specification + if (boneIndex < 0) { // bad bone specification return NULL; } boneInfo_t *bone = &ghlInfo->mBlist[boneIndex]; - if (!(bone->flags & BONE_ANGLES_RAGDOLL)) - { // only want to return rag bones + if (!(bone->flags & BONE_ANGLES_RAGDOLL)) { // only want to return rag bones return NULL; } return bone; } -qboolean G2API_RagPCJConstraint( - CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) -{ +qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { // this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1767,18 +1435,14 @@ qboolean G2API_RagPCJConstraint( return qtrue; } -qboolean G2API_RagPCJGradientSpeed( - CGhoul2Info_v &ghoul2, const char *boneName, const float speed) -{ +qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { // this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1787,55 +1451,39 @@ qboolean G2API_RagPCJGradientSpeed( return qtrue; } -qboolean -G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) -{ +qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { // this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } - if (!pos) - { // go back to none in case we have one then + if (!pos) { // go back to none in case we have one then bone->hasOverGoal = false; - } - else - { + } else { VectorCopy(pos, bone->overGoalSpot); bone->hasOverGoal = true; } return qtrue; } -qboolean G2API_GetRagBonePos( - CGhoul2Info_v &ghoul2, - const char *boneName, - vec3_t pos, - vec3_t entAngles, - vec3_t entPos, - vec3_t entScale) -{ //do something? +qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, + vec3_t entScale) { // do something? return qfalse; } -qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) -{ +qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } @@ -1846,167 +1494,104 @@ qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3 return qtrue; } -qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) -{ +qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return qfalse; } - if (force) - { + if (force) { ghlInfo->mFlags |= GHOUL2_RAG_FORCESOLVE; - } - else - { + } else { ghlInfo->mFlags &= ~GHOUL2_RAG_FORCESOLVE; } return qtrue; } -qboolean G2_SetBoneIKState( - CGhoul2Info_v &ghoul2, - int time, - const char *boneName, - int ikState, - sharedSetBoneIKStateParams_t *params); -qboolean G2API_SetBoneIKState( - CGhoul2Info_v &ghoul2, - int time, - const char *boneName, - int ikState, - sharedSetBoneIKStateParams_t *params) -{ +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params); +qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return G2_SetBoneIKState(ghoul2, time, boneName, ikState, params); } -qboolean G2_IKMove( - CGhoul2Info_v &ghoul2, - int time, - sharedIKMoveParams_t *params); -qboolean G2API_IKMove( - CGhoul2Info_v &ghoul2, - int time, - sharedIKMoveParams_t *params) -{ - return G2_IKMove(ghoul2, time, params); -} +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params); +qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { return G2_IKMove(ghoul2, time, params); } -qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Remove_Bolt(ghlInfo->mBltlist, index); } return qfalse; } -int G2API_AddBolt( - CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) -{ +int G2API_AddBolt(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) { // assert(ghoul2.size()>modelIndex); - if (ghoul2.size() > modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Add_Bolt( - ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Add_Bolt(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); } } return -1; } -int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Add_Bolt_Surf_Num( - ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); +int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Add_Bolt_Surf_Num(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); } return -1; } -qboolean G2API_AttachG2Model( - CGhoul2Info_v &ghoul2From, - int modelFrom, - CGhoul2Info_v &ghoul2To, - int toBoltIndex, - int toModel) -{ +qboolean G2API_AttachG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int toBoltIndex, int toModel) { assert(toBoltIndex >= 0); - if (toBoltIndex < 0) - { + if (toBoltIndex < 0) { return qfalse; } - if (G2_SetupModelPointers(ghoul2From) && G2_SetupModelPointers(ghoul2To)) - { + if (G2_SetupModelPointers(ghoul2From) && G2_SetupModelPointers(ghoul2To)) { // make sure we have a model to attach, a model to attach to, and a // bolt on that model if ((ghoul2From.size() > modelFrom) && (ghoul2To.size() > toModel) && - ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || - (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) - { + ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link toModel &= MODEL_AND; toBoltIndex &= BOLT_AND; - ghoul2From[modelFrom].mModelBoltLink = - (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); + ghoul2From[modelFrom].mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); return qtrue; } } return qfalse; } -void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) -{ - if (ghoul2.size() > modelIndex) - { +void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) { + if (ghoul2.size() > modelIndex) { ghoul2[modelIndex].mModelBoltLink = boltInfo; } } -qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - ghlInfo->mModelBoltLink = -1; - return qtrue; +qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { + ghlInfo->mModelBoltLink = -1; + return qtrue; } return qfalse; } -qboolean G2API_AttachEnt( - int *boltInfo, - CGhoul2Info_v &ghoul2, - int modelIndex, - int toBoltIndex, - int entNum, - int toModelNum) -{ +qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info_v &ghoul2, int modelIndex, int toBoltIndex, int entNum, int toModelNum) { CGhoul2Info *ghlInfoTo = &ghoul2[modelIndex]; - if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) - { + if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) { // make sure we have a model to attach, a model to attach to, and a // bolt on that model - if (ghlInfoTo->mBltlist.size() && - ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || - (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if (ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link toModelNum &= MODEL_AND; toBoltIndex &= BOLT_AND; entNum &= ENTITY_AND; - *boltInfo = (toBoltIndex << BOLT_SHIFT) | - (toModelNum << MODEL_SHIFT) | - (entNum << ENTITY_SHIFT); + *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); return qtrue; } } @@ -2016,30 +1601,16 @@ qboolean G2API_AttachEnt( qboolean gG2_GBMNoReconstruct; qboolean gG2_GBMUseSPMethod; -qboolean G2API_GetBoltMatrix_SPMethod( - CGhoul2Info_v &ghoul2, - const int modelIndex, - const int boltIndex, - mdxaBone_t *matrix, - const vec3_t angles, - const vec3_t position, - const int frameNum, - qhandle_t *modelList, - const vec3_t scale) -{ +qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, const vec3_t scale) { assert(ghoul2.size() > modelIndex); - if (ghoul2.size() > modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (ghlInfo && - (boltIndex < (int)ghlInfo->mBltlist.size()) && - boltIndex >= 0) - { + if (ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) && boltIndex >= 0) { // make sure we have transformed the skeleton - if (!gG2_GBMNoReconstruct) - { + if (!gG2_GBMNoReconstruct) { G2_ConstructGhoulSkeleton(ghoul2, frameNum, true, scale); } @@ -2049,23 +1620,19 @@ qboolean G2API_GetBoltMatrix_SPMethod( mdxaBone_t *use; use = &ghlInfo->mBltlist[boltIndex].position; - if (scale[0] || scale[1] || scale[2]) - { + if (scale[0] || scale[1] || scale[2]) { scaled = *use; use = &scaled; // scale the bolt position by the scale factor for this model // since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { scaled.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { scaled.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { scaled.matrix[2][3] *= scale[2]; } } @@ -2089,62 +1656,26 @@ qboolean G2API_GetBoltMatrix_SPMethod( #define G2NOTE(exp, m) ((void)0) #define G2ANIM(ghlInfo, m) ((void)0) bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum); -void G2_GetBoltMatrixLow( - CGhoul2Info &ghoul2, - int boltNum, - const vec3_t scale, - mdxaBone_t &retMatrix); -void G2_GetBoneMatrixLow( - CGhoul2Info &ghoul2, - int boneNum, - const vec3_t scale, - mdxaBone_t &retMatrix, - mdxaBone_t *&retBasepose, - mdxaBone_t *&retBaseposeInv); - -qboolean G2API_GetBoltMatrix( - CGhoul2Info_v &ghoul2, - const int modelIndex, - const int boltIndex, - mdxaBone_t *matrix, - const vec3_t angles, - const vec3_t position, - const int frameNum, - qhandle_t *modelList, - vec3_t scale) -{ +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); + +qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { G2ERROR(matrix, "NULL matrix"); - G2ERROR( - modelIndex >= 0 && modelIndex < ghoul2.size(), - "Invalid ModelIndex"); - const static mdxaBone_t identityMatrix = { - { - {0.0f, -1.0f, 0.0f, 0.0f}, - {1.0f, 0.0f, 0.0f, 0.0f}, - {0.0f, 0.0f, 1.0f, 0.0f} - } - }; + G2ERROR(modelIndex >= 0 && modelIndex < ghoul2.size(), "Invalid ModelIndex"); + const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; G2_GenerateWorldMatrix(angles, position); - if (G2_SetupModelPointers(ghoul2)) - { - if (matrix && modelIndex >= 0 && modelIndex < ghoul2.size()) - { + if (G2_SetupModelPointers(ghoul2)) { + if (matrix && modelIndex >= 0 && modelIndex < ghoul2.size()) { int tframeNum = G2API_GetTime(frameNum); CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - G2ERROR - (boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()), - va("Invalid Bolt Index (%d:%s)", - boltIndex, - ghlInfo->mFileName)); - - if (boltIndex >= 0 && ghlInfo && - (boltIndex < (int)ghlInfo->mBltlist.size())) - { + G2ERROR(boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()), va("Invalid Bolt Index (%d:%s)", boltIndex, ghlInfo->mFileName)); + + if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size())) { mdxaBone_t bolt; - if (G2_NeedsRecalc(ghlInfo, tframeNum)) - { + if (G2_NeedsRecalc(ghlInfo, tframeNum)) { G2_ConstructGhoulSkeleton(ghoul2, tframeNum, true, scale); } @@ -2152,18 +1683,15 @@ qboolean G2API_GetBoltMatrix( // scale the bolt position by the scale factor for this model // since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } @@ -2173,18 +1701,15 @@ qboolean G2API_GetBoltMatrix( Mat3x4_Multiply(matrix, &worldMatrix, &bolt); #if G2API_DEBUG - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 4; j++) - { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { assert(!_isnan(matrix->matrix[i][j])); } } #endif // _DEBUG G2ANIM(ghlInfo, "G2API_GetBoltMatrix"); - if (!gG2_GBMUseSPMethod) - { + if (!gG2_GBMUseSPMethod) { // this is horribly stupid and I hate it. But lots of game // code is written to assume this 90 degree offset thing. mdxaBone_t rotMat, tempMatrix; @@ -2198,56 +1723,42 @@ qboolean G2API_GetBoltMatrix( origin[0] = tempMatrix.matrix[0][3]; origin[1] = tempMatrix.matrix[1][3]; origin[2] = tempMatrix.matrix[2][3]; - tempMatrix.matrix[0][3] = - tempMatrix.matrix[1][3] = - tempMatrix.matrix[2][3] = 0; + tempMatrix.matrix[0][3] = tempMatrix.matrix[1][3] = tempMatrix.matrix[2][3] = 0; Mat3x4_Multiply(matrix, &tempMatrix, &rotMat); matrix->matrix[0][3] = origin[0]; matrix->matrix[1][3] = origin[1]; matrix->matrix[2][3] = origin[2]; - } - else - { // reset it + } else { // reset it gG2_GBMUseSPMethod = qfalse; } return qtrue; } } - } - else - { + } else { G2WARNING(0, "G2API_GetBoltMatrix Failed on empty or bad model"); } Mat3x4_Multiply(matrix, &worldMatrix, (mdxaBone_t *)&identityMatrix); return qfalse; } -void G2API_ListSurfaces(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListSurfaces(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Surfaces(ghlInfo->mFileName); } } -void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Bones(ghlInfo->mFileName, frame); } } // decide if we have Ghoul2 models associated with this ghoul list or not -qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) -{ - if (ghoul2.size()) - { - for (int i = 0; i < ghoul2.size(); i++) - { - if (ghoul2[i].mModelindex != -1) - { +qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) { + if (ghoul2.size()) { + for (int i = 0; i < ghoul2.size(); i++) { + if (ghoul2[i].mModelindex != -1) { return qtrue; } } @@ -2257,11 +1768,7 @@ qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) // run through the Ghoul2 models and set each of the mModel values to the // correct one from the cgs.gameModel offset lsit -void G2API_SetGhoul2ModelIndexes( - CGhoul2Info_v &ghoul2, - qhandle_t *modelList, - qhandle_t *skinList) -{ +void G2API_SetGhoul2ModelIndexes(CGhoul2Info_v &ghoul2, qhandle_t *modelList, qhandle_t *skinList) { return; #if 0 int i; @@ -2284,16 +1791,13 @@ void G2API_SetGhoul2ModelIndexes( #endif } -char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) -{ - model_t *mod_m = R_GetModelByHandle(modelIndex); +char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) { + model_t *mod_m = R_GetModelByHandle(modelIndex); return mod_m->data.glm->header->animName; } -qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetAnimFileName(ghlInfo->mFileName, filename); } return qfalse; @@ -2304,39 +1808,29 @@ qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) SV_QsortEntityNumbers ======================= */ -static int QDECL QsortDistance(const void *a, const void *b) -{ +static int QDECL QsortDistance(const void *a, const void *b) { const float &ea = ((CollisionRecord_t *)a)->mDistance; const float &eb = ((CollisionRecord_t *)b)->mDistance; - if (ea < eb) - { + if (ea < eb) { return -1; } return 1; } -static bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) -{ +static bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) { // see if we need to do another transform bool needTrans = false; - for (auto &bone : g2->mBlist) - { + for (auto &bone : g2->mBlist) { float time; - if (bone.pauseTime) - { + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (frameNum - bone.startTime) / 50.0f; } const int newFrame = bone.startFrame + (time * bone.animSpeed); - if (newFrame < bone.endFrame || - (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || - (bone.flags & BONE_NEED_TRANSFORM)) - { + if (newFrame < bone.endFrame || (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || (bone.flags & BONE_NEED_TRANSFORM)) { // ok, we're gonna have to do it. bone is apparently animating. bone.flags &= ~BONE_NEED_TRANSFORM; needTrans = true; @@ -2346,51 +1840,30 @@ static bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) return needTrans; } -void G2API_CollisionDetectCache( - CollisionRecord_t *collRecMap, - CGhoul2Info_v &ghoul2, - const vec3_t angles, - const vec3_t position, - int frameNumber, - int entNum, - vec3_t rayStart, - vec3_t rayEnd, - vec3_t scale, - IHeapAllocator *G2VertSpace, - int traceFlags, - int useLod, - float fRadius) -{ +void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) { // this will store off the transformed verts for the next trace - this is // slower, but for models that do not animate frequently it is much much // faster. -rww - if (G2_SetupModelPointers(ghoul2)) - { + if (G2_SetupModelPointers(ghoul2)) { vec3_t transRayStart, transRayEnd; int tframeNum = G2API_GetTime(frameNumber); // make sure we have transformed the whole skeletons for each model - if (G2_NeedRetransform(&ghoul2[0], tframeNum) || - !ghoul2[0].mTransformedVertsArray) - { + if (G2_NeedRetransform(&ghoul2[0], tframeNum) || !ghoul2[0].mTransformedVertsArray) { // optimization, only create new transform space if we need to, // otherwise store it off! int i = 0; - while (i < ghoul2.size()) - { + while (i < ghoul2.size()) { CGhoul2Info &g2 = ghoul2[i]; - if (!g2.mTransformedVertsArray || - !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) - { + if (!g2.mTransformedVertsArray || !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) { // reworked so we only alloc once! if we have a pointer, // but not a ghoul2_zonetransalloc flag, then that means it // is a miniheap pointer. Just stomp over it. - int iSize = - g2.currentModel->data.glm->header->numSurfaces * 4; - g2.mTransformedVertsArray = - (size_t *)Z_Malloc(iSize, TAG_GHOUL2, qtrue); + int iSize = g2.currentModel->data.glm->header->numSurfaces * 4; + g2.mTransformedVertsArray = (size_t *)Z_Malloc(iSize, TAG_GHOUL2, qtrue); } g2.mFlags |= GHOUL2_ZONETRANSALLOC; @@ -2402,13 +1875,7 @@ void G2API_CollisionDetectCache( // now having done that, time to build the model #ifdef _G2_GORE - G2_TransformModel( - ghoul2, - frameNumber, - scale, - G2VertSpace, - useLod, - false); + G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod, false); #else G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); #endif @@ -2424,31 +1891,15 @@ void G2API_CollisionDetectCache( // now walk each model and check the ray against each poly - sigh, this // is SO expensive. I wish there was a better way to do this. - G2_TraceModels( - ghoul2, - transRayStart, - transRayEnd, - collRecMap, - entNum, - traceFlags, - useLod, - fRadius + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius #ifdef _G2_GORE - , - 0, - 0, - 0, - 0, - 0, - qfalse + , + 0, 0, 0, 0, 0, qfalse #endif - ); + ); int i; - for (i = 0; - i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; - i++) - { + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) { } // now sort the resulting array of collision records so they are @@ -2457,23 +1908,9 @@ void G2API_CollisionDetectCache( } } -void G2API_CollisionDetect( - CollisionRecord_t *collRecMap, - CGhoul2Info_v &ghoul2, - const vec3_t angles, - const vec3_t position, - int frameNumber, - int entNum, - vec3_t rayStart, - vec3_t rayEnd, - vec3_t scale, - IHeapAllocator *G2VertSpace, - int traceFlags, - int useLod, - float fRadius) -{ - if (G2_SetupModelPointers(ghoul2)) - { +void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) { + if (G2_SetupModelPointers(ghoul2)) { vec3_t transRayStart, transRayEnd; // make sure we have transformed the whole skeletons for each model @@ -2486,8 +1923,7 @@ void G2API_CollisionDetect( // now having done that, time to build the model #ifdef _G2_GORE - G2_TransformModel( - ghoul2, frameNumber, scale, G2VertSpace, useLod, false); + G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod, false); #else G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); #endif @@ -2499,31 +1935,15 @@ void G2API_CollisionDetect( // now walk each model and check the ray against each poly - sigh, this // is SO expensive. I wish there was a better way to do this. - G2_TraceModels( - ghoul2, - transRayStart, - transRayEnd, - collRecMap, - entNum, - traceFlags, - useLod, - fRadius + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius #ifdef _G2_GORE - , - 0, - 0, - 0, - 0, - 0, - qfalse + , + 0, 0, 0, 0, 0, qfalse #endif - ); + ); int i; - for (i = 0; - i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; - i++) - { + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) { } // now sort the resulting array of collision records so they are @@ -2532,10 +1952,8 @@ void G2API_CollisionDetect( } } -qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mFlags &= GHOUL2_NEWORIGIN; ghlInfo->mFlags |= flags; return qtrue; @@ -2543,20 +1961,16 @@ qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) return qfalse; } -int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { return (ghlInfo->mFlags & ~GHOUL2_NEWORIGIN); } return 0; } // given a boltmatrix, return in vec a normalised vector for the axis requested in flags -void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) -{ - switch (flags) - { +void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) { + switch (flags) { case ORIGIN: vec[0] = boltMatrix->matrix[0][3]; vec[1] = boltMatrix->matrix[1][3]; @@ -2566,7 +1980,7 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v vec[0] = boltMatrix->matrix[0][1]; vec[1] = boltMatrix->matrix[1][1]; vec[2] = boltMatrix->matrix[2][1]; - break; + break; case POSITIVE_X: vec[0] = boltMatrix->matrix[0][0]; vec[1] = boltMatrix->matrix[1][0]; @@ -2595,36 +2009,29 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v } } +int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) { + assert(modelIndex == -1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it + // if ya want it, we will add it back correctly -int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) -{ - assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it - // if ya want it, we will add it back correctly - - //G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); - if (g2From.IsValid()) - { + // G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); + if (g2From.IsValid()) { #ifdef _DEBUG - if (g2To.IsValid()) - { + if (g2To.IsValid()) { assert(!"Copying to a valid g2 instance?!"); - if (g2To[0].mBoneCache) - { + if (g2To[0].mBoneCache) { assert(!"Instance has a bonecache too.. it's gonna get stomped"); } } #endif g2To.DeepCopy(g2From); -#ifdef _G2_GORE //check through gore stuff then, as well. +#ifdef _G2_GORE // check through gore stuff then, as well. int model = 0; - while (model < g2To.size()) - { - if ( g2To[model].mGoreSetTag ) - { - CGoreSet* gore = FindGoreSet ( g2To[model].mGoreSetTag ); + while (model < g2To.size()) { + if (g2To[model].mGoreSetTag) { + CGoreSet *gore = FindGoreSet(g2To[model].mGoreSetTag); assert(gore); gore->mRefCount++; } @@ -2632,28 +2039,25 @@ int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int mod model++; } #endif - //G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); - //G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); + // G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); + // G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); } return -1; } -void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) -{ +void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) { #if 0 qboolean forceReconstruct = qtrue; -#endif //model1 was not getting reconstructed like it should for thrown sabers? - //might have been a bug in the reconstruct checking which has since been - //mangled and probably fixed. -rww +#endif // model1 was not getting reconstructed like it should for thrown sabers? + // might have been a bug in the reconstruct checking which has since been + // mangled and probably fixed. -rww // assume we actually have a model to copy from - if (ghoul2From.size() > modelFrom) - { + if (ghoul2From.size() > modelFrom) { // if we don't have enough models on the to side, resize us so we do - if (ghoul2To.size() <= modelTo) - { - assert (modelTo < 5); + if (ghoul2To.size() <= modelTo) { + assert(modelTo < 5); ghoul2To.resize(modelTo + 1); #if 0 forceReconstruct = qtrue; @@ -2661,10 +2065,8 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // do the copy - if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) - { //remove the bonecache before we stomp over this instance. - if (ghoul2To[modelTo].mBoneCache) - { + if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) { // remove the bonecache before we stomp over this instance. + if (ghoul2To[modelTo].mBoneCache) { RemoveBoneCache(ghoul2To[modelTo].mBoneCache); ghoul2To[modelTo].mBoneCache = 0; } @@ -2683,24 +2085,19 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // This version will automatically copy everything about this model, and make a new one if necessary. -void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) -{ - //int ignore; +void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) { + // int ignore; - if (*g2To) - { // This is bad. We only want to do this if there is not yet a to declared. + if (*g2To) { // This is bad. We only want to do this if there is not yet a to declared. assert(0); return; } *g2To = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -2708,51 +2105,44 @@ void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) #endif CGhoul2Info_v &ghoul2 = *(*g2To); - /*ignore = */G2API_CopyGhoul2Instance(g2From, ghoul2, -1); - + /*ignore = */ G2API_CopyGhoul2Instance(g2From, ghoul2, -1); + return; } -char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber) -{ +char *G2API_GetSurfaceName(CGhoul2Info_v &ghoul2, int modelIndex, int surfNumber) { static char noSurface[1] = ""; CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmSurfHierarchy_t *surfInfo = 0; + if (G2_SetupModelPointers(ghlInfo)) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmSurfHierarchy_t *surfInfo = 0; mdxmHeader_t *mdxm; #ifndef FINAL_BUILD - if (!mod || !mod->data.glm || !mod->data.glm->header) - { + if (!mod || !mod->data.glm || !mod->data.glm->header) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad model on instance %s.", ghlInfo->mFileName); } #endif mdxm = mod->data.glm->header; - //ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model - //may have.. but how did they get that surf index to begin with? Oh well. - if (surfNumber < 0 || surfNumber >= mdxm->numSurfaces) - { + // ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model + // may have.. but how did they get that surf index to begin with? Oh well. + if (surfNumber < 0 || surfNumber >= mdxm->numSurfaces) { Com_Printf("G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); return noSurface; } - surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, 0); - if (surf) - { + if (surf) { #ifndef FINAL_BUILD - if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mdxm->numSurfaces) - { + if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mdxm->numSurfaces) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad surf num (%i) on surf for instance %s.", surf->thisSurfaceIndex, ghlInfo->mFileName); } #endif - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->name; } @@ -2760,24 +2150,18 @@ char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber return noSurface; } - -int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetSurfaceIndex(ghlInfo, surfaceName); } return -1; } -char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) -{ - if (G2_SetupModelPointers(ghoul2)) - { - if (ghoul2.size() > modelIndex) - { - //model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - //return mod->mdxm->animName; +char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) { + if (G2_SetupModelPointers(ghoul2)) { + if (ghoul2.size() > modelIndex) { + // model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + // return mod->mdxm->animName; assert(ghoul2[modelIndex].currentModel && ghoul2[modelIndex].currentModel->data.glm); return ghoul2[modelIndex].currentModel->data.glm->header->animName; @@ -2786,27 +2170,19 @@ char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) return NULL; } -qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) -{ +qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { - if (boltIndex < 0) - { - char modelName[MAX_QPATH]; - if (ghlInfo->currentModel && - ghlInfo->currentModel->name[0]) - { + if (G2_SetupModelPointers(ghlInfo)) { + if (boltIndex < 0) { + char modelName[MAX_QPATH]; + if (ghlInfo->currentModel && ghlInfo->currentModel->name[0]) { strcpy(modelName, ghlInfo->currentModel->name); - } - else - { + } else { strcpy(modelName, "None?!"); } @@ -2820,96 +2196,71 @@ qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) return qfalse; } -int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Get_Bone_Index(ghlInfo, boneName); } return -1; } -qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ - return G2_SaveGhoul2Models(ghoul2, buffer, size); -} +qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { return G2_SaveGhoul2Models(ghoul2, buffer, size); } -void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) -{ - G2_LoadGhoul2Model(ghoul2, buffer); -} +void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) { G2_LoadGhoul2Model(ghoul2, buffer); } -void G2API_FreeSaveBuffer(char *buffer) -{ - Z_Free(buffer); -} +void G2API_FreeSaveBuffer(char *buffer) { Z_Free(buffer); } // this is kinda sad, but I need to call the destructor in this module (exe), not the game.dll... // -void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) -{ +void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) { #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif - ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning + ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning } -//see if surfs have any shader info... -qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// see if surfs have any shader info... +qboolean G2API_SkinlessModel(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(g2)) - { - model_t *mod = (model_t *)g2->currentModel; + if (G2_SetupModelPointers(g2)) { + model_t *mod = (model_t *)g2->currentModel; - if (mod && - mod->data.glm && - mod->data.glm->header) - { - mdxmSurfHierarchy_t *surf; + if (mod && mod->data.glm && mod->data.glm->header) { + mdxmSurfHierarchy_t *surf; int i; mdxmHeader_t *mdxm = mod->data.glm->header; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); - for (i = 0; i < mdxm->numSurfaces; i++) - { - if (surf->shader[0]) - { //found a surface with a shader name, ok. - return qfalse; + for (i = 0; i < mdxm->numSurfaces; i++) { + if (surf->shader[0]) { // found a surface with a shader name, ok. + return qfalse; } - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } } } - //found nothing. + // found nothing. return qtrue; } -int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) -{ - return ghoul2.size(); -} +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) { return ghoul2.size(); } //#ifdef _SOF2 #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling -//way of seeing how many marks are on a model currently -rww -int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// way of seeing how many marks are on a model currently -rww +int G2API_GetNumGoreMarks(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (g2->mGoreSetTag) - { + if (g2->mGoreSetTag) { CGoreSet *goreSet = FindGoreSet(g2->mGoreSetTag); - if (goreSet) - { + if (goreSet) { return goreSet->mGoreRecords.size(); } } @@ -2917,25 +2268,20 @@ int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) return 0; } -void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) -{ +void G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { int i; - for (i=0; inumLods,3); //limit to the number of lods the main model has - for(lod=lodbias;lodnumLods, 3); // limit to the number of lods the main model has + for (lod = lodbias; lod < maxLod; lod++) { // now having done that, time to build the model ri.GetG2VertSpaceServer()->ResetHeap(); - G2_TransformModel(ghoul2, gore.currentTime, gore.scale,ri.GetG2VertSpaceServer(),lod,true); + G2_TransformModel(ghoul2, gore.currentTime, gore.scale, ri.GetG2VertSpaceServer(), lod, true); // now walk each model and compute new texture coordinates - G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0,lod,0.0f,gore.SSize,gore.TSize,gore.theta,gore.shader,&gore,qtrue); + G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0, lod, 0.0f, gore.SSize, gore.TSize, gore.theta, gore.shader, &gore, + qtrue); } } #endif qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up { - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } - ghlInfo->mValid=false; - if (ghlInfo->mModelindex != -1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + ghlInfo->mValid = false; + if (ghlInfo->mModelindex != -1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); - if (ghlInfo->currentModel) - { - if (ghlInfo->currentModel->data.glm && - ghlInfo->currentModel->data.glm->header) - { + if (ghlInfo->currentModel) { + if (ghlInfo->currentModel->data.glm && ghlInfo->currentModel->data.glm->header) { mdxmHeader_t *mdxm = ghlInfo->currentModel->data.glm->header; - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=mdxm->ofsEnd) - { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=mdxm->ofsEnd; + ghlInfo->currentModelSize = mdxm->ofsEnd; ghlInfo->animModel = R_GetModelByHandle(mdxm->animIndex); - if (ghlInfo->animModel) - { + if (ghlInfo->animModel) { ghlInfo->aHeader = ghlInfo->animModel->data.gla; - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } return (qboolean)ghlInfo->mValid; } @@ -3044,93 +2375,76 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_SetupModelPointers.Start(); #endif - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } -// if (ghlInfo->mValid && ghlInfo->currentModel) - if (0) - { //rww - Why are we bothering with all this? We can't change models like this anyway. - //This function goes over 200k on the precision timer (in debug, but still), so I'm - //cutting it off here because it gets called constantly. + // if (ghlInfo->mValid && ghlInfo->currentModel) + if (0) { // rww - Why are we bothering with all this? We can't change models like this anyway. + // This function goes over 200k on the precision timer (in debug, but still), so I'm + // cutting it off here because it gets called constantly. #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_SetupModelPointers += G2PerformanceTimer_G2_SetupModelPointers.End(); #endif return qtrue; } - ghlInfo->mValid=false; + ghlInfo->mValid = false; -// G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); - if (ghlInfo->mModelindex != -1) - { - G2ERROR(ghlInfo->mFileName[0],"empty ghlInfo->mFileName"); + // G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); + if (ghlInfo->mModelindex != -1) { + G2ERROR(ghlInfo->mFileName[0], "empty ghlInfo->mFileName"); // RJ - experimental optimization! - if (!ghlInfo->mModel || 1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + if (!ghlInfo->mModel || 1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); } - G2ERROR(ghlInfo->currentModel,va("NULL Model (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel) - { - G2ERROR(ghlInfo->currentModel->modelData,va("Model has no mdxm (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel->data.glm && - ghlInfo->currentModel->data.glm->header) - { + G2ERROR(ghlInfo->currentModel, va("NULL Model (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel) { + G2ERROR(ghlInfo->currentModel->modelData, va("Model has no mdxm (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel->data.glm && ghlInfo->currentModel->data.glm->header) { mdxmHeader_t *mdxm = ghlInfo->currentModel->data.glm->header; - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=mdxm->ofsEnd) - { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=mdxm->ofsEnd; - G2ERROR(ghlInfo->currentModelSize,va("Zero sized Model? (glm) %s",ghlInfo->mFileName)); + ghlInfo->currentModelSize = mdxm->ofsEnd; + G2ERROR(ghlInfo->currentModelSize, va("Zero sized Model? (glm) %s", ghlInfo->mFileName)); ghlInfo->animModel = R_GetModelByHandle(mdxm->animIndex); - G2ERROR(ghlInfo->animModel,va("NULL Model (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->animModel) - { + G2ERROR(ghlInfo->animModel, va("NULL Model (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->animModel) { ghlInfo->aHeader = ghlInfo->animModel->data.gla; - G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + G2ERROR(ghlInfo->aHeader, va("Model has no mdxa (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - G2ERROR(ghlInfo->currentAnimModelSize,va("Zero sized Model? (gla) %s",ghlInfo->mFileName)); - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + G2ERROR(ghlInfo->currentAnimModelSize, va("Zero sized Model? (gla) %s", ghlInfo->mFileName)); + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } #ifdef G2_PERFORMANCE_ANALYSIS @@ -3141,22 +2455,15 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2) // returns true if any model is properly set up { - bool ret=false; + bool ret = false; int i; - for (i=0; imValid); - boltInfo_t tempBolt; + boltInfo_t tempBolt; // first up, make sure have a surface first - if (surfNum >= (int)slist.size()) - { + if (surfNum >= (int)slist.size()) { return -1; } - // look through entire list - see if it's already there first - for(size_t i=0; imValid); - model_t *mod_m = (model_t *)ghlInfo->currentModel; - model_t *mod_a = (model_t *)ghlInfo->animModel; - int x, surfNum = -1; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boltInfo_t tempBolt; - int flags; + model_t *mod_m = (model_t *)ghlInfo->currentModel; + model_t *mod_a = (model_t *)ghlInfo->animModel; + int x, surfNum = -1; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boltInfo_t tempBolt; + int flags; // first up, we'll search for that which this bolt names in all the surfaces - surfNum = G2_IsSurfaceLegal((void*)mod_m, boneName, &flags); + surfNum = G2_IsSurfaceLegal((void *)mod_m, boneName, &flags); // did we find it as a surface? - if (surfNum != -1) - { - // look through entire list - see if it's already there first - for(size_t i=0; idata.gla; - offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mdxa->numBones) - { + if (x == mdxa->numBones) { // didn't find it? Error - //assert(0&&x == mod_a->mdxa->numBones); + // assert(0&&x == mod_a->mdxa->numBones); #ifdef _DEBUG // Com_Printf("WARNING: %s not found on skeleton\n", boneName); #endif @@ -179,11 +155,9 @@ int G2_Add_Bolt(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, } // look through entire list - see if it's already there first - for(size_t i=0; i-1; i--) - { - if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) - { + for (int i = bltlist.size() - 1; i > -1; i--) { + if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != bltlist.size()) - { + if (newSize != bltlist.size()) { // yes, so lets do it bltlist.resize(newSize); } - } return qtrue; } @@ -259,29 +222,20 @@ qboolean G2_Remove_Bolt (boltInfo_v &bltlist, int index) } // set the bolt list to all unused so the bone transformation routine ignores it. -void G2_Init_Bolt_List(boltInfo_v &bltlist) -{ - bltlist.clear(); -} +void G2_Init_Bolt_List(boltInfo_v &bltlist) { bltlist.clear(); } -// remove any bolts that reference original surfaces, generated surfaces, or bones that aren't active anymore -void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) -{ +// remove any bolts that reference original surfaces, generated surfaces, or bones that aren't active anymore +void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) { // walk the bolt list - for (size_t i=0; i #else #include -#endif +#endif #include "ghoul2/G2_gore.h" //#define RAG_TRACE_DEBUG_LINES #include "client/client.h" //while this is all "shared" code, there are some places where we want to make cgame callbacks (for ragdoll) only if the cgvm exists -//rww - RAGDOLL_END +// rww - RAGDOLL_END //===================================================================================================================== // Bone List handling routines - so entities can override bone info on a bone by bone level, and also interrogate this info -// Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the +// Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the // gla file, not the glm file type. -int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; +int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; mdxaHeader_t *mdxa = mod->data.gla; - offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; ioffsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -54,36 +50,32 @@ int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) } // we need to add a bone to the list - find a free one and see if we can find a corresponding bone in the gla file -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) -{ +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { int x; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boneInfo_t tempBone; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boneInfo_t tempBone; mdxaHeader_t *mdxa = mod->data.gla; - //rww - RAGDOLL_BEGIN + // rww - RAGDOLL_BEGIN memset(&tempBone, 0, sizeof(tempBone)); - //rww - RAGDOLL_END - - offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // rww - RAGDOLL_END + + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mdxa->numBones) - { + if (x == mdxa->numBones) { // didn't find it? Error - //assert(0); + // assert(0); #ifdef _DEBUG Com_Printf("WARNING: Failed to add bone %s\n", boneName); #endif @@ -95,24 +87,19 @@ int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) } // look through entire list - see if it's already there first - for(size_t i=0; ioffsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } - } - else - { + } else { // if we found an entry that had a -1 for the bonenumber, then we hit a bone slot that was empty blist[i].boneNumber = x; blist[i].flags = 0; - return i; + return i; } } @@ -123,69 +110,56 @@ int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) tempBone.boneNumber = x; tempBone.flags = 0; blist.push_back(tempBone); - return blist.size()-1; + return blist.size() - 1; } - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) -{ - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { +qboolean G2_Remove_Bone_Index(boneInfo_v &blist, int index) { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // check the flags first - if it's still being used Do NOT remove it - if (!blist[index].flags) - { + if (!blist[index].flags) { // set this bone to not used blist[index].boneNumber = -1; - unsigned int newSize = blist.size(); + unsigned int newSize = blist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=blist.size()-1; i>-1; i--) - { - if (blist[i].boneNumber == -1) - { + for (int i = blist.size() - 1; i > -1; i--) { + if (blist[i].boneNumber == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != blist.size()) - { + if (newSize != blist.size()) { // yes, so lets do it blist.resize(newSize); } - + return qtrue; } } -// assert(0); + // assert(0); // no return qfalse; } // given a bone number, see if there is an override bone in the bone list -int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) -{ +int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) { // look through entire list - for(size_t i=0; ioffsets[blist[index].boneNumber]); - Mat3x4_Multiply(&temp1, boneOverride,&skel->BasePoseMatInv); - Mat3x4_Multiply(boneOverride,&skel->BasePoseMat, &temp1); - - } - else - { + Mat3x4_Multiply(&temp1, boneOverride, &skel->BasePoseMatInv); + Mat3x4_Multiply(boneOverride, &skel->BasePoseMat, &temp1); + + } else { VectorCopy(angles, newAngles); // why I should need do this Fuck alone knows. But I do. - if (left == POSITIVE_Y) - { - newAngles[0] +=180; + if (left == POSITIVE_Y) { + newAngles[0] += 180; } Create_Matrix(newAngles, &temp1); @@ -327,13 +291,12 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[2][0] = permutation.matrix[2][1] = permutation.matrix[2][2] = permutation.matrix[2][3] = 0; // determine what axis newAngles Yaw should revolve around - switch (forward) - { + switch (forward) { case NEGATIVE_X: - permutation.matrix[0][0] = -1; // works + permutation.matrix[0][0] = -1; // works break; case POSITIVE_X: - permutation.matrix[0][0] = 1; // works + permutation.matrix[0][0] = 1; // works break; case NEGATIVE_Y: permutation.matrix[1][0] = -1; @@ -352,8 +315,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles pitch should revolve around - switch (left) - { + switch (left) { case NEGATIVE_X: permutation.matrix[0][1] = -1; break; @@ -361,10 +323,10 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[0][1] = 1; break; case NEGATIVE_Y: - permutation.matrix[1][1] = -1; // works + permutation.matrix[1][1] = -1; // works break; case POSITIVE_Y: - permutation.matrix[1][1] = 1; // works + permutation.matrix[1][1] = 1; // works break; case NEGATIVE_Z: permutation.matrix[2][1] = -1; @@ -377,8 +339,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles Roll should revolve around - switch (up) - { + switch (up) { case NEGATIVE_X: permutation.matrix[0][2] = -1; break; @@ -392,74 +353,54 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[1][2] = 1; break; case NEGATIVE_Z: - permutation.matrix[2][2] = -1; // works + permutation.matrix[2][2] = -1; // works break; case POSITIVE_Z: - permutation.matrix[2][2] = 1; // works + permutation.matrix[2][2] = 1; // works break; default: break; } - Mat3x4_Multiply(boneOverride, &temp1,&permutation); - + Mat3x4_Multiply(boneOverride, &temp1, &permutation); } // keep a copy of the matrix in the newmatrix which is actually what we use memcpy(&blist[index].newMatrix, &blist[index].matrix, sizeof(mdxaBone_t)); - } //========================================================================================= //// Public Bone Routines - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ +qboolean G2_Remove_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { int index; assert(ghlInfo->animModel); index = G2_Find_Bone(ghlInfo->animModel, blist, boneName); - + return G2_Remove_Bone_Index(blist, index); } #define DEBUG_PCJ (0) - // Given a model handle, and a bone name, we want to set angles specifically // for overriding -qboolean G2_Set_Bone_Angles_Index( - boneInfo_v &blist, - const int index, - const float *angles, - const int flags, - const Eorientations yaw, - const Eorientations pitch, - const Eorientations roll, - qhandle_t *modelList, - const int modelIndex, - const int blendTime, - const int currentTime) -{ - if ( index >= (int)blist.size() || blist[index].boneNumber == -1 ) - { +qboolean G2_Set_Bone_Angles_Index(boneInfo_v &blist, const int index, const float *angles, const int flags, const Eorientations yaw, const Eorientations pitch, + const Eorientations roll, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + if (index >= (int)blist.size() || blist[index].boneNumber == -1) { // we are attempting to set a bone override that doesn't exist return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { // don't accept any calls on ragdoll bones return qtrue; } } - - if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) - { + + if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) { // you CANNOT call this with an index with these kinds of bone // overrides - we need the model details for these kinds of bone angle // overrides @@ -473,17 +414,7 @@ qboolean G2_Set_Bone_Angles_Index( blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf( - "PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", - index, - currentTime, - angles[0], - angles[1], - angles[2], - yaw, - pitch, - roll, - flags); + Com_OPrintf("PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], yaw, pitch, roll, flags); #endif G2_Generate_Matrix(nullptr, blist, index, angles, flags, yaw, pitch, roll); @@ -492,21 +423,18 @@ qboolean G2_Set_Bone_Angles_Index( } // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, - const int flags, const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_a; +qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, const int modelIndex, const int blendTime, + const int currentTime) { + model_t *mod_a; mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - + int index = G2_Find_Bone(mod_a, blist, boneName); + // did we find it? - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } @@ -516,7 +444,7 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); @@ -527,43 +455,37 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); return qtrue; } -// assert(0); - //Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. + // assert(0); + // Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. // no return qfalse; } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, - const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, - const int modelIndex, const int blendTime, const int currentTime) -{ +qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + const int modelIndex, const int blendTime, const int currentTime) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } @@ -576,36 +498,28 @@ qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_m; - if (!fileName[0]) - { +qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, const int flags, + qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + model_t *mod_m; + if (!fileName[0]) { mod_m = R_GetModelByHandle(modelList[modelIndex]); - } - else - { + } else { mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); } - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); - - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -619,8 +533,7 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -637,108 +550,76 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons #define DEBUG_G2_TIMING (0) -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim_Index( - boneInfo_v &blist, - const int index, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime, - const int numFrames) -{ - int modFlags = flags; - - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int currentTime, const float setFrame, const int blendTime, const int numFrames) { + int modFlags = flags; + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } - //mark it for needing a transform for the cached trace transform stuff + // mark it for needing a transform for the cached trace transform stuff blist[index].flags |= BONE_NEED_TRANSFORM; } - if (setFrame != -1) - { + if (setFrame != -1) { assert((setFrame >= startFrame) && (setFrame <= endFrame)); } - if (flags & BONE_ANIM_BLEND) - { - float currentFrame, animSpeed; - int startFrame, endFrame, flags; + if (flags & BONE_ANIM_BLEND) { + float currentFrame, animSpeed; + int startFrame, endFrame, flags; // figure out where we are now - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) - { - if (blist[index].blendStart == currentTime) //we're replacing a blend in progress which hasn't started + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) { + if (blist[index].blendStart == currentTime) // we're replacing a blend in progress which hasn't started { // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; - } - else - { - if (animSpeed<0.0f) - { + } else { + if (animSpeed < 0.0f) { blist[index].blendFrame = floor(currentFrame); blist[index].blendLerpFrame = floor(currentFrame); - } - else - { + } else { blist[index].blendFrame = currentFrame; - blist[index].blendLerpFrame = currentFrame+1; - + blist[index].blendLerpFrame = currentFrame + 1; + // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendFrame >= endFrame ) - { - // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].blendFrame >= endFrame) { + // we only want to lerp with the first frame of the anim if we are looping + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { - blist[index].blendFrame = endFrame -1; + } else { + blist[index].blendFrame = endFrame - 1; } } } - + // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendLerpFrame >= endFrame ) - { - // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].blendLerpFrame >= endFrame) { + // we only want to lerp with the first frame of the anim if we are looping + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendLerpFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { + } else { blist[index].blendLerpFrame = endFrame - 1; } } @@ -747,19 +628,15 @@ qboolean G2_Set_Bone_Anim_Index( // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; blist[index].blendStart = currentTime; - } } // hmm, we weren't animating on this bone. In which case disable the blend - else - { + else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = 0; modFlags &= ~(BONE_ANIM_BLEND); } - } - else - { + } else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = blist[index].blendStart = 0; // we aren't blending, so remove the option to do so @@ -771,108 +648,66 @@ qboolean G2_Set_Bone_Anim_Index( blist[index].animSpeed = animSpeed; blist[index].pauseTime = 0; // start up the animation:) - if (setFrame != -1) - { - blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); - } - else - { + if (setFrame != -1) { + blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0) / animSpeed)); + } else { blist[index].lastTime = blist[index].startTime = currentTime; } blist[index].flags &= ~(BONE_ANIM_TOTAL); - if (blist[index].flags < 0) - { + if (blist[index].flags < 0) { blist[index].flags = 0; } blist[index].flags |= modFlags; #if DEBUG_G2_TIMING - if (index==2) - { - const boneInfo_t &bone=blist[index]; + if (index == 2) { + const boneInfo_t &bone = blist[index]; char mess[1000]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess,"sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, "sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", index, currentTime, bone.startTime, bone.startFrame, + bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, "saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", index, currentTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, + bone.flags); } - else - { - sprintf(mess,"saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); - } - Com_OPrintf("%s",mess); + Com_OPrintf("%s", mess); } #endif return qtrue; - } -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, - boneInfo_v &blist, - const char *boneName, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - if (index == -1) - { + int index = G2_Find_Bone(mod_a, blist, boneName); + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } - if (index != -1) - { - return G2_Set_Bone_Anim_Index(blist,index,startFrame,endFrame,flags,animSpeed,currentTime,setFrame,blendTime,ghlInfo->aHeader->numFrames); + if (index != -1) { + return G2_Set_Bone_Anim_Index(blist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); } return qfalse; } -qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - +qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) { + model_t *mod_a = (model_t *)ghlInfo->animModel; + int index = G2_Find_Bone(mod_a, blist, boneName); + // did we find it? - if (index != -1) - { + if (index != -1) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; return qtrue; @@ -883,24 +718,21 @@ qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const c // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp); + +qboolean G2_Get_Bone_Anim_Index(boneInfo_v &blist, const int index, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *retAnimSpeed, qhandle_t *modelList, int numFrames) { -qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int numFrames) -{ - // did we find it? - if ((index>=0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) - { + if ((index >= 0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - int lcurrentFrame,newFrame; + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + int lcurrentFrame, newFrame; float lerp; - G2_TimingModel(blist[index],currentTime,numFrames,lcurrentFrame,newFrame,lerp); + G2_TimingModel(blist[index], currentTime, numFrames, lcurrentFrame, newFrame, lerp); - *currentFrame =float(lcurrentFrame)+lerp; + *currentFrame = float(lcurrentFrame) + lerp; *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; *flags = blist[index].flags; @@ -908,40 +740,36 @@ qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int c return qtrue; } } - *startFrame=0; - *endFrame=1; - *currentFrame=0.0f; - *flags=0; - *retAnimSpeed=0.0f; + *startFrame = 0; + *endFrame = 1; + *currentFrame = 0.0f; + *flags = 0; + *retAnimSpeed = 0.0f; return qfalse; } // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - - if (index==-1) - { + int index = G2_Find_Bone(mod_a, blist, boneName); + + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); - if (index == -1) - { + if (index == -1) { return qfalse; } } - + assert(ghlInfo->aHeader); - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) - { - assert(*startFrame>=0&&*startFrameaHeader->numFrames); - assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); - assert(*currentFrame>=0.0f&&((int)(*currentFrame))aHeader->numFrames); + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) { + assert(*startFrame >= 0 && *startFrame < ghlInfo->aHeader->numFrames); + assert(*endFrame > 0 && *endFrame <= ghlInfo->aHeader->numFrames); + assert(*currentFrame >= 0.0f && ((int)(*currentFrame)) < ghlInfo->aHeader->numFrames); return qtrue; } @@ -949,20 +777,17 @@ qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *b } // given a model, bonelist and bonename, lets pause an anim if it's playing. -qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; + + int index = G2_Find_Bone(mod_a, blist, boneName); - int index = G2_Find_Bone(mod_a, blist, boneName); - // did we find it? - if (index != -1) - { + if (index != -1) { // are we pausing or un pausing? - if (blist[index].pauseTime) - { - int startFrame, endFrame, flags; - float currentFrame, animSpeed; + if (blist[index].pauseTime) { + int startFrame, endFrame, flags; + float currentFrame, animSpeed; // figure out what frame we are on now G2_Get_Bone_Anim(ghlInfo, blist, boneName, blist[index].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, 0); @@ -972,11 +797,10 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].pauseTime = 0; } // ahh, just pausing, the easy bit - else - { + else { blist[index].pauseTime = currentTime; } - + return qtrue; } assert(0); @@ -984,18 +808,15 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char return qfalse; } -qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); - +qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + // did we find it? - if (index != -1) - { + if (index != -1) { // are we paused? - if (blist[index].pauseTime) - { + if (blist[index].pauseTime) { // yup. paused. return qtrue; } @@ -1006,11 +827,9 @@ qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneNa } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) -{ - - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { +qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) { + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -1022,15 +841,13 @@ qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); - +qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANIM_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1041,32 +858,27 @@ qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char * } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) -{ - - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { +qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) { + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; - } + } blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); - } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); - +qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1076,76 +888,56 @@ qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char return qfalse; } - // actually walk the bone list and update each and every bone if we have ended an animation for them. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index ) -{ +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index) { boneInfo_v &blist = ghoul2[index].mBlist; // look through entire list - for(size_t i=0; i 0.0f) && (newFrame_g > endFrame-1 )) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1 ))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { - if (newFrame_g <= endFrame+1) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + if (animSpeed < 0.0f) { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } - } - else - { - if (newFrame_g >= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } } // figure out new start time - float frameTime = newFrame_g - blist[i].startFrame ; + float frameTime = newFrame_g - blist[i].startFrame; blist[i].startTime = currentTime - (int)((frameTime / animSpeed) * 50.0f); - if (blist[i].startTime>currentTime) - { - blist[i].startTime=currentTime; + if (blist[i].startTime > currentTime) { + blist[i].startTime = currentTime; } assert(blist[i].startTime <= currentTime); blist[i].lastTime = blist[i].startTime; - } - else - { - if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) - { + } else { + if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) { // nope, just stop it. And remove the bone if possible G2_Stop_Bone_Index(blist, i, (BONE_ANIM_TOTAL)); } @@ -1157,136 +949,127 @@ void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const in } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN /* rag stuff */ -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool LimitAngles,CRagDollUpdateParams *params = NULL); -static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale); -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V,const vec3_t currentOrg,CRagDollUpdateParams *params, int curTime); -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered); - -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum); +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool LimitAngles, + CRagDollUpdateParams *params = NULL); +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V, int g2Index, int frameNum, const vec3_t angles, const vec3_t position, const vec3_t scale); +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime); +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered); + +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv); +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum); #define MAX_BONES_RAG (256) -struct SRagEffector -{ - vec3_t currentOrigin; - vec3_t desiredDirection; - vec3_t desiredOrigin; - float radius; - float weight; +struct SRagEffector { + vec3_t currentOrigin; + vec3_t desiredDirection; + vec3_t desiredOrigin; + float radius; + float weight; }; -#define RAG_MASK (CONTENTS_SOLID|CONTENTS_TERRAIN)//|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) +#define RAG_MASK \ + (CONTENTS_SOLID | \ + CONTENTS_TERRAIN) //|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) -extern cvar_t *broadsword; -extern cvar_t *broadsword_kickbones; -extern cvar_t *broadsword_kickorigin; -extern cvar_t *broadsword_dontstopanim; -extern cvar_t *broadsword_waitforshot; -extern cvar_t *broadsword_playflop; +extern cvar_t *broadsword; +extern cvar_t *broadsword_kickbones; +extern cvar_t *broadsword_kickorigin; +extern cvar_t *broadsword_dontstopanim; +extern cvar_t *broadsword_waitforshot; +extern cvar_t *broadsword_playflop; -extern cvar_t *broadsword_effcorr; +extern cvar_t *broadsword_effcorr; -extern cvar_t *broadsword_ragtobase; +extern cvar_t *broadsword_ragtobase; -extern cvar_t *broadsword_dircap; +extern cvar_t *broadsword_dircap; -extern cvar_t *broadsword_extra1; -extern cvar_t *broadsword_extra2; +extern cvar_t *broadsword_extra1; +extern cvar_t *broadsword_extra2; -#define RAG_PCJ (0x00001) -#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well -#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well -#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well -#define RAG_EFFECTOR (0x00100) -#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint -#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint -#define RAG_BONE_LIGHTWEIGHT (0x04000) //used to indicate a bone's velocity treatment -#define RAG_PCJ_IK_CONTROLLED (0x08000) //controlled from IK move input -#define RAG_UNSNAPPABLE (0x10000) //cannot be broken out of constraints ever +#define RAG_PCJ (0x00001) +#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well +#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well +#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well +#define RAG_EFFECTOR (0x00100) +#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint +#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint +#define RAG_BONE_LIGHTWEIGHT (0x04000) // used to indicate a bone's velocity treatment +#define RAG_PCJ_IK_CONTROLLED (0x08000) // controlled from IK move input +#define RAG_UNSNAPPABLE (0x10000) // cannot be broken out of constraints ever // thiese flags are on the model and correspond to... //#define GHOUL2_RESERVED_FOR_RAGDOLL 0x0ff0 // these are not defined here for dependecies sake -#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll -#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim -#define GHOUL2_RAG_DONE 0x0200 // got end death anim -#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event -#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll +#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim +#define GHOUL2_RAG_DONE 0x0200 // got end death anim +#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event +#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled //#define flrand Q_flrand -static mdxaBone_t* ragBasepose[MAX_BONES_RAG]; -static mdxaBone_t* ragBaseposeInv[MAX_BONES_RAG]; -static mdxaBone_t ragBones[MAX_BONES_RAG]; -static SRagEffector ragEffectors[MAX_BONES_RAG]; -static boneInfo_t *ragBoneData[MAX_BONES_RAG]; -static int tempDependents[MAX_BONES_RAG]; -static int ragBlistIndex[MAX_BONES_RAG]; -static int numRags; -static vec3_t ragBoneMins; -static vec3_t ragBoneMaxs; -static vec3_t ragBoneCM; -static bool haveDesiredPelvisOffset=false; -static vec3_t desiredPelvisOffset; // this is for the root -static float ragOriginChange=0.0f; -static vec3_t ragOriginChangeDir; -//debug +static mdxaBone_t *ragBasepose[MAX_BONES_RAG]; +static mdxaBone_t *ragBaseposeInv[MAX_BONES_RAG]; +static mdxaBone_t ragBones[MAX_BONES_RAG]; +static SRagEffector ragEffectors[MAX_BONES_RAG]; +static boneInfo_t *ragBoneData[MAX_BONES_RAG]; +static int tempDependents[MAX_BONES_RAG]; +static int ragBlistIndex[MAX_BONES_RAG]; +static int numRags; +static vec3_t ragBoneMins; +static vec3_t ragBoneMaxs; +static vec3_t ragBoneCM; +static bool haveDesiredPelvisOffset = false; +static vec3_t desiredPelvisOffset; // this is for the root +static float ragOriginChange = 0.0f; +static vec3_t ragOriginChangeDir; +// debug #if 0 static vec3_t handPos={0,0,0}; static vec3_t handPos2={0,0,0}; #endif -enum ERagState -{ - ERS_DYNAMIC, - ERS_SETTLING, - ERS_SETTLED -}; -static int ragState; - -static std::vector rag; // once we get the dependents precomputed this can be local +enum ERagState { ERS_DYNAMIC, ERS_SETTLING, ERS_SETTLED }; +static int ragState; +static std::vector rag; // once we get the dependents precomputed this can be local static void G2_Generate_MatrixRag( - // caution this must not be called before the whole skeleton is "remembered" - boneInfo_v &blist, - int index) -{ - + // caution this must not be called before the whole skeleton is "remembered" + boneInfo_v &blist, int index) { - boneInfo_t &bone=blist[index];//.sent; + boneInfo_t &bone = blist[index]; //.sent; - memcpy(&bone.matrix,&bone.ragOverrideMatrix, sizeof(mdxaBone_t)); + memcpy(&bone.matrix, &bone.ragOverrideMatrix, sizeof(mdxaBone_t)); #ifdef _DEBUG - int i,j; - for (i = 0; i < 3; i++ ) - { - for (j = 0; j < 4; j++ ) - { - assert( !Q_isnan(bone.matrix.matrix[i][j])); + int i, j; + for (i = 0; i < 3; i++) { + for (j = 0; j < 4; j++) { + assert(!Q_isnan(bone.matrix.matrix[i][j])); } } -#endif// _DEBUG - memcpy(&blist[index].newMatrix,&bone.matrix, sizeof(mdxaBone_t)); +#endif // _DEBUG + memcpy(&blist[index].newMatrix, &bone.matrix, sizeof(mdxaBone_t)); } -int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); /* @@ -1301,112 +1084,84 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa aHeader = animModel->mdxa; assert(aHeader); - offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); */ // look through entire list - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); - //skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + // skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } #if _DEBUG // G2_Bone_Not_Found(boneName,ghlInfo->mFileName); -#endif +#endif // didn't find it return -1; } -static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - CGhoul2Info &ghoul2, - const vec3_t scale, - const vec3_t origin) -{ +static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, CGhoul2Info &ghoul2, const vec3_t scale, const vec3_t origin) { // do not change the state of the skeleton here - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; - VectorCopy(origin,bone.extraVec1); + if (index != -1) { + boneInfo_t &bone = blist[index]; + VectorCopy(origin, bone.extraVec1); - G2_GetBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.originalTrueBoneMatrix,bone.basepose,bone.baseposeInv); -// bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); - bone.originalOrigin[0]=bone.originalTrueBoneMatrix.matrix[0][3]; - bone.originalOrigin[1]=bone.originalTrueBoneMatrix.matrix[1][3]; - bone.originalOrigin[2]=bone.originalTrueBoneMatrix.matrix[2][3]; + G2_GetBoneMatrixLow(ghoul2, bone.boneNumber, scale, bone.originalTrueBoneMatrix, bone.basepose, bone.baseposeInv); + // bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); + bone.originalOrigin[0] = bone.originalTrueBoneMatrix.matrix[0][3]; + bone.originalOrigin[1] = bone.originalTrueBoneMatrix.matrix[1][3]; + bone.originalOrigin[2] = bone.originalTrueBoneMatrix.matrix[2][3]; } return index; } -static int G2_Set_Bone_Angles_Rag( - CGhoul2Info &ghoul2, - const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - const int flags, - const float radius, - const vec3_t angleMin=0, - const vec3_t angleMax=0, - const int blendTime=500) -{ - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); +static int G2_Set_Bone_Angles_Rag(CGhoul2Info &ghoul2, const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, const int flags, const float radius, + const vec3_t angleMin = 0, const vec3_t angleMax = 0, const int blendTime = 500) { + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; + if (index != -1) { + boneInfo_t &bone = blist[index]; bone.flags &= ~(BONE_ANGLES_TOTAL); bone.flags |= BONE_ANGLES_RAGDOLL; - if (flags&RAG_PCJ) - { - if (flags&RAG_PCJ_POST_MULT) - { + if (flags & RAG_PCJ) { + if (flags & RAG_PCJ_POST_MULT) { bone.flags |= BONE_ANGLES_POSTMULT; - } - else if (flags&RAG_PCJ_MODEL_ROOT) - { + } else if (flags & RAG_PCJ_MODEL_ROOT) { bone.flags |= BONE_ANGLES_PREMULT; -// bone.flags |= BONE_ANGLES_POSTMULT; - } - else - { + // bone.flags |= BONE_ANGLES_POSTMULT; + } else { assert(!"Invalid RAG PCJ\n"); } } - bone.ragStartTime=G2API_GetTime(0); + bone.ragStartTime = G2API_GetTime(0); bone.boneBlendStart = bone.ragStartTime; bone.boneBlendTime = blendTime; - bone.radius=radius; - bone.weight=1.0f; + bone.radius = radius; + bone.weight = 1.0f; - //init the others to valid values + // init the others to valid values bone.epGravFactor = 0; VectorClear(bone.epVelocity); bone.solidCount = 0; @@ -1422,48 +1177,37 @@ static int G2_Set_Bone_Angles_Rag( bone.hasOverGoal = false; bone.hasAnimFrameMatrix = -1; -// bone.weight=pow(radius,1.7f); //cubed was too harsh -// bone.weight=radius*radius*radius; - if (angleMin&&angleMax) - { - VectorCopy(angleMin,bone.minAngles); - VectorCopy(angleMax,bone.maxAngles); - } - else - { - VectorCopy(bone.currentAngles,bone.minAngles); // I guess this isn't a rag pcj then - VectorCopy(bone.currentAngles,bone.maxAngles); - } - if (!bone.lastTimeUpdated) - { - static mdxaBone_t id = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - memcpy(&bone.ragOverrideMatrix,&id, sizeof(mdxaBone_t)); + // bone.weight=pow(radius,1.7f); //cubed was too harsh + // bone.weight=radius*radius*radius; + if (angleMin && angleMax) { + VectorCopy(angleMin, bone.minAngles); + VectorCopy(angleMax, bone.maxAngles); + } else { + VectorCopy(bone.currentAngles, bone.minAngles); // I guess this isn't a rag pcj then + VectorCopy(bone.currentAngles, bone.maxAngles); + } + if (!bone.lastTimeUpdated) { + static mdxaBone_t id = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + memcpy(&bone.ragOverrideMatrix, &id, sizeof(mdxaBone_t)); VectorClear(bone.anglesOffset); VectorClear(bone.positionOffset); - VectorClear(bone.velocityEffector); // this is actually a velocity now - VectorClear(bone.velocityRoot); // this is actually a velocity now + VectorClear(bone.velocityEffector); // this is actually a velocity now + VectorClear(bone.velocityRoot); // this is actually a velocity now VectorClear(bone.lastPosition); VectorClear(bone.lastShotDir); - bone.lastContents=0; + bone.lastContents = 0; // if this is non-zero, we are in a dynamic state - bone.firstCollisionTime=bone.ragStartTime; + bone.firstCollisionTime = bone.ragStartTime; // if this is non-zero, we are in a settling state - bone.restTime=0; + bone.restTime = 0; // if they are both zero, we are in a settled state - bone.firstTime=0; + bone.firstTime = 0; - bone.RagFlags=flags; - bone.DependentRagIndexMask=0; + bone.RagFlags = flags; + bone.DependentRagIndexMask = 0; - G2_Generate_MatrixRag(blist,index); // set everything to th id + G2_Generate_MatrixRag(blist, index); // set everything to th id #if 0 VectorClear(bone.currentAngles); @@ -1471,32 +1215,25 @@ static int G2_Set_Bone_Angles_Rag( // VectorScale(bone.currentAngles,0.5f,bone.currentAngles); #else { - if ( - (flags&RAG_PCJ_MODEL_ROOT) || - (flags&RAG_PCJ_PELVIS) || - !(flags&RAG_PCJ)) - { + if ((flags & RAG_PCJ_MODEL_ROOT) || (flags & RAG_PCJ_PELVIS) || !(flags & RAG_PCJ)) { VectorClear(bone.currentAngles); - } - else - { + } else { int k; - for (k=0;k<3;k++) - { - float scalar=flrand(-1.0f,1.0f); - scalar*=flrand(-1.0f,1.0f)*flrand(-1.0f,1.0f); + for (k = 0; k < 3; k++) { + float scalar = flrand(-1.0f, 1.0f); + scalar *= flrand(-1.0f, 1.0f) * flrand(-1.0f, 1.0f); // this is a heavily central distribution // center it on .5 (and make it small) - scalar*=0.5f; - scalar+=0.5f; + scalar *= 0.5f; + scalar += 0.5f; - bone.currentAngles[k]=(bone.minAngles[k]-bone.maxAngles[k])*scalar+bone.maxAngles[k]; + bone.currentAngles[k] = (bone.minAngles[k] - bone.maxAngles[k]) * scalar + bone.maxAngles[k]; } } } // VectorClear(bone.currentAngles); #endif - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); } } return index; @@ -1505,50 +1242,43 @@ static int G2_Set_Bone_Angles_Rag( class CRagDollParams; const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2); - -static void G2_RagDollMatchPosition() -{ - haveDesiredPelvisOffset=false; +static void G2_RagDollMatchPosition() { + haveDesiredPelvisOffset = false; int i; - for (i=0;inumBones); -#else //The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list - //and let them re-set their anims/angles gameside. +#else // The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list + // and let them re-set their anims/angles gameside. int i = 0; - while (i < blist.size()) - { + while (i < blist.size()) { boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) - { + if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -1634,96 +1356,70 @@ void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V) i++; } #endif - ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED); + ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED); } -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) -{ - if (parms) - { - parms->CallRagDollBegin=qfalse; +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms) { + if (parms) { + parms->CallRagDollBegin = qfalse; } - if (!broadsword||!broadsword->integer||!parms) - { + if (!broadsword || !broadsword->integer || !parms) { return; } int model; - for (model = 0; model < ghoul2V.size(); model++) - { - if (ghoul2V[model].mModelindex != -1) - { + for (model = 0; model < ghoul2V.size(); model++) { + if (ghoul2V[model].mModelindex != -1) { break; } } - if (model==ghoul2V.size()) - { + if (model == ghoul2V.size()) { return; } - CGhoul2Info &ghoul2=ghoul2V[model]; - const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); - if (!mod_a) - { + CGhoul2Info &ghoul2 = ghoul2V[model]; + const mdxaHeader_t *mod_a = G2_GetModA(ghoul2); + if (!mod_a) { return; } - int curTime=G2API_GetTime(0); + int curTime = G2API_GetTime(0); boneInfo_v &blist = ghoul2.mBlist; - int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); - switch (parms->RagPhase) - { + int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); + switch (parms->RagPhase) { case CRagDollParams::RP_START_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING; - return; /// not doing anything with this yet + ghoul2.mFlags |= GHOUL2_RAG_PENDING; + return; /// not doing anything with this yet break; case CRagDollParams::RP_END_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE; - if (broadsword_waitforshot && - broadsword_waitforshot->integer) - { - if (broadsword_waitforshot->integer==2) - { - if (!(ghoul2.mFlags&(GHOUL2_RAG_COLLISION_DURING_DEATH|GHOUL2_RAG_COLLISION_SLIDE))) - { - //nothing was encountered, lets just wait for the first shot + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE; + if (broadsword_waitforshot && broadsword_waitforshot->integer) { + if (broadsword_waitforshot->integer == 2) { + if (!(ghoul2.mFlags & (GHOUL2_RAG_COLLISION_DURING_DEATH | GHOUL2_RAG_COLLISION_SLIDE))) { + // nothing was encountered, lets just wait for the first shot return; // we ain't starting yet } - } - else - { + } else { return; // we ain't starting yet } } break; case CRagDollParams::RP_DEATH_COLLISION: - if (parms->collisionType) - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_SLIDE; - } - else - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_DURING_DEATH; + if (parms->collisionType) { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_SLIDE; + } else { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_DURING_DEATH; } - if (broadsword_dontstopanim && broadsword_waitforshot && - (broadsword_dontstopanim->integer || broadsword_waitforshot->integer) - ) - { - if (!(ghoul2.mFlags&GHOUL2_RAG_DONE)) - { + if (broadsword_dontstopanim && broadsword_waitforshot && (broadsword_dontstopanim->integer || broadsword_waitforshot->integer)) { + if (!(ghoul2.mFlags & GHOUL2_RAG_DONE)) { return; // we ain't starting yet } } break; case CRagDollParams::RP_CORPSE_SHOT: - if (broadsword_kickorigin && - broadsword_kickorigin->integer) - { - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - //rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. + if (broadsword_kickorigin && broadsword_kickorigin->integer) { + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + // rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. /* float magicFactor14=8.0f; //64.0f; // kick strength @@ -1748,29 +1444,22 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) } break; case CRagDollParams::RP_GET_PELVIS_OFFSET: - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { VectorClear(parms->pelvisAnglesOffset); VectorClear(parms->pelvisPositionOffset); } // intentional lack of a break case CRagDollParams::RP_SET_PELVIS_OFFSET: - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { - VectorCopy(bone.anglesOffset,parms->pelvisAnglesOffset); - VectorCopy(bone.positionOffset,parms->pelvisPositionOffset); - } - else - { - VectorCopy(parms->pelvisAnglesOffset,bone.anglesOffset); - VectorCopy(parms->pelvisPositionOffset,bone.positionOffset); + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { + VectorCopy(bone.anglesOffset, parms->pelvisAnglesOffset); + VectorCopy(bone.positionOffset, parms->pelvisPositionOffset); + } else { + VectorCopy(parms->pelvisAnglesOffset, bone.anglesOffset); + VectorCopy(parms->pelvisPositionOffset, bone.positionOffset); } } } @@ -1786,228 +1475,220 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) return; break; } - if (ghoul2.mFlags&GHOUL2_RAG_STARTED) - { + if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { // only going to begin ragdoll once, everything else depends on what happens to the origin return; } - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED; // well anyway we are going live - parms->CallRagDollBegin=qtrue; + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED; // well anyway we are going live + parms->CallRagDollBegin = qtrue; G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); - - G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"cranium",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); - - //int startFrame = 3665, endFrame = 3665+1; + G2_Set_Bone_Rag(mod_a, blist, "model_root", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "pelvis", ghoul2, parms->scale, parms->position); + + G2_Set_Bone_Rag(mod_a, blist, "lower_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "upper_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "thoracic", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "cranium", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhand", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhand", ghoul2, parms->scale, parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ceyebrow", ghoul2, parms->scale, parms->position); + + // int startFrame = 3665, endFrame = 3665+1; int startFrame = parms->startFrame, endFrame = parms->endFrame; - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"upper_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lower_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"Motion",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); -// G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, -// BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, -// 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "upper_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lower_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "Motion", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + // G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, + // BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + // 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - static const float fRadScale = 0.3f;//0.5f; + static const float fRadScale = 0.3f; // 0.5f; - vec3_t pcjMin,pcjMax; - VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); - VectorSet(pcjMax,90.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + vec3_t pcjMin, pcjMax; + VectorSet(pcjMin, -90.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 90.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "model_root", RAG_PCJ_MODEL_ROOT | RAG_PCJ | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 100); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "pelvis", RAG_PCJ_PELVIS | RAG_PCJ | RAG_PCJ_POST_MULT | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, + 100); #if 1 // new base anim, unconscious flop - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT; //|RAG_EFFECTOR; - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,15.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); - VectorSet(pcjMax,25.0f,25.0f,25.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -25.0f, -25.0f, -25.0f); + VectorSet(pcjMax, 25.0f, 25.0f, 25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 12.0f * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, 6.0f * fRadScale, pcjMin, pcjMax, 500); static const float sFactLeg = 1.0f; static const float sFactArm = 1.0f; static const float sRadArm = 1.0f; static const float sRadLeg = 1.0f; - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); - VectorSet(pcjMax,15.0f,40.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); + VectorSet(pcjMin, -50.0f, -80.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 40.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,30.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); - VectorSet(pcjMax,30.0f,5.0f,20.0f); + VectorSet(pcjMin, -80.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 5.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -60.0f, -5.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); #else // old base anim - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,45.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags,10.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,60.0f,45.0f); - VectorSet(pcjMax,180.0f,180.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - //VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,90.0f,100.0f); - VectorSet(pcjMax,180.0f,180.0f,100.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 45.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags, 10.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,60.0f,45.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + // VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,90.0f,100.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 100.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); //-120/120 - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,5.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-90.0f,-50.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //120 - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 5.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -90.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // 120 + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); #endif - float sRadEArm = 1.2f; float sRadELeg = 1.2f; -// int rhand= - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,5.0f); -//match the currrent animation - if (!G2_RagDollSetup(ghoul2,curTime,true,parms->position,false)) - { + // int rhand= + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ceyebrow", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 5.0f); + // match the currrent animation + if (!G2_RagDollSetup(ghoul2, curTime, true, parms->position, false)) { assert(!"failed to add any rag bones"); return; } - G2_RagDollCurrentPosition(ghoul2V,model,curTime,parms->angles,parms->position,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, parms->position, parms->scale); int k; CRagDollUpdateParams fparms; @@ -2018,7 +1699,7 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) fparms.me = parms->me; fparms.settleFrame = parms->endFrame; - //Guess I don't need to do this, do I? + // Guess I don't need to do this, do I? G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); vec3_t dPos; @@ -2027,49 +1708,40 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) dPos[2] -= 6; #endif - for (k=0;kangles,dPos,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, dPos, parms->scale); G2_RagDollMatchPosition(); - G2_RagDollSolve(ghoul2V,model,1.0f*(1.0f-k/40.0f),curTime,dPos,false); + G2_RagDollSolve(ghoul2V, model, 1.0f * (1.0f - k / 40.0f), curTime, dPos, false); } } -void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t hit) -{ - if (!broadsword||!broadsword->integer) - { +void G2_SetRagDollBullet(CGhoul2Info &ghoul2, const vec3_t rayStart, const vec3_t hit) { + if (!broadsword || !broadsword->integer) { return; } vec3_t shotDir; - VectorSubtract(hit,rayStart,shotDir); - float len=VectorLength(shotDir); - if (len<1.0f) - { + VectorSubtract(hit, rayStart, shotDir); + float len = VectorLength(shotDir); + if (len < 1.0f) { return; } - float lenr=1.0f/len; - shotDir[0]*=lenr; - shotDir[1]*=lenr; - shotDir[2]*=lenr; + float lenr = 1.0f / len; + shotDir[0] *= lenr; + shotDir[1] *= lenr; + shotDir[2] *= lenr; - bool firstOne=false; - if (broadsword_kickbones&&broadsword_kickbones->integer) - { - int magicFactor13=150.0f; // squared radius multiplier for shot effects + bool firstOne = false; + if (broadsword_kickbones && broadsword_kickbones->integer) { + int magicFactor13 = 150.0f; // squared radius multiplier for shot effects boneInfo_v &blist = ghoul2.mBlist; - for(int i=(int)(blist.size()-1);i>=0;i--) - { - boneInfo_t &bone=blist[i]; - if ((bone.flags & BONE_ANGLES_TOTAL)) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (!firstOne) - { - firstOne=true; + for (int i = (int)(blist.size() - 1); i >= 0; i--) { + boneInfo_t &bone = blist[i]; + if ((bone.flags & BONE_ANGLES_TOTAL)) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (!firstOne) { + firstOne = true; #if 0 int curTime=G2API_GetTime(0); const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); @@ -2112,229 +1784,174 @@ void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t #endif } - VectorCopy(shotDir,bone.lastShotDir); + VectorCopy(shotDir, bone.lastShotDir); vec3_t dir; - VectorSubtract(bone.lastPosition,hit,dir); - len=VectorLength(dir); - if (len<1.0f) - { - len=1.0f; + VectorSubtract(bone.lastPosition, hit, dir); + len = VectorLength(dir); + if (len < 1.0f) { + len = 1.0f; } - lenr=1.0f/len; - float effect=lenr; - effect*=magicFactor13*effect; // this is cubed, one of them is absorbed by the next calc - bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f)); -// bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); - assert( !Q_isnan(shotDir[2])); - // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + lenr = 1.0f / len; + float effect = lenr; + effect *= magicFactor13 * effect; // this is cubed, one of them is absorbed by the next calc + bone.velocityEffector[0] = shotDir[0] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[1] = shotDir[1] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[2] = fabs(shotDir[2]) * (effect + flrand(0.0f, 0.05f)); + // bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + assert(!Q_isnan(shotDir[2])); + // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); // go dynamic - bone.firstCollisionTime=G2API_GetTime(0); -// bone.firstCollisionTime=0; - bone.restTime=0; + bone.firstCollisionTime = G2API_GetTime(0); + // bone.firstCollisionTime=0; + bone.restTime = 0; } } } } } +static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone, int frameNum, const vec3_t origin, bool &resetOrigin) { + ragOriginChange = DistanceSquared(origin, bone.extraVec1); + VectorSubtract(origin, bone.extraVec1, ragOriginChangeDir); -static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone,int frameNum,const vec3_t origin,bool &resetOrigin) -{ - ragOriginChange=DistanceSquared(origin,bone.extraVec1); - VectorSubtract(origin,bone.extraVec1,ragOriginChangeDir); - - float decay=1.0f; + float decay = 1.0f; - int dynamicTime=1000; - int settleTime=1000; + int dynamicTime = 1000; + int settleTime = 1000; - if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } - } - else if (bone.firstCollisionTime>0) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + } else if (bone.firstCollisionTime > 0) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } -//decay=0.0f; - } - else if (bone.restTime>0) - { - decay=1.0f-(frameNum-bone.restTime)/float(dynamicTime); - if (decay<0.0f) - { - decay=0.0f; - } - if (decay>1.0f) - { - decay=1.0f; - } - float magicFactor8=1.0f; // Power for decay - decay=pow(decay,magicFactor8); - ragState=ERS_SETTLING; - if (frameNum>bone.restTime+settleTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { - bone.restTime=frameNum; - } - else - { + // decay=0.0f; + } else if (bone.restTime > 0) { + decay = 1.0f - (frameNum - bone.restTime) / float(dynamicTime); + if (decay < 0.0f) { + decay = 0.0f; + } + if (decay > 1.0f) { + decay = 1.0f; + } + float magicFactor8 = 1.0f; // Power for decay + decay = pow(decay, magicFactor8); + ragState = ERS_SETTLING; + if (frameNum > bone.restTime + settleTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { + bone.restTime = frameNum; + } else { // stop - bone.restTime=0; - ragState=ERS_SETTLED; + bone.restTime = 0; + ragState = ERS_SETTLED; } } -//decay=0.0f; - } - else - { - if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else if (ragOriginChange>15.0f) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else - { - ragState=ERS_SETTLED; - } - decay=0.0f; - } -// ragState=ERS_SETTLED; -// decay=0.0f; + // decay=0.0f; + } else { + if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else if (ragOriginChange > 15.0f) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else { + ragState = ERS_SETTLED; + } + decay = 0.0f; + } + // ragState=ERS_SETTLED; + // decay=0.0f; return decay; } -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered) -{ - int minSurvivingBone=10000; - //int minSurvivingBoneAt=-1; - int minSurvivingBoneAlt=10000; - //int minSurvivingBoneAtAlt=-1; +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered) { + int minSurvivingBone = 10000; + // int minSurvivingBoneAt=-1; + int minSurvivingBoneAlt = 10000; + // int minSurvivingBoneAtAlt=-1; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; rag.clear(); - int numRendered=0; - int numNotRendered=0; - //int pelvisAt=-1; - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if ((bone.flags & BONE_ANGLES_RAGDOLL) || (bone.flags & BONE_ANGLES_IK)) { + // rww - this was (!anyRendered) before. Isn't that wrong? (if anyRendered, then wasRendered should be true) + bool wasRendered = (!anyRendered) || // offscreeen or something + G2_WasBoneRendered(ghoul2, bone.boneNumber); + if (!wasRendered) { + bone.RagFlags |= RAG_WAS_NOT_RENDERED; numNotRendered++; - } - else - { - bone.RagFlags&=~RAG_WAS_NOT_RENDERED; - bone.RagFlags|=RAG_WAS_EVER_RENDERED; + } else { + bone.RagFlags &= ~RAG_WAS_NOT_RENDERED; + bone.RagFlags |= RAG_WAS_EVER_RENDERED; numRendered++; } - if (bone.RagFlags&RAG_PCJ_PELVIS) - { - //pelvisAt=i; - } - else if (bone.RagFlags&RAG_PCJ_MODEL_ROOT) - { - } - else if (wasRendered && (bone.RagFlags&RAG_PCJ)) - { - if (minSurvivingBone>bone.boneNumber) - { - minSurvivingBone=bone.boneNumber; - //minSurvivingBoneAt=i; + if (bone.RagFlags & RAG_PCJ_PELVIS) { + // pelvisAt=i; + } else if (bone.RagFlags & RAG_PCJ_MODEL_ROOT) { + } else if (wasRendered && (bone.RagFlags & RAG_PCJ)) { + if (minSurvivingBone > bone.boneNumber) { + minSurvivingBone = bone.boneNumber; + // minSurvivingBoneAt=i; } - } - else if (wasRendered) - { - if (minSurvivingBoneAlt>bone.boneNumber) - { - minSurvivingBoneAlt=bone.boneNumber; - //minSurvivingBoneAtAlt=i; + } else if (wasRendered) { + if (minSurvivingBoneAlt > bone.boneNumber) { + minSurvivingBoneAlt = bone.boneNumber; + // minSurvivingBoneAtAlt=i; } } - if ( - anyRendered && - (bone.RagFlags&RAG_WAS_EVER_RENDERED) && - !(bone.RagFlags&RAG_PCJ_MODEL_ROOT) && - !(bone.RagFlags&RAG_PCJ_PELVIS) && - !wasRendered && - (bone.RagFlags&RAG_EFFECTOR) - ) - { + if (anyRendered && (bone.RagFlags & RAG_WAS_EVER_RENDERED) && !(bone.RagFlags & RAG_PCJ_MODEL_ROOT) && !(bone.RagFlags & RAG_PCJ_PELVIS) && + !wasRendered && (bone.RagFlags & RAG_EFFECTOR)) { // this thing was rendered in the past, but wasn't now, although other bones were, lets get rid of it -// bone.flags &= ~BONE_ANGLES_RAGDOLL; -// bone.RagFlags = 0; -//Com_OPrintf("Deleted Effector %d\n",i); -// continue; + // bone.flags &= ~BONE_ANGLES_RAGDOLL; + // bone.RagFlags = 0; + // Com_OPrintf("Deleted Effector %d\n",i); + // continue; } - if ((int)rag.size()=0); - assert(numRags= 0); + assert(numRags < MAX_BONES_RAG); + + // ragStartTime=bone.ragStartTime; + + bone.ragIndex = numRags; + ragBoneData[numRags] = &bone; + ragEffectors[numRags].radius = bone.radius; + ragEffectors[numRags].weight = bone.weight; + G2_GetBoneBasepose(ghoul2, bone.boneNumber, bone.basepose, bone.baseposeInv); numRags++; } } - if (!numRags) - { + if (!numRags) { return false; } return true; } -static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params, int curTime) -{ - if (!broadsword||!broadsword->integer) - { +static void G2_RagDoll(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params, int curTime) { + if (!broadsword || !broadsword->integer) { return; } - if (!params) - { + if (!params) { assert(0); return; } @@ -2417,9 +2028,9 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * dPos[2] -= 6; #endif -// params->DebugLine(handPos,handPos2,false); - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + // params->DebugLine(handPos,handPos2,false); + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; @@ -2456,24 +2067,20 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; // this loop checks for settled - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if (bone.flags & BONE_ANGLES_RAGDOLL) { // check for state transitions - decay=G2_RagSetState(ghoul2,bone,frameNum,dPos,resetOrigin); // set the current state + decay = G2_RagSetState(ghoul2, bone, frameNum, dPos, resetOrigin); // set the current state - if (ragState==ERS_SETTLED) - { + if (ragState == ERS_SETTLED) { #if 0 bool noneInSolid = true; @@ -2503,37 +2110,31 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * return; #endif } - if (G2_WasBoneRendered(ghoul2,bone.boneNumber)) - { - anyRendered=true; + if (G2_WasBoneRendered(ghoul2, bone.boneNumber)) { + anyRendered = true; break; } } } } - //int iters=(ragState==ERS_DYNAMIC)?2:1; - int iters=(ragState==ERS_DYNAMIC)?4:2; - //bool kicked=false; - if (ragOriginChangeDir[2]<-100.0f) - { - //kicked=true; - //iters*=8; - iters*=2; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) + // int iters=(ragState==ERS_DYNAMIC)?2:1; + int iters = (ragState == ERS_DYNAMIC) ? 4 : 2; + // bool kicked=false; + if (ragOriginChangeDir[2] < -100.0f) { + // kicked=true; + // iters*=8; + iters *= 2; // rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) } - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,dPos,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, dPos, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (int i=0;iangles,dPos,params->scale); + for (int i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, dPos, params->scale); - if (G2_RagDollSettlePositionNumeroTrois(ghoul2V,dPos,params,curTime)) - { + if (G2_RagDollSettlePositionNumeroTrois(ghoul2V, dPos, params, curTime)) { #if 0 //effectors are start solid alot, so this was pretty extreme if (!kicked&&iters<4) @@ -2544,13 +2145,12 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif } - //params->position[2] += 16; - G2_RagDollSolve(ghoul2V,g2Index,decay*2.0f,frameNum,dPos,true,params); + // params->position[2] += 16; + G2_RagDollSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, dPos, true, params); } } - if (params->me != ENTITYNUM_NONE) - { + if (params->me != ENTITYNUM_NONE) { #if 0 vec3_t worldMins,worldMaxs; worldMins[0]=params->position[0]-17; @@ -2562,11 +2162,11 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * //Com_OPrintf(va("%f \n",worldMins[2]); // params->DebugLine(worldMins,worldMaxs,true); #endif - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); -// SV_UnlinkEntity(params->me); -// params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); -// params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); -// SV_LinkEntity(params->me); + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); + // SV_UnlinkEntity(params->me); + // params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); + // params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); + // SV_LinkEntity(params->me); } } @@ -2574,19 +2174,16 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * #define _DEBUG_BONE_NAMES #endif -static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); +static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; iragBoneMaxs[k]) - { - ragBoneMaxs[k]=ragEffectors[i].currentOrigin[k]; + ragBoneCM[k] = ragEffectors[i].currentOrigin[k] * cmweight; + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; + ragBoneMins[k] = ragEffectors[i].currentOrigin[k]; + } else { + ragBoneCM[k] += ragEffectors[i].currentOrigin[k] * ragEffectors[i].weight; + if (ragEffectors[i].currentOrigin[k] > ragBoneMaxs[k]) { + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; } - if (ragEffectors[i].currentOrigin[k]0.0f); + assert(totalWt > 0.0f); int k; { - float wtInv=1.0f/totalWt; - for (k=0;k<3;k++) - { - ragBoneMaxs[k]-=position[k]; - ragBoneMins[k]-=position[k]; - ragBoneMaxs[k]+=10.0f; - ragBoneMins[k]-=10.0f; - ragBoneCM[k]*=wtInv; + float wtInv = 1.0f / totalWt; + for (k = 0; k < 3; k++) { + ragBoneMaxs[k] -= position[k]; + ragBoneMins[k] -= position[k]; + ragBoneMaxs[k] += 10.0f; + ragBoneMins[k] -= 10.0f; + ragBoneCM[k] *= wtInv; - ragBoneCM[k]=ragEffectors[0].currentOrigin[k]; // use the pelvis + ragBoneCM[k] = ragEffectors[0].currentOrigin[k]; // use the pelvis } } } @@ -2675,13 +2263,12 @@ int ragSSCount = 0; int ragTraceCount = 0; #endif -void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) -{ +void Rag_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, + const EG2_Collision eG2TraceType, const int useLod) { #ifdef _DEBUG int ragPreTrace = ri.Milliseconds(); #endif - if ( ri.CGVMLoaded() ) - { + if (ri.CGVMLoaded()) { ragCallbackTraceLine_t *callData = (ragCallbackTraceLine_t *)ri.GetSharedMemory(); VectorCopy(start, callData->start); @@ -2691,14 +2278,12 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v callData->ignore = passEntityNum; callData->mask = contentmask; - ri.CGVM_RagCallback( RAG_CALLBACK_TRACELINE ); + ri.CGVM_RagCallback(RAG_CALLBACK_TRACELINE); *results = callData->tr; - } - else - { + } else { results->entityNum = ENTITYNUM_NONE; - //SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); + // SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); ri.CM_BoxTrace(results, start, end, mins, maxs, 0, contentmask, 0); results->entityNum = results->fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; } @@ -2707,39 +2292,35 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v int ragPostTrace = ri.Milliseconds(); ragTraceTime += (ragPostTrace - ragPreTrace); - if (results->startsolid) - { + if (results->startsolid) { ragSSCount++; } ragTraceCount++; #endif } -//run advanced physics on each bone indivudually -//an adaption of my "exphys" custom game physics model -#define MAX_GRAVITY_PULL 256//512 +// run advanced physics on each bone indivudually +// an adaption of my "exphys" custom game physics model +#define MAX_GRAVITY_PULL 256 // 512 -static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) -{ +static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) { trace_t tr; vec3_t gSpot; VectorCopy(org, gSpot); - gSpot[2] -= 1.0f; //seems reasonable to me + gSpot[2] -= 1.0f; // seems reasonable to me Rag_Trace(&tr, org, mins, maxs, gSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) - { //not in solid, and hit something. Guess it's ground. + if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) { // not in solid, and hit something. Guess it's ground. return true; } return false; } -static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, const vec3_t testMaxs, - const float gravity, const float mass, const float bounce) -{ +static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, + const vec3_t testMaxs, const float gravity, const float mass, const float bounce) { trace_t tr; vec3_t projectedOrigin; vec3_t vNorm; @@ -2750,68 +2331,54 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR assert(mass <= 1.0f && mass >= 0.01f); - if (bone.physicsSettled) - { //then we have no need to continue + if (bone.physicsSettled) { // then we have no need to continue return true; } - if (gravity) - { //factor it in before we do anything. + if (gravity) { // factor it in before we do anything. VectorCopy(e.currentOrigin, ground); ground[2] -= 1.0f; Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, ground, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.entityNum == ENTITYNUM_NONE) - { + if (tr.entityNum == ENTITYNUM_NONE) { boneOnGround = false; - } - else - { + } else { boneOnGround = true; } - if (!boneOnGround) - { - if (!params->velocity[2]) - { //only increase gravitational pull once the actual entity is still + if (!boneOnGround) { + if (!params->velocity[2]) { // only increase gravitational pull once the actual entity is still bone.epGravFactor += gravity; } - if (bone.epGravFactor > MAX_GRAVITY_PULL) - { //cap it off if needed + if (bone.epGravFactor > MAX_GRAVITY_PULL) { // cap it off if needed bone.epGravFactor = MAX_GRAVITY_PULL; } bone.epVelocity[2] -= bone.epGravFactor; - } - else - { //if we're sitting on something then reset the gravity factor. + } else { // if we're sitting on something then reset the gravity factor. bone.epGravFactor = 0; } - } - else - { + } else { boneOnGround = G2_BoneOnGround(e.currentOrigin, testMins, testMaxs, params->me); } - if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) - { //nothing to do if we have no velocity even after gravity. + if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) { // nothing to do if we have no velocity even after gravity. VectorCopy(e.currentOrigin, goalSpot); return true; } - //get the projected origin based on velocity. + // get the projected origin based on velocity. VectorMA(e.currentOrigin, velScaling, bone.epVelocity, projectedOrigin); - //scale it down based on mass - VectorScale(bone.epVelocity, 1.0f-mass, bone.epVelocity); + // scale it down based on mass + VectorScale(bone.epVelocity, 1.0f - mass, bone.epVelocity); VectorCopy(bone.epVelocity, vNorm); vTotal = VectorNormalize(vNorm); - if (vTotal < 1 && boneOnGround) - { //we've pretty much stopped moving anyway, just clear it out then. + if (vTotal < 1 && boneOnGround) { // we've pretty much stopped moving anyway, just clear it out then. VectorClear(bone.epVelocity); bone.epGravFactor = 0; VectorCopy(e.currentOrigin, goalSpot); @@ -2820,52 +2387,44 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, projectedOrigin, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.startsolid || tr.allsolid) - { //can't go anywhere from here + if (tr.startsolid || tr.allsolid) { // can't go anywhere from here return false; } - //Go ahead and set it to the trace endpoint regardless of what it hit + // Go ahead and set it to the trace endpoint regardless of what it hit VectorCopy(tr.endpos, goalSpot); - if (tr.fraction == 1.0f) - { //Nothing was in the way. + if (tr.fraction == 1.0f) { // Nothing was in the way. return true; } - if (bounce) - { - vTotal *= bounce; //scale it by bounce + if (bounce) { + vTotal *= bounce; // scale it by bounce - VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + VectorScale(tr.plane.normal, vTotal, vNorm); // scale the trace plane normal by the bounce factor - if (vNorm[2] > 0) - { - bone.epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. - if (bone.epGravFactor < 0) - { + if (vNorm[2] > 0) { + bone.epGravFactor -= vNorm[2] * (1.0f - mass); // The lighter it is the more gravity will be reduced by bouncing vertically. + if (bone.epGravFactor < 0) { bone.epGravFactor = 0; } } - VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); //add it into the existing velocity. + VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); // add it into the existing velocity. - //I suppose it could be sort of neat to make a game callback here to actual do stuff - //when bones slam into things. But it could be slow too. + // I suppose it could be sort of neat to make a game callback here to actual do stuff + // when bones slam into things. But it could be slow too. /* if (tr.entityNum != ENTITYNUM_NONE && ent->touch) { //then call the touch function ent->touch(ent, &g_entities[tr.entityNum], &tr); } */ - } - else - { //if no bounce, kill when it hits something. + } else { // if no bounce, kill when it hits something. bone.epVelocity[0] = 0; bone.epVelocity[1] = 0; - if (!gravity) - { + if (!gravity) { bone.epVelocity[2] = 0; } } @@ -2873,9 +2432,8 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR } #ifdef _DEBUG_BONE_NAMES -static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) -{ - if ( !ri.CGVMLoaded() ) +static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) { + if (!ri.CGVMLoaded()) return; ragCallbackDebugBox_t *callData = (ragCallbackDebugBox_t *)ri.GetSharedMemory(); @@ -2884,12 +2442,11 @@ static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) VectorCopy(mins, callData->mins); VectorCopy(maxs, callData->maxs); - ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGBOX ); + ri.CGVM_RagCallback(RAG_CALLBACK_DEBUGBOX); } -static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) -{ - if ( !ri.CGVMLoaded() ) +static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) { + if (!ri.CGVMLoaded()) return; ragCallbackDebugLine_t *callData = (ragCallbackDebugLine_t *)ri.GetSharedMemory(); @@ -2900,338 +2457,286 @@ static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color callData->color = color; callData->radius = radius; - ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGLINE ); + ri.CGVM_RagCallback(RAG_CALLBACK_DEBUGLINE); } #endif #ifdef _OLD_STYLE_SETTLE -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ - haveDesiredPelvisOffset=false; +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) { + haveDesiredPelvisOffset = false; vec3_t desiredPos; int i; assert(params); - //assert(params->me); //no longer valid, because me is an index! - int ignoreNum=params->me; + // assert(params->me); //no longer valid, because me is an index! + int ignoreNum = params->me; - bool anyStartSolid=false; + bool anyStartSolid = false; - vec3_t groundSpot={0,0,0}; + vec3_t groundSpot = {0, 0, 0}; // lets find the floor at our quake origin { vec3_t testStart; - VectorCopy(currentOrg,testStart); //last arg is dest + VectorCopy(currentOrg, testStart); // last arg is dest vec3_t testEnd; - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]-=200.0f; + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] -= 200.0f; vec3_t testMins; vec3_t testMaxs; - VectorSet(testMins,-10,-10,-10); - VectorSet(testMaxs,10,10,10); + VectorSet(testMins, -10, -10, -10); + VectorSet(testMaxs, 10, 10, 10); { - trace_t tr; - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0/*SV_TRACE_NO_PLAYER*/); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0 /*SV_TRACE_NO_PLAYER*/); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { - //hmmm, punt - VectorCopy(currentOrg,groundSpot); //last arg is dest - groundSpot[2]-=30.0f; - } - else - { - VectorCopy(tr.endpos,groundSpot); //last arg is dest + if (tr.startsolid) { + // hmmm, punt + VectorCopy(currentOrg, groundSpot); // last arg is dest + groundSpot[2] -= 30.0f; + } else { + VectorCopy(tr.endpos, groundSpot); // last arg is dest } } } - for (i=0;i groundSpot[2]) - { - testStart[2]=groundSpot[2]+(e.radius-10.0f); - } - else - { + if (e.currentOrigin[2] > groundSpot[2]) { + testStart[2] = groundSpot[2] + (e.radius - 10.0f); + } else { // lets try higher - testStart[2]=groundSpot[2]+8.0f; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + testStart[2] = groundSpot[2] + 8.0f; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } } - } - if (tr.startsolid) - { - iAmStartSolid=true; - anyStartSolid=true; + if (tr.startsolid) { + iAmStartSolid = true; + anyStartSolid = true; // above the origin, so lets slide away - if (e.currentOrigin[2] > groundSpot[2]) - { - if (params) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + if (e.currentOrigin[2] > groundSpot[2]) { + if (params) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } + } else { + // harumph, we are really screwed } - else - { - //harumph, we are really screwed - } - } - else - { - vertEffectorTraceFraction=tr.fraction; - if (params && - vertEffectorTraceFraction < .95f && - fabsf(tr.plane.normal[2]) < .707f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + } else { + vertEffectorTraceFraction = tr.fraction; + if (params && vertEffectorTraceFraction < .95f && fabsf(tr.plane.normal[2]) < .707f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } } } vec3_t effectorGroundSpot; - VectorAdvance(testStart,vertEffectorTraceFraction,testEnd,effectorGroundSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorAdvance(testStart, vertEffectorTraceFraction, testEnd, effectorGroundSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // trace from the quake origin horzontally to the effector - // gonna choose the maximum of the ground spot or the effector location + // gonna choose the maximum of the ground spot or the effector location // and clamp it to be roughly in the bbox - VectorCopy(groundSpot,testStart); //last arg is dest - if (iAmStartSolid) - { + VectorCopy(groundSpot, testStart); // last arg is dest + if (iAmStartSolid) { // we don't have a meaningful ground spot - VectorCopy(e.currentOrigin,testEnd); //last arg is dest + VectorCopy(e.currentOrigin, testEnd); // last arg is dest bone.solidCount++; - } - else - { - VectorCopy(effectorGroundSpot,testEnd); //last arg is dest + } else { + VectorCopy(effectorGroundSpot, testEnd); // last arg is dest bone.solidCount = 0; } - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); float ztest; - if (testEnd[2]>testStart[2]) - { - ztest=testEnd[2]; + if (testEnd[2] > testStart[2]) { + ztest = testEnd[2]; + } else { + ztest = testStart[2]; } - else - { - ztest=testStart[2]; - } - if (ztest c := (1-t)a+tb + float magicFactor44 = 1.0f; // going to trace a bit longer, this also serves as an expansion parameter + VectorAdvance(testStart, magicFactor44, testEnd, testEnd); // VA(a,t,b,c)-> c := (1-t)a+tb - float horzontalTraceFraction=0.0f; - vec3_t HorizontalHitSpot={0,0,0}; + float horzontalTraceFraction = 0.0f; + vec3_t HorizontalHitSpot = {0, 0, 0}; { - trace_t tr; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (tr.startsolid) - { - horzontalTraceFraction=1.0f; + horzontalTraceFraction = tr.fraction; + if (tr.startsolid) { + horzontalTraceFraction = 1.0f; // punt - VectorCopy(e.currentOrigin,HorizontalHitSpot); - } - else - { - VectorCopy(tr.endpos,HorizontalHitSpot); - int magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //rww - An..int? - VectorAdvance(tr.endpos,magicFactor46,testStart,HorizontalHitSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(e.currentOrigin, HorizontalHitSpot); + } else { + VectorCopy(tr.endpos, HorizontalHitSpot); + int magicFactor46 = 0.98f; // shorten percetage to make sure we can go down along a wall + // float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + // rww - An..int? + VectorAdvance(tr.endpos, magicFactor46, testStart, HorizontalHitSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // roughly speaking this is a wall - if (horzontalTraceFraction<0.9f) - { - + if (horzontalTraceFraction < 0.9f) { + // roughly speaking this is a wall - if (fabsf(tr.plane.normal[2])<0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + if (fabsf(tr.plane.normal[2]) < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } - } - else if (!iAmStartSolid && - effectorGroundSpot[2] < groundSpot[2] - 8.0f) - { + } else if (!iAmStartSolid && effectorGroundSpot[2] < groundSpot[2] - 8.0f) { // this is a situation where we have something dangling below the pelvis, we want to find the plane going downhill away from the origin // for various reasons, without this correction the body will actually move away from places it can fall off. - //gotta run the trace backwards to get a plane + // gotta run the trace backwards to get a plane { - trace_t tr; - VectorCopy(effectorGroundSpot,testStart); - VectorCopy(groundSpot,testEnd); + trace_t tr; + VectorCopy(effectorGroundSpot, testStart); + VectorCopy(groundSpot, testEnd); // this can be a line trace, we just want the plane normal - Rag_Trace(&tr,testEnd,0,0,testStart,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + Rag_Trace(&tr, testEnd, 0, 0, testStart, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (!tr.startsolid && tr.fraction< 0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + horzontalTraceFraction = tr.fraction; + if (!tr.startsolid && tr.fraction < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } } } } } - vec3_t goalSpot={0,0,0}; + vec3_t goalSpot = {0, 0, 0}; // now lets trace down - VectorCopy(HorizontalHitSpot,testStart); - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]=e.currentOrigin[2]-30.0f; + VectorCopy(HorizontalHitSpot, testStart); + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] = e.currentOrigin[2] - 30.0f; { - trace_t tr; - Rag_Trace(&tr,testStart,NULL,NULL,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, NULL, NULL, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { + if (tr.startsolid) { // punt, go to the origin I guess - VectorCopy(currentOrg,goalSpot); - } - else - { - VectorCopy(tr.endpos,goalSpot); - int magicFactor47=0.5f; // shorten percentage to make sure we can go down along a wall - VectorAdvance(tr.endpos,magicFactor47,testStart,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(currentOrg, goalSpot); + } else { + VectorCopy(tr.endpos, goalSpot); + int magicFactor47 = 0.5f; // shorten percentage to make sure we can go down along a wall + VectorAdvance(tr.endpos, magicFactor47, testStart, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb } } // ok now as the horizontal trace fraction approaches zero, we want to head toward the horizontalHitSpot - //geeze I would like some reasonable trace fractions - assert(horzontalTraceFraction>=0.0f&&horzontalTraceFraction<=1.0f); - VectorAdvance(HorizontalHitSpot,horzontalTraceFraction*horzontalTraceFraction,goalSpot,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + // geeze I would like some reasonable trace fractions + assert(horzontalTraceFraction >= 0.0f && horzontalTraceFraction <= 1.0f); + VectorAdvance(HorizontalHitSpot, horzontalTraceFraction * horzontalTraceFraction, goalSpot, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb #if 0 if ((bone.RagFlags & RAG_EFFECTOR) && (bone.RagFlags & RAG_BONE_LIGHTWEIGHT)) { //new rule - don't even bother unless it's a lightweight effector @@ -3285,22 +2790,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif int k; - int magicFactor12=0.8f; // dampening of velocity applied - int magicFactor16=10.0f; // effect multiplier of velocity applied + int magicFactor12 = 0.8f; // dampening of velocity applied + int magicFactor16 = 10.0f; // effect multiplier of velocity applied - if (iAmStartSolid) - { + if (iAmStartSolid) { magicFactor16 = 30.0f; } - for (k=0;k<3;k++) - { - e.desiredDirection[k]=goalSpot[k]-e.currentOrigin[k]; - e.desiredDirection[k]+=magicFactor16*bone.velocityEffector[k]; - e.desiredDirection[k]+=flrand(-0.75f,0.75f)*flrand(-0.75f,0.75f); - bone.velocityEffector[k]*=magicFactor12; + for (k = 0; k < 3; k++) { + e.desiredDirection[k] = goalSpot[k] - e.currentOrigin[k]; + e.desiredDirection[k] += magicFactor16 * bone.velocityEffector[k]; + e.desiredDirection[k] += flrand(-0.75f, 0.75f) * flrand(-0.75f, 0.75f); + bone.velocityEffector[k] *= magicFactor12; } - VectorCopy(e.currentOrigin,bone.lastPosition); // last arg is dest + VectorCopy(e.currentOrigin, bone.lastPosition); // last arg is dest } return anyStartSolid; } @@ -3323,17 +2826,14 @@ static inline int G2_RagIndexForBoneNum(int boneNum) #endif #ifdef _RAG_PRINT_TEST -void G2_RagPrintMatrix(mdxaBone_t *mat) -{ +void G2_RagPrintMatrix(mdxaBone_t *mat) { char x[1024]; x[0] = 0; int n = 0; - while (n < 3) - { + while (n < 3) { int o = 0; - while (o < 4) - { - strcat(x, va("%f ", mat->matrix[n][o])); + while (o < 4) { + strcat(x, va("%f ", mat->matrix[n][o])); o++; } n++; @@ -3346,34 +2846,31 @@ void G2_RagPrintMatrix(mdxaBone_t *mat) void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale); void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame); -static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) -{ +static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) { static mdxaBone_t trueBaseMatrix, baseBoneMatrix; - //get matrix for the settleFrame to use as an ideal + // get matrix for the settleFrame to use as an ideal G2_RagGetAnimMatrix(ghoul2, bone.boneNumber, trueBaseMatrix, params->settleFrame); assert(bone.hasAnimFrameMatrix == params->settleFrame); - G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, - trueBaseMatrix, baseBoneMatrix, params->scale); + G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, trueBaseMatrix, baseBoneMatrix, params->scale); - //Use params to multiply world coordinate/dir matrix into the - //bone matrix and give us a useable world position + // Use params to multiply world coordinate/dir matrix into the + // bone matrix and give us a useable world position Mat3x4_Multiply(&retMatrix, &worldMatrix, &baseBoneMatrix); assert(!Q_isnan(retMatrix.matrix[2][3])); } -//get the current pelvis Z direction and the base anim matrix Z direction -//so they can be compared and used to offset -rww +// get the current pelvis Z direction and the base anim matrix Z direction +// so they can be compared and used to offset -rww void G2_GetRagBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &retMatrix); -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); -static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) -{ +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) { static mdxaBone_t final; static mdxaBone_t x; - //static mdxaBone_t *unused1, *unused2; - //static vec3_t lumbarPos; + // static mdxaBone_t *unused1, *unused2; + // static vec3_t lumbarPos; assert(ghoul2.animModel); int boneIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, "pelvis"); @@ -3389,8 +2886,8 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd G2API_GiveMeVectorFromMatrix(&final, ORIGIN, pos); G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, dir); #else - //We have the anim matrix pelvis pos now, so get the normal one as well - //G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); + // We have the anim matrix pelvis pos now, so get the normal one as well + // G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); int bolt = G2_Add_Bolt(&ghoul2, ghoul2.mBltlist, ghoul2.mSlist, "pelvis"); G2_GetBoltMatrixLow(ghoul2, bolt, params->scale, x); Mat3x4_Multiply(&final, &worldMatrix, &x); @@ -3418,13 +2915,13 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd */ } -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ //now returns true if any bone was in solid, otherwise false +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, + int curTime) { // now returns true if any bone was in solid, otherwise false int ignoreNum = params->me; static int i; static vec3_t goalSpot; static trace_t tr; - //static trace_t solidTr; + // static trace_t solidTr; static int k; static const float velocityDampening = 1.0f; static const float velocityMultiplier = 60.0f; @@ -3441,38 +2938,31 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve static bool hasBasePos; static vec3_t animPelvisDir, pelvisDir, animPelvisPos, pelvisPos; - //Maybe customize per-bone? + // Maybe customize per-bone? static const float gravity = 3.0f; static const float mass = 0.09f; - static const float bounce = 0.0f;//1.3f; - //Bouncing and stuff unfortunately does not work too well at the moment. - //Need to keep a seperate "physics origin" or make the filthy solve stuff - //better. + static const float bounce = 0.0f; // 1.3f; + // Bouncing and stuff unfortunately does not work too well at the moment. + // Need to keep a seperate "physics origin" or make the filthy solve stuff + // better. bool inAir = false; - if (params->velocity[0] || params->velocity[1] || params->velocity[2]) - { + if (params->velocity[0] || params->velocity[1] || params->velocity[2]) { inAir = true; } - if (!params->scale[0] && !params->scale[1] && !params->scale[2]) - { + if (!params->scale[0] && !params->scale[1] && !params->scale[2]) { VectorSet(entScale, 1.0f, 1.0f, 1.0f); - } - else - { + } else { VectorCopy(params->scale, entScale); } - if (broadsword_ragtobase && - broadsword_ragtobase->integer > 1) - { - //grab the pelvis directions to offset base positions for bones - G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, - animPelvisDir); + if (broadsword_ragtobase && broadsword_ragtobase->integer > 1) { + // grab the pelvis directions to offset base positions for bones + G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, animPelvisDir); - //don't care about the pitch offsets + // don't care about the pitch offsets pelvisDir[2] = 0; animPelvisDir[2] = 0; @@ -3490,42 +2980,36 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(uanimPelvisPos, blah, 50, 0xff0000, 1); */ - //just convert to angles now, that's all we'll ever use them for + // just convert to angles now, that's all we'll ever use them for vectoangles(pelvisDir, pelvisDir); vectoangles(animPelvisDir, animPelvisDir); } - for (i = 0; i < numRags; i++) - { + for (i = 0; i < numRags; i++) { boneInfo_t &bone = *ragBoneData[i]; SRagEffector &e = ragEffectors[i]; - if (inAir) - { + if (inAir) { bone.airTime = curTime + 30; } - if (bone.RagFlags & RAG_PCJ_PELVIS) - { - VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2]+DEFAULT_MINS_2)+((bone.radius*entScale[2])+2)); + if (bone.RagFlags & RAG_PCJ_PELVIS) { + VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2] + DEFAULT_MINS_2) + ((bone.radius * entScale[2]) + 2)); VectorSubtract(goalSpot, e.currentOrigin, desiredPelvisOffset); haveDesiredPelvisOffset = true; VectorCopy(e.currentOrigin, bone.lastPosition); - continue; + continue; } - if (!(bone.RagFlags & RAG_EFFECTOR)) - { - continue; + if (!(bone.RagFlags & RAG_EFFECTOR)) { + continue; } - if (bone.hasOverGoal) - { //api call was made to override the goal spot + if (bone.hasOverGoal) { // api call was made to override the goal spot VectorCopy(bone.overGoalSpot, goalSpot); bone.solidCount = 0; - for (k = 0; k < 3; k++) - { + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); bone.velocityEffector[k] *= velocityDampening; @@ -3535,22 +3019,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - VectorSet(testMins, -e.radius*entScale[0], -e.radius*entScale[1], -e.radius*entScale[2]); - VectorSet(testMaxs, e.radius*entScale[0], e.radius*entScale[1], e.radius*entScale[2]); + VectorSet(testMins, -e.radius * entScale[0], -e.radius * entScale[1], -e.radius * entScale[2]); + VectorSet(testMaxs, e.radius * entScale[0], e.radius * entScale[1], e.radius * entScale[2]); assert(ghoul2V[0].mBoneCache); - //get the parent bone's position + // get the parent bone's position hasDaddy = false; - if (bone.boneNumber) - { + if (bone.boneNumber) { assert(ghoul2V[0].animModel); assert(ghoul2V[0].aHeader); - if (bone.parentBoneIndex == -1) - { - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; + if (bone.parentBoneIndex == -1) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; int bParentIndex, bParentListIndex = -1; offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); @@ -3558,66 +3040,54 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve bParentIndex = skel->parent; - while (bParentIndex > 0) - { //go upward through hierarchy searching for the first parent that is a rag bone + while (bParentIndex > 0) { // go upward through hierarchy searching for the first parent that is a rag bone skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bParentIndex]); bParentIndex = skel->parent; bParentListIndex = G2_Find_Bone(ghoul2V[0].animModel, ghoul2V[0].mBlist, skel->name); - if (bParentListIndex != -1) - { + if (bParentListIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bParentListIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //valid rag bone + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // valid rag bone break; } } - //didn't work out, reset to -1 again + // didn't work out, reset to -1 again bParentListIndex = -1; } bone.parentBoneIndex = bParentListIndex; } - if (bone.parentBoneIndex != -1) - { + if (bone.parentBoneIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bone.parentBoneIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //has origin calculated for us already + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // has origin calculated for us already VectorCopy(ragEffectors[pbone.ragIndex].currentOrigin, parentOrigin); hasDaddy = true; } } } - //get the position this bone would be in if we were in the desired frame + // get the position this bone would be in if we were in the desired frame hasBasePos = false; - if (broadsword_ragtobase && - broadsword_ragtobase->integer) - { + if (broadsword_ragtobase && broadsword_ragtobase->integer) { vec3_t v, a; float f; G2_RagGetWorldAnimMatrix(ghoul2V[0], bone, params, worldBaseMatrix); G2API_GiveMeVectorFromMatrix(&worldBaseMatrix, ORIGIN, basePos); - if (broadsword_ragtobase->integer > 1) - { - float fa = AngleNormalize180(animPelvisDir[YAW]-pelvisDir[YAW]); - float d = fa-bone.offsetRotation; + if (broadsword_ragtobase->integer > 1) { + float fa = AngleNormalize180(animPelvisDir[YAW] - pelvisDir[YAW]); + float d = fa - bone.offsetRotation; - if (d > 16.0f || - d < -16.0f) - { //don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates + if (d > 16.0f || d < -16.0f) { // don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates bone.offsetRotation = fa; - } - else - { + } else { fa = bone.offsetRotation; } - //Rotate the point around the pelvis based on the offsets between pelvis positions + // Rotate the point around the pelvis based on the offsets between pelvis positions VectorSubtract(basePos, animPelvisPos, v); f = VectorLength(v); vectoangles(v, a); @@ -3626,14 +3096,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve VectorNormalize(v); VectorMA(animPelvisPos, f, v, basePos); - //re-orient the position of the bone to the current position of the pelvis + // re-orient the position of the bone to the current position of the pelvis VectorSubtract(basePos, animPelvisPos, v); - //push the spots outward? (to stretch the skeleton more) - //v[0] *= 1.5f; - //v[1] *= 1.5f; + // push the spots outward? (to stretch the skeleton more) + // v[0] *= 1.5f; + // v[1] *= 1.5f; VectorAdd(pelvisPos, v, basePos); } -#if 0 //for debugging frame skeleton +#if 0 // for debugging frame skeleton mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; @@ -3663,27 +3133,23 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve hasBasePos = true; } - //Are we in solid? - if (hasDaddy) - { + // Are we in solid? + if (hasDaddy) { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, parentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - //Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - } - else - { + // Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } else { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, params->position, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); } - if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) - { //currently in solid, see what we can do about it + if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) { // currently in solid, see what we can do about it vec3_t vSub; startSolid = true; anySolid = true; - if (hasBasePos)// && bone.solidCount < 32) - { //only go to the base pos for slightly in solid bones -#if 0 //over-compensation + if (hasBasePos) // && bone.solidCount < 32) + { // only go to the base pos for slightly in solid bones +#if 0 // over-compensation float fl; float floorBase; @@ -3697,102 +3163,84 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve { goalSpot[2] = floorBase; } -#else //just use the spot directly +#else // just use the spot directly VectorCopy(basePos, goalSpot); - goalSpot[2] = (params->position[2]-23)-testMins[2]; + goalSpot[2] = (params->position[2] - 23) - testMins[2]; #endif - //Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); - } - else - { //if deep in solid want to try to rise up out of solid before hinting back to base + // Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); + } else { // if deep in solid want to try to rise up out of solid before hinting back to base VectorSubtract(e.currentOrigin, params->position, vSub); VectorNormalize(vSub); VectorMA(params->position, 40.0f, vSub, goalSpot); - //should be 1 unit above the ground taking bounding box sizes into account - goalSpot[2] = (params->position[2]-23)-testMins[2]; + // should be 1 unit above the ground taking bounding box sizes into account + goalSpot[2] = (params->position[2] - 23) - testMins[2]; } - //Trace from the entity origin in the direction between the origin and current bone position to - //find a good eventual goal position + // Trace from the entity origin in the direction between the origin and current bone position to + // find a good eventual goal position Rag_Trace(&tr, params->position, testMins, testMaxs, goalSpot, params->me, RAG_MASK, G2_NOCOLLIDE, 0); VectorCopy(tr.endpos, goalSpot); - } - else - { + } else { startSolid = false; -#if 1 //do hinting? - //Hint the bone back to the base origin - if (hasDaddy || hasBasePos) - { - if (hasBasePos) - { - VectorSubtract(basePos, e.currentOrigin, velDir); - } - else - { +#if 1 // do hinting? + // Hint the bone back to the base origin + if (hasDaddy || hasBasePos) { + if (hasBasePos) { + VectorSubtract(basePos, e.currentOrigin, velDir); + } else { VectorSubtract(e.currentOrigin, parentOrigin, velDir); } - } - else - { + } else { VectorSubtract(e.currentOrigin, params->position, velDir); } - if (VectorLength(velDir) > 2.0f) - { //don't bother if already close + if (VectorLength(velDir) > 2.0f) { // don't bother if already close VectorNormalize(velDir); VectorScale(velDir, 8.0f, velDir); - velDir[2] = 0; //don't want to nudge on Z, the gravity will take care of things. + velDir[2] = 0; // don't want to nudge on Z, the gravity will take care of things. VectorAdd(bone.epVelocity, velDir, bone.epVelocity); } #endif - //Factor the object's velocity into the bone's velocity, by pushing the bone - //opposite the velocity to give the apperance the lighter limbs are being "dragged" - //behind those of greater mass. - if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) - { + // Factor the object's velocity into the bone's velocity, by pushing the bone + // opposite the velocity to give the apperance the lighter limbs are being "dragged" + // behind those of greater mass. + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) { vec3_t vel; float vellen; VectorCopy(params->velocity, vel); - //Scale down since our velocity scale is different from standard game physics + // Scale down since our velocity scale is different from standard game physics VectorScale(vel, 0.5f, vel); vellen = VectorLength(vel); - if (vellen > 64.0f) - { //cap it off - VectorScale(vel, 64.0f/vellen, vel); + if (vellen > 64.0f) { // cap it off + VectorScale(vel, 64.0f / vellen, vel); } - //Invert the velocity so we go opposite the heavier parts and drag behind + // Invert the velocity so we go opposite the heavier parts and drag behind VectorInverse(vel); - if (vel[2]) - { //want to override entirely instead then + if (vel[2]) { // want to override entirely instead then VectorCopy(vel, bone.epVelocity); - } - else - { + } else { VectorAdd(bone.epVelocity, vel, bone.epVelocity); } } - //We're not in solid so we can apply physics freely now. - if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, - gravity, mass, bounce)) - { //if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin + // We're not in solid so we can apply physics freely now. + if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, gravity, mass, + bounce)) { // if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin VectorCopy(params->position, goalSpot); } } - //Set this now so we know what to do for angle limiting - if (startSolid) - { + // Set this now so we know what to do for angle limiting + if (startSolid) { bone.solidCount++; #if 0 if ( ri.CGVMLoaded() && bone.solidCount > 8 ) @@ -3816,8 +3264,7 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif #ifdef _DEBUG_BONE_NAMES - if (bone.solidCount > 64) - { + if (bone.solidCount > 64) { char *debugBoneName = G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber); vec3_t absmin, absmax; @@ -3832,14 +3279,12 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(e.currentOrigin, goalSpot, 50, 0x00ff00, 1); } #endif - } - else - { + } else { bone.solidCount = 0; } -#if 0 //standard goalSpot capping? - //unless we are really in solid, we should keep adjustments minimal +#if 0 // standard goalSpot capping? + // unless we are really in solid, we should keep adjustments minimal if (/*bone.epGravFactor < 64 &&*/ bone.solidCount < 2 && !inAir) { @@ -3858,22 +3303,17 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif - //Set the desired direction based on the goal position and other factors. - for (k = 0; k < 3; k++) - { + // Set the desired direction based on the goal position and other factors. + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); - if (broadsword_dircap && - broadsword_dircap->value) - { + if (broadsword_dircap && broadsword_dircap->value) { float cap = broadsword_dircap->value; - if (bone.solidCount > 5) - { - float solidFactor = bone.solidCount*0.2f; + if (bone.solidCount > 5) { + float solidFactor = bone.solidCount * 0.2f; - if (solidFactor > 16.0f) - { //don't go too high or something ugly might happen + if (solidFactor > 16.0f) { // don't go too high or something ugly might happen solidFactor = 16.0f; } @@ -3881,12 +3321,9 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve cap *= 8; } - if (e.desiredDirection[k] > cap) - { + if (e.desiredDirection[k] > cap) { e.desiredDirection[k] = cap; - } - else if (e.desiredDirection[k] < -cap) - { + } else if (e.desiredDirection[k] < -cap) { e.desiredDirection[k] = -cap; } } @@ -3903,25 +3340,19 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif -static float AngleNormZero(float theta) -{ - float ret=fmodf(theta,360.0f); - if (ret<-180.0f) - { - ret+=360.0f; - } - else if (ret>180.0f) - { - ret-=360.0f; +static float AngleNormZero(float theta) { + float ret = fmodf(theta, 360.0f); + if (ret < -180.0f) { + ret += 360.0f; + } else if (ret > 180.0f) { + ret -= 360.0f; } - assert(ret>=-180.0f&&ret<=180.0f); + assert(ret >= -180.0f && ret <= 180.0f); return ret; } -static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) -{ - if ( !ri.CGVMLoaded() || !params ) - { +static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) { + if (!ri.CGVMLoaded() || !params) { return; } @@ -3930,15 +3361,15 @@ static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDol callData->entNum = params->me; strcpy(callData->boneName, G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber)); - ri.CGVM_RagCallback( RAG_CALLBACK_BONESNAP ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONESNAP); } -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool limitAngles,CRagDollUpdateParams *params) -{ +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool limitAngles, + CRagDollUpdateParams *params) { int i; - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; mdxaBone_t N; mdxaBone_t P; @@ -3952,96 +3383,88 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; - // END this is the objective function thing - for (i=0;i50.0f) { @@ -4052,216 +3475,189 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f bone.velocityRoot[k]=-50.0f; } */ - //No -rww - bone.ragOverrideMatrix.matrix[k][3]=bone.velocityRoot[k]; + // No -rww + bone.ragOverrideMatrix.matrix[k][3] = bone.velocityRoot[k]; } } - } - else - { + } else { vec3_t delAngles; VectorClear(delAngles); - for (k=0;k<3;k++) - { - tAngles[k]+=0.5f; - Create_Matrix(tAngles,&temp2); //dest 2nd arg - tAngles[k]-=0.5f; - Mat3x4_Multiply(&temp1,&P,&temp2); //dest first arg - Mat3x4_Multiply(&Gs[k],&temp1,&N); //dest first arg - + for (k = 0; k < 3; k++) { + tAngles[k] += 0.5f; + Create_Matrix(tAngles, &temp2); // dest 2nd arg + tAngles[k] -= 0.5f; + Mat3x4_Multiply(&temp1, &P, &temp2); // dest first arg + Mat3x4_Multiply(&Gs[k], &temp1, &N); // dest first arg } - int allSolidCount = 0;//bone.solidCount; + int allSolidCount = 0; // bone.solidCount; // fixme precompute this - int numDep=G2_GetBoneDependents(ghoul2,bone.boneNumber,tempDependents,MAX_BONES_RAG); + int numDep = G2_GetBoneDependents(ghoul2, bone.boneNumber, tempDependents, MAX_BONES_RAG); int j; - int numRagDep=0; - for (j=0;jragIndex; - assert(depIndex>i); // these are supposed to be topologically sorted + int depIndex = rag[tempDependents[j]]->ragIndex; + assert(depIndex > i); // these are supposed to be topologically sorted assert(ragBoneData[depIndex]); - boneInfo_t &depBone=*ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector + boneInfo_t &depBone = *ragBoneData[depIndex]; + if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Mat3x4_Multiply(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Mat3x4_Multiply(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } allSolidCount += depBone.solidCount; } } - //bone.solidCount = allSolidCount; + // bone.solidCount = allSolidCount; allSolidCount += bone.solidCount; - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9=0.75f; // dampfactor for angle changes - float magicFactor1=0.40f; //controls the speed of the gradient descent - float magicFactor32 = 1.5f; - float recip=0.0f; - if (numRagDep) - { - recip=sqrt(4.0f/float(numRagDep)); + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = 0.40f; // controls the speed of the gradient descent + float magicFactor32 = 1.5f; + float recip = 0.0f; + if (numRagDep) { + recip = sqrt(4.0f / float(numRagDep)); } - if (allSolidCount > 32) - { + if (allSolidCount > 32) { magicFactor1 = 0.6f; - } - else if (allSolidCount > 10) - { + } else if (allSolidCount > 10) { magicFactor1 = 0.5f; } - if (bone.overGradSpeed) - { //api call was made to specify a speed for this bone + if (bone.overGradSpeed) { // api call was made to specify a speed for this bone magicFactor1 = bone.overGradSpeed; } - float fac=decay*recip*magicFactor1; - assert(fac>=0.0f); + float fac = decay * recip * magicFactor1; + assert(fac >= 0.0f); #if 0 if (bone.RagFlags & RAG_PCJ_PELVIS) { magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable } #endif - if (ragState==ERS_DYNAMIC) - { - magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + if (ragState == ERS_DYNAMIC) { + magicFactor9 = .85f; // we don't want this swinging radically, make the whole thing kindof unstable } -#if 1 //constraint breaks? - if (bone.RagFlags & RAG_UNSNAPPABLE) - { +#if 1 // constraint breaks? + if (bone.RagFlags & RAG_UNSNAPPABLE) { magicFactor32 = 1.0f; } #endif - for (k=0;k<3;k++) - { - bone.currentAngles[k]+=delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k]=(bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; - bone.currentAngles[k]=AngleNormZero(bone.currentAngles[k]); + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); // bone.currentAngles[k]=flrand(bone.minAngles[k],bone.maxAngles[k]); -#if 1 //constraint breaks? - if (limitAngles && ( allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE) )) //32 tries and still in solid? Then we'll let you move freely +#if 1 // constraint breaks? + if (limitAngles && (allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE))) // 32 tries and still in solid? Then we'll let you move freely #else if (limitAngles) #endif { - if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) - { - //magicFactor32 += (allSolidCount/32); + if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) { + // magicFactor32 += (allSolidCount/32); - if (bone.currentAngles[k]>bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k]=bone.maxAngles[k]*magicFactor32; + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k]bone.maxAngles[k]*magicFactor32) - { + for (k = 0; k < 3; k++) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { isSnapped = true; break; } - if (bone.currentAngles[k]ragIndex; - if (!ragBoneData[depIndex]) - { + int depIndex = rag[tempDependents[j]]->ragIndex; + if (!ragBoneData[depIndex]) { continue; } - boneInfo_t &depBone=*ragBoneData[depIndex]; + boneInfo_t &depBone = *ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) - { + if (depBone.RagFlags & RAG_EFFECTOR) { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Mat3x4_Multiply(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Mat3x4_Multiply(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } } } @@ -4361,221 +3747,173 @@ static void G2_IKSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameN VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9 = 0.75f; // dampfactor for angle changes - float magicFactor1 = bone.ikSpeed; //controls the speed of the gradient descent - float magicFactor32 = 1.0f; - float recip = 0.0f; - bool freeThisBone = false; + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = bone.ikSpeed; // controls the speed of the gradient descent + float magicFactor32 = 1.0f; + float recip = 0.0f; + bool freeThisBone = false; - if (!magicFactor1) - { + if (!magicFactor1) { magicFactor1 = 0.40f; } - - recip = sqrt(4.0f/1.0f); - float fac = (decay*recip*magicFactor1); + recip = sqrt(4.0f / 1.0f); + + float fac = (decay * recip * magicFactor1); assert(fac >= 0.0f); - if (ragState == ERS_DYNAMIC) - { + if (ragState == ERS_DYNAMIC) { magicFactor9 = 0.85f; // we don't want this swinging radically, make the whole thing kindof unstable } - - if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && - !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) - { + if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) { freeThisBone = true; } - for (k = 0; k < 3; k++) - { - bone.currentAngles[k] += delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k] = (bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); - if (limitAngles && !freeThisBone) - { - if (bone.currentAngles[k] > bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.maxAngles[k]*magicFactor32; + if (limitAngles && !freeThisBone) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k] < bone.minAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.minAngles[k]*magicFactor32; + if (bone.currentAngles[k] < bone.minAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.minAngles[k] * magicFactor32; } } } Create_Matrix(bone.currentAngles, &temp1); bone.ragOverrideMatrix = *bone.basepose * (temp1 * *bone.baseposeInv); - assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + assert(!Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); G2_Generate_MatrixRag(blist, ragBlistIndex[bone.boneNumber]); } } -static void G2_DoIK(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params) -{ +static void G2_DoIK(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params) { int i; - if (!params) - { + if (!params) { assert(0); return; } - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; - int iters = 12; //since we don't trace or anything, we can afford this. + int iters = 12; // since we don't trace or anything, we can afford this. - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,params->position,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, params->position, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (i=0;iangles,params->position,params->scale); + for (i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); G2_IKReposition(params->position, params); - G2_IKSolve(ghoul2V,g2Index,decay*2.0f,frameNum,params->position,true); + G2_IKSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, params->position, true); } } - if (params->me != ENTITYNUM_NONE) - { - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); + if (params->me != ENTITYNUM_NONE) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); } } -//rww - cut out the entire non-ragdoll section of this.. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index,CRagDollUpdateParams *params) -{ - bool anyRagDoll=false; +// rww - cut out the entire non-ragdoll section of this.. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index, CRagDollUpdateParams *params) { + bool anyRagDoll = false; bool anyIK = false; - for(size_t i=0; iangles, parms->position); @@ -4584,27 +3922,26 @@ void G2_InitIK(CGhoul2Info_v &ghoul2V, sharedRagDollUpdateParams_t *parms, int t // new base anim, unconscious flop int pcjFlags; - //Only need the standard effectors for this. - pcjFlags = RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rhand",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lhand",pcjFlags,6.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ceyebrow",pcjFlags,10.0f); + // Only need the standard effectors for this. + pcjFlags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rhand", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lhand", pcjFlags, 6.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ceyebrow", pcjFlags, 10.0f); } -qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ - model_t *mod_a; +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + model_t *mod_a; int g2index = 0; int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; @@ -4613,19 +3950,15 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName boneInfo_v &blist = g2.mBlist; mod_a = (model_t *)g2.animModel; - if (!boneName) - { //null bonename param means it's time to init the ik stuff on this instance + if (!boneName) { // null bonename param means it's time to init the ik stuff on this instance sharedRagDollUpdateParams_t sRDUP; - if (ikState == IKS_NONE) - { //this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags + if (ikState == IKS_NONE) { // this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags size_t i = 0; - while (i < blist.size()) - { //we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ - //limb after they reset it gameside, it's reasonable for IK bones. + while (i < blist.size()) { // we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ + // limb after they reset it gameside, it's reasonable for IK bones. boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1) - { + if (bone.boneNumber != -1) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -4637,8 +3970,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName } assert(params); - if (!params) - { + if (!params) { return qfalse; } @@ -4651,60 +3983,53 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } - if (!rmod_a || !mod_a) - { + if (!rmod_a || !mod_a) { return qfalse; } int index = G2_Find_Bone(mod_a, blist, boneName); - - if (index == -1) - { + + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index == -1) - { //couldn't find or add the bone.. + if (index == -1) { // couldn't find or add the bone.. return qfalse; } boneInfo_t &bone = blist[index]; - if (ikState == IKS_NONE) - { //remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since - //we don't store bone index handles gameside anywhere. - if (!(bone.flags & BONE_ANGLES_RAGDOLL)) - { //you can't set the ik state to none if it's not a rag/ik bone. + if (ikState == IKS_NONE) { // remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since + // we don't store bone index handles gameside anywhere. + if (!(bone.flags & BONE_ANGLES_RAGDOLL)) { // you can't set the ik state to none if it's not a rag/ik bone. return qfalse; } - //bone.flags = 0; - //G2_Remove_Bone_Index(blist, index); - //actually, I want to keep it on the rag list, and remove it as an IK bone instead. + // bone.flags = 0; + // G2_Remove_Bone_Index(blist, index); + // actually, I want to keep it on the rag list, and remove it as an IK bone instead. bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags |= BONE_ANGLES_IK; bone.RagFlags &= ~RAG_PCJ_IK_CONTROLLED; return qtrue; } - //need params if we're not resetting. - if (!params) - { + // need params if we're not resetting. + if (!params) { assert(0); return qfalse; } - if (bone.flags & BONE_ANGLES_RAGDOLL) - { //otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be BONE_ANGLES_IK, active are considered rag) + if (bone.flags & BONE_ANGLES_RAGDOLL) { // otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be + // BONE_ANGLES_IK, active are considered rag) return qfalse; } G2_GenerateWorldMatrix(params->angles, params->origin); G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); - int pcjFlags = RAG_PCJ|RAG_PCJ_IK_CONTROLLED|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + int pcjFlags = RAG_PCJ | RAG_PCJ_IK_CONTROLLED | RAG_PCJ_POST_MULT | RAG_EFFECTOR; - if (params->pcjOverrides) - { + if (params->pcjOverrides) { pcjFlags = params->pcjOverrides; } @@ -4715,11 +4040,10 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName int startFrame = params->startFrame, endFrame = params->endFrame; - if (bone.startFrame != startFrame || bone.endFrame != endFrame || params->forceAnimOnBone) - { //if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. - G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f, curTime, float(startFrame), 150, 0, true); + if (bone.startFrame != startFrame || bone.endFrame != endFrame || + params->forceAnimOnBone) { // if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. + G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); } G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); @@ -4727,8 +4051,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName bone.lastTimeUpdated = 0; G2_Set_Bone_Angles_Rag(g2, rmod_a, blist, boneName, pcjFlags, params->radius, params->pcjMins, params->pcjMaxs, params->blendTime); - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { assert(!"failed to add any rag bones"); return qfalse; } @@ -4736,8 +4059,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } -qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { #if 0 model_t *mod_a; int g2index = 0; @@ -4778,17 +4100,15 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; - //rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { //changed models, possibly. + // rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { // changed models, possibly. return qfalse; } - for (int i=0;idesiredOrigin, bone.ikPosition); bone.ikSpeed = params->movementSpeed; @@ -4799,21 +4119,16 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params } // set the bone list to all unused so the bone transformation routine ignores it. -void G2_Init_Bone_List(boneInfo_v &blist, int numBones) -{ +void G2_Init_Bone_List(boneInfo_v &blist, int numBones) { blist.clear(); blist.reserve(numBones); } -void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) -{ +void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; imFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); +int G2_Get_Bone_Index(CGhoul2Info *ghoul2, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2->mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); return (G2_Find_Bone(mod_a, ghoul2->mBlist, boneName)); } diff --git a/codemp/rd-rend2/G2_gore_r2.cpp b/codemp/rd-rend2/G2_gore_r2.cpp index f28d367bfa..fa1e10bd20 100644 --- a/codemp/rd-rend2/G2_gore_r2.cpp +++ b/codemp/rd-rend2/G2_gore_r2.cpp @@ -25,17 +25,11 @@ along with this program; if not, see . #ifdef _G2_GORE -R2GoreTextureCoordinates::R2GoreTextureCoordinates() -{ - Com_Memset (tex, 0, sizeof (tex)); -} +R2GoreTextureCoordinates::R2GoreTextureCoordinates() { Com_Memset(tex, 0, sizeof(tex)); } -R2GoreTextureCoordinates::~R2GoreTextureCoordinates() -{ - for ( int i = 0; i < MAX_LODS; i++ ) - { - if ( tex[i] ) - { +R2GoreTextureCoordinates::~R2GoreTextureCoordinates() { + for (int i = 0; i < MAX_LODS; i++) { + if (tex[i]) { ri.Z_Free(tex[i]->verts); tex[i]->verts = NULL; ri.Z_Free(tex[i]->indexes); diff --git a/codemp/rd-rend2/G2_misc.cpp b/codemp/rd-rend2/G2_misc.cpp index ac64001c4e..d231f967d1 100644 --- a/codemp/rd-rend2/G2_misc.cpp +++ b/codemp/rd-rend2/G2_misc.cpp @@ -12,331 +12,260 @@ #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) -static int CurrentTag=GORE_TAG_UPPER+1; -static int CurrentTagUpper=GORE_TAG_UPPER; +static int CurrentTag = GORE_TAG_UPPER + 1; +static int CurrentTagUpper = GORE_TAG_UPPER; static std::map GoreRecords; -static std::map,int> GoreTagsTemp; // this is a surface index to gore tag map used only - // temporarily during the generation phase so we reuse gore tags per LOD +static std::map, int> GoreTagsTemp; // this is a surface index to gore tag map used only + // temporarily during the generation phase so we reuse gore tags per LOD int goreModelIndex; -static cvar_t *cg_g2MarksAllModels=NULL; +static cvar_t *cg_g2MarksAllModels = NULL; R2GoreTextureCoordinates *FindR2GoreRecord(int tag); -static inline void DestroyGoreTexCoordinates(int tag) -{ +static inline void DestroyGoreTexCoordinates(int tag) { R2GoreTextureCoordinates *gTC = FindR2GoreRecord(tag); - if (!gTC) - { + if (!gTC) { return; } gTC->~R2GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } - -int AllocR2GoreRecord() -{ - while (GoreRecords.size()>MAX_GORE_RECORDS) - { - int tagHigh=(*GoreRecords.begin()).first&GORE_TAG_MASK; +int AllocR2GoreRecord() { + while (GoreRecords.size() > MAX_GORE_RECORDS) { + int tagHigh = (*GoreRecords.begin()).first & GORE_TAG_MASK; std::map::iterator it; R2GoreTextureCoordinates *gTC; it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~R2GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); - while (GoreRecords.size()) - { - if (((*GoreRecords.begin()).first&GORE_TAG_MASK)!=tagHigh) - { + while (GoreRecords.size()) { + if (((*GoreRecords.begin()).first & GORE_TAG_MASK) != tagHigh) { break; } it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~R2GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); } } - int ret=CurrentTag; - GoreRecords[CurrentTag]= R2GoreTextureCoordinates(); + int ret = CurrentTag; + GoreRecords[CurrentTag] = R2GoreTextureCoordinates(); CurrentTag++; return ret; } -void ResetGoreTag() -{ +void ResetGoreTag() { GoreTagsTemp.clear(); - CurrentTag=CurrentTagUpper; - CurrentTagUpper+=GORE_TAG_UPPER; + CurrentTag = CurrentTagUpper; + CurrentTagUpper += GORE_TAG_UPPER; } -R2GoreTextureCoordinates *FindR2GoreRecord(int tag) -{ - std::map::iterator i=GoreRecords.find(tag); - if (i!=GoreRecords.end()) - { +R2GoreTextureCoordinates *FindR2GoreRecord(int tag) { + std::map::iterator i = GoreRecords.find(tag); + if (i != GoreRecords.end()) { return &(*i).second; } return 0; } -void *G2_GetGoreRecord(int tag) -{ - return FindR2GoreRecord(tag); -} +void *G2_GetGoreRecord(int tag) { return FindR2GoreRecord(tag); } -void DeleteR2GoreRecord(int tag) -{ +void DeleteR2GoreRecord(int tag) { DestroyGoreTexCoordinates(tag); GoreRecords.erase(tag); } -static int CurrentGoreSet=1; // this is a UUID for gore sets -static std::map GoreSets; // map from uuid to goreset +static int CurrentGoreSet = 1; // this is a UUID for gore sets +static std::map GoreSets; // map from uuid to goreset -CGoreSet *FindGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { +CGoreSet *FindGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { return (*f).second; } return 0; } -CGoreSet *NewGoreSet() -{ - CGoreSet *ret=new CGoreSet(CurrentGoreSet++); - GoreSets[ret->mMyGoreSetTag]=ret; +CGoreSet *NewGoreSet() { + CGoreSet *ret = new CGoreSet(CurrentGoreSet++); + GoreSets[ret->mMyGoreSetTag] = ret; ret->mRefCount = 1; return ret; } -void DeleteGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { - if ( (*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0 ) - { +void DeleteGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { + if ((*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0) { delete (*f).second; GoreSets.erase(f); - } - else - { + } else { (*f).second->mRefCount--; } } } - -CGoreSet::~CGoreSet() -{ - std::multimap::iterator i; - for (i=mGoreRecords.begin();i!=mGoreRecords.end();i++) - { +CGoreSet::~CGoreSet() { + std::multimap::iterator i; + for (i = mGoreRecords.begin(); i != mGoreRecords.end(); i++) { DeleteR2GoreRecord((*i).second.mGoreTag); } }; #endif // _SOF2 -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache); +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache); #ifdef _MSC_VER -#pragma warning(disable : 4512) //assignment op could not be genereated +#pragma warning(disable : 4512) // assignment op could not be genereated #endif -class CTraceSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - model_t *currentModel; - int lod; - vec3_t rayStart; - vec3_t rayEnd; - CollisionRecord_t *collRecMap; - int entNum; - int modelIndex; - skin_t *skin; +class CTraceSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + model_t *currentModel; + int lod; + vec3_t rayStart; + vec3_t rayEnd; + CollisionRecord_t *collRecMap; + int entNum; + int modelIndex; + skin_t *skin; #ifdef _WIN32 - struct shader_t *cust_shader; + struct shader_t *cust_shader; #else - shader_t *cust_shader; + shader_t *cust_shader; #endif - size_t *TransformedVertsArray; - int traceFlags; - bool hitOne; - float m_fRadius; + size_t *TransformedVertsArray; + int traceFlags; + bool hitOne; + float m_fRadius; #ifdef _G2_GORE - //gore application thing - float ssize; - float tsize; - float theta; - int goreShader; - CGhoul2Info *ghoul2info; + // gore application thing + float ssize; + float tsize; + float theta; + int goreShader; + CGhoul2Info *ghoul2info; // Procedural-gore application things - SSkinGoreData *gore; + SSkinGoreData *gore; #endif - CTraceSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - int initlod, - vec3_t initrayStart, - vec3_t initrayEnd, - CollisionRecord_t *initcollRecMap, - int initentNum, - int initmodelIndex, - skin_t *initskin, - shader_t *initcust_shader, - size_t *initTransformedVertsArray, - int inittraceFlags, + CTraceSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, model_t *initcurrentModel, int initlod, vec3_t initrayStart, vec3_t initrayEnd, + CollisionRecord_t *initcollRecMap, int initentNum, int initmodelIndex, skin_t *initskin, shader_t *initcust_shader, + size_t *initTransformedVertsArray, int inittraceFlags, #ifdef _G2_GORE - float fRadius, - float initssize, - float inittsize, - float inittheta, - int initgoreShader, - CGhoul2Info *initghoul2info, - SSkinGoreData *initgore): + float fRadius, float initssize, float inittsize, float inittheta, int initgoreShader, CGhoul2Info *initghoul2info, SSkinGoreData *initgore) + : #else - float fRadius): + float fRadius) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - currentModel(initcurrentModel), - lod(initlod), - collRecMap(initcollRecMap), - entNum(initentNum), - modelIndex(initmodelIndex), - skin(initskin), - cust_shader(initcust_shader), - TransformedVertsArray(initTransformedVertsArray), - traceFlags(inittraceFlags), + surfaceNum(initsurfaceNum), rootSList(initrootSList), currentModel(initcurrentModel), lod(initlod), collRecMap(initcollRecMap), entNum(initentNum), + modelIndex(initmodelIndex), skin(initskin), cust_shader(initcust_shader), TransformedVertsArray(initTransformedVertsArray), + traceFlags(inittraceFlags), #ifdef _G2_GORE - m_fRadius(fRadius), - ssize(initssize), - tsize(inittsize), - theta(inittheta), - goreShader(initgoreShader), - ghoul2info(initghoul2info), - gore(initgore) + m_fRadius(fRadius), ssize(initssize), tsize(inittsize), theta(inittheta), goreShader(initgoreShader), ghoul2info(initghoul2info), gore(initgore) #else - m_fRadius(fRadius) + m_fRadius(fRadius) #endif { VectorCopy(initrayStart, rayStart); VectorCopy(initrayEnd, rayEnd); hitOne = false; - } - + } }; // assorted Ghoul 2 functions. // list all surfaces associated with a model -void G2_List_Model_Surfaces(const char *fileName) -{ - int i, x; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - mdxmSurfHierarchy_t *surf; +void G2_List_Model_Surfaces(const char *fileName) { + int i, x; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + mdxmSurfHierarchy_t *surf; mdxmHeader_t *mdxm = mod_m->data.glm->header; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); mdxmSurface_t *surface = (mdxmSurface_t *)((byte *)mdxm + mdxm->ofsLODs + sizeof(mdxmLOD_t)); - for ( x = 0 ; x < mdxm->numSurfaces ; x++) - { + for (x = 0; x < mdxm->numSurfaces; x++) { Com_Printf("Surface %i Name %s\n", x, surf->name); - if ( r_verbose->integer ) - { - Com_Printf("Num Descendants %i\n", surf->numChildren); - for (i=0; inumChildren; i++) - { + if (r_verbose->integer) { + Com_Printf("Num Descendants %i\n", surf->numChildren); + for (i = 0; i < surf->numChildren; i++) { Com_Printf("Descendant %i\n", surf->childIndexes[i]); } } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); - surface =(mdxmSurface_t *)( (byte *)surface + surface->ofsEnd ); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); + surface = (mdxmSurface_t *)((byte *)surface + surface->ofsEnd); } - } // list all bones associated with a model -void G2_List_Model_Bones(const char *fileName, int frame) -{ - int x, i; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); -// mdxaFrame_t *aframe=0; -// int frameSize; - mdxaHeader_t *header = mod_a->data.gla; +void G2_List_Model_Bones(const char *fileName, int frame) { + int x, i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + // mdxaFrame_t *aframe=0; + // int frameSize; + mdxaHeader_t *header = mod_a->data.gla; // figure out where the offset list is offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); -// frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); + // frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); -// aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); + // aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); // walk each bone and list it's name - for (x=0; x< header->numBones; x++) - { + for (x = 0; x < header->numBones; x++) { skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[x]); Com_Printf("Bone %i Name %s\n", x, skel->name); Com_Printf("X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); // if we are in verbose mode give us more details - if ( r_verbose->integer ) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); - for (i=0; inumChildren; i++) - { - Com_Printf("Num Descendants %i\n", skel->numChildren); + if (r_verbose->integer) { + Com_Printf("Num Descendants %i\n", skel->numChildren); + for (i = 0; i < skel->numChildren; i++) { + Com_Printf("Num Descendants %i\n", skel->numChildren); } } } } - /************************************************************************************************ * G2_GetAnimFileName * obtain the .gla filename for a model * * Input - * filename of model + * filename of model * * Output * true if we successfully obtained a filename, false otherwise * ************************************************************************************************/ -qboolean G2_GetAnimFileName(const char *fileName, char **filename) -{ +qboolean G2_GetAnimFileName(const char *fileName, char **filename) { // find the model we want - model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); - if (mod) - { + if (mod) { mdxmHeader_t *mdxm = mod->data.glm->header; - if (mdxm && mdxm->animName[0] != 0) - { + if (mdxm && mdxm->animName[0] != 0) { *filename = mdxm->animName; return qtrue; } @@ -344,91 +273,82 @@ qboolean G2_GetAnimFileName(const char *fileName, char **filename) return qfalse; } - ///////////////////////////////////////////////////////////////////// -// +// // Code for collision detection for models gameside // ///////////////////////////////////////////////////////////////////// -int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) -{ +int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) { int returnLod = useLod; - // if we are overriding the LOD at top level, then we can afford to only check this level of model - if (ghoul2.mLodBias > returnLod) - { - returnLod = ghoul2.mLodBias; - } -// assert(G2_MODEL_OK(&ghoul2)); - + // if we are overriding the LOD at top level, then we can afford to only check this level of model + if (ghoul2.mLodBias > returnLod) { + returnLod = ghoul2.mLodBias; + } + // assert(G2_MODEL_OK(&ghoul2)); + mdxmHeader_t *mdxm = ghoul2.currentModel->data.glm->header; assert(ghoul2.currentModel); assert(mdxm); - //what about r_lodBias? + // what about r_lodBias? // now ensure that we haven't selected a lod that doesn't exist for this model - if ( returnLod >= mdxm->numLODs ) - { - returnLod = mdxm->numLODs - 1; - } + if (returnLod >= mdxm->numLODs) { + returnLod = mdxm->numLODs - 1; + } return returnLod; } -void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray,CBoneCache *boneCache) -{ - int j, k; - mdxmVertex_t *v; - float *TransformedVerts; +void R_TransformEachSurface(const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray, CBoneCache *boneCache) { + int j, k; + mdxmVertex_t *v; + float *TransformedVerts; // // deform the vertexes by the lerped bones // - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); - + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); + // alloc some space for the transformed verts to get put in TransformedVerts = (float *)G2VertSpace->MiniHeapAlloc(surface->numVerts * 5 * 4); TransformedVertsArray[surface->thisSurfaceIndex] = (size_t)TransformedVerts; - if (!TransformedVerts) - { + if (!TransformedVerts) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } // whip through and actually transform each vertex const int numVerts = surface->numVerts; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // optimisation issue - if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) - { - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// mdxmWeight_t *w; + if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) { + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } int pos = j * 5; @@ -440,38 +360,34 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } - } - else - { + } else { int pos = 0; - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// const mdxmWeight_t *w; + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // const mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } // copy tranformed verts into temp space @@ -482,48 +398,43 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos++] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } } } -void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) -{ - int i; +void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, + IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) { + int i; assert(currentModel); assert(currentModel->data.glm && currentModel->data.glm->header); // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void*)currentModel, surfaceNum, lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); - + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { + if (!offFlags) { R_TransformEachSurface(surface, scale, G2VertSpace, TransformedVertArray, boneCache); } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { G2_TransformSurfaces(surfInfo->childIndexes[i], rootSList, boneCache, currentModel, lod, scale, G2VertSpace, TransformedVertArray, secondTimeAround); } } @@ -535,72 +446,59 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, IHeapAllocator *G2VertSpace, int useLod) #endif { - int i, lod; - vec3_t correctScale; - qboolean firstModelOnly = qfalse; + int i, lod; + vec3_t correctScale; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models"); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe - if (!scale[0]) - { + if (!scale[0]) { correctScale[0] = 1.0; } - if (!scale[1]) - { + if (!scale[1]) { correctScale[1] = 1.0; } - if (!scale[2]) - { + if (!scale[2]) { correctScale[2] = 1.0; } // walk each possible model for this entity and try rendering it out - for (i=0; i=g.currentModel->numLods) - { + if (lod >= g.currentModel->numLods) { g.mTransformedVertsArray = 0; - if ( firstModelOnly ) - { + if (firstModelOnly) { // we don't really need to do multiple models for gore. return; } - //do the rest + // do the rest continue; } - } - else - { + } else { #endif lod = G2_DecideTraceLod(g, useLod); #ifdef _G2_GORE @@ -610,25 +508,22 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, mdxmHeader_t *mdxm = g.currentModel->data.glm->header; // give us space for the transformed vertex array to be put in - if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) - { //do not stomp if we're using zone space - g.mTransformedVertsArray = (size_t*)G2VertSpace->MiniHeapAlloc(mdxm->numSurfaces * sizeof (size_t)); - if (!g.mTransformedVertsArray) - { + if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) { // do not stomp if we're using zone space + g.mTransformedVertsArray = (size_t *)G2VertSpace->MiniHeapAlloc(mdxm->numSurfaces * sizeof(size_t)); + if (!g.mTransformedVertsArray) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } } - memset(g.mTransformedVertsArray, 0,mdxm->numSurfaces * sizeof (size_t)); + memset(g.mTransformedVertsArray, 0, mdxm->numSurfaces * sizeof(size_t)); - G2_FindOverrideSurface(-1,g.mSlist); //reset the quick surface override lookup; + G2_FindOverrideSurface(-1, g.mSlist); // reset the quick surface override lookup; // recursively call the model surface transform - G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); + G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); #ifdef _G2_GORE - if (ApplyGore && firstModelOnly) - { + if (ApplyGore && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -636,11 +531,9 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, } } - // work out how much space a triangle takes -static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) -{ - vec3_t cross, ab, cb; +static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) { + vec3_t cross, ab, cb; VectorSubtract(A, B, ab); VectorSubtract(C, B, cb); @@ -650,75 +543,65 @@ static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) } // actually determine the S and T of the coordinate we hit in a given poly -static void G2_BuildHitPointST( const vec3_t A, const float SA, const float TA, - const vec3_t B, const float SB, const float TB, - const vec3_t C, const float SC, const float TC, - const vec3_t P, float *s, float *t,float &bary_i,float &bary_j) -{ - float areaABC = G2_AreaOfTri(A, B, C); +static void G2_BuildHitPointST(const vec3_t A, const float SA, const float TA, const vec3_t B, const float SB, const float TB, const vec3_t C, const float SC, + const float TC, const vec3_t P, float *s, float *t, float &bary_i, float &bary_j) { + float areaABC = G2_AreaOfTri(A, B, C); float i = G2_AreaOfTri(P, B, C) / areaABC; - bary_i=i; + bary_i = i; float j = G2_AreaOfTri(A, P, C) / areaABC; - bary_j=j; + bary_j = j; float k = G2_AreaOfTri(A, B, P) / areaABC; *s = SA * i + SB * j + SC * k; *t = TA * i + TB * j + TC * k; - *s=fmod(*s, 1); - if (*s< 0) - { - *s+= 1.0; + *s = fmod(*s, 1); + if (*s < 0) { + *s += 1.0; } - *t=fmod(*t, 1); - if (*t< 0) - { - *t+= 1.0; + *t = fmod(*t, 1); + if (*t < 0) { + *t += 1.0; } - } - // routine that works out given a ray whether or not it hits a poly -qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, - const vec3_t A, const vec3_t B, const vec3_t C, - qboolean backFaces,qboolean frontFaces,vec3_t returnedPoint,vec3_t returnedNormal, float *denom) -{ - static const float tiny=1E-10f; +qboolean G2_SegmentTriangleTest(const vec3_t start, const vec3_t end, const vec3_t A, const vec3_t B, const vec3_t C, qboolean backFaces, qboolean frontFaces, + vec3_t returnedPoint, vec3_t returnedNormal, float *denom) { + static const float tiny = 1E-10f; vec3_t returnedNormalT; vec3_t edgeAC; VectorSubtract(C, A, edgeAC); - VectorSubtract(B, A, returnedNormalT); + VectorSubtract(B, A, returnedNormalT); CrossProduct(returnedNormalT, edgeAC, returnedNormal); - + vec3_t ray; VectorSubtract(end, start, ray); - *denom=DotProduct(ray, returnedNormal); - - if (fabs(*denom)0)|| // not accepting back faces - (!frontFaces && *denom<0)) //not accepting front faces + *denom = DotProduct(ray, returnedNormal); + + if (fabs(*denom) < tiny || // triangle parallel to ray + (!backFaces && *denom > 0) || // not accepting back faces + (!frontFaces && *denom < 0)) // not accepting front faces { return qfalse; } vec3_t toPlane; VectorSubtract(A, start, toPlane); - - float t=DotProduct(toPlane, returnedNormal)/ *denom; - - if (t<0.0f||t>1.0f) - { + + float t = DotProduct(toPlane, returnedNormal) / *denom; + + if (t < 0.0f || t > 1.0f) { return qfalse; // off segment } - + VectorScale(ray, t, ray); - + VectorAdd(ray, start, returnedPoint); vec3_t edgePA; @@ -729,260 +612,218 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t edgePC; VectorSubtract(C, returnedPoint, edgePC); - + vec3_t temp; - + CrossProduct(edgePA, edgePB, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePC, edgePA, temp); - if (DotProduct(temp,returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } - + CrossProduct(edgePB, edgePC, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle - } + } return qtrue; } #ifdef _G2_GORE -struct SVertexTemp -{ +struct SVertexTemp { int flags; int touch; int newindex; float tex[2]; - SVertexTemp() - { - touch=0; - } + SVertexTemp() { touch = 0; } }; static SVertexTemp GoreVerts[MAX_GORE_VERTS]; static int GoreIndexCopy[MAX_GORE_VERTS]; -static int GoreTouch=1; +static int GoreTouch = 1; static int GoreIndecies[MAX_GORE_INDECIES]; #define GORE_MARGIN (0.0f) -int G2API_GetTime(int argTime); +int G2API_GetTime(int argTime); // now we at poly level, check each model space transformed poly against the model world transfomed ray -void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) -{ - int j; +void G2_GorePolys(const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + CrossProduct(TS.rayEnd, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(TS.rayEnd, basis2, basis1); } - CrossProduct(TS.rayEnd,basis1,basis2); + CrossProduct(TS.rayEnd, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil - assert(DotProduct(basis1,basis1)>.0001f); - assert(DotProduct(basis2,basis2)>.0001f); + assert(DotProduct(basis1, basis1) > .0001f); + assert(DotProduct(basis2, basis2) > .0001f); VectorNormalize(basis1); VectorNormalize(basis2); - float c=cos(TS.theta); - float s=sin(TS.theta); + float c = cos(TS.theta); + float s = sin(TS.theta); - VectorScale(basis1,.5f*c/TS.tsize,taxis); - VectorMA(taxis,.5f*s/TS.tsize,basis2,taxis); + VectorScale(basis1, .5f * c / TS.tsize, taxis); + VectorMA(taxis, .5f * s / TS.tsize, basis2, taxis); - VectorScale(basis1,-.5f*s/TS.ssize,saxis); - VectorMA(saxis,.5f*c/TS.ssize,basis2,saxis); + VectorScale(basis1, -.5f * s / TS.ssize, saxis); + VectorMA(saxis, .5f * c / TS.ssize, basis2, saxis); float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; int numVerts = surface->numVerts; - int flags=15; - assert(numVertsGORE_MARGIN) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + float s = DotProduct(delta, saxis) + 0.5f; + float t = DotProduct(delta, taxis) + 0.5f; + int vflags = 0; + if (s > GORE_MARGIN) { + vflags |= 1; } - if (s<1.0f-GORE_MARGIN) - { - vflags|=2; + if (s < 1.0f - GORE_MARGIN) { + vflags |= 2; } - if (t>GORE_MARGIN) - { - vflags|=4; + if (t > GORE_MARGIN) { + vflags |= 4; } - if (t<1.0f-GORE_MARGIN) - { - vflags|=8; + if (t < 1.0f - GORE_MARGIN) { + vflags |= 8; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; - GoreVerts[j].tex[0]=s; - GoreVerts[j].tex[1]=t; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; + GoreVerts[j].tex[0] = s; + GoreVerts[j].tex[1] = t; } - if (flags) - { + if (flags) { return; // completely off the gore splotch. } - int numTris,newNumTris,newNumVerts; + int numTris, newNumTris, newNumVerts; numTris = surface->numTriangles; - mdxmTriangle_t *tris; - tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + mdxmTriangle_t *tris; + tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; - newNumTris=0; - newNumVerts=0; + newNumTris = 0; + newNumVerts = 0; GoreTouch++; - if (!TS.gore) - { + if (!TS.gore) { return; } - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 15 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; + if (flags) { continue; } - if (!TS.gore->frontFaces || !TS.gore->backFaces) - { + if (!TS.gore->frontFaces || !TS.gore->backFaces) { // we need to back/front face cull - vec3_t e1,e2,n; + vec3_t e1, e2, n; - VectorSubtract(&verts[tris[j].indexes[1]*5],&verts[tris[j].indexes[0]*5],e1); - VectorSubtract(&verts[tris[j].indexes[2]*5],&verts[tris[j].indexes[0]*5],e2); - CrossProduct(e1,e2,n); - if (DotProduct(TS.rayEnd,n)>0.0f) - { - if (!TS.gore->frontFaces) - { + VectorSubtract(&verts[tris[j].indexes[1] * 5], &verts[tris[j].indexes[0] * 5], e1); + VectorSubtract(&verts[tris[j].indexes[2] * 5], &verts[tris[j].indexes[0] * 5], e2); + CrossProduct(e1, e2, n); + if (DotProduct(TS.rayEnd, n) > 0.0f) { + if (!TS.gore->frontFaces) { continue; } - } - else - { - if (!TS.gore->backFaces) - { + } else { + if (!TS.gore->backFaces) { continue; } } - } int k; - assert(newNumTris*3+3,int>::iterator f=GoreTagsTemp.find(std::pair(goreModelIndex,TS.surfaceNum)); - if (f==GoreTagsTemp.end()) // need to generate a record + std::map, int>::iterator f = GoreTagsTemp.find(std::pair(goreModelIndex, TS.surfaceNum)); + if (f == GoreTagsTemp.end()) // need to generate a record { - newTag=AllocR2GoreRecord(); - CGoreSet *goreSet=0; - if (TS.ghoul2info->mGoreSetTag) - { - goreSet=FindGoreSet(TS.ghoul2info->mGoreSetTag); + newTag = AllocR2GoreRecord(); + CGoreSet *goreSet = 0; + if (TS.ghoul2info->mGoreSetTag) { + goreSet = FindGoreSet(TS.ghoul2info->mGoreSetTag); } - if (!goreSet) - { - goreSet=NewGoreSet(); - TS.ghoul2info->mGoreSetTag=goreSet->mMyGoreSetTag; + if (!goreSet) { + goreSet = NewGoreSet(); + TS.ghoul2info->mGoreSetTag = goreSet->mMyGoreSetTag; } assert(goreSet); SGoreSurface add; - add.shader=TS.goreShader; - add.mDeleteTime=0; - if (TS.gore->lifeTime) - { - add.mDeleteTime=G2API_GetTime(0) + TS.gore->lifeTime; + add.shader = TS.goreShader; + add.mDeleteTime = 0; + if (TS.gore->lifeTime) { + add.mDeleteTime = G2API_GetTime(0) + TS.gore->lifeTime; } add.mFadeTime = TS.gore->fadeOutTime; add.mFadeRGB = !!(TS.gore->fadeRGB); add.mGoreTag = newTag; - add.mGoreGrowStartTime=G2API_GetTime(0); - if( TS.gore->growDuration == -1) - { - add.mGoreGrowEndTime = -1; // set this to -1 to disable growing - } - else - { + add.mGoreGrowStartTime = G2API_GetTime(0); + if (TS.gore->growDuration == -1) { + add.mGoreGrowEndTime = -1; // set this to -1 to disable growing + } else { add.mGoreGrowEndTime = G2API_GetTime(0) + TS.gore->growDuration; } assert(TS.gore->growDuration != 0); - add.mGoreGrowFactor = ( 1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); //curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; - add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; - - goreSet->mGoreRecords.insert(std::pair(TS.surfaceNum,add)); - GoreTagsTemp[std::pair(goreModelIndex,TS.surfaceNum)]=newTag; - } - else - { - newTag=(*f).second; + add.mGoreGrowFactor = + (1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); // curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; + add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; + + goreSet->mGoreRecords.insert(std::pair(TS.surfaceNum, add)); + GoreTagsTemp[std::pair(goreModelIndex, TS.surfaceNum)] = newTag; + } else { + newTag = (*f).second; } - R2GoreTextureCoordinates *gore= FindR2GoreRecord(newTag); - if (gore) - { - srfG2GoreSurface_t *goreSurface=(srfG2GoreSurface_t *)Z_Malloc ( sizeof(srfG2GoreSurface_t), TAG_GHOUL2_GORE, qtrue ); + R2GoreTextureCoordinates *gore = FindR2GoreRecord(newTag); + if (gore) { + srfG2GoreSurface_t *goreSurface = (srfG2GoreSurface_t *)Z_Malloc(sizeof(srfG2GoreSurface_t), TAG_GHOUL2_GORE, qtrue); - if ( gore->tex[TS.lod] ) - { + if (gore->tex[TS.lod]) { if (gore->tex[TS.lod]->verts) Z_Free(gore->tex[TS.lod]->verts); if (gore->tex[TS.lod]->indexes) @@ -990,28 +831,25 @@ void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSu Z_Free(gore->tex[TS.lod]); } - gore->tex[TS.lod]=(srfG2GoreSurface_t *)goreSurface; + gore->tex[TS.lod] = (srfG2GoreSurface_t *)goreSurface; goreSurface->numVerts = newNumVerts; - goreSurface->verts = (g2GoreVert_t *)Z_Malloc(sizeof(g2GoreVert_t)*newNumVerts, TAG_GHOUL2_GORE, qtrue); + goreSurface->verts = (g2GoreVert_t *)Z_Malloc(sizeof(g2GoreVert_t) * newNumVerts, TAG_GHOUL2_GORE, qtrue); - for (j=0;jverts[j].texCoords[0] = GoreVerts[GoreIndexCopy[j]].tex[0]; goreSurface->verts[j].texCoords[1] = GoreVerts[GoreIndexCopy[j]].tex[1]; } mdxmVertex_t *v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); int *boneRef = (int *)((byte *)surface + surface->ofsBoneReferences); - for (j = 0; j < newNumVerts; j++) - { + for (j = 0; j < newNumVerts; j++) { mdxmVertex_t currentVert = v[GoreIndexCopy[j]]; VectorCopy(currentVert.vertCoords, goreSurface->verts[j].position); goreSurface->verts[j].normal = R_VboPackNormal(currentVert.normal); - + int numWeights = G2_GetVertWeights(¤tVert); float fTotalWeight = 0.0f; - for (int w = 0; w < numWeights; w++) - { + for (int w = 0; w < numWeights; w++) { float weight = G2_GetVertBoneWeight(¤tVert, w, fTotalWeight, numWeights); goreSurface->verts[j].weights[w] = (byte)(weight * 255.0f); int packedIndex = G2_GetVertBoneIndex(¤tVert, w); @@ -1019,9 +857,8 @@ void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSu } } - goreSurface->indexes = (glIndex_t *)Z_Malloc(sizeof(glIndex_t)*newNumTris*3, TAG_GHOUL2_GORE, qtrue); - for (j = 0; j < newNumTris * 3; j++) - { + goreSurface->indexes = (glIndex_t *)Z_Malloc(sizeof(glIndex_t) * newNumTris * 3, TAG_GHOUL2_GORE, qtrue); + for (j = 0; j < newNumTris * 3; j++) { goreSurface->indexes[j] = GoreIndecies[j] + tr.goreVBOCurrentIndex; } goreSurface->numIndexes = newNumTris * 3; @@ -1030,15 +867,13 @@ void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSu } } #else -struct SVertexTemp -{ +struct SVertexTemp { int flags; -// int touch; -// int newindex; -// float tex[2]; - SVertexTemp() - { -// touch=0; + // int touch; + // int newindex; + // float tex[2]; + SVertexTemp() { + // touch=0; } }; @@ -1047,44 +882,37 @@ static SVertexTemp GoreVerts[MAX_GORE_VERTS]; #endif // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) -{ - int j, numTris; - +static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) { + int j, numTris; + // whip through and actually transform each vertex - const mdxmTriangle_t *tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); const float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; numTris = surface->numTriangles; - for ( j = 0; j < numTris; j++ ) - { - float face; - vec3_t hitPoint, normal; + for (j = 0; j < numTris; j++) { + float face; + vec3_t hitPoint, normal; // determine actual coords for this triangle const float *point1 = &verts[(tris[j].indexes[0] * 5)]; const float *point2 = &verts[(tris[j].indexes[1] * 5)]; const float *point3 = &verts[(tris[j].indexes[2] * 5)]; // did we hit it? int i; - if (G2_SegmentTriangleTest(TS.rayStart, TS.rayEnd, point1, point2, point3, qtrue, qtrue, hitPoint, normal, &face)) - { // find space in the collision records for this record - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; - if (face>0) - { + if (face > 0) { newCol.mFlags = G2_FRONTFACE; - } - else - { + } else { newCol.mFlags = G2_BACKFACE; } @@ -1101,62 +929,61 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ newCol.mMaterial = newCol.mLocation = 0; // Determine our location within the texture, and barycentric coordinates - G2_BuildHitPointST(point1, point1[3], point1[4], - point2, point2[3], point2[4], - point3, point3[3], point3[4], - hitPoint, &x_pos, &y_pos,newCol.mBarycentricI,newCol.mBarycentricJ); - -/* - const shader_t *shader = 0; - // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit location and hit material info - if ( cust_shader ) - { - shader = cust_shader; - } - else if ( skin ) - { - int j; - - // match the surface name to something in the skin file - shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { - // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = skin->surfaces[j]->shader; - break; - } - } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); - } - - // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little point - if ((shader->hitLocation) || (shader->hitMaterial)) - { - // ok, we have a floating point position. - determine location in data we need to look at - if (shader->hitLocation) - { - newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + - ((int)(y_pos * hitMatReg[shader->hitLocation].height) * hitMatReg[shader->hitLocation].width) + - ((int)(x_pos * hitMatReg[shader->hitLocation].width))); - Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); - } - - if (shader->hitMaterial) - { - newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + - ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * hitMatReg[shader->hitMaterial].width) + - ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); - } - } -*/ + G2_BuildHitPointST(point1, point1[3], point1[4], point2, point2[3], point2[4], point3, point3[3], point3[4], hitPoint, &x_pos, &y_pos, + newCol.mBarycentricI, newCol.mBarycentricJ); + + /* + const shader_t *shader = 0; + // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit + location and hit material info if ( cust_shader ) + { + shader = cust_shader; + } + else if ( skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little + point if ((shader->hitLocation) || (shader->hitMaterial)) + { + // ok, we have a floating point position. - determine location in data we need to look at + if (shader->hitLocation) + { + newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + + ((int)(y_pos * hitMatReg[shader->hitLocation].height) * + hitMatReg[shader->hitLocation].width) + + ((int)(x_pos * hitMatReg[shader->hitLocation].width))); + Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); + } + + if (shader->hitMaterial) + { + newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + + ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * + hitMatReg[shader->hitMaterial].width) + + ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); + } + } + */ // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } @@ -1164,12 +991,11 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen - //It happens. And the assert is bugging me. - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen + // It happens. And the assert is bugging me. + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1177,148 +1003,126 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ } // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_RadiusTracePolys( - const mdxmSurface_t *surface, - CTraceSurface &TS - ) -{ - int j; +static bool G2_RadiusTracePolys(const mdxmSurface_t *surface, CTraceSurface &TS) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; vec3_t v3RayDir; VectorSubtract(TS.rayEnd, TS.rayStart, v3RayDir); - CrossProduct(v3RayDir,basis2,basis1); + CrossProduct(v3RayDir, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(v3RayDir,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(v3RayDir, basis2, basis1); } - CrossProduct(v3RayDir,basis1,basis2); + CrossProduct(v3RayDir, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil -// assert(DotProduct(basis1,basis1)>.0001f); -// assert(DotProduct(basis2,basis2)>.0001f); + // assert(DotProduct(basis1,basis1)>.0001f); + // assert(DotProduct(basis2,basis2)>.0001f); VectorNormalize(basis1); VectorNormalize(basis2); - const float c=cos(0.0f);//theta - const float s=sin(0.0f);//theta + const float c = cos(0.0f); // theta + const float s = sin(0.0f); // theta - VectorScale(basis1, 0.5f * c / TS.m_fRadius,taxis); - VectorMA(taxis, 0.5f * s / TS.m_fRadius,basis2,taxis); + VectorScale(basis1, 0.5f * c / TS.m_fRadius, taxis); + VectorMA(taxis, 0.5f * s / TS.m_fRadius, basis2, taxis); - VectorScale(basis1,-0.5f * s /TS.m_fRadius,saxis); - VectorMA( saxis, 0.5f * c /TS.m_fRadius,basis2,saxis); + VectorScale(basis1, -0.5f * s / TS.m_fRadius, saxis); + VectorMA(saxis, 0.5f * c / TS.m_fRadius, basis2, saxis); - const float * const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + const float *const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; const int numVerts = surface->numVerts; - - int flags=63; - //rayDir/=lengthSquared(raydir); - const float f = VectorLengthSquared(v3RayDir); - v3RayDir[0]/=f; - v3RayDir[1]/=f; - v3RayDir[2]/=f; - - for ( j = 0; j < numVerts; j++ ) - { - const int pos=j*5; + + int flags = 63; + // rayDir/=lengthSquared(raydir); + const float f = VectorLengthSquared(v3RayDir); + v3RayDir[0] /= f; + v3RayDir[1] /= f; + v3RayDir[2] /= f; + + for (j = 0; j < numVerts; j++) { + const int pos = j * 5; vec3_t delta; - delta[0]=verts[pos+0]-TS.rayStart[0]; - delta[1]=verts[pos+1]-TS.rayStart[1]; - delta[2]=verts[pos+2]-TS.rayStart[2]; - const float s=DotProduct(delta,saxis)+0.5f; - const float t=DotProduct(delta,taxis)+0.5f; - const float u=DotProduct(delta,v3RayDir); - int vflags=0; - - if (s>0) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + const float s = DotProduct(delta, saxis) + 0.5f; + const float t = DotProduct(delta, taxis) + 0.5f; + const float u = DotProduct(delta, v3RayDir); + int vflags = 0; + + if (s > 0) { + vflags |= 1; } - if (s<1) - { - vflags|=2; + if (s < 1) { + vflags |= 2; } - if (t>0) - { - vflags|=4; + if (t > 0) { + vflags |= 4; } - if (t<1) - { - vflags|=8; + if (t < 1) { + vflags |= 8; } - if (u>0) - { - vflags|=16; + if (u > 0) { + vflags |= 16; } - if (u<1) - { - vflags|=32; + if (u < 1) { + vflags |= 32; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; } - if (flags) - { + if (flags) { return false; // completely off the gore splotch (so presumably hit nothing? -Ste) } const int numTris = surface->numTriangles; - const mdxmTriangle_t * const tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *const tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 63 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; int i; - if (flags) - { + if (flags) { continue; - } - else - { + } else { // we hit a triangle, so init a collision record... // - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; -// if (face>0) -// { - newCol.mFlags = G2_FRONTFACE; -// } -// else -// { -// newCol.mFlags = G2_BACKFACE; -// } - - //get normal from triangle + // if (face>0) + // { + newCol.mFlags = G2_FRONTFACE; + // } + // else + // { + // newCol.mFlags = G2_BACKFACE; + // } + + // get normal from triangle const float *A = &verts[(tris[j].indexes[0] * 5)]; const float *B = &verts[(tris[j].indexes[1] * 5)]; const float *C = &verts[(tris[j].indexes[2] * 5)]; @@ -1335,28 +1139,26 @@ static bool G2_RadiusTracePolys( newCol.mMaterial = newCol.mLocation = 0; // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } - - vec3_t distVect; + vec3_t distVect; #if 0 //i don't know the hitPoint, but let's just assume it's the first vert for now... float *hitPoint = (float *)A; #else - //yeah, I want the collision point. Let's work out the impact point on the triangle. -rww + // yeah, I want the collision point. Let's work out the impact point on the triangle. -rww vec3_t hitPoint; float side, side2; float dist; - float third = -(A[0]*(B[1]*C[2] - C[1]*B[2]) + B[0]*(C[1]*A[2] - A[1]*C[2]) + C[0]*(A[1]*B[2] - B[1]*A[2]) ); + float third = -(A[0] * (B[1] * C[2] - C[1] * B[2]) + B[0] * (C[1] * A[2] - A[1] * C[2]) + C[0] * (A[1] * B[2] - B[1] * A[2])); VectorSubtract(TS.rayEnd, TS.rayStart, distVect); - side = normal[0]*TS.rayStart[0] + normal[1]*TS.rayStart[1] + normal[2]*TS.rayStart[2] + third; - side2 = normal[0]*distVect[0] + normal[1]*distVect[1] + normal[2]*distVect[2]; - dist = side/side2; + side = normal[0] * TS.rayStart[0] + normal[1] * TS.rayStart[1] + normal[2] * TS.rayStart[2] + third; + side2 = normal[0] * distVect[0] + normal[1] * distVect[1] + normal[2] * distVect[2]; + dist = side / side2; VectorMA(TS.rayStart, -dist, distVect, hitPoint); #endif @@ -1369,11 +1171,10 @@ static bool G2_RadiusTracePolys( break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1381,24 +1182,21 @@ static bool G2_RadiusTracePolys( return false; } - // look at a surface and then do the trace on each poly -static void G2_TraceSurfaces(CTraceSurface &TS) -{ - int i; +static void G2_TraceSurfaces(CTraceSurface &TS) { + int i; // back track and get the surfinfo struct for this surface assert(TS.currentModel); assert(TS.currentModel->data.glm && TS.currentModel->data.glm->header); - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); - + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); // don't allow recursion if we've already hit a polygon - if (TS.hitOne) - { + if (TS.hitOne) { return; } @@ -1406,39 +1204,28 @@ static void G2_TraceSurfaces(CTraceSurface &TS) int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, try to hit it - if (!offFlags) - { + if (!offFlags) { #ifdef _G2_GORE - if (TS.collRecMap) - { + if (TS.collRecMap) { #endif - if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace + if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace { // .. then use radius check // - if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, - TS - ) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, + TS) && + (TS.traceFlags == G2_RETURNONHIT)) { TS.hitOne = true; return; } - } - else - { + } else { // go away and trace the polys in this surface - if (G2_TracePolys(surface, surfInfo, TS) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_TracePolys(surface, surfInfo, TS) && (TS.traceFlags == G2_RETURNONHIT)) { // ok, we hit one, *and* we want to return instantly because the returnOnHit is set // so indicate we've hit one, so other surfaces don't get hit and return TS.hitOne = true; @@ -1446,124 +1233,108 @@ static void G2_TraceSurfaces(CTraceSurface &TS) } } #ifdef _G2_GORE - } - else - { + } else { G2_GorePolys(surface, TS, surfInfo); } #endif } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren && !TS.hitOne; i++) - { + for (i = 0; i < surfInfo->numChildren && !TS.hitOne; i++) { TS.surfaceNum = surfInfo->childIndexes[i]; G2_TraceSurfaces(TS); } } #ifdef _G2_GORE -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius, float ssize,float tsize,float theta,int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius, float ssize, float tsize, float theta, int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) #else -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius) #endif { - int i, lod; - skin_t *skin; - shader_t *cust_shader; - qboolean firstModelOnly = qfalse; + int i, lod; + skin_t *skin; + shader_t *cust_shader; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models"); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif // walk each possible model for this entity and try tracing against it - for (i=0; i 0 && ghoul2[i].mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( ghoul2[i].mSkin ); - } - else - { + if (ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(ghoul2[i].mSkin); + } else { skin = NULL; } - lod = G2_DecideTraceLod(ghoul2[i],useLod); + lod = G2_DecideTraceLod(ghoul2[i], useLod); #ifdef _G2_GORE - if ( skipIfLODNotMatch ) - {//we only want to hit this SPECIFIC LOD... - if ( lod != useLod ) - {//doesn't match, skip this model + if (skipIfLODNotMatch) { // we only want to hit this SPECIFIC LOD... + if (lod != useLod) { // doesn't match, skip this model continue; } } #endif - //reset the quick surface override lookup - G2_FindOverrideSurface(-1, ghoul2[i].mSlist); + // reset the quick surface override lookup + G2_FindOverrideSurface(-1, ghoul2[i].mSlist); #ifdef _G2_GORE - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); #else - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); #endif // start the surface recursion loop G2_TraceSurfaces(TS); // if we've hit one surface on one model, don't bother doing the rest - if (TS.hitOne) - { + if (TS.hitOne) { break; } #ifdef _G2_GORE - if (!collRecMap&&firstModelOnly) - { + if (!collRecMap && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -1571,29 +1342,25 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli } } -void TransformPoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2]; +void TransformPoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2]; } } -void TransformAndTranslatePoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { +void TransformAndTranslatePoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2] + mat->matrix[i][3]; + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2] + mat->matrix[i][3]; } } - // create a matrix using a set of angles -void Create_Matrix(const float *angle, mdxaBone_t *matrix) -{ - vec3_t axis[3]; +void Create_Matrix(const float *angle, mdxaBone_t *matrix) { + vec3_t axis[3]; // convert angles to axis - AnglesToAxis( angle, axis ); + AnglesToAxis(angle, axis); matrix->matrix[0][0] = axis[0][0]; matrix->matrix[1][0] = axis[0][1]; matrix->matrix[2][0] = axis[0][2]; @@ -1609,35 +1376,27 @@ void Create_Matrix(const float *angle, mdxaBone_t *matrix) matrix->matrix[0][3] = 0; matrix->matrix[1][3] = 0; matrix->matrix[2][3] = 0; - - } // given a matrix, generate the inverse of that matrix -void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) -{ +void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) { int i, j; - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - dest->matrix[i][j]=src->matrix[j][i]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + dest->matrix[i][j] = src->matrix[j][i]; } } - for (i = 0; i < 3; i++) - { - dest->matrix[i][3]=0; - for (j = 0; j < 3; j++) - { - dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + for (i = 0; i < 3; i++) { + dest->matrix[i][3] = 0; + for (j = 0; j < 3; j++) { + dest->matrix[i][3] -= dest->matrix[i][j] * src->matrix[j][3]; } } } // generate the world matrix for a given set of angles and origin - called from lots of places -void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) -{ +void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) { Create_Matrix(angles, &worldMatrix); worldMatrix.matrix[0][3] = origin[0]; worldMatrix.matrix[1][3] = origin[1]; @@ -1647,19 +1406,17 @@ void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) } // go away and determine what the pointer for a specific surface definition within the model definition is -void *G2_FindSurface(void *mod_t, int index, int lod) -{ +void *G2_FindSurface(void *mod_t, int index, int lod) { // damn include file dependancies - model_t *mod = (model_t *)mod_t; + model_t *mod = (model_t *)mod_t; mdxmHeader_t *mdxm = mod->data.glm->header; // point at first lod list - byte *current = (byte*)((size_t)mdxm + (size_t)mdxm->ofsLODs); + byte *current = (byte *)((size_t)mdxm + (size_t)mdxm->ofsLODs); int i; - //walk the lods - for (i=0; iofsEnd; } @@ -1674,16 +1431,14 @@ void *G2_FindSurface(void *mod_t, int index, int lod) return (void *)current; } -#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) +#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) #define BOLT_SAVE_BLOCK_SIZE (sizeof(boltInfo_t) - sizeof(mdxaBone_t)) #define BONE_SAVE_BLOCK_SIZE sizeof(boneInfo_t) -qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ +qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { // is there anything to save? - if (!ghoul2.size()) - { + if (!ghoul2.size()) { *buffer = (char *)Z_Malloc(4, TAG_GHOUL2, qtrue); int *tempBuffer = (int *)*buffer; *tempBuffer = 0; @@ -1698,69 +1453,64 @@ qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) int ghoul2BlockSize = (size_t)&ghoul2[0].mTransformedVertsArray - (size_t)&ghoul2[0].mModelindex; // add in count for number of ghoul2 models - *size += 4; + *size += 4; // start out working out the total size of the buffer we need to allocate int i; // Linux GCC is forcing new scoping rules - for (i=0; i i) && - (nextGhoul2[i].mModelindex != -1) && - (nextGhoul2[i].mBlist.size() > x) && - (nextGhoul2[i].mBlist[x].boneNumber != -1)) - { - boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; + if ((nextGhoul2.size() > i) && (nextGhoul2[i].mModelindex != -1) && (nextGhoul2[i].mBlist.size() > x) && + (nextGhoul2[i].mBlist[x].boneNumber != -1)) { + boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; // does this bone override actually have anything in it, and if it does, is it a bone angles override? - if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) - { - float *nowMatrix = (float*) &bone.matrix; - float *nextMatrix = (float*) &nextBone.matrix; - float *newMatrix = (float*) &bone.newMatrix; + if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) { + float *nowMatrix = (float *)&bone.matrix; + float *nextMatrix = (float *)&nextBone.matrix; + float *newMatrix = (float *)&bone.newMatrix; // now interpolate the matrix - for (int z=0; z < 12; z++) - { - newMatrix[z] = nowMatrix[z] + interpolation * ( nextMatrix[z] - nowMatrix[z] ); + for (int z = 0; z < 12; z++) { + newMatrix[z] = nowMatrix[z] + interpolation * (nextMatrix[z] - nowMatrix[z]); } } - } - else - { + } else { memcpy(&ghoul2[i].mBlist[x].newMatrix, &ghoul2[i].mBlist[x].matrix, sizeof(mdxaBone_t)); } } diff --git a/codemp/rd-rend2/G2_surfaces.cpp b/codemp/rd-rend2/G2_surfaces.cpp index 9fe81bf606..3965b8fc09 100644 --- a/codemp/rd-rend2/G2_surfaces.cpp +++ b/codemp/rd-rend2/G2_surfaces.cpp @@ -3,46 +3,33 @@ #include "ghoul2/g2_local.h" #include "tr_local.h" #ifdef _MSC_VER -#pragma warning(disable : 4512) //assignment op could not be genereated +#pragma warning(disable : 4512) // assignment op could not be genereated #endif -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - boneInfo_v &initboneList): - - surfaceNum(initsurfaceNum), - boneUsedList(initboneUsedList), - rootSList(initrootSList), - currentModel(initcurrentModel), - boneList(initboneList) { } +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; + + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : + + surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; extern void G2_ConstructUsedBoneList(CConstructBoneList &CBL); - //===================================================================================================================== // Surface List handling routines - so entities can determine what surfaces attached to a model are operational or not. // find a particular surface in the surface override list -surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) -{ +surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) { // look through entire list - for(size_t i=0; idata.glm->header; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surf->name)) - { + for (int i = 0; i < mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surf->name)) { *flags = surf->flags; return i; } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } return -1; } - /************************************************************************************************ * G2_FindSurface * find a surface in a ghoul2 surface override list based on it's name @@ -85,41 +68,33 @@ int G2_IsSurfaceLegal(void *mod, const char *surfaceName, int *flags) * pointer to surface if successful, false otherwise * ************************************************************************************************/ -mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, - int *surfIndex/*NULL*/) -{ - int i = 0; +mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, int *surfIndex /*NULL*/) { + int i = 0; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->data.glm->header + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo; + mdxmSurfHierarchy_t *surfInfo; // did we find a ghoul 2 model or not? - if (!mod->data.glm || !mod->data.glm->header) - { + if (!mod->data.glm || !mod->data.glm->header) { assert(0); - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } - - // first find if we already have this surface in the list - for (i = slist.size() - 1; i >= 0; i--) - { - if ((slist[i].surface != 10000) && (slist[i].surface != -1)) - { - mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); + + // first find if we already have this surface in the list + for (i = slist.size() - 1; i >= 0; i--) { + if ((slist[i].surface != 10000) && (slist[i].surface != -1)) { + mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); // back track and get the surfinfo struct for this surface surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); - // are these the droids we're looking for? - if (!Q_stricmp (surfInfo->name, surfaceName)) - { + // are these the droids we're looking for? + if (!Q_stricmp(surfInfo->name, surfaceName)) { // yup - if (surfIndex) - { + if (surfIndex) { *surfIndex = i; } return surf; @@ -127,33 +102,29 @@ mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const } } // didn't find it - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } // set a named surface offFlags - if it doesn't find a surface with this name in the list then it will add one. -qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) -{ - int surfIndex = -1; - surfaceInfo_t temp_slist_entry; - mdxmSurface_t *surf; +qboolean G2_SetSurfaceOnOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) { + int surfIndex = -1; + surfaceInfo_t temp_slist_entry; + mdxmSurface_t *surf; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; // did we find a ghoul 2 model or not? - if (!mod->data.glm || !mod->data.glm->header) - { + if (!mod->data.glm || !mod->data.glm->header) { assert(0); return qfalse; } - - // first find if we already have this surface in the list + + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value // slist[surfIndex].offFlags = offFlags; @@ -162,24 +133,20 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c slist[surfIndex].offFlags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); slist[surfIndex].offFlags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); return qtrue; - } - else - { + } else { // ok, not in the list already - in that case, lets verify this surface exists in the model mesh - int flags; - int surfaceNum = G2_IsSurfaceLegal((void*)mod, surfaceName, &flags); - if (surfaceNum != -1) - { + int flags; + int surfaceNum = G2_IsSurfaceLegal((void *)mod, surfaceName, &flags); + if (surfaceNum != -1) { int newflags = flags; // the only bit we really care about in the incoming flags is the off bit newflags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); newflags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); - if (newflags != flags) - { // insert here then because it changed, no need to add an override otherwise + if (newflags != flags) { // insert here then because it changed, no need to add an override otherwise temp_slist_entry.offFlags = newflags; temp_slist_entry.surface = surfaceNum; - + slist.push_back(temp_slist_entry); } return qtrue; @@ -188,26 +155,22 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin) { int j; - const skin_t *skin = R_GetSkinByHandle( renderSkin ); + const skin_t *skin = R_GetSkinByHandle(renderSkin); - ghlInfo->mSlist.clear(); //remove any overrides we had before. + ghlInfo->mSlist.clear(); // remove any overrides we had before. ghlInfo->mMeshFrameNum = 0; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - //Raz: why is this using the shader name and not the surface name? - if ( !strcmp( ((shader_t *)skin->surfaces[j]->shader)->name, "*off") ) { + // Raz: why is this using the shader name and not the surface name? + if (!strcmp(((shader_t *)skin->surfaces[j]->shader)->name, "*off")) { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, G2SURFACEFLAG_OFF); - } - else - { - int flags; + } else { + int flags; int surfaceNum = G2_IsSurfaceLegal((void *)ghlInfo->currentModel, skin->surfaces[j]->name, &flags); - if ( (surfaceNum != -1) && (!(flags&G2SURFACEFLAG_OFF)) ) //only turn on if it's not an "_off" surface + if ((surfaceNum != -1) && (!(flags & G2SURFACEFLAG_OFF))) // only turn on if it's not an "_off" surface { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, 0); } @@ -216,106 +179,87 @@ void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) } // return a named surfaces off flags - should tell you if this surface is on or off. -int G2_IsSurfaceOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int surfIndex = -1; - mdxmSurface_t *surf = 0; +int G2_IsSurfaceOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int surfIndex = -1; + mdxmSurface_t *surf = 0; mdxmHeader_t *mdxm = mod->data.glm->header; // did we find a ghoul 2 model or not? - if (!mdxm) - { + if (!mdxm) { return 0; } - - // first find if we already have this surface in the list + + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value return slist[surfIndex].offFlags; } // ok, we didn't find it in the surface list. Lets look at the original surface then. - mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surface->name)) - { + for (int i = 0; i < mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surface->name)) { return surface->flags; } // find the next surface - surface = (mdxmSurfHierarchy_t *)( (byte *)surface + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surface->numChildren ] )); + surface = (mdxmSurfHierarchy_t *)((byte *)surface + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surface->numChildren])); } assert(0); return 0; } -void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) -{ - int i; - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); +void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) { + int i; + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, indicate as such in the active surface list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { + if (!(offFlags & G2SURFACEFLAG_OFF)) { activeSurfaces[surfaceNum] = 1; - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { surfaceNum = surfInfo->childIndexes[i]; G2_FindRecursiveSurface(currentModel, surfaceNum, rootList, activeSurfaces); } - } -void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) -{ +void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; idata.glm->header; mdxaHeader_t *mdxa = mod_a->data.gla; // did we find a ghoul 2 model or not? - if (!mdxm) - { + if (!mdxm) { return qfalse; } // first find if we already have this surface in the list surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) - { + if (surf != -1) { // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) - { + if (ghoul2[modelIndex].mSurfaceRoot == surf) { return qtrue; } @@ -367,11 +307,7 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, activeBones, ghoul2[modelIndex].mSlist, mod_m, ghoul2[modelIndex].mBlist); G2_ConstructUsedBoneList(CBL); @@ -385,24 +321,20 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model - if (((int)ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) - { + if (((int)ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) { CGhoul2Info_v *g2i = &ghoul2; G2API_RemoveGhoul2Model((CGhoul2Info_v **)&g2i, i); } } } - //No support for this, for now. + // No support for this, for now. // remember to free what we used Z_Free(activeSurfaces); @@ -410,97 +342,95 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch return (qtrue); } -/* -//g2r if (entstate->ghoul2) - { - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int surf; - int flags; - int *activeSurfaces, *activeBones; - - // did we find a ghoul 2 model or not? - if (!mod_m->mdxm) - { - return qfalse; - } - - // first find if we already have this surface in the list - surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) + /* + //g2r if (entstate->ghoul2) { - // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int surf; + int flags; + int *activeSurfaces, *activeBones; + + // did we find a ghoul 2 model or not? + if (!mod_m->mdxm) { - return qtrue; + return qfalse; } - // set the root surface - ghoul2[modelIndex].mSurfaceRoot = surf; + // first find if we already have this surface in the list + surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); + if (surf != -1) + { + // first see if this ghoul2 model already has this as a root surface + if (ghoul2[modelIndex].mSurfaceRoot == surf) + { + return qtrue; + } - // ok, now the tricky bits. - // firstly, generate a list of active / on surfaces below the root point + // set the root surface + ghoul2[modelIndex].mSurfaceRoot = surf; - // gimme some space to put this list into - activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); - memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); - activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); - memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); + // ok, now the tricky bits. + // firstly, generate a list of active / on surfaces below the root point - G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); + // gimme some space to put this list into + activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); + memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); + activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); + memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); - // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); - G2_ConstructUsedBoneList(CBL); + // now generate the used bone list + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, + activeBones, + ghoul2[modelIndex].mSlist, + mod_m, + ghoul2[modelIndex].mBlist); - // now remove all procedural or override surfaces that refer to surfaces that arent on this list - G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); + G2_ConstructUsedBoneList(CBL); - // now remove all bones that are pointing at bones that aren't active - G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); + // now remove all procedural or override surfaces that refer to surfaces that arent on this list + G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); - // then remove all bolts that point at surfaces or bones that *arent* active. - G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); + // now remove all bones that are pointing at bones that aren't active + G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); - // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; - // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model - if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + // are we even bolted to anything? + if (ghoul2[i].mModelBoltLink != -1) { - G2API_RemoveGhoul2Model(entstate, i); + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model + if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && + (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + { + G2API_RemoveGhoul2Model(entstate, i); + } } } - } - // remember to free what we used - Z_Free(activeSurfaces); - Z_Free(activeBones); + // remember to free what we used + Z_Free(activeSurfaces); + Z_Free(activeBones); - return (qtrue); + return (qtrue); + } } - } - assert(0);*/ + assert(0);*/ return qfalse; } - extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); -int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ +int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { surfaceInfo_t temp_slist_entry; @@ -508,13 +438,11 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float lod = G2_DecideTraceLod(*(CGhoul2Info *)(ghoul2), lod); // first up, see if we have a free one already set up - look only from the end of the constant surfaces onwards - for (size_t i=0; imSlist.size(); i++) - { + for (size_t i = 0; i < ghoul2->mSlist.size(); i++) { // is the surface count -1? That would indicate it's free - if (ghoul2->mSlist[i].surface == -1) - { + if (ghoul2->mSlist[i].surface == -1) { ghoul2->mSlist[i].offFlags = G2SURFACEFLAG_GENERATED; - ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces + ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces ghoul2->mSlist[i].genBarycentricI = BarycentricI; ghoul2->mSlist[i].genBarycentricJ = BarycentricJ; ghoul2->mSlist[i].genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); @@ -534,34 +462,28 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float ghoul2->mSlist.push_back(temp_slist_entry); - return (ghoul2->mSlist.size() -1 ); + return (ghoul2->mSlist.size() - 1); } -qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) -{ - // did we find it? - if (index != -1) - { - // set us to be the 'not active' state +qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) { + // did we find it? + if (index != -1) { + // set us to be the 'not active' state slist[index].surface = -1; unsigned int newSize = slist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=slist.size()-1; i>-1; i--) - { - if (slist[i].surface == -1) - { + for (int i = slist.size() - 1; i > -1; i--) { + if (slist[i].surface == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != slist.size()) - { + if (newSize != slist.size()) { // yes, so lets do it slist.resize(newSize); } @@ -575,38 +497,32 @@ qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) return qfalse; } - -int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->data.glm->header + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = 0; +int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = 0; // walk each surface and see if this index is listed in it's children surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, index, 0); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->parentIndex; - } -int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int flags; - +int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int flags; + return G2_IsSurfaceLegal(mod, surfaceName, &flags); } -int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) -{ - int flags = 0;//, surfFlags = 0; - int surfIndex = 0; +int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) { + int flags = 0; //, surfFlags = 0; + int surfIndex = 0; assert(ghlInfo->currentModel); assert(ghlInfo->currentModel->data.glm && ghlInfo->currentModel->data.glm->header); - if (!ghlInfo->currentModel->data.glm || !ghlInfo->currentModel->data.glm->header) - { + if (!ghlInfo->currentModel->data.glm || !ghlInfo->currentModel->data.glm->header) { return -1; } @@ -614,55 +530,47 @@ int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceI // find the original surface in the surface list int surfNum = G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, surfaceName, &flags); - if ( surfNum != -1 ) - {//must be legal - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->data.glm->header + sizeof(mdxmHeader_t)); + if (surfNum != -1) { // must be legal + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->data.glm->header + sizeof(mdxmHeader_t)); const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); surfNum = surfInfo->parentIndex; // walk the surface hierarchy up until we hit the root - while (surfNum != -1) - { - const mdxmSurface_t *parentSurf; - int parentFlags; - const mdxmSurfHierarchy_t *parentSurfInfo; + while (surfNum != -1) { + const mdxmSurface_t *parentSurf; + int parentFlags; + const mdxmSurfHierarchy_t *parentSurfInfo; parentSurfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); // find the original surface in the surface list - //G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags + // G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, parentSurfInfo->name, &parentFlags); - // now see if we already have overriden this surface in the slist + // now see if we already have overriden this surface in the slist parentSurf = G2_FindSurface(ghlInfo, slist, parentSurfInfo->name, &surfIndex); - if (parentSurf) - { + if (parentSurf) { // set descendants value parentFlags = slist[surfIndex].offFlags; } // now we have the parent flags, lets see if any have the 'no descendants' flag set - if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) { flags |= G2SURFACEFLAG_OFF; - break; + break; } // set up scan of next parent surfNum = parentSurfInfo->parentIndex; } - } - else - { + } else { return -1; } - if ( flags == 0 ) - {//it's not being overridden by a parent - // now see if we already have overriden this surface in the slist + if (flags == 0) { // it's not being overridden by a parent + // now see if we already have overriden this surface in the slist const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value flags = slist[surfIndex].offFlags; } - // ok, at this point in flags we have what this surface is set to, and the index of the surface itself + // ok, at this point in flags we have what this surface is set to, and the index of the surface itself } return flags; } diff --git a/codemp/rd-rend2/MikkTSpace/mikktspace.c b/codemp/rd-rend2/MikkTSpace/mikktspace.c index 0342ae0146..69157297d0 100644 --- a/codemp/rd-rend2/MikkTSpace/mikktspace.c +++ b/codemp/rd-rend2/MikkTSpace/mikktspace.c @@ -30,27 +30,23 @@ #include "mikktspace.h" -#define TFALSE 0 -#define TTRUE 1 +#define TFALSE 0 +#define TTRUE 1 #ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 +#define M_PI 3.1415926535897932384626433832795 #endif -#define INTERNAL_RND_SORT_SEED 39871946 +#define INTERNAL_RND_SORT_SEED 39871946 // internal structure typedef struct { float x, y, z; } SVec3; -static tbool veq( const SVec3 v1, const SVec3 v2 ) -{ - return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); -} +static tbool veq(const SVec3 v1, const SVec3 v2) { return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); } -static SVec3 vadd( const SVec3 v1, const SVec3 v2 ) -{ +static SVec3 vadd(const SVec3 v1, const SVec3 v2) { SVec3 vRes; vRes.x = v1.x + v2.x; @@ -60,9 +56,7 @@ static SVec3 vadd( const SVec3 v1, const SVec3 v2 ) return vRes; } - -static SVec3 vsub( const SVec3 v1, const SVec3 v2 ) -{ +static SVec3 vsub(const SVec3 v1, const SVec3 v2) { SVec3 vRes; vRes.x = v1.x - v2.x; @@ -72,8 +66,7 @@ static SVec3 vsub( const SVec3 v1, const SVec3 v2 ) return vRes; } -static SVec3 vscale(const float fS, const SVec3 v) -{ +static SVec3 vscale(const float fS, const SVec3 v) { SVec3 vRes; vRes.x = fS * v.x; @@ -83,68 +76,49 @@ static SVec3 vscale(const float fS, const SVec3 v) return vRes; } -static float LengthSquared( const SVec3 v ) -{ - return v.x*v.x + v.y*v.y + v.z*v.z; -} - -static float Length( const SVec3 v ) -{ - return sqrtf(LengthSquared(v)); -} +static float LengthSquared(const SVec3 v) { return v.x * v.x + v.y * v.y + v.z * v.z; } -static SVec3 Normalize( const SVec3 v ) -{ - return vscale(1 / Length(v), v); -} +static float Length(const SVec3 v) { return sqrtf(LengthSquared(v)); } -static float vdot( const SVec3 v1, const SVec3 v2) -{ - return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; -} +static SVec3 Normalize(const SVec3 v) { return vscale(1 / Length(v), v); } +static float vdot(const SVec3 v1, const SVec3 v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } -static tbool NotZero(const float fX) -{ +static tbool NotZero(const float fX) { // could possibly use FLT_EPSILON instead return fabsf(fX) > FLT_MIN; } -static tbool VNotZero(const SVec3 v) -{ +static tbool VNotZero(const SVec3 v) { // might change this to an epsilon based test return NotZero(v.x) || NotZero(v.y) || NotZero(v.z); } - - typedef struct { int iNrFaces; - int * pTriMembers; + int *pTriMembers; } SSubGroup; typedef struct { int iNrFaces; - int * pFaceIndices; + int *pFaceIndices; int iVertexRepresentitive; tbool bOrientPreservering; } SGroup; -// -#define MARK_DEGENERATE 1 -#define QUAD_ONE_DEGEN_TRI 2 -#define GROUP_WITH_ANY 4 -#define ORIENT_PRESERVING 8 - - +// +#define MARK_DEGENERATE 1 +#define QUAD_ONE_DEGEN_TRI 2 +#define GROUP_WITH_ANY 4 +#define ORIENT_PRESERVING 8 typedef struct { int FaceNeighbors[3]; - SGroup * AssignedGroup[3]; - + SGroup *AssignedGroup[3]; + // normalized first order face derivatives SVec3 vOs, vOt; - float fMagS, fMagT; // original magnitudes + float fMagS, fMagT; // original magnitudes // determines if the current and the next triangle are a quad. int iOrgFaceNumber; @@ -157,113 +131,100 @@ typedef struct { float fMagS; SVec3 vOt; float fMagT; - int iCounter; // this is to average back into quads. + int iCounter; // this is to average back into quads. tbool bOrient; } STSpace; -static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); -static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); -static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn); +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn); +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn); static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn); -static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], - const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, - const SMikkTSpaceContext * pContext); - -static int MakeIndex(const int iFace, const int iVert) -{ - assert(iVert>=0 && iVert<4 && iFace>=0); - return (iFace<<2) | (iVert&0x3); +static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], const int iNrActiveGroups, const int piTriListIn[], + const float fThresCos, const SMikkTSpaceContext *pContext); + +static int MakeIndex(const int iFace, const int iVert) { + assert(iVert >= 0 && iVert < 4 && iFace >= 0); + return (iFace << 2) | (iVert & 0x3); } -static void IndexToData(int * piFace, int * piVert, const int iIndexIn) -{ - piVert[0] = iIndexIn&0x3; - piFace[0] = iIndexIn>>2; +static void IndexToData(int *piFace, int *piVert, const int iIndexIn) { + piVert[0] = iIndexIn & 0x3; + piFace[0] = iIndexIn >> 2; } -static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1) -{ +static STSpace AvgTSpace(const STSpace *pTS0, const STSpace *pTS1) { STSpace ts_res; // this if is important. Due to floating point precision // averaging when ts0==ts1 will cause a slight difference // which results in tangent space splits later on - if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT && - veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt)) - { + if (pTS0->fMagS == pTS1->fMagS && pTS0->fMagT == pTS1->fMagT && veq(pTS0->vOs, pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt)) { ts_res.fMagS = pTS0->fMagS; ts_res.fMagT = pTS0->fMagT; ts_res.vOs = pTS0->vOs; ts_res.vOt = pTS0->vOt; - } - else - { - ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS); - ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT); - ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs); - ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt); - if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs); - if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt); + } else { + ts_res.fMagS = 0.5f * (pTS0->fMagS + pTS1->fMagS); + ts_res.fMagT = 0.5f * (pTS0->fMagT + pTS1->fMagT); + ts_res.vOs = vadd(pTS0->vOs, pTS1->vOs); + ts_res.vOt = vadd(pTS0->vOt, pTS1->vOt); + if (VNotZero(ts_res.vOs)) + ts_res.vOs = Normalize(ts_res.vOs); + if (VNotZero(ts_res.vOt)) + ts_res.vOt = Normalize(ts_res.vOt); } return ts_res; } - - -static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index); -static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index); -static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index); - +static SVec3 GetPosition(const SMikkTSpaceContext *pContext, const int index); +static SVec3 GetNormal(const SMikkTSpaceContext *pContext, const int index); +static SVec3 GetTexCoord(const SMikkTSpaceContext *pContext, const int index); // degen triangles static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris); -static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris); - +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn, + const int iTotTris); -tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext) -{ - return genTangSpace(pContext, 180.0f); -} +tbool genTangSpaceDefault(const SMikkTSpaceContext *pContext) { return genTangSpace(pContext, 180.0f); } -tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold) -{ +tbool genTangSpace(const SMikkTSpaceContext *pContext, const float fAngularThreshold) { // count nr_triangles - int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL; - STriInfo * pTriInfos = NULL; - SGroup * pGroups = NULL; - STSpace * psTspace = NULL; - int iNrTrianglesIn = 0, f=0, t=0, i=0; + int *piTriListIn = NULL, *piGroupTrianglesBuffer = NULL; + STriInfo *pTriInfos = NULL; + SGroup *pGroups = NULL; + STSpace *psTspace = NULL; + int iNrTrianglesIn = 0, f = 0, t = 0, i = 0; int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0; int iNrActiveGroups = 0, index = 0; const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext); tbool bRes = TFALSE; - const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f); + const float fThresCos = (float)cos((fAngularThreshold * (float)M_PI) / 180.0f); // verify all call-backs have been set - if ( pContext->m_pInterface->m_getNumFaces==NULL || - pContext->m_pInterface->m_getNumVerticesOfFace==NULL || - pContext->m_pInterface->m_getPosition==NULL || - pContext->m_pInterface->m_getNormal==NULL || - pContext->m_pInterface->m_getTexCoord==NULL ) + if (pContext->m_pInterface->m_getNumFaces == NULL || pContext->m_pInterface->m_getNumVerticesOfFace == NULL || + pContext->m_pInterface->m_getPosition == NULL || pContext->m_pInterface->m_getNormal == NULL || pContext->m_pInterface->m_getTexCoord == NULL) return TFALSE; // count triangles on supported faces - for (f=0; fm_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts==3) ++iNrTrianglesIn; - else if (verts==4) iNrTrianglesIn += 2; + if (verts == 3) + ++iNrTrianglesIn; + else if (verts == 4) + iNrTrianglesIn += 2; } - if (iNrTrianglesIn<=0) return TFALSE; + if (iNrTrianglesIn <= 0) + return TFALSE; // allocate memory for an index list - piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn); - pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn); - if (piTriListIn==NULL || pTriInfos==NULL) - { - if (piTriListIn!=NULL) free(piTriListIn); - if (pTriInfos!=NULL) free(pTriInfos); + piTriListIn = (int *)malloc(sizeof(int) * 3 * iNrTrianglesIn); + pTriInfos = (STriInfo *)malloc(sizeof(STriInfo) * iNrTrianglesIn); + if (piTriListIn == NULL || pTriInfos == NULL) { + if (piTriListIn != NULL) + free(piTriListIn); + if (pTriInfos != NULL) + free(pTriInfos); return TFALSE; } @@ -271,22 +232,21 @@ tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThre iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn); // make a welded index list of identical positions and attributes (pos, norm, texc) - //printf("gen welded index list begin\n"); + // printf("gen welded index list begin\n"); GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn); - //printf("gen welded index list end\n"); + // printf("gen welded index list end\n"); // Mark all degenerate triangles iTotTris = iNrTrianglesIn; iDegenTriangles = 0; - for (t=0; tm_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts!=3 && verts!=4) continue; - + if (verts != 3 && verts != 4) + continue; // I've decided to let degenerate triangles and group-with-anythings // vary between left/right hand coordinate systems at the vertices. @@ -399,15 +362,14 @@ tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThre }*/ // set data - for (i=0; ivOs.x, pTSpace->vOs.y, pTSpace->vOs.z}; float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z}; - if (pContext->m_pInterface->m_setTSpace!=NULL) + if (pContext->m_pInterface->m_setTSpace != NULL) pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i); - if (pContext->m_pInterface->m_setTSpaceBasic!=NULL) - pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i); + if (pContext->m_pInterface->m_setTSpaceBasic != NULL) + pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient == TTRUE ? 1.0f : (-1.0f), f, i); ++index; } @@ -415,7 +377,6 @@ tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThre free(psTspace); - return TTRUE; } @@ -429,176 +390,183 @@ typedef struct { static const int g_iCells = 2048; #ifdef _MSC_VER -# define NOINLINE __declspec(noinline) +#define NOINLINE __declspec(noinline) #else -# define NOINLINE __attribute__ ((noinline)) +#define NOINLINE __attribute__((noinline)) #endif // it is IMPORTANT that this function is called to evaluate the hash since // inlining could potentially reorder instructions and generate different // results for the same effective input value fVal. -static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal) -{ - const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin)); +static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal) { + const float fIndex = g_iCells * ((fVal - fMin) / (fMax - fMin)); const int iIndex = (int)fIndex; return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1); } -static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in); -static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries); -static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext *pContext, const int iL_in, const int iR_in); +static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext *pContext, const int pTable[], const int iEntries); +static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn); -static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) -{ +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn) { // Generate bounding box - int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL; - STmpVert * pTmpVert = NULL; - int i=0, iChannel=0, k=0, e=0; - int iMaxCount=0; + int *piHashTable = NULL, *piHashCount = NULL, *piHashOffsets = NULL, *piHashCount2 = NULL; + STmpVert *pTmpVert = NULL; + int i = 0, iChannel = 0, k = 0, e = 0; + int iMaxCount = 0; SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim; float fMin, fMax; - for (i=1; i<(iNrTrianglesIn*3); i++) - { + for (i = 1; i < (iNrTrianglesIn * 3); i++) { const int index = piTriList_in_and_out[i]; const SVec3 vP = GetPosition(pContext, index); - if (vMin.x > vP.x) vMin.x = vP.x; - else if (vMax.x < vP.x) vMax.x = vP.x; - if (vMin.y > vP.y) vMin.y = vP.y; - else if (vMax.y < vP.y) vMax.y = vP.y; - if (vMin.z > vP.z) vMin.z = vP.z; - else if (vMax.z < vP.z) vMax.z = vP.z; + if (vMin.x > vP.x) + vMin.x = vP.x; + else if (vMax.x < vP.x) + vMax.x = vP.x; + if (vMin.y > vP.y) + vMin.y = vP.y; + else if (vMax.y < vP.y) + vMax.y = vP.y; + if (vMin.z > vP.z) + vMin.z = vP.z; + else if (vMax.z < vP.z) + vMax.z = vP.z; } - vDim = vsub(vMax,vMin); + vDim = vsub(vMax, vMin); iChannel = 0; - fMin = vMin.x; fMax=vMax.x; - if (vDim.y>vDim.x && vDim.y>vDim.z) - { - iChannel=1; + fMin = vMin.x; + fMax = vMax.x; + if (vDim.y > vDim.x && vDim.y > vDim.z) { + iChannel = 1; fMin = vMin.y; fMax = vMax.y; - } - else if (vDim.z>vDim.x) - { - iChannel=2; + } else if (vDim.z > vDim.x) { + iChannel = 2; fMin = vMin.z; fMax = vMax.z; } // make allocations - piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3); - piHashCount = (int *) malloc(sizeof(int)*g_iCells); - piHashOffsets = (int *) malloc(sizeof(int)*g_iCells); - piHashCount2 = (int *) malloc(sizeof(int)*g_iCells); - - if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL) - { - if (piHashTable!=NULL) free(piHashTable); - if (piHashCount!=NULL) free(piHashCount); - if (piHashOffsets!=NULL) free(piHashOffsets); - if (piHashCount2!=NULL) free(piHashCount2); + piHashTable = (int *)malloc(sizeof(int) * iNrTrianglesIn * 3); + piHashCount = (int *)malloc(sizeof(int) * g_iCells); + piHashOffsets = (int *)malloc(sizeof(int) * g_iCells); + piHashCount2 = (int *)malloc(sizeof(int) * g_iCells); + + if (piHashTable == NULL || piHashCount == NULL || piHashOffsets == NULL || piHashCount2 == NULL) { + if (piHashTable != NULL) + free(piHashTable); + if (piHashCount != NULL) + free(piHashCount); + if (piHashOffsets != NULL) + free(piHashOffsets); + if (piHashCount2 != NULL) + free(piHashCount2); GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn); return; } - memset(piHashCount, 0, sizeof(int)*g_iCells); - memset(piHashCount2, 0, sizeof(int)*g_iCells); + memset(piHashCount, 0, sizeof(int) * g_iCells); + memset(piHashCount2, 0, sizeof(int) * g_iCells); // count amount of elements in each cell unit - for (i=0; i<(iNrTrianglesIn*3); i++) - { + for (i = 0; i < (iNrTrianglesIn * 3); i++) { const int index = piTriList_in_and_out[i]; const SVec3 vP = GetPosition(pContext, index); - const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z); + const float fVal = iChannel == 0 ? vP.x : (iChannel == 1 ? vP.y : vP.z); const int iCell = FindGridCell(fMin, fMax, fVal); ++piHashCount[iCell]; } // evaluate start index of each cell. - piHashOffsets[0]=0; - for (k=1; kpTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c]; - if (fvMax[c] pTmpVert[l].vert[c]) + fvMin[c] = pTmpVert[l].vert[c]; + if (fvMax[c] < pTmpVert[l].vert[c]) + fvMax[c] = pTmpVert[l].vert[c]; } } - dx = fvMax[0]-fvMin[0]; - dy = fvMax[1]-fvMin[1]; - dz = fvMax[2]-fvMin[2]; + dx = fvMax[0] - fvMin[0]; + dy = fvMax[1] - fvMin[1]; + dz = fvMax[2] - fvMin[2]; channel = 0; - if (dy>dx && dy>dz) channel=1; - else if (dz>dx) channel=2; + if (dy > dx && dy > dz) + channel = 1; + else if (dz > dx) + channel = 2; - fSep = 0.5f*(fvMax[channel]+fvMin[channel]); + fSep = 0.5f * (fvMax[channel] + fvMin[channel]); // stop if all vertices are NaNs if (!isfinite(fSep)) @@ -606,11 +574,9 @@ static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], cons // terminate recursion when the separation/average value // is no longer strictly between fMin and fMax values. - if (fSep>=fvMax[channel] || fSep<=fvMin[channel]) - { + if (fSep >= fvMax[channel] || fSep <= fvMin[channel]) { // complete the weld - for (l=iL_in; l<=iR_in; l++) - { + for (l = iL_in; l <= iR_in; l++) { int i = pTmpVert[l].index; const int index = piTriList_in_and_out[i]; const SVec3 vP = GetPosition(pContext, index); @@ -618,85 +584,79 @@ static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], cons const SVec3 vT = GetTexCoord(pContext, index); tbool bNotFound = TTRUE; - int l2=iL_in, i2rec=-1; - while (l20); // at least 2 entries + } else { + int iL = iL_in, iR = iR_in; + assert((iR_in - iL_in) > 0); // at least 2 entries // separate (by fSep) all points between iL_in and iR_in in pTmpVert[] - while (iL < iR) - { + while (iL < iR) { tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE; - while ((!bReadyLeftSwap) && iL=iL_in && iL<=iR_in); - bReadyLeftSwap = !(pTmpVert[iL].vert[channel]= iL_in && iL <= iR_in); + bReadyLeftSwap = !(pTmpVert[iL].vert[channel] < fSep); + if (!bReadyLeftSwap) + ++iL; } - while ((!bReadyRightSwap) && iL=iL_in && iR<=iR_in); - bReadyRightSwap = pTmpVert[iR].vert[channel]= iL_in && iR <= iR_in); + bReadyRightSwap = pTmpVert[iR].vert[channel] < fSep; + if (!bReadyRightSwap) + --iR; } - assert( (iLm_pInterface->m_getNumFaces(pContext); f++) - { + for (f = 0; f < pContext->m_pInterface->m_getNumFaces(pContext); f++) { const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts!=3 && verts!=4) continue; + if (verts != 3 && verts != 4) + continue; pTriInfos[iDstTriIndex].iOrgFaceNumber = f; pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs; - if (verts==3) - { - unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num; - pVerts[0]=0; pVerts[1]=1; pVerts[2]=2; - piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0); - piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1); - piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2); - ++iDstTriIndex; // next - } - else - { + if (verts == 3) { + unsigned char *pVerts = pTriInfos[iDstTriIndex].vert_num; + pVerts[0] = 0; + pVerts[1] = 1; + pVerts[2] = 2; + piTriList_out[iDstTriIndex * 3 + 0] = MakeIndex(f, 0); + piTriList_out[iDstTriIndex * 3 + 1] = MakeIndex(f, 1); + piTriList_out[iDstTriIndex * 3 + 2] = MakeIndex(f, 2); + ++iDstTriIndex; // next + } else { { - pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f; - pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs; + pTriInfos[iDstTriIndex + 1].iOrgFaceNumber = f; + pTriInfos[iDstTriIndex + 1].iTSpacesOffs = iTSpacesOffs; } { @@ -809,104 +764,114 @@ static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_ const SVec3 T1 = GetTexCoord(pContext, i1); const SVec3 T2 = GetTexCoord(pContext, i2); const SVec3 T3 = GetTexCoord(pContext, i3); - const float distSQ_02 = LengthSquared(vsub(T2,T0)); - const float distSQ_13 = LengthSquared(vsub(T3,T1)); + const float distSQ_02 = LengthSquared(vsub(T2, T0)); + const float distSQ_13 = LengthSquared(vsub(T3, T1)); tbool bQuadDiagIs_02; - if (distSQ_02m_pInterface->m_getPosition(pContext, pos, iF, iI); - res.x=pos[0]; res.y=pos[1]; res.z=pos[2]; + res.x = pos[0]; + res.y = pos[1]; + res.z = pos[2]; return res; } -static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index) -{ +static SVec3 GetNormal(const SMikkTSpaceContext *pContext, const int index) { int iF, iI; - SVec3 res; float norm[3]; + SVec3 res; + float norm[3]; IndexToData(&iF, &iI, index); pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI); - res.x=norm[0]; res.y=norm[1]; res.z=norm[2]; + res.x = norm[0]; + res.y = norm[1]; + res.z = norm[2]; return res; } -static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index) -{ +static SVec3 GetTexCoord(const SMikkTSpaceContext *pContext, const int index) { int iF, iI; - SVec3 res; float texc[2]; + SVec3 res; + float texc[2]; IndexToData(&iF, &iI, index); pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI); - res.x=texc[0]; res.y=texc[1]; res.z=1.0f; + res.x = texc[0]; + res.y = texc[1]; + res.z = 1.0f; return res; } @@ -914,47 +879,47 @@ static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index) ///////////////////////////////////////////////////////////////////////////////////////////////////// typedef union { - struct - { + struct { int i0, i1, f; }; int array[3]; } SEdge; -static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn); +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge *pEdges, const int piTriListIn[], const int iNrTrianglesIn); static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn); // returns the texture area times 2 -static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[]) -{ +static float CalcTexArea(const SMikkTSpaceContext *pContext, const int indices[]) { const SVec3 t1 = GetTexCoord(pContext, indices[0]); const SVec3 t2 = GetTexCoord(pContext, indices[1]); const SVec3 t3 = GetTexCoord(pContext, indices[2]); - const float t21x = t2.x-t1.x; - const float t21y = t2.y-t1.y; - const float t31x = t3.x-t1.x; - const float t31y = t3.y-t1.y; + const float t21x = t2.x - t1.x; + const float t21y = t2.y - t1.y; + const float t31x = t3.x - t1.x; + const float t31y = t3.y - t1.y; - const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x; + const float fSignedAreaSTx2 = t21x * t31y - t21y * t31x; - return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2; + return fSignedAreaSTx2 < 0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2; } -static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) -{ - int f=0, i=0, t=0; +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn) { + int f = 0, i = 0, t = 0; // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function. // generate neighbor info list - for (f=0; f0 ? ORIENT_PRESERVING : 0); - - if ( NotZero(fSignedAreaSTx2) ) - { + const SVec3 v1 = GetPosition(pContext, piTriListIn[f * 3 + 0]); + const SVec3 v2 = GetPosition(pContext, piTriListIn[f * 3 + 1]); + const SVec3 v3 = GetPosition(pContext, piTriListIn[f * 3 + 2]); + const SVec3 t1 = GetTexCoord(pContext, piTriListIn[f * 3 + 0]); + const SVec3 t2 = GetTexCoord(pContext, piTriListIn[f * 3 + 1]); + const SVec3 t3 = GetTexCoord(pContext, piTriListIn[f * 3 + 2]); + + const float t21x = t2.x - t1.x; + const float t21y = t2.y - t1.y; + const float t31x = t3.x - t1.x; + const float t31y = t3.y - t1.y; + const SVec3 d1 = vsub(v2, v1); + const SVec3 d2 = vsub(v3, v1); + + const float fSignedAreaSTx2 = t21x * t31y - t21y * t31x; + // assert(fSignedAreaSTx2!=0); + SVec3 vOs = vsub(vscale(t31y, d1), vscale(t21y, d2)); // eq 18 + SVec3 vOt = vadd(vscale(-t31x, d1), vscale(t21x, d2)); // eq 19 + + pTriInfos[f].iFlag |= (fSignedAreaSTx2 > 0 ? ORIENT_PRESERVING : 0); + + if (NotZero(fSignedAreaSTx2)) { const float fAbsArea = fabsf(fSignedAreaSTx2); const float fLenOs = Length(vOs); const float fLenOt = Length(vOt); - const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f; - if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs); - if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt); + const float fS = (pTriInfos[f].iFlag & ORIENT_PRESERVING) == 0 ? (-1.0f) : 1.0f; + if (NotZero(fLenOs)) + pTriInfos[f].vOs = vscale(fS / fLenOs, vOs); + if (NotZero(fLenOt)) + pTriInfos[f].vOt = vscale(fS / fLenOt, vOt); // evaluate magnitudes prior to normalization of vOs and vOt pTriInfos[f].fMagS = fLenOs / fAbsArea; pTriInfos[f].fMagT = fLenOt / fAbsArea; // if this is a good triangle - if ( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT)) + if (NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT)) pTriInfos[f].iFlag &= (~GROUP_WITH_ANY); } } // force otherwise healthy quads to a fixed orientation - while (t<(iNrTrianglesIn-1)) - { + while (t < (iNrTrianglesIn - 1)) { const int iFO_a = pTriInfos[t].iOrgFaceNumber; - const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; - if (iFO_a==iFO_b) // this is a quad + const int iFO_b = pTriInfos[t + 1].iOrgFaceNumber; + if (iFO_a == iFO_b) // this is a quad { - const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - + const tbool bIsDeg_a = (pTriInfos[t].iFlag & MARK_DEGENERATE) != 0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t + 1].iFlag & MARK_DEGENERATE) != 0 ? TTRUE : TFALSE; + // bad triangles should already have been removed by // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false - if ((bIsDeg_a||bIsDeg_b)==TFALSE) - { - const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + if ((bIsDeg_a || bIsDeg_b) == TFALSE) { + const tbool bOrientA = (pTriInfos[t].iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; + const tbool bOrientB = (pTriInfos[t + 1].iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; // if this happens the quad has extremely bad mapping!! - if (bOrientA!=bOrientB) - { - //printf("found quad with bad mapping\n"); + if (bOrientA != bOrientB) { + // printf("found quad with bad mapping\n"); tbool bChooseOrientFirstTri = TFALSE; - if ((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE; - else if ( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) ) + if ((pTriInfos[t + 1].iFlag & GROUP_WITH_ANY) != 0) + bChooseOrientFirstTri = TTRUE; + else if (CalcTexArea(pContext, &piTriListIn[t * 3 + 0]) >= CalcTexArea(pContext, &piTriListIn[(t + 1) * 3 + 0])) bChooseOrientFirstTri = TTRUE; // force match { - const int t0 = bChooseOrientFirstTri ? t : (t+1); - const int t1 = bChooseOrientFirstTri ? (t+1) : t; - pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first - pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit + const int t0 = bChooseOrientFirstTri ? t : (t + 1); + const int t1 = bChooseOrientFirstTri ? (t + 1) : t; + pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first + pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag & ORIENT_PRESERVING); // copy bit } } } t += 2; - } - else + } else ++t; } - + // match up edge pairs { - SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3); - if (pEdges==NULL) + SEdge *pEdges = (SEdge *)malloc(sizeof(SEdge) * iNrTrianglesIn * 3); + if (pEdges == NULL) BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn); - else - { + else { BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn); - + free(pEdges); } } @@ -1063,58 +1024,50 @@ static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMi ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// -static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup); -static void AddTriToGroup(SGroup * pGroup, const int iTriIndex); +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup *pGroup); +static void AddTriToGroup(SGroup *pGroup, const int iTriIndex); -static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn) -{ - const int iNrMaxGroups = iNrTrianglesIn*3; +static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn) { + const int iNrMaxGroups = iNrTrianglesIn * 3; int iNrActiveGroups = 0; - int iOffset = 0, f=0, i=0; - (void)iNrMaxGroups; /* quiet warnings in non debug mode */ - for (f=0; fiVertexRepresentitive = vert_index; - pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0; + pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag & ORIENT_PRESERVING) != 0; pTriInfos[f].AssignedGroup[i]->iNrFaces = 0; pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset]; ++iNrActiveGroups; AddTriToGroup(pTriInfos[f].AssignedGroup[i], f); - bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + bOrPre = (pTriInfos[f].iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; neigh_indexL = pTriInfos[f].FaceNeighbors[i]; - neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2]; - if (neigh_indexL>=0) // neighbor + neigh_indexR = pTriInfos[f].FaceNeighbors[i > 0 ? (i - 1) : 2]; + if (neigh_indexL >= 0) // neighbor { - const tbool bAnswer = - AssignRecur(piTriListIn, pTriInfos, neigh_indexL, - pTriInfos[f].AssignedGroup[i] ); - - const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + const tbool bAnswer = AssignRecur(piTriListIn, pTriInfos, neigh_indexL, pTriInfos[f].AssignedGroup[i]); + + const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre != bOrPre2 ? TTRUE : TFALSE; assert(bAnswer || bDiff); - (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ } - if (neigh_indexR>=0) // neighbor + if (neigh_indexR >= 0) // neighbor { - const tbool bAnswer = - AssignRecur(piTriListIn, pTriInfos, neigh_indexR, - pTriInfos[f].AssignedGroup[i] ); + const tbool bAnswer = AssignRecur(piTriListIn, pTriInfos, neigh_indexR, pTriInfos[f].AssignedGroup[i]); - const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre != bOrPre2 ? TTRUE : TFALSE; assert(bAnswer || bDiff); - (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ } // update offset @@ -1130,45 +1083,44 @@ static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupT return iNrActiveGroups; } -static void AddTriToGroup(SGroup * pGroup, const int iTriIndex) -{ +static void AddTriToGroup(SGroup *pGroup, const int iTriIndex) { pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex; ++pGroup->iNrFaces; } -static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], - const int iMyTriIndex, SGroup * pGroup) -{ - STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex]; +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup *pGroup) { + STriInfo *pMyTriInfo = &psTriInfos[iMyTriIndex]; // track down vertex const int iVertRep = pGroup->iVertexRepresentitive; - const int * pVerts = &piTriListIn[3*iMyTriIndex+0]; - int i=-1; - if (pVerts[0]==iVertRep) i=0; - else if (pVerts[1]==iVertRep) i=1; - else if (pVerts[2]==iVertRep) i=2; - assert(i>=0 && i<3); + const int *pVerts = &piTriListIn[3 * iMyTriIndex + 0]; + int i = -1; + if (pVerts[0] == iVertRep) + i = 0; + else if (pVerts[1] == iVertRep) + i = 1; + else if (pVerts[2] == iVertRep) + i = 2; + assert(i >= 0 && i < 3); // early out - if (pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE; - else if (pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE; - if ((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0) - { + if (pMyTriInfo->AssignedGroup[i] == pGroup) + return TTRUE; + else if (pMyTriInfo->AssignedGroup[i] != NULL) + return TFALSE; + if ((pMyTriInfo->iFlag & GROUP_WITH_ANY) != 0) { // first to group with a group-with-anything triangle // determines it's orientation. // This is the only existing order dependency in the code!! - if ( pMyTriInfo->AssignedGroup[0] == NULL && - pMyTriInfo->AssignedGroup[1] == NULL && - pMyTriInfo->AssignedGroup[2] == NULL ) - { + if (pMyTriInfo->AssignedGroup[0] == NULL && pMyTriInfo->AssignedGroup[1] == NULL && pMyTriInfo->AssignedGroup[2] == NULL) { pMyTriInfo->iFlag &= (~ORIENT_PRESERVING); pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0); } } { - const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - if (bOrient != pGroup->bOrientPreservering) return TFALSE; + const tbool bOrient = (pMyTriInfo->iFlag & ORIENT_PRESERVING) != 0 ? TTRUE : TFALSE; + if (bOrient != pGroup->bOrientPreservering) + return TFALSE; } AddTriToGroup(pGroup, iMyTriIndex); @@ -1176,107 +1128,111 @@ static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], { const int neigh_indexL = pMyTriInfo->FaceNeighbors[i]; - const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2]; - if (neigh_indexL>=0) + const int neigh_indexR = pMyTriInfo->FaceNeighbors[i > 0 ? (i - 1) : 2]; + if (neigh_indexL >= 0) AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup); - if (neigh_indexR>=0) + if (neigh_indexR >= 0) AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup); } - - return TTRUE; } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// -static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2); -static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed); -static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive); - -static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], - const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, - const SMikkTSpaceContext * pContext) -{ - STSpace * pSubGroupTspace = NULL; - SSubGroup * pUniSubGroups = NULL; - int * pTmpMembers = NULL; - int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0; - for (g=0; giNrFaces; i++) // triangles + for (i = 0; i < pGroup->iNrFaces; i++) // triangles { - const int f = pGroup->pFaceIndices[i]; // triangle number - int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0; + const int f = pGroup->pFaceIndices[i]; // triangle number + int index = -1, iVertIndex = -1, iOF_1 = -1, iMembers = 0, j = 0, l = 0; SSubGroup tmp_group; tbool bFound; SVec3 n, vOs, vOt; - if (pTriInfos[f].AssignedGroup[0]==pGroup) index=0; - else if (pTriInfos[f].AssignedGroup[1]==pGroup) index=1; - else if (pTriInfos[f].AssignedGroup[2]==pGroup) index=2; - assert(index>=0 && index<3); + if (pTriInfos[f].AssignedGroup[0] == pGroup) + index = 0; + else if (pTriInfos[f].AssignedGroup[1] == pGroup) + index = 1; + else if (pTriInfos[f].AssignedGroup[2] == pGroup) + index = 2; + assert(index >= 0 && index < 3); - iVertIndex = piTriListIn[f*3+index]; - assert(iVertIndex==pGroup->iVertexRepresentitive); + iVertIndex = piTriListIn[f * 3 + index]; + assert(iVertIndex == pGroup->iVertexRepresentitive); // is normalized already n = GetNormal(pContext, iVertIndex); - + // project - vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); - vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); - if ( VNotZero(vOs) ) vOs = Normalize(vOs); - if ( VNotZero(vOt) ) vOt = Normalize(vOt); + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n, pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n, pTriInfos[f].vOt), n)); + if (VNotZero(vOs)) + vOs = Normalize(vOs); + if (VNotZero(vOt)) + vOt = Normalize(vOt); // original face number iOF_1 = pTriInfos[f].iOrgFaceNumber; - + iMembers = 0; - for (j=0; jiNrFaces; j++) - { - const int t = pGroup->pFaceIndices[j]; // triangle number + for (j = 0; j < pGroup->iNrFaces; j++) { + const int t = pGroup->pFaceIndices[j]; // triangle number const int iOF_2 = pTriInfos[t].iOrgFaceNumber; // project - SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n)); - SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n)); - if ( VNotZero(vOs2) ) vOs2 = Normalize(vOs2); - if ( VNotZero(vOt2) ) vOt2 = Normalize(vOt2); + SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n, pTriInfos[t].vOs), n)); + SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n, pTriInfos[t].vOt), n)); + if (VNotZero(vOs2)) + vOs2 = Normalize(vOs2); + if (VNotZero(vOt2)) + vOt2 = Normalize(vOt2); { - const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE; + const tbool bAny = ((pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY) != 0 ? TTRUE : TFALSE; // make sure triangles which belong to the same quad are joined. - const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE; + const tbool bSameOrgFace = iOF_1 == iOF_2 ? TTRUE : TFALSE; - const float fCosS = vdot(vOs,vOs2); - const float fCosT = vdot(vOt,vOt2); + const float fCosS = vdot(vOs, vOs2); + const float fCosT = vdot(vOt, vOt2); - assert(f!=t || bSameOrgFace); // sanity check - if (bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos)) + assert(f != t || bSameOrgFace); // sanity check + if (bAny || bSameOrgFace || (fCosS > fThresCos && fCosT > fThresCos)) pTmpMembers[iMembers++] = t; } } @@ -1284,35 +1240,32 @@ static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], con // sort pTmpMembers tmp_group.iNrFaces = iMembers; tmp_group.pTriMembers = pTmpMembers; - if (iMembers>1) - { - unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? - QuickSort(pTmpMembers, 0, iMembers-1, uSeed); + if (iMembers > 1) { + unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? + QuickSort(pTmpMembers, 0, iMembers - 1, uSeed); } // look for an existing match bFound = TFALSE; - l=0; - while (liVertexRepresentitive); ++iUniqueSubGroups; @@ -1331,27 +1284,24 @@ static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], con { const int iOffs = pTriInfos[f].iTSpacesOffs; const int iVert = pTriInfos[f].vert_num[index]; - STSpace * pTS_out = &psTspace[iOffs+iVert]; - assert(pTS_out->iCounter<2); - assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering); - if (pTS_out->iCounter==1) - { + STSpace *pTS_out = &psTspace[iOffs + iVert]; + assert(pTS_out->iCounter < 2); + assert(((pTriInfos[f].iFlag & ORIENT_PRESERVING) != 0) == pGroup->bOrientPreservering); + if (pTS_out->iCounter == 1) { *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]); - pTS_out->iCounter = 2; // update counter + pTS_out->iCounter = 2; // update counter pTS_out->bOrient = pGroup->bOrientPreservering; - } - else - { - assert(pTS_out->iCounter==0); + } else { + assert(pTS_out->iCounter == 0); *pTS_out = pSubGroupTspace[l]; - pTS_out->iCounter = 1; // update counter + pTS_out->iCounter = 1; // update counter pTS_out->bOrient = pGroup->bOrientPreservering; } } } // clean up and offset iUniqueTspaces - for (s=0; s=0 && i<3); + int i = -1, index = -1, i0 = -1, i1 = -1, i2 = -1; + if (piTriListIn[3 * f + 0] == iVertexRepresentitive) + i = 0; + else if (piTriListIn[3 * f + 1] == iVertexRepresentitive) + i = 1; + else if (piTriListIn[3 * f + 2] == iVertexRepresentitive) + i = 2; + assert(i >= 0 && i < 3); // project - index = piTriListIn[3*f+i]; + index = piTriListIn[3 * f + i]; n = GetNormal(pContext, index); - vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); - vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); - if ( VNotZero(vOs) ) vOs = Normalize(vOs); - if ( VNotZero(vOt) ) vOt = Normalize(vOt); + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n, pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n, pTriInfos[f].vOt), n)); + if (VNotZero(vOs)) + vOs = Normalize(vOs); + if (VNotZero(vOt)) + vOt = Normalize(vOt); - i2 = piTriListIn[3*f + (i<2?(i+1):0)]; - i1 = piTriListIn[3*f + i]; - i0 = piTriListIn[3*f + (i>0?(i-1):2)]; + i2 = piTriListIn[3 * f + (i < 2 ? (i + 1) : 0)]; + i1 = piTriListIn[3 * f + i]; + i0 = piTriListIn[3 * f + (i > 0 ? (i - 1) : 2)]; p0 = GetPosition(pContext, i0); p1 = GetPosition(pContext, i1); p2 = GetPosition(pContext, i2); - v1 = vsub(p0,p1); - v2 = vsub(p2,p1); + v1 = vsub(p0, p1); + v2 = vsub(p2, p1); // project - v1 = vsub(v1, vscale(vdot(n,v1),n)); if ( VNotZero(v1) ) v1 = Normalize(v1); - v2 = vsub(v2, vscale(vdot(n,v2),n)); if ( VNotZero(v2) ) v2 = Normalize(v2); + v1 = vsub(v1, vscale(vdot(n, v1), n)); + if (VNotZero(v1)) + v1 = Normalize(v1); + v2 = vsub(v2, vscale(vdot(n, v2), n)); + if (VNotZero(v2)) + v2 = Normalize(v2); // weight contribution by the angle // between the two edge vectors - fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos); - fAngle = (float) acos(fCos); + fCos = vdot(v1, v2); + fCos = fCos > 1 ? 1 : (fCos < (-1) ? (-1) : fCos); + fAngle = (float)acos(fCos); fMagS = pTriInfos[f].fMagS; fMagT = pTriInfos[f].fMagT; - res.vOs=vadd(res.vOs, vscale(fAngle,vOs)); - res.vOt=vadd(res.vOt,vscale(fAngle,vOt)); - res.fMagS+=(fAngle*fMagS); - res.fMagT+=(fAngle*fMagT); + res.vOs = vadd(res.vOs, vscale(fAngle, vOs)); + res.vOt = vadd(res.vOt, vscale(fAngle, vOt)); + res.fMagS += (fAngle * fMagS); + res.fMagT += (fAngle * fMagT); fAngleSum += fAngle; } } // normalize - if ( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs); - if ( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt); - if (fAngleSum>0) - { + if (VNotZero(res.vOs)) + res.vOs = Normalize(res.vOs); + if (VNotZero(res.vOt)) + res.vOt = Normalize(res.vOt); + if (fAngleSum > 0) { res.fMagS /= fAngleSum; res.fMagT /= fAngleSum; } @@ -1438,53 +1401,50 @@ static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriL return res; } -static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2) -{ - tbool bStillSame=TTRUE; - int i=0; - if (pg1->iNrFaces!=pg2->iNrFaces) return TFALSE; - while (iiNrFaces && bStillSame) - { - bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE; - if (bStillSame) ++i; +static tbool CompareSubGroups(const SSubGroup *pg1, const SSubGroup *pg2) { + tbool bStillSame = TTRUE; + int i = 0; + if (pg1->iNrFaces != pg2->iNrFaces) + return TFALSE; + while (i < pg1->iNrFaces && bStillSame) { + bStillSame = pg1->pTriMembers[i] == pg2->pTriMembers[i] ? TTRUE : TFALSE; + if (bStillSame) + ++i; } return bStillSame; } -static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed) -{ +static void QuickSort(int *pSortBuffer, int iLeft, int iRight, unsigned int uSeed) { int iL, iR, n, index, iMid, iTmp; // Random - unsigned int t=uSeed&31; - t=(uSeed<>(32-t)); - uSeed=uSeed+t+3; + unsigned int t = uSeed & 31; + t = (uSeed << t) | (uSeed >> (32 - t)); + uSeed = uSeed + t + 3; // Random end - iL=iLeft; iR=iRight; - n = (iR-iL)+1; - assert(n>=0); - index = (int) (uSeed%n); - - iMid=pSortBuffer[index + iL]; + iL = iLeft; + iR = iRight; + n = (iR - iL) + 1; + assert(n >= 0); + index = (int)(uSeed % n); + iMid = pSortBuffer[index + iL]; - do - { + do { while (pSortBuffer[iL] < iMid) ++iL; while (pSortBuffer[iR] > iMid) --iR; - if (iL <= iR) - { + if (iL <= iR) { iTmp = pSortBuffer[iL]; pSortBuffer[iL] = pSortBuffer[iR]; pSortBuffer[iR] = iTmp; - ++iL; --iR; + ++iL; + --iR; } - } - while (iL <= iR); + } while (iL <= iR); if (iLeft < iR) QuickSort(pSortBuffer, iLeft, iR, uSeed); @@ -1495,41 +1455,37 @@ static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSee ///////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// -static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed); -static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in); +static void QuickSortEdges(SEdge *pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed); +static void GetEdge(int *i0_out, int *i1_out, int *edgenum_out, const int indices[], const int i0_in, const int i1_in); -static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn) -{ +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge *pEdges, const int piTriListIn[], const int iNrTrianglesIn) { // build array of edges - unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? - int iEntries=0, iCurStartIndex=-1, f=0, i=0; - for (f=0; f pSortBuffer[iRight].array[channel]) - { + const int iElems = iRight - iLeft + 1; + if (iElems < 2) + return; + else if (iElems == 2) { + if (pSortBuffer[iLeft].array[channel] > pSortBuffer[iRight].array[channel]) { sTmp = pSortBuffer[iLeft]; pSortBuffer[iLeft] = pSortBuffer[iRight]; pSortBuffer[iRight] = sTmp; @@ -1663,35 +1604,33 @@ static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int } // Random - t=uSeed&31; - t=(uSeed<>(32-t)); - uSeed=uSeed+t+3; + t = uSeed & 31; + t = (uSeed << t) | (uSeed >> (32 - t)); + uSeed = uSeed + t + 3; // Random end iL = iLeft; iR = iRight; - n = (iR-iL)+1; - assert(n>=0); - index = (int) (uSeed%n); + n = (iR - iL) + 1; + assert(n >= 0); + index = (int)(uSeed % n); - iMid=pSortBuffer[index + iL].array[channel]; + iMid = pSortBuffer[index + iL].array[channel]; - do - { + do { while (pSortBuffer[iL].array[channel] < iMid) ++iL; while (pSortBuffer[iR].array[channel] > iMid) --iR; - if (iL <= iR) - { + if (iL <= iR) { sTmp = pSortBuffer[iL]; pSortBuffer[iL] = pSortBuffer[iR]; pSortBuffer[iR] = sTmp; - ++iL; --iR; + ++iL; + --iR; } - } - while (iL <= iR); + } while (iL <= iR); if (iLeft < iR) QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed); @@ -1700,197 +1639,175 @@ static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int } // resolve ordering and edge number -static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in) -{ +static void GetEdge(int *i0_out, int *i1_out, int *edgenum_out, const int indices[], const int i0_in, const int i1_in) { *edgenum_out = -1; - + // test if first index is on the edge - if (indices[0]==i0_in || indices[0]==i1_in) - { + if (indices[0] == i0_in || indices[0] == i1_in) { // test if second index is on the edge - if (indices[1]==i0_in || indices[1]==i1_in) - { - edgenum_out[0]=0; // first edge - i0_out[0]=indices[0]; - i1_out[0]=indices[1]; - } - else - { - edgenum_out[0]=2; // third edge - i0_out[0]=indices[2]; - i1_out[0]=indices[0]; + if (indices[1] == i0_in || indices[1] == i1_in) { + edgenum_out[0] = 0; // first edge + i0_out[0] = indices[0]; + i1_out[0] = indices[1]; + } else { + edgenum_out[0] = 2; // third edge + i0_out[0] = indices[2]; + i1_out[0] = indices[0]; } - } - else - { + } else { // only second and third index is on the edge - edgenum_out[0]=1; // second edge - i0_out[0]=indices[1]; - i1_out[0]=indices[2]; + edgenum_out[0] = 1; // second edge + i0_out[0] = indices[1]; + i1_out[0] = indices[2]; } } - ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////// Degenerate triangles //////////////////////////////////// -static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris) -{ - int iNextGoodTriangleSearchIndex=-1; +static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris) { + int iNextGoodTriangleSearchIndex = -1; tbool bStillFindingGoodOnes; // locate quads with only one good triangle - int t=0; - while (t<(iTotTris-1)) - { + int t = 0; + while (t < (iTotTris - 1)) { const int iFO_a = pTriInfos[t].iOrgFaceNumber; - const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; - if (iFO_a==iFO_b) // this is a quad + const int iFO_b = pTriInfos[t + 1].iOrgFaceNumber; + if (iFO_a == iFO_b) // this is a quad { - const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - if ((bIsDeg_a^bIsDeg_b)!=0) - { + const tbool bIsDeg_a = (pTriInfos[t].iFlag & MARK_DEGENERATE) != 0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t + 1].iFlag & MARK_DEGENERATE) != 0 ? TTRUE : TFALSE; + if ((bIsDeg_a ^ bIsDeg_b) != 0) { pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI; - pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI; + pTriInfos[t + 1].iFlag |= QUAD_ONE_DEGEN_TRI; } t += 2; - } - else + } else ++t; } // reorder list so all degen triangles are moved to the back // without reordering the good triangles iNextGoodTriangleSearchIndex = 1; - t=0; + t = 0; bStillFindingGoodOnes = TTRUE; - while (t (t+1)); + assert(iNextGoodTriangleSearchIndex > (t + 1)); // swap triangle t0 and t1 - if (!bJustADegenerate) - { - int i=0; - for (i=0; i<3; i++) - { - const int index = piTriList_out[t0*3+i]; - piTriList_out[t0*3+i] = piTriList_out[t1*3+i]; - piTriList_out[t1*3+i] = index; + if (!bJustADegenerate) { + int i = 0; + for (i = 0; i < 3; i++) { + const int index = piTriList_out[t0 * 3 + i]; + piTriList_out[t0 * 3 + i] = piTriList_out[t1 * 3 + i]; + piTriList_out[t1 * 3 + i] = index; } { const STriInfo tri_info = pTriInfos[t0]; pTriInfos[t0] = pTriInfos[t1]; pTriInfos[t1] = tri_info; } - } - else - bStillFindingGoodOnes = TFALSE; // this is not supposed to happen + } else + bStillFindingGoodOnes = TFALSE; // this is not supposed to happen } - if (bStillFindingGoodOnes) ++t; + if (bStillFindingGoodOnes) + ++t; } - assert(bStillFindingGoodOnes); // code will still work. + assert(bStillFindingGoodOnes); // code will still work. assert(iNrTrianglesIn == t); } -static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris) -{ - int t=0, i=0; +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext *pContext, const int iNrTrianglesIn, + const int iTotTris) { + int t = 0, i = 0; // deal with degenerate triangles // punishment for degenerate triangles is O(N^2) - for (t=iNrTrianglesIn; t; -bool ShouldEscape( char c ) -{ - switch ( c ) - { +bool ShouldEscape(char c) { + switch (c) { case '\\': case '"': return true; @@ -27,31 +24,24 @@ bool ShouldEscape( char c ) } } -std::string& Escape( std::string& s ) -{ - std::string::difference_type escapableCharacters = std::count_if( s.begin(), s.end(), ShouldEscape ); - if ( escapableCharacters == 0 ) - { +std::string &Escape(std::string &s) { + std::string::difference_type escapableCharacters = std::count_if(s.begin(), s.end(), ShouldEscape); + if (escapableCharacters == 0) { return s; } - if ( s.capacity() < (s.length() + escapableCharacters) ) - { + if (s.capacity() < (s.length() + escapableCharacters)) { // Grow if necessary. s.resize(s.length() + escapableCharacters); } std::string::iterator it = s.begin(); - while ( it != s.end() ) - { + while (it != s.end()) { char c = *it; - if ( ShouldEscape(c) ) - { + if (ShouldEscape(c)) { it = s.insert(it, '\\'); it += 2; - } - else - { + } else { ++it; } } @@ -59,55 +49,53 @@ std::string& Escape( std::string& s ) return s; } -bool EndsWith( const std::string& s, const std::string& suffix ) -{ - return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0; -} +bool EndsWith(const std::string &s, const std::string &suffix) { return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0; } -const char *GetShaderSuffix( GPUShaderType type ) -{ - switch ( type ) - { - case GPUSHADER_VERTEX: return "_vp"; - case GPUSHADER_FRAGMENT: return "_fp"; - case GPUSHADER_GEOMETRY: return "_gp"; - default: assert(!"Invalid shader type"); +const char *GetShaderSuffix(GPUShaderType type) { + switch (type) { + case GPUSHADER_VERTEX: + return "_vp"; + case GPUSHADER_FRAGMENT: + return "_fp"; + case GPUSHADER_GEOMETRY: + return "_gp"; + default: + assert(!"Invalid shader type"); } return nullptr; } -const char *ToString( GPUShaderType type ) -{ - switch ( type ) - { - case GPUSHADER_VERTEX: return "GPUSHADER_VERTEX"; - case GPUSHADER_FRAGMENT: return "GPUSHADER_FRAGMENT"; - case GPUSHADER_GEOMETRY: return "GPUSHADER_GEOMETRY"; - default: assert(!"Invalid shader type"); +const char *ToString(GPUShaderType type) { + switch (type) { + case GPUSHADER_VERTEX: + return "GPUSHADER_VERTEX"; + case GPUSHADER_FRAGMENT: + return "GPUSHADER_FRAGMENT"; + case GPUSHADER_GEOMETRY: + return "GPUSHADER_GEOMETRY"; + default: + assert(!"Invalid shader type"); } return nullptr; } } // anonymous namespace -int main( int argc, char *argv[] ) -{ +int main(int argc, char *argv[]) { StringList args(argv, argv + argc); - if ( args.empty() ) - { + if (args.empty()) { std::cerr << "No GLSL files were given.\n"; return EXIT_FAILURE; } - if ( args.size() < 4 ) - { + if (args.size() < 4) { // 0 = exe, 1 = cpp file, 2 = h file, 2+ = glsl files return EXIT_FAILURE; } - std::string& shadersCppFile = args[1]; - std::string& shadersHeaderFile = args[2]; + std::string &shadersCppFile = args[1]; + std::string &shadersHeaderFile = args[2]; StringList glslFiles(args.begin() + 3, args.end()); std::cout << "Outputting to '" << shadersCppFile << "' and '" << shadersHeaderFile << "'\n"; @@ -124,12 +112,9 @@ int main( int argc, char *argv[] ) cppStream << "// This file is auto-generated. DO NOT EDIT BY HAND\n"; cppStream << "#include \"tr_local.h\"\n\n"; - for ( StringList::const_iterator it = glslFiles.begin(); - it != glslFiles.end(); ++it ) - { + for (StringList::const_iterator it = glslFiles.begin(); it != glslFiles.end(); ++it) { // Get shader name from file name - if ( !EndsWith(*it, ".glsl") ) - { + if (!EndsWith(*it, ".glsl")) { std::cerr << *it << " doesn't end with .glsl extension.\n"; continue; } @@ -139,16 +124,15 @@ int main( int argc, char *argv[] ) // Write, one line at a time to the output std::ifstream fs(it->c_str()); - if ( !fs ) - { + if (!fs) { std::cerr << *it << " could not be opened.\n"; continue; } - //from: https://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file/22986486 + // from: https://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file/22986486 fs.ignore(std::numeric_limits::max()); std::streamsize fileSize = fs.gcount(); - fs.clear(); // Since ignore will have set eof. + fs.clear(); // Since ignore will have set eof. fs.seekg(0, std::ios::beg); allocator.Reset(); @@ -157,18 +141,16 @@ int main( int argc, char *argv[] ) memset(programText, 0, (size_t)fileSize + 1); fs.read(programText, fileSize); - GPUProgramDesc programDesc = ParseProgramSource(allocator, programText); - for ( size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i ) - { - GPUShaderDesc& shaderDesc = programDesc.shaders[i]; + GPUProgramDesc programDesc = ParseProgramSource(allocator, programText); + for (size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i) { + GPUShaderDesc &shaderDesc = programDesc.shaders[i]; const char *suffix = GetShaderSuffix(shaderDesc.type); cppStream << "const char *fallback_" + shaderName + suffix + " = \""; const char *lineStart = shaderDesc.source; const char *lineEnd = strchr(lineStart, '\n'); - while ( lineEnd ) - { + while (lineEnd) { line.assign(lineStart, lineEnd - lineStart); cppStream << Escape(line); cppStream << "\\n\"\n\""; @@ -182,40 +164,34 @@ int main( int argc, char *argv[] ) } cppStream << "GPUShaderDesc fallback_" << shaderName << "Shaders[] = {\n"; - for ( size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i ) - { - GPUShaderDesc& shaderDesc = programDesc.shaders[i]; + for (size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i) { + GPUShaderDesc &shaderDesc = programDesc.shaders[i]; const char *suffix = GetShaderSuffix(shaderDesc.type); - cppStream << " { " << ToString(shaderDesc.type) << ", " - "fallback_" << shaderName << suffix << ", " - << shaderDesc.firstLineNumber << " },\n"; + cppStream << " { " << ToString(shaderDesc.type) + << ", " + "fallback_" + << shaderName << suffix << ", " << shaderDesc.firstLineNumber << " },\n"; } cppStream << "};\n"; - cppStream << "extern const GPUProgramDesc fallback_" << shaderName << "Program = { " - << programDesc.numShaders << ", fallback_" << shaderName << "Shaders };\n\n"; + cppStream << "extern const GPUProgramDesc fallback_" << shaderName << "Program = { " << programDesc.numShaders << ", fallback_" << shaderName + << "Shaders };\n\n"; headerStream << "extern const GPUProgramDesc fallback_" << shaderName << "Program;\n"; } std::ofstream cppFile(shadersCppFile); - if ( !cppFile ) - { + if (!cppFile) { std::cerr << "Could not create file '" << shadersCppFile << "'\n"; - } - else - { + } else { cppFile << cppStream.str(); } std::ofstream headerFile(shadersHeaderFile); - if (!headerFile) - { + if (!headerFile) { std::cerr << "Could not create file '" << shadersHeaderFile << "'\n"; - } - else - { + } else { headerFile << headerStream.str(); } } diff --git a/codemp/rd-rend2/tr_allocator.cpp b/codemp/rd-rend2/tr_allocator.cpp index 4da0228c8c..0182a1310f 100644 --- a/codemp/rd-rend2/tr_allocator.cpp +++ b/codemp/rd-rend2/tr_allocator.cpp @@ -2,40 +2,32 @@ #include "tr_allocator.h" #include "tr_local.h" -Allocator::Allocator( void *memory, size_t memorySize, size_t alignment ) - : alignment(alignment) - , ownMemory(false) - , unalignedBase(memory) - , alignedBase(PADP(unalignedBase, alignment)) - , mark(alignedBase) - , end((char *)unalignedBase + memorySize) -{ +Allocator::Allocator(void *memory, size_t memorySize, size_t alignment) + : alignment(alignment), ownMemory(false), unalignedBase(memory), alignedBase(PADP(unalignedBase, alignment)), mark(alignedBase), + end((char *)unalignedBase + memorySize) { assert(unalignedBase); assert(memorySize); assert(alignment); } -Allocator::Allocator( size_t memorySize, size_t alignment ) - : alignment(alignment) - , ownMemory(true) +Allocator::Allocator(size_t memorySize, size_t alignment) + : alignment(alignment), ownMemory(true) #if defined(GLSL_BUILDTOOL) - , unalignedBase(malloc(memorySize)) + , + unalignedBase(malloc(memorySize)) #else - , unalignedBase(Z_Malloc(memorySize, TAG_SHADERTEXT)) + , + unalignedBase(Z_Malloc(memorySize, TAG_SHADERTEXT)) #endif - , alignedBase(PADP(unalignedBase, alignment)) - , mark(alignedBase) - , end((char *)unalignedBase + memorySize) -{ + , + alignedBase(PADP(unalignedBase, alignment)), mark(alignedBase), end((char *)unalignedBase + memorySize) { assert(unalignedBase); assert(memorySize); assert(alignment); } -Allocator::~Allocator() -{ - if ( ownMemory ) - { +Allocator::~Allocator() { + if (ownMemory) { #if defined(GLSL_BUILDTOOL) free(unalignedBase); #else @@ -44,20 +36,12 @@ Allocator::~Allocator() } } -void *Allocator::Base() const -{ - return alignedBase; -} +void *Allocator::Base() const { return alignedBase; } -size_t Allocator::GetSize() const -{ - return (size_t)((char *)end - (char *)alignedBase); -} +size_t Allocator::GetSize() const { return (size_t)((char *)end - (char *)alignedBase); } -void *Allocator::Alloc( size_t allocSize ) -{ - if ( (size_t)((char *)end - (char *)mark) < allocSize ) - { +void *Allocator::Alloc(size_t allocSize) { + if ((size_t)((char *)end - (char *)mark) < allocSize) { assert(!"Allocator is out of memory"); return nullptr; } @@ -70,17 +54,8 @@ void *Allocator::Alloc( size_t allocSize ) return result; } -void *Allocator::Mark() const -{ - return mark; -} +void *Allocator::Mark() const { return mark; } -void Allocator::Reset() -{ - mark = alignedBase; -} +void Allocator::Reset() { mark = alignedBase; } -void Allocator::ResetTo( void *m ) -{ - mark = m; -} +void Allocator::ResetTo(void *m) { mark = m; } diff --git a/codemp/rd-rend2/tr_animation.cpp b/codemp/rd-rend2/tr_animation.cpp index b1ca5e95f8..46dd2841af 100644 --- a/codemp/rd-rend2/tr_animation.cpp +++ b/codemp/rd-rend2/tr_animation.cpp @@ -27,13 +27,12 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA All bones should be an identity orientation to display the mesh exactly as it is specified. -For all other frames, the bones represent the transformation from the +For all other frames, the bones represent the transformation from the orientation of the bone in the base frame to the orientation in this frame. */ - // copied and adapted from tr_mesh.c /* @@ -42,89 +41,77 @@ R_MDRCullModel ============= */ -static int R_MDRCullModel( mdrHeader_t *header, trRefEntity_t *ent ) { - vec3_t bounds[2]; - mdrFrame_t *oldFrame, *newFrame; - int i, frameSize; +static int R_MDRCullModel(mdrHeader_t *header, trRefEntity_t *ent) { + vec3_t bounds[2]; + mdrFrame_t *oldFrame, *newFrame; + int i, frameSize; + + frameSize = (size_t)(&((mdrFrame_t *)0)->bones[header->numBones]); - frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); - // compute frame pointers - newFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.frame); - oldFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.oldframe); + newFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + frameSize * ent->e.frame); + oldFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + frameSize * ent->e.oldframe); // cull bounding sphere ONLY if this is not an upscaled entity - if ( !ent->e.nonNormalizedAxes ) - { - if ( ent->e.frame == ent->e.oldframe ) - { - switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) - { + if (!ent->e.nonNormalizedAxes) { + if (ent->e.frame == ent->e.oldframe) { + switch (R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius)) { // Ummm... yeah yeah I know we don't really have an md3 here.. but we pretend // we do. After all, the purpose of mdrs are not that different, are they? - - case CULL_OUT: - tr.pc.c_sphere_cull_md3_out++; - return CULL_OUT; - case CULL_IN: - tr.pc.c_sphere_cull_md3_in++; - return CULL_IN; + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; - case CULL_CLIP: - tr.pc.c_sphere_cull_md3_clip++; - break; + case CULL_IN: + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + + case CULL_CLIP: + tr.pc.c_sphere_cull_md3_clip++; + break; } - } - else - { + } else { int sphereCull, sphereCullB; - sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); - if ( newFrame == oldFrame ) { + sphereCull = R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius); + if (newFrame == oldFrame) { sphereCullB = sphereCull; } else { - sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + sphereCullB = R_CullLocalPointAndRadius(oldFrame->localOrigin, oldFrame->radius); } - if ( sphereCull == sphereCullB ) - { - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == sphereCullB) { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; - } - else if ( sphereCull == CULL_IN ) - { + } else if (sphereCull == CULL_IN) { tr.pc.c_sphere_cull_md3_in++; return CULL_IN; - } - else - { + } else { tr.pc.c_sphere_cull_md3_clip++; } } } } - + // calculate a bounding box in the current coordinate system - for (i = 0 ; i < 3 ; i++) { + for (i = 0; i < 3; i++) { bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; } - switch ( R_CullLocalBox( bounds ) ) - { - case CULL_IN: - tr.pc.c_box_cull_md3_in++; - return CULL_IN; - case CULL_CLIP: - tr.pc.c_box_cull_md3_clip++; - return CULL_CLIP; - case CULL_OUT: - default: - tr.pc.c_box_cull_md3_out++; - return CULL_OUT; + switch (R_CullLocalBox(bounds)) { + case CULL_IN: + tr.pc.c_box_cull_md3_in++; + return CULL_IN; + case CULL_CLIP: + tr.pc.c_box_cull_md3_clip++; + return CULL_CLIP; + case CULL_OUT: + default: + tr.pc.c_box_cull_md3_out++; + return CULL_OUT; } } @@ -135,33 +122,33 @@ R_MDRComputeFogNum ================= */ -int R_MDRComputeFogNum( mdrHeader_t *header, trRefEntity_t *ent ) { - int i, j; - fog_t *fog; - mdrFrame_t *mdrFrame; - vec3_t localOrigin; +int R_MDRComputeFogNum(mdrHeader_t *header, trRefEntity_t *ent) { + int i, j; + fog_t *fog; + mdrFrame_t *mdrFrame; + vec3_t localOrigin; int frameSize; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - - frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); + + frameSize = (size_t)(&((mdrFrame_t *)0)->bones[header->numBones]); // FIXME: non-normalized axis issues - mdrFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.frame); - VectorAdd( ent->e.origin, mdrFrame->localOrigin, localOrigin ); - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + mdrFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + frameSize * ent->e.frame); + VectorAdd(ent->e.origin, mdrFrame->localOrigin, localOrigin); + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( localOrigin[j] - mdrFrame->radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (localOrigin[j] - mdrFrame->radius >= fog->bounds[1][j]) { break; } - if ( localOrigin[j] + mdrFrame->radius <= fog->bounds[0][j] ) { + if (localOrigin[j] + mdrFrame->radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -169,7 +156,6 @@ int R_MDRComputeFogNum( mdrHeader_t *header, trRefEntity_t *ent ) { return 0; } - /* ============== R_MDRAddAnimSurfaces @@ -178,45 +164,36 @@ R_MDRAddAnimSurfaces // much stuff in there is just copied from R_AddMd3Surfaces in tr_mesh.c -void R_MDRAddAnimSurfaces( trRefEntity_t *ent, int entityNum ) { - mdrHeader_t *header; - mdrSurface_t *surface; - mdrLOD_t *lod; - shader_t *shader; - skin_t *skin; - int i, j; - int lodnum = 0; - int fogNum = 0; - int cull; - int cubemapIndex; - qboolean personalModel; +void R_MDRAddAnimSurfaces(trRefEntity_t *ent, int entityNum) { + mdrHeader_t *header; + mdrSurface_t *surface; + mdrLOD_t *lod; + shader_t *shader; + skin_t *skin; + int i, j; + int lodnum = 0; + int fogNum = 0; + int cull; + int cubemapIndex; + qboolean personalModel; header = (mdrHeader_t *)tr.currentModel->data.mdr; - - personalModel = (qboolean)( - (ent->e.renderfx & RF_THIRD_PERSON) && - !(tr.viewParms.isPortal || - (tr.viewParms.flags & VPF_DEPTHSHADOW))); - - if ( ent->e.renderfx & RF_WRAP_FRAMES ) - { + + personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !(tr.viewParms.isPortal || (tr.viewParms.flags & VPF_DEPTHSHADOW))); + + if (ent->e.renderfx & RF_WRAP_FRAMES) { ent->e.frame %= header->numFrames; ent->e.oldframe %= header->numFrames; - } - + } + // // Validate the frames so there is no chance of a crash. // This will write directly into the entity structure, so // when the surfaces are rendered, they don't need to be // range checked again. // - if ((ent->e.frame >= header->numFrames) - || (ent->e.frame < 0) - || (ent->e.oldframe >= header->numFrames) - || (ent->e.oldframe < 0) ) - { - ri.Printf( PRINT_DEVELOPER, "R_MDRAddAnimSurfaces: no such frame %d to %d for '%s'\n", - ent->e.oldframe, ent->e.frame, tr.currentModel->name ); + if ((ent->e.frame >= header->numFrames) || (ent->e.frame < 0) || (ent->e.oldframe >= header->numFrames) || (ent->e.oldframe < 0)) { + ri.Printf(PRINT_DEVELOPER, "R_MDRAddAnimSurfaces: no such frame %d to %d for '%s'\n", ent->e.oldframe, ent->e.frame, tr.currentModel->name); ent->e.frame = 0; ent->e.oldframe = 0; } @@ -225,81 +202,66 @@ void R_MDRAddAnimSurfaces( trRefEntity_t *ent, int entityNum ) { // cull the entire model if merged bounding box of both frames // is outside the view frustum. // - cull = R_MDRCullModel (header, ent); - if ( cull == CULL_OUT ) { + cull = R_MDRCullModel(header, ent); + if (cull == CULL_OUT) { return; - } + } // figure out the current LOD of the model we're rendering, and set the lod pointer respectively. lodnum = R_ComputeLOD(ent); // check whether this model has as that many LODs at all. If not, try the closest thing we got. - if(header->numLODs <= 0) + if (header->numLODs <= 0) return; - if(header->numLODs <= lodnum) + if (header->numLODs <= lodnum) lodnum = header->numLODs - 1; - lod = (mdrLOD_t *)( (byte *)header + header->ofsLODs); - for(i = 0; i < lodnum; i++) - { - lod = (mdrLOD_t *) ((byte *) lod + lod->ofsEnd); + lod = (mdrLOD_t *)((byte *)header + header->ofsLODs); + for (i = 0; i < lodnum; i++) { + lod = (mdrLOD_t *)((byte *)lod + lod->ofsEnd); } // fogNum? - fogNum = R_MDRComputeFogNum( header, ent ); + fogNum = R_MDRComputeFogNum(header, ent); cubemapIndex = R_CubemapForPoint(ent->e.origin); - surface = (mdrSurface_t *)( (byte *)lod + lod->ofsSurfaces ); + surface = (mdrSurface_t *)((byte *)lod + lod->ofsSurfaces); - for ( i = 0 ; i < lod->numSurfaces ; i++ ) - { - - if(ent->e.customShader) + for (i = 0; i < lod->numSurfaces; i++) { + + if (ent->e.customShader) shader = R_GetShaderByHandle(ent->e.customShader); - else if(ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) - { + else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin = R_GetSkinByHandle(ent->e.customSkin); shader = tr.defaultShader; - - for(j = 0; j < skin->numSurfaces; j++) - { - if (!strcmp(skin->surfaces[j]->name, surface->name)) - { + + for (j = 0; j < skin->numSurfaces; j++) { + if (!strcmp(skin->surfaces[j]->name, surface->name)) { shader = (shader_t *)skin->surfaces[j]->shader; break; } } - } - else if(surface->shaderIndex > 0) - shader = R_GetShaderByHandle( surface->shaderIndex ); + } else if (surface->shaderIndex > 0) + shader = R_GetShaderByHandle(surface->shaderIndex); else shader = tr.defaultShader; // we will add shadows even if the main object isn't visible in the view // stencil shadows can't do personal models unless I polyhedron clip - if ( !personalModel - && r_shadows->integer == 2 - && fogNum == 0 - && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) - { - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.shadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0 ); + if (!personalModel && r_shadows->integer == 2 && fogNum == 0 && !(ent->e.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, entityNum, tr.shadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 - && fogNum == 0 - && (ent->e.renderfx & RF_SHADOW_PLANE ) - && shader->sort == SS_OPAQUE ) - { - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0 ); + if (r_shadows->integer == 3 && fogNum == 0 && (ent->e.renderfx & RF_SHADOW_PLANE) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0); } if (!personalModel) - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex ); + R_AddDrawSurf((surfaceType_t *)surface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex); - surface = (mdrSurface_t *)( (byte *)surface + surface->ofsEnd ); + surface = (mdrSurface_t *)((byte *)surface + surface->ofsEnd); } } @@ -308,54 +270,47 @@ void R_MDRAddAnimSurfaces( trRefEntity_t *ent, int entityNum ) { RB_MDRSurfaceAnim ============== */ -void RB_MDRSurfaceAnim( mdrSurface_t *surface ) -{ - int i, j, k; - float frontlerp, backlerp; - int *triangles; - int indexes; - int baseIndex, baseVertex; - int numVerts; - mdrVertex_t *v; - mdrHeader_t *header; - mdrFrame_t *frame; - mdrFrame_t *oldFrame; - mdrBone_t bones[MDR_MAX_BONES], *bonePtr, *bone; - - int frameSize; +void RB_MDRSurfaceAnim(mdrSurface_t *surface) { + int i, j, k; + float frontlerp, backlerp; + int *triangles; + int indexes; + int baseIndex, baseVertex; + int numVerts; + mdrVertex_t *v; + mdrHeader_t *header; + mdrFrame_t *frame; + mdrFrame_t *oldFrame; + mdrBone_t bones[MDR_MAX_BONES], *bonePtr, *bone; + + int frameSize; // don't lerp if lerping off, or this is the only frame, or the last frame... // - if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) - { - backlerp = 0; // if backlerp is 0, lerping is off and frontlerp is never used - frontlerp = 1; - } - else - { - backlerp = backEnd.currentEntity->e.backlerp; - frontlerp = 1.0f - backlerp; + if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) { + backlerp = 0; // if backlerp is 0, lerping is off and frontlerp is never used + frontlerp = 1; + } else { + backlerp = backEnd.currentEntity->e.backlerp; + frontlerp = 1.0f - backlerp; } header = (mdrHeader_t *)((byte *)surface + surface->ofsHeader); - frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); + frameSize = (size_t)(&((mdrFrame_t *)0)->bones[header->numBones]); + + frame = (mdrFrame_t *)((byte *)header + header->ofsFrames + backEnd.currentEntity->e.frame * frameSize); + oldFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + backEnd.currentEntity->e.oldframe * frameSize); - frame = (mdrFrame_t *)((byte *)header + header->ofsFrames + - backEnd.currentEntity->e.frame * frameSize ); - oldFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + - backEnd.currentEntity->e.oldframe * frameSize ); + RB_CheckOverflow(surface->numVerts, surface->numTriangles); - RB_CheckOverflow( surface->numVerts, surface->numTriangles ); + triangles = (int *)((byte *)surface + surface->ofsTriangles); + indexes = surface->numTriangles * 3; + baseIndex = tess.numIndexes; + baseVertex = tess.numVertexes; - triangles = (int *) ((byte *)surface + surface->ofsTriangles); - indexes = surface->numTriangles * 3; - baseIndex = tess.numIndexes; - baseVertex = tess.numVertexes; - // Set up all triangles. - for (j = 0 ; j < indexes ; j++) - { + for (j = 0; j < indexes; j++) { tess.indexes[baseIndex + j] = baseVertex + triangles[j]; } tess.numIndexes += indexes; @@ -363,17 +318,13 @@ void RB_MDRSurfaceAnim( mdrSurface_t *surface ) // // lerp all the needed bones // - if ( !backlerp ) - { + if (!backlerp) { // no lerping needed bonePtr = frame->bones; - } - else - { + } else { bonePtr = bones; - - for ( i = 0 ; i < header->numBones*12 ; i++ ) - { + + for (i = 0; i < header->numBones * 12; i++) { ((float *)bonePtr)[i] = frontlerp * ((float *)frame->bones)[i] + backlerp * ((float *)oldFrame->bones)[i]; } } @@ -382,26 +333,24 @@ void RB_MDRSurfaceAnim( mdrSurface_t *surface ) // deform the vertexes by the lerped bones // numVerts = surface->numVerts; - v = (mdrVertex_t *) ((byte *)surface + surface->ofsVerts); - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; - mdrWeight_t *w; - - VectorClear( tempVert ); - VectorClear( tempNormal ); + v = (mdrVertex_t *)((byte *)surface + surface->ofsVerts); + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + mdrWeight_t *w; + + VectorClear(tempVert); + VectorClear(tempNormal); w = v->weights; - for ( k = 0 ; k < v->numWeights ; k++, w++ ) - { + for (k = 0; k < v->numWeights; k++, w++) { bone = bonePtr + w->boneIndex; - - tempVert[0] += w->boneWeight * ( DotProduct( bone->matrix[0], w->offset ) + bone->matrix[0][3] ); - tempVert[1] += w->boneWeight * ( DotProduct( bone->matrix[1], w->offset ) + bone->matrix[1][3] ); - tempVert[2] += w->boneWeight * ( DotProduct( bone->matrix[2], w->offset ) + bone->matrix[2][3] ); - - tempNormal[0] += w->boneWeight * DotProduct( bone->matrix[0], v->normal ); - tempNormal[1] += w->boneWeight * DotProduct( bone->matrix[1], v->normal ); - tempNormal[2] += w->boneWeight * DotProduct( bone->matrix[2], v->normal ); + + tempVert[0] += w->boneWeight * (DotProduct(bone->matrix[0], w->offset) + bone->matrix[0][3]); + tempVert[1] += w->boneWeight * (DotProduct(bone->matrix[1], w->offset) + bone->matrix[1][3]); + tempVert[2] += w->boneWeight * (DotProduct(bone->matrix[2], w->offset) + bone->matrix[2][3]); + + tempNormal[0] += w->boneWeight * DotProduct(bone->matrix[0], v->normal); + tempNormal[1] += w->boneWeight * DotProduct(bone->matrix[1], v->normal); + tempNormal[2] += w->boneWeight * DotProduct(bone->matrix[2], v->normal); } tess.xyz[baseVertex + j][0] = tempVert[0]; diff --git a/codemp/rd-rend2/tr_backend.cpp b/codemp/rd-rend2/tr_backend.cpp index 65c19308ff..cddb478ac9 100644 --- a/codemp/rd-rend2/tr_backend.cpp +++ b/codemp/rd-rend2/tr_backend.cpp @@ -24,67 +24,59 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "glext.h" #include -backEndData_t *backEndData; -backEndState_t backEnd; +backEndData_t *backEndData; +backEndState_t backEnd; - -static float s_flipMatrix[16] = { +static float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; - + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; /* ** GL_Bind */ -void GL_Bind( image_t *image ) { +void GL_Bind(image_t *image) { int texnum; - if ( !image ) { - ri.Printf( PRINT_WARNING, "GL_Bind: NULL image\n" ); + if (!image) { + ri.Printf(PRINT_WARNING, "GL_Bind: NULL image\n"); texnum = tr.defaultImage->texnum; } else { texnum = image->texnum; } - if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option + if (r_nobind->integer && tr.dlightImage) { // performance evaluation option texnum = tr.dlightImage->texnum; } - if ( glState.currenttextures[glState.currenttmu] != texnum ) { - if ( image ) { + if (glState.currenttextures[glState.currenttmu] != texnum) { + if (image) { image->frameUsed = tr.frameCount; } glState.currenttextures[glState.currenttmu] = texnum; if (image && image->flags & IMGFLAG_CUBEMAP) - qglBindTexture( GL_TEXTURE_CUBE_MAP, texnum ); + qglBindTexture(GL_TEXTURE_CUBE_MAP, texnum); else if (image->flags & IMGFLAG_3D) qglBindTexture(GL_TEXTURE_3D, texnum); else if (image->flags & IMGFLAG_2D_ARRAY) qglBindTexture(GL_TEXTURE_2D_ARRAY, texnum); else - qglBindTexture( GL_TEXTURE_2D, texnum ); + qglBindTexture(GL_TEXTURE_2D, texnum); } } /* ** GL_SelectTexture */ -void GL_SelectTexture( int unit ) -{ - if ( glState.currenttmu == unit ) - { +void GL_SelectTexture(int unit) { + if (glState.currenttmu == unit) { return; } if (!(unit >= 0 && unit <= 31)) - ri.Error( ERR_DROP, "GL_SelectTexture: unit = %i", unit ); + ri.Error(ERR_DROP, "GL_SelectTexture: unit = %i", unit); - qglActiveTexture( GL_TEXTURE0 + unit ); + qglActiveTexture(GL_TEXTURE0 + unit); glState.currenttmu = unit; } @@ -92,66 +84,60 @@ void GL_SelectTexture( int unit ) /* ** GL_BindToTMU */ -void GL_BindToTMU( image_t *image, int tmu ) -{ - int texnum; - int oldtmu = glState.currenttmu; +void GL_BindToTMU(image_t *image, int tmu) { + int texnum; + int oldtmu = glState.currenttmu; if (!image) texnum = 0; else texnum = image->texnum; - if ( glState.currenttextures[tmu] != texnum ) { - GL_SelectTexture( tmu ); + if (glState.currenttextures[tmu] != texnum) { + GL_SelectTexture(tmu); if (image) image->frameUsed = tr.frameCount; glState.currenttextures[tmu] = texnum; if (image && (image->flags & IMGFLAG_CUBEMAP)) - qglBindTexture( GL_TEXTURE_CUBE_MAP, texnum ); + qglBindTexture(GL_TEXTURE_CUBE_MAP, texnum); else if (image && (image->flags & IMGFLAG_3D)) qglBindTexture(GL_TEXTURE_3D, texnum); else if (image && (image->flags & IMGFLAG_2D_ARRAY)) qglBindTexture(GL_TEXTURE_2D_ARRAY, texnum); else - qglBindTexture( GL_TEXTURE_2D, texnum ); + qglBindTexture(GL_TEXTURE_2D, texnum); } } /* ** GL_Cull */ -void GL_Cull( int cullType ) { - if ( glState.faceCulling == cullType ) { +void GL_Cull(int cullType) { + if (glState.faceCulling == cullType) { return; } - if ( backEnd.projection2D ) + if (backEnd.projection2D) cullType = CT_TWO_SIDED; - if ( cullType == CT_TWO_SIDED ) - { - if ( glState.faceCulling != CT_TWO_SIDED ) - qglDisable( GL_CULL_FACE ); - } - else - { + if (cullType == CT_TWO_SIDED) { + if (glState.faceCulling != CT_TWO_SIDED) + qglDisable(GL_CULL_FACE); + } else { qboolean cullFront = (qboolean)(cullType == CT_FRONT_SIDED); - - if ( glState.faceCulling == CT_TWO_SIDED ) - qglEnable( GL_CULL_FACE ); - qglCullFace( cullFront ? GL_FRONT : GL_BACK); + if (glState.faceCulling == CT_TWO_SIDED) + qglEnable(GL_CULL_FACE); + + qglCullFace(cullFront ? GL_FRONT : GL_BACK); } glState.faceCulling = cullType; } -void GL_DepthRange( float min, float max ) -{ - if ( glState.minDepth == min && glState.maxDepth == max ) - { +void GL_DepthRange(float min, float max) { + if (glState.minDepth == min && glState.maxDepth == max) { return; } @@ -166,49 +152,36 @@ void GL_DepthRange( float min, float max ) ** This routine is responsible for setting the most commonly changed state ** in Q3. */ -void GL_State( uint32_t stateBits ) -{ +void GL_State(uint32_t stateBits) { uint32_t diff = stateBits ^ glState.glStateBits; - if ( !diff ) - { + if (!diff) { return; } // // check depthFunc bits // - if ( diff & GLS_DEPTHFUNC_BITS ) - { - if ( stateBits & GLS_DEPTHFUNC_EQUAL ) - { - qglDepthFunc( GL_EQUAL ); - } - else if ( stateBits & GLS_DEPTHFUNC_GREATER ) - { - qglDepthFunc( GL_GREATER ); - } - else if ( stateBits & GLS_DEPTHFUNC_LESS ) - { - qglDepthFunc( GL_LESS ); - } - else - { - qglDepthFunc( GL_LEQUAL ); + if (diff & GLS_DEPTHFUNC_BITS) { + if (stateBits & GLS_DEPTHFUNC_EQUAL) { + qglDepthFunc(GL_EQUAL); + } else if (stateBits & GLS_DEPTHFUNC_GREATER) { + qglDepthFunc(GL_GREATER); + } else if (stateBits & GLS_DEPTHFUNC_LESS) { + qglDepthFunc(GL_LESS); + } else { + qglDepthFunc(GL_LEQUAL); } } // // check blend bits // - if ( diff & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { + if (diff & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { GLenum srcFactor = GL_ONE, dstFactor = GL_ONE; - if ( stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { - switch ( stateBits & GLS_SRCBLEND_BITS ) - { + if (stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { + switch (stateBits & GLS_SRCBLEND_BITS) { case GLS_SRCBLEND_ZERO: srcFactor = GL_ZERO; break; @@ -237,12 +210,11 @@ void GL_State( uint32_t stateBits ) srcFactor = GL_SRC_ALPHA_SATURATE; break; default: - ri.Error( ERR_DROP, "GL_State: invalid src blend state bits" ); + ri.Error(ERR_DROP, "GL_State: invalid src blend state bits"); break; } - switch ( stateBits & GLS_DSTBLEND_BITS ) - { + switch (stateBits & GLS_DSTBLEND_BITS) { case GLS_DSTBLEND_ZERO: dstFactor = GL_ZERO; break; @@ -268,45 +240,35 @@ void GL_State( uint32_t stateBits ) dstFactor = GL_ONE_MINUS_DST_ALPHA; break; default: - ri.Error( ERR_DROP, "GL_State: invalid dst blend state bits" ); + ri.Error(ERR_DROP, "GL_State: invalid dst blend state bits"); break; } - qglEnable( GL_BLEND ); - qglBlendFunc( srcFactor, dstFactor ); - } - else - { - qglDisable( GL_BLEND ); + qglEnable(GL_BLEND); + qglBlendFunc(srcFactor, dstFactor); + } else { + qglDisable(GL_BLEND); } } // // check colormask // - if ( diff & GLS_COLORMASK_BITS ) - { - if ( stateBits & GLS_COLORMASK_BITS ) - { - qglColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); - } - else - { - qglColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); + if (diff & GLS_COLORMASK_BITS) { + if (stateBits & GLS_COLORMASK_BITS) { + qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + } else { + qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } } // // check stenciltest // - if (diff & GLS_STENCILTEST_ENABLE) - { - if (stateBits & GLS_STENCILTEST_ENABLE) - { + if (diff & GLS_STENCILTEST_ENABLE) { + if (stateBits & GLS_STENCILTEST_ENABLE) { qglEnable(GL_STENCIL_TEST); - } - else - { + } else { qglDisable(GL_STENCIL_TEST); } } @@ -314,99 +276,66 @@ void GL_State( uint32_t stateBits ) // // check depthmask // - if ( diff & GLS_DEPTHMASK_TRUE ) - { - if ( stateBits & GLS_DEPTHMASK_TRUE ) - { - qglDepthMask( GL_TRUE ); - } - else - { - qglDepthMask( GL_FALSE ); + if (diff & GLS_DEPTHMASK_TRUE) { + if (stateBits & GLS_DEPTHMASK_TRUE) { + qglDepthMask(GL_TRUE); + } else { + qglDepthMask(GL_FALSE); } } // // fill/line mode // - if ( diff & GLS_POLYMODE_LINE ) - { - if ( stateBits & GLS_POLYMODE_LINE ) - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); - } - else - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + if (diff & GLS_POLYMODE_LINE) { + if (stateBits & GLS_POLYMODE_LINE) { + qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + } else { + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } // // depthtest // - if ( diff & GLS_DEPTHTEST_DISABLE ) - { - if ( stateBits & GLS_DEPTHTEST_DISABLE ) - { - qglDisable( GL_DEPTH_TEST ); - } - else - { - qglEnable( GL_DEPTH_TEST ); + if (diff & GLS_DEPTHTEST_DISABLE) { + if (stateBits & GLS_DEPTHTEST_DISABLE) { + qglDisable(GL_DEPTH_TEST); + } else { + qglEnable(GL_DEPTH_TEST); } } - if ( diff & GLS_POLYGON_OFFSET_FILL ) - { - if ( stateBits & GLS_POLYGON_OFFSET_FILL ) - { - qglEnable( GL_POLYGON_OFFSET_FILL ); - } - else - { - qglDisable( GL_POLYGON_OFFSET_FILL ); + if (diff & GLS_POLYGON_OFFSET_FILL) { + if (stateBits & GLS_POLYGON_OFFSET_FILL) { + qglEnable(GL_POLYGON_OFFSET_FILL); + } else { + qglDisable(GL_POLYGON_OFFSET_FILL); } } glState.glStateBits = stateBits; } -void GL_VertexAttribPointers( - size_t numAttributes, - vertexAttribute_t *attributes ) -{ +void GL_VertexAttribPointers(size_t numAttributes, vertexAttribute_t *attributes) { assert(attributes != nullptr || numAttributes == 0); uint32_t newAttribs = 0; - for ( int i = 0; i < numAttributes; i++ ) - { - vertexAttribute_t& attrib = attributes[i]; - vertexAttribute_t& currentAttrib = glState.currentVaoAttribs[attrib.index]; + for (int i = 0; i < numAttributes; i++) { + vertexAttribute_t &attrib = attributes[i]; + vertexAttribute_t ¤tAttrib = glState.currentVaoAttribs[attrib.index]; newAttribs |= (1 << attrib.index); - if (memcmp(¤tAttrib, &attrib, sizeof(currentAttrib)) == 0) - { + if (memcmp(¤tAttrib, &attrib, sizeof(currentAttrib)) == 0) { // No change continue; } R_BindVBO(attrib.vbo); - if ( attrib.integerAttribute ) - { - qglVertexAttribIPointer(attrib.index, - attrib.numComponents, - attrib.type, - attrib.stride, - BUFFER_OFFSET(attrib.offset)); - } - else - { - qglVertexAttribPointer(attrib.index, - attrib.numComponents, - attrib.type, - attrib.normalize, - attrib.stride, - BUFFER_OFFSET(attrib.offset)); + if (attrib.integerAttribute) { + qglVertexAttribIPointer(attrib.index, attrib.numComponents, attrib.type, attrib.stride, BUFFER_OFFSET(attrib.offset)); + } else { + qglVertexAttribPointer(attrib.index, attrib.numComponents, attrib.type, attrib.normalize, attrib.stride, BUFFER_OFFSET(attrib.offset)); } if (currentAttrib.stepRate != attrib.stepRate) @@ -416,14 +345,11 @@ void GL_VertexAttribPointers( } uint32_t diff = newAttribs ^ glState.vertexAttribsState; - if ( diff ) - { - for ( int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1 ) - { + if (diff) { + for (int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1) { // FIXME: Use BitScanForward? - if (diff & j) - { - if(newAttribs & j) + if (diff & j) { + if (newAttribs & j) qglEnableVertexAttribArray(i); else qglDisableVertexAttribArray(i); @@ -434,59 +360,31 @@ void GL_VertexAttribPointers( } } -void GL_DrawIndexed( - GLenum primitiveType, - int numIndices, - GLenum indexType, - int offset, - int numInstances, - int baseVertex) -{ +void GL_DrawIndexed(GLenum primitiveType, int numIndices, GLenum indexType, int offset, int numInstances, int baseVertex) { assert(numInstances > 0); - qglDrawElementsInstancedBaseVertex( - primitiveType, - numIndices, - indexType, - BUFFER_OFFSET(offset), - numInstances, - baseVertex); -} - -void GL_MultiDrawIndexed( - GLenum primitiveType, - int *numIndices, - glIndex_t **offsets, - int numDraws) -{ + qglDrawElementsInstancedBaseVertex(primitiveType, numIndices, indexType, BUFFER_OFFSET(offset), numInstances, baseVertex); +} + +void GL_MultiDrawIndexed(GLenum primitiveType, int *numIndices, glIndex_t **offsets, int numDraws) { assert(numDraws > 0); - qglMultiDrawElements( - primitiveType, - numIndices, - GL_INDEX_TYPE, - (const GLvoid **)offsets, - numDraws); + qglMultiDrawElements(primitiveType, numIndices, GL_INDEX_TYPE, (const GLvoid **)offsets, numDraws); } -void GL_Draw( GLenum primitiveType, int firstVertex, int numVertices, int numInstances ) -{ +void GL_Draw(GLenum primitiveType, int firstVertex, int numVertices, int numInstances) { assert(numInstances > 0); qglDrawArraysInstanced(primitiveType, firstVertex, numVertices, numInstances); } -void GL_SetProjectionMatrix(matrix_t matrix) -{ +void GL_SetProjectionMatrix(matrix_t matrix) { Matrix16Copy(matrix, glState.projection); - Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); + Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); } - -void GL_SetModelviewMatrix(matrix_t matrix) -{ +void GL_SetModelviewMatrix(matrix_t matrix) { Matrix16Copy(matrix, glState.modelview); - Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); + Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); } - /* ================ RB_Hyperspace @@ -494,30 +392,22 @@ RB_Hyperspace A player has predicted a teleport, but hasn't arrived yet ================ */ -static void RB_Hyperspace( void ) { - float c = ( backEnd.refdef.time & 255 ) / 255.0f; - vec4_t v = { c, c, c, 1.0f }; - qglClearBufferfv( GL_COLOR, 0, v ); +static void RB_Hyperspace(void) { + float c = (backEnd.refdef.time & 255) / 255.0f; + vec4_t v = {c, c, c, 1.0f}; + qglClearBufferfv(GL_COLOR, 0, v); } - -static void SetViewportAndScissor( void ) { - GL_SetProjectionMatrix( backEnd.viewParms.projectionMatrix ); +static void SetViewportAndScissor(void) { + GL_SetProjectionMatrix(backEnd.viewParms.projectionMatrix); // set the window clipping - qglViewport( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglViewport(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); - if ( !backEnd.viewParms.scissorX && !backEnd.viewParms.scissorY && - !backEnd.viewParms.scissorWidth && !backEnd.viewParms.scissorHeight ) - { - qglScissor( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - } - else - { - qglScissor( backEnd.viewParms.scissorX, backEnd.viewParms.scissorY, - backEnd.viewParms.scissorWidth, backEnd.viewParms.scissorHeight ); + if (!backEnd.viewParms.scissorX && !backEnd.viewParms.scissorY && !backEnd.viewParms.scissorWidth && !backEnd.viewParms.scissorHeight) { + qglScissor(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); + } else { + qglScissor(backEnd.viewParms.scissorX, backEnd.viewParms.scissorY, backEnd.viewParms.scissorWidth, backEnd.viewParms.scissorHeight); } } @@ -529,7 +419,7 @@ Any mirrored or portaled views have already been drawn, so prepare to actually render the visible surfaces for this view ================= */ -void RB_BeginDrawingView (void) { +void RB_BeginDrawingView(void) { int clearBits = 0; // we will need to change the projection matrix before drawing @@ -538,19 +428,13 @@ void RB_BeginDrawingView (void) { // FIXME: HUGE HACK: render to the screen fbo if we've already postprocessed the frame and aren't drawing more world // drawing more world check is in case of double renders, such as skyportals - if (backEnd.viewParms.targetFbo == NULL) - { - if (!tr.renderFbo || (backEnd.framePostProcessed && (backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) - { + if (backEnd.viewParms.targetFbo == NULL) { + if (!tr.renderFbo || (backEnd.framePostProcessed && (backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } - } - else - { + } else { FBO_Bind(backEnd.viewParms.targetFbo); } @@ -560,35 +444,30 @@ void RB_BeginDrawingView (void) { SetViewportAndScissor(); // ensures that depth writes are enabled for the depth clear - GL_State( GLS_DEFAULT ); + GL_State(GLS_DEFAULT); // clear relevant buffers clearBits = GL_DEPTH_BUFFER_BIT; - if ( r_clear->integer ) - { + if (r_clear->integer) { clearBits |= GL_COLOR_BUFFER_BIT; } - if ( r_measureOverdraw->integer || r_shadows->integer == 2 ) - { + if (r_measureOverdraw->integer || r_shadows->integer == 2) { clearBits |= GL_STENCIL_BUFFER_BIT; } - if ( r_fastsky->integer && !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) ) - { - clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used + if (r_fastsky->integer && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) { + clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used #ifdef _DEBUG - qglClearColor( 0.8f, 0.7f, 0.4f, 1.0f ); // FIXME: get color of sky + qglClearColor(0.8f, 0.7f, 0.4f, 1.0f); // FIXME: get color of sky #else - qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); // FIXME: get color of sky + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); // FIXME: get color of sky #endif } - if (tr.refdef.rdflags & RDF_AUTOMAP || (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) - { - if (tr.world && tr.world->globalFog) - { - const fog_t *fog = tr.world->globalFog; + if (tr.refdef.rdflags & RDF_AUTOMAP || (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) { + if (tr.world && tr.world->globalFog) { + const fog_t *fog = tr.world->globalFog; clearBits |= GL_COLOR_BUFFER_BIT; qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); @@ -600,17 +479,15 @@ void RB_BeginDrawingView (void) { clearBits &= ~GL_COLOR_BUFFER_BIT; if (clearBits > 0 && !(backEnd.viewParms.flags & VPF_NOCLEAR)) - qglClear( clearBits ); + qglClear(clearBits); - if (backEnd.viewParms.targetFbo == NULL) - { + if (backEnd.viewParms.targetFbo == NULL) { // Clear the glow target float black[] = {0.0f, 0.0f, 0.0f, 1.0f}; - qglClearBufferfv (GL_COLOR, 1, black); + qglClearBufferfv(GL_COLOR, 1, black); } - if ( ( backEnd.refdef.rdflags & RDF_HYPERSPACE ) ) - { + if ((backEnd.refdef.rdflags & RDF_HYPERSPACE)) { RB_Hyperspace(); return; } @@ -619,7 +496,7 @@ void RB_BeginDrawingView (void) { backEnd.skyRenderedThisView = qfalse; // clip to the plane of the portal - if ( backEnd.viewParms.isPortal ) { + if (backEnd.viewParms.isPortal) { #if 0 float plane[4]; double plane2[4]; @@ -634,7 +511,7 @@ void RB_BeginDrawingView (void) { plane2[2] = DotProduct (backEnd.viewParms.ori.axis[2], plane); plane2[3] = DotProduct (plane, backEnd.viewParms.ori.origin) - plane[3]; #endif - GL_SetModelviewMatrix( s_flipMatrix ); + GL_SetModelviewMatrix(s_flipMatrix); } if (backEnd.viewParms.flags & VPF_POINTSHADOW) @@ -643,70 +520,36 @@ void RB_BeginDrawingView (void) { qglPolygonOffset(r_offsetFactor->value, r_offsetUnits->value); } +#define MAC_EVENT_PUMP_MSEC 5 -#define MAC_EVENT_PUMP_MSEC 5 - -void DrawItemSetVertexAttributes( - DrawItem& drawItem, - const vertexAttribute_t *attributes, - uint32_t count, - Allocator& allocator) -{ +void DrawItemSetVertexAttributes(DrawItem &drawItem, const vertexAttribute_t *attributes, uint32_t count, Allocator &allocator) { drawItem.numAttributes = count; drawItem.attributes = ojkAllocArray(allocator, count); - memcpy( - drawItem.attributes, attributes, sizeof(*drawItem.attributes) * count); + memcpy(drawItem.attributes, attributes, sizeof(*drawItem.attributes) * count); } -void DrawItemSetSamplerBindings( - DrawItem& drawItem, - const SamplerBinding *bindings, - uint32_t count, - Allocator& allocator) -{ +void DrawItemSetSamplerBindings(DrawItem &drawItem, const SamplerBinding *bindings, uint32_t count, Allocator &allocator) { drawItem.numSamplerBindings = count; drawItem.samplerBindings = ojkAllocArray(allocator, count); - memcpy( - drawItem.samplerBindings, - bindings, - sizeof(*drawItem.samplerBindings) * count); -} - -void DrawItemSetUniformBlockBindings( - DrawItem& drawItem, - const UniformBlockBinding *bindings, - uint32_t count, - Allocator& allocator) -{ - drawItem.numUniformBlockBindings = count; - drawItem.uniformBlockBindings = ojkAllocArray( - allocator, count); - memcpy( - drawItem.uniformBlockBindings, - bindings, - sizeof(*drawItem.uniformBlockBindings) * count); + memcpy(drawItem.samplerBindings, bindings, sizeof(*drawItem.samplerBindings) * count); } -UniformDataWriter::UniformDataWriter() - : failed(false) - , shaderProgram(nullptr) - , scratch(scratchBuffer, sizeof(scratchBuffer), 1) -{ +void DrawItemSetUniformBlockBindings(DrawItem &drawItem, const UniformBlockBinding *bindings, uint32_t count, Allocator &allocator) { + drawItem.numUniformBlockBindings = count; + drawItem.uniformBlockBindings = ojkAllocArray(allocator, count); + memcpy(drawItem.uniformBlockBindings, bindings, sizeof(*drawItem.uniformBlockBindings) * count); } -void UniformDataWriter::Start( shaderProgram_t *sp ) -{ - shaderProgram = sp; -} +UniformDataWriter::UniformDataWriter() : failed(false), shaderProgram(nullptr), scratch(scratchBuffer, sizeof(scratchBuffer), 1) {} + +void UniformDataWriter::Start(shaderProgram_t *sp) { shaderProgram = sp; } -UniformDataWriter& UniformDataWriter::SetUniformInt( uniform_t uniform, int value ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformInt(uniform_t uniform, int value) { + if (shaderProgram->uniforms[uniform] == -1) return *this; void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(int)); - if ( !memory ) - { + if (!memory) { failed = true; return *this; } @@ -721,19 +564,14 @@ UniformDataWriter& UniformDataWriter::SetUniformInt( uniform_t uniform, int valu return *this; } -UniformDataWriter& UniformDataWriter::SetUniformFloat( uniform_t uniform, float value ) -{ - return SetUniformFloat(uniform, &value, 1); -} +UniformDataWriter &UniformDataWriter::SetUniformFloat(uniform_t uniform, float value) { return SetUniformFloat(uniform, &value, 1); } -UniformDataWriter& UniformDataWriter::SetUniformFloat( uniform_t uniform, float *values, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformFloat(uniform_t uniform, float *values, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float) * count); + if (!memory) { failed = true; return *this; } @@ -746,20 +584,17 @@ UniformDataWriter& UniformDataWriter::SetUniformFloat( uniform_t uniform, float return *this; } -UniformDataWriter& UniformDataWriter::SetUniformVec2( uniform_t uniform, float x, float y ) -{ +UniformDataWriter &UniformDataWriter::SetUniformVec2(uniform_t uniform, float x, float y) { vec2_t values = {x, y}; return SetUniformVec2(uniform, values); } -UniformDataWriter& UniformDataWriter::SetUniformVec2( uniform_t uniform, const float *values, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformVec2(uniform_t uniform, const float *values, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec2_t)*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec2_t) * count); + if (!memory) { failed = true; return *this; } @@ -772,20 +607,17 @@ UniformDataWriter& UniformDataWriter::SetUniformVec2( uniform_t uniform, const f return *this; } -UniformDataWriter& UniformDataWriter::SetUniformVec3( uniform_t uniform, float x, float y, float z ) -{ +UniformDataWriter &UniformDataWriter::SetUniformVec3(uniform_t uniform, float x, float y, float z) { vec3_t values = {x, y, z}; return SetUniformVec3(uniform, values); } -UniformDataWriter& UniformDataWriter::SetUniformVec3( uniform_t uniform, const float *values, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformVec3(uniform_t uniform, const float *values, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec3_t)*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec3_t) * count); + if (!memory) { failed = true; return *this; } @@ -798,20 +630,17 @@ UniformDataWriter& UniformDataWriter::SetUniformVec3( uniform_t uniform, const f return *this; } -UniformDataWriter& UniformDataWriter::SetUniformVec4( uniform_t uniform, float x, float y, float z, float w ) -{ +UniformDataWriter &UniformDataWriter::SetUniformVec4(uniform_t uniform, float x, float y, float z, float w) { vec4_t values = {x, y, z, w}; return SetUniformVec4(uniform, values); } -UniformDataWriter& UniformDataWriter::SetUniformVec4( uniform_t uniform, const float *values, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformVec4(uniform_t uniform, const float *values, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec4_t)*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec4_t) * count); + if (!memory) { failed = true; return *this; } @@ -824,14 +653,12 @@ UniformDataWriter& UniformDataWriter::SetUniformVec4( uniform_t uniform, const f return *this; } -UniformDataWriter& UniformDataWriter::SetUniformMatrix4x3( uniform_t uniform, const float *matrix, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformMatrix4x3(uniform_t uniform, const float *matrix, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*12*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float) * 12 * count); + if (!memory) { failed = true; return *this; } @@ -844,14 +671,12 @@ UniformDataWriter& UniformDataWriter::SetUniformMatrix4x3( uniform_t uniform, co return *this; } -UniformDataWriter& UniformDataWriter::SetUniformMatrix4x4( uniform_t uniform, const float *matrix, size_t count ) -{ - if ( shaderProgram->uniforms[uniform] == -1 ) +UniformDataWriter &UniformDataWriter::SetUniformMatrix4x4(uniform_t uniform, const float *matrix, size_t count) { + if (shaderProgram->uniforms[uniform] == -1) return *this; - void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*16*count); - if ( !memory ) - { + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float) * 16 * count); + if (!memory) { failed = true; return *this; } @@ -864,11 +689,9 @@ UniformDataWriter& UniformDataWriter::SetUniformMatrix4x4( uniform_t uniform, co return *this; } -UniformData *UniformDataWriter::Finish( Allocator& destHeap ) -{ +UniformData *UniformDataWriter::Finish(Allocator &destHeap) { UniformData *endSentinel = ojkAlloc(scratch); - if ( failed || !endSentinel ) - { + if (failed || !endSentinel) { return nullptr; } @@ -888,17 +711,11 @@ UniformData *UniformDataWriter::Finish( Allocator& destHeap ) return result; } -SamplerBindingsWriter::SamplerBindingsWriter() - : failed(false) - , count(0) -{ -} +SamplerBindingsWriter::SamplerBindingsWriter() : failed(false), count(0) {} -SamplerBindingsWriter& SamplerBindingsWriter::AddStaticImage( image_t *image, int unit ) -{ +SamplerBindingsWriter &SamplerBindingsWriter::AddStaticImage(image_t *image, int unit) { SamplerBinding *binding = &scratch[count]; - if ( !binding ) - { + if (!binding) { failed = true; return *this; } @@ -911,15 +728,12 @@ SamplerBindingsWriter& SamplerBindingsWriter::AddStaticImage( image_t *image, in return *this; } -SamplerBindingsWriter& SamplerBindingsWriter::AddAnimatedImage( textureBundle_t *bundle, int unit ) -{ +SamplerBindingsWriter &SamplerBindingsWriter::AddAnimatedImage(textureBundle_t *bundle, int unit) { int index; - if ( bundle->isVideoMap ) - { + if (bundle->isVideoMap) { SamplerBinding *binding = &scratch[count]; - if ( !binding ) - { + if (!binding) { failed = true; return *this; } @@ -932,91 +746,71 @@ SamplerBindingsWriter& SamplerBindingsWriter::AddAnimatedImage( textureBundle_t return *this; } - if ( bundle->numImageAnimations <= 1 ) - { + if (bundle->numImageAnimations <= 1) { return AddStaticImage(bundle->image[0], unit); } - if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) - { + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX) { index = backEnd.currentEntity->e.skinNum; - } - else - { + } else { // it is necessary to do this messy calc to make sure animations line up // exactly with waveforms of the same frequency - index = Q_ftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index = Q_ftol(tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE); index = Q_max(0, index >> FUNCTABLE_SIZE2); } - if ( bundle->oneShotAnimMap ) - { + if (bundle->oneShotAnimMap) { index = Q_min(index, bundle->numImageAnimations - 1); - } - else - { + } else { // loop index %= bundle->numImageAnimations; } - return AddStaticImage(bundle->image[ index ], unit); + return AddStaticImage(bundle->image[index], unit); } -SamplerBinding *SamplerBindingsWriter::Finish( Allocator& destHeap, uint32_t* numBindings ) -{ - if ( failed ) - { +SamplerBinding *SamplerBindingsWriter::Finish(Allocator &destHeap, uint32_t *numBindings) { + if (failed) { return nullptr; } SamplerBinding *result = ojkAllocArray(destHeap, count); - if ( numBindings ) - { + if (numBindings) { *numBindings = count; } - memcpy(result, scratch, sizeof(SamplerBinding)*count); + memcpy(result, scratch, sizeof(SamplerBinding) * count); failed = false; count = 0; return result; } -struct Pass -{ +struct Pass { int maxDrawItems; int numDrawItems; DrawItem *drawItems; uint32_t *sortKeys; }; -static void RB_BindTextures( size_t numBindings, const SamplerBinding *bindings ) -{ - for ( size_t i = 0; i < numBindings; ++i ) - { - const SamplerBinding& binding = bindings[i]; - if ( binding.videoMapHandle ) - { +static void RB_BindTextures(size_t numBindings, const SamplerBinding *bindings) { + for (size_t i = 0; i < numBindings; ++i) { + const SamplerBinding &binding = bindings[i]; + if (binding.videoMapHandle) { int oldtmu = glState.currenttmu; GL_SelectTexture(binding.slot); ri.CIN_RunCinematic(binding.videoMapHandle - 1); ri.CIN_UploadCinematic(binding.videoMapHandle - 1); GL_SelectTexture(oldtmu); - } - else - { + } else { GL_BindToTMU(binding.image, binding.slot); } } } -static void RB_BindUniformBlocks( - size_t numBindings, - const UniformBlockBinding *bindings) -{ - for (size_t i = 0; i < numBindings; ++i) - { - const UniformBlockBinding& binding = bindings[i]; +static void RB_BindUniformBlocks(size_t numBindings, const UniformBlockBinding *bindings) { + for (size_t i = 0; i < numBindings; ++i) { + const UniformBlockBinding &binding = bindings[i]; if (binding.offset < 0) RB_BindUniformBlock(binding.ubo, binding.block, 0); else @@ -1024,32 +818,21 @@ static void RB_BindUniformBlocks( } } -static void RB_SetRenderState(const RenderState& renderState) -{ +static void RB_SetRenderState(const RenderState &renderState) { GL_Cull(renderState.cullType); GL_State(renderState.stateBits); - GL_DepthRange( - renderState.depthRange.minDepth, - renderState.depthRange.maxDepth); + GL_DepthRange(renderState.depthRange.minDepth, renderState.depthRange.maxDepth); - if (renderState.transformFeedback) - { + if (renderState.transformFeedback) { qglEnable(GL_RASTERIZER_DISCARD); qglBeginTransformFeedback(GL_POINTS); } } -static void RB_BindTransformFeedbackBuffer(const bufferBinding_t& binding) -{ - if (memcmp(&glState.currentXFBBO, &binding, sizeof(binding)) != 0) - { +static void RB_BindTransformFeedbackBuffer(const bufferBinding_t &binding) { + if (memcmp(&glState.currentXFBBO, &binding, sizeof(binding)) != 0) { if (binding.buffer != 0) - qglBindBufferRange( - GL_TRANSFORM_FEEDBACK_BUFFER, - 0, - binding.buffer, - binding.offset, - binding.size); + qglBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, binding.buffer, binding.offset, binding.size); else qglBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0); @@ -1057,14 +840,9 @@ static void RB_BindTransformFeedbackBuffer(const bufferBinding_t& binding) } } -static void RB_DrawItems( - int numDrawItems, - const DrawItem *drawItems, - uint32_t *drawOrder) -{ - for ( int i = 0; i < numDrawItems; ++i ) - { - const DrawItem& drawItem = drawItems[drawOrder[i]]; +static void RB_DrawItems(int numDrawItems, const DrawItem *drawItems, uint32_t *drawOrder) { + for (int i = 0; i < numDrawItems; ++i) { + const DrawItem &drawItem = drawItems[drawOrder[i]]; if (drawItem.ibo != nullptr) R_BindIBO(drawItem.ibo); @@ -1073,85 +851,61 @@ static void RB_DrawItems( GL_VertexAttribPointers(drawItem.numAttributes, drawItem.attributes); RB_BindTextures(drawItem.numSamplerBindings, drawItem.samplerBindings); - RB_BindUniformBlocks( - drawItem.numUniformBlockBindings, - drawItem.uniformBlockBindings); + RB_BindUniformBlocks(drawItem.numUniformBlockBindings, drawItem.uniformBlockBindings); RB_BindTransformFeedbackBuffer(drawItem.transformFeedbackBuffer); GLSL_SetUniforms(drawItem.program, drawItem.uniformData); RB_SetRenderState(drawItem.renderState); - switch ( drawItem.draw.type ) - { - case DRAW_COMMAND_MULTI_INDEXED: - { - GL_MultiDrawIndexed(drawItem.draw.primitiveType, - drawItem.draw.params.multiIndexed.numIndices, - drawItem.draw.params.multiIndexed.firstIndices, - drawItem.draw.params.multiIndexed.numDraws); - break; - } + switch (drawItem.draw.type) { + case DRAW_COMMAND_MULTI_INDEXED: { + GL_MultiDrawIndexed(drawItem.draw.primitiveType, drawItem.draw.params.multiIndexed.numIndices, drawItem.draw.params.multiIndexed.firstIndices, + drawItem.draw.params.multiIndexed.numDraws); + break; + } - case DRAW_COMMAND_INDEXED: - { - GL_DrawIndexed(drawItem.draw.primitiveType, - drawItem.draw.params.indexed.numIndices, - drawItem.draw.params.indexed.indexType, - drawItem.draw.params.indexed.firstIndex, - drawItem.draw.numInstances, - drawItem.draw.params.indexed.baseVertex); - break; - } + case DRAW_COMMAND_INDEXED: { + GL_DrawIndexed(drawItem.draw.primitiveType, drawItem.draw.params.indexed.numIndices, drawItem.draw.params.indexed.indexType, + drawItem.draw.params.indexed.firstIndex, drawItem.draw.numInstances, drawItem.draw.params.indexed.baseVertex); + break; + } - case DRAW_COMMAND_ARRAYS: - { - GL_Draw( - drawItem.draw.primitiveType, - drawItem.draw.params.arrays.firstVertex, - drawItem.draw.params.arrays.numVertices, - drawItem.draw.numInstances); - break; - } + case DRAW_COMMAND_ARRAYS: { + GL_Draw(drawItem.draw.primitiveType, drawItem.draw.params.arrays.firstVertex, drawItem.draw.params.arrays.numVertices, drawItem.draw.numInstances); + break; + } - default: - { - assert(!"Invalid or unhandled draw type"); - break; - } + default: { + assert(!"Invalid or unhandled draw type"); + break; + } } - if (drawItem.renderState.transformFeedback) - { + if (drawItem.renderState.transformFeedback) { qglEndTransformFeedback(); qglDisable(GL_RASTERIZER_DISCARD); } } } -void RB_AddDrawItem( Pass *pass, uint32_t sortKey, const DrawItem& drawItem ) -{ +void RB_AddDrawItem(Pass *pass, uint32_t sortKey, const DrawItem &drawItem) { // There will be no pass if we are drawing a 2D object. - if ( pass ) - { - if ( pass->numDrawItems >= pass->maxDrawItems ) - { + if (pass) { + if (pass->numDrawItems >= pass->maxDrawItems) { assert(!"Ran out of space for pass"); return; } pass->sortKeys[pass->numDrawItems] = sortKey; pass->drawItems[pass->numDrawItems++] = drawItem; - } - else - { + } else { uint32_t drawOrder[] = {0}; RB_DrawItems(1, &drawItem, drawOrder); } } -static Pass *RB_CreatePass( Allocator& allocator, int capacity ) -{ +static Pass *RB_CreatePass(Allocator &allocator, int capacity) { Pass *pass = ojkAlloc(*backEndData->perFrameMemory); *pass = {}; pass->maxDrawItems = capacity; @@ -1160,16 +914,12 @@ static Pass *RB_CreatePass( Allocator& allocator, int capacity ) return pass; } -static void RB_PrepareForEntity( int entityNum, float originalTime ) -{ - if ( entityNum != REFENTITYNUM_WORLD ) - { +static void RB_PrepareForEntity(int entityNum, float originalTime) { + if (entityNum != REFENTITYNUM_WORLD) { backEnd.currentEntity = &backEnd.refdef.entities[entityNum]; backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; - } - else - { + } else { backEnd.currentEntity = &tr.worldEntity; backEnd.refdef.floatTime = originalTime; @@ -1180,11 +930,7 @@ static void RB_PrepareForEntity( int entityNum, float originalTime ) tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; } -static void RB_SubmitDrawSurfsForDepthFill( - drawSurf_t *drawSurfs, - int numDrawSurfs, - float originalTime ) -{ +static void RB_SubmitDrawSurfsForDepthFill(drawSurf_t *drawSurfs, int numDrawSurfs, float originalTime) { shader_t *oldShader = nullptr; int oldEntityNum = -1; int oldSort = -1; @@ -1192,8 +938,7 @@ static void RB_SubmitDrawSurfsForDepthFill( CBoneCache *oldBoneCache = nullptr; drawSurf_t *drawSurf = drawSurfs; - for ( int i = 0; i < numDrawSurfs; i++, drawSurf++ ) - { + for (int i = 0; i < numDrawSurfs; i++, drawSurf++) { shader_t *shader; int cubemapIndex; int postRender; @@ -1205,25 +950,21 @@ static void RB_SubmitDrawSurfsForDepthFill( if (shader->useSimpleDepthShader == qtrue) shader = tr.defaultShader; - if (shader->sort != SS_OPAQUE || shader->useDistortion) - { + if (shader->sort != SS_OPAQUE || shader->useDistortion) { // Don't draw yet, let's see what's to come continue; } - if (*drawSurf->surface == SF_MDX) - { - if (((CRenderableSurface*)drawSurf->surface)->boneCache != oldBoneCache) - { + if (*drawSurf->surface == SF_MDX) { + if (((CRenderableSurface *)drawSurf->surface)->boneCache != oldBoneCache) { RB_EndSurface(); RB_BeginSurface(shader, 0, 0); - oldBoneCache = ((CRenderableSurface*)drawSurf->surface)->boneCache; - tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface*)drawSurf->surface); + oldBoneCache = ((CRenderableSurface *)drawSurf->surface)->boneCache; + tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface *)drawSurf->surface); } } - if ( shader == oldShader && entityNum == oldEntityNum ) - { + if (shader == oldShader && entityNum == oldEntityNum) { // fast path, same as previous sort rb_surfaceTable[*drawSurf->surface](drawSurf->surface); continue; @@ -1233,11 +974,8 @@ static void RB_SubmitDrawSurfsForDepthFill( // a "entityMergable" shader is a shader that can have surfaces from // seperate entities merged into a single batch, like smoke and blood // puff sprites - if ( shader != oldShader || - (entityNum != oldEntityNum && !shader->entityMergable) ) - { - if ( oldShader != nullptr ) - { + if (shader != oldShader || (entityNum != oldEntityNum && !shader->entityMergable)) { + if (oldShader != nullptr) { RB_EndSurface(); } @@ -1249,8 +987,7 @@ static void RB_SubmitDrawSurfsForDepthFill( oldSort = drawSurf->sort; // change the modelview matrix if needed - if ( entityNum != oldEntityNum ) - { + if (entityNum != oldEntityNum) { RB_PrepareForEntity(entityNum, originalTime); oldEntityNum = entityNum; } @@ -1261,17 +998,12 @@ static void RB_SubmitDrawSurfsForDepthFill( } // draw the contents of the last shader batch - if ( oldShader != nullptr ) - { + if (oldShader != nullptr) { RB_EndSurface(); } } -static void RB_SubmitDrawSurfs( - drawSurf_t *drawSurfs, - int numDrawSurfs, - float originalTime ) -{ +static void RB_SubmitDrawSurfs(drawSurf_t *drawSurfs, int numDrawSurfs, float originalTime) { shader_t *oldShader = nullptr; int oldEntityNum = -1; int oldSort = -1; @@ -1283,8 +1015,7 @@ static void RB_SubmitDrawSurfs( CBoneCache *oldBoneCache = nullptr; drawSurf_t *drawSurf = drawSurfs; - for ( int i = 0; i < numDrawSurfs; i++, drawSurf++ ) - { + for (int i = 0; i < numDrawSurfs; i++, drawSurf++) { shader_t *shader; int cubemapIndex; int postRender; @@ -1297,25 +1028,17 @@ static void RB_SubmitDrawSurfs( fogNum = drawSurf->fogIndex; dlighted = drawSurf->dlightBits; - if (*drawSurf->surface == SF_MDX) - { - if (((CRenderableSurface*)drawSurf->surface)->boneCache != oldBoneCache) - { + if (*drawSurf->surface == SF_MDX) { + if (((CRenderableSurface *)drawSurf->surface)->boneCache != oldBoneCache) { RB_EndSurface(); RB_BeginSurface(shader, fogNum, cubemapIndex); - oldBoneCache = ((CRenderableSurface*)drawSurf->surface)->boneCache; - tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface*)drawSurf->surface); + oldBoneCache = ((CRenderableSurface *)drawSurf->surface)->boneCache; + tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface *)drawSurf->surface); } } - if ( shader == oldShader && - fogNum == oldFogNum && - postRender == oldPostRender && - cubemapIndex == oldCubemapIndex && - entityNum == oldEntityNum && - dlighted == oldDlighted && - backEnd.refractionFill == shader->useDistortion ) - { + if (shader == oldShader && fogNum == oldFogNum && postRender == oldPostRender && cubemapIndex == oldCubemapIndex && entityNum == oldEntityNum && + dlighted == oldDlighted && backEnd.refractionFill == shader->useDistortion) { // fast path, same as previous sort rb_surfaceTable[*drawSurf->surface](drawSurf->surface); continue; @@ -1327,15 +1050,9 @@ static void RB_SubmitDrawSurfs( // change the tess parameters if needed // a "entityMergable" shader is a shader that can have surfaces from seperate // entities merged into a single batch, like smoke and blood puff sprites - if ( (shader != oldShader || - fogNum != oldFogNum || - dlighted != oldDlighted || - postRender != oldPostRender || - cubemapIndex != oldCubemapIndex || - (entityNum != oldEntityNum && !shader->entityMergable)) ) - { - if ( oldShader != nullptr ) - { + if ((shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted || postRender != oldPostRender || cubemapIndex != oldCubemapIndex || + (entityNum != oldEntityNum && !shader->entityMergable))) { + if (oldShader != nullptr) { RB_EndSurface(); } @@ -1348,14 +1065,13 @@ static void RB_SubmitDrawSurfs( oldCubemapIndex = cubemapIndex; } - if ( entityNum != oldEntityNum ) - { + if (entityNum != oldEntityNum) { RB_PrepareForEntity(entityNum, originalTime); oldEntityNum = entityNum; } - qboolean isDistortionShader = (qboolean) - ((shader->useDistortion == qtrue) || (backEnd.currentEntity && backEnd.currentEntity->e.renderfx & RF_DISTORTION)); + qboolean isDistortionShader = + (qboolean)((shader->useDistortion == qtrue) || (backEnd.currentEntity && backEnd.currentEntity->e.renderfx & RF_DISTORTION)); if (backEnd.refractionFill != isDistortionShader) continue; @@ -1369,28 +1085,20 @@ static void RB_SubmitDrawSurfs( } // draw the contents of the last shader batch - if ( oldShader != nullptr ) - { + if (oldShader != nullptr) { RB_EndSurface(); } } -static void RB_SubmitRenderPass( - Pass& renderPass, - Allocator& allocator ) -{ - uint32_t *drawOrder = ojkAllocArray( - allocator, renderPass.numDrawItems); +static void RB_SubmitRenderPass(Pass &renderPass, Allocator &allocator) { + uint32_t *drawOrder = ojkAllocArray(allocator, renderPass.numDrawItems); uint32_t numDrawItems = renderPass.numDrawItems; - for ( uint32_t i = 0; i < numDrawItems; ++i ) + for (uint32_t i = 0; i < numDrawItems; ++i) drawOrder[i] = i; uint32_t *sortKeys = renderPass.sortKeys; - std::sort(drawOrder, drawOrder + numDrawItems, [sortKeys]( uint32_t a, uint32_t b ) - { - return sortKeys[a] < sortKeys[b]; - }); + std::sort(drawOrder, drawOrder + numDrawItems, [sortKeys](uint32_t a, uint32_t b) { return sortKeys[a] < sortKeys[b]; }); RB_DrawItems(renderPass.numDrawItems, renderPass.drawItems, drawOrder); } @@ -1400,8 +1108,7 @@ static void RB_SubmitRenderPass( RB_RenderDrawSurfList ================== */ -static void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) -{ +static void RB_RenderDrawSurfList(drawSurf_t *drawSurfs, int numDrawSurfs) { /* merging surfaces together that share the same shader (e.g. polys, patches) upload per frame data - but this might be the same between render passes? @@ -1437,8 +1144,7 @@ static void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) // Prepare memory for the current render pass void *allocMark = backEndData->perFrameMemory->Mark(); assert(backEndData->currentPass == nullptr); - backEndData->currentPass = RB_CreatePass( - *backEndData->perFrameMemory, numDrawSurfs * estimatedNumShaderStages); + backEndData->currentPass = RB_CreatePass(*backEndData->perFrameMemory, numDrawSurfs * estimatedNumShaderStages); // save original time for entity shader offsets float originalTime = backEnd.refdef.floatTime; @@ -1447,19 +1153,14 @@ static void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) backEnd.currentEntity = &tr.worldEntity; backEnd.pc.c_surfaces += numDrawSurfs; - if ( backEnd.depthFill ) - { + if (backEnd.depthFill) { RB_SubmitDrawSurfsForDepthFill(drawSurfs, numDrawSurfs, originalTime); - } - else - { + } else { RB_SubmitDrawSurfs(drawSurfs, numDrawSurfs, originalTime); } // Do the drawing and release memory - RB_SubmitRenderPass( - *backEndData->currentPass, - *backEndData->perFrameMemory); + RB_SubmitRenderPass(*backEndData->currentPass, *backEndData->perFrameMemory); backEndData->perFrameMemory->ResetTo(allocMark); backEndData->currentPass = nullptr; @@ -1470,7 +1171,6 @@ static void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) GL_SetModelviewMatrix(backEnd.viewParms.world.modelViewMatrix); } - /* ============================================================================ @@ -1485,7 +1185,7 @@ RB_SetGL2D ================ */ -void RB_SetGL2D (void) { +void RB_SetGL2D(void) { matrix_t matrix; int width, height; @@ -1495,29 +1195,24 @@ void RB_SetGL2D (void) { backEnd.projection2D = qtrue; backEnd.last2DFBO = glState.currentFBO; - if (glState.currentFBO) - { + if (glState.currentFBO) { width = glState.currentFBO->width; height = glState.currentFBO->height; - } - else - { + } else { width = glConfig.vidWidth; height = glConfig.vidHeight; } // set 2D virtual screen size - qglViewport( 0, 0, width, height ); - qglScissor( 0, 0, width, height ); + qglViewport(0, 0, width, height); + qglScissor(0, 0, width, height); Matrix16Ortho(0, 640, 480, 0, 0, 1, matrix); GL_SetProjectionMatrix(matrix); Matrix16Identity(matrix); GL_SetModelviewMatrix(matrix); - GL_State( GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); GL_Cull(CT_TWO_SIDED); @@ -1529,7 +1224,6 @@ void RB_SetGL2D (void) { backEnd.refdef.colorScale = 1.0f; } - /* ============= RE_StretchRaw @@ -1539,18 +1233,18 @@ Stretches a raw 32 bit power of 2 bitmap image over the given screen rectangle. Used for cinematics. ============= */ -void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) { - int i, j; - int start, end; +void RE_StretchRaw(int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) { + int i, j; + int start, end; vec4_t quadVerts[4]; vec2_t texCoords[4]; - if ( !tr.registered ) { + if (!tr.registered) { return; } R_IssuePendingRenderCommands(); - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } @@ -1558,87 +1252,83 @@ void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte * qglFinish(); start = 0; - if ( r_speeds->integer ) { + if (r_speeds->integer) { start = ri.Milliseconds(); } // make sure rows and cols are powers of 2 - for ( i = 0 ; ( 1 << i ) < cols ; i++ ) { + for (i = 0; (1 << i) < cols; i++) { } - for ( j = 0 ; ( 1 << j ) < rows ; j++ ) { + for (j = 0; (1 << j) < rows; j++) { } - if ( ( 1 << i ) != cols || ( 1 << j ) != rows) { - ri.Error (ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); + if ((1 << i) != cols || (1 << j) != rows) { + ri.Error(ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); } - RE_UploadCinematic (cols, rows, data, client, dirty); + RE_UploadCinematic(cols, rows, data, client, dirty); - if ( r_speeds->integer ) { + if (r_speeds->integer) { end = ri.Milliseconds(); - ri.Printf( PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start ); + ri.Printf(PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start); } // FIXME: HUGE hack - if (!tr.renderFbo || backEnd.framePostProcessed) - { + if (!tr.renderFbo || backEnd.framePostProcessed) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } RB_SetGL2D(); - VectorSet4(quadVerts[0], x, y, 0.0f, 1.0f); - VectorSet4(quadVerts[1], x + w, y, 0.0f, 1.0f); + VectorSet4(quadVerts[0], x, y, 0.0f, 1.0f); + VectorSet4(quadVerts[1], x + w, y, 0.0f, 1.0f); VectorSet4(quadVerts[2], x + w, y + h, 0.0f, 1.0f); - VectorSet4(quadVerts[3], x, y + h, 0.0f, 1.0f); + VectorSet4(quadVerts[3], x, y + h, 0.0f, 1.0f); - VectorSet2(texCoords[0], 0.5f / cols, 0.5f / rows); + VectorSet2(texCoords[0], 0.5f / cols, 0.5f / rows); VectorSet2(texCoords[1], (cols - 0.5f) / cols, 0.5f / rows); VectorSet2(texCoords[2], (cols - 0.5f) / cols, (rows - 0.5f) / rows); - VectorSet2(texCoords[3], 0.5f / cols, (rows - 0.5f) / rows); + VectorSet2(texCoords[3], 0.5f / cols, (rows - 0.5f) / rows); GLSL_BindProgram(&tr.textureColorShader); - + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); GLSL_SetUniformVec4(&tr.textureColorShader, UNIFORM_COLOR, colorWhite); RB_InstantQuad2(quadVerts, texCoords); } -void RE_UploadCinematic (int cols, int rows, const byte *data, int client, qboolean dirty) { +void RE_UploadCinematic(int cols, int rows, const byte *data, int client, qboolean dirty) { - GL_Bind( tr.scratchImage[client] ); + GL_Bind(tr.scratchImage[client]); // if the scratchImage isn't in the format we want, specify it as a new texture - if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) { + if (cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height) { tr.scratchImage[client]->width = tr.scratchImage[client]->uploadWidth = cols; tr.scratchImage[client]->height = tr.scratchImage[client]->uploadHeight = rows; - qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { if (dirty) { // otherwise, just subimage upload it so that drivers can tell we are going to be changing // it and don't try and do a texture compression - qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data); } } } - /* ============= RB_SetColor ============= */ -static const void *RB_SetColor( const void *data ) { - const setColorCommand_t *cmd; +static const void *RB_SetColor(const void *data) { + const setColorCommand_t *cmd; cmd = (const setColorCommand_t *)data; @@ -1655,79 +1345,76 @@ static const void *RB_SetColor( const void *data ) { RB_StretchPic ============= */ -static const void *RB_StretchPic ( const void *data ) { - const stretchPicCommand_t *cmd; +static const void *RB_StretchPic(const void *data) { + const stretchPicCommand_t *cmd; shader_t *shader; cmd = (const stretchPicCommand_t *)data; // FIXME: HUGE hack - if (!tr.renderFbo || backEnd.framePostProcessed) - { + if (!tr.renderFbo || backEnd.framePostProcessed) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } RB_SetGL2D(); shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0, 0 ); + RB_BeginSurface(shader, 0, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1 ]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2 ]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 1]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 2]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 3]); - tess.xyz[ numVerts ][0] = cmd->x; - tess.xyz[ numVerts ][1] = cmd->y; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = cmd->x; + tess.xyz[numVerts][1] = cmd->y; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 1 ][1] = cmd->y; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 1][1] = cmd->y; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 2 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 2][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = cmd->x; - tess.xyz[ numVerts + 3 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = cmd->x; + tess.xyz[numVerts + 3][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } @@ -1737,90 +1424,82 @@ static const void *RB_StretchPic ( const void *data ) { RB_DrawRotatePic ============= */ -static const void *RB_RotatePic ( const void *data ) -{ - const rotatePicCommand_t *cmd; +static const void *RB_RotatePic(const void *data) { + const rotatePicCommand_t *cmd; shader_t *shader; cmd = (const rotatePicCommand_t *)data; // FIXME: HUGE hack - if (!tr.renderFbo || backEnd.framePostProcessed) - { + if (!tr.renderFbo || backEnd.framePostProcessed) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } RB_SetGL2D(); shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0, 0 ); + RB_BeginSurface(shader, 0, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd->a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x + cmd->w, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x + cmd->w, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 1]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 2]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 3]); - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[2][0]; + tess.xyz[numVerts + 1][1] = m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } @@ -1830,90 +1509,82 @@ static const void *RB_RotatePic ( const void *data ) RB_DrawRotatePic2 ============= */ -static const void *RB_RotatePic2 ( const void *data ) -{ - const rotatePicCommand_t *cmd; +static const void *RB_RotatePic2(const void *data) { + const rotatePicCommand_t *cmd; shader_t *shader; cmd = (const rotatePicCommand_t *)data; // FIXME: HUGE hack - if (!tr.renderFbo || backEnd.framePostProcessed) - { + if (!tr.renderFbo || backEnd.framePostProcessed) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } RB_SetGL2D(); shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0, 0 ); + RB_BeginSurface(shader, 0, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd->a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2]); - VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 1]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 2]); + VectorCopy4(backEnd.color2D, tess.vertexColors[numVerts + 3]); - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 1][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } @@ -1938,25 +1609,14 @@ static const void *RB_PrefilterEnvMap(const void *data) { qglGenerateMipmap(GL_TEXTURE_CUBE_MAP); qglBindTexture(GL_TEXTURE_CUBE_MAP, 0); - if (!cmd->cubemap->image) - { + if (!cmd->cubemap->image) { GLenum cubemapFormat = GL_RGBA8; - if (r_hdr->integer) - { + if (r_hdr->integer) { cubemapFormat = GL_RGBA16F; } // FIX ME: Only allocate needed mip level! - cmd->cubemap->image = R_CreateImage( - va("*cubeMap%d", cmd->cubemapId), - NULL, - CUBE_MAP_SIZE, - CUBE_MAP_SIZE, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE | - IMGFLAG_MIPMAP | - IMGFLAG_CUBEMAP, - cubemapFormat); + cmd->cubemap->image = R_CreateImage(va("*cubeMap%d", cmd->cubemapId), NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MIPMAP | IMGFLAG_CUBEMAP, cubemapFormat); } assert(cmd->cubemap->image); @@ -1964,8 +1624,7 @@ static const void *RB_PrefilterEnvMap(const void *data) { int height = cmd->cubemap->image->height; float roughnessMips = (float)CUBE_MAP_ROUGHNESS_MIPS; - for (int level = 0; level <= CUBE_MAP_ROUGHNESS_MIPS; level++) - { + for (int level = 0; level <= CUBE_MAP_ROUGHNESS_MIPS; level++) { FBO_Bind(tr.filterCubeFbo); qglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd->cubemap->image->texnum, level); GL_BindToTMU(tr.renderCubeImage, TB_CUBEMAP); @@ -1985,19 +1644,17 @@ static const void *RB_PrefilterEnvMap(const void *data) { return (const void *)(cmd + 1); } - -static void RB_RenderSSAO() -{ +static void RB_RenderSSAO() { const float zmax = backEnd.viewParms.zFar; const float zmin = r_znear->value; - const vec4_t viewInfo = { zmax / zmin, zmax, 0.0f, 0.0f }; + const vec4_t viewInfo = {zmax / zmin, zmax, 0.0f, 0.0f}; FBO_Bind(tr.quarterFbo[0]); qglViewport(0, 0, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height); qglScissor(0, 0, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height); - GL_State( GLS_DEPTHTEST_DISABLE ); + GL_State(GLS_DEPTHTEST_DISABLE); GLSL_BindProgram(&tr.ssaoShader); @@ -2013,7 +1670,7 @@ static void RB_RenderSSAO() GLSL_BindProgram(&tr.depthBlurShader[0]); - GL_BindToTMU(tr.quarterImage[0], TB_COLORMAP); + GL_BindToTMU(tr.quarterImage[0], TB_COLORMAP); GL_BindToTMU(tr.hdrDepthImage, TB_LIGHTMAP); GLSL_SetUniformVec4(&tr.depthBlurShader[0], UNIFORM_VIEWINFO, viewInfo); @@ -2026,85 +1683,55 @@ static void RB_RenderSSAO() GLSL_BindProgram(&tr.depthBlurShader[1]); - GL_BindToTMU(tr.quarterImage[1], TB_COLORMAP); + GL_BindToTMU(tr.quarterImage[1], TB_COLORMAP); GL_BindToTMU(tr.hdrDepthImage, TB_LIGHTMAP); GLSL_SetUniformVec4(&tr.depthBlurShader[1], UNIFORM_VIEWINFO, viewInfo); RB_InstantTriangle(); } -static void RB_RenderDepthOnly( drawSurf_t *drawSurfs, int numDrawSurfs ) -{ +static void RB_RenderDepthOnly(drawSurf_t *drawSurfs, int numDrawSurfs) { backEnd.depthFill = qtrue; qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); RB_RenderDrawSurfList(drawSurfs, numDrawSurfs); - qglColorMask( - !backEnd.colorMask[0], - !backEnd.colorMask[1], - !backEnd.colorMask[2], - !backEnd.colorMask[3]); + qglColorMask(!backEnd.colorMask[0], !backEnd.colorMask[1], !backEnd.colorMask[2], !backEnd.colorMask[3]); backEnd.depthFill = qfalse; // Only resolve the main pass depth - if (tr.msaaResolveFbo && backEnd.viewParms.targetFbo == tr.renderFbo) - { - FBO_FastBlit( - tr.renderFbo, NULL, - tr.msaaResolveFbo, NULL, - GL_DEPTH_BUFFER_BIT, - GL_NEAREST); - } - else if (tr.renderFbo == NULL) - { + if (tr.msaaResolveFbo && backEnd.viewParms.targetFbo == tr.renderFbo) { + FBO_FastBlit(tr.renderFbo, NULL, tr.msaaResolveFbo, NULL, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } else if (tr.renderFbo == NULL) { // If we're rendering directly to the screen, copy the depth to a texture GL_BindToTMU(tr.renderDepthImage, 0); - qglCopyTexImage2D( - GL_TEXTURE_2D, 0, - GL_DEPTH_COMPONENT24, 0, - 0, glConfig.vidWidth, - glConfig.vidHeight, 0); + qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 0, 0, glConfig.vidWidth, glConfig.vidHeight, 0); } - if (r_ssao->integer && - !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && - !(tr.viewParms.isSkyPortal)) - { + if (r_ssao->integer && !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && !(tr.viewParms.isSkyPortal)) { // need the depth in a texture we can do GL_LINEAR sampling on, so // copy it to an HDR image vec4i_t srcBox; VectorSet4(srcBox, 0, tr.renderDepthImage->height, tr.renderDepthImage->width, -tr.renderDepthImage->height); - FBO_BlitFromTexture( - tr.renderDepthImage, - srcBox, - nullptr, - tr.hdrDepthFbo, - nullptr, - nullptr, - nullptr, 0); + FBO_BlitFromTexture(tr.renderDepthImage, srcBox, nullptr, tr.hdrDepthFbo, nullptr, nullptr, nullptr, 0); } } -static void RB_RenderMainPass( drawSurf_t *drawSurfs, int numDrawSurfs ) -{ - if ( backEnd.viewParms.flags & VPF_DEPTHSHADOW ) - { +static void RB_RenderMainPass(drawSurf_t *drawSurfs, int numDrawSurfs) { + if (backEnd.viewParms.flags & VPF_DEPTHSHADOW) { return; } RB_RenderDrawSurfList(drawSurfs, numDrawSurfs); - if (r_drawSun->integer) - { + if (r_drawSun->integer) { RB_DrawSun(0.1, tr.sunShader); } - if (r_drawSunRays->integer) - { + if (r_drawSunRays->integer) { FBO_t *oldFbo = glState.currentFBO; FBO_Bind(tr.sunRaysFbo); - - qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); - qglClear( GL_COLOR_BUFFER_BIT ); + + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); + qglClear(GL_COLOR_BUFFER_BIT); tr.sunFlareQueryActive[tr.sunFlareQueryIndex] = qtrue; qglBeginQuery(GL_SAMPLES_PASSED, tr.sunFlareQuery[tr.sunFlareQueryIndex]); @@ -2122,31 +1749,24 @@ static void RB_RenderMainPass( drawSurf_t *drawSurfs, int numDrawSurfs ) RB_RenderFlares(); } -static void RB_RenderAllDepthRelatedPasses( drawSurf_t *drawSurfs, int numDrawSurfs ) -{ - if ( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) - { +static void RB_RenderAllDepthRelatedPasses(drawSurf_t *drawSurfs, int numDrawSurfs) { + if (backEnd.refdef.rdflags & RDF_NOWORLDMODEL) { return; } - if ( !r_depthPrepass->integer && !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) ) - { + if (!r_depthPrepass->integer && !(backEnd.viewParms.flags & VPF_DEPTHSHADOW)) { return; } FBO_t *oldFbo = glState.currentFBO; - if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) - { + if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) { qglEnable(GL_DEPTH_CLAMP); } RB_RenderDepthOnly(drawSurfs, numDrawSurfs); - if (r_ssao->integer && - !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && - !(tr.viewParms.isSkyPortal)) - { + if (r_ssao->integer && !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && !(tr.viewParms.isSkyPortal)) { RB_RenderSSAO(); } @@ -2154,16 +1774,13 @@ static void RB_RenderAllDepthRelatedPasses( drawSurf_t *drawSurfs, int numDrawSu FBO_Bind(oldFbo); SetViewportAndScissor(); - if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) - { + if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) { qglDisable(GL_DEPTH_CLAMP); } } -static void RB_UpdateCameraConstants(gpuFrame_t *frame) -{ - for (int i = 0; i < tr.numCachedViewParms; i++) - { +static void RB_UpdateCameraConstants(gpuFrame_t *frame) { + for (int i = 0; i < tr.numCachedViewParms; i++) { backEnd.viewParms = tr.cachedViewParms[i]; const float zmax = tr.cachedViewParms[i].zFar; const float zmin = tr.cachedViewParms[i].zNear; @@ -2182,23 +1799,18 @@ static void RB_UpdateCameraConstants(gpuFrame_t *frame) VectorScale(tr.cachedViewParms[i].ori.axis[2], ymax, viewBasis[2]); CameraBlock cameraBlock = {}; - Matrix16Multiply( - tr.cachedViewParms[i].projectionMatrix, - tr.cachedViewParms[i].world.modelViewMatrix, - cameraBlock.viewProjectionMatrix); + Matrix16Multiply(tr.cachedViewParms[i].projectionMatrix, tr.cachedViewParms[i].world.modelViewMatrix, cameraBlock.viewProjectionMatrix); VectorSet4(cameraBlock.viewInfo, zmax / zmin, zmax, 0.0f, 0.0f); VectorCopy(viewBasis[0], cameraBlock.viewForward); VectorCopy(viewBasis[1], cameraBlock.viewLeft); VectorCopy(viewBasis[2], cameraBlock.viewUp); VectorCopy(tr.cachedViewParms[i].ori.origin, cameraBlock.viewOrigin); - tr.cameraUboOffsets[tr.cachedViewParms[i].currentViewParm] = RB_AppendConstantsData( - frame, &cameraBlock, sizeof(cameraBlock)); + tr.cameraUboOffsets[tr.cachedViewParms[i].currentViewParm] = RB_AppendConstantsData(frame, &cameraBlock, sizeof(cameraBlock)); } } -static void RB_UpdateSceneConstants(gpuFrame_t *frame, const trRefdef_t *refdef) -{ +static void RB_UpdateSceneConstants(gpuFrame_t *frame, const trRefdef_t *refdef) { SceneBlock sceneBlock = {}; VectorCopy4(refdef->sunDir, sceneBlock.primaryLightOrigin); VectorCopy(refdef->sunAmbCol, sceneBlock.primaryLightAmbient); @@ -2210,12 +1822,10 @@ static void RB_UpdateSceneConstants(gpuFrame_t *frame, const trRefdef_t *refdef) sceneBlock.currentTime = refdef->floatTime; sceneBlock.frameTime = refdef->frameTime; - tr.sceneUboOffset = RB_AppendConstantsData( - frame, &sceneBlock, sizeof(sceneBlock)); + tr.sceneUboOffset = RB_AppendConstantsData(frame, &sceneBlock, sizeof(sceneBlock)); } -static void RB_UpdateLightsConstants(gpuFrame_t *frame, const trRefdef_t *refdef) -{ +static void RB_UpdateLightsConstants(gpuFrame_t *frame, const trRefdef_t *refdef) { LightsBlock lightsBlock = {}; memcpy(lightsBlock.shadowVP1, refdef->sunShadowMvp[0], sizeof(matrix_t)); @@ -2223,40 +1833,28 @@ static void RB_UpdateLightsConstants(gpuFrame_t *frame, const trRefdef_t *refdef memcpy(lightsBlock.shadowVP3, refdef->sunShadowMvp[2], sizeof(matrix_t)); lightsBlock.numLights = MIN(refdef->num_dlights, MAX_DLIGHTS); - for (int i = 0; i < lightsBlock.numLights; ++i) - { + for (int i = 0; i < lightsBlock.numLights; ++i) { const dlight_t *dlight = refdef->dlights + i; LightsBlock::Light *lightData = lightsBlock.lights + i; - VectorSet4( - lightData->origin, - dlight->origin[0], - dlight->origin[1], - dlight->origin[2], - 1.0f); + VectorSet4(lightData->origin, dlight->origin[0], dlight->origin[1], dlight->origin[2], 1.0f); VectorCopy(dlight->color, lightData->color); lightData->radius = dlight->radius; } // TODO: Add pshadow data - tr.lightsUboOffset = RB_AppendConstantsData( - frame, &lightsBlock, sizeof(lightsBlock)); + tr.lightsUboOffset = RB_AppendConstantsData(frame, &lightsBlock, sizeof(lightsBlock)); } -static void RB_UpdateFogsConstants(gpuFrame_t *frame) -{ +static void RB_UpdateFogsConstants(gpuFrame_t *frame) { FogsBlock fogsBlock = {}; - if (tr.world == nullptr) - { + if (tr.world == nullptr) { fogsBlock.numFogs = 0; - } - else - { + } else { fogsBlock.numFogs = tr.world->numfogs - 1; // Don't reserve fog 0 as 'null' } - for (int i = 0; i < fogsBlock.numFogs; ++i) - { + for (int i = 0; i < fogsBlock.numFogs; ++i) { const fog_t *fog = tr.world->fogs + i + 1; FogsBlock::Fog *fogData = fogsBlock.fogs + i; @@ -2266,14 +1864,10 @@ static void RB_UpdateFogsConstants(gpuFrame_t *frame) fogData->hasPlane = fog->hasSurface; } - tr.fogsUboOffset = RB_AppendConstantsData( - frame, &fogsBlock, sizeof(fogsBlock)); + tr.fogsUboOffset = RB_AppendConstantsData(frame, &fogsBlock, sizeof(fogsBlock)); } -static void RB_UpdateEntityLightConstants( - EntityBlock& entityBlock, - const trRefEntity_t *refEntity) -{ +static void RB_UpdateEntityLightConstants(EntityBlock &entityBlock, const trRefEntity_t *refEntity) { static const float normalizeFactor = 1.0f / 255.0f; VectorScale(refEntity->ambientLight, normalizeFactor, entityBlock.ambientLight); @@ -2284,8 +1878,7 @@ static void RB_UpdateEntityLightConstants( float lightRadius; VectorCopy(refEntity->modelLightDir, lightDir); lightRadius = 300.0f; - if (r_shadows->integer == 2) - { + if (r_shadows->integer == 2) { lightDir[2] = 0.0f; VectorNormalize(lightDir); VectorSet(lightDir, lightDir[0] * 0.3f, lightDir[1] * 0.3f, 1.0f); @@ -2297,20 +1890,14 @@ static void RB_UpdateEntityLightConstants( entityBlock.lightRadius = lightRadius; } -static void RB_UpdateEntityMatrixConstants( - EntityBlock& entityBlock, - const trRefEntity_t *refEntity) -{ +static void RB_UpdateEntityMatrixConstants(EntityBlock &entityBlock, const trRefEntity_t *refEntity) { orientationr_t ori; R_RotateForEntity(refEntity, &backEnd.viewParms, &ori); Matrix16Copy(ori.modelMatrix, entityBlock.modelMatrix); VectorCopy(ori.viewOrigin, entityBlock.localViewOrigin); } -static void RB_UpdateEntityModelConstants( - EntityBlock& entityBlock, - const trRefEntity_t *refEntity) -{ +static void RB_UpdateEntityModelConstants(EntityBlock &entityBlock, const trRefEntity_t *refEntity) { static const float normalizeFactor = 1.0f / 255.0f; entityBlock.fxVolumetricBase = -1.0f; @@ -2327,8 +1914,7 @@ static void RB_UpdateEntityModelConstants( entityBlock.entityTime = -refEntity->e.shaderTime; } -static void RB_UpdateSkyEntityConstants(gpuFrame_t *frame, const trRefdef_t *refdef) -{ +static void RB_UpdateSkyEntityConstants(gpuFrame_t *frame, const trRefdef_t *refdef) { EntityBlock skyEntityBlock = {}; skyEntityBlock.fxVolumetricBase = -1.0f; @@ -2336,18 +1922,12 @@ static void RB_UpdateSkyEntityConstants(gpuFrame_t *frame, const trRefdef_t *ref Matrix16Translation(tr.skyPortalParms.ori.origin, skyEntityBlock.modelMatrix); else Matrix16Translation(refdef->vieworg, skyEntityBlock.modelMatrix); - tr.skyEntityUboOffset = RB_AppendConstantsData( - frame, &skyEntityBlock, sizeof(skyEntityBlock)); + tr.skyEntityUboOffset = RB_AppendConstantsData(frame, &skyEntityBlock, sizeof(skyEntityBlock)); } static void ComputeDeformValues( - //const trRefEntity_t *refEntity, - const shader_t *shader, - deform_t *type, - genFunc_t *waveFunc, - vec4_t deformParams0, - vec4_t deformParams1) -{ + // const trRefEntity_t *refEntity, + const shader_t *shader, deform_t *type, genFunc_t *waveFunc, vec4_t deformParams0, vec4_t deformParams1) { // u_DeformGen *type = DEFORM_NONE; *waveFunc = GF_NONE; @@ -2359,13 +1939,11 @@ static void ComputeDeformValues( return; }*/ - if (!ShaderRequiresCPUDeforms(shader)) - { + if (!ShaderRequiresCPUDeforms(shader)) { // only support the first one - const deformStage_t *ds = &shader->deforms[0]; + const deformStage_t *ds = &shader->deforms[0]; - switch (ds->deformation) - { + switch (ds->deformation) { case DEFORM_WAVE: *type = DEFORM_WAVE; *waveFunc = ds->deformationWave.func; @@ -2384,8 +1962,8 @@ static void ComputeDeformValues( deformParams0[0] = 0.0f; deformParams0[1] = ds->bulgeHeight; // amplitude - deformParams0[2] = ds->bulgeWidth; // phase - deformParams0[3] = ds->bulgeSpeed; // frequency + deformParams0[2] = ds->bulgeWidth; // phase + deformParams0[3] = ds->bulgeSpeed; // frequency deformParams1[0] = 0.0f; deformParams1[1] = 0.0f; deformParams1[2] = 0.0f; @@ -2414,8 +1992,8 @@ static void ComputeDeformValues( deformParams0[0] = 0.0f; deformParams0[1] = ds->deformationWave.amplitude; // amplitude - deformParams0[2] = 0.0f; // phase - deformParams0[3] = ds->deformationWave.frequency; // frequency + deformParams0[2] = 0.0f; // phase + deformParams0[3] = ds->deformationWave.frequency; // frequency deformParams1[0] = 0.0f; deformParams1[1] = 0.0f; deformParams1[2] = 0.0f; @@ -2446,33 +2024,24 @@ static void ComputeDeformValues( } } -void RB_AddShaderToShaderInstanceUBO(shader_t *shader) -{ - if (shader->numDeforms != 1 && !shader->portalRange) - { +void RB_AddShaderToShaderInstanceUBO(shader_t *shader) { + if (shader->numDeforms != 1 && !shader->portalRange) { shader->ShaderInstanceUboOffset = -1; return; } - + ShaderInstanceBlock shaderInstanceBlock = {}; - ComputeDeformValues( - shader, - (deform_t *)&shaderInstanceBlock.deformType, - (genFunc_t *)&shaderInstanceBlock.deformFunc, - shaderInstanceBlock.deformParams0, - shaderInstanceBlock.deformParams1); + ComputeDeformValues(shader, (deform_t *)&shaderInstanceBlock.deformType, (genFunc_t *)&shaderInstanceBlock.deformFunc, shaderInstanceBlock.deformParams0, + shaderInstanceBlock.deformParams1); shaderInstanceBlock.portalRange = shader->portalRange; shaderInstanceBlock.time = -shader->timeOffset; - shader->ShaderInstanceUboOffset = RB_AddShaderInstanceBlock((void*)&shaderInstanceBlock); + shader->ShaderInstanceUboOffset = RB_AddShaderInstanceBlock((void *)&shaderInstanceBlock); } -static void RB_UpdateEntityConstants( - gpuFrame_t *frame, const trRefdef_t *refdef) -{ +static void RB_UpdateEntityConstants(gpuFrame_t *frame, const trRefdef_t *refdef) { memset(tr.entityUboOffsets, 0, sizeof(tr.entityUboOffsets)); - for (int i = 0; i < refdef->num_entities; i++) - { + for (int i = 0; i < refdef->num_entities; i++) { trRefEntity_t *ent = &refdef->entities[i]; R_SetupEntityLighting(refdef, ent); @@ -2482,8 +2051,7 @@ static void RB_UpdateEntityConstants( RB_UpdateEntityMatrixConstants(entityBlock, ent); RB_UpdateEntityModelConstants(entityBlock, ent); - tr.entityUboOffsets[i] = RB_AppendConstantsData( - frame, &entityBlock, sizeof(entityBlock)); + tr.entityUboOffsets[i] = RB_AppendConstantsData(frame, &entityBlock, sizeof(entityBlock)); } const trRefEntity_t *ent = &tr.worldEntity; @@ -2492,16 +2060,13 @@ static void RB_UpdateEntityConstants( RB_UpdateEntityMatrixConstants(entityBlock, ent); RB_UpdateEntityModelConstants(entityBlock, ent); - tr.entityUboOffsets[REFENTITYNUM_WORLD] = RB_AppendConstantsData( - frame, &entityBlock, sizeof(entityBlock)); + tr.entityUboOffsets[REFENTITYNUM_WORLD] = RB_AppendConstantsData(frame, &entityBlock, sizeof(entityBlock)); RB_UpdateSkyEntityConstants(frame, refdef); } -static void RB_UpdateGhoul2Constants(gpuFrame_t *frame, const trRefdef_t *refdef) -{ - for (int i = 0; i < refdef->num_entities; i++) - { +static void RB_UpdateGhoul2Constants(gpuFrame_t *frame, const trRefdef_t *refdef) { + for (int i = 0; i < refdef->num_entities; i++) { const trRefEntity_t *ent = &refdef->entities[i]; if (ent->e.reType != RT_MODEL) continue; @@ -2510,15 +2075,12 @@ static void RB_UpdateGhoul2Constants(gpuFrame_t *frame, const trRefdef_t *refdef if (!model) continue; - switch (model->type) - { + switch (model->type) { case MOD_MDXM: - case MOD_BAD: - { + case MOD_BAD: { // Transform Bones and upload them RB_TransformBones(ent, refdef, backEndData->realFrameNumber, frame); - } - break; + } break; default: break; @@ -2526,8 +2088,7 @@ static void RB_UpdateGhoul2Constants(gpuFrame_t *frame, const trRefdef_t *refdef } } -void RB_UpdateConstants(const trRefdef_t *refdef) -{ +void RB_UpdateConstants(const trRefdef_t *refdef) { gpuFrame_t *frame = backEndData->currentFrame; RB_BeginConstantsUpdate(frame); @@ -2547,13 +2108,13 @@ RB_DrawBuffer ============= */ -static const void *RB_DrawBuffer( const void *data ) { - const drawBufferCommand_t *cmd; +static const void *RB_DrawBuffer(const void *data) { + const drawBufferCommand_t *cmd; cmd = (const drawBufferCommand_t *)data; // finish any 2D drawing if needed - if(tess.numIndexes) + if (tess.numIndexes) RB_EndSurface(); return (const void *)(cmd + 1); @@ -2569,29 +2130,29 @@ was there. This is used to test for texture thrashing. Also called by RE_EndRegistration =============== */ -void RB_ShowImages( void ) { - int i; - image_t *image; - float x, y, w, h; - int start, end; +void RB_ShowImages(void) { + int i; + image_t *image; + float x, y, w, h; + int start, end; RB_SetGL2D(); - qglClear( GL_COLOR_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT); qglFinish(); start = ri.Milliseconds(); image = tr.images; - for ( i=0 ; i < tr.numImages; i++, image = image->poolNext ) { + for (i = 0; i < tr.numImages; i++, image = image->poolNext) { w = glConfig.vidWidth / 20; h = glConfig.vidHeight / 15; x = i % 20 * w; y = i / 20 * h; // show in proportional size in mode 2 - if ( r_showImages->integer == 2 ) { + if (r_showImages->integer == 2) { w *= image->uploadWidth / 512.0f; h *= image->uploadHeight / 512.0f; } @@ -2613,8 +2174,7 @@ void RB_ShowImages( void ) { qglFinish(); end = ri.Milliseconds(); - ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); - + ri.Printf(PRINT_ALL, "%i msec to draw all images\n", end - start); } /* @@ -2623,8 +2183,7 @@ RB_ColorMask ============= */ -static const void *RB_ColorMask(const void *data) -{ +static const void *RB_ColorMask(const void *data) { const colorMaskCommand_t *cmd = (colorMaskCommand_t *)data; // finish any 2D drawing if needed @@ -2637,7 +2196,7 @@ static const void *RB_ColorMask(const void *data) backEnd.colorMask[3] = (qboolean)(!cmd->rgba[3]); qglColorMask(cmd->rgba[0], cmd->rgba[1], cmd->rgba[2], cmd->rgba[3]); - + return (const void *)(cmd + 1); } @@ -2647,59 +2206,52 @@ RB_ClearDepth ============= */ -static const void *RB_ClearDepth(const void *data) -{ +static const void *RB_ClearDepth(const void *data) { const clearDepthCommand_t *cmd = (clearDepthCommand_t *)data; - + // finish any 2D drawing if needed - if(tess.numIndexes) + if (tess.numIndexes) RB_EndSurface(); // texture swapping test if (r_showImages->integer) RB_ShowImages(); - if (!tr.renderFbo || backEnd.framePostProcessed) - { + if (!tr.renderFbo || backEnd.framePostProcessed) { FBO_Bind(NULL); - } - else - { + } else { FBO_Bind(tr.renderFbo); } qglClear(GL_DEPTH_BUFFER_BIT); // if we're doing MSAA, clear the depth texture for the resolve buffer - if (tr.msaaResolveFbo) - { + if (tr.msaaResolveFbo) { FBO_Bind(tr.msaaResolveFbo); qglClear(GL_DEPTH_BUFFER_BIT); } - return (const void *)(cmd + 1); } - /* ============= RB_SwapBuffers ============= */ -static const void *RB_SwapBuffers( const void *data ) { - const swapBuffersCommand_t *cmd; +static const void *RB_SwapBuffers(const void *data) { + const swapBuffersCommand_t *cmd; // finish any 2D drawing if needed - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } ResetGhoul2RenderableSurfaceHeap(); // texture swapping test - if ( r_showImages->integer ) { + if (r_showImages->integer) { RB_ShowImages(); } @@ -2707,42 +2259,36 @@ static const void *RB_SwapBuffers( const void *data ) { // we measure overdraw by reading back the stencil buffer and // counting up the number of increments that have happened - if ( r_measureOverdraw->integer ) { + if (r_measureOverdraw->integer) { int i; long sum = 0; unsigned char *stencilReadback; - stencilReadback = (unsigned char *)ri.Hunk_AllocateTempMemory( glConfig.vidWidth * glConfig.vidHeight ); - qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback ); + stencilReadback = (unsigned char *)ri.Hunk_AllocateTempMemory(glConfig.vidWidth * glConfig.vidHeight); + qglReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback); - for ( i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++ ) { + for (i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++) { sum += stencilReadback[i]; } backEnd.pc.c_overDraw += sum; - ri.Hunk_FreeTempMemory( stencilReadback ); + ri.Hunk_FreeTempMemory(stencilReadback); } - if (!backEnd.framePostProcessed) - { - if (tr.msaaResolveFbo && r_hdr->integer) - { + if (!backEnd.framePostProcessed) { + if (tr.msaaResolveFbo && r_hdr->integer) { // Resolving an RGB16F MSAA FBO to the screen messes with the brightness, so resolve to an RGB16F FBO first FBO_FastBlit(tr.renderFbo, NULL, tr.msaaResolveFbo, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); FBO_FastBlit(tr.msaaResolveFbo, NULL, NULL, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); - } - else if (tr.renderFbo) - { + } else if (tr.renderFbo) { FBO_FastBlit(tr.renderFbo, NULL, NULL, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); } } - if ( tr.numFramesToCapture > 0 ) - { + if (tr.numFramesToCapture > 0) { tr.numFramesToCapture--; - if ( !tr.numFramesToCapture ) - { - ri.Printf( PRINT_ALL, "Frames captured\n" ); + if (!tr.numFramesToCapture) { + ri.Printf(PRINT_ALL, "Frames captured\n"); ri.FS_FCloseFile(tr.debugFile); tr.debugFile = 0; } @@ -2750,9 +2296,9 @@ static const void *RB_SwapBuffers( const void *data ) { R_NewFrameSync(); - GLimp_LogComment( "***************** RB_SwapBuffers *****************\n\n\n" ); + GLimp_LogComment("***************** RB_SwapBuffers *****************\n\n\n"); - ri.WIN_Present( &window ); + ri.WIN_Present(&window); return (const void *)(cmd + 1); } @@ -2763,33 +2309,29 @@ RB_PostProcess ============= */ -const void *RB_PostProcess(const void *data) -{ +const void *RB_PostProcess(const void *data) { const postProcessCommand_t *cmd = (const postProcessCommand_t *)data; FBO_t *srcFbo; vec4i_t srcBox, dstBox; qboolean autoExposure; // finish any 2D drawing if needed - if(tess.numIndexes) + if (tess.numIndexes) RB_EndSurface(); - if (cmd) - { + if (cmd) { backEnd.refdef = cmd->refdef; backEnd.viewParms = cmd->viewParms; } srcFbo = tr.renderFbo; - if (tr.msaaResolveFbo) - { + if (tr.msaaResolveFbo) { // Resolve the MSAA before anything else // Can't resolve just part of the MSAA FBO, so multiple views will suffer a performance hit here FBO_FastBlit(tr.renderFbo, NULL, tr.msaaResolveFbo, NULL, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); srcFbo = tr.msaaResolveFbo; - if ( r_dynamicGlow->integer ) - { + if (r_dynamicGlow->integer) { FBO_FastBlitIndexed(tr.renderFbo, tr.msaaResolveFbo, 1, 1, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); } } @@ -2819,14 +2361,13 @@ const void *RB_PostProcess(const void *data) } #endif - if (r_dynamicGlow->integer) - { + if (r_dynamicGlow->integer) { RB_BloomDownscale(tr.glowImage, tr.glowFboScaled[0]); int numPasses = Com_Clampi(1, ARRAY_LEN(tr.glowFboScaled), r_dynamicGlowPasses->integer); - for ( int i = 1; i < numPasses; i++ ) + for (int i = 1; i < numPasses; i++) RB_BloomDownscale(tr.glowFboScaled[i - 1], tr.glowFboScaled[i]); - for ( int i = numPasses - 2; i >= 0; i-- ) + for (int i = numPasses - 2; i >= 0; i--) RB_BloomUpscale(tr.glowFboScaled[i + 1], tr.glowFboScaled[i]); } srcBox[0] = backEnd.viewParms.viewportX; @@ -2834,24 +2375,16 @@ const void *RB_PostProcess(const void *data) srcBox[2] = backEnd.viewParms.viewportWidth; srcBox[3] = backEnd.viewParms.viewportHeight; - if (srcFbo) - { - if (r_hdr->integer && (r_toneMap->integer || r_forceToneMap->integer)) - { + if (srcFbo) { + if (r_hdr->integer && (r_toneMap->integer || r_forceToneMap->integer)) { autoExposure = (qboolean)(r_autoExposure->integer || r_forceAutoExposure->integer); RB_ToneMap(srcFbo, srcBox, NULL, dstBox, autoExposure); - } - else if (r_cameraExposure->value == 0.0f) - { + } else if (r_cameraExposure->value == 0.0f) { FBO_FastBlit(srcFbo, srcBox, NULL, dstBox, GL_COLOR_BUFFER_BIT, GL_NEAREST); - } - else - { + } else { vec4_t color; - color[0] = - color[1] = - color[2] = pow(2, r_cameraExposure->value); //exp2(r_cameraExposure->value); + color[0] = color[1] = color[2] = pow(2, r_cameraExposure->value); // exp2(r_cameraExposure->value); color[3] = 1.0f; FBO_Blit(srcFbo, srcBox, NULL, NULL, dstBox, NULL, color, 0); @@ -2869,13 +2402,11 @@ const void *RB_PostProcess(const void *data) RB_BokehBlur(NULL, srcBox, NULL, dstBox, backEnd.refdef.blurFactor); #endif - if (r_debugWeather->integer == 2) - { + if (r_debugWeather->integer == 2) { FBO_BlitFromTexture(tr.weatherDepthImage, NULL, NULL, NULL, nullptr, NULL, NULL, 0); } - if (0) - { + if (0) { vec4i_t dstBox; VectorSet4(dstBox, 256, glConfig.vidHeight - 256, 256, 256); FBO_BlitFromTexture(tr.renderDepthImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); @@ -2883,8 +2414,7 @@ const void *RB_PostProcess(const void *data) FBO_BlitFromTexture(tr.screenShadowImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); } - if (0 && r_ssao->integer) - { + if (0 && r_ssao->integer) { vec4i_t dstBox; VectorSet4(dstBox, 0, glConfig.vidHeight, 512, -512); FBO_BlitFromTexture(tr.screenSsaoImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); @@ -2894,8 +2424,7 @@ const void *RB_PostProcess(const void *data) FBO_BlitFromTexture(tr.quarterImage[1], NULL, NULL, NULL, dstBox, NULL, NULL, 0); } - if (0) - { + if (0) { vec4i_t dstBox; VectorSet4(dstBox, 256, glConfig.vidHeight - 256, 256, 256); FBO_BlitFromTexture(tr.sunRaysImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); @@ -2916,86 +2445,71 @@ const void *RB_PostProcess(const void *data) } #endif - if (r_dynamicGlow->integer != 0) - { + if (r_dynamicGlow->integer != 0) { // Composite the glow/bloom texture int blendFunc = 0; - vec4_t color = { 1.0f, 1.0f, 1.0f, 1.0f }; + vec4_t color = {1.0f, 1.0f, 1.0f, 1.0f}; - if ( r_dynamicGlow->integer == 2 ) - { + if (r_dynamicGlow->integer == 2) { // Debug output blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO; - } - else if ( r_dynamicGlowSoft->integer ) - { + } else if (r_dynamicGlowSoft->integer) { blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; color[0] = color[1] = color[2] = r_dynamicGlowIntensity->value; - } - else - { + } else { blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; color[0] = color[1] = color[2] = r_dynamicGlowIntensity->value; } - FBO_BlitFromTexture (tr.glowFboScaled[0]->colorImage[0], NULL, NULL, NULL, NULL, NULL, color, blendFunc); + FBO_BlitFromTexture(tr.glowFboScaled[0]->colorImage[0], NULL, NULL, NULL, NULL, NULL, color, blendFunc); } backEnd.framePostProcessed = qtrue; FBO_Bind(NULL); backEnd.refractionFill = qtrue; - RB_RenderDrawSurfList( - backEnd.refdef.drawSurfs + backEnd.refdef.fistDrawSurf, - backEnd.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); + RB_RenderDrawSurfList(backEnd.refdef.drawSurfs + backEnd.refdef.fistDrawSurf, backEnd.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); backEnd.refractionFill = qfalse; return (const void *)(cmd + 1); } -static const void *RB_BeginTimedBlock( const void *data ) -{ +static const void *RB_BeginTimedBlock(const void *data) { const beginTimedBlockCommand_t *cmd = (const beginTimedBlockCommand_t *)data; - if ( glRefConfig.timerQuery ) - { + if (glRefConfig.timerQuery) { gpuFrame_t *currentFrame = &backEndData->frames[backEndData->realFrameNumber % MAX_FRAMES]; gpuTimer_t *timer = currentFrame->timers + currentFrame->numTimers++; - if ( cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS ) - { + if (cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS) { gpuTimedBlock_t *timedBlock = currentFrame->timedBlocks + cmd->timerHandle; timedBlock->beginTimer = timer->queryName; timedBlock->name = cmd->name; currentFrame->numTimedBlocks++; - qglQueryCounter( timer->queryName, GL_TIMESTAMP ); + qglQueryCounter(timer->queryName, GL_TIMESTAMP); } } return (const void *)(cmd + 1); } -static const void *RB_EndTimedBlock( const void *data ) -{ +static const void *RB_EndTimedBlock(const void *data) { const endTimedBlockCommand_t *cmd = (const endTimedBlockCommand_t *)data; - if ( glRefConfig.timerQuery ) - { + if (glRefConfig.timerQuery) { gpuFrame_t *currentFrame = &backEndData->frames[backEndData->realFrameNumber % MAX_FRAMES]; gpuTimer_t *timer = currentFrame->timers + currentFrame->numTimers++; - if ( cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS ) - { + if (cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS) { gpuTimedBlock_t *timedBlock = currentFrame->timedBlocks + cmd->timerHandle; timedBlock->endTimer = timer->queryName; - qglQueryCounter( timer->queryName, GL_TIMESTAMP ); + qglQueryCounter(timer->queryName, GL_TIMESTAMP); } } return (const void *)(cmd + 1); } - /* ============= RB_DrawSurfs @@ -3003,7 +2517,7 @@ RB_DrawSurfs ============= */ static const void *RB_DrawSurfs(const void *data) { - const drawSurfsCommand_t *cmd; + const drawSurfsCommand_t *cmd; // finish any 2D drawing if needed if (tess.numIndexes) { @@ -3018,8 +2532,7 @@ static const void *RB_DrawSurfs(const void *data) { // clear the z buffer, set the modelview, etc RB_BeginDrawingView(); - if (cmd->numDrawSurfs > 0) - { + if (cmd->numDrawSurfs > 0) { RB_RenderAllDepthRelatedPasses(cmd->drawSurfs, cmd->numDrawSurfs); RB_RenderMainPass(cmd->drawSurfs, cmd->numDrawSurfs); @@ -3028,47 +2541,46 @@ static const void *RB_DrawSurfs(const void *data) { return (const void *)(cmd + 1); } - /* ==================== RB_ExecuteRenderCommands ==================== */ -void RB_ExecuteRenderCommands( const void *data ) { - int t1, t2; +void RB_ExecuteRenderCommands(const void *data) { + int t1, t2; - t1 = ri.Milliseconds (); + t1 = ri.Milliseconds(); - while ( 1 ) { + while (1) { data = PADP(data, sizeof(void *)); - switch ( *(const int *)data ) { + switch (*(const int *)data) { case RC_SET_COLOR: - data = RB_SetColor( data ); + data = RB_SetColor(data); break; case RC_STRETCH_PIC: - data = RB_StretchPic( data ); + data = RB_StretchPic(data); break; case RC_ROTATE_PIC: - data = RB_RotatePic( data ); + data = RB_RotatePic(data); break; case RC_ROTATE_PIC2: - data = RB_RotatePic2( data ); + data = RB_RotatePic2(data); break; case RC_DRAW_SURFS: - data = RB_DrawSurfs( data ); + data = RB_DrawSurfs(data); break; case RC_DRAW_BUFFER: - data = RB_DrawBuffer( data ); + data = RB_DrawBuffer(data); break; case RC_SWAP_BUFFERS: - data = RB_SwapBuffers( data ); + data = RB_SwapBuffers(data); break; case RC_SCREENSHOT: - data = RB_TakeScreenshotCmd( data ); + data = RB_TakeScreenshotCmd(data); break; case RC_VIDEOFRAME: - data = RB_TakeVideoFrameCmd( data ); + data = RB_TakeVideoFrameCmd(data); break; case RC_COLORMASK: data = RB_ColorMask(data); @@ -3077,7 +2589,7 @@ void RB_ExecuteRenderCommands( const void *data ) { data = RB_ClearDepth(data); break; case RC_CONVOLVECUBEMAP: - data = RB_PrefilterEnvMap( data ); + data = RB_PrefilterEnvMap(data); break; case RC_POSTPROCESS: data = RB_PostProcess(data); @@ -3091,15 +2603,13 @@ void RB_ExecuteRenderCommands( const void *data ) { case RC_END_OF_LIST: default: // finish any 2D drawing if needed - if(tess.numIndexes) + if (tess.numIndexes) RB_EndSurface(); // stop rendering - t2 = ri.Milliseconds (); + t2 = ri.Milliseconds(); backEnd.pc.msec = t2 - t1; return; } } - } - diff --git a/codemp/rd-rend2/tr_bsp.cpp b/codemp/rd-rend2/tr_bsp.cpp index 172174d318..02eb8b3084 100644 --- a/codemp/rd-rend2/tr_bsp.cpp +++ b/codemp/rd-rend2/tr_bsp.cpp @@ -43,28 +43,26 @@ void RE_LoadWorldMap( const char *name ); */ -static world_t s_worldData; -static byte *fileBase; +static world_t s_worldData; +static byte *fileBase; //=============================================================================== -static void HSVtoRGB( float h, float s, float v, float rgb[3] ) -{ +static void HSVtoRGB(float h, float s, float v, float rgb[3]) { int i; float f; float p, q, t; h *= 5; - i = floor( h ); + i = floor(h); f = h - i; - p = v * ( 1 - s ); - q = v * ( 1 - s * f ); - t = v * ( 1 - s * ( 1 - f ) ); + p = v * (1 - s); + q = v * (1 - s * f); + t = v * (1 - s * (1 - f)); - switch ( i ) - { + switch (i) { case 0: rgb[0] = v; rgb[1] = t; @@ -104,11 +102,11 @@ R_ColorShiftLightingBytes =============== */ -static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { - int shift, r, g, b; +static void R_ColorShiftLightingBytes(byte in[4], byte out[4]) { + int shift, r, g, b; // shift the color data based on overbright range - shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + shift = Q_max(0, r_mapOverBrightBits->integer - tr.overbrightBits); // shift the data based on overbright range r = in[0] << shift; @@ -116,8 +114,8 @@ static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { b = in[2] << shift; // normalize by color instead of saturating to white - if ( ( r | g | b ) > 255 ) { - int max; + if ((r | g | b) > 255) { + int max; max = r > g ? r : g; max = max > b ? max : b; @@ -132,15 +130,13 @@ static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { out[3] = in[3]; } - /* =============== R_ColorShiftLightingFloats =============== */ -static void R_ColorShiftLightingFloats(float in[4], float out[4], float scale, bool overbrightBits = true ) -{ +static void R_ColorShiftLightingFloats(float in[4], float out[4], float scale, bool overbrightBits = true) { float r, g, b; if (overbrightBits) @@ -150,10 +146,8 @@ static void R_ColorShiftLightingFloats(float in[4], float out[4], float scale, b g = in[1] * scale; b = in[2] * scale; - if (!glRefConfig.floatLightmap) - { - if (r > 1.0f || g > 1.0f || b > 1.0f) - { + if (!glRefConfig.floatLightmap) { + if (r > 1.0f || g > 1.0f || b > 1.0f) { float high = Q_max(Q_max(r, g), b); r /= high; @@ -168,8 +162,7 @@ static void R_ColorShiftLightingFloats(float in[4], float out[4], float scale, b out[3] = in[3]; } -void ColorToRGBA16F(const vec3_t color, unsigned short rgba16f[4]) -{ +void ColorToRGBA16F(const vec3_t color, unsigned short rgba16f[4]) { rgba16f[0] = FloatToHalf(color[0]); rgba16f[1] = FloatToHalf(color[1]); rgba16f[2] = FloatToHalf(color[2]); @@ -182,15 +175,15 @@ R_LoadLightmaps =============== */ -#define DEFAULT_LIGHTMAP_SIZE 128 +#define DEFAULT_LIGHTMAP_SIZE 128 #define MAX_LIGHTMAP_PAGES 2 -static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { - byte *buf, *buf_p; - dsurface_t *surf; - int len; - byte *image; - int imageSize; - int i, j, numLightmaps = 0, textureInternalFormat = 0; +static void R_LoadLightmaps(world_t *worldData, lump_t *l, lump_t *surfs) { + byte *buf, *buf_p; + dsurface_t *surf; + int len; + byte *image; + int imageSize; + int i, j, numLightmaps = 0, textureInternalFormat = 0; float maxIntensity = 0; double sumIntensity = 0; int numColorComponents = 3; @@ -204,18 +197,13 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { len = l->filelen; // test for external lightmaps if (!len) { - for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); - i < surfs->filelen / sizeof(dsurface_t); - i++, surf++) { - for (int j = 0; j < MAXLIGHTMAPS; j++) - { + for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); i < surfs->filelen / sizeof(dsurface_t); i++, surf++) { + for (int j = 0; j < MAXLIGHTMAPS; j++) { numLightmaps = MAX(numLightmaps, LittleLong(surf->lightmapNum[j]) + 1); } } buf = NULL; - } - else - { + } else { numLightmaps = len / (tr.lightmapSize * tr.lightmapSize * 3); buf = fileBase + l->fileofs; tr.worldInternalLightmapping = qtrue; @@ -225,16 +213,14 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { return; // test for hdr lighting - if (hdr_capable && tr.worldInternalLightmapping) - { + if (hdr_capable && tr.worldInternalLightmapping) { char filename[MAX_QPATH]; byte *externalLightmap = NULL; int lightmapWidth = tr.lightmapSize; int lightmapHeight = tr.lightmapSize; Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.hdr", worldData->baseName, 0); R_LoadHDRImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); - if (externalLightmap != NULL) - { + if (externalLightmap != NULL) { tr.worldInternalLightmapping = qfalse; ri.Hunk_FreeTempMemory(externalLightmap); } @@ -244,20 +230,14 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { R_IssuePendingRenderCommands(); // check for deluxe mapping - if (numLightmaps <= 1) - { + if (numLightmaps <= 1) { tr.worldDeluxeMapping = qfalse; - } - else - { + } else { tr.worldDeluxeMapping = qtrue; tr.worldInternalDeluxeMapping = qtrue; // Check that none of the deluxe maps are referenced by any of the map surfaces. - for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); - tr.worldDeluxeMapping && i < surfs->filelen / sizeof(dsurface_t); - i++, surf++) { - for (int j = 0; j < MAXLIGHTMAPS; j++) - { + for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); tr.worldDeluxeMapping && i < surfs->filelen / sizeof(dsurface_t); i++, surf++) { + for (int j = 0; j < MAXLIGHTMAPS; j++) { int lightmapNum = LittleLong(surf->lightmapNum[j]); if (lightmapNum >= 0 && (lightmapNum & 1) != 0) { @@ -277,8 +257,7 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { if (tr.worldDeluxeMapping) numLightmaps >>= 1; - if (tr.worldInternalLightmapping) - { + if (tr.worldInternalLightmapping) { const int targetLightmapsPerX = (int)ceilf(sqrtf(numLightmaps)); int lightmapsPerX = 1; @@ -293,17 +272,14 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { // FIXME: What happens if we need more? tr.numLightmaps = 1; - } - else - { + } else { tr.numLightmaps = numLightmaps; } - tr.lightmaps = (image_t **)ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low ); + tr.lightmaps = (image_t **)ri.Hunk_Alloc(tr.numLightmaps * sizeof(image_t *), h_low); - if (tr.worldDeluxeMapping) - { - tr.deluxemaps = (image_t **)ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low ); + if (tr.worldDeluxeMapping) { + tr.deluxemaps = (image_t **)ri.Hunk_Alloc(tr.numLightmaps * sizeof(image_t *), h_low); } if (hdr_capable) @@ -311,41 +287,24 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { else textureInternalFormat = GL_RGBA8; - if (tr.worldInternalLightmapping) - { - for (i = 0; i < tr.numLightmaps; i++) - { - tr.lightmaps[i] = R_CreateImage( - va("_lightmapatlas%d", i), - NULL, - tr.lightmapAtlasSize[0], - tr.lightmapAtlasSize[1], - IMGTYPE_COLORALPHA, - IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - textureInternalFormat); + if (tr.worldInternalLightmapping) { + for (i = 0; i < tr.numLightmaps; i++) { + tr.lightmaps[i] = R_CreateImage(va("_lightmapatlas%d", i), NULL, tr.lightmapAtlasSize[0], tr.lightmapAtlasSize[1], IMGTYPE_COLORALPHA, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, textureInternalFormat); - if (tr.worldDeluxeMapping) - { - tr.deluxemaps[i] = R_CreateImage( - va("_fatdeluxemap%d", i), - NULL, - tr.lightmapAtlasSize[0], - tr.lightmapAtlasSize[1], - IMGTYPE_DELUXE, - IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - 0); + if (tr.worldDeluxeMapping) { + tr.deluxemaps[i] = R_CreateImage(va("_fatdeluxemap%d", i), NULL, tr.lightmapAtlasSize[0], tr.lightmapAtlasSize[1], IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); } } } - for (i = 0; i < numLightmaps; i++) - { + for (i = 0; i < numLightmaps; i++) { int xoff = 0, yoff = 0; int lightmapnum = i; // expand the 24 bit on-disk to 32 bit - if (tr.worldInternalLightmapping) - { + if (tr.worldInternalLightmapping) { xoff = (i % tr.lightmapsPerAtlasSide[0]) * tr.lightmapSize; yoff = (i / tr.lightmapsPerAtlasSide[0]) * tr.lightmapSize; lightmapnum = 0; @@ -361,8 +320,7 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { int bppc; bool foundLightmap = true; - if (!tr.worldInternalLightmapping) - { + if (!tr.worldInternalLightmapping) { if (hdr_capable) Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.hdr", worldData->baseName, i * (tr.worldDeluxeMapping ? 2 : 1)); else @@ -370,70 +328,53 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { bppc = 16; R_LoadHDRImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); - if (!externalLightmap) - { + if (!externalLightmap) { bppc = 8; R_LoadImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); } } - if (externalLightmap) - { + if (externalLightmap) { int newImageSize = lightmapWidth * lightmapHeight * 4 * 2; - if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) - { + if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) { ri.Printf(PRINT_ALL, "Error loading %s: non %dx%d lightmaps\n", filename, tr.lightmapSize, tr.lightmapSize); Z_Free(externalLightmap); externalLightmap = NULL; continue; - } - else if (newImageSize > imageSize) - { + } else if (newImageSize > imageSize) { Z_Free(image); imageSize = newImageSize; image = (byte *)Z_Malloc(imageSize, TAG_BSP, qfalse); } numColorComponents = 4; } - if (!externalLightmap) - { + if (!externalLightmap) { lightmapWidth = tr.lightmapSize; lightmapHeight = tr.lightmapSize; numColorComponents = 3; } foundLightmap = true; - if (externalLightmap) - { - if (bppc > 8) - { + if (externalLightmap) { + if (bppc > 8) { hdrL = (float *)externalLightmap; tr.hdrLighting = qtrue; - } - else - { + } else { buf_p = externalLightmap; } - } - else if (buf) - { + } else if (buf) { if (tr.worldDeluxeMapping) buf_p = buf + (i * 2) * tr.lightmapSize * tr.lightmapSize * 3; else buf_p = buf + i * tr.lightmapSize * tr.lightmapSize * 3; - } - else - { + } else { buf_p = NULL; foundLightmap = false; } - if (foundLightmap) - { - for (j = 0; j < lightmapWidth * lightmapHeight; j++) - { - if (hdrL && hdr_capable) - { + if (foundLightmap) { + for (j = 0; j < lightmapWidth * lightmapHeight; j++) { + if (hdrL && hdr_capable) { vec4_t color; int column = (j % lightmapWidth); int rowIndex = (int)floor(j / lightmapHeight) * lightmapHeight; @@ -447,20 +388,17 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { R_ColorShiftLightingFloats(color, color, 1.0f / M_PI, false); ColorToRGBA16F(color, (uint16_t *)(&image[j * 8])); - } - else if (buf_p && hdr_capable) - { + } else if (buf_p && hdr_capable) { vec4_t color; - //hack: convert LDR lightmap to HDR one - color[0] = MAX(buf_p[j*numColorComponents + 0], 0.499f); - color[1] = MAX(buf_p[j*numColorComponents + 1], 0.499f); - color[2] = MAX(buf_p[j*numColorComponents + 2], 0.499f); + // hack: convert LDR lightmap to HDR one + color[0] = MAX(buf_p[j * numColorComponents + 0], 0.499f); + color[1] = MAX(buf_p[j * numColorComponents + 1], 0.499f); + color[2] = MAX(buf_p[j * numColorComponents + 2], 0.499f); // if under an arbitrary value (say 12) grey it out // this prevents weird splotches in dimly lit areas - if (color[0] + color[1] + color[2] < 12.0f) - { + if (color[0] + color[1] + color[2] < 12.0f) { float avg = (color[0] + color[1] + color[2]) * 0.3333f; color[0] = avg; color[1] = avg; @@ -471,16 +409,13 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { R_ColorShiftLightingFloats(color, color, 1.0f / 255.0f); ColorToRGBA16F(color, (unsigned short *)(&image[j * 8])); - } - else if (buf_p) - { - if (r_lightmap->integer == 2) - { // color code by intensity as development tool (FIXME: check range) - float r = buf_p[j*numColorComponents + 0]; - float g = buf_p[j*numColorComponents + 1]; - float b = buf_p[j*numColorComponents + 2]; + } else if (buf_p) { + if (r_lightmap->integer == 2) { // color code by intensity as development tool (FIXME: check range) + float r = buf_p[j * numColorComponents + 0]; + float g = buf_p[j * numColorComponents + 1]; + float b = buf_p[j * numColorComponents + 2]; float intensity; - float out[3] = { 0.0, 0.0, 0.0 }; + float out[3] = {0.0, 0.0, 0.0}; intensity = 0.33f * r + 0.685f * g + 0.063f * b; @@ -500,9 +435,7 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { image[j * 4 + 3] = 255; sumIntensity += intensity; - } - else - { + } else { R_ColorShiftLightingBytes(&buf_p[j * numColorComponents], &image[j * 4]); image[j * 4 + 3] = 255; } @@ -510,32 +443,17 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { } if (tr.worldInternalLightmapping) - R_UpdateSubImage( - tr.lightmaps[lightmapnum], - image, - xoff, - yoff, - lightmapWidth, - lightmapHeight); + R_UpdateSubImage(tr.lightmaps[lightmapnum], image, xoff, yoff, lightmapWidth, lightmapHeight); else - tr.lightmaps[i] = R_CreateImage( - va("*lightmap%d", i), - image, - lightmapWidth, - lightmapHeight, - IMGTYPE_COLORALPHA, - IMGFLAG_NOLIGHTSCALE | - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE, - textureInternalFormat); + tr.lightmaps[i] = R_CreateImage(va("*lightmap%d", i), image, lightmapWidth, lightmapHeight, IMGTYPE_COLORALPHA, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, textureInternalFormat); } if (externalLightmap) Z_Free(externalLightmap); } - if (tr.worldDeluxeMapping && buf) - { + if (tr.worldDeluxeMapping && buf) { buf_p = buf + (i * 2 + 1) * tr.lightmapSize * tr.lightmapSize * 3; for (j = 0; j < tr.lightmapSize * tr.lightmapSize; j++) { @@ -544,42 +462,20 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { image[j * 4 + 2] = buf_p[j * 3 + 2]; // make 0,0,0 into 127,127,127 - if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) - { - image[j*4+0] = - image[j*4+1] = - image[j*4+2] = 127; + if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) { + image[j * 4 + 0] = image[j * 4 + 1] = image[j * 4 + 2] = 127; } image[j * 4 + 3] = 255; } - if (tr.worldInternalLightmapping) - { - R_UpdateSubImage( - tr.deluxemaps[lightmapnum], - image, - xoff, - yoff, - tr.lightmapSize, - tr.lightmapSize); + if (tr.worldInternalLightmapping) { + R_UpdateSubImage(tr.deluxemaps[lightmapnum], image, xoff, yoff, tr.lightmapSize, tr.lightmapSize); + } else { + tr.deluxemaps[i] = R_CreateImage(va("*deluxemap%d", i), image, tr.lightmapSize, tr.lightmapSize, IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); } - else - { - tr.deluxemaps[i] = R_CreateImage( - va("*deluxemap%d", i), - image, - tr.lightmapSize, - tr.lightmapSize, - IMGTYPE_DELUXE, - IMGFLAG_NOLIGHTSCALE | - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE, - 0); - } - } - else if (r_deluxeMapping->integer) - { + } else if (r_deluxeMapping->integer) { char filename[MAX_QPATH]; byte *externalLightmap = NULL; int lightmapWidth = tr.lightmapSize; @@ -595,8 +491,7 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { if (!externalLightmap) continue; - if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) - { + if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) { ri.Printf(PRINT_ALL, "Error loading %s: non %dx%d deluxemaps\n", filename, tr.lightmapSize, tr.lightmapSize); Z_Free(externalLightmap); externalLightmap = NULL; @@ -604,8 +499,7 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { } int newImageSize = lightmapWidth * lightmapHeight * 4 * 2; - if (newImageSize > imageSize) - { + if (newImageSize > imageSize) { Z_Free(image); imageSize = newImageSize; image = (byte *)Z_Malloc(imageSize, TAG_BSP, qfalse); @@ -619,54 +513,26 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { image[j * 4 + 2] = buf_p[j * 4 + 2]; // make 0,0,0 into 127,127,127 - if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) - { - image[j * 4 + 0] = - image[j * 4 + 1] = - image[j * 4 + 2] = 127; + if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) { + image[j * 4 + 0] = image[j * 4 + 1] = image[j * 4 + 2] = 127; } image[j * 4 + 3] = 255; } - if (!tr.deluxemaps) - { + if (!tr.deluxemaps) { tr.deluxemaps = (image_t **)ri.Hunk_Alloc(tr.numLightmaps * sizeof(image_t *), h_low); - if (tr.worldInternalLightmapping) - { - tr.deluxemaps[lightmapnum] = R_CreateImage( - va("_fatdeluxemap%d", i), - NULL, - tr.lightmapAtlasSize[0], - tr.lightmapAtlasSize[1], - IMGTYPE_DELUXE, - IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - 0); + if (tr.worldInternalLightmapping) { + tr.deluxemaps[lightmapnum] = R_CreateImage(va("_fatdeluxemap%d", i), NULL, tr.lightmapAtlasSize[0], tr.lightmapAtlasSize[1], IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); } } - if (tr.worldInternalLightmapping) - { - R_UpdateSubImage( - tr.deluxemaps[lightmapnum], - image, - xoff, - yoff, - lightmapWidth, - lightmapHeight); - } - else - { - tr.deluxemaps[i] = R_CreateImage( - va("*deluxemap%d", i), - image, - lightmapWidth, - lightmapHeight, - IMGTYPE_DELUXE, - IMGFLAG_NOLIGHTSCALE | - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE, - 0); + if (tr.worldInternalLightmapping) { + R_UpdateSubImage(tr.deluxemaps[lightmapnum], image, xoff, yoff, lightmapWidth, lightmapHeight); + } else { + tr.deluxemaps[i] = R_CreateImage(va("*deluxemap%d", i), image, lightmapWidth, lightmapHeight, IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); } Z_Free(externalLightmap); @@ -674,27 +540,24 @@ static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { } } - if ( r_lightmap->integer == 2 ) { - ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) ); + if (r_lightmap->integer == 2) { + ri.Printf(PRINT_ALL, "Brightest lightmap value: %d\n", (int)(maxIntensity * 255)); } Z_Free(image); if (tr.deluxemaps) tr.worldDeluxeMapping = qtrue; - } - +} -static float FatPackU(float input, int lightmapnum) -{ +static float FatPackU(float input, int lightmapnum) { if (lightmapnum < 0) return input; if (tr.worldInternalDeluxeMapping) lightmapnum >>= 1; - if (tr.lightmapAtlasSize[0] > 0) - { + if (tr.lightmapAtlasSize[0] > 0) { const int lightmapXOffset = lightmapnum % tr.lightmapsPerAtlasSide[0]; const float invLightmapSide = 1.0f / tr.lightmapsPerAtlasSide[0]; @@ -704,16 +567,14 @@ static float FatPackU(float input, int lightmapnum) return input; } -static float FatPackV(float input, int lightmapnum) -{ +static float FatPackV(float input, int lightmapnum) { if (lightmapnum < 0) return input; if (tr.worldInternalDeluxeMapping) lightmapnum >>= 1; - if (tr.lightmapAtlasSize[1] > 0) - { + if (tr.lightmapAtlasSize[1] > 0) { const int lightmapYOffset = lightmapnum / tr.lightmapsPerAtlasSide[0]; const float invLightmapSide = 1.0f / tr.lightmapsPerAtlasSide[1]; @@ -723,9 +584,7 @@ static float FatPackV(float input, int lightmapnum) return input; } - -static int FatLightmap(int lightmapnum) -{ +static int FatLightmap(int lightmapnum) { if (lightmapnum < 0) return lightmapnum; @@ -746,82 +605,78 @@ This is called by the clipmodel subsystem so we can share the 1.8 megs of space in big maps... ================= */ -void RE_SetWorldVisData( const byte *vis ) { - tr.externalVisData = vis; -} - +void RE_SetWorldVisData(const byte *vis) { tr.externalVisData = vis; } /* ================= R_LoadVisibility ================= */ -static void R_LoadVisibility( world_t *worldData, lump_t *l ) { - int len; - byte *buf; +static void R_LoadVisibility(world_t *worldData, lump_t *l) { + int len; + byte *buf; len = (worldData->numClusters + 63) & ~63; worldData->novis = (byte *)ri.Hunk_Alloc(len, h_low); Com_Memset(worldData->novis, 0xff, len); len = l->filelen; - if ( !len ) { + if (!len) { return; } buf = fileBase + l->fileofs; - worldData->numClusters = LittleLong( ((int *)buf)[0] ); - worldData->clusterBytes = LittleLong( ((int *)buf)[1] ); + worldData->numClusters = LittleLong(((int *)buf)[0]); + worldData->clusterBytes = LittleLong(((int *)buf)[1]); // CM_Load should have given us the vis data to share, so // we don't need to allocate another copy - if ( tr.externalVisData ) { + if (tr.externalVisData) { worldData->vis = tr.externalVisData; } else { - byte *dest; + byte *dest; - dest = (byte *)ri.Hunk_Alloc( len - 8, h_low ); - Com_Memcpy( dest, buf + 8, len - 8 ); + dest = (byte *)ri.Hunk_Alloc(len - 8, h_low); + Com_Memcpy(dest, buf + 8, len - 8); worldData->vis = dest; } } //=============================================================================== - /* =============== ShaderForShaderNum =============== */ -static shader_t *ShaderForShaderNum( const world_t *worldData, int shaderNum, const int *lightmapNums, const byte *lightmapStyles, const byte *vertexStyles ) { - shader_t *shader; - dshader_t *dsh; - const byte *styles = lightmapStyles; - - int _shaderNum = LittleLong( shaderNum ); - if ( _shaderNum < 0 || _shaderNum >= worldData->numShaders ) { - ri.Error( ERR_DROP, "ShaderForShaderNum: bad num %i", _shaderNum ); +static shader_t *ShaderForShaderNum(const world_t *worldData, int shaderNum, const int *lightmapNums, const byte *lightmapStyles, const byte *vertexStyles) { + shader_t *shader; + dshader_t *dsh; + const byte *styles = lightmapStyles; + + int _shaderNum = LittleLong(shaderNum); + if (_shaderNum < 0 || _shaderNum >= worldData->numShaders) { + ri.Error(ERR_DROP, "ShaderForShaderNum: bad num %i", _shaderNum); } - dsh = &worldData->shaders[ _shaderNum ]; + dsh = &worldData->shaders[_shaderNum]; - if ( lightmapNums[0] == LIGHTMAP_BY_VERTEX ) { + if (lightmapNums[0] == LIGHTMAP_BY_VERTEX) { styles = vertexStyles; } - if ( r_vertexLight->integer ) { + if (r_vertexLight->integer) { lightmapNums = lightmapsVertex; styles = vertexStyles; } - if ( r_fullbright->integer ) { + if (r_fullbright->integer) { lightmapNums = lightmapsFullBright; } - shader = R_FindShader( dsh->shader, lightmapNums, styles, qtrue ); + shader = R_FindShader(dsh->shader, lightmapNums, styles, qtrue); // if the shader had errors, just use default shader - if ( shader->defaultShader ) { + if (shader->defaultShader) { return tr.defaultShader; } @@ -833,38 +688,37 @@ static shader_t *ShaderForShaderNum( const world_t *worldData, int shaderNum, co ParseFace =============== */ -static void ParseFace( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf, int *indexes ) { - int i, j; - srfBspSurface_t *cv; - glIndex_t *tri; - int numVerts, numIndexes, badTriangles; +static void ParseFace(const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf, + int *indexes) { + int i, j; + srfBspSurface_t *cv; + glIndex_t *tri; + int numVerts, numIndexes, badTriangles; int realLightmapNum[MAXLIGHTMAPS]; - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - { - realLightmapNum[j] = FatLightmap (LittleLong (ds->lightmapNum[j])); + for (j = 0; j < MAXLIGHTMAPS; j++) { + realLightmapNum[j] = FatLightmap(LittleLong(ds->lightmapNum[j])); } surf->numSurfaceSprites = 0; surf->surfaceSprites = nullptr; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (!surf->fogIndex && worldData->globalFog != nullptr) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) { surf->fogIndex = worldData->globalFogIndex; } // get shader value - surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles); - if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = ShaderForShaderNum(worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles); + if (r_singleShader->integer && !surf->shader->isSky) { surf->shader = tr.defaultShader; } numVerts = LittleLong(ds->numVerts); numIndexes = LittleLong(ds->numIndexes); - //cv = ri.Hunk_Alloc(sizeof(*cv), h_low); + // cv = ri.Hunk_Alloc(sizeof(*cv), h_low); cv = (srfBspSurface_t *)surf->data; cv->surfaceType = SF_FACE; @@ -880,56 +734,43 @@ static void ParseFace( const world_t *worldData, dsurface_t *ds, drawVert_t *ver verts += LittleLong(ds->firstVert); if (tangentSpace) tangentSpace += LittleLong(ds->firstVert); - for(i = 0; i < numVerts; i++) - { + for (i = 0; i < numVerts; i++) { vec4_t color; - for(j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { cv->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); cv->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); } - if (tangentSpace) - { + if (tangentSpace) { for (j = 0; j < 4; j++) cv->verts[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); } AddPointToBounds(cv->verts[i].xyz, surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]); - for(j = 0; j < 2; j++) - { + for (j = 0; j < 2; j++) { cv->verts[i].st[j] = LittleFloat(verts[i].st[j]); } - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - { - cv->verts[i].lightmap[j][0] = FatPackU( - LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); - cv->verts[i].lightmap[j][1] = FatPackV( - LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); + for (j = 0; j < MAXLIGHTMAPS; j++) { + cv->verts[i].lightmap[j][0] = FatPackU(LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); + cv->verts[i].lightmap[j][1] = FatPackV(LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); float scale = 1.0f / 255.0f; - if (hdrVertColors) - { + if (hdrVertColors) { float *hdrColor = hdrVertColors + (ds->firstVert + i) * 3; color[0] = hdrColor[0] / M_PI; color[1] = hdrColor[1] / M_PI; color[2] = hdrColor[2] / M_PI; scale = 1.0f; - } - else - { - //hack: convert LDR vertex colors to HDR - if (r_hdr->integer) - { + } else { + // hack: convert LDR vertex colors to HDR + if (r_hdr->integer) { color[0] = MAX(verts[i].color[j][0], 0.499f); color[1] = MAX(verts[i].color[j][1], 0.499f); color[2] = MAX(verts[i].color[j][2], 0.499f); - } - else - { + } else { color[0] = verts[i].color[j][0]; color[1] = verts[i].color[j][1]; color[2] = verts[i].color[j][2]; @@ -937,148 +778,131 @@ static void ParseFace( const world_t *worldData, dsurface_t *ds, drawVert_t *ver } color[3] = verts[i].color[j][3] / 255.0f; - R_ColorShiftLightingFloats( color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL ); + R_ColorShiftLightingFloats(color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL); } } // copy triangles badTriangles = 0; indexes += LittleLong(ds->firstIndex); - for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) - { - for(j = 0; j < 3; j++) - { + for (i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) { + for (j = 0; j < 3; j++) { tri[j] = LittleLong(indexes[i + j]); - if(tri[j] >= numVerts) - { + if (tri[j] >= numVerts) { ri.Error(ERR_DROP, "Bad index in face surface"); } } - if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) - { + if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) { tri -= 3; badTriangles++; } } - if (badTriangles) - { - ri.Printf(PRINT_WARNING, "Face has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles); + if (badTriangles) { + ri.Printf(PRINT_WARNING, "Face has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, + numIndexes / 3 - badTriangles); cv->numIndexes -= badTriangles * 3; } // take the plane information from the lightmap vector - for ( i = 0 ; i < 3 ; i++ ) { - cv->cullPlane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + cv->cullPlane.normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } - cv->cullPlane.dist = DotProduct( cv->verts[0].xyz, cv->cullPlane.normal ); - SetPlaneSignbits( &cv->cullPlane ); - cv->cullPlane.type = PlaneTypeForNormal( cv->cullPlane.normal ); + cv->cullPlane.dist = DotProduct(cv->verts[0].xyz, cv->cullPlane.normal); + SetPlaneSignbits(&cv->cullPlane); + cv->cullPlane.type = PlaneTypeForNormal(cv->cullPlane.normal); surf->cullinfo.plane = cv->cullPlane; surf->data = (surfaceType_t *)cv; } - /* =============== ParseMesh =============== */ -static void ParseMesh ( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf ) { - srfBspSurface_t *grid; - int i, j; - int width, height, numPoints; - srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE]; - vec3_t bounds[2]; - vec3_t tmpVec; - static surfaceType_t skipData = SF_SKIP; +static void ParseMesh(const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf) { + srfBspSurface_t *grid; + int i, j; + int width, height, numPoints; + srfVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]; + vec3_t bounds[2]; + vec3_t tmpVec; + static surfaceType_t skipData = SF_SKIP; int realLightmapNum[MAXLIGHTMAPS]; - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - realLightmapNum[j] = FatLightmap(LittleLong (ds->lightmapNum[j])); + for (j = 0; j < MAXLIGHTMAPS; j++) + realLightmapNum[j] = FatLightmap(LittleLong(ds->lightmapNum[j])); surf->numSurfaceSprites = 0; surf->surfaceSprites = nullptr; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (!surf->fogIndex && worldData->globalFog != nullptr) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) { surf->fogIndex = worldData->globalFogIndex; } // get shader value - surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles ); - if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = ShaderForShaderNum(worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles); + if (r_singleShader->integer && !surf->shader->isSky) { surf->shader = tr.defaultShader; } // we may have a nodraw surface, because they might still need to // be around for movement clipping - if ( worldData->shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) { + if (worldData->shaders[LittleLong(ds->shaderNum)].surfaceFlags & SURF_NODRAW) { surf->data = &skipData; return; } - width = LittleLong( ds->patchWidth ); - height = LittleLong( ds->patchHeight ); + width = LittleLong(ds->patchWidth); + height = LittleLong(ds->patchHeight); - if(width < 0 || width > MAX_PATCH_SIZE || height < 0 || height > MAX_PATCH_SIZE) + if (width < 0 || width > MAX_PATCH_SIZE || height < 0 || height > MAX_PATCH_SIZE) ri.Error(ERR_DROP, "ParseMesh: bad size"); - verts += LittleLong( ds->firstVert ); + verts += LittleLong(ds->firstVert); if (tangentSpace) tangentSpace += LittleLong(ds->firstVert); numPoints = width * height; - for(i = 0; i < numPoints; i++) - { + for (i = 0; i < numPoints; i++) { vec4_t color; - for(j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { points[i].xyz[j] = LittleFloat(verts[i].xyz[j]); points[i].normal[j] = LittleFloat(verts[i].normal[j]); } - if (tangentSpace) - { + if (tangentSpace) { for (j = 0; j < 4; j++) points[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); } - for(j = 0; j < 2; j++) - { + for (j = 0; j < 2; j++) { points[i].st[j] = LittleFloat(verts[i].st[j]); } - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - { + for (j = 0; j < MAXLIGHTMAPS; j++) { points[i].lightmap[j][0] = FatPackU(LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); points[i].lightmap[j][1] = FatPackV(LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); float scale = 1.0f / 255.0f; - if (hdrVertColors) - { - float *hdrColor = hdrVertColors + (ds->firstVert + i)*3; + if (hdrVertColors) { + float *hdrColor = hdrVertColors + (ds->firstVert + i) * 3; color[0] = hdrColor[0] / M_PI; color[1] = hdrColor[1] / M_PI; color[2] = hdrColor[2] / M_PI; scale = 1.0f; - } - else - { - //hack: convert LDR vertex colors to HDR - if (r_hdr->integer) - { + } else { + // hack: convert LDR vertex colors to HDR + if (r_hdr->integer) { color[0] = MAX(verts[i].color[j][0], 0.499f); color[1] = MAX(verts[i].color[j][1], 0.499f); color[2] = MAX(verts[i].color[j][2], 0.499f); - } - else - { + } else { color[0] = verts[i].color[j][0]; color[1] = verts[i].color[j][1]; color[2] = verts[i].color[j][2]; @@ -1086,25 +910,25 @@ static void ParseMesh ( const world_t *worldData, dsurface_t *ds, drawVert_t *ve } color[3] = verts[i].color[j][3] / 255.0f; - R_ColorShiftLightingFloats( color, points[i].vertexColors[j], scale, hdrVertColors != NULL ); + R_ColorShiftLightingFloats(color, points[i].vertexColors[j], scale, hdrVertColors != NULL); } } // pre-tesseleate - grid = R_SubdividePatchToGrid( width, height, points ); + grid = R_SubdividePatchToGrid(width, height, points); surf->data = (surfaceType_t *)grid; // copy the level of detail origin, which is the center // of the group of all curves that must subdivide the same // to avoid cracking - for ( i = 0 ; i < 3 ; i++ ) { - bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] ); - bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] ); - } - VectorAdd( bounds[0], bounds[1], bounds[1] ); - VectorScale( bounds[1], 0.5f, grid->lodOrigin ); - VectorSubtract( bounds[0], grid->lodOrigin, tmpVec ); - grid->lodRadius = VectorLength( tmpVec ); + for (i = 0; i < 3; i++) { + bounds[0][i] = LittleFloat(ds->lightmapVecs[0][i]); + bounds[1][i] = LittleFloat(ds->lightmapVecs[1][i]); + } + VectorAdd(bounds[0], bounds[1], bounds[1]); + VectorScale(bounds[1], 0.5f, grid->lodOrigin); + VectorSubtract(bounds[0], grid->lodOrigin, tmpVec); + grid->lodRadius = VectorLength(tmpVec); } /* @@ -1112,36 +936,36 @@ static void ParseMesh ( const world_t *worldData, dsurface_t *ds, drawVert_t *ve ParseTriSurf =============== */ -static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf, int *indexes ) { +static void ParseTriSurf(const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, + msurface_t *surf, int *indexes) { srfBspSurface_t *cv; - glIndex_t *tri; - int i, j; - int numVerts, numIndexes, badTriangles; + glIndex_t *tri; + int i, j; + int numVerts, numIndexes, badTriangles; int realLightmapNum[MAXLIGHTMAPS]; - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - realLightmapNum[j] = FatLightmap(LittleLong (ds->lightmapNum[j])); + for (j = 0; j < MAXLIGHTMAPS; j++) + realLightmapNum[j] = FatLightmap(LittleLong(ds->lightmapNum[j])); surf->numSurfaceSprites = 0; surf->surfaceSprites = nullptr; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (!surf->fogIndex && worldData->globalFog != nullptr) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) { surf->fogIndex = worldData->globalFogIndex; } // get shader - surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles ); - if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = ShaderForShaderNum(worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles); + if (r_singleShader->integer && !surf->shader->isSky) { surf->shader = tr.defaultShader; } numVerts = LittleLong(ds->numVerts); numIndexes = LittleLong(ds->numIndexes); - //cv = ri.Hunk_Alloc(sizeof(*cv), h_low); + // cv = ri.Hunk_Alloc(sizeof(*cv), h_low); cv = (srfBspSurface_t *)surf->data; cv->surfaceType = SF_TRIANGLES; @@ -1151,7 +975,7 @@ static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t * cv->numVerts = numVerts; cv->verts = (srfVert_t *)ri.Hunk_Alloc(numVerts * sizeof(cv->verts[0]), h_low); - surf->data = (surfaceType_t *) cv; + surf->data = (surfaceType_t *)cv; // copy vertexes surf->cullinfo.type = CULLINFO_BOX; @@ -1159,56 +983,43 @@ static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t * verts += LittleLong(ds->firstVert); if (tangentSpace) tangentSpace += LittleLong(ds->firstVert); - for (i = 0; i < numVerts; i++) - { + for (i = 0; i < numVerts; i++) { vec4_t color; - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { cv->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); cv->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); } - if (tangentSpace) - { + if (tangentSpace) { for (j = 0; j < 4; j++) cv->verts[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); } - AddPointToBounds( cv->verts[i].xyz, surf->cullinfo.bounds[0], surf->cullinfo.bounds[1] ); + AddPointToBounds(cv->verts[i].xyz, surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]); - for(j = 0; j < 2; j++) - { + for (j = 0; j < 2; j++) { cv->verts[i].st[j] = LittleFloat(verts[i].st[j]); } - for ( j = 0; j < MAXLIGHTMAPS; j++ ) - { - cv->verts[i].lightmap[j][0] = FatPackU( - LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); - cv->verts[i].lightmap[j][1] = FatPackV( - LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); + for (j = 0; j < MAXLIGHTMAPS; j++) { + cv->verts[i].lightmap[j][0] = FatPackU(LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); + cv->verts[i].lightmap[j][1] = FatPackV(LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); float scale = 1.0f / 255.0f; - if (hdrVertColors) - { + if (hdrVertColors) { float *hdrColor = hdrVertColors + ((ds->firstVert + i) * 3); color[0] = hdrColor[0] / M_PI; color[1] = hdrColor[1] / M_PI; color[2] = hdrColor[2] / M_PI; scale = 1.0f; - } - else - { - //hack: convert LDR vertex colors to HDR - if (r_hdr->integer) - { + } else { + // hack: convert LDR vertex colors to HDR + if (r_hdr->integer) { color[0] = MAX(verts[i].color[j][0], 0.499f); color[1] = MAX(verts[i].color[j][1], 0.499f); color[2] = MAX(verts[i].color[j][2], 0.499f); - } - else - { + } else { color[0] = verts[i].color[j][0]; color[1] = verts[i].color[j][1]; color[2] = verts[i].color[j][2]; @@ -1216,35 +1027,31 @@ static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t * } color[3] = verts[i].color[j][3] / 255.0f; - R_ColorShiftLightingFloats( color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL ); + R_ColorShiftLightingFloats(color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL); } } // copy triangles badTriangles = 0; indexes += LittleLong(ds->firstIndex); - for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) - { - for(j = 0; j < 3; j++) - { + for (i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) { + for (j = 0; j < 3; j++) { tri[j] = LittleLong(indexes[i + j]); - if(tri[j] >= numVerts) - { + if (tri[j] >= numVerts) { ri.Error(ERR_DROP, "Bad index in face surface"); } } - if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) - { + if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) { tri -= 3; badTriangles++; } } - if (badTriangles) - { - ri.Printf(PRINT_WARNING, "Trisurf has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles); + if (badTriangles) { + ri.Printf(PRINT_WARNING, "Trisurf has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, + numVerts, numIndexes / 3 - badTriangles); cv->numIndexes -= badTriangles * 3; } } @@ -1254,27 +1061,26 @@ static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t * ParseFlare =============== */ -static void ParseFlare( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) { - srfFlare_t *flare; - int i; +static void ParseFlare(const world_t *worldData, dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes) { + srfFlare_t *flare; + int i; surf->numSurfaceSprites = 0; surf->surfaceSprites = nullptr; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (!surf->fogIndex && worldData->globalFog != nullptr) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) { surf->fogIndex = worldData->globalFogIndex; } // get shader - surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles ); - if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = ShaderForShaderNum(worldData, ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles); + if (r_singleShader->integer && !surf->shader->isSky) { surf->shader = tr.defaultShader; } - //flare = ri.Hunk_Alloc( sizeof( *flare ), h_low ); + // flare = ri.Hunk_Alloc( sizeof( *flare ), h_low ); flare = (srfFlare_t *)surf->data; flare->surfaceType = SF_FLARE; @@ -1285,14 +1091,13 @@ static void ParseFlare( const world_t *worldData, dsurface_t *ds, drawVert_t *ve surf->data = (surfaceType_t *)flare; - for ( i = 0 ; i < 3 ; i++ ) { - flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] ); - flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] ); - flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + flare->origin[i] = LittleFloat(ds->lightmapOrigin[i]); + flare->color[i] = LittleFloat(ds->lightmapVecs[0][i]); + flare->normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } } - /* ================= R_MergedWidthPoints @@ -1303,11 +1108,14 @@ returns true if there are grid points merged on a width edge int R_MergedWidthPoints(srfBspSurface_t *grid, int offset) { int i, j; - for (i = 1; i < grid->width-1; i++) { - for (j = i + 1; j < grid->width-1; j++) { - if ( fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) continue; - if ( fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) continue; - if ( fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) continue; + for (i = 1; i < grid->width - 1; i++) { + for (j = i + 1; j < grid->width - 1; j++) { + if (fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) + continue; + if (fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) + continue; + if (fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) + continue; return qtrue; } } @@ -1324,11 +1132,14 @@ returns true if there are grid points merged on a height edge int R_MergedHeightPoints(srfBspSurface_t *grid, int offset) { int i, j; - for (i = 1; i < grid->height-1; i++) { - for (j = i + 1; j < grid->height-1; j++) { - if ( fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) continue; - if ( fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) continue; - if ( fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) continue; + for (i = 1; i < grid->height - 1; i++) { + for (j = i + 1; j < grid->height - 1; j++) { + if (fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) + continue; + if (fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) + continue; + if (fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) + continue; return qtrue; } } @@ -1344,41 +1155,56 @@ NOTE: never sync LoD through grid edges with merged points! FIXME: write generalized version that also avoids cracks between a patch and one that meets half way? ================= */ -void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t *grid1 ) { +void R_FixSharedVertexLodError_r(world_t *worldData, int start, srfBspSurface_t *grid1) { int j, k, l, m, n, offset1, offset2, touch; srfBspSurface_t *grid2; - for ( j = start; j < worldData->numsurfaces; j++ ) { + for (j = start; j < worldData->numsurfaces; j++) { // - grid2 = (srfBspSurface_t *) worldData->surfaces[j].data; + grid2 = (srfBspSurface_t *)worldData->surfaces[j].data; // if this surface is not a grid - if ( grid2->surfaceType != SF_GRID ) continue; + if (grid2->surfaceType != SF_GRID) + continue; // if the LOD errors are already fixed for this patch - if ( grid2->lodFixed == 2 ) continue; + if (grid2->lodFixed == 2) + continue; // grids in the same LOD group should have the exact same lod radius - if ( grid1->lodRadius != grid2->lodRadius ) continue; + if (grid1->lodRadius != grid2->lodRadius) + continue; // grids in the same LOD group should have the exact same lod origin - if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; - if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; - if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + if (grid1->lodOrigin[0] != grid2->lodOrigin[0]) + continue; + if (grid1->lodOrigin[1] != grid2->lodOrigin[1]) + continue; + if (grid1->lodOrigin[2] != grid2->lodOrigin[2]) + continue; // touch = qfalse; for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; - if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = 1; k < grid1->width-1; k++) { + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; + if (R_MergedWidthPoints(grid1, offset1)) + continue; + for (k = 1; k < grid1->width - 1; k++) { for (m = 0; m < 2; m++) { - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - if (R_MergedWidthPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->width-1; l++) { - // - if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->width - 1; l++) { + // + if (fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->widthLodError[l] = grid1->widthLodError[k]; touch = qtrue; @@ -1386,14 +1212,20 @@ void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t } for (m = 0; m < 2; m++) { - if (m) offset2 = grid2->width-1; - else offset2 = 0; - if (R_MergedHeightPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->height-1; l++) { - // - if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->height - 1; l++) { + // + if (fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->heightLodError[l] = grid1->widthLodError[k]; touch = qtrue; @@ -1403,20 +1235,29 @@ void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; - if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = 1; k < grid1->height-1; k++) { + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; + if (R_MergedHeightPoints(grid1, offset1)) + continue; + for (k = 1; k < grid1->height - 1; k++) { for (m = 0; m < 2; m++) { - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - if (R_MergedWidthPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->width-1; l++) { - // - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->width - 1; l++) { + // + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->widthLodError[l] = grid1->heightLodError[k]; touch = qtrue; @@ -1424,14 +1265,20 @@ void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t } for (m = 0; m < 2; m++) { - if (m) offset2 = grid2->width-1; - else offset2 = 0; - if (R_MergedHeightPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->height-1; l++) { - // - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->height - 1; l++) { + // + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->heightLodError[l] = grid1->heightLodError[k]; touch = qtrue; @@ -1441,9 +1288,9 @@ void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t } if (touch) { grid2->lodFixed = 2; - R_FixSharedVertexLodError_r ( worldData, start, grid2 ); - //NOTE: this would be correct but makes things really slow - //grid2->lodFixed = 1; + R_FixSharedVertexLodError_r(worldData, start, grid2); + // NOTE: this would be correct but makes things really slow + // grid2->lodFixed = 1; } } } @@ -1456,88 +1303,90 @@ This function assumes that all patches in one group are nicely stitched together If this is not the case this function will still do its job but won't fix the highest LoD cracks. ================= */ -void R_FixSharedVertexLodError( world_t *worldData ) { +void R_FixSharedVertexLodError(world_t *worldData) { int i; srfBspSurface_t *grid1; - for ( i = 0; i < worldData->numsurfaces; i++ ) { + for (i = 0; i < worldData->numsurfaces; i++) { // - grid1 = (srfBspSurface_t *) worldData->surfaces[i].data; + grid1 = (srfBspSurface_t *)worldData->surfaces[i].data; // if this surface is not a grid - if ( grid1->surfaceType != SF_GRID ) + if (grid1->surfaceType != SF_GRID) continue; // - if ( grid1->lodFixed ) + if (grid1->lodFixed) continue; // grid1->lodFixed = 2; // recursively fix other patches in the same LOD group - R_FixSharedVertexLodError_r( worldData, i + 1, grid1); + R_FixSharedVertexLodError_r(worldData, i + 1, grid1); } } - /* =============== R_StitchPatches =============== */ -int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { +int R_StitchPatches(world_t *worldData, int grid1num, int grid2num) { float *v1, *v2; srfBspSurface_t *grid1, *grid2; int k, l, m, n, offset1, offset2, row, column; - grid1 = (srfBspSurface_t *) worldData->surfaces[grid1num].data; - grid2 = (srfBspSurface_t *) worldData->surfaces[grid2num].data; + grid1 = (srfBspSurface_t *)worldData->surfaces[grid1num].data; + grid2 = (srfBspSurface_t *)worldData->surfaces[grid2num].data; for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = 0; k < grid1->width-2; k += 2) { + for (k = 0; k < grid1->width - 2; k += 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - for ( l = 0; l < grid2->width-1; l++) { - // + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k + 2 + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1545,43 +1394,44 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - for ( l = 0; l < grid2->height-1; l++) { + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + for (l = 0; l < grid2->height - 1; l++) { // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k + 2 + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1589,52 +1439,55 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = 0; k < grid1->height-2; k += 2) { + for (k = 0; k < grid1->height - 2; k += 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - for ( l = 0; l < grid2->width-1; l++) { - // + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1642,43 +1495,44 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - for ( l = 0; l < grid2->height-1; l++) { - // + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1686,53 +1540,56 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = grid1->width-1; k > 1; k -= 2) { + for (k = grid1->width - 1; k > 1; k -= 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - for ( l = 0; l < grid2->width-1; l++) { - // + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k - 2 + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1740,45 +1597,46 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - for ( l = 0; l < grid2->height-1; l++) { - // + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k - 2 + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k + 1]); if (!grid2) break; grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1786,52 +1644,55 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = grid1->height-1; k > 1; k -= 2) { + for (k = grid1->height - 1; k > 1; k -= 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - for ( l = 0; l < grid2->width-1; l++) { - // + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1839,43 +1700,44 @@ int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - for ( l = 0; l < grid2->height-1; l++) { - // + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData->surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1897,26 +1759,30 @@ of the patch (on the same row or column) the vertices will not be joined and cra might still appear at that side. =============== */ -int R_TryStitchingPatch( world_t *worldData, int grid1num ) { +int R_TryStitchingPatch(world_t *worldData, int grid1num) { int j, numstitches; srfBspSurface_t *grid1, *grid2; numstitches = 0; - grid1 = (srfBspSurface_t *) worldData->surfaces[grid1num].data; - for ( j = 0; j < worldData->numsurfaces; j++ ) { + grid1 = (srfBspSurface_t *)worldData->surfaces[grid1num].data; + for (j = 0; j < worldData->numsurfaces; j++) { // - grid2 = (srfBspSurface_t *) worldData->surfaces[j].data; + grid2 = (srfBspSurface_t *)worldData->surfaces[j].data; // if this surface is not a grid - if ( grid2->surfaceType != SF_GRID ) continue; + if (grid2->surfaceType != SF_GRID) + continue; // grids in the same LOD group should have the exact same lod radius - if ( grid1->lodRadius != grid2->lodRadius ) continue; + if (grid1->lodRadius != grid2->lodRadius) + continue; // grids in the same LOD group should have the exact same lod origin - if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; - if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; - if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + if (grid1->lodOrigin[0] != grid2->lodOrigin[0]) + continue; + if (grid1->lodOrigin[1] != grid2->lodOrigin[1]) + continue; + if (grid1->lodOrigin[2] != grid2->lodOrigin[2]) + continue; // - while (R_StitchPatches(worldData, grid1num, j)) - { + while (R_StitchPatches(worldData, grid1num, j)) { numstitches++; } } @@ -1928,32 +1794,30 @@ int R_TryStitchingPatch( world_t *worldData, int grid1num ) { R_StitchAllPatches =============== */ -void R_StitchAllPatches( world_t *worldData ) { +void R_StitchAllPatches(world_t *worldData) { int i, stitched, numstitches; srfBspSurface_t *grid1; numstitches = 0; - do - { + do { stitched = qfalse; - for ( i = 0; i < worldData->numsurfaces; i++ ) { + for (i = 0; i < worldData->numsurfaces; i++) { // - grid1 = (srfBspSurface_t *) worldData->surfaces[i].data; + grid1 = (srfBspSurface_t *)worldData->surfaces[i].data; // if this surface is not a grid - if ( grid1->surfaceType != SF_GRID ) + if (grid1->surfaceType != SF_GRID) continue; // - if ( grid1->lodStitched ) + if (grid1->lodStitched) continue; // grid1->lodStitched = qtrue; stitched = qtrue; // - numstitches += R_TryStitchingPatch( worldData, i ); + numstitches += R_TryStitchingPatch(worldData, i); } - } - while (stitched); - ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches ); + } while (stitched); + ri.Printf(PRINT_ALL, "stitched %d LoD cracks\n", numstitches); } /* @@ -1961,26 +1825,26 @@ void R_StitchAllPatches( world_t *worldData ) { R_MovePatchSurfacesToHunk =============== */ -void R_MovePatchSurfacesToHunk( world_t *worldData ) { +void R_MovePatchSurfacesToHunk(world_t *worldData) { int i, size; srfBspSurface_t *grid, *hunkgrid; - for ( i = 0; i < worldData->numsurfaces; i++ ) { + for (i = 0; i < worldData->numsurfaces; i++) { // - grid = (srfBspSurface_t *) worldData->surfaces[i].data; + grid = (srfBspSurface_t *)worldData->surfaces[i].data; // if this surface is not a grid - if ( grid->surfaceType != SF_GRID ) + if (grid->surfaceType != SF_GRID) continue; // size = sizeof(*grid); hunkgrid = (srfBspSurface_t *)ri.Hunk_Alloc(size, h_low); Com_Memcpy(hunkgrid, grid, size); - hunkgrid->widthLodError = (float *)ri.Hunk_Alloc( grid->width * 4, h_low ); - Com_Memcpy( hunkgrid->widthLodError, grid->widthLodError, grid->width * 4 ); + hunkgrid->widthLodError = (float *)ri.Hunk_Alloc(grid->width * 4, h_low); + Com_Memcpy(hunkgrid->widthLodError, grid->widthLodError, grid->width * 4); - hunkgrid->heightLodError = (float *)ri.Hunk_Alloc( grid->height * 4, h_low ); - Com_Memcpy( hunkgrid->heightLodError, grid->heightLodError, grid->height * 4 ); + hunkgrid->heightLodError = (float *)ri.Hunk_Alloc(grid->height * 4, h_low); + Com_Memcpy(hunkgrid->heightLodError, grid->heightLodError, grid->height * 4); hunkgrid->numIndexes = grid->numIndexes; hunkgrid->indexes = (glIndex_t *)ri.Hunk_Alloc(grid->numIndexes * sizeof(glIndex_t), h_low); @@ -1990,48 +1854,45 @@ void R_MovePatchSurfacesToHunk( world_t *worldData ) { hunkgrid->verts = (srfVert_t *)ri.Hunk_Alloc(grid->numVerts * sizeof(srfVert_t), h_low); Com_Memcpy(hunkgrid->verts, grid->verts, grid->numVerts * sizeof(srfVert_t)); - R_FreeSurfaceGridMesh( grid ); + R_FreeSurfaceGridMesh(grid); - worldData->surfaces[i].data = (surfaceType_t *) hunkgrid; + worldData->surfaces[i].data = (surfaceType_t *)hunkgrid; } } - /* ================= BSPSurfaceCompare compare function for qsort() ================= */ -static int BSPSurfaceCompare(const void *a, const void *b) -{ - msurface_t *aa, *bb; +static int BSPSurfaceCompare(const void *a, const void *b) { + msurface_t *aa, *bb; - aa = *(msurface_t **) a; - bb = *(msurface_t **) b; + aa = *(msurface_t **)a; + bb = *(msurface_t **)b; // shader first - if(aa->shader->sortedIndex < bb->shader->sortedIndex) + if (aa->shader->sortedIndex < bb->shader->sortedIndex) return -1; - else if(aa->shader->sortedIndex > bb->shader->sortedIndex) + else if (aa->shader->sortedIndex > bb->shader->sortedIndex) return 1; // by fogIndex - if(aa->fogIndex < bb->fogIndex) + if (aa->fogIndex < bb->fogIndex) return -1; - else if(aa->fogIndex > bb->fogIndex) + else if (aa->fogIndex > bb->fogIndex) return 1; // by cubemapIndex - if(aa->cubemapIndex < bb->cubemapIndex) + if (aa->cubemapIndex < bb->cubemapIndex) return -1; - else if(aa->cubemapIndex > bb->cubemapIndex) + else if (aa->cubemapIndex > bb->cubemapIndex) return 1; - return 0; } @@ -2040,19 +1901,18 @@ static int BSPSurfaceCompare(const void *a, const void *b) R_CreateWorldVBOs =============== */ -static void R_CreateWorldVBOs( world_t *worldData ) -{ - int i, j, k; +static void R_CreateWorldVBOs(world_t *worldData) { + int i, j, k; - int numVerts; - packedVertex_t *verts; + int numVerts; + packedVertex_t *verts; - int numIndexes; - glIndex_t *indexes; + int numIndexes; + glIndex_t *indexes; - int numSortedSurfaces, numSurfaces; - msurface_t *surface, **firstSurf, **lastSurf, **currSurf; - msurface_t **surfacesSorted; + int numSortedSurfaces, numSurfaces; + msurface_t *surface, **firstSurf, **lastSurf, **currSurf; + msurface_t **surfacesSorted; VBO_t *vbo; IBO_t *ibo; @@ -2060,14 +1920,13 @@ static void R_CreateWorldVBOs( world_t *worldData ) int maxVboSize = 64 * 1024 * 1024; int maxIboSize = 16 * 1024 * 1024; - int startTime, endTime; + int startTime, endTime; startTime = ri.Milliseconds(); // count surfaces numSortedSurfaces = 0; - for(surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) - { + for (surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) { srfBspSurface_t *bspSurf; shader_t *shader = surface->shader; @@ -2084,7 +1943,7 @@ static void R_CreateWorldVBOs( world_t *worldData ) if (!(*surface->data == SF_FACE || *surface->data == SF_GRID || *surface->data == SF_TRIANGLES)) continue; - bspSurf = (srfBspSurface_t *) surface->data; + bspSurf = (srfBspSurface_t *)surface->data; if (!bspSurf->numIndexes || !bspSurf->numVerts) continue; @@ -2096,8 +1955,7 @@ static void R_CreateWorldVBOs( world_t *worldData ) surfacesSorted = (msurface_t **)Z_Malloc(numSortedSurfaces * sizeof(*surfacesSorted), TAG_BSP); j = 0; - for(surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) - { + for (surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) { srfBspSurface_t *bspSurf; shader_t *shader = surface->shader; @@ -2114,7 +1972,7 @@ static void R_CreateWorldVBOs( world_t *worldData ) if (!(*surface->data == SF_FACE || *surface->data == SF_GRID || *surface->data == SF_TRIANGLES)) continue; - bspSurf = (srfBspSurface_t *) surface->data; + bspSurf = (srfBspSurface_t *)surface->data; if (!bspSurf->numIndexes || !bspSurf->numVerts) continue; @@ -2125,31 +1983,27 @@ static void R_CreateWorldVBOs( world_t *worldData ) qsort(surfacesSorted, numSortedSurfaces, sizeof(*surfacesSorted), BSPSurfaceCompare); k = 0; - for(firstSurf = lastSurf = surfacesSorted; firstSurf < &surfacesSorted[numSortedSurfaces]; firstSurf = lastSurf) - { + for (firstSurf = lastSurf = surfacesSorted; firstSurf < &surfacesSorted[numSortedSurfaces]; firstSurf = lastSurf) { int currVboSize, currIboSize; // Find range of surfaces to merge by: // - Collecting a number of surfaces which fit under maxVboSize/maxIboSize, or // - All the surfaces with a single shader which go over maxVboSize/maxIboSize currVboSize = currIboSize = 0; - while (currVboSize < maxVboSize && currIboSize < maxIboSize && lastSurf < &surfacesSorted[numSortedSurfaces]) - { + while (currVboSize < maxVboSize && currIboSize < maxIboSize && lastSurf < &surfacesSorted[numSortedSurfaces]) { int addVboSize, addIboSize, currShaderIndex; addVboSize = addIboSize = 0; currShaderIndex = (*lastSurf)->shader->sortedIndex; - for(currSurf = lastSurf; currSurf < &surfacesSorted[numSortedSurfaces] && (*currSurf)->shader->sortedIndex == currShaderIndex; currSurf++) - { - srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + for (currSurf = lastSurf; currSurf < &surfacesSorted[numSortedSurfaces] && (*currSurf)->shader->sortedIndex == currShaderIndex; currSurf++) { + srfBspSurface_t *bspSurf = (srfBspSurface_t *)(*currSurf)->data; addVboSize += bspSurf->numVerts * sizeof(srfVert_t); addIboSize += bspSurf->numIndexes * sizeof(glIndex_t); } - if ((currVboSize != 0 && addVboSize + currVboSize > maxVboSize) - || (currIboSize != 0 && addIboSize + currIboSize > maxIboSize)) + if ((currVboSize != 0 && addVboSize + currVboSize > maxVboSize) || (currIboSize != 0 && addIboSize + currIboSize > maxIboSize)) break; lastSurf = currSurf; @@ -2162,9 +2016,8 @@ static void R_CreateWorldVBOs( world_t *worldData ) numVerts = 0; numIndexes = 0; numSurfaces = 0; - for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) - { - srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) { + srfBspSurface_t *bspSurf = (srfBspSurface_t *)(*currSurf)->data; numVerts += bspSurf->numVerts; numIndexes += bspSurf->numIndexes; @@ -2180,17 +2033,15 @@ static void R_CreateWorldVBOs( world_t *worldData ) // set up indices and copy vertices numVerts = 0; numIndexes = 0; - for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) - { - srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) { + srfBspSurface_t *bspSurf = (srfBspSurface_t *)(*currSurf)->data; glIndex_t *surfIndex; bspSurf->firstIndex = numIndexes; bspSurf->minIndex = numVerts + bspSurf->indexes[0]; bspSurf->maxIndex = numVerts + bspSurf->indexes[0]; - for(i = 0, surfIndex = bspSurf->indexes; i < bspSurf->numIndexes; i++, surfIndex++) - { + for (i = 0, surfIndex = bspSurf->indexes; i < bspSurf->numIndexes; i++, surfIndex++) { indexes[numIndexes++] = numVerts + *surfIndex; bspSurf->minIndex = MIN(bspSurf->minIndex, numVerts + *surfIndex); bspSurf->maxIndex = MAX(bspSurf->maxIndex, numVerts + *surfIndex); @@ -2198,38 +2049,35 @@ static void R_CreateWorldVBOs( world_t *worldData ) bspSurf->firstVert = numVerts; - for(i = 0; i < bspSurf->numVerts; i++) - { - packedVertex_t& vert = verts[numVerts++]; + for (i = 0; i < bspSurf->numVerts; i++) { + packedVertex_t &vert = verts[numVerts++]; - VectorCopy (bspSurf->verts[i].xyz, vert.position); - vert.normal = R_VboPackNormal (bspSurf->verts[i].normal); + VectorCopy(bspSurf->verts[i].xyz, vert.position); + vert.normal = R_VboPackNormal(bspSurf->verts[i].normal); if (VectorLengthSquared(bspSurf->verts[i].tangent) > 0.001f) vert.tangent = R_VboPackTangent(bspSurf->verts[i].tangent); else vert.tangent = 0u; - VectorCopy2 (bspSurf->verts[i].st, vert.texcoords[0]); + VectorCopy2(bspSurf->verts[i].st, vert.texcoords[0]); - for (int j = 0; j < MAXLIGHTMAPS; j++) - { - VectorCopy2 (bspSurf->verts[i].lightmap[j], vert.texcoords[1 + j]); + for (int j = 0; j < MAXLIGHTMAPS; j++) { + VectorCopy2(bspSurf->verts[i].lightmap[j], vert.texcoords[1 + j]); } - for (int j = 0; j < MAXLIGHTMAPS; j++) - { - VectorCopy4 (bspSurf->verts[i].vertexColors[j], vert.colors[j]); + for (int j = 0; j < MAXLIGHTMAPS; j++) { + VectorCopy4(bspSurf->verts[i].vertexColors[j], vert.colors[j]); } - vert.lightDirection = R_VboPackNormal (bspSurf->verts[i].lightdir); + vert.lightDirection = R_VboPackNormal(bspSurf->verts[i].lightdir); } } - R_CalcMikkTSpaceBSPSurface(numIndexes/3, verts, indexes); + R_CalcMikkTSpaceBSPSurface(numIndexes / 3, verts, indexes); - vbo = R_CreateVBO((byte *)verts, sizeof (packedVertex_t) * numVerts, VBO_USAGE_STATIC); - ibo = R_CreateIBO((byte *)indexes, numIndexes * sizeof (glIndex_t), VBO_USAGE_STATIC); + vbo = R_CreateVBO((byte *)verts, sizeof(packedVertex_t) * numVerts, VBO_USAGE_STATIC); + ibo = R_CreateIBO((byte *)indexes, numIndexes * sizeof(glIndex_t), VBO_USAGE_STATIC); // Setup the offsets and strides vbo->offsets[ATTR_INDEX_POSITION] = offsetof(packedVertex_t, position); @@ -2267,9 +2115,8 @@ static void R_CreateWorldVBOs( world_t *worldData ) vbo->sizes[ATTR_INDEX_COLOR] = sizeof(verts->colors); // point bsp surfaces to VBO - for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) - { - srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) { + srfBspSurface_t *bspSurf = (srfBspSurface_t *)(*currSurf)->data; bspSurf->vbo = vbo; bspSurf->ibo = ibo; @@ -2292,14 +2139,14 @@ static void R_CreateWorldVBOs( world_t *worldData ) R_LoadSurfaces =============== */ -static void R_LoadSurfaces( world_t *worldData, lump_t *surfs, lump_t *verts, lump_t *indexLump ) { - dsurface_t *in; - msurface_t *out; - drawVert_t *dv; - int *indexes; - int count; - int numFaces, numMeshes, numTriSurfs, numFlares; - int i; +static void R_LoadSurfaces(world_t *worldData, lump_t *surfs, lump_t *verts, lump_t *indexLump) { + dsurface_t *in; + msurface_t *out; + drawVert_t *dv; + int *indexes; + int count; + int numFaces, numMeshes, numTriSurfs, numFlares; + int i; float *hdrVertColors = NULL; numFaces = 0; @@ -2308,39 +2155,37 @@ static void R_LoadSurfaces( world_t *worldData, lump_t *surfs, lump_t *verts, lu numFlares = 0; if (surfs->filelen % sizeof(*in)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); count = surfs->filelen / sizeof(*in); dv = (drawVert_t *)(fileBase + verts->fileofs); if (verts->filelen % sizeof(*dv)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); indexes = (int *)(fileBase + indexLump->fileofs); - if ( indexLump->filelen % sizeof(*indexes)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + if (indexLump->filelen % sizeof(*indexes)) + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); - out = (msurface_t *)ri.Hunk_Alloc ( count * sizeof(*out), h_low ); + out = (msurface_t *)ri.Hunk_Alloc(count * sizeof(*out), h_low); worldData->surfaces = out; worldData->numsurfaces = count; - worldData->surfacesViewCount = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesViewCount), h_low ); - worldData->surfacesDlightBits = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesDlightBits), h_low ); - worldData->surfacesPshadowBits = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesPshadowBits), h_low ); + worldData->surfacesViewCount = (int *)ri.Hunk_Alloc(count * sizeof(*worldData->surfacesViewCount), h_low); + worldData->surfacesDlightBits = (int *)ri.Hunk_Alloc(count * sizeof(*worldData->surfacesDlightBits), h_low); + worldData->surfacesPshadowBits = (int *)ri.Hunk_Alloc(count * sizeof(*worldData->surfacesPshadowBits), h_low); // load hdr vertex colors - if (r_hdr->integer) - { + if (r_hdr->integer) { char filename[MAX_QPATH]; int size; - Com_sprintf( filename, sizeof( filename ), "maps/%s/vertlight.raw", worldData->baseName); - //ri.Printf(PRINT_ALL, "looking for %s\n", filename); + Com_sprintf(filename, sizeof(filename), "maps/%s/vertlight.raw", worldData->baseName); + // ri.Printf(PRINT_ALL, "looking for %s\n", filename); size = ri.FS_ReadFile(filename, (void **)&hdrVertColors); - if (hdrVertColors) - { - //ri.Printf(PRINT_ALL, "Found!\n"); + if (hdrVertColors) { + // ri.Printf(PRINT_ALL, "Found!\n"); if (size != sizeof(float) * 3 * verts->filelen / sizeof(*dv)) ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)((sizeof(float)) * 3 * verts->filelen / sizeof(*dv))); } @@ -2352,45 +2197,43 @@ static void R_LoadSurfaces( world_t *worldData, lump_t *surfs, lump_t *verts, lu Com_sprintf(filename, sizeof(filename), "maps/%s.tspace", worldData->baseName); int size = ri.FS_ReadFile(filename, (void **)&tangentSpace); - if (tangentSpace) - { + if (tangentSpace) { assert(size == (verts->filelen / sizeof(*dv)) * sizeof(float) * 4); if (size != sizeof(tangentSpace[0]) * verts->filelen / sizeof(*dv)) ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)(sizeof(float) * 4 * verts->filelen / sizeof(*dv))); } - // Two passes, allocate surfaces first, then load them full of data // This ensures surfaces are close together to reduce L2 cache misses when using VBOs, // which don't actually use the verts and indexes in = (dsurface_t *)(fileBase + surfs->fileofs); out = worldData->surfaces; - for ( i = 0 ; i < count ; i++, in++, out++ ) { - switch ( LittleLong( in->surfaceType ) ) { - case MST_PATCH: - // FIXME: do this - break; - case MST_TRIANGLE_SOUP: - out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low); - break; - case MST_PLANAR: - out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low); - break; - case MST_FLARE: - out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfFlare_t), h_low); - break; - default: - break; + for (i = 0; i < count; i++, in++, out++) { + switch (LittleLong(in->surfaceType)) { + case MST_PATCH: + // FIXME: do this + break; + case MST_TRIANGLE_SOUP: + out->data = (surfaceType_t *)ri.Hunk_Alloc(sizeof(srfBspSurface_t), h_low); + break; + case MST_PLANAR: + out->data = (surfaceType_t *)ri.Hunk_Alloc(sizeof(srfBspSurface_t), h_low); + break; + case MST_FLARE: + out->data = (surfaceType_t *)ri.Hunk_Alloc(sizeof(srfFlare_t), h_low); + break; + default: + break; } } in = (dsurface_t *)(fileBase + surfs->fileofs); out = worldData->surfaces; - for ( i = 0 ; i < count ; i++, in++, out++ ) { - switch ( LittleLong( in->surfaceType ) ) { + for (i = 0; i < count; i++, in++, out++) { + switch (LittleLong(in->surfaceType)) { case MST_PATCH: - ParseMesh ( worldData, in, dv, tangentSpace, hdrVertColors, out ); + ParseMesh(worldData, in, dv, tangentSpace, hdrVertColors, out); { srfBspSurface_t *surface = (srfBspSurface_t *)out->data; @@ -2403,105 +2246,93 @@ static void R_LoadSurfaces( world_t *worldData, lump_t *surfs, lump_t *verts, lu numMeshes++; break; case MST_TRIANGLE_SOUP: - ParseTriSurf( worldData, in, dv, tangentSpace, hdrVertColors, out, indexes ); + ParseTriSurf(worldData, in, dv, tangentSpace, hdrVertColors, out, indexes); numTriSurfs++; break; case MST_PLANAR: - ParseFace( worldData, in, dv, tangentSpace, hdrVertColors, out, indexes ); + ParseFace(worldData, in, dv, tangentSpace, hdrVertColors, out, indexes); numFaces++; break; case MST_FLARE: - ParseFlare( worldData, in, dv, out, indexes ); - { - out->cullinfo.type = CULLINFO_NONE; - } + ParseFlare(worldData, in, dv, out, indexes); + { out->cullinfo.type = CULLINFO_NONE; } numFlares++; break; default: - ri.Error( ERR_DROP, "Bad surfaceType" ); + ri.Error(ERR_DROP, "Bad surfaceType"); } } - if (hdrVertColors) - { + if (hdrVertColors) { ri.FS_FreeFile(hdrVertColors); } - if ( r_patchStitching->integer ) { + if (r_patchStitching->integer) { R_StitchAllPatches(worldData); } R_FixSharedVertexLodError(worldData); - if ( r_patchStitching->integer ) { + if (r_patchStitching->integer) { R_MovePatchSurfacesToHunk(worldData); } - ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", - numFaces, numMeshes, numTriSurfs, numFlares ); + ri.Printf(PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", numFaces, numMeshes, numTriSurfs, numFlares); } - - /* ================= R_LoadSubmodels ================= */ -static void R_LoadSubmodels( world_t *worldData, int worldIndex, lump_t *l ) { - dmodel_t *in; - bmodel_t *out; - int i, j, count; +static void R_LoadSubmodels(world_t *worldData, int worldIndex, lump_t *l) { + dmodel_t *in; + bmodel_t *out; + int i, j, count; in = (dmodel_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); count = l->filelen / sizeof(*in); worldData->numBModels = count; - worldData->bmodels = out = (bmodel_t *)ri.Hunk_Alloc( count * sizeof(*out), h_low ); + worldData->bmodels = out = (bmodel_t *)ri.Hunk_Alloc(count * sizeof(*out), h_low); - for ( i=0 ; itype = MOD_BRUSH; model->data.bmodel = out; - if (worldIndex >= 0) - { - Com_sprintf( model->name, sizeof( model->name ), "*%d-%d", worldIndex, i ); - } - else - { - Com_sprintf( model->name, sizeof( model->name ), "*%d", i ); + if (worldIndex >= 0) { + Com_sprintf(model->name, sizeof(model->name), "*%d-%d", worldIndex, i); + } else { + Com_sprintf(model->name, sizeof(model->name), "*%d", i); } - for (j=0 ; j<3 ; j++) { - out->bounds[0][j] = LittleFloat (in->mins[j]); - out->bounds[1][j] = LittleFloat (in->maxs[j]); + for (j = 0; j < 3; j++) { + out->bounds[0][j] = LittleFloat(in->mins[j]); + out->bounds[1][j] = LittleFloat(in->maxs[j]); } CModelCache->InsertModelHandle(model->name, model->index); out->worldIndex = worldIndex; - out->firstSurface = LittleLong( in->firstSurface ); - out->numSurfaces = LittleLong( in->numSurfaces ); + out->firstSurface = LittleLong(in->firstSurface); + out->numSurfaces = LittleLong(in->numSurfaces); - if (i == 0) - { + if (i == 0) { // Add this for limiting VBO surface creation worldData->numWorldSurfaces = out->numSurfaces; } } } - - //================================================================== /* @@ -2509,13 +2340,12 @@ static void R_LoadSubmodels( world_t *worldData, int worldIndex, lump_t *l ) { R_SetParent ================= */ -static void R_SetParent (mnode_t *node, mnode_t *parent) -{ +static void R_SetParent(mnode_t *node, mnode_t *parent) { node->parent = parent; if (node->contents != -1) return; - R_SetParent (node->children[0], node); - R_SetParent (node->children[1], node); + R_SetParent(node->children[0], node); + R_SetParent(node->children[1], node); } /* @@ -2523,44 +2353,40 @@ static void R_SetParent (mnode_t *node, mnode_t *parent) R_LoadNodesAndLeafs ================= */ -static void R_LoadNodesAndLeafs (world_t *worldData, lump_t *nodeLump, lump_t *leafLump) { - int i, j, p; - dnode_t *in; - dleaf_t *inLeaf; - mnode_t *out; - int numNodes, numLeafs; +static void R_LoadNodesAndLeafs(world_t *worldData, lump_t *nodeLump, lump_t *leafLump) { + int i, j, p; + dnode_t *in; + dleaf_t *inLeaf; + mnode_t *out; + int numNodes, numLeafs; in = (dnode_t *)(fileBase + nodeLump->fileofs); - if (nodeLump->filelen % sizeof(dnode_t) || - leafLump->filelen % sizeof(dleaf_t) ) { - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + if (nodeLump->filelen % sizeof(dnode_t) || leafLump->filelen % sizeof(dleaf_t)) { + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); } numNodes = nodeLump->filelen / sizeof(dnode_t); numLeafs = leafLump->filelen / sizeof(dleaf_t); - out = (mnode_t *)ri.Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), h_low); + out = (mnode_t *)ri.Hunk_Alloc((numNodes + numLeafs) * sizeof(*out), h_low); worldData->nodes = out; worldData->numnodes = numNodes + numLeafs; worldData->numDecisionNodes = numNodes; // load nodes - for ( i=0 ; imins[j] = LittleLong (in->mins[j]); - out->maxs[j] = LittleLong (in->maxs[j]); + for (i = 0; i < numNodes; i++, in++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(in->mins[j]); + out->maxs[j] = LittleLong(in->maxs[j]); } p = LittleLong(in->planeNum); out->plane = worldData->planes + p; - out->contents = CONTENTS_NODE; // differentiate from leafs + out->contents = CONTENTS_NODE; // differentiate from leafs - for (j=0 ; j<2 ; j++) - { - p = LittleLong (in->children[j]); + for (j = 0; j < 2; j++) { + p = LittleLong(in->children[j]); if (p >= 0) out->children[j] = worldData->nodes + p; else @@ -2570,18 +2396,16 @@ static void R_LoadNodesAndLeafs (world_t *worldData, lump_t *nodeLump, lump_t *l // load leafs inLeaf = (dleaf_t *)(fileBase + leafLump->fileofs); - for ( i=0 ; imins[j] = LittleLong (inLeaf->mins[j]); - out->maxs[j] = LittleLong (inLeaf->maxs[j]); + for (i = 0; i < numLeafs; i++, inLeaf++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(inLeaf->mins[j]); + out->maxs[j] = LittleLong(inLeaf->maxs[j]); } out->cluster = LittleLong(inLeaf->cluster); out->area = LittleLong(inLeaf->area); - if ( out->cluster >= worldData->numClusters ) { + if (out->cluster >= worldData->numClusters) { worldData->numClusters = out->cluster + 1; } @@ -2590,7 +2414,7 @@ static void R_LoadNodesAndLeafs (world_t *worldData, lump_t *nodeLump, lump_t *l } // chain decendants - R_SetParent (worldData->nodes, NULL); + R_SetParent(worldData->nodes, NULL); } //============================================================================= @@ -2600,88 +2424,84 @@ static void R_LoadNodesAndLeafs (world_t *worldData, lump_t *nodeLump, lump_t *l R_LoadShaders ================= */ -static void R_LoadShaders( world_t *worldData, lump_t *l ) { - int i, count; - dshader_t *in, *out; +static void R_LoadShaders(world_t *worldData, lump_t *l) { + int i, count; + dshader_t *in, *out; in = (dshader_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); count = l->filelen / sizeof(*in); - out = (dshader_t *)ri.Hunk_Alloc ( count*sizeof(*out), h_low ); + out = (dshader_t *)ri.Hunk_Alloc(count * sizeof(*out), h_low); worldData->shaders = out; worldData->numShaders = count; - Com_Memcpy( out, in, count*sizeof(*out) ); + Com_Memcpy(out, in, count * sizeof(*out)); - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); count = l->filelen / sizeof(*in); - out = (int *)ri.Hunk_Alloc ( count*sizeof(*out), h_low); + out = (int *)ri.Hunk_Alloc(count * sizeof(*out), h_low); worldData->marksurfaces = out; worldData->nummarksurfaces = count; - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); count = l->filelen / sizeof(*in); - out = (cplane_t *)ri.Hunk_Alloc ( count*2*sizeof(*out), h_low); + out = (cplane_t *)ri.Hunk_Alloc(count * 2 * sizeof(*out), h_low); worldData->planes = out; worldData->numplanes = count; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + for (j = 0; j < 3; j++) { + out->normal[j] = LittleFloat(in->normal[j]); if (out->normal[j] < 0) { - bits |= 1<dist = LittleFloat (in->dist); - out->type = PlaneTypeForNormal( out->normal ); + out->dist = LittleFloat(in->dist); + out->type = PlaneTypeForNormal(out->normal); out->signbits = bits; } } @@ -2692,145 +2512,136 @@ R_LoadFogs ================= */ -static void R_LoadFogs( world_t *worldData, lump_t *l, lump_t *brushesLump, lump_t *sidesLump ) { - int i; - fog_t *out; - dfog_t *fogs; - dbrush_t *brushes, *brush; - dbrushside_t *sides; - int count, brushesCount, sidesCount; - int sideNum; - int planeNum; - shader_t *shader; - float d; - int firstSide; +static void R_LoadFogs(world_t *worldData, lump_t *l, lump_t *brushesLump, lump_t *sidesLump) { + int i; + fog_t *out; + dfog_t *fogs; + dbrush_t *brushes, *brush; + dbrushside_t *sides; + int count, brushesCount, sidesCount; + int sideNum; + int planeNum; + shader_t *shader; + float d; + int firstSide; fogs = (dfog_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*fogs)) { - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); } count = l->filelen / sizeof(*fogs); // create fog strucutres for them worldData->numfogs = count + 1; - worldData->fogs = (fog_t *)ri.Hunk_Alloc ( worldData->numfogs*sizeof(*out), h_low); + worldData->fogs = (fog_t *)ri.Hunk_Alloc(worldData->numfogs * sizeof(*out), h_low); worldData->globalFog = nullptr; worldData->globalFogIndex = -1; out = worldData->fogs + 1; - if ( !count ) { + if (!count) { return; } brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); if (brushesLump->filelen % sizeof(*brushes)) { - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); } brushesCount = brushesLump->filelen / sizeof(*brushes); sides = (dbrushside_t *)(fileBase + sidesLump->fileofs); if (sidesLump->filelen % sizeof(*sides)) { - ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); } sidesCount = sidesLump->filelen / sizeof(*sides); - for ( i=0 ; ioriginalBrushNumber = LittleLong( fogs->brushNum ); + for (i = 0; i < count; i++, fogs++) { + out->originalBrushNumber = LittleLong(fogs->brushNum); - if ( out->originalBrushNumber == -1 ) - { + if (out->originalBrushNumber == -1) { out->bounds[0][0] = out->bounds[0][1] = out->bounds[0][2] = MIN_WORLD_COORD; out->bounds[1][0] = out->bounds[1][1] = out->bounds[1][2] = MAX_WORLD_COORD; firstSide = -1; worldData->globalFog = worldData->fogs + i + 1; worldData->globalFogIndex = i + 1; - } - else - { - if ( (unsigned)out->originalBrushNumber >= brushesCount ) { - ri.Error( ERR_DROP, "fog brushNumber out of range" ); + } else { + if ((unsigned)out->originalBrushNumber >= brushesCount) { + ri.Error(ERR_DROP, "fog brushNumber out of range"); } brush = brushes + out->originalBrushNumber; - firstSide = LittleLong( brush->firstSide ); + firstSide = LittleLong(brush->firstSide); - if ( (unsigned)firstSide > sidesCount - 6 ) { - ri.Error( ERR_DROP, "fog brush sideNumber out of range" ); + if ((unsigned)firstSide > sidesCount - 6) { + ri.Error(ERR_DROP, "fog brush sideNumber out of range"); } // brushes are always sorted with the axial sides first sideNum = firstSide + 0; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][0] = -worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][0] = -worldData->planes[planeNum].dist; sideNum = firstSide + 1; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][0] = worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][0] = worldData->planes[planeNum].dist; sideNum = firstSide + 2; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][1] = -worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][1] = -worldData->planes[planeNum].dist; sideNum = firstSide + 3; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][1] = worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][1] = worldData->planes[planeNum].dist; sideNum = firstSide + 4; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][2] = -worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][2] = -worldData->planes[planeNum].dist; sideNum = firstSide + 5; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][2] = worldData->planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][2] = worldData->planes[planeNum].dist; } // get information from the shader for fog parameters - shader = R_FindShader( fogs->shader, lightmapsNone, stylesDefault, qtrue ); + shader = R_FindShader(fogs->shader, lightmapsNone, stylesDefault, qtrue); - if (shader->defaultShader == qtrue || shader->fogParms.depthForOpaque == 0) - { + if (shader->defaultShader == qtrue || shader->fogParms.depthForOpaque == 0) { ri.Printf(PRINT_WARNING, "Couldn't find proper shader for bsp fog %i %s\n", i, fogs->shader); shader->fogParms.depthForOpaque = 65535.f; } out->parms = shader->fogParms; - VectorSet4(out->color, - shader->fogParms.color[0] * tr.identityLight, - shader->fogParms.color[1] * tr.identityLight, - shader->fogParms.color[2] * tr.identityLight, - 1.0); + VectorSet4(out->color, shader->fogParms.color[0] * tr.identityLight, shader->fogParms.color[1] * tr.identityLight, + shader->fogParms.color[2] * tr.identityLight, 1.0); d = shader->fogParms.depthForOpaque < 1 ? 1 : shader->fogParms.depthForOpaque; out->tcScale = 1.0f / d; // set the gradient vector - sideNum = LittleLong( fogs->visibleSide ); + sideNum = LittleLong(fogs->visibleSide); out->hasSurface = (out->originalBrushNumber == -1) ? qfalse : qtrue; - if ( sideNum != -1 ) { - planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum ); - VectorSubtract( vec3_origin, worldData->planes[ planeNum ].normal, out->surface ); - out->surface[3] = -worldData->planes[ planeNum ].dist; + if (sideNum != -1) { + planeNum = LittleLong(sides[firstSide + sideNum].planeNum); + VectorSubtract(vec3_origin, worldData->planes[planeNum].normal, out->surface); + out->surface[3] = -worldData->planes[planeNum].dist; } out++; } - } - /* ================ R_LoadLightGrid ================ */ -void R_LoadLightGrid( world_t *worldData, lump_t *l ) { - int i; - vec3_t maxs; - float *wMins, *wMaxs; +void R_LoadLightGrid(world_t *worldData, lump_t *l) { + int i; + vec3_t maxs; + float *wMins, *wMaxs; worldData->lightGridInverseSize[0] = 1.0f / worldData->lightGridSize[0]; worldData->lightGridInverseSize[1] = 1.0f / worldData->lightGridSize[1]; @@ -2839,55 +2650,46 @@ void R_LoadLightGrid( world_t *worldData, lump_t *l ) { wMins = worldData->bmodels[0].bounds[0]; wMaxs = worldData->bmodels[0].bounds[1]; - for ( i = 0 ; i < 3 ; i++ ) { - worldData->lightGridOrigin[i] = worldData->lightGridSize[i] * ceil( wMins[i] / worldData->lightGridSize[i] ); - maxs[i] = worldData->lightGridSize[i] * floor( wMaxs[i] / worldData->lightGridSize[i] ); - worldData->lightGridBounds[i] = (maxs[i] - worldData->lightGridOrigin[i])/worldData->lightGridSize[i] + 1; + for (i = 0; i < 3; i++) { + worldData->lightGridOrigin[i] = worldData->lightGridSize[i] * ceil(wMins[i] / worldData->lightGridSize[i]); + maxs[i] = worldData->lightGridSize[i] * floor(wMaxs[i] / worldData->lightGridSize[i]); + worldData->lightGridBounds[i] = (maxs[i] - worldData->lightGridOrigin[i]) / worldData->lightGridSize[i] + 1; } int numGridDataElements = l->filelen / sizeof(*worldData->lightGridData); - worldData->lightGridData = (mgrid_t *)ri.Hunk_Alloc( l->filelen, h_low ); - Com_Memcpy( worldData->lightGridData, (void *)(fileBase + l->fileofs), l->filelen ); + worldData->lightGridData = (mgrid_t *)ri.Hunk_Alloc(l->filelen, h_low); + Com_Memcpy(worldData->lightGridData, (void *)(fileBase + l->fileofs), l->filelen); // deal with overbright bits - for ( i = 0 ; i < numGridDataElements ; i++ ) - { - for(int j = 0; j < MAXLIGHTMAPS; j++) - { - R_ColorShiftLightingBytes( - worldData->lightGridData[i].ambientLight[j], - worldData->lightGridData[i].ambientLight[j]); - R_ColorShiftLightingBytes( - worldData->lightGridData[i].directLight[j], - worldData->lightGridData[i].directLight[j]); + for (i = 0; i < numGridDataElements; i++) { + for (int j = 0; j < MAXLIGHTMAPS; j++) { + R_ColorShiftLightingBytes(worldData->lightGridData[i].ambientLight[j], worldData->lightGridData[i].ambientLight[j]); + R_ColorShiftLightingBytes(worldData->lightGridData[i].directLight[j], worldData->lightGridData[i].directLight[j]); } } // load hdr lightgrid - if (r_hdr->integer) - { + if (r_hdr->integer) { char filename[MAX_QPATH]; float *hdrLightGrid; int size; - Com_sprintf( filename, sizeof( filename ), "maps/%s/lightgrid.raw", worldData->baseName); - //ri.Printf(PRINT_ALL, "looking for %s\n", filename); + Com_sprintf(filename, sizeof(filename), "maps/%s/lightgrid.raw", worldData->baseName); + // ri.Printf(PRINT_ALL, "looking for %s\n", filename); size = ri.FS_ReadFile(filename, (void **)&hdrLightGrid); - if (hdrLightGrid) - { - if (size != sizeof(float) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]) - { - ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)(sizeof(float)) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]); + if (hdrLightGrid) { + if (size != sizeof(float) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]) { + ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, + (int)(sizeof(float)) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]); } worldData->hdrLightGrid = (float *)ri.Hunk_Alloc(size, h_low); - for (i = 0; i < worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]; i++) - { - worldData->hdrLightGrid[i * 6 ] = hdrLightGrid[i * 6 ] / M_PI; + for (i = 0; i < worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]; i++) { + worldData->hdrLightGrid[i * 6] = hdrLightGrid[i * 6] / M_PI; worldData->hdrLightGrid[i * 6 + 1] = hdrLightGrid[i * 6 + 1] / M_PI; worldData->hdrLightGrid[i * 6 + 2] = hdrLightGrid[i * 6 + 2] / M_PI; worldData->hdrLightGrid[i * 6 + 3] = hdrLightGrid[i * 6 + 3] / M_PI; @@ -2907,17 +2709,17 @@ R_LoadLightGridArray ================ */ -void R_LoadLightGridArray( world_t *worldData, lump_t *l ) { +void R_LoadLightGridArray(world_t *worldData, lump_t *l) { worldData->numGridArrayElements = worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]; - if ( (unsigned)l->filelen != worldData->numGridArrayElements * sizeof(*worldData->lightGridArray) ) { - Com_Printf (S_COLOR_YELLOW "WARNING: light grid array mismatch\n" ); + if ((unsigned)l->filelen != worldData->numGridArrayElements * sizeof(*worldData->lightGridArray)) { + Com_Printf(S_COLOR_YELLOW "WARNING: light grid array mismatch\n"); worldData->lightGridData = NULL; return; } - worldData->lightGridArray = (unsigned short *)Hunk_Alloc( l->filelen, h_low ); - memcpy( worldData->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen ); + worldData->lightGridArray = (unsigned short *)Hunk_Alloc(l->filelen, h_low); + memcpy(worldData->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen); } /* @@ -2925,58 +2727,58 @@ void R_LoadLightGridArray( world_t *worldData, lump_t *l ) { R_LoadEntities ================ */ -void R_LoadEntities( world_t *worldData, lump_t *l ) { +void R_LoadEntities(world_t *worldData, lump_t *l) { const char *p; char *token, *s; char vertexRemapShaderText[] = "vertexremapshader"; char remapShaderText[] = "remapshader"; char keyname[MAX_TOKEN_CHARS]; char value[MAX_TOKEN_CHARS]; - world_t *w; + world_t *w; w = worldData; w->lightGridSize[0] = 64; w->lightGridSize[1] = 64; w->lightGridSize[2] = 128; - tr.distanceCull = 6000;//DEFAULT_DISTANCE_CULL; + tr.distanceCull = 6000; // DEFAULT_DISTANCE_CULL; p = (char *)(fileBase + l->fileofs); // store for reference by the cgame - w->entityString = (char *)ri.Hunk_Alloc( l->filelen + 1, h_low ); - strcpy( w->entityString, p ); + w->entityString = (char *)ri.Hunk_Alloc(l->filelen + 1, h_low); + strcpy(w->entityString, p); w->entityParsePoint = w->entityString; - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); if (!*token || *token != '{') { return; } // only parse the world spawn - while ( 1 ) { + while (1) { // parse key - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(keyname, token, sizeof(keyname)); // parse value - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(value, token, sizeof(value)); // check for remapping of shaders for vertex lighting s = vertexRemapShaderText; - if (!Q_strncmp(keyname, s, strlen(s)) ) { + if (!Q_strncmp(keyname, s, strlen(s))) { s = strchr(value, ';'); if (!s) { - ri.Printf( PRINT_WARNING, "WARNING: no semi colon in vertexshaderremap '%s'\n", value ); + ri.Printf(PRINT_WARNING, "WARNING: no semi colon in vertexshaderremap '%s'\n", value); break; } *s++ = 0; @@ -2987,23 +2789,23 @@ void R_LoadEntities( world_t *worldData, lump_t *l ) { } // check for remapping of shaders s = remapShaderText; - if (!Q_strncmp(keyname, s, strlen(s)) ) { + if (!Q_strncmp(keyname, s, strlen(s))) { s = strchr(value, ';'); if (!s) { - ri.Printf( PRINT_WARNING, "WARNING: no semi colon in shaderremap '%s'\n", value ); + ri.Printf(PRINT_WARNING, "WARNING: no semi colon in shaderremap '%s'\n", value); break; } *s++ = 0; R_RemapShader(value, s, "0"); continue; } - if (!Q_stricmp(keyname, "distanceCull")) { - sscanf(value, "%f", &tr.distanceCull ); + if (!Q_stricmp(keyname, "distanceCull")) { + sscanf(value, "%f", &tr.distanceCull); continue; } // check for a different grid size if (!Q_stricmp(keyname, "gridsize")) { - sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] ); + sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2]); continue; } @@ -3020,19 +2822,18 @@ void R_LoadEntities( world_t *worldData, lump_t *l ) { R_GetEntityToken ================= */ -qboolean R_GetEntityToken( char *buffer, int size ) { - char *s; +qboolean R_GetEntityToken(char *buffer, int size) { + char *s; world_t *worldData = &s_worldData; - if (size == -1) - { //force reset + if (size == -1) { // force reset worldData->entityParsePoint = worldData->entityString; return qtrue; } - s = COM_Parse( (const char **)&worldData->entityParsePoint ); - Q_strncpyz( buffer, s, size ); - if ( !worldData->entityParsePoint && !s[0] ) { + s = COM_Parse((const char **)&worldData->entityParsePoint); + Q_strncpyz(buffer, s, size); + if (!worldData->entityParsePoint && !s[0]) { worldData->entityParsePoint = worldData->entityString; return qfalse; } else { @@ -3045,69 +2846,67 @@ qboolean R_GetEntityToken( char *buffer, int size ) { #endif // derived from G_ParseSpawnVars() in g_spawn.c -static qboolean R_ParseSpawnVars( char *spawnVarChars, int maxSpawnVarChars, int *numSpawnVars, char *spawnVars[MAX_SPAWN_VARS][2] ) -{ - char keyname[MAX_TOKEN_CHARS]; - char com_token[MAX_TOKEN_CHARS]; - int numSpawnVarChars = 0; +static qboolean R_ParseSpawnVars(char *spawnVarChars, int maxSpawnVarChars, int *numSpawnVars, char *spawnVars[MAX_SPAWN_VARS][2]) { + char keyname[MAX_TOKEN_CHARS]; + char com_token[MAX_TOKEN_CHARS]; + int numSpawnVarChars = 0; *numSpawnVars = 0; // parse the opening brace - if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) { + if (!R_GetEntityToken(com_token, sizeof(com_token))) { // end of spawn string return qfalse; } - if ( com_token[0] != '{' ) { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: found %s when expecting {\n",com_token ); + if (com_token[0] != '{') { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: found %s when expecting {\n", com_token); return qfalse; } // go through all the key / value pairs - while ( 1 ) { + while (1) { int keyLength, tokenLength; // parse key - if ( !R_GetEntityToken( keyname, sizeof( keyname ) ) ) { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" ); + if (!R_GetEntityToken(keyname, sizeof(keyname))) { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n"); return qfalse; } - if ( keyname[0] == '}' ) { + if (keyname[0] == '}') { break; } // parse value - if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" ); + if (!R_GetEntityToken(com_token, sizeof(com_token))) { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n"); return qfalse; } - if ( com_token[0] == '}' ) { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: closing brace without data\n" ); + if (com_token[0] == '}') { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: closing brace without data\n"); return qfalse; } - if ( *numSpawnVars == MAX_SPAWN_VARS ) { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VARS\n" ); + if (*numSpawnVars == MAX_SPAWN_VARS) { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VARS\n"); return qfalse; } keyLength = strlen(keyname) + 1; tokenLength = strlen(com_token) + 1; - if (numSpawnVarChars + keyLength + tokenLength > maxSpawnVarChars) - { - ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VAR_CHARS\n" ); + if (numSpawnVarChars + keyLength + tokenLength > maxSpawnVarChars) { + ri.Printf(PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VAR_CHARS\n"); return qfalse; } strcpy(spawnVarChars + numSpawnVarChars, keyname); - spawnVars[ *numSpawnVars ][0] = spawnVarChars + numSpawnVarChars; + spawnVars[*numSpawnVars][0] = spawnVarChars + numSpawnVarChars; numSpawnVarChars += keyLength; strcpy(spawnVarChars + numSpawnVarChars, com_token); - spawnVars[ *numSpawnVars ][1] = spawnVarChars + numSpawnVarChars; + spawnVars[*numSpawnVars][1] = spawnVarChars + numSpawnVarChars; numSpawnVarChars += tokenLength; (*numSpawnVars)++; @@ -3116,8 +2915,7 @@ static qboolean R_ParseSpawnVars( char *spawnVarChars, int maxSpawnVarChars, int return qtrue; } -void R_LoadEnvironmentJson(const char *baseName) -{ +void R_LoadEnvironmentJson(const char *baseName) { char filename[MAX_QPATH]; union { @@ -3138,23 +2936,20 @@ void R_LoadEnvironmentJson(const char *baseName) ri.Printf(PRINT_ALL, "Loaded Enviroment JSON: %s\n", filename); - if (JSON_ValueGetType(buffer.c, bufferEnd) != JSONTYPE_OBJECT) - { + if (JSON_ValueGetType(buffer.c, bufferEnd) != JSONTYPE_OBJECT) { ri.Printf(PRINT_ALL, "Bad %s: does not start with a object\n", filename); ri.FS_FreeFile(buffer.v); return; } //-----------------------------CUBEMAPS------------------------------------ environmentArrayJson = JSON_ObjectGetNamedValue(buffer.c, bufferEnd, "Cubemaps"); - if (!environmentArrayJson) - { + if (!environmentArrayJson) { ri.Printf(PRINT_ALL, "Bad %s: no Cubemaps\n", filename); ri.FS_FreeFile(buffer.v); return; } - if (JSON_ValueGetType(environmentArrayJson, bufferEnd) != JSONTYPE_ARRAY) - { + if (JSON_ValueGetType(environmentArrayJson, bufferEnd) != JSONTYPE_ARRAY) { ri.Printf(PRINT_ALL, "Bad %s: Cubemaps not an array\n", filename); ri.FS_FreeFile(buffer.v); return; @@ -3163,8 +2958,7 @@ void R_LoadEnvironmentJson(const char *baseName) tr.numCubemaps = JSON_ArrayGetIndex(environmentArrayJson, bufferEnd, NULL, 0); tr.cubemaps = (cubemap_t *)ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low); - for (i = 0; i < tr.numCubemaps; i++) - { + for (i = 0; i < tr.numCubemaps; i++) { cubemap_t *cubemap = &tr.cubemaps[i]; const char *cubemapJson, *keyValueJson, *indexes[3]; int j; @@ -3189,8 +2983,7 @@ void R_LoadEnvironmentJson(const char *baseName) ri.FS_FreeFile(buffer.v); } -void R_LoadCubemapEntities(const char *cubemapEntityName) -{ +void R_LoadCubemapEntities(const char *cubemapEntityName) { char spawnVarChars[2048]; int numSpawnVars; char *spawnVars[MAX_SPAWN_VARS][2]; @@ -3198,12 +2991,10 @@ void R_LoadCubemapEntities(const char *cubemapEntityName) // count cubemaps numCubemaps = 0; - while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) - { + while (R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) { int i; - for (i = 0; i < numSpawnVars; i++) - { + for (i = 0; i < numSpawnVars; i++) { if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName)) numCubemaps++; } @@ -3216,8 +3007,7 @@ void R_LoadCubemapEntities(const char *cubemapEntityName) tr.cubemaps = (cubemap_t *)ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low); numCubemaps = 0; - while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) - { + while (R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) { int i; char name[MAX_QPATH]; qboolean isCubemap = qfalse; @@ -3226,27 +3016,22 @@ void R_LoadCubemapEntities(const char *cubemapEntityName) float parallaxRadius = 1000.0f; name[0] = '\0'; - for (i = 0; i < numSpawnVars; i++) - { + for (i = 0; i < numSpawnVars; i++) { if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName)) isCubemap = qtrue; if (!Q_stricmp(spawnVars[i][0], "name")) Q_strncpyz(name, spawnVars[i][1], MAX_QPATH); - if (!Q_stricmp(spawnVars[i][0], "origin")) - { + if (!Q_stricmp(spawnVars[i][0], "origin")) { sscanf(spawnVars[i][1], "%f %f %f", &origin[0], &origin[1], &origin[2]); originSet = qtrue; - } - else if (!Q_stricmp(spawnVars[i][0], "radius")) - { + } else if (!Q_stricmp(spawnVars[i][0], "radius")) { sscanf(spawnVars[i][1], "%f", ¶llaxRadius); } } - if (isCubemap && originSet) - { + if (isCubemap && originSet) { cubemap_t *cubemap = &tr.cubemaps[numCubemaps]; Q_strncpyz(cubemap->name, name, MAX_QPATH); VectorCopy(origin, cubemap->origin); @@ -3257,60 +3042,47 @@ void R_LoadCubemapEntities(const char *cubemapEntityName) } } -static void R_AssignCubemapsToWorldSurfaces(world_t *worldData) -{ - world_t *w; +static void R_AssignCubemapsToWorldSurfaces(world_t *worldData) { + world_t *w; int i; w = worldData; - for (i = 0; i < w->numsurfaces; i++) - { + for (i = 0; i < w->numsurfaces; i++) { msurface_t *surf = &w->surfaces[i]; vec3_t surfOrigin; - if (surf->cullinfo.type & CULLINFO_SPHERE) - { + if (surf->cullinfo.type & CULLINFO_SPHERE) { VectorCopy(surf->cullinfo.localOrigin, surfOrigin); - } - else if (surf->cullinfo.type & CULLINFO_BOX) - { + } else if (surf->cullinfo.type & CULLINFO_BOX) { surfOrigin[0] = (surf->cullinfo.bounds[0][0] + surf->cullinfo.bounds[1][0]) * 0.5f; surfOrigin[1] = (surf->cullinfo.bounds[0][1] + surf->cullinfo.bounds[1][1]) * 0.5f; surfOrigin[2] = (surf->cullinfo.bounds[0][2] + surf->cullinfo.bounds[1][2]) * 0.5f; - } - else - { - //ri.Printf(PRINT_ALL, "surface %d has no cubemap\n", i); + } else { + // ri.Printf(PRINT_ALL, "surface %d has no cubemap\n", i); continue; } surf->cubemapIndex = R_CubemapForPoint(surfOrigin); - //ri.Printf(PRINT_ALL, "surface %d has cubemap %d\n", i, surf->cubemapIndex); + // ri.Printf(PRINT_ALL, "surface %d has cubemap %d\n", i, surf->cubemapIndex); } } - -static void R_RenderAllCubemaps() -{ +static void R_RenderAllCubemaps() { R_IssuePendingRenderCommands(); R_InitNextFrame(); GLenum cubemapFormat = GL_RGBA8; - if (r_hdr->integer) - { + if (r_hdr->integer) { cubemapFormat = GL_RGBA16F; } - for (int k = 0; k <= r_cubeMappingBounces->integer; k++) - { + for (int k = 0; k <= r_cubeMappingBounces->integer; k++) { bool bounce = k != 0; // Limit number of Cubemaps per map int maxCubemaps = MIN(tr.numCubemaps, 128); - for (int i = 0; i < maxCubemaps; i++) - { - for (int j = 0; j < 6; j++) - { + for (int i = 0; i < maxCubemaps; i++) { + for (int j = 0; j < 6; j++) { R_RenderCubemapSide(i, j, bounce); } @@ -3320,12 +3092,10 @@ static void R_RenderAllCubemaps() } } - -void R_LoadWeatherZones(world_t *worldData, lump_t *brushesLump, lump_t *sidesLump) -{ - dbrush_t *brushes; - dbrushside_t *sides; - int brushesCount, sidesCount; +void R_LoadWeatherZones(world_t *worldData, lump_t *brushesLump, lump_t *sidesLump) { + dbrush_t *brushes; + dbrushside_t *sides; + int brushesCount, sidesCount; brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); if (brushesLump->filelen % sizeof(*brushes)) { @@ -3351,15 +3121,13 @@ void R_LoadWeatherZones(world_t *worldData, lump_t *brushesLump, lump_t *sidesLu if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_NONE) tr.weatherSystem->weatherBrushType = currentBrushType; - if (tr.weatherSystem->weatherBrushType != currentBrushType) - { + if (tr.weatherSystem->weatherBrushType != currentBrushType) { Com_Error(ERR_DROP, "Weather Effect: Both Indoor and Outdoor brushs encountered in map.\n"); return; } vec4_t planes[64]; - for (int j = 0; j < brushes->numSides; j++) - { + for (int j = 0; j < brushes->numSides; j++) { int currentSideIndex = brushes->firstSide + j; int currentPlaneIndex = sides[currentSideIndex].planeNum; planes[j][0] = worldData->planes[currentPlaneIndex].normal[0]; @@ -3372,7 +3140,6 @@ void R_LoadWeatherZones(world_t *worldData, lump_t *brushesLump, lump_t *sidesLu } } - /* ================= R_MergeLeafSurfaces @@ -3380,8 +3147,7 @@ R_MergeLeafSurfaces Merges surfaces that share a common leaf ================= */ -static void R_MergeLeafSurfaces(world_t *worldData) -{ +static void R_MergeLeafSurfaces(world_t *worldData) { int i, j, k; int numWorldSurfaces; int mergedSurfIndex; @@ -3402,18 +3168,15 @@ static void R_MergeLeafSurfaces(world_t *worldData) numWorldSurfaces = worldData->numWorldSurfaces; // use viewcount to keep track of mergers - for (i = 0; i < numWorldSurfaces; i++) - { + for (i = 0; i < numWorldSurfaces; i++) { worldData->surfacesViewCount[i] = -1; } // mark matching surfaces - for (i = 0; i < worldData->numnodes - worldData->numDecisionNodes; i++) - { + for (i = 0; i < worldData->numnodes - worldData->numDecisionNodes; i++) { mnode_t *leaf = worldData->nodes + worldData->numDecisionNodes + i; - for (j = 0; j < leaf->nummarksurfaces; j++) - { + for (j = 0; j < leaf->nummarksurfaces; j++) { msurface_t *surf1; shader_t *shader1; int fogIndex1; @@ -3427,22 +3190,19 @@ static void R_MergeLeafSurfaces(world_t *worldData) surf1 = worldData->surfaces + surfNum1; - if ((*surf1->data != SF_GRID) && - (*surf1->data != SF_TRIANGLES) && - (*surf1->data != SF_FACE)) - { + if ((*surf1->data != SF_GRID) && (*surf1->data != SF_TRIANGLES) && (*surf1->data != SF_FACE)) { continue; } shader1 = surf1->shader; - if(shader1->isSky) + if (shader1->isSky) continue; - if(shader1->isPortal) + if (shader1->isPortal) continue; - if(ShaderRequiresCPUDeforms(shader1)) + if (ShaderRequiresCPUDeforms(shader1)) continue; fogIndex1 = surf1->fogIndex; @@ -3450,8 +3210,7 @@ static void R_MergeLeafSurfaces(world_t *worldData) worldData->surfacesViewCount[surfNum1] = surfNum1; - for (k = j + 1; k < leaf->nummarksurfaces; k++) - { + for (k = j + 1; k < leaf->nummarksurfaces; k++) { msurface_t *surf2; shader_t *shader2; int fogIndex2; @@ -3465,9 +3224,7 @@ static void R_MergeLeafSurfaces(world_t *worldData) surf2 = worldData->surfaces + surfNum2; - if ((*surf2->data != SF_GRID) && - (*surf2->data != SF_TRIANGLES) && - (*surf2->data != SF_FACE)) + if ((*surf2->data != SF_GRID) && (*surf2->data != SF_TRIANGLES) && (*surf2->data != SF_FACE)) continue; shader2 = surf2->shader; @@ -3491,20 +3248,17 @@ static void R_MergeLeafSurfaces(world_t *worldData) } // don't add surfaces that don't merge to any others to the merged list - for (i = 0; i < numWorldSurfaces; i++) - { + for (i = 0; i < numWorldSurfaces; i++) { qboolean merges = qfalse; if (worldData->surfacesViewCount[i] != i) continue; - for (j = 0; j < numWorldSurfaces; j++) - { + for (j = 0; j < numWorldSurfaces; j++) { if (j == i) continue; - if (worldData->surfacesViewCount[j] == i) - { + if (worldData->surfacesViewCount[j] == i) { merges = qtrue; break; } @@ -3517,42 +3271,27 @@ static void R_MergeLeafSurfaces(world_t *worldData) // count merged/unmerged surfaces numMergedSurfaces = 0; numUnmergedSurfaces = 0; - for (i = 0; i < numWorldSurfaces; i++) - { - if (worldData->surfacesViewCount[i] == i) - { + for (i = 0; i < numWorldSurfaces; i++) { + if (worldData->surfacesViewCount[i] == i) { numMergedSurfaces++; - } - else if (worldData->surfacesViewCount[i] == -1) - { + } else if (worldData->surfacesViewCount[i] == -1) { numUnmergedSurfaces++; } } // Allocate merged surfaces - worldData->mergedSurfaces = - (msurface_t *)ri.Hunk_Alloc( - sizeof(*worldData->mergedSurfaces) * numMergedSurfaces, h_low); - worldData->mergedSurfacesViewCount = - (int *)ri.Hunk_Alloc( - sizeof(*worldData->mergedSurfacesViewCount) * numMergedSurfaces, h_low); - worldData->mergedSurfacesDlightBits = - (int *)ri.Hunk_Alloc( - sizeof(*worldData->mergedSurfacesDlightBits) * numMergedSurfaces, h_low); - worldData->mergedSurfacesPshadowBits = - (int *)ri.Hunk_Alloc( - sizeof(*worldData->mergedSurfacesPshadowBits) * numMergedSurfaces, h_low); + worldData->mergedSurfaces = (msurface_t *)ri.Hunk_Alloc(sizeof(*worldData->mergedSurfaces) * numMergedSurfaces, h_low); + worldData->mergedSurfacesViewCount = (int *)ri.Hunk_Alloc(sizeof(*worldData->mergedSurfacesViewCount) * numMergedSurfaces, h_low); + worldData->mergedSurfacesDlightBits = (int *)ri.Hunk_Alloc(sizeof(*worldData->mergedSurfacesDlightBits) * numMergedSurfaces, h_low); + worldData->mergedSurfacesPshadowBits = (int *)ri.Hunk_Alloc(sizeof(*worldData->mergedSurfacesPshadowBits) * numMergedSurfaces, h_low); worldData->numMergedSurfaces = numMergedSurfaces; // view surfaces are like mark surfaces, except negative ones represent merged surfaces // -1 represents 0, -2 represents 1, and so on - worldData->viewSurfaces = - (int *)ri.Hunk_Alloc( - sizeof(*worldData->viewSurfaces) * worldData->nummarksurfaces, h_low); + worldData->viewSurfaces = (int *)ri.Hunk_Alloc(sizeof(*worldData->viewSurfaces) * worldData->nummarksurfaces, h_low); // copy view surfaces into mark surfaces - for (i = 0; i < worldData->nummarksurfaces; i++) - { + for (i = 0; i < worldData->nummarksurfaces; i++) { worldData->viewSurfaces[i] = worldData->marksurfaces[i]; } @@ -3563,8 +3302,7 @@ static void R_MergeLeafSurfaces(world_t *worldData) numIboIndexes = 0; mergedSurfIndex = 0; mergedSurf = worldData->mergedSurfaces; - for (i = 0; i < numWorldSurfaces; i++) - { + for (i = 0; i < numWorldSurfaces; i++) { msurface_t *surf1; vec3_t bounds[2]; @@ -3588,8 +3326,7 @@ static void R_MergeLeafSurfaces(world_t *worldData) numSurfsToMerge = 0; numIndexes = 0; numVerts = 0; - for (j = i; j < numWorldSurfaces; j++) - { + for (j = i; j < numWorldSurfaces; j++) { msurface_t *surf2; srfBspSurface_t *bspSurf; @@ -3598,30 +3335,28 @@ static void R_MergeLeafSurfaces(world_t *worldData) surf2 = worldData->surfaces + j; - bspSurf = (srfBspSurface_t *) surf2->data; + bspSurf = (srfBspSurface_t *)surf2->data; numIndexes += bspSurf->numIndexes; numVerts += bspSurf->numVerts; numSurfsToMerge++; } - if (numVerts == 0 || numIndexes == 0 || numSurfsToMerge < 2) - { + if (numVerts == 0 || numIndexes == 0 || numSurfsToMerge < 2) { continue; } // create ibo - ibo = tr.ibos[tr.numIBOs++] = (IBO_t*)ri.Hunk_Alloc(sizeof(*ibo), h_low); + ibo = tr.ibos[tr.numIBOs++] = (IBO_t *)ri.Hunk_Alloc(sizeof(*ibo), h_low); memset(ibo, 0, sizeof(*ibo)); numIboIndexes = 0; // allocate indexes - iboIndexes = outIboIndexes = (glIndex_t*)Z_Malloc(numIndexes * sizeof(*outIboIndexes), TAG_BSP); + iboIndexes = outIboIndexes = (glIndex_t *)Z_Malloc(numIndexes * sizeof(*outIboIndexes), TAG_BSP); // Merge surfaces (indexes) and calculate bounds ClearBounds(bounds[0], bounds[1]); firstIndex = numIboIndexes; - for (j = i; j < numWorldSurfaces; j++) - { + for (j = i; j < numWorldSurfaces; j++) { msurface_t *surf2; srfBspSurface_t *bspSurf; @@ -3633,9 +3368,8 @@ static void R_MergeLeafSurfaces(world_t *worldData) AddPointToBounds(surf2->cullinfo.bounds[0], bounds[0], bounds[1]); AddPointToBounds(surf2->cullinfo.bounds[1], bounds[0], bounds[1]); - bspSurf = (srfBspSurface_t *) surf2->data; - for (k = 0; k < bspSurf->numIndexes; k++) - { + bspSurf = (srfBspSurface_t *)surf2->data; + for (k = 0; k < bspSurf->numIndexes; k++) { *outIboIndexes++ = bspSurf->indexes[k] + bspSurf->firstVert; numIboIndexes++; } @@ -3656,8 +3390,7 @@ static void R_MergeLeafSurfaces(world_t *worldData) vboSurf->minIndex = *(iboIndexes + firstIndex); vboSurf->maxIndex = *(iboIndexes + firstIndex); - for (j = 0; j < numIndexes; j++) - { + for (j = 0; j < numIndexes; j++) { vboSurf->minIndex = MIN(vboSurf->minIndex, *(iboIndexes + firstIndex + j)); vboSurf->maxIndex = MAX(vboSurf->maxIndex, *(iboIndexes + firstIndex + j)); } @@ -3669,10 +3402,10 @@ static void R_MergeLeafSurfaces(world_t *worldData) VectorCopy(bounds[1], mergedSurf->cullinfo.bounds[1]); mergedSurf->cullinfo.type = CULLINFO_BOX; - mergedSurf->data = (surfaceType_t *)vboSurf; - mergedSurf->fogIndex = surf1->fogIndex; - mergedSurf->cubemapIndex = surf1->cubemapIndex; - mergedSurf->shader = surf1->shader; + mergedSurf->data = (surfaceType_t *)vboSurf; + mergedSurf->fogIndex = surf1->fogIndex; + mergedSurf->cubemapIndex = surf1->cubemapIndex; + mergedSurf->shader = surf1->shader; // finish up the ibo qglGenBuffers(1, &ibo->indexesVBO); @@ -3683,16 +3416,14 @@ static void R_MergeLeafSurfaces(world_t *worldData) GL_CheckErrors(); - Z_Free(iboIndexes); + Z_Free(iboIndexes); // redirect view surfaces to this surf - for (j = 0; j < numWorldSurfaces; j++) - { + for (j = 0; j < numWorldSurfaces; j++) { if (worldData->surfacesViewCount[j] != i) continue; - for (k = 0; k < worldData->nummarksurfaces; k++) - { + for (k = 0; k < worldData->nummarksurfaces; k++) { int *mark = worldData->marksurfaces + k; int *view = worldData->viewSurfaces + k; @@ -3707,48 +3438,38 @@ static void R_MergeLeafSurfaces(world_t *worldData) endTime = ri.Milliseconds(); - ri.Printf(PRINT_ALL, "Processed %d surfaces into %d merged, %d unmerged in %5.2f seconds\n", - numWorldSurfaces, numMergedSurfaces, numUnmergedSurfaces, (endTime - startTime) / 1000.0f); + ri.Printf(PRINT_ALL, "Processed %d surfaces into %d merged, %d unmerged in %5.2f seconds\n", numWorldSurfaces, numMergedSurfaces, numUnmergedSurfaces, + (endTime - startTime) / 1000.0f); // reset viewcounts - for (i = 0; i < numWorldSurfaces; i++) - { + for (i = 0; i < numWorldSurfaces; i++) { worldData->surfacesViewCount[i] = -1; } } - -static void R_CalcVertexLightDirs( world_t *worldData ) -{ +static void R_CalcVertexLightDirs(world_t *worldData) { int i, k; msurface_t *surface; - for(k = 0, surface = &worldData->surfaces[0]; k < worldData->numsurfaces /* worldData->numWorldSurfaces */; k++, surface++) - { - srfBspSurface_t *bspSurf = (srfBspSurface_t *) surface->data; + for (k = 0, surface = &worldData->surfaces[0]; k < worldData->numsurfaces /* worldData->numWorldSurfaces */; k++, surface++) { + srfBspSurface_t *bspSurf = (srfBspSurface_t *)surface->data; - switch(bspSurf->surfaceType) - { - case SF_FACE: - case SF_GRID: - case SF_TRIANGLES: - for(i = 0; i < bspSurf->numVerts; i++) - R_LightDirForPoint( - bspSurf->verts[i].xyz, - bspSurf->verts[i].lightdir, - bspSurf->verts[i].normal, - worldData ); + switch (bspSurf->surfaceType) { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + for (i = 0; i < bspSurf->numVerts; i++) + R_LightDirForPoint(bspSurf->verts[i].xyz, bspSurf->verts[i].lightdir, bspSurf->verts[i].normal, worldData); - break; + break; - default: - break; + default: + break; } } } -struct sprite_t -{ +struct sprite_t { vec4_t position; vec3_t normal; vec3_t color; @@ -3756,33 +3477,29 @@ struct sprite_t vec2_t skew; }; -static uint32_t UpdateHash( const char *text, uint32_t hash ) -{ - for ( int i = 0; text[i]; ++i ) - { +static uint32_t UpdateHash(const char *text, uint32_t hash) { + for (int i = 0; text[i]; ++i) { char letter = tolower((unsigned char)text[i]); - if (letter == '.') break; // don't include extension - if (letter == '\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names - hash += (uint32_t)(letter)*(i+119); + hash += (uint32_t)(letter) * (i + 119); } return (hash ^ (hash >> 10) ^ (hash >> 20)); } -static uint32_t R_CountSurfaceSprites( - const srfBspSurface_t *bspSurf, - float density, - const shaderStage_t *stage) -{ +static uint32_t R_CountSurfaceSprites(const srfBspSurface_t *bspSurf, float density, const shaderStage_t *stage) { uint32_t numStageSprites = 0; const srfVert_t *verts = bspSurf->verts; const glIndex_t *indexes = bspSurf->indexes; - for (int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3) - { + for (int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3) { const srfVert_t *v0 = verts + indexes[i + 0]; const srfVert_t *v1 = verts + indexes[i + 1]; const srfVert_t *v2 = verts + indexes[i + 2]; @@ -3792,21 +3509,18 @@ static uint32_t R_CountSurfaceSprites( VectorCopy(v1->xyz, p1); VectorCopy(v2->xyz, p2); - const vec2_t p01 = { p1[0] - p0[0], p1[1] - p0[1] }; - const vec2_t p02 = { p2[0] - p0[0], p2[1] - p0[1] }; + const vec2_t p01 = {p1[0] - p0[0], p1[1] - p0[1]}; + const vec2_t p02 = {p2[0] - p0[0], p2[1] - p0[1]}; const float zarea = std::fabs(p02[0] * p01[1] - p02[1] * p01[0]); - if (zarea <= 1.0) - { + if (zarea <= 1.0) { // Triangle's area is too small to consider. continue; } const float step = density * Q_rsqrt(zarea); - for (float a = 0.0f; a < 1.0f; a += step) - { - for (float b = 0.0f, bend = (1.0f - a); b < bend; b += step) - { + for (float a = 0.0f; a < 1.0f; a += step) { + for (float b = 0.0f, bend = (1.0f - a); b < bend; b += step) { numStageSprites += 1; } } @@ -3814,31 +3528,21 @@ static uint32_t R_CountSurfaceSprites( return numStageSprites; } -static int R_CreateSurfaceSpritesVertexData( - const srfBspSurface_t *bspSurf, - float density, - const shaderStage_t *stage, - std::vector *sprites) -{ +static int R_CreateSurfaceSpritesVertexData(const srfBspSurface_t *bspSurf, float density, const shaderStage_t *stage, std::vector *sprites) { const srfVert_t *verts = bspSurf->verts; const glIndex_t *indexes = bspSurf->indexes; - vec4_t color = { 1.0, 1.0, 1.0, 1.0 }; - if (stage->rgbGen == CGEN_CONST) - { + vec4_t color = {1.0, 1.0, 1.0, 1.0}; + if (stage->rgbGen == CGEN_CONST) { color[0] = stage->constantColor[0]; color[1] = stage->constantColor[1]; color[2] = stage->constantColor[2]; } - bool vertexLit = ( - stage->rgbGen == CGEN_VERTEX || - stage->rgbGen == CGEN_EXACT_VERTEX || - stage->rgbGen == CGEN_VERTEX_LIT || - stage->rgbGen == CGEN_EXACT_VERTEX_LIT); + bool vertexLit = + (stage->rgbGen == CGEN_VERTEX || stage->rgbGen == CGEN_EXACT_VERTEX || stage->rgbGen == CGEN_VERTEX_LIT || stage->rgbGen == CGEN_EXACT_VERTEX_LIT); int numSprites = 0; - for ( int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3 ) - { + for (int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3) { const srfVert_t *v0 = verts + indexes[i + 0]; const srfVert_t *v1 = verts + indexes[i + 1]; const srfVert_t *v2 = verts + indexes[i + 2]; @@ -3861,9 +3565,8 @@ static int R_CreateSurfaceSpritesVertexData( const vec2_t p01 = {p1[0] - p0[0], p1[1] - p0[1]}; const vec2_t p02 = {p2[0] - p0[0], p2[1] - p0[1]}; - const float zarea = std::fabs(p02[0]*p01[1] - p02[1]*p01[0]); - if ( zarea <= 1.0 ) - { + const float zarea = std::fabs(p02[0] * p01[1] - p02[1] * p01[0]); + if (zarea <= 1.0) { // Triangle's area is too small to consider. continue; } @@ -3873,17 +3576,17 @@ static int R_CreateSurfaceSpritesVertexData( // Pick random points inside of each triangle, using barycentric // coordinates. const float step = density * Q_rsqrt(zarea); - for ( float a = 0.0f; a < 1.0f; a += step ) - { - for ( float b = 0.0f, bend = (1.0f - a); b < bend; b += step ) - { - float x = flrand(0.0f, 1.0f)*step + a; - float y = flrand(0.0f, 1.0f)*step + b; + for (float a = 0.0f; a < 1.0f; a += step) { + for (float b = 0.0f, bend = (1.0f - a); b < bend; b += step) { + float x = flrand(0.0f, 1.0f) * step + a; + float y = flrand(0.0f, 1.0f) * step + b; float z = 1.0f - x - y; // Ensure we're inside the triangle bounds. - if ( x > 1.0f ) continue; - if ( (x + y ) > 1.0f ) continue; + if (x > 1.0f) + continue; + if ((x + y) > 1.0f) + continue; // Calculate position inside triangle. // pos = (((p0*x) + p1*y) + p2*z) @@ -3893,27 +3596,25 @@ static int R_CreateSurfaceSpritesVertexData( VectorMA(sprite.position, z, p2, sprite.position); sprite.position[3] = flrand(0.0f, 1.0f); - if (vertexLit) - { + if (vertexLit) { VectorMA(sprite.color, x, c0, sprite.color); VectorMA(sprite.color, y, c1, sprite.color); VectorMA(sprite.color, z, c2, sprite.color); VectorScale(sprite.color, tr.identityLight, sprite.color); - } - else + } else VectorCopy(color, sprite.color); // x*x + y*y = 1.0 // => y*y = 1.0 - x*x // => y = -/+sqrt(1.0 - x*x) float nx = flrand(-1.0f, 1.0f); - float ny = std::sqrt(1.0f - nx*nx); + float ny = std::sqrt(1.0f - nx * nx); ny *= irand(0, 1) ? -1 : 1; VectorSet(sprite.normal, nx, ny, 0.0f); - sprite.widthHeight[0] = stage->ss->width*(1.0f + (stage->ss->variance[0] * flrand(0.0f, 1.0f))); - sprite.widthHeight[1] = stage->ss->height*(1.0f + (stage->ss->variance[1] * flrand(0.0f, 1.0f))); + sprite.widthHeight[0] = stage->ss->width * (1.0f + (stage->ss->variance[0] * flrand(0.0f, 1.0f))); + sprite.widthHeight[1] = stage->ss->height * (1.0f + (stage->ss->variance[1] * flrand(0.0f, 1.0f))); if (stage->ss->facing == SURFSPRITE_FACING_DOWN) sprite.widthHeight[1] *= -1.0f; @@ -3931,25 +3632,19 @@ static int R_CreateSurfaceSpritesVertexData( return numSprites; } -static void R_GenerateSurfaceSprites( - const srfBspSurface_t *bspSurf, - const shader_t *shader, - const shaderStage_t *stage, - const int fogIndex, - srfSprites_t *out, - std::vector *sprites) -{ +static void R_GenerateSurfaceSprites(const srfBspSurface_t *bspSurf, const shader_t *shader, const shaderStage_t *stage, const int fogIndex, srfSprites_t *out, + std::vector *sprites) { const surfaceSprite_t *surfaceSprite = stage->ss; const textureBundle_t *bundle = &stage->bundle[0]; uint32_t hash = 0; - for ( int i = 0; bundle->image[i]; ++i ) + for (int i = 0; bundle->image[i]; ++i) hash = UpdateHash(bundle->image[i]->imgName, hash); out->baseVertex = sprites->size(); out->surfaceType = SF_SPRITES; out->sprite = surfaceSprite; - //R_CreateSurfaceSpritesVertexData(bspSurf, surfaceSprite->density, stage, sprites); + // R_CreateSurfaceSpritesVertexData(bspSurf, surfaceSprite->density, stage, sprites); out->numSprites = R_CreateSurfaceSpritesVertexData(bspSurf, surfaceSprite->density, stage, sprites); out->numIndices = out->numSprites * 6; out->fogIndex = fogIndex; @@ -3958,8 +3653,7 @@ static void R_GenerateSurfaceSprites( out->ibo = NULL; // FIXME: Need a better way to handle this. - out->shader = R_CreateShaderFromTextureBundle(va("*ss_%08x\n", hash), - bundle, stage->stateBits); + out->shader = R_CreateShaderFromTextureBundle(va("*ss_%08x\n", hash), bundle, stage->stateBits); out->shader->spriteUbo = shader->spriteUbo; out->shader->cullType = shader->cullType; @@ -3967,8 +3661,7 @@ static void R_GenerateSurfaceSprites( out->alphaTestType = stage->alphaTestType; out->numAttributes = 4; - out->attributes = (vertexAttribute_t *)ri.Hunk_Alloc( - sizeof(vertexAttribute_t) * out->numAttributes, h_low); + out->attributes = (vertexAttribute_t *)ri.Hunk_Alloc(sizeof(vertexAttribute_t) * out->numAttributes, h_low); out->attributes[0].vbo = out->vbo; out->attributes[0].index = ATTR_INDEX_POSITION; @@ -4011,11 +3704,9 @@ static void R_GenerateSurfaceSprites( out->attributes[3].stepRate = 0; } -static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) -{ +static void R_GenerateSurfaceSprites(const world_t *world, int worldIndex) { int numSpriteStages = 0; - for (int i = 0; i < tr.numShaders; i++) - { + for (int i = 0; i < tr.numShaders; i++) { const shader_t *shader = tr.shaders[i]; if (shader->spriteUbo != NULL) continue; @@ -4026,33 +3717,25 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) if (numSpriteStages == 0) return; - //TODO: put into backend + // TODO: put into backend const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; size_t spriteAlignedBlockSize = (sizeof(SurfaceSpriteBlock) + alignment) & ~alignment; - if (glState.currentGlobalUBO != tr.spriteUbos[worldIndex]) - { + if (glState.currentGlobalUBO != tr.spriteUbos[worldIndex]) { qglBindBuffer(GL_UNIFORM_BUFFER, tr.spriteUbos[worldIndex]); glState.currentGlobalUBO = tr.spriteUbos[worldIndex]; } - qglBufferData( - GL_UNIFORM_BUFFER, - numSpriteStages * spriteAlignedBlockSize, - nullptr, - GL_STATIC_DRAW); + qglBufferData(GL_UNIFORM_BUFFER, numSpriteStages * spriteAlignedBlockSize, nullptr, GL_STATIC_DRAW); size_t alignedBlockSize = 0; - for (int i = 0; i < tr.numShaders; i++) - { + for (int i = 0; i < tr.numShaders; i++) { shader_t *shader = tr.shaders[i]; if (!shader->numSurfaceSpriteStages) continue; shader->spriteUbo = tr.spriteUbos[worldIndex]; - for (int j = 0, numStages = shader->numUnfoggedPasses; - j < numStages; ++j) - { + for (int j = 0, numStages = shader->numUnfoggedPasses; j < numStages; ++j) { const shaderStage_t *stage = shader->stages[j]; if (!stage) break; @@ -4060,8 +3743,7 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) if (!stage->ss || stage->ss->type == SURFSPRITE_NONE) continue; - if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) - { + if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) { continue; } @@ -4080,8 +3762,7 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) surfaceSpriteBlock.fxAlphaEnd = ss->fxAlphaEnd; ss->spriteUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, ss->spriteUboOffset, sizeof(SurfaceSpriteBlock), &surfaceSpriteBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, ss->spriteUboOffset, sizeof(SurfaceSpriteBlock), &surfaceSpriteBlock); alignedBlockSize += spriteAlignedBlockSize; } } @@ -4093,9 +3774,8 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) { std::vector sprites_index_data; sprites_index_data.reserve(98298); - for (int i = 0; i < 98299; i++) - { - const uint16_t face_indices[] = { 0, 1, 2, 0, 2, 3 }; + for (int i = 0; i < 98299; i++) { + const uint16_t face_indices[] = {0, 1, 2, 0, 2, 3}; int vert_index = face_indices[i % 6] + (int(i / 6) * 4); sprites_index_data.push_back(vert_index); } @@ -4105,84 +3785,72 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) std::vector currentBatch; currentBatch.reserve(65535); // worst case, theres at least 65535 surfaces with exactly one sprite - for ( int i = 0, numSurfaces = world->numsurfaces; i < numSurfaces; ++i ) - { + for (int i = 0, numSurfaces = world->numsurfaces; i < numSurfaces; ++i) { msurface_t *surf = surfaces + i; const srfBspSurface_t *bspSurf = (srfBspSurface_t *)surf->data; - switch ( bspSurf->surfaceType ) - { - case SF_FACE: - case SF_GRID: - case SF_TRIANGLES: - { - const shader_t *shader = surf->shader; - if ( !shader->numSurfaceSpriteStages ) - continue; - - surf->numSurfaceSprites = shader->numSurfaceSpriteStages; - surf->surfaceSprites = (srfSprites_t *)ri.Hunk_Alloc( - sizeof(srfSprites_t) * surf->numSurfaceSprites, h_low); + switch (bspSurf->surfaceType) { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: { + const shader_t *shader = surf->shader; + if (!shader->numSurfaceSpriteStages) + continue; - int surfaceSpriteNum = 0; - for ( int j = 0, numStages = shader->numUnfoggedPasses; - j < numStages; ++j ) - { - const shaderStage_t *stage = shader->stages[j]; - if ( !stage ) - break; + surf->numSurfaceSprites = shader->numSurfaceSpriteStages; + surf->surfaceSprites = (srfSprites_t *)ri.Hunk_Alloc(sizeof(srfSprites_t) * surf->numSurfaceSprites, h_low); - if ( !stage->ss || stage->ss->type == SURFSPRITE_NONE ) - continue; + int surfaceSpriteNum = 0; + for (int j = 0, numStages = shader->numUnfoggedPasses; j < numStages; ++j) { + const shaderStage_t *stage = shader->stages[j]; + if (!stage) + break; - if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) - { - ri.Printf(PRINT_WARNING, "depthFunc equal is not supported on surface sprites in rend2. Skipping stage\n"); - surf->numSurfaceSprites -= 1; - continue; - } + if (!stage->ss || stage->ss->type == SURFSPRITE_NONE) + continue; - srfSprites_t *sprite = surf->surfaceSprites + surfaceSpriteNum; - int numCurrentSurfaceSprites = R_CountSurfaceSprites(bspSurf, stage->ss->density, stage); - if ((sprites_data.size() + numCurrentSurfaceSprites * 4) > 65535) - { - VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), - sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); - - for (srfSprites_t *sp : currentBatch) - { - sp->vbo = vbo; - sp->ibo = ibo; - sp->attributes[0].vbo = vbo; - sp->attributes[1].vbo = vbo; - sp->attributes[2].vbo = vbo; - sp->attributes[3].vbo = vbo; - } + if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) { + ri.Printf(PRINT_WARNING, "depthFunc equal is not supported on surface sprites in rend2. Skipping stage\n"); + surf->numSurfaceSprites -= 1; + continue; + } - sprites_data.clear(); - currentBatch.clear(); + srfSprites_t *sprite = surf->surfaceSprites + surfaceSpriteNum; + int numCurrentSurfaceSprites = R_CountSurfaceSprites(bspSurf, stage->ss->density, stage); + if ((sprites_data.size() + numCurrentSurfaceSprites * 4) > 65535) { + VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); + + for (srfSprites_t *sp : currentBatch) { + sp->vbo = vbo; + sp->ibo = ibo; + sp->attributes[0].vbo = vbo; + sp->attributes[1].vbo = vbo; + sp->attributes[2].vbo = vbo; + sp->attributes[3].vbo = vbo; } - R_GenerateSurfaceSprites(bspSurf, shader, stage, surf->fogIndex, sprite, &sprites_data); - currentBatch.push_back(sprite); - - ++surfaceSpriteNum; + sprites_data.clear(); + currentBatch.clear(); } - break; + + R_GenerateSurfaceSprites(bspSurf, shader, stage, surf->fogIndex, sprite, &sprites_data); + currentBatch.push_back(sprite); + + ++surfaceSpriteNum; } + break; + } - default: - break; + default: + break; } } if (sprites_data.size() == 0) return; - VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), - sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); + VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); - for (srfSprites_t *sp : currentBatch) - { + for (srfSprites_t *sp : currentBatch) { sp->vbo = vbo; sp->ibo = ibo; sp->attributes[0].vbo = vbo; @@ -4192,8 +3860,7 @@ static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) } } -world_t *R_LoadBSP(const char *name, int *bspIndex) -{ +world_t *R_LoadBSP(const char *name, int *bspIndex) { union { byte *b; void *v; @@ -4201,14 +3868,10 @@ world_t *R_LoadBSP(const char *name, int *bspIndex) world_t *worldData; int worldIndex = -1; - if (bspIndex == nullptr) - { + if (bspIndex == nullptr) { worldData = &s_worldData; - } - else - { - if (tr.numBspModels >= MAX_SUB_BSP) - { + } else { + if (tr.numBspModels >= MAX_SUB_BSP) { // too many return nullptr; } @@ -4221,12 +3884,10 @@ world_t *R_LoadBSP(const char *name, int *bspIndex) } // load it - ri.FS_ReadFile(name, &buffer.v); - if (!buffer.b) - { - if (bspIndex == nullptr) - { - ri.Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name); + ri.FS_ReadFile(name, &buffer.v); + if (!buffer.b) { + if (bspIndex == nullptr) { + ri.Error(ERR_DROP, "RE_LoadWorldMap: %s not found", name); } return nullptr; @@ -4245,40 +3906,22 @@ world_t *R_LoadBSP(const char *name, int *bspIndex) fileBase = (byte *)header; int bspVersion = LittleLong(header->version); - if (bspVersion != BSP_VERSION) - { - ri.Error( - ERR_DROP, - "R_LoadBSP: %s has wrong version number (%i should be %i)", - name, - bspVersion, - BSP_VERSION); + if (bspVersion != BSP_VERSION) { + ri.Error(ERR_DROP, "R_LoadBSP: %s has wrong version number (%i should be %i)", name, bspVersion, BSP_VERSION); } // swap all the lumps - for (int i = 0; i < sizeof(dheader_t) / 4; ++i) - { - ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + for (int i = 0; i < sizeof(dheader_t) / 4; ++i) { + ((int *)header)[i] = LittleLong(((int *)header)[i]); } // load into heap R_LoadEntities(worldData, &header->lumps[LUMP_ENTITIES]); R_LoadShaders(worldData, &header->lumps[LUMP_SHADERS]); - R_LoadLightmaps( - worldData, - &header->lumps[LUMP_LIGHTMAPS], - &header->lumps[LUMP_SURFACES]); + R_LoadLightmaps(worldData, &header->lumps[LUMP_LIGHTMAPS], &header->lumps[LUMP_SURFACES]); R_LoadPlanes(worldData, &header->lumps[LUMP_PLANES]); - R_LoadFogs( - worldData, - &header->lumps[LUMP_FOGS], - &header->lumps[LUMP_BRUSHES], - &header->lumps[LUMP_BRUSHSIDES]); - R_LoadSurfaces( - worldData, - &header->lumps[LUMP_SURFACES], - &header->lumps[LUMP_DRAWVERTS], - &header->lumps[LUMP_DRAWINDEXES]); + R_LoadFogs(worldData, &header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES]); + R_LoadSurfaces(worldData, &header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES]); R_LoadMarksurfaces(worldData, &header->lumps[LUMP_LEAFSURFACES]); R_LoadNodesAndLeafs(worldData, &header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS]); R_LoadSubmodels(worldData, worldIndex, &header->lumps[LUMP_MODELS]); @@ -4290,50 +3933,36 @@ world_t *R_LoadBSP(const char *name, int *bspIndex) R_CalcVertexLightDirs(worldData); if (bspIndex == nullptr) - R_LoadWeatherZones( - worldData, - &header->lumps[LUMP_BRUSHES], - &header->lumps[LUMP_BRUSHSIDES]); + R_LoadWeatherZones(worldData, &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES]); R_GenerateSurfaceSprites(worldData, worldIndex + 1); // load cubemaps - if (r_cubeMapping->integer && bspIndex == nullptr) - { + if (r_cubeMapping->integer && bspIndex == nullptr) { // Try loading an env.json file first R_LoadEnvironmentJson(worldData->baseName); const int numCubemapEntities = 5; - const char *cubemapEntities[numCubemapEntities] = - { - "misc_cubemap", - "info_player_deathmatch", - "info_player_start", - "info_player_duel", - "info_player_intermission", + const char *cubemapEntities[numCubemapEntities] = { + "misc_cubemap", "info_player_deathmatch", "info_player_start", "info_player_duel", "info_player_intermission", }; - if (!tr.numCubemaps) - { - for (int i = 0; i < numCubemapEntities; i++) - { + if (!tr.numCubemaps) { + for (int i = 0; i < numCubemapEntities; i++) { R_LoadCubemapEntities(cubemapEntities[i]); if (tr.numCubemaps) break; } - } - if (tr.numCubemaps) - { + if (tr.numCubemaps) { R_AssignCubemapsToWorldSurfaces(worldData); } } // create static VBOS from the world R_CreateWorldVBOs(worldData); - if (r_mergeLeafSurfaces->integer) - { + if (r_mergeLeafSurfaces->integer) { R_MergeLeafSurfaces(worldData); } @@ -4355,14 +3984,13 @@ RE_LoadWorldMap Called directly from cgame ================= */ -void RE_LoadWorldMap( const char *name ) { - if (tr.worldMapLoaded) - { +void RE_LoadWorldMap(const char *name) { + if (tr.worldMapLoaded) { ri.Error(ERR_DROP, "ERROR: attempted to redundantly load world map"); } // set default map light scale - tr.mapLightScale = 1.0f; + tr.mapLightScale = 1.0f; tr.sunShadowScale = 0.5f; // set default sun color to be used if it isn't @@ -4390,16 +4018,14 @@ void RE_LoadWorldMap( const char *name ) { tr.explicitToneMap = false; world_t *world = R_LoadBSP(name); - if (world == nullptr) - { + if (world == nullptr) { // clear tr.world so the next/ try will not look at the partially // loaded version tr.world = nullptr; return; } - if (r_hdr->integer && tr.hdrLighting && !tr.explicitToneMap) - { + if (r_hdr->integer && tr.hdrLighting && !tr.explicitToneMap) { tr.toneMinAvgMaxLevel[0] = -8.0f; tr.toneMinAvgMaxLevel[1] = 0.0f; tr.toneMinAvgMaxLevel[2] = 2.0f; @@ -4411,8 +4037,7 @@ void RE_LoadWorldMap( const char *name ) { R_InitWeatherForMap(); // Render all cubemaps - if (r_cubeMapping->integer && tr.numCubemaps) - { + if (r_cubeMapping->integer && tr.numCubemaps) { R_RenderAllCubemaps(); } } diff --git a/codemp/rd-rend2/tr_cache.cpp b/codemp/rd-rend2/tr_cache.cpp index 4b546f90c9..7caab1e936 100644 --- a/codemp/rd-rend2/tr_cache.cpp +++ b/codemp/rd-rend2/tr_cache.cpp @@ -4,71 +4,47 @@ #include "tr_cache.h" #include -namespace -{ +namespace { -void NormalizePath( char *out, const char *path, size_t outSize ) -{ +void NormalizePath(char *out, const char *path, size_t outSize) { assert(outSize == MAX_QPATH); Q_strncpyz(out, path, outSize); Q_strlwr(out); } -} +} // namespace // This differs significantly from Raven's own caching code. // For starters, we are allowed to use ri-> whatever because we don't care about running on dedicated (use rd-vanilla!) CModelCacheManager *CModelCache = new CModelCacheManager(); -CachedFile::CachedFile() - : pDiskImage(nullptr) - , iLevelLastUsedOn(0) - , iPAKChecksum(-1) - , iAllocSize(0) -{ -} +CachedFile::CachedFile() : pDiskImage(nullptr), iLevelLastUsedOn(0), iPAKChecksum(-1), iAllocSize(0) {} -CModelCacheManager::FileCache::iterator CModelCacheManager::FindFile( const char *path ) -{ - return std::find_if( - std::begin(files), std::end(files), [path]( const CachedFile& file ) - { - return strcmp(path, file.path) == 0; - }); +CModelCacheManager::FileCache::iterator CModelCacheManager::FindFile(const char *path) { + return std::find_if(std::begin(files), std::end(files), [path](const CachedFile &file) { return strcmp(path, file.path) == 0; }); } -static const byte FakeGLAFile[] = -{ - 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x01, 0x00, 0x00, 0x00, - 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, - 0x26, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, - 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, - 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, - 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, - 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, - 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, - 0x00, 0x80, 0x00, 0x80, 0x00, 0x80 -}; - -qboolean CModelCacheManager::LoadFile( const char *pFileName, void **ppFileBuffer, qboolean *pbAlreadyCached ) -{ +static const byte FakeGLAFile[] = { + 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0x3F, 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x26, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6C, 0x74, 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, + 0xFF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80}; + +qboolean CModelCacheManager::LoadFile(const char *pFileName, void **ppFileBuffer, qboolean *pbAlreadyCached) { char path[MAX_QPATH]; NormalizePath(path, pFileName, sizeof(path)); auto cacheEntry = FindFile(path); - if ( cacheEntry != std::end(files) ) - { + if (cacheEntry != std::end(files)) { *ppFileBuffer = cacheEntry->pDiskImage; *pbAlreadyCached = qtrue; @@ -78,51 +54,46 @@ qboolean CModelCacheManager::LoadFile( const char *pFileName, void **ppFileBuffe *pbAlreadyCached = qfalse; // special case intercept first... - if (!strcmp (sDEFAULT_GLA_NAME ".gla", path)) - { + if (!strcmp(sDEFAULT_GLA_NAME ".gla", path)) { // return fake params as though it was found on disk... - void *pvFakeGLAFile = Z_Malloc(sizeof (FakeGLAFile), TAG_FILESYS, qfalse); + void *pvFakeGLAFile = Z_Malloc(sizeof(FakeGLAFile), TAG_FILESYS, qfalse); - memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof (FakeGLAFile)); + memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); *ppFileBuffer = pvFakeGLAFile; - return qtrue; + return qtrue; } int len = ri.FS_ReadFile(path, ppFileBuffer); - if ( len == -1 || *ppFileBuffer == NULL ) - { + if (len == -1 || *ppFileBuffer == NULL) { return qfalse; } - ri.Printf( PRINT_DEVELOPER, "C_LoadFile(): Loaded %s from disk\n", pFileName ); + ri.Printf(PRINT_DEVELOPER, "C_LoadFile(): Loaded %s from disk\n", pFileName); return qtrue; } - -void* CModelCacheManager::Allocate( int iSize, void *pvDiskBuffer, const char *psModelFileName, qboolean *bAlreadyFound, memtag_t eTag ) -{ - int iChecksum; - char sModelName[MAX_QPATH]; +void *CModelCacheManager::Allocate(int iSize, void *pvDiskBuffer, const char *psModelFileName, qboolean *bAlreadyFound, memtag_t eTag) { + int iChecksum; + char sModelName[MAX_QPATH]; /* Standard NULL checking. */ - if( !psModelFileName || !psModelFileName[0] ) + if (!psModelFileName || !psModelFileName[0]) return NULL; - if( !bAlreadyFound ) + if (!bAlreadyFound) return NULL; NormalizePath(sModelName, psModelFileName, sizeof(sModelName)); CachedFile *pFile = nullptr; auto cacheEntry = FindFile(sModelName); - if (cacheEntry == files.end()) - { + if (cacheEntry == files.end()) { /* Create this image. */ - if( pvDiskBuffer ) - Z_MorphMallocTag( pvDiskBuffer, eTag ); + if (pvDiskBuffer) + Z_MorphMallocTag(pvDiskBuffer, eTag); else pvDiskBuffer = Z_Malloc(iSize, eTag, qfalse); @@ -132,13 +103,11 @@ void* CModelCacheManager::Allocate( int iSize, void *pvDiskBuffer, const char *p pFile->iAllocSize = iSize; Q_strncpyz(pFile->path, sModelName, sizeof(pFile->path)); - if( ri.FS_FileIsInPAK( sModelName, &iChecksum ) ) - pFile->iPAKChecksum = iChecksum; /* Otherwise, it will be -1. */ + if (ri.FS_FileIsInPAK(sModelName, &iChecksum)) + pFile->iPAKChecksum = iChecksum; /* Otherwise, it will be -1. */ *bAlreadyFound = qfalse; - } - else - { + } else { /* * Already found it. * TODO: shader caching. @@ -155,10 +124,8 @@ void* CModelCacheManager::Allocate( int iSize, void *pvDiskBuffer, const char *p /* * Clears out the cache (done on renderer shutdown I suppose) */ -void CModelCacheManager::DeleteAll( void ) -{ - for ( auto& file : files ) - { +void CModelCacheManager::DeleteAll(void) { + for (auto &file : files) { Z_Free(file.pDiskImage); } @@ -170,57 +137,45 @@ void CModelCacheManager::DeleteAll( void ) * Scans the cache for assets which don't match the checksum, and dumps * those that don't match. */ -void CModelCacheManager::DumpNonPure( void ) -{ - ri.Printf( PRINT_DEVELOPER, "CCacheManager::DumpNonPure():\n"); +void CModelCacheManager::DumpNonPure(void) { + ri.Printf(PRINT_DEVELOPER, "CCacheManager::DumpNonPure():\n"); - for ( auto it = files.begin(); it != files.end(); /* empty */ ) - { + for (auto it = files.begin(); it != files.end(); /* empty */) { int iChecksum; - int iInPak = ri.FS_FileIsInPAK( it->path, &iChecksum ); + int iInPak = ri.FS_FileIsInPAK(it->path, &iChecksum); - if( iInPak == -1 || iChecksum != it->iPAKChecksum ) - { + if (iInPak == -1 || iChecksum != it->iPAKChecksum) { /* Erase the file because it doesn't match the checksum */ - ri.Printf( PRINT_DEVELOPER, "Dumping none pure model \"%s\"", it->path ); + ri.Printf(PRINT_DEVELOPER, "Dumping none pure model \"%s\"", it->path); - if( it->pDiskImage ) - Z_Free( it->pDiskImage ); + if (it->pDiskImage) + Z_Free(it->pDiskImage); it = files.erase(it); - } - else - { + } else { ++it; } } - ri.Printf( PRINT_DEVELOPER, "CCacheManager::DumpNonPure(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, "CCacheManager::DumpNonPure(): Ok\n"); } -CModelCacheManager::AssetCache::iterator CModelCacheManager::FindAsset( const char *path ) -{ - return std::find_if( - std::begin(assets), std::end(assets), [path]( const Asset& asset ) - { - return strcmp(path, asset.path) == 0; - }); +CModelCacheManager::AssetCache::iterator CModelCacheManager::FindAsset(const char *path) { + return std::find_if(std::begin(assets), std::end(assets), [path](const Asset &asset) { return strcmp(path, asset.path) == 0; }); } -qhandle_t CModelCacheManager::GetModelHandle( const char *fileName ) -{ +qhandle_t CModelCacheManager::GetModelHandle(const char *fileName) { char path[MAX_QPATH]; NormalizePath(path, fileName, sizeof(path)); const auto it = FindAsset(path); - if( it == std::end(assets) ) + if (it == std::end(assets)) return -1; // asset not found return it->handle; } -void CModelCacheManager::InsertModelHandle( const char *fileName, qhandle_t handle ) -{ +void CModelCacheManager::InsertModelHandle(const char *fileName, qhandle_t handle) { char path[MAX_QPATH]; NormalizePath(path, fileName, sizeof(path)); @@ -230,39 +185,33 @@ void CModelCacheManager::InsertModelHandle( const char *fileName, qhandle_t hand assets.emplace_back(asset); } -qboolean CModelCacheManager::LevelLoadEnd( qboolean deleteUnusedByLevel ) -{ - qboolean bAtLeastOneModelFreed = qfalse; +qboolean CModelCacheManager::LevelLoadEnd(qboolean deleteUnusedByLevel) { + qboolean bAtLeastOneModelFreed = qfalse; - ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd():\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd():\n"); - for ( auto it = files.begin(); it != files.end(); /* empty */ ) - { + for (auto it = files.begin(); it != files.end(); /* empty */) { bool bDeleteThis = false; - if( deleteUnusedByLevel ) + if (deleteUnusedByLevel) bDeleteThis = (it->iLevelLastUsedOn != tr.currentLevel); else bDeleteThis = (it->iLevelLastUsedOn < tr.currentLevel); - if( bDeleteThis ) - { - ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "Dumping \"%s\"", it->path); - if( it->pDiskImage ) - { - Z_Free( it->pDiskImage ); - bAtLeastOneModelFreed = qtrue; // FIXME: is this correct? shouldn't it be in the next lower scope? + if (bDeleteThis) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_GREEN "Dumping \"%s\"", it->path); + if (it->pDiskImage) { + Z_Free(it->pDiskImage); + bAtLeastOneModelFreed = qtrue; // FIXME: is this correct? shouldn't it be in the next lower scope? } it = files.erase(it); - } - else - { + } else { ++it; } } - ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd(): Ok\n"); return bAtLeastOneModelFreed; } @@ -271,73 +220,60 @@ qboolean CModelCacheManager::LevelLoadEnd( qboolean deleteUnusedByLevel ) * Wrappers for the above funcs so they export properly. */ -qboolean C_Models_LevelLoadEnd( qboolean deleteUnusedByLevel ) -{ - return CModelCache->LevelLoadEnd(deleteUnusedByLevel); -} +qboolean C_Models_LevelLoadEnd(qboolean deleteUnusedByLevel) { return CModelCache->LevelLoadEnd(deleteUnusedByLevel); } -qboolean C_Images_LevelLoadEnd() -{ - return qfalse; -} +qboolean C_Images_LevelLoadEnd() { return qfalse; } /* * Shader storage and retrieval, unique to the model caching */ -void CModelCacheManager::StoreShaderRequest( const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke ) -{ +void CModelCacheManager::StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke) { char sModelName[MAX_QPATH]; NormalizePath(sModelName, psModelFileName, sizeof(sModelName)); auto file = FindFile(sModelName); - if ( file == files.end() ) - { + if (file == files.end()) { return; } - if( file->pDiskImage == NULL ) - { + if (file->pDiskImage == NULL) { /* Shouldn't even happen. */ assert(0); return; } - - int iNameOffset = psShaderName - (char *)file->pDiskImage; - int iPokeOffset = (char*) piShaderIndexPoke - (char *)file->pDiskImage; + + int iNameOffset = psShaderName - (char *)file->pDiskImage; + int iPokeOffset = (char *)piShaderIndexPoke - (char *)file->pDiskImage; file->shaderCache.push_back(ShaderCacheEntry(iNameOffset, iPokeOffset)); } -void CModelCacheManager::AllocateShaders( const char *psFileName ) -{ +void CModelCacheManager::AllocateShaders(const char *psFileName) { // if we already had this model entry, then re-register all the shaders it wanted... char sModelName[MAX_QPATH]; NormalizePath(sModelName, psFileName, sizeof(sModelName)); auto file = FindFile(sModelName); - if ( file == files.end() ) - { + if (file == files.end()) { return; } - if( file->pDiskImage == NULL ) - { + if (file->pDiskImage == NULL) { /* Shouldn't even happen. */ assert(0); return; } - for( const ShaderCacheEntry& shader : file->shaderCache ) - { - char *psShaderName = ((char*)file->pDiskImage + shader.nameOffset); - int *piShaderPokePtr = (int *)((char*)file->pDiskImage + shader.pokeOffset); + for (const ShaderCacheEntry &shader : file->shaderCache) { + char *psShaderName = ((char *)file->pDiskImage + shader.nameOffset); + int *piShaderPokePtr = (int *)((char *)file->pDiskImage + shader.pokeOffset); shader_t *sh = R_FindShader(psShaderName, lightmapsNone, stylesDefault, qtrue); - if ( sh->defaultShader ) + if (sh->defaultShader) *piShaderPokePtr = 0; - else + else *piShaderPokePtr = sh->index; } } diff --git a/codemp/rd-rend2/tr_cmds.cpp b/codemp/rd-rend2/tr_cmds.cpp index 12027fdb05..358ebc31ac 100644 --- a/codemp/rd-rend2/tr_cmds.cpp +++ b/codemp/rd-rend2/tr_cmds.cpp @@ -27,118 +27,93 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA R_PerformanceCounters ===================== */ -void R_PerformanceCounters( void ) { +void R_PerformanceCounters(void) { gpuFrame_t *currentFrame = backEndData->frames + (backEndData->realFrameNumber % MAX_FRAMES); - if ( !r_speeds->integer ) { + if (!r_speeds->integer) { // clear the counters even if we aren't printing - Com_Memset( &tr.pc, 0, sizeof( tr.pc ) ); - Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + Com_Memset(&tr.pc, 0, sizeof(tr.pc)); + Com_Memset(&backEnd.pc, 0, sizeof(backEnd.pc)); currentFrame->numTimedBlocks = 0; currentFrame->numTimers = 0; return; } if (r_speeds->integer == 1) { - ri.Printf (PRINT_ALL, "%i/%i/%i shaders/batches/surfs %i leafs %i verts %i/%i tris %.2f mtex %.2f dc\n", - backEnd.pc.c_shaders, backEnd.pc.c_surfBatches, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, - backEnd.pc.c_indexes/3, backEnd.pc.c_totalIndexes/3, - R_SumOfUsedImages()/(1000000.0f), backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight) ); + ri.Printf(PRINT_ALL, "%i/%i/%i shaders/batches/surfs %i leafs %i verts %i/%i tris %.2f mtex %.2f dc\n", backEnd.pc.c_shaders, backEnd.pc.c_surfBatches, + backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, backEnd.pc.c_indexes / 3, backEnd.pc.c_totalIndexes / 3, + R_SumOfUsedImages() / (1000000.0f), backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight)); } else if (r_speeds->integer == 2) { - ri.Printf (PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out, - tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out ); - ri.Printf (PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out, - tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out ); + ri.Printf(PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, + tr.pc.c_sphere_cull_patch_out, tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out); + ri.Printf(PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, + tr.pc.c_sphere_cull_md3_out, tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out); } else if (r_speeds->integer == 3) { - ri.Printf (PRINT_ALL, "viewcluster: %i\n", tr.viewCluster ); + ri.Printf(PRINT_ALL, "viewcluster: %i\n", tr.viewCluster); } else if (r_speeds->integer == 4) { - if ( backEnd.pc.c_dlightVertexes ) { - ri.Printf (PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", - tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, - backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 ); + if (backEnd.pc.c_dlightVertexes) { + ri.Printf(PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, + backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3); } - } - else if (r_speeds->integer == 5 ) - { - ri.Printf( PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar ); - } - else if (r_speeds->integer == 6 ) - { - ri.Printf( PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", - backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders ); - } - else if (r_speeds->integer == 7 ) - { - ri.Printf( PRINT_ALL, "VBO draws: static %i dynamic %i (%.2fKB)\nMultidraws: %i merged %i\n", - backEnd.pc.c_staticVboDraws, backEnd.pc.c_dynamicVboDraws, backEnd.pc.c_dynamicVboTotalSize / (1024.0f), - backEnd.pc.c_multidraws, backEnd.pc.c_multidrawsMerged ); - ri.Printf( PRINT_ALL, "GLSL binds: %i draws: gen %i light %i fog %i dlight %i\n", - backEnd.pc.c_glslShaderBinds, backEnd.pc.c_genericDraws, backEnd.pc.c_lightallDraws, backEnd.pc.c_fogDraws, backEnd.pc.c_dlightDraws); - } - else if (r_speeds->integer == 8) - { - ri.Printf( PRINT_ALL, "0-19: %d 20-49: %d 50-99: %d 100-299: %d\n", - backEnd.pc.c_triangleCountBins[TRI_BIN_0_19], - backEnd.pc.c_triangleCountBins[TRI_BIN_20_49], - backEnd.pc.c_triangleCountBins[TRI_BIN_50_99], - backEnd.pc.c_triangleCountBins[TRI_BIN_100_299]); - - ri.Printf( PRINT_ALL, "300-599: %d 600-999: %d 1000-1499: %d 1500-1999: %d\n", - backEnd.pc.c_triangleCountBins[TRI_BIN_300_599], - backEnd.pc.c_triangleCountBins[TRI_BIN_600_999], - backEnd.pc.c_triangleCountBins[TRI_BIN_1000_1499], - backEnd.pc.c_triangleCountBins[TRI_BIN_1500_1999]); - ri.Printf( PRINT_ALL, "2000-2999: %d 3000+: %d\n", - backEnd.pc.c_triangleCountBins[TRI_BIN_2000_2999], - backEnd.pc.c_triangleCountBins[TRI_BIN_3000_PLUS]); - } - else if ( r_speeds->integer == 100 ) - { + } else if (r_speeds->integer == 5) { + ri.Printf(PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar); + } else if (r_speeds->integer == 6) { + ri.Printf(PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders); + } else if (r_speeds->integer == 7) { + ri.Printf(PRINT_ALL, "VBO draws: static %i dynamic %i (%.2fKB)\nMultidraws: %i merged %i\n", backEnd.pc.c_staticVboDraws, backEnd.pc.c_dynamicVboDraws, + backEnd.pc.c_dynamicVboTotalSize / (1024.0f), backEnd.pc.c_multidraws, backEnd.pc.c_multidrawsMerged); + ri.Printf(PRINT_ALL, "GLSL binds: %i draws: gen %i light %i fog %i dlight %i\n", backEnd.pc.c_glslShaderBinds, backEnd.pc.c_genericDraws, + backEnd.pc.c_lightallDraws, backEnd.pc.c_fogDraws, backEnd.pc.c_dlightDraws); + } else if (r_speeds->integer == 8) { + ri.Printf(PRINT_ALL, "0-19: %d 20-49: %d 50-99: %d 100-299: %d\n", backEnd.pc.c_triangleCountBins[TRI_BIN_0_19], + backEnd.pc.c_triangleCountBins[TRI_BIN_20_49], backEnd.pc.c_triangleCountBins[TRI_BIN_50_99], + backEnd.pc.c_triangleCountBins[TRI_BIN_100_299]); + + ri.Printf(PRINT_ALL, "300-599: %d 600-999: %d 1000-1499: %d 1500-1999: %d\n", backEnd.pc.c_triangleCountBins[TRI_BIN_300_599], + backEnd.pc.c_triangleCountBins[TRI_BIN_600_999], backEnd.pc.c_triangleCountBins[TRI_BIN_1000_1499], + backEnd.pc.c_triangleCountBins[TRI_BIN_1500_1999]); + ri.Printf(PRINT_ALL, "2000-2999: %d 3000+: %d\n", backEnd.pc.c_triangleCountBins[TRI_BIN_2000_2999], backEnd.pc.c_triangleCountBins[TRI_BIN_3000_PLUS]); + } else if (r_speeds->integer == 100) { gpuFrame_t *frame = backEndData->frames + (backEndData->realFrameNumber % MAX_FRAMES); // TODO: We want to draw this as text on the screen... // Print to console for now int numTimedBlocks = frame->numTimedBlocks; - for ( int i = 0; i < numTimedBlocks; i++ ) - { + for (int i = 0; i < numTimedBlocks; i++) { gpuTimedBlock_t *timedBlock = frame->timedBlocks + i; GLuint64 startTime, endTime, diffInNs; float diffInMs; - qglGetQueryObjectui64v( timedBlock->beginTimer, GL_QUERY_RESULT, &startTime); - qglGetQueryObjectui64v( timedBlock->endTimer, GL_QUERY_RESULT, &endTime); + qglGetQueryObjectui64v(timedBlock->beginTimer, GL_QUERY_RESULT, &startTime); + qglGetQueryObjectui64v(timedBlock->endTimer, GL_QUERY_RESULT, &endTime); diffInNs = endTime - startTime; diffInMs = diffInNs / 1e6f; - ri.Printf( PRINT_ALL, "%s: %.3fms ", timedBlock->name, diffInMs ); + ri.Printf(PRINT_ALL, "%s: %.3fms ", timedBlock->name, diffInMs); - if ( (i % 7) == 6 ) - { - ri.Printf( PRINT_ALL, "\n" ); + if ((i % 7) == 6) { + ri.Printf(PRINT_ALL, "\n"); } } - ri.Printf( PRINT_ALL, "\n" ); + ri.Printf(PRINT_ALL, "\n"); } - Com_Memset( &tr.pc, 0, sizeof( tr.pc ) ); - Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + Com_Memset(&tr.pc, 0, sizeof(tr.pc)); + Com_Memset(&backEnd.pc, 0, sizeof(backEnd.pc)); currentFrame->numTimedBlocks = 0; currentFrame->numTimers = 0; } - /* ==================== R_IssueRenderCommands ==================== */ -void R_IssueRenderCommands( qboolean runPerformanceCounters ) { - renderCommandList_t *cmdList; +void R_IssueRenderCommands(qboolean runPerformanceCounters) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; assert(cmdList); @@ -148,18 +123,17 @@ void R_IssueRenderCommands( qboolean runPerformanceCounters ) { // clear it out, in case this is a sync and not a buffer flip cmdList->used = 0; - if ( runPerformanceCounters ) { + if (runPerformanceCounters) { R_PerformanceCounters(); } // actually start the commands going - if ( !r_skipBackEnd->integer ) { + if (!r_skipBackEnd->integer) { // let it start on the new batch - RB_ExecuteRenderCommands( cmdList->cmds ); + RB_ExecuteRenderCommands(cmdList->cmds); } } - /* ==================== R_IssuePendingRenderCommands @@ -167,11 +141,11 @@ R_IssuePendingRenderCommands Issue any pending commands and wait for them to complete. ==================== */ -void R_IssuePendingRenderCommands( void ) { - if ( !tr.registered ) { +void R_IssuePendingRenderCommands(void) { + if (!tr.registered) { return; } - R_IssueRenderCommands( qfalse ); + R_IssueRenderCommands(qfalse); } /* @@ -181,16 +155,16 @@ R_GetCommandBuffer make sure there is enough command space ============ */ -static void *R_GetCommandBufferReserved( int bytes, int reservedBytes ) { - renderCommandList_t *cmdList; +static void *R_GetCommandBufferReserved(int bytes, int reservedBytes) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; bytes = PAD(bytes, sizeof(void *)); // always leave room for the end of list command - if ( cmdList->used + bytes + sizeof(int) + reservedBytes > MAX_RENDER_COMMANDS ) { - if ( bytes > MAX_RENDER_COMMANDS - (int)sizeof(int)) { - ri.Error( ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes ); + if (cmdList->used + bytes + sizeof(int) + reservedBytes > MAX_RENDER_COMMANDS) { + if (bytes > MAX_RENDER_COMMANDS - (int)sizeof(int)) { + ri.Error(ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes); } // if we run out of room, just start dropping commands return NULL; @@ -207,10 +181,7 @@ R_GetCommandBuffer make sure there is enough command space ============ */ -void *R_GetCommandBuffer(int bytes) { - return R_GetCommandBufferReserved(bytes, PAD(sizeof(swapBuffersCommand_t), sizeof(void *))); -} - +void *R_GetCommandBuffer(int bytes) { return R_GetCommandBufferReserved(bytes, PAD(sizeof(swapBuffersCommand_t), sizeof(void *))); } /* ============= @@ -218,14 +189,14 @@ R_AddDrawSurfCmd ============= */ -void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { - drawSurfsCommand_t *cmd; +void R_AddDrawSurfCmd(drawSurf_t *drawSurfs, int numDrawSurfs) { + drawSurfsCommand_t *cmd; if (!tr.registered) { return; } - cmd = (drawSurfsCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawSurfsCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_DRAW_SURFS; @@ -243,18 +214,18 @@ R_AddConvolveCubemapsCmd ============= */ -void R_AddConvolveCubemapCmd( cubemap_t *cubemap , int cubemapId ) { - convolveCubemapCommand_t *cmd; - +void R_AddConvolveCubemapCmd(cubemap_t *cubemap, int cubemapId) { + convolveCubemapCommand_t *cmd; + if (!tr.registered) { return; } - cmd = (convolveCubemapCommand_t *)R_GetCommandBuffer( sizeof( *cmd )); - if ( !cmd ) { + cmd = (convolveCubemapCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_CONVOLVECUBEMAP; - + cmd->cubemap = cubemap; cmd->cubemapId = cubemapId; } @@ -265,14 +236,14 @@ R_PostProcessingCmd ============= */ -void R_AddPostProcessCmd( ) { - postProcessCommand_t *cmd; +void R_AddPostProcessCmd() { + postProcessCommand_t *cmd; if (!tr.registered) { return; } - cmd = (postProcessCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (postProcessCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_POSTPROCESS; @@ -281,21 +252,18 @@ void R_AddPostProcessCmd( ) { cmd->viewParms = tr.viewParms; } -qhandle_t R_BeginTimedBlockCmd( const char *name ) -{ +qhandle_t R_BeginTimedBlockCmd(const char *name) { beginTimedBlockCommand_t *cmd; if (!tr.registered) { return (qhandle_t)-1; } - cmd = (beginTimedBlockCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) - { + cmd = (beginTimedBlockCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return (qhandle_t)-1; } - if ( tr.numTimedBlocks >= (MAX_GPU_TIMERS / 2) ) - { + if (tr.numTimedBlocks >= (MAX_GPU_TIMERS / 2)) { return (qhandle_t)-1; } @@ -306,21 +274,18 @@ qhandle_t R_BeginTimedBlockCmd( const char *name ) return (qhandle_t)cmd->timerHandle; } -void R_EndTimedBlockCmd( qhandle_t timerHandle ) -{ +void R_EndTimedBlockCmd(qhandle_t timerHandle) { endTimedBlockCommand_t *cmd; if (!tr.registered) { return; } - cmd = (endTimedBlockCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) - { + cmd = (endTimedBlockCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } - if ( cmd->timerHandle == -1 ) - { + if (cmd->timerHandle == -1) { return; } @@ -335,19 +300,19 @@ RE_SetColor Passing NULL will set the color to white ============= */ -void RE_SetColor( const float *rgba ) { - setColorCommand_t *cmd; +void RE_SetColor(const float *rgba) { + setColorCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (setColorCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (setColorCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_SET_COLOR; - if ( !rgba ) { - static float colorWhite[4] = { 1, 1, 1, 1 }; + if (!rgba) { + static float colorWhite[4] = {1, 1, 1, 1}; rgba = colorWhite; } @@ -363,19 +328,18 @@ void RE_SetColor( const float *rgba ) { RE_RotatePic ============= */ -void RE_RotatePic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -392,19 +356,18 @@ void RE_RotatePic ( float x, float y, float w, float h, RE_RotatePic2 ============= */ -void RE_RotatePic2 ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC2; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -421,19 +384,18 @@ void RE_RotatePic2 ( float x, float y, float w, float h, RE_StretchPic ============= */ -void RE_StretchPic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2, qhandle_t hShader ) { - stretchPicCommand_t *cmd; +void RE_StretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + stretchPicCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (stretchPicCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (stretchPicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_STRETCH_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -444,50 +406,43 @@ void RE_StretchPic ( float x, float y, float w, float h, cmd->t2 = t2; } -#define MODE_RED_CYAN 1 -#define MODE_RED_BLUE 2 -#define MODE_RED_GREEN 3 +#define MODE_RED_CYAN 1 +#define MODE_RED_BLUE 2 +#define MODE_RED_GREEN 3 #define MODE_GREEN_MAGENTA 4 -#define MODE_MAX MODE_GREEN_MAGENTA +#define MODE_MAX MODE_GREEN_MAGENTA -void R_SetColorMode(GLboolean *rgba, stereoFrame_t stereoFrame, int colormode) -{ +void R_SetColorMode(GLboolean *rgba, stereoFrame_t stereoFrame, int colormode) { rgba[0] = rgba[1] = rgba[2] = rgba[3] = GL_TRUE; - - if(colormode > MODE_MAX) - { - if(stereoFrame == STEREO_LEFT) + + if (colormode > MODE_MAX) { + if (stereoFrame == STEREO_LEFT) stereoFrame = STEREO_RIGHT; - else if(stereoFrame == STEREO_RIGHT) + else if (stereoFrame == STEREO_RIGHT) stereoFrame = STEREO_LEFT; - + colormode -= MODE_MAX; } - - if(colormode == MODE_GREEN_MAGENTA) - { - if(stereoFrame == STEREO_LEFT) + + if (colormode == MODE_GREEN_MAGENTA) { + if (stereoFrame == STEREO_LEFT) rgba[0] = rgba[2] = GL_FALSE; - else if(stereoFrame == STEREO_RIGHT) + else if (stereoFrame == STEREO_RIGHT) rgba[1] = GL_FALSE; - } - else - { - if(stereoFrame == STEREO_LEFT) + } else { + if (stereoFrame == STEREO_LEFT) rgba[1] = rgba[2] = GL_FALSE; - else if(stereoFrame == STEREO_RIGHT) - { + else if (stereoFrame == STEREO_RIGHT) { rgba[0] = GL_FALSE; - - if(colormode == MODE_RED_BLUE) + + if (colormode == MODE_RED_BLUE) rgba[1] = GL_FALSE; - else if(colormode == MODE_RED_GREEN) + else if (colormode == MODE_RED_GREEN) rgba[2] = GL_FALSE; } } } - /* ==================== RE_BeginFrame @@ -496,33 +451,29 @@ If running in stereo, RE_BeginFrame will be called twice for each RE_EndFrame ==================== */ -void RE_BeginFrame( stereoFrame_t stereoFrame ) { - drawBufferCommand_t *cmd = NULL; +void RE_BeginFrame(stereoFrame_t stereoFrame) { + drawBufferCommand_t *cmd = NULL; colorMaskCommand_t *colcmd = NULL; - if ( !tr.registered ) { + if (!tr.registered) { return; } int frameNumber = backEndData->realFrameNumber; gpuFrame_t *thisFrame = &backEndData->frames[frameNumber % MAX_FRAMES]; backEndData->currentFrame = thisFrame; - if ( thisFrame->sync ) - { + if (thisFrame->sync) { GLsync sync = thisFrame->sync; - GLenum result = qglClientWaitSync( sync, 0, 0 ); - if ( result != GL_ALREADY_SIGNALED ) - { - ri.Printf( PRINT_DEVELOPER, "OpenGL: GPU is more than %d frames behind! Waiting for this frame to finish...\n", MAX_FRAMES ); + GLenum result = qglClientWaitSync(sync, 0, 0); + if (result != GL_ALREADY_SIGNALED) { + ri.Printf(PRINT_DEVELOPER, "OpenGL: GPU is more than %d frames behind! Waiting for this frame to finish...\n", MAX_FRAMES); static const GLuint64 HALF_SECOND = 500 * 1000 * 1000; - do - { - result = qglClientWaitSync( sync, GL_SYNC_FLUSH_COMMANDS_BIT, HALF_SECOND); - if ( result == GL_WAIT_FAILED ) - { + do { + result = qglClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, HALF_SECOND); + if (result == GL_WAIT_FAILED) { // This indicates that opengl context was lost, is there a way to recover? - qglDeleteSync( sync ); + qglDeleteSync(sync); thisFrame->sync = NULL; thisFrame->uboWriteOffset = 0; @@ -538,10 +489,9 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { ri.Error(ERR_DROP, "OpenGL: Failed to wait for fence. Context lost. (0x%x)\n", qglGetError()); return; } - } - while ( result != GL_ALREADY_SIGNALED && result != GL_CONDITION_SATISFIED ); + } while (result != GL_ALREADY_SIGNALED && result != GL_CONDITION_SATISFIED); } - qglDeleteSync( sync ); + qglDeleteSync(sync); thisFrame->sync = NULL; // Perform readback operations @@ -572,37 +522,29 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // do overdraw measurement // - if ( r_measureOverdraw->integer ) - { - if ( glConfig.stencilBits < 4 ) - { - ri.Printf( PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + if (r_measureOverdraw->integer) { + if (glConfig.stencilBits < 4) { + ri.Printf(PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else if ( r_shadows->integer == 2 ) - { - ri.Printf( PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + } else if (r_shadows->integer == 2) { + ri.Printf(PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n"); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else - { + } else { R_IssuePendingRenderCommands(); - qglEnable( GL_STENCIL_TEST ); - qglStencilMask( ~0U ); - qglClearStencil( 0U ); - qglStencilFunc( GL_ALWAYS, 0U, ~0U ); - qglStencilOp( GL_KEEP, GL_INCR, GL_INCR ); + qglEnable(GL_STENCIL_TEST); + qglStencilMask(~0U); + qglClearStencil(0U); + qglStencilFunc(GL_ALWAYS, 0U, ~0U); + qglStencilOp(GL_KEEP, GL_INCR, GL_INCR); } r_measureOverdraw->modified = qfalse; - } - else - { + } else { // this is only reached if it was on and is now off - if ( r_measureOverdraw->modified ) { + if (r_measureOverdraw->modified) { R_IssuePendingRenderCommands(); - qglDisable( GL_STENCIL_TEST ); + qglDisable(GL_STENCIL_TEST); } r_measureOverdraw->modified = qfalse; } @@ -610,9 +552,9 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // texturemode stuff // - if ( r_textureMode->modified || r_ext_texture_filter_anisotropic->modified ) { + if (r_textureMode->modified || r_ext_texture_filter_anisotropic->modified) { R_IssuePendingRenderCommands(); - GL_TextureMode( r_textureMode->string ); + GL_TextureMode(r_textureMode->string); r_textureMode->modified = qfalse; r_ext_texture_filter_anisotropic->modified = qfalse; } @@ -620,7 +562,7 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // gamma stuff // - if ( r_gamma->modified ) { + if (r_gamma->modified) { r_gamma->modified = qfalse; R_IssuePendingRenderCommands(); @@ -628,35 +570,30 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { } // check for errors - if ( !r_ignoreGLErrors->integer ) - { + if (!r_ignoreGLErrors->integer) { R_IssuePendingRenderCommands(); GLenum err = qglGetError(); - if ( err != GL_NO_ERROR ) - Com_Error( ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err ); + if (err != GL_NO_ERROR) + Com_Error(ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err); } if (glConfig.stereoEnabled) { - if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + if (!(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)))) return; - + cmd->commandId = RC_DRAW_BUFFER; - - if ( stereoFrame == STEREO_LEFT ) { + + if (stereoFrame == STEREO_LEFT) { cmd->buffer = (int)GL_BACK_LEFT; - } else if ( stereoFrame == STEREO_RIGHT ) { + } else if (stereoFrame == STEREO_RIGHT) { cmd->buffer = (int)GL_BACK_RIGHT; } else { - ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + ri.Error(ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame); } - } - else - { - if(r_anaglyphMode->integer) - { - if(r_anaglyphMode->modified) - { + } else { + if (r_anaglyphMode->integer) { + if (r_anaglyphMode->modified) { // clear both, front and backbuffer. qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); backEnd.colorMask[0] = qfalse; @@ -664,16 +601,14 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { backEnd.colorMask[2] = qfalse; backEnd.colorMask[3] = qfalse; qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); - + // clear all framebuffers - if (tr.msaaResolveFbo) - { + if (tr.msaaResolveFbo) { FBO_Bind(tr.msaaResolveFbo); qglClear(GL_COLOR_BUFFER_BIT); } - if (tr.renderFbo) - { + if (tr.renderFbo) { FBO_Bind(tr.renderFbo); qglClear(GL_COLOR_BUFFER_BIT); } @@ -687,48 +622,40 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { r_anaglyphMode->modified = qfalse; } - - if(stereoFrame == STEREO_LEFT) - { - if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + + if (stereoFrame == STEREO_LEFT) { + if (!(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)))) return; - - if( !(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd))) ) + + if (!(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd)))) return; - } - else if(stereoFrame == STEREO_RIGHT) - { + } else if (stereoFrame == STEREO_RIGHT) { clearDepthCommand_t *cldcmd; - - if( !(cldcmd = (clearDepthCommand_t *)R_GetCommandBuffer(sizeof(*cldcmd))) ) + + if (!(cldcmd = (clearDepthCommand_t *)R_GetCommandBuffer(sizeof(*cldcmd)))) return; cldcmd->commandId = RC_CLEARDEPTH; - if( !(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd))) ) + if (!(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd)))) return; - } - else - ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + } else + ri.Error(ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame); R_SetColorMode(colcmd->rgba, stereoFrame, r_anaglyphMode->integer); colcmd->commandId = RC_COLORMASK; - } - else - { - if(stereoFrame != STEREO_CENTER) - ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame ); + } else { + if (stereoFrame != STEREO_CENTER) + ri.Error(ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame); - if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + if (!(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)))) return; } - if(cmd) - { + if (cmd) { cmd->commandId = RC_DRAW_BUFFER; - if(r_anaglyphMode->modified) - { + if (r_anaglyphMode->modified) { qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); backEnd.colorMask[0] = qfalse; backEnd.colorMask[1] = qfalse; @@ -743,12 +670,11 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { cmd->buffer = (int)GL_BACK; } } - + tr.refdef.stereoFrame = stereoFrame; } -void R_NewFrameSync() -{ +void R_NewFrameSync() { gpuFrame_t *currentFrame = backEndData->currentFrame; assert(!currentFrame->sync); @@ -759,7 +685,6 @@ void R_NewFrameSync() backEnd.projection2D = qfalse; } - /* ============= RE_EndFrame @@ -767,27 +692,27 @@ RE_EndFrame Returns the number of msec spent in the back end ============= */ -void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { - swapBuffersCommand_t *cmd; +void RE_EndFrame(int *frontEndMsec, int *backEndMsec) { + swapBuffersCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (swapBuffersCommand_t *)R_GetCommandBufferReserved( sizeof( *cmd ), 0 ); - if ( !cmd ) { + cmd = (swapBuffersCommand_t *)R_GetCommandBufferReserved(sizeof(*cmd), 0); + if (!cmd) { return; } cmd->commandId = RC_SWAP_BUFFERS; - R_IssueRenderCommands( qtrue ); + R_IssueRenderCommands(qtrue); R_InitNextFrame(); - if ( frontEndMsec ) { + if (frontEndMsec) { *frontEndMsec = tr.frontEndMsec; } tr.frontEndMsec = 0; - if ( backEndMsec ) { + if (backEndMsec) { *backEndMsec = backEnd.pc.msec; } backEnd.pc.msec = 0; @@ -798,17 +723,15 @@ void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { RE_TakeVideoFrame ============= */ -void RE_TakeVideoFrame( int width, int height, - byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg ) -{ - videoFrameCommand_t *cmd; +void RE_TakeVideoFrame(int width, int height, byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg) { + videoFrameCommand_t *cmd; - if( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (videoFrameCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if( !cmd ) { + cmd = (videoFrameCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } diff --git a/codemp/rd-rend2/tr_curve.cpp b/codemp/rd-rend2/tr_curve.cpp index 90c24c4950..6c095c5099 100644 --- a/codemp/rd-rend2/tr_curve.cpp +++ b/codemp/rd-rend2/tr_curve.cpp @@ -37,13 +37,12 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, */ - /* ============ LerpDrawVert ============ */ -static void LerpDrawVert( srfVert_t *a, srfVert_t *b, srfVert_t *out ) { +static void LerpDrawVert(srfVert_t *a, srfVert_t *b, srfVert_t *out) { out->xyz[0] = 0.5f * (a->xyz[0] + b->xyz[0]); out->xyz[1] = 0.5f * (a->xyz[1] + b->xyz[1]); out->xyz[2] = 0.5f * (a->xyz[2] + b->xyz[2]); @@ -51,8 +50,7 @@ static void LerpDrawVert( srfVert_t *a, srfVert_t *b, srfVert_t *out ) { out->st[0] = 0.5f * (a->st[0] + b->st[0]); out->st[1] = 0.5f * (a->st[1] + b->st[1]); - for ( int i = 0; i < MAXLIGHTMAPS; i++ ) - { + for (int i = 0; i < MAXLIGHTMAPS; i++) { out->lightmap[i][0] = 0.5f * (a->lightmap[i][0] + b->lightmap[i][0]); out->lightmap[i][1] = 0.5f * (a->lightmap[i][1] + b->lightmap[i][1]); @@ -68,14 +66,14 @@ static void LerpDrawVert( srfVert_t *a, srfVert_t *b, srfVert_t *out ) { Transpose ============ */ -static void Transpose( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - srfVert_t temp; - - if ( width > height ) { - for ( i = 0 ; i < height ; i++ ) { - for ( j = i + 1 ; j < width ; j++ ) { - if ( j < height ) { +static void Transpose(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + srfVert_t temp; + + if (width > height) { + for (i = 0; i < height; i++) { + for (j = i + 1; j < width; j++) { + if (j < height) { // swap the value temp = ctrl[j][i]; ctrl[j][i] = ctrl[i][j]; @@ -87,9 +85,9 @@ static void Transpose( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_ } } } else { - for ( i = 0 ; i < width ; i++ ) { - for ( j = i + 1 ; j < height ; j++ ) { - if ( j < width ) { + for (i = 0; i < width; i++) { + for (j = i + 1; j < height; j++) { + if (j < width) { // swap the value temp = ctrl[i][j]; ctrl[i][j] = ctrl[j][i]; @@ -101,10 +99,8 @@ static void Transpose( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_ } } } - } - /* ================= MakeMeshNormals @@ -112,129 +108,122 @@ MakeMeshNormals Handles all the complicated wrapping and degenerate cases ================= */ -static void MakeMeshNormals( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j, k, dist; - vec3_t normal; - vec3_t sum; - int count = 0; - vec3_t base; - vec3_t delta; - int x, y; - srfVert_t *dv; - vec3_t around[8], temp; - qboolean good[8]; - qboolean wrapWidth, wrapHeight; - float len; -static int neighbors[8][2] = { - {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} - }; +static void MakeMeshNormals(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j, k, dist; + vec3_t normal; + vec3_t sum; + int count = 0; + vec3_t base; + vec3_t delta; + int x, y; + srfVert_t *dv; + vec3_t around[8], temp; + qboolean good[8]; + qboolean wrapWidth, wrapHeight; + float len; + static int neighbors[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; wrapWidth = qfalse; - for ( i = 0 ; i < height ; i++ ) { - VectorSubtract( ctrl[i][0].xyz, ctrl[i][width-1].xyz, delta ); - len = VectorLengthSquared( delta ); - if ( len > 1.0 ) { + for (i = 0; i < height; i++) { + VectorSubtract(ctrl[i][0].xyz, ctrl[i][width - 1].xyz, delta); + len = VectorLengthSquared(delta); + if (len > 1.0) { break; } } - if ( i == height ) { + if (i == height) { wrapWidth = qtrue; } wrapHeight = qfalse; - for ( i = 0 ; i < width ; i++ ) { - VectorSubtract( ctrl[0][i].xyz, ctrl[height-1][i].xyz, delta ); - len = VectorLengthSquared( delta ); - if ( len > 1.0 ) { + for (i = 0; i < width; i++) { + VectorSubtract(ctrl[0][i].xyz, ctrl[height - 1][i].xyz, delta); + len = VectorLengthSquared(delta); + if (len > 1.0) { break; } } - if ( i == width) { + if (i == width) { wrapHeight = qtrue; } - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { count = 0; dv = &ctrl[j][i]; - VectorCopy( dv->xyz, base ); - for ( k = 0 ; k < 8 ; k++ ) { - VectorClear( around[k] ); + VectorCopy(dv->xyz, base); + for (k = 0; k < 8; k++) { + VectorClear(around[k]); good[k] = qfalse; - for ( dist = 1 ; dist <= 3 ; dist++ ) { + for (dist = 1; dist <= 3; dist++) { x = i + neighbors[k][0] * dist; y = j + neighbors[k][1] * dist; - if ( wrapWidth ) { - if ( x < 0 ) { + if (wrapWidth) { + if (x < 0) { x = width - 1 + x; - } else if ( x >= width ) { + } else if (x >= width) { x = 1 + x - width; } } - if ( wrapHeight ) { - if ( y < 0 ) { + if (wrapHeight) { + if (y < 0) { y = height - 1 + y; - } else if ( y >= height ) { + } else if (y >= height) { y = 1 + y - height; } } - if ( x < 0 || x >= width || y < 0 || y >= height ) { - break; // edge of patch + if (x < 0 || x >= width || y < 0 || y >= height) { + break; // edge of patch } - VectorSubtract( ctrl[y][x].xyz, base, temp ); - if ( VectorNormalize2( temp, temp ) == 0 ) { - continue; // degenerate edge, get more dist + VectorSubtract(ctrl[y][x].xyz, base, temp); + if (VectorNormalize2(temp, temp) == 0) { + continue; // degenerate edge, get more dist } else { good[k] = qtrue; - VectorCopy( temp, around[k] ); - break; // good edge + VectorCopy(temp, around[k]); + break; // good edge } } } - VectorClear( sum ); - for ( k = 0 ; k < 8 ; k++ ) { - if ( !good[k] || !good[(k+1)&7] ) { - continue; // didn't get two points + VectorClear(sum); + for (k = 0; k < 8; k++) { + if (!good[k] || !good[(k + 1) & 7]) { + continue; // didn't get two points } - CrossProduct( around[(k+1)&7], around[k], normal ); - if ( VectorNormalize2( normal, normal ) == 0 ) { + CrossProduct(around[(k + 1) & 7], around[k], normal); + if (VectorNormalize2(normal, normal) == 0) { continue; } - VectorAdd( normal, sum, sum ); + VectorAdd(normal, sum, sum); count++; } - //if ( count == 0 ) { + // if ( count == 0 ) { // printf("bad normal\n"); - //} - VectorNormalize2( sum, dv->normal ); + // } + VectorNormalize2(sum, dv->normal); } } } static void MakeMeshTangentVectors(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], int numIndexes, - glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) -{ - int i, j; - srfVert_t *dv[3]; - static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; - glIndex_t *tri; + glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]) { + int i, j; + srfVert_t *dv[3]; + static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; + glIndex_t *tri; // FIXME: use more elegant way - for(i = 0; i < width; i++) - { - for(j = 0; j < height; j++) - { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { dv[0] = &ctrl2[j * width + i]; *dv[0] = ctrl[j][i]; } } - for(i = 0, tri = indexes; i < numIndexes; i += 3, tri += 3) - { + for (i = 0, tri = indexes; i < numIndexes; i += 3, tri += 3) { dv[0] = &ctrl2[tri[0]]; dv[1] = &ctrl2[tri[1]]; dv[2] = &ctrl2[tri[2]]; @@ -242,10 +231,8 @@ static void MakeMeshTangentVectors(int width, int height, srfVert_t ctrl[MAX_GRI R_CalcTangentVectors(dv); } - for(i = 0; i < width; i++) - { - for(j = 0; j < height; j++) - { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { dv[0] = &ctrl2[j * width + i]; dv[1] = &ctrl[j][i]; @@ -255,22 +242,19 @@ static void MakeMeshTangentVectors(int width, int height, srfVert_t ctrl[MAX_GRI } static int MakeMeshIndexes(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], - glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) -{ - int i, j; - int numIndexes; - int w, h; - srfVert_t *dv; - static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; + glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]) { + int i, j; + int numIndexes; + int w, h; + srfVert_t *dv; + static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; h = height - 1; w = width - 1; numIndexes = 0; - for(i = 0; i < h; i++) - { - for(j = 0; j < w; j++) - { - int v1, v2, v3, v4; + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) { + int v1, v2, v3, v4; // vertex order to be reckognized as tristrips v1 = i * width + j + 1; @@ -289,10 +273,8 @@ static int MakeMeshIndexes(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][ } // FIXME: use more elegant way - for(i = 0; i < width; i++) - { - for(j = 0; j < height; j++) - { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { dv = &ctrl2[j * width + i]; *dv = ctrl[j][i]; } @@ -301,45 +283,42 @@ static int MakeMeshIndexes(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][ return numIndexes; } - /* ============ InvertCtrl ============ */ -static void InvertCtrl( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - srfVert_t temp; +static void InvertCtrl(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + srfVert_t temp; - for ( i = 0 ; i < height ; i++ ) { - for ( j = 0 ; j < width/2 ; j++ ) { + for (i = 0; i < height; i++) { + for (j = 0; j < width / 2; j++) { temp = ctrl[i][j]; - ctrl[i][j] = ctrl[i][width-1-j]; - ctrl[i][width-1-j] = temp; + ctrl[i][j] = ctrl[i][width - 1 - j]; + ctrl[i][width - 1 - j] = temp; } } } - /* ================= InvertErrorTable ================= */ -static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int height ) { - int i; - float copy[2][MAX_GRID_SIZE]; +static void InvertErrorTable(float errorTable[2][MAX_GRID_SIZE], int width, int height) { + int i; + float copy[2][MAX_GRID_SIZE]; - Com_Memcpy( copy, errorTable, sizeof( copy ) ); + Com_Memcpy(copy, errorTable, sizeof(copy)); - for ( i = 0 ; i < width ; i++ ) { - errorTable[1][i] = copy[0][i]; //[width-1-i]; + for (i = 0; i < width; i++) { + errorTable[1][i] = copy[0][i]; //[width-1-i]; } - for ( i = 0 ; i < height ; i++ ) { - errorTable[0][i] = copy[1][height-1-i]; + for (i = 0; i < height; i++) { + errorTable[0][i] = copy[1][height - 1 - i]; } - } /* @@ -347,25 +326,23 @@ static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int PutPointsOnCurve ================== */ -static void PutPointsOnCurve( srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], - int width, int height ) { - int i, j; - srfVert_t prev, next; - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 1 ; j < height ; j += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j+1][i], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j-1][i], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); +static void PutPointsOnCurve(srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], int width, int height) { + int i, j; + srfVert_t prev, next; + + for (i = 0; i < width; i++) { + for (j = 1; j < height; j += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j + 1][i], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j - 1][i], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } - - for ( j = 0 ; j < height ; j++ ) { - for ( i = 1 ; i < width ; i += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j][i+1], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j][i-1], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); + for (j = 0; j < height; j++) { + for (i = 1; i < width; i += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j][i + 1], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j][i - 1], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } } @@ -375,25 +352,24 @@ static void PutPointsOnCurve( srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], R_CreateSurfaceGridMesh ================= */ -srfBspSurface_t *R_CreateSurfaceGridMesh(int width, int height, - srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE], - int numIndexes, glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) { +srfBspSurface_t *R_CreateSurfaceGridMesh(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE], + int numIndexes, glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]) { int i, j, size; - srfVert_t *vert; - vec3_t tmpVec; + srfVert_t *vert; + vec3_t tmpVec; srfBspSurface_t *grid; // copy the results out to a grid - size = (width * height - 1) * sizeof( srfVert_t ) + sizeof( *grid ); + size = (width * height - 1) * sizeof(srfVert_t) + sizeof(*grid); - grid = /*ri.Hunk_Alloc*/ (srfBspSurface_t *)Z_Malloc( size, TAG_GRIDMESH ); + grid = /*ri.Hunk_Alloc*/ (srfBspSurface_t *)Z_Malloc(size, TAG_GRIDMESH); Com_Memset(grid, 0, size); - grid->widthLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc( width * 4, TAG_GRIDMESH ); - Com_Memcpy( grid->widthLodError, errorTable[0], width * 4 ); + grid->widthLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc(width * 4, TAG_GRIDMESH); + Com_Memcpy(grid->widthLodError, errorTable[0], width * 4); - grid->heightLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc( height * 4, TAG_GRIDMESH ); - Com_Memcpy( grid->heightLodError, errorTable[1], height * 4 ); + grid->heightLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc(height * 4, TAG_GRIDMESH); + Com_Memcpy(grid->heightLodError, errorTable[1], height * 4); grid->numIndexes = numIndexes; grid->indexes = (glIndex_t *)Z_Malloc(grid->numIndexes * sizeof(glIndex_t), TAG_GRIDMESH); @@ -405,22 +381,22 @@ srfBspSurface_t *R_CreateSurfaceGridMesh(int width, int height, grid->width = width; grid->height = height; grid->surfaceType = SF_GRID; - ClearBounds( grid->cullBounds[0], grid->cullBounds[1] ); - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - vert = &grid->verts[j*width+i]; + ClearBounds(grid->cullBounds[0], grid->cullBounds[1]); + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + vert = &grid->verts[j * width + i]; *vert = ctrl[j][i]; - AddPointToBounds( vert->xyz, grid->cullBounds[0], grid->cullBounds[1] ); + AddPointToBounds(vert->xyz, grid->cullBounds[0], grid->cullBounds[1]); } } // compute local origin and bounds - VectorAdd( grid->cullBounds[0], grid->cullBounds[1], grid->cullOrigin ); - VectorScale( grid->cullOrigin, 0.5f, grid->cullOrigin ); - VectorSubtract( grid->cullBounds[0], grid->cullOrigin, tmpVec ); - grid->cullRadius = VectorLength( tmpVec ); + VectorAdd(grid->cullBounds[0], grid->cullBounds[1], grid->cullOrigin); + VectorScale(grid->cullOrigin, 0.5f, grid->cullOrigin); + VectorSubtract(grid->cullBounds[0], grid->cullOrigin, tmpVec); + grid->cullRadius = VectorLength(tmpVec); - VectorCopy( grid->cullOrigin, grid->lodOrigin ); + VectorCopy(grid->cullOrigin, grid->lodOrigin); grid->lodRadius = grid->cullRadius; // return grid; @@ -431,7 +407,7 @@ srfBspSurface_t *R_CreateSurfaceGridMesh(int width, int height, R_FreeSurfaceGridMesh ================= */ -void R_FreeSurfaceGridMesh( srfBspSurface_t *grid ) { +void R_FreeSurfaceGridMesh(srfBspSurface_t *grid) { Z_Free(grid->widthLodError); Z_Free(grid->heightLodError); Z_Free(grid->indexes); @@ -444,73 +420,71 @@ void R_FreeSurfaceGridMesh( srfBspSurface_t *grid ) { R_SubdividePatchToGrid ================= */ -srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, - srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) { - int i, j, k, l; +srfBspSurface_t *R_SubdividePatchToGrid(int width, int height, srfVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]) { + int i, j, k, l; srfVert_t prev; srfVert_t next; srfVert_t mid; - float len, maxLen; - int dir; - int t; - srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; - float errorTable[2][MAX_GRID_SIZE]; - int numIndexes; - static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + float len, maxLen; + int dir; + int t; + srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]; int consecutiveComplete; - Com_Memset (&prev, 0, sizeof (prev)); - Com_Memset (&next, 0, sizeof (next)); - Com_Memset (&mid, 0, sizeof (mid)); + Com_Memset(&prev, 0, sizeof(prev)); + Com_Memset(&next, 0, sizeof(next)); + Com_Memset(&mid, 0, sizeof(mid)); - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - ctrl[j][i] = points[j*width+i]; + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + ctrl[j][i] = points[j * width + i]; } } - for ( dir = 0 ; dir < 2 ; dir++ ) { + for (dir = 0; dir < 2; dir++) { - for ( j = 0 ; j < MAX_GRID_SIZE ; j++ ) { + for (j = 0; j < MAX_GRID_SIZE; j++) { errorTable[dir][j] = 0; } consecutiveComplete = 0; // horizontal subdivisions - for ( j = 0 ; ; j = (j + 2) % (width - 1) ) { + for (j = 0;; j = (j + 2) % (width - 1)) { // check subdivided midpoints against control points // FIXME: also check midpoints of adjacent patches against the control points // this would basically stitch all patches in the same LOD group together. maxLen = 0; - for ( i = 0 ; i < height ; i++ ) { - vec3_t midxyz; - vec3_t midxyz2; - vec3_t dir; - vec3_t projected; - float d; + for (i = 0; i < height; i++) { + vec3_t midxyz; + vec3_t midxyz2; + vec3_t dir; + vec3_t projected; + float d; // calculate the point on the curve - for ( l = 0 ; l < 3 ; l++ ) { - midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j+1].xyz[l] * 2 - + ctrl[i][j+2].xyz[l] ) * 0.25f; + for (l = 0; l < 3; l++) { + midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j + 1].xyz[l] * 2 + ctrl[i][j + 2].xyz[l]) * 0.25f; } // see how far off the line it is // using dist-from-line will not account for internal // texture warping, but it gives a lot less polygons than // dist-from-midpoint - VectorSubtract( midxyz, ctrl[i][j].xyz, midxyz ); - VectorSubtract( ctrl[i][j+2].xyz, ctrl[i][j].xyz, dir ); - VectorNormalize( dir ); - - d = DotProduct( midxyz, dir ); - VectorScale( dir, d, projected ); - VectorSubtract( midxyz, projected, midxyz2); - len = VectorLengthSquared( midxyz2 ); // we will do the sqrt later - if ( len > maxLen ) { + VectorSubtract(midxyz, ctrl[i][j].xyz, midxyz); + VectorSubtract(ctrl[i][j + 2].xyz, ctrl[i][j].xyz, dir); + VectorNormalize(dir); + + d = DotProduct(midxyz, dir); + VectorScale(dir, d, projected); + VectorSubtract(midxyz, projected, midxyz2); + len = VectorLengthSquared(midxyz2); // we will do the sqrt later + if (len > maxLen) { maxLen = len; } } @@ -518,8 +492,8 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, maxLen = sqrt(maxLen); // if all the points are on the lines, remove the entire columns - if ( maxLen < 0.1f ) { - errorTable[dir][j+1] = 999; + if (maxLen < 0.1f) { + errorTable[dir][j + 1] = 999; // if we go over the whole grid twice without adding any columns, stop if (++consecutiveComplete >= width) break; @@ -527,32 +501,32 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, } // see if we want to insert subdivided columns - if ( width + 2 > MAX_GRID_SIZE ) { - errorTable[dir][j+1] = 1.0f/maxLen; - break; // can't subdivide any more + if (width + 2 > MAX_GRID_SIZE) { + errorTable[dir][j + 1] = 1.0f / maxLen; + break; // can't subdivide any more } - if ( maxLen <= r_subdivisions->value ) { - errorTable[dir][j+1] = 1.0f/maxLen; + if (maxLen <= r_subdivisions->value) { + errorTable[dir][j + 1] = 1.0f / maxLen; // if we go over the whole grid twice without adding any columns, stop if (++consecutiveComplete >= width) break; - continue; // didn't need subdivision + continue; // didn't need subdivision } - errorTable[dir][j+2] = 1.0f/maxLen; + errorTable[dir][j + 2] = 1.0f / maxLen; consecutiveComplete = 0; // insert two columns and replace the peak width += 2; - for ( i = 0 ; i < height ; i++ ) { - LerpDrawVert( &ctrl[i][j], &ctrl[i][j+1], &prev ); - LerpDrawVert( &ctrl[i][j+1], &ctrl[i][j+2], &next ); - LerpDrawVert( &prev, &next, &mid ); + for (i = 0; i < height; i++) { + LerpDrawVert(&ctrl[i][j], &ctrl[i][j + 1], &prev); + LerpDrawVert(&ctrl[i][j + 1], &ctrl[i][j + 2], &next); + LerpDrawVert(&prev, &next, &mid); - for ( k = width - 1 ; k > j + 3 ; k-- ) { - ctrl[i][k] = ctrl[i][k-2]; + for (k = width - 1; k > j + 3; k--) { + ctrl[i][k] = ctrl[i][k - 2]; } ctrl[i][j + 1] = prev; ctrl[i][j + 2] = mid; @@ -563,39 +537,38 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, j += 2; } - Transpose( width, height, ctrl ); + Transpose(width, height, ctrl); t = width; width = height; height = t; } - // put all the aproximating points on the curve - PutPointsOnCurve( ctrl, width, height ); + PutPointsOnCurve(ctrl, width, height); // cull out any rows or columns that are colinear - for ( i = 1 ; i < width-1 ; i++ ) { - if ( errorTable[0][i] != 999 ) { + for (i = 1; i < width - 1; i++) { + if (errorTable[0][i] != 999) { continue; } - for ( j = i+1 ; j < width ; j++ ) { - for ( k = 0 ; k < height ; k++ ) { - ctrl[k][j-1] = ctrl[k][j]; + for (j = i + 1; j < width; j++) { + for (k = 0; k < height; k++) { + ctrl[k][j - 1] = ctrl[k][j]; } - errorTable[0][j-1] = errorTable[0][j]; + errorTable[0][j - 1] = errorTable[0][j]; } width--; } - for ( i = 1 ; i < height-1 ; i++ ) { - if ( errorTable[1][i] != 999 ) { + for (i = 1; i < height - 1; i++) { + if (errorTable[1][i] != 999) { continue; } - for ( j = i+1 ; j < height ; j++ ) { - for ( k = 0 ; k < width ; k++ ) { - ctrl[j-1][k] = ctrl[j][k]; + for (j = i + 1; j < height; j++) { + for (k = 0; k < width; k++) { + ctrl[j - 1][k] = ctrl[j][k]; } - errorTable[1][j-1] = errorTable[1][j]; + errorTable[1][j - 1] = errorTable[1][j]; } height--; } @@ -604,13 +577,13 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, // flip for longest tristrips as an optimization // the results should be visually identical with or // without this step - if ( height > width ) { - Transpose( width, height, ctrl ); - InvertErrorTable( errorTable, width, height ); + if (height > width) { + Transpose(width, height, ctrl); + InvertErrorTable(errorTable, width, height); t = width; width = height; height = t; - InvertCtrl( width, height, ctrl ); + InvertCtrl(width, height, ctrl); } #endif @@ -618,7 +591,7 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); MakeMeshTangentVectors(width, height, ctrl, numIndexes, indexes); return R_CreateSurfaceGridMesh(width, height, ctrl, errorTable, numIndexes, indexes); @@ -629,15 +602,15 @@ srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, R_GridInsertColumn =============== */ -srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, vec3_t point, float loderror ) { +srfBspSurface_t *R_GridInsertColumn(srfBspSurface_t *grid, int column, int row, vec3_t point, float loderror) { int i, j; int width, height, oldwidth; srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; float errorTable[2][MAX_GRID_SIZE]; float lodRadius; vec3_t lodOrigin; - int numIndexes; - static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]; oldwidth = 0; width = grid->width + 1; @@ -646,9 +619,9 @@ srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, height = grid->height; for (i = 0; i < width; i++) { if (i == column) { - //insert new column + // insert new column for (j = 0; j < grid->height; j++) { - LerpDrawVert( &grid->verts[j * grid->width + i-1], &grid->verts[j * grid->width + i], &ctrl[j][i] ); + LerpDrawVert(&grid->verts[j * grid->width + i - 1], &grid->verts[j * grid->width + i], &ctrl[j][i]); if (j == row) VectorCopy(point, ctrl[j][i].xyz); } @@ -665,13 +638,13 @@ srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, errorTable[1][j] = grid->heightLodError[j]; } // put all the aproximating points on the curve - //PutPointsOnCurve( ctrl, width, height ); + // PutPointsOnCurve( ctrl, width, height ); // calculate indexes numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); VectorCopy(grid->lodOrigin, lodOrigin); lodRadius = grid->lodRadius; @@ -689,15 +662,15 @@ srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, R_GridInsertRow =============== */ -srfBspSurface_t *R_GridInsertRow( srfBspSurface_t *grid, int row, int column, vec3_t point, float loderror ) { +srfBspSurface_t *R_GridInsertRow(srfBspSurface_t *grid, int row, int column, vec3_t point, float loderror) { int i, j; int width, height, oldheight; srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; float errorTable[2][MAX_GRID_SIZE]; float lodRadius; vec3_t lodOrigin; - int numIndexes; - static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE - 1) * (MAX_GRID_SIZE - 1) * 2 * 3]; oldheight = 0; width = grid->width; @@ -706,9 +679,9 @@ srfBspSurface_t *R_GridInsertRow( srfBspSurface_t *grid, int row, int column, ve return NULL; for (i = 0; i < height; i++) { if (i == row) { - //insert new row + // insert new row for (j = 0; j < grid->width; j++) { - LerpDrawVert( &grid->verts[(i-1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j] ); + LerpDrawVert(&grid->verts[(i - 1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j]); if (j == column) VectorCopy(point, ctrl[i][j].xyz); } @@ -725,13 +698,13 @@ srfBspSurface_t *R_GridInsertRow( srfBspSurface_t *grid, int row, int column, ve errorTable[0][j] = grid->widthLodError[j]; } // put all the aproximating points on the curve - //PutPointsOnCurve( ctrl, width, height ); + // PutPointsOnCurve( ctrl, width, height ); // calculate indexes numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); VectorCopy(grid->lodOrigin, lodOrigin); lodRadius = grid->lodRadius; diff --git a/codemp/rd-rend2/tr_decals.cpp b/codemp/rd-rend2/tr_decals.cpp index 6bf4222da7..2ef160c60d 100644 --- a/codemp/rd-rend2/tr_decals.cpp +++ b/codemp/rd-rend2/tr_decals.cpp @@ -1,33 +1,27 @@ #include "tr_local.h" -#define MAX_VERTS_ON_DECAL_POLY 10 -#define MAX_DECAL_POLYS 500 - -typedef struct decalPoly_s -{ - int time; - int fadetime; - qhandle_t shader; - float color[4]; - poly_t poly; - polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; +#define MAX_VERTS_ON_DECAL_POLY 10 +#define MAX_DECAL_POLYS 500 + +typedef struct decalPoly_s { + int time; + int fadetime; + qhandle_t shader; + float color[4]; + poly_t poly; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; } decalPoly_t; -enum -{ - DECALPOLY_TYPE_NORMAL, - DECALPOLY_TYPE_FADE, - DECALPOLY_TYPE_MAX -}; +enum { DECALPOLY_TYPE_NORMAL, DECALPOLY_TYPE_FADE, DECALPOLY_TYPE_MAX }; -#define DECAL_FADE_TIME 1000 +#define DECAL_FADE_TIME 1000 -decalPoly_t* RE_AllocDecal( int type ); +decalPoly_t *RE_AllocDecal(int type); -static decalPoly_t re_decalPolys[DECALPOLY_TYPE_MAX][MAX_DECAL_POLYS]; +static decalPoly_t re_decalPolys[DECALPOLY_TYPE_MAX][MAX_DECAL_POLYS]; -static int re_decalPolyHead[DECALPOLY_TYPE_MAX]; -static int re_decalPolyTotal[DECALPOLY_TYPE_MAX]; +static int re_decalPolyHead[DECALPOLY_TYPE_MAX]; +static int re_decalPolyTotal[DECALPOLY_TYPE_MAX]; /* =================== @@ -36,26 +30,24 @@ RE_ClearDecals This is called to remove all decals from the world =================== */ -void RE_ClearDecals( void ) { - memset( re_decalPolys, 0, sizeof(re_decalPolys) ); - memset( re_decalPolyHead, 0, sizeof(re_decalPolyHead) ); - memset( re_decalPolyTotal, 0, sizeof(re_decalPolyTotal) ); +void RE_ClearDecals(void) { + memset(re_decalPolys, 0, sizeof(re_decalPolys)); + memset(re_decalPolyHead, 0, sizeof(re_decalPolyHead)); + memset(re_decalPolyTotal, 0, sizeof(re_decalPolyTotal)); } -void R_InitDecals( void ) { - RE_ClearDecals(); -} +void R_InitDecals(void) { RE_ClearDecals(); } -void RE_FreeDecal( int type, int index ) { - if ( !re_decalPolys[type][index].time ) +void RE_FreeDecal(int type, int index) { + if (!re_decalPolys[type][index].time) return; - - if ( type == DECALPOLY_TYPE_NORMAL ) { - decalPoly_t* fade; - fade = RE_AllocDecal( DECALPOLY_TYPE_FADE ); + if (type == DECALPOLY_TYPE_NORMAL) { + decalPoly_t *fade; + + fade = RE_AllocDecal(DECALPOLY_TYPE_FADE); - memcpy( fade, &re_decalPolys[type][index], sizeof( decalPoly_t ) ); + memcpy(fade, &re_decalPolys[type][index], sizeof(decalPoly_t)); fade->time = tr.refdef.time; fade->fadetime = tr.refdef.time + DECAL_FADE_TIME; @@ -73,48 +65,47 @@ RE_AllocDecal Will allways succeed, even if it requires freeing an old active mark =================== */ -decalPoly_t* RE_AllocDecal( int type ) { - decalPoly_t *le; - +decalPoly_t *RE_AllocDecal(int type) { + decalPoly_t *le; + // See if the cvar changed - if ( re_decalPolyTotal[type] > r_markcount->integer ) + if (re_decalPolyTotal[type] > r_markcount->integer) RE_ClearDecals(); le = &re_decalPolys[type][re_decalPolyHead[type]]; // If it has no time its the first occasion its been used - if ( le->time ) { - if ( le->time != tr.refdef.time ) { - int i = re_decalPolyHead[type]; + if (le->time) { + if (le->time != tr.refdef.time) { + int i = re_decalPolyHead[type]; - // since we are killing one that existed before, make sure we + // since we are killing one that existed before, make sure we // kill all the other marks that belong to the group do { i++; - if ( i >= r_markcount->integer ) + if (i >= r_markcount->integer) i = 0; // Break out on the first one thats not part of the group - if ( re_decalPolys[type][i].time != le->time ) + if (re_decalPolys[type][i].time != le->time) break; - RE_FreeDecal ( type, i ); - } while ( i != re_decalPolyHead[type] ); + RE_FreeDecal(type, i); + } while (i != re_decalPolyHead[type]); - RE_FreeDecal( type, re_decalPolyHead[type] ); - } - else - RE_FreeDecal( type, re_decalPolyHead[type] ); + RE_FreeDecal(type, re_decalPolyHead[type]); + } else + RE_FreeDecal(type, re_decalPolyHead[type]); } - memset( le, 0, sizeof(decalPoly_t) ); + memset(le, 0, sizeof(decalPoly_t)); le->time = tr.refdef.time; re_decalPolyTotal[type]++; // Move on to the next decal poly and wrap around if need be re_decalPolyHead[type]++; - if ( re_decalPolyHead[type] >= r_markcount->integer ) + if (re_decalPolyHead[type] >= r_markcount->integer) re_decalPolyHead[type] = 0; return le; @@ -131,40 +122,39 @@ temporary marks will not be stored or randomly oriented, but immediately passed to the renderer. ================= */ -#define MAX_DECAL_FRAGMENTS 128 -#define MAX_DECAL_POINTS 384 - -void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, qboolean alphaFade, float radius, qboolean temporary ) -{ - matrix3_t axis; - float texCoordScale; - vec3_t originalPoints[4]; - byte colors[4]; - int i, j; - int numFragments; - markFragment_t markFragments[MAX_DECAL_FRAGMENTS], *mf; - vec3_t markPoints[MAX_DECAL_POINTS]; - vec3_t projection; +#define MAX_DECAL_FRAGMENTS 128 +#define MAX_DECAL_POINTS 384 + +void RE_AddDecalToScene(qhandle_t decalShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, + qboolean alphaFade, float radius, qboolean temporary) { + matrix3_t axis; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j; + int numFragments; + markFragment_t markFragments[MAX_DECAL_FRAGMENTS], *mf; + vec3_t markPoints[MAX_DECAL_POINTS]; + vec3_t projection; assert(decalShader); - if ( r_markcount->integer <= 0 && !temporary ) + if (r_markcount->integer <= 0 && !temporary) return; - if ( radius <= 0 ) - Com_Error( ERR_FATAL, "RE_AddDecalToScene: called with <= 0 radius" ); + if (radius <= 0) + Com_Error(ERR_FATAL, "RE_AddDecalToScene: called with <= 0 radius"); // create the texture axis - VectorNormalize2( dir, axis[0] ); - PerpendicularVector( axis[1], axis[0] ); - RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); - CrossProduct( axis[0], axis[2], axis[1] ); + VectorNormalize2(dir, axis[0]); + PerpendicularVector(axis[1], axis[0]); + RotatePointAroundVector(axis[2], axis[0], axis[1], orientation); + CrossProduct(axis[0], axis[2], axis[1]); texCoordScale = 0.5 * 1.0 / radius; // create the full polygon - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; @@ -172,49 +162,44 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ } // get the fragments - VectorScale( dir, -20, projection ); - numFragments = R_MarkFragments( 4, (const vec3_t*)originalPoints, - projection, MAX_DECAL_POINTS, markPoints[0], - MAX_DECAL_FRAGMENTS, markFragments ); + VectorScale(dir, -20, projection); + numFragments = R_MarkFragments(4, (const vec3_t *)originalPoints, projection, MAX_DECAL_POINTS, markPoints[0], MAX_DECAL_FRAGMENTS, markFragments); colors[0] = red * 255; colors[1] = green * 255; colors[2] = blue * 255; colors[3] = alpha * 255; - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) - { - polyVert_t *v; - polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; - decalPoly_t *decal; + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; + decalPoly_t *decal; // we have an upper limit on the complexity of polygons // that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_DECAL_POLY ) + if (mf->numPoints > MAX_VERTS_ON_DECAL_POLY) mf->numPoints = MAX_VERTS_ON_DECAL_POLY; - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) - { - vec3_t delta; + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { + vec3_t delta; - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); - VectorSubtract( v->xyz, origin, delta ); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale; - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale; + VectorSubtract(v->xyz, origin, delta); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * texCoordScale; + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * texCoordScale; *(int *)v->modulate = *(int *)colors; } // if it is a temporary (shadow) mark, add it immediately and forget about it - if ( temporary ) - { - RE_AddPolyToScene( decalShader, mf->numPoints, verts, 1 ); + if (temporary) { + RE_AddPolyToScene(decalShader, mf->numPoints, verts, 1); continue; } // otherwise save it persistantly - decal = RE_AllocDecal( DECALPOLY_TYPE_NORMAL ); + decal = RE_AllocDecal(DECALPOLY_TYPE_NORMAL); decal->time = tr.refdef.time; decal->shader = decalShader; decal->poly.numVerts = mf->numPoints; @@ -222,7 +207,7 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ decal->color[1] = green; decal->color[2] = blue; decal->color[3] = alpha; - memcpy( decal->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(decal->verts, verts, mf->numPoints * sizeof(verts[0])); } } @@ -231,69 +216,56 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ R_AddDecals =============== */ -void R_AddDecals( void ) -{ - int decalPoly; - int type; - static int lastMarkCount = -1; - - if ( r_markcount->integer != lastMarkCount ) { - if ( lastMarkCount != -1 ) +void R_AddDecals(void) { + int decalPoly; + int type; + static int lastMarkCount = -1; + + if (r_markcount->integer != lastMarkCount) { + if (lastMarkCount != -1) RE_ClearDecals(); lastMarkCount = r_markcount->integer; } - if ( r_markcount->integer <= 0 ) + if (r_markcount->integer <= 0) return; - for ( type = DECALPOLY_TYPE_NORMAL; type < DECALPOLY_TYPE_MAX; type ++ ) - { + for (type = DECALPOLY_TYPE_NORMAL; type < DECALPOLY_TYPE_MAX; type++) { decalPoly = re_decalPolyHead[type]; - do - { - decalPoly_t* p = &re_decalPolys[type][decalPoly]; + do { + decalPoly_t *p = &re_decalPolys[type][decalPoly]; - if ( p->time ) - { - if ( p->fadetime ) - { + if (p->time) { + if (p->fadetime) { int t; // fade all marks out with time t = tr.refdef.time - p->time; - if ( t < DECAL_FADE_TIME ) - { + if (t < DECAL_FADE_TIME) { float fade; - int j; + int j; fade = 255.0f * (1.0f - ((float)t / DECAL_FADE_TIME)); - - for ( j = 0 ; j < p->poly.numVerts ; j++ ) - { + + for (j = 0; j < p->poly.numVerts; j++) { p->verts[j].modulate[3] = fade; } - RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); - } - else - { - RE_FreeDecal ( type, decalPoly ); + RE_AddPolyToScene(p->shader, p->poly.numVerts, p->verts, 1); + } else { + RE_FreeDecal(type, decalPoly); } - } - else - { - RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); + } else { + RE_AddPolyToScene(p->shader, p->poly.numVerts, p->verts, 1); } } decalPoly++; - if ( decalPoly >= r_markcount->integer ) - { + if (decalPoly >= r_markcount->integer) { decalPoly = 0; } - } - while ( decalPoly != re_decalPolyHead[type] ); + } while (decalPoly != re_decalPolyHead[type]); } } diff --git a/codemp/rd-rend2/tr_extensions.cpp b/codemp/rd-rend2/tr_extensions.cpp index 55bf6c9ffe..94bb76418f 100644 --- a/codemp/rd-rend2/tr_extensions.cpp +++ b/codemp/rd-rend2/tr_extensions.cpp @@ -241,24 +241,19 @@ PFNGLQUERYCOUNTERPROC qglQueryCounter; PFNGLGETQUERYOBJECTI64VPROC qglGetQueryObjecti64v; PFNGLGETQUERYOBJECTUI64VPROC qglGetQueryObjectui64v; -static qboolean GLimp_HaveExtension(const char *ext) -{ - const char *ptr = Q_stristr( glConfigExt.originalExtensionString, ext ); +static qboolean GLimp_HaveExtension(const char *ext) { + const char *ptr = Q_stristr(glConfigExt.originalExtensionString, ext); if (ptr == NULL) return qfalse; ptr += strlen(ext); - return (qboolean)((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. + return (qboolean)((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. } -template -static qboolean GetGLFunction ( GLFuncType& glFunction, const char *glFunctionString, qboolean errorOnFailure ) -{ - glFunction = (GLFuncType)GL_GetProcAddress (glFunctionString); - if ( glFunction == NULL ) - { - if ( errorOnFailure ) - { - Com_Error (ERR_FATAL, "ERROR: OpenGL function '%s' could not be found.\n", glFunctionString); +template static qboolean GetGLFunction(GLFuncType &glFunction, const char *glFunctionString, qboolean errorOnFailure) { + glFunction = (GLFuncType)GL_GetProcAddress(glFunctionString); + if (glFunction == NULL) { + if (errorOnFailure) { + Com_Error(ERR_FATAL, "ERROR: OpenGL function '%s' could not be found.\n", glFunctionString); } return qfalse; @@ -267,205 +262,228 @@ static qboolean GetGLFunction ( GLFuncType& glFunction, const char *glFunctionSt return qtrue; } - -static void QCALL GLimp_OnError(GLenum source, GLenum type, GLuint id, GLenum severity, - GLsizei length, const GLchar *message, const void *userParam) -{ +static void QCALL GLimp_OnError(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { const char *severityText = ""; const char *typeText = ""; const char *sourceText = ""; - switch ( source ) - { - case GL_DEBUG_SOURCE_API_ARB: sourceText = "API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: sourceText = "WS"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: sourceText = "SC"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: sourceText = "3rd"; break; - case GL_DEBUG_SOURCE_APPLICATION_ARB: sourceText = "App"; break; - case GL_DEBUG_SOURCE_OTHER_ARB: sourceText = "Oth"; break; + switch (source) { + case GL_DEBUG_SOURCE_API_ARB: + sourceText = "API"; + break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: + sourceText = "WS"; + break; + case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: + sourceText = "SC"; + break; + case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: + sourceText = "3rd"; + break; + case GL_DEBUG_SOURCE_APPLICATION_ARB: + sourceText = "App"; + break; + case GL_DEBUG_SOURCE_OTHER_ARB: + sourceText = "Oth"; + break; } - switch ( severity ) - { - case GL_DEBUG_SEVERITY_HIGH_ARB: severityText = "High"; break; - case GL_DEBUG_SEVERITY_MEDIUM_ARB: severityText = "Medium"; break; - case GL_DEBUG_SEVERITY_LOW_ARB: severityText = "Low"; break; + switch (severity) { + case GL_DEBUG_SEVERITY_HIGH_ARB: + severityText = "High"; + break; + case GL_DEBUG_SEVERITY_MEDIUM_ARB: + severityText = "Medium"; + break; + case GL_DEBUG_SEVERITY_LOW_ARB: + severityText = "Low"; + break; } - switch ( type ) - { - case GL_DEBUG_TYPE_ERROR_ARB: typeText = "Error"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: typeText = "Deprecated"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: typeText = "Undefined"; break; - case GL_DEBUG_TYPE_PORTABILITY_ARB: typeText = "Portability"; break; - case GL_DEBUG_TYPE_PERFORMANCE_ARB: typeText = "Performance"; break; - case GL_DEBUG_TYPE_OTHER_ARB: typeText = "Other"; break; + switch (type) { + case GL_DEBUG_TYPE_ERROR_ARB: + typeText = "Error"; + break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: + typeText = "Deprecated"; + break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: + typeText = "Undefined"; + break; + case GL_DEBUG_TYPE_PORTABILITY_ARB: + typeText = "Portability"; + break; + case GL_DEBUG_TYPE_PERFORMANCE_ARB: + typeText = "Performance"; + break; + case GL_DEBUG_TYPE_OTHER_ARB: + typeText = "Other"; + break; } - Com_Printf( S_COLOR_YELLOW "OpenGL -> [%s][%s][%s] %s\n", sourceText, severityText, typeText, message ); + Com_Printf(S_COLOR_YELLOW "OpenGL -> [%s][%s][%s] %s\n", sourceText, severityText, typeText, message); } -void GLimp_InitCoreFunctions() -{ +void GLimp_InitCoreFunctions() { Com_Printf("Initializing OpenGL 3.2 functions\n"); // Drawing commands - GetGLFunction (qglDrawRangeElements, "glDrawRangeElements", qtrue); - GetGLFunction (qglDrawArraysInstanced, "glDrawArraysInstanced", qtrue); - GetGLFunction (qglDrawElementsInstanced, "glDrawElementsInstanced", qtrue); - GetGLFunction (qglDrawElementsBaseVertex, "glDrawElementsBaseVertex", qtrue); - GetGLFunction (qglDrawRangeElementsBaseVertex, "glDrawRangeElementsBaseVertex", qtrue); - GetGLFunction (qglDrawElementsInstancedBaseVertex, "glDrawElementsInstancedBaseVertex", qtrue); - GetGLFunction (qglMultiDrawArrays, "glMultiDrawArrays", qtrue); - GetGLFunction (qglMultiDrawElements, "glMultiDrawElements", qtrue); - GetGLFunction (qglMultiDrawElementsBaseVertex, "glMultiDrawElementsBaseVertex", qtrue); + GetGLFunction(qglDrawRangeElements, "glDrawRangeElements", qtrue); + GetGLFunction(qglDrawArraysInstanced, "glDrawArraysInstanced", qtrue); + GetGLFunction(qglDrawElementsInstanced, "glDrawElementsInstanced", qtrue); + GetGLFunction(qglDrawElementsBaseVertex, "glDrawElementsBaseVertex", qtrue); + GetGLFunction(qglDrawRangeElementsBaseVertex, "glDrawRangeElementsBaseVertex", qtrue); + GetGLFunction(qglDrawElementsInstancedBaseVertex, "glDrawElementsInstancedBaseVertex", qtrue); + GetGLFunction(qglMultiDrawArrays, "glMultiDrawArrays", qtrue); + GetGLFunction(qglMultiDrawElements, "glMultiDrawElements", qtrue); + GetGLFunction(qglMultiDrawElementsBaseVertex, "glMultiDrawElementsBaseVertex", qtrue); // Vertex arrays - GetGLFunction (qglVertexAttribPointer, "glVertexAttribPointer", qtrue); - GetGLFunction (qglVertexAttribIPointer, "glVertexAttribIPointer", qtrue); - GetGLFunction (qglVertexAttribDivisor, "glVertexAttribDivisor", qtrue); - GetGLFunction (qglEnableVertexAttribArray, "glEnableVertexAttribArray", qtrue); - GetGLFunction (qglDisableVertexAttribArray, "glDisableVertexAttribArray", qtrue); + GetGLFunction(qglVertexAttribPointer, "glVertexAttribPointer", qtrue); + GetGLFunction(qglVertexAttribIPointer, "glVertexAttribIPointer", qtrue); + GetGLFunction(qglVertexAttribDivisor, "glVertexAttribDivisor", qtrue); + GetGLFunction(qglEnableVertexAttribArray, "glEnableVertexAttribArray", qtrue); + GetGLFunction(qglDisableVertexAttribArray, "glDisableVertexAttribArray", qtrue); // Vertex array objects - GetGLFunction (qglGenVertexArrays, "glGenVertexArrays", qtrue); - GetGLFunction (qglDeleteVertexArrays, "glDeleteVertexArrays", qtrue); - GetGLFunction (qglBindVertexArray, "glBindVertexArray", qtrue); - GetGLFunction (qglIsVertexArray, "glIsVertexArray", qtrue); - - GetGLFunction (qglVertexAttrib1f, "glVertexAttrib1f", qtrue); - GetGLFunction (qglVertexAttrib2f, "glVertexAttrib2f", qtrue); - GetGLFunction (qglVertexAttrib3f, "glVertexAttrib3f", qtrue); - GetGLFunction (qglVertexAttrib4f, "glVertexAttrib4f", qtrue); - + GetGLFunction(qglGenVertexArrays, "glGenVertexArrays", qtrue); + GetGLFunction(qglDeleteVertexArrays, "glDeleteVertexArrays", qtrue); + GetGLFunction(qglBindVertexArray, "glBindVertexArray", qtrue); + GetGLFunction(qglIsVertexArray, "glIsVertexArray", qtrue); + + GetGLFunction(qglVertexAttrib1f, "glVertexAttrib1f", qtrue); + GetGLFunction(qglVertexAttrib2f, "glVertexAttrib2f", qtrue); + GetGLFunction(qglVertexAttrib3f, "glVertexAttrib3f", qtrue); + GetGLFunction(qglVertexAttrib4f, "glVertexAttrib4f", qtrue); + // Buffer objects qglGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &glRefConfig.uniformBufferOffsetAlignment); qglGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &glRefConfig.maxUniformBlockSize); qglGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &glRefConfig.maxUniformBufferBindings); - GetGLFunction (qglBindBuffer, "glBindBuffer", qtrue); - GetGLFunction (qglDeleteBuffers, "glDeleteBuffers", qtrue); - GetGLFunction (qglGenBuffers, "glGenBuffers", qtrue); - GetGLFunction (qglBufferData, "glBufferData", qtrue); - GetGLFunction (qglBufferSubData, "glBufferSubData", qtrue); - GetGLFunction (qglGetBufferSubData, "glGetBufferSubData", qtrue); - GetGLFunction (qglGetBufferParameteriv, "glGetBufferParameteriv", qtrue); - GetGLFunction (qglGetBufferParameteri64v, "glGetBufferParameteri64v", qtrue); - GetGLFunction (qglGetBufferPointerv, "glGetBufferPointerv", qtrue); - GetGLFunction (qglBindBufferRange, "glBindBufferRange", qtrue); - GetGLFunction (qglBindBufferBase, "glBindBufferBase", qtrue); - GetGLFunction (qglMapBufferRange, "glMapBufferRange", qtrue); - GetGLFunction (qglMapBuffer, "glMapBuffer", qtrue); - GetGLFunction (qglFlushMappedBufferRange, "glFlushMappedBufferRange", qtrue); - GetGLFunction (qglUnmapBuffer, "glUnmapBuffer", qtrue); - GetGLFunction (qglCopyBufferSubData, "glCopyBufferSubData", qtrue); - GetGLFunction (qglIsBuffer, "glIsBuffer", qtrue); + GetGLFunction(qglBindBuffer, "glBindBuffer", qtrue); + GetGLFunction(qglDeleteBuffers, "glDeleteBuffers", qtrue); + GetGLFunction(qglGenBuffers, "glGenBuffers", qtrue); + GetGLFunction(qglBufferData, "glBufferData", qtrue); + GetGLFunction(qglBufferSubData, "glBufferSubData", qtrue); + GetGLFunction(qglGetBufferSubData, "glGetBufferSubData", qtrue); + GetGLFunction(qglGetBufferParameteriv, "glGetBufferParameteriv", qtrue); + GetGLFunction(qglGetBufferParameteri64v, "glGetBufferParameteri64v", qtrue); + GetGLFunction(qglGetBufferPointerv, "glGetBufferPointerv", qtrue); + GetGLFunction(qglBindBufferRange, "glBindBufferRange", qtrue); + GetGLFunction(qglBindBufferBase, "glBindBufferBase", qtrue); + GetGLFunction(qglMapBufferRange, "glMapBufferRange", qtrue); + GetGLFunction(qglMapBuffer, "glMapBuffer", qtrue); + GetGLFunction(qglFlushMappedBufferRange, "glFlushMappedBufferRange", qtrue); + GetGLFunction(qglUnmapBuffer, "glUnmapBuffer", qtrue); + GetGLFunction(qglCopyBufferSubData, "glCopyBufferSubData", qtrue); + GetGLFunction(qglIsBuffer, "glIsBuffer", qtrue); // Texturing - GetGLFunction (qglActiveTexture, "glActiveTexture", qtrue); - GetGLFunction (qglTexImage3D, "glTexImage3D", qtrue); + GetGLFunction(qglActiveTexture, "glActiveTexture", qtrue); + GetGLFunction(qglTexImage3D, "glTexImage3D", qtrue); // Shader objects - GetGLFunction (qglCreateShader, "glCreateShader", qtrue); - GetGLFunction (qglShaderSource, "glShaderSource", qtrue); - GetGLFunction (qglCompileShader, "glCompileShader", qtrue); - GetGLFunction (qglDeleteShader, "glDeleteShader", qtrue); - GetGLFunction (qglIsShader, "glIsShader", qtrue); - GetGLFunction (qglGetShaderiv, "glGetShaderiv", qtrue); - GetGLFunction (qglGetShaderInfoLog, "glGetShaderInfoLog", qtrue); - GetGLFunction (qglGetShaderSource, "glGetShaderSource", qtrue); + GetGLFunction(qglCreateShader, "glCreateShader", qtrue); + GetGLFunction(qglShaderSource, "glShaderSource", qtrue); + GetGLFunction(qglCompileShader, "glCompileShader", qtrue); + GetGLFunction(qglDeleteShader, "glDeleteShader", qtrue); + GetGLFunction(qglIsShader, "glIsShader", qtrue); + GetGLFunction(qglGetShaderiv, "glGetShaderiv", qtrue); + GetGLFunction(qglGetShaderInfoLog, "glGetShaderInfoLog", qtrue); + GetGLFunction(qglGetShaderSource, "glGetShaderSource", qtrue); // Program objects - GetGLFunction (qglCreateProgram, "glCreateProgram", qtrue); - GetGLFunction (qglAttachShader, "glAttachShader", qtrue); - GetGLFunction (qglDetachShader, "glDetachShader", qtrue); - GetGLFunction (qglLinkProgram, "glLinkProgram", qtrue); - GetGLFunction (qglUseProgram, "glUseProgram", qtrue); - GetGLFunction (qglDeleteProgram, "glDeleteProgram", qtrue); - GetGLFunction (qglValidateProgram, "glValidateProgram", qtrue); - GetGLFunction (qglIsProgram, "glIsProgram", qtrue); - GetGLFunction (qglGetProgramiv, "glGetProgramiv", qtrue); - GetGLFunction (qglGetAttachedShaders, "glGetAttachedShaders", qtrue); - GetGLFunction (qglGetProgramInfoLog, "glGetProgramInfoLog", qtrue); - GetGLFunction (qglBindFragDataLocation, "glBindFragDataLocation", qtrue); + GetGLFunction(qglCreateProgram, "glCreateProgram", qtrue); + GetGLFunction(qglAttachShader, "glAttachShader", qtrue); + GetGLFunction(qglDetachShader, "glDetachShader", qtrue); + GetGLFunction(qglLinkProgram, "glLinkProgram", qtrue); + GetGLFunction(qglUseProgram, "glUseProgram", qtrue); + GetGLFunction(qglDeleteProgram, "glDeleteProgram", qtrue); + GetGLFunction(qglValidateProgram, "glValidateProgram", qtrue); + GetGLFunction(qglIsProgram, "glIsProgram", qtrue); + GetGLFunction(qglGetProgramiv, "glGetProgramiv", qtrue); + GetGLFunction(qglGetAttachedShaders, "glGetAttachedShaders", qtrue); + GetGLFunction(qglGetProgramInfoLog, "glGetProgramInfoLog", qtrue); + GetGLFunction(qglBindFragDataLocation, "glBindFragDataLocation", qtrue); // Vertex attributes - GetGLFunction (qglGetActiveAttrib, "glGetActiveAttrib", qtrue); - GetGLFunction (qglGetAttribLocation, "glGetAttribLocation", qtrue); - GetGLFunction (qglBindAttribLocation, "glBindAttribLocation", qtrue); - GetGLFunction (qglGetVertexAttribdv, "glGetVertexAttribdv", qtrue); - GetGLFunction (qglGetVertexAttribfv, "glGetVertexAttribfv", qtrue); - GetGLFunction (qglGetVertexAttribiv, "glGetVertexAttribiv", qtrue); - GetGLFunction (qglGetVertexAttribIiv, "glGetVertexAttribIiv", qtrue); - GetGLFunction (qglGetVertexAttribIuiv, "glGetVertexAttribIuiv", qtrue); + GetGLFunction(qglGetActiveAttrib, "glGetActiveAttrib", qtrue); + GetGLFunction(qglGetAttribLocation, "glGetAttribLocation", qtrue); + GetGLFunction(qglBindAttribLocation, "glBindAttribLocation", qtrue); + GetGLFunction(qglGetVertexAttribdv, "glGetVertexAttribdv", qtrue); + GetGLFunction(qglGetVertexAttribfv, "glGetVertexAttribfv", qtrue); + GetGLFunction(qglGetVertexAttribiv, "glGetVertexAttribiv", qtrue); + GetGLFunction(qglGetVertexAttribIiv, "glGetVertexAttribIiv", qtrue); + GetGLFunction(qglGetVertexAttribIuiv, "glGetVertexAttribIuiv", qtrue); // Varying variables - GetGLFunction (qglTransformFeedbackVaryings, "glTransformFeedbackVaryings", qtrue); - GetGLFunction (qglGetTransformFeedbackVarying, "glGetTransformFeedbackVarying", qtrue); + GetGLFunction(qglTransformFeedbackVaryings, "glTransformFeedbackVaryings", qtrue); + GetGLFunction(qglGetTransformFeedbackVarying, "glGetTransformFeedbackVarying", qtrue); // Uniform variables - GetGLFunction (qglGetUniformLocation, "glGetUniformLocation", qtrue); - GetGLFunction (qglGetUniformBlockIndex, "glGetUniformBlockIndex", qtrue); - GetGLFunction (qglGetActiveUniformBlockName, "glGetActiveUniformBlockName", qtrue); - GetGLFunction (qglGetActiveUniformBlockiv, "glGetActiveUniformBlockiv", qtrue); - GetGLFunction (qglGetUniformIndices, "glGetUniformIndices", qtrue); - GetGLFunction (qglGetActiveUniformName, "glGetActiveUniformName", qtrue); - GetGLFunction (qglGetActiveUniform, "glGetActiveUniform", qtrue); - GetGLFunction (qglGetActiveUniformsiv, "glGetActiveUniformsiv", qtrue); - GetGLFunction (qglUniform1i, "glUniform1i", qtrue); - GetGLFunction (qglUniform2i, "glUniform2i", qtrue); - GetGLFunction (qglUniform3i, "glUniform3i", qtrue); - GetGLFunction (qglUniform4i, "glUniform4i", qtrue); - GetGLFunction (qglUniform1f, "glUniform1f", qtrue); - GetGLFunction (qglUniform2f, "glUniform2f", qtrue); - GetGLFunction (qglUniform3f, "glUniform3f", qtrue); - GetGLFunction (qglUniform4f, "glUniform4f", qtrue); - GetGLFunction (qglUniform1iv, "glUniform1iv", qtrue); - GetGLFunction (qglUniform2iv, "glUniform2iv", qtrue); - GetGLFunction (qglUniform3iv, "glUniform3iv", qtrue); - GetGLFunction (qglUniform4iv, "glUniform4iv", qtrue); - GetGLFunction (qglUniform1fv, "glUniform1fv", qtrue); - GetGLFunction (qglUniform2fv, "glUniform2fv", qtrue); - GetGLFunction (qglUniform3fv, "glUniform3fv", qtrue); - GetGLFunction (qglUniform4fv, "glUniform4fv", qtrue); - GetGLFunction (qglUniform1ui, "glUniform1ui", qtrue); - GetGLFunction (qglUniform2ui, "glUniform2ui", qtrue); - GetGLFunction (qglUniform3ui, "glUniform3ui", qtrue); - GetGLFunction (qglUniform4ui, "glUniform4ui", qtrue); - GetGLFunction (qglUniform1uiv, "glUniform1uiv", qtrue); - GetGLFunction (qglUniform2uiv, "glUniform2uiv", qtrue); - GetGLFunction (qglUniform3uiv, "glUniform3uiv", qtrue); - GetGLFunction (qglUniform4uiv, "glUniform4uiv", qtrue); - GetGLFunction (qglUniformMatrix2fv, "glUniformMatrix2fv", qtrue); - GetGLFunction (qglUniformMatrix3fv, "glUniformMatrix3fv", qtrue); - GetGLFunction (qglUniformMatrix4fv, "glUniformMatrix4fv", qtrue); - GetGLFunction (qglUniformMatrix2x3fv, "glUniformMatrix2x3fv", qtrue); - GetGLFunction (qglUniformMatrix3x2fv, "glUniformMatrix3x2fv", qtrue); - GetGLFunction (qglUniformMatrix2x4fv, "glUniformMatrix2x4fv", qtrue); - GetGLFunction (qglUniformMatrix4x2fv, "glUniformMatrix4x2fv", qtrue); - GetGLFunction (qglUniformMatrix3x4fv, "glUniformMatrix3x4fv", qtrue); - GetGLFunction (qglUniformMatrix4x3fv, "glUniformMatrix4x3fv", qtrue); - GetGLFunction (qglUniformBlockBinding, "glUniformBlockBinding", qtrue); - GetGLFunction (qglGetUniformfv, "glGetUniformfv", qtrue); - GetGLFunction (qglGetUniformiv, "glGetUniformiv", qtrue); - GetGLFunction (qglGetUniformuiv, "glGetUniformuiv", qtrue); + GetGLFunction(qglGetUniformLocation, "glGetUniformLocation", qtrue); + GetGLFunction(qglGetUniformBlockIndex, "glGetUniformBlockIndex", qtrue); + GetGLFunction(qglGetActiveUniformBlockName, "glGetActiveUniformBlockName", qtrue); + GetGLFunction(qglGetActiveUniformBlockiv, "glGetActiveUniformBlockiv", qtrue); + GetGLFunction(qglGetUniformIndices, "glGetUniformIndices", qtrue); + GetGLFunction(qglGetActiveUniformName, "glGetActiveUniformName", qtrue); + GetGLFunction(qglGetActiveUniform, "glGetActiveUniform", qtrue); + GetGLFunction(qglGetActiveUniformsiv, "glGetActiveUniformsiv", qtrue); + GetGLFunction(qglUniform1i, "glUniform1i", qtrue); + GetGLFunction(qglUniform2i, "glUniform2i", qtrue); + GetGLFunction(qglUniform3i, "glUniform3i", qtrue); + GetGLFunction(qglUniform4i, "glUniform4i", qtrue); + GetGLFunction(qglUniform1f, "glUniform1f", qtrue); + GetGLFunction(qglUniform2f, "glUniform2f", qtrue); + GetGLFunction(qglUniform3f, "glUniform3f", qtrue); + GetGLFunction(qglUniform4f, "glUniform4f", qtrue); + GetGLFunction(qglUniform1iv, "glUniform1iv", qtrue); + GetGLFunction(qglUniform2iv, "glUniform2iv", qtrue); + GetGLFunction(qglUniform3iv, "glUniform3iv", qtrue); + GetGLFunction(qglUniform4iv, "glUniform4iv", qtrue); + GetGLFunction(qglUniform1fv, "glUniform1fv", qtrue); + GetGLFunction(qglUniform2fv, "glUniform2fv", qtrue); + GetGLFunction(qglUniform3fv, "glUniform3fv", qtrue); + GetGLFunction(qglUniform4fv, "glUniform4fv", qtrue); + GetGLFunction(qglUniform1ui, "glUniform1ui", qtrue); + GetGLFunction(qglUniform2ui, "glUniform2ui", qtrue); + GetGLFunction(qglUniform3ui, "glUniform3ui", qtrue); + GetGLFunction(qglUniform4ui, "glUniform4ui", qtrue); + GetGLFunction(qglUniform1uiv, "glUniform1uiv", qtrue); + GetGLFunction(qglUniform2uiv, "glUniform2uiv", qtrue); + GetGLFunction(qglUniform3uiv, "glUniform3uiv", qtrue); + GetGLFunction(qglUniform4uiv, "glUniform4uiv", qtrue); + GetGLFunction(qglUniformMatrix2fv, "glUniformMatrix2fv", qtrue); + GetGLFunction(qglUniformMatrix3fv, "glUniformMatrix3fv", qtrue); + GetGLFunction(qglUniformMatrix4fv, "glUniformMatrix4fv", qtrue); + GetGLFunction(qglUniformMatrix2x3fv, "glUniformMatrix2x3fv", qtrue); + GetGLFunction(qglUniformMatrix3x2fv, "glUniformMatrix3x2fv", qtrue); + GetGLFunction(qglUniformMatrix2x4fv, "glUniformMatrix2x4fv", qtrue); + GetGLFunction(qglUniformMatrix4x2fv, "glUniformMatrix4x2fv", qtrue); + GetGLFunction(qglUniformMatrix3x4fv, "glUniformMatrix3x4fv", qtrue); + GetGLFunction(qglUniformMatrix4x3fv, "glUniformMatrix4x3fv", qtrue); + GetGLFunction(qglUniformBlockBinding, "glUniformBlockBinding", qtrue); + GetGLFunction(qglGetUniformfv, "glGetUniformfv", qtrue); + GetGLFunction(qglGetUniformiv, "glGetUniformiv", qtrue); + GetGLFunction(qglGetUniformuiv, "glGetUniformuiv", qtrue); // Transform feedback - GetGLFunction (qglBeginTransformFeedback, "glBeginTransformFeedback", qtrue); - GetGLFunction (qglEndTransformFeedback, "glEndTransformFeedback", qtrue); + GetGLFunction(qglBeginTransformFeedback, "glBeginTransformFeedback", qtrue); + GetGLFunction(qglEndTransformFeedback, "glEndTransformFeedback", qtrue); // Texture compression - GetGLFunction (qglCompressedTexImage3D, "glCompressedTexImage3D", qtrue); - GetGLFunction (qglCompressedTexImage2D, "glCompressedTexImage2D", qtrue); - GetGLFunction (qglCompressedTexImage1D, "glCompressedTexImage1D", qtrue); - GetGLFunction (qglCompressedTexSubImage3D, "glCompressedTexSubImage3D", qtrue); - GetGLFunction (qglCompressedTexSubImage2D, "glCompressedTexSubImage2D", qtrue); - GetGLFunction (qglCompressedTexSubImage1D, "glCompressedTexSubImage1D", qtrue); - GetGLFunction (qglGetCompressedTexImage, "glGetCompressedTexImage", qtrue); + GetGLFunction(qglCompressedTexImage3D, "glCompressedTexImage3D", qtrue); + GetGLFunction(qglCompressedTexImage2D, "glCompressedTexImage2D", qtrue); + GetGLFunction(qglCompressedTexImage1D, "glCompressedTexImage1D", qtrue); + GetGLFunction(qglCompressedTexSubImage3D, "glCompressedTexSubImage3D", qtrue); + GetGLFunction(qglCompressedTexSubImage2D, "glCompressedTexSubImage2D", qtrue); + GetGLFunction(qglCompressedTexSubImage1D, "glCompressedTexSubImage1D", qtrue); + GetGLFunction(qglGetCompressedTexImage, "glGetCompressedTexImage", qtrue); // GLSL { char version[256]; - Q_strncpyz( version, (const char *) qglGetString (GL_SHADING_LANGUAGE_VERSION), sizeof( version ) ); + Q_strncpyz(version, (const char *)qglGetString(GL_SHADING_LANGUAGE_VERSION), sizeof(version)); sscanf(version, "%d.%d", &glRefConfig.glslMajorVersion, &glRefConfig.glslMinorVersion); ri.Printf(PRINT_ALL, "...using GLSL version %s\n", version); @@ -475,98 +493,86 @@ void GLimp_InitCoreFunctions() qglGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &glRefConfig.maxRenderbufferSize); qglGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &glRefConfig.maxColorAttachments); - GetGLFunction (qglIsRenderbuffer, "glIsRenderbuffer", qtrue); - GetGLFunction (qglBindRenderbuffer, "glBindRenderbuffer", qtrue); - GetGLFunction (qglDeleteRenderbuffers, "glDeleteRenderbuffers", qtrue); - GetGLFunction (qglGenRenderbuffers, "glGenRenderbuffers", qtrue); - GetGLFunction (qglRenderbufferStorage, "glRenderbufferStorage", qtrue); - GetGLFunction (qglGetRenderbufferParameteriv, "glGetRenderbufferParameteriv", qtrue); - GetGLFunction (qglIsFramebuffer, "glIsFramebuffer", qtrue); - GetGLFunction (qglBindFramebuffer, "glBindFramebuffer", qtrue); - GetGLFunction (qglDeleteFramebuffers, "glDeleteFramebuffers", qtrue); - GetGLFunction (qglGenFramebuffers, "glGenFramebuffers", qtrue); - GetGLFunction (qglCheckFramebufferStatus, "glCheckFramebufferStatus", qtrue); - GetGLFunction (qglFramebufferTexture1D, "glFramebufferTexture1D", qtrue); - GetGLFunction (qglFramebufferTexture2D, "glFramebufferTexture2D", qtrue); - GetGLFunction (qglFramebufferTexture3D, "glFramebufferTexture3D", qtrue); - GetGLFunction (qglFramebufferTexture, "glFramebufferTexture", qtrue); - GetGLFunction (qglFramebufferTextureLayer, "glFramebufferTextureLayer", qtrue); - GetGLFunction (qglFramebufferRenderbuffer, "glFramebufferRenderbuffer", qtrue); - GetGLFunction (qglGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv", qtrue); - GetGLFunction (qglRenderbufferStorageMultisample, "glRenderbufferStorageMultisample", qtrue); - GetGLFunction (qglBlitFramebuffer, "glBlitFramebuffer", qtrue); - GetGLFunction (qglGenerateMipmap, "glGenerateMipmap", qtrue); - GetGLFunction (qglDrawBuffers, "glDrawBuffers", qtrue); - GetGLFunction (qglClearBufferfv, "glClearBufferfv", qtrue); - GetGLFunction (qglStencilOpSeparate, "glStencilOpSeparate", qtrue); + GetGLFunction(qglIsRenderbuffer, "glIsRenderbuffer", qtrue); + GetGLFunction(qglBindRenderbuffer, "glBindRenderbuffer", qtrue); + GetGLFunction(qglDeleteRenderbuffers, "glDeleteRenderbuffers", qtrue); + GetGLFunction(qglGenRenderbuffers, "glGenRenderbuffers", qtrue); + GetGLFunction(qglRenderbufferStorage, "glRenderbufferStorage", qtrue); + GetGLFunction(qglGetRenderbufferParameteriv, "glGetRenderbufferParameteriv", qtrue); + GetGLFunction(qglIsFramebuffer, "glIsFramebuffer", qtrue); + GetGLFunction(qglBindFramebuffer, "glBindFramebuffer", qtrue); + GetGLFunction(qglDeleteFramebuffers, "glDeleteFramebuffers", qtrue); + GetGLFunction(qglGenFramebuffers, "glGenFramebuffers", qtrue); + GetGLFunction(qglCheckFramebufferStatus, "glCheckFramebufferStatus", qtrue); + GetGLFunction(qglFramebufferTexture1D, "glFramebufferTexture1D", qtrue); + GetGLFunction(qglFramebufferTexture2D, "glFramebufferTexture2D", qtrue); + GetGLFunction(qglFramebufferTexture3D, "glFramebufferTexture3D", qtrue); + GetGLFunction(qglFramebufferTexture, "glFramebufferTexture", qtrue); + GetGLFunction(qglFramebufferTextureLayer, "glFramebufferTextureLayer", qtrue); + GetGLFunction(qglFramebufferRenderbuffer, "glFramebufferRenderbuffer", qtrue); + GetGLFunction(qglGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv", qtrue); + GetGLFunction(qglRenderbufferStorageMultisample, "glRenderbufferStorageMultisample", qtrue); + GetGLFunction(qglBlitFramebuffer, "glBlitFramebuffer", qtrue); + GetGLFunction(qglGenerateMipmap, "glGenerateMipmap", qtrue); + GetGLFunction(qglDrawBuffers, "glDrawBuffers", qtrue); + GetGLFunction(qglClearBufferfv, "glClearBufferfv", qtrue); + GetGLFunction(qglStencilOpSeparate, "glStencilOpSeparate", qtrue); // Queries - GetGLFunction (qglGenQueries, "glGenQueries", qtrue); - GetGLFunction (qglDeleteQueries, "glDeleteQueries", qtrue); - GetGLFunction (qglIsQuery, "glIsQuery", qtrue); - GetGLFunction (qglBeginQuery, "glBeginQuery", qtrue); - GetGLFunction (qglEndQuery, "glEndQuery", qtrue); - GetGLFunction (qglGetQueryiv, "glGetQueryiv", qtrue); - GetGLFunction (qglGetQueryObjectiv, "glGetQueryObjectiv", qtrue); - GetGLFunction (qglGetQueryObjectuiv, "glGetQueryObjectuiv", qtrue); + GetGLFunction(qglGenQueries, "glGenQueries", qtrue); + GetGLFunction(qglDeleteQueries, "glDeleteQueries", qtrue); + GetGLFunction(qglIsQuery, "glIsQuery", qtrue); + GetGLFunction(qglBeginQuery, "glBeginQuery", qtrue); + GetGLFunction(qglEndQuery, "glEndQuery", qtrue); + GetGLFunction(qglGetQueryiv, "glGetQueryiv", qtrue); + GetGLFunction(qglGetQueryObjectiv, "glGetQueryObjectiv", qtrue); + GetGLFunction(qglGetQueryObjectuiv, "glGetQueryObjectuiv", qtrue); // GL state - GetGLFunction (qglGetStringi, "glGetStringi", qtrue); + GetGLFunction(qglGetStringi, "glGetStringi", qtrue); // Sync objects and fences - GetGLFunction (qglFenceSync, "glFenceSync", qtrue); - GetGLFunction (qglDeleteSync, "glDeleteSync", qtrue); - GetGLFunction (qglClientWaitSync, "glClientWaitSync", qtrue); - GetGLFunction (qglWaitSync, "glWaitSync", qtrue); - + GetGLFunction(qglFenceSync, "glFenceSync", qtrue); + GetGLFunction(qglDeleteSync, "glDeleteSync", qtrue); + GetGLFunction(qglClientWaitSync, "glClientWaitSync", qtrue); + GetGLFunction(qglWaitSync, "glWaitSync", qtrue); } -void GLW_InitTextureCompression( void ); -void GLimp_InitExtensions() -{ +void GLW_InitTextureCompression(void); +void GLimp_InitExtensions() { const char *extension; - const char* result[3] = { "...ignoring %s\n", "...using %s\n", "...%s not found\n" }; + const char *result[3] = {"...ignoring %s\n", "...using %s\n", "...%s not found\n"}; - Com_Printf ("Initializing OpenGL extensions\n" ); + Com_Printf("Initializing OpenGL extensions\n"); // Select our tc scheme GLW_InitTextureCompression(); // GL_EXT_texture_filter_anisotropic glConfig.maxTextureFilterAnisotropy = 0; - if ( GLimp_HaveExtension( "EXT_texture_filter_anisotropic" ) ) - { - qglGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy ); - Com_Printf ("...GL_EXT_texture_filter_anisotropic available\n" ); - - if ( r_ext_texture_filter_anisotropic->integer > 1 ) - { - Com_Printf ("...using GL_EXT_texture_filter_anisotropic\n" ); + if (GLimp_HaveExtension("EXT_texture_filter_anisotropic")) { + qglGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy); + Com_Printf("...GL_EXT_texture_filter_anisotropic available\n"); + + if (r_ext_texture_filter_anisotropic->integer > 1) { + Com_Printf("...using GL_EXT_texture_filter_anisotropic\n"); + } else { + Com_Printf("...ignoring GL_EXT_texture_filter_anisotropic\n"); } - else - { - Com_Printf ("...ignoring GL_EXT_texture_filter_anisotropic\n" ); + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) { + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); } - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); - if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) - { - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); - } - } - else - { - Com_Printf ("...GL_EXT_texture_filter_anisotropic not found\n" ); - ri.Cvar_Set( "r_ext_texture_filter_anisotropic_avail", "0" ); + } else { + Com_Printf("...GL_EXT_texture_filter_anisotropic not found\n"); + ri.Cvar_Set("r_ext_texture_filter_anisotropic_avail", "0"); } // Memory info glRefConfig.memInfo = MI_NONE; - if( GLimp_HaveExtension( "GL_NVX_gpu_memory_info" ) ) - { + if (GLimp_HaveExtension("GL_NVX_gpu_memory_info")) { glRefConfig.memInfo = MI_NVX; - } - else if( GLimp_HaveExtension( "GL_ATI_meminfo" ) ) - { + } else if (GLimp_HaveExtension("GL_ATI_meminfo")) { glRefConfig.memInfo = MI_ATI; } @@ -574,91 +580,72 @@ void GLimp_InitExtensions() // GL_EXT_texture_compression_latc extension = "GL_EXT_texture_compression_latc"; - if (GLimp_HaveExtension(extension)) - { + if (GLimp_HaveExtension(extension)) { if (r_ext_compressed_textures->integer) glRefConfig.textureCompression |= TCR_LATC; ri.Printf(PRINT_ALL, result[r_ext_compressed_textures->integer ? 1 : 0], extension); - } - else - { + } else { ri.Printf(PRINT_ALL, result[2], extension); } // GL_ARB_texture_compression_bptc extension = "GL_ARB_texture_compression_bptc"; - if (GLimp_HaveExtension(extension)) - { + if (GLimp_HaveExtension(extension)) { if (r_ext_compressed_textures->integer >= 2) glRefConfig.textureCompression |= TCR_BPTC; ri.Printf(PRINT_ALL, result[(r_ext_compressed_textures->integer >= 2) ? 1 : 0], extension); - } - else - { + } else { ri.Printf(PRINT_ALL, result[2], extension); } // GL_ARB_texture_storage extension = "GL_ARB_texture_storage"; glRefConfig.immutableTextures = qfalse; - if( GLimp_HaveExtension( extension ) ) - { + if (GLimp_HaveExtension(extension)) { qboolean loaded = qtrue; - - loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage3D, "glTexStorage3D", qfalse)); - loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage1D, "glTexStorage1D", qfalse)); - loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage2D, "glTexStorage2D", qfalse)); + + loaded = (qboolean)(loaded && GetGLFunction(qglTexStorage3D, "glTexStorage3D", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglTexStorage1D, "glTexStorage1D", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglTexStorage2D, "glTexStorage2D", qfalse)); glRefConfig.immutableTextures = loaded; ri.Printf(PRINT_ALL, result[loaded], extension); - } - else - { + } else { ri.Printf(PRINT_ALL, result[2], extension); } // GL_ARB_buffer_storage extension = "GL_ARB_buffer_storage"; glRefConfig.immutableBuffers = qfalse; - if( GLimp_HaveExtension( extension ) ) - { + if (GLimp_HaveExtension(extension)) { qboolean loaded = qtrue; - - if ( r_arb_buffer_storage->integer ) - { - loaded = (qboolean)(loaded && GetGLFunction (qglBufferStorage, "glBufferStorage", qfalse)); - } - else - { + + if (r_arb_buffer_storage->integer) { + loaded = (qboolean)(loaded && GetGLFunction(qglBufferStorage, "glBufferStorage", qfalse)); + } else { loaded = qfalse; } glRefConfig.immutableBuffers = loaded; ri.Printf(PRINT_ALL, result[loaded], extension); - } - else - { + } else { ri.Printf(PRINT_ALL, result[2], extension); } // GL_ARB_debug_output extension = "GL_ARB_debug_output"; - if ( GLimp_HaveExtension( extension ) ) - { + if (GLimp_HaveExtension(extension)) { qboolean loaded = qtrue; - if ( r_debugContext->integer ) - { - loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageControlARB, "glDebugMessageControlARB", qfalse)); - loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageInsertARB, "glDebugMessageInsertARB", qfalse)); - loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageCallbackARB, "glDebugMessageCallbackARB", qfalse)); - loaded = (qboolean)(loaded && GetGLFunction (qglGetDebugMessageLogARB, "glGetDebugMessageLogARB", qfalse)); - } - else - { + if (r_debugContext->integer) { + loaded = (qboolean)(loaded && GetGLFunction(qglDebugMessageControlARB, "glDebugMessageControlARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglDebugMessageInsertARB, "glDebugMessageInsertARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglDebugMessageCallbackARB, "glDebugMessageCallbackARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglGetDebugMessageLogARB, "glGetDebugMessageLogARB", qfalse)); + } else { loaded = qfalse; } @@ -668,8 +655,7 @@ void GLimp_InitExtensions() // GL_ARB_timer_query extension = "GL_ARB_timer_query"; - if ( GLimp_HaveExtension( extension ) ) - { + if (GLimp_HaveExtension(extension)) { qboolean loaded = qtrue; loaded = (qboolean)(loaded && GetGLFunction(qglQueryCounter, "glQueryCounter", qfalse)); @@ -684,9 +670,8 @@ void GLimp_InitExtensions() // use float lightmaps? glRefConfig.floatLightmap = (qboolean)(r_floatLightmap->integer && r_hdr->integer); - if ( glRefConfig.debugContext ) - { - qglEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB ); + if (glRefConfig.debugContext) { + qglEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); qglDebugMessageCallbackARB(GLimp_OnError, NULL); } } diff --git a/codemp/rd-rend2/tr_extramath.cpp b/codemp/rd-rend2/tr_extramath.cpp index 76cf7c5cb5..87fe84c2f3 100644 --- a/codemp/rd-rend2/tr_extramath.cpp +++ b/codemp/rd-rend2/tr_extramath.cpp @@ -26,107 +26,155 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // Some matrix helper functions // FIXME: do these already exist in ioq3 and I don't know about them? -void Matrix16Zero( matrix_t out ) -{ - out[ 0] = 0.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = 0.0f; - out[ 1] = 0.0f; out[ 5] = 0.0f; out[ 9] = 0.0f; out[13] = 0.0f; - out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 0.0f; out[14] = 0.0f; - out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 0.0f; +void Matrix16Zero(matrix_t out) { + out[0] = 0.0f; + out[4] = 0.0f; + out[8] = 0.0f; + out[12] = 0.0f; + out[1] = 0.0f; + out[5] = 0.0f; + out[9] = 0.0f; + out[13] = 0.0f; + out[2] = 0.0f; + out[6] = 0.0f; + out[10] = 0.0f; + out[14] = 0.0f; + out[3] = 0.0f; + out[7] = 0.0f; + out[11] = 0.0f; + out[15] = 0.0f; } -void Matrix16Identity( matrix_t out ) -{ - out[ 0] = 1.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = 0.0f; - out[ 1] = 0.0f; out[ 5] = 1.0f; out[ 9] = 0.0f; out[13] = 0.0f; - out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 1.0f; out[14] = 0.0f; - out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +void Matrix16Identity(matrix_t out) { + out[0] = 1.0f; + out[4] = 0.0f; + out[8] = 0.0f; + out[12] = 0.0f; + out[1] = 0.0f; + out[5] = 1.0f; + out[9] = 0.0f; + out[13] = 0.0f; + out[2] = 0.0f; + out[6] = 0.0f; + out[10] = 1.0f; + out[14] = 0.0f; + out[3] = 0.0f; + out[7] = 0.0f; + out[11] = 0.0f; + out[15] = 1.0f; } -void Matrix16Copy( const matrix_t in, matrix_t out ) -{ - out[ 0] = in[ 0]; out[ 4] = in[ 4]; out[ 8] = in[ 8]; out[12] = in[12]; - out[ 1] = in[ 1]; out[ 5] = in[ 5]; out[ 9] = in[ 9]; out[13] = in[13]; - out[ 2] = in[ 2]; out[ 6] = in[ 6]; out[10] = in[10]; out[14] = in[14]; - out[ 3] = in[ 3]; out[ 7] = in[ 7]; out[11] = in[11]; out[15] = in[15]; +void Matrix16Copy(const matrix_t in, matrix_t out) { + out[0] = in[0]; + out[4] = in[4]; + out[8] = in[8]; + out[12] = in[12]; + out[1] = in[1]; + out[5] = in[5]; + out[9] = in[9]; + out[13] = in[13]; + out[2] = in[2]; + out[6] = in[6]; + out[10] = in[10]; + out[14] = in[14]; + out[3] = in[3]; + out[7] = in[7]; + out[11] = in[11]; + out[15] = in[15]; } -void Matrix16Multiply( const matrix_t in1, const matrix_t in2, matrix_t out ) -{ - out[ 0] = in1[ 0] * in2[ 0] + in1[ 4] * in2[ 1] + in1[ 8] * in2[ 2] + in1[12] * in2[ 3]; - out[ 1] = in1[ 1] * in2[ 0] + in1[ 5] * in2[ 1] + in1[ 9] * in2[ 2] + in1[13] * in2[ 3]; - out[ 2] = in1[ 2] * in2[ 0] + in1[ 6] * in2[ 1] + in1[10] * in2[ 2] + in1[14] * in2[ 3]; - out[ 3] = in1[ 3] * in2[ 0] + in1[ 7] * in2[ 1] + in1[11] * in2[ 2] + in1[15] * in2[ 3]; - - out[ 4] = in1[ 0] * in2[ 4] + in1[ 4] * in2[ 5] + in1[ 8] * in2[ 6] + in1[12] * in2[ 7]; - out[ 5] = in1[ 1] * in2[ 4] + in1[ 5] * in2[ 5] + in1[ 9] * in2[ 6] + in1[13] * in2[ 7]; - out[ 6] = in1[ 2] * in2[ 4] + in1[ 6] * in2[ 5] + in1[10] * in2[ 6] + in1[14] * in2[ 7]; - out[ 7] = in1[ 3] * in2[ 4] + in1[ 7] * in2[ 5] + in1[11] * in2[ 6] + in1[15] * in2[ 7]; - - out[ 8] = in1[ 0] * in2[ 8] + in1[ 4] * in2[ 9] + in1[ 8] * in2[10] + in1[12] * in2[11]; - out[ 9] = in1[ 1] * in2[ 8] + in1[ 5] * in2[ 9] + in1[ 9] * in2[10] + in1[13] * in2[11]; - out[10] = in1[ 2] * in2[ 8] + in1[ 6] * in2[ 9] + in1[10] * in2[10] + in1[14] * in2[11]; - out[11] = in1[ 3] * in2[ 8] + in1[ 7] * in2[ 9] + in1[11] * in2[10] + in1[15] * in2[11]; - - out[12] = in1[ 0] * in2[12] + in1[ 4] * in2[13] + in1[ 8] * in2[14] + in1[12] * in2[15]; - out[13] = in1[ 1] * in2[12] + in1[ 5] * in2[13] + in1[ 9] * in2[14] + in1[13] * in2[15]; - out[14] = in1[ 2] * in2[12] + in1[ 6] * in2[13] + in1[10] * in2[14] + in1[14] * in2[15]; - out[15] = in1[ 3] * in2[12] + in1[ 7] * in2[13] + in1[11] * in2[14] + in1[15] * in2[15]; +void Matrix16Multiply(const matrix_t in1, const matrix_t in2, matrix_t out) { + out[0] = in1[0] * in2[0] + in1[4] * in2[1] + in1[8] * in2[2] + in1[12] * in2[3]; + out[1] = in1[1] * in2[0] + in1[5] * in2[1] + in1[9] * in2[2] + in1[13] * in2[3]; + out[2] = in1[2] * in2[0] + in1[6] * in2[1] + in1[10] * in2[2] + in1[14] * in2[3]; + out[3] = in1[3] * in2[0] + in1[7] * in2[1] + in1[11] * in2[2] + in1[15] * in2[3]; + + out[4] = in1[0] * in2[4] + in1[4] * in2[5] + in1[8] * in2[6] + in1[12] * in2[7]; + out[5] = in1[1] * in2[4] + in1[5] * in2[5] + in1[9] * in2[6] + in1[13] * in2[7]; + out[6] = in1[2] * in2[4] + in1[6] * in2[5] + in1[10] * in2[6] + in1[14] * in2[7]; + out[7] = in1[3] * in2[4] + in1[7] * in2[5] + in1[11] * in2[6] + in1[15] * in2[7]; + + out[8] = in1[0] * in2[8] + in1[4] * in2[9] + in1[8] * in2[10] + in1[12] * in2[11]; + out[9] = in1[1] * in2[8] + in1[5] * in2[9] + in1[9] * in2[10] + in1[13] * in2[11]; + out[10] = in1[2] * in2[8] + in1[6] * in2[9] + in1[10] * in2[10] + in1[14] * in2[11]; + out[11] = in1[3] * in2[8] + in1[7] * in2[9] + in1[11] * in2[10] + in1[15] * in2[11]; + + out[12] = in1[0] * in2[12] + in1[4] * in2[13] + in1[8] * in2[14] + in1[12] * in2[15]; + out[13] = in1[1] * in2[12] + in1[5] * in2[13] + in1[9] * in2[14] + in1[13] * in2[15]; + out[14] = in1[2] * in2[12] + in1[6] * in2[13] + in1[10] * in2[14] + in1[14] * in2[15]; + out[15] = in1[3] * in2[12] + in1[7] * in2[13] + in1[11] * in2[14] + in1[15] * in2[15]; } -void Matrix16Transform( const matrix_t in1, const vec4_t in2, vec4_t out ) -{ - out[ 0] = in1[ 0] * in2[ 0] + in1[ 4] * in2[ 1] + in1[ 8] * in2[ 2] + in1[12] * in2[ 3]; - out[ 1] = in1[ 1] * in2[ 0] + in1[ 5] * in2[ 1] + in1[ 9] * in2[ 2] + in1[13] * in2[ 3]; - out[ 2] = in1[ 2] * in2[ 0] + in1[ 6] * in2[ 1] + in1[10] * in2[ 2] + in1[14] * in2[ 3]; - out[ 3] = in1[ 3] * in2[ 0] + in1[ 7] * in2[ 1] + in1[11] * in2[ 2] + in1[15] * in2[ 3]; +void Matrix16Transform(const matrix_t in1, const vec4_t in2, vec4_t out) { + out[0] = in1[0] * in2[0] + in1[4] * in2[1] + in1[8] * in2[2] + in1[12] * in2[3]; + out[1] = in1[1] * in2[0] + in1[5] * in2[1] + in1[9] * in2[2] + in1[13] * in2[3]; + out[2] = in1[2] * in2[0] + in1[6] * in2[1] + in1[10] * in2[2] + in1[14] * in2[3]; + out[3] = in1[3] * in2[0] + in1[7] * in2[1] + in1[11] * in2[2] + in1[15] * in2[3]; } -qboolean Matrix16Compare( const matrix_t a, const matrix_t b ) -{ - return (qboolean)(!(a[ 0] != b[ 0] || a[ 4] != b[ 4] || a[ 8] != b[ 8] || a[12] != b[12] || - a[ 1] != b[ 1] || a[ 5] != b[ 5] || a[ 9] != b[ 9] || a[13] != b[13] || - a[ 2] != b[ 2] || a[ 6] != b[ 6] || a[10] != b[10] || a[14] != b[14] || - a[ 3] != b[ 3] || a[ 7] != b[ 7] || a[11] != b[11] || a[15] != b[15])); +qboolean Matrix16Compare(const matrix_t a, const matrix_t b) { + return (qboolean)(!(a[0] != b[0] || a[4] != b[4] || a[8] != b[8] || a[12] != b[12] || a[1] != b[1] || a[5] != b[5] || a[9] != b[9] || a[13] != b[13] || + a[2] != b[2] || a[6] != b[6] || a[10] != b[10] || a[14] != b[14] || a[3] != b[3] || a[7] != b[7] || a[11] != b[11] || a[15] != b[15])); } -void Matrix16Dump( const matrix_t in ) -{ - ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 0], in[ 4], in[ 8], in[12]); - ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 1], in[ 5], in[ 9], in[13]); - ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 2], in[ 6], in[10], in[14]); - ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 3], in[ 7], in[11], in[15]); +void Matrix16Dump(const matrix_t in) { + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[0], in[4], in[8], in[12]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[1], in[5], in[9], in[13]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[2], in[6], in[10], in[14]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[3], in[7], in[11], in[15]); } -void Matrix16Translation(const vec3_t vec, matrix_t out ) -{ - out[ 0] = 1.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = vec[0]; - out[ 1] = 0.0f; out[ 5] = 1.0f; out[ 9] = 0.0f; out[13] = vec[1]; - out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 1.0f; out[14] = vec[2]; - out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +void Matrix16Translation(const vec3_t vec, matrix_t out) { + out[0] = 1.0f; + out[4] = 0.0f; + out[8] = 0.0f; + out[12] = vec[0]; + out[1] = 0.0f; + out[5] = 1.0f; + out[9] = 0.0f; + out[13] = vec[1]; + out[2] = 0.0f; + out[6] = 0.0f; + out[10] = 1.0f; + out[14] = vec[2]; + out[3] = 0.0f; + out[7] = 0.0f; + out[11] = 0.0f; + out[15] = 1.0f; } -void Matrix16Ortho( float left, float right, float bottom, float top, float znear, float zfar, matrix_t out ) -{ - out[ 0] = 2.0f / (right - left); out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = -(right + left) / (right - left); - out[ 1] = 0.0f; out[ 5] = 2.0f / (top - bottom); out[ 9] = 0.0f; out[13] = -(top + bottom) / (top - bottom); - out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 2.0f / (zfar - znear); out[14] = -(zfar + znear) / (zfar - znear); - out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +void Matrix16Ortho(float left, float right, float bottom, float top, float znear, float zfar, matrix_t out) { + out[0] = 2.0f / (right - left); + out[4] = 0.0f; + out[8] = 0.0f; + out[12] = -(right + left) / (right - left); + out[1] = 0.0f; + out[5] = 2.0f / (top - bottom); + out[9] = 0.0f; + out[13] = -(top + bottom) / (top - bottom); + out[2] = 0.0f; + out[6] = 0.0f; + out[10] = 2.0f / (zfar - znear); + out[14] = -(zfar + znear) / (zfar - znear); + out[3] = 0.0f; + out[7] = 0.0f; + out[11] = 0.0f; + out[15] = 1.0f; } -void Matrix16View(vec3_t axes[3], vec3_t origin, matrix_t out) -{ - out[0] = axes[0][0]; - out[1] = axes[1][0]; - out[2] = axes[2][0]; - out[3] = 0; +void Matrix16View(vec3_t axes[3], vec3_t origin, matrix_t out) { + out[0] = axes[0][0]; + out[1] = axes[1][0]; + out[2] = axes[2][0]; + out[3] = 0; - out[4] = axes[0][1]; - out[5] = axes[1][1]; - out[6] = axes[2][1]; - out[7] = 0; + out[4] = axes[0][1]; + out[5] = axes[1][1]; + out[6] = axes[2][1]; + out[7] = 0; - out[8] = axes[0][2]; - out[9] = axes[1][2]; + out[8] = axes[0][2]; + out[9] = axes[1][2]; out[10] = axes[2][2]; out[11] = 0; @@ -136,50 +184,60 @@ void Matrix16View(vec3_t axes[3], vec3_t origin, matrix_t out) out[15] = 1; } -void Matrix16SimpleInverse( const matrix_t in, matrix_t out) -{ +void Matrix16SimpleInverse(const matrix_t in, matrix_t out) { vec3_t v; float invSqrLen; - + VectorCopy(in + 0, v); - invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - out[ 0] = v[0]; out[ 4] = v[1]; out[ 8] = v[2]; out[12] = -DotProduct(v, &in[12]); + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + out[0] = v[0]; + out[4] = v[1]; + out[8] = v[2]; + out[12] = -DotProduct(v, &in[12]); VectorCopy(in + 4, v); - invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - out[ 1] = v[0]; out[ 5] = v[1]; out[ 9] = v[2]; out[13] = -DotProduct(v, &in[12]); + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + out[1] = v[0]; + out[5] = v[1]; + out[9] = v[2]; + out[13] = -DotProduct(v, &in[12]); VectorCopy(in + 8, v); - invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - out[ 2] = v[0]; out[ 6] = v[1]; out[10] = v[2]; out[14] = -DotProduct(v, &in[12]); - - out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + out[2] = v[0]; + out[6] = v[1]; + out[10] = v[2]; + out[14] = -DotProduct(v, &in[12]); + + out[3] = 0.0f; + out[7] = 0.0f; + out[11] = 0.0f; + out[15] = 1.0f; } -void VectorLerp( vec3_t a, vec3_t b, float lerp, vec3_t c) -{ +void VectorLerp(vec3_t a, vec3_t b, float lerp, vec3_t c) { c[0] = a[0] * (1.0f - lerp) + b[0] * lerp; c[1] = a[1] * (1.0f - lerp) + b[1] * lerp; c[2] = a[2] * (1.0f - lerp) + b[2] * lerp; } -qboolean SpheresIntersect(vec3_t origin1, float radius1, vec3_t origin2, float radius2) -{ +qboolean SpheresIntersect(vec3_t origin1, float radius1, vec3_t origin2, float radius2) { float radiusSum = radius1 + radius2; vec3_t diff; - + VectorSubtract(origin1, origin2, diff); - if (DotProduct(diff, diff) <= radiusSum * radiusSum) - { + if (DotProduct(diff, diff) <= radiusSum * radiusSum) { return qtrue; } return qfalse; } -void BoundingSphereOfSpheres(vec3_t origin1, float radius1, vec3_t origin2, float radius2, vec3_t origin3, float *radius3) -{ +void BoundingSphereOfSpheres(vec3_t origin1, float radius1, vec3_t origin2, float radius2, vec3_t origin3, float *radius3) { vec3_t diff; VectorScale(origin1, 0.5f, origin3); @@ -189,8 +247,7 @@ void BoundingSphereOfSpheres(vec3_t origin1, float radius1, vec3_t origin2, floa *radius3 = VectorLength(diff) * 0.5f + MAX(radius1, radius2); } -int NextPowerOfTwo(int in) -{ +int NextPowerOfTwo(int in) { int out; for (out = 1; out < in; out <<= 1) @@ -199,12 +256,10 @@ int NextPowerOfTwo(int in) return out; } -unsigned short FloatToHalf(float in) -{ +unsigned short FloatToHalf(float in) { unsigned short out; - - union - { + + union { float f; unsigned int i; } f32; @@ -214,24 +269,20 @@ unsigned short FloatToHalf(float in) f32.f = in; - sign = (f32.i & 0x80000000) >> 31; + sign = (f32.i & 0x80000000) >> 31; inExponent = (f32.i & 0x7F800000) >> 23; - inFraction = f32.i & 0x007FFFFF; + inFraction = f32.i & 0x007FFFFF; outExponent = CLAMP(inExponent - 127, -15, 16) + 15; outFraction = 0; - if (outExponent == 0x1F) - { + if (outExponent == 0x1F) { if (inExponent == 0xFF && inFraction != 0) outFraction = 0x3FF; - } - else if (outExponent == 0x00) - { + } else if (outExponent == 0x00) { if (inExponent == 0x00 && inFraction != 0) outFraction = 0x3FF; - } - else + } else outFraction = inFraction >> 13; out = (sign << 15) | (outExponent << 10) | outFraction; @@ -239,8 +290,7 @@ unsigned short FloatToHalf(float in) return out; } -uint32_t ReverseBits(uint32_t v) -{ +uint32_t ReverseBits(uint32_t v) { v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1); v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2); v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); @@ -249,8 +299,7 @@ uint32_t ReverseBits(uint32_t v) return v; } -float GSmithCorrelated(float roughness, float NdotV, float NdotL) -{ +float GSmithCorrelated(float roughness, float NdotV, float NdotL) { const float m = roughness * roughness; const float m2 = m * m; const float visV = NdotL * sqrtf(NdotV * (NdotV - NdotV * m2) + m2); @@ -259,8 +308,7 @@ float GSmithCorrelated(float roughness, float NdotV, float NdotL) return 0.5f / (visV + visL); } -float V_Neubelt(float NdotV, float NdotL) -{ +float V_Neubelt(float NdotV, float NdotL) { // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" return 1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV)); } diff --git a/codemp/rd-rend2/tr_fbo.cpp b/codemp/rd-rend2/tr_fbo.cpp index 9a7e4f97a6..06bf3b5bd4 100644 --- a/codemp/rd-rend2/tr_fbo.cpp +++ b/codemp/rd-rend2/tr_fbo.cpp @@ -28,10 +28,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA R_CheckFBO ============= */ -qboolean R_CheckFBO(const FBO_t * fbo) -{ - int code; - int id; +qboolean R_CheckFBO(const FBO_t *fbo) { + int code; + int id; qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &id); qglBindFramebuffer(GL_FRAMEBUFFER, fbo->frameBuffer); @@ -40,55 +39,52 @@ qboolean R_CheckFBO(const FBO_t * fbo) qglBindFramebuffer(GL_FRAMEBUFFER, id); - if(code == GL_FRAMEBUFFER_COMPLETE) - { + if (code == GL_FRAMEBUFFER_COMPLETE) { return qtrue; } // an error occured - switch (code) - { - case GL_FRAMEBUFFER_COMPLETE: - break; + switch (code) { + case GL_FRAMEBUFFER_COMPLETE: + break; - case GL_FRAMEBUFFER_UNSUPPORTED: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Unsupported framebuffer format\n", fbo->name); - break; + case GL_FRAMEBUFFER_UNSUPPORTED: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Unsupported framebuffer format\n", fbo->name); + break; - case GL_FRAMEBUFFER_UNDEFINED: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Default framebuffer was checked, but does not exist\n", fbo->name); - break; + case GL_FRAMEBUFFER_UNDEFINED: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Default framebuffer was checked, but does not exist\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete attachment\n", fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete attachment\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, no attachments attached\n", fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, no attachments attached\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched multisampling values\n", fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched multisampling values\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched layer targets\n", - fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched layer targets\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing draw buffer\n", fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing draw buffer\n", fbo->name); + break; - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing read buffer\n", fbo->name); - break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing read buffer\n", fbo->name); + break; - default: - ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) unknown error 0x%X\n", fbo->name, code); - //ri.Error(ERR_FATAL, "R_CheckFBO: (%s) unknown error 0x%X", fbo->name, code); - //assert(0); - break; + default: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) unknown error 0x%X\n", fbo->name, code); + // ri.Error(ERR_FATAL, "R_CheckFBO: (%s) unknown error 0x%X", fbo->name, code); + // assert(0); + break; } return qfalse; @@ -99,27 +95,22 @@ qboolean R_CheckFBO(const FBO_t * fbo) FBO_Create ============ */ -FBO_t *FBO_Create(const char *name, int width, int height) -{ - FBO_t *fbo; +FBO_t *FBO_Create(const char *name, int width, int height) { + FBO_t *fbo; - if(strlen(name) >= MAX_QPATH) - { + if (strlen(name) >= MAX_QPATH) { ri.Error(ERR_DROP, "FBO_Create: \"%s\" is too long", name); } - if(width <= 0 || width > glRefConfig.maxRenderbufferSize) - { + if (width <= 0 || width > glRefConfig.maxRenderbufferSize) { ri.Error(ERR_DROP, "FBO_Create: bad width %i", width); } - if(height <= 0 || height > glRefConfig.maxRenderbufferSize) - { + if (height <= 0 || height > glRefConfig.maxRenderbufferSize) { ri.Error(ERR_DROP, "FBO_Create: bad height %i", height); } - if(tr.numFBOs == MAX_FBOS) - { + if (tr.numFBOs == MAX_FBOS) { ri.Error(ERR_DROP, "FBO_Create: MAX_FBOS hit"); } @@ -134,56 +125,54 @@ FBO_t *FBO_Create(const char *name, int width, int height) return fbo; } -void FBO_CreateBuffer(FBO_t *fbo, int format, int index, int multisample) -{ +void FBO_CreateBuffer(FBO_t *fbo, int format, int index, int multisample) { uint32_t *pRenderBuffer; GLenum attachment; qboolean absent; - switch(format) - { - case GL_RGB: - case GL_RGBA: - case GL_RGB8: - case GL_RGBA8: - case GL_RGB16F: - case GL_RGBA16F: - case GL_RGB32F: - case GL_RGBA32F: - fbo->colorFormat = format; - pRenderBuffer = &fbo->colorBuffers[index]; - attachment = GL_COLOR_ATTACHMENT0 + index; - break; - - case GL_DEPTH_COMPONENT: - case GL_DEPTH_COMPONENT16: - case GL_DEPTH_COMPONENT24: - case GL_DEPTH_COMPONENT32: - fbo->depthFormat = format; - pRenderBuffer = &fbo->depthBuffer; - attachment = GL_DEPTH_ATTACHMENT; - break; - - case GL_STENCIL_INDEX: - case GL_STENCIL_INDEX1: - case GL_STENCIL_INDEX4: - case GL_STENCIL_INDEX8: - case GL_STENCIL_INDEX16: - fbo->stencilFormat = format; - pRenderBuffer = &fbo->stencilBuffer; - attachment = GL_STENCIL_ATTACHMENT; - break; - - case GL_DEPTH_STENCIL: - case GL_DEPTH24_STENCIL8: - fbo->packedDepthStencilFormat = format; - pRenderBuffer = &fbo->packedDepthStencilBuffer; - attachment = 0; // special for stencil and depth - break; - - default: - ri.Printf(PRINT_WARNING, "FBO_CreateBuffer: invalid format %d\n", format); - return; + switch (format) { + case GL_RGB: + case GL_RGBA: + case GL_RGB8: + case GL_RGBA8: + case GL_RGB16F: + case GL_RGBA16F: + case GL_RGB32F: + case GL_RGBA32F: + fbo->colorFormat = format; + pRenderBuffer = &fbo->colorBuffers[index]; + attachment = GL_COLOR_ATTACHMENT0 + index; + break; + + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + fbo->depthFormat = format; + pRenderBuffer = &fbo->depthBuffer; + attachment = GL_DEPTH_ATTACHMENT; + break; + + case GL_STENCIL_INDEX: + case GL_STENCIL_INDEX1: + case GL_STENCIL_INDEX4: + case GL_STENCIL_INDEX8: + case GL_STENCIL_INDEX16: + fbo->stencilFormat = format; + pRenderBuffer = &fbo->stencilBuffer; + attachment = GL_STENCIL_ATTACHMENT; + break; + + case GL_DEPTH_STENCIL: + case GL_DEPTH24_STENCIL8: + fbo->packedDepthStencilFormat = format; + pRenderBuffer = &fbo->packedDepthStencilBuffer; + attachment = 0; // special for stencil and depth + break; + + default: + ri.Printf(PRINT_WARNING, "FBO_CreateBuffer: invalid format %d\n", format); + return; } absent = (qboolean)(*pRenderBuffer == 0); @@ -191,37 +180,28 @@ void FBO_CreateBuffer(FBO_t *fbo, int format, int index, int multisample) qglGenRenderbuffers(1, pRenderBuffer); qglBindRenderbuffer(GL_RENDERBUFFER, *pRenderBuffer); - if (multisample) - { + if (multisample) { qglRenderbufferStorageMultisample(GL_RENDERBUFFER, multisample, format, fbo->width, fbo->height); - } - else - { + } else { qglRenderbufferStorage(GL_RENDERBUFFER, format, fbo->width, fbo->height); } - if(absent) - { - if (attachment == 0) - { - qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, *pRenderBuffer); + if (absent) { + if (attachment == 0) { + qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, *pRenderBuffer); qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, *pRenderBuffer); - } - else + } else qglFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, *pRenderBuffer); } } - /* ================= R_AttachFBOTexture1D ================= */ -void R_AttachFBOTexture1D(int texId, int index) -{ - if(index < 0 || index >= glRefConfig.maxColorAttachments) - { +void R_AttachFBOTexture1D(int texId, int index) { + if (index < 0 || index >= glRefConfig.maxColorAttachments) { ri.Printf(PRINT_WARNING, "R_AttachFBOTexture1D: invalid attachment index %i\n", index); return; } @@ -234,18 +214,13 @@ void R_AttachFBOTexture1D(int texId, int index) R_AttachFBOTexture2D ================= */ -void R_AttachFBOTexture2D(int target, int texId, int index) -{ - if (target != GL_TEXTURE_2D && - (target < GL_TEXTURE_CUBE_MAP_POSITIVE_X || - target > GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)) - { +void R_AttachFBOTexture2D(int target, int texId, int index) { + if (target != GL_TEXTURE_2D && (target < GL_TEXTURE_CUBE_MAP_POSITIVE_X || target > GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)) { ri.Printf(PRINT_WARNING, "R_AttachFBOTexture2D: invalid target %i\n", target); return; } - if (index < 0 || index >= glRefConfig.maxColorAttachments) - { + if (index < 0 || index >= glRefConfig.maxColorAttachments) { ri.Printf(PRINT_WARNING, "R_AttachFBOTexture2D: invalid attachment index %i\n", index); return; } @@ -258,10 +233,8 @@ void R_AttachFBOTexture2D(int target, int texId, int index) R_AttachFBOTexture3D ================= */ -void R_AttachFBOTexture3D(int texId, int index, int zOffset) -{ - if(index < 0 || index >= glRefConfig.maxColorAttachments) - { +void R_AttachFBOTexture3D(int texId, int index, int zOffset) { + if (index < 0 || index >= glRefConfig.maxColorAttachments) { ri.Printf(PRINT_WARNING, "R_AttachFBOTexture3D: invalid attachment index %i\n", index); return; } @@ -274,25 +247,17 @@ void R_AttachFBOTexture3D(int texId, int index, int zOffset) R_AttachFBOTextureDepth ================= */ -void R_AttachFBOTextureDepth(int texId) -{ - qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, 0); -} +void R_AttachFBOTextureDepth(int texId) { qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, 0); } /* ================= R_AttachFBOTexturePackedDepthStencil ================= */ -void R_AttachFBOTexturePackedDepthStencil(int texId) -{ - qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, 0); -} +void R_AttachFBOTexturePackedDepthStencil(int texId) { qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, 0); } -void FBO_AttachTextureImage(image_t *img, int index) -{ - if (!glState.currentFBO) - { +void FBO_AttachTextureImage(image_t *img, int index) { + if (!glState.currentFBO) { ri.Printf(PRINT_WARNING, "FBO: attempted to attach a texture image with no FBO bound!\n"); return; } @@ -303,10 +268,8 @@ void FBO_AttachTextureImage(image_t *img, int index) glState.currentFBO->colorBuffers[index] = img->texnum; } -static void FBO_SetupDrawBuffers() -{ - if (!glState.currentFBO) - { +static void FBO_SetupDrawBuffers() { + if (!glState.currentFBO) { ri.Printf(PRINT_WARNING, "FBO: attempted to attach a texture image with no FBO bound!\n"); return; } @@ -315,23 +278,18 @@ static void FBO_SetupDrawBuffers() int numBuffers = 0; GLenum bufs[8]; - while ( currentFBO->colorBuffers[numBuffers] != 0 ) - { + while (currentFBO->colorBuffers[numBuffers] != 0) { numBuffers++; } - if ( numBuffers == 0 ) - { - qglDrawBuffer (GL_NONE); - } - else - { - for ( int i = 0; i < numBuffers; i++ ) - { + if (numBuffers == 0) { + qglDrawBuffer(GL_NONE); + } else { + for (int i = 0; i < numBuffers; i++) { bufs[i] = GL_COLOR_ATTACHMENT0 + i; } - qglDrawBuffers (numBuffers, bufs); + qglDrawBuffers(numBuffers, bufs); } } @@ -340,13 +298,11 @@ static void FBO_SetupDrawBuffers() FBO_Bind ============ */ -void FBO_Bind(FBO_t * fbo) -{ +void FBO_Bind(FBO_t *fbo) { if (glState.currentFBO == fbo) return; - - if (r_logFile->integer) - { + + if (r_logFile->integer) { // don't just call LogComment, or we will get a call to va() every frame! if (fbo) GLimp_LogComment(va("--- FBO_Bind( %s ) ---\n", fbo->name)); @@ -354,13 +310,10 @@ void FBO_Bind(FBO_t * fbo) GLimp_LogComment("--- FBO_Bind ( NULL ) ---\n"); } - if (!fbo) - { + if (!fbo) { qglBindFramebuffer(GL_FRAMEBUFFER, 0); glState.currentFBO = NULL; - } - else - { + } else { qglBindFramebuffer(GL_FRAMEBUFFER, fbo->frameBuffer); glState.currentFBO = fbo; } @@ -371,10 +324,9 @@ void FBO_Bind(FBO_t * fbo) FBO_Init ============ */ -void FBO_Init(void) -{ - int i; - int hdrFormat, multisample; +void FBO_Init(void) { + int i; + int hdrFormat, multisample; ri.Printf(PRINT_ALL, "------- FBO_Init -------\n"); @@ -384,45 +336,39 @@ void FBO_Init(void) R_IssuePendingRenderCommands(); -/* if(glRefConfig.textureNonPowerOfTwo) - { - width = glConfig.vidWidth; - height = glConfig.vidHeight; - } - else - { - width = NextPowerOfTwo(glConfig.vidWidth); - height = NextPowerOfTwo(glConfig.vidHeight); - } */ + /* if(glRefConfig.textureNonPowerOfTwo) + { + width = glConfig.vidWidth; + height = glConfig.vidHeight; + } + else + { + width = NextPowerOfTwo(glConfig.vidWidth); + height = NextPowerOfTwo(glConfig.vidHeight); + } */ hdrFormat = GL_RGBA8; - if (r_hdr->integer) - { + if (r_hdr->integer) { hdrFormat = GL_RGBA16F; } qglGetIntegerv(GL_MAX_SAMPLES, &multisample); - if (r_ext_framebuffer_multisample->integer < multisample) - { + if (r_ext_framebuffer_multisample->integer < multisample) { multisample = r_ext_framebuffer_multisample->integer; } if (multisample < 2) multisample = 0; - if (multisample != r_ext_framebuffer_multisample->integer) - { + if (multisample != r_ext_framebuffer_multisample->integer) { ri.Cvar_SetValue("r_ext_framebuffer_multisample", (float)multisample); } - + // only create a render FBO if we need to resolve MSAA or do HDR // otherwise just render straight to the screen (tr.renderFbo = NULL) - if (multisample) - { - tr.renderFbo = FBO_Create( - "_render", tr.renderDepthImage->width, - tr.renderDepthImage->height); + if (multisample) { + tr.renderFbo = FBO_Create("_render", tr.renderDepthImage->width, tr.renderDepthImage->height); FBO_Bind(tr.renderFbo); FBO_CreateBuffer(tr.renderFbo, hdrFormat, 0, multisample); @@ -432,9 +378,7 @@ void FBO_Init(void) R_CheckFBO(tr.renderFbo); - tr.msaaResolveFbo = FBO_Create( - "_msaaResolve", tr.renderDepthImage->width, - tr.renderDepthImage->height); + tr.msaaResolveFbo = FBO_Create("_msaaResolve", tr.renderDepthImage->width, tr.renderDepthImage->height); FBO_Bind(tr.msaaResolveFbo); FBO_AttachTextureImage(tr.renderImage, 0); @@ -443,12 +387,8 @@ void FBO_Init(void) FBO_SetupDrawBuffers(); R_CheckFBO(tr.msaaResolveFbo); - } - else - { - tr.renderFbo = FBO_Create( - "_render", tr.renderDepthImage->width, - tr.renderDepthImage->height); + } else { + tr.renderFbo = FBO_Create("_render", tr.renderDepthImage->width, tr.renderDepthImage->height); FBO_Bind(tr.renderFbo); FBO_AttachTextureImage(tr.renderImage, 0); @@ -462,30 +402,24 @@ void FBO_Init(void) // clear render buffer // this fixes the corrupt screen bug with r_hdr 1 on older hardware FBO_Bind(tr.renderFbo); - qglClearColor( 0.f, 0.f, 0.f, 1 ); - qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + qglClearColor(0.f, 0.f, 0.f, 1); + qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glow buffers { - for ( int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++ ) - { - tr.glowFboScaled[i] = FBO_Create( - va("*glowScaled%d", i), tr.glowImageScaled[i]->width, - tr.glowImageScaled[i]->height); + for (int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++) { + tr.glowFboScaled[i] = FBO_Create(va("*glowScaled%d", i), tr.glowImageScaled[i]->width, tr.glowImageScaled[i]->height); - FBO_Bind (tr.glowFboScaled[i]); - FBO_AttachTextureImage (tr.glowImageScaled[i], 0); + FBO_Bind(tr.glowFboScaled[i]); + FBO_AttachTextureImage(tr.glowImageScaled[i], 0); FBO_SetupDrawBuffers(); - R_CheckFBO (tr.glowFboScaled[i]); + R_CheckFBO(tr.glowFboScaled[i]); } } - if (r_drawSunRays->integer) - { - tr.sunRaysFbo = FBO_Create( - "_sunRays", tr.renderDepthImage->width, - tr.renderDepthImage->height); + if (r_drawSunRays->integer) { + tr.sunRaysFbo = FBO_Create("_sunRays", tr.renderDepthImage->width, tr.renderDepthImage->height); FBO_Bind(tr.sunRaysFbo); FBO_AttachTextureImage(tr.sunRaysImage, 0); @@ -496,13 +430,9 @@ void FBO_Init(void) } #if MAX_DRAWN_PSHADOWS > 0 - if (tr.pshadowArrayImage != NULL) - { - for( i = 0; i < MAX_DRAWN_PSHADOWS; i++) - { - tr.pshadowFbos[i] = FBO_Create( - va("_shadowmap%i", i), tr.pshadowArrayImage->width, - tr.pshadowArrayImage->height); + if (tr.pshadowArrayImage != NULL) { + for (i = 0; i < MAX_DRAWN_PSHADOWS; i++) { + tr.pshadowFbos[i] = FBO_Create(va("_shadowmap%i", i), tr.pshadowArrayImage->width, tr.pshadowArrayImage->height); FBO_Bind(tr.pshadowFbos[i]); qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.pshadowArrayImage->texnum, 0, i); @@ -510,14 +440,11 @@ void FBO_Init(void) qglReadBuffer(GL_NONE); R_CheckFBO(tr.pshadowFbos[i]); } - } #endif - if (r_dlightMode->integer >= 2) - { - for (i = 0; i < MAX_DLIGHTS * 6; i++) - { + if (r_dlightMode->integer >= 2) { + for (i = 0; i < MAX_DLIGHTS * 6; i++) { tr.shadowCubeFbo[i] = FBO_Create(va("_shadowCubeFbo_%i", i), PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE); FBO_Bind(tr.shadowCubeFbo[i]); qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.pointShadowArrayImage->texnum, 0, i); @@ -527,14 +454,9 @@ void FBO_Init(void) } } - if (tr.sunShadowArrayImage != NULL) - { - for ( i = 0; i < 3; i++) - { - tr.sunShadowFbo[i] = FBO_Create( - va("_sunshadowmap%i", i), - tr.sunShadowArrayImage->width, - tr.sunShadowArrayImage->height); + if (tr.sunShadowArrayImage != NULL) { + for (i = 0; i < 3; i++) { + tr.sunShadowFbo[i] = FBO_Create(va("_sunshadowmap%i", i), tr.sunShadowArrayImage->width, tr.sunShadowArrayImage->height); FBO_Bind(tr.sunShadowFbo[i]); qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.sunShadowArrayImage->texnum, 0, i); @@ -544,9 +466,7 @@ void FBO_Init(void) R_CheckFBO(tr.sunShadowFbo[i]); } - tr.screenShadowFbo = FBO_Create( - "_screenshadow", tr.screenShadowImage->width, - tr.screenShadowImage->height); + tr.screenShadowFbo = FBO_Create("_screenshadow", tr.screenShadowImage->width, tr.screenShadowImage->height); FBO_Bind(tr.screenShadowFbo); FBO_AttachTextureImage(tr.screenShadowImage, 0); @@ -555,11 +475,8 @@ void FBO_Init(void) R_CheckFBO(tr.screenShadowFbo); } - for (i = 0; i < 2; i++) - { - tr.textureScratchFbo[i] = FBO_Create( - va("_texturescratch%d", i), tr.textureScratchImage[i]->width, - tr.textureScratchImage[i]->height); + for (i = 0; i < 2; i++) { + tr.textureScratchFbo[i] = FBO_Create(va("_texturescratch%d", i), tr.textureScratchImage[i]->width, tr.textureScratchImage[i]->height); FBO_Bind(tr.textureScratchFbo[i]); FBO_AttachTextureImage(tr.textureScratchImage[i], 0); @@ -569,9 +486,7 @@ void FBO_Init(void) } { - tr.calcLevelsFbo = FBO_Create( - "_calclevels", tr.calcLevelsImage->width, - tr.calcLevelsImage->height); + tr.calcLevelsFbo = FBO_Create("_calclevels", tr.calcLevelsImage->width, tr.calcLevelsImage->height); FBO_Bind(tr.calcLevelsFbo); FBO_AttachTextureImage(tr.calcLevelsImage, 0); @@ -581,9 +496,7 @@ void FBO_Init(void) } { - tr.targetLevelsFbo = FBO_Create( - "_targetlevels", tr.targetLevelsImage->width, - tr.targetLevelsImage->height); + tr.targetLevelsFbo = FBO_Create("_targetlevels", tr.targetLevelsImage->width, tr.targetLevelsImage->height); FBO_Bind(tr.targetLevelsFbo); FBO_AttachTextureImage(tr.targetLevelsImage, 0); @@ -592,11 +505,8 @@ void FBO_Init(void) R_CheckFBO(tr.targetLevelsFbo); } - for (i = 0; i < 2; i++) - { - tr.quarterFbo[i] = FBO_Create( - va("_quarter%d", i), tr.quarterImage[i]->width, - tr.quarterImage[i]->height); + for (i = 0; i < 2; i++) { + tr.quarterFbo[i] = FBO_Create(va("_quarter%d", i), tr.quarterImage[i]->width, tr.quarterImage[i]->height); FBO_Bind(tr.quarterFbo[i]); FBO_AttachTextureImage(tr.quarterImage[i], 0); @@ -605,10 +515,8 @@ void FBO_Init(void) R_CheckFBO(tr.quarterFbo[i]); } - if (r_ssao->integer) - { - tr.hdrDepthFbo = FBO_Create( - "_hdrDepth", tr.hdrDepthImage->width, tr.hdrDepthImage->height); + if (r_ssao->integer) { + tr.hdrDepthFbo = FBO_Create("_hdrDepth", tr.hdrDepthImage->width, tr.hdrDepthImage->height); FBO_Bind(tr.hdrDepthFbo); FBO_AttachTextureImage(tr.hdrDepthImage, 0); @@ -616,9 +524,7 @@ void FBO_Init(void) R_CheckFBO(tr.hdrDepthFbo); - tr.screenSsaoFbo = FBO_Create( - "_screenssao", tr.screenSsaoImage->width, - tr.screenSsaoImage->height); + tr.screenSsaoFbo = FBO_Create("_screenssao", tr.screenSsaoImage->width, tr.screenSsaoImage->height); FBO_Bind(tr.screenSsaoFbo); FBO_AttachTextureImage(tr.screenSsaoImage, 0); @@ -627,13 +533,9 @@ void FBO_Init(void) R_CheckFBO(tr.screenSsaoFbo); } - if (tr.renderCubeImage != NULL) - { - for (i = 0; i < 6; i++) - { - tr.renderCubeFbo[i] = FBO_Create( - "_renderCubeFbo", tr.renderCubeImage->width, - tr.renderCubeImage->height); + if (tr.renderCubeImage != NULL) { + for (i = 0; i < 6; i++) { + tr.renderCubeFbo[i] = FBO_Create("_renderCubeFbo", tr.renderCubeImage->width, tr.renderCubeImage->height); FBO_Bind(tr.renderCubeFbo[i]); R_AttachFBOTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, tr.renderCubeImage->texnum, 0); glState.currentFBO->colorImage[0] = tr.renderCubeImage; @@ -644,9 +546,7 @@ void FBO_Init(void) R_CheckFBO(tr.renderCubeFbo[i]); } - tr.filterCubeFbo = FBO_Create( - "_filterCubeFbo", tr.renderCubeImage->width, - tr.renderCubeImage->height); + tr.filterCubeFbo = FBO_Create("_filterCubeFbo", tr.renderCubeImage->width, tr.renderCubeImage->height); FBO_Bind(tr.filterCubeFbo); qglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tr.renderCubeImage->texnum, 0); glState.currentFBO->colorImage[0] = tr.renderCubeImage; @@ -655,12 +555,8 @@ void FBO_Init(void) R_CheckFBO(tr.filterCubeFbo); } - if (tr.weatherDepthImage != nullptr) - { - tr.weatherDepthFbo = FBO_Create( - "_weatherDepthFbo", - tr.weatherDepthImage->width, - tr.weatherDepthImage->height); + if (tr.weatherDepthImage != nullptr) { + tr.weatherDepthFbo = FBO_Create("_weatherDepthFbo", tr.weatherDepthImage->width, tr.weatherDepthImage->height); FBO_Bind(tr.weatherDepthFbo); R_AttachFBOTextureDepth(tr.weatherDepthImage->texnum); @@ -679,32 +575,29 @@ void FBO_Init(void) FBO_Shutdown ============ */ -void FBO_Shutdown(void) -{ - int i, j; - FBO_t *fbo; +void FBO_Shutdown(void) { + int i, j; + FBO_t *fbo; ri.Printf(PRINT_ALL, "------- FBO_Shutdown -------\n"); FBO_Bind(NULL); - for(i = 0; i < tr.numFBOs; i++) - { + for (i = 0; i < tr.numFBOs; i++) { fbo = tr.fbos[i]; - for(j = 0; j < glRefConfig.maxColorAttachments; j++) - { - if(fbo->colorBuffers[j]) + for (j = 0; j < glRefConfig.maxColorAttachments; j++) { + if (fbo->colorBuffers[j]) qglDeleteRenderbuffers(1, &fbo->colorBuffers[j]); } - if(fbo->depthBuffer) + if (fbo->depthBuffer) qglDeleteRenderbuffers(1, &fbo->depthBuffer); - if(fbo->stencilBuffer) + if (fbo->stencilBuffer) qglDeleteRenderbuffers(1, &fbo->stencilBuffer); - if(fbo->frameBuffer) + if (fbo->frameBuffer) qglDeleteFramebuffers(1, &fbo->frameBuffer); } } @@ -714,16 +607,14 @@ void FBO_Shutdown(void) R_FBOList_f ============ */ -void R_FBOList_f(void) -{ - int i; - FBO_t *fbo; +void R_FBOList_f(void) { + int i; + FBO_t *fbo; ri.Printf(PRINT_ALL, " size name\n"); ri.Printf(PRINT_ALL, "----------------------------------------------------------\n"); - for(i = 0; i < tr.numFBOs; i++) - { + for (i = 0; i < tr.numFBOs; i++) { fbo = tr.fbos[i]; ri.Printf(PRINT_ALL, " %4i: %4i %4i %s\n", i, fbo->width, fbo->height, fbo->name); @@ -732,8 +623,8 @@ void R_FBOList_f(void) ri.Printf(PRINT_ALL, " %i FBOs\n", tr.numFBOs); } -void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexScale, FBO_t *dst, vec4i_t inDstBox, struct shaderProgram_s *shaderProgram, vec4_t inColor, int blend) -{ +void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexScale, FBO_t *dst, vec4i_t inDstBox, struct shaderProgram_s *shaderProgram, + vec4_t inColor, int blend) { vec4i_t dstBox, srcBox; vec2_t srcTexScale; vec4_t color; @@ -747,80 +638,59 @@ void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexS if (!src) return; - if (inSrcBox) - { - VectorSet4(srcBox, inSrcBox[0], inSrcBox[1], inSrcBox[0] + inSrcBox[2], inSrcBox[1] + inSrcBox[3]); - } - else - { + if (inSrcBox) { + VectorSet4(srcBox, inSrcBox[0], inSrcBox[1], inSrcBox[0] + inSrcBox[2], inSrcBox[1] + inSrcBox[3]); + } else { VectorSet4(srcBox, 0, 0, src->width, src->height); } // framebuffers are 0 bottom, Y up. - if (inDstBox) - { - if (dst) - { + if (inDstBox) { + if (dst) { dstBox[0] = inDstBox[0]; dstBox[1] = dst->height - inDstBox[1] - inDstBox[3]; dstBox[2] = inDstBox[0] + inDstBox[2]; dstBox[3] = dst->height - inDstBox[1]; - } - else - { + } else { dstBox[0] = inDstBox[0]; dstBox[1] = glConfig.vidHeight - inDstBox[1] - inDstBox[3]; dstBox[2] = inDstBox[0] + inDstBox[2]; dstBox[3] = glConfig.vidHeight - inDstBox[1]; } - } - else if (dst) - { + } else if (dst) { VectorSet4(dstBox, 0, dst->height, dst->width, 0); - } - else - { + } else { VectorSet4(dstBox, 0, glConfig.vidHeight, glConfig.vidWidth, 0); } - if (inSrcTexScale) - { + if (inSrcTexScale) { VectorCopy2(inSrcTexScale, srcTexScale); - } - else - { + } else { srcTexScale[0] = srcTexScale[1] = 1.0f; } - if (inColor) - { + if (inColor) { VectorCopy4(inColor, color); - } - else - { + } else { VectorCopy4(colorWhite, color); } - if (!shaderProgram) - { + if (!shaderProgram) { shaderProgram = &tr.textureColorShader; } FBO_Bind(dst); - if (glState.currentFBO) - { + if (glState.currentFBO) { width = glState.currentFBO->width; height = glState.currentFBO->height; - } - else - { + } else { width = glConfig.vidWidth; height = glConfig.vidHeight; } - qglViewport( 0, 0, width, height ); - qglScissor( 0, 0, width, height ); + qglViewport(0, 0, width, height); + qglScissor(0, 0, width, height); Matrix16Ortho(0, width, height, 0, 0, 1, projection); @@ -833,18 +703,22 @@ void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexS VectorSet4(quadVerts[2], dstBox[2], dstBox[3], 0, 1); VectorSet4(quadVerts[3], dstBox[0], dstBox[3], 0, 1); - texCoords[0][0] = srcBox[0] / (float)src->width; texCoords[0][1] = 1.0f - srcBox[1] / (float)src->height; - texCoords[1][0] = srcBox[2] / (float)src->width; texCoords[1][1] = 1.0f - srcBox[1] / (float)src->height; - texCoords[2][0] = srcBox[2] / (float)src->width; texCoords[2][1] = 1.0f - srcBox[3] / (float)src->height; - texCoords[3][0] = srcBox[0] / (float)src->width; texCoords[3][1] = 1.0f - srcBox[3] / (float)src->height; + texCoords[0][0] = srcBox[0] / (float)src->width; + texCoords[0][1] = 1.0f - srcBox[1] / (float)src->height; + texCoords[1][0] = srcBox[2] / (float)src->width; + texCoords[1][1] = 1.0f - srcBox[1] / (float)src->height; + texCoords[2][0] = srcBox[2] / (float)src->width; + texCoords[2][1] = 1.0f - srcBox[3] / (float)src->height; + texCoords[3][0] = srcBox[0] / (float)src->width; + texCoords[3][1] = 1.0f - srcBox[3] / (float)src->height; - invTexRes[0] = 1.0f / src->width * srcTexScale[0]; + invTexRes[0] = 1.0f / src->width * srcTexScale[0]; invTexRes[1] = 1.0f / src->height * srcTexScale[1]; - GL_State( blend ); + GL_State(blend); GLSL_BindProgram(shaderProgram); - + GLSL_SetUniformMatrix4x4(shaderProgram, UNIFORM_MODELVIEWPROJECTIONMATRIX, projection); GLSL_SetUniformVec4(shaderProgram, UNIFORM_COLOR, color); GLSL_SetUniformVec2(shaderProgram, UNIFORM_INVTEXRES, invTexRes); @@ -856,102 +730,80 @@ void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexS FBO_Bind(oldFbo); } -void FBO_Blit(FBO_t *src, vec4i_t inSrcBox, vec2_t srcTexScale, FBO_t *dst, vec4i_t dstBox, struct shaderProgram_s *shaderProgram, vec4_t color, int blend) -{ +void FBO_Blit(FBO_t *src, vec4i_t inSrcBox, vec2_t srcTexScale, FBO_t *dst, vec4i_t dstBox, struct shaderProgram_s *shaderProgram, vec4_t color, int blend) { vec4i_t srcBox; - if (!src) - { + if (!src) { ri.Printf(PRINT_WARNING, "Tried to blit from a NULL FBO!\n"); return; } // framebuffers are 0 bottom, Y up. - if (inSrcBox) - { + if (inSrcBox) { srcBox[0] = inSrcBox[0]; srcBox[1] = src->height - inSrcBox[1] - inSrcBox[3]; srcBox[2] = inSrcBox[2]; srcBox[3] = inSrcBox[3]; - } - else - { + } else { VectorSet4(srcBox, 0, src->height, src->width, -src->height); } FBO_BlitFromTexture(src->colorImage[0], srcBox, srcTexScale, dst, dstBox, shaderProgram, color, blend | GLS_DEPTHTEST_DISABLE); } -void FBO_FastBlit(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, int buffers, int filter) -{ +void FBO_FastBlit(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, int buffers, int filter) { vec4i_t srcBoxFinal, dstBoxFinal; GLuint srcFb, dstFb; // get to a neutral state first - //FBO_Bind(NULL); + // FBO_Bind(NULL); srcFb = src ? src->frameBuffer : 0; dstFb = dst ? dst->frameBuffer : 0; - if (!srcBox) - { - if (src) - { + if (!srcBox) { + if (src) { VectorSet4(srcBoxFinal, 0, 0, src->width, src->height); - } - else - { + } else { VectorSet4(srcBoxFinal, 0, 0, glConfig.vidWidth, glConfig.vidHeight); } - } - else - { + } else { VectorSet4(srcBoxFinal, srcBox[0], srcBox[1], srcBox[0] + srcBox[2], srcBox[1] + srcBox[3]); } - if (!dstBox) - { - if (dst) - { + if (!dstBox) { + if (dst) { VectorSet4(dstBoxFinal, 0, 0, dst->width, dst->height); - } - else - { + } else { VectorSet4(dstBoxFinal, 0, 0, glConfig.vidWidth, glConfig.vidHeight); } - } - else - { + } else { VectorSet4(dstBoxFinal, dstBox[0], dstBox[1], dstBox[0] + dstBox[2], dstBox[1] + dstBox[3]); } qglBindFramebuffer(GL_READ_FRAMEBUFFER, srcFb); qglBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFb); - qglBlitFramebuffer(srcBoxFinal[0], srcBoxFinal[1], srcBoxFinal[2], srcBoxFinal[3], - dstBoxFinal[0], dstBoxFinal[1], dstBoxFinal[2], dstBoxFinal[3], - buffers, filter); + qglBlitFramebuffer(srcBoxFinal[0], srcBoxFinal[1], srcBoxFinal[2], srcBoxFinal[3], dstBoxFinal[0], dstBoxFinal[1], dstBoxFinal[2], dstBoxFinal[3], buffers, + filter); qglBindFramebuffer(GL_FRAMEBUFFER, 0); glState.currentFBO = NULL; } -void FBO_FastBlitIndexed(FBO_t *src, FBO_t *dst, int srcReadBuffer, int dstDrawBuffer, int buffers, int filter) -{ - assert (src != NULL); - assert (dst != NULL); +void FBO_FastBlitIndexed(FBO_t *src, FBO_t *dst, int srcReadBuffer, int dstDrawBuffer, int buffers, int filter) { + assert(src != NULL); + assert(dst != NULL); qglBindFramebuffer(GL_READ_FRAMEBUFFER, src->frameBuffer); - qglReadBuffer (GL_COLOR_ATTACHMENT0 + srcReadBuffer); + qglReadBuffer(GL_COLOR_ATTACHMENT0 + srcReadBuffer); qglBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst->frameBuffer); - qglDrawBuffer (GL_COLOR_ATTACHMENT0 + dstDrawBuffer); + qglDrawBuffer(GL_COLOR_ATTACHMENT0 + dstDrawBuffer); - qglBlitFramebuffer(0, 0, src->width, src->height, - 0, 0, dst->width, dst->height, - buffers, filter); + qglBlitFramebuffer(0, 0, src->width, src->height, 0, 0, dst->width, dst->height, buffers, filter); - qglReadBuffer (GL_COLOR_ATTACHMENT0); + qglReadBuffer(GL_COLOR_ATTACHMENT0); glState.currentFBO = dst; FBO_SetupDrawBuffers(); diff --git a/codemp/rd-rend2/tr_flares.cpp b/codemp/rd-rend2/tr_flares.cpp index be6d4120e1..5f1b048780 100644 --- a/codemp/rd-rend2/tr_flares.cpp +++ b/codemp/rd-rend2/tr_flares.cpp @@ -54,56 +54,54 @@ up to five or more times in a frame with 3D status bar icons). ============================================================================= */ - // flare states maintain visibility over multiple frames for fading // layers: view, mirror, menu typedef struct flare_s { - struct flare_s *next; // for active chain + struct flare_s *next; // for active chain - int addedFrame; + int addedFrame; - qboolean inPortal; // true if in a portal view of the scene - int frameSceneNum; - void *surface; - int fogNum; + qboolean inPortal; // true if in a portal view of the scene + int frameSceneNum; + void *surface; + int fogNum; - int fadeTime; + int fadeTime; - qboolean visible; // state of last test - float drawIntensity; // may be non 0 even if !visible due to fading + qboolean visible; // state of last test + float drawIntensity; // may be non 0 even if !visible due to fading - int windowX, windowY; - float eyeZ; + int windowX, windowY; + float eyeZ; - vec3_t origin; - vec3_t color; - vec3_t normal; + vec3_t origin; + vec3_t color; + vec3_t normal; } flare_t; -#define MAX_FLARES 128 +#define MAX_FLARES 128 -flare_t r_flareStructs[MAX_FLARES]; -flare_t *r_activeFlares, *r_inactiveFlares; +flare_t r_flareStructs[MAX_FLARES]; +flare_t *r_activeFlares, *r_inactiveFlares; /* ================== R_ClearFlares ================== */ -void R_ClearFlares( void ) { - int i; +void R_ClearFlares(void) { + int i; - Com_Memset( r_flareStructs, 0, sizeof( r_flareStructs ) ); + Com_Memset(r_flareStructs, 0, sizeof(r_flareStructs)); r_activeFlares = NULL; r_inactiveFlares = NULL; - for ( i = 0 ; i < MAX_FLARES ; i++ ) { + for (i = 0; i < MAX_FLARES; i++) { r_flareStructs[i].next = r_inactiveFlares; r_inactiveFlares = &r_flareStructs[i]; } } - /* ================== RB_AddFlare @@ -111,52 +109,48 @@ RB_AddFlare This is called at surface tesselation time ================== */ -void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal ) { - int i; - flare_t *f; - vec3_t local; - float d = 1.0f; - vec4_t eye, clip, normalized, window; +void RB_AddFlare(void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal) { + int i; + flare_t *f; + vec3_t local; + float d = 1.0f; + vec4_t eye, clip, normalized, window; backEnd.pc.c_flareAdds++; - if(normal && (normal[0] || normal[1] || normal[2])) - { - VectorSubtract( backEnd.viewParms.ori.origin, point, local ); + if (normal && (normal[0] || normal[1] || normal[2])) { + VectorSubtract(backEnd.viewParms.ori.origin, point, local); VectorNormalizeFast(local); d = DotProduct(local, normal); } // if the point is off the screen, don't bother adding it // calculate screen coordinates and depth - R_TransformModelToClip( point, backEnd.ori.modelViewMatrix, - backEnd.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(point, backEnd.ori.modelViewMatrix, backEnd.viewParms.projectionMatrix, eye, clip); // check to see if the point is completely off screen - for ( i = 0 ; i < 3 ; i++ ) { - if ( clip[i] >= clip[3] || clip[i] <= -clip[3] ) { + for (i = 0; i < 3; i++) { + if (clip[i] >= clip[3] || clip[i] <= -clip[3]) { return; } } - R_TransformClipToWindow( clip, &backEnd.viewParms, normalized, window ); + R_TransformClipToWindow(clip, &backEnd.viewParms, normalized, window); - if ( window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth - || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight ) { - return; // shouldn't happen, since we check the clip[] above, except for FP rounding + if (window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight) { + return; // shouldn't happen, since we check the clip[] above, except for FP rounding } // see if a flare with a matching surface, scene, and view exists - for ( f = r_activeFlares ; f ; f = f->next ) { - if ( f->surface == surface && f->frameSceneNum == backEnd.viewParms.frameSceneNum - && f->inPortal == backEnd.viewParms.isPortal ) { + for (f = r_activeFlares; f; f = f->next) { + if (f->surface == surface && f->frameSceneNum == backEnd.viewParms.frameSceneNum && f->inPortal == backEnd.viewParms.isPortal) { break; } } // allocate a new one - if (!f ) { - if ( !r_inactiveFlares ) { + if (!f) { + if (!r_inactiveFlares) { // the list is completely full return; } @@ -171,7 +165,7 @@ void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t f->addedFrame = -1; } - if ( f->addedFrame != backEnd.viewParms.frameCount - 1 ) { + if (f->addedFrame != backEnd.viewParms.frameCount - 1) { f->visible = qfalse; f->fadeTime = backEnd.refdef.time - 2000; } @@ -180,12 +174,12 @@ void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t f->fogNum = fogNum; VectorCopy(point, f->origin); - VectorCopy( color, f->color ); - VectorCopy( normal, f->normal); + VectorCopy(color, f->color); + VectorCopy(normal, f->normal); // fade the intensity of the flare down as the // light surface turns away from the viewer - VectorScale( f->color, d, f->color ); + VectorScale(f->color, d, f->color); // save info needed to test f->windowX = backEnd.viewParms.viewportX + window[0]; @@ -199,44 +193,42 @@ void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t RB_AddDlightFlares ================== */ -void RB_AddDlightFlares( void ) { - dlight_t *l; - int i, j, k; - fog_t *fog = NULL; +void RB_AddDlightFlares(void) { + dlight_t *l; + int i, j, k; + fog_t *fog = NULL; - if ( !r_flares->integer ) { + if (!r_flares->integer) { return; } l = backEnd.refdef.dlights; - if(tr.world) + if (tr.world) fog = tr.world->fogs; - for (i=0 ; inumfogs ; j++ ) { + if (fog) { + // find which fog volume the light is in + for (j = 1; j < tr.world->numfogs; j++) { fog = &tr.world->fogs[j]; - for ( k = 0 ; k < 3 ; k++ ) { - if ( l->origin[k] < fog->bounds[0][k] || l->origin[k] > fog->bounds[1][k] ) { + for (k = 0; k < 3; k++) { + if (l->origin[k] < fog->bounds[0][k] || l->origin[k] > fog->bounds[1][k]) { break; } } - if ( k == 3 ) { + if (k == 3) { break; } } - if ( j == tr.world->numfogs ) { + if (j == tr.world->numfogs) { j = 0; } - } - else + } else j = 0; - RB_AddFlare( (void *)l, j, l->origin, l->color, NULL ); + RB_AddFlare((void *)l, j, l->origin, l->color, NULL); } } @@ -253,45 +245,42 @@ FLARE BACK END RB_TestFlare ================== */ -void RB_TestFlare( flare_t *f ) { - float depth; - qboolean visible; - float fade; - float screenZ; - FBO_t *oldFbo; +void RB_TestFlare(flare_t *f) { + float depth; + qboolean visible; + float fade; + float screenZ; + FBO_t *oldFbo; backEnd.pc.c_flareTests++; // if we're doing multisample rendering, read from the correct FBO oldFbo = glState.currentFBO; - if (tr.msaaResolveFbo) - { + if (tr.msaaResolveFbo) { FBO_Bind(tr.msaaResolveFbo); } // read back the z buffer contents, which is bad // TODO: Don't use glReadPixels - qglReadPixels( f->windowX, f->windowY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth ); + qglReadPixels(f->windowX, f->windowY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); // if we're doing multisample rendering, switch to the old FBO - if (tr.msaaResolveFbo) - { + if (tr.msaaResolveFbo) { FBO_Bind(oldFbo); } - screenZ = backEnd.viewParms.projectionMatrix[14] / - ( ( 2*depth - 1 ) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10] ); + screenZ = backEnd.viewParms.projectionMatrix[14] / ((2 * depth - 1) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10]); - visible = (qboolean)(( -f->eyeZ - -screenZ ) < 24); + visible = (qboolean)((-f->eyeZ - -screenZ) < 24); - if ( visible ) { - if ( !f->visible ) { + if (visible) { + if (!f->visible) { f->visible = qtrue; f->fadeTime = backEnd.refdef.time - 1; } - fade = ( ( backEnd.refdef.time - f->fadeTime ) / 500.0f ); + fade = ((backEnd.refdef.time - f->fadeTime) / 500.0f); } else { - // Dont fade out when flare is occluded. Will result in the ability to see + // Dont fade out when flare is occluded. Will result in the ability to see // flares through surfaces on high movement speeds /*if ( f->visible ) { f->visible = qfalse; @@ -301,40 +290,39 @@ void RB_TestFlare( flare_t *f ) { fade = 0.0f; } - if ( fade < 0 ) { + if (fade < 0) { fade = 0; } - if ( fade > 1 ) { + if (fade > 1) { fade = 1; } f->drawIntensity = fade; } - /* ================== RB_RenderFlare ================== */ -void RB_RenderFlare( flare_t *f ) { - vec4_t color; +void RB_RenderFlare(flare_t *f) { + vec4_t color; backEnd.pc.c_flareRenders++; srfFlare_t *flare = (srfFlare_t *)f->surface; backEnd.currentEntity = &tr.worldEntity; - RB_BeginSurface( flare->shader, f->fogNum, 0 ); + RB_BeginSurface(flare->shader, f->fogNum, 0); - vec3_t dir; - vec3_t left, up; - vec3_t origin; - float d, dist; + vec3_t dir; + vec3_t left, up; + vec3_t origin; + float d, dist; // calculate the xyz locations for the four corners VectorMA(f->origin, 3, f->normal, origin); - float* snormal = f->normal; + float *snormal = f->normal; VectorSubtract(origin, backEnd.viewParms.ori.origin, dir); dist = VectorNormalize(dir); @@ -349,15 +337,13 @@ void RB_RenderFlare( flare_t *f ) { color[0] = d; color[1] = d; color[2] = d; - color[3] = 1.0f; //only gets used if the shader has cgen exact_vertex! + color[3] = 1.0f; // only gets used if the shader has cgen exact_vertex! float radius = tess.shader->portalRange ? tess.shader->portalRange : 30; - if (dist < 512.0f) - { + if (dist < 512.0f) { radius = radius * dist / 512.0f; } - if (radius < 5.0f) - { + if (radius < 5.0f) { radius = 5.0f; } VectorScale(backEnd.viewParms.ori.axis[1], radius, left); @@ -387,12 +373,12 @@ when occluded by something in the main view, and portal flares that should extend past the portal edge will be overwritten. ================== */ -void RB_RenderFlares (void) { - flare_t *f; - flare_t **prev; - qboolean draw; +void RB_RenderFlares(void) { + flare_t *f; + flare_t **prev; + qboolean draw; - if ( !r_flares->integer ) { + if (!r_flares->integer) { return; } @@ -404,14 +390,14 @@ void RB_RenderFlares (void) { backEnd.currentEntity = &tr.worldEntity; backEnd.ori = backEnd.viewParms.world; -// RB_AddDlightFlares(); + // RB_AddDlightFlares(); // perform z buffer readback on each flare in this view draw = qfalse; prev = &r_activeFlares; - while ( ( f = *prev ) != NULL ) { + while ((f = *prev) != NULL) { // throw out any flares that weren't added last frame - if ( f->addedFrame < backEnd.viewParms.frameCount - 1 ) { + if (f->addedFrame < backEnd.viewParms.frameCount - 1) { *prev = f->next; f->next = r_inactiveFlares; r_inactiveFlares = f; @@ -420,10 +406,9 @@ void RB_RenderFlares (void) { // don't draw any here that aren't from this scene / portal f->drawIntensity = 0; - if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum - && f->inPortal == backEnd.viewParms.isPortal ) { - RB_TestFlare( f ); - if ( f->drawIntensity ) { + if (f->frameSceneNum == backEnd.viewParms.frameSceneNum && f->inPortal == backEnd.viewParms.isPortal) { + RB_TestFlare(f); + if (f->drawIntensity) { draw = qtrue; } else { // this flare has completely faded out, so remove it from the chain @@ -437,20 +422,13 @@ void RB_RenderFlares (void) { prev = &f->next; } - if ( !draw ) { - return; // none visible + if (!draw) { + return; // none visible } - for ( f = r_activeFlares ; f ; f = f->next ) { - if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum - && f->inPortal == backEnd.viewParms.isPortal - && f->drawIntensity ) { - RB_RenderFlare( f ); + for (f = r_activeFlares; f; f = f->next) { + if (f->frameSceneNum == backEnd.viewParms.frameSceneNum && f->inPortal == backEnd.viewParms.isPortal && f->drawIntensity) { + RB_RenderFlare(f); } } } - - - - - diff --git a/codemp/rd-rend2/tr_ghoul2.cpp b/codemp/rd-rend2/tr_ghoul2.cpp index aea553066e..b974222d32 100644 --- a/codemp/rd-rend2/tr_ghoul2.cpp +++ b/codemp/rd-rend2/tr_ghoul2.cpp @@ -1,4 +1,4 @@ -#include "client/client.h" //FIXME!! EVIL - just include the definitions needed +#include "client/client.h" //FIXME!! EVIL - just include the definitions needed #include "tr_local.h" #include "qcommon/matcomp.h" #include "qcommon/qcommon.h" @@ -9,12 +9,12 @@ #endif #ifdef _MSC_VER -#pragma warning (disable: 4512) //default assignment operator could not be gened +#pragma warning(disable : 4512) // default assignment operator could not be gened #endif #include "qcommon/disablewarnings.h" #include "tr_cache.h" -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) #ifdef G2_PERFORMANCE_ANALYSIS #include "qcommon/timing.h" @@ -41,8 +41,7 @@ int G2Time_RB_SurfaceGhoul = 0; int G2Time_G2_SetupModelPointers = 0; int G2Time_PreciseFrame = 0; -void G2Time_ResetTimers(void) -{ +void G2Time_ResetTimers(void) { G2Time_RenderSurfaces = 0; G2Time_R_AddGHOULSurfaces = 0; G2Time_G2_TransformGhoulBones = 0; @@ -55,42 +54,33 @@ void G2Time_ResetTimers(void) G2PerformanceCounter_G2_TransformGhoulBones = 0; } -void G2Time_ReportTimers(void) -{ - Com_Printf("\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: %i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: %i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", - G2Time_RenderSurfaces, - G2Time_R_AddGHOULSurfaces, - G2Time_G2_TransformGhoulBones, - G2Time_G2_ProcessGeneratedSurfaceBolts, - G2Time_ProcessModelBoltSurfaces, - G2Time_G2_ConstructGhoulSkeleton, - G2Time_RB_SurfaceGhoul, - G2Time_G2_SetupModelPointers, - G2Time_PreciseFrame, - G2PerformanceCounter_G2_TransformGhoulBones - ); +void G2Time_ReportTimers(void) { + Com_Printf("\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: " + "%i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: " + "%i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", + G2Time_RenderSurfaces, G2Time_R_AddGHOULSurfaces, G2Time_G2_TransformGhoulBones, G2Time_G2_ProcessGeneratedSurfaceBolts, + G2Time_ProcessModelBoltSurfaces, G2Time_G2_ConstructGhoulSkeleton, G2Time_RB_SurfaceGhoul, G2Time_G2_SetupModelPointers, G2Time_PreciseFrame, + G2PerformanceCounter_G2_TransformGhoulBones); } #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef __linux__ #include #else #include #endif -//rww - RAGDOLL_END +// rww - RAGDOLL_END static const int MAX_RENDERABLE_SURFACES = 2048; static CRenderableSurface renderSurfHeap[MAX_RENDERABLE_SURFACES]; static int currentRenderSurfIndex = 0; -static CRenderableSurface *AllocGhoul2RenderableSurface() -{ - if ( currentRenderSurfIndex >= MAX_RENDERABLE_SURFACES - 1) - { +static CRenderableSurface *AllocGhoul2RenderableSurface() { + if (currentRenderSurfIndex >= MAX_RENDERABLE_SURFACES - 1) { ResetGhoul2RenderableSurfaceHeap(); - ri.Printf( PRINT_DEVELOPER, "AllocRenderableSurface: Reached maximum number of Ghoul2 renderable surfaces (%d)\n", MAX_RENDERABLE_SURFACES ); + ri.Printf(PRINT_DEVELOPER, "AllocRenderableSurface: Reached maximum number of Ghoul2 renderable surfaces (%d)\n", MAX_RENDERABLE_SURFACES); } CRenderableSurface *rs = &renderSurfHeap[currentRenderSurfIndex++]; @@ -100,38 +90,27 @@ static CRenderableSurface *AllocGhoul2RenderableSurface() return rs; } -void ResetGhoul2RenderableSurfaceHeap() -{ - currentRenderSurfIndex = 0; -} +void ResetGhoul2RenderableSurfaceHeap() { currentRenderSurfIndex = 0; } bool HackadelicOnClient = false; // means this is a render traversal qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); -extern cvar_t *r_Ghoul2AnimSmooth; -extern cvar_t *r_Ghoul2UnSqashAfterSmooth; +extern cvar_t *r_Ghoul2AnimSmooth; +extern cvar_t *r_Ghoul2UnSqashAfterSmooth; -static const mdxaBone_t identityMatrix = -{ - { - { 0.0f, -1.0f, 0.0f, 0.0f }, - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } -}; +static const mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; // I hate doing this, but this is the simplest way to get this into the routines it needs to be -mdxaBone_t worldMatrix; -mdxaBone_t worldMatrixInv; +mdxaBone_t worldMatrix; +mdxaBone_t worldMatrixInv; #ifdef _G2_GORE -qhandle_t goreShader=-1; +qhandle_t goreShader = -1; #endif // nasty little matrix multiply going on here.. -void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *in) -{ +void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *in) { assert(out != nullptr); assert(in2 != nullptr); assert(in != nullptr); @@ -162,7 +141,7 @@ void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *i const float m21 = in->matrix[2][1]; const float m22 = in->matrix[2][2]; const float m23 = in->matrix[2][3]; - + // first row of out out->matrix[0][0] = (n00 * m00) + (n01 * m10) + (n02 * m20); out->matrix[0][1] = (n00 * m01) + (n01 * m11) + (n02 * m21); @@ -182,128 +161,85 @@ void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *i out->matrix[2][3] = (n20 * m03) + (n21 * m13) + (n22 * m23) + n23; } -void Mat3x4_Scale( mdxaBone_t *result, const mdxaBone_t *lhs, const float scale ) -{ - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 3; ++j ) - { +void Mat3x4_Scale(mdxaBone_t *result, const mdxaBone_t *lhs, const float scale) { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { result->matrix[i][j] = lhs->matrix[i][j] * scale; } } } -void Mat3x4_Lerp( - mdxaBone_t *result, - const mdxaBone_t *lhs, - const mdxaBone_t *rhs, - const float t ) -{ - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 4; ++j ) - { +void Mat3x4_Lerp(mdxaBone_t *result, const mdxaBone_t *lhs, const mdxaBone_t *rhs, const float t) { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { result->matrix[i][j] = lhs->matrix[i][j] * t + rhs->matrix[i][j] * (1.0f - t); } } } -const mdxaBone_t operator +( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) -{ +const mdxaBone_t operator+(const mdxaBone_t &lhs, const mdxaBone_t &rhs) { mdxaBone_t result; - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 4; ++j ) - { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { result.matrix[i][j] = lhs.matrix[i][j] + rhs.matrix[i][j]; } } return result; } -const mdxaBone_t operator -( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) -{ +const mdxaBone_t operator-(const mdxaBone_t &lhs, const mdxaBone_t &rhs) { mdxaBone_t result; - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 4; ++j ) - { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { result.matrix[i][j] = lhs.matrix[i][j] - rhs.matrix[i][j]; } } return result; } -const mdxaBone_t operator *( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) -{ +const mdxaBone_t operator*(const mdxaBone_t &lhs, const mdxaBone_t &rhs) { mdxaBone_t result; Mat3x4_Multiply(&result, &lhs, &rhs); return result; } -const mdxaBone_t operator *( const mdxaBone_t& lhs, const float scale ) -{ +const mdxaBone_t operator*(const mdxaBone_t &lhs, const float scale) { mdxaBone_t result; - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 4; ++j ) - { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 4; ++j) { result.matrix[i][j] = lhs.matrix[i][j] * scale; } } return result; } -const mdxaBone_t operator *( const float scale, const mdxaBone_t& rhs ) -{ - return rhs * scale; -} +const mdxaBone_t operator*(const float scale, const mdxaBone_t &rhs) { return rhs * scale; } +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v& initrootSList, - model_t *initcurrentModel, - boneInfo_v& initboneList) - : surfaceNum(initsurfaceNum) - , boneUsedList(initboneUsedList) - , rootSList(initrootSList) - , currentModel(initcurrentModel) - , boneList(initboneList) - { - } + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; -class CTransformBone -{ -public: +class CTransformBone { + public: int touch; // for minimal recalculation int touchRender; - mdxaBone_t boneMatrix; //final matrix - int parent; // only set once - - CTransformBone() - : touch(0) - , touchRender(0) - { - } + mdxaBone_t boneMatrix; // final matrix + int parent; // only set once + CTransformBone() : touch(0), touchRender(0) {} }; -struct SBoneCalc -{ +struct SBoneCalc { int newFrame; - int currentFrame; + int currentFrame; float backlerp; float blendFrame; int blendOldFrame; @@ -312,23 +248,17 @@ struct SBoneCalc }; class CBoneCache; -static void G2_TransformBone( int index, CBoneCache &CB ); +static void G2_TransformBone(int index, CBoneCache &CB); -class CBoneCache -{ - void EvalLow( int index ) - { +class CBoneCache { + void EvalLow(int index) { assert(index >= 0 && index < (int)mBones.size()); - if ( mFinalBones[index].touch != mCurrentTouch ) - { + if (mFinalBones[index].touch != mCurrentTouch) { // need to evaluate the bone - assert((mFinalBones[index].parent >= 0 - && mFinalBones[index].parent < (int)mFinalBones.size()) || - (index == 0 && mFinalBones[index].parent == -1)); + assert((mFinalBones[index].parent >= 0 && mFinalBones[index].parent < (int)mFinalBones.size()) || (index == 0 && mFinalBones[index].parent == -1)); - if ( mFinalBones[index].parent >= 0 ) - { + if (mFinalBones[index].parent >= 0) { EvalLow(mFinalBones[index].parent); // make sure parent is evaluated const SBoneCalc &par = mBones[mFinalBones[index].parent]; @@ -348,27 +278,20 @@ class CBoneCache } } - void SmoothLow( int index ) - { - if ( mSmoothBones[index].touch == mLastTouch ) - { - const mdxaBone_t& newM = mFinalBones[index].boneMatrix; - mdxaBone_t& oldM = mSmoothBones[index].boneMatrix; + void SmoothLow(int index) { + if (mSmoothBones[index].touch == mLastTouch) { + const mdxaBone_t &newM = mFinalBones[index].boneMatrix; + mdxaBone_t &oldM = mSmoothBones[index].boneMatrix; oldM = mSmoothFactor * (oldM - newM) + newM; - } - else - { + } else { mSmoothBones[index].boneMatrix = mFinalBones[index].boneMatrix; } - const mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); - const mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[index]); + const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[index]); - mdxaBone_t tempMatrix = - mSmoothBones[index].boneMatrix * skel->BasePoseMat; + mdxaBone_t tempMatrix = mSmoothBones[index].boneMatrix * skel->BasePoseMat; const float maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[1][0]); @@ -379,20 +302,18 @@ class CBoneCache mSmoothBones[index].touch = mCurrentTouch; #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { assert(!Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -public: - int frameSize; - const mdxaHeader_t *header; - const model_t *mod; + public: + int frameSize; + const mdxaHeader_t *header; + const model_t *mod; // these are split for better cpu cache behavior std::vector mBones; @@ -405,7 +326,7 @@ class CBoneCache int mCurrentTouch; int mCurrentTouchRender; - int mLastTouch; + int mLastTouch; int mLastLastTouch; // for render smoothing @@ -415,83 +336,59 @@ class CBoneCache // GPU Data mat3x4_t boneMatrices[MAX_G2_BONES]; - int uboOffset; - int uboGPUFrame; - - CBoneCache( const model_t *amod, const mdxaHeader_t *aheader ) - : header(aheader) - , mod(amod) - , mBones(header->numBones) - , mFinalBones(header->numBones) - , mSmoothBones(header->numBones) - , mCurrentTouch(3) - , mLastTouch(2) - , mLastLastTouch(1) - , mSmoothingActive(false) - , mUnsquash(false) - , mSmoothFactor(0.0f) - , uboOffset(-1) - , uboGPUFrame(-1) - { + int uboOffset; + int uboGPUFrame; + + CBoneCache(const model_t *amod, const mdxaHeader_t *aheader) + : header(aheader), mod(amod), mBones(header->numBones), mFinalBones(header->numBones), mSmoothBones(header->numBones), mCurrentTouch(3), mLastTouch(2), + mLastLastTouch(1), mSmoothingActive(false), mUnsquash(false), mSmoothFactor(0.0f), uboOffset(-1), uboGPUFrame(-1) { assert(amod); assert(aheader); - + Com_Memset(boneMatrices, 0, sizeof(boneMatrices)); int numBones = header->numBones; - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); - for ( int i = 0; i < numBones; ++i ) - { - mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); + for (int i = 0; i < numBones; ++i) { + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); mFinalBones[i].parent = skel->parent; } } - SBoneCalc &Root() - { + SBoneCalc &Root() { assert(mBones.size()); return mBones[0]; } - const mdxaBone_t &EvalUnsmooth( int index ) - { + const mdxaBone_t &EvalUnsmooth(int index) { EvalLow(index); - if ( mSmoothingActive && mSmoothBones[index].touch ) - { + if (mSmoothingActive && mSmoothBones[index].touch) { return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - const mdxaBone_t &Eval( int index ) - { - //Hey, this is what sof2 does. Let's try it out. - assert(index >= 0 && index <( int)mBones.size()); - if ( mFinalBones[index].touch != mCurrentTouch ) - { + const mdxaBone_t &Eval(int index) { + // Hey, this is what sof2 does. Let's try it out. + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { EvalLow(index); } return mFinalBones[index].boneMatrix; } - const mdxaBone_t &EvalRender( int index ) - { + const mdxaBone_t &EvalRender(int index) { assert(index >= 0 && index < (int)mBones.size()); - if ( mFinalBones[index].touch != mCurrentTouch ) - { + if (mFinalBones[index].touch != mCurrentTouch) { mFinalBones[index].touchRender = mCurrentTouchRender; EvalLow(index); } - if ( mSmoothingActive ) - { - if ( mSmoothBones[index].touch != mCurrentTouch ) - { + if (mSmoothingActive) { + if (mSmoothBones[index].touch != mCurrentTouch) { SmoothLow(index); } @@ -501,26 +398,22 @@ class CBoneCache return mFinalBones[index].boneMatrix; } - bool WasRendered( int index ) - { + bool WasRendered(int index) { assert(index >= 0 && index < (int)mBones.size()); return mFinalBones[index].touchRender == mCurrentTouchRender; } - int GetParent( int index ) - { - if ( index == 0 ) - { + int GetParent(int index) { + if (index == 0) { return -1; } - assert( index > 0 && index < (int)mBones.size()); + assert(index > 0 && index < (int)mBones.size()); return mFinalBones[index].parent; } }; -void RemoveBoneCache(CBoneCache *boneCache) -{ +void RemoveBoneCache(CBoneCache *boneCache) { #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations -= sizeof(*boneCache); #endif @@ -529,49 +422,37 @@ void RemoveBoneCache(CBoneCache *boneCache) } #ifdef _G2_LISTEN_SERVER_OPT -void CopyBoneCache(CBoneCache *to, CBoneCache *from) -{ - memcpy(to, from, sizeof(CBoneCache)); -} +void CopyBoneCache(CBoneCache *to, CBoneCache *from) { memcpy(to, from, sizeof(CBoneCache)); } #endif -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache) -{ +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache) { assert(boneCache); return boneCache->Eval(index); } // rww - RAGDOLL_BEGIN -const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) -{ - if (!ghoul2.mBoneCache) - { +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) { + if (!ghoul2.mBoneCache) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.header; } -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep) -{ +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep) { // fixme, these should be precomputed - if (!ghoul2.mBoneCache || !maxDep) - { + if (!ghoul2.mBoneCache || !maxDep) { return 0; } CBoneCache &boneCache = *ghoul2.mBoneCache; - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); - mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); int numDependencies = 0; - for (int i = 0; i < skel->numChildren; i++) - { - if (!maxDep) - { + for (int i = 0; i < skel->numChildren; i++) { + if (!maxDep) { return i; // number added } @@ -582,15 +463,13 @@ int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int numDependencies++; } - for (int i = 0; i < skel->numChildren; i++) - { + for (int i = 0; i < skel->numChildren; i++) { int num = G2_GetBoneDependents(ghoul2, skel->children[i], tempDependents, maxDep); tempDependents += num; numDependencies += num; maxDep -= num; assert(maxDep >= 0); - if (!maxDep) - { + if (!maxDep) { break; } } @@ -598,10 +477,8 @@ int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int return numDependencies; } -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) -{ - if (!ghoul2.mBoneCache) - { +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return false; } @@ -609,14 +486,8 @@ bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) return boneCache.WasRendered(boneNum); } -void G2_GetBoneBasepose( - CGhoul2Info &ghoul2, - int boneNum, - mdxaBone_t *&retBasepose, - mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { // yikes retBasepose = const_cast(&identityMatrix); retBaseposeInv = const_cast(&identityMatrix); @@ -628,18 +499,15 @@ void G2_GetBoneBasepose( assert(boneCache.mod); assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); retBasepose = &skel->BasePoseMat; retBaseposeInv = &skel->BasePoseMatInv; } -char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) -{ - if (!ghoul2.mBoneCache) - { +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return NULL; } @@ -647,43 +515,32 @@ char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) assert(boneCache.mod); assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); return skel->name; } -void G2_RagGetBoneBasePoseMatrixLow( - CGhoul2Info &ghoul2, - int boneNum, - mdxaBone_t &boneMatrix, - mdxaBone_t &retMatrix, - vec3_t scale) -{ +void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) { assert(ghoul2.mBoneCache); CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); Mat3x4_Multiply(&retMatrix, &boneMatrix, &skel->BasePoseMat); - if (scale[0]) - { + if (scale[0]) { retMatrix.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { retMatrix.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { retMatrix.matrix[2][3] *= scale[2]; } @@ -692,16 +549,8 @@ void G2_RagGetBoneBasePoseMatrixLow( VectorNormalize((float *)&retMatrix.matrix[2]); } -void G2_GetBoneMatrixLow( - CGhoul2Info &ghoul2, - int boneNum, - const vec3_t scale, - mdxaBone_t &retMatrix, - mdxaBone_t *&retBasepose, - mdxaBone_t *&retBaseposeInv) -{ - if ( !ghoul2.mBoneCache ) - { +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { retMatrix = identityMatrix; // yikes retBasepose = const_cast(&identityMatrix); @@ -715,29 +564,22 @@ void G2_GetBoneMatrixLow( assert(boneCache.mod); assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); - Mat3x4_Multiply( - &bolt, - &boneCache.Eval(boneNum), - &skel->BasePoseMat); + Mat3x4_Multiply(&bolt, &boneCache.Eval(boneNum), &skel->BasePoseMat); retBasepose = &skel->BasePoseMat; retBaseposeInv = &skel->BasePoseMatInv; - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } @@ -748,108 +590,69 @@ void G2_GetBoneMatrixLow( Mat3x4_Multiply(&retMatrix, &worldMatrix, &bolt); #ifdef _DEBUG - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 4; j++) - { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { assert(!Q_isnan(retMatrix.matrix[i][j])); } } #endif // _DEBUG } -int G2_GetParentBoneMatrixLow( - CGhoul2Info &ghoul2, - int boneNum, - const vec3_t scale, - mdxaBone_t &retMatrix, - mdxaBone_t *&retBasepose, - mdxaBone_t *&retBaseposeInv) -{ +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) { int parent = -1; - if ( ghoul2.mBoneCache ) - { + if (ghoul2.mBoneCache) { CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); assert(boneNum >= 0 && boneNum < boneCache.header->numBones); parent = boneCache.GetParent(boneNum); - if ( parent < 0 || parent >= boneCache.header->numBones ) - { + if (parent < 0 || parent >= boneCache.header->numBones) { parent = -1; retMatrix = identityMatrix; // yikes retBasepose = const_cast(&identityMatrix); retBaseposeInv = const_cast(&identityMatrix); - } - else - { - G2_GetBoneMatrixLow( - ghoul2, - parent, - scale, - retMatrix, - retBasepose, - retBaseposeInv); + } else { + G2_GetBoneMatrixLow(ghoul2, parent, scale, retMatrix, retBasepose, retBaseposeInv); } } return parent; } -//rww - RAGDOLL_END - -class CRenderSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - shader_t *cust_shader; - int fogNum; - qboolean personalModel; - CBoneCache *boneCache; - int renderfx; - skin_t *skin; - model_t *currentModel; - int lod; - boltInfo_v &boltList; +// rww - RAGDOLL_END + +class CRenderSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + shader_t *cust_shader; + int fogNum; + qboolean personalModel; + CBoneCache *boneCache; + int renderfx; + skin_t *skin; + model_t *currentModel; + int lod; + boltInfo_v &boltList; #ifdef _G2_GORE - shader_t *gore_shader; - CGoreSet *gore_set; + shader_t *gore_shader; + CGoreSet *gore_set; #endif - CRenderSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - shader_t *initcust_shader, - int initfogNum, - qboolean initpersonalModel, - CBoneCache *initboneCache, - int initrenderfx, - skin_t *initskin, - model_t *initcurrentModel, - int initlod, + CRenderSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, shader_t *initcust_shader, int initfogNum, qboolean initpersonalModel, + CBoneCache *initboneCache, int initrenderfx, skin_t *initskin, model_t *initcurrentModel, int initlod, #ifdef _G2_GORE - boltInfo_v &initboltList, - shader_t *initgore_shader, - CGoreSet *initgore_set + boltInfo_v &initboltList, shader_t *initgore_shader, CGoreSet *initgore_set #else - boltInfo_v &initboltList + boltInfo_v &initboltList #endif - ) - : surfaceNum(initsurfaceNum) - , rootSList(initrootSList) - , cust_shader(initcust_shader) - , fogNum(initfogNum) - , personalModel(initpersonalModel) - , boneCache(initboneCache) - , renderfx(initrenderfx) - , skin(initskin) - , currentModel(initcurrentModel) - , lod(initlod) - , boltList(initboltList) + ) + : surfaceNum(initsurfaceNum), rootSList(initrootSList), cust_shader(initcust_shader), fogNum(initfogNum), personalModel(initpersonalModel), + boneCache(initboneCache), renderfx(initrenderfx), skin(initskin), currentModel(initcurrentModel), lod(initlod), boltList(initboltList) #ifdef _G2_GORE - , gore_shader(initgore_shader) - , gore_set(initgore_set) + , + gore_shader(initgore_shader), gore_set(initgore_set) #endif { } @@ -860,42 +663,37 @@ class CRenderSurface All bones should be an identity orientation to display the mesh exactly as it is specified. -For all other frames, the bones represent the transformation from the +For all other frames, the bones represent the transformation from the orientation of the bone in the base frame to the orientation in this frame. */ - /* ============= R_ACullModel ============= */ -static int R_GCullModel( trRefEntity_t *ent ) { +static int R_GCullModel(trRefEntity_t *ent) { // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } - // cull bounding sphere - switch ( R_CullLocalPointAndRadius( vec3_origin, ent->e.radius * largestScale) ) - { - case CULL_OUT: - tr.pc.c_sphere_cull_md3_out++; - return CULL_OUT; + // cull bounding sphere + switch (R_CullLocalPointAndRadius(vec3_origin, ent->e.radius * largestScale)) { + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; case CULL_IN: tr.pc.c_sphere_cull_md3_in++; @@ -904,37 +702,36 @@ static int R_GCullModel( trRefEntity_t *ent ) { case CULL_CLIP: tr.pc.c_sphere_cull_md3_clip++; return CULL_IN; - } + } return CULL_IN; } - /* ================= R_AComputeFogNum ================= */ -static int R_GComputeFogNum( trRefEntity_t *ent ) { +static int R_GComputeFogNum(trRefEntity_t *ent) { - int i, j; - fog_t *fog; + int i, j; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j]) { break; } - if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + if (ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -943,78 +740,62 @@ static int R_GComputeFogNum( trRefEntity_t *ent ) { } // work out lod for this entity. -static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int lodBias ) -{ +static int G2_ComputeLOD(trRefEntity_t *ent, const model_t *currentModel, int lodBias) { float flod, lodscale; float projectedRadius; int lod; - if ( currentModel->numLods < 2 ) - { // model has only 1 LOD level, skip computations and bias - return(0); + if (currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias + return (0); } - if ( r_lodbias->integer > lodBias ) - { + if (r_lodbias->integer > lodBias) { lodBias = r_lodbias->integer; } // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } - projectedRadius = ProjectRadius( 0.75*largestScale*ent->e.radius, ent->e.origin ); + projectedRadius = ProjectRadius(0.75 * largestScale * ent->e.radius, ent->e.origin); // we reduce the radius to make the LOD match other model types which use // the actual bound box size - if ( projectedRadius != 0 ) - { - lodscale = (r_lodscale->value+r_autolodscalevalue->value); - if ( lodscale > 20 ) - { - lodscale = 20; - } - else if ( lodscale < 0 ) - { + if (projectedRadius != 0) { + lodscale = (r_lodscale->value + r_autolodscalevalue->value); + if (lodscale > 20) { + lodscale = 20; + } else if (lodscale < 0) { lodscale = 0; } - flod = 1.0f - projectedRadius * lodscale; - } - else - { - // object intersects near view plane, e.g. view weapon - flod = 0; - } - flod *= currentModel->numLods; - lod = Q_ftol( flod ); - - if ( lod < 0 ) - { - lod = 0; - } - else if ( lod >= currentModel->numLods ) - { - lod = currentModel->numLods - 1; - } + flod = 1.0f - projectedRadius * lodscale; + } else { + // object intersects near view plane, e.g. view weapon + flod = 0; + } + flod *= currentModel->numLods; + lod = Q_ftol(flod); + if (lod < 0) { + lod = 0; + } else if (lod >= currentModel->numLods) { + lod = currentModel->numLods - 1; + } lod += lodBias; - - if ( lod >= currentModel->numLods ) + + if (lod >= currentModel->numLods) lod = currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; @@ -1024,119 +805,97 @@ static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int l // // Bone Manipulation code - -void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) -{ +void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) { // this is revised for the 3x4 matrix we use in G2. - float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; + float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; float s; // If the trace of the matrix is greater than zero, then // perform an "instant" calculation. // Important note wrt. rouning errors: // Test if ( T > 0.00000001 ) to avoid large distortions! - if (t > 0.00000001) - { - s = sqrt(t) * 2; - quat[0] = ( mat->matrix[1][2] - mat->matrix[2][1] ) / s; - quat[1] = ( mat->matrix[2][0] - mat->matrix[0][2] ) / s; - quat[2] = ( mat->matrix[0][1] - mat->matrix[1][0] ) / s; - quat[3] = 0.25 * s; - } - else - { + if (t > 0.00000001) { + s = sqrt(t) * 2; + quat[0] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; + quat[1] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; + quat[2] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; + quat[3] = 0.25 * s; + } else { // If the trace of the matrix is equal to zero then identify // which major diagonal element has the greatest value. // Depending on this, calculate the following: - if ( mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2] ) { - // Column 0: - s = sqrt( 1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2])* 2; + if (mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2]) { + // Column 0: + s = sqrt(1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2]) * 2; quat[0] = 0.25 * s; - quat[1] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; - quat[2] = (mat->matrix[2][0] + mat->matrix[0][2] ) / s; - quat[3] = (mat->matrix[1][2] - mat->matrix[2][1] ) / s; - - } else if ( mat->matrix[1][1] > mat->matrix[2][2] ) { - // Column 1: - s = sqrt( 1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2] ) * 2; - quat[0] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; + quat[1] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; + quat[2] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[3] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; + + } else if (mat->matrix[1][1] > mat->matrix[2][2]) { + // Column 1: + s = sqrt(1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2]) * 2; + quat[0] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; quat[1] = 0.25 * s; - quat[2] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; - quat[3] = (mat->matrix[2][0] - mat->matrix[0][2] ) / s; + quat[2] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; + quat[3] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; } else { // Column 2: - s = sqrt( 1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1] ) * 2; - quat[0] = (mat->matrix[2][0]+ mat->matrix[0][2] ) / s; - quat[1] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; + s = sqrt(1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1]) * 2; + quat[0] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[1] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; quat[2] = 0.25 * s; - quat[3] = (mat->matrix[0][1] - mat->matrix[1][0] ) / s; + quat[3] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; } } } -void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) -{ - const float xx = quat[0] * quat[0]; - const float xy = quat[0] * quat[1]; - const float xz = quat[0] * quat[2]; - const float xw = quat[0] * quat[3]; +void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) { + const float xx = quat[0] * quat[0]; + const float xy = quat[0] * quat[1]; + const float xz = quat[0] * quat[2]; + const float xw = quat[0] * quat[3]; - const float yy = quat[1] * quat[1]; - const float yz = quat[1] * quat[2]; - const float yw = quat[1] * quat[3]; + const float yy = quat[1] * quat[1]; + const float yz = quat[1] * quat[2]; + const float yw = quat[1] * quat[3]; - const float zz = quat[2] * quat[2]; - const float zw = quat[2] * quat[3]; + const float zz = quat[2] * quat[2]; + const float zw = quat[2] * quat[3]; - mat->matrix[0][0] = 1 - 2 * ( yy + zz ); - mat->matrix[1][0] = 2 * ( xy - zw ); - mat->matrix[2][0] = 2 * ( xz + yw ); + mat->matrix[0][0] = 1 - 2 * (yy + zz); + mat->matrix[1][0] = 2 * (xy - zw); + mat->matrix[2][0] = 2 * (xz + yw); - mat->matrix[0][1] = 2 * ( xy + zw ); - mat->matrix[1][1] = 1 - 2 * ( xx + zz ); - mat->matrix[2][1] = 2 * ( yz - xw ); + mat->matrix[0][1] = 2 * (xy + zw); + mat->matrix[1][1] = 1 - 2 * (xx + zz); + mat->matrix[2][1] = 2 * (yz - xw); - mat->matrix[0][2] = 2 * ( xz - yw ); - mat->matrix[1][2] = 2 * ( yz + xw ); - mat->matrix[2][2] = 1 - 2 * ( xx + yy ); + mat->matrix[0][2] = 2 * (xz - yw); + mat->matrix[1][2] = 2 * (yz + xw); + mat->matrix[2][2] = 1 - 2 * (xx + yy); - mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; + mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; } -static int G2_GetBonePoolIndex( const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) -{ +static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) { const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); - mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte*)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); + mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); return (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); } -/*static inline*/ void UnCompressBone( - float mat[3][4], - int iBoneIndex, - const mdxaHeader_t *pMDXAHeader, - int iFrame) -{ - mdxaCompQuatBone_t *pCompBonePool = - (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); - MC_UnCompressQuat( - mat, - pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); +/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) { + mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); + MC_UnCompressQuat(mat, pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); } #define DEBUG_G2_TIMING (0) #define DEBUG_G2_TIMING_RENDER_ONLY (1) -void G2_TimingModel( - boneInfo_t &bone, - int currentTime, - int numFramesInFile, - int ¤tFrame, - int &newFrame, - float& lerp) -{ +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp) { assert(bone.startFrame >= 0); assert(bone.startFrame <= numFramesInFile); assert(bone.endFrame >= 0); @@ -1145,12 +904,9 @@ void G2_TimingModel( // yes - add in animation speed to current frame const float animSpeed = bone.animSpeed; float time; - if (bone.pauseTime) - { + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (currentTime - bone.startTime) / 50.0f; } @@ -1161,24 +917,18 @@ void G2_TimingModel( const float endFrame = (float)bone.endFrame; // we are supposed to be animating right? - if ( numFramesInAnim != 0 ) - { + if (numFramesInAnim != 0) { // did we run off the end? - if ( (animSpeed > 0.0f && newLerpFrame > (endFrame - 1)) || - (animSpeed < 0.0f && newLerpFrame < (endFrame + 1)) ) - { + if ((animSpeed > 0.0f && newLerpFrame > (endFrame - 1)) || (animSpeed < 0.0f && newLerpFrame < (endFrame + 1))) { // yep - decide what to do - if ( bone.flags & BONE_ANIM_OVERRIDE_LOOP ) - { + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if ( animSpeed < 0.0f ) - { + if (animSpeed < 0.0f) { // we don't use this case, or so I am told // if we do, let me know, I need to insure the mod works // should we be creating a virtual frame? - if ( (newLerpFrame < (endFrame + 1)) && (newLerpFrame >= endFrame) ) - { + if ((newLerpFrame < (endFrame + 1)) && (newLerpFrame >= endFrame)) { // now figure out what we are lerping between delta is // the fraction between this frame and the next, since // the new anim is always at a .0f; @@ -1187,14 +937,9 @@ void G2_TimingModel( // frames are easy to calculate currentFrame = endFrame; newFrame = bone.startFrame; - } - else - { - if ( newLerpFrame <= (endFrame + 1) ) - { - newLerpFrame = - endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - - numFramesInAnim; + } else { + if (newLerpFrame <= (endFrame + 1)) { + newLerpFrame = endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - numFramesInAnim; } // now figure out what we are lerping between delta is @@ -1206,21 +951,15 @@ void G2_TimingModel( currentFrame = ceil(newLerpFrame); // should we be creating a virtual frame? - if ( currentFrame <= (endFrame + 1) ) - { + if (currentFrame <= (endFrame + 1)) { newFrame = bone.startFrame; - } - else - { + } else { newFrame = currentFrame - 1; } } - } - else - { + } else { // should we be creating a virtual frame? - if ( (newLerpFrame > (endFrame - 1)) && (newLerpFrame < endFrame)) - { + if ((newLerpFrame > (endFrame - 1)) && (newLerpFrame < endFrame)) { // now figure out what we are lerping between delta is // the fraction between this frame and the next, since // the new anim is always at a .0f; @@ -1229,14 +968,9 @@ void G2_TimingModel( // frames are easy to calculate currentFrame = (int)newLerpFrame; newFrame = bone.startFrame; - } - else - { - if ( newLerpFrame >= endFrame ) - { - newLerpFrame = - endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - - numFramesInAnim; + } else { + if (newLerpFrame >= endFrame) { + newLerpFrame = endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - numFramesInAnim; } // now figure out what we are lerping between delta is @@ -1248,44 +982,30 @@ void G2_TimingModel( currentFrame = (int)newLerpFrame; // should we be creating a virtual frame? - if ( newLerpFrame >= (endFrame - 1) ) - { + if (newLerpFrame >= (endFrame - 1)) { newFrame = bone.startFrame; - } - else - { + } else { newFrame = currentFrame + 1; } } } - } - else - { - if ( ((bone.flags & BONE_ANIM_OVERRIDE_FREEZE) == BONE_ANIM_OVERRIDE_FREEZE) ) - { + } else { + if (((bone.flags & BONE_ANIM_OVERRIDE_FREEZE) == BONE_ANIM_OVERRIDE_FREEZE)) { // if we are supposed to reset the default anim, then do so - if ( animSpeed > 0.0f ) - { + if (animSpeed > 0.0f) { currentFrame = bone.endFrame - 1; - } - else - { + } else { currentFrame = bone.endFrame + 1; } newFrame = currentFrame; lerp = 0.0f; - } - else - { + } else { bone.flags &= ~BONE_ANIM_TOTAL; } } - } - else - { - if (animSpeed> 0.0) - { + } else { + if (animSpeed > 0.0) { // frames are easy to calculate currentFrame = (int)newLerpFrame; @@ -1294,72 +1014,55 @@ void G2_TimingModel( // want to display lerp = (newLerpFrame - currentFrame); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame + 1; // are we now on the end frame? - assert((int)endFrame<=numFramesInFile); - if (newFrame >= (int)endFrame) - { + assert((int)endFrame <= numFramesInFile); + if (newFrame >= (int)endFrame) { // we only want to lerp with the first frame of the anim if - // we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - } - else - { + // we are looping + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { + newFrame = bone.startFrame; + } else { // if we intend to end this anim or freeze after this, then // just keep on the last frame - newFrame = bone.endFrame-1; + newFrame = bone.endFrame - 1; } } - } - else - { - lerp = (ceil(newLerpFrame)-newLerpFrame); + } else { + lerp = (ceil(newLerpFrame) - newLerpFrame); // frames are easy to calculate currentFrame = ceil(newLerpFrame); - if (currentFrame>bone.startFrame) - { - currentFrame=bone.startFrame; + if (currentFrame > bone.startFrame) { + currentFrame = bone.startFrame; newFrame = currentFrame; lerp = 0.0f; - } - else - { - newFrame = currentFrame-1; + } else { + newFrame = currentFrame - 1; // are we now on the end frame? - if (newFrame < endFrame+1) - { + if (newFrame < endFrame + 1) { // we only want to lerp with the first frame of the - // anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; + // anim if we are looping + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { + newFrame = bone.startFrame; } // if we intend to end this anim or freeze after this, // then just keep on the last frame - else - { - newFrame = bone.endFrame+1; + else { + newFrame = bone.endFrame + 1; } } } } } - } - else - { - if ( animSpeed < 0.0 ) - { + } else { + if (animSpeed < 0.0) { currentFrame = bone.endFrame + 1; - } - else - { + } else { currentFrame = bone.endFrame - 1; } @@ -1383,12 +1086,7 @@ void G2_RagPrintMatrix(mdxaBone_t *mat); int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); -void G2_RagGetAnimMatrix( - CGhoul2Info &ghoul2, - const int boneNum, - mdxaBone_t &matrix, - const int frame) -{ +void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame) { mdxaBone_t animMatrix; mdxaSkel_t *skel; mdxaSkel_t *pskel; @@ -1406,16 +1104,12 @@ void G2_RagGetAnimMatrix( offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); - //find/add the bone in the list - if (!skel->name[0]) - { + // find/add the bone in the list + if (!skel->name[0]) { bListIndex = -1; - } - else - { + } else { bListIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); - if (bListIndex == -1) - { + if (bListIndex == -1) { #ifdef _RAG_PRINT_TEST Com_Printf("Attempting to add %s\n", skel->name); #endif @@ -1427,18 +1121,16 @@ void G2_RagGetAnimMatrix( boneInfo_t &bone = ghoul2.mBlist[bListIndex]; - if (bone.hasAnimFrameMatrix == frame) - { //already calculated so just grab it + if (bone.hasAnimFrameMatrix == frame) { // already calculated so just grab it matrix = bone.animFrameMatrix; return; } - //get the base matrix for the specified frame + // get the base matrix for the specified frame UnCompressBone(animMatrix.matrix, boneNum, ghoul2.mBoneCache->header, frame); parent = skel->parent; - if (boneNum > 0 && parent > -1) - { + if (boneNum > 0 && parent > -1) { // recursively call to assure all parent matrices are set up G2_RagGetAnimMatrix(ghoul2, parent, matrix, frame); @@ -1447,15 +1139,11 @@ void G2_RagGetAnimMatrix( // taking bone matrix for the skeleton frame and parent's // animFrameMatrix into account, determine our final animFrameMatrix - if (!pskel->name[0]) - { + if (!pskel->name[0]) { parentBlistIndex = -1; - } - else - { + } else { parentBlistIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); - if (parentBlistIndex == -1) - { + if (parentBlistIndex == -1) { parentBlistIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); } } @@ -1465,43 +1153,34 @@ void G2_RagGetAnimMatrix( boneInfo_t &pbone = ghoul2.mBlist[parentBlistIndex]; // this should have been calc'd in the recursive call - assert(pbone.hasAnimFrameMatrix == frame); + assert(pbone.hasAnimFrameMatrix == frame); Mat3x4_Multiply(&bone.animFrameMatrix, &pbone.animFrameMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (parentBlistIndex != -1 && bListIndex != -1) - { + if (parentBlistIndex != -1 && bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); } #endif - } - else - { + } else { // root Mat3x4_Multiply(&bone.animFrameMatrix, &ghoul2.mBoneCache->rootMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (bListIndex != -1) - { + if (bListIndex != -1) { actuallySet = true; - } - else - { + } else { Com_Printf("BAD LIST INDEX: %s\n", skel->name); } #endif } - //never need to figure it out again + // never need to figure it out again bone.hasAnimFrameMatrix = frame; #ifdef _RAG_PRINT_TEST - if (!actuallySet) - { + if (!actuallySet) { Com_Printf("SET FAILURE\n"); G2_RagPrintMatrix(&bone.animFrameMatrix); } @@ -1510,52 +1189,43 @@ void G2_RagGetAnimMatrix( matrix = bone.animFrameMatrix; } -static void G2_TransformBone( int child, CBoneCache& BC ) -{ +static void G2_TransformBone(int child, CBoneCache &BC) { SBoneCalc &TB = BC.mBones[child]; mdxaBone_t currentBone; - boneInfo_v& boneList = *BC.rootBoneList; + boneInfo_v &boneList = *BC.rootBoneList; int angleOverride = 0; #if DEBUG_G2_TIMING - bool printTiming=false; + bool printTiming = false; #endif // should this bone be overridden by a bone in the bone list? int boneListIndex = G2_Find_Bone_In_List(boneList, child); - if (boneListIndex != -1) - { + if (boneListIndex != -1) { // we found a bone in the list - we need to override something here. - boneInfo_t& bone = boneList[boneListIndex]; + boneInfo_t &bone = boneList[boneListIndex]; int boneFlags = bone.flags; - + // do we override the rotational angles? - if ( boneFlags & BONE_ANGLES_TOTAL ) - { + if (boneFlags & BONE_ANGLES_TOTAL) { angleOverride = boneFlags & BONE_ANGLES_TOTAL; } // set blending stuff if we need to - if ( boneFlags & BONE_ANIM_BLEND ) - { + if (boneFlags & BONE_ANIM_BLEND) { const float blendTime = BC.incomingTime - bone.blendStart; // only set up the blend anim if we actually have some blend time // left on this bone anim - otherwise we might corrupt some blend // higher up the hiearchy - if ( blendTime >= 0.0f && blendTime < bone.blendTime ) - { + if (blendTime >= 0.0f && blendTime < bone.blendTime) { TB.blendFrame = bone.blendFrame; TB.blendOldFrame = bone.blendLerpFrame; TB.blendLerp = (blendTime / bone.blendTime); TB.blendMode = true; - } - else - { + } else { TB.blendMode = false; } - } - else if ( boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE) ) - { + } else if (boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { // turn off blending if we are just doing a straing animation // override TB.blendMode = false; @@ -1563,139 +1233,84 @@ static void G2_TransformBone( int child, CBoneCache& BC ) // should this animation be overridden by an animation in the bone // list? - if (boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - G2_TimingModel( - bone, - BC.incomingTime, - BC.header->numFrames, - TB.currentFrame, - TB.newFrame, - TB.backlerp); + if (boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + G2_TimingModel(bone, BC.incomingTime, BC.header->numFrames, TB.currentFrame, TB.newFrame, TB.backlerp); } #if DEBUG_G2_TIMING - printTiming=true; + printTiming = true; #endif } // figure out where the location of the bone animation data is - if ( !(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames) ) - { + if (!(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames)) { TB.newFrame = 0; } - if ( !(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames) ) - { + if (!(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames)) { TB.currentFrame = 0; } // figure out where the location of the blended animation data is - if ( TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1) ) - { + if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1)) { TB.blendFrame = 0.0; } - if ( !(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames) ) - { + if (!(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames)) { TB.blendOldFrame = 0; } #if DEBUG_G2_TIMING #if DEBUG_G2_TIMING_RENDER_ONLY - if (!HackadelicOnClient) - { + if (!HackadelicOnClient) { printTiming = false; } #endif - if (printTiming) - { + if (printTiming) { char mess[1000]; - if (TB.blendMode) - { - sprintf( - mess, - "b %2d %5d %4d %4d %4d %4d %f %f\n", - boneListIndex, - BC.incomingTime, - (int)TB.newFrame, - (int)TB.currentFrame, - (int)TB.blendFrame, - (int)TB.blendOldFrame, - TB.backlerp, - TB.blendLerp); - } - else - { - sprintf( - mess, - "a %2d %5d %4d %4d %f\n", - boneListIndex, - BC.incomingTime, - TB.newFrame, - TB.currentFrame, - TB.backlerp); + if (TB.blendMode) { + sprintf(mess, "b %2d %5d %4d %4d %4d %4d %f %f\n", boneListIndex, BC.incomingTime, (int)TB.newFrame, (int)TB.currentFrame, (int)TB.blendFrame, + (int)TB.blendOldFrame, TB.backlerp, TB.blendLerp); + } else { + sprintf(mess, "a %2d %5d %4d %4d %f\n", boneListIndex, BC.incomingTime, TB.newFrame, TB.currentFrame, TB.backlerp); } - Com_OPrintf("%s",mess); + Com_OPrintf("%s", mess); - const boneInfo_t &bone=boneList[boneListIndex]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf( - mess, - " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame); - } - else - { - sprintf(mess," bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags); + const boneInfo_t &bone = boneList[boneListIndex]; + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, + " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + boneListIndex, BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, + bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, " bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", boneListIndex, + BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags); } } #endif - assert(child >=0 && child < BC.header->numBones); + assert(child >= 0 && child < BC.header->numBones); // decide where the transformed bone is going - + // lerp this bone - use the temp space on the ref entity to put the bone // transforms into - if ( !TB.backlerp ) - { + if (!TB.backlerp) { UnCompressBone(currentBone.matrix, child, BC.header, TB.currentFrame); - } - else - { + } else { mdxaBone_t newFrameBone; mdxaBone_t currentFrameBone; UnCompressBone(newFrameBone.matrix, child, BC.header, TB.newFrame); - UnCompressBone(currentFrameBone.matrix, child, BC.header, TB.currentFrame); + UnCompressBone(currentFrameBone.matrix, child, BC.header, TB.currentFrame); Mat3x4_Lerp(¤tBone, &newFrameBone, ¤tFrameBone, TB.backlerp); } // are we blending with another frame of anim? // blend in the other frame if we need to - if ( TB.blendMode ) - { + if (TB.blendMode) { mdxaBone_t blendFrameBone; mdxaBone_t blendOldFrameBone; UnCompressBone(blendFrameBone.matrix, child, BC.header, TB.blendFrame); @@ -1707,47 +1322,34 @@ static void G2_TransformBone( int child, CBoneCache& BC ) Mat3x4_Lerp(¤tBone, ¤tBone, &lerpFrameBone, TB.blendLerp); } - if ( !child ) - { + if (!child) { // now multiply by the root matrix, so we can offset this model // should we need to BC.mFinalBones[child].boneMatrix = BC.rootMatrix * currentBone; } // figure out where the bone hirearchy info is - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); - mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[child]); + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[child]); int parent = BC.mFinalBones[child].parent; assert((parent == -1 && child == 0) || (parent >= 0 && parent < (int)BC.mBones.size())); - if ( angleOverride & BONE_ANGLES_REPLACE ) - { - const bool isRag = - ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) != 0); + if (angleOverride & BONE_ANGLES_REPLACE) { + const bool isRag = ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) != 0); - mdxaBone_t& bone = BC.mFinalBones[child].boneMatrix; - const boneInfo_t& boneOverride = boneList[boneListIndex]; + mdxaBone_t &bone = BC.mFinalBones[child].boneMatrix; + const boneInfo_t &boneOverride = boneList[boneListIndex]; // give us the matrix the animation thinks we should have, so we // can get the correct X&Y coors const mdxaBone_t firstPass = BC.mFinalBones[parent].boneMatrix * currentBone; - if (isRag) - { + if (isRag) { // this is crazy, we are gonna drive the animation to ID while we // are doing post mults to compensate. mdxaBone_t temp = firstPass * skel->BasePoseMat; - const float matrixScale = VectorLength((float*)&temp); - mdxaBone_t toMatrix = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; + const float matrixScale = VectorLength((float *)&temp); + mdxaBone_t toMatrix = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; toMatrix.matrix[0][0] = matrixScale; toMatrix.matrix[1][1] = matrixScale; toMatrix.matrix[2][2] = matrixScale; @@ -1759,44 +1361,33 @@ static void G2_TransformBone( int child, CBoneCache& BC ) float blendTime = BC.incomingTime - boneOverride.boneBlendStart; float blendLerp = (blendTime / boneOverride.boneBlendTime); - if (blendLerp > 0.0f) - { + if (blendLerp > 0.0f) { // has started - if (blendLerp > 1.0f) - { + if (blendLerp > 1.0f) { bone = temp; - } - else - { + } else { Mat3x4_Lerp(&bone, &temp, ¤tBone, blendLerp); } } - } - else - { + } else { // are we attempting to blend with the base animation? and still // within blend time? - if (boneOverride.boneBlendTime > 0.0f && - (((boneOverride.boneBlendStart + boneOverride.boneBlendTime) < BC.incomingTime))) - { + if (boneOverride.boneBlendTime > 0.0f && (((boneOverride.boneBlendStart + boneOverride.boneBlendTime) < BC.incomingTime))) { // ok, we are supposed to be blending. Work out lerp const float blendTime = BC.incomingTime - boneOverride.boneBlendStart; const float blendLerp = (blendTime / boneOverride.boneBlendTime); - if (blendLerp <= 1) - { - if (blendLerp < 0) - { + if (blendLerp <= 1) { + if (blendLerp < 0) { assert(0); } // now work out the matrix we want to get *to* - firstPass // is where we are coming *from* mdxaBone_t temp = firstPass * skel->BasePoseMat; - const float matrixScale = VectorLength((const float*)&temp); + const float matrixScale = VectorLength((const float *)&temp); - const mdxaBone_t& m = - HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; + const mdxaBone_t &m = HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; mdxaBone_t newMatrixTemp; Mat3x4_Scale(&newMatrixTemp, &m, matrixScale); @@ -1804,22 +1395,17 @@ static void G2_TransformBone( int child, CBoneCache& BC ) newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - temp = newMatrixTemp * skel->BasePoseMatInv; + temp = newMatrixTemp * skel->BasePoseMatInv; Mat3x4_Lerp(&bone, &temp, &firstPass, blendLerp); - } - else - { + } else { bone = firstPass; } - } - else - { + } else { // no, so just override it directly const mdxaBone_t temp = firstPass * skel->BasePoseMat; - const float matrixScale = VectorLength((const float*)&temp); + const float matrixScale = VectorLength((const float *)&temp); - const mdxaBone_t& m = - HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; + const mdxaBone_t &m = HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; mdxaBone_t newMatrixTemp; Mat3x4_Scale(&newMatrixTemp, &m, matrixScale); @@ -1827,82 +1413,51 @@ static void G2_TransformBone( int child, CBoneCache& BC ) newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - bone = newMatrixTemp * skel->BasePoseMatInv; + bone = newMatrixTemp * skel->BasePoseMatInv; } } - } - else if (angleOverride & BONE_ANGLES_PREMULT) - { - const mdxaBone_t& boneA = - child ? BC.mFinalBones[parent].boneMatrix : BC.rootMatrix; + } else if (angleOverride & BONE_ANGLES_PREMULT) { + const mdxaBone_t &boneA = child ? BC.mFinalBones[parent].boneMatrix : BC.rootMatrix; - const mdxaBone_t& boneB = - HackadelicOnClient ? - boneList[boneListIndex].newMatrix : - boneList[boneListIndex].matrix; + const mdxaBone_t &boneB = HackadelicOnClient ? boneList[boneListIndex].newMatrix : boneList[boneListIndex].matrix; BC.mFinalBones[child].boneMatrix = boneA * boneB; - if ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) == 0) - { - BC.mFinalBones[child].boneMatrix = - BC.mFinalBones[child].boneMatrix * currentBone; + if ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) == 0) { + BC.mFinalBones[child].boneMatrix = BC.mFinalBones[child].boneMatrix * currentBone; } - } - else if (child) - { + } else if (child) { // now transform the matrix by it's parent, asumming we have a parent, and // we aren't overriding the angles absolutely - BC.mFinalBones[child].boneMatrix = - BC.mFinalBones[parent].boneMatrix * currentBone; + BC.mFinalBones[child].boneMatrix = BC.mFinalBones[parent].boneMatrix * currentBone; } // now multiply our resulting bone by an override matrix should we need to - if (angleOverride & BONE_ANGLES_POSTMULT) - { - const mdxaBone_t& postMultMatrix = - HackadelicOnClient ? - boneList[boneListIndex].newMatrix : - boneList[boneListIndex].matrix; + if (angleOverride & BONE_ANGLES_POSTMULT) { + const mdxaBone_t &postMultMatrix = HackadelicOnClient ? boneList[boneListIndex].newMatrix : boneList[boneListIndex].matrix; - BC.mFinalBones[child].boneMatrix = - BC.mFinalBones[child].boneMatrix * postMultMatrix; + BC.mFinalBones[child].boneMatrix = BC.mFinalBones[child].boneMatrix * postMultMatrix; } } -void G2_SetUpBolts( - mdxaHeader_t *header, - CGhoul2Info &ghoul2, - mdxaBone_v &bonePtr, - boltInfo_v &boltList) -{ - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); +void G2_SetUpBolts(mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, boltInfo_v &boltList) { + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); - for ( size_t i = 0; i < boltList.size(); ++i ) - { - if ( boltList[i].boneNumber == -1 ) - { + for (size_t i = 0; i < boltList.size(); ++i) { + if (boltList[i].boneNumber == -1) { continue; } // figure out where the bone hirearchy info is - mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltList[i].boneNumber]); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltList[i].boneNumber]); boltList[i].position = bonePtr[boltList[i].boneNumber].second * skel->BasePoseMat; } } -#define GHOUL2_RAG_STARTED 0x0010 -//rwwFIXMEFIXME: Move this into the stupid header or something. +#define GHOUL2_RAG_STARTED 0x0010 +// rwwFIXMEFIXME: Move this into the stupid header or something. -static void G2_TransformGhoulBones( - boneInfo_v &rootBoneList, - mdxaBone_t &rootMatrix, - CGhoul2Info &ghoul2, - int time, - bool smooth = true) -{ +static void G2_TransformGhoulBones(boneInfo_v &rootBoneList, mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time, bool smooth = true) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_TransformGhoulBones.Start(); G2PerformanceCounter_G2_TransformGhoulBones++; @@ -1914,58 +1469,42 @@ static void G2_TransformGhoulBones( assert(ghoul2.aHeader); assert(ghoul2.currentModel); assert(ghoul2.currentModel->data.glm && ghoul2.currentModel->data.glm->header); - if (!aHeader->numBones) - { + if (!aHeader->numBones) { assert(0); // this would be strange return; } - if (!ghoul2.mBoneCache) - { - ghoul2.mBoneCache=new CBoneCache(currentModel,aHeader); + if (!ghoul2.mBoneCache) { + ghoul2.mBoneCache = new CBoneCache(currentModel, aHeader); #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations += sizeof(*ghoul2.mBoneCache); #endif } - ghoul2.mBoneCache->mod=currentModel; - ghoul2.mBoneCache->header=aHeader; - assert(ghoul2.mBoneCache->mBones.size()==(unsigned)aHeader->numBones); + ghoul2.mBoneCache->mod = currentModel; + ghoul2.mBoneCache->header = aHeader; + assert(ghoul2.mBoneCache->mBones.size() == (unsigned)aHeader->numBones); - ghoul2.mBoneCache->mSmoothingActive=false; - ghoul2.mBoneCache->mUnsquash=false; + ghoul2.mBoneCache->mSmoothingActive = false; + ghoul2.mBoneCache->mUnsquash = false; // master smoothing control - if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue("dedicated")) - { + if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue("dedicated")) { ghoul2.mBoneCache->mLastTouch = ghoul2.mBoneCache->mLastLastTouch; // master smoothing control float val = r_Ghoul2AnimSmooth->value; - if (val > 0.0f && val < 1.0f) - { - if (ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) - { + if (val > 0.0f && val < 1.0f) { + if (ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) { val = 0.9f; - } - else if (ghoul2.mFlags & GHOUL2_RAG_STARTED) - { - for (size_t k = 0; k < rootBoneList.size(); k++) - { + } else if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { + for (size_t k = 0; k < rootBoneList.size(); k++) { boneInfo_t &bone = rootBoneList[k]; - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (bone.firstCollisionTime && - bone.firstCollisionTime > (time - 250) && - bone.firstCollisionTime < time) - { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (bone.firstCollisionTime && bone.firstCollisionTime > (time - 250) && bone.firstCollisionTime < time) { val = 0.9f; - } - else if (bone.airTime > time) - { + } else if (bone.airTime > time) { val = 0.2f; - } - else - { + } else { val = 0.8f; } break; @@ -1976,26 +1515,20 @@ static void G2_TransformGhoulBones( ghoul2.mBoneCache->mSmoothFactor = val; // meaningless formula ghoul2.mBoneCache->mSmoothingActive = true; - if (r_Ghoul2UnSqashAfterSmooth->integer) - { + if (r_Ghoul2UnSqashAfterSmooth->integer) { ghoul2.mBoneCache->mUnsquash = true; } } - } - else - { + } else { ghoul2.mBoneCache->mSmoothFactor = 1.0f; } ghoul2.mBoneCache->mCurrentTouch++; - if (HackadelicOnClient) - { + if (HackadelicOnClient) { ghoul2.mBoneCache->mLastLastTouch = ghoul2.mBoneCache->mCurrentTouch; ghoul2.mBoneCache->mCurrentTouchRender = ghoul2.mBoneCache->mCurrentTouch; - } - else - { + } else { ghoul2.mBoneCache->mCurrentTouchRender = 0; } @@ -2019,23 +1552,14 @@ static void G2_TransformGhoulBones( #endif } - #define MDX_TAG_ORIGIN 2 //====================================================================== // -// Surface Manipulation code - +// Surface Manipulation code // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt( - mdxaBone_v &bonePtr, - mdxmSurface_t *surface, - int boltNum, - boltInfo_v &boltList, - surfaceInfo_t *surfInfo, - model_t *mod) -{ +void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, surfaceInfo_t *surfInfo, model_t *mod) { mdxmVertex_t *v, *vert0, *vert1, *vert2; vec3_t axes[3], sides[3]; float pTri[3][3], d; @@ -2043,16 +1567,13 @@ void G2_ProcessSurfaceBolt( // now there are two types of tag surface - model ones and procedural // generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = - (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = - (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -2082,65 +1603,44 @@ void G2_ProcessSurfaceBolt( // w = vert0->weights; float fTotalWeight = 0.0f; int iNumWeights = G2_GetVertWeights(vert0); - for (k = 0; k < iNumWeights; k++) - { + for (k = 0; k < iNumWeights; k++) { int iBoneIndex = G2_GetVertBoneIndex(vert0, k); float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); - pTri[0][0] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); - pTri[0][1] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); - pTri[0][2] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + pTri[0][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } fTotalWeight = 0.0f; iNumWeights = G2_GetVertWeights(vert1); - for (k = 0; k < iNumWeights; k++) - { + for (k = 0; k < iNumWeights; k++) { int iBoneIndex = G2_GetVertBoneIndex(vert1, k); float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); - pTri[1][0] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); - pTri[1][1] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); - pTri[1][2] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + pTri[1][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } fTotalWeight = 0.0f; iNumWeights = G2_GetVertWeights(vert2); - for (k = 0; k < iNumWeights; k++) - { + for (k = 0; k < iNumWeights; k++) { int iBoneIndex = G2_GetVertBoneIndex(vert2, k); float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); - pTri[2][0] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); - pTri[2][1] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); - pTri[2][2] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + pTri[2][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } vec3_t normal; @@ -2151,15 +1651,12 @@ void G2_ProcessSurfaceBolt( float baryCentricK = 1.0 - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); // now we have the model transformed into model space, now generate an origin. - boltList[boltNum].position.matrix[0][3] = (pTri[0][0] * surfInfo->genBarycentricI) + - (pTri[1][0] * surfInfo->genBarycentricJ) + - (pTri[2][0] * baryCentricK); - boltList[boltNum].position.matrix[1][3] = (pTri[0][1] * surfInfo->genBarycentricI) + - (pTri[1][1] * surfInfo->genBarycentricJ) + - (pTri[2][1] * baryCentricK); - boltList[boltNum].position.matrix[2][3] = (pTri[0][2] * surfInfo->genBarycentricI) + - (pTri[1][2] * surfInfo->genBarycentricJ) + - (pTri[2][2] * baryCentricK); + boltList[boltNum].position.matrix[0][3] = + (pTri[0][0] * surfInfo->genBarycentricI) + (pTri[1][0] * surfInfo->genBarycentricJ) + (pTri[2][0] * baryCentricK); + boltList[boltNum].position.matrix[1][3] = + (pTri[0][1] * surfInfo->genBarycentricI) + (pTri[1][1] * surfInfo->genBarycentricJ) + (pTri[2][1] * baryCentricK); + boltList[boltNum].position.matrix[2][3] = + (pTri[0][2] * surfInfo->genBarycentricI) + (pTri[1][2] * surfInfo->genBarycentricJ) + (pTri[2][2] * baryCentricK); // generate a normal to this new triangle VectorSubtract(pTri[0], pTri[1], vec0); @@ -2196,14 +1693,12 @@ void G2_ProcessSurfaceBolt( boltList[boltNum].position.matrix[2][2] = right[2]; } // no, we are looking at a normal model tag - else - { + else { int *piBoneRefs = (int *)((byte *)surface + surface->ofsBoneReferences); // whip through and actually transform each vertex v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { // mdxmWeight_t *w; VectorClear(pTri[j]); @@ -2211,24 +1706,17 @@ void G2_ProcessSurfaceBolt( const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for (k = 0; k < iNumWeights; k++) - { + for (k = 0; k < iNumWeights; k++) { int iBoneIndex = G2_GetVertBoneIndex(v, k); float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); // bone = bonePtr + piBoneRefs[w->boneIndex]; - pTri[j][0] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); - pTri[j][1] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); - pTri[j][2] += - fBoneWeight * - (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords) + - bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + pTri[j][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } v++; @@ -2239,8 +1727,7 @@ void G2_ProcessSurfaceBolt( memset(sides, 0, sizeof(sides)); // work out actual sides of the tag triangle - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; @@ -2284,44 +1771,32 @@ void G2_ProcessSurfaceBolt( // now go through all the generated surfaces that aren't included in the model // surface hierarchy and create the correct bolt info for them -void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) -{ +void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.Start(); #endif // look through the surfaces off the end of the pre-defined model surfaces - for ( size_t i = 0, numSurfaces = ghoul2.mSlist.size(); i < numSurfaces; i++ ) - { + for (size_t i = 0, numSurfaces = ghoul2.mSlist.size(); i < numSurfaces; i++) { // only look for bolts if we are actually a generated surface, and not // just an overriden one - if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) - { + if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) { // well alrighty then. Lets see if there is a bolt that is // attempting to use it - int boltNum = G2_Find_Bolt_Surface_Num( - ghoul2.mBltlist, i, G2SURFACEFLAG_GENERATED); + int boltNum = G2_Find_Bolt_Surface_Num(ghoul2.mBltlist, i, G2SURFACEFLAG_GENERATED); - if (boltNum != -1) - { - G2_ProcessSurfaceBolt( - bonePtr, - nullptr, - boltNum, - ghoul2.mBltlist, - &ghoul2.mSlist[i], mod_t); + if (boltNum != -1) { + G2_ProcessSurfaceBolt(bonePtr, nullptr, boltNum, ghoul2.mBltlist, &ghoul2.mSlist[i], mod_t); } } } #ifdef G2_PERFORMANCE_ANALYSIS - G2Time_G2_ProcessGeneratedSurfaceBolts += - G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.End(); + G2Time_G2_ProcessGeneratedSurfaceBolts += G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.End(); #endif } -void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum ) -{ +void RenderSurfaces(CRenderSurface &RS, const trRefEntity_t *ent, int entityNum) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_RenderSurfaces.Start(); #endif @@ -2336,51 +1811,39 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum assert(RS.currentModel); assert(RS.currentModel->data.glm && RS.currentModel->data.glm->header); // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = - (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *) - ((byte *)RS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *) - ((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)RS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { - if ( RS.cust_shader ) - { + if (!offFlags) { + if (RS.cust_shader) { shader = RS.cust_shader; - } - else if ( RS.skin ) - { - int j; - + } else if (RS.skin) { + int j; + // match the surface name to something in the skin file shader = tr.defaultShader; - for ( j = 0 ; j < RS.skin->numSurfaces ; j++ ) - { + for (j = 0; j < RS.skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( RS.skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = (shader_t*)RS.skin->surfaces[j]->shader; + if (!strcmp(RS.skin->surfaces[j]->name, surfInfo->name)) { + shader = (shader_t *)RS.skin->surfaces[j]->shader; break; } } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } else { + shader = R_GetShaderByHandle(surfInfo->shaderIndex); } // Get dlightBits and Cubemap @@ -2392,101 +1855,69 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum int cubemapIndex = R_CubemapForPoint(ent->e.origin); // don't add third_person objects if not viewing through a portal - if ( !RS.personalModel ) - { + if (!RS.personalModel) { // set the surface info to point at the where the transformed bone // list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = AllocGhoul2RenderableSurface(); newSurf->vboMesh = &RS.currentModel->data.glm->vboModels[RS.lod].vboMeshes[RS.surfaceNum]; - assert (newSurf->vboMesh != NULL && RS.surfaceNum == surface->thisSurfaceIndex); + assert(newSurf->vboMesh != NULL && RS.surfaceNum == surface->thisSurfaceIndex); newSurf->surfaceData = surface; newSurf->boneCache = RS.boneCache; newSurf->dlightBits = dlightBits; // render shadows? - if (r_shadows->integer == 2 - && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) - && shader->sort == SS_OPAQUE) + if (r_shadows->integer == 2 && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) newSurf->genShadows = qtrue; - R_AddDrawSurf( - (surfaceType_t *)newSurf, - entityNum, - (shader_t *)shader, - RS.fogNum, - qfalse, - R_IsPostRenderEntity(ent), - cubemapIndex); + R_AddDrawSurf((surfaceType_t *)newSurf, entityNum, (shader_t *)shader, RS.fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex); #ifdef _G2_GORE - if ( RS.gore_set && drawGore ) - { + if (RS.gore_set && drawGore) { int curTime = G2API_GetTime(tr.refdef.time); auto range = RS.gore_set->mGoreRecords.equal_range(RS.surfaceNum); CRenderableSurface *last = newSurf; - for ( auto k = range.first; k != range.second; /* blank */ ) - { + for (auto k = range.first; k != range.second; /* blank */) { auto kcur = k; k++; R2GoreTextureCoordinates *tex = FindR2GoreRecord(kcur->second.mGoreTag); - if (!tex || // it is gone, lets get rid of it - (kcur->second.mDeleteTime && - curTime >= kcur->second.mDeleteTime)) // out of time + if (!tex || // it is gone, lets get rid of it + (kcur->second.mDeleteTime && curTime >= kcur->second.mDeleteTime)) // out of time { RS.gore_set->mGoreRecords.erase(kcur); - } - else if (tex->tex[RS.lod]) - { + } else if (tex->tex[RS.lod]) { CRenderableSurface *newSurf2 = AllocGhoul2RenderableSurface(); *newSurf2 = *newSurf; newSurf2->goreChain = 0; newSurf2->alternateTex = tex->tex[RS.lod]; newSurf2->scale = 1.0f; newSurf2->fade = 1.0f; - newSurf2->impactTime = 1.0f; // done with - int magicFactor42 = 500; // ms, impact time - if (curTime > kcur->second.mGoreGrowStartTime && - curTime < (kcur->second.mGoreGrowStartTime + magicFactor42) ) - { - newSurf2->impactTime = - float(curTime - kcur->second.mGoreGrowStartTime) / - float(magicFactor42); // linear + newSurf2->impactTime = 1.0f; // done with + int magicFactor42 = 500; // ms, impact time + if (curTime > kcur->second.mGoreGrowStartTime && curTime < (kcur->second.mGoreGrowStartTime + magicFactor42)) { + newSurf2->impactTime = float(curTime - kcur->second.mGoreGrowStartTime) / float(magicFactor42); // linear } #ifdef REND2_SP_MAYBE - if (curTime < kcur->second.mGoreGrowEndTime) - { - newSurf2->scale = Q_max( - 1.0f, - 1.0f / - ((curTime - kcur->second.mGoreGrowStartTime) * - kcur->second.mGoreGrowFactor + - kcur->second.mGoreGrowOffset)); + if (curTime < kcur->second.mGoreGrowEndTime) { + newSurf2->scale = + Q_max(1.0f, 1.0f / ((curTime - kcur->second.mGoreGrowStartTime) * kcur->second.mGoreGrowFactor + kcur->second.mGoreGrowOffset)); } #endif shader_t *gshader; - if (kcur->second.shader) - { - gshader = R_GetShaderByHandle(kcur->second.shader); - } - else - { + if (kcur->second.shader) { + gshader = R_GetShaderByHandle(kcur->second.shader); + } else { gshader = R_GetShaderByHandle(goreShader); } #ifdef REND2_SP_MAYBE // Set fade on surf. // Only if we have a fade time set, and let us fade on // rgb if we want -rww - if (kcur->second.mDeleteTime && kcur->second.mFadeTime) - { - if ( (kcur->second.mDeleteTime - curTime) < kcur->second.mFadeTime ) - { - newSurf2->fade = - (float)(kcur->second.mDeleteTime - curTime) / - kcur->second.mFadeTime; - if (kcur->second.mFadeRGB) - { + if (kcur->second.mDeleteTime && kcur->second.mFadeTime) { + if ((kcur->second.mDeleteTime - curTime) < kcur->second.mFadeTime) { + newSurf2->fade = (float)(kcur->second.mDeleteTime - curTime) / kcur->second.mFadeTime; + if (kcur->second.mFadeRGB) { // RGB fades are scaled from 2.0f to 3.0f // (simply to differentiate) newSurf2->fade = Q_max(2.01f, newSurf2->fade + 2.0f); @@ -2496,14 +1927,7 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum #endif last->goreChain = newSurf2; last = newSurf2; - R_AddDrawSurf( - (surfaceType_t *)newSurf2, - entityNum, - gshader, - RS.fogNum, - qfalse, - R_IsPostRenderEntity(ent), - cubemapIndex); + R_AddDrawSurf((surfaceType_t *)newSurf2, entityNum, gshader, RS.fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex); } } } @@ -2511,10 +1935,7 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum } // projection shadows work fine with personal models - if (r_shadows->integer == 3 - && RS.fogNum == 0 - && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) - && shader->sort == SS_OPAQUE) { + if (r_shadows->integer == 3 && RS.fogNum == 0 && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) { CRenderableSurface *newSurf = AllocGhoul2RenderableSurface(); newSurf->vboMesh = &RS.currentModel->data.glm->vboModels[RS.lod].vboMeshes[RS.surfaceNum]; @@ -2524,16 +1945,14 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum R_AddDrawSurf((surfaceType_t *)newSurf, entityNum, tr.projectionShadowShader, 0, qfalse, qfalse, 0); } } - + // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { RS.surfaceNum = surfInfo->childIndexes[i]; RenderSurfaces(RS, ent, entityNum); } @@ -2545,14 +1964,7 @@ void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum // Go through the model and deal with just the surfaces that are tagged as bolt // on points - this is for the server side skeleton construction -void ProcessModelBoltSurfaces( - int surfaceNum, - surfaceInfo_v &rootSList, - mdxaBone_v &bonePtr, - model_t *currentModel, - int lod, - boltInfo_v &boltList) -{ +void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, mdxaBone_v &bonePtr, model_t *currentModel, int lod, boltInfo_v &boltList) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_ProcessModelBoltSurfaces.Start(); #endif @@ -2560,12 +1972,9 @@ void ProcessModelBoltSurfaces( int offFlags = 0; // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = (mdxmSurface_t *) - G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *) - ((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *) - ((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); @@ -2574,34 +1983,28 @@ void ProcessModelBoltSurfaces( offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // is this surface considered a bolt surface? - if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) - { + if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) { // well alrighty then. Lets see if there is a bolt that is attempting to use it int boltNum = G2_Find_Bolt_Surface_Num(boltList, surfaceNum, 0); // yes - ok, processing time. - if (boltNum != -1) - { + if (boltNum != -1) { G2_ProcessSurfaceBolt(bonePtr, surface, boltNum, boltList, surfOverride, currentModel); } } - + // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { - ProcessModelBoltSurfaces( - surfInfo->childIndexes[i], rootSList, bonePtr, currentModel, lod, boltList); + for (i = 0; i < surfInfo->numChildren; i++) { + ProcessModelBoltSurfaces(surfInfo->childIndexes[i], rootSList, bonePtr, currentModel, lod, boltList); } #ifdef G2_PERFORMANCE_ANALYSIS @@ -2609,133 +2012,111 @@ void ProcessModelBoltSurfaces( #endif } - // build the used bone list so when doing bone transforms we can determine if we need to do it or not -void G2_ConstructUsedBoneList(CConstructBoneList &CBL) -{ - int i, j; - int offFlags = 0; +void G2_ConstructUsedBoneList(CConstructBoneList &CBL) { + int i, j; + int offFlags = 0; mdxmHeader_t *mdxm = CBL.currentModel->data.glm->header; // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); - const model_t *mod_a = R_GetModelByHandle(mdxm->animIndex); - mdxaHeader_t *mdxa = mod_a->data.gla; - const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - const mdxaSkel_t *skel, *childSkel; + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const model_t *mod_a = R_GetModelByHandle(mdxm->animIndex); + mdxaHeader_t *mdxa = mod_a->data.gla; + const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel, *childSkel; // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { - int *bonesReferenced = (int *)((byte*)surface + surface->ofsBoneReferences); + if (!(offFlags & G2SURFACEFLAG_OFF)) { + int *bonesReferenced = (int *)((byte *)surface + surface->ofsBoneReferences); // now whip through the bones this surface uses - for (i=0; inumBoneReferences;i++) - { + for (i = 0; i < surface->numBoneReferences; i++) { int iBoneIndex = bonesReferenced[i]; CBL.boneUsedList[iBoneIndex] = 1; // now go and check all the descendant bones attached to this bone and see if any have the always flag on them. If so, activate them - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); // for every child bone... - for (j=0; j< skel->numChildren; j++) - { + for (j = 0; j < skel->numChildren; j++) { // get the skel data struct for each child bone of the referenced bone - childSkel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); + childSkel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); // does it have the always on flag on? - if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) - { + if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) { // yes, make sure it's in the list of bones to be transformed. CBL.boneUsedList[skel->children[j]] = 1; } } // now we need to ensure that the parents of this bone are actually active... - // + // int iParentBone = skel->parent; - while (iParentBone != -1) - { - if (CBL.boneUsedList[iParentBone]) // no need to go higher + while (iParentBone != -1) { + if (CBL.boneUsedList[iParentBone]) // no need to go higher break; CBL.boneUsedList[iParentBone] = 1; - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iParentBone]); + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iParentBone]); iParentBone = skel->parent; } } - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { CBL.surfaceNum = surfInfo->childIndexes[i]; G2_ConstructUsedBoneList(CBL); } } - // sort all the ghoul models in this list so if they go in reference order. // This will ensure the bolt on's are attached to the right place on the // previous model, since it ensures the model being attached to is built and // rendered first. // NOTE!! This assumes at least one model will NOT have a parent. If it does - // we are screwed -static void G2_Sort_Models( - CGhoul2Info_v& ghoul2, - int *const modelList, - int modelListCapacity, - int *const modelCount ) -{ +static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int *const modelList, int modelListCapacity, int *const modelCount) { *modelCount = 0; - if ( modelListCapacity < ghoul2.size() ) - { + if (modelListCapacity < ghoul2.size()) { return; } // first walk all the possible ghoul2 models, and stuff the out array with // those with no parents - for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) - { - CGhoul2Info& g2Info = ghoul2[i]; + for (int i = 0, numModels = ghoul2.size(); i < numModels; ++i) { + CGhoul2Info &g2Info = ghoul2[i]; // have a ghoul model here? - if ( g2Info.mModelindex == -1 ) - { + if (g2Info.mModelindex == -1) { continue; } - if ( !g2Info.mValid ) - { + if (!g2Info.mValid) { continue; } // are we attached to anything? - if ( g2Info.mModelBoltLink == -1 ) - { + if (g2Info.mModelBoltLink == -1) { // no, insert us first modelList[(*modelCount)++] = i; - } + } } int startPoint = 0; @@ -2743,37 +2124,30 @@ static void G2_Sort_Models( // now, using that list of parentless models, walk the descendant tree for // each of them, inserting the descendents in the list - while ( startPoint != endPoint ) - { - for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) - { - CGhoul2Info& g2Info = ghoul2[i]; + while (startPoint != endPoint) { + for (int i = 0, numModels = ghoul2.size(); i < numModels; ++i) { + CGhoul2Info &g2Info = ghoul2[i]; // have a ghoul model here? - if ( g2Info.mModelindex == -1 ) - { + if (g2Info.mModelindex == -1) { continue; } - if ( !g2Info.mValid ) - { + if (!g2Info.mValid) { continue; } // what does this model think it's attached to? - if ( g2Info.mModelBoltLink == -1 ) - { + if (g2Info.mModelBoltLink == -1) { continue; } int boltTo = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; // is it any of the models we just added to the list? - for ( int j = startPoint; j < endPoint; ++j ) - { + for (int j = startPoint; j < endPoint; ++j) { // is this my parent model? - if ( boltTo == modelList[j] ) - { + if (boltTo == modelList[j]) { // yes, insert into list and exit now modelList[(*modelCount)++] = i; break; @@ -2787,20 +2161,18 @@ static void G2_Sort_Models( } } -void *G2_FindSurface_BC(const model_s *mod, int index, int lod) -{ +void *G2_FindSurface_BC(const model_s *mod, int index, int lod) { mdxmHeader_t *mdxm = mod->data.glm->header; assert(mod); assert(mdxm); // point at first lod list - byte *current = (byte*)((intptr_t)mdxm + (intptr_t)mdxm->ofsLODs); + byte *current = (byte *)((intptr_t)mdxm + (intptr_t)mdxm->ofsLODs); int i; - //walk the lods - assert(lod>=0&&lodnumLODs); - for (i=0; i= 0 && lod < mdxm->numLODs); + for (i = 0; i < lod; i++) { mdxmLOD_t *lodData = (mdxmLOD_t *)current; current += lodData->ofsEnd; } @@ -2810,90 +2182,63 @@ void *G2_FindSurface_BC(const model_s *mod, int index, int lod) mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; // we are now looking at the offset array - assert(index>=0&&indexnumSurfaces); + assert(index >= 0 && index < mdxm->numSurfaces); current += indexes->offsets[index]; return (void *)current; } // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt2( - CBoneCache &boneCache, - const mdxmSurface_t *surface, - int boltNum, - boltInfo_v &boltList, - const surfaceInfo_t *surfInfo, - const model_t *mod, - mdxaBone_t &retMatrix) -{ - float pTri[3][3]; +void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, + const model_t *mod, mdxaBone_t &retMatrix) { + float pTri[3][3]; // now there are two types of tag surface - model ones and procedural // generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { const int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; const int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - const mdxmSurface_t *originalSurf = - (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); - const mdxmTriangle_t *originalTriangleIndexes = - (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + const mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); + const mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); - // get the original polys indexes + // get the original polys indexes const int index0 = originalTriangleIndexes[polyNumber].indexes[0]; const int index1 = originalTriangleIndexes[polyNumber].indexes[1]; const int index2 = originalTriangleIndexes[polyNumber].indexes[2]; // decide where the original verts are - const mdxmVertex_t *surfVerts = - (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); - const mdxmVertex_t *verts[3] = { - surfVerts + index0, - surfVerts + index1, - surfVerts + index2 - }; + const mdxmVertex_t *surfVerts = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + const mdxmVertex_t *verts[3] = {surfVerts + index0, surfVerts + index1, surfVerts + index2}; // clear out the triangle verts to be - VectorClear(pTri[0]); - VectorClear(pTri[1]); - VectorClear(pTri[2]); - const int *piBoneReferences = - (int *)((byte*)originalSurf + originalSurf->ofsBoneReferences); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + const int *piBoneReferences = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); - for ( int i = 0; i < 3; ++i ) - { + for (int i = 0; i < 3; ++i) { // now go and transform just the points we need from the surface that // was hit originally const int iNumWeights = G2_GetVertWeights(verts[i]); float fTotalWeight = 0.0f; - for ( int k = 0 ; k < iNumWeights ; k++ ) - { + for (int k = 0; k < iNumWeights; k++) { const int iBoneIndex = G2_GetVertBoneIndex(verts[i], k); - const float fBoneWeight = G2_GetVertBoneWeight( - verts[i], k, fTotalWeight, iNumWeights); + const float fBoneWeight = G2_GetVertBoneWeight(verts[i], k, fTotalWeight, iNumWeights); const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); - pTri[i][0] += fBoneWeight * - (DotProduct(bone.matrix[0], verts[i]->vertCoords) + bone.matrix[0][3]); - pTri[i][1] += fBoneWeight * - (DotProduct(bone.matrix[1], verts[i]->vertCoords) + bone.matrix[1][3]); - pTri[i][2] += fBoneWeight * - (DotProduct(bone.matrix[2], verts[i]->vertCoords) + bone.matrix[2][3]); + pTri[i][0] += fBoneWeight * (DotProduct(bone.matrix[0], verts[i]->vertCoords) + bone.matrix[0][3]); + pTri[i][1] += fBoneWeight * (DotProduct(bone.matrix[1], verts[i]->vertCoords) + bone.matrix[1][3]); + pTri[i][2] += fBoneWeight * (DotProduct(bone.matrix[2], verts[i]->vertCoords) + bone.matrix[2][3]); } } - const float baryCentricK = - 1.0f - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); + const float baryCentricK = 1.0f - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); // now we have the model transformed into model space, now generate an origin. - for ( int i = 0; i < 3; ++i ) - { - retMatrix.matrix[i][3] = - (pTri[0][i] * surfInfo->genBarycentricI) + - (pTri[1][i] * surfInfo->genBarycentricJ) + - (pTri[2][i] * baryCentricK); + for (int i = 0; i < 3; ++i) { + retMatrix.matrix[i][3] = (pTri[0][i] * surfInfo->genBarycentricI) + (pTri[1][i] * surfInfo->genBarycentricJ) + (pTri[2][i] * baryCentricK); } // generate a normal to this new triangle @@ -2901,7 +2246,7 @@ void G2_ProcessSurfaceBolt2( VectorSubtract(pTri[0], pTri[1], vec0); VectorSubtract(pTri[2], pTri[1], vec1); - vec3_t normal; + vec3_t normal; CrossProduct(vec0, vec1, normal); VectorNormalize(normal); @@ -2927,7 +2272,7 @@ void G2_ProcessSurfaceBolt2( // right is always straight vec3_t right; - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector retMatrix.matrix[0][2] = right[0]; @@ -2936,68 +2281,58 @@ void G2_ProcessSurfaceBolt2( } // no, we are looking at a normal model tag - else - { - // whip through and actually transform each vertex - const mdxmVertex_t *v = - (const mdxmVertex_t *)((byte *)surface + surface->ofsVerts); - const int *piBoneReferences = - (const int*)((byte *)surface + surface->ofsBoneReferences); - for ( int j = 0; j < 3; j++ ) - { - VectorClear(pTri[j]); - - const int iNumWeights = G2_GetVertWeights( v ); + else { + // whip through and actually transform each vertex + const mdxmVertex_t *v = (const mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + const int *piBoneReferences = (const int *)((byte *)surface + surface->ofsBoneReferences); + for (int j = 0; j < 3; j++) { + VectorClear(pTri[j]); + + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( int k = 0 ; k < iNumWeights ; k++) - { + for (int k = 0; k < iNumWeights; k++) { const int iBoneIndex = G2_GetVertBoneIndex(v, k); - const float fBoneWeight = - G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + const float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); - pTri[j][0] += fBoneWeight * - (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); - pTri[j][1] += fBoneWeight * - (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); - pTri[j][2] += fBoneWeight * - (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - } - - v++; - } - - // clear out used arrays + pTri[j][0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); + } + + v++; + } + + // clear out used arrays vec3_t axes[3] = {}; vec3_t sides[3] = {}; - // work out actual sides of the tag triangle - for ( int j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; - sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; - sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; - } + // work out actual sides of the tag triangle + for (int j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } // do math trig to work out what the matrix will be from this // triangle's translated position - VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); - VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); // project shortest side so that it is exactly 90 degrees to the longer // side - float d = DotProduct(axes[0], axes[1]); - VectorMA(axes[0], -d, axes[1], axes[0]); - VectorNormalize2(axes[0], axes[0]); + float d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); - CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); - VectorNormalize2(axes[2], axes[2]); + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); // set up location in world space of the origin point in out going // matrix - retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; // copy axis to matrix - do some magic to orient minus Y to positive X // and so on so bolt on stuff is oriented correctly @@ -3015,104 +2350,66 @@ void G2_ProcessSurfaceBolt2( } } -void G2_GetBoltMatrixLow( - CGhoul2Info& ghoul2, - int boltNum, - const vec3_t scale, - mdxaBone_t& retMatrix) -{ - if ( !ghoul2.mBoneCache ) - { +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix) { + if (!ghoul2.mBoneCache) { retMatrix = identityMatrix; return; } - CBoneCache& boneCache = *ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - boltInfo_v& boltList = ghoul2.mBltlist; - if ( boltList.empty() || boltNum >= boltList.size() ) - { + boltInfo_v &boltList = ghoul2.mBltlist; + if (boltList.empty() || boltNum >= boltList.size()) { retMatrix = identityMatrix; return; } - boltInfo_t& bolt = boltList[boltNum]; + boltInfo_t &bolt = boltList[boltNum]; int boltBone = bolt.boneNumber; int boltSurface = bolt.surfaceNumber; - if ( boltBone >= 0 ) - { - mdxaSkelOffsets_t *offsets = - (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); - mdxaSkel_t *skel = - (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltBone]); + if (boltBone >= 0) { + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltBone]); - Mat3x4_Multiply( - &retMatrix, - (mdxaBone_t *)&boneCache.EvalUnsmooth(boltBone), - &skel->BasePoseMat); - } - else if ( boltSurface >= 0 ) - { + Mat3x4_Multiply(&retMatrix, (mdxaBone_t *)&boneCache.EvalUnsmooth(boltBone), &skel->BasePoseMat); + } else if (boltSurface >= 0) { const surfaceInfo_t *surfInfo = nullptr; - for ( const surfaceInfo_t& t : ghoul2.mSlist ) - { - if ( t.surface == boltSurface ) - { + for (const surfaceInfo_t &t : ghoul2.mSlist) { + if (t.surface == boltSurface) { surfInfo = &t; } } mdxmSurface_t *surface = nullptr; - if ( !surfInfo ) - { - surface = (mdxmSurface_t *)G2_FindSurface_BC( - boneCache.mod, boltSurface, 0); + if (!surfInfo) { + surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod, boltSurface, 0); } - if ( !surface && surfInfo && surfInfo->surface < 10000 ) - { - surface = (mdxmSurface_t *)G2_FindSurface_BC( - boneCache.mod, surfInfo->surface, 0); + if (!surface && surfInfo && surfInfo->surface < 10000) { + surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod, surfInfo->surface, 0); } - G2_ProcessSurfaceBolt2( - boneCache, - surface, - boltNum, - boltList, - surfInfo, - (model_t *)boneCache.mod, - retMatrix); - } - else - { - // we have a bolt without a bone or surface, not a huge problem but we - // ought to at least clear the bolt matrix + G2_ProcessSurfaceBolt2(boneCache, surface, boltNum, boltList, surfInfo, (model_t *)boneCache.mod, retMatrix); + } else { + // we have a bolt without a bone or surface, not a huge problem but we + // ought to at least clear the bolt matrix retMatrix = identityMatrix; } } -static void RootMatrix( - CGhoul2Info_v &ghoul2, - int time, - const vec3_t scale, - mdxaBone_t &retMatrix) -{ - for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) - { - if ( ghoul2[i].mModelindex == -1 || !ghoul2[i].mValid ) - { +static void RootMatrix(CGhoul2Info_v &ghoul2, int time, const vec3_t scale, mdxaBone_t &retMatrix) { + for (int i = 0, numModels = ghoul2.size(); i < numModels; ++i) { + if (ghoul2[i].mModelindex == -1 || !ghoul2[i].mValid) { continue; } - if ( ghoul2[i].mFlags & GHOUL2_NEWORIGIN ) - { + if (ghoul2[i].mFlags & GHOUL2_NEWORIGIN) { mdxaBone_t bolt; mdxaBone_t tempMatrix; - G2_ConstructGhoulSkeleton(ghoul2, time, false, scale); + G2_ConstructGhoulSkeleton(ghoul2, time, false, scale); G2_GetBoltMatrixLow(ghoul2[i], ghoul2[i].mNewOrigin, scale, bolt); tempMatrix.matrix[0][0] = 1.0f; @@ -3144,28 +2441,24 @@ R_AddGHOULSurfaces ============== */ -void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) -{ +void R_AddGhoulSurfaces(trRefEntity_t *ent, int entityNum) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_R_AddGHOULSurfaces.Start(); #endif CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->e.ghoul2); - if ( !ghoul2.IsValid() ) - { + if (!ghoul2.IsValid()) { return; } // if we don't want server ghoul2 models and this is one, or we just don't // want ghoul2 models at all, then return - if (r_noServerGhoul2->integer) - { + if (r_noServerGhoul2->integer) { return; } - if (!G2_SetupModelPointers(ghoul2)) - { + if (!G2_SetupModelPointers(ghoul2)) { return; } @@ -3174,18 +2467,14 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) // cull the entire model if merged bounding box of both frames is outside // the view frustum. int cull = R_GCullModel(ent); - if ( cull == CULL_OUT ) - { + if (cull == CULL_OUT) { return; } HackadelicOnClient = true; - // don't add third_person objects if not in a portal - qboolean personalModel = (qboolean)( - (ent->e.renderfx & RF_THIRD_PERSON) && - !(tr.viewParms.isPortal || - (tr.viewParms.flags & VPF_DEPTHSHADOW))); + // don't add third_person objects if not in a portal + qboolean personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !(tr.viewParms.isPortal || (tr.viewParms.flags & VPF_DEPTHSHADOW))); int modelList[256]; assert(ghoul2.size() < ARRAY_LEN(modelList)); @@ -3200,24 +2489,20 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) assert(modelList[255] == 548); #ifdef _G2_GORE - if ( goreShader == -1 ) - { + if (goreShader == -1) { goreShader = RE_RegisterShader("gfx/damage/burnmark1"); } #endif // walk each possible model for this entity and try rendering it out - for (int j = 0; j < modelCount; ++j ) - { - CGhoul2Info& g2Info = ghoul2[modelList[j]]; + for (int j = 0; j < modelCount; ++j) { + CGhoul2Info &g2Info = ghoul2[modelList[j]]; - if ( !g2Info.mValid ) - { + if (!g2Info.mValid) { continue; } - - if ( (g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0 ) - { + + if ((g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0) { continue; } @@ -3225,70 +2510,40 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) skin_t *skin = nullptr; shader_t *cust_shader = nullptr; - if (ent->e.customShader) - { - cust_shader = R_GetShaderByHandle(ent->e.customShader ); - } - else - { + if (ent->e.customShader) { + cust_shader = R_GetShaderByHandle(ent->e.customShader); + } else { cust_shader = nullptr; // figure out the custom skin thing - if (g2Info.mCustomSkin) - { - skin = R_GetSkinByHandle(g2Info.mCustomSkin ); - } - else if (ent->e.customSkin) - { - skin = R_GetSkinByHandle(ent->e.customSkin ); - } - else if ( g2Info.mSkin > 0 && g2Info.mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( g2Info.mSkin ); + if (g2Info.mCustomSkin) { + skin = R_GetSkinByHandle(g2Info.mCustomSkin); + } else if (ent->e.customSkin) { + skin = R_GetSkinByHandle(ent->e.customSkin); + } else if (g2Info.mSkin > 0 && g2Info.mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(g2Info.mSkin); } } - int whichLod = G2_ComputeLOD( ent, g2Info.currentModel, g2Info.mLodBias ); - G2_FindOverrideSurface(-1, g2Info.mSlist); //reset the quick surface override lookup; + int whichLod = G2_ComputeLOD(ent, g2Info.currentModel, g2Info.mLodBias); + G2_FindOverrideSurface(-1, g2Info.mSlist); // reset the quick surface override lookup; #ifdef _G2_GORE CGoreSet *gore = nullptr; - if ( g2Info.mGoreSetTag ) - { + if (g2Info.mGoreSetTag) { gore = FindGoreSet(g2Info.mGoreSetTag); - if ( !gore ) // my gore is gone, so remove it + if (!gore) // my gore is gone, so remove it { g2Info.mGoreSetTag = 0; } } - CRenderSurface RS(g2Info.mSurfaceRoot, - g2Info.mSlist, - cust_shader, - fogNum, - personalModel, - g2Info.mBoneCache, - ent->e.renderfx, - skin, - (model_t *)g2Info.currentModel, - whichLod, - g2Info.mBltlist, - nullptr, - gore); + CRenderSurface RS(g2Info.mSurfaceRoot, g2Info.mSlist, cust_shader, fogNum, personalModel, g2Info.mBoneCache, ent->e.renderfx, skin, + (model_t *)g2Info.currentModel, whichLod, g2Info.mBltlist, nullptr, gore); #else - CRenderSurface RS(g2Info.mSurfaceRoot, - g2Info.mSlist, - cust_shader, - fogNum, - personalModel, - g2Info.mBoneCache, - ent->e.renderfx, - skin, - (model_t *)g2Info.currentModel, - whichLod, - g2Info.mBltlist); + CRenderSurface RS(g2Info.mSurfaceRoot, g2Info.mSlist, cust_shader, fogNum, personalModel, g2Info.mBoneCache, ent->e.renderfx, skin, + (model_t *)g2Info.currentModel, whichLod, g2Info.mBltlist); #endif - if ( !personalModel && (RS.renderfx & RF_SHADOW_PLANE) ) - { + if (!personalModel && (RS.renderfx & RF_SHADOW_PLANE)) { RS.renderfx |= RF_NOSHADOW; } @@ -3306,22 +2561,16 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) qboolean G2API_OverrideServerWithClientData(CGhoul2Info *serverInstance); #endif -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) -{ +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum) { G2_SetupModelPointers(ghlInfo); // not sure if I still need this test, probably - if (ghlInfo->mSkelFrameNum!=frameNum|| - !ghlInfo->mBoneCache|| - ghlInfo->mBoneCache->mod!=ghlInfo->currentModel) - { + if (ghlInfo->mSkelFrameNum != frameNum || !ghlInfo->mBoneCache || ghlInfo->mBoneCache->mod != ghlInfo->currentModel) { #ifdef _G2_LISTEN_SERVER_OPT - if (ghlInfo->entityNum != ENTITYNUM_NONE && - G2API_OverrideServerWithClientData(ghlInfo)) - { //if we can manage this, then we don't have to reconstruct + if (ghlInfo->entityNum != ENTITYNUM_NONE && G2API_OverrideServerWithClientData(ghlInfo)) { // if we can manage this, then we don't have to reconstruct return false; } #endif - ghlInfo->mSkelFrameNum=frameNum; + ghlInfo->mSkelFrameNum = frameNum; return true; } return false; @@ -3334,12 +2583,7 @@ builds a complete skeleton for all ghoul models in a CGhoul2Info_v class using LOD 0 ============== */ -void G2_ConstructGhoulSkeleton( - CGhoul2Info_v &ghoul2, - const int frameNum, - bool checkForNewOrigin, - const vec3_t scale) -{ +void G2_ConstructGhoulSkeleton(CGhoul2Info_v &ghoul2, const int frameNum, bool checkForNewOrigin, const vec3_t scale) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ConstructGhoulSkeleton.Start(); #endif @@ -3350,76 +2594,57 @@ void G2_ConstructGhoulSkeleton( assert(ghoul2.size() <= ARRAY_LEN(modelList)); modelList[255] = 548; - if ( checkForNewOrigin ) - { + if (checkForNewOrigin) { RootMatrix(ghoul2, frameNum, scale, rootMatrix); - } - else - { + } else { rootMatrix = identityMatrix; } G2_Sort_Models(ghoul2, modelList, ARRAY_LEN(modelList), &modelCount); assert(modelList[255] == 548); - for ( int j = 0; j < modelCount; j++ ) - { + for (int j = 0; j < modelCount; j++) { int i = modelList[j]; - CGhoul2Info& g2Info = ghoul2[i]; + CGhoul2Info &g2Info = ghoul2[i]; - if ( !g2Info.mValid ) - { + if (!g2Info.mValid) { continue; } - if ( j && g2Info.mModelBoltLink != -1 ) - { - int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; - int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (j && g2Info.mModelBoltLink != -1) { + int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, scale, bolt); - G2_TransformGhoulBones( - g2Info.mBlist, - bolt, - g2Info, - frameNum, - checkForNewOrigin); - } - else + G2_TransformGhoulBones(g2Info.mBlist, bolt, g2Info, frameNum, checkForNewOrigin); + } else #ifdef _G2_LISTEN_SERVER_OPT - if (g2Info.entityNum == ENTITYNUM_NONE || g2Info.mSkelFrameNum != frameNum) + if (g2Info.entityNum == ENTITYNUM_NONE || g2Info.mSkelFrameNum != frameNum) #endif { - G2_TransformGhoulBones( - g2Info.mBlist, - rootMatrix, - g2Info, - frameNum, - checkForNewOrigin); + G2_TransformGhoulBones(g2Info.mBlist, rootMatrix, g2Info, frameNum, checkForNewOrigin); } } #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_ConstructGhoulSkeleton += G2PerformanceTimer_G2_ConstructGhoulSkeleton.End(); #endif -} +} -static inline float G2_GetVertBoneWeightNotSlow( const mdxmVertex_t *pVert, const int iWeightNum) -{ +static inline float G2_GetVertBoneWeightNotSlow(const mdxmVertex_t *pVert, const int iWeightNum) { float fBoneWeight; int iTemp = pVert->BoneWeightings[iWeightNum]; - iTemp|= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT+(iWeightNum*2)) ) & iG2_BONEWEIGHT_TOPBITS_AND; + iTemp |= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT + (iWeightNum * 2))) & iG2_BONEWEIGHT_TOPBITS_AND; fBoneWeight = fG2_BONEWEIGHT_RECIPROCAL_MULT * iTemp; return fBoneWeight; } -void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int currentFrameNum, gpuFrame_t *frame) -{ +void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int currentFrameNum, gpuFrame_t *frame) { if (!ent->e.ghoul2 || !G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) return; @@ -3430,13 +2655,11 @@ void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int c // if we don't want server ghoul2 models and this is one, or we just don't // want ghoul2 models at all, then return - if (r_noServerGhoul2->integer) - { + if (r_noServerGhoul2->integer) { return; } - if (!G2_SetupModelPointers(ghoul2)) - { + if (!G2_SetupModelPointers(ghoul2)) { return; } @@ -3460,31 +2683,25 @@ void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int c G2_GenerateWorldMatrix(ent->e.angles, ent->e.origin); // walk each possible model for this entity and try transforming all bones - for (int j = 0; j < modelCount; ++j) - { - CGhoul2Info& g2Info = ghoul2[modelList[j]]; + for (int j = 0; j < modelCount; ++j) { + CGhoul2Info &g2Info = ghoul2[modelList[j]]; - if (!g2Info.mValid) - { + if (!g2Info.mValid) { continue; } - if ((g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0) - { + if ((g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0) { continue; } - if (j && g2Info.mModelBoltLink != -1) - { - int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; - int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (j && g2Info.mModelBoltLink != -1) { + int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, ent->e.modelScale, bolt); G2_TransformGhoulBones(g2Info.mBlist, bolt, g2Info, currentTime); - } - else - { + } else { G2_TransformGhoulBones(g2Info.mBlist, rootMatrix, g2Info, currentTime); } @@ -3492,58 +2709,42 @@ void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int c if (bc->uboGPUFrame == currentFrameNum) return; - for (int bone = 0; bone < (int)bc->mBones.size(); bone++) - { - const mdxaBone_t& b = bc->EvalRender(bone); - Com_Memcpy( - bc->boneMatrices + bone, - &b.matrix[0][0], - sizeof(mat3x4_t)); + for (int bone = 0; bone < (int)bc->mBones.size(); bone++) { + const mdxaBone_t &b = bc->EvalRender(bone); + Com_Memcpy(bc->boneMatrices + bone, &b.matrix[0][0], sizeof(mat3x4_t)); } bc->uboOffset = -1; SkeletonBoneMatricesBlock bonesBlock = {}; - Com_Memcpy( - bonesBlock.matrices, - bc->boneMatrices, - sizeof(mat3x4_t) * bc->mBones.size()); + Com_Memcpy(bonesBlock.matrices, bc->boneMatrices, sizeof(mat3x4_t) * bc->mBones.size()); - int uboOffset = RB_AppendConstantsData( - frame, &bonesBlock, sizeof(mat3x4_t) * bc->mBones.size()); + int uboOffset = RB_AppendConstantsData(frame, &bonesBlock, sizeof(mat3x4_t) * bc->mBones.size()); bc->uboOffset = uboOffset; bc->uboGPUFrame = currentFrameNum; } } -int RB_GetBoneUboOffset(CRenderableSurface *surf) -{ +int RB_GetBoneUboOffset(CRenderableSurface *surf) { if (surf->boneCache) return surf->boneCache->uboOffset; else return -1; } -void RB_SetBoneUboOffset(CRenderableSurface *surf, int offset, int currentFrameNum) -{ +void RB_SetBoneUboOffset(CRenderableSurface *surf, int offset, int currentFrameNum) { surf->boneCache->uboOffset = offset; surf->boneCache->uboGPUFrame = currentFrameNum; } -void RB_FillBoneBlock(CRenderableSurface *surf, mat3x4_t *outMatrices) -{ - Com_Memcpy( - outMatrices, - surf->boneCache->boneMatrices, - sizeof(surf->boneCache->boneMatrices)); +void RB_FillBoneBlock(CRenderableSurface *surf, mat3x4_t *outMatrices) { + Com_Memcpy(outMatrices, surf->boneCache->boneMatrices, sizeof(surf->boneCache->boneMatrices)); } -void RB_SurfaceGhoul( CRenderableSurface *surf ) -{ +void RB_SurfaceGhoul(CRenderableSurface *surf) { mdxmVBOMesh_t *surface = surf->vboMesh; - if ( surface->vbo == NULL || surface->ibo == NULL ) - { + if (surface->vbo == NULL || surface->ibo == NULL) { return; } @@ -3554,8 +2755,7 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) int indexOffset = surface->indexOffset; #ifdef _G2_GORE - if (surf->alternateTex) - { + if (surf->alternateTex) { R_BindVBO(tr.goreVBO); R_BindIBO(tr.goreIBO); tess.externalIBO = tr.goreIBO; @@ -3568,34 +2768,25 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) #ifdef REND2_SP_MAYBE // UNTESTED CODE - if (surf->scale > 1.0f) - { + if (surf->scale > 1.0f) { tess.scale = true; tess.texCoords[tess.firstIndex][0][0] = surf->scale; } - //now check for fade overrides -rww - if (surf->fade) - { + // now check for fade overrides -rww + if (surf->fade) { static int lFade; - if (surf->fade < 1.0) - { + if (surf->fade < 1.0) { tess.fade = true; - lFade = Q_ftol(254.4f*surf->fade); - tess.svars.colors[tess.firstIndex][0] = - tess.svars.colors[tess.firstIndex][1] = - tess.svars.colors[tess.firstIndex][2] = Q_ftol(1.0f); + lFade = Q_ftol(254.4f * surf->fade); + tess.svars.colors[tess.firstIndex][0] = tess.svars.colors[tess.firstIndex][1] = tess.svars.colors[tess.firstIndex][2] = Q_ftol(1.0f); tess.svars.colors[tess.firstIndex][3] = lFade; - } - else if (surf->fade > 2.0f && surf->fade < 3.0f) - { //hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww + } else if (surf->fade > 2.0f && surf->fade < 3.0f) { // hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww tess.fade = true; - lFade = Q_ftol(254.4f*(surf->fade - 2.0f)); - if (lFade < tess.svars.colors[tess.firstIndex][0]) - { //don't set it unless the fade is less than the current r value (to avoid brightening suddenly before we start fading) - tess.svars.colors[tess.firstIndex][0] = - tess.svars.colors[tess.firstIndex][1] = - tess.svars.colors[tess.firstIndex][2] = lFade; + lFade = Q_ftol(254.4f * (surf->fade - 2.0f)); + if (lFade < tess.svars.colors[tess.firstIndex][0]) { // don't set it unless the fade is less than the current r value (to avoid brightening + // suddenly before we start fading) + tess.svars.colors[tess.firstIndex][0] = tess.svars.colors[tess.firstIndex][1] = tess.svars.colors[tess.firstIndex][2] = lFade; } tess.svars.colors[tess.firstIndex][3] = lFade; } @@ -3623,67 +2814,53 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) firstIndexOffset = BUFFER_OFFSET(indexOffset * sizeof(glIndex_t)); lastIndexOffset = BUFFER_OFFSET((indexOffset + numIndexes) * sizeof(glIndex_t)); - if (r_mergeMultidraws->integer) - { + if (r_mergeMultidraws->integer) { i = 0; - if (r_mergeMultidraws->integer == 1) - { + if (r_mergeMultidraws->integer == 1) { // lazy merge, only check the last primitive - if (tess.multiDrawPrimitives) - { + if (tess.multiDrawPrimitives) { i = tess.multiDrawPrimitives - 1; } } - for (; i < tess.multiDrawPrimitives; i++) - { - if (tess.multiDrawLastIndex[i] == firstIndexOffset) - { + for (; i < tess.multiDrawPrimitives; i++) { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) { mergeBack = i; } - if (lastIndexOffset == tess.multiDrawFirstIndex[i]) - { + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) { mergeForward = i; } } } - if (mergeBack != -1 && mergeForward == -1) - { + if (mergeBack != -1 && mergeForward == -1) { tess.multiDrawNumIndexes[mergeBack] += numIndexes; tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], minIndex); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack == -1 && mergeForward != -1) - { + } else if (mergeBack == -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeForward] += numIndexes; tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], minIndex); tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack != -1 && mergeForward != -1) - { + } else if (mergeBack != -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeBack] += numIndexes + tess.multiDrawNumIndexes[mergeForward]; tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], minIndex)); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex)); tess.multiDrawPrimitives--; - if (mergeForward != tess.multiDrawPrimitives) - { + if (mergeForward != tess.multiDrawPrimitives) { tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; } backEnd.pc.c_multidrawsMerged += 2; - } - else if (mergeBack == -1 && mergeForward == -1) - { + } else if (mergeBack == -1 && mergeForward == -1) { tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = numIndexes; tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; @@ -3701,7 +2878,7 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) glState.skeletalAnimation = qtrue; } - + /* ================= R_LoadMDXM - load a Ghoul 2 Mesh file @@ -3718,394 +2895,389 @@ Complete list of all 72 bones: */ int OldToNewRemapTable[72] = { -0,// Bone 0: "model_root": Parent: "" (index -1) -1,// Bone 1: "pelvis": Parent: "model_root" (index 0) -2,// Bone 2: "Motion": Parent: "pelvis" (index 1) -3,// Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) -4,// Bone 4: "lfemurX": Parent: "pelvis" (index 1) -5,// Bone 5: "ltibia": Parent: "pelvis" (index 1) -6,// Bone 6: "ltalus": Parent: "pelvis" (index 1) -6,// Bone 7: "ltarsal": Parent: "pelvis" (index 1) -7,// Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) -8,// Bone 9: "rfemurX": Parent: "pelvis" (index 1) -9,// Bone10: "rtibia": Parent: "pelvis" (index 1) -10,// Bone11: "rtalus": Parent: "pelvis" (index 1) -10,// Bone12: "rtarsal": Parent: "pelvis" (index 1) -11,// Bone13: "lower_lumbar": Parent: "pelvis" (index 1) -12,// Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) -13,// Bone15: "thoracic": Parent: "upper_lumbar" (index 14) -14,// Bone16: "cervical": Parent: "thoracic" (index 15) -15,// Bone17: "cranium": Parent: "cervical" (index 16) -16,// Bone18: "ceyebrow": Parent: "face_always_" (index 71) -17,// Bone19: "jaw": Parent: "face_always_" (index 71) -18,// Bone20: "lblip2": Parent: "face_always_" (index 71) -19,// Bone21: "leye": Parent: "face_always_" (index 71) -20,// Bone22: "rblip2": Parent: "face_always_" (index 71) -21,// Bone23: "ltlip2": Parent: "face_always_" (index 71) -22,// Bone24: "rtlip2": Parent: "face_always_" (index 71) -23,// Bone25: "reye": Parent: "face_always_" (index 71) -24,// Bone26: "rclavical": Parent: "thoracic" (index 15) -25,// Bone27: "rhumerus": Parent: "thoracic" (index 15) -26,// Bone28: "rhumerusX": Parent: "thoracic" (index 15) -27,// Bone29: "rradius": Parent: "thoracic" (index 15) -28,// Bone30: "rradiusX": Parent: "thoracic" (index 15) -29,// Bone31: "rhand": Parent: "thoracic" (index 15) -29,// Bone32: "mc7": Parent: "thoracic" (index 15) -34,// Bone33: "r_d5_j1": Parent: "thoracic" (index 15) -35,// Bone34: "r_d5_j2": Parent: "thoracic" (index 15) -35,// Bone35: "r_d5_j3": Parent: "thoracic" (index 15) -30,// Bone36: "r_d1_j1": Parent: "thoracic" (index 15) -31,// Bone37: "r_d1_j2": Parent: "thoracic" (index 15) -31,// Bone38: "r_d1_j3": Parent: "thoracic" (index 15) -32,// Bone39: "r_d2_j1": Parent: "thoracic" (index 15) -33,// Bone40: "r_d2_j2": Parent: "thoracic" (index 15) -33,// Bone41: "r_d2_j3": Parent: "thoracic" (index 15) -32,// Bone42: "r_d3_j1": Parent: "thoracic" (index 15) -33,// Bone43: "r_d3_j2": Parent: "thoracic" (index 15) -33,// Bone44: "r_d3_j3": Parent: "thoracic" (index 15) -34,// Bone45: "r_d4_j1": Parent: "thoracic" (index 15) -35,// Bone46: "r_d4_j2": Parent: "thoracic" (index 15) -35,// Bone47: "r_d4_j3": Parent: "thoracic" (index 15) -36,// Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) -37,// Bone49: "lclavical": Parent: "thoracic" (index 15) -38,// Bone50: "lhumerus": Parent: "thoracic" (index 15) -39,// Bone51: "lhumerusX": Parent: "thoracic" (index 15) -40,// Bone52: "lradius": Parent: "thoracic" (index 15) -41,// Bone53: "lradiusX": Parent: "thoracic" (index 15) -42,// Bone54: "lhand": Parent: "thoracic" (index 15) -42,// Bone55: "mc5": Parent: "thoracic" (index 15) -43,// Bone56: "l_d5_j1": Parent: "thoracic" (index 15) -44,// Bone57: "l_d5_j2": Parent: "thoracic" (index 15) -44,// Bone58: "l_d5_j3": Parent: "thoracic" (index 15) -43,// Bone59: "l_d4_j1": Parent: "thoracic" (index 15) -44,// Bone60: "l_d4_j2": Parent: "thoracic" (index 15) -44,// Bone61: "l_d4_j3": Parent: "thoracic" (index 15) -45,// Bone62: "l_d3_j1": Parent: "thoracic" (index 15) -46,// Bone63: "l_d3_j2": Parent: "thoracic" (index 15) -46,// Bone64: "l_d3_j3": Parent: "thoracic" (index 15) -45,// Bone65: "l_d2_j1": Parent: "thoracic" (index 15) -46,// Bone66: "l_d2_j2": Parent: "thoracic" (index 15) -46,// Bone67: "l_d2_j3": Parent: "thoracic" (index 15) -47,// Bone68: "l_d1_j1": Parent: "thoracic" (index 15) -48,// Bone69: "l_d1_j2": Parent: "thoracic" (index 15) -48,// Bone70: "l_d1_j3": Parent: "thoracic" (index 15) -52// Bone71: "face_always_": Parent: "cranium" (index 17) + 0, // Bone 0: "model_root": Parent: "" (index -1) + 1, // Bone 1: "pelvis": Parent: "model_root" (index 0) + 2, // Bone 2: "Motion": Parent: "pelvis" (index 1) + 3, // Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) + 4, // Bone 4: "lfemurX": Parent: "pelvis" (index 1) + 5, // Bone 5: "ltibia": Parent: "pelvis" (index 1) + 6, // Bone 6: "ltalus": Parent: "pelvis" (index 1) + 6, // Bone 7: "ltarsal": Parent: "pelvis" (index 1) + 7, // Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) + 8, // Bone 9: "rfemurX": Parent: "pelvis" (index 1) + 9, // Bone10: "rtibia": Parent: "pelvis" (index 1) + 10, // Bone11: "rtalus": Parent: "pelvis" (index 1) + 10, // Bone12: "rtarsal": Parent: "pelvis" (index 1) + 11, // Bone13: "lower_lumbar": Parent: "pelvis" (index 1) + 12, // Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) + 13, // Bone15: "thoracic": Parent: "upper_lumbar" (index 14) + 14, // Bone16: "cervical": Parent: "thoracic" (index 15) + 15, // Bone17: "cranium": Parent: "cervical" (index 16) + 16, // Bone18: "ceyebrow": Parent: "face_always_" (index 71) + 17, // Bone19: "jaw": Parent: "face_always_" (index 71) + 18, // Bone20: "lblip2": Parent: "face_always_" (index 71) + 19, // Bone21: "leye": Parent: "face_always_" (index 71) + 20, // Bone22: "rblip2": Parent: "face_always_" (index 71) + 21, // Bone23: "ltlip2": Parent: "face_always_" (index 71) + 22, // Bone24: "rtlip2": Parent: "face_always_" (index 71) + 23, // Bone25: "reye": Parent: "face_always_" (index 71) + 24, // Bone26: "rclavical": Parent: "thoracic" (index 15) + 25, // Bone27: "rhumerus": Parent: "thoracic" (index 15) + 26, // Bone28: "rhumerusX": Parent: "thoracic" (index 15) + 27, // Bone29: "rradius": Parent: "thoracic" (index 15) + 28, // Bone30: "rradiusX": Parent: "thoracic" (index 15) + 29, // Bone31: "rhand": Parent: "thoracic" (index 15) + 29, // Bone32: "mc7": Parent: "thoracic" (index 15) + 34, // Bone33: "r_d5_j1": Parent: "thoracic" (index 15) + 35, // Bone34: "r_d5_j2": Parent: "thoracic" (index 15) + 35, // Bone35: "r_d5_j3": Parent: "thoracic" (index 15) + 30, // Bone36: "r_d1_j1": Parent: "thoracic" (index 15) + 31, // Bone37: "r_d1_j2": Parent: "thoracic" (index 15) + 31, // Bone38: "r_d1_j3": Parent: "thoracic" (index 15) + 32, // Bone39: "r_d2_j1": Parent: "thoracic" (index 15) + 33, // Bone40: "r_d2_j2": Parent: "thoracic" (index 15) + 33, // Bone41: "r_d2_j3": Parent: "thoracic" (index 15) + 32, // Bone42: "r_d3_j1": Parent: "thoracic" (index 15) + 33, // Bone43: "r_d3_j2": Parent: "thoracic" (index 15) + 33, // Bone44: "r_d3_j3": Parent: "thoracic" (index 15) + 34, // Bone45: "r_d4_j1": Parent: "thoracic" (index 15) + 35, // Bone46: "r_d4_j2": Parent: "thoracic" (index 15) + 35, // Bone47: "r_d4_j3": Parent: "thoracic" (index 15) + 36, // Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) + 37, // Bone49: "lclavical": Parent: "thoracic" (index 15) + 38, // Bone50: "lhumerus": Parent: "thoracic" (index 15) + 39, // Bone51: "lhumerusX": Parent: "thoracic" (index 15) + 40, // Bone52: "lradius": Parent: "thoracic" (index 15) + 41, // Bone53: "lradiusX": Parent: "thoracic" (index 15) + 42, // Bone54: "lhand": Parent: "thoracic" (index 15) + 42, // Bone55: "mc5": Parent: "thoracic" (index 15) + 43, // Bone56: "l_d5_j1": Parent: "thoracic" (index 15) + 44, // Bone57: "l_d5_j2": Parent: "thoracic" (index 15) + 44, // Bone58: "l_d5_j3": Parent: "thoracic" (index 15) + 43, // Bone59: "l_d4_j1": Parent: "thoracic" (index 15) + 44, // Bone60: "l_d4_j2": Parent: "thoracic" (index 15) + 44, // Bone61: "l_d4_j3": Parent: "thoracic" (index 15) + 45, // Bone62: "l_d3_j1": Parent: "thoracic" (index 15) + 46, // Bone63: "l_d3_j2": Parent: "thoracic" (index 15) + 46, // Bone64: "l_d3_j3": Parent: "thoracic" (index 15) + 45, // Bone65: "l_d2_j1": Parent: "thoracic" (index 15) + 46, // Bone66: "l_d2_j2": Parent: "thoracic" (index 15) + 46, // Bone67: "l_d2_j3": Parent: "thoracic" (index 15) + 47, // Bone68: "l_d1_j1": Parent: "thoracic" (index 15) + 48, // Bone69: "l_d1_j2": Parent: "thoracic" (index 15) + 48, // Bone70: "l_d1_j3": Parent: "thoracic" (index 15) + 52 // Bone71: "face_always_": Parent: "cranium" (index 17) }; - /* Bone 0: "model_root": - Parent: "" (index -1) - #Kids: 1 - Child 0: (index 1), name "pelvis" + Parent: "" (index -1) + #Kids: 1 + Child 0: (index 1), name "pelvis" Bone 1: "pelvis": - Parent: "model_root" (index 0) - #Kids: 4 - Child 0: (index 2), name "Motion" - Child 1: (index 3), name "lfemurYZ" - Child 2: (index 7), name "rfemurYZ" - Child 3: (index 11), name "lower_lumbar" + Parent: "model_root" (index 0) + #Kids: 4 + Child 0: (index 2), name "Motion" + Child 1: (index 3), name "lfemurYZ" + Child 2: (index 7), name "rfemurYZ" + Child 3: (index 11), name "lower_lumbar" Bone 2: "Motion": - Parent: "pelvis" (index 1) - #Kids: 0 + Parent: "pelvis" (index 1) + #Kids: 0 Bone 3: "lfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 4), name "lfemurX" - Child 1: (index 5), name "ltibia" - Child 2: (index 49), name "ltail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 4), name "lfemurX" + Child 1: (index 5), name "ltibia" + Child 2: (index 49), name "ltail" Bone 4: "lfemurX": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 5: "ltibia": - Parent: "lfemurYZ" (index 3) - #Kids: 1 - Child 0: (index 6), name "ltalus" + Parent: "lfemurYZ" (index 3) + #Kids: 1 + Child 0: (index 6), name "ltalus" Bone 6: "ltalus": - Parent: "ltibia" (index 5) - #Kids: 0 + Parent: "ltibia" (index 5) + #Kids: 0 Bone 7: "rfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 8), name "rfemurX" - Child 1: (index 9), name "rtibia" - Child 2: (index 50), name "rtail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 8), name "rfemurX" + Child 1: (index 9), name "rtibia" + Child 2: (index 50), name "rtail" Bone 8: "rfemurX": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 9: "rtibia": - Parent: "rfemurYZ" (index 7) - #Kids: 1 - Child 0: (index 10), name "rtalus" + Parent: "rfemurYZ" (index 7) + #Kids: 1 + Child 0: (index 10), name "rtalus" Bone 10: "rtalus": - Parent: "rtibia" (index 9) - #Kids: 0 + Parent: "rtibia" (index 9) + #Kids: 0 Bone 11: "lower_lumbar": - Parent: "pelvis" (index 1) - #Kids: 1 - Child 0: (index 12), name "upper_lumbar" + Parent: "pelvis" (index 1) + #Kids: 1 + Child 0: (index 12), name "upper_lumbar" Bone 12: "upper_lumbar": - Parent: "lower_lumbar" (index 11) - #Kids: 1 - Child 0: (index 13), name "thoracic" + Parent: "lower_lumbar" (index 11) + #Kids: 1 + Child 0: (index 13), name "thoracic" Bone 13: "thoracic": - Parent: "upper_lumbar" (index 12) - #Kids: 5 - Child 0: (index 14), name "cervical" - Child 1: (index 24), name "rclavical" - Child 2: (index 25), name "rhumerus" - Child 3: (index 37), name "lclavical" - Child 4: (index 38), name "lhumerus" + Parent: "upper_lumbar" (index 12) + #Kids: 5 + Child 0: (index 14), name "cervical" + Child 1: (index 24), name "rclavical" + Child 2: (index 25), name "rhumerus" + Child 3: (index 37), name "lclavical" + Child 4: (index 38), name "lhumerus" Bone 14: "cervical": - Parent: "thoracic" (index 13) - #Kids: 1 - Child 0: (index 15), name "cranium" + Parent: "thoracic" (index 13) + #Kids: 1 + Child 0: (index 15), name "cranium" Bone 15: "cranium": - Parent: "cervical" (index 14) - #Kids: 1 - Child 0: (index 52), name "face_always_" + Parent: "cervical" (index 14) + #Kids: 1 + Child 0: (index 52), name "face_always_" Bone 16: "ceyebrow": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 17: "jaw": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 18: "lblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 19: "leye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 20: "rblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 21: "ltlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 22: "rtlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 23: "reye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 24: "rclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 25: "rhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 26), name "rhumerusX" - Child 1: (index 27), name "rradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 26), name "rhumerusX" + Child 1: (index 27), name "rradius" Bone 26: "rhumerusX": - Parent: "rhumerus" (index 25) - #Kids: 0 + Parent: "rhumerus" (index 25) + #Kids: 0 Bone 27: "rradius": - Parent: "rhumerus" (index 25) - #Kids: 9 - Child 0: (index 28), name "rradiusX" - Child 1: (index 29), name "rhand" - Child 2: (index 30), name "r_d1_j1" - Child 3: (index 31), name "r_d1_j2" - Child 4: (index 32), name "r_d2_j1" - Child 5: (index 33), name "r_d2_j2" - Child 6: (index 34), name "r_d4_j1" - Child 7: (index 35), name "r_d4_j2" - Child 8: (index 36), name "rhang_tag_bone" + Parent: "rhumerus" (index 25) + #Kids: 9 + Child 0: (index 28), name "rradiusX" + Child 1: (index 29), name "rhand" + Child 2: (index 30), name "r_d1_j1" + Child 3: (index 31), name "r_d1_j2" + Child 4: (index 32), name "r_d2_j1" + Child 5: (index 33), name "r_d2_j2" + Child 6: (index 34), name "r_d4_j1" + Child 7: (index 35), name "r_d4_j2" + Child 8: (index 36), name "rhang_tag_bone" Bone 28: "rradiusX": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 29: "rhand": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 30: "r_d1_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 31: "r_d1_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 32: "r_d2_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 33: "r_d2_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 34: "r_d4_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 35: "r_d4_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 36: "rhang_tag_bone": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 37: "lclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 38: "lhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 39), name "lhumerusX" - Child 1: (index 40), name "lradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 39), name "lhumerusX" + Child 1: (index 40), name "lradius" Bone 39: "lhumerusX": - Parent: "lhumerus" (index 38) - #Kids: 0 + Parent: "lhumerus" (index 38) + #Kids: 0 Bone 40: "lradius": - Parent: "lhumerus" (index 38) - #Kids: 9 - Child 0: (index 41), name "lradiusX" - Child 1: (index 42), name "lhand" - Child 2: (index 43), name "l_d4_j1" - Child 3: (index 44), name "l_d4_j2" - Child 4: (index 45), name "l_d2_j1" - Child 5: (index 46), name "l_d2_j2" - Child 6: (index 47), name "l_d1_j1" - Child 7: (index 48), name "l_d1_j2" - Child 8: (index 51), name "lhang_tag_bone" + Parent: "lhumerus" (index 38) + #Kids: 9 + Child 0: (index 41), name "lradiusX" + Child 1: (index 42), name "lhand" + Child 2: (index 43), name "l_d4_j1" + Child 3: (index 44), name "l_d4_j2" + Child 4: (index 45), name "l_d2_j1" + Child 5: (index 46), name "l_d2_j2" + Child 6: (index 47), name "l_d1_j1" + Child 7: (index 48), name "l_d1_j2" + Child 8: (index 51), name "lhang_tag_bone" Bone 41: "lradiusX": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 42: "lhand": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 43: "l_d4_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 44: "l_d4_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 45: "l_d2_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 46: "l_d2_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 47: "l_d1_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 48: "l_d1_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 49: "ltail": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 50: "rtail": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 51: "lhang_tag_bone": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 52: "face_always_": - Parent: "cranium" (index 15) - #Kids: 8 - Child 0: (index 16), name "ceyebrow" - Child 1: (index 17), name "jaw" - Child 2: (index 18), name "lblip2" - Child 3: (index 19), name "leye" - Child 4: (index 20), name "rblip2" - Child 5: (index 21), name "ltlip2" - Child 6: (index 22), name "rtlip2" - Child 7: (index 23), name "reye" + Parent: "cranium" (index 15) + #Kids: 8 + Child 0: (index 16), name "ceyebrow" + Child 1: (index 17), name "jaw" + Child 2: (index 18), name "lblip2" + Child 3: (index 19), name "leye" + Child 4: (index 20), name "rblip2" + Child 5: (index 21), name "ltlip2" + Child 6: (index 22), name "rtlip2" + Child 7: (index 23), name "reye" */ -qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) -{ - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - mdxmSurfHierarchy_t *surfInfo; - - pinmodel= (mdxmHeader_t *)buffer; +qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + mdxmSurfHierarchy_t *surfInfo; + + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... - // + // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXM_VERSION) { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXM_VERSION); + Com_Printf(S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); return qfalse; } - mod->type = MOD_MDXM; - mod->dataSize += size; - + mod->type = MOD_MDXM; + mod->dataSize += size; + qboolean bAlreadyFound = qfalse; - mdxm = (mdxmHeader_t*)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); - mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc (sizeof (mdxmData_t), h_low); + mdxm = (mdxmHeader_t *)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc(sizeof(mdxmData_t), h_low); mod->data.glm->header = mdxm; - //RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + // RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a // tag-morph, so we need to set the bool reference passed into this // function to true, to tell the caller NOT to do an ri.FS_Freefile @@ -4114,7 +3286,7 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); + assert(mdxm == buffer); LL(mdxm->ident); LL(mdxm->version); @@ -4124,78 +3296,67 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & LL(mdxm->ofsSurfHierarchy); LL(mdxm->ofsEnd); } - + // first up, go load in the animation file we need that has the skeletal // animation info for this model - mdxm->animIndex = RE_RegisterModel(va ("%s.gla",mdxm->animName)); + mdxm->animIndex = RE_RegisterModel(va("%s.gla", mdxm->animName)); - if (!mdxm->animIndex) - { - Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); + if (!mdxm->animIndex) { + Com_Printf(S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } bool isAnOldModelFile = false; - if (mdxm->numBones == 72 && strstr(mdxm->animName,"_humanoid") ) - { + if (mdxm->numBones == 72 && strstr(mdxm->animName, "_humanoid")) { isAnOldModelFile = true; } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->numChildren); LL(surfInfo->parentIndex); - Q_strlwr(surfInfo->name); //just in case - if ( !strcmp( &surfInfo->name[strlen(surfInfo->name)-4],"_off") ) - { - surfInfo->name[strlen(surfInfo->name)-4]=0; //remove "_off" from name + Q_strlwr(surfInfo->name); // just in case + if (!strcmp(&surfInfo->name[strlen(surfInfo->name) - 4], "_off")) { + surfInfo->name[strlen(surfInfo->name) - 4] = 0; // remove "_off" from name } // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } - shader_t *sh; + shader_t *sh; // get the shader name - sh = R_FindShader( surfInfo->shader, lightmapsNone, stylesDefault, qtrue ); + sh = R_FindShader(surfInfo->shader, lightmapsNone, stylesDefault, qtrue); // insert it in the surface list - if ( sh->defaultShader ) - { + if (sh->defaultShader) { surfInfo->shaderIndex = 0; - } - else - { + } else { surfInfo->shaderIndex = sh->index; } - CModelCache->StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); + CModelCache->StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); // find the next surface surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + offsetof(mdxmSurfHierarchy_t, childIndexes) + sizeof(int) * surfInfo->numChildren); } - + // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->numTriangles); LL(surf->ofsTriangles); LL(surf->numVerts); @@ -4204,59 +3365,43 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & LL(surf->ofsHeader); LL(surf->numBoneReferences); LL(surf->ofsBoneReferences); -// LL(surf->maxVertBoneWeights); + // LL(surf->maxVertBoneWeights); triCount += surf->numTriangles; - - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error( - ERR_DROP, - "R_LoadMDXM: %s has more than %i verts on a surface (%i)", - mod_name, - SHADER_MAX_VERTEXES, - surf->numVerts); + + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error( - ERR_DROP, - "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", - mod_name, - SHADER_MAX_INDEXES / 3, - surf->numTriangles); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } - + // change to surface identifier surf->ident = SF_MDX; // register the shaders - if (isAnOldModelFile) - { - int *boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { - if (boneRef[j] >= 0 && boneRef[j] < 72) - { - boneRef[j]=OldToNewRemapTable[boneRef[j]]; - } - else - { - boneRef[j]=0; + if (isAnOldModelFile) { + int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { + if (boneRef[j] >= 0 && boneRef[j] < 72) { + boneRef[j] = OldToNewRemapTable[boneRef[j]]; + } else { + boneRef[j] = 0; } } } // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } // Make a copy on the GPU lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); - mod->data.glm->vboModels = (mdxmVBOModel_t *)ri.Hunk_Alloc (sizeof (mdxmVBOModel_t) * mdxm->numLODs, h_low); - for ( l = 0; l < mdxm->numLODs; l++ ) - { + mod->data.glm->vboModels = (mdxmVBOModel_t *)ri.Hunk_Alloc(sizeof(mdxmVBOModel_t) * mdxm->numLODs, h_low); + for (l = 0; l < mdxm->numLODs; l++) { mdxmVBOModel_t *vboModel = &mod->data.glm->vboModels[l]; mdxmVBOMesh_t *vboMeshes; @@ -4275,18 +3420,17 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & int numTriangles = 0; // +1 to add total vertex count - int *baseVertexes = (int *)ri.Hunk_AllocateTempMemory (sizeof (int) * (mdxm->numSurfaces + 1)); - int *indexOffsets = (int *)ri.Hunk_AllocateTempMemory (sizeof (int) * mdxm->numSurfaces); + int *baseVertexes = (int *)ri.Hunk_AllocateTempMemory(sizeof(int) * (mdxm->numSurfaces + 1)); + int *indexOffsets = (int *)ri.Hunk_AllocateTempMemory(sizeof(int) * mdxm->numSurfaces); vboModel->numVBOMeshes = mdxm->numSurfaces; - vboModel->vboMeshes = (mdxmVBOMesh_t *)ri.Hunk_Alloc (sizeof (mdxmVBOMesh_t) * mdxm->numSurfaces, h_low); + vboModel->vboMeshes = (mdxmVBOMesh_t *)ri.Hunk_Alloc(sizeof(mdxmVBOMesh_t) * mdxm->numSurfaces, h_low); vboMeshes = vboModel->vboMeshes; - surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); // Calculate the required size of the vertex buffer. - for ( int n = 0; n < mdxm->numSurfaces; n++ ) - { + for (int n = 0; n < mdxm->numSurfaces; n++) { baseVertexes[n] = numVerts; indexOffsets[n] = numTriangles * 3; @@ -4298,39 +3442,39 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & baseVertexes[mdxm->numSurfaces] = numVerts; - dataSize += numVerts * sizeof (*verts); - dataSize += numVerts * sizeof (*normals); - dataSize += numVerts * sizeof (*texcoords); - dataSize += numVerts * sizeof (*weights) * 4; - dataSize += numVerts * sizeof (*bonerefs) * 4; - dataSize += numVerts * sizeof (*tangents); + dataSize += numVerts * sizeof(*verts); + dataSize += numVerts * sizeof(*normals); + dataSize += numVerts * sizeof(*texcoords); + dataSize += numVerts * sizeof(*weights) * 4; + dataSize += numVerts * sizeof(*bonerefs) * 4; + dataSize += numVerts * sizeof(*tangents); // Allocate and write to memory - data = (byte *)ri.Hunk_AllocateTempMemory (dataSize); + data = (byte *)ri.Hunk_AllocateTempMemory(dataSize); ofsPosition = stride; verts = (vec3_t *)(data + ofsPosition); - stride += sizeof (*verts); + stride += sizeof(*verts); ofsNormals = stride; normals = (uint32_t *)(data + ofsNormals); - stride += sizeof (*normals); + stride += sizeof(*normals); ofsTexcoords = stride; texcoords = (vec2_t *)(data + ofsTexcoords); - stride += sizeof (*texcoords); + stride += sizeof(*texcoords); ofsBoneRefs = stride; bonerefs = data + ofsBoneRefs; - stride += sizeof (*bonerefs) * 4; + stride += sizeof(*bonerefs) * 4; ofsWeights = stride; weights = data + ofsWeights; - stride += sizeof (*weights) * 4; + stride += sizeof(*weights) * 4; ofsTangents = stride; tangents = (uint32_t *)(data + ofsTangents); - stride += sizeof (*tangents); + stride += sizeof(*tangents); // Fill in the index buffer and compute tangents glIndex_t *indices = (glIndex_t *)ri.Hunk_AllocateTempMemory(sizeof(glIndex_t) * numTriangles * 3); @@ -4339,14 +3483,12 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); - for (int n = 0; n < mdxm->numSurfaces; n++) - { + for (int n = 0; n < mdxm->numSurfaces; n++) { mdxmTriangle_t *t = (mdxmTriangle_t *)((byte *)surf + surf->ofsTriangles); glIndex_t *surf_indices = (glIndex_t *)ri.Hunk_AllocateTempMemory(sizeof(glIndex_t) * surf->numTriangles * 3); glIndex_t *surf_index = surf_indices; - for (int k = 0; k < surf->numTriangles; k++, index += 3, surf_index += 3) - { + for (int k = 0; k < surf->numTriangles; k++, index += 3, surf_index += 3) { index[0] = t[k].indexes[0] + baseVertexes[n]; assert(index[0] >= 0 && index[0] < numVerts); @@ -4365,13 +3507,7 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & mdxmVertex_t *vertices = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); mdxmVertexTexCoord_t *textureCoordinates = (mdxmVertexTexCoord_t *)(vertices + surf->numVerts); - R_CalcMikkTSpaceGlmSurface( - surf->numTriangles, - vertices, - textureCoordinates, - tangentsf + baseVertexes[n], - surf_indices - ); + R_CalcMikkTSpaceGlmSurface(surf->numTriangles, vertices, textureCoordinates, tangentsf + baseVertexes[n], surf_indices); ri.Hunk_FreeTempMemory(surf_indices); @@ -4380,16 +3516,14 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & assert(index == (indices + numTriangles * 3)); - surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); - for (int n = 0; n < mdxm->numSurfaces; n++) - { + for (int n = 0; n < mdxm->numSurfaces; n++) { // Positions and normals mdxmVertex_t *v = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); - for (int k = 0; k < surf->numVerts; k++) - { + for (int k = 0; k < surf->numVerts; k++) { VectorCopy(v[k].vertCoords, *verts); *normals = R_VboPackNormal(v[k].normal); @@ -4398,13 +3532,11 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & } // Weights - for (int k = 0; k < surf->numVerts; k++) - { + for (int k = 0; k < surf->numVerts; k++) { int numWeights = G2_GetVertWeights(&v[k]); int lastWeight = 255; int lastInfluence = numWeights - 1; - for (int w = 0; w < lastInfluence; w++) - { + for (int w = 0; w < lastInfluence; w++) { float weight = G2_GetVertBoneWeightNotSlow(&v[k], w); weights[w] = (byte)(weight * 255.0f); int packedIndex = G2_GetVertBoneIndex(&v[k], w); @@ -4421,8 +3553,7 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & bonerefs[lastInfluence] = boneRef[packedIndex]; // Fill in the rest of the info with zeroes. - for (int w = numWeights; w < 4; w++) - { + for (int w = numWeights; w < 4; w++) { weights[w] = 0; bonerefs[w] = 0; } @@ -4433,16 +3564,14 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & // Texture coordinates mdxmVertexTexCoord_t *tc = (mdxmVertexTexCoord_t *)(v + surf->numVerts); - for (int k = 0; k < surf->numVerts; k++) - { + for (int k = 0; k < surf->numVerts; k++) { (*texcoords)[0] = tc[k].texCoords[0]; (*texcoords)[1] = tc[k].texCoords[1]; texcoords = (vec2_t *)((byte *)texcoords + stride); } - for (int k = 0; k < surf->numVerts; k++) - { + for (int k = 0; k < surf->numVerts; k++) { *tangents = *(tangentsf + baseVertexes[n] + k); tangents = (uint32_t *)((byte *)tangents + stride); } @@ -4450,19 +3579,18 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } - assert ((byte *)verts == (data + dataSize)); + assert((byte *)verts == (data + dataSize)); - const char *modelName = strrchr (mdxm->name, '/'); - if (modelName == NULL) - { + const char *modelName = strrchr(mdxm->name, '/'); + if (modelName == NULL) { modelName = mdxm->name; } - VBO_t *vbo = R_CreateVBO (data, dataSize, VBO_USAGE_STATIC); + VBO_t *vbo = R_CreateVBO(data, dataSize, VBO_USAGE_STATIC); IBO_t *ibo = R_CreateIBO((byte *)indices, sizeof(glIndex_t) * numTriangles * 3, VBO_USAGE_STATIC); - ri.Hunk_FreeTempMemory (data); - ri.Hunk_FreeTempMemory (tangentsf); - ri.Hunk_FreeTempMemory (indices); + ri.Hunk_FreeTempMemory(data); + ri.Hunk_FreeTempMemory(tangentsf); + ri.Hunk_FreeTempMemory(indices); vbo->offsets[ATTR_INDEX_POSITION] = ofsPosition; vbo->offsets[ATTR_INDEX_NORMAL] = ofsNormals; @@ -4485,10 +3613,9 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & vbo->sizes[ATTR_INDEX_BONE_INDEXES] = sizeof(*bonerefs); vbo->sizes[ATTR_INDEX_TANGENT] = sizeof(*tangents); - surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); - for ( int n = 0; n < mdxm->numSurfaces; n++ ) - { + for (int n = 0; n < mdxm->numSurfaces; n++) { vboMeshes[n].vbo = vbo; vboMeshes[n].ibo = ibo; @@ -4504,8 +3631,8 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & vboModel->vbo = vbo; vboModel->ibo = ibo; - ri.Hunk_FreeTempMemory (indexOffsets); - ri.Hunk_FreeTempMemory (baseVertexes); + ri.Hunk_FreeTempMemory(indexOffsets); + ri.Hunk_FreeTempMemory(baseVertexes); lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } @@ -4517,52 +3644,24 @@ qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean & #ifdef CREATE_LIMB_HIERARCHY -#define NUM_ROOTPARENTS 4 -#define NUM_OTHERPARENTS 12 -#define NUM_BOTTOMBONES 4 +#define NUM_ROOTPARENTS 4 +#define NUM_OTHERPARENTS 12 +#define NUM_BOTTOMBONES 4 -#define CHILD_PADDING 4 //I don't know, I guess this can be changed. +#define CHILD_PADDING 4 // I don't know, I guess this can be changed. -static const char *rootParents[NUM_ROOTPARENTS] = -{ - "rfemurYZ", - "rhumerus", - "lfemurYZ", - "lhumerus" -}; +static const char *rootParents[NUM_ROOTPARENTS] = {"rfemurYZ", "rhumerus", "lfemurYZ", "lhumerus"}; -static const char *otherParents[NUM_OTHERPARENTS] = -{ - "rhumerusX", - "rradius", - "rradiusX", - "lhumerusX", - "lradius", - "lradiusX", - "rfemurX", - "rtibia", - "rtalus", - "lfemurX", - "ltibia", - "ltalus" -}; +static const char *otherParents[NUM_OTHERPARENTS] = {"rhumerusX", "rradius", "rradiusX", "lhumerusX", "lradius", "lradiusX", + "rfemurX", "rtibia", "rtalus", "lfemurX", "ltibia", "ltalus"}; -static const char *bottomBones[NUM_BOTTOMBONES] = -{ - "rtarsal", - "rhand", - "ltarsal", - "lhand" -}; +static const char *bottomBones[NUM_BOTTOMBONES] = {"rtarsal", "rhand", "ltarsal", "lhand"}; -qboolean BoneIsRootParent(char *name) -{ +qboolean BoneIsRootParent(char *name) { int i = 0; - while (i < NUM_ROOTPARENTS) - { - if (!Q_stricmp(name, rootParents[i])) - { + while (i < NUM_ROOTPARENTS) { + if (!Q_stricmp(name, rootParents[i])) { return qtrue; } @@ -4572,14 +3671,11 @@ qboolean BoneIsRootParent(char *name) return qfalse; } -qboolean BoneIsOtherParent(char *name) -{ +qboolean BoneIsOtherParent(char *name) { int i = 0; - while (i < NUM_OTHERPARENTS) - { - if (!Q_stricmp(name, otherParents[i])) - { + while (i < NUM_OTHERPARENTS) { + if (!Q_stricmp(name, otherParents[i])) { return qtrue; } @@ -4589,14 +3685,11 @@ qboolean BoneIsOtherParent(char *name) return qfalse; } -qboolean BoneIsBottom(char *name) -{ +qboolean BoneIsBottom(char *name) { int i = 0; - while (i < NUM_BOTTOMBONES) - { - if (!Q_stricmp(name, bottomBones[i])) - { + while (i < NUM_BOTTOMBONES) { + if (!Q_stricmp(name, bottomBones[i])) { return qtrue; } @@ -4606,26 +3699,24 @@ qboolean BoneIsBottom(char *name) return qfalse; } -void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) -{ +void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) { int i = 0; - //where the next bone starts - byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex+1]); + // where the next bone starts + byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex + 1]); int size = (*endMarker - nextBone); - memmove((nextBone+CHILD_PADDING), nextBone, size); + memmove((nextBone + CHILD_PADDING), nextBone, size); memset(nextBone, 0, CHILD_PADDING); *endMarker += CHILD_PADDING; // Move the whole thing down CHILD_PADDING amount in memory, clear the new // preceding space, and increment the end pointer. - i = boneIndex+1; + i = boneIndex + 1; // Now add CHILD_PADDING amount to every offset beginning at the offset of // the bone that was moved. - while (i < mdxa->numBones) - { + while (i < mdxa->numBones) { offsets->offsets[i] += CHILD_PADDING; i++; } @@ -4637,80 +3728,48 @@ void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneInd // after that point. } -//Proper/desired hierarchy list -static const char *BoneHierarchyList[] = -{ - "lfemurYZ", - "lfemurX", - "ltibia", - "ltalus", - "ltarsal", - - "rfemurYZ", - "rfemurX", - "rtibia", - "rtalus", - "rtarsal", - - "lhumerus", - "lhumerusX", - "lradius", - "lradiusX", - "lhand", - - "rhumerus", - "rhumerusX", - "rradius", - "rradiusX", - "rhand", - - 0 -}; +// Proper/desired hierarchy list +static const char *BoneHierarchyList[] = {"lfemurYZ", "lfemurX", "ltibia", "ltalus", "ltarsal", + + "rfemurYZ", "rfemurX", "rtibia", "rtalus", "rtarsal", + + "lhumerus", "lhumerusX", "lradius", "lradiusX", "lhand", -//Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. -int BoneParentChildIndex( - mdxaHeader_t *mdxa, - mdxaSkelOffsets_t *offsets, - mdxaSkel_t *boneInfo, - qboolean child) -{ + "rhumerus", "rhumerusX", "rradius", "rradiusX", "rhand", + + 0}; + +// Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. +int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSkel_t *boneInfo, qboolean child) { int i = 0; int matchindex = -1; mdxaSkel_t *bone; const char *match = NULL; - while (BoneHierarchyList[i]) - { - if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) - { + while (BoneHierarchyList[i]) { + if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) { // we have a match, the slot above this will be our desired parent. // (or below for child) - if (child) - { - match = BoneHierarchyList[i+1]; - } - else - { - match = BoneHierarchyList[i-1]; + if (child) { + match = BoneHierarchyList[i + 1]; + } else { + match = BoneHierarchyList[i - 1]; } break; } i++; } - if (!match) - { //no good + if (!match) { // no good return -1; } i = 0; - while (i < mdxa->numBones) - { + while (i < mdxa->numBones) { bone = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (bone && !Q_stricmp(bone->name, match)) - { //this is the one + if (bone && !Q_stricmp(bone->name, match)) { // this is the one matchindex = i; break; } @@ -4720,15 +3779,14 @@ int BoneParentChildIndex( return matchindex; } -#endif //CREATE_LIMB_HIERARCHY +#endif // CREATE_LIMB_HIERARCHY /* ================= R_LoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) -{ +qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { mdxaHeader_t *pinmodel, *mdxa; int version; @@ -4753,19 +3811,13 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & version = (pinmodel->version); size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } - if (version != MDXA_VERSION) - { - Com_Printf( - S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", - mod_name, - version, - MDXA_VERSION); + if (version != MDXA_VERSION) { + Com_Printf(S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", mod_name, version, MDXA_VERSION); return qfalse; } @@ -4780,18 +3832,16 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & int childNumber = (NUM_ROOTPARENTS + NUM_OTHERPARENTS); // Allocate us some extra space so we can shift memory down. - size += (childNumber * (CHILD_PADDING * 8)); + size += (childNumber * (CHILD_PADDING * 8)); #endif // CREATE_LIMB_HIERARCHY - mdxa = (mdxaHeader_t *)CModelCache->Allocate( - size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = (mdxaHeader_t *)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); mod->data.gla = mdxa; // I should probably eliminate 'bAlreadyFound', but wtf? - assert(bAlreadyCached == bAlreadyFound); + assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { #ifdef CREATE_LIMB_HIERARCHY memcpy(mdxa, buffer, oSize); #else @@ -4814,8 +3864,7 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & } #ifdef CREATE_LIMB_HIERARCHY - if (!bAlreadyFound) - { + if (!bAlreadyFound) { mdxaSkel_t *boneParent; sizeMarker = (byte *)mdxa + mdxa->ofsEnd; @@ -4825,16 +3874,13 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & // ragdoll. mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for (i = 0; i < mdxa->numBones; i++) - { + for (i = 0; i < mdxa->numBones; i++) { boneInfo = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); - if (boneInfo) - { + if (boneInfo) { char *bname = boneInfo->name; - if (BoneIsRootParent(bname)) - { + if (BoneIsRootParent(bname)) { // These are the main parent bones. We don't want to change // their parents, but we want to give them children. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); @@ -4843,33 +3889,23 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; boneInfo->children[boneInfo->numChildren - 1] = newChild; - } - else - { + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } - } - else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) - { - if (!BoneIsBottom(bname)) - { // unless it's last in the chain it has the next bone as a child. + } else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) { + if (!BoneIsBottom(bname)) { // unless it's last in the chain it has the next bone as a child. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); - boneInfo = (mdxaSkel_t *) - ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; boneInfo->children[boneInfo->numChildren - 1] = newChild; - } - else - { + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } } @@ -4878,27 +3914,19 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & // child for whoever was parenting it. int oldParent = boneInfo->parent; - if (oldParent > -1) - { - boneParent = (mdxaSkel_t *) - ((byte *)offsets + offsets->offsets[oldParent]); - } - else - { + if (oldParent > -1) { + boneParent = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[oldParent]); + } else { boneParent = NULL; } - if (boneParent) - { + if (boneParent) { k = 0; - while (k < boneParent->numChildren) - { - if (boneParent->children[k] == i) - { // this bone is the child + while (k < boneParent->numChildren) { + if (boneParent->children[k] == i) { // this bone is the child k++; - while (k < boneParent->numChildren) - { + while (k < boneParent->numChildren) { boneParent->children[k - 1] = boneParent->children[k]; k++; } @@ -4914,12 +3942,9 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & // ownership, mark the bone's new parent. int newParent = BoneParentChildIndex(mdxa, offsets, boneInfo, qfalse); - if (newParent != -1) - { + if (newParent != -1) { boneInfo->parent = newParent; - } - else - { + } else { assert(!"Failed to find matching parent for bone in hierarchy creation"); } } @@ -4928,17 +3953,14 @@ qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean & } #endif // CREATE_LIMB_HIERARCHY - if (mdxa->numFrames < 1) - { + if (mdxa->numFrames < 1) { Com_Printf(S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { + if (bAlreadyFound) { return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } return qtrue; } - diff --git a/codemp/rd-rend2/tr_glsl.cpp b/codemp/rd-rend2/tr_glsl.cpp index 5a3201fa52..395ae8c617 100644 --- a/codemp/rd-rend2/tr_glsl.cpp +++ b/codemp/rd-rend2/tr_glsl.cpp @@ -27,144 +27,135 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA void GLSL_BindNullProgram(void); const uniformBlockInfo_t uniformBlocksInfo[UNIFORM_BLOCK_COUNT] = { - { 0, "Camera", sizeof(CameraBlock) }, - { 1, "Scene", sizeof(SceneBlock) }, - { 2, "Lights", sizeof(LightsBlock) }, - { 3, "Fogs", sizeof(FogsBlock) }, - { 4, "Entity", sizeof(EntityBlock) }, - { 5, "ShaderInstance", sizeof(ShaderInstanceBlock) }, - { 6, "Bones", sizeof(SkeletonBoneMatricesBlock) }, - { 10, "SurfaceSprite", sizeof(SurfaceSpriteBlock) }, + {0, "Camera", sizeof(CameraBlock)}, + {1, "Scene", sizeof(SceneBlock)}, + {2, "Lights", sizeof(LightsBlock)}, + {3, "Fogs", sizeof(FogsBlock)}, + {4, "Entity", sizeof(EntityBlock)}, + {5, "ShaderInstance", sizeof(ShaderInstanceBlock)}, + {6, "Bones", sizeof(SkeletonBoneMatricesBlock)}, + {10, "SurfaceSprite", sizeof(SurfaceSpriteBlock)}, }; -typedef struct uniformInfo_s -{ +typedef struct uniformInfo_s { const char *name; int type; int size; -} -uniformInfo_t; +} uniformInfo_t; // These must be in the same order as in uniform_t in tr_local.h. -static uniformInfo_t uniformsInfo[] = -{ - { "u_DiffuseMap", GLSL_INT, 1 }, - { "u_LightMap", GLSL_INT, 1 }, - { "u_NormalMap", GLSL_INT, 1 }, - { "u_DeluxeMap", GLSL_INT, 1 }, - { "u_SpecularMap", GLSL_INT, 1 }, - { "u_SSAOMap", GLSL_INT, 1 }, - - { "u_TextureMap", GLSL_INT, 1 }, - { "u_LevelsMap", GLSL_INT, 1 }, - { "u_CubeMap", GLSL_INT, 1 }, - { "u_EnvBrdfMap", GLSL_INT, 1 }, - - { "u_ScreenImageMap", GLSL_INT, 1 }, - { "u_ScreenDepthMap", GLSL_INT, 1 }, - - { "u_ShadowMap", GLSL_INT, 1 }, - { "u_ShadowMap2", GLSL_INT, 1 }, - - { "u_ShadowMvp", GLSL_MAT4x4, 1 }, - { "u_ShadowMvp2", GLSL_MAT4x4, 1 }, - { "u_ShadowMvp3", GLSL_MAT4x4, 1 }, - - { "u_EnableTextures", GLSL_VEC4, 1 }, - - { "u_DiffuseTexMatrix", GLSL_VEC4, 1 }, - { "u_DiffuseTexOffTurb", GLSL_VEC4, 1 }, - - { "u_TCGen0", GLSL_INT, 1 }, - { "u_TCGen0Vector0", GLSL_VEC3, 1 }, - { "u_TCGen0Vector1", GLSL_VEC3, 1 }, - { "u_TCGen1", GLSL_INT, 1 }, - - { "u_ColorGen", GLSL_INT, 1 }, - { "u_AlphaGen", GLSL_INT, 1 }, - { "u_Color", GLSL_VEC4, 1 }, - { "u_BaseColor", GLSL_VEC4, 1 }, - { "u_VertColor", GLSL_VEC4, 1 }, - - { "u_DlightInfo", GLSL_VEC4, 1 }, - { "u_LightForward", GLSL_VEC3, 1 }, - { "u_LightUp", GLSL_VEC3, 1 }, - { "u_LightRight", GLSL_VEC3, 1 }, - { "u_LightOrigin", GLSL_VEC4, 1 }, - { "u_ModelLightDir", GLSL_VEC3, 1 }, - { "u_LightRadius", GLSL_FLOAT, 1 }, - { "u_AmbientLight", GLSL_VEC3, 1 }, - { "u_DirectedLight", GLSL_VEC3, 1 }, - { "u_Disintegration", GLSL_VEC4, 1 }, - { "u_LightMask", GLSL_INT, 1 }, - { "u_FogIndex", GLSL_INT, 1 }, - - { "u_FogColorMask", GLSL_VEC4, 1 }, - - { "u_ModelMatrix", GLSL_MAT4x4, 1 }, - { "u_ModelViewProjectionMatrix", GLSL_MAT4x4, 1 }, - - { "u_Time", GLSL_FLOAT, 1 }, - { "u_VertexLerp" , GLSL_FLOAT, 1 }, - { "u_NormalScale", GLSL_VEC4, 1 }, - { "u_SpecularScale", GLSL_VEC4, 1 }, - { "u_ParallaxBias", GLSL_FLOAT, 1 }, - - { "u_ViewInfo", GLSL_VEC4, 1 }, - { "u_ViewOrigin", GLSL_VEC3, 1 }, - { "u_LocalViewOrigin", GLSL_VEC3, 1 }, - { "u_ViewForward", GLSL_VEC3, 1 }, - { "u_ViewLeft", GLSL_VEC3, 1 }, - { "u_ViewUp", GLSL_VEC3, 1 }, - - { "u_InvTexRes", GLSL_VEC2, 1 }, - { "u_AutoExposureMinMax", GLSL_VEC2, 1 }, - { "u_ToneMinAvgMaxLinear", GLSL_VEC3, 1 }, - - { "u_CubeMapInfo", GLSL_VEC4, 1 }, - - { "u_AlphaTestType", GLSL_INT, 1 }, - - { "u_FXVolumetricBase", GLSL_FLOAT, 1 }, - { "u_MapZExtents", GLSL_VEC2, 1 }, - { "u_ZoneOffset", GLSL_VEC2, 9 }, - { "u_EnvForce", GLSL_VEC3, 1 }, - { "u_RandomOffset", GLSL_VEC4, 1 }, - { "u_ChunkParticles", GLSL_INT, 1 }, +static uniformInfo_t uniformsInfo[] = { + {"u_DiffuseMap", GLSL_INT, 1}, + {"u_LightMap", GLSL_INT, 1}, + {"u_NormalMap", GLSL_INT, 1}, + {"u_DeluxeMap", GLSL_INT, 1}, + {"u_SpecularMap", GLSL_INT, 1}, + {"u_SSAOMap", GLSL_INT, 1}, + + {"u_TextureMap", GLSL_INT, 1}, + {"u_LevelsMap", GLSL_INT, 1}, + {"u_CubeMap", GLSL_INT, 1}, + {"u_EnvBrdfMap", GLSL_INT, 1}, + + {"u_ScreenImageMap", GLSL_INT, 1}, + {"u_ScreenDepthMap", GLSL_INT, 1}, + + {"u_ShadowMap", GLSL_INT, 1}, + {"u_ShadowMap2", GLSL_INT, 1}, + + {"u_ShadowMvp", GLSL_MAT4x4, 1}, + {"u_ShadowMvp2", GLSL_MAT4x4, 1}, + {"u_ShadowMvp3", GLSL_MAT4x4, 1}, + + {"u_EnableTextures", GLSL_VEC4, 1}, + + {"u_DiffuseTexMatrix", GLSL_VEC4, 1}, + {"u_DiffuseTexOffTurb", GLSL_VEC4, 1}, + + {"u_TCGen0", GLSL_INT, 1}, + {"u_TCGen0Vector0", GLSL_VEC3, 1}, + {"u_TCGen0Vector1", GLSL_VEC3, 1}, + {"u_TCGen1", GLSL_INT, 1}, + + {"u_ColorGen", GLSL_INT, 1}, + {"u_AlphaGen", GLSL_INT, 1}, + {"u_Color", GLSL_VEC4, 1}, + {"u_BaseColor", GLSL_VEC4, 1}, + {"u_VertColor", GLSL_VEC4, 1}, + + {"u_DlightInfo", GLSL_VEC4, 1}, + {"u_LightForward", GLSL_VEC3, 1}, + {"u_LightUp", GLSL_VEC3, 1}, + {"u_LightRight", GLSL_VEC3, 1}, + {"u_LightOrigin", GLSL_VEC4, 1}, + {"u_ModelLightDir", GLSL_VEC3, 1}, + {"u_LightRadius", GLSL_FLOAT, 1}, + {"u_AmbientLight", GLSL_VEC3, 1}, + {"u_DirectedLight", GLSL_VEC3, 1}, + {"u_Disintegration", GLSL_VEC4, 1}, + {"u_LightMask", GLSL_INT, 1}, + {"u_FogIndex", GLSL_INT, 1}, + + {"u_FogColorMask", GLSL_VEC4, 1}, + + {"u_ModelMatrix", GLSL_MAT4x4, 1}, + {"u_ModelViewProjectionMatrix", GLSL_MAT4x4, 1}, + + {"u_Time", GLSL_FLOAT, 1}, + {"u_VertexLerp", GLSL_FLOAT, 1}, + {"u_NormalScale", GLSL_VEC4, 1}, + {"u_SpecularScale", GLSL_VEC4, 1}, + {"u_ParallaxBias", GLSL_FLOAT, 1}, + + {"u_ViewInfo", GLSL_VEC4, 1}, + {"u_ViewOrigin", GLSL_VEC3, 1}, + {"u_LocalViewOrigin", GLSL_VEC3, 1}, + {"u_ViewForward", GLSL_VEC3, 1}, + {"u_ViewLeft", GLSL_VEC3, 1}, + {"u_ViewUp", GLSL_VEC3, 1}, + + {"u_InvTexRes", GLSL_VEC2, 1}, + {"u_AutoExposureMinMax", GLSL_VEC2, 1}, + {"u_ToneMinAvgMaxLinear", GLSL_VEC3, 1}, + + {"u_CubeMapInfo", GLSL_VEC4, 1}, + + {"u_AlphaTestType", GLSL_INT, 1}, + + {"u_FXVolumetricBase", GLSL_FLOAT, 1}, + {"u_MapZExtents", GLSL_VEC2, 1}, + {"u_ZoneOffset", GLSL_VEC2, 9}, + {"u_EnvForce", GLSL_VEC3, 1}, + {"u_RandomOffset", GLSL_VEC4, 1}, + {"u_ChunkParticles", GLSL_INT, 1}, }; -static void GLSL_PrintProgramInfoLog(GLuint object, qboolean developerOnly) -{ +static void GLSL_PrintProgramInfoLog(GLuint object, qboolean developerOnly) { char msgPart[1024]; int maxLength = 0; int printLevel = developerOnly ? PRINT_DEVELOPER : PRINT_ALL; qglGetProgramiv(object, GL_INFO_LOG_LENGTH, &maxLength); - if (maxLength <= 0) - { + if (maxLength <= 0) { ri.Printf(printLevel, "No compile log.\n"); return; } ri.Printf(printLevel, "compile log:\n"); - if (maxLength < 1023) - { + if (maxLength < 1023) { qglGetProgramInfoLog(object, maxLength, &maxLength, msgPart); msgPart[maxLength + 1] = '\0'; ri.Printf(printLevel, "%s\n", msgPart); - } - else - { + } else { char *msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); qglGetProgramInfoLog(object, maxLength, &maxLength, msg); - for(int i = 0; i < maxLength; i += 1023) - { + for (int i = 0; i < maxLength; i += 1023) { Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); ri.Printf(printLevel, "%s\n", msgPart); @@ -174,40 +165,34 @@ static void GLSL_PrintProgramInfoLog(GLuint object, qboolean developerOnly) } } -static void GLSL_PrintShaderInfoLog(GLuint object, qboolean developerOnly) -{ - char *msg; - static char msgPart[1024]; - int maxLength = 0; - int i; - int printLevel = developerOnly ? PRINT_DEVELOPER : PRINT_ALL; +static void GLSL_PrintShaderInfoLog(GLuint object, qboolean developerOnly) { + char *msg; + static char msgPart[1024]; + int maxLength = 0; + int i; + int printLevel = developerOnly ? PRINT_DEVELOPER : PRINT_ALL; qglGetShaderiv(object, GL_INFO_LOG_LENGTH, &maxLength); - if (maxLength <= 0) - { + if (maxLength <= 0) { ri.Printf(printLevel, "No compile log.\n"); return; } ri.Printf(printLevel, "compile log:\n"); - if (maxLength < 1023) - { + if (maxLength < 1023) { qglGetShaderInfoLog(object, maxLength, &maxLength, msgPart); msgPart[maxLength + 1] = '\0'; ri.Printf(printLevel, "%s\n", msgPart); - } - else - { + } else { msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); qglGetShaderInfoLog(object, maxLength, &maxLength, msg); - for(i = 0; i < maxLength; i += 1024) - { + for (i = 0; i < maxLength; i += 1024) { Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); ri.Printf(printLevel, "%s\n", msgPart); @@ -217,13 +202,11 @@ static void GLSL_PrintShaderInfoLog(GLuint object, qboolean developerOnly) } } -static void GLSL_PrintShaderSource(GLuint shader) -{ +static void GLSL_PrintShaderSource(GLuint shader) { int maxLength = 0; qglGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &maxLength); - if ( maxLength == 0 ) - { + if (maxLength == 0) { Com_Printf("No shader source available to output\n"); return; } @@ -231,8 +214,7 @@ static void GLSL_PrintShaderSource(GLuint shader) char *msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); qglGetShaderSource(shader, maxLength, nullptr, msg); - for (int i = 0; i < maxLength; i += 1023) - { + for (int i = 0; i < maxLength; i += 1023) { char msgPart[1024]; Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); ri.Printf(PRINT_ALL, "%s\n", msgPart); @@ -241,13 +223,7 @@ static void GLSL_PrintShaderSource(GLuint shader) Z_Free(msg); } -static size_t GLSL_GetShaderHeader( - GLenum shaderType, - const GLcharARB *extra, - int firstLineNumber, - char *dest, - size_t size) -{ +static size_t GLSL_GetShaderHeader(GLenum shaderType, const GLcharARB *extra, int firstLineNumber, char *dest, size_t size) { float fbufWidthScale, fbufHeightScale; dest[0] = '\0'; @@ -255,109 +231,80 @@ static size_t GLSL_GetShaderHeader( Q_strcat(dest, size, "#version 150 core\n"); Q_strcat(dest, size, - "#ifndef M_PI\n" - "#define M_PI 3.14159265358979323846\n" - "#endif\n"); + "#ifndef M_PI\n" + "#define M_PI 3.14159265358979323846\n" + "#endif\n"); Q_strcat(dest, size, - va("#ifndef deformGen_t\n" - "#define deformGen_t\n" - "#define DEFORM_NONE %i\n" - "#define DEFORM_WAVE %i\n" - "#define DEFORM_NORMALS %i\n" - "#define DEFORM_BULGE %i\n" - "#define DEFORM_BULGE_UNIFORM %i\n" - "#define DEFORM_MOVE %i\n" - "#define DEFORM_PROJECTION_SHADOW %i\n" - "#define DEFORM_DISINTEGRATION %i\n" - "#define WF_NONE %i\n" - "#define WF_SIN %i\n" - "#define WF_SQUARE %i\n" - "#define WF_TRIANGLE %i\n" - "#define WF_SAWTOOTH %i\n" - "#define WF_INVERSE_SAWTOOTH %i\n" - "#endif\n", - DEFORM_NONE, - DEFORM_WAVE, - DEFORM_NORMALS, - DEFORM_BULGE, - DEFORM_BULGE_UNIFORM, - DEFORM_MOVE, - DEFORM_PROJECTION_SHADOW, - DEFORM_DISINTEGRATION, - GF_NONE, - GF_SIN, - GF_SQUARE, - GF_TRIANGLE, - GF_SAWTOOTH, - GF_INVERSE_SAWTOOTH)); + va("#ifndef deformGen_t\n" + "#define deformGen_t\n" + "#define DEFORM_NONE %i\n" + "#define DEFORM_WAVE %i\n" + "#define DEFORM_NORMALS %i\n" + "#define DEFORM_BULGE %i\n" + "#define DEFORM_BULGE_UNIFORM %i\n" + "#define DEFORM_MOVE %i\n" + "#define DEFORM_PROJECTION_SHADOW %i\n" + "#define DEFORM_DISINTEGRATION %i\n" + "#define WF_NONE %i\n" + "#define WF_SIN %i\n" + "#define WF_SQUARE %i\n" + "#define WF_TRIANGLE %i\n" + "#define WF_SAWTOOTH %i\n" + "#define WF_INVERSE_SAWTOOTH %i\n" + "#endif\n", + DEFORM_NONE, DEFORM_WAVE, DEFORM_NORMALS, DEFORM_BULGE, DEFORM_BULGE_UNIFORM, DEFORM_MOVE, DEFORM_PROJECTION_SHADOW, DEFORM_DISINTEGRATION, + GF_NONE, GF_SIN, GF_SQUARE, GF_TRIANGLE, GF_SAWTOOTH, GF_INVERSE_SAWTOOTH)); Q_strcat(dest, size, - va("#ifndef tcGen_t\n" - "#define tcGen_t\n" - "#define TCGEN_LIGHTMAP %i\n" - "#define TCGEN_LIGHTMAP1 %i\n" - "#define TCGEN_LIGHTMAP2 %i\n" - "#define TCGEN_LIGHTMAP3 %i\n" - "#define TCGEN_TEXTURE %i\n" - "#define TCGEN_ENVIRONMENT_MAPPED %i\n" - "#define TCGEN_FOG %i\n" - "#define TCGEN_VECTOR %i\n" - "#endif\n", - TCGEN_LIGHTMAP, - TCGEN_LIGHTMAP1, - TCGEN_LIGHTMAP2, - TCGEN_LIGHTMAP3, - TCGEN_TEXTURE, - TCGEN_ENVIRONMENT_MAPPED, - TCGEN_FOG, - TCGEN_VECTOR)); + va("#ifndef tcGen_t\n" + "#define tcGen_t\n" + "#define TCGEN_LIGHTMAP %i\n" + "#define TCGEN_LIGHTMAP1 %i\n" + "#define TCGEN_LIGHTMAP2 %i\n" + "#define TCGEN_LIGHTMAP3 %i\n" + "#define TCGEN_TEXTURE %i\n" + "#define TCGEN_ENVIRONMENT_MAPPED %i\n" + "#define TCGEN_FOG %i\n" + "#define TCGEN_VECTOR %i\n" + "#endif\n", + TCGEN_LIGHTMAP, TCGEN_LIGHTMAP1, TCGEN_LIGHTMAP2, TCGEN_LIGHTMAP3, TCGEN_TEXTURE, TCGEN_ENVIRONMENT_MAPPED, TCGEN_FOG, TCGEN_VECTOR)); Q_strcat(dest, size, - va("#ifndef colorGen_t\n" - "#define colorGen_t\n" - "#define CGEN_LIGHTING_DIFFUSE %i\n" - "#define CGEN_DISINTEGRATION_1 %i\n" - "#define CGEN_DISINTEGRATION_2 %i\n" - "#endif\n", - CGEN_LIGHTING_DIFFUSE, - CGEN_DISINTEGRATION_1, - CGEN_DISINTEGRATION_2)); + va("#ifndef colorGen_t\n" + "#define colorGen_t\n" + "#define CGEN_LIGHTING_DIFFUSE %i\n" + "#define CGEN_DISINTEGRATION_1 %i\n" + "#define CGEN_DISINTEGRATION_2 %i\n" + "#endif\n", + CGEN_LIGHTING_DIFFUSE, CGEN_DISINTEGRATION_1, CGEN_DISINTEGRATION_2)); Q_strcat(dest, size, - va("#ifndef alphaGen_t\n" - "#define alphaGen_t\n" - "#define AGEN_LIGHTING_SPECULAR %i\n" - "#define AGEN_PORTAL %i\n" - "#endif\n", - AGEN_LIGHTING_SPECULAR, - AGEN_PORTAL)); + va("#ifndef alphaGen_t\n" + "#define alphaGen_t\n" + "#define AGEN_LIGHTING_SPECULAR %i\n" + "#define AGEN_PORTAL %i\n" + "#endif\n", + AGEN_LIGHTING_SPECULAR, AGEN_PORTAL)); Q_strcat(dest, size, - va("#define ALPHA_TEST_GT0 %d\n" - "#define ALPHA_TEST_LT128 %d\n" - "#define ALPHA_TEST_GE128 %d\n" - "#define ALPHA_TEST_GE192 %d\n", - ALPHA_TEST_GT0, - ALPHA_TEST_LT128, - ALPHA_TEST_GE128, - ALPHA_TEST_GE192)); + va("#define ALPHA_TEST_GT0 %d\n" + "#define ALPHA_TEST_LT128 %d\n" + "#define ALPHA_TEST_GE128 %d\n" + "#define ALPHA_TEST_GE192 %d\n", + ALPHA_TEST_GT0, ALPHA_TEST_LT128, ALPHA_TEST_GE128, ALPHA_TEST_GE192)); - Q_strcat(dest, size, - va("#define MAX_G2_BONES %i\n", - MAX_G2_BONES)); + Q_strcat(dest, size, va("#define MAX_G2_BONES %i\n", MAX_G2_BONES)); fbufWidthScale = (float)glConfig.vidWidth; fbufHeightScale = (float)glConfig.vidHeight; Q_strcat(dest, size, - va("#ifndef r_FBufScale\n" - "#define r_FBufScale vec2(%f, %f)\n" - "#endif\n", - fbufWidthScale, - fbufHeightScale)); + va("#ifndef r_FBufScale\n" + "#define r_FBufScale vec2(%f, %f)\n" + "#endif\n", + fbufWidthScale, fbufHeightScale)); - if (r_cubeMapping->integer) - { + if (r_cubeMapping->integer) { Q_strcat(dest, size, va("#define CUBEMAP_RESOLUTION float(%i)\n", CUBE_MAP_SIZE)); Q_strcat(dest, size, va("#define ROUGHNESS_MIPS float(%i)\n", CUBE_MAP_ROUGHNESS_MIPS)); } @@ -365,16 +312,14 @@ static size_t GLSL_GetShaderHeader( if (r_ssao->integer) Q_strcat(dest, size, "#define USE_SSAO\n"); - if (r_deluxeSpecular->value > 0.000001f) - { + if (r_deluxeSpecular->value > 0.000001f) { Q_strcat(dest, size, va("#define r_deluxeSpecular %f\n", r_deluxeSpecular->value)); } if (r_hdr->integer && (r_toneMap->integer || r_forceToneMap->integer)) Q_strcat(dest, size, "#define USE_TONEMAPPING\n"); - if (extra) - { + if (extra) { Q_strcat(dest, size, extra); } @@ -386,30 +331,22 @@ static size_t GLSL_GetShaderHeader( return strlen(dest); } -static bool GLSL_IsGPUShaderCompiled (GLuint shader) -{ +static bool GLSL_IsGPUShaderCompiled(GLuint shader) { GLint compiled; qglGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); return (compiled == GL_TRUE); } -static GLuint GLSL_CompileGPUShader( - GLuint program, - const GLchar *buffer, - int size, - GLenum shaderType) -{ +static GLuint GLSL_CompileGPUShader(GLuint program, const GLchar *buffer, int size, GLenum shaderType) { GLuint shader = qglCreateShader(shaderType); - if ( shader == 0 ) - { + if (shader == 0) { return 0; } qglShaderSource(shader, 1, &buffer, &size); qglCompileShader(shader); - if ( !GLSL_IsGPUShaderCompiled(shader) ) - { + if (!GLSL_IsGPUShaderCompiled(shader)) { GLSL_PrintShaderSource(shader); GLSL_PrintShaderInfoLog(shader, qfalse); @@ -422,22 +359,18 @@ static GLuint GLSL_CompileGPUShader( return shader; } -static const char *GLSL_GetShaderFileSuffix( GLenum shaderType ) -{ - static struct - { +static const char *GLSL_GetShaderFileSuffix(GLenum shaderType) { + static struct { GLenum shaderType; const char *extension; } shaderToFileExtensionSuffix[] = { - { GL_VERTEX_SHADER, "vp" }, - { GL_FRAGMENT_SHADER, "fp" }, - { GL_GEOMETRY_SHADER, "gp" }, + {GL_VERTEX_SHADER, "vp"}, + {GL_FRAGMENT_SHADER, "fp"}, + {GL_GEOMETRY_SHADER, "gp"}, }; - for ( const auto& suffix : shaderToFileExtensionSuffix ) - { - if ( shaderType == suffix.shaderType ) - { + for (const auto &suffix : shaderToFileExtensionSuffix) { + if (shaderType == suffix.shaderType) { return suffix.extension; } } @@ -445,13 +378,7 @@ static const char *GLSL_GetShaderFileSuffix( GLenum shaderType ) return nullptr; } -static size_t GLSL_LoadGPUShaderSource( - const char *name, - const char *fallback, - GLenum shaderType, - char *dest, - int destSize) -{ +static size_t GLSL_LoadGPUShaderSource(const char *name, const char *fallback, GLenum shaderType, char *dest, int destSize) { const char *shaderSuffix = GLSL_GetShaderFileSuffix(shaderType); assert(shaderSuffix != nullptr); @@ -460,67 +387,55 @@ static size_t GLSL_LoadGPUShaderSource( int shaderTextLen = 0; GLcharARB *buffer = nullptr; - if ( r_externalGLSL->integer ) - { + if (r_externalGLSL->integer) { shaderTextLen = ri.FS_ReadFile(filename, (void **)&buffer); } const char *shaderText = nullptr; - if ( !buffer ) - { - if ( fallback ) - { + if (!buffer) { + if (fallback) { ri.Printf(PRINT_DEVELOPER, "...loading built-in '%s'\n", filename); shaderText = fallback; shaderTextLen = strlen(shaderText); ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); - } - else - { + } else { ri.Printf(PRINT_DEVELOPER, "couldn't load '%s'\n", filename); return 0; } - } - else - { + } else { ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); shaderText = buffer; } int result = 0; - if ( destSize >= (shaderTextLen + 1) ) - { + if (destSize >= (shaderTextLen + 1)) { Q_strncpyz(dest, shaderText, destSize); result = strlen(dest); } - if ( buffer ) - { + if (buffer) { ri.FS_FreeFile(buffer); } - + return result; } -static void GLSL_LinkProgram(GLuint program) -{ +static void GLSL_LinkProgram(GLuint program) { qglLinkProgram(program); GLint linked; qglGetProgramiv(program, GL_LINK_STATUS, &linked); - if ( linked != GL_TRUE ) - { + if (linked != GL_TRUE) { GLSL_PrintProgramInfoLog(program, qfalse); ri.Printf(PRINT_ALL, "\n"); ri.Error(ERR_FATAL, "shaders failed to link"); } } -static void GLSL_ShowProgramUniforms(GLuint program) -{ - int i, count, size; - GLenum type; - char uniformName[1000]; +static void GLSL_ShowProgramUniforms(GLuint program) { + int i, count, size; + GLenum type; + char uniformName[1000]; // install the executables in the program object as part of current state. qglUseProgram(program); @@ -531,8 +446,7 @@ static void GLSL_ShowProgramUniforms(GLuint program) qglGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count); // Loop over each of the active uniforms, and set their value - for(i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { qglGetActiveUniform(program, i, sizeof(uniformName), NULL, &size, &type, uniformName); ri.Printf(PRINT_DEVELOPER, "active uniform: '%s'\n", uniformName); @@ -541,24 +455,23 @@ static void GLSL_ShowProgramUniforms(GLuint program) qglUseProgram(0); } -static void GLSL_BindShaderInterface( shaderProgram_t *program ) -{ +static void GLSL_BindShaderInterface(shaderProgram_t *program) { static const char *shaderInputNames[] = { - "attr_Position", // ATTR_INDEX_POSITION - "attr_TexCoord0", // ATTR_INDEX_TEXCOORD0 - "attr_TexCoord1", // ATTR_INDEX_TEXCOORD1 - "attr_TexCoord2", // ATTR_INDEX_TEXCOORD2 - "attr_TexCoord3", // ATTR_INDEX_TEXCOORD3 - "attr_TexCoord4", // ATTR_INDEX_TEXCOORD4 - "attr_Tangent", // ATTR_INDEX_TANGENT - "attr_Normal", // ATTR_INDEX_NORMAL - "attr_Color", // ATTR_INDEX_COLOR - "attr_LightDirection", // ATTR_INDEX_LIGHTDIRECTION - "attr_BoneIndexes", // ATTR_INDEX_BONE_INDEXES - "attr_BoneWeights", // ATTR_INDEX_BONE_WEIGHTS - "attr_Position2", // ATTR_INDEX_POSITION2 - "attr_Tangent2", // ATTR_INDEX_TANGENT2 - "attr_Normal2", // ATTR_INDEX_NORMAL2 + "attr_Position", // ATTR_INDEX_POSITION + "attr_TexCoord0", // ATTR_INDEX_TEXCOORD0 + "attr_TexCoord1", // ATTR_INDEX_TEXCOORD1 + "attr_TexCoord2", // ATTR_INDEX_TEXCOORD2 + "attr_TexCoord3", // ATTR_INDEX_TEXCOORD3 + "attr_TexCoord4", // ATTR_INDEX_TEXCOORD4 + "attr_Tangent", // ATTR_INDEX_TANGENT + "attr_Normal", // ATTR_INDEX_NORMAL + "attr_Color", // ATTR_INDEX_COLOR + "attr_LightDirection", // ATTR_INDEX_LIGHTDIRECTION + "attr_BoneIndexes", // ATTR_INDEX_BONE_INDEXES + "attr_BoneWeights", // ATTR_INDEX_BONE_WEIGHTS + "attr_Position2", // ATTR_INDEX_POSITION2 + "attr_Tangent2", // ATTR_INDEX_TANGENT2 + "attr_Normal2", // ATTR_INDEX_NORMAL2 }; static const char *xfbVarNames[XFB_VAR_COUNT] = { @@ -567,17 +480,14 @@ static void GLSL_BindShaderInterface( shaderProgram_t *program ) }; static const char *shaderOutputNames[] = { - "out_Color", // Color output - "out_Glow", // Glow output + "out_Color", // Color output + "out_Glow", // Glow output }; const uint32_t attribs = program->attribs; - if (attribs != 0) - { - for ( int attribIndex = 0; attribIndex < ATTR_INDEX_MAX; ++attribIndex ) - { - if ( !(attribs & (1u << attribIndex)) ) - { + if (attribs != 0) { + for (int attribIndex = 0; attribIndex < ATTR_INDEX_MAX; ++attribIndex) { + if (!(attribs & (1u << attribIndex))) { continue; } @@ -585,165 +495,118 @@ static void GLSL_BindShaderInterface( shaderProgram_t *program ) } } - for ( int outputIndex = 0; outputIndex < ARRAY_LEN(shaderOutputNames); ++outputIndex ) - { + for (int outputIndex = 0; outputIndex < ARRAY_LEN(shaderOutputNames); ++outputIndex) { qglBindFragDataLocation(program->program, outputIndex, shaderOutputNames[outputIndex]); } const uint32_t xfbVars = program->xfbVariables; - if (xfbVars != 0) - { + if (xfbVars != 0) { size_t activeXfbVarsCount = 0; const char *activeXfbVarNames[XFB_VAR_COUNT] = {}; - for (uint32_t xfbVarIndex = 0; xfbVarIndex < XFB_VAR_COUNT; ++xfbVarIndex) - { - if ((xfbVars & (1u << xfbVarIndex)) != 0) - { + for (uint32_t xfbVarIndex = 0; xfbVarIndex < XFB_VAR_COUNT; ++xfbVarIndex) { + if ((xfbVars & (1u << xfbVarIndex)) != 0) { activeXfbVarNames[activeXfbVarsCount++] = xfbVarNames[xfbVarIndex]; } } - qglTransformFeedbackVaryings( - program->program, activeXfbVarsCount, activeXfbVarNames, GL_INTERLEAVED_ATTRIBS); + qglTransformFeedbackVaryings(program->program, activeXfbVarsCount, activeXfbVarNames, GL_INTERLEAVED_ATTRIBS); } } -GLenum ToGLShaderType( GPUShaderType type ) -{ - switch ( type ) - { - case GPUSHADER_VERTEX: - return GL_VERTEX_SHADER; +GLenum ToGLShaderType(GPUShaderType type) { + switch (type) { + case GPUSHADER_VERTEX: + return GL_VERTEX_SHADER; - case GPUSHADER_FRAGMENT: - return GL_FRAGMENT_SHADER; + case GPUSHADER_FRAGMENT: + return GL_FRAGMENT_SHADER; - case GPUSHADER_GEOMETRY: - return GL_GEOMETRY_SHADER; + case GPUSHADER_GEOMETRY: + return GL_GEOMETRY_SHADER; - default: - assert(!"Invalid shader type"); - return 0; + default: + assert(!"Invalid shader type"); + return 0; } return 0; } -class ShaderProgramBuilder -{ - public: - ShaderProgramBuilder(); - ~ShaderProgramBuilder(); +class ShaderProgramBuilder { + public: + ShaderProgramBuilder(); + ~ShaderProgramBuilder(); - ShaderProgramBuilder(const ShaderProgramBuilder&) = delete; - ShaderProgramBuilder& operator=(const ShaderProgramBuilder&) = delete; + ShaderProgramBuilder(const ShaderProgramBuilder &) = delete; + ShaderProgramBuilder &operator=(const ShaderProgramBuilder &) = delete; - void Start( - const char *name, - const uint32_t attribs, - const uint32_t xfbVariables); - bool AddShader(const GPUShaderDesc& shaderDesc, const char *extra); - bool Build(shaderProgram_t *program); + void Start(const char *name, const uint32_t attribs, const uint32_t xfbVariables); + bool AddShader(const GPUShaderDesc &shaderDesc, const char *extra); + bool Build(shaderProgram_t *program); - private: - static const size_t MAX_SHADER_SOURCE_LEN = 16384; + private: + static const size_t MAX_SHADER_SOURCE_LEN = 16384; - void ReleaseShaders(); + void ReleaseShaders(); - const char *name; - uint32_t attribs; - uint32_t xfbVariables; - GLuint program; - GLuint shaderNames[GPUSHADER_TYPE_COUNT]; - size_t numShaderNames; - std::string shaderSource; + const char *name; + uint32_t attribs; + uint32_t xfbVariables; + GLuint program; + GLuint shaderNames[GPUSHADER_TYPE_COUNT]; + size_t numShaderNames; + std::string shaderSource; }; ShaderProgramBuilder::ShaderProgramBuilder() - : name(nullptr) - , attribs(0) - , program(0) - , shaderNames() - , numShaderNames(0) - , shaderSource(MAX_SHADER_SOURCE_LEN, '\0') -{ -} - -ShaderProgramBuilder::~ShaderProgramBuilder() -{ - if ( program ) - { + : name(nullptr), attribs(0), program(0), shaderNames(), numShaderNames(0), shaderSource(MAX_SHADER_SOURCE_LEN, '\0') {} + +ShaderProgramBuilder::~ShaderProgramBuilder() { + if (program) { ReleaseShaders(); qglDeleteProgram(program); } } -void ShaderProgramBuilder::Start( - const char *name, - const uint32_t attribs, - const uint32_t xfbVariables) -{ +void ShaderProgramBuilder::Start(const char *name, const uint32_t attribs, const uint32_t xfbVariables) { this->program = qglCreateProgram(); this->name = name; this->attribs = attribs; this->xfbVariables = xfbVariables; } -bool ShaderProgramBuilder::AddShader( const GPUShaderDesc& shaderDesc, const char *extra ) -{ +bool ShaderProgramBuilder::AddShader(const GPUShaderDesc &shaderDesc, const char *extra) { static const int MAX_ATTEMPTS = 3; const GLenum apiShader = ToGLShaderType(shaderDesc.type); size_t sourceLen = 0; size_t headerLen = 0; int attempts = 0; - while ( sourceLen == 0 && attempts < MAX_ATTEMPTS ) - { - headerLen = GLSL_GetShaderHeader( - apiShader, - extra, - shaderDesc.firstLineNumber, - &shaderSource[0], - shaderSource.size()); - - sourceLen = GLSL_LoadGPUShaderSource( - name, - shaderDesc.source, - apiShader, - &shaderSource[headerLen], - shaderSource.size() - headerLen); - - if ( sourceLen == 0 ) - { + while (sourceLen == 0 && attempts < MAX_ATTEMPTS) { + headerLen = GLSL_GetShaderHeader(apiShader, extra, shaderDesc.firstLineNumber, &shaderSource[0], shaderSource.size()); + + sourceLen = GLSL_LoadGPUShaderSource(name, shaderDesc.source, apiShader, &shaderSource[headerLen], shaderSource.size() - headerLen); + + if (sourceLen == 0) { shaderSource.resize(shaderSource.size() * 2); } - + ++attempts; } - if ( sourceLen == 0 ) - { - ri.Printf( - PRINT_ALL, - "ShaderProgramBuilder::AddShader: Failed to allocate enough memory for " - "shader '%s'\n", - name); + if (sourceLen == 0) { + ri.Printf(PRINT_ALL, + "ShaderProgramBuilder::AddShader: Failed to allocate enough memory for " + "shader '%s'\n", + name); return false; } - const GLuint shader = GLSL_CompileGPUShader( - program, - shaderSource.c_str(), - sourceLen + headerLen, - apiShader); - if ( shader == 0 ) - { - ri.Printf( - PRINT_ALL, - "ShaderProgramBuilder::AddShader: Unable to load \"%s\"\n", - name); + const GLuint shader = GLSL_CompileGPUShader(program, shaderSource.c_str(), sourceLen + headerLen, apiShader); + if (shader == 0) { + ri.Printf(PRINT_ALL, "ShaderProgramBuilder::AddShader: Unable to load \"%s\"\n", name); return false; } @@ -753,8 +616,7 @@ bool ShaderProgramBuilder::AddShader( const GPUShaderDesc& shaderDesc, const cha return true; } -bool ShaderProgramBuilder::Build( shaderProgram_t *shaderProgram ) -{ +bool ShaderProgramBuilder::Build(shaderProgram_t *shaderProgram) { const size_t nameBufferSize = strlen(name) + 1; shaderProgram->name = (char *)Z_Malloc(nameBufferSize, TAG_GENERAL); Q_strncpyz(shaderProgram->name, name, nameBufferSize); @@ -772,10 +634,8 @@ bool ShaderProgramBuilder::Build( shaderProgram_t *shaderProgram ) return true; } -void ShaderProgramBuilder::ReleaseShaders() -{ - for ( size_t i = 0; i < numShaderNames; ++i ) - { +void ShaderProgramBuilder::ReleaseShaders() { + for (size_t i = 0; i < numShaderNames; ++i) { qglDetachShader(program, shaderNames[i]); qglDeleteShader(shaderNames[i]); } @@ -783,153 +643,101 @@ void ShaderProgramBuilder::ReleaseShaders() numShaderNames = 0; } -static bool GLSL_LoadGPUShader( - ShaderProgramBuilder& builder, - shaderProgram_t *program, - const char *name, - const uint32_t attribs, - const uint32_t xfbVariables, - const GLcharARB *extra, - const GPUProgramDesc& programDesc) -{ +static bool GLSL_LoadGPUShader(ShaderProgramBuilder &builder, shaderProgram_t *program, const char *name, const uint32_t attribs, const uint32_t xfbVariables, + const GLcharARB *extra, const GPUProgramDesc &programDesc) { builder.Start(name, attribs, xfbVariables); - for ( int i = 0; i < programDesc.numShaders; ++i ) - { - const GPUShaderDesc& shaderDesc = programDesc.shaders[i]; - if ( !builder.AddShader(shaderDesc, extra) ) - { + for (int i = 0; i < programDesc.numShaders; ++i) { + const GPUShaderDesc &shaderDesc = programDesc.shaders[i]; + if (!builder.AddShader(shaderDesc, extra)) { return false; } } return builder.Build(program); } -void GLSL_InitUniforms(shaderProgram_t *program) -{ - program->uniforms = (GLint *)Z_Malloc( - UNIFORM_COUNT * sizeof(*program->uniforms), TAG_GENERAL); - program->uniformBufferOffsets = (short *)Z_Malloc( - UNIFORM_COUNT * sizeof(*program->uniformBufferOffsets), TAG_GENERAL); +void GLSL_InitUniforms(shaderProgram_t *program) { + program->uniforms = (GLint *)Z_Malloc(UNIFORM_COUNT * sizeof(*program->uniforms), TAG_GENERAL); + program->uniformBufferOffsets = (short *)Z_Malloc(UNIFORM_COUNT * sizeof(*program->uniformBufferOffsets), TAG_GENERAL); GLint *uniforms = program->uniforms; int size = 0; - for (int i = 0; i < UNIFORM_COUNT; i++) - { + for (int i = 0; i < UNIFORM_COUNT; i++) { uniforms[i] = qglGetUniformLocation(program->program, uniformsInfo[i].name); if (uniforms[i] == -1) continue; - + program->uniformBufferOffsets[i] = size; - switch(uniformsInfo[i].type) - { - case GLSL_INT: - size += sizeof(GLint) * uniformsInfo[i].size; - break; - case GLSL_FLOAT: - size += sizeof(GLfloat) * uniformsInfo[i].size; - break; - case GLSL_VEC2: - size += sizeof(float) * 2 * uniformsInfo[i].size; - break; - case GLSL_VEC3: - size += sizeof(float) * 3 * uniformsInfo[i].size; - break; - case GLSL_VEC4: - size += sizeof(float) * 4 * uniformsInfo[i].size; - break; - case GLSL_MAT4x3: - size += sizeof(float) * 12 * uniformsInfo[i].size; - break; - case GLSL_MAT4x4: - size += sizeof(float) * 16 * uniformsInfo[i].size; - break; - default: - break; + switch (uniformsInfo[i].type) { + case GLSL_INT: + size += sizeof(GLint) * uniformsInfo[i].size; + break; + case GLSL_FLOAT: + size += sizeof(GLfloat) * uniformsInfo[i].size; + break; + case GLSL_VEC2: + size += sizeof(float) * 2 * uniformsInfo[i].size; + break; + case GLSL_VEC3: + size += sizeof(float) * 3 * uniformsInfo[i].size; + break; + case GLSL_VEC4: + size += sizeof(float) * 4 * uniformsInfo[i].size; + break; + case GLSL_MAT4x3: + size += sizeof(float) * 12 * uniformsInfo[i].size; + break; + case GLSL_MAT4x4: + size += sizeof(float) * 16 * uniformsInfo[i].size; + break; + default: + break; } } program->uniformBuffer = (char *)Z_Malloc(size, TAG_SHADERTEXT, qtrue); program->uniformBlocks = 0; - for ( int i = 0; i < UNIFORM_BLOCK_COUNT; ++i ) - { - const GLuint blockIndex = qglGetUniformBlockIndex( - program->program, uniformBlocksInfo[i].name); + for (int i = 0; i < UNIFORM_BLOCK_COUNT; ++i) { + const GLuint blockIndex = qglGetUniformBlockIndex(program->program, uniformBlocksInfo[i].name); if (blockIndex == GL_INVALID_INDEX) continue; - ri.Printf( - PRINT_DEVELOPER, - "Binding block %d (name '%s', size %zu bytes) to slot %d\n", - blockIndex, - uniformBlocksInfo[i].name, - uniformBlocksInfo[i].size, - uniformBlocksInfo[i].slot); - qglUniformBlockBinding( - program->program, blockIndex, uniformBlocksInfo[i].slot); + ri.Printf(PRINT_DEVELOPER, "Binding block %d (name '%s', size %zu bytes) to slot %d\n", blockIndex, uniformBlocksInfo[i].name, + uniformBlocksInfo[i].size, uniformBlocksInfo[i].slot); + qglUniformBlockBinding(program->program, blockIndex, uniformBlocksInfo[i].slot); program->uniformBlocks |= (1u << i); } GLint numActiveUniformBlocks = 0; qglGetProgramiv(program->program, GL_ACTIVE_UNIFORM_BLOCKS, &numActiveUniformBlocks); ri.Printf(PRINT_DEVELOPER, "..num uniform blocks: %d\n", numActiveUniformBlocks); - for (int i = 0; i < numActiveUniformBlocks; ++i) - { + for (int i = 0; i < numActiveUniformBlocks; ++i) { char blockName[512]; - qglGetActiveUniformBlockName( - program->program, - i, - sizeof(blockName), - nullptr, - blockName); + qglGetActiveUniformBlockName(program->program, i, sizeof(blockName), nullptr, blockName); GLint blockSize = 0; - qglGetActiveUniformBlockiv( - program->program, i, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize); + qglGetActiveUniformBlockiv(program->program, i, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize); ri.Printf(PRINT_DEVELOPER, "..block %d: %s (%d bytes)\n", i, blockName, blockSize); GLint numMembers = 0; - qglGetActiveUniformBlockiv( - program->program, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &numMembers); + qglGetActiveUniformBlockiv(program->program, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &numMembers); - if (numMembers > 0) - { + if (numMembers > 0) { GLuint memberIndices[128]; - qglGetActiveUniformBlockiv( - program->program, - i, - GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, - (GLint *)memberIndices); + qglGetActiveUniformBlockiv(program->program, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, (GLint *)memberIndices); GLint memberOffsets[128]; - qglGetActiveUniformsiv( - program->program, - numMembers, - memberIndices, - GL_UNIFORM_OFFSET, - memberOffsets); + qglGetActiveUniformsiv(program->program, numMembers, memberIndices, GL_UNIFORM_OFFSET, memberOffsets); GLint memberTypes[128]; - qglGetActiveUniformsiv( - program->program, - numMembers, - memberIndices, - GL_UNIFORM_TYPE, - memberTypes); - - for (int j = 0; j < numMembers; ++j) - { + qglGetActiveUniformsiv(program->program, numMembers, memberIndices, GL_UNIFORM_TYPE, memberTypes); + + for (int j = 0; j < numMembers; ++j) { char memberName[512]; - qglGetActiveUniformName( - program->program, - memberIndices[j], - sizeof(memberName), - nullptr, - memberName); + qglGetActiveUniformName(program->program, memberIndices[j], sizeof(memberName), nullptr, memberName); ri.Printf(PRINT_DEVELOPER, "....uniform '%s'\n", memberName); ri.Printf(PRINT_DEVELOPER, "......offset: %d\n", memberOffsets[j]); - switch (memberTypes[j]) - { + switch (memberTypes[j]) { case GL_FLOAT: ri.Printf(PRINT_DEVELOPER, "......type: float\n"); break; @@ -954,16 +762,14 @@ void GLSL_InitUniforms(shaderProgram_t *program) } } -void GLSL_FinishGPUShader(shaderProgram_t *program) -{ +void GLSL_FinishGPUShader(shaderProgram_t *program) { #if defined(_DEBUG) GLSL_ShowProgramUniforms(program->program); GL_CheckErrors(); #endif } -void GLSL_SetUniforms( shaderProgram_t *program, UniformData *uniformData ) -{ +void GLSL_SetUniforms(shaderProgram_t *program, UniformData *uniformData) { if (uniformData == nullptr) return; @@ -971,94 +777,81 @@ void GLSL_SetUniforms( shaderProgram_t *program, UniformData *uniformData ) if (data == nullptr) return; - while ( data->index != UNIFORM_COUNT ) - { - switch ( uniformsInfo[data->index].type ) - { - case GLSL_INT: - { - assert(data->numElements == 1); - GLint *value = (GLint *)(data + 1); - GLSL_SetUniformInt(program, data->index, *value); - data = reinterpret_cast(value + data->numElements); - break; - } + while (data->index != UNIFORM_COUNT) { + switch (uniformsInfo[data->index].type) { + case GLSL_INT: { + assert(data->numElements == 1); + GLint *value = (GLint *)(data + 1); + GLSL_SetUniformInt(program, data->index, *value); + data = reinterpret_cast(value + data->numElements); + break; + } - case GLSL_FLOAT: - { - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformFloatN(program, data->index, value, data->numElements); - data = reinterpret_cast(value + data->numElements); - break; - } + case GLSL_FLOAT: { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformFloatN(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements); + break; + } - case GLSL_VEC2: - { - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformVec2N(program, data->index, value, data->numElements); - data = reinterpret_cast(value + data->numElements*2); - break; - } + case GLSL_VEC2: { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec2N(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements * 2); + break; + } - case GLSL_VEC3: - { - assert(data->numElements == 1); - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformVec3(program, data->index, value); - data = reinterpret_cast(value + data->numElements*3); - break; - } + case GLSL_VEC3: { + assert(data->numElements == 1); + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec3(program, data->index, value); + data = reinterpret_cast(value + data->numElements * 3); + break; + } - case GLSL_VEC4: - { - assert(data->numElements == 1); - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformVec4(program, data->index, value); - data = reinterpret_cast(value + data->numElements*4); - break; - } + case GLSL_VEC4: { + assert(data->numElements == 1); + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec4(program, data->index, value); + data = reinterpret_cast(value + data->numElements * 4); + break; + } - case GLSL_MAT4x3: - { - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformMatrix4x3(program, data->index, value, data->numElements); - data = reinterpret_cast(value + data->numElements*12); - break; - } + case GLSL_MAT4x3: { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformMatrix4x3(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements * 12); + break; + } - case GLSL_MAT4x4: - { - GLfloat *value = (GLfloat *)(data + 1); - GLSL_SetUniformMatrix4x4(program, data->index, value, data->numElements); - data = reinterpret_cast(value + data->numElements*16); - break; - } + case GLSL_MAT4x4: { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformMatrix4x4(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements * 16); + break; + } - default: - { - assert(!"Invalid uniform data type"); - return; - } + default: { + assert(!"Invalid uniform data type"); + return; + } } } } -void GLSL_SetUniformInt(shaderProgram_t *program, int uniformNum, GLint value) -{ +void GLSL_SetUniformInt(shaderProgram_t *program, int uniformNum, GLint value) { GLint *uniforms = program->uniforms; GLint *compare = (GLint *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_INT) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformInt: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_INT) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformInt: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (value == *compare) - { + if (value == *compare) { return; } @@ -1067,46 +860,40 @@ void GLSL_SetUniformInt(shaderProgram_t *program, int uniformNum, GLint value) qglUniform1i(uniforms[uniformNum], value); } -void GLSL_SetUniformFloat(shaderProgram_t *program, int uniformNum, GLfloat value) -{ +void GLSL_SetUniformFloat(shaderProgram_t *program, int uniformNum, GLfloat value) { GLint *uniforms = program->uniforms; GLfloat *compare = (GLfloat *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_FLOAT) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloat: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_FLOAT) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformFloat: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (value == *compare) - { + if (value == *compare) { return; } *compare = value; - + qglUniform1f(uniforms[uniformNum], value); } -void GLSL_SetUniformVec2(shaderProgram_t *program, int uniformNum, const vec2_t v) -{ +void GLSL_SetUniformVec2(shaderProgram_t *program, int uniformNum, const vec2_t v) { GLint *uniforms = program->uniforms; float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_VEC2) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec2: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_VEC2) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (v[0] == compare[0] && v[1] == compare[1]) - { + if (v[0] == compare[0] && v[1] == compare[1]) { return; } @@ -1116,31 +903,25 @@ void GLSL_SetUniformVec2(shaderProgram_t *program, int uniformNum, const vec2_t qglUniform2f(uniforms[uniformNum], v[0], v[1]); } -void GLSL_SetUniformVec2N(shaderProgram_t *program, int uniformNum, const float *v, int numVec2s) -{ +void GLSL_SetUniformVec2N(shaderProgram_t *program, int uniformNum, const float *v, int numVec2s) { GLint *uniforms = program->uniforms; float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_VEC2) - { + if (uniformsInfo[uniformNum].type != GLSL_VEC2) { ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (uniformsInfo[uniformNum].size < numVec2s) - { - ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2N: uniform %i only has %d elements! Tried to set %d\n", - uniformNum, - uniformsInfo[uniformNum].size, - numVec2s); + if (uniformsInfo[uniformNum].size < numVec2s) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2N: uniform %i only has %d elements! Tried to set %d\n", uniformNum, uniformsInfo[uniformNum].size, + numVec2s); return; } - if (memcmp(compare, v, sizeof(vec2_t) * numVec2s) == 0) - { + if (memcmp(compare, v, sizeof(vec2_t) * numVec2s) == 0) { return; } @@ -1149,22 +930,19 @@ void GLSL_SetUniformVec2N(shaderProgram_t *program, int uniformNum, const float qglUniform2fv(uniforms[uniformNum], numVec2s, v); } -void GLSL_SetUniformVec3(shaderProgram_t *program, int uniformNum, const vec3_t v) -{ +void GLSL_SetUniformVec3(shaderProgram_t *program, int uniformNum, const vec3_t v) { GLint *uniforms = program->uniforms; float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_VEC3) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec3: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_VEC3) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec3: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (VectorCompare(v, compare)) - { + if (VectorCompare(v, compare)) { return; } @@ -1173,22 +951,19 @@ void GLSL_SetUniformVec3(shaderProgram_t *program, int uniformNum, const vec3_t qglUniform3f(uniforms[uniformNum], v[0], v[1], v[2]); } -void GLSL_SetUniformVec4(shaderProgram_t *program, int uniformNum, const vec4_t v) -{ +void GLSL_SetUniformVec4(shaderProgram_t *program, int uniformNum, const vec4_t v) { GLint *uniforms = program->uniforms; float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_VEC4) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec4: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_VEC4) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec4: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (VectorCompare4(v, compare)) - { + if (VectorCompare4(v, compare)) { return; } @@ -1197,50 +972,42 @@ void GLSL_SetUniformVec4(shaderProgram_t *program, int uniformNum, const vec4_t qglUniform4f(uniforms[uniformNum], v[0], v[1], v[2], v[3]); } -void GLSL_SetUniformFloatN(shaderProgram_t *program, int uniformNum, const float *v, int numFloats) -{ +void GLSL_SetUniformFloatN(shaderProgram_t *program, int uniformNum, const float *v, int numFloats) { GLint *uniforms = program->uniforms; float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_FLOAT) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloatN: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_FLOAT) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformFloatN: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } - if (uniformsInfo[uniformNum].size < numFloats) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloatN: uniform %i only has %d elements! Tried to set %d\n", - uniformNum, - uniformsInfo[uniformNum].size, - numFloats ); + if (uniformsInfo[uniformNum].size < numFloats) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformFloatN: uniform %i only has %d elements! Tried to set %d\n", uniformNum, uniformsInfo[uniformNum].size, + numFloats); return; } - if ( memcmp( compare, v, sizeof( float ) * numFloats ) == 0 ) - { + if (memcmp(compare, v, sizeof(float) * numFloats) == 0) { return; } - memcpy( compare, v, sizeof( float ) * numFloats ); + memcpy(compare, v, sizeof(float) * numFloats); qglUniform1fv(uniforms[uniformNum], numFloats, v); } -void GLSL_SetUniformMatrix4x3(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) -{ +void GLSL_SetUniformMatrix4x3(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) { GLint *uniforms = program->uniforms; float *compare; if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_MAT4x3) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformMatrix4x3: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_MAT4x3) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformMatrix4x3: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } @@ -1248,27 +1015,24 @@ void GLSL_SetUniformMatrix4x3(shaderProgram_t *program, int uniformNum, const fl return; compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); - if (memcmp (matrix, compare, sizeof (float) * 12 * numElements) == 0) - { + if (memcmp(matrix, compare, sizeof(float) * 12 * numElements) == 0) { return; } - Com_Memcpy (compare, matrix, sizeof (float) * 12 * numElements); + Com_Memcpy(compare, matrix, sizeof(float) * 12 * numElements); qglUniformMatrix4x3fv(uniforms[uniformNum], numElements, GL_FALSE, matrix); } -void GLSL_SetUniformMatrix4x4(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) -{ +void GLSL_SetUniformMatrix4x4(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) { GLint *uniforms = program->uniforms; float *compare; if (uniforms[uniformNum] == -1) return; - if (uniformsInfo[uniformNum].type != GLSL_MAT4x4) - { - ri.Printf( PRINT_WARNING, "GLSL_SetUniformMatrix4x4: wrong type for uniform %i in program %s\n", uniformNum, program->name); + if (uniformsInfo[uniformNum].type != GLSL_MAT4x4) { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformMatrix4x4: wrong type for uniform %i in program %s\n", uniformNum, program->name); return; } @@ -1276,53 +1040,45 @@ void GLSL_SetUniformMatrix4x4(shaderProgram_t *program, int uniformNum, const fl return; compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); - if (memcmp (matrix, compare, sizeof (float) * 16 * numElements) == 0) - { + if (memcmp(matrix, compare, sizeof(float) * 16 * numElements) == 0) { return; } - Com_Memcpy (compare, matrix, sizeof (float) * 16 * numElements); + Com_Memcpy(compare, matrix, sizeof(float) * 16 * numElements); qglUniformMatrix4fv(uniforms[uniformNum], numElements, GL_FALSE, matrix); } -void GLSL_DeleteGPUShader(shaderProgram_t *program) -{ - if(program->program) - { +void GLSL_DeleteGPUShader(shaderProgram_t *program) { + if (program->program) { qglDeleteProgram(program->program); - Z_Free (program->name); - Z_Free (program->uniformBuffer); - Z_Free (program->uniformBufferOffsets); - Z_Free (program->uniforms); + Z_Free(program->name); + Z_Free(program->uniformBuffer); + Z_Free(program->uniformBufferOffsets); + Z_Free(program->uniforms); Com_Memset(program, 0, sizeof(*program)); } } -static bool GLSL_IsValidPermutationForGeneric (int shaderCaps) -{ +static bool GLSL_IsValidPermutationForGeneric(int shaderCaps) { #ifdef REND2_SP - if ( (shaderCaps & GENERICDEF_USE_VERTEX_ANIMATION) && - (shaderCaps & GENERICDEF_USE_SKELETAL_ANIMATION) ) + if ((shaderCaps & GENERICDEF_USE_VERTEX_ANIMATION) && (shaderCaps & GENERICDEF_USE_SKELETAL_ANIMATION)) return false; #endif // REND2_SP return true; } -static bool GLSL_IsValidPermutationForFog (int shaderCaps) -{ +static bool GLSL_IsValidPermutationForFog(int shaderCaps) { #ifdef REND2_SP - if ( (shaderCaps & FOGDEF_USE_VERTEX_ANIMATION) && - (shaderCaps & FOGDEF_USE_SKELETAL_ANIMATION) ) + if ((shaderCaps & FOGDEF_USE_VERTEX_ANIMATION) && (shaderCaps & FOGDEF_USE_SKELETAL_ANIMATION)) return false; #endif // REND2_SP return true; } -static bool GLSL_IsValidPermutationForLight (int lightType, int shaderCaps) -{ +static bool GLSL_IsValidPermutationForLight(int lightType, int shaderCaps) { if ((shaderCaps & LIGHTDEF_USE_PARALLAXMAP) && !r_parallaxMapping->integer) return false; @@ -1330,20 +1086,16 @@ static bool GLSL_IsValidPermutationForLight (int lightType, int shaderCaps) return false; #ifdef REND2_SP - if ( (shaderCaps & LIGHTDEF_USE_SKELETAL_ANIMATION) && - (shaderCaps & LIGHTDEF_USE_VERTEX_ANIMATION) ) + if ((shaderCaps & LIGHTDEF_USE_SKELETAL_ANIMATION) && (shaderCaps & LIGHTDEF_USE_VERTEX_ANIMATION)) return false; #endif // REND2_SP return true; } -Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) -{ - for ( size_t i = 0; i < numBlocks; ++i ) - { +Block *FindBlock(const char *name, Block *blocks, size_t numBlocks) { + for (size_t i = 0; i < numBlocks; ++i) { Block *block = blocks + i; - if ( Q_stricmpn(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0 ) - { + if (Q_stricmpn(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0) { return block; } } @@ -1351,25 +1103,22 @@ Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) return nullptr; } -void GLSL_InitSplashScreenShader() -{ - const char *vs = - "#version 150 core\n" - "out vec2 var_TexCoords;\n" - "void main() {\n" - " vec2 position = vec2(2.0 * float(gl_VertexID & 2) - 1.0, 4.0 * float(gl_VertexID & 1) - 1.0);\n" - " gl_Position = vec4(position, 0.0, 1.0);\n" - " var_TexCoords = vec2(position.x * 0.5 + 0.5, 2.0 - (position.y * 0.5 + 0.5));\n" - "}"; - - const char *fs = - "#version 150 core\n" - "uniform sampler2D u_SplashTexture;\n" - "in vec2 var_TexCoords;\n" - "out vec4 out_Color;\n" - "void main() {\n" - " out_Color = texture(u_SplashTexture, var_TexCoords);\n" - "}"; +void GLSL_InitSplashScreenShader() { + const char *vs = "#version 150 core\n" + "out vec2 var_TexCoords;\n" + "void main() {\n" + " vec2 position = vec2(2.0 * float(gl_VertexID & 2) - 1.0, 4.0 * float(gl_VertexID & 1) - 1.0);\n" + " gl_Position = vec4(position, 0.0, 1.0);\n" + " var_TexCoords = vec2(position.x * 0.5 + 0.5, 2.0 - (position.y * 0.5 + 0.5));\n" + "}"; + + const char *fs = "#version 150 core\n" + "uniform sampler2D u_SplashTexture;\n" + "in vec2 var_TexCoords;\n" + "out vec4 out_Color;\n" + "void main() {\n" + " out_Color = texture(u_SplashTexture, var_TexCoords);\n" + "}"; GLuint vshader = qglCreateShader(GL_VERTEX_SHADER); qglShaderSource(vshader, 1, &vs, NULL); @@ -1390,20 +1139,16 @@ void GLSL_InitSplashScreenShader() Q_strncpyz(tr.splashScreenShader.name, "splash", splashLen + 1); } -static const GPUProgramDesc *LoadProgramSource( - const char *programName, Allocator& allocator, const GPUProgramDesc& fallback ) -{ +static const GPUProgramDesc *LoadProgramSource(const char *programName, Allocator &allocator, const GPUProgramDesc &fallback) { const GPUProgramDesc *result = &fallback; - - if ( r_externalGLSL->integer ) - { + + if (r_externalGLSL->integer) { char *buffer; char programPath[MAX_QPATH]; Com_sprintf(programPath, sizeof(programPath), "glsl/%s.glsl", programName); long size = ri.FS_ReadFile(programPath, (void **)&buffer); - if ( size ) - { + if (size) { GPUProgramDesc *externalProgramDesc = ojkAlloc(allocator); *externalProgramDesc = ParseProgramSource(allocator, buffer); result = externalProgramDesc; @@ -1414,20 +1159,14 @@ static const GPUProgramDesc *LoadProgramSource( return result; } -static int GLSL_LoadGPUProgramGeneric( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramGeneric(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("generic", allocator, fallback_genericProgram); - for ( int i = 0; i < GENERICDEF_COUNT; i++ ) - { - if (!GLSL_IsValidPermutationForGeneric(i)) - { + const GPUProgramDesc *programDesc = LoadProgramSource("generic", allocator, fallback_genericProgram); + for (int i = 0; i < GENERICDEF_COUNT; i++) { + if (!GLSL_IsValidPermutationForGeneric(i)) { continue; } @@ -1437,20 +1176,17 @@ static int GLSL_LoadGPUProgramGeneric( if (i & GENERICDEF_USE_DEFORM_VERTEXES) Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); - if (i & GENERICDEF_USE_TCGEN_AND_TCMOD) - { + if (i & GENERICDEF_USE_TCGEN_AND_TCMOD) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); } #ifdef REND2_SP - if (i & GENERICDEF_USE_VERTEX_ANIMATION) - { + if (i & GENERICDEF_USE_VERTEX_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); attribs |= ATTR_POSITION2 | ATTR_NORMAL2; } #endif // REND2_SP - if (i & GENERICDEF_USE_SKELETAL_ANIMATION) - { + if (i & GENERICDEF_USE_SKELETAL_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; } @@ -1467,9 +1203,7 @@ static int GLSL_LoadGPUProgramGeneric( if (i & GENERICDEF_USE_ALPHA_TEST) Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); - if (!GLSL_LoadGPUShader(builder, &tr.genericShader[i], "generic", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.genericShader[i], "generic", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load generic shader!"); } @@ -1477,7 +1211,7 @@ static int GLSL_LoadGPUProgramGeneric( qglUseProgram(tr.genericShader[i].program); GLSL_SetUniformInt(&tr.genericShader[i], UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); - GLSL_SetUniformInt(&tr.genericShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); + GLSL_SetUniformInt(&tr.genericShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); qglUseProgram(0); GLSL_FinishGPUShader(&tr.genericShader[i]); @@ -1488,38 +1222,29 @@ static int GLSL_LoadGPUProgramGeneric( return numPrograms; } -static int GLSL_LoadGPUProgramFogPass( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramFogPass(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("fogpass", allocator, fallback_fogpassProgram); - for (int i = 0; i < FOGDEF_COUNT; i++) - { - if (!GLSL_IsValidPermutationForFog(i)) - { + const GPUProgramDesc *programDesc = LoadProgramSource("fogpass", allocator, fallback_fogpassProgram); + for (int i = 0; i < FOGDEF_COUNT; i++) { + if (!GLSL_IsValidPermutationForFog(i)) { continue; } - uint32_t attribs = - (ATTR_POSITION | ATTR_NORMAL | ATTR_TEXCOORD0); + uint32_t attribs = (ATTR_POSITION | ATTR_NORMAL | ATTR_TEXCOORD0); extradefines[0] = '\0'; if (i & FOGDEF_USE_DEFORM_VERTEXES) Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); #ifdef REND2_SP - if (i & FOGDEF_USE_VERTEX_ANIMATION) - { + if (i & FOGDEF_USE_VERTEX_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); attribs |= ATTR_POSITION2 | ATTR_NORMAL2 } #endif // REND2_SP - if (i & FOGDEF_USE_SKELETAL_ANIMATION) - { + if (i & FOGDEF_USE_SKELETAL_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; } @@ -1530,9 +1255,7 @@ static int GLSL_LoadGPUProgramFogPass( if (i & FOGDEF_USE_ALPHA_TEST) Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); - if (!GLSL_LoadGPUShader(builder, &tr.fogShader[i], "fogpass", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.fogShader[i], "fogpass", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load fogpass shader!"); } @@ -1544,45 +1267,37 @@ static int GLSL_LoadGPUProgramFogPass( qglUseProgram(0); GLSL_FinishGPUShader(&tr.fogShader[i]); - + ++numPrograms; } return numPrograms; } -static int GLSL_LoadGPUProgramRefraction( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc) -{ +static int GLSL_LoadGPUProgramRefraction(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("refraction", allocator, fallback_refractionProgram); - for (int i = 0; i < REFRACTIONDEF_COUNT; i++) - { + const GPUProgramDesc *programDesc = LoadProgramSource("refraction", allocator, fallback_refractionProgram); + for (int i = 0; i < REFRACTIONDEF_COUNT; i++) { uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_NORMAL | ATTR_COLOR; extradefines[0] = '\0'; if (i & REFRACTIONDEF_USE_DEFORM_VERTEXES) Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); - if (i & REFRACTIONDEF_USE_TCGEN_AND_TCMOD) - { + if (i & REFRACTIONDEF_USE_TCGEN_AND_TCMOD) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); } #ifdef REND2_SP - if (i & REFRACTIONDEF_USE_VERTEX_ANIMATION) - { + if (i & REFRACTIONDEF_USE_VERTEX_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); attribs |= ATTR_POSITION2 | ATTR_NORMAL2; } #endif // REND2_SP - if (i & REFRACTIONDEF_USE_SKELETAL_ANIMATION) - { + if (i & REFRACTIONDEF_USE_SKELETAL_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; } @@ -1596,9 +1311,7 @@ static int GLSL_LoadGPUProgramRefraction( if (i & REFRACTIONDEF_USE_SRGB_TRANSFORM) Q_strcat(extradefines, sizeof(extradefines), "#define USE_LINEAR_LIGHT\n"); - if (!GLSL_LoadGPUShader(builder, &tr.refractionShader[i], "refraction", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.refractionShader[i], "refraction", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load refraction shader!"); } @@ -1618,24 +1331,18 @@ static int GLSL_LoadGPUProgramRefraction( return numPrograms; } -static int GLSL_LoadGPUProgramLightAll( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramLightAll(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("lightall", allocator, fallback_lightallProgram); - const bool useFastLight = - (!r_normalMapping->integer && !r_specularMapping->integer); - for ( int i = 0; i < LIGHTDEF_COUNT; i++ ) - { + const GPUProgramDesc *programDesc = LoadProgramSource("lightall", allocator, fallback_lightallProgram); + const bool useFastLight = (!r_normalMapping->integer && !r_specularMapping->integer); + for (int i = 0; i < LIGHTDEF_COUNT; i++) { int lightType = i & LIGHTDEF_LIGHTTYPE_MASK; // skip impossible combos - if (!GLSL_IsValidPermutationForLight (lightType, i)) + if (!GLSL_IsValidPermutationForLight(lightType, i)) continue; uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_COLOR | ATTR_NORMAL; @@ -1645,8 +1352,7 @@ static int GLSL_LoadGPUProgramLightAll( if (r_hdr->integer && !glRefConfig.floatLightmap) Q_strcat(extradefines, sizeof(extradefines), "#define RGBM_LIGHTMAP\n"); - if (lightType) - { + if (lightType) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT\n"); if (useFastLight) @@ -1655,38 +1361,33 @@ static int GLSL_LoadGPUProgramLightAll( if (r_dlightMode->integer >= 2) Q_strcat(extradefines, sizeof(extradefines), "#define USE_DSHADOWS\n"); - switch (lightType) - { - case LIGHTDEF_USE_LIGHTMAP: - { - Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHTMAP\n"); + switch (lightType) { + case LIGHTDEF_USE_LIGHTMAP: { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHTMAP\n"); - if (r_deluxeMapping->integer && !useFastLight) - Q_strcat(extradefines, sizeof(extradefines), "#define USE_DELUXEMAP\n"); + if (r_deluxeMapping->integer && !useFastLight) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DELUXEMAP\n"); - attribs |= ATTR_TEXCOORD1 | ATTR_LIGHTDIRECTION; - break; - } + attribs |= ATTR_TEXCOORD1 | ATTR_LIGHTDIRECTION; + break; + } - case LIGHTDEF_USE_LIGHT_VECTOR: - { - Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VECTOR\n"); - break; - } + case LIGHTDEF_USE_LIGHT_VECTOR: { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VECTOR\n"); + break; + } - case LIGHTDEF_USE_LIGHT_VERTEX: - { - Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VERTEX\n"); - attribs |= ATTR_LIGHTDIRECTION; - break; - } + case LIGHTDEF_USE_LIGHT_VERTEX: { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VERTEX\n"); + attribs |= ATTR_LIGHTDIRECTION; + break; + } - default: - break; + default: + break; } - if (r_normalMapping->integer) - { + if (r_normalMapping->integer) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_NORMALMAP\n"); if ((i & LIGHTDEF_USE_PARALLAXMAP) && r_parallaxMapping->integer) @@ -1695,8 +1396,7 @@ static int GLSL_LoadGPUProgramLightAll( attribs |= ATTR_TANGENT; } - if (r_specularMapping->integer) - { + if (r_specularMapping->integer) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_SPECULARMAP\n"); if (i & LIGHTDEF_USE_SPEC_GLOSS) Q_strcat(extradefines, sizeof(extradefines), "#define USE_SPECGLOSS\n"); @@ -1706,8 +1406,7 @@ static int GLSL_LoadGPUProgramLightAll( Q_strcat(extradefines, sizeof(extradefines), "#define USE_CUBEMAP\n"); } - if (r_sunlightMode->integer) - { + if (r_sunlightMode->integer) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_SHADOWMAP\n"); if (r_sunlightMode->integer == 1) @@ -1721,40 +1420,31 @@ static int GLSL_LoadGPUProgramLightAll( if (r_shadowFilter->integer >= 2) Q_strcat(extradefines, sizeof(extradefines), "#define USE_SHADOW_FILTER2\n"); - Q_strcat( - extradefines, sizeof(extradefines), - va("#define r_shadowMapSize %d\n", r_shadowMapSize->integer)); - Q_strcat( - extradefines, sizeof(extradefines), - va("#define r_shadowCascadeZFar %f\n", r_shadowCascadeZFar->value)); + Q_strcat(extradefines, sizeof(extradefines), va("#define r_shadowMapSize %d\n", r_shadowMapSize->integer)); + Q_strcat(extradefines, sizeof(extradefines), va("#define r_shadowCascadeZFar %f\n", r_shadowCascadeZFar->value)); } - if (i & LIGHTDEF_USE_TCGEN_AND_TCMOD) - { + if (i & LIGHTDEF_USE_TCGEN_AND_TCMOD) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); } - if (i & LIGHTDEF_USE_CLOTH_BRDF) - { + if (i & LIGHTDEF_USE_CLOTH_BRDF) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_CLOTH_BRDF\n"); } #ifdef REND2_SP - if (i & LIGHTDEF_USE_VERTEX_ANIMATION) - { + if (i & LIGHTDEF_USE_VERTEX_ANIMATION) { Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); attribs |= ATTR_POSITION2 | ATTR_NORMAL2; if (r_normalMapping->integer) attribs |= ATTR_TANGENT2; - } - else + } else #endif // REND2_SP - if (i & LIGHTDEF_USE_SKELETAL_ANIMATION) - { - Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); - attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; - } + if (i & LIGHTDEF_USE_SKELETAL_ANIMATION) { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + } if (i & LIGHTDEF_USE_ALPHA_TEST) Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); @@ -1762,94 +1452,54 @@ static int GLSL_LoadGPUProgramLightAll( if (i & LIGHTDEF_USE_GLOW_BUFFER) Q_strcat(extradefines, sizeof(extradefines), "#define USE_GLOW_BUFFER\n"); - if (!GLSL_LoadGPUShader(builder, &tr.lightallShader[i], "lightall", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.lightallShader[i], "lightall", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load lightall shader!"); } GLSL_InitUniforms(&tr.lightallShader[i]); qglUseProgram(tr.lightallShader[i].program); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_NORMALMAP, TB_NORMALMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DELUXEMAP, TB_DELUXEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_NORMALMAP, TB_NORMALMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DELUXEMAP, TB_DELUXEMAP); GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SPECULARMAP, TB_SPECULARMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP, TB_SHADOWMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_CUBEMAP, TB_CUBEMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_ENVBRDFMAP, TB_ENVBRDFMAP); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP2, TB_SHADOWMAPARRAY); - GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SSAOMAP, TB_SSAOMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP, TB_SHADOWMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_CUBEMAP, TB_CUBEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_ENVBRDFMAP, TB_ENVBRDFMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP2, TB_SHADOWMAPARRAY); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SSAOMAP, TB_SSAOMAP); qglUseProgram(0); GLSL_FinishGPUShader(&tr.lightallShader[i]); - + ++numPrograms; } return numPrograms; } -static int GLSL_LoadGPUProgramBasicWithDefinitions( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc, - shaderProgram_t *shaderProgram, - const char *programName, - const GPUProgramDesc& programFallback, - const char *extraDefines, - const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, - const uint32_t xfbVariables = NO_XFB_VARS) -{ +static int GLSL_LoadGPUProgramBasicWithDefinitions(ShaderProgramBuilder &builder, Allocator &scratchAlloc, shaderProgram_t *shaderProgram, + const char *programName, const GPUProgramDesc &programFallback, const char *extraDefines, + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, const uint32_t xfbVariables = NO_XFB_VARS) { Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); - const GPUProgramDesc *programDesc = - LoadProgramSource(programName, allocator, programFallback); - if (!GLSL_LoadGPUShader( - builder, - shaderProgram, - programName, - attribs, - xfbVariables, - extraDefines, - *programDesc)) - { + const GPUProgramDesc *programDesc = LoadProgramSource(programName, allocator, programFallback); + if (!GLSL_LoadGPUShader(builder, shaderProgram, programName, attribs, xfbVariables, extraDefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load %s shader!", programName); } return 1; } -static int GLSL_LoadGPUProgramBasic( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc, - shaderProgram_t *shaderProgram, - const char *programName, - const GPUProgramDesc& programFallback, - const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, - const uint32_t xfbVariables = NO_XFB_VARS) -{ - return GLSL_LoadGPUProgramBasicWithDefinitions( - builder, - scratchAlloc, - shaderProgram, - programName, - programFallback, - nullptr, - attribs, - xfbVariables); -} - -static int GLSL_LoadGPUProgramTextureColor( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.textureColorShader, - "texturecolor", - fallback_texturecolorProgram); +static int GLSL_LoadGPUProgramBasic(ShaderProgramBuilder &builder, Allocator &scratchAlloc, shaderProgram_t *shaderProgram, const char *programName, + const GPUProgramDesc &programFallback, const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, + const uint32_t xfbVariables = NO_XFB_VARS) { + return GLSL_LoadGPUProgramBasicWithDefinitions(builder, scratchAlloc, shaderProgram, programName, programFallback, nullptr, attribs, xfbVariables); +} + +static int GLSL_LoadGPUProgramTextureColor(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.textureColorShader, "texturecolor", fallback_texturecolorProgram); GLSL_InitUniforms(&tr.textureColorShader); @@ -1862,20 +1512,11 @@ static int GLSL_LoadGPUProgramTextureColor( return 1; } -static int GLSL_LoadGPUProgramPShadow( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramPShadow(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { const char *extradefines = "#define USE_PCF\n#define USE_DISCARD\n"; - GLSL_LoadGPUProgramBasicWithDefinitions( - builder, - scratchAlloc, - &tr.pshadowShader, - "pshadow", - fallback_pshadowProgram, - extradefines, - ATTR_POSITION | ATTR_NORMAL); + GLSL_LoadGPUProgramBasicWithDefinitions(builder, scratchAlloc, &tr.pshadowShader, "pshadow", fallback_pshadowProgram, extradefines, + ATTR_POSITION | ATTR_NORMAL); GLSL_InitUniforms(&tr.pshadowShader); @@ -1884,27 +1525,21 @@ static int GLSL_LoadGPUProgramPShadow( qglUseProgram(0); GLSL_FinishGPUShader(&tr.pshadowShader); - + return 1; } -static int GLSL_LoadGPUProgramVShadow( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc) -{ +static int GLSL_LoadGPUProgramVShadow(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("shadowvolume", allocator, fallback_shadowvolumeProgram); + const GPUProgramDesc *programDesc = LoadProgramSource("shadowvolume", allocator, fallback_shadowvolumeProgram); const uint32_t attribs = ATTR_POSITION | ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; extradefines[0] = '\0'; Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); - if (!GLSL_LoadGPUShader(builder, &tr.volumeShadowShader, "shadowvolume", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.volumeShadowShader, "shadowvolume", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load shadowvolume shader!"); } @@ -1914,16 +1549,8 @@ static int GLSL_LoadGPUProgramVShadow( return 1; } -static int GLSL_LoadGPUProgramDownscale4x( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.down4xShader, - "down4x", - fallback_down4xProgram); +static int GLSL_LoadGPUProgramDownscale4x(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.down4xShader, "down4x", fallback_down4xProgram); GLSL_InitUniforms(&tr.down4xShader); @@ -1932,20 +1559,12 @@ static int GLSL_LoadGPUProgramDownscale4x( qglUseProgram(0); GLSL_FinishGPUShader(&tr.down4xShader); - + return 1; } -static int GLSL_LoadGPUProgramBokeh( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.bokehShader, - "bokeh", - fallback_bokehProgram); +static int GLSL_LoadGPUProgramBokeh(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.bokehShader, "bokeh", fallback_bokehProgram); GLSL_InitUniforms(&tr.bokehShader); @@ -1954,36 +1573,27 @@ static int GLSL_LoadGPUProgramBokeh( qglUseProgram(0); GLSL_FinishGPUShader(&tr.bokehShader); - + return 1; } -static int GLSL_LoadGPUProgramTonemap( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramTonemap(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("tonemap", allocator, fallback_tonemapProgram); + const GPUProgramDesc *programDesc = LoadProgramSource("tonemap", allocator, fallback_tonemapProgram); const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; extradefines[0] = '\0'; - if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[0], "tonemap", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[0], "tonemap", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load tonemap shader!"); } Q_strcat(extradefines, sizeof(extradefines), "#define USE_LINEAR_LIGHT\n"); - if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[1], "tonemap", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[1], "tonemap", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load tonemap shader!"); } - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { GLSL_InitUniforms(&tr.tonemapShader[i]); qglUseProgram(tr.tonemapShader[i].program); GLSL_SetUniformInt(&tr.tonemapShader[i], UNIFORM_TEXTUREMAP, TB_COLORMAP); @@ -1994,27 +1604,20 @@ static int GLSL_LoadGPUProgramTonemap( return 2; } -static int GLSL_LoadGPUProgramCalcLuminanceLevel( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramCalcLuminanceLevel(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("calclevels4x", allocator, fallback_calclevels4xProgram); - for ( int i = 0; i < 2; i++ ) - { + const GPUProgramDesc *programDesc = LoadProgramSource("calclevels4x", allocator, fallback_calclevels4xProgram); + for (int i = 0; i < 2; i++) { const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; extradefines[0] = '\0'; if (!i) Q_strcat(extradefines, sizeof(extradefines), "#define FIRST_PASS\n"); - if (!GLSL_LoadGPUShader(builder, &tr.calclevels4xShader[i], "calclevels4x", attribs, - NO_XFB_VARS, extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.calclevels4xShader[i], "calclevels4x", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load calclevels4x shader!"); } @@ -2025,23 +1628,15 @@ static int GLSL_LoadGPUProgramCalcLuminanceLevel( qglUseProgram(0); GLSL_FinishGPUShader(&tr.calclevels4xShader[i]); - + ++numPrograms; } return numPrograms; } -static int GLSL_LoadGPUProgramSSAO( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.ssaoShader, - "ssao", - fallback_ssaoProgram); +static int GLSL_LoadGPUProgramSSAO(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.ssaoShader, "ssao", fallback_ssaoProgram); GLSL_InitUniforms(&tr.ssaoShader); @@ -2054,16 +1649,8 @@ static int GLSL_LoadGPUProgramSSAO( return 1; } -static int GLSL_LoadGPUProgramPrefilterEnvMap( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.prefilterEnvMapShader, - "prefilterEnvMap", - fallback_prefilterEnvMapProgram); +static int GLSL_LoadGPUProgramPrefilterEnvMap(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.prefilterEnvMapShader, "prefilterEnvMap", fallback_prefilterEnvMapProgram); GLSL_InitUniforms(&tr.prefilterEnvMapShader); @@ -2076,18 +1663,13 @@ static int GLSL_LoadGPUProgramPrefilterEnvMap( return 1; } -static int GLSL_LoadGPUProgramDepthBlur( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramDepthBlur(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("depthBlur", allocator, fallback_depthblurProgram); - for ( int i = 0; i < 2; i++ ) - { + const GPUProgramDesc *programDesc = LoadProgramSource("depthBlur", allocator, fallback_depthblurProgram); + for (int i = 0; i < 2; i++) { const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; extradefines[0] = '\0'; @@ -2096,10 +1678,7 @@ static int GLSL_LoadGPUProgramDepthBlur( else Q_strcat(extradefines, sizeof(extradefines), "#define USE_HORIZONTAL_BLUR\n"); - - if (!GLSL_LoadGPUShader(builder, &tr.depthBlurShader[i], "depthBlur", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.depthBlurShader[i], "depthBlur", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load depthBlur shader!"); } @@ -2118,35 +1697,26 @@ static int GLSL_LoadGPUProgramDepthBlur( return numPrograms; } -static int GLSL_LoadGPUProgramGaussianBlur( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramGaussianBlur(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("gaussian_blur", allocator, fallback_gaussian_blurProgram); + const GPUProgramDesc *programDesc = LoadProgramSource("gaussian_blur", allocator, fallback_gaussian_blurProgram); const uint32_t attribs = 0; extradefines[0] = '\0'; - Q_strcat (extradefines, sizeof (extradefines), "#define BLUR_X"); + Q_strcat(extradefines, sizeof(extradefines), "#define BLUR_X"); - if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[0], "gaussian_blur", attribs, - NO_XFB_VARS, extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[0], "gaussian_blur", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load gaussian_blur (X-direction) shader!"); } - if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[1], "gaussian_blur", attribs, - NO_XFB_VARS, nullptr, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[1], "gaussian_blur", attribs, NO_XFB_VARS, nullptr, *programDesc)) { ri.Error(ERR_FATAL, "Could not load gaussian_blur (Y-direction) shader!"); } int numPrograms = 0; - for ( int i = 0; i < 2; i++ ) - { + for (int i = 0; i < 2; i++) { GLSL_InitUniforms(&tr.gaussianBlurShader[i]); GLSL_FinishGPUShader(&tr.gaussianBlurShader[i]); ++numPrograms; @@ -2155,88 +1725,56 @@ static int GLSL_LoadGPUProgramGaussianBlur( return numPrograms; } -static int GLSL_LoadGPUProgramDynamicGlowUpsample( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.dglowUpsample, - "dglow_upsample", - fallback_dglow_upsampleProgram, - 0); +static int GLSL_LoadGPUProgramDynamicGlowUpsample(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.dglowUpsample, "dglow_upsample", fallback_dglow_upsampleProgram, 0); GLSL_InitUniforms(&tr.dglowUpsample); GLSL_FinishGPUShader(&tr.dglowUpsample); return 1; } -static int GLSL_LoadGPUProgramDynamicGlowDownsample( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.dglowDownsample, - "dglow_downsample", - fallback_dglow_downsampleProgram, - 0); +static int GLSL_LoadGPUProgramDynamicGlowDownsample(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.dglowDownsample, "dglow_downsample", fallback_dglow_downsampleProgram, 0); GLSL_InitUniforms(&tr.dglowDownsample); GLSL_FinishGPUShader(&tr.dglowDownsample); return 1; } -static int GLSL_LoadGPUProgramSurfaceSprites( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ +static int GLSL_LoadGPUProgramSurfaceSprites(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { int numPrograms = 0; Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); char extradefines[1200]; - const GPUProgramDesc *programDesc = - LoadProgramSource("surface_sprites", allocator, fallback_surface_spritesProgram); + const GPUProgramDesc *programDesc = LoadProgramSource("surface_sprites", allocator, fallback_surface_spritesProgram); const uint32_t attribs = ATTR_POSITION | ATTR_POSITION2 | ATTR_NORMAL | ATTR_COLOR; - for ( int i = 0; i < SSDEF_COUNT; ++i ) - { + for (int i = 0; i < SSDEF_COUNT; ++i) { extradefines[0] = '\0'; - if ( (i & SSDEF_FACE_CAMERA) && (i & SSDEF_FACE_UP) ) + if ((i & SSDEF_FACE_CAMERA) && (i & SSDEF_FACE_UP)) continue; - if ( i & SSDEF_FACE_CAMERA ) - Q_strcat(extradefines, sizeof(extradefines), - "#define FACE_CAMERA\n"); - else if ( i & SSDEF_FACE_UP ) - Q_strcat(extradefines, sizeof(extradefines), - "#define FACE_UP\n"); + if (i & SSDEF_FACE_CAMERA) + Q_strcat(extradefines, sizeof(extradefines), "#define FACE_CAMERA\n"); + else if (i & SSDEF_FACE_UP) + Q_strcat(extradefines, sizeof(extradefines), "#define FACE_UP\n"); else if (i & SSDEF_FLATTENED) - Q_strcat(extradefines, sizeof(extradefines), - "#define FACE_FLATTENED\n"); + Q_strcat(extradefines, sizeof(extradefines), "#define FACE_FLATTENED\n"); if (i & SSDEF_FX_SPRITE) - Q_strcat(extradefines, sizeof(extradefines), - "#define FX_SPRITE\n"); + Q_strcat(extradefines, sizeof(extradefines), "#define FX_SPRITE\n"); - if ( i & SSDEF_USE_FOG ) - Q_strcat(extradefines, sizeof(extradefines), - "#define USE_FOG\n"); + if (i & SSDEF_USE_FOG) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_FOG\n"); - if ( i & SSDEF_ALPHA_TEST ) - Q_strcat(extradefines, sizeof(extradefines), - "#define ALPHA_TEST\n"); + if (i & SSDEF_ALPHA_TEST) + Q_strcat(extradefines, sizeof(extradefines), "#define ALPHA_TEST\n"); if (i & SSDEF_ADDITIVE) - Q_strcat(extradefines, sizeof(extradefines), - "#define ADDITIVE_BLEND\n"); - + Q_strcat(extradefines, sizeof(extradefines), "#define ADDITIVE_BLEND\n"); + shaderProgram_t *program = tr.spriteShader + i; - if (!GLSL_LoadGPUShader(builder, program, "surface_sprites", attribs, NO_XFB_VARS, - extradefines, *programDesc)) - { + if (!GLSL_LoadGPUShader(builder, program, "surface_sprites", attribs, NO_XFB_VARS, extradefines, *programDesc)) { ri.Error(ERR_FATAL, "Could not load surface sprites shader!"); } @@ -2248,17 +1786,8 @@ static int GLSL_LoadGPUProgramSurfaceSprites( return numPrograms; } -static int GLSL_LoadGPUProgramWeather( - ShaderProgramBuilder& builder, - Allocator& scratchAlloc ) -{ - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.weatherShader, - "weather", - fallback_weatherProgram, - ATTR_POSITION | ATTR_COLOR); +static int GLSL_LoadGPUProgramWeather(ShaderProgramBuilder &builder, Allocator &scratchAlloc) { + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.weatherShader, "weather", fallback_weatherProgram, ATTR_POSITION | ATTR_COLOR); GLSL_InitUniforms(&tr.weatherShader); qglUseProgram(tr.weatherShader.program); @@ -2267,14 +1796,8 @@ static int GLSL_LoadGPUProgramWeather( qglUseProgram(0); GLSL_FinishGPUShader(&tr.weatherShader); - GLSL_LoadGPUProgramBasic( - builder, - scratchAlloc, - &tr.weatherUpdateShader, - "weatherUpdate", - fallback_weatherUpdateProgram, - ATTR_POSITION | ATTR_COLOR, - (1u << XFB_VAR_POSITION) | (1u << XFB_VAR_VELOCITY)); + GLSL_LoadGPUProgramBasic(builder, scratchAlloc, &tr.weatherUpdateShader, "weatherUpdate", fallback_weatherUpdateProgram, ATTR_POSITION | ATTR_COLOR, + (1u << XFB_VAR_POSITION) | (1u << XFB_VAR_VELOCITY)); GLSL_InitUniforms(&tr.weatherUpdateShader); GLSL_FinishGPUShader(&tr.weatherUpdateShader); @@ -2282,8 +1805,7 @@ static int GLSL_LoadGPUProgramWeather( return 2; } -void GLSL_LoadGPUShaders() -{ +void GLSL_LoadGPUShaders() { #if 0 // vertex size = 48 bytes VertexFormat bspVertexFormat = { @@ -2344,7 +1866,7 @@ void GLSL_LoadGPUShaders() Allocator allocator(512 * 1024); ShaderProgramBuilder builder; - + int numGenShaders = 0; int numLightShaders = 0; int numEtcShaders = 0; @@ -2369,25 +1891,23 @@ void GLSL_LoadGPUShaders() numEtcShaders += GLSL_LoadGPUProgramSurfaceSprites(builder, allocator); numEtcShaders += GLSL_LoadGPUProgramWeather(builder, allocator); - ri.Printf(PRINT_ALL, "loaded %i GLSL shaders (%i gen %i light %i etc) in %5.2f seconds\n", - numGenShaders + numLightShaders + numEtcShaders, numGenShaders, numLightShaders, - numEtcShaders, (ri.Milliseconds() - startTime) / 1000.0); + ri.Printf(PRINT_ALL, "loaded %i GLSL shaders (%i gen %i light %i etc) in %5.2f seconds\n", numGenShaders + numLightShaders + numEtcShaders, numGenShaders, + numLightShaders, numEtcShaders, (ri.Milliseconds() - startTime) / 1000.0); } -void GLSL_ShutdownGPUShaders(void) -{ +void GLSL_ShutdownGPUShaders(void) { int i; ri.Printf(PRINT_ALL, "------- GLSL_ShutdownGPUShaders -------\n"); - for ( int i = 0; i < ATTR_INDEX_MAX; i++ ) + for (int i = 0; i < ATTR_INDEX_MAX; i++) qglDisableVertexAttribArray(i); GLSL_BindNullProgram(); GLSL_DeleteGPUShader(&tr.splashScreenShader); - for ( i = 0; i < GENERICDEF_COUNT; i++) + for (i = 0; i < GENERICDEF_COUNT; i++) GLSL_DeleteGPUShader(&tr.genericShader[i]); for (i = 0; i < REFRACTIONDEF_COUNT; i++) @@ -2395,10 +1915,10 @@ void GLSL_ShutdownGPUShaders(void) GLSL_DeleteGPUShader(&tr.textureColorShader); - for ( i = 0; i < FOGDEF_COUNT; i++) + for (i = 0; i < FOGDEF_COUNT; i++) GLSL_DeleteGPUShader(&tr.fogShader[i]); - for ( i = 0; i < LIGHTDEF_COUNT; i++) + for (i = 0; i < LIGHTDEF_COUNT; i++) GLSL_DeleteGPUShader(&tr.lightallShader[i]); GLSL_DeleteGPUShader(&tr.pshadowShader); @@ -2409,12 +1929,12 @@ void GLSL_ShutdownGPUShaders(void) for (i = 0; i < 2; ++i) GLSL_DeleteGPUShader(&tr.tonemapShader[i]); - for ( i = 0; i < 2; i++) + for (i = 0; i < 2; i++) GLSL_DeleteGPUShader(&tr.calclevels4xShader[i]); GLSL_DeleteGPUShader(&tr.ssaoShader); - for ( i = 0; i < 2; i++) + for (i = 0; i < 2; i++) GLSL_DeleteGPUShader(&tr.depthBlurShader[i]); GLSL_DeleteGPUShader(&tr.testcubeShader); @@ -2437,108 +1957,87 @@ void GLSL_ShutdownGPUShaders(void) qglUseProgram(0); } -void GLSL_BindProgram(shaderProgram_t * program) -{ - if(!program) - { +void GLSL_BindProgram(shaderProgram_t *program) { + if (!program) { GLSL_BindNullProgram(); return; } - if(r_logFile->integer) - { + if (r_logFile->integer) { // don't just call LogComment, or we will get a call to va() every frame! GLimp_LogComment(va("--- GL_BindProgram( %s ) ---\n", program->name)); } - if(glState.currentProgram != program) - { + if (glState.currentProgram != program) { qglUseProgram(program->program); glState.currentProgram = program; backEnd.pc.c_glslShaderBinds++; } } - -void GLSL_BindNullProgram(void) -{ - if(r_logFile->integer) - { +void GLSL_BindNullProgram(void) { + if (r_logFile->integer) { GLimp_LogComment("--- GL_BindNullProgram ---\n"); } - if(glState.currentProgram) - { + if (glState.currentProgram) { qglUseProgram(0); glState.currentProgram = NULL; } } -void GLSL_VertexAttribsState(uint32_t stateBits, VertexArraysProperties *vertexArraysOut) -{ +void GLSL_VertexAttribsState(uint32_t stateBits, VertexArraysProperties *vertexArraysOut) { VertexArraysProperties vertexArraysLocal; VertexArraysProperties *vertexArrays = vertexArraysOut; - if ( !vertexArrays ) - { + if (!vertexArrays) { vertexArrays = &vertexArraysLocal; } - if ( tess.useInternalVBO ) - { + if (tess.useInternalVBO) { CalculateVertexArraysProperties(stateBits, vertexArrays); - for ( int i = 0; i < vertexArrays->numVertexArrays; i++ ) - { + for (int i = 0; i < vertexArrays->numVertexArrays; i++) { int attributeIndex = vertexArrays->enabledAttributes[i]; vertexArrays->offsets[attributeIndex] += backEndData->currentFrame->dynamicVboCommitOffset; } - } - else - { + } else { CalculateVertexArraysFromVBO(stateBits, glState.currentVBO, vertexArrays); } GLSL_VertexAttribPointers(vertexArrays); - } -void GL_VertexArraysToAttribs( - vertexAttribute_t *attribs, - size_t attribsCount, - const VertexArraysProperties *vertexArrays) -{ +void GL_VertexArraysToAttribs(vertexAttribute_t *attribs, size_t attribsCount, const VertexArraysProperties *vertexArrays) { assert(attribsCount == ATTR_INDEX_MAX); - static const struct - { + static const struct { int numComponents; GLboolean integerAttribute; GLenum type; GLboolean normalize; } attributes[ATTR_INDEX_MAX] = { - { 3, GL_FALSE, GL_FLOAT, GL_FALSE }, // position - { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc0 - { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc1 - { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc2 - { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc3 - { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc4 - { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // tangent - { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // normal - { 4, GL_FALSE, GL_FLOAT, GL_FALSE }, // color - { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // light direction - { 4, GL_TRUE, GL_UNSIGNED_BYTE, GL_FALSE }, // bone indices - { 4, GL_FALSE, GL_UNSIGNED_BYTE, GL_TRUE }, // bone weights + {3, GL_FALSE, GL_FLOAT, GL_FALSE}, // position + {2, GL_FALSE, GL_FLOAT, GL_FALSE}, // tc0 + {2, GL_FALSE, GL_FLOAT, GL_FALSE}, // tc1 + {2, GL_FALSE, GL_FLOAT, GL_FALSE}, // tc2 + {2, GL_FALSE, GL_FLOAT, GL_FALSE}, // tc3 + {2, GL_FALSE, GL_FLOAT, GL_FALSE}, // tc4 + {4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE}, // tangent + {4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE}, // normal + {4, GL_FALSE, GL_FLOAT, GL_FALSE}, // color + {4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE}, // light direction + {4, GL_TRUE, GL_UNSIGNED_BYTE, GL_FALSE}, // bone indices + {4, GL_FALSE, GL_UNSIGNED_BYTE, GL_TRUE}, // bone weights #ifdef REND2_SP - { 3, GL_FALSE, GL_FLOAT, GL_FALSE }, // pos2 - { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // tangent2 - { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // normal2 -#endif // REND2_SP + {3, GL_FALSE, GL_FLOAT, GL_FALSE}, // pos2 + {4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE}, // tangent2 + {4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE}, // normal2 +#endif // REND2_SP }; - for ( int i = 0; i < vertexArrays->numVertexArrays; i++ ) - { + for (int i = 0; i < vertexArrays->numVertexArrays; i++) { int attributeIndex = vertexArrays->enabledAttributes[i]; - vertexAttribute_t& attrib = attribs[i]; + vertexAttribute_t &attrib = attribs[i]; attrib.vbo = glState.currentVBO; attrib.index = attributeIndex; @@ -2552,11 +2051,9 @@ void GL_VertexArraysToAttribs( } } -void GLSL_VertexAttribPointers(const VertexArraysProperties *vertexArrays) -{ +void GLSL_VertexAttribPointers(const VertexArraysProperties *vertexArrays) { // don't just call LogComment, or we will get a call to va() every frame! - if (r_logFile->integer) - { + if (r_logFile->integer) { GLimp_LogComment("--- GL_VertexAttribPointers() ---\n"); } @@ -2565,13 +2062,11 @@ void GLSL_VertexAttribPointers(const VertexArraysProperties *vertexArrays) GL_VertexAttribPointers(vertexArrays->numVertexArrays, attribs); } - -shaderProgram_t *GLSL_GetGenericShaderProgram(int stage) -{ +shaderProgram_t *GLSL_GetGenericShaderProgram(int stage) { shaderStage_t *pStage = tess.xstages[stage]; int shaderAttribs = 0; - if ( pStage->alphaTestType != ALPHA_TEST_NONE ) + if (pStage->alphaTestType != ALPHA_TEST_NONE) shaderAttribs |= GENERICDEF_USE_ALPHA_TEST; if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) @@ -2580,57 +2075,47 @@ shaderProgram_t *GLSL_GetGenericShaderProgram(int stage) if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2) shaderAttribs |= GENERICDEF_USE_DEFORM_VERTEXES; - switch (pStage->rgbGen) - { - case CGEN_LIGHTING_DIFFUSE: - shaderAttribs |= GENERICDEF_USE_RGBAGEN; - break; - default: - break; + switch (pStage->rgbGen) { + case CGEN_LIGHTING_DIFFUSE: + shaderAttribs |= GENERICDEF_USE_RGBAGEN; + break; + default: + break; } - switch (pStage->alphaGen) - { - case AGEN_LIGHTING_SPECULAR: - case AGEN_PORTAL: - shaderAttribs |= GENERICDEF_USE_RGBAGEN; - break; - default: - break; + switch (pStage->alphaGen) { + case AGEN_LIGHTING_SPECULAR: + case AGEN_PORTAL: + shaderAttribs |= GENERICDEF_USE_RGBAGEN; + break; + default: + break; } - if (tess.fogNum && - pStage->adjustColorsForFog != ACFF_NONE && - r_drawfog->integer) + if (tess.fogNum && pStage->adjustColorsForFog != ACFF_NONE && r_drawfog->integer) shaderAttribs |= GENERICDEF_USE_FOG; - if (pStage->bundle[0].tcGen != TCGEN_TEXTURE) - { + if (pStage->bundle[0].tcGen != TCGEN_TEXTURE) { shaderAttribs |= GENERICDEF_USE_TCGEN_AND_TCMOD; } - if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) - { + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) { shaderAttribs |= GENERICDEF_USE_DEFORM_VERTEXES; } #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { shaderAttribs |= GENERICDEF_USE_VERTEX_ANIMATION; } #endif // REND2_SP - if (glState.skeletalAnimation) - { + if (glState.skeletalAnimation) { shaderAttribs |= GENERICDEF_USE_SKELETAL_ANIMATION; } - if (pStage->bundle[0].numTexMods) - { + if (pStage->bundle[0].numTexMods) { shaderAttribs |= GENERICDEF_USE_TCGEN_AND_TCMOD; } - if (pStage->glow) - { + if (pStage->glow) { shaderAttribs |= GENERICDEF_USE_GLOW_BUFFER; } diff --git a/codemp/rd-rend2/tr_glsl_parse.cpp b/codemp/rd-rend2/tr_glsl_parse.cpp index 94fdb9fb6b..3a8b98bc11 100644 --- a/codemp/rd-rend2/tr_glsl_parse.cpp +++ b/codemp/rd-rend2/tr_glsl_parse.cpp @@ -24,16 +24,12 @@ along with this program; if not, see . #include #endif -namespace -{ +namespace { -Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) -{ - for ( size_t i = 0; i < numBlocks; ++i ) - { +Block *FindBlock(const char *name, Block *blocks, size_t numBlocks) { + for (size_t i = 0; i < numBlocks; ++i) { Block *block = blocks + i; - if ( strncmp(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0 ) - { + if (strncmp(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0) { return block; } } @@ -43,57 +39,45 @@ Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) // [M] strncpy_s is not present on linux and VS only function #if !defined(_WIN32) -void strncpy_s( char *dest, size_t destSize, const char *src, size_t srcSize ) -{ +void strncpy_s(char *dest, size_t destSize, const char *src, size_t srcSize) { // This isn't really a safe version, but I know the inputs to expect. size_t len = std::min(srcSize, destSize); memcpy(dest, src, len); - if ( (destSize - len) > 0 ) + if ((destSize - len) > 0) memset(dest + len, 0, destSize - len); } #endif +} // namespace -} - -GPUProgramDesc ParseProgramSource( Allocator& allocator, const char *text ) -{ +GPUProgramDesc ParseProgramSource(Allocator &allocator, const char *text) { int numBlocks = 0; Block blocks[MAX_BLOCKS]; Block *prevBlock = nullptr; int i = 0; int line = 1; - while ( text[i] ) - { - if ( strncmp(text + i, "/*[", 3) == 0 ) - { + while (text[i]) { + if (strncmp(text + i, "/*[", 3) == 0) { int startHeaderTitle = i + 3; int endHeaderTitle = -1; int endHeaderText = -1; int j = startHeaderTitle; - while ( text[j] ) - { - if ( text[j] == ']' ) - { + while (text[j]) { + if (text[j] == ']') { endHeaderTitle = j; - } - else if ( strncmp(text + j, "*/\n", 3) == 0 ) - { + } else if (strncmp(text + j, "*/\n", 3) == 0) { endHeaderText = j; line++; break; - } - else if ( text[j] == '\n' ) - { + } else if (text[j] == '\n') { line++; } ++j; } - if ( endHeaderTitle == -1 || endHeaderText == -1 ) - { + if (endHeaderTitle == -1 || endHeaderText == -1) { #if defined(GLSL_BUILDTOOL) std::cerr << "Unclosed block marker\n"; #else @@ -111,39 +95,31 @@ GPUProgramDesc ParseProgramSource( Allocator& allocator, const char *text ) block->blockTextLength = 0; block->blockTextFirstLine = line; - if ( prevBlock ) - { + if (prevBlock) { prevBlock->blockTextLength = (text + i) - prevBlock->blockText; } prevBlock = block; i = endHeaderText + 3; continue; - } - else if ( text[i] == '\n' ) - { + } else if (text[i] == '\n') { line++; } ++i; } - if ( prevBlock ) - { + if (prevBlock) { prevBlock->blockTextLength = (text + i) - prevBlock->blockText; } - static const char *shaderBlockNames[GPUSHADER_TYPE_COUNT] = { - "Vertex", "Fragment", "Geometry" - }; + static const char *shaderBlockNames[GPUSHADER_TYPE_COUNT] = {"Vertex", "Fragment", "Geometry"}; GPUProgramDesc theProgram = {}; const Block *parsedBlocks[GPUSHADER_TYPE_COUNT] = {}; - for ( const auto& shaderBlockName : shaderBlockNames ) - { + for (const auto &shaderBlockName : shaderBlockNames) { Block *block = FindBlock(shaderBlockName, blocks, numBlocks); - if ( block ) - { + if (block) { parsedBlocks[theProgram.numShaders++] = block; } } @@ -151,25 +127,17 @@ GPUProgramDesc ParseProgramSource( Allocator& allocator, const char *text ) theProgram.shaders = ojkAllocArray(allocator, theProgram.numShaders); int shaderIndex = 0; - for ( int shaderType = 0; - shaderType < theProgram.numShaders; - ++shaderType ) - { + for (int shaderType = 0; shaderType < theProgram.numShaders; ++shaderType) { const Block *block = parsedBlocks[shaderType]; - if ( !block ) - { + if (!block) { continue; } char *source = ojkAllocString(allocator, block->blockTextLength); - strncpy_s( - source, - block->blockTextLength + 1, - block->blockText, - block->blockTextLength); + strncpy_s(source, block->blockTextLength + 1, block->blockText, block->blockTextLength); - GPUShaderDesc& shaderDesc = theProgram.shaders[shaderIndex]; + GPUShaderDesc &shaderDesc = theProgram.shaders[shaderIndex]; shaderDesc.type = static_cast(shaderType); shaderDesc.source = source; shaderDesc.firstLineNumber = block->blockTextFirstLine; diff --git a/codemp/rd-rend2/tr_image.cpp b/codemp/rd-rend2/tr_image.cpp index b2ae7ec4af..4c495add35 100644 --- a/codemp/rd-rend2/tr_image.cpp +++ b/codemp/rd-rend2/tr_image.cpp @@ -23,33 +23,30 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" #include "glext.h" -static byte s_intensitytable[256]; +static byte s_intensitytable[256]; static unsigned char s_gammatable[256]; -int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; -int gl_filter_max = GL_LINEAR; +int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; +int gl_filter_max = GL_LINEAR; #define FILE_HASH_SIZE 1553 // Prime numbers are a good size for hash tables :) #define NUM_IMAGES_PER_POOL_ALLOC 512 -static struct ImagesPool -{ +static struct ImagesPool { image_t *pPool; ImagesPool *pNext; -} *imagesPool; +} * imagesPool; static image_t *hashTable[FILE_HASH_SIZE]; /* Extends the size of the images pool allocator */ -static void R_ExtendImagesPool() -{ +static void R_ExtendImagesPool() { ImagesPool *pool = (ImagesPool *)Z_Malloc(sizeof(*pool), TAG_GENERAL); image_t *freeImages = (image_t *)Z_Malloc(sizeof(*freeImages) * NUM_IMAGES_PER_POOL_ALLOC, TAG_IMAGE_T); - for ( int i = 0; i < (NUM_IMAGES_PER_POOL_ALLOC - 1); i++ ) - { + for (int i = 0; i < (NUM_IMAGES_PER_POOL_ALLOC - 1); i++) { freeImages[i].poolNext = &freeImages[i + 1]; } freeImages[NUM_IMAGES_PER_POOL_ALLOC - 1].poolNext = tr.imagesFreeList; @@ -64,45 +61,45 @@ static void R_ExtendImagesPool() /* ** R_GammaCorrect */ -void R_GammaCorrect( byte *buffer, int bufSize ) { +void R_GammaCorrect(byte *buffer, int bufSize) { int i; - for ( i = 0; i < bufSize; i++ ) { + for (i = 0; i < bufSize; i++) { buffer[i] = s_gammatable[buffer[i]]; } } typedef struct { const char *name; - int minimize, maximize; + int minimize, maximize; } textureMode_t; -textureMode_t modes[] = { - {"GL_NEAREST", GL_NEAREST, GL_NEAREST}, - {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR} -}; +textureMode_t modes[] = {{"GL_NEAREST", GL_NEAREST, GL_NEAREST}, + {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}}; /* ================ return a hash value for the filename ================ */ -static long generateHashValue( const char *fname ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower(fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } @@ -114,47 +111,41 @@ static long generateHashValue( const char *fname ) { GL_TextureMode =============== */ -void GL_TextureMode( const char *string ) { - int i; - image_t *glt; +void GL_TextureMode(const char *string) { + int i; + image_t *glt; - for ( i=0 ; i< 6 ; i++ ) { - if ( !Q_stricmp( modes[i].name, string ) ) { + for (i = 0; i < 6; i++) { + if (!Q_stricmp(modes[i].name, string)) { break; } } - - if ( i == 6 ) { - ri.Printf (PRINT_ALL, "bad filter name\n"); + if (i == 6) { + ri.Printf(PRINT_ALL, "bad filter name\n"); return; } gl_filter_min = modes[i].minimize; gl_filter_max = modes[i].maximize; - - if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) - { - ri.Cvar_SetValue ("r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy); + + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) { + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy); } // change all the existing mipmap texture objects glt = tr.images; - for ( i = 0 ; i < tr.numImages ; i++, glt = glt->poolNext ) { - if ( glt->flags & IMGFLAG_MIPMAP ) { - GL_Bind (glt); + for (i = 0; i < tr.numImages; i++, glt = glt->poolNext) { + if (glt->flags & IMGFLAG_MIPMAP) { + GL_Bind(glt); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - - if ( r_ext_texture_filter_anisotropic->value > 0.0f ) - { - if ( glConfig.maxTextureFilterAnisotropy > 1.0f ) - { - qglTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); - } - else - { - qglTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); + + if (r_ext_texture_filter_anisotropic->value > 0.0f) { + if (glConfig.maxTextureFilterAnisotropy > 1.0f) { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); + } else { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } } } @@ -166,14 +157,14 @@ void GL_TextureMode( const char *string ) { R_SumOfUsedImages =============== */ -int R_SumOfUsedImages( void ) { - int total; +int R_SumOfUsedImages(void) { + int total; int i; image_t *image = tr.images; total = 0; - for ( i = 0; i < tr.numImages; i++, image = image->poolNext ) { - if ( image->frameUsed == tr.frameCount ) { + for (i = 0; i < tr.numImages; i++, image = image->poolNext) { + if (image->frameUsed == tr.frameCount) { total += image->uploadWidth * image->uploadHeight; } } @@ -181,25 +172,21 @@ int R_SumOfUsedImages( void ) { return total; } -static float GetReadableSize( int bytes, const char **units ) -{ +static float GetReadableSize(int bytes, const char **units) { float result = bytes; *units = "b "; - if (result >= 1024.0f) - { + if (result >= 1024.0f) { result /= 1024.0f; *units = "kb"; } - if (result >= 1024.0f) - { + if (result >= 1024.0f) { result /= 1024.0f; *units = "Mb"; } - if (result >= 1024.0f) - { + if (result >= 1024.0f) { result /= 1024.0f; *units = "Gb"; } @@ -212,7 +199,7 @@ static float GetReadableSize( int bytes, const char **units ) R_ImageList_f =============== */ -void R_ImageList_f( void ) { +void R_ImageList_f(void) { int i; int estTotalSize = 0; const char *sizeSuffix; @@ -220,86 +207,84 @@ void R_ImageList_f( void ) { ri.Printf(PRINT_ALL, "\n -w-- -h-- type -size- --name-------\n"); - for ( i = 0 ; i < tr.numImages ; i++, image = image->poolNext ) - { + for (i = 0; i < tr.numImages; i++, image = image->poolNext) { const char *format = "???? "; int estSize; estSize = image->uploadHeight * image->uploadWidth; - switch(image->internalFormat) - { - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: - format = "sDXT1"; - // 64 bits per 16 pixels, so 4 bits per pixel - estSize /= 2; - break; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: - format = "sDXT5"; - // 128 bits per 16 pixels, so 1 byte per pixel - break; - case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: - format = "sBPTC"; - // 128 bits per 16 pixels, so 1 byte per pixel - break; - case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: - format = "LATC "; - // 128 bits per 16 pixels, so 1 byte per pixel - break; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - format = "DXT1 "; - // 64 bits per 16 pixels, so 4 bits per pixel - estSize /= 2; - break; - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - format = "DXT5 "; - // 128 bits per 16 pixels, so 1 byte per pixel - break; - case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: - format = "BPTC "; - // 128 bits per 16 pixels, so 1 byte per pixel - break; - case GL_RGB4_S3TC: - format = "S3TC "; - // same as DXT1? - estSize /= 2; - break; - case GL_RGBA4: - case GL_RGBA8: - case GL_RGBA: - format = "RGBA "; - // 4 bytes per pixel - estSize *= 4; - break; - case GL_RGB5: - case GL_RGB8: - case GL_RGB: - format = "RGB "; - // 3 bytes per pixel? - estSize *= 3; - break; - case GL_SRGB: - case GL_SRGB8: - format = "sRGB "; - // 3 bytes per pixel? - estSize *= 3; - break; - case GL_SRGB_ALPHA: - case GL_SRGB8_ALPHA8: - format = "sRGBA"; - // 4 bytes per pixel? - estSize *= 4; - break; - case GL_DEPTH_COMPONENT24: - format = "D24 "; - break; + switch (image->internalFormat) { + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: + format = "sDXT1"; + // 64 bits per 16 pixels, so 4 bits per pixel + estSize /= 2; + break; + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: + format = "sDXT5"; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: + format = "sBPTC"; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: + format = "LATC "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + format = "DXT1 "; + // 64 bits per 16 pixels, so 4 bits per pixel + estSize /= 2; + break; + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + format = "DXT5 "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + format = "BPTC "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_RGB4_S3TC: + format = "S3TC "; + // same as DXT1? + estSize /= 2; + break; + case GL_RGBA4: + case GL_RGBA8: + case GL_RGBA: + format = "RGBA "; + // 4 bytes per pixel + estSize *= 4; + break; + case GL_RGB5: + case GL_RGB8: + case GL_RGB: + format = "RGB "; + // 3 bytes per pixel? + estSize *= 3; + break; + case GL_SRGB: + case GL_SRGB8: + format = "sRGB "; + // 3 bytes per pixel? + estSize *= 3; + break; + case GL_SRGB_ALPHA: + case GL_SRGB8_ALPHA8: + format = "sRGBA"; + // 4 bytes per pixel? + estSize *= 4; + break; + case GL_DEPTH_COMPONENT24: + format = "D24 "; + break; } // mipmap adds about 50% if (image->flags & IMGFLAG_MIPMAP) estSize += estSize / 2; - float printSize = GetReadableSize(estSize, &sizeSuffix); + float printSize = GetReadableSize(estSize, &sizeSuffix); ri.Printf(PRINT_ALL, "%4i: %4ix%4i %s %7.2f%s %s\n", i, image->uploadWidth, image->uploadHeight, format, printSize, sizeSuffix, image->imgName); estTotalSize += estSize; @@ -307,9 +292,9 @@ void R_ImageList_f( void ) { float printSize = GetReadableSize(estTotalSize, &sizeSuffix); - ri.Printf (PRINT_ALL, " ---------\n"); - ri.Printf (PRINT_ALL, " approx %i bytes (%.2f%s)\n", estTotalSize, printSize, sizeSuffix); - ri.Printf (PRINT_ALL, " %i total images\n\n", tr.numImages ); + ri.Printf(PRINT_ALL, " ---------\n"); + ri.Printf(PRINT_ALL, " approx %i bytes (%.2f%s)\n", estTotalSize, printSize, sizeSuffix); + ri.Printf(PRINT_ALL, " %i total images\n\n", tr.numImages); } //======================================================================= @@ -323,61 +308,57 @@ Used to resample images in a more general than quartering fashion. This will only be filtered properly if the resampled size is greater than half the original size. -If a larger shrinking is needed, use the mipmap function +If a larger shrinking is needed, use the mipmap function before or after. ================ */ -static void ResampleTexture( byte *in, int inwidth, int inheight, byte *out, - int outwidth, int outheight ) { - int i, j; - byte *inrow, *inrow2; - int frac, fracstep; - int p1[2048], p2[2048]; - byte *pix1, *pix2, *pix3, *pix4; - - if (outwidth>2048) +static void ResampleTexture(byte *in, int inwidth, int inheight, byte *out, int outwidth, int outheight) { + int i, j; + byte *inrow, *inrow2; + int frac, fracstep; + int p1[2048], p2[2048]; + byte *pix1, *pix2, *pix3, *pix4; + + if (outwidth > 2048) ri.Error(ERR_DROP, "ResampleTexture: max width"); - - fracstep = inwidth*0x10000/outwidth; - frac = fracstep>>2; - for ( i=0 ; i>16); + fracstep = inwidth * 0x10000 / outwidth; + + frac = fracstep >> 2; + for (i = 0; i < outwidth; i++) { + p1[i] = 4 * (frac >> 16); frac += fracstep; } - frac = 3*(fracstep>>2); - for ( i=0 ; i>16); + frac = 3 * (fracstep >> 2); + for (i = 0; i < outwidth; i++) { + p2[i] = 4 * (frac >> 16); frac += fracstep; } - for (i=0 ; i>2; - *out++ = (pix1[1] + pix2[1] + pix3[1] + pix4[1])>>2; - *out++ = (pix1[2] + pix2[2] + pix3[2] + pix4[2])>>2; - *out++ = (pix1[3] + pix2[3] + pix3[3] + pix4[3])>>2; + *out++ = (pix1[0] + pix2[0] + pix3[0] + pix4[0]) >> 2; + *out++ = (pix1[1] + pix2[1] + pix3[1] + pix4[1]) >> 2; + *out++ = (pix1[2] + pix2[2] + pix3[2] + pix4[2]) >> 2; + *out++ = (pix1[3] + pix2[3] + pix3[3] + pix4[3]) >> 2; } } } -static void RGBAtoYCoCgA(const byte *in, byte *out, int width, int height) -{ +static void RGBAtoYCoCgA(const byte *in, byte *out, int width, int height) { int x, y; - for (y = 0; y < height; y++) - { - const byte *inbyte = in + y * width * 4; - byte *outbyte = out + y * width * 4; + for (y = 0; y < height; y++) { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { byte r, g, b, a, rb2; r = *inbyte++; @@ -386,7 +367,7 @@ static void RGBAtoYCoCgA(const byte *in, byte *out, int width, int height) a = *inbyte++; rb2 = (r + b) >> 1; - *outbyte++ = (g + rb2) >> 1; // Y = R/4 + G/2 + B/4 + *outbyte++ = (g + rb2) >> 1; // Y = R/4 + G/2 + B/4 *outbyte++ = (r - b + 256) >> 1; // Co = R/2 - B/2 *outbyte++ = (g - rb2 + 256) >> 1; // Cg = -R/4 + G/2 - B/4 *outbyte++ = a; @@ -394,81 +375,68 @@ static void RGBAtoYCoCgA(const byte *in, byte *out, int width, int height) } } -static void YCoCgAtoRGBA(const byte *in, byte *out, int width, int height) -{ +static void YCoCgAtoRGBA(const byte *in, byte *out, int width, int height) { int x, y; - for (y = 0; y < height; y++) - { - const byte *inbyte = in + y * width * 4; - byte *outbyte = out + y * width * 4; + for (y = 0; y < height; y++) { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { byte _Y, Co, Cg, a; _Y = *inbyte++; Co = *inbyte++; Cg = *inbyte++; - a = *inbyte++; + a = *inbyte++; - *outbyte++ = CLAMP(_Y + Co - Cg, 0, 255); // R = Y + Co - Cg - *outbyte++ = CLAMP(_Y + Cg - 128, 0, 255); // G = Y + Cg + *outbyte++ = CLAMP(_Y + Co - Cg, 0, 255); // R = Y + Co - Cg + *outbyte++ = CLAMP(_Y + Cg - 128, 0, 255); // G = Y + Cg *outbyte++ = CLAMP(_Y - Co - Cg + 256, 0, 255); // B = Y - Co - Cg *outbyte++ = a; } } } - // uses a sobel filter to change a texture to a normal map -static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qboolean clampToEdge) -{ +static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qboolean clampToEdge) { int x, y, max; // convert to heightmap, storing in alpha // same as converting to Y in YCoCg max = 1; - for (y = 0; y < height; y++) - { - const byte *inbyte = in + y * width * 4; - byte *outbyte = out + y * width * 4 + 3; + for (y = 0; y < height; y++) { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4 + 3; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { byte result = (inbyte[0] >> 2) + (inbyte[1] >> 1) + (inbyte[2] >> 2); result = result * result / 255; // Make linear *outbyte = result; max = MAX(max, *outbyte); outbyte += 4; - inbyte += 4; + inbyte += 4; } } // level out heights - if (max < 255) - { - for (y = 0; y < height; y++) - { + if (max < 255) { + for (y = 0; y < height; y++) { byte *outbyte = out + y * width * 4 + 3; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { *outbyte = *outbyte + (255 - max); outbyte += 4; } } } - // now run sobel filter over height values to generate X and Y // then normalize - for (y = 0; y < height; y++) - { + for (y = 0; y < height; y++) { byte *outbyte = out + y * width * 4; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { // 0 1 2 // 3 4 5 // 6 7 8 @@ -478,30 +446,21 @@ static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qbool vec3_t normal; i = 0; - for (y2 = -1; y2 <= 1; y2++) - { + for (y2 = -1; y2 <= 1; y2++) { int src_y = y + y2; - if (clampToEdge) - { + if (clampToEdge) { src_y = CLAMP(src_y, 0, height - 1); - } - else - { + } else { src_y = (src_y + height) % height; } - - for (x2 = -1; x2 <= 1; x2++) - { + for (x2 = -1; x2 <= 1; x2++) { int src_x = x + x2; - if (clampToEdge) - { + if (clampToEdge) { src_x = CLAMP(src_x, 0, width - 1); - } - else - { + } else { src_x = (src_x + width) % width; } @@ -509,18 +468,15 @@ static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qbool } } - normal[0] = s[0] - s[2] - + 2 * s[3] - 2 * s[5] - + s[6] - s[8]; + normal[0] = s[0] - s[2] + 2 * s[3] - 2 * s[5] + s[6] - s[8]; - normal[1] = s[0] + 2 * s[1] + s[2] + normal[1] = s[0] + 2 * s[1] + s[2] - - s[6] - 2 * s[7] - s[8]; + - s[6] - 2 * s[7] - s[8]; normal[2] = s[4] * 4; - if (!VectorNormalize2(normal, normal)) - { + if (!VectorNormalize2(normal, normal)) { VectorSet(normal, 0, 0, 1); } @@ -532,34 +488,30 @@ static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qbool } } -#define COPYSAMPLE(a,b) *(unsigned int *)(a) = *(unsigned int *)(b) +#define COPYSAMPLE(a, b) *(unsigned int *)(a) = *(unsigned int *)(b) // based on Fast Curve Based Interpolation // from Fast Artifacts-Free Image Interpolation (http://www.andreagiachetti.it/icbi/) // assumes data has a 2 pixel thick border of clamped or wrapped data // expects data to be a grid with even (0, 0), (2, 0), (0, 2), (2, 2) etc pixels filled // only performs FCBI on specified component -static void DoFCBI(byte *in, byte *out, int width, int height, int component) -{ +static void DoFCBI(byte *in, byte *out, int width, int height, int component) { int x, y; byte *outbyte, *inbyte; // copy in to out - for (y = 2; y < height - 2; y += 2) - { - inbyte = in + (y * width + 2) * 4 + component; + for (y = 2; y < height - 2; y += 2) { + inbyte = in + (y * width + 2) * 4 + component; outbyte = out + (y * width + 2) * 4 + component; - for (x = 2; x < width - 2; x += 2) - { + for (x = 2; x < width - 2; x += 2) { *outbyte = *inbyte; outbyte += 8; inbyte += 8; } } - - for (y = 3; y < height - 3; y += 2) - { + + for (y = 3; y < height - 3; y += 2) { // diagonals // // NWp - northwest interpolated pixel @@ -604,8 +556,8 @@ static void DoFCBI(byte *in, byte *out, int width, int height, int component) // optimization one // SAMPLE2(sa, x-1, y-3); - //SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); - //SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); + // SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); + // SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); // SAMPLE2(sk, x-1, y+3); // optimization two @@ -615,62 +567,74 @@ static void DoFCBI(byte *in, byte *out, int width, int height, int component) line4 = in + ((y + 3) * width + (x - 1)) * 4 + component; // COPYSAMPLE(sa, line1); line1 += 8; - //COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; COPYSAMPLE(se, line2); line2 += 8; - //COPYSAMPLE(sg, line3); line3 += 8; COPYSAMPLE(sh, line3); line3 += 8; COPYSAMPLE(si, line3); line3 += 8; + // COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; COPYSAMPLE(se, line2); line2 += 8; + // COPYSAMPLE(sg, line3); line3 += 8; COPYSAMPLE(sh, line3); line3 += 8; COPYSAMPLE(si, line3); line3 += 8; // COPYSAMPLE(sk, line4); line4 += 8; - sa = *line1; line1 += 8; - sc = *line2; line2 += 8; sd = *line2; line2 += 8; se = *line2; line2 += 8; - sg = *line3; line3 += 8; sh = *line3; line3 += 8; si = *line3; line3 += 8; - sk = *line4; line4 += 8; + sa = *line1; + line1 += 8; + sc = *line2; + line2 += 8; + sd = *line2; + line2 += 8; + se = *line2; + line2 += 8; + sg = *line3; + line3 += 8; + sh = *line3; + line3 += 8; + si = *line3; + line3 += 8; + sk = *line4; + line4 += 8; outbyte = out + (y * width + x) * 4 + component; - for ( ; x < width - 3; x += 2) - { + for (; x < width - 3; x += 2) { int NWd, NEd, NWp, NEp; // original // SAMPLE2(sa, x-1, y-3); SAMPLE2(sb, x+1, y-3); - //SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); SAMPLE2(sf, x+3, y-1); - //SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); SAMPLE2(sj, x+3, y+1); + // SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); SAMPLE2(sf, x+3, y-1); + // SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); SAMPLE2(sj, x+3, y+1); // SAMPLE2(sk, x-1, y+3); SAMPLE2(sl, x+1, y+3); // optimization one - //SAMPLE2(sb, x+1, y-3); - //SAMPLE2(sf, x+3, y-1); - //SAMPLE2(sj, x+3, y+1); - //SAMPLE2(sl, x+1, y+3); + // SAMPLE2(sb, x+1, y-3); + // SAMPLE2(sf, x+3, y-1); + // SAMPLE2(sj, x+3, y+1); + // SAMPLE2(sl, x+1, y+3); // optimization two - //COPYSAMPLE(sb, line1); line1 += 8; - //COPYSAMPLE(sf, line2); line2 += 8; - //COPYSAMPLE(sj, line3); line3 += 8; - //COPYSAMPLE(sl, line4); line4 += 8; - - sb = *line1; line1 += 8; - sf = *line2; line2 += 8; - sj = *line3; line3 += 8; - sl = *line4; line4 += 8; + // COPYSAMPLE(sb, line1); line1 += 8; + // COPYSAMPLE(sf, line2); line2 += 8; + // COPYSAMPLE(sj, line3); line3 += 8; + // COPYSAMPLE(sl, line4); line4 += 8; + + sb = *line1; + line1 += 8; + sf = *line2; + line2 += 8; + sj = *line3; + line3 += 8; + sl = *line4; + line4 += 8; NWp = sd + si; NEp = se + sh; NWd = abs(sd - si); NEd = abs(se - sh); - if (NWd > 100 || NEd > 100 || abs(NWp-NEp) > 200) - { + if (NWd > 100 || NEd > 100 || abs(NWp - NEp) > 200) { if (NWd < NEd) *outbyte = NWp >> 1; else *outbyte = NEp >> 1; - } - else - { + } else { int NWdd, NEdd; - //NEdd = abs(sg + sd + sb - 3 * (se + sh) + sk + si + sf); - //NWdd = abs(sa + se + sj - 3 * (sd + si) + sc + sh + sl); + // NEdd = abs(sg + sd + sb - 3 * (se + sh) + sk + si + sf); + // NWdd = abs(sa + se + sj - 3 * (sd + si) + sc + sh + sl); NEdd = abs(sg + sb - 3 * NEp + sk + sf + NWp); NWdd = abs(sa + sj - 3 * NWp + sc + sl + NEp); @@ -683,33 +647,34 @@ static void DoFCBI(byte *in, byte *out, int width, int height, int component) outbyte += 8; // COPYSAMPLE(sa, sb); - //COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); COPYSAMPLE(se, sf); - //COPYSAMPLE(sg, sh); COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); + // COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); COPYSAMPLE(se, sf); + // COPYSAMPLE(sg, sh); COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); // COPYSAMPLE(sk, sl); - sa = sb; - sc = sd; sd = se; se = sf; - sg = sh; sh = si; si = sj; - sk = sl; + sa = sb; + sc = sd; + sd = se; + se = sf; + sg = sh; + sh = si; + si = sj; + sk = sl; } } // hack: copy out to in again - for (y = 3; y < height - 3; y += 2) - { + for (y = 3; y < height - 3; y += 2) { inbyte = out + (y * width + 3) * 4 + component; outbyte = in + (y * width + 3) * 4 + component; - for (x = 3; x < width - 3; x += 2) - { + for (x = 3; x < width - 3; x += 2) { *outbyte = *inbyte; outbyte += 8; inbyte += 8; } } - - for (y = 2; y < height - 3; y++) - { + + for (y = 2; y < height - 3; y++) { // horizontal & vertical // // hp - horizontally interpolated pixel @@ -745,131 +710,139 @@ static void DoFCBI(byte *in, byte *out, int width, int height, int component) byte sa, sb, sc, sd, se, sf, sg, sh, si, sj, sk, sl; byte *line1, *line2, *line3, *line4, *line5; - //x = (y + 1) % 2; + // x = (y + 1) % 2; x = (y + 1) % 2 + 2; - + // optimization one // SAMPLE2(sa, x-1, y-2); - //SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); + // SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); // SAMPLE2(sf, x-1, y ); - //SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); + // SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); // SAMPLE2(sk, x-1, y+2); line1 = in + ((y - 2) * width + (x - 1)) * 4 + component; line2 = in + ((y - 1) * width + (x - 2)) * 4 + component; - line3 = in + ((y ) * width + (x - 1)) * 4 + component; + line3 = in + ((y)*width + (x - 1)) * 4 + component; line4 = in + ((y + 1) * width + (x - 2)) * 4 + component; line5 = in + ((y + 2) * width + (x - 1)) * 4 + component; // COPYSAMPLE(sa, line1); line1 += 8; - //COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; + // COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; // COPYSAMPLE(sf, line3); line3 += 8; - //COPYSAMPLE(sh, line4); line4 += 8; COPYSAMPLE(si, line4); line4 += 8; - // COPYSAMPLE(sk, line5); line5 += 8; - - sa = *line1; line1 += 8; - sc = *line2; line2 += 8; sd = *line2; line2 += 8; - sf = *line3; line3 += 8; - sh = *line4; line4 += 8; si = *line4; line4 += 8; - sk = *line5; line5 += 8; + // COPYSAMPLE(sh, line4); line4 += 8; COPYSAMPLE(si, line4); line4 += 8; + // COPYSAMPLE(sk, line5); line5 += 8; + + sa = *line1; + line1 += 8; + sc = *line2; + line2 += 8; + sd = *line2; + line2 += 8; + sf = *line3; + line3 += 8; + sh = *line4; + line4 += 8; + si = *line4; + line4 += 8; + sk = *line5; + line5 += 8; outbyte = out + (y * width + x) * 4 + component; - for ( ; x < width - 3; x+=2) - { + for (; x < width - 3; x += 2) { int hd, vd, hp, vp; // SAMPLE2(sa, x-1, y-2); SAMPLE2(sb, x+1, y-2); - //SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); SAMPLE2(se, x+2, y-1); + // SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); SAMPLE2(se, x+2, y-1); // SAMPLE2(sf, x-1, y ); SAMPLE2(sg, x+1, y ); - //SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); SAMPLE2(sj, x+2, y+1); + // SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); SAMPLE2(sj, x+2, y+1); // SAMPLE2(sk, x-1, y+2); SAMPLE2(sl, x+1, y+2); // optimization one - //SAMPLE2(sb, x+1, y-2); - //SAMPLE2(se, x+2, y-1); - //SAMPLE2(sg, x+1, y ); - //SAMPLE2(sj, x+2, y+1); - //SAMPLE2(sl, x+1, y+2); - - //COPYSAMPLE(sb, line1); line1 += 8; - //COPYSAMPLE(se, line2); line2 += 8; - //COPYSAMPLE(sg, line3); line3 += 8; - //COPYSAMPLE(sj, line4); line4 += 8; - //COPYSAMPLE(sl, line5); line5 += 8; - - sb = *line1; line1 += 8; - se = *line2; line2 += 8; - sg = *line3; line3 += 8; - sj = *line4; line4 += 8; - sl = *line5; line5 += 8; - - hp = sf + sg; + // SAMPLE2(sb, x+1, y-2); + // SAMPLE2(se, x+2, y-1); + // SAMPLE2(sg, x+1, y ); + // SAMPLE2(sj, x+2, y+1); + // SAMPLE2(sl, x+1, y+2); + + // COPYSAMPLE(sb, line1); line1 += 8; + // COPYSAMPLE(se, line2); line2 += 8; + // COPYSAMPLE(sg, line3); line3 += 8; + // COPYSAMPLE(sj, line4); line4 += 8; + // COPYSAMPLE(sl, line5); line5 += 8; + + sb = *line1; + line1 += 8; + se = *line2; + line2 += 8; + sg = *line3; + line3 += 8; + sj = *line4; + line4 += 8; + sl = *line5; + line5 += 8; + + hp = sf + sg; vp = sd + si; hd = abs(sf - sg); vd = abs(sd - si); - if (hd > 100 || vd > 100 || abs(hp-vp) > 200) - { + if (hd > 100 || vd > 100 || abs(hp - vp) > 200) { if (hd < vd) *outbyte = hp >> 1; else *outbyte = vp >> 1; - } - else - { + } else { int hdd, vdd; - //hdd = abs(sc[i] + sd[i] + se[i] - 3 * (sf[i] + sg[i]) + sh[i] + si[i] + sj[i]); - //vdd = abs(sa[i] + sf[i] + sk[i] - 3 * (sd[i] + si[i]) + sb[i] + sg[i] + sl[i]); + // hdd = abs(sc[i] + sd[i] + se[i] - 3 * (sf[i] + sg[i]) + sh[i] + si[i] + sj[i]); + // vdd = abs(sa[i] + sf[i] + sk[i] - 3 * (sd[i] + si[i]) + sb[i] + sg[i] + sl[i]); hdd = abs(sc + se - 3 * hp + sh + sj + vp); vdd = abs(sa + sk - 3 * vp + sb + sl + hp); if (hdd > vdd) *outbyte = hp >> 1; - else + else *outbyte = vp >> 1; } outbyte += 8; // COPYSAMPLE(sa, sb); - //COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); + // COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); // COPYSAMPLE(sf, sg); - //COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); + // COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); // COPYSAMPLE(sk, sl); - sa = sb; - sc = sd; sd = se; - sf = sg; - sh = si; si = sj; - sk = sl; + sa = sb; + sc = sd; + sd = se; + sf = sg; + sh = si; + si = sj; + sk = sl; } } } // Similar to FCBI, but throws out the second order derivatives for speed -static void DoFCBIQuick(byte *in, byte *out, int width, int height, int component) -{ +static void DoFCBIQuick(byte *in, byte *out, int width, int height, int component) { int x, y; byte *outbyte, *inbyte; // copy in to out - for (y = 2; y < height - 2; y += 2) - { - inbyte = in + (y * width + 2) * 4 + component; + for (y = 2; y < height - 2; y += 2) { + inbyte = in + (y * width + 2) * 4 + component; outbyte = out + (y * width + 2) * 4 + component; - for (x = 2; x < width - 2; x += 2) - { + for (x = 2; x < width - 2; x += 2) { *outbyte = *inbyte; outbyte += 8; inbyte += 8; } } - for (y = 3; y < height - 4; y += 2) - { + for (y = 3; y < height - 4; y += 2) { byte sd, se, sh, si; byte *line2, *line3; @@ -878,17 +851,20 @@ static void DoFCBIQuick(byte *in, byte *out, int width, int height, int componen line2 = in + ((y - 1) * width + (x - 1)) * 4 + component; line3 = in + ((y + 1) * width + (x - 1)) * 4 + component; - sd = *line2; line2 += 8; - sh = *line3; line3 += 8; + sd = *line2; + line2 += 8; + sh = *line3; + line3 += 8; outbyte = out + (y * width + x) * 4 + component; - for ( ; x < width - 4; x += 2) - { + for (; x < width - 4; x += 2) { int NWd, NEd, NWp, NEp; - se = *line2; line2 += 8; - si = *line3; line3 += 8; + se = *line2; + line2 += 8; + si = *line3; + line3 += 8; NWp = sd + si; NEp = se + sh; @@ -908,43 +884,43 @@ static void DoFCBIQuick(byte *in, byte *out, int width, int height, int componen } // hack: copy out to in again - for (y = 3; y < height - 3; y += 2) - { - inbyte = out + (y * width + 3) * 4 + component; - outbyte = in + (y * width + 3) * 4 + component; + for (y = 3; y < height - 3; y += 2) { + inbyte = out + (y * width + 3) * 4 + component; + outbyte = in + (y * width + 3) * 4 + component; - for (x = 3; x < width - 3; x += 2) - { + for (x = 3; x < width - 3; x += 2) { *outbyte = *inbyte; outbyte += 8; inbyte += 8; } } - - for (y = 2; y < height - 3; y++) - { + + for (y = 2; y < height - 3; y++) { byte sd, sf, sg, si; byte *line2, *line3, *line4; x = (y + 1) % 2 + 2; - line2 = in + ((y - 1) * width + (x )) * 4 + component; - line3 = in + ((y ) * width + (x - 1)) * 4 + component; - line4 = in + ((y + 1) * width + (x )) * 4 + component; + line2 = in + ((y - 1) * width + (x)) * 4 + component; + line3 = in + ((y)*width + (x - 1)) * 4 + component; + line4 = in + ((y + 1) * width + (x)) * 4 + component; outbyte = out + (y * width + x) * 4 + component; - sf = *line3; line3 += 8; + sf = *line3; + line3 += 8; - for ( ; x < width - 3; x+=2) - { + for (; x < width - 3; x += 2) { int hd, vd, hp, vp; - sd = *line2; line2 += 8; - sg = *line3; line3 += 8; - si = *line4; line4 += 8; - - hp = sf + sg; + sd = *line2; + line2 += 8; + sg = *line3; + line3 += 8; + si = *line4; + line4 += 8; + + hp = sf + sg; vp = sd + si; hd = abs(sf - sg); vd = abs(sd - si); @@ -963,29 +939,25 @@ static void DoFCBIQuick(byte *in, byte *out, int width, int height, int componen // Similar to DoFCBIQuick, but just takes the average instead of checking derivatives // as well, this operates on all four components -static void DoLinear(byte *in, byte *out, int width, int height) -{ +static void DoLinear(byte *in, byte *out, int width, int height) { int x, y, i; byte *outbyte, *inbyte; // copy in to out - for (y = 2; y < height - 2; y += 2) - { + for (y = 2; y < height - 2; y += 2) { x = 2; - inbyte = in + (y * width + x) * 4; + inbyte = in + (y * width + x) * 4; outbyte = out + (y * width + x) * 4; - for ( ; x < width - 2; x += 2) - { + for (; x < width - 2; x += 2) { COPYSAMPLE(outbyte, inbyte); outbyte += 8; inbyte += 8; } } - for (y = 1; y < height - 1; y += 2) - { + for (y = 1; y < height - 1; y += 2) { byte sd[4] = {0}, se[4] = {0}, sh[4] = {0}, si[4] = {0}; byte *line2, *line3; @@ -994,18 +966,20 @@ static void DoLinear(byte *in, byte *out, int width, int height) line2 = in + ((y - 1) * width + (x - 1)) * 4; line3 = in + ((y + 1) * width + (x - 1)) * 4; - COPYSAMPLE(sd, line2); line2 += 8; - COPYSAMPLE(sh, line3); line3 += 8; + COPYSAMPLE(sd, line2); + line2 += 8; + COPYSAMPLE(sh, line3); + line3 += 8; outbyte = out + (y * width + x) * 4; - for ( ; x < width - 1; x += 2) - { - COPYSAMPLE(se, line2); line2 += 8; - COPYSAMPLE(si, line3); line3 += 8; + for (; x < width - 1; x += 2) { + COPYSAMPLE(se, line2); + line2 += 8; + COPYSAMPLE(si, line3); + line3 += 8; - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { *outbyte++ = (sd[i] + si[i] + se[i] + sh[i]) >> 2; } @@ -1017,44 +991,43 @@ static void DoLinear(byte *in, byte *out, int width, int height) } // hack: copy out to in again - for (y = 1; y < height - 1; y += 2) - { + for (y = 1; y < height - 1; y += 2) { x = 1; - inbyte = out + (y * width + x) * 4; - outbyte = in + (y * width + x) * 4; + inbyte = out + (y * width + x) * 4; + outbyte = in + (y * width + x) * 4; - for ( ; x < width - 1; x += 2) - { + for (; x < width - 1; x += 2) { COPYSAMPLE(outbyte, inbyte); outbyte += 8; inbyte += 8; } } - - for (y = 1; y < height - 1; y++) - { + + for (y = 1; y < height - 1; y++) { byte sd[4], sf[4], sg[4], si[4]; byte *line2, *line3, *line4; x = y % 2 + 1; - line2 = in + ((y - 1) * width + (x )) * 4; - line3 = in + ((y ) * width + (x - 1)) * 4; - line4 = in + ((y + 1) * width + (x )) * 4; + line2 = in + ((y - 1) * width + (x)) * 4; + line3 = in + ((y)*width + (x - 1)) * 4; + line4 = in + ((y + 1) * width + (x)) * 4; - COPYSAMPLE(sf, line3); line3 += 8; + COPYSAMPLE(sf, line3); + line3 += 8; outbyte = out + (y * width + x) * 4; - for ( ; x < width - 1; x += 2) - { - COPYSAMPLE(sd, line2); line2 += 8; - COPYSAMPLE(sg, line3); line3 += 8; - COPYSAMPLE(si, line4); line4 += 8; + for (; x < width - 1; x += 2) { + COPYSAMPLE(sd, line2); + line2 += 8; + COPYSAMPLE(sg, line3); + line3 += 8; + COPYSAMPLE(si, line4); + line4 += 8; - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { *outbyte++ = (sf[i] + sg[i] + sd[i] + si[i]) >> 2; } @@ -1065,18 +1038,14 @@ static void DoLinear(byte *in, byte *out, int width, int height) } } - -static void ExpandHalfTextureToGrid( byte *data, int width, int height) -{ +static void ExpandHalfTextureToGrid(byte *data, int width, int height) { int x, y; - for (y = height / 2; y > 0; y--) - { - byte *outbyte = data + ((y * 2 - 1) * (width) - 2) * 4; - byte *inbyte = data + (y * (width / 2) - 1) * 4; + for (y = height / 2; y > 0; y--) { + byte *outbyte = data + ((y * 2 - 1) * (width)-2) * 4; + byte *inbyte = data + (y * (width / 2) - 1) * 4; - for (x = width / 2; x > 0; x--) - { + for (x = width / 2; x > 0; x--) { COPYSAMPLE(outbyte, inbyte); outbyte -= 8; @@ -1085,24 +1054,21 @@ static void ExpandHalfTextureToGrid( byte *data, int width, int height) } } -static void FillInNormalizedZ(const byte *in, byte *out, int width, int height) -{ +static void FillInNormalizedZ(const byte *in, byte *out, int width, int height) { int x, y; - for (y = 0; y < height; y++) - { - const byte *inbyte = in + y * width * 4; - byte *outbyte = out + y * width * 4; + for (y = 0; y < height; y++) { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { byte nx, ny, nz, h; float fnx, fny, fll, fnz; nx = *inbyte++; ny = *inbyte++; inbyte++; - h = *inbyte++; + h = *inbyte++; fnx = OffsetByteToFloat(nx); fny = OffsetByteToFloat(ny); @@ -1122,15 +1088,13 @@ static void FillInNormalizedZ(const byte *in, byte *out, int width, int height) } } - // size must be even -#define WORKBLOCK_SIZE 128 -#define WORKBLOCK_BORDER 4 +#define WORKBLOCK_SIZE 128 +#define WORKBLOCK_BORDER 4 #define WORKBLOCK_REALSIZE (WORKBLOCK_SIZE + WORKBLOCK_BORDER * 2) // assumes that data has already been expanded into a 2x2 grid -static void FCBIByBlock(byte *data, int width, int height, qboolean clampToEdge, qboolean normalized) -{ +static void FCBIByBlock(byte *data, int width, int height, qboolean clampToEdge, qboolean normalized) { byte workdata[WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4]; byte outdata[WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4]; byte *inbyte, *outbyte; @@ -1139,48 +1103,38 @@ static void FCBIByBlock(byte *data, int width, int height, qboolean clampToEdge, ExpandHalfTextureToGrid(data, width, height); - for (y = 0; y < height; y += WORKBLOCK_SIZE) - { - for (x = 0; x < width; x += WORKBLOCK_SIZE) - { + for (y = 0; y < height; y += WORKBLOCK_SIZE) { + for (x = 0; x < width; x += WORKBLOCK_SIZE) { int x2, y2; int workwidth, workheight, fullworkwidth, fullworkheight; - workwidth = MIN(WORKBLOCK_SIZE, width - x); + workwidth = MIN(WORKBLOCK_SIZE, width - x); workheight = MIN(WORKBLOCK_SIZE, height - y); - fullworkwidth = workwidth + WORKBLOCK_BORDER * 2; + fullworkwidth = workwidth + WORKBLOCK_BORDER * 2; fullworkheight = workheight + WORKBLOCK_BORDER * 2; - //memset(workdata, 0, WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4); + // memset(workdata, 0, WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4); // fill in work block - for (y2 = 0; y2 < fullworkheight; y2 += 2) - { + for (y2 = 0; y2 < fullworkheight; y2 += 2) { srcy = y + y2 - WORKBLOCK_BORDER; - if (clampToEdge) - { + if (clampToEdge) { srcy = CLAMP(srcy, 0, height - 2); - } - else - { + } else { srcy = (srcy + height) % height; } - outbyte = workdata + y2 * fullworkwidth * 4; - inbyte = data + srcy * width * 4; + outbyte = workdata + y2 * fullworkwidth * 4; + inbyte = data + srcy * width * 4; - for (x2 = 0; x2 < fullworkwidth; x2 += 2) - { + for (x2 = 0; x2 < fullworkwidth; x2 += 2) { srcx = x + x2 - WORKBLOCK_BORDER; - if (clampToEdge) - { + if (clampToEdge) { srcx = CLAMP(srcx, 0, width - 2); - } - else - { + } else { srcx = (srcx + width) % width; } @@ -1192,46 +1146,39 @@ static void FCBIByBlock(byte *data, int width, int height, qboolean clampToEdge, // submit work block DoLinear(workdata, outdata, fullworkwidth, fullworkheight); - if (!normalized) - { - switch (r_imageUpsampleType->integer) - { - case 0: - break; - case 1: - DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); - break; - case 2: - default: - DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); - break; + if (!normalized) { + switch (r_imageUpsampleType->integer) { + case 0: + break; + case 1: + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); + break; + case 2: + default: + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); + break; } - } - else - { - switch (r_imageUpsampleType->integer) - { - case 0: - break; - case 1: - DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); - DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 1); - break; - case 2: - default: - DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); - DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 1); - break; + } else { + switch (r_imageUpsampleType->integer) { + case 0: + break; + case 1: + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 1); + break; + case 2: + default: + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 1); + break; } } // copy back work block - for (y2 = 0; y2 < workheight; y2++) - { + for (y2 = 0; y2 < workheight; y2++) { inbyte = outdata + ((y2 + WORKBLOCK_BORDER) * fullworkwidth + WORKBLOCK_BORDER) * 4; - outbyte = data + ((y + y2) * width + x) * 4; - for (x2 = 0; x2 < workwidth; x2++) - { + outbyte = data + ((y + y2) * width + x) * 4; + for (x2 = 0; x2 < workwidth; x2++) { COPYSAMPLE(outbyte, inbyte); outbyte += 4; inbyte += 4; @@ -1250,48 +1197,37 @@ Scale up the pixel values in a texture to increase the lighting range ================ */ -void R_LightScaleTexture (byte *in, int inwidth, int inheight, qboolean only_gamma ) -{ - if ( only_gamma ) - { - if ( !glConfig.deviceSupportsGamma ) - { - int i, c; - byte *p; +void R_LightScaleTexture(byte *in, int inwidth, int inheight, qboolean only_gamma) { + if (only_gamma) { + if (!glConfig.deviceSupportsGamma) { + int i, c; + byte *p; p = in; - c = inwidth*inheight; - for (i=0 ; i> 1; outHeight = inHeight >> 1; - temp = (unsigned int *)ri.Hunk_AllocateTempMemory( outWidth * outHeight * 4 ); + temp = (unsigned int *)ri.Hunk_AllocateTempMemory(outWidth * outHeight * 4); inWidthMask = inWidth - 1; inHeightMask = inHeight - 1; - for ( i = 0 ; i < outHeight ; i++ ) { - for ( j = 0 ; j < outWidth ; j++ ) { - outpix = (byte *) ( temp + i * outWidth + j ); - for ( k = 0 ; k < 4 ; k++ ) { - total = - 1 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + - 1 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + - - 2 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + - 4 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + - 4 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + - - 2 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + - 4 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + - 4 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + - - 1 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + - 2 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + - 1 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k]; + for (i = 0; i < outHeight; i++) { + for (j = 0; j < outWidth; j++) { + outpix = (byte *)(temp + i * outWidth + j); + for (k = 0; k < 4; k++) { + total = 1 * (&in[4 * (((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask))])[k] + + 1 * (&in[4 * (((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask))])[k] + + + 2 * (&in[4 * (((i * 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask))])[k] + + 4 * (&in[4 * (((i * 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask))])[k] + + 4 * (&in[4 * (((i * 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask))])[k] + + + 2 * (&in[4 * (((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask))])[k] + + 4 * (&in[4 * (((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask))])[k] + + 4 * (&in[4 * (((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask))])[k] + + + 1 * (&in[4 * (((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask))])[k] + + 2 * (&in[4 * (((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask))])[k] + + 1 * (&in[4 * (((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask))])[k]; outpix[k] = total / 36; } } } - Com_Memcpy( in, temp, outWidth * outHeight * 4 ); - ri.Hunk_FreeTempMemory( temp ); + Com_Memcpy(in, temp, outWidth * outHeight * 4); + ri.Hunk_FreeTempMemory(temp); } +static void R_MipMapsRGB(byte *in, int inWidth, int inHeight) { + int i, j, k; + int outWidth, outHeight; + byte *temp; -static void R_MipMapsRGB( byte *in, int inWidth, int inHeight) -{ - int i, j, k; - int outWidth, outHeight; - byte *temp; - - if ( r_simpleMipMaps->integer ) + if (r_simpleMipMaps->integer) return; outWidth = inWidth >> 1; outHeight = inHeight >> 1; - temp = (byte *)ri.Hunk_AllocateTempMemory( outWidth * outHeight * 4 ); - - for ( i = 0 ; i < outHeight ; i++ ) { - byte *outbyte = temp + ( i * outWidth ) * 4; - byte *inbyte1 = in + ( i * 2 * inWidth ) * 4; - byte *inbyte2 = in + ( (i * 2 + 1) * inWidth ) * 4; - for ( j = 0 ; j < outWidth ; j++ ) { - for ( k = 0 ; k < 3 ; k++ ) { + temp = (byte *)ri.Hunk_AllocateTempMemory(outWidth * outHeight * 4); + + for (i = 0; i < outHeight; i++) { + byte *outbyte = temp + (i * outWidth) * 4; + byte *inbyte1 = in + (i * 2 * inWidth) * 4; + byte *inbyte2 = in + ((i * 2 + 1) * inWidth) * 4; + for (j = 0; j < outWidth; j++) { + for (k = 0; k < 3; k++) { float total, current; - current = ByteToFloat(inbyte1[0]); total = sRGBtoRGB((double)current); - current = ByteToFloat(inbyte1[4]); total += sRGBtoRGB((double)current); - current = ByteToFloat(inbyte2[0]); total += sRGBtoRGB((double)current); - current = ByteToFloat(inbyte2[4]); total += sRGBtoRGB((double)current); + current = ByteToFloat(inbyte1[0]); + total = sRGBtoRGB((double)current); + current = ByteToFloat(inbyte1[4]); + total += sRGBtoRGB((double)current); + current = ByteToFloat(inbyte2[0]); + total += sRGBtoRGB((double)current); + current = ByteToFloat(inbyte2[4]); + total += sRGBtoRGB((double)current); total *= 0.25f; @@ -1398,8 +1334,8 @@ static void R_MipMapsRGB( byte *in, int inWidth, int inHeight) } } - Com_Memcpy( in, temp, outWidth * outHeight * 4 ); - ri.Hunk_FreeTempMemory( temp ); + Com_Memcpy(in, temp, outWidth * outHeight * 4); + ri.Hunk_FreeTempMemory(temp); } /* @@ -1409,22 +1345,19 @@ R_MipMap Operates in place, quartering the size of the texture ================ */ -static void R_MipMap (byte *in, int width, int height) { - - if ( !r_simpleMipMaps->integer ) - R_MipMap2( in, width, height ); +static void R_MipMap(byte *in, int width, int height) { + if (!r_simpleMipMaps->integer) + R_MipMap2(in, width, height); } +static void R_MipMapLuminanceAlpha(const byte *in, byte *out, int width, int height) { + int i, j, row; -static void R_MipMapLuminanceAlpha (const byte *in, byte *out, int width, int height) -{ - int i, j, row; - - if ( r_simpleMipMaps->integer ) + if (r_simpleMipMaps->integer) return; - if ( width == 1 && height == 1 ) { + if (width == 1 && height == 1) { return; } @@ -1432,83 +1365,75 @@ static void R_MipMapLuminanceAlpha (const byte *in, byte *out, int width, int he width >>= 1; height >>= 1; - if ( width == 0 || height == 0 ) { - width += height; // get largest - for (i=0 ; i> 1; + if (width == 0 || height == 0) { + width += height; // get largest + for (i = 0; i < width; i++, out += 4, in += 8) { + out[0] = out[1] = out[2] = (in[0] + in[4]) >> 1; out[3] = (in[3] + in[7]) >> 1; } return; } - for (i=0 ; i> 2; - out[3] = (in[3] + in[7] + in[row+3] + in[row+7]) >> 2; + for (i = 0; i < height; i++, in += row) { + for (j = 0; j < width; j++, out += 4, in += 8) { + out[0] = out[1] = out[2] = (in[0] + in[4] + in[row] + in[row + 4]) >> 2; + out[3] = (in[3] + in[7] + in[row + 3] + in[row + 7]) >> 2; } } - } - -static void R_MipMapNormalHeight (const byte *in, byte *out, int width, int height, qboolean swizzle) -{ - int i, j; - int row; +static void R_MipMapNormalHeight(const byte *in, byte *out, int width, int height, qboolean swizzle) { + int i, j; + int row; int sx = swizzle ? 3 : 0; int sa = swizzle ? 0 : 3; - if ( r_simpleMipMaps->integer ) + if (r_simpleMipMaps->integer) return; - if ( width == 1 && height == 1 ) { + if (width == 1 && height == 1) { return; } row = width * 4; width >>= 1; height >>= 1; - - for (i=0 ; i> 9; - data[1] = ( data[1] * inverseAlpha + premult[1] ) >> 9; - data[2] = ( data[2] * inverseAlpha + premult[2] ) >> 9; + for (i = 0; i < pixelCount; i++, data += 4) { + data[0] = (data[0] * inverseAlpha + premult[0]) >> 9; + data[1] = (data[1] * inverseAlpha + premult[1]) >> 9; + data[2] = (data[2] * inverseAlpha + premult[2]) >> 9; } } -byte mipBlendColors[16][4] = { - {0,0,0,0}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, +byte mipBlendColors[16][4] = { + {0, 0, 0, 0}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, + {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, }; -static void RawImage_SwizzleRA( byte *data, int width, int height ) -{ +static void RawImage_SwizzleRA(byte *data, int width, int height) { int i; byte *ptr = data, swap; - for (i=0; iinteger && scaled_width > width ) + if (r_roundImagesDown->integer && scaled_width > width) scaled_width >>= 1; - if ( r_roundImagesDown->integer && scaled_height > height ) + if (r_roundImagesDown->integer && scaled_height > height) scaled_height >>= 1; - if ( picmip && data && resampledBuffer && r_imageUpsample->integer && - scaled_width < r_imageUpsampleMaxSize->integer && scaled_height < r_imageUpsampleMaxSize->integer) - { + if (picmip && data && resampledBuffer && r_imageUpsample->integer && scaled_width < r_imageUpsampleMaxSize->integer && + scaled_height < r_imageUpsampleMaxSize->integer) { int finalwidth, finalheight; - //int startTime, endTime; + // int startTime, endTime; - //startTime = ri.Milliseconds(); + // startTime = ri.Milliseconds(); finalwidth = scaled_width << r_imageUpsample->integer; finalheight = scaled_height << r_imageUpsample->integer; - while ( finalwidth > r_imageUpsampleMaxSize->integer - || finalheight > r_imageUpsampleMaxSize->integer ) { + while (finalwidth > r_imageUpsampleMaxSize->integer || finalheight > r_imageUpsampleMaxSize->integer) { finalwidth >>= 1; finalheight >>= 1; } - while ( finalwidth > glConfig.maxTextureSize - || finalheight > glConfig.maxTextureSize ) { + while (finalwidth > glConfig.maxTextureSize || finalheight > glConfig.maxTextureSize) { finalwidth >>= 1; finalheight >>= 1; } - *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory( finalwidth * finalheight * 4 ); + *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory(finalwidth * finalheight * 4); - if (scaled_width != width || scaled_height != height) - { - ResampleTexture (*data, width, height, *resampledBuffer, scaled_width, scaled_height); - } - else - { + if (scaled_width != width || scaled_height != height) { + ResampleTexture(*data, width, height, *resampledBuffer, scaled_width, scaled_height); + } else { byte *inbyte, *outbyte; int i; inbyte = *data; outbyte = *resampledBuffer; - for (i = width * height * 4; i > 0; i--) - { + for (i = width * height * 4; i > 0; i--) { *outbyte++ = *inbyte++; } } @@ -1648,37 +1546,30 @@ static void RawImage_ScaleToPower2( byte **data, int *inout_width, int *inout_he if (type == IMGTYPE_COLORALPHA) RGBAtoYCoCgA(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); - while (scaled_width < finalwidth || scaled_height < finalheight) - { + while (scaled_width < finalwidth || scaled_height < finalheight) { scaled_width <<= 1; scaled_height <<= 1; FCBIByBlock(*resampledBuffer, scaled_width, scaled_height, clampToEdge, (qboolean)(type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT)); } - if (type == IMGTYPE_COLORALPHA) - { + if (type == IMGTYPE_COLORALPHA) { YCoCgAtoRGBA(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); - } - else if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) - { + } else if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) { FillInNormalizedZ(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); } + // endTime = ri.Milliseconds(); - //endTime = ri.Milliseconds(); - - //ri.Printf(PRINT_ALL, "upsampled %dx%d to %dx%d in %dms\n", width, height, scaled_width, scaled_height, endTime - startTime); + // ri.Printf(PRINT_ALL, "upsampled %dx%d to %dx%d in %dms\n", width, height, scaled_width, scaled_height, endTime - startTime); *data = *resampledBuffer; width = scaled_width; height = scaled_height; - } - else if ( scaled_width != width || scaled_height != height ) { - if (data && resampledBuffer) - { - *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory( scaled_width * scaled_height * 4 ); - ResampleTexture (*data, width, height, *resampledBuffer, scaled_width, scaled_height); + } else if (scaled_width != width || scaled_height != height) { + if (data && resampledBuffer) { + *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory(scaled_width * scaled_height * 4); + ResampleTexture(*data, width, height, *resampledBuffer, scaled_width, scaled_height); *data = *resampledBuffer; } width = scaled_width; @@ -1688,7 +1579,7 @@ static void RawImage_ScaleToPower2( byte **data, int *inout_width, int *inout_he // // perform optional picmip operation // - if ( picmip ) { + if (picmip) { scaled_width >>= r_picmip->integer; scaled_height >>= r_picmip->integer; } @@ -1708,30 +1599,25 @@ static void RawImage_ScaleToPower2( byte **data, int *inout_width, int *inout_he // scale both axis down equally so we don't have to // deal with a half mip resampling // - while ( scaled_width > glConfig.maxTextureSize - || scaled_height > glConfig.maxTextureSize ) { + while (scaled_width > glConfig.maxTextureSize || scaled_height > glConfig.maxTextureSize) { scaled_width >>= 1; scaled_height >>= 1; } - *inout_width = width; - *inout_height = height; - *inout_scaled_width = scaled_width; + *inout_width = width; + *inout_height = height; + *inout_scaled_width = scaled_width; *inout_scaled_height = scaled_height; } - -static qboolean RawImage_HasAlpha(const byte *scan, int numPixels) -{ +static qboolean RawImage_HasAlpha(const byte *scan, int numPixels) { int i; if (!scan) return qtrue; - for ( i = 0; i < numPixels; i++ ) - { - if ( scan[i*4 + 3] != 255 ) - { + for (i = 0; i < numPixels; i++) { + if (scan[i * 4 + 3] != 255) { return qtrue; } } @@ -1739,58 +1625,40 @@ static qboolean RawImage_HasAlpha(const byte *scan, int numPixels) return qfalse; } -static GLenum RawImage_GetFormat(const byte *data, int numPixels, qboolean lightMap, imgType_t type, int flags) -{ +static GLenum RawImage_GetFormat(const byte *data, int numPixels, qboolean lightMap, imgType_t type, int flags) { int samples = 3; GLenum internalFormat = GL_RGB8; qboolean forceNoCompression = (qboolean)(flags & IMGFLAG_NO_COMPRESSION); qboolean normalmap = (qboolean)(type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT); - if(normalmap) - { - if ((!RawImage_HasAlpha(data, numPixels) || (type == IMGTYPE_NORMAL)) && !forceNoCompression && (glRefConfig.textureCompression & TCR_LATC)) - { + if (normalmap) { + if ((!RawImage_HasAlpha(data, numPixels) || (type == IMGTYPE_NORMAL)) && !forceNoCompression && (glRefConfig.textureCompression & TCR_LATC)) { internalFormat = GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; - } - else - { - if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) - { + } else { + if (!forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB) { internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - } - else if ( r_texturebits->integer == 16 ) - { + } else if (r_texturebits->integer == 16) { internalFormat = GL_RGBA4; - } - else if ( r_texturebits->integer == 32 ) - { + } else if (r_texturebits->integer == 32) { internalFormat = GL_RGBA8; - } - else - { + } else { internalFormat = GL_RGBA8; } } - } - else if(lightMap) - { + } else if (lightMap) { #if 0 if(r_greyscale->integer) internalFormat = GL_LUMINANCE; else #endif - internalFormat = GL_RGBA; - } - else - { - if (RawImage_HasAlpha(data, numPixels)) - { + internalFormat = GL_RGBA; + } else { + if (RawImage_HasAlpha(data, numPixels)) { samples = 4; } // select proper internal format - if ( samples == 3 ) - { + if (samples == 3) { #if 0 if(r_greyscale->integer) { @@ -1804,34 +1672,21 @@ static GLenum RawImage_GetFormat(const byte *data, int numPixels, qboolean light else #endif { - if ( !forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC) ) - { + if (!forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC)) { internalFormat = GL_COMPRESSED_RGBA_BPTC_UNORM_ARB; - } - else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) - { + } else if (!forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB) { internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - } - else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC ) - { + } else if (!forceNoCompression && glConfig.textureCompression == TC_S3TC) { internalFormat = GL_RGB4_S3TC; - } - else if ( r_texturebits->integer == 16 ) - { + } else if (r_texturebits->integer == 16) { internalFormat = GL_RGB5; - } - else if ( r_texturebits->integer == 32 ) - { + } else if (r_texturebits->integer == 32) { internalFormat = GL_RGB8; - } - else - { + } else { internalFormat = GL_RGB8; } } - } - else if ( samples == 4 ) - { + } else if (samples == 4) { #if 0 if(r_greyscale->integer) { @@ -1845,115 +1700,93 @@ static GLenum RawImage_GetFormat(const byte *data, int numPixels, qboolean light else #endif { - if ( !forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC) ) - { + if (!forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC)) { internalFormat = GL_COMPRESSED_RGBA_BPTC_UNORM_ARB; - } - else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) - { + } else if (!forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB) { internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - } - else if ( r_texturebits->integer == 16 ) - { + } else if (r_texturebits->integer == 16) { internalFormat = GL_RGBA4; - } - else if ( r_texturebits->integer == 32 ) - { + } else if (r_texturebits->integer == 32) { internalFormat = GL_RGBA8; - } - else - { + } else { internalFormat = GL_RGBA8; } } } - if (flags & IMGFLAG_SRGB) - { - switch(internalFormat) - { - case GL_RGB: - internalFormat = GL_SRGB8; - break; + if (flags & IMGFLAG_SRGB) { + switch (internalFormat) { + case GL_RGB: + internalFormat = GL_SRGB8; + break; - case GL_RGB4: - case GL_RGB5: - case GL_RGB8: - internalFormat = GL_SRGB8; - break; + case GL_RGB4: + case GL_RGB5: + case GL_RGB8: + internalFormat = GL_SRGB8; + break; - case GL_RGBA: - internalFormat = GL_SRGB_ALPHA; - break; + case GL_RGBA: + internalFormat = GL_SRGB_ALPHA; + break; - case GL_RGBA4: - case GL_RGBA8: - internalFormat = GL_SRGB8_ALPHA8; - break; + case GL_RGBA4: + case GL_RGBA8: + internalFormat = GL_SRGB8_ALPHA8; + break; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + break; - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - break; + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + break; - case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: - internalFormat = GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB; - break; + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB; + break; } } } return internalFormat; -} - -static int CalcNumMipmapLevels ( int width, int height ) -{ - return static_cast(ceil (log2 (Q_max (width, height))) + 1); -} - -static qboolean IsBPTCTextureFormat( GLenum internalformat ) -{ - switch ( internalformat ) - { - case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: - case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: - case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB: - case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB: - return qtrue; +} - default: - return qfalse; +static int CalcNumMipmapLevels(int width, int height) { return static_cast(ceil(log2(Q_max(width, height))) + 1); } + +static qboolean IsBPTCTextureFormat(GLenum internalformat) { + switch (internalformat) { + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: + case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB: + case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB: + return qtrue; + + default: + return qfalse; } } -static qboolean ShouldUseImmutableTextures(int imageFlags, GLenum internalformat) -{ - if ( glRefConfig.hardwareVendor == IHV_AMD ) - { +static qboolean ShouldUseImmutableTextures(int imageFlags, GLenum internalformat) { + if (glRefConfig.hardwareVendor == IHV_AMD) { // Corrupted texture data is seen when using BPTC + immutable textures - if ( IsBPTCTextureFormat( internalformat ) ) - { + if (IsBPTCTextureFormat(internalformat)) { return qfalse; } } - if ( imageFlags & IMGFLAG_MUTABLE ) - { + if (imageFlags & IMGFLAG_MUTABLE) { return qfalse; } return glRefConfig.immutableTextures; } -static void RawImage_UploadTexture( byte *data, int x, int y, int width, int height, GLenum internalFormat, imgType_t type, int flags, qboolean subtexture ) -{ +static void RawImage_UploadTexture(byte *data, int x, int y, int width, int height, GLenum internalFormat, imgType_t type, int flags, qboolean subtexture) { int dataFormat, dataType; - switch (internalFormat) - { + switch (internalFormat) { case GL_DEPTH_COMPONENT: case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: @@ -1987,62 +1820,43 @@ static void RawImage_UploadTexture( byte *data, int x, int y, int width, int hei break; } - if ( subtexture ) - { - qglTexSubImage2D (GL_TEXTURE_2D, 0, x, y, width, height, dataFormat, dataType, data); - } - else - { - if ( ShouldUseImmutableTextures( flags, internalFormat ) ) - { - int numLevels = (flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels (width, height) : 1; + if (subtexture) { + qglTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, dataFormat, dataType, data); + } else { + if (ShouldUseImmutableTextures(flags, internalFormat)) { + int numLevels = (flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels(width, height) : 1; - qglTexStorage2D (GL_TEXTURE_2D, numLevels, internalFormat, width, height); + qglTexStorage2D(GL_TEXTURE_2D, numLevels, internalFormat, width, height); - if ( data != NULL ) - { - qglTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, width, height, dataFormat, dataType, data); + if (data != NULL) { + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, dataFormat, dataType, data); } - } - else - { - qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, dataType, data ); + } else { + qglTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, dataType, data); } } - if ((flags & IMGFLAG_MIPMAP) && (!r_simpleMipMaps->integer) && - (data != NULL || !ShouldUseImmutableTextures(flags, internalFormat) )) - { + if ((flags & IMGFLAG_MIPMAP) && (!r_simpleMipMaps->integer) && (data != NULL || !ShouldUseImmutableTextures(flags, internalFormat))) { // Don't need to generate mipmaps if we are generating an immutable texture and // the data is NULL. All levels have already been allocated by glTexStorage2D. int miplevel = 0; - - while (width > 1 || height > 1) - { - if (data) - { - if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) - { - if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) - { - R_MipMapLuminanceAlpha( data, data, width, height ); - } - else - { - R_MipMapNormalHeight( data, data, width, height, qtrue); + + while (width > 1 || height > 1) { + if (data) { + if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) { + if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) { + R_MipMapLuminanceAlpha(data, data, width, height); + } else { + R_MipMapNormalHeight(data, data, width, height, qtrue); } - } - else if (flags & IMGFLAG_SRGB) - { - R_MipMapsRGB( data, width, height ); - } - else - { - R_MipMap( data, width, height ); + } else if (flags & IMGFLAG_SRGB) { + R_MipMapsRGB(data, width, height); + } else { + R_MipMap(data, width, height); } } - + width >>= 1; height >>= 1; if (width < 1) @@ -2051,34 +1865,25 @@ static void RawImage_UploadTexture( byte *data, int x, int y, int width, int hei height = 1; miplevel++; - if ( data && r_colorMipLevels->integer ) - R_BlendOverTexture( (byte *)data, width * height, mipBlendColors[miplevel] ); + if (data && r_colorMipLevels->integer) + R_BlendOverTexture((byte *)data, width * height, mipBlendColors[miplevel]); - if ( subtexture ) - { + if (subtexture) { x >>= 1; y >>= 1; - qglTexSubImage2D( GL_TEXTURE_2D, miplevel, x, y, width, height, dataFormat, dataType, data ); - } - else - { - if ( ShouldUseImmutableTextures(flags, internalFormat) ) - { - qglTexSubImage2D (GL_TEXTURE_2D, miplevel, 0, 0, width, height, dataFormat, dataType, data ); - } - else - { - qglTexImage2D (GL_TEXTURE_2D, miplevel, internalFormat, width, height, 0, dataFormat, dataType, data ); + qglTexSubImage2D(GL_TEXTURE_2D, miplevel, x, y, width, height, dataFormat, dataType, data); + } else { + if (ShouldUseImmutableTextures(flags, internalFormat)) { + qglTexSubImage2D(GL_TEXTURE_2D, miplevel, 0, 0, width, height, dataFormat, dataType, data); + } else { + qglTexImage2D(GL_TEXTURE_2D, miplevel, internalFormat, width, height, 0, dataFormat, dataType, data); } } } } } -static bool IsPowerOfTwo ( int i ) -{ - return (i & (i - 1)) == 0; -} +static bool IsPowerOfTwo(int i) { return (i & (i - 1)) == 0; } /* =============== @@ -2087,64 +1892,54 @@ Upload32 =============== */ extern qboolean charSet; -static void Upload32( byte *data, int width, int height, imgType_t type, int flags, - qboolean lightMap, GLenum internalFormat, int *pUploadWidth, int *pUploadHeight) -{ - byte *scaledBuffer = NULL; - byte *resampledBuffer = NULL; - int scaled_width = width; - int scaled_height = height; - int i, c; - byte *scan; - - if ( !IsPowerOfTwo (width) || !IsPowerOfTwo (height) ) - { +static void Upload32(byte *data, int width, int height, imgType_t type, int flags, qboolean lightMap, GLenum internalFormat, int *pUploadWidth, + int *pUploadHeight) { + byte *scaledBuffer = NULL; + byte *resampledBuffer = NULL; + int scaled_width = width; + int scaled_height = height; + int i, c; + byte *scan; + + if (!IsPowerOfTwo(width) || !IsPowerOfTwo(height)) { RawImage_ScaleToPower2(&data, &width, &height, &scaled_width, &scaled_height, type, flags, &resampledBuffer); } - scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory( sizeof( unsigned ) * scaled_width * scaled_height ); + scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory(sizeof(unsigned) * scaled_width * scaled_height); // // scan the texture for each channel's max values // and verify if the alpha channel is being used or not // - c = width*height; + c = width * height; scan = data; - - if( r_greyscale->integer ) - { - for ( i = 0; i < c; i++ ) - { - byte luma = LUMA(scan[i*4], scan[i*4 + 1], scan[i*4 + 2]); - scan[i*4] = luma; - scan[i*4 + 1] = luma; - scan[i*4 + 2] = luma; + + if (r_greyscale->integer) { + for (i = 0; i < c; i++) { + byte luma = LUMA(scan[i * 4], scan[i * 4 + 1], scan[i * 4 + 2]); + scan[i * 4] = luma; + scan[i * 4 + 1] = luma; + scan[i * 4 + 2] = luma; } - } - else if( r_greyscale->value ) - { - for ( i = 0; i < c; i++ ) - { - float luma = LUMA(scan[i*4], scan[i*4 + 1], scan[i*4 + 2]); - scan[i*4] = LERP(scan[i*4], luma, r_greyscale->value); - scan[i*4 + 1] = LERP(scan[i*4 + 1], luma, r_greyscale->value); - scan[i*4 + 2] = LERP(scan[i*4 + 2], luma, r_greyscale->value); + } else if (r_greyscale->value) { + for (i = 0; i < c; i++) { + float luma = LUMA(scan[i * 4], scan[i * 4 + 1], scan[i * 4 + 2]); + scan[i * 4] = LERP(scan[i * 4], luma, r_greyscale->value); + scan[i * 4 + 1] = LERP(scan[i * 4 + 1], luma, r_greyscale->value); + scan[i * 4 + 2] = LERP(scan[i * 4 + 2], luma, r_greyscale->value); } } // normals are always swizzled - if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) - { + if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) { RawImage_SwizzleRA(data, width, height); } // LATC2 is only used for normals - if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) - { + if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) { byte *in = data; int c = width * height; - while (c--) - { + while (c--) { in[0] = in[1]; in[2] = in[1]; in += 4; @@ -2152,47 +1947,40 @@ static void Upload32( byte *data, int width, int height, imgType_t type, int fla } // copy or resample data as appropriate for first MIP level - if ( ( scaled_width == width ) && - ( scaled_height == height ) ) { - if (!(flags & IMGFLAG_MIPMAP)) - { - RawImage_UploadTexture( data, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse ); - //qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + if ((scaled_width == width) && (scaled_height == height)) { + if (!(flags & IMGFLAG_MIPMAP)) { + RawImage_UploadTexture(data, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse); + // qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); *pUploadWidth = scaled_width; *pUploadHeight = scaled_height; goto done; } - Com_Memcpy (scaledBuffer, data, width*height*4); - } - else if ( !r_simpleMipMaps->integer ) - { + Com_Memcpy(scaledBuffer, data, width * height * 4); + } else if (!r_simpleMipMaps->integer) { // use the normal mip-mapping function to go down from here - while ( width > scaled_width || height > scaled_height ) { + while (width > scaled_width || height > scaled_height) { - if (flags & IMGFLAG_SRGB) - { - R_MipMapsRGB( (byte *)data, width, height ); - } - else - { - R_MipMap( (byte *)data, width, height ); + if (flags & IMGFLAG_SRGB) { + R_MipMapsRGB((byte *)data, width, height); + } else { + R_MipMap((byte *)data, width, height); } width >>= 1; height >>= 1; - if ( width < 1 ) { + if (width < 1) { width = 1; } - if ( height < 1 ) { + if (height < 1) { height = 1; } } - Com_Memcpy( scaledBuffer, data, width * height * 4 ); + Com_Memcpy(scaledBuffer, data, width * height * 4); } if (!(flags & IMGFLAG_NOLIGHTSCALE)) - R_LightScaleTexture (scaledBuffer, scaled_width, scaled_height, (qboolean)(!(flags & IMGFLAG_MIPMAP)) ); + R_LightScaleTexture(scaledBuffer, scaled_width, scaled_height, (qboolean)(!(flags & IMGFLAG_MIPMAP))); *pUploadWidth = scaled_width; *pUploadHeight = scaled_height; @@ -2201,36 +1989,29 @@ static void Upload32( byte *data, int width, int height, imgType_t type, int fla done: - if (flags & IMGFLAG_MIPMAP) - { - if (r_ext_texture_filter_anisotropic->value > 1.0f && glConfig.maxTextureFilterAnisotropy > 0.0f) - { - qglTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, - Com_Clamp( 1.0f, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->value ) ); + if (flags & IMGFLAG_MIPMAP) { + if (r_ext_texture_filter_anisotropic->value > 1.0f && glConfig.maxTextureFilterAnisotropy > 0.0f) { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, + Com_Clamp(1.0f, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->value)); } qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - } - else - { - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } else { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } GL_CheckErrors(); - if ( scaledBuffer != 0 ) - ri.Hunk_FreeTempMemory( scaledBuffer ); - if ( resampledBuffer != 0 ) - ri.Hunk_FreeTempMemory( resampledBuffer ); + if (scaledBuffer != 0) + ri.Hunk_FreeTempMemory(scaledBuffer); + if (resampledBuffer != 0) + ri.Hunk_FreeTempMemory(resampledBuffer); } - -static void EmptyTexture( int width, int height, imgType_t type, int flags, - qboolean lightMap, GLenum internalFormat, int *pUploadWidth, int *pUploadHeight ) -{ - int scaled_width, scaled_height; +static void EmptyTexture(int width, int height, imgType_t type, int flags, qboolean lightMap, GLenum internalFormat, int *pUploadWidth, int *pUploadHeight) { + int scaled_width, scaled_height; RawImage_ScaleToPower2(NULL, &width, &height, &scaled_width, &scaled_height, type, flags, NULL); @@ -2239,48 +2020,41 @@ static void EmptyTexture( int width, int height, imgType_t type, int flags, RawImage_UploadTexture(NULL, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse); - if (flags & IMGFLAG_MIPMAP) - { - if (r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0.0f) - { - qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, - (GLint)Com_Clamp( 1, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->integer ) ); + if (flags & IMGFLAG_MIPMAP) { + if (r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0.0f) { + qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, + (GLint)Com_Clamp(1, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->integer)); } qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - } - else - { - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } else { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // Fix for sampling depth buffer on old nVidia cards // from http://www.idevgames.com/forums/thread-4141-post-34844.html#pid34844 - switch(internalFormat) - { - case GL_DEPTH_COMPONENT: - case GL_DEPTH_COMPONENT16: - case GL_DEPTH_COMPONENT24: - case GL_DEPTH_COMPONENT32: - //qglTexParameterf(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE ); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - break; - default: - break; + switch (internalFormat) { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + // qglTexParameterf(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + break; + default: + break; } GL_CheckErrors(); } -static image_t *R_AllocImage() -{ +static image_t *R_AllocImage() { image_t *result; - if ( !tr.imagesFreeList ) - { + if (!tr.imagesFreeList) { R_ExtendImagesPool(); } @@ -2341,16 +2115,16 @@ R_CreateImage This is the only way any 2d image_t are created ================ */ -image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgType_t type, int flags, int internalFormat ) { - image_t *image; - qboolean isLightmap = qfalse; - long hash; - int glWrapClampMode; +image_t *R_CreateImage(const char *name, byte *pic, int width, int height, imgType_t type, int flags, int internalFormat) { + image_t *image; + qboolean isLightmap = qfalse; + long hash; + int glWrapClampMode; - if (strlen(name) >= MAX_QPATH ) { - ri.Error (ERR_DROP, "R_CreateImage: \"%s\" is too long", name); + if (strlen(name) >= MAX_QPATH) { + ri.Error(ERR_DROP, "R_CreateImage: \"%s\" is too long", name); } - if ( !strncmp( name, "*lightmap", 9 ) ) { + if (!strncmp(name, "*lightmap", 9)) { isLightmap = qtrue; } @@ -2360,7 +2134,7 @@ image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgT image->type = type; image->flags = flags; - Q_strncpyz (image->imgName, name, sizeof (image->imgName)); + Q_strncpyz(image->imgName, name, sizeof(image->imgName)); image->width = width; image->height = height; @@ -2369,8 +2143,7 @@ image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgT else glWrapClampMode = GL_REPEAT; - if (!internalFormat) - { + if (!internalFormat) { if (image->flags & IMGFLAG_CUBEMAP) internalFormat = r_hdr->integer ? GL_RGBA16F : GL_RGBA8; else @@ -2380,24 +2153,22 @@ image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgT image->internalFormat = internalFormat; // lightmaps are always allocated on TMU 1 - if ( isLightmap ) { + if (isLightmap) { image->TMU = 1; } else { image->TMU = 0; } - GL_SelectTexture( image->TMU ); + GL_SelectTexture(image->TMU); - if (image->flags & IMGFLAG_CUBEMAP) - { + if (image->flags & IMGFLAG_CUBEMAP) { GL_Bind(image); qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); int format = GL_BGRA; - switch (internalFormat) - { + switch (internalFormat) { case GL_DEPTH_COMPONENT: case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: @@ -2408,32 +2179,24 @@ image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgT break; } - if (image->flags & IMGFLAG_MIPMAP) - { + if (image->flags & IMGFLAG_MIPMAP) { qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - } - else - { + } else { qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - if ( ShouldUseImmutableTextures( image->flags, internalFormat ) ) - { - int numLevels = (image->flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels (width, height) : 1; + if (ShouldUseImmutableTextures(image->flags, internalFormat)) { + int numLevels = (image->flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels(width, height) : 1; - qglTexStorage2D (GL_TEXTURE_CUBE_MAP, numLevels, internalFormat, width, height); + qglTexStorage2D(GL_TEXTURE_CUBE_MAP, numLevels, internalFormat, width, height); - if ( pic != NULL ) - { - for ( int i = 0; i < 6; i++ ) - { - qglTexSubImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, pic); + if (pic != NULL) { + for (int i = 0; i < 6; i++) { + qglTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, pic); } } - } - else - { + } else { qglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); qglTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); qglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); @@ -2447,32 +2210,23 @@ image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgT image->uploadWidth = width; image->uploadHeight = height; - } - else - { + } else { GL_Bind(image); - if (pic) - { - Upload32( pic, image->width, image->height, image->type, image->flags, - isLightmap, image->internalFormat, &image->uploadWidth, - &image->uploadHeight ); - } - else - { - EmptyTexture(image->width, image->height, image->type, image->flags, - isLightmap, image->internalFormat, &image->uploadWidth, - &image->uploadHeight ); + if (pic) { + Upload32(pic, image->width, image->height, image->type, image->flags, isLightmap, image->internalFormat, &image->uploadWidth, &image->uploadHeight); + } else { + EmptyTexture(image->width, image->height, image->type, image->flags, isLightmap, image->internalFormat, &image->uploadWidth, &image->uploadHeight); } - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode); if (image->flags & IMGFLAG_MIPMAP && r_simpleMipMaps->integer) qglGenerateMipmap(GL_TEXTURE_2D); } - GL_SelectTexture( 0 ); + GL_SelectTexture(0); hash = generateHashValue(name); image->next = hashTable[hash]; @@ -2488,12 +2242,11 @@ R_Create2DImageArray This is the only way any 2d array sampler image_t are created ================ */ -image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height, int layers, imgType_t type, int flags, int internalFormat) -{ - image_t *image; - long hash; - int glWrapClampMode; - int format; +image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height, int layers, imgType_t type, int flags, int internalFormat) { + image_t *image; + long hash; + int glWrapClampMode; + int format; if (strlen(name) >= MAX_QPATH) { ri.Error(ERR_DROP, "R_Create2DImageArray: \"%s\" is too long", name); @@ -2517,8 +2270,7 @@ image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height else glWrapClampMode = GL_REPEAT; - switch (internalFormat) - { + switch (internalFormat) { case GL_DEPTH_COMPONENT: case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: @@ -2537,24 +2289,20 @@ image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height else qglTexImage3D(GL_TEXTURE_2D_ARRAY, 0, internalFormat, width, height, layers, 0, format, GL_UNSIGNED_BYTE, NULL); - switch (internalFormat) - { + switch (internalFormat) { case GL_DEPTH_COMPONENT: case GL_DEPTH_COMPONENT16: case GL_DEPTH_COMPONENT24: case GL_DEPTH_COMPONENT32: - + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - if (flags & IMGLFAG_SHADOWCOMP) - { + if (flags & IMGLFAG_SHADOWCOMP) { qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); qglTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); qglTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); - } - else - { + } else { qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } @@ -2577,109 +2325,95 @@ image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height return image; } -void R_UpdateSubImage( image_t *image, byte *pic, int x, int y, int width, int height ) -{ +void R_UpdateSubImage(image_t *image, byte *pic, int x, int y, int width, int height) { byte *scaledBuffer = NULL; byte *resampledBuffer = NULL; - int scaled_width, scaled_height, scaled_x, scaled_y; + int scaled_width, scaled_height, scaled_x, scaled_y; byte *data = pic; // normals are always swizzled - if (image->type == IMGTYPE_NORMAL || image->type == IMGTYPE_NORMALHEIGHT) - { + if (image->type == IMGTYPE_NORMAL || image->type == IMGTYPE_NORMALHEIGHT) { RawImage_SwizzleRA(pic, width, height); } // LATC2 is only used for normals - if (image->internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) - { + if (image->internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) { byte *in = data; int c = width * height; - while (c--) - { + while (c--) { in[0] = in[1]; in[2] = in[1]; in += 4; } } - RawImage_ScaleToPower2(&pic, &width, &height, &scaled_width, &scaled_height, image->type, image->flags, &resampledBuffer); - scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory( sizeof( unsigned ) * scaled_width * scaled_height ); + scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory(sizeof(unsigned) * scaled_width * scaled_height); - GL_SelectTexture( image->TMU ); - GL_Bind(image); + GL_SelectTexture(image->TMU); + GL_Bind(image); // copy or resample data as appropriate for first MIP level - if ( ( scaled_width == width ) && - ( scaled_height == height ) ) { - if (!(image->flags & IMGFLAG_MIPMAP)) - { + if ((scaled_width == width) && (scaled_height == height)) { + if (!(image->flags & IMGFLAG_MIPMAP)) { scaled_x = x * scaled_width / width; scaled_y = y * scaled_height / height; - RawImage_UploadTexture( data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue ); - //qglTexSubImage2D( GL_TEXTURE_2D, 0, scaled_x, scaled_y, scaled_width, scaled_height, GL_RGBA, GL_UNSIGNED_BYTE, data ); + RawImage_UploadTexture(data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue); + // qglTexSubImage2D( GL_TEXTURE_2D, 0, scaled_x, scaled_y, scaled_width, scaled_height, GL_RGBA, GL_UNSIGNED_BYTE, data ); GL_CheckErrors(); goto done; } - Com_Memcpy (scaledBuffer, data, width*height*4); - } - else if ( !r_simpleMipMaps->integer ) - { + Com_Memcpy(scaledBuffer, data, width * height * 4); + } else if (!r_simpleMipMaps->integer) { // use the normal mip-mapping function to go down from here - while ( width > scaled_width || height > scaled_height ) { + while (width > scaled_width || height > scaled_height) { - if (image->flags & IMGFLAG_SRGB) - { - R_MipMapsRGB( (byte *)data, width, height ); - } - else - { - R_MipMap( (byte *)data, width, height ); + if (image->flags & IMGFLAG_SRGB) { + R_MipMapsRGB((byte *)data, width, height); + } else { + R_MipMap((byte *)data, width, height); } width >>= 1; height >>= 1; x >>= 1; y >>= 1; - if ( width < 1 ) { + if (width < 1) { width = 1; } - if ( height < 1 ) { + if (height < 1) { height = 1; } } - Com_Memcpy( scaledBuffer, data, width * height * 4 ); - } - else if ( !r_simpleMipMaps->integer ) - { + Com_Memcpy(scaledBuffer, data, width * height * 4); + } else if (!r_simpleMipMaps->integer) { qglGenerateMipmap(GL_TEXTURE_2D); } if (!(image->flags & IMGFLAG_NOLIGHTSCALE)) - R_LightScaleTexture (scaledBuffer, scaled_width, scaled_height, (qboolean)(!(image->flags & IMGFLAG_MIPMAP)) ); + R_LightScaleTexture(scaledBuffer, scaled_width, scaled_height, (qboolean)(!(image->flags & IMGFLAG_MIPMAP))); scaled_x = x * scaled_width / width; scaled_y = y * scaled_height / height; - RawImage_UploadTexture( (byte *)data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue ); + RawImage_UploadTexture((byte *)data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue); done: - - GL_SelectTexture( 0 ); + + GL_SelectTexture(0); GL_CheckErrors(); - if ( scaledBuffer != 0 ) - ri.Hunk_FreeTempMemory( scaledBuffer ); - if ( resampledBuffer != 0 ) - ri.Hunk_FreeTempMemory( resampledBuffer ); + if (scaledBuffer != 0) + ri.Hunk_FreeTempMemory(scaledBuffer); + if (resampledBuffer != 0) + ri.Hunk_FreeTempMemory(resampledBuffer); } -image_t* R_GetLoadedImage(const char *name, int flags) { - long hash; - image_t *image; +image_t *R_GetLoadedImage(const char *name, int flags) { + long hash; + image_t *image; hash = generateHashValue(name); for (image = hashTable[hash]; image; image = image->next) { @@ -2696,11 +2430,10 @@ image_t* R_GetLoadedImage(const char *name, int flags) { return NULL; } -void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName, int flags) -{ - char packedName[MAX_QPATH]; - int packedWidth, packedHeight; - byte *packedPic; +void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName, int flags) { + char packedName[MAX_QPATH]; + int packedWidth, packedHeight; + byte *packedPic; image_t *image; if (!packedImageName) { @@ -2708,8 +2441,7 @@ void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName } float baseSpecularScale = 1.0f; - switch (stage->specularType) - { + switch (stage->specularType) { case SPEC_RMOS: case SPEC_MOSR: case SPEC_ORMS: @@ -2727,12 +2459,9 @@ void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName // see if the image is already loaded // image = R_GetLoadedImage(packedName, flags); - if (image != NULL) - { - // Don't scale occlusion, roughness and metalness - stage->specularScale[0] = - stage->specularScale[2] = - stage->specularScale[3] = 1.0f; + if (image != NULL) { + // Don't scale occlusion, roughness and metalness + stage->specularScale[0] = stage->specularScale[2] = stage->specularScale[3] = 1.0f; stage->specularScale[1] = baseSpecularScale; stage->bundle[TB_ORMSMAP].image[0] = image; @@ -2744,16 +2473,13 @@ void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName return; } - // Don't scale occlusion, roughness and metalness - stage->specularScale[0] = - stage->specularScale[2] = - stage->specularScale[3] = 1.0f; + // Don't scale occlusion, roughness and metalness + stage->specularScale[0] = stage->specularScale[2] = stage->specularScale[3] = 1.0f; stage->specularScale[1] = baseSpecularScale; - - GLint swizzle[4] = { GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; - switch (stage->specularType) - { + GLint swizzle[4] = {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}; + + switch (stage->specularType) { case SPEC_RMO: swizzle[0] = GL_BLUE; swizzle[1] = GL_RED; @@ -2790,11 +2516,10 @@ void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName Z_Free(packedPic); } -image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageName, int flags) -{ - char sdrName[MAX_QPATH]; - int specWidth, specHeight; - byte *specPic; +image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageName, int flags) { + char sdrName[MAX_QPATH]; + int specWidth, specHeight; + byte *specPic; image_t *image; if (!specImageName) @@ -2816,15 +2541,13 @@ image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageNam byte *sdrSpecPic = (byte *)ri.Hunk_AllocateTempMemory(sizeof(unsigned) * specWidth * specHeight); vec3_t currentColor; - for (int i = 0; i < specWidth * specHeight * 4; i += 4) - { + for (int i = 0; i < specWidth * specHeight * 4; i += 4) { currentColor[0] = ByteToFloat(specPic[i + 0]); currentColor[1] = ByteToFloat(specPic[i + 1]); currentColor[2] = ByteToFloat(specPic[i + 2]); - float ratio = - (sRGBtoRGB(currentColor[0]) + sRGBtoRGB(currentColor[1]) + sRGBtoRGB(currentColor[1])) / - (currentColor[0] + currentColor[1] + currentColor[2]); + float ratio = + (sRGBtoRGB(currentColor[0]) + sRGBtoRGB(currentColor[1]) + sRGBtoRGB(currentColor[1])) / (currentColor[0] + currentColor[1] + currentColor[2]); sdrSpecPic[i + 0] = FloatToByte(currentColor[0] * ratio); sdrSpecPic[i + 1] = FloatToByte(currentColor[1] * ratio); @@ -2836,44 +2559,40 @@ image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageNam return R_CreateImage(sdrName, sdrSpecPic, specWidth, specHeight, IMGTYPE_COLORALPHA, flags & ~IMGFLAG_SRGB, 0); } -static void R_CreateNormalMap ( const char *name, byte *pic, int width, int height, int flags ) -{ +static void R_CreateNormalMap(const char *name, byte *pic, int width, int height, int flags) { char normalName[MAX_QPATH]; image_t *normalImage; int normalWidth, normalHeight; int normalFlags; - + normalFlags = (flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_SRGB)) | IMGFLAG_NOLIGHTSCALE; - + COM_StripExtension(name, normalName, sizeof(normalName)); Q_strcat(normalName, sizeof(normalName), "_n"); - + // find normalmap in case it's there normalImage = R_FindImageFile(normalName, IMGTYPE_NORMAL, normalFlags); - + // if not, generate it - if (normalImage == NULL) - { + if (normalImage == NULL) { byte *normalPic; int x, y; - + normalWidth = width; normalHeight = height; normalPic = (byte *)Z_Malloc(width * height * 4, TAG_GENERAL); RGBAtoNormal(pic, normalPic, width, height, (qboolean)(flags & IMGFLAG_CLAMPTOEDGE)); - + #if 1 // Brighten up the original image to work with the normal map RGBAtoYCoCgA(pic, pic, width, height); - for (y = 0; y < height; y++) - { - byte *picbyte = pic + y * width * 4; + for (y = 0; y < height; y++) { + byte *picbyte = pic + y * width * 4; byte *normbyte = normalPic + y * width * 4; - for (x = 0; x < width; x++) - { + for (x = 0; x < width; x++) { int div = MAX(normbyte[2] - 127, 16); picbyte[0] = CLAMP(picbyte[0] * 128 / div, 0, 255); - picbyte += 4; + picbyte += 4; normbyte += 4; } } @@ -2882,60 +2601,55 @@ static void R_CreateNormalMap ( const char *name, byte *pic, int width, int heig // Blur original image's luma to work with the normal map { byte *blurPic; - + RGBAtoYCoCgA(pic, pic, width, height); blurPic = ri.Malloc(width * height); - - for (y = 1; y < height - 1; y++) - { - byte *picbyte = pic + y * width * 4; + + for (y = 1; y < height - 1; y++) { + byte *picbyte = pic + y * width * 4; byte *blurbyte = blurPic + y * width; - + picbyte += 4; blurbyte += 1; - - for (x = 1; x < width - 1; x++) - { + + for (x = 1; x < width - 1; x++) { int result; - - result = *(picbyte - (width + 1) * 4) + *(picbyte - width * 4) + *(picbyte - (width - 1) * 4) + - *(picbyte - 1 * 4) + *(picbyte ) + *(picbyte + 1 * 4) + - *(picbyte + (width - 1) * 4) + *(picbyte + width * 4) + *(picbyte + (width + 1) * 4); - + + result = *(picbyte - (width + 1) * 4) + *(picbyte - width * 4) + *(picbyte - (width - 1) * 4) + *(picbyte - 1 * 4) + *(picbyte) + + *(picbyte + 1 * 4) + *(picbyte + (width - 1) * 4) + *(picbyte + width * 4) + *(picbyte + (width + 1) * 4); + result /= 9; - + *blurbyte = result; picbyte += 4; blurbyte += 1; } } - + // FIXME: do borders - - for (y = 1; y < height - 1; y++) - { - byte *picbyte = pic + y * width * 4; + + for (y = 1; y < height - 1; y++) { + byte *picbyte = pic + y * width * 4; byte *blurbyte = blurPic + y * width; - + picbyte += 4; blurbyte += 1; - - for (x = 1; x < width - 1; x++) - { + + for (x = 1; x < width - 1; x++) { picbyte[0] = *blurbyte; picbyte += 4; blurbyte += 1; } } - + ri.Free(blurPic); - + YCoCgAtoRGBA(pic, pic, width, height); } #endif - - R_CreateImage( normalName, normalPic, normalWidth, normalHeight, IMGTYPE_NORMAL, normalFlags, 0 ); - Z_Free( normalPic ); + + R_CreateImage(normalName, normalPic, normalWidth, normalHeight, IMGTYPE_NORMAL, normalFlags, 0); + Z_Free(normalPic); } } @@ -2947,11 +2661,10 @@ Finds or loads the given image. Returns NULL if it fails, not a default image. ============== */ -image_t *R_FindImageFile( const char *name, imgType_t type, int flags ) -{ - image_t *image; - int width, height; - byte *pic; +image_t *R_FindImageFile(const char *name, imgType_t type, int flags) { + image_t *image; + int width, height; + byte *pic; int internalFormat = 0; int loadFlags = flags; @@ -2965,25 +2678,19 @@ image_t *R_FindImageFile( const char *name, imgType_t type, int flags ) // // load the pic from disk // - if (r_hdr->integer && (flags & IMGFLAG_HDR || flags & IMGFLAG_HDR_LIGHTMAP)) - { + if (r_hdr->integer && (flags & IMGFLAG_HDR || flags & IMGFLAG_HDR_LIGHTMAP)) { char filename[MAX_QPATH]; Com_sprintf(filename, sizeof(filename), "%s.hdr", name); - float *floatBuffer; + float *floatBuffer; R_LoadHDRImage(filename, &pic, &width, &height); - if (pic == NULL) - { + if (pic == NULL) { R_LoadImage(name, &pic, &width, &height); - } - else - { - for (int i = 0; i < width*height; i++) - { + } else { + for (int i = 0; i < width * height; i++) { vec4_t color; - floatBuffer = (float*)pic; - memcpy(color, &floatBuffer[i*3], 12); - if (flags & IMGFLAG_HDR_LIGHTMAP) - { + floatBuffer = (float *)pic; + memcpy(color, &floatBuffer[i * 3], 12); + if (flags & IMGFLAG_HDR_LIGHTMAP) { color[0] = color[0] / M_PI; color[1] = color[1] / M_PI; color[2] = color[2] / M_PI; @@ -2999,98 +2706,84 @@ image_t *R_FindImageFile( const char *name, imgType_t type, int flags ) internalFormat = GL_RGBA16F; loadFlags = flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_MIPMAP); } - } - else - { + } else { R_LoadImage(name, &pic, &width, &height); } - if ( pic == NULL ) { + if (pic == NULL) { return NULL; } - if (r_normalMapping->integer && !(type == IMGTYPE_NORMAL) && - (flags & IMGFLAG_PICMIP) && (flags & IMGFLAG_MIPMAP) && (flags & IMGFLAG_GENNORMALMAP)) - { - R_CreateNormalMap( name, pic, width, height, flags ); + if (r_normalMapping->integer && !(type == IMGTYPE_NORMAL) && (flags & IMGFLAG_PICMIP) && (flags & IMGFLAG_MIPMAP) && (flags & IMGFLAG_GENNORMALMAP)) { + R_CreateNormalMap(name, pic, width, height, flags); } // flip height info, so we don't need to do this in the shader later - if (type == IMGTYPE_NORMALHEIGHT) - { - for (int i = 0; i < width*height; i++) - { + if (type == IMGTYPE_NORMALHEIGHT) { + for (int i = 0; i < width * height; i++) { pic[4 * i + 3] = 255 - pic[4 * i + 3]; } } - image = R_CreateImage( name, pic, width, height, type, loadFlags, internalFormat); - Z_Free( pic ); - + image = R_CreateImage(name, pic, width, height, type, loadFlags, internalFormat); + Z_Free(pic); + return image; } - /* ================ R_CreateDlightImage ================ */ -#define DLIGHT_SIZE 16 -static void R_CreateDlightImage( void ) { - int width, height; - byte *pic; +#define DLIGHT_SIZE 16 +static void R_CreateDlightImage(void) { + int width, height; + byte *pic; R_LoadImage("gfx/2d/dlight", &pic, &width, &height); - if (pic) - { - tr.dlightImage = R_CreateImage("*dlight", pic, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0 ); + if (pic) { + tr.dlightImage = R_CreateImage("*dlight", pic, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); Z_Free(pic); - } - else - { // if we dont get a successful load - int x,y; - byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; - int b; + } else { // if we dont get a successful load + int x, y; + byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; + int b; // make a centered inverse-square falloff blob for dynamic lighting - for (x=0 ; x 255) { b = 255; - } else if ( b < 75 ) { + } else if (b < 75) { b = 0; } - data[y][x][0] = - data[y][x][1] = - data[y][x][2] = b; - data[y][x][3] = 255; + data[y][x][0] = data[y][x][1] = data[y][x][2] = b; + data[y][x][3] = 255; } } - tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0 ); + tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0); } } - /* ================= R_InitFogTable ================= */ -void R_InitFogTable( void ) { - int i; - float d; - float exp; - +void R_InitFogTable(void) { + int i; + float d; + float exp; + exp = 0.5; - for ( i = 0 ; i < FOG_TABLE_SIZE ; i++ ) { - d = pow ( (float)i/(FOG_TABLE_SIZE-1), exp ); + for (i = 0; i < FOG_TABLE_SIZE; i++) { + d = pow((float)i / (FOG_TABLE_SIZE - 1), exp); tr.fogTable[i] = d; } @@ -3105,28 +2798,28 @@ This is called for each texel of the fog texture on startup and for each vertex of transparent shaders in fog dynamically ================ */ -float R_FogFactor( float s, float t ) { - float d; +float R_FogFactor(float s, float t) { + float d; - s -= 1.0/512; - if ( s < 0 ) { + s -= 1.0 / 512; + if (s < 0) { return 0; } - if ( t < 1.0/32 ) { + if (t < 1.0 / 32) { return 0; } - if ( t < 31.0/32 ) { - s *= (t - 1.0f/32.0f) / (30.0f/32.0f); + if (t < 31.0 / 32) { + s *= (t - 1.0f / 32.0f) / (30.0f / 32.0f); } // we need to leave a lot of clamp range s *= 8; - if ( s > 1.0 ) { + if (s > 1.0) { s = 1.0; } - d = tr.fogTable[ (int)(s * (FOG_TABLE_SIZE-1)) ]; + d = tr.fogTable[(int)(s * (FOG_TABLE_SIZE - 1))]; return d; } @@ -3136,39 +2829,37 @@ float R_FogFactor( float s, float t ) { R_CreateFogImage ================ */ -#define FOG_S 256 -#define FOG_T 32 -static void R_CreateFogImage( void ) { - int x,y; - byte *data; - float d; - float borderColor[4]; +#define FOG_S 256 +#define FOG_T 32 +static void R_CreateFogImage(void) { + int x, y; + byte *data; + float d; + float borderColor[4]; - data = (byte *)ri.Hunk_AllocateTempMemory( FOG_S * FOG_T * 4 ); + data = (byte *)ri.Hunk_AllocateTempMemory(FOG_S * FOG_T * 4); // S is distance, T is depth - for (x=0 ; x 0.0f) - { + if (NdotL > 0.0f) { float const visibility = GSmithCorrelated(roughness, NdotV, NdotL); float const NdotLVisPDF = NdotL * visibility * (4.0f * VdotH / NdotH); float const fresnel = powf(1.0f - VdotH, 5.0f); @@ -3255,8 +2942,7 @@ static void R_CreateEnvBrdfLUT(void) { float const NdotH = MAX(hz, 0.0f); float const VdotH = MAX(vdh, 0.0f); - if (NdotL > 0.0f) - { + if (NdotL > 0.0f) { float const velvetV = V_Neubelt(NdotV, NdotL); float const rcp_pdf = 4.0f * VdotH / NdotH; velvet += NdotL * velvetV * rcp_pdf; @@ -3274,14 +2960,8 @@ static void R_CreateEnvBrdfLUT(void) { } } - tr.envBrdfImage = R_CreateImage( - "*envBrdfLUT", - (byte*)data, - LUT_WIDTH, - LUT_HEIGHT, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - GL_RGB16F); + tr.envBrdfImage = + R_CreateImage("*envBrdfLUT", (byte *)data, LUT_WIDTH, LUT_HEIGHT, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGB16F); } /* @@ -3289,37 +2969,23 @@ static void R_CreateEnvBrdfLUT(void) { R_CreateDefaultImage ================== */ -#define DEFAULT_SIZE 16 -static void R_CreateDefaultImage( void ) { - int x; - byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; +#define DEFAULT_SIZE 16 +static void R_CreateDefaultImage(void) { + int x; + byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; // the default image will be a box, to allow you to see the mapping coordinates - Com_Memset( data, 32, sizeof( data ) ); - for ( x = 0 ; x < DEFAULT_SIZE ; x++ ) { - data[0][x][0] = - data[0][x][1] = - data[0][x][2] = - data[0][x][3] = 255; - - data[x][0][0] = - data[x][0][1] = - data[x][0][2] = - data[x][0][3] = 255; - - data[DEFAULT_SIZE-1][x][0] = - data[DEFAULT_SIZE-1][x][1] = - data[DEFAULT_SIZE-1][x][2] = - data[DEFAULT_SIZE-1][x][3] = 255; - - data[x][DEFAULT_SIZE-1][0] = - data[x][DEFAULT_SIZE-1][1] = - data[x][DEFAULT_SIZE-1][2] = - data[x][DEFAULT_SIZE-1][3] = 255; - } - tr.defaultImage = R_CreateImage( - "*default", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, - IMGTYPE_COLORALPHA, IMGFLAG_MIPMAP, GL_RGBA8); + Com_Memset(data, 32, sizeof(data)); + for (x = 0; x < DEFAULT_SIZE; x++) { + data[0][x][0] = data[0][x][1] = data[0][x][2] = data[0][x][3] = 255; + + data[x][0][0] = data[x][0][1] = data[x][0][2] = data[x][0][3] = 255; + + data[DEFAULT_SIZE - 1][x][0] = data[DEFAULT_SIZE - 1][x][1] = data[DEFAULT_SIZE - 1][x][2] = data[DEFAULT_SIZE - 1][x][3] = 255; + + data[x][DEFAULT_SIZE - 1][0] = data[x][DEFAULT_SIZE - 1][1] = data[x][DEFAULT_SIZE - 1][2] = data[x][DEFAULT_SIZE - 1][3] = 255; + } + tr.defaultImage = R_CreateImage("*default", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, IMGTYPE_COLORALPHA, IMGFLAG_MIPMAP, GL_RGBA8); } /* @@ -3327,52 +2993,37 @@ static void R_CreateDefaultImage( void ) { R_CreateBuiltinImages ================== */ -void R_CreateBuiltinImages( void ) { - int x,y; - byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; +void R_CreateBuiltinImages(void) { + int x, y; + byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; R_CreateDefaultImage(); // we use a solid white image instead of disabling texturing - Com_Memset( data, 255, sizeof( data ) ); - tr.whiteImage = R_CreateImage( - "*white", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, IMGFLAG_NONE, - GL_RGBA8); + Com_Memset(data, 255, sizeof(data)); + tr.whiteImage = R_CreateImage("*white", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, IMGFLAG_NONE, GL_RGBA8); - if (r_dlightMode->integer >= 2) - { - tr.pointShadowArrayImage = R_Create2DImageArray( - va("*pointshadowmapImage"), - NULL, - DSHADOW_MAP_SIZE, - DSHADOW_MAP_SIZE, - MAX_DLIGHTS*6, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, - GL_DEPTH_COMPONENT16); + if (r_dlightMode->integer >= 2) { + tr.pointShadowArrayImage = + R_Create2DImageArray(va("*pointshadowmapImage"), NULL, DSHADOW_MAP_SIZE, DSHADOW_MAP_SIZE, MAX_DLIGHTS * 6, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, GL_DEPTH_COMPONENT16); } // with overbright bits active, we need an image which is some fraction of // full color, for default lightmaps, etc for (x = 0; x < DEFAULT_SIZE; x++) { - for (y =0; y < DEFAULT_SIZE; y++) { - data[y][x][0] = - data[y][x][1] = - data[y][x][2] = tr.identityLightByte; + for (y = 0; y < DEFAULT_SIZE; y++) { + data[y][x][0] = data[y][x][1] = data[y][x][2] = tr.identityLightByte; data[y][x][3] = 255; } } - tr.identityLightImage = R_CreateImage( - "*identityLight", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, - IMGFLAG_NONE, 0); + tr.identityLightImage = R_CreateImage("*identityLight", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, IMGFLAG_NONE, 0); // scratchimage is usually used for cinematic drawing for (x = 0; x < 32; x++) { - tr.scratchImage[x] = R_CreateImage( - "*scratch", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, - IMGTYPE_COLORALPHA, - IMGFLAG_PICMIP | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MUTABLE, 0); + tr.scratchImage[x] = + R_CreateImage("*scratch", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, IMGTYPE_COLORALPHA, IMGFLAG_PICMIP | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MUTABLE, 0); } R_CreateDlightImage(); @@ -3388,54 +3039,39 @@ void R_CreateBuiltinImages( void ) { int rgbFormat = GL_RGBA8; - tr.renderImage = R_CreateImage( - "_render", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.renderImage = R_CreateImage("_render", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); - tr.glowImage = R_CreateImage( - "*glow", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.glowImage = R_CreateImage("*glow", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); int glowImageWidth = width; int glowImageHeight = height; - for (int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++) - { - tr.glowImageScaled[i] = R_CreateImage( - va("*glowScaled%d", i), NULL, glowImageWidth, glowImageHeight, - IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - hdrFormat); + for (int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++) { + tr.glowImageScaled[i] = R_CreateImage(va("*glowScaled%d", i), NULL, glowImageWidth, glowImageHeight, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); glowImageWidth = Q_max(1, glowImageWidth >> 1); glowImageHeight = Q_max(1, glowImageHeight >> 1); } if (r_drawSunRays->integer) - tr.sunRaysImage = R_CreateImage( - "*sunRays", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, rgbFormat); - - tr.renderDepthImage = R_CreateImage( - "*renderdepth", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH24_STENCIL8); - tr.textureDepthImage = R_CreateImage( - "*texturedepth", NULL, PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE, - IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - GL_DEPTH_COMPONENT24); + tr.sunRaysImage = R_CreateImage("*sunRays", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, rgbFormat); + + tr.renderDepthImage = + R_CreateImage("*renderdepth", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH24_STENCIL8); + tr.textureDepthImage = R_CreateImage("*texturedepth", NULL, PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH_COMPONENT24); { unsigned short sdata[4]; void *p; - if (hdrFormat == GL_RGBA16F) - { + if (hdrFormat == GL_RGBA16F) { sdata[0] = FloatToHalf(0.0f); sdata[1] = FloatToHalf(0.45f); sdata[2] = FloatToHalf(1.0f); sdata[3] = FloatToHalf(1.0f); p = &sdata[0]; - } - else - { + } else { data[0][0][0] = 0; data[0][0][1] = 0.45f * 255; data[0][0][2] = 255; @@ -3443,142 +3079,93 @@ void R_CreateBuiltinImages( void ) { p = data; } - tr.calcLevelsImage = R_CreateImage( - "*calcLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); - tr.targetLevelsImage = R_CreateImage( - "*targetLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); - tr.fixedLevelsImage = R_CreateImage( - "*fixedLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.calcLevelsImage = R_CreateImage("*calcLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.targetLevelsImage = R_CreateImage("*targetLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.fixedLevelsImage = R_CreateImage("*fixedLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); } - for (x = 0; x < 2; x++) - { - tr.textureScratchImage[x] = R_CreateImage( - va("*textureScratch%d", x), NULL, 256, 256, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); + for (x = 0; x < 2; x++) { + tr.textureScratchImage[x] = + R_CreateImage(va("*textureScratch%d", x), NULL, 256, 256, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); } - for (x = 0; x < 2; x++) - { - tr.quarterImage[x] = R_CreateImage( - va("*quarter%d", x), NULL, width / 2, height / 2, - IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - GL_RGBA8); + for (x = 0; x < 2; x++) { + tr.quarterImage[x] = + R_CreateImage(va("*quarter%d", x), NULL, width / 2, height / 2, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); } - if (r_ssao->integer) - { - tr.screenSsaoImage = R_CreateImage( - "*screenSsao", NULL, width / 2, height / 2, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); - tr.hdrDepthImage = R_CreateImage( - "*hdrDepth", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R32F); + if (r_ssao->integer) { + tr.screenSsaoImage = + R_CreateImage("*screenSsao", NULL, width / 2, height / 2, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); + tr.hdrDepthImage = R_CreateImage("*hdrDepth", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R32F); } - if (r_shadows->integer == 4) - { - tr.pshadowArrayImage = R_Create2DImageArray( - va("*pshadowmapArray"), - NULL, - PSHADOW_MAP_SIZE, - PSHADOW_MAP_SIZE, - MAX_DRAWN_PSHADOWS, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, - GL_DEPTH_COMPONENT16); - } - - if (r_sunlightMode->integer) - { - tr.sunShadowArrayImage = R_Create2DImageArray( - va("*sunShadowmapArray"), - NULL, - r_shadowMapSize->integer, - r_shadowMapSize->integer, - 3, // number of cascades - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, - GL_DEPTH_COMPONENT16); - - tr.screenShadowImage = R_CreateImage( - "*screenShadow", NULL, width, height, IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R8); - } - - if (r_cubeMapping->integer) - { - tr.renderCubeImage = R_CreateImage( - "*renderCube", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE | - IMGFLAG_MIPMAP | - IMGFLAG_CUBEMAP, - hdrFormat); - - tr.renderCubeDepthImage = R_CreateImage( - "*renderdepth", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | - IMGFLAG_CLAMPTOEDGE, - GL_DEPTH24_STENCIL8); - } - - tr.weatherDepthImage = R_CreateImage( - "*weatherDepth", - nullptr, - 1024, - 1024, - IMGTYPE_COLORALPHA, - IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, - GL_DEPTH_COMPONENT16); -} + if (r_shadows->integer == 4) { + tr.pshadowArrayImage = R_Create2DImageArray(va("*pshadowmapArray"), NULL, PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE, MAX_DRAWN_PSHADOWS, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, GL_DEPTH_COMPONENT16); + } + + if (r_sunlightMode->integer) { + tr.sunShadowArrayImage = + R_Create2DImageArray(va("*sunShadowmapArray"), NULL, r_shadowMapSize->integer, r_shadowMapSize->integer, + 3, // number of cascades + IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, GL_DEPTH_COMPONENT16); + + tr.screenShadowImage = R_CreateImage("*screenShadow", NULL, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R8); + } + + if (r_cubeMapping->integer) { + tr.renderCubeImage = R_CreateImage("*renderCube", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MIPMAP | IMGFLAG_CUBEMAP, hdrFormat); + tr.renderCubeDepthImage = R_CreateImage("*renderdepth", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH24_STENCIL8); + } + + tr.weatherDepthImage = + R_CreateImage("*weatherDepth", nullptr, 1024, 1024, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH_COMPONENT16); +} /* =============== R_SetColorMappings =============== */ -void R_SetColorMappings( void ) { - int i, j; - float g; - int inf; +void R_SetColorMappings(void) { + int i, j; + float g; + int inf; // setup the overbright lighting tr.overbrightBits = r_overBrightBits->integer; // allow 2 overbright bits - if ( tr.overbrightBits > 2 ) { + if (tr.overbrightBits > 2) { tr.overbrightBits = 2; - } else if ( tr.overbrightBits < 0 ) { + } else if (tr.overbrightBits < 0) { tr.overbrightBits = 0; } - tr.identityLight = 1.0f / ( 1 << tr.overbrightBits ); + tr.identityLight = 1.0f / (1 << tr.overbrightBits); tr.identityLightByte = 255 * tr.identityLight; - if ( r_intensity->value <= 1 ) { - ri.Cvar_Set( "r_intensity", "1" ); + if (r_intensity->value <= 1) { + ri.Cvar_Set("r_intensity", "1"); } - if ( r_gamma->value < 0.5f ) { - ri.Cvar_Set( "r_gamma", "0.5" ); - } else if ( r_gamma->value > 3.0f ) { - ri.Cvar_Set( "r_gamma", "3.0" ); + if (r_gamma->value < 0.5f) { + ri.Cvar_Set("r_gamma", "0.5"); + } else if (r_gamma->value > 3.0f) { + ri.Cvar_Set("r_gamma", "3.0"); } g = r_gamma->value; - for ( i = 0; i < 256; i++ ) { - if ( g == 1 ) { + for (i = 0; i < 256; i++) { + if (g == 1) { inf = i; } else { - inf = 255 * pow ( i/255.0f, 1.0f / g ) + 0.5f; + inf = 255 * pow(i / 255.0f, 1.0f / g) + 0.5f; } inf <<= tr.overbrightBits; if (inf < 0) { @@ -3590,7 +3177,7 @@ void R_SetColorMappings( void ) { s_gammatable[i] = inf; } - for (i=0 ; i<256 ; i++) { + for (i = 0; i < 256; i++) { j = i * r_intensity->value; if (j > 255) { j = 255; @@ -3598,17 +3185,15 @@ void R_SetColorMappings( void ) { s_intensitytable[i] = j; } - if ( glConfig.deviceSupportsGamma ) - { - ri.WIN_SetGamma( &glConfig, s_gammatable, s_gammatable, s_gammatable ); + if (glConfig.deviceSupportsGamma) { + ri.WIN_SetGamma(&glConfig, s_gammatable, s_gammatable, s_gammatable); } } /* Initialise the images pool allocator */ -void R_InitImagesPool() -{ +void R_InitImagesPool() { Com_Memset(hashTable, 0, sizeof(hashTable)); imagesPool = NULL; @@ -3621,7 +3206,7 @@ void R_InitImagesPool() R_InitImages =============== */ -void R_InitImages( void ) { +void R_InitImages(void) { // build brightness translation tables R_SetColorMappings(); @@ -3634,10 +3219,9 @@ void R_InitImages( void ) { R_DeleteTextures =============== */ -void R_DeleteTextures( void ) { +void R_DeleteTextures(void) { image_t *image = tr.images; - while ( image ) - { + while (image) { qglDeleteTextures(1, &image->texnum); image = image->poolNext; } @@ -3645,8 +3229,7 @@ void R_DeleteTextures( void ) { tr.numImages = 0; // Free pool and allocated images - while ( imagesPool ) - { + while (imagesPool) { ImagesPool *pNext = imagesPool->pNext; Z_Free(imagesPool->pPool); Z_Free(imagesPool); @@ -3654,9 +3237,9 @@ void R_DeleteTextures( void ) { imagesPool = pNext; } - Com_Memset( glState.currenttextures, 0, sizeof( glState.currenttextures ) ); - GL_SelectTexture( 1 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); - GL_SelectTexture( 0 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); + Com_Memset(glState.currenttextures, 0, sizeof(glState.currenttextures)); + GL_SelectTexture(1); + qglBindTexture(GL_TEXTURE_2D, 0); + GL_SelectTexture(0); + qglBindTexture(GL_TEXTURE_2D, 0); } diff --git a/codemp/rd-rend2/tr_image_stb.cpp b/codemp/rd-rend2/tr_image_stb.cpp index 17a2baae20..efa98ebcda 100644 --- a/codemp/rd-rend2/tr_image_stb.cpp +++ b/codemp/rd-rend2/tr_image_stb.cpp @@ -24,23 +24,17 @@ along with this program; if not, see . #include "tr_local.h" -static void* R_LocalMalloc(size_t size) -{ - return ri.Hunk_AllocateTempMemory(size); -} +static void *R_LocalMalloc(size_t size) { return ri.Hunk_AllocateTempMemory(size); } -static void* R_LocalReallocSized(void *ptr, size_t old_size, size_t new_size) -{ +static void *R_LocalReallocSized(void *ptr, size_t old_size, size_t new_size) { void *mem = ri.Hunk_AllocateTempMemory(new_size); - if (ptr) - { + if (ptr) { memcpy(mem, ptr, old_size); ri.Hunk_FreeTempMemory(ptr); } return mem; } -static void R_LocalFree(void *ptr) -{ +static void R_LocalFree(void *ptr) { if (ptr) ri.Hunk_FreeTempMemory(ptr); } @@ -59,13 +53,11 @@ static void R_LocalFree(void *ptr) #define IMG_FLOAT 1 // Loads a HDR image from file. -void R_LoadHDRImage( const char *filename, byte **data, int *width, int *height ) -{ +void R_LoadHDRImage(const char *filename, byte **data, int *width, int *height) { byte *buf = NULL; int x, y, n; - int len = ri.FS_ReadFile (filename, (void **)&buf); - if ( len <= 0 || buf == NULL ) - { + int len = ri.FS_ReadFile(filename, (void **)&buf); + if (len <= 0 || buf == NULL) { return; } stbi_set_flip_vertically_on_load(0); @@ -85,5 +77,4 @@ void R_LoadHDRImage( const char *filename, byte **data, int *width, int *height *height = y; else *height = 0; - } diff --git a/codemp/rd-rend2/tr_init.cpp b/codemp/rd-rend2/tr_init.cpp index 183fbcae90..f2a1663fca 100644 --- a/codemp/rd-rend2/tr_init.cpp +++ b/codemp/rd-rend2/tr_init.cpp @@ -33,254 +33,251 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #endif static size_t STATIC_UNIFORM_BUFFER_SIZE = 1 * 1024 * 1024; -static size_t FRAME_UNIFORM_BUFFER_SIZE = 8*1024*1024; -static size_t FRAME_VERTEX_BUFFER_SIZE = 12*1024*1024; -static size_t FRAME_INDEX_BUFFER_SIZE = 4*1024*1024; +static size_t FRAME_UNIFORM_BUFFER_SIZE = 8 * 1024 * 1024; +static size_t FRAME_VERTEX_BUFFER_SIZE = 12 * 1024 * 1024; +static size_t FRAME_INDEX_BUFFER_SIZE = 4 * 1024 * 1024; #if defined(_WIN32) extern "C" { - __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; - __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; +__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } #endif -glconfig_t glConfig; +glconfig_t glConfig; glconfigExt_t glConfigExt; glRefConfig_t glRefConfig; -glstate_t glState; -window_t window; - -cvar_t *se_language; - -cvar_t *r_verbose; -cvar_t *r_ignore; - -cvar_t *r_detailTextures; - -cvar_t *r_znear; -cvar_t *r_zproj; -cvar_t *r_stereoSeparation; - -cvar_t *r_skipBackEnd; - -cvar_t *r_stereo; -cvar_t *r_anaglyphMode; - -cvar_t *r_greyscale; - -cvar_t *r_measureOverdraw; - -cvar_t *r_inGameVideo; -cvar_t *r_fastsky; -cvar_t *r_drawSun; -cvar_t *r_dynamiclight; - -cvar_t *r_lodbias; -cvar_t *r_lodscale; -cvar_t *r_autolodscalevalue; - -cvar_t *r_norefresh; -cvar_t *r_drawentities; -cvar_t *r_drawworld; -cvar_t *r_drawfog; -cvar_t *r_speeds; -cvar_t *r_fullbright; -cvar_t *r_novis; -cvar_t *r_nocull; -cvar_t *r_facePlaneCull; -cvar_t *r_showcluster; -cvar_t *r_nocurves; - -cvar_t *r_allowExtensions; - -cvar_t *r_ext_compressed_textures; -cvar_t *r_ext_multitexture; -cvar_t *r_ext_compiled_vertex_array; -cvar_t *r_ext_texture_env_add; -cvar_t *r_ext_texture_filter_anisotropic; -cvar_t *r_ext_preferred_tc_method; - -cvar_t *r_ext_draw_range_elements; -cvar_t *r_ext_multi_draw_arrays; -cvar_t *r_ext_texture_float; -cvar_t *r_arb_half_float_pixel; -cvar_t *r_ext_framebuffer_multisample; -cvar_t *r_arb_seamless_cube_map; -cvar_t *r_arb_vertex_type_2_10_10_10_rev; -cvar_t *r_arb_buffer_storage; - -cvar_t *r_mergeMultidraws; -cvar_t *r_mergeLeafSurfaces; - -cvar_t *r_cameraExposure; - -cvar_t *r_externalGLSL; - -cvar_t *r_hdr; -cvar_t *r_floatLightmap; - -cvar_t *r_toneMap; -cvar_t *r_forceToneMap; -cvar_t *r_forceToneMapMin; -cvar_t *r_forceToneMapAvg; -cvar_t *r_forceToneMapMax; - -cvar_t *r_autoExposure; -cvar_t *r_forceAutoExposure; -cvar_t *r_forceAutoExposureMin; -cvar_t *r_forceAutoExposureMax; - -cvar_t *r_depthPrepass; -cvar_t *r_ssao; - -cvar_t *r_normalMapping; -cvar_t *r_specularMapping; -cvar_t *r_deluxeMapping; -cvar_t *r_deluxeSpecular; -cvar_t *r_parallaxMapping; -cvar_t *r_forceParallaxBias; -cvar_t *r_cubeMapping; -cvar_t *r_cubeMappingBounces; -cvar_t *r_baseNormalX; -cvar_t *r_baseNormalY; -cvar_t *r_baseParallax; -cvar_t *r_baseSpecular; -cvar_t *r_dlightMode; -cvar_t *r_pshadowDist; -cvar_t *r_imageUpsample; -cvar_t *r_imageUpsampleMaxSize; -cvar_t *r_imageUpsampleType; -cvar_t *r_genNormalMaps; -cvar_t *r_forceSun; -cvar_t *r_forceSunMapLightScale; -cvar_t *r_forceSunLightScale; -cvar_t *r_forceSunAmbientScale; -cvar_t *r_sunlightMode; -cvar_t *r_drawSunRays; -cvar_t *r_sunShadows; -cvar_t *r_shadowFilter; -cvar_t *r_shadowMapSize; -cvar_t *r_shadowCascadeZNear; -cvar_t *r_shadowCascadeZFar; -cvar_t *r_shadowCascadeZBias; -cvar_t *r_ignoreDstAlpha; - -cvar_t *r_ignoreGLErrors; -cvar_t *r_logFile; - -cvar_t *r_texturebits; - -cvar_t *r_drawBuffer; -cvar_t *r_lightmap; -cvar_t *r_vertexLight; -cvar_t *r_uiFullScreen; -cvar_t *r_shadows; -cvar_t *r_flares; -cvar_t *r_nobind; -cvar_t *r_singleShader; -cvar_t *r_roundImagesDown; -cvar_t *r_colorMipLevels; -cvar_t *r_picmip; -cvar_t *r_showtris; -cvar_t *r_showsky; -cvar_t *r_shownormals; -cvar_t *r_finish; -cvar_t *r_clear; -cvar_t *r_markcount; -cvar_t *r_textureMode; -cvar_t *r_offsetFactor; -cvar_t *r_offsetUnits; -cvar_t *r_shadowOffsetFactor; -cvar_t *r_shadowOffsetUnits; -cvar_t *r_gamma; -cvar_t *r_intensity; -cvar_t *r_lockpvs; -cvar_t *r_noportals; -cvar_t *r_portalOnly; - -cvar_t *r_subdivisions; -cvar_t *r_lodCurveError; - - - -cvar_t *r_overBrightBits; -cvar_t *r_mapOverBrightBits; - -cvar_t *r_debugSurface; -cvar_t *r_simpleMipMaps; - -cvar_t *r_showImages; - -cvar_t *r_ambientScale; -cvar_t *r_directedScale; -cvar_t *r_debugLight; -cvar_t *r_debugSort; -cvar_t *r_printShaders; -cvar_t *r_saveFontData; +glstate_t glState; +window_t window; + +cvar_t *se_language; + +cvar_t *r_verbose; +cvar_t *r_ignore; + +cvar_t *r_detailTextures; + +cvar_t *r_znear; +cvar_t *r_zproj; +cvar_t *r_stereoSeparation; + +cvar_t *r_skipBackEnd; + +cvar_t *r_stereo; +cvar_t *r_anaglyphMode; + +cvar_t *r_greyscale; + +cvar_t *r_measureOverdraw; + +cvar_t *r_inGameVideo; +cvar_t *r_fastsky; +cvar_t *r_drawSun; +cvar_t *r_dynamiclight; + +cvar_t *r_lodbias; +cvar_t *r_lodscale; +cvar_t *r_autolodscalevalue; + +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawworld; +cvar_t *r_drawfog; +cvar_t *r_speeds; +cvar_t *r_fullbright; +cvar_t *r_novis; +cvar_t *r_nocull; +cvar_t *r_facePlaneCull; +cvar_t *r_showcluster; +cvar_t *r_nocurves; + +cvar_t *r_allowExtensions; + +cvar_t *r_ext_compressed_textures; +cvar_t *r_ext_multitexture; +cvar_t *r_ext_compiled_vertex_array; +cvar_t *r_ext_texture_env_add; +cvar_t *r_ext_texture_filter_anisotropic; +cvar_t *r_ext_preferred_tc_method; + +cvar_t *r_ext_draw_range_elements; +cvar_t *r_ext_multi_draw_arrays; +cvar_t *r_ext_texture_float; +cvar_t *r_arb_half_float_pixel; +cvar_t *r_ext_framebuffer_multisample; +cvar_t *r_arb_seamless_cube_map; +cvar_t *r_arb_vertex_type_2_10_10_10_rev; +cvar_t *r_arb_buffer_storage; + +cvar_t *r_mergeMultidraws; +cvar_t *r_mergeLeafSurfaces; + +cvar_t *r_cameraExposure; + +cvar_t *r_externalGLSL; + +cvar_t *r_hdr; +cvar_t *r_floatLightmap; + +cvar_t *r_toneMap; +cvar_t *r_forceToneMap; +cvar_t *r_forceToneMapMin; +cvar_t *r_forceToneMapAvg; +cvar_t *r_forceToneMapMax; + +cvar_t *r_autoExposure; +cvar_t *r_forceAutoExposure; +cvar_t *r_forceAutoExposureMin; +cvar_t *r_forceAutoExposureMax; + +cvar_t *r_depthPrepass; +cvar_t *r_ssao; + +cvar_t *r_normalMapping; +cvar_t *r_specularMapping; +cvar_t *r_deluxeMapping; +cvar_t *r_deluxeSpecular; +cvar_t *r_parallaxMapping; +cvar_t *r_forceParallaxBias; +cvar_t *r_cubeMapping; +cvar_t *r_cubeMappingBounces; +cvar_t *r_baseNormalX; +cvar_t *r_baseNormalY; +cvar_t *r_baseParallax; +cvar_t *r_baseSpecular; +cvar_t *r_dlightMode; +cvar_t *r_pshadowDist; +cvar_t *r_imageUpsample; +cvar_t *r_imageUpsampleMaxSize; +cvar_t *r_imageUpsampleType; +cvar_t *r_genNormalMaps; +cvar_t *r_forceSun; +cvar_t *r_forceSunMapLightScale; +cvar_t *r_forceSunLightScale; +cvar_t *r_forceSunAmbientScale; +cvar_t *r_sunlightMode; +cvar_t *r_drawSunRays; +cvar_t *r_sunShadows; +cvar_t *r_shadowFilter; +cvar_t *r_shadowMapSize; +cvar_t *r_shadowCascadeZNear; +cvar_t *r_shadowCascadeZFar; +cvar_t *r_shadowCascadeZBias; +cvar_t *r_ignoreDstAlpha; + +cvar_t *r_ignoreGLErrors; +cvar_t *r_logFile; + +cvar_t *r_texturebits; + +cvar_t *r_drawBuffer; +cvar_t *r_lightmap; +cvar_t *r_vertexLight; +cvar_t *r_uiFullScreen; +cvar_t *r_shadows; +cvar_t *r_flares; +cvar_t *r_nobind; +cvar_t *r_singleShader; +cvar_t *r_roundImagesDown; +cvar_t *r_colorMipLevels; +cvar_t *r_picmip; +cvar_t *r_showtris; +cvar_t *r_showsky; +cvar_t *r_shownormals; +cvar_t *r_finish; +cvar_t *r_clear; +cvar_t *r_markcount; +cvar_t *r_textureMode; +cvar_t *r_offsetFactor; +cvar_t *r_offsetUnits; +cvar_t *r_shadowOffsetFactor; +cvar_t *r_shadowOffsetUnits; +cvar_t *r_gamma; +cvar_t *r_intensity; +cvar_t *r_lockpvs; +cvar_t *r_noportals; +cvar_t *r_portalOnly; + +cvar_t *r_subdivisions; +cvar_t *r_lodCurveError; + +cvar_t *r_overBrightBits; +cvar_t *r_mapOverBrightBits; + +cvar_t *r_debugSurface; +cvar_t *r_simpleMipMaps; + +cvar_t *r_showImages; + +cvar_t *r_ambientScale; +cvar_t *r_directedScale; +cvar_t *r_debugLight; +cvar_t *r_debugSort; +cvar_t *r_printShaders; +cvar_t *r_saveFontData; #ifdef _DEBUG -cvar_t *r_noPrecacheGLA; +cvar_t *r_noPrecacheGLA; #endif -cvar_t *r_noServerGhoul2; -cvar_t *r_Ghoul2AnimSmooth=0; -cvar_t *r_Ghoul2UnSqashAfterSmooth=0; -//cvar_t *r_Ghoul2UnSqash; -//cvar_t *r_Ghoul2TimeBase=0; from single player -//cvar_t *r_Ghoul2NoLerp; -//cvar_t *r_Ghoul2NoBlend; -//cvar_t *r_Ghoul2BlendMultiplier=0; - -cvar_t *broadsword=0; -cvar_t *broadsword_kickbones=0; -cvar_t *broadsword_kickorigin=0; -cvar_t *broadsword_playflop=0; -cvar_t *broadsword_dontstopanim=0; -cvar_t *broadsword_waitforshot=0; -cvar_t *broadsword_smallbbox=0; -cvar_t *broadsword_extra1=0; -cvar_t *broadsword_extra2=0; - -cvar_t *broadsword_effcorr=0; -cvar_t *broadsword_ragtobase=0; -cvar_t *broadsword_dircap=0; - -cvar_t *r_marksOnTriangleMeshes; - -cvar_t *r_aviMotionJpegQuality; -cvar_t *r_screenshotJpegQuality; -cvar_t *r_surfaceSprites; +cvar_t *r_noServerGhoul2; +cvar_t *r_Ghoul2AnimSmooth = 0; +cvar_t *r_Ghoul2UnSqashAfterSmooth = 0; +// cvar_t *r_Ghoul2UnSqash; +// cvar_t *r_Ghoul2TimeBase=0; from single player +// cvar_t *r_Ghoul2NoLerp; +// cvar_t *r_Ghoul2NoBlend; +// cvar_t *r_Ghoul2BlendMultiplier=0; + +cvar_t *broadsword = 0; +cvar_t *broadsword_kickbones = 0; +cvar_t *broadsword_kickorigin = 0; +cvar_t *broadsword_playflop = 0; +cvar_t *broadsword_dontstopanim = 0; +cvar_t *broadsword_waitforshot = 0; +cvar_t *broadsword_smallbbox = 0; +cvar_t *broadsword_extra1 = 0; +cvar_t *broadsword_extra2 = 0; + +cvar_t *broadsword_effcorr = 0; +cvar_t *broadsword_ragtobase = 0; +cvar_t *broadsword_dircap = 0; + +cvar_t *r_marksOnTriangleMeshes; + +cvar_t *r_aviMotionJpegQuality; +cvar_t *r_screenshotJpegQuality; +cvar_t *r_surfaceSprites; // the limits apply to the sum of all scenes in a frame -- // the main view, all the 3D icons, etc -#define DEFAULT_MAX_POLYS 600 -#define DEFAULT_MAX_POLYVERTS 3000 -cvar_t *r_maxpolys; -cvar_t *r_maxpolyverts; -int max_polys; -int max_polyverts; - -cvar_t *r_dynamicGlow; -cvar_t *r_dynamicGlowPasses; -cvar_t *r_dynamicGlowDelta; -cvar_t *r_dynamicGlowIntensity; -cvar_t *r_dynamicGlowSoft; -cvar_t *r_dynamicGlowWidth; -cvar_t *r_dynamicGlowHeight; +#define DEFAULT_MAX_POLYS 600 +#define DEFAULT_MAX_POLYVERTS 3000 +cvar_t *r_maxpolys; +cvar_t *r_maxpolyverts; +int max_polys; +int max_polyverts; + +cvar_t *r_dynamicGlow; +cvar_t *r_dynamicGlowPasses; +cvar_t *r_dynamicGlowDelta; +cvar_t *r_dynamicGlowIntensity; +cvar_t *r_dynamicGlowSoft; +cvar_t *r_dynamicGlowWidth; +cvar_t *r_dynamicGlowHeight; cvar_t *r_debugContext; cvar_t *r_debugWeather; -cvar_t *r_aspectCorrectFonts; +cvar_t *r_aspectCorrectFonts; -cvar_t *r_patchStitching; +cvar_t *r_patchStitching; -extern void RB_SetGL2D (void); -static void R_Splash() -{ - const GLfloat black[] = { 0.0f, 0.0f, 0.0f, 1.0f }; +extern void RB_SetGL2D(void); +static void R_Splash() { + const GLfloat black[] = {0.0f, 0.0f, 0.0f, 1.0f}; - qglViewport( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); + qglViewport(0, 0, glConfig.vidWidth, glConfig.vidHeight); qglClearBufferfv(GL_COLOR, 0, black); qglClear(GL_DEPTH_BUFFER_BIT); @@ -288,9 +285,9 @@ static void R_Splash() GL_Cull(CT_TWO_SIDED); - image_t *pImage = R_FindImageFile( "menu/splash", IMGTYPE_COLORALPHA, IMGFLAG_NONE); - if (pImage ) - GL_Bind( pImage ); + image_t *pImage = R_FindImageFile("menu/splash", IMGTYPE_COLORALPHA, IMGFLAG_NONE); + if (pImage) + GL_Bind(pImage); GL_State(GLS_DEPTHTEST_DISABLE); GLSL_BindProgram(&tr.splashScreenShader); @@ -304,115 +301,84 @@ static void R_Splash() Cannot use strstr directly to differentiate between (for eg) reg_combiners and reg_combiners2 */ -bool GL_CheckForExtension(const char *ext) -{ - const char *ptr = Q_stristr( glConfigExt.originalExtensionString, ext ); +bool GL_CheckForExtension(const char *ext) { + const char *ptr = Q_stristr(glConfigExt.originalExtensionString, ext); if (ptr == NULL) return false; ptr += strlen(ext); - return ((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. + return ((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. } - -void GLW_InitTextureCompression( void ) -{ +void GLW_InitTextureCompression(void) { bool newer_tc, old_tc; // Check for available tc methods. newer_tc = GL_CheckForExtension("ARB_texture_compression") && GL_CheckForExtension("EXT_texture_compression_s3tc"); old_tc = GL_CheckForExtension("GL_S3_s3tc"); - if ( old_tc ) - { - Com_Printf ("...GL_S3_s3tc available\n" ); + if (old_tc) { + Com_Printf("...GL_S3_s3tc available\n"); } - if ( newer_tc ) - { - Com_Printf ("...GL_EXT_texture_compression_s3tc available\n" ); + if (newer_tc) { + Com_Printf("...GL_EXT_texture_compression_s3tc available\n"); } - if ( !r_ext_compressed_textures->value ) - { + if (!r_ext_compressed_textures->value) { // Compressed textures are off glConfig.textureCompression = TC_NONE; - Com_Printf ("...ignoring texture compression\n" ); - } - else if ( !old_tc && !newer_tc ) - { + Com_Printf("...ignoring texture compression\n"); + } else if (!old_tc && !newer_tc) { // Requesting texture compression, but no method found glConfig.textureCompression = TC_NONE; - Com_Printf ("...no supported texture compression method found\n" ); - Com_Printf (".....ignoring texture compression\n" ); - } - else - { + Com_Printf("...no supported texture compression method found\n"); + Com_Printf(".....ignoring texture compression\n"); + } else { // some form of supported texture compression is avaiable, so see if the user has a preference - if ( r_ext_preferred_tc_method->integer == TC_NONE ) - { + if (r_ext_preferred_tc_method->integer == TC_NONE) { // No preference, so pick the best - if ( newer_tc ) - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_S3_s3tc\n" ); + } else { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } - } - else - { + } else { // User has specified a preference, now see if this request can be honored - if ( old_tc && newer_tc ) - { + if (old_tc && newer_tc) { // both are avaiable, so we can use the desired tc method - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { - Com_Printf ("...using preferred tc method, GL_S3_s3tc\n" ); + if (r_ext_preferred_tc_method->integer == TC_S3TC) { + Com_Printf("...using preferred tc method, GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { - Com_Printf ("...using preferred tc method, GL_EXT_texture_compression_s3tc\n" ); + } else { + Com_Printf("...using preferred tc method, GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Both methods are not available, so this gets trickier - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { + if (r_ext_preferred_tc_method->integer == TC_S3TC) { // Preferring to user older compression - if ( old_tc ) - { - Com_Printf ("...using GL_S3_s3tc\n" ); + if (old_tc) { + Com_Printf("...using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_S3_s3tc not available\n" ); - Com_Printf (".....falling back to GL_EXT_texture_compression_s3tc\n" ); + Com_Printf("...preferred tc method, GL_S3_s3tc not available\n"); + Com_Printf(".....falling back to GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Preferring to user newer compression - if ( newer_tc ) - { - Com_Printf ("...using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n" ); - Com_Printf (".....falling back to GL_S3_s3tc\n" ); + Com_Printf("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n"); + Com_Printf(".....falling back to GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } } @@ -422,51 +388,45 @@ void GLW_InitTextureCompression( void ) } // Truncates the GL extensions string by only allowing up to 'maxExtensions' extensions in the string. -static const char *TruncateGLExtensionsString (const char *extensionsString, int maxExtensions) -{ +static const char *TruncateGLExtensionsString(const char *extensionsString, int maxExtensions) { const char *p = extensionsString; const char *q; int numExtensions = 0; - size_t extensionsLen = strlen (extensionsString); + size_t extensionsLen = strlen(extensionsString); char *truncatedExtensions; - while ( (q = strchr (p, ' ')) != NULL && numExtensions < maxExtensions ) - { + while ((q = strchr(p, ' ')) != NULL && numExtensions < maxExtensions) { p = q + 1; numExtensions++; } - if ( q != NULL ) - { + if (q != NULL) { // We still have more extensions. We'll call this the end extensionsLen = p - extensionsString - 1; } truncatedExtensions = (char *)Z_Malloc(extensionsLen + 1, TAG_GENERAL); - Q_strncpyz (truncatedExtensions, extensionsString, extensionsLen + 1); + Q_strncpyz(truncatedExtensions, extensionsString, extensionsLen + 1); return truncatedExtensions; } -static const char *GetGLExtensionsString() -{ +static const char *GetGLExtensionsString() { GLint numExtensions; glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); size_t extensionStringLen = 0; - for ( int i = 0; i < numExtensions; i++ ) - { + for (int i = 0; i < numExtensions; i++) { extensionStringLen += strlen((const char *)qglGetStringi(GL_EXTENSIONS, i)) + 1; } char *extensionString = (char *)Z_Malloc(extensionStringLen + 1, TAG_GENERAL); char *p = extensionString; - for ( int i = 0; i < numExtensions; i++ ) - { + for (int i = 0; i < numExtensions; i++) { const char *extension = (const char *)qglGetStringi(GL_EXTENSIONS, i); - while ( *extension != '\0' ) + while (*extension != '\0') *p++ = *extension++; *p++ = ' '; @@ -486,8 +446,7 @@ static const char *GetGLExtensionsString() ** setting variables, checking GL constants, and reporting the gfx system config ** to the user. */ -static void InitOpenGL( void ) -{ +static void InitOpenGL(void) { // // initialize OS specific portions of the renderer // @@ -499,8 +458,7 @@ static void InitOpenGL( void ) // - r_gamma // - if ( glConfig.vidWidth == 0 ) - { + if (glConfig.vidWidth == 0) { windowDesc_t windowDesc = {}; memset(&glConfig, 0, sizeof(glConfig)); @@ -508,42 +466,35 @@ static void InitOpenGL( void ) windowDesc.gl.majorVersion = 3; windowDesc.gl.minorVersion = 2; windowDesc.gl.profile = GLPROFILE_CORE; - if ( r_debugContext->integer ) + if (r_debugContext->integer) windowDesc.gl.contextFlags = GLCONTEXT_DEBUG; window = ri.WIN_Init(&windowDesc, &glConfig); GLimp_InitCoreFunctions(); - Com_Printf( "GL_RENDERER: %s\n", (char *)qglGetString (GL_RENDERER) ); + Com_Printf("GL_RENDERER: %s\n", (char *)qglGetString(GL_RENDERER)); // get our config strings - glConfig.vendor_string = (const char *)qglGetString (GL_VENDOR); - glConfig.renderer_string = (const char *)qglGetString (GL_RENDERER); - glConfig.version_string = (const char *)qglGetString (GL_VERSION); + glConfig.vendor_string = (const char *)qglGetString(GL_VENDOR); + glConfig.renderer_string = (const char *)qglGetString(GL_RENDERER); + glConfig.version_string = (const char *)qglGetString(GL_VERSION); glConfig.extensions_string = GetGLExtensionsString(); glConfigExt.originalExtensionString = glConfig.extensions_string; glConfig.extensions_string = TruncateGLExtensionsString(glConfigExt.originalExtensionString, 128); // OpenGL driver constants - qglGetIntegerv( GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize ); + qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize); // Determine GPU IHV - if ( Q_stristr( glConfig.vendor_string, "ATI Technologies Inc." ) ) - { + if (Q_stristr(glConfig.vendor_string, "ATI Technologies Inc.")) { glRefConfig.hardwareVendor = IHV_AMD; - } - else if ( Q_stristr( glConfig.vendor_string, "NVIDIA" ) ) - { + } else if (Q_stristr(glConfig.vendor_string, "NVIDIA")) { glRefConfig.hardwareVendor = IHV_NVIDIA; - } - else if ( Q_stristr( glConfig.vendor_string, "INTEL") ) - { + } else if (Q_stristr(glConfig.vendor_string, "INTEL")) { glRefConfig.hardwareVendor = IHV_INTEL; - } - else - { + } else { glRefConfig.hardwareVendor = IHV_UNKNOWN; } @@ -562,10 +513,8 @@ static void InitOpenGL( void ) // set default state GL_SetDefaultState(); - R_Splash(); //get something on screen asap - } - else - { + R_Splash(); // get something on screen asap + } else { // set default state GL_SetDefaultState(); } @@ -576,37 +525,37 @@ static void InitOpenGL( void ) GL_CheckErrors ================== */ -void GL_CheckErrs( const char *file, int line ) { +void GL_CheckErrs(const char *file, int line) { #if defined(_DEBUG) - GLenum err; - char s[64]; + GLenum err; + char s[64]; err = qglGetError(); - if ( err == GL_NO_ERROR ) { + if (err == GL_NO_ERROR) { return; } - if ( r_ignoreGLErrors->integer ) { + if (r_ignoreGLErrors->integer) { return; } - switch( err ) { - case GL_INVALID_ENUM: - strcpy( s, "GL_INVALID_ENUM" ); - break; - case GL_INVALID_VALUE: - strcpy( s, "GL_INVALID_VALUE" ); - break; - case GL_INVALID_OPERATION: - strcpy( s, "GL_INVALID_OPERATION" ); - break; - case GL_OUT_OF_MEMORY: - strcpy( s, "GL_OUT_OF_MEMORY" ); - break; - default: - Com_sprintf( s, sizeof(s), "%i", err); - break; + switch (err) { + case GL_INVALID_ENUM: + strcpy(s, "GL_INVALID_ENUM"); + break; + case GL_INVALID_VALUE: + strcpy(s, "GL_INVALID_VALUE"); + break; + case GL_INVALID_OPERATION: + strcpy(s, "GL_INVALID_OPERATION"); + break; + case GL_OUT_OF_MEMORY: + strcpy(s, "GL_OUT_OF_MEMORY"); + break; + default: + Com_sprintf(s, sizeof(s), "%i", err); + break; } - ri.Error( ERR_FATAL, "GL_CheckErrors: %s in %s at line %d", s , file, line); + ri.Error(ERR_FATAL, "GL_CheckErrors: %s in %s at line %d", s, file, line); #endif } @@ -646,9 +595,7 @@ Return value must be freed with ri.Hunk_FreeTempMemory() ================== */ -static byte *RB_ReadPixels( - int x, int y, int width, int height, size_t *offset, int *padlen) -{ +static byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen) { byte *buffer, *bufstart; int padwidth, linelen; GLint packAlign; @@ -661,7 +608,7 @@ static byte *RB_ReadPixels( // Allocate a few more bytes so that we can choose an alignment we like buffer = (byte *)ri.Hunk_AllocateTempMemory(padwidth * height + *offset + packAlign - 1); - bufstart = (byte*)(PADP((intptr_t) buffer + *offset, packAlign)); + bufstart = (byte *)(PADP((intptr_t)buffer + *offset, packAlign)); qglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, bufstart); *offset = bufstart - buffer; @@ -670,15 +617,11 @@ static byte *RB_ReadPixels( return buffer; } -static void ConvertRGBtoBGR( - byte *dst, const byte *src, int stride, int width, int height) -{ +static void ConvertRGBtoBGR(byte *dst, const byte *src, int stride, int width, int height) { const byte *row = src; - for (int y = 0; y < height; ++y) - { + for (int y = 0; y < height; ++y) { const byte *pixelRGB = row; - for (int x = 0; x < width; ++x) - { + for (int x = 0; x < width; ++x) { // swap rgb to bgr const byte temp = pixelRGB[0]; *dst++ = pixelRGB[2]; @@ -692,13 +635,7 @@ static void ConvertRGBtoBGR( } } -static void R_SaveTGA( - const char *filename, - const byte *pixels, - int width, - int height, - int stride) -{ +static void R_SaveTGA(const char *filename, const byte *pixels, int width, int height, int stride) { const size_t headerSize = 18; const size_t pixelBufferSize = stride * height; const size_t bufferSize = headerSize + pixelBufferSize; @@ -707,7 +644,7 @@ static void R_SaveTGA( // Write TGA header Com_Memset(buffer, 0, headerSize); - buffer[2] = 2; // uncompressed type + buffer[2] = 2; // uncompressed type buffer[12] = width & 255; buffer[13] = width >> 8; buffer[14] = height & 255; @@ -725,15 +662,8 @@ static void R_SaveTGA( R_SaveScreenshotTGA ================== */ -static void R_SaveScreenshotTGA( - const screenshotReadback_t *screenshotReadback, byte *pixels) -{ - R_SaveTGA( - screenshotReadback->filename, - pixels, - screenshotReadback->width, - screenshotReadback->height, - screenshotReadback->strideInBytes); +static void R_SaveScreenshotTGA(const screenshotReadback_t *screenshotReadback, byte *pixels) { + R_SaveTGA(screenshotReadback->filename, pixels, screenshotReadback->width, screenshotReadback->height, screenshotReadback->strideInBytes); } /* @@ -741,15 +671,8 @@ static void R_SaveScreenshotTGA( R_SaveScreenshotPNG ================== */ -static void R_SaveScreenshotPNG( - const screenshotReadback_t *screenshotReadback, byte *pixels) -{ - RE_SavePNG( - screenshotReadback->filename, - pixels, - screenshotReadback->width, - screenshotReadback->height, - 3); +static void R_SaveScreenshotPNG(const screenshotReadback_t *screenshotReadback, byte *pixels) { + RE_SavePNG(screenshotReadback->filename, pixels, screenshotReadback->width, screenshotReadback->height, 3); } /* @@ -757,33 +680,19 @@ static void R_SaveScreenshotPNG( R_SaveScreenshotJPG ================== */ -static void R_SaveScreenshotJPG( - const screenshotReadback_t *screenshotReadback, byte *pixels) -{ - RE_SaveJPG( - screenshotReadback->filename, - r_screenshotJpegQuality->integer, - screenshotReadback->width, - screenshotReadback->height, - pixels, - screenshotReadback->strideInBytes - screenshotReadback->rowInBytes); +static void R_SaveScreenshotJPG(const screenshotReadback_t *screenshotReadback, byte *pixels) { + RE_SaveJPG(screenshotReadback->filename, r_screenshotJpegQuality->integer, screenshotReadback->width, screenshotReadback->height, pixels, + screenshotReadback->strideInBytes - screenshotReadback->rowInBytes); } -void R_SaveScreenshot(screenshotReadback_t *screenshotReadback) -{ +void R_SaveScreenshot(screenshotReadback_t *screenshotReadback) { qglBindBuffer(GL_PIXEL_PACK_BUFFER, screenshotReadback->pbo); - byte *pixelBuffer = static_cast( - qglMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY)); + byte *pixelBuffer = static_cast(qglMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY)); - if (pixelBuffer == nullptr) - { - ri.Printf( - PRINT_ALL, - S_COLOR_RED "Failed to read screenshot data from GPU\n"); - } - else - { + if (pixelBuffer == nullptr) { + ri.Printf(PRINT_ALL, S_COLOR_RED "Failed to read screenshot data from GPU\n"); + } else { const int height = screenshotReadback->height; const int stride = screenshotReadback->strideInBytes; const size_t pixelBufferSize = stride * height; @@ -795,19 +704,18 @@ void R_SaveScreenshot(screenshotReadback_t *screenshotReadback) if (glConfig.deviceSupportsGamma) R_GammaCorrect(pixels, pixelBufferSize); - switch (screenshotReadback->format) - { - case SSF_JPEG: - R_SaveScreenshotJPG(screenshotReadback, pixels); - break; + switch (screenshotReadback->format) { + case SSF_JPEG: + R_SaveScreenshotJPG(screenshotReadback, pixels); + break; - case SSF_TGA: - R_SaveScreenshotTGA(screenshotReadback, pixels); - break; + case SSF_TGA: + R_SaveScreenshotTGA(screenshotReadback, pixels); + break; - case SSF_PNG: - R_SaveScreenshotPNG(screenshotReadback, pixels); - break; + case SSF_PNG: + R_SaveScreenshotPNG(screenshotReadback, pixels); + break; } ri.Hunk_FreeTempMemory(pixels); @@ -822,7 +730,7 @@ void R_SaveScreenshot(screenshotReadback_t *screenshotReadback) R_TakeScreenshotCmd ================== */ -const void *RB_TakeScreenshotCmd( const void *data ) { +const void *RB_TakeScreenshotCmd(const void *data) { const screenshotCommand_t *cmd; cmd = (const screenshotCommand_t *)data; @@ -843,21 +751,15 @@ const void *RB_TakeScreenshotCmd( const void *data ) { qglGenBuffers(1, &screenshot->pbo); qglBindBuffer(GL_PIXEL_PACK_BUFFER, screenshot->pbo); - qglBufferData( - GL_PIXEL_PACK_BUFFER, - strideInBytes * cmd->height, - nullptr, - GL_STATIC_COPY); - qglReadPixels( - cmd->x, cmd->y, cmd->width, cmd->height, GL_RGB, GL_UNSIGNED_BYTE, 0); + qglBufferData(GL_PIXEL_PACK_BUFFER, strideInBytes * cmd->height, nullptr, GL_STATIC_COPY); + qglReadPixels(cmd->x, cmd->y, cmd->width, cmd->height, GL_RGB, GL_UNSIGNED_BYTE, 0); screenshot->strideInBytes = strideInBytes; screenshot->rowInBytes = linelen; screenshot->width = cmd->width; screenshot->height = cmd->height; screenshot->format = cmd->format; - Q_strncpyz( - screenshot->filename, cmd->fileName, sizeof(screenshot->filename)); + Q_strncpyz(screenshot->filename, cmd->fileName, sizeof(screenshot->filename)); return (const void *)(cmd + 1); } @@ -867,12 +769,12 @@ const void *RB_TakeScreenshotCmd( const void *data ) { R_TakeScreenshot ================== */ -void R_TakeScreenshot( int x, int y, int width, int height, char *name, screenshotFormat_t format ) { - static char fileName[MAX_OSPATH]; // bad things if two screenshots per frame? - screenshotCommand_t *cmd; +void R_TakeScreenshot(int x, int y, int width, int height, char *name, screenshotFormat_t format) { + static char fileName[MAX_OSPATH]; // bad things if two screenshots per frame? + screenshotCommand_t *cmd; - cmd = (screenshotCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (screenshotCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_SCREENSHOT; @@ -881,7 +783,7 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *name, screensh cmd->y = y; cmd->width = width; cmd->height = height; - Q_strncpyz( fileName, name, sizeof(fileName) ); + Q_strncpyz(fileName, name, sizeof(fileName)); cmd->fileName = fileName; cmd->format = format; } @@ -891,14 +793,14 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *name, screensh R_ScreenshotFilename ================== */ -void R_ScreenshotFilename( char *buf, int bufSize, const char *ext ) { +void R_ScreenshotFilename(char *buf, int bufSize, const char *ext) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "screenshots/shot%s%s", timeStr, ext ); + Com_sprintf(buf, bufSize, "screenshots/shot%s%s", timeStr, ext); } /* @@ -910,47 +812,47 @@ the menu system, sampled down from full screen distorted images ==================== */ #define LEVELSHOTSIZE 256 -static void R_LevelShot( void ) { - char checkname[MAX_OSPATH]; - byte *buffer; - byte *source, *allsource; - byte *src, *dst; - size_t offset = 0; - int padlen; - int x, y; - int r, g, b; - float xScale, yScale; - int xx, yy; - - Com_sprintf( checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName ); +static void R_LevelShot(void) { + char checkname[MAX_OSPATH]; + byte *buffer; + byte *source, *allsource; + byte *src, *dst; + size_t offset = 0; + int padlen; + int x, y; + int r, g, b; + float xScale, yScale; + int xx, yy; + + Com_sprintf(checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName); allsource = RB_ReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, &offset, &padlen); source = allsource + offset; - buffer = (byte *)ri.Hunk_AllocateTempMemory(LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18); - Com_Memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type + buffer = (byte *)ri.Hunk_AllocateTempMemory(LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18); + Com_Memset(buffer, 0, 18); + buffer[2] = 2; // uncompressed type buffer[12] = LEVELSHOTSIZE & 255; buffer[13] = LEVELSHOTSIZE >> 8; buffer[14] = LEVELSHOTSIZE & 255; buffer[15] = LEVELSHOTSIZE >> 8; - buffer[16] = 24; // pixel size + buffer[16] = 24; // pixel size // resample from source - xScale = glConfig.vidWidth / (4.0*LEVELSHOTSIZE); - yScale = glConfig.vidHeight / (3.0*LEVELSHOTSIZE); - for ( y = 0 ; y < LEVELSHOTSIZE ; y++ ) { - for ( x = 0 ; x < LEVELSHOTSIZE ; x++ ) { + xScale = glConfig.vidWidth / (4.0 * LEVELSHOTSIZE); + yScale = glConfig.vidHeight / (3.0 * LEVELSHOTSIZE); + for (y = 0; y < LEVELSHOTSIZE; y++) { + for (x = 0; x < LEVELSHOTSIZE; x++) { r = g = b = 0; - for ( yy = 0 ; yy < 3 ; yy++ ) { - for ( xx = 0 ; xx < 4 ; xx++ ) { - src = source + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) ); + for (yy = 0; yy < 3; yy++) { + for (xx = 0; xx < 4; xx++) { + src = source + 3 * (glConfig.vidWidth * (int)((y * 3 + yy) * yScale) + (int)((x * 4 + xx) * xScale)); r += src[0]; g += src[1]; b += src[2]; } } - dst = buffer + 18 + 3 * ( y * LEVELSHOTSIZE + x ); + dst = buffer + 18 + 3 * (y * LEVELSHOTSIZE + x); dst[0] = b / 12; dst[1] = g / 12; dst[2] = r / 12; @@ -958,16 +860,16 @@ static void R_LevelShot( void ) { } // gamma correct - if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) { - R_GammaCorrect( buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 ); + if ((tr.overbrightBits > 0) && glConfig.deviceSupportsGamma) { + R_GammaCorrect(buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3); } - ri.FS_WriteFile( checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18 ); + ri.FS_WriteFile(checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18); - ri.Hunk_FreeTempMemory( buffer ); - ri.Hunk_FreeTempMemory( allsource ); + ri.Hunk_FreeTempMemory(buffer); + ri.Hunk_FreeTempMemory(allsource); - ri.Printf( PRINT_ALL, "Wrote %s\n", checkname ); + ri.Printf(PRINT_ALL, "Wrote %s\n", checkname); } /* @@ -982,100 +884,97 @@ screenshot [filename] Doesn't print the pacifier message if there is a second arg ================== */ -void R_ScreenShotTGA_f (void) { +void R_ScreenShotTGA_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.tga", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.tga", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".tga" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".tga"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_TGA ); + R_TakeScreenshot(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_TGA); - if ( !silent ) - ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); + if (!silent) + ri.Printf(PRINT_ALL, "Wrote %s\n", checkname); } -void R_ScreenShotPNG_f (void) { +void R_ScreenShotPNG_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.png", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.png", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".png" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".png"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_PNG ); + R_TakeScreenshot(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_PNG); - if ( !silent ) - ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); + if (!silent) + ri.Printf(PRINT_ALL, "Wrote %s\n", checkname); } -void R_ScreenShotJPEG_f (void) { +void R_ScreenShotJPEG_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.jpg", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.jpg", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".jpg" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".jpg"); - if ( ri.FS_FileExists( checkname ) ) { - Com_Printf( "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + Com_Printf("ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_JPEG ); + R_TakeScreenshot(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_JPEG); - if ( !silent ) - ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); + if (!silent) + ri.Printf(PRINT_ALL, "Wrote %s\n", checkname); } //============================================================================ @@ -1085,16 +984,15 @@ void R_ScreenShotJPEG_f (void) { RB_TakeVideoFrameCmd ================== */ -const void *RB_TakeVideoFrameCmd( const void *data ) -{ - const videoFrameCommand_t *cmd; - byte *cBuf; - size_t memcount, linelen; - int padwidth, avipadwidth, padlen, avipadlen; +const void *RB_TakeVideoFrameCmd(const void *data) { + const videoFrameCommand_t *cmd; + byte *cBuf; + size_t memcount, linelen; + int padwidth, avipadwidth, padlen, avipadlen; GLint packAlign; // finish any 2D drawing if needed - if(tess.numIndexes) + if (tess.numIndexes) RB_EndSurface(); cmd = (const videoFrameCommand_t *)data; @@ -1110,26 +1008,20 @@ const void *RB_TakeVideoFrameCmd( const void *data ) avipadwidth = PAD(linelen, AVI_LINE_PADDING); avipadlen = avipadwidth - linelen; - cBuf = (byte*)(PADP(cmd->captureBuffer, packAlign)); + cBuf = (byte *)(PADP(cmd->captureBuffer, packAlign)); - qglReadPixels(0, 0, cmd->width, cmd->height, GL_RGB, - GL_UNSIGNED_BYTE, cBuf); + qglReadPixels(0, 0, cmd->width, cmd->height, GL_RGB, GL_UNSIGNED_BYTE, cBuf); memcount = padwidth * cmd->height; // gamma correct - if(glConfig.deviceSupportsGamma) + if (glConfig.deviceSupportsGamma) R_GammaCorrect(cBuf, memcount); - if(cmd->motionJpeg) - { - memcount = RE_SaveJPGToBuffer(cmd->encodeBuffer, linelen * cmd->height, - r_aviMotionJpegQuality->integer, - cmd->width, cmd->height, cBuf, padlen); + if (cmd->motionJpeg) { + memcount = RE_SaveJPGToBuffer(cmd->encodeBuffer, linelen * cmd->height, r_aviMotionJpegQuality->integer, cmd->width, cmd->height, cBuf, padlen); ri.CL_WriteAVIVideoFrame(cmd->encodeBuffer, memcount); - } - else - { + } else { byte *lineend, *memend; byte *srcptr, *destptr; @@ -1138,11 +1030,9 @@ const void *RB_TakeVideoFrameCmd( const void *data ) memend = srcptr + memcount; // swap R and B and remove line paddings - while(srcptr < memend) - { + while (srcptr < memend) { lineend = srcptr + linelen; - while(srcptr < lineend) - { + while (srcptr < lineend) { *destptr++ = srcptr[2]; *destptr++ = srcptr[1]; *destptr++ = srcptr[0]; @@ -1166,22 +1056,21 @@ const void *RB_TakeVideoFrameCmd( const void *data ) /* ** GL_SetDefaultState */ -void GL_SetDefaultState( void ) -{ - qglClearDepth( 1.0f ); +void GL_SetDefaultState(void) { + qglClearDepth(1.0f); qglCullFace(GL_FRONT); // initialize downstream texture unit if we're running // in a multitexture environment - GL_SelectTexture( 1 ); - GL_TextureMode( r_textureMode->string ); - GL_SelectTexture( 0 ); + GL_SelectTexture(1); + GL_TextureMode(r_textureMode->string); + GL_SelectTexture(0); - GL_TextureMode( r_textureMode->string ); + GL_TextureMode(r_textureMode->string); - //qglShadeModel( GL_SMOOTH ); - qglDepthFunc( GL_LEQUAL ); + // qglShadeModel( GL_SMOOTH ); + qglDepthFunc(GL_LEQUAL); Com_Memset(&glState, 0, sizeof(glState)); @@ -1197,13 +1086,13 @@ void GL_SetDefaultState( void ) qglBindBuffer(GL_ARRAY_BUFFER, 0); qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - qglDepthMask( GL_TRUE ); - qglDisable( GL_DEPTH_TEST ); - qglEnable( GL_SCISSOR_TEST ); + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + qglDepthMask(GL_TRUE); + qglDisable(GL_DEPTH_TEST); + qglEnable(GL_SCISSOR_TEST); qglEnable(GL_PROGRAM_POINT_SIZE); - qglDisable( GL_CULL_FACE ); - qglDisable( GL_BLEND ); + qglDisable(GL_CULL_FACE); + qglDisable(GL_BLEND); qglEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); @@ -1228,10 +1117,9 @@ void R_PrintLongString(const char *string) { int size = strlen(string); p = string; - while(size > 0) - { - Q_strncpyz(buffer, p, sizeof (buffer) ); - ri.Printf( PRINT_ALL, "%s", buffer ); + while (size > 0) { + Q_strncpyz(buffer, p, sizeof(buffer)); + ri.Printf(PRINT_ALL, "%s", buffer); p += 1023; size -= 1023; } @@ -1242,75 +1130,52 @@ void R_PrintLongString(const char *string) { GfxInfo_f ================ */ -static void GfxInfo_f( void ) -{ - const char *enablestrings[] = - { - "disabled", - "enabled" - }; - const char *fsstrings[] = - { - "windowed", - "fullscreen" - }; - const char *noborderstrings[] = - { - "", - "noborder " - }; +static void GfxInfo_f(void) { + const char *enablestrings[] = {"disabled", "enabled"}; + const char *fsstrings[] = {"windowed", "fullscreen"}; + const char *noborderstrings[] = {"", "noborder "}; int fullscreen = ri.Cvar_VariableIntegerValue("r_fullscreen"); int noborder = ri.Cvar_VariableIntegerValue("r_noborder"); - ri.Printf( PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string ); - ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string ); - ri.Printf( PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string ); - ri.Printf( PRINT_ALL, "GL_EXTENSIONS: " ); - R_PrintLongString( glConfigExt.originalExtensionString ); - ri.Printf( PRINT_ALL, "\n" ); - ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize ); - ri.Printf( PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); - ri.Printf( PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", - ri.Cvar_VariableIntegerValue("r_mode"), - glConfig.vidWidth, glConfig.vidHeight, - fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], - fsstrings[fullscreen == 1] ); - if ( glConfig.displayFrequency ) - { - ri.Printf( PRINT_ALL, "%d\n", glConfig.displayFrequency ); - } - else - { - ri.Printf( PRINT_ALL, "N/A\n" ); + ri.Printf(PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string); + ri.Printf(PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string); + ri.Printf(PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string); + ri.Printf(PRINT_ALL, "GL_EXTENSIONS: "); + R_PrintLongString(glConfigExt.originalExtensionString); + ri.Printf(PRINT_ALL, "\n"); + ri.Printf(PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize); + ri.Printf(PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits); + ri.Printf(PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", ri.Cvar_VariableIntegerValue("r_mode"), glConfig.vidWidth, glConfig.vidHeight, + fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], fsstrings[fullscreen == 1]); + if (glConfig.displayFrequency) { + ri.Printf(PRINT_ALL, "%d\n", glConfig.displayFrequency); + } else { + ri.Printf(PRINT_ALL, "N/A\n"); } - if ( glConfig.deviceSupportsGamma ) - { - ri.Printf( PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits ); - } - else - { - ri.Printf( PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits ); + if (glConfig.deviceSupportsGamma) { + ri.Printf(PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits); + } else { + ri.Printf(PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits); } - ri.Printf( PRINT_ALL, "texturemode: %s\n", r_textureMode->string ); - ri.Printf( PRINT_ALL, "picmip: %d\n", r_picmip->integer ); - ri.Printf( PRINT_ALL, "texture bits: %d\n", r_texturebits->integer ); + ri.Printf(PRINT_ALL, "texturemode: %s\n", r_textureMode->string); + ri.Printf(PRINT_ALL, "picmip: %d\n", r_picmip->integer); + ri.Printf(PRINT_ALL, "texture bits: %d\n", r_texturebits->integer); - if ( r_vertexLight->integer ) - { - ri.Printf( PRINT_ALL, "HACK: using vertex lightmap approximation\n" ); + if (r_vertexLight->integer) { + ri.Printf(PRINT_ALL, "HACK: using vertex lightmap approximation\n"); } int displayRefresh = ri.Cvar_VariableIntegerValue("r_displayRefresh"); - if ( displayRefresh ) { - ri.Printf( PRINT_ALL, "Display refresh set to %d\n", displayRefresh ); + if (displayRefresh) { + ri.Printf(PRINT_ALL, "Display refresh set to %d\n", displayRefresh); } - if ( r_finish->integer ) { - ri.Printf( PRINT_ALL, "Forcing glFinish\n" ); + if (r_finish->integer) { + ri.Printf(PRINT_ALL, "Forcing glFinish\n"); } - ri.Printf( PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_dynamicGlow->integer != 0] ); + ri.Printf(PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_dynamicGlow->integer != 0]); } /* @@ -1318,244 +1183,231 @@ static void GfxInfo_f( void ) GfxMemInfo_f ================ */ -void GfxMemInfo_f( void ) -{ - switch (glRefConfig.memInfo) - { - case MI_NONE: - { - ri.Printf(PRINT_ALL, "No extension found for GPU memory info.\n"); - } - break; - case MI_NVX: - { - int value; - - qglGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &value); - ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX: %ikb\n", value); - - qglGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &value); - ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX: %ikb\n", value); - - qglGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &value); - ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX: %ikb\n", value); - - qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &value); - ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTION_COUNT_NVX: %i\n", value); - - qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &value); - ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTED_MEMORY_NVX: %ikb\n", value); - } - break; - case MI_ATI: - { - // GL_ATI_meminfo - int value[4]; - - qglGetIntegerv(GL_VBO_FREE_MEMORY_ATI, &value[0]); - ri.Printf(PRINT_ALL, "VBO_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); - - qglGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, &value[0]); - ri.Printf(PRINT_ALL, "TEXTURE_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); - - qglGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, &value[0]); - ri.Printf(PRINT_ALL, "RENDERBUFFER_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); - } - break; +void GfxMemInfo_f(void) { + switch (glRefConfig.memInfo) { + case MI_NONE: { + ri.Printf(PRINT_ALL, "No extension found for GPU memory info.\n"); + } break; + case MI_NVX: { + int value; + + qglGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTION_COUNT_NVX: %i\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTED_MEMORY_NVX: %ikb\n", value); + } break; + case MI_ATI: { + // GL_ATI_meminfo + int value[4]; + + qglGetIntegerv(GL_VBO_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "VBO_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + + qglGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "TEXTURE_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + + qglGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "RENDERBUFFER_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + } break; } } -static void R_CaptureFrameData_f() -{ +static void R_CaptureFrameData_f() { int argc = ri.Cmd_Argc(); - if ( argc <= 1 ) - { - ri.Printf( PRINT_ALL, "Usage: %s \n", ri.Cmd_Argv(0)); + if (argc <= 1) { + ri.Printf(PRINT_ALL, "Usage: %s \n", ri.Cmd_Argv(0)); return; } - const char *cmd = ri.Cmd_Argv(1); - if ( Q_stricmp(cmd, "single") == 0 ) + if (Q_stricmp(cmd, "single") == 0) tr.numFramesToCapture = 1; - else if ( Q_stricmp(cmd, "multi") == 0 ) + else if (Q_stricmp(cmd, "multi") == 0) tr.numFramesToCapture = atoi(ri.Cmd_Argv(1)); int len = ri.FS_FOpenFileByMode("rend2.log", &tr.debugFile, FS_APPEND); - if ( len == -1 || !tr.debugFile ) - { - ri.Printf( PRINT_ERROR, "Failed to open rend2 log file\n" ); + if (len == -1 || !tr.debugFile) { + ri.Printf(PRINT_ERROR, "Failed to open rend2 log file\n"); tr.numFramesToCapture = 0; } } typedef struct consoleCommand_s { - const char *cmd; - xcommand_t func; + const char *cmd; + xcommand_t func; } consoleCommand_t; -static consoleCommand_t commands[] = { - { "imagelist", R_ImageList_f }, - { "shaderlist", R_ShaderList_f }, - { "skinlist", R_SkinList_f }, - { "fontlist", R_FontList_f }, - { "screenshot", R_ScreenShotJPEG_f }, - { "screenshot_png", R_ScreenShotPNG_f }, - { "screenshot_tga", R_ScreenShotTGA_f }, - { "gfxinfo", GfxInfo_f }, - { "gfxmeminfo", GfxMemInfo_f }, - { "r_we", R_WorldEffect_f }, +static consoleCommand_t commands[] = { + {"imagelist", R_ImageList_f}, + {"shaderlist", R_ShaderList_f}, + {"skinlist", R_SkinList_f}, + {"fontlist", R_FontList_f}, + {"screenshot", R_ScreenShotJPEG_f}, + {"screenshot_png", R_ScreenShotPNG_f}, + {"screenshot_tga", R_ScreenShotTGA_f}, + {"gfxinfo", GfxInfo_f}, + {"gfxmeminfo", GfxMemInfo_f}, + {"r_we", R_WorldEffect_f}, //{ "imagecacheinfo", RE_RegisterImages_Info_f }, - { "modellist", R_Modellist_f }, + {"modellist", R_Modellist_f}, //{ "modelcacheinfo", RE_RegisterModels_Info_f }, - { "vbolist", R_VBOList_f }, - { "capframes", R_CaptureFrameData_f }, + {"vbolist", R_VBOList_f}, + {"capframes", R_CaptureFrameData_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); - +static const size_t numCommands = ARRAY_LEN(commands); /* =============== R_Register =============== */ -void R_Register( void ) -{ +void R_Register(void) { // // latched and archived variables // - r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE | CVAR_LATCH, "Allow GL extensions" ); - r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compress_textures", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable texture compression" ); - r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); - r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); - r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); - r_ext_preferred_tc_method = ri.Cvar_Get( "r_ext_preferred_tc_method", "0", CVAR_ARCHIVE | CVAR_LATCH, "Preferred texture compression method" ); - - r_ext_draw_range_elements = ri.Cvar_Get( "r_ext_draw_range_elements", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); - r_ext_multi_draw_arrays = ri.Cvar_Get( "r_ext_multi_draw_arrays", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); - r_ext_texture_float = ri.Cvar_Get( "r_ext_texture_float", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable floating-point textures" ); - r_arb_half_float_pixel = ri.Cvar_Get( "r_arb_half_float_pixel", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable ARB_half_float GL extension" ); - r_ext_framebuffer_multisample = ri.Cvar_Get( "r_ext_multisample", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable framebuffer MSAA" ); - r_arb_seamless_cube_map = ri.Cvar_Get( "r_arb_seamless_cube_map", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable seamless cube map filtering GL extension" ); - r_arb_vertex_type_2_10_10_10_rev = ri.Cvar_Get( "r_arb_vertex_type_2_10_10_10_rev", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable 1010102 UI data type" ); - r_arb_buffer_storage = ri.Cvar_Get( "r_arb_buffer_storage", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable buffer storage GL extension" ); - r_ext_texture_filter_anisotropic = ri.Cvar_Get( "r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE, "Disable/enable anisotropic texture filtering" ); - - r_dynamicGlow = ri.Cvar_Get( "r_dynamicGlow", "0", CVAR_ARCHIVE, "" ); - r_dynamicGlowPasses = ri.Cvar_Get( "r_dynamicGlowPasses", "5", CVAR_ARCHIVE, "" ); - r_dynamicGlowDelta = ri.Cvar_Get( "r_dynamicGlowDelta", "0.8f", CVAR_ARCHIVE, "" ); - r_dynamicGlowIntensity = ri.Cvar_Get( "r_dynamicGlowIntensity", "1.13f", CVAR_ARCHIVE, "" ); - r_dynamicGlowSoft = ri.Cvar_Get( "r_dynamicGlowSoft", "1", CVAR_ARCHIVE, "" ); - r_dynamicGlowWidth = ri.Cvar_Get( "r_dynamicGlowWidth", "320", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_dynamicGlowHeight = ri.Cvar_Get( "r_dynamicGlowHeight", "240", CVAR_ARCHIVE|CVAR_LATCH, "" ); - - r_debugContext = ri.Cvar_Get( "r_debugContext", "0", CVAR_LATCH, "" ); - r_debugWeather = ri.Cvar_Get( "r_debugWeather", "0", CVAR_ARCHIVE, "" ); - - r_picmip = ri.Cvar_Get ("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - ri.Cvar_CheckRange( r_picmip, 0, 16, qtrue ); - r_roundImagesDown = ri.Cvar_Get ("r_roundImagesDown", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_colorMipLevels = ri.Cvar_Get ("r_colorMipLevels", "0", CVAR_LATCH, "" ); - r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_overBrightBits = ri.Cvar_Get ("r_overBrightBits", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_uiFullScreen = ri.Cvar_Get( "r_uifullscreen", "0", 0, ""); - r_subdivisions = ri.Cvar_Get ("r_subdivisions", "4", CVAR_ARCHIVE | CVAR_LATCH, ""); - ri.Cvar_CheckRange( r_subdivisions, 4, 80, qfalse ); - r_stereo = ri.Cvar_Get( "r_stereo", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_allowExtensions = ri.Cvar_Get("r_allowExtensions", "1", CVAR_ARCHIVE | CVAR_LATCH, "Allow GL extensions"); + r_ext_compressed_textures = ri.Cvar_Get("r_ext_compress_textures", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable texture compression"); + r_ext_multitexture = ri.Cvar_Get("r_ext_multitexture", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused"); + r_ext_compiled_vertex_array = ri.Cvar_Get("r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused"); + r_ext_texture_env_add = ri.Cvar_Get("r_ext_texture_env_add", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused"); + r_ext_preferred_tc_method = ri.Cvar_Get("r_ext_preferred_tc_method", "0", CVAR_ARCHIVE | CVAR_LATCH, "Preferred texture compression method"); + + r_ext_draw_range_elements = ri.Cvar_Get("r_ext_draw_range_elements", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused"); + r_ext_multi_draw_arrays = ri.Cvar_Get("r_ext_multi_draw_arrays", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused"); + r_ext_texture_float = ri.Cvar_Get("r_ext_texture_float", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable floating-point textures"); + r_arb_half_float_pixel = ri.Cvar_Get("r_arb_half_float_pixel", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable ARB_half_float GL extension"); + r_ext_framebuffer_multisample = ri.Cvar_Get("r_ext_multisample", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable framebuffer MSAA"); + r_arb_seamless_cube_map = ri.Cvar_Get("r_arb_seamless_cube_map", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable seamless cube map filtering GL extension"); + r_arb_vertex_type_2_10_10_10_rev = ri.Cvar_Get("r_arb_vertex_type_2_10_10_10_rev", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable 1010102 UI data type"); + r_arb_buffer_storage = ri.Cvar_Get("r_arb_buffer_storage", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable buffer storage GL extension"); + r_ext_texture_filter_anisotropic = ri.Cvar_Get("r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE, "Disable/enable anisotropic texture filtering"); + + r_dynamicGlow = ri.Cvar_Get("r_dynamicGlow", "0", CVAR_ARCHIVE, ""); + r_dynamicGlowPasses = ri.Cvar_Get("r_dynamicGlowPasses", "5", CVAR_ARCHIVE, ""); + r_dynamicGlowDelta = ri.Cvar_Get("r_dynamicGlowDelta", "0.8f", CVAR_ARCHIVE, ""); + r_dynamicGlowIntensity = ri.Cvar_Get("r_dynamicGlowIntensity", "1.13f", CVAR_ARCHIVE, ""); + r_dynamicGlowSoft = ri.Cvar_Get("r_dynamicGlowSoft", "1", CVAR_ARCHIVE, ""); + r_dynamicGlowWidth = ri.Cvar_Get("r_dynamicGlowWidth", "320", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_dynamicGlowHeight = ri.Cvar_Get("r_dynamicGlowHeight", "240", CVAR_ARCHIVE | CVAR_LATCH, ""); + + r_debugContext = ri.Cvar_Get("r_debugContext", "0", CVAR_LATCH, ""); + r_debugWeather = ri.Cvar_Get("r_debugWeather", "0", CVAR_ARCHIVE, ""); + + r_picmip = ri.Cvar_Get("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_picmip, 0, 16, qtrue); + r_roundImagesDown = ri.Cvar_Get("r_roundImagesDown", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_colorMipLevels = ri.Cvar_Get("r_colorMipLevels", "0", CVAR_LATCH, ""); + r_detailTextures = ri.Cvar_Get("r_detailtextures", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_texturebits = ri.Cvar_Get("r_texturebits", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_overBrightBits = ri.Cvar_Get("r_overBrightBits", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_simpleMipMaps = ri.Cvar_Get("r_simpleMipMaps", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_vertexLight = ri.Cvar_Get("r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_uiFullScreen = ri.Cvar_Get("r_uifullscreen", "0", 0, ""); + r_subdivisions = ri.Cvar_Get("r_subdivisions", "4", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_subdivisions, 4, 80, qfalse); + r_stereo = ri.Cvar_Get("r_stereo", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); r_greyscale = ri.Cvar_Get("r_greyscale", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); ri.Cvar_CheckRange(r_greyscale, 0, 1, qfalse); - r_externalGLSL = ri.Cvar_Get( "r_externalGLSL", "0", CVAR_LATCH, "" ); + r_externalGLSL = ri.Cvar_Get("r_externalGLSL", "0", CVAR_LATCH, ""); - r_hdr = ri.Cvar_Get( "r_hdr", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable rendering in HDR" ); - r_floatLightmap = ri.Cvar_Get( "r_floatLightmap", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable HDR lightmap support" ); + r_hdr = ri.Cvar_Get("r_hdr", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable rendering in HDR"); + r_floatLightmap = ri.Cvar_Get("r_floatLightmap", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable HDR lightmap support"); - r_toneMap = ri.Cvar_Get( "r_toneMap", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable tonemapping" ); - r_forceToneMap = ri.Cvar_Get( "r_forceToneMap", "0", CVAR_CHEAT, "" ); - r_forceToneMapMin = ri.Cvar_Get( "r_forceToneMapMin", "-8.0", CVAR_CHEAT, "" ); - r_forceToneMapAvg = ri.Cvar_Get( "r_forceToneMapAvg", "-2.0", CVAR_CHEAT, "" ); - r_forceToneMapMax = ri.Cvar_Get( "r_forceToneMapMax", "0.0", CVAR_CHEAT, "" ); + r_toneMap = ri.Cvar_Get("r_toneMap", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable tonemapping"); + r_forceToneMap = ri.Cvar_Get("r_forceToneMap", "0", CVAR_CHEAT, ""); + r_forceToneMapMin = ri.Cvar_Get("r_forceToneMapMin", "-8.0", CVAR_CHEAT, ""); + r_forceToneMapAvg = ri.Cvar_Get("r_forceToneMapAvg", "-2.0", CVAR_CHEAT, ""); + r_forceToneMapMax = ri.Cvar_Get("r_forceToneMapMax", "0.0", CVAR_CHEAT, ""); - r_autoExposure = ri.Cvar_Get( "r_autoExposure", "1", CVAR_ARCHIVE, "Disable/enable auto exposure" ); - r_forceAutoExposure = ri.Cvar_Get( "r_forceAutoExposure", "0", CVAR_CHEAT, "" ); - r_forceAutoExposureMin = ri.Cvar_Get( "r_forceAutoExposureMin", "-2.0", CVAR_CHEAT, "" ); - r_forceAutoExposureMax = ri.Cvar_Get( "r_forceAutoExposureMax", "2.0", CVAR_CHEAT, "" ); + r_autoExposure = ri.Cvar_Get("r_autoExposure", "1", CVAR_ARCHIVE, "Disable/enable auto exposure"); + r_forceAutoExposure = ri.Cvar_Get("r_forceAutoExposure", "0", CVAR_CHEAT, ""); + r_forceAutoExposureMin = ri.Cvar_Get("r_forceAutoExposureMin", "-2.0", CVAR_CHEAT, ""); + r_forceAutoExposureMax = ri.Cvar_Get("r_forceAutoExposureMax", "2.0", CVAR_CHEAT, ""); - r_cameraExposure = ri.Cvar_Get( "r_cameraExposure", "0", CVAR_CHEAT, "" ); + r_cameraExposure = ri.Cvar_Get("r_cameraExposure", "0", CVAR_CHEAT, ""); - r_depthPrepass = ri.Cvar_Get( "r_depthPrepass", "1", CVAR_ARCHIVE, "" ); - r_ssao = ri.Cvar_Get( "r_ssao", "0", CVAR_LATCH | CVAR_ARCHIVE, "" ); + r_depthPrepass = ri.Cvar_Get("r_depthPrepass", "1", CVAR_ARCHIVE, ""); + r_ssao = ri.Cvar_Get("r_ssao", "0", CVAR_LATCH | CVAR_ARCHIVE, ""); - r_normalMapping = ri.Cvar_Get( "r_normalMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable normal mapping" ); - r_specularMapping = ri.Cvar_Get( "r_specularMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable specular mapping" ); - r_deluxeMapping = ri.Cvar_Get( "r_deluxeMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable reading deluxemaps when compiled with q3map2" ); + r_normalMapping = ri.Cvar_Get("r_normalMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable normal mapping"); + r_specularMapping = ri.Cvar_Get("r_specularMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable specular mapping"); + r_deluxeMapping = ri.Cvar_Get("r_deluxeMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable reading deluxemaps when compiled with q3map2"); r_deluxeSpecular = ri.Cvar_Get("r_deluxeSpecular", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable/scale the specular response from deluxemaps"); - r_parallaxMapping = ri.Cvar_Get( "r_parallaxMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable parallax mapping" ); - r_cubeMapping = ri.Cvar_Get( "r_cubeMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable cubemapping" ); - r_cubeMappingBounces = ri.Cvar_Get("r_cubeMappingBounces", "0", CVAR_ARCHIVE | CVAR_LATCH, "Renders cubemaps multiple times to get reflections in reflections"); + r_parallaxMapping = ri.Cvar_Get("r_parallaxMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable parallax mapping"); + r_cubeMapping = ri.Cvar_Get("r_cubeMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable cubemapping"); + r_cubeMappingBounces = + ri.Cvar_Get("r_cubeMappingBounces", "0", CVAR_ARCHIVE | CVAR_LATCH, "Renders cubemaps multiple times to get reflections in reflections"); ri.Cvar_CheckRange(r_cubeMappingBounces, 0, 2, qfalse); - r_baseNormalX = ri.Cvar_Get( "r_baseNormalX", "1.0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_baseNormalY = ri.Cvar_Get( "r_baseNormalY", "1.0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_baseParallax = ri.Cvar_Get( "r_baseParallax", "0.05", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_baseSpecular = ri.Cvar_Get( "r_baseSpecular", "0.04", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_dlightMode = ri.Cvar_Get( "r_dlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_pshadowDist = ri.Cvar_Get( "r_pshadowDist", "128", CVAR_ARCHIVE, "" ); - r_imageUpsample = ri.Cvar_Get( "r_imageUpsample", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_imageUpsampleMaxSize = ri.Cvar_Get( "r_imageUpsampleMaxSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_imageUpsampleType = ri.Cvar_Get( "r_imageUpsampleType", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_genNormalMaps = ri.Cvar_Get( "r_genNormalMaps", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable generating normal maps from diffuse maps" ); - - r_forceSun = ri.Cvar_Get( "r_forceSun", "0", CVAR_CHEAT, "" ); - r_forceSunMapLightScale = ri.Cvar_Get( "r_forceSunMapLightScale", "1.0", CVAR_CHEAT, "" ); - r_forceSunLightScale = ri.Cvar_Get( "r_forceSunLightScale", "1.0", CVAR_CHEAT, "" ); - r_forceSunAmbientScale = ri.Cvar_Get( "r_forceSunAmbientScale", "0.5", CVAR_CHEAT, "" ); - r_drawSunRays = ri.Cvar_Get( "r_drawSunRays", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_sunlightMode = ri.Cvar_Get( "r_sunlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - - r_sunShadows = ri.Cvar_Get( "r_sunShadows", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_shadowFilter = ri.Cvar_Get( "r_shadowFilter", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_shadowMapSize = ri.Cvar_Get( "r_shadowMapSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_shadowCascadeZNear = ri.Cvar_Get( "r_shadowCascadeZNear", "4", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_shadowCascadeZFar = ri.Cvar_Get( "r_shadowCascadeZFar", "3072", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_shadowCascadeZBias = ri.Cvar_Get( "r_shadowCascadeZBias", "-320", CVAR_ARCHIVE | CVAR_LATCH, "" ); - r_ignoreDstAlpha = ri.Cvar_Get( "r_ignoreDstAlpha", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_baseNormalX = ri.Cvar_Get("r_baseNormalX", "1.0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_baseNormalY = ri.Cvar_Get("r_baseNormalY", "1.0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_baseParallax = ri.Cvar_Get("r_baseParallax", "0.05", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_baseSpecular = ri.Cvar_Get("r_baseSpecular", "0.04", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_dlightMode = ri.Cvar_Get("r_dlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_pshadowDist = ri.Cvar_Get("r_pshadowDist", "128", CVAR_ARCHIVE, ""); + r_imageUpsample = ri.Cvar_Get("r_imageUpsample", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_imageUpsampleMaxSize = ri.Cvar_Get("r_imageUpsampleMaxSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_imageUpsampleType = ri.Cvar_Get("r_imageUpsampleType", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_genNormalMaps = ri.Cvar_Get("r_genNormalMaps", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable generating normal maps from diffuse maps"); + + r_forceSun = ri.Cvar_Get("r_forceSun", "0", CVAR_CHEAT, ""); + r_forceSunMapLightScale = ri.Cvar_Get("r_forceSunMapLightScale", "1.0", CVAR_CHEAT, ""); + r_forceSunLightScale = ri.Cvar_Get("r_forceSunLightScale", "1.0", CVAR_CHEAT, ""); + r_forceSunAmbientScale = ri.Cvar_Get("r_forceSunAmbientScale", "0.5", CVAR_CHEAT, ""); + r_drawSunRays = ri.Cvar_Get("r_drawSunRays", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_sunlightMode = ri.Cvar_Get("r_sunlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + + r_sunShadows = ri.Cvar_Get("r_sunShadows", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_shadowFilter = ri.Cvar_Get("r_shadowFilter", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_shadowMapSize = ri.Cvar_Get("r_shadowMapSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_shadowCascadeZNear = ri.Cvar_Get("r_shadowCascadeZNear", "4", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_shadowCascadeZFar = ri.Cvar_Get("r_shadowCascadeZFar", "3072", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_shadowCascadeZBias = ri.Cvar_Get("r_shadowCascadeZBias", "-320", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_ignoreDstAlpha = ri.Cvar_Get("r_ignoreDstAlpha", "1", CVAR_ARCHIVE | CVAR_LATCH, ""); // // temporary latched variables that can only change over a restart // - r_fullbright = ri.Cvar_Get ("r_fullbright", "0", CVAR_LATCH|CVAR_CHEAT, "" ); - r_mapOverBrightBits = ri.Cvar_Get ("r_mapOverBrightBits", "0", CVAR_LATCH, "" ); - r_intensity = ri.Cvar_Get ("r_intensity", "1", CVAR_LATCH, "" ); - r_singleShader = ri.Cvar_Get ("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH, "" ); + r_fullbright = ri.Cvar_Get("r_fullbright", "0", CVAR_LATCH | CVAR_CHEAT, ""); + r_mapOverBrightBits = ri.Cvar_Get("r_mapOverBrightBits", "0", CVAR_LATCH, ""); + r_intensity = ri.Cvar_Get("r_intensity", "1", CVAR_LATCH, ""); + r_singleShader = ri.Cvar_Get("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH, ""); // // archived variables that can change at any time // - r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE|CVAR_CHEAT, "" ); - r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE, "" ); - r_flares = ri.Cvar_Get ("r_flares", "0", CVAR_ARCHIVE, "" ); - r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_CHEAT, "" ); - ri.Cvar_CheckRange( r_znear, 0.001f, 200, qfalse ); - r_autolodscalevalue = ri.Cvar_Get( "r_autolodscalevalue", "0", CVAR_ROM, "" ); - r_zproj = ri.Cvar_Get( "r_zproj", "64", CVAR_ARCHIVE, "" ); - r_stereoSeparation = ri.Cvar_Get( "r_stereoSeparation", "64", CVAR_ARCHIVE, "" ); - r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE, "" ); - r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE, "" ); - r_inGameVideo = ri.Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE, "" ); - r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE, "" ); - r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE, "" ); - r_finish = ri.Cvar_Get ("r_finish", "0", CVAR_ARCHIVE, ""); - r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, "" ); - r_markcount = ri.Cvar_Get( "r_markcount", "100", CVAR_ARCHIVE, "" ); - r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE, "" ); - r_facePlaneCull = ri.Cvar_Get ("r_facePlaneCull", "1", CVAR_ARCHIVE, "" ); - - r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.6", CVAR_CHEAT, "" ); - r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT, "" ); + r_lodCurveError = ri.Cvar_Get("r_lodCurveError", "250", CVAR_ARCHIVE | CVAR_CHEAT, ""); + r_lodbias = ri.Cvar_Get("r_lodbias", "0", CVAR_ARCHIVE, ""); + r_flares = ri.Cvar_Get("r_flares", "0", CVAR_ARCHIVE, ""); + r_znear = ri.Cvar_Get("r_znear", "4", CVAR_CHEAT, ""); + ri.Cvar_CheckRange(r_znear, 0.001f, 200, qfalse); + r_autolodscalevalue = ri.Cvar_Get("r_autolodscalevalue", "0", CVAR_ROM, ""); + r_zproj = ri.Cvar_Get("r_zproj", "64", CVAR_ARCHIVE, ""); + r_stereoSeparation = ri.Cvar_Get("r_stereoSeparation", "64", CVAR_ARCHIVE, ""); + r_ignoreGLErrors = ri.Cvar_Get("r_ignoreGLErrors", "1", CVAR_ARCHIVE, ""); + r_fastsky = ri.Cvar_Get("r_fastsky", "0", CVAR_ARCHIVE, ""); + r_inGameVideo = ri.Cvar_Get("r_inGameVideo", "1", CVAR_ARCHIVE, ""); + r_drawSun = ri.Cvar_Get("r_drawSun", "0", CVAR_ARCHIVE, ""); + r_dynamiclight = ri.Cvar_Get("r_dynamiclight", "1", CVAR_ARCHIVE, ""); + r_finish = ri.Cvar_Get("r_finish", "0", CVAR_ARCHIVE, ""); + r_textureMode = ri.Cvar_Get("r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, ""); + r_markcount = ri.Cvar_Get("r_markcount", "100", CVAR_ARCHIVE, ""); + r_gamma = ri.Cvar_Get("r_gamma", "1", CVAR_ARCHIVE, ""); + r_facePlaneCull = ri.Cvar_Get("r_facePlaneCull", "1", CVAR_ARCHIVE, ""); + + r_ambientScale = ri.Cvar_Get("r_ambientScale", "0.6", CVAR_CHEAT, ""); + r_directedScale = ri.Cvar_Get("r_directedScale", "1", CVAR_CHEAT, ""); r_anaglyphMode = ri.Cvar_Get("r_anaglyphMode", "0", CVAR_ARCHIVE, ""); r_mergeMultidraws = ri.Cvar_Get("r_mergeMultidraws", "1", CVAR_ARCHIVE, ""); @@ -1564,51 +1416,51 @@ void R_Register( void ) // // temporary variables that can change at any time // - r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_TEMP, "" ); + r_showImages = ri.Cvar_Get("r_showImages", "0", CVAR_TEMP, ""); - r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP, "" ); - r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT, "" ); - r_printShaders = ri.Cvar_Get( "r_printShaders", "0", 0, "" ); - r_saveFontData = ri.Cvar_Get( "r_saveFontData", "0", 0, "" ); + r_debugLight = ri.Cvar_Get("r_debuglight", "0", CVAR_TEMP, ""); + r_debugSort = ri.Cvar_Get("r_debugSort", "0", CVAR_CHEAT, ""); + r_printShaders = ri.Cvar_Get("r_printShaders", "0", 0, ""); + r_saveFontData = ri.Cvar_Get("r_saveFontData", "0", 0, ""); r_forceParallaxBias = ri.Cvar_Get("r_forceParallaxBias", "0", CVAR_TEMP, ""); ri.Cvar_CheckRange(r_forceParallaxBias, 0.0f, 1.0f, qfalse); - r_nocurves = ri.Cvar_Get ("r_nocurves", "0", CVAR_CHEAT, "" ); - r_drawworld = ri.Cvar_Get ("r_drawworld", "1", CVAR_CHEAT, "" ); + r_nocurves = ri.Cvar_Get("r_nocurves", "0", CVAR_CHEAT, ""); + r_drawworld = ri.Cvar_Get("r_drawworld", "1", CVAR_CHEAT, ""); r_drawfog = ri.Cvar_Get("r_drawfog", "2", CVAR_CHEAT, ""); - r_lightmap = ri.Cvar_Get ("r_lightmap", "0", 0, "" ); - r_portalOnly = ri.Cvar_Get ("r_portalOnly", "0", CVAR_CHEAT, "" ); - - r_skipBackEnd = ri.Cvar_Get ("r_skipBackEnd", "0", CVAR_CHEAT, ""); - - r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT, "" ); - r_lodscale = ri.Cvar_Get( "r_lodscale", "5", CVAR_CHEAT, "" ); - r_norefresh = ri.Cvar_Get ("r_norefresh", "0", CVAR_CHEAT, ""); - r_drawentities = ri.Cvar_Get ("r_drawentities", "1", CVAR_CHEAT, "" ); - r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_CHEAT, "" ); - r_nocull = ri.Cvar_Get ("r_nocull", "0", CVAR_CHEAT, ""); - r_novis = ri.Cvar_Get ("r_novis", "0", CVAR_CHEAT, ""); - r_showcluster = ri.Cvar_Get ("r_showcluster", "0", CVAR_CHEAT, ""); - r_speeds = ri.Cvar_Get ("r_speeds", "0", CVAR_CHEAT, ""); - r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT, "" ); - r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT, "" ); - r_debugSurface = ri.Cvar_Get ("r_debugSurface", "0", CVAR_CHEAT, ""); - r_nobind = ri.Cvar_Get ("r_nobind", "0", CVAR_CHEAT, ""); - r_showtris = ri.Cvar_Get ("r_showtris", "0", CVAR_CHEAT, ""); - r_showsky = ri.Cvar_Get ("r_showsky", "0", CVAR_CHEAT, ""); - r_shownormals = ri.Cvar_Get ("r_shownormals", "0", CVAR_CHEAT, ""); - r_clear = ri.Cvar_Get ("r_clear", "0", CVAR_CHEAT, ""); - r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT, "" ); - r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT, "" ); + r_lightmap = ri.Cvar_Get("r_lightmap", "0", 0, ""); + r_portalOnly = ri.Cvar_Get("r_portalOnly", "0", CVAR_CHEAT, ""); + + r_skipBackEnd = ri.Cvar_Get("r_skipBackEnd", "0", CVAR_CHEAT, ""); + + r_measureOverdraw = ri.Cvar_Get("r_measureOverdraw", "0", CVAR_CHEAT, ""); + r_lodscale = ri.Cvar_Get("r_lodscale", "5", CVAR_CHEAT, ""); + r_norefresh = ri.Cvar_Get("r_norefresh", "0", CVAR_CHEAT, ""); + r_drawentities = ri.Cvar_Get("r_drawentities", "1", CVAR_CHEAT, ""); + r_ignore = ri.Cvar_Get("r_ignore", "1", CVAR_CHEAT, ""); + r_nocull = ri.Cvar_Get("r_nocull", "0", CVAR_CHEAT, ""); + r_novis = ri.Cvar_Get("r_novis", "0", CVAR_CHEAT, ""); + r_showcluster = ri.Cvar_Get("r_showcluster", "0", CVAR_CHEAT, ""); + r_speeds = ri.Cvar_Get("r_speeds", "0", CVAR_CHEAT, ""); + r_verbose = ri.Cvar_Get("r_verbose", "0", CVAR_CHEAT, ""); + r_logFile = ri.Cvar_Get("r_logFile", "0", CVAR_CHEAT, ""); + r_debugSurface = ri.Cvar_Get("r_debugSurface", "0", CVAR_CHEAT, ""); + r_nobind = ri.Cvar_Get("r_nobind", "0", CVAR_CHEAT, ""); + r_showtris = ri.Cvar_Get("r_showtris", "0", CVAR_CHEAT, ""); + r_showsky = ri.Cvar_Get("r_showsky", "0", CVAR_CHEAT, ""); + r_shownormals = ri.Cvar_Get("r_shownormals", "0", CVAR_CHEAT, ""); + r_clear = ri.Cvar_Get("r_clear", "0", CVAR_CHEAT, ""); + r_offsetFactor = ri.Cvar_Get("r_offsetfactor", "-1", CVAR_CHEAT, ""); + r_offsetUnits = ri.Cvar_Get("r_offsetunits", "-2", CVAR_CHEAT, ""); r_shadowOffsetFactor = ri.Cvar_Get("r_shadowOffsetFactor", "1.0", CVAR_CHEAT, ""); r_shadowOffsetUnits = ri.Cvar_Get("r_shadowOffsetUnits", "1.0", CVAR_CHEAT, ""); - r_drawBuffer = ri.Cvar_Get( "r_drawBuffer", "GL_BACK", CVAR_CHEAT, "" ); - r_lockpvs = ri.Cvar_Get ("r_lockpvs", "0", CVAR_CHEAT, ""); - r_noportals = ri.Cvar_Get ("r_noportals", "0", CVAR_CHEAT, ""); - r_shadows = ri.Cvar_Get( "cg_shadows", "1", 0, "" ); + r_drawBuffer = ri.Cvar_Get("r_drawBuffer", "GL_BACK", CVAR_CHEAT, ""); + r_lockpvs = ri.Cvar_Get("r_lockpvs", "0", CVAR_CHEAT, ""); + r_noportals = ri.Cvar_Get("r_noportals", "0", CVAR_CHEAT, ""); + r_shadows = ri.Cvar_Get("cg_shadows", "1", 0, ""); r_marksOnTriangleMeshes = ri.Cvar_Get("r_marksOnTriangleMeshes", "0", CVAR_ARCHIVE, ""); @@ -1616,67 +1468,63 @@ void R_Register( void ) r_screenshotJpegQuality = ri.Cvar_Get("r_screenshotJpegQuality", "90", CVAR_ARCHIVE, ""); r_surfaceSprites = ri.Cvar_Get("r_surfaceSprites", "1", CVAR_ARCHIVE, ""); - r_aspectCorrectFonts = ri.Cvar_Get( "r_aspectCorrectFonts", "0", CVAR_ARCHIVE, "" ); - r_maxpolys = ri.Cvar_Get( "r_maxpolys", XSTRING( DEFAULT_MAX_POLYS ), 0, ""); - r_maxpolyverts = ri.Cvar_Get( "r_maxpolyverts", XSTRING( DEFAULT_MAX_POLYVERTS ), 0, "" ); + r_aspectCorrectFonts = ri.Cvar_Get("r_aspectCorrectFonts", "0", CVAR_ARCHIVE, ""); + r_maxpolys = ri.Cvar_Get("r_maxpolys", XSTRING(DEFAULT_MAX_POLYS), 0, ""); + r_maxpolyverts = ri.Cvar_Get("r_maxpolyverts", XSTRING(DEFAULT_MAX_POLYVERTS), 0, ""); /* Ghoul2 Insert Start */ #ifdef _DEBUG - r_noPrecacheGLA = ri.Cvar_Get( "r_noPrecacheGLA", "0", CVAR_CHEAT, "" ); + r_noPrecacheGLA = ri.Cvar_Get("r_noPrecacheGLA", "0", CVAR_CHEAT, ""); #endif - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", CVAR_CHEAT, "" ); - r_Ghoul2AnimSmooth = ri.Cvar_Get( "r_ghoul2animsmooth", "0.3", CVAR_NONE, "" ); - r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get( "r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, "" ); - broadsword = ri.Cvar_Get( "broadsword", "0", CVAR_ARCHIVE, "" ); - broadsword_kickbones = ri.Cvar_Get( "broadsword_kickbones", "1", CVAR_NONE, "" ); - broadsword_kickorigin = ri.Cvar_Get( "broadsword_kickorigin", "1", CVAR_NONE, "" ); - broadsword_dontstopanim = ri.Cvar_Get( "broadsword_dontstopanim", "0", CVAR_NONE, "" ); - broadsword_waitforshot = ri.Cvar_Get( "broadsword_waitforshot", "0", CVAR_NONE, "" ); - broadsword_playflop = ri.Cvar_Get( "broadsword_playflop", "1", CVAR_NONE, "" ); - broadsword_smallbbox = ri.Cvar_Get( "broadsword_smallbbox", "0", CVAR_NONE, "" ); - broadsword_extra1 = ri.Cvar_Get( "broadsword_extra1", "0", CVAR_NONE, "" ); - broadsword_extra2 = ri.Cvar_Get( "broadsword_extra2", "0", CVAR_NONE, "" ); - broadsword_effcorr = ri.Cvar_Get( "broadsword_effcorr", "1", CVAR_NONE, "" ); - broadsword_ragtobase = ri.Cvar_Get( "broadsword_ragtobase", "2", CVAR_NONE, "" ); - broadsword_dircap = ri.Cvar_Get( "broadsword_dircap", "64", CVAR_NONE, "" ); -/* -Ghoul2 Insert End -*/ + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", CVAR_CHEAT, ""); + r_Ghoul2AnimSmooth = ri.Cvar_Get("r_ghoul2animsmooth", "0.3", CVAR_NONE, ""); + r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get("r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, ""); + broadsword = ri.Cvar_Get("broadsword", "0", CVAR_ARCHIVE, ""); + broadsword_kickbones = ri.Cvar_Get("broadsword_kickbones", "1", CVAR_NONE, ""); + broadsword_kickorigin = ri.Cvar_Get("broadsword_kickorigin", "1", CVAR_NONE, ""); + broadsword_dontstopanim = ri.Cvar_Get("broadsword_dontstopanim", "0", CVAR_NONE, ""); + broadsword_waitforshot = ri.Cvar_Get("broadsword_waitforshot", "0", CVAR_NONE, ""); + broadsword_playflop = ri.Cvar_Get("broadsword_playflop", "1", CVAR_NONE, ""); + broadsword_smallbbox = ri.Cvar_Get("broadsword_smallbbox", "0", CVAR_NONE, ""); + broadsword_extra1 = ri.Cvar_Get("broadsword_extra1", "0", CVAR_NONE, ""); + broadsword_extra2 = ri.Cvar_Get("broadsword_extra2", "0", CVAR_NONE, ""); + broadsword_effcorr = ri.Cvar_Get("broadsword_effcorr", "1", CVAR_NONE, ""); + broadsword_ragtobase = ri.Cvar_Get("broadsword_ragtobase", "2", CVAR_NONE, ""); + broadsword_dircap = ri.Cvar_Get("broadsword_dircap", "64", CVAR_NONE, ""); + /* + Ghoul2 Insert End + */ - r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces" ); + r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces"); - se_language = ri.Cvar_Get ( "se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, "" ); + se_language = ri.Cvar_Get("se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, ""); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_AddCommand( commands[i].cmd, commands[i].func, "" ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_AddCommand(commands[i].cmd, commands[i].func, ""); } -void R_InitQueries(void) -{ +void R_InitQueries(void) { if (r_drawSunRays->integer) qglGenQueries(ARRAY_LEN(tr.sunFlareQuery), tr.sunFlareQuery); } -void R_ShutDownQueries(void) -{ +void R_ShutDownQueries(void) { if (r_drawSunRays->integer) qglDeleteQueries(ARRAY_LEN(tr.sunFlareQuery), tr.sunFlareQuery); } -void RE_SetLightStyle (int style, int color); +void RE_SetLightStyle(int style, int color); -static void R_InitBackEndFrameData() -{ - GLuint timerQueries[MAX_GPU_TIMERS*MAX_FRAMES]; - qglGenQueries(MAX_GPU_TIMERS*MAX_FRAMES, timerQueries); +static void R_InitBackEndFrameData() { + GLuint timerQueries[MAX_GPU_TIMERS * MAX_FRAMES]; + qglGenQueries(MAX_GPU_TIMERS * MAX_FRAMES, timerQueries); GLuint ubos[MAX_FRAMES]; qglGenBuffers(MAX_FRAMES, ubos); - for ( int i = 0; i < MAX_FRAMES; i++ ) - { + for (int i = 0; i < MAX_FRAMES; i++) { gpuFrame_t *frame = backEndData->frames + i; const GLbitfield mapBits = GL_MAP_WRITE_BIT | GL_MAP_COHERENT_BIT | GL_MAP_PERSISTENT_BIT; @@ -1687,39 +1535,30 @@ static void R_InitBackEndFrameData() glState.currentGlobalUBO = frame->ubo; // TODO: persistently mapped UBOs - qglBufferData(GL_UNIFORM_BUFFER, FRAME_UNIFORM_BUFFER_SIZE, - nullptr, GL_DYNAMIC_DRAW); + qglBufferData(GL_UNIFORM_BUFFER, FRAME_UNIFORM_BUFFER_SIZE, nullptr, GL_DYNAMIC_DRAW); - frame->dynamicVbo = R_CreateVBO(nullptr, FRAME_VERTEX_BUFFER_SIZE, - VBO_USAGE_DYNAMIC); + frame->dynamicVbo = R_CreateVBO(nullptr, FRAME_VERTEX_BUFFER_SIZE, VBO_USAGE_DYNAMIC); frame->dynamicVboCommitOffset = 0; frame->dynamicVboWriteOffset = 0; - frame->dynamicIbo = R_CreateIBO(nullptr, FRAME_INDEX_BUFFER_SIZE, - VBO_USAGE_DYNAMIC); + frame->dynamicIbo = R_CreateIBO(nullptr, FRAME_INDEX_BUFFER_SIZE, VBO_USAGE_DYNAMIC); frame->dynamicIboCommitOffset = 0; frame->dynamicIboWriteOffset = 0; - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { R_BindVBO(frame->dynamicVbo); - frame->dynamicVboMemory = qglMapBufferRange(GL_ARRAY_BUFFER, 0, - frame->dynamicVbo->vertexesSize, mapBits); + frame->dynamicVboMemory = qglMapBufferRange(GL_ARRAY_BUFFER, 0, frame->dynamicVbo->vertexesSize, mapBits); R_BindIBO(frame->dynamicIbo); - frame->dynamicIboMemory = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, - frame->dynamicIbo->indexesSize, mapBits); - } - else - { + frame->dynamicIboMemory = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, frame->dynamicIbo->indexesSize, mapBits); + } else { frame->dynamicVboMemory = nullptr; frame->dynamicIboMemory = nullptr; } - for ( int j = 0; j < MAX_GPU_TIMERS; j++ ) - { + for (int j = 0; j < MAX_GPU_TIMERS; j++) { gpuTimer_t *timer = frame->timers + j; - timer->queryName = timerQueries[i*MAX_GPU_TIMERS + j]; + timer->queryName = timerQueries[i * MAX_GPU_TIMERS + j]; } } @@ -1727,12 +1566,8 @@ static void R_InitBackEndFrameData() } #ifdef _G2_GORE -static void R_InitGoreVao() -{ - tr.goreVBO = R_CreateVBO( - nullptr, - sizeof(g2GoreVert_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_VERTS * MAX_FRAMES, - VBO_USAGE_DYNAMIC); +static void R_InitGoreVao() { + tr.goreVBO = R_CreateVBO(nullptr, sizeof(g2GoreVert_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_VERTS * MAX_FRAMES, VBO_USAGE_DYNAMIC); tr.goreVBO->offsets[ATTR_INDEX_POSITION] = offsetof(g2GoreVert_t, position); tr.goreVBO->offsets[ATTR_INDEX_NORMAL] = offsetof(g2GoreVert_t, normal); tr.goreVBO->offsets[ATTR_INDEX_TEXCOORD0] = offsetof(g2GoreVert_t, texCoords); @@ -1754,51 +1589,34 @@ static void R_InitGoreVao() tr.goreVBO->sizes[ATTR_INDEX_BONE_INDEXES] = sizeof(byte); tr.goreVBO->sizes[ATTR_INDEX_TANGENT] = sizeof(uint32_t); - tr.goreIBO = R_CreateIBO( - nullptr, - sizeof(glIndex_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_INDECIES * MAX_FRAMES, - VBO_USAGE_DYNAMIC); + tr.goreIBO = R_CreateIBO(nullptr, sizeof(glIndex_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_INDECIES * MAX_FRAMES, VBO_USAGE_DYNAMIC); tr.goreIBOCurrentIndex = 0; tr.goreVBOCurrentIndex = 0; } #endif -static void R_InitStaticConstants() -{ +static void R_InitStaticConstants() { const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; size_t alignedBlockSize = 0; qglBindBuffer(GL_UNIFORM_BUFFER, tr.staticUbo); - qglBufferData( - GL_UNIFORM_BUFFER, - STATIC_UNIFORM_BUFFER_SIZE, - nullptr, - GL_STATIC_DRAW); + qglBufferData(GL_UNIFORM_BUFFER, STATIC_UNIFORM_BUFFER_SIZE, nullptr, GL_STATIC_DRAW); // Setup static 2d camera data EntityBlock entity2DBlock = {}; entity2DBlock.fxVolumetricBase = -1.0f; Matrix16Identity(entity2DBlock.modelMatrix); tr.entity2DUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, 0, sizeof(entity2DBlock), &entity2DBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(entity2DBlock), &entity2DBlock); alignedBlockSize += (sizeof(EntityBlock) + alignment) & ~alignment; // Setup static 2d camera data CameraBlock a2DCameraBlock = {}; - Matrix16Ortho( - 0.0f, - 640.0f, - 480.0f, - 0.0f, - 0.0f, - 1.0f, - a2DCameraBlock.viewProjectionMatrix); + Matrix16Ortho(0.0f, 640.0f, 480.0f, 0.0f, 0.0f, 1.0f, a2DCameraBlock.viewProjectionMatrix); tr.camera2DUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.camera2DUboOffset, sizeof(a2DCameraBlock), &a2DCameraBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.camera2DUboOffset, sizeof(a2DCameraBlock), &a2DCameraBlock); alignedBlockSize += (sizeof(CameraBlock) + alignment) & ~alignment; // Setup static flare entity data @@ -1807,24 +1625,15 @@ static void R_InitStaticConstants() Matrix16Identity(entityFlareBlock.modelMatrix); tr.entityFlareUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.entityFlareUboOffset, sizeof(entityFlareBlock), &entityFlareBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.entityFlareUboOffset, sizeof(entityFlareBlock), &entityFlareBlock); alignedBlockSize += (sizeof(EntityBlock) + alignment) & ~alignment; // Setup static flare camera data CameraBlock flareCameraBlock = {}; - Matrix16Ortho( - 0.0f, - glConfig.vidWidth, - glConfig.vidHeight, - 0.0f, - -99999.0f, - 99999.0f, - flareCameraBlock.viewProjectionMatrix); + Matrix16Ortho(0.0f, glConfig.vidWidth, glConfig.vidHeight, 0.0f, -99999.0f, 99999.0f, flareCameraBlock.viewProjectionMatrix); tr.cameraFlareUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.cameraFlareUboOffset, sizeof(flareCameraBlock), &flareCameraBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.cameraFlareUboOffset, sizeof(flareCameraBlock), &flareCameraBlock); alignedBlockSize += (sizeof(CameraBlock) + alignment) & ~alignment; // Setup default light block @@ -1832,8 +1641,7 @@ static void R_InitStaticConstants() lightsBlock.numLights = 0; tr.defaultLightsUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.defaultLightsUboOffset, sizeof(lightsBlock), &lightsBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.defaultLightsUboOffset, sizeof(lightsBlock), &lightsBlock); alignedBlockSize += (sizeof(LightsBlock) + alignment) & ~alignment; // Setup default scene block @@ -1843,23 +1651,20 @@ static void R_InitStaticConstants() sceneBlock.frameTime = 0.1f; tr.defaultSceneUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.defaultSceneUboOffset, sizeof(sceneBlock), &sceneBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.defaultSceneUboOffset, sizeof(sceneBlock), &sceneBlock); alignedBlockSize += (sizeof(SceneBlock) + alignment) & ~alignment; // Setup default fogs block FogsBlock fogsBlock = {}; fogsBlock.numFogs = 0; tr.defaultFogsUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.defaultFogsUboOffset, sizeof(fogsBlock), &fogsBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.defaultFogsUboOffset, sizeof(fogsBlock), &fogsBlock); alignedBlockSize += (sizeof(FogsBlock) + alignment) & ~alignment; // Setup default shader instance block ShaderInstanceBlock shaderInstanceBlock = {}; tr.defaultShaderInstanceUboOffset = alignedBlockSize; - qglBufferSubData( - GL_UNIFORM_BUFFER, tr.defaultShaderInstanceUboOffset, sizeof(shaderInstanceBlock), &shaderInstanceBlock); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.defaultShaderInstanceUboOffset, sizeof(shaderInstanceBlock), &shaderInstanceBlock); alignedBlockSize += (sizeof(ShaderInstanceBlock) + alignment) & ~alignment; qglBindBuffer(GL_UNIFORM_BUFFER, NULL); @@ -1868,33 +1673,28 @@ static void R_InitStaticConstants() GL_CheckErrors(); } -static void R_ShutdownBackEndFrameData() -{ - if ( !backEndData ) +static void R_ShutdownBackEndFrameData() { + if (!backEndData) return; - for ( int i = 0; i < MAX_FRAMES; i++ ) - { + for (int i = 0; i < MAX_FRAMES; i++) { gpuFrame_t *frame = backEndData->frames + i; - if (frame->sync) - { + if (frame->sync) { qglDeleteSync(frame->sync); frame->sync = NULL; } qglDeleteBuffers(1, &frame->ubo); - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { R_BindVBO(frame->dynamicVbo); R_BindIBO(frame->dynamicIbo); qglUnmapBuffer(GL_ARRAY_BUFFER); qglUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); } - for ( int j = 0; j < MAX_GPU_TIMERS; j++ ) - { + for (int j = 0; j < MAX_GPU_TIMERS; j++) { gpuTimer_t *timer = frame->timers + j; qglDeleteQueries(1, &timer->queryName); } @@ -1906,42 +1706,34 @@ static void R_ShutdownBackEndFrameData() R_Init =============== */ -void R_Init( void ) { +void R_Init(void) { byte *ptr; int i; - ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); + ri.Printf(PRINT_ALL, "----- R_Init -----\n"); // clear all our internal state - Com_Memset( &tr, 0, sizeof( tr ) ); - Com_Memset( &backEnd, 0, sizeof( backEnd ) ); - Com_Memset( &tess, 0, sizeof( tess ) ); - + Com_Memset(&tr, 0, sizeof(tr)); + Com_Memset(&backEnd, 0, sizeof(backEnd)); + Com_Memset(&tess, 0, sizeof(tess)); // // init function tables // - for ( i = 0; i < FUNCTABLE_SIZE; i++ ) - { - tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) ); - tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f; + for (i = 0; i < FUNCTABLE_SIZE; i++) { + tr.sinTable[i] = sin(DEG2RAD(i * 360.0f / ((float)(FUNCTABLE_SIZE - 1)))); + tr.squareTable[i] = (i < FUNCTABLE_SIZE / 2) ? 1.0f : -1.0f; tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE; tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i]; - if ( i < FUNCTABLE_SIZE / 2 ) - { - if ( i < FUNCTABLE_SIZE / 4 ) - { - tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 ); - } - else - { - tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4]; + if (i < FUNCTABLE_SIZE / 2) { + if (i < FUNCTABLE_SIZE / 4) { + tr.triangleTable[i] = (float)i / (FUNCTABLE_SIZE / 4); + } else { + tr.triangleTable[i] = 1.0f - tr.triangleTable[i - FUNCTABLE_SIZE / 4]; } - } - else - { - tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2]; + } else { + tr.triangleTable[i] = -tr.triangleTable[i - FUNCTABLE_SIZE / 2]; } } @@ -1951,16 +1743,11 @@ void R_Init( void ) { R_NoiseInit(); R_Register(); - max_polys = Q_min( r_maxpolys->integer, DEFAULT_MAX_POLYS ); - max_polyverts = Q_min( r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS ); + max_polys = Q_min(r_maxpolys->integer, DEFAULT_MAX_POLYS); + max_polyverts = Q_min(r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS); - ptr = (byte*)ri.Hunk_Alloc( - sizeof( *backEndData ) + - sizeof(srfPoly_t) * max_polys + - sizeof(polyVert_t) * max_polyverts + - sizeof(Allocator) + - PER_FRAME_MEMORY_BYTES, - h_low); + ptr = (byte *)ri.Hunk_Alloc( + sizeof(*backEndData) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts + sizeof(Allocator) + PER_FRAME_MEMORY_BYTES, h_low); backEndData = (backEndData_t *)ptr; ptr = (byte *)(backEndData + 1); @@ -1971,13 +1758,12 @@ void R_Init( void ) { backEndData->polyVerts = (polyVert_t *)ptr; ptr += sizeof(*backEndData->polyVerts) * max_polyverts; - backEndData->perFrameMemory = new(ptr) Allocator(ptr + sizeof(*backEndData->perFrameMemory), PER_FRAME_MEMORY_BYTES); + backEndData->perFrameMemory = new (ptr) Allocator(ptr + sizeof(*backEndData->perFrameMemory), PER_FRAME_MEMORY_BYTES); R_InitNextFrame(); - for ( int i = 0; i < MAX_LIGHT_STYLES; i++ ) - { - RE_SetLightStyle (i, -1); + for (int i = 0; i < MAX_LIGHT_STYLES; i++) { + RE_SetLightStyle(i, -1); } R_InitImagesPool(); @@ -1998,7 +1784,7 @@ void R_Init( void ) { GLSL_LoadGPUShaders(); - R_InitShaders (qfalse); + R_InitShaders(qfalse); R_InitSkins(); @@ -2014,15 +1800,15 @@ void R_Init( void ) { #if defined(_DEBUG) GLenum err = qglGetError(); - if ( err != GL_NO_ERROR ) - ri.Printf( PRINT_ALL, "glGetError() = 0x%x\n", err ); + if (err != GL_NO_ERROR) + ri.Printf(PRINT_ALL, "glGetError() = 0x%x\n", err); #endif RestoreGhoul2InfoArray(); // print info GfxInfo_f(); - ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); + ri.Printf(PRINT_ALL, "----- finished R_Init -----\n"); } /* @@ -2030,12 +1816,12 @@ void R_Init( void ) { RE_Shutdown =============== */ -void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { +void RE_Shutdown(qboolean destroyWindow, qboolean restarting) { - ri.Printf( PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow ); + ri.Printf(PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_RemoveCommand( commands[i].cmd ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_RemoveCommand(commands[i].cmd); // Flush here to make sure all the fences are processed qglFlush(); @@ -2047,15 +1833,14 @@ void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { R_ShutdownWeatherSystem(); R_ShutdownFonts(); - if ( tr.registered ) { + if (tr.registered) { R_ShutDownQueries(); FBO_Shutdown(); R_DeleteTextures(); R_DestroyGPUBuffers(); GLSL_ShutdownGPUShaders(); - if ( destroyWindow && restarting ) - { + if (destroyWindow && restarting) { ri.Z_Free((void *)glConfig.extensions_string); ri.Z_Free((void *)glConfigExt.originalExtensionString); @@ -2065,7 +1850,7 @@ void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { } // shut down platform specific OpenGL stuff - if ( destroyWindow ) { + if (destroyWindow) { ri.WIN_Shutdown(); } @@ -2080,7 +1865,7 @@ RE_EndRegistration Touch all images to make sure they are resident ============= */ -void RE_EndRegistration( void ) { +void RE_EndRegistration(void) { R_IssuePendingRenderCommands(); if (!ri.Sys_LowPhysicalMemory()) { RB_ShowImages(); @@ -2090,14 +1875,14 @@ void RE_EndRegistration( void ) { // HACK extern qboolean gG2_GBMNoReconstruct; extern qboolean gG2_GBMUseSPMethod; -static void G2API_BoltMatrixReconstruction( qboolean reconstruct ) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } -static void G2API_BoltMatrixSPMethod( qboolean spMethod ) { gG2_GBMUseSPMethod = spMethod; } +static void G2API_BoltMatrixReconstruction(qboolean reconstruct) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } +static void G2API_BoltMatrixSPMethod(qboolean spMethod) { gG2_GBMUseSPMethod = spMethod; } -static float GetDistanceCull( void ) { return tr.distanceCull; } +static float GetDistanceCull(void) { return tr.distanceCull; } -extern void R_SVModelInit( void ); //tr_model.cpp +extern void R_SVModelInit(void); // tr_model.cpp -static void GetRealRes( int *w, int *h ) { +static void GetRealRes(int *w, int *h) { *w = glConfig.vidWidth; *h = glConfig.vidHeight; } @@ -2105,11 +1890,9 @@ static void GetRealRes( int *w, int *h ) { // STUBS, REPLACEME qboolean stub_InitializeWireframeAutomap() { return qtrue; } -void RE_GetLightStyle(int style, color4ub_t color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_GetLightStyle: %d is out of range", style ); +void RE_GetLightStyle(int style, color4ub_t color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_GetLightStyle: %d is out of range", style); return; } @@ -2117,16 +1900,14 @@ void RE_GetLightStyle(int style, color4ub_t color) baDest->i = baSource->i; } -void RE_SetLightStyle(int style, int color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_SetLightStyle: %d is out of range", style ); +void RE_SetLightStyle(int style, int color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_SetLightStyle: %d is out of range", style); return; } byteAlias_t *ba = (byteAlias_t *)&styleColors[style]; - if ( ba->i != color) { + if (ba->i != color) { ba->i = color; } } @@ -2134,38 +1915,32 @@ void RE_SetLightStyle(int style, int color) void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal); void RE_WorldEffectCommand(const char *cmd); -void stub_RE_AddWeatherZone ( vec3_t mins, vec3_t maxs ) {} // Intentionally left blank. Rend2 reads the zones manually on bsp load -static void RE_SetRefractionProperties ( float distortionAlpha, float distortionStretch, qboolean distortionPrePost, qboolean distortionNegate ) { } +void stub_RE_AddWeatherZone(vec3_t mins, vec3_t maxs) {} // Intentionally left blank. Rend2 reads the zones manually on bsp load +static void RE_SetRefractionProperties(float distortionAlpha, float distortionStretch, qboolean distortionPrePost, qboolean distortionNegate) {} -void C_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) -{ - static char sPrevMapName[MAX_QPATH]={0}; +void C_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) { + static char sPrevMapName[MAX_QPATH] = {0}; bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; - if( bDeleteModels ) + if (bDeleteModels) CModelCache->DeleteAll(); - else if( ri.Cvar_VariableIntegerValue( "sv_pure" ) ) + else if (ri.Cvar_VariableIntegerValue("sv_pure")) CModelCache->DumpNonPure(); tr.numBSPModels = 0; /* If we're switching to the same level, don't increment current level */ - if (Q_stricmp( psMapName,sPrevMapName )) - { - Q_strncpyz( sPrevMapName, psMapName, sizeof(sPrevMapName) ); + if (Q_stricmp(psMapName, sPrevMapName)) { + Q_strncpyz(sPrevMapName, psMapName, sizeof(sPrevMapName)); tr.currentLevel++; } } -int C_GetLevel( void ) -{ - return tr.currentLevel; -} +int C_GetLevel(void) { return tr.currentLevel; } -void C_LevelLoadEnd( void ) -{ - CModelCache->LevelLoadEnd( qfalse ); - ri.SND_RegisterAudio_LevelLoadEnd( qfalse ); +void C_LevelLoadEnd(void) { + CModelCache->LevelLoadEnd(qfalse); + ri.SND_RegisterAudio_LevelLoadEnd(qfalse); ri.S_RestartMusic(); } @@ -2176,17 +1951,16 @@ GetRefAPI @@@@@@@@@@@@@@@@@@@@@ */ extern "C" { -Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t *rimp ) { - static refexport_t re; +Q_EXPORT refexport_t *QDECL GetRefAPI(int apiVersion, refimport_t *rimp) { + static refexport_t re; - assert( rimp ); + assert(rimp); ri = *rimp; - Com_Memset( &re, 0, sizeof( re ) ); + Com_Memset(&re, 0, sizeof(re)); - if ( apiVersion != REF_API_VERSION ) { - ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", - REF_API_VERSION, apiVersion ); + if (apiVersion != REF_API_VERSION) { + ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion); return NULL; } @@ -2264,104 +2038,104 @@ Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t *rimp ) { re.TakeVideoFrame = RE_TakeVideoFrame; - re.InitSkins = R_InitSkins; - re.InitShaders = R_InitShaders; - re.SVModelInit = R_SVModelInit; - re.HunkClearCrap = RE_HunkClearCrap; - - re.G2API_AddBolt = G2API_AddBolt; - re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; - re.G2API_AddSurface = G2API_AddSurface; - re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; - re.G2API_AttachEnt = G2API_AttachEnt; - re.G2API_AttachG2Model = G2API_AttachG2Model; - re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; - re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; - re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; - re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; - re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; - re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; - re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; - re.G2API_CollisionDetect = G2API_CollisionDetect; - re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; - re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; - re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; - re.G2API_DetachG2Model = G2API_DetachG2Model; - re.G2API_DoesBoneExist = G2API_DoesBoneExist; - re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; - re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; - re.G2API_GetAnimFileName = G2API_GetAnimFileName; - re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; - re.G2API_GetAnimRange = G2API_GetAnimRange; - re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; - re.G2API_GetBoneAnim = G2API_GetBoneAnim; - re.G2API_GetBoneIndex = G2API_GetBoneIndex; - re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; - re.G2API_GetGLAName = G2API_GetGLAName; - re.G2API_GetModelName = G2API_GetModelName; - re.G2API_GetParentSurface = G2API_GetParentSurface; - re.G2API_GetRagBonePos = G2API_GetRagBonePos; - re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; - re.G2API_GetSurfaceName = G2API_GetSurfaceName; - re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; - re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; - re.G2API_GetTime = G2API_GetTime; - re.G2API_Ghoul2Size = G2API_Ghoul2Size; - re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; - re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; - re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; - re.G2API_IKMove = G2API_IKMove; - re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; - re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; - re.G2API_IsPaused = G2API_IsPaused; - re.G2API_ListBones = G2API_ListBones; - re.G2API_ListSurfaces = G2API_ListSurfaces; - re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; - re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; - re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; - re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; - re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; - re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; - re.G2API_RagEffectorKick = G2API_RagEffectorKick; - re.G2API_RagForceSolve = G2API_RagForceSolve; - re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; - re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; - re.G2API_RemoveBolt = G2API_RemoveBolt; - re.G2API_RemoveBone = G2API_RemoveBone; - re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; - re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; - re.G2API_RemoveSurface = G2API_RemoveSurface; - re.G2API_ResetRagDoll = G2API_ResetRagDoll; - re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; - re.G2API_SetBoltInfo = G2API_SetBoltInfo; - re.G2API_SetBoneAngles = G2API_SetBoneAngles; - re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; - re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; - re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; - re.G2API_SetBoneAnim = G2API_SetBoneAnim; - re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; - re.G2API_SetBoneIKState = G2API_SetBoneIKState; - re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; - re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; - re.G2API_SetLodBias = G2API_SetLodBias; - re.G2API_SetNewOrigin = G2API_SetNewOrigin; - re.G2API_SetRagDoll = G2API_SetRagDoll; - re.G2API_SetRootSurface = G2API_SetRootSurface; - re.G2API_SetShader = G2API_SetShader; - re.G2API_SetSkin = G2API_SetSkin; - re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; - re.G2API_SetTime = G2API_SetTime; - re.G2API_SkinlessModel = G2API_SkinlessModel; - re.G2API_StopBoneAngles = G2API_StopBoneAngles; - re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; - re.G2API_StopBoneAnim = G2API_StopBoneAnim; - re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; - - #ifdef _G2_GORE - re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; - re.G2API_AddSkinGore = G2API_AddSkinGore; - re.G2API_ClearSkinGore = G2API_ClearSkinGore; - #endif // _SOF2 + re.InitSkins = R_InitSkins; + re.InitShaders = R_InitShaders; + re.SVModelInit = R_SVModelInit; + re.HunkClearCrap = RE_HunkClearCrap; + + re.G2API_AddBolt = G2API_AddBolt; + re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; + re.G2API_AddSurface = G2API_AddSurface; + re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; + re.G2API_AttachEnt = G2API_AttachEnt; + re.G2API_AttachG2Model = G2API_AttachG2Model; + re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; + re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; + re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; + re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; + re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; + re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; + re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; + re.G2API_CollisionDetect = G2API_CollisionDetect; + re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; + re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; + re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; + re.G2API_DetachG2Model = G2API_DetachG2Model; + re.G2API_DoesBoneExist = G2API_DoesBoneExist; + re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; + re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; + re.G2API_GetAnimFileName = G2API_GetAnimFileName; + re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; + re.G2API_GetAnimRange = G2API_GetAnimRange; + re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; + re.G2API_GetBoneAnim = G2API_GetBoneAnim; + re.G2API_GetBoneIndex = G2API_GetBoneIndex; + re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; + re.G2API_GetGLAName = G2API_GetGLAName; + re.G2API_GetModelName = G2API_GetModelName; + re.G2API_GetParentSurface = G2API_GetParentSurface; + re.G2API_GetRagBonePos = G2API_GetRagBonePos; + re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; + re.G2API_GetSurfaceName = G2API_GetSurfaceName; + re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; + re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; + re.G2API_GetTime = G2API_GetTime; + re.G2API_Ghoul2Size = G2API_Ghoul2Size; + re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; + re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; + re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; + re.G2API_IKMove = G2API_IKMove; + re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; + re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; + re.G2API_IsPaused = G2API_IsPaused; + re.G2API_ListBones = G2API_ListBones; + re.G2API_ListSurfaces = G2API_ListSurfaces; + re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; + re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; + re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; + re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; + re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; + re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; + re.G2API_RagEffectorKick = G2API_RagEffectorKick; + re.G2API_RagForceSolve = G2API_RagForceSolve; + re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; + re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; + re.G2API_RemoveBolt = G2API_RemoveBolt; + re.G2API_RemoveBone = G2API_RemoveBone; + re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; + re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; + re.G2API_RemoveSurface = G2API_RemoveSurface; + re.G2API_ResetRagDoll = G2API_ResetRagDoll; + re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; + re.G2API_SetBoltInfo = G2API_SetBoltInfo; + re.G2API_SetBoneAngles = G2API_SetBoneAngles; + re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; + re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; + re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; + re.G2API_SetBoneAnim = G2API_SetBoneAnim; + re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; + re.G2API_SetBoneIKState = G2API_SetBoneIKState; + re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; + re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; + re.G2API_SetLodBias = G2API_SetLodBias; + re.G2API_SetNewOrigin = G2API_SetNewOrigin; + re.G2API_SetRagDoll = G2API_SetRagDoll; + re.G2API_SetRootSurface = G2API_SetRootSurface; + re.G2API_SetShader = G2API_SetShader; + re.G2API_SetSkin = G2API_SetSkin; + re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; + re.G2API_SetTime = G2API_SetTime; + re.G2API_SkinlessModel = G2API_SkinlessModel; + re.G2API_StopBoneAngles = G2API_StopBoneAngles; + re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; + re.G2API_StopBoneAnim = G2API_StopBoneAnim; + re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; + +#ifdef _G2_GORE + re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; + re.G2API_AddSkinGore = G2API_AddSkinGore; + re.G2API_ClearSkinGore = G2API_ClearSkinGore; +#endif // _SOF2 /* Ghoul2 Insert End diff --git a/codemp/rd-rend2/tr_light.cpp b/codemp/rd-rend2/tr_light.cpp index 4716956cf4..9a029174ea 100644 --- a/codemp/rd-rend2/tr_light.cpp +++ b/codemp/rd-rend2/tr_light.cpp @@ -23,13 +23,12 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" -#define DLIGHT_AT_RADIUS 16 +#define DLIGHT_AT_RADIUS 16 // at the edge of a dlight's influence, this amount of light will be added -#define DLIGHT_MINIMUM_RADIUS 16 +#define DLIGHT_MINIMUM_RADIUS 16 // never calculate a range less than this to prevent huge light numbers - /* =============== R_TransformDlights @@ -39,15 +38,15 @@ Used by both the front end (for DlightBmodel) and the back end (before doing the lighting calculation) =============== */ -void R_TransformDlights( int count, dlight_t *dl, orientationr_t *ori) { - int i; - vec3_t temp; - - for ( i = 0 ; i < count ; i++, dl++ ) { - VectorSubtract( dl->origin, ori->origin, temp ); - dl->transformed[0] = DotProduct( temp, ori->axis[0] ); - dl->transformed[1] = DotProduct( temp, ori->axis[1] ); - dl->transformed[2] = DotProduct( temp, ori->axis[2] ); +void R_TransformDlights(int count, dlight_t *dl, orientationr_t *ori) { + int i; + vec3_t temp; + + for (i = 0; i < count; i++, dl++) { + VectorSubtract(dl->origin, ori->origin, temp); + dl->transformed[0] = DotProduct(temp, ori->axis[0]); + dl->transformed[1] = DotProduct(temp, ori->axis[1]); + dl->transformed[2] = DotProduct(temp, ori->axis[2]); } } @@ -58,29 +57,29 @@ R_DlightBmodel Determine which dynamic lights may effect this bmodel ============= */ -void R_DlightBmodel( bmodel_t *bmodel, trRefEntity_t *ent ) { - int i, j; - dlight_t *dl; - int mask; - msurface_t *surf; +void R_DlightBmodel(bmodel_t *bmodel, trRefEntity_t *ent) { + int i, j; + dlight_t *dl; + int mask; + msurface_t *surf; // transform all the lights - R_TransformDlights( tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori ); + R_TransformDlights(tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori); mask = 0; - for ( i=0 ; itransformed[j] - bmodel->bounds[1][j] > dl->radius ) { + for (j = 0; j < 3; j++) { + if (dl->transformed[j] - bmodel->bounds[1][j] > dl->radius) { break; } - if ( bmodel->bounds[0][j] - dl->transformed[j] > dl->radius ) { + if (bmodel->bounds[0][j] - dl->transformed[j] > dl->radius) { break; } } - if ( j < 3 ) { + if (j < 3) { continue; } @@ -91,25 +90,23 @@ void R_DlightBmodel( bmodel_t *bmodel, trRefEntity_t *ent ) { ent->needDlights = (qboolean)(mask != 0); // set the dlight bits in all the surfaces - for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { + for (i = 0; i < bmodel->numSurfaces; i++) { surf = tr.world->surfaces + bmodel->firstSurface + i; - switch(*surf->data) - { - case SF_FACE: - case SF_GRID: - case SF_TRIANGLES: - case SF_VBO_MESH: - ((srfBspSurface_t *)surf->data)->dlightBits = mask; - break; + switch (*surf->data) { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->dlightBits = mask; + break; - default: - break; + default: + break; } } } - /* ============================================================================= @@ -118,9 +115,9 @@ LIGHT SAMPLING ============================================================================= */ -extern cvar_t *r_ambientScale; -extern cvar_t *r_directedScale; -extern cvar_t *r_debugLight; +extern cvar_t *r_ambientScale; +extern cvar_t *r_directedScale; +extern cvar_t *r_debugLight; /* ================= @@ -128,44 +125,44 @@ R_SetupEntityLightingGrid ================= */ -static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { - vec3_t lightOrigin; - int pos[3]; - int i, j; - float frac[3]; - int gridStep[3]; - vec3_t direction; - float totalFactor; +static void R_SetupEntityLightingGrid(trRefEntity_t *ent, world_t *world) { + vec3_t lightOrigin; + int pos[3]; + int i, j; + float frac[3]; + int gridStep[3]; + vec3_t direction; + float totalFactor; uint32_t startGridPos; - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } - VectorSubtract( lightOrigin, world->lightGridOrigin, lightOrigin ); - for ( i = 0 ; i < 3 ; i++ ) { - float v; + VectorSubtract(lightOrigin, world->lightGridOrigin, lightOrigin); + for (i = 0; i < 3; i++) { + float v; - v = lightOrigin[i]*world->lightGridInverseSize[i]; - pos[i] = floor( v ); + v = lightOrigin[i] * world->lightGridInverseSize[i]; + pos[i] = floor(v); frac[i] = v - pos[i]; - if ( pos[i] < 0 ) { + if (pos[i] < 0) { pos[i] = 0; - } else if ( pos[i] >= world->lightGridBounds[i] - 1 ) { + } else if (pos[i] >= world->lightGridBounds[i] - 1) { pos[i] = world->lightGridBounds[i] - 1; } } - VectorClear( ent->ambientLight ); - VectorClear( ent->directedLight ); - VectorClear( direction ); + VectorClear(ent->ambientLight); + VectorClear(ent->directedLight); + VectorClear(direction); - assert( world->lightGridData ); // NULL with -nolight maps + assert(world->lightGridData); // NULL with -nolight maps // trilerp the light value gridStep[0] = 1; @@ -174,22 +171,22 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { startGridPos = pos[0] * gridStep[0] + pos[1] * gridStep[1] + pos[2] * gridStep[2]; totalFactor = 0; - for ( i = 0 ; i < 8 ; i++ ) { - float factor; - mgrid_t *data; + for (i = 0; i < 8; i++) { + float factor; + mgrid_t *data; uint32_t gridPos; - int lat, lng; - vec3_t normal; + int lat, lng; + vec3_t normal; - #if idppc +#if idppc float d0, d1, d2, d3, d4, d5; - #endif +#endif factor = 1.0; gridPos = startGridPos; - for ( j = 0 ; j < 3 ; j++ ) { - if ( i & (1<= world->numGridArrayElements) - {//we've gone off the array somehow + if (gridPos >= world->numGridArrayElements) { // we've gone off the array somehow continue; } - data = world->lightGridData + *(world->lightGridArray+gridPos); - if ( data->styles[0] == LS_LSNONE ) - { - continue; // ignore samples in walls + data = world->lightGridData + *(world->lightGridArray + gridPos); + if (data->styles[0] == LS_LSNONE) { + continue; // ignore samples in walls } totalFactor += factor; - #if idppc - d0 = data[0]; d1 = data[1]; d2 = data[2]; - d3 = data[3]; d4 = data[4]; d5 = data[5]; +#if idppc + d0 = data[0]; + d1 = data[1]; + d2 = data[2]; + d3 = data[3]; + d4 = data[4]; + d5 = data[5]; ent->ambientLight[0] += factor * d0; ent->ambientLight[1] += factor * d1; @@ -220,9 +219,8 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { ent->directedLight[0] += factor * d3; ent->directedLight[1] += factor * d4; ent->directedLight[2] += factor * d5; - #else - if (world->hdrLightGrid) - { +#else + if (world->hdrLightGrid) { float *hdrData = world->hdrLightGrid + (gridPos * 6); ent->ambientLight[0] += factor * hdrData[0] * 255.0f; ent->ambientLight[1] += factor * hdrData[1] * 255.0f; @@ -231,14 +229,10 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { ent->directedLight[0] += factor * hdrData[3] * 255.0f; ent->directedLight[1] += factor * hdrData[4] * 255.0f; ent->directedLight[2] += factor * hdrData[5] * 255.0f; - } - else - { - for(j=0;jstyles[j] != LS_LSNONE) - { - const byte style= data->styles[j]; + } else { + for (j = 0; j < MAXLIGHTMAPS; j++) { + if (data->styles[j] != LS_LSNONE) { + const byte style = data->styles[j]; ent->ambientLight[0] += factor * data->ambientLight[j][0] * styleColors[style][0] / 255.0f; ent->ambientLight[1] += factor * data->ambientLight[j][1] * styleColors[style][1] / 255.0f; @@ -247,70 +241,67 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { ent->directedLight[0] += factor * data->directLight[j][0] * styleColors[style][0] / 255.0f; ent->directedLight[1] += factor * data->directLight[j][1] * styleColors[style][1] / 255.0f; ent->directedLight[2] += factor * data->directLight[j][2] * styleColors[style][2] / 255.0f; - } - else - { + } else { break; } } } - #endif +#endif lat = data->latLong[1]; lng = data->latLong[0]; - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) // decode Z as cos( long ) - normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + normal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + normal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; - VectorMA( direction, factor, normal, direction ); + VectorMA(direction, factor, normal, direction); } - if ( totalFactor > 0 && totalFactor < 0.99 ) { + if (totalFactor > 0 && totalFactor < 0.99) { totalFactor = 1.0f / totalFactor; - VectorScale( ent->ambientLight, totalFactor, ent->ambientLight ); - VectorScale( ent->directedLight, totalFactor, ent->directedLight ); + VectorScale(ent->ambientLight, totalFactor, ent->ambientLight); + VectorScale(ent->directedLight, totalFactor, ent->directedLight); } - VectorScale( ent->ambientLight, r_ambientScale->value, ent->ambientLight ); - VectorScale( ent->directedLight, r_directedScale->value, ent->directedLight ); + VectorScale(ent->ambientLight, r_ambientScale->value, ent->ambientLight); + VectorScale(ent->directedLight, r_directedScale->value, ent->directedLight); - VectorNormalize2( direction, ent->lightDir ); + VectorNormalize2(direction, ent->lightDir); } - /* =============== LogLight =============== */ -static void LogLight( trRefEntity_t *ent ) { - int max1, max2; +static void LogLight(trRefEntity_t *ent) { + int max1, max2; - if ( !(ent->e.renderfx & RF_FIRST_PERSON ) ) { + if (!(ent->e.renderfx & RF_FIRST_PERSON)) { return; } max1 = ent->ambientLight[0]; - if ( ent->ambientLight[1] > max1 ) { + if (ent->ambientLight[1] > max1) { max1 = ent->ambientLight[1]; - } else if ( ent->ambientLight[2] > max1 ) { + } else if (ent->ambientLight[2] > max1) { max1 = ent->ambientLight[2]; } max2 = ent->directedLight[0]; - if ( ent->directedLight[1] > max2 ) { + if (ent->directedLight[1] > max2) { max2 = ent->directedLight[1]; - } else if ( ent->directedLight[2] > max2 ) { + } else if (ent->directedLight[2] > max2) { max2 = ent->directedLight[2]; } - ri.Printf( PRINT_ALL, "amb:%i dir:%i\n", max1, max2 ); + ri.Printf(PRINT_ALL, "amb:%i dir:%i\n", max1, max2); } /* @@ -321,14 +312,14 @@ Calculates all the lighting values that will be used by the Calc_* functions ================= */ -void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { - int i; - float d; - vec3_t lightDir; - vec3_t lightOrigin; - - // lighting calculations - if ( ent->lightingCalculated ) { +void R_SetupEntityLighting(const trRefdef_t *refdef, trRefEntity_t *ent) { + int i; + float d; + vec3_t lightDir; + vec3_t lightOrigin; + + // lighting calculations + if (ent->lightingCalculated) { return; } ent->lightingCalculated = qtrue; @@ -336,50 +327,40 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { // // trace a sample point down to find ambient light // - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } // if NOWORLDMODEL, only use dynamic lights (menu system, etc) - if ( !(refdef->rdflags & RDF_NOWORLDMODEL ) - && tr.world->lightGridData ) { - R_SetupEntityLightingGrid( ent, tr.world ); + if (!(refdef->rdflags & RDF_NOWORLDMODEL) && tr.world->lightGridData) { + R_SetupEntityLightingGrid(ent, tr.world); } else { - ent->ambientLight[0] = ent->ambientLight[1] = - ent->ambientLight[2] = tr.identityLight * 150; - ent->directedLight[0] = ent->directedLight[1] = - ent->directedLight[2] = tr.identityLight * 150; - VectorCopy( tr.sunDirection, ent->lightDir ); + ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = tr.identityLight * 150; + ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = tr.identityLight * 150; + VectorCopy(tr.sunDirection, ent->lightDir); } // only do min lighting when there is no hdr light data - if (tr.hdrLighting != qtrue) - { + if (tr.hdrLighting != qtrue) { // bonus items and view weapons have a fixed minimum add - if (1/*!r_hdr->integer*/) { + if (1 /*!r_hdr->integer*/) { // give everything a minimum light add ent->ambientLight[0] += tr.identityLight * 32; ent->ambientLight[1] += tr.identityLight * 32; ent->ambientLight[2] += tr.identityLight * 32; } - if (ent->e.renderfx & RF_MINLIGHT) - { //the minlight flag is now for items rotating on their holo thing - if (ent->e.shaderRGBA[0] == 255 && - ent->e.shaderRGBA[1] == 255 && - ent->e.shaderRGBA[2] == 0) - { + if (ent->e.renderfx & RF_MINLIGHT) { // the minlight flag is now for items rotating on their holo thing + if (ent->e.shaderRGBA[0] == 255 && ent->e.shaderRGBA[1] == 255 && ent->e.shaderRGBA[2] == 0) { ent->ambientLight[0] += tr.identityLight * 255; ent->ambientLight[1] += tr.identityLight * 255; ent->ambientLight[2] += tr.identityLight * 0; - } - else - { + } else { ent->ambientLight[0] += tr.identityLight * 16; ent->ambientLight[1] += tr.identityLight * 96; ent->ambientLight[2] += tr.identityLight * 150; @@ -387,21 +368,20 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { } } - d = VectorLength( ent->directedLight ); - VectorScale( ent->lightDir, d, lightDir ); + d = VectorLength(ent->directedLight); + VectorScale(ent->lightDir, d, lightDir); // clamp ambient - if (tr.hdrLighting != qtrue) - { - for ( i = 0 ; i < 3 ; i++ ) { - if ( ent->ambientLight[i] > tr.identityLightByte ) { + if (tr.hdrLighting != qtrue) { + for (i = 0; i < 3; i++) { + if (ent->ambientLight[i] > tr.identityLightByte) { ent->ambientLight[i] = tr.identityLightByte; } } } - if ( r_debugLight->integer ) { - LogLight( ent ); + if (r_debugLight->integer) { + LogLight(ent); } // save out the byte packet version @@ -409,14 +389,14 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { ((byte *)&ent->ambientLightInt)[1] = Q_ftol(ent->ambientLight[1]); ((byte *)&ent->ambientLightInt)[2] = Q_ftol(ent->ambientLight[2]); ((byte *)&ent->ambientLightInt)[3] = 0xff; - + // transform the direction to local space - VectorNormalize( lightDir ); + VectorNormalize(lightDir); VectorCopy(lightDir, ent->lightDir); - ent->modelLightDir[0] = DotProduct( lightDir, ent->e.axis[0] ); - ent->modelLightDir[1] = DotProduct( lightDir, ent->e.axis[1] ); - ent->modelLightDir[2] = DotProduct( lightDir, ent->e.axis[2] ); + ent->modelLightDir[0] = DotProduct(lightDir, ent->e.axis[0]); + ent->modelLightDir[1] = DotProduct(lightDir, ent->e.axis[1]); + ent->modelLightDir[2] = DotProduct(lightDir, ent->e.axis[2]); } /* @@ -424,16 +404,15 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { R_LightForPoint ================= */ -int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) -{ +int R_LightForPoint(vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { trRefEntity_t ent; - - if ( tr.world->lightGridData == NULL ) - return qfalse; + + if (tr.world->lightGridData == NULL) + return qfalse; Com_Memset(&ent, 0, sizeof(ent)); - VectorCopy( point, ent.e.origin ); - R_SetupEntityLightingGrid( &ent, tr.world ); + VectorCopy(point, ent.e.origin); + R_SetupEntityLightingGrid(&ent, tr.world); VectorCopy(ent.ambientLight, ambientLight); VectorCopy(ent.directedLight, directedLight); VectorCopy(ent.lightDir, lightDir); @@ -441,17 +420,15 @@ int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, ve return qtrue; } - -int R_LightDirForPoint( vec3_t point, vec3_t lightDir, vec3_t normal, world_t *world ) -{ +int R_LightDirForPoint(vec3_t point, vec3_t lightDir, vec3_t normal, world_t *world) { trRefEntity_t ent; - - if ( world->lightGridData == NULL ) - return qfalse; + + if (world->lightGridData == NULL) + return qfalse; Com_Memset(&ent, 0, sizeof(ent)); - VectorCopy( point, ent.e.origin ); - R_SetupEntityLightingGrid( &ent, world ); + VectorCopy(point, ent.e.origin); + R_SetupEntityLightingGrid(&ent, world); if (DotProduct(ent.lightDir, normal) > 0.2f) VectorCopy(ent.lightDir, lightDir); @@ -461,17 +438,15 @@ int R_LightDirForPoint( vec3_t point, vec3_t lightDir, vec3_t normal, world_t *w return qtrue; } -int R_DLightsForPoint(const vec3_t point, const float radius) -{ +int R_DLightsForPoint(const vec3_t point, const float radius) { int dlightBits = 0; vec3_t delta; dlight_t currentDlight; float distance; float radiusSum; - for (int i = 0; i < tr.refdef.num_dlights; i++) - { + for (int i = 0; i < tr.refdef.num_dlights; i++) { currentDlight = tr.refdef.dlights[i]; - + VectorSubtract(point, currentDlight.origin, delta); distance = VectorLength(delta); radiusSum = radius + currentDlight.radius; @@ -482,25 +457,21 @@ int R_DLightsForPoint(const vec3_t point, const float radius) return dlightBits; } -int R_CubemapForPoint( const vec3_t point ) -{ +int R_CubemapForPoint(const vec3_t point) { int cubemapIndex = -1; - if (r_cubeMapping->integer && tr.numCubemaps) - { + if (r_cubeMapping->integer && tr.numCubemaps) { int i; float shortest = (float)WORLD_SIZE * (float)WORLD_SIZE; - for (i = 0; i < tr.numCubemaps; i++) - { + for (i = 0; i < tr.numCubemaps; i++) { vec3_t diff; float length; VectorSubtract(point, tr.cubemaps[i].origin, diff); length = DotProduct(diff, diff); - if (shortest > length) - { + if (shortest > length) { shortest = length; cubemapIndex = i; } diff --git a/codemp/rd-rend2/tr_main.cpp b/codemp/rd-rend2/tr_main.cpp index 17c5c736a9..a4f17060c4 100644 --- a/codemp/rd-rend2/tr_main.cpp +++ b/codemp/rd-rend2/tr_main.cpp @@ -28,42 +28,33 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "ghoul2/g2_local.h" -trGlobals_t tr; +trGlobals_t tr; -static float s_flipMatrix[16] = { +static float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; - -refimport_t ri; +refimport_t ri; // entities that will have procedurally generated surfaces will just // point at this for their sorting surface -surfaceType_t entitySurface = SF_ENTITY; +surfaceType_t entitySurface = SF_ENTITY; /* ================ R_CompareVert ================ */ -qboolean R_CompareVert(srfVert_t * v1, srfVert_t * v2, qboolean checkST) -{ - int i; +qboolean R_CompareVert(srfVert_t *v1, srfVert_t *v2, qboolean checkST) { + int i; - for (i = 0; i < 3; i++) - { - if (floor(v1->xyz[i] + 0.1) != floor(v2->xyz[i] + 0.1)) - { + for (i = 0; i < 3; i++) { + if (floor(v1->xyz[i] + 0.1) != floor(v2->xyz[i] + 0.1)) { return qfalse; } - if (checkST && ((v1->st[0] != v2->st[0]) || (v1->st[1] != v2->st[1]))) - { + if (checkST && ((v1->st[0] != v2->st[0]) || (v1->st[1] != v2->st[1]))) { return qfalse; } } @@ -76,9 +67,8 @@ qboolean R_CompareVert(srfVert_t * v1, srfVert_t * v2, qboolean checkST) R_CalcNormalForTriangle ============= */ -void R_CalcNormalForTriangle(vec3_t normal, const vec3_t v0, const vec3_t v1, const vec3_t v2) -{ - vec3_t udir, vdir; +void R_CalcNormalForTriangle(vec3_t normal, const vec3_t v0, const vec3_t v1, const vec3_t v2) { + vec3_t udir, vdir; // compute the face normal based on vertex points VectorSubtract(v2, v0, udir); @@ -94,16 +84,13 @@ R_CalcTangentsForTriangle http://members.rogers.com/deseric/tangentspace.htm ============= */ -void R_CalcTangentsForTriangle(vec3_t tangent, vec3_t bitangent, - const vec3_t v0, const vec3_t v1, const vec3_t v2, - const vec2_t t0, const vec2_t t1, const vec2_t t2) -{ - int i; - vec3_t planes[3]; - vec3_t u, v; - - for(i = 0; i < 3; i++) - { +void R_CalcTangentsForTriangle(vec3_t tangent, vec3_t bitangent, const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, + const vec2_t t2) { + int i; + vec3_t planes[3]; + vec3_t u, v; + + for (i = 0; i < 3; i++) { VectorSet(u, v1[i] - v0[i], t1[0] - t0[0], t1[1] - t0[1]); VectorSet(v, v2[i] - v0[i], t2[0] - t0[0], t2[1] - t0[1]); @@ -113,11 +100,11 @@ void R_CalcTangentsForTriangle(vec3_t tangent, vec3_t bitangent, CrossProduct(u, v, planes[i]); } - //So your tangent space will be defined by this : - //Normal = Normal of the triangle or Tangent X Bitangent (careful with the cross product, - // you have to make sure the normal points in the right direction) - //Tangent = ( dp(Fx(s,t)) / ds, dp(Fy(s,t)) / ds, dp(Fz(s,t)) / ds ) or ( -Bx/Ax, -By/Ay, - Bz/Az ) - //Bitangent = ( dp(Fx(s,t)) / dt, dp(Fy(s,t)) / dt, dp(Fz(s,t)) / dt ) or ( -Cx/Ax, -Cy/Ay, -Cz/Az ) + // So your tangent space will be defined by this : + // Normal = Normal of the triangle or Tangent X Bitangent (careful with the cross product, + // you have to make sure the normal points in the right direction) + // Tangent = ( dp(Fx(s,t)) / ds, dp(Fy(s,t)) / ds, dp(Fz(s,t)) / ds ) or ( -Bx/Ax, -By/Ay, - Bz/Az ) + // Bitangent = ( dp(Fx(s,t)) / dt, dp(Fy(s,t)) / dt, dp(Fz(s,t)) / dt ) or ( -Cx/Ax, -Cy/Ay, -Cz/Az ) // tangent... tangent[0] = -planes[0][1] / planes[0][0]; @@ -132,26 +119,21 @@ void R_CalcTangentsForTriangle(vec3_t tangent, vec3_t bitangent, VectorNormalize(bitangent); } - - - /* ============= R_CalcTangentSpace ============= */ -void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, - const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, const vec2_t t2) -{ - vec3_t cp, u, v; - vec3_t faceNormal; +void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, + const vec2_t t2) { + vec3_t cp, u, v; + vec3_t faceNormal; VectorSet(u, v1[0] - v0[0], t1[0] - t0[0], t1[1] - t0[1]); VectorSet(v, v2[0] - v0[0], t2[0] - t0[0], t2[1] - t0[1]); CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[0] = -cp[1] / cp[0]; bitangent[0] = -cp[2] / cp[0]; } @@ -160,8 +142,7 @@ void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, v[0] = v2[1] - v0[1]; CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[1] = -cp[1] / cp[0]; bitangent[1] = -cp[2] / cp[0]; } @@ -170,8 +151,7 @@ void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, v[0] = v2[2] - v0[2]; CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[2] = -cp[1] / cp[0]; bitangent[2] = -cp[2] / cp[0]; } @@ -180,14 +160,11 @@ void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, VectorNormalize(bitangent); // compute the face normal based on vertex points - if ( normal[0] == 0.0f && normal[1] == 0.0f && normal[2] == 0.0f ) - { + if (normal[0] == 0.0f && normal[1] == 0.0f && normal[2] == 0.0f) { VectorSubtract(v2, v0, u); VectorSubtract(v1, v0, v); CrossProduct(u, v, faceNormal); - } - else - { + } else { VectorCopy(normal, faceNormal); } @@ -195,46 +172,43 @@ void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, #if 1 // Gram-Schmidt orthogonalize - //tangent[a] = (t - n * Dot(n, t)).Normalize(); + // tangent[a] = (t - n * Dot(n, t)).Normalize(); VectorMA(tangent, -DotProduct(faceNormal, tangent), faceNormal, tangent); VectorNormalize(tangent); // compute the cross product B=NxT - //CrossProduct(normal, tangent, bitangent); + // CrossProduct(normal, tangent, bitangent); #else // normal, compute the cross product N=TxB CrossProduct(tangent, bitangent, normal); VectorNormalize(normal); - if(DotProduct(normal, faceNormal) < 0) - { - //VectorInverse(normal); - //VectorInverse(tangent); - //VectorInverse(bitangent); + if (DotProduct(normal, faceNormal) < 0) { + // VectorInverse(normal); + // VectorInverse(tangent); + // VectorInverse(bitangent); // compute the cross product T=BxN CrossProduct(bitangent, faceNormal, tangent); // compute the cross product B=NxT - //CrossProduct(normal, tangent, bitangent); + // CrossProduct(normal, tangent, bitangent); } #endif VectorCopy(faceNormal, normal); } -void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, - const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, const vec2_t t2) -{ - vec3_t cp, u, v; - vec3_t faceNormal; +void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, + const vec2_t t1, const vec2_t t2) { + vec3_t cp, u, v; + vec3_t faceNormal; VectorSet(u, v1[0] - v0[0], t1[0] - t0[0], t1[1] - t0[1]); VectorSet(v, v2[0] - v0[0], t2[0] - t0[0], t2[1] - t0[1]); CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[0] = -cp[1] / cp[0]; bitangent[0] = -cp[2] / cp[0]; } @@ -243,8 +217,7 @@ void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, v[0] = v2[1] - v0[1]; CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[1] = -cp[1] / cp[0]; bitangent[1] = -cp[2] / cp[0]; } @@ -253,8 +226,7 @@ void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, v[0] = v2[2] - v0[2]; CrossProduct(u, v, cp); - if(fabs(cp[0]) > 10e-6) - { + if (fabs(cp[0]) > 10e-6) { tangent[2] = -cp[1] / cp[0]; bitangent[2] = -cp[2] / cp[0]; } @@ -286,7 +258,7 @@ void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, VectorCopy(faceNormal, normal); #else // Gram-Schmidt orthogonalize - //tangent[a] = (t - n * Dot(n, t)).Normalize(); + // tangent[a] = (t - n * Dot(n, t)).Normalize(); VectorMA(tangent, -DotProduct(faceNormal, tangent), faceNormal, tangent); VectorNormalizeFast(tangent); #endif @@ -297,11 +269,9 @@ void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, /* http://www.terathon.com/code/tangent.html */ -void R_CalcTexDirs(vec3_t sdir, vec3_t tdir, const vec3_t v1, const vec3_t v2, - const vec3_t v3, const vec2_t w1, const vec2_t w2, const vec2_t w3) -{ - float x1, x2, y1, y2, z1, z2; - float s1, s2, t1, t2, r; +void R_CalcTexDirs(vec3_t sdir, vec3_t tdir, const vec3_t v1, const vec3_t v2, const vec3_t v3, const vec2_t w1, const vec2_t w2, const vec2_t w3) { + float x1, x2, y1, y2, z1, z2; + float s1, s2, t1, t2, r; x1 = v2[0] - v1[0]; x2 = v3[0] - v1[0]; @@ -321,8 +291,7 @@ void R_CalcTexDirs(vec3_t sdir, vec3_t tdir, const vec3_t v1, const vec3_t v2, VectorSet(tdir, (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); } -void R_CalcTbnFromNormalAndTexDirs(vec3_t tangent, vec3_t bitangent, vec3_t normal, vec3_t sdir, vec3_t tdir) -{ +void R_CalcTbnFromNormalAndTexDirs(vec3_t tangent, vec3_t bitangent, vec3_t normal, vec3_t sdir, vec3_t tdir) { vec3_t n_cross_t; float n_dot_t, handedness; @@ -340,21 +309,18 @@ void R_CalcTbnFromNormalAndTexDirs(vec3_t tangent, vec3_t bitangent, vec3_t norm VectorScale(bitangent, handedness, bitangent); } -qboolean R_CalcTangentVectors(srfVert_t * dv[3]) -{ - int i; - float bb, s, t; - vec3_t bary; - +qboolean R_CalcTangentVectors(srfVert_t *dv[3]) { + int i; + float bb, s, t; + vec3_t bary; /* calculate barycentric basis for the triangle */ bb = (dv[1]->st[0] - dv[0]->st[0]) * (dv[2]->st[1] - dv[0]->st[1]) - (dv[2]->st[0] - dv[0]->st[0]) * (dv[1]->st[1] - dv[0]->st[1]); - if(fabs(bb) < 0.00000001f) + if (fabs(bb) < 0.00000001f) return qfalse; /* do each vertex */ - for(i = 0; i < 3; i++) - { + for (i = 0; i < 3; i++) { vec3_t bitangent, nxt; // calculate s tangent vector @@ -460,21 +426,19 @@ int R_CullLocalBox(vec3_t localBounds[2]) { return CULL_CLIP; // partially clipped #else - int j; - vec3_t transformed; - vec3_t v; - vec3_t worldBounds[2]; + int j; + vec3_t transformed; + vec3_t v; + vec3_t worldBounds[2]; - if(r_nocull->integer) - { + if (r_nocull->integer) { return CULL_CLIP; } // transform into world space ClearBounds(worldBounds[0], worldBounds[1]); - for(j = 0; j < 8; j++) - { + for (j = 0; j < 8; j++) { v[0] = localBounds[j & 1][0]; v[1] = localBounds[(j >> 1) & 1][1]; v[2] = localBounds[(j >> 2) & 1][2]; @@ -496,34 +460,30 @@ Returns CULL_IN, CULL_CLIP, or CULL_OUT ================= */ int R_CullBox(vec3_t worldBounds[2]) { - int i; - cplane_t *frust; - qboolean anyClip; - int r, numPlanes; + int i; + cplane_t *frust; + qboolean anyClip; + int r, numPlanes; numPlanes = (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 5 : 4; // check against frustum planes anyClip = qfalse; - for(i = 0; i < numPlanes; i++) - { + for (i = 0; i < numPlanes; i++) { frust = &tr.viewParms.frustum[i]; r = BoxOnPlaneSide(worldBounds[0], worldBounds[1], frust); - if(r == 2) - { + if (r == 2) { // completely outside frustum return CULL_OUT; } - if(r == 3) - { + if (r == 3) { anyClip = qtrue; } } - if(!anyClip) - { + if (!anyClip) { // completely inside frustum return CULL_IN; } @@ -535,58 +495,50 @@ int R_CullBox(vec3_t worldBounds[2]) { /* ** R_CullLocalPointAndRadius */ -int R_CullLocalPointAndRadius( const vec3_t pt, float radius ) -{ +int R_CullLocalPointAndRadius(const vec3_t pt, float radius) { vec3_t transformed; - R_LocalPointToWorld( pt, transformed ); + R_LocalPointToWorld(pt, transformed); - return R_CullPointAndRadius( transformed, radius ); + return R_CullPointAndRadius(transformed, radius); } /* ** R_CullPointAndRadius */ -int R_CullPointAndRadiusEx( const vec3_t pt, float radius, const cplane_t* frustum, int numPlanes ) -{ - int i; - float dist; - const cplane_t *frust; +int R_CullPointAndRadiusEx(const vec3_t pt, float radius, const cplane_t *frustum, int numPlanes) { + int i; + float dist; + const cplane_t *frust; qboolean mightBeClipped = qfalse; - if ( r_nocull->integer ) { + if (r_nocull->integer) { return CULL_CLIP; } // check against frustum planes - for (i = 0 ; i < numPlanes ; i++) - { + for (i = 0; i < numPlanes; i++) { frust = &frustum[i]; - dist = DotProduct( pt, frust->normal) - frust->dist; - if ( dist < -radius ) - { + dist = DotProduct(pt, frust->normal) - frust->dist; + if (dist < -radius) { return CULL_OUT; - } - else if ( dist <= radius ) - { + } else if (dist <= radius) { mightBeClipped = qtrue; } } - if ( mightBeClipped ) - { + if (mightBeClipped) { return CULL_CLIP; } - return CULL_IN; // completely inside frustum + return CULL_IN; // completely inside frustum } /* ** R_CullPointAndRadius */ -int R_CullPointAndRadius( const vec3_t pt, float radius ) -{ +int R_CullPointAndRadius(const vec3_t pt, float radius) { return R_CullPointAndRadiusEx(pt, radius, tr.viewParms.frustum, (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 5 : 4); } @@ -596,7 +548,7 @@ R_LocalNormalToWorld ================= */ -void R_LocalNormalToWorld (const vec3_t local, vec3_t world) { +void R_LocalNormalToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2]; @@ -608,7 +560,7 @@ R_LocalPointToWorld ================= */ -void R_LocalPointToWorld (const vec3_t local, vec3_t world) { +void R_LocalPointToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0] + tr.ori.origin[0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1] + tr.ori.origin[1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2] + tr.ori.origin[2]; @@ -620,7 +572,7 @@ R_WorldToLocal ================= */ -void R_WorldToLocal (const vec3_t world, vec3_t local) { +void R_WorldToLocal(const vec3_t world, vec3_t local) { local[0] = DotProduct(world, tr.ori.axis[0]); local[1] = DotProduct(world, tr.ori.axis[1]); local[2] = DotProduct(world, tr.ori.axis[2]); @@ -632,24 +584,17 @@ R_TransformModelToClip ========================== */ -void R_TransformModelToClip( const vec3_t src, const float *modelViewMatrix, const float *projectionMatrix, - vec4_t eye, vec4_t dst ) { +void R_TransformModelToClip(const vec3_t src, const float *modelViewMatrix, const float *projectionMatrix, vec4_t eye, vec4_t dst) { int i; - for ( i = 0 ; i < 4 ; i++ ) { - eye[i] = - src[0] * modelViewMatrix[ i + 0 * 4 ] + - src[1] * modelViewMatrix[ i + 1 * 4 ] + - src[2] * modelViewMatrix[ i + 2 * 4 ] + - 1 * modelViewMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + eye[i] = + src[0] * modelViewMatrix[i + 0 * 4] + src[1] * modelViewMatrix[i + 1 * 4] + src[2] * modelViewMatrix[i + 2 * 4] + 1 * modelViewMatrix[i + 3 * 4]; } - for ( i = 0 ; i < 4 ; i++ ) { - dst[i] = - eye[0] * projectionMatrix[ i + 0 * 4 ] + - eye[1] * projectionMatrix[ i + 1 * 4 ] + - eye[2] * projectionMatrix[ i + 2 * 4 ] + - eye[3] * projectionMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + dst[i] = eye[0] * projectionMatrix[i + 0 * 4] + eye[1] * projectionMatrix[i + 1 * 4] + eye[2] * projectionMatrix[i + 2 * 4] + + eye[3] * projectionMatrix[i + 3 * 4]; } } @@ -659,36 +604,31 @@ R_TransformClipToWindow ========================== */ -void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ) { +void R_TransformClipToWindow(const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window) { normalized[0] = clip[0] / clip[3]; normalized[1] = clip[1] / clip[3]; - normalized[2] = ( clip[2] + clip[3] ) / ( 2 * clip[3] ); + normalized[2] = (clip[2] + clip[3]) / (2 * clip[3]); - window[0] = 0.5f * ( 1.0f + normalized[0] ) * view->viewportWidth; - window[1] = 0.5f * ( 1.0f + normalized[1] ) * view->viewportHeight; + window[0] = 0.5f * (1.0f + normalized[0]) * view->viewportWidth; + window[1] = 0.5f * (1.0f + normalized[1]) * view->viewportHeight; window[2] = normalized[2]; - window[0] = (int) ( window[0] + 0.5 ); - window[1] = (int) ( window[1] + 0.5 ); + window[0] = (int)(window[0] + 0.5); + window[1] = (int)(window[1] + 0.5); } - /* ========================== myGlMultMatrix ========================== */ -void myGlMultMatrix( const float *a, const float *b, float *out ) { - int i, j; +void myGlMultMatrix(const float *a, const float *b, float *out) { + int i, j; - for ( i = 0 ; i < 4 ; i++ ) { - for ( j = 0 ; j < 4 ; j++ ) { - out[ i * 4 + j ] = - a [ i * 4 + 0 ] * b [ 0 * 4 + j ] - + a [ i * 4 + 1 ] * b [ 1 * 4 + j ] - + a [ i * 4 + 2 ] * b [ 2 * 4 + j ] - + a [ i * 4 + 3 ] * b [ 3 * 4 + j ]; + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + out[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] + a[i * 4 + 1] * b[1 * 4 + j] + a[i * 4 + 2] * b[2 * 4 + j] + a[i * 4 + 3] * b[3 * 4 + j]; } } } @@ -702,22 +642,20 @@ Does NOT produce any GL calls Called by both the front end and the back end ================= */ -void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, - orientationr_t *ori ) -{ - vec3_t delta; - float axisLength; +void R_RotateForEntity(const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *ori) { + vec3_t delta; + float axisLength; - if ( ent->e.reType != RT_MODEL || ent == &tr.worldEntity ) { + if (ent->e.reType != RT_MODEL || ent == &tr.worldEntity) { *ori = viewParms->world; return; } - VectorCopy( ent->e.origin, ori->origin ); + VectorCopy(ent->e.origin, ori->origin); - VectorCopy( ent->e.axis[0], ori->axis[0] ); - VectorCopy( ent->e.axis[1], ori->axis[1] ); - VectorCopy( ent->e.axis[2], ori->axis[2] ); + VectorCopy(ent->e.axis[0], ori->axis[0]); + VectorCopy(ent->e.axis[1], ori->axis[1]); + VectorCopy(ent->e.axis[2], ori->axis[2]); ori->modelMatrix[0] = ori->axis[0][0]; ori->modelMatrix[4] = ori->axis[1][0]; @@ -741,12 +679,12 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, // calculate the viewer origin in the model's space // needed for fog, specular, and environment mapping - VectorSubtract( viewParms->ori.origin, ori->origin, delta ); + VectorSubtract(viewParms->ori.origin, ori->origin, delta); // compensate for scale in the axes if necessary - if ( ent->e.nonNormalizedAxes ) { - axisLength = VectorLength( ent->e.axis[0] ); - if ( !axisLength ) { + if (ent->e.nonNormalizedAxes) { + axisLength = VectorLength(ent->e.axis[0]); + if (!axisLength) { axisLength = 0; } else { axisLength = 1.0f / axisLength; @@ -755,9 +693,9 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, axisLength = 1.0f; } - ori->viewOrigin[0] = DotProduct( delta, ori->axis[0] ) * axisLength; - ori->viewOrigin[1] = DotProduct( delta, ori->axis[1] ) * axisLength; - ori->viewOrigin[2] = DotProduct( delta, ori->axis[2] ) * axisLength; + ori->viewOrigin[0] = DotProduct(delta, ori->axis[0]) * axisLength; + ori->viewOrigin[1] = DotProduct(delta, ori->axis[1]) * axisLength; + ori->viewOrigin[2] = DotProduct(delta, ori->axis[2]) * axisLength; } /* @@ -767,10 +705,9 @@ R_RotateForViewer Sets up the modelview matrix for a given viewParm ================= */ -static void R_RotateForViewer(orientationr_t *ori, viewParms_t *viewParms) -{ - float viewerMatrix[16]; - vec3_t origin; +static void R_RotateForViewer(orientationr_t *ori, viewParms_t *viewParms) { + float viewerMatrix[16]; + vec3_t origin; *ori = {}; ori->axis[0][0] = 1.0f; @@ -810,15 +747,13 @@ static void R_RotateForViewer(orientationr_t *ori, viewParms_t *viewParms) /* ** SetFarClip */ -static void R_SetFarClip( viewParms_t *viewParms, const trRefdef_t *refdef ) -{ - float farthestCornerDistance = 0; - int i; +static void R_SetFarClip(viewParms_t *viewParms, const trRefdef_t *refdef) { + float farthestCornerDistance = 0; + int i; // if not rendering the world (icons, menus, etc) // set a 2k far clip plane - if (refdef != NULL) - { + if (refdef != NULL) { if (refdef->rdflags & RDF_NOWORLDMODEL) { // override the zfar then if (refdef->rdflags & RDF_AUTOMAP) @@ -828,46 +763,35 @@ static void R_SetFarClip( viewParms_t *viewParms, const trRefdef_t *refdef ) return; } } - + // // set far clipping planes dynamically // - for ( i = 0; i < 8; i++ ) - { + for (i = 0; i < 8; i++) { vec3_t v; float distance; - if ( i & 1 ) - { + if (i & 1) { v[0] = viewParms->visBounds[0][0]; - } - else - { + } else { v[0] = viewParms->visBounds[1][0]; } - if ( i & 2 ) - { + if (i & 2) { v[1] = viewParms->visBounds[0][1]; - } - else - { + } else { v[1] = viewParms->visBounds[1][1]; } - if ( i & 4 ) - { + if (i & 4) { v[2] = viewParms->visBounds[0][2]; - } - else - { + } else { v[2] = viewParms->visBounds[1][2]; } - distance = DistanceSquared( viewParms->ori.origin, v ); + distance = DistanceSquared(viewParms->ori.origin, v); - if ( distance > farthestCornerDistance ) - { + if (distance > farthestCornerDistance) { farthestCornerDistance = distance; } } @@ -875,7 +799,7 @@ static void R_SetFarClip( viewParms_t *viewParms, const trRefdef_t *refdef ) // Bring in the zFar to the distanceCull distance // The sky renders at zFar so need to move it out a little // ...and make sure there is a minimum zfar to prevent problems - viewParms->zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf( farthestCornerDistance )); + viewParms->zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf(farthestCornerDistance)); } /* @@ -886,14 +810,12 @@ Set up the culling frustum planes for the current view using the results we got the projection matrix. ================= */ -void R_SetupFrustum (viewParms_t *dest, float xmin, float xmax, float ymax, float zProj, float zFar, float stereoSep) -{ +void R_SetupFrustum(viewParms_t *dest, float xmin, float xmax, float ymax, float zProj, float zFar, float stereoSep) { vec3_t ofsorigin; float oppleg, adjleg, length; int i; - - if(stereoSep == 0 && xmin == -xmax) - { + + if (stereoSep == 0 && xmin == -xmax) { // symmetric case can be simplified VectorCopy(dest->ori.origin, ofsorigin); @@ -906,13 +828,11 @@ void R_SetupFrustum (viewParms_t *dest, float xmin, float xmax, float ymax, floa VectorScale(dest->ori.axis[0], oppleg, dest->frustum[1].normal); VectorMA(dest->frustum[1].normal, -adjleg, dest->ori.axis[1], dest->frustum[1].normal); - } - else - { + } else { // In stereo rendering, due to the modification of the projection matrix, dest->ori.origin is not the // actual origin that we're rendering so offset the tip of the view pyramid. VectorMA(dest->ori.origin, stereoSep, dest->ori.axis[1], ofsorigin); - + oppleg = xmax + stereoSep; length = sqrt(oppleg * oppleg + zProj * zProj); VectorScale(dest->ori.axis[0], oppleg / length, dest->frustum[0].normal); @@ -933,23 +853,22 @@ void R_SetupFrustum (viewParms_t *dest, float xmin, float xmax, float ymax, floa VectorScale(dest->ori.axis[0], oppleg, dest->frustum[3].normal); VectorMA(dest->frustum[3].normal, -adjleg, dest->ori.axis[2], dest->frustum[3].normal); - - for (i=0 ; i<4 ; i++) { + + for (i = 0; i < 4; i++) { dest->frustum[i].type = PLANE_NON_AXIAL; - dest->frustum[i].dist = DotProduct (ofsorigin, dest->frustum[i].normal); - SetPlaneSignbits( &dest->frustum[i] ); + dest->frustum[i].dist = DotProduct(ofsorigin, dest->frustum[i].normal); + SetPlaneSignbits(&dest->frustum[i]); } - if (zFar != 0.0f) - { + if (zFar != 0.0f) { vec3_t farpoint; VectorMA(ofsorigin, zFar, dest->ori.axis[0], farpoint); VectorScale(dest->ori.axis[0], -1.0f, dest->frustum[4].normal); dest->frustum[4].type = PLANE_NON_AXIAL; - dest->frustum[4].dist = DotProduct (farpoint, dest->frustum[4].normal); - SetPlaneSignbits( &dest->frustum[4] ); + dest->frustum[4].dist = DotProduct(farpoint, dest->frustum[4].normal); + SetPlaneSignbits(&dest->frustum[4]); dest->flags |= VPF_FARPLANEFRUSTUM; } } @@ -959,21 +878,19 @@ void R_SetupFrustum (viewParms_t *dest, float xmin, float xmax, float ymax, floa R_SetupProjection =============== */ -void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean computeFrustum) -{ - float xmin, xmax, ymin, ymax; - float width, height, stereoSep = r_stereoSeparation->value; +void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean computeFrustum) { + float xmin, xmax, ymin, ymax; + float width, height, stereoSep = r_stereoSeparation->value; /* - * offset the view origin of the viewer for stereo rendering + * offset the view origin of the viewer for stereo rendering * by setting the projection matrix appropriately. */ - if(stereoSep != 0) - { - if(dest->stereoFrame == STEREO_LEFT) + if (stereoSep != 0) { + if (dest->stereoFrame == STEREO_LEFT) stereoSep = zProj / stereoSep; - else if(dest->stereoFrame == STEREO_RIGHT) + else if (dest->stereoFrame == STEREO_RIGHT) stereoSep = zProj / -stereoSep; else stereoSep = 0; @@ -987,7 +904,7 @@ void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean comp width = xmax - xmin; height = ymax - ymin; - + dest->projectionMatrix[0] = 2 * zProj / width; dest->projectionMatrix[4] = 0; dest->projectionMatrix[8] = (xmax + xmin + 2 * stereoSep) / width; @@ -995,16 +912,16 @@ void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean comp dest->projectionMatrix[1] = 0; dest->projectionMatrix[5] = 2 * zProj / height; - dest->projectionMatrix[9] = ( ymax + ymin ) / height; // normally 0 + dest->projectionMatrix[9] = (ymax + ymin) / height; // normally 0 dest->projectionMatrix[13] = 0; dest->projectionMatrix[3] = 0; dest->projectionMatrix[7] = 0; dest->projectionMatrix[11] = -1; dest->projectionMatrix[15] = 0; - + // Now that we have all the data for the projection matrix we can also setup the view frustum. - if(computeFrustum) + if (computeFrustum) R_SetupFrustum(dest, xmin, xmax, ymax, zProj, zFar, stereoSep); } @@ -1015,24 +932,22 @@ R_SetupProjectionZ Sets the z-component transformation part in the projection matrix =============== */ -void R_SetupProjectionZ(viewParms_t *dest) -{ +void R_SetupProjectionZ(viewParms_t *dest) { float zNear, zFar, depth; - - zNear = dest->zNear; - zFar = dest->zFar; - depth = zFar - zNear; + zNear = dest->zNear; + zFar = dest->zFar; + + depth = zFar - zNear; dest->projectionMatrix[2] = 0; dest->projectionMatrix[6] = 0; - dest->projectionMatrix[10] = -( zFar + zNear ) / depth; + dest->projectionMatrix[10] = -(zFar + zNear) / depth; dest->projectionMatrix[14] = -2 * zFar * zNear / depth; - if (dest->isPortal) - { - float plane[4]; - float plane2[4]; + if (dest->isPortal) { + float plane[4]; + float plane2[4]; vec4_t q, c; // transform portal plane into camera space @@ -1041,10 +956,10 @@ void R_SetupProjectionZ(viewParms_t *dest) plane[2] = dest->portalPlane.normal[2]; plane[3] = dest->portalPlane.dist; - plane2[0] = -DotProduct (dest->ori.axis[1], plane); - plane2[1] = DotProduct (dest->ori.axis[2], plane); - plane2[2] = -DotProduct (dest->ori.axis[0], plane); - plane2[3] = DotProduct (plane, dest->ori.origin) - plane[3]; + plane2[0] = -DotProduct(dest->ori.axis[1], plane); + plane2[1] = DotProduct(dest->ori.axis[2], plane); + plane2[2] = -DotProduct(dest->ori.axis[0], plane); + plane2[3] = DotProduct(plane, dest->ori.origin) - plane[3]; // Lengyel, Eric. "Modifying the Projection Matrix to Perform Oblique Near-plane Clipping". // Terathon Software 3D Graphics Library, 2004. http://www.terathon.com/code/oblique.html @@ -1055,8 +970,8 @@ void R_SetupProjectionZ(viewParms_t *dest) VectorScale4(plane2, 2.0f / DotProduct4(plane2, q), c); - dest->projectionMatrix[2] = c[0]; - dest->projectionMatrix[6] = c[1]; + dest->projectionMatrix[2] = c[0]; + dest->projectionMatrix[6] = c[1]; dest->projectionMatrix[10] = c[2] + 1.0f; dest->projectionMatrix[14] = c[3]; } @@ -1067,10 +982,9 @@ void R_SetupProjectionZ(viewParms_t *dest) R_SetupProjectionOrtho =============== */ -void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) -{ +void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) { float xmin, xmax, ymin, ymax, znear, zfar; - //viewParms_t *dest = &tr.viewParms; + // viewParms_t *dest = &tr.viewParms; int i; vec3_t pop; @@ -1081,34 +995,34 @@ void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) // |/ |/ // Y--+ +--X - xmin = viewBounds[0][1]; - xmax = viewBounds[1][1]; - ymin = -viewBounds[1][2]; - ymax = -viewBounds[0][2]; - znear = viewBounds[0][0]; - zfar = viewBounds[1][0]; + xmin = viewBounds[0][1]; + xmax = viewBounds[1][1]; + ymin = -viewBounds[1][2]; + ymax = -viewBounds[0][2]; + znear = viewBounds[0][0]; + zfar = viewBounds[1][0]; - dest->projectionMatrix[0] = 2 / (xmax - xmin); - dest->projectionMatrix[4] = 0; - dest->projectionMatrix[8] = 0; + dest->projectionMatrix[0] = 2 / (xmax - xmin); + dest->projectionMatrix[4] = 0; + dest->projectionMatrix[8] = 0; dest->projectionMatrix[12] = (xmax + xmin) / (xmax - xmin); - dest->projectionMatrix[1] = 0; - dest->projectionMatrix[5] = 2 / (ymax - ymin); - dest->projectionMatrix[9] = 0; + dest->projectionMatrix[1] = 0; + dest->projectionMatrix[5] = 2 / (ymax - ymin); + dest->projectionMatrix[9] = 0; dest->projectionMatrix[13] = (ymax + ymin) / (ymax - ymin); - dest->projectionMatrix[2] = 0; - dest->projectionMatrix[6] = 0; + dest->projectionMatrix[2] = 0; + dest->projectionMatrix[6] = 0; dest->projectionMatrix[10] = -2 / (zfar - znear); dest->projectionMatrix[14] = -(zfar + znear) / (zfar - znear); - dest->projectionMatrix[3] = 0; - dest->projectionMatrix[7] = 0; + dest->projectionMatrix[3] = 0; + dest->projectionMatrix[7] = 0; dest->projectionMatrix[11] = 0; dest->projectionMatrix[15] = 1; - VectorScale(dest->ori.axis[1], 1.0f, dest->frustum[0].normal); + VectorScale(dest->ori.axis[1], 1.0f, dest->frustum[0].normal); VectorMA(dest->ori.origin, viewBounds[0][1], dest->frustum[0].normal, pop); dest->frustum[0].dist = DotProduct(pop, dest->frustum[0].normal); @@ -1116,7 +1030,7 @@ void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) VectorMA(dest->ori.origin, -viewBounds[1][1], dest->frustum[1].normal, pop); dest->frustum[1].dist = DotProduct(pop, dest->frustum[1].normal); - VectorScale(dest->ori.axis[2], 1.0f, dest->frustum[2].normal); + VectorScale(dest->ori.axis[2], 1.0f, dest->frustum[2].normal); VectorMA(dest->ori.origin, viewBounds[0][2], dest->frustum[2].normal, pop); dest->frustum[2].dist = DotProduct(pop, dest->frustum[2].normal); @@ -1127,11 +1041,10 @@ void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) VectorScale(dest->ori.axis[0], -1.0f, dest->frustum[4].normal); VectorMA(dest->ori.origin, -viewBounds[1][0], dest->frustum[4].normal, pop); dest->frustum[4].dist = DotProduct(pop, dest->frustum[4].normal); - - for (i = 0; i < 5; i++) - { + + for (i = 0; i < 5; i++) { dest->frustum[i].type = PLANE_NON_AXIAL; - SetPlaneSignbits (&dest->frustum[i]); + SetPlaneSignbits(&dest->frustum[i]); } dest->flags |= VPF_FARPLANEFRUSTUM; @@ -1142,48 +1055,47 @@ void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) R_MirrorPoint ================= */ -void R_MirrorPoint (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - vec3_t local; - vec3_t transformed; - float d; +void R_MirrorPoint(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + vec3_t local; + vec3_t transformed; + float d; - VectorSubtract( in, surface->origin, local ); + VectorSubtract(in, surface->origin, local); - VectorClear( transformed ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(transformed); + for (i = 0; i < 3; i++) { d = DotProduct(local, surface->axis[i]); - VectorMA( transformed, d, camera->axis[i], transformed ); + VectorMA(transformed, d, camera->axis[i], transformed); } - VectorAdd( transformed, camera->origin, out ); + VectorAdd(transformed, camera->origin, out); } -void R_MirrorVector (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - float d; +void R_MirrorVector(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + float d; - VectorClear( out ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(out); + for (i = 0; i < 3; i++) { d = DotProduct(in, surface->axis[i]); - VectorMA( out, d, camera->axis[i], out ); + VectorMA(out, d, camera->axis[i], out); } } - /* ============= R_PlaneForSurface ============= */ -void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { - srfBspSurface_t *tri; - srfPoly_t *poly; - srfVert_t *v1, *v2, *v3; - vec4_t plane4; +void R_PlaneForSurface(surfaceType_t *surfType, cplane_t *plane) { + srfBspSurface_t *tri; + srfPoly_t *poly; + srfVert_t *v1, *v2, *v3; + vec4_t plane4; if (!surfType) { - Com_Memset (plane, 0, sizeof(*plane)); + Com_Memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -1196,18 +1108,18 @@ void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { v1 = tri->verts + tri->indexes[0]; v2 = tri->verts + tri->indexes[1]; v3 = tri->verts + tri->indexes[2]; - PlaneFromPoints( plane4, v1->xyz, v2->xyz, v3->xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, v1->xyz, v2->xyz, v3->xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; case SF_POLY: poly = (srfPoly_t *)surfType; - PlaneFromPoints( plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; default: - Com_Memset (plane, 0, sizeof(*plane)); + Com_Memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -1223,66 +1135,62 @@ be moving and rotating. Returns qtrue if it should be mirrored ================= */ -qboolean R_GetPortalOrientations(const msurface_t *surf, int entityNum, - orientation_t *surface, orientation_t *camera, - vec3_t pvsOrigin, qboolean *mirror ) { - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; - vec3_t transformed; +qboolean R_GetPortalOrientations(const msurface_t *surf, int entityNum, orientation_t *surface, orientation_t *camera, vec3_t pvsOrigin, qboolean *mirror) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; + vec3_t transformed; // create plane axis for the portal we are seeing - R_PlaneForSurface( surf->data, &originalPlane ); + R_PlaneForSurface(surf->data, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) { + if (entityNum != REFENTITYNUM_WORLD) { const trRefEntity_t *currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); } else { plane = originalPlane; } - VectorCopy( plane.normal, surface->axis[0] ); - PerpendicularVector( surface->axis[1], surface->axis[0] ); - CrossProduct( surface->axis[0], surface->axis[1], surface->axis[2] ); + VectorCopy(plane.normal, surface->axis[0]); + PerpendicularVector(surface->axis[1], surface->axis[0]); + CrossProduct(surface->axis[0], surface->axis[1], surface->axis[2]); // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // get the pvsOrigin from the entity - VectorCopy( e->e.oldorigin, pvsOrigin ); + VectorCopy(e->e.oldorigin, pvsOrigin); // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) { - VectorScale( plane.normal, plane.dist, surface->origin ); - VectorCopy( surface->origin, camera->origin ); - VectorSubtract( vec3_origin, surface->axis[0], camera->axis[0] ); - VectorCopy( surface->axis[1], camera->axis[1] ); - VectorCopy( surface->axis[2], camera->axis[2] ); + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { + VectorScale(plane.normal, plane.dist, surface->origin); + VectorCopy(surface->origin, camera->origin); + VectorSubtract(vec3_origin, surface->axis[0], camera->axis[0]); + VectorCopy(surface->axis[1], camera->axis[1]); + VectorCopy(surface->axis[2], camera->axis[2]); *mirror = qtrue; return qtrue; @@ -1290,38 +1198,37 @@ qboolean R_GetPortalOrientations(const msurface_t *surf, int entityNum, // project the origin onto the surface plane to get // an origin point we can rotate around - d = DotProduct( e->e.origin, plane.normal ) - plane.dist; - VectorMA( e->e.origin, -d, surface->axis[0], surface->origin ); - + d = DotProduct(e->e.origin, plane.normal) - plane.dist; + VectorMA(e->e.origin, -d, surface->axis[0], surface->origin); + // now get the camera origin and orientation - VectorCopy( e->e.oldorigin, camera->origin ); - AxisCopy( e->e.axis, camera->axis ); - VectorSubtract( vec3_origin, camera->axis[0], camera->axis[0] ); - VectorSubtract( vec3_origin, camera->axis[1], camera->axis[1] ); + VectorCopy(e->e.oldorigin, camera->origin); + AxisCopy(e->e.axis, camera->axis); + VectorSubtract(vec3_origin, camera->axis[0], camera->axis[0]); + VectorSubtract(vec3_origin, camera->axis[1], camera->axis[1]); // optionally rotate - if ( e->e.oldframe ) { + if (e->e.oldframe) { // if a speed is specified - if ( e->e.frame ) { + if (e->e.frame) { // continuous rotate - d = (tr.refdef.time/1000.0f) * e->e.frame; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + d = (tr.refdef.time / 1000.0f) * e->e.frame; + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } else { // bobbing rotate, with skinNum being the rotation offset - d = sin( tr.refdef.time * 0.003f ); + d = sin(tr.refdef.time * 0.003f); d = e->e.skinNum + d * 4; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } - } - else if ( e->e.skinNum ) { + } else if (e->e.skinNum) { d = e->e.skinNum; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } *mirror = qfalse; return qtrue; @@ -1336,58 +1243,52 @@ qboolean R_GetPortalOrientations(const msurface_t *surf, int entityNum, // to see a surface before the server has communicated the matching // portal surface entity, so we don't want to print anything here... - //ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); + // ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); return qfalse; } -static qboolean IsMirror( const msurface_t *surface, int entityNum ) -{ - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; +static qboolean IsMirror(const msurface_t *surface, int entityNum) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; // create plane axis for the portal we are seeing - R_PlaneForSurface( surface->data, &originalPlane ); + R_PlaneForSurface(surface->data, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) - { + if (entityNum != REFENTITYNUM_WORLD) { const trRefEntity_t *currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); - } + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); + } // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) - { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) - { + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { return qtrue; } @@ -1401,7 +1302,7 @@ static qboolean IsMirror( const msurface_t *surface, int entityNum ) ** ** Determines if a surface is completely offscreen. */ -static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_t clipDest[128], int *numVertices ) { +static qboolean SurfIsOffscreen(const msurface_t *surface, int entityNum, vec4_t clipDest[128], int *numVertices) { float shortest = 100000000; int numTriangles; vec4_t clip, eye; @@ -1410,13 +1311,12 @@ static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_ unsigned int pointAnd = (unsigned int)~0; // TODO: Check if set properly here already - //R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + // R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); - RB_BeginSurface(surface->shader, 0, 0 ); - rb_surfaceTable[ *surface->data ](surface->data); + RB_BeginSurface(surface->shader, 0, 0); + rb_surfaceTable[*surface->data](surface->data); - if ( tess.numVertexes > 128 ) - { + if (tess.numVertexes > 128) { // Don't bother trying, just assume it's off-screen and make it look bad. Besides, artists // shouldn't be using this many vertices on a mirror surface anyway :) return qtrue; @@ -1424,23 +1324,18 @@ static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_ *numVertices = tess.numVertexes; - for ( i = 0; i < tess.numVertexes; i++ ) - { + for (i = 0; i < tess.numVertexes; i++) { int j; unsigned int pointFlags = 0; - R_TransformModelToClip( tess.xyz[i], tr.viewParms.world.modelViewMatrix, tr.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(tess.xyz[i], tr.viewParms.world.modelViewMatrix, tr.viewParms.projectionMatrix, eye, clip); VectorCopy4(clip, clipDest[i]); - for ( j = 0; j < 3; j++ ) - { - if ( clip[j] >= clip[3] ) - { - pointFlags |= (1 << (j*2)); - } - else if ( clip[j] <= -clip[3] ) - { - pointFlags |= ( 1 << (j*2+1)); + for (j = 0; j < 3; j++) { + if (clip[j] >= clip[3]) { + pointFlags |= (1 << (j * 2)); + } else if (clip[j] <= -clip[3]) { + pointFlags |= (1 << (j * 2 + 1)); } } pointAnd &= pointFlags; @@ -1448,8 +1343,7 @@ static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_ } // trivially reject - if ( pointAnd ) - { + if (pointAnd) { return qtrue; } @@ -1460,41 +1354,35 @@ static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_ // we have in the game right now. numTriangles = tess.numIndexes / 3; - for ( i = 0; i < tess.numIndexes; i += 3 ) - { + for (i = 0; i < tess.numIndexes; i += 3) { vec3_t normal, tNormal; float len; - VectorSubtract( tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal ); + VectorSubtract(tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal); - len = VectorLengthSquared( normal ); // lose the sqrt - if ( len < shortest ) - { + len = VectorLengthSquared(normal); // lose the sqrt + if (len < shortest) { shortest = len; } R_VboUnpackNormal(tNormal, tess.normal[tess.indexes[i]]); - if ( DotProduct( normal, tNormal ) >= 0 ) - { + if (DotProduct(normal, tNormal) >= 0) { numTriangles--; } } - if ( !numTriangles ) - { + if (!numTriangles) { return qtrue; } // mirrors can early out at this point, since we don't do a fade over distance // with them (although we could) - if ( IsMirror( surface, entityNum) ) - { + if (IsMirror(surface, entityNum)) { return qfalse; } - if ( shortest > (tess.shader->portalRange*tess.shader->portalRange) ) - { + if (shortest > (tess.shader->portalRange * tess.shader->portalRange)) { return qtrue; } @@ -1508,25 +1396,25 @@ R_MirrorViewBySurface Returns qtrue if another view has been rendered ======================== */ -qboolean R_MirrorViewBySurface (msurface_t *surface, int entityNum) { - vec4_t clipDest[128]; - int numVertices; - viewParms_t newParms; - viewParms_t oldParms; - orientation_t surfaceOri, camera; +qboolean R_MirrorViewBySurface(msurface_t *surface, int entityNum) { + vec4_t clipDest[128]; + int numVertices; + viewParms_t newParms; + viewParms_t oldParms; + orientation_t surfaceOri, camera; // don't recursively mirror if (tr.viewParms.isPortal) { - ri.Printf( PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n" ); + ri.Printf(PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n"); return qfalse; } - if ( r_noportals->integer || (r_fastsky->integer == 1) ) { + if (r_noportals->integer || (r_fastsky->integer == 1)) { return qfalse; } // trivially reject portal/mirror - if ( SurfIsOffscreen(surface, entityNum, clipDest, &numVertices ) ) { + if (SurfIsOffscreen(surface, entityNum, clipDest, &numVertices)) { return qfalse; } @@ -1538,9 +1426,8 @@ qboolean R_MirrorViewBySurface (msurface_t *surface, int entityNum) { newParms.zFar = 0.0f; newParms.zNear = r_znear->value; newParms.flags &= ~VPF_FARPLANEFRUSTUM; - if ( !R_GetPortalOrientations(surface, entityNum, &surfaceOri, &camera, - newParms.pvsOrigin, &newParms.isMirror ) ) { - return qfalse; // bad portal, no portalentity + if (!R_GetPortalOrientations(surface, entityNum, &surfaceOri, &camera, newParms.pvsOrigin, &newParms.isMirror)) { + return qfalse; // bad portal, no portalentity } if (newParms.isMirror) @@ -1607,14 +1494,14 @@ qboolean R_MirrorViewBySurface (msurface_t *surface, int entityNum) { newParms.scissorWidth = maxRectX - minRectX; newParms.scissorHeight = maxRectY - minRectY;*/ - R_MirrorPoint (oldParms.ori.origin, &surfaceOri, &camera, newParms.ori.origin ); + R_MirrorPoint(oldParms.ori.origin, &surfaceOri, &camera, newParms.ori.origin); - VectorSubtract( vec3_origin, camera.axis[0], newParms.portalPlane.normal ); - newParms.portalPlane.dist = DotProduct( camera.origin, newParms.portalPlane.normal ); - - R_MirrorVector (oldParms.ori.axis[0], &surfaceOri, &camera, newParms.ori.axis[0]); - R_MirrorVector (oldParms.ori.axis[1], &surfaceOri, &camera, newParms.ori.axis[1]); - R_MirrorVector (oldParms.ori.axis[2], &surfaceOri, &camera, newParms.ori.axis[2]); + VectorSubtract(vec3_origin, camera.axis[0], newParms.portalPlane.normal); + newParms.portalPlane.dist = DotProduct(camera.origin, newParms.portalPlane.normal); + + R_MirrorVector(oldParms.ori.axis[0], &surfaceOri, &camera, newParms.ori.axis[0]); + R_MirrorVector(oldParms.ori.axis[1], &surfaceOri, &camera, newParms.ori.axis[1]); + R_MirrorVector(oldParms.ori.axis[2], &surfaceOri, &camera, newParms.ori.axis[2]); // OPTIMIZE further: restrict the viewport and set up the view and projection // matrices so they only draw into the tightest screen-space aligned box required @@ -1651,25 +1538,25 @@ R_SpriteFogNum See if a sprite is inside a fog volume ================= */ -int R_SpriteFogNum( trRefEntity_t *ent ) { - int i, j; - fog_t *fog; +int R_SpriteFogNum(trRefEntity_t *ent) { + int i, j; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j]) { break; } - if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + if (ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -1690,27 +1577,26 @@ DRAWSURF SORTING R_Radix =============== */ -static QINLINE void R_Radix( int byte, int size, drawSurf_t *source, drawSurf_t *dest ) -{ - int count[ 256 ] = { 0 }; - int index[ 256 ]; - int i; - unsigned char *sortKey = NULL; - unsigned char *end = NULL; - - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - end = sortKey + ( size * sizeof( drawSurf_t ) ); - for( ; sortKey < end; sortKey += sizeof( drawSurf_t ) ) - ++count[ *sortKey ]; - - index[ 0 ] = 0; - - for( i = 1; i < 256; ++i ) - index[ i ] = index[ i - 1 ] + count[ i - 1 ]; - - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - for( i = 0; i < size; ++i, sortKey += sizeof( drawSurf_t ) ) - dest[ index[ *sortKey ]++ ] = source[ i ]; +static QINLINE void R_Radix(int byte, int size, drawSurf_t *source, drawSurf_t *dest) { + int count[256] = {0}; + int index[256]; + int i; + unsigned char *sortKey = NULL; + unsigned char *end = NULL; + + sortKey = ((unsigned char *)&source[0].sort) + byte; + end = sortKey + (size * sizeof(drawSurf_t)); + for (; sortKey < end; sortKey += sizeof(drawSurf_t)) + ++count[*sortKey]; + + index[0] = 0; + + for (i = 1; i < 256; ++i) + index[i] = index[i - 1] + count[i - 1]; + + sortKey = ((unsigned char *)&source[0].sort) + byte; + for (i = 0; i < size; ++i, sortKey += sizeof(drawSurf_t)) + dest[index[*sortKey]++] = source[i]; } /* @@ -1720,29 +1606,25 @@ R_RadixSort Radix sort with 4 byte size buckets =============== */ -static void R_RadixSort( drawSurf_t *source, int size ) -{ - static drawSurf_t scratch[ MAX_DRAWSURFS ]; +static void R_RadixSort(drawSurf_t *source, int size) { + static drawSurf_t scratch[MAX_DRAWSURFS]; #ifdef Q3_LITTLE_ENDIAN - R_Radix( 0, size, source, scratch ); - R_Radix( 1, size, scratch, source ); - R_Radix( 2, size, source, scratch ); - R_Radix( 3, size, scratch, source ); + R_Radix(0, size, source, scratch); + R_Radix(1, size, scratch, source); + R_Radix(2, size, source, scratch); + R_Radix(3, size, scratch, source); #else - R_Radix( 3, size, source, scratch ); - R_Radix( 2, size, scratch, source ); - R_Radix( 1, size, source, scratch ); - R_Radix( 0, size, scratch, source ); -#endif //Q3_LITTLE_ENDIAN + R_Radix(3, size, source, scratch); + R_Radix(2, size, scratch, source); + R_Radix(1, size, source, scratch); + R_Radix(0, size, scratch, source); +#endif // Q3_LITTLE_ENDIAN } //========================================================================================== -bool R_IsPostRenderEntity ( const trRefEntity_t *refEntity ) -{ - return (refEntity->e.renderfx & RF_DISTORTION) || - (refEntity->e.renderfx & RF_FORCEPOST) || - (refEntity->e.renderfx & RF_FORCE_ENT_ALPHA); +bool R_IsPostRenderEntity(const trRefEntity_t *refEntity) { + return (refEntity->e.renderfx & RF_DISTORTION) || (refEntity->e.renderfx & RF_FORCEPOST) || (refEntity->e.renderfx & RF_FORCE_ENT_ALPHA); } /* @@ -1750,16 +1632,14 @@ bool R_IsPostRenderEntity ( const trRefEntity_t *refEntity ) R_DecomposeSort ================= */ -void R_DecomposeSort( uint32_t sort, int *entityNum, shader_t **shader, int *cubemap, int *postRender ) -{ - *shader = tr.sortedShaders[ ( sort >> QSORT_SHADERNUM_SHIFT ) & QSORT_SHADERNUM_MASK ]; - *postRender = (sort >> QSORT_POSTRENDER_SHIFT ) & QSORT_POSTRENDER_MASK; +void R_DecomposeSort(uint32_t sort, int *entityNum, shader_t **shader, int *cubemap, int *postRender) { + *shader = tr.sortedShaders[(sort >> QSORT_SHADERNUM_SHIFT) & QSORT_SHADERNUM_MASK]; + *postRender = (sort >> QSORT_POSTRENDER_SHIFT) & QSORT_POSTRENDER_MASK; *entityNum = (sort >> QSORT_ENTITYNUM_SHIFT) & QSORT_ENTITYNUM_MASK; - *cubemap = (sort >> QSORT_CUBEMAP_SHIFT ) & QSORT_CUBEMAP_MASK; + *cubemap = (sort >> QSORT_CUBEMAP_SHIFT) & QSORT_CUBEMAP_MASK; } -uint32_t R_CreateSortKey(int entityNum, int sortedShaderIndex, int cubemapIndex, int postRender) -{ +uint32_t R_CreateSortKey(int entityNum, int sortedShaderIndex, int cubemapIndex, int postRender) { uint32_t key = 0; key |= (sortedShaderIndex & QSORT_SHADERNUM_MASK) << QSORT_SHADERNUM_SHIFT; @@ -1775,31 +1655,20 @@ uint32_t R_CreateSortKey(int entityNum, int sortedShaderIndex, int cubemapIndex, R_AddDrawSurf ================= */ -void R_AddDrawSurf( - surfaceType_t *surface, - int entityNum, - shader_t *shader, - int fogIndex, - int dlightMap, - int postRender, - int cubemap) -{ +void R_AddDrawSurf(surfaceType_t *surface, int entityNum, shader_t *shader, int fogIndex, int dlightMap, int postRender, int cubemap) { int index; drawSurf_t *surf; - if (tr.refdef.rdflags & RDF_NOFOG) - { + if (tr.refdef.rdflags & RDF_NOFOG) { fogIndex = 0; } - if ( (shader->surfaceFlags & SURF_FORCESIGHT) && !(tr.refdef.rdflags & RDF_ForceSightOn) ) - { //if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw + if ((shader->surfaceFlags & SURF_FORCESIGHT) && + !(tr.refdef.rdflags & RDF_ForceSightOn)) { // if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw return; } - if (tr.viewParms.flags & VPF_DEPTHSHADOW && - (postRender == qtrue || shader->sort != SS_OPAQUE)) - { + if (tr.viewParms.flags & VPF_DEPTHSHADOW && (postRender == qtrue || shader->sort != SS_OPAQUE)) { return; } @@ -1809,20 +1678,16 @@ void R_AddDrawSurf( surf = tr.refdef.drawSurfs + index; surf->surface = surface; - if (tr.viewParms.flags & VPF_DEPTHSHADOW && - shader->useSimpleDepthShader == qtrue) - { + if (tr.viewParms.flags & VPF_DEPTHSHADOW && shader->useSimpleDepthShader == qtrue) { surf->sort = R_CreateSortKey(entityNum, tr.defaultShader->sortedIndex, 0, 0); surf->dlightBits = 0; surf->fogIndex = 0; - } - else - { + } else { surf->sort = R_CreateSortKey(entityNum, shader->sortedIndex, cubemap, postRender); surf->dlightBits = dlightMap; surf->fogIndex = fogIndex; } - + tr.refdef.numDrawSurfs++; } @@ -1831,7 +1696,7 @@ void R_AddDrawSurf( R_SortAndSubmitDrawSurfs ================= */ -void R_SortAndSubmitDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { +void R_SortAndSubmitDrawSurfs(drawSurf_t *drawSurfs, int numDrawSurfs) { // it is possible for some views to not have any surfaces if (numDrawSurfs < 1) return; @@ -1839,33 +1704,32 @@ void R_SortAndSubmitDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { // if we overflowed MAX_DRAWSURFS, the drawsurfs // wrapped around in the buffer and we will be missing // the first surfaces, not the last ones - if ( numDrawSurfs > MAX_DRAWSURFS ) - numDrawSurfs = MAX_DRAWSURFS; + if (numDrawSurfs > MAX_DRAWSURFS) + numDrawSurfs = MAX_DRAWSURFS; - R_RadixSort( drawSurfs, numDrawSurfs ); + R_RadixSort(drawSurfs, numDrawSurfs); - R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); + R_AddDrawSurfCmd(drawSurfs, numDrawSurfs); } -static void R_AddEntitySurface(const trRefdef_t *refdef, trRefEntity_t *ent, int entityNum) -{ - shader_t *shader; +static void R_AddEntitySurface(const trRefdef_t *refdef, trRefEntity_t *ent, int entityNum) { + shader_t *shader; ent->needDlights = qfalse; // // the weapon model must be handled special -- - // we don't want the hacked weapon position showing in + // we don't want the hacked weapon position showing in // mirrors, because the true body position will already be drawn // - if ( (ent->e.renderfx & RF_FIRST_PERSON) && (tr.viewParms.flags & VPF_NOVIEWMODEL)) { + if ((ent->e.renderfx & RF_FIRST_PERSON) && (tr.viewParms.flags & VPF_NOVIEWMODEL)) { return; } // simple generated models, like sprites and beams, are not culled - switch ( ent->e.reType ) { + switch (ent->e.reType) { case RT_PORTALSURFACE: - break; // don't draw anything + break; // don't draw anything case RT_SPRITE: case RT_BEAM: case RT_ORIENTED_QUAD: @@ -1877,94 +1741,64 @@ static void R_AddEntitySurface(const trRefdef_t *refdef, trRefEntity_t *ent, int // self blood sprites, talk balloons, etc should not be drawn in the primary // view. We can't just do this check for all entities, because md3 // entities may still want to cast shadows from them - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { return; } - shader = R_GetShaderByHandle( ent->e.customShader ); - R_AddDrawSurf( - &entitySurface, - entityNum, - shader, - R_SpriteFogNum(ent), - 0, - R_IsPostRenderEntity(ent), - 0 /* cubeMap */ ); + shader = R_GetShaderByHandle(ent->e.customShader); + R_AddDrawSurf(&entitySurface, entityNum, shader, R_SpriteFogNum(ent), 0, R_IsPostRenderEntity(ent), 0 /* cubeMap */); break; case RT_MODEL: // we must set up parts of tr.ori for model culling - R_RotateForEntity( ent, &tr.viewParms, &tr.ori ); + R_RotateForEntity(ent, &tr.viewParms, &tr.ori); - tr.currentModel = R_GetModelByHandle( ent->e.hModel ); + tr.currentModel = R_GetModelByHandle(ent->e.hModel); if (!tr.currentModel) { - R_AddDrawSurf( - &entitySurface, - entityNum, - tr.defaultShader, - 0, - 0, - R_IsPostRenderEntity(ent), - 0/* cubeMap */ ); + R_AddDrawSurf(&entitySurface, entityNum, tr.defaultShader, 0, 0, R_IsPostRenderEntity(ent), 0 /* cubeMap */); } else { - switch ( tr.currentModel->type ) { + switch (tr.currentModel->type) { case MOD_MESH: - R_AddMD3Surfaces( ent, entityNum ); + R_AddMD3Surfaces(ent, entityNum); break; case MOD_MDR: - R_MDRAddAnimSurfaces( ent, entityNum ); + R_MDRAddAnimSurfaces(ent, entityNum); break; case MOD_IQM: - R_AddIQMSurfaces( ent, entityNum ); + R_AddIQMSurfaces(ent, entityNum); break; case MOD_BRUSH: - R_AddBrushModelSurfaces( ent, entityNum ); + R_AddBrushModelSurfaces(ent, entityNum); break; case MOD_MDXM: if (ent->e.ghoul2) R_AddGhoulSurfaces(ent, entityNum); break; - case MOD_BAD: // null model axis - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal ) { + case MOD_BAD: // null model axis + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { break; } - if ( ent->e.ghoul2 && - G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2)) ) - { + if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) { R_AddGhoulSurfaces(ent, entityNum); break; } - // FIX ME: always draw null axis model instead of rejecting the drawcall + // FIX ME: always draw null axis model instead of rejecting the drawcall if (tr.currentModel->dataSize > 0) - R_AddDrawSurf( - &entitySurface, - entityNum, - tr.defaultShader, - 0, - 0, - R_IsPostRenderEntity(ent), - 0 /* cubeMap */ ); + R_AddDrawSurf(&entitySurface, entityNum, tr.defaultShader, 0, 0, R_IsPostRenderEntity(ent), 0 /* cubeMap */); break; default: - ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad modeltype" ); + ri.Error(ERR_DROP, "R_AddEntitySurfaces: Bad modeltype"); break; } } break; case RT_ENT_CHAIN: shader = R_GetShaderByHandle(ent->e.customShader); - R_AddDrawSurf( - &entitySurface, - entityNum, - shader, - R_SpriteFogNum(ent), - false, - R_IsPostRenderEntity(ent), - 0 /* cubeMap */ ); + R_AddDrawSurf(&entitySurface, entityNum, shader, R_SpriteFogNum(ent), false, R_IsPostRenderEntity(ent), 0 /* cubeMap */); break; default: - ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad reType" ); + ri.Error(ERR_DROP, "R_AddEntitySurfaces: Bad reType"); } } @@ -1973,47 +1807,38 @@ static void R_AddEntitySurface(const trRefdef_t *refdef, trRefEntity_t *ent, int R_AddEntitySurfaces ============= */ -static void R_AddEntitySurfaces(const trRefdef_t *refdef) -{ - if ( !r_drawentities->integer ) - { +static void R_AddEntitySurfaces(const trRefdef_t *refdef) { + if (!r_drawentities->integer) { return; } int entityStart = 0; int numEntities = refdef->num_entities; - if (tr.world && tr.world->skyboxportal) - { - if (tr.viewParms.isSkyPortal) - { + if (tr.world && tr.world->skyboxportal) { + if (tr.viewParms.isSkyPortal) { // Stop after skyportal entities numEntities = tr.skyPortalEntities; - } - else - { + } else { // Skip skyportal entities entityStart = tr.skyPortalEntities; } } - for (int i = entityStart; i < numEntities; i++) - { + for (int i = entityStart; i < numEntities; i++) { trRefEntity_t *ent = refdef->entities + i; R_AddEntitySurface(refdef, ent, i); } } - /* ==================== R_GenerateDrawSurfs ==================== */ -void R_GenerateDrawSurfs( viewParms_t *viewParms, trRefdef_t *refdef ) { +void R_GenerateDrawSurfs(viewParms_t *viewParms, trRefdef_t *refdef) { // TODO: Get rid of this - if (viewParms->viewParmType == VPT_PLAYER_SHADOWS) - { + if (viewParms->viewParmType == VPT_PLAYER_SHADOWS) { int entityNum = viewParms->targetFboLayer; trRefEntity_t *ent = refdef->entities + entityNum; R_AddEntitySurface(refdef, ent, entityNum); @@ -2026,8 +1851,7 @@ void R_GenerateDrawSurfs( viewParms_t *viewParms, trRefdef_t *refdef ) { R_AddPolygonSurfaces(refdef); - if ( tr.viewParms.viewParmType > VPT_POINT_SHADOWS && tr.world ) - { + if (tr.viewParms.viewParmType > VPT_POINT_SHADOWS && tr.world) { R_AddWeatherSurfaces(); } } @@ -2037,7 +1861,7 @@ void R_GenerateDrawSurfs( viewParms_t *viewParms, trRefdef_t *refdef ) { R_DebugPolygon ================ */ -void R_DebugPolygon( int color, int numPoints, float *points ) { +void R_DebugPolygon(int color, int numPoints, float *points) { // FIXME: implement this #if 0 int i; @@ -2073,19 +1897,18 @@ R_DebugGraphics Visualization aid for movement clipping debugging ==================== */ -void R_DebugGraphics( void ) { - if ( !r_debugSurface->integer ) { +void R_DebugGraphics(void) { + if (!r_debugSurface->integer) { return; } R_IssuePendingRenderCommands(); - GL_Bind( tr.whiteImage); - GL_Cull( CT_FRONT_SIDED ); - ri.CM_DrawDebugSurface( R_DebugPolygon ); + GL_Bind(tr.whiteImage); + GL_Cull(CT_FRONT_SIDED); + ri.CM_DrawDebugSurface(R_DebugPolygon); } - /* ================ R_RenderView @@ -2094,9 +1917,9 @@ A view may be either the actual camera view, or a mirror / remote location ================ */ -void R_RenderView (viewParms_t *parms) { +void R_RenderView(viewParms_t *parms) { - if ( parms->viewportWidth <= 0 || parms->viewportHeight <= 0 ) { + if (parms->viewportWidth <= 0 || parms->viewportHeight <= 0) { return; } @@ -2110,23 +1933,20 @@ void R_RenderView (viewParms_t *parms) { R_GenerateDrawSurfs(&tr.viewParms, &tr.refdef); - R_SortAndSubmitDrawSurfs( tr.refdef.drawSurfs + tr.refdef.fistDrawSurf, tr.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); + R_SortAndSubmitDrawSurfs(tr.refdef.drawSurfs + tr.refdef.fistDrawSurf, tr.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); // draw main system development information (surface outlines, etc) R_DebugGraphics(); } - -void R_RenderDlightCubemaps(const refdef_t *fd) -{ +void R_RenderDlightCubemaps(const refdef_t *fd) { int i; - for (i = 0; i < tr.refdef.num_dlights; i++) - { - viewParms_t shadowParms; + for (i = 0; i < tr.refdef.num_dlights; i++) { + viewParms_t shadowParms; int j; - Com_Memset( &shadowParms, 0, sizeof( shadowParms ) ); + Com_Memset(&shadowParms, 0, sizeof(shadowParms)); shadowParms.viewportX = 0; shadowParms.viewportY = 0; @@ -2142,51 +1962,49 @@ void R_RenderDlightCubemaps(const refdef_t *fd) shadowParms.zFar = tr.refdef.dlights[i].radius; shadowParms.zNear = 1.0f; - VectorCopy( tr.refdef.dlights[i].origin, shadowParms.ori.origin ); + VectorCopy(tr.refdef.dlights[i].origin, shadowParms.ori.origin); - for (j = 0; j < 6; j++) - { - switch(j) - { - case 0: - // -X - VectorSet( shadowParms.ori.axis[0], -1, 0, 0); - VectorSet( shadowParms.ori.axis[1], 0, 0, -1); - VectorSet( shadowParms.ori.axis[2], 0, 1, 0); - break; - case 1: - // +X - VectorSet( shadowParms.ori.axis[0], 1, 0, 0); - VectorSet( shadowParms.ori.axis[1], 0, 0, 1); - VectorSet( shadowParms.ori.axis[2], 0, 1, 0); - break; - case 2: - // -Y - VectorSet( shadowParms.ori.axis[0], 0, -1, 0); - VectorSet( shadowParms.ori.axis[1], 1, 0, 0); - VectorSet( shadowParms.ori.axis[2], 0, 0, -1); - break; - case 3: - // +Y - VectorSet( shadowParms.ori.axis[0], 0, 1, 0); - VectorSet( shadowParms.ori.axis[1], 1, 0, 0); - VectorSet( shadowParms.ori.axis[2], 0, 0, 1); - break; - case 4: - // -Z - VectorSet( shadowParms.ori.axis[0], 0, 0, -1); - VectorSet( shadowParms.ori.axis[1], 1, 0, 0); - VectorSet( shadowParms.ori.axis[2], 0, 1, 0); - break; - case 5: - // +Z - VectorSet( shadowParms.ori.axis[0], 0, 0, 1); - VectorSet( shadowParms.ori.axis[1], -1, 0, 0); - VectorSet( shadowParms.ori.axis[2], 0, 1, 0); - break; + for (j = 0; j < 6; j++) { + switch (j) { + case 0: + // -X + VectorSet(shadowParms.ori.axis[0], -1, 0, 0); + VectorSet(shadowParms.ori.axis[1], 0, 0, -1); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 1: + // +X + VectorSet(shadowParms.ori.axis[0], 1, 0, 0); + VectorSet(shadowParms.ori.axis[1], 0, 0, 1); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 2: + // -Y + VectorSet(shadowParms.ori.axis[0], 0, -1, 0); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 0, -1); + break; + case 3: + // +Y + VectorSet(shadowParms.ori.axis[0], 0, 1, 0); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 0, 1); + break; + case 4: + // -Z + VectorSet(shadowParms.ori.axis[0], 0, 0, -1); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 5: + // +Z + VectorSet(shadowParms.ori.axis[0], 0, 0, 1); + VectorSet(shadowParms.ori.axis[1], -1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; } - shadowParms.targetFbo = tr.shadowCubeFbo[i*6+j]; + shadowParms.targetFbo = tr.shadowCubeFbo[i * 6 + j]; shadowParms.targetFboLayer = 0; R_RenderView(&shadowParms); @@ -2198,39 +2016,23 @@ void R_RenderDlightCubemaps(const refdef_t *fd) } } -void R_SetOrientationOriginAndAxis( - orientationr_t& orientation, - const vec3_t origin, - const vec3_t forward, - const vec3_t left, - const vec3_t up) -{ +void R_SetOrientationOriginAndAxis(orientationr_t &orientation, const vec3_t origin, const vec3_t forward, const vec3_t left, const vec3_t up) { VectorCopy(origin, orientation.origin); VectorCopy(forward, orientation.axis[0]); VectorCopy(left, orientation.axis[1]); VectorCopy(up, orientation.axis[2]); } -void R_SetOrientationOriginAndAxis( - orientationr_t& orientation, - const vec3_t origin, - const matrix3_t axis) -{ +void R_SetOrientationOriginAndAxis(orientationr_t &orientation, const vec3_t origin, const matrix3_t axis) { R_SetOrientationOriginAndAxis(orientation, origin, axis[0], axis[1], axis[2]); } -void R_SetupViewParmsForOrthoRendering( - int viewportWidth, - int viewportHeight, - FBO_t *fbo, - viewParmFlags_t viewParmFlags, - const orientationr_t& orientation, - const vec3_t viewBounds[2]) -{ - viewParms_t& viewParms = tr.viewParms; +void R_SetupViewParmsForOrthoRendering(int viewportWidth, int viewportHeight, FBO_t *fbo, viewParmFlags_t viewParmFlags, const orientationr_t &orientation, + const vec3_t viewBounds[2]) { + viewParms_t &viewParms = tr.viewParms; viewParms = {}; - viewParms.viewportWidth = viewportWidth; + viewParms.viewportWidth = viewportWidth; viewParms.viewportHeight = viewportHeight; viewParms.flags = viewParmFlags; viewParms.targetFbo = fbo; @@ -2250,25 +2052,22 @@ void R_SetupViewParmsForOrthoRendering( R_SetupProjectionOrtho(&viewParms, viewBounds); } -void R_SetupPshadowMaps(trRefdef_t *refdef) -{ - viewParms_t shadowParms; +void R_SetupPshadowMaps(trRefdef_t *refdef) { + viewParms_t shadowParms; int i; // first, make a list of shadows - for ( i = 0; i < refdef->num_entities; i++) - { + for (i = 0; i < refdef->num_entities; i++) { trRefEntity_t *ent = &refdef->entities[i]; - if((ent->e.renderfx & (RF_FIRST_PERSON | RF_NOSHADOW))) + if ((ent->e.renderfx & (RF_FIRST_PERSON | RF_NOSHADOW))) continue; - //if((ent->e.renderfx & RF_THIRD_PERSON)) - //continue; + // if((ent->e.renderfx & RF_THIRD_PERSON)) + // continue; - if (ent->e.reType == RT_MODEL) - { - model_t *model = R_GetModelByHandle( ent->e.hModel ); + if (ent->e.reType == RT_MODEL) { + model_t *model = R_GetModelByHandle(ent->e.hModel); pshadow_t shadow; float radius = 0.0f; float scale = 1.0f; @@ -2278,33 +2077,28 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) if (!model) continue; - if (ent->e.nonNormalizedAxes) - { - scale = VectorLength( ent->e.axis[0] ); + if (ent->e.nonNormalizedAxes) { + scale = VectorLength(ent->e.axis[0]); } - switch (model->type) - { - case MOD_MDXM: - case MOD_BAD: - { - if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) - { - // scale the radius if needed - float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - largestScale = ent->e.modelScale[1]; - if (ent->e.modelScale[2] > largestScale) - largestScale = ent->e.modelScale[2]; - if (!largestScale) - largestScale = 1; - radius = ent->e.radius * largestScale * 1.2; - } + switch (model->type) { + case MOD_MDXM: + case MOD_BAD: { + if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) { + // scale the radius if needed + float largestScale = ent->e.modelScale[0]; + if (ent->e.modelScale[1] > largestScale) + largestScale = ent->e.modelScale[1]; + if (ent->e.modelScale[2] > largestScale) + largestScale = ent->e.modelScale[2]; + if (!largestScale) + largestScale = 1; + radius = ent->e.radius * largestScale * 1.2; } - break; + } break; - default: - break; + default: + break; } if (!radius) @@ -2326,12 +2120,10 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) VectorCopy(ent->e.origin, shadow.entityOrigins[0]); shadow.entityRadiuses[0] = radius; - for (j = 0; j < MAX_CALC_PSHADOWS; j++) - { + for (j = 0; j < MAX_CALC_PSHADOWS; j++) { pshadow_t swap; - if (j + 1 > refdef->num_pshadows) - { + if (j + 1 > refdef->num_pshadows) { refdef->num_pshadows = j + 1; refdef->pshadows[j] = shadow; break; @@ -2350,14 +2142,12 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) } // cap number of drawn pshadows - if (refdef->num_pshadows > MAX_DRAWN_PSHADOWS) - { + if (refdef->num_pshadows > MAX_DRAWN_PSHADOWS) { refdef->num_pshadows = MAX_DRAWN_PSHADOWS; } // next, fill up the rest of the shadow info - for ( i = 0; i < refdef->num_pshadows; i++) - { + for (i = 0; i < refdef->num_pshadows; i++) { pshadow_t *shadow = &refdef->pshadows[i]; vec3_t up; vec3_t ambientLight, directedLight, lightDir; @@ -2375,8 +2165,7 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) if (DotProduct(lightDir, lightDir) < 0.9f) VectorSet(lightDir, 0.0f, 0.0f, 1.0f); #endif - if (shadow->viewRadius * 3.0f > shadow->lightRadius) - { + if (shadow->viewRadius * 3.0f > shadow->lightRadius) { shadow->lightRadius = shadow->viewRadius * 3.0f; } @@ -2386,8 +2175,7 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) VectorScale(lightDir, -1.0f, shadow->lightViewAxis[0]); VectorSet(up, 0, 0, -1); - if ( fabs(DotProduct(up, shadow->lightViewAxis[0])) > 0.9f ) - { + if (fabs(DotProduct(up, shadow->lightViewAxis[0])) > 0.9f) { VectorSet(up, -1, 0, 0); } @@ -2402,8 +2190,7 @@ void R_SetupPshadowMaps(trRefdef_t *refdef) } } -void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) -{ +void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) { refdef_t refdef = {}; float oldColorScale = tr.refdef.colorScale; @@ -2415,8 +2202,7 @@ void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) refdef.x = 0; refdef.y = 0; - switch (cubemapSide) - { + switch (cubemapSide) { case 0: // +X VectorSet(refdef.viewaxis[0], 1, 0, 0); @@ -2461,10 +2247,8 @@ void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) tr.refdef.colorScale = 1.0f; - for (int i = 0; i < tr.numCachedViewParms; i++) - { - if (!tr.cachedViewParms[i].targetFbo) - { + for (int i = 0; i < tr.numCachedViewParms; i++) { + if (!tr.cachedViewParms[i].targetFbo) { tr.cachedViewParms[i].targetFbo = tr.renderCubeFbo[cubemapSide]; tr.cachedViewParms[i].targetFboLayer = 0; tr.cachedViewParms[i].flags |= VPF_NOVIEWMODEL; @@ -2481,8 +2265,7 @@ void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) R_NewFrameSync(); } -void R_SetupViewParms(const trRefdef_t *refdef) -{ +void R_SetupViewParms(const trRefdef_t *refdef) { tr.viewCount++; Com_Memset(&tr.viewParms, 0, sizeof(viewParms_t)); tr.viewParms.viewportX = refdef->x; @@ -2510,8 +2293,7 @@ void R_SetupViewParms(const trRefdef_t *refdef) R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); R_SetupProjection(&tr.viewParms, tr.viewParms.zNear, tr.viewParms.zFar, qtrue); - if (tr.world) - { + if (tr.world) { R_MarkLeaves(); // clear out the visible min/max @@ -2525,49 +2307,45 @@ void R_SetupViewParms(const trRefdef_t *refdef) R_SetupProjectionZ(&tr.viewParms); } -qboolean R_AddPortalView(const trRefdef_t *refdef) -{ +qboolean R_AddPortalView(const trRefdef_t *refdef) { if (!tr.world) return qfalse; - for (int i = 0; i < tr.world->numWorldSurfaces; i++) - { + for (int i = 0; i < tr.world->numWorldSurfaces; i++) { if (tr.world->surfacesViewCount[i] != tr.viewCount) continue; - msurface_t *surface = tr.world->surfaces + i; + msurface_t *surface = tr.world->surfaces + i; if (surface->shader->sort != SS_PORTAL) { continue; } // if the mirror was completely clipped away, we may need to check another surface if (R_MirrorViewBySurface(surface, REFENTITYNUM_WORLD)) { - return qtrue; // only one mirror view at a time + return qtrue; // only one mirror view at a time } } - for (int i = 0; i < tr.world->numMergedSurfaces; i++) - { + for (int i = 0; i < tr.world->numMergedSurfaces; i++) { if (tr.world->mergedSurfacesViewCount[i] != tr.viewCount) continue; - msurface_t *surface = tr.world->mergedSurfaces + i; + msurface_t *surface = tr.world->mergedSurfaces + i; if (surface->shader->sort != SS_PORTAL) { continue; } // if the mirror was completely clipped away, we may need to check another surface if (R_MirrorViewBySurface(surface, REFENTITYNUM_WORLD)) { - return qtrue; // only one mirror view at a time + return qtrue; // only one mirror view at a time } } - for (int i = 0; i < refdef->num_entities; i++) - { + for (int i = 0; i < refdef->num_entities; i++) { trRefEntity_t *ent = &refdef->entities[i]; switch (ent->e.reType) { case RT_PORTALSURFACE: - break; // don't draw anything + break; // don't draw anything case RT_SPRITE: case RT_BEAM: case RT_ORIENTED_QUAD: @@ -2586,30 +2364,27 @@ qboolean R_AddPortalView(const trRefdef_t *refdef) tr.currentModel = R_GetModelByHandle(ent->e.hModel); if (!tr.currentModel) { continue; - } - else { + } else { switch (tr.currentModel->type) { - case MOD_BRUSH: - { - //R_AddBrushModelSurfaces(ent, i); + case MOD_BRUSH: { + // R_AddBrushModelSurfaces(ent, i); bmodel_t *bmodel = tr.currentModel->data.bmodel; world_t *world = R_GetWorld(bmodel->worldIndex); for (int j = 0; j < bmodel->numSurfaces; j++) { int surf = bmodel->firstSurface + j; // TODO: use pvs of misc_bsp models - msurface_t *surface = world->surfaces + surf; + msurface_t *surface = world->surfaces + surf; if (surface->shader->sort != SS_PORTAL) { continue; } // if the mirror was completely clipped away, we may need to check another surface if (R_MirrorViewBySurface(surface, i)) { - return qtrue; // only one mirror view at a time + return qtrue; // only one mirror view at a time } } - } - break; + } break; case MOD_MESH: case MOD_MDR: case MOD_IQM: @@ -2630,17 +2405,12 @@ qboolean R_AddPortalView(const trRefdef_t *refdef) return qfalse; } -static float CalcSplit(float n, float f, float i, float m) -{ - return (n * pow(f / n, i / m) + (f - n) * i / m) / 2.0f; -} +static float CalcSplit(float n, float f, float i, float m) { return (n * pow(f / n, i / m) + (f - n) * i / m) / 2.0f; } -void R_GatherFrameViews(trRefdef_t *refdef) -{ +void R_GatherFrameViews(trRefdef_t *refdef) { int mainFlags = 0; // skyportal view - if (tr.world && tr.world->skyboxportal) - { + if (tr.world && tr.world->skyboxportal) { tr.viewCount++; tr.viewParms = tr.skyPortalParms; R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); @@ -2667,14 +2437,11 @@ void R_GatherFrameViews(trRefdef_t *refdef) if (tr.world) R_MarkLeaves(); - if (!(refdef->rdflags & RDF_NOWORLDMODEL)) - { + if (!(refdef->rdflags & RDF_NOWORLDMODEL)) { // dlight shadowmaps - if (refdef->num_dlights && r_dlightMode->integer >= 2) - { - for (int i = 0; i < refdef->num_dlights; i++) - { - viewParms_t shadowParms; + if (refdef->num_dlights && r_dlightMode->integer >= 2) { + for (int i = 0; i < refdef->num_dlights; i++) { + viewParms_t shadowParms; int j; Com_Memset(&shadowParms, 0, sizeof(shadowParms)); @@ -2695,10 +2462,8 @@ void R_GatherFrameViews(trRefdef_t *refdef) VectorCopy(refdef->dlights[i].origin, shadowParms.ori.origin); - for (j = 0; j < 6; j++) - { - switch (j) - { + for (j = 0; j < 6; j++) { + switch (j) { case 0: // -X VectorSet(shadowParms.ori.axis[0], -1, 0, 0); @@ -2754,12 +2519,10 @@ void R_GatherFrameViews(trRefdef_t *refdef) } // pshadow shadowmaps - if (r_shadows->integer == 4) - { + if (r_shadows->integer == 4) { R_SetupPshadowMaps(refdef); - for (int i = 0; i < tr.refdef.num_pshadows; i++) - { + for (int i = 0; i < tr.refdef.num_pshadows; i++) { pshadow_t *shadow = &tr.refdef.pshadows[i]; tr.viewParms.viewportX = 0; @@ -2810,7 +2573,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) dest->projectionMatrix[1] = 0; dest->projectionMatrix[5] = 2 / (ymax - ymin); - dest->projectionMatrix[9] = (ymax + ymin) / (ymax - ymin); // normally 0 + dest->projectionMatrix[9] = (ymax + ymin) / (ymax - ymin); // normally 0 dest->projectionMatrix[13] = 0; dest->projectionMatrix[2] = 0; @@ -2843,8 +2606,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) VectorMA(dest->ori.origin, -shadow->lightRadius, dest->frustum[4].normal, pop); dest->frustum[4].dist = DotProduct(pop, dest->frustum[4].normal); - for (int j = 0; j < 5; j++) - { + for (int j = 0; j < 5; j++) { dest->frustum[j].type = PLANE_NON_AXIAL; SetPlaneSignbits(&dest->frustum[j]); } @@ -2857,12 +2619,10 @@ void R_GatherFrameViews(trRefdef_t *refdef) tr.numCachedViewParms++; } } - } // sun shadowmaps - if (r_sunlightMode->integer && r_depthPrepass->value && (r_forceSun->integer || tr.sunShadows)) - { + if (r_sunlightMode->integer && r_depthPrepass->value && (r_forceSun->integer || tr.sunShadows)) { vec3_t lightViewAxis[3]; vec3_t lightOrigin; float splitZNear, splitZFar, splitBias; @@ -2873,10 +2633,8 @@ void R_GatherFrameViews(trRefdef_t *refdef) viewZFar = r_shadowCascadeZFar->value; splitBias = r_shadowCascadeZBias->value; - for (int level = 0; level < 3; level++) - { - switch (level) - { + for (int level = 0; level < 3; level++) { + switch (level) { case 0: default: splitZNear = viewZNear; @@ -2899,8 +2657,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) VectorSet(lightViewAxis[2], 0, 0, 1); // Check if too close to parallel to light direction - if (fabs(DotProduct(lightViewAxis[2], lightViewAxis[0])) > 0.9f) - { + if (fabs(DotProduct(lightViewAxis[2], lightViewAxis[0])) > 0.9f) { // Use world left as light view up VectorSet(lightViewAxis[2], 0, 1, 0); } @@ -2929,7 +2686,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) VectorMA(point, ly, refdef->viewaxis[2], point); VectorCopy(point, frustrumPoint0); VectorAdd(point, splitCenter, splitCenter); - + VectorMA(base, -lx, refdef->viewaxis[1], point); VectorMA(point, ly, refdef->viewaxis[2], point); VectorAdd(point, splitCenter, splitCenter); @@ -2979,14 +2736,10 @@ void R_GatherFrameViews(trRefdef_t *refdef) orientationr_t orientation = {}; R_SetOrientationOriginAndAxis(orientation, lightOrigin, lightViewAxis); - R_SetupViewParmsForOrthoRendering( - tr.sunShadowFbo[level]->width, - tr.sunShadowFbo[level]->height, - tr.sunShadowFbo[level], - VPF_DEPTHSHADOW | VPF_DEPTHCLAMP | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL | VPF_SHADOWCASCADES, - orientation, - lightviewBounds); - + R_SetupViewParmsForOrthoRendering(tr.sunShadowFbo[level]->width, tr.sunShadowFbo[level]->height, tr.sunShadowFbo[level], + VPF_DEPTHSHADOW | VPF_DEPTHCLAMP | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL | VPF_SHADOWCASCADES, orientation, + lightviewBounds); + // Moving the Light in Texel-Sized Increments // from http://msdn.microsoft.com/en-us/library/windows/desktop/ee416324%28v=vs.85%29.aspx static float worldUnitsPerTexel = 2.0f * lightviewBounds[1][0] / (float)tr.sunShadowFbo[level]->width; @@ -3000,10 +2753,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) tr.viewParms.world.modelViewMatrix[13] *= worldUnitsPerTexel; tr.viewParms.world.modelViewMatrix[14] *= worldUnitsPerTexel; - Matrix16Multiply( - tr.viewParms.projectionMatrix, - tr.viewParms.world.modelViewMatrix, - refdef->sunShadowMvp[level]); + Matrix16Multiply(tr.viewParms.projectionMatrix, tr.viewParms.world.modelViewMatrix, refdef->sunShadowMvp[level]); tr.viewParms.currentViewParm = tr.numCachedViewParms; tr.viewParms.viewParmType = VPT_SUN_SHADOWS; @@ -3017,8 +2767,7 @@ void R_GatherFrameViews(trRefdef_t *refdef) // main view { R_SetupViewParms(refdef); - if (R_AddPortalView(refdef)) - { + if (R_AddPortalView(refdef)) { // this is a debug option to see exactly what is being mirrored if (r_portalOnly->integer) return; diff --git a/codemp/rd-rend2/tr_marks.cpp b/codemp/rd-rend2/tr_marks.cpp index 6e12616d13..c233f6084d 100644 --- a/codemp/rd-rend2/tr_marks.cpp +++ b/codemp/rd-rend2/tr_marks.cpp @@ -24,9 +24,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" //#include "assert.h" -#define MAX_VERTS_ON_POLY 64 +#define MAX_VERTS_ON_POLY 64 -#define MARKER_OFFSET 0 // 1 +#define MARKER_OFFSET 0 // 1 /* ============= @@ -35,22 +35,21 @@ R_ChopPolyBehindPlane Out must have space for two more vertexes than in ============= */ -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 -static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], - int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], - vec3_t normal, float dist, float epsilon) { - float dists[MAX_VERTS_ON_POLY+4] = { 0 }; - int sides[MAX_VERTS_ON_POLY+4] = { 0 }; - int counts[3]; - float dot; - int i, j; - float *p1, *p2, *clip; - float d; +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 +static void R_ChopPolyBehindPlane(int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], vec3_t normal, + float dist, float epsilon) { + float dists[MAX_VERTS_ON_POLY + 4] = {0}; + int sides[MAX_VERTS_ON_POLY + 4] = {0}; + int counts[3]; + float dot; + int i, j; + float *p1, *p2, *clip; + float d; // don't clip if it might overflow - if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) { + if (numInPoints >= MAX_VERTS_ON_POLY - 2) { *numOutPoints = 0; return; } @@ -58,13 +57,13 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - for ( i = 0 ; i < numInPoints ; i++ ) { - dot = DotProduct( inPoints[i], normal ); + for (i = 0; i < numInPoints; i++) { + dot = DotProduct(inPoints[i], normal); dot -= dist; dists[i] = dot; - if ( dot > epsilon ) { + if (dot > epsilon) { sides[i] = SIDE_FRONT; - } else if ( dot < -epsilon ) { + } else if (dot < -epsilon) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; @@ -76,40 +75,40 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON *numOutPoints = 0; - if ( !counts[0] ) { + if (!counts[0]) { return; } - if ( !counts[1] ) { + if (!counts[1]) { *numOutPoints = numInPoints; - Com_Memcpy( outPoints, inPoints, numInPoints * sizeof(vec3_t) ); + Com_Memcpy(outPoints, inPoints, numInPoints * sizeof(vec3_t)); return; } - for ( i = 0 ; i < numInPoints ; i++ ) { + for (i = 0; i < numInPoints; i++) { p1 = inPoints[i]; - clip = outPoints[ *numOutPoints ]; - - if ( sides[i] == SIDE_ON ) { - VectorCopy( p1, clip ); + clip = outPoints[*numOutPoints]; + + if (sides[i] == SIDE_ON) { + VectorCopy(p1, clip); (*numOutPoints)++; continue; } - - if ( sides[i] == SIDE_FRONT ) { - VectorCopy( p1, clip ); + + if (sides[i] == SIDE_FRONT) { + VectorCopy(p1, clip); (*numOutPoints)++; - clip = outPoints[ *numOutPoints ]; + clip = outPoints[*numOutPoints]; } - if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) { + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) { continue; } - + // generate a split point - p2 = inPoints[ (i+1) % numInPoints ]; + p2 = inPoints[(i + 1) % numInPoints]; - d = dists[i] - dists[i+1]; - if ( d == 0 ) { + d = dists[i] - dists[i + 1]; + if (d == 0) { dot = 0; } else { dot = dists[i] / d; @@ -117,8 +116,8 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON // clip xyz - for (j=0 ; j<3 ; j++) { - clip[j] = p1[j] + dot * ( p2[j] - p1[j] ); + for (j = 0; j < 3; j++) { + clip[j] = p1[j] + dot * (p2[j] - p1[j]); } (*numOutPoints)++; @@ -133,13 +132,13 @@ R_BoxSurfaces_r */ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **list, int listsize, int *listlength, vec3_t dir) { - int s, c; - msurface_t *surf; + int s, c; + msurface_t *surf; int *mark; // do the tail recursion in a loop - while ( node->contents == -1 ) { - s = BoxOnPlaneSide( mins, maxs, node->plane ); + while (node->contents == -1) { + s = BoxOnPlaneSide(mins, maxs, node->plane); if (s == 1) { node = node->children[0]; } else if (s == 2) { @@ -156,28 +155,26 @@ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **li while (c--) { int *surfViewCount; // - if (*listlength >= listsize) break; + if (*listlength >= listsize) + break; // surfViewCount = &tr.world->surfacesViewCount[*mark]; surf = tr.world->surfaces + *mark; // check if the surface has NOIMPACT or NOMARKS set - if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) ) - || ( surf->shader->contentFlags & CONTENTS_FOG ) ) { + if ((surf->shader->surfaceFlags & (SURF_NOIMPACT | SURF_NOMARKS)) || (surf->shader->contentFlags & CONTENTS_FOG)) { *surfViewCount = tr.viewCount; } // extra check for surfaces to avoid list overflows else if (*(surf->data) == SF_FACE) { // the face plane should go through the box - s = BoxOnPlaneSide( mins, maxs, &surf->cullinfo.plane ); + s = BoxOnPlaneSide(mins, maxs, &surf->cullinfo.plane); if (s == 1 || s == 2) { *surfViewCount = tr.viewCount; } else if (DotProduct(surf->cullinfo.plane.normal, dir) > -0.5) { - // don't add faces that make sharp angles with the projection direction + // don't add faces that make sharp angles with the projection direction *surfViewCount = tr.viewCount; } - } - else if (*(surf->data) != SF_GRID && - *(surf->data) != SF_TRIANGLES) + } else if (*(surf->data) != SF_GRID && *(surf->data) != SF_TRIANGLES) *surfViewCount = tr.viewCount; // check the viewCount because the surface may have // already been added if it spans multiple leafs @@ -196,36 +193,31 @@ R_AddMarkFragments ================= */ -void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], - int numPlanes, vec3_t *normals, float *dists, - int maxPoints, vec3_t pointBuffer, - int maxFragments, markFragment_t *fragmentBuffer, - int *returnedPoints, int *returnedFragments, - vec3_t mins, vec3_t maxs) { +void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], int numPlanes, vec3_t *normals, float *dists, int maxPoints, + vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer, int *returnedPoints, int *returnedFragments, vec3_t mins, + vec3_t maxs) { int pingPong, i; - markFragment_t *mf; + markFragment_t *mf; // chop the surface by all the bounding planes of the to be projected polygon pingPong = 0; - for ( i = 0 ; i < numPlanes ; i++ ) { + for (i = 0; i < numPlanes; i++) { - R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong], - &numClipPoints, clipPoints[!pingPong], - normals[i], dists[i], 0.5 ); + R_ChopPolyBehindPlane(numClipPoints, clipPoints[pingPong], &numClipPoints, clipPoints[!pingPong], normals[i], dists[i], 0.5); pingPong ^= 1; - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { break; } } // completely clipped away? - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { return; } // add this fragment to the returned list - if ( numClipPoints + (*returnedPoints) > maxPoints ) { - return; // not enough space for this polygon + if (numClipPoints + (*returnedPoints) > maxPoints) { + return; // not enough space for this polygon } /* // all the clip points should be within the bounding box @@ -243,7 +235,7 @@ void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POL mf = fragmentBuffer + (*returnedFragments); mf->firstPoint = (*returnedPoints); mf->numPoints = numClipPoints; - Com_Memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t) ); + Com_Memcpy(pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t)); (*returnedPoints) += numClipPoints; (*returnedFragments)++; @@ -255,52 +247,53 @@ R_MarkFragments ================= */ -int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, - int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) { - int numsurfaces, numPlanes; - int i, j, k, m, n; - surfaceType_t *surfaces[64]; - vec3_t mins, maxs; - int returnedFragments; - int returnedPoints; - vec3_t normals[MAX_VERTS_ON_POLY+2]; - float dists[MAX_VERTS_ON_POLY+2]; - vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; - int numClipPoints; - float *v; - srfBspSurface_t *cv; - glIndex_t *tri; - srfVert_t *dv; - vec3_t normal; - vec3_t projectionDir; - vec3_t v1, v2; +int R_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + int numsurfaces, numPlanes; + int i, j, k, m, n; + surfaceType_t *surfaces[64]; + vec3_t mins, maxs; + int returnedFragments; + int returnedPoints; + vec3_t normals[MAX_VERTS_ON_POLY + 2]; + float dists[MAX_VERTS_ON_POLY + 2]; + vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; + int numClipPoints; + float *v; + srfBspSurface_t *cv; + glIndex_t *tri; + srfVert_t *dv; + vec3_t normal; + vec3_t projectionDir; + vec3_t v1, v2; if (numPoints <= 0) { return 0; } - //increment view count for double check prevention + // increment view count for double check prevention tr.viewCount++; // - VectorNormalize2( projection, projectionDir ); + VectorNormalize2(projection, projectionDir); // find all the brushes that are to be considered - ClearBounds( mins, maxs ); - for ( i = 0 ; i < numPoints ; i++ ) { - vec3_t temp; + ClearBounds(mins, maxs); + for (i = 0; i < numPoints; i++) { + vec3_t temp; - AddPointToBounds( points[i], mins, maxs ); - VectorAdd( points[i], projection, temp ); - AddPointToBounds( temp, mins, maxs ); + AddPointToBounds(points[i], mins, maxs); + VectorAdd(points[i], projection, temp); + AddPointToBounds(temp, mins, maxs); // make sure we get all the leafs (also the one(s) in front of the hit surface) - VectorMA( points[i], -20, projectionDir, temp ); - AddPointToBounds( temp, mins, maxs ); + VectorMA(points[i], -20, projectionDir, temp); + AddPointToBounds(temp, mins, maxs); } - if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY; + if (numPoints > MAX_VERTS_ON_POLY) + numPoints = MAX_VERTS_ON_POLY; // create the bounding planes for the to be projected polygon - for ( i = 0 ; i < numPoints ; i++ ) { - VectorSubtract(points[(i+1)%numPoints], points[i], v1); + for (i = 0; i < numPoints; i++) { + VectorSubtract(points[(i + 1) % numPoints], points[i], v1); VectorAdd(points[i], projection, v2); VectorSubtract(points[i], v2, v2); CrossProduct(v1, v2, normals[i]); @@ -310,26 +303,26 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio // add near and far clipping planes for projection VectorCopy(projectionDir, normals[numPoints]); dists[numPoints] = DotProduct(normals[numPoints], points[0]) - 32; - VectorCopy(projectionDir, normals[numPoints+1]); - VectorInverse(normals[numPoints+1]); - dists[numPoints+1] = DotProduct(normals[numPoints+1], points[0]) - 20; + VectorCopy(projectionDir, normals[numPoints + 1]); + VectorInverse(normals[numPoints + 1]); + dists[numPoints + 1] = DotProduct(normals[numPoints + 1], points[0]) - 20; numPlanes = numPoints + 2; numsurfaces = 0; R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir); - //assert(numsurfaces <= 64); - //assert(numsurfaces != 64); + // assert(numsurfaces <= 64); + // assert(numsurfaces != 64); returnedPoints = 0; returnedFragments = 0; - for ( i = 0 ; i < numsurfaces ; i++ ) { + for (i = 0; i < numsurfaces; i++) { if (*surfaces[i] == SF_GRID) { - cv = (srfBspSurface_t *) surfaces[i]; - for ( m = 0 ; m < cv->height - 1 ; m++ ) { - for ( n = 0 ; n < cv->width - 1 ; n++ ) { + cv = (srfBspSurface_t *)surfaces[i]; + for (m = 0; m < cv->height - 1; m++) { + for (n = 0; n < cv->width - 1; n++) { // We triangulate the grid and chop all triangles within // the bounding planes of the to be projected polygon. // LOD is not taken into account, not such a big deal though. @@ -368,14 +361,11 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.1) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } @@ -383,8 +373,8 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[1].normal, clipPoints[0][0]); VectorCopy(dv[cv->width].xyz, clipPoints[0][1]); VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]); - VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]); - VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width+1].normal, clipPoints[0][2]); + VectorCopy(dv[cv->width + 1].xyz, clipPoints[0][2]); + VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width + 1].normal, clipPoints[0][2]); // check the normal of this triangle VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1); VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2); @@ -392,75 +382,55 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.05) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } } - } - else if (*surfaces[i] == SF_FACE) { + } else if (*surfaces[i] == SF_FACE) { - srfBspSurface_t *surf = ( srfBspSurface_t * ) surfaces[i]; + srfBspSurface_t *surf = (srfBspSurface_t *)surfaces[i]; // check the normal of this face if (DotProduct(surf->cullPlane.normal, projectionDir) > -0.5) { continue; } - for(k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) - { - for(j = 0; j < 3; j++) - { + for (k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) { + for (j = 0; j < 3; j++) { v = surf->verts[tri[j]].xyz; VectorMA(v, MARKER_OFFSET, surf->cullPlane.normal, clipPoints[0][j]); } // add the fragments of this face - R_AddMarkFragments( 3 , clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, - &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } - } - else if(*surfaces[i] == SF_TRIANGLES && r_marksOnTriangleMeshes->integer) { + } else if (*surfaces[i] == SF_TRIANGLES && r_marksOnTriangleMeshes->integer) { - srfBspSurface_t *surf = (srfBspSurface_t *) surfaces[i]; + srfBspSurface_t *surf = (srfBspSurface_t *)surfaces[i]; - for(k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) - { - for(j = 0; j < 3; j++) - { + for (k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) { + for (j = 0; j < 3; j++) { v = surf->verts[tri[j]].xyz; VectorMA(v, MARKER_OFFSET, surf->verts[tri[j]].normal, clipPoints[0][j]); } // add the fragments of this face - R_AddMarkFragments(3, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if(returnedFragments == maxFragments) - { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } } return returnedFragments; } - - - - - diff --git a/codemp/rd-rend2/tr_mesh.cpp b/codemp/rd-rend2/tr_mesh.cpp index 4b93f07377..b99dbbbcce 100644 --- a/codemp/rd-rend2/tr_mesh.cpp +++ b/codemp/rd-rend2/tr_mesh.cpp @@ -23,48 +23,38 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" -float ProjectRadius( float r, vec3_t location ) -{ +float ProjectRadius(float r, vec3_t location) { float pr; float dist; float c; - vec3_t p; - float projected[4]; + vec3_t p; + float projected[4]; - c = DotProduct( tr.viewParms.ori.axis[0], tr.viewParms.ori.origin ); - dist = DotProduct( tr.viewParms.ori.axis[0], location ) - c; + c = DotProduct(tr.viewParms.ori.axis[0], tr.viewParms.ori.origin); + dist = DotProduct(tr.viewParms.ori.axis[0], location) - c; - if ( dist <= 0 ) + if (dist <= 0) return 0; p[0] = 0; - p[1] = fabs( r ); + p[1] = fabs(r); p[2] = -dist; - projected[0] = p[0] * tr.viewParms.projectionMatrix[0] + - p[1] * tr.viewParms.projectionMatrix[4] + - p[2] * tr.viewParms.projectionMatrix[8] + + projected[0] = p[0] * tr.viewParms.projectionMatrix[0] + p[1] * tr.viewParms.projectionMatrix[4] + p[2] * tr.viewParms.projectionMatrix[8] + tr.viewParms.projectionMatrix[12]; - projected[1] = p[0] * tr.viewParms.projectionMatrix[1] + - p[1] * tr.viewParms.projectionMatrix[5] + - p[2] * tr.viewParms.projectionMatrix[9] + + projected[1] = p[0] * tr.viewParms.projectionMatrix[1] + p[1] * tr.viewParms.projectionMatrix[5] + p[2] * tr.viewParms.projectionMatrix[9] + tr.viewParms.projectionMatrix[13]; - projected[2] = p[0] * tr.viewParms.projectionMatrix[2] + - p[1] * tr.viewParms.projectionMatrix[6] + - p[2] * tr.viewParms.projectionMatrix[10] + + projected[2] = p[0] * tr.viewParms.projectionMatrix[2] + p[1] * tr.viewParms.projectionMatrix[6] + p[2] * tr.viewParms.projectionMatrix[10] + tr.viewParms.projectionMatrix[14]; - projected[3] = p[0] * tr.viewParms.projectionMatrix[3] + - p[1] * tr.viewParms.projectionMatrix[7] + - p[2] * tr.viewParms.projectionMatrix[11] + + projected[3] = p[0] * tr.viewParms.projectionMatrix[3] + p[1] * tr.viewParms.projectionMatrix[7] + p[2] * tr.viewParms.projectionMatrix[11] + tr.viewParms.projectionMatrix[15]; - pr = projected[1] / projected[3]; - if ( pr > 1.0f ) + if (pr > 1.0f) pr = 1.0f; return pr; @@ -75,22 +65,19 @@ float ProjectRadius( float r, vec3_t location ) R_CullModel ============= */ -static int R_CullModel( mdvModel_t *model, trRefEntity_t *ent ) { - vec3_t bounds[2]; - mdvFrame_t *oldFrame, *newFrame; - int i; +static int R_CullModel(mdvModel_t *model, trRefEntity_t *ent) { + vec3_t bounds[2]; + mdvFrame_t *oldFrame, *newFrame; + int i; // compute frame pointers newFrame = model->frames + ent->e.frame; oldFrame = model->frames + ent->e.oldframe; // cull bounding sphere ONLY if this is not an upscaled entity - if ( !ent->e.nonNormalizedAxes ) - { - if ( ent->e.frame == ent->e.oldframe ) - { - switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) - { + if (!ent->e.nonNormalizedAxes) { + if (ent->e.frame == ent->e.oldframe) { + switch (R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius)) { case CULL_OUT: tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; @@ -103,46 +90,37 @@ static int R_CullModel( mdvModel_t *model, trRefEntity_t *ent ) { tr.pc.c_sphere_cull_md3_clip++; break; } - } - else - { + } else { int sphereCull, sphereCullB; - sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); - if ( newFrame == oldFrame ) { + sphereCull = R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius); + if (newFrame == oldFrame) { sphereCullB = sphereCull; } else { - sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + sphereCullB = R_CullLocalPointAndRadius(oldFrame->localOrigin, oldFrame->radius); } - if ( sphereCull == sphereCullB ) - { - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == sphereCullB) { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; - } - else if ( sphereCull == CULL_IN ) - { + } else if (sphereCull == CULL_IN) { tr.pc.c_sphere_cull_md3_in++; return CULL_IN; - } - else - { + } else { tr.pc.c_sphere_cull_md3_clip++; } } } } - + // calculate a bounding box in the current coordinate system - for (i = 0 ; i < 3 ; i++) { + for (i = 0; i < 3; i++) { bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; } - switch ( R_CullLocalBox( bounds ) ) - { + switch (R_CullLocalBox(bounds)) { case CULL_IN: tr.pc.c_box_cull_md3_in++; return CULL_IN; @@ -156,14 +134,13 @@ static int R_CullModel( mdvModel_t *model, trRefEntity_t *ent ) { } } - /* ================= R_ComputeLOD ================= */ -int R_ComputeLOD( trRefEntity_t *ent ) { +int R_ComputeLOD(trRefEntity_t *ent) { float radius; float flod, lodscale; float projectedRadius; @@ -172,44 +149,36 @@ int R_ComputeLOD( trRefEntity_t *ent ) { mdrFrame_t *mdrframe; int lod; - if ( tr.currentModel->numLods < 2 ) - { + if (tr.currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias lod = 0; - } - else - { + } else { // multiple LODs exist, so compute projected bounding sphere // and use that as a criteria for selecting LOD - if(tr.currentModel->type == MOD_MDR) - { + if (tr.currentModel->type == MOD_MDR) { int frameSize; mdr = tr.currentModel->data.mdr; - frameSize = (size_t) (&((mdrFrame_t *)0)->bones[mdr->numBones]); - - mdrframe = (mdrFrame_t *) ((byte *) mdr + mdr->ofsFrames + frameSize * ent->e.frame); - + frameSize = (size_t)(&((mdrFrame_t *)0)->bones[mdr->numBones]); + + mdrframe = (mdrFrame_t *)((byte *)mdr + mdr->ofsFrames + frameSize * ent->e.frame); + radius = RadiusFromBounds(mdrframe->bounds[0], mdrframe->bounds[1]); - } - else - { - //frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames ); + } else { + // frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames ); frame = tr.currentModel->data.mdv[0]->frames; frame += ent->e.frame; - radius = RadiusFromBounds( frame->bounds[0], frame->bounds[1] ); + radius = RadiusFromBounds(frame->bounds[0], frame->bounds[1]); } - if ( ( projectedRadius = ProjectRadius( radius, ent->e.origin ) ) != 0 ) - { - lodscale = (r_lodscale->value+r_autolodscalevalue->integer); - if (lodscale > 20) lodscale = 20; + if ((projectedRadius = ProjectRadius(radius, ent->e.origin)) != 0) { + lodscale = (r_lodscale->value + r_autolodscalevalue->integer); + if (lodscale > 20) + lodscale = 20; flod = 1.0f - projectedRadius * lodscale; - } - else - { + } else { // object intersects near view plane, e.g. view weapon flod = 0; } @@ -217,21 +186,18 @@ int R_ComputeLOD( trRefEntity_t *ent ) { flod *= tr.currentModel->numLods; lod = Q_ftol(flod); - if ( lod < 0 ) - { + if (lod < 0) { lod = 0; - } - else if ( lod >= tr.currentModel->numLods ) - { + } else if (lod >= tr.currentModel->numLods) { lod = tr.currentModel->numLods - 1; } } lod += r_lodbias->integer; - - if ( lod >= tr.currentModel->numLods ) + + if (lod >= tr.currentModel->numLods) lod = tr.currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; @@ -243,30 +209,30 @@ R_ComputeFogNum ================= */ -int R_ComputeFogNum( mdvModel_t *model, trRefEntity_t *ent ) { - int i, j; - fog_t *fog; - mdvFrame_t *mdvFrame; - vec3_t localOrigin; +int R_ComputeFogNum(mdvModel_t *model, trRefEntity_t *ent) { + int i, j; + fog_t *fog; + mdvFrame_t *mdvFrame; + vec3_t localOrigin; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } // FIXME: non-normalized axis issues mdvFrame = model->frames + ent->e.frame; - VectorAdd( ent->e.origin, mdvFrame->localOrigin, localOrigin ); - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + VectorAdd(ent->e.origin, mdvFrame->localOrigin, localOrigin); + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( localOrigin[j] - mdvFrame->radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (localOrigin[j] - mdvFrame->radius >= fog->bounds[1][j]) { break; } - if ( localOrigin[j] + mdvFrame->radius <= fog->bounds[0][j] ) { + if (localOrigin[j] + mdvFrame->radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -280,22 +246,21 @@ R_AddMD3Surfaces ================= */ -void R_AddMD3Surfaces( trRefEntity_t *ent, int entityNum ) { - int i; - mdvModel_t *model = NULL; - mdvSurface_t *surface = NULL; - shader_t *shader = NULL; - int cull; - int lod; - int fogNum; - int cubemapIndex; - qboolean personalModel; +void R_AddMD3Surfaces(trRefEntity_t *ent, int entityNum) { + int i; + mdvModel_t *model = NULL; + mdvSurface_t *surface = NULL; + shader_t *shader = NULL; + int cull; + int lod; + int fogNum; + int cubemapIndex; + qboolean personalModel; // don't add third_person objects if not in a portal - personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !(tr.viewParms.isPortal - || (tr.viewParms.flags & VPF_DEPTHSHADOW))); + personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !(tr.viewParms.isPortal || (tr.viewParms.flags & VPF_DEPTHSHADOW))); - if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + if (ent->e.renderfx & RF_WRAP_FRAMES) { ent->e.frame %= tr.currentModel->data.mdv[0]->numFrames; ent->e.oldframe %= tr.currentModel->data.mdv[0]->numFrames; } @@ -306,21 +271,17 @@ void R_AddMD3Surfaces( trRefEntity_t *ent, int entityNum ) { // when the surfaces are rendered, they don't need to be // range checked again. // - if ( (ent->e.frame >= tr.currentModel->data.mdv[0]->numFrames) - || (ent->e.frame < 0) - || (ent->e.oldframe >= tr.currentModel->data.mdv[0]->numFrames) - || (ent->e.oldframe < 0) ) { - ri.Printf( PRINT_DEVELOPER, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", - ent->e.oldframe, ent->e.frame, - tr.currentModel->name ); - ent->e.frame = 0; - ent->e.oldframe = 0; + if ((ent->e.frame >= tr.currentModel->data.mdv[0]->numFrames) || (ent->e.frame < 0) || (ent->e.oldframe >= tr.currentModel->data.mdv[0]->numFrames) || + (ent->e.oldframe < 0)) { + ri.Printf(PRINT_DEVELOPER, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", ent->e.oldframe, ent->e.frame, tr.currentModel->name); + ent->e.frame = 0; + ent->e.oldframe = 0; } // // compute LOD // - lod = R_ComputeLOD( ent ); + lod = R_ComputeLOD(ent); model = tr.currentModel->data.mdv[lod]; @@ -328,15 +289,15 @@ void R_AddMD3Surfaces( trRefEntity_t *ent, int entityNum ) { // cull the entire model if merged bounding box of both frames // is outside the view frustum. // - cull = R_CullModel ( model, ent ); - if ( cull == CULL_OUT ) { + cull = R_CullModel(model, ent); + if (cull == CULL_OUT) { return; } // // see if we are in a fog volume // - fogNum = R_ComputeFogNum( model, ent ); + fogNum = R_ComputeFogNum(model, ent); cubemapIndex = R_CubemapForPoint(ent->e.origin); // FIX ME: not tested! Animated models might be handled incorrecly @@ -346,55 +307,47 @@ void R_AddMD3Surfaces( trRefEntity_t *ent, int entityNum ) { // draw all surfaces // surface = model->surfaces; - for ( i = 0 ; i < model->numSurfaces ; i++ ) { + for (i = 0; i < model->numSurfaces; i++) { - if ( ent->e.customShader ) { - shader = R_GetShaderByHandle( ent->e.customShader ); - } else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) { + if (ent->e.customShader) { + shader = R_GetShaderByHandle(ent->e.customShader); + } else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin_t *skin; - int j; + int j; - skin = R_GetSkinByHandle( ent->e.customSkin ); + skin = R_GetSkinByHandle(ent->e.customSkin); // match the surface name to something in the skin file shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surface->name ) ) { + if (!strcmp(skin->surfaces[j]->name, surface->name)) { shader = (shader_t *)skin->surfaces[j]->shader; break; } } if (shader == tr.defaultShader) { - ri.Printf( PRINT_DEVELOPER, "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); - } - else if (shader->defaultShader) { - ri.Printf( PRINT_DEVELOPER, "WARNING: shader %s in skin %s not found\n", shader->name, skin->name); + ri.Printf(PRINT_DEVELOPER, "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); + } else if (shader->defaultShader) { + ri.Printf(PRINT_DEVELOPER, "WARNING: shader %s in skin %s not found\n", shader->name, skin->name); } - //} else if ( surface->numShaders <= 0 ) { - //shader = tr.defaultShader; + //} else if ( surface->numShaders <= 0 ) { + // shader = tr.defaultShader; } else { - //md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders ); - //md3Shader += ent->e.skinNum % surface->numShaders; - //shader = tr.shaders[ md3Shader->shaderIndex ]; - shader = tr.shaders[ surface->shaderIndexes[ ent->e.skinNum % surface->numShaderIndexes ] ]; + // md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders ); + // md3Shader += ent->e.skinNum % surface->numShaders; + // shader = tr.shaders[ md3Shader->shaderIndex ]; + shader = tr.shaders[surface->shaderIndexes[ent->e.skinNum % surface->numShaderIndexes]]; } // don't add third_person objects if not viewing through a portal - if(!personalModel) - { + if (!personalModel) { srfVBOMDVMesh_t *vboSurface = &model->vboSurfaces[i]; - R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, dlightBits, R_IsPostRenderEntity(ent), cubemapIndex ); - //R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex ); + R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, dlightBits, R_IsPostRenderEntity(ent), cubemapIndex); + // R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex ); } surface++; } - } - - - - - diff --git a/codemp/rd-rend2/tr_model.cpp b/codemp/rd-rend2/tr_model.cpp index 0f9d746110..fa26be07b7 100644 --- a/codemp/rd-rend2/tr_model.cpp +++ b/codemp/rd-rend2/tr_model.cpp @@ -25,25 +25,23 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_cache.h" #include -#define LL(x) x=LittleLong(x) - +#define LL(x) x = LittleLong(x) static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *modName); -static qboolean R_LoadMDR(model_t *mod, void *buffer, int filesize, const char *name ); +static qboolean R_LoadMDR(model_t *mod, void *buffer, int filesize, const char *name); /* ==================== R_RegisterMD3 ==================== */ -qhandle_t R_RegisterMD3(const char *name, model_t *mod) -{ - unsigned *buf; - int lod; - int ident; - qboolean loaded = qfalse; - int numLoaded; - char filename[MAX_QPATH], namebuf[MAX_QPATH+20]; +qhandle_t R_RegisterMD3(const char *name, model_t *mod) { + unsigned *buf; + int lod; + int ident; + qboolean loaded = qfalse; + int numLoaded; + char filename[MAX_QPATH], namebuf[MAX_QPATH + 20]; char *fext, defex[] = "md3"; numLoaded = 0; @@ -51,60 +49,53 @@ qhandle_t R_RegisterMD3(const char *name, model_t *mod) strcpy(filename, name); fext = strchr(filename, '.'); - if(!fext) + if (!fext) fext = defex; - else - { + else { *fext = '\0'; fext++; } - for (lod = MD3_MAX_LODS - 1 ; lod >= 0 ; lod--) - { - if(lod) + for (lod = MD3_MAX_LODS - 1; lod >= 0; lod--) { + if (lod) Com_sprintf(namebuf, sizeof(namebuf), "%s_%d.%s", filename, lod, fext); else Com_sprintf(namebuf, sizeof(namebuf), "%s.%s", filename, fext); qboolean bAlreadyCached = qfalse; - if( !CModelCache->LoadFile( namebuf, (void**)&buf, &bAlreadyCached ) ) + if (!CModelCache->LoadFile(namebuf, (void **)&buf, &bAlreadyCached)) continue; ident = *(unsigned *)buf; - if( !bAlreadyCached ) + if (!bAlreadyCached) LL(ident); - - switch(ident) - { - case MD3_IDENT: - loaded = R_LoadMD3(mod, lod, buf, namebuf); - break; - case MDXA_IDENT: - loaded = R_LoadMDXA(mod, buf, namebuf, bAlreadyCached); - break; - case MDXM_IDENT: - loaded = R_LoadMDXM(mod, buf, name, bAlreadyCached); - break; - default: - ri.Printf(PRINT_WARNING, "R_RegisterMD3: unknown ident for %s\n", name); - break; + + switch (ident) { + case MD3_IDENT: + loaded = R_LoadMD3(mod, lod, buf, namebuf); + break; + case MDXA_IDENT: + loaded = R_LoadMDXA(mod, buf, namebuf, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = R_LoadMDXM(mod, buf, name, bAlreadyCached); + break; + default: + ri.Printf(PRINT_WARNING, "R_RegisterMD3: unknown ident for %s\n", name); + break; } - if(loaded) - { + if (loaded) { mod->numLods++; numLoaded++; - } - else + } else break; } - if(numLoaded) - { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for(lod--; lod >= 0; lod--) - { + for (lod--; lod >= 0; lod--) { mod->numLods++; mod->data.mdv[lod] = mod->data.mdv[lod + 1]; } @@ -113,7 +104,7 @@ qhandle_t R_RegisterMD3(const char *name, model_t *mod) } #ifdef _DEBUG - ri.Printf(PRINT_WARNING,"R_RegisterMD3: couldn't load %s\n", name); + ri.Printf(PRINT_WARNING, "R_RegisterMD3: couldn't load %s\n", name); #endif mod->type = MOD_BAD; @@ -125,36 +116,33 @@ qhandle_t R_RegisterMD3(const char *name, model_t *mod) R_RegisterMDR ==================== */ -qhandle_t R_RegisterMDR(const char *name, model_t *mod) -{ +qhandle_t R_RegisterMDR(const char *name, model_t *mod) { union { unsigned *u; void *v; } buf; - int ident; + int ident; qboolean loaded = qfalse; int filesize; - filesize = ri.FS_ReadFile(name, (void **) &buf.v); - if(!buf.u) - { + filesize = ri.FS_ReadFile(name, (void **)&buf.v); + if (!buf.u) { mod->type = MOD_BAD; return 0; } - + ident = LittleLong(*(unsigned *)buf.u); - if(ident == MDR_IDENT) + if (ident == MDR_IDENT) loaded = R_LoadMDR(mod, buf.u, filesize, name); - ri.FS_FreeFile (buf.v); - - if(!loaded) - { - ri.Printf(PRINT_WARNING,"R_RegisterMDR: couldn't load mdr file %s\n", name); + ri.FS_FreeFile(buf.v); + + if (!loaded) { + ri.Printf(PRINT_WARNING, "R_RegisterMDR: couldn't load mdr file %s\n", name); mod->type = MOD_BAD; return 0; } - + return mod->index; } @@ -163,8 +151,7 @@ qhandle_t R_RegisterMDR(const char *name, model_t *mod) R_RegisterIQM ==================== */ -qhandle_t R_RegisterIQM(const char *name, model_t *mod) -{ +qhandle_t R_RegisterIQM(const char *name, model_t *mod) { union { unsigned *u; void *v; @@ -172,46 +159,41 @@ qhandle_t R_RegisterIQM(const char *name, model_t *mod) qboolean loaded = qfalse; int filesize; - filesize = ri.FS_ReadFile(name, (void **) &buf.v); - if(!buf.u) - { + filesize = ri.FS_ReadFile(name, (void **)&buf.v); + if (!buf.u) { mod->type = MOD_BAD; return 0; } - + loaded = R_LoadIQM(mod, buf.u, filesize, name); - ri.FS_FreeFile (buf.v); - - if(!loaded) - { - ri.Printf(PRINT_WARNING,"R_RegisterIQM: couldn't load iqm file %s\n", name); + ri.FS_FreeFile(buf.v); + + if (!loaded) { + ri.Printf(PRINT_WARNING, "R_RegisterIQM: couldn't load iqm file %s\n", name); mod->type = MOD_BAD; return 0; } - + return mod->index; } - -typedef struct -{ +typedef struct { const char *ext; - qhandle_t (*ModelLoader)( const char *, model_t * ); + qhandle_t (*ModelLoader)(const char *, model_t *); } modelExtToLoaderMap_t; // Note that the ordering indicates the order of preference used // when there are multiple models of different formats available -static modelExtToLoaderMap_t modelLoaders[ ] = -{ - { "iqm", R_RegisterIQM }, - { "mdr", R_RegisterMDR }, - { "md3", R_RegisterMD3 }, - /* +static modelExtToLoaderMap_t modelLoaders[] = { + {"iqm", R_RegisterIQM}, + {"mdr", R_RegisterMDR}, + {"md3", R_RegisterMD3}, + /* Ghoul 2 Insert Start */ - { "glm", R_RegisterMD3 }, - { "gla", R_RegisterMD3 }, + {"glm", R_RegisterMD3}, + {"gla", R_RegisterMD3}, /* Ghoul 2 Insert End */ @@ -222,11 +204,11 @@ static int numModelLoaders = ARRAY_LEN(modelLoaders); /* ** R_GetModelByHandle */ -model_t *R_GetModelByHandle( qhandle_t index ) { - model_t *mod; +model_t *R_GetModelByHandle(qhandle_t index) { + model_t *mod; // out of range gets the defualt model - if ( index < 1 || index >= tr.numModels ) { + if (index < 1 || index >= tr.numModels) { return tr.models[0]; } @@ -240,14 +222,14 @@ model_t *R_GetModelByHandle( qhandle_t index ) { /* ** R_AllocModel */ -model_t *R_AllocModel( void ) { - model_t *mod; +model_t *R_AllocModel(void) { + model_t *mod; - if ( tr.numModels == MAX_MOD_KNOWN ) { + if (tr.numModels == MAX_MOD_KNOWN) { return NULL; } - mod = (model_t *)ri.Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), h_low ); + mod = (model_t *)ri.Hunk_Alloc(sizeof(*tr.models[tr.numModels]), h_low); mod->index = tr.numModels; tr.models[tr.numModels] = mod; tr.numModels++; @@ -255,15 +237,13 @@ model_t *R_AllocModel( void ) { return mod; } -static qhandle_t RE_RegisterBSP(const char *name) -{ +static qhandle_t RE_RegisterBSP(const char *name) { char bspFilePath[MAX_QPATH]; Com_sprintf(bspFilePath, sizeof(bspFilePath), "maps/%s.bsp", name + 1); int bspIndex; world_t *world = R_LoadBSP(bspFilePath, &bspIndex); - if (world == nullptr) - { + if (world == nullptr) { return 0; } @@ -271,8 +251,7 @@ static qhandle_t RE_RegisterBSP(const char *name) Com_sprintf(bspModelIdent, sizeof(bspModelIdent), "*%d-0", bspIndex); qhandle_t modelHandle = CModelCache->GetModelHandle(bspModelIdent); - if (modelHandle == -1) - { + if (modelHandle == -1) { return 0; } @@ -291,51 +270,48 @@ optimization to prevent disk rescanning if they are asked for again. ==================== */ -qhandle_t RE_RegisterModel( const char *name ) { - model_t *mod; - qhandle_t hModel; - qboolean orgNameFailed = qfalse; - int orgLoader = -1; - int i; - char localName[ MAX_QPATH ]; - const char *ext; - char altName[ MAX_QPATH ]; - - if ( !name || !name[0] ) { - ri.Printf( PRINT_ALL, "RE_RegisterModel: NULL name\n" ); +qhandle_t RE_RegisterModel(const char *name) { + model_t *mod; + qhandle_t hModel; + qboolean orgNameFailed = qfalse; + int orgLoader = -1; + int i; + char localName[MAX_QPATH]; + const char *ext; + char altName[MAX_QPATH]; + + if (!name || !name[0]) { + ri.Printf(PRINT_ALL, "RE_RegisterModel: NULL name\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Model name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Model name exceeds MAX_QPATH\n"); return 0; } // search the currently loaded models - if( ( hModel = CModelCache->GetModelHandle( name ) ) != -1 ) + if ((hModel = CModelCache->GetModelHandle(name)) != -1) return hModel; - if ( name[0] == '*' ) - { - if ( strcmp (name, "*default.gla") != 0 ) - { + if (name[0] == '*') { + if (strcmp(name, "*default.gla") != 0) { return 0; } } - if( name[0] == '#' ) - { + if (name[0] == '#') { return RE_RegisterBSP(name); } // allocate a new model_t - if ( ( mod = R_AllocModel() ) == NULL ) { - ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + if ((mod = R_AllocModel()) == NULL) { + ri.Printf(PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); R_IssuePendingRenderCommands(); @@ -345,38 +321,31 @@ qhandle_t RE_RegisterModel( const char *name ) { // // load the files // - Q_strncpyz( localName, name, MAX_QPATH ); + Q_strncpyz(localName, name, MAX_QPATH); - ext = COM_GetExtension( localName ); + ext = COM_GetExtension(localName); - if( *ext ) - { + if (*ext) { // Look for the correct loader and use it - for( i = 0; i < numModelLoaders; i++ ) - { - if( !Q_stricmp( ext, modelLoaders[ i ].ext ) ) - { + for (i = 0; i < numModelLoaders; i++) { + if (!Q_stricmp(ext, modelLoaders[i].ext)) { // Load - hModel = modelLoaders[ i ].ModelLoader( localName, mod ); + hModel = modelLoaders[i].ModelLoader(localName, mod); break; } } // A loader was found - if( i < numModelLoaders ) - { - if( !hModel ) - { + if (i < numModelLoaders) { + if (!hModel) { // Loader failed, most likely because the file isn't there; // try again without the extension orgNameFailed = qtrue; orgLoader = i; - COM_StripExtension( name, localName, MAX_QPATH ); - } - else - { + COM_StripExtension(name, localName, MAX_QPATH); + } else { // Something loaded - CModelCache->InsertModelHandle( name, hModel ); + CModelCache->InsertModelHandle(name, hModel); return mod->index; } } @@ -384,86 +353,80 @@ qhandle_t RE_RegisterModel( const char *name ) { // Try and find a suitable match using all // the model formats supported - for( i = 0; i < numModelLoaders; i++ ) - { + for (i = 0; i < numModelLoaders; i++) { if (i == orgLoader) continue; - Com_sprintf( altName, sizeof (altName), "%s.%s", localName, modelLoaders[ i ].ext ); + Com_sprintf(altName, sizeof(altName), "%s.%s", localName, modelLoaders[i].ext); // Load - hModel = modelLoaders[ i ].ModelLoader( altName, mod ); - - if( hModel ) - { - if( orgNameFailed ) - { - ri.Printf( PRINT_DEVELOPER, "WARNING: %s not present, using %s instead\n", - name, altName ); + hModel = modelLoaders[i].ModelLoader(altName, mod); + + if (hModel) { + if (orgNameFailed) { + ri.Printf(PRINT_DEVELOPER, "WARNING: %s not present, using %s instead\n", name, altName); } break; } } - CModelCache->InsertModelHandle( name, hModel ); + CModelCache->InsertModelHandle(name, hModel); return hModel; } -//rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. -//You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated -//server is running, which is the entire point of having these seperate functions. If anything major -//is changed in the non-server-only versions of these functions it would be wise to incorporate it -//here as well. +// rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. +// You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated +// server is running, which is the entire point of having these seperate functions. If anything major +// is changed in the non-server-only versions of these functions it would be wise to incorporate it +// here as well. /* ================= R_LoadMDXA_Server - load a Ghoul 2 animation file ================= */ -qboolean R_LoadMDXA_Server( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean R_LoadMDXA_Server(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... - // + // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } - + if (version != MDXA_VERSION) { return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxa = (mdxaHeader_t*)CModelCache->Allocate( size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA ); + mdxa = (mdxaHeader_t *)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); mod->data.gla = mdxa; - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { - // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the + if (!bAlreadyFound) { + // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... // // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); -// memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxa == buffer); + // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing LL(mdxa->ident); LL(mdxa->version); @@ -473,13 +436,12 @@ qboolean R_LoadMDXA_Server( model_t *mod, void *buffer, const char *mod_name, qb LL(mdxa->ofsEnd); } - if ( mdxa->numFrames < 1 ) { + if (mdxa->numFrames < 1) { return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } return qtrue; @@ -490,25 +452,24 @@ qboolean R_LoadMDXA_Server( model_t *mod, void *buffer, const char *mod_name, qb R_LoadMDXM_Server - load a Ghoul 2 Mesh file ================= */ -qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - //shader_t *sh; - mdxmSurfHierarchy_t *surfInfo; - - pinmodel= (mdxmHeader_t *)buffer; +qboolean R_LoadMDXM_Server(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + // shader_t *sh; + mdxmSurfHierarchy_t *surfInfo; + + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... - // + // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } @@ -517,27 +478,26 @@ qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qb return qfalse; } - mod->type = MOD_MDXM; - mod->dataSize += size; - + mod->type = MOD_MDXM; + mod->dataSize += size; + qboolean bAlreadyFound = qfalse; - mdxm = (mdxmHeader_t*)CModelCache->Allocate( size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM ); - mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc (sizeof (mdxmData_t), h_low); + mdxm = (mdxmHeader_t *)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc(sizeof(mdxmData_t), h_low); mod->data.glm->header = mdxm; - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { - // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the + if (!bAlreadyFound) { + // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... // // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -547,56 +507,50 @@ qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qb LL(mdxm->ofsSurfHierarchy); LL(mdxm->ofsEnd); } - + // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterServerModel(va ("%s.gla",mdxm->animName)); - if (!mdxm->animIndex) - { + mdxm->animIndex = RE_RegisterServerModel(va("%s.gla", mdxm->animName)); + if (!mdxm->animIndex) { return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->numChildren); LL(surfInfo->parentIndex); // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } // We will not be using shaders on the server. - //sh = 0; + // sh = 0; // insert it in the surface list - + surfInfo->shaderIndex = 0; CModelCache->StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } - + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } + // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->numTriangles); LL(surf->ofsTriangles); LL(surf->numVerts); @@ -605,28 +559,28 @@ qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qb LL(surf->ofsHeader); LL(surf->numBoneReferences); LL(surf->ofsBoneReferences); -// LL(surf->maxVertBoneWeights); + // LL(surf->maxVertBoneWeights); triCount += surf->numTriangles; - - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { + + if (surf->numVerts > SHADER_MAX_VERTEXES) { return qfalse; } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { return qfalse; } - + // change to surface identifier surf->ident = SF_MDX; // register the shaders // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; @@ -637,14 +591,13 @@ qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qb R_RegisterMDX_Server ==================== */ -qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) -{ - unsigned *buf; - int lod; - int ident; - qboolean loaded = qfalse; - int numLoaded; - char filename[MAX_QPATH], namebuf[MAX_QPATH+20]; +qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) { + unsigned *buf; + int lod; + int ident; + qboolean loaded = qfalse; + int numLoaded; + char filename[MAX_QPATH], namebuf[MAX_QPATH + 20]; char *fext, defex[] = "md3"; numLoaded = 0; @@ -652,57 +605,50 @@ qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) strcpy(filename, name); fext = strchr(filename, '.'); - if(!fext) + if (!fext) fext = defex; - else - { + else { *fext = '\0'; fext++; } - for (lod = MD3_MAX_LODS - 1 ; lod >= 0 ; lod--) - { - if(lod) + for (lod = MD3_MAX_LODS - 1; lod >= 0; lod--) { + if (lod) Com_sprintf(namebuf, sizeof(namebuf), "%s_%d.%s", filename, lod, fext); else Com_sprintf(namebuf, sizeof(namebuf), "%s.%s", filename, fext); qboolean bAlreadyCached = qfalse; - if( !CModelCache->LoadFile( namebuf, (void**)&buf, &bAlreadyCached ) ) + if (!CModelCache->LoadFile(namebuf, (void **)&buf, &bAlreadyCached)) continue; ident = *(unsigned *)buf; - if( !bAlreadyCached ) + if (!bAlreadyCached) LL(ident); - - switch(ident) - { - case MDXA_IDENT: - loaded = R_LoadMDXA_Server(mod, buf, namebuf, bAlreadyCached); - break; - case MDXM_IDENT: - loaded = R_LoadMDXM_Server(mod, buf, namebuf, bAlreadyCached); - break; - default: - //ri.Printf(PRINT_WARNING, "R_RegisterMDX_Server: unknown ident for %s\n", name); - break; + + switch (ident) { + case MDXA_IDENT: + loaded = R_LoadMDXA_Server(mod, buf, namebuf, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = R_LoadMDXM_Server(mod, buf, namebuf, bAlreadyCached); + break; + default: + // ri.Printf(PRINT_WARNING, "R_RegisterMDX_Server: unknown ident for %s\n", name); + break; } - if(loaded) - { + if (loaded) { mod->numLods++; numLoaded++; - } - else + } else break; } - if(numLoaded) - { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for(lod--; lod >= 0; lod--) - { + for (lod--; lod >= 0; lod--) { mod->numLods++; mod->data.mdv[lod] = mod->data.mdv[lod + 1]; } @@ -710,9 +656,9 @@ qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) return mod->index; } -/*#ifdef _DEBUG - ri.Printf(PRINT_WARNING,"R_RegisterMDX_Server: couldn't load %s\n", name); -#endif*/ + /*#ifdef _DEBUG + ri.Printf(PRINT_WARNING,"R_RegisterMDX_Server: couldn't load %s\n", name); + #endif*/ mod->type = MOD_BAD; return 0; @@ -720,13 +666,12 @@ qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) // Note that the ordering indicates the order of preference used // when there are multiple models of different formats available -static modelExtToLoaderMap_t serverModelLoaders[ ] = -{ - /* +static modelExtToLoaderMap_t serverModelLoaders[] = { + /* Ghoul 2 Insert Start */ - { "glm", R_RegisterMDX_Server }, - { "gla", R_RegisterMDX_Server }, + {"glm", R_RegisterMDX_Server}, + {"gla", R_RegisterMDX_Server}, /* Ghoul 2 Insert End */ @@ -734,46 +679,44 @@ static modelExtToLoaderMap_t serverModelLoaders[ ] = static int numServerModelLoaders = ARRAY_LEN(serverModelLoaders); -qhandle_t RE_RegisterServerModel( const char *name ) { - model_t *mod; - qhandle_t hModel; - int i; - char localName[ MAX_QPATH ]; - const char *ext; +qhandle_t RE_RegisterServerModel(const char *name) { + model_t *mod; + qhandle_t hModel; + int i; + char localName[MAX_QPATH]; + const char *ext; - if (!r_noServerGhoul2) - { //keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing though. - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", 0, ""); + if (!r_noServerGhoul2) { // keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing + // though. + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", 0, ""); } - if ( !name || !name[0] ) { + if (!name || !name[0]) { return 0; } - if ( strlen( name ) >= MAX_QPATH ) { + if (strlen(name) >= MAX_QPATH) { return 0; } // search the currently loaded models - if( ( hModel = CModelCache->GetModelHandle( name ) ) != -1 ) + if ((hModel = CModelCache->GetModelHandle(name)) != -1) return hModel; - if ( name[0] == '*' ) - { - if ( strcmp (name, "*default.gla") != 0 ) - { + if (name[0] == '*') { + if (strcmp(name, "*default.gla") != 0) { return 0; } } // allocate a new model_t - if ( ( mod = R_AllocModel() ) == NULL ) { - ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + if ((mod = R_AllocModel()) == NULL) { + ri.Printf(PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); R_IssuePendingRenderCommands(); @@ -783,36 +726,31 @@ qhandle_t RE_RegisterServerModel( const char *name ) { // // load the files // - Q_strncpyz( localName, name, MAX_QPATH ); + Q_strncpyz(localName, name, MAX_QPATH); - ext = COM_GetExtension( localName ); + ext = COM_GetExtension(localName); - if( *ext ) - { + if (*ext) { // Look for the correct loader and use it - for( i = 0; i < numServerModelLoaders; i++ ) - { - if( !Q_stricmp( ext, serverModelLoaders[ i ].ext ) ) - { + for (i = 0; i < numServerModelLoaders; i++) { + if (!Q_stricmp(ext, serverModelLoaders[i].ext)) { // Load - hModel = serverModelLoaders[ i ].ModelLoader( localName, mod ); + hModel = serverModelLoaders[i].ModelLoader(localName, mod); break; } } // A loader was found - if( i < numServerModelLoaders ) - { - if( hModel ) - { + if (i < numServerModelLoaders) { + if (hModel) { // Something loaded - CModelCache->InsertModelHandle( name, hModel ); + CModelCache->InsertModelHandle(name, hModel); return mod->index; } } } - CModelCache->InsertModelHandle( name, hModel ); + CModelCache->InsertModelHandle(name, hModel); return hModel; } @@ -821,37 +759,35 @@ qhandle_t RE_RegisterServerModel( const char *name ) { R_LoadMD3 ================= */ -static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modName) -{ - int i, j; - - md3Header_t *md3Model; - md3Frame_t *md3Frame; - md3Surface_t *md3Surf; - md3Shader_t *md3Shader; - md3Triangle_t *md3Tri; - md3St_t *md3st; +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *modName) { + int i, j; + + md3Header_t *md3Model; + md3Frame_t *md3Frame; + md3Surface_t *md3Surf; + md3Shader_t *md3Shader; + md3Triangle_t *md3Tri; + md3St_t *md3st; md3XyzNormal_t *md3xyz; - md3Tag_t *md3Tag; + md3Tag_t *md3Tag; - mdvModel_t *mdvModel; - mdvFrame_t *frame; - mdvSurface_t *surf;//, *surface; - int *shaderIndex; - glIndex_t *tri; - mdvVertex_t *v; - mdvSt_t *st; - mdvTag_t *tag; - mdvTagName_t *tagName; + mdvModel_t *mdvModel; + mdvFrame_t *frame; + mdvSurface_t *surf; //, *surface; + int *shaderIndex; + glIndex_t *tri; + mdvVertex_t *v; + mdvSt_t *st; + mdvTag_t *tag; + mdvTagName_t *tagName; - int version; - int size; + int version; + int size; - md3Model = (md3Header_t *) buffer; + md3Model = (md3Header_t *)buffer; version = LittleLong(md3Model->version); - if(version != MD3_VERSION) - { + if (version != MD3_VERSION) { ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has wrong version (%i should be %i)\n", modName, version, MD3_VERSION); return qfalse; } @@ -859,14 +795,13 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN mod->type = MOD_MESH; size = LittleLong(md3Model->ofsEnd); mod->dataSize += size; - //mdvModel = mod->mdv[lod] = (mdvModel_t *)ri.Hunk_Alloc(sizeof(mdvModel_t), h_low); + // mdvModel = mod->mdv[lod] = (mdvModel_t *)ri.Hunk_Alloc(sizeof(mdvModel_t), h_low); qboolean bAlreadyFound = qfalse; md3Model = (md3Header_t *)CModelCache->Allocate(size, buffer, modName, &bAlreadyFound, TAG_MODEL_MD3); mdvModel = mod->data.mdv[lod] = (mdvModel_t *)ri.Hunk_Alloc(sizeof(*mdvModel), h_low); -// Com_Memcpy(mod->md3[lod], buffer, LittleLong(md3Model->ofsEnd)); - if( !bAlreadyFound ) - { // HACK + // Com_Memcpy(mod->md3[lod], buffer, LittleLong(md3Model->ofsEnd)); + if (!bAlreadyFound) { // HACK LL(md3Model->ident); LL(md3Model->version); LL(md3Model->numFrames); @@ -876,14 +811,11 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN LL(md3Model->ofsTags); LL(md3Model->ofsSurfaces); LL(md3Model->ofsEnd); - } - else - { - CModelCache->AllocateShaders( modName ); + } else { + CModelCache->AllocateShaders(modName); } - if(md3Model->numFrames < 1) - { + if (md3Model->numFrames < 1) { ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has no frames\n", modName); return qfalse; } @@ -892,12 +824,10 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN mdvModel->numFrames = md3Model->numFrames; mdvModel->frames = frame = (mdvFrame_t *)ri.Hunk_Alloc(sizeof(*frame) * md3Model->numFrames, h_low); - md3Frame = (md3Frame_t *) ((byte *) md3Model + md3Model->ofsFrames); - for(i = 0; i < md3Model->numFrames; i++, frame++, md3Frame++) - { + md3Frame = (md3Frame_t *)((byte *)md3Model + md3Model->ofsFrames); + for (i = 0; i < md3Model->numFrames; i++, frame++, md3Frame++) { frame->radius = LittleFloat(md3Frame->radius); - for(j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { frame->bounds[0][j] = LittleFloat(md3Frame->bounds[0][j]); frame->bounds[1][j] = LittleFloat(md3Frame->bounds[1][j]); frame->localOrigin[j] = LittleFloat(md3Frame->localOrigin[j]); @@ -908,11 +838,9 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN mdvModel->numTags = md3Model->numTags; mdvModel->tags = tag = (mdvTag_t *)ri.Hunk_Alloc(sizeof(*tag) * (md3Model->numTags * md3Model->numFrames), h_low); - md3Tag = (md3Tag_t *) ((byte *) md3Model + md3Model->ofsTags); - for(i = 0; i < md3Model->numTags * md3Model->numFrames; i++, tag++, md3Tag++) - { - for(j = 0; j < 3; j++) - { + md3Tag = (md3Tag_t *)((byte *)md3Model + md3Model->ofsTags); + for (i = 0; i < md3Model->numTags * md3Model->numFrames; i++, tag++, md3Tag++) { + for (j = 0; j < 3; j++) { tag->origin[j] = LittleFloat(md3Tag->origin[j]); tag->axis[0][j] = LittleFloat(md3Tag->axis[0][j]); tag->axis[1][j] = LittleFloat(md3Tag->axis[1][j]); @@ -920,12 +848,10 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN } } - mdvModel->tagNames = tagName = (mdvTagName_t *)ri.Hunk_Alloc(sizeof(*tagName) * (md3Model->numTags), h_low); - md3Tag = (md3Tag_t *) ((byte *) md3Model + md3Model->ofsTags); - for(i = 0; i < md3Model->numTags; i++, tagName++, md3Tag++) - { + md3Tag = (md3Tag_t *)((byte *)md3Model + md3Model->ofsTags); + for (i = 0; i < md3Model->numTags; i++, tagName++, md3Tag++) { Q_strncpyz(tagName->name, md3Tag->name, sizeof(tagName->name)); } @@ -933,9 +859,8 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN mdvModel->numSurfaces = md3Model->numSurfaces; mdvModel->surfaces = surf = (mdvSurface_t *)ri.Hunk_Alloc(sizeof(*surf) * md3Model->numSurfaces, h_low); - md3Surf = (md3Surface_t *) ((byte *) md3Model + md3Model->ofsSurfaces); - for(i = 0; i < md3Model->numSurfaces; i++) - { + md3Surf = (md3Surface_t *)((byte *)md3Model + md3Model->ofsSurfaces); + for (i = 0; i < md3Model->numSurfaces; i++) { LL(md3Surf->ident); LL(md3Surf->flags); LL(md3Surf->numFrames); @@ -948,18 +873,14 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN LL(md3Surf->ofsXyzNormals); LL(md3Surf->ofsEnd); - if(md3Surf->numVerts >= SHADER_MAX_VERTEXES) - { - ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i verts on %s (%i).\n", - modName, SHADER_MAX_VERTEXES - 1, md3Surf->name[0] ? md3Surf->name : "a surface", - md3Surf->numVerts ); + if (md3Surf->numVerts >= SHADER_MAX_VERTEXES) { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i verts on %s (%i).\n", modName, SHADER_MAX_VERTEXES - 1, + md3Surf->name[0] ? md3Surf->name : "a surface", md3Surf->numVerts); return qfalse; } - if(md3Surf->numTriangles * 3 >= SHADER_MAX_INDEXES) - { - ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i triangles on %s (%i).\n", - modName, ( SHADER_MAX_INDEXES / 3 ) - 1, md3Surf->name[0] ? md3Surf->name : "a surface", - md3Surf->numTriangles ); + if (md3Surf->numTriangles * 3 >= SHADER_MAX_INDEXES) { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i triangles on %s (%i).\n", modName, (SHADER_MAX_INDEXES / 3) - 1, + md3Surf->name[0] ? md3Surf->name : "a surface", md3Surf->numTriangles); return qfalse; } @@ -978,8 +899,7 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN // strip off a trailing _1 or _2 // this is a crutch for q3data being a mess j = strlen(surf->name); - if(j > 2 && surf->name[j - 2] == '_') - { + if (j > 2 && surf->name[j - 2] == '_') { surf->name[j - 2] = 0; } @@ -987,18 +907,14 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN surf->numShaderIndexes = md3Surf->numShaders; surf->shaderIndexes = shaderIndex = (int *)ri.Hunk_Alloc(sizeof(*shaderIndex) * md3Surf->numShaders, h_low); - md3Shader = (md3Shader_t *) ((byte *) md3Surf + md3Surf->ofsShaders); - for(j = 0; j < md3Surf->numShaders; j++, shaderIndex++, md3Shader++) - { - shader_t *sh; + md3Shader = (md3Shader_t *)((byte *)md3Surf + md3Surf->ofsShaders); + for (j = 0; j < md3Surf->numShaders; j++, shaderIndex++, md3Shader++) { + shader_t *sh; sh = R_FindShader(md3Shader->name, lightmapsNone, stylesDefault, qtrue); - if(sh->defaultShader) - { + if (sh->defaultShader) { *shaderIndex = 0; - } - else - { + } else { *shaderIndex = sh->index; } } @@ -1007,9 +923,8 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN surf->numIndexes = md3Surf->numTriangles * 3; surf->indexes = tri = (glIndex_t *)ri.Hunk_Alloc(sizeof(*tri) * 3 * md3Surf->numTriangles, h_low); - md3Tri = (md3Triangle_t *) ((byte *) md3Surf + md3Surf->ofsTriangles); - for(j = 0; j < md3Surf->numTriangles; j++, tri += 3, md3Tri++) - { + md3Tri = (md3Triangle_t *)((byte *)md3Surf + md3Surf->ofsTriangles); + for (j = 0; j < md3Surf->numTriangles; j++, tri += 3, md3Tri++) { tri[0] = LittleLong(md3Tri->indexes[0]); tri[1] = LittleLong(md3Tri->indexes[1]); tri[2] = LittleLong(md3Tri->indexes[2]); @@ -1019,9 +934,8 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN surf->numVerts = md3Surf->numVerts; surf->verts = v = (mdvVertex_t *)ri.Hunk_Alloc(sizeof(*v) * (md3Surf->numVerts * md3Surf->numFrames), h_low); - md3xyz = (md3XyzNormal_t *) ((byte *) md3Surf + md3Surf->ofsXyzNormals); - for(j = 0; j < md3Surf->numVerts * md3Surf->numFrames; j++, md3xyz++, v++) - { + md3xyz = (md3XyzNormal_t *)((byte *)md3Surf + md3Surf->ofsXyzNormals); + for (j = 0; j < md3Surf->numVerts * md3Surf->numFrames; j++, md3xyz++, v++) { unsigned lat, lng; unsigned short normal; @@ -1031,32 +945,31 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN normal = LittleShort(md3xyz->normal); - lat = ( normal >> 8 ) & 0xff; - lng = ( normal & 0xff ); - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat = (normal >> 8) & 0xff; + lng = (normal & 0xff); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) // decode Z as cos( long ) - v->normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + v->normal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; v->normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - v->normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + v->normal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; } // swap all the ST surf->st = st = (mdvSt_t *)ri.Hunk_Alloc(sizeof(*st) * md3Surf->numVerts, h_low); - md3st = (md3St_t *) ((byte *) md3Surf + md3Surf->ofsSt); - for(j = 0; j < md3Surf->numVerts; j++, md3st++, st++) - { + md3st = (md3St_t *)((byte *)md3Surf + md3Surf->ofsSt); + for (j = 0; j < md3Surf->numVerts; j++, md3st++, st++) { st->st[0] = LittleFloat(md3st->st[0]); st->st[1] = LittleFloat(md3st->st[1]); } // find the next surface - md3Surf = (md3Surface_t *) ((byte *) md3Surf + md3Surf->ofsEnd); + md3Surf = (md3Surface_t *)((byte *)md3Surf + md3Surf->ofsEnd); surf++; } @@ -1086,8 +999,7 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN int *indexOffsets = (int *)ri.Hunk_AllocateTempMemory(sizeof(int) * mdvModel->numSurfaces); // Calculate the required size of the vertex buffer. - for (int n = 0; n < mdvModel->numSurfaces; n++, surf++) - { + for (int n = 0; n < mdvModel->numSurfaces; n++, surf++) { baseVertexes[n] = numVerts; indexOffsets[n] = numIndexes; @@ -1125,26 +1037,18 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN glIndex_t *index = indices; surf = mdvModel->surfaces; - for (i = 0; i < mdvModel->numSurfaces; i++, surf++) - { + for (i = 0; i < mdvModel->numSurfaces; i++, surf++) { uint32_t *tangentsf = (uint32_t *)ri.Hunk_AllocateTempMemory(sizeof(uint32_t) * surf->numVerts); - R_CalcMikkTSpaceMD3Surface( - surf->numIndexes / 3, - surf->verts, - tangentsf, - surf->st, - surf->indexes); - - for (int k = 0; k < surf->numIndexes; k++) - { + R_CalcMikkTSpaceMD3Surface(surf->numIndexes / 3, surf->verts, tangentsf, surf->st, surf->indexes); + + for (int k = 0; k < surf->numIndexes; k++) { *index = surf->indexes[k] + baseVertexes[i]; assert(*index >= 0 && *index < numVerts); index++; } v = surf->verts; - for (j = 0; j < surf->numVerts; j++, v++) - { + for (j = 0; j < surf->numVerts; j++, v++) { VectorCopy(v->xyz, *verts); *normals = R_VboPackNormal(v->normal); *tangents = tangentsf[j]; @@ -1188,8 +1092,7 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN vbo->sizes[ATTR_INDEX_TANGENT] = sizeof(*tangents); surf = mdvModel->surfaces; - for (i = 0; i < mdvModel->numSurfaces; i++, surf++, vboSurf++) - { + for (i = 0; i < mdvModel->numSurfaces; i++, surf++, vboSurf++) { vboSurf->surfaceType = SF_VBO_MDVMESH; vboSurf->mdvModel = mdvModel; vboSurf->mdvSurface = surf; @@ -1210,44 +1113,39 @@ static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modN return qtrue; } - - /* ================= R_LoadMDR ================= */ -static qboolean R_LoadMDR( model_t *mod, void *buffer, int filesize, const char *mod_name ) -{ - int i, j, k, l; - mdrHeader_t *pinmodel, *mdr; - mdrFrame_t *frame; - mdrLOD_t *lod, *curlod; - mdrSurface_t *surf, *cursurf; - mdrTriangle_t *tri, *curtri; - mdrVertex_t *v, *curv; - mdrWeight_t *weight, *curweight; - mdrTag_t *tag, *curtag; - int size; - shader_t *sh; +static qboolean R_LoadMDR(model_t *mod, void *buffer, int filesize, const char *mod_name) { + int i, j, k, l; + mdrHeader_t *pinmodel, *mdr; + mdrFrame_t *frame; + mdrLOD_t *lod, *curlod; + mdrSurface_t *surf, *cursurf; + mdrTriangle_t *tri, *curtri; + mdrVertex_t *v, *curv; + mdrWeight_t *weight, *curweight; + mdrTag_t *tag, *curtag; + int size; + shader_t *sh; pinmodel = (mdrHeader_t *)buffer; pinmodel->version = LittleLong(pinmodel->version); - if (pinmodel->version != MDR_VERSION) - { + if (pinmodel->version != MDR_VERSION) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has wrong version (%i should be %i)\n", mod_name, pinmodel->version, MDR_VERSION); return qfalse; } size = LittleLong(pinmodel->ofsEnd); - - if(size > filesize) - { + + if (size > filesize) { ri.Printf(PRINT_WARNING, "R_LoadMDR: Header of %s is broken. Wrong filesize declared!\n", mod_name); return qfalse; } - + mod->type = MOD_MDR; LL(pinmodel->numFrames); @@ -1256,29 +1154,26 @@ static qboolean R_LoadMDR( model_t *mod, void *buffer, int filesize, const char // This is a model that uses some type of compressed Bones. We don't want to uncompress every bone for each rendered frame // over and over again, we'll uncompress it in this function already, so we must adjust the size of the target mdr. - if(pinmodel->ofsFrames < 0) - { + if (pinmodel->ofsFrames < 0) { // mdrFrame_t is larger than mdrCompFrame_t: size += pinmodel->numFrames * sizeof(frame->name); // now add enough space for the uncompressed bones. size += pinmodel->numFrames * pinmodel->numBones * ((sizeof(mdrBone_t) - sizeof(mdrCompBone_t))); } - + // simple bounds check - if(pinmodel->numBones < 0 || - sizeof(*mdr) + pinmodel->numFrames * (sizeof(*frame) + (pinmodel->numBones - 1) * sizeof(*frame->bones)) > size) - { + if (pinmodel->numBones < 0 || sizeof(*mdr) + pinmodel->numFrames * (sizeof(*frame) + (pinmodel->numBones - 1) * sizeof(*frame->bones)) > size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } mod->dataSize += size; - mod->data.mdr = mdr = (mdrHeader_t*)ri.Hunk_Alloc( size, h_low ); + mod->data.mdr = mdr = (mdrHeader_t *)ri.Hunk_Alloc(size, h_low); // Copy all the values over from the file and fix endian issues in the process, if necessary. - + mdr->ident = LittleLong(pinmodel->ident); - mdr->version = pinmodel->version; // Don't need to swap byte order on this one, we already did above. + mdr->version = pinmodel->version; // Don't need to swap byte order on this one, we already did above. Q_strncpyz(mdr->name, pinmodel->name, sizeof(mdr->name)); mdr->numFrames = pinmodel->numFrames; mdr->numBones = pinmodel->numBones; @@ -1288,170 +1183,148 @@ static qboolean R_LoadMDR( model_t *mod, void *buffer, int filesize, const char mod->numLods = mdr->numLODs; - if ( mdr->numFrames < 1 ) - { + if (mdr->numFrames < 1) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has no frames\n", mod_name); return qfalse; } /* The first frame will be put into the first free space after the header */ frame = (mdrFrame_t *)(mdr + 1); - mdr->ofsFrames = (int)((byte *) frame - (byte *) mdr); - - if (pinmodel->ofsFrames < 0) - { + mdr->ofsFrames = (int)((byte *)frame - (byte *)mdr); + + if (pinmodel->ofsFrames < 0) { mdrCompFrame_t *cframe; - - // compressed model... - cframe = (mdrCompFrame_t *)((byte *) pinmodel - pinmodel->ofsFrames); - - for(i = 0; i < mdr->numFrames; i++) - { - for(j = 0; j < 3; j++) - { + + // compressed model... + cframe = (mdrCompFrame_t *)((byte *)pinmodel - pinmodel->ofsFrames); + + for (i = 0; i < mdr->numFrames; i++) { + for (j = 0; j < 3; j++) { frame->bounds[0][j] = LittleFloat(cframe->bounds[0][j]); frame->bounds[1][j] = LittleFloat(cframe->bounds[1][j]); frame->localOrigin[j] = LittleFloat(cframe->localOrigin[j]); } frame->radius = LittleFloat(cframe->radius); - frame->name[0] = '\0'; // No name supplied in the compressed version. - - for(j = 0; j < mdr->numBones; j++) - { - for(k = 0; k < (sizeof(cframe->bones[j].Comp) / 2); k++) - { + frame->name[0] = '\0'; // No name supplied in the compressed version. + + for (j = 0; j < mdr->numBones; j++) { + for (k = 0; k < (sizeof(cframe->bones[j].Comp) / 2); k++) { // Do swapping for the uncompressing functions. They seem to use shorts // values only, so I assume this will work. Never tested it on other // platforms, though. - - ((unsigned short *)(cframe->bones[j].Comp))[k] = - LittleShort( ((unsigned short *)(cframe->bones[j].Comp))[k] ); + + ((unsigned short *)(cframe->bones[j].Comp))[k] = LittleShort(((unsigned short *)(cframe->bones[j].Comp))[k]); } - + /* Now do the actual uncompressing */ MC_UnCompress(frame->bones[j].matrix, cframe->bones[j].Comp); } - + // Next Frame... - cframe = (mdrCompFrame_t *) &cframe->bones[j]; - frame = (mdrFrame_t *) &frame->bones[j]; + cframe = (mdrCompFrame_t *)&cframe->bones[j]; + frame = (mdrFrame_t *)&frame->bones[j]; } - } - else - { + } else { mdrFrame_t *curframe; - + // uncompressed model... // - - curframe = (mdrFrame_t *)((byte *) pinmodel + pinmodel->ofsFrames); - + + curframe = (mdrFrame_t *)((byte *)pinmodel + pinmodel->ofsFrames); + // swap all the frames - for ( i = 0 ; i < mdr->numFrames ; i++) - { - for(j = 0; j < 3; j++) - { + for (i = 0; i < mdr->numFrames; i++) { + for (j = 0; j < 3; j++) { frame->bounds[0][j] = LittleFloat(curframe->bounds[0][j]); frame->bounds[1][j] = LittleFloat(curframe->bounds[1][j]); frame->localOrigin[j] = LittleFloat(curframe->localOrigin[j]); } - + frame->radius = LittleFloat(curframe->radius); Q_strncpyz(frame->name, curframe->name, sizeof(frame->name)); - - for (j = 0; j < (int) (mdr->numBones * sizeof(mdrBone_t) / 4); j++) - { - ((float *)frame->bones)[j] = LittleFloat( ((float *)curframe->bones)[j] ); + + for (j = 0; j < (int)(mdr->numBones * sizeof(mdrBone_t) / 4); j++) { + ((float *)frame->bones)[j] = LittleFloat(((float *)curframe->bones)[j]); } - - curframe = (mdrFrame_t *) &curframe->bones[mdr->numBones]; - frame = (mdrFrame_t *) &frame->bones[mdr->numBones]; + + curframe = (mdrFrame_t *)&curframe->bones[mdr->numBones]; + frame = (mdrFrame_t *)&frame->bones[mdr->numBones]; } } - + // frame should now point to the first free address after all frames. - lod = (mdrLOD_t *) frame; - mdr->ofsLODs = (int) ((byte *) lod - (byte *)mdr); - - curlod = (mdrLOD_t *)((byte *) pinmodel + LittleLong(pinmodel->ofsLODs)); - + lod = (mdrLOD_t *)frame; + mdr->ofsLODs = (int)((byte *)lod - (byte *)mdr); + + curlod = (mdrLOD_t *)((byte *)pinmodel + LittleLong(pinmodel->ofsLODs)); + // swap all the LOD's - for ( l = 0 ; l < mdr->numLODs ; l++) - { + for (l = 0; l < mdr->numLODs; l++) { // simple bounds check - if((byte *) (lod + 1) > (byte *) mdr + size) - { + if ((byte *)(lod + 1) > (byte *)mdr + size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } lod->numSurfaces = LittleLong(curlod->numSurfaces); - + // swap all the surfaces - surf = (mdrSurface_t *) (lod + 1); - lod->ofsSurfaces = (int)((byte *) surf - (byte *) lod); - cursurf = (mdrSurface_t *) ((byte *)curlod + LittleLong(curlod->ofsSurfaces)); - - for ( i = 0 ; i < lod->numSurfaces ; i++) - { + surf = (mdrSurface_t *)(lod + 1); + lod->ofsSurfaces = (int)((byte *)surf - (byte *)lod); + cursurf = (mdrSurface_t *)((byte *)curlod + LittleLong(curlod->ofsSurfaces)); + + for (i = 0; i < lod->numSurfaces; i++) { // simple bounds check - if((byte *) (surf + 1) > (byte *) mdr + size) - { + if ((byte *)(surf + 1) > (byte *)mdr + size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } // first do some copying stuff - + surf->ident = SF_MDR; Q_strncpyz(surf->name, cursurf->name, sizeof(surf->name)); Q_strncpyz(surf->shader, cursurf->shader, sizeof(surf->shader)); - - surf->ofsHeader = (byte *) mdr - (byte *) surf; - + + surf->ofsHeader = (byte *)mdr - (byte *)surf; + surf->numVerts = LittleLong(cursurf->numVerts); surf->numTriangles = LittleLong(cursurf->numTriangles); // numBoneReferences and BoneReferences generally seem to be unused - + // now do the checks that may fail. - if ( surf->numVerts >= SHADER_MAX_VERTEXES ) - { - ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i verts on %s (%i).\n", - mod_name, SHADER_MAX_VERTEXES-1, surf->name[0] ? surf->name : "a surface", - surf->numVerts ); + if (surf->numVerts >= SHADER_MAX_VERTEXES) { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i verts on %s (%i).\n", mod_name, SHADER_MAX_VERTEXES - 1, + surf->name[0] ? surf->name : "a surface", surf->numVerts); return qfalse; } - if ( surf->numTriangles*3 >= SHADER_MAX_INDEXES ) - { - ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i triangles on %s (%i).\n", - mod_name, ( SHADER_MAX_INDEXES / 3 ) - 1, surf->name[0] ? surf->name : "a surface", - surf->numTriangles ); + if (surf->numTriangles * 3 >= SHADER_MAX_INDEXES) { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i triangles on %s (%i).\n", mod_name, (SHADER_MAX_INDEXES / 3) - 1, + surf->name[0] ? surf->name : "a surface", surf->numTriangles); return qfalse; } // lowercase the surface name so skin compares are faster - Q_strlwr( surf->name ); + Q_strlwr(surf->name); // register the shaders sh = R_FindShader(surf->shader, lightmapsNone, stylesDefault, qtrue); - if ( sh->defaultShader ) { + if (sh->defaultShader) { surf->shaderIndex = 0; } else { surf->shaderIndex = sh->index; } - + // now copy the vertexes. - v = (mdrVertex_t *) (surf + 1); - surf->ofsVerts = (int)((byte *) v - (byte *) surf); - curv = (mdrVertex_t *) ((byte *)cursurf + LittleLong(cursurf->ofsVerts)); - - for(j = 0; j < surf->numVerts; j++) - { + v = (mdrVertex_t *)(surf + 1); + surf->ofsVerts = (int)((byte *)v - (byte *)surf); + curv = (mdrVertex_t *)((byte *)cursurf + LittleLong(cursurf->ofsVerts)); + + for (j = 0; j < surf->numVerts; j++) { LL(curv->numWeights); - + // simple bounds check - if(curv->numWeights < 0 || (byte *) (v + 1) + (curv->numWeights - 1) * sizeof(*weight) > (byte *) mdr + size) - { + if (curv->numWeights < 0 || (byte *)(v + 1) + (curv->numWeights - 1) * sizeof(*weight) > (byte *)mdr + size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } @@ -1459,107 +1332,100 @@ static qboolean R_LoadMDR( model_t *mod, void *buffer, int filesize, const char v->normal[0] = LittleFloat(curv->normal[0]); v->normal[1] = LittleFloat(curv->normal[1]); v->normal[2] = LittleFloat(curv->normal[2]); - + v->texCoords[0] = LittleFloat(curv->texCoords[0]); v->texCoords[1] = LittleFloat(curv->texCoords[1]); - + v->numWeights = curv->numWeights; weight = &v->weights[0]; curweight = &curv->weights[0]; - + // Now copy all the weights - for(k = 0; k < v->numWeights; k++) - { + for (k = 0; k < v->numWeights; k++) { weight->boneIndex = LittleLong(curweight->boneIndex); weight->boneWeight = LittleFloat(curweight->boneWeight); - + weight->offset[0] = LittleFloat(curweight->offset[0]); weight->offset[1] = LittleFloat(curweight->offset[1]); weight->offset[2] = LittleFloat(curweight->offset[2]); - + weight++; curweight++; } - - v = (mdrVertex_t *) weight; - curv = (mdrVertex_t *) curweight; + + v = (mdrVertex_t *)weight; + curv = (mdrVertex_t *)curweight; } - + // we know the offset to the triangles now: - tri = (mdrTriangle_t *) v; - surf->ofsTriangles = (int)((byte *) tri - (byte *) surf); - curtri = (mdrTriangle_t *)((byte *) cursurf + LittleLong(cursurf->ofsTriangles)); - + tri = (mdrTriangle_t *)v; + surf->ofsTriangles = (int)((byte *)tri - (byte *)surf); + curtri = (mdrTriangle_t *)((byte *)cursurf + LittleLong(cursurf->ofsTriangles)); + // simple bounds check - if(surf->numTriangles < 0 || (byte *) (tri + surf->numTriangles) > (byte *) mdr + size) - { + if (surf->numTriangles < 0 || (byte *)(tri + surf->numTriangles) > (byte *)mdr + size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } - for(j = 0; j < surf->numTriangles; j++) - { + for (j = 0; j < surf->numTriangles; j++) { tri->indexes[0] = LittleLong(curtri->indexes[0]); tri->indexes[1] = LittleLong(curtri->indexes[1]); tri->indexes[2] = LittleLong(curtri->indexes[2]); - + tri++; curtri++; } - + // tri now points to the end of the surface. - surf->ofsEnd = (byte *) tri - (byte *) surf; - surf = (mdrSurface_t *) tri; + surf->ofsEnd = (byte *)tri - (byte *)surf; + surf = (mdrSurface_t *)tri; // find the next surface. - cursurf = (mdrSurface_t *) ((byte *) cursurf + LittleLong(cursurf->ofsEnd)); + cursurf = (mdrSurface_t *)((byte *)cursurf + LittleLong(cursurf->ofsEnd)); } // surf points to the next lod now. - lod->ofsEnd = (int)((byte *) surf - (byte *) lod); - lod = (mdrLOD_t *) surf; + lod->ofsEnd = (int)((byte *)surf - (byte *)lod); + lod = (mdrLOD_t *)surf; // find the next LOD. - curlod = (mdrLOD_t *)((byte *) curlod + LittleLong(curlod->ofsEnd)); + curlod = (mdrLOD_t *)((byte *)curlod + LittleLong(curlod->ofsEnd)); } - + // lod points to the first tag now, so update the offset too. - tag = (mdrTag_t *) lod; - mdr->ofsTags = (int)((byte *) tag - (byte *) mdr); - curtag = (mdrTag_t *) ((byte *)pinmodel + LittleLong(pinmodel->ofsTags)); + tag = (mdrTag_t *)lod; + mdr->ofsTags = (int)((byte *)tag - (byte *)mdr); + curtag = (mdrTag_t *)((byte *)pinmodel + LittleLong(pinmodel->ofsTags)); // simple bounds check - if(mdr->numTags < 0 || (byte *) (tag + mdr->numTags) > (byte *) mdr + size) - { + if (mdr->numTags < 0 || (byte *)(tag + mdr->numTags) > (byte *)mdr + size) { ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); return qfalse; } - - for (i = 0 ; i < mdr->numTags ; i++) - { + + for (i = 0; i < mdr->numTags; i++) { tag->boneIndex = LittleLong(curtag->boneIndex); Q_strncpyz(tag->name, curtag->name, sizeof(tag->name)); - + tag++; curtag++; } - + // And finally we know the real offset to the end. - mdr->ofsEnd = (int)((byte *) tag - (byte *) mdr); + mdr->ofsEnd = (int)((byte *)tag - (byte *)mdr); // phew! we're done. - + return qtrue; } - - //============================================================================= /* ** RE_BeginRegistration */ -void RE_BeginRegistration( glconfig_t *glconfigOut ) { +void RE_BeginRegistration(glconfig_t *glconfigOut) { R_Init(); @@ -1568,7 +1434,7 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { R_IssuePendingRenderCommands(); tr.visIndex = 0; - memset(tr.visClusters, -2, sizeof(tr.visClusters)); // force markleafs to regenerate + memset(tr.visClusters, -2, sizeof(tr.visClusters)); // force markleafs to regenerate R_ClearFlares(); RE_ClearScene(); @@ -1578,23 +1444,20 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { // NOTE: this sucks, for some reason the first stretch pic is never drawn // without this we'd see a white flash on a level load because the very // first time the level shot would not be drawn -// RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0); + // RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0); } //============================================================================= -void R_SVModelInit() -{ - R_ModelInit(); -} +void R_SVModelInit() { R_ModelInit(); } /* =============== R_ModelInit =============== */ -void R_ModelInit( void ) { - model_t *mod; +void R_ModelInit(void) { + model_t *mod; // leave a space for NULL model tr.numModels = 0; @@ -1606,8 +1469,7 @@ void R_ModelInit( void ) { } extern void KillTheShaderHashTable(void); -void RE_HunkClearCrap(void) -{ //get your dirty sticky assets off me, you damn dirty hunk! +void RE_HunkClearCrap(void) { // get your dirty sticky assets off me, you damn dirty hunk! KillTheShaderHashTable(); tr.numModels = 0; CModelCache->DeleteAll(); @@ -1615,64 +1477,59 @@ void RE_HunkClearCrap(void) tr.numSkins = 0; } - /* ================ R_Modellist_f ================ */ -void R_Modellist_f( void ) { - int i, j; - model_t *mod; - int total; - int lods; +void R_Modellist_f(void) { + int i, j; + model_t *mod; + int total; + int lods; total = 0; - for ( i = 1 ; i < tr.numModels; i++ ) { + for (i = 1; i < tr.numModels; i++) { mod = tr.models[i]; lods = 1; - for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) { - if ( mod->data.mdv[j] && mod->data.mdv[j] != mod->data.mdv[j-1] ) { + for (j = 1; j < MD3_MAX_LODS; j++) { + if (mod->data.mdv[j] && mod->data.mdv[j] != mod->data.mdv[j - 1]) { lods++; } } - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n",mod->dataSize, lods, mod->name ); + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, lods, mod->name); total += mod->dataSize; } - ri.Printf( PRINT_ALL, "%8i : Total models\n", total ); + ri.Printf(PRINT_ALL, "%8i : Total models\n", total); -#if 0 // not working right with new hunk +#if 0 // not working right with new hunk if ( tr.world ) { ri.Printf( PRINT_ALL, "\n%8i : %s\n", tr.world->dataSize, tr.world->name ); } #endif } - //============================================================================= - /* ================ R_GetTag ================ */ -static mdvTag_t *R_GetTag( mdvModel_t *mod, int frame, const char *_tagName ) { - int i; - mdvTag_t *tag; - mdvTagName_t *tagName; +static mdvTag_t *R_GetTag(mdvModel_t *mod, int frame, const char *_tagName) { + int i; + mdvTag_t *tag; + mdvTagName_t *tagName; - if ( frame >= mod->numFrames ) { + if (frame >= mod->numFrames) { // it is possible to have a bad frame while changing models, so don't error frame = mod->numFrames - 1; } tag = mod->tags + frame * mod->numTags; tagName = mod->tagNames; - for(i = 0; i < mod->numTags; i++, tag++, tagName++) - { - if(!strcmp(tagName->name, _tagName)) - { + for (i = 0; i < mod->numTags; i++, tag++, tagName++) { + if (!strcmp(tagName->name, _tagName)) { return tag; } } @@ -1680,45 +1537,40 @@ static mdvTag_t *R_GetTag( mdvModel_t *mod, int frame, const char *_tagName ) { return NULL; } -void R_GetAnimTag( mdrHeader_t *mod, int framenum, const char *tagName, mdvTag_t * dest) -{ - int i, j, k; - int frameSize; - mdrFrame_t *frame; - mdrTag_t *tag; +void R_GetAnimTag(mdrHeader_t *mod, int framenum, const char *tagName, mdvTag_t *dest) { + int i, j, k; + int frameSize; + mdrFrame_t *frame; + mdrTag_t *tag; - if ( framenum >= mod->numFrames ) - { + if (framenum >= mod->numFrames) { // it is possible to have a bad frame while changing models, so don't error framenum = mod->numFrames - 1; } tag = (mdrTag_t *)((byte *)mod + mod->ofsTags); - for ( i = 0 ; i < mod->numTags ; i++, tag++ ) - { - if ( !strcmp( tag->name, tagName ) ) - { + for (i = 0; i < mod->numTags; i++, tag++) { + if (!strcmp(tag->name, tagName)) { // uncompressed model... // - frameSize = (intptr_t)( &((mdrFrame_t *)0)->bones[ mod->numBones ] ); - frame = (mdrFrame_t *)((byte *)mod + mod->ofsFrames + framenum * frameSize ); + frameSize = (intptr_t)(&((mdrFrame_t *)0)->bones[mod->numBones]); + frame = (mdrFrame_t *)((byte *)mod + mod->ofsFrames + framenum * frameSize); - for (j = 0; j < 3; j++) - { + for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) - dest->axis[j][k]=frame->bones[tag->boneIndex].matrix[k][j]; + dest->axis[j][k] = frame->bones[tag->boneIndex].matrix[k][j]; } - dest->origin[0]=frame->bones[tag->boneIndex].matrix[0][3]; - dest->origin[1]=frame->bones[tag->boneIndex].matrix[1][3]; - dest->origin[2]=frame->bones[tag->boneIndex].matrix[2][3]; + dest->origin[0] = frame->bones[tag->boneIndex].matrix[0][3]; + dest->origin[1] = frame->bones[tag->boneIndex].matrix[1][3]; + dest->origin[2] = frame->bones[tag->boneIndex].matrix[2][3]; return; } } - AxisClear( dest->axis ); - VectorClear( dest->origin ); + AxisClear(dest->axis); + VectorClear(dest->origin); } /* @@ -1726,113 +1578,102 @@ void R_GetAnimTag( mdrHeader_t *mod, int framenum, const char *tagName, mdvTag_t R_LerpTag ================ */ -int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, - float frac, const char *tagName ) { - mdvTag_t *start, *end; - mdvTag_t start_space, end_space; - int i; - float frontLerp, backLerp; - model_t *model; - - model = R_GetModelByHandle( handle ); - if ( !model->data.mdv[0] ) - { - if(model->type == MOD_MDR) - { +int R_LerpTag(orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, float frac, const char *tagName) { + mdvTag_t *start, *end; + mdvTag_t start_space, end_space; + int i; + float frontLerp, backLerp; + model_t *model; + + model = R_GetModelByHandle(handle); + if (!model->data.mdv[0]) { + if (model->type == MOD_MDR) { start = &start_space; end = &end_space; - R_GetAnimTag((mdrHeader_t *) model->data.mdr, startFrame, tagName, start); - R_GetAnimTag((mdrHeader_t *) model->data.mdr, endFrame, tagName, end); - } - else if( model->type == MOD_IQM ) { - return R_IQMLerpTag( tag, (iqmData_t *)model->data.iqm, - startFrame, endFrame, - frac, tagName ); + R_GetAnimTag((mdrHeader_t *)model->data.mdr, startFrame, tagName, start); + R_GetAnimTag((mdrHeader_t *)model->data.mdr, endFrame, tagName, end); + } else if (model->type == MOD_IQM) { + return R_IQMLerpTag(tag, (iqmData_t *)model->data.iqm, startFrame, endFrame, frac, tagName); } else { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; - } - } - else - { - start = R_GetTag( model->data.mdv[0], startFrame, tagName ); - end = R_GetTag( model->data.mdv[0], endFrame, tagName ); - if ( !start || !end ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + } else { + start = R_GetTag(model->data.mdv[0], startFrame, tagName); + end = R_GetTag(model->data.mdv[0], endFrame, tagName); + if (!start || !end) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } } - + frontLerp = frac; backLerp = 1.0f - frac; - for ( i = 0 ; i < 3 ; i++ ) { - tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; - tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; - tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; - tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; + for (i = 0; i < 3; i++) { + tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; + tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; + tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; + tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; } - VectorNormalize( tag->axis[0] ); - VectorNormalize( tag->axis[1] ); - VectorNormalize( tag->axis[2] ); + VectorNormalize(tag->axis[0]); + VectorNormalize(tag->axis[1]); + VectorNormalize(tag->axis[2]); return qtrue; } - /* ==================== R_ModelBounds ==================== */ -void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) { - model_t *model; +void R_ModelBounds(qhandle_t handle, vec3_t mins, vec3_t maxs) { + model_t *model; + + model = R_GetModelByHandle(handle); - model = R_GetModelByHandle( handle ); + if (model->type == MOD_BRUSH) { + VectorCopy(model->data.bmodel->bounds[0], mins); + VectorCopy(model->data.bmodel->bounds[1], maxs); - if(model->type == MOD_BRUSH) { - VectorCopy( model->data.bmodel->bounds[0], mins ); - VectorCopy( model->data.bmodel->bounds[1], maxs ); - return; } else if (model->type == MOD_MESH) { - mdvModel_t *header; - mdvFrame_t *frame; + mdvModel_t *header; + mdvFrame_t *frame; header = model->data.mdv[0]; frame = header->frames; - VectorCopy( frame->bounds[0], mins ); - VectorCopy( frame->bounds[1], maxs ); - + VectorCopy(frame->bounds[0], mins); + VectorCopy(frame->bounds[1], maxs); + return; } else if (model->type == MOD_MDR) { - mdrHeader_t *header; - mdrFrame_t *frame; + mdrHeader_t *header; + mdrFrame_t *frame; header = model->data.mdr; - frame = (mdrFrame_t *) ((byte *)header + header->ofsFrames); + frame = (mdrFrame_t *)((byte *)header + header->ofsFrames); + + VectorCopy(frame->bounds[0], mins); + VectorCopy(frame->bounds[1], maxs); - VectorCopy( frame->bounds[0], mins ); - VectorCopy( frame->bounds[1], maxs ); - return; - } else if(model->type == MOD_IQM) { + } else if (model->type == MOD_IQM) { iqmData_t *iqmData; - + iqmData = model->data.iqm; - if(iqmData->bounds) - { + if (iqmData->bounds) { VectorCopy(iqmData->bounds, mins); VectorCopy(iqmData->bounds + 3, maxs); return; } } - VectorClear( mins ); - VectorClear( maxs ); + VectorClear(mins); + VectorClear(maxs); } diff --git a/codemp/rd-rend2/tr_model_iqm.cpp b/codemp/rd-rend2/tr_model_iqm.cpp index 7639ac1b2d..a597d7027a 100644 --- a/codemp/rd-rend2/tr_model_iqm.cpp +++ b/codemp/rd-rend2/tr_model_iqm.cpp @@ -23,64 +23,54 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" -#define LL(x) x=LittleLong(x) +#define LL(x) x = LittleLong(x) // 3x4 identity matrix -static float identityMatrix[12] = { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0 -}; - -static qboolean IQM_CheckRange( iqmHeader_t *header, int offset, - int count,int size ) { +static float identityMatrix[12] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}; + +static qboolean IQM_CheckRange(iqmHeader_t *header, int offset, int count, int size) { // return true if the range specified by offset, count and size // doesn't fit into the file - return (qboolean)( count <= 0 || - offset < 0 || - offset > header->filesize || - offset + count * size < 0 || - offset + count * size > header->filesize ); + return (qboolean)(count <= 0 || offset < 0 || offset > header->filesize || offset + count * size < 0 || offset + count * size > header->filesize); } // "multiply" 3x4 matrices, these are assumed to be the top 3 rows // of a 4x4 matrix with the last row = (0 0 0 1) -static void Matrix34Multiply( float *a, float *b, float *out ) { - out[ 0] = a[0] * b[0] + a[1] * b[4] + a[ 2] * b[ 8]; - out[ 1] = a[0] * b[1] + a[1] * b[5] + a[ 2] * b[ 9]; - out[ 2] = a[0] * b[2] + a[1] * b[6] + a[ 2] * b[10]; - out[ 3] = a[0] * b[3] + a[1] * b[7] + a[ 2] * b[11] + a[ 3]; - out[ 4] = a[4] * b[0] + a[5] * b[4] + a[ 6] * b[ 8]; - out[ 5] = a[4] * b[1] + a[5] * b[5] + a[ 6] * b[ 9]; - out[ 6] = a[4] * b[2] + a[5] * b[6] + a[ 6] * b[10]; - out[ 7] = a[4] * b[3] + a[5] * b[7] + a[ 6] * b[11] + a[ 7]; - out[ 8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[ 8]; - out[ 9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[ 9]; +static void Matrix34Multiply(float *a, float *b, float *out) { + out[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8]; + out[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9]; + out[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10]; + out[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3]; + out[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8]; + out[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9]; + out[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10]; + out[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7]; + out[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8]; + out[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9]; out[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10]; out[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11]; } -static void Matrix34Multiply_OnlySetOrigin( float *a, float *b, float *out ) { - out[ 3] = a[0] * b[3] + a[1] * b[7] + a[ 2] * b[11] + a[ 3]; - out[ 7] = a[4] * b[3] + a[5] * b[7] + a[ 6] * b[11] + a[ 7]; +static void Matrix34Multiply_OnlySetOrigin(float *a, float *b, float *out) { + out[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3]; + out[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7]; out[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11]; } -static void InterpolateMatrix( float *a, float *b, float lerp, float *mat ) { +static void InterpolateMatrix(float *a, float *b, float lerp, float *mat) { float unLerp = 1.0f - lerp; - mat[ 0] = a[ 0] * unLerp + b[ 0] * lerp; - mat[ 1] = a[ 1] * unLerp + b[ 1] * lerp; - mat[ 2] = a[ 2] * unLerp + b[ 2] * lerp; - mat[ 3] = a[ 3] * unLerp + b[ 3] * lerp; - mat[ 4] = a[ 4] * unLerp + b[ 4] * lerp; - mat[ 5] = a[ 5] * unLerp + b[ 5] * lerp; - mat[ 6] = a[ 6] * unLerp + b[ 6] * lerp; - mat[ 7] = a[ 7] * unLerp + b[ 7] * lerp; - mat[ 8] = a[ 8] * unLerp + b[ 8] * lerp; - mat[ 9] = a[ 9] * unLerp + b[ 9] * lerp; + mat[0] = a[0] * unLerp + b[0] * lerp; + mat[1] = a[1] * unLerp + b[1] * lerp; + mat[2] = a[2] * unLerp + b[2] * lerp; + mat[3] = a[3] * unLerp + b[3] * lerp; + mat[4] = a[4] * unLerp + b[4] * lerp; + mat[5] = a[5] * unLerp + b[5] * lerp; + mat[6] = a[6] * unLerp + b[6] * lerp; + mat[7] = a[7] * unLerp + b[7] * lerp; + mat[8] = a[8] * unLerp + b[8] * lerp; + mat[9] = a[9] * unLerp + b[9] * lerp; mat[10] = a[10] * unLerp + b[10] * lerp; mat[11] = a[11] * unLerp + b[11] * lerp; } -static void JointToMatrix( vec4_t rot, vec3_t scale, vec3_t trans, - float *mat ) { +static void JointToMatrix(vec4_t rot, vec3_t scale, vec3_t trans, float *mat) { float xx = 2.0f * rot[0] * rot[0]; float yy = 2.0f * rot[1] * rot[1]; float zz = 2.0f * rot[2] * rot[2]; @@ -91,38 +81,49 @@ static void JointToMatrix( vec4_t rot, vec3_t scale, vec3_t trans, float wy = 2.0f * rot[3] * rot[1]; float wz = 2.0f * rot[3] * rot[2]; - mat[ 0] = scale[0] * (1.0f - (yy + zz)); - mat[ 1] = scale[0] * (xy - wz); - mat[ 2] = scale[0] * (xz + wy); - mat[ 3] = trans[0]; - mat[ 4] = scale[1] * (xy + wz); - mat[ 5] = scale[1] * (1.0f - (xx + zz)); - mat[ 6] = scale[1] * (yz - wx); - mat[ 7] = trans[1]; - mat[ 8] = scale[2] * (xz - wy); - mat[ 9] = scale[2] * (yz + wx); + mat[0] = scale[0] * (1.0f - (yy + zz)); + mat[1] = scale[0] * (xy - wz); + mat[2] = scale[0] * (xz + wy); + mat[3] = trans[0]; + mat[4] = scale[1] * (xy + wz); + mat[5] = scale[1] * (1.0f - (xx + zz)); + mat[6] = scale[1] * (yz - wx); + mat[7] = trans[1]; + mat[8] = scale[2] * (xz - wy); + mat[9] = scale[2] * (yz + wx); mat[10] = scale[2] * (1.0f - (xx + yy)); mat[11] = trans[2]; } -static void Matrix34Invert( float *inMat, float *outMat ) -{ +static void Matrix34Invert(float *inMat, float *outMat) { vec3_t trans; float invSqrLen, *v; - - outMat[ 0] = inMat[ 0]; outMat[ 1] = inMat[ 4]; outMat[ 2] = inMat[ 8]; - outMat[ 4] = inMat[ 1]; outMat[ 5] = inMat[ 5]; outMat[ 6] = inMat[ 9]; - outMat[ 8] = inMat[ 2]; outMat[ 9] = inMat[ 6]; outMat[10] = inMat[10]; - - v = outMat + 0; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - v = outMat + 4; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - v = outMat + 8; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); - trans[0] = inMat[ 3]; - trans[1] = inMat[ 7]; + outMat[0] = inMat[0]; + outMat[1] = inMat[4]; + outMat[2] = inMat[8]; + outMat[4] = inMat[1]; + outMat[5] = inMat[5]; + outMat[6] = inMat[9]; + outMat[8] = inMat[2]; + outMat[9] = inMat[6]; + outMat[10] = inMat[10]; + + v = outMat + 0; + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + v = outMat + 4; + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + v = outMat + 8; + invSqrLen = 1.0f / DotProduct(v, v); + VectorScale(v, invSqrLen, v); + + trans[0] = inMat[3]; + trans[1] = inMat[7]; trans[2] = inMat[11]; - outMat[ 3] = -DotProduct(outMat + 0, trans); - outMat[ 7] = -DotProduct(outMat + 4, trans); + outMat[3] = -DotProduct(outMat + 0, trans); + outMat[7] = -DotProduct(outMat + 4, trans); outMat[11] = -DotProduct(outMat + 8, trans); } @@ -133,104 +134,99 @@ R_LoadIQM Load an IQM model and compute the joint matrices for every frame. ================= */ -qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_name ) { - iqmHeader_t *header; - iqmVertexArray_t *vertexarray; - iqmTriangle_t *triangle; - iqmMesh_t *mesh; - iqmJoint_t *joint; - iqmPose_t *pose; - iqmBounds_t *bounds; - unsigned short *framedata; - char *str; - int i, j; - float jointInvMats[IQM_MAX_JOINTS * 12]; - float *mat, *matInv; - size_t size, joint_names; - iqmData_t *iqmData; - srfIQModel_t *surface; - char meshName[MAX_QPATH]; - byte blendIndexesType, blendWeightsType; - - if( filesize < sizeof(iqmHeader_t) ) { +qboolean R_LoadIQM(model_t *mod, void *buffer, int filesize, const char *mod_name) { + iqmHeader_t *header; + iqmVertexArray_t *vertexarray; + iqmTriangle_t *triangle; + iqmMesh_t *mesh; + iqmJoint_t *joint; + iqmPose_t *pose; + iqmBounds_t *bounds; + unsigned short *framedata; + char *str; + int i, j; + float jointInvMats[IQM_MAX_JOINTS * 12]; + float *mat, *matInv; + size_t size, joint_names; + iqmData_t *iqmData; + srfIQModel_t *surface; + char meshName[MAX_QPATH]; + byte blendIndexesType, blendWeightsType; + + if (filesize < sizeof(iqmHeader_t)) { return qfalse; } header = (iqmHeader_t *)buffer; - if( Q_strncmp( header->magic, IQM_MAGIC, sizeof(header->magic) ) ) { + if (Q_strncmp(header->magic, IQM_MAGIC, sizeof(header->magic))) { return qfalse; } - LL( header->version ); - if( header->version != IQM_VERSION ) { - ri.Printf(PRINT_WARNING, "R_LoadIQM: %s is a unsupported IQM version (%d), only version %d is supported.\n", - mod_name, header->version, IQM_VERSION); + LL(header->version); + if (header->version != IQM_VERSION) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s is a unsupported IQM version (%d), only version %d is supported.\n", mod_name, header->version, IQM_VERSION); return qfalse; } - LL( header->filesize ); - if( header->filesize > filesize || header->filesize > 16<<20 ) { + LL(header->filesize); + if (header->filesize > filesize || header->filesize > 16 << 20) { return qfalse; } - LL( header->flags ); - LL( header->num_text ); - LL( header->ofs_text ); - LL( header->num_meshes ); - LL( header->ofs_meshes ); - LL( header->num_vertexarrays ); - LL( header->num_vertexes ); - LL( header->ofs_vertexarrays ); - LL( header->num_triangles ); - LL( header->ofs_triangles ); - LL( header->ofs_adjacency ); - LL( header->num_joints ); - LL( header->ofs_joints ); - LL( header->num_poses ); - LL( header->ofs_poses ); - LL( header->num_anims ); - LL( header->ofs_anims ); - LL( header->num_frames ); - LL( header->num_framechannels ); - LL( header->ofs_frames ); - LL( header->ofs_bounds ); - LL( header->num_comment ); - LL( header->ofs_comment ); - LL( header->num_extensions ); - LL( header->ofs_extensions ); + LL(header->flags); + LL(header->num_text); + LL(header->ofs_text); + LL(header->num_meshes); + LL(header->ofs_meshes); + LL(header->num_vertexarrays); + LL(header->num_vertexes); + LL(header->ofs_vertexarrays); + LL(header->num_triangles); + LL(header->ofs_triangles); + LL(header->ofs_adjacency); + LL(header->num_joints); + LL(header->ofs_joints); + LL(header->num_poses); + LL(header->ofs_poses); + LL(header->num_anims); + LL(header->ofs_anims); + LL(header->num_frames); + LL(header->num_framechannels); + LL(header->ofs_frames); + LL(header->ofs_bounds); + LL(header->num_comment); + LL(header->ofs_comment); + LL(header->num_extensions); + LL(header->ofs_extensions); // check ioq3 joint limit - if ( header->num_joints > IQM_MAX_JOINTS ) { - ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %d joints (%d).\n", - mod_name, IQM_MAX_JOINTS, header->num_joints); + if (header->num_joints > IQM_MAX_JOINTS) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %d joints (%d).\n", mod_name, IQM_MAX_JOINTS, header->num_joints); return qfalse; } blendIndexesType = blendWeightsType = IQM_UBYTE; // check and swap vertex arrays - if( IQM_CheckRange( header, header->ofs_vertexarrays, - header->num_vertexarrays, - sizeof(iqmVertexArray_t) ) ) { + if (IQM_CheckRange(header, header->ofs_vertexarrays, header->num_vertexarrays, sizeof(iqmVertexArray_t))) { return qfalse; } vertexarray = (iqmVertexArray_t *)((byte *)header + header->ofs_vertexarrays); - for( i = 0; i < header->num_vertexarrays; i++, vertexarray++ ) { - int n, *intPtr; + for (i = 0; i < header->num_vertexarrays; i++, vertexarray++) { + int n, *intPtr; - if( vertexarray->size <= 0 || vertexarray->size > 4 ) { + if (vertexarray->size <= 0 || vertexarray->size > 4) { return qfalse; } // total number of values n = header->num_vertexes * vertexarray->size; - switch( vertexarray->format ) { + switch (vertexarray->format) { case IQM_BYTE: case IQM_UBYTE: // 1 byte, no swapping necessary - if( IQM_CheckRange( header, vertexarray->offset, - n, sizeof(byte) ) ) { + if (IQM_CheckRange(header, vertexarray->offset, n, sizeof(byte))) { return qfalse; } break; @@ -238,13 +234,12 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na case IQM_UINT: case IQM_FLOAT: // 4-byte swap - if( IQM_CheckRange( header, vertexarray->offset, - n, sizeof(float) ) ) { + if (IQM_CheckRange(header, vertexarray->offset, n, sizeof(float))) { return qfalse; } intPtr = (int *)((byte *)header + vertexarray->offset); - for( j = 0; j < n; j++, intPtr++ ) { - LL( *intPtr ); + for (j = 0; j < n; j++, intPtr++) { + LL(*intPtr); } break; default: @@ -253,45 +248,37 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na break; } - switch( vertexarray->type ) { + switch (vertexarray->type) { case IQM_POSITION: case IQM_NORMAL: - if( vertexarray->format != IQM_FLOAT || - vertexarray->size != 3 ) { + if (vertexarray->format != IQM_FLOAT || vertexarray->size != 3) { return qfalse; } break; case IQM_TANGENT: - if( vertexarray->format != IQM_FLOAT || - vertexarray->size != 4 ) { + if (vertexarray->format != IQM_FLOAT || vertexarray->size != 4) { return qfalse; } break; case IQM_TEXCOORD: - if( vertexarray->format != IQM_FLOAT || - vertexarray->size != 2 ) { + if (vertexarray->format != IQM_FLOAT || vertexarray->size != 2) { return qfalse; } break; case IQM_BLENDINDEXES: - if( (vertexarray->format != IQM_INT && - vertexarray->format != IQM_UBYTE) || - vertexarray->size != 4 ) { + if ((vertexarray->format != IQM_INT && vertexarray->format != IQM_UBYTE) || vertexarray->size != 4) { return qfalse; } blendIndexesType = vertexarray->format; break; case IQM_BLENDWEIGHTS: - if( (vertexarray->format != IQM_FLOAT && - vertexarray->format != IQM_UBYTE) || - vertexarray->size != 4 ) { + if ((vertexarray->format != IQM_FLOAT && vertexarray->format != IQM_UBYTE) || vertexarray->size != 4) { return qfalse; } blendWeightsType = vertexarray->format; break; case IQM_COLOR: - if( vertexarray->format != IQM_UBYTE || - vertexarray->size != 4 ) { + if (vertexarray->format != IQM_UBYTE || vertexarray->size != 4) { return qfalse; } break; @@ -299,154 +286,132 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na } // check and swap triangles - if( IQM_CheckRange( header, header->ofs_triangles, - header->num_triangles, sizeof(iqmTriangle_t) ) ) { + if (IQM_CheckRange(header, header->ofs_triangles, header->num_triangles, sizeof(iqmTriangle_t))) { return qfalse; } triangle = (iqmTriangle_t *)((byte *)header + header->ofs_triangles); - for( i = 0; i < header->num_triangles; i++, triangle++ ) { - LL( triangle->vertex[0] ); - LL( triangle->vertex[1] ); - LL( triangle->vertex[2] ); - - if( triangle->vertex[0] > header->num_vertexes || - triangle->vertex[1] > header->num_vertexes || - triangle->vertex[2] > header->num_vertexes ) { + for (i = 0; i < header->num_triangles; i++, triangle++) { + LL(triangle->vertex[0]); + LL(triangle->vertex[1]); + LL(triangle->vertex[2]); + + if (triangle->vertex[0] > header->num_vertexes || triangle->vertex[1] > header->num_vertexes || triangle->vertex[2] > header->num_vertexes) { return qfalse; } } // check and swap meshes - if( IQM_CheckRange( header, header->ofs_meshes, - header->num_meshes, sizeof(iqmMesh_t) ) ) { + if (IQM_CheckRange(header, header->ofs_meshes, header->num_meshes, sizeof(iqmMesh_t))) { return qfalse; } mesh = (iqmMesh_t *)((byte *)header + header->ofs_meshes); - for( i = 0; i < header->num_meshes; i++, mesh++) { - LL( mesh->name ); - LL( mesh->material ); - LL( mesh->first_vertex ); - LL( mesh->num_vertexes ); - LL( mesh->first_triangle ); - LL( mesh->num_triangles ); - - if ( mesh->name < header->num_text ) { - Q_strncpyz( meshName, (char*)header + header->ofs_text + mesh->name, sizeof (meshName) ); + for (i = 0; i < header->num_meshes; i++, mesh++) { + LL(mesh->name); + LL(mesh->material); + LL(mesh->first_vertex); + LL(mesh->num_vertexes); + LL(mesh->first_triangle); + LL(mesh->num_triangles); + + if (mesh->name < header->num_text) { + Q_strncpyz(meshName, (char *)header + header->ofs_text + mesh->name, sizeof(meshName)); } else { meshName[0] = '\0'; } // check ioq3 limits - if ( mesh->num_vertexes >= SHADER_MAX_VERTEXES ) - { - ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i verts on %s (%i).\n", - mod_name, SHADER_MAX_VERTEXES-1, meshName[0] ? meshName : "a surface", - mesh->num_vertexes ); + if (mesh->num_vertexes >= SHADER_MAX_VERTEXES) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i verts on %s (%i).\n", mod_name, SHADER_MAX_VERTEXES - 1, + meshName[0] ? meshName : "a surface", mesh->num_vertexes); return qfalse; } - if ( mesh->num_triangles*3 >= SHADER_MAX_INDEXES ) - { - ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i triangles on %s (%i).\n", - mod_name, ( SHADER_MAX_INDEXES / 3 ) - 1, meshName[0] ? meshName : "a surface", - mesh->num_triangles ); + if (mesh->num_triangles * 3 >= SHADER_MAX_INDEXES) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i triangles on %s (%i).\n", mod_name, (SHADER_MAX_INDEXES / 3) - 1, + meshName[0] ? meshName : "a surface", mesh->num_triangles); return qfalse; } - if( mesh->first_vertex >= header->num_vertexes || - mesh->first_vertex + mesh->num_vertexes > header->num_vertexes || - mesh->first_triangle >= header->num_triangles || - mesh->first_triangle + mesh->num_triangles > header->num_triangles || - mesh->name >= header->num_text || - mesh->material >= header->num_text ) { + if (mesh->first_vertex >= header->num_vertexes || mesh->first_vertex + mesh->num_vertexes > header->num_vertexes || + mesh->first_triangle >= header->num_triangles || mesh->first_triangle + mesh->num_triangles > header->num_triangles || + mesh->name >= header->num_text || mesh->material >= header->num_text) { return qfalse; } } - if( header->num_poses != header->num_joints && header->num_poses != 0 ) { - ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has %d poses and %d joints, must have the same number or 0 poses\n", - mod_name, header->num_poses, header->num_joints ); + if (header->num_poses != header->num_joints && header->num_poses != 0) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has %d poses and %d joints, must have the same number or 0 poses\n", mod_name, header->num_poses, + header->num_joints); return qfalse; } joint_names = 0; - if ( header->num_joints ) - { + if (header->num_joints) { // check and swap joints - if( IQM_CheckRange( header, header->ofs_joints, - header->num_joints, sizeof(iqmJoint_t) ) ) { + if (IQM_CheckRange(header, header->ofs_joints, header->num_joints, sizeof(iqmJoint_t))) { return qfalse; } joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); - for( i = 0; i < header->num_joints; i++, joint++ ) { - LL( joint->name ); - LL( joint->parent ); - LL( joint->translate[0] ); - LL( joint->translate[1] ); - LL( joint->translate[2] ); - LL( joint->rotate[0] ); - LL( joint->rotate[1] ); - LL( joint->rotate[2] ); - LL( joint->rotate[3] ); - LL( joint->scale[0] ); - LL( joint->scale[1] ); - LL( joint->scale[2] ); - - if( joint->parent < -1 || - joint->parent >= (int)header->num_joints || - joint->name >= (int)header->num_text ) { + for (i = 0; i < header->num_joints; i++, joint++) { + LL(joint->name); + LL(joint->parent); + LL(joint->translate[0]); + LL(joint->translate[1]); + LL(joint->translate[2]); + LL(joint->rotate[0]); + LL(joint->rotate[1]); + LL(joint->rotate[2]); + LL(joint->rotate[3]); + LL(joint->scale[0]); + LL(joint->scale[1]); + LL(joint->scale[2]); + + if (joint->parent < -1 || joint->parent >= (int)header->num_joints || joint->name >= (int)header->num_text) { return qfalse; } - joint_names += strlen( (char *)header + header->ofs_text + - joint->name ) + 1; + joint_names += strlen((char *)header + header->ofs_text + joint->name) + 1; } } - if ( header->num_poses ) - { + if (header->num_poses) { // check and swap poses - if( IQM_CheckRange( header, header->ofs_poses, - header->num_poses, sizeof(iqmPose_t) ) ) { + if (IQM_CheckRange(header, header->ofs_poses, header->num_poses, sizeof(iqmPose_t))) { return qfalse; } pose = (iqmPose_t *)((byte *)header + header->ofs_poses); - for( i = 0; i < header->num_poses; i++, pose++ ) { - LL( pose->parent ); - LL( pose->mask ); - LL( pose->channeloffset[0] ); - LL( pose->channeloffset[1] ); - LL( pose->channeloffset[2] ); - LL( pose->channeloffset[3] ); - LL( pose->channeloffset[4] ); - LL( pose->channeloffset[5] ); - LL( pose->channeloffset[6] ); - LL( pose->channeloffset[7] ); - LL( pose->channeloffset[8] ); - LL( pose->channeloffset[9] ); - LL( pose->channelscale[0] ); - LL( pose->channelscale[1] ); - LL( pose->channelscale[2] ); - LL( pose->channelscale[3] ); - LL( pose->channelscale[4] ); - LL( pose->channelscale[5] ); - LL( pose->channelscale[6] ); - LL( pose->channelscale[7] ); - LL( pose->channelscale[8] ); - LL( pose->channelscale[9] ); + for (i = 0; i < header->num_poses; i++, pose++) { + LL(pose->parent); + LL(pose->mask); + LL(pose->channeloffset[0]); + LL(pose->channeloffset[1]); + LL(pose->channeloffset[2]); + LL(pose->channeloffset[3]); + LL(pose->channeloffset[4]); + LL(pose->channeloffset[5]); + LL(pose->channeloffset[6]); + LL(pose->channeloffset[7]); + LL(pose->channeloffset[8]); + LL(pose->channeloffset[9]); + LL(pose->channelscale[0]); + LL(pose->channelscale[1]); + LL(pose->channelscale[2]); + LL(pose->channelscale[3]); + LL(pose->channelscale[4]); + LL(pose->channelscale[5]); + LL(pose->channelscale[6]); + LL(pose->channelscale[7]); + LL(pose->channelscale[8]); + LL(pose->channelscale[9]); } } - if (header->ofs_bounds) - { + if (header->ofs_bounds) { // check and swap model bounds - if(IQM_CheckRange(header, header->ofs_bounds, - header->num_frames, sizeof(*bounds))) - { + if (IQM_CheckRange(header, header->ofs_bounds, header->num_frames, sizeof(*bounds))) { return qfalse; } - bounds = (iqmBounds_t *) ((byte *) header + header->ofs_bounds); - for(i = 0; i < header->num_frames; i++) - { + bounds = (iqmBounds_t *)((byte *)header + header->ofs_bounds); + for (i = 0; i < header->num_frames; i++) { LL(bounds->bbmin[0]); LL(bounds->bbmin[1]); LL(bounds->bbmin[2]); @@ -460,20 +425,20 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na // allocate the model and copy the data size = sizeof(iqmData_t); - size += header->num_meshes * sizeof( srfIQModel_t ); - size += header->num_joints * 12 * sizeof( float ); // joint mats - size += header->num_poses * header->num_frames * 12 * sizeof( float ); // pose mats - if(header->ofs_bounds) - size += header->num_frames * 6 * sizeof(float); // model bounds + size += header->num_meshes * sizeof(srfIQModel_t); + size += header->num_joints * 12 * sizeof(float); // joint mats + size += header->num_poses * header->num_frames * 12 * sizeof(float); // pose mats + if (header->ofs_bounds) + size += header->num_frames * 6 * sizeof(float); // model bounds size += header->num_vertexes * 3 * sizeof(float); // positions size += header->num_vertexes * 2 * sizeof(float); // texcoords size += header->num_vertexes * 3 * sizeof(float); // normals size += header->num_vertexes * 4 * sizeof(float); // tangents size += header->num_vertexes * 4 * sizeof(byte); // blendIndexes size += header->num_vertexes * 4 * sizeof(byte); // colors - size += header->num_joints * sizeof(int); // parents + size += header->num_joints * sizeof(int); // parents size += header->num_triangles * 3 * sizeof(int); // triangles - size += joint_names; // joint names + size += joint_names; // joint names // blendWeights if (blendWeightsType == IQM_FLOAT) { @@ -483,48 +448,46 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na } mod->type = MOD_IQM; - iqmData = (iqmData_t *)ri.Hunk_Alloc( size, h_low ); + iqmData = (iqmData_t *)ri.Hunk_Alloc(size, h_low); mod->data.iqm = iqmData; // fill header iqmData->num_vertexes = header->num_vertexes; iqmData->num_triangles = header->num_triangles; - iqmData->num_frames = header->num_frames; + iqmData->num_frames = header->num_frames; iqmData->num_surfaces = header->num_meshes; - iqmData->num_joints = header->num_joints; - iqmData->num_poses = header->num_poses; + iqmData->num_joints = header->num_joints; + iqmData->num_poses = header->num_poses; iqmData->blendWeightsType = blendWeightsType; - iqmData->surfaces = (srfIQModel_t *)(iqmData + 1); - iqmData->jointMats = (float *) (iqmData->surfaces + iqmData->num_surfaces); - iqmData->poseMats = iqmData->jointMats + 12 * header->num_joints; - if(header->ofs_bounds) - { - iqmData->bounds = iqmData->poseMats + 12 * header->num_poses * header->num_frames; - iqmData->positions = iqmData->bounds + 6 * header->num_frames; - } - else - iqmData->positions = iqmData->poseMats + 12 * header->num_poses * header->num_frames; - iqmData->texcoords = iqmData->positions + 3 * header->num_vertexes; - iqmData->normals = iqmData->texcoords + 2 * header->num_vertexes; - iqmData->tangents = iqmData->normals + 3 * header->num_vertexes; + iqmData->surfaces = (srfIQModel_t *)(iqmData + 1); + iqmData->jointMats = (float *)(iqmData->surfaces + iqmData->num_surfaces); + iqmData->poseMats = iqmData->jointMats + 12 * header->num_joints; + if (header->ofs_bounds) { + iqmData->bounds = iqmData->poseMats + 12 * header->num_poses * header->num_frames; + iqmData->positions = iqmData->bounds + 6 * header->num_frames; + } else + iqmData->positions = iqmData->poseMats + 12 * header->num_poses * header->num_frames; + iqmData->texcoords = iqmData->positions + 3 * header->num_vertexes; + iqmData->normals = iqmData->texcoords + 2 * header->num_vertexes; + iqmData->tangents = iqmData->normals + 3 * header->num_vertexes; iqmData->blendIndexes = (byte *)(iqmData->tangents + 4 * header->num_vertexes); - if(blendWeightsType == IQM_FLOAT) { + if (blendWeightsType == IQM_FLOAT) { iqmData->blendWeights.f = (float *)(iqmData->blendIndexes + 4 * header->num_vertexes); - iqmData->colors = (byte *)(iqmData->blendWeights.f + 4 * header->num_vertexes); + iqmData->colors = (byte *)(iqmData->blendWeights.f + 4 * header->num_vertexes); } else { iqmData->blendWeights.b = iqmData->blendIndexes + 4 * header->num_vertexes; - iqmData->colors = iqmData->blendWeights.b + 4 * header->num_vertexes; + iqmData->colors = iqmData->blendWeights.b + 4 * header->num_vertexes; } iqmData->jointParents = (int *)(iqmData->colors + 4 * header->num_vertexes); - iqmData->triangles = iqmData->jointParents + header->num_joints; - iqmData->names = (char *)(iqmData->triangles + 3 * header->num_triangles); + iqmData->triangles = iqmData->jointParents + header->num_joints; + iqmData->names = (char *)(iqmData->triangles + 3 * header->num_triangles); - if ( header->num_joints == 0 ) + if (header->num_joints == 0) iqmData->jointMats = NULL; - if ( header->num_poses == 0 ) + if (header->num_poses == 0) iqmData->poseMats = NULL; // calculate joint matrices and their inverses @@ -532,83 +495,79 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na mat = iqmData->jointMats; matInv = jointInvMats; joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); - for( i = 0; i < header->num_joints; i++, joint++ ) { + for (i = 0; i < header->num_joints; i++, joint++) { float baseFrame[12], invBaseFrame[12]; - - JointToMatrix( joint->rotate, joint->scale, joint->translate, baseFrame ); - Matrix34Invert( baseFrame, invBaseFrame ); - - if ( joint->parent >= 0 ) - { - Matrix34Multiply( iqmData->jointMats + 12 * joint->parent, baseFrame, mat ); + + JointToMatrix(joint->rotate, joint->scale, joint->translate, baseFrame); + Matrix34Invert(baseFrame, invBaseFrame); + + if (joint->parent >= 0) { + Matrix34Multiply(iqmData->jointMats + 12 * joint->parent, baseFrame, mat); mat += 12; - Matrix34Multiply( invBaseFrame, jointInvMats + 12 * joint->parent, matInv ); + Matrix34Multiply(invBaseFrame, jointInvMats + 12 * joint->parent, matInv); matInv += 12; - } - else - { - Com_Memcpy( mat, baseFrame, sizeof(baseFrame) ); + } else { + Com_Memcpy(mat, baseFrame, sizeof(baseFrame)); mat += 12; - Com_Memcpy( matInv, invBaseFrame, sizeof(invBaseFrame) ); + Com_Memcpy(matInv, invBaseFrame, sizeof(invBaseFrame)); matInv += 12; - } + } } // calculate pose matrices framedata = (unsigned short *)((byte *)header + header->ofs_frames); mat = iqmData->poseMats; - for( i = 0; i < header->num_frames; i++ ) { + for (i = 0; i < header->num_frames; i++) { pose = (iqmPose_t *)((byte *)header + header->ofs_poses); - for( j = 0; j < header->num_poses; j++, pose++ ) { - vec3_t translate; - vec4_t rotate; - vec3_t scale; - float mat1[12], mat2[12]; + for (j = 0; j < header->num_poses; j++, pose++) { + vec3_t translate; + vec4_t rotate; + vec3_t scale; + float mat1[12], mat2[12]; translate[0] = pose->channeloffset[0]; - if( pose->mask & 0x001) + if (pose->mask & 0x001) translate[0] += *framedata++ * pose->channelscale[0]; translate[1] = pose->channeloffset[1]; - if( pose->mask & 0x002) + if (pose->mask & 0x002) translate[1] += *framedata++ * pose->channelscale[1]; translate[2] = pose->channeloffset[2]; - if( pose->mask & 0x004) + if (pose->mask & 0x004) translate[2] += *framedata++ * pose->channelscale[2]; rotate[0] = pose->channeloffset[3]; - if( pose->mask & 0x008) + if (pose->mask & 0x008) rotate[0] += *framedata++ * pose->channelscale[3]; rotate[1] = pose->channeloffset[4]; - if( pose->mask & 0x010) + if (pose->mask & 0x010) rotate[1] += *framedata++ * pose->channelscale[4]; rotate[2] = pose->channeloffset[5]; - if( pose->mask & 0x020) + if (pose->mask & 0x020) rotate[2] += *framedata++ * pose->channelscale[5]; rotate[3] = pose->channeloffset[6]; - if( pose->mask & 0x040) + if (pose->mask & 0x040) rotate[3] += *framedata++ * pose->channelscale[6]; scale[0] = pose->channeloffset[7]; - if( pose->mask & 0x080) + if (pose->mask & 0x080) scale[0] += *framedata++ * pose->channelscale[7]; scale[1] = pose->channeloffset[8]; - if( pose->mask & 0x100) + if (pose->mask & 0x100) scale[1] += *framedata++ * pose->channelscale[8]; scale[2] = pose->channeloffset[9]; - if( pose->mask & 0x200) + if (pose->mask & 0x200) scale[2] += *framedata++ * pose->channelscale[9]; // construct transformation matrix - JointToMatrix( rotate, scale, translate, mat1 ); - - if( pose->parent >= 0 ) { - Matrix34Multiply( iqmData->jointMats + 12 * pose->parent, - mat1, mat2 ); + JointToMatrix(rotate, scale, translate, mat1); + + if (pose->parent >= 0) { + Matrix34Multiply(iqmData->jointMats + 12 * pose->parent, mat1, mat2); } else { - Com_Memcpy( mat2, mat1, sizeof(mat1) ); + Com_Memcpy(mat2, mat1, sizeof(mat1)); } - - Matrix34Multiply( mat2, jointInvMats + 12 * j, mat ); + + Matrix34Multiply(mat2, jointInvMats + 12 * j, mat); mat += 12; } } @@ -618,12 +577,12 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na mesh = (iqmMesh_t *)((byte *)header + header->ofs_meshes); surface = iqmData->surfaces; str = (char *)header + header->ofs_text; - for( i = 0; i < header->num_meshes; i++, mesh++, surface++ ) { + for (i = 0; i < header->num_meshes; i++, mesh++, surface++) { surface->surfaceType = SF_IQM; - Q_strncpyz(surface->name, str + mesh->name, sizeof (surface->name)); + Q_strncpyz(surface->name, str + mesh->name, sizeof(surface->name)); Q_strlwr(surface->name); // lowercase the surface name so skin compares are faster - surface->shader = R_FindShader( str + mesh->material, lightmapsNone, stylesDefault, qtrue ); - if( surface->shader->defaultShader ) + surface->shader = R_FindShader(str + mesh->material, lightmapsNone, stylesDefault, qtrue); + if (surface->shader->defaultShader) surface->shader = tr.defaultShader; surface->data = iqmData; surface->first_vertex = mesh->first_vertex; @@ -634,96 +593,77 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na // copy vertexarrays and indexes vertexarray = (iqmVertexArray_t *)((byte *)header + header->ofs_vertexarrays); - for( i = 0; i < header->num_vertexarrays; i++, vertexarray++ ) { - int n; + for (i = 0; i < header->num_vertexarrays; i++, vertexarray++) { + int n; // total number of values n = header->num_vertexes * vertexarray->size; - switch( vertexarray->type ) { + switch (vertexarray->type) { case IQM_POSITION: - Com_Memcpy( iqmData->positions, - (byte *)header + vertexarray->offset, - n * sizeof(float) ); + Com_Memcpy(iqmData->positions, (byte *)header + vertexarray->offset, n * sizeof(float)); break; case IQM_NORMAL: - Com_Memcpy( iqmData->normals, - (byte *)header + vertexarray->offset, - n * sizeof(float) ); + Com_Memcpy(iqmData->normals, (byte *)header + vertexarray->offset, n * sizeof(float)); break; case IQM_TANGENT: - Com_Memcpy( iqmData->tangents, - (byte *)header + vertexarray->offset, - n * sizeof(float) ); + Com_Memcpy(iqmData->tangents, (byte *)header + vertexarray->offset, n * sizeof(float)); break; case IQM_TEXCOORD: - Com_Memcpy( iqmData->texcoords, - (byte *)header + vertexarray->offset, - n * sizeof(float) ); + Com_Memcpy(iqmData->texcoords, (byte *)header + vertexarray->offset, n * sizeof(float)); break; case IQM_BLENDINDEXES: - if( blendIndexesType == IQM_INT ) { - int *data = (int*)((byte*)header + vertexarray->offset); - for ( j = 0; j < n; j++ ) { + if (blendIndexesType == IQM_INT) { + int *data = (int *)((byte *)header + vertexarray->offset); + for (j = 0; j < n; j++) { iqmData->blendIndexes[j] = (byte)data[j]; } } else { - Com_Memcpy( iqmData->blendIndexes, - (byte *)header + vertexarray->offset, - n * sizeof(byte) ); + Com_Memcpy(iqmData->blendIndexes, (byte *)header + vertexarray->offset, n * sizeof(byte)); } break; case IQM_BLENDWEIGHTS: - if( blendWeightsType == IQM_FLOAT ) { - Com_Memcpy( iqmData->blendWeights.f, - (byte *)header + vertexarray->offset, - n * sizeof(float) ); + if (blendWeightsType == IQM_FLOAT) { + Com_Memcpy(iqmData->blendWeights.f, (byte *)header + vertexarray->offset, n * sizeof(float)); } else { - Com_Memcpy( iqmData->blendWeights.b, - (byte *)header + vertexarray->offset, - n * sizeof(byte) ); + Com_Memcpy(iqmData->blendWeights.b, (byte *)header + vertexarray->offset, n * sizeof(byte)); } break; case IQM_COLOR: - Com_Memcpy( iqmData->colors, - (byte *)header + vertexarray->offset, - n * sizeof(byte) ); + Com_Memcpy(iqmData->colors, (byte *)header + vertexarray->offset, n * sizeof(byte)); break; } } // copy joint parents joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); - for( i = 0; i < header->num_joints; i++, joint++ ) { + for (i = 0; i < header->num_joints; i++, joint++) { iqmData->jointParents[i] = joint->parent; } // copy triangles triangle = (iqmTriangle_t *)((byte *)header + header->ofs_triangles); - for( i = 0; i < header->num_triangles; i++, triangle++ ) { - iqmData->triangles[3*i+0] = triangle->vertex[0]; - iqmData->triangles[3*i+1] = triangle->vertex[1]; - iqmData->triangles[3*i+2] = triangle->vertex[2]; + for (i = 0; i < header->num_triangles; i++, triangle++) { + iqmData->triangles[3 * i + 0] = triangle->vertex[0]; + iqmData->triangles[3 * i + 1] = triangle->vertex[1]; + iqmData->triangles[3 * i + 2] = triangle->vertex[2]; } // copy joint names str = iqmData->names; joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); - for( i = 0; i < header->num_joints; i++, joint++ ) { - char *name = (char *)header + header->ofs_text + - joint->name; - int len = strlen( name ) + 1; - Com_Memcpy( str, name, len ); + for (i = 0; i < header->num_joints; i++, joint++) { + char *name = (char *)header + header->ofs_text + joint->name; + int len = strlen(name) + 1; + Com_Memcpy(str, name, len); str += len; } // copy model bounds - if(header->ofs_bounds) - { + if (header->ofs_bounds) { mat = iqmData->bounds; - bounds = (iqmBounds_t *) ((byte *) header + header->ofs_bounds); - for(i = 0; i < header->num_frames; i++) - { + bounds = (iqmBounds_t *)((byte *)header + header->ofs_bounds); + for (i = 0; i < header->num_frames; i++) { mat[0] = bounds->bbmin[0]; mat[1] = bounds->bbmin[1]; mat[2] = bounds->bbmin[2]; @@ -744,10 +684,10 @@ qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_na R_CullIQM ============= */ -static int R_CullIQM( iqmData_t *data, trRefEntity_t *ent ) { - vec3_t bounds[2]; - float *oldBounds, *newBounds; - int i; +static int R_CullIQM(iqmData_t *data, trRefEntity_t *ent) { + vec3_t bounds[2]; + float *oldBounds, *newBounds; + int i; if (!data->bounds) { tr.pc.c_box_cull_md3_clip++; @@ -755,17 +695,16 @@ static int R_CullIQM( iqmData_t *data, trRefEntity_t *ent ) { } // compute bounds pointers - oldBounds = data->bounds + 6*ent->e.oldframe; - newBounds = data->bounds + 6*ent->e.frame; + oldBounds = data->bounds + 6 * ent->e.oldframe; + newBounds = data->bounds + 6 * ent->e.frame; // calculate a bounding box in the current coordinate system - for (i = 0 ; i < 3 ; i++) { + for (i = 0; i < 3; i++) { bounds[0][i] = oldBounds[i] < newBounds[i] ? oldBounds[i] : newBounds[i]; - bounds[1][i] = oldBounds[i+3] > newBounds[i+3] ? oldBounds[i+3] : newBounds[i+3]; + bounds[1][i] = oldBounds[i + 3] > newBounds[i + 3] ? oldBounds[i + 3] : newBounds[i + 3]; } - switch ( R_CullLocalBox( bounds ) ) - { + switch (R_CullLocalBox(bounds)) { case CULL_IN: tr.pc.c_box_cull_md3_in++; return CULL_IN; @@ -785,41 +724,41 @@ R_ComputeIQMFogNum ================= */ -int R_ComputeIQMFogNum( iqmData_t *data, trRefEntity_t *ent ) { - int i, j; - fog_t *fog; - const float *bounds; - const float defaultBounds[6] = { -8, -8, -8, 8, 8, 8 }; - vec3_t diag, center; - vec3_t localOrigin; - float radius; - - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { +int R_ComputeIQMFogNum(iqmData_t *data, trRefEntity_t *ent) { + int i, j; + fog_t *fog; + const float *bounds; + const float defaultBounds[6] = {-8, -8, -8, 8, 8, 8}; + vec3_t diag, center; + vec3_t localOrigin; + float radius; + + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } // FIXME: non-normalized axis issues if (data->bounds) { - bounds = data->bounds + 6*ent->e.frame; + bounds = data->bounds + 6 * ent->e.frame; } else { bounds = defaultBounds; } - VectorSubtract( bounds+3, bounds, diag ); - VectorMA( bounds, 0.5f, diag, center ); - VectorAdd( ent->e.origin, center, localOrigin ); - radius = 0.5f * VectorLength( diag ); + VectorSubtract(bounds + 3, bounds, diag); + VectorMA(bounds, 0.5f, diag, center); + VectorAdd(ent->e.origin, center, localOrigin); + radius = 0.5f * VectorLength(diag); - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( localOrigin[j] - radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (localOrigin[j] - radius >= fog->bounds[1][j]) { break; } - if ( localOrigin[j] + radius <= fog->bounds[0][j] ) { + if (localOrigin[j] + radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -834,16 +773,16 @@ R_AddIQMSurfaces Add all surfaces of this model ================= */ -void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { - iqmData_t *data; - srfIQModel_t *surface; - int i, j; - qboolean personalModel; - int cull; - int fogNum; - int cubemapIndex; - shader_t *shader; - skin_t *skin; +void R_AddIQMSurfaces(trRefEntity_t *ent, int entityNum) { + iqmData_t *data; + srfIQModel_t *surface; + int i, j; + qboolean personalModel; + int cull; + int fogNum; + int cubemapIndex; + shader_t *shader; + skin_t *skin; data = tr.currentModel->data.iqm; surface = data->surfaces; @@ -851,7 +790,7 @@ void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { // don't add third_person objects if not in a portal personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); - if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + if (ent->e.renderfx & RF_WRAP_FRAMES) { ent->e.frame %= data->num_frames; ent->e.oldframe %= data->num_frames; } @@ -862,13 +801,8 @@ void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { // when the surfaces are rendered, they don't need to be // range checked again. // - if ( (ent->e.frame >= data->num_frames) - || (ent->e.frame < 0) - || (ent->e.oldframe >= data->num_frames) - || (ent->e.oldframe < 0) ) { - ri.Printf( PRINT_DEVELOPER, "R_AddIQMSurfaces: no such frame %d to %d for '%s'\n", - ent->e.oldframe, ent->e.frame, - tr.currentModel->name ); + if ((ent->e.frame >= data->num_frames) || (ent->e.frame < 0) || (ent->e.oldframe >= data->num_frames) || (ent->e.oldframe < 0)) { + ri.Printf(PRINT_DEVELOPER, "R_AddIQMSurfaces: no such frame %d to %d for '%s'\n", ent->e.oldframe, ent->e.frame, tr.currentModel->name); ent->e.frame = 0; ent->e.oldframe = 0; } @@ -877,30 +811,27 @@ void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { // cull the entire model if merged bounding box of both frames // is outside the view frustum. // - cull = R_CullIQM ( data, ent ); - if ( cull == CULL_OUT ) { + cull = R_CullIQM(data, ent); + if (cull == CULL_OUT) { return; } // // see if we are in a fog volume // - fogNum = R_ComputeIQMFogNum( data, ent ); + fogNum = R_ComputeIQMFogNum(data, ent); cubemapIndex = R_CubemapForPoint(ent->e.origin); - for ( i = 0 ; i < data->num_surfaces ; i++ ) { - if(ent->e.customShader) - shader = R_GetShaderByHandle( ent->e.customShader ); - else if(ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) - { + for (i = 0; i < data->num_surfaces; i++) { + if (ent->e.customShader) + shader = R_GetShaderByHandle(ent->e.customShader); + else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin = R_GetSkinByHandle(ent->e.customSkin); shader = tr.defaultShader; - for(j = 0; j < skin->numSurfaces; j++) - { - if (!strcmp(skin->surfaces[j]->name, surface->name)) - { + for (j = 0; j < skin->numSurfaces; j++) { + if (!strcmp(skin->surfaces[j]->name, surface->name)) { shader = (shader_t *)skin->surfaces[j]->shader; break; } @@ -912,97 +843,81 @@ void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { // we will add shadows even if the main object isn't visible in the view // stencil shadows can't do personal models unless I polyhedron clip - if ( !personalModel - && r_shadows->integer == 2 - && fogNum == 0 - && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.shadowShader, 0, 0, R_IsPostRenderEntity(ent), 0 ); + if (!personalModel && r_shadows->integer == 2 && fogNum == 0 && !(ent->e.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, entityNum, tr.shadowShader, 0, 0, R_IsPostRenderEntity(ent), 0); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 - && fogNum == 0 - && (ent->e.renderfx & RF_SHADOW_PLANE ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, 0, R_IsPostRenderEntity(ent), 0 ); + if (r_shadows->integer == 3 && fogNum == 0 && (ent->e.renderfx & RF_SHADOW_PLANE) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, 0, R_IsPostRenderEntity(ent), 0); } - if( !personalModel ) { - R_AddDrawSurf( (surfaceType_t *)surface, entityNum, shader, fogNum, 0, R_IsPostRenderEntity(ent), cubemapIndex ); + if (!personalModel) { + R_AddDrawSurf((surfaceType_t *)surface, entityNum, shader, fogNum, 0, R_IsPostRenderEntity(ent), cubemapIndex); } surface++; } } +static void ComputePoseMats(iqmData_t *data, int frame, int oldframe, float backlerp, float *mat) { + float *mat1, *mat2; + int *joint = data->jointParents; + int i; -static void ComputePoseMats( iqmData_t *data, int frame, int oldframe, - float backlerp, float *mat ) { - float *mat1, *mat2; - int *joint = data->jointParents; - int i; - - if ( data->num_poses == 0 ) { - for( i = 0; i < data->num_joints; i++, joint++ ) { - if( *joint >= 0 ) { - Matrix34Multiply( mat + 12 * *joint, - identityMatrix, mat + 12*i ); + if (data->num_poses == 0) { + for (i = 0; i < data->num_joints; i++, joint++) { + if (*joint >= 0) { + Matrix34Multiply(mat + 12 * *joint, identityMatrix, mat + 12 * i); } else { - Com_Memcpy( mat + 12*i, identityMatrix, 12 * sizeof(float) ); + Com_Memcpy(mat + 12 * i, identityMatrix, 12 * sizeof(float)); } } return; } - if ( oldframe == frame ) { + if (oldframe == frame) { mat1 = data->poseMats + 12 * data->num_poses * frame; - for( i = 0; i < data->num_poses; i++, joint++ ) { - if( *joint >= 0 ) { - Matrix34Multiply( mat + 12 * *joint, - mat1 + 12*i, mat + 12*i ); + for (i = 0; i < data->num_poses; i++, joint++) { + if (*joint >= 0) { + Matrix34Multiply(mat + 12 * *joint, mat1 + 12 * i, mat + 12 * i); } else { - Com_Memcpy( mat + 12*i, mat1 + 12*i, 12 * sizeof(float) ); + Com_Memcpy(mat + 12 * i, mat1 + 12 * i, 12 * sizeof(float)); } } - } else { + } else { mat1 = data->poseMats + 12 * data->num_poses * frame; mat2 = data->poseMats + 12 * data->num_poses * oldframe; - - for( i = 0; i < data->num_poses; i++, joint++ ) { - if( *joint >= 0 ) { + + for (i = 0; i < data->num_poses; i++, joint++) { + if (*joint >= 0) { float tmpMat[12]; - InterpolateMatrix( mat1 + 12*i, mat2 + 12*i, - backlerp, tmpMat ); - Matrix34Multiply( mat + 12 * *joint, - tmpMat, mat + 12*i ); - + InterpolateMatrix(mat1 + 12 * i, mat2 + 12 * i, backlerp, tmpMat); + Matrix34Multiply(mat + 12 * *joint, tmpMat, mat + 12 * i); + } else { - InterpolateMatrix( mat1 + 12*i, mat2 + 12*i, - backlerp, mat ); + InterpolateMatrix(mat1 + 12 * i, mat2 + 12 * i, backlerp, mat); } } } } -static void ComputeJointMats( iqmData_t *data, int frame, int oldframe, - float backlerp, float *mat ) { - float *mat1; - int i; +static void ComputeJointMats(iqmData_t *data, int frame, int oldframe, float backlerp, float *mat) { + float *mat1; + int i; - ComputePoseMats( data, frame, oldframe, backlerp, mat ); + ComputePoseMats(data, frame, oldframe, backlerp, mat); - for( i = 0; i < data->num_joints; i++ ) { + for (i = 0; i < data->num_joints; i++) { float outmat[12]; mat1 = mat + 12 * i; Com_Memcpy(outmat, mat1, sizeof(outmat)); - Matrix34Multiply_OnlySetOrigin( outmat, data->jointMats + 12 * i, mat1 ); + Matrix34Multiply_OnlySetOrigin(outmat, data->jointMats + 12 * i, mat1); } } - /* ================= RB_AddIQMSurfaces @@ -1010,27 +925,27 @@ RB_AddIQMSurfaces Compute vertices for this model surface ================= */ -void RB_IQMSurfaceAnim( surfaceType_t *surface ) { - srfIQModel_t *surf = (srfIQModel_t *)surface; - iqmData_t *data = surf->data; - float jointMats[IQM_MAX_JOINTS * 12]; - int i; +void RB_IQMSurfaceAnim(surfaceType_t *surface) { + srfIQModel_t *surf = (srfIQModel_t *)surface; + iqmData_t *data = surf->data; + float jointMats[IQM_MAX_JOINTS * 12]; + int i; - vec4_t *outXYZ; - uint32_t *outNormal; - uint32_t *outTangent; - vec2_t (*outTexCoord)[NUM_TESS_TEXCOORDS]; - vec4_t *outColor; + vec4_t *outXYZ; + uint32_t *outNormal; + uint32_t *outTangent; + vec2_t(*outTexCoord)[NUM_TESS_TEXCOORDS]; + vec4_t *outColor; - int frame = data->num_frames ? backEnd.currentEntity->e.frame % data->num_frames : 0; - int oldframe = data->num_frames ? backEnd.currentEntity->e.oldframe % data->num_frames : 0; - float backlerp = backEnd.currentEntity->e.backlerp; + int frame = data->num_frames ? backEnd.currentEntity->e.frame % data->num_frames : 0; + int oldframe = data->num_frames ? backEnd.currentEntity->e.oldframe % data->num_frames : 0; + float backlerp = backEnd.currentEntity->e.backlerp; - int *tri; - glIndex_t *ptr; - glIndex_t base; + int *tri; + glIndex_t *ptr; + glIndex_t base; - RB_CHECKOVERFLOW( surf->num_vertexes, surf->num_triangles * 3 ); + RB_CHECKOVERFLOW(surf->num_vertexes, surf->num_triangles * 3); outXYZ = &tess.xyz[tess.numVertexes]; outNormal = &tess.normal[tess.numVertexes]; @@ -1039,107 +954,97 @@ void RB_IQMSurfaceAnim( surfaceType_t *surface ) { outColor = &tess.vertexColors[tess.numVertexes]; // compute interpolated joint matrices - if ( data->num_poses > 0 ) { - ComputePoseMats( data, frame, oldframe, backlerp, jointMats ); + if (data->num_poses > 0) { + ComputePoseMats(data, frame, oldframe, backlerp, jointMats); } // transform vertexes and fill other data - for( i = 0; i < surf->num_vertexes; - i++, outXYZ++, outNormal++, outTexCoord++, outColor++ ) { - int j, k; - float vtxMat[12]; - float nrmMat[9]; - int vtx = i + surf->first_vertex; - float blendWeights[4]; - int numWeights; - - for ( numWeights = 0; numWeights < 4; numWeights++ ) { - if ( data->blendWeightsType == IQM_FLOAT ) - blendWeights[numWeights] = data->blendWeights.f[4*vtx + numWeights]; + for (i = 0; i < surf->num_vertexes; i++, outXYZ++, outNormal++, outTexCoord++, outColor++) { + int j, k; + float vtxMat[12]; + float nrmMat[9]; + int vtx = i + surf->first_vertex; + float blendWeights[4]; + int numWeights; + + for (numWeights = 0; numWeights < 4; numWeights++) { + if (data->blendWeightsType == IQM_FLOAT) + blendWeights[numWeights] = data->blendWeights.f[4 * vtx + numWeights]; else - blendWeights[numWeights] = (float)data->blendWeights.b[4*vtx + numWeights] / 255.0f; + blendWeights[numWeights] = (float)data->blendWeights.b[4 * vtx + numWeights] / 255.0f; - if ( blendWeights[numWeights] <= 0 ) + if (blendWeights[numWeights] <= 0) break; } - if ( data->num_poses == 0 || numWeights == 0 ) { + if (data->num_poses == 0 || numWeights == 0) { // no blend joint, use identity matrix. - Com_Memcpy( vtxMat, identityMatrix, 12 * sizeof (float) ); + Com_Memcpy(vtxMat, identityMatrix, 12 * sizeof(float)); } else { // compute the vertex matrix by blending the up to // four blend weights - Com_Memset( vtxMat, 0, 12 * sizeof (float) ); - for( j = 0; j < numWeights; j++ ) { - for( k = 0; k < 12; k++ ) { - vtxMat[k] += blendWeights[j] * jointMats[12*data->blendIndexes[4*vtx + j] + k]; + Com_Memset(vtxMat, 0, 12 * sizeof(float)); + for (j = 0; j < numWeights; j++) { + for (k = 0; k < 12; k++) { + vtxMat[k] += blendWeights[j] * jointMats[12 * data->blendIndexes[4 * vtx + j] + k]; } } } // compute the normal matrix as transpose of the adjoint // of the vertex matrix - nrmMat[ 0] = vtxMat[ 5]*vtxMat[10] - vtxMat[ 6]*vtxMat[ 9]; - nrmMat[ 1] = vtxMat[ 6]*vtxMat[ 8] - vtxMat[ 4]*vtxMat[10]; - nrmMat[ 2] = vtxMat[ 4]*vtxMat[ 9] - vtxMat[ 5]*vtxMat[ 8]; - nrmMat[ 3] = vtxMat[ 2]*vtxMat[ 9] - vtxMat[ 1]*vtxMat[10]; - nrmMat[ 4] = vtxMat[ 0]*vtxMat[10] - vtxMat[ 2]*vtxMat[ 8]; - nrmMat[ 5] = vtxMat[ 1]*vtxMat[ 8] - vtxMat[ 0]*vtxMat[ 9]; - nrmMat[ 6] = vtxMat[ 1]*vtxMat[ 6] - vtxMat[ 2]*vtxMat[ 5]; - nrmMat[ 7] = vtxMat[ 2]*vtxMat[ 4] - vtxMat[ 0]*vtxMat[ 6]; - nrmMat[ 8] = vtxMat[ 0]*vtxMat[ 5] - vtxMat[ 1]*vtxMat[ 4]; - - (*outTexCoord)[0][0] = data->texcoords[2*vtx + 0]; - (*outTexCoord)[0][1] = data->texcoords[2*vtx + 1]; + nrmMat[0] = vtxMat[5] * vtxMat[10] - vtxMat[6] * vtxMat[9]; + nrmMat[1] = vtxMat[6] * vtxMat[8] - vtxMat[4] * vtxMat[10]; + nrmMat[2] = vtxMat[4] * vtxMat[9] - vtxMat[5] * vtxMat[8]; + nrmMat[3] = vtxMat[2] * vtxMat[9] - vtxMat[1] * vtxMat[10]; + nrmMat[4] = vtxMat[0] * vtxMat[10] - vtxMat[2] * vtxMat[8]; + nrmMat[5] = vtxMat[1] * vtxMat[8] - vtxMat[0] * vtxMat[9]; + nrmMat[6] = vtxMat[1] * vtxMat[6] - vtxMat[2] * vtxMat[5]; + nrmMat[7] = vtxMat[2] * vtxMat[4] - vtxMat[0] * vtxMat[6]; + nrmMat[8] = vtxMat[0] * vtxMat[5] - vtxMat[1] * vtxMat[4]; + + (*outTexCoord)[0][0] = data->texcoords[2 * vtx + 0]; + (*outTexCoord)[0][1] = data->texcoords[2 * vtx + 1]; (*outTexCoord)[1][0] = (*outTexCoord)[0][0]; (*outTexCoord)[1][1] = (*outTexCoord)[0][1]; (*outXYZ)[0] = - vtxMat[ 0] * data->positions[3*vtx+0] + - vtxMat[ 1] * data->positions[3*vtx+1] + - vtxMat[ 2] * data->positions[3*vtx+2] + - vtxMat[ 3]; + vtxMat[0] * data->positions[3 * vtx + 0] + vtxMat[1] * data->positions[3 * vtx + 1] + vtxMat[2] * data->positions[3 * vtx + 2] + vtxMat[3]; (*outXYZ)[1] = - vtxMat[ 4] * data->positions[3*vtx+0] + - vtxMat[ 5] * data->positions[3*vtx+1] + - vtxMat[ 6] * data->positions[3*vtx+2] + - vtxMat[ 7]; + vtxMat[4] * data->positions[3 * vtx + 0] + vtxMat[5] * data->positions[3 * vtx + 1] + vtxMat[6] * data->positions[3 * vtx + 2] + vtxMat[7]; (*outXYZ)[2] = - vtxMat[ 8] * data->positions[3*vtx+0] + - vtxMat[ 9] * data->positions[3*vtx+1] + - vtxMat[10] * data->positions[3*vtx+2] + - vtxMat[11]; + vtxMat[8] * data->positions[3 * vtx + 0] + vtxMat[9] * data->positions[3 * vtx + 1] + vtxMat[10] * data->positions[3 * vtx + 2] + vtxMat[11]; (*outXYZ)[3] = 1.0f; { vec3_t normal; vec4_t tangent; - normal[0] = DotProduct(&nrmMat[0], &data->normals[3*vtx]); - normal[1] = DotProduct(&nrmMat[3], &data->normals[3*vtx]); - normal[2] = DotProduct(&nrmMat[6], &data->normals[3*vtx]); + normal[0] = DotProduct(&nrmMat[0], &data->normals[3 * vtx]); + normal[1] = DotProduct(&nrmMat[3], &data->normals[3 * vtx]); + normal[2] = DotProduct(&nrmMat[6], &data->normals[3 * vtx]); *outNormal = R_VboPackNormal(normal); - tangent[0] = DotProduct(&nrmMat[0], &data->tangents[4*vtx]); - tangent[1] = DotProduct(&nrmMat[3], &data->tangents[4*vtx]); - tangent[2] = DotProduct(&nrmMat[6], &data->tangents[4*vtx]); - tangent[3] = data->tangents[4*vtx+3]; + tangent[0] = DotProduct(&nrmMat[0], &data->tangents[4 * vtx]); + tangent[1] = DotProduct(&nrmMat[3], &data->tangents[4 * vtx]); + tangent[2] = DotProduct(&nrmMat[6], &data->tangents[4 * vtx]); + tangent[3] = data->tangents[4 * vtx + 3]; *outTangent++ = R_VboPackTangent(tangent); } - (*outColor)[0] = data->colors[4*vtx+0] / 255.0f; - (*outColor)[1] = data->colors[4*vtx+1] / 255.0f; - (*outColor)[2] = data->colors[4*vtx+2] / 255.0f; - (*outColor)[3] = data->colors[4*vtx+3] / 255.0f; + (*outColor)[0] = data->colors[4 * vtx + 0] / 255.0f; + (*outColor)[1] = data->colors[4 * vtx + 1] / 255.0f; + (*outColor)[2] = data->colors[4 * vtx + 2] / 255.0f; + (*outColor)[3] = data->colors[4 * vtx + 3] / 255.0f; } tri = data->triangles + 3 * surf->first_triangle; ptr = &tess.indexes[tess.numIndexes]; base = tess.numVertexes; - for( i = 0; i < surf->num_triangles; i++ ) { + for (i = 0; i < surf->num_triangles; i++) { *ptr++ = base + (*tri++ - surf->first_vertex); *ptr++ = base + (*tri++ - surf->first_vertex); *ptr++ = base + (*tri++ - surf->first_vertex); @@ -1149,26 +1054,24 @@ void RB_IQMSurfaceAnim( surfaceType_t *surface ) { tess.numVertexes += surf->num_vertexes; } -int R_IQMLerpTag( orientation_t *tag, iqmData_t *data, - int startFrame, int endFrame, - float frac, const char *tagName ) { - float jointMats[IQM_MAX_JOINTS * 12]; - int joint; - char *names = data->names; +int R_IQMLerpTag(orientation_t *tag, iqmData_t *data, int startFrame, int endFrame, float frac, const char *tagName) { + float jointMats[IQM_MAX_JOINTS * 12]; + int joint; + char *names = data->names; // get joint number by reading the joint names - for( joint = 0; joint < data->num_joints; joint++ ) { - if( !strcmp( tagName, names ) ) + for (joint = 0; joint < data->num_joints; joint++) { + if (!strcmp(tagName, names)) break; - names += strlen( names ) + 1; + names += strlen(names) + 1; } - if( joint >= data->num_joints ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + if (joint >= data->num_joints) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } - ComputeJointMats( data, startFrame, endFrame, frac, jointMats ); + ComputeJointMats(data, startFrame, endFrame, frac, jointMats); tag->axis[0][0] = jointMats[12 * joint + 0]; tag->axis[1][0] = jointMats[12 * joint + 1]; diff --git a/codemp/rd-rend2/tr_postprocess.cpp b/codemp/rd-rend2/tr_postprocess.cpp index 9502cb50e7..98dcc56d96 100644 --- a/codemp/rd-rend2/tr_postprocess.cpp +++ b/codemp/rd-rend2/tr_postprocess.cpp @@ -22,16 +22,13 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" -void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, int autoExposure) -{ +void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, int autoExposure) { vec4i_t srcBox, dstBox; vec4_t color; static int lastFrameCount = 0; - if (autoExposure) - { - if (lastFrameCount == 0 || tr.frameCount < lastFrameCount || tr.frameCount - lastFrameCount > 5) - { + if (autoExposure) { + if (lastFrameCount == 0 || tr.frameCount < lastFrameCount || tr.frameCount - lastFrameCount > 5) { // determine average log luminance FBO_t *srcFbo, *dstFbo, *tmp; int size = 256; @@ -46,8 +43,7 @@ void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, in dstFbo = tr.textureScratchFbo[1]; // downscale to 1x1 texture - while (size > 1) - { + while (size > 1) { VectorSet4(srcBox, 0, 0, size, size); size >>= 1; VectorSet4(dstBox, 0, 0, size, size); @@ -66,22 +62,18 @@ void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, in // blend with old log luminance for gradual change VectorSet4(srcBox, 0, 0, 0, 0); - color[0] = - color[1] = - color[2] = 1.0f; + color[0] = color[1] = color[2] = 1.0f; color[3] = Com_Clamp(0.0f, 1.0f, 0.001f * backEnd.refdef.frameTime); - FBO_Blit(tr.targetLevelsFbo, srcBox, NULL, tr.calcLevelsFbo, NULL, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + FBO_Blit(tr.targetLevelsFbo, srcBox, NULL, tr.calcLevelsFbo, NULL, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); } // tonemap - color[0] = - color[1] = - color[2] = powf(2.0f, r_cameraExposure->value); //exp2(r_cameraExposure->value); + color[0] = color[1] = color[2] = powf(2.0f, r_cameraExposure->value); // exp2(r_cameraExposure->value); color[3] = 1.0f; if (autoExposure) - GL_BindToTMU(tr.calcLevelsImage, TB_LEVELSMAP); + GL_BindToTMU(tr.calcLevelsImage, TB_LEVELSMAP); else GL_BindToTMU(tr.fixedLevelsImage, TB_LEVELSMAP); @@ -97,22 +89,20 @@ RB_BokehBlur Blurs a part of one framebuffer to another. -Framebuffers can be identical. +Framebuffers can be identical. ============= */ -void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float blur) -{ -// vec4i_t srcBox, dstBox; +void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float blur) { + // vec4i_t srcBox, dstBox; vec4_t color; - + blur *= 10.0f; if (blur < 0.004f) return; // bokeh blur - if (blur > 0.0f) - { + if (blur > 0.0f) { vec4i_t quarterBox; quarterBox[0] = 0; @@ -121,21 +111,19 @@ void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float quarterBox[3] = -tr.quarterFbo[0]->height; // create a quarter texture - //FBO_Blit(NULL, NULL, NULL, tr.quarterFbo[0], NULL, NULL, NULL, 0); + // FBO_Blit(NULL, NULL, NULL, tr.quarterFbo[0], NULL, NULL, NULL, 0); FBO_FastBlit(src, srcBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); } #ifndef HQ_BLUR - if (blur > 1.0f) - { + if (blur > 1.0f) { // create a 1/16th texture - //FBO_Blit(tr.quarterFbo[0], NULL, NULL, tr.textureScratchFbo[0], NULL, NULL, NULL, 0); + // FBO_Blit(tr.quarterFbo[0], NULL, NULL, tr.textureScratchFbo[0], NULL, NULL, NULL, 0); FBO_FastBlit(tr.quarterFbo[0], NULL, tr.textureScratchFbo[0], NULL, GL_COLOR_BUFFER_BIT, GL_LINEAR); } #endif - if (blur > 0.0f && blur <= 1.0f) - { + if (blur > 0.0f && blur <= 1.0f) { // Crossfade original with quarter texture VectorSet4(color, 1, 1, 1, blur); @@ -143,37 +131,31 @@ void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float } #ifndef HQ_BLUR // ok blur, but can see some pixelization - else if (blur > 1.0f && blur <= 2.0f) - { + else if (blur > 1.0f && blur <= 2.0f) { // crossfade quarter texture with 1/16th texture FBO_Blit(tr.quarterFbo[0], NULL, NULL, dst, dstBox, NULL, NULL, 0); VectorSet4(color, 1, 1, 1, blur - 1.0f); FBO_Blit(tr.textureScratchFbo[0], NULL, NULL, dst, dstBox, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - } - else if (blur > 2.0f) - { + } else if (blur > 2.0f) { // blur 1/16th texture then replace int i; - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { vec2_t blurTexScale; float subblur; subblur = ((blur - 2.0f) / 2.0f) / 3.0f * (float)(i + 1); - blurTexScale[0] = - blurTexScale[1] = subblur; + blurTexScale[0] = blurTexScale[1] = subblur; - color[0] = - color[1] = - color[2] = 0.5f; + color[0] = color[1] = color[2] = 0.5f; color[3] = 1.0f; if (i != 0) - FBO_Blit(tr.textureScratchFbo[0], NULL, blurTexScale, tr.textureScratchFbo[1], NULL, &tr.bokehShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); + FBO_Blit(tr.textureScratchFbo[0], NULL, blurTexScale, tr.textureScratchFbo[1], NULL, &tr.bokehShader, color, + GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); else FBO_Blit(tr.textureScratchFbo[0], NULL, blurTexScale, tr.textureScratchFbo[1], NULL, &tr.bokehShader, color, 0); } @@ -181,8 +163,7 @@ void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float FBO_Blit(tr.textureScratchFbo[1], NULL, NULL, dst, dstBox, &tr.textureColorShader, NULL, 0); } #else // higher quality blur, but slower - else if (blur > 1.0f) - { + else if (blur > 1.0f) { // blur quarter texture then replace int i; @@ -191,25 +172,22 @@ void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float VectorSet4(color, 0.5f, 0.5f, 0.5f, 1); - for (i = 0; i < 2; i++) - { + for (i = 0; i < 2; i++) { vec2_t blurTexScale; float subblur; subblur = (blur - 1.0f) / 2.0f * (float)(i + 1); - blurTexScale[0] = - blurTexScale[1] = subblur; + blurTexScale[0] = blurTexScale[1] = subblur; - color[0] = - color[1] = - color[2] = 1.0f; + color[0] = color[1] = color[2] = 1.0f; if (i != 0) color[3] = 1.0f; else color[3] = 0.5f; - FBO_Blit(tr.quarterFbo[0], NULL, blurTexScale, tr.quarterFbo[1], NULL, &tr.bokehShader, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + FBO_Blit(tr.quarterFbo[0], NULL, blurTexScale, tr.quarterFbo[1], NULL, &tr.bokehShader, color, + GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); } FBO_Blit(tr.quarterFbo[1], NULL, NULL, dst, dstBox, &tr.textureColorShader, NULL, 0); @@ -217,9 +195,8 @@ void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float #endif } - -static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretch, float x, float y, float w, float h, float xcenter, float ycenter, float alpha) -{ +static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretch, float x, float y, float w, float h, float xcenter, float ycenter, + float alpha) { vec4i_t srcBox, dstBox; vec4_t color; const float inc = 1.f / passes; @@ -229,8 +206,7 @@ static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretc { vec2_t texScale; - texScale[0] = - texScale[1] = 1.0f; + texScale[0] = texScale[1] = 1.0f; alpha *= inc; VectorSet4(color, alpha, alpha, alpha, 1.0f); @@ -241,30 +217,26 @@ static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretc --passes; scale = mul; - while (passes > 0) - { + while (passes > 0) { float iscale = 1.f / scale; float s0 = xcenter * (1.f - iscale); float t0 = (1.0f - ycenter) * (1.f - iscale); float s1 = iscale + s0; float t1 = iscale + t0; - if (srcFbo) - { + if (srcFbo) { srcBox[0] = s0 * srcFbo->width; srcBox[1] = t0 * srcFbo->height; srcBox[2] = (s1 - s0) * srcFbo->width; srcBox[3] = (t1 - t0) * srcFbo->height; - } - else - { + } else { srcBox[0] = s0 * glConfig.vidWidth; srcBox[1] = t0 * glConfig.vidHeight; srcBox[2] = (s1 - s0) * glConfig.vidWidth; srcBox[3] = (t1 - t0) * glConfig.vidHeight; } - - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); scale *= mul; --passes; @@ -272,9 +244,7 @@ static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretc } } - -static qboolean RB_UpdateSunFlareVis(void) -{ +static qboolean RB_UpdateSunFlareVis(void) { GLuint sampleCount = 0; tr.sunFlareQueryIndex ^= 1; @@ -282,11 +252,9 @@ static qboolean RB_UpdateSunFlareVis(void) return qtrue; /* debug code */ - if (0) - { + if (0) { int iter; - for (iter=0 ; ; ++iter) - { + for (iter = 0;; ++iter) { GLint available = 0; qglGetQueryObjectiv(tr.sunFlareQuery[tr.sunFlareQueryIndex], GL_QUERY_RESULT_AVAILABLE, &available); if (available) @@ -295,19 +263,18 @@ static qboolean RB_UpdateSunFlareVis(void) ri.Printf(PRINT_DEVELOPER, "Waited %d iterations\n", iter); } - + qglGetQueryObjectuiv(tr.sunFlareQuery[tr.sunFlareQueryIndex], GL_QUERY_RESULT, &sampleCount); return (qboolean)(sampleCount > 0); } -void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) -{ +void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) { vec4_t color; float dot; const float cutoff = 0.25f; qboolean colorize = qtrue; -// float w, h, w2, h2; + // float w, h, w2, h2; matrix_t mvp; vec4_t pos, hpos; @@ -323,17 +290,17 @@ void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) float dist; matrix_t trans, model; - Matrix16Translation( backEnd.viewParms.ori.origin, trans ); - Matrix16Multiply( backEnd.viewParms.world.modelViewMatrix, trans, model ); + Matrix16Translation(backEnd.viewParms.ori.origin, trans); + Matrix16Multiply(backEnd.viewParms.world.modelViewMatrix, trans, model); Matrix16Multiply(backEnd.viewParms.projectionMatrix, model, mvp); - dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) - VectorScale( tr.sunDirection, dist, pos ); + VectorScale(tr.sunDirection, dist, pos); } // project sun point - //Matrix16Multiply(backEnd.viewParms.projectionMatrix, backEnd.viewParms.world.modelViewMatrix, mvp); + // Matrix16Multiply(backEnd.viewParms.projectionMatrix, backEnd.viewParms.world.modelViewMatrix, mvp); Matrix16Transform(mvp, pos, hpos); // transform to UV coords @@ -348,23 +315,19 @@ void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) vec2_t texScale; vec4i_t rayBox, quarterBox; - texScale[0] = - texScale[1] = 1.0f; + texScale[0] = texScale[1] = 1.0f; VectorSet4(color, mul, mul, mul, 1); - if (srcFbo) - { - rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / srcFbo->width; + if (srcFbo) { + rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / srcFbo->width; rayBox[1] = srcBox[1] * tr.sunRaysFbo->height / srcFbo->height; - rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / srcFbo->width; + rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / srcFbo->width; rayBox[3] = srcBox[3] * tr.sunRaysFbo->height / srcFbo->height; - } - else - { - rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / glConfig.vidWidth; + } else { + rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / glConfig.vidWidth; rayBox[1] = srcBox[1] * tr.sunRaysFbo->height / glConfig.vidHeight; - rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / glConfig.vidWidth; + rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / glConfig.vidWidth; rayBox[3] = srcBox[3] * tr.sunRaysFbo->height / glConfig.vidHeight; } @@ -374,36 +337,32 @@ void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) quarterBox[3] = -tr.quarterFbo[0]->height; // first, downsample the framebuffer - if (colorize) - { + if (colorize) { FBO_FastBlit(srcFbo, srcBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); FBO_Blit(tr.sunRaysFbo, rayBox, NULL, tr.quarterFbo[0], quarterBox, NULL, color, GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO); - } - else - { + } else { FBO_FastBlit(tr.sunRaysFbo, rayBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); } } // radial blur passes, ping-ponging between the two quarter-size buffers { - const float stretch_add = 2.f/3.f; + const float stretch_add = 2.f / 3.f; float stretch = 1.f + stretch_add; int i; - for (i=0; i<2; ++i) - { - RB_RadialBlur(tr.quarterFbo[i&1], tr.quarterFbo[(~i) & 1], 5, stretch, 0.f, 0.f, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height, pos[0], pos[1], 1.125f); + for (i = 0; i < 2; ++i) { + RB_RadialBlur(tr.quarterFbo[i & 1], tr.quarterFbo[(~i) & 1], 5, stretch, 0.f, 0.f, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height, pos[0], + pos[1], 1.125f); stretch += stretch_add; } } - + // add result back on top of the main buffer { float mul = 1.f; vec2_t texScale; - texScale[0] = - texScale[1] = 1.0f; + texScale[0] = texScale[1] = 1.0f; VectorSet4(color, mul, mul, mul, 1); @@ -411,8 +370,7 @@ void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) } } -static void RB_BlurAxis(FBO_t *srcFbo, FBO_t *dstFbo, float strength, qboolean horizontal) -{ +static void RB_BlurAxis(FBO_t *srcFbo, FBO_t *dstFbo, float strength, qboolean horizontal) { float dx, dy; float xmul, ymul; float weights[3] = { @@ -437,57 +395,48 @@ static void RB_BlurAxis(FBO_t *srcFbo, FBO_t *dstFbo, float strength, qboolean h vec4_t color; vec2_t texScale; - texScale[0] = - texScale[1] = 1.0f; + texScale[0] = texScale[1] = 1.0f; VectorSet4(color, weights[0], weights[0], weights[0], 1.0f); VectorSet4(srcBox, 0, 0, srcFbo->width, srcFbo->height); VectorSet4(dstBox, 0, 0, dstFbo->width, dstFbo->height); - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, 0 ); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, 0); VectorSet4(color, weights[1], weights[1], weights[1], 1.0f); dx = offsets[1] * xmul; dy = offsets[1] * ymul; VectorSet4(srcBox, dx, dy, srcFbo->width, srcFbo->height); - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); VectorSet4(srcBox, -dx, -dy, srcFbo->width, srcFbo->height); - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); VectorSet4(color, weights[2], weights[2], weights[2], 1.0f); dx = offsets[2] * xmul; dy = offsets[2] * ymul; VectorSet4(srcBox, dx, dy, srcFbo->width, srcFbo->height); - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); VectorSet4(srcBox, -dx, -dy, srcFbo->width, srcFbo->height); - FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); } } -void RB_HBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) -{ - RB_BlurAxis(srcFbo, dstFbo, strength, qtrue); -} +void RB_HBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) { RB_BlurAxis(srcFbo, dstFbo, strength, qtrue); } -void RB_VBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) -{ - RB_BlurAxis(srcFbo, dstFbo, strength, qfalse); -} +void RB_VBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) { RB_BlurAxis(srcFbo, dstFbo, strength, qfalse); } -void RB_GaussianBlur(FBO_t *srcFbo, FBO_t *intermediateFbo, FBO_t *dstFbo, float spread) -{ +void RB_GaussianBlur(FBO_t *srcFbo, FBO_t *intermediateFbo, FBO_t *dstFbo, float spread) { // Blur X vec2_t scale; - VectorSet2 (scale, spread, spread); + VectorSet2(scale, spread, spread); - FBO_Blit (srcFbo, NULL, scale, intermediateFbo, NULL, &tr.gaussianBlurShader[0], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); + FBO_Blit(srcFbo, NULL, scale, intermediateFbo, NULL, &tr.gaussianBlurShader[0], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); // Blur Y - FBO_Blit (intermediateFbo, NULL, scale, dstFbo, NULL, &tr.gaussianBlurShader[1], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); + FBO_Blit(intermediateFbo, NULL, scale, dstFbo, NULL, &tr.gaussianBlurShader[1], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); } -void RB_BloomDownscale(image_t *sourceImage, FBO_t *destFBO) -{ - vec2_t invTexRes = { 1.0f / sourceImage->width, 1.0f / sourceImage->height }; +void RB_BloomDownscale(image_t *sourceImage, FBO_t *destFBO) { + vec2_t invTexRes = {1.0f / sourceImage->width, 1.0f / sourceImage->height}; FBO_Bind(destFBO); GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); @@ -503,15 +452,11 @@ void RB_BloomDownscale(image_t *sourceImage, FBO_t *destFBO) qglDrawArrays(GL_TRIANGLES, 0, 3); } -void RB_BloomDownscale(FBO_t *sourceFBO, FBO_t *destFBO) -{ - RB_BloomDownscale(sourceFBO->colorImage[0], destFBO); -} +void RB_BloomDownscale(FBO_t *sourceFBO, FBO_t *destFBO) { RB_BloomDownscale(sourceFBO->colorImage[0], destFBO); } -void RB_BloomUpscale(FBO_t *sourceFBO, FBO_t *destFBO) -{ +void RB_BloomUpscale(FBO_t *sourceFBO, FBO_t *destFBO) { image_t *sourceImage = sourceFBO->colorImage[0]; - vec2_t invTexRes = { 1.0f / sourceImage->width, 1.0f / sourceImage->height }; + vec2_t invTexRes = {1.0f / sourceImage->width, 1.0f / sourceImage->height}; FBO_Bind(destFBO); GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); diff --git a/codemp/rd-rend2/tr_scene.cpp b/codemp/rd-rend2/tr_scene.cpp index b62dca2004..cca4c25fd1 100644 --- a/codemp/rd-rend2/tr_scene.cpp +++ b/codemp/rd-rend2/tr_scene.cpp @@ -22,19 +22,18 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" -int r_firstSceneDrawSurf; +int r_firstSceneDrawSurf; -int r_numdlights; -int r_firstSceneDlight; +int r_numdlights; +int r_firstSceneDlight; -int r_numentities; -int r_firstSceneEntity; +int r_numentities; +int r_firstSceneEntity; -int r_numpolys; -int r_firstScenePoly; - -int r_numpolyverts; +int r_numpolys; +int r_firstScenePoly; +int r_numpolyverts; /* ==================== @@ -42,7 +41,7 @@ R_InitNextFrame ==================== */ -void R_InitNextFrame( void ) { +void R_InitNextFrame(void) { backEndData->commands.used = 0; tr.numTimedBlocks = 0; @@ -61,14 +60,13 @@ void R_InitNextFrame( void ) { r_numpolyverts = 0; } - /* ==================== RE_ClearScene ==================== */ -void RE_ClearScene( void ) { +void RE_ClearScene(void) { r_firstSceneDlight = r_numdlights; r_firstSceneEntity = r_numentities; r_firstScenePoly = r_numpolys; @@ -89,21 +87,14 @@ R_AddPolygonSurfaces Adds all the scene's polys into this view's drawsurf list ===================== */ -void R_AddPolygonSurfaces( const trRefdef_t *refdef ) { +void R_AddPolygonSurfaces(const trRefdef_t *refdef) { srfPoly_t *poly; - int fogMask = -((refdef->rdflags & RDF_NOFOG) == 0); + int fogMask = -((refdef->rdflags & RDF_NOFOG) == 0); int i; - for ( i = 0, poly = refdef->polys; i < refdef->numPolys ; i++, poly++ ) { - shader_t *sh = R_GetShaderByHandle( poly->hShader ); - R_AddDrawSurf( - (surfaceType_t *)poly, - REFENTITYNUM_WORLD, - sh, - poly->fogIndex & fogMask, - qfalse, - qfalse, - 0 /* cubemapIndex */ ); + for (i = 0, poly = refdef->polys; i < refdef->numPolys; i++, poly++) { + shader_t *sh = R_GetShaderByHandle(poly->hShader); + R_AddDrawSurf((surfaceType_t *)poly, REFENTITYNUM_WORLD, sh, poly->fogIndex & fogMask, qfalse, qfalse, 0 /* cubemapIndex */); } } @@ -113,22 +104,20 @@ RE_AddPolyToScene ===================== */ -void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys ) { - srfPoly_t *poly; - int i, j; - int fogIndex; - fog_t *fog; - vec3_t bounds[2]; - - if ( !tr.registered ) { +void RE_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys) { + srfPoly_t *poly; + int i, j; + int fogIndex; + fog_t *fog; + vec3_t bounds[2]; + + if (!tr.registered) { return; } - for ( j = 0; j < numPolys; j++ ) { - if ( (r_numpolyverts + numVerts) > max_polyverts || r_numpolys >= max_polys ) { - ri.Printf( - PRINT_DEVELOPER, - S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); + for (j = 0; j < numPolys; j++) { + if ((r_numpolyverts + numVerts) > max_polyverts || r_numpolys >= max_polys) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); return; } @@ -137,39 +126,35 @@ void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts poly->hShader = hShader; poly->numVerts = numVerts; poly->verts = &backEndData->polyVerts[r_numpolyverts]; - - Com_Memcpy( poly->verts, &verts[numVerts*j], numVerts * sizeof( *verts ) ); + + Com_Memcpy(poly->verts, &verts[numVerts * j], numVerts * sizeof(*verts)); // done. r_numpolys++; r_numpolyverts += numVerts; // if no world is loaded - if ( tr.world == NULL ) { + if (tr.world == NULL) { fogIndex = 0; } // see if it is in a fog volume - else if ( tr.world->numfogs == 1 ) { + else if (tr.world->numfogs == 1) { fogIndex = 0; } else { // find which fog volume the poly is in - VectorCopy( poly->verts[0].xyz, bounds[0] ); - VectorCopy( poly->verts[0].xyz, bounds[1] ); - for ( i = 1 ; i < poly->numVerts ; i++ ) { - AddPointToBounds( poly->verts[i].xyz, bounds[0], bounds[1] ); + VectorCopy(poly->verts[0].xyz, bounds[0]); + VectorCopy(poly->verts[0].xyz, bounds[1]); + for (i = 1; i < poly->numVerts; i++) { + AddPointToBounds(poly->verts[i].xyz, bounds[0], bounds[1]); } - for ( fogIndex = 1 ; fogIndex < tr.world->numfogs ; fogIndex++ ) { - fog = &tr.world->fogs[fogIndex]; - if ( bounds[1][0] >= fog->bounds[0][0] - && bounds[1][1] >= fog->bounds[0][1] - && bounds[1][2] >= fog->bounds[0][2] - && bounds[0][0] <= fog->bounds[1][0] - && bounds[0][1] <= fog->bounds[1][1] - && bounds[0][2] <= fog->bounds[1][2] ) { + for (fogIndex = 1; fogIndex < tr.world->numfogs; fogIndex++) { + fog = &tr.world->fogs[fogIndex]; + if (bounds[1][0] >= fog->bounds[0][0] && bounds[1][1] >= fog->bounds[0][1] && bounds[1][2] >= fog->bounds[0][2] && + bounds[0][0] <= fog->bounds[1][0] && bounds[0][1] <= fog->bounds[1][1] && bounds[0][2] <= fog->bounds[1][2]) { break; } } - if ( fogIndex == tr.world->numfogs ) { + if (fogIndex == tr.world->numfogs) { fogIndex = 0; } } @@ -177,36 +162,34 @@ void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts } } - //================================================================================= - /* ===================== RE_AddRefEntityToScene ===================== */ -void RE_AddRefEntityToScene( const refEntity_t *ent ) { +void RE_AddRefEntityToScene(const refEntity_t *ent) { vec3_t cross; - if ( !tr.registered ) { + if (!tr.registered) { return; } - if ( r_numentities >= MAX_REFENTITIES ) { + if (r_numentities >= MAX_REFENTITIES) { ri.Printf(PRINT_DEVELOPER, "RE_AddRefEntityToScene: Dropping refEntity, reached MAX_REFENTITIES\n"); return; } - if ( Q_isnan(ent->origin[0]) || Q_isnan(ent->origin[1]) || Q_isnan(ent->origin[2]) ) { + if (Q_isnan(ent->origin[0]) || Q_isnan(ent->origin[1]) || Q_isnan(ent->origin[2])) { static qboolean firstTime = qtrue; if (firstTime) { firstTime = qfalse; - ri.Printf( PRINT_WARNING, "RE_AddRefEntityToScene passed a refEntity which has an origin with a NaN component\n"); + ri.Printf(PRINT_WARNING, "RE_AddRefEntityToScene passed a refEntity which has an origin with a NaN component\n"); } return; } - if ( (int)ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) { - ri.Error( ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType ); + if ((int)ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE) { + ri.Error(ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType); } backEndData->entities[r_numentities].e = *ent; @@ -225,54 +208,51 @@ RE_AddMiniRefEntityToScene 1:1 with how vanilla does it --eez ===================== */ -void RE_AddMiniRefEntityToScene( const miniRefEntity_t *miniRefEnt ) { +void RE_AddMiniRefEntityToScene(const miniRefEntity_t *miniRefEnt) { refEntity_t entity; - if(!tr.registered) + if (!tr.registered) return; - if(!miniRefEnt) + if (!miniRefEnt) return; memset(&entity, 0, sizeof(entity)); memcpy(&entity, miniRefEnt, sizeof(*miniRefEnt)); RE_AddRefEntityToScene(&entity); } - /* ===================== RE_AddDynamicLightToScene ===================== */ -void RE_AddDynamicLightToScene( const vec3_t org, float intensity, float r, float g, float b, int additive ) { - dlight_t *dl; +void RE_AddDynamicLightToScene(const vec3_t org, float intensity, float r, float g, float b, int additive) { + dlight_t *dl; - if ( !tr.registered ) { + if (!tr.registered) { return; } - if ( r_numdlights >= MAX_DLIGHTS ) { + if (r_numdlights >= MAX_DLIGHTS) { return; } - if ( intensity <= 0 ) { + if (intensity <= 0) { return; } dl = &backEndData->dlights[r_numdlights++]; - VectorCopy (org, dl->origin); + VectorCopy(org, dl->origin); dl->radius = intensity; dl->color[0] = r; dl->color[1] = g; dl->color[2] = b; - if (r_hdr->integer) - { + if (r_hdr->integer) { float maxValue = MAX(r, MAX(g, b)); - if (maxValue > 1.0f) - { + if (maxValue > 1.0f) { VectorScale(dl->color, 1.0f / maxValue, dl->color); dl->radius *= maxValue; } dl->radius = MIN(dl->radius, 65535.0f); } - + dl->additive = additive; } @@ -282,9 +262,7 @@ RE_AddLightToScene ===================== */ -void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - RE_AddDynamicLightToScene( org, intensity, r, g, b, qfalse ); -} +void RE_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { RE_AddDynamicLightToScene(org, intensity, r, g, b, qfalse); } /* ===================== @@ -292,13 +270,10 @@ RE_AddAdditiveLightToScene ===================== */ -void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - RE_AddDynamicLightToScene( org, intensity, r, g, b, qtrue ); -} +void RE_AddAdditiveLightToScene(const vec3_t org, float intensity, float r, float g, float b) { RE_AddDynamicLightToScene(org, intensity, r, g, b, qtrue); } -void RE_BeginScene(const refdef_t *fd) -{ - Com_Memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) ); +void RE_BeginScene(const refdef_t *fd) { + Com_Memcpy(tr.refdef.text, fd->text, sizeof(tr.refdef.text)); tr.refdef.x = fd->x; tr.refdef.y = fd->y; @@ -307,10 +282,10 @@ void RE_BeginScene(const refdef_t *fd) tr.refdef.fov_x = fd->fov_x; tr.refdef.fov_y = fd->fov_y; - VectorCopy( fd->vieworg, tr.refdef.vieworg ); - VectorCopy( fd->viewaxis[0], tr.refdef.viewaxis[0] ); - VectorCopy( fd->viewaxis[1], tr.refdef.viewaxis[1] ); - VectorCopy( fd->viewaxis[2], tr.refdef.viewaxis[2] ); + VectorCopy(fd->vieworg, tr.refdef.vieworg); + VectorCopy(fd->viewaxis[0], tr.refdef.viewaxis[0]); + VectorCopy(fd->viewaxis[1], tr.refdef.viewaxis[1]); + VectorCopy(fd->viewaxis[2], tr.refdef.viewaxis[2]); tr.refdef.time = fd->time; tr.refdef.rdflags = fd->rdflags; @@ -319,18 +294,18 @@ void RE_BeginScene(const refdef_t *fd) // copy the areamask data over and note if it has changed, which // will force a reset of the visible leafs even if the view hasn't moved tr.refdef.areamaskModified = qfalse; - if ( ! (tr.refdef.rdflags & RDF_NOWORLDMODEL) ) { - int areaDiff; - int i; + if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) { + int areaDiff; + int i; // compare the area bits areaDiff = 0; - for (i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++) { + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { areaDiff |= ((int *)tr.refdef.areamask)[i] ^ ((int *)fd->areamask)[i]; ((int *)tr.refdef.areamask)[i] = ((int *)fd->areamask)[i]; } - if ( areaDiff ) { + if (areaDiff) { // a door just opened or something tr.refdef.areamaskModified = qtrue; } @@ -341,42 +316,29 @@ void RE_BeginScene(const refdef_t *fd) tr.refdef.sunAmbCol[3] = 1.0f; VectorCopy(tr.sunDirection, tr.refdef.sunDir); - if ( (fd->rdflags & RDF_NOWORLDMODEL) || !(r_depthPrepass->value) ){ + if ((fd->rdflags & RDF_NOWORLDMODEL) || !(r_depthPrepass->value)) { tr.refdef.colorScale = 1.0f; VectorSet(tr.refdef.sunCol, 0, 0, 0); VectorSet(tr.refdef.sunAmbCol, 0, 0, 0); - } - else - { + } else { tr.refdef.colorScale = r_forceSun->integer ? r_forceSunMapLightScale->value : tr.mapLightScale; - if (r_sunlightMode->integer == 1) - { - tr.refdef.sunCol[0] = - tr.refdef.sunCol[1] = - tr.refdef.sunCol[2] = 1.0f; + if (r_sunlightMode->integer == 1) { + tr.refdef.sunCol[0] = tr.refdef.sunCol[1] = tr.refdef.sunCol[2] = 1.0f; - tr.refdef.sunAmbCol[0] = - tr.refdef.sunAmbCol[1] = - tr.refdef.sunAmbCol[2] = r_forceSun->integer ? r_forceSunAmbientScale->value : tr.sunShadowScale; - } - else - { + tr.refdef.sunAmbCol[0] = tr.refdef.sunAmbCol[1] = tr.refdef.sunAmbCol[2] = r_forceSun->integer ? r_forceSunAmbientScale->value : tr.sunShadowScale; + } else { float scale = pow(2.0f, r_mapOverBrightBits->integer - tr.overbrightBits - 8); - if (r_forceSun->integer) - { - VectorScale(tr.sunLight, scale * r_forceSunLightScale->value, tr.refdef.sunCol); + if (r_forceSun->integer) { + VectorScale(tr.sunLight, scale * r_forceSunLightScale->value, tr.refdef.sunCol); VectorScale(tr.sunLight, scale * r_forceSunAmbientScale->value, tr.refdef.sunAmbCol); - } - else - { - VectorScale(tr.sunLight, scale, tr.refdef.sunCol); + } else { + VectorScale(tr.sunLight, scale, tr.refdef.sunCol); VectorScale(tr.sunLight, scale * tr.sunShadowScale, tr.refdef.sunAmbCol); } } - if (r_forceSun->integer == 2) - { + if (r_forceSun->integer == 2) { vec4_t lightDir, lightCol; int scale = 32768; float angle = (fd->time % scale) / (float)scale * M_PI; @@ -385,9 +347,7 @@ void RE_BeginScene(const refdef_t *fd) lightDir[2] = sin(angle) * cos(35.0f * M_PI / 180.0f); lightDir[3] = 0.0f; - lightCol[0] = - lightCol[1] = - lightCol[2] = CLAMP(sin(angle) * 2.0f, 0.0f, 1.0f) * 2.0f; + lightCol[0] = lightCol[1] = lightCol[2] = CLAMP(sin(angle) * 2.0f, 0.0f, 1.0f) * 2.0f; lightCol[3] = 1.0f; VectorCopy4(lightDir, tr.refdef.sunDir); @@ -396,25 +356,19 @@ void RE_BeginScene(const refdef_t *fd) } } - if (r_forceAutoExposure->integer) - { + if (r_forceAutoExposure->integer) { tr.refdef.autoExposureMinMax[0] = r_forceAutoExposureMin->value; tr.refdef.autoExposureMinMax[1] = r_forceAutoExposureMax->value; - } - else - { + } else { tr.refdef.autoExposureMinMax[0] = tr.autoExposureMinMax[0]; tr.refdef.autoExposureMinMax[1] = tr.autoExposureMinMax[1]; } - if (r_forceToneMap->integer) - { + if (r_forceToneMap->integer) { tr.refdef.toneMinAvgMaxLinear[0] = pow(2, r_forceToneMapMin->value); tr.refdef.toneMinAvgMaxLinear[1] = pow(2, r_forceToneMapAvg->value); tr.refdef.toneMinAvgMaxLinear[2] = pow(2, r_forceToneMapMax->value); - } - else - { + } else { tr.refdef.toneMinAvgMaxLinear[0] = pow(2, tr.toneMinAvgMaxLevel[0]); tr.refdef.toneMinAvgMaxLinear[1] = pow(2, tr.toneMinAvgMaxLevel[1]); tr.refdef.toneMinAvgMaxLinear[2] = pow(2, tr.toneMinAvgMaxLevel[2]); @@ -422,19 +376,16 @@ void RE_BeginScene(const refdef_t *fd) // Makro - copy exta info if present if (fd->rdflags & RDF_EXTRA) { - const refdefex_t* extra = (const refdefex_t*) (fd+1); + const refdefex_t *extra = (const refdefex_t *)(fd + 1); tr.refdef.blurFactor = extra->blurFactor; - if (fd->rdflags & RDF_SUNLIGHT) - { - VectorCopy(extra->sunDir, tr.refdef.sunDir); - VectorCopy(extra->sunCol, tr.refdef.sunCol); + if (fd->rdflags & RDF_SUNLIGHT) { + VectorCopy(extra->sunDir, tr.refdef.sunDir); + VectorCopy(extra->sunCol, tr.refdef.sunCol); VectorCopy(extra->sunAmbCol, tr.refdef.sunAmbCol); } - } - else - { + } else { tr.refdef.blurFactor = 0.0f; } @@ -453,7 +404,7 @@ void RE_BeginScene(const refdef_t *fd) // Add the decals here because decals add polys and we need to ensure // that the polys are added before the the renderer is prepared - if ( !(fd->rdflags & RDF_NOWORLDMODEL) ) + if (!(fd->rdflags & RDF_NOWORLDMODEL)) R_AddDecals(); tr.refdef.numPolys = r_numpolys - r_firstScenePoly; @@ -464,20 +415,16 @@ void RE_BeginScene(const refdef_t *fd) // turn off dynamic lighting globally by clearing all the // dlights if it needs to be disabled or if vertex lighting is enabled - if ( r_dynamiclight->integer == 0 || - r_vertexLight->integer == 1 ) { + if (r_dynamiclight->integer == 0 || r_vertexLight->integer == 1) { tr.refdef.num_dlights = 0; } - if (fd->rdflags & RDF_SKYBOXPORTAL) - { + if (fd->rdflags & RDF_SKYBOXPORTAL) { tr.world->skyboxportal = 1; // Don't update constants yet. Store everything and render everything next scene return; - } - else - { + } else { // pasted this from SP // cdr - only change last time for the real render, not the portal tr.refdef.lastTime = fd->time; @@ -491,13 +438,13 @@ void RE_BeginScene(const refdef_t *fd) tr.frameSceneNum++; tr.sceneCount++; - //ri.Printf(PRINT_ALL, "RE_BeginScene Frame: %i, skyportal: %i, entities: %i\n", backEndData->realFrameNumber, int(tr.world->skyboxportal && (tr.refdef.rdflags & RDF_SKYBOXPORTAL)), tr.refdef.num_entities); + // ri.Printf(PRINT_ALL, "RE_BeginScene Frame: %i, skyportal: %i, entities: %i\n", backEndData->realFrameNumber, int(tr.world->skyboxportal && + // (tr.refdef.rdflags & RDF_SKYBOXPORTAL)), tr.refdef.num_entities); R_GatherFrameViews(&tr.refdef); RB_UpdateConstants(&tr.refdef); } -void RE_EndScene() -{ +void RE_EndScene() { // the next scene rendered in this frame will tack on after this one r_firstSceneDrawSurf = tr.refdef.numDrawSurfs; r_firstSceneEntity = r_numentities; @@ -518,31 +465,29 @@ Rendering a scene may require multiple views to be rendered to handle mirrors, @@@@@@@@@@@@@@@@@@@@@ */ -void RE_RenderScene( const refdef_t *fd ) -{ - int startTime; +void RE_RenderScene(const refdef_t *fd) { + int startTime; - if ( !tr.registered ) { + if (!tr.registered) { return; } - GLimp_LogComment( "====== RE_RenderScene =====\n" ); + GLimp_LogComment("====== RE_RenderScene =====\n"); - if ( r_norefresh->integer ) { + if (r_norefresh->integer) { return; } startTime = ri.Milliseconds(); - if (!tr.world && !( fd->rdflags & RDF_NOWORLDMODEL ) ) { - ri.Error (ERR_DROP, "R_RenderScene: NULL worldmodel"); + if (!tr.world && !(fd->rdflags & RDF_NOWORLDMODEL)) { + ri.Error(ERR_DROP, "R_RenderScene: NULL worldmodel"); } RE_BeginScene(fd); // Store skyportal info and don't render yet - if (tr.refdef.rdflags & RDF_SKYBOXPORTAL) - { - viewParms_t parms; + if (tr.refdef.rdflags & RDF_SKYBOXPORTAL) { + viewParms_t parms; Com_Memset(&parms, 0, sizeof(parms)); parms.viewportX = fd->x; parms.viewportY = glConfig.vidHeight - (fd->y + fd->height); @@ -572,8 +517,7 @@ void RE_RenderScene( const refdef_t *fd ) } // Render all the passes - for (int i = 0; i < tr.numCachedViewParms; i++) - { + for (int i = 0; i < tr.numCachedViewParms; i++) { qhandle_t timer = R_BeginTimedBlockCmd(va("Render Pass %i", i)); tr.refdef.numDrawSurfs = 0; R_RenderView(&tr.cachedViewParms[i]); @@ -581,11 +525,10 @@ void RE_RenderScene( const refdef_t *fd ) R_EndTimedBlockCmd(timer); } - if(!( fd->rdflags & RDF_NOWORLDMODEL )) - { - qhandle_t timer = R_BeginTimedBlockCmd( "Post processing" ); + if (!(fd->rdflags & RDF_NOWORLDMODEL)) { + qhandle_t timer = R_BeginTimedBlockCmd("Post processing"); R_AddPostProcessCmd(); - R_EndTimedBlockCmd( timer ); + R_EndTimedBlockCmd(timer); } R_IssuePendingRenderCommands(); diff --git a/codemp/rd-rend2/tr_shade.cpp b/codemp/rd-rend2/tr_shade.cpp index bc65a71cb7..3268bc3538 100644 --- a/codemp/rd-rend2/tr_shade.cpp +++ b/codemp/rd-rend2/tr_shade.cpp @@ -21,7 +21,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ // tr_shade.c -#include "tr_local.h" +#include "tr_local.h" #include "tr_allocator.h" /* @@ -31,10 +31,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA This file deals with applying shaders to surface data in the tess struct. */ -color4ub_t styleColors[MAX_LIGHT_STYLES]; - -void RB_BinTriangleCounts( void ); +color4ub_t styleColors[MAX_LIGHT_STYLES]; +void RB_BinTriangleCounts(void); /* ================== @@ -43,26 +42,17 @@ R_DrawElements ================== */ -void R_DrawElementsVBO( int numIndexes, glIndex_t firstIndex, glIndex_t minIndex, glIndex_t maxIndex ) -{ - int offset = firstIndex * sizeof(glIndex_t) + - (tess.useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); +void R_DrawElementsVBO(int numIndexes, glIndex_t firstIndex, glIndex_t minIndex, glIndex_t maxIndex) { + int offset = firstIndex * sizeof(glIndex_t) + (tess.useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); GL_DrawIndexed(GL_TRIANGLES, numIndexes, GL_INDEX_TYPE, offset, 1, 0); } - -static void R_DrawMultiElementsVBO( int multiDrawPrimitives, glIndex_t *multiDrawMinIndex, glIndex_t *multiDrawMaxIndex, - GLsizei *multiDrawNumIndexes, glIndex_t **multiDrawFirstIndex) -{ - GL_MultiDrawIndexed( - GL_TRIANGLES, - multiDrawNumIndexes, - multiDrawFirstIndex, - multiDrawPrimitives); +static void R_DrawMultiElementsVBO(int multiDrawPrimitives, glIndex_t *multiDrawMinIndex, glIndex_t *multiDrawMaxIndex, GLsizei *multiDrawNumIndexes, + glIndex_t **multiDrawFirstIndex) { + GL_MultiDrawIndexed(GL_TRIANGLES, multiDrawNumIndexes, multiDrawFirstIndex, multiDrawPrimitives); } - /* ============================================================= @@ -71,8 +61,7 @@ SURFACE SHADERS ============================================================= */ -shaderCommands_t tess; - +shaderCommands_t tess; /* ================= @@ -80,10 +69,10 @@ R_BindAnimatedImageToTMU ================= */ -void R_BindAnimatedImageToTMU( textureBundle_t *bundle, int tmu ) { - int index; +void R_BindAnimatedImageToTMU(textureBundle_t *bundle, int tmu) { + int index; - if ( bundle->isVideoMap ) { + if (bundle->isVideoMap) { int oldtmu = glState.currenttmu; GL_SelectTexture(tmu); ri.CIN_RunCinematic(bundle->videoMapHandle); @@ -92,42 +81,35 @@ void R_BindAnimatedImageToTMU( textureBundle_t *bundle, int tmu ) { return; } - if ( bundle->numImageAnimations <= 1 ) { - GL_BindToTMU( bundle->image[0], tmu); + if (bundle->numImageAnimations <= 1) { + GL_BindToTMU(bundle->image[0], tmu); return; } - if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) - { + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX) { index = backEnd.currentEntity->e.skinNum; - } - else - { + } else { // it is necessary to do this messy calc to make sure animations line up // exactly with waveforms of the same frequency - index = Q_ftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index = Q_ftol(tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE); index >>= FUNCTABLE_SIZE2; - if ( index < 0 ) { - index = 0; // may happen with shader time offsets + if (index < 0) { + index = 0; // may happen with shader time offsets } } - if ( bundle->oneShotAnimMap ) - { - if ( index >= bundle->numImageAnimations ) - { + if (bundle->oneShotAnimMap) { + if (index >= bundle->numImageAnimations) { // stick on last frame index = bundle->numImageAnimations - 1; } - } - else - { + } else { // loop index %= bundle->numImageAnimations; } - GL_BindToTMU( bundle->image[ index ], tmu ); + GL_BindToTMU(bundle->image[index], tmu); } /* @@ -139,7 +121,7 @@ because a surface may be forced to perform a RB_End due to overflow. ============== */ -void RB_BeginSurface( shader_t *shader, int fogNum, int cubemapIndex ) { +void RB_BeginSurface(shader_t *shader, int fogNum, int cubemapIndex) { shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader; @@ -150,8 +132,8 @@ void RB_BeginSurface( shader_t *shader, int fogNum, int cubemapIndex ) { tess.shader = state; tess.fogNum = fogNum; tess.cubemapIndex = cubemapIndex; - tess.dlightBits = 0; // will be OR'd in by surface functions - tess.pshadowBits = 0; // will be OR'd in by surface functions + tess.dlightBits = 0; // will be OR'd in by surface functions + tess.pshadowBits = 0; // will be OR'd in by surface functions tess.xstages = state->stages; tess.numPasses = state->numUnfoggedPasses; tess.currentStageIteratorFunc = state->optimalStageIteratorFunc; @@ -163,41 +145,48 @@ void RB_BeginSurface( shader_t *shader, int fogNum, int cubemapIndex ) { tess.shaderTime = tess.shader->clampTime; } - if (backEnd.viewParms.flags & VPF_DEPTHSHADOW) - { + if (backEnd.viewParms.flags & VPF_DEPTHSHADOW) { tess.currentStageIteratorFunc = RB_StageIteratorGeneric; } } +extern float EvalWaveForm(const waveForm_t *wf); +extern float EvalWaveFormClamped(const waveForm_t *wf); - -extern float EvalWaveForm( const waveForm_t *wf ); -extern float EvalWaveFormClamped( const waveForm_t *wf ); - - -static void ComputeTexMods( shaderStage_t *pStage, int bundleNum, float *outMatrix, float *outOffTurb) -{ +static void ComputeTexMods(shaderStage_t *pStage, int bundleNum, float *outMatrix, float *outOffTurb) { int tm; float matrix[6], currentmatrix[6]; textureBundle_t *bundle = &pStage->bundle[bundleNum]; - matrix[0] = 1.0f; matrix[2] = 0.0f; matrix[4] = 0.0f; - matrix[1] = 0.0f; matrix[3] = 1.0f; matrix[5] = 0.0f; + matrix[0] = 1.0f; + matrix[2] = 0.0f; + matrix[4] = 0.0f; + matrix[1] = 0.0f; + matrix[3] = 1.0f; + matrix[5] = 0.0f; + + currentmatrix[0] = 1.0f; + currentmatrix[2] = 0.0f; + currentmatrix[4] = 0.0f; + currentmatrix[1] = 0.0f; + currentmatrix[3] = 1.0f; + currentmatrix[5] = 0.0f; + + outMatrix[0] = 1.0f; + outMatrix[2] = 0.0f; + outMatrix[1] = 0.0f; + outMatrix[3] = 1.0f; + + outOffTurb[0] = 0.0f; + outOffTurb[1] = 0.0f; + outOffTurb[2] = 0.0f; + outOffTurb[3] = 0.0f; + + for (tm = 0; tm < bundle->numTexMods; tm++) { + switch (bundle->texMods[tm].type) { - currentmatrix[0] = 1.0f; currentmatrix[2] = 0.0f; currentmatrix[4] = 0.0f; - currentmatrix[1] = 0.0f; currentmatrix[3] = 1.0f; currentmatrix[5] = 0.0f; - - outMatrix[0] = 1.0f; outMatrix[2] = 0.0f; - outMatrix[1] = 0.0f; outMatrix[3] = 1.0f; - - outOffTurb[0] = 0.0f; outOffTurb[1] = 0.0f; outOffTurb[2] = 0.0f; outOffTurb[3] = 0.0f; - - for ( tm = 0; tm < bundle->numTexMods ; tm++ ) { - switch ( bundle->texMods[tm].type ) - { - case TMOD_NONE: - tm = TR_MAX_TEXMODS; // break out of for loop + tm = TR_MAX_TEXMODS; // break out of for loop break; case TMOD_TURBULENT: @@ -205,41 +194,35 @@ static void ComputeTexMods( shaderStage_t *pStage, int bundleNum, float *outMatr break; case TMOD_ENTITY_TRANSLATE: - RB_CalcScrollTexMatrix( backEnd.currentEntity->e.shaderTexCoord, matrix ); + RB_CalcScrollTexMatrix(backEnd.currentEntity->e.shaderTexCoord, matrix); break; case TMOD_SCROLL: - RB_CalcScrollTexMatrix( bundle->texMods[tm].scroll, - matrix ); + RB_CalcScrollTexMatrix(bundle->texMods[tm].scroll, matrix); break; case TMOD_SCALE: - RB_CalcScaleTexMatrix( bundle->texMods[tm].scale, - matrix ); + RB_CalcScaleTexMatrix(bundle->texMods[tm].scale, matrix); break; - + case TMOD_STRETCH: - RB_CalcStretchTexMatrix( &bundle->texMods[tm].wave, - matrix ); + RB_CalcStretchTexMatrix(&bundle->texMods[tm].wave, matrix); break; case TMOD_TRANSFORM: - RB_CalcTransformTexMatrix( &bundle->texMods[tm], - matrix ); + RB_CalcTransformTexMatrix(&bundle->texMods[tm], matrix); break; case TMOD_ROTATE: - RB_CalcRotateTexMatrix( bundle->texMods[tm].rotateSpeed, - matrix ); + RB_CalcRotateTexMatrix(bundle->texMods[tm].rotateSpeed, matrix); break; default: - ri.Error( ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'", bundle->texMods[tm].type, tess.shader->name ); + ri.Error(ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'", bundle->texMods[tm].type, tess.shader->name); break; } - switch ( bundle->texMods[tm].type ) - { + switch (bundle->texMods[tm].type) { case TMOD_NONE: case TMOD_TURBULENT: default: @@ -271,203 +254,153 @@ static void ComputeTexMods( shaderStage_t *pStage, int bundleNum, float *outMatr } } -static void ComputeShaderColors( shaderStage_t *pStage, vec4_t baseColor, vec4_t vertColor, int blend, colorGen_t *forceRGBGen, alphaGen_t *forceAlphaGen ) -{ +static void ComputeShaderColors(shaderStage_t *pStage, vec4_t baseColor, vec4_t vertColor, int blend, colorGen_t *forceRGBGen, alphaGen_t *forceAlphaGen) { colorGen_t rgbGen = pStage->rgbGen; alphaGen_t alphaGen = pStage->alphaGen; - baseColor[0] = - baseColor[1] = - baseColor[2] = - baseColor[3] = 1.0f; - - vertColor[0] = - vertColor[1] = - vertColor[2] = - vertColor[3] = 0.0f; - - if ( forceRGBGen != NULL && *forceRGBGen != CGEN_BAD ) - { + baseColor[0] = baseColor[1] = baseColor[2] = baseColor[3] = 1.0f; + + vertColor[0] = vertColor[1] = vertColor[2] = vertColor[3] = 0.0f; + + if (forceRGBGen != NULL && *forceRGBGen != CGEN_BAD) { rgbGen = *forceRGBGen; } - if ( forceAlphaGen != NULL && *forceAlphaGen != AGEN_IDENTITY ) - { + if (forceAlphaGen != NULL && *forceAlphaGen != AGEN_IDENTITY) { alphaGen = *forceAlphaGen; } - switch ( rgbGen ) - { - case CGEN_IDENTITY_LIGHTING: - baseColor[0] = - baseColor[1] = - baseColor[2] = tr.identityLight; - break; - case CGEN_EXACT_VERTEX: - case CGEN_EXACT_VERTEX_LIT: - baseColor[0] = - baseColor[1] = - baseColor[2] = - baseColor[3] = 0.0f; - - vertColor[0] = - vertColor[1] = - vertColor[2] = - vertColor[3] = 1.0f; - break; - case CGEN_CONST: - baseColor[0] = pStage->constantColor[0]; - baseColor[1] = pStage->constantColor[1]; - baseColor[2] = pStage->constantColor[2]; - baseColor[3] = pStage->constantColor[3]; - break; - case CGEN_VERTEX: - baseColor[0] = - baseColor[1] = - baseColor[2] = - baseColor[3] = 0.0f; - - vertColor[0] = - vertColor[1] = - vertColor[2] = tr.identityLight; - vertColor[3] = 1.0f; - break; - case CGEN_VERTEX_LIT: - baseColor[0] = - baseColor[1] = - baseColor[2] = - baseColor[3] = 0.0f; - - vertColor[0] = - vertColor[1] = - vertColor[2] = - vertColor[3] = tr.identityLight; - break; - case CGEN_ONE_MINUS_VERTEX: - baseColor[0] = - baseColor[1] = - baseColor[2] = tr.identityLight; - - vertColor[0] = - vertColor[1] = - vertColor[2] = -tr.identityLight; - break; - case CGEN_FOG: - { - fog_t *fog = tr.world->fogs + tess.fogNum; - VectorCopy4(fog->color, baseColor); - } - break; - case CGEN_WAVEFORM: - baseColor[0] = - baseColor[1] = - baseColor[2] = RB_CalcWaveColorSingle( &pStage->rgbWave ); - break; - case CGEN_ENTITY: - case CGEN_LIGHTING_DIFFUSE_ENTITY: - if (backEnd.currentEntity) - { - baseColor[0] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; - baseColor[1] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; - baseColor[2] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; - baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; - - if ( alphaGen == AGEN_IDENTITY && - backEnd.currentEntity->e.shaderRGBA[3] == 255 ) - { - alphaGen = AGEN_SKIP; - } - } - break; - case CGEN_ONE_MINUS_ENTITY: - if (backEnd.currentEntity) - { - baseColor[0] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; - baseColor[1] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; - baseColor[2] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; - baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + switch (rgbGen) { + case CGEN_IDENTITY_LIGHTING: + baseColor[0] = baseColor[1] = baseColor[2] = tr.identityLight; + break; + case CGEN_EXACT_VERTEX: + case CGEN_EXACT_VERTEX_LIT: + baseColor[0] = baseColor[1] = baseColor[2] = baseColor[3] = 0.0f; + + vertColor[0] = vertColor[1] = vertColor[2] = vertColor[3] = 1.0f; + break; + case CGEN_CONST: + baseColor[0] = pStage->constantColor[0]; + baseColor[1] = pStage->constantColor[1]; + baseColor[2] = pStage->constantColor[2]; + baseColor[3] = pStage->constantColor[3]; + break; + case CGEN_VERTEX: + baseColor[0] = baseColor[1] = baseColor[2] = baseColor[3] = 0.0f; + + vertColor[0] = vertColor[1] = vertColor[2] = tr.identityLight; + vertColor[3] = 1.0f; + break; + case CGEN_VERTEX_LIT: + baseColor[0] = baseColor[1] = baseColor[2] = baseColor[3] = 0.0f; + + vertColor[0] = vertColor[1] = vertColor[2] = vertColor[3] = tr.identityLight; + break; + case CGEN_ONE_MINUS_VERTEX: + baseColor[0] = baseColor[1] = baseColor[2] = tr.identityLight; + + vertColor[0] = vertColor[1] = vertColor[2] = -tr.identityLight; + break; + case CGEN_FOG: { + fog_t *fog = tr.world->fogs + tess.fogNum; + VectorCopy4(fog->color, baseColor); + } break; + case CGEN_WAVEFORM: + baseColor[0] = baseColor[1] = baseColor[2] = RB_CalcWaveColorSingle(&pStage->rgbWave); + break; + case CGEN_ENTITY: + case CGEN_LIGHTING_DIFFUSE_ENTITY: + if (backEnd.currentEntity) { + baseColor[0] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; + baseColor[1] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; + baseColor[2] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; + baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + + if (alphaGen == AGEN_IDENTITY && backEnd.currentEntity->e.shaderRGBA[3] == 255) { + alphaGen = AGEN_SKIP; } - break; - case CGEN_LIGHTMAPSTYLE: - VectorScale4 (styleColors[pStage->lightmapStyle], 1.0f / 255.0f, baseColor); - break; - case CGEN_IDENTITY: - case CGEN_LIGHTING_DIFFUSE: - case CGEN_BAD: - break; - default: - break; + } + break; + case CGEN_ONE_MINUS_ENTITY: + if (backEnd.currentEntity) { + baseColor[0] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; + baseColor[1] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; + baseColor[2] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; + baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + break; + case CGEN_LIGHTMAPSTYLE: + VectorScale4(styleColors[pStage->lightmapStyle], 1.0f / 255.0f, baseColor); + break; + case CGEN_IDENTITY: + case CGEN_LIGHTING_DIFFUSE: + case CGEN_BAD: + break; + default: + break; } // // alphaGen // - switch ( alphaGen ) - { - case AGEN_SKIP: - break; - case AGEN_CONST: - if ( rgbGen != CGEN_CONST ) { - baseColor[3] = pStage->constantColor[3]; - vertColor[3] = 0.0f; - } - break; - case AGEN_WAVEFORM: - baseColor[3] = RB_CalcWaveAlphaSingle( &pStage->alphaWave ); - vertColor[3] = 0.0f; - break; - case AGEN_ENTITY: - if (backEnd.currentEntity) - { - baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; - } - vertColor[3] = 0.0f; - break; - case AGEN_ONE_MINUS_ENTITY: - if (backEnd.currentEntity) - { - baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; - } - vertColor[3] = 0.0f; - break; - case AGEN_VERTEX: - if ( rgbGen != CGEN_VERTEX ) { - baseColor[3] = 0.0f; - vertColor[3] = 1.0f; - } - break; - case AGEN_ONE_MINUS_VERTEX: - baseColor[3] = 1.0f; - vertColor[3] = -1.0f; - break; - case AGEN_IDENTITY: - case AGEN_LIGHTING_SPECULAR: - case AGEN_PORTAL: - // Done entirely in vertex program - baseColor[3] = 1.0f; + switch (alphaGen) { + case AGEN_SKIP: + break; + case AGEN_CONST: + if (rgbGen != CGEN_CONST) { + baseColor[3] = pStage->constantColor[3]; vertColor[3] = 0.0f; - break; - default: - break; - } - - if ( forceAlphaGen != NULL ) - { + } + break; + case AGEN_WAVEFORM: + baseColor[3] = RB_CalcWaveAlphaSingle(&pStage->alphaWave); + vertColor[3] = 0.0f; + break; + case AGEN_ENTITY: + if (backEnd.currentEntity) { + baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + vertColor[3] = 0.0f; + break; + case AGEN_ONE_MINUS_ENTITY: + if (backEnd.currentEntity) { + baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + vertColor[3] = 0.0f; + break; + case AGEN_VERTEX: + if (rgbGen != CGEN_VERTEX) { + baseColor[3] = 0.0f; + vertColor[3] = 1.0f; + } + break; + case AGEN_ONE_MINUS_VERTEX: + baseColor[3] = 1.0f; + vertColor[3] = -1.0f; + break; + case AGEN_IDENTITY: + case AGEN_LIGHTING_SPECULAR: + case AGEN_PORTAL: + // Done entirely in vertex program + baseColor[3] = 1.0f; + vertColor[3] = 0.0f; + break; + default: + break; + } + + if (forceAlphaGen != NULL) { *forceAlphaGen = alphaGen; } - if ( forceRGBGen != NULL ) - { + if (forceRGBGen != NULL) { *forceRGBGen = rgbGen; } - + // multiply color by overbrightbits if this isn't a blend - if (tr.overbrightBits - && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_DST_COLOR) - && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_ONE_MINUS_DST_COLOR) - && !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_SRC_COLOR) - && !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) - { + if (tr.overbrightBits && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_DST_COLOR) && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_ONE_MINUS_DST_COLOR) && + !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_SRC_COLOR) && !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) { float scale = 1 << tr.overbrightBits; baseColor[0] *= scale; @@ -494,82 +427,51 @@ static void ComputeShaderColors( shaderStage_t *pStage, vec4_t baseColor, vec4_t #endif } -static void ComputeFogColorMask( shaderStage_t *pStage, vec4_t fogColorMask ) -{ - switch(pStage->adjustColorsForFog) - { - case ACFF_MODULATE_RGB: - fogColorMask[0] = - fogColorMask[1] = - fogColorMask[2] = 1.0f; - fogColorMask[3] = 0.0f; - break; - case ACFF_MODULATE_ALPHA: - fogColorMask[0] = - fogColorMask[1] = - fogColorMask[2] = 0.0f; - fogColorMask[3] = 1.0f; - break; - case ACFF_MODULATE_RGBA: - fogColorMask[0] = - fogColorMask[1] = - fogColorMask[2] = - fogColorMask[3] = 1.0f; - break; - default: - fogColorMask[0] = - fogColorMask[1] = - fogColorMask[2] = - fogColorMask[3] = 0.0f; - break; +static void ComputeFogColorMask(shaderStage_t *pStage, vec4_t fogColorMask) { + switch (pStage->adjustColorsForFog) { + case ACFF_MODULATE_RGB: + fogColorMask[0] = fogColorMask[1] = fogColorMask[2] = 1.0f; + fogColorMask[3] = 0.0f; + break; + case ACFF_MODULATE_ALPHA: + fogColorMask[0] = fogColorMask[1] = fogColorMask[2] = 0.0f; + fogColorMask[3] = 1.0f; + break; + case ACFF_MODULATE_RGBA: + fogColorMask[0] = fogColorMask[1] = fogColorMask[2] = fogColorMask[3] = 1.0f; + break; + default: + fogColorMask[0] = fogColorMask[1] = fogColorMask[2] = fogColorMask[3] = 0.0f; + break; } } -static void CaptureDrawData(const shaderCommands_t *input, shaderStage_t *stage, int glslShaderIndex, int stageIndex ) -{ - if ( !tr.numFramesToCapture ) +static void CaptureDrawData(const shaderCommands_t *input, shaderStage_t *stage, int glslShaderIndex, int stageIndex) { + if (!tr.numFramesToCapture) return; - if ( input->multiDrawPrimitives ) - { + if (input->multiDrawPrimitives) { int numIndexes = 0; - for ( int i = 0; i < input->multiDrawPrimitives; i++ ) + for (int i = 0; i < input->multiDrawPrimitives; i++) numIndexes += input->multiDrawNumIndexes[i]; - const char *data = va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,Y\n", - tr.frameCount, - backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), - stage->glslShaderGroup ? "lightall" : "generic", glslShaderIndex, - input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, - input->fogNum, - input->cubemapIndex, - glState.vertexAttribsState, - glState.glStateBits, - glState.currentVBO->vertexesVBO, - glState.currentIBO->indexesVBO, - numIndexes / 3); + const char *data = + va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,Y\n", tr.frameCount, + backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), stage->glslShaderGroup ? "lightall" : "generic", + glslShaderIndex, input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, input->fogNum, input->cubemapIndex, + glState.vertexAttribsState, glState.glStateBits, glState.currentVBO->vertexesVBO, glState.currentIBO->indexesVBO, numIndexes / 3); ri.FS_Write(data, strlen(data), tr.debugFile); - } - else - { - const char *data = va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,N\n", - tr.frameCount, - backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), - stage->glslShaderGroup ? "lightall" : "generic", glslShaderIndex, - input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, - input->fogNum, - input->cubemapIndex, - glState.vertexAttribsState, - glState.glStateBits, - glState.currentVBO->vertexesVBO, - glState.currentIBO->indexesVBO, - input->numIndexes / 3); + } else { + const char *data = + va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,N\n", tr.frameCount, + backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), stage->glslShaderGroup ? "lightall" : "generic", + glslShaderIndex, input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, input->fogNum, input->cubemapIndex, + glState.vertexAttribsState, glState.glStateBits, glState.currentVBO->vertexesVBO, glState.currentIBO->indexesVBO, input->numIndexes / 3); ri.FS_Write(data, strlen(data), tr.debugFile); } } -uint32_t RB_CreateSortKey( const DrawItem& item, int stage, int layer ) -{ +uint32_t RB_CreateSortKey(const DrawItem &item, int stage, int layer) { uint32_t key = 0; uintptr_t shaderProgram = (uintptr_t)item.program; @@ -582,23 +484,20 @@ uint32_t RB_CreateSortKey( const DrawItem& item, int stage, int layer ) return key; } -static cullType_t RB_GetCullType( const viewParms_t *viewParms, const trRefEntity_t *refEntity, cullType_t shaderCullType ) -{ +static cullType_t RB_GetCullType(const viewParms_t *viewParms, const trRefEntity_t *refEntity, cullType_t shaderCullType) { assert(refEntity); cullType_t cullType = CT_TWO_SIDED; - if ( !backEnd.projection2D ) - { - if ( shaderCullType != CT_TWO_SIDED ) - { + if (!backEnd.projection2D) { + if (shaderCullType != CT_TWO_SIDED) { bool cullFront = (shaderCullType == CT_FRONT_SIDED); - if ( viewParms->isMirror ) + if (viewParms->isMirror) cullFront = !cullFront; - if ( refEntity->mirrored ) + if (refEntity->mirrored) cullFront = !cullFront; - if ( viewParms->flags & VPF_DEPTHSHADOW ) + if (viewParms->flags & VPF_DEPTHSHADOW) cullFront = !cullFront; cullType = (cullFront ? CT_FRONT_SIDED : CT_BACK_SIDED); @@ -608,78 +507,50 @@ static cullType_t RB_GetCullType( const viewParms_t *viewParms, const trRefEntit return cullType; } -DepthRange RB_GetDepthRange( const trRefEntity_t *re, const shader_t *shader ) -{ +DepthRange RB_GetDepthRange(const trRefEntity_t *re, const shader_t *shader) { DepthRange range = {0.0f, 1.0f}; - if ( shader->isSky ) - { + if (shader->isSky) { // r_showsky will let all the sky blocks be drawn in // front of everything to allow developers to see how // much sky is getting sucked in - if ( !r_showsky->integer ) - { + if (!r_showsky->integer) { range.minDepth = 1.0f; range.maxDepth = 1.0f; - } - else - { + } else { range.maxDepth = 0.0f; } - } - else if ( re->e.renderfx & RF_NODEPTH ) - { + } else if (re->e.renderfx & RF_NODEPTH) { range.maxDepth = 0.0f; - } - else if ( re->e.renderfx & RF_DEPTHHACK ) - { + } else if (re->e.renderfx & RF_DEPTHHACK) { range.maxDepth = 0.3f; } return range; } -void RB_FillDrawCommand( - DrawCommand& drawCmd, - GLenum primitiveType, - int numInstances, - const shaderCommands_t *input -) -{ +void RB_FillDrawCommand(DrawCommand &drawCmd, GLenum primitiveType, int numInstances, const shaderCommands_t *input) { drawCmd.primitiveType = primitiveType; drawCmd.numInstances = numInstances; - if ( input->multiDrawPrimitives ) - { - if ( input->multiDrawPrimitives == 1 ) - { + if (input->multiDrawPrimitives) { + if (input->multiDrawPrimitives == 1) { drawCmd.type = DRAW_COMMAND_INDEXED; drawCmd.params.indexed.indexType = GL_INDEX_TYPE; drawCmd.params.indexed.firstIndex = (glIndex_t)(size_t)(input->multiDrawFirstIndex[0]); drawCmd.params.indexed.numIndices = input->multiDrawNumIndexes[0]; drawCmd.params.indexed.baseVertex = 0; - } - else - { + } else { drawCmd.type = DRAW_COMMAND_MULTI_INDEXED; drawCmd.params.multiIndexed.numDraws = input->multiDrawPrimitives; - drawCmd.params.multiIndexed.firstIndices = - ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); - memcpy(drawCmd.params.multiIndexed.firstIndices, - input->multiDrawFirstIndex, - sizeof(glIndex_t *) * input->multiDrawPrimitives); - - drawCmd.params.multiIndexed.numIndices = - ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); - memcpy(drawCmd.params.multiIndexed.numIndices, - input->multiDrawNumIndexes, - sizeof(GLsizei *) * input->multiDrawPrimitives); + drawCmd.params.multiIndexed.firstIndices = ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); + memcpy(drawCmd.params.multiIndexed.firstIndices, input->multiDrawFirstIndex, sizeof(glIndex_t *) * input->multiDrawPrimitives); + + drawCmd.params.multiIndexed.numIndices = ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); + memcpy(drawCmd.params.multiIndexed.numIndices, input->multiDrawNumIndexes, sizeof(GLsizei *) * input->multiDrawPrimitives); } - } - else - { - int offset = input->firstIndex * sizeof(glIndex_t) + - (input->useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); + } else { + int offset = input->firstIndex * sizeof(glIndex_t) + (input->useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); drawCmd.type = DRAW_COMMAND_INDEXED; drawCmd.params.indexed.indexType = GL_INDEX_TYPE; @@ -689,114 +560,85 @@ void RB_FillDrawCommand( } } -static UniformBlockBinding GetCameraBlockUniformBinding( - const trRefEntity_t *refEntity) -{ +static UniformBlockBinding GetCameraBlockUniformBinding(const trRefEntity_t *refEntity) { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.block = UNIFORM_BLOCK_CAMERA; - if (refEntity == &backEnd.entity2D) - { + if (refEntity == &backEnd.entity2D) { binding.ubo = tr.staticUbo; binding.offset = tr.camera2DUboOffset; - } - else if (refEntity == &backEnd.entityFlare) - { + } else if (refEntity == &backEnd.entityFlare) { binding.ubo = tr.staticUbo; binding.offset = tr.cameraFlareUboOffset; - } - else - { + } else { binding.ubo = currentFrameUbo; binding.offset = tr.cameraUboOffsets[backEnd.viewParms.currentViewParm]; } return binding; } -static UniformBlockBinding GetLightsBlockUniformBinding() -{ +static UniformBlockBinding GetLightsBlockUniformBinding() { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.block = UNIFORM_BLOCK_LIGHTS; - if (tr.lightsUboOffset == -1) - { + if (tr.lightsUboOffset == -1) { binding.ubo = tr.staticUbo; binding.offset = tr.defaultLightsUboOffset; - } - else - { + } else { binding.ubo = currentFrameUbo; binding.offset = tr.lightsUboOffset; } return binding; } -static UniformBlockBinding GetSceneBlockUniformBinding() -{ +static UniformBlockBinding GetSceneBlockUniformBinding() { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.block = UNIFORM_BLOCK_SCENE; - if (tr.sceneUboOffset == -1) - { + if (tr.sceneUboOffset == -1) { binding.ubo = tr.staticUbo; binding.offset = tr.defaultSceneUboOffset; - } - else - { + } else { binding.ubo = currentFrameUbo; binding.offset = tr.sceneUboOffset; } return binding; } -static UniformBlockBinding GetFogsBlockUniformBinding() -{ +static UniformBlockBinding GetFogsBlockUniformBinding() { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.block = UNIFORM_BLOCK_FOGS; - if (tr.fogsUboOffset == -1) - { + if (tr.fogsUboOffset == -1) { binding.ubo = tr.staticUbo; binding.offset = tr.defaultFogsUboOffset; - } - else - { + } else { binding.ubo = currentFrameUbo; binding.offset = tr.fogsUboOffset; } return binding; } -static UniformBlockBinding GetEntityBlockUniformBinding( - const trRefEntity_t *refEntity) -{ +static UniformBlockBinding GetEntityBlockUniformBinding(const trRefEntity_t *refEntity) { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.block = UNIFORM_BLOCK_ENTITY; - if (refEntity == &backEnd.entity2D) - { + if (refEntity == &backEnd.entity2D) { binding.ubo = tr.staticUbo; binding.offset = tr.entity2DUboOffset; - } - else if (refEntity == &backEnd.entityFlare) - { + } else if (refEntity == &backEnd.entityFlare) { binding.ubo = tr.staticUbo; binding.offset = tr.entityFlareUboOffset; - } - else - { + } else { binding.ubo = currentFrameUbo; - if (!refEntity || refEntity == &tr.worldEntity) - { + if (!refEntity || refEntity == &tr.worldEntity) { binding.offset = tr.entityUboOffsets[REFENTITYNUM_WORLD]; - } - else - { + } else { const int refEntityNum = refEntity - backEnd.refdef.entities; binding.offset = tr.entityUboOffsets[refEntityNum]; } @@ -805,9 +647,7 @@ static UniformBlockBinding GetEntityBlockUniformBinding( return binding; } -static UniformBlockBinding GetBonesBlockUniformBinding( - const trRefEntity_t *refEntity) -{ +static UniformBlockBinding GetBonesBlockUniformBinding(const trRefEntity_t *refEntity) { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.ubo = currentFrameUbo; @@ -817,24 +657,20 @@ static UniformBlockBinding GetBonesBlockUniformBinding( binding.offset = 0; else if (refEntity == &backEnd.entity2D) binding.offset = 0; - else - { + else { binding.offset = tr.animationBoneUboOffset; } return binding; } -static UniformBlockBinding GetShaderInstanceBlockUniformBinding( - const trRefEntity_t *refEntity, const shader_t *shader) -{ +static UniformBlockBinding GetShaderInstanceBlockUniformBinding(const trRefEntity_t *refEntity, const shader_t *shader) { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; UniformBlockBinding binding = {}; binding.ubo = tr.shaderInstanceUbo; binding.block = UNIFORM_BLOCK_SHADER_INSTANCE; - if (shader->ShaderInstanceUboOffset == -1) - { + if (shader->ShaderInstanceUboOffset == -1) { binding.ubo = tr.staticUbo; binding.offset = tr.defaultShaderInstanceUboOffset; return binding; @@ -854,24 +690,21 @@ Draws triangle outlines for debugging */ static void DrawTris(shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); { int index = 0; - if (input->shader->numDeforms && !ShaderRequiresCPUDeforms(input->shader)) - { + if (input->shader->numDeforms && !ShaderRequiresCPUDeforms(input->shader)) { index |= GENERICDEF_USE_DEFORM_VERTEXES; } #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { index |= GENERICDEF_USE_VERTEX_ANIMATION; } #endif // REND2_SP - else if (glState.skeletalAnimation) - { + else if (glState.skeletalAnimation) { index |= GENERICDEF_USE_SKELETAL_ANIMATION; } @@ -882,17 +715,12 @@ static void DrawTris(shaderCommands_t *input, const VertexArraysProperties *vert uniformDataWriter.Start(sp); const UniformBlockBinding uniformBlockBindings[] = { - GetCameraBlockUniformBinding(backEnd.currentEntity), - GetSceneBlockUniformBinding(), - GetEntityBlockUniformBinding(backEnd.currentEntity), - GetShaderInstanceBlockUniformBinding( - backEnd.currentEntity, input->shader), - GetBonesBlockUniformBinding(backEnd.currentEntity) - }; + GetCameraBlockUniformBinding(backEnd.currentEntity), GetSceneBlockUniformBinding(), GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding(backEnd.currentEntity, input->shader), GetBonesBlockUniformBinding(backEnd.currentEntity)}; samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DIFFUSEMAP); - const vec4_t baseColor = { 1.0f, 1.0f, 1.0f, 1.0f }; - const vec4_t vertColor = { 0.0f, 0.0f, 0.0f, 0.0f }; + const vec4_t baseColor = {1.0f, 1.0f, 1.0f, 1.0f}; + const vec4_t vertColor = {0.0f, 0.0f, 0.0f, 0.0f}; uniformDataWriter.SetUniformVec4(UNIFORM_BASECOLOR, baseColor); uniformDataWriter.SetUniformVec4(UNIFORM_VERTCOLOR, vertColor); @@ -903,13 +731,10 @@ static void DrawTris(shaderCommands_t *input, const VertexArraysProperties *vert item.program = sp; item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; item.uniformData = uniformDataWriter.Finish(frameAllocator); - item.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); - DrawItemSetVertexAttributes( - item, attribs, vertexArrays->numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); @@ -927,15 +752,15 @@ Draws vertex normals for debugging ================ */ static void DrawNormals(shaderCommands_t *input) { - //FIXME: implement this + // FIXME: implement this } -static void ProjectPshadowVBOGLSL( const shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) { - int l; - vec3_t origin; - float radius; +static void ProjectPshadowVBOGLSL(const shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { + int l; + vec3_t origin; + float radius; - if ( !backEnd.refdef.num_pshadows ) { + if (!backEnd.refdef.num_pshadows) { return; } @@ -948,17 +773,17 @@ static void ProjectPshadowVBOGLSL( const shaderCommands_t *input, const VertexAr vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); - for ( l = 0; l < backEnd.refdef.num_pshadows; l++ ) { - pshadow_t *ps; + for (l = 0; l < backEnd.refdef.num_pshadows; l++) { + pshadow_t *ps; shaderProgram_t *sp; vec4_t vector; - if ( !( tess.pshadowBits & ( 1 << l ) ) ) { - continue; // this surface definately doesn't have any of this shadow + if (!(tess.pshadowBits & (1 << l))) { + continue; // this surface definately doesn't have any of this shadow } ps = &backEnd.refdef.pshadows[l]; - VectorCopy( ps->lightOrigin, origin ); + VectorCopy(ps->lightOrigin, origin); radius = ps->lightRadius; sp = &tr.pshadowShader; @@ -999,14 +824,12 @@ static void ProjectPshadowVBOGLSL( const shaderCommands_t *input, const VertexAr item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; item.numAttributes = vertexArrays->numVertexArrays; - item.attributes = ojkAllocArray( - *backEndData->perFrameMemory, vertexArrays->numVertexArrays); - memcpy(item.attributes, attribs, sizeof(*item.attributes)*vertexArrays->numVertexArrays); + item.attributes = ojkAllocArray(*backEndData->perFrameMemory, vertexArrays->numVertexArrays); + memcpy(item.attributes, attribs, sizeof(*item.attributes) * vertexArrays->numVertexArrays); item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); // FIXME: This is a bit ugly with the casting - item.samplerBindings = samplerBindingsWriter.Finish( - *backEndData->perFrameMemory, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(*backEndData->perFrameMemory, &item.numSamplerBindings); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); @@ -1026,8 +849,7 @@ RB_FogPass Blends a fog texture on top of everything else =================== */ -static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) -{ +static void RB_FogPass(shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { cullType_t cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; @@ -1044,15 +866,13 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v else if (glState.skeletalAnimation) shaderBits |= FOGDEF_USE_SKELETAL_ANIMATION; - if (tr.world && tr.world->globalFog && - input->fogNum != tr.world->globalFogIndex && - input->shader->sort != SS_FOG) + if (tr.world && tr.world->globalFog && input->fogNum != tr.world->globalFogIndex && input->shader->sort != SS_FOG) shaderBits |= FOGDEF_USE_FALLBACK_GLOBAL_FOG; if (input->numPasses > 0) if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) shaderBits |= FOGDEF_USE_ALPHA_TEST; - + shaderProgram_t *sp = tr.fogShader + shaderBits; backEnd.pc.c_fogDraws++; @@ -1062,29 +882,24 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v uniformDataWriter.SetUniformInt(UNIFORM_FOGINDEX, input->fogNum - 1); if (input->numPasses > 0) uniformDataWriter.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, input->xstages[0]->alphaTestType); - + uint32_t stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - if ( tess.shader->fogPass == FP_EQUAL ) + if (tess.shader->fogPass == FP_EQUAL) stateBits |= GLS_DEPTHFUNC_EQUAL; if (input->shader->polygonOffset == qtrue) stateBits |= GLS_POLYGON_OFFSET_FILL; const UniformBlockBinding uniformBlockBindings[] = { - GetCameraBlockUniformBinding(backEnd.currentEntity), - GetFogsBlockUniformBinding(), - GetEntityBlockUniformBinding(backEnd.currentEntity), - GetShaderInstanceBlockUniformBinding( - backEnd.currentEntity, input->shader), - GetBonesBlockUniformBinding(backEnd.currentEntity) - }; + GetCameraBlockUniformBinding(backEnd.currentEntity), GetFogsBlockUniformBinding(), GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding(backEnd.currentEntity, input->shader), GetBonesBlockUniformBinding(backEnd.currentEntity)}; SamplerBindingsWriter samplerBindingsWriter; if (input->numPasses > 0) if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) samplerBindingsWriter.AddStaticImage(input->xstages[0]->bundle[0].image[0], 0); - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; DrawItem item = {}; item.renderState.stateBits = stateBits; item.renderState.cullType = cullType; @@ -1092,13 +907,10 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v item.program = sp; item.uniformData = uniformDataWriter.Finish(frameAllocator); item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; - item.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); - DrawItemSetVertexAttributes( - item, attribs, vertexArrays->numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); @@ -1106,8 +918,7 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v RB_AddDrawItem(backEndData->currentPass, key, item); // invert fog planes and render global fog into them - if (input->fogNum != tr.world->globalFogIndex && tr.world->globalFogIndex != -1) - { + if (input->fogNum != tr.world->globalFogIndex && tr.world->globalFogIndex != -1) { // only invert render fog planes if (input->shader->sort != SS_FOG) return; @@ -1123,8 +934,7 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v UniformDataWriter uniformDataWriterBack; uniformDataWriterBack.Start(sp); uniformDataWriterBack.SetUniformInt(UNIFORM_FOGINDEX, tr.world->globalFogIndex - 1); - if (input->numPasses > 0) - { + if (input->numPasses > 0) { uniformDataWriterBack.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, input->xstages[0]->alphaTestType); SamplerBindingsWriter samplerBindingsWriter; if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) @@ -1135,13 +945,10 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v memcpy(&backItem, &item, sizeof(item)); backItem.renderState.cullType = cullType; backItem.uniformData = uniformDataWriterBack.Finish(frameAllocator); - backItem.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + backItem.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); - DrawItemSetVertexAttributes( - backItem, attribs, vertexArrays->numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - backItem, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(backItem, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(backItem, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(backItem.draw, GL_TRIANGLES, 1, input); @@ -1150,23 +957,19 @@ static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *v } } -static unsigned int RB_CalcShaderVertexAttribs( const shader_t *shader ) -{ +static unsigned int RB_CalcShaderVertexAttribs(const shader_t *shader) { unsigned int vertexAttribs = shader->vertexAttribs; #ifdef REND2_SP - if(glState.vertexAnimation) - { - //vertexAttribs &= ~ATTR_COLOR; + if (glState.vertexAnimation) { + // vertexAttribs &= ~ATTR_COLOR; vertexAttribs |= ATTR_POSITION2; - if (vertexAttribs & ATTR_NORMAL) - { + if (vertexAttribs & ATTR_NORMAL) { vertexAttribs |= ATTR_NORMAL2; vertexAttribs |= ATTR_TANGENT2; } } #endif // REND2_SP - if (glState.skeletalAnimation) - { + if (glState.skeletalAnimation) { vertexAttribs |= ATTR_BONE_WEIGHTS; vertexAttribs |= ATTR_BONE_INDEXES; } @@ -1174,39 +977,32 @@ static unsigned int RB_CalcShaderVertexAttribs( const shader_t *shader ) return vertexAttribs; } -static shaderProgram_t *SelectShaderProgram( int stageIndex, shaderStage_t *stage, shaderProgram_t *glslShaderGroup, bool useAlphaTestGE192, bool forceRefraction ) -{ +static shaderProgram_t *SelectShaderProgram(int stageIndex, shaderStage_t *stage, shaderProgram_t *glslShaderGroup, bool useAlphaTestGE192, + bool forceRefraction) { uint32_t index; shaderProgram_t *result = nullptr; - if (forceRefraction) - { + if (forceRefraction) { index = 0; - if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) - { + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) { index |= REFRACTIONDEF_USE_DEFORM_VERTEXES; } #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { index |= REFRACTIONDEF_USE_VERTEX_ANIMATION; } #endif // REND2_SP - else if (glState.skeletalAnimation) - { + else if (glState.skeletalAnimation) { index |= REFRACTIONDEF_USE_SKELETAL_ANIMATION; } if (stage->bundle[0].tcGen != TCGEN_TEXTURE || (stage->bundle[0].numTexMods)) index |= REFRACTIONDEF_USE_TCGEN_AND_TCMOD; - if (!useAlphaTestGE192) - { + if (!useAlphaTestGE192) { if (stage->alphaTestType != ALPHA_TEST_NONE) index |= REFRACTIONDEF_USE_TCGEN_AND_TCMOD | REFRACTIONDEF_USE_ALPHA_TEST; - } - else - { + } else { index |= REFRACTIONDEF_USE_ALPHA_TEST; } @@ -1216,66 +1012,49 @@ static shaderProgram_t *SelectShaderProgram( int stageIndex, shaderStage_t *stag return &tr.refractionShader[index]; } - if (backEnd.depthFill) - { - if (glslShaderGroup == tr.lightallShader) - { + if (backEnd.depthFill) { + if (glslShaderGroup == tr.lightallShader) { index = 0; - if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) - { + if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) { #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { index |= LIGHTDEF_USE_VERTEX_ANIMATION; - } - else + } else #endif // REND2_SP - if (glState.skeletalAnimation) - { - index |= LIGHTDEF_USE_SKELETAL_ANIMATION; - } + if (glState.skeletalAnimation) { + index |= LIGHTDEF_USE_SKELETAL_ANIMATION; + } } - if ( !useAlphaTestGE192 ) - { + if (!useAlphaTestGE192) { if (stage->alphaTestType != ALPHA_TEST_NONE) index |= LIGHTDEF_USE_ALPHA_TEST; - } - else - { + } else { index |= LIGHTDEF_USE_ALPHA_TEST; } result = &stage->glslShaderGroup[index]; backEnd.pc.c_lightallDraws++; - } - else - { + } else { index = 0; - if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) - { + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) { index |= GENERICDEF_USE_DEFORM_VERTEXES; } #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { index |= GENERICDEF_USE_VERTEX_ANIMATION; } #endif // REND2_SP - else if (glState.skeletalAnimation) - { + else if (glState.skeletalAnimation) { index |= GENERICDEF_USE_SKELETAL_ANIMATION; } - if ( !useAlphaTestGE192 ) - { + if (!useAlphaTestGE192) { if (stage->alphaTestType != ALPHA_TEST_NONE) index |= GENERICDEF_USE_TCGEN_AND_TCMOD | GENERICDEF_USE_ALPHA_TEST; - } - else - { + } else { index |= GENERICDEF_USE_ALPHA_TEST; } @@ -1288,47 +1067,34 @@ static shaderProgram_t *SelectShaderProgram( int stageIndex, shaderStage_t *stag result = &tr.genericShader[index]; backEnd.pc.c_genericDraws++; } - } - else if (stage->glslShaderGroup == tr.lightallShader) - { + } else if (stage->glslShaderGroup == tr.lightallShader) { index = stage->glslShaderIndex; - if (r_lightmap->integer && (index & LIGHTDEF_USE_LIGHTMAP) && !(index & LIGHTDEF_USE_LIGHT_VERTEX)) - { + if (r_lightmap->integer && (index & LIGHTDEF_USE_LIGHTMAP) && !(index & LIGHTDEF_USE_LIGHT_VERTEX)) { index = LIGHTDEF_USE_LIGHTMAP; - } - else - { - if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) - { + } else { + if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) { #ifdef REND2_SP - if (glState.vertexAnimation) - { + if (glState.vertexAnimation) { index |= LIGHTDEF_USE_VERTEX_ANIMATION; } #endif // REND2_SP - if (glState.skeletalAnimation) - { + if (glState.skeletalAnimation) { index |= LIGHTDEF_USE_SKELETAL_ANIMATION; - } + } } - if ( !useAlphaTestGE192 ) - { + if (!useAlphaTestGE192) { if (stage->alphaTestType != ALPHA_TEST_NONE) index |= LIGHTDEF_USE_TCGEN_AND_TCMOD | LIGHTDEF_USE_ALPHA_TEST; - } - else - { + } else { index |= LIGHTDEF_USE_ALPHA_TEST; } } result = &stage->glslShaderGroup[index]; backEnd.pc.c_lightallDraws++; - } - else - { + } else { result = GLSL_GetGenericShaderProgram(stageIndex); backEnd.pc.c_genericDraws++; } @@ -1348,8 +1114,7 @@ void RB_ShadowTessEnd(shaderCommands_t *input, const VertexArraysProperties *ver return; } - if (!input->numVertexes || !input->numIndexes || input->useInternalVBO) - { + if (!input->numVertexes || !input->numIndexes || input->useInternalVBO) { return; } @@ -1357,30 +1122,26 @@ void RB_ShadowTessEnd(shaderCommands_t *input, const VertexArraysProperties *ver GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); GL_VertexAttribPointers(vertexArrays->numVertexArrays, attribs); - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; cullType_t cullType = CT_TWO_SIDED; int stateBits = GLS_DEPTHFUNC_LESS | GLS_STENCILTEST_ENABLE | GLS_COLORMASK_BITS; - const UniformBlockBinding uniformBlockBindings[] = { - GetCameraBlockUniformBinding(backEnd.currentEntity), - GetEntityBlockUniformBinding(backEnd.currentEntity), - GetBonesBlockUniformBinding(backEnd.currentEntity) - }; + const UniformBlockBinding uniformBlockBindings[] = {GetCameraBlockUniformBinding(backEnd.currentEntity), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetBonesBlockUniformBinding(backEnd.currentEntity)}; DrawItem item = {}; item.renderState.stateBits = stateBits; item.renderState.cullType = cullType; - DepthRange range = { 0.0f, 1.0f }; + DepthRange range = {0.0f, 1.0f}; item.renderState.depthRange = range; item.program = &tr.volumeShadowShader; item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; - DrawItemSetVertexAttributes( - item, attribs, vertexArrays->numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); @@ -1388,9 +1149,8 @@ void RB_ShadowTessEnd(shaderCommands_t *input, const VertexArraysProperties *ver RB_AddDrawItem(backEndData->currentPass, key, item); } -static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) -{ - Allocator& frameAllocator = *backEndData->perFrameMemory; +static void RB_IterateStagesGeneric(shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { + Allocator &frameAllocator = *backEndData->perFrameMemory; cullType_t cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; @@ -1399,8 +1159,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays UniformDataWriter uniformDataWriter; SamplerBindingsWriter samplerBindingsWriter; - for ( int stage = 0; stage < MAX_SHADER_STAGES; stage++ ) - { + for (int stage = 0; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = input->xstages[stage]; shaderProgram_t *sp; vec4_t texMatrix; @@ -1413,34 +1172,28 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays bool forceRefraction = false; vec4_t disintegrationInfo; - if ( !pStage ) - { + if (!pStage) { break; } - if ( pStage->ss ) - { + if (pStage->ss) { continue; } stateBits = pStage->stateBits; - if (backEnd.currentEntity) - { + if (backEnd.currentEntity) { assert(backEnd.currentEntity->e.renderfx >= 0); - if ( backEnd.currentEntity->e.renderfx & ( RF_DISINTEGRATE1 | RF_DISINTEGRATE2 )) - { - if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1 ) - { + if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) { + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1) { // we want to be able to rip a hole in the thing being // disintegrated, and by doing the depth-testing it avoids some // kinds of artefacts, but will probably introduce others? stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHMASK_TRUE; forceRGBGen = CGEN_DISINTEGRATION_1; useAlphaTestGE192 = true; - } - else + } else forceRGBGen = CGEN_DISINTEGRATION_2; disintegrationInfo[0] = backEnd.currentEntity->e.oldorigin[0]; @@ -1448,9 +1201,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays disintegrationInfo[2] = backEnd.currentEntity->e.oldorigin[2]; disintegrationInfo[3] = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; disintegrationInfo[3] *= disintegrationInfo[3]; - } - else if ( backEnd.currentEntity->e.renderfx & RF_RGB_TINT ) - {//want to use RGBGen from ent + } else if (backEnd.currentEntity->e.renderfx & RF_RGB_TINT) { // want to use RGBGen from ent forceRGBGen = CGEN_ENTITY; } @@ -1461,11 +1212,9 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays if (input->shader->useDistortion == qtrue || backEnd.currentEntity->e.renderfx & RF_DISTORTION) forceRefraction = true; - if ( backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA ) - { + if (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA) { stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - if ( backEnd.currentEntity->e.renderfx & RF_ALPHA_DEPTH ) - { + if (backEnd.currentEntity->e.renderfx & RF_ALPHA_DEPTH) { // depth write, so faces through the model will be stomped // over by nearer ones. this works because we draw // RF_FORCE_ENT_ALPHA stuff after everything else, including @@ -1482,8 +1231,8 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays assert(sp); uniformDataWriter.Start(sp); - - if ( input->fogNum ) { + + if (input->fogNum) { vec4_t fogColorMask; ComputeFogColorMask(pStage, fogColorMask); uniformDataWriter.SetUniformVec4(UNIFORM_FOGCOLORMASK, fogColorMask); @@ -1491,60 +1240,44 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays } float volumetricBaseValue = -1.0f; - if ( backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC ) - { + if (backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC) { volumetricBaseValue = backEnd.currentEntity->e.shaderRGBA[0] / 255.0f; - } - else - { + } else { vec4_t baseColor; vec4_t vertColor; #ifdef REND2_SP_MAYBE // Fade will be set true when rendering some gore surfaces - if (input->fade) - { + if (input->fade) { VectorCopy4(input->svars.colors[input->firstIndex], baseColor); VectorScale4(baseColor, 1.0f / 255.0f, baseColor); VectorSet4(vertColor, 0.0f, 0.0f, 0.0f, 0.0f); - } - else + } else #endif ComputeShaderColors(pStage, baseColor, vertColor, stateBits, &forceRGBGen, &forceAlphaGen); - if ((backEnd.refdef.colorScale != 1.0f) && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) - { + if ((backEnd.refdef.colorScale != 1.0f) && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) { // use VectorScale to only scale first three values, not alpha VectorScale(baseColor, backEnd.refdef.colorScale, baseColor); VectorScale(vertColor, backEnd.refdef.colorScale, vertColor); } - if (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA) - { - baseColor[3] = backEnd.currentEntity->e.shaderRGBA[3] / 255.0f; + if (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA) { + baseColor[3] = backEnd.currentEntity->e.shaderRGBA[3] / 255.0f; vertColor[3] = 0.0f; } - if (backEnd.currentEntity->e.hModel != NULL) - { + if (backEnd.currentEntity->e.hModel != NULL) { model_t *model = R_GetModelByHandle(backEnd.currentEntity->e.hModel); - if (model->type != MOD_BRUSH) - { - switch (forceRGBGen) - { + if (model->type != MOD_BRUSH) { + switch (forceRGBGen) { case CGEN_EXACT_VERTEX: case CGEN_EXACT_VERTEX_LIT: case CGEN_VERTEX: case CGEN_VERTEX_LIT: - baseColor[0] = - baseColor[1] = - baseColor[2] = - baseColor[3] = 0.0f; - - vertColor[0] = - vertColor[1] = - vertColor[2] = - vertColor[3] = tr.identityLight; + baseColor[0] = baseColor[1] = baseColor[2] = baseColor[3] = 0.0f; + + vertColor[0] = vertColor[1] = vertColor[2] = vertColor[3] = tr.identityLight; break; default: break; @@ -1568,12 +1301,9 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) uniformDataWriter.SetUniformVec4(UNIFORM_DISINTEGRATION, disintegrationInfo); - if (forceRefraction) - { + if (forceRefraction) { vec4_t color; - color[0] = - color[1] = - color[2] = powf(2.0f, r_cameraExposure->value); + color[0] = color[1] = color[2] = powf(2.0f, r_cameraExposure->value); color[3] = 10.0f; uniformDataWriter.SetUniformVec4(UNIFORM_COLOR, color); uniformDataWriter.SetUniformVec2(UNIFORM_AUTOEXPOSUREMINMAX, tr.refdef.autoExposureMinMax); @@ -1586,25 +1316,19 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays texMatrix[0] = texMatrix[3] = input->texCoords[input->firstIndex][0][0]; else #endif - ComputeTexMods(pStage, TB_DIFFUSEMAP, texMatrix, texOffTurb); + ComputeTexMods(pStage, TB_DIFFUSEMAP, texMatrix, texOffTurb); uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXMATRIX, texMatrix); uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXOFFTURB, texOffTurb); uniformDataWriter.SetUniformInt(UNIFORM_TCGEN0, pStage->bundle[0].tcGen); uniformDataWriter.SetUniformInt(UNIFORM_TCGEN1, pStage->bundle[1].tcGen); - if (pStage->bundle[0].tcGen == TCGEN_VECTOR) - { + if (pStage->bundle[0].tcGen == TCGEN_VECTOR) { uniformDataWriter.SetUniformVec3(UNIFORM_TCGEN0VECTOR0, pStage->bundle[0].tcGenVectors[0]); uniformDataWriter.SetUniformVec3(UNIFORM_TCGEN0VECTOR1, pStage->bundle[0].tcGenVectors[1]); } - vec4_t normalScale = { - pStage->normalScale[0], - pStage->normalScale[1], - backEnd.viewParms.isPortal ? -1.0f : 1.0f, - pStage->normalScale[3] - }; + vec4_t normalScale = {pStage->normalScale[0], pStage->normalScale[1], backEnd.viewParms.isPortal ? -1.0f : 1.0f, pStage->normalScale[3]}; uniformDataWriter.SetUniformVec4(UNIFORM_NORMALSCALE, normalScale); uniformDataWriter.SetUniformVec4(UNIFORM_SPECULARSCALE, pStage->specularScale); @@ -1612,24 +1336,18 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays const float parallaxBias = r_forceParallaxBias->value > 0.0f ? r_forceParallaxBias->value : pStage->parallaxBias; uniformDataWriter.SetUniformFloat(UNIFORM_PARALLAXBIAS, parallaxBias); - const AlphaTestType alphaTestType = - useAlphaTestGE192 ? ALPHA_TEST_GE192 : pStage->alphaTestType; + const AlphaTestType alphaTestType = useAlphaTestGE192 ? ALPHA_TEST_GE192 : pStage->alphaTestType; uniformDataWriter.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, alphaTestType); // // do multitexture // - bool enableCubeMaps = ( r_cubeMapping->integer - && !(tr.viewParms.flags & VPF_NOCUBEMAPS) - && input->cubemapIndex > 0 - && pStage->rgbGen != CGEN_LIGHTMAPSTYLE ); - bool enableDLights = ( tess.dlightBits - && tess.shader->sort <= SS_OPAQUE - && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY)) - && pStage->rgbGen != CGEN_LIGHTMAPSTYLE ); - - if (forceRefraction) - { + bool enableCubeMaps = + (r_cubeMapping->integer && !(tr.viewParms.flags & VPF_NOCUBEMAPS) && input->cubemapIndex > 0 && pStage->rgbGen != CGEN_LIGHTMAPSTYLE); + bool enableDLights = (tess.dlightBits && tess.shader->sort <= SS_OPAQUE && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY)) && + pStage->rgbGen != CGEN_LIGHTMAPSTYLE); + + if (forceRefraction) { FBO_t *srcFbo = tr.renderFbo; if (tr.msaaResolveFbo) srcFbo = tr.msaaResolveFbo; @@ -1642,44 +1360,30 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays samplerBindingsWriter.AddStaticImage(tr.calcLevelsImage, TB_LEVELSMAP); else samplerBindingsWriter.AddStaticImage(tr.fixedLevelsImage, TB_LEVELSMAP); - } - else if ( backEnd.depthFill ) - { + } else if (backEnd.depthFill) { if (pStage->alphaTestType == ALPHA_TEST_NONE) samplerBindingsWriter.AddStaticImage(tr.whiteImage, 0); - else if ( pStage->bundle[TB_COLORMAP].image[0] != 0 ) + else if (pStage->bundle[TB_COLORMAP].image[0] != 0) samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_COLORMAP], TB_COLORMAP); - } - else if ( pStage->glslShaderGroup == tr.lightallShader ) - { + } else if (pStage->glslShaderGroup == tr.lightallShader) { int i; vec4_t enableTextures = {}; - if (r_sunlightMode->integer && - (backEnd.viewParms.flags & VPF_USESUNLIGHT) && - (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK)) - { + if (r_sunlightMode->integer && (backEnd.viewParms.flags & VPF_USESUNLIGHT) && (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK)) { samplerBindingsWriter.AddStaticImage(tr.sunShadowArrayImage, TB_SHADOWMAP); enableTextures[2] = 1.0f; - } - else + } else samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SHADOWMAP); - if ((r_lightmap->integer == 1 || r_lightmap->integer == 2) && - (pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap)) - { - for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) - { + if ((r_lightmap->integer == 1 || r_lightmap->integer == 2) && (pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap)) { + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) { if (i == TB_DIFFUSEMAP) samplerBindingsWriter.AddStaticImage(tr.whiteImage, i); else samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[i], i); } - } - else if (r_lightmap->integer == 3 && pStage->bundle[TB_DELUXEMAP].image[0]) - { - for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) - { + } else if (r_lightmap->integer == 3 && pStage->bundle[TB_DELUXEMAP].image[0]) { + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) { if (i == TB_LIGHTMAP) samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DELUXEMAP], i); else if (i == TB_DIFFUSEMAP) @@ -1687,11 +1391,9 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays else samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[i], i); } - } - else - { + } else { qboolean light = (qboolean)((pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) != 0); - qboolean allowVertexLighting = (qboolean)!(r_normalMapping->integer || r_specularMapping->integer); + qboolean allowVertexLighting = (qboolean) !(r_normalMapping->integer || r_specularMapping->integer); if (pStage->bundle[TB_DIFFUSEMAP].image[0]) samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DIFFUSEMAP], TB_DIFFUSEMAP); @@ -1708,34 +1410,24 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays // - disable texture sampling in glsl shader with #ifdefs, as before // -> increases the number of shaders that must be compiled // - if (light && !allowVertexLighting) - { - if (pStage->bundle[TB_NORMALMAP].image[0]) - { + if (light && !allowVertexLighting) { + if (pStage->bundle[TB_NORMALMAP].image[0]) { samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_NORMALMAP], TB_NORMALMAP); enableTextures[0] = 1.0f; - } - else if (r_normalMapping->integer) - { + } else if (r_normalMapping->integer) { samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_NORMALMAP); } - if (pStage->bundle[TB_DELUXEMAP].image[0]) - { + if (pStage->bundle[TB_DELUXEMAP].image[0]) { samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DELUXEMAP], TB_DELUXEMAP); enableTextures[1] = 1.0f; - } - else if (r_deluxeMapping->integer) - { + } else if (r_deluxeMapping->integer) { samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DELUXEMAP); } - if (pStage->bundle[TB_SPECULARMAP].image[0]) - { + if (pStage->bundle[TB_SPECULARMAP].image[0]) { samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_SPECULARMAP], TB_SPECULARMAP); - } - else if (r_specularMapping->integer) - { + } else if (r_specularMapping->integer) { samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SPECULARMAP); } @@ -1743,24 +1435,18 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays samplerBindingsWriter.AddStaticImage(tr.screenSsaoImage, TB_SSAOMAP); else if (r_ssao->integer) samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SSAOMAP); - } - if ( enableCubeMaps ) - { - enableTextures[3] = 1.0f; + if (enableCubeMaps) { + enableTextures[3] = 1.0f; } } uniformDataWriter.SetUniformVec4(UNIFORM_ENABLETEXTURES, enableTextures); - } - else if ( pStage->bundle[1].image[0] != 0 ) - { + } else if (pStage->bundle[1].image[0] != 0) { samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[0], 0); samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[1], 1); - } - else - { + } else { // // set state // @@ -1770,8 +1456,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays // // testing cube map // - if ( enableCubeMaps ) - { + if (enableCubeMaps) { vec4_t vec; cubemap_t *cubemap = &tr.cubemaps[input->cubemapIndex - 1]; @@ -1785,28 +1470,23 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays uniformDataWriter.SetUniformVec4(UNIFORM_CUBEMAPINFO, vec); } - - if (enableDLights) - { + + if (enableDLights) { uniformDataWriter.SetUniformInt(UNIFORM_LIGHTMASK, tess.dlightBits); if (r_dlightMode->integer > 1) samplerBindingsWriter.AddStaticImage(tr.pointShadowArrayImage, TB_SHADOWMAPARRAY); - } - else + } else uniformDataWriter.SetUniformInt(UNIFORM_LIGHTMASK, 0); CaptureDrawData(input, pStage, index, stage); - const UniformBlockBinding uniformBlockBindings[] = { - GetCameraBlockUniformBinding(backEnd.currentEntity), - GetLightsBlockUniformBinding(), - GetSceneBlockUniformBinding(), - GetFogsBlockUniformBinding(), - GetEntityBlockUniformBinding(backEnd.currentEntity), - GetShaderInstanceBlockUniformBinding( - backEnd.currentEntity, input->shader), - GetBonesBlockUniformBinding(backEnd.currentEntity) - }; + const UniformBlockBinding uniformBlockBindings[] = {GetCameraBlockUniformBinding(backEnd.currentEntity), + GetLightsBlockUniformBinding(), + GetSceneBlockUniformBinding(), + GetFogsBlockUniformBinding(), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding(backEnd.currentEntity, input->shader), + GetBonesBlockUniformBinding(backEnd.currentEntity)}; DrawItem item = {}; item.renderState.stateBits = stateBits; @@ -1815,13 +1495,10 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays item.program = sp; item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; item.uniformData = uniformDataWriter.Finish(frameAllocator); - item.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); - DrawItemSetVertexAttributes( - item, attribs, vertexArrays->numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); @@ -1830,8 +1507,7 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays RB_AddDrawItem(backEndData->currentPass, key, item); // allow skipping out to show just lightmaps during development - if ( r_lightmap->integer && ( pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap ) ) - { + if (r_lightmap->integer && (pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap)) { break; } @@ -1843,35 +1519,29 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArrays /* ** RB_StageIteratorGeneric */ -void RB_StageIteratorGeneric( void ) -{ +void RB_StageIteratorGeneric(void) { shaderCommands_t *input = &tess; - if (!input->numVertexes || !input->numIndexes) - { + if (!input->numVertexes || !input->numIndexes) { return; } // // log this call // - if ( r_logFile->integer ) - { + if (r_logFile->integer) { // don't just call LogComment, or we will get // a call to va() every frame! - GLimp_LogComment( va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name) ); + GLimp_LogComment(va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name)); } // // update vertex buffer data - // - uint32_t vertexAttribs = RB_CalcShaderVertexAttribs( input->shader ); - if (tess.useInternalVBO) - { + // + uint32_t vertexAttribs = RB_CalcShaderVertexAttribs(input->shader); + if (tess.useInternalVBO) { RB_DeformTessGeometry(); RB_UpdateVBOs(vertexAttribs); - } - else - { + } else { backEnd.pc.c_staticVboDraws++; } @@ -1879,53 +1549,40 @@ void RB_StageIteratorGeneric( void ) // vertex arrays // VertexArraysProperties vertexArrays; - if ( tess.useInternalVBO ) - { + if (tess.useInternalVBO) { CalculateVertexArraysProperties(vertexAttribs, &vertexArrays); - for ( int i = 0; i < vertexArrays.numVertexArrays; i++ ) - { + for (int i = 0; i < vertexArrays.numVertexArrays; i++) { int attributeIndex = vertexArrays.enabledAttributes[i]; vertexArrays.offsets[attributeIndex] += backEndData->currentFrame->dynamicVboCommitOffset; } - } - else - { + } else { CalculateVertexArraysFromVBO(vertexAttribs, glState.currentVBO, &vertexArrays); } - if ( backEnd.depthFill ) - { - RB_IterateStagesGeneric( input, &vertexArrays ); - } - else - { - RB_IterateStagesGeneric( input, &vertexArrays ); + if (backEnd.depthFill) { + RB_IterateStagesGeneric(input, &vertexArrays); + } else { + RB_IterateStagesGeneric(input, &vertexArrays); // // pshadows! // - if (r_shadows->integer == 4 && - tess.pshadowBits && - tess.shader->sort <= SS_OPAQUE && - !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY))) - { - ProjectPshadowVBOGLSL( input, &vertexArrays ); + if (r_shadows->integer == 4 && tess.pshadowBits && tess.shader->sort <= SS_OPAQUE && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY))) { + ProjectPshadowVBOGLSL(input, &vertexArrays); } // // volumeshadows! // - if (glState.genShadows && r_shadows->integer == 2) - { - RB_ShadowTessEnd( input, &vertexArrays ); + if (glState.genShadows && r_shadows->integer == 2) { + RB_ShadowTessEnd(input, &vertexArrays); } // // now do fog // const fog_t *fog = nullptr; - if ( tr.world && input->fogNum != 0) - { + if (tr.world && input->fogNum != 0) { fog = tr.world->fogs + input->fogNum; } if (fog && tess.shader->fogPass && r_drawfog->integer) @@ -1934,35 +1591,34 @@ void RB_StageIteratorGeneric( void ) // // draw debugging stuff // - if ( r_showtris->integer ) { - DrawTris( input, &vertexArrays ); + if (r_showtris->integer) { + DrawTris(input, &vertexArrays); } - if ( r_shownormals->integer ) { - DrawNormals( input ); + if (r_shownormals->integer) { + DrawNormals(input); } } RB_CommitInternalBufferData(); } -void RB_BinTriangleCounts( void ) -{ +void RB_BinTriangleCounts(void) { int numTriangles = tess.numIndexes / 3; - if ( numTriangles < 20 ) + if (numTriangles < 20) backEnd.pc.c_triangleCountBins[TRI_BIN_0_19]++; - else if ( numTriangles < 50 ) + else if (numTriangles < 50) backEnd.pc.c_triangleCountBins[TRI_BIN_20_49]++; - else if ( numTriangles < 100 ) + else if (numTriangles < 100) backEnd.pc.c_triangleCountBins[TRI_BIN_50_99]++; - else if ( numTriangles < 300 ) + else if (numTriangles < 300) backEnd.pc.c_triangleCountBins[TRI_BIN_100_299]++; - else if ( numTriangles < 600 ) + else if (numTriangles < 600) backEnd.pc.c_triangleCountBins[TRI_BIN_300_599]++; - else if ( numTriangles < 1000 ) + else if (numTriangles < 1000) backEnd.pc.c_triangleCountBins[TRI_BIN_1000_1499]++; - else if ( numTriangles < 1500 ) + else if (numTriangles < 1500) backEnd.pc.c_triangleCountBins[TRI_BIN_1500_1999]++; - else if ( numTriangles < 2000 ) + else if (numTriangles < 2000) backEnd.pc.c_triangleCountBins[TRI_BIN_2000_2999]++; else backEnd.pc.c_triangleCountBins[TRI_BIN_3000_PLUS]++; @@ -1971,7 +1627,7 @@ void RB_BinTriangleCounts( void ) /* ** RB_EndSurface */ -void RB_EndSurface( void ) { +void RB_EndSurface(void) { shaderCommands_t *input; input = &tess; @@ -1980,29 +1636,26 @@ void RB_EndSurface( void ) { return; } - if (input->indexes[SHADER_MAX_INDEXES-1] != 0) { - ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); - } - if (input->xyz[SHADER_MAX_VERTEXES-1][0] != 0) { - ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); + if (input->indexes[SHADER_MAX_INDEXES - 1] != 0) { + ri.Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); + } + if (input->xyz[SHADER_MAX_VERTEXES - 1][0] != 0) { + ri.Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); } // for debugging of sort order issues, stop rendering after a given sort value - if ( r_debugSort->integer && r_debugSort->integer < tess.shader->sort ) { + if (r_debugSort->integer && r_debugSort->integer < tess.shader->sort) { return; } if (tr.world && !backEnd.framePostProcessed) { - if (tr.world->skyboxportal) - { + if (tr.world->skyboxportal) { // world - if (!(tr.viewParms.isSkyPortal) && (tess.currentStageIteratorFunc == RB_StageIteratorSky)) - { // don't process these tris at all + if (!(tr.viewParms.isSkyPortal) && (tess.currentStageIteratorFunc == RB_StageIteratorSky)) { // don't process these tris at all return; } // portal sky - else if (!(backEnd.refdef.rdflags & RDF_DRAWSKYBOX) && (tess.currentStageIteratorFunc != RB_StageIteratorSky)) - { // /only/ process sky tris + else if (!(backEnd.refdef.rdflags & RDF_DRAWSKYBOX) && (tess.currentStageIteratorFunc != RB_StageIteratorSky)) { // /only/ process sky tris return; } } @@ -2033,5 +1686,5 @@ void RB_EndSurface( void ) { glState.skeletalAnimation = qfalse; glState.genShadows = qfalse; - GLimp_LogComment( "----------\n" ); + GLimp_LogComment("----------\n"); } diff --git a/codemp/rd-rend2/tr_shade_calc.cpp b/codemp/rd-rend2/tr_shade_calc.cpp index 840bc8087a..1357d5500a 100644 --- a/codemp/rd-rend2/tr_shade_calc.cpp +++ b/codemp/rd-rend2/tr_shade_calc.cpp @@ -23,13 +23,11 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" +#define WAVEVALUE(table, base, amplitude, phase, freq) \ + ((base) + table[Q_ftol((((phase) + tess.shaderTime * (freq)) * FUNCTABLE_SIZE)) & FUNCTABLE_MASK] * (amplitude)) -#define WAVEVALUE( table, base, amplitude, phase, freq ) ((base) + table[ Q_ftol( ( ( (phase) + tess.shaderTime * (freq) ) * FUNCTABLE_SIZE ) ) & FUNCTABLE_MASK ] * (amplitude)) - -static float *TableForFunc( genFunc_t func ) -{ - switch ( func ) - { +static float *TableForFunc(genFunc_t func) { + switch (func) { case GF_SIN: return tr.sinTable; case GF_TRIANGLE: @@ -45,7 +43,7 @@ static float *TableForFunc( genFunc_t func ) break; } - ri.Error( ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'", func, tess.shader->name ); + ri.Error(ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'", func, tess.shader->name); return NULL; } @@ -54,36 +52,32 @@ static float *TableForFunc( genFunc_t func ) ** ** Evaluates a given waveForm_t, referencing backEnd.refdef.time directly */ -static float EvalWaveForm( const waveForm_t *wf ) -{ - float *table; +static float EvalWaveForm(const waveForm_t *wf) { + float *table; - if ( wf->func == GF_NOISE ) { - return ( wf->base + R_NoiseGet4f( 0, 0, 0, ( backEnd.refdef.floatTime + wf->phase ) * wf->frequency ) * wf->amplitude ); + if (wf->func == GF_NOISE) { + return (wf->base + R_NoiseGet4f(0, 0, 0, (backEnd.refdef.floatTime + wf->phase) * wf->frequency) * wf->amplitude); } else if (wf->func == GF_RAND) { - if( GetNoiseTime( backEnd.refdef.time + wf->phase ) <= wf->frequency ) { + if (GetNoiseTime(backEnd.refdef.time + wf->phase) <= wf->frequency) { return (wf->base + wf->amplitude); } else { return wf->base; } } - table = TableForFunc( wf->func ); + table = TableForFunc(wf->func); - return WAVEVALUE( table, wf->base, wf->amplitude, wf->phase, wf->frequency ); + return WAVEVALUE(table, wf->base, wf->amplitude, wf->phase, wf->frequency); } -static float EvalWaveFormClamped( const waveForm_t *wf ) -{ - float glow = EvalWaveForm( wf ); +static float EvalWaveFormClamped(const waveForm_t *wf) { + float glow = EvalWaveForm(wf); - if ( glow < 0 ) - { + if (glow < 0) { return 0; } - if ( glow > 1 ) - { + if (glow > 1) { return 1; } @@ -93,14 +87,17 @@ static float EvalWaveFormClamped( const waveForm_t *wf ) /* ** RB_CalcStretchTexMatrix */ -void RB_CalcStretchTexMatrix( const waveForm_t *wf, float *matrix ) -{ +void RB_CalcStretchTexMatrix(const waveForm_t *wf, float *matrix) { float p; - p = 1.0f / EvalWaveForm( wf ); + p = 1.0f / EvalWaveForm(wf); - matrix[0] = p; matrix[2] = 0; matrix[4] = 0.5f - 0.5f * p; - matrix[1] = 0; matrix[3] = p; matrix[5] = 0.5f - 0.5f * p; + matrix[0] = p; + matrix[2] = 0; + matrix[4] = 0.5f - 0.5f * p; + matrix[1] = 0; + matrix[3] = p; + matrix[5] = 0.5f - 0.5f * p; } /* @@ -117,40 +114,31 @@ RB_CalcDeformVertexes ======================== */ -void RB_CalcDeformVertexes( deformStage_t *ds ) -{ +void RB_CalcDeformVertexes(deformStage_t *ds) { int i; - vec3_t offset; - float scale; - float *xyz = ( float * ) tess.xyz; - uint32_t *normal = ( uint32_t * ) tess.normal; - float *table; - - if ( ds->deformationWave.frequency == 0 ) - { - scale = EvalWaveForm( &ds->deformationWave ); - - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) - { + vec3_t offset; + float scale; + float *xyz = (float *)tess.xyz; + uint32_t *normal = (uint32_t *)tess.normal; + float *table; + + if (ds->deformationWave.frequency == 0) { + scale = EvalWaveForm(&ds->deformationWave); + + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal++) { R_VboUnpackNormal(offset, *normal); - + xyz[0] += offset[0] * scale; xyz[1] += offset[1] * scale; xyz[2] += offset[2] * scale; } - } - else - { - table = TableForFunc( ds->deformationWave.func ); + } else { + table = TableForFunc(ds->deformationWave.func); - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) - { - float off = ( xyz[0] + xyz[1] + xyz[2] ) * ds->deformationSpread; + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal++) { + float off = (xyz[0] + xyz[1] + xyz[2]) * ds->deformationSpread; - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase + off, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase + off, ds->deformationWave.frequency); R_VboUnpackNormal(offset, *normal); @@ -168,33 +156,30 @@ RB_CalcDeformNormals Wiggle the normals for wavy environment mapping ========================= */ -void RB_CalcDeformNormals( deformStage_t *ds ) { +void RB_CalcDeformNormals(deformStage_t *ds) { int i; - float scale; - float *xyz = ( float * ) tess.xyz; - uint32_t *normal = ( uint32_t * ) tess.normal; + float scale; + float *xyz = (float *)tess.xyz; + uint32_t *normal = (uint32_t *)tess.normal; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) { + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal++) { vec3_t fNormal; R_VboUnpackNormal(fNormal, *normal); scale = 0.98f; - scale = R_NoiseGet4f( xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - fNormal[ 0 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + fNormal[0] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - fNormal[ 1 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + fNormal[1] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - fNormal[ 2 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + fNormal[2] += ds->deformationWave.amplitude * scale; - VectorNormalizeFast( fNormal ); + VectorNormalizeFast(fNormal); *normal = R_VboPackNormal(fNormal); } @@ -206,33 +191,32 @@ RB_CalcBulgeVertexes ======================== */ -void RB_CalcBulgeVertexes( deformStage_t *ds ) { +void RB_CalcBulgeVertexes(deformStage_t *ds) { int i; - const float *st = ( const float * ) tess.texCoords[0]; - float *xyz = ( float * ) tess.xyz; - uint32_t *normal = ( uint32_t * ) tess.normal; - float now; + const float *st = (const float *)tess.texCoords[0]; + float *xyz = (float *)tess.xyz; + uint32_t *normal = (uint32_t *)tess.normal; + float now; now = backEnd.refdef.time * ds->bulgeSpeed * 0.001f; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, st += NUM_TESS_TEXCOORDS*2, normal++ ) { - int off; + for (i = 0; i < tess.numVertexes; i++, xyz += 4, st += NUM_TESS_TEXCOORDS * 2, normal++) { + int off; float scale; vec3_t fNormal; R_VboUnpackNormal(fNormal, *normal); - off = (float)( FUNCTABLE_SIZE / (M_PI*2) ) * ( st[0] * ds->bulgeWidth + now ); + off = (float)(FUNCTABLE_SIZE / (M_PI * 2)) * (st[0] * ds->bulgeWidth + now); + + scale = tr.sinTable[off & FUNCTABLE_MASK] * ds->bulgeHeight; - scale = tr.sinTable[ off & FUNCTABLE_MASK ] * ds->bulgeHeight; - xyz[0] += fNormal[0] * scale; xyz[1] += fNormal[1] * scale; xyz[2] += fNormal[2] * scale; } } - /* ====================== RB_CalcMoveVertexes @@ -240,29 +224,25 @@ RB_CalcMoveVertexes A deformation that can move an entire surface along a wave path ====================== */ -void RB_CalcMoveVertexes( deformStage_t *ds ) { - int i; - float *xyz; - float *table; - float scale; - vec3_t offset; +void RB_CalcMoveVertexes(deformStage_t *ds) { + int i; + float *xyz; + float *table; + float scale; + vec3_t offset; - table = TableForFunc( ds->deformationWave.func ); + table = TableForFunc(ds->deformationWave.func); - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase, ds->deformationWave.frequency); - VectorScale( ds->moveVector, scale, offset ); + VectorScale(ds->moveVector, scale, offset); - xyz = ( float * ) tess.xyz; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - VectorAdd( xyz, offset, xyz ); + xyz = (float *)tess.xyz; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + VectorAdd(xyz, offset, xyz); } } - /* ============= DeformText @@ -270,14 +250,14 @@ DeformText Change a polygon into a bunch of text polygons ============= */ -void DeformText( const char *text ) { - int i; - vec3_t origin, width, height; - int len; - int ch; - float color[4]; - float bottom, top; - vec3_t mid; +void DeformText(const char *text) { + int i; + vec3_t origin, width, height; + int len; + int ch; + float color[4]; + float bottom, top; + vec3_t mid; vec3_t fNormal; height[0] = 0; @@ -285,33 +265,33 @@ void DeformText( const char *text ) { height[2] = -1; R_VboUnpackNormal(fNormal, tess.normal[0]); - CrossProduct( fNormal, height, width ); + CrossProduct(fNormal, height, width); // find the midpoint of the box - VectorClear( mid ); + VectorClear(mid); bottom = 999999; top = -999999; - for ( i = 0 ; i < 4 ; i++ ) { - VectorAdd( tess.xyz[i], mid, mid ); - if ( tess.xyz[i][2] < bottom ) { + for (i = 0; i < 4; i++) { + VectorAdd(tess.xyz[i], mid, mid); + if (tess.xyz[i][2] < bottom) { bottom = tess.xyz[i][2]; } - if ( tess.xyz[i][2] > top ) { + if (tess.xyz[i][2] > top) { top = tess.xyz[i][2]; } } - VectorScale( mid, 0.25f, origin ); + VectorScale(mid, 0.25f, origin); // determine the individual character size height[0] = 0; height[1] = 0; - height[2] = ( top - bottom ) * 0.5f; + height[2] = (top - bottom) * 0.5f; - VectorScale( width, height[2] * -0.75f, width ); + VectorScale(width, height[2] * -0.75f, width); // determine the starting position - len = strlen( text ); - VectorMA( origin, (len-1), width, origin ); + len = strlen(text); + VectorMA(origin, (len - 1), width, origin); // clear the shader indexes tess.numIndexes = 0; @@ -321,24 +301,24 @@ void DeformText( const char *text ) { color[0] = color[1] = color[2] = color[3] = 1.0f; // draw each character - for ( i = 0 ; i < len ; i++ ) { + for (i = 0; i < len; i++) { ch = text[i]; ch &= 255; - if ( ch != ' ' ) { - int row, col; - float frow, fcol, size; + if (ch != ' ') { + int row, col; + float frow, fcol, size; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; - frow = row*0.0625f; - fcol = col*0.0625f; + frow = row * 0.0625f; + fcol = col * 0.0625f; size = 0.0625f; - RB_AddQuadStampExt( origin, width, height, color, fcol, frow, fcol + size, frow + size ); + RB_AddQuadStampExt(origin, width, height, color, fcol, frow, fcol + size, frow + size); } - VectorMA( origin, -2, width, origin ); + VectorMA(origin, -2, width, origin); } } @@ -347,10 +327,10 @@ void DeformText( const char *text ) { GlobalVectorToLocal ================== */ -static void GlobalVectorToLocal( const vec3_t in, vec3_t out ) { - out[0] = DotProduct( in, backEnd.ori.axis[0] ); - out[1] = DotProduct( in, backEnd.ori.axis[1] ); - out[2] = DotProduct( in, backEnd.ori.axis[2] ); +static void GlobalVectorToLocal(const vec3_t in, vec3_t out) { + out[0] = DotProduct(in, backEnd.ori.axis[0]); + out[1] = DotProduct(in, backEnd.ori.axis[1]); + out[2] = DotProduct(in, backEnd.ori.axis[2]); } /* @@ -361,20 +341,20 @@ Assuming all the triangles for this shader are independant quads, rebuild them as forward facing sprites ===================== */ -static void AutospriteDeform( void ) { - int i; - int oldVerts; - float *xyz; - vec3_t mid, delta; - float radius; - vec3_t left, up; - vec3_t leftDir, upDir; - - if ( tess.numVertexes & 3 ) { - ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd vertex count\n", tess.shader->name ); +static void AutospriteDeform(void) { + int i; + int oldVerts; + float *xyz; + vec3_t mid, delta; + float radius; + vec3_t left, up; + vec3_t leftDir, upDir; + + if (tess.numVertexes & 3) { + ri.Printf(PRINT_WARNING, "Autosprite shader %s had odd vertex count\n", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd index count\n", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + ri.Printf(PRINT_WARNING, "Autosprite shader %s had odd index count\n", tess.shader->name); } oldVerts = tess.numVertexes; @@ -382,15 +362,15 @@ static void AutospriteDeform( void ) { tess.numIndexes = 0; tess.firstIndex = 0; - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[1], leftDir ); - GlobalVectorToLocal( backEnd.viewParms.ori.axis[2], upDir ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[1], leftDir); + GlobalVectorToLocal(backEnd.viewParms.ori.axis[2], upDir); } else { - VectorCopy( backEnd.viewParms.ori.axis[1], leftDir ); - VectorCopy( backEnd.viewParms.ori.axis[2], upDir ); + VectorCopy(backEnd.viewParms.ori.axis[1], leftDir); + VectorCopy(backEnd.viewParms.ori.axis[2], upDir); } - for ( i = 0 ; i < oldVerts ; i+=4 ) { + for (i = 0; i < oldVerts; i += 4) { // find the midpoint xyz = tess.xyz[i]; @@ -398,34 +378,33 @@ static void AutospriteDeform( void ) { mid[1] = 0.25f * (xyz[1] + xyz[5] + xyz[9] + xyz[13]); mid[2] = 0.25f * (xyz[2] + xyz[6] + xyz[10] + xyz[14]); - VectorSubtract( xyz, mid, delta ); - radius = VectorLength( delta ) * 0.707f; // / sqrt(2) + VectorSubtract(xyz, mid, delta); + radius = VectorLength(delta) * 0.707f; // / sqrt(2) + + VectorScale(leftDir, radius, left); + VectorScale(upDir, radius, up); - VectorScale( leftDir, radius, left ); - VectorScale( upDir, radius, up ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); + } - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + // compensate for scale in the axes if necessary + if (backEnd.currentEntity->e.nonNormalizedAxes) { + float axisLength; + axisLength = VectorLength(backEnd.currentEntity->e.axis[0]); + if (!axisLength) { + axisLength = 0; + } else { + axisLength = 1.0f / axisLength; + } + VectorScale(left, axisLength, left); + VectorScale(up, axisLength, up); } - // compensate for scale in the axes if necessary - if ( backEnd.currentEntity->e.nonNormalizedAxes ) { - float axisLength; - axisLength = VectorLength( backEnd.currentEntity->e.axis[0] ); - if ( !axisLength ) { - axisLength = 0; - } else { - axisLength = 1.0f / axisLength; - } - VectorScale(left, axisLength, left); - VectorScale(up, axisLength, up); - } - - RB_AddQuadStamp( mid, left, up, tess.vertexColors[i] ); + RB_AddQuadStamp(mid, left, up, tess.vertexColors[i]); } } - /* ===================== Autosprite2Deform @@ -433,43 +412,36 @@ Autosprite2Deform Autosprite2 will pivot a rectangular quad along the center of its long axis ===================== */ -int edgeVerts[6][2] = { - { 0, 1 }, - { 0, 2 }, - { 0, 3 }, - { 1, 2 }, - { 1, 3 }, - { 2, 3 } -}; - -static void Autosprite2Deform( void ) { - int i, j, k; - int indexes; - float *xyz; - vec3_t forward; - - if ( tess.numVertexes & 3 ) { - ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd vertex count\n", tess.shader->name ); +int edgeVerts[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}}; + +static void Autosprite2Deform(void) { + int i, j, k; + int indexes; + float *xyz; + vec3_t forward; + + if (tess.numVertexes & 3) { + ri.Printf(PRINT_WARNING, "Autosprite2 shader %s had odd vertex count\n", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd index count\n", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + ri.Printf(PRINT_WARNING, "Autosprite2 shader %s had odd index count\n", tess.shader->name); } - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[0], forward ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[0], forward); } else { - VectorCopy( backEnd.viewParms.ori.axis[0], forward ); + VectorCopy(backEnd.viewParms.ori.axis[0], forward); } // this is a lot of work for two triangles... // we could precalculate a lot of it is an issue, but it would mess up // the shader abstraction - for ( i = 0, indexes = 0 ; i < tess.numVertexes ; i+=4, indexes+=6 ) { - float lengths[2]; - int nums[2]; - vec3_t mid[2]; - vec3_t major, minor; - float *v1, *v2; + for (i = 0, indexes = 0; i < tess.numVertexes; i += 4, indexes += 6) { + float lengths[2]; + int nums[2]; + vec3_t mid[2]; + vec3_t major, minor; + float *v1, *v2; // find the midpoint xyz = tess.xyz[i]; @@ -478,28 +450,28 @@ static void Autosprite2Deform( void ) { nums[0] = nums[1] = 0; lengths[0] = lengths[1] = 999999; - for ( j = 0 ; j < 6 ; j++ ) { - float l; - vec3_t temp; + for (j = 0; j < 6; j++) { + float l; + vec3_t temp; v1 = xyz + 4 * edgeVerts[j][0]; v2 = xyz + 4 * edgeVerts[j][1]; - VectorSubtract( v1, v2, temp ); - - l = DotProduct( temp, temp ); - if ( l < lengths[0] ) { + VectorSubtract(v1, v2, temp); + + l = DotProduct(temp, temp); + if (l < lengths[0]) { nums[1] = nums[0]; lengths[1] = lengths[0]; nums[0] = j; lengths[0] = l; - } else if ( l < lengths[1] ) { + } else if (l < lengths[1]) { nums[1] = j; lengths[1] = l; } } - for ( j = 0 ; j < 2 ; j++ ) { + for (j = 0; j < 2; j++) { v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; @@ -509,75 +481,72 @@ static void Autosprite2Deform( void ) { } // find the vector of the major axis - VectorSubtract( mid[1], mid[0], major ); + VectorSubtract(mid[1], mid[0], major); // cross this with the view direction to get minor axis - CrossProduct( major, forward, minor ); - VectorNormalize( minor ); - + CrossProduct(major, forward, minor); + VectorNormalize(minor); + // re-project the points - for ( j = 0 ; j < 2 ; j++ ) { - float l; + for (j = 0; j < 2; j++) { + float l; v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; - l = 0.5 * sqrt( lengths[j] ); - + l = 0.5 * sqrt(lengths[j]); + // we need to see which direction this edge // is used to determine direction of projection - for ( k = 0 ; k < 5 ; k++ ) { - if ( tess.indexes[ indexes + k ] == i + edgeVerts[nums[j]][0] - && tess.indexes[ indexes + k + 1 ] == i + edgeVerts[nums[j]][1] ) { + for (k = 0; k < 5; k++) { + if (tess.indexes[indexes + k] == i + edgeVerts[nums[j]][0] && tess.indexes[indexes + k + 1] == i + edgeVerts[nums[j]][1]) { break; } } - if ( k == 5 ) { - VectorMA( mid[j], l, minor, v1 ); - VectorMA( mid[j], -l, minor, v2 ); + if (k == 5) { + VectorMA(mid[j], l, minor, v1); + VectorMA(mid[j], -l, minor, v2); } else { - VectorMA( mid[j], -l, minor, v1 ); - VectorMA( mid[j], l, minor, v2 ); + VectorMA(mid[j], -l, minor, v1); + VectorMA(mid[j], l, minor, v2); } } } } - /* ===================== RB_DeformTessGeometry ===================== */ -void RB_DeformTessGeometry( void ) { - int i; - deformStage_t *ds; +void RB_DeformTessGeometry(void) { + int i; + deformStage_t *ds; - if(!ShaderRequiresCPUDeforms(tess.shader)) - { + if (!ShaderRequiresCPUDeforms(tess.shader)) { // we don't need the following CPU deforms return; } - for ( i = 0 ; i < tess.shader->numDeforms ; i++ ) { - ds = &tess.shader->deforms[ i ]; + for (i = 0; i < tess.shader->numDeforms; i++) { + ds = &tess.shader->deforms[i]; - switch ( ds->deformation ) { - case DEFORM_NONE: - break; + switch (ds->deformation) { + case DEFORM_NONE: + break; case DEFORM_NORMALS: - RB_CalcDeformNormals( ds ); + RB_CalcDeformNormals(ds); break; case DEFORM_WAVE: - RB_CalcDeformVertexes( ds ); + RB_CalcDeformVertexes(ds); break; case DEFORM_BULGE: - RB_CalcBulgeVertexes( ds ); + RB_CalcBulgeVertexes(ds); break; case DEFORM_MOVE: - RB_CalcMoveVertexes( ds ); + RB_CalcMoveVertexes(ds); break; case DEFORM_PROJECTION_SHADOW: RB_ProjectionShadowDeform(); @@ -596,7 +565,7 @@ void RB_DeformTessGeometry( void ) { case DEFORM_TEXT5: case DEFORM_TEXT6: case DEFORM_TEXT7: - DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] ); + DeformText(backEnd.refdef.text[ds->deformation - DEFORM_TEXT0]); break; } } @@ -610,24 +579,21 @@ COLORS ==================================================================== */ - /* ** RB_CalcWaveColorSingle */ -float RB_CalcWaveColorSingle( const waveForm_t *wf ) -{ +float RB_CalcWaveColorSingle(const waveForm_t *wf) { float glow; - if ( wf->func == GF_NOISE ) { - glow = wf->base + R_NoiseGet4f( 0, 0, 0, ( tess.shaderTime + wf->phase ) * wf->frequency ) * wf->amplitude; + if (wf->func == GF_NOISE) { + glow = wf->base + R_NoiseGet4f(0, 0, 0, (tess.shaderTime + wf->phase) * wf->frequency) * wf->amplitude; } else { - glow = EvalWaveForm( wf ) * tr.identityLight; + glow = EvalWaveForm(wf) * tr.identityLight; } - - if ( glow < 0 ) { + + if (glow < 0) { glow = 0; - } - else if ( glow > 1 ) { + } else if (glow > 1) { glow = 1; } @@ -637,25 +603,22 @@ float RB_CalcWaveColorSingle( const waveForm_t *wf ) /* ** RB_CalcWaveAlphaSingle */ -float RB_CalcWaveAlphaSingle( const waveForm_t *wf ) -{ - return EvalWaveFormClamped( wf ); -} +float RB_CalcWaveAlphaSingle(const waveForm_t *wf) { return EvalWaveFormClamped(wf); } /* ** RB_CalcModulateColorsByFog */ -void RB_CalcModulateColorsByFog( unsigned char *colors ) { - int i; - float texCoords[SHADER_MAX_VERTEXES][2]; +void RB_CalcModulateColorsByFog(unsigned char *colors) { + int i; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[0] *= f; colors[1] *= f; colors[2] *= f; @@ -679,24 +642,24 @@ projected textures, but I don't trust the drivers and it doesn't fit our shader data. ======================== */ -void RB_CalcFogTexCoords( float *st ) { - int i; - float *v; - float s, t; - float eyeT; - qboolean eyeOutside; - fog_t *fog; - vec3_t local; - vec4_t fogDistanceVector, fogDepthVector = {0, 0, 0, 0}; +void RB_CalcFogTexCoords(float *st) { + int i; + float *v; + float s, t; + float eyeT; + qboolean eyeOutside; + fog_t *fog; + vec3_t local; + vec4_t fogDistanceVector, fogDepthVector = {0, 0, 0, 0}; fog = tr.world->fogs + tess.fogNum; // all fogging distance is based on world Z units - VectorSubtract( backEnd.ori.origin, backEnd.viewParms.ori.origin, local ); + VectorSubtract(backEnd.ori.origin, backEnd.viewParms.ori.origin, local); fogDistanceVector[0] = -backEnd.ori.modelViewMatrix[2]; fogDistanceVector[1] = -backEnd.ori.modelViewMatrix[6]; fogDistanceVector[2] = -backEnd.ori.modelViewMatrix[10]; - fogDistanceVector[3] = DotProduct( local, backEnd.viewParms.ori.axis[0] ); + fogDistanceVector[3] = DotProduct(local, backEnd.viewParms.ori.axis[0]); // scale the fog vectors based on the fog's thickness fogDistanceVector[0] *= fog->tcScale; @@ -705,49 +668,46 @@ void RB_CalcFogTexCoords( float *st ) { fogDistanceVector[3] *= fog->tcScale; // rotate the gradient vector for this orientation - if ( fog->hasSurface ) { - fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + - fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; - fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + - fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; - fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + - fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; - fogDepthVector[3] = -fog->surface[3] + DotProduct( backEnd.ori.origin, fog->surface ); - - eyeT = DotProduct( backEnd.ori.viewOrigin, fogDepthVector ) + fogDepthVector[3]; + if (fog->hasSurface) { + fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; + fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; + fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; + fogDepthVector[3] = -fog->surface[3] + DotProduct(backEnd.ori.origin, fog->surface); + + eyeT = DotProduct(backEnd.ori.viewOrigin, fogDepthVector) + fogDepthVector[3]; } else { - eyeT = 1; // non-surface fog always has eye inside + eyeT = 1; // non-surface fog always has eye inside } // see if the viewpoint is outside // this is needed for clipping distance even for constant fog - if ( eyeT < 0 ) { + if (eyeT < 0) { eyeOutside = qtrue; } else { eyeOutside = qfalse; } - fogDistanceVector[3] += 1.0/512; + fogDistanceVector[3] += 1.0 / 512; // calculate density for each point - for (i = 0, v = tess.xyz[0] ; i < tess.numVertexes ; i++, v += 4) { + for (i = 0, v = tess.xyz[0]; i < tess.numVertexes; i++, v += 4) { // calculate the length in fog - s = DotProduct( v, fogDistanceVector ) + fogDistanceVector[3]; - t = DotProduct( v, fogDepthVector ) + fogDepthVector[3]; + s = DotProduct(v, fogDistanceVector) + fogDistanceVector[3]; + t = DotProduct(v, fogDepthVector) + fogDepthVector[3]; - // partially clipped fogs use the T axis - if ( eyeOutside ) { - if ( t < 1.0 ) { - t = 1.0/32; // point is outside, so no fogging + // partially clipped fogs use the T axis + if (eyeOutside) { + if (t < 1.0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 1.0/32 + 30.0/32 * t / ( t - eyeT ); // cut the distance at the fog plane + t = 1.0 / 32 + 30.0 / 32 * t / (t - eyeT); // cut the distance at the fog plane } } else { - if ( t < 0 ) { - t = 1.0/32; // point is outside, so no fogging + if (t < 0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 31.0/32; + t = 31.0 / 32; } } @@ -760,8 +720,7 @@ void RB_CalcFogTexCoords( float *st ) { /* ** RB_CalcTurbulentFactors */ -void RB_CalcTurbulentFactors( const waveForm_t *wf, float *amplitude, float *now ) -{ +void RB_CalcTurbulentFactors(const waveForm_t *wf, float *amplitude, float *now) { *now = wf->phase + tess.shaderTime * wf->frequency; *amplitude = wf->amplitude; } @@ -769,17 +728,19 @@ void RB_CalcTurbulentFactors( const waveForm_t *wf, float *amplitude, float *now /* ** RB_CalcScaleTexMatrix */ -void RB_CalcScaleTexMatrix( const float scale[2], float *matrix ) -{ - matrix[0] = scale[0]; matrix[2] = 0.0f; matrix[4] = 0.0f; - matrix[1] = 0.0f; matrix[3] = scale[1]; matrix[5] = 0.0f; +void RB_CalcScaleTexMatrix(const float scale[2], float *matrix) { + matrix[0] = scale[0]; + matrix[2] = 0.0f; + matrix[4] = 0.0f; + matrix[1] = 0.0f; + matrix[3] = scale[1]; + matrix[5] = 0.0f; } /* ** RB_CalcScrollTexMatrix */ -void RB_CalcScrollTexMatrix( const float scrollSpeed[2], float *matrix ) -{ +void RB_CalcScrollTexMatrix(const float scrollSpeed[2], float *matrix) { float timeScale = tess.shaderTime; float adjustedScrollS, adjustedScrollT; @@ -788,38 +749,48 @@ void RB_CalcScrollTexMatrix( const float scrollSpeed[2], float *matrix ) // clamp so coordinates don't continuously get larger, causing problems // with hardware limits - adjustedScrollS = adjustedScrollS - floor( adjustedScrollS ); - adjustedScrollT = adjustedScrollT - floor( adjustedScrollT ); - - matrix[0] = 1.0f; matrix[2] = 0.0f; matrix[4] = adjustedScrollS; - matrix[1] = 0.0f; matrix[3] = 1.0f; matrix[5] = adjustedScrollT; + adjustedScrollS = adjustedScrollS - floor(adjustedScrollS); + adjustedScrollT = adjustedScrollT - floor(adjustedScrollT); + + matrix[0] = 1.0f; + matrix[2] = 0.0f; + matrix[4] = adjustedScrollS; + matrix[1] = 0.0f; + matrix[3] = 1.0f; + matrix[5] = adjustedScrollT; } /* ** RB_CalcTransformTexMatrix */ -void RB_CalcTransformTexMatrix( const texModInfo_t *tmi, float *matrix ) -{ - matrix[0] = tmi->matrix[0][0]; matrix[2] = tmi->matrix[1][0]; matrix[4] = tmi->translate[0]; - matrix[1] = tmi->matrix[0][1]; matrix[3] = tmi->matrix[1][1]; matrix[5] = tmi->translate[1]; +void RB_CalcTransformTexMatrix(const texModInfo_t *tmi, float *matrix) { + matrix[0] = tmi->matrix[0][0]; + matrix[2] = tmi->matrix[1][0]; + matrix[4] = tmi->translate[0]; + matrix[1] = tmi->matrix[0][1]; + matrix[3] = tmi->matrix[1][1]; + matrix[5] = tmi->translate[1]; } /* ** RB_CalcRotateTexMatrix */ -void RB_CalcRotateTexMatrix( float degsPerSecond, float *matrix ) -{ +void RB_CalcRotateTexMatrix(float degsPerSecond, float *matrix) { float timeScale = tess.shaderTime; float degs; int index; float sinValue, cosValue; degs = -degsPerSecond * timeScale; - index = degs * ( FUNCTABLE_SIZE / 360.0f ); + index = degs * (FUNCTABLE_SIZE / 360.0f); - sinValue = tr.sinTable[ index & FUNCTABLE_MASK ]; - cosValue = tr.sinTable[ ( index + FUNCTABLE_SIZE / 4 ) & FUNCTABLE_MASK ]; + sinValue = tr.sinTable[index & FUNCTABLE_MASK]; + cosValue = tr.sinTable[(index + FUNCTABLE_SIZE / 4) & FUNCTABLE_MASK]; - matrix[0] = cosValue; matrix[2] = -sinValue; matrix[4] = 0.5 - 0.5 * cosValue + 0.5 * sinValue; - matrix[1] = sinValue; matrix[3] = cosValue; matrix[5] = 0.5 - 0.5 * sinValue - 0.5 * cosValue; + matrix[0] = cosValue; + matrix[2] = -sinValue; + matrix[4] = 0.5 - 0.5 * cosValue + 0.5 * sinValue; + matrix[1] = sinValue; + matrix[3] = cosValue; + matrix[5] = 0.5 - 0.5 * sinValue - 0.5 * cosValue; } diff --git a/codemp/rd-rend2/tr_shader.cpp b/codemp/rd-rend2/tr_shader.cpp index c3f8e2c470..70884c9596 100644 --- a/codemp/rd-rend2/tr_shader.cpp +++ b/codemp/rd-rend2/tr_shader.cpp @@ -27,104 +27,64 @@ static char *s_shaderText; // the shader is parsed into these global variables, then copied into // dynamically allocated memory if it is valid. -static shaderStage_t stages[MAX_SHADER_STAGES]; -static shader_t shader; -static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; +static shaderStage_t stages[MAX_SHADER_STAGES]; +static shader_t shader; +static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; // Hash value (generated using the generateHashValueForText function) for the original // retail JKA shader for gfx/2d/wedge. #define RETAIL_ROCKET_WEDGE_SHADER_HASH (1217042) -#define FILE_HASH_SIZE 1024 -static shader_t* hashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 +static shader_t *hashTable[FILE_HASH_SIZE]; -#define MAX_SHADERTEXT_HASH 2048 -static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = { 0 }; +#define MAX_SHADERTEXT_HASH 2048 +static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = {0}; -const int lightmapsNone[MAXLIGHTMAPS] = -{ - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE -}; +const int lightmapsNone[MAXLIGHTMAPS] = {LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE}; -const int lightmaps2d[MAXLIGHTMAPS] = -{ - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D -}; +const int lightmaps2d[MAXLIGHTMAPS] = {LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D}; -const int lightmapsVertex[MAXLIGHTMAPS] = -{ - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX -}; +const int lightmapsVertex[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX}; -const int lightmapsFullBright[MAXLIGHTMAPS] = -{ - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE -}; +const int lightmapsFullBright[MAXLIGHTMAPS] = {LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE}; -const byte stylesDefault[MAXLIGHTMAPS] = -{ - LS_NORMAL, - LS_LSNONE, - LS_LSNONE, - LS_LSNONE -}; +const byte stylesDefault[MAXLIGHTMAPS] = {LS_NORMAL, LS_LSNONE, LS_LSNONE, LS_LSNONE}; -qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndexes, const byte *styles ); +qhandle_t RE_RegisterShaderLightMap(const char *name, const int *lightmapIndexes, const byte *styles); -void KillTheShaderHashTable(void) -{ - memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); -} +void KillTheShaderHashTable(void) { memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); } -qboolean ShaderHashTableExists(void) -{ - if (shaderTextHashTable[0]) - { +qboolean ShaderHashTableExists(void) { + if (shaderTextHashTable[0]) { return qtrue; } return qfalse; } -static void ClearGlobalShader(void) -{ - int i; +static void ClearGlobalShader(void) { + int i; - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; - //stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; + // stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; // default normal/specular VectorSet4(stages[i].normalScale, 0.0f, 0.0f, 0.0f, 0.0f); - stages[i].specularScale[0] = - stages[i].specularScale[1] = - stages[i].specularScale[2] = r_baseSpecular->value; + stages[i].specularScale[0] = stages[i].specularScale[1] = stages[i].specularScale[2] = r_baseSpecular->value; stages[i].specularScale[3] = 0.99f; } shader.contentFlags = CONTENTS_SOLID | CONTENTS_OPAQUE; } -static uint32_t generateHashValueForText( const char *string, size_t length ) -{ +static uint32_t generateHashValueForText(const char *string, size_t length) { int i = 0; uint32_t hash = 0; - while ( length-- ) - { + while (length--) { hash += string[i] * (i + 119); i++; } @@ -137,50 +97,53 @@ static uint32_t generateHashValueForText( const char *string, size_t length ) return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); - hash &= (size-1); + hash &= (size - 1); return hash; } void R_RemapShader(const char *shaderName, const char *newShaderName, const char *timeOffset) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh, *sh2; - qhandle_t h; + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh, *sh2; + qhandle_t h; - sh = R_FindShaderByName( shaderName ); + sh = R_FindShaderByName(shaderName); if (sh == NULL || sh == tr.defaultShader) { - h = RE_RegisterShaderLightMap (shaderName, lightmapsNone, stylesDefault); + h = RE_RegisterShaderLightMap(shaderName, lightmapsNone, stylesDefault); sh = R_GetShaderByHandle(h); } if (sh == NULL || sh == tr.defaultShader) { - ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: shader %s not found\n", shaderName ); + ri.Printf(PRINT_WARNING, "WARNING: R_RemapShader: shader %s not found\n", shaderName); return; } - sh2 = R_FindShaderByName( newShaderName ); + sh2 = R_FindShaderByName(newShaderName); if (sh2 == NULL || sh2 == tr.defaultShader) { - h = RE_RegisterShaderLightMap (newShaderName, lightmapsNone, stylesDefault); + h = RE_RegisterShaderLightMap(newShaderName, lightmapsNone, stylesDefault); sh2 = R_GetShaderByHandle(h); } if (sh2 == NULL || sh2 == tr.defaultShader) { - ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: new shader %s not found\n", newShaderName ); + ri.Printf(PRINT_WARNING, "WARNING: R_RemapShader: new shader %s not found\n", newShaderName); return; } @@ -207,115 +170,90 @@ void R_RemapShader(const char *shaderName, const char *newShaderName, const char ParseVector =============== */ -static qboolean ParseVector( const char **text, int count, float *v ) { - char *token; - int i; +static qboolean ParseVector(const char **text, int count, float *v) { + char *token; + int i; // FIXME: spaces are currently required after parens, should change parseext... - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "(" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "(")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } - for ( i = 0 ; i < count ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { - ri.Printf( PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name ); + for (i = 0; i < count; i++) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name); return qfalse; } - v[i] = atof( token ); + v[i] = atof(token); } - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, ")" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, ")")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } return qtrue; } - /* =============== ParseAlphaTestFunc =============== */ -static void ParseAlphaTestFunc( shaderStage_t *stage, const char *funcname ) -{ +static void ParseAlphaTestFunc(shaderStage_t *stage, const char *funcname) { stage->alphaTestType = ALPHA_TEST_NONE; - if ( !Q_stricmp( funcname, "GT0" ) ) + if (!Q_stricmp(funcname, "GT0")) stage->alphaTestType = ALPHA_TEST_GT0; - else if ( !Q_stricmp( funcname, "LT128" ) ) + else if (!Q_stricmp(funcname, "LT128")) stage->alphaTestType = ALPHA_TEST_LT128; - else if ( !Q_stricmp( funcname, "GE128" ) ) + else if (!Q_stricmp(funcname, "GE128")) stage->alphaTestType = ALPHA_TEST_GE128; - else if ( !Q_stricmp( funcname, "GE192" ) ) + else if (!Q_stricmp(funcname, "GE192")) stage->alphaTestType = ALPHA_TEST_GE192; else - ri.Printf( PRINT_WARNING, - "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", - funcname, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name); } - /* =============== NameToSrcBlendMode =============== */ -static int NameToSrcBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToSrcBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_SRCBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_SRCBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_COLOR")) { return GLS_SRCBLEND_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_COLOR")) { return GLS_SRCBLEND_ONE_MINUS_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_SRCBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { - if ( r_ignoreDstAlpha->integer ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { + if (r_ignoreDstAlpha->integer) { return GLS_SRCBLEND_ONE; } return GLS_SRCBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { - if ( r_ignoreDstAlpha->integer ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { + if (r_ignoreDstAlpha->integer) { return GLS_SRCBLEND_ZERO; } return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA_SATURATE")) { return GLS_SRCBLEND_ALPHA_SATURATE; } - ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_SRCBLEND_ONE; } @@ -324,52 +262,34 @@ static int NameToSrcBlendMode( const char *name ) NameToDstBlendMode =============== */ -static int NameToDstBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToDstBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_DSTBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_DSTBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_DSTBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { - if ( r_ignoreDstAlpha->integer ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { + if (r_ignoreDstAlpha->integer) { return GLS_DSTBLEND_ONE; } return GLS_DSTBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { - if ( r_ignoreDstAlpha->integer ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { + if (r_ignoreDstAlpha->integer) { return GLS_DSTBLEND_ZERO; } return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_COLOR")) { return GLS_DSTBLEND_SRC_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_COLOR")) { return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; } - ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_DSTBLEND_ONE; } @@ -378,456 +298,362 @@ static int NameToDstBlendMode( const char *name ) NameToGenFunc =============== */ -static genFunc_t NameToGenFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "sin" ) ) - { +static genFunc_t NameToGenFunc(const char *funcname) { + if (!Q_stricmp(funcname, "sin")) { return GF_SIN; - } - else if ( !Q_stricmp( funcname, "square" ) ) - { + } else if (!Q_stricmp(funcname, "square")) { return GF_SQUARE; - } - else if ( !Q_stricmp( funcname, "triangle" ) ) - { + } else if (!Q_stricmp(funcname, "triangle")) { return GF_TRIANGLE; - } - else if ( !Q_stricmp( funcname, "sawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "sawtooth")) { return GF_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "inversesawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "inversesawtooth")) { return GF_INVERSE_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "noise" ) ) - { + } else if (!Q_stricmp(funcname, "noise")) { return GF_NOISE; - } - else if ( !Q_stricmp( funcname, "random" ) ) - { + } else if (!Q_stricmp(funcname, "random")) { return GF_RAND; } - ri.Printf( PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name); return GF_SIN; } - /* =================== ParseWaveForm =================== */ -static void ParseWaveForm( const char **text, waveForm_t *wave ) -{ +static void ParseWaveForm(const char **text, waveForm_t *wave) { char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->func = NameToGenFunc( token ); + wave->func = NameToGenFunc(token); // BASE, AMP, PHASE, FREQ - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->base = atof( token ); + wave->base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->amplitude = atof( token ); + wave->amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->phase = atof( token ); + wave->phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->frequency = atof( token ); + wave->frequency = atof(token); } - /* =================== ParseTexMod =================== */ -static void ParseTexMod( const char *_text, shaderStage_t *stage ) -{ +static void ParseTexMod(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; texModInfo_t *tmi; - if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) { - ri.Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'", shader.name ); + if (stage->bundle[0].numTexMods == TR_MAX_TEXMODS) { + ri.Error(ERR_DROP, "ERROR: too many tcMod stages in shader '%s'", shader.name); return; } tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods]; stage->bundle[0].numTexMods++; - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); // // turb // - if ( !Q_stricmp( token, "turb" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "turb")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.base = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.amplitude = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.phase = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_TURBULENT; } // // scale // - else if ( !Q_stricmp( token, "scale" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->scale[0] = atof( token ); + tmi->scale[0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->scale[1] = atof( token ); + tmi->scale[1] = atof(token); tmi->type = TMOD_SCALE; } // // scroll // - else if ( !Q_stricmp( token, "scroll" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scroll")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->scroll[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + tmi->scroll[0] = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->scroll[1] = atof( token ); + tmi->scroll[1] = atof(token); tmi->type = TMOD_SCROLL; } // // stretch // - else if ( !Q_stricmp( token, "stretch" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "stretch")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.func = NameToGenFunc( token ); + tmi->wave.func = NameToGenFunc(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); + tmi->wave.base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); + tmi->wave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); + tmi->wave.phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); - + tmi->wave.frequency = atof(token); + tmi->type = TMOD_STRETCH; } // // transform // - else if ( !Q_stricmp( token, "transform" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "transform")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][0] = atof( token ); + tmi->matrix[0][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][1] = atof( token ); + tmi->matrix[0][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][0] = atof( token ); + tmi->matrix[1][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][1] = atof( token ); + tmi->matrix[1][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); + tmi->translate[0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); + tmi->translate[1] = atof(token); tmi->type = TMOD_TRANSFORM; } // // rotate // - else if ( !Q_stricmp( token, "rotate" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rotate")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name); return; } - tmi->rotateSpeed = atof( token ); + tmi->rotateSpeed = atof(token); tmi->type = TMOD_ROTATE; } // // entityTranslate // - else if ( !Q_stricmp( token, "entityTranslate" ) ) - { + else if (!Q_stricmp(token, "entityTranslate")) { tmi->type = TMOD_ENTITY_TRANSLATE; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name); } } -static animMapType_t AnimMapType( const char *token ) -{ - if ( !Q_stricmp( token, "clampanimMap" ) ) { return ANIMMAP_CLAMP; } - else if ( !Q_stricmp( token, "oneshotanimMap" ) ) { return ANIMMAP_ONESHOT; } - else { return ANIMMAP_NORMAL; } +static animMapType_t AnimMapType(const char *token) { + if (!Q_stricmp(token, "clampanimMap")) { + return ANIMMAP_CLAMP; + } else if (!Q_stricmp(token, "oneshotanimMap")) { + return ANIMMAP_ONESHOT; + } else { + return ANIMMAP_NORMAL; + } } -static const char *animMapNames[] = { - "animMap", - "clapanimMap", - "oneshotanimMap" -}; +static const char *animMapNames[] = {"animMap", "clapanimMap", "oneshotanimMap"}; -static bool ParseSurfaceSprites( const char *buffer, shaderStage_t *stage ) -{ +static bool ParseSurfaceSprites(const char *buffer, shaderStage_t *stage) { const char *token; const char **text = &buffer; surfaceSpriteType_t sstype = SURFSPRITE_NONE; // spritetype - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", - shader.name); + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return false; } - if ( !Q_stricmp(token, "vertical") ) - { + if (!Q_stricmp(token, "vertical")) { sstype = SURFSPRITE_VERTICAL; - } - else if ( !Q_stricmp(token, "oriented") ) - { + } else if (!Q_stricmp(token, "oriented")) { sstype = SURFSPRITE_ORIENTED; - } - else if ( !Q_stricmp(token, "effect") ) - { + } else if (!Q_stricmp(token, "effect")) { sstype = SURFSPRITE_EFFECT; - } - else if ( !Q_stricmp(token, "flattened") ) - { + } else if (!Q_stricmp(token, "flattened")) { sstype = SURFSPRITE_FLATTENED; - } - else - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", - shader.name); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", shader.name); return false; } // width - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", - shader.name); + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return false; } float width = atof(token); - if ( width <= 0.0f ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", - shader.name); + if (width <= 0.0f) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", shader.name); return false; } // height - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", - shader.name); + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return false; } float height = atof(token); - if ( height <= 0.0f ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", - shader.name); + if (height <= 0.0f) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", shader.name); return false; } // density - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", - shader.name); + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return false; } float density = atof(token); - if ( density <= 0.0f ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", - shader.name); + if (density <= 0.0f) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", shader.name); return false; } // fadedist - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", - shader.name); + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return false; } float fadedist = atof(token); - if ( fadedist < 32.0f ) - { - ri.Printf(PRINT_ALL, - S_COLOR_YELLOW "WARNING: invalid fadedist (%.2f < 32) in shader '%s'\n", - fadedist, shader.name); + if (fadedist < 32.0f) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid fadedist (%.2f < 32) in shader '%s'\n", fadedist, shader.name); return false; } - if ( !stage->ss ) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); - + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // These are all set by the command lines. @@ -850,7 +676,7 @@ static bool ParseSurfaceSprites( const char *buffer, shaderStage_t *stage ) stage->ss->vertSkew = 0.0f; // These are effect parameters that need defaults nonetheless. - stage->ss->fxDuration = 1000; // 1 second + stage->ss->fxDuration = 1000; // 1 second stage->ss->fxGrow[0] = 0.0f; stage->ss->fxGrow[1] = 0.0f; stage->ss->fxAlphaStart = 1.0f; @@ -874,19 +700,13 @@ static bool ParseSurfaceSprites( const char *buffer, shaderStage_t *stage ) // ssFXGrow // ssFXAlphaRange // ssFXWeather -static bool ParseSurfaceSpritesOptional( - const char *param, - const char *buffer, - shaderStage_t *stage -) -{ +static bool ParseSurfaceSpritesOptional(const char *param, const char *buffer, shaderStage_t *stage) { const char *token; const char **text = &buffer; float value; - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // TODO: Tidy this up some how. There's a lot of repeated code @@ -894,137 +714,118 @@ static bool ParseSurfaceSpritesOptional( // // fademax // - if (!Q_stricmp(param, "ssFademax")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFademax")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value <= stage->ss->fadeDist) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, shader.name ); + if (value <= stage->ss->fadeDist) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, + shader.name); return false; } - stage->ss->fadeMax=value; + stage->ss->fadeMax = value; return true; } // // fadescale // - if (!Q_stricmp(param, "ssFadescale")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFadescale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name); return false; } value = atof(token); - stage->ss->fadeScale=value; + stage->ss->fadeScale = value; return true; } // // variance // - if (!Q_stricmp(param, "ssVariance")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVariance")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name); return false; } - stage->ss->variance[0]=value; + stage->ss->variance[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name); return false; } - stage->ss->variance[1]=value; + stage->ss->variance[1] = value; return true; } // // hangdown // - if (!Q_stricmp(param, "ssHangdown")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssHangdown")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name); return false; } - stage->ss->facing=SURFSPRITE_FACING_DOWN; + stage->ss->facing = SURFSPRITE_FACING_DOWN; return true; } // // anyangle // - if (!Q_stricmp(param, "ssAnyangle")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssAnyangle")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name); return false; } - stage->ss->facing=SURFSPRITE_FACING_ANY; + stage->ss->facing = SURFSPRITE_FACING_ANY; return true; } // // faceup // - if (!Q_stricmp(param, "ssFaceup")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFaceup")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name); return false; } - stage->ss->facing=SURFSPRITE_FACING_UP; + stage->ss->facing = SURFSPRITE_FACING_UP; return true; } // // wind // - if (!Q_stricmp(param, "ssWind")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWind")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name); return false; } - stage->ss->wind=value; - if (stage->ss->windIdle <= 0) - { // Also override the windidle, it usually is the same as wind + stage->ss->wind = value; + if (stage->ss->windIdle <= 0) { // Also override the windidle, it usually is the same as wind stage->ss->windIdle = value; } return true; @@ -1033,144 +834,123 @@ static bool ParseSurfaceSpritesOptional( // // windidle // - if (!Q_stricmp(param, "ssWindidle")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWindidle")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name); return false; } - stage->ss->windIdle=value; + stage->ss->windIdle = value; return true; } // // vertskew // - if (!Q_stricmp(param, "ssVertskew")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVertskew")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name); return false; } - stage->ss->vertSkew=value; + stage->ss->vertSkew = value; return true; } // // fxduration // - if (!Q_stricmp(param, "ssFXDuration")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXDuration")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value <= 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name ); + if (value <= 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name); return false; } - stage->ss->fxDuration=value; + stage->ss->fxDuration = value; return true; } // // fxgrow // - if (!Q_stricmp(param, "ssFXGrow")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXGrow")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name); return false; } - stage->ss->fxGrow[0]=value; + stage->ss->fxGrow[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name); return false; } - stage->ss->fxGrow[1]=value; + stage->ss->fxGrow[1] = value; return true; } // // fxalpharange // - if (!Q_stricmp(param, "ssFXAlphaRange")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXAlphaRange")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name); return false; } - stage->ss->fxAlphaStart=value; + stage->ss->fxAlphaStart = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name); return false; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name); return false; } - stage->ss->fxAlphaEnd=value; + stage->ss->fxAlphaEnd = value; return true; } // // fxweather // - if (!Q_stricmp(param, "ssFXWeather")) - { - if (stage->ss->type != SURFSPRITE_EFFECT) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXWeather")) { + if (stage->ss->type != SURFSPRITE_EFFECT) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name); return false; } stage->ss->type = SURFSPRITE_WEATHERFX; @@ -1180,7 +960,7 @@ static bool ParseSurfaceSpritesOptional( // // invalid ss command. // - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name); return false; } @@ -1189,8 +969,7 @@ static bool ParseSurfaceSpritesOptional( ParseStage =================== */ -static qboolean ParseStage( shaderStage_t *stage, const char **text ) -{ +static qboolean ParseStage(shaderStage_t *stage, const char **text) { char *token; unsigned depthMaskBits = GLS_DEPTHMASK_TRUE; unsigned blendSrcBits = 0; @@ -1203,44 +982,36 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) stage->active = qtrue; stage->specularType = SPEC_NONE; - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: no matching '}' found\n" ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: no matching '}' found\n"); return qfalse; } - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // // map or clampmap // - else if ( !Q_stricmp( token, "map" ) || (!Q_stricmp(token, "clampmap"))) - { + else if (!Q_stricmp(token, "map") || (!Q_stricmp(token, "clampmap"))) { int flags = !Q_stricmp(token, "clampmap") ? IMGFLAG_CLAMPTOEDGE : IMGFLAG_NONE; - - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); + + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "$whiteimage" ) ) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[0].image[0] = tr.whiteImage; continue; - } - else if ( !Q_stricmp( token, "$lightmap" ) ) - { + } else if (!Q_stricmp(token, "$lightmap")) { stage->bundle[0].isLightmap = qtrue; - if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) { + if (shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps) { #ifndef FINAL_BUILD - ri.Printf (PRINT_ALL, S_COLOR_RED "Lightmap requested but none avilable for shader '%s'\n", shader.name); + ri.Printf(PRINT_ALL, S_COLOR_RED "Lightmap requested but none avilable for shader '%s'\n", shader.name); #endif stage->bundle[0].image[0] = tr.whiteImage; } else { @@ -1249,25 +1020,20 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) stage->bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; } continue; - } - else if ( !Q_stricmp( token, "$deluxemap" ) ) - { - if (!tr.worldDeluxeMapping) - { - ri.Printf( PRINT_WARNING, "WARNING: shader '%s' wants a deluxe map in a map compiled without them\n", shader.name ); + } else if (!Q_stricmp(token, "$deluxemap")) { + if (!tr.worldDeluxeMapping) { + ri.Printf(PRINT_WARNING, "WARNING: shader '%s' wants a deluxe map in a map compiled without them\n", shader.name); return qfalse; } stage->bundle[0].isLightmap = qtrue; - if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) { + if (shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps) { stage->bundle[0].image[0] = tr.whiteImage; } else { stage->bundle[0].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; } continue; - } - else - { + } else { imgType_t type = IMGTYPE_COLORALPHA; if (!shader.noMipMaps) @@ -1288,9 +1054,8 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) Q_strncpyz(bufferBaseColorTextureName, token, sizeof(bufferBaseColorTextureName)); stage->bundle[0].image[0] = R_FindImageFile(bufferBaseColorTextureName, type, flags); - if ( !stage->bundle[0].image[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + if (!stage->bundle[0].image[0]) { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1298,13 +1063,11 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // normalMap or normalHeightMap // - else if (!Q_stricmp(token, "normalMap") || !Q_stricmp(token, "normalHeightMap")) - { + else if (!Q_stricmp(token, "normalMap") || !Q_stricmp(token, "normalHeightMap")) { imgType_t type = !Q_stricmp(token, "normalHeightMap") ? IMGTYPE_NORMALHEIGHT : IMGTYPE_NORMAL; token = COM_ParseExt(text, qfalse); - if (!token[0]) - { + if (!token[0]) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'normalMap' keyword in shader '%s'\n", shader.name); return qfalse; } @@ -1323,8 +1086,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) flags |= IMGFLAG_NOLIGHTSCALE; stage->bundle[TB_NORMALMAP].image[0] = R_FindImageFile(token, type, flags); - if (!stage->bundle[TB_NORMALMAP].image[0]) - { + if (!stage->bundle[TB_NORMALMAP].image[0]) { ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find normalMap '%s' in shader '%s'\n", token, shader.name); return qfalse; } @@ -1334,21 +1096,18 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // specMap || specularMap // - else if (!Q_stricmp(token, "specMap") || !Q_stricmp(token, "specularMap")) - { + else if (!Q_stricmp(token, "specMap") || !Q_stricmp(token, "specularMap")) { imgType_t type = IMGTYPE_COLORALPHA; token = COM_ParseExt(text, qfalse); - if (!token[0]) - { + if (!token[0]) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'specularMap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->specularType = SPEC_SPECGLOSS; VectorSet4(stage->specularScale, 1.0f, 1.0f, 1.0f, 0.0f); - if (!Q_stricmp(token, "$whiteimage")) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; continue; } @@ -1370,27 +1129,23 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) else stage->bundle[TB_SPECULARMAP].image[0] = R_BuildSDRSpecGlossImage(stage, token, flags); - if (!stage->bundle[TB_SPECULARMAP].image[0]) - { + if (!stage->bundle[TB_SPECULARMAP].image[0]) { ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find specMap '%s' in shader '%s'\n", token, shader.name); return qfalse; } - + } // // rmoMap || rmosMap // - else if (!Q_stricmp(token, "rmoMap") || !Q_stricmp(token, "rmosMap")) - { + else if (!Q_stricmp(token, "rmoMap") || !Q_stricmp(token, "rmosMap")) { token = COM_ParseExt(text, qfalse); - if (!token[0]) - { + if (!token[0]) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'rmoMap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->specularType = !Q_stricmp(token, "rmosMap") ? SPEC_RMOS : SPEC_RMO; - if (!Q_stricmp(token, "$whiteimage")) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; continue; } @@ -1399,17 +1154,14 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // moxrMap || mosrMap // - else if (!Q_stricmp(token, "moxrMap") || !Q_stricmp(token, "mosrMap")) - { + else if (!Q_stricmp(token, "moxrMap") || !Q_stricmp(token, "mosrMap")) { token = COM_ParseExt(text, qfalse); - if (!token[0]) - { + if (!token[0]) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'moxrMap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->specularType = !Q_stricmp(token, "mosrMap") ? SPEC_MOSR : SPEC_MOXR; - if (!Q_stricmp(token, "$whiteimage")) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; continue; } @@ -1418,17 +1170,14 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // ormMap || ormsMap // - else if (!Q_stricmp(token, "ormMap") || !Q_stricmp(token, "ormsMap")) - { + else if (!Q_stricmp(token, "ormMap") || !Q_stricmp(token, "ormsMap")) { token = COM_ParseExt(text, qfalse); - if (!token[0]) - { + if (!token[0]) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'ormMap' keyword in shader '%s'\n", shader.name); return qfalse; } stage->specularType = !Q_stricmp(token, "ormsMap") ? SPEC_ORMS : SPEC_ORM; - if (!Q_stricmp(token, "$whiteimage")) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; continue; } @@ -1437,28 +1186,26 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // animMap .... // - else if ( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampanimMap" ) || !Q_stricmp( token, "oneshotanimMap" ) ) - { - animMapType_t type = AnimMapType( token ); - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for '%s' keyword in shader '%s'\n", animMapNames[type], shader.name ); + else if (!Q_stricmp(token, "animMap") || !Q_stricmp(token, "clampanimMap") || !Q_stricmp(token, "oneshotanimMap")) { + animMapType_t type = AnimMapType(token); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for '%s' keyword in shader '%s'\n", animMapNames[type], shader.name); return qfalse; } - stage->bundle[0].imageAnimationSpeed = atof( token ); + stage->bundle[0].imageAnimationSpeed = atof(token); stage->bundle[0].oneShotAnimMap = (qboolean)(type == ANIMMAP_ONESHOT); // parse up to MAX_IMAGE_ANIMATIONS animations - while ( 1 ) { - int num; + while (1) { + int num; - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { break; } num = stage->bundle[0].numImageAnimations; - if ( num < MAX_IMAGE_ANIMATIONS ) { + if (num < MAX_IMAGE_ANIMATIONS) { imgType_t imgtype = IMGTYPE_COLORALPHA; int flags = type == ANIMMAP_CLAMP ? IMGFLAG_CLAMPTOEDGE : IMGFLAG_NONE; @@ -1477,25 +1224,21 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) if (r_genNormalMaps->integer) flags |= IMGFLAG_GENNORMALMAP; - stage->bundle[0].image[num] = R_FindImageFile( token, imgtype, flags ); - if ( !stage->bundle[0].image[num] ) - { - ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + stage->bundle[0].image[num] = R_FindImageFile(token, imgtype, flags); + if (!stage->bundle[0].image[num]) { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } stage->bundle[0].numImageAnimations++; } } - } - else if ( !Q_stricmp( token, "videoMap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "videoMap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name); return qfalse; } - stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic( token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader)); + stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic(token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader)); if (stage->bundle[0].videoMapHandle != -1) { stage->bundle[0].isVideoMap = qtrue; stage->bundle[0].image[0] = tr.scratchImage[stage->bundle[0].videoMapHandle]; @@ -1504,153 +1247,127 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // alphafunc // - else if ( !Q_stricmp( token, "alphaFunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaFunc")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name); return qfalse; } - ParseAlphaTestFunc( stage, token ); + ParseAlphaTestFunc(stage, token); } // // depthFunc // - else if ( !Q_stricmp( token, "depthfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "depthfunc")) { + token = COM_ParseExt(text, qfalse); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name ); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "lequal" ) ) - { + if (!Q_stricmp(token, "lequal")) { depthFuncBits = 0; - } - else if ( !Q_stricmp( token, "equal" ) ) - { + } else if (!Q_stricmp(token, "equal")) { depthFuncBits = GLS_DEPTHFUNC_EQUAL; - } - else if ( !Q_stricmp( token, "disable" ) ) - { + } else if (!Q_stricmp(token, "disable")) { depthFuncBits = GLS_DEPTHTEST_DISABLE; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name); continue; } } // // detail // - else if ( !Q_stricmp( token, "detail" ) ) - { + else if (!Q_stricmp(token, "detail")) { stage->isDetail = qtrue; } // // blendfunc // or blendfunc // - else if ( !Q_stricmp( token, "blendfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "blendfunc")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } // check for "simple" blends first - if ( !Q_stricmp( token, "add" ) ) { + if (!Q_stricmp(token, "add")) { blendSrcBits = GLS_SRCBLEND_ONE; blendDstBits = GLS_DSTBLEND_ONE; - } else if ( !Q_stricmp( token, "filter" ) ) { + } else if (!Q_stricmp(token, "filter")) { blendSrcBits = GLS_SRCBLEND_DST_COLOR; blendDstBits = GLS_DSTBLEND_ZERO; - } else if ( !Q_stricmp( token, "blend" ) ) { + } else if (!Q_stricmp(token, "blend")) { blendSrcBits = GLS_SRCBLEND_SRC_ALPHA; blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } else { // complex double blends - blendSrcBits = NameToSrcBlendMode( token ); + blendSrcBits = NameToSrcBlendMode(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } - blendDstBits = NameToDstBlendMode( token ); + blendDstBits = NameToDstBlendMode(token); } // clear depth mask for blended surfaces - if ( !depthMaskExplicit ) - { + if (!depthMaskExplicit) { depthMaskBits = 0; } } // // specularReflectance // - else if (!Q_stricmp(token, "specularreflectance")) - { + else if (!Q_stricmp(token, "specularreflectance")) { token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specular reflectance in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for specular reflectance in shader '%s'\n", shader.name); continue; } - stage->specularScale[0] = - stage->specularScale[1] = - stage->specularScale[2] = Com_Clamp( 0.0f, 1.0f, atof( token ) ); + stage->specularScale[0] = stage->specularScale[1] = stage->specularScale[2] = Com_Clamp(0.0f, 1.0f, atof(token)); } // // specularExponent // - else if (!Q_stricmp(token, "specularexponent")) - { + else if (!Q_stricmp(token, "specularexponent")) { float exponent; token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specular exponent in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for specular exponent in shader '%s'\n", shader.name); continue; } - exponent = atof( token ); + exponent = atof(token); - // Change shininess to gloss - // FIXME: assumes max exponent of 8192 and min of 1, must change here if altered in lightall_fp.glsl - exponent = CLAMP(exponent, 1.0, 8192.0); + // Change shininess to gloss + // FIXME: assumes max exponent of 8192 and min of 1, must change here if altered in lightall_fp.glsl + exponent = CLAMP(exponent, 1.0, 8192.0); stage->specularScale[3] = 1.0f - (log(exponent) / log(8192.0)); } // - // gloss + // gloss // - else if ( !Q_stricmp( token, "gloss" ) ) - { + else if (!Q_stricmp(token, "gloss")) { token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for gloss in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for gloss in shader '%s'\n", shader.name); continue; } - stage->specularScale[3] = 1.0 - atof( token ); + stage->specularScale[3] = 1.0 - atof(token); } // // roughness // - else if (!Q_stricmp(token, "roughness")) - { + else if (!Q_stricmp(token, "roughness")) { token = COM_ParseExt(text, qfalse); - if (token[0] == 0) - { + if (token[0] == 0) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for roughness in shader '%s'\n", shader.name); continue; } @@ -1660,25 +1377,21 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // parallaxDepth // - else if (!Q_stricmp(token, "parallaxdepth")) - { + else if (!Q_stricmp(token, "parallaxdepth")) { token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for parallaxDepth in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for parallaxDepth in shader '%s'\n", shader.name); continue; } - stage->normalScale[3] = atof( token ); + stage->normalScale[3] = atof(token); } // // parallaxBias // - else if (!Q_stricmp(token, "parallaxbias")) - { + else if (!Q_stricmp(token, "parallaxbias")) { token = COM_ParseExt(text, qfalse); - if (token[0] == 0) - { + if (token[0] == 0) { ri.Printf(PRINT_WARNING, "WARNING: missing parameter for parallaxBias in shader '%s'\n", shader.name); continue; } @@ -1690,35 +1403,31 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // or normalScale // or normalScale // - else if (!Q_stricmp(token, "normalscale")) - { + else if (!Q_stricmp(token, "normalscale")) { token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for normalScale in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for normalScale in shader '%s'\n", shader.name); continue; } - stage->normalScale[0] = atof( token ); + stage->normalScale[0] = atof(token); token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { + if (token[0] == 0) { // one value, applies to X/Y stage->normalScale[1] = stage->normalScale[0]; continue; } - stage->normalScale[1] = atof( token ); + stage->normalScale[1] = atof(token); token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { + if (token[0] == 0) { // two values, no height continue; } - stage->normalScale[3] = atof( token ); + stage->normalScale[3] = atof(token); } // // specularScale @@ -1726,315 +1435,231 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // or specularScale // or specularScale when metal roughness workflow is used // - else if (!Q_stricmp(token, "specularscale")) - { + else if (!Q_stricmp(token, "specularscale")) { token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name); continue; } - stage->specularScale[0] = atof( token ); + stage->specularScale[0] = atof(token); token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name); continue; } - stage->specularScale[1] = atof( token ); + stage->specularScale[1] = atof(token); token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { + if (token[0] == 0) { // two values, rgb then gloss stage->specularScale[3] = 1.0 - stage->specularScale[1]; - stage->specularScale[1] = - stage->specularScale[2] = stage->specularScale[0]; + stage->specularScale[1] = stage->specularScale[2] = stage->specularScale[0]; continue; } - stage->specularScale[2] = atof( token ); + stage->specularScale[2] = atof(token); token = COM_ParseExt(text, qfalse); - if ( token[0] == 0 ) - { + if (token[0] == 0) { // three values, rgb continue; } - stage->specularScale[3] = 1.0 - atof( token ); + stage->specularScale[3] = 1.0 - atof(token); } // // rgbGen // - else if ( !Q_stricmp( token, "rgbGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rgbGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->rgbWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->rgbWave); stage->rgbGen = CGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - vec3_t color; + } else if (!Q_stricmp(token, "const")) { + vec3_t color; - ParseVector( text, 3, color ); + ParseVector(text, 3, color); stage->constantColor[0] = color[0]; stage->constantColor[1] = color[1]; stage->constantColor[2] = color[2]; - if (tr.hdrLighting == qfalse) - { + if (tr.hdrLighting == qfalse) { stage->constantColor[0] = MIN(color[0], 1.0f); stage->constantColor[1] = MIN(color[1], 1.0f); stage->constantColor[2] = MIN(color[2], 1.0f); } stage->rgbGen = CGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->rgbGen = CGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "identityLighting" ) ) - { + } else if (!Q_stricmp(token, "identityLighting")) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->rgbGen = CGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->rgbGen = CGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->rgbGen = CGEN_VERTEX; - if ( stage->alphaGen == 0 ) { + if (stage->alphaGen == 0) { stage->alphaGen = AGEN_VERTEX; } - } - else if ( !Q_stricmp( token, "exactVertex" ) ) - { + } else if (!Q_stricmp(token, "exactVertex")) { stage->rgbGen = CGEN_EXACT_VERTEX; - } - else if ( !Q_stricmp( token, "vertexLit" ) ) - { + } else if (!Q_stricmp(token, "vertexLit")) { stage->rgbGen = CGEN_VERTEX_LIT; - if ( stage->alphaGen == 0 ) { + if (stage->alphaGen == 0) { stage->alphaGen = AGEN_VERTEX; } - } - else if ( !Q_stricmp( token, "exactVertexLit" ) ) - { + } else if (!Q_stricmp(token, "exactVertexLit")) { stage->rgbGen = CGEN_EXACT_VERTEX_LIT; - } - else if ( !Q_stricmp( token, "lightingDiffuse" ) ) - { + } else if (!Q_stricmp(token, "lightingDiffuse")) { stage->rgbGen = CGEN_LIGHTING_DIFFUSE; - } - else if ( !Q_stricmp( token, "lightingDiffuseEntity" ) ) - { - if (shader.lightmapIndex[0] != LIGHTMAP_NONE) - { - Com_Printf( S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "lightingDiffuseEntity")) { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) { + Com_Printf(S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->rgbGen = CGEN_ONE_MINUS_VERTEX; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // - // alphaGen + // alphaGen // - else if ( !Q_stricmp( token, "alphaGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->alphaWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->alphaWave); stage->alphaGen = AGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - token = COM_ParseExt( text, qfalse ); - stage->constantColor[3] = atof( token ); + } else if (!Q_stricmp(token, "const")) { + token = COM_ParseExt(text, qfalse); + stage->constantColor[3] = atof(token); stage->alphaGen = AGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->alphaGen = AGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->alphaGen = AGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->alphaGen = AGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->alphaGen = AGEN_VERTEX; - } - else if ( !Q_stricmp( token, "lightingSpecular" ) ) - { + } else if (!Q_stricmp(token, "lightingSpecular")) { stage->alphaGen = AGEN_LIGHTING_SPECULAR; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->alphaGen = AGEN_ONE_MINUS_VERTEX; - } - else if ( !Q_stricmp( token, "dot" ) ) - { - //stage->alphaGen = AGEN_DOT; - } - else if ( !Q_stricmp( token, "oneMinusDot" ) ) - { - //stage->alphaGen = AGEN_ONE_MINUS_DOT; - } - else if ( !Q_stricmp( token, "portal" ) ) - { + } else if (!Q_stricmp(token, "dot")) { + // stage->alphaGen = AGEN_DOT; + } else if (!Q_stricmp(token, "oneMinusDot")) { + // stage->alphaGen = AGEN_ONE_MINUS_DOT; + } else if (!Q_stricmp(token, "portal")) { stage->alphaGen = AGEN_PORTAL; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { shader.portalRange = 256; - ri.Printf( PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name ); - } - else - { - shader.portalRange = atof( token ); + ri.Printf(PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name); + } else { + shader.portalRange = atof(token); } - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // tcGen // - else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "texgen") || !Q_stricmp(token, "tcGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "environment" ) ) - { + if (!Q_stricmp(token, "environment")) { stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED; - } - else if ( !Q_stricmp( token, "lightmap" ) ) - { + } else if (!Q_stricmp(token, "lightmap")) { stage->bundle[0].tcGen = TCGEN_LIGHTMAP; - } - else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) ) - { + } else if (!Q_stricmp(token, "texture") || !Q_stricmp(token, "base")) { stage->bundle[0].tcGen = TCGEN_TEXTURE; - } - else if ( !Q_stricmp( token, "vector" ) ) - { - ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] ); + } else if (!Q_stricmp(token, "vector")) { + ParseVector(text, 3, stage->bundle[0].tcGenVectors[0]); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[1]); stage->bundle[0].tcGen = TCGEN_VECTOR; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name); } } // // tcMod <...> // - else if ( !Q_stricmp( token, "tcMod" ) ) - { + else if (!Q_stricmp(token, "tcMod")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseTexMod( buffer, stage ); + ParseTexMod(buffer, stage); continue; } // // depthmask // - else if ( !Q_stricmp( token, "depthwrite" ) ) - { + else if (!Q_stricmp(token, "depthwrite")) { depthMaskBits = GLS_DEPTHMASK_TRUE; depthMaskExplicit = qtrue; continue; } // If this stage has glow... GLOWXXX - else if ( Q_stricmp( token, "glow" ) == 0 ) - { + else if (Q_stricmp(token, "glow") == 0) { stage->glow = qtrue; continue; } // // If this stage is cloth - else if (Q_stricmp(token, "cloth") == 0) - { + else if (Q_stricmp(token, "cloth") == 0) { stage->cloth = qtrue; continue; } // surfaceSprites ... // - else if ( !Q_stricmp( token, "surfacesprites" ) ) - { + else if (!Q_stricmp(token, "surfacesprites")) { char buffer[1024] = {}; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } bool hasSS = (stage->ss != nullptr); - if ( ParseSurfaceSprites( buffer, stage ) && !hasSS ) - { + if (ParseSurfaceSprites(buffer, stage) && !hasSS) { ++shader.numSurfaceSpriteStages; } @@ -2053,32 +1678,27 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // ssGrow // ssWeather // - else if (!Q_stricmpn(token, "ss", 2)) - { + else if (!Q_stricmpn(token, "ss", 2)) { char buffer[1024] = {}; char param[128] = {}; - Q_strncpyz( param, token, sizeof( param ) ); + Q_strncpyz(param, token, sizeof(param)); - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == '\0' ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == '\0') break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } bool hasSS = (stage->ss != nullptr); - if ( ParseSurfaceSpritesOptional( param, buffer, stage ) && !hasSS ) - { + if (ParseSurfaceSpritesOptional(param, buffer, stage) && !hasSS) { ++shader.numSurfaceSpriteStages; } continue; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -2086,8 +1706,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // load packed textures // - if (stage->specularType != SPEC_SPECGLOSS && stage->specularType != SPEC_NONE) - { + if (stage->specularType != SPEC_SPECGLOSS && stage->specularType != SPEC_NONE) { int flags = IMGFLAG_NOLIGHTSCALE; if (!shader.noMipMaps) @@ -2105,14 +1724,12 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // search for shader based external lightmaps that were created by q3map2 // - if (stage->bundle[0].tcGen == TCGEN_LIGHTMAP && stage->bundle[0].isLightmap == qfalse) - { - const char *filename = { va("%s/lm_", tr.worldName) }; - if (!Q_strncmp(filename, bufferBaseColorTextureName, sizeof(filename))) - { - if (shader.isHDRLit) - { - image_t *hdrImage = R_FindImageFile(bufferBaseColorTextureName, IMGTYPE_COLORALPHA, IMGFLAG_NOLIGHTSCALE | IMGFLAG_HDR_LIGHTMAP | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE); + if (stage->bundle[0].tcGen == TCGEN_LIGHTMAP && stage->bundle[0].isLightmap == qfalse) { + const char *filename = {va("%s/lm_", tr.worldName)}; + if (!Q_strncmp(filename, bufferBaseColorTextureName, sizeof(filename))) { + if (shader.isHDRLit) { + image_t *hdrImage = R_FindImageFile(bufferBaseColorTextureName, IMGTYPE_COLORALPHA, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_HDR_LIGHTMAP | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE); if (hdrImage) stage->bundle[0].image[0] = hdrImage; } @@ -2134,31 +1751,25 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // if cgen isn't explicitly specified, use either identity or identitylighting // - if ( stage->rgbGen == CGEN_BAD ) { - if ( blendSrcBits == 0 || - blendSrcBits == GLS_SRCBLEND_ONE || - blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) { + if (stage->rgbGen == CGEN_BAD) { + if (blendSrcBits == 0 || blendSrcBits == GLS_SRCBLEND_ONE || blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; } else { stage->rgbGen = CGEN_IDENTITY; } } - // // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending // - if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && - ( blendDstBits == GLS_DSTBLEND_ZERO ) ) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ZERO)) { blendDstBits = blendSrcBits = 0; depthMaskBits = GLS_DEPTHMASK_TRUE; } // decide which agens we can skip - if ( stage->alphaGen == AGEN_IDENTITY ) { - if ( stage->rgbGen == CGEN_IDENTITY - || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) { + if (stage->alphaGen == AGEN_IDENTITY) { + if (stage->rgbGen == CGEN_IDENTITY || stage->rgbGen == CGEN_LIGHTING_DIFFUSE) { stage->alphaGen = AGEN_SKIP; } } @@ -2166,9 +1777,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // compute state bits // - stage->stateBits = depthMaskBits | - blendSrcBits | blendDstBits | - depthFuncBits; + stage->stateBits = depthMaskBits | blendSrcBits | blendDstBits | depthFuncBits; return qtrue; } @@ -2187,147 +1796,134 @@ deformVertexes autoSprite2 deformVertexes text[0-7] =============== */ -static void ParseDeform( const char **text ) { - char *token; - deformStage_t *ds; +static void ParseDeform(const char **text) { + char *token; + deformStage_t *ds; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name); return; } - if ( shader.numDeforms == MAX_SHADER_DEFORMS ) { - ri.Printf( PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name ); + if (shader.numDeforms == MAX_SHADER_DEFORMS) { + ri.Printf(PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name); return; } - ds = &shader.deforms[ shader.numDeforms ]; + ds = &shader.deforms[shader.numDeforms]; shader.numDeforms++; - if ( !Q_stricmp( token, "projectionShadow" ) ) { + if (!Q_stricmp(token, "projectionShadow")) { ds->deformation = DEFORM_PROJECTION_SHADOW; return; } - if ( !Q_stricmp( token, "autosprite" ) ) { + if (!Q_stricmp(token, "autosprite")) { ds->deformation = DEFORM_AUTOSPRITE; return; } - if ( !Q_stricmp( token, "autosprite2" ) ) { + if (!Q_stricmp(token, "autosprite2")) { ds->deformation = DEFORM_AUTOSPRITE2; return; } - if ( !Q_stricmpn( token, "text", 4 ) ) { - int n; - + if (!Q_stricmpn(token, "text", 4)) { + int n; + n = token[4] - '0'; - if ( n < 0 || n > 7 ) { + if (n < 0 || n > 7) { n = 0; } ds->deformation = (deform_t)(DEFORM_TEXT0 + n); return; } - if ( !Q_stricmp( token, "bulge" ) ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "bulge")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeWidth = atof( token ); + ds->bulgeWidth = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeHeight = atof( token ); + ds->bulgeHeight = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeSpeed = atof( token ); + ds->bulgeSpeed = atof(token); ds->deformation = DEFORM_BULGE; return; } - if ( !Q_stricmp( token, "wave" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "wave")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - if ( atof( token ) != 0 ) - { - ds->deformationSpread = 1.0f / atof( token ); - } - else - { + if (atof(token) != 0) { + ds->deformationSpread = 1.0f / atof(token); + } else { ds->deformationSpread = 100.0f; - ri.Printf( PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_WAVE; return; } - if ( !Q_stricmp( token, "normal" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "normal")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.amplitude = atof( token ); + ds->deformationWave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.frequency = atof( token ); + ds->deformationWave.frequency = atof(token); ds->deformation = DEFORM_NORMALS; return; } - if ( !Q_stricmp( token, "move" ) ) { - int i; + if (!Q_stricmp(token, "move")) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + for (i = 0; i < 3; i++) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->moveVector[i] = atof( token ); + ds->moveVector[i] = atof(token); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_MOVE; return; } - ri.Printf( PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name ); + ri.Printf(PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name); } - /* =============== ParseSkyParms @@ -2335,11 +1931,11 @@ ParseSkyParms skyParms =============== */ -static void ParseSkyParms( const char **text ) { - char *token; - static const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; - char pathname[MAX_QPATH]; - int i; +static void ParseSkyParms(const char **text) { + char *token; + static const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; + char pathname[MAX_QPATH]; + int i; int imgFlags = IMGFLAG_MIPMAP | IMGFLAG_PICMIP | IMGFLAG_CLAMPTOEDGE; if (shader.noTC) @@ -2349,19 +1945,19 @@ static void ParseSkyParms( const char **text ) { imgFlags |= IMGFLAG_SRGB | IMGFLAG_HDR | IMGFLAG_NOLIGHTSCALE; // srgb or hdr are requested. If hdr is found, the srgb flag will be ignored // outerbox - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name); return; } - if ( strcmp( token, "-" ) ) { - for (i=0 ; i<6 ; i++) { - Com_sprintf( pathname, sizeof(pathname), "%s_%s", token, suf[i] ); - shader.sky.outerbox[i] = R_FindImageFile( ( char * ) pathname, IMGTYPE_COLORALPHA, imgFlags ); + if (strcmp(token, "-")) { + for (i = 0; i < 6; i++) { + Com_sprintf(pathname, sizeof(pathname), "%s_%s", token, suf[i]); + shader.sky.outerbox[i] = R_FindImageFile((char *)pathname, IMGTYPE_COLORALPHA, imgFlags); - if ( !shader.sky.outerbox[i] ) { - if ( i ) - shader.sky.outerbox[i] = shader.sky.outerbox[i-1]; //not found, so let's use the previous image + if (!shader.sky.outerbox[i]) { + if (i) + shader.sky.outerbox[i] = shader.sky.outerbox[i - 1]; // not found, so let's use the previous image else shader.sky.outerbox[i] = tr.defaultImage; } @@ -2369,72 +1965,70 @@ static void ParseSkyParms( const char **text ) { } // cloudheight - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name); return; } - shader.sky.cloudHeight = atof( token ); - if ( !shader.sky.cloudHeight ) { + shader.sky.cloudHeight = atof(token); + if (!shader.sky.cloudHeight) { shader.sky.cloudHeight = 512; } - R_InitSkyTexCoords( shader.sky.cloudHeight ); + R_InitSkyTexCoords(shader.sky.cloudHeight); // innerbox - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "-" ) ) { - ri.Printf( PRINT_WARNING, "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "-")) { + ri.Printf(PRINT_WARNING, "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); } shader.isSky = qtrue; } - /* ================= ParseSort ================= */ -void ParseSort( const char **text ) { - char *token; +void ParseSort(const char **text) { + char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name); return; } - if ( !Q_stricmp( token, "portal" ) ) { + if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; - } else if ( !Q_stricmp( token, "sky" ) ) { + } else if (!Q_stricmp(token, "sky")) { shader.sort = SS_ENVIRONMENT; - } else if ( !Q_stricmp( token, "opaque" ) ) { + } else if (!Q_stricmp(token, "opaque")) { shader.sort = SS_OPAQUE; - } else if ( !Q_stricmp( token, "decal" ) ) { + } else if (!Q_stricmp(token, "decal")) { shader.sort = SS_DECAL; - } else if ( !Q_stricmp( token, "seeThrough" ) ) { + } else if (!Q_stricmp(token, "seeThrough")) { shader.sort = SS_SEE_THROUGH; - } else if ( !Q_stricmp( token, "banner" ) ) { + } else if (!Q_stricmp(token, "banner")) { shader.sort = SS_BANNER; - } else if ( !Q_stricmp( token, "additive" ) ) { + } else if (!Q_stricmp(token, "additive")) { shader.sort = SS_BLEND1; - } else if ( !Q_stricmp( token, "nearest" ) ) { + } else if (!Q_stricmp(token, "nearest")) { shader.sort = SS_NEAREST; - } else if ( !Q_stricmp( token, "underwater" ) ) { + } else if (!Q_stricmp(token, "underwater")) { shader.sort = SS_UNDERWATER; - } else if ( !Q_stricmp( token, "inside" ) ) { + } else if (!Q_stricmp(token, "inside")) { shader.sort = SS_INSIDE; - } else if ( !Q_stricmp( token, "mid_inside" ) ) { + } else if (!Q_stricmp(token, "mid_inside")) { shader.sort = SS_MID_INSIDE; - } else if ( !Q_stricmp( token, "middle" ) ) { + } else if (!Q_stricmp(token, "middle")) { shader.sort = SS_MIDDLE; - } else if ( !Q_stricmp( token, "mid_outside" ) ) { + } else if (!Q_stricmp(token, "mid_outside")) { shader.sort = SS_MID_OUTSIDE; - } else if ( !Q_stricmp( token, "outside" ) ) { + } else if (!Q_stricmp(token, "outside")) { shader.sort = SS_OUTSIDE; - } - else { - shader.sort = atof( token ); + } else { + shader.sort = atof(token); } } @@ -2443,80 +2037,71 @@ void ParseSort( const char **text ) { ParseMaterial ================= */ -const char *materialNames[MATERIAL_LAST] = -{ - MATERIALS -}; +const char *materialNames[MATERIAL_LAST] = {MATERIALS}; -void ParseMaterial( const char **text ) -{ - char *token; - int i; +void ParseMaterial(const char **text) { + char *token; + int i; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - Com_Printf (S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name); return; } - for(i = 0; i < MATERIAL_LAST; i++) - { - if ( !Q_stricmp( token, materialNames[i] ) ) - { + for (i = 0; i < MATERIAL_LAST; i++) { + if (!Q_stricmp(token, materialNames[i])) { shader.surfaceFlags |= i; break; } } } - // this table is also present in q3map typedef struct infoParm_s { - const char *name; - uint32_t clearSolid, surfaceFlags, contents; + const char *name; + uint32_t clearSolid, surfaceFlags, contents; } infoParm_t; -infoParm_t infoParms[] = { +infoParm_t infoParms[] = { // Game content Flags - { "nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE }, // special hack to clear solid flag - { "nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE }, // special hack to clear opaque flag - { "lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA }, // very damaging - { "slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME }, // mildly damaging - { "water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER }, // - { "fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering - { "shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP }, // block shots, but not people - { "playerclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP }, // block only the player - { "monsterclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP }, // - { "botclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP }, // for bots - { "trigger", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER }, // - { "nodrop", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc) - { "terrain", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN }, // use special terrain collsion - { "ladder", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER }, // climb up in it like water - { "abseil", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL }, // can abseil down this brush - { "outside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE }, // volume is considered to be in the outside (i.e. not indoors) - { "inside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE }, // volume is considered to be inside (i.e. indoors) - - { "detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL }, // don't include in structural bsp - { "trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT }, // surface has an alpha component + {"nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE}, // special hack to clear solid flag + {"nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE}, // special hack to clear opaque flag + {"lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA}, // very damaging + {"slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME}, // mildly damaging + {"water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER}, // + {"fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering + {"shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP}, // block shots, but not people + {"playerclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP}, // block only the player + {"monsterclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP}, // + {"botclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP}, // for bots + {"trigger", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER}, // + {"nodrop", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP}, // don't drop items or leave bodies (death fog, lava, etc) + {"terrain", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN}, // use special terrain collsion + {"ladder", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER}, // climb up in it like water + {"abseil", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL}, // can abseil down this brush + {"outside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE}, // volume is considered to be in the outside (i.e. not indoors) + {"inside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE}, // volume is considered to be inside (i.e. indoors) + + {"detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL}, // don't include in structural bsp + {"trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT}, // surface has an alpha component /* Game surface flags */ - { "sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE }, // emit light from an environment map - { "slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE }, // - - { "nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE }, // - { "noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE }, // don't make impact explosions or marks - { "nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE }, // don't make impact marks, but still explode - { "nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE }, // don't generate a drawsurface (or a lightmap) - { "nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE }, // - { "nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE }, // don't ever add dynamic lights - { "metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE }, // - { "nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE }, // No misc ents on this surface - { "forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE }, // - { "forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE }, // only visible with force sight + {"sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE}, // emit light from an environment map + {"slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE}, // + + {"nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE}, // + {"noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE}, // don't make impact explosions or marks + {"nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE}, // don't make impact marks, but still explode + {"nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE}, // don't generate a drawsurface (or a lightmap) + {"nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE}, // + {"nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE}, // don't ever add dynamic lights + {"metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE}, // + {"nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE}, // No misc ents on this surface + {"forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE}, // + {"forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE}, // only visible with force sight }; - /* =============== ParseSurfaceParm @@ -2524,14 +2109,14 @@ ParseSurfaceParm surfaceparm =============== */ -static void ParseSurfaceParm( const char **text ) { - char *token; - int numInfoParms = ARRAY_LEN( infoParms ); - int i; - - token = COM_ParseExt( text, qfalse ); - for ( i = 0 ; i < numInfoParms ; i++ ) { - if ( !Q_stricmp( token, infoParms[i].name ) ) { +static void ParseSurfaceParm(const char **text) { + char *token; + int numInfoParms = ARRAY_LEN(infoParms); + int i; + + token = COM_ParseExt(text, qfalse); + for (i = 0; i < numInfoParms; i++) { + if (!Q_stricmp(token, infoParms[i].name)) { shader.surfaceFlags |= infoParms[i].surfaceFlags; shader.contentFlags |= infoParms[i].contents; shader.contentFlags &= infoParms[i].clearSolid; @@ -2549,45 +2134,38 @@ shader. Parse it into the global shader variable. Later functions will optimize it. ================= */ -static qboolean ParseShader( const char **text ) -{ +static qboolean ParseShader(const char **text) { char *token; const char *begin = *text; int s; s = 0; - token = COM_ParseExt( text, qtrue ); - if ( token[0] != '{' ) - { - ri.Printf( PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name ); + token = COM_ParseExt(text, qtrue); + if (token[0] != '{') { + ri.Printf(PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name); return qfalse; } - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name); return qfalse; } // end of shader definition - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // stage definition - else if ( token[0] == '{' ) - { - if ( s >= MAX_SHADER_STAGES ) { - ri.Printf( PRINT_WARNING, "WARNING: too many stages in shader %s\n", shader.name ); + else if (token[0] == '{') { + if (s >= MAX_SHADER_STAGES) { + ri.Printf(PRINT_WARNING, "WARNING: too many stages in shader %s\n", shader.name); return qfalse; } - if ( !ParseStage( &stages[s], text ) ) - { + if (!ParseStage(&stages[s], text)) { return qfalse; } stages[s].active = qtrue; @@ -2596,161 +2174,141 @@ static qboolean ParseShader( const char **text ) continue; } // skip stuff that only the QuakeEdRadient needs - else if ( !Q_stricmpn( token, "qer", 3 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "qer", 3)) { + SkipRestOfLine(text); continue; } // material deprecated as of 11 Jan 01 // material undeprecated as of 7 May 01 - q3map_material deprecated - else if ( !Q_stricmp( token, "material" ) || !Q_stricmp( token, "q3map_material" ) ) - { - ParseMaterial( text ); - } + else if (!Q_stricmp(token, "material") || !Q_stricmp(token, "q3map_material")) { + ParseMaterial(text); + } // sun parms - else if ( !Q_stricmp( token, "sun" ) || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) || !Q_stricmp( token, "q3gl2_sun" ) ) { - float a, b; + else if (!Q_stricmp(token, "sun") || !Q_stricmp(token, "q3map_sun") || !Q_stricmp(token, "q3map_sunExt") || !Q_stricmp(token, "q3gl2_sun")) { + float a, b; qboolean isGL2Sun = qfalse; - if (!Q_stricmp( token, "q3gl2_sun" ) && r_sunShadows->integer ) - { + if (!Q_stricmp(token, "q3gl2_sun") && r_sunShadows->integer) { isGL2Sun = qtrue; tr.sunShadows = qtrue; } - token = COM_ParseExt( text, qfalse ); - tr.sunLight[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[1] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[2] = atof( token ); - - VectorNormalize( tr.sunLight ); - - token = COM_ParseExt( text, qfalse ); - a = atof( token ); - VectorScale( tr.sunLight, a, tr.sunLight); - - token = COM_ParseExt( text, qfalse ); - a = atof( token ); + token = COM_ParseExt(text, qfalse); + tr.sunLight[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[1] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[2] = atof(token); + + VectorNormalize(tr.sunLight); + + token = COM_ParseExt(text, qfalse); + a = atof(token); + VectorScale(tr.sunLight, a, tr.sunLight); + + token = COM_ParseExt(text, qfalse); + a = atof(token); a = a / 180 * M_PI; - token = COM_ParseExt( text, qfalse ); - b = atof( token ); + token = COM_ParseExt(text, qfalse); + b = atof(token); b = b / 180 * M_PI; - tr.sunDirection[0] = cos( a ) * cos( b ); - tr.sunDirection[1] = sin( a ) * cos( b ); - tr.sunDirection[2] = sin( b ); + tr.sunDirection[0] = cos(a) * cos(b); + tr.sunDirection[1] = sin(a) * cos(b); + tr.sunDirection[2] = sin(b); - if (isGL2Sun) - { - token = COM_ParseExt( text, qfalse ); + if (isGL2Sun) { + token = COM_ParseExt(text, qfalse); tr.mapLightScale = atof(token); - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); tr.sunShadowScale = atof(token); - if (tr.sunShadowScale < 0.0f) - { - ri.Printf (PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 0.0.\n"); + if (tr.sunShadowScale < 0.0f) { + ri.Printf(PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 0.0.\n"); tr.sunShadowScale = 0.0f; - } - else if (tr.sunShadowScale > 1.0f) - { - ri.Printf (PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 1.0.\n"); + } else if (tr.sunShadowScale > 1.0f) { + ri.Printf(PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 1.0.\n"); tr.sunShadowScale = 1.0f; } } - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // tonemap parms - else if ( !Q_stricmp( token, "q3gl2_tonemap" ) ) { - token = COM_ParseExt( text, qfalse ); - tr.toneMinAvgMaxLevel[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.toneMinAvgMaxLevel[1] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.toneMinAvgMaxLevel[2] = atof( token ); - - token = COM_ParseExt( text, qfalse ); - tr.autoExposureMinMax[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.autoExposureMinMax[1] = atof( token ); + else if (!Q_stricmp(token, "q3gl2_tonemap")) { + token = COM_ParseExt(text, qfalse); + tr.toneMinAvgMaxLevel[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.toneMinAvgMaxLevel[1] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.toneMinAvgMaxLevel[2] = atof(token); + + token = COM_ParseExt(text, qfalse); + tr.autoExposureMinMax[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.autoExposureMinMax[1] = atof(token); tr.explicitToneMap = true; - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // q3map_surfacelight deprecated as of 16 Jul 01 - else if ( !Q_stricmp( token, "surfacelight" ) || !Q_stricmp( token, "q3map_surfacelight" ) ) - { - SkipRestOfLine( text ); + else if (!Q_stricmp(token, "surfacelight") || !Q_stricmp(token, "q3map_surfacelight")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "lightColor" ) ) - { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "lightColor")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "deformvertexes" ) || !Q_stricmp( token, "deform" ) ) { - ParseDeform( text ); + } else if (!Q_stricmp(token, "deformvertexes") || !Q_stricmp(token, "deform")) { + ParseDeform(text); continue; - } - else if ( !Q_stricmp( token, "tesssize" ) ) { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "tesssize")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "clampTime" ) ) { - token = COM_ParseExt( text, qfalse ); + } else if (!Q_stricmp(token, "clampTime")) { + token = COM_ParseExt(text, qfalse); if (token[0]) { shader.clampTime = atof(token); } } // skip stuff that only the q3map needs - else if ( !Q_stricmpn( token, "q3map", 5 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "q3map", 5)) { + SkipRestOfLine(text); continue; } // skip stuff that only q3map or the server needs - else if ( !Q_stricmp( token, "surfaceParm" ) ) { - ParseSurfaceParm( text ); + else if (!Q_stricmp(token, "surfaceParm")) { + ParseSurfaceParm(text); continue; } // no mip maps - else if ( !Q_stricmp( token, "nomipmaps" ) ) - { + else if (!Q_stricmp(token, "nomipmaps")) { shader.noMipMaps = qtrue; shader.noPicMip = qtrue; continue; } // refractive surface - else if ( !Q_stricmp(token, "refractive" ) ) - { + else if (!Q_stricmp(token, "refractive")) { shader.useDistortion = qtrue; continue; } // no picmip adjustment - else if ( !Q_stricmp( token, "nopicmip" ) ) - { + else if (!Q_stricmp(token, "nopicmip")) { shader.noPicMip = qtrue; continue; - } - else if ( !Q_stricmp( token, "noglfog" ) ) - { - //shader.fogPass = FP_NONE; + } else if (!Q_stricmp(token, "noglfog")) { + // shader.fogPass = FP_NONE; continue; } // polygonOffset - else if ( !Q_stricmp( token, "polygonOffset" ) ) - { + else if (!Q_stricmp(token, "polygonOffset")) { shader.polygonOffset = qtrue; continue; - } - else if ( !Q_stricmp( token, "noTC" ) ) - { + } else if (!Q_stricmp(token, "noTC")) { shader.noTC = qtrue; continue; } @@ -2758,82 +2316,66 @@ static qboolean ParseShader( const char **text ) // to be merged into one batch. This is a savings for smoke // puffs and blood, but can't be used for anything where the // shader calcs (not the surface function) reference the entity color or scroll - else if ( !Q_stricmp( token, "entityMergable" ) ) - { + else if (!Q_stricmp(token, "entityMergable")) { shader.entityMergable = qtrue; continue; } // fogParms - else if ( !Q_stricmp( token, "fogParms" ) ) - { - if ( !ParseVector( text, 3, shader.fogParms.color ) ) { + else if (!Q_stricmp(token, "fogParms")) { + if (!ParseVector(text, 3, shader.fogParms.color)) { return qfalse; } - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name); continue; } - shader.fogParms.depthForOpaque = atof( token ); + shader.fogParms.depthForOpaque = atof(token); // skip any old gradient directions - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // portal - else if ( !Q_stricmp(token, "portal") ) - { + else if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; shader.isPortal = qtrue; continue; } // skyparms - else if ( !Q_stricmp( token, "skyparms" ) ) - { - ParseSkyParms( text ); + else if (!Q_stricmp(token, "skyparms")) { + ParseSkyParms(text); continue; } // light determines flaring in q3map, not needed here - else if ( !Q_stricmp(token, "light") ) - { - COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "light")) { + COM_ParseExt(text, qfalse); continue; } // cull - else if ( !Q_stricmp( token, "cull") ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "cull")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) ) - { + if (!Q_stricmp(token, "none") || !Q_stricmp(token, "twosided") || !Q_stricmp(token, "disable")) { shader.cullType = CT_TWO_SIDED; - } - else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) ) - { + } else if (!Q_stricmp(token, "back") || !Q_stricmp(token, "backside") || !Q_stricmp(token, "backsided")) { shader.cullType = CT_BACK_SIDED; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name); } continue; } // sort - else if ( !Q_stricmp( token, "sort" ) ) - { - ParseSort( text ); + else if (!Q_stricmp(token, "sort")) { + ParseSort(text); continue; - } - else - { - ri.Printf( PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name); return qfalse; } } @@ -2841,7 +2383,7 @@ static qboolean ParseShader( const char **text ) // // ignore shaders that don't have any stages, unless it is a sky or fog // - if ( s == 0 && !shader.isSky && !(shader.contentFlags & CONTENTS_FOG ) ) { + if (s == 0 && !shader.isSky && !(shader.contentFlags & CONTENTS_FOG)) { return qfalse; } @@ -2855,10 +2397,8 @@ static qboolean ParseShader( const char **text ) // We match against the retail version of gfx/2d/wedge by calculating the // hash value of the shader text, and comparing it against a precalculated // value. - uint32_t shaderHash = generateHashValueForText( begin, *text - begin ); - if ( shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && - Q_stricmp( shader.name, "gfx/2d/wedge" ) == 0 ) - { + uint32_t shaderHash = generateHashValueForText(begin, *text - begin); + if (shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && Q_stricmp(shader.name, "gfx/2d/wedge") == 0) { stages[0].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); stages[0].stateBits |= GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } @@ -2882,15 +2422,13 @@ See if we can use on of the simple fastpath stage functions, otherwise set to the generic stage function =================== */ -static void ComputeStageIteratorFunc( void ) -{ +static void ComputeStageIteratorFunc(void) { shader.optimalStageIteratorFunc = RB_StageIteratorGeneric; // // see if this should go into the sky path // - if ( shader.isSky ) - { + if (shader.isSky) { shader.optimalStageIteratorFunc = RB_StageIteratorSky; return; } @@ -2904,197 +2442,165 @@ Check which vertex attributes we only need, so we don't need to submit/copy all of them. =================== */ -static void ComputeVertexAttribs(void) -{ +static void ComputeVertexAttribs(void) { int i, stage; // dlights always need ATTR_NORMAL shader.vertexAttribs = ATTR_POSITION | ATTR_NORMAL | ATTR_COLOR; - if (shader.defaultShader) - { + if (shader.defaultShader) { shader.vertexAttribs |= ATTR_TEXCOORD0; return; } - if(shader.numDeforms) - { - for ( i = 0; i < shader.numDeforms; i++) - { - deformStage_t *ds = &shader.deforms[i]; + if (shader.numDeforms) { + for (i = 0; i < shader.numDeforms; i++) { + deformStage_t *ds = &shader.deforms[i]; - switch (ds->deformation) - { - case DEFORM_BULGE: - shader.vertexAttribs |= ATTR_NORMAL | ATTR_TEXCOORD0; - break; + switch (ds->deformation) { + case DEFORM_BULGE: + shader.vertexAttribs |= ATTR_NORMAL | ATTR_TEXCOORD0; + break; - case DEFORM_AUTOSPRITE: - shader.vertexAttribs |= ATTR_NORMAL | ATTR_COLOR; - break; + case DEFORM_AUTOSPRITE: + shader.vertexAttribs |= ATTR_NORMAL | ATTR_COLOR; + break; - case DEFORM_WAVE: - case DEFORM_NORMALS: - case DEFORM_TEXT0: - case DEFORM_TEXT1: - case DEFORM_TEXT2: - case DEFORM_TEXT3: - case DEFORM_TEXT4: - case DEFORM_TEXT5: - case DEFORM_TEXT6: - case DEFORM_TEXT7: - shader.vertexAttribs |= ATTR_NORMAL; - break; + case DEFORM_WAVE: + case DEFORM_NORMALS: + case DEFORM_TEXT0: + case DEFORM_TEXT1: + case DEFORM_TEXT2: + case DEFORM_TEXT3: + case DEFORM_TEXT4: + case DEFORM_TEXT5: + case DEFORM_TEXT6: + case DEFORM_TEXT7: + shader.vertexAttribs |= ATTR_NORMAL; + break; - default: - case DEFORM_NONE: - case DEFORM_MOVE: - case DEFORM_PROJECTION_SHADOW: - case DEFORM_AUTOSPRITE2: - break; + default: + case DEFORM_NONE: + case DEFORM_MOVE: + case DEFORM_PROJECTION_SHADOW: + case DEFORM_AUTOSPRITE2: + break; } } } - for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) - { + for (stage = 0; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) - { + if (!pStage->active) { break; } - if (pStage->glslShaderGroup == tr.lightallShader) - { + if (pStage->glslShaderGroup == tr.lightallShader) { shader.vertexAttribs |= ATTR_NORMAL; - if ((pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) && - (r_normalMapping->integer != 0 || - r_specularMapping->integer != 0)) - { + if ((pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) && (r_normalMapping->integer != 0 || r_specularMapping->integer != 0)) { shader.vertexAttribs |= ATTR_TANGENT; } - switch (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) - { - case LIGHTDEF_USE_LIGHTMAP: - case LIGHTDEF_USE_LIGHT_VERTEX: - shader.vertexAttribs |= ATTR_LIGHTDIRECTION; - break; - default: - break; + switch (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) { + case LIGHTDEF_USE_LIGHTMAP: + case LIGHTDEF_USE_LIGHT_VERTEX: + shader.vertexAttribs |= ATTR_LIGHTDIRECTION; + break; + default: + break; } } - for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) - { - if ( pStage->bundle[i].image[0] == 0 ) - { + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) { + if (pStage->bundle[i].image[0] == 0) { continue; } - switch(pStage->bundle[i].tcGen) - { - case TCGEN_TEXTURE: - shader.vertexAttribs |= ATTR_TEXCOORD0; - break; - case TCGEN_LIGHTMAP: - case TCGEN_LIGHTMAP1: - case TCGEN_LIGHTMAP2: - case TCGEN_LIGHTMAP3: - shader.vertexAttribs |= (ATTR_TEXCOORD1 | ATTR_TEXCOORD2 | - ATTR_TEXCOORD3 | ATTR_TEXCOORD4); - break; - case TCGEN_ENVIRONMENT_MAPPED: - shader.vertexAttribs |= ATTR_NORMAL; - break; - - default: - break; - } - } - - switch(pStage->rgbGen) - { - case CGEN_EXACT_VERTEX: - case CGEN_VERTEX: - case CGEN_EXACT_VERTEX_LIT: - case CGEN_VERTEX_LIT: - case CGEN_ONE_MINUS_VERTEX: - shader.vertexAttribs |= ATTR_COLOR; + switch (pStage->bundle[i].tcGen) { + case TCGEN_TEXTURE: + shader.vertexAttribs |= ATTR_TEXCOORD0; break; - - case CGEN_LIGHTING_DIFFUSE: - case CGEN_LIGHTING_DIFFUSE_ENTITY: + case TCGEN_LIGHTMAP: + case TCGEN_LIGHTMAP1: + case TCGEN_LIGHTMAP2: + case TCGEN_LIGHTMAP3: + shader.vertexAttribs |= (ATTR_TEXCOORD1 | ATTR_TEXCOORD2 | ATTR_TEXCOORD3 | ATTR_TEXCOORD4); + break; + case TCGEN_ENVIRONMENT_MAPPED: shader.vertexAttribs |= ATTR_NORMAL; break; default: break; + } } - switch(pStage->alphaGen) - { - case AGEN_LIGHTING_SPECULAR: - shader.vertexAttribs |= ATTR_NORMAL; - break; + switch (pStage->rgbGen) { + case CGEN_EXACT_VERTEX: + case CGEN_VERTEX: + case CGEN_EXACT_VERTEX_LIT: + case CGEN_VERTEX_LIT: + case CGEN_ONE_MINUS_VERTEX: + shader.vertexAttribs |= ATTR_COLOR; + break; - case AGEN_VERTEX: - case AGEN_ONE_MINUS_VERTEX: - shader.vertexAttribs |= ATTR_COLOR; - break; + case CGEN_LIGHTING_DIFFUSE: + case CGEN_LIGHTING_DIFFUSE_ENTITY: + shader.vertexAttribs |= ATTR_NORMAL; + break; - default: - break; + default: + break; + } + + switch (pStage->alphaGen) { + case AGEN_LIGHTING_SPECULAR: + shader.vertexAttribs |= ATTR_NORMAL; + break; + + case AGEN_VERTEX: + case AGEN_ONE_MINUS_VERTEX: + shader.vertexAttribs |= ATTR_COLOR; + break; + + default: + break; } } } -static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightmap, - qboolean useLightVector, qboolean useLightVertex, qboolean tcgen) -{ +static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightmap, qboolean useLightVector, qboolean useLightVertex, qboolean tcgen) { int defs = 0; - //ri.Printf(PRINT_ALL, "shader %s has diffuse %s", shader.name, stage->bundle[0].image[0]->imgName); + // ri.Printf(PRINT_ALL, "shader %s has diffuse %s", shader.name, stage->bundle[0].image[0]->imgName); // reuse diffuse, mark others inactive stage->type = ST_GLSL; - if (lightmap) - { - //ri.Printf(PRINT_ALL, ", lightmap"); + if (lightmap) { + // ri.Printf(PRINT_ALL, ", lightmap"); stage->bundle[TB_LIGHTMAP] = lightmap->bundle[0]; defs |= LIGHTDEF_USE_LIGHTMAP; - } - else if (useLightVector) - { + } else if (useLightVector) { defs |= LIGHTDEF_USE_LIGHT_VECTOR; - } - else if (useLightVertex) - { + } else if (useLightVertex) { defs |= LIGHTDEF_USE_LIGHT_VERTEX; } - if (r_deluxeMapping->integer && tr.worldDeluxeMapping && lightmap) - { - //ri.Printf(PRINT_ALL, ", deluxemap"); + if (r_deluxeMapping->integer && tr.worldDeluxeMapping && lightmap) { + // ri.Printf(PRINT_ALL, ", deluxemap"); stage->bundle[TB_DELUXEMAP] = lightmap->bundle[TB_DELUXEMAP]; } - if (r_normalMapping->integer) - { + if (r_normalMapping->integer) { image_t *diffuseImg; - if (stage->bundle[TB_NORMALMAP].image[0]) - { - if (stage->bundle[TB_NORMALMAP].image[0]->type == IMGTYPE_NORMALHEIGHT && - r_parallaxMapping->integer && - defs & LIGHTDEF_LIGHTTYPE_MASK) + if (stage->bundle[TB_NORMALMAP].image[0]) { + if (stage->bundle[TB_NORMALMAP].image[0]->type == IMGTYPE_NORMALHEIGHT && r_parallaxMapping->integer && defs & LIGHTDEF_LIGHTTYPE_MASK) defs |= LIGHTDEF_USE_PARALLAXMAP; - //ri.Printf(PRINT_ALL, ", normalmap %s", stage->bundle[TB_NORMALMAP].image[0]->imgName); - } - else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) - { + // ri.Printf(PRINT_ALL, ", normalmap %s", stage->bundle[TB_NORMALMAP].image[0]->imgName); + } else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) { char normalName[MAX_QPATH]; image_t *normalImg; int normalFlags = (diffuseImg->flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_SRGB)) | IMGFLAG_NOLIGHTSCALE; @@ -3105,19 +2611,15 @@ static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightm normalImg = R_FindImageFile(normalName, IMGTYPE_NORMALHEIGHT, normalFlags); - if (normalImg) - { + if (normalImg) { parallax = qtrue; - } - else - { + } else { // try a normal image ("_n" suffix) normalName[strlen(normalName) - 1] = '\0'; normalImg = R_FindImageFile(normalName, IMGTYPE_NORMAL, normalFlags); } - if (normalImg) - { + if (normalImg) { stage->bundle[TB_NORMALMAP] = stage->bundle[0]; stage->bundle[TB_NORMALMAP].numImageAnimations = 0; stage->bundle[TB_NORMALMAP].image[0] = normalImg; @@ -3130,16 +2632,12 @@ static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightm } } - if (r_specularMapping->integer) - { + if (r_specularMapping->integer) { image_t *diffuseImg; - if (stage->bundle[TB_SPECULARMAP].image[0]) - { + if (stage->bundle[TB_SPECULARMAP].image[0]) { if (stage->specularType == SPEC_SPECGLOSS) defs |= LIGHTDEF_USE_SPEC_GLOSS; - } - else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) - { + } else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) { char imageName[MAX_QPATH]; image_t *specularImg; int specularFlags = diffuseImg->flags & ~(IMGFLAG_GENNORMALMAP); @@ -3152,35 +2650,29 @@ static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightm else specularImg = R_BuildSDRSpecGlossImage(stage, imageName, specularFlags); - if (specularImg) - { + if (specularImg) { stage->bundle[TB_SPECULARMAP] = stage->bundle[0]; stage->bundle[TB_SPECULARMAP].numImageAnimations = 0; stage->bundle[TB_SPECULARMAP].image[0] = specularImg; stage->specularType = SPEC_SPECGLOSS; defs |= LIGHTDEF_USE_SPEC_GLOSS; VectorSet4(stage->specularScale, 1.0f, 1.0f, 1.0f, 0.0f); - } - else - { + } else { // Data images shouldn't be lightscaled specularFlags |= IMGFLAG_NOLIGHTSCALE; COM_StripExtension(diffuseImg->imgName, imageName, MAX_QPATH); Q_strcat(imageName, MAX_QPATH, "_rmo"); stage->specularType = SPEC_RMO; R_LoadPackedMaterialImage(stage, imageName, specularFlags); - - if (!stage->bundle[TB_ORMSMAP].image[0]) - { + + if (!stage->bundle[TB_ORMSMAP].image[0]) { COM_StripExtension(diffuseImg->imgName, imageName, MAX_QPATH); Q_strcat(imageName, MAX_QPATH, "_orm"); stage->specularType = SPEC_ORM; R_LoadPackedMaterialImage(stage, imageName, specularFlags); - if (!stage->bundle[TB_ORMSMAP].image[0]) - { + if (!stage->bundle[TB_ORMSMAP].image[0]) { stage->specularScale[0] = 0.0f; - stage->specularScale[2] = - stage->specularScale[3] = 1.0f; + stage->specularScale[2] = stage->specularScale[3] = 1.0f; stage->specularScale[1] = 0.5f; } } @@ -3188,8 +2680,7 @@ static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightm } } - if (tcgen || stage->bundle[0].numTexMods) - { + if (tcgen || stage->bundle[0].numTexMods) { defs |= LIGHTDEF_USE_TCGEN_AND_TCMOD; } @@ -3202,117 +2693,100 @@ static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightm if (stage->alphaTestType != ALPHA_TEST_NONE) defs |= LIGHTDEF_USE_ALPHA_TEST; - //ri.Printf(PRINT_ALL, ".\n"); + // ri.Printf(PRINT_ALL, ".\n"); stage->glslShaderGroup = tr.lightallShader; stage->glslShaderIndex = defs; } - -static qboolean CollapseStagesToGLSL(void) -{ +static qboolean CollapseStagesToGLSL(void) { int i, j, numStages; qboolean skip = qfalse; - ri.Printf (PRINT_DEVELOPER, "Collapsing stages for shader '%s'\n", shader.name); + ri.Printf(PRINT_DEVELOPER, "Collapsing stages for shader '%s'\n", shader.name); // skip shaders with deforms - if (shader.numDeforms == 1) - { + if (shader.numDeforms == 1) { skip = qtrue; - ri.Printf (PRINT_DEVELOPER, "> Shader has vertex deformations. Aborting stage collapsing\n"); + ri.Printf(PRINT_DEVELOPER, "> Shader has vertex deformations. Aborting stage collapsing\n"); } - ri.Printf (PRINT_DEVELOPER, "> Original shader stage order:\n"); + ri.Printf(PRINT_DEVELOPER, "> Original shader stage order:\n"); - for ( int i = 0; i < MAX_SHADER_STAGES; i++ ) - { + for (int i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *stage = &stages[i]; - if ( !stage->active ) - { + if (!stage->active) { continue; } - ri.Printf (PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); + ri.Printf(PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); } - if (!skip) - { + if (!skip) { // scan for shaders that aren't supported - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; if (!pStage->active) continue; - if (pStage->adjustColorsForFog) - { + if (pStage->adjustColorsForFog) { skip = qtrue; break; } - if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && - pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) - { - int blendBits = pStage->stateBits & ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); - - if (blendBits != (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) - && blendBits != (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR) - && blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE)) //lightstyle lightmap stages + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) { + int blendBits = pStage->stateBits & (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); + + if (blendBits != (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) && blendBits != (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR) && + blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE)) // lightstyle lightmap stages { skip = qtrue; break; } } - switch(pStage->bundle[0].tcGen) - { - case TCGEN_TEXTURE: - case TCGEN_LIGHTMAP: - case TCGEN_LIGHTMAP1: - case TCGEN_LIGHTMAP2: - case TCGEN_LIGHTMAP3: - case TCGEN_ENVIRONMENT_MAPPED: - case TCGEN_VECTOR: - break; - default: - skip = qtrue; - break; + switch (pStage->bundle[0].tcGen) { + case TCGEN_TEXTURE: + case TCGEN_LIGHTMAP: + case TCGEN_LIGHTMAP1: + case TCGEN_LIGHTMAP2: + case TCGEN_LIGHTMAP3: + case TCGEN_ENVIRONMENT_MAPPED: + case TCGEN_VECTOR: + break; + default: + skip = qtrue; + break; } - switch(pStage->alphaGen) - { - case AGEN_PORTAL: - case AGEN_LIGHTING_SPECULAR: - skip = qtrue; - break; - default: - break; + switch (pStage->alphaGen) { + case AGEN_PORTAL: + case AGEN_LIGHTING_SPECULAR: + skip = qtrue; + break; + default: + break; } } } - if (!skip) - { + if (!skip) { shaderStage_t *lightmaps[MAX_SHADER_STAGES] = {}; - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; if (!pStage->active) continue; - if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) - { + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) { lightmaps[i] = pStage; } } - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; shaderStage_t *diffuse, *lightmap; qboolean parallax, tcgen, diffuselit, vertexlit; @@ -3328,13 +2802,12 @@ static qboolean CollapseStagesToGLSL(void) if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) continue; - diffuse = pStage; + diffuse = pStage; parallax = qfalse; lightmap = NULL; // we have a diffuse map, find matching lightmap - for (j = i + 1; j < MAX_SHADER_STAGES; j++) - { + for (j = i + 1; j < MAX_SHADER_STAGES; j++) { shaderStage_t *pStage2 = &stages[j]; if (!pStage2->active) @@ -3343,11 +2816,8 @@ static qboolean CollapseStagesToGLSL(void) if (pStage2->glow) continue; - if (pStage2->bundle[0].tcGen >= TCGEN_LIGHTMAP && - pStage2->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && - pStage2->rgbGen != CGEN_EXACT_VERTEX) - { - ri.Printf (PRINT_DEVELOPER, "> Setting lightmap for %s to %s\n", pStage->bundle[0].image[0]->imgName, pStage2->bundle[0].image[0]->imgName); + if (pStage2->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage2->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && pStage2->rgbGen != CGEN_EXACT_VERTEX) { + ri.Printf(PRINT_DEVELOPER, "> Setting lightmap for %s to %s\n", pStage->bundle[0].image[0]->imgName, pStage2->bundle[0].image[0]->imgName); lightmap = pStage2; lightmaps[j] = NULL; break; @@ -3355,43 +2825,36 @@ static qboolean CollapseStagesToGLSL(void) } tcgen = qfalse; - if (diffuse->bundle[0].tcGen == TCGEN_ENVIRONMENT_MAPPED - || (diffuse->bundle[0].tcGen >= TCGEN_LIGHTMAP && diffuse->bundle[0].tcGen <= TCGEN_LIGHTMAP3) - || diffuse->bundle[0].tcGen == TCGEN_VECTOR) - { + if (diffuse->bundle[0].tcGen == TCGEN_ENVIRONMENT_MAPPED || + (diffuse->bundle[0].tcGen >= TCGEN_LIGHTMAP && diffuse->bundle[0].tcGen <= TCGEN_LIGHTMAP3) || diffuse->bundle[0].tcGen == TCGEN_VECTOR) { tcgen = qtrue; } diffuselit = qfalse; - if (diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE || - diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) - { + if (diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE || diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) { diffuselit = qtrue; } vertexlit = qfalse; - if (diffuse->rgbGen == CGEN_VERTEX_LIT || diffuse->rgbGen == CGEN_EXACT_VERTEX_LIT || diffuse->rgbGen == CGEN_VERTEX || diffuse->rgbGen == CGEN_EXACT_VERTEX) - { + if (diffuse->rgbGen == CGEN_VERTEX_LIT || diffuse->rgbGen == CGEN_EXACT_VERTEX_LIT || diffuse->rgbGen == CGEN_VERTEX || + diffuse->rgbGen == CGEN_EXACT_VERTEX) { vertexlit = qtrue; } CollapseStagesToLightall(diffuse, lightmap, diffuselit, vertexlit, tcgen); - //find lightstyle stages - if (lightmap != NULL) - { - for (j = i + 2; j < MAX_SHADER_STAGES; j++) - { + // find lightstyle stages + if (lightmap != NULL) { + for (j = i + 2; j < MAX_SHADER_STAGES; j++) { shaderStage_t *pStage2 = &stages[j]; int blendBits = pStage2->stateBits & (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); - if (blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE) - || (pStage2->bundle[0].tcGen < TCGEN_LIGHTMAP && pStage2->bundle[0].tcGen > TCGEN_LIGHTMAP3) - || pStage2->rgbGen != CGEN_LIGHTMAPSTYLE) + if (blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE) || + (pStage2->bundle[0].tcGen < TCGEN_LIGHTMAP && pStage2->bundle[0].tcGen > TCGEN_LIGHTMAP3) || pStage2->rgbGen != CGEN_LIGHTMAPSTYLE) break; - //style stage is the previous lightmap stage which is not used anymore + // style stage is the previous lightmap stage which is not used anymore shaderStage_t *styleStage = &stages[j - 1]; int style = pStage2->lightmapStyle; @@ -3413,44 +2876,35 @@ static qboolean CollapseStagesToGLSL(void) } // deactivate lightmap stages - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; if (!pStage->active) continue; - if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && - pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && - lightmaps[i] == NULL) - { + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && lightmaps[i] == NULL) { pStage->active = qfalse; } } } - if (skip) - { + if (skip) { // set default specular scale for skipped shaders that will use metalness workflow by default - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; pStage->specularScale[0] = 0.0f; - pStage->specularScale[2] = - pStage->specularScale[3] = 1.0f; + pStage->specularScale[2] = pStage->specularScale[3] = 1.0f; pStage->specularScale[1] = 0.5f; } } // remove inactive stages numStages = 0; - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + for (i = 0; i < MAX_SHADER_STAGES; i++) { if (!stages[i].active) continue; - if (i == numStages) - { + if (i == numStages) { numStages++; continue; } @@ -3462,10 +2916,8 @@ static qboolean CollapseStagesToGLSL(void) // convert any remaining lightmap stages to a lighting pass with a white texture // only do this with r_sunlightMode non-zero, as it's only for correct shadows. - if (r_sunlightMode->integer && shader.numDeforms != 1) - { - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + if (r_sunlightMode->integer && shader.numDeforms != 1) { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; if (!pStage->active) @@ -3474,9 +2926,8 @@ static qboolean CollapseStagesToGLSL(void) if (pStage->adjustColorsForFog) continue; - if (pStage->bundle[TB_DIFFUSEMAP].tcGen >= TCGEN_LIGHTMAP - && pStage->bundle[TB_DIFFUSEMAP].tcGen <= TCGEN_LIGHTMAP3 - && pStage->rgbGen != CGEN_LIGHTMAPSTYLE) //don't convert lightstyled lightmap stages + if (pStage->bundle[TB_DIFFUSEMAP].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[TB_DIFFUSEMAP].tcGen <= TCGEN_LIGHTMAP3 && + pStage->rgbGen != CGEN_LIGHTMAPSTYLE) // don't convert lightstyled lightmap stages { pStage->glslShaderGroup = tr.lightallShader; pStage->glslShaderIndex = LIGHTDEF_USE_LIGHTMAP; @@ -3489,10 +2940,8 @@ static qboolean CollapseStagesToGLSL(void) } // convert any remaining lightingdiffuse stages to a lighting pass - if (shader.numDeforms != 1) - { - for (i = 0; i < MAX_SHADER_STAGES; i++) - { + if (shader.numDeforms != 1) { + for (i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *pStage = &stages[i]; if (!pStage->active) @@ -3501,16 +2950,11 @@ static qboolean CollapseStagesToGLSL(void) if (pStage->adjustColorsForFog) continue; - if (pStage->rgbGen == CGEN_LIGHTING_DIFFUSE || - pStage->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) - { - if (pStage->glslShaderGroup != tr.lightallShader) - { + if (pStage->rgbGen == CGEN_LIGHTING_DIFFUSE || pStage->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) { + if (pStage->glslShaderGroup != tr.lightallShader) { pStage->glslShaderGroup = tr.lightallShader; pStage->glslShaderIndex = LIGHTDEF_USE_LIGHT_VECTOR; - } - else if (!(pStage->glslShaderIndex & LIGHTDEF_USE_LIGHT_VECTOR)) - { + } else if (!(pStage->glslShaderIndex & LIGHTDEF_USE_LIGHT_VECTOR)) { pStage->glslShaderIndex &= ~LIGHTDEF_LIGHTTYPE_MASK; pStage->glslShaderIndex |= LIGHTDEF_USE_LIGHT_VECTOR; } @@ -3521,18 +2965,16 @@ static qboolean CollapseStagesToGLSL(void) } } - ri.Printf (PRINT_DEVELOPER, "> New shader stage order:\n"); + ri.Printf(PRINT_DEVELOPER, "> New shader stage order:\n"); - for ( int i = 0; i < MAX_SHADER_STAGES; i++ ) - { + for (int i = 0; i < MAX_SHADER_STAGES; i++) { shaderStage_t *stage = &stages[i]; - if ( !stage->active ) - { + if (!stage->active) { continue; } - ri.Printf (PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); + ri.Printf(PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); } return (qboolean)numStages; @@ -3550,70 +2992,64 @@ sortedIndex. ============== */ extern bool gServerSkinHack; -static void FixRenderCommandList( int newShader ) { - if( !gServerSkinHack ) { - renderCommandList_t *cmdList = &backEndData->commands; +static void FixRenderCommandList(int newShader) { + if (!gServerSkinHack) { + renderCommandList_t *cmdList = &backEndData->commands; - if( cmdList ) { + if (cmdList) { const void *curCmd = cmdList->cmds; - while ( 1 ) { + while (1) { curCmd = PADP(curCmd, sizeof(void *)); - switch ( *(const int *)curCmd ) { - case RC_SET_COLOR: - { + switch (*(const int *)curCmd) { + case RC_SET_COLOR: { const setColorCommand_t *sc_cmd = (const setColorCommand_t *)curCmd; curCmd = (const void *)(sc_cmd + 1); break; - } - case RC_STRETCH_PIC: - { + } + case RC_STRETCH_PIC: { const stretchPicCommand_t *sp_cmd = (const stretchPicCommand_t *)curCmd; curCmd = (const void *)(sp_cmd + 1); break; - } + } case RC_ROTATE_PIC: - case RC_ROTATE_PIC2: - { - const rotatePicCommand_t *sp_cmd = (const rotatePicCommand_t *)curCmd; - curCmd = (const void *)(sp_cmd + 1); - break; - } - case RC_DRAW_SURFS: - { + case RC_ROTATE_PIC2: { + const rotatePicCommand_t *sp_cmd = (const rotatePicCommand_t *)curCmd; + curCmd = (const void *)(sp_cmd + 1); + break; + } + case RC_DRAW_SURFS: { int i; - drawSurf_t *drawSurf; - shader_t *shader; - int postRender; - int sortedIndex; - int cubemap; - int entityNum; - const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd; - - for( i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++ ) { - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &cubemap, &postRender ); - sortedIndex = (( drawSurf->sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1)); - if( sortedIndex >= newShader ) { + drawSurf_t *drawSurf; + shader_t *shader; + int postRender; + int sortedIndex; + int cubemap; + int entityNum; + const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd; + + for (i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++) { + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &cubemap, &postRender); + sortedIndex = ((drawSurf->sort >> QSORT_SHADERNUM_SHIFT) & (MAX_SHADERS - 1)); + if (sortedIndex >= newShader) { sortedIndex++; drawSurf->sort = R_CreateSortKey(entityNum, sortedIndex, cubemap, postRender); } } curCmd = (const void *)(ds_cmd + 1); break; - } - case RC_DRAW_BUFFER: - { + } + case RC_DRAW_BUFFER: { const drawBufferCommand_t *db_cmd = (const drawBufferCommand_t *)curCmd; curCmd = (const void *)(db_cmd + 1); break; - } - case RC_SWAP_BUFFERS: - { + } + case RC_SWAP_BUFFERS: { const swapBuffersCommand_t *sb_cmd = (const swapBuffersCommand_t *)curCmd; curCmd = (const void *)(sb_cmd + 1); break; - } + } case RC_END_OF_LIST: default: return; @@ -3634,76 +3070,73 @@ shaders. Sets shader->sortedIndex ============== */ -static void SortNewShader( void ) { - int i; - float sort; - shader_t *newShader; +static void SortNewShader(void) { + int i; + float sort; + shader_t *newShader; - newShader = tr.shaders[ tr.numShaders - 1 ]; + newShader = tr.shaders[tr.numShaders - 1]; sort = newShader->sort; int numStagesInNewShader = 0; - while ( newShader->stages[numStagesInNewShader] ) + while (newShader->stages[numStagesInNewShader]) numStagesInNewShader++; - for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) { + for (i = tr.numShaders - 2; i >= 0; i--) { shader_t *shader = tr.sortedShaders[i]; int numStages = 0; - while ( shader->stages[numStages] ) + while (shader->stages[numStages]) numStages++; - if ( shader->sort < sort ) { + if (shader->sort < sort) { break; } - if ( shader->sort == sort && numStages <= numStagesInNewShader ) - { + if (shader->sort == sort && numStages <= numStagesInNewShader) { break; } - - tr.sortedShaders[i+1] = shader; - tr.sortedShaders[i+1]->sortedIndex++; + + tr.sortedShaders[i + 1] = shader; + tr.sortedShaders[i + 1]->sortedIndex++; } // Arnout: fix rendercommandlist // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 - FixRenderCommandList( i+1 ); + FixRenderCommandList(i + 1); - newShader->sortedIndex = i+1; - tr.sortedShaders[i+1] = newShader; + newShader->sortedIndex = i + 1; + tr.sortedShaders[i + 1] = newShader; } - /* ==================== GeneratePermanentShader ==================== */ -static shader_t *GeneratePermanentShader( void ) { - shader_t *newShader; - int i, b; - int size, hash; +static shader_t *GeneratePermanentShader(void) { + shader_t *newShader; + int i, b; + int size, hash; - if ( tr.numShaders == MAX_SHADERS ) { - ri.Printf( PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); + if (tr.numShaders == MAX_SHADERS) { + ri.Printf(PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); return tr.defaultShader; } - newShader = (shader_t *)ri.Hunk_Alloc( sizeof( shader_t ), h_low ); + newShader = (shader_t *)ri.Hunk_Alloc(sizeof(shader_t), h_low); *newShader = shader; - if ( shader.sort <= SS_SEE_THROUGH ) { + if (shader.sort <= SS_SEE_THROUGH) { newShader->fogPass = FP_EQUAL; - } else if ( shader.contentFlags & CONTENTS_FOG ) { + } else if (shader.contentFlags & CONTENTS_FOG) { newShader->fogPass = FP_LE; } else { newShader->fogPass = FP_NONE; } // determain if fog pass can use depth equal or not - if (newShader->fogPass == FP_EQUAL) - { + if (newShader->fogPass == FP_EQUAL) { newShader->fogPass = FP_LE; bool allPassesAlpha = true; for (int stage = 0; stage < MAX_SHADER_STAGES; stage++) { @@ -3718,8 +3151,7 @@ static shader_t *GeneratePermanentShader( void ) { if (pStage->adjustColorsForFog != ACFF_MODULATE_ALPHA) allPassesAlpha = false; - if (pStage->stateBits & GLS_DEPTHMASK_TRUE) - { + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) { newShader->fogPass = FP_EQUAL; break; } @@ -3729,25 +3161,25 @@ static shader_t *GeneratePermanentShader( void ) { newShader->fogPass = FP_NONE; } - tr.shaders[ tr.numShaders ] = newShader; + tr.shaders[tr.numShaders] = newShader; newShader->index = tr.numShaders; - - tr.sortedShaders[ tr.numShaders ] = newShader; + + tr.sortedShaders[tr.numShaders] = newShader; newShader->sortedIndex = tr.numShaders; tr.numShaders++; - for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) { - if ( !stages[i].active ) { + for (i = 0; i < newShader->numUnfoggedPasses; i++) { + if (!stages[i].active) { break; } - newShader->stages[i] = (shaderStage_t *)ri.Hunk_Alloc( sizeof( stages[i] ), h_low ); + newShader->stages[i] = (shaderStage_t *)ri.Hunk_Alloc(sizeof(stages[i]), h_low); *newShader->stages[i] = stages[i]; - for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) { - size = newShader->stages[i]->bundle[b].numTexMods * sizeof( texModInfo_t ); - newShader->stages[i]->bundle[b].texMods = (texModInfo_t *)ri.Hunk_Alloc( size, h_low ); - Com_Memcpy( newShader->stages[i]->bundle[b].texMods, stages[i].bundle[b].texMods, size ); + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { + size = newShader->stages[i]->bundle[b].numTexMods * sizeof(texModInfo_t); + newShader->stages[i]->bundle[b].texMods = (texModInfo_t *)ri.Hunk_Alloc(size, h_low); + Com_Memcpy(newShader->stages[i]->bundle[b].texMods, stages[i].bundle[b].texMods, size); } } @@ -3771,93 +3203,90 @@ pass, trying to guess which is the correct one to best aproximate what it is supposed to look like. ================= */ -static void VertexLightingCollapse( void ) { - int stage; - shaderStage_t *bestStage; - int bestImageRank; - int rank; +static void VertexLightingCollapse(void) { + int stage; + shaderStage_t *bestStage; + int bestImageRank; + int rank; // if we aren't opaque, just use the first pass - if ( shader.sort == SS_OPAQUE ) { + if (shader.sort == SS_OPAQUE) { // pick the best texture for the single pass bestStage = &stages[0]; bestImageRank = -999999; - for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) { + for (stage = 0; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } rank = 0; - if ( pStage->bundle[0].isLightmap ) { + if (pStage->bundle[0].isLightmap) { rank -= 100; } - if ( pStage->bundle[0].tcGen != TCGEN_TEXTURE ) { + if (pStage->bundle[0].tcGen != TCGEN_TEXTURE) { rank -= 5; } - if ( pStage->bundle[0].numTexMods ) { + if (pStage->bundle[0].numTexMods) { rank -= 5; } - if ( pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING ) { + if (pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING) { rank -= 3; } - if ( rank > bestImageRank ) { + if (rank > bestImageRank) { bestImageRank = rank; bestStage = pStage; } } stages[0].bundle[0] = bestStage->bundle[0]; - stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + stages[0].stateBits &= ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); stages[0].stateBits |= GLS_DEPTHMASK_TRUE; - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; } else { stages[0].rgbGen = CGEN_EXACT_VERTEX; } - stages[0].alphaGen = AGEN_SKIP; + stages[0].alphaGen = AGEN_SKIP; } else { // don't use a lightmap (tesla coils) - if ( stages[0].bundle[0].isLightmap ) { + if (stages[0].bundle[0].isLightmap) { stages[0] = stages[1]; } // if we were in a cross-fade cgen, hack it to normal - if ( stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY ) { + if (stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } - if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH ) - && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH ) ) { + if ((stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH) && + (stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH)) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } - if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH ) - && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH ) ) { + if ((stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH) && + (stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH)) { stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; } } - for ( stage = 1; stage < MAX_SHADER_STAGES; stage++ ) { + for (stage = 1; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } - Com_Memset( pStage, 0, sizeof( *pStage ) ); + Com_Memset(pStage, 0, sizeof(*pStage)); } } -int FindFirstLightmapStage ( const shaderStage_t *stages, int numStages ) -{ - for ( int i = 0; i < numStages; i++ ) - { +int FindFirstLightmapStage(const shaderStage_t *stages, int numStages) { + for (int i = 0; i < numStages; i++) { const shaderStage_t *stage = &stages[i]; - if ( stage->active && stage->bundle[0].isLightmap ) - { + if (stage->active && stage->bundle[0].isLightmap) { return i; } } @@ -3865,12 +3294,9 @@ int FindFirstLightmapStage ( const shaderStage_t *stages, int numStages ) return numStages; } -int GetNumStylesInShader ( const shader_t *shader ) -{ - for ( int i = 0; i < MAXLIGHTMAPS; i++ ) - { - if ( shader->styles[i] >= LS_UNUSED ) - { +int GetNumStylesInShader(const shader_t *shader) { + for (int i = 0; i < MAXLIGHTMAPS; i++) { + if (shader->styles[i] >= LS_UNUSED) { return i - 1; } } @@ -3886,7 +3312,7 @@ Returns a freshly allocated shader with all the needed info from the current global working shader ========================= */ -static shader_t *FinishShader( void ) { +static shader_t *FinishShader(void) { int stage; uint32_t shaderStateBits = 0; qboolean hasLightmapStage = qfalse; @@ -3894,60 +3320,50 @@ static shader_t *FinishShader( void ) { // // set sky stuff appropriate // - if ( shader.isSky ) { + if (shader.isSky) { shader.sort = SS_ENVIRONMENT; } // // set polygon offset // - if ( shader.polygonOffset ) { + if (shader.polygonOffset) { shaderStateBits |= GLS_POLYGON_OFFSET_FILL; - if ( !shader.sort ) { + if (!shader.sort) { shader.sort = SS_DECAL; } } int lmStage; - for(lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) - { + for (lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) { shaderStage_t *pStage = &stages[lmStage]; - if (pStage->active && pStage->bundle[0].isLightmap) - { + if (pStage->active && pStage->bundle[0].isLightmap) { break; } } - if (lmStage < MAX_SHADER_STAGES) - { - if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) - { - if (lmStage == 0) //< MAX_SHADER_STAGES-1) - {//copy the rest down over the lightmap slot - memmove(&stages[lmStage], &stages[lmStage+1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES-lmStage-1)); - memset(&stages[MAX_SHADER_STAGES-1], 0, sizeof(shaderStage_t)); - //change blending on the moved down stage + if (lmStage < MAX_SHADER_STAGES) { + if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { + if (lmStage == 0) //< MAX_SHADER_STAGES-1) + { // copy the rest down over the lightmap slot + memmove(&stages[lmStage], &stages[lmStage + 1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES - lmStage - 1)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(shaderStage_t)); + // change blending on the moved down stage stages[lmStage].stateBits = GLS_DEFAULT; } - //change anything that was moved down (or the *white if LM is first) to use vertex color + // change anything that was moved down (or the *white if LM is first) to use vertex color stages[lmStage].rgbGen = CGEN_EXACT_VERTEX; stages[lmStage].alphaGen = AGEN_SKIP; - lmStage = MAX_SHADER_STAGES; //skip the style checking below + lmStage = MAX_SHADER_STAGES; // skip the style checking below } } // if 2+ stages and first stage is lightmap, switch them // this makes it easier for the later bits to process - if (stages[0].active && - stages[0].bundle[0].isLightmap && - stages[1].active && - shader.numDeforms != 1) - { + if (stages[0].active && stages[0].bundle[0].isLightmap && stages[1].active && shader.numDeforms != 1) { int blendBits = stages[1].stateBits & (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); - if (blendBits == (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) - || blendBits == (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR)) - { + if (blendBits == (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) || blendBits == (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR)) { int stateBits0 = stages[0].stateBits; int stateBits1 = stages[1].stateBits; shaderStage_t swapStage; @@ -3963,72 +3379,60 @@ static shader_t *FinishShader( void ) { } } - if (lmStage < MAX_SHADER_STAGES)// && !r_fullbright->value) + if (lmStage < MAX_SHADER_STAGES) // && !r_fullbright->value) { - int numStyles; - int i; + int numStyles; + int i; - for(numStyles=0;numStyles= LS_UNUSED) - { + for (numStyles = 0; numStyles < MAXLIGHTMAPS; numStyles++) { + if (shader.styles[numStyles] >= LS_UNUSED) { break; } } numStyles--; - if (numStyles > 0) - { - for(i=MAX_SHADER_STAGES-1;i>lmStage+numStyles;i--) - { - stages[i] = stages[i-numStyles]; + if (numStyles > 0) { + for (i = MAX_SHADER_STAGES - 1; i > lmStage + numStyles; i--) { + stages[i] = stages[i - numStyles]; } - for(i=0;iinteger && tr.worldDeluxeMapping) - { - stages[lmStage+i+1].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[i+1]]; - stages[lmStage+i+1].bundle[TB_DELUXEMAP].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP+i+1); + for (i = 0; i < numStyles; i++) { + stages[lmStage + i + 1] = stages[lmStage]; + if (shader.lightmapIndex[i + 1] == LIGHTMAP_BY_VERTEX) { + stages[lmStage + i + 1].bundle[0].image[0] = tr.whiteImage; + } else if (shader.lightmapIndex[i + 1] < 0) { + Com_Error(ERR_DROP, "FinishShader: light style with no light map or vertex color for shader %s", shader.name); + } else { + stages[lmStage + i + 1].bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex[i + 1]]; + stages[lmStage + i + 1].bundle[0].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP + i + 1); + if (r_deluxeMapping->integer && tr.worldDeluxeMapping) { + stages[lmStage + i + 1].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[i + 1]]; + stages[lmStage + i + 1].bundle[TB_DELUXEMAP].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP + i + 1); } } - stages[lmStage+i+1].rgbGen = CGEN_LIGHTMAPSTYLE; - stages[lmStage+i+1].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); - stages[lmStage+i+1].stateBits |= GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + stages[lmStage + i + 1].rgbGen = CGEN_LIGHTMAPSTYLE; + stages[lmStage + i + 1].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); + stages[lmStage + i + 1].stateBits |= GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; } } - for(i=0;i<=numStyles;i++) - { - stages[lmStage+i].lightmapStyle = shader.styles[i]; + for (i = 0; i <= numStyles; i++) { + stages[lmStage + i].lightmapStyle = shader.styles[i]; } } // // set appropriate stage information // - for ( stage = 0; stage < MAX_SHADER_STAGES; ) { + for (stage = 0; stage < MAX_SHADER_STAGES;) { shaderStage_t *pStage = &stages[stage]; - if ( !pStage->active ) { + if (!pStage->active) { break; } // check for a missing texture - if ( !pStage->bundle[0].image[0] ) { - ri.Printf( PRINT_WARNING, "Shader %s, stage %d has no image. This stage will be ignored\n", shader.name, stage + 1 ); + if (!pStage->bundle[0].image[0]) { + ri.Printf(PRINT_WARNING, "Shader %s, stage %d has no image. This stage will be ignored\n", shader.name, stage + 1); pStage->active = qfalse; stage++; continue; @@ -4037,26 +3441,23 @@ static shader_t *FinishShader( void ) { // // ditch this stage if it's detail and detail textures are disabled // - if ( pStage->isDetail && !r_detailTextures->integer ) - { + if (pStage->isDetail && !r_detailTextures->integer) { int index; - - for(index = stage + 1; index < MAX_SHADER_STAGES; index++) - { - if(!stages[index].active) + + for (index = stage + 1; index < MAX_SHADER_STAGES; index++) { + if (!stages[index].active) break; } - - if(index < MAX_SHADER_STAGES) + + if (index < MAX_SHADER_STAGES) memmove(pStage, pStage + 1, sizeof(*pStage) * (index - stage)); - else - { - if(stage + 1 < MAX_SHADER_STAGES) + else { + if (stage + 1 < MAX_SHADER_STAGES) memmove(pStage, pStage + 1, sizeof(*pStage) * (index - stage - 1)); - + Com_Memset(&stages[index - 1], 0, sizeof(*stages)); } - + continue; } @@ -4065,15 +3466,15 @@ static shader_t *FinishShader( void ) { // // default texture coordinate generation // - if ( pStage->bundle[0].isLightmap ) { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].isLightmap) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_LIGHTMAP; if (r_deluxeMapping->integer && tr.worldDeluxeMapping) pStage->bundle[TB_DELUXEMAP].tcGen = TCGEN_LIGHTMAP; } hasLightmapStage = qtrue; } else { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_TEXTURE; } } @@ -4081,8 +3482,7 @@ static shader_t *FinishShader( void ) { // // determine sort order and fog color adjustment // - if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) && - ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) { + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) && (stages[0].stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS))) { int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS; int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS; @@ -4093,18 +3493,16 @@ static shader_t *FinishShader( void ) { // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA // modulate, additive - if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) || - ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) { + if (((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) || + ((blendSrcBits == GLS_SRCBLEND_ZERO) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR))) { pStage->adjustColorsForFog = ACFF_MODULATE_RGB; } // strict blend - else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA; } // premultiplied alpha - else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_RGBA; } else { // we can't adjust this one correctly, so it won't be exactly correct in fog @@ -4114,37 +3512,34 @@ static shader_t *FinishShader( void ) { pStage->adjustColorsForFog = ACFF_NONE; // don't screw with sort order if this is a portal or environment - if ( !shader.sort ) { + if (!shader.sort) { // see through item, like a grill or grate - if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) { + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) { shader.sort = SS_SEE_THROUGH; } else { - if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) { // GL_ONE GL_ONE needs to come a bit later shader.sort = SS_BLEND1; - } - else - { + } else { shader.sort = SS_BLEND0; } } } } - + stage++; } // there are times when you will need to manually apply a sort to // opaque alpha tested shaders that have later blend passes - if ( !shader.sort ) { + if (!shader.sort) { shader.sort = SS_OPAQUE; } // // if we are in r_vertexLight mode, never use a lightmap texture // - if ( stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer) ) { + if (stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer)) { VertexLightingCollapse(); hasLightmapStage = qfalse; } @@ -4154,10 +3549,10 @@ static shader_t *FinishShader( void ) { // stage = CollapseStagesToGLSL(); - if ( shader.lightmapIndex[0] >= 0 && !hasLightmapStage ) { - ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name ); + if (shader.lightmapIndex[0] >= 0 && !hasLightmapStage) { + ri.Printf(PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name); // Don't set this, it will just add duplicate shaders to the hash - //shader.lightmapIndex = LIGHTMAP_NONE; + // shader.lightmapIndex = LIGHTMAP_NONE; } // @@ -4170,9 +3565,7 @@ static shader_t *FinishShader( void ) { shader.sort = SS_FOG; // determain if the shader can be simplified when beeing rendered to depth - if (shader.sort == SS_OPAQUE && - shader.numDeforms == 0) - { + if (shader.sort == SS_OPAQUE && shader.numDeforms == 0) { for (stage = 0; stage < MAX_SHADER_STAGES; stage++) { shaderStage_t *pStage = &stages[stage]; @@ -4208,7 +3601,7 @@ return NULL if not found If found, it will return a valid shader ===================== */ -static const char *FindShaderInShaderText( const char *shadername ) { +static const char *FindShaderInShaderText(const char *shadername) { char *token; const char *p; @@ -4217,44 +3610,40 @@ static const char *FindShaderInShaderText( const char *shadername ) { hash = generateHashValue(shadername, MAX_SHADERTEXT_HASH); - if(shaderTextHashTable[hash]) - { - for (i = 0; shaderTextHashTable[hash][i]; i++) - { + if (shaderTextHashTable[hash]) { + for (i = 0; shaderTextHashTable[hash][i]; i++) { p = shaderTextHashTable[hash][i]; token = COM_ParseExt(&p, qtrue); - - if(!Q_stricmp(token, shadername)) + + if (!Q_stricmp(token, shadername)) return p; } } p = s_shaderText; - if ( !p ) { + if (!p) { return NULL; } // look for label - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( !Q_stricmp( token, shadername ) ) { + if (!Q_stricmp(token, shadername)) { return p; - } - else { + } else { // skip the definition - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } } return NULL; } - /* ================== R_FindShaderByName @@ -4263,12 +3652,12 @@ Will always return a valid shader, but it might be the default shader if the real one can't be found. ================== */ -shader_t *R_FindShaderByName( const char *name ) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindShaderByName(const char *name) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( (name==NULL) || (name[0] == 0) ) { + if ((name == NULL) || (name[0] == 0)) { return tr.defaultShader; } @@ -4279,7 +3668,7 @@ shader_t *R_FindShaderByName( const char *name ) { // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader @@ -4293,27 +3682,21 @@ shader_t *R_FindShaderByName( const char *name ) { return tr.defaultShader; } -static qboolean IsShader ( const shader_t *sh, const char *name, const int *lightmapIndexes, const byte *styles ) -{ - if ( Q_stricmp (sh->name, name) != 0 ) - { +static qboolean IsShader(const shader_t *sh, const char *name, const int *lightmapIndexes, const byte *styles) { + if (Q_stricmp(sh->name, name) != 0) { return qfalse; } - if ( sh->defaultShader ) - { + if (sh->defaultShader) { return qtrue; } - for ( int i = 0; i < MAXLIGHTMAPS; i++ ) - { - if ( sh->lightmapIndex[i] != lightmapIndexes[i] ) - { + for (int i = 0; i < MAXLIGHTMAPS; i++) { + if (sh->lightmapIndex[i] != lightmapIndexes[i]) { return qfalse; } - if ( sh->styles[i] != styles[i] ) - { + if (sh->styles[i] != styles[i]) { return qfalse; } } @@ -4326,15 +3709,13 @@ static qboolean IsShader ( const shader_t *sh, const char *name, const int *ligh R_FindLightmaps =============== */ -static inline const int *R_FindLightmaps(const int *lightmapIndexes) -{ +static inline const int *R_FindLightmaps(const int *lightmapIndexes) { // don't bother with vertex lighting if (*lightmapIndexes < 0) return lightmapIndexes; // do the lightmaps exist? - for (int i = 0; i < MAXLIGHTMAPS; i++) - { + for (int i = 0; i < MAXLIGHTMAPS; i++) { if (lightmapIndexes[i] >= tr.numLightmaps || tr.lightmaps[lightmapIndexes[i]] == NULL) return lightmapsVertex; } @@ -4369,24 +3750,24 @@ most world construction surfaces. =============== */ -shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) { - char strippedName[MAX_QPATH]; - int hash, flags; - const char *shaderText; - image_t *image; - shader_t *sh; - - if ( name[0] == 0 ) { +shader_t *R_FindShader(const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + int hash, flags; + const char *shaderText; + image_t *image; + shader_t *sh; + + if (name[0] == 0) { return tr.defaultShader; } // use (fullbright) vertex lighting if the bsp file doesn't have // lightmaps - if ( lightmapIndexes[0] >= 0 && lightmapIndexes[0] >= tr.numLightmaps ) { + if (lightmapIndexes[0] >= 0 && lightmapIndexes[0] >= tr.numLightmaps) { lightmapIndexes = lightmapsVertex; - } else if ( lightmapIndexes[0] < LIGHTMAP_2D ) { + } else if (lightmapIndexes[0] < LIGHTMAP_2D) { // negative lightmap indexes cause stray pointers (think tr.lightmaps[lightmapIndex]) - ri.Printf( PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndexes[0] ); + ri.Printf(PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndexes[0]); lightmapIndexes = lightmapsVertex; } @@ -4404,7 +3785,7 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if ( IsShader (sh, strippedName, lightmapIndexes, styles) ) { + if (IsShader(sh, strippedName, lightmapIndexes, styles)) { // match found return sh; } @@ -4413,17 +3794,15 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte // clear the global shader ClearGlobalShader(); Q_strncpyz(shader.name, strippedName, sizeof(shader.name)); - Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); - Com_Memcpy (shader.styles, styles, sizeof (shader.styles)); + Com_Memcpy(shader.lightmapIndex, lightmapIndexes, sizeof(shader.lightmapIndex)); + Com_Memcpy(shader.styles, styles, sizeof(shader.styles)); switch (lightmapIndexes[0]) { case LIGHTMAP_2D: - case LIGHTMAP_WHITEIMAGE: - { + case LIGHTMAP_WHITEIMAGE: { shader.isHDRLit = qfalse; break; } - default: - { + default: { shader.isHDRLit = tr.hdrLighting; break; } @@ -4432,15 +3811,15 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte // // attempt to define shader from an explicit parameter file // - shaderText = FindShaderInShaderText( strippedName ); - if ( shaderText ) { + shaderText = FindShaderInShaderText(strippedName); + if (shaderText) { // enable this when building a pak file to get a global list // of all explicit shaders - if ( r_printShaders->integer ) { - ri.Printf( PRINT_ALL, "*SHADER* %s\n", name ); + if (r_printShaders->integer) { + ri.Printf(PRINT_ALL, "*SHADER* %s\n", name); } - if ( !ParseShader( &shaderText ) ) { + if (!ParseShader(&shaderText)) { // had errors, so use default shader shader.defaultShader = qtrue; } @@ -4448,7 +3827,6 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte return sh; } - // // if not defined in the in-memory shader descriptions, // look for a single supported image file @@ -4459,21 +3837,18 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte if (shader.isHDRLit == qtrue) flags |= IMGFLAG_SRGB; - if (mipRawImage) - { + if (mipRawImage) { flags |= IMGFLAG_MIPMAP | IMGFLAG_PICMIP; if (r_genNormalMaps->integer) flags |= IMGFLAG_GENNORMALMAP; - } - else - { + } else { flags |= IMGFLAG_CLAMPTOEDGE; } - image = R_FindImageFile( name, IMGTYPE_COLORALPHA, flags ); - if ( !image ) { - ri.Printf( PRINT_DEVELOPER, "Couldn't find image file for shader %s\n", name ); + image = R_FindImageFile(name, IMGTYPE_COLORALPHA, flags); + if (!image) { + ri.Printf(PRINT_DEVELOPER, "Couldn't find image file for shader %s\n", name); shader.defaultShader = qtrue; return FinishShader(); } @@ -4481,29 +3856,27 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte // // create the default shading commands // - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image[0] = tr.whiteImage; stages[0].active = qtrue; @@ -4521,8 +3894,8 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte if (r_deluxeMapping->integer && tr.worldDeluxeMapping) stages[0].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; stages[0].active = qtrue; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image[0] = image; @@ -4534,17 +3907,16 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte return FinishShader(); } -shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) -{ - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindServerShader(const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( name[0] == 0 ) { + if (name[0] == 0) { return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); @@ -4556,7 +3928,7 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, cons // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if ( IsShader (sh, name, lightmapIndexes, styles) ) { + if (IsShader(sh, name, lightmapIndexes, styles)) { // match found return sh; } @@ -4565,34 +3937,34 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, cons // clear the global shader ClearGlobalShader(); Q_strncpyz(shader.name, strippedName, sizeof(shader.name)); - Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); - + Com_Memcpy(shader.lightmapIndex, lightmapIndexes, sizeof(shader.lightmapIndex)); + shader.defaultShader = qtrue; return FinishShader(); } qhandle_t RE_RegisterShaderFromImage(const char *name, const int *lightmapIndexes, const byte *styles, image_t *image, qboolean mipRawImage) { - int hash; - shader_t *sh; + int hash; + shader_t *sh; hash = generateHashValue(name, FILE_HASH_SIZE); // probably not necessary since this function // only gets called from tr_font.c with lightmapIndex == LIGHTMAP_2D // but better safe than sorry. - if ( lightmapIndexes[0] >= tr.numLightmaps ) { + if (lightmapIndexes[0] >= tr.numLightmaps) { lightmapIndexes = lightmapsFullBright; } // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if ( IsShader (sh, name, lightmapIndexes, styles) ) { + if (IsShader(sh, name, lightmapIndexes, styles)) { // match found return sh->index; } @@ -4601,36 +3973,34 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, const int *lightmapIndexe // clear the global shader ClearGlobalShader(); Q_strncpyz(shader.name, name, sizeof(shader.name)); - Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); + Com_Memcpy(shader.lightmapIndex, lightmapIndexes, sizeof(shader.lightmapIndex)); // // create the default shading commands // shader.isHDRLit = tr.hdrLighting; - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; shader.isHDRLit = qfalse; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image[0] = tr.whiteImage; stages[0].active = qtrue; @@ -4649,8 +4019,8 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, const int *lightmapIndexe if (r_deluxeMapping->integer && tr.worldDeluxeMapping) stages[0].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; stages[0].active = qtrue; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image[0] = image; @@ -4660,11 +4030,10 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, const int *lightmapIndexe } sh = FinishShader(); - return sh->index; + return sh->index; } - -/* +/* ==================== RE_RegisterShader @@ -4675,30 +4044,29 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndexes, const byte *styles ) { - shader_t *sh; +qhandle_t RE_RegisterShaderLightMap(const char *name, const int *lightmapIndexes, const byte *styles) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmapIndexes, styles, qtrue ); + sh = R_FindShader(name, lightmapIndexes, styles, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - -/* +/* ==================== RE_RegisterShader @@ -4709,29 +4077,28 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShader( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShader(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qtrue ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShaderNoMip @@ -4739,31 +4106,30 @@ RE_RegisterShaderNoMip For menu graphics that should never be picmiped ==================== */ -qhandle_t RE_RegisterShaderNoMip( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShaderNoMip(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qfalse ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qfalse); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } -//added for ui -rww -const char *RE_ShaderNameFromIndex(int index) -{ +// added for ui -rww +const char *RE_ShaderNameFromIndex(int index) { assert(index >= 0 && index < tr.numShaders && tr.shaders[index]); return tr.shaders[index]->name; } @@ -4776,13 +4142,13 @@ When a handle is passed in by another module, this range checks it and returns a valid (possibly default) shader_t to be used internally. ==================== */ -shader_t *R_GetShaderByHandle( qhandle_t hShader ) { - if ( hShader < 0 ) { - ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); +shader_t *R_GetShaderByHandle(qhandle_t hShader) { + if (hShader < 0) { + ri.Printf(PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } - if ( hShader >= tr.numShaders ) { - ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + if (hShader >= tr.numShaders) { + ri.Printf(PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } return tr.shaders[hShader]; @@ -4796,52 +4162,52 @@ Dump information on all valid shaders to the console A second parameter will cause it to print in sorted order =============== */ -void R_ShaderList_f (void) { - int i; - int count; - shader_t *shader; +void R_ShaderList_f(void) { + int i; + int count; + shader_t *shader; - ri.Printf (PRINT_ALL, "-----------------------\n"); + ri.Printf(PRINT_ALL, "-----------------------\n"); count = 0; - for ( i = 0 ; i < tr.numShaders ; i++ ) { - if ( ri.Cmd_Argc() > 1 ) { + for (i = 0; i < tr.numShaders; i++) { + if (ri.Cmd_Argc() > 1) { shader = tr.sortedShaders[i]; } else { shader = tr.shaders[i]; } - ri.Printf( PRINT_ALL, "%i ", shader->numUnfoggedPasses ); + ri.Printf(PRINT_ALL, "%i ", shader->numUnfoggedPasses); - if (shader->lightmapIndex[0] >= 0 ) { - ri.Printf (PRINT_ALL, "L "); + if (shader->lightmapIndex[0] >= 0) { + ri.Printf(PRINT_ALL, "L "); } else { - ri.Printf (PRINT_ALL, " "); + ri.Printf(PRINT_ALL, " "); } - if ( shader->explicitlyDefined ) { - ri.Printf( PRINT_ALL, "E " ); + if (shader->explicitlyDefined) { + ri.Printf(PRINT_ALL, "E "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->optimalStageIteratorFunc == RB_StageIteratorGeneric ) { - ri.Printf( PRINT_ALL, "gen " ); - } else if ( shader->optimalStageIteratorFunc == RB_StageIteratorSky ) { - ri.Printf( PRINT_ALL, "sky " ); + if (shader->optimalStageIteratorFunc == RB_StageIteratorGeneric) { + ri.Printf(PRINT_ALL, "gen "); + } else if (shader->optimalStageIteratorFunc == RB_StageIteratorSky) { + ri.Printf(PRINT_ALL, "sky "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->defaultShader ) { - ri.Printf (PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); + if (shader->defaultShader) { + ri.Printf(PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); } else { - ri.Printf (PRINT_ALL, ": %s\n", shader->name); + ri.Printf(PRINT_ALL, ": %s\n", shader->name); } count++; } - ri.Printf (PRINT_ALL, "%i total shaders\n", count); - ri.Printf (PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "%i total shaders\n", count); + ri.Printf(PRINT_ALL, "------------------\n"); } /* @@ -4852,9 +4218,8 @@ Finds and loads all .shader files, combining them into a single large text block that can be scanned for shader names ===================== */ -#define MAX_SHADER_FILES 4096 -static void ScanAndLoadShaderFiles( void ) -{ +#define MAX_SHADER_FILES 4096 +static void ScanAndLoadShaderFiles(void) { char **shaderFiles; char *buffers[MAX_SHADER_FILES]; const char *p; @@ -4867,72 +4232,63 @@ static void ScanAndLoadShaderFiles( void ) long sum = 0, summand; // scan for shader files - shaderFiles = ri.FS_ListFiles( "shaders", ".shader", &numShaderFiles ); + shaderFiles = ri.FS_ListFiles("shaders", ".shader", &numShaderFiles); - if ( !shaderFiles || !numShaderFiles ) - { - ri.Printf( PRINT_WARNING, "WARNING: no shader files found\n" ); + if (!shaderFiles || !numShaderFiles) { + ri.Printf(PRINT_WARNING, "WARNING: no shader files found\n"); return; } - if ( numShaderFiles > MAX_SHADER_FILES ) { + if (numShaderFiles > MAX_SHADER_FILES) { numShaderFiles = MAX_SHADER_FILES; } // load and parse shader files - for ( i = 0; i < numShaderFiles; i++ ) - { + for (i = 0; i < numShaderFiles; i++) { char filename[MAX_QPATH]; // look for a .mtr file first { char *ext; - Com_sprintf( filename, sizeof( filename ), "shaders/%s", shaderFiles[i] ); - if ( (ext = strrchr(filename, '.')) ) - { + Com_sprintf(filename, sizeof(filename), "shaders/%s", shaderFiles[i]); + if ((ext = strrchr(filename, '.'))) { strcpy(ext, ".mtr"); } - if ( ri.FS_ReadFile( filename, NULL ) <= 0 ) - { - Com_sprintf( filename, sizeof( filename ), "shaders/%s", shaderFiles[i] ); + if (ri.FS_ReadFile(filename, NULL) <= 0) { + Com_sprintf(filename, sizeof(filename), "shaders/%s", shaderFiles[i]); } } - - ri.Printf( PRINT_DEVELOPER, "...loading '%s'\n", filename ); - summand = ri.FS_ReadFile( filename, (void **)&buffers[i] ); - - if ( !buffers[i] ) - ri.Error( ERR_DROP, "Couldn't load %s", filename ); - + + ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); + summand = ri.FS_ReadFile(filename, (void **)&buffers[i]); + + if (!buffers[i]) + ri.Error(ERR_DROP, "Couldn't load %s", filename); + // Do a simple check on the shader structure in that file to make sure one bad shader file cannot fuck up all other shaders. p = buffers[i]; COM_BeginParseSession(filename); - while(1) - { + while (1) { token = COM_ParseExt(&p, qtrue); - - if(!*token) + + if (!*token) break; Q_strncpyz(shaderName, token, sizeof(shaderName)); shaderLine = COM_GetCurrentParseLine(); - if (token[0] == '#') - { - ri.Printf(PRINT_WARNING, "WARNING: Deprecated shader comment \"%s\" on line %d in file %s. Ignoring line.\n", - shaderName, shaderLine, filename); + if (token[0] == '#') { + ri.Printf(PRINT_WARNING, "WARNING: Deprecated shader comment \"%s\" on line %d in file %s. Ignoring line.\n", shaderName, shaderLine, + filename); SkipRestOfLine(&p); continue; } token = COM_ParseExt(&p, qtrue); - if(token[0] != '{' || token[1] != '\0') - { - ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing opening brace", - filename, shaderName, shaderLine); - if (token[0]) - { + if (token[0] != '{' || token[1] != '\0') { + ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing opening brace", filename, shaderName, shaderLine); + if (token[0]) { ri.Printf(PRINT_WARNING, " (found \"%s\" on line %d)", token, COM_GetCurrentParseLine()); } ri.Printf(PRINT_WARNING, ".\n"); @@ -4941,51 +4297,48 @@ static void ScanAndLoadShaderFiles( void ) break; } - if(!SkipBracedSection(&p, 1)) - { - ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing closing brace.\n", - filename, shaderName, shaderLine); + if (!SkipBracedSection(&p, 1)) { + ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing closing brace.\n", filename, shaderName, + shaderLine); ri.FS_FreeFile(buffers[i]); buffers[i] = NULL; break; } } - - + if (buffers[i]) - sum += summand; + sum += summand; } // build single large buffer - s_shaderText = (char *)ri.Hunk_Alloc( sum + numShaderFiles*2, h_low ); - s_shaderText[ 0 ] = '\0'; + s_shaderText = (char *)ri.Hunk_Alloc(sum + numShaderFiles * 2, h_low); + s_shaderText[0] = '\0'; textEnd = s_shaderText; - + // free in reverse order, so the temp files are all dumped - for ( i = numShaderFiles - 1; i >= 0 ; i-- ) - { - if ( !buffers[i] ) + for (i = numShaderFiles - 1; i >= 0; i--) { + if (!buffers[i]) continue; - strcat( textEnd, buffers[i] ); - strcat( textEnd, "\n" ); - textEnd += strlen( textEnd ); - ri.FS_FreeFile( buffers[i] ); + strcat(textEnd, buffers[i]); + strcat(textEnd, "\n"); + textEnd += strlen(textEnd); + ri.FS_FreeFile(buffers[i]); } - COM_Compress( s_shaderText ); + COM_Compress(s_shaderText); // free up memory - ri.FS_FreeFileList( shaderFiles ); + ri.FS_FreeFileList(shaderFiles); Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); size = 0; p = s_shaderText; // look for shader names - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } @@ -4997,21 +4350,21 @@ static void ScanAndLoadShaderFiles( void ) size += MAX_SHADERTEXT_HASH; - hashMem = (char *)ri.Hunk_Alloc( size * sizeof(char *), h_low ); + hashMem = (char *)ri.Hunk_Alloc(size * sizeof(char *), h_low); for (i = 0; i < MAX_SHADERTEXT_HASH; i++) { - shaderTextHashTable[i] = (char **) hashMem; - hashMem = ((char *) hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *)); + shaderTextHashTable[i] = (char **)hashMem; + hashMem = ((char *)hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *)); } Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); p = s_shaderText; // look for shader names - while ( 1 ) { + while (1) { oldp = (char *)p; - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } @@ -5022,17 +4375,11 @@ static void ScanAndLoadShaderFiles( void ) } return; - } -shader_t *R_CreateShaderFromTextureBundle( - const char *name, - const textureBundle_t *bundle, - uint32_t stateBits) -{ +shader_t *R_CreateShaderFromTextureBundle(const char *name, const textureBundle_t *bundle, uint32_t stateBits) { shader_t *result = R_FindShaderByName(name); - if ( result == tr.defaultShader ) - { + if (result == tr.defaultShader) { Com_Memset(&shader, 0, sizeof(shader)); Com_Memset(&stages, 0, sizeof(stages)); @@ -5051,17 +4398,17 @@ shader_t *R_CreateShaderFromTextureBundle( CreateInternalShaders ==================== */ -static void CreateInternalShaders( void ) { +static void CreateInternalShaders(void) { tr.numShaders = 0; // init the default shader - Com_Memset( &shader, 0, sizeof( shader ) ); - Com_Memset( &stages, 0, sizeof( stages ) ); + Com_Memset(&shader, 0, sizeof(shader)); + Com_Memset(&stages, 0, sizeof(stages)); - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "", sizeof(shader.name)); - Com_Memcpy (shader.lightmapIndex, lightmapsNone, sizeof (shader.lightmapIndex)); - for ( int i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + Com_Memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); + for (int i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; } @@ -5071,12 +4418,12 @@ static void CreateInternalShaders( void ) { tr.defaultShader = FinishShader(); // shadow shader is just a marker - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); - shader.sort = SS_BANNER; //SS_STENCIL_SHADOW; + Q_strncpyz(shader.name, "", sizeof(shader.name)); + shader.sort = SS_BANNER; // SS_STENCIL_SHADOW; tr.shadowShader = FinishShader(); // distortion shader is just a marker - Q_strncpyz( shader.name, "internal_distortion", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "internal_distortion", sizeof(shader.name)); shader.sort = SS_BLEND0; shader.defaultShader = qfalse; tr.distortionShader = FinishShader(); @@ -5089,17 +4436,16 @@ static void CreateInternalShaders( void ) { tr.weatherInternalShader = FinishShader(); } -static void CreateExternalShaders( void ) { - tr.projectionShadowShader = R_FindShader( "projectionShadow", lightmapsNone, stylesDefault, qtrue ); - tr.flareShader = R_FindShader( "gfx/misc/flare", lightmapsNone, stylesDefault, qtrue ); +static void CreateExternalShaders(void) { + tr.projectionShadowShader = R_FindShader("projectionShadow", lightmapsNone, stylesDefault, qtrue); + tr.flareShader = R_FindShader("gfx/misc/flare", lightmapsNone, stylesDefault, qtrue); - tr.sunShader = R_FindShader( "sun", lightmapsNone, stylesDefault, qtrue ); + tr.sunShader = R_FindShader("sun", lightmapsNone, stylesDefault, qtrue); - tr.sunFlareShader = R_FindShader( "gfx/2d/sunflare", lightmapsNone, stylesDefault, qtrue); + tr.sunFlareShader = R_FindShader("gfx/2d/sunflare", lightmapsNone, stylesDefault, qtrue); // HACK: if sunflare is missing, make one using the flare image or dlight image - if (tr.sunFlareShader->defaultShader) - { + if (tr.sunFlareShader->defaultShader) { image_t *image; if (!tr.flareShader->defaultShader && tr.flareShader->stages[0] && tr.flareShader->stages[0]->bundle[0].image[0]) @@ -5107,18 +4453,17 @@ static void CreateExternalShaders( void ) { else image = tr.dlightImage; - Com_Memset( &shader, 0, sizeof( shader ) ); - Com_Memset( &stages, 0, sizeof( stages ) ); + Com_Memset(&shader, 0, sizeof(shader)); + Com_Memset(&stages, 0, sizeof(stages)); - Q_strncpyz( shader.name, "gfx/2d/sunflare", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "gfx/2d/sunflare", sizeof(shader.name)); - Com_Memcpy (shader.lightmapIndex, lightmapsNone, sizeof (shader.lightmapIndex)); + Com_Memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); stages[0].bundle[0].image[0] = image; stages[0].active = qtrue; stages[0].stateBits = GLS_DEFAULT; tr.sunFlareShader = FinishShader(); } - } /* @@ -5126,13 +4471,12 @@ static void CreateExternalShaders( void ) { R_InitShaders ================== */ -void R_InitShaders( qboolean server ) { - ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); +void R_InitShaders(qboolean server) { + ri.Printf(PRINT_ALL, "Initializing Shaders\n"); Com_Memset(hashTable, 0, sizeof(hashTable)); - if ( !server ) - { + if (!server) { CreateInternalShaders(); ScanAndLoadShaderFiles(); diff --git a/codemp/rd-rend2/tr_shadows.cpp b/codemp/rd-rend2/tr_shadows.cpp index eb0b472dfc..b4b1e47501 100644 --- a/codemp/rd-rend2/tr_shadows.cpp +++ b/codemp/rd-rend2/tr_shadows.cpp @@ -73,24 +73,23 @@ void RB_ShadowFinish(void) { qglStencilFunc(GL_ALWAYS, 0, 0xff); } - /* ================= RB_ProjectionShadowDeform ================= */ -void RB_ProjectionShadowDeform( void ) { - float *xyz; - int i; - float h; - vec3_t ground; - vec3_t light; - float groundDist; - float d; - vec3_t lightDir; - - xyz = ( float * ) tess.xyz; +void RB_ProjectionShadowDeform(void) { + float *xyz; + int i; + float h; + vec3_t ground; + vec3_t light; + float groundDist; + float d; + vec3_t lightDir; + + xyz = (float *)tess.xyz; ground[0] = backEnd.ori.axis[0][2]; ground[1] = backEnd.ori.axis[1][2]; @@ -98,12 +97,12 @@ void RB_ProjectionShadowDeform( void ) { groundDist = backEnd.ori.origin[2] - backEnd.currentEntity->e.shadowPlane; - VectorCopy( backEnd.currentEntity->modelLightDir, lightDir ); - d = DotProduct( lightDir, ground ); + VectorCopy(backEnd.currentEntity->modelLightDir, lightDir); + d = DotProduct(lightDir, ground); // don't let the shadows get too long or go negative - if ( d < 0.5 ) { - VectorMA( lightDir, (0.5 - d), ground, lightDir ); - d = DotProduct( lightDir, ground ); + if (d < 0.5) { + VectorMA(lightDir, (0.5 - d), ground, lightDir); + d = DotProduct(lightDir, ground); } d = 1.0 / d; @@ -111,8 +110,8 @@ void RB_ProjectionShadowDeform( void ) { light[1] = lightDir[1] * d; light[2] = lightDir[2] * d; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - h = DotProduct( xyz, ground ) + groundDist; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + h = DotProduct(xyz, ground) + groundDist; xyz[0] -= light[0] * h; xyz[1] -= light[1] * h; diff --git a/codemp/rd-rend2/tr_skin.cpp b/codemp/rd-rend2/tr_skin.cpp index d14f211b6a..5049ac216c 100644 --- a/codemp/rd-rend2/tr_skin.cpp +++ b/codemp/rd-rend2/tr_skin.cpp @@ -8,8 +8,8 @@ SKINS ============================================================================ */ -static char *CommaParse( char **data_p ); -//can't be dec'd here since we need it for non-dedicated builds now as well. +static char *CommaParse(char **data_p); +// can't be dec'd here since we need it for non-dedicated builds now as well. /* =============== @@ -20,9 +20,8 @@ RE_RegisterSkin bool gServerSkinHack = false; - -shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) ; -static char *CommaParse( char **data_p ); +shader_t *R_FindServerShader(const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage); +static char *CommaParse(char **data_p); /* =============== RE_SplitSkins @@ -31,207 +30,192 @@ return= true if three part skins found output= qualified names to three skins if return is true, undefined if false =============== */ -bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) -{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; - if (strchr(INname, '|')) - { +bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) { // INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; + if (strchr(INname, '|')) { char name[MAX_QPATH]; strcpy(name, INname); char *p = strchr(name, '|'); - *p=0; + *p = 0; p++; - //fill in the base path - strcpy (skinhead, name); - strcpy (skintorso, name); - strcpy (skinlower, name); - - //now get the the individual files - - //advance to second - char *p2 = strchr(p, '|'); + // fill in the base path + strcpy(skinhead, name); + strcpy(skintorso, name); + strcpy(skinlower, name); + + // now get the the individual files + + // advance to second + char *p2 = strchr(p, '|'); assert(p2); - if (!p2) - { + if (!p2) { return false; } - *p2=0; + *p2 = 0; p2++; - strcat (skinhead, p); - strcat (skinhead, ".skin"); - + strcat(skinhead, p); + strcat(skinhead, ".skin"); - //advance to third + // advance to third p = strchr(p2, '|'); assert(p); - if (!p) - { + if (!p) { return false; } - *p=0; + *p = 0; p++; - strcat (skintorso,p2); - strcat (skintorso, ".skin"); + strcat(skintorso, p2); + strcat(skintorso, ".skin"); + + strcat(skinlower, p); + strcat(skinlower, ".skin"); - strcat (skinlower,p); - strcat (skinlower, ".skin"); - return true; } return false; } // given a name, go get the skin we want and return -qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin) -{ - skin_t *skin; - skinSurface_t *surf; - char *text, *text_p; - char *token; - char surfName[MAX_QPATH]; +qhandle_t RE_RegisterIndividualSkin(const char *name, qhandle_t hSkin) { + skin_t *skin; + skinSurface_t *surf; + char *text, *text_p; + char *token; + char surfName[MAX_QPATH]; // load and parse the skin file - ri.FS_ReadFile( name, (void **)&text ); - if ( !text ) { + ri.FS_ReadFile(name, (void **)&text); + if (!text) { #ifndef FINAL_BUILD - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name ); + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name); #endif return 0; } - assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append + assert(tr.skins[hSkin]); // should already be setup, but might be an 3part append skin = tr.skins[hSkin]; text_p = text; - while ( text_p && *text_p ) { + while (text_p && *text_p) { // get surface name - token = CommaParse( &text_p ); - Q_strncpyz( surfName, token, sizeof( surfName ) ); + token = CommaParse(&text_p); + Q_strncpyz(surfName, token, sizeof(surfName)); - if ( !token[0] ) { + if (!token[0]) { break; } // lowercase the surface name so skin compares are faster - Q_strlwr( surfName ); + Q_strlwr(surfName); - if ( *text_p == ',' ) { + if (*text_p == ',') { text_p++; } - if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one... + if (!strncmp(token, "tag_", 4)) { // these aren't in there, but just in case you load an id style one... continue; } - + // parse the shader name - token = CommaParse( &text_p ); + token = CommaParse(&text_p); - if ( !strcmp( &surfName[strlen(surfName)-4], "_off") ) - { - if ( !strcmp( token ,"*off" ) ) - { - continue; //don't need these double offs + if (!strcmp(&surfName[strlen(surfName) - 4], "_off")) { + if (!strcmp(token, "*off")) { + continue; // don't need these double offs } - surfName[strlen(surfName)-4] = 0; //remove the "_off" + surfName[strlen(surfName) - 4] = 0; // remove the "_off" } - if ( (unsigned)skin->numSurfaces >= ARRAY_LEN( skin->surfaces ) ) - { - assert( ARRAY_LEN( skin->surfaces ) > (unsigned)skin->numSurfaces ); - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) more than %d surfaces!\n", name, ARRAY_LEN( skin->surfaces ) ); + if ((unsigned)skin->numSurfaces >= ARRAY_LEN(skin->surfaces)) { + assert(ARRAY_LEN(skin->surfaces) > (unsigned)skin->numSurfaces); + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) more than %d surfaces!\n", name, ARRAY_LEN(skin->surfaces)); break; } - surf = (skinSurface_t *) Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low ); + surf = (skinSurface_t *)Hunk_Alloc(sizeof(*skin->surfaces[0]), h_low); skin->surfaces[skin->numSurfaces] = (_skinSurface_t *)surf; - Q_strncpyz( surf->name, surfName, sizeof( surf->name ) ); + Q_strncpyz(surf->name, surfName, sizeof(surf->name)); - if (gServerSkinHack) surf->shader = R_FindServerShader( token, lightmapsNone, stylesDefault, qtrue ); - else surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue ); + if (gServerSkinHack) + surf->shader = R_FindServerShader(token, lightmapsNone, stylesDefault, qtrue); + else + surf->shader = R_FindShader(token, lightmapsNone, stylesDefault, qtrue); skin->numSurfaces++; } - ri.FS_FreeFile( text ); - + ri.FS_FreeFile(text); // never let a skin have 0 shaders - if ( skin->numSurfaces == 0 ) { - return 0; // use default skin + if (skin->numSurfaces == 0) { + return 0; // use default skin } return hSkin; } -qhandle_t RE_RegisterSkin( const char *name ) { - qhandle_t hSkin; - skin_t *skin; +qhandle_t RE_RegisterSkin(const char *name) { + qhandle_t hSkin; + skin_t *skin; - if ( !name || !name[0] ) { - Com_Printf( "Empty name passed to RE_RegisterSkin\n" ); + if (!name || !name[0]) { + Com_Printf("Empty name passed to RE_RegisterSkin\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - Com_Printf( "Skin name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + Com_Printf("Skin name exceeds MAX_QPATH\n"); return 0; } // see if the skin is already loaded - for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) { + for (hSkin = 1; hSkin < tr.numSkins; hSkin++) { skin = tr.skins[hSkin]; - if ( !Q_stricmp( skin->name, name ) ) { - if( skin->numSurfaces == 0 ) { - return 0; // default skin + if (!Q_stricmp(skin->name, name)) { + if (skin->numSurfaces == 0) { + return 0; // default skin } return hSkin; } } // allocate a new skin - if ( tr.numSkins == MAX_SKINS ) { - Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); + if (tr.numSkins == MAX_SKINS) { + Com_Printf("WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name); return 0; } tr.numSkins++; - skin = (struct skin_s *)Hunk_Alloc( sizeof( skin_t ), h_low ); + skin = (struct skin_s *)Hunk_Alloc(sizeof(skin_t), h_low); tr.skins[hSkin] = skin; - Q_strncpyz( skin->name, name, sizeof( skin->name ) ); + Q_strncpyz(skin->name, name, sizeof(skin->name)); skin->numSurfaces = 0; // make sure the render thread is stopped R_IssuePendingRenderCommands(); // If not a .skin file, load as a single shader - if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) { -/* skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); - skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); - return hSkin; -*/ + if (strcmp(name + strlen(name) - 5, ".skin")) { + /* skin->numSurfaces = 1; + skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); + skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + return hSkin; + */ } - char skinhead[MAX_QPATH]={0}; - char skintorso[MAX_QPATH]={0}; - char skinlower[MAX_QPATH]={0}; - if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) ) - {//three part + char skinhead[MAX_QPATH] = {0}; + char skintorso[MAX_QPATH] = {0}; + char skinlower[MAX_QPATH] = {0}; + if (RE_SplitSkins(name, (char *)&skinhead, (char *)&skintorso, (char *)&skinlower)) { // three part hSkin = RE_RegisterIndividualSkin(skinhead, hSkin); - if (hSkin) - { + if (hSkin) { hSkin = RE_RegisterIndividualSkin(skintorso, hSkin); - if (hSkin) - { + if (hSkin) { hSkin = RE_RegisterIndividualSkin(skinlower, hSkin); } } - } - else - {//single skin + } else { // single skin hSkin = RE_RegisterIndividualSkin(name, hSkin); } - return(hSkin); + return (hSkin); } - - /* ================== CommaParse @@ -240,76 +224,65 @@ This is unfortunate, but the skin files aren't compatible with our normal parsing rules. ================== */ -static char *CommaParse( char **data_p ) { +static char *CommaParse(char **data_p) { int c = 0, len; char *data; - static char com_token[MAX_TOKEN_CHARS]; + static char com_token[MAX_TOKEN_CHARS]; data = *data_p; len = 0; com_token[0] = 0; // make sure incoming data is valid - if ( !data ) { + if (!data) { *data_p = NULL; return com_token; } - while ( 1 ) { + while (1) { // skip whitespace - while( (c = *data) <= ' ') { - if( !c ) { + while ((c = *data) <= ' ') { + if (!c) { break; } data++; } - c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { while (*data && *data != '\n') data++; } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { + else if (c == '/' && data[1] == '*') { + while (*data && (*data != '*' || data[1] != '/')) { data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } - if ( c == 0 ) { + if (c == 0) { return ""; } // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if (len < MAX_TOKEN_CHARS) - { + if (len < MAX_TOKEN_CHARS) { com_token[len] = c; len++; } @@ -317,25 +290,22 @@ static char *CommaParse( char **data_p ) { } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS) - { + do { + if (len < MAX_TOKEN_CHARS) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32 && c != ',' ); + } while (c > 32 && c != ','); - if (len == MAX_TOKEN_CHARS) - { -// Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS); + if (len == MAX_TOKEN_CHARS) { + // Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS); len = 0; } com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -346,13 +316,11 @@ RE_RegisterServerSkin Mangled version of the above function to load .skin files on the server. =============== */ -qhandle_t RE_RegisterServerSkin( const char *name ) { +qhandle_t RE_RegisterServerSkin(const char *name) { qhandle_t r; - if (ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && - ShaderHashTableExists()) - { //If the client is running then we can go straight into the normal registerskin func + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // If the client is running then we can go straight into the normal registerskin func return RE_RegisterSkin(name); } @@ -368,16 +336,16 @@ qhandle_t RE_RegisterServerSkin( const char *name ) { R_InitSkins =============== */ -void R_InitSkins( void ) { - skin_t *skin; +void R_InitSkins(void) { + skin_t *skin; tr.numSkins = 1; // make the default skin have all default shaders - skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc( sizeof( skin_t ), h_low ); - Q_strncpyz( skin->name, "", sizeof( skin->name ) ); + skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc(sizeof(skin_t), h_low); + Q_strncpyz(skin->name, "", sizeof(skin->name)); skin->numSurfaces = 1; - skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc( sizeof( skinSurface_t ), h_low ); + skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc(sizeof(skinSurface_t), h_low); skin->surfaces[0]->shader = tr.defaultShader; } @@ -386,11 +354,11 @@ void R_InitSkins( void ) { R_GetSkinByHandle =============== */ -skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { - if ( hSkin < 1 || hSkin >= tr.numSkins ) { +skin_t *R_GetSkinByHandle(qhandle_t hSkin) { + if (hSkin < 1 || hSkin >= tr.numSkins) { return tr.skins[0]; } - return tr.skins[ hSkin ]; + return tr.skins[hSkin]; } /* @@ -398,20 +366,19 @@ skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { R_SkinList_f =============== */ -void R_SkinList_f( void ) { - int i, j; - skin_t *skin; +void R_SkinList_f(void) { + int i, j; + skin_t *skin; - Com_Printf ( "------------------\n"); + Com_Printf("------------------\n"); - for ( i = 0 ; i < tr.numSkins ; i++ ) { + for (i = 0; i < tr.numSkins; i++) { skin = tr.skins[i]; - Com_Printf ("%3i:%s\n", i, skin->name ); - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { - Com_Printf (" %s = %s\n", - skin->surfaces[j]->name, ((shader_t* )skin->surfaces[j]->shader)->name ); + Com_Printf("%3i:%s\n", i, skin->name); + for (j = 0; j < skin->numSurfaces; j++) { + Com_Printf(" %s = %s\n", skin->surfaces[j]->name, ((shader_t *)skin->surfaces[j]->shader)->name); } } - Com_Printf ( "------------------\n"); + Com_Printf("------------------\n"); } diff --git a/codemp/rd-rend2/tr_sky.cpp b/codemp/rd-rend2/tr_sky.cpp index 98a60c6058..3d2d9db3a6 100644 --- a/codemp/rd-rend2/tr_sky.cpp +++ b/codemp/rd-rend2/tr_sky.cpp @@ -22,11 +22,11 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // tr_sky.c #include "tr_local.h" -#define SKY_SUBDIVISIONS 8 -#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS/2) +#define SKY_SUBDIVISIONS 8 +#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS / 2) -static float s_cloudTexCoords[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; -static float s_cloudTexP[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; +static float s_cloudTexCoords[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; +static float s_cloudTexP[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; /* =================================================================================== @@ -36,72 +36,56 @@ POLYGON TO BOX SIDE PROJECTION =================================================================================== */ -static vec3_t sky_clip[6] = -{ - {1,1,0}, - {1,-1,0}, - {0,-1,1}, - {0,1,1}, - {1,0,1}, - {-1,0,1} -}; +static vec3_t sky_clip[6] = {{1, 1, 0}, {1, -1, 0}, {0, -1, 1}, {0, 1, 1}, {1, 0, 1}, {-1, 0, 1}}; -static float sky_mins[2][6], sky_maxs[2][6]; -static float sky_min, sky_max; +static float sky_mins[2][6], sky_maxs[2][6]; +static float sky_min, sky_max; /* ================ AddSkyPolygon ================ */ -static void AddSkyPolygon (int nump, vec3_t vecs) -{ - int i,j; - vec3_t v, av; - float s, t, dv; - int axis; - float *vp; +static void AddSkyPolygon(int nump, vec3_t vecs) { + int i, j; + vec3_t v, av; + float s, t, dv; + int axis; + float *vp; // s = [0]/[2], t = [1]/[2] - static int vec_to_st[6][3] = - { - {-2,3,1}, - {2,3,-1}, + static int vec_to_st[6][3] = { + {-2, 3, 1}, + {2, 3, -1}, - {1,3,2}, - {-1,3,-2}, + {1, 3, 2}, + {-1, 3, -2}, - {-2,-1,3}, - {-2,1,-3} + {-2, -1, 3}, + {-2, 1, -3} - // {-1,2,3}, - // {1,2,-3} + // {-1,2,3}, + // {1,2,-3} }; // decide which face it maps to - VectorCopy (vec3_origin, v); - for (i=0, vp=vecs ; i av[1] && av[0] > av[2]) - { + if (av[0] > av[1] && av[0] > av[2]) { if (v[0] < 0) axis = 1; else axis = 0; - } - else if (av[1] > av[2] && av[1] > av[0]) - { + } else if (av[1] > av[2] && av[1] > av[0]) { if (v[1] < 0) axis = 3; else axis = 2; - } - else - { + } else { if (v[2] < 0) axis = 5; else @@ -109,25 +93,24 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } // project new texture coords - for (i=0 ; i 0) dv = vecs[j - 1]; else dv = -vecs[-j - 1]; if (dv < 0.001) - continue; // don't divide by zero + continue; // don't divide by zero j = vec_to_st[axis][0]; if (j < 0) - s = -vecs[-j -1] / dv; + s = -vecs[-j - 1] / dv; else - s = vecs[j-1] / dv; + s = vecs[j - 1] / dv; j = vec_to_st[axis][1]; if (j < 0) - t = -vecs[-j -1] / dv; + t = -vecs[-j - 1] / dv; else - t = vecs[j-1] / dv; + t = vecs[j - 1] / dv; if (s < sky_mins[0][axis]) sky_mins[0][axis] = s; @@ -140,92 +123,81 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } } -#define ON_EPSILON 0.1f // point on plane side epsilon -#define MAX_CLIP_VERTS 64 +#define ON_EPSILON 0.1f // point on plane side epsilon +#define MAX_CLIP_VERTS 64 /* ================ ClipSkyPolygon ================ */ -static void ClipSkyPolygon (int nump, vec3_t vecs, int stage) -{ - float *norm; - float *v; - qboolean front, back; - float d, e; - float dists[MAX_CLIP_VERTS]; - int sides[MAX_CLIP_VERTS]; - vec3_t newv[2][MAX_CLIP_VERTS]; - int newc[2]; - int i, j; - - if (nump > MAX_CLIP_VERTS-2) - ri.Error (ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); - if (stage == 6) - { // fully clipped, so draw it - AddSkyPolygon (nump, vecs); +static void ClipSkyPolygon(int nump, vec3_t vecs, int stage) { + float *norm; + float *v; + qboolean front, back; + float d, e; + float dists[MAX_CLIP_VERTS]; + int sides[MAX_CLIP_VERTS]; + vec3_t newv[2][MAX_CLIP_VERTS]; + int newc[2]; + int i, j; + + if (nump > MAX_CLIP_VERTS - 2) + ri.Error(ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); + if (stage == 6) { // fully clipped, so draw it + AddSkyPolygon(nump, vecs); return; } front = back = qfalse; norm = sky_clip[stage]; - for (i=0, v = vecs ; i ON_EPSILON) - { + for (i = 0, v = vecs; i < nump; i++, v += 3) { + d = DotProduct(v, norm); + if (d > ON_EPSILON) { front = qtrue; sides[i] = SIDE_FRONT; - } - else if (d < -ON_EPSILON) - { + } else if (d < -ON_EPSILON) { back = qtrue; sides[i] = SIDE_BACK; - } - else + } else sides[i] = SIDE_ON; dists[i] = d; } - if (!front || !back) - { // not clipped - ClipSkyPolygon (nump, vecs, stage+1); + if (!front || !back) { // not clipped + ClipSkyPolygon(nump, vecs, stage + 1); return; } // clip it sides[i] = sides[0]; dists[i] = dists[0]; - VectorCopy (vecs, (vecs+(i*3)) ); + VectorCopy(vecs, (vecs + (i * 3))); newc[0] = newc[1] = 0; - for (i=0, v = vecs ; inumIndexes; i += 3 ) - { - for (j = 0 ; j < 3 ; j++) - { - VectorSubtract( input->xyz[input->indexes[i+j]], - backEnd.viewParms.ori.origin, - p[j] ); + for (i = 0; i < input->numIndexes; i += 3) { + for (j = 0; j < 3; j++) { + VectorSubtract(input->xyz[input->indexes[i + j]], backEnd.viewParms.ori.origin, p[j]); } - ClipSkyPolygon( 3, p[0], 0 ); + ClipSkyPolygon(3, p[0], 0); } } @@ -289,79 +256,62 @@ CLOUD VERTEX GENERATION ** ** Parms: s, t range from -1 to 1 */ -static void MakeSkyVec( float s, float t, int axis, float outSt[2], vec3_t outXYZ ) -{ +static void MakeSkyVec(float s, float t, int axis, float outSt[2], vec3_t outXYZ) { // 1 = s, 2 = t, 3 = 2048 - static int st_to_vec[6][3] = - { - {3,-1,2}, - {-3,1,2}, + static int st_to_vec[6][3] = { + {3, -1, 2}, {-3, 1, 2}, - {1,3,2}, - {-1,-3,2}, + {1, 3, 2}, {-1, -3, 2}, - {-2,-1,3}, // 0 degrees yaw, look straight up - {2,-1,-3} // look straight down + {-2, -1, 3}, // 0 degrees yaw, look straight up + {2, -1, -3} // look straight down }; - vec3_t b; - int j, k; - float boxSize; + vec3_t b; + int j, k; + float boxSize; - boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) - b[0] = s*boxSize; - b[1] = t*boxSize; + boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + b[0] = s * boxSize; + b[1] = t * boxSize; b[2] = boxSize; - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { k = st_to_vec[axis][j]; - if (k < 0) - { + if (k < 0) { outXYZ[j] = -b[-k - 1]; - } - else - { + } else { outXYZ[j] = b[k - 1]; } } // avoid bilerp seam - s = (s+1)*0.5; - t = (t+1)*0.5; - if (s < sky_min) - { + s = (s + 1) * 0.5; + t = (t + 1) * 0.5; + if (s < sky_min) { s = sky_min; - } - else if (s > sky_max) - { + } else if (s > sky_max) { s = sky_max; } - if (t < sky_min) - { + if (t < sky_min) { t = sky_min; - } - else if (t > sky_max) - { + } else if (t > sky_max) { t = sky_max; } t = 1.0 - t; - - if ( outSt ) - { + if (outSt) { outSt[0] = s; outSt[1] = t; } } -static vec3_t s_skyPoints[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; -static float s_skyTexCoords[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; +static vec3_t s_skyPoints[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; +static float s_skyTexCoords[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; -static void DrawSkySide( struct image_s *image, const int mins[2], const int maxs[2] ) -{ +static void DrawSkySide(struct image_s *image, const int mins[2], const int maxs[2]) { const uint32_t SKY_BOX_VERTEX_ATTRIBUTES = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_COLOR | ATTR_NORMAL; int s, t; int firstVertex = tess.numVertexes; @@ -369,13 +319,9 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max int maxIndex = tess.maxIndex; tess.firstIndex = tess.numIndexes; - - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; - t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; - s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { + + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t <= maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { tess.xyz[tess.numVertexes][0] = s_skyPoints[t][s][0]; tess.xyz[tess.numVertexes][1] = s_skyPoints[t][s][1]; tess.xyz[tess.numVertexes][2] = s_skyPoints[t][s][2]; @@ -389,8 +335,7 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max tess.numVertexes++; - if(tess.numVertexes >= SHADER_MAX_VERTEXES) - { + if (tess.numVertexes >= SHADER_MAX_VERTEXES) { ri.Error(ERR_DROP, "SHADER_MAX_VERTEXES hit in DrawSkySideVBO()"); } } @@ -399,21 +344,18 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max float ssize = maxs[0] - mins[0]; float tsize = maxs[1] - mins[1]; float ssizePlusOne = ssize + 1.0f; - for ( t = 0; t < tsize; t++ ) - { - for ( s = 0; s < ssize; s++ ) - { - if ((tess.numIndexes + 6) >= SHADER_MAX_INDEXES) - { + for (t = 0; t < tsize; t++) { + for (s = 0; s < ssize; s++) { + if ((tess.numIndexes + 6) >= SHADER_MAX_INDEXES) { ri.Error(ERR_DROP, "SHADER_MAX_INDEXES hit in DrawSkySideVBO()"); } - tess.indexes[tess.numIndexes++] = s + t * ssizePlusOne + firstVertex; - tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; - tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = s + t * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; - tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; - tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; tess.indexes[tess.numIndexes++] = (s + 1) + (t + 1) * ssizePlusOne + firstVertex; } } @@ -426,11 +368,9 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max VertexArraysProperties vertexArrays; CalculateVertexArraysProperties(SKY_BOX_VERTEX_ATTRIBUTES, &vertexArrays); - for ( int i = 0; i < vertexArrays.numVertexArrays; i++ ) - { + for (int i = 0; i < vertexArrays.numVertexArrays; i++) { int attributeIndex = vertexArrays.enabledAttributes[i]; - vertexArrays.offsets[attributeIndex] += - backEndData->currentFrame->dynamicVboCommitOffset; + vertexArrays.offsets[attributeIndex] += backEndData->currentFrame->dynamicVboCommitOffset; } vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; @@ -438,27 +378,21 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max UniformDataWriter uniformDataWriter; SamplerBindingsWriter samplerBindingsWriter; - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; shaderProgram_t *sp = &tr.lightallShader[0]; float colorScale = backEnd.refdef.colorScale; uniformDataWriter.Start(sp); - uniformDataWriter.SetUniformVec4( - UNIFORM_BASECOLOR, colorScale, colorScale, colorScale, 1.0f); - uniformDataWriter.SetUniformVec4( - UNIFORM_VERTCOLOR, 0.0f, 0.0f, 0.0f, 0.0f); - uniformDataWriter.SetUniformVec4( - UNIFORM_DIFFUSETEXMATRIX, 1.0f, 0.0f, 0.0f, 1.0f); - uniformDataWriter.SetUniformVec4( - UNIFORM_DIFFUSETEXOFFTURB, 0.0f, 0.0f, 0.0f, 0.0f); + uniformDataWriter.SetUniformVec4(UNIFORM_BASECOLOR, colorScale, colorScale, colorScale, 1.0f); + uniformDataWriter.SetUniformVec4(UNIFORM_VERTCOLOR, 0.0f, 0.0f, 0.0f, 0.0f); + uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXMATRIX, 1.0f, 0.0f, 0.0f, 1.0f); + uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXOFFTURB, 0.0f, 0.0f, 0.0f, 0.0f); samplerBindingsWriter.AddStaticImage(image, TB_DIFFUSEMAP); const GLuint currentFrameUbo = backEndData->currentFrame->ubo; - const UniformBlockBinding uniformBlockBindings[] = { - { currentFrameUbo, tr.skyEntityUboOffset, UNIFORM_BLOCK_ENTITY }, - { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA } - }; + const UniformBlockBinding uniformBlockBindings[] = {{currentFrameUbo, tr.skyEntityUboOffset, UNIFORM_BLOCK_ENTITY}, + {currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA}}; DrawItem item = {}; item.renderState.cullType = CT_TWO_SIDED; @@ -467,13 +401,10 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max item.ibo = backEndData->currentFrame->dynamicIbo; item.uniformData = uniformDataWriter.Finish(frameAllocator); - item.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); - DrawItemSetVertexAttributes( - item, attribs, vertexArrays.numVertexArrays, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, attribs, vertexArrays.numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, &tess); item.draw.params.indexed.numIndices -= tess.firstIndex; @@ -482,7 +413,7 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max RB_AddDrawItem(backEndData->currentPass, key, item); RB_CommitInternalBufferData(); - + tess.useInternalVBO = qfalse; tess.numIndexes = tess.firstIndex; tess.numVertexes = firstVertex; @@ -491,28 +422,24 @@ static void DrawSkySide( struct image_s *image, const int mins[2], const int max tess.maxIndex = maxIndex; } -static void DrawSkyBox( shader_t *shader ) -{ - int i; +static void DrawSkyBox(shader_t *shader) { + int i; sky_min = 0; sky_max = 1; - Com_Memset( s_skyTexCoords, 0, sizeof( s_skyTexCoords ) ); + Com_Memset(s_skyTexCoords, 0, sizeof(s_skyTexCoords)); - for (i=0 ; i<6 ; i++) - { + for (i = 0; i < 6; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } @@ -521,50 +448,39 @@ static void DrawSkyBox( shader_t *shader ) sky_maxs_subd[0] = sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS; sky_maxs_subd[1] = sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; - t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; - s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - s_skyTexCoords[t][s], - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, + s_skyTexCoords[t][s], s_skyPoints[t][s]); } } - DrawSkySide( shader->sky.outerbox[i], - sky_mins_subd, - sky_maxs_subd ); + DrawSkySide(shader->sky.outerbox[i], sky_mins_subd, sky_maxs_subd); } - } -static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean addIndexes ) -{ +static void FillCloudySkySide(const int mins[2], const int maxs[2], qboolean addIndexes) { int s, t; int vertexStart = tess.numVertexes; int tHeight, sWidth; @@ -572,67 +488,57 @@ static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean ad tHeight = maxs[1] - mins[1] + 1; sWidth = maxs[0] - mins[0] + 1; - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - VectorAdd( s_skyPoints[t][s], backEnd.viewParms.ori.origin, - tess.xyz[tess.numVertexes] ); + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t <= maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { + VectorAdd(s_skyPoints[t][s], backEnd.viewParms.ori.origin, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0]; tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1]; tess.numVertexes++; - if ( tess.numVertexes >= SHADER_MAX_VERTEXES ) - { - ri.Error( ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()" ); + if (tess.numVertexes >= SHADER_MAX_VERTEXES) { + ri.Error(ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()"); } } } // only add indexes for one pass, otherwise it would draw multiple times for each pass - if ( addIndexes ) { - for ( t = 0; t < tHeight-1; t++ ) - { - for ( s = 0; s < sWidth-1; s++ ) - { - tess.indexes[tess.numIndexes] = vertexStart + s + t * ( sWidth ); + if (addIndexes) { + for (t = 0; t < tHeight - 1; t++) { + for (s = 0; s < sWidth - 1; s++) { + tess.indexes[tess.numIndexes] = vertexStart + s + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; } } } } -static void FillCloudBox( const shader_t *shader, int stage ) -{ +static void FillCloudBox(const shader_t *shader, int stage) { int i; // don't want to draw the bottom - for ( i =0; i < 5; i++ ) - { + for (i = 0; i < 5; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; const float MIN_T = -HALF_SKY_SUBDIVISIONS; - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } @@ -641,38 +547,31 @@ static void FillCloudBox( const shader_t *shader, int stage ) sky_maxs_subd[0] = Q_ftol(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS); sky_maxs_subd[1] = Q_ftol(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS); - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < MIN_T ) + if (sky_mins_subd[1] < MIN_T) sky_mins_subd[1] = MIN_T; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < MIN_T ) + if (sky_maxs_subd[1] < MIN_T) sky_maxs_subd[1] = MIN_T; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; - t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; - s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + s_skyPoints[t][s]); s_skyTexCoords[t][s][0] = s_cloudTexCoords[i][t][s][0]; s_skyTexCoords[t][s][1] = s_cloudTexCoords[i][t][s][1]; @@ -680,23 +579,22 @@ static void FillCloudBox( const shader_t *shader, int stage ) } // only add indexes for first stage - FillCloudySkySide( sky_mins_subd, sky_maxs_subd, (qboolean)( stage == 0 ) ); + FillCloudySkySide(sky_mins_subd, sky_maxs_subd, (qboolean)(stage == 0)); } } /* ** R_BuildCloudData */ -void R_BuildCloudData( shaderCommands_t *input ) -{ - int i; - shader_t *shader; +void R_BuildCloudData(shaderCommands_t *input) { + int i; + shader_t *shader; shader = input->shader; - assert( shader->isSky ); + assert(shader->isSky); - sky_min = 1.0 / 256.0f; // FIXME: not correct? + sky_min = 1.0 / 256.0f; // FIXME: not correct? sky_max = 255.0 / 256.0f; // set up for drawing @@ -706,14 +604,12 @@ void R_BuildCloudData( shaderCommands_t *input ) tess.useInternalVBO = qtrue; tess.externalIBO = nullptr; - if ( shader->sky.cloudHeight ) - { - for ( i = 0; i < MAX_SHADER_STAGES; i++ ) - { - if ( !tess.xstages[i] ) { + if (shader->sky.cloudHeight) { + for (i = 0; i < MAX_SHADER_STAGES; i++) { + if (!tess.xstages[i]) { break; } - FillCloudBox( shader, i ); + FillCloudBox(shader, i); } } } @@ -722,9 +618,8 @@ void R_BuildCloudData( shaderCommands_t *input ) ** R_InitSkyTexCoords ** Called when a sky shader is parsed */ -#define SQR( a ) ((a)*(a)) -void R_InitSkyTexCoords( float heightCloud ) -{ +#define SQR(a) ((a) * (a)) +void R_InitSkyTexCoords(float heightCloud) { int i, s, t; float radiusWorld = 4096; float p; @@ -736,41 +631,31 @@ void R_InitSkyTexCoords( float heightCloud ) // a world hasn't been bounded backEnd.viewParms.zFar = 1024; - for ( i = 0; i < 6; i++ ) - { - for ( t = 0; t <= SKY_SUBDIVISIONS; t++ ) - { - for ( s = 0; s <= SKY_SUBDIVISIONS; s++ ) - { + for (i = 0; i < 6; i++) { + for (t = 0; t <= SKY_SUBDIVISIONS; t++) { + for (s = 0; s <= SKY_SUBDIVISIONS; s++) { // compute vector from view origin to sky side integral point - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - skyVec ); + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + skyVec); // compute parametric value 'p' that intersects with cloud layer - p = ( 1.0f / ( 2 * DotProduct( skyVec, skyVec ) ) ) * - ( -2 * skyVec[2] * radiusWorld + - 2 * sqrt( SQR( skyVec[2] ) * SQR( radiusWorld ) + - 2 * SQR( skyVec[0] ) * radiusWorld * heightCloud + - SQR( skyVec[0] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[1] ) * radiusWorld * heightCloud + - SQR( skyVec[1] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[2] ) * radiusWorld * heightCloud + - SQR( skyVec[2] ) * SQR( heightCloud ) ) ); + p = (1.0f / (2 * DotProduct(skyVec, skyVec))) * + (-2 * skyVec[2] * radiusWorld + + 2 * sqrt(SQR(skyVec[2]) * SQR(radiusWorld) + 2 * SQR(skyVec[0]) * radiusWorld * heightCloud + SQR(skyVec[0]) * SQR(heightCloud) + + 2 * SQR(skyVec[1]) * radiusWorld * heightCloud + SQR(skyVec[1]) * SQR(heightCloud) + + 2 * SQR(skyVec[2]) * radiusWorld * heightCloud + SQR(skyVec[2]) * SQR(heightCloud))); s_cloudTexP[i][t][s] = p; // compute intersection point based on p - VectorScale( skyVec, p, v ); + VectorScale(skyVec, p, v); v[2] += radiusWorld; // compute vector from world origin to intersection point 'v' - VectorNormalize( v ); + VectorNormalize(v); - sRad = Q_acos( v[0] ); - tRad = Q_acos( v[1] ); + sRad = Q_acos(v[0]); + tRad = Q_acos(v[1]); s_cloudTexCoords[i][t][s][0] = sRad; s_cloudTexCoords[i][t][s][1] = tRad; @@ -784,36 +669,36 @@ void R_InitSkyTexCoords( float heightCloud ) /* ** RB_DrawSun */ -void RB_DrawSun( float scale, shader_t *shader ) { - float size; - float dist; - vec3_t origin, vec1, vec2; +void RB_DrawSun(float scale, shader_t *shader) { + float size; + float dist; + vec3_t origin, vec1, vec2; - if ( !backEnd.skyRenderedThisView ) { + if (!backEnd.skyRenderedThisView) { return; } // FIXME: this could be a lot cleaner matrix_t translation, modelview; - Matrix16Translation( backEnd.viewParms.ori.origin, translation ); - Matrix16Multiply( backEnd.viewParms.world.modelViewMatrix, translation, modelview ); - GL_SetModelviewMatrix( modelview ); + Matrix16Translation(backEnd.viewParms.ori.origin, translation); + Matrix16Multiply(backEnd.viewParms.world.modelViewMatrix, translation, modelview); + GL_SetModelviewMatrix(modelview); - dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) size = dist * scale; - VectorScale( tr.sunDirection, dist, origin ); - PerpendicularVector( vec1, tr.sunDirection ); - CrossProduct( tr.sunDirection, vec1, vec2 ); + VectorScale(tr.sunDirection, dist, origin); + PerpendicularVector(vec1, tr.sunDirection); + CrossProduct(tr.sunDirection, vec1, vec2); - VectorScale( vec1, size, vec1 ); - VectorScale( vec2, size, vec2 ); + VectorScale(vec1, size, vec1); + VectorScale(vec2, size, vec2); // farthest depth range GL_DepthRange(1.0f, 1.0f); - RB_BeginSurface( shader, 0, 0 ); + RB_BeginSurface(shader, 0, 0); RB_AddQuadStamp(origin, vec1, vec2, colorWhite); @@ -823,9 +708,6 @@ void RB_DrawSun( float scale, shader_t *shader ) { GL_DepthRange(0.0f, 1.0f); } - - - /* ================ RB_StageIteratorSky @@ -835,8 +717,8 @@ All of the visible sky triangles are in tess Other things could be stuck in here, like birds in the sky, etc ================ */ -void RB_StageIteratorSky( void ) { - if ( r_fastsky->integer ) { +void RB_StageIteratorSky(void) { + if (r_fastsky->integer) { return; } @@ -847,25 +729,19 @@ void RB_StageIteratorSky( void ) { // go through all the polygons and project them onto // the sky box to see which blocks on each side need // to be drawn - RB_ClipSkyPolygons( &tess ); + RB_ClipSkyPolygons(&tess); // draw the outer skybox - if ( tess.shader->sky.outerbox[0] && - tess.shader->sky.outerbox[0] != tr.defaultImage ) { - DrawSkyBox( tess.shader ); + if (tess.shader->sky.outerbox[0] && tess.shader->sky.outerbox[0] != tr.defaultImage) { + DrawSkyBox(tess.shader); } // generate the vertexes for all the clouds, which will be drawn // by the generic shader routine - R_BuildCloudData( &tess ); + R_BuildCloudData(&tess); RB_StageIteratorGeneric(); // note that sky was drawn so we will draw a sun later backEnd.skyRenderedThisView = qtrue; } - - - - - diff --git a/codemp/rd-rend2/tr_subs.cpp b/codemp/rd-rend2/tr_subs.cpp index 0228319861..0dde57b78a 100644 --- a/codemp/rd-rend2/tr_subs.cpp +++ b/codemp/rd-rend2/tr_subs.cpp @@ -23,11 +23,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "tr_local.h" - -void QDECL Com_Printf( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Printf(const char *msg, ...) { + va_list argptr; + char text[1024]; va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); @@ -36,10 +34,9 @@ void QDECL Com_Printf( const char *msg, ... ) ri.Printf(PRINT_ALL, "%s", text); } -void QDECL Com_OPrintf( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_OPrintf(const char *msg, ...) { + va_list argptr; + char text[1024]; va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); @@ -48,10 +45,9 @@ void QDECL Com_OPrintf( const char *msg, ... ) ri.OPrintf("%s", text); } -void QDECL Com_Error( int level, const char *error, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Error(int level, const char *error, ...) { + va_list argptr; + char text[1024]; va_start(argptr, error); Q_vsnprintf(text, sizeof(text), error, argptr); @@ -61,35 +57,19 @@ void QDECL Com_Error( int level, const char *error, ... ) } // HUNK -void *Hunk_AllocateTempMemory( int size ) { - return ri.Hunk_AllocateTempMemory( size ); -} +void *Hunk_AllocateTempMemory(int size) { return ri.Hunk_AllocateTempMemory(size); } -void Hunk_FreeTempMemory( void *buf ) { - ri.Hunk_FreeTempMemory( buf ); -} +void Hunk_FreeTempMemory(void *buf) { ri.Hunk_FreeTempMemory(buf); } -void *Hunk_Alloc( int size, ha_pref preference ) { - return ri.Hunk_Alloc( size, preference ); -} +void *Hunk_Alloc(int size, ha_pref preference) { return ri.Hunk_Alloc(size, preference); } -int Hunk_MemoryRemaining( void ) { - return ri.Hunk_MemoryRemaining(); -} +int Hunk_MemoryRemaining(void) { return ri.Hunk_MemoryRemaining(); } // ZONE -void *Z_Malloc( int iSize, memtag_t eTag, qboolean bZeroit, int iAlign ) { - return ri.Z_Malloc( iSize, eTag, bZeroit, iAlign ); -} +void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign) { return ri.Z_Malloc(iSize, eTag, bZeroit, iAlign); } -void Z_Free( void *ptr ) { - ri.Z_Free( ptr ); -} +void Z_Free(void *ptr) { ri.Z_Free(ptr); } -int Z_MemSize( memtag_t eTag ) { - return ri.Z_MemSize( eTag ); -} +int Z_MemSize(memtag_t eTag) { return ri.Z_MemSize(eTag); } -void Z_MorphMallocTag( void *pvBuffer, memtag_t eDesiredTag ) { - ri.Z_MorphMallocTag( pvBuffer, eDesiredTag ); -} +void Z_MorphMallocTag(void *pvBuffer, memtag_t eDesiredTag) { ri.Z_MorphMallocTag(pvBuffer, eDesiredTag); } diff --git a/codemp/rd-rend2/tr_surface.cpp b/codemp/rd-rend2/tr_surface.cpp index fc3255a5ed..09cbbbcf50 100644 --- a/codemp/rd-rend2/tr_surface.cpp +++ b/codemp/rd-rend2/tr_surface.cpp @@ -37,126 +37,110 @@ It is safe to actually issue drawing commands here if you don't want to use the shader system. */ - //============================================================================ - /* ============== RB_CheckOverflow ============== */ -void RB_CheckOverflow( int verts, int indexes ) { - if ((tess.numVertexes + verts) < SHADER_MAX_VERTEXES && - (tess.numIndexes + indexes) < SHADER_MAX_INDEXES) - { +void RB_CheckOverflow(int verts, int indexes) { + if ((tess.numVertexes + verts) < SHADER_MAX_VERTEXES && (tess.numIndexes + indexes) < SHADER_MAX_INDEXES) { return; } RB_EndSurface(); - if ( verts >= SHADER_MAX_VERTEXES ) { - ri.Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES ); + if (verts >= SHADER_MAX_VERTEXES) { + ri.Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES); } - if ( indexes >= SHADER_MAX_INDEXES ) { - ri.Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES ); + if (indexes >= SHADER_MAX_INDEXES) { + ri.Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES); } - RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex); } -void RB_CheckVBOandIBO(VBO_t *vbo, IBO_t *ibo) -{ - if (vbo != glState.currentVBO || - ibo != glState.currentIBO || - tess.multiDrawPrimitives >= MAX_MULTIDRAW_PRIMITIVES) - { +void RB_CheckVBOandIBO(VBO_t *vbo, IBO_t *ibo) { + if (vbo != glState.currentVBO || ibo != glState.currentIBO || tess.multiDrawPrimitives >= MAX_MULTIDRAW_PRIMITIVES) { RB_EndSurface(); - RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex); R_BindVBO(vbo); R_BindIBO(ibo); } - if (vbo != backEndData->currentFrame->dynamicVbo && - ibo != backEndData->currentFrame->dynamicIbo) - { + if (vbo != backEndData->currentFrame->dynamicVbo && ibo != backEndData->currentFrame->dynamicIbo) { tess.useInternalVBO = qfalse; } - if ( ibo != backEndData->currentFrame->dynamicIbo ) - { + if (ibo != backEndData->currentFrame->dynamicIbo) { tess.externalIBO = ibo; } } - /* ============== RB_AddQuadStampExt ============== */ -void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, float color[4], float s1, float t1, float s2, float t2 ) { - vec3_t normal; - int ndx; +void RB_AddQuadStampExt(vec3_t origin, vec3_t left, vec3_t up, float color[4], float s1, float t1, float s2, float t2) { + vec3_t normal; + int ndx; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); ndx = tess.numVertexes; // triangle indexes for a simple quad - tess.indexes[ tess.numIndexes ] = ndx; - tess.indexes[ tess.numIndexes + 1 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 2 ] = ndx + 3; + tess.indexes[tess.numIndexes] = ndx; + tess.indexes[tess.numIndexes + 1] = ndx + 1; + tess.indexes[tess.numIndexes + 2] = ndx + 3; - tess.indexes[ tess.numIndexes + 3 ] = ndx + 3; - tess.indexes[ tess.numIndexes + 4 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 5 ] = ndx + 2; + tess.indexes[tess.numIndexes + 3] = ndx + 3; + tess.indexes[tess.numIndexes + 4] = ndx + 1; + tess.indexes[tess.numIndexes + 5] = ndx + 2; tess.xyz[ndx][0] = origin[0] + left[0] + up[0]; tess.xyz[ndx][1] = origin[1] + left[1] + up[1]; tess.xyz[ndx][2] = origin[2] + left[2] + up[2]; - tess.xyz[ndx+1][0] = origin[0] - left[0] + up[0]; - tess.xyz[ndx+1][1] = origin[1] - left[1] + up[1]; - tess.xyz[ndx+1][2] = origin[2] - left[2] + up[2]; + tess.xyz[ndx + 1][0] = origin[0] - left[0] + up[0]; + tess.xyz[ndx + 1][1] = origin[1] - left[1] + up[1]; + tess.xyz[ndx + 1][2] = origin[2] - left[2] + up[2]; - tess.xyz[ndx+2][0] = origin[0] - left[0] - up[0]; - tess.xyz[ndx+2][1] = origin[1] - left[1] - up[1]; - tess.xyz[ndx+2][2] = origin[2] - left[2] - up[2]; - - tess.xyz[ndx+3][0] = origin[0] + left[0] - up[0]; - tess.xyz[ndx+3][1] = origin[1] + left[1] - up[1]; - tess.xyz[ndx+3][2] = origin[2] + left[2] - up[2]; + tess.xyz[ndx + 2][0] = origin[0] - left[0] - up[0]; + tess.xyz[ndx + 2][1] = origin[1] - left[1] - up[1]; + tess.xyz[ndx + 2][2] = origin[2] - left[2] - up[2]; + tess.xyz[ndx + 3][0] = origin[0] + left[0] - up[0]; + tess.xyz[ndx + 3][1] = origin[1] + left[1] - up[1]; + tess.xyz[ndx + 3][2] = origin[2] + left[2] - up[2]; // constant normal all the way around - VectorSubtract( vec3_origin, backEnd.viewParms.ori.axis[0], normal ); + VectorSubtract(vec3_origin, backEnd.viewParms.ori.axis[0], normal); - tess.normal[ndx] = - tess.normal[ndx+1] = - tess.normal[ndx+2] = - tess.normal[ndx+3] = R_VboPackNormal(normal); + tess.normal[ndx] = tess.normal[ndx + 1] = tess.normal[ndx + 2] = tess.normal[ndx + 3] = R_VboPackNormal(normal); // standard square texture coordinates - VectorSet2(tess.texCoords[ndx ][0], s1, t1); - VectorSet2(tess.texCoords[ndx ][1], s1, t1); + VectorSet2(tess.texCoords[ndx][0], s1, t1); + VectorSet2(tess.texCoords[ndx][1], s1, t1); - VectorSet2(tess.texCoords[ndx+1][0], s2, t1); - VectorSet2(tess.texCoords[ndx+1][1], s2, t1); + VectorSet2(tess.texCoords[ndx + 1][0], s2, t1); + VectorSet2(tess.texCoords[ndx + 1][1], s2, t1); - VectorSet2(tess.texCoords[ndx+2][0], s2, t2); - VectorSet2(tess.texCoords[ndx+2][1], s2, t2); + VectorSet2(tess.texCoords[ndx + 2][0], s2, t2); + VectorSet2(tess.texCoords[ndx + 2][1], s2, t2); - VectorSet2(tess.texCoords[ndx+3][0], s1, t2); - VectorSet2(tess.texCoords[ndx+3][1], s1, t2); + VectorSet2(tess.texCoords[ndx + 3][0], s1, t2); + VectorSet2(tess.texCoords[ndx + 3][1], s1, t2); // constant color all the way around // should this be identity and let the shader specify from entity? VectorCopy4(color, tess.vertexColors[ndx]); - VectorCopy4(color, tess.vertexColors[ndx+1]); - VectorCopy4(color, tess.vertexColors[ndx+2]); - VectorCopy4(color, tess.vertexColors[ndx+3]); + VectorCopy4(color, tess.vertexColors[ndx + 1]); + VectorCopy4(color, tess.vertexColors[ndx + 2]); + VectorCopy4(color, tess.vertexColors[ndx + 3]); tess.numVertexes += 4; tess.numIndexes += 6; @@ -167,10 +151,7 @@ void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, float color[4], RB_AddQuadStamp ============== */ -void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, float color[4] ) { - RB_AddQuadStampExt( origin, left, up, color, 0, 0, 1, 1 ); -} - +void RB_AddQuadStamp(vec3_t origin, vec3_t left, vec3_t up, float color[4]) { RB_AddQuadStampExt(origin, left, up, color, 0, 0, 1, 1); } /* ============== @@ -179,9 +160,8 @@ RB_InstantQuad based on Tess_InstantQuad from xreal ============== */ -void RB_InstantQuad2(vec4_t quadVerts[4], vec2_t texCoords[4]) -{ -// GLimp_LogComment("--- RB_InstantQuad2 ---\n"); // FIXME: REIMPLEMENT (wasn't implemented in ioq3 to begin with) --eez +void RB_InstantQuad2(vec4_t quadVerts[4], vec2_t texCoords[4]) { + // GLimp_LogComment("--- RB_InstantQuad2 ---\n"); // FIXME: REIMPLEMENT (wasn't implemented in ioq3 to begin with) --eez tess.numVertexes = 0; tess.numIndexes = 0; @@ -229,9 +209,7 @@ void RB_InstantQuad2(vec4_t quadVerts[4], vec2_t texCoords[4]) tess.useInternalVBO = qfalse; } - -void RB_InstantQuad(vec4_t quadVerts[4]) -{ +void RB_InstantQuad(vec4_t quadVerts[4]) { vec2_t texCoords[4]; VectorSet2(texCoords[0], 0.0f, 0.0f); @@ -240,57 +218,52 @@ void RB_InstantQuad(vec4_t quadVerts[4]) VectorSet2(texCoords[3], 0.0f, 1.0f); GLSL_BindProgram(&tr.textureColorShader); - + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); GLSL_SetUniformVec4(&tr.textureColorShader, UNIFORM_COLOR, colorWhite); RB_InstantQuad2(quadVerts, texCoords); } -void RB_InstantTriangle() -{ - qglDrawArrays(GL_TRIANGLES, 0, 3); -} - - +void RB_InstantTriangle() { qglDrawArrays(GL_TRIANGLES, 0, 3); } /* ============== RB_SurfaceSprite ============== */ -static void RB_SurfaceSprite( void ) { - vec3_t left, up; - float radius; - float colors[4]; - trRefEntity_t *ent = backEnd.currentEntity; +static void RB_SurfaceSprite(void) { + vec3_t left, up; + float radius; + float colors[4]; + trRefEntity_t *ent = backEnd.currentEntity; // calculate the xyz locations for the four corners radius = ent->e.radius; - if ( ent->e.rotation == 0 ) { - VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); - VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); + if (ent->e.rotation == 0) { + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); } else { - float s, c; - float ang; - + float s, c; + float ang; + ang = M_PI * ent->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); } - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } VectorScale4(ent->e.shaderRGBA, 1.0f / 255.0f, colors); - RB_AddQuadStamp( ent->e.origin, left, up, colors ); + RB_AddQuadStamp(ent->e.origin, left, up, colors); } /* @@ -298,52 +271,47 @@ static void RB_SurfaceSprite( void ) { RB_SurfaceOrientedQuad ======================= */ -static void RB_SurfaceOrientedQuad( void ) -{ - vec3_t left, up; - float radius; - float color[4]; +static void RB_SurfaceOrientedQuad(void) { + vec3_t left, up; + float radius; + float color[4]; // calculate the xyz locations for the four corners radius = backEnd.currentEntity->e.radius; -// MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); - VectorCopy( backEnd.currentEntity->e.axis[1], left ); - VectorCopy( backEnd.currentEntity->e.axis[2], up ); - - if ( backEnd.currentEntity->e.rotation == 0 ) - { - VectorScale( left, radius, left ); - VectorScale( up, radius, up ); - } - else - { - vec3_t tempLeft, tempUp; - float s, c; - float ang; - + // MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); + VectorCopy(backEnd.currentEntity->e.axis[1], left); + VectorCopy(backEnd.currentEntity->e.axis[2], up); + + if (backEnd.currentEntity->e.rotation == 0) { + VectorScale(left, radius, left); + VectorScale(up, radius, up); + } else { + vec3_t tempLeft, tempUp; + float s, c; + float ang; + ang = M_PI * backEnd.currentEntity->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); // Use a temp so we don't trash the values we'll need later - VectorScale( left, c * radius, tempLeft ); - VectorMA( tempLeft, -s * radius, up, tempLeft ); + VectorScale(left, c * radius, tempLeft); + VectorMA(tempLeft, -s * radius, up, tempLeft); - VectorScale( up, c * radius, tempUp ); - VectorMA( tempUp, s * radius, left, up ); // no need to use the temp anymore, so copy into the dest vector ( up ) + VectorScale(up, c * radius, tempUp); + VectorMA(tempUp, s * radius, left, up); // no need to use the temp anymore, so copy into the dest vector ( up ) // This was copied for safekeeping, we're done, so we can move it back to left - VectorCopy( tempLeft, left ); + VectorCopy(tempLeft, left); } - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, color); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, color); - RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, color); + RB_AddQuadStamp(backEnd.currentEntity->e.origin, left, up, color); } /* @@ -351,28 +319,28 @@ static void RB_SurfaceOrientedQuad( void ) RB_SurfacePolychain ============= */ -static void RB_SurfacePolychain( srfPoly_t *p ) { - int i; - int numv; +static void RB_SurfacePolychain(srfPoly_t *p) { + int i; + int numv; - RB_CHECKOVERFLOW( p->numVerts, 3*(p->numVerts - 2) ); + RB_CHECKOVERFLOW(p->numVerts, 3 * (p->numVerts - 2)); // fan triangles into the tess array numv = tess.numVertexes; - for ( i = 0; i < p->numVerts; i++ ) { - VectorCopy( p->verts[i].xyz, tess.xyz[numv] ); + for (i = 0; i < p->numVerts; i++) { + VectorCopy(p->verts[i].xyz, tess.xyz[numv]); tess.texCoords[numv][0][0] = p->verts[i].st[0]; tess.texCoords[numv][0][1] = p->verts[i].st[1]; - tess.vertexColors[numv][0] = p->verts[ i ].modulate[0] / 255.0f; - tess.vertexColors[numv][1] = p->verts[ i ].modulate[1] / 255.0f; - tess.vertexColors[numv][2] = p->verts[ i ].modulate[2] / 255.0f; - tess.vertexColors[numv][3] = p->verts[ i ].modulate[3] / 255.0f; + tess.vertexColors[numv][0] = p->verts[i].modulate[0] / 255.0f; + tess.vertexColors[numv][1] = p->verts[i].modulate[1] / 255.0f; + tess.vertexColors[numv][2] = p->verts[i].modulate[2] / 255.0f; + tess.vertexColors[numv][3] = p->verts[i].modulate[3] / 255.0f; numv++; } // generate fan indexes into the tess array - for ( i = 0; i < p->numVerts-2; i++ ) { + for (i = 0; i < p->numVerts - 2; i++) { tess.indexes[tess.numIndexes + 0] = tess.numVertexes; tess.indexes[tess.numIndexes + 1] = tess.numVertexes + i + 1; tess.indexes[tess.numIndexes + 2] = tess.numVertexes + i + 2; @@ -382,90 +350,81 @@ static void RB_SurfacePolychain( srfPoly_t *p ) { tess.numVertexes = numv; } -static void RB_SurfaceVertsAndIndexes( int numVerts, srfVert_t *verts, int numIndexes, glIndex_t *indexes, int dlightBits, int pshadowBits) -{ - int i; - glIndex_t *inIndex; - srfVert_t *dv; - float *xyz, *texCoords, *lightCoords; - uint32_t *lightdir; - uint32_t *normal; - uint32_t *tangent; - glIndex_t *outIndex; - float *color; - gpuFrame_t *currentFrame = backEndData->currentFrame; +static void RB_SurfaceVertsAndIndexes(int numVerts, srfVert_t *verts, int numIndexes, glIndex_t *indexes, int dlightBits, int pshadowBits) { + int i; + glIndex_t *inIndex; + srfVert_t *dv; + float *xyz, *texCoords, *lightCoords; + uint32_t *lightdir; + uint32_t *normal; + uint32_t *tangent; + glIndex_t *outIndex; + float *color; + gpuFrame_t *currentFrame = backEndData->currentFrame; RB_CheckVBOandIBO(currentFrame->dynamicVbo, currentFrame->dynamicIbo); - RB_CHECKOVERFLOW( numVerts, numIndexes ); + RB_CHECKOVERFLOW(numVerts, numIndexes); inIndex = indexes; - outIndex = &tess.indexes[ tess.numIndexes ]; - for ( i = 0 ; i < numIndexes ; i++ ) { + outIndex = &tess.indexes[tess.numIndexes]; + for (i = 0; i < numIndexes; i++) { *outIndex++ = tess.numVertexes + *inIndex++; } tess.numIndexes += numIndexes; - if ( tess.shader->vertexAttribs & ATTR_POSITION ) - { + if (tess.shader->vertexAttribs & ATTR_POSITION) { dv = verts; - xyz = tess.xyz[ tess.numVertexes ]; - for ( i = 0 ; i < numVerts ; i++, dv++, xyz+=4 ) + xyz = tess.xyz[tess.numVertexes]; + for (i = 0; i < numVerts; i++, dv++, xyz += 4) VectorCopy(dv->xyz, xyz); } - if ( tess.shader->vertexAttribs & ATTR_NORMAL ) - { + if (tess.shader->vertexAttribs & ATTR_NORMAL) { dv = verts; - normal = &tess.normal[ tess.numVertexes ]; - for ( i = 0 ; i < numVerts ; i++, dv++, normal++ ) + normal = &tess.normal[tess.numVertexes]; + for (i = 0; i < numVerts; i++, dv++, normal++) *normal = R_VboPackNormal(dv->normal); } - if ( tess.shader->vertexAttribs & ATTR_TANGENT ) - { + if (tess.shader->vertexAttribs & ATTR_TANGENT) { dv = verts; - tangent = &tess.tangent[ tess.numVertexes ]; - for ( i = 0 ; i < numVerts ; i++, dv++, tangent++ ) + tangent = &tess.tangent[tess.numVertexes]; + for (i = 0; i < numVerts; i++, dv++, tangent++) *tangent = R_VboPackTangent(dv->tangent); } - if ( tess.shader->vertexAttribs & ATTR_TEXCOORD0 ) - { + if (tess.shader->vertexAttribs & ATTR_TEXCOORD0) { dv = verts; - texCoords = tess.texCoords[ tess.numVertexes ][0]; - for ( i = 0 ; i < numVerts ; i++, dv++, texCoords+=NUM_TESS_TEXCOORDS*2 ) + texCoords = tess.texCoords[tess.numVertexes][0]; + for (i = 0; i < numVerts; i++, dv++, texCoords += NUM_TESS_TEXCOORDS * 2) VectorCopy2(dv->st, texCoords); } - for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) - { - if ( tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc) ) - { + for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) { + if (tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc)) { dv = verts; - lightCoords = tess.texCoords[ tess.numVertexes ][1 + tc]; - for ( i = 0 ; i < numVerts ; i++, dv++, lightCoords+=NUM_TESS_TEXCOORDS*2 ) + lightCoords = tess.texCoords[tess.numVertexes][1 + tc]; + for (i = 0; i < numVerts; i++, dv++, lightCoords += NUM_TESS_TEXCOORDS * 2) VectorCopy2(dv->lightmap[tc], lightCoords); } } - if ( tess.shader->vertexAttribs & ATTR_COLOR ) - { + if (tess.shader->vertexAttribs & ATTR_COLOR) { dv = verts; - color = tess.vertexColors[ tess.numVertexes ]; - for ( i = 0 ; i < numVerts ; i++, dv++, color+=4 ) + color = tess.vertexColors[tess.numVertexes]; + for (i = 0; i < numVerts; i++, dv++, color += 4) VectorCopy4(dv->vertexColors[0], color); } - if ( tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION ) - { + if (tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION) { dv = verts; - lightdir = &tess.lightdir[ tess.numVertexes ]; - for ( i = 0 ; i < numVerts ; i++, dv++, lightdir++ ) + lightdir = &tess.lightdir[tess.numVertexes]; + for (i = 0; i < numVerts; i++, dv++, lightdir++) *lightdir = R_VboPackNormal(dv->lightdir); } -#if 0 // nothing even uses vertex dlightbits +#if 0 // nothing even uses vertex dlightbits for ( i = 0 ; i < numVerts ; i++ ) { tess.vertexDlightBits[ tess.numVertexes + i ] = dlightBits; } @@ -477,23 +436,16 @@ static void RB_SurfaceVertsAndIndexes( int numVerts, srfVert_t *verts, int numIn tess.numVertexes += numVerts; } -static qboolean RB_SurfaceVbo( - VBO_t *vbo, IBO_t *ibo, int numVerts, int numIndexes, int firstIndex, - int minIndex, int maxIndex, int dlightBits, int pshadowBits, qboolean shaderCheck) -{ +static qboolean RB_SurfaceVbo(VBO_t *vbo, IBO_t *ibo, int numVerts, int numIndexes, int firstIndex, int minIndex, int maxIndex, int dlightBits, int pshadowBits, + qboolean shaderCheck) { int i, mergeForward, mergeBack; GLvoid *firstIndexOffset, *lastIndexOffset; - if (!vbo || !ibo) - { + if (!vbo || !ibo) { return qfalse; } - if (shaderCheck && - (ShaderRequiresCPUDeforms(tess.shader) || - tess.shader->isSky || - tess.shader->isPortal)) - { + if (shaderCheck && (ShaderRequiresCPUDeforms(tess.shader) || tess.shader->isSky || tess.shader->isPortal)) { return qfalse; } @@ -506,69 +458,55 @@ static qboolean RB_SurfaceVbo( mergeForward = -1; mergeBack = -1; firstIndexOffset = BUFFER_OFFSET(firstIndex * sizeof(glIndex_t)); - lastIndexOffset = BUFFER_OFFSET((firstIndex + numIndexes) * sizeof(glIndex_t)); + lastIndexOffset = BUFFER_OFFSET((firstIndex + numIndexes) * sizeof(glIndex_t)); - if (r_mergeMultidraws->integer) - { + if (r_mergeMultidraws->integer) { i = 0; - if (r_mergeMultidraws->integer == 1) - { + if (r_mergeMultidraws->integer == 1) { // lazy merge, only check the last primitive - if (tess.multiDrawPrimitives) - { + if (tess.multiDrawPrimitives) { i = tess.multiDrawPrimitives - 1; } } - for (; i < tess.multiDrawPrimitives; i++) - { - if (tess.multiDrawLastIndex[i] == firstIndexOffset) - { + for (; i < tess.multiDrawPrimitives; i++) { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) { mergeBack = i; } - if (lastIndexOffset == tess.multiDrawFirstIndex[i]) - { + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) { mergeForward = i; } } } - if (mergeBack != -1 && mergeForward == -1) - { + if (mergeBack != -1 && mergeForward == -1) { tess.multiDrawNumIndexes[mergeBack] += numIndexes; - tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], minIndex); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack == -1 && mergeForward != -1) - { + } else if (mergeBack == -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeForward] += numIndexes; - tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; - tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], minIndex); tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack != -1 && mergeForward != -1) - { + } else if (mergeBack != -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeBack] += numIndexes + tess.multiDrawNumIndexes[mergeForward]; - tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], minIndex)); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex)); tess.multiDrawPrimitives--; - if (mergeForward != tess.multiDrawPrimitives) - { + if (mergeForward != tess.multiDrawPrimitives) { tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; } backEnd.pc.c_multidrawsMerged += 2; - } - else if (mergeBack == -1 && mergeForward == -1) - { + } else if (mergeBack == -1 && mergeForward == -1) { tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = numIndexes; tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; @@ -579,7 +517,7 @@ static qboolean RB_SurfaceVbo( backEnd.pc.c_multidraws++; - tess.numIndexes += numIndexes; + tess.numIndexes += numIndexes; tess.numVertexes += numVerts; return qtrue; @@ -590,33 +528,28 @@ static qboolean RB_SurfaceVbo( RB_SurfaceBSPTriangles ============= */ -static void RB_SurfaceBSPTriangles( srfBspSurface_t *srf ) { - if( RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, - srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) - { +static void RB_SurfaceBSPTriangles(srfBspSurface_t *srf) { + if (RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, + qtrue)) { return; } - RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, - srf->indexes, srf->dlightBits, srf->pshadowBits); + RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, srf->indexes, srf->dlightBits, srf->pshadowBits); } - - /* ============== RB_SurfaceBeam ============== */ -static void RB_SurfaceBeam( void ) -{ +static void RB_SurfaceBeam(void) { #define NUM_BEAM_SEGS 6 refEntity_t *e; shaderProgram_t *sp = &tr.textureColorShader; - int i; + int i; vec3_t perpvec; vec3_t direction, normalized_direction; - vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; + vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; vec3_t oldorigin, origin; e = &backEnd.currentEntity->e; @@ -633,23 +566,22 @@ static void RB_SurfaceBeam( void ) normalized_direction[1] = direction[1] = oldorigin[1] - origin[1]; normalized_direction[2] = direction[2] = oldorigin[2] - origin[2]; - if ( VectorNormalize( normalized_direction ) == 0 ) + if (VectorNormalize(normalized_direction) == 0) return; - PerpendicularVector( perpvec, normalized_direction ); + PerpendicularVector(perpvec, normalized_direction); - VectorScale( perpvec, 4, perpvec ); + VectorScale(perpvec, 4, perpvec); - for ( i = 0; i < NUM_BEAM_SEGS ; i++ ) - { - RotatePointAroundVector( start_points[i], normalized_direction, perpvec, (360.0/NUM_BEAM_SEGS)*i ); -// VectorAdd( start_points[i], origin, start_points[i] ); - VectorAdd( start_points[i], direction, end_points[i] ); + for (i = 0; i < NUM_BEAM_SEGS; i++) { + RotatePointAroundVector(start_points[i], normalized_direction, perpvec, (360.0 / NUM_BEAM_SEGS) * i); + // VectorAdd( start_points[i], origin, start_points[i] ); + VectorAdd(start_points[i], direction, end_points[i]); } - GL_Bind( tr.whiteImage ); + GL_Bind(tr.whiteImage); - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); // FIXME: Quake3 doesn't use this, so I never tested it tess.numVertexes = 0; @@ -658,19 +590,19 @@ static void RB_SurfaceBeam( void ) tess.minIndex = 0; tess.maxIndex = 0; - for ( i = 0; i <= NUM_BEAM_SEGS; i++ ) { - VectorCopy(start_points[ i % NUM_BEAM_SEGS ], tess.xyz[tess.numVertexes++]); - VectorCopy(end_points [ i % NUM_BEAM_SEGS ], tess.xyz[tess.numVertexes++]); + for (i = 0; i <= NUM_BEAM_SEGS; i++) { + VectorCopy(start_points[i % NUM_BEAM_SEGS], tess.xyz[tess.numVertexes++]); + VectorCopy(end_points[i % NUM_BEAM_SEGS], tess.xyz[tess.numVertexes++]); } - for ( i = 0; i < NUM_BEAM_SEGS; i++ ) { - tess.indexes[tess.numIndexes++] = i * 2; - tess.indexes[tess.numIndexes++] = (i + 1) * 2; - tess.indexes[tess.numIndexes++] = 1 + i * 2; + for (i = 0; i < NUM_BEAM_SEGS; i++) { + tess.indexes[tess.numIndexes++] = i * 2; + tess.indexes[tess.numIndexes++] = (i + 1) * 2; + tess.indexes[tess.numIndexes++] = 1 + i * 2; - tess.indexes[tess.numIndexes++] = 1 + i * 2; - tess.indexes[tess.numIndexes++] = (i + 1) * 2; - tess.indexes[tess.numIndexes++] = 1 + (i + 1) * 2; + tess.indexes[tess.numIndexes++] = 1 + i * 2; + tess.indexes[tess.numIndexes++] = (i + 1) * 2; + tess.indexes[tess.numIndexes++] = 1 + (i + 1) * 2; } tess.minIndex = 0; @@ -679,12 +611,12 @@ static void RB_SurfaceBeam( void ) // FIXME: A lot of this can probably be removed for speed, and refactored into a more convenient function RB_UpdateVBOs(ATTR_POSITION); - + GLSL_VertexAttribsState(ATTR_POSITION, NULL); GLSL_BindProgram(sp); - + GLSL_SetUniformMatrix4x4(sp, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); - + GLSL_SetUniformVec4(sp, UNIFORM_COLOR, colorRed); R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); @@ -702,56 +634,52 @@ static void RB_SurfaceBeam( void ) //------------------ // DoSprite //------------------ -static void DoSprite( vec3_t origin, float radius, float rotation ) -{ - float s, c; - float ang; - vec3_t left, up; - float color[4]; - +static void DoSprite(vec3_t origin, float radius, float rotation) { + float s, c; + float ang; + vec3_t left, up; + float color[4]; + ang = M_PI * rotation / 180.0f; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, color); - RB_AddQuadStamp( origin, left, up, color ); + RB_AddQuadStamp(origin, left, up, color); } //------------------ // RB_SurfaceSaber //------------------ -static void RB_SurfaceSaberGlow() -{ - vec3_t end; +static void RB_SurfaceSaberGlow() { + vec3_t end; refEntity_t *e; e = &backEnd.currentEntity->e; // Render the glow part of the blade - for ( float i = e->saberLength; i > 0; i -= e->radius * 0.65f ) - { - VectorMA( e->origin, i, e->axis[0], end ); + for (float i = e->saberLength; i > 0; i -= e->radius * 0.65f) { + VectorMA(e->origin, i, e->axis[0], end); - DoSprite( end, e->radius, 0.0f );//random() * 360.0f ); + DoSprite(end, e->radius, 0.0f); // random() * 360.0f ); e->radius += 0.017f; } // Big hilt sprite // Please don't kill me Pat...I liked the hilt glow blob, but wanted a subtle pulse.:) Feel free to ditch it if you don't like it. --Jeff // Please don't kill me Jeff... The pulse is good, but now I want the halo bigger if the saber is shorter... --Pat - DoSprite( e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f );//random() * 360.0f ); + DoSprite(e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f); // random() * 360.0f ); } /* @@ -765,48 +693,47 @@ RB_SurfaceLine // STScale (how many times to loop a texture) // alpha // RGB -// +// // Values for proper line object... // lifetime // dscale // startalpha, endalpha // startRGB, endRGB -// +// -static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) -{ - float spanWidth2; - int vbase; +static void DoLine(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth) { + float spanWidth2; + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; spanWidth2 = -spanWidth; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; tess.indexes[tess.numIndexes++] = vbase; @@ -818,37 +745,36 @@ static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float tess.indexes[tess.numIndexes++] = vbase + 3; } -static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2 ) -{ - int vbase; +static void DoLine2(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2) { + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( start, -spanWidth, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, -spanWidth, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, -spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorMA(end, -spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; tess.indexes[tess.numIndexes++] = vbase; @@ -860,39 +786,38 @@ static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, floa tess.indexes[tess.numIndexes++] = vbase + 3; } -static void DoLine_Oriented( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) -{ - float spanWidth2; - int vbase; +static void DoLine_Oriented(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth) { + float spanWidth2; + int vbase; vbase = tess.numVertexes; spanWidth2 = -spanWidth; // FIXME: use quad stamp? - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 1; tess.texCoords[tess.numVertexes][0][1] = 0; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 1; tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; - VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; tess.indexes[tess.numIndexes++] = vbase; @@ -907,42 +832,40 @@ static void DoLine_Oriented( const vec3_t start, const vec3_t end, const vec3_t //----------------- // RB_SurfaceLine //----------------- -static void RB_SurfaceLine( void ) -{ +static void RB_SurfaceLine(void) { refEntity_t *e; - vec3_t right; - vec3_t start, end; - vec3_t v1, v2; + vec3_t right; + vec3_t start, end; + vec3_t v1, v2; e = &backEnd.currentEntity->e; - VectorCopy( e->oldorigin, end ); - VectorCopy( e->origin, start ); + VectorCopy(e->oldorigin, end); + VectorCopy(e->origin, start); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); - DoLine( start, end, right, e->radius); + DoLine(start, end, right, e->radius); } -static void RB_SurfaceOrientedLine( void ) -{ +static void RB_SurfaceOrientedLine(void) { refEntity_t *e; - vec3_t right; - vec3_t start, end; + vec3_t right; + vec3_t start, end; e = &backEnd.currentEntity->e; - VectorCopy( e->oldorigin, end ); - VectorCopy( e->origin, start ); + VectorCopy(e->oldorigin, end); + VectorCopy(e->origin, start); // compute side vector - VectorNormalize( e->axis[1] ); + VectorNormalize(e->axis[1]); VectorCopy(e->axis[1], right); - DoLine_Oriented( start, end, right, e->data.line.width*0.5 ); + DoLine_Oriented(start, end, right, e->data.line.width * 0.5); } /* @@ -954,24 +877,22 @@ RB_SurfaceCylinder #define NUM_CYLINDER_SEGMENTS 32 // FIXME: use quad stamp? -static void DoCylinderPart(polyVert_t *verts) -{ - int vbase; - int i; +static void DoCylinderPart(polyVert_t *verts) { + int vbase; + int i; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; - for (i=0; i<4; i++) - { - VectorCopy( verts->xyz, tess.xyz[tess.numVertexes] ); + for (i = 0; i < 4; i++) { + VectorCopy(verts->xyz, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = verts->st[0]; tess.texCoords[tess.numVertexes][0][1] = verts->st[1]; - VectorScale4 (verts->modulate, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + VectorScale4(verts->modulate, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); tess.numVertexes++; verts++; - } + } tess.indexes[tess.numIndexes++] = vbase; tess.indexes[tess.numIndexes++] = vbase + 1; @@ -986,73 +907,68 @@ static void DoCylinderPart(polyVert_t *verts) // e->oldorigin holds the top point // e->radius holds the radius -static void RB_SurfaceCylinder( void ) -{ - static polyVert_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS], verts[4]; - vec3_t vr, vu, midpoint, v1; - float detail, length; - int i; - int segments; +static void RB_SurfaceCylinder(void) { + static polyVert_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS], verts[4]; + vec3_t vr, vu, midpoint, v1; + float detail, length; + int i; + int segments; refEntity_t *e; - int nextSegment; + int nextSegment; e = &backEnd.currentEntity->e; - //Work out the detail level of this cylinder - VectorAdd( e->origin, e->oldorigin, midpoint ); - VectorScale(midpoint, 0.5f, midpoint); // Average start and end + // Work out the detail level of this cylinder + VectorAdd(e->origin, e->oldorigin, midpoint); + VectorScale(midpoint, 0.5f, midpoint); // Average start and end - VectorSubtract( midpoint, backEnd.viewParms.ori.origin, midpoint ); - length = VectorNormalize( midpoint ); + VectorSubtract(midpoint, backEnd.viewParms.ori.origin, midpoint); + length = VectorNormalize(midpoint); // this doesn't need to be perfect....just a rough compensation for zoom level is enough length *= (backEnd.viewParms.fovX / 90.0f); - detail = 1 - ((float) length / 1024 ); + detail = 1 - ((float)length / 1024); segments = NUM_CYLINDER_SEGMENTS * detail; // 3 is the absolute minimum, but the pop between 3-8 is too noticeable - if ( segments < 8 ) - { + if (segments < 8) { segments = 8; } - if ( segments > NUM_CYLINDER_SEGMENTS ) - { + if (segments > NUM_CYLINDER_SEGMENTS) { segments = NUM_CYLINDER_SEGMENTS; } - //Get the direction vector - MakeNormalVectors( e->axis[0], vr, vu ); + // Get the direction vector + MakeNormalVectors(e->axis[0], vr, vu); - VectorScale( vu, e->radius, v1 ); // size1 - VectorScale( vu, e->rotation, vu ); // size2 + VectorScale(vu, e->radius, v1); // size1 + VectorScale(vu, e->rotation, vu); // size2 // Calculate the step around the cylinder detail = 360.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { - //Upper ring - RotatePointAroundVector( upper_points[i].xyz, e->axis[0], vu, detail * i ); - VectorAdd( upper_points[i].xyz, e->origin, upper_points[i].xyz ); - - //Lower ring - RotatePointAroundVector( lower_points[i].xyz, e->axis[0], v1, detail * i ); - VectorAdd( lower_points[i].xyz, e->oldorigin, lower_points[i].xyz ); + for (i = 0; i < segments; i++) { + // Upper ring + RotatePointAroundVector(upper_points[i].xyz, e->axis[0], vu, detail * i); + VectorAdd(upper_points[i].xyz, e->origin, upper_points[i].xyz); + + // Lower ring + RotatePointAroundVector(lower_points[i].xyz, e->axis[0], v1, detail * i); + VectorAdd(lower_points[i].xyz, e->oldorigin, lower_points[i].xyz); } - + // Calculate the texture coords so the texture can wrap around the whole cylinder detail = 1.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { - if ( i + 1 < segments ) + for (i = 0; i < segments; i++) { + if (i + 1 < segments) nextSegment = i + 1; else nextSegment = 0; - VectorCopy( upper_points[i].xyz, verts[0].xyz ); + VectorCopy(upper_points[i].xyz, verts[0].xyz); verts[0].st[1] = 1.0f; verts[0].st[0] = detail * i; verts[0].modulate[0] = (byte)(e->shaderRGBA[0]); @@ -1060,7 +976,7 @@ static void RB_SurfaceCylinder( void ) verts[0].modulate[2] = (byte)(e->shaderRGBA[2]); verts[0].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( lower_points[i].xyz, verts[1].xyz ); + VectorCopy(lower_points[i].xyz, verts[1].xyz); verts[1].st[1] = 0.0f; verts[1].st[0] = detail * i; verts[1].modulate[0] = (byte)(e->shaderRGBA[0]); @@ -1068,17 +984,17 @@ static void RB_SurfaceCylinder( void ) verts[1].modulate[2] = (byte)(e->shaderRGBA[2]); verts[1].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( lower_points[nextSegment].xyz, verts[2].xyz ); + VectorCopy(lower_points[nextSegment].xyz, verts[2].xyz); verts[2].st[1] = 0.0f; - verts[2].st[0] = detail * ( i + 1 ); + verts[2].st[0] = detail * (i + 1); verts[2].modulate[0] = (byte)(e->shaderRGBA[0]); verts[2].modulate[1] = (byte)(e->shaderRGBA[1]); verts[2].modulate[2] = (byte)(e->shaderRGBA[2]); verts[2].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( upper_points[nextSegment].xyz, verts[3].xyz ); + VectorCopy(upper_points[nextSegment].xyz, verts[3].xyz); verts[3].st[1] = 1.0f; - verts[3].st[0] = detail * ( i + 1 ); + verts[3].st[0] = detail * (i + 1); verts[3].modulate[0] = (byte)(e->shaderRGBA[0]); verts[3].modulate[1] = (byte)(e->shaderRGBA[1]); verts[3].modulate[2] = (byte)(e->shaderRGBA[2]); @@ -1112,43 +1028,41 @@ static float Q_crandom( int *seed ) { static void CreateShape() //---------------------------------------------------------------------------- { - VectorSet( sh1, 0.66f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f, - 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f ); + VectorSet(sh1, 0.66f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f, 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f); // it seems to look best to have a point on one side of the ideal line, then the other point on the other side. - VectorSet( sh2, 0.33f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right - -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f );// up + VectorSet(sh2, 0.33f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right + -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f); // up } //---------------------------------------------------------------------------- -static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count ) +static void ApplyShape(vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count) //---------------------------------------------------------------------------- { - vec3_t point1, point2, fwd; - vec3_t rt, up; - float perc, dis; + vec3_t point1, point2, fwd; + vec3_t rt, up; + float perc, dis; - if ( count < 1 ) - { + if (count < 1) { // done recursing - DoLine2( start, end, right, sradius, eradius ); + DoLine2(start, end, right, sradius, eradius); return; } - - CreateShape(); - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ) * 0.7f; - MakeNormalVectors( fwd, rt, up ); + CreateShape(); + + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd) * 0.7f; + MakeNormalVectors(fwd, rt, up); perc = sh1[0]; - VectorScale( start, perc, point1 ); - VectorMA( point1, 1.0f - perc, end, point1 ); - VectorMA( point1, dis * sh1[1], rt, point1 ); - VectorMA( point1, dis * sh1[2], up, point1 ); + VectorScale(start, perc, point1); + VectorMA(point1, 1.0f - perc, end, point1); + VectorMA(point1, dis * sh1[1], rt, point1); + VectorMA(point1, dis * sh1[2], up, point1); // do a quick and dirty interpolation of the radius at that point float rads1, rads2; @@ -1157,104 +1071,97 @@ static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, f rads2 = sradius * 0.333f + eradius * 0.666f; // recursion - ApplyShape( start, point1, right, sradius, rads1, count - 1 ); + ApplyShape(start, point1, right, sradius, rads1, count - 1); perc = sh2[0]; - VectorScale( start, perc, point2 ); - VectorMA( point2, 1.0f - perc, end, point2 ); - VectorMA( point2, dis * sh2[1], rt, point2 ); - VectorMA( point2, dis * sh2[2], up, point2 ); - + VectorScale(start, perc, point2); + VectorMA(point2, 1.0f - perc, end, point2); + VectorMA(point2, dis * sh2[1], rt, point2); + VectorMA(point2, dis * sh2[2], up, point2); + // recursion - ApplyShape( point2, point1, right, rads1, rads2, count - 1 ); - ApplyShape( point2, end, right, rads2, eradius, count - 1 ); + ApplyShape(point2, point1, right, rads1, rads2, count - 1); + ApplyShape(point2, end, right, rads2, eradius, count - 1); } //---------------------------------------------------------------------------- -static void DoBoltSeg( vec3_t start, vec3_t end, vec3_t right, float radius ) +static void DoBoltSeg(vec3_t start, vec3_t end, vec3_t right, float radius) //---------------------------------------------------------------------------- { refEntity_t *e; vec3_t fwd, old; - vec3_t cur, off={10,10,10}; + vec3_t cur, off = {10, 10, 10}; vec3_t rt, up; vec3_t temp; - int i; - float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; + int i; + float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; e = &backEnd.currentEntity->e; - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd); + + MakeNormalVectors(fwd, rt, up); - MakeNormalVectors( fwd, rt, up ); + VectorCopy(start, old); - VectorCopy( start, old ); - oldRadius = newRadius = radius; - for ( i = 20; i <= dis; i+= 20 ) - { + for (i = 20; i <= dis; i += 20) { // because of our large step size, we may not actually draw to the end. In this case, fudge our percent so that we are basically complete - if ( i + 20 > dis ) - { + if (i + 20 > dis) { perc = 1.0f; - } - else - { + } else { // percentage of the amount of line completed perc = (float)i / dis; } // create our level of deviation for this point - VectorScale( fwd, Q_crandom(&e->frame) * 3.0f, temp ); // move less in fwd direction, chaos also does not affect this - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], rt, temp ); // move more in direction perpendicular to line, angles is really the chaos - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], up, temp ); // move more in direction perpendicular to line + VectorScale(fwd, Q_crandom(&e->frame) * 3.0f, temp); // move less in fwd direction, chaos also does not affect this + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], rt, temp); // move more in direction perpendicular to line, angles is really the chaos + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], up, temp); // move more in direction perpendicular to line // track our total level of offset from the ideal line - VectorAdd( off, temp, off ); + VectorAdd(off, temp, off); - // Move from start to end, always adding our current level of offset from the ideal line + // Move from start to end, always adding our current level of offset from the ideal line // Even though we are adding a random offset.....by nature, we always move from exactly start....to end - VectorAdd( start, off, cur ); - VectorScale( cur, 1.0f - perc, cur ); - VectorMA( cur, perc, end, cur ); + VectorAdd(start, off, cur); + VectorScale(cur, 1.0f - perc, cur); + VectorMA(cur, perc, end, cur); - if ( e->renderfx & RF_TAPERED ) - { + if (e->renderfx & RF_TAPERED) { // This does pretty close to perfect tapering since apply shape interpolates the old and new as it goes along. // by using one minus the square, the radius stays fairly constant, then drops off quickly at the very point of the bolt - oldRadius = radius * (1.0f-oldPerc*oldPerc); - newRadius = radius * (1.0f-perc*perc); + oldRadius = radius * (1.0f - oldPerc * oldPerc); + newRadius = radius * (1.0f - perc * perc); } // Apply the random shape to our line seg to give it some micro-detail-jaggy-coolness. - ApplyShape( cur, old, right, newRadius, oldRadius, LIGHTNING_RECURSION_LEVEL ); - + ApplyShape(cur, old, right, newRadius, oldRadius, LIGHTNING_RECURSION_LEVEL); + // randomly split off to create little tendrils, but don't do it too close to the end and especially if we are not even of the forked variety - if ( ( e->renderfx & RF_FORKED ) && f_count > 0 && Q_random(&e->frame) > 0.94f && radius * (1.0f - perc) > 0.2f ) - { + if ((e->renderfx & RF_FORKED) && f_count > 0 && Q_random(&e->frame) > 0.94f && radius * (1.0f - perc) > 0.2f) { vec3_t newDest; f_count--; // Pick a point somewhere between the current point and the final endpoint - VectorAdd( cur, e->oldorigin, newDest ); - VectorScale( newDest, 0.5f, newDest ); + VectorAdd(cur, e->oldorigin, newDest); + VectorScale(newDest, 0.5f, newDest); // And then add some crazy offset - for ( int t = 0; t < 3; t++ ) - { + for (int t = 0; t < 3; t++) { newDest[t] += Q_crandom(&e->frame) * 80; } // we could branch off using OLD and NEWDEST, but that would allow multiple forks...whereas, we just want simpler brancing - DoBoltSeg( cur, newDest, right, newRadius ); + DoBoltSeg(cur, newDest, right, newRadius); } // Current point along the line becomes our new old attach point - VectorCopy( cur, old ); + VectorCopy(cur, old); oldPerc = perc; } } @@ -1264,44 +1171,40 @@ static void RB_SurfaceElectricity() //------------------------------------------ { refEntity_t *e; - vec3_t right, fwd; - vec3_t start, end; - vec3_t v1, v2; - float radius, perc = 1.0f, dis; + vec3_t right, fwd; + vec3_t start, end; + vec3_t v1, v2; + float radius, perc = 1.0f, dis; e = &backEnd.currentEntity->e; radius = e->radius; - VectorCopy( e->origin, start ); + VectorCopy(e->origin, start); - VectorSubtract( e->oldorigin, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(e->oldorigin, start, fwd); + dis = VectorNormalize(fwd); // see if we should grow from start to end - if ( e->renderfx & RF_GROW ) - { - perc = 1.0f - ( e->axis[0][2]/*endTime*/ - tr.refdef.time ) / e->axis[0][1]/*duration*/; + if (e->renderfx & RF_GROW) { + perc = 1.0f - (e->axis[0][2] /*endTime*/ - tr.refdef.time) / e->axis[0][1] /*duration*/; - if ( perc > 1.0f ) - { + if (perc > 1.0f) { perc = 1.0f; - } - else if ( perc < 0.0f ) - { + } else if (perc < 0.0f) { perc = 0.0f; } } - VectorMA( start, perc * dis, fwd, e->oldorigin ); - VectorCopy( e->oldorigin, end ); + VectorMA(start, perc * dis, fwd, e->oldorigin); + VectorCopy(e->oldorigin, end); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); - DoBoltSeg( start, end, right, radius ); + DoBoltSeg(start, end, right, radius); } //================================================================================ @@ -1316,7 +1219,7 @@ static void RB_SurfaceElectricity() static void VectorArrayNormalize(vec4_t *normals, unsigned int count) { // assert(count); - + #if idppc { register float half = 0.5; @@ -1364,8 +1267,6 @@ static void VectorArrayNormalize(vec4_t *normals, unsigned int count) } #endif - - /* ** LerpMeshVertexes */ @@ -1501,8 +1402,7 @@ static void LerpMeshVertexes_altivec(md3Surface_t *surf, float backlerp) #endif #endif -static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) -{ +static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) { #if 0 short *oldXyz, *newXyz, *oldNormals, *newNormals; float *outXyz, *outNormal; @@ -1602,24 +1502,22 @@ static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) float *outXyz; uint32_t *outNormal; mdvVertex_t *newVerts; - int vertNum; + int vertNum; newVerts = surf->verts + backEnd.currentEntity->e.frame * surf->numVerts; - outXyz = tess.xyz[tess.numVertexes]; + outXyz = tess.xyz[tess.numVertexes]; outNormal = &tess.normal[tess.numVertexes]; - if (backlerp == 0) - { + if (backlerp == 0) { // // just copy the vertexes // - for (vertNum=0 ; vertNum < surf->numVerts ; vertNum++) - { + for (vertNum = 0; vertNum < surf->numVerts; vertNum++) { vec3_t normal; - VectorCopy(newVerts->xyz, outXyz); + VectorCopy(newVerts->xyz, outXyz); VectorCopy(newVerts->normal, normal); *outNormal = R_VboPackNormal(normal); @@ -1628,9 +1526,7 @@ static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) outXyz += 4; outNormal++; } - } - else - { + } else { // // interpolate and copy the vertex and normal // @@ -1639,11 +1535,10 @@ static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) oldVerts = surf->verts + backEnd.currentEntity->e.oldframe * surf->numVerts; - for (vertNum=0 ; vertNum < surf->numVerts ; vertNum++) - { + for (vertNum = 0; vertNum < surf->numVerts; vertNum++) { vec3_t normal; - VectorLerp(newVerts->xyz, oldVerts->xyz, backlerp, outXyz); + VectorLerp(newVerts->xyz, oldVerts->xyz, backlerp, outXyz); VectorLerp(newVerts->normal, oldVerts->normal, backlerp, normal); VectorNormalize(normal); @@ -1655,11 +1550,9 @@ static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) outNormal++; } } - } -static void LerpMeshVertexes(mdvSurface_t *surf, float backlerp) -{ +static void LerpMeshVertexes(mdvSurface_t *surf, float backlerp) { #if 0 #if idppc_altivec if (com_altivec->integer) { @@ -1669,35 +1562,34 @@ static void LerpMeshVertexes(mdvSurface_t *surf, float backlerp) } #endif // idppc_altivec #endif - LerpMeshVertexes_scalar( surf, backlerp ); + LerpMeshVertexes_scalar(surf, backlerp); } - /* ============= RB_SurfaceMesh ============= */ static void RB_SurfaceMesh(mdvSurface_t *surface) { - int j; - float backlerp; - mdvSt_t *texCoords; - int Bob, Doug; - int numVerts; + int j; + float backlerp; + mdvSt_t *texCoords; + int Bob, Doug; + int numVerts; - if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) { + if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) { backlerp = 0; - } else { + } else { backlerp = backEnd.currentEntity->e.backlerp; } - RB_CHECKOVERFLOW( surface->numVerts, surface->numIndexes ); + RB_CHECKOVERFLOW(surface->numVerts, surface->numIndexes); - LerpMeshVertexes (surface, backlerp); + LerpMeshVertexes(surface, backlerp); Bob = tess.numIndexes; Doug = tess.numVertexes; - for (j = 0 ; j < surface->numIndexes ; j++) { + for (j = 0; j < surface->numIndexes; j++) { tess.indexes[Bob + j] = Doug + surface->indexes[j]; } tess.numIndexes += surface->numIndexes; @@ -1705,58 +1597,50 @@ static void RB_SurfaceMesh(mdvSurface_t *surface) { texCoords = surface->st; numVerts = surface->numVerts; - for ( j = 0; j < numVerts; j++ ) { + for (j = 0; j < numVerts; j++) { tess.texCoords[Doug + j][0][0] = texCoords[j].st[0]; tess.texCoords[Doug + j][0][1] = texCoords[j].st[1]; // FIXME: fill in lightmapST for completeness? } tess.numVertexes += surface->numVerts; - } - /* ============== RB_SurfaceFace ============== */ -static void RB_SurfaceBSPFace( srfBspSurface_t *srf ) { - if( RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, - srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) - { +static void RB_SurfaceBSPFace(srfBspSurface_t *srf) { + if (RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, + qtrue)) { return; } - RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, - srf->indexes, srf->dlightBits, srf->pshadowBits); + RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, srf->indexes, srf->dlightBits, srf->pshadowBits); } - -static float LodErrorForVolume( vec3_t local, float radius ) { - vec3_t world; - float d; +static float LodErrorForVolume(vec3_t local, float radius) { + vec3_t world; + float d; // never let it go negative - if ( r_lodCurveError->value < 0 ) { + if (r_lodCurveError->value < 0) { return 0; } - world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + - local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; - world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + - local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; - world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + - local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; + world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; + world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; + world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; - VectorSubtract( world, backEnd.viewParms.ori.origin, world ); - d = DotProduct( world, backEnd.viewParms.ori.axis[0] ); + VectorSubtract(world, backEnd.viewParms.ori.origin, world); + d = DotProduct(world, backEnd.viewParms.ori.axis[0]); - if ( d < 0 ) { + if (d < 0) { d = -d; } d -= radius; - if ( d < 1 ) { + if (d < 1) { d = 1; } @@ -1770,29 +1654,28 @@ RB_SurfaceGrid Just copy the grid of points and triangulate ============= */ -static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { - int i, j; - float *xyz; - float *texCoords, *lightCoords[MAXLIGHTMAPS]; +static void RB_SurfaceBSPGrid(srfBspSurface_t *srf) { + int i, j; + float *xyz; + float *texCoords, *lightCoords[MAXLIGHTMAPS]; uint32_t *normal; uint32_t *tangent; - float *color; + float *color; uint32_t *lightdir; - srfVert_t *dv; - int rows, irows, vrows; - int used; - int widthTable[MAX_GRID_SIZE]; - int heightTable[MAX_GRID_SIZE]; - float lodError; - int lodWidth, lodHeight; - int numVertexes; - int dlightBits; - int pshadowBits; - //int *vDlightBits; - - if( RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, - srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) - { + srfVert_t *dv; + int rows, irows, vrows; + int used; + int widthTable[MAX_GRID_SIZE]; + int heightTable[MAX_GRID_SIZE]; + float lodError; + int lodWidth, lodHeight; + int numVertexes; + int dlightBits; + int pshadowBits; + // int *vDlightBits; + + if (RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, + qtrue)) { return; } @@ -1803,57 +1686,56 @@ static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { tess.pshadowBits |= pshadowBits; // determine the allowable discrepance - lodError = LodErrorForVolume( srf->lodOrigin, srf->lodRadius ); + lodError = LodErrorForVolume(srf->lodOrigin, srf->lodRadius); // determine which rows and columns of the subdivision // we are actually going to use widthTable[0] = 0; lodWidth = 1; - for ( i = 1 ; i < srf->width-1 ; i++ ) { - if ( srf->widthLodError[i] <= lodError ) { + for (i = 1; i < srf->width - 1; i++) { + if (srf->widthLodError[i] <= lodError) { widthTable[lodWidth] = i; lodWidth++; } } - widthTable[lodWidth] = srf->width-1; + widthTable[lodWidth] = srf->width - 1; lodWidth++; heightTable[0] = 0; lodHeight = 1; - for ( i = 1 ; i < srf->height-1 ; i++ ) { - if ( srf->heightLodError[i] <= lodError ) { + for (i = 1; i < srf->height - 1; i++) { + if (srf->heightLodError[i] <= lodError) { heightTable[lodHeight] = i; lodHeight++; } } - heightTable[lodHeight] = srf->height-1; + heightTable[lodHeight] = srf->height - 1; lodHeight++; - // very large grids may have more points or indexes than can be fit // in the tess structure, so we may have to issue it in multiple passes used = 0; - while ( used < lodHeight - 1 ) { + while (used < lodHeight - 1) { // see how many rows of both verts and indexes we can add without overflowing do { - vrows = ( SHADER_MAX_VERTEXES - tess.numVertexes ) / lodWidth; - irows = ( SHADER_MAX_INDEXES - tess.numIndexes ) / ( lodWidth * 6 ); + vrows = (SHADER_MAX_VERTEXES - tess.numVertexes) / lodWidth; + irows = (SHADER_MAX_INDEXES - tess.numIndexes) / (lodWidth * 6); // if we don't have enough space for at least one strip, flush the buffer - if ( vrows < 2 || irows < 1 ) { + if (vrows < 2 || irows < 1) { RB_EndSurface(); - RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex); } else { break; } - } while ( 1 ); - + } while (1); + rows = irows; - if ( vrows < irows + 1 ) { + if (vrows < irows + 1) { rows = vrows - 1; } - if ( used + rows > lodHeight ) { + if (used + rows > lodHeight) { rows = lodHeight - used; } @@ -1867,52 +1749,43 @@ static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { lightCoords[tc] = tess.texCoords[numVertexes][1 + tc]; color = tess.vertexColors[numVertexes]; lightdir = &tess.lightdir[numVertexes]; - //vDlightBits = &tess.vertexDlightBits[numVertexes]; + // vDlightBits = &tess.vertexDlightBits[numVertexes]; - for ( i = 0 ; i < rows ; i++ ) { - for ( j = 0 ; j < lodWidth ; j++ ) { - dv = srf->verts + heightTable[ used + i ] * srf->width - + widthTable[ j ]; + for (i = 0; i < rows; i++) { + for (j = 0; j < lodWidth; j++) { + dv = srf->verts + heightTable[used + i] * srf->width + widthTable[j]; - if ( tess.shader->vertexAttribs & ATTR_POSITION ) - { + if (tess.shader->vertexAttribs & ATTR_POSITION) { VectorCopy(dv->xyz, xyz); xyz += 4; } - if ( tess.shader->vertexAttribs & ATTR_NORMAL ) - { + if (tess.shader->vertexAttribs & ATTR_NORMAL) { *normal++ = R_VboPackNormal(dv->normal); } - if ( tess.shader->vertexAttribs & ATTR_TANGENT ) - { + if (tess.shader->vertexAttribs & ATTR_TANGENT) { *tangent++ = R_VboPackTangent(dv->tangent); } - if ( tess.shader->vertexAttribs & ATTR_TEXCOORD0 ) - { + if (tess.shader->vertexAttribs & ATTR_TEXCOORD0) { VectorCopy2(dv->st, texCoords); - texCoords += NUM_TESS_TEXCOORDS*2; + texCoords += NUM_TESS_TEXCOORDS * 2; } - for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) - { - if ( tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc) ) - { + for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) { + if (tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc)) { VectorCopy2(dv->lightmap[tc], lightCoords[tc]); - lightCoords[tc] += NUM_TESS_TEXCOORDS*2; + lightCoords[tc] += NUM_TESS_TEXCOORDS * 2; } } - if ( tess.shader->vertexAttribs & ATTR_COLOR ) - { + if (tess.shader->vertexAttribs & ATTR_COLOR) { VectorCopy4(dv->vertexColors[0], color); color += 4; } - if ( tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION ) - { + if (tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION) { *lightdir++ = R_VboPackNormal(dv->lightdir); } @@ -1920,32 +1793,31 @@ static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { } } - // add the indexes { - int numIndexes; - int w, h; + int numIndexes; + int w, h; h = rows - 1; w = lodWidth - 1; numIndexes = tess.numIndexes; - for (i = 0 ; i < h ; i++) { - for (j = 0 ; j < w ; j++) { - int v1, v2, v3, v4; - + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) { + int v1, v2, v3, v4; + // vertex order to be reckognized as tristrips - v1 = numVertexes + i*lodWidth + j + 1; + v1 = numVertexes + i * lodWidth + j + 1; v2 = v1 - 1; v3 = v2 + lodWidth; v4 = v3 + 1; tess.indexes[numIndexes] = v2; - tess.indexes[numIndexes+1] = v3; - tess.indexes[numIndexes+2] = v1; - - tess.indexes[numIndexes+3] = v1; - tess.indexes[numIndexes+4] = v3; - tess.indexes[numIndexes+5] = v4; + tess.indexes[numIndexes + 1] = v3; + tess.indexes[numIndexes + 2] = v1; + + tess.indexes[numIndexes + 3] = v1; + tess.indexes[numIndexes + 4] = v3; + tess.indexes[numIndexes + 5] = v4; numIndexes += 6; } } @@ -1959,7 +1831,6 @@ static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { } } - /* =========================================================================== @@ -1975,7 +1846,7 @@ RB_SurfaceAxis Draws x/y/z lines from the origin for orientation debugging =================== */ -static void RB_SurfaceAxis( void ) { +static void RB_SurfaceAxis(void) { // FIXME: implement this #if 0 GL_Bind( tr.whiteImage ); @@ -2005,8 +1876,8 @@ RB_SurfaceEntity Entities that have a single procedurally generated surface ==================== */ -static void RB_SurfaceEntity( surfaceType_t *surfType ) { - switch( backEnd.currentEntity->e.reType ) { +static void RB_SurfaceEntity(surfaceType_t *surfType) { + switch (backEnd.currentEntity->e.reType) { case RT_SPRITE: RB_SurfaceSprite(); break; @@ -2031,30 +1902,27 @@ static void RB_SurfaceEntity( surfaceType_t *surfType ) { case RT_CYLINDER: RB_SurfaceCylinder(); break; - case RT_ENT_CHAIN: - { - static trRefEntity_t tempEnt = *backEnd.currentEntity; + case RT_ENT_CHAIN: { + static trRefEntity_t tempEnt = *backEnd.currentEntity; - //rww - if not static then currentEntity is garbage because - //this is a local. This was not static in sof2.. but I guess - //they never check ce.renderfx so it didn't show up. + // rww - if not static then currentEntity is garbage because + // this is a local. This was not static in sof2.. but I guess + // they never check ce.renderfx so it didn't show up. - const int start = backEnd.currentEntity->e.uRefEnt.uMini.miniStart; - const int count = backEnd.currentEntity->e.uRefEnt.uMini.miniCount; - assert(count > 0); - backEnd.currentEntity = &tempEnt; - - assert(backEnd.currentEntity->e.renderfx >= 0); + const int start = backEnd.currentEntity->e.uRefEnt.uMini.miniStart; + const int count = backEnd.currentEntity->e.uRefEnt.uMini.miniCount; + assert(count > 0); + backEnd.currentEntity = &tempEnt; - for (int i = 0, j = start; i < count; i++, j++) - { - backEnd.currentEntity->e = backEnd.refdef.entities[j].e; - assert(backEnd.currentEntity->e.renderfx >= 0); + assert(backEnd.currentEntity->e.renderfx >= 0); - RB_SurfaceEntity(surfType); - } + for (int i = 0, j = start; i < count; i++, j++) { + backEnd.currentEntity->e = backEnd.refdef.entities[j].e; + assert(backEnd.currentEntity->e.renderfx >= 0); + + RB_SurfaceEntity(surfType); } - break; + } break; default: RB_SurfaceAxis(); break; @@ -2063,38 +1931,31 @@ static void RB_SurfaceEntity( surfaceType_t *surfType ) { tess.shader->entityMergable = qtrue; } -static void RB_SurfaceBad( surfaceType_t *surfType ) { - ri.Printf( PRINT_ALL, "Bad surface tesselated.\n" ); -} +static void RB_SurfaceBad(surfaceType_t *surfType) { ri.Printf(PRINT_ALL, "Bad surface tesselated.\n"); } -static void RB_SurfaceFlare(srfFlare_t *surf) -{ +static void RB_SurfaceFlare(srfFlare_t *surf) { if (r_flares->integer) RB_AddFlare(surf, tess.fogNum, surf->origin, surf->color, surf->normal); } -static void RB_SurfaceVBOMesh(srfBspSurface_t * srf) -{ - RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, - srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qfalse ); +static void RB_SurfaceVBOMesh(srfBspSurface_t *srf) { + RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qfalse); } -void RB_SurfaceVBOMDVMesh(srfVBOMDVMesh_t * surface) -{ +void RB_SurfaceVBOMDVMesh(srfVBOMDVMesh_t *surface) { int i, mergeForward, mergeBack; GLvoid *firstIndexOffset, *lastIndexOffset; GLimp_LogComment("--- RB_SurfaceVBOMDVMesh ---\n"); - if(!surface->vbo || !surface->ibo) + if (!surface->vbo || !surface->ibo) return; - if (glState.currentVBO != surface->vbo) - { + if (glState.currentVBO != surface->vbo) { RB_EndSurface(); } - //drawSurf_t drawSurf = + // drawSurf_t drawSurf = R_BindVBO(surface->vbo); R_BindIBO(surface->ibo); @@ -2110,67 +1971,53 @@ void RB_SurfaceVBOMDVMesh(srfVBOMDVMesh_t * surface) firstIndexOffset = BUFFER_OFFSET(surface->indexOffset * sizeof(glIndex_t)); lastIndexOffset = BUFFER_OFFSET(surface->numIndexes * sizeof(glIndex_t)); - if (r_mergeMultidraws->integer) - { + if (r_mergeMultidraws->integer) { i = 0; - if (r_mergeMultidraws->integer == 1) - { + if (r_mergeMultidraws->integer == 1) { // lazy merge, only check the last primitive - if (tess.multiDrawPrimitives) - { + if (tess.multiDrawPrimitives) { i = tess.multiDrawPrimitives - 1; } } - for (; i < tess.multiDrawPrimitives; i++) - { - if (tess.multiDrawLastIndex[i] == firstIndexOffset) - { + for (; i < tess.multiDrawPrimitives; i++) { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) { mergeBack = i; } - if (lastIndexOffset == tess.multiDrawFirstIndex[i]) - { + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) { mergeForward = i; } } } - if (mergeBack != -1 && mergeForward == -1) - { + if (mergeBack != -1 && mergeForward == -1) { tess.multiDrawNumIndexes[mergeBack] += surface->numIndexes; tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], surface->minIndex); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], surface->maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack == -1 && mergeForward != -1) - { + } else if (mergeBack == -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeForward] += surface->numIndexes; tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], surface->minIndex); tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], surface->maxIndex); backEnd.pc.c_multidrawsMerged++; - } - else if (mergeBack != -1 && mergeForward != -1) - { + } else if (mergeBack != -1 && mergeForward != -1) { tess.multiDrawNumIndexes[mergeBack] += surface->numIndexes + tess.multiDrawNumIndexes[mergeForward]; tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], surface->minIndex)); tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], surface->maxIndex)); tess.multiDrawPrimitives--; - if (mergeForward != tess.multiDrawPrimitives) - { + if (mergeForward != tess.multiDrawPrimitives) { tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; } backEnd.pc.c_multidrawsMerged += 2; - } - else if (mergeBack == -1 && mergeForward == -1) - { + } else if (mergeBack == -1 && mergeForward == -1) { tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = surface->numIndexes; tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; @@ -2185,19 +2032,17 @@ void RB_SurfaceVBOMDVMesh(srfVBOMDVMesh_t * surface) tess.numVertexes += surface->numVerts; } -static void RB_SurfaceSkip( void *surf ) { -} +static void RB_SurfaceSkip(void *surf) {} -static void RB_SurfaceSprites( srfSprites_t *surf ) -{ - if ( !r_surfaceSprites->integer || surf->numSprites == 0) +static void RB_SurfaceSprites(srfSprites_t *surf) { + if (!r_surfaceSprites->integer || surf->numSprites == 0) return; RB_EndSurface(); // TODO: Do we want a 2-level lod system where far away sprites are // just flat surfaces? - + // TODO: Check which pass (z-prepass/shadow/forward) we're rendering for? shader_t *shader = surf->shader; shaderStage_t *firstStage = shader->stages[0]; @@ -2205,10 +2050,10 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) const surfaceSprite_t *ss = surf->sprite; uint32_t shaderFlags = 0; - if ( surf->alphaTestType != ALPHA_TEST_NONE ) + if (surf->alphaTestType != ALPHA_TEST_NONE) shaderFlags |= SSDEF_ALPHA_TEST; - if ( ss->type == SURFSPRITE_ORIENTED ) + if (ss->type == SURFSPRITE_ORIENTED) shaderFlags |= SSDEF_FACE_CAMERA; if (ss->facing == SURFSPRITE_FACING_UP) @@ -2220,7 +2065,7 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) if (ss->type == SURFSPRITE_EFFECT || ss->type == SURFSPRITE_WEATHERFX) shaderFlags |= SSDEF_FX_SPRITE; - if ((firstStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) + if ((firstStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) shaderFlags |= SSDEF_ADDITIVE; if (surf->fogIndex > 0 && r_drawfog->integer) @@ -2231,46 +2076,40 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) UniformDataWriter uniformDataWriter; uniformDataWriter.Start(program); - + // FIXME: Use entity block for this - uniformDataWriter.SetUniformMatrix4x4( - UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + uniformDataWriter.SetUniformMatrix4x4(UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); - uniformDataWriter.SetUniformInt( - UNIFORM_ALPHA_TEST_TYPE, surf->alphaTestType); + uniformDataWriter.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, surf->alphaTestType); if (surf->fogIndex != -1) uniformDataWriter.SetUniformInt(UNIFORM_FOGINDEX, surf->fogIndex - 1); - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; SamplerBindingsWriter samplerBindingsWriter; samplerBindingsWriter.AddAnimatedImage(&firstStage->bundle[0], TB_COLORMAP); const GLuint currentFrameUbo = backEndData->currentFrame->ubo; const GLuint currentSpriteUbo = shader->spriteUbo; - const UniformBlockBinding uniformBlockBindings[] = { - { currentSpriteUbo, ss->spriteUboOffset, UNIFORM_BLOCK_SURFACESPRITE }, - { currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE }, - { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA }, - { currentFrameUbo, tr.fogsUboOffset, UNIFORM_BLOCK_FOGS } - }; + const UniformBlockBinding uniformBlockBindings[] = {{currentSpriteUbo, ss->spriteUboOffset, UNIFORM_BLOCK_SURFACESPRITE}, + {currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE}, + {currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA}, + {currentFrameUbo, tr.fogsUboOffset, UNIFORM_BLOCK_FOGS}}; uint32_t numBindings; UniformData *spriteUniformData = uniformDataWriter.Finish(frameAllocator); - SamplerBinding *spriteSamplerBinding = samplerBindingsWriter.Finish( - frameAllocator, &numBindings); + SamplerBinding *spriteSamplerBinding = samplerBindingsWriter.Finish(frameAllocator, &numBindings); int numDrawIndicesUndrawn = surf->numIndices; int baseVertex = surf->baseVertex; - while (numDrawIndicesUndrawn > 5) - { + while (numDrawIndicesUndrawn > 5) { int drawIndices = numDrawIndicesUndrawn > 98298 ? 98298 : numDrawIndicesUndrawn; DrawItem item = {}; item.renderState.stateBits = firstStage->stateBits; item.renderState.cullType = CT_TWO_SIDED; - item.renderState.depthRange = DepthRange{ 0.0f, 1.0f }; + item.renderState.depthRange = DepthRange{0.0f, 1.0f}; item.program = program; item.ibo = surf->ibo; @@ -2279,10 +2118,8 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) item.samplerBindings = spriteSamplerBinding; item.numSamplerBindings = numBindings; - DrawItemSetVertexAttributes( - item, surf->attributes, surf->numAttributes, frameAllocator); - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + DrawItemSetVertexAttributes(item, surf->attributes, surf->numAttributes, frameAllocator); + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); item.draw.type = DRAW_COMMAND_INDEXED; item.draw.primitiveType = GL_TRIANGLES; @@ -2294,7 +2131,7 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) tess.externalIBO = surf->ibo; - uint32_t RB_CreateSortKey(const DrawItem& item, int stage, int layer); + uint32_t RB_CreateSortKey(const DrawItem &item, int stage, int layer); uint32_t key = RB_CreateSortKey(item, 0, surf->shader->sort); RB_AddDrawItem(backEndData->currentPass, key, item); @@ -2303,21 +2140,21 @@ static void RB_SurfaceSprites( srfSprites_t *surf ) } } -void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])( void *) = { - (void(*)(void*))RB_SurfaceBad, // SF_BAD, - (void(*)(void*))RB_SurfaceSkip, // SF_SKIP, - (void(*)(void*))RB_SurfaceBSPFace, // SF_FACE, - (void(*)(void*))RB_SurfaceBSPGrid, // SF_GRID, - (void(*)(void*))RB_SurfaceBSPTriangles, // SF_TRIANGLES, - (void(*)(void*))RB_SurfacePolychain, // SF_POLY, - (void(*)(void*))RB_SurfaceMesh, // SF_MDV, - (void(*)(void*))RB_MDRSurfaceAnim, // SF_MDR, - (void(*)(void*))RB_IQMSurfaceAnim, // SF_IQM, - (void(*)(void*))RB_SurfaceGhoul, // SF_MDX, - (void(*)(void*))RB_SurfaceFlare, // SF_FLARE, - (void(*)(void*))RB_SurfaceEntity, // SF_ENTITY - (void(*)(void*))RB_SurfaceVBOMesh, // SF_VBO_MESH, - (void(*)(void*))RB_SurfaceVBOMDVMesh, // SF_VBO_MDVMESH - (void(*)(void*))RB_SurfaceSprites, // SF_SPRITES - (void(*)(void*))RB_SurfaceWeather, // SF_WEATHER +void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *) = { + (void (*)(void *))RB_SurfaceBad, // SF_BAD, + (void (*)(void *))RB_SurfaceSkip, // SF_SKIP, + (void (*)(void *))RB_SurfaceBSPFace, // SF_FACE, + (void (*)(void *))RB_SurfaceBSPGrid, // SF_GRID, + (void (*)(void *))RB_SurfaceBSPTriangles, // SF_TRIANGLES, + (void (*)(void *))RB_SurfacePolychain, // SF_POLY, + (void (*)(void *))RB_SurfaceMesh, // SF_MDV, + (void (*)(void *))RB_MDRSurfaceAnim, // SF_MDR, + (void (*)(void *))RB_IQMSurfaceAnim, // SF_IQM, + (void (*)(void *))RB_SurfaceGhoul, // SF_MDX, + (void (*)(void *))RB_SurfaceFlare, // SF_FLARE, + (void (*)(void *))RB_SurfaceEntity, // SF_ENTITY + (void (*)(void *))RB_SurfaceVBOMesh, // SF_VBO_MESH, + (void (*)(void *))RB_SurfaceVBOMDVMesh, // SF_VBO_MDVMESH + (void (*)(void *))RB_SurfaceSprites, // SF_SPRITES + (void (*)(void *))RB_SurfaceWeather, // SF_WEATHER }; diff --git a/codemp/rd-rend2/tr_tangentspace.cpp b/codemp/rd-rend2/tr_tangentspace.cpp index 0c523784e6..a14df0aff3 100644 --- a/codemp/rd-rend2/tr_tangentspace.cpp +++ b/codemp/rd-rend2/tr_tangentspace.cpp @@ -21,7 +21,6 @@ along with this program; if not, see . #include "tr_local.h" #include "MikkTSpace/mikktspace.h" - /* ================ R_FixMikktVertIndex @@ -33,83 +32,72 @@ Change when mesh importers swaps different indices! (modelling tool standard is backface culling vs frontface culling in id tech 3) ================ */ -int R_FixMikktVertIndex(const int index) -{ - switch (index % 3) - { - case 2: return 1; - case 1: return 2; - default: return index; +int R_FixMikktVertIndex(const int index) { + switch (index % 3) { + case 2: + return 1; + case 1: + return 2; + default: + return index; } return index; } -struct BspMeshData -{ +struct BspMeshData { int numSurfaces; packedVertex_t *vertices; glIndex_t *indices; }; -int R_GetNumFaces(const SMikkTSpaceContext * pContext) -{ +int R_GetNumFaces(const SMikkTSpaceContext *pContext) { BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; return meshData->numSurfaces; } -int R_GetNumVertices(const SMikkTSpaceContext * pContext, const int iFace) -{ - return 3; -} +int R_GetNumVertices(const SMikkTSpaceContext *pContext, const int iFace) { return 3; } -void R_GetBSPPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) -{ +void R_GetBSPPosition(const SMikkTSpaceContext *pContext, float *fvPosOut, const int iFace, const int iVert) { BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - packedVertex_t& vertex = meshData->vertices[index]; + packedVertex_t &vertex = meshData->vertices[index]; fvPosOut[0] = vertex.position[0]; fvPosOut[1] = vertex.position[1]; fvPosOut[2] = vertex.position[2]; } -void R_GetNormalBSPSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) -{ +void R_GetNormalBSPSurface(const SMikkTSpaceContext *pContext, float *fvNormOut, const int iFace, const int iVert) { BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - packedVertex_t& vertex = meshData->vertices[index]; + packedVertex_t &vertex = meshData->vertices[index]; fvNormOut[0] = ((vertex.normal) & 0x3ff) * 1.0f / 511.5f - 1.0f; fvNormOut[1] = ((vertex.normal >> 10) & 0x3ff) * 1.0f / 511.5f - 1.0f; fvNormOut[2] = ((vertex.normal >> 20) & 0x3ff) * 1.0f / 511.5f - 1.0f; } -void R_GetBSPTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) -{ +void R_GetBSPTexCoord(const SMikkTSpaceContext *pContext, float *fvTexcOut, const int iFace, const int iVert) { BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - packedVertex_t& vertex = meshData->vertices[index]; + packedVertex_t &vertex = meshData->vertices[index]; fvTexcOut[0] = vertex.texcoords[0][0]; fvTexcOut[1] = vertex.texcoords[0][1]; } -void R_SetBSPTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) -{ +void R_SetBSPTSpaceBasic(const SMikkTSpaceContext *pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) { BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - packedVertex_t& vertex = meshData->vertices[index]; + packedVertex_t &vertex = meshData->vertices[index]; if (vertex.tangent == 0u) - vertex.tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) - | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) - | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) - | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); + vertex.tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) | + (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); } -void R_CalcMikkTSpaceBSPSurface(int numSurfaces, packedVertex_t *vertices, glIndex_t *indices) -{ +void R_CalcMikkTSpaceBSPSurface(int numSurfaces, packedVertex_t *vertices, glIndex_t *indices) { SMikkTSpaceInterface tangentSpaceInterface; tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; @@ -132,8 +120,7 @@ void R_CalcMikkTSpaceBSPSurface(int numSurfaces, packedVertex_t *vertices, glInd genTangSpaceDefault(&modelContext); } -struct ModelMeshData -{ +struct ModelMeshData { int numSurfaces; mdvVertex_t *verts; uint32_t *tangents; @@ -141,8 +128,7 @@ struct ModelMeshData glIndex_t *indices; }; -void R_GetModelPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) -{ +void R_GetModelPosition(const SMikkTSpaceContext *pContext, float *fvPosOut, const int iFace, const int iVert) { ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; @@ -151,8 +137,7 @@ void R_GetModelPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, co fvPosOut[2] = meshData->verts[index].xyz[2]; } -void R_GetNormalModelSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) -{ +void R_GetNormalModelSurface(const SMikkTSpaceContext *pContext, float *fvNormOut, const int iFace, const int iVert) { ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; @@ -162,8 +147,7 @@ void R_GetNormalModelSurface(const SMikkTSpaceContext * pContext, float *fvNormO fvNormOut[2] = meshData->verts[index].normal[2]; } -void R_GetModelTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) -{ +void R_GetModelTexCoord(const SMikkTSpaceContext *pContext, float *fvTexcOut, const int iFace, const int iVert) { ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; @@ -171,22 +155,17 @@ void R_GetModelTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, c fvTexcOut[1] = meshData->texcoords[index].st[1]; } -void R_SetModelTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) -{ +void R_SetModelTSpaceBasic(const SMikkTSpaceContext *pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) { ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - uint32_t& tangent = meshData->tangents[index]; - tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) - | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) - | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) - | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); - + uint32_t &tangent = meshData->tangents[index]; + tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) | + (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); } -void R_CalcMikkTSpaceMD3Surface(int numSurfaces, mdvVertex_t *verts, uint32_t *tangents, mdvSt_t *texcoords, glIndex_t *indices) -{ +void R_CalcMikkTSpaceMD3Surface(int numSurfaces, mdvVertex_t *verts, uint32_t *tangents, mdvSt_t *texcoords, glIndex_t *indices) { SMikkTSpaceInterface tangentSpaceInterface; tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; tangentSpaceInterface.m_getNumVerticesOfFace = R_GetNumVertices; @@ -209,8 +188,7 @@ void R_CalcMikkTSpaceMD3Surface(int numSurfaces, mdvVertex_t *verts, uint32_t *t genTangSpaceDefault(&modelContext); } -struct GlmMeshData -{ +struct GlmMeshData { int numSurfaces; mdxmVertex_t *vertices; mdxmVertexTexCoord_t *tcs; @@ -218,54 +196,47 @@ struct GlmMeshData glIndex_t *indices; }; -void R_GetGlmPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) -{ +void R_GetGlmPosition(const SMikkTSpaceContext *pContext, float *fvPosOut, const int iFace, const int iVert) { GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - mdxmVertex_t& vertex = meshData->vertices[index]; + mdxmVertex_t &vertex = meshData->vertices[index]; fvPosOut[0] = vertex.vertCoords[0]; fvPosOut[1] = vertex.vertCoords[1]; fvPosOut[2] = vertex.vertCoords[2]; } -void R_GetNormalGlmSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) -{ +void R_GetNormalGlmSurface(const SMikkTSpaceContext *pContext, float *fvNormOut, const int iFace, const int iVert) { GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - mdxmVertex_t& vertex = meshData->vertices[index]; + mdxmVertex_t &vertex = meshData->vertices[index]; fvNormOut[0] = vertex.normal[0]; fvNormOut[1] = vertex.normal[1]; fvNormOut[2] = vertex.normal[2]; } -void R_GetGlmTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) -{ +void R_GetGlmTexCoord(const SMikkTSpaceContext *pContext, float *fvTexcOut, const int iFace, const int iVert) { GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - mdxmVertexTexCoord_t& tcs = meshData->tcs[index]; + mdxmVertexTexCoord_t &tcs = meshData->tcs[index]; fvTexcOut[0] = tcs.texCoords[0]; fvTexcOut[1] = tcs.texCoords[1]; } -void R_SetGlmTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) -{ +void R_SetGlmTSpaceBasic(const SMikkTSpaceContext *pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) { GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; const int vert_index = R_FixMikktVertIndex(iVert); glIndex_t index = meshData->indices[iFace * 3 + vert_index]; - uint32_t& tangent = meshData->tangents[index]; + uint32_t &tangent = meshData->tangents[index]; - tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) - | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) - | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) - | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); + tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) | + (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); } -void R_CalcMikkTSpaceGlmSurface(int numSurfaces, mdxmVertex_t *vertices, mdxmVertexTexCoord_t *textureCoordinates, uint32_t *tangents, glIndex_t *indices) -{ +void R_CalcMikkTSpaceGlmSurface(int numSurfaces, mdxmVertex_t *vertices, mdxmVertexTexCoord_t *textureCoordinates, uint32_t *tangents, glIndex_t *indices) { SMikkTSpaceInterface tangentSpaceInterface; tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; diff --git a/codemp/rd-rend2/tr_vbo.cpp b/codemp/rd-rend2/tr_vbo.cpp index 4025bd31d5..ef17e8f748 100644 --- a/codemp/rd-rend2/tr_vbo.cpp +++ b/codemp/rd-rend2/tr_vbo.cpp @@ -26,53 +26,42 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "G2_gore_r2.h" #endif - -uint32_t R_VboPackTangent(vec4_t v) -{ - return (((uint32_t)(v[3] * 1.5f + 2.0f )) << 30) - | (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) - | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) - | (((uint32_t)(v[0] * 511.5f + 512.0f))); +uint32_t R_VboPackTangent(vec4_t v) { + return (((uint32_t)(v[3] * 1.5f + 2.0f)) << 30) | (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) | + (((uint32_t)(v[0] * 511.5f + 512.0f))); } -uint32_t R_VboPackNormal(vec3_t v) -{ - return (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) - | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) - | (((uint32_t)(v[0] * 511.5f + 512.0f))); +uint32_t R_VboPackNormal(vec3_t v) { + return (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) | (((uint32_t)(v[0] * 511.5f + 512.0f))); } -void R_VboUnpackTangent(vec4_t v, uint32_t b) -{ - v[0] = ((b) & 0x3ff) * 1.0f/511.5f - 1.0f; - v[1] = ((b >> 10) & 0x3ff) * 1.0f/511.5f - 1.0f; - v[2] = ((b >> 20) & 0x3ff) * 1.0f/511.5f - 1.0f; - v[3] = ((b >> 30) & 0x3) * 1.0f/1.5f - 1.0f; +void R_VboUnpackTangent(vec4_t v, uint32_t b) { + v[0] = ((b)&0x3ff) * 1.0f / 511.5f - 1.0f; + v[1] = ((b >> 10) & 0x3ff) * 1.0f / 511.5f - 1.0f; + v[2] = ((b >> 20) & 0x3ff) * 1.0f / 511.5f - 1.0f; + v[3] = ((b >> 30) & 0x3) * 1.0f / 1.5f - 1.0f; } -void R_VboUnpackNormal(vec3_t v, uint32_t b) -{ - v[0] = ((b) & 0x3ff) * 1.0f/511.5f - 1.0f; - v[1] = ((b >> 10) & 0x3ff) * 1.0f/511.5f - 1.0f; - v[2] = ((b >> 20) & 0x3ff) * 1.0f/511.5f - 1.0f; +void R_VboUnpackNormal(vec3_t v, uint32_t b) { + v[0] = ((b)&0x3ff) * 1.0f / 511.5f - 1.0f; + v[1] = ((b >> 10) & 0x3ff) * 1.0f / 511.5f - 1.0f; + v[2] = ((b >> 20) & 0x3ff) * 1.0f / 511.5f - 1.0f; } -static GLenum GetGLBufferUsage ( vboUsage_t usage ) -{ - switch (usage) - { - case VBO_USAGE_STATIC: - return GL_STATIC_DRAW; +static GLenum GetGLBufferUsage(vboUsage_t usage) { + switch (usage) { + case VBO_USAGE_STATIC: + return GL_STATIC_DRAW; - case VBO_USAGE_DYNAMIC: - return GL_STREAM_DRAW; + case VBO_USAGE_DYNAMIC: + return GL_STREAM_DRAW; - case VBO_USAGE_XFB: - return GL_STREAM_COPY; + case VBO_USAGE_XFB: + return GL_STREAM_COPY; - default: - ri.Error (ERR_FATAL, "bad vboUsage_t given: %i", usage); - return GL_INVALID_OPERATION; + default: + ri.Error(ERR_FATAL, "bad vboUsage_t given: %i", usage); + return GL_INVALID_OPERATION; } } @@ -81,12 +70,11 @@ static GLenum GetGLBufferUsage ( vboUsage_t usage ) R_CreateVBO ============ */ -VBO_t *R_CreateVBO(byte * vertexes, int vertexesSize, vboUsage_t usage) -{ - VBO_t *vbo; +VBO_t *R_CreateVBO(byte *vertexes, int vertexesSize, vboUsage_t usage) { + VBO_t *vbo; - if ( tr.numVBOs == MAX_VBOS ) { - ri.Error( ERR_DROP, "R_CreateVBO: MAX_VBOS hit"); + if (tr.numVBOs == MAX_VBOS) { + ri.Error(ERR_DROP, "R_CreateVBO: MAX_VBOS hit"); } R_IssuePendingRenderCommands(); @@ -100,19 +88,15 @@ VBO_t *R_CreateVBO(byte * vertexes, int vertexesSize, vboUsage_t usage) tr.numVBOs++; qglBindBuffer(GL_ARRAY_BUFFER, vbo->vertexesVBO); - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { GLbitfield creationFlags = 0; - if ( usage == VBO_USAGE_DYNAMIC ) - { + if (usage == VBO_USAGE_DYNAMIC) { creationFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; } qglBufferStorage(GL_ARRAY_BUFFER, vertexesSize, vertexes, creationFlags); - } - else - { - int glUsage = GetGLBufferUsage (usage); + } else { + int glUsage = GetGLBufferUsage(usage); qglBufferData(GL_ARRAY_BUFFER, vertexesSize, vertexes, glUsage); } @@ -130,12 +114,11 @@ VBO_t *R_CreateVBO(byte * vertexes, int vertexesSize, vboUsage_t usage) R_CreateIBO ============ */ -IBO_t *R_CreateIBO(byte * indexes, int indexesSize, vboUsage_t usage) -{ - IBO_t *ibo; +IBO_t *R_CreateIBO(byte *indexes, int indexesSize, vboUsage_t usage) { + IBO_t *ibo; - if ( tr.numIBOs == MAX_IBOS ) { - ri.Error( ERR_DROP, "R_CreateIBO: MAX_IBOS hit"); + if (tr.numIBOs == MAX_IBOS) { + ri.Error(ERR_DROP, "R_CreateIBO: MAX_IBOS hit"); } R_IssuePendingRenderCommands(); @@ -147,20 +130,16 @@ IBO_t *R_CreateIBO(byte * indexes, int indexesSize, vboUsage_t usage) tr.numIBOs++; qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo->indexesVBO); - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { GLbitfield creationFlags = 0; - if ( usage == VBO_USAGE_DYNAMIC ) - { + if (usage == VBO_USAGE_DYNAMIC) { creationFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; } qglBufferStorage(GL_ELEMENT_ARRAY_BUFFER, indexesSize, indexes, creationFlags); GL_CheckErrors(); - } - else - { - int glUsage = GetGLBufferUsage (usage); + } else { + int glUsage = GetGLBufferUsage(usage); qglBufferData(GL_ELEMENT_ARRAY_BUFFER, indexesSize, indexes, glUsage); } @@ -178,22 +157,18 @@ IBO_t *R_CreateIBO(byte * indexes, int indexesSize, vboUsage_t usage) R_BindVBO ============ */ -void R_BindVBO(VBO_t * vbo) -{ - if(!vbo) - { - //R_BindNullVBO(); +void R_BindVBO(VBO_t *vbo) { + if (!vbo) { + // R_BindNullVBO(); ri.Error(ERR_DROP, "R_BindVBO: NULL vbo"); return; } - if(r_logFile->integer) - { + if (r_logFile->integer) { GLimp_LogComment("--- R_BindVBO() ---\n"); } - if(glState.currentVBO != vbo) - { + if (glState.currentVBO != vbo) { glState.currentVBO = vbo; glState.vertexAttribsInterpolation = 0; @@ -215,12 +190,10 @@ void R_BindVBO(VBO_t * vbo) R_BindNullVBO ============ */ -void R_BindNullVBO(void) -{ +void R_BindNullVBO(void) { GLimp_LogComment("--- R_BindNullVBO ---\n"); - if(glState.currentVBO) - { + if (glState.currentVBO) { qglBindBuffer(GL_ARRAY_BUFFER, 0); glState.currentVBO = NULL; } @@ -233,22 +206,18 @@ void R_BindNullVBO(void) R_BindIBO ============ */ -void R_BindIBO(IBO_t * ibo) -{ - if(!ibo) - { - //R_BindNullIBO(); +void R_BindIBO(IBO_t *ibo) { + if (!ibo) { + // R_BindNullIBO(); ri.Error(ERR_DROP, "R_BindIBO: NULL ibo"); return; } - if(r_logFile->integer) - { + if (r_logFile->integer) { GLimp_LogComment("--- R_BindIBO() ---\n"); } - if(glState.currentIBO != ibo) - { + if (glState.currentIBO != ibo) { qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo->indexesVBO); glState.currentIBO = ibo; @@ -262,12 +231,10 @@ void R_BindIBO(IBO_t * ibo) R_BindNullIBO ============ */ -void R_BindNullIBO(void) -{ +void R_BindNullIBO(void) { GLimp_LogComment("--- R_BindNullIBO ---\n"); - if(glState.currentIBO) - { + if (glState.currentIBO) { qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glState.currentIBO = NULL; } @@ -278,8 +245,7 @@ void R_BindNullIBO(void) R_InitGPUBuffers ============ */ -void R_InitGPUBuffers(void) -{ +void R_InitGPUBuffers(void) { ri.Printf(PRINT_ALL, "------- R_InitGPUBuffers -------\n"); // glGenBuffers only allocates the IDs for these buffers. The 'buffer object' is @@ -294,11 +260,7 @@ void R_InitGPUBuffers(void) qglBindBuffer(GL_UNIFORM_BUFFER, tr.shaderInstanceUbo); glState.currentGlobalUBO = tr.shaderInstanceUbo; - qglBufferData( - GL_UNIFORM_BUFFER, - MAX_SHADERS * alignedBlockSize, - nullptr, - GL_STATIC_DRAW); + qglBufferData(GL_UNIFORM_BUFFER, MAX_SHADERS * alignedBlockSize, nullptr, GL_STATIC_DRAW); tr.numVBOs = 0; tr.numIBOs = 0; @@ -314,8 +276,7 @@ void R_InitGPUBuffers(void) R_DestroyGPUBuffers ============ */ -void R_DestroyGPUBuffers(void) -{ +void R_DestroyGPUBuffers(void) { ri.Printf(PRINT_ALL, "------- R_DestroyGPUBuffers -------\n"); R_BindNullVBO(); @@ -325,22 +286,18 @@ void R_DestroyGPUBuffers(void) qglDeleteBuffers(MAX_SUB_BSP + 1, tr.spriteUbos); qglDeleteBuffers(1, &tr.shaderInstanceUbo); - for (int i = 0; i < tr.numVBOs; i++) - { + for (int i = 0; i < tr.numVBOs; i++) { VBO_t *vbo = tr.vbos[i]; - if (vbo->vertexesVBO) - { + if (vbo->vertexesVBO) { qglDeleteBuffers(1, &vbo->vertexesVBO); } } - for (int i = 0; i < tr.numIBOs; i++) - { + for (int i = 0; i < tr.numIBOs; i++) { IBO_t *ibo = tr.ibos[i]; - if (ibo->indexesVBO) - { + if (ibo->indexesVBO) { qglDeleteBuffers(1, &ibo->indexesVBO); } } @@ -354,22 +311,20 @@ void R_DestroyGPUBuffers(void) R_VBOList_f ============ */ -void R_VBOList_f(void) -{ - int i; - VBO_t *vbo; - IBO_t *ibo; - int vertexesSize = 0; - int indexesSize = 0; +void R_VBOList_f(void) { + int i; + VBO_t *vbo; + IBO_t *ibo; + int vertexesSize = 0; + int indexesSize = 0; - ri.Printf (PRINT_ALL, " vertex buffers\n"); - ri.Printf (PRINT_ALL, "----------------\n\n"); + ri.Printf(PRINT_ALL, " vertex buffers\n"); + ri.Printf(PRINT_ALL, "----------------\n\n"); ri.Printf(PRINT_ALL, " id size (MB)\n"); ri.Printf(PRINT_ALL, "---------------\n"); - for(i = 0; i < tr.numVBOs; i++) - { + for (i = 0; i < tr.numVBOs; i++) { vbo = tr.vbos[i]; ri.Printf(PRINT_ALL, " %4i %4.2f\n", i, vbo->vertexesSize / (1024.0f * 1024.0f)); @@ -380,15 +335,13 @@ void R_VBOList_f(void) ri.Printf(PRINT_ALL, " %d total buffers\n", tr.numVBOs); ri.Printf(PRINT_ALL, " %.2f MB in total\n\n", vertexesSize / (1024.0f * 1024.0f)); - - ri.Printf (PRINT_ALL, " index buffers\n"); - ri.Printf (PRINT_ALL, "---------------\n\n"); + ri.Printf(PRINT_ALL, " index buffers\n"); + ri.Printf(PRINT_ALL, "---------------\n\n"); ri.Printf(PRINT_ALL, " id size (MB)\n"); ri.Printf(PRINT_ALL, "---------------\n"); - for(i = 0; i < tr.numIBOs; i++) - { + for (i = 0; i < tr.numIBOs; i++) { ibo = tr.ibos[i]; ri.Printf(PRINT_ALL, " %4i %4.2f\n", i, ibo->indexesSize / (1024.0f * 1024.0f)); @@ -400,173 +353,79 @@ void R_VBOList_f(void) ri.Printf(PRINT_ALL, " %.2f MB in total\n\n", indexesSize / (1024.0f * 1024.0f)); } -void AddVertexArray( - VertexArraysProperties *properties, - int attributeIndex, - size_t size, - int stride, - int offset, - void *stream, - int streamStride) -{ - properties->enabledAttributes[properties->numVertexArrays] = attributeIndex; - properties->offsets[attributeIndex] = offset; - properties->vertexDataSize += size; - properties->sizes[attributeIndex] = size; - properties->strides[attributeIndex] = stride; - properties->streams[attributeIndex] = stream; - properties->streamStrides[attributeIndex] = streamStride; +void AddVertexArray(VertexArraysProperties *properties, int attributeIndex, size_t size, int stride, int offset, void *stream, int streamStride) { + properties->enabledAttributes[properties->numVertexArrays] = attributeIndex; + properties->offsets[attributeIndex] = offset; + properties->vertexDataSize += size; + properties->sizes[attributeIndex] = size; + properties->strides[attributeIndex] = stride; + properties->streams[attributeIndex] = stream; + properties->streamStrides[attributeIndex] = streamStride; properties->numVertexArrays++; } -void CalculateVertexArraysProperties(uint32_t attributes, VertexArraysProperties *properties) -{ +void CalculateVertexArraysProperties(uint32_t attributes, VertexArraysProperties *properties) { properties->vertexDataSize = 0; properties->numVertexArrays = 0; - if (!attributes) - { - attributes = - ATTR_POSITION | - ATTR_TEXCOORD0 | - ATTR_TEXCOORD1 | - ATTR_NORMAL | - ATTR_TANGENT | - ATTR_COLOR | - ATTR_LIGHTDIRECTION; + if (!attributes) { + attributes = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_TEXCOORD1 | ATTR_NORMAL | ATTR_TANGENT | ATTR_COLOR | ATTR_LIGHTDIRECTION; } - if (attributes & ATTR_BITS) - { + if (attributes & ATTR_BITS) { if (attributes & ATTR_POSITION) - AddVertexArray( - properties, - ATTR_INDEX_POSITION, - sizeof(tess.xyz[0]), - 0, - properties->vertexDataSize, - tess.xyz, - sizeof(tess.xyz[0])); + AddVertexArray(properties, ATTR_INDEX_POSITION, sizeof(tess.xyz[0]), 0, properties->vertexDataSize, tess.xyz, sizeof(tess.xyz[0])); if (attributes & ATTR_TEXCOORD0) - AddVertexArray( - properties, - ATTR_INDEX_TEXCOORD0, - sizeof(tess.texCoords[0][0]), - 0, - properties->vertexDataSize, - tess.texCoords[0][0], - sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + AddVertexArray(properties, ATTR_INDEX_TEXCOORD0, sizeof(tess.texCoords[0][0]), 0, properties->vertexDataSize, tess.texCoords[0][0], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); if (attributes & ATTR_TEXCOORD1) - AddVertexArray( - properties, - ATTR_INDEX_TEXCOORD1, - sizeof(tess.texCoords[0][1]), - 0, - properties->vertexDataSize, - tess.texCoords[0][1], - sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + AddVertexArray(properties, ATTR_INDEX_TEXCOORD1, sizeof(tess.texCoords[0][1]), 0, properties->vertexDataSize, tess.texCoords[0][1], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); if (attributes & ATTR_TEXCOORD2) - AddVertexArray( - properties, - ATTR_INDEX_TEXCOORD2, - sizeof(tess.texCoords[0][2]) * 2, - 0, - properties->vertexDataSize, - tess.texCoords[0][2], - sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); -; + AddVertexArray(properties, ATTR_INDEX_TEXCOORD2, sizeof(tess.texCoords[0][2]) * 2, 0, properties->vertexDataSize, tess.texCoords[0][2], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + ; if (attributes & ATTR_TEXCOORD3) - AddVertexArray( - properties, - ATTR_INDEX_TEXCOORD3, - sizeof(tess.texCoords[0][3]) * 2, - 0, - properties->vertexDataSize, - tess.texCoords[0][3], - sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); - + AddVertexArray(properties, ATTR_INDEX_TEXCOORD3, sizeof(tess.texCoords[0][3]) * 2, 0, properties->vertexDataSize, tess.texCoords[0][3], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); if (attributes & ATTR_TEXCOORD4) - AddVertexArray( - properties, - ATTR_INDEX_TEXCOORD4, - sizeof(tess.texCoords[0][4]) * 2, - 0, - properties->vertexDataSize, - tess.texCoords[0][4], - sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + AddVertexArray(properties, ATTR_INDEX_TEXCOORD4, sizeof(tess.texCoords[0][4]) * 2, 0, properties->vertexDataSize, tess.texCoords[0][4], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); if (attributes & ATTR_NORMAL) - AddVertexArray( - properties, - ATTR_INDEX_NORMAL, - sizeof(tess.normal[0]), - 0, - properties->vertexDataSize, - tess.normal, - sizeof(tess.normal[0])); + AddVertexArray(properties, ATTR_INDEX_NORMAL, sizeof(tess.normal[0]), 0, properties->vertexDataSize, tess.normal, sizeof(tess.normal[0])); if (attributes & ATTR_TANGENT) - AddVertexArray( - properties, - ATTR_INDEX_TANGENT, - sizeof(tess.tangent[0]), - 0, - properties->vertexDataSize, - tess.tangent, - sizeof(tess.tangent[0])); + AddVertexArray(properties, ATTR_INDEX_TANGENT, sizeof(tess.tangent[0]), 0, properties->vertexDataSize, tess.tangent, sizeof(tess.tangent[0])); if (attributes & ATTR_COLOR) - AddVertexArray( - properties, - ATTR_INDEX_COLOR, - sizeof(tess.vertexColors[0]), - 0, - properties->vertexDataSize, - tess.vertexColors, - sizeof(tess.vertexColors[0])); + AddVertexArray(properties, ATTR_INDEX_COLOR, sizeof(tess.vertexColors[0]), 0, properties->vertexDataSize, tess.vertexColors, + sizeof(tess.vertexColors[0])); if (attributes & ATTR_LIGHTDIRECTION) - AddVertexArray( - properties, - ATTR_INDEX_LIGHTDIRECTION, - sizeof(tess.lightdir[0]), - 0, - properties->vertexDataSize, - tess.lightdir, - sizeof(tess.lightdir[0])); + AddVertexArray(properties, ATTR_INDEX_LIGHTDIRECTION, sizeof(tess.lightdir[0]), 0, properties->vertexDataSize, tess.lightdir, + sizeof(tess.lightdir[0])); } - for ( int i = 0; i < properties->numVertexArrays; i++ ) + for (int i = 0; i < properties->numVertexArrays; i++) properties->strides[properties->enabledAttributes[i]] = properties->vertexDataSize; } -void CalculateVertexArraysFromVBO( - uint32_t attributes, - const VBO_t *vbo, - VertexArraysProperties *properties) -{ +void CalculateVertexArraysFromVBO(uint32_t attributes, const VBO_t *vbo, VertexArraysProperties *properties) { properties->vertexDataSize = 0; properties->numVertexArrays = 0; - for (int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1) - { + for (int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1) { if (vbo->sizes[i] == 0) continue; if (attributes & j) - AddVertexArray( - properties, - i, - vbo->sizes[i], - vbo->strides[i], - vbo->offsets[i], - NULL, - 0); + AddVertexArray(properties, i, vbo->sizes[i], vbo->strides[i], vbo->offsets[i], NULL, 0); } } @@ -579,8 +438,7 @@ Adapted from Tess_UpdateVBOs from xreal Update the default VBO to replace the client side vertex arrays ============== */ -void RB_UpdateVBOs(unsigned int attribBits) -{ +void RB_UpdateVBOs(unsigned int attribBits) { gpuFrame_t *currentFrame = backEndData->currentFrame; GLimp_LogComment("--- RB_UpdateVBOs ---\n"); @@ -588,8 +446,7 @@ void RB_UpdateVBOs(unsigned int attribBits) backEnd.pc.c_dynamicVboDraws++; // update the default VBO - if (tess.numVertexes > 0 && tess.numVertexes <= SHADER_MAX_VERTEXES) - { + if (tess.numVertexes > 0 && tess.numVertexes <= SHADER_MAX_VERTEXES) { VBO_t *frameVbo = currentFrame->dynamicVbo; GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; VertexArraysProperties vertexArrays = {}; @@ -598,8 +455,7 @@ void RB_UpdateVBOs(unsigned int attribBits) int totalVertexDataSize = tess.numVertexes * vertexArrays.vertexDataSize; backEnd.pc.c_dynamicVboTotalSize += totalVertexDataSize; - if ( (currentFrame->dynamicVboWriteOffset + totalVertexDataSize) > frameVbo->vertexesSize ) - { + if ((currentFrame->dynamicVboWriteOffset + totalVertexDataSize) > frameVbo->vertexesSize) { // TODO: Eh...resize? assert(!"This shouldn't happen"); return; @@ -608,22 +464,16 @@ void RB_UpdateVBOs(unsigned int attribBits) R_BindVBO(frameVbo); void *dstPtr; - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { dstPtr = (byte *)currentFrame->dynamicVboMemory + currentFrame->dynamicVboWriteOffset; - } - else - { - dstPtr = qglMapBufferRange(GL_ARRAY_BUFFER, currentFrame->dynamicVboWriteOffset, - totalVertexDataSize, mapFlags); + } else { + dstPtr = qglMapBufferRange(GL_ARRAY_BUFFER, currentFrame->dynamicVboWriteOffset, totalVertexDataSize, mapFlags); } // Interleave the data void *writePtr = dstPtr; - for ( int i = 0; i < tess.numVertexes; i++ ) - { - for ( int j = 0; j < vertexArrays.numVertexArrays; j++ ) - { + for (int i = 0; i < tess.numVertexes; i++) { + for (int j = 0; j < vertexArrays.numVertexArrays; j++) { const int attributeIndex = vertexArrays.enabledAttributes[j]; const size_t attribSize = vertexArrays.sizes[attributeIndex]; const int streamStride = vertexArrays.streamStrides[attributeIndex]; @@ -634,8 +484,7 @@ void RB_UpdateVBOs(unsigned int attribBits) } } - if ( !glRefConfig.immutableBuffers ) - { + if (!glRefConfig.immutableBuffers) { qglUnmapBuffer(GL_ARRAY_BUFFER); } @@ -643,36 +492,29 @@ void RB_UpdateVBOs(unsigned int attribBits) } // update the default IBO - if(tess.numIndexes > 0 && tess.numIndexes <= SHADER_MAX_INDEXES) - { + if (tess.numIndexes > 0 && tess.numIndexes <= SHADER_MAX_INDEXES) { IBO_t *frameIbo = currentFrame->dynamicIbo; GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; int totalIndexDataSize = tess.numIndexes * sizeof(tess.indexes[0]); R_BindIBO(frameIbo); - if ( (currentFrame->dynamicIboWriteOffset + totalIndexDataSize) > frameIbo->indexesSize ) - { + if ((currentFrame->dynamicIboWriteOffset + totalIndexDataSize) > frameIbo->indexesSize) { // TODO: Resize the buffer? assert(!"This shouldn't happen"); return; } void *dst; - if ( glRefConfig.immutableBuffers ) - { + if (glRefConfig.immutableBuffers) { dst = (byte *)currentFrame->dynamicIboMemory + currentFrame->dynamicIboWriteOffset; - } - else - { - dst = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, currentFrame->dynamicIboWriteOffset, - totalIndexDataSize, mapFlags); + } else { + dst = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, currentFrame->dynamicIboWriteOffset, totalIndexDataSize, mapFlags); } memcpy(dst, tess.indexes, totalIndexDataSize); - if ( !glRefConfig.immutableBuffers ) - { + if (!glRefConfig.immutableBuffers) { qglUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); } @@ -681,8 +523,7 @@ void RB_UpdateVBOs(unsigned int attribBits) } #ifdef _G2_GORE -void RB_UpdateGoreVBO(srfG2GoreSurface_t *goreSurface) -{ +void RB_UpdateGoreVBO(srfG2GoreSurface_t *goreSurface) { goreSurface->firstVert = tr.goreVBOCurrentIndex; goreSurface->firstIndex = tr.goreIBOCurrentIndex; @@ -690,49 +531,33 @@ void RB_UpdateGoreVBO(srfG2GoreSurface_t *goreSurface) tr.goreVBOCurrentIndex = 0; R_BindVBO(tr.goreVBO); - qglBufferSubData( - GL_ARRAY_BUFFER, - sizeof(g2GoreVert_t) * tr.goreVBOCurrentIndex, - sizeof(g2GoreVert_t) * goreSurface->numVerts, - goreSurface->verts - ); + qglBufferSubData(GL_ARRAY_BUFFER, sizeof(g2GoreVert_t) * tr.goreVBOCurrentIndex, sizeof(g2GoreVert_t) * goreSurface->numVerts, goreSurface->verts); tr.goreVBOCurrentIndex += goreSurface->numVerts; if (tr.goreIBOCurrentIndex + goreSurface->numVerts >= (MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_INDECIES * MAX_FRAMES)) tr.goreIBOCurrentIndex = 0; R_BindIBO(tr.goreIBO); - qglBufferSubData( - GL_ELEMENT_ARRAY_BUFFER, - sizeof(glIndex_t) * tr.goreIBOCurrentIndex, - sizeof(glIndex_t) * goreSurface->numIndexes, - goreSurface->indexes - ); + qglBufferSubData(GL_ELEMENT_ARRAY_BUFFER, sizeof(glIndex_t) * tr.goreIBOCurrentIndex, sizeof(glIndex_t) * goreSurface->numIndexes, goreSurface->indexes); tr.goreIBOCurrentIndex += goreSurface->numIndexes; } #endif -void RB_CommitInternalBufferData() -{ +void RB_CommitInternalBufferData() { gpuFrame_t *currentFrame = backEndData->currentFrame; currentFrame->dynamicIboCommitOffset = currentFrame->dynamicIboWriteOffset; currentFrame->dynamicVboCommitOffset = currentFrame->dynamicVboWriteOffset; } -void RB_BindUniformBlock(GLuint ubo, uniformBlock_t block, int offset) -{ +void RB_BindUniformBlock(GLuint ubo, uniformBlock_t block, int offset) { const uniformBlockInfo_t *blockInfo = uniformBlocksInfo + block; assert(blockInfo->slot < MAX_UBO_BINDINGS); bufferBinding_t *currentBinding = glState.currentUBOs + blockInfo->slot; - if (currentBinding->buffer != ubo || - currentBinding->offset != offset || - currentBinding->size != blockInfo->size) - { - qglBindBufferRange( - GL_UNIFORM_BUFFER, blockInfo->slot, ubo, offset, blockInfo->size); + if (currentBinding->buffer != ubo || currentBinding->offset != offset || currentBinding->size != blockInfo->size) { + qglBindBufferRange(GL_UNIFORM_BUFFER, blockInfo->slot, ubo, offset, blockInfo->size); glState.currentGlobalUBO = ubo; currentBinding->buffer = ubo; @@ -741,16 +566,14 @@ void RB_BindUniformBlock(GLuint ubo, uniformBlock_t block, int offset) } } -int RB_BindAndUpdateFrameUniformBlock(uniformBlock_t block, void *data) -{ +int RB_BindAndUpdateFrameUniformBlock(uniformBlock_t block, void *data) { const uniformBlockInfo_t *blockInfo = uniformBlocksInfo + block; gpuFrame_t *thisFrame = backEndData->currentFrame; const int offset = thisFrame->uboWriteOffset; RB_BindUniformBlock(thisFrame->ubo, block, offset); - qglBufferSubData(GL_UNIFORM_BUFFER, - thisFrame->uboWriteOffset, blockInfo->size, data); + qglBufferSubData(GL_UNIFORM_BUFFER, thisFrame->uboWriteOffset, blockInfo->size, data); const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; const size_t alignedBlockSize = (blockInfo->size + alignment) & ~alignment; @@ -759,17 +582,14 @@ int RB_BindAndUpdateFrameUniformBlock(uniformBlock_t block, void *data) return offset; } -int RB_AddShaderInstanceBlock(void *data) -{ - if (glState.currentGlobalUBO != tr.shaderInstanceUbo) - { +int RB_AddShaderInstanceBlock(void *data) { + if (glState.currentGlobalUBO != tr.shaderInstanceUbo) { qglBindBuffer(GL_UNIFORM_BUFFER, tr.shaderInstanceUbo); glState.currentGlobalUBO = tr.shaderInstanceUbo; } const size_t writeOffset = tr.shaderInstanceUboWriteOffset; - qglBufferSubData(GL_UNIFORM_BUFFER, - tr.shaderInstanceUboWriteOffset, sizeof(ShaderInstanceBlock), data); + qglBufferSubData(GL_UNIFORM_BUFFER, tr.shaderInstanceUboWriteOffset, sizeof(ShaderInstanceBlock), data); const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; const size_t alignedBlockSize = (sizeof(ShaderInstanceBlock) + alignment) & ~alignment; @@ -778,30 +598,19 @@ int RB_AddShaderInstanceBlock(void *data) return writeOffset; } -void RB_BeginConstantsUpdate(gpuFrame_t *frame) -{ - if (glState.currentGlobalUBO != frame->ubo) - { +void RB_BeginConstantsUpdate(gpuFrame_t *frame) { + if (glState.currentGlobalUBO != frame->ubo) { qglBindBuffer(GL_UNIFORM_BUFFER, frame->ubo); glState.currentGlobalUBO = frame->ubo; } - const GLbitfield mapFlags = - GL_MAP_WRITE_BIT | - GL_MAP_UNSYNCHRONIZED_BIT | - GL_MAP_FLUSH_EXPLICIT_BIT; + const GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT | GL_MAP_FLUSH_EXPLICIT_BIT; frame->uboMapBase = frame->uboWriteOffset; - frame->uboMemory = qglMapBufferRange( - GL_UNIFORM_BUFFER, - frame->uboWriteOffset, - frame->uboSize - frame->uboWriteOffset, - mapFlags); + frame->uboMemory = qglMapBufferRange(GL_UNIFORM_BUFFER, frame->uboWriteOffset, frame->uboSize - frame->uboWriteOffset, mapFlags); } -int RB_AppendConstantsData( - gpuFrame_t *frame, const void *data, size_t dataSize) -{ +int RB_AppendConstantsData(gpuFrame_t *frame, const void *data, size_t dataSize) { const size_t writeOffset = frame->uboWriteOffset; const size_t relativeOffset = writeOffset - frame->uboMapBase; @@ -815,11 +624,7 @@ int RB_AppendConstantsData( return writeOffset; } -void RB_EndConstantsUpdate(const gpuFrame_t *frame) -{ - qglFlushMappedBufferRange( - GL_UNIFORM_BUFFER, - frame->uboMapBase, - frame->uboWriteOffset - frame->uboMapBase); +void RB_EndConstantsUpdate(const gpuFrame_t *frame) { + qglFlushMappedBufferRange(GL_UNIFORM_BUFFER, frame->uboMapBase, frame->uboWriteOffset - frame->uboMapBase); qglUnmapBuffer(GL_UNIFORM_BUFFER); } \ No newline at end of file diff --git a/codemp/rd-rend2/tr_weather.cpp b/codemp/rd-rend2/tr_weather.cpp index f3a5620673..f4e964defa 100644 --- a/codemp/rd-rend2/tr_weather.cpp +++ b/codemp/rd-rend2/tr_weather.cpp @@ -23,457 +23,357 @@ along with this program; if not, see . #include #include -namespace -{ - const int CHUNK_COUNT = 9; // in 3x3 arrangement - const float CHUNK_EXTENDS = 2000.f; - const float HALF_CHUNK_EXTENDS = CHUNK_EXTENDS * 0.5f; - - struct rainVertex_t - { - vec3_t position; - vec3_t velocity; - }; - - void RB_UpdateWindObject( windObject_t *wo ) - { - if (wo->targetVelocityTimeRemaining == 0) - { - if (Q_flrand(0.f, 1.f) < wo->chanceOfDeadTime) - { - wo->targetVelocityTimeRemaining = Q_flrand(wo->deadTimeMinMax[0], wo->deadTimeMinMax[1]); - VectorSet(wo->targetVelocity, 0.0f, 0.0f, 0.0f); - } - else - { - wo->targetVelocityTimeRemaining = Q_flrand(1000.f, 2500.f); - VectorSet( - wo->targetVelocity, - Q_flrand(wo->minVelocity[0], wo->maxVelocity[0]), - Q_flrand(wo->minVelocity[1], wo->maxVelocity[1]), - Q_flrand(wo->minVelocity[2], wo->maxVelocity[2])); - } - return; +namespace { +const int CHUNK_COUNT = 9; // in 3x3 arrangement +const float CHUNK_EXTENDS = 2000.f; +const float HALF_CHUNK_EXTENDS = CHUNK_EXTENDS * 0.5f; + +struct rainVertex_t { + vec3_t position; + vec3_t velocity; +}; + +void RB_UpdateWindObject(windObject_t *wo) { + if (wo->targetVelocityTimeRemaining == 0) { + if (Q_flrand(0.f, 1.f) < wo->chanceOfDeadTime) { + wo->targetVelocityTimeRemaining = Q_flrand(wo->deadTimeMinMax[0], wo->deadTimeMinMax[1]); + VectorSet(wo->targetVelocity, 0.0f, 0.0f, 0.0f); + } else { + wo->targetVelocityTimeRemaining = Q_flrand(1000.f, 2500.f); + VectorSet(wo->targetVelocity, Q_flrand(wo->minVelocity[0], wo->maxVelocity[0]), Q_flrand(wo->minVelocity[1], wo->maxVelocity[1]), + Q_flrand(wo->minVelocity[2], wo->maxVelocity[2])); } - - wo->targetVelocityTimeRemaining--; - vec3_t deltaVelocity; - VectorSubtract(wo->targetVelocity, wo->currentVelocity, deltaVelocity); - float DeltaVelocityLen = VectorNormalize(deltaVelocity); - if (DeltaVelocityLen > 10.f) - { - DeltaVelocityLen = 10.f; - } - VectorScale(deltaVelocity, DeltaVelocityLen, deltaVelocity); - VectorAdd(wo->currentVelocity, deltaVelocity, wo->currentVelocity); + return; } - void GenerateRainModel( weatherObject_t& ws, const int maxParticleCount ) - { - const int mapExtentZ = (int)(tr.world->bmodels[0].bounds[1][2] - tr.world->bmodels[0].bounds[0][2]); - const int PARTICLE_COUNT = (int)(maxParticleCount * mapExtentZ / CHUNK_EXTENDS); - std::vector rainVertices(PARTICLE_COUNT * CHUNK_COUNT); - - for ( int i = 0; i < rainVertices.size(); ++i ) - { - rainVertex_t& vertex = rainVertices[i]; - vertex.position[0] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); - vertex.position[1] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); - vertex.position[2] = Q_flrand(tr.world->bmodels[0].bounds[0][2], tr.world->bmodels[0].bounds[1][2]); - vertex.velocity[0] = 0.0f; //Q_flrand(0.0f, 0.0f); - vertex.velocity[1] = 0.0f; //Q_flrand(0.0f, 0.0f); - vertex.velocity[2] = 0.0f; //Q_flrand(-1.0f, 0.0f); - } + wo->targetVelocityTimeRemaining--; + vec3_t deltaVelocity; + VectorSubtract(wo->targetVelocity, wo->currentVelocity, deltaVelocity); + float DeltaVelocityLen = VectorNormalize(deltaVelocity); + if (DeltaVelocityLen > 10.f) { + DeltaVelocityLen = 10.f; + } + VectorScale(deltaVelocity, DeltaVelocityLen, deltaVelocity); + VectorAdd(wo->currentVelocity, deltaVelocity, wo->currentVelocity); +} - ws.lastVBO = R_CreateVBO( - nullptr, - sizeof(rainVertex_t) * rainVertices.size(), - VBO_USAGE_XFB); - ws.vbo = R_CreateVBO( - (byte *)rainVertices.data(), - sizeof(rainVertex_t) * rainVertices.size(), - VBO_USAGE_XFB); - ws.vboLastUpdateFrame = 0; - - ws.attribsTemplate[0].index = ATTR_INDEX_POSITION; - ws.attribsTemplate[0].numComponents = 3; - ws.attribsTemplate[0].offset = offsetof(rainVertex_t, position); - ws.attribsTemplate[0].stride = sizeof(rainVertex_t); - ws.attribsTemplate[0].type = GL_FLOAT; - ws.attribsTemplate[0].vbo = nullptr; - - ws.attribsTemplate[1].index = ATTR_INDEX_COLOR; - ws.attribsTemplate[1].numComponents = 3; - ws.attribsTemplate[1].offset = offsetof(rainVertex_t, velocity); - ws.attribsTemplate[1].stride = sizeof(rainVertex_t); - ws.attribsTemplate[1].type = GL_FLOAT; - ws.attribsTemplate[1].vbo = nullptr; +void GenerateRainModel(weatherObject_t &ws, const int maxParticleCount) { + const int mapExtentZ = (int)(tr.world->bmodels[0].bounds[1][2] - tr.world->bmodels[0].bounds[0][2]); + const int PARTICLE_COUNT = (int)(maxParticleCount * mapExtentZ / CHUNK_EXTENDS); + std::vector rainVertices(PARTICLE_COUNT * CHUNK_COUNT); + + for (int i = 0; i < rainVertices.size(); ++i) { + rainVertex_t &vertex = rainVertices[i]; + vertex.position[0] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); + vertex.position[1] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); + vertex.position[2] = Q_flrand(tr.world->bmodels[0].bounds[0][2], tr.world->bmodels[0].bounds[1][2]); + vertex.velocity[0] = 0.0f; // Q_flrand(0.0f, 0.0f); + vertex.velocity[1] = 0.0f; // Q_flrand(0.0f, 0.0f); + vertex.velocity[2] = 0.0f; // Q_flrand(-1.0f, 0.0f); } - bool intersectPlane(const vec3_t n, const float dist, const vec3_t l0, const vec3_t l, float &t) - { - // assuming vectors are all normalized - float denom = DotProduct(n, l); - if (denom > 1e-6) { - t = -(DotProduct(l0, n) + dist) / denom; - return (t >= 0); - } + ws.lastVBO = R_CreateVBO(nullptr, sizeof(rainVertex_t) * rainVertices.size(), VBO_USAGE_XFB); + ws.vbo = R_CreateVBO((byte *)rainVertices.data(), sizeof(rainVertex_t) * rainVertices.size(), VBO_USAGE_XFB); + ws.vboLastUpdateFrame = 0; + + ws.attribsTemplate[0].index = ATTR_INDEX_POSITION; + ws.attribsTemplate[0].numComponents = 3; + ws.attribsTemplate[0].offset = offsetof(rainVertex_t, position); + ws.attribsTemplate[0].stride = sizeof(rainVertex_t); + ws.attribsTemplate[0].type = GL_FLOAT; + ws.attribsTemplate[0].vbo = nullptr; + + ws.attribsTemplate[1].index = ATTR_INDEX_COLOR; + ws.attribsTemplate[1].numComponents = 3; + ws.attribsTemplate[1].offset = offsetof(rainVertex_t, velocity); + ws.attribsTemplate[1].stride = sizeof(rainVertex_t); + ws.attribsTemplate[1].type = GL_FLOAT; + ws.attribsTemplate[1].vbo = nullptr; +} - return false; +bool intersectPlane(const vec3_t n, const float dist, const vec3_t l0, const vec3_t l, float &t) { + // assuming vectors are all normalized + float denom = DotProduct(n, l); + if (denom > 1e-6) { + t = -(DotProduct(l0, n) + dist) / denom; + return (t >= 0); } - void GenerateDepthMap() - { - R_IssuePendingRenderCommands(); - R_InitNextFrame(); - RE_BeginFrame(STEREO_CENTER); - - vec3_t mapSize; - vec3_t halfMapSize; - VectorSubtract( - tr.world->bmodels[0].bounds[0], - tr.world->bmodels[0].bounds[1], - mapSize); - VectorScale(mapSize, -0.5f, halfMapSize); - mapSize[2] = 0.0f; - - const vec3_t forward = {0.0f, 0.0f, -1.0f}; - const vec3_t left = {0.0f, 1.0f, 0.0f}; - const vec3_t up = {-1.0f, 0.0f, 0.0f}; - - vec3_t viewOrigin; - VectorMA(tr.world->bmodels[0].bounds[1], 0.5f, mapSize, viewOrigin); - viewOrigin[2] = tr.world->bmodels[0].bounds[1][2]; - - orientationr_t orientation; - R_SetOrientationOriginAndAxis(orientation, viewOrigin, forward, left, up); - - const vec3_t viewBounds[2] = { - { 0.0f, -halfMapSize[1], -halfMapSize[0] }, - { halfMapSize[2] * 2.0f, halfMapSize[1], halfMapSize[0] } - }; + return false; +} - R_SetupViewParmsForOrthoRendering( - tr.weatherDepthFbo->width, - tr.weatherDepthFbo->height, - tr.weatherDepthFbo, - VPF_DEPTHCLAMP | VPF_DEPTHSHADOW | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL, - orientation, - viewBounds); - Matrix16Multiply( - tr.viewParms.projectionMatrix, - tr.viewParms.world.modelViewMatrix, - tr.weatherSystem->weatherMVP); - - if (tr.weatherSystem->numWeatherBrushes > 0) - { - FBO_Bind(tr.weatherDepthFbo); - - qglViewport(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); - qglScissor(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); - - if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) // used outside brushes - { - qglClearDepth(0.0f); - GL_State(GLS_DEPTHMASK_TRUE | GLS_DEPTHFUNC_GREATER); - } - else // used inside brushes - { - qglClearDepth(1.0f); - GL_State(GLS_DEPTHMASK_TRUE); - } +void GenerateDepthMap() { + R_IssuePendingRenderCommands(); + R_InitNextFrame(); + RE_BeginFrame(STEREO_CENTER); + + vec3_t mapSize; + vec3_t halfMapSize; + VectorSubtract(tr.world->bmodels[0].bounds[0], tr.world->bmodels[0].bounds[1], mapSize); + VectorScale(mapSize, -0.5f, halfMapSize); + mapSize[2] = 0.0f; + + const vec3_t forward = {0.0f, 0.0f, -1.0f}; + const vec3_t left = {0.0f, 1.0f, 0.0f}; + const vec3_t up = {-1.0f, 0.0f, 0.0f}; - qglClear(GL_DEPTH_BUFFER_BIT); + vec3_t viewOrigin; + VectorMA(tr.world->bmodels[0].bounds[1], 0.5f, mapSize, viewOrigin); + viewOrigin[2] = tr.world->bmodels[0].bounds[1][2]; + + orientationr_t orientation; + R_SetOrientationOriginAndAxis(orientation, viewOrigin, forward, left, up); + + const vec3_t viewBounds[2] = {{0.0f, -halfMapSize[1], -halfMapSize[0]}, {halfMapSize[2] * 2.0f, halfMapSize[1], halfMapSize[0]}}; + + R_SetupViewParmsForOrthoRendering(tr.weatherDepthFbo->width, tr.weatherDepthFbo->height, tr.weatherDepthFbo, + VPF_DEPTHCLAMP | VPF_DEPTHSHADOW | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL, orientation, viewBounds); + Matrix16Multiply(tr.viewParms.projectionMatrix, tr.viewParms.world.modelViewMatrix, tr.weatherSystem->weatherMVP); + + if (tr.weatherSystem->numWeatherBrushes > 0) { + FBO_Bind(tr.weatherDepthFbo); + + qglViewport(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); + qglScissor(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); + + if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) // used outside brushes + { + qglClearDepth(0.0f); + GL_State(GLS_DEPTHMASK_TRUE | GLS_DEPTHFUNC_GREATER); + } else // used inside brushes + { qglClearDepth(1.0f); - qglEnable(GL_DEPTH_CLAMP); + GL_State(GLS_DEPTHMASK_TRUE); + } - GL_Cull(CT_TWO_SIDED); - vec4_t color = { 0.0f, 0.0f, 0.0f, 1.0f }; - backEnd.currentEntity = &tr.worldEntity; + qglClear(GL_DEPTH_BUFFER_BIT); + qglClearDepth(1.0f); + qglEnable(GL_DEPTH_CLAMP); - vec3_t stepSize = { - abs(mapSize[0]) / tr.weatherDepthFbo->width, - abs(mapSize[1]) / tr.weatherDepthFbo->height, - 0.0, - }; + GL_Cull(CT_TWO_SIDED); + vec4_t color = {0.0f, 0.0f, 0.0f, 1.0f}; + backEnd.currentEntity = &tr.worldEntity; - vec3_t up = { - stepSize[0] * 0.5f, - 0.0f, - 0.0f - }; - vec3_t left = { - 0.0f, - stepSize[1] * 0.5f, - 0.0f + vec3_t stepSize = { + abs(mapSize[0]) / tr.weatherDepthFbo->width, + abs(mapSize[1]) / tr.weatherDepthFbo->height, + 0.0, + }; + + vec3_t up = {stepSize[0] * 0.5f, 0.0f, 0.0f}; + vec3_t left = {0.0f, stepSize[1] * 0.5f, 0.0f}; + vec3_t traceVec = {0.0f, 0.0f, -1.0f}; + + for (int i = 0; i < tr.weatherSystem->numWeatherBrushes; i++) { + RE_BeginFrame(STEREO_CENTER); + weatherBrushes_t *currentWeatherBrush = &tr.weatherSystem->weatherBrushes[i]; + + // RBSP brushes actually store their bounding box in the first 6 planes! Nice + vec3_t mins = { + -currentWeatherBrush->planes[0][3], + -currentWeatherBrush->planes[2][3], + -currentWeatherBrush->planes[4][3], }; - vec3_t traceVec = { - 0.0f, - 0.0f, - -1.0f + vec3_t maxs = { + currentWeatherBrush->planes[1][3], + currentWeatherBrush->planes[3][3], + currentWeatherBrush->planes[5][3], }; - for (int i = 0; i < tr.weatherSystem->numWeatherBrushes; i++) - { - RE_BeginFrame(STEREO_CENTER); - weatherBrushes_t *currentWeatherBrush = &tr.weatherSystem->weatherBrushes[i]; - - // RBSP brushes actually store their bounding box in the first 6 planes! Nice - vec3_t mins = { - -currentWeatherBrush->planes[0][3], - -currentWeatherBrush->planes[2][3], - -currentWeatherBrush->planes[4][3], - }; - vec3_t maxs = { - currentWeatherBrush->planes[1][3], - currentWeatherBrush->planes[3][3], - currentWeatherBrush->planes[5][3], - }; - - ivec2_t numSteps = { - int((maxs[0] - mins[0]) / stepSize[0]) + 2, - int((maxs[1] - mins[1]) / stepSize[1]) + 2 - }; - - vec2_t rayOrigin = { - tr.world->bmodels[0].bounds[0][0] + (floorf((mins[0] - tr.world->bmodels[0].bounds[0][0]) / stepSize[0]) + 0.5f) * stepSize[0], - tr.world->bmodels[0].bounds[0][1] + (floorf((mins[1] - tr.world->bmodels[0].bounds[0][1]) / stepSize[1]) + 0.5f) * stepSize[1] - }; - - for (int y = 0; y < (int)numSteps[1]; y++) - { - for (int x = 0; x < (int)numSteps[0]; x++) - { - vec3_t rayPos = { - rayOrigin[0] + x * stepSize[0], - rayOrigin[1] + y * stepSize[1], - tr.world->bmodels[0].bounds[1][2] - }; - - // Find intersection point with the brush - float t = 0.0f; - for (int j = 0; j < currentWeatherBrush->numPlanes; j++) - { - vec3_t plane_normal; - float plane_dist; - if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) - { - plane_normal[0] = currentWeatherBrush->planes[j][0]; - plane_normal[1] = currentWeatherBrush->planes[j][1]; - plane_normal[2] = currentWeatherBrush->planes[j][2]; - plane_dist = -currentWeatherBrush->planes[j][3]; - } - else - { - plane_normal[0] = -currentWeatherBrush->planes[j][0]; - plane_normal[1] = -currentWeatherBrush->planes[j][1]; - plane_normal[2] = -currentWeatherBrush->planes[j][2]; - plane_dist = currentWeatherBrush->planes[j][3]; - } - - float dist = 0.0f; - if (intersectPlane(plane_normal, plane_dist, rayPos, traceVec, dist)) - t = MAX(t, dist); + ivec2_t numSteps = {int((maxs[0] - mins[0]) / stepSize[0]) + 2, int((maxs[1] - mins[1]) / stepSize[1]) + 2}; + + vec2_t rayOrigin = {tr.world->bmodels[0].bounds[0][0] + (floorf((mins[0] - tr.world->bmodels[0].bounds[0][0]) / stepSize[0]) + 0.5f) * stepSize[0], + tr.world->bmodels[0].bounds[0][1] + (floorf((mins[1] - tr.world->bmodels[0].bounds[0][1]) / stepSize[1]) + 0.5f) * stepSize[1]}; + + for (int y = 0; y < (int)numSteps[1]; y++) { + for (int x = 0; x < (int)numSteps[0]; x++) { + vec3_t rayPos = {rayOrigin[0] + x * stepSize[0], rayOrigin[1] + y * stepSize[1], tr.world->bmodels[0].bounds[1][2]}; + + // Find intersection point with the brush + float t = 0.0f; + for (int j = 0; j < currentWeatherBrush->numPlanes; j++) { + vec3_t plane_normal; + float plane_dist; + if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) { + plane_normal[0] = currentWeatherBrush->planes[j][0]; + plane_normal[1] = currentWeatherBrush->planes[j][1]; + plane_normal[2] = currentWeatherBrush->planes[j][2]; + plane_dist = -currentWeatherBrush->planes[j][3]; + } else { + plane_normal[0] = -currentWeatherBrush->planes[j][0]; + plane_normal[1] = -currentWeatherBrush->planes[j][1]; + plane_normal[2] = -currentWeatherBrush->planes[j][2]; + plane_dist = currentWeatherBrush->planes[j][3]; } - bool hit = true; - rayPos[2] -= t; - - // Now test if the intersected point is actually on the brush - for (int j = 0; j < currentWeatherBrush->numPlanes; j++) - { - vec4_t *plane = ¤tWeatherBrush->planes[j]; - vec3_t normal = { - currentWeatherBrush->planes[j][0], - currentWeatherBrush->planes[j][1], - currentWeatherBrush->planes[j][2] - }; - if (DotProduct(rayPos, normal) > currentWeatherBrush->planes[j][3] + 1e-3) - hit = false; - } - - if (!hit) - continue; - - // Just draw it when batch is full - if (tess.numVertexes + 4 >= SHADER_MAX_VERTEXES || tess.numIndexes + 6 >= SHADER_MAX_INDEXES) - { - RB_UpdateVBOs(ATTR_POSITION); - GLSL_VertexAttribsState(ATTR_POSITION, NULL); - GLSL_BindProgram(&tr.textureColorShader); - GLSL_SetUniformMatrix4x4( - &tr.textureColorShader, - UNIFORM_MODELVIEWPROJECTIONMATRIX, - tr.weatherSystem->weatherMVP); - R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); - - RB_CommitInternalBufferData(); - - tess.numIndexes = 0; - tess.numVertexes = 0; - tess.firstIndex = 0; - tess.multiDrawPrimitives = 0; - tess.externalIBO = nullptr; - } - - RB_AddQuadStamp(rayPos, left, up, color); + float dist = 0.0f; + if (intersectPlane(plane_normal, plane_dist, rayPos, traceVec, dist)) + t = MAX(t, dist); } - } - R_NewFrameSync(); - } - // draw remaining quads - RB_UpdateVBOs(ATTR_POSITION); - GLSL_VertexAttribsState(ATTR_POSITION, NULL); - GLSL_BindProgram(&tr.textureColorShader); - GLSL_SetUniformMatrix4x4( - &tr.textureColorShader, - UNIFORM_MODELVIEWPROJECTIONMATRIX, - tr.weatherSystem->weatherMVP); - R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); - - RB_CommitInternalBufferData(); - - tess.numIndexes = 0; - tess.numVertexes = 0; - tess.firstIndex = 0; - tess.multiDrawPrimitives = 0; - tess.externalIBO = nullptr; - - qglDisable(GL_DEPTH_CLAMP); - } + bool hit = true; + rayPos[2] -= t; + + // Now test if the intersected point is actually on the brush + for (int j = 0; j < currentWeatherBrush->numPlanes; j++) { + vec4_t *plane = ¤tWeatherBrush->planes[j]; + vec3_t normal = {currentWeatherBrush->planes[j][0], currentWeatherBrush->planes[j][1], currentWeatherBrush->planes[j][2]}; + if (DotProduct(rayPos, normal) > currentWeatherBrush->planes[j][3] + 1e-3) + hit = false; + } - RE_BeginFrame(STEREO_CENTER); + if (!hit) + continue; - if (tr.weatherSystem->numWeatherBrushes > 0) - tr.viewParms.flags |= VPF_NOCLEAR; + // Just draw it when batch is full + if (tess.numVertexes + 4 >= SHADER_MAX_VERTEXES || tess.numIndexes + 6 >= SHADER_MAX_INDEXES) { + RB_UpdateVBOs(ATTR_POSITION); + GLSL_VertexAttribsState(ATTR_POSITION, NULL); + GLSL_BindProgram(&tr.textureColorShader); + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, tr.weatherSystem->weatherMVP); + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); - tr.refdef.numDrawSurfs = 0; - tr.refdef.drawSurfs = backEndData->drawSurfs; + RB_CommitInternalBufferData(); - tr.refdef.num_entities = 0; - tr.refdef.entities = backEndData->entities; + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.multiDrawPrimitives = 0; + tess.externalIBO = nullptr; + } - tr.refdef.num_dlights = 0; - tr.refdef.dlights = backEndData->dlights; + RB_AddQuadStamp(rayPos, left, up, color); + } + } + R_NewFrameSync(); + } - tr.refdef.fistDrawSurf = 0; + // draw remaining quads + RB_UpdateVBOs(ATTR_POSITION); + GLSL_VertexAttribsState(ATTR_POSITION, NULL); + GLSL_BindProgram(&tr.textureColorShader); + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, tr.weatherSystem->weatherMVP); + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); - tr.skyPortalEntities = 0; + RB_CommitInternalBufferData(); - tr.viewParms.targetFbo = tr.weatherDepthFbo; - tr.viewParms.currentViewParm = 0; - Com_Memcpy(&tr.cachedViewParms[0], &tr.viewParms, sizeof(viewParms_t)); - tr.numCachedViewParms = 1; + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.multiDrawPrimitives = 0; + tess.externalIBO = nullptr; - RB_UpdateConstants(&tr.refdef); + qglDisable(GL_DEPTH_CLAMP); + } - R_GenerateDrawSurfs(&tr.viewParms, &tr.refdef); - R_SortAndSubmitDrawSurfs(tr.refdef.drawSurfs, tr.refdef.numDrawSurfs); + RE_BeginFrame(STEREO_CENTER); - R_IssuePendingRenderCommands(); - tr.refdef.numDrawSurfs = 0; - tr.numCachedViewParms = 0; + if (tr.weatherSystem->numWeatherBrushes > 0) + tr.viewParms.flags |= VPF_NOCLEAR; - RE_EndScene(); + tr.refdef.numDrawSurfs = 0; + tr.refdef.drawSurfs = backEndData->drawSurfs; - R_NewFrameSync(); - } + tr.refdef.num_entities = 0; + tr.refdef.entities = backEndData->entities; - void RB_SimulateWeather(weatherObject_t *ws, vec2_t *zoneOffsets, int zoneIndex) - { - if (ws->vboLastUpdateFrame == backEndData->realFrameNumber || - tr.weatherSystem->frozen) - { - // Already simulated for this frame - return; - } + tr.refdef.num_dlights = 0; + tr.refdef.dlights = backEndData->dlights; - // Intentionally switched. Previous frame's VBO would be in ws.vbo and - // this frame's VBO would be ws.lastVBO. - VBO_t *lastRainVBO = ws->vbo; - VBO_t *rainVBO = ws->lastVBO; + tr.refdef.fistDrawSurf = 0; - Allocator& frameAllocator = *backEndData->perFrameMemory; + tr.skyPortalEntities = 0; - DrawItem item = {}; - item.renderState.transformFeedback = true; - item.transformFeedbackBuffer = {rainVBO->vertexesVBO, 0, rainVBO->vertexesSize}; - item.program = &tr.weatherUpdateShader; + tr.viewParms.targetFbo = tr.weatherDepthFbo; + tr.viewParms.currentViewParm = 0; + Com_Memcpy(&tr.cachedViewParms[0], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms = 1; - const size_t numAttribs = ARRAY_LEN(ws->attribsTemplate); - item.numAttributes = numAttribs; - item.attributes = ojkAllocArray( - *backEndData->perFrameMemory, numAttribs); - memcpy( - item.attributes, - ws->attribsTemplate, - sizeof(*item.attributes) * numAttribs); - item.attributes[0].vbo = lastRainVBO; - item.attributes[1].vbo = lastRainVBO; - - UniformDataWriter uniformDataWriter; - uniformDataWriter.Start(&tr.weatherUpdateShader); - - const vec2_t mapZExtents = { - tr.world->bmodels[0].bounds[0][2], - tr.world->bmodels[0].bounds[1][2] - }; - const float frictionInverse = 0.7f; - vec3_t envForce = { - tr.weatherSystem->windDirection[0] * frictionInverse, - tr.weatherSystem->windDirection[1] * frictionInverse, - -ws->gravity * frictionInverse - }; - vec4_t randomOffset = { - Q_flrand(-4.0f, 4.0f), - Q_flrand(-4.0f, 4.0f), - Q_flrand(0.0f, 1.0f), - tr.world->bmodels[0].bounds[1][2] - backEnd.viewParms.ori.origin[2] - }; - uniformDataWriter.SetUniformVec2(UNIFORM_MAPZEXTENTS, mapZExtents); - uniformDataWriter.SetUniformVec3(UNIFORM_ENVFORCE, envForce); - uniformDataWriter.SetUniformVec4(UNIFORM_RANDOMOFFSET, randomOffset); - uniformDataWriter.SetUniformVec2(UNIFORM_ZONEOFFSET, (float*)zoneOffsets, 9); - uniformDataWriter.SetUniformInt(UNIFORM_CHUNK_PARTICLES, ws->particleCount); + RB_UpdateConstants(&tr.refdef); - item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); + R_GenerateDrawSurfs(&tr.viewParms, &tr.refdef); + R_SortAndSubmitDrawSurfs(tr.refdef.drawSurfs, tr.refdef.numDrawSurfs); - const GLuint currentFrameUbo = backEndData->currentFrame->ubo; - const UniformBlockBinding uniformBlockBindings[] = { - { currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE } - }; - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + R_IssuePendingRenderCommands(); + tr.refdef.numDrawSurfs = 0; + tr.numCachedViewParms = 0; - item.draw.type = DRAW_COMMAND_ARRAYS; - item.draw.numInstances = 1; - item.draw.primitiveType = GL_POINTS; - item.draw.params.arrays.numVertices = ws->particleCount * CHUNK_COUNT; + RE_EndScene(); - // This is a bit dodgy. Push this towards the front of the queue so we - // guarantee this happens before the actual drawing - const uint32_t key = RB_CreateSortKey(item, 0, SS_ENVIRONMENT); - RB_AddDrawItem(backEndData->currentPass, key, item); + R_NewFrameSync(); +} - ws->vboLastUpdateFrame = backEndData->realFrameNumber; - std::swap(ws->lastVBO, ws->vbo); +void RB_SimulateWeather(weatherObject_t *ws, vec2_t *zoneOffsets, int zoneIndex) { + if (ws->vboLastUpdateFrame == backEndData->realFrameNumber || tr.weatherSystem->frozen) { + // Already simulated for this frame + return; } + + // Intentionally switched. Previous frame's VBO would be in ws.vbo and + // this frame's VBO would be ws.lastVBO. + VBO_t *lastRainVBO = ws->vbo; + VBO_t *rainVBO = ws->lastVBO; + + Allocator &frameAllocator = *backEndData->perFrameMemory; + + DrawItem item = {}; + item.renderState.transformFeedback = true; + item.transformFeedbackBuffer = {rainVBO->vertexesVBO, 0, rainVBO->vertexesSize}; + item.program = &tr.weatherUpdateShader; + + const size_t numAttribs = ARRAY_LEN(ws->attribsTemplate); + item.numAttributes = numAttribs; + item.attributes = ojkAllocArray(*backEndData->perFrameMemory, numAttribs); + memcpy(item.attributes, ws->attribsTemplate, sizeof(*item.attributes) * numAttribs); + item.attributes[0].vbo = lastRainVBO; + item.attributes[1].vbo = lastRainVBO; + + UniformDataWriter uniformDataWriter; + uniformDataWriter.Start(&tr.weatherUpdateShader); + + const vec2_t mapZExtents = {tr.world->bmodels[0].bounds[0][2], tr.world->bmodels[0].bounds[1][2]}; + const float frictionInverse = 0.7f; + vec3_t envForce = {tr.weatherSystem->windDirection[0] * frictionInverse, tr.weatherSystem->windDirection[1] * frictionInverse, + -ws->gravity * frictionInverse}; + vec4_t randomOffset = {Q_flrand(-4.0f, 4.0f), Q_flrand(-4.0f, 4.0f), Q_flrand(0.0f, 1.0f), + tr.world->bmodels[0].bounds[1][2] - backEnd.viewParms.ori.origin[2]}; + uniformDataWriter.SetUniformVec2(UNIFORM_MAPZEXTENTS, mapZExtents); + uniformDataWriter.SetUniformVec3(UNIFORM_ENVFORCE, envForce); + uniformDataWriter.SetUniformVec4(UNIFORM_RANDOMOFFSET, randomOffset); + uniformDataWriter.SetUniformVec2(UNIFORM_ZONEOFFSET, (float *)zoneOffsets, 9); + uniformDataWriter.SetUniformInt(UNIFORM_CHUNK_PARTICLES, ws->particleCount); + + item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); + + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + const UniformBlockBinding uniformBlockBindings[] = {{currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE}}; + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); + + item.draw.type = DRAW_COMMAND_ARRAYS; + item.draw.numInstances = 1; + item.draw.primitiveType = GL_POINTS; + item.draw.params.arrays.numVertices = ws->particleCount * CHUNK_COUNT; + + // This is a bit dodgy. Push this towards the front of the queue so we + // guarantee this happens before the actual drawing + const uint32_t key = RB_CreateSortKey(item, 0, SS_ENVIRONMENT); + RB_AddDrawItem(backEndData->currentPass, key, item); + + ws->vboLastUpdateFrame = backEndData->realFrameNumber; + std::swap(ws->lastVBO, ws->vbo); } +} // namespace -void R_InitWeatherForMap() -{ +void R_InitWeatherForMap() { for (int i = 0; i < NUM_WEATHER_TYPES; i++) if (tr.weatherSystem->weatherSlots[i].active) GenerateRainModel(tr.weatherSystem->weatherSlots[i], maxWeatherTypeParticles[i]); GenerateDepthMap(); } -void R_InitWeatherSystem() -{ +void R_InitWeatherSystem() { Com_Printf("Initializing weather system\n"); - tr.weatherSystem = - (weatherSystem_t *)Z_Malloc(sizeof(*tr.weatherSystem), TAG_R_TERRAIN, qtrue); + tr.weatherSystem = (weatherSystem_t *)Z_Malloc(sizeof(*tr.weatherSystem), TAG_R_TERRAIN, qtrue); tr.weatherSystem->weatherSurface.surfaceType = SF_WEATHER; tr.weatherSystem->frozen = false; tr.weatherSystem->activeWeatherTypes = 0; @@ -484,19 +384,14 @@ void R_InitWeatherSystem() tr.weatherSystem->weatherSlots[i].active = false; } -void R_ShutdownWeatherSystem() -{ - if (tr.weatherSystem != nullptr) - { +void R_ShutdownWeatherSystem() { + if (tr.weatherSystem != nullptr) { Com_Printf("Shutting down weather system\n"); Z_Free(tr.weatherSystem); tr.weatherSystem = nullptr; - } - else - { - ri.Printf(PRINT_DEVELOPER, - "Weather system shutdown requested, but it is already shut down.\n"); + } else { + ri.Printf(PRINT_DEVELOPER, "Weather system shutdown requested, but it is already shut down.\n"); } } @@ -506,8 +401,8 @@ WE_ParseVector =============== */ qboolean WE_ParseVector(const char **text, int count, float *v) { - char *token; - int i; + char *token; + int i; // FIXME: spaces are currently required after parens, should change parseext... token = COM_ParseExt(text, qfalse); @@ -534,10 +429,8 @@ qboolean WE_ParseVector(const char **text, int count, float *v) { return qtrue; } -void R_AddWeatherBrush(uint8_t numPlanes, vec4_t *planes) -{ - if (tr.weatherSystem->numWeatherBrushes >= (MAX_WEATHER_ZONES * 2)) - { +void R_AddWeatherBrush(uint8_t numPlanes, vec4_t *planes) { + if (tr.weatherSystem->numWeatherBrushes >= (MAX_WEATHER_ZONES * 2)) { ri.Printf(PRINT_WARNING, "Max weather brushes hit. Skipping new inside/outside brush\n"); return; } @@ -547,27 +440,23 @@ void R_AddWeatherBrush(uint8_t numPlanes, vec4_t *planes) tr.weatherSystem->numWeatherBrushes++; } -void RE_WorldEffectCommand(const char *command) -{ - if (!command) - { +void RE_WorldEffectCommand(const char *command) { + if (!command) { return; } COM_BeginParseSession("RE_WorldEffectCommand"); - const char *token;//, *origCommand; + const char *token; //, *origCommand; token = COM_ParseExt(&command, qfalse); - if (!token) - { + if (!token) { return; } - //Die - clean up the whole weather system -rww - if (Q_stricmp(token, "die") == 0) - { + // Die - clean up the whole weather system -rww + if (Q_stricmp(token, "die") == 0) { for (int i = 0; i < NUM_WEATHER_TYPES; i++) tr.weatherSystem->weatherSlots[i].active = false; tr.weatherSystem->activeWeatherTypes = 0; @@ -577,8 +466,7 @@ void RE_WorldEffectCommand(const char *command) // Clear - Removes All Particle Clouds And Wind Zones //---------------------------------------------------- - else if (Q_stricmp(token, "clear") == 0) - { + else if (Q_stricmp(token, "clear") == 0) { for (int i = 0; i < NUM_WEATHER_TYPES; i++) tr.weatherSystem->weatherSlots[i].active = false; tr.weatherSystem->activeWeatherTypes = 0; @@ -588,22 +476,19 @@ void RE_WorldEffectCommand(const char *command) // Freeze / UnFreeze - Stops All Particle Motion Updates //-------------------------------------------------------- - else if (Q_stricmp(token, "freeze") == 0) - { + else if (Q_stricmp(token, "freeze") == 0) { tr.weatherSystem->frozen = !tr.weatherSystem->frozen; } //// Add a zone ////--------------- - else if (Q_stricmp(token, "zone") == 0) - { + else if (Q_stricmp(token, "zone") == 0) { ri.Printf(PRINT_DEVELOPER, "Weather zones aren't used in rend2, but inside/outside brushes\n"); } // Basic Wind //------------ - else if (Q_stricmp(token, "wind") == 0) - { + else if (Q_stricmp(token, "wind") == 0) { windObject_t *currentWindObject = &tr.weatherSystem->windSlots[tr.weatherSystem->activeWindObjects]; currentWindObject->chanceOfDeadTime = 0.3f; currentWindObject->deadTimeMinMax[0] = 1000.0f; @@ -620,27 +505,18 @@ void RE_WorldEffectCommand(const char *command) // Constant Wind //--------------- - else if (Q_stricmp(token, "constantwind") == 0) - { + else if (Q_stricmp(token, "constantwind") == 0) { vec3_t parsedWind; - vec3_t defaultWind = { 0.f, 0.8f, 0.f }; + vec3_t defaultWind = {0.f, 0.8f, 0.f}; if (!WE_ParseVector(&command, 3, parsedWind)) - VectorAdd( - tr.weatherSystem->constWindDirection, - defaultWind, - tr.weatherSystem->constWindDirection); + VectorAdd(tr.weatherSystem->constWindDirection, defaultWind, tr.weatherSystem->constWindDirection); else - VectorMA( - tr.weatherSystem->constWindDirection, - 0.001f, - parsedWind, - tr.weatherSystem->constWindDirection); + VectorMA(tr.weatherSystem->constWindDirection, 0.001f, parsedWind, tr.weatherSystem->constWindDirection); } // Gusting Wind //-------------- - else if (Q_stricmp(token, "gustingwind") == 0) - { + else if (Q_stricmp(token, "gustingwind") == 0) { windObject_t *currentWindObject = &tr.weatherSystem->windSlots[tr.weatherSystem->activeWindObjects]; currentWindObject->chanceOfDeadTime = 0.3f; currentWindObject->deadTimeMinMax[0] = 2000.0f; @@ -657,8 +533,7 @@ void RE_WorldEffectCommand(const char *command) // Create A Rain Storm //--------------------- - else if (Q_stricmp(token, "lightrain") == 0) - { + else if (Q_stricmp(token, "lightrain") == 0) { /*nCloud.Initialize(500, "gfx/world/rain.jpg", 3); nCloud.mHeight = 80.0f; nCloud.mWidth = 1.2f; @@ -687,16 +562,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, - 0.5f, - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); } // Create A Rain Storm //--------------------- - else if (Q_stricmp(token, "rain") == 0) - { + else if (Q_stricmp(token, "rain") == 0) { /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); nCloud.mHeight = 80.0f; nCloud.mWidth = 1.2f; @@ -725,16 +596,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, - 0.5f, - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); } // Create A Rain Storm //--------------------- - else if (Q_stricmp(token, "acidrain") == 0) - { + else if (Q_stricmp(token, "acidrain") == 0) { /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); nCloud.mHeight = 80.0f; nCloud.mWidth = 2.0f; @@ -768,16 +635,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.34f, 0.7f, 0.34f, 0.7f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, - 0.7f, - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.7f, tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); } // Create A Rain Storm //--------------------- - else if (Q_stricmp(token, "heavyrain") == 0) - { + else if (Q_stricmp(token, "heavyrain") == 0) { /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); nCloud.mHeight = 80.0f; nCloud.mWidth = 1.2f; @@ -806,16 +669,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, - 0.5f, - tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); } // Create A Snow Storm //--------------------- - else if (Q_stricmp(token, "snow") == 0) - { + else if (Q_stricmp(token, "snow") == 0) { /*nCloud.Initialize(1000, "gfx/effects/snowflake1.bmp"); nCloud.mBlendMode = 1; nCloud.mRotationChangeNext = 0; @@ -839,16 +698,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_SNOW].drawImage = R_FindImageFile("gfx/effects/snowflake1", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_SNOW].color, 0.75f, 0.75f, 0.75f, 0.75f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_SNOW].color, - 0.75f, - tr.weatherSystem->weatherSlots[WEATHER_SNOW].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_SNOW].color, 0.75f, tr.weatherSystem->weatherSlots[WEATHER_SNOW].color); } // Create A Some stuff //--------------------- - else if (Q_stricmp(token, "spacedust") == 0) - { + else if (Q_stricmp(token, "spacedust") == 0) { /*nCloud.Initialize(count, "gfx/effects/snowpuff1.tga"); nCloud.mHeight = 1.2f; nCloud.mWidth = 1.2f; @@ -887,16 +742,12 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].drawImage = R_FindImageFile("gfx/effects/snowpuff1", type, flags); VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color, 0.75f, 0.75f, 0.75f, 0.75f); - VectorScale( - tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color, - 0.75f, - tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color, 0.75f, tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color); } // Create A Sand Storm //--------------------- - else if (Q_stricmp(token, "sand") == 0) - { + else if (Q_stricmp(token, "sand") == 0) { /*nCloud.Initialize(400, "gfx/effects/alpha_smoke2b.tga"); nCloud.mGravity = 0; @@ -935,8 +786,7 @@ void RE_WorldEffectCommand(const char *command) // Create Blowing Clouds Of Fog //------------------------------ - else if (Q_stricmp(token, "fog") == 0) - { + else if (Q_stricmp(token, "fog") == 0) { /*nCloud.Initialize(60, "gfx/effects/alpha_smoke2b.tga"); nCloud.mBlendMode = 1; nCloud.mGravity = 0; @@ -973,8 +823,7 @@ void RE_WorldEffectCommand(const char *command) // Create Heavy Rain Particle Cloud //----------------------------------- - else if (Q_stricmp(token, "heavyrainfog") == 0) - { + else if (Q_stricmp(token, "heavyrainfog") == 0) { /*nCloud.Initialize(70, "gfx/effects/alpha_smoke2b.tga"); nCloud.mBlendMode = 1; nCloud.mGravity = 0; @@ -996,7 +845,7 @@ void RE_WorldEffectCommand(const char *command) tr.weatherSystem->weatherSlots[WEATHER_FOG].particleCount = 70; tr.weatherSystem->weatherSlots[WEATHER_FOG].active = true; - tr.weatherSystem->weatherSlots[WEATHER_FOG].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].gravity = 0.0f; tr.weatherSystem->weatherSlots[WEATHER_FOG].fadeDistance = 2400.f; tr.weatherSystem->weatherSlots[WEATHER_FOG].size[0] = 300.f; @@ -1014,8 +863,7 @@ void RE_WorldEffectCommand(const char *command) // Create Blowing Clouds Of Fog //------------------------------ - else if (Q_stricmp(token, "light_fog") == 0) - { + else if (Q_stricmp(token, "light_fog") == 0) { /*nCloud.Initialize(40, "gfx/effects/alpha_smoke2b.tga"); nCloud.mBlendMode = 1; nCloud.mGravity = 0; @@ -1053,16 +901,11 @@ void RE_WorldEffectCommand(const char *command) VectorScale(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.12f, tr.weatherSystem->weatherSlots[WEATHER_FOG].color); } - else if (Q_stricmp(token, "outsideshake") == 0) - { + else if (Q_stricmp(token, "outsideshake") == 0) { ri.Printf(PRINT_DEVELOPER, "outsideshake isn't supported in MP\n"); - } - else if (Q_stricmp(token, "outsidepain") == 0) - { + } else if (Q_stricmp(token, "outsidepain") == 0) { ri.Printf(PRINT_DEVELOPER, "outsidepain isn't supported in MP\n"); - } - else - { + } else { ri.Printf(PRINT_ALL, "Weather Effect: Please enter a valid command.\n"); ri.Printf(PRINT_ALL, " die\n"); ri.Printf(PRINT_ALL, " clear\n"); @@ -1071,7 +914,7 @@ void RE_WorldEffectCommand(const char *command) ri.Printf(PRINT_ALL, " wind\n"); ri.Printf(PRINT_ALL, " constantwind (velocity)\n"); ri.Printf(PRINT_ALL, " gustingwind\n"); - //ri.Printf(PRINT_ALL, " windzone (mins) (maxs) (velocity)\n"); + // ri.Printf(PRINT_ALL, " windzone (mins) (maxs) (velocity)\n"); ri.Printf(PRINT_ALL, " lightrain\n"); ri.Printf(PRINT_ALL, " rain\n"); ri.Printf(PRINT_ALL, " acidrain\n"); @@ -1083,41 +926,33 @@ void RE_WorldEffectCommand(const char *command) ri.Printf(PRINT_ALL, " heavyrainfog\n"); ri.Printf(PRINT_ALL, " light_fog\n"); ri.Printf(PRINT_ALL, " outsideshake\n"); // not available in MP - ri.Printf(PRINT_ALL, " outsidepain\n"); // not available in MP + ri.Printf(PRINT_ALL, " outsidepain\n"); // not available in MP } } -void R_WorldEffect_f(void) -{ - char temp[2048] = { 0 }; +void R_WorldEffect_f(void) { + char temp[2048] = {0}; ri.Cmd_ArgsBuffer(temp, sizeof(temp)); RE_WorldEffectCommand(temp); } -void R_AddWeatherSurfaces() -{ +void R_AddWeatherSurfaces() { assert(tr.weatherSystem); - if (tr.weatherSystem->activeWeatherTypes == 0 && - r_debugWeather->integer == 0) + if (tr.weatherSystem->activeWeatherTypes == 0 && r_debugWeather->integer == 0) return; - R_AddDrawSurf( - (surfaceType_t *)&tr.weatherSystem->weatherSurface, - REFENTITYNUM_WORLD, - tr.weatherInternalShader, - 0, /* fogIndex */ - qfalse, /* dlightMap */ - qfalse, /* postRender */ - 0 /* cubemapIndex */ + R_AddDrawSurf((surfaceType_t *)&tr.weatherSystem->weatherSurface, REFENTITYNUM_WORLD, tr.weatherInternalShader, 0, /* fogIndex */ + qfalse, /* dlightMap */ + qfalse, /* postRender */ + 0 /* cubemapIndex */ ); } -void RB_SurfaceWeather( srfWeather_t *surf ) -{ +void RB_SurfaceWeather(srfWeather_t *surf) { assert(tr.weatherSystem); - weatherSystem_t& ws = *tr.weatherSystem; + weatherSystem_t &ws = *tr.weatherSystem; assert(surf == &ws.weatherSurface); RB_EndSurface(); @@ -1126,27 +961,20 @@ void RB_SurfaceWeather( srfWeather_t *surf ) const float numMinZonesY = std::floor((abs(tr.world->bmodels[0].bounds[0][1]) / CHUNK_EXTENDS) + 0.5f); vec3_t viewOrigin; VectorCopy(backEnd.viewParms.ori.origin, viewOrigin); - float centerZoneOffsetX = - std::floor((viewOrigin[0] / CHUNK_EXTENDS) + 0.5f); - float centerZoneOffsetY = - std::floor((viewOrigin[1] / CHUNK_EXTENDS) + 0.5f); + float centerZoneOffsetX = std::floor((viewOrigin[0] / CHUNK_EXTENDS) + 0.5f); + float centerZoneOffsetY = std::floor((viewOrigin[1] / CHUNK_EXTENDS) + 0.5f); vec2_t zoneOffsets[9]; - GLint zoneMapping[9]; - int centerZoneIndex; + GLint zoneMapping[9]; + int centerZoneIndex; { int chunkIndex = 0; int currentIndex = 0; - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x, ++currentIndex) - { - chunkIndex = (int(centerZoneOffsetX + numMinZonesX) + x + 1) % 3; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x, ++currentIndex) { + chunkIndex = (int(centerZoneOffsetX + numMinZonesX) + x + 1) % 3; chunkIndex += (int(centerZoneOffsetY + numMinZonesY) + y + 1) % 3 * 3; - VectorSet2( - zoneOffsets[chunkIndex], - x, - y); + VectorSet2(zoneOffsets[chunkIndex], x, y); zoneMapping[currentIndex] = chunkIndex; if (x == 0 && y == 0) centerZoneIndex = currentIndex; @@ -1156,55 +984,41 @@ void RB_SurfaceWeather( srfWeather_t *surf ) // Get current global wind vector VectorCopy(tr.weatherSystem->constWindDirection, tr.weatherSystem->windDirection); - for (int i = 0; i < tr.weatherSystem->activeWindObjects; i++) - { + for (int i = 0; i < tr.weatherSystem->activeWindObjects; i++) { windObject_t *windObject = &tr.weatherSystem->windSlots[i]; RB_UpdateWindObject(windObject); VectorAdd(windObject->currentVelocity, tr.weatherSystem->windDirection, tr.weatherSystem->windDirection); } - Allocator& frameAllocator = *backEndData->perFrameMemory; + Allocator &frameAllocator = *backEndData->perFrameMemory; // Simulate and render all the weather zones - for (int weatherType = 0; weatherType < NUM_WEATHER_TYPES; weatherType++) - { + for (int weatherType = 0; weatherType < NUM_WEATHER_TYPES; weatherType++) { weatherObject_t *weatherObject = &ws.weatherSlots[weatherType]; if (!weatherObject->active) continue; if (weatherObject->vbo == nullptr) - GenerateRainModel( - tr.weatherSystem->weatherSlots[weatherType], - maxWeatherTypeParticles[weatherType]); + GenerateRainModel(tr.weatherSystem->weatherSlots[weatherType], maxWeatherTypeParticles[weatherType]); RB_SimulateWeather(weatherObject, &zoneOffsets[0], centerZoneIndex); - vec4_t viewInfo = { - weatherObject->size[0], - weatherObject->size[1], - weatherObject->velocityOrientationScale, - weatherObject->fadeDistance - }; + vec4_t viewInfo = {weatherObject->size[0], weatherObject->size[1], weatherObject->velocityOrientationScale, weatherObject->fadeDistance}; - int stateBits = weatherType == WEATHER_SAND ? - GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA : - GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + int stateBits = weatherType == WEATHER_SAND ? GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA + : GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; DrawItem item = {}; item.renderState.stateBits = stateBits; item.renderState.cullType = CT_TWO_SIDED; - item.renderState.depthRange = { 0.0f, 1.0f }; + item.renderState.depthRange = {0.0f, 1.0f}; item.program = &tr.weatherShader; const size_t numAttribs = ARRAY_LEN(weatherObject->attribsTemplate); item.numAttributes = numAttribs; - item.attributes = ojkAllocArray( - *backEndData->perFrameMemory, numAttribs); - memcpy( - item.attributes, - weatherObject->attribsTemplate, - sizeof(*item.attributes) * numAttribs); + item.attributes = ojkAllocArray(*backEndData->perFrameMemory, numAttribs); + memcpy(item.attributes, weatherObject->attribsTemplate, sizeof(*item.attributes) * numAttribs); item.attributes[0].vbo = weatherObject->vbo; item.attributes[1].vbo = weatherObject->vbo; @@ -1213,25 +1027,17 @@ void RB_SurfaceWeather( srfWeather_t *surf ) item.draw.primitiveType = GL_POINTS; item.draw.params.arrays.numVertices = weatherObject->particleCount; - //TODO: Cull non visable zones + // TODO: Cull non visable zones int currentIndex = 0; - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x, ++currentIndex) - { + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x, ++currentIndex) { const GLuint currentFrameUbo = backEndData->currentFrame->ubo; - const UniformBlockBinding uniformBlockBindings[] = { - { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA } - }; - DrawItemSetUniformBlockBindings( - item, uniformBlockBindings, frameAllocator); + const UniformBlockBinding uniformBlockBindings[] = {{currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA}}; + DrawItemSetUniformBlockBindings(item, uniformBlockBindings, frameAllocator); UniformDataWriter uniformDataWriter; uniformDataWriter.Start(&tr.weatherShader); - uniformDataWriter.SetUniformVec2( - UNIFORM_ZONEOFFSET, - (centerZoneOffsetX + x) * CHUNK_EXTENDS, - (centerZoneOffsetY + y) * CHUNK_EXTENDS); + uniformDataWriter.SetUniformVec2(UNIFORM_ZONEOFFSET, (centerZoneOffsetX + x) * CHUNK_EXTENDS, (centerZoneOffsetY + y) * CHUNK_EXTENDS); uniformDataWriter.SetUniformFloat(UNIFORM_TIME, backEnd.refdef.frameTime); uniformDataWriter.SetUniformVec4(UNIFORM_COLOR, weatherObject->color); uniformDataWriter.SetUniformVec4(UNIFORM_VIEWINFO, viewInfo); @@ -1245,8 +1051,7 @@ void RB_SurfaceWeather( srfWeather_t *surf ) else samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DIFFUSEMAP); - item.samplerBindings = samplerBindingsWriter.Finish( - frameAllocator, &item.numSamplerBindings); + item.samplerBindings = samplerBindingsWriter.Finish(frameAllocator, &item.numSamplerBindings); item.draw.params.arrays.firstVertex = weatherObject->particleCount * zoneMapping[currentIndex]; diff --git a/codemp/rd-rend2/tr_world.cpp b/codemp/rd-rend2/tr_world.cpp index 0204652440..859f2525b4 100644 --- a/codemp/rd-rend2/tr_world.cpp +++ b/codemp/rd-rend2/tr_world.cpp @@ -21,15 +21,10 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tr_local.h" - -world_t *R_GetWorld(int worldIndex) -{ - if (worldIndex == -1) - { +world_t *R_GetWorld(int worldIndex) { + if (worldIndex == -1) { return tr.world; - } - else - { + } else { return tr.bspModels[worldIndex]; } } @@ -42,40 +37,34 @@ Tries to cull surfaces before they are lighted or added to the sorting list. ================ */ -static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { - if ( r_nocull->integer || surf->cullinfo.type == CULLINFO_NONE) { +static qboolean R_CullSurface(msurface_t *surf, int entityNum) { + if (r_nocull->integer || surf->cullinfo.type == CULLINFO_NONE) { return qfalse; } - if ( *surf->data == SF_GRID && r_nocurves->integer ) { + if (*surf->data == SF_GRID && r_nocurves->integer) { return qtrue; } - if (surf->cullinfo.type & CULLINFO_PLANE) - { + if (surf->cullinfo.type & CULLINFO_PLANE) { // Only true for SF_FACE, so treat like its own function - float d; + float d; cullType_t ct; - if ( !r_facePlaneCull->integer ) { + if (!r_facePlaneCull->integer) { return qfalse; } ct = surf->shader->cullType; - if (ct == CT_TWO_SIDED) - { + if (ct == CT_TWO_SIDED) { return qfalse; } - if (tr.viewParms.flags & (VPF_DEPTHSHADOW) && tr.viewParms.flags & (VPF_SHADOWCASCADES)) - { - if (ct == CT_FRONT_SIDED) - { + if (tr.viewParms.flags & (VPF_DEPTHSHADOW) && tr.viewParms.flags & (VPF_SHADOWCASCADES)) { + if (ct == CT_FRONT_SIDED) { ct = CT_BACK_SIDED; - } - else if (ct == CT_BACK_SIDED) - { + } else if (ct == CT_BACK_SIDED) { ct = CT_FRONT_SIDED; } } @@ -83,7 +72,7 @@ static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { // do proper cull for orthographic projection if (tr.viewParms.flags & VPF_ORTHOGRAPHIC) { d = DotProduct(tr.viewParms.ori.axis[0], surf->cullinfo.plane.normal); - if ( ct == CT_FRONT_SIDED ) { + if (ct == CT_FRONT_SIDED) { if (d > 0) return qtrue; } else { @@ -93,17 +82,17 @@ static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { return qfalse; } - d = DotProduct (tr.ori.viewOrigin, surf->cullinfo.plane.normal); + d = DotProduct(tr.ori.viewOrigin, surf->cullinfo.plane.normal); // don't cull exactly on the plane, because there are levels of rounding // through the BSP, ICD, and hardware that may cause pixel gaps if an - // epsilon isn't allowed here - if ( ct == CT_FRONT_SIDED ) { - if ( d < surf->cullinfo.plane.dist - 8 ) { + // epsilon isn't allowed here + if (ct == CT_FRONT_SIDED) { + if (d < surf->cullinfo.plane.dist - 8) { return qtrue; } } else { - if ( d > surf->cullinfo.plane.dist + 8 ) { + if (d > surf->cullinfo.plane.dist + 8) { return qtrue; } } @@ -111,34 +100,30 @@ static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { return qfalse; } - if (surf->cullinfo.type & CULLINFO_SPHERE) - { - int sphereCull; + if (surf->cullinfo.type & CULLINFO_SPHERE) { + int sphereCull; - if ( entityNum != REFENTITYNUM_WORLD ) { - sphereCull = R_CullLocalPointAndRadius( surf->cullinfo.localOrigin, surf->cullinfo.radius ); + if (entityNum != REFENTITYNUM_WORLD) { + sphereCull = R_CullLocalPointAndRadius(surf->cullinfo.localOrigin, surf->cullinfo.radius); } else { - sphereCull = R_CullPointAndRadius( surf->cullinfo.localOrigin, surf->cullinfo.radius ); + sphereCull = R_CullPointAndRadius(surf->cullinfo.localOrigin, surf->cullinfo.radius); } - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == CULL_OUT) { return qtrue; } } - if (surf->cullinfo.type & CULLINFO_BOX) - { + if (surf->cullinfo.type & CULLINFO_BOX) { int boxCull; - if ( entityNum != REFENTITYNUM_WORLD ) { - boxCull = R_CullLocalBox( surf->cullinfo.bounds ); + if (entityNum != REFENTITYNUM_WORLD) { + boxCull = R_CullLocalBox(surf->cullinfo.bounds); } else { - boxCull = R_CullBox( surf->cullinfo.bounds ); + boxCull = R_CullBox(surf->cullinfo.bounds); } - if ( boxCull == CULL_OUT ) - { + if (boxCull == CULL_OUT) { return qtrue; } } @@ -146,7 +131,6 @@ static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { return qfalse; } - /* ==================== R_DlightSurface @@ -156,75 +140,67 @@ that is touched by one or more dlights, so try to throw out more dlights if possible. ==================== */ -static int R_DlightSurface( msurface_t *surf, int dlightBits ) { - float d; - int i; - dlight_t *dl; - - if ( surf->cullinfo.type & CULLINFO_PLANE ) - { - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { +static int R_DlightSurface(msurface_t *surf, int dlightBits) { + float d; + int i; + dlight_t *dl; + + if (surf->cullinfo.type & CULLINFO_PLANE) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - d = DotProduct( dl->origin, surf->cullinfo.plane.normal ) - surf->cullinfo.plane.dist; - if ( d < -dl->radius || d > dl->radius ) { + d = DotProduct(dl->origin, surf->cullinfo.plane.normal) - surf->cullinfo.plane.dist; + if (d < -dl->radius || d > dl->radius) { // dlight doesn't reach the plane - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } } - - if ( surf->cullinfo.type & CULLINFO_BOX ) - { - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + + if (surf->cullinfo.type & CULLINFO_BOX) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - if ( dl->origin[0] - dl->radius > surf->cullinfo.bounds[1][0] - || dl->origin[0] + dl->radius < surf->cullinfo.bounds[0][0] - || dl->origin[1] - dl->radius > surf->cullinfo.bounds[1][1] - || dl->origin[1] + dl->radius < surf->cullinfo.bounds[0][1] - || dl->origin[2] - dl->radius > surf->cullinfo.bounds[1][2] - || dl->origin[2] + dl->radius < surf->cullinfo.bounds[0][2] ) { + if (dl->origin[0] - dl->radius > surf->cullinfo.bounds[1][0] || dl->origin[0] + dl->radius < surf->cullinfo.bounds[0][0] || + dl->origin[1] - dl->radius > surf->cullinfo.bounds[1][1] || dl->origin[1] + dl->radius < surf->cullinfo.bounds[0][1] || + dl->origin[2] - dl->radius > surf->cullinfo.bounds[1][2] || dl->origin[2] + dl->radius < surf->cullinfo.bounds[0][2]) { // dlight doesn't reach the bounds - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } } - if ( surf->cullinfo.type & CULLINFO_SPHERE ) - { - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + if (surf->cullinfo.type & CULLINFO_SPHERE) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - if (!SpheresIntersect(dl->origin, dl->radius, surf->cullinfo.localOrigin, surf->cullinfo.radius)) - { + if (!SpheresIntersect(dl->origin, dl->radius, surf->cullinfo.localOrigin, surf->cullinfo.radius)) { // dlight doesn't reach the bounds - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } } - switch(*surf->data) - { - case SF_FACE: - case SF_GRID: - case SF_TRIANGLES: - case SF_VBO_MESH: - ((srfBspSurface_t *)surf->data)->dlightBits = dlightBits; - break; + switch (*surf->data) { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->dlightBits = dlightBits; + break; - default: - dlightBits = 0; - break; + default: + dlightBits = 0; + break; } - if ( dlightBits ) { + if (dlightBits) { tr.pc.c_dlightSurfaces++; } else { tr.pc.c_dlightSurfacesCulled++; @@ -240,133 +216,113 @@ R_PshadowSurface Just like R_DlightSurface, cull any we can ==================== */ -static int R_PshadowSurface( msurface_t *surf, int pshadowBits ) { - float d; - int i; - pshadow_t *ps; - - if ( surf->cullinfo.type & CULLINFO_PLANE ) - { - for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { - if ( ! ( pshadowBits & ( 1 << i ) ) ) { +static int R_PshadowSurface(msurface_t *surf, int pshadowBits) { + float d; + int i; + pshadow_t *ps; + + if (surf->cullinfo.type & CULLINFO_PLANE) { + for (i = 0; i < tr.refdef.num_pshadows; i++) { + if (!(pshadowBits & (1 << i))) { continue; } ps = &tr.refdef.pshadows[i]; - d = DotProduct( ps->lightOrigin, surf->cullinfo.plane.normal ) - surf->cullinfo.plane.dist; - if ( d < -ps->lightRadius || d > ps->lightRadius ) { + d = DotProduct(ps->lightOrigin, surf->cullinfo.plane.normal) - surf->cullinfo.plane.dist; + if (d < -ps->lightRadius || d > ps->lightRadius) { // pshadow doesn't reach the plane - pshadowBits &= ~( 1 << i ); + pshadowBits &= ~(1 << i); } } } - - if ( surf->cullinfo.type & CULLINFO_BOX ) - { - for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { - if ( ! ( pshadowBits & ( 1 << i ) ) ) { + + if (surf->cullinfo.type & CULLINFO_BOX) { + for (i = 0; i < tr.refdef.num_pshadows; i++) { + if (!(pshadowBits & (1 << i))) { continue; } ps = &tr.refdef.pshadows[i]; - if ( ps->lightOrigin[0] - ps->lightRadius > surf->cullinfo.bounds[1][0] - || ps->lightOrigin[0] + ps->lightRadius < surf->cullinfo.bounds[0][0] - || ps->lightOrigin[1] - ps->lightRadius > surf->cullinfo.bounds[1][1] - || ps->lightOrigin[1] + ps->lightRadius < surf->cullinfo.bounds[0][1] - || ps->lightOrigin[2] - ps->lightRadius > surf->cullinfo.bounds[1][2] - || ps->lightOrigin[2] + ps->lightRadius < surf->cullinfo.bounds[0][2] - || BoxOnPlaneSide(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1], &ps->cullPlane) == 2 ) { + if (ps->lightOrigin[0] - ps->lightRadius > surf->cullinfo.bounds[1][0] || ps->lightOrigin[0] + ps->lightRadius < surf->cullinfo.bounds[0][0] || + ps->lightOrigin[1] - ps->lightRadius > surf->cullinfo.bounds[1][1] || ps->lightOrigin[1] + ps->lightRadius < surf->cullinfo.bounds[0][1] || + ps->lightOrigin[2] - ps->lightRadius > surf->cullinfo.bounds[1][2] || ps->lightOrigin[2] + ps->lightRadius < surf->cullinfo.bounds[0][2] || + BoxOnPlaneSide(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1], &ps->cullPlane) == 2) { // pshadow doesn't reach the bounds - pshadowBits &= ~( 1 << i ); + pshadowBits &= ~(1 << i); } } } - if ( surf->cullinfo.type & CULLINFO_SPHERE ) - { - for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { - if ( ! ( pshadowBits & ( 1 << i ) ) ) { + if (surf->cullinfo.type & CULLINFO_SPHERE) { + for (i = 0; i < tr.refdef.num_pshadows; i++) { + if (!(pshadowBits & (1 << i))) { continue; } ps = &tr.refdef.pshadows[i]; - if (!SpheresIntersect(ps->viewOrigin, ps->viewRadius, surf->cullinfo.localOrigin, surf->cullinfo.radius) - || DotProduct( surf->cullinfo.localOrigin, ps->cullPlane.normal ) - ps->cullPlane.dist < -surf->cullinfo.radius) - { + if (!SpheresIntersect(ps->viewOrigin, ps->viewRadius, surf->cullinfo.localOrigin, surf->cullinfo.radius) || + DotProduct(surf->cullinfo.localOrigin, ps->cullPlane.normal) - ps->cullPlane.dist < -surf->cullinfo.radius) { // pshadow doesn't reach the bounds - pshadowBits &= ~( 1 << i ); + pshadowBits &= ~(1 << i); } } } - switch(*surf->data) - { - case SF_FACE: - case SF_GRID: - case SF_TRIANGLES: - case SF_VBO_MESH: - ((srfBspSurface_t *)surf->data)->pshadowBits = pshadowBits; - break; + switch (*surf->data) { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->pshadowBits = pshadowBits; + break; - default: - pshadowBits = 0; - break; + default: + pshadowBits = 0; + break; } - if ( pshadowBits ) { - //tr.pc.c_dlightSurfaces++; + if (pshadowBits) { + // tr.pc.c_dlightSurfaces++; } return pshadowBits; } - /* ====================== R_AddWorldSurface ====================== */ -static void R_AddWorldSurface( - msurface_t *surf, - const trRefEntity_t *entity, - int entityNum, - int dlightBits, - int pshadowBits) -{ +static void R_AddWorldSurface(msurface_t *surf, const trRefEntity_t *entity, int entityNum, int dlightBits, int pshadowBits) { // FIXME: bmodel fog? // try to cull before dlighting or adding - if ( R_CullSurface( surf, entityNum ) ) { + if (R_CullSurface(surf, entityNum)) { return; } // check for dlighting // TODO: implement dlight culling for non worldspawn surfaces - if ( dlightBits ) { + if (dlightBits) { if (entityNum != REFENTITYNUM_WORLD) dlightBits = (1 << tr.refdef.num_dlights) - 1; else - dlightBits = R_DlightSurface( surf, dlightBits ); + dlightBits = R_DlightSurface(surf, dlightBits); } // set pshadows - if ( pshadowBits ) { - R_PshadowSurface( surf, pshadowBits ); + if (pshadowBits) { + R_PshadowSurface(surf, pshadowBits); } bool isPostRenderEntity = false; - if ( entityNum != REFENTITYNUM_WORLD ) - { + if (entityNum != REFENTITYNUM_WORLD) { assert(entity); isPostRenderEntity = R_IsPostRenderEntity(entity); } - R_AddDrawSurf( surf->data, entityNum, surf->shader, surf->fogIndex, - dlightBits, isPostRenderEntity, surf->cubemapIndex ); + R_AddDrawSurf(surf->data, entityNum, surf->shader, surf->fogIndex, dlightBits, isPostRenderEntity, surf->cubemapIndex); - for ( int i = 0, numSprites = surf->numSurfaceSprites; - i < numSprites; ++i ) - { + for (int i = 0, numSprites = surf->numSurfaceSprites; i < numSprites; ++i) { srfSprites_t *sprites = surf->surfaceSprites + i; - R_AddDrawSurf((surfaceType_t *)sprites, entityNum, sprites->shader, - surf->fogIndex, dlightBits, isPostRenderEntity, 0); + R_AddDrawSurf((surfaceType_t *)sprites, entityNum, sprites->shader, surf->fogIndex, dlightBits, isPostRenderEntity, 0); } } @@ -383,32 +339,30 @@ static void R_AddWorldSurface( R_AddBrushModelSurfaces ================= */ -void R_AddBrushModelSurfaces ( trRefEntity_t *ent, int entityNum ) { - model_t *pModel = R_GetModelByHandle( ent->e.hModel ); +void R_AddBrushModelSurfaces(trRefEntity_t *ent, int entityNum) { + model_t *pModel = R_GetModelByHandle(ent->e.hModel); bmodel_t *bmodel = pModel->data.bmodel; - int clip = R_CullLocalBox( bmodel->bounds ); - if ( clip == CULL_OUT ) { + int clip = R_CullLocalBox(bmodel->bounds); + if (clip == CULL_OUT) { return; } - + if (!(tr.viewParms.flags & VPF_DEPTHSHADOW)) - R_DlightBmodel( bmodel, ent ); + R_DlightBmodel(bmodel, ent); world_t *world = R_GetWorld(bmodel->worldIndex); - for ( int i = 0 ; i < bmodel->numSurfaces ; i++ ) { + for (int i = 0; i < bmodel->numSurfaces; i++) { int surf = bmodel->firstSurface + i; - - if (world->surfacesViewCount[surf] != tr.viewCount) - { + + if (world->surfacesViewCount[surf] != tr.viewCount) { world->surfacesViewCount[surf] = tr.viewCount; R_AddWorldSurface(world->surfaces + surf, ent, entityNum, ent->needDlights, 0); } } } -float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) -{ - vec3_t vec1, vec2, dis1, dis2; +float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) { + vec3_t vec1, vec2, dis1, dis2; // Get area of tri1 VectorSubtract(v1, v2, vec1); @@ -423,27 +377,24 @@ float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) VectorScale(dis2, 0.25f, dis2); // Return addition of disSqr of each tri area - return (dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + - dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2]); + return (dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2]); } -void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) -{ - int surf; - srfBspSurface_t *face; +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { + int surf; + srfBspSurface_t *face; // Not sure if we really need to track the best two candidates - int maxDist[2] = { 0,0 }; - int maxIndx[2] = { 0,0 }; - int dist = 0; - float dot1, dot2; + int maxDist[2] = {0, 0}; + int maxIndx[2] = {0, 0}; + int dist = 0; + float dot1, dot2; model_t *pModel = R_GetModelByHandle(bmodelIndex); bmodel_t *bmodel = pModel->data.bmodel; world_t *world = R_GetWorld(bmodel->worldIndex); // Loop through all surfaces on the brush and find the best two candidates - for (int i = 0; i < bmodel->numSurfaces; i++) - { + for (int i = 0; i < bmodel->numSurfaces; i++) { surf = bmodel->firstSurface + i; face = (srfBspSurface_t *)(world->surfaces + surf)->data; @@ -451,8 +402,7 @@ void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) dist = GetQuadArea(face->verts[0].xyz, face->verts[1].xyz, face->verts[2].xyz, face->verts[3].xyz); // Check against the highest max - if (dist > maxDist[0]) - { + if (dist > maxDist[0]) { // Shuffle our current maxes down maxDist[1] = maxDist[0]; maxIndx[1] = maxIndx[0]; @@ -461,8 +411,7 @@ void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) maxIndx[0] = i; } // Check against the second highest max - else if (dist >= maxDist[1]) - { + else if (dist >= maxDist[1]) { // just stomp the old maxDist[1] = dist; maxIndx[1] = i; @@ -479,32 +428,22 @@ void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) face = (srfBspSurface_t *)(world->surfaces + surf)->data; dot2 = DotProduct(face->cullPlane.normal, tr.refdef.viewaxis[0]); - if (dot2 < dot1 && dot2 < 0.0f) - { + if (dot2 < dot1 && dot2 < 0.0f) { surf = bmodel->firstSurface + maxIndx[1]; // use the second face - } - else if (dot1 < dot2 && dot1 < 0.0f) - { + } else if (dot1 < dot2 && dot1 < 0.0f) { surf = bmodel->firstSurface + maxIndx[0]; // use the first face - } - else - { // Possibly only have one face, so may as well use the first face, which also should be the best one - //i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen + } else { // Possibly only have one face, so may as well use the first face, which also should be the best one + // i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen surf = bmodel->firstSurface + maxIndx[0]; // use the first face } face = (srfBspSurface_t *)(world->surfaces + surf)->data; - for (int t = 0; t < 4; t++) - { + for (int t = 0; t < 4; t++) { VectorCopy(face->verts[t].xyz, verts[t]); } } -void RE_SetRangedFog ( float range ) -{ - tr.rangedFog = range; -} - +void RE_SetRangedFog(float range) { tr.rangedFog = range; } /* ============================================================= @@ -514,83 +453,80 @@ void RE_SetRangedFog ( float range ) ============================================================= */ - /* ================ R_RecursiveWorldNode ================ */ -void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits, int pshadowBits ) -{ +void R_RecursiveWorldNode(mnode_t *node, int planeBits, int dlightBits, int pshadowBits) { do { - int newDlights[2]; + int newDlights[2]; unsigned int newPShadows[2]; // if the node wasn't marked as potentially visible, exit // pvs is skipped for depth shadows - if (!(tr.viewParms.flags & VPF_DEPTHSHADOW) && - node->visCounts[tr.visIndex] != tr.visCounts[tr.visIndex]) { + if (!(tr.viewParms.flags & VPF_DEPTHSHADOW) && node->visCounts[tr.visIndex] != tr.visCounts[tr.visIndex]) { return; } // if the bounding volume is outside the frustum, nothing // inside can be visible OPTIMIZE: don't do this all the way to leafs? - if ( !r_nocull->integer ) { - int r; + if (!r_nocull->integer) { + int r; - if ( planeBits & 1 ) { + if (planeBits & 1) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[0]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~1; // all descendants will also be in front + if (r == 1) { + planeBits &= ~1; // all descendants will also be in front } } - if ( planeBits & 2 ) { + if (planeBits & 2) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[1]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~2; // all descendants will also be in front + if (r == 1) { + planeBits &= ~2; // all descendants will also be in front } } - if ( planeBits & 4 ) { + if (planeBits & 4) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[2]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~4; // all descendants will also be in front + if (r == 1) { + planeBits &= ~4; // all descendants will also be in front } } - if ( planeBits & 8 ) { + if (planeBits & 8) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[3]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~8; // all descendants will also be in front + if (r == 1) { + planeBits &= ~8; // all descendants will also be in front } } - if ( planeBits & 16 ) { + if (planeBits & 16) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[4]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~16; // all descendants will also be in front + if (r == 1) { + planeBits &= ~16; // all descendants will also be in front } } } - if ( node->contents != -1 ) { + if (node->contents != -1) { break; } @@ -600,57 +536,57 @@ void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits, int psh // determine which dlights are needed newDlights[0] = 0; newDlights[1] = 0; - if ( dlightBits ) { - for ( int i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( !(dlightBits & (1 << i)) ) { + if (dlightBits) { + for (int i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dlight_t *dl = &tr.refdef.dlights[i]; float dist = DotProduct(dl->origin, node->plane->normal) - node->plane->dist; - - if ( dist > -dl->radius ) { - newDlights[0] |= ( 1 << i ); + + if (dist > -dl->radius) { + newDlights[0] |= (1 << i); } - if ( dist < dl->radius ) { - newDlights[1] |= ( 1 << i ); + if (dist < dl->radius) { + newDlights[1] |= (1 << i); } } } newPShadows[0] = 0; newPShadows[1] = 0; - if ( pshadowBits ) { - for ( int i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { - if ( !(pshadowBits & (1 << i)) ) { + if (pshadowBits) { + for (int i = 0; i < tr.refdef.num_pshadows; i++) { + if (!(pshadowBits & (1 << i))) { continue; } pshadow_t *shadow = &tr.refdef.pshadows[i]; float dist = DotProduct(shadow->lightOrigin, node->plane->normal) - node->plane->dist; - - if ( dist > -shadow->lightRadius ) { - newPShadows[0] |= ( 1 << i ); + + if (dist > -shadow->lightRadius) { + newPShadows[0] |= (1 << i); } - if ( dist < shadow->lightRadius ) { - newPShadows[1] |= ( 1 << i ); + if (dist < shadow->lightRadius) { + newPShadows[1] |= (1 << i); } } } // recurse down the children, front side first - R_RecursiveWorldNode (node->children[0], planeBits, newDlights[0], newPShadows[0] ); + R_RecursiveWorldNode(node->children[0], planeBits, newDlights[0], newPShadows[0]); // tail recurse node = node->children[1]; dlightBits = newDlights[1]; pshadowBits = newPShadows[1]; - } while ( 1 ); + } while (1); { // leaf node, so add mark surfaces - int c; + int c; int surf, *view; tr.pc.c_leafs++; @@ -674,30 +610,21 @@ void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits, int psh while (c--) { // just mark it as visible, so we don't jump out of the cache derefencing the surface surf = *view; - if (surf < 0) - { - if (tr.world->mergedSurfacesViewCount[-surf - 1] != tr.viewCount) - { - tr.world->mergedSurfacesViewCount[-surf - 1] = tr.viewCount; + if (surf < 0) { + if (tr.world->mergedSurfacesViewCount[-surf - 1] != tr.viewCount) { + tr.world->mergedSurfacesViewCount[-surf - 1] = tr.viewCount; tr.world->mergedSurfacesDlightBits[-surf - 1] = dlightBits; tr.world->mergedSurfacesPshadowBits[-surf - 1] = pshadowBits; - } - else - { + } else { tr.world->mergedSurfacesDlightBits[-surf - 1] |= dlightBits; tr.world->mergedSurfacesPshadowBits[-surf - 1] |= pshadowBits; } - } - else - { - if (tr.world->surfacesViewCount[surf] != tr.viewCount) - { + } else { + if (tr.world->surfacesViewCount[surf] != tr.viewCount) { tr.world->surfacesViewCount[surf] = tr.viewCount; tr.world->surfacesDlightBits[surf] = dlightBits; tr.world->surfacesPshadowBits[surf] = pshadowBits; - } - else - { + } else { tr.world->surfacesDlightBits[surf] |= dlightBits; tr.world->surfacesPshadowBits[surf] |= pshadowBits; } @@ -707,35 +634,34 @@ void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits, int psh } } - /* =============== R_PointInLeaf =============== */ -static mnode_t *R_PointInLeaf( const vec3_t p ) { - mnode_t *node; - float d; - cplane_t *plane; - - if ( !tr.world ) { - ri.Error (ERR_DROP, "R_PointInLeaf: bad model"); +static mnode_t *R_PointInLeaf(const vec3_t p) { + mnode_t *node; + float d; + cplane_t *plane; + + if (!tr.world) { + ri.Error(ERR_DROP, "R_PointInLeaf: bad model"); } node = tr.world->nodes; - while( 1 ) { + while (1) { if (node->contents != -1) { break; } plane = node->plane; - d = DotProduct (p,plane->normal) - plane->dist; + d = DotProduct(p, plane->normal) - plane->dist; if (d > 0) { node = node->children[0]; } else { node = node->children[1]; } } - + return node; } @@ -744,8 +670,8 @@ static mnode_t *R_PointInLeaf( const vec3_t p ) { R_ClusterPVS ============== */ -static const byte *R_ClusterPVS (int cluster) { - if (!tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters ) { +static const byte *R_ClusterPVS(int cluster) { + if (!tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters) { return tr.world->novis; } @@ -757,19 +683,19 @@ static const byte *R_ClusterPVS (int cluster) { R_inPVS ================= */ -qboolean R_inPVS( const vec3_t p1, const vec3_t p2, byte *mask ) { - int leafnum; - int cluster; +qboolean R_inPVS(const vec3_t p1, const vec3_t p2, byte *mask) { + int leafnum; + int cluster; - leafnum = ri.CM_PointLeafnum (p1); - cluster = ri.CM_LeafCluster (leafnum); + leafnum = ri.CM_PointLeafnum(p1); + cluster = ri.CM_LeafCluster(leafnum); - //agh, the damn snapshot mask doesn't work for this - mask = (byte *) ri.CM_ClusterPVS (cluster); + // agh, the damn snapshot mask doesn't work for this + mask = (byte *)ri.CM_ClusterPVS(cluster); - leafnum = ri.CM_PointLeafnum (p2); - cluster = ri.CM_LeafCluster (leafnum); - if ( !(mask[cluster>>3] & (1<<(cluster&7))) ) + leafnum = ri.CM_PointLeafnum(p2); + cluster = ri.CM_LeafCluster(leafnum); + if (!(mask[cluster >> 3] & (1 << (cluster & 7)))) return qfalse; return qtrue; @@ -783,35 +709,28 @@ Mark the leaves and nodes that are in the PVS for the current cluster =============== */ -void R_MarkLeaves( void ) -{ +void R_MarkLeaves(void) { // lockpvs lets designers walk around to determine the // extent of the current pvs - if ( r_lockpvs->integer ) { + if (r_lockpvs->integer) { return; } // current viewcluster - mnode_t *leaf = R_PointInLeaf(tr.viewParms.pvsOrigin); + mnode_t *leaf = R_PointInLeaf(tr.viewParms.pvsOrigin); int cluster = leaf->cluster; // if the cluster is the same and the area visibility matrix // hasn't changed, we don't need to mark everything again - for (int i = 0; i < MAX_VISCOUNTS; i++) - { + for (int i = 0; i < MAX_VISCOUNTS; i++) { // if the areamask or r_showcluster was modified, invalidate all visclusters // this caused doors to open into undrawn areas - if (tr.refdef.areamaskModified || r_showcluster->modified) - { + if (tr.refdef.areamaskModified || r_showcluster->modified) { tr.visClusters[i] = -2; - } - else if (tr.visClusters[i] == cluster) - { - if (tr.visClusters[i] != tr.visClusters[tr.visIndex] && r_showcluster->integer) - { - ri.Printf(PRINT_ALL, "found cluster:%i area:%i index:%i\n", - cluster, leaf->area, i); + } else if (tr.visClusters[i] == cluster) { + if (tr.visClusters[i] != tr.visClusters[tr.visIndex] && r_showcluster->integer) { + ri.Printf(PRINT_ALL, "found cluster:%i area:%i index:%i\n", cluster, leaf->area, i); } tr.visIndex = i; @@ -823,24 +742,24 @@ void R_MarkLeaves( void ) tr.visCounts[tr.visIndex]++; tr.visClusters[tr.visIndex] = cluster; - if ( r_showcluster->modified || r_showcluster->integer ) { + if (r_showcluster->modified || r_showcluster->integer) { r_showcluster->modified = qfalse; - if ( r_showcluster->integer ) { - ri.Printf( PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area ); + if (r_showcluster->integer) { + ri.Printf(PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area); } } const byte *vis = R_ClusterPVS(tr.visClusters[tr.visIndex]); - + int i; for (i = 0, leaf = (tr.world->nodes + tr.world->numDecisionNodes); i < (tr.world->numnodes - tr.world->numDecisionNodes); i++, leaf++) { cluster = leaf->cluster; - if ( cluster < 0 || cluster >= tr.world->numClusters ) { + if (cluster < 0 || cluster >= tr.world->numClusters) { continue; } // check general pvs - if ( !(vis[cluster>>3] & (1<<(cluster&7))) ) { + if (!(vis[cluster >> 3] & (1 << (cluster & 7)))) { continue; } @@ -848,8 +767,8 @@ void R_MarkLeaves( void ) byte *areamask = tr.viewParms.isSkyPortal == qtrue ? tr.skyPortalAreaMask : tr.refdef.areamask; // check for door connection - if ( (areamask[leaf->area>>3] & (1<<(leaf->area&7)) ) ) { - continue; // not visible + if ((areamask[leaf->area >> 3] & (1 << (leaf->area & 7)))) { + continue; // not visible } mnode_t *parent = leaf; @@ -864,20 +783,19 @@ void R_MarkLeaves( void ) } } - /* ============= R_AddWorldSurfaces ============= */ -void R_AddWorldSurfaces( viewParms_t *viewParms, trRefdef_t *refdef ) { +void R_AddWorldSurfaces(viewParms_t *viewParms, trRefdef_t *refdef) { int planeBits, dlightBits, pshadowBits; - if ( !r_drawworld->integer ) { + if (!r_drawworld->integer) { return; } - if ( refdef->rdflags & RDF_NOWORLDMODEL ) { + if (refdef->rdflags & RDF_NOWORLDMODEL) { return; } @@ -895,13 +813,10 @@ void R_AddWorldSurfaces( viewParms_t *viewParms, trRefdef_t *refdef ) { planeBits = (viewParms->flags & VPF_FARPLANEFRUSTUM) ? 31 : 15; - if ( viewParms->flags & VPF_DEPTHSHADOW ) - { + if (viewParms->flags & VPF_DEPTHSHADOW) { dlightBits = 0; pshadowBits = 0; - } - else - { + } else { dlightBits = (1 << refdef->num_dlights) - 1; if (r_shadows->integer == 4) pshadowBits = (1 << refdef->num_pshadows) - 1; @@ -914,29 +829,18 @@ void R_AddWorldSurfaces( viewParms_t *viewParms, trRefdef_t *refdef ) { // now add all the potentially visible surfaces R_RotateForEntity(&tr.worldEntity, &tr.viewParms, &tr.ori); - for (int i = 0; i < tr.world->numWorldSurfaces; i++) - { + for (int i = 0; i < tr.world->numWorldSurfaces; i++) { if (tr.world->surfacesViewCount[i] != tr.viewCount) continue; - R_AddWorldSurface( - tr.world->surfaces + i, - nullptr, - REFENTITYNUM_WORLD, - tr.world->surfacesDlightBits[i], - tr.world->surfacesPshadowBits[i]); + R_AddWorldSurface(tr.world->surfaces + i, nullptr, REFENTITYNUM_WORLD, tr.world->surfacesDlightBits[i], tr.world->surfacesPshadowBits[i]); } - for (int i = 0; i < tr.world->numMergedSurfaces; i++) - { + for (int i = 0; i < tr.world->numMergedSurfaces; i++) { if (tr.world->mergedSurfacesViewCount[i] != tr.viewCount) continue; - R_AddWorldSurface( - tr.world->mergedSurfaces + i, - nullptr, - REFENTITYNUM_WORLD, - tr.world->mergedSurfacesDlightBits[i], - tr.world->mergedSurfacesPshadowBits[i]); + R_AddWorldSurface(tr.world->mergedSurfaces + i, nullptr, REFENTITYNUM_WORLD, tr.world->mergedSurfacesDlightBits[i], + tr.world->mergedSurfacesPshadowBits[i]); } } diff --git a/codemp/rd-vanilla/G2_API.cpp b/codemp/rd-vanilla/G2_API.cpp index 117cc8bbfd..70f703a460 100644 --- a/codemp/rd-vanilla/G2_API.cpp +++ b/codemp/rd-vanilla/G2_API.cpp @@ -36,68 +36,55 @@ int g_G2ServerAlloc = 0; int g_G2ClientAlloc = 0; int g_G2AllocServer = 0; -//stupid debug crap to track leaks in case they happen. -//we used to shove everything into a map and delete it all and not care about -//leaks, but that was not the Right Thing. -rww -#define MAX_TRACKED_ALLOC 4096 -static bool g_G2AllocTrackInit = false; //want to keep this thing contained +// stupid debug crap to track leaks in case they happen. +// we used to shove everything into a map and delete it all and not care about +// leaks, but that was not the Right Thing. -rww +#define MAX_TRACKED_ALLOC 4096 +static bool g_G2AllocTrackInit = false; // want to keep this thing contained static CGhoul2Info_v *g_G2AllocTrack[MAX_TRACKED_ALLOC]; -void G2_DEBUG_InitPtrTracker(void) -{ +void G2_DEBUG_InitPtrTracker(void) { memset(g_G2AllocTrack, 0, sizeof(g_G2AllocTrack)); g_G2AllocTrackInit = true; } -void G2_DEBUG_ReportLeaks(void) -{ +void G2_DEBUG_ReportLeaks(void) { int i = 0; - if (!g_G2AllocTrackInit) - { - ri.Printf( PRINT_ALL, "g2 leak tracker was never initialized!\n"); + if (!g_G2AllocTrackInit) { + ri.Printf(PRINT_ALL, "g2 leak tracker was never initialized!\n"); return; } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i]) - { - ri.Printf( PRINT_ALL, "Bad guy found in slot %i, attempting to access...", i); + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i]) { + ri.Printf(PRINT_ALL, "Bad guy found in slot %i, attempting to access...", i); CGhoul2Info_v &g2v = *g_G2AllocTrack[i]; CGhoul2Info &g2 = g2v[0]; - if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) - { - ri.Printf( PRINT_ALL, "Bad guy's filename is %s\n", g2.mFileName); - } - else - { - ri.Printf( PRINT_ALL, "He's not valid! BURN HIM!\n"); + if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) { + ri.Printf(PRINT_ALL, "Bad guy's filename is %s\n", g2.mFileName); + } else { + ri.Printf(PRINT_ALL, "He's not valid! BURN HIM!\n"); } } i++; } } -void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (!g_G2AllocTrack[i]) - { + while (i < MAX_TRACKED_ALLOC) { + if (!g_G2AllocTrack[i]) { g_G2AllocTrack[i] = g2; return; } @@ -106,29 +93,22 @@ void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { - ri.Printf( PRINT_ALL, "%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { - ri.Printf( PRINT_ALL, "Crap g2 instance passed to instance tracker (in).\n"); + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { + ri.Printf(PRINT_ALL, "%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); + } else { + ri.Printf(PRINT_ALL, "Crap g2 instance passed to instance tracker (in).\n"); } } -void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) -{ +void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) { int i = 0; - if (!g_G2AllocTrackInit) - { + if (!g_G2AllocTrackInit) { G2_DEBUG_InitPtrTracker(); } - while (i < MAX_TRACKED_ALLOC) - { - if (g_G2AllocTrack[i] == g2) - { + while (i < MAX_TRACKED_ALLOC) { + if (g_G2AllocTrack[i] == g2) { g_G2AllocTrack[i] = NULL; return; } @@ -137,13 +117,10 @@ void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) CGhoul2Info_v &g2v = *g2; - if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) - { - ri.Printf( PRINT_ALL, "%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); - } - else - { - ri.Printf( PRINT_ALL, "Crap g2 instance passed to instance tracker (out).\n"); + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) { + ri.Printf(PRINT_ALL, "%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); + } else { + ri.Printf(PRINT_ALL, "Crap g2 instance passed to instance tracker (out).\n"); } } #endif @@ -152,76 +129,66 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo); -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #define NUM_G2T_TIME (2) static int G2TimeBases[NUM_G2T_TIME]; -void G2API_SetTime(int currentTime,int clock) -{ - assert(clock>=0&&clock= 0 && clock < NUM_G2T_TIME); #if G2_DEBUG_TIME - ri.Printf( PRINT_ALL, "Set Time: before c%6d s%6d",G2TimeBases[1],G2TimeBases[0]); + ri.Printf(PRINT_ALL, "Set Time: before c%6d s%6d", G2TimeBases[1], G2TimeBases[0]); #endif - G2TimeBases[clock]=currentTime; - if (G2TimeBases[1]>G2TimeBases[0]+200) - { - G2TimeBases[1]=0; // use server time instead + G2TimeBases[clock] = currentTime; + if (G2TimeBases[1] > G2TimeBases[0] + 200) { + G2TimeBases[1] = 0; // use server time instead return; } #if G2_DEBUG_TIME - ri.Printf( PRINT_ALL, " after c%6d s%6d\n",G2TimeBases[1],G2TimeBases[0]); + ri.Printf(PRINT_ALL, " after c%6d s%6d\n", G2TimeBases[1], G2TimeBases[0]); #endif } -int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar +int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar { - int ret=G2TimeBases[1]; - if ( !ret ) - { + int ret = G2TimeBases[1]; + if (!ret) { ret = G2TimeBases[0]; } return ret; } -//rww - RAGDOLL_END +// rww - RAGDOLL_END -//rww - Stuff to allow association of ghoul2 instances to entity numbers. -//This way, on listen servers when both the client and server are doing -//ghoul2 operations, we can copy relevant data off the client instance -//directly onto the server instance and slash the transforms and whatnot -//right in half. +// rww - Stuff to allow association of ghoul2 instances to entity numbers. +// This way, on listen servers when both the client and server are doing +// ghoul2 operations, we can copy relevant data off the client instance +// directly onto the server instance and slash the transforms and whatnot +// right in half. #ifdef _G2_LISTEN_SERVER_OPT CGhoul2Info_v *g2ClientAttachments[MAX_GENTITIES]; #endif -void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) -{ //Assign the pointers in the arrays +void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) { // Assign the pointers in the arrays #ifdef _G2_LISTEN_SERVER_OPT - if (server) - { + if (server) { ghoul2[0].entityNum = entityNum; - } - else - { + } else { g2ClientAttachments[entityNum] = &ghoul2; } #endif } -void G2API_ClearAttachedInstance(int entityNum) -{ +void G2API_ClearAttachedInstance(int entityNum) { #ifdef _G2_LISTEN_SERVER_OPT g2ClientAttachments[entityNum] = NULL; #endif } -void G2API_CleanEntAttachments(void) -{ +void G2API_CleanEntAttachments(void) { #ifdef _G2_LISTEN_SERVER_OPT int i = 0; - while (i < MAX_GENTITIES) - { + while (i < MAX_GENTITIES) { g2ClientAttachments[i] = NULL; i++; } @@ -232,21 +199,18 @@ void G2API_CleanEntAttachments(void) void CopyBoneCache(CBoneCache *to, CBoneCache *from); #endif -qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelIndex) -{ +qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v &ghoul2, int modelIndex) { #ifndef _G2_LISTEN_SERVER_OPT return qfalse; #else CGhoul2Info *serverInstance = &ghoul2[modelIndex]; CGhoul2Info *clientInstance; - if (ri.Cvar_VariableIntegerValue( "dedicated" )) - { //No client to get from! + if (ri.Cvar_VariableIntegerValue("dedicated")) { // No client to get from! return qfalse; } - if (!g2ClientAttachments[serverInstance->entityNum]) - { //No clientside instance is attached to this entity + if (!g2ClientAttachments[serverInstance->entityNum]) { // No clientside instance is attached to this entity return qfalse; } @@ -255,17 +219,15 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde int frameNum = G2API_GetTime(0); - if (clientInstance->mSkelFrameNum != frameNum) - { //it has to be constructed already + if (clientInstance->mSkelFrameNum != frameNum) { // it has to be constructed already return qfalse; } - if (!clientInstance->mBoneCache) - { //that just won't do + if (!clientInstance->mBoneCache) { // that just won't do return qfalse; } - //Just copy over the essentials + // Just copy over the essentials serverInstance->aHeader = clientInstance->aHeader; serverInstance->animModel = clientInstance->animModel; serverInstance->currentAnimModelSize = clientInstance->currentAnimModelSize; @@ -277,14 +239,12 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde serverInstance->mSurfaceRoot = clientInstance->mSurfaceRoot; serverInstance->mTransformedVertsArray = clientInstance->mTransformedVertsArray; - if (!serverInstance->mBoneCache) - { //if this is the case.. I guess we can use the client one instead + if (!serverInstance->mBoneCache) { // if this is the case.. I guess we can use the client one instead serverInstance->mBoneCache = clientInstance->mBoneCache; } - //Copy the contents of the client cache over the contents of the server cache - if (serverInstance->mBoneCache != clientInstance->mBoneCache) - { + // Copy the contents of the client cache over the contents of the server cache + if (serverInstance->mBoneCache != clientInstance->mBoneCache) { CopyBoneCache(serverInstance->mBoneCache, clientInstance->mBoneCache); } @@ -297,221 +257,201 @@ qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelInde #define MAX_G2_MODELS (1024) #define G2_MODEL_BITS (10) -#define G2_INDEX_MASK (MAX_G2_MODELS-1) +#define G2_INDEX_MASK (MAX_G2_MODELS - 1) -static size_t GetSizeOfGhoul2Info ( const CGhoul2Info& g2Info ) -{ +static size_t GetSizeOfGhoul2Info(const CGhoul2Info &g2Info) { size_t size = 0; // This is pretty ugly, but we don't want to save everything in the CGhoul2Info object. - size += offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + size += offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); // Surface vector + size - size += sizeof (int); - size += g2Info.mSlist.size() * sizeof (surfaceInfo_t); + size += sizeof(int); + size += g2Info.mSlist.size() * sizeof(surfaceInfo_t); // Bone vector + size - size += sizeof (int); - size += g2Info.mBlist.size() * sizeof (boneInfo_t); + size += sizeof(int); + size += g2Info.mBlist.size() * sizeof(boneInfo_t); // Bolt vector + size - size += sizeof (int); - size += g2Info.mBltlist.size() * sizeof (boltInfo_t); + size += sizeof(int); + size += g2Info.mBltlist.size() * sizeof(boltInfo_t); return size; } -static size_t SerializeGhoul2Info ( char *buffer, const CGhoul2Info& g2Info ) -{ +static size_t SerializeGhoul2Info(char *buffer, const CGhoul2Info &g2Info) { char *base = buffer; size_t blockSize; // Oh the ugliness... - blockSize = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (buffer, &g2Info.mModelindex, blockSize); + blockSize = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(buffer, &g2Info.mModelindex, blockSize); buffer += blockSize; // Surfaces vector + size *(int *)buffer = g2Info.mSlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mSlist.size() * sizeof (surfaceInfo_t); - memcpy (buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof (surfaceInfo_t)); + blockSize = g2Info.mSlist.size() * sizeof(surfaceInfo_t); + memcpy(buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof(surfaceInfo_t)); buffer += blockSize; // Bones vector + size *(int *)buffer = g2Info.mBlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mBlist.size() * sizeof (boneInfo_t); - memcpy (buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof (boneInfo_t)); + blockSize = g2Info.mBlist.size() * sizeof(boneInfo_t); + memcpy(buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof(boneInfo_t)); buffer += blockSize; // Bolts vector + size *(int *)buffer = g2Info.mBltlist.size(); - buffer += sizeof (int); + buffer += sizeof(int); - blockSize = g2Info.mBltlist.size() * sizeof (boltInfo_t); - memcpy (buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof (boltInfo_t)); + blockSize = g2Info.mBltlist.size() * sizeof(boltInfo_t); + memcpy(buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof(boltInfo_t)); buffer += blockSize; return static_cast(buffer - base); } -static size_t DeserializeGhoul2Info ( const char *buffer, CGhoul2Info& g2Info ) -{ +static size_t DeserializeGhoul2Info(const char *buffer, CGhoul2Info &g2Info) { const char *base = buffer; size_t size; - size = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); - memcpy (&g2Info.mModelindex, buffer, size); + size = offsetof(CGhoul2Info, mTransformedVertsArray) - offsetof(CGhoul2Info, mModelindex); + memcpy(&g2Info.mModelindex, buffer, size); buffer += size; // Surfaces vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mSlist.assign ((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); - buffer += sizeof (surfaceInfo_t) * size; + g2Info.mSlist.assign((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); + buffer += sizeof(surfaceInfo_t) * size; // Bones vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBlist.assign ((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); - buffer += sizeof (boneInfo_t) * size; + g2Info.mBlist.assign((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); + buffer += sizeof(boneInfo_t) * size; // Bolt vector size = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - g2Info.mBltlist.assign ((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); - buffer += sizeof (boltInfo_t) * size; + g2Info.mBltlist.assign((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); + buffer += sizeof(boltInfo_t) * size; return static_cast(buffer - base); } -class Ghoul2InfoArray : public IGhoul2InfoArray -{ - std::vector mInfos[MAX_G2_MODELS]; - int mIds[MAX_G2_MODELS]; - std::list mFreeIndecies; - void DeleteLow(int idx) - { - for (size_t model=0; model< mInfos[idx].size(); model++) - { - if (mInfos[idx][model].mBoneCache) - { +class Ghoul2InfoArray : public IGhoul2InfoArray { + std::vector mInfos[MAX_G2_MODELS]; + int mIds[MAX_G2_MODELS]; + std::list mFreeIndecies; + void DeleteLow(int idx) { + for (size_t model = 0; model < mInfos[idx].size(); model++) { + if (mInfos[idx][model].mBoneCache) { RemoveBoneCache(mInfos[idx][model].mBoneCache); - mInfos[idx][model].mBoneCache=0; + mInfos[idx][model].mBoneCache = 0; } } mInfos[idx].clear(); - if ((mIds[idx]>>G2_MODEL_BITS)>(1<<(31-G2_MODEL_BITS))) - { - mIds[idx]=MAX_G2_MODELS+idx; //rollover reset id to minimum value + if ((mIds[idx] >> G2_MODEL_BITS) > (1 << (31 - G2_MODEL_BITS))) { + mIds[idx] = MAX_G2_MODELS + idx; // rollover reset id to minimum value mFreeIndecies.push_back(idx); - } - else - { - mIds[idx]+=MAX_G2_MODELS; + } else { + mIds[idx] += MAX_G2_MODELS; mFreeIndecies.push_front(idx); } } -public: - Ghoul2InfoArray() - { + + public: + Ghoul2InfoArray() { int i; - for (i=0;i(buffer - base); } - size_t Deserialize ( const char *buffer, size_t size ) - { + size_t Deserialize(const char *buffer, size_t size) { const char *base = buffer; size_t count; // Free indices count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mFreeIndecies.assign ((int *)buffer, (int *)buffer + count); - buffer += sizeof (int) * count; + mFreeIndecies.assign((int *)buffer, (int *)buffer + count); + buffer += sizeof(int) * count; // IDs - memcpy (mIds, buffer, sizeof (mIds)); - buffer += sizeof (mIds); + memcpy(mIds, buffer, sizeof(mIds)); + buffer += sizeof(mIds); // Ghoul2 infos - for ( size_t i = 0; i < MAX_G2_MODELS; i++ ) - { + for (size_t i = 0; i < MAX_G2_MODELS; i++) { mInfos[i].clear(); count = *(int *)buffer; - buffer += sizeof (int); + buffer += sizeof(int); - mInfos[i].resize (count); + mInfos[i].resize(count); - for ( size_t j = 0; j < count; j++ ) - { - buffer += DeserializeGhoul2Info (buffer, mInfos[i][j]); + for (size_t j = 0; j < count; j++) { + buffer += DeserializeGhoul2Info(buffer, mInfos[i][j]); } } @@ -519,117 +459,93 @@ class Ghoul2InfoArray : public IGhoul2InfoArray } #if G2API_DEBUG - ~Ghoul2InfoArray() - { + ~Ghoul2InfoArray() { char mess[1000]; - if (mFreeIndecies.size()::iterator j; - for (j=mFreeIndecies.begin();j!=mFreeIndecies.end();++j) - { - if (*j==i) + for (j = mFreeIndecies.begin(); j != mFreeIndecies.end(); ++j) { + if (*j == i) break; } - if (j==mFreeIndecies.end()) - { - sprintf(mess,"Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); + if (j == mFreeIndecies.end()) { + sprintf(mess, "Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); OutputDebugString(mess); - if (mInfos[i].size()) - { - sprintf(mess,"%s\n", mInfos[i][0].mFileName); + if (mInfos[i].size()) { + sprintf(mess, "%s\n", mInfos[i][0].mFileName); OutputDebugString(mess); } } } - } - else - { + } else { OutputDebugString("No ghoul2 info slots leaked\n"); } } #endif - int New() - { - if (mFreeIndecies.empty()) - { + int New() { + if (mFreeIndecies.empty()) { assert(0); Com_Error(ERR_FATAL, "Out of ghoul2 info slots"); - } // gonna pull from the front, doing a - int idx=*mFreeIndecies.begin(); + int idx = *mFreeIndecies.begin(); mFreeIndecies.erase(mFreeIndecies.begin()); return mIds[idx]; } - bool IsValid(int handle) const - { - if ( handle <= 0 ) - { + bool IsValid(int handle) const { + if (handle <= 0) { return false; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + if (mIds[handle & G2_INDEX_MASK] != handle) // not a valid handle, could be old { return false; } return true; } - void Delete(int handle) - { - if (handle <= 0) - { + void Delete(int handle) { + if (handle <= 0) { return; } - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + if (mIds[handle & G2_INDEX_MASK] == handle) { + DeleteLow(handle & G2_INDEX_MASK); } } - std::vector &Get(int handle) - { - assert(handle>0); //null handle - assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); + std::vector &Get(int handle) { + assert(handle > 0); // null handle + assert((handle & G2_INDEX_MASK) >= 0 && (handle & G2_INDEX_MASK) < MAX_G2_MODELS); // junk handle + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + assert(!(handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle)); - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - const std::vector &Get(int handle) const - { - assert(handle>0); - assert(mIds[handle&G2_INDEX_MASK]==handle); // not a valid handle, could be old or garbage - return mInfos[handle&G2_INDEX_MASK]; + const std::vector &Get(int handle) const { + assert(handle > 0); + assert(mIds[handle & G2_INDEX_MASK] == handle); // not a valid handle, could be old or garbage + return mInfos[handle & G2_INDEX_MASK]; } #if G2API_DEBUG - vector &GetDebug(int handle) - { + vector &GetDebug(int handle) { static vector null; - if (handle<=0||(handle&G2_INDEX_MASK)<0||(handle&G2_INDEX_MASK)>=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle) - { + if (handle <= 0 || (handle & G2_INDEX_MASK) < 0 || (handle & G2_INDEX_MASK) >= MAX_G2_MODELS || mIds[handle & G2_INDEX_MASK] != handle) { return *(vector *)0; // null reference, intentional } - return mInfos[handle&G2_INDEX_MASK]; + return mInfos[handle & G2_INDEX_MASK]; } - void TestAllAnims() - { + void TestAllAnims() { int j; - for (j=0;j &ghoul2=mInfos[j]; + for (j = 0; j < MAX_G2_MODELS; j++) { + vector &ghoul2 = mInfos[j]; int i; - for (i=0; iDeserialize ((const char *)data, size); - Z_Free ((void *)data); + singleton->Deserialize((const char *)data, size); + Z_Free((void *)data); #ifdef _DEBUG - assert (read == size); + assert(read == size); #endif } } -void SaveGhoul2InfoArray() -{ +void SaveGhoul2InfoArray() { size_t size = singleton->GetSerializedSize(); - void *data = Z_Malloc (size, TAG_GHOUL2); + void *data = Z_Malloc(size, TAG_GHOUL2); #ifdef _DEBUG size_t written = #endif - singleton->Serialize ((char *)data); + singleton->Serialize((char *)data); #ifdef _DEBUG - assert (written == size); + assert(written == size); #endif - if ( !ri.PD_Store (PERSISTENT_G2DATA, data, size) ) - { - Com_Printf (S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); + if (!ri.PD_Store(PERSISTENT_G2DATA, data, size)) { + Com_Printf(S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); } } -void Ghoul2InfoArray_Free(void) -{ - if(singleton) { +void Ghoul2InfoArray_Free(void) { + if (singleton) { delete singleton; singleton = NULL; } } // this is the ONLY function to read entity states directly -void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) -{ - if (*ghoul2Ptr) - { +void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) { + if (*ghoul2Ptr) { CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. extern int R_GetRNumEntities(void); extern void R_SetRNumEntities(int num); //check if this instance is actually on a refentity @@ -749,16 +656,13 @@ void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) #endif #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghoul2Ptr); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghoul2Ptr); } g_Ghoul2Allocations -= sizeof(*ghoul2Ptr); @@ -770,15 +674,12 @@ void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) } } -qboolean G2_ShouldRegisterServer(void) -{ +qboolean G2_ShouldRegisterServer(void) { vm_t *currentVM = ri.GetCurrentVM(); - if ( currentVM && currentVM->slot == VM_GAME ) - { - if ( ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && ShaderHashTableExists()) - { //if the hunk has been marked then we are now loading client assets so don't load on server. + if (currentVM && currentVM->slot == VM_GAME) { + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // if the hunk has been marked then we are now loading client assets so don't load on server. return qfalse; } @@ -787,37 +688,30 @@ qboolean G2_ShouldRegisterServer(void) return qfalse; } -qhandle_t G2API_PrecacheGhoul2Model( const char *fileName ) -{ - if ( G2_ShouldRegisterServer() ) - return RE_RegisterServerModel( fileName ); +qhandle_t G2API_PrecacheGhoul2Model(const char *fileName) { + if (G2_ShouldRegisterServer()) + return RE_RegisterServerModel(fileName); else - return RE_RegisterModel( fileName ); + return RE_RegisterModel(fileName); } // initialise all that needs to be on a new Ghoul II model -int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, - qhandle_t customShader, int modelFlags, int lodBias) -{ - int model; +int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { + int model; // are we actually asking for a model to be loaded. - if (!fileName || !fileName[0]) - { + if (!fileName || !fileName[0]) { assert(0); return -1; } - if (!(*ghoul2Ptr)) - { + if (!(*ghoul2Ptr)) { *ghoul2Ptr = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -828,29 +722,23 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); // find a free spot in the list - for (model=0; model< ghoul2.size(); model++) - { - if (ghoul2[model].mModelindex == -1) - { - ghoul2[model]=CGhoul2Info(); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModelindex == -1) { + ghoul2[model] = CGhoul2Info(); break; } } - if (model==ghoul2.size()) - { //init should not be used to create additional models, only the first one - assert(ghoul2.size() < 4); //use G2API_CopySpecificG2Model to add models + if (model == ghoul2.size()) { // init should not be used to create additional models, only the first one + assert(ghoul2.size() < 4); // use G2API_CopySpecificG2Model to add models ghoul2.push_back(CGhoul2Info()); } strcpy(ghoul2[model].mFileName, fileName); ghoul2[model].mModelindex = model; - if (!G2_TestModelPointers(&ghoul2[model])) - { - ghoul2[model].mFileName[0]=0; + if (!G2_TestModelPointers(&ghoul2[model])) { + ghoul2[model].mFileName[0] = 0; ghoul2[model].mModelindex = -1; - } - else - { + } else { G2_Init_Bone_List(ghoul2[model].mBlist, ghoul2[model].aHeader->numBones); G2_Init_Bolt_List(ghoul2[model].mBltlist); ghoul2[model].mCustomShader = customShader; @@ -864,27 +752,22 @@ int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int m return ghoul2[model].mModelindex; } -qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mLodBias = lodBias; return qtrue; } return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin); -qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin); +qboolean G2API_SetSkin(CGhoul2Info_v &ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomSkin = customSkin; - if (renderSkin) - {//this is going to set the surfs on/off matching the skin file - G2_SetSurfaceOnOffFromSkin( ghlInfo, renderSkin ); + if (renderSkin) { // this is going to set the surfs on/off matching the skin file + G2_SetSurfaceOnOffFromSkin(ghlInfo, renderSkin); } return qtrue; @@ -892,27 +775,22 @@ qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSk return qfalse; } -qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mCustomShader = customShader; return qtrue; } return qfalse; } -qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) -{ +qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, surfaceName, flags); @@ -920,29 +798,23 @@ qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, c return qfalse; } -int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceOff(ghlInfo, ghlInfo->mSlist, surfaceName); } return -1; } -qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghoul2)) - { +qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) { + if (G2_SetupModelPointers(ghoul2)) { return G2_SetRootSurface(ghoul2, modelIndex, surfaceName); } return qfalse; } -int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); @@ -950,10 +822,8 @@ int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, fl return -1; } -qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mMeshFrameNum = 0; return G2_RemoveSurface(ghlInfo->mSlist, index); @@ -961,66 +831,55 @@ qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) return qfalse; } -int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetParentSurface(ghlInfo, index); } return -1; } -int G2API_GetSurfaceRenderStatus(CGhoul2Info_v& ghoul2, int modelIndex, const char *surfaceName) -{ +int G2API_GetSurfaceRenderStatus(CGhoul2Info_v &ghoul2, int modelIndex, const char *surfaceName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { return G2_IsSurfaceRendered(ghlInfo, surfaceName, ghlInfo->mSlist); } return -1; } -qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { return qfalse; } return qtrue; } -qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) -{ +qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) { CGhoul2Info_v &ghlInfo = **ghlRemove; // sanity check - if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) - { + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) { // if we hit this assert then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. assert(0); return qfalse; } - if (ghlInfo.size() > modelIndex) - { + if (ghlInfo.size() > modelIndex) { #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -1028,40 +887,32 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; int newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (int i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -1071,43 +922,36 @@ qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex } } - return qtrue; } -qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) -{//remove 'em ALL! +qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) { // remove 'em ALL! CGhoul2Info_v &ghlInfo = **ghlRemove; - int modelIndex = 0; + int modelIndex = 0; int newSize = 0; int i; // sanity check - if ( !ghlInfo.size() ) - {// if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that + if (!ghlInfo.size()) { // if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that // one way or another is already gone. return qfalse; } - for ( modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++ ) - { - if ( ghlInfo[modelIndex].mModelindex == -1 ) - { + for (modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++) { + if (ghlInfo[modelIndex].mModelindex == -1) { continue; } #ifdef _G2_GORE // Cleanup the gore attached to this model - if ( ghlInfo[modelIndex].mGoreSetTag ) - { - DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + if (ghlInfo[modelIndex].mGoreSetTag) { + DeleteGoreSet(ghlInfo[modelIndex].mGoreSetTag); ghlInfo[modelIndex].mGoreSetTag = 0; } #endif - if (ghlInfo[modelIndex].mBoneCache) - { + if (ghlInfo[modelIndex].mBoneCache) { RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); - ghlInfo[modelIndex].mBoneCache=0; + ghlInfo[modelIndex].mBoneCache = 0; } // clear out the vectors this model used. @@ -1115,41 +959,33 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) ghlInfo[modelIndex].mBltlist.clear(); ghlInfo[modelIndex].mSlist.clear(); - // set us to be the 'not active' state + // set us to be the 'not active' state ghlInfo[modelIndex].mModelindex = -1; } newSize = ghlInfo.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (i=ghlInfo.size()-1; i>-1; i--) - { - if (ghlInfo[i].mModelindex == -1) - { + for (i = ghlInfo.size() - 1; i > -1; i--) { + if (ghlInfo[i].mModelindex == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != ghlInfo.size()) - { + if (newSize != ghlInfo.size()) { // yes, so lets do it ghlInfo.resize(newSize); } // if we are not using any space, just delete the ghoul2 vector entirely - if (!ghlInfo.size()) - { + if (!ghlInfo.size()) { #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc -= sizeof(*ghlRemove); - } - else - { + } else { g_G2ClientAlloc -= sizeof(*ghlRemove); } g_Ghoul2Allocations -= sizeof(*ghlRemove); @@ -1160,201 +996,172 @@ qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) return qtrue; } -//check if a bone exists on skeleton without actually adding to the bone list -rww -qboolean G2API_DoesBoneExist(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +// check if a bone exists on skeleton without actually adding to the bone list -rww +qboolean G2API_DoesBoneExist(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { //model is valid + if (G2_SetupModelPointers(ghlInfo)) { // model is valid mdxaHeader_t *mdxa = ghlInfo->currentModel->mdxa; - if (mdxa) - { //get the skeleton data and iterate through the bones + if (mdxa) { // get the skeleton data and iterate through the bones int i; mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for (i = 0; i < mdxa->numBones; i++) - { - skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (!Q_stricmp(skel->name, boneName)) - { //got it + for (i = 0; i < mdxa->numBones; i++) { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + if (!Q_stricmp(skel->name, boneName)) { // got it return qtrue; } } } } - //guess it doesn't exist + // guess it doesn't exist return qfalse; } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled -//rww - RAGDOLL_END +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +// rww - RAGDOLL_END -qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ +qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, + const int currentTime, const float AsetFrame, const int blendTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); - if (endFrame<=0) - { - endFrame=1; + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); + return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, + ghlInfo->aHeader->numFrames); } return qfalse; } #define _PLEASE_SHUT_THE_HELL_UP -qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) -{ - int endFrame=AendFrame; - int startFrame=AstartFrame; - float setFrame=AsetFrame; +qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, + const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) { + int endFrame = AendFrame; + int startFrame = AstartFrame; + float setFrame = AsetFrame; #ifndef _PLEASE_SHUT_THE_HELL_UP - assert(endFrame>0); - assert(startFrame>=0); - assert(endFrame<100000); - assert(startFrame<100000); - assert(setFrame>=0.0f||setFrame==-1.0f); - assert(setFrame<=100000.0f); + assert(endFrame > 0); + assert(startFrame >= 0); + assert(endFrame < 100000); + assert(startFrame < 100000); + assert(setFrame >= 0.0f || setFrame == -1.0f); + assert(setFrame <= 100000.0f); #endif - if (endFrame<=0) - { - endFrame=1; + if (endFrame <= 0) { + endFrame = 1; } - if (endFrame>=100000) - { - endFrame=1; + if (endFrame >= 100000) { + endFrame = 1; } - if (startFrame<0) - { - startFrame=0; + if (startFrame < 0) { + startFrame = 0; } - if (startFrame>=100000) - { - startFrame=0; + if (startFrame >= 100000) { + startFrame = 0; } - if (setFrame<0.0f&&setFrame!=-1.0f) - { - setFrame=0.0f; + if (setFrame < 0.0f && setFrame != -1.0f) { + setFrame = 0.0f; } - if (setFrame>100000.0f) - { - setFrame=0.0f; + if (setFrame > 100000.0f) { + setFrame = 0.0f; } - if (ghoul2.size()>modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); + return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } } return qfalse; } -qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, - int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList) -{ - assert(startFrame!=endFrame); //this is bad - assert(startFrame!=flags); //this is bad - assert(endFrame!=flags); //this is bad - assert(currentFrame!=animSpeed); //this is bad +qboolean G2API_GetBoneAnim(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *animSpeed, int *modelList) { + assert(startFrame != endFrame); // this is bad + assert(startFrame != flags); // this is bad + assert(endFrame != flags); // this is bad + assert(currentFrame != animSpeed); // this is bad CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - int aCurrentTime=G2API_GetTime(currentTime); - qboolean ret=G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, - startFrame, endFrame, flags, animSpeed, modelList, ghlInfo->mModelindex); + if (G2_SetupModelPointers(ghlInfo)) { + int aCurrentTime = G2API_GetTime(currentTime); + qboolean ret = G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, + ghlInfo->mModelindex); #ifdef _DEBUG /* assert(*endFrame>0); @@ -1364,29 +1171,23 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo assert(*currentFrame>=0.0f); assert(*currentFrame<100000.0f); */ - if (*endFrame<1) - { - *endFrame=1; + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } - if (*currentFrame<0.0f) - { - *currentFrame=0.0f; + if (*currentFrame < 0.0f) { + *currentFrame = 0.0f; } - if (*currentFrame>100000) - { - *currentFrame=1; + if (*currentFrame > 100000) { + *currentFrame = 1; } #endif return ret; @@ -1394,32 +1195,26 @@ qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *bo return qfalse; } -qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) -{ - assert(startFrame!=endFrame); //this is bad - if (G2_SetupModelPointers(ghlInfo)) - { - qboolean ret=G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); +qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) { + assert(startFrame != endFrame); // this is bad + if (G2_SetupModelPointers(ghlInfo)) { + qboolean ret = G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); #ifdef _DEBUG - assert(*endFrame>0); - assert(*endFrame<100000); - assert(*startFrame>=0); - assert(*startFrame<100000); - if (*endFrame<1) - { - *endFrame=1; + assert(*endFrame > 0); + assert(*endFrame < 100000); + assert(*startFrame >= 0); + assert(*startFrame < 100000); + if (*endFrame < 1) { + *endFrame = 1; } - if (*endFrame>100000) - { - *endFrame=1; + if (*endFrame > 100000) { + *endFrame = 1; } - if (*startFrame<0) - { - *startFrame=0; + if (*startFrame < 0) { + *startFrame = 0; } - if (*startFrame>100000) - { - *startFrame=1; + if (*startFrame > 100000) { + *startFrame = 1; } #endif return ret; @@ -1427,126 +1222,101 @@ qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *sta return qfalse; } - -qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); +qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); } return qfalse; } -qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); +qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); } return qfalse; } -qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); +qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } -qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, - const Eorientations yaw, const Eorientations pitch, const Eorientations roll, - qhandle_t *modelList, int blendTime, int currentTime) -{ +qboolean G2API_SetBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index, const vec3_t angles, const int flags, const Eorientations yaw, + const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, int blendTime, int currentTime) { qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghlInfo); } - if (res) - { + if (res) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles_Index( ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, modelList, ghlInfo->mModelindex, blendTime, currentTime); + return G2_Set_Bone_Angles_Index(ghlInfo->mBlist, index, angles, flags, yaw, pitch, roll, modelList, ghlInfo->mModelindex, blendTime, currentTime); } return qfalse; } -qboolean G2API_SetBoneAngles(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const vec3_t angles, const int flags, - const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *modelList, int blendTime, int currentTime ) -{ - if (ghoul2.size()>modelIndex) - { +qboolean G2API_SetBoneAngles(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const vec3_t angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; qboolean setPtrs = qfalse; qboolean res = qfalse; - //rww - RAGDOLL_BEGIN - if (ghlInfo) - { + // rww - RAGDOLL_BEGIN + if (ghlInfo) { res = G2_SetupModelPointers(ghlInfo); setPtrs = qtrue; - if (res) - { - if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) - { + if (res) { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) { return qfalse; } } } - //rww - RAGDOLL_END + // rww - RAGDOLL_END - if (!setPtrs) - { + if (!setPtrs) { res = G2_SetupModelPointers(ghoul2); } - if (res) - { - // ensure we flush the cache + if (res) { + // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, modelList, ghlInfo->mModelindex, blendTime, currentTime); + return G2_Set_Bone_Angles(ghlInfo, ghlInfo->mBlist, boneName, angles, flags, up, left, forward, modelList, ghlInfo->mModelindex, blendTime, + currentTime); } } return qfalse; } -qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; return G2_Set_Bone_Angles_Matrix_Index(ghlInfo->mBlist, index, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); @@ -1554,11 +1324,9 @@ qboolean G2API_SetBoneAnglesMatrixIndex(CGhoul2Info *ghlInfo, const int index, c return qfalse; } -qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, int blendTime, int currentTime) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, int blendTime, + int currentTime) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; return G2_Set_Bone_Angles_Matrix(ghlInfo->mFileName, ghlInfo->mBlist, boneName, matrix, flags, modelList, ghlInfo->mModelindex, blendTime, currentTime); @@ -1566,83 +1334,65 @@ qboolean G2API_SetBoneAnglesMatrix(CGhoul2Info *ghlInfo, const char *boneName, c return qfalse; } -qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); + return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); } return qfalse; } -qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Stop_Bone_Angles(ghlInfo->mFileName, ghlInfo->mBlist, boneName); + return G2_Stop_Bone_Angles(ghlInfo->mFileName, ghlInfo->mBlist, boneName); } return qfalse; } - -void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) -{ +void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (status) - { //turn it on + if (status) { // turn it on ghlInfo->mFlags |= GHOUL2_CRAZY_SMOOTH; - } - else - { //off + } else { // off ghlInfo->mFlags &= ~GHOUL2_CRAZY_SMOOTH; } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN class CRagDollParams; -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms); -void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms) -{ - G2_SetRagDoll(ghoul2,parms); -} +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms); +void G2API_SetRagDoll(CGhoul2Info_v &ghoul2, CRagDollParams *parms) { G2_SetRagDoll(ghoul2, parms); } void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V); -void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) -{ - G2_ResetRagDoll(ghoul2); -} -//rww - RAGDOLL_END +void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) { G2_ResetRagDoll(ghoul2); } +// rww - RAGDOLL_END -qboolean G2API_RemoveBone(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) -{ +qboolean G2API_RemoveBone(CGhoul2Info_v &ghoul2, int modelIndex, const char *boneName) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { // ensure we flush the cache ghlInfo->mSkelFrameNum = 0; - return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); + return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); } return qfalse; } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef _DEBUG extern int ragTraceTime; extern int ragSSCount; extern int ragTraceCount; #endif -void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUpdateParams *params) -{ +void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) { int model; - int currentTime=G2API_GetTime(AcurrentTime); + int currentTime = G2API_GetTime(AcurrentTime); #ifdef _DEBUG ragTraceTime = 0; @@ -1651,11 +1401,9 @@ void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUp #endif // Walk the list and find all models that are active - for (model = 0; model < ghoul2.size(); model++) - { - if (ghoul2[model].mModel) - { - G2_Animate_Bone_List(ghoul2,currentTime,model,params); + for (model = 0; model < ghoul2.size(); model++) { + if (ghoul2[model].mModel) { + G2_Animate_Bone_List(ghoul2, currentTime, model, params); } } #ifdef _DEBUG @@ -1666,55 +1414,48 @@ void G2API_AnimateG2ModelsRag(CGhoul2Info_v &ghoul2, int AcurrentTime,CRagDollUp } */ - //keep sane limits here, if it gets too slow an assert is proper. + // keep sane limits here, if it gets too slow an assert is proper. // assert(ragTraceTime < 150); // assert(ragTraceCount < 1500); #endif } -//rww - RAGDOLL_END +// rww - RAGDOLL_END int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); -#define RAG_PCJ (0x00001) -#define RAG_EFFECTOR (0x00100) +#define RAG_PCJ (0x00001) +#define RAG_EFFECTOR (0x00100) -static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) -{ +static inline boneInfo_t *G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return NULL; } int boneIndex = G2_Find_Bone_Rag(ghlInfo, ghlInfo->mBlist, boneName); - if (boneIndex < 0) - { //bad bone specification + if (boneIndex < 0) { // bad bone specification return NULL; } boneInfo_t *bone = &ghlInfo->mBlist[boneIndex]; - if (!(bone->flags & BONE_ANGLES_RAGDOLL)) - { //only want to return rag bones + if (!(bone->flags & BONE_ANGLES_RAGDOLL)) { // only want to return rag bones return NULL; } return bone; } -qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) -{ +qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1724,17 +1465,14 @@ qboolean G2API_RagPCJConstraint(CGhoul2Info_v &ghoul2, const char *boneName, vec return qtrue; } -qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) -{ +qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, const float speed) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_PCJ)) - { //this function is only for PCJ bones + if (!(bone->RagFlags & RAG_PCJ)) { // this function is only for PCJ bones return qfalse; } @@ -1743,48 +1481,38 @@ qboolean G2API_RagPCJGradientSpeed(CGhoul2Info_v &ghoul2, const char *boneName, return qtrue; } -qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) -{ +qboolean G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } - if (!pos) - { //go back to none in case we have one then + if (!pos) { // go back to none in case we have one then bone->hasOverGoal = false; - } - else - { + } else { VectorCopy(pos, bone->overGoalSpot); bone->hasOverGoal = true; } return qtrue; } -qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) -{ //do something? +qboolean G2API_GetRagBonePos(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { // do something? return qfalse; } -qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) -{ +qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) { boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); - if (!bone) - { + if (!bone) { return qfalse; } - if (!(bone->RagFlags & RAG_EFFECTOR)) - { //this function is only for effectors + if (!(bone->RagFlags & RAG_EFFECTOR)) { // this function is only for effectors return qfalse; } @@ -1795,22 +1523,17 @@ qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3 return qtrue; } -qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) -{ +qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) { assert(ghoul2.size()); CGhoul2Info *ghlInfo = &ghoul2[0]; - if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) - { //can't do this if not in ragdoll + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) { // can't do this if not in ragdoll return qfalse; } - if (force) - { + if (force) { ghlInfo->mFlags |= GHOUL2_RAG_FORCESOLVE; - } - else - { + } else { ghlInfo->mFlags &= ~GHOUL2_RAG_FORCESOLVE; } @@ -1818,133 +1541,104 @@ qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) } qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params); -qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ +qboolean G2API_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return G2_SetBoneIKState(ghoul2, time, boneName, ikState, params); } qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params); -qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ - return G2_IKMove(ghoul2, time, params); -} +qboolean G2API_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { return G2_IKMove(ghoul2, time, params); } -qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - return G2_Remove_Bolt( ghlInfo->mBltlist, index); +qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) { + if (G2_SetupModelPointers(ghlInfo)) { + return G2_Remove_Bolt(ghlInfo->mBltlist, index); } return qfalse; } -int G2API_AddBolt(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) -{ -// assert(ghoul2.size()>modelIndex); +int G2API_AddBolt(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) { + // assert(ghoul2.size()>modelIndex); - if (ghoul2.size()>modelIndex) - { + if (ghoul2.size() > modelIndex) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Add_Bolt(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); } } return -1; } -int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Add_Bolt_Surf_Num(ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); } return -1; } - -qboolean G2API_AttachG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int toBoltIndex, int toModel) -{ - assert( toBoltIndex >= 0 ); - if ( toBoltIndex < 0 ) - { +qboolean G2API_AttachG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int toBoltIndex, int toModel) { + assert(toBoltIndex >= 0); + if (toBoltIndex < 0) { return qfalse; } - if (G2_SetupModelPointers(ghoul2From)&&G2_SetupModelPointers(ghoul2To)) - { + if (G2_SetupModelPointers(ghoul2From) && G2_SetupModelPointers(ghoul2To)) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if ((ghoul2From.size() > modelFrom) && - (ghoul2To.size() > toModel) && - ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if ((ghoul2From.size() > modelFrom) && (ghoul2To.size() > toModel) && + ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModel &= MODEL_AND; - toBoltIndex &= BOLT_AND; - ghoul2From[modelFrom].mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); - return qtrue; + toModel &= MODEL_AND; + toBoltIndex &= BOLT_AND; + ghoul2From[modelFrom].mModelBoltLink = (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); + return qtrue; } } return qfalse; } -void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) -{ - if (ghoul2.size() > modelIndex) - { +void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) { + if (ghoul2.size() > modelIndex) { ghoul2[modelIndex].mModelBoltLink = boltInfo; } } -qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { - ghlInfo->mModelBoltLink = -1; - return qtrue; +qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { + ghlInfo->mModelBoltLink = -1; + return qtrue; } return qfalse; } -qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info_v& ghoul2, int modelIndex, int toBoltIndex, int entNum, int toModelNum) -{ +qboolean G2API_AttachEnt(int *boltInfo, CGhoul2Info_v &ghoul2, int modelIndex, int toBoltIndex, int entNum, int toModelNum) { CGhoul2Info *ghlInfoTo = &ghoul2[modelIndex]; - if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) - { + if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) { // make sure we have a model to attach, a model to attach to, and a bolt on that model - if ( ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) - { + if (ghlInfoTo->mBltlist.size() && ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) { // encode the bolt address into the model bolt link - toModelNum &= MODEL_AND; - toBoltIndex &= BOLT_AND; - entNum &= ENTITY_AND; - *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); - return qtrue; + toModelNum &= MODEL_AND; + toBoltIndex &= BOLT_AND; + entNum &= ENTITY_AND; + *boltInfo = (toBoltIndex << BOLT_SHIFT) | (toModelNum << MODEL_SHIFT) | (entNum << ENTITY_SHIFT); + return qtrue; } } return qfalse; - } qboolean gG2_GBMNoReconstruct; qboolean gG2_GBMUseSPMethod; qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int frameNum, qhandle_t *modelList, const vec3_t scale ) -{ + const vec3_t position, const int frameNum, qhandle_t *modelList, const vec3_t scale) { assert(ghoul2.size() > modelIndex); - if ((ghoul2.size() > modelIndex)) - { + if ((ghoul2.size() > modelIndex)) { CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - //assert(boltIndex < ghlInfo->mBltlist.size()); + // assert(boltIndex < ghlInfo->mBltlist.size()); - if (ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) && boltIndex >= 0 ) - { + if (ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) && boltIndex >= 0) { // make sure we have transformed the skeleton - if (!gG2_GBMNoReconstruct) - { + if (!gG2_GBMNoReconstruct) { G2_ConstructGhoulSkeleton(ghoul2, frameNum, true, scale); } @@ -1952,33 +1646,29 @@ qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelInde mdxaBone_t scaled; mdxaBone_t *use; - use=&ghlInfo->mBltlist[boltIndex].position; + use = &ghlInfo->mBltlist[boltIndex].position; - if (scale[0]||scale[1]||scale[2]) - { - scaled=*use; - use=&scaled; + if (scale[0] || scale[1] || scale[2]) { + scaled = *use; + use = &scaled; // scale the bolt position by the scale factor for this model since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { scaled.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { scaled.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { scaled.matrix[2][3] *= scale[2]; } } // pre generate the world matrix G2_GenerateWorldMatrix(angles, position); - VectorNormalize((float*)use->matrix[0]); - VectorNormalize((float*)use->matrix[1]); - VectorNormalize((float*)use->matrix[2]); + VectorNormalize((float *)use->matrix[0]); + VectorNormalize((float *)use->matrix[1]); + VectorNormalize((float *)use->matrix[2]); Multiply_3x4Matrix(matrix, &worldMatrix, use); return qtrue; @@ -1987,44 +1677,33 @@ qboolean G2API_GetBoltMatrix_SPMethod(CGhoul2Info_v &ghoul2, const int modelInde return qfalse; } -#define G2ERROR(exp,m) ((void)0) //rwwFIXMEFIXME: This is because I'm lazy. -#define G2WARNING(exp,m) ((void)0) -#define G2NOTE(exp,m) ((void)0) -#define G2ANIM(ghlInfo,m) ((void)0) -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum); -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); +#define G2ERROR(exp, m) ((void)0) // rwwFIXMEFIXME: This is because I'm lazy. +#define G2WARNING(exp, m) ((void)0) +#define G2NOTE(exp, m) ((void)0) +#define G2ANIM(ghlInfo, m) ((void)0) +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum); +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); -//qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, +// qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, // const vec3_t position, const int AframeNum, qhandle_t *modelList, const vec3_t scale ) -qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, - const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) -{ -// G2ERROR(ghoul2.IsValid(),"Invalid ghlInfo"); - G2ERROR(matrix,"NULL matrix"); - G2ERROR(modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size(), "Invalid ModelIndex"); + const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; G2_GenerateWorldMatrix(angles, position); - if (G2_SetupModelPointers(ghoul2)) - { - if (matrix&&modelIndex>=0&&modelIndex= 0 && modelIndex < ghoul2.size()) { + int tframeNum = G2API_GetTime(frameNum); CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - G2ERROR(boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()),va("Invalid Bolt Index (%d:%s)",boltIndex,ghlInfo->mFileName)); + G2ERROR(boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()), va("Invalid Bolt Index (%d:%s)", boltIndex, ghlInfo->mFileName)); - if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size()) ) - { + if (boltIndex >= 0 && ghlInfo && (boltIndex < (int)ghlInfo->mBltlist.size())) { mdxaBone_t bolt; -#if 0 //yeah, screw it +#if 0 // yeah, screw it if (!gG2_GBMNoReconstruct) { //This should only be used when you know what you're doing. if (G2_NeedsRecalc(ghlInfo,tframeNum)) @@ -2037,44 +1716,37 @@ qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const gG2_GBMNoReconstruct = qfalse; } #else - if (G2_NeedsRecalc(ghlInfo,tframeNum)) - { - G2_ConstructGhoulSkeleton(ghoul2,tframeNum,true,scale); + if (G2_NeedsRecalc(ghlInfo, tframeNum)) { + G2_ConstructGhoulSkeleton(ghoul2, tframeNum, true, scale); } #endif - G2_GetBoltMatrixLow(*ghlInfo,boltIndex,scale,bolt); + G2_GetBoltMatrixLow(*ghlInfo, boltIndex, scale, bolt); // scale the bolt position by the scale factor for this model since at this point its still in model space - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); Multiply_3x4Matrix(matrix, &worldMatrix, &bolt); #if G2API_DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !_isnan(matrix->matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!_isnan(matrix->matrix[i][j])); } } -#endif// _DEBUG - G2ANIM(ghlInfo,"G2API_GetBoltMatrix"); +#endif // _DEBUG + G2ANIM(ghlInfo, "G2API_GetBoltMatrix"); - if (!gG2_GBMUseSPMethod) - { //this is horribly stupid and I hate it. But lots of game code is written to assume this 90 degree offset thing. + if (!gG2_GBMUseSPMethod) { // this is horribly stupid and I hate it. But lots of game code is written to assume this 90 degree offset thing. float ftemp; ftemp = matrix->matrix[0][0]; matrix->matrix[0][0] = -matrix->matrix[0][1]; @@ -2087,50 +1759,38 @@ qboolean G2API_GetBoltMatrix(CGhoul2Info_v &ghoul2, const int modelIndex, const ftemp = matrix->matrix[2][0]; matrix->matrix[2][0] = -matrix->matrix[2][1]; matrix->matrix[2][1] = ftemp; - } - else - { //reset it + } else { // reset it gG2_GBMUseSPMethod = qfalse; } return qtrue; } } - } - else - { - G2WARNING(0,"G2API_GetBoltMatrix Failed on empty or bad model"); + } else { + G2WARNING(0, "G2API_GetBoltMatrix Failed on empty or bad model"); } Multiply_3x4Matrix(matrix, &worldMatrix, (mdxaBone_t *)&identityMatrix); return qfalse; } -void G2API_ListSurfaces(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListSurfaces(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Surfaces(ghlInfo->mFileName); } } -void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) { + if (G2_SetupModelPointers(ghlInfo)) { G2_List_Model_Bones(ghlInfo->mFileName, frame); } } // decide if we have Ghoul2 models associated with this ghoul list or not -qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) -{ +qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) { int i; - if (ghoul2.size()) - { - for (i=0; imdxm->animName; } @@ -2181,10 +1838,8 @@ char *G2API_GetAnimFileNameIndex(qhandle_t modelIndex) * true if a good filename was obtained, false otherwise * ************************************************************************************************/ -qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetAnimFileName(ghlInfo->mFileName, filename); } return qfalse; @@ -2195,39 +1850,32 @@ qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) SV_QsortEntityNumbers ======================= */ -static int QDECL QsortDistance( const void *a, const void *b ) { - const float &ea = ((CollisionRecord_t*)a)->mDistance; - const float &eb = ((CollisionRecord_t*)b)->mDistance; +static int QDECL QsortDistance(const void *a, const void *b) { + const float &ea = ((CollisionRecord_t *)a)->mDistance; + const float &eb = ((CollisionRecord_t *)b)->mDistance; - if ( ea < eb ) { + if (ea < eb) { return -1; } return 1; } -static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) -{ //see if we need to do another transform +static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) { // see if we need to do another transform size_t i = 0; bool needTrans = false; - while (i < g2->mBlist.size()) - { - float time; + while (i < g2->mBlist.size()) { + float time; boneInfo_t &bone = g2->mBlist[i]; - if (bone.pauseTime) - { + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (frameNum - bone.startTime) / 50.0f; } int newFrame = bone.startFrame + (time * bone.animSpeed); - if (newFrame < bone.endFrame || - (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || - (bone.flags & BONE_NEED_TRANSFORM)) - { //ok, we're gonna have to do it. bone is apparently animating. + if (newFrame < bone.endFrame || (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || + (bone.flags & BONE_NEED_TRANSFORM)) { // ok, we're gonna have to do it. bone is apparently animating. bone.flags &= ~BONE_NEED_TRANSFORM; needTrans = true; } @@ -2237,25 +1885,23 @@ static inline bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) return needTrans; } -void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) -{ //this will store off the transformed verts for the next trace - this is slower, but for models that do not animate - //frequently it is much much faster. -rww +void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, + float fRadius) { // this will store off the transformed verts for the next trace - this is slower, but for models that do not + // animate frequently it is much much faster. -rww #if 0 // UNUSED int *test = ghoul2[0].mTransformedVertsArray; #endif - if (G2_SetupModelPointers(ghoul2)) - { - vec3_t transRayStart, transRayEnd; + if (G2_SetupModelPointers(ghoul2)) { + vec3_t transRayStart, transRayEnd; - int tframeNum=G2API_GetTime(frameNumber); + int tframeNum = G2API_GetTime(frameNumber); // make sure we have transformed the whole skeletons for each model - if (G2_NeedRetransform(&ghoul2[0], tframeNum) || !ghoul2[0].mTransformedVertsArray) - { //optimization, only create new transform space if we need to, otherwise - //store it off! + if (G2_NeedRetransform(&ghoul2[0], tframeNum) || + !ghoul2[0].mTransformedVertsArray) { // optimization, only create new transform space if we need to, otherwise + // store it off! int i = 0; - while (i < ghoul2.size()) - { + while (i < ghoul2.size()) { CGhoul2Info &g2 = ghoul2[i]; /* @@ -2265,10 +1911,9 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh g2.mTransformedVertsArray = 0; } */ - if (!g2.mTransformedVertsArray || !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) - { //reworked so we only alloc once! - //if we have a pointer, but not a ghoul2_zonetransalloc flag, then that means - //it is a miniheap pointer. Just stomp over it. + if (!g2.mTransformedVertsArray || !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) { // reworked so we only alloc once! + // if we have a pointer, but not a ghoul2_zonetransalloc flag, then that means + // it is a miniheap pointer. Just stomp over it. int iSize = g2.currentModel->mdxm->numSurfaces * 4; g2.mTransformedVertsArray = (size_t *)Z_Malloc(iSize, TAG_GHOUL2, qtrue); } @@ -2287,7 +1932,7 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); #endif - //don't need to do this anymore now that I am using a flag for zone alloc. + // don't need to do this anymore now that I am using a flag for zone alloc. /* i = 0; while (i < ghoul2.size()) @@ -2314,23 +1959,21 @@ void G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, CGhoul2Info_v &gh // now walk each model and check the ray against each poly - sigh, this is SO expensive. I wish there was a better way to do this. #ifdef _G2_GORE - G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius,0,0,0,0,0,qfalse); + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius, 0, 0, 0, 0, 0, qfalse); #else G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius); #endif int i; - for ( i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i ++ ); + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) + ; // now sort the resulting array of collision records so they are distance ordered - qsort( collRecMap, i, - sizeof( CollisionRecord_t ), QsortDistance ); + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); } } - -void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, - int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) -{ +void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, IHeapAllocator *G2VertSpace, int traceFlags, int useLod, float fRadius) { /* if (1) { @@ -2340,9 +1983,8 @@ void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, } */ - if (G2_SetupModelPointers(ghoul2)) - { - vec3_t transRayStart, transRayEnd; + if (G2_SetupModelPointers(ghoul2)) { + vec3_t transRayStart, transRayEnd; // make sure we have transformed the whole skeletons for each model G2_ConstructGhoulSkeleton(ghoul2, frameNumber, true, scale); @@ -2366,23 +2008,21 @@ void G2API_CollisionDetect(CollisionRecord_t *collRecMap, CGhoul2Info_v &ghoul2, // now walk each model and check the ray against each poly - sigh, this is SO expensive. I wish there was a better way to do this. #ifdef _G2_GORE - G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius,0,0,0,0,0,qfalse); + G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius, 0, 0, 0, 0, 0, qfalse); #else G2_TraceModels(ghoul2, transRayStart, transRayEnd, collRecMap, entNum, traceFlags, useLod, fRadius); #endif int i; - for ( i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i ++ ); + for (i = 0; i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; i++) + ; // now sort the resulting array of collision records so they are distance ordered - qsort( collRecMap, i, - sizeof( CollisionRecord_t ), QsortDistance ); + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); } } -qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) { + if (G2_SetupModelPointers(ghlInfo)) { ghlInfo->mFlags &= GHOUL2_NEWORIGIN; ghlInfo->mFlags |= flags; return qtrue; @@ -2390,20 +2030,16 @@ qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) return qfalse; } -int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) { + if (G2_SetupModelPointers(ghlInfo)) { return (ghlInfo->mFlags & ~GHOUL2_NEWORIGIN); } return 0; } // given a boltmatrix, return in vec a normalised vector for the axis requested in flags -void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) -{ - switch (flags) - { +void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) { + switch (flags) { case ORIGIN: vec[0] = boltMatrix->matrix[0][3]; vec[1] = boltMatrix->matrix[1][3]; @@ -2413,7 +2049,7 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v vec[0] = boltMatrix->matrix[0][1]; vec[1] = boltMatrix->matrix[1][1]; vec[2] = boltMatrix->matrix[2][1]; - break; + break; case POSITIVE_X: vec[0] = boltMatrix->matrix[0][0]; vec[1] = boltMatrix->matrix[1][0]; @@ -2442,36 +2078,29 @@ void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, v } } +int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) { + assert(modelIndex == -1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it + // if ya want it, we will add it back correctly -int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) -{ - assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it - // if ya want it, we will add it back correctly - - //G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); - if (g2From.IsValid()) - { + // G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); + if (g2From.IsValid()) { #ifdef _DEBUG - if (g2To.IsValid()) - { + if (g2To.IsValid()) { assert(!"Copying to a valid g2 instance?!"); - if (g2To[0].mBoneCache) - { + if (g2To[0].mBoneCache) { assert(!"Instance has a bonecache too.. it's gonna get stomped"); } } #endif g2To.DeepCopy(g2From); -#ifdef _G2_GORE //check through gore stuff then, as well. +#ifdef _G2_GORE // check through gore stuff then, as well. int model = 0; - while (model < g2To.size()) - { - if ( g2To[model].mGoreSetTag ) - { - CGoreSet* gore = FindGoreSet ( g2To[model].mGoreSetTag ); + while (model < g2To.size()) { + if (g2To[model].mGoreSetTag) { + CGoreSet *gore = FindGoreSet(g2To[model].mGoreSetTag); assert(gore); gore->mRefCount++; } @@ -2479,28 +2108,25 @@ int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int mod model++; } #endif - //G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); - //G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); + // G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); + // G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); } return -1; } -void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) -{ +void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) { #if 0 qboolean forceReconstruct = qtrue; -#endif //model1 was not getting reconstructed like it should for thrown sabers? - //might have been a bug in the reconstruct checking which has since been - //mangled and probably fixed. -rww +#endif // model1 was not getting reconstructed like it should for thrown sabers? + // might have been a bug in the reconstruct checking which has since been + // mangled and probably fixed. -rww // assume we actually have a model to copy from - if (ghoul2From.size() > modelFrom) - { + if (ghoul2From.size() > modelFrom) { // if we don't have enough models on the to side, resize us so we do - if (ghoul2To.size() <= modelTo) - { - assert (modelTo < 5); + if (ghoul2To.size() <= modelTo) { + assert(modelTo < 5); ghoul2To.resize(modelTo + 1); #if 0 forceReconstruct = qtrue; @@ -2508,10 +2134,8 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // do the copy - if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) - { //remove the bonecache before we stomp over this instance. - if (ghoul2To[modelTo].mBoneCache) - { + if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) { // remove the bonecache before we stomp over this instance. + if (ghoul2To[modelTo].mBoneCache) { RemoveBoneCache(ghoul2To[modelTo].mBoneCache); ghoul2To[modelTo].mBoneCache = 0; } @@ -2530,24 +2154,19 @@ void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2 } // This version will automatically copy everything about this model, and make a new one if necessary. -void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) -{ - //int ignore; +void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) { + // int ignore; - if (*g2To) - { // This is bad. We only want to do this if there is not yet a to declared. + if (*g2To) { // This is bad. We only want to do this if there is not yet a to declared. assert(0); return; } *g2To = new CGhoul2Info_v; #ifdef _FULL_G2_LEAK_CHECKING - if (g_G2AllocServer) - { + if (g_G2AllocServer) { g_G2ServerAlloc += sizeof(CGhoul2Info_v); - } - else - { + } else { g_G2ClientAlloc += sizeof(CGhoul2Info_v); } g_Ghoul2Allocations += sizeof(CGhoul2Info_v); @@ -2555,48 +2174,41 @@ void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) #endif CGhoul2Info_v &ghoul2 = *(*g2To); - /*ignore = */G2API_CopyGhoul2Instance(g2From, ghoul2, -1); + /*ignore = */ G2API_CopyGhoul2Instance(g2From, ghoul2, -1); return; } -char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber) -{ +char *G2API_GetSurfaceName(CGhoul2Info_v &ghoul2, int modelIndex, int surfNumber) { static char noSurface[1] = ""; CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(ghlInfo)) - { - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmSurfHierarchy_t *surfInfo = 0; + if (G2_SetupModelPointers(ghlInfo)) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmSurfHierarchy_t *surfInfo = 0; #ifndef FINAL_BUILD - if (!mod || !mod->mdxm) - { + if (!mod || !mod->mdxm) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad model on instance %s.", ghlInfo->mFileName); } #endif - //ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model - //may have.. but how did they get that surf index to begin with? Oh well. - if (surfNumber < 0 || surfNumber >= mod->mdxm->numSurfaces) - { - ri.Printf( PRINT_ALL, "G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); + // ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model + // may have.. but how did they get that surf index to begin with? Oh well. + if (surfNumber < 0 || surfNumber >= mod->mdxm->numSurfaces) { + ri.Printf(PRINT_ALL, "G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); return noSurface; } - surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, 0); - if (surf) - { + if (surf) { #ifndef FINAL_BUILD - if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mod->mdxm->numSurfaces) - { + if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mod->mdxm->numSurfaces) { Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad surf num (%i) on surf for instance %s.", surf->thisSurfaceIndex, ghlInfo->mFileName); } #endif - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->name; } @@ -2604,24 +2216,18 @@ char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber return noSurface; } - -int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_GetSurfaceIndex(ghlInfo, surfaceName); } return -1; } -char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) -{ - if (G2_SetupModelPointers(ghoul2)) - { - if ((ghoul2.size() > modelIndex)) - { - //model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - //return mod->mdxm->animName; +char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) { + if (G2_SetupModelPointers(ghoul2)) { + if ((ghoul2.size() > modelIndex)) { + // model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + // return mod->mdxm->animName; assert(ghoul2[modelIndex].currentModel && ghoul2[modelIndex].currentModel->mdxm); return ghoul2[modelIndex].currentModel->mdxm->animName; @@ -2630,27 +2236,19 @@ char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) return NULL; } -qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) -{ +qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) { CGhoul2Info *ghlInfo = NULL; - if (ghoul2.size()>0) - { + if (ghoul2.size() > 0) { ghlInfo = &ghoul2[0]; } - if (G2_SetupModelPointers(ghlInfo)) - { - if (boltIndex < 0) - { - char modelName[MAX_QPATH]; - if (ghlInfo->currentModel && - ghlInfo->currentModel->name[0]) - { + if (G2_SetupModelPointers(ghlInfo)) { + if (boltIndex < 0) { + char modelName[MAX_QPATH]; + if (ghlInfo->currentModel && ghlInfo->currentModel->name[0]) { strcpy(modelName, ghlInfo->currentModel->name); - } - else - { + } else { strcpy(modelName, "None?!"); } @@ -2664,94 +2262,70 @@ qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) return qfalse; } -int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) -{ - if (G2_SetupModelPointers(ghlInfo)) - { +int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) { + if (G2_SetupModelPointers(ghlInfo)) { return G2_Get_Bone_Index(ghlInfo, boneName); } return -1; } -qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ - return G2_SaveGhoul2Models(ghoul2, buffer, size); -} +qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { return G2_SaveGhoul2Models(ghoul2, buffer, size); } -void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) -{ - G2_LoadGhoul2Model(ghoul2, buffer); -} +void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) { G2_LoadGhoul2Model(ghoul2, buffer); } -void G2API_FreeSaveBuffer(char *buffer) -{ - Z_Free(buffer); -} +void G2API_FreeSaveBuffer(char *buffer) { Z_Free(buffer); } // this is kinda sad, but I need to call the destructor in this module (exe), not the game.dll... // -void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) -{ +void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) { #ifdef _G2_GORE - G2API_ClearSkinGore ( ghoul2 ); + G2API_ClearSkinGore(ghoul2); #endif - ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning + ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning } -//see if surfs have any shader info... -qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// see if surfs have any shader info... +qboolean G2API_SkinlessModel(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (G2_SetupModelPointers(g2)) - { - model_t *mod = (model_t *)g2->currentModel; + if (G2_SetupModelPointers(g2)) { + model_t *mod = (model_t *)g2->currentModel; - if (mod && - mod->mdxm) - { - mdxmSurfHierarchy_t *surf; + if (mod && mod->mdxm) { + mdxmSurfHierarchy_t *surf; int i; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy); - for (i = 0; i < mod->mdxm->numSurfaces; i++) - { - if (surf->shader[0]) - { //found a surface with a shader name, ok. - return qfalse; + for (i = 0; i < mod->mdxm->numSurfaces; i++) { + if (surf->shader[0]) { // found a surface with a shader name, ok. + return qfalse; } - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } } } - //found nothing. + // found nothing. return qtrue; } -int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) -{ - return ghoul2.size(); -} +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) { return ghoul2.size(); } //#ifdef _SOF2 #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling -//way of seeing how many marks are on a model currently -rww -int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) -{ +// way of seeing how many marks are on a model currently -rww +int G2API_GetNumGoreMarks(CGhoul2Info_v &ghoul2, int modelIndex) { CGhoul2Info *g2 = &ghoul2[modelIndex]; - if (g2->mGoreSetTag) - { + if (g2->mGoreSetTag) { CGoreSet *goreSet = FindGoreSet(g2->mGoreSetTag); - if (goreSet) - { + if (goreSet) { return goreSet->mGoreRecords.size(); } } @@ -2759,117 +2333,98 @@ int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) return 0; } -void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) -{ +void G2API_ClearSkinGore(CGhoul2Info_v &ghoul2) { int i; - for (i=0; inumLods,3); //limit to the number of lods the main model has - for(lod=lodbias;lodnumLods, 3); // limit to the number of lods the main model has + for (lod = lodbias; lod < maxLod; lod++) { // now having done that, time to build the model ri.GetG2VertSpaceServer()->ResetHeap(); - G2_TransformModel(ghoul2, gore.currentTime, gore.scale,ri.GetG2VertSpaceServer(),lod,true); + G2_TransformModel(ghoul2, gore.currentTime, gore.scale, ri.GetG2VertSpaceServer(), lod, true); // now walk each model and compute new texture coordinates - G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0,lod,0.0f,gore.SSize,gore.TSize,gore.theta,gore.shader,&gore,qtrue); + G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0, lod, 0.0f, gore.SSize, gore.TSize, gore.theta, gore.shader, &gore, + qtrue); } } #endif qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up { - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } - ghlInfo->mValid=false; - if (ghlInfo->mModelindex != -1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + ghlInfo->mValid = false; + if (ghlInfo->mModelindex != -1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); - if (ghlInfo->currentModel) - { - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + if (ghlInfo->currentModel) { + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } return (qboolean)ghlInfo->mValid; } @@ -2885,91 +2440,75 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_SetupModelPointers.Start(); #endif - G2ERROR(ghlInfo,"NULL ghlInfo"); - if (!ghlInfo) - { + G2ERROR(ghlInfo, "NULL ghlInfo"); + if (!ghlInfo) { return qfalse; } -// if (ghlInfo->mValid && ghlInfo->currentModel) - if (0) - { //rww - Why are we bothering with all this? We can't change models like this anyway. - //This function goes over 200k on the precision timer (in debug, but still), so I'm - //cutting it off here because it gets called constantly. + // if (ghlInfo->mValid && ghlInfo->currentModel) + if (0) { // rww - Why are we bothering with all this? We can't change models like this anyway. + // This function goes over 200k on the precision timer (in debug, but still), so I'm + // cutting it off here because it gets called constantly. #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_SetupModelPointers += G2PerformanceTimer_G2_SetupModelPointers.End(); #endif return qtrue; } - ghlInfo->mValid=false; + ghlInfo->mValid = false; -// G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); - if (ghlInfo->mModelindex != -1) - { - G2ERROR(ghlInfo->mFileName[0],"empty ghlInfo->mFileName"); + // G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); + if (ghlInfo->mModelindex != -1) { + G2ERROR(ghlInfo->mFileName[0], "empty ghlInfo->mFileName"); // RJ - experimental optimization! - if (!ghlInfo->mModel || 1) - { - if (ri.Cvar_VariableIntegerValue( "dedicated" ) || - (G2_ShouldRegisterServer())) //supreme hackery! + if (!ghlInfo->mModel || 1) { + if (ri.Cvar_VariableIntegerValue("dedicated") || (G2_ShouldRegisterServer())) // supreme hackery! { ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); - } - else - { + } else { ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); } ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); } - G2ERROR(ghlInfo->currentModel,va("NULL Model (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel) - { - G2ERROR(ghlInfo->currentModel->mdxm,va("Model has no mdxm (glm) %s",ghlInfo->mFileName)); - if (ghlInfo->currentModel->mdxm) - { - if (ghlInfo->currentModelSize) - { - if (ghlInfo->currentModelSize!=ghlInfo->currentModel->mdxm->ofsEnd) - { + G2ERROR(ghlInfo->currentModel, va("NULL Model (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel) { + G2ERROR(ghlInfo->currentModel->mdxm, va("Model has no mdxm (glm) %s", ghlInfo->mFileName)); + if (ghlInfo->currentModel->mdxm) { + if (ghlInfo->currentModelSize) { + if (ghlInfo->currentModelSize != ghlInfo->currentModel->mdxm->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentModelSize=ghlInfo->currentModel->mdxm->ofsEnd; - G2ERROR(ghlInfo->currentModelSize,va("Zero sized Model? (glm) %s",ghlInfo->mFileName)); + ghlInfo->currentModelSize = ghlInfo->currentModel->mdxm->ofsEnd; + G2ERROR(ghlInfo->currentModelSize, va("Zero sized Model? (glm) %s", ghlInfo->mFileName)); ghlInfo->animModel = R_GetModelByHandle(ghlInfo->currentModel->mdxm->animIndex); - G2ERROR(ghlInfo->animModel,va("NULL Model (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->animModel) - { - ghlInfo->aHeader =ghlInfo->animModel->mdxa; - G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); - if (ghlInfo->aHeader) - { - if (ghlInfo->currentAnimModelSize) - { - if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) - { + G2ERROR(ghlInfo->animModel, va("NULL Model (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->animModel) { + ghlInfo->aHeader = ghlInfo->animModel->mdxa; + G2ERROR(ghlInfo->aHeader, va("Model has no mdxa (gla) %s", ghlInfo->mFileName)); + if (ghlInfo->aHeader) { + if (ghlInfo->currentAnimModelSize) { + if (ghlInfo->currentAnimModelSize != ghlInfo->aHeader->ofsEnd) { Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); } } - ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; - G2ERROR(ghlInfo->currentAnimModelSize,va("Zero sized Model? (gla) %s",ghlInfo->mFileName)); - ghlInfo->mValid=true; + ghlInfo->currentAnimModelSize = ghlInfo->aHeader->ofsEnd; + G2ERROR(ghlInfo->currentAnimModelSize, va("Zero sized Model? (gla) %s", ghlInfo->mFileName)); + ghlInfo->mValid = true; } } } } } - if (!ghlInfo->mValid) - { - ghlInfo->currentModel=0; - ghlInfo->currentModelSize=0; - ghlInfo->animModel=0; - ghlInfo->currentAnimModelSize=0; - ghlInfo->aHeader=0; + if (!ghlInfo->mValid) { + ghlInfo->currentModel = 0; + ghlInfo->currentModelSize = 0; + ghlInfo->animModel = 0; + ghlInfo->currentAnimModelSize = 0; + ghlInfo->aHeader = 0; } #ifdef G2_PERFORMANCE_ANALYSIS @@ -2980,22 +2519,15 @@ qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the mode qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2) // returns true if any model is properly set up { - bool ret=false; + bool ret = false; int i; - for (i=0; i. // Bolt List handling routines - so entities can attach themselves to any part of the model in question // Given a bone number, see if that bone is already in our bone list -int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) -{ +int G2_Find_Bolt_Bone_Num(boltInfo_v &bltlist, const int boneNum) { // look through entire list - for(size_t i=0; imValid); - boltInfo_t tempBolt; + boltInfo_t tempBolt; // first up, make sure have a surface first - if (surfNum >= (int)slist.size()) - { + if (surfNum >= (int)slist.size()) { return -1; } - // look through entire list - see if it's already there first - for(size_t i=0; imValid); - model_t *mod_m = (model_t *)ghlInfo->currentModel; - model_t *mod_a = (model_t *)ghlInfo->animModel; - int x, surfNum = -1; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boltInfo_t tempBolt; - int flags; + model_t *mod_m = (model_t *)ghlInfo->currentModel; + model_t *mod_a = (model_t *)ghlInfo->animModel; + int x, surfNum = -1; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boltInfo_t tempBolt; + int flags; // first up, we'll search for that which this bolt names in all the surfaces - surfNum = G2_IsSurfaceLegal((void*)mod_m, boneName, &flags); + surfNum = G2_IsSurfaceLegal((void *)mod_m, boneName, &flags); // did we find it as a surface? - if (surfNum != -1) - { - // look through entire list - see if it's already there first - for(size_t i=0; imdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mod_a->mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mod_a->mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mod_a->mdxa->numBones) - { + if (x == mod_a->mdxa->numBones) { // didn't find it? Error - //assert(0&&x == mod_a->mdxa->numBones); + // assert(0&&x == mod_a->mdxa->numBones); #ifdef _DEBUG // ri.Printf( PRINT_ALL, "WARNING: %s not found on skeleton\n", boneName); #endif @@ -200,11 +176,9 @@ int G2_Add_Bolt(CGhoul2Info *ghlInfo, boltInfo_v &bltlist, surfaceInfo_v &slist, } // look through entire list - see if it's already there first - for(size_t i=0; i-1; i--) - { - if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) - { + for (int i = bltlist.size() - 1; i > -1; i--) { + if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != bltlist.size()) - { + if (newSize != bltlist.size()) { // yes, so lets do it bltlist.resize(newSize); } - } return qtrue; } @@ -280,29 +243,20 @@ qboolean G2_Remove_Bolt (boltInfo_v &bltlist, int index) } // set the bolt list to all unused so the bone transformation routine ignores it. -void G2_Init_Bolt_List(boltInfo_v &bltlist) -{ - bltlist.clear(); -} +void G2_Init_Bolt_List(boltInfo_v &bltlist) { bltlist.clear(); } // remove any bolts that reference original surfaces, generated surfaces, or bones that aren't active anymore -void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) -{ +void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) { // walk the bolt list - for (size_t i=0; i. #include "ghoul2/G2.h" #include "ghoul2/g2_local.h" -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifndef __linux__ #include #else @@ -37,26 +37,23 @@ along with this program; if not, see . //#define RAG_TRACE_DEBUG_LINES #include "client/client.h" //while this is all "shared" code, there are some places where we want to make cgame callbacks (for ragdoll) only if the cgvm exists -//rww - RAGDOLL_END +// rww - RAGDOLL_END //===================================================================================================================== // Bone List handling routines - so entities can override bone info on a bone by bone level, and also interrogate this info // Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the // gla file, not the glm file type. -int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); +int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; imdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -75,116 +71,97 @@ int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) } // we need to add a bone to the list - find a free one and see if we can find a corresponding bone in the gla file -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) -{ +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) { int x; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - boneInfo_t tempBone; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boneInfo_t tempBone; - //rww - RAGDOLL_BEGIN + // rww - RAGDOLL_BEGIN memset(&tempBone, 0, sizeof(tempBone)); - //rww - RAGDOLL_END + // rww - RAGDOLL_END - offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t)); - // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find - for (x=0; x< mod->mdxa->numBones; x++) - { - skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); - // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x = 0; x < mod->mdxa->numBones; x++) { + skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) { break; } } // check to see we did actually make a match with a bone in the model - if (x == mod->mdxa->numBones) - { + if (x == mod->mdxa->numBones) { // didn't find it? Error - //assert(0); + // assert(0); #ifdef _DEBUG - ri.Printf( PRINT_ALL, "WARNING: Failed to add bone %s\n", boneName); + ri.Printf(PRINT_ALL, "WARNING: Failed to add bone %s\n", boneName); #endif #ifdef _RAG_PRINT_TEST - ri.Printf( PRINT_ALL, "WARNING: Failed to add bone %s\n", boneName); + ri.Printf(PRINT_ALL, "WARNING: Failed to add bone %s\n", boneName); #endif return -1; } // look through entire list - see if it's already there first - for(size_t i=0; imdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } - } - else - { + } else { // if we found an entry that had a -1 for the bonenumber, then we hit a bone slot that was empty blist[i].boneNumber = x; blist[i].flags = 0; - return i; + return i; } } #ifdef _RAG_PRINT_TEST - ri.Printf( PRINT_ALL, "New bone added for %s\n", boneName); + ri.Printf(PRINT_ALL, "New bone added for %s\n", boneName); #endif // ok, we didn't find an existing bone of that name, or an empty slot. Lets add an entry tempBone.boneNumber = x; tempBone.flags = 0; blist.push_back(tempBone); - return blist.size()-1; + return blist.size() - 1; } - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) -{ - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { +qboolean G2_Remove_Bone_Index(boneInfo_v &blist, int index) { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // check the flags first - if it's still being used Do NOT remove it - if (!blist[index].flags) - { + if (!blist[index].flags) { // set this bone to not used blist[index].boneNumber = -1; - unsigned int newSize = blist.size(); + unsigned int newSize = blist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=blist.size()-1; i>-1; i--) - { - if (blist[i].boneNumber == -1) - { + for (int i = blist.size() - 1; i > -1; i--) { + if (blist[i].boneNumber == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != blist.size()) - { + if (newSize != blist.size()) { // yes, so lets do it blist.resize(newSize); } @@ -193,19 +170,16 @@ qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) } } -// assert(0); + // assert(0); // no return qfalse; } // given a bone number, see if there is an override bone in the bone list -int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) -{ +int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) { // look through entire list - for(size_t i=0; imdxa + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)mod->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[index].boneNumber]); - Multiply_3x4Matrix(&temp1, boneOverride,&skel->BasePoseMatInv); - Multiply_3x4Matrix(boneOverride,&skel->BasePoseMat, &temp1); + Multiply_3x4Matrix(&temp1, boneOverride, &skel->BasePoseMatInv); + Multiply_3x4Matrix(boneOverride, &skel->BasePoseMat, &temp1); - } - else - { + } else { VectorCopy(angles, newAngles); // why I should need do this Fuck alone knows. But I do. - if (left == POSITIVE_Y) - { - newAngles[0] +=180; + if (left == POSITIVE_Y) { + newAngles[0] += 180; } Create_Matrix(newAngles, &temp1); @@ -346,13 +310,12 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[2][0] = permutation.matrix[2][1] = permutation.matrix[2][2] = permutation.matrix[2][3] = 0; // determine what axis newAngles Yaw should revolve around - switch (forward) - { + switch (forward) { case NEGATIVE_X: - permutation.matrix[0][0] = -1; // works + permutation.matrix[0][0] = -1; // works break; case POSITIVE_X: - permutation.matrix[0][0] = 1; // works + permutation.matrix[0][0] = 1; // works break; case NEGATIVE_Y: permutation.matrix[1][0] = -1; @@ -371,8 +334,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles pitch should revolve around - switch (left) - { + switch (left) { case NEGATIVE_X: permutation.matrix[0][1] = -1; break; @@ -380,10 +342,10 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[0][1] = 1; break; case NEGATIVE_Y: - permutation.matrix[1][1] = -1; // works + permutation.matrix[1][1] = -1; // works break; case POSITIVE_Y: - permutation.matrix[1][1] = 1; // works + permutation.matrix[1][1] = 1; // works break; case NEGATIVE_Z: permutation.matrix[2][1] = -1; @@ -396,8 +358,7 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const } // determine what axis newAngles Roll should revolve around - switch (up) - { + switch (up) { case NEGATIVE_X: permutation.matrix[0][2] = -1; break; @@ -411,31 +372,27 @@ void G2_Generate_Matrix(const model_t *mod, boneInfo_v &blist, int index, const permutation.matrix[1][2] = 1; break; case NEGATIVE_Z: - permutation.matrix[2][2] = -1; // works + permutation.matrix[2][2] = -1; // works break; case POSITIVE_Z: - permutation.matrix[2][2] = 1; // works + permutation.matrix[2][2] = 1; // works break; default: break; } - Multiply_3x4Matrix(boneOverride, &temp1,&permutation); - + Multiply_3x4Matrix(boneOverride, &temp1, &permutation); } // keep a copy of the matrix in the newmatrix which is actually what we use memcpy(&blist[index].newMatrix, &blist[index].matrix, sizeof(mdxaBone_t)); - } //========================================================================================= //// Public Bone Routines - // Given a model handle, and a bone name, we want to remove this bone from the bone override list -qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ +qboolean G2_Remove_Bone(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { int index; assert(ghlInfo->animModel); @@ -446,30 +403,22 @@ qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *bo #define DEBUG_PCJ (0) - // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles_Index( boneInfo_v &blist, const int index, - const float *angles, const int flags, const Eorientations yaw, - const Eorientations pitch, const Eorientations roll, qhandle_t *modelList, - const int modelIndex, const int blendTime, const int currentTime) -{ - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { +qboolean G2_Set_Bone_Angles_Index(boneInfo_v &blist, const int index, const float *angles, const int flags, const Eorientations yaw, const Eorientations pitch, + const Eorientations roll, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } - if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) - { + if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) { // you CANNOT call this with an index with these kinds of bone overrides - we need the model details for these kinds of bone angle overrides assert(0); return qfalse; @@ -481,30 +430,26 @@ qboolean G2_Set_Bone_Angles_Index( boneInfo_v &blist, const int index, blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf("PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],yaw,pitch,roll,flags); + Com_OPrintf("PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], yaw, pitch, roll, flags); #endif G2_Generate_Matrix(NULL, blist, index, angles, flags, yaw, pitch, roll); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding -qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, - const int flags, const Eorientations up, const Eorientations left, const Eorientations forward, - qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_a; +qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, const int flags, const Eorientations up, + const Eorientations left, const Eorientations forward, qhandle_t *modelList, const int modelIndex, const int blendTime, + const int currentTime) { + model_t *mod_a; mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } @@ -514,7 +459,7 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); @@ -525,43 +470,37 @@ qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; blist[index].boneBlendStart = currentTime; blist[index].boneBlendTime = blendTime; #if DEBUG_PCJ - Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", index, currentTime, angles[0], angles[1], angles[2], up, left, forward, flags); #endif G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); return qtrue; } -// assert(0); - //Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. + // assert(0); + // Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. // no return qfalse; } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, - const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, - const int modelIndex, const int blendTime, const int currentTime) -{ +qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + const int modelIndex, const int blendTime, const int currentTime) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } @@ -574,36 +513,28 @@ qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); return qtrue; - } // Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly -qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, - const int flags, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) -{ - model_t *mod_m; - if (!fileName[0]) - { +qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, const int flags, + qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) { + model_t *mod_m; + if (!fileName[0]) { mod_m = R_GetModelByHandle(modelList[modelIndex]); - } - else - { + } else { mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); } - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } // did we find it? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -617,8 +548,7 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons index = G2_Add_Bone(mod_a, blist, boneName); // did we find a free one? - if (index != -1) - { + if (index != -1) { // yes, so set the angles and flags correctly blist[index].flags &= ~(BONE_ANGLES_TOTAL); blist[index].flags |= flags; @@ -635,108 +565,76 @@ qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, cons #define DEBUG_G2_TIMING (0) -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim_Index( - boneInfo_v &blist, - const int index, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime, - const int numFrames) -{ - int modFlags = flags; +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim_Index(boneInfo_v &blist, const int index, const int startFrame, const int endFrame, const int flags, const float animSpeed, + const int currentTime, const float setFrame, const int blendTime, const int numFrames) { + int modFlags = flags; - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } - //mark it for needing a transform for the cached trace transform stuff + // mark it for needing a transform for the cached trace transform stuff blist[index].flags |= BONE_NEED_TRANSFORM; } - if (setFrame != -1) - { + if (setFrame != -1) { assert((setFrame >= startFrame) && (setFrame <= endFrame)); } - if (flags & BONE_ANIM_BLEND) - { - float currentFrame, animSpeed; - int startFrame, endFrame, flags; + if (flags & BONE_ANIM_BLEND) { + float currentFrame, animSpeed; + int startFrame, endFrame, flags; // figure out where we are now - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) - { - if (blist[index].blendStart == currentTime) //we're replacing a blend in progress which hasn't started + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) { + if (blist[index].blendStart == currentTime) // we're replacing a blend in progress which hasn't started { // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; - } - else - { - if (animSpeed<0.0f) - { + } else { + if (animSpeed < 0.0f) { blist[index].blendFrame = floor(currentFrame); blist[index].blendLerpFrame = floor(currentFrame); - } - else - { + } else { blist[index].blendFrame = currentFrame; - blist[index].blendLerpFrame = currentFrame+1; + blist[index].blendLerpFrame = currentFrame + 1; // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendFrame >= endFrame ) - { + if (blist[index].blendFrame >= endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { - blist[index].blendFrame = endFrame -1; + } else { + blist[index].blendFrame = endFrame - 1; } } } // cope with if the lerp frame is actually off the end of the anim - if (blist[index].blendLerpFrame >= endFrame ) - { + if (blist[index].blendLerpFrame >= endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) { blist[index].blendLerpFrame = startFrame; } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - // assert(endFrame>0); - if (endFrame <= 0) - { + else { + // assert(endFrame>0); + if (endFrame <= 0) { blist[index].blendLerpFrame = 0; - } - else - { + } else { blist[index].blendLerpFrame = endFrame - 1; } } @@ -745,19 +643,15 @@ qboolean G2_Set_Bone_Anim_Index( // set the amount of time it's going to take to blend this anim with the last frame of the last one blist[index].blendTime = blendTime; blist[index].blendStart = currentTime; - } } // hmm, we weren't animating on this bone. In which case disable the blend - else - { + else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = 0; modFlags &= ~(BONE_ANIM_BLEND); } - } - else - { + } else { blist[index].blendFrame = blist[index].blendLerpFrame = 0; blist[index].blendTime = blist[index].blendStart = 0; // we aren't blending, so remove the option to do so @@ -769,108 +663,66 @@ qboolean G2_Set_Bone_Anim_Index( blist[index].animSpeed = animSpeed; blist[index].pauseTime = 0; // start up the animation:) - if (setFrame != -1) - { - blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); - } - else - { + if (setFrame != -1) { + blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0) / animSpeed)); + } else { blist[index].lastTime = blist[index].startTime = currentTime; } blist[index].flags &= ~(BONE_ANIM_TOTAL); - if (blist[index].flags < 0) - { + if (blist[index].flags < 0) { blist[index].flags = 0; } blist[index].flags |= modFlags; #if DEBUG_G2_TIMING - if (index==2) - { - const boneInfo_t &bone=blist[index]; + if (index == 2) { + const boneInfo_t &bone = blist[index]; char mess[1000]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess,"sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, "sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", index, currentTime, bone.startTime, bone.startFrame, + bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, "saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", index, currentTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, + bone.flags); } - else - { - sprintf(mess,"saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - index, - currentTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); - } - Com_OPrintf("%s",mess); + Com_OPrintf("%s", mess); } #endif return qtrue; - } -// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims -qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, - boneInfo_v &blist, - const char *boneName, - const int startFrame, - const int endFrame, - const int flags, - const float animSpeed, - const int currentTime, - const float setFrame, - const int blendTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of +// anims +qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); - if (index == -1) - { + int index = G2_Find_Bone(mod_a, blist, boneName); + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index != -1) - { - if (blist[index].flags & BONE_ANGLES_RAGDOLL) - { + if (index != -1) { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) { return qtrue; // don't accept any calls on ragdoll bones } } - if (index != -1) - { - return G2_Set_Bone_Anim_Index(blist,index,startFrame,endFrame,flags,animSpeed,currentTime,setFrame,blendTime,ghlInfo->aHeader->numFrames); + if (index != -1) { + return G2_Set_Bone_Anim_Index(blist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); } return qfalse; } -qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) { + model_t *mod_a = (model_t *)ghlInfo->animModel; + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; return qtrue; @@ -881,24 +733,21 @@ qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const c // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp); -qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int numFrames) -{ +qboolean G2_Get_Bone_Anim_Index(boneInfo_v &blist, const int index, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *retAnimSpeed, qhandle_t *modelList, int numFrames) { // did we find it? - if ((index>=0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) - { + if ((index >= 0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) { // are we an animating bone? - if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - int lcurrentFrame,newFrame; + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + int lcurrentFrame, newFrame; float lerp; - G2_TimingModel(blist[index],currentTime,numFrames,lcurrentFrame,newFrame,lerp); + G2_TimingModel(blist[index], currentTime, numFrames, lcurrentFrame, newFrame, lerp); - *currentFrame =float(lcurrentFrame)+lerp; + *currentFrame = float(lcurrentFrame) + lerp; *startFrame = blist[index].startFrame; *endFrame = blist[index].endFrame; *flags = blist[index].flags; @@ -906,40 +755,36 @@ qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int c return qtrue; } } - *startFrame=0; - *endFrame=1; - *currentFrame=0.0f; - *flags=0; - *retAnimSpeed=0.0f; + *startFrame = 0; + *endFrame = 1; + *currentFrame = 0.0f; + *flags = 0; + *retAnimSpeed = 0.0f; return qfalse; } // given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation // NOTE if we aren't running an animation, then qfalse is returned -qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, - float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, + int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); - if (index==-1) - { + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); - if (index == -1) - { + if (index == -1) { return qfalse; } } assert(ghlInfo->aHeader); - if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) - { - assert(*startFrame>=0&&*startFrameaHeader->numFrames); - assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); - assert(*currentFrame>=0.0f&&((int)(*currentFrame))aHeader->numFrames); + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) { + assert(*startFrame >= 0 && *startFrame < ghlInfo->aHeader->numFrames); + assert(*endFrame > 0 && *endFrame <= ghlInfo->aHeader->numFrames); + assert(*currentFrame >= 0.0f && ((int)(*currentFrame)) < ghlInfo->aHeader->numFrames); return qtrue; } @@ -947,20 +792,17 @@ qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *b } // given a model, bonelist and bonename, lets pause an anim if it's playing. -qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) -{ - model_t *mod_a = (model_t *)ghlInfo->animModel; +qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) { + model_t *mod_a = (model_t *)ghlInfo->animModel; - int index = G2_Find_Bone(mod_a, blist, boneName); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we pausing or un pausing? - if (blist[index].pauseTime) - { - int startFrame = 0, endFrame = 0, flags = 0; - float currentFrame = 0.0f, animSpeed = 1.0f; + if (blist[index].pauseTime) { + int startFrame = 0, endFrame = 0, flags = 0; + float currentFrame = 0.0f, animSpeed = 1.0f; // figure out what frame we are on now G2_Get_Bone_Anim(ghlInfo, blist, boneName, blist[index].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, 0); @@ -970,8 +812,7 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char blist[index].pauseTime = 0; } // ahh, just pausing, the easy bit - else - { + else { blist[index].pauseTime = currentTime; } @@ -982,18 +823,15 @@ qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char return qfalse; } -qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { // are we paused? - if (blist[index].pauseTime) - { + if (blist[index].pauseTime) { // yup. paused. return qtrue; } @@ -1004,11 +842,9 @@ qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneNa } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -1020,15 +856,13 @@ qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANIM_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1039,11 +873,9 @@ qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char * } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) -{ +qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) { - if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) - { + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) { // we are attempting to set a bone override that doesn't exist assert(0); return qfalse; @@ -1052,19 +884,16 @@ qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); - } // given a model, bonelist and bonename, lets stop an anim if it's playing. -qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) -{ - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int index = G2_Find_Bone(mod_a, blist, boneName); +qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); // did we find it? - if (index != -1) - { + if (index != -1) { blist[index].flags &= ~(BONE_ANGLES_TOTAL); // try and remove this bone if we can return G2_Remove_Bone_Index(blist, index); @@ -1074,76 +903,56 @@ qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char return qfalse; } - // actually walk the bone list and update each and every bone if we have ended an animation for them. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index ) -{ +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index) { boneInfo_v &blist = ghoul2[index].mBlist; // look through entire list - for(size_t i=0; i 0.0f) && (newFrame_g > endFrame-1 )) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1 ))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { - if (newFrame_g <= endFrame+1) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + if (animSpeed < 0.0f) { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } - } - else - { - if (newFrame_g >= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } } // figure out new start time - float frameTime = newFrame_g - blist[i].startFrame ; + float frameTime = newFrame_g - blist[i].startFrame; blist[i].startTime = currentTime - (int)((frameTime / animSpeed) * 50.0f); - if (blist[i].startTime>currentTime) - { - blist[i].startTime=currentTime; + if (blist[i].startTime > currentTime) { + blist[i].startTime = currentTime; } assert(blist[i].startTime <= currentTime); blist[i].lastTime = blist[i].startTime; - } - else - { - if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) - { + } else { + if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) { // nope, just stop it. And remove the bone if possible G2_Stop_Bone_Index(blist, i, (BONE_ANIM_TOTAL)); } @@ -1155,136 +964,127 @@ void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const in } } -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN /* rag stuff */ -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool LimitAngles,CRagDollUpdateParams *params = NULL); -static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale); -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V,const vec3_t currentOrg,CRagDollUpdateParams *params, int curTime); -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered); - -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep); -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum); +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool LimitAngles, + CRagDollUpdateParams *params = NULL); +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V, int g2Index, int frameNum, const vec3_t angles, const vec3_t position, const vec3_t scale); +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime); +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered); + +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv); +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv); +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum); #define MAX_BONES_RAG (256) -struct SRagEffector -{ - vec3_t currentOrigin; - vec3_t desiredDirection; - vec3_t desiredOrigin; - float radius; - float weight; +struct SRagEffector { + vec3_t currentOrigin; + vec3_t desiredDirection; + vec3_t desiredOrigin; + float radius; + float weight; }; -#define RAG_MASK (CONTENTS_SOLID|CONTENTS_TERRAIN)//|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) +#define RAG_MASK \ + (CONTENTS_SOLID | \ + CONTENTS_TERRAIN) //|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) -extern cvar_t *broadsword; -extern cvar_t *broadsword_kickbones; -extern cvar_t *broadsword_kickorigin; -extern cvar_t *broadsword_dontstopanim; -extern cvar_t *broadsword_waitforshot; -extern cvar_t *broadsword_playflop; +extern cvar_t *broadsword; +extern cvar_t *broadsword_kickbones; +extern cvar_t *broadsword_kickorigin; +extern cvar_t *broadsword_dontstopanim; +extern cvar_t *broadsword_waitforshot; +extern cvar_t *broadsword_playflop; -extern cvar_t *broadsword_effcorr; +extern cvar_t *broadsword_effcorr; -extern cvar_t *broadsword_ragtobase; +extern cvar_t *broadsword_ragtobase; -extern cvar_t *broadsword_dircap; +extern cvar_t *broadsword_dircap; -extern cvar_t *broadsword_extra1; -extern cvar_t *broadsword_extra2; +extern cvar_t *broadsword_extra1; +extern cvar_t *broadsword_extra2; -#define RAG_PCJ (0x00001) -#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well -#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well -#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well -#define RAG_EFFECTOR (0x00100) -#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint -#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint -#define RAG_BONE_LIGHTWEIGHT (0x04000) //used to indicate a bone's velocity treatment -#define RAG_PCJ_IK_CONTROLLED (0x08000) //controlled from IK move input -#define RAG_UNSNAPPABLE (0x10000) //cannot be broken out of constraints ever +#define RAG_PCJ (0x00001) +#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well +#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well +#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well +#define RAG_EFFECTOR (0x00100) +#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint +#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint +#define RAG_BONE_LIGHTWEIGHT (0x04000) // used to indicate a bone's velocity treatment +#define RAG_PCJ_IK_CONTROLLED (0x08000) // controlled from IK move input +#define RAG_UNSNAPPABLE (0x10000) // cannot be broken out of constraints ever // thiese flags are on the model and correspond to... //#define GHOUL2_RESERVED_FOR_RAGDOLL 0x0ff0 // these are not defined here for dependecies sake -#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll -#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim -#define GHOUL2_RAG_DONE 0x0200 // got end death anim -#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event -#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event -#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll +#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim +#define GHOUL2_RAG_DONE 0x0200 // got end death anim +#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event +#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event +#define GHOUL2_RAG_FORCESOLVE 0x1000 // api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled //#define flrand Q_flrand -static mdxaBone_t* ragBasepose[MAX_BONES_RAG]; -static mdxaBone_t* ragBaseposeInv[MAX_BONES_RAG]; -static mdxaBone_t ragBones[MAX_BONES_RAG]; -static SRagEffector ragEffectors[MAX_BONES_RAG]; -static boneInfo_t *ragBoneData[MAX_BONES_RAG]; -static int tempDependents[MAX_BONES_RAG]; -static int ragBlistIndex[MAX_BONES_RAG]; -static int numRags; -static vec3_t ragBoneMins; -static vec3_t ragBoneMaxs; -static vec3_t ragBoneCM; -static bool haveDesiredPelvisOffset=false; -static vec3_t desiredPelvisOffset; // this is for the root -static float ragOriginChange=0.0f; -static vec3_t ragOriginChangeDir; -//debug +static mdxaBone_t *ragBasepose[MAX_BONES_RAG]; +static mdxaBone_t *ragBaseposeInv[MAX_BONES_RAG]; +static mdxaBone_t ragBones[MAX_BONES_RAG]; +static SRagEffector ragEffectors[MAX_BONES_RAG]; +static boneInfo_t *ragBoneData[MAX_BONES_RAG]; +static int tempDependents[MAX_BONES_RAG]; +static int ragBlistIndex[MAX_BONES_RAG]; +static int numRags; +static vec3_t ragBoneMins; +static vec3_t ragBoneMaxs; +static vec3_t ragBoneCM; +static bool haveDesiredPelvisOffset = false; +static vec3_t desiredPelvisOffset; // this is for the root +static float ragOriginChange = 0.0f; +static vec3_t ragOriginChangeDir; +// debug #if 0 static vec3_t handPos={0,0,0}; static vec3_t handPos2={0,0,0}; #endif -enum ERagState -{ - ERS_DYNAMIC, - ERS_SETTLING, - ERS_SETTLED -}; -static int ragState; - -static std::vector rag; // once we get the dependents precomputed this can be local +enum ERagState { ERS_DYNAMIC, ERS_SETTLING, ERS_SETTLED }; +static int ragState; +static std::vector rag; // once we get the dependents precomputed this can be local static void G2_Generate_MatrixRag( - // caution this must not be called before the whole skeleton is "remembered" - boneInfo_v &blist, - int index) -{ + // caution this must not be called before the whole skeleton is "remembered" + boneInfo_v &blist, int index) { + boneInfo_t &bone = blist[index]; //.sent; - boneInfo_t &bone=blist[index];//.sent; - - memcpy(&bone.matrix,&bone.ragOverrideMatrix, sizeof(mdxaBone_t)); + memcpy(&bone.matrix, &bone.ragOverrideMatrix, sizeof(mdxaBone_t)); #ifdef _DEBUG - int i,j; - for (i = 0; i < 3; i++ ) - { - for (j = 0; j < 4; j++ ) - { - assert( !Q_isnan(bone.matrix.matrix[i][j])); + int i, j; + for (i = 0; i < 3; i++) { + for (j = 0; j < 4; j++) { + assert(!Q_isnan(bone.matrix.matrix[i][j])); } } -#endif// _DEBUG - memcpy(&blist[index].newMatrix,&bone.matrix, sizeof(mdxaBone_t)); +#endif // _DEBUG + memcpy(&blist[index].newMatrix, &bone.matrix, sizeof(mdxaBone_t)); } -int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); /* @@ -1299,26 +1099,23 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa aHeader = animModel->mdxa; assert(aHeader); - offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); + offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); */ // look through entire list - for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); - //skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + // skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); // if name is the same, we found it - if (!Q_stricmp(skel->name, boneName)) - { + if (!Q_stricmp(skel->name, boneName)) { return i; } } @@ -1329,82 +1126,57 @@ int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneNa return -1; } -static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - CGhoul2Info &ghoul2, - const vec3_t scale, - const vec3_t origin) -{ +static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, CGhoul2Info &ghoul2, const vec3_t scale, const vec3_t origin) { // do not change the state of the skeleton here - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; - VectorCopy(origin,bone.extraVec1); + if (index != -1) { + boneInfo_t &bone = blist[index]; + VectorCopy(origin, bone.extraVec1); - G2_GetBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.originalTrueBoneMatrix,bone.basepose,bone.baseposeInv); -// bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); - assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); - bone.originalOrigin[0]=bone.originalTrueBoneMatrix.matrix[0][3]; - bone.originalOrigin[1]=bone.originalTrueBoneMatrix.matrix[1][3]; - bone.originalOrigin[2]=bone.originalTrueBoneMatrix.matrix[2][3]; + G2_GetBoneMatrixLow(ghoul2, bone.boneNumber, scale, bone.originalTrueBoneMatrix, bone.basepose, bone.baseposeInv); + // bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); + assert(!Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); + bone.originalOrigin[0] = bone.originalTrueBoneMatrix.matrix[0][3]; + bone.originalOrigin[1] = bone.originalTrueBoneMatrix.matrix[1][3]; + bone.originalOrigin[2] = bone.originalTrueBoneMatrix.matrix[2][3]; } return index; } -static int G2_Set_Bone_Angles_Rag( - CGhoul2Info &ghoul2, - const mdxaHeader_t *mod_a, - boneInfo_v &blist, - const char *boneName, - const int flags, - const float radius, - const vec3_t angleMin=0, - const vec3_t angleMax=0, - const int blendTime=500) -{ - int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); +static int G2_Set_Bone_Angles_Rag(CGhoul2Info &ghoul2, const mdxaHeader_t *mod_a, boneInfo_v &blist, const char *boneName, const int flags, const float radius, + const vec3_t angleMin = 0, const vec3_t angleMax = 0, const int blendTime = 500) { + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(ghoul2.animModel, blist, boneName); } - if (index != -1) - { - boneInfo_t &bone=blist[index]; + if (index != -1) { + boneInfo_t &bone = blist[index]; bone.flags &= ~(BONE_ANGLES_TOTAL); bone.flags |= BONE_ANGLES_RAGDOLL; - if (flags&RAG_PCJ) - { - if (flags&RAG_PCJ_POST_MULT) - { + if (flags & RAG_PCJ) { + if (flags & RAG_PCJ_POST_MULT) { bone.flags |= BONE_ANGLES_POSTMULT; - } - else if (flags&RAG_PCJ_MODEL_ROOT) - { + } else if (flags & RAG_PCJ_MODEL_ROOT) { bone.flags |= BONE_ANGLES_PREMULT; -// bone.flags |= BONE_ANGLES_POSTMULT; - } - else - { + // bone.flags |= BONE_ANGLES_POSTMULT; + } else { assert(!"Invalid RAG PCJ\n"); } } - bone.ragStartTime=G2API_GetTime(0); + bone.ragStartTime = G2API_GetTime(0); bone.boneBlendStart = bone.ragStartTime; bone.boneBlendTime = blendTime; - bone.radius=radius; - bone.weight=1.0f; + bone.radius = radius; + bone.weight = 1.0f; - //init the others to valid values + // init the others to valid values bone.epGravFactor = 0; VectorClear(bone.epVelocity); bone.solidCount = 0; @@ -1420,48 +1192,37 @@ static int G2_Set_Bone_Angles_Rag( bone.hasOverGoal = false; bone.hasAnimFrameMatrix = -1; -// bone.weight=pow(radius,1.7f); //cubed was too harsh -// bone.weight=radius*radius*radius; - if (angleMin&&angleMax) - { - VectorCopy(angleMin,bone.minAngles); - VectorCopy(angleMax,bone.maxAngles); - } - else - { - VectorCopy(bone.currentAngles,bone.minAngles); // I guess this isn't a rag pcj then - VectorCopy(bone.currentAngles,bone.maxAngles); - } - if (!bone.lastTimeUpdated) - { - static mdxaBone_t id = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - memcpy(&bone.ragOverrideMatrix,&id, sizeof(mdxaBone_t)); + // bone.weight=pow(radius,1.7f); //cubed was too harsh + // bone.weight=radius*radius*radius; + if (angleMin && angleMax) { + VectorCopy(angleMin, bone.minAngles); + VectorCopy(angleMax, bone.maxAngles); + } else { + VectorCopy(bone.currentAngles, bone.minAngles); // I guess this isn't a rag pcj then + VectorCopy(bone.currentAngles, bone.maxAngles); + } + if (!bone.lastTimeUpdated) { + static mdxaBone_t id = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + memcpy(&bone.ragOverrideMatrix, &id, sizeof(mdxaBone_t)); VectorClear(bone.anglesOffset); VectorClear(bone.positionOffset); - VectorClear(bone.velocityEffector); // this is actually a velocity now - VectorClear(bone.velocityRoot); // this is actually a velocity now + VectorClear(bone.velocityEffector); // this is actually a velocity now + VectorClear(bone.velocityRoot); // this is actually a velocity now VectorClear(bone.lastPosition); VectorClear(bone.lastShotDir); - bone.lastContents=0; + bone.lastContents = 0; // if this is non-zero, we are in a dynamic state - bone.firstCollisionTime=bone.ragStartTime; + bone.firstCollisionTime = bone.ragStartTime; // if this is non-zero, we are in a settling state - bone.restTime=0; + bone.restTime = 0; // if they are both zero, we are in a settled state - bone.firstTime=0; + bone.firstTime = 0; - bone.RagFlags=flags; - bone.DependentRagIndexMask=0; + bone.RagFlags = flags; + bone.DependentRagIndexMask = 0; - G2_Generate_MatrixRag(blist,index); // set everything to th id + G2_Generate_MatrixRag(blist, index); // set everything to th id #if 0 VectorClear(bone.currentAngles); @@ -1469,32 +1230,25 @@ static int G2_Set_Bone_Angles_Rag( // VectorScale(bone.currentAngles,0.5f,bone.currentAngles); #else { - if ( - (flags&RAG_PCJ_MODEL_ROOT) || - (flags&RAG_PCJ_PELVIS) || - !(flags&RAG_PCJ)) - { + if ((flags & RAG_PCJ_MODEL_ROOT) || (flags & RAG_PCJ_PELVIS) || !(flags & RAG_PCJ)) { VectorClear(bone.currentAngles); - } - else - { + } else { int k; - for (k=0;k<3;k++) - { - float scalar=flrand(-1.0f,1.0f); - scalar*=flrand(-1.0f,1.0f)*flrand(-1.0f,1.0f); + for (k = 0; k < 3; k++) { + float scalar = flrand(-1.0f, 1.0f); + scalar *= flrand(-1.0f, 1.0f) * flrand(-1.0f, 1.0f); // this is a heavily central distribution // center it on .5 (and make it small) - scalar*=0.5f; - scalar+=0.5f; + scalar *= 0.5f; + scalar += 0.5f; - bone.currentAngles[k]=(bone.minAngles[k]-bone.maxAngles[k])*scalar+bone.maxAngles[k]; + bone.currentAngles[k] = (bone.minAngles[k] - bone.maxAngles[k]) * scalar + bone.maxAngles[k]; } } } // VectorClear(bone.currentAngles); #endif - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); } } return index; @@ -1503,50 +1257,43 @@ static int G2_Set_Bone_Angles_Rag( class CRagDollParams; const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2); - -static void G2_RagDollMatchPosition() -{ - haveDesiredPelvisOffset=false; +static void G2_RagDollMatchPosition() { + haveDesiredPelvisOffset = false; int i; - for (i=0;inumBones); -#else //The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list - //and let them re-set their anims/angles gameside. +#else // The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list + // and let them re-set their anims/angles gameside. int i = 0; - while (i < blist.size()) - { + while (i < blist.size()) { boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) - { + if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -1632,96 +1371,70 @@ void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V) i++; } #endif - ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED); + ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED); } -void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) -{ - if (parms) - { - parms->CallRagDollBegin=qfalse; +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V, CRagDollParams *parms) { + if (parms) { + parms->CallRagDollBegin = qfalse; } - if (!broadsword||!broadsword->integer||!parms) - { + if (!broadsword || !broadsword->integer || !parms) { return; } int model; - for (model = 0; model < ghoul2V.size(); model++) - { - if (ghoul2V[model].mModelindex != -1) - { + for (model = 0; model < ghoul2V.size(); model++) { + if (ghoul2V[model].mModelindex != -1) { break; } } - if (model==ghoul2V.size()) - { + if (model == ghoul2V.size()) { return; } - CGhoul2Info &ghoul2=ghoul2V[model]; - const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); - if (!mod_a) - { + CGhoul2Info &ghoul2 = ghoul2V[model]; + const mdxaHeader_t *mod_a = G2_GetModA(ghoul2); + if (!mod_a) { return; } - int curTime=G2API_GetTime(0); + int curTime = G2API_GetTime(0); boneInfo_v &blist = ghoul2.mBlist; - int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); - switch (parms->RagPhase) - { + int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); + switch (parms->RagPhase) { case CRagDollParams::RP_START_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING; - return; /// not doing anything with this yet + ghoul2.mFlags |= GHOUL2_RAG_PENDING; + return; /// not doing anything with this yet break; case CRagDollParams::RP_END_DEATH_ANIM: - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE; - if (broadsword_waitforshot && - broadsword_waitforshot->integer) - { - if (broadsword_waitforshot->integer==2) - { - if (!(ghoul2.mFlags&(GHOUL2_RAG_COLLISION_DURING_DEATH|GHOUL2_RAG_COLLISION_SLIDE))) - { - //nothing was encountered, lets just wait for the first shot + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE; + if (broadsword_waitforshot && broadsword_waitforshot->integer) { + if (broadsword_waitforshot->integer == 2) { + if (!(ghoul2.mFlags & (GHOUL2_RAG_COLLISION_DURING_DEATH | GHOUL2_RAG_COLLISION_SLIDE))) { + // nothing was encountered, lets just wait for the first shot return; // we ain't starting yet } - } - else - { + } else { return; // we ain't starting yet } } break; case CRagDollParams::RP_DEATH_COLLISION: - if (parms->collisionType) - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_SLIDE; + if (parms->collisionType) { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_SLIDE; + } else { + ghoul2.mFlags |= GHOUL2_RAG_COLLISION_DURING_DEATH; } - else - { - ghoul2.mFlags|=GHOUL2_RAG_COLLISION_DURING_DEATH; - } - if (broadsword_dontstopanim && broadsword_waitforshot && - (broadsword_dontstopanim->integer || broadsword_waitforshot->integer) - ) - { - if (!(ghoul2.mFlags&GHOUL2_RAG_DONE)) - { + if (broadsword_dontstopanim && broadsword_waitforshot && (broadsword_dontstopanim->integer || broadsword_waitforshot->integer)) { + if (!(ghoul2.mFlags & GHOUL2_RAG_DONE)) { return; // we ain't starting yet } } break; case CRagDollParams::RP_CORPSE_SHOT: - if (broadsword_kickorigin && - broadsword_kickorigin->integer) - { - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - //rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. + if (broadsword_kickorigin && broadsword_kickorigin->integer) { + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + // rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. /* float magicFactor14=8.0f; //64.0f; // kick strength @@ -1746,29 +1459,22 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) } break; case CRagDollParams::RP_GET_PELVIS_OFFSET: - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { VectorClear(parms->pelvisAnglesOffset); VectorClear(parms->pelvisPositionOffset); } // intentional lack of a break case CRagDollParams::RP_SET_PELVIS_OFFSET: - if (index>=0&&index<(int)blist.size()) - { - boneInfo_t &bone=blist[index]; - if (bone.boneNumber>=0) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) - { - VectorCopy(bone.anglesOffset,parms->pelvisAnglesOffset); - VectorCopy(bone.positionOffset,parms->pelvisPositionOffset); - } - else - { - VectorCopy(parms->pelvisAnglesOffset,bone.anglesOffset); - VectorCopy(parms->pelvisPositionOffset,bone.positionOffset); + if (index >= 0 && index < (int)blist.size()) { + boneInfo_t &bone = blist[index]; + if (bone.boneNumber >= 0) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (parms->RagPhase == CRagDollParams::RP_GET_PELVIS_OFFSET) { + VectorCopy(bone.anglesOffset, parms->pelvisAnglesOffset); + VectorCopy(bone.positionOffset, parms->pelvisPositionOffset); + } else { + VectorCopy(parms->pelvisAnglesOffset, bone.anglesOffset); + VectorCopy(parms->pelvisPositionOffset, bone.positionOffset); } } } @@ -1784,8 +1490,7 @@ void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) return; break; } - if (ghoul2.mFlags&GHOUL2_RAG_STARTED) - { + if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { // only going to begin ragdoll once, everything else depends on what happens to the origin return; } @@ -1796,223 +1501,216 @@ if (index>=0) } #endif - ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED; // well anyway we are going live - parms->CallRagDollBegin=qtrue; + ghoul2.mFlags |= GHOUL2_RAG_PENDING | GHOUL2_RAG_DONE | GHOUL2_RAG_STARTED; // well anyway we are going live + parms->CallRagDollBegin = qtrue; G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); - - G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"cranium",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); - //G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); - G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); - - //int startFrame = 3665, endFrame = 3665+1; + G2_Set_Bone_Rag(mod_a, blist, "model_root", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "pelvis", ghoul2, parms->scale, parms->position); + + G2_Set_Bone_Rag(mod_a, blist, "lower_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "upper_lumbar", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "thoracic", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "cranium", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhumerus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradius", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurYZ", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltibia", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rhand", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lhand", ghoul2, parms->scale, parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); + // G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rtalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ltalus", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lradiusX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "rfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "lfemurX", ghoul2, parms->scale, parms->position); + G2_Set_Bone_Rag(mod_a, blist, "ceyebrow", ghoul2, parms->scale, parms->position); + + // int startFrame = 3665, endFrame = 3665+1; int startFrame = parms->startFrame, endFrame = parms->endFrame; - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"upper_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lower_lumbar",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"Motion",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); -// G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, -// BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, -// 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rfemurYZ",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lhumerus",startFrame,endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f,curTime,float(startFrame),150,0,true); - -// should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "upper_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lower_lumbar", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "Motion", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + // G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, + // BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + // 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rfemurYZ", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "rhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a, blist, "lhumerus", startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); + + // should already be set G2_GenerateWorldMatrix(parms->angles, parms->position); G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); - static const float fRadScale = 0.3f;//0.5f; + static const float fRadScale = 0.3f; // 0.5f; - vec3_t pcjMin,pcjMax; - VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); - VectorSet(pcjMax,90.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + vec3_t pcjMin, pcjMax; + VectorSet(pcjMin, -90.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 90.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "model_root", RAG_PCJ_MODEL_ROOT | RAG_PCJ | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 100); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "pelvis", RAG_PCJ_PELVIS | RAG_PCJ | RAG_PCJ_POST_MULT | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, + 100); #if 1 // new base anim, unconscious flop - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT; //|RAG_EFFECTOR; - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,15.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); - VectorSet(pcjMax,25.0f,25.0f,25.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags | RAG_UNSNAPPABLE, 10.0f * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -25.0f, -25.0f, -25.0f); + VectorSet(pcjMax, 25.0f, 25.0f, 25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags | RAG_EFFECTOR | RAG_UNSNAPPABLE, 12.0f * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, 6.0f * fRadScale, pcjMin, pcjMax, 500); static const float sFactLeg = 1.0f; static const float sFactArm = 1.0f; static const float sRadArm = 1.0f; static const float sRadLeg = 1.0f; - VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); - VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorSet(pcjMin, -100.0f, -40.0f, -15.0f); + VectorSet(pcjMax, -15.0f, 80.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); - VectorSet(pcjMax,15.0f,40.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); + VectorSet(pcjMin, -50.0f, -80.0f, -15.0f); + VectorSet(pcjMax, 15.0f, 40.0f, 15.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT | RAG_UNSNAPPABLE, (4.0f * sRadArm) * fRadScale, pcjMin, pcjMax, + 500); - VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); - VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorSet(pcjMin, -25.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 90.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,30.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 20.0f, -20.0f); VectorScale(pcjMin, sFactArm, pcjMin); VectorScale(pcjMax, sFactArm, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, (3.0f * sRadArm) * fRadScale, pcjMin, pcjMax, 500); - - VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); - VectorSet(pcjMax,30.0f,5.0f,20.0f); + VectorSet(pcjMin, -80.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 30.0f, 5.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -60.0f, -5.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,100.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 100.0f, 15.0f, 15.0f); VectorScale(pcjMin, sFactLeg, pcjMin); VectorScale(pcjMax, sFactLeg, pcjMax); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadLeg) * fRadScale, pcjMin, pcjMax, 500); #else // old base anim - int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); - VectorSet(pcjMax,45.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); - VectorSet(pcjMax,45.0f,45.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags,10.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); - VectorSet(pcjMax,10.0f,10.0f,90.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,60.0f,45.0f); - VectorSet(pcjMax,180.0f,180.0f,45.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - //VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); - VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); - //VectorSet(pcjMax,60.0f,90.0f,100.0f); - VectorSet(pcjMax,180.0f,180.0f,100.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + int pcjflags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + VectorSet(pcjMin, -15.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 45.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lower_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "upper_lumbar", pcjflags, 10.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -45.0f, -45.0f, -45.0f); + VectorSet(pcjMax, 45.0f, 45.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "thoracic", pcjflags, 10.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -10.0f, -10.0f, -90.0f); + VectorSet(pcjMax, 10.0f, 10.0f, 90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "cranium", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,60.0f,45.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + // VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); + VectorSet(pcjMin, -180.0f, -180.0f, -100.0f); + // VectorSet(pcjMax,60.0f,90.0f,100.0f); + VectorSet(pcjMax, 180.0f, 180.0f, 100.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhumerus", pcjflags | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); //-120/120 - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); - VectorSet(pcjMax,5.0f,20.0f,-20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); - - VectorSet(pcjMin,-90.0f,-50.0f,-20.0f); - VectorSet(pcjMax,50.0f,20.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); - VectorSet(pcjMax,50.0f,50.0f,20.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); - - //120 - VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); - VectorSet(pcjMin,20.0f,-15.0f,-15.0f); - VectorSet(pcjMax,120.0f,15.0f,15.0f); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -120.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 5.0f, 20.0f, -20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradius", pcjflags | RAG_BONE_LIGHTWEIGHT, 3.0f, pcjMin, pcjMax, 500); + + VectorSet(pcjMin, -90.0f, -50.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 20.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, -90.0f, -20.0f, -20.0f); + VectorSet(pcjMax, 50.0f, 50.0f, 20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurYZ", pcjflags | RAG_BONE_LIGHTWEIGHT, 6.0f, pcjMin, pcjMax, 500); + + // 120 + VectorSet(pcjMin, -20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); + VectorSet(pcjMin, 20.0f, -15.0f, -15.0f); + VectorSet(pcjMax, 120.0f, 15.0f, 15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltibia", pcjflags | RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 4.0f, pcjMin, pcjMax, 500); #endif - float sRadEArm = 1.2f; float sRadELeg = 1.2f; -// int rhand= - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); -// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); - //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); - G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,5.0f); -//match the currrent animation - if (!G2_RagDollSetup(ghoul2,curTime,true,parms->position,false)) - { + // int rhand= + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lhand", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rtalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ltalus", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (4.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lradiusX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (6.0f * sRadEArm) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "rfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "lfemurX", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, (10.0f * sRadELeg) * fRadScale); + // G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a, blist, "ceyebrow", RAG_EFFECTOR | RAG_BONE_LIGHTWEIGHT, 5.0f); + // match the currrent animation + if (!G2_RagDollSetup(ghoul2, curTime, true, parms->position, false)) { assert(!"failed to add any rag bones"); return; } - G2_RagDollCurrentPosition(ghoul2V,model,curTime,parms->angles,parms->position,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, parms->position, parms->scale); #if 0 if (rhand>0) { @@ -2032,7 +1730,7 @@ if (index>=0) fparms.me = parms->me; fparms.settleFrame = parms->endFrame; - //Guess I don't need to do this, do I? + // Guess I don't need to do this, do I? G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); vec3_t dPos; @@ -2041,49 +1739,40 @@ if (index>=0) dPos[2] -= 6; #endif - for (k=0;kangles,dPos,parms->scale); + G2_RagDollCurrentPosition(ghoul2V, model, curTime, parms->angles, dPos, parms->scale); G2_RagDollMatchPosition(); - G2_RagDollSolve(ghoul2V,model,1.0f*(1.0f-k/40.0f),curTime,dPos,false); + G2_RagDollSolve(ghoul2V, model, 1.0f * (1.0f - k / 40.0f), curTime, dPos, false); } } -void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t hit) -{ - if (!broadsword||!broadsword->integer) - { +void G2_SetRagDollBullet(CGhoul2Info &ghoul2, const vec3_t rayStart, const vec3_t hit) { + if (!broadsword || !broadsword->integer) { return; } vec3_t shotDir; - VectorSubtract(hit,rayStart,shotDir); - float len=VectorLength(shotDir); - if (len<1.0f) - { + VectorSubtract(hit, rayStart, shotDir); + float len = VectorLength(shotDir); + if (len < 1.0f) { return; } - float lenr=1.0f/len; - shotDir[0]*=lenr; - shotDir[1]*=lenr; - shotDir[2]*=lenr; + float lenr = 1.0f / len; + shotDir[0] *= lenr; + shotDir[1] *= lenr; + shotDir[2] *= lenr; - bool firstOne=false; - if (broadsword_kickbones&&broadsword_kickbones->integer) - { - int magicFactor13=150.0f; // squared radius multiplier for shot effects + bool firstOne = false; + if (broadsword_kickbones && broadsword_kickbones->integer) { + int magicFactor13 = 150.0f; // squared radius multiplier for shot effects boneInfo_v &blist = ghoul2.mBlist; - for(int i=(int)(blist.size()-1);i>=0;i--) - { - boneInfo_t &bone=blist[i]; - if ((bone.flags & BONE_ANGLES_TOTAL)) - { - if (bone.flags & BONE_ANGLES_RAGDOLL) - { - if (!firstOne) - { - firstOne=true; + for (int i = (int)(blist.size() - 1); i >= 0; i--) { + boneInfo_t &bone = blist[i]; + if ((bone.flags & BONE_ANGLES_TOTAL)) { + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (!firstOne) { + firstOne = true; #if 0 int curTime=G2API_GetTime(0); const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); @@ -2126,229 +1815,174 @@ void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t #endif } - VectorCopy(shotDir,bone.lastShotDir); + VectorCopy(shotDir, bone.lastShotDir); vec3_t dir; - VectorSubtract(bone.lastPosition,hit,dir); - len=VectorLength(dir); - if (len<1.0f) - { - len=1.0f; + VectorSubtract(bone.lastPosition, hit, dir); + len = VectorLength(dir); + if (len < 1.0f) { + len = 1.0f; } - lenr=1.0f/len; - float effect=lenr; - effect*=magicFactor13*effect; // this is cubed, one of them is absorbed by the next calc - bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f)); - bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f)); -// bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); -// bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); - assert( !Q_isnan(shotDir[2])); - // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); - // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + lenr = 1.0f / len; + float effect = lenr; + effect *= magicFactor13 * effect; // this is cubed, one of them is absorbed by the next calc + bone.velocityEffector[0] = shotDir[0] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[1] = shotDir[1] * (effect + flrand(0.0f, 0.05f)); + bone.velocityEffector[2] = fabs(shotDir[2]) * (effect + flrand(0.0f, 0.05f)); + // bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + // bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + assert(!Q_isnan(shotDir[2])); + // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); // go dynamic - bone.firstCollisionTime=G2API_GetTime(0); -// bone.firstCollisionTime=0; - bone.restTime=0; + bone.firstCollisionTime = G2API_GetTime(0); + // bone.firstCollisionTime=0; + bone.restTime = 0; } } } } } +static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone, int frameNum, const vec3_t origin, bool &resetOrigin) { + ragOriginChange = DistanceSquared(origin, bone.extraVec1); + VectorSubtract(origin, bone.extraVec1, ragOriginChangeDir); -static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone,int frameNum,const vec3_t origin,bool &resetOrigin) -{ - ragOriginChange=DistanceSquared(origin,bone.extraVec1); - VectorSubtract(origin,bone.extraVec1,ragOriginChangeDir); - - float decay=1.0f; + float decay = 1.0f; - int dynamicTime=1000; - int settleTime=1000; + int dynamicTime = 1000; + int settleTime = 1000; - if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } - } - else if (bone.firstCollisionTime>0) - { - ragState=ERS_DYNAMIC; - if (frameNum>bone.firstCollisionTime+dynamicTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { //if we moved, or if this bone is still in solid - bone.firstCollisionTime=frameNum; - } - else - { + } else if (bone.firstCollisionTime > 0) { + ragState = ERS_DYNAMIC; + if (frameNum > bone.firstCollisionTime + dynamicTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { // if we moved, or if this bone is still in solid + bone.firstCollisionTime = frameNum; + } else { // settle out - bone.firstCollisionTime=0; - bone.restTime=frameNum; - ragState=ERS_SETTLING; + bone.firstCollisionTime = 0; + bone.restTime = frameNum; + ragState = ERS_SETTLING; } } -//decay=0.0f; - } - else if (bone.restTime>0) - { - decay=1.0f-(frameNum-bone.restTime)/float(dynamicTime); - if (decay<0.0f) - { - decay=0.0f; - } - if (decay>1.0f) - { - decay=1.0f; - } - float magicFactor8=1.0f; // Power for decay - decay=pow(decay,magicFactor8); - ragState=ERS_SETTLING; - if (frameNum>bone.restTime+settleTime) - { - VectorCopy(origin,bone.extraVec1); - if (ragOriginChange>15.0f) - { - bone.restTime=frameNum; - } - else - { + // decay=0.0f; + } else if (bone.restTime > 0) { + decay = 1.0f - (frameNum - bone.restTime) / float(dynamicTime); + if (decay < 0.0f) { + decay = 0.0f; + } + if (decay > 1.0f) { + decay = 1.0f; + } + float magicFactor8 = 1.0f; // Power for decay + decay = pow(decay, magicFactor8); + ragState = ERS_SETTLING; + if (frameNum > bone.restTime + settleTime) { + VectorCopy(origin, bone.extraVec1); + if (ragOriginChange > 15.0f) { + bone.restTime = frameNum; + } else { // stop - bone.restTime=0; - ragState=ERS_SETTLED; + bone.restTime = 0; + ragState = ERS_SETTLED; } } -//decay=0.0f; - } - else - { - if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else if (ragOriginChange>15.0f) - { - bone.firstCollisionTime=frameNum; - ragState=ERS_DYNAMIC; - } - else - { - ragState=ERS_SETTLED; - } - decay=0.0f; - } -// ragState=ERS_SETTLED; -// decay=0.0f; + // decay=0.0f; + } else { + if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else if (ragOriginChange > 15.0f) { + bone.firstCollisionTime = frameNum; + ragState = ERS_DYNAMIC; + } else { + ragState = ERS_SETTLED; + } + decay = 0.0f; + } + // ragState=ERS_SETTLED; + // decay=0.0f; return decay; } -static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered) -{ - int minSurvivingBone=10000; - //int minSurvivingBoneAt=-1; - int minSurvivingBoneAlt=10000; - //int minSurvivingBoneAtAlt=-1; +static bool G2_RagDollSetup(CGhoul2Info &ghoul2, int frameNum, bool resetOrigin, const vec3_t origin, bool anyRendered) { + int minSurvivingBone = 10000; + // int minSurvivingBoneAt=-1; + int minSurvivingBoneAlt = 10000; + // int minSurvivingBoneAtAlt=-1; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; rag.clear(); - int numRendered=0; - int numNotRendered=0; - //int pelvisAt=-1; - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if ((bone.flags & BONE_ANGLES_RAGDOLL) || (bone.flags & BONE_ANGLES_IK)) { + // rww - this was (!anyRendered) before. Isn't that wrong? (if anyRendered, then wasRendered should be true) + bool wasRendered = (!anyRendered) || // offscreeen or something + G2_WasBoneRendered(ghoul2, bone.boneNumber); + if (!wasRendered) { + bone.RagFlags |= RAG_WAS_NOT_RENDERED; numNotRendered++; - } - else - { - bone.RagFlags&=~RAG_WAS_NOT_RENDERED; - bone.RagFlags|=RAG_WAS_EVER_RENDERED; + } else { + bone.RagFlags &= ~RAG_WAS_NOT_RENDERED; + bone.RagFlags |= RAG_WAS_EVER_RENDERED; numRendered++; } - if (bone.RagFlags&RAG_PCJ_PELVIS) - { - //pelvisAt=i; - } - else if (bone.RagFlags&RAG_PCJ_MODEL_ROOT) - { - } - else if (wasRendered && (bone.RagFlags&RAG_PCJ)) - { - if (minSurvivingBone>bone.boneNumber) - { - minSurvivingBone=bone.boneNumber; - //minSurvivingBoneAt=i; + if (bone.RagFlags & RAG_PCJ_PELVIS) { + // pelvisAt=i; + } else if (bone.RagFlags & RAG_PCJ_MODEL_ROOT) { + } else if (wasRendered && (bone.RagFlags & RAG_PCJ)) { + if (minSurvivingBone > bone.boneNumber) { + minSurvivingBone = bone.boneNumber; + // minSurvivingBoneAt=i; } - } - else if (wasRendered) - { - if (minSurvivingBoneAlt>bone.boneNumber) - { - minSurvivingBoneAlt=bone.boneNumber; - //minSurvivingBoneAtAlt=i; + } else if (wasRendered) { + if (minSurvivingBoneAlt > bone.boneNumber) { + minSurvivingBoneAlt = bone.boneNumber; + // minSurvivingBoneAtAlt=i; } } - if ( - anyRendered && - (bone.RagFlags&RAG_WAS_EVER_RENDERED) && - !(bone.RagFlags&RAG_PCJ_MODEL_ROOT) && - !(bone.RagFlags&RAG_PCJ_PELVIS) && - !wasRendered && - (bone.RagFlags&RAG_EFFECTOR) - ) - { + if (anyRendered && (bone.RagFlags & RAG_WAS_EVER_RENDERED) && !(bone.RagFlags & RAG_PCJ_MODEL_ROOT) && !(bone.RagFlags & RAG_PCJ_PELVIS) && + !wasRendered && (bone.RagFlags & RAG_EFFECTOR)) { // this thing was rendered in the past, but wasn't now, although other bones were, lets get rid of it -// bone.flags &= ~BONE_ANGLES_RAGDOLL; -// bone.RagFlags = 0; -//Com_OPrintf("Deleted Effector %d\n",i); -// continue; + // bone.flags &= ~BONE_ANGLES_RAGDOLL; + // bone.RagFlags = 0; + // Com_OPrintf("Deleted Effector %d\n",i); + // continue; } - if ((int)rag.size()=0); - assert(numRags= 0); + assert(numRags < MAX_BONES_RAG); + + // ragStartTime=bone.ragStartTime; + + bone.ragIndex = numRags; + ragBoneData[numRags] = &bone; + ragEffectors[numRags].radius = bone.radius; + ragEffectors[numRags].weight = bone.weight; + G2_GetBoneBasepose(ghoul2, bone.boneNumber, bone.basepose, bone.baseposeInv); numRags++; } } - if (!numRags) - { + if (!numRags) { return false; } return true; } -static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params, int curTime) -{ - if (!broadsword||!broadsword->integer) - { +static void G2_RagDoll(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params, int curTime) { + if (!broadsword || !broadsword->integer) { return; } - if (!params) - { + if (!params) { assert(0); return; } @@ -2431,9 +2059,9 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * dPos[2] -= 6; #endif -// params->DebugLine(handPos,handPos2,false); - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + // params->DebugLine(handPos,handPos2,false); + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; @@ -2470,24 +2098,20 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; // this loop checks for settled - for(size_t i=0; i=0) - { - assert(bone.boneNumber= 0) { + assert(bone.boneNumber < MAX_BONES_RAG); + if (bone.flags & BONE_ANGLES_RAGDOLL) { // check for state transitions - decay=G2_RagSetState(ghoul2,bone,frameNum,dPos,resetOrigin); // set the current state + decay = G2_RagSetState(ghoul2, bone, frameNum, dPos, resetOrigin); // set the current state - if (ragState==ERS_SETTLED) - { + if (ragState == ERS_SETTLED) { #if 0 bool noneInSolid = true; @@ -2517,37 +2141,31 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * return; #endif } - if (G2_WasBoneRendered(ghoul2,bone.boneNumber)) - { - anyRendered=true; + if (G2_WasBoneRendered(ghoul2, bone.boneNumber)) { + anyRendered = true; break; } } } } - //int iters=(ragState==ERS_DYNAMIC)?2:1; - int iters=(ragState==ERS_DYNAMIC)?4:2; - //bool kicked=false; - if (ragOriginChangeDir[2]<-100.0f) - { - //kicked=true; - //iters*=8; - iters*=2; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) + // int iters=(ragState==ERS_DYNAMIC)?2:1; + int iters = (ragState == ERS_DYNAMIC) ? 4 : 2; + // bool kicked=false; + if (ragOriginChangeDir[2] < -100.0f) { + // kicked=true; + // iters*=8; + iters *= 2; // rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) } - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,dPos,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, dPos, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (int i=0;iangles,dPos,params->scale); + for (int i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, dPos, params->scale); - if (G2_RagDollSettlePositionNumeroTrois(ghoul2V,dPos,params,curTime)) - { + if (G2_RagDollSettlePositionNumeroTrois(ghoul2V, dPos, params, curTime)) { #if 0 //effectors are start solid alot, so this was pretty extreme if (!kicked&&iters<4) @@ -2558,13 +2176,12 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * } #endif } - //params->position[2] += 16; - G2_RagDollSolve(ghoul2V,g2Index,decay*2.0f,frameNum,dPos,true,params); + // params->position[2] += 16; + G2_RagDollSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, dPos, true, params); } } - if (params->me != ENTITYNUM_NONE) - { + if (params->me != ENTITYNUM_NONE) { #if 0 vec3_t worldMins,worldMaxs; worldMins[0]=params->position[0]-17; @@ -2576,11 +2193,11 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * //Com_OPrintf(va("%f \n",worldMins[2]); // params->DebugLine(worldMins,worldMaxs,true); #endif - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); -// SV_UnlinkEntity(params->me); -// params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); -// params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); -// SV_LinkEntity(params->me); + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); + // SV_UnlinkEntity(params->me); + // params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); + // params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); + // SV_LinkEntity(params->me); } } @@ -2588,19 +2205,16 @@ static void G2_RagDoll(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams * #define _DEBUG_BONE_NAMES #endif -static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) -{ - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); +static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); // look through entire list - for(size_t i=0; iragBoneMaxs[k]) - { - ragBoneMaxs[k]=ragEffectors[i].currentOrigin[k]; + ragBoneCM[k] = ragEffectors[i].currentOrigin[k] * cmweight; + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; + ragBoneMins[k] = ragEffectors[i].currentOrigin[k]; + } else { + ragBoneCM[k] += ragEffectors[i].currentOrigin[k] * ragEffectors[i].weight; + if (ragEffectors[i].currentOrigin[k] > ragBoneMaxs[k]) { + ragBoneMaxs[k] = ragEffectors[i].currentOrigin[k]; } - if (ragEffectors[i].currentOrigin[k]0.0f); + assert(totalWt > 0.0f); int k; { - float wtInv=1.0f/totalWt; - for (k=0;k<3;k++) - { - ragBoneMaxs[k]-=position[k]; - ragBoneMins[k]-=position[k]; - ragBoneMaxs[k]+=10.0f; - ragBoneMins[k]-=10.0f; - ragBoneCM[k]*=wtInv; + float wtInv = 1.0f / totalWt; + for (k = 0; k < 3; k++) { + ragBoneMaxs[k] -= position[k]; + ragBoneMins[k] -= position[k]; + ragBoneMaxs[k] += 10.0f; + ragBoneMins[k] -= 10.0f; + ragBoneCM[k] *= wtInv; - ragBoneCM[k]=ragEffectors[0].currentOrigin[k]; // use the pelvis + ragBoneCM[k] = ragEffectors[0].currentOrigin[k]; // use the pelvis } } } @@ -2690,13 +2295,12 @@ int ragSSCount = 0; int ragTraceCount = 0; #endif -void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) -{ +void Rag_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, + const EG2_Collision eG2TraceType, const int useLod) { #ifdef _DEBUG int ragPreTrace = ri.Milliseconds(); #endif - if ( ri.CGVMLoaded() ) - { + if (ri.CGVMLoaded()) { ragCallbackTraceLine_t *callData = (ragCallbackTraceLine_t *)ri.GetSharedMemory(); VectorCopy(start, callData->start); @@ -2706,14 +2310,12 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v callData->ignore = passEntityNum; callData->mask = contentmask; - ri.CGVM_RagCallback( RAG_CALLBACK_TRACELINE ); + ri.CGVM_RagCallback(RAG_CALLBACK_TRACELINE); *results = callData->tr; - } - else - { + } else { results->entityNum = ENTITYNUM_NONE; - //SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); + // SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); ri.CM_BoxTrace(results, start, end, mins, maxs, 0, contentmask, 0); results->entityNum = results->fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; } @@ -2722,39 +2324,35 @@ void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const v int ragPostTrace = ri.Milliseconds(); ragTraceTime += (ragPostTrace - ragPreTrace); - if (results->startsolid) - { + if (results->startsolid) { ragSSCount++; } ragTraceCount++; #endif } -//run advanced physics on each bone indivudually -//an adaption of my "exphys" custom game physics model -#define MAX_GRAVITY_PULL 256//512 +// run advanced physics on each bone indivudually +// an adaption of my "exphys" custom game physics model +#define MAX_GRAVITY_PULL 256 // 512 -static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) -{ +static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) { trace_t tr; vec3_t gSpot; VectorCopy(org, gSpot); - gSpot[2] -= 1.0f; //seems reasonable to me + gSpot[2] -= 1.0f; // seems reasonable to me Rag_Trace(&tr, org, mins, maxs, gSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) - { //not in solid, and hit something. Guess it's ground. + if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) { // not in solid, and hit something. Guess it's ground. return true; } return false; } -static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, const vec3_t testMaxs, - const float gravity, const float mass, const float bounce) -{ +static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, + const vec3_t testMaxs, const float gravity, const float mass, const float bounce) { trace_t tr; vec3_t projectedOrigin; vec3_t vNorm; @@ -2765,68 +2363,54 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR assert(mass <= 1.0f && mass >= 0.01f); - if (bone.physicsSettled) - { //then we have no need to continue + if (bone.physicsSettled) { // then we have no need to continue return true; } - if (gravity) - { //factor it in before we do anything. + if (gravity) { // factor it in before we do anything. VectorCopy(e.currentOrigin, ground); ground[2] -= 1.0f; Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, ground, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.entityNum == ENTITYNUM_NONE) - { + if (tr.entityNum == ENTITYNUM_NONE) { boneOnGround = false; - } - else - { + } else { boneOnGround = true; } - if (!boneOnGround) - { - if (!params->velocity[2]) - { //only increase gravitational pull once the actual entity is still + if (!boneOnGround) { + if (!params->velocity[2]) { // only increase gravitational pull once the actual entity is still bone.epGravFactor += gravity; } - if (bone.epGravFactor > MAX_GRAVITY_PULL) - { //cap it off if needed + if (bone.epGravFactor > MAX_GRAVITY_PULL) { // cap it off if needed bone.epGravFactor = MAX_GRAVITY_PULL; } bone.epVelocity[2] -= bone.epGravFactor; - } - else - { //if we're sitting on something then reset the gravity factor. + } else { // if we're sitting on something then reset the gravity factor. bone.epGravFactor = 0; } - } - else - { + } else { boneOnGround = G2_BoneOnGround(e.currentOrigin, testMins, testMaxs, params->me); } - if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) - { //nothing to do if we have no velocity even after gravity. + if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) { // nothing to do if we have no velocity even after gravity. VectorCopy(e.currentOrigin, goalSpot); return true; } - //get the projected origin based on velocity. + // get the projected origin based on velocity. VectorMA(e.currentOrigin, velScaling, bone.epVelocity, projectedOrigin); - //scale it down based on mass - VectorScale(bone.epVelocity, 1.0f-mass, bone.epVelocity); + // scale it down based on mass + VectorScale(bone.epVelocity, 1.0f - mass, bone.epVelocity); VectorCopy(bone.epVelocity, vNorm); vTotal = VectorNormalize(vNorm); - if (vTotal < 1 && boneOnGround) - { //we've pretty much stopped moving anyway, just clear it out then. + if (vTotal < 1 && boneOnGround) { // we've pretty much stopped moving anyway, just clear it out then. VectorClear(bone.epVelocity); bone.epGravFactor = 0; VectorCopy(e.currentOrigin, goalSpot); @@ -2835,52 +2419,44 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, projectedOrigin, params->me, RAG_MASK, G2_NOCOLLIDE, 0); - if (tr.startsolid || tr.allsolid) - { //can't go anywhere from here + if (tr.startsolid || tr.allsolid) { // can't go anywhere from here return false; } - //Go ahead and set it to the trace endpoint regardless of what it hit + // Go ahead and set it to the trace endpoint regardless of what it hit VectorCopy(tr.endpos, goalSpot); - if (tr.fraction == 1.0f) - { //Nothing was in the way. + if (tr.fraction == 1.0f) { // Nothing was in the way. return true; } - if (bounce) - { - vTotal *= bounce; //scale it by bounce + if (bounce) { + vTotal *= bounce; // scale it by bounce - VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + VectorScale(tr.plane.normal, vTotal, vNorm); // scale the trace plane normal by the bounce factor - if (vNorm[2] > 0) - { - bone.epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. - if (bone.epGravFactor < 0) - { + if (vNorm[2] > 0) { + bone.epGravFactor -= vNorm[2] * (1.0f - mass); // The lighter it is the more gravity will be reduced by bouncing vertically. + if (bone.epGravFactor < 0) { bone.epGravFactor = 0; } } - VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); //add it into the existing velocity. + VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); // add it into the existing velocity. - //I suppose it could be sort of neat to make a game callback here to actual do stuff - //when bones slam into things. But it could be slow too. + // I suppose it could be sort of neat to make a game callback here to actual do stuff + // when bones slam into things. But it could be slow too. /* if (tr.entityNum != ENTITYNUM_NONE && ent->touch) { //then call the touch function ent->touch(ent, &g_entities[tr.entityNum], &tr); } */ - } - else - { //if no bounce, kill when it hits something. + } else { // if no bounce, kill when it hits something. bone.epVelocity[0] = 0; bone.epVelocity[1] = 0; - if (!gravity) - { + if (!gravity) { bone.epVelocity[2] = 0; } } @@ -2888,9 +2464,8 @@ static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CR } #ifdef _DEBUG_BONE_NAMES -static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) -{ - if ( !ri.CGVMLoaded() ) +static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) { + if (!ri.CGVMLoaded()) return; ragCallbackDebugBox_t *callData = (ragCallbackDebugBox_t *)ri.GetSharedMemory(); @@ -2899,12 +2474,11 @@ static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) VectorCopy(mins, callData->mins); VectorCopy(maxs, callData->maxs); - ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGBOX ); + ri.CGVM_RagCallback(RAG_CALLBACK_DEBUGBOX); } -static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) -{ - if ( !ri.CGVMLoaded() ) +static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) { + if (!ri.CGVMLoaded()) return; ragCallbackDebugLine_t *callData = (ragCallbackDebugLine_t *)ri.GetSharedMemory(); @@ -2915,338 +2489,286 @@ static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color callData->color = color; callData->radius = radius; - ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGLINE ); + ri.CGVM_RagCallback(RAG_CALLBACK_DEBUGLINE); } #endif #ifdef _OLD_STYLE_SETTLE -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ - haveDesiredPelvisOffset=false; +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) { + haveDesiredPelvisOffset = false; vec3_t desiredPos; int i; assert(params); - //assert(params->me); //no longer valid, because me is an index! - int ignoreNum=params->me; + // assert(params->me); //no longer valid, because me is an index! + int ignoreNum = params->me; - bool anyStartSolid=false; + bool anyStartSolid = false; - vec3_t groundSpot={0,0,0}; + vec3_t groundSpot = {0, 0, 0}; // lets find the floor at our quake origin { vec3_t testStart; - VectorCopy(currentOrg,testStart); //last arg is dest + VectorCopy(currentOrg, testStart); // last arg is dest vec3_t testEnd; - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]-=200.0f; + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] -= 200.0f; vec3_t testMins; vec3_t testMaxs; - VectorSet(testMins,-10,-10,-10); - VectorSet(testMaxs,10,10,10); - - { - trace_t tr; - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0/*SV_TRACE_NO_PLAYER*/); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); - } - if (tr.startsolid) - { - //hmmm, punt - VectorCopy(currentOrg,groundSpot); //last arg is dest - groundSpot[2]-=30.0f; + VectorSet(testMins, -10, -10, -10); + VectorSet(testMaxs, 10, 10, 10); + + { + trace_t tr; + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0 /*SV_TRACE_NO_PLAYER*/); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - else - { - VectorCopy(tr.endpos,groundSpot); //last arg is dest + if (tr.startsolid) { + // hmmm, punt + VectorCopy(currentOrg, groundSpot); // last arg is dest + groundSpot[2] -= 30.0f; + } else { + VectorCopy(tr.endpos, groundSpot); // last arg is dest } } } - for (i=0;i groundSpot[2]) - { - testStart[2]=groundSpot[2]+(e.radius-10.0f); - } - else - { + if (e.currentOrigin[2] > groundSpot[2]) { + testStart[2] = groundSpot[2] + (e.radius - 10.0f); + } else { // lets try higher - testStart[2]=groundSpot[2]+8.0f; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + testStart[2] = groundSpot[2] + 8.0f; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } } - } - if (tr.startsolid) - { - iAmStartSolid=true; - anyStartSolid=true; + if (tr.startsolid) { + iAmStartSolid = true; + anyStartSolid = true; // above the origin, so lets slide away - if (e.currentOrigin[2] > groundSpot[2]) - { - if (params) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + if (e.currentOrigin[2] > groundSpot[2]) { + if (params) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } + } else { + // harumph, we are really screwed } - else - { - //harumph, we are really screwed - } - } - else - { - vertEffectorTraceFraction=tr.fraction; - if (params && - vertEffectorTraceFraction < .95f && - fabsf(tr.plane.normal[2]) < .707f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + } else { + vertEffectorTraceFraction = tr.fraction; + if (params && vertEffectorTraceFraction < .95f && fabsf(tr.plane.normal[2]) < .707f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } } } vec3_t effectorGroundSpot; - VectorAdvance(testStart,vertEffectorTraceFraction,testEnd,effectorGroundSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorAdvance(testStart, vertEffectorTraceFraction, testEnd, effectorGroundSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // trace from the quake origin horzontally to the effector // gonna choose the maximum of the ground spot or the effector location // and clamp it to be roughly in the bbox - VectorCopy(groundSpot,testStart); //last arg is dest - if (iAmStartSolid) - { + VectorCopy(groundSpot, testStart); // last arg is dest + if (iAmStartSolid) { // we don't have a meaningful ground spot - VectorCopy(e.currentOrigin,testEnd); //last arg is dest + VectorCopy(e.currentOrigin, testEnd); // last arg is dest bone.solidCount++; - } - else - { - VectorCopy(effectorGroundSpot,testEnd); //last arg is dest + } else { + VectorCopy(effectorGroundSpot, testEnd); // last arg is dest bone.solidCount = 0; } - assert( !Q_isnan(testStart[1])); - assert( !Q_isnan(testEnd[1])); - assert( !Q_isnan(testMins[1])); - assert( !Q_isnan(testMaxs[1])); + assert(!Q_isnan(testStart[1])); + assert(!Q_isnan(testEnd[1])); + assert(!Q_isnan(testMins[1])); + assert(!Q_isnan(testMaxs[1])); float ztest; - if (testEnd[2]>testStart[2]) - { - ztest=testEnd[2]; - } - else - { - ztest=testStart[2]; + if (testEnd[2] > testStart[2]) { + ztest = testEnd[2]; + } else { + ztest = testStart[2]; } - if (ztest c := (1-t)a+tb + float magicFactor44 = 1.0f; // going to trace a bit longer, this also serves as an expansion parameter + VectorAdvance(testStart, magicFactor44, testEnd, testEnd); // VA(a,t,b,c)-> c := (1-t)a+tb - float horzontalTraceFraction=0.0f; - vec3_t HorizontalHitSpot={0,0,0}; + float horzontalTraceFraction = 0.0f; + vec3_t HorizontalHitSpot = {0, 0, 0}; { - trace_t tr; - Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + trace_t tr; + Rag_Trace(&tr, testStart, testMins, testMaxs, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (tr.startsolid) - { - horzontalTraceFraction=1.0f; + horzontalTraceFraction = tr.fraction; + if (tr.startsolid) { + horzontalTraceFraction = 1.0f; // punt - VectorCopy(e.currentOrigin,HorizontalHitSpot); - } - else - { - VectorCopy(tr.endpos,HorizontalHitSpot); - int magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall - //rww - An..int? - VectorAdvance(tr.endpos,magicFactor46,testStart,HorizontalHitSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(e.currentOrigin, HorizontalHitSpot); + } else { + VectorCopy(tr.endpos, HorizontalHitSpot); + int magicFactor46 = 0.98f; // shorten percetage to make sure we can go down along a wall + // float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + // rww - An..int? + VectorAdvance(tr.endpos, magicFactor46, testStart, HorizontalHitSpot); // VA(a,t,b,c)-> c := (1-t)a+tb // roughly speaking this is a wall - if (horzontalTraceFraction<0.9f) - { + if (horzontalTraceFraction < 0.9f) { // roughly speaking this is a wall - if (fabsf(tr.plane.normal[2])<0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + if (fabsf(tr.plane.normal[2]) < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } - } - else if (!iAmStartSolid && - effectorGroundSpot[2] < groundSpot[2] - 8.0f) - { + } else if (!iAmStartSolid && effectorGroundSpot[2] < groundSpot[2] - 8.0f) { // this is a situation where we have something dangling below the pelvis, we want to find the plane going downhill away from the origin // for various reasons, without this correction the body will actually move away from places it can fall off. - //gotta run the trace backwards to get a plane + // gotta run the trace backwards to get a plane { - trace_t tr; - VectorCopy(effectorGroundSpot,testStart); - VectorCopy(groundSpot,testEnd); + trace_t tr; + VectorCopy(effectorGroundSpot, testStart); + VectorCopy(groundSpot, testEnd); // this can be a line trace, we just want the plane normal - Rag_Trace(&tr,testEnd,0,0,testStart,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + Rag_Trace(&tr, testEnd, 0, 0, testStart, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - horzontalTraceFraction=tr.fraction; - if (!tr.startsolid && tr.fraction< 0.7f) - { - //SRagDollEffectorCollision args(e.currentOrigin,tr); - //args.useTracePlane=true; - //params->EffectorCollision(args); - if ( ri.CGVMLoaded() ) - { //make a callback and see if the cgame wants to help us out + horzontalTraceFraction = tr.fraction; + if (!tr.startsolid && tr.fraction < 0.7f) { + // SRagDollEffectorCollision args(e.currentOrigin,tr); + // args.useTracePlane=true; + // params->EffectorCollision(args); + if (ri.CGVMLoaded()) { // make a callback and see if the cgame wants to help us out ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); VectorCopy(e.currentOrigin, callData->bonePos); callData->entNum = params->me; callData->solidCount = bone.solidCount; - ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONEINSOLID); } } } } } } - vec3_t goalSpot={0,0,0}; + vec3_t goalSpot = {0, 0, 0}; // now lets trace down - VectorCopy(HorizontalHitSpot,testStart); - VectorCopy(testStart,testEnd); //last arg is dest - testEnd[2]=e.currentOrigin[2]-30.0f; - { - trace_t tr; - Rag_Trace(&tr,testStart,NULL,NULL,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); - if (tr.entityNum==0) - { - VectorAdvance(testStart,.5f,testEnd,tr.endpos); + VectorCopy(HorizontalHitSpot, testStart); + VectorCopy(testStart, testEnd); // last arg is dest + testEnd[2] = e.currentOrigin[2] - 30.0f; + { + trace_t tr; + Rag_Trace(&tr, testStart, NULL, NULL, testEnd, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + if (tr.entityNum == 0) { + VectorAdvance(testStart, .5f, testEnd, tr.endpos); } - if (tr.startsolid) - { + if (tr.startsolid) { // punt, go to the origin I guess - VectorCopy(currentOrg,goalSpot); - } - else - { - VectorCopy(tr.endpos,goalSpot); - int magicFactor47=0.5f; // shorten percentage to make sure we can go down along a wall - VectorAdvance(tr.endpos,magicFactor47,testStart,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + VectorCopy(currentOrg, goalSpot); + } else { + VectorCopy(tr.endpos, goalSpot); + int magicFactor47 = 0.5f; // shorten percentage to make sure we can go down along a wall + VectorAdvance(tr.endpos, magicFactor47, testStart, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb } } // ok now as the horizontal trace fraction approaches zero, we want to head toward the horizontalHitSpot - //geeze I would like some reasonable trace fractions - assert(horzontalTraceFraction>=0.0f&&horzontalTraceFraction<=1.0f); - VectorAdvance(HorizontalHitSpot,horzontalTraceFraction*horzontalTraceFraction,goalSpot,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + // geeze I would like some reasonable trace fractions + assert(horzontalTraceFraction >= 0.0f && horzontalTraceFraction <= 1.0f); + VectorAdvance(HorizontalHitSpot, horzontalTraceFraction * horzontalTraceFraction, goalSpot, goalSpot); // VA(a,t,b,c)-> c := (1-t)a+tb #if 0 if ((bone.RagFlags & RAG_EFFECTOR) && (bone.RagFlags & RAG_BONE_LIGHTWEIGHT)) { //new rule - don't even bother unless it's a lightweight effector @@ -3300,22 +2822,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif int k; - int magicFactor12=0.8f; // dampening of velocity applied - int magicFactor16=10.0f; // effect multiplier of velocity applied + int magicFactor12 = 0.8f; // dampening of velocity applied + int magicFactor16 = 10.0f; // effect multiplier of velocity applied - if (iAmStartSolid) - { + if (iAmStartSolid) { magicFactor16 = 30.0f; } - for (k=0;k<3;k++) - { - e.desiredDirection[k]=goalSpot[k]-e.currentOrigin[k]; - e.desiredDirection[k]+=magicFactor16*bone.velocityEffector[k]; - e.desiredDirection[k]+=flrand(-0.75f,0.75f)*flrand(-0.75f,0.75f); - bone.velocityEffector[k]*=magicFactor12; + for (k = 0; k < 3; k++) { + e.desiredDirection[k] = goalSpot[k] - e.currentOrigin[k]; + e.desiredDirection[k] += magicFactor16 * bone.velocityEffector[k]; + e.desiredDirection[k] += flrand(-0.75f, 0.75f) * flrand(-0.75f, 0.75f); + bone.velocityEffector[k] *= magicFactor12; } - VectorCopy(e.currentOrigin,bone.lastPosition); // last arg is dest + VectorCopy(e.currentOrigin, bone.lastPosition); // last arg is dest } return anyStartSolid; } @@ -3338,57 +2858,51 @@ static inline int G2_RagIndexForBoneNum(int boneNum) #endif #ifdef _RAG_PRINT_TEST -void G2_RagPrintMatrix(mdxaBone_t *mat) -{ +void G2_RagPrintMatrix(mdxaBone_t *mat) { char x[1024]; x[0] = 0; int n = 0; - while (n < 3) - { + while (n < 3) { int o = 0; - while (o < 4) - { - strcat(x, va("%f ", mat->matrix[n][o])); + while (o < 4) { + strcat(x, va("%f ", mat->matrix[n][o])); o++; } n++; } strcat(x, "\n"); - ri.Printf( PRINT_ALL, x); + ri.Printf(PRINT_ALL, x); } #endif void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale); void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame); -static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) -{ +static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) { static mdxaBone_t trueBaseMatrix, baseBoneMatrix; - //get matrix for the settleFrame to use as an ideal + // get matrix for the settleFrame to use as an ideal G2_RagGetAnimMatrix(ghoul2, bone.boneNumber, trueBaseMatrix, params->settleFrame); assert(bone.hasAnimFrameMatrix == params->settleFrame); - G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, - trueBaseMatrix, baseBoneMatrix, params->scale); + G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, trueBaseMatrix, baseBoneMatrix, params->scale); - //Use params to multiply world coordinate/dir matrix into the - //bone matrix and give us a useable world position + // Use params to multiply world coordinate/dir matrix into the + // bone matrix and give us a useable world position Multiply_3x4Matrix(&retMatrix, &worldMatrix, &baseBoneMatrix); assert(!Q_isnan(retMatrix.matrix[2][3])); } -//get the current pelvis Z direction and the base anim matrix Z direction -//so they can be compared and used to offset -rww +// get the current pelvis Z direction and the base anim matrix Z direction +// so they can be compared and used to offset -rww void G2_GetRagBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &retMatrix); -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); -static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) -{ +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix); +static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) { static mdxaBone_t final; static mdxaBone_t x; - //static mdxaBone_t *unused1, *unused2; - //static vec3_t lumbarPos; + // static mdxaBone_t *unused1, *unused2; + // static vec3_t lumbarPos; assert(ghoul2.animModel); int boneIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, "pelvis"); @@ -3404,8 +2918,8 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd G2API_GiveMeVectorFromMatrix(&final, ORIGIN, pos); G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, dir); #else - //We have the anim matrix pelvis pos now, so get the normal one as well - //G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); + // We have the anim matrix pelvis pos now, so get the normal one as well + // G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); int bolt = G2_Add_Bolt(&ghoul2, ghoul2.mBltlist, ghoul2.mSlist, "pelvis"); G2_GetBoltMatrixLow(ghoul2, bolt, params->scale, x); Multiply_3x4Matrix(&final, &worldMatrix, &x); @@ -3433,13 +2947,13 @@ static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpd */ } -static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) -{ //now returns true if any bone was in solid, otherwise false +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, + int curTime) { // now returns true if any bone was in solid, otherwise false int ignoreNum = params->me; static int i; static vec3_t goalSpot; static trace_t tr; - //static trace_t solidTr; + // static trace_t solidTr; static int k; static const float velocityDampening = 1.0f; static const float velocityMultiplier = 60.0f; @@ -3456,38 +2970,31 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve static bool hasBasePos; static vec3_t animPelvisDir, pelvisDir, animPelvisPos, pelvisPos; - //Maybe customize per-bone? + // Maybe customize per-bone? static const float gravity = 3.0f; static const float mass = 0.09f; - static const float bounce = 0.0f;//1.3f; - //Bouncing and stuff unfortunately does not work too well at the moment. - //Need to keep a seperate "physics origin" or make the filthy solve stuff - //better. + static const float bounce = 0.0f; // 1.3f; + // Bouncing and stuff unfortunately does not work too well at the moment. + // Need to keep a seperate "physics origin" or make the filthy solve stuff + // better. bool inAir = false; - if (params->velocity[0] || params->velocity[1] || params->velocity[2]) - { + if (params->velocity[0] || params->velocity[1] || params->velocity[2]) { inAir = true; } - if (!params->scale[0] && !params->scale[1] && !params->scale[2]) - { + if (!params->scale[0] && !params->scale[1] && !params->scale[2]) { VectorSet(entScale, 1.0f, 1.0f, 1.0f); - } - else - { + } else { VectorCopy(params->scale, entScale); } - if (broadsword_ragtobase && - broadsword_ragtobase->integer > 1) - { - //grab the pelvis directions to offset base positions for bones - G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, - animPelvisDir); + if (broadsword_ragtobase && broadsword_ragtobase->integer > 1) { + // grab the pelvis directions to offset base positions for bones + G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, animPelvisDir); - //don't care about the pitch offsets + // don't care about the pitch offsets pelvisDir[2] = 0; animPelvisDir[2] = 0; @@ -3505,24 +3012,21 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(uanimPelvisPos, blah, 50, 0xff0000, 1); */ - //just convert to angles now, that's all we'll ever use them for + // just convert to angles now, that's all we'll ever use them for vectoangles(pelvisDir, pelvisDir); vectoangles(animPelvisDir, animPelvisDir); } - for (i = 0; i < numRags; i++) - { + for (i = 0; i < numRags; i++) { boneInfo_t &bone = *ragBoneData[i]; SRagEffector &e = ragEffectors[i]; - if (inAir) - { + if (inAir) { bone.airTime = curTime + 30; } - if (bone.RagFlags & RAG_PCJ_PELVIS) - { - VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2]+DEFAULT_MINS_2)+((bone.radius*entScale[2])+2)); + if (bone.RagFlags & RAG_PCJ_PELVIS) { + VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2] + DEFAULT_MINS_2) + ((bone.radius * entScale[2]) + 2)); VectorSubtract(goalSpot, e.currentOrigin, desiredPelvisOffset); haveDesiredPelvisOffset = true; @@ -3530,17 +3034,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - if (!(bone.RagFlags & RAG_EFFECTOR)) - { + if (!(bone.RagFlags & RAG_EFFECTOR)) { continue; } - if (bone.hasOverGoal) - { //api call was made to override the goal spot + if (bone.hasOverGoal) { // api call was made to override the goal spot VectorCopy(bone.overGoalSpot, goalSpot); bone.solidCount = 0; - for (k = 0; k < 3; k++) - { + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); bone.velocityEffector[k] *= velocityDampening; @@ -3550,22 +3051,20 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve continue; } - VectorSet(testMins, -e.radius*entScale[0], -e.radius*entScale[1], -e.radius*entScale[2]); - VectorSet(testMaxs, e.radius*entScale[0], e.radius*entScale[1], e.radius*entScale[2]); + VectorSet(testMins, -e.radius * entScale[0], -e.radius * entScale[1], -e.radius * entScale[2]); + VectorSet(testMaxs, e.radius * entScale[0], e.radius * entScale[1], e.radius * entScale[2]); assert(ghoul2V[0].mBoneCache); - //get the parent bone's position + // get the parent bone's position hasDaddy = false; - if (bone.boneNumber) - { + if (bone.boneNumber) { assert(ghoul2V[0].animModel); assert(ghoul2V[0].aHeader); - if (bone.parentBoneIndex == -1) - { - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; + if (bone.parentBoneIndex == -1) { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; int bParentIndex, bParentListIndex = -1; offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); @@ -3573,66 +3072,54 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve bParentIndex = skel->parent; - while (bParentIndex > 0) - { //go upward through hierarchy searching for the first parent that is a rag bone + while (bParentIndex > 0) { // go upward through hierarchy searching for the first parent that is a rag bone skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bParentIndex]); bParentIndex = skel->parent; bParentListIndex = G2_Find_Bone(ghoul2V[0].animModel, ghoul2V[0].mBlist, skel->name); - if (bParentListIndex != -1) - { + if (bParentListIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bParentListIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //valid rag bone + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // valid rag bone break; } } - //didn't work out, reset to -1 again + // didn't work out, reset to -1 again bParentListIndex = -1; } bone.parentBoneIndex = bParentListIndex; } - if (bone.parentBoneIndex != -1) - { + if (bone.parentBoneIndex != -1) { boneInfo_t &pbone = ghoul2V[0].mBlist[bone.parentBoneIndex]; - if (pbone.flags & BONE_ANGLES_RAGDOLL) - { //has origin calculated for us already + if (pbone.flags & BONE_ANGLES_RAGDOLL) { // has origin calculated for us already VectorCopy(ragEffectors[pbone.ragIndex].currentOrigin, parentOrigin); hasDaddy = true; } } } - //get the position this bone would be in if we were in the desired frame + // get the position this bone would be in if we were in the desired frame hasBasePos = false; - if (broadsword_ragtobase && - broadsword_ragtobase->integer) - { + if (broadsword_ragtobase && broadsword_ragtobase->integer) { vec3_t v, a; float f; G2_RagGetWorldAnimMatrix(ghoul2V[0], bone, params, worldBaseMatrix); G2API_GiveMeVectorFromMatrix(&worldBaseMatrix, ORIGIN, basePos); - if (broadsword_ragtobase->integer > 1) - { - float fa = AngleNormalize180(animPelvisDir[YAW]-pelvisDir[YAW]); - float d = fa-bone.offsetRotation; + if (broadsword_ragtobase->integer > 1) { + float fa = AngleNormalize180(animPelvisDir[YAW] - pelvisDir[YAW]); + float d = fa - bone.offsetRotation; - if (d > 16.0f || - d < -16.0f) - { //don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates + if (d > 16.0f || d < -16.0f) { // don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates bone.offsetRotation = fa; - } - else - { + } else { fa = bone.offsetRotation; } - //Rotate the point around the pelvis based on the offsets between pelvis positions + // Rotate the point around the pelvis based on the offsets between pelvis positions VectorSubtract(basePos, animPelvisPos, v); f = VectorLength(v); vectoangles(v, a); @@ -3641,14 +3128,14 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve VectorNormalize(v); VectorMA(animPelvisPos, f, v, basePos); - //re-orient the position of the bone to the current position of the pelvis + // re-orient the position of the bone to the current position of the pelvis VectorSubtract(basePos, animPelvisPos, v); - //push the spots outward? (to stretch the skeleton more) - //v[0] *= 1.5f; - //v[1] *= 1.5f; + // push the spots outward? (to stretch the skeleton more) + // v[0] *= 1.5f; + // v[1] *= 1.5f; VectorAdd(pelvisPos, v, basePos); } -#if 0 //for debugging frame skeleton +#if 0 // for debugging frame skeleton mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; @@ -3678,27 +3165,23 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve hasBasePos = true; } - //Are we in solid? - if (hasDaddy) - { + // Are we in solid? + if (hasDaddy) { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, parentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - //Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); - } - else - { + // Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } else { Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, params->position, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); } - if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) - { //currently in solid, see what we can do about it + if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) { // currently in solid, see what we can do about it vec3_t vSub; startSolid = true; anySolid = true; - if (hasBasePos)// && bone.solidCount < 32) - { //only go to the base pos for slightly in solid bones -#if 0 //over-compensation + if (hasBasePos) // && bone.solidCount < 32) + { // only go to the base pos for slightly in solid bones +#if 0 // over-compensation float fl; float floorBase; @@ -3712,102 +3195,84 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve { goalSpot[2] = floorBase; } -#else //just use the spot directly +#else // just use the spot directly VectorCopy(basePos, goalSpot); - goalSpot[2] = (params->position[2]-23)-testMins[2]; + goalSpot[2] = (params->position[2] - 23) - testMins[2]; #endif - //ri.Printf( PRINT_ALL, "%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); - } - else - { //if deep in solid want to try to rise up out of solid before hinting back to base + // ri.Printf( PRINT_ALL, "%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); + } else { // if deep in solid want to try to rise up out of solid before hinting back to base VectorSubtract(e.currentOrigin, params->position, vSub); VectorNormalize(vSub); VectorMA(params->position, 40.0f, vSub, goalSpot); - //should be 1 unit above the ground taking bounding box sizes into account - goalSpot[2] = (params->position[2]-23)-testMins[2]; + // should be 1 unit above the ground taking bounding box sizes into account + goalSpot[2] = (params->position[2] - 23) - testMins[2]; } - //Trace from the entity origin in the direction between the origin and current bone position to - //find a good eventual goal position + // Trace from the entity origin in the direction between the origin and current bone position to + // find a good eventual goal position Rag_Trace(&tr, params->position, testMins, testMaxs, goalSpot, params->me, RAG_MASK, G2_NOCOLLIDE, 0); VectorCopy(tr.endpos, goalSpot); - } - else - { + } else { startSolid = false; -#if 1 //do hinting? - //Hint the bone back to the base origin - if (hasDaddy || hasBasePos) - { - if (hasBasePos) - { +#if 1 // do hinting? + // Hint the bone back to the base origin + if (hasDaddy || hasBasePos) { + if (hasBasePos) { VectorSubtract(basePos, e.currentOrigin, velDir); - } - else - { + } else { VectorSubtract(e.currentOrigin, parentOrigin, velDir); } - } - else - { + } else { VectorSubtract(e.currentOrigin, params->position, velDir); } - if (VectorLength(velDir) > 2.0f) - { //don't bother if already close + if (VectorLength(velDir) > 2.0f) { // don't bother if already close VectorNormalize(velDir); VectorScale(velDir, 8.0f, velDir); - velDir[2] = 0; //don't want to nudge on Z, the gravity will take care of things. + velDir[2] = 0; // don't want to nudge on Z, the gravity will take care of things. VectorAdd(bone.epVelocity, velDir, bone.epVelocity); } #endif - //Factor the object's velocity into the bone's velocity, by pushing the bone - //opposite the velocity to give the apperance the lighter limbs are being "dragged" - //behind those of greater mass. - if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) - { + // Factor the object's velocity into the bone's velocity, by pushing the bone + // opposite the velocity to give the apperance the lighter limbs are being "dragged" + // behind those of greater mass. + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) { vec3_t vel; float vellen; VectorCopy(params->velocity, vel); - //Scale down since our velocity scale is different from standard game physics + // Scale down since our velocity scale is different from standard game physics VectorScale(vel, 0.5f, vel); vellen = VectorLength(vel); - if (vellen > 64.0f) - { //cap it off - VectorScale(vel, 64.0f/vellen, vel); + if (vellen > 64.0f) { // cap it off + VectorScale(vel, 64.0f / vellen, vel); } - //Invert the velocity so we go opposite the heavier parts and drag behind + // Invert the velocity so we go opposite the heavier parts and drag behind VectorInverse(vel); - if (vel[2]) - { //want to override entirely instead then + if (vel[2]) { // want to override entirely instead then VectorCopy(vel, bone.epVelocity); - } - else - { + } else { VectorAdd(bone.epVelocity, vel, bone.epVelocity); } } - //We're not in solid so we can apply physics freely now. - if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, - gravity, mass, bounce)) - { //if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin + // We're not in solid so we can apply physics freely now. + if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, gravity, mass, + bounce)) { // if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin VectorCopy(params->position, goalSpot); } } - //Set this now so we know what to do for angle limiting - if (startSolid) - { + // Set this now so we know what to do for angle limiting + if (startSolid) { bone.solidCount++; #if 0 if ( ri.CGVMLoaded() && bone.solidCount > 8 ) @@ -3831,14 +3296,13 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve #endif #ifdef _DEBUG_BONE_NAMES - if (bone.solidCount > 64) - { + if (bone.solidCount > 64) { char *debugBoneName = G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber); vec3_t absmin, absmax; assert(debugBoneName); - ri.Printf( PRINT_ALL, "High bone (%s, %i) solid count: %i\n", debugBoneName, bone.boneNumber, bone.solidCount); + ri.Printf(PRINT_ALL, "High bone (%s, %i) solid count: %i\n", debugBoneName, bone.boneNumber, bone.solidCount); VectorAdd(e.currentOrigin, testMins, absmin); VectorAdd(e.currentOrigin, testMaxs, absmax); @@ -3847,14 +3311,12 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve G2_RagDebugLine(e.currentOrigin, goalSpot, 50, 0x00ff00, 1); } #endif - } - else - { + } else { bone.solidCount = 0; } -#if 0 //standard goalSpot capping? - //unless we are really in solid, we should keep adjustments minimal +#if 0 // standard goalSpot capping? + // unless we are really in solid, we should keep adjustments minimal if (/*bone.epGravFactor < 64 &&*/ bone.solidCount < 2 && !inAir) { @@ -3873,22 +3335,17 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif - //Set the desired direction based on the goal position and other factors. - for (k = 0; k < 3; k++) - { + // Set the desired direction based on the goal position and other factors. + for (k = 0; k < 3; k++) { e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); - if (broadsword_dircap && - broadsword_dircap->value) - { + if (broadsword_dircap && broadsword_dircap->value) { float cap = broadsword_dircap->value; - if (bone.solidCount > 5) - { - float solidFactor = bone.solidCount*0.2f; + if (bone.solidCount > 5) { + float solidFactor = bone.solidCount * 0.2f; - if (solidFactor > 16.0f) - { //don't go too high or something ugly might happen + if (solidFactor > 16.0f) { // don't go too high or something ugly might happen solidFactor = 16.0f; } @@ -3896,12 +3353,9 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve cap *= 8; } - if (e.desiredDirection[k] > cap) - { + if (e.desiredDirection[k] > cap) { e.desiredDirection[k] = cap; - } - else if (e.desiredDirection[k] < -cap) - { + } else if (e.desiredDirection[k] < -cap) { e.desiredDirection[k] = -cap; } } @@ -3918,25 +3372,19 @@ static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const ve } #endif -static float AngleNormZero(float theta) -{ - float ret=fmodf(theta,360.0f); - if (ret<-180.0f) - { - ret+=360.0f; +static float AngleNormZero(float theta) { + float ret = fmodf(theta, 360.0f); + if (ret < -180.0f) { + ret += 360.0f; + } else if (ret > 180.0f) { + ret -= 360.0f; } - else if (ret>180.0f) - { - ret-=360.0f; - } - assert(ret>=-180.0f&&ret<=180.0f); + assert(ret >= -180.0f && ret <= 180.0f); return ret; } -static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) -{ - if ( !ri.CGVMLoaded() || !params ) - { +static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) { + if (!ri.CGVMLoaded() || !params) { return; } @@ -3945,15 +3393,15 @@ static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDol callData->entNum = params->me; strcpy(callData->boneName, G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber)); - ri.CGVM_RagCallback( RAG_CALLBACK_BONESNAP ); + ri.CGVM_RagCallback(RAG_CALLBACK_BONESNAP); } -static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool limitAngles,CRagDollUpdateParams *params) -{ +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V, int g2Index, float decay, int frameNum, const vec3_t currentOrg, bool limitAngles, + CRagDollUpdateParams *params) { int i; - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; mdxaBone_t N; mdxaBone_t P; @@ -3967,96 +3415,88 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f assert(ghoul2.mFileName[0]); boneInfo_v &blist = ghoul2.mBlist; - // END this is the objective function thing - for (i=0;i50.0f) { @@ -4067,193 +3507,168 @@ static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int f bone.velocityRoot[k]=-50.0f; } */ - //No -rww - bone.ragOverrideMatrix.matrix[k][3]=bone.velocityRoot[k]; + // No -rww + bone.ragOverrideMatrix.matrix[k][3] = bone.velocityRoot[k]; } } - } - else - { + } else { vec3_t delAngles; VectorClear(delAngles); - for (k=0;k<3;k++) - { - tAngles[k]+=0.5f; - Create_Matrix(tAngles,&temp2); //dest 2nd arg - tAngles[k]-=0.5f; - Multiply_3x4Matrix(&temp1,&P,&temp2); //dest first arg - Multiply_3x4Matrix(&Gs[k],&temp1,&N); //dest first arg - + for (k = 0; k < 3; k++) { + tAngles[k] += 0.5f; + Create_Matrix(tAngles, &temp2); // dest 2nd arg + tAngles[k] -= 0.5f; + Multiply_3x4Matrix(&temp1, &P, &temp2); // dest first arg + Multiply_3x4Matrix(&Gs[k], &temp1, &N); // dest first arg } - int allSolidCount = 0;//bone.solidCount; + int allSolidCount = 0; // bone.solidCount; // fixme precompute this - int numDep=G2_GetBoneDependents(ghoul2,bone.boneNumber,tempDependents,MAX_BONES_RAG); + int numDep = G2_GetBoneDependents(ghoul2, bone.boneNumber, tempDependents, MAX_BONES_RAG); int j; - int numRagDep=0; - for (j=0;jragIndex; - assert(depIndex>i); // these are supposed to be topologically sorted + int depIndex = rag[tempDependents[j]]->ragIndex; + assert(depIndex > i); // these are supposed to be topologically sorted assert(ragBoneData[depIndex]); - boneInfo_t &depBone=*ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector + boneInfo_t &depBone = *ragBoneData[depIndex]; + if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } allSolidCount += depBone.solidCount; } } - //bone.solidCount = allSolidCount; + // bone.solidCount = allSolidCount; allSolidCount += bone.solidCount; - VectorCopy(bone.currentAngles,bone.lastAngles); + VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9=0.75f; // dampfactor for angle changes - float magicFactor1=0.40f; //controls the speed of the gradient descent - float magicFactor32 = 1.5f; - float recip=0.0f; - if (numRagDep) - { - recip=sqrt(4.0f/float(numRagDep)); + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = 0.40f; // controls the speed of the gradient descent + float magicFactor32 = 1.5f; + float recip = 0.0f; + if (numRagDep) { + recip = sqrt(4.0f / float(numRagDep)); } - if (allSolidCount > 32) - { + if (allSolidCount > 32) { magicFactor1 = 0.6f; - } - else if (allSolidCount > 10) - { + } else if (allSolidCount > 10) { magicFactor1 = 0.5f; } - if (bone.overGradSpeed) - { //api call was made to specify a speed for this bone + if (bone.overGradSpeed) { // api call was made to specify a speed for this bone magicFactor1 = bone.overGradSpeed; } - float fac=decay*recip*magicFactor1; - assert(fac>=0.0f); + float fac = decay * recip * magicFactor1; + assert(fac >= 0.0f); #if 0 if (bone.RagFlags & RAG_PCJ_PELVIS) { magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable } #endif - if (ragState==ERS_DYNAMIC) - { - magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + if (ragState == ERS_DYNAMIC) { + magicFactor9 = .85f; // we don't want this swinging radically, make the whole thing kindof unstable } -#if 1 //constraint breaks? - if (bone.RagFlags & RAG_UNSNAPPABLE) - { +#if 1 // constraint breaks? + if (bone.RagFlags & RAG_UNSNAPPABLE) { magicFactor32 = 1.0f; } #endif - for (k=0;k<3;k++) - { - bone.currentAngles[k]+=delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k]=(bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; - bone.currentAngles[k]=AngleNormZero(bone.currentAngles[k]); + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); // bone.currentAngles[k]=flrand(bone.minAngles[k],bone.maxAngles[k]); -#if 1 //constraint breaks? - if (limitAngles && ( allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE) )) //32 tries and still in solid? Then we'll let you move freely +#if 1 // constraint breaks? + if (limitAngles && (allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE))) // 32 tries and still in solid? Then we'll let you move freely #else if (limitAngles) #endif { - if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) - { - //magicFactor32 += (allSolidCount/32); + if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) { + // magicFactor32 += (allSolidCount/32); - if (bone.currentAngles[k]>bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k]=bone.maxAngles[k]*magicFactor32; + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k]bone.maxAngles[k]*magicFactor32) - { + for (k = 0; k < 3; k++) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { isSnapped = true; break; } - if (bone.currentAngles[k]ragIndex; - if (!ragBoneData[depIndex]) - { + int depIndex = rag[tempDependents[j]]->ragIndex; + if (!ragBoneData[depIndex]) { continue; } - boneInfo_t &depBone=*ragBoneData[depIndex]; + boneInfo_t &depBone = *ragBoneData[depIndex]; - if (depBone.RagFlags & RAG_EFFECTOR) - { + if (depBone.RagFlags & RAG_EFFECTOR) { // this is a dependent of me, and also a rag numRagDep++; - for (k=0;k<3;k++) - { - Multiply_3x4Matrix(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + for (k = 0; k < 3; k++) { + Multiply_3x4Matrix(&Enew[k], &Gs[k], &ragBones[depIndex]); // dest first arg vec3_t tPosition; - tPosition[0]=Enew[k].matrix[0][3]; - tPosition[1]=Enew[k].matrix[1][3]; - tPosition[2]=Enew[k].matrix[2][3]; + tPosition[0] = Enew[k].matrix[0][3]; + tPosition[1] = Enew[k].matrix[1][3]; + tPosition[2] = Enew[k].matrix[2][3]; vec3_t change; - VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg - float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); - assert( !Q_isnan(goodness)); - goodness*=depBone.weight; - delAngles[k]+=goodness; // keep bigger stuff more out of wall or something - assert( !Q_isnan(delAngles[k])); + VectorSubtract(tPosition, ragEffectors[depIndex].currentOrigin, change); // dest is last arg + float goodness = DotProduct(change, ragEffectors[depIndex].desiredDirection); + assert(!Q_isnan(goodness)); + goodness *= depBone.weight; + delAngles[k] += goodness; // keep bigger stuff more out of wall or something + assert(!Q_isnan(delAngles[k])); } } } @@ -4376,222 +3779,174 @@ static void G2_IKSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameN VectorCopy(bone.currentAngles, bone.lastAngles); // Update angles - float magicFactor9 = 0.75f; // dampfactor for angle changes - float magicFactor1 = bone.ikSpeed; //controls the speed of the gradient descent - float magicFactor32 = 1.0f; - float recip = 0.0f; - bool freeThisBone = false; + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = bone.ikSpeed; // controls the speed of the gradient descent + float magicFactor32 = 1.0f; + float recip = 0.0f; + bool freeThisBone = false; - if (!magicFactor1) - { + if (!magicFactor1) { magicFactor1 = 0.40f; } - recip = sqrt(4.0f/1.0f); + recip = sqrt(4.0f / 1.0f); - float fac = (decay*recip*magicFactor1); + float fac = (decay * recip * magicFactor1); assert(fac >= 0.0f); - if (ragState == ERS_DYNAMIC) - { + if (ragState == ERS_DYNAMIC) { magicFactor9 = 0.85f; // we don't want this swinging radically, make the whole thing kindof unstable } - - if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && - !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) - { + if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) { freeThisBone = true; } - for (k = 0; k < 3; k++) - { - bone.currentAngles[k] += delAngles[k]*fac; + for (k = 0; k < 3; k++) { + bone.currentAngles[k] += delAngles[k] * fac; - bone.currentAngles[k] = (bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = (bone.lastAngles[k] - bone.currentAngles[k]) * magicFactor9 + bone.currentAngles[k]; bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); - if (limitAngles && !freeThisBone) - { - if (bone.currentAngles[k] > bone.maxAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.maxAngles[k]*magicFactor32; + if (limitAngles && !freeThisBone) { + if (bone.currentAngles[k] > bone.maxAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.maxAngles[k] * magicFactor32; } - if (bone.currentAngles[k] < bone.minAngles[k]*magicFactor32) - { - bone.currentAngles[k] = bone.minAngles[k]*magicFactor32; + if (bone.currentAngles[k] < bone.minAngles[k] * magicFactor32) { + bone.currentAngles[k] = bone.minAngles[k] * magicFactor32; } } } Create_Matrix(bone.currentAngles, &temp1); Multiply_3x4Matrix(&temp2, &temp1, bone.baseposeInv); Multiply_3x4Matrix(&bone.ragOverrideMatrix, bone.basepose, &temp2); - assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + assert(!Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); G2_Generate_MatrixRag(blist, ragBlistIndex[bone.boneNumber]); } } -static void G2_DoIK(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params) -{ +static void G2_DoIK(CGhoul2Info_v &ghoul2V, int g2Index, CRagDollUpdateParams *params) { int i; - if (!params) - { + if (!params) { assert(0); return; } - int frameNum=G2API_GetTime(0); - CGhoul2Info &ghoul2=ghoul2V[g2Index]; + int frameNum = G2API_GetTime(0); + CGhoul2Info &ghoul2 = ghoul2V[g2Index]; assert(ghoul2.mFileName[0]); - float decay=1.0f; - bool resetOrigin=false; - bool anyRendered=false; + float decay = 1.0f; + bool resetOrigin = false; + bool anyRendered = false; - int iters = 12; //since we don't trace or anything, we can afford this. + int iters = 12; // since we don't trace or anything, we can afford this. - if (iters) - { - if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,params->position,anyRendered)) - { + if (iters) { + if (!G2_RagDollSetup(ghoul2, frameNum, resetOrigin, params->position, anyRendered)) { return; } // ok, now our data structures are compact and set up in topological order - for (i=0;iangles,params->position,params->scale); + for (i = 0; i < iters; i++) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); G2_IKReposition(params->position, params); - G2_IKSolve(ghoul2V,g2Index,decay*2.0f,frameNum,params->position,true); + G2_IKSolve(ghoul2V, g2Index, decay * 2.0f, frameNum, params->position, true); } } - if (params->me != ENTITYNUM_NONE) - { - G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); + if (params->me != ENTITYNUM_NONE) { + G2_RagDollCurrentPosition(ghoul2V, g2Index, frameNum, params->angles, params->position, params->scale); } } -//rww - cut out the entire non-ragdoll section of this.. -void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index,CRagDollUpdateParams *params) -{ - bool anyRagDoll=false; +// rww - cut out the entire non-ragdoll section of this.. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index, CRagDollUpdateParams *params) { + bool anyRagDoll = false; bool anyIK = false; - for(size_t i=0; iangles, parms->position); @@ -4624,27 +3979,26 @@ void G2_InitIK(CGhoul2Info_v &ghoul2V, sharedRagDollUpdateParams_t *parms, int t G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); #endif - //Only need the standard effectors for this. - pcjFlags = RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; - - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rhand",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lhand",pcjFlags,6.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); -// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltibia",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltalus",pcjFlags,4.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lradiusX",pcjFlags,6.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lfemurX",pcjFlags,10.0f); - G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ceyebrow",pcjFlags,10.0f); + // Only need the standard effectors for this. + pcjFlags = RAG_PCJ | RAG_PCJ_POST_MULT | RAG_EFFECTOR; + + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rhand", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lhand", pcjFlags, 6.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); + // G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltibia", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rtalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ltalus", pcjFlags, 4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lradiusX", pcjFlags, 6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "rfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "lfemurX", pcjFlags, 10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a, blist, "ceyebrow", pcjFlags, 10.0f); } -qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) -{ - model_t *mod_a; +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + model_t *mod_a; int g2index = 0; int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; @@ -4653,19 +4007,15 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName boneInfo_v &blist = g2.mBlist; mod_a = (model_t *)g2.animModel; - if (!boneName) - { //null bonename param means it's time to init the ik stuff on this instance + if (!boneName) { // null bonename param means it's time to init the ik stuff on this instance sharedRagDollUpdateParams_t sRDUP; - if (ikState == IKS_NONE) - { //this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags + if (ikState == IKS_NONE) { // this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags size_t i = 0; - while (i < blist.size()) - { //we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ - //limb after they reset it gameside, it's reasonable for IK bones. + while (i < blist.size()) { // we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ + // limb after they reset it gameside, it's reasonable for IK bones. boneInfo_t &bone = blist[i]; - if (bone.boneNumber != -1) - { + if (bone.boneNumber != -1) { bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags &= ~BONE_ANGLES_IK; bone.RagFlags = 0; @@ -4677,8 +4027,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName } assert(params); - if (!params) - { + if (!params) { return qfalse; } @@ -4691,53 +4040,47 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } - if (!rmod_a || !mod_a) - { + if (!rmod_a || !mod_a) { return qfalse; } int index = G2_Find_Bone(mod_a, blist, boneName); - if (index == -1) - { + if (index == -1) { index = G2_Add_Bone(mod_a, blist, boneName); } - if (index == -1) - { //couldn't find or add the bone.. + if (index == -1) { // couldn't find or add the bone.. return qfalse; } boneInfo_t &bone = blist[index]; - if (ikState == IKS_NONE) - { //remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since - //we don't store bone index handles gameside anywhere. - if (!(bone.flags & BONE_ANGLES_RAGDOLL)) - { //you can't set the ik state to none if it's not a rag/ik bone. + if (ikState == IKS_NONE) { // remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since + // we don't store bone index handles gameside anywhere. + if (!(bone.flags & BONE_ANGLES_RAGDOLL)) { // you can't set the ik state to none if it's not a rag/ik bone. return qfalse; } - //bone.flags = 0; - //G2_Remove_Bone_Index(blist, index); - //actually, I want to keep it on the rag list, and remove it as an IK bone instead. + // bone.flags = 0; + // G2_Remove_Bone_Index(blist, index); + // actually, I want to keep it on the rag list, and remove it as an IK bone instead. bone.flags &= ~BONE_ANGLES_RAGDOLL; bone.flags |= BONE_ANGLES_IK; bone.RagFlags &= ~RAG_PCJ_IK_CONTROLLED; return qtrue; } - //need params if we're not resetting. - if (!params) - { + // need params if we're not resetting. + if (!params) { assert(0); return qfalse; } - if (bone.flags & BONE_ANGLES_RAGDOLL) - { //otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be BONE_ANGLES_IK, active are considered rag) + if (bone.flags & BONE_ANGLES_RAGDOLL) { // otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be + // BONE_ANGLES_IK, active are considered rag) return qfalse; } -#if 0 //this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's +#if 0 // this is wrong now.. we're only initing effectors with initik now.. which SHOULDN'T be used as pcj's if (!(bone.flags & BONE_ANGLES_IK) && !(bone.flags & BONE_ANGLES_RAGDOLL)) { //IK system has not been inited yet, because any bone that can be IK should be in the ragdoll list, not flagged as BONE_ANGLES_RAGDOLL but as BONE_ANGLES_IK sharedRagDollUpdateParams_t sRDUP; @@ -4760,10 +4103,9 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); #endif - int pcjFlags = RAG_PCJ|RAG_PCJ_IK_CONTROLLED|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + int pcjFlags = RAG_PCJ | RAG_PCJ_IK_CONTROLLED | RAG_PCJ_POST_MULT | RAG_EFFECTOR; - if (params->pcjOverrides) - { + if (params->pcjOverrides) { pcjFlags = params->pcjOverrides; } @@ -4774,11 +4116,10 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName int startFrame = params->startFrame, endFrame = params->endFrame; - if (bone.startFrame != startFrame || bone.endFrame != endFrame || params->forceAnimOnBone) - { //if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. - G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame-1, - BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, - 1.0f, curTime, float(startFrame), 150, 0, true); + if (bone.startFrame != startFrame || bone.endFrame != endFrame || + params->forceAnimOnBone) { // if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. + G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame - 1, BONE_ANIM_OVERRIDE_FREEZE | BONE_ANIM_BLEND, 1.0f, curTime, + float(startFrame), 150, 0, true); } G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); @@ -4786,8 +4127,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName bone.lastTimeUpdated = 0; G2_Set_Bone_Angles_Rag(g2, rmod_a, blist, boneName, pcjFlags, params->radius, params->pcjMins, params->pcjMaxs, params->blendTime); - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { assert(!"failed to add any rag bones"); return qfalse; } @@ -4795,8 +4135,7 @@ qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName return qtrue; } -qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) -{ +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) { #if 0 model_t *mod_a; int g2index = 0; @@ -4837,17 +4176,15 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params int curTime = time; CGhoul2Info &g2 = ghoul2[g2index]; - //rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? - if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) - { //changed models, possibly. + // rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? + if (!G2_RagDollSetup(g2, curTime, true, params->origin, false)) { // changed models, possibly. return qfalse; } - for (int i=0;idesiredOrigin, bone.ikPosition); bone.ikSpeed = params->movementSpeed; @@ -4858,21 +4195,16 @@ qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params } // set the bone list to all unused so the bone transformation routine ignores it. -void G2_Init_Bone_List(boneInfo_v &blist, int numBones) -{ +void G2_Init_Bone_List(boneInfo_v &blist, int numBones) { blist.clear(); blist.reserve(numBones); } -void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) -{ +void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; imFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); +int G2_Get_Bone_Index(CGhoul2Info *ghoul2, const char *boneName) { + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2->mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); return (G2_Find_Bone(mod_a, ghoul2->mBlist, boneName)); } diff --git a/codemp/rd-vanilla/G2_misc.cpp b/codemp/rd-vanilla/G2_misc.cpp index 248fc88819..4d9271230b 100644 --- a/codemp/rd-vanilla/G2_misc.cpp +++ b/codemp/rd-vanilla/G2_misc.cpp @@ -33,303 +33,236 @@ along with this program; if not, see . #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) -static int CurrentTag=GORE_TAG_UPPER+1; -static int CurrentTagUpper=GORE_TAG_UPPER; +static int CurrentTag = GORE_TAG_UPPER + 1; +static int CurrentTagUpper = GORE_TAG_UPPER; -static std::map GoreRecords; -static std::map,int> GoreTagsTemp; // this is a surface index to gore tag map used only - // temporarily during the generation phase so we reuse gore tags per LOD +static std::map GoreRecords; +static std::map, int> GoreTagsTemp; // this is a surface index to gore tag map used only + // temporarily during the generation phase so we reuse gore tags per LOD int goreModelIndex; -static cvar_t *cg_g2MarksAllModels=NULL; +static cvar_t *cg_g2MarksAllModels = NULL; GoreTextureCoordinates *FindGoreRecord(int tag); -static inline void DestroyGoreTexCoordinates(int tag) -{ +static inline void DestroyGoreTexCoordinates(int tag) { GoreTextureCoordinates *gTC = FindGoreRecord(tag); - if (!gTC) - { + if (!gTC) { return; } gTC->~GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } -//TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all +// TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all #define MAX_GORE_RECORDS (500) -int AllocGoreRecord() -{ - while (GoreRecords.size()>MAX_GORE_RECORDS) - { - int tagHigh=(*GoreRecords.begin()).first&GORE_TAG_MASK; - std::map::iterator it; +int AllocGoreRecord() { + while (GoreRecords.size() > MAX_GORE_RECORDS) { + int tagHigh = (*GoreRecords.begin()).first & GORE_TAG_MASK; + std::map::iterator it; GoreTextureCoordinates *gTC; it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); - while (GoreRecords.size()) - { - if (((*GoreRecords.begin()).first&GORE_TAG_MASK)!=tagHigh) - { + while (GoreRecords.size()) { + if (((*GoreRecords.begin()).first & GORE_TAG_MASK) != tagHigh) { break; } it = GoreRecords.begin(); gTC = &(*it).second; - if (gTC) - { + if (gTC) { gTC->~GoreTextureCoordinates(); } GoreRecords.erase(GoreRecords.begin()); } } - int ret=CurrentTag; - GoreRecords[CurrentTag]=GoreTextureCoordinates(); + int ret = CurrentTag; + GoreRecords[CurrentTag] = GoreTextureCoordinates(); CurrentTag++; return ret; } -void ResetGoreTag() -{ +void ResetGoreTag() { GoreTagsTemp.clear(); - CurrentTag=CurrentTagUpper; - CurrentTagUpper+=GORE_TAG_UPPER; + CurrentTag = CurrentTagUpper; + CurrentTagUpper += GORE_TAG_UPPER; } -GoreTextureCoordinates *FindGoreRecord(int tag) -{ - std::map::iterator i=GoreRecords.find(tag); - if (i!=GoreRecords.end()) - { +GoreTextureCoordinates *FindGoreRecord(int tag) { + std::map::iterator i = GoreRecords.find(tag); + if (i != GoreRecords.end()) { return &(*i).second; } return 0; } -void *G2_GetGoreRecord(int tag) -{ - return FindGoreRecord(tag); -} +void *G2_GetGoreRecord(int tag) { return FindGoreRecord(tag); } -void DeleteGoreRecord(int tag) -{ +void DeleteGoreRecord(int tag) { DestroyGoreTexCoordinates(tag); GoreRecords.erase(tag); } -static int CurrentGoreSet=1; // this is a UUID for gore sets -static std::map GoreSets; // map from uuid to goreset +static int CurrentGoreSet = 1; // this is a UUID for gore sets +static std::map GoreSets; // map from uuid to goreset -CGoreSet *FindGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { +CGoreSet *FindGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { return (*f).second; } return 0; } -CGoreSet *NewGoreSet() -{ - CGoreSet *ret=new CGoreSet(CurrentGoreSet++); - GoreSets[ret->mMyGoreSetTag]=ret; +CGoreSet *NewGoreSet() { + CGoreSet *ret = new CGoreSet(CurrentGoreSet++); + GoreSets[ret->mMyGoreSetTag] = ret; ret->mRefCount = 1; return ret; } -void DeleteGoreSet(int goreSetTag) -{ - std::map::iterator f=GoreSets.find(goreSetTag); - if (f!=GoreSets.end()) - { - if ( (*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0 ) - { +void DeleteGoreSet(int goreSetTag) { + std::map::iterator f = GoreSets.find(goreSetTag); + if (f != GoreSets.end()) { + if ((*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0) { delete (*f).second; GoreSets.erase(f); - } - else - { + } else { (*f).second->mRefCount--; } } } - -CGoreSet::~CGoreSet() -{ - std::multimap::iterator i; - for (i=mGoreRecords.begin();i!=mGoreRecords.end();++i) - { +CGoreSet::~CGoreSet() { + std::multimap::iterator i; + for (i = mGoreRecords.begin(); i != mGoreRecords.end(); ++i) { DeleteGoreRecord((*i).second.mGoreTag); } }; #endif // _SOF2 -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache); -class CTraceSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - model_t *currentModel; - int lod; - vec3_t rayStart; - vec3_t rayEnd; - CollisionRecord_t *collRecMap; - int entNum; - int modelIndex; - skin_t *skin; - shader_t *cust_shader; - size_t *TransformedVertsArray; - int traceFlags; - bool hitOne; - float m_fRadius; +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache); +class CTraceSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + model_t *currentModel; + int lod; + vec3_t rayStart; + vec3_t rayEnd; + CollisionRecord_t *collRecMap; + int entNum; + int modelIndex; + skin_t *skin; + shader_t *cust_shader; + size_t *TransformedVertsArray; + int traceFlags; + bool hitOne; + float m_fRadius; #ifdef _G2_GORE - //gore application thing - float ssize; - float tsize; - float theta; - int goreShader; - CGhoul2Info *ghoul2info; + // gore application thing + float ssize; + float tsize; + float theta; + int goreShader; + CGhoul2Info *ghoul2info; // Procedural-gore application things - SSkinGoreData *gore; + SSkinGoreData *gore; #endif - CTraceSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - int initlod, - vec3_t initrayStart, - vec3_t initrayEnd, - CollisionRecord_t *initcollRecMap, - int initentNum, - int initmodelIndex, - skin_t *initskin, - shader_t *initcust_shader, - size_t *initTransformedVertsArray, - int inittraceFlags, + CTraceSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, model_t *initcurrentModel, int initlod, vec3_t initrayStart, vec3_t initrayEnd, + CollisionRecord_t *initcollRecMap, int initentNum, int initmodelIndex, skin_t *initskin, shader_t *initcust_shader, + size_t *initTransformedVertsArray, int inittraceFlags, #ifdef _G2_GORE - float fRadius, - float initssize, - float inittsize, - float inittheta, - int initgoreShader, - CGhoul2Info *initghoul2info, - SSkinGoreData *initgore): + float fRadius, float initssize, float inittsize, float inittheta, int initgoreShader, CGhoul2Info *initghoul2info, SSkinGoreData *initgore) + : #else - float fRadius): + float fRadius) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - currentModel(initcurrentModel), - lod(initlod), - collRecMap(initcollRecMap), - entNum(initentNum), - modelIndex(initmodelIndex), - skin(initskin), - cust_shader(initcust_shader), - TransformedVertsArray(initTransformedVertsArray), - traceFlags(inittraceFlags), + surfaceNum(initsurfaceNum), rootSList(initrootSList), currentModel(initcurrentModel), lod(initlod), collRecMap(initcollRecMap), entNum(initentNum), + modelIndex(initmodelIndex), skin(initskin), cust_shader(initcust_shader), TransformedVertsArray(initTransformedVertsArray), + traceFlags(inittraceFlags), #ifdef _G2_GORE - m_fRadius(fRadius), - ssize(initssize), - tsize(inittsize), - theta(inittheta), - goreShader(initgoreShader), - ghoul2info(initghoul2info), - gore(initgore) + m_fRadius(fRadius), ssize(initssize), tsize(inittsize), theta(inittheta), goreShader(initgoreShader), ghoul2info(initghoul2info), gore(initgore) #else - m_fRadius(fRadius) + m_fRadius(fRadius) #endif { VectorCopy(initrayStart, rayStart); VectorCopy(initrayEnd, rayEnd); hitOne = false; } - }; // assorted Ghoul 2 functions. // list all surfaces associated with a model -void G2_List_Model_Surfaces(const char *fileName) -{ - int i, x; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - mdxmSurfHierarchy_t *surf; +void G2_List_Model_Surfaces(const char *fileName) { + int i, x; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + mdxmSurfHierarchy_t *surf; - surf = (mdxmSurfHierarchy_t *) ( (byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); mdxmSurface_t *surface = (mdxmSurface_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsLODs + sizeof(mdxmLOD_t)); - for ( x = 0 ; x < mod_m->mdxm->numSurfaces ; x++) - { - ri.Printf( PRINT_ALL, "Surface %i Name %s\n", x, surf->name); - if ( r_verbose->integer ) - { - ri.Printf( PRINT_ALL, "Num Descendants %i\n", surf->numChildren); - for (i=0; inumChildren; i++) - { - ri.Printf( PRINT_ALL, "Descendant %i\n", surf->childIndexes[i]); + for (x = 0; x < mod_m->mdxm->numSurfaces; x++) { + ri.Printf(PRINT_ALL, "Surface %i Name %s\n", x, surf->name); + if (r_verbose->integer) { + ri.Printf(PRINT_ALL, "Num Descendants %i\n", surf->numChildren); + for (i = 0; i < surf->numChildren; i++) { + ri.Printf(PRINT_ALL, "Descendant %i\n", surf->childIndexes[i]); } } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); - surface =(mdxmSurface_t *)( (byte *)surface + surface->ofsEnd ); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); + surface = (mdxmSurface_t *)((byte *)surface + surface->ofsEnd); } - } // list all bones associated with a model -void G2_List_Model_Bones(const char *fileName, int frame) -{ - int x, i; - mdxaSkel_t *skel; - mdxaSkelOffsets_t *offsets; - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); -// mdxaFrame_t *aframe=0; -// int frameSize; - mdxaHeader_t *header = mod_a->mdxa; +void G2_List_Model_Bones(const char *fileName, int frame) { + int x, i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + // mdxaFrame_t *aframe=0; + // int frameSize; + mdxaHeader_t *header = mod_a->mdxa; // figure out where the offset list is offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); -// frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); + // frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); -// aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); + // aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); // walk each bone and list it's name - for (x=0; x< mod_a->mdxa->numBones; x++) - { + for (x = 0; x < mod_a->mdxa->numBones; x++) { skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[x]); - ri.Printf( PRINT_ALL, "Bone %i Name %s\n", x, skel->name); + ri.Printf(PRINT_ALL, "Bone %i Name %s\n", x, skel->name); - ri.Printf( PRINT_ALL, "X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); + ri.Printf(PRINT_ALL, "X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); // if we are in verbose mode give us more details - if ( r_verbose->integer ) - { - ri.Printf( PRINT_ALL, "Num Descendants %i\n", skel->numChildren); - for (i=0; inumChildren; i++) - { - ri.Printf( PRINT_ALL, "Num Descendants %i\n", skel->numChildren); + if (r_verbose->integer) { + ri.Printf(PRINT_ALL, "Num Descendants %i\n", skel->numChildren); + for (i = 0; i < skel->numChildren; i++) { + ri.Printf(PRINT_ALL, "Num Descendants %i\n", skel->numChildren); } } } } - /************************************************************************************************ * G2_GetAnimFileName * obtain the .gla filename for a model @@ -341,103 +274,92 @@ void G2_List_Model_Bones(const char *fileName, int frame) * true if we successfully obtained a filename, false otherwise * ************************************************************************************************/ -qboolean G2_GetAnimFileName(const char *fileName, char **filename) -{ +qboolean G2_GetAnimFileName(const char *fileName, char **filename) { // find the model we want - model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); - if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) - { + if (mod && mod->mdxm && (mod->mdxm->animName[0] != 0)) { *filename = mod->mdxm->animName; return qtrue; } return qfalse; } - ///////////////////////////////////////////////////////////////////// // // Code for collision detection for models gameside // ///////////////////////////////////////////////////////////////////// -int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) -{ +int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) { int returnLod = useLod; - // if we are overriding the LOD at top level, then we can afford to only check this level of model - if (ghoul2.mLodBias > returnLod) - { - returnLod = ghoul2.mLodBias; - } -// assert(G2_MODEL_OK(&ghoul2)); + // if we are overriding the LOD at top level, then we can afford to only check this level of model + if (ghoul2.mLodBias > returnLod) { + returnLod = ghoul2.mLodBias; + } + // assert(G2_MODEL_OK(&ghoul2)); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - //what about r_lodBias? + // what about r_lodBias? // now ensure that we haven't selected a lod that doesn't exist for this model - if ( returnLod >= ghoul2.currentModel->mdxm->numLODs ) - { - returnLod = ghoul2.currentModel->mdxm->numLODs - 1; - } + if (returnLod >= ghoul2.currentModel->mdxm->numLODs) { + returnLod = ghoul2.currentModel->mdxm->numLODs - 1; + } return returnLod; } -void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray,CBoneCache *boneCache) -{ - int j, k; - mdxmVertex_t *v; - float *TransformedVerts; +void R_TransformEachSurface(const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray, CBoneCache *boneCache) { + int j, k; + mdxmVertex_t *v; + float *TransformedVerts; // // deform the vertexes by the lerped bones // - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); // alloc some space for the transformed verts to get put in TransformedVerts = (float *)G2VertSpace->MiniHeapAlloc(surface->numVerts * 5 * 4); TransformedVertsArray[surface->thisSurfaceIndex] = (size_t)TransformedVerts; - if (!TransformedVerts) - { + if (!TransformedVerts) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } // whip through and actually transform each vertex const int numVerts = surface->numVerts; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // optimisation issue - if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) - { - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// mdxmWeight_t *w; + if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) { + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } int pos = j * 5; @@ -449,38 +371,34 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } - } - else - { + } else { int pos = 0; - for ( j = 0; j < numVerts; j++ ) - { - vec3_t tempVert, tempNormal; -// const mdxmWeight_t *w; + for (j = 0; j < numVerts; j++) { + vec3_t tempVert, tempNormal; + // const mdxmWeight_t *w; - VectorClear( tempVert ); - VectorClear( tempNormal ); -// w = v->weights; + VectorClear(tempVert); + VectorClear(tempNormal); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); - const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + const mdxaBone_t &bone = EvalBoneCache(piBoneReferences[iBoneIndex], boneCache); - tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + tempVert[0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + tempVert[1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + tempVert[2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); - tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); - tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); - tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + tempNormal[0] += fBoneWeight * DotProduct(bone.matrix[0], v->normal); + tempNormal[1] += fBoneWeight * DotProduct(bone.matrix[1], v->normal); + tempNormal[2] += fBoneWeight * DotProduct(bone.matrix[2], v->normal); } // copy tranformed verts into temp space @@ -491,48 +409,43 @@ void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAl TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; TransformedVerts[pos++] = pTexCoords[j].texCoords[1]; - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; } } } -void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) -{ - int i; +void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, + IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) { + int i; assert(currentModel); assert(currentModel->mdxm); // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void*)currentModel, surfaceNum, lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { + if (!offFlags) { R_TransformEachSurface(surface, scale, G2VertSpace, TransformedVertArray, boneCache); } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { G2_TransformSurfaces(surfInfo->childIndexes[i], rootSList, boneCache, currentModel, lod, scale, G2VertSpace, TransformedVertArray, secondTimeAround); } } @@ -544,72 +457,59 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, IHeapAllocator *G2VertSpace, int useLod) #endif { - int i, lod; - vec3_t correctScale; - qboolean firstModelOnly = qfalse; + int i, lod; + vec3_t correctScale; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, ""); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe - if (!scale[0]) - { + if (!scale[0]) { correctScale[0] = 1.0; } - if (!scale[1]) - { + if (!scale[1]) { correctScale[1] = 1.0; } - if (!scale[2]) - { + if (!scale[2]) { correctScale[2] = 1.0; } // walk each possible model for this entity and try rendering it out - for (i=0; i=g.currentModel->numLods) - { + if (lod >= g.currentModel->numLods) { g.mTransformedVertsArray = 0; - if ( firstModelOnly ) - { + if (firstModelOnly) { // we don't really need to do multiple models for gore. return; } - //do the rest + // do the rest continue; } - } - else - { + } else { #endif lod = G2_DecideTraceLod(g, useLod); #ifdef _G2_GORE @@ -617,25 +517,22 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, #endif // give us space for the transformed vertex array to be put in - if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) - { //do not stomp if we're using zone space - g.mTransformedVertsArray = (size_t*)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof (size_t)); - if (!g.mTransformedVertsArray) - { + if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) { // do not stomp if we're using zone space + g.mTransformedVertsArray = (size_t *)G2VertSpace->MiniHeapAlloc(g.currentModel->mdxm->numSurfaces * sizeof(size_t)); + if (!g.mTransformedVertsArray) { Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); } } - memset(g.mTransformedVertsArray, 0,g.currentModel->mdxm->numSurfaces * sizeof (size_t)); + memset(g.mTransformedVertsArray, 0, g.currentModel->mdxm->numSurfaces * sizeof(size_t)); - G2_FindOverrideSurface(-1,g.mSlist); //reset the quick surface override lookup; + G2_FindOverrideSurface(-1, g.mSlist); // reset the quick surface override lookup; // recursively call the model surface transform - G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); + G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); #ifdef _G2_GORE - if (ApplyGore && firstModelOnly) - { + if (ApplyGore && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -643,11 +540,9 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, } } - // work out how much space a triangle takes -static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) -{ - vec3_t cross, ab, cb; +static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) { + vec3_t cross, ab, cb; VectorSubtract(A, B, ab); VectorSubtract(C, B, cb); @@ -657,43 +552,34 @@ static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) } // actually determine the S and T of the coordinate we hit in a given poly -static void G2_BuildHitPointST( const vec3_t A, const float SA, const float TA, - const vec3_t B, const float SB, const float TB, - const vec3_t C, const float SC, const float TC, - const vec3_t P, float *s, float *t,float &bary_i,float &bary_j) -{ - float areaABC = G2_AreaOfTri(A, B, C); +static void G2_BuildHitPointST(const vec3_t A, const float SA, const float TA, const vec3_t B, const float SB, const float TB, const vec3_t C, const float SC, + const float TC, const vec3_t P, float *s, float *t, float &bary_i, float &bary_j) { + float areaABC = G2_AreaOfTri(A, B, C); float i = G2_AreaOfTri(P, B, C) / areaABC; - bary_i=i; + bary_i = i; float j = G2_AreaOfTri(A, P, C) / areaABC; - bary_j=j; + bary_j = j; float k = G2_AreaOfTri(A, B, P) / areaABC; *s = SA * i + SB * j + SC * k; *t = TA * i + TB * j + TC * k; - *s=fmod(*s, 1); - if (*s< 0) - { - *s+= 1.0; + *s = fmod(*s, 1); + if (*s < 0) { + *s += 1.0; } - *t=fmod(*t, 1); - if (*t< 0) - { - *t+= 1.0; + *t = fmod(*t, 1); + if (*t < 0) { + *t += 1.0; } - } - // routine that works out given a ray whether or not it hits a poly -qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, - const vec3_t A, const vec3_t B, const vec3_t C, - qboolean backFaces,qboolean frontFaces,vec3_t returnedPoint,vec3_t returnedNormal, float *denom) -{ - static const float tiny=1E-10f; +qboolean G2_SegmentTriangleTest(const vec3_t start, const vec3_t end, const vec3_t A, const vec3_t B, const vec3_t C, qboolean backFaces, qboolean frontFaces, + vec3_t returnedPoint, vec3_t returnedNormal, float *denom) { + static const float tiny = 1E-10f; vec3_t returnedNormalT; vec3_t edgeAC; @@ -705,11 +591,11 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t ray; VectorSubtract(end, start, ray); - *denom=DotProduct(ray, returnedNormal); + *denom = DotProduct(ray, returnedNormal); - if (fabs(*denom)0)|| // not accepting back faces - (!frontFaces && *denom<0)) //not accepting front faces + if (fabs(*denom) < tiny || // triangle parallel to ray + (!backFaces && *denom > 0) || // not accepting back faces + (!frontFaces && *denom < 0)) // not accepting front faces { return qfalse; } @@ -717,10 +603,9 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t toPlane; VectorSubtract(A, start, toPlane); - float t=DotProduct(toPlane, returnedNormal)/ *denom; + float t = DotProduct(toPlane, returnedNormal) / *denom; - if (t<0.0f||t>1.0f) - { + if (t < 0.0f || t > 1.0f) { return qfalse; // off segment } @@ -740,324 +625,277 @@ qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, vec3_t temp; CrossProduct(edgePA, edgePB, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePC, edgePA, temp); - if (DotProduct(temp,returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } CrossProduct(edgePB, edgePC, temp); - if (DotProduct(temp, returnedNormal)<0.0f) - { + if (DotProduct(temp, returnedNormal) < 0.0f) { return qfalse; // off triangle } return qtrue; } #ifdef _G2_GORE -struct SVertexTemp -{ +struct SVertexTemp { int flags; int touch; int newindex; float tex[2]; - SVertexTemp() - { - touch=0; - } + SVertexTemp() { touch = 0; } }; #define MAX_GORE_VERTS (3000) static SVertexTemp GoreVerts[MAX_GORE_VERTS]; static int GoreIndexCopy[MAX_GORE_VERTS]; -static int GoreTouch=1; +static int GoreTouch = 1; #define MAX_GORE_INDECIES (6000) static int GoreIndecies[MAX_GORE_INDECIES]; #define GORE_MARGIN (0.0f) -int G2API_GetTime(int argTime); +int G2API_GetTime(int argTime); // now we at poly level, check each model space transformed poly against the model world transfomed ray -void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) -{ - int j; +void G2_GorePolys(const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + CrossProduct(TS.rayEnd, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(TS.rayEnd,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(TS.rayEnd, basis2, basis1); } - CrossProduct(TS.rayEnd,basis1,basis2); + CrossProduct(TS.rayEnd, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil - assert(DotProduct(basis1,basis1)>.0001f); - assert(DotProduct(basis2,basis2)>.0001f); + assert(DotProduct(basis1, basis1) > .0001f); + assert(DotProduct(basis2, basis2) > .0001f); VectorNormalize(basis1); VectorNormalize(basis2); - float c=cos(TS.theta); - float s=sin(TS.theta); + float c = cos(TS.theta); + float s = sin(TS.theta); - VectorScale(basis1,.5f*c/TS.tsize,taxis); - VectorMA(taxis,.5f*s/TS.tsize,basis2,taxis); + VectorScale(basis1, .5f * c / TS.tsize, taxis); + VectorMA(taxis, .5f * s / TS.tsize, basis2, taxis); - VectorScale(basis1,-.5f*s/TS.ssize,saxis); - VectorMA(saxis,.5f*c/TS.ssize,basis2,saxis); + VectorScale(basis1, -.5f * s / TS.ssize, saxis); + VectorMA(saxis, .5f * c / TS.ssize, basis2, saxis); float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; int numVerts = surface->numVerts; - int flags=15; - assert(numVertsGORE_MARGIN) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + float s = DotProduct(delta, saxis) + 0.5f; + float t = DotProduct(delta, taxis) + 0.5f; + int vflags = 0; + if (s > GORE_MARGIN) { + vflags |= 1; } - if (s<1.0f-GORE_MARGIN) - { - vflags|=2; + if (s < 1.0f - GORE_MARGIN) { + vflags |= 2; } - if (t>GORE_MARGIN) - { - vflags|=4; + if (t > GORE_MARGIN) { + vflags |= 4; } - if (t<1.0f-GORE_MARGIN) - { - vflags|=8; + if (t < 1.0f - GORE_MARGIN) { + vflags |= 8; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; - GoreVerts[j].tex[0]=s; - GoreVerts[j].tex[1]=t; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; + GoreVerts[j].tex[0] = s; + GoreVerts[j].tex[1] = t; } - if (flags) - { + if (flags) { return; // completely off the gore splotch. } - int numTris,newNumTris,newNumVerts; + int numTris, newNumTris, newNumVerts; numTris = surface->numTriangles; - mdxmTriangle_t *tris; - tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + mdxmTriangle_t *tris; + tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; - newNumTris=0; - newNumVerts=0; + newNumTris = 0; + newNumVerts = 0; GoreTouch++; - if (!TS.gore) - { + if (!TS.gore) { return; } - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 15 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; + if (flags) { continue; } - if (!TS.gore->frontFaces || !TS.gore->backFaces) - { + if (!TS.gore->frontFaces || !TS.gore->backFaces) { // we need to back/front face cull - vec3_t e1,e2,n; + vec3_t e1, e2, n; - VectorSubtract(&verts[tris[j].indexes[1]*5],&verts[tris[j].indexes[0]*5],e1); - VectorSubtract(&verts[tris[j].indexes[2]*5],&verts[tris[j].indexes[0]*5],e2); - CrossProduct(e1,e2,n); - if (DotProduct(TS.rayEnd,n)>0.0f) - { - if (!TS.gore->frontFaces) - { + VectorSubtract(&verts[tris[j].indexes[1] * 5], &verts[tris[j].indexes[0] * 5], e1); + VectorSubtract(&verts[tris[j].indexes[2] * 5], &verts[tris[j].indexes[0] * 5], e2); + CrossProduct(e1, e2, n); + if (DotProduct(TS.rayEnd, n) > 0.0f) { + if (!TS.gore->frontFaces) { continue; } - } - else - { - if (!TS.gore->backFaces) - { + } else { + if (!TS.gore->backFaces) { continue; } } - } int k; - assert(newNumTris*3+3,int>::iterator f=GoreTagsTemp.find(std::make_pair(goreModelIndex,TS.surfaceNum)); - if (f==GoreTagsTemp.end()) // need to generate a record + std::map, int>::iterator f = GoreTagsTemp.find(std::make_pair(goreModelIndex, TS.surfaceNum)); + if (f == GoreTagsTemp.end()) // need to generate a record { - newTag=AllocGoreRecord(); - CGoreSet *goreSet=0; - if (TS.ghoul2info->mGoreSetTag) - { - goreSet=FindGoreSet(TS.ghoul2info->mGoreSetTag); + newTag = AllocGoreRecord(); + CGoreSet *goreSet = 0; + if (TS.ghoul2info->mGoreSetTag) { + goreSet = FindGoreSet(TS.ghoul2info->mGoreSetTag); } - if (!goreSet) - { - goreSet=NewGoreSet(); - TS.ghoul2info->mGoreSetTag=goreSet->mMyGoreSetTag; + if (!goreSet) { + goreSet = NewGoreSet(); + TS.ghoul2info->mGoreSetTag = goreSet->mMyGoreSetTag; } assert(goreSet); SGoreSurface add; - add.shader=TS.goreShader; - add.mDeleteTime=0; - if (TS.gore->lifeTime) - { - add.mDeleteTime=G2API_GetTime(0) + TS.gore->lifeTime; + add.shader = TS.goreShader; + add.mDeleteTime = 0; + if (TS.gore->lifeTime) { + add.mDeleteTime = G2API_GetTime(0) + TS.gore->lifeTime; } add.mFadeTime = TS.gore->fadeOutTime; add.mFadeRGB = (TS.gore->fadeRGB != qfalse); add.mGoreTag = newTag; - add.mGoreGrowStartTime=G2API_GetTime(0); - if( TS.gore->growDuration == -1) - { - add.mGoreGrowEndTime = -1; // set this to -1 to disable growing - } - else - { + add.mGoreGrowStartTime = G2API_GetTime(0); + if (TS.gore->growDuration == -1) { + add.mGoreGrowEndTime = -1; // set this to -1 to disable growing + } else { add.mGoreGrowEndTime = G2API_GetTime(0) + TS.gore->growDuration; } assert(TS.gore->growDuration != 0); - add.mGoreGrowFactor = ( 1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); //curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; + add.mGoreGrowFactor = + (1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); // curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; - goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum,add)); - GoreTagsTemp[std::make_pair(goreModelIndex,TS.surfaceNum)]=newTag; + goreSet->mGoreRecords.insert(std::make_pair(TS.surfaceNum, add)); + GoreTagsTemp[std::make_pair(goreModelIndex, TS.surfaceNum)] = newTag; + } else { + newTag = (*f).second; } - else - { - newTag=(*f).second; - } - GoreTextureCoordinates *gore=FindGoreRecord(newTag); - if (gore) - { - assert(sizeof(float)==sizeof(int)); + GoreTextureCoordinates *gore = FindGoreRecord(newTag); + if (gore) { + assert(sizeof(float) == sizeof(int)); // data block format: - unsigned int size= - sizeof(int)+ // num verts - sizeof(int)+ // num tris - sizeof(int)*newNumVerts+ // which verts to copy from original surface - sizeof(float)*4*newNumVerts+ // storgage for deformed verts - sizeof(float)*4*newNumVerts+ // storgage for deformed normal - sizeof(float)*2*newNumVerts+ // texture coordinates - sizeof(int)*newNumTris*3; // new indecies + unsigned int size = sizeof(int) + // num verts + sizeof(int) + // num tris + sizeof(int) * newNumVerts + // which verts to copy from original surface + sizeof(float) * 4 * newNumVerts + // storgage for deformed verts + sizeof(float) * 4 * newNumVerts + // storgage for deformed normal + sizeof(float) * 2 * newNumVerts + // texture coordinates + sizeof(int) * newNumTris * 3; // new indecies - int *data=(int *)Z_Malloc ( sizeof(int)*size, TAG_GHOUL2_GORE, qtrue ); + int *data = (int *)Z_Malloc(sizeof(int) * size, TAG_GHOUL2_GORE, qtrue); - - if ( gore->tex[TS.lod] ) - { + if (gore->tex[TS.lod]) { Z_Free(gore->tex[TS.lod]); } - gore->tex[TS.lod]=(float *)data; - *data++=newNumVerts; - *data++=newNumTris; + gore->tex[TS.lod] = (float *)data; + *data++ = newNumVerts; + *data++ = newNumTris; - memcpy(data,GoreIndexCopy,sizeof(int)*newNumVerts); - data+=newNumVerts*9; // skip verts and normals - float *fdata=(float *)data; + memcpy(data, GoreIndexCopy, sizeof(int) * newNumVerts); + data += newNumVerts * 9; // skip verts and normals + float *fdata = (float *)data; - for (j=0;jtex[TS.lod])*sizeof(int)==size); + data = (int *)fdata; + memcpy(data, GoreIndecies, sizeof(int) * newNumTris * 3); + data += newNumTris * 3; + assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); fdata = (float *)data; // build the entity to gore matrix - VectorCopy(saxis,fdata+0); - VectorCopy(taxis,fdata+4); - VectorCopy(TS.rayEnd,fdata+8); - VectorNormalize(fdata+0); - VectorNormalize(fdata+4); - VectorNormalize(fdata+8); - fdata[3]=-0.5f; // subtract texture center - fdata[7]=-0.5f; - fdata[11]=0.0f; - vec3_t shotOriginInCurrentSpace; // unknown space - TransformPoint(TS.rayStart,shotOriginInCurrentSpace,(mdxaBone_t *)fdata); // dest middle arg + VectorCopy(saxis, fdata + 0); + VectorCopy(taxis, fdata + 4); + VectorCopy(TS.rayEnd, fdata + 8); + VectorNormalize(fdata + 0); + VectorNormalize(fdata + 4); + VectorNormalize(fdata + 8); + fdata[3] = -0.5f; // subtract texture center + fdata[7] = -0.5f; + fdata[11] = 0.0f; + vec3_t shotOriginInCurrentSpace; // unknown space + TransformPoint(TS.rayStart, shotOriginInCurrentSpace, (mdxaBone_t *)fdata); // dest middle arg // this will insure the shot origin in our unknown space is now the shot origin, making it a known space - fdata[3]-=shotOriginInCurrentSpace[0]; - fdata[7]-=shotOriginInCurrentSpace[1]; - fdata[11]-=shotOriginInCurrentSpace[2]; - Inverse_Matrix((mdxaBone_t *)fdata,(mdxaBone_t *)(fdata+12)); // dest 2nd arg - data+=24; + fdata[3] -= shotOriginInCurrentSpace[0]; + fdata[7] -= shotOriginInCurrentSpace[1]; + fdata[11] -= shotOriginInCurrentSpace[2]; + Inverse_Matrix((mdxaBone_t *)fdata, (mdxaBone_t *)(fdata + 12)); // dest 2nd arg + data += 24; -// assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); + // assert((data - (int *)gore->tex[TS.lod]) * sizeof(int) == size); } } #else -struct SVertexTemp -{ +struct SVertexTemp { int flags; -// int touch; -// int newindex; -// float tex[2]; - SVertexTemp() - { -// touch=0; + // int touch; + // int newindex; + // float tex[2]; + SVertexTemp() { + // touch=0; } }; @@ -1066,44 +904,37 @@ static SVertexTemp GoreVerts[MAX_GORE_VERTS]; #endif // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) -{ - int j, numTris; +static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) { + int j, numTris; // whip through and actually transform each vertex - const mdxmTriangle_t *tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); const float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; numTris = surface->numTriangles; - for ( j = 0; j < numTris; j++ ) - { - float face; - vec3_t hitPoint, normal; + for (j = 0; j < numTris; j++) { + float face; + vec3_t hitPoint, normal; // determine actual coords for this triangle const float *point1 = &verts[(tris[j].indexes[0] * 5)]; const float *point2 = &verts[(tris[j].indexes[1] * 5)]; const float *point3 = &verts[(tris[j].indexes[2] * 5)]; // did we hit it? int i; - if (G2_SegmentTriangleTest(TS.rayStart, TS.rayEnd, point1, point2, point3, qtrue, qtrue, hitPoint, normal, &face)) - { // find space in the collision records for this record - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; - if (face>0) - { + if (face > 0) { newCol.mFlags = G2_FRONTFACE; - } - else - { + } else { newCol.mFlags = G2_BACKFACE; } @@ -1120,62 +951,61 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ newCol.mMaterial = newCol.mLocation = 0; // Determine our location within the texture, and barycentric coordinates - G2_BuildHitPointST(point1, point1[3], point1[4], - point2, point2[3], point2[4], - point3, point3[3], point3[4], - hitPoint, &x_pos, &y_pos,newCol.mBarycentricI,newCol.mBarycentricJ); - -/* - const shader_t *shader = 0; - // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit location and hit material info - if ( cust_shader ) - { - shader = cust_shader; - } - else if ( skin ) - { - int j; - - // match the surface name to something in the skin file - shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { - // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = skin->surfaces[j]->shader; - break; - } - } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); - } - - // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little point - if ((shader->hitLocation) || (shader->hitMaterial)) - { - // ok, we have a floating point position. - determine location in data we need to look at - if (shader->hitLocation) - { - newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + - ((int)(y_pos * hitMatReg[shader->hitLocation].height) * hitMatReg[shader->hitLocation].width) + - ((int)(x_pos * hitMatReg[shader->hitLocation].width))); - ri.Printf( PRINT_ALL, "G2_TracePolys hit location: %d\n", newCol.mLocation); - } - - if (shader->hitMaterial) - { - newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + - ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * hitMatReg[shader->hitMaterial].width) + - ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); - } - } -*/ + G2_BuildHitPointST(point1, point1[3], point1[4], point2, point2[3], point2[4], point3, point3[3], point3[4], hitPoint, &x_pos, &y_pos, + newCol.mBarycentricI, newCol.mBarycentricJ); + + /* + const shader_t *shader = 0; + // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit + location and hit material info if ( cust_shader ) + { + shader = cust_shader; + } + else if ( skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little + point if ((shader->hitLocation) || (shader->hitMaterial)) + { + // ok, we have a floating point position. - determine location in data we need to look at + if (shader->hitLocation) + { + newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + + ((int)(y_pos * hitMatReg[shader->hitLocation].height) * + hitMatReg[shader->hitLocation].width) + + ((int)(x_pos * hitMatReg[shader->hitLocation].width))); + ri.Printf( PRINT_ALL, "G2_TracePolys hit location: %d\n", newCol.mLocation); + } + + if (shader->hitMaterial) + { + newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + + ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * + hitMatReg[shader->hitMaterial].width) + + ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); + } + } + */ // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } @@ -1183,12 +1013,11 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen - //It happens. And the assert is bugging me. - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen + // It happens. And the assert is bugging me. + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1196,148 +1025,126 @@ static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_ } // now we're at poly level, check each model space transformed poly against the model world transfomed ray -static bool G2_RadiusTracePolys( - const mdxmSurface_t *surface, - CTraceSurface &TS - ) -{ - int j; +static bool G2_RadiusTracePolys(const mdxmSurface_t *surface, CTraceSurface &TS) { + int j; vec3_t basis1; vec3_t basis2; vec3_t taxis; vec3_t saxis; - basis2[0]=0.0f; - basis2[1]=0.0f; - basis2[2]=1.0f; + basis2[0] = 0.0f; + basis2[1] = 0.0f; + basis2[2] = 1.0f; vec3_t v3RayDir; VectorSubtract(TS.rayEnd, TS.rayStart, v3RayDir); - CrossProduct(v3RayDir,basis2,basis1); + CrossProduct(v3RayDir, basis2, basis1); - if (DotProduct(basis1,basis1)<.1f) - { - basis2[0]=0.0f; - basis2[1]=1.0f; - basis2[2]=0.0f; - CrossProduct(v3RayDir,basis2,basis1); + if (DotProduct(basis1, basis1) < .1f) { + basis2[0] = 0.0f; + basis2[1] = 1.0f; + basis2[2] = 0.0f; + CrossProduct(v3RayDir, basis2, basis1); } - CrossProduct(v3RayDir,basis1,basis2); + CrossProduct(v3RayDir, basis1, basis2); // Give me a shot direction not a bunch of zeros :) -Gil -// assert(DotProduct(basis1,basis1)>.0001f); -// assert(DotProduct(basis2,basis2)>.0001f); + // assert(DotProduct(basis1,basis1)>.0001f); + // assert(DotProduct(basis2,basis2)>.0001f); VectorNormalize(basis1); VectorNormalize(basis2); - const float c=cos(0.0f);//theta - const float s=sin(0.0f);//theta + const float c = cos(0.0f); // theta + const float s = sin(0.0f); // theta - VectorScale(basis1, 0.5f * c / TS.m_fRadius,taxis); - VectorMA(taxis, 0.5f * s / TS.m_fRadius,basis2,taxis); + VectorScale(basis1, 0.5f * c / TS.m_fRadius, taxis); + VectorMA(taxis, 0.5f * s / TS.m_fRadius, basis2, taxis); - VectorScale(basis1,-0.5f * s /TS.m_fRadius,saxis); - VectorMA( saxis, 0.5f * c /TS.m_fRadius,basis2,saxis); + VectorScale(basis1, -0.5f * s / TS.m_fRadius, saxis); + VectorMA(saxis, 0.5f * c / TS.m_fRadius, basis2, saxis); - const float * const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + const float *const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; const int numVerts = surface->numVerts; - int flags=63; - //rayDir/=lengthSquared(raydir); + int flags = 63; + // rayDir/=lengthSquared(raydir); const float f = VectorLengthSquared(v3RayDir); - v3RayDir[0]/=f; - v3RayDir[1]/=f; - v3RayDir[2]/=f; + v3RayDir[0] /= f; + v3RayDir[1] /= f; + v3RayDir[2] /= f; - for ( j = 0; j < numVerts; j++ ) - { - const int pos=j*5; + for (j = 0; j < numVerts; j++) { + const int pos = j * 5; vec3_t delta; - delta[0]=verts[pos+0]-TS.rayStart[0]; - delta[1]=verts[pos+1]-TS.rayStart[1]; - delta[2]=verts[pos+2]-TS.rayStart[2]; - const float s=DotProduct(delta,saxis)+0.5f; - const float t=DotProduct(delta,taxis)+0.5f; - const float u=DotProduct(delta,v3RayDir); - int vflags=0; - - if (s>0) - { - vflags|=1; + delta[0] = verts[pos + 0] - TS.rayStart[0]; + delta[1] = verts[pos + 1] - TS.rayStart[1]; + delta[2] = verts[pos + 2] - TS.rayStart[2]; + const float s = DotProduct(delta, saxis) + 0.5f; + const float t = DotProduct(delta, taxis) + 0.5f; + const float u = DotProduct(delta, v3RayDir); + int vflags = 0; + + if (s > 0) { + vflags |= 1; } - if (s<1) - { - vflags|=2; + if (s < 1) { + vflags |= 2; } - if (t>0) - { - vflags|=4; + if (t > 0) { + vflags |= 4; } - if (t<1) - { - vflags|=8; + if (t < 1) { + vflags |= 8; } - if (u>0) - { - vflags|=16; + if (u > 0) { + vflags |= 16; } - if (u<1) - { - vflags|=32; + if (u < 1) { + vflags |= 32; } - vflags=(~vflags); - flags&=vflags; - GoreVerts[j].flags=vflags; + vflags = (~vflags); + flags &= vflags; + GoreVerts[j].flags = vflags; } - if (flags) - { + if (flags) { return false; // completely off the gore splotch (so presumably hit nothing? -Ste) } const int numTris = surface->numTriangles; - const mdxmTriangle_t * const tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const mdxmTriangle_t *const tris = (mdxmTriangle_t *)((byte *)surface + surface->ofsTriangles); - for ( j = 0; j < numTris; j++ ) - { - assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]= 0 && tris[j].indexes[0] < numVerts); + assert(tris[j].indexes[1] >= 0 && tris[j].indexes[1] < numVerts); + assert(tris[j].indexes[2] >= 0 && tris[j].indexes[2] < numVerts); + flags = 63 & GoreVerts[tris[j].indexes[0]].flags & GoreVerts[tris[j].indexes[1]].flags & GoreVerts[tris[j].indexes[2]].flags; int i; - if (flags) - { + if (flags) { continue; - } - else - { + } else { // we hit a triangle, so init a collision record... // - for (i=0; ithisSurfaceIndex; newCol.mModelIndex = TS.modelIndex; -// if (face>0) -// { - newCol.mFlags = G2_FRONTFACE; -// } -// else -// { -// newCol.mFlags = G2_BACKFACE; -// } - - //get normal from triangle + // if (face>0) + // { + newCol.mFlags = G2_FRONTFACE; + // } + // else + // { + // newCol.mFlags = G2_BACKFACE; + // } + + // get normal from triangle const float *A = &verts[(tris[j].indexes[0] * 5)]; const float *B = &verts[(tris[j].indexes[1] * 5)]; const float *C = &verts[(tris[j].indexes[2] * 5)]; @@ -1354,28 +1161,26 @@ static bool G2_RadiusTracePolys( newCol.mMaterial = newCol.mLocation = 0; // exit now if we should - if (TS.traceFlags == G2_RETURNONHIT) - { + if (TS.traceFlags == G2_RETURNONHIT) { TS.hitOne = true; return true; } - - vec3_t distVect; + vec3_t distVect; #if 0 //i don't know the hitPoint, but let's just assume it's the first vert for now... float *hitPoint = (float *)A; #else - //yeah, I want the collision point. Let's work out the impact point on the triangle. -rww + // yeah, I want the collision point. Let's work out the impact point on the triangle. -rww vec3_t hitPoint; float side, side2; float dist; - float third = -(A[0]*(B[1]*C[2] - C[1]*B[2]) + B[0]*(C[1]*A[2] - A[1]*C[2]) + C[0]*(A[1]*B[2] - B[1]*A[2]) ); + float third = -(A[0] * (B[1] * C[2] - C[1] * B[2]) + B[0] * (C[1] * A[2] - A[1] * C[2]) + C[0] * (A[1] * B[2] - B[1] * A[2])); VectorSubtract(TS.rayEnd, TS.rayStart, distVect); - side = normal[0]*TS.rayStart[0] + normal[1]*TS.rayStart[1] + normal[2]*TS.rayStart[2] + third; - side2 = normal[0]*distVect[0] + normal[1]*distVect[1] + normal[2]*distVect[2]; - dist = side/side2; + side = normal[0] * TS.rayStart[0] + normal[1] * TS.rayStart[1] + normal[2] * TS.rayStart[2] + third; + side2 = normal[0] * distVect[0] + normal[1] * distVect[1] + normal[2] * distVect[2]; + dist = side / side2; VectorMA(TS.rayStart, -dist, distVect, hitPoint); #endif @@ -1388,11 +1193,10 @@ static bool G2_RadiusTracePolys( break; } } - if (i==MAX_G2_COLLISIONS) - { - //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN - TS.hitOne = true; //force stop recursion - return true; // return true to avoid wasting further time, but no hit will result without a record + if (i == MAX_G2_COLLISIONS) { + // assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN + TS.hitOne = true; // force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record } } } @@ -1400,24 +1204,21 @@ static bool G2_RadiusTracePolys( return false; } - // look at a surface and then do the trace on each poly -static void G2_TraceSurfaces(CTraceSurface &TS) -{ - int i; +static void G2_TraceSurfaces(CTraceSurface &TS) { + int i; // back track and get the surfinfo struct for this surface assert(TS.currentModel); assert(TS.currentModel->mdxm); - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); // don't allow recursion if we've already hit a polygon - if (TS.hitOne) - { + if (TS.hitOne) { return; } @@ -1425,39 +1226,28 @@ static void G2_TraceSurfaces(CTraceSurface &TS) int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, try to hit it - if (!offFlags) - { + if (!offFlags) { #ifdef _G2_GORE - if (TS.collRecMap) - { + if (TS.collRecMap) { #endif - if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace + if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace { // .. then use radius check // - if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, - TS - ) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, + TS) && + (TS.traceFlags == G2_RETURNONHIT)) { TS.hitOne = true; return; } - } - else - { + } else { // go away and trace the polys in this surface - if (G2_TracePolys(surface, surfInfo, TS) - && (TS.traceFlags == G2_RETURNONHIT) - ) - { + if (G2_TracePolys(surface, surfInfo, TS) && (TS.traceFlags == G2_RETURNONHIT)) { // ok, we hit one, *and* we want to return instantly because the returnOnHit is set // so indicate we've hit one, so other surfaces don't get hit and return TS.hitOne = true; @@ -1465,124 +1255,108 @@ static void G2_TraceSurfaces(CTraceSurface &TS) } } #ifdef _G2_GORE - } - else - { + } else { G2_GorePolys(surface, TS, surfInfo); } #endif } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren && !TS.hitOne; i++) - { + for (i = 0; i < surfInfo->numChildren && !TS.hitOne; i++) { TS.surfaceNum = surfInfo->childIndexes[i]; G2_TraceSurfaces(TS); } } #ifdef _G2_GORE -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius, float ssize,float tsize,float theta,int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius, float ssize, float tsize, float theta, int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) #else -void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius) +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, + float fRadius) #endif { - int i, lod; - skin_t *skin; - shader_t *cust_shader; - qboolean firstModelOnly = qfalse; + int i, lod; + skin_t *skin; + shader_t *cust_shader; + qboolean firstModelOnly = qfalse; #ifdef _G2_GORE - if ( cg_g2MarksAllModels == NULL ) - { - cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); + if (cg_g2MarksAllModels == NULL) { + cg_g2MarksAllModels = ri.Cvar_Get("cg_g2MarksAllModels", "0", 0, ""); } - if (cg_g2MarksAllModels == NULL - || !cg_g2MarksAllModels->integer ) - { + if (cg_g2MarksAllModels == NULL || !cg_g2MarksAllModels->integer) { firstModelOnly = qtrue; } #endif // walk each possible model for this entity and try tracing against it - for (i=0; i 0 && ghoul2[i].mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( ghoul2[i].mSkin ); - } - else - { + if (ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(ghoul2[i].mSkin); + } else { skin = NULL; } - lod = G2_DecideTraceLod(ghoul2[i],useLod); + lod = G2_DecideTraceLod(ghoul2[i], useLod); #ifdef _G2_GORE - if ( skipIfLODNotMatch ) - {//we only want to hit this SPECIFIC LOD... - if ( lod != useLod ) - {//doesn't match, skip this model + if (skipIfLODNotMatch) { // we only want to hit this SPECIFIC LOD... + if (lod != useLod) { // doesn't match, skip this model continue; } } #endif - //reset the quick surface override lookup + // reset the quick surface override lookup G2_FindOverrideSurface(-1, ghoul2[i].mSlist); #ifdef _G2_GORE - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); #else - CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, + cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); #endif // start the surface recursion loop G2_TraceSurfaces(TS); // if we've hit one surface on one model, don't bother doing the rest - if (TS.hitOne) - { + if (TS.hitOne) { break; } #ifdef _G2_GORE - if (!collRecMap&&firstModelOnly) - { + if (!collRecMap && firstModelOnly) { // we don't really need to do multiple models for gore. break; } @@ -1590,29 +1364,25 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli } } -void TransformPoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2]; +void TransformPoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2]; } } -void TransformAndTranslatePoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { +void TransformAndTranslatePoint(const vec3_t in, vec3_t out, mdxaBone_t *mat) { - for (int i=0;i<3;i++) - { - out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2] + mat->matrix[i][3]; + for (int i = 0; i < 3; i++) { + out[i] = in[0] * mat->matrix[i][0] + in[1] * mat->matrix[i][1] + in[2] * mat->matrix[i][2] + mat->matrix[i][3]; } } - // create a matrix using a set of angles -void Create_Matrix(const float *angle, mdxaBone_t *matrix) -{ - matrix3_t axis; +void Create_Matrix(const float *angle, mdxaBone_t *matrix) { + matrix3_t axis; // convert angles to axis - AnglesToAxis( angle, axis ); + AnglesToAxis(angle, axis); matrix->matrix[0][0] = axis[0][0]; matrix->matrix[1][0] = axis[0][1]; matrix->matrix[2][0] = axis[0][2]; @@ -1628,35 +1398,27 @@ void Create_Matrix(const float *angle, mdxaBone_t *matrix) matrix->matrix[0][3] = 0; matrix->matrix[1][3] = 0; matrix->matrix[2][3] = 0; - - } // given a matrix, generate the inverse of that matrix -void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) -{ +void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) { int i, j; - for (i = 0; i < 3; i++) - { - for (j = 0; j < 3; j++) - { - dest->matrix[i][j]=src->matrix[j][i]; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + dest->matrix[i][j] = src->matrix[j][i]; } } - for (i = 0; i < 3; i++) - { - dest->matrix[i][3]=0; - for (j = 0; j < 3; j++) - { - dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + for (i = 0; i < 3; i++) { + dest->matrix[i][3] = 0; + for (j = 0; j < 3; j++) { + dest->matrix[i][3] -= dest->matrix[i][j] * src->matrix[j][3]; } } } // generate the world matrix for a given set of angles and origin - called from lots of places -void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) -{ +void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) { Create_Matrix(angles, &worldMatrix); worldMatrix.matrix[0][3] = origin[0]; worldMatrix.matrix[1][3] = origin[1]; @@ -1666,18 +1428,16 @@ void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) } // go away and determine what the pointer for a specific surface definition within the model definition is -void *G2_FindSurface(void *mod_t, int index, int lod) -{ +void *G2_FindSurface(void *mod_t, int index, int lod) { // damn include file dependancies - model_t *mod = (model_t *)mod_t; + model_t *mod = (model_t *)mod_t; // point at first lod list - byte *current = (byte*)((size_t)mod->mdxm + (size_t)mod->mdxm->ofsLODs); + byte *current = (byte *)((size_t)mod->mdxm + (size_t)mod->mdxm->ofsLODs); int i; - //walk the lods - for (i=0; iofsEnd; } @@ -1692,16 +1452,14 @@ void *G2_FindSurface(void *mod_t, int index, int lod) return (void *)current; } -#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) +#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) #define BOLT_SAVE_BLOCK_SIZE (sizeof(boltInfo_t) - sizeof(mdxaBone_t)) #define BONE_SAVE_BLOCK_SIZE sizeof(boneInfo_t) -qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) -{ +qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) { // is there anything to save? - if (!ghoul2.size()) - { + if (!ghoul2.size()) { *buffer = (char *)Z_Malloc(4, TAG_GHOUL2, qtrue); int *tempBuffer = (int *)*buffer; *tempBuffer = 0; @@ -1719,8 +1477,7 @@ qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) *size += 4; // start out working out the total size of the buffer we need to allocate int i; // Linux GCC is forcing new scoping rules - for (i=0; i i) && - (nextGhoul2[i].mModelindex != -1) && - (nextGhoul2[i].mBlist.size() > x) && - (nextGhoul2[i].mBlist[x].boneNumber != -1)) - { - boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; + if ((nextGhoul2.size() > i) && (nextGhoul2[i].mModelindex != -1) && (nextGhoul2[i].mBlist.size() > x) && + (nextGhoul2[i].mBlist[x].boneNumber != -1)) { + boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; // does this bone override actually have anything in it, and if it does, is it a bone angles override? - if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) - { - float *nowMatrix = (float*) &bone.matrix; - float *nextMatrix = (float*) &nextBone.matrix; - float *newMatrix = (float*) &bone.newMatrix; + if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) { + float *nowMatrix = (float *)&bone.matrix; + float *nextMatrix = (float *)&nextBone.matrix; + float *newMatrix = (float *)&bone.newMatrix; // now interpolate the matrix - for (int z=0; z < 12; z++) - { - newMatrix[z] = nowMatrix[z] + interpolation * ( nextMatrix[z] - nowMatrix[z] ); + for (int z = 0; z < 12; z++) { + newMatrix[z] = nowMatrix[z] + interpolation * (nextMatrix[z] - nowMatrix[z]); } } - } - else - { + } else { memcpy(&ghoul2[i].mBlist[x].newMatrix, &ghoul2[i].mBlist[x].matrix, sizeof(mdxaBone_t)); } } diff --git a/codemp/rd-vanilla/G2_surfaces.cpp b/codemp/rd-vanilla/G2_surfaces.cpp index 2019e09440..f7800642ab 100644 --- a/codemp/rd-vanilla/G2_surfaces.cpp +++ b/codemp/rd-vanilla/G2_surfaces.cpp @@ -25,43 +25,30 @@ along with this program; if not, see . #include "ghoul2/g2_local.h" #include "tr_local.h" -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - boneInfo_v &initboneList): - - surfaceNum(initsurfaceNum), - boneUsedList(initboneUsedList), - rootSList(initrootSList), - currentModel(initcurrentModel), - boneList(initboneList) { } +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; + + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : + + surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; extern void G2_ConstructUsedBoneList(CConstructBoneList &CBL); - //===================================================================================================================== // Surface List handling routines - so entities can determine what surfaces attached to a model are operational or not. // find a particular surface in the surface override list -surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) -{ +surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) { // look through entire list - for(size_t i=0; imdxm + mod_m->mdxm->ofsSurfHierarchy ); + surf = (mdxmSurfHierarchy_t *)((byte *)mod_m->mdxm + mod_m->mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mod_m->mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surf->name)) - { + for (int i = 0; i < mod_m->mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surf->name)) { *flags = surf->flags; return i; } // find the next surface - surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surf = (mdxmSurfHierarchy_t *)((byte *)surf + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surf->numChildren])); } return -1; } - /************************************************************************************************ * G2_FindSurface * find a surface in a ghoul2 surface override list based on it's name @@ -103,41 +86,33 @@ int G2_IsSurfaceLegal(void *mod, const char *surfaceName, int *flags) * pointer to surface if successful, false otherwise * ************************************************************************************************/ -mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, - int *surfIndex/*NULL*/) -{ - int i = 0; +mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, int *surfIndex /*NULL*/) { + int i = 0; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo; + mdxmSurfHierarchy_t *surfInfo; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { assert(0); - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } - // first find if we already have this surface in the list - for (i = slist.size() - 1; i >= 0; i--) - { - if ((slist[i].surface != 10000) && (slist[i].surface != -1)) - { - mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); + // first find if we already have this surface in the list + for (i = slist.size() - 1; i >= 0; i--) { + if ((slist[i].surface != 10000) && (slist[i].surface != -1)) { + mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); // back track and get the surfinfo struct for this surface surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); - // are these the droids we're looking for? - if (!Q_stricmp (surfInfo->name, surfaceName)) - { + // are these the droids we're looking for? + if (!Q_stricmp(surfInfo->name, surfaceName)) { // yup - if (surfIndex) - { + if (surfIndex) { *surfIndex = i; } return surf; @@ -145,33 +120,29 @@ mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const } } // didn't find it - if (surfIndex) - { + if (surfIndex) { *surfIndex = -1; } return 0; } // set a named surface offFlags - if it doesn't find a surface with this name in the list then it will add one. -qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) -{ - int surfIndex = -1; - surfaceInfo_t temp_slist_entry; - mdxmSurface_t *surf; +qboolean G2_SetSurfaceOnOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) { + int surfIndex = -1; + surfaceInfo_t temp_slist_entry; + mdxmSurface_t *surf; // find the model we want - model_t *mod = (model_t *)ghlInfo->currentModel; + model_t *mod = (model_t *)ghlInfo->currentModel; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { assert(0); return qfalse; } - // first find if we already have this surface in the list + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value // slist[surfIndex].offFlags = offFlags; @@ -180,21 +151,17 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c slist[surfIndex].offFlags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); slist[surfIndex].offFlags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); return qtrue; - } - else - { + } else { // ok, not in the list already - in that case, lets verify this surface exists in the model mesh - int flags; - int surfaceNum = G2_IsSurfaceLegal((void*)mod, surfaceName, &flags); - if (surfaceNum != -1) - { + int flags; + int surfaceNum = G2_IsSurfaceLegal((void *)mod, surfaceName, &flags); + if (surfaceNum != -1) { int newflags = flags; // the only bit we really care about in the incoming flags is the off bit newflags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); newflags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); - if (newflags != flags) - { // insert here then because it changed, no need to add an override otherwise + if (newflags != flags) { // insert here then because it changed, no need to add an override otherwise temp_slist_entry.offFlags = newflags; temp_slist_entry.surface = surfaceNum; @@ -206,26 +173,22 @@ qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const c return qfalse; } -void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) -{ +void G2_SetSurfaceOnOffFromSkin(CGhoul2Info *ghlInfo, qhandle_t renderSkin) { int j; - const skin_t *skin = R_GetSkinByHandle( renderSkin ); + const skin_t *skin = R_GetSkinByHandle(renderSkin); - ghlInfo->mSlist.clear(); //remove any overrides we had before. + ghlInfo->mSlist.clear(); // remove any overrides we had before. ghlInfo->mMeshFrameNum = 0; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) - { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - //FIXME: why is this using the shader name and not the surface name? - if ( !strcmp( ((shader_t *)skin->surfaces[j]->shader)->name, "*off") ) { + // FIXME: why is this using the shader name and not the surface name? + if (!strcmp(((shader_t *)skin->surfaces[j]->shader)->name, "*off")) { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, G2SURFACEFLAG_OFF); - } - else - { - int flags; + } else { + int flags; int surfaceNum = G2_IsSurfaceLegal((void *)ghlInfo->currentModel, skin->surfaces[j]->name, &flags); - if ( (surfaceNum != -1) && (!(flags&G2SURFACEFLAG_OFF)) ) //only turn on if it's not an "_off" surface + if ((surfaceNum != -1) && (!(flags & G2SURFACEFLAG_OFF))) // only turn on if it's not an "_off" surface { G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, 0); } @@ -234,105 +197,86 @@ void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) } // return a named surfaces off flags - should tell you if this surface is on or off. -int G2_IsSurfaceOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int surfIndex = -1; - mdxmSurface_t *surf = 0; +int G2_IsSurfaceOff(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int surfIndex = -1; + mdxmSurface_t *surf = 0; // did we find a ghoul 2 model or not? - if (!mod->mdxm) - { + if (!mod->mdxm) { return 0; } - // first find if we already have this surface in the list + // first find if we already have this surface in the list surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value return slist[surfIndex].offFlags; } // ok, we didn't find it in the surface list. Lets look at the original surface then. - mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *) ( (byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy ); + mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *)((byte *)mod->mdxm + mod->mdxm->ofsSurfHierarchy); - for ( int i = 0 ; i < mod->mdxm->numSurfaces ; i++) - { - if (!Q_stricmp(surfaceName, surface->name)) - { + for (int i = 0; i < mod->mdxm->numSurfaces; i++) { + if (!Q_stricmp(surfaceName, surface->name)) { return surface->flags; } // find the next surface - surface = (mdxmSurfHierarchy_t *)( (byte *)surface + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surface->numChildren ] )); + surface = (mdxmSurfHierarchy_t *)((byte *)surface + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surface->numChildren])); } assert(0); return 0; } -void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) -{ - int i; - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); +void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) { + int i; + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); // really, we should use the default flags for this surface unless it's been overriden int offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, indicate as such in the active surface list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { + if (!(offFlags & G2SURFACEFLAG_OFF)) { activeSurfaces[surfaceNum] = 1; - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { surfaceNum = surfInfo->childIndexes[i]; G2_FindRecursiveSurface(currentModel, surfaceNum, rootList, activeSurfaces); } - } -void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) -{ +void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) { // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore - for (size_t i=0; imdxm) - { + if (!mod_m->mdxm) { return qfalse; } // first find if we already have this surface in the list surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) - { + if (surf != -1) { // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) - { + if (ghoul2[modelIndex].mSurfaceRoot == surf) { return qtrue; } @@ -382,11 +322,7 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, activeBones, ghoul2[modelIndex].mSlist, mod_m, ghoul2[modelIndex].mBlist); G2_ConstructUsedBoneList(CBL); @@ -400,24 +336,20 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model if (((int)ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) - { + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) { CGhoul2Info_v *g2i = &ghoul2; G2API_RemoveGhoul2Model((CGhoul2Info_v **)&g2i, i); } } } - //No support for this, for now. + // No support for this, for now. // remember to free what we used Z_Free(activeSurfaces); @@ -425,97 +357,95 @@ qboolean G2_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const ch return (qtrue); } -/* -//g2r if (entstate->ghoul2) - { - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); - model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); - model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); - int surf; - int flags; - int *activeSurfaces, *activeBones; - - // did we find a ghoul 2 model or not? - if (!mod_m->mdxm) + /* + //g2r if (entstate->ghoul2) { - return qfalse; - } - - // first find if we already have this surface in the list - surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); - if (surf != -1) - { - // first see if this ghoul2 model already has this as a root surface - if (ghoul2[modelIndex].mSurfaceRoot == surf) + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int surf; + int flags; + int *activeSurfaces, *activeBones; + + // did we find a ghoul 2 model or not? + if (!mod_m->mdxm) { - return qtrue; + return qfalse; } - // set the root surface - ghoul2[modelIndex].mSurfaceRoot = surf; + // first find if we already have this surface in the list + surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); + if (surf != -1) + { + // first see if this ghoul2 model already has this as a root surface + if (ghoul2[modelIndex].mSurfaceRoot == surf) + { + return qtrue; + } + + // set the root surface + ghoul2[modelIndex].mSurfaceRoot = surf; - // ok, now the tricky bits. - // firstly, generate a list of active / on surfaces below the root point + // ok, now the tricky bits. + // firstly, generate a list of active / on surfaces below the root point - // gimme some space to put this list into - activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); - memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); - activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); - memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); + // gimme some space to put this list into + activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); + memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); + activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); + memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); - G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); + G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); - // now generate the used bone list - CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, - activeBones, - ghoul2[modelIndex].mSlist, - mod_m, - ghoul2[modelIndex].mBlist); + // now generate the used bone list + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, + activeBones, + ghoul2[modelIndex].mSlist, + mod_m, + ghoul2[modelIndex].mBlist); - G2_ConstructUsedBoneList(CBL); + G2_ConstructUsedBoneList(CBL); - // now remove all procedural or override surfaces that refer to surfaces that arent on this list - G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); + // now remove all procedural or override surfaces that refer to surfaces that arent on this list + G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); - // now remove all bones that are pointing at bones that aren't active - G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); + // now remove all bones that are pointing at bones that aren't active + G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); - // then remove all bolts that point at surfaces or bones that *arent* active. - G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); + // then remove all bolts that point at surfaces or bones that *arent* active. + G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); - // then remove all models on this ghoul2 instance that use those bolts that are being removed. - for (int i=0; i> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; - // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model - if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || - ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && - (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + // are we even bolted to anything? + if (ghoul2[i].mModelBoltLink != -1) { - G2API_RemoveGhoul2Model(entstate, i); + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model + if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && + (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + { + G2API_RemoveGhoul2Model(entstate, i); + } } } - } - // remember to free what we used - Z_Free(activeSurfaces); - Z_Free(activeBones); + // remember to free what we used + Z_Free(activeSurfaces); + Z_Free(activeBones); - return (qtrue); + return (qtrue); + } } - } - assert(0);*/ + assert(0);*/ return qfalse; } - extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); -int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) -{ +int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod) { surfaceInfo_t temp_slist_entry; @@ -523,13 +453,11 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float lod = G2_DecideTraceLod(*(CGhoul2Info *)(ghoul2), lod); // first up, see if we have a free one already set up - look only from the end of the constant surfaces onwards - for (size_t i=0; imSlist.size(); i++) - { + for (size_t i = 0; i < ghoul2->mSlist.size(); i++) { // is the surface count -1? That would indicate it's free - if (ghoul2->mSlist[i].surface == -1) - { + if (ghoul2->mSlist[i].surface == -1) { ghoul2->mSlist[i].offFlags = G2SURFACEFLAG_GENERATED; - ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces + ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces ghoul2->mSlist[i].genBarycentricI = BarycentricI; ghoul2->mSlist[i].genBarycentricJ = BarycentricJ; ghoul2->mSlist[i].genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); @@ -549,34 +477,28 @@ int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float ghoul2->mSlist.push_back(temp_slist_entry); - return (ghoul2->mSlist.size() -1 ); + return (ghoul2->mSlist.size() - 1); } -qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) -{ - // did we find it? - if (index != -1) - { - // set us to be the 'not active' state +qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) { + // did we find it? + if (index != -1) { + // set us to be the 'not active' state slist[index].surface = -1; unsigned int newSize = slist.size(); // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list - for (int i=slist.size()-1; i>-1; i--) - { - if (slist[i].surface == -1) - { + for (int i = slist.size() - 1; i > -1; i--) { + if (slist[i].surface == -1) { newSize = i; } // once we hit one that isn't a -1, we are done. - else - { + else { break; } } // do we need to resize? - if (newSize != slist.size()) - { + if (newSize != slist.size()) { // yes, so lets do it slist.resize(newSize); } @@ -590,38 +512,32 @@ qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) return qfalse; } - -int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - mdxmSurface_t *surf = 0; - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = 0; +int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = 0; // walk each surface and see if this index is listed in it's children surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, index, 0); surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); return surfInfo->parentIndex; - } -int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) -{ - model_t *mod = (model_t *)ghlInfo->currentModel; - int flags; +int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) { + model_t *mod = (model_t *)ghlInfo->currentModel; + int flags; return G2_IsSurfaceLegal(mod, surfaceName, &flags); } -int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) -{ - int flags = 0;//, surfFlags = 0; - int surfIndex = 0; +int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) { + int flags = 0; //, surfFlags = 0; + int surfIndex = 0; assert(ghlInfo->currentModel); assert(ghlInfo->currentModel->mdxm); - if (!ghlInfo->currentModel->mdxm) - { + if (!ghlInfo->currentModel->mdxm) { return -1; } @@ -629,55 +545,47 @@ int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceI // find the original surface in the surface list int surfNum = G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, surfaceName, &flags); - if ( surfNum != -1 ) - {//must be legal - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); + if (surfNum != -1) { // must be legal + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->mdxm + sizeof(mdxmHeader_t)); const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); surfNum = surfInfo->parentIndex; // walk the surface hierarchy up until we hit the root - while (surfNum != -1) - { - const mdxmSurface_t *parentSurf; - int parentFlags = 0; - const mdxmSurfHierarchy_t *parentSurfInfo; + while (surfNum != -1) { + const mdxmSurface_t *parentSurf; + int parentFlags = 0; + const mdxmSurfHierarchy_t *parentSurfInfo; parentSurfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); // find the original surface in the surface list - //G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags + // G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, parentSurfInfo->name, &parentFlags); // now see if we already have overriden this surface in the slist parentSurf = G2_FindSurface(ghlInfo, slist, parentSurfInfo->name, &surfIndex); - if (parentSurf) - { + if (parentSurf) { // set descendants value parentFlags = slist[surfIndex].offFlags; } // now we have the parent flags, lets see if any have the 'no descendants' flag set - if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) { flags |= G2SURFACEFLAG_OFF; break; } // set up scan of next parent surfNum = parentSurfInfo->parentIndex; } - } - else - { + } else { return -1; } - if ( flags == 0 ) - {//it's not being overridden by a parent + if (flags == 0) { // it's not being overridden by a parent // now see if we already have overriden this surface in the slist const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); - if (surf) - { + if (surf) { // set descendants value flags = slist[surfIndex].offFlags; } - // ok, at this point in flags we have what this surface is set to, and the index of the surface itself + // ok, at this point in flags we have what this surface is set to, and the index of the surface itself } return flags; } diff --git a/codemp/rd-vanilla/tr_WorldEffects.cpp b/codemp/rd-vanilla/tr_WorldEffects.cpp index 636635697b..b81db9214f 100644 --- a/codemp/rd-vanilla/tr_WorldEffects.cpp +++ b/codemp/rd-vanilla/tr_WorldEffects.cpp @@ -44,215 +44,161 @@ along with this program; if not, see . //////////////////////////////////////////////////////////////////////////////////////// // Defines //////////////////////////////////////////////////////////////////////////////////////// -#define GLS_ALPHA (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA) -#define MAX_WIND_ZONES 10 -#define MAX_WEATHER_ZONES 10 -#define MAX_PUFF_SYSTEMS 2 -#define MAX_PARTICLE_CLOUDS 5 - -#define POINTCACHE_CELL_SIZE 96.0f +#define GLS_ALPHA (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA) +#define MAX_WIND_ZONES 10 +#define MAX_WEATHER_ZONES 10 +#define MAX_PUFF_SYSTEMS 2 +#define MAX_PARTICLE_CLOUDS 5 +#define POINTCACHE_CELL_SIZE 96.0f //////////////////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////////////////// -float mMillisecondsElapsed = 0; -float mSecondsElapsed = 0; -bool mFrozen = false; - -CVec3 mGlobalWindVelocity; -CVec3 mGlobalWindDirection; -float mGlobalWindSpeed; -int mParticlesRendered; - +float mMillisecondsElapsed = 0; +float mSecondsElapsed = 0; +bool mFrozen = false; +CVec3 mGlobalWindVelocity; +CVec3 mGlobalWindDirection; +float mGlobalWindSpeed; +int mParticlesRendered; //////////////////////////////////////////////////////////////////////////////////////// // Handy Functions //////////////////////////////////////////////////////////////////////////////////////// // Returns a float min <= x < max (exclusive; will get max - 0.00001; but never max) -inline float WE_flrand(float min, float max) { - return ((rand() * (max - min)) / (RAND_MAX)) + min; -} +inline float WE_flrand(float min, float max) { return ((rand() * (max - min)) / (RAND_MAX)) + min; } //////////////////////////////////////////////////////////////////////////////////////// // Externs & Fwd Decl. //////////////////////////////////////////////////////////////////////////////////////// -extern void SetViewportAndScissor( void ); +extern void SetViewportAndScissor(void); -inline void VectorFloor(vec3_t in) -{ +inline void VectorFloor(vec3_t in) { in[0] = floorf(in[0]); in[1] = floorf(in[1]); in[2] = floorf(in[2]); } -inline void VectorCeil(vec3_t in) -{ +inline void VectorCeil(vec3_t in) { in[0] = ceilf(in[0]); in[1] = ceilf(in[1]); in[2] = ceilf(in[2]); } -inline float FloatRand(void) -{ - return ((float)rand() / (float)RAND_MAX); -} +inline float FloatRand(void) { return ((float)rand() / (float)RAND_MAX); } -inline void SnapFloatToGrid(float& f, int GridSize) -{ +inline void SnapFloatToGrid(float &f, int GridSize) { f = (int)(f); - bool fNeg = (f<0); - if (fNeg) - { - f *= -1; // Temporarly make it positive + bool fNeg = (f < 0); + if (fNeg) { + f *= -1; // Temporarly make it positive } - int Offset = ((int)(f) % (int)(GridSize)); - int OffsetAbs = abs(Offset); - if (OffsetAbs>(GridSize/2)) - { + int Offset = ((int)(f) % (int)(GridSize)); + int OffsetAbs = abs(Offset); + if (OffsetAbs > (GridSize / 2)) { Offset = (GridSize - OffsetAbs) * -1; } f -= Offset; - if (fNeg) - { - f *= -1; // Put It Back To Negative + if (fNeg) { + f *= -1; // Put It Back To Negative } f = (int)(f); - assert(((int)(f)%(int)(GridSize)) == 0); + assert(((int)(f) % (int)(GridSize)) == 0); } -inline void SnapVectorToGrid(CVec3& Vec, int GridSize) -{ +inline void SnapVectorToGrid(CVec3 &Vec, int GridSize) { SnapFloatToGrid(Vec[0], GridSize); SnapFloatToGrid(Vec[1], GridSize); SnapFloatToGrid(Vec[2], GridSize); } - - - - //////////////////////////////////////////////////////////////////////////////////////// // Range Structures //////////////////////////////////////////////////////////////////////////////////////// -struct SVecRange -{ - CVec3 mMins; - CVec3 mMaxs; +struct SVecRange { + CVec3 mMins; + CVec3 mMaxs; - inline void Clear() - { + inline void Clear() { mMins.Clear(); mMaxs.Clear(); } - inline void Pick(CVec3& V) - { + inline void Pick(CVec3 &V) { V[0] = WE_flrand(mMins[0], mMaxs[0]); V[1] = WE_flrand(mMins[1], mMaxs[1]); V[2] = WE_flrand(mMins[2], mMaxs[2]); } - inline void Wrap(CVec3& V, SVecRange &spawnRange) - { - if (V[0]mMaxs[0]) - { - const float d = V[0]-mMaxs[0]; - V[0] = mMins[0]+fmod(d, mMaxs[0]-mMins[0]); + if (V[0] > mMaxs[0]) { + const float d = V[0] - mMaxs[0]; + V[0] = mMins[0] + fmod(d, mMaxs[0] - mMins[0]); } - if (V[1]mMaxs[1]) - { - const float d = V[1]-mMaxs[1]; - V[1] = mMins[1]+fmod(d, mMaxs[1]-mMins[1]); + if (V[1] > mMaxs[1]) { + const float d = V[1] - mMaxs[1]; + V[1] = mMins[1] + fmod(d, mMaxs[1] - mMins[1]); } - if (V[2]mMaxs[2]) - { - const float d = V[2]-mMaxs[2]; - V[2] = mMins[2]+fmod(d, mMaxs[2]-mMins[2]); + if (V[2] > mMaxs[2]) { + const float d = V[2] - mMaxs[2]; + V[2] = mMins[2] + fmod(d, mMaxs[2] - mMins[2]); } } - inline bool In(const CVec3& V) - { - return (V>mMins && V mMins && V < mMaxs); } }; -struct SFloatRange -{ - float mMin; - float mMax; +struct SFloatRange { + float mMin; + float mMax; - inline void Clear() - { + inline void Clear() { mMin = 0; mMax = 0; } - inline void Pick(float& V) - { - V = WE_flrand(mMin, mMax); - } - inline bool In(const float& V) - { - return (V>mMin && V mMin && V < mMax); } }; -struct SIntRange -{ - int mMin; - int mMax; +struct SIntRange { + int mMin; + int mMax; - inline void Clear() - { + inline void Clear() { mMin = 0; mMax = 0; } - inline void Pick(int& V) - { - V = Q_irand(mMin, mMax); - } - inline bool In(const int& V) - { - return (V>mMin && V mMin && V < mMax); } }; - - - - //////////////////////////////////////////////////////////////////////////////////////// // The Particle Class //////////////////////////////////////////////////////////////////////////////////////// -class CWeatherParticle -{ -public: - enum - { +class CWeatherParticle { + public: + enum { FLAG_RENDER = 0, FLAG_FADEIN, @@ -261,60 +207,53 @@ class CWeatherParticle FLAG_MAX }; - typedef ratl::bits_vs TFlags; + typedef ratl::bits_vs TFlags; - float mAlpha; - TFlags mFlags; - CVec3 mPosition; - CVec3 mVelocity; - float mMass; // A higher number will more greatly resist force and result in greater gravity + float mAlpha; + TFlags mFlags; + CVec3 mPosition; + CVec3 mVelocity; + float mMass; // A higher number will more greatly resist force and result in greater gravity }; - - - - //////////////////////////////////////////////////////////////////////////////////////// // The Wind //////////////////////////////////////////////////////////////////////////////////////// -class CWindZone -{ -public: - bool mGlobal; - SVecRange mRBounds; - SVecRange mRVelocity; - SIntRange mRDuration; - SIntRange mRDeadTime; - float mMaxDeltaVelocityPerUpdate; - float mChanceOfDeadTime; - - CVec3 mCurrentVelocity; - CVec3 mTargetVelocity; - int mTargetVelocityTimeRemaining; - - -public: +class CWindZone { + public: + bool mGlobal; + SVecRange mRBounds; + SVecRange mRVelocity; + SIntRange mRDuration; + SIntRange mRDeadTime; + float mMaxDeltaVelocityPerUpdate; + float mChanceOfDeadTime; + + CVec3 mCurrentVelocity; + CVec3 mTargetVelocity; + int mTargetVelocityTimeRemaining; + + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - void Initialize() - { + void Initialize() { mRBounds.Clear(); - mGlobal = true; + mGlobal = true; - mRVelocity.mMins = -1500.0f; - mRVelocity.mMins[2] = -10.0f; - mRVelocity.mMaxs = 1500.0f; - mRVelocity.mMaxs[2] = 10.0f; + mRVelocity.mMins = -1500.0f; + mRVelocity.mMins[2] = -10.0f; + mRVelocity.mMaxs = 1500.0f; + mRVelocity.mMaxs[2] = 10.0f; - mMaxDeltaVelocityPerUpdate = 10.0f; + mMaxDeltaVelocityPerUpdate = 10.0f; - mRDuration.mMin = 1000; - mRDuration.mMax = 2000; + mRDuration.mMin = 1000; + mRDuration.mMax = 2000; - mChanceOfDeadTime = 0.3f; - mRDeadTime.mMin = 1000; - mRDeadTime.mMax = 3000; + mChanceOfDeadTime = 0.3f; + mRDeadTime.mMin = 1000; + mRDeadTime.mMax = 3000; mCurrentVelocity.Clear(); mTargetVelocity.Clear(); @@ -324,29 +263,21 @@ class CWindZone //////////////////////////////////////////////////////////////////////////////////// // Update - Changes wind when current target velocity expires //////////////////////////////////////////////////////////////////////////////////// - void Update() - { - if (mTargetVelocityTimeRemaining==0) - { - if (FloatRand() mMaxDeltaVelocityPerUpdate) - { + CVec3 DeltaVelocity(mTargetVelocity - mCurrentVelocity); + float DeltaVelocityLen = VectorNormalize(DeltaVelocity.v); + if (DeltaVelocityLen > mMaxDeltaVelocityPerUpdate) { DeltaVelocityLen = mMaxDeltaVelocityPerUpdate; } DeltaVelocity *= (DeltaVelocityLen); @@ -354,60 +285,50 @@ class CWindZone } } }; -ratl::vector_vs mWindZones; +ratl::vector_vs mWindZones; -bool R_GetWindVector(vec3_t windVector) -{ +bool R_GetWindVector(vec3_t windVector) { VectorCopy(mGlobalWindDirection.v, windVector); return true; } -bool R_GetWindSpeed(float &windSpeed) -{ +bool R_GetWindSpeed(float &windSpeed) { windSpeed = mGlobalWindSpeed; return true; } -bool R_GetWindGusting() -{ - return (mGlobalWindSpeed>1000.0f); -} - - +bool R_GetWindGusting() { return (mGlobalWindSpeed > 1000.0f); } //////////////////////////////////////////////////////////////////////////////////////// // Outside Point Cache //////////////////////////////////////////////////////////////////////////////////////// -class COutside -{ -public: +class COutside { + public: //////////////////////////////////////////////////////////////////////////////////// - //Global Public Outside Variables + // Global Public Outside Variables //////////////////////////////////////////////////////////////////////////////////// - bool mOutsideShake; - float mOutsidePain; + bool mOutsideShake; + float mOutsidePain; -private: + private: //////////////////////////////////////////////////////////////////////////////////// // The Outside Cache //////////////////////////////////////////////////////////////////////////////////// - bool mCacheInit; // Has It Been Cached? - - struct SWeatherZone - { - static bool mMarkedOutside; - uint32_t* mPointCache; - SVecRange mExtents; - SVecRange mSize; - int mWidth; - int mHeight; - int mDepth; + bool mCacheInit; // Has It Been Cached? + + struct SWeatherZone { + static bool mMarkedOutside; + uint32_t *mPointCache; + SVecRange mExtents; + SVecRange mSize; + int mWidth; + int mHeight; + int mDepth; //////////////////////////////////////////////////////////////////////////////////// // Convert To Cell //////////////////////////////////////////////////////////////////////////////////// - inline void ConvertToCell(const CVec3& pos, int& x, int& y, int& z, int& bit) - { + inline void ConvertToCell(const CVec3 &pos, int &x, int &y, int &z, int &bit) { x = (int)((pos[0] / POINTCACHE_CELL_SIZE) - mSize.mMins[0]); y = (int)((pos[1] / POINTCACHE_CELL_SIZE) - mSize.mMins[1]); z = (int)((pos[2] / POINTCACHE_CELL_SIZE) - mSize.mMins[2]); @@ -419,100 +340,74 @@ class COutside //////////////////////////////////////////////////////////////////////////////////// // CellOutside - Test to see if a given cell is outside //////////////////////////////////////////////////////////////////////////////////// - inline bool CellOutside(int x, int y, int z, int bit) - { - if ((x < 0 || x >= mWidth) || (y < 0 || y >= mHeight) || (z < 0 || z >= mDepth) || (bit < 0 || bit >= 32)) - { + inline bool CellOutside(int x, int y, int z, int bit) { + if ((x < 0 || x >= mWidth) || (y < 0 || y >= mHeight) || (z < 0 || z >= mDepth) || (bit < 0 || bit >= 32)) { return !(mMarkedOutside); } - return (mMarkedOutside==(!!(mPointCache[((z * mWidth * mHeight) + (y * mWidth) + x)]&(1 << bit)))); + return (mMarkedOutside == (!!(mPointCache[((z * mWidth * mHeight) + (y * mWidth) + x)] & (1 << bit)))); } }; - ratl::vector_vs mWeatherZones; + ratl::vector_vs mWeatherZones; - -private: + private: //////////////////////////////////////////////////////////////////////////////////// // Iteration Variables //////////////////////////////////////////////////////////////////////////////////// - int mWCells; - int mHCells; - - int mXCell; - int mYCell; - int mZBit; - - int mXMax; - int mYMax; - int mZMax; + int mWCells; + int mHCells; + int mXCell; + int mYCell; + int mZBit; -private: - + int mXMax; + int mYMax; + int mZMax; + private: //////////////////////////////////////////////////////////////////////////////////// // Contents Outside //////////////////////////////////////////////////////////////////////////////////// - inline bool ContentsOutside(int contents) - { - if (contents&CONTENTS_WATER || contents&CONTENTS_SOLID) - { + inline bool ContentsOutside(int contents) { + if (contents & CONTENTS_WATER || contents & CONTENTS_SOLID) { return false; } - if (mCacheInit) - { - if (SWeatherZone::mMarkedOutside) - { - return (!!(contents&CONTENTS_OUTSIDE)); + if (mCacheInit) { + if (SWeatherZone::mMarkedOutside) { + return (!!(contents & CONTENTS_OUTSIDE)); } - return (!(contents&CONTENTS_INSIDE)); + return (!(contents & CONTENTS_INSIDE)); } - return !!(contents&CONTENTS_OUTSIDE); + return !!(contents & CONTENTS_OUTSIDE); } - - - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Constructor - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - void Reset() - { + void Reset() { mOutsideShake = false; mOutsidePain = 0.0; mCacheInit = false; SWeatherZone::mMarkedOutside = false; - for (int wz=0; wz> 5; + Wz.mWidth = (int)(Wz.mSize.mMaxs[0] - Wz.mSize.mMins[0]); + Wz.mHeight = (int)(Wz.mSize.mMaxs[1] - Wz.mSize.mMins[1]); + Wz.mDepth = ((int)(Wz.mSize.mMaxs[2] - Wz.mSize.mMins[2]) + 31) >> 5; - int arraySize = (Wz.mWidth * Wz.mHeight * Wz.mDepth); - Wz.mPointCache = (uint32_t *)Z_Malloc(arraySize*sizeof(uint32_t), TAG_POINTCACHE, qtrue); + int arraySize = (Wz.mWidth * Wz.mHeight * Wz.mDepth); + Wz.mPointCache = (uint32_t *)Z_Malloc(arraySize * sizeof(uint32_t), TAG_POINTCACHE, qtrue); } } - - //////////////////////////////////////////////////////////////////////////////////// // Cache - Will Scan the World, Creating The Cache //////////////////////////////////////////////////////////////////////////////////// - void Cache() - { - if (!tr.world || mCacheInit) - { + void Cache() { + if (!tr.world || mCacheInit) { return; } - CVec3 CurPos; - CVec3 Size; - CVec3 Mins; - int x, y, z, q, zbase; - bool curPosOutside; - uint32_t contents; - uint32_t bit; - + CVec3 CurPos; + CVec3 Size; + CVec3 Mins; + int x, y, z, q, zbase; + bool curPosOutside; + uint32_t contents; + uint32_t bit; // Record The Extents Of The World Incase No Other Weather Zones Exist //--------------------------------------------------------------------- - if (!mWeatherZones.size()) - { - ri.Printf( PRINT_ALL, "WARNING: No Weather Zones Encountered\n"); + if (!mWeatherZones.size()) { + ri.Printf(PRINT_ALL, "WARNING: No Weather Zones Encountered\n"); AddWeatherZone(tr.world->bmodels[0].bounds[0], tr.world->bmodels[0].bounds[1]); } // Iterate Over All Weather Zones //-------------------------------- - for (int zone=0; zoneSRC - int mFilterMode; // 0 = LINEAR, 1 = NEAREST + int mBlendMode; // 0 = ALPHA, 1 = SRC->SRC + int mFilterMode; // 0 = LINEAR, 1 = NEAREST - float mFade; // How much to fade in and out 1.0 = instant, 0.01 = very slow + float mFade; // How much to fade in and out 1.0 = instant, 0.01 = very slow - SFloatRange mRotation; - float mRotationDelta; - float mRotationDeltaTarget; - float mRotationCurrent; - SIntRange mRotationChangeTimer; - int mRotationChangeNext; + SFloatRange mRotation; + float mRotationDelta; + float mRotationDeltaTarget; + float mRotationCurrent; + SIntRange mRotationChangeTimer; + int mRotationChangeNext; - SFloatRange mMass; // Determines how slowness to accelerate, higher number = slower - float mFrictionInverse; // How much air friction does this particle have 1.0=none, 0.0=nomove + SFloatRange mMass; // Determines how slowness to accelerate, higher number = slower + float mFrictionInverse; // How much air friction does this particle have 1.0=none, 0.0=nomove - int mParticleCount; + int mParticleCount; - bool mWaterParticles; + bool mWaterParticles; - - - -public: + public: //////////////////////////////////////////////////////////////////////////////////// // Initialize - Create Image, Particles, And Setup All Values //////////////////////////////////////////////////////////////////////////////////// - void Initialize(int count, const char* texturePath, int VertexCount=4) - { + void Initialize(int count, const char *texturePath, int VertexCount = 4) { Reset(); - assert(mParticleCount==0 && mParticles==0); - assert(mImage==0); + assert(mParticleCount == 0 && mParticles == 0); + assert(mImage == 0); // Create The Image //------------------ mImage = R_FindImageFile(texturePath, qfalse, qfalse, qfalse, GL_CLAMP); - if (!mImage) - { + if (!mImage) { Com_Error(ERR_DROP, "CWeatherParticleCloud: Could not texture %s", texturePath); } GL_Bind(mImage); - - // Create The Particles //---------------------- - mParticleCount = count; - mParticles = new CWeatherParticle[mParticleCount]; - - + mParticleCount = count; + mParticles = new CWeatherParticle[mParticleCount]; - CWeatherParticle* part=0; - for (int particleNum=0; particleNummPosition.Clear(); part->mVelocity.Clear(); - part->mAlpha = 0.0f; + part->mAlpha = 0.0f; mMass.Pick(part->mMass); } mVertexCount = VertexCount; - mGLModeEnum = (mVertexCount==3)?(GL_TRIANGLES):(GL_QUADS); + mGLModeEnum = (mVertexCount == 3) ? (GL_TRIANGLES) : (GL_QUADS); } - //////////////////////////////////////////////////////////////////////////////////// // Reset - Initializes all data to default values //////////////////////////////////////////////////////////////////////////////////// - void Reset() - { - if (mImage) - { + void Reset() { + if (mImage) { // TODO: Free Image? } - mImage = 0; - if (mParticleCount) - { - delete [] mParticles; + mImage = 0; + if (mParticleCount) { + delete[] mParticles; } - mParticleCount = 0; - mParticles = 0; - - mPopulated = 0; - + mParticleCount = 0; + mParticles = 0; + mPopulated = 0; // These Are The Default Startup Values For Constant Data //======================================================== mOrientWithVelocity = false; - mWaterParticles = false; + mWaterParticles = false; - mSpawnPlaneDistance = 500; - mSpawnPlaneSize = 500; - mSpawnRange.mMins = -(mSpawnPlaneDistance*1.25f); - mSpawnRange.mMaxs = (mSpawnPlaneDistance*1.25f); + mSpawnPlaneDistance = 500; + mSpawnPlaneSize = 500; + mSpawnRange.mMins = -(mSpawnPlaneDistance * 1.25f); + mSpawnRange.mMaxs = (mSpawnPlaneDistance * 1.25f); - mGravity = 300.0f; // Units Per Second + mGravity = 300.0f; // Units Per Second - mColor = 1.0f; + mColor = 1.0f; - mVertexCount = 4; - mWidth = 1.0f; - mHeight = 1.0f; + mVertexCount = 4; + mWidth = 1.0f; + mHeight = 1.0f; - mBlendMode = 0; - mFilterMode = 0; + mBlendMode = 0; + mFilterMode = 0; - mFade = 10.0f; + mFade = 10.0f; mRotation.Clear(); - mRotationDelta = 0.0f; - mRotationDeltaTarget= 0.0f; - mRotationCurrent = 0.0f; - mRotationChangeNext = -1; - mRotation.mMin = -0.7f; - mRotation.mMax = 0.7f; + mRotationDelta = 0.0f; + mRotationDeltaTarget = 0.0f; + mRotationCurrent = 0.0f; + mRotationChangeNext = -1; + mRotation.mMin = -0.7f; + mRotation.mMax = 0.7f; mRotationChangeTimer.mMin = 500; mRotationChangeTimer.mMax = 2000; - mMass.mMin = 5.0f; - mMass.mMax = 10.0f; + mMass.mMin = 5.0f; + mMass.mMax = 10.0f; - mFrictionInverse = 0.7f; // No Friction? + mFrictionInverse = 0.7f; // No Friction? } //////////////////////////////////////////////////////////////////////////////////// // Constructor - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - CWeatherParticleCloud() - { + CWeatherParticleCloud() { mImage = 0; mParticleCount = 0; Reset(); @@ -919,92 +744,76 @@ class CWeatherParticleCloud //////////////////////////////////////////////////////////////////////////////////// // Initialize - Will setup default values for all data //////////////////////////////////////////////////////////////////////////////////// - ~CWeatherParticleCloud() - { - Reset(); - } - + ~CWeatherParticleCloud() { Reset(); } //////////////////////////////////////////////////////////////////////////////////// // UseSpawnPlane - Check To See If We Should Spawn On A Plane, Or Just Wrap The Box //////////////////////////////////////////////////////////////////////////////////// - inline bool UseSpawnPlane() - { - return (mGravity!=0.0f); - } - + inline bool UseSpawnPlane() { return (mGravity != 0.0f); } //////////////////////////////////////////////////////////////////////////////////// // Update - Applies All Physics Forces To All Contained Particles //////////////////////////////////////////////////////////////////////////////////// - void Update() - { - CWeatherParticle* part=0; - CVec3 partForce; - CVec3 partMoved; - CVec3 partToCamera; - bool partRendering; - bool partOutside; - bool partInRange; - bool partInView; - int particleNum; - float particleFade = (mFade * mSecondsElapsed); - -/* TODO: Non Global Wind Zones - CWindZone* wind=0; - int windNum; - int windCount = mWindZones.size(); -*/ + void Update() { + CWeatherParticle *part = 0; + CVec3 partForce; + CVec3 partMoved; + CVec3 partToCamera; + bool partRendering; + bool partOutside; + bool partInRange; + bool partInView; + int particleNum; + float particleFade = (mFade * mSecondsElapsed); + + /* TODO: Non Global Wind Zones + CWindZone* wind=0; + int windNum; + int windCount = mWindZones.size(); + */ // Compute Camera //---------------- { - mCameraPosition = backEnd.viewParms.ori.origin; - mCameraForward = backEnd.viewParms.ori.axis[0]; - mCameraLeft = backEnd.viewParms.ori.axis[1]; - mCameraDown = backEnd.viewParms.ori.axis[2]; + mCameraPosition = backEnd.viewParms.ori.origin; + mCameraForward = backEnd.viewParms.ori.axis[0]; + mCameraLeft = backEnd.viewParms.ori.axis[1]; + mCameraDown = backEnd.viewParms.ori.axis[2]; - if (mRotationChangeNext!=-1) - { - if (mRotationChangeNext==0) - { + if (mRotationChangeNext != -1) { + if (mRotationChangeNext == 0) { mRotation.Pick(mRotationDeltaTarget); mRotationChangeTimer.Pick(mRotationChangeNext); - if (mRotationChangeNext<=0) - { + if (mRotationChangeNext <= 0) { mRotationChangeNext = 1; } } mRotationChangeNext--; - float RotationDeltaDifference = (mRotationDeltaTarget - mRotationDelta); - if (fabsf(RotationDeltaDifference)>0.01) - { - mRotationDelta += RotationDeltaDifference; // Blend To New Delta + float RotationDeltaDifference = (mRotationDeltaTarget - mRotationDelta); + if (fabsf(RotationDeltaDifference) > 0.01) { + mRotationDelta += RotationDeltaDifference; // Blend To New Delta } - mRotationCurrent += (mRotationDelta * mSecondsElapsed); + mRotationCurrent += (mRotationDelta * mSecondsElapsed); float s = sinf(mRotationCurrent); float c = cosf(mRotationCurrent); - CVec3 TempCamLeft(mCameraLeft); + CVec3 TempCamLeft(mCameraLeft); mCameraLeft *= (c * mWidth); mCameraLeft.ScaleAdd(mCameraDown, (s * mWidth * -1.0f)); mCameraDown *= (c * mHeight); mCameraDown.ScaleAdd(TempCamLeft, (s * mHeight)); - } - else - { - mCameraLeft *= mWidth; - mCameraDown *= mHeight; + } else { + mCameraLeft *= mWidth; + mCameraDown *= mHeight; } } - // Compute Global Force //---------------------- - CVec3 force; + CVec3 force; { force.Clear(); @@ -1014,10 +823,9 @@ class CWeatherParticleCloud // Apply Wind Velocity //--------------------- - force += mGlobalWindVelocity; + force += mGlobalWindVelocity; } - // Update Range //-------------- { @@ -1026,24 +834,18 @@ class CWeatherParticleCloud // If Using A Spawn Plane, Increase The Range Box A Bit To Account For Rotation On The Spawn Plane //------------------------------------------------------------------------------------------------- - if (UseSpawnPlane()) - { - for (int dim=0; dim<3; dim++) - { - if (force[dim]>0.01) - { - mRange.mMins[dim] -= (mSpawnPlaneDistance/2.0f); - } - else if (force[dim]<-0.01) - { - mRange.mMaxs[dim] += (mSpawnPlaneDistance/2.0f); + if (UseSpawnPlane()) { + for (int dim = 0; dim < 3; dim++) { + if (force[dim] > 0.01) { + mRange.mMins[dim] -= (mSpawnPlaneDistance / 2.0f); + } else if (force[dim] < -0.01) { + mRange.mMaxs[dim] += (mSpawnPlaneDistance / 2.0f); } } - mSpawnPlaneNorm = force; - mSpawnSpeed = VectorNormalize(mSpawnPlaneNorm.v); + mSpawnPlaneNorm = force; + mSpawnSpeed = VectorNormalize(mSpawnPlaneNorm.v); MakeNormalVectors(mSpawnPlaneNorm.v, mSpawnPlaneRight.v, mSpawnPlaneUp.v); - if (mOrientWithVelocity) - { + if (mOrientWithVelocity) { mCameraDown = mSpawnPlaneNorm; mCameraDown *= (mHeight * -1); } @@ -1051,36 +853,28 @@ class CWeatherParticleCloud // Optimization For Quad Position Calculation //-------------------------------------------- - if (mVertexCount==4) - { - mCameraLeftPlusUp = (mCameraLeft - mCameraDown); + if (mVertexCount == 4) { + mCameraLeftPlusUp = (mCameraLeft - mCameraDown); mCameraLeftMinusUp = (mCameraLeft + mCameraDown); - } - else - { - mCameraLeftPlusUp = (mCameraDown + mCameraLeft); // should really be called mCamera Left + Down + } else { + mCameraLeftPlusUp = (mCameraDown + mCameraLeft); // should really be called mCamera Left + Down } } // Stop All Additional Processing //-------------------------------- - if (mFrozen) - { + if (mFrozen) { return; } - - // Now Update All Particles //-------------------------- mParticleCountRender = 0; - for (particleNum=0; particleNummPosition); // First Time Spawn Location + if (!mPopulated) { + mRange.Pick(part->mPosition); // First Time Spawn Location } // Grab The Force And Apply Non Global Wind @@ -1088,40 +882,36 @@ class CWeatherParticleCloud partForce = force; partForce /= part->mMass; - // Apply The Force //----------------- - part->mVelocity += partForce; - part->mVelocity *= mFrictionInverse; + part->mVelocity += partForce; + part->mVelocity *= mFrictionInverse; part->mPosition.ScaleAdd(part->mVelocity, mSecondsElapsed); - partToCamera = (part->mPosition - mCameraPosition); - partRendering = part->mFlags.get_bit(CWeatherParticle::FLAG_RENDER); - partOutside = mOutside.PointOutside(part->mPosition, mWidth, mHeight); - partInRange = mRange.In(part->mPosition); - partInView = (partOutside && partInRange && (partToCamera.Dot(mCameraForward)>0.0f)); + partToCamera = (part->mPosition - mCameraPosition); + partRendering = part->mFlags.get_bit(CWeatherParticle::FLAG_RENDER); + partOutside = mOutside.PointOutside(part->mPosition, mWidth, mHeight); + partInRange = mRange.In(part->mPosition); + partInView = (partOutside && partInRange && (partToCamera.Dot(mCameraForward) > 0.0f)); // Process Respawn //----------------- - if (!partInRange && !partRendering) - { + if (!partInRange && !partRendering) { part->mVelocity.Clear(); // Reselect A Position On The Spawn Plane //---------------------------------------- - if (UseSpawnPlane()) - { - part->mPosition = mCameraPosition; - part->mPosition -= (mSpawnPlaneNorm* mSpawnPlaneDistance); - part->mPosition += (mSpawnPlaneRight*WE_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); - part->mPosition += (mSpawnPlaneUp* WE_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); + if (UseSpawnPlane()) { + part->mPosition = mCameraPosition; + part->mPosition -= (mSpawnPlaneNorm * mSpawnPlaneDistance); + part->mPosition += (mSpawnPlaneRight * WE_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); + part->mPosition += (mSpawnPlaneUp * WE_flrand(-mSpawnPlaneSize, mSpawnPlaneSize)); } // Otherwise, Just Wrap Around To The Other End Of The Range //----------------------------------------------------------- - else - { + else { mRange.Wrap(part->mPosition, mSpawnRange); } partInRange = true; @@ -1132,24 +922,21 @@ class CWeatherParticleCloud { // Start A Fade Out //------------------ - if (partRendering && !partInView) - { + if (partRendering && !partInView) { part->mFlags.clear_bit(CWeatherParticle::FLAG_FADEIN); part->mFlags.set_bit(CWeatherParticle::FLAG_FADEOUT); } // Switch From Fade Out To Fade In //--------------------------------- - else if (partRendering && partInView && part->mFlags.get_bit(CWeatherParticle::FLAG_FADEOUT)) - { + else if (partRendering && partInView && part->mFlags.get_bit(CWeatherParticle::FLAG_FADEOUT)) { part->mFlags.set_bit(CWeatherParticle::FLAG_FADEIN); part->mFlags.clear_bit(CWeatherParticle::FLAG_FADEOUT); } // Start A Fade In //----------------- - else if (!partRendering && partInView) - { + else if (!partRendering && partInView) { partRendering = true; part->mAlpha = 0.0f; part->mFlags.set_bit(CWeatherParticle::FLAG_RENDER); @@ -1159,16 +946,13 @@ class CWeatherParticleCloud // Update Fade //------------- - if (partRendering) - { + if (partRendering) { // Update Fade Out //----------------- - if (part->mFlags.get_bit(CWeatherParticle::FLAG_FADEOUT)) - { + if (part->mFlags.get_bit(CWeatherParticle::FLAG_FADEOUT)) { part->mAlpha -= particleFade; - if (part->mAlpha<=0.0f) - { + if (part->mAlpha <= 0.0f) { part->mAlpha = 0.0f; part->mFlags.clear_bit(CWeatherParticle::FLAG_FADEOUT); part->mFlags.clear_bit(CWeatherParticle::FLAG_FADEIN); @@ -1179,11 +963,9 @@ class CWeatherParticleCloud // Update Fade In //---------------- - else if (part->mFlags.get_bit(CWeatherParticle::FLAG_FADEIN)) - { + else if (part->mFlags.get_bit(CWeatherParticle::FLAG_FADEIN)) { part->mAlpha += particleFade; - if (part->mAlpha>=mColor[3]) - { + if (part->mAlpha >= mColor[3]) { part->mFlags.clear_bit(CWeatherParticle::FLAG_FADEIN); part->mAlpha = mColor[3]; } @@ -1193,15 +975,9 @@ class CWeatherParticleCloud // Keep Track Of The Number Of Particles To Render //------------------------------------------------- - if (part->mFlags.get_bit(CWeatherParticle::FLAG_RENDER)) - { - mParticleCountRender ++; + if (part->mFlags.get_bit(CWeatherParticle::FLAG_RENDER)) { + mParticleCountRender++; } - - - - - } mPopulated = true; } @@ -1209,131 +985,102 @@ class CWeatherParticleCloud //////////////////////////////////////////////////////////////////////////////////// // Render - //////////////////////////////////////////////////////////////////////////////////// - void Render() - { - CWeatherParticle* part=0; - int particleNum; - + void Render() { + CWeatherParticle *part = 0; + int particleNum; // Set The GL State And Image Binding //------------------------------------ - GL_State((mBlendMode==0)?(GLS_ALPHA):(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)); + GL_State((mBlendMode == 0) ? (GLS_ALPHA) : (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)); GL_Bind(mImage); - // Enable And Disable Things //--------------------------- qglEnable(GL_TEXTURE_2D); - //qglDisable(GL_CULL_FACE); - //naughty, you are making the assumption that culling is on when you get here. -rww + // qglDisable(GL_CULL_FACE); + // naughty, you are making the assumption that culling is on when you get here. -rww GL_Cull(CT_TWO_SIDED); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (mFilterMode==0)?(GL_LINEAR):(GL_NEAREST)); - qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (mFilterMode==0)?(GL_LINEAR):(GL_NEAREST)); - + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (mFilterMode == 0) ? (GL_LINEAR) : (GL_NEAREST)); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (mFilterMode == 0) ? (GL_LINEAR) : (GL_NEAREST)); // Setup Matrix Mode And Translation //----------------------------------- qglMatrixMode(GL_MODELVIEW); qglPushMatrix(); - // Begin //------- qglBegin(mGLModeEnum); - for (particleNum=0; particleNummFlags.get_bit(CWeatherParticle::FLAG_RENDER)) - { + if (!part->mFlags.get_bit(CWeatherParticle::FLAG_RENDER)) { continue; } // Blend Mode Zero -> Apply Alpha Just To Alpha Channel //------------------------------------------------------ - if (mBlendMode==0) - { + if (mBlendMode == 0) { qglColor4f(mColor[0], mColor[1], mColor[2], part->mAlpha); } // Otherwise Apply Alpha To All Channels //--------------------------------------- - else - { - qglColor4f(mColor[0]*part->mAlpha, mColor[1]*part->mAlpha, mColor[2]*part->mAlpha, mColor[3]*part->mAlpha); + else { + qglColor4f(mColor[0] * part->mAlpha, mColor[1] * part->mAlpha, mColor[2] * part->mAlpha, mColor[3] * part->mAlpha); } // Render A Triangle //------------------- - if (mVertexCount==3) - { - qglTexCoord2f(1.0, 0.0); - qglVertex3f(part->mPosition[0], - part->mPosition[1], - part->mPosition[2]); + if (mVertexCount == 3) { + qglTexCoord2f(1.0, 0.0); + qglVertex3f(part->mPosition[0], part->mPosition[1], part->mPosition[2]); qglTexCoord2f(0.0, 1.0); - qglVertex3f(part->mPosition[0] + mCameraLeft[0], - part->mPosition[1] + mCameraLeft[1], - part->mPosition[2] + mCameraLeft[2]); + qglVertex3f(part->mPosition[0] + mCameraLeft[0], part->mPosition[1] + mCameraLeft[1], part->mPosition[2] + mCameraLeft[2]); qglTexCoord2f(0.0, 0.0); - qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], - part->mPosition[1] + mCameraLeftPlusUp[1], - part->mPosition[2] + mCameraLeftPlusUp[2]); + qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], part->mPosition[1] + mCameraLeftPlusUp[1], part->mPosition[2] + mCameraLeftPlusUp[2]); } // Render A Quad //--------------- - else - { + else { // Left bottom. - qglTexCoord2f( 0.0, 0.0 ); - qglVertex3f(part->mPosition[0] - mCameraLeftMinusUp[0], - part->mPosition[1] - mCameraLeftMinusUp[1], - part->mPosition[2] - mCameraLeftMinusUp[2] ); + qglTexCoord2f(0.0, 0.0); + qglVertex3f(part->mPosition[0] - mCameraLeftMinusUp[0], part->mPosition[1] - mCameraLeftMinusUp[1], part->mPosition[2] - mCameraLeftMinusUp[2]); // Right bottom. - qglTexCoord2f( 1.0, 0.0 ); - qglVertex3f(part->mPosition[0] - mCameraLeftPlusUp[0], - part->mPosition[1] - mCameraLeftPlusUp[1], - part->mPosition[2] - mCameraLeftPlusUp[2] ); + qglTexCoord2f(1.0, 0.0); + qglVertex3f(part->mPosition[0] - mCameraLeftPlusUp[0], part->mPosition[1] - mCameraLeftPlusUp[1], part->mPosition[2] - mCameraLeftPlusUp[2]); // Right top. - qglTexCoord2f( 1.0, 1.0 ); - qglVertex3f(part->mPosition[0] + mCameraLeftMinusUp[0], - part->mPosition[1] + mCameraLeftMinusUp[1], - part->mPosition[2] + mCameraLeftMinusUp[2] ); + qglTexCoord2f(1.0, 1.0); + qglVertex3f(part->mPosition[0] + mCameraLeftMinusUp[0], part->mPosition[1] + mCameraLeftMinusUp[1], part->mPosition[2] + mCameraLeftMinusUp[2]); // Left top. - qglTexCoord2f( 0.0, 1.0 ); - qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], - part->mPosition[1] + mCameraLeftPlusUp[1], - part->mPosition[2] + mCameraLeftPlusUp[2] ); + qglTexCoord2f(0.0, 1.0); + qglVertex3f(part->mPosition[0] + mCameraLeftPlusUp[0], part->mPosition[1] + mCameraLeftPlusUp[1], part->mPosition[2] + mCameraLeftPlusUp[2]); } } qglEnd(); - //qglEnable(GL_CULL_FACE); - //you don't need to do this when you are properly setting cull state. + // qglEnable(GL_CULL_FACE); + // you don't need to do this when you are properly setting cull state. qglPopMatrix(); mParticlesRendered += mParticleCountRender; } }; -ratl::vector_vs mParticleClouds; - - +ratl::vector_vs mParticleClouds; //////////////////////////////////////////////////////////////////////////////////////// // Init World Effects - Will Iterate Over All Particle Clouds, Clear Them Out, And Erase //////////////////////////////////////////////////////////////////////////////////////// -void R_InitWorldEffects(void) -{ +void R_InitWorldEffects(void) { srand(ri.Milliseconds()); - for (int i=0; i1000.0f) - { + if (mMillisecondsElapsed > 1000.0f) { mMillisecondsElapsed = 1000.0f; } mSecondsElapsed = (mMillisecondsElapsed / 1000.0f); - // Make Sure We Are Always Outside Cached //---------------------------------------- - if (!mOutside.Initialized()) - { + if (!mOutside.Initialized()) { mOutside.Cache(); - } - else - { + } else { // Update All Wind Zones //----------------------- - if (!mFrozen) - { + if (!mFrozen) { mGlobalWindVelocity.Clear(); - for (int wz=0; wz. // This vertex shader basically passes through most values and calculates no lighting. The only // unusual thing it does is add the inputed texel offsets to all four texture units (this allows // nearest neighbor pixel peeking). -const unsigned char g_strGlowVShaderARB[] = -{ - "!!ARBvp1.0\ +const unsigned char g_strGlowVShaderARB[] = {"!!ARBvp1.0\ \ # Input.\n\ ATTRIB iPos = vertex.position;\ @@ -69,14 +67,11 @@ const unsigned char g_strGlowVShaderARB[] = ADD oTex2, iTex0, TexelOffset2;\ ADD oTex3, iTex0, TexelOffset3;\ \ - END" -}; + END"}; // This Pixel Shader loads four texture units and adds them all together (with a modifier // multiplied to each in the process). The final output is r0 = t0 + t1 + t2 + t3. -const unsigned char g_strGlowPShaderARB[] = -{ - "!!ARBfp1.0\ +const unsigned char g_strGlowPShaderARB[] = {"!!ARBfp1.0\ \ # Input.\n\ ATTRIB iColor = fragment.color.primary;\ @@ -105,49 +100,44 @@ const unsigned char g_strGlowPShaderARB[] = \ MOV oColor, r0;\ \ - END" -}; + END"}; -static const char *gammaCorrectVtxShader = -"!!ARBvp1.0\ +static const char *gammaCorrectVtxShader = "!!ARBvp1.0\ MOV result.position, vertex.position;\ MOV result.texcoord[0], vertex.texcoord[0];\ END"; -static const char *gammaCorrectPxShader = -"!!ARBfp1.0\ +static const char *gammaCorrectPxShader = "!!ARBfp1.0\ TEMP r0;\ TEX r0, fragment.texcoord[0], texture[0], RECT;\ TEX result.color, r0, texture[1], 3D;\ END"; /***********************************************************************************************************/ -#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 -#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B void ARB_InitGPUShaders(void) { - if ( !qglGenProgramsARB ) - { + if (!qglGenProgramsARB) { return; } // Allocate and Load the global 'Glow' Vertex Program. - AReis - qglGenProgramsARB( 1, &tr.glowVShader ); - qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, tr.glowVShader ); - qglProgramStringARB( GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, ( GLsizei ) strlen( ( char * ) g_strGlowVShaderARB ), g_strGlowVShaderARB ); + qglGenProgramsARB(1, &tr.glowVShader); + qglBindProgramARB(GL_VERTEX_PROGRAM_ARB, tr.glowVShader); + qglProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen((char *)g_strGlowVShaderARB), g_strGlowVShaderARB); -// const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); + // const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); int iErrPos = 0; - qglGetIntegerv( GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos ); - assert( iErrPos == -1 ); + qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos); + assert(iErrPos == -1); // NOTE: I make an assumption here. If you have (current) nvidia hardware, you obviously support register combiners instead of fragment // programs, so use those. The problem with this is that nv30 WILL support fragment shaders, breaking this logic. The good thing is that // if you always ask for regcoms before fragment shaders, you'll always just use regcoms (problem solved... for now). - AReis // Load Pixel Shaders (either regcoms or fragprogs). - if ( qglCombinerParameteriNV ) - { + if (qglCombinerParameteriNV) { // The purpose of this regcom is to blend all the pixels together from the 4 texture units, but with their // texture coordinates offset by 1 (or more) texels, effectively letting us blend adjoining pixels. The weight is // used to either strengthen or weaken the pixel intensity. The more it diffuses (the higher the radius of the glow), @@ -168,41 +158,39 @@ void ARB_InitGPUShaders(void) { madd r0, c0, t2, r0; madd r0, c0, t3, r0; */ - tr.glowPShader = qglGenLists( 1 ); - qglNewList( tr.glowPShader, GL_COMPILE ); - qglCombinerParameteriNV( GL_NUM_GENERAL_COMBINERS_NV, 2 ); - - // spare0 = fBlend * tex0 + fBlend * tex1. - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerOutputNV( GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); - - // spare1 = fBlend * tex2 + fBlend * tex3. - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerInputNV( GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglCombinerOutputNV( GL_COMBINER1_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE1_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE ); - - // ( A * B ) + ( ( 1 - A ) * C ) + D = ( spare0 * 1 ) + ( ( 1 - spare0 ) * 0 ) + spare1 == spare0 + spare1. - qglFinalCombinerInputNV( GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); - qglFinalCombinerInputNV( GL_VARIABLE_D_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB ); + tr.glowPShader = qglGenLists(1); + qglNewList(tr.glowPShader, GL_COMPILE); + qglCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, 2); + + // spare0 = fBlend * tex0 + fBlend * tex1. + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); + + // spare1 = fBlend * tex2 + fBlend * tex3. + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE3_ARB, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_D_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglCombinerOutputNV(GL_COMBINER1_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE1_NV, GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); + + // ( A * B ) + ( ( 1 - A ) * C ) + D = ( spare0 * 1 ) + ( ( 1 - spare0 ) * 0 ) + spare1 == spare0 + spare1. + qglFinalCombinerInputNV(GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + qglFinalCombinerInputNV(GL_VARIABLE_D_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); qglEndList(); - } - else - { - qglGenProgramsARB( 1, &tr.glowPShader ); - qglBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader ); - qglProgramStringARB( GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, ( GLsizei ) strlen( ( char * ) g_strGlowPShaderARB ), g_strGlowPShaderARB ); + } else { + qglGenProgramsARB(1, &tr.glowPShader); + qglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader); + qglProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen((char *)g_strGlowPShaderARB), g_strGlowPShaderARB); -// const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); + // const GLubyte *strErr = qglGetString( GL_PROGRAM_ERROR_STRING_ARB ); int iErrPos = 0; - qglGetIntegerv( GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos ); - assert( iErrPos == -1 ); + qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &iErrPos); + assert(iErrPos == -1); } qglGenProgramsARB(1, &tr.gammaCorrectVtxShader); @@ -211,20 +199,16 @@ void ARB_InitGPUShaders(void) { int errorChar; qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorChar); - if ( errorChar != -1 ) - { + if (errorChar != -1) { Com_Printf(S_COLOR_RED "ERROR: Failed to compile gamma correction vertex shader. Error at character %d\n", errorChar); glConfigExt.doGammaCorrectionWithShaders = qfalse; - } - else - { + } else { qglGenProgramsARB(1, &tr.gammaCorrectPxShader); qglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, tr.gammaCorrectPxShader); qglProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(gammaCorrectPxShader), gammaCorrectPxShader); qglGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorChar); - if ( errorChar != -1 ) - { + if (errorChar != -1) { Com_Printf(S_COLOR_RED "Failed to compile gamma correction pixel shader. Error at character %d\n", errorChar); glConfigExt.doGammaCorrectionWithShaders = qfalse; } diff --git a/codemp/rd-vanilla/tr_backend.cpp b/codemp/rd-vanilla/tr_backend.cpp index d5091999c2..a09daeaa9d 100644 --- a/codemp/rd-vanilla/tr_backend.cpp +++ b/codemp/rd-vanilla/tr_backend.cpp @@ -25,14 +25,14 @@ along with this program; if not, see . #include "glext.h" #include "tr_WorldEffects.h" -backEndData_t *backEndData; -backEndState_t backEnd; +backEndData_t *backEndData; +backEndState_t backEnd; bool tr_stencilled = false; -extern qboolean tr_distortionPrePost; //tr_shadows.cpp -extern qboolean tr_distortionNegate; //tr_shadows.cpp -extern void RB_CaptureScreenImage(void); //tr_shadows.cpp -extern void RB_DistortionFill(void); //tr_shadows.cpp +extern qboolean tr_distortionPrePost; // tr_shadows.cpp +extern qboolean tr_distortionNegate; // tr_shadows.cpp +extern void RB_CaptureScreenImage(void); // tr_shadows.cpp +extern void RB_DistortionFill(void); // tr_shadows.cpp static void RB_DrawGlowOverlay(); static void RB_BlurGlowTexture(); @@ -48,122 +48,95 @@ extern void R_SetupFrustum(void); static const float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; /* ** GL_Bind */ -void GL_Bind( image_t *image ) { +void GL_Bind(image_t *image) { int texnum; - if ( !image ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "GL_Bind: NULL image\n" ); + if (!image) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "GL_Bind: NULL image\n"); texnum = tr.defaultImage->texnum; } else { texnum = image->texnum; } - if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option + if (r_nobind->integer && tr.dlightImage) { // performance evaluation option texnum = tr.dlightImage->texnum; } - if ( glState.currenttextures[glState.currenttmu] != texnum ) { + if (glState.currenttextures[glState.currenttmu] != texnum) { image->frameUsed = tr.frameCount; glState.currenttextures[glState.currenttmu] = texnum; - qglBindTexture (GL_TEXTURE_2D, texnum); + qglBindTexture(GL_TEXTURE_2D, texnum); } } /* ** GL_SelectTexture */ -void GL_SelectTexture( int unit ) -{ - if ( glState.currenttmu == unit ) - { +void GL_SelectTexture(int unit) { + if (glState.currenttmu == unit) { return; } - if ( unit == 0 ) - { - qglActiveTextureARB( GL_TEXTURE0_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE0_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE0_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE0_ARB )\n" ); - } - else if ( unit == 1 ) - { - qglActiveTextureARB( GL_TEXTURE1_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE1_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE1_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE1_ARB )\n" ); - } - else if ( unit == 2 ) - { - qglActiveTextureARB( GL_TEXTURE2_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE2_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE2_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE2_ARB )\n" ); - } - else if ( unit == 3 ) - { - qglActiveTextureARB( GL_TEXTURE3_ARB ); - GLimp_LogComment( "glActiveTextureARB( GL_TEXTURE3_ARB )\n" ); - qglClientActiveTextureARB( GL_TEXTURE3_ARB ); - GLimp_LogComment( "glClientActiveTextureARB( GL_TEXTURE3_ARB )\n" ); - } - else { - Com_Error( ERR_DROP, "GL_SelectTexture: unit = %i", unit ); + if (unit == 0) { + qglActiveTextureARB(GL_TEXTURE0_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE0_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE0_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE0_ARB )\n"); + } else if (unit == 1) { + qglActiveTextureARB(GL_TEXTURE1_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE1_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE1_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE1_ARB )\n"); + } else if (unit == 2) { + qglActiveTextureARB(GL_TEXTURE2_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE2_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE2_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE2_ARB )\n"); + } else if (unit == 3) { + qglActiveTextureARB(GL_TEXTURE3_ARB); + GLimp_LogComment("glActiveTextureARB( GL_TEXTURE3_ARB )\n"); + qglClientActiveTextureARB(GL_TEXTURE3_ARB); + GLimp_LogComment("glClientActiveTextureARB( GL_TEXTURE3_ARB )\n"); + } else { + Com_Error(ERR_DROP, "GL_SelectTexture: unit = %i", unit); } glState.currenttmu = unit; } - /* ** GL_Cull */ -void GL_Cull( int cullType ) { - if ( glState.faceCulling == cullType ) { +void GL_Cull(int cullType) { + if (glState.faceCulling == cullType) { return; } glState.faceCulling = cullType; - if (backEnd.projection2D) { //don't care, we're in 2d when it's always disabled + if (backEnd.projection2D) { // don't care, we're in 2d when it's always disabled return; } - if ( cullType == CT_TWO_SIDED ) - { - qglDisable( GL_CULL_FACE ); - } - else - { - qglEnable( GL_CULL_FACE ); + if (cullType == CT_TWO_SIDED) { + qglDisable(GL_CULL_FACE); + } else { + qglEnable(GL_CULL_FACE); - if ( cullType == CT_BACK_SIDED ) - { - if ( backEnd.viewParms.isMirror ) - { - qglCullFace( GL_FRONT ); - } - else - { - qglCullFace( GL_BACK ); - } - } - else - { - if ( backEnd.viewParms.isMirror ) - { - qglCullFace( GL_BACK ); + if (cullType == CT_BACK_SIDED) { + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_FRONT); + } else { + qglCullFace(GL_BACK); } - else - { - qglCullFace( GL_FRONT ); + } else { + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_BACK); + } else { + qglCullFace(GL_FRONT); } } } @@ -172,32 +145,28 @@ void GL_Cull( int cullType ) { /* ** GL_TexEnv */ -void GL_TexEnv( int env ) -{ - if ( env == glState.texEnv[glState.currenttmu] ) - { +void GL_TexEnv(int env) { + if (env == glState.texEnv[glState.currenttmu]) { return; } glState.texEnv[glState.currenttmu] = env; - - switch ( env ) - { + switch (env) { case GL_MODULATE: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); break; case GL_REPLACE: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); break; case GL_DECAL: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); break; case GL_ADD: - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD ); + qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD); break; default: - Com_Error( ERR_DROP, "GL_TexEnv: invalid env '%d' passed\n", env ); + Com_Error(ERR_DROP, "GL_TexEnv: invalid env '%d' passed\n", env); break; } } @@ -208,41 +177,32 @@ void GL_TexEnv( int env ) ** This routine is responsible for setting the most commonly changed state ** in Q3. */ -void GL_State( uint32_t stateBits ) -{ +void GL_State(uint32_t stateBits) { uint32_t diff = stateBits ^ glState.glStateBits; - if ( !diff ) - { + if (!diff) { return; } // // check depthFunc bits // - if ( diff & GLS_DEPTHFUNC_EQUAL ) - { - if ( stateBits & GLS_DEPTHFUNC_EQUAL ) - { - qglDepthFunc( GL_EQUAL ); - } - else - { - qglDepthFunc( GL_LEQUAL ); + if (diff & GLS_DEPTHFUNC_EQUAL) { + if (stateBits & GLS_DEPTHFUNC_EQUAL) { + qglDepthFunc(GL_EQUAL); + } else { + qglDepthFunc(GL_LEQUAL); } } // // check blend bits // - if ( diff & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { + if (diff & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { GLenum srcFactor, dstFactor; - if ( stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) - { - switch ( stateBits & GLS_SRCBLEND_BITS ) - { + if (stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) { + switch (stateBits & GLS_SRCBLEND_BITS) { case GLS_SRCBLEND_ZERO: srcFactor = GL_ZERO; break; @@ -271,13 +231,12 @@ void GL_State( uint32_t stateBits ) srcFactor = GL_SRC_ALPHA_SATURATE; break; default: - srcFactor = GL_ONE; // to get warning to shut up - Com_Error( ERR_DROP, "GL_State: invalid src blend state bits\n" ); + srcFactor = GL_ONE; // to get warning to shut up + Com_Error(ERR_DROP, "GL_State: invalid src blend state bits\n"); break; } - switch ( stateBits & GLS_DSTBLEND_BITS ) - { + switch (stateBits & GLS_DSTBLEND_BITS) { case GLS_DSTBLEND_ZERO: dstFactor = GL_ZERO; break; @@ -303,93 +262,77 @@ void GL_State( uint32_t stateBits ) dstFactor = GL_ONE_MINUS_DST_ALPHA; break; default: - dstFactor = GL_ONE; // to get warning to shut up - Com_Error( ERR_DROP, "GL_State: invalid dst blend state bits\n" ); + dstFactor = GL_ONE; // to get warning to shut up + Com_Error(ERR_DROP, "GL_State: invalid dst blend state bits\n"); break; } - qglEnable( GL_BLEND ); - qglBlendFunc( srcFactor, dstFactor ); - } - else - { - qglDisable( GL_BLEND ); + qglEnable(GL_BLEND); + qglBlendFunc(srcFactor, dstFactor); + } else { + qglDisable(GL_BLEND); } } // // check depthmask // - if ( diff & GLS_DEPTHMASK_TRUE ) - { - if ( stateBits & GLS_DEPTHMASK_TRUE ) - { - qglDepthMask( GL_TRUE ); - } - else - { - qglDepthMask( GL_FALSE ); + if (diff & GLS_DEPTHMASK_TRUE) { + if (stateBits & GLS_DEPTHMASK_TRUE) { + qglDepthMask(GL_TRUE); + } else { + qglDepthMask(GL_FALSE); } } // // fill/line mode // - if ( diff & GLS_POLYMODE_LINE ) - { - if ( stateBits & GLS_POLYMODE_LINE ) - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); - } - else - { - qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + if (diff & GLS_POLYMODE_LINE) { + if (stateBits & GLS_POLYMODE_LINE) { + qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + } else { + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } // // depthtest // - if ( diff & GLS_DEPTHTEST_DISABLE ) - { - if ( stateBits & GLS_DEPTHTEST_DISABLE ) - { - qglDisable( GL_DEPTH_TEST ); - } - else - { - qglEnable( GL_DEPTH_TEST ); + if (diff & GLS_DEPTHTEST_DISABLE) { + if (stateBits & GLS_DEPTHTEST_DISABLE) { + qglDisable(GL_DEPTH_TEST); + } else { + qglEnable(GL_DEPTH_TEST); } } // // alpha test // - if ( diff & GLS_ATEST_BITS ) - { - switch ( stateBits & GLS_ATEST_BITS ) - { + if (diff & GLS_ATEST_BITS) { + switch (stateBits & GLS_ATEST_BITS) { case 0: - qglDisable( GL_ALPHA_TEST ); + qglDisable(GL_ALPHA_TEST); break; case GLS_ATEST_GT_0: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GREATER, 0.0f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GREATER, 0.0f); break; case GLS_ATEST_LT_80: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_LESS, 0.5f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_LESS, 0.5f); break; case GLS_ATEST_GE_80: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GEQUAL, 0.5f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GEQUAL, 0.5f); break; case GLS_ATEST_GE_C0: - qglEnable( GL_ALPHA_TEST ); - qglAlphaFunc( GL_GEQUAL, 0.75f ); + qglEnable(GL_ALPHA_TEST); + qglAlphaFunc(GL_GEQUAL, 0.75f); break; default: - assert( 0 ); + assert(0); break; } } @@ -397,8 +340,6 @@ void GL_State( uint32_t stateBits ) glState.glStateBits = stateBits; } - - /* ================ RB_Hyperspace @@ -406,31 +347,28 @@ RB_Hyperspace A player has predicted a teleport, but hasn't arrived yet ================ */ -static void RB_Hyperspace( void ) { - float c; +static void RB_Hyperspace(void) { + float c; - if ( !backEnd.isHyperspace ) { + if (!backEnd.isHyperspace) { // do initialization shit } - c = ( backEnd.refdef.time & 255 ) / 255.0f; - qglClearColor( c, c, c, 1 ); - qglClear( GL_COLOR_BUFFER_BIT ); + c = (backEnd.refdef.time & 255) / 255.0f; + qglClearColor(c, c, c, 1); + qglClear(GL_COLOR_BUFFER_BIT); backEnd.isHyperspace = qtrue; } - -void SetViewportAndScissor( void ) { +void SetViewportAndScissor(void) { qglMatrixMode(GL_PROJECTION); - qglLoadMatrixf( backEnd.viewParms.projectionMatrix ); + qglLoadMatrixf(backEnd.viewParms.projectionMatrix); qglMatrixMode(GL_MODELVIEW); // set the window clipping - qglViewport( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - qglScissor( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, - backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglViewport(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); + qglScissor(backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); } /* @@ -441,15 +379,15 @@ Any mirrored or portaled views have already been drawn, so prepare to actually render the visible surfaces for this view ================= */ -void RB_BeginDrawingView (void) { +void RB_BeginDrawingView(void) { int clearBits = GL_DEPTH_BUFFER_BIT; // sync with gl if needed - if ( r_finish->integer == 1 && !glState.finishCalled ) { - qglFinish (); + if (r_finish->integer == 1 && !glState.finishCalled) { + qglFinish(); glState.finishCalled = qtrue; } - if ( r_finish->integer == 0 ) { + if (r_finish->integer == 0) { glState.finishCalled = qtrue; } @@ -463,137 +401,122 @@ void RB_BeginDrawingView (void) { SetViewportAndScissor(); // ensures that depth writes are enabled for the depth clear - GL_State( GLS_DEFAULT ); + GL_State(GLS_DEFAULT); // clear relevant buffers - if ( r_measureOverdraw->integer || r_shadows->integer == 2 || tr_stencilled ) - { + if (r_measureOverdraw->integer || r_shadows->integer == 2 || tr_stencilled) { clearBits |= GL_STENCIL_BUFFER_BIT; tr_stencilled = false; } - if (skyboxportal) - { - if ( backEnd.refdef.rdflags & RDF_SKYBOXPORTAL ) - { // portal scene, clear whatever is necessary - if (r_fastsky->integer || (backEnd.refdef.rdflags & RDF_NOWORLDMODEL) ) - { // fastsky: clear color + if (skyboxportal) { + if (backEnd.refdef.rdflags & RDF_SKYBOXPORTAL) { // portal scene, clear whatever is necessary + if (r_fastsky->integer || (backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) { // fastsky: clear color // try clearing first with the portal sky fog color, then the world fog color, then finally a default clearBits |= GL_COLOR_BUFFER_BIT; - //rwwFIXMEFIXME: Clear with fog color if there is one - qglClearColor ( 0.5, 0.5, 0.5, 1.0 ); + // rwwFIXMEFIXME: Clear with fog color if there is one + qglClearColor(0.5, 0.5, 0.5, 1.0); } } - } - else - { - if ( r_fastsky->integer && !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && !g_bRenderGlowingObjects ) - { - clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used + } else { + if (r_fastsky->integer && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && !g_bRenderGlowingObjects) { + clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used #ifdef _DEBUG - qglClearColor( 0.8f, 0.7f, 0.4f, 1.0f ); // FIXME: get color of sky + qglClearColor(0.8f, 0.7f, 0.4f, 1.0f); // FIXME: get color of sky #else - qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); // FIXME: get color of sky + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); // FIXME: get color of sky #endif } } - if ( tr.refdef.rdflags & RDF_AUTOMAP || (!( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) && r_DynamicGlow->integer && !g_bRenderGlowingObjects ) ) - { - if (tr.world && tr.world->globalFog != -1) - { //this is because of a bug in multiple scenes I think, it needs to clear for the second scene but it doesn't normally. - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + if (tr.refdef.rdflags & RDF_AUTOMAP || (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && r_DynamicGlow->integer && !g_bRenderGlowingObjects)) { + if (tr.world && + tr.world->globalFog != -1) { // this is because of a bug in multiple scenes I think, it needs to clear for the second scene but it doesn't normally. + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; clearBits |= GL_COLOR_BUFFER_BIT; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); } } // If this pass is to just render the glowing objects, don't clear the depth buffer since // we're sharing it with the main scene (since the main scene has already been rendered). -AReis - if ( g_bRenderGlowingObjects ) - { + if (g_bRenderGlowingObjects) { clearBits &= ~GL_DEPTH_BUFFER_BIT; } - if (clearBits) - { - qglClear( clearBits ); + if (clearBits) { + qglClear(clearBits); } - if ( ( backEnd.refdef.rdflags & RDF_HYPERSPACE ) ) - { + if ((backEnd.refdef.rdflags & RDF_HYPERSPACE)) { RB_Hyperspace(); return; - } - else - { + } else { backEnd.isHyperspace = qfalse; } - glState.faceCulling = -1; // force face culling to set next time + glState.faceCulling = -1; // force face culling to set next time // we will only draw a sun if there was sky rendered in this view backEnd.skyRenderedThisView = qfalse; // clip to the plane of the portal - if ( backEnd.viewParms.isPortal ) { - float plane[4]; - double plane2[4]; + if (backEnd.viewParms.isPortal) { + float plane[4]; + double plane2[4]; plane[0] = backEnd.viewParms.portalPlane.normal[0]; plane[1] = backEnd.viewParms.portalPlane.normal[1]; plane[2] = backEnd.viewParms.portalPlane.normal[2]; plane[3] = backEnd.viewParms.portalPlane.dist; - plane2[0] = DotProduct (backEnd.viewParms.ori.axis[0], plane); - plane2[1] = DotProduct (backEnd.viewParms.ori.axis[1], plane); - plane2[2] = DotProduct (backEnd.viewParms.ori.axis[2], plane); - plane2[3] = DotProduct (plane, backEnd.viewParms.ori.origin) - plane[3]; + plane2[0] = DotProduct(backEnd.viewParms.ori.axis[0], plane); + plane2[1] = DotProduct(backEnd.viewParms.ori.axis[1], plane); + plane2[2] = DotProduct(backEnd.viewParms.ori.axis[2], plane); + plane2[3] = DotProduct(plane, backEnd.viewParms.ori.origin) - plane[3]; - qglLoadMatrixf( s_flipMatrix ); - qglClipPlane (GL_CLIP_PLANE0, plane2); - qglEnable (GL_CLIP_PLANE0); + qglLoadMatrixf(s_flipMatrix); + qglClipPlane(GL_CLIP_PLANE0, plane2); + qglEnable(GL_CLIP_PLANE0); } else { - qglDisable (GL_CLIP_PLANE0); + qglDisable(GL_CLIP_PLANE0); } } -#define MAC_EVENT_PUMP_MSEC 5 +#define MAC_EVENT_PUMP_MSEC 5 -//used by RF_DISTORTION -static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) -{ - int xcenter, ycenter; - vec3_t local, transformed; - vec3_t vfwd; - vec3_t vright; - vec3_t vup; +// used by RF_DISTORTION +static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y) { + int xcenter, ycenter; + vec3_t local, transformed; + vec3_t vfwd; + vec3_t vright; + vec3_t vup; float xzi; float yzi; xcenter = glConfig.vidWidth / 2; ycenter = glConfig.vidHeight / 2; - //AngleVectors (tr.refdef.viewangles, vfwd, vright, vup); + // AngleVectors (tr.refdef.viewangles, vfwd, vright, vup); VectorCopy(tr.refdef.viewaxis[0], vfwd); VectorCopy(tr.refdef.viewaxis[1], vright); VectorCopy(tr.refdef.viewaxis[2], vup); - VectorSubtract (worldCoord, tr.refdef.vieworg, local); + VectorSubtract(worldCoord, tr.refdef.vieworg, local); - transformed[0] = DotProduct(local,vright); - transformed[1] = DotProduct(local,vup); - transformed[2] = DotProduct(local,vfwd); + transformed[0] = DotProduct(local, vright); + transformed[1] = DotProduct(local, vup); + transformed[2] = DotProduct(local, vfwd); // Make sure Z is not negative. - if(transformed[2] < 0.01) - { + if (transformed[2] < 0.01) { return false; } - xzi = xcenter / transformed[2] * (90.0/tr.refdef.fov_x); - yzi = ycenter / transformed[2] * (90.0/tr.refdef.fov_y); + xzi = xcenter / transformed[2] * (90.0 / tr.refdef.fov_x); + yzi = ycenter / transformed[2] * (90.0 / tr.refdef.fov_y); *x = xcenter + xzi * transformed[0]; *y = ycenter - yzi * transformed[1]; @@ -601,11 +524,10 @@ static inline bool R_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, f return true; } -//used by RF_DISTORTION -static inline bool R_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y ) -{ - float xF, yF; - bool retVal = R_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF ); +// used by RF_DISTORTION +static inline bool R_WorldCoordToScreenCoord(vec3_t worldCoord, int *x, int *y) { + float xF, yF; + bool retVal = R_WorldCoordToScreenCoordFloat(worldCoord, &xF, &yF); *x = (int)xF; *y = (int)yF; return retVal; @@ -616,19 +538,19 @@ static inline bool R_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y RB_RenderDrawSurfList ================== */ -//number of possible surfs we can postrender. -//note that postrenders lack much of the optimization that the standard sort-render crap does, -//so it's slower. -#define MAX_POST_RENDERS 128 +// number of possible surfs we can postrender. +// note that postrenders lack much of the optimization that the standard sort-render crap does, +// so it's slower. +#define MAX_POST_RENDERS 128 typedef struct postRender_s { - int fogNum; - int entNum; - int dlighted; - int depthRange; - drawSurf_t *drawSurf; - shader_t *shader; - qboolean eValid; + int fogNum; + int entNum; + int dlighted; + int depthRange; + drawSurf_t *drawSurf; + shader_t *shader; + qboolean eValid; } postRender_t; static postRender_t g_postRenders[MAX_POST_RENDERS]; @@ -670,22 +592,21 @@ static inline bool R_AverageTessXYZ(vec3_t dest) } #endif -void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { - shader_t *shader, *oldShader; - int fogNum, oldFogNum; - int entityNum, oldEntityNum; - int dlighted, oldDlighted; - int depthRange, oldDepthRange; - int i; - drawSurf_t *drawSurf; - unsigned int oldSort; - float originalTime; - trRefEntity_t *curEnt; - postRender_t *pRender; - bool didShadowPass = false; - - if (g_bRenderGlowingObjects) - { //only shadow on initial passes +void RB_RenderDrawSurfList(drawSurf_t *drawSurfs, int numDrawSurfs) { + shader_t *shader, *oldShader; + int fogNum, oldFogNum; + int entityNum, oldEntityNum; + int dlighted, oldDlighted; + int depthRange, oldDepthRange; + int i; + drawSurf_t *drawSurf; + unsigned int oldSort; + float originalTime; + trRefEntity_t *curEnt; + postRender_t *pRender; + bool didShadowPass = false; + + if (g_bRenderGlowingObjects) { // only shadow on initial passes didShadowPass = true; } @@ -693,7 +614,7 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { originalTime = backEnd.refdef.floatTime; // clear the z buffer, set the modelview, etc - RB_BeginDrawingView (); + RB_BeginDrawingView(); // draw everything oldEntityNum = -1; @@ -702,24 +623,21 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { oldFogNum = -1; oldDepthRange = qfalse; oldDlighted = qfalse; - oldSort = (unsigned int) -1; + oldSort = (unsigned int)-1; depthRange = qfalse; backEnd.pc.c_surfaces += numDrawSurfs; - for (i = 0, drawSurf = drawSurfs ; i < numDrawSurfs ; i++, drawSurf++) - { - if ( drawSurf->sort == oldSort ) - { + for (i = 0, drawSurf = drawSurfs; i < numDrawSurfs; i++, drawSurf++) { + if (drawSurf->sort == oldSort) { // fast path, same as previous sort - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); continue; } - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted ); + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted); // If we're rendering glowing objects, but this shader has no stages with glow, skip it! - if ( g_bRenderGlowingObjects && !shader->hasGlow ) - { + if (g_bRenderGlowingObjects && !shader->hasGlow) { shader = oldShader; entityNum = oldEntityNum; fogNum = oldFogNum; @@ -733,38 +651,31 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // change the tess parameters if needed // a "entityMergable" shader is a shader that can have surfaces from seperate // entities merged into a single batch, like smoke and blood puff sprites - if (entityNum != REFENTITYNUM_WORLD && - g_numPostRenders < MAX_POST_RENDERS) - { - if ( (backEnd.refdef.entities[entityNum].e.renderfx & RF_DISTORTION) || - (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCEPOST) || - (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCE_ENT_ALPHA) ) - { //must render last + if (entityNum != REFENTITYNUM_WORLD && g_numPostRenders < MAX_POST_RENDERS) { + if ((backEnd.refdef.entities[entityNum].e.renderfx & RF_DISTORTION) || (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCEPOST) || + (backEnd.refdef.entities[entityNum].e.renderfx & RF_FORCE_ENT_ALPHA)) { // must render last curEnt = &backEnd.refdef.entities[entityNum]; pRender = &g_postRenders[g_numPostRenders]; g_numPostRenders++; depthRange = 0; - //figure this stuff out now and store it - if ( curEnt->e.renderfx & RF_NODEPTH ) - { + // figure this stuff out now and store it + if (curEnt->e.renderfx & RF_NODEPTH) { depthRange = 2; - } - else if ( curEnt->e.renderfx & RF_DEPTHHACK ) - { + } else if (curEnt->e.renderfx & RF_DEPTHHACK) { depthRange = 1; } pRender->depthRange = depthRange; - //It is not necessary to update the old* values because - //we are not updating now with the current values. + // It is not necessary to update the old* values because + // we are not updating now with the current values. depthRange = oldDepthRange; - //store off the ent num + // store off the ent num pRender->entNum = entityNum; - //remember the other values necessary for rendering this surf + // remember the other values necessary for rendering this surf pRender->drawSurf = drawSurf; pRender->dlighted = dlighted; pRender->fogNum = fogNum; @@ -777,19 +688,17 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { } else */ - { - pRender->eValid = qtrue; - } + { pRender->eValid = qtrue; } - //assure the info is back to the last set state + // assure the info is back to the last set state shader = oldShader; entityNum = oldEntityNum; fogNum = oldFogNum; dlighted = oldDlighted; - oldSort = -20; //invalidate this thing, cause we may want to postrender more surfs of the same sort + oldSort = -20; // invalidate this thing, cause we may want to postrender more surfs of the same sort - //continue without bothering to begin a draw surf + // continue without bothering to begin a draw surf continue; } } @@ -832,19 +741,16 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { } */ - if (shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted - || ( entityNum != oldEntityNum && !shader->entityMergable ) ) - { + if (shader != oldShader || fogNum != oldFogNum || dlighted != oldDlighted || (entityNum != oldEntityNum && !shader->entityMergable)) { if (oldShader != NULL) { RB_EndSurface(); - if (!didShadowPass && shader && shader->sort > SS_BANNER) - { + if (!didShadowPass && shader && shader->sort > SS_BANNER) { RB_ShadowFinish(); didShadowPass = true; } } - RB_BeginSurface( shader, fogNum ); + RB_BeginSurface(shader, fogNum); oldShader = shader; oldFogNum = fogNum; oldDlighted = dlighted; @@ -853,10 +759,10 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // // change the modelview matrix if needed // - if ( entityNum != oldEntityNum ) { + if (entityNum != oldEntityNum) { depthRange = 0; - if ( entityNum != REFENTITYNUM_WORLD ) { + if (entityNum != REFENTITYNUM_WORLD) { backEnd.currentEntity = &backEnd.refdef.entities[entityNum]; backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; @@ -865,18 +771,17 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; // set up the transformation matrix - R_RotateForEntity( backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori ); + R_RotateForEntity(backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori); // set up the dynamic lighting if needed - if ( backEnd.currentEntity->needDlights ) { - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + if (backEnd.currentEntity->needDlights) { + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } - if ( backEnd.currentEntity->e.renderfx & RF_NODEPTH ) { + if (backEnd.currentEntity->e.renderfx & RF_NODEPTH) { // No depth at all, very rare but some things for seeing through walls depthRange = 2; - } - else if ( backEnd.currentEntity->e.renderfx & RF_DEPTHHACK ) { + } else if (backEnd.currentEntity->e.renderfx & RF_DEPTHHACK) { // hack the depth range to prevent view model from poking into walls depthRange = 1; } @@ -887,28 +792,28 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // we have to reset the shaderTime as well otherwise image animations on // the world (like water) continue with the wrong frame tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } - qglLoadMatrixf( backEnd.ori.modelMatrix ); + qglLoadMatrixf(backEnd.ori.modelMatrix); // // change depthrange if needed // - if ( oldDepthRange != depthRange ) { - switch ( depthRange ) { - default: - case 0: - qglDepthRange (0, 1); - break; - - case 1: - qglDepthRange (0, .3); - break; - - case 2: - qglDepthRange (0, 0); - break; + if (oldDepthRange != depthRange) { + switch (depthRange) { + default: + case 0: + qglDepthRange(0, 1); + break; + + case 1: + qglDepthRange(0, .3); + break; + + case 2: + qglDepthRange(0, 0); + break; } oldDepthRange = depthRange; @@ -918,13 +823,13 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { } // add the triangles for this surface - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); } backEnd.refdef.floatTime = originalTime; // draw the contents of the last shader batch - //assert(entityNum < MAX_GENTITIES); + // assert(entityNum < MAX_GENTITIES); if (oldShader != NULL) { RB_EndSurface(); @@ -935,23 +840,20 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { glState.glStateBits = -1; #endif - if (tr_stencilled && tr_distortionPrePost) - { //ok, cap it now + if (tr_stencilled && tr_distortionPrePost) { // ok, cap it now RB_CaptureScreenImage(); RB_DistortionFill(); } - //render distortion surfs (or anything else that needs to be post-rendered) - if (g_numPostRenders > 0) - { + // render distortion surfs (or anything else that needs to be post-rendered) + if (g_numPostRenders > 0) { int lastPostEnt = -1; - while (g_numPostRenders > 0) - { + while (g_numPostRenders > 0) { g_numPostRenders--; pRender = &g_postRenders[g_numPostRenders]; - RB_BeginSurface( pRender->shader, pRender->fogNum ); + RB_BeginSurface(pRender->shader, pRender->fogNum); /* if (!pRender->eValid && pRender->entNum == REFENTITYNUM_WORLD) @@ -967,7 +869,7 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { } else */ - { //ent + { // ent backEnd.currentEntity = &backEnd.refdef.entities[pRender->entNum]; backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; @@ -976,31 +878,30 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; // set up the transformation matrix - R_RotateForEntity( backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori ); + R_RotateForEntity(backEnd.currentEntity, &backEnd.viewParms, &backEnd.ori); // set up the dynamic lighting if needed - if ( backEnd.currentEntity->needDlights ) { - R_TransformDlights( backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori ); + if (backEnd.currentEntity->needDlights) { + R_TransformDlights(backEnd.refdef.num_dlights, backEnd.refdef.dlights, &backEnd.ori); } } - qglLoadMatrixf( backEnd.ori.modelMatrix ); + qglLoadMatrixf(backEnd.ori.modelMatrix); depthRange = pRender->depthRange; - switch ( depthRange ) - { - default: - case 0: - qglDepthRange (0, 1); - break; + switch (depthRange) { + default: + case 0: + qglDepthRange(0, 1); + break; - case 1: - qglDepthRange (0, .3); - break; + case 1: + qglDepthRange(0, .3); + break; - case 2: - qglDepthRange (0, 0); - break; + case 2: + qglDepthRange(0, 0); + break; } /* @@ -1071,20 +972,17 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { lastPostEnt = ENTITYNUM_NONE; } */ - if (!pRender->eValid) - { - } - else if ((backEnd.refdef.entities[pRender->entNum].e.renderfx & RF_DISTORTION) && - lastPostEnt != pRender->entNum) - { //do the capture now, we only need to do it once per ent + if (!pRender->eValid) { + } else if ((backEnd.refdef.entities[pRender->entNum].e.renderfx & RF_DISTORTION) && + lastPostEnt != pRender->entNum) { // do the capture now, we only need to do it once per ent int x, y; int rad; bool r; - //We are going to just bind this, and then the CopyTexImage is going to - //stomp over this texture num in texture memory. - GL_Bind( tr.screenImage ); + // We are going to just bind this, and then the CopyTexImage is going to + // stomp over this texture num in texture memory. + GL_Bind(tr.screenImage); -#if 0 //yeah.. this kinda worked but it was stupid +#if 0 // yeah.. this kinda worked but it was stupid if (pRender->eValid) { r = R_WorldCoordToScreenCoord( backEnd.currentEntity->e.origin, &x, &y ); @@ -1102,61 +1000,52 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { rad = 256; } #else - r = R_WorldCoordToScreenCoord( backEnd.currentEntity->e.origin, &x, &y ); + r = R_WorldCoordToScreenCoord(backEnd.currentEntity->e.origin, &x, &y); rad = backEnd.currentEntity->e.radius; #endif - if (r) - { + if (r) { int cX, cY; - cX = glConfig.vidWidth-x-(rad/2); - cY = glConfig.vidHeight-y-(rad/2); + cX = glConfig.vidWidth - x - (rad / 2); + cY = glConfig.vidHeight - y - (rad / 2); - if (cX+rad > glConfig.vidWidth) - { //would it go off screen? - cX = glConfig.vidWidth-rad; - } - else if (cX < 0) - { //cap it off at 0 + if (cX + rad > glConfig.vidWidth) { // would it go off screen? + cX = glConfig.vidWidth - rad; + } else if (cX < 0) { // cap it off at 0 cX = 0; } - if (cY+rad > glConfig.vidHeight) - { //would it go off screen? - cY = glConfig.vidHeight-rad; - } - else if (cY < 0) - { //cap it off at 0 + if (cY + rad > glConfig.vidHeight) { // would it go off screen? + cY = glConfig.vidHeight - rad; + } else if (cY < 0) { // cap it off at 0 cY = 0; } - //now copy a portion of the screen to this texture + // now copy a portion of the screen to this texture qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, cX, cY, rad, rad, 0); lastPostEnt = pRender->entNum; } } - rb_surfaceTable[ *pRender->drawSurf->surface ]( pRender->drawSurf->surface ); + rb_surfaceTable[*pRender->drawSurf->surface](pRender->drawSurf->surface); RB_EndSurface(); } } // go back to the world modelview matrix - qglLoadMatrixf( backEnd.viewParms.world.modelMatrix ); - if ( depthRange ) { - qglDepthRange (0, 1); + qglLoadMatrixf(backEnd.viewParms.world.modelMatrix); + if (depthRange) { + qglDepthRange(0, 1); } #if 0 RB_DrawSun(); #endif - if (tr_stencilled && !tr_distortionPrePost) - { //draw in the stencil buffer's cutout + if (tr_stencilled && !tr_distortionPrePost) { // draw in the stencil buffer's cutout RB_DistortionFill(); } - if (!didShadowPass) - { + if (!didShadowPass) { // darken down any stencil shadows RB_ShadowFinish(); didShadowPass = true; @@ -1165,10 +1054,9 @@ void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) { // add light flares on lights that aren't obscured // rww - 9-13-01 [1-26-01-sof2] -// RB_RenderFlares(); + // RB_RenderFlares(); } - /* ============================================================================ @@ -1183,31 +1071,28 @@ RB_SetGL2D ================ */ -void RB_SetGL2D (void) { +void RB_SetGL2D(void) { backEnd.projection2D = qtrue; // set 2D virtual screen size - qglViewport( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); - qglScissor( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); + qglViewport(0, 0, glConfig.vidWidth, glConfig.vidHeight); + qglScissor(0, 0, glConfig.vidWidth, glConfig.vidHeight); qglMatrixMode(GL_PROJECTION); - qglLoadIdentity (); - qglOrtho (0, 640, 480, 0, 0, 1); + qglLoadIdentity(); + qglOrtho(0, 640, 480, 0, 0, 1); qglMatrixMode(GL_MODELVIEW); - qglLoadIdentity (); + qglLoadIdentity(); - GL_State( GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - qglDisable( GL_CULL_FACE ); - qglDisable( GL_CLIP_PLANE0 ); + qglDisable(GL_CULL_FACE); + qglDisable(GL_CLIP_PLANE0); // set time for 2D shaders - backEnd.refdef.time = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + backEnd.refdef.time = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); backEnd.refdef.floatTime = backEnd.refdef.time * 0.001f; } - /* ============= RE_StretchRaw @@ -1217,16 +1102,15 @@ Stretches a raw 32 bit power of 2 bitmap image over the given screen rectangle. Used for cinematics. ============= */ -void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) -{ - int start, end; +void RE_StretchRaw(int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) { + int start, end; - if ( !tr.registered ) { + if (!tr.registered) { return; } R_IssuePendingRenderCommands(); - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } @@ -1234,88 +1118,86 @@ void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte * qglFinish(); start = end = 0; - if ( r_speeds->integer ) { - start = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + if (r_speeds->integer) { + start = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); } // make sure rows and cols are powers of 2 - if ( (cols&(cols-1)) || (rows&(rows-1)) ) - { - Com_Error (ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); + if ((cols & (cols - 1)) || (rows & (rows - 1))) { + Com_Error(ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); } - GL_Bind( tr.scratchImage[client] ); + GL_Bind(tr.scratchImage[client]); // if the scratchImage isn't in the format we want, specify it as a new texture - if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) { + if (cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height) { tr.scratchImage[client]->width = cols; tr.scratchImage[client]->height = rows; - qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); + qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); } else { if (dirty) { // otherwise, just subimage upload it so that drivers can tell we are going to be changing // it and don't try and do a texture compression - qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data); } } - if ( r_speeds->integer ) { - end = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); - ri.Printf( PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start ); + if (r_speeds->integer) { + end = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); + ri.Printf(PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start); } RB_SetGL2D(); - qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight ); - - qglBegin (GL_QUADS); - qglTexCoord2f ( 0.5f / cols, 0.5f / rows ); - qglVertex2f (x, y); - qglTexCoord2f ( ( cols - 0.5f ) / cols , 0.5f / rows ); - qglVertex2f (x+w, y); - qglTexCoord2f ( ( cols - 0.5f ) / cols, ( rows - 0.5f ) / rows ); - qglVertex2f (x+w, y+h); - qglTexCoord2f ( 0.5f / cols, ( rows - 0.5f ) / rows ); - qglVertex2f (x, y+h); - qglEnd (); + qglColor3f(tr.identityLight, tr.identityLight, tr.identityLight); + + qglBegin(GL_QUADS); + qglTexCoord2f(0.5f / cols, 0.5f / rows); + qglVertex2f(x, y); + qglTexCoord2f((cols - 0.5f) / cols, 0.5f / rows); + qglVertex2f(x + w, y); + qglTexCoord2f((cols - 0.5f) / cols, (rows - 0.5f) / rows); + qglVertex2f(x + w, y + h); + qglTexCoord2f(0.5f / cols, (rows - 0.5f) / rows); + qglVertex2f(x, y + h); + qglEnd(); } -void RE_UploadCinematic (int cols, int rows, const byte *data, int client, qboolean dirty) { +void RE_UploadCinematic(int cols, int rows, const byte *data, int client, qboolean dirty) { - GL_Bind( tr.scratchImage[client] ); + GL_Bind(tr.scratchImage[client]); // if the scratchImage isn't in the format we want, specify it as a new texture - if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) { + if (cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height) { // Note: q3 has the commented sections being uploaded width/height - tr.scratchImage[client]->width = /*tr.scratchImage[client]->width =*/ cols; - tr.scratchImage[client]->height = /*tr.scratchImage[client]->height =*/ rows; - qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP ); + tr.scratchImage[client]->width = /*tr.scratchImage[client]->width =*/cols; + tr.scratchImage[client]->height = /*tr.scratchImage[client]->height =*/rows; + qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glConfig.clampToEdgeAvailable ? GL_CLAMP_TO_EDGE : GL_CLAMP); } else { if (dirty) { // otherwise, just subimage upload it so that drivers can tell we are going to be changing // it and don't try and do a texture compression - qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data); } } } - /* ============= RB_SetColor ============= */ -const void *RB_SetColor( const void *data ) { - const setColorCommand_t *cmd; +const void *RB_SetColor(const void *data) { + const setColorCommand_t *cmd; cmd = (const setColorCommand_t *)data; @@ -1332,86 +1214,88 @@ const void *RB_SetColor( const void *data ) { RB_StretchPic ============= */ -const void *RB_StretchPic ( const void *data ) { - const stretchPicCommand_t *cmd; +const void *RB_StretchPic(const void *data) { + const stretchPicCommand_t *cmd; shader_t *shader; - int numVerts, numIndexes; + int numVerts, numIndexes; cmd = (const stretchPicCommand_t *)data; - if ( !backEnd.projection2D ) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); numVerts = tess.numVertexes; numIndexes = tess.numIndexes; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = cmd->x; - tess.xyz[ numVerts ][1] = cmd->y; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = cmd->x; + tess.xyz[numVerts][1] = cmd->y; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 1 ][1] = cmd->y; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 1][1] = cmd->y; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = cmd->x + cmd->w; - tess.xyz[ numVerts + 2 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = cmd->x + cmd->w; + tess.xyz[numVerts + 2][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = cmd->x; - tess.xyz[ numVerts + 3 ][1] = cmd->y + cmd->h; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = cmd->x; + tess.xyz[numVerts + 3][1] = cmd->y + cmd->h; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); } - /* ============= RB_DrawRotatePic ============= */ -const void *RB_RotatePic ( const void *data ) -{ - const rotatePicCommand_t *cmd; +const void *RB_RotatePic(const void *data) { + const rotatePicCommand_t *cmd; image_t *image; shader_t *shader; @@ -1420,80 +1304,79 @@ const void *RB_RotatePic ( const void *data ) shader = cmd->shader; image = &shader->stages[0].bundle[0].image[0]; - if ( image ) { - if ( !backEnd.projection2D ) { + if (image) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd-> a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x + cmd->w, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x + cmd->w, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[2][0]; + tess.xyz[numVerts + 1][1] = m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); - } return (const void *)(cmd + 1); @@ -1504,9 +1387,8 @@ const void *RB_RotatePic ( const void *data ) RB_DrawRotatePic2 ============= */ -const void *RB_RotatePic2 ( const void *data ) -{ - const rotatePicCommand_t *cmd; +const void *RB_RotatePic2(const void *data) { + const rotatePicCommand_t *cmd; image_t *image; shader_t *shader; @@ -1514,86 +1396,83 @@ const void *RB_RotatePic2 ( const void *data ) shader = cmd->shader; - if ( shader->numUnfoggedPasses ) - { + if (shader->numUnfoggedPasses) { image = &shader->stages[0].bundle[0].image[0]; - if ( image ) - { - if ( !backEnd.projection2D ) { + if (image) { + if (!backEnd.projection2D) { RB_SetGL2D(); } shader = cmd->shader; - if ( shader != tess.shader ) { - if ( tess.numIndexes ) { + if (shader != tess.shader) { + if (tess.numIndexes) { RB_EndSurface(); } backEnd.currentEntity = &backEnd.entity2D; - RB_BeginSurface( shader, 0 ); + RB_BeginSurface(shader, 0); } - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); int numVerts = tess.numVertexes; int numIndexes = tess.numIndexes; - float angle = DEG2RAD( cmd-> a ); - float s = sinf( angle ); - float c = cosf( angle ); + float angle = DEG2RAD(cmd->a); + float s = sinf(angle); + float c = cosf(angle); - matrix3_t m = { - { c, s, 0.0f }, - { -s, c, 0.0f }, - { cmd->x, cmd->y, 1.0f } - }; + matrix3_t m = {{c, s, 0.0f}, {-s, c, 0.0f}, {cmd->x, cmd->y, 1.0f}}; tess.numVertexes += 4; tess.numIndexes += 6; - tess.indexes[ numIndexes ] = numVerts + 3; - tess.indexes[ numIndexes + 1 ] = numVerts + 0; - tess.indexes[ numIndexes + 2 ] = numVerts + 2; - tess.indexes[ numIndexes + 3 ] = numVerts + 2; - tess.indexes[ numIndexes + 4 ] = numVerts + 0; - tess.indexes[ numIndexes + 5 ] = numVerts + 1; + tess.indexes[numIndexes] = numVerts + 3; + tess.indexes[numIndexes + 1] = numVerts + 0; + tess.indexes[numIndexes + 2] = numVerts + 2; + tess.indexes[numIndexes + 3] = numVerts + 2; + tess.indexes[numIndexes + 4] = numVerts + 0; + tess.indexes[numIndexes + 5] = numVerts + 1; byteAlias_t *baDest = NULL, *baSource = (byteAlias_t *)&backEnd.color2D; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; baDest->ui = baSource->ui; - baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 0]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 1]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 2]; + baDest->ui = baSource->ui; + baDest = (byteAlias_t *)&tess.vertexColors[numVerts + 3]; + baDest->ui = baSource->ui; - tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts ][2] = 0; + tess.xyz[numVerts][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts][2] = 0; - tess.texCoords[ numVerts ][0][0] = cmd->s1; - tess.texCoords[ numVerts ][0][1] = cmd->t1; + tess.texCoords[numVerts][0][0] = cmd->s1; + tess.texCoords[numVerts][0][1] = cmd->t1; - tess.xyz[ numVerts + 1 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 1 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 1 ][2] = 0; + tess.xyz[numVerts + 1][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 1][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 1][2] = 0; - tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + tess.texCoords[numVerts + 1][0][0] = cmd->s2; + tess.texCoords[numVerts + 1][0][1] = cmd->t1; - tess.xyz[ numVerts + 2 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 2 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 2 ][2] = 0; + tess.xyz[numVerts + 2][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 2][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 2][2] = 0; - tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; - tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 2][0][0] = cmd->s2; + tess.texCoords[numVerts + 2][0][1] = cmd->t2; - tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; - tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; - tess.xyz[ numVerts + 3 ][2] = 0; + tess.xyz[numVerts + 3][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[numVerts + 3][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[numVerts + 3][2] = 0; - tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; - tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + tess.texCoords[numVerts + 3][0][0] = cmd->s1; + tess.texCoords[numVerts + 3][0][1] = cmd->t2; return (const void *)(cmd + 1); - #if 0 // Hmmm, this is not too cool GL_State( GLS_DEPTHTEST_DISABLE | @@ -1606,18 +1485,17 @@ const void *RB_RotatePic2 ( const void *data ) return (const void *)(cmd + 1); } - /* ============= RB_DrawSurfs ============= */ -const void *RB_DrawSurfs( const void *data ) { - const drawSurfsCommand_t *cmd; +const void *RB_DrawSurfs(const void *data) { + const drawSurfsCommand_t *cmd; // finish any 2D drawing if needed - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } @@ -1626,7 +1504,7 @@ const void *RB_DrawSurfs( const void *data ) { backEnd.refdef = cmd->refdef; backEnd.viewParms = cmd->viewParms; - RB_RenderDrawSurfList( cmd->drawSurfs, cmd->numDrawSurfs ); + RB_RenderDrawSurfList(cmd->drawSurfs, cmd->numDrawSurfs); // Dynamic Glow/Flares: /* @@ -1638,34 +1516,33 @@ const void *RB_DrawSurfs( const void *data ) { */ // Render dynamic glowing/flaring objects. - if ( !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && g_bDynamicGlowSupported && r_DynamicGlow->integer ) - { + if (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL) && g_bDynamicGlowSupported && r_DynamicGlow->integer) { // Copy the normal scene to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, glConfig.vidWidth, glConfig.vidHeight ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, glConfig.vidWidth, glConfig.vidHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Just clear colors, but leave the depth buffer intact so we can 'share' it. - qglClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); - qglClear( GL_COLOR_BUFFER_BIT ); + qglClearColor(0.0f, 0.0f, 0.0f, 0.0f); + qglClear(GL_COLOR_BUFFER_BIT); // Render the glowing objects. g_bRenderGlowingObjects = true; - RB_RenderDrawSurfList( cmd->drawSurfs, cmd->numDrawSurfs ); + RB_RenderDrawSurfList(cmd->drawSurfs, cmd->numDrawSurfs); g_bRenderGlowingObjects = false; qglFinish(); // Copy the glow scene to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, glConfig.vidWidth, glConfig.vidHeight ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, glConfig.vidWidth, glConfig.vidHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Resize the viewport to the blur texture size. const int oldViewWidth = backEnd.viewParms.viewportWidth; @@ -1678,18 +1555,18 @@ const void *RB_DrawSurfs( const void *data ) { RB_BlurGlowTexture(); // Copy the finished glow scene back to texture. - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); // Set the viewport back to normal. backEnd.viewParms.viewportWidth = oldViewWidth; backEnd.viewParms.viewportHeight = oldViewHeight; SetViewportAndScissor(); - qglClear( GL_COLOR_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT); // Draw the glow additively over the screen. RB_DrawGlowOverlay(); @@ -1698,65 +1575,61 @@ const void *RB_DrawSurfs( const void *data ) { return (const void *)(cmd + 1); } - /* ============= RB_DrawBuffer ============= */ -const void *RB_DrawBuffer( const void *data ) { - const drawBufferCommand_t *cmd; +const void *RB_DrawBuffer(const void *data) { + const drawBufferCommand_t *cmd; cmd = (const drawBufferCommand_t *)data; - qglDrawBuffer( cmd->buffer ); + qglDrawBuffer(cmd->buffer); // clear screen for debugging - if (tr.world && tr.world->globalFog != -1) - { - const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; + if (tr.world && tr.world->globalFog != -1) { + const fog_t *fog = &tr.world->fogs[tr.world->globalFog]; - qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f ); - qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); - } - else if ( r_clear->integer ) { + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); + qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } else if (r_clear->integer) { int i = r_clear->integer; if (i == 42) { - i = Q_irand(0,8); + i = Q_irand(0, 8); } - switch (i) - { + switch (i) { default: - qglClearColor( 1, 0, 0.5, 1 ); // default q3 pink + qglClearColor(1, 0, 0.5, 1); // default q3 pink break; case 1: - qglClearColor( 1.0, 0.0, 0.0, 1.0); //red + qglClearColor(1.0, 0.0, 0.0, 1.0); // red break; case 2: - qglClearColor( 0.0, 1.0, 0.0, 1.0); //green + qglClearColor(0.0, 1.0, 0.0, 1.0); // green break; case 3: - qglClearColor( 1.0, 1.0, 0.0, 1.0); //yellow + qglClearColor(1.0, 1.0, 0.0, 1.0); // yellow break; case 4: - qglClearColor( 0.0, 0.0, 1.0, 1.0); //blue + qglClearColor(0.0, 0.0, 1.0, 1.0); // blue break; case 5: - qglClearColor( 0.0, 1.0, 1.0, 1.0); //cyan + qglClearColor(0.0, 1.0, 1.0, 1.0); // cyan break; case 6: - qglClearColor( 1.0, 0.0, 1.0, 1.0); //magenta + qglClearColor(1.0, 0.0, 1.0, 1.0); // magenta break; case 7: - qglClearColor( 1.0, 1.0, 1.0, 1.0); //white + qglClearColor(1.0, 1.0, 1.0, 1.0); // white break; case 8: - qglClearColor( 0.0, 0.0, 0.0, 1.0); //black + qglClearColor(0.0, 0.0, 0.0, 1.0); // black break; } - qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } return (const void *)(cmd + 1); @@ -1772,59 +1645,56 @@ was there. This is used to test for texture thrashing. Also called by RE_EndRegistration =============== */ -void RB_ShowImages( void ) { - image_t *image; - float x, y, w, h; -// int start, end; +void RB_ShowImages(void) { + image_t *image; + float x, y, w, h; + // int start, end; - if ( !backEnd.projection2D ) { + if (!backEnd.projection2D) { RB_SetGL2D(); } - qglClear( GL_COLOR_BUFFER_BIT ); + qglClear(GL_COLOR_BUFFER_BIT); qglFinish(); -// start = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + // start = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); - - int i=0; - R_Images_StartIteration(); - while ( (image = R_Images_GetNextIteration()) != NULL) - { + int i = 0; + R_Images_StartIteration(); + while ((image = R_Images_GetNextIteration()) != NULL) { w = glConfig.vidWidth / 20; h = glConfig.vidHeight / 15; x = i % 20 * w; y = i / 20 * h; // show in proportional size in mode 2 - if ( r_showImages->integer == 2 ) { + if (r_showImages->integer == 2) { w *= image->width / 512.0; h *= image->height / 512.0; } - GL_Bind( image ); - qglBegin (GL_QUADS); - qglTexCoord2f( 0, 0 ); - qglVertex2f( x, y ); - qglTexCoord2f( 1, 0 ); - qglVertex2f( x + w, y ); - qglTexCoord2f( 1, 1 ); - qglVertex2f( x + w, y + h ); - qglTexCoord2f( 0, 1 ); - qglVertex2f( x, y + h ); + GL_Bind(image); + qglBegin(GL_QUADS); + qglTexCoord2f(0, 0); + qglVertex2f(x, y); + qglTexCoord2f(1, 0); + qglVertex2f(x + w, y); + qglTexCoord2f(1, 1); + qglVertex2f(x + w, y + h); + qglTexCoord2f(0, 1); + qglVertex2f(x, y + h); qglEnd(); i++; } qglFinish(); -// end = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); -// ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); + // end = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + // ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); } -static void RB_GammaCorrectRender() -{ +static void RB_GammaCorrectRender() { qglPushAttrib(GL_CLIENT_ALL_ATTRIB_BITS); RB_SetGL2D(); @@ -1846,17 +1716,17 @@ static void RB_GammaCorrectRender() qglEnable(GL_FRAGMENT_PROGRAM_ARB); qglBegin(GL_QUADS); - qglTexCoord2f(0.0f, 0.0f); - qglVertex2f(-1.0f, -1.0f); + qglTexCoord2f(0.0f, 0.0f); + qglVertex2f(-1.0f, -1.0f); - qglTexCoord2f(0.0f, (float)glConfig.vidHeight); - qglVertex2f(-1.0f, 1.0f); + qglTexCoord2f(0.0f, (float)glConfig.vidHeight); + qglVertex2f(-1.0f, 1.0f); - qglTexCoord2f((float)glConfig.vidWidth, (float)glConfig.vidHeight); - qglVertex2f( 1.0f, 1.0f); + qglTexCoord2f((float)glConfig.vidWidth, (float)glConfig.vidHeight); + qglVertex2f(1.0f, 1.0f); - qglTexCoord2f((float)glConfig.vidWidth, 0.0f); - qglVertex2f( 1.0f, -1.0f); + qglTexCoord2f((float)glConfig.vidWidth, 0.0f); + qglVertex2f(1.0f, -1.0f); qglEnd(); qglDisable(GL_VERTEX_PROGRAM_ARB); @@ -1868,28 +1738,26 @@ static void RB_GammaCorrectRender() qglPopAttrib(); } - /* ============= RB_SwapBuffers ============= */ -const void *RB_SwapBuffers( const void *data ) { - const swapBuffersCommand_t *cmd; +const void *RB_SwapBuffers(const void *data) { + const swapBuffersCommand_t *cmd; // finish any 2D drawing if needed - if ( tess.numIndexes ) { + if (tess.numIndexes) { RB_EndSurface(); } - if ( glConfigExt.doGammaCorrectionWithShaders ) - { + if (glConfigExt.doGammaCorrectionWithShaders) { RB_GammaCorrectRender(); } // texture swapping test - if ( r_showImages->integer ) { + if (r_showImages->integer) { RB_ShowImages(); } @@ -1897,51 +1765,48 @@ const void *RB_SwapBuffers( const void *data ) { // we measure overdraw by reading back the stencil buffer and // counting up the number of increments that have happened - if ( r_measureOverdraw->integer ) { + if (r_measureOverdraw->integer) { int i; long sum = 0; unsigned char *stencilReadback; - stencilReadback = (unsigned char *)Hunk_AllocateTempMemory( glConfig.vidWidth * glConfig.vidHeight ); - qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback ); + stencilReadback = (unsigned char *)Hunk_AllocateTempMemory(glConfig.vidWidth * glConfig.vidHeight); + qglReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback); - for ( i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++ ) { + for (i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++) { sum += stencilReadback[i]; } backEnd.pc.c_overDraw += sum; - Hunk_FreeTempMemory( stencilReadback ); + Hunk_FreeTempMemory(stencilReadback); } - if ( !glState.finishCalled ) { - qglFinish(); + if (!glState.finishCalled) { + qglFinish(); } - GLimp_LogComment( "***************** RB_SwapBuffers *****************\n\n\n" ); + GLimp_LogComment("***************** RB_SwapBuffers *****************\n\n\n"); - ri.WIN_Present(&window); + ri.WIN_Present(&window); backEnd.projection2D = qfalse; return (const void *)(cmd + 1); } -const void *RB_WorldEffects( const void *data ) -{ - const drawBufferCommand_t *cmd; +const void *RB_WorldEffects(const void *data) { + const drawBufferCommand_t *cmd; cmd = (const drawBufferCommand_t *)data; // Always flush the tess buffer - if ( tess.shader && tess.numIndexes ) - { + if (tess.shader && tess.numIndexes) { RB_EndSurface(); } RB_RenderWorldEffects(); - if(tess.shader) - { - RB_BeginSurface( tess.shader, tess.fogNum ); + if (tess.shader) { + RB_BeginSurface(tess.shader, tess.fogNum); } return (const void *)(cmd + 1); @@ -1952,42 +1817,42 @@ const void *RB_WorldEffects( const void *data ) RB_ExecuteRenderCommands ==================== */ -extern const void *R_DrawWireframeAutomap(const void *data); //tr_world.cpp -void RB_ExecuteRenderCommands( const void *data ) { - int t1, t2; +extern const void *R_DrawWireframeAutomap(const void *data); // tr_world.cpp +void RB_ExecuteRenderCommands(const void *data) { + int t1, t2; - t1 = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + t1 = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); - while ( 1 ) { + while (1) { data = PADP(data, sizeof(void *)); - switch ( *(const int *)data ) { + switch (*(const int *)data) { case RC_SET_COLOR: - data = RB_SetColor( data ); + data = RB_SetColor(data); break; case RC_STRETCH_PIC: - data = RB_StretchPic( data ); + data = RB_StretchPic(data); break; case RC_ROTATE_PIC: - data = RB_RotatePic( data ); + data = RB_RotatePic(data); break; case RC_ROTATE_PIC2: - data = RB_RotatePic2( data ); + data = RB_RotatePic2(data); break; case RC_DRAW_SURFS: - data = RB_DrawSurfs( data ); + data = RB_DrawSurfs(data); break; case RC_DRAW_BUFFER: - data = RB_DrawBuffer( data ); + data = RB_DrawBuffer(data); break; case RC_SWAP_BUFFERS: - data = RB_SwapBuffers( data ); + data = RB_SwapBuffers(data); break; case RC_VIDEOFRAME: - data = RB_TakeVideoFrameCmd( data ); + data = RB_TakeVideoFrameCmd(data); break; case RC_WORLD_EFFECTS: - data = RB_WorldEffects( data ); + data = RB_WorldEffects(data); break; case RC_AUTO_MAP: data = R_DrawWireframeAutomap(data); @@ -1995,71 +1860,64 @@ void RB_ExecuteRenderCommands( const void *data ) { case RC_END_OF_LIST: default: // stop rendering - t2 = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + t2 = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); backEnd.pc.msec = t2 - t1; return; } } - } // What Pixel Shader type is currently active (regcoms or fragment programs). GLuint g_uiCurrentPixelShaderType = 0x0; // Begin using a Pixel Shader. -void BeginPixelShader( GLuint uiType, GLuint uiID ) -{ - switch ( uiType ) - { - // Using Register Combiners, so call the Display List that stores it. - case GL_REGISTER_COMBINERS_NV: - { - // Just in case... - if ( !qglCombinerParameterfvNV ) - return; +void BeginPixelShader(GLuint uiType, GLuint uiID) { + switch (uiType) { + // Using Register Combiners, so call the Display List that stores it. + case GL_REGISTER_COMBINERS_NV: { + // Just in case... + if (!qglCombinerParameterfvNV) + return; - // Call the list with the regcom in it. - qglEnable( GL_REGISTER_COMBINERS_NV ); - qglCallList( uiID ); + // Call the list with the regcom in it. + qglEnable(GL_REGISTER_COMBINERS_NV); + qglCallList(uiID); - g_uiCurrentPixelShaderType = GL_REGISTER_COMBINERS_NV; - } + g_uiCurrentPixelShaderType = GL_REGISTER_COMBINERS_NV; + } return; - // Using Fragment Programs, so call the program. - case GL_FRAGMENT_PROGRAM_ARB: - { - // Just in case... - if ( !qglGenProgramsARB ) - return; + // Using Fragment Programs, so call the program. + case GL_FRAGMENT_PROGRAM_ARB: { + // Just in case... + if (!qglGenProgramsARB) + return; - qglEnable( GL_FRAGMENT_PROGRAM_ARB ); - qglBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, uiID ); + qglEnable(GL_FRAGMENT_PROGRAM_ARB); + qglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, uiID); - g_uiCurrentPixelShaderType = GL_FRAGMENT_PROGRAM_ARB; - } + g_uiCurrentPixelShaderType = GL_FRAGMENT_PROGRAM_ARB; + } return; } } // Stop using a Pixel Shader and return states to normal. -void EndPixelShader() -{ - if ( g_uiCurrentPixelShaderType == 0x0 ) +void EndPixelShader() { + if (g_uiCurrentPixelShaderType == 0x0) return; - qglDisable( g_uiCurrentPixelShaderType ); + qglDisable(g_uiCurrentPixelShaderType); } // Hack variable for deciding which kind of texture rectangle thing to do (for some // reason it acts different on radeon! It's against the spec!). extern bool g_bTextureRectangleHack; -static inline void RB_BlurGlowTexture() -{ - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); - qglDisable( GL_DEPTH_TEST ); +static inline void RB_BlurGlowTexture() { + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); + qglDisable(GL_DEPTH_TEST); // Go into orthographic 2d mode. qglMatrixMode(GL_PROJECTION); @@ -2079,26 +1937,23 @@ static inline void RB_BlurGlowTexture() // NOTE: The 0.25 is because we're blending 4 textures (so = 1.0) and we want a relatively normalized pixel // intensity distribution, but this won't happen anyways if intensity is higher than 1.0. float fBlurDistribution = r_DynamicGlowIntensity->value * 0.25f; - float fBlurWeight[4] = { fBlurDistribution, fBlurDistribution, fBlurDistribution, 1.0f }; + float fBlurWeight[4] = {fBlurDistribution, fBlurDistribution, fBlurDistribution, 1.0f}; // Enable and set the Vertex Program. - qglEnable( GL_VERTEX_PROGRAM_ARB ); - qglBindProgramARB( GL_VERTEX_PROGRAM_ARB, tr.glowVShader ); + qglEnable(GL_VERTEX_PROGRAM_ARB); + qglBindProgramARB(GL_VERTEX_PROGRAM_ARB, tr.glowVShader); // Apply Pixel Shaders. - if ( qglCombinerParameterfvNV ) - { - BeginPixelShader( GL_REGISTER_COMBINERS_NV, tr.glowPShader ); + if (qglCombinerParameterfvNV) { + BeginPixelShader(GL_REGISTER_COMBINERS_NV, tr.glowPShader); // Pass the blur weight to the regcom. - qglCombinerParameterfvNV( GL_CONSTANT_COLOR0_NV, (float*)&fBlurWeight ); - } - else if ( qglProgramEnvParameter4fARB ) - { - BeginPixelShader( GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader ); + qglCombinerParameterfvNV(GL_CONSTANT_COLOR0_NV, (float *)&fBlurWeight); + } else if (qglProgramEnvParameter4fARB) { + BeginPixelShader(GL_FRAGMENT_PROGRAM_ARB, tr.glowPShader); // Pass the blur weight to the Fragment Program. - qglProgramEnvParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 0, fBlurWeight[0], fBlurWeight[1], fBlurWeight[2], fBlurWeight[3] ); + qglProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, fBlurWeight[0], fBlurWeight[1], fBlurWeight[2], fBlurWeight[3]); } ///////////////////////////////////////////////////////// @@ -2110,89 +1965,86 @@ static inline void RB_BlurGlowTexture() GLuint uiTex = tr.screenGlow; - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); ///////////////////////////////////////////////////////// // Draw the blur passes (each pass blurs it more, increasing the blur radius ). ///////////////////////////////////////////////////////// - //int iTexWidth = backEnd.viewParms.viewportWidth, iTexHeight = backEnd.viewParms.viewportHeight; + // int iTexWidth = backEnd.viewParms.viewportWidth, iTexHeight = backEnd.viewParms.viewportHeight; int iTexWidth = glConfig.vidWidth, iTexHeight = glConfig.vidHeight; - for ( int iNumBlurPasses = 0; iNumBlurPasses < r_DynamicGlowPasses->integer; iNumBlurPasses++ ) - { + for (int iNumBlurPasses = 0; iNumBlurPasses < r_DynamicGlowPasses->integer; iNumBlurPasses++) { // Load the Texel Offsets into the Vertex Program. - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 0, -fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 1, -fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 2, fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f ); - qglProgramEnvParameter4fARB( GL_VERTEX_PROGRAM_ARB, 3, fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f ); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 0, -fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 1, -fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 2, fTexelWidthOffset, -fTexelWidthOffset, 0.0f, 0.0f); + qglProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 3, fTexelWidthOffset, fTexelWidthOffset, 0.0f, 0.0f); // After first pass put the tex coords to the viewport size. - if ( iNumBlurPasses == 1 ) - { + if (iNumBlurPasses == 1) { // OK, very weird, but dependent on which texture rectangle extension we're using, the // texture either needs to be always texure correct or view correct... - if ( !g_bTextureRectangleHack ) - { + if (!g_bTextureRectangleHack) { iTexWidth = backEnd.viewParms.viewportWidth; iTexHeight = backEnd.viewParms.viewportHeight; } uiTex = tr.blurImage; - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); // Copy the current image over. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, uiTex ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, uiTex); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); } // Draw the fullscreen quad. - qglBegin( GL_QUADS ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, iTexHeight ); - qglVertex2f( 0, 0 ); + qglBegin(GL_QUADS); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, iTexHeight); + qglVertex2f(0, 0); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 0 ); - qglVertex2f( 0, backEnd.viewParms.viewportHeight ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, 0, 0); + qglVertex2f(0, backEnd.viewParms.viewportHeight); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, iTexWidth, 0 ); - qglVertex2f( backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, iTexWidth, 0); + qglVertex2f(backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, iTexWidth, iTexHeight ); - qglVertex2f( backEnd.viewParms.viewportWidth, 0 ); + qglMultiTexCoord2fARB(GL_TEXTURE0_ARB, iTexWidth, iTexHeight); + qglVertex2f(backEnd.viewParms.viewportWidth, 0); qglEnd(); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglCopyTexSubImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglCopyTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, 0, 0, backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight); // Increase the texel offsets. // NOTE: This is possibly the most important input to the effect. Even by using an exponential function I've been able to @@ -2204,20 +2056,20 @@ static inline void RB_BlurGlowTexture() } // Disable multi-texturing. - qglActiveTextureARB( GL_TEXTURE3_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE3_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB( GL_TEXTURE2_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE2_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglActiveTextureARB(GL_TEXTURE1_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); + qglActiveTextureARB(GL_TEXTURE0_ARB); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); - qglDisable( GL_VERTEX_PROGRAM_ARB ); + qglDisable(GL_VERTEX_PROGRAM_ARB); EndPixelShader(); qglMatrixMode(GL_PROJECTION); @@ -2225,18 +2077,17 @@ static inline void RB_BlurGlowTexture() qglMatrixMode(GL_MODELVIEW); qglPopMatrix(); - qglDisable( GL_BLEND ); - qglEnable( GL_DEPTH_TEST ); + qglDisable(GL_BLEND); + qglEnable(GL_DEPTH_TEST); - glState.currenttmu = 0; //this matches the last one we activated + glState.currenttmu = 0; // this matches the last one we activated } // Draw the glow blur over the screen additively. -static inline void RB_DrawGlowOverlay() -{ - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); - qglDisable( GL_DEPTH_TEST ); +static inline void RB_DrawGlowOverlay() { + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); + qglDisable(GL_DEPTH_TEST); // Go into orthographic 2d mode. qglMatrixMode(GL_PROJECTION); @@ -2249,120 +2100,116 @@ static inline void RB_DrawGlowOverlay() GL_State(0); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); + qglDisable(GL_TEXTURE_2D); + qglEnable(GL_TEXTURE_RECTANGLE_ARB); // For debug purposes. - if ( r_DynamicGlow->integer != 2 ) - { + if (r_DynamicGlow->integer != 2) { // Render the normal scene texture. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage); qglBegin(GL_QUADS); - qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - qglTexCoord2f( 0, glConfig.vidHeight ); - qglVertex2f( 0, 0 ); + qglColor4f(1.0f, 1.0f, 1.0f, 1.0f); + qglTexCoord2f(0, glConfig.vidHeight); + qglVertex2f(0, 0); - qglTexCoord2f( 0, 0 ); - qglVertex2f( 0, glConfig.vidHeight ); + qglTexCoord2f(0, 0); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f( glConfig.vidWidth, 0 ); - qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); + qglTexCoord2f(glConfig.vidWidth, 0); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f( glConfig.vidWidth, glConfig.vidHeight ); - qglVertex2f( glConfig.vidWidth, 0 ); + qglTexCoord2f(glConfig.vidWidth, glConfig.vidHeight); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); } // One and Inverse Src Color give a very soft addition, while one one is a bit stronger. With one one we can // use additive blending through multitexture though. - if ( r_DynamicGlowSoft->integer ) - { - qglBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_COLOR ); - } - else - { - qglBlendFunc( GL_ONE, GL_ONE ); + if (r_DynamicGlowSoft->integer) { + qglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); + } else { + qglBlendFunc(GL_ONE, GL_ONE); } - qglEnable( GL_BLEND ); + qglEnable(GL_BLEND); // Now additively render the glow texture. - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); qglBegin(GL_QUADS); - qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - qglTexCoord2f( 0, r_DynamicGlowHeight->integer ); - qglVertex2f( 0, 0 ); + qglColor4f(1.0f, 1.0f, 1.0f, 1.0f); + qglTexCoord2f(0, r_DynamicGlowHeight->integer); + qglVertex2f(0, 0); - qglTexCoord2f( 0, 0 ); - qglVertex2f( 0, glConfig.vidHeight ); + qglTexCoord2f(0, 0); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f( r_DynamicGlowWidth->integer, 0 ); - qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); + qglTexCoord2f(r_DynamicGlowWidth->integer, 0); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f( r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer ); - qglVertex2f( glConfig.vidWidth, 0 ); + qglTexCoord2f(r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); - qglBlendFunc( GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR ); - qglDisable( GL_BLEND ); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + qglEnable(GL_TEXTURE_2D); + qglBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR); + qglDisable(GL_BLEND); // NOTE: Multi-texture wasn't that much faster (we're obviously not bottlenecked by transform pipeline), // and besides, soft glow looks better anyways. -/* else - { - int iTexWidth = glConfig.vidWidth, iTexHeight = glConfig.vidHeight; - if ( GL_TEXTURE_RECTANGLE_ARB == GL_TEXTURE_RECTANGLE_NV ) + /* else { - iTexWidth = r_DynamicGlowWidth->integer; - iTexHeight = r_DynamicGlowHeight->integer; - } + int iTexWidth = glConfig.vidWidth, iTexHeight = glConfig.vidHeight; + if ( GL_TEXTURE_RECTANGLE_ARB == GL_TEXTURE_RECTANGLE_NV ) + { + iTexWidth = r_DynamicGlowWidth->integer; + iTexHeight = r_DynamicGlowHeight->integer; + } + + qglActiveTextureARB( GL_TEXTURE1_ARB ); + qglDisable( GL_TEXTURE_2D ); + qglEnable( GL_TEXTURE_RECTANGLE_ARB ); + qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow ); + qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD ); + + qglActiveTextureARB(GL_TEXTURE0_ARB ); + qglDisable( GL_TEXTURE_2D ); + qglEnable( GL_TEXTURE_RECTANGLE_ARB ); + qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); + qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.screenGlow ); - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD ); + qglBegin(GL_QUADS); + qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, iTexHeight ); + qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, glConfig.vidHeight ); + qglVertex2f( 0, 0 ); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglDisable( GL_TEXTURE_2D ); - qglEnable( GL_TEXTURE_RECTANGLE_ARB ); - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.sceneImage ); - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); + qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, 0 ); + qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 0 ); + qglVertex2f( 0, glConfig.vidHeight ); - qglBegin(GL_QUADS); - qglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, iTexHeight ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, glConfig.vidHeight ); - qglVertex2f( 0, 0 ); - - qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, 0 ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 0 ); - qglVertex2f( 0, glConfig.vidHeight ); - - qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, iTexWidth, 0 ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, glConfig.vidWidth, 0 ); - qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); - - qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, iTexWidth, iTexHeight ); - qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, glConfig.vidWidth, glConfig.vidHeight ); - qglVertex2f( glConfig.vidWidth, 0 ); - qglEnd(); + qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, iTexWidth, 0 ); + qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, glConfig.vidWidth, 0 ); + qglVertex2f( glConfig.vidWidth, glConfig.vidHeight ); - qglActiveTextureARB( GL_TEXTURE1_ARB ); - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglMultiTexCoord2fARB( GL_TEXTURE1_ARB, iTexWidth, iTexHeight ); + qglMultiTexCoord2fARB( GL_TEXTURE0_ARB, glConfig.vidWidth, glConfig.vidHeight ); + qglVertex2f( glConfig.vidWidth, 0 ); + qglEnd(); - qglActiveTextureARB(GL_TEXTURE0_ARB ); - qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - qglEnable( GL_TEXTURE_2D ); - }*/ + qglActiveTextureARB( GL_TEXTURE1_ARB ); + qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + + qglActiveTextureARB(GL_TEXTURE0_ARB ); + qglTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + qglDisable( GL_TEXTURE_RECTANGLE_ARB ); + qglEnable( GL_TEXTURE_2D ); + }*/ qglMatrixMode(GL_PROJECTION); qglPopMatrix(); qglMatrixMode(GL_MODELVIEW); qglPopMatrix(); - qglEnable( GL_DEPTH_TEST ); + qglEnable(GL_DEPTH_TEST); } diff --git a/codemp/rd-vanilla/tr_bsp.cpp b/codemp/rd-vanilla/tr_bsp.cpp index ecc3df602f..e327ab88ea 100644 --- a/codemp/rd-vanilla/tr_bsp.cpp +++ b/codemp/rd-vanilla/tr_bsp.cpp @@ -34,31 +34,29 @@ void RE_LoadWorldMap( const char *name ); */ -static world_t s_worldData; -static byte *fileBase; +static world_t s_worldData; +static byte *fileBase; -int c_subdivisions; -int c_gridVerts; +int c_subdivisions; +int c_gridVerts; //=============================================================================== -static void HSVtoRGB( float h, float s, float v, float rgb[3] ) -{ +static void HSVtoRGB(float h, float s, float v, float rgb[3]) { int i; float f; float p, q, t; h *= 5; - i = floor( h ); + i = floor(h); f = h - i; - p = v * ( 1 - s ); - q = v * ( 1 - s * f ); - t = v * ( 1 - s * ( 1 - f ) ); + p = v * (1 - s); + q = v * (1 - s * f); + t = v * (1 - s * (1 - f)); - switch ( i ) - { + switch (i) { case 0: rgb[0] = v; rgb[1] = t; @@ -98,11 +96,11 @@ R_ColorShiftLightingBytes =============== */ -void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { +void R_ColorShiftLightingBytes(byte in[4], byte out[4]) { int shift, r, g, b; // shift the color data based on overbright range - shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + shift = Q_max(0, r_mapOverBrightBits->integer - tr.overbrightBits); // shift the data based on overbright range r = in[0] << shift; @@ -110,8 +108,8 @@ void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { b = in[2] << shift; // normalize by color instead of saturating to white - if ( (r|g|b) > 255 ) { - int max; + if ((r | g | b) > 255) { + int max; max = r > g ? r : g; max = max > b ? max : b; @@ -132,11 +130,11 @@ R_ColorShiftLightingBytes =============== */ -void R_ColorShiftLightingBytes( byte in[3] ) { +void R_ColorShiftLightingBytes(byte in[3]) { int shift, r, g, b; // shift the color data based on overbright range - shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + shift = Q_max(0, r_mapOverBrightBits->integer - tr.overbrightBits); // shift the data based on overbright range r = in[0] << shift; @@ -144,8 +142,8 @@ void R_ColorShiftLightingBytes( byte in[3] ) { b = in[2] << shift; // normalize by color instead of saturating to white - if ( (r|g|b) > 255 ) { - int max; + if ((r | g | b) > 255) { + int max; max = r > g ? r : g; max = max > b ? max : b; @@ -165,22 +163,21 @@ R_LoadLightmaps =============== */ -#define LIGHTMAP_SIZE 128 -static void R_LoadLightmaps( lump_t *l, const char *psMapName, world_t &worldData ) { - byte *buf, *buf_p; - int len; - byte image[LIGHTMAP_SIZE*LIGHTMAP_SIZE*4]; - int i, j; +#define LIGHTMAP_SIZE 128 +static void R_LoadLightmaps(lump_t *l, const char *psMapName, world_t &worldData) { + byte *buf, *buf_p; + int len; + byte image[LIGHTMAP_SIZE * LIGHTMAP_SIZE * 4]; + int i, j; float maxIntensity = 0; double sumIntensity = 0; - if (&worldData == &s_worldData) - { + if (&worldData == &s_worldData) { tr.numLightmaps = 0; } - len = l->filelen; - if ( !len ) { + len = l->filelen; + if (!len) { return; } buf = fileBase + l->fileofs; @@ -190,69 +187,66 @@ static void R_LoadLightmaps( lump_t *l, const char *psMapName, world_t &worldDat // create all the lightmaps tr.numLightmaps = len / (LIGHTMAP_SIZE * LIGHTMAP_SIZE * 3); - if ( tr.numLightmaps == 1 ) { - //FIXME: HACK: maps with only one lightmap turn up fullbright for some reason. - //this avoids this, but isn't the correct solution. + if (tr.numLightmaps == 1) { + // FIXME: HACK: maps with only one lightmap turn up fullbright for some reason. + // this avoids this, but isn't the correct solution. tr.numLightmaps++; } // if we are in r_vertexLight mode, we don't need the lightmaps at all - if ( r_vertexLight->integer ) { + if (r_vertexLight->integer) { return; } char sMapName[MAX_QPATH]; COM_StripExtension(psMapName, sMapName, sizeof(sMapName)); - for ( i = 0 ; i < tr.numLightmaps ; i++ ) { + for (i = 0; i < tr.numLightmaps; i++) { // expand the 24 bit on-disk to 32 bit - buf_p = buf + i * LIGHTMAP_SIZE*LIGHTMAP_SIZE * 3; - - if ( r_lightmap->integer == 2 ) - { // color code by intensity as development tool (FIXME: check range) - for ( j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ ) - { - float r = buf_p[j*3+0]; - float g = buf_p[j*3+1]; - float b = buf_p[j*3+2]; + buf_p = buf + i * LIGHTMAP_SIZE * LIGHTMAP_SIZE * 3; + + if (r_lightmap->integer == 2) { // color code by intensity as development tool (FIXME: check range) + for (j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++) { + float r = buf_p[j * 3 + 0]; + float g = buf_p[j * 3 + 1]; + float b = buf_p[j * 3 + 2]; float intensity; float out[3] = {0.0f, 0.0f, 0.0f}; intensity = 0.33f * r + 0.685f * g + 0.063f * b; - if ( intensity > 255 ) + if (intensity > 255) intensity = 1.0f; else intensity /= 255.0f; - if ( intensity > maxIntensity ) + if (intensity > maxIntensity) maxIntensity = intensity; - HSVtoRGB( intensity, 1.00, 0.50, out ); + HSVtoRGB(intensity, 1.00, 0.50, out); - image[j*4+0] = out[0] * 255; - image[j*4+1] = out[1] * 255; - image[j*4+2] = out[2] * 255; - image[j*4+3] = 255; + image[j * 4 + 0] = out[0] * 255; + image[j * 4 + 1] = out[1] * 255; + image[j * 4 + 2] = out[2] * 255; + image[j * 4 + 3] = 255; sumIntensity += intensity; } } else { - for ( j = 0 ; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++ ) { - R_ColorShiftLightingBytes( &buf_p[j*3], &image[j*4] ); - image[j*4+3] = 255; + for (j = 0; j < LIGHTMAP_SIZE * LIGHTMAP_SIZE; j++) { + R_ColorShiftLightingBytes(&buf_p[j * 3], &image[j * 4]); + image[j * 4 + 3] = 255; } } - tr.lightmaps[i] = R_CreateImage( va("*%s/lightmap%d",sMapName,i), image, - LIGHTMAP_SIZE, LIGHTMAP_SIZE, GL_RGBA, qfalse, qfalse, (qboolean)r_ext_compressed_lightmaps->integer, GL_CLAMP ); + tr.lightmaps[i] = R_CreateImage(va("*%s/lightmap%d", sMapName, i), image, LIGHTMAP_SIZE, LIGHTMAP_SIZE, GL_RGBA, qfalse, qfalse, + (qboolean)r_ext_compressed_lightmaps->integer, GL_CLAMP); } - if ( r_lightmap->integer == 2 ) { - ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) ); + if (r_lightmap->integer == 2) { + ri.Printf(PRINT_ALL, "Brightest lightmap value: %d\n", (int)(maxIntensity * 255)); } } - /* ================= RE_SetWorldVisData @@ -261,42 +255,39 @@ This is called by the clipmodel subsystem so we can share the 1.8 megs of space in big maps... ================= */ -void RE_SetWorldVisData( const byte *vis ) { - tr.externalVisData = vis; -} - +void RE_SetWorldVisData(const byte *vis) { tr.externalVisData = vis; } /* ================= R_LoadVisibility ================= */ -static void R_LoadVisibility( lump_t *l, world_t &worldData ) { - int len; - byte *buf; +static void R_LoadVisibility(lump_t *l, world_t &worldData) { + int len; + byte *buf; - len = ( worldData.numClusters + 63 ) & ~63; - worldData.novis = (unsigned char *)Hunk_Alloc( len, h_low ); - memset( worldData.novis, 0xff, len ); + len = (worldData.numClusters + 63) & ~63; + worldData.novis = (unsigned char *)Hunk_Alloc(len, h_low); + memset(worldData.novis, 0xff, len); - len = l->filelen; - if ( !len ) { + len = l->filelen; + if (!len) { return; } buf = fileBase + l->fileofs; - worldData.numClusters = LittleLong( ((int *)buf)[0] ); - worldData.clusterBytes = LittleLong( ((int *)buf)[1] ); + worldData.numClusters = LittleLong(((int *)buf)[0]); + worldData.clusterBytes = LittleLong(((int *)buf)[1]); // CM_Load should have given us the vis data to share, so // we don't need to allocate another copy - if ( tr.externalVisData ) { + if (tr.externalVisData) { worldData.vis = tr.externalVisData; } else { - byte *dest; + byte *dest; - dest = (unsigned char *)Hunk_Alloc( len - 8, h_low ); - memcpy( dest, buf + 8, len - 8 ); + dest = (unsigned char *)Hunk_Alloc(len - 8, h_low); + memcpy(dest, buf + 8, len - 8); worldData.vis = dest; } } @@ -308,35 +299,32 @@ static void R_LoadVisibility( lump_t *l, world_t &worldData ) { ShaderForShaderNum =============== */ -static shader_t *ShaderForShaderNum( int shaderNum, const int *lightmapNum, const byte *lightmapStyles, const byte *vertexStyles, world_t &worldData ) -{ - shader_t *shader; - dshader_t *dsh; - const byte *styles; +static shader_t *ShaderForShaderNum(int shaderNum, const int *lightmapNum, const byte *lightmapStyles, const byte *vertexStyles, world_t &worldData) { + shader_t *shader; + dshader_t *dsh; + const byte *styles; styles = lightmapStyles; - LL( shaderNum ); - if ( shaderNum < 0 || shaderNum >= worldData.numShaders ) { - Com_Error( ERR_DROP, "ShaderForShaderNum: bad num %i", shaderNum ); + LL(shaderNum); + if (shaderNum < 0 || shaderNum >= worldData.numShaders) { + Com_Error(ERR_DROP, "ShaderForShaderNum: bad num %i", shaderNum); } - dsh = &worldData.shaders[ shaderNum ]; + dsh = &worldData.shaders[shaderNum]; - if (lightmapNum[0] == LIGHTMAP_BY_VERTEX) - { + if (lightmapNum[0] == LIGHTMAP_BY_VERTEX) { styles = vertexStyles; } - if ( r_vertexLight->integer ) - { + if (r_vertexLight->integer) { lightmapNum = lightmapsVertex; styles = vertexStyles; } - shader = R_FindShader( dsh->shader, lightmapNum, styles, qtrue ); + shader = R_FindShader(dsh->shader, lightmapNum, styles, qtrue); // if the shader had errors, just use default shader - if ( shader->defaultShader ) { + if (shader->defaultShader) { return tr.defaultShader; } @@ -348,164 +336,155 @@ static shader_t *ShaderForShaderNum( int shaderNum, const int *lightmapNum, cons ParseFace =============== */ -static void ParseFace( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index ) { - int i, j, k; - srfSurfaceFace_t *cv; - int numPoints, numIndexes; - int lightmapNum[MAXLIGHTMAPS]; - int sfaceSize, ofsIndexes; +static void ParseFace(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index) { + int i, j, k; + srfSurfaceFace_t *cv; + int numPoints, numIndexes; + int lightmapNum[MAXLIGHTMAPS]; + int sfaceSize, ofsIndexes; - for(i = 0; i < MAXLIGHTMAPS; i++) - { - lightmapNum[i] = LittleLong( ds->lightmapNum[i] ); + for (i = 0; i < MAXLIGHTMAPS; i++) { + lightmapNum[i] = LittleLong(ds->lightmapNum[i]); } // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader value - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - numPoints = LittleLong( ds->numVerts ); + numPoints = LittleLong(ds->numVerts); if (numPoints > MAX_FACE_POINTS) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: MAX_FACE_POINTS exceeded: %i\n", numPoints); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: MAX_FACE_POINTS exceeded: %i\n", numPoints); numPoints = MAX_FACE_POINTS; surf->shader = tr.defaultShader; } - numIndexes = LittleLong( ds->numIndexes ); + numIndexes = LittleLong(ds->numIndexes); // create the srfSurfaceFace_t - sfaceSize = sizeof( *cv ) - sizeof( cv->points ) + sizeof( cv->points[0] ) * numPoints; + sfaceSize = sizeof(*cv) - sizeof(cv->points) + sizeof(cv->points[0]) * numPoints; ofsIndexes = sfaceSize; - sfaceSize += sizeof( int ) * numIndexes; + sfaceSize += sizeof(int) * numIndexes; - cv = (srfSurfaceFace_t *)Hunk_Alloc( sfaceSize, h_low ); + cv = (srfSurfaceFace_t *)Hunk_Alloc(sfaceSize, h_low); cv->surfaceType = SF_FACE; cv->numPoints = numPoints; cv->numIndices = numIndexes; cv->ofsIndices = ofsIndexes; - verts += LittleLong( ds->firstVert ); - for ( i = 0 ; i < numPoints ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - cv->points[i][j] = LittleFloat( verts[i].xyz[j] ); + verts += LittleLong(ds->firstVert); + for (i = 0; i < numPoints; i++) { + for (j = 0; j < 3; j++) { + cv->points[i][j] = LittleFloat(verts[i].xyz[j]); } - for ( j = 0 ; j < 2 ; j++ ) { - cv->points[i][3+j] = LittleFloat( verts[i].st[j] ); - for(k=0;kpoints[i][VERTEX_LM+j+(k*2)] = LittleFloat( verts[i].lightmap[k][j] ); + for (j = 0; j < 2; j++) { + cv->points[i][3 + j] = LittleFloat(verts[i].st[j]); + for (k = 0; k < MAXLIGHTMAPS; k++) { + cv->points[i][VERTEX_LM + j + (k * 2)] = LittleFloat(verts[i].lightmap[k][j]); } } - for(k=0;kpoints[i][VERTEX_COLOR+k] ); + for (k = 0; k < MAXLIGHTMAPS; k++) { + R_ColorShiftLightingBytes(verts[i].color[k], (byte *)&cv->points[i][VERTEX_COLOR + k]); } } - indexes += LittleLong( ds->firstIndex ); - for ( i = 0 ; i < numIndexes ; i++ ) { - ((int *)((byte *)cv + cv->ofsIndices ))[i] = LittleLong( indexes[ i ] ); + indexes += LittleLong(ds->firstIndex); + for (i = 0; i < numIndexes; i++) { + ((int *)((byte *)cv + cv->ofsIndices))[i] = LittleLong(indexes[i]); } // take the plane information from the lightmap vector - for ( i = 0 ; i < 3 ; i++ ) { - cv->plane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + cv->plane.normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } - cv->plane.dist = DotProduct( cv->points[0], cv->plane.normal ); - SetPlaneSignbits( &cv->plane ); - cv->plane.type = PlaneTypeForNormal( cv->plane.normal ); + cv->plane.dist = DotProduct(cv->points[0], cv->plane.normal); + SetPlaneSignbits(&cv->plane); + cv->plane.type = PlaneTypeForNormal(cv->plane.normal); surf->data = (surfaceType_t *)cv; } - /* =============== ParseMesh =============== */ -static void ParseMesh ( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, world_t &worldData, int index ) { - srfGridMesh_t *grid; - int i, j, k; - int width, height, numPoints; - drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE]; - int lightmapNum[MAXLIGHTMAPS]; - vec3_t bounds[2]; - vec3_t tmpVec; - static surfaceType_t skipData = SF_SKIP; +static void ParseMesh(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, world_t &worldData, int index) { + srfGridMesh_t *grid; + int i, j, k; + int width, height, numPoints; + drawVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]; + int lightmapNum[MAXLIGHTMAPS]; + vec3_t bounds[2]; + vec3_t tmpVec; + static surfaceType_t skipData = SF_SKIP; - for(i=0;ilightmapNum[i] ); + for (i = 0; i < MAXLIGHTMAPS; i++) { + lightmapNum[i] = LittleLong(ds->lightmapNum[i]); } // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader value - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapNum, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } // we may have a nodraw surface, because they might still need to // be around for movement clipping - if ( worldData.shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) { + if (worldData.shaders[LittleLong(ds->shaderNum)].surfaceFlags & SURF_NODRAW) { surf->data = &skipData; return; } - width = LittleLong( ds->patchWidth ); - height = LittleLong( ds->patchHeight ); + width = LittleLong(ds->patchWidth); + height = LittleLong(ds->patchHeight); - verts += LittleLong( ds->firstVert ); + verts += LittleLong(ds->firstVert); numPoints = width * height; - for ( i = 0 ; i < numPoints ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - points[i].xyz[j] = LittleFloat( verts[i].xyz[j] ); - points[i].normal[j] = LittleFloat( verts[i].normal[j] ); + for (i = 0; i < numPoints; i++) { + for (j = 0; j < 3; j++) { + points[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + points[i].normal[j] = LittleFloat(verts[i].normal[j]); } - for ( j = 0 ; j < 2 ; j++ ) { - points[i].st[j] = LittleFloat( verts[i].st[j] ); - for(k=0;kdata = (surfaceType_t *)grid; // copy the level of detail origin, which is the center // of the group of all curves that must subdivide the same // to avoid cracking - for ( i = 0 ; i < 3 ; i++ ) { - bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] ); - bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] ); - } - VectorAdd( bounds[0], bounds[1], bounds[1] ); - VectorScale( bounds[1], 0.5f, grid->lodOrigin ); - VectorSubtract( bounds[0], grid->lodOrigin, tmpVec ); - grid->lodRadius = VectorLength( tmpVec ); + for (i = 0; i < 3; i++) { + bounds[0][i] = LittleFloat(ds->lightmapVecs[0][i]); + bounds[1][i] = LittleFloat(ds->lightmapVecs[1][i]); + } + VectorAdd(bounds[0], bounds[1], bounds[1]); + VectorScale(bounds[1], 0.5f, grid->lodOrigin); + VectorSubtract(bounds[0], grid->lodOrigin, tmpVec); + grid->lodRadius = VectorLength(tmpVec); } /* @@ -513,73 +492,69 @@ static void ParseMesh ( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, worl ParseTriSurf =============== */ -static void ParseTriSurf( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index ) { - srfTriangles_t *tri; - int i, j, k; - int numVerts, numIndexes; +static void ParseTriSurf(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index) { + srfTriangles_t *tri; + int i, j, k; + int numVerts, numIndexes; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - numVerts = LittleLong( ds->numVerts ); - numIndexes = LittleLong( ds->numIndexes ); + numVerts = LittleLong(ds->numVerts); + numIndexes = LittleLong(ds->numIndexes); - if ( numVerts >= SHADER_MAX_VERTEXES ) { - Com_Error(ERR_DROP, "ParseTriSurf: verts > MAX (%d > %d) on misc_model %s", numVerts, SHADER_MAX_VERTEXES, surf->shader->name ); + if (numVerts >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "ParseTriSurf: verts > MAX (%d > %d) on misc_model %s", numVerts, SHADER_MAX_VERTEXES, surf->shader->name); } - if ( numIndexes >= SHADER_MAX_INDEXES ) { - Com_Error(ERR_DROP, "ParseTriSurf: indices > MAX (%d > %d) on misc_model %s", numIndexes, SHADER_MAX_INDEXES, surf->shader->name ); + if (numIndexes >= SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "ParseTriSurf: indices > MAX (%d > %d) on misc_model %s", numIndexes, SHADER_MAX_INDEXES, surf->shader->name); } - tri = (srfTriangles_t *)Hunk_Alloc( sizeof( *tri ) + numVerts * sizeof( tri->verts[0] ) - + numIndexes * sizeof( tri->indexes[0] ), h_low ); + tri = (srfTriangles_t *)Hunk_Alloc(sizeof(*tri) + numVerts * sizeof(tri->verts[0]) + numIndexes * sizeof(tri->indexes[0]), h_low); tri->surfaceType = SF_TRIANGLES; tri->numVerts = numVerts; tri->numIndexes = numIndexes; tri->verts = (drawVert_t *)(tri + 1); - tri->indexes = (int *)(tri->verts + tri->numVerts ); + tri->indexes = (int *)(tri->verts + tri->numVerts); surf->data = (surfaceType_t *)tri; // copy vertexes - ClearBounds( tri->bounds[0], tri->bounds[1] ); - verts += LittleLong( ds->firstVert ); - for ( i = 0 ; i < numVerts ; i++ ) { - for ( j = 0 ; j < 3 ; j++ ) { - tri->verts[i].xyz[j] = LittleFloat( verts[i].xyz[j] ); - tri->verts[i].normal[j] = LittleFloat( verts[i].normal[j] ); + ClearBounds(tri->bounds[0], tri->bounds[1]); + verts += LittleLong(ds->firstVert); + for (i = 0; i < numVerts; i++) { + for (j = 0; j < 3; j++) { + tri->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + tri->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); } - AddPointToBounds( tri->verts[i].xyz, tri->bounds[0], tri->bounds[1] ); - for ( j = 0 ; j < 2 ; j++ ) { - tri->verts[i].st[j] = LittleFloat( verts[i].st[j] ); - for(k=0;kverts[i].lightmap[k][j] = LittleFloat( verts[i].lightmap[k][j] ); + AddPointToBounds(tri->verts[i].xyz, tri->bounds[0], tri->bounds[1]); + for (j = 0; j < 2; j++) { + tri->verts[i].st[j] = LittleFloat(verts[i].st[j]); + for (k = 0; k < MAXLIGHTMAPS; k++) { + tri->verts[i].lightmap[k][j] = LittleFloat(verts[i].lightmap[k][j]); } } - for(k=0;kverts[i].color[k] ); + for (k = 0; k < MAXLIGHTMAPS; k++) { + R_ColorShiftLightingBytes(verts[i].color[k], tri->verts[i].color[k]); } } // copy indexes - indexes += LittleLong( ds->firstIndex ); - for ( i = 0 ; i < numIndexes ; i++ ) { - tri->indexes[i] = LittleLong( indexes[i] ); - if ( tri->indexes[i] < 0 || tri->indexes[i] >= numVerts ) { - Com_Error( ERR_DROP, "Bad index in triangle surface" ); + indexes += LittleLong(ds->firstIndex); + for (i = 0; i < numIndexes; i++) { + tri->indexes[i] = LittleLong(indexes[i]); + if (tri->indexes[i] < 0 || tri->indexes[i] >= numVerts) { + Com_Error(ERR_DROP, "Bad index in triangle surface"); } } } @@ -589,37 +564,35 @@ static void ParseTriSurf( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, in ParseFlare =============== */ -static void ParseFlare( dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index ) { - srfFlare_t *flare; - int i; - int lightmaps[MAXLIGHTMAPS] = { LIGHTMAP_BY_VERTEX }; +static void ParseFlare(dsurface_t *ds, mapVert_t *verts, msurface_t *surf, int *indexes, world_t &worldData, int index) { + srfFlare_t *flare; + int i; + int lightmaps[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX}; // get fog volume - surf->fogIndex = LittleLong( ds->fogNum ) + 1; - if (index && !surf->fogIndex && tr.world->globalFog != -1) - { + surf->fogIndex = LittleLong(ds->fogNum) + 1; + if (index && !surf->fogIndex && tr.world->globalFog != -1) { surf->fogIndex = worldData.globalFog; } // get shader - surf->shader = ShaderForShaderNum( ds->shaderNum, lightmaps, ds->lightmapStyles, ds->vertexStyles, worldData ); - if ( r_singleShader->integer && !surf->shader->sky ) { + surf->shader = ShaderForShaderNum(ds->shaderNum, lightmaps, ds->lightmapStyles, ds->vertexStyles, worldData); + if (r_singleShader->integer && !surf->shader->sky) { surf->shader = tr.defaultShader; } - flare = (struct srfFlare_s *)Hunk_Alloc( sizeof( *flare ), h_low ); + flare = (struct srfFlare_s *)Hunk_Alloc(sizeof(*flare), h_low); flare->surfaceType = SF_FLARE; surf->data = (surfaceType_t *)flare; - for ( i = 0 ; i < 3 ; i++ ) { - flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] ); - flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] ); - flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + for (i = 0; i < 3; i++) { + flare->origin[i] = LittleFloat(ds->lightmapOrigin[i]); + flare->color[i] = LittleFloat(ds->lightmapVecs[0][i]); + flare->normal[i] = LittleFloat(ds->lightmapVecs[2][i]); } } - /* ================= R_MergedWidthPoints @@ -630,11 +603,14 @@ returns true if there are grid points merged on a width edge int R_MergedWidthPoints(srfGridMesh_t *grid, int offset) { int i, j; - for (i = 1; i < grid->width-1; i++) { - for (j = i + 1; j < grid->width-1; j++) { - if ( fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) continue; - if ( fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) continue; - if ( fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) continue; + for (i = 1; i < grid->width - 1; i++) { + for (j = i + 1; j < grid->width - 1; j++) { + if (fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) + continue; + if (fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) + continue; + if (fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) + continue; return qtrue; } } @@ -651,11 +627,14 @@ returns true if there are grid points merged on a height edge int R_MergedHeightPoints(srfGridMesh_t *grid, int offset) { int i, j; - for (i = 1; i < grid->height-1; i++) { - for (j = i + 1; j < grid->height-1; j++) { - if ( fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) continue; - if ( fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) continue; - if ( fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) continue; + for (i = 1; i < grid->height - 1; i++) { + for (j = i + 1; j < grid->height - 1; j++) { + if (fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) + continue; + if (fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) + continue; + if (fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) + continue; return qtrue; } } @@ -671,41 +650,56 @@ NOTE: never sync LoD through grid edges with merged points! FIXME: write generalized version that also avoids cracks between a patch and one that meets half way? ================= */ -void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1, world_t &worldData ) { +void R_FixSharedVertexLodError_r(int start, srfGridMesh_t *grid1, world_t &worldData) { int j, k, l, m, n, offset1, offset2, touch; srfGridMesh_t *grid2; - for ( j = start; j < worldData.numsurfaces; j++ ) { + for (j = start; j < worldData.numsurfaces; j++) { // - grid2 = (srfGridMesh_t *) worldData.surfaces[j].data; + grid2 = (srfGridMesh_t *)worldData.surfaces[j].data; // if this surface is not a grid - if ( grid2->surfaceType != SF_GRID ) continue; + if (grid2->surfaceType != SF_GRID) + continue; // if the LOD errors are already fixed for this patch - if ( grid2->lodFixed == 2 ) continue; + if (grid2->lodFixed == 2) + continue; // grids in the same LOD group should have the exact same lod radius - if ( grid1->lodRadius != grid2->lodRadius ) continue; + if (grid1->lodRadius != grid2->lodRadius) + continue; // grids in the same LOD group should have the exact same lod origin - if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; - if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; - if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + if (grid1->lodOrigin[0] != grid2->lodOrigin[0]) + continue; + if (grid1->lodOrigin[1] != grid2->lodOrigin[1]) + continue; + if (grid1->lodOrigin[2] != grid2->lodOrigin[2]) + continue; // touch = qfalse; for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; - if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = 1; k < grid1->width-1; k++) { + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; + if (R_MergedWidthPoints(grid1, offset1)) + continue; + for (k = 1; k < grid1->width - 1; k++) { for (m = 0; m < 2; m++) { - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - if (R_MergedWidthPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->width-1; l++) { - // - if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->width - 1; l++) { + // + if (fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->widthLodError[l] = grid1->widthLodError[k]; touch = qtrue; @@ -713,14 +707,20 @@ void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1, world_t &worl } for (m = 0; m < 2; m++) { - if (m) offset2 = grid2->width-1; - else offset2 = 0; - if (R_MergedHeightPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->height-1; l++) { - // - if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->height - 1; l++) { + // + if (fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->heightLodError[l] = grid1->widthLodError[k]; touch = qtrue; @@ -730,20 +730,29 @@ void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1, world_t &worl } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; - if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = 1; k < grid1->height-1; k++) { + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; + if (R_MergedHeightPoints(grid1, offset1)) + continue; + for (k = 1; k < grid1->height - 1; k++) { for (m = 0; m < 2; m++) { - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - if (R_MergedWidthPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->width-1; l++) { - // - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->width - 1; l++) { + // + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->widthLodError[l] = grid1->heightLodError[k]; touch = qtrue; @@ -751,14 +760,20 @@ void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1, world_t &worl } for (m = 0; m < 2; m++) { - if (m) offset2 = grid2->width-1; - else offset2 = 0; - if (R_MergedHeightPoints(grid2, offset2)) continue; - for ( l = 1; l < grid2->height-1; l++) { - // - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; - if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) + continue; + for (l = 1; l < grid2->height - 1; l++) { + // + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) + continue; + if (fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) + continue; // ok the points are equal and should have the same lod error grid2->heightLodError[l] = grid1->heightLodError[k]; touch = qtrue; @@ -768,9 +783,9 @@ void R_FixSharedVertexLodError_r( int start, srfGridMesh_t *grid1, world_t &worl } if (touch) { grid2->lodFixed = 2; - R_FixSharedVertexLodError_r ( start, grid2, worldData ); - //NOTE: this would be correct but makes things really slow - //grid2->lodFixed = 1; + R_FixSharedVertexLodError_r(start, grid2, worldData); + // NOTE: this would be correct but makes things really slow + // grid2->lodFixed = 1; } } } @@ -783,90 +798,92 @@ This function assumes that all patches in one group are nicely stitched together If this is not the case this function will still do its job but won't fix the highest LoD cracks. ================= */ -void R_FixSharedVertexLodError( world_t &worldData ) { +void R_FixSharedVertexLodError(world_t &worldData) { int i; srfGridMesh_t *grid1; - for ( i = 0; i < worldData.numsurfaces; i++ ) { + for (i = 0; i < worldData.numsurfaces; i++) { // - grid1 = (srfGridMesh_t *) worldData.surfaces[i].data; + grid1 = (srfGridMesh_t *)worldData.surfaces[i].data; // if this surface is not a grid - if ( grid1->surfaceType != SF_GRID ) + if (grid1->surfaceType != SF_GRID) continue; // - if ( grid1->lodFixed ) + if (grid1->lodFixed) continue; // grid1->lodFixed = 2; // recursively fix other patches in the same LOD group - R_FixSharedVertexLodError_r( i + 1, grid1, worldData); + R_FixSharedVertexLodError_r(i + 1, grid1, worldData); } } - /* =============== R_StitchPatches =============== */ -int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { +int R_StitchPatches(int grid1num, int grid2num, world_t &worldData) { int k, l, m, n, offset1, offset2, row, column; srfGridMesh_t *grid1, *grid2; float *v1, *v2; - grid1 = (srfGridMesh_t *) worldData.surfaces[grid1num].data; - grid2 = (srfGridMesh_t *) worldData.surfaces[grid2num].data; + grid1 = (srfGridMesh_t *)worldData.surfaces[grid1num].data; + grid2 = (srfGridMesh_t *)worldData.surfaces[grid2num].data; for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = 0; k < grid1->width-2; k += 2) { + for (k = 0; k < grid1->width - 2; k += 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - //if (R_MergedWidthPoints(grid2, offset2)) + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + // if (R_MergedWidthPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->width-1; l++) { - // + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k + 2 + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -874,45 +891,46 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - //if (R_MergedHeightPoints(grid2, offset2)) + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + // if (R_MergedHeightPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->height-1; l++) { + for (l = 0; l < grid2->height - 1; l++) { // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k + 2 + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -920,54 +938,57 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = 0; k < grid1->height-2; k += 2) { + for (k = 0; k < grid1->height - 2; k += 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - //if (R_MergedWidthPoints(grid2, offset2)) + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + // if (R_MergedWidthPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->width-1; l++) { - // + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -975,45 +996,46 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - //if (R_MergedHeightPoints(grid2, offset2)) + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + // if (R_MergedHeightPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->height-1; l++) { - // + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1021,55 +1043,58 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = (grid1->height-1) * grid1->width; - else offset1 = 0; + if (n) + offset1 = (grid1->height - 1) * grid1->width; + else + offset1 = 0; if (R_MergedWidthPoints(grid1, offset1)) continue; - for (k = grid1->width-1; k > 1; k -= 2) { + for (k = grid1->width - 1; k > 1; k -= 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - //if (R_MergedWidthPoints(grid2, offset2)) + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + // if (R_MergedWidthPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->width-1; l++) { - // + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k - 2 + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1077,47 +1102,48 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - //if (R_MergedHeightPoints(grid2, offset2)) + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + // if (R_MergedHeightPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->height-1; l++) { - // + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[k - 2 + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k + 1]); if (!grid2) break; grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1125,54 +1151,57 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { } for (n = 0; n < 2; n++) { // - if (n) offset1 = grid1->width-1; - else offset1 = 0; + if (n) + offset1 = grid1->width - 1; + else + offset1 = 0; if (R_MergedHeightPoints(grid1, offset1)) continue; - for (k = grid1->height-1; k > 1; k -= 2) { + for (k = grid1->height - 1; k > 1; k -= 2) { for (m = 0; m < 2; m++) { - if ( grid2->width >= MAX_GRID_SIZE ) + if (grid2->width >= MAX_GRID_SIZE) break; - if (m) offset2 = (grid2->height-1) * grid2->width; - else offset2 = 0; - //if (R_MergedWidthPoints(grid2, offset2)) + if (m) + offset2 = (grid2->height - 1) * grid2->width; + else + offset2 = 0; + // if (R_MergedWidthPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->width-1; l++) { - // + for (l = 0; l < grid2->width - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; v2 = grid2->verts[l + 1 + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[l + offset2].xyz; v2 = grid2->verts[(l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert column into grid2 right after after column l - if (m) row = grid2->height-1; - else row = 0; - grid2 = R_GridInsertColumn( grid2, l+1, row, - grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + row = grid2->height - 1; + else + row = 0; + grid2 = R_GridInsertColumn(grid2, l + 1, row, grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1180,45 +1209,46 @@ int R_StitchPatches( int grid1num, int grid2num, world_t &worldData ) { if (grid2->height >= MAX_GRID_SIZE) break; - if (m) offset2 = grid2->width-1; - else offset2 = 0; - //if (R_MergedHeightPoints(grid2, offset2)) + if (m) + offset2 = grid2->width - 1; + else + offset2 = 0; + // if (R_MergedHeightPoints(grid2, offset2)) // continue; - for ( l = 0; l < grid2->height-1; l++) { - // + for (l = 0; l < grid2->height - 1; l++) { + // v1 = grid1->verts[grid1->width * k + offset1].xyz; v2 = grid2->verts[grid2->width * l + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) > .1) + if (fabs(v1[0] - v2[0]) > .1) continue; - if ( fabs(v1[1] - v2[1]) > .1) + if (fabs(v1[1] - v2[1]) > .1) continue; - if ( fabs(v1[2] - v2[2]) > .1) + if (fabs(v1[2] - v2[2]) > .1) continue; // v1 = grid2->verts[grid2->width * l + offset2].xyz; v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; - if ( fabs(v1[0] - v2[0]) < .01 && - fabs(v1[1] - v2[1]) < .01 && - fabs(v1[2] - v2[2]) < .01) + if (fabs(v1[0] - v2[0]) < .01 && fabs(v1[1] - v2[1]) < .01 && fabs(v1[2] - v2[2]) < .01) continue; // - //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); // insert row into grid2 right after after row l - if (m) column = grid2->width-1; - else column = 0; - grid2 = R_GridInsertRow( grid2, l+1, column, - grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + if (m) + column = grid2->width - 1; + else + column = 0; + grid2 = R_GridInsertRow(grid2, l + 1, column, grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k + 1]); grid2->lodStitched = qfalse; - worldData.surfaces[grid2num].data = (surfaceType_t *) grid2; + worldData.surfaces[grid2num].data = (surfaceType_t *)grid2; return qtrue; } } @@ -1240,26 +1270,30 @@ of the patch (on the same row or column) the vertices will not be joined and cra might still appear at that side. =============== */ -int R_TryStitchingPatch( int grid1num, world_t &worldData ) { +int R_TryStitchingPatch(int grid1num, world_t &worldData) { int j, numstitches; srfGridMesh_t *grid1, *grid2; numstitches = 0; - grid1 = (srfGridMesh_t *) worldData.surfaces[grid1num].data; - for ( j = 0; j < worldData.numsurfaces; j++ ) { + grid1 = (srfGridMesh_t *)worldData.surfaces[grid1num].data; + for (j = 0; j < worldData.numsurfaces; j++) { // - grid2 = (srfGridMesh_t *) worldData.surfaces[j].data; + grid2 = (srfGridMesh_t *)worldData.surfaces[j].data; // if this surface is not a grid - if ( grid2->surfaceType != SF_GRID ) continue; + if (grid2->surfaceType != SF_GRID) + continue; // grids in the same LOD group should have the exact same lod radius - if ( grid1->lodRadius != grid2->lodRadius ) continue; + if (grid1->lodRadius != grid2->lodRadius) + continue; // grids in the same LOD group should have the exact same lod origin - if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; - if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; - if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + if (grid1->lodOrigin[0] != grid2->lodOrigin[0]) + continue; + if (grid1->lodOrigin[1] != grid2->lodOrigin[1]) + continue; + if (grid1->lodOrigin[2] != grid2->lodOrigin[2]) + continue; // - while (R_StitchPatches(grid1num, j, worldData)) - { + while (R_StitchPatches(grid1num, j, worldData)) { numstitches++; } } @@ -1271,32 +1305,30 @@ int R_TryStitchingPatch( int grid1num, world_t &worldData ) { R_StitchAllPatches =============== */ -void R_StitchAllPatches( world_t &worldData ) { +void R_StitchAllPatches(world_t &worldData) { int i, stitched, numstitches; srfGridMesh_t *grid1; numstitches = 0; - do - { + do { stitched = qfalse; - for ( i = 0; i < worldData.numsurfaces; i++ ) { + for (i = 0; i < worldData.numsurfaces; i++) { // - grid1 = (srfGridMesh_t *) worldData.surfaces[i].data; + grid1 = (srfGridMesh_t *)worldData.surfaces[i].data; // if this surface is not a grid - if ( grid1->surfaceType != SF_GRID ) + if (grid1->surfaceType != SF_GRID) continue; // - if ( grid1->lodStitched ) + if (grid1->lodStitched) continue; // grid1->lodStitched = qtrue; stitched = qtrue; // - numstitches += R_TryStitchingPatch( i, worldData ); + numstitches += R_TryStitchingPatch(i, worldData); } - } - while (stitched); -// ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches ); + } while (stitched); + // ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches ); } /* @@ -1308,26 +1340,26 @@ void R_MovePatchSurfacesToHunk(world_t &worldData) { int i, size; srfGridMesh_t *grid, *hunkgrid; - for ( i = 0; i < worldData.numsurfaces; i++ ) { + for (i = 0; i < worldData.numsurfaces; i++) { // - grid = (srfGridMesh_t *) worldData.surfaces[i].data; + grid = (srfGridMesh_t *)worldData.surfaces[i].data; // if this surface is not a grid - if ( grid->surfaceType != SF_GRID ) + if (grid->surfaceType != SF_GRID) continue; // - size = (grid->width * grid->height - 1) * sizeof( drawVert_t ) + sizeof( *grid ); - hunkgrid = (struct srfGridMesh_s *)Hunk_Alloc( size, h_low ); + size = (grid->width * grid->height - 1) * sizeof(drawVert_t) + sizeof(*grid); + hunkgrid = (struct srfGridMesh_s *)Hunk_Alloc(size, h_low); memcpy(hunkgrid, grid, size); - hunkgrid->widthLodError = (float *)Hunk_Alloc( grid->width * 4, h_low ); - memcpy( hunkgrid->widthLodError, grid->widthLodError, grid->width * 4 ); + hunkgrid->widthLodError = (float *)Hunk_Alloc(grid->width * 4, h_low); + memcpy(hunkgrid->widthLodError, grid->widthLodError, grid->width * 4); - hunkgrid->heightLodError = (float *)Hunk_Alloc( grid->height * 4, h_low ); - memcpy( hunkgrid->heightLodError, grid->heightLodError, grid->height * 4 ); + hunkgrid->heightLodError = (float *)Hunk_Alloc(grid->height * 4, h_low); + memcpy(hunkgrid->heightLodError, grid->heightLodError, grid->height * 4); - R_FreeSurfaceGridMesh( grid ); + R_FreeSurfaceGridMesh(grid); - worldData.surfaces[i].data = (surfaceType_t *) hunkgrid; + worldData.surfaces[i].data = (surfaceType_t *)hunkgrid; } } @@ -1336,14 +1368,14 @@ void R_MovePatchSurfacesToHunk(world_t &worldData) { R_LoadSurfaces =============== */ -static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump, world_t &worldData, int index ) { - dsurface_t *in; - msurface_t *out; - mapVert_t *dv; - int *indexes; - int count; - int numFaces, numMeshes, numTriSurfs, numFlares; - int i; +static void R_LoadSurfaces(lump_t *surfs, lump_t *verts, lump_t *indexLump, world_t &worldData, int index) { + dsurface_t *in; + msurface_t *out; + mapVert_t *dv; + int *indexes; + int count; + int numFaces, numMeshes, numTriSurfs, numFlares; + int i; numFaces = 0; numMeshes = 0; @@ -1352,118 +1384,111 @@ static void R_LoadSurfaces( lump_t *surfs, lump_t *verts, lump_t *indexLump, wor in = (dsurface_t *)(fileBase + surfs->fileofs); if (surfs->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = surfs->filelen / sizeof(*in); dv = (mapVert_t *)(fileBase + verts->fileofs); if (verts->filelen % sizeof(*dv)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); indexes = (int *)(fileBase + indexLump->fileofs); - if ( indexLump->filelen % sizeof(*indexes)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + if (indexLump->filelen % sizeof(*indexes)) + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); - out = (struct msurface_s *)Hunk_Alloc ( count * sizeof(*out), h_low ); + out = (struct msurface_s *)Hunk_Alloc(count * sizeof(*out), h_low); worldData.surfaces = out; worldData.numsurfaces = count; - for ( i = 0 ; i < count ; i++, in++, out++ ) { - switch ( LittleLong( in->surfaceType ) ) { + for (i = 0; i < count; i++, in++, out++) { + switch (LittleLong(in->surfaceType)) { case MST_PATCH: - ParseMesh ( in, dv, out, worldData, index ); + ParseMesh(in, dv, out, worldData, index); numMeshes++; break; case MST_TRIANGLE_SOUP: - ParseTriSurf( in, dv, out, indexes, worldData, index ); + ParseTriSurf(in, dv, out, indexes, worldData, index); numTriSurfs++; break; case MST_PLANAR: - ParseFace( in, dv, out, indexes, worldData, index ); + ParseFace(in, dv, out, indexes, worldData, index); numFaces++; break; case MST_FLARE: - ParseFlare( in, dv, out, indexes, worldData, index ); + ParseFlare(in, dv, out, indexes, worldData, index); numFlares++; break; default: - Com_Error( ERR_DROP, "Bad surfaceType" ); + Com_Error(ERR_DROP, "Bad surfaceType"); } } - if ( r_patchStitching->integer ) { + if (r_patchStitching->integer) { R_StitchAllPatches(worldData); } R_FixSharedVertexLodError(worldData); - if ( r_patchStitching->integer ) { + if (r_patchStitching->integer) { R_MovePatchSurfacesToHunk(worldData); } - ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", numFaces, numMeshes, numTriSurfs, numFlares ); + ri.Printf(PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", numFaces, numMeshes, numTriSurfs, numFlares); } - - /* ================= R_LoadSubmodels ================= */ -static void R_LoadSubmodels( lump_t *l, world_t &worldData, int index ) { - dmodel_t *in; - bmodel_t *out; - int i, j, count; +static void R_LoadSubmodels(lump_t *l, world_t &worldData, int index) { + dmodel_t *in; + bmodel_t *out; + int i, j, count; in = (dmodel_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - worldData.bmodels = out = (bmodel_t *)Hunk_Alloc( count * sizeof(*out), h_low ); + worldData.bmodels = out = (bmodel_t *)Hunk_Alloc(count * sizeof(*out), h_low); - for ( i=0 ; itype = MOD_BRUSH; model->bmodel = out; - if (index) - { - Com_sprintf( model->name, sizeof( model->name ), "*%d-%d", index, i ); + if (index) { + Com_sprintf(model->name, sizeof(model->name), "*%d-%d", index, i); model->bspInstance = qtrue; - } - else - { - Com_sprintf( model->name, sizeof( model->name ), "*%d", i); + } else { + Com_sprintf(model->name, sizeof(model->name), "*%d", i); } - for (j=0 ; j<3 ; j++) { - out->bounds[0][j] = LittleFloat (in->mins[j]); - out->bounds[1][j] = LittleFloat (in->maxs[j]); + for (j = 0; j < 3; j++) { + out->bounds[0][j] = LittleFloat(in->mins[j]); + out->bounds[1][j] = LittleFloat(in->maxs[j]); } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ RE_InsertModelIntoHash(model->name, model); -/* -Ghoul2 Insert End -*/ - out->firstSurface = worldData.surfaces + LittleLong( in->firstSurface ); - out->numSurfaces = LittleLong( in->numSurfaces ); + /* + Ghoul2 Insert End + */ + out->firstSurface = worldData.surfaces + LittleLong(in->firstSurface); + out->numSurfaces = LittleLong(in->numSurfaces); } } - - //================================================================== /* @@ -1471,13 +1496,12 @@ Ghoul2 Insert End R_SetParent ================= */ -static void R_SetParent (mnode_t *node, mnode_t *parent) -{ +static void R_SetParent(mnode_t *node, mnode_t *parent) { node->parent = parent; if (node->contents != -1) return; - R_SetParent (node->children[0], node); - R_SetParent (node->children[1], node); + R_SetParent(node->children[0], node); + R_SetParent(node->children[1], node); } /* @@ -1485,44 +1509,40 @@ static void R_SetParent (mnode_t *node, mnode_t *parent) R_LoadNodesAndLeafs ================= */ -static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &worldData) { - int i, j, p; - dnode_t *in; - dleaf_t *inLeaf; - mnode_t *out; - int numNodes, numLeafs; +static void R_LoadNodesAndLeafs(lump_t *nodeLump, lump_t *leafLump, world_t &worldData) { + int i, j, p; + dnode_t *in; + dleaf_t *inLeaf; + mnode_t *out; + int numNodes, numLeafs; in = (dnode_t *)(fileBase + nodeLump->fileofs); - if (nodeLump->filelen % sizeof(dnode_t) || - leafLump->filelen % sizeof(dleaf_t) ) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + if (nodeLump->filelen % sizeof(dnode_t) || leafLump->filelen % sizeof(dleaf_t)) { + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } numNodes = nodeLump->filelen / sizeof(dnode_t); numLeafs = leafLump->filelen / sizeof(dleaf_t); - out = (struct mnode_s *)Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), h_low); + out = (struct mnode_s *)Hunk_Alloc((numNodes + numLeafs) * sizeof(*out), h_low); worldData.nodes = out; worldData.numnodes = numNodes + numLeafs; worldData.numDecisionNodes = numNodes; // load nodes - for ( i=0 ; imins[j] = LittleLong (in->mins[j]); - out->maxs[j] = LittleLong (in->maxs[j]); + for (i = 0; i < numNodes; i++, in++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(in->mins[j]); + out->maxs[j] = LittleLong(in->maxs[j]); } p = LittleLong(in->planeNum); out->plane = worldData.planes + p; - out->contents = CONTENTS_NODE; // differentiate from leafs + out->contents = CONTENTS_NODE; // differentiate from leafs - for (j=0 ; j<2 ; j++) - { - p = LittleLong (in->children[j]); + for (j = 0; j < 2; j++) { + p = LittleLong(in->children[j]); if (p >= 0) out->children[j] = worldData.nodes + p; else @@ -1532,28 +1552,25 @@ static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &wo // load leafs inLeaf = (dleaf_t *)(fileBase + leafLump->fileofs); - for ( i=0 ; imins[j] = LittleLong (inLeaf->mins[j]); - out->maxs[j] = LittleLong (inLeaf->maxs[j]); + for (i = 0; i < numLeafs; i++, inLeaf++, out++) { + for (j = 0; j < 3; j++) { + out->mins[j] = LittleLong(inLeaf->mins[j]); + out->maxs[j] = LittleLong(inLeaf->maxs[j]); } out->cluster = LittleLong(inLeaf->cluster); out->area = LittleLong(inLeaf->area); - if ( out->cluster >= worldData.numClusters ) { + if (out->cluster >= worldData.numClusters) { worldData.numClusters = out->cluster + 1; } - out->firstmarksurface = worldData.marksurfaces + - LittleLong(inLeaf->firstLeafSurface); + out->firstmarksurface = worldData.marksurfaces + LittleLong(inLeaf->firstLeafSurface); out->nummarksurfaces = LittleLong(inLeaf->numLeafSurfaces); } // chain decendants - R_SetParent (worldData.nodes, NULL); + R_SetParent(worldData.nodes, NULL); } //============================================================================= @@ -1563,88 +1580,84 @@ static void R_LoadNodesAndLeafs (lump_t *nodeLump, lump_t *leafLump, world_t &wo R_LoadShaders ================= */ -static void R_LoadShaders( lump_t *l, world_t &worldData ) { - int i, count; - dshader_t *in, *out; +static void R_LoadShaders(lump_t *l, world_t &worldData) { + int i, count; + dshader_t *in, *out; in = (dshader_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (dshader_t *)Hunk_Alloc ( count*sizeof(*out), h_low ); + out = (dshader_t *)Hunk_Alloc(count * sizeof(*out), h_low); worldData.shaders = out; worldData.numShaders = count; - memcpy( out, in, count*sizeof(*out) ); + memcpy(out, in, count * sizeof(*out)); - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (struct msurface_s **)Hunk_Alloc ( count*sizeof(*out), h_low); + out = (struct msurface_s **)Hunk_Alloc(count * sizeof(*out), h_low); worldData.marksurfaces = out; worldData.nummarksurfaces = count; - for ( i=0 ; ifileofs); if (l->filelen % sizeof(*in)) - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); count = l->filelen / sizeof(*in); - out = (struct cplane_s *)Hunk_Alloc ( count*2*sizeof(*out), h_low); + out = (struct cplane_s *)Hunk_Alloc(count * 2 * sizeof(*out), h_low); worldData.planes = out; worldData.numplanes = count; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + for (j = 0; j < 3; j++) { + out->normal[j] = LittleFloat(in->normal[j]); if (out->normal[j] < 0) { - bits |= 1<dist = LittleFloat (in->dist); - out->type = PlaneTypeForNormal( out->normal ); + out->dist = LittleFloat(in->dist); + out->type = PlaneTypeForNormal(out->normal); out->signbits = bits; } } @@ -1655,37 +1668,35 @@ R_LoadFogs ================= */ -static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world_t &worldData, int index ) { - int i; - fog_t *out; - dfog_t *fogs; - dbrush_t *brushes, *brush; - dbrushside_t *sides; - int count, brushesCount, sidesCount; - int sideNum; - int planeNum; - shader_t *shader; - float d; - int firstSide=0; - int lightmaps[MAXLIGHTMAPS] = { LIGHTMAP_NONE } ; +static void R_LoadFogs(lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world_t &worldData, int index) { + int i; + fog_t *out; + dfog_t *fogs; + dbrush_t *brushes, *brush; + dbrushside_t *sides; + int count, brushesCount, sidesCount; + int sideNum; + int planeNum; + shader_t *shader; + float d; + int firstSide = 0; + int lightmaps[MAXLIGHTMAPS] = {LIGHTMAP_NONE}; fogs = (dfog_t *)(fileBase + l->fileofs); if (l->filelen % sizeof(*fogs)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } count = l->filelen / sizeof(*fogs); // create fog strucutres for them worldData.numfogs = count + 1; - worldData.fogs = (fog_t *)Hunk_Alloc ( worldData.numfogs*sizeof(*out), h_low); + worldData.fogs = (fog_t *)Hunk_Alloc(worldData.numfogs * sizeof(*out), h_low); worldData.globalFog = -1; out = worldData.fogs + 1; // Copy the global fog from the main world into the bsp instance - if(index) - { - if(tr.world && (tr.world->globalFog != -1)) - { + if (index) { + if (tr.world && (tr.world->globalFog != -1)) { // Use the nightvision fog slot worldData.fogs[worldData.numfogs] = tr.world->fogs[tr.world->globalFog]; worldData.globalFog = worldData.numfogs; @@ -1693,123 +1704,114 @@ static void R_LoadFogs( lump_t *l, lump_t *brushesLump, lump_t *sidesLump, world } } - if ( !count ) { + if (!count) { return; } brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); if (brushesLump->filelen % sizeof(*brushes)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } brushesCount = brushesLump->filelen / sizeof(*brushes); sides = (dbrushside_t *)(fileBase + sidesLump->fileofs); if (sidesLump->filelen % sizeof(*sides)) { - Com_Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData.name); + Com_Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData.name); } sidesCount = sidesLump->filelen / sizeof(*sides); - for ( i=0 ; ioriginalBrushNumber = LittleLong( fogs->brushNum ); + for (i = 0; i < count; i++, fogs++) { + out->originalBrushNumber = LittleLong(fogs->brushNum); - if (out->originalBrushNumber == -1) - { + if (out->originalBrushNumber == -1) { out->bounds[0][0] = out->bounds[0][1] = out->bounds[0][2] = MIN_WORLD_COORD; out->bounds[1][0] = out->bounds[1][1] = out->bounds[1][2] = MAX_WORLD_COORD; firstSide = -1; - worldData.globalFog = i+1; - } - else - { - if ( (unsigned)out->originalBrushNumber >= (unsigned)brushesCount ) { - Com_Error( ERR_DROP, "fog brushNumber out of range" ); + worldData.globalFog = i + 1; + } else { + if ((unsigned)out->originalBrushNumber >= (unsigned)brushesCount) { + Com_Error(ERR_DROP, "fog brushNumber out of range"); } brush = brushes + out->originalBrushNumber; - firstSide = LittleLong( brush->firstSide ); + firstSide = LittleLong(brush->firstSide); - if ( (unsigned)firstSide > (unsigned)(sidesCount - 6) ) { - Com_Error( ERR_DROP, "fog brush sideNumber out of range" ); + if ((unsigned)firstSide > (unsigned)(sidesCount - 6)) { + Com_Error(ERR_DROP, "fog brush sideNumber out of range"); } // brushes are always sorted with the axial sides first sideNum = firstSide + 0; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][0] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][0] = -worldData.planes[planeNum].dist; sideNum = firstSide + 1; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][0] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][0] = worldData.planes[planeNum].dist; sideNum = firstSide + 2; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][1] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][1] = -worldData.planes[planeNum].dist; sideNum = firstSide + 3; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][1] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][1] = worldData.planes[planeNum].dist; sideNum = firstSide + 4; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[0][2] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[0][2] = -worldData.planes[planeNum].dist; sideNum = firstSide + 5; - planeNum = LittleLong( sides[ sideNum ].planeNum ); - out->bounds[1][2] = worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[sideNum].planeNum); + out->bounds[1][2] = worldData.planes[planeNum].dist; } // get information from the shader for fog parameters - shader = R_FindShader( fogs->shader, lightmaps, stylesDefault, qtrue ); + shader = R_FindShader(fogs->shader, lightmaps, stylesDefault, qtrue); - if (!shader->fogParms) - {//bad shader!! + if (!shader->fogParms) { // bad shader!! assert(shader->fogParms); out->parms.color[0] = 1.0f; out->parms.color[1] = 0.0f; out->parms.color[2] = 0.0f; out->parms.depthForOpaque = 250.0f; - } - else - { + } else { out->parms = *shader->fogParms; } - out->colorInt = ColorBytes4 ( out->parms.color[0] * tr.identityLight, - out->parms.color[1] * tr.identityLight, - out->parms.color[2] * tr.identityLight, 1.0 ); + out->colorInt = + ColorBytes4(out->parms.color[0] * tr.identityLight, out->parms.color[1] * tr.identityLight, out->parms.color[2] * tr.identityLight, 1.0); d = out->parms.depthForOpaque < 1 ? 1 : out->parms.depthForOpaque; - out->tcScale = 1.0f / ( d * 8 ); + out->tcScale = 1.0f / (d * 8); // set the gradient vector - sideNum = LittleLong( fogs->visibleSide ); + sideNum = LittleLong(fogs->visibleSide); - if ( sideNum == -1 ) { - //rww - we need to set this to qtrue for global fog as well + if (sideNum == -1) { + // rww - we need to set this to qtrue for global fog as well out->hasSurface = qtrue; } else { out->hasSurface = qtrue; - planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum ); - VectorSubtract( vec3_origin, worldData.planes[ planeNum ].normal, out->surface ); - out->surface[3] = -worldData.planes[ planeNum ].dist; + planeNum = LittleLong(sides[firstSide + sideNum].planeNum); + VectorSubtract(vec3_origin, worldData.planes[planeNum].normal, out->surface); + out->surface[3] = -worldData.planes[planeNum].dist; } out++; } - } - /* ================ R_LoadLightGrid ================ */ -void R_LoadLightGrid( lump_t *l, world_t &worldData ) { - int i, j; - vec3_t maxs; - world_t *w; - float *wMins, *wMaxs; +void R_LoadLightGrid(lump_t *l, world_t &worldData) { + int i, j; + vec3_t maxs; + world_t *w; + float *wMins, *wMaxs; w = &worldData; @@ -1820,22 +1822,20 @@ void R_LoadLightGrid( lump_t *l, world_t &worldData ) { wMins = w->bmodels[0].bounds[0]; wMaxs = w->bmodels[0].bounds[1]; - for ( i = 0 ; i < 3 ; i++ ) { - w->lightGridOrigin[i] = w->lightGridSize[i] * ceil( wMins[i] / w->lightGridSize[i] ); - maxs[i] = w->lightGridSize[i] * floor( wMaxs[i] / w->lightGridSize[i] ); - w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i])/w->lightGridSize[i] + 1; + for (i = 0; i < 3; i++) { + w->lightGridOrigin[i] = w->lightGridSize[i] * ceil(wMins[i] / w->lightGridSize[i]); + maxs[i] = w->lightGridSize[i] * floor(wMaxs[i] / w->lightGridSize[i]); + w->lightGridBounds[i] = (maxs[i] - w->lightGridOrigin[i]) / w->lightGridSize[i] + 1; } int numGridDataElements = l->filelen / sizeof(*w->lightGridData); - w->lightGridData = (mgrid_t *)Hunk_Alloc( l->filelen, h_low ); - memcpy( w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen ); + w->lightGridData = (mgrid_t *)Hunk_Alloc(l->filelen, h_low); + memcpy(w->lightGridData, (void *)(fileBase + l->fileofs), l->filelen); // deal with overbright bits - for ( i = 0 ; i < numGridDataElements ; i++ ) - { - for(j=0;jlightGridData[i].ambientLight[j]); R_ColorShiftLightingBytes(w->lightGridData[i].directLight[j]); } @@ -1848,26 +1848,26 @@ R_LoadLightGridArray ================ */ -void R_LoadLightGridArray( lump_t *l, world_t &worldData ) { - world_t *w; +void R_LoadLightGridArray(lump_t *l, world_t &worldData) { + world_t *w; #ifdef Q3_BIG_ENDIAN - int i; + int i; #endif w = &worldData; w->numGridArrayElements = w->lightGridBounds[0] * w->lightGridBounds[1] * w->lightGridBounds[2]; - if ( (unsigned)l->filelen != w->numGridArrayElements * sizeof(*w->lightGridArray) ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: light grid array mismatch\n" ); + if ((unsigned)l->filelen != w->numGridArrayElements * sizeof(*w->lightGridArray)) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: light grid array mismatch\n"); w->lightGridData = NULL; return; } - w->lightGridArray = (unsigned short *)Hunk_Alloc( l->filelen, h_low ); - memcpy( w->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen ); + w->lightGridArray = (unsigned short *)Hunk_Alloc(l->filelen, h_low); + memcpy(w->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen); #ifdef Q3_BIG_ENDIAN - for ( i = 0 ; i < w->numGridArrayElements ; i++ ) { + for (i = 0; i < w->numGridArrayElements; i++) { w->lightGridArray[i] = LittleShort(w->lightGridArray[i]); } #endif @@ -1878,12 +1878,12 @@ void R_LoadLightGridArray( lump_t *l, world_t &worldData ) { R_LoadEntities ================ */ -void R_LoadEntities( lump_t *l, world_t &worldData ) { +void R_LoadEntities(lump_t *l, world_t &worldData) { const char *p; char *token, *s; char keyname[MAX_TOKEN_CHARS]; char value[MAX_TOKEN_CHARS]; - world_t *w; + world_t *w; float ambient = 1; w = &worldData; @@ -1892,46 +1892,46 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { w->lightGridSize[2] = 128; VectorSet(tr.sunAmbient, 1, 1, 1); - tr.distanceCull = 6000;//DEFAULT_DISTANCE_CULL; + tr.distanceCull = 6000; // DEFAULT_DISTANCE_CULL; p = (char *)(fileBase + l->fileofs); // store for reference by the cgame - w->entityString = (char *)Hunk_Alloc( l->filelen + 1, h_low ); - strcpy( w->entityString, p ); + w->entityString = (char *)Hunk_Alloc(l->filelen + 1, h_low); + strcpy(w->entityString, p); w->entityParsePoint = w->entityString; - COM_BeginParseSession ("R_LoadEntities"); + COM_BeginParseSession("R_LoadEntities"); - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); if (!*token || *token != '{') { return; } // only parse the world spawn - while ( 1 ) { + while (1) { // parse key - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(keyname, token, sizeof(keyname)); // parse value - token = COM_ParseExt( &p, qtrue ); + token = COM_ParseExt(&p, qtrue); - if ( !*token || *token == '}' ) { + if (!*token || *token == '}') { break; } Q_strncpyz(value, token, sizeof(value)); // check for remapping of shaders for vertex lighting s = "vertexremapshader"; - if (!Q_strncmp(keyname, s, strlen(s)) ) { + if (!Q_strncmp(keyname, s, strlen(s))) { s = strchr(value, ';'); if (!s) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: no semi colon in vertexshaderremap '%s'\n", value ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: no semi colon in vertexshaderremap '%s'\n", value); break; } *s++ = 0; @@ -1942,28 +1942,28 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { } // check for remapping of shaders s = "remapshader"; - if (!Q_strncmp(keyname, s, strlen(s)) ) { + if (!Q_strncmp(keyname, s, strlen(s))) { s = strchr(value, ';'); if (!s) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: no semi colon in shaderremap '%s'\n", value ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: no semi colon in shaderremap '%s'\n", value); break; } *s++ = 0; R_RemapShader(value, s, "0"); continue; } - if (!Q_stricmp(keyname, "distanceCull")) { - sscanf(value, "%f", &tr.distanceCull ); + if (!Q_stricmp(keyname, "distanceCull")) { + sscanf(value, "%f", &tr.distanceCull); continue; } // check for a different grid size if (!Q_stricmp(keyname, "gridsize")) { - sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] ); + sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2]); continue; } - // find the optional world ambient for arioche + // find the optional world ambient for arioche if (!Q_stricmp(keyname, "_color")) { - sscanf(value, "%f %f %f", &tr.sunAmbient[0], &tr.sunAmbient[1], &tr.sunAmbient[2] ); + sscanf(value, "%f %f %f", &tr.sunAmbient[0], &tr.sunAmbient[1], &tr.sunAmbient[2]); continue; } if (!Q_stricmp(keyname, "ambient")) { @@ -1971,8 +1971,8 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { continue; } } - //both default to 1 so no harm if not present. - VectorScale( tr.sunAmbient, ambient, tr.sunAmbient); + // both default to 1 so no harm if not present. + VectorScale(tr.sunAmbient, ambient, tr.sunAmbient); } /* @@ -1980,18 +1980,17 @@ void R_LoadEntities( lump_t *l, world_t &worldData ) { R_GetEntityToken ================= */ -qboolean R_GetEntityToken( char *buffer, int size ) { - const char *s; +qboolean R_GetEntityToken(char *buffer, int size) { + const char *s; - if (size == -1) - { //force reset + if (size == -1) { // force reset s_worldData.entityParsePoint = s_worldData.entityString; return qtrue; } - s = COM_Parse( (const char **) &s_worldData.entityParsePoint ); - Q_strncpyz( buffer, s, size ); - if ( !s_worldData.entityParsePoint || !s[0] ) { + s = COM_Parse((const char **)&s_worldData.entityParsePoint); + Q_strncpyz(buffer, s, size); + if (!s_worldData.entityParsePoint || !s[0]) { return qfalse; } else { return qtrue; @@ -2005,18 +2004,16 @@ RE_LoadWorldMap Called directly from cgame ================= */ -void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) -{ - dheader_t *header; - byte *buffer; - byte *startMarker; +void RE_LoadWorldMap_Actual(const char *name, world_t &worldData, int index) { + dheader_t *header; + byte *buffer; + byte *startMarker; - if ( tr.worldMapLoaded && !index ) { - Com_Error( ERR_DROP, "ERROR: attempted to redundantly load world map\n" ); + if (tr.worldMapLoaded && !index) { + Com_Error(ERR_DROP, "ERROR: attempted to redundantly load world map\n"); } - if (!index) - { + if (!index) { skyboxportal = 0; // set default sun direction to be used if it isn't @@ -2025,7 +2022,7 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) tr.sunDirection[1] = 0.3f; tr.sunDirection[2] = 0.9f; - VectorNormalize( tr.sunDirection ); + VectorNormalize(tr.sunDirection); tr.worldMapLoaded = qtrue; @@ -2036,27 +2033,24 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) // check for cached disk file from the server first... // - if (ri.CM_GetCachedMapDiskImage()) - { + if (ri.CM_GetCachedMapDiskImage()) { buffer = (byte *)ri.CM_GetCachedMapDiskImage(); - } - else - { + } else { // still needs loading... // - ri.FS_ReadFile( name, (void **)&buffer ); - if ( !buffer ) { - Com_Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name); + ri.FS_ReadFile(name, (void **)&buffer); + if (!buffer) { + Com_Error(ERR_DROP, "RE_LoadWorldMap: %s not found", name); } } - memset( &worldData, 0, sizeof( worldData ) ); - Q_strncpyz( worldData.name, name, sizeof( worldData.name ) ); - Q_strncpyz( tr.worldDir, name, sizeof( tr.worldDir ) ); - Q_strncpyz( worldData.baseName, COM_SkipPath( worldData.name ), sizeof( worldData.name ) ); + memset(&worldData, 0, sizeof(worldData)); + Q_strncpyz(worldData.name, name, sizeof(worldData.name)); + Q_strncpyz(tr.worldDir, name, sizeof(tr.worldDir)); + Q_strncpyz(worldData.baseName, COM_SkipPath(worldData.name), sizeof(worldData.name)); - COM_StripExtension( worldData.baseName, worldData.baseName, sizeof( worldData.baseName ) ); - COM_StripExtension( tr.worldDir, tr.worldDir, sizeof( tr.worldDir ) ); + COM_StripExtension(worldData.baseName, worldData.baseName, sizeof(worldData.baseName)); + COM_StripExtension(tr.worldDir, tr.worldDir, sizeof(tr.worldDir)); startMarker = (byte *)Hunk_Alloc(0, h_low); c_gridVerts = 0; @@ -2064,57 +2058,50 @@ void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ) header = (dheader_t *)buffer; fileBase = (byte *)header; - int i = LittleLong (header->version); - if ( i != BSP_VERSION ) { - Com_Error (ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)", - name, i, BSP_VERSION); + int i = LittleLong(header->version); + if (i != BSP_VERSION) { + Com_Error(ERR_DROP, "RE_LoadWorldMap: %s has wrong version number (%i should be %i)", name, i, BSP_VERSION); } // swap all the lumps - for (size_t i=0 ; ilumps[LUMP_SHADERS], worldData ); - R_LoadLightmaps( &header->lumps[LUMP_LIGHTMAPS], name, worldData ); - R_LoadPlanes (&header->lumps[LUMP_PLANES], worldData); - R_LoadFogs( &header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES], worldData, index ); - R_LoadSurfaces( &header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES], worldData, index ); - R_LoadMarksurfaces (&header->lumps[LUMP_LEAFSURFACES], worldData); - R_LoadNodesAndLeafs (&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS], worldData); - R_LoadSubmodels (&header->lumps[LUMP_MODELS], worldData, index); - R_LoadVisibility( &header->lumps[LUMP_VISIBILITY], worldData ); + R_LoadShaders(&header->lumps[LUMP_SHADERS], worldData); + R_LoadLightmaps(&header->lumps[LUMP_LIGHTMAPS], name, worldData); + R_LoadPlanes(&header->lumps[LUMP_PLANES], worldData); + R_LoadFogs(&header->lumps[LUMP_FOGS], &header->lumps[LUMP_BRUSHES], &header->lumps[LUMP_BRUSHSIDES], worldData, index); + R_LoadSurfaces(&header->lumps[LUMP_SURFACES], &header->lumps[LUMP_DRAWVERTS], &header->lumps[LUMP_DRAWINDEXES], worldData, index); + R_LoadMarksurfaces(&header->lumps[LUMP_LEAFSURFACES], worldData); + R_LoadNodesAndLeafs(&header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS], worldData); + R_LoadSubmodels(&header->lumps[LUMP_MODELS], worldData, index); + R_LoadVisibility(&header->lumps[LUMP_VISIBILITY], worldData); worldData.dataSize = (byte *)Hunk_Alloc(0, h_low) - startMarker; - if (!index) - { - R_LoadEntities( &header->lumps[LUMP_ENTITIES], worldData ); - R_LoadLightGrid( &header->lumps[LUMP_LIGHTGRID], worldData ); - R_LoadLightGridArray( &header->lumps[LUMP_LIGHTARRAY], worldData ); + if (!index) { + R_LoadEntities(&header->lumps[LUMP_ENTITIES], worldData); + R_LoadLightGrid(&header->lumps[LUMP_LIGHTGRID], worldData); + R_LoadLightGridArray(&header->lumps[LUMP_LIGHTARRAY], worldData); // only set tr.world now that we know the entire level has loaded properly tr.world = &worldData; } - if (ri.CM_GetCachedMapDiskImage()) - { - Z_Free( ri.CM_GetCachedMapDiskImage() ); - ri.CM_SetCachedMapDiskImage( NULL ); - } - else - { - ri.FS_FreeFile( buffer ); + if (ri.CM_GetCachedMapDiskImage()) { + Z_Free(ri.CM_GetCachedMapDiskImage()); + ri.CM_SetCachedMapDiskImage(NULL); + } else { + ri.FS_FreeFile(buffer); } } - // new wrapper used for convenience to tell z_malloc()-fail recovery code whether it's safe to dump the cached-bsp or not. // -void RE_LoadWorldMap( const char *name ) -{ - ri.CM_SetUsingCache( qtrue ); - RE_LoadWorldMap_Actual( name, s_worldData, 0 ); - ri.CM_SetUsingCache( qfalse ); +void RE_LoadWorldMap(const char *name) { + ri.CM_SetUsingCache(qtrue); + RE_LoadWorldMap_Actual(name, s_worldData, 0); + ri.CM_SetUsingCache(qfalse); } diff --git a/codemp/rd-vanilla/tr_cmds.cpp b/codemp/rd-vanilla/tr_cmds.cpp index 59433b3aa2..b93c356617 100644 --- a/codemp/rd-vanilla/tr_cmds.cpp +++ b/codemp/rd-vanilla/tr_cmds.cpp @@ -23,62 +23,51 @@ along with this program; if not, see . #include "tr_local.h" - /* ===================== R_PerformanceCounters ===================== */ -void R_PerformanceCounters( void ) { - if ( !r_speeds->integer ) { +void R_PerformanceCounters(void) { + if (!r_speeds->integer) { // clear the counters even if we aren't printing - memset( &tr.pc, 0, sizeof( tr.pc ) ); - memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + memset(&tr.pc, 0, sizeof(tr.pc)); + memset(&backEnd.pc, 0, sizeof(backEnd.pc)); return; } if (r_speeds->integer == 1) { - const float texSize = R_SumOfUsedImages( qfalse )/(8*1048576.0f)*(r_texturebits->integer?r_texturebits->integer:glConfig.colorBits); - ri.Printf( PRINT_ALL, "%i/%i shdrs/srfs %i leafs %i vrts %i/%i tris %.2fMB tex %.2f dc\n", - backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, - backEnd.pc.c_indexes/3, backEnd.pc.c_totalIndexes/3, - texSize, backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight) ); + const float texSize = R_SumOfUsedImages(qfalse) / (8 * 1048576.0f) * (r_texturebits->integer ? r_texturebits->integer : glConfig.colorBits); + ri.Printf(PRINT_ALL, "%i/%i shdrs/srfs %i leafs %i vrts %i/%i tris %.2fMB tex %.2f dc\n", backEnd.pc.c_shaders, backEnd.pc.c_surfaces, tr.pc.c_leafs, + backEnd.pc.c_vertexes, backEnd.pc.c_indexes / 3, backEnd.pc.c_totalIndexes / 3, texSize, + backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight)); } else if (r_speeds->integer == 2) { - ri.Printf( PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out, - tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out ); - ri.Printf( PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", - tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out, - tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out ); + ri.Printf(PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, + tr.pc.c_sphere_cull_patch_out, tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out); + ri.Printf(PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, + tr.pc.c_sphere_cull_md3_out, tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out); } else if (r_speeds->integer == 3) { - ri.Printf( PRINT_ALL, "viewcluster: %i\n", tr.viewCluster ); + ri.Printf(PRINT_ALL, "viewcluster: %i\n", tr.viewCluster); } else if (r_speeds->integer == 4) { - if ( backEnd.pc.c_dlightVertexes ) { - ri.Printf( PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", - tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, - backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 ); + if (backEnd.pc.c_dlightVertexes) { + ri.Printf(PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, + backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3); } - } - else if (r_speeds->integer == 5 ) - { - ri.Printf( PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar ); - } - else if (r_speeds->integer == 6 ) - { - ri.Printf( PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", - backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders ); - } - else if (r_speeds->integer == 7) { + } else if (r_speeds->integer == 5) { + ri.Printf(PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar); + } else if (r_speeds->integer == 6) { + ri.Printf(PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders); + } else if (r_speeds->integer == 7) { const float texSize = R_SumOfUsedImages(qtrue) / (1048576.0f); - const float backBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.colorBits / (8.0f * 1024*1024); - const float depthBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.depthBits / (8.0f * 1024*1024); - const float stencilBuff= glConfig.vidWidth * glConfig.vidHeight * glConfig.stencilBits / (8.0f * 1024*1024); - ri.Printf( PRINT_ALL, "Tex MB %.2f + buffers %.2f MB = Total %.2fMB\n", - texSize, backBuff*2+depthBuff+stencilBuff, texSize+backBuff*2+depthBuff+stencilBuff); + const float backBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.colorBits / (8.0f * 1024 * 1024); + const float depthBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.depthBits / (8.0f * 1024 * 1024); + const float stencilBuff = glConfig.vidWidth * glConfig.vidHeight * glConfig.stencilBits / (8.0f * 1024 * 1024); + ri.Printf(PRINT_ALL, "Tex MB %.2f + buffers %.2f MB = Total %.2fMB\n", texSize, backBuff * 2 + depthBuff + stencilBuff, + texSize + backBuff * 2 + depthBuff + stencilBuff); } - memset( &tr.pc, 0, sizeof( tr.pc ) ); - memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + memset(&tr.pc, 0, sizeof(tr.pc)); + memset(&backEnd.pc, 0, sizeof(backEnd.pc)); } /* @@ -86,8 +75,8 @@ void R_PerformanceCounters( void ) { R_IssueRenderCommands ==================== */ -void R_IssueRenderCommands( qboolean runPerformanceCounters ) { - renderCommandList_t *cmdList; +void R_IssueRenderCommands(qboolean runPerformanceCounters) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; @@ -100,18 +89,17 @@ void R_IssueRenderCommands( qboolean runPerformanceCounters ) { // at this point, the back end thread is idle, so it is ok // to look at it's performance counters - if ( runPerformanceCounters ) { + if (runPerformanceCounters) { R_PerformanceCounters(); } // actually start the commands going - if ( !r_skipBackEnd->integer ) { + if (!r_skipBackEnd->integer) { // let it start on the new batch - RB_ExecuteRenderCommands( cmdList->cmds ); + RB_ExecuteRenderCommands(cmdList->cmds); } } - /* ==================== R_IssuePendingRenderCommands @@ -119,11 +107,11 @@ R_IssuePendingRenderCommands Issue any pending commands and wait for them to complete. ==================== */ -void R_IssuePendingRenderCommands( void ) { - if ( !tr.registered ) { +void R_IssuePendingRenderCommands(void) { + if (!tr.registered) { return; } - R_IssueRenderCommands( qfalse ); + R_IssueRenderCommands(qfalse); } /* @@ -133,16 +121,16 @@ R_GetCommandBufferReserved make sure there is enough command space ============ */ -static void *R_GetCommandBufferReserved( int bytes, int reservedBytes ) { - renderCommandList_t *cmdList; +static void *R_GetCommandBufferReserved(int bytes, int reservedBytes) { + renderCommandList_t *cmdList; cmdList = &backEndData->commands; bytes = PAD(bytes, sizeof(void *)); // always leave room for the end of list command - if ( cmdList->used + bytes + sizeof( int ) + reservedBytes > MAX_RENDER_COMMANDS ) { - if ( bytes > MAX_RENDER_COMMANDS - (int)sizeof( int ) ) { - ri.Error( ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes ); + if (cmdList->used + bytes + sizeof(int) + reservedBytes > MAX_RENDER_COMMANDS) { + if (bytes > MAX_RENDER_COMMANDS - (int)sizeof(int)) { + ri.Error(ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes); } // if we run out of room, just start dropping commands return NULL; @@ -160,10 +148,7 @@ R_GetCommandBuffer make sure there is enough command space ============ */ -static void *R_GetCommandBuffer( int bytes ) { - return R_GetCommandBufferReserved( bytes, PAD( sizeof( swapBuffersCommand_t ), sizeof(void *) ) ); -} - +static void *R_GetCommandBuffer(int bytes) { return R_GetCommandBufferReserved(bytes, PAD(sizeof(swapBuffersCommand_t), sizeof(void *))); } /* ============= @@ -171,11 +156,11 @@ R_AddDrawSurfCmd ============= */ -void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { - drawSurfsCommand_t *cmd; +void R_AddDrawSurfCmd(drawSurf_t *drawSurfs, int numDrawSurfs) { + drawSurfsCommand_t *cmd; - cmd = (drawSurfsCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawSurfsCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_DRAW_SURFS; @@ -187,7 +172,6 @@ void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { cmd->viewParms = tr.viewParms; } - /* ============= RE_SetColor @@ -195,46 +179,43 @@ RE_SetColor Passing NULL will set the color to white ============= */ -void RE_SetColor( const float *rgba ) { - setColorCommand_t *cmd; +void RE_SetColor(const float *rgba) { + setColorCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (setColorCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (setColorCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_SET_COLOR; - if ( !rgba ) { + if (!rgba) { rgba = colorWhite; } cmd->color[0] = rgba[0]; cmd->color[1] = rgba[1]; cmd->color[2] = rgba[2]; cmd->color[3] = rgba[3]; - } - /* ============= RE_StretchPic ============= */ -void RE_StretchPic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2, qhandle_t hShader ) { - stretchPicCommand_t *cmd; +void RE_StretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + stretchPicCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (stretchPicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (stretchPicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_STRETCH_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -250,19 +231,18 @@ void RE_StretchPic ( float x, float y, float w, float h, RE_RotatePic ============= */ -void RE_RotatePic ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -279,20 +259,19 @@ void RE_RotatePic ( float x, float y, float w, float h, RE_RotatePic2 ============= */ -void RE_RotatePic2 ( float x, float y, float w, float h, - float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { - rotatePicCommand_t *cmd; +void RE_RotatePic2(float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader) { + rotatePicCommand_t *cmd; if (!tr.registered) { return; } - cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (rotatePicCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_ROTATE_PIC2; - cmd->shader = R_GetShaderByHandle( hShader ); + cmd->shader = R_GetShaderByHandle(hShader); cmd->x = x; cmd->y = y; cmd->w = w; @@ -304,30 +283,27 @@ void RE_RotatePic2 ( float x, float y, float w, float h, cmd->a = a; } -void RE_RenderWorldEffects(void) -{ - drawBufferCommand_t *cmd; +void RE_RenderWorldEffects(void) { + drawBufferCommand_t *cmd; if (!tr.registered) { return; } - cmd = (drawBufferCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_WORLD_EFFECTS; } -void RE_RenderAutoMap(void) -{ - drawBufferCommand_t *cmd; +void RE_RenderAutoMap(void) { + drawBufferCommand_t *cmd; if (!tr.registered) { return; } - cmd = (drawBufferCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) - { + cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_AUTO_MAP; @@ -341,10 +317,10 @@ If running in stereo, RE_BeginFrame will be called twice for each RE_EndFrame ==================== */ -void RE_BeginFrame( stereoFrame_t stereoFrame ) { - drawBufferCommand_t *cmd = NULL; +void RE_BeginFrame(stereoFrame_t stereoFrame) { + drawBufferCommand_t *cmd = NULL; - if ( !tr.registered ) { + if (!tr.registered) { return; } glState.finishCalled = qfalse; @@ -355,37 +331,29 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // do overdraw measurement // - if ( r_measureOverdraw->integer ) - { - if ( glConfig.stencilBits < 4 ) - { - ri.Printf( PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + if (r_measureOverdraw->integer) { + if (glConfig.stencilBits < 4) { + ri.Printf(PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else if ( r_shadows->integer == 2 ) - { - ri.Printf( PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" ); - ri.Cvar_Set( "r_measureOverdraw", "0" ); + } else if (r_shadows->integer == 2) { + ri.Printf(PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n"); + ri.Cvar_Set("r_measureOverdraw", "0"); r_measureOverdraw->modified = qfalse; - } - else - { + } else { R_IssuePendingRenderCommands(); - qglEnable( GL_STENCIL_TEST ); - qglStencilMask( ~0U ); - qglClearStencil( 0U ); - qglStencilFunc( GL_ALWAYS, 0U, ~0U ); - qglStencilOp( GL_KEEP, GL_INCR, GL_INCR ); + qglEnable(GL_STENCIL_TEST); + qglStencilMask(~0U); + qglClearStencil(0U); + qglStencilFunc(GL_ALWAYS, 0U, ~0U); + qglStencilOp(GL_KEEP, GL_INCR, GL_INCR); } r_measureOverdraw->modified = qfalse; - } - else - { + } else { // this is only reached if it was on and is now off - if ( r_measureOverdraw->modified ) { + if (r_measureOverdraw->modified) { R_IssuePendingRenderCommands(); - qglDisable( GL_STENCIL_TEST ); + qglDisable(GL_STENCIL_TEST); } r_measureOverdraw->modified = qfalse; } @@ -393,9 +361,9 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // texturemode stuff // - if ( r_textureMode->modified || r_ext_texture_filter_anisotropic->modified) { + if (r_textureMode->modified || r_ext_texture_filter_anisotropic->modified) { R_IssuePendingRenderCommands(); - GL_TextureMode( r_textureMode->string ); + GL_TextureMode(r_textureMode->string); r_textureMode->modified = qfalse; r_ext_texture_filter_anisotropic->modified = qfalse; } @@ -403,7 +371,7 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { // // gamma stuff // - if ( r_gamma->modified ) { + if (r_gamma->modified) { r_gamma->modified = qfalse; R_IssuePendingRenderCommands(); @@ -412,46 +380,43 @@ void RE_BeginFrame( stereoFrame_t stereoFrame ) { } // check for errors - if ( !r_ignoreGLErrors->integer ) { + if (!r_ignoreGLErrors->integer) { R_IssuePendingRenderCommands(); GLenum err = qglGetError(); - if ( err != GL_NO_ERROR ) { - Com_Error( ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err ); + if (err != GL_NO_ERROR) { + Com_Error(ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err); } } // // draw buffer stuff // - cmd = (drawBufferCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) { + cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) { return; } cmd->commandId = RC_DRAW_BUFFER; - if ( glConfig.stereoEnabled ) { - if ( stereoFrame == STEREO_LEFT ) { + if (glConfig.stereoEnabled) { + if (stereoFrame == STEREO_LEFT) { cmd->buffer = (int)GL_BACK_LEFT; - } else if ( stereoFrame == STEREO_RIGHT ) { + } else if (stereoFrame == STEREO_RIGHT) { cmd->buffer = (int)GL_BACK_RIGHT; } else { - Com_Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + Com_Error(ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame); } } else { - if ( stereoFrame != STEREO_CENTER ) { - Com_Error( ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame ); - } -// if ( !Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) ) { -// cmd->buffer = (int)GL_FRONT; -// } else - { - cmd->buffer = (int)GL_BACK; + if (stereoFrame != STEREO_CENTER) { + Com_Error(ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame); } + // if ( !Q_stricmp( r_drawBuffer->string, "GL_FRONT" ) ) { + // cmd->buffer = (int)GL_FRONT; + // } else + { cmd->buffer = (int)GL_BACK; } } } - /* ============= RE_EndFrame @@ -459,29 +424,29 @@ RE_EndFrame Returns the number of msec spent in the back end ============= */ -void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { - swapBuffersCommand_t *cmd; +void RE_EndFrame(int *frontEndMsec, int *backEndMsec) { + swapBuffersCommand_t *cmd; - if ( !tr.registered ) { + if (!tr.registered) { return; } - cmd = (swapBuffersCommand_t *) R_GetCommandBufferReserved( sizeof( *cmd ), 0 ); - if ( !cmd ) { + cmd = (swapBuffersCommand_t *)R_GetCommandBufferReserved(sizeof(*cmd), 0); + if (!cmd) { return; } cmd->commandId = RC_SWAP_BUFFERS; - R_IssueRenderCommands( qtrue ); + R_IssueRenderCommands(qtrue); // use the other buffers next frame, because another CPU // may still be rendering into the current ones R_InitNextFrame(); - if ( frontEndMsec ) { + if (frontEndMsec) { *frontEndMsec = tr.frontEndMsec; } tr.frontEndMsec = 0; - if ( backEndMsec ) { + if (backEndMsec) { *backEndMsec = backEnd.pc.msec; } backEnd.pc.msec = 0; @@ -492,15 +457,14 @@ void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { RE_TakeVideoFrame ============= */ -void RE_TakeVideoFrame( int width, int height, byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg ) -{ +void RE_TakeVideoFrame(int width, int height, byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg) { videoFrameCommand_t *cmd; - if ( !tr.registered ) + if (!tr.registered) return; - cmd = (videoFrameCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); - if ( !cmd ) + cmd = (videoFrameCommand_t *)R_GetCommandBuffer(sizeof(*cmd)); + if (!cmd) return; cmd->commandId = RC_VIDEOFRAME; diff --git a/codemp/rd-vanilla/tr_curve.cpp b/codemp/rd-vanilla/tr_curve.cpp index e3d75834f1..c66bd42e31 100644 --- a/codemp/rd-vanilla/tr_curve.cpp +++ b/codemp/rd-vanilla/tr_curve.cpp @@ -38,15 +38,13 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, */ - /* ============ LerpDrawVert ============ */ -static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) -{ - int k; +static void LerpDrawVert(drawVert_t *a, drawVert_t *b, drawVert_t *out) { + int k; out->xyz[0] = 0.5 * (a->xyz[0] + b->xyz[0]); out->xyz[1] = 0.5 * (a->xyz[1] + b->xyz[1]); @@ -59,8 +57,7 @@ static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) out->normal[1] = 0.5 * (a->normal[1] + b->normal[1]); out->normal[2] = 0.5 * (a->normal[2] + b->normal[2]); - for(k=0;klightmap[k][0] = 0.5 * (a->lightmap[k][0] + b->lightmap[k][0]); out->lightmap[k][1] = 0.5 * (a->lightmap[k][1] + b->lightmap[k][1]); @@ -76,14 +73,14 @@ static void LerpDrawVert( drawVert_t *a, drawVert_t *b, drawVert_t *out ) Transpose ============ */ -static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - drawVert_t temp; - - if ( width > height ) { - for ( i = 0 ; i < height ; i++ ) { - for ( j = i + 1 ; j < width ; j++ ) { - if ( j < height ) { +static void Transpose(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + drawVert_t temp; + + if (width > height) { + for (i = 0; i < height; i++) { + for (j = i + 1; j < width; j++) { + if (j < height) { // swap the value temp = ctrl[j][i]; ctrl[j][i] = ctrl[i][j]; @@ -95,9 +92,9 @@ static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX } } } else { - for ( i = 0 ; i < width ; i++ ) { - for ( j = i + 1 ; j < height ; j++ ) { - if ( j < width ) { + for (i = 0; i < width; i++) { + for (j = i + 1; j < height; j++) { + if (j < width) { // swap the value temp = ctrl[i][j]; ctrl[i][j] = ctrl[j][i]; @@ -109,10 +106,8 @@ static void Transpose( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX } } } - } - /* ================= MakeMeshNormals @@ -120,106 +115,103 @@ MakeMeshNormals Handles all the complicated wrapping and degenerate cases ================= */ -static void MakeMeshNormals( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j, k, dist; - vec3_t normal; - vec3_t sum; - int count; - vec3_t base; - vec3_t delta; - int x, y; - drawVert_t *dv; - vec3_t around[8], temp; - qboolean good[8]; - qboolean wrapWidth, wrapHeight; - float len; -static int neighbors[8][2] = { - {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} - }; +static void MakeMeshNormals(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j, k, dist; + vec3_t normal; + vec3_t sum; + int count; + vec3_t base; + vec3_t delta; + int x, y; + drawVert_t *dv; + vec3_t around[8], temp; + qboolean good[8]; + qboolean wrapWidth, wrapHeight; + float len; + static int neighbors[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; wrapWidth = qfalse; - for ( i = 0 ; i < height ; i++ ) { - VectorSubtract( ctrl[i][0].xyz, ctrl[i][width-1].xyz, delta ); - len = VectorLengthSquared( delta ); - if ( len > 1.0 ) { + for (i = 0; i < height; i++) { + VectorSubtract(ctrl[i][0].xyz, ctrl[i][width - 1].xyz, delta); + len = VectorLengthSquared(delta); + if (len > 1.0) { break; } } - if ( i == height ) { + if (i == height) { wrapWidth = qtrue; } wrapHeight = qfalse; - for ( i = 0 ; i < width ; i++ ) { - VectorSubtract( ctrl[0][i].xyz, ctrl[height-1][i].xyz, delta ); - len = VectorLengthSquared( delta ); - if ( len > 1.0 ) { + for (i = 0; i < width; i++) { + VectorSubtract(ctrl[0][i].xyz, ctrl[height - 1][i].xyz, delta); + len = VectorLengthSquared(delta); + if (len > 1.0) { break; } } - if ( i == width) { + if (i == width) { wrapHeight = qtrue; } - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { count = 0; dv = &ctrl[j][i]; - VectorCopy( dv->xyz, base ); - for ( k = 0 ; k < 8 ; k++ ) { - VectorClear( around[k] ); + VectorCopy(dv->xyz, base); + for (k = 0; k < 8; k++) { + VectorClear(around[k]); good[k] = qfalse; - for ( dist = 1 ; dist <= 3 ; dist++ ) { + for (dist = 1; dist <= 3; dist++) { x = i + neighbors[k][0] * dist; y = j + neighbors[k][1] * dist; - if ( wrapWidth ) { - if ( x < 0 ) { + if (wrapWidth) { + if (x < 0) { x = width - 1 + x; - } else if ( x >= width ) { + } else if (x >= width) { x = 1 + x - width; } } - if ( wrapHeight ) { - if ( y < 0 ) { + if (wrapHeight) { + if (y < 0) { y = height - 1 + y; - } else if ( y >= height ) { + } else if (y >= height) { y = 1 + y - height; } } - if ( x < 0 || x >= width || y < 0 || y >= height ) { - break; // edge of patch + if (x < 0 || x >= width || y < 0 || y >= height) { + break; // edge of patch } - VectorSubtract( ctrl[y][x].xyz, base, temp ); - if ( VectorNormalize2( temp, temp ) == 0 ) { - continue; // degenerate edge, get more dist + VectorSubtract(ctrl[y][x].xyz, base, temp); + if (VectorNormalize2(temp, temp) == 0) { + continue; // degenerate edge, get more dist } else { good[k] = qtrue; - VectorCopy( temp, around[k] ); - break; // good edge + VectorCopy(temp, around[k]); + break; // good edge } } } - VectorClear( sum ); - for ( k = 0 ; k < 8 ; k++ ) { - if ( !good[k] || !good[(k+1)&7] ) { - continue; // didn't get two points + VectorClear(sum); + for (k = 0; k < 8; k++) { + if (!good[k] || !good[(k + 1) & 7]) { + continue; // didn't get two points } - CrossProduct( around[(k+1)&7], around[k], normal ); - if ( VectorNormalize2( normal, normal ) == 0 ) { + CrossProduct(around[(k + 1) & 7], around[k], normal); + if (VectorNormalize2(normal, normal) == 0) { continue; } - VectorAdd( normal, sum, sum ); + VectorAdd(normal, sum, sum); count++; } - if ( count == 0 ) { -//printf("bad normal\n"); + if (count == 0) { + // printf("bad normal\n"); count = 1; } - VectorNormalize2( sum, dv->normal ); + VectorNormalize2(sum, dv->normal); } } } @@ -229,15 +221,15 @@ static int neighbors[8][2] = { InvertCtrl ============ */ -static void InvertCtrl( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { - int i, j; - drawVert_t temp; +static void InvertCtrl(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]) { + int i, j; + drawVert_t temp; - for ( i = 0 ; i < height ; i++ ) { - for ( j = 0 ; j < width/2 ; j++ ) { + for (i = 0; i < height; i++) { + for (j = 0; j < width / 2; j++) { temp = ctrl[i][j]; - ctrl[i][j] = ctrl[i][width-1-j]; - ctrl[i][width-1-j] = temp; + ctrl[i][j] = ctrl[i][width - 1 - j]; + ctrl[i][width - 1 - j] = temp; } } } @@ -247,20 +239,19 @@ static void InvertCtrl( int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MA InvertErrorTable ================= */ -static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int height ) { - int i; - float copy[2][MAX_GRID_SIZE]; +static void InvertErrorTable(float errorTable[2][MAX_GRID_SIZE], int width, int height) { + int i; + float copy[2][MAX_GRID_SIZE]; - memcpy( copy, errorTable, sizeof( copy ) ); + memcpy(copy, errorTable, sizeof(copy)); - for ( i = 0 ; i < width ; i++ ) { - errorTable[1][i] = copy[0][i]; //[width-1-i]; + for (i = 0; i < width; i++) { + errorTable[1][i] = copy[0][i]; //[width-1-i]; } - for ( i = 0 ; i < height ; i++ ) { - errorTable[0][i] = copy[1][height-1-i]; + for (i = 0; i < height; i++) { + errorTable[0][i] = copy[1][height - 1 - i]; } - } /* @@ -268,25 +259,23 @@ static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int PutPointsOnCurve ================== */ -static void PutPointsOnCurve( drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], - int width, int height ) { - int i, j; - drawVert_t prev, next; - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 1 ; j < height ; j += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j+1][i], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j-1][i], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); +static void PutPointsOnCurve(drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], int width, int height) { + int i, j; + drawVert_t prev, next; + + for (i = 0; i < width; i++) { + for (j = 1; j < height; j += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j + 1][i], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j - 1][i], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } - - for ( j = 0 ; j < height ; j++ ) { - for ( i = 1 ; i < width ; i += 2 ) { - LerpDrawVert( &ctrl[j][i], &ctrl[j][i+1], &prev ); - LerpDrawVert( &ctrl[j][i], &ctrl[j][i-1], &next ); - LerpDrawVert( &prev, &next, &ctrl[j][i] ); + for (j = 0; j < height; j++) { + for (i = 1; i < width; i += 2) { + LerpDrawVert(&ctrl[j][i], &ctrl[j][i + 1], &prev); + LerpDrawVert(&ctrl[j][i], &ctrl[j][i - 1], &next); + LerpDrawVert(&prev, &next, &ctrl[j][i]); } } } @@ -296,44 +285,43 @@ static void PutPointsOnCurve( drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], R_CreateSurfaceGridMesh ================= */ -srfGridMesh_t *R_CreateSurfaceGridMesh(int width, int height, - drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE] ) { +srfGridMesh_t *R_CreateSurfaceGridMesh(int width, int height, drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE]) { int i, j, size; - drawVert_t *vert; - vec3_t tmpVec; + drawVert_t *vert; + vec3_t tmpVec; srfGridMesh_t *grid; // copy the results out to a grid - size = (width * height - 1) * sizeof( drawVert_t ) + sizeof( *grid ); + size = (width * height - 1) * sizeof(drawVert_t) + sizeof(*grid); - grid = (struct srfGridMesh_s *)/*Hunk_Alloc*/ Z_Malloc( size, TAG_GRIDMESH, qfalse ); + grid = (struct srfGridMesh_s *)/*Hunk_Alloc*/ Z_Malloc(size, TAG_GRIDMESH, qfalse); memset(grid, 0, size); - grid->widthLodError = (float *)/*Hunk_Alloc*/ Z_Malloc( width * 4, TAG_GRIDMESH, qfalse ); - memcpy( grid->widthLodError, errorTable[0], width * 4 ); + grid->widthLodError = (float *)/*Hunk_Alloc*/ Z_Malloc(width * 4, TAG_GRIDMESH, qfalse); + memcpy(grid->widthLodError, errorTable[0], width * 4); - grid->heightLodError = (float *)/*Hunk_Alloc*/ Z_Malloc( height * 4, TAG_GRIDMESH, qfalse ); - memcpy( grid->heightLodError, errorTable[1], height * 4 ); + grid->heightLodError = (float *)/*Hunk_Alloc*/ Z_Malloc(height * 4, TAG_GRIDMESH, qfalse); + memcpy(grid->heightLodError, errorTable[1], height * 4); grid->width = width; grid->height = height; grid->surfaceType = SF_GRID; - ClearBounds( grid->meshBounds[0], grid->meshBounds[1] ); - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - vert = &grid->verts[j*width+i]; + ClearBounds(grid->meshBounds[0], grid->meshBounds[1]); + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + vert = &grid->verts[j * width + i]; *vert = ctrl[j][i]; - AddPointToBounds( vert->xyz, grid->meshBounds[0], grid->meshBounds[1] ); + AddPointToBounds(vert->xyz, grid->meshBounds[0], grid->meshBounds[1]); } } // compute local origin and bounds - VectorAdd( grid->meshBounds[0], grid->meshBounds[1], grid->localOrigin ); - VectorScale( grid->localOrigin, 0.5f, grid->localOrigin ); - VectorSubtract( grid->meshBounds[0], grid->localOrigin, tmpVec ); - grid->meshRadius = VectorLength( tmpVec ); + VectorAdd(grid->meshBounds[0], grid->meshBounds[1], grid->localOrigin); + VectorScale(grid->localOrigin, 0.5f, grid->localOrigin); + VectorSubtract(grid->meshBounds[0], grid->localOrigin, tmpVec); + grid->meshRadius = VectorLength(tmpVec); - VectorCopy( grid->localOrigin, grid->lodOrigin ); + VectorCopy(grid->localOrigin, grid->lodOrigin); grid->lodRadius = grid->meshRadius; // return grid; @@ -344,7 +332,7 @@ srfGridMesh_t *R_CreateSurfaceGridMesh(int width, int height, R_FreeSurfaceGridMesh ================= */ -void R_FreeSurfaceGridMesh( srfGridMesh_t *grid ) { +void R_FreeSurfaceGridMesh(srfGridMesh_t *grid) { Z_Free(grid->widthLodError); Z_Free(grid->heightLodError); Z_Free(grid); @@ -355,95 +343,93 @@ void R_FreeSurfaceGridMesh( srfGridMesh_t *grid ) { R_SubdividePatchToGrid ================= */ -srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, - drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) { - int i, j, k, l; - drawVert_t prev, next, mid; - float len, maxLen; - int dir; - int t; - drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; - float errorTable[2][MAX_GRID_SIZE]; - - for ( i = 0 ; i < width ; i++ ) { - for ( j = 0 ; j < height ; j++ ) { - ctrl[j][i] = points[j*width+i]; +srfGridMesh_t *R_SubdividePatchToGrid(int width, int height, drawVert_t points[MAX_PATCH_SIZE * MAX_PATCH_SIZE]) { + int i, j, k, l; + drawVert_t prev, next, mid; + float len, maxLen; + int dir; + int t; + drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + + for (i = 0; i < width; i++) { + for (j = 0; j < height; j++) { + ctrl[j][i] = points[j * width + i]; } } - for ( dir = 0 ; dir < 2 ; dir++ ) { + for (dir = 0; dir < 2; dir++) { - for ( j = 0 ; j < MAX_GRID_SIZE ; j++ ) { + for (j = 0; j < MAX_GRID_SIZE; j++) { errorTable[dir][j] = 0; } // horizontal subdivisions - for ( j = 0 ; j + 2 < width ; j += 2 ) { + for (j = 0; j + 2 < width; j += 2) { // check subdivided midpoints against control points // FIXME: also check midpoints of adjacent patches against the control points // this would basically stitch all patches in the same LOD group together. maxLen = 0; - for ( i = 0 ; i < height ; i++ ) { - vec3_t midxyz; - vec3_t dir; - vec3_t projected; - float d; + for (i = 0; i < height; i++) { + vec3_t midxyz; + vec3_t dir; + vec3_t projected; + float d; // calculate the point on the curve - for ( l = 0 ; l < 3 ; l++ ) { - midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j+1].xyz[l] * 2 - + ctrl[i][j+2].xyz[l] ) * 0.25f; + for (l = 0; l < 3; l++) { + midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j + 1].xyz[l] * 2 + ctrl[i][j + 2].xyz[l]) * 0.25f; } // see how far off the line it is // using dist-from-line will not account for internal // texture warping, but it gives a lot less polygons than // dist-from-midpoint - VectorSubtract( midxyz, ctrl[i][j].xyz, midxyz ); - VectorSubtract( ctrl[i][j+2].xyz, ctrl[i][j].xyz, dir ); - VectorNormalize( dir ); + VectorSubtract(midxyz, ctrl[i][j].xyz, midxyz); + VectorSubtract(ctrl[i][j + 2].xyz, ctrl[i][j].xyz, dir); + VectorNormalize(dir); - d = DotProduct( midxyz, dir ); - VectorScale( dir, d, projected ); - VectorSubtract( midxyz, projected, midxyz); - len = VectorLengthSquared( midxyz ); // we will do the sqrt later + d = DotProduct(midxyz, dir); + VectorScale(dir, d, projected); + VectorSubtract(midxyz, projected, midxyz); + len = VectorLengthSquared(midxyz); // we will do the sqrt later - if ( len > maxLen ) { + if (len > maxLen) { maxLen = len; } } maxLen = sqrt(maxLen); // if all the points are on the lines, remove the entire columns - if ( maxLen < 0.1f ) { - errorTable[dir][j+1] = 999; + if (maxLen < 0.1f) { + errorTable[dir][j + 1] = 999; continue; } // see if we want to insert subdivided columns - if ( width + 2 > MAX_GRID_SIZE ) { - errorTable[dir][j+1] = 1.0f/maxLen; - continue; // can't subdivide any more + if (width + 2 > MAX_GRID_SIZE) { + errorTable[dir][j + 1] = 1.0f / maxLen; + continue; // can't subdivide any more } - if ( maxLen <= r_subdivisions->value ) { - errorTable[dir][j+1] = 1.0f/maxLen; - continue; // didn't need subdivision + if (maxLen <= r_subdivisions->value) { + errorTable[dir][j + 1] = 1.0f / maxLen; + continue; // didn't need subdivision } - errorTable[dir][j+2] = 1.0f/maxLen; + errorTable[dir][j + 2] = 1.0f / maxLen; // insert two columns and replace the peak width += 2; - for ( i = 0 ; i < height ; i++ ) { - LerpDrawVert( &ctrl[i][j], &ctrl[i][j+1], &prev ); - LerpDrawVert( &ctrl[i][j+1], &ctrl[i][j+2], &next ); - LerpDrawVert( &prev, &next, &mid ); + for (i = 0; i < height; i++) { + LerpDrawVert(&ctrl[i][j], &ctrl[i][j + 1], &prev); + LerpDrawVert(&ctrl[i][j + 1], &ctrl[i][j + 2], &next); + LerpDrawVert(&prev, &next, &mid); - for ( k = width - 1 ; k > j + 3 ; k-- ) { - ctrl[i][k] = ctrl[i][k-2]; + for (k = width - 1; k > j + 3; k--) { + ctrl[i][k] = ctrl[i][k - 2]; } ctrl[i][j + 1] = prev; ctrl[i][j + 2] = mid; @@ -452,42 +438,40 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, // back up and recheck this set again, it may need more subdivision j -= 2; - } - Transpose( width, height, ctrl ); + Transpose(width, height, ctrl); t = width; width = height; height = t; } - // put all the aproximating points on the curve - PutPointsOnCurve( ctrl, width, height ); + PutPointsOnCurve(ctrl, width, height); // cull out any rows or columns that are colinear - for ( i = 1 ; i < width-1 ; i++ ) { - if ( errorTable[0][i] != 999 ) { + for (i = 1; i < width - 1; i++) { + if (errorTable[0][i] != 999) { continue; } - for ( j = i+1 ; j < width ; j++ ) { - for ( k = 0 ; k < height ; k++ ) { - ctrl[k][j-1] = ctrl[k][j]; + for (j = i + 1; j < width; j++) { + for (k = 0; k < height; k++) { + ctrl[k][j - 1] = ctrl[k][j]; } - errorTable[0][j-1] = errorTable[0][j]; + errorTable[0][j - 1] = errorTable[0][j]; } width--; } - for ( i = 1 ; i < height-1 ; i++ ) { - if ( errorTable[1][i] != 999 ) { + for (i = 1; i < height - 1; i++) { + if (errorTable[1][i] != 999) { continue; } - for ( j = i+1 ; j < height ; j++ ) { - for ( k = 0 ; k < width ; k++ ) { - ctrl[j-1][k] = ctrl[j][k]; + for (j = i + 1; j < height; j++) { + for (k = 0; k < width; k++) { + ctrl[j - 1][k] = ctrl[j][k]; } - errorTable[1][j-1] = errorTable[1][j]; + errorTable[1][j - 1] = errorTable[1][j]; } height--; } @@ -496,20 +480,20 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, // flip for longest tristrips as an optimization // the results should be visually identical with or // without this step - if ( height > width ) { - Transpose( width, height, ctrl ); - InvertErrorTable( errorTable, width, height ); + if (height > width) { + Transpose(width, height, ctrl); + InvertErrorTable(errorTable, width, height); t = width; width = height; height = t; - InvertCtrl( width, height, ctrl ); + InvertCtrl(width, height, ctrl); } #endif // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); - return R_CreateSurfaceGridMesh( width, height, ctrl, errorTable ); + return R_CreateSurfaceGridMesh(width, height, ctrl, errorTable); } /* @@ -517,7 +501,7 @@ srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, R_GridInsertColumn =============== */ -srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec3_t point, float loderror ) { +srfGridMesh_t *R_GridInsertColumn(srfGridMesh_t *grid, int column, int row, vec3_t point, float loderror) { int i, j; int width, height, oldwidth; drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; @@ -532,9 +516,9 @@ srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec height = grid->height; for (i = 0; i < width; i++) { if (i == column) { - //insert new column + // insert new column for (j = 0; j < grid->height; j++) { - LerpDrawVert( &grid->verts[j * grid->width + i-1], &grid->verts[j * grid->width + i], &ctrl[j][i] ); + LerpDrawVert(&grid->verts[j * grid->width + i - 1], &grid->verts[j * grid->width + i], &ctrl[j][i]); if (j == row) VectorCopy(point, ctrl[j][i].xyz); } @@ -551,16 +535,16 @@ srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec errorTable[1][j] = grid->heightLodError[j]; } // put all the aproximating points on the curve - //PutPointsOnCurve( ctrl, width, height ); + // PutPointsOnCurve( ctrl, width, height ); // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); VectorCopy(grid->lodOrigin, lodOrigin); lodRadius = grid->lodRadius; // free the old grid R_FreeSurfaceGridMesh(grid); // create a new grid - grid = R_CreateSurfaceGridMesh( width, height, ctrl, errorTable ); + grid = R_CreateSurfaceGridMesh(width, height, ctrl, errorTable); grid->lodRadius = lodRadius; VectorCopy(lodOrigin, grid->lodOrigin); return grid; @@ -571,7 +555,7 @@ srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec R_GridInsertRow =============== */ -srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t point, float loderror ) { +srfGridMesh_t *R_GridInsertRow(srfGridMesh_t *grid, int row, int column, vec3_t point, float loderror) { int i, j; int width, height, oldheight; drawVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; @@ -586,9 +570,9 @@ srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t return NULL; for (i = 0; i < height; i++) { if (i == row) { - //insert new row + // insert new row for (j = 0; j < grid->width; j++) { - LerpDrawVert( &grid->verts[(i-1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j] ); + LerpDrawVert(&grid->verts[(i - 1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j]); if (j == column) VectorCopy(point, ctrl[i][j].xyz); } @@ -605,16 +589,16 @@ srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t errorTable[0][j] = grid->widthLodError[j]; } // put all the aproximating points on the curve - //PutPointsOnCurve( ctrl, width, height ); + // PutPointsOnCurve( ctrl, width, height ); // calculate normals - MakeMeshNormals( width, height, ctrl ); + MakeMeshNormals(width, height, ctrl); VectorCopy(grid->lodOrigin, lodOrigin); lodRadius = grid->lodRadius; // free the old grid R_FreeSurfaceGridMesh(grid); // create a new grid - grid = R_CreateSurfaceGridMesh( width, height, ctrl, errorTable ); + grid = R_CreateSurfaceGridMesh(width, height, ctrl, errorTable); grid->lodRadius = lodRadius; VectorCopy(lodOrigin, grid->lodOrigin); return grid; diff --git a/codemp/rd-vanilla/tr_decals.cpp b/codemp/rd-vanilla/tr_decals.cpp index 6e52131211..37d0f9b952 100644 --- a/codemp/rd-vanilla/tr_decals.cpp +++ b/codemp/rd-vanilla/tr_decals.cpp @@ -23,34 +23,28 @@ along with this program; if not, see . #include "tr_local.h" -#define MAX_VERTS_ON_DECAL_POLY 10 -#define MAX_DECAL_POLYS 500 - -typedef struct decalPoly_s -{ - int time; - int fadetime; - qhandle_t shader; - float color[4]; - poly_t poly; - polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; +#define MAX_VERTS_ON_DECAL_POLY 10 +#define MAX_DECAL_POLYS 500 + +typedef struct decalPoly_s { + int time; + int fadetime; + qhandle_t shader; + float color[4]; + poly_t poly; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; } decalPoly_t; -enum -{ - DECALPOLY_TYPE_NORMAL, - DECALPOLY_TYPE_FADE, - DECALPOLY_TYPE_MAX -}; +enum { DECALPOLY_TYPE_NORMAL, DECALPOLY_TYPE_FADE, DECALPOLY_TYPE_MAX }; -#define DECAL_FADE_TIME 1000 +#define DECAL_FADE_TIME 1000 -decalPoly_t* RE_AllocDecal( int type ); +decalPoly_t *RE_AllocDecal(int type); -static decalPoly_t re_decalPolys[DECALPOLY_TYPE_MAX][MAX_DECAL_POLYS]; +static decalPoly_t re_decalPolys[DECALPOLY_TYPE_MAX][MAX_DECAL_POLYS]; -static int re_decalPolyHead[DECALPOLY_TYPE_MAX]; -static int re_decalPolyTotal[DECALPOLY_TYPE_MAX]; +static int re_decalPolyHead[DECALPOLY_TYPE_MAX]; +static int re_decalPolyTotal[DECALPOLY_TYPE_MAX]; /* =================== @@ -59,26 +53,24 @@ RE_ClearDecals This is called to remove all decals from the world =================== */ -void RE_ClearDecals( void ) { - memset( re_decalPolys, 0, sizeof(re_decalPolys) ); - memset( re_decalPolyHead, 0, sizeof(re_decalPolyHead) ); - memset( re_decalPolyTotal, 0, sizeof(re_decalPolyTotal) ); +void RE_ClearDecals(void) { + memset(re_decalPolys, 0, sizeof(re_decalPolys)); + memset(re_decalPolyHead, 0, sizeof(re_decalPolyHead)); + memset(re_decalPolyTotal, 0, sizeof(re_decalPolyTotal)); } -void R_InitDecals( void ) { - RE_ClearDecals(); -} +void R_InitDecals(void) { RE_ClearDecals(); } -void RE_FreeDecal( int type, int index ) { - if ( !re_decalPolys[type][index].time ) +void RE_FreeDecal(int type, int index) { + if (!re_decalPolys[type][index].time) return; - if ( type == DECALPOLY_TYPE_NORMAL ) { - decalPoly_t* fade; + if (type == DECALPOLY_TYPE_NORMAL) { + decalPoly_t *fade; - fade = RE_AllocDecal( DECALPOLY_TYPE_FADE ); + fade = RE_AllocDecal(DECALPOLY_TYPE_FADE); - memcpy( fade, &re_decalPolys[type][index], sizeof( decalPoly_t ) ); + memcpy(fade, &re_decalPolys[type][index], sizeof(decalPoly_t)); fade->time = tr.refdef.time; fade->fadetime = tr.refdef.time + DECAL_FADE_TIME; @@ -96,48 +88,47 @@ RE_AllocDecal Will allways succeed, even if it requires freeing an old active mark =================== */ -decalPoly_t* RE_AllocDecal( int type ) { - decalPoly_t *le; +decalPoly_t *RE_AllocDecal(int type) { + decalPoly_t *le; // See if the cvar changed - if ( re_decalPolyTotal[type] > r_markcount->integer ) + if (re_decalPolyTotal[type] > r_markcount->integer) RE_ClearDecals(); le = &re_decalPolys[type][re_decalPolyHead[type]]; // If it has no time its the first occasion its been used - if ( le->time ) { - if ( le->time != tr.refdef.time ) { + if (le->time) { + if (le->time != tr.refdef.time) { int i = re_decalPolyHead[type]; // since we are killing one that existed before, make sure we // kill all the other marks that belong to the group do { i++; - if ( i >= r_markcount->integer ) + if (i >= r_markcount->integer) i = 0; // Break out on the first one thats not part of the group - if ( re_decalPolys[type][i].time != le->time ) + if (re_decalPolys[type][i].time != le->time) break; - RE_FreeDecal ( type, i ); - } while ( i != re_decalPolyHead[type] ); + RE_FreeDecal(type, i); + } while (i != re_decalPolyHead[type]); - RE_FreeDecal( type, re_decalPolyHead[type] ); - } - else - RE_FreeDecal( type, re_decalPolyHead[type] ); + RE_FreeDecal(type, re_decalPolyHead[type]); + } else + RE_FreeDecal(type, re_decalPolyHead[type]); } - memset( le, 0, sizeof(decalPoly_t) ); + memset(le, 0, sizeof(decalPoly_t)); le->time = tr.refdef.time; re_decalPolyTotal[type]++; // Move on to the next decal poly and wrap around if need be re_decalPolyHead[type]++; - if ( re_decalPolyHead[type] >= r_markcount->integer ) + if (re_decalPolyHead[type] >= r_markcount->integer) re_decalPolyHead[type] = 0; return le; @@ -154,40 +145,39 @@ temporary marks will not be stored or randomly oriented, but immediately passed to the renderer. ================= */ -#define MAX_DECAL_FRAGMENTS 128 -#define MAX_DECAL_POINTS 384 - -void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, qboolean alphaFade, float radius, qboolean temporary ) -{ - matrix3_t axis; - float texCoordScale; - vec3_t originalPoints[4]; - byte colors[4]; - int i, j; - int numFragments; - markFragment_t markFragments[MAX_DECAL_FRAGMENTS], *mf; - vec3_t markPoints[MAX_DECAL_POINTS]; - vec3_t projection; +#define MAX_DECAL_FRAGMENTS 128 +#define MAX_DECAL_POINTS 384 + +void RE_AddDecalToScene(qhandle_t decalShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, + qboolean alphaFade, float radius, qboolean temporary) { + matrix3_t axis; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j; + int numFragments; + markFragment_t markFragments[MAX_DECAL_FRAGMENTS], *mf; + vec3_t markPoints[MAX_DECAL_POINTS]; + vec3_t projection; assert(decalShader); - if ( r_markcount->integer <= 0 && !temporary ) + if (r_markcount->integer <= 0 && !temporary) return; - if ( radius <= 0 ) - Com_Error( ERR_FATAL, "RE_AddDecalToScene: called with <= 0 radius" ); + if (radius <= 0) + Com_Error(ERR_FATAL, "RE_AddDecalToScene: called with <= 0 radius"); // create the texture axis - VectorNormalize2( dir, axis[0] ); - PerpendicularVector( axis[1], axis[0] ); - RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); - CrossProduct( axis[0], axis[2], axis[1] ); + VectorNormalize2(dir, axis[0]); + PerpendicularVector(axis[1], axis[0]); + RotatePointAroundVector(axis[2], axis[0], axis[1], orientation); + CrossProduct(axis[0], axis[2], axis[1]); texCoordScale = 0.5 * 1.0 / radius; // create the full polygon - for ( i = 0 ; i < 3 ; i++ ) - { + for (i = 0; i < 3; i++) { originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; @@ -195,50 +185,45 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ } // get the fragments - VectorScale( dir, -20, projection ); - numFragments = R_MarkFragments( 4, (const vec3_t*)originalPoints, - projection, MAX_DECAL_POINTS, markPoints[0], - MAX_DECAL_FRAGMENTS, markFragments ); + VectorScale(dir, -20, projection); + numFragments = R_MarkFragments(4, (const vec3_t *)originalPoints, projection, MAX_DECAL_POINTS, markPoints[0], MAX_DECAL_FRAGMENTS, markFragments); colors[0] = red * 255; colors[1] = green * 255; colors[2] = blue * 255; colors[3] = alpha * 255; - for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) - { - polyVert_t *v; - polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; - decalPoly_t *decal; + for (i = 0, mf = markFragments; i < numFragments; i++, mf++) { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; + decalPoly_t *decal; // we have an upper limit on the complexity of polygons // that we store persistantly - if ( mf->numPoints > MAX_VERTS_ON_DECAL_POLY ) + if (mf->numPoints > MAX_VERTS_ON_DECAL_POLY) mf->numPoints = MAX_VERTS_ON_DECAL_POLY; - for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) - { - vec3_t delta; + for (j = 0, v = verts; j < mf->numPoints; j++, v++) { + vec3_t delta; - VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + VectorCopy(markPoints[mf->firstPoint + j], v->xyz); - VectorSubtract( v->xyz, origin, delta ); - v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale; - v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale; + VectorSubtract(v->xyz, origin, delta); + v->st[0] = 0.5 + DotProduct(delta, axis[1]) * texCoordScale; + v->st[1] = 0.5 + DotProduct(delta, axis[2]) * texCoordScale; - for ( int k=0; k<4; k++ ) + for (int k = 0; k < 4; k++) v->modulate[k] = colors[k]; } // if it is a temporary (shadow) mark, add it immediately and forget about it - if ( temporary ) - { - RE_AddPolyToScene( decalShader, mf->numPoints, verts, 1 ); + if (temporary) { + RE_AddPolyToScene(decalShader, mf->numPoints, verts, 1); continue; } // otherwise save it persistantly - decal = RE_AllocDecal( DECALPOLY_TYPE_NORMAL ); + decal = RE_AllocDecal(DECALPOLY_TYPE_NORMAL); decal->time = tr.refdef.time; decal->shader = decalShader; decal->poly.numVerts = mf->numPoints; @@ -246,7 +231,7 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ decal->color[1] = green; decal->color[2] = blue; decal->color[3] = alpha; - memcpy( decal->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + memcpy(decal->verts, verts, mf->numPoints * sizeof(verts[0])); } } @@ -255,69 +240,56 @@ void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_ R_AddDecals =============== */ -void R_AddDecals( void ) -{ - int decalPoly; - int type; - static int lastMarkCount = -1; - - if ( r_markcount->integer != lastMarkCount ) { - if ( lastMarkCount != -1 ) +void R_AddDecals(void) { + int decalPoly; + int type; + static int lastMarkCount = -1; + + if (r_markcount->integer != lastMarkCount) { + if (lastMarkCount != -1) RE_ClearDecals(); lastMarkCount = r_markcount->integer; } - if ( r_markcount->integer <= 0 ) + if (r_markcount->integer <= 0) return; - for ( type = DECALPOLY_TYPE_NORMAL; type < DECALPOLY_TYPE_MAX; type ++ ) - { + for (type = DECALPOLY_TYPE_NORMAL; type < DECALPOLY_TYPE_MAX; type++) { decalPoly = re_decalPolyHead[type]; - do - { - decalPoly_t* p = &re_decalPolys[type][decalPoly]; + do { + decalPoly_t *p = &re_decalPolys[type][decalPoly]; - if ( p->time ) - { - if ( p->fadetime ) - { + if (p->time) { + if (p->fadetime) { int t; // fade all marks out with time t = tr.refdef.time - p->time; - if ( t < DECAL_FADE_TIME ) - { + if (t < DECAL_FADE_TIME) { float fade; - int j; + int j; fade = 255.0f * (1.0f - ((float)t / DECAL_FADE_TIME)); - for ( j = 0 ; j < p->poly.numVerts ; j++ ) - { + for (j = 0; j < p->poly.numVerts; j++) { p->verts[j].modulate[3] = fade; } - RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); + RE_AddPolyToScene(p->shader, p->poly.numVerts, p->verts, 1); + } else { + RE_FreeDecal(type, decalPoly); } - else - { - RE_FreeDecal ( type, decalPoly ); - } - } - else - { - RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); + } else { + RE_AddPolyToScene(p->shader, p->poly.numVerts, p->verts, 1); } } decalPoly++; - if ( decalPoly >= r_markcount->integer ) - { + if (decalPoly >= r_markcount->integer) { decalPoly = 0; } - } - while ( decalPoly != re_decalPolyHead[type] ); + } while (decalPoly != re_decalPolyHead[type]); } } diff --git a/codemp/rd-vanilla/tr_ghoul2.cpp b/codemp/rd-vanilla/tr_ghoul2.cpp index f4ca58b8d6..e946a8f2cd 100644 --- a/codemp/rd-vanilla/tr_ghoul2.cpp +++ b/codemp/rd-vanilla/tr_ghoul2.cpp @@ -20,7 +20,7 @@ along with this program; if not, see . =========================================================================== */ -#include "client/client.h" //FIXME!! EVIL - just include the definitions needed +#include "client/client.h" //FIXME!! EVIL - just include the definitions needed #include "tr_local.h" #include "qcommon/matcomp.h" #include "qcommon/qcommon.h" @@ -32,9 +32,9 @@ along with this program; if not, see . #include "qcommon/disablewarnings.h" -#define LL(x) x=LittleLong(x) -#define LS(x) x=LittleShort(x) -#define LF(x) x=LittleFloat(x) +#define LL(x) x = LittleLong(x) +#define LS(x) x = LittleShort(x) +#define LF(x) x = LittleFloat(x) #ifdef G2_PERFORMANCE_ANALYSIS #include "qcommon/timing.h" @@ -61,8 +61,7 @@ int G2Time_RB_SurfaceGhoul = 0; int G2Time_G2_SetupModelPointers = 0; int G2Time_PreciseFrame = 0; -void G2Time_ResetTimers(void) -{ +void G2Time_ResetTimers(void) { G2Time_RenderSurfaces = 0; G2Time_R_AddGHOULSurfaces = 0; G2Time_G2_TransformGhoulBones = 0; @@ -75,39 +74,33 @@ void G2Time_ResetTimers(void) G2PerformanceCounter_G2_TransformGhoulBones = 0; } -void G2Time_ReportTimers(void) -{ - ri.Printf( PRINT_ALL, "\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: %i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: %i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", - G2Time_RenderSurfaces, - G2Time_R_AddGHOULSurfaces, - G2Time_G2_TransformGhoulBones, - G2Time_G2_ProcessGeneratedSurfaceBolts, - G2Time_ProcessModelBoltSurfaces, - G2Time_G2_ConstructGhoulSkeleton, - G2Time_RB_SurfaceGhoul, - G2Time_G2_SetupModelPointers, - G2Time_PreciseFrame, - G2PerformanceCounter_G2_TransformGhoulBones - ); +void G2Time_ReportTimers(void) { + ri.Printf(PRINT_ALL, + "\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: " + "%i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: " + "%i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", + G2Time_RenderSurfaces, G2Time_R_AddGHOULSurfaces, G2Time_G2_TransformGhoulBones, G2Time_G2_ProcessGeneratedSurfaceBolts, + G2Time_ProcessModelBoltSurfaces, G2Time_G2_ConstructGhoulSkeleton, G2Time_RB_SurfaceGhoul, G2Time_G2_SetupModelPointers, G2Time_PreciseFrame, + G2PerformanceCounter_G2_TransformGhoulBones); } #endif -//rww - RAGDOLL_BEGIN +// rww - RAGDOLL_BEGIN #ifdef __linux__ #include #else #include #endif -//rww - RAGDOLL_END +// rww - RAGDOLL_END -bool HackadelicOnClient=false; // means this is a render traversal +bool HackadelicOnClient = false; // means this is a render traversal qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); -extern cvar_t *r_Ghoul2AnimSmooth; -extern cvar_t *r_Ghoul2UnSqashAfterSmooth; +extern cvar_t *r_Ghoul2AnimSmooth; +extern cvar_t *r_Ghoul2UnSqashAfterSmooth; #if 0 static inline int G2_Find_Bone_ByNum(const model_t *mod, boneInfo_v &blist, const int boneNum) @@ -127,117 +120,89 @@ static inline int G2_Find_Bone_ByNum(const model_t *mod, boneInfo_v &blist, cons } #endif -const static mdxaBone_t identityMatrix = -{ - { - { 0.0f, -1.0f, 0.0f, 0.0f }, - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } -}; +const static mdxaBone_t identityMatrix = {{{0.0f, -1.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; // I hate doing this, but this is the simplest way to get this into the routines it needs to be -mdxaBone_t worldMatrix; -mdxaBone_t worldMatrixInv; +mdxaBone_t worldMatrix; +mdxaBone_t worldMatrixInv; #ifdef _G2_GORE -qhandle_t goreShader=-1; +qhandle_t goreShader = -1; #endif -class CConstructBoneList -{ -public: - int surfaceNum; - int *boneUsedList; - surfaceInfo_v &rootSList; - model_t *currentModel; - boneInfo_v &boneList; - - CConstructBoneList( - int initsurfaceNum, - int *initboneUsedList, - surfaceInfo_v &initrootSList, - model_t *initcurrentModel, - boneInfo_v &initboneList): +class CConstructBoneList { + public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; - surfaceNum(initsurfaceNum), - boneUsedList(initboneUsedList), - rootSList(initrootSList), - currentModel(initcurrentModel), - boneList(initboneList) { } + CConstructBoneList(int initsurfaceNum, int *initboneUsedList, surfaceInfo_v &initrootSList, model_t *initcurrentModel, boneInfo_v &initboneList) + : + surfaceNum(initsurfaceNum), boneUsedList(initboneUsedList), rootSList(initrootSList), currentModel(initcurrentModel), boneList(initboneList) {} }; -class CTransformBone -{ -public: - int touch; // for minimal recalculation - //rww - RAGDOLL_BEGIN - int touchRender; - //rww - RAGDOLL_END - mdxaBone_t boneMatrix; //final matrix - int parent; // only set once - - CTransformBone() - { - touch=0; - //rww - RAGDOLL_BEGIN +class CTransformBone { + public: + int touch; // for minimal recalculation + // rww - RAGDOLL_BEGIN + int touchRender; + // rww - RAGDOLL_END + mdxaBone_t boneMatrix; // final matrix + int parent; // only set once + + CTransformBone() { + touch = 0; + // rww - RAGDOLL_BEGIN touchRender = 0; - //rww - RAGDOLL_END + // rww - RAGDOLL_END } - }; -struct SBoneCalc -{ - int newFrame; - int currentFrame; - float backlerp; - float blendFrame; - int blendOldFrame; - bool blendMode; - float blendLerp; +struct SBoneCalc { + int newFrame; + int currentFrame; + float backlerp; + float blendFrame; + int blendOldFrame; + bool blendMode; + float blendLerp; }; class CBoneCache; -void G2_TransformBone(int index,CBoneCache &CB); +void G2_TransformBone(int index, CBoneCache &CB); -class CBoneCache -{ - void SetRenderMatrix(CTransformBone *bone) { - } +class CBoneCache { + void SetRenderMatrix(CTransformBone *bone) {} - void EvalLow(int index) - { - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { + void EvalLow(int index) { + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { // need to evaluate the bone - assert((mFinalBones[index].parent>=0&&mFinalBones[index].parent<(int)mFinalBones.size())||(index==0&&mFinalBones[index].parent==-1)); - if (mFinalBones[index].parent>=0) - { + assert((mFinalBones[index].parent >= 0 && mFinalBones[index].parent < (int)mFinalBones.size()) || (index == 0 && mFinalBones[index].parent == -1)); + if (mFinalBones[index].parent >= 0) { EvalLow(mFinalBones[index].parent); // make sure parent is evaluated - SBoneCalc &par=mBones[mFinalBones[index].parent]; - mBones[index].newFrame=par.newFrame; - mBones[index].currentFrame=par.currentFrame; - mBones[index].backlerp=par.backlerp; - mBones[index].blendFrame=par.blendFrame; - mBones[index].blendOldFrame=par.blendOldFrame; - mBones[index].blendMode=par.blendMode; - mBones[index].blendLerp=par.blendLerp; + SBoneCalc &par = mBones[mFinalBones[index].parent]; + mBones[index].newFrame = par.newFrame; + mBones[index].currentFrame = par.currentFrame; + mBones[index].backlerp = par.backlerp; + mBones[index].blendFrame = par.blendFrame; + mBones[index].blendOldFrame = par.blendOldFrame; + mBones[index].blendMode = par.blendMode; + mBones[index].blendLerp = par.blendLerp; } - G2_TransformBone(index,*this); - mFinalBones[index].touch=mCurrentTouch; + G2_TransformBone(index, *this); + mFinalBones[index].touch = mCurrentTouch; } } -//rww - RAGDOLL_BEGIN - void SmoothLow(int index) - { - if (mSmoothBones[index].touch==mLastTouch) - { + // rww - RAGDOLL_BEGIN + void SmoothLow(int index) { + if (mSmoothBones[index].touch == mLastTouch) { int i; - float *oldM=&mSmoothBones[index].boneMatrix.matrix[0][0]; - float *newM=&mFinalBones[index].boneMatrix.matrix[0][0]; -#if 0 //this is just too slow. I need a better way. + float *oldM = &mSmoothBones[index].boneMatrix.matrix[0][0]; + float *newM = &mFinalBones[index].boneMatrix.matrix[0][0]; +#if 0 // this is just too slow. I need a better way. static float smoothFactor; smoothFactor = mSmoothFactor; @@ -277,120 +242,107 @@ class CBoneCache } #endif - for (i=0;i<12;i++,oldM++,newM++) - { - *oldM=mSmoothFactor*(*oldM-*newM)+*newM; + for (i = 0; i < 12; i++, oldM++, newM++) { + *oldM = mSmoothFactor * (*oldM - *newM) + *newM; } - } - else - { - memcpy(&mSmoothBones[index].boneMatrix,&mFinalBones[index].boneMatrix,sizeof(mdxaBone_t)); + } else { + memcpy(&mSmoothBones[index].boneMatrix, &mFinalBones[index].boneMatrix, sizeof(mdxaBone_t)); } mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[index]); mdxaBone_t tempMatrix; - Multiply_3x4Matrix(&tempMatrix,&mSmoothBones[index].boneMatrix, &skel->BasePoseMat); + Multiply_3x4Matrix(&tempMatrix, &mSmoothBones[index].boneMatrix, &skel->BasePoseMat); float maxl; - maxl=VectorLength(&skel->BasePoseMat.matrix[0][0]); + maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[0][0]); VectorNormalize(&tempMatrix.matrix[1][0]); VectorNormalize(&tempMatrix.matrix[2][0]); - VectorScale(&tempMatrix.matrix[0][0],maxl,&tempMatrix.matrix[0][0]); - VectorScale(&tempMatrix.matrix[1][0],maxl,&tempMatrix.matrix[1][0]); - VectorScale(&tempMatrix.matrix[2][0],maxl,&tempMatrix.matrix[2][0]); - Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); - mSmoothBones[index].touch=mCurrentTouch; + VectorScale(&tempMatrix.matrix[0][0], maxl, &tempMatrix.matrix[0][0]); + VectorScale(&tempMatrix.matrix[1][0], maxl, &tempMatrix.matrix[1][0]); + VectorScale(&tempMatrix.matrix[2][0], maxl, &tempMatrix.matrix[2][0]); + Multiply_3x4Matrix(&mSmoothBones[index].boneMatrix, &tempMatrix, &skel->BasePoseMatInv); + mSmoothBones[index].touch = mCurrentTouch; #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -//rww - RAGDOLL_END -public: - int frameSize; - const mdxaHeader_t *header; - const model_t *mod; + // rww - RAGDOLL_END + public: + int frameSize; + const mdxaHeader_t *header; + const model_t *mod; // these are split for better cpu cache behavior std::vector mBones; std::vector mFinalBones; std::vector mSmoothBones; // for render smoothing - //vector mSkels; + // vector mSkels; - boneInfo_v *rootBoneList; - mdxaBone_t rootMatrix; - int incomingTime; + boneInfo_v *rootBoneList; + mdxaBone_t rootMatrix; + int incomingTime; - int mCurrentTouch; - //rww - RAGDOLL_BEGIN - int mCurrentTouchRender; - int mLastTouch; - int mLastLastTouch; - //rww - RAGDOLL_END + int mCurrentTouch; + // rww - RAGDOLL_BEGIN + int mCurrentTouchRender; + int mLastTouch; + int mLastLastTouch; + // rww - RAGDOLL_END // for render smoothing - bool mSmoothingActive; - bool mUnsquash; - float mSmoothFactor; + bool mSmoothingActive; + bool mUnsquash; + float mSmoothFactor; - CBoneCache(const model_t *amod,const mdxaHeader_t *aheader) : - header(aheader), - mod(amod) - { + CBoneCache(const model_t *amod, const mdxaHeader_t *aheader) : header(aheader), mod(amod) { assert(amod); assert(aheader); - mSmoothingActive=false; - mUnsquash=false; - mSmoothFactor=0.0f; + mSmoothingActive = false; + mUnsquash = false; + mSmoothFactor = 0.0f; - int numBones=header->numBones; + int numBones = header->numBones; mBones.resize(numBones); mFinalBones.resize(numBones); mSmoothBones.resize(numBones); -// mSkels.resize(numBones); - //rww - removed mSkels + // mSkels.resize(numBones); + // rww - removed mSkels mdxaSkelOffsets_t *offsets; - mdxaSkel_t *skel; + mdxaSkel_t *skel; offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); int i; - for (i=0;ioffsets[i]); - //mSkels[i]=skel; - //ditto - mFinalBones[i].parent=skel->parent; + // mSkels[i]=skel; + // ditto + mFinalBones[i].parent = skel->parent; } - mCurrentTouch=3; -//rww - RAGDOLL_BEGIN - mLastTouch=2; - mLastLastTouch=1; -//rww - RAGDOLL_END + mCurrentTouch = 3; + // rww - RAGDOLL_BEGIN + mLastTouch = 2; + mLastLastTouch = 1; + // rww - RAGDOLL_END } - SBoneCalc &Root() - { + SBoneCalc &Root() { assert(mBones.size()); return mBones[0]; } - const mdxaBone_t &EvalUnsmooth(int index) - { + const mdxaBone_t &EvalUnsmooth(int index) { EvalLow(index); - if (mSmoothingActive&&mSmoothBones[index].touch) - { + if (mSmoothingActive && mSmoothBones[index].touch) { return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - const mdxaBone_t &Eval(int index) - { + const mdxaBone_t &Eval(int index) { /* bool wasEval=EvalLow(index); if (mSmoothingActive) @@ -445,54 +397,45 @@ class CBoneCache return mFinalBones[index].boneMatrix; */ - //Hey, this is what sof2 does. Let's try it out. - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { + // Hey, this is what sof2 does. Let's try it out. + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { EvalLow(index); } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_BEGIN - const inline mdxaBone_t &EvalRender(int index) - { - assert(index>=0&&index<(int)mBones.size()); - if (mFinalBones[index].touch!=mCurrentTouch) - { - mFinalBones[index].touchRender=mCurrentTouchRender; + // rww - RAGDOLL_BEGIN + const inline mdxaBone_t &EvalRender(int index) { + assert(index >= 0 && index < (int)mBones.size()); + if (mFinalBones[index].touch != mCurrentTouch) { + mFinalBones[index].touchRender = mCurrentTouchRender; EvalLow(index); } - if (mSmoothingActive) - { - if (mSmoothBones[index].touch!=mCurrentTouch) - { + if (mSmoothingActive) { + if (mSmoothBones[index].touch != mCurrentTouch) { SmoothLow(index); } return mSmoothBones[index].boneMatrix; } return mFinalBones[index].boneMatrix; } - //rww - RAGDOLL_END - //rww - RAGDOLL_BEGIN - bool WasRendered(int index) - { - assert(index>=0&&index<(int)mBones.size()); - return mFinalBones[index].touchRender==mCurrentTouchRender; + // rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + bool WasRendered(int index) { + assert(index >= 0 && index < (int)mBones.size()); + return mFinalBones[index].touchRender == mCurrentTouchRender; } - int GetParent(int index) - { - if (index==0) - { + int GetParent(int index) { + if (index == 0) { return -1; } - assert(index>=0&&index<(int)mBones.size()); + assert(index >= 0 && index < (int)mBones.size()); return mFinalBones[index].parent; } - //rww - RAGDOLL_END + // rww - RAGDOLL_END }; -void RemoveBoneCache(CBoneCache *boneCache) -{ +void RemoveBoneCache(CBoneCache *boneCache) { #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations -= sizeof(*boneCache); #endif @@ -501,116 +444,98 @@ void RemoveBoneCache(CBoneCache *boneCache) } #ifdef _G2_LISTEN_SERVER_OPT -void CopyBoneCache(CBoneCache *to, CBoneCache *from) -{ - memcpy(to, from, sizeof(CBoneCache)); -} +void CopyBoneCache(CBoneCache *to, CBoneCache *from) { memcpy(to, from, sizeof(CBoneCache)); } #endif -const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache) -{ +const mdxaBone_t &EvalBoneCache(int index, CBoneCache *boneCache) { assert(boneCache); return boneCache->Eval(index); } -//rww - RAGDOLL_BEGIN -const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) -{ - if (!ghoul2.mBoneCache) - { +// rww - RAGDOLL_BEGIN +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) { + if (!ghoul2.mBoneCache) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.header; } -int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep) -{ +int G2_GetBoneDependents(CGhoul2Info &ghoul2, int boneNum, int *tempDependents, int maxDep) { // fixme, these should be precomputed - if (!ghoul2.mBoneCache||!maxDep) - { + if (!ghoul2.mBoneCache || !maxDep) { return 0; } - CBoneCache &boneCache=*ghoul2.mBoneCache; - mdxaSkel_t *skel; + CBoneCache &boneCache = *ghoul2.mBoneCache; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); int i; - int ret=0; - for (i=0;inumChildren;i++) - { - if (!maxDep) - { + int ret = 0; + for (i = 0; i < skel->numChildren; i++) { + if (!maxDep) { return i; // number added } - *tempDependents=skel->children[i]; - assert(*tempDependents>0&&*tempDependentsnumBones); + *tempDependents = skel->children[i]; + assert(*tempDependents > 0 && *tempDependents < boneCache.header->numBones); maxDep--; tempDependents++; ret++; } - for (i=0;inumChildren;i++) - { - int num=G2_GetBoneDependents(ghoul2,skel->children[i],tempDependents,maxDep); - tempDependents+=num; - ret+=num; - maxDep-=num; - assert(maxDep>=0); - if (!maxDep) - { + for (i = 0; i < skel->numChildren; i++) { + int num = G2_GetBoneDependents(ghoul2, skel->children[i], tempDependents, maxDep); + tempDependents += num; + ret += num; + maxDep -= num; + assert(maxDep >= 0); + if (!maxDep) { break; } } return ret; } -bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) -{ - if (!ghoul2.mBoneCache) - { +bool G2_WasBoneRendered(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return false; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; return boneCache.WasRendered(boneNum); } -void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { +void G2_GetBoneBasepose(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; } -char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) -{ - if (!ghoul2.mBoneCache) - { +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) { + if (!ghoul2.mBoneCache) { return NULL; } - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); @@ -618,185 +543,150 @@ char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) return skel->name; } -void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) -{ +void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale) { assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&retMatrix, &boneMatrix, &skel->BasePoseMat); - if (scale[0]) - { + if (scale[0]) { retMatrix.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { retMatrix.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { retMatrix.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&retMatrix.matrix[0]); - VectorNormalize((float*)&retMatrix.matrix[1]); - VectorNormalize((float*)&retMatrix.matrix[2]); + VectorNormalize((float *)&retMatrix.matrix[0]); + VectorNormalize((float *)&retMatrix.matrix[1]); + VectorNormalize((float *)&retMatrix.matrix[2]); } -void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, mdxaBone_t *&retBaseposeInv) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); return; } mdxaBone_t bolt; assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); - mdxaSkel_t *skel; + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); Multiply_3x4Matrix(&bolt, (mdxaBone_t *)&boneCache.Eval(boneNum), &skel->BasePoseMat); // DEST FIRST ARG - retBasepose=&skel->BasePoseMat; - retBaseposeInv=&skel->BasePoseMatInv; + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; - if (scale[0]) - { + if (scale[0]) { bolt.matrix[0][3] *= scale[0]; } - if (scale[1]) - { + if (scale[1]) { bolt.matrix[1][3] *= scale[1]; } - if (scale[2]) - { + if (scale[2]) { bolt.matrix[2][3] *= scale[2]; } - VectorNormalize((float*)&bolt.matrix[0]); - VectorNormalize((float*)&bolt.matrix[1]); - VectorNormalize((float*)&bolt.matrix[2]); + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); - Multiply_3x4Matrix(&retMatrix,&worldMatrix, &bolt); + Multiply_3x4Matrix(&retMatrix, &worldMatrix, &bolt); #ifdef _DEBUG - for ( int i = 0; i < 3; i++ ) - { - for ( int j = 0; j < 4; j++ ) - { - assert( !Q_isnan(retMatrix.matrix[i][j])); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + assert(!Q_isnan(retMatrix.matrix[i][j])); } } -#endif// _DEBUG +#endif // _DEBUG } -int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv) -{ - int parent=-1; - if (ghoul2.mBoneCache) - { - CBoneCache &boneCache=*ghoul2.mBoneCache; +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, const vec3_t scale, mdxaBone_t &retMatrix, mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) { + int parent = -1; + if (ghoul2.mBoneCache) { + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - assert(boneNum>=0&&boneNumnumBones); - parent=boneCache.GetParent(boneNum); - if (parent<0||parent>=boneCache.header->numBones) - { - parent=-1; - retMatrix=identityMatrix; + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + parent = boneCache.GetParent(boneNum); + if (parent < 0 || parent >= boneCache.header->numBones) { + parent = -1; + retMatrix = identityMatrix; // yikes - retBasepose=const_cast(&identityMatrix); - retBaseposeInv=const_cast(&identityMatrix); - } - else - { - G2_GetBoneMatrixLow(ghoul2,parent,scale,retMatrix,retBasepose,retBaseposeInv); + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + } else { + G2_GetBoneMatrixLow(ghoul2, parent, scale, retMatrix, retBasepose, retBaseposeInv); } } return parent; } -//rww - RAGDOLL_END - -class CRenderSurface -{ -public: - int surfaceNum; - surfaceInfo_v &rootSList; - shader_t *cust_shader; - int fogNum; - qboolean personalModel; - CBoneCache *boneCache; - int renderfx; - skin_t *skin; - model_t *currentModel; - int lod; - boltInfo_v &boltList; +// rww - RAGDOLL_END + +class CRenderSurface { + public: + int surfaceNum; + surfaceInfo_v &rootSList; + shader_t *cust_shader; + int fogNum; + qboolean personalModel; + CBoneCache *boneCache; + int renderfx; + skin_t *skin; + model_t *currentModel; + int lod; + boltInfo_v &boltList; #ifdef _G2_GORE - shader_t *gore_shader; - CGoreSet *gore_set; + shader_t *gore_shader; + CGoreSet *gore_set; #endif - CRenderSurface( - int initsurfaceNum, - surfaceInfo_v &initrootSList, - shader_t *initcust_shader, - int initfogNum, - qboolean initpersonalModel, - CBoneCache *initboneCache, - int initrenderfx, - skin_t *initskin, - model_t *initcurrentModel, - int initlod, + CRenderSurface(int initsurfaceNum, surfaceInfo_v &initrootSList, shader_t *initcust_shader, int initfogNum, qboolean initpersonalModel, + CBoneCache *initboneCache, int initrenderfx, skin_t *initskin, model_t *initcurrentModel, int initlod, #ifdef _G2_GORE - boltInfo_v &initboltList, - shader_t *initgore_shader, - CGoreSet *initgore_set): + boltInfo_v &initboltList, shader_t *initgore_shader, CGoreSet *initgore_set) + : #else - boltInfo_v &initboltList): + boltInfo_v &initboltList) + : #endif - surfaceNum(initsurfaceNum), - rootSList(initrootSList), - cust_shader(initcust_shader), - fogNum(initfogNum), - personalModel(initpersonalModel), - boneCache(initboneCache), - renderfx(initrenderfx), - skin(initskin), - currentModel(initcurrentModel), - lod(initlod), + surfaceNum(initsurfaceNum), rootSList(initrootSList), cust_shader(initcust_shader), fogNum(initfogNum), personalModel(initpersonalModel), + boneCache(initboneCache), renderfx(initrenderfx), skin(initskin), currentModel(initcurrentModel), lod(initlod), #ifdef _G2_GORE - boltList(initboltList), - gore_shader(initgore_shader), - gore_set(initgore_set) + boltList(initboltList), gore_shader(initgore_shader), gore_set(initgore_set) #else - boltList(initboltList) + boltList(initboltList) #endif - {} + { + } }; #ifdef _G2_GORE #define MAX_RENDER_SURFACES (2048) static CRenderableSurface RSStorage[MAX_RENDER_SURFACES]; -static unsigned int NextRS=0; +static unsigned int NextRS = 0; -CRenderableSurface *AllocRS() -{ - CRenderableSurface *ret=&RSStorage[NextRS]; +CRenderableSurface *AllocRS() { + CRenderableSurface *ret = &RSStorage[NextRS]; ret->Init(); NextRS++; - NextRS%=MAX_RENDER_SURFACES; + NextRS %= MAX_RENDER_SURFACES; return ret; } #endif @@ -812,36 +702,31 @@ frame. */ - /* ============= R_ACullModel ============= */ -static int R_GCullModel( trRefEntity_t *ent ) { +static int R_GCullModel(trRefEntity_t *ent) { // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } // cull bounding sphere - switch ( R_CullLocalPointAndRadius( vec3_origin, ent->e.radius * largestScale) ) - { - case CULL_OUT: - tr.pc.c_sphere_cull_md3_out++; - return CULL_OUT; + switch (R_CullLocalPointAndRadius(vec3_origin, ent->e.radius * largestScale)) { + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; case CULL_IN: tr.pc.c_sphere_cull_md3_in++; @@ -850,37 +735,36 @@ static int R_GCullModel( trRefEntity_t *ent ) { case CULL_CLIP: tr.pc.c_sphere_cull_md3_clip++; return CULL_IN; - } + } return CULL_IN; } - /* ================= R_AComputeFogNum ================= */ -static int R_GComputeFogNum( trRefEntity_t *ent ) { +static int R_GComputeFogNum(trRefEntity_t *ent) { - int i, j; - fog_t *fog; + int i, j; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j]) { break; } - if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + if (ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -889,74 +773,60 @@ static int R_GComputeFogNum( trRefEntity_t *ent ) { } // work out lod for this entity. -static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int lodBias ) -{ +static int G2_ComputeLOD(trRefEntity_t *ent, const model_t *currentModel, int lodBias) { float flod, lodscale; float projectedRadius; int lod; - if ( currentModel->numLods < 2 ) - { // model has only 1 LOD level, skip computations and bias - return(0); + if (currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias + return (0); } - if ( r_lodbias->integer > lodBias ) - { + if (r_lodbias->integer > lodBias) { lodBias = r_lodbias->integer; } // scale the radius if need be float largestScale = ent->e.modelScale[0]; - if (ent->e.modelScale[1] > largestScale) - { + if (ent->e.modelScale[1] > largestScale) { largestScale = ent->e.modelScale[1]; } - if (ent->e.modelScale[2] > largestScale) - { + if (ent->e.modelScale[2] > largestScale) { largestScale = ent->e.modelScale[2]; } - if (!largestScale) - { + if (!largestScale) { largestScale = 1; } - if ( ( projectedRadius = ProjectRadius( 0.75*largestScale*ent->e.radius, ent->e.origin ) ) != 0 ) //we reduce the radius to make the LOD match other model types which use the actual bound box size - { - lodscale = (r_lodscale->value+r_autolodscalevalue->value); - if ( lodscale > 20 ) - { + if ((projectedRadius = ProjectRadius(0.75 * largestScale * ent->e.radius, ent->e.origin)) != + 0) // we reduce the radius to make the LOD match other model types which use the actual bound box size + { + lodscale = (r_lodscale->value + r_autolodscalevalue->value); + if (lodscale > 20) { lodscale = 20; - } - else if ( lodscale < 0 ) - { + } else if (lodscale < 0) { lodscale = 0; } - flod = 1.0f - projectedRadius * lodscale; - } - else - { - // object intersects near view plane, e.g. view weapon - flod = 0; - } - flod *= currentModel->numLods; - lod = Q_ftol( flod ); - - if ( lod < 0 ) - { - lod = 0; - } - else if ( lod >= currentModel->numLods ) - { - lod = currentModel->numLods - 1; - } + flod = 1.0f - projectedRadius * lodscale; + } else { + // object intersects near view plane, e.g. view weapon + flod = 0; + } + flod *= currentModel->numLods; + lod = Q_ftol(flod); + if (lod < 0) { + lod = 0; + } else if (lod >= currentModel->numLods) { + lod = currentModel->numLods - 1; + } lod += lodBias; - if ( lod >= currentModel->numLods ) + if (lod >= currentModel->numLods) lod = currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; @@ -966,277 +836,231 @@ static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int l // // Bone Manipulation code - -void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) -{ +void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) { // this is revised for the 3x4 matrix we use in G2. - float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; + float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; float s; - //If the trace of the matrix is greater than zero, then - //perform an "instant" calculation. - //Important note wrt. rouning errors: - //Test if ( T > 0.00000001 ) to avoid large distortions! - if (t > 0.00000001) - { - s = sqrt(t) * 2; - quat[0] = ( mat->matrix[1][2] - mat->matrix[2][1] ) / s; - quat[1] = ( mat->matrix[2][0] - mat->matrix[0][2] ) / s; - quat[2] = ( mat->matrix[0][1] - mat->matrix[1][0] ) / s; - quat[3] = 0.25 * s; - } - else - { - //If the trace of the matrix is equal to zero then identify - //which major diagonal element has the greatest value. - - //Depending on this, calculate the following: - - if ( mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2] ) { // Column 0: - s = sqrt( 1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2])* 2; + // If the trace of the matrix is greater than zero, then + // perform an "instant" calculation. + // Important note wrt. rouning errors: + // Test if ( T > 0.00000001 ) to avoid large distortions! + if (t > 0.00000001) { + s = sqrt(t) * 2; + quat[0] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; + quat[1] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; + quat[2] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; + quat[3] = 0.25 * s; + } else { + // If the trace of the matrix is equal to zero then identify + // which major diagonal element has the greatest value. + + // Depending on this, calculate the following: + + if (mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2]) { // Column 0: + s = sqrt(1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2]) * 2; quat[0] = 0.25 * s; - quat[1] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; - quat[2] = (mat->matrix[2][0] + mat->matrix[0][2] ) / s; - quat[3] = (mat->matrix[1][2] - mat->matrix[2][1] ) / s; + quat[1] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; + quat[2] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[3] = (mat->matrix[1][2] - mat->matrix[2][1]) / s; - } else if ( mat->matrix[1][1] > mat->matrix[2][2] ) { // Column 1: - s = sqrt( 1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2] ) * 2; - quat[0] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; + } else if (mat->matrix[1][1] > mat->matrix[2][2]) { // Column 1: + s = sqrt(1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2]) * 2; + quat[0] = (mat->matrix[0][1] + mat->matrix[1][0]) / s; quat[1] = 0.25 * s; - quat[2] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; - quat[3] = (mat->matrix[2][0] - mat->matrix[0][2] ) / s; + quat[2] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; + quat[3] = (mat->matrix[2][0] - mat->matrix[0][2]) / s; - } else { // Column 2: - s = sqrt( 1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1] ) * 2; - quat[0] = (mat->matrix[2][0]+ mat->matrix[0][2] ) / s; - quat[1] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; + } else { // Column 2: + s = sqrt(1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1]) * 2; + quat[0] = (mat->matrix[2][0] + mat->matrix[0][2]) / s; + quat[1] = (mat->matrix[1][2] + mat->matrix[2][1]) / s; quat[2] = 0.25 * s; - quat[3] = (mat->matrix[0][1] - mat->matrix[1][0] ) / s; + quat[3] = (mat->matrix[0][1] - mat->matrix[1][0]) / s; } } } -void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) -{ +void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) { - float xx = quat[0] * quat[0]; - float xy = quat[0] * quat[1]; - float xz = quat[0] * quat[2]; - float xw = quat[0] * quat[3]; + float xx = quat[0] * quat[0]; + float xy = quat[0] * quat[1]; + float xz = quat[0] * quat[2]; + float xw = quat[0] * quat[3]; - float yy = quat[1] * quat[1]; - float yz = quat[1] * quat[2]; - float yw = quat[1] * quat[3]; + float yy = quat[1] * quat[1]; + float yz = quat[1] * quat[2]; + float yw = quat[1] * quat[3]; - float zz = quat[2] * quat[2]; - float zw = quat[2] * quat[3]; + float zz = quat[2] * quat[2]; + float zw = quat[2] * quat[3]; - mat->matrix[0][0] = 1 - 2 * ( yy + zz ); - mat->matrix[1][0] = 2 * ( xy - zw ); - mat->matrix[2][0] = 2 * ( xz + yw ); + mat->matrix[0][0] = 1 - 2 * (yy + zz); + mat->matrix[1][0] = 2 * (xy - zw); + mat->matrix[2][0] = 2 * (xz + yw); - mat->matrix[0][1] = 2 * ( xy + zw ); - mat->matrix[1][1] = 1 - 2 * ( xx + zz ); - mat->matrix[2][1] = 2 * ( yz - xw ); + mat->matrix[0][1] = 2 * (xy + zw); + mat->matrix[1][1] = 1 - 2 * (xx + zz); + mat->matrix[2][1] = 2 * (yz - xw); - mat->matrix[0][2] = 2 * ( xz - yw ); - mat->matrix[1][2] = 2 * ( yz + xw ); - mat->matrix[2][2] = 1 - 2 * ( xx + yy ); + mat->matrix[0][2] = 2 * (xz - yw); + mat->matrix[1][2] = 2 * (yz + xw); + mat->matrix[2][2] = 1 - 2 * (xx + yy); - mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; + mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; } // nasty little matrix multiply going on here.. -void Multiply_3x4Matrix(mdxaBone_t *out, mdxaBone_t *in2, mdxaBone_t *in) -{ +void Multiply_3x4Matrix(mdxaBone_t *out, mdxaBone_t *in2, mdxaBone_t *in) { // first row of out out->matrix[0][0] = (in2->matrix[0][0] * in->matrix[0][0]) + (in2->matrix[0][1] * in->matrix[1][0]) + (in2->matrix[0][2] * in->matrix[2][0]); out->matrix[0][1] = (in2->matrix[0][0] * in->matrix[0][1]) + (in2->matrix[0][1] * in->matrix[1][1]) + (in2->matrix[0][2] * in->matrix[2][1]); out->matrix[0][2] = (in2->matrix[0][0] * in->matrix[0][2]) + (in2->matrix[0][1] * in->matrix[1][2]) + (in2->matrix[0][2] * in->matrix[2][2]); - out->matrix[0][3] = (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; + out->matrix[0][3] = + (in2->matrix[0][0] * in->matrix[0][3]) + (in2->matrix[0][1] * in->matrix[1][3]) + (in2->matrix[0][2] * in->matrix[2][3]) + in2->matrix[0][3]; // second row of outf out out->matrix[1][0] = (in2->matrix[1][0] * in->matrix[0][0]) + (in2->matrix[1][1] * in->matrix[1][0]) + (in2->matrix[1][2] * in->matrix[2][0]); out->matrix[1][1] = (in2->matrix[1][0] * in->matrix[0][1]) + (in2->matrix[1][1] * in->matrix[1][1]) + (in2->matrix[1][2] * in->matrix[2][1]); out->matrix[1][2] = (in2->matrix[1][0] * in->matrix[0][2]) + (in2->matrix[1][1] * in->matrix[1][2]) + (in2->matrix[1][2] * in->matrix[2][2]); - out->matrix[1][3] = (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; + out->matrix[1][3] = + (in2->matrix[1][0] * in->matrix[0][3]) + (in2->matrix[1][1] * in->matrix[1][3]) + (in2->matrix[1][2] * in->matrix[2][3]) + in2->matrix[1][3]; // third row of out out out->matrix[2][0] = (in2->matrix[2][0] * in->matrix[0][0]) + (in2->matrix[2][1] * in->matrix[1][0]) + (in2->matrix[2][2] * in->matrix[2][0]); out->matrix[2][1] = (in2->matrix[2][0] * in->matrix[0][1]) + (in2->matrix[2][1] * in->matrix[1][1]) + (in2->matrix[2][2] * in->matrix[2][1]); out->matrix[2][2] = (in2->matrix[2][0] * in->matrix[0][2]) + (in2->matrix[2][1] * in->matrix[1][2]) + (in2->matrix[2][2] * in->matrix[2][2]); - out->matrix[2][3] = (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; + out->matrix[2][3] = + (in2->matrix[2][0] * in->matrix[0][3]) + (in2->matrix[2][1] * in->matrix[1][3]) + (in2->matrix[2][2] * in->matrix[2][3]) + in2->matrix[2][3]; } - -static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) -{ - const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); - mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte*)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); +static int G2_GetBonePoolIndex(const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) { + const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); + mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); return (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); } - -/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) -{ - mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); - MC_UnCompressQuat(mat, pCompBonePool[ G2_GetBonePoolIndex( pMDXAHeader, iFrame, iBoneIndex ) ].Comp); +/*static inline*/ void UnCompressBone(float mat[3][4], int iBoneIndex, const mdxaHeader_t *pMDXAHeader, int iFrame) { + mdxaCompQuatBone_t *pCompBonePool = (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); + MC_UnCompressQuat(mat, pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); } #define DEBUG_G2_TIMING (0) #define DEBUG_G2_TIMING_RENDER_ONLY (1) -void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp) -{ - assert(bone.startFrame>=0); - assert(bone.startFrame<=numFramesInFile); - assert(bone.endFrame>=0); - assert(bone.endFrame<=numFramesInFile); +void G2_TimingModel(boneInfo_t &bone, int currentTime, int numFramesInFile, int ¤tFrame, int &newFrame, float &lerp) { + assert(bone.startFrame >= 0); + assert(bone.startFrame <= numFramesInFile); + assert(bone.endFrame >= 0); + assert(bone.endFrame <= numFramesInFile); // yes - add in animation speed to current frame - float animSpeed = bone.animSpeed; - float time; - if (bone.pauseTime) - { + float animSpeed = bone.animSpeed; + float time; + if (bone.pauseTime) { time = (bone.pauseTime - bone.startTime) / 50.0f; - } - else - { + } else { time = (currentTime - bone.startTime) / 50.0f; } - if (time<0.0f) - { - time=0.0f; + if (time < 0.0f) { + time = 0.0f; } - float newFrame_g = bone.startFrame + (time * animSpeed); + float newFrame_g = bone.startFrame + (time * animSpeed); - int animSize = bone.endFrame - bone.startFrame; - float endFrame = (float)bone.endFrame; + int animSize = bone.endFrame - bone.startFrame; + float endFrame = (float)bone.endFrame; // we are supposed to be animating right? - if (animSize) - { + if (animSize) { // did we run off the end? - if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || - ((animSpeed < 0.0f) && (newFrame_g < endFrame+1))) - { + if (((animSpeed > 0.0f) && (newFrame_g > endFrame - 1)) || ((animSpeed < 0.0f) && (newFrame_g < endFrame + 1))) { // yep - decide what to do - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) { // get our new animation frame back within the bounds of the animation set - if (animSpeed < 0.0f) - { + if (animSpeed < 0.0f) { // we don't use this case, or so I am told // if we do, let me know, I need to insure the mod works // should we be creating a virtual frame? - if ((newFrame_g < endFrame+1) && (newFrame_g >= endFrame)) - { + if ((newFrame_g < endFrame + 1) && (newFrame_g >= endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = float(endFrame+1)-newFrame_g; + lerp = float(endFrame + 1) - newFrame_g; // frames are easy to calculate currentFrame = endFrame; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g <= endFrame + 1) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; - lerp = (ceil(newFrame_g)-newFrame_g); + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (currentFrame <= endFrame+1 ) - { + if (currentFrame <= endFrame + 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame - 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - } - else - { + } else { // should we be creating a virtual frame? - if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) - { + if ((newFrame_g > endFrame - 1) && (newFrame_g < endFrame)) { // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= endFrame) - { - newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + assert(newFrame >= 0 && newFrame < numFramesInFile); + } else { + if (newFrame_g >= endFrame) { + newFrame_g = endFrame + fmod(newFrame_g - endFrame, animSize) - animSize; } // now figure out what we are lerping between // delta is the fraction between this frame and the next, since the new anim is always at a .0f; lerp = (newFrame_g - (int)newFrame_g); // frames are easy to calculate currentFrame = (int)newFrame_g; - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); // should we be creating a virtual frame? - if (newFrame_g >= endFrame - 1) - { + if (newFrame_g >= endFrame - 1) { newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { newFrame = currentFrame + 1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } // sanity check - assert (((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); - } - else - { - if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) - { + assert(((newFrame < endFrame) && (newFrame >= bone.startFrame)) || (animSize < 10)); + } else { + if (((bone.flags & (BONE_ANIM_OVERRIDE_FREEZE)) == (BONE_ANIM_OVERRIDE_FREEZE))) { // if we are supposed to reset the default anim, then do so - if (animSpeed > 0.0f) - { + if (animSpeed > 0.0f) { currentFrame = bone.endFrame - 1; - assert(currentFrame>=0&¤tFrame=0&¤tFrame= 0 && currentFrame < numFramesInFile); + } else { + currentFrame = bone.endFrame + 1; + assert(currentFrame >= 0 && currentFrame < numFramesInFile); } newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } - else - { + } else { bone.flags &= ~(BONE_ANIM_TOTAL); } - } - } - else - { - if (animSpeed> 0.0) - { + } else { + if (animSpeed > 0.0) { // frames are easy to calculate currentFrame = (int)newFrame_g; @@ -1244,99 +1068,80 @@ void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int &cu // frame we want to display lerp = (newFrame_g - currentFrame); - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame + 1; // are we now on the end frame? - assert((int)endFrame<=numFramesInFile); - if (newFrame >= (int)endFrame) - { + assert((int)endFrame <= numFramesInFile); + if (newFrame >= (int)endFrame) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame-1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); + } else { + lerp = (ceil(newFrame_g) - newFrame_g); // frames are easy to calculate currentFrame = ceil(newFrame_g); - if (currentFrame>bone.startFrame) - { - currentFrame=bone.startFrame; + if (currentFrame > bone.startFrame) { + currentFrame = bone.startFrame; newFrame = currentFrame; - lerp=0.0f; - } - else - { - newFrame=currentFrame-1; + lerp = 0.0f; + } else { + newFrame = currentFrame - 1; // are we now on the end frame? - if (newFrame < endFrame+1) - { + if (newFrame < endFrame + 1) { // we only want to lerp with the first frame of the anim if we are looping - if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) - { - newFrame = bone.startFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } // if we intend to end this anim or freeze after this, then just keep on the last frame - else - { - newFrame = bone.endFrame+1; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); } } } - assert(currentFrame>=0&¤tFrame=0&&newFrame= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); } } - } - else - { - if (animSpeed<0.0) - { - currentFrame = bone.endFrame+1; - } - else - { - currentFrame = bone.endFrame-1; + } else { + if (animSpeed < 0.0) { + currentFrame = bone.endFrame + 1; + } else { + currentFrame = bone.endFrame - 1; } - if (currentFrame<0) - { - currentFrame=0; + if (currentFrame < 0) { + currentFrame = 0; } - assert(currentFrame>=0&¤tFrame= 0 && currentFrame < numFramesInFile); newFrame = currentFrame; - assert(newFrame>=0&&newFrame= 0 && newFrame < numFramesInFile); lerp = 0; - } - assert(currentFrame>=0&¤tFrame=0&&newFrame=0.0f&&lerp<=1.0f); + assert(currentFrame >= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); + assert(lerp >= 0.0f && lerp <= 1.0f); } #ifdef _RAG_PRINT_TEST void G2_RagPrintMatrix(mdxaBone_t *mat); #endif -//basically construct a seperate skeleton with full hierarchy to store a matrix -//off which will give us the desired settling position given the frame in the skeleton -//that should be used -rww -int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName); +// basically construct a seperate skeleton with full hierarchy to store a matrix +// off which will give us the desired settling position given the frame in the skeleton +// that should be used -rww +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); -void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame) -{ +void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame) { mdxaBone_t animMatrix; mdxaSkel_t *skel; mdxaSkel_t *pskel; @@ -1354,18 +1159,14 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[boneNum]); - //find/add the bone in the list - if (!skel->name[0]) - { + // find/add the bone in the list + if (!skel->name[0]) { bListIndex = -1; - } - else - { + } else { bListIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); - if (bListIndex == -1) - { + if (bListIndex == -1) { #ifdef _RAG_PRINT_TEST - ri.Printf( PRINT_ALL, "Attempting to add %s\n", skel->name); + ri.Printf(PRINT_ALL, "Attempting to add %s\n", skel->name); #endif bListIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); } @@ -1375,34 +1176,28 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &bone = ghoul2.mBlist[bListIndex]; - if (bone.hasAnimFrameMatrix == frame) - { //already calculated so just grab it + if (bone.hasAnimFrameMatrix == frame) { // already calculated so just grab it matrix = bone.animFrameMatrix; return; } - //get the base matrix for the specified frame + // get the base matrix for the specified frame UnCompressBone(animMatrix.matrix, boneNum, ghoul2.mBoneCache->header, frame); parent = skel->parent; - if (boneNum > 0 && parent > -1) - { - //recursively call to assure all parent matrices are set up + if (boneNum > 0 && parent > -1) { + // recursively call to assure all parent matrices are set up G2_RagGetAnimMatrix(ghoul2, parent, matrix, frame); - //assign the new skel ptr for our parent + // assign the new skel ptr for our parent pskel = (mdxaSkel_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t) + offsets->offsets[parent]); - //taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix - if (!pskel->name[0]) - { + // taking bone matrix for the skeleton frame and parent's animFrameMatrix into account, determine our final animFrameMatrix + if (!pskel->name[0]) { parentBlistIndex = -1; - } - else - { + } else { parentBlistIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); - if (parentBlistIndex == -1) - { + if (parentBlistIndex == -1) { parentBlistIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); } } @@ -1411,47 +1206,38 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat boneInfo_t &pbone = ghoul2.mBlist[parentBlistIndex]; - assert(pbone.hasAnimFrameMatrix == frame); //this should have been calc'd in the recursive call + assert(pbone.hasAnimFrameMatrix == frame); // this should have been calc'd in the recursive call Multiply_3x4Matrix(&bone.animFrameMatrix, &pbone.animFrameMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (parentBlistIndex != -1 && bListIndex != -1) - { + if (parentBlistIndex != -1 && bListIndex != -1) { actuallySet = true; - } - else - { - ri.Printf( PRINT_ALL, "BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); + } else { + ri.Printf(PRINT_ALL, "BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); } #endif - } - else - { //root + } else { // root Multiply_3x4Matrix(&bone.animFrameMatrix, &ghoul2.mBoneCache->rootMatrix, &animMatrix); #ifdef _RAG_PRINT_TEST - if (bListIndex != -1) - { + if (bListIndex != -1) { actuallySet = true; - } - else - { - ri.Printf( PRINT_ALL, "BAD LIST INDEX: %s\n", skel->name); + } else { + ri.Printf(PRINT_ALL, "BAD LIST INDEX: %s\n", skel->name); } #endif - //bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; - //Maybe use this for the root, so that the orientation is in sync with the current - //root matrix? However this would require constant recalculation of this base - //skeleton which I currently do not want. + // bone.animFrameMatrix = ghoul2.mBoneCache->mFinalBones[boneNum].boneMatrix; + // Maybe use this for the root, so that the orientation is in sync with the current + // root matrix? However this would require constant recalculation of this base + // skeleton which I currently do not want. } - //never need to figure it out again + // never need to figure it out again bone.hasAnimFrameMatrix = frame; #ifdef _RAG_PRINT_TEST - if (!actuallySet) - { - ri.Printf( PRINT_ALL, "SET FAILURE\n"); + if (!actuallySet) { + ri.Printf(PRINT_ALL, "SET FAILURE\n"); G2_RagPrintMatrix(&bone.animFrameMatrix); } #endif @@ -1459,65 +1245,57 @@ void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &mat matrix = bone.animFrameMatrix; } -void G2_TransformBone (int child,CBoneCache &BC) -{ - SBoneCalc &TB=BC.mBones[child]; - static mdxaBone_t tbone[6]; -// mdxaFrame_t *aFrame=0; -// mdxaFrame_t *bFrame=0; -// mdxaFrame_t *aoldFrame=0; -// mdxaFrame_t *boldFrame=0; - static mdxaSkel_t *skel; +void G2_TransformBone(int child, CBoneCache &BC) { + SBoneCalc &TB = BC.mBones[child]; + static mdxaBone_t tbone[6]; + // mdxaFrame_t *aFrame=0; + // mdxaFrame_t *bFrame=0; + // mdxaFrame_t *aoldFrame=0; + // mdxaFrame_t *boldFrame=0; + static mdxaSkel_t *skel; static mdxaSkelOffsets_t *offsets; - boneInfo_v &boneList = *BC.rootBoneList; - static int j, boneListIndex; - int angleOverride = 0; + boneInfo_v &boneList = *BC.rootBoneList; + static int j, boneListIndex; + int angleOverride = 0; #if DEBUG_G2_TIMING - bool printTiming=false; + bool printTiming = false; #endif // should this bone be overridden by a bone in the bone list? boneListIndex = G2_Find_Bone_In_List(boneList, child); - if (boneListIndex != -1) - { + if (boneListIndex != -1) { // we found a bone in the list - we need to override something here. // do we override the rotational angles? - if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) - { + if ((boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL)) { angleOverride = (boneList[boneListIndex].flags) & (BONE_ANGLES_TOTAL); } // set blending stuff if we need to - if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) - { + if (boneList[boneListIndex].flags & BONE_ANIM_BLEND) { float blendTime = BC.incomingTime - boneList[boneListIndex].blendStart; - // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the hiearchy - if (blendTime>=0.0f&&blendTime < boneList[boneListIndex].blendTime) - { - TB.blendFrame = boneList[boneListIndex].blendFrame; + // only set up the blend anim if we actually have some blend time left on this bone anim - otherwise we might corrupt some blend higher up the + // hiearchy + if (blendTime >= 0.0f && blendTime < boneList[boneListIndex].blendTime) { + TB.blendFrame = boneList[boneListIndex].blendFrame; TB.blendOldFrame = boneList[boneListIndex].blendLerpFrame; TB.blendLerp = (blendTime / boneList[boneListIndex].blendTime); TB.blendMode = true; - } - else - { + } else { TB.blendMode = false; } - } - else if (/*r_Ghoul2NoBlend->integer||*/((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) + } else if (/*r_Ghoul2NoBlend->integer||*/ ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE))) // turn off blending if we are just doing a straing animation override { TB.blendMode = false; } // should this animation be overridden by an animation in the bone list? - if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) - { - G2_TimingModel(boneList[boneListIndex],BC.incomingTime,BC.header->numFrames,TB.currentFrame,TB.newFrame,TB.backlerp); + if ((boneList[boneListIndex].flags) & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) { + G2_TimingModel(boneList[boneListIndex], BC.incomingTime, BC.header->numFrames, TB.currentFrame, TB.newFrame, TB.backlerp); } #if DEBUG_G2_TIMING - printTiming=true; + printTiming = true; #endif /* if ((r_Ghoul2NoLerp->integer)||((boneList[boneListIndex].flags) & (BONE_ANIM_NO_LERP))) @@ -1525,290 +1303,219 @@ void G2_TransformBone (int child,CBoneCache &BC) TB.backlerp = 0.0f; } */ - //rwwFIXMEFIXME: Use? + // rwwFIXMEFIXME: Use? } // figure out where the location of the bone animation data is - assert(TB.newFrame>=0&&TB.newFramenumFrames); - if (!(TB.newFrame>=0&&TB.newFramenumFrames)) - { - TB.newFrame=0; + assert(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames); + if (!(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames)) { + TB.newFrame = 0; } -// aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); - assert(TB.currentFrame>=0&&TB.currentFramenumFrames); - if (!(TB.currentFrame>=0&&TB.currentFramenumFrames)) - { - TB.currentFrame=0; + // aFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.newFrame * BC.frameSize ); + assert(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames); + if (!(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames)) { + TB.currentFrame = 0; } -// aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); + // aoldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.currentFrame * BC.frameSize ); // figure out where the location of the blended animation data is - assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1))); - if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames+1) ) - { - TB.blendFrame=0.0; + assert(!(TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1))); + if (TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1)) { + TB.blendFrame = 0.0; } -// bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); - assert(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames); - if (!(TB.blendOldFrame>=0&&TB.blendOldFramenumFrames)) - { - TB.blendOldFrame=0; + // bFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + (int)TB.blendFrame * BC.frameSize ); + assert(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames); + if (!(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames)) { + TB.blendOldFrame = 0; } #if DEBUG_G2_TIMING #if DEBUG_G2_TIMING_RENDER_ONLY - if (!HackadelicOnClient) - { - printTiming=false; + if (!HackadelicOnClient) { + printTiming = false; } #endif - if (printTiming) - { + if (printTiming) { char mess[1000]; - if (TB.blendMode) - { - sprintf(mess,"b %2d %5d %4d %4d %4d %4d %f %f\n",boneListIndex,BC.incomingTime,(int)TB.newFrame,(int)TB.currentFrame,(int)TB.blendFrame,(int)TB.blendOldFrame,TB.backlerp,TB.blendLerp); - } - else - { - sprintf(mess,"a %2d %5d %4d %4d %f\n",boneListIndex,BC.incomingTime,TB.newFrame,TB.currentFrame,TB.backlerp); - } - Com_OPrintf("%s",mess); - const boneInfo_t &bone=boneList[boneListIndex]; - if (bone.flags&BONE_ANIM_BLEND) - { - sprintf(mess," bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags, - bone.blendStart, - bone.blendStart+bone.blendTime, - bone.blendFrame, - bone.blendLerpFrame - ); + if (TB.blendMode) { + sprintf(mess, "b %2d %5d %4d %4d %4d %4d %f %f\n", boneListIndex, BC.incomingTime, (int)TB.newFrame, (int)TB.currentFrame, (int)TB.blendFrame, + (int)TB.blendOldFrame, TB.backlerp, TB.blendLerp); + } else { + sprintf(mess, "a %2d %5d %4d %4d %f\n", boneListIndex, BC.incomingTime, TB.newFrame, TB.currentFrame, TB.backlerp); } - else - { - sprintf(mess," bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", - boneListIndex, - BC.incomingTime, - bone.startTime, - bone.startFrame, - bone.endFrame, - bone.animSpeed, - bone.flags - ); + Com_OPrintf("%s", mess); + const boneInfo_t &bone = boneList[boneListIndex]; + if (bone.flags & BONE_ANIM_BLEND) { + sprintf(mess, + " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + boneListIndex, BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags, bone.blendStart, + bone.blendStart + bone.blendTime, bone.blendFrame, bone.blendLerpFrame); + } else { + sprintf(mess, " bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", boneListIndex, + BC.incomingTime, bone.startTime, bone.startFrame, bone.endFrame, bone.animSpeed, bone.flags); } -// Com_OPrintf("%s",mess); + // Com_OPrintf("%s",mess); } #endif -// boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); + // boldFrame = (mdxaFrame_t *)((byte *)BC.header + BC.header->ofsFrames + TB.blendOldFrame * BC.frameSize ); -// mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); + // mdxaCompBone_t *compBonePointer = (mdxaCompBone_t *)((byte *)BC.header + BC.header->ofsCompBonePool); - assert(child>=0&&childnumBones); -// assert(bFrame->boneIndexes[child]>=0); -// assert(boldFrame->boneIndexes[child]>=0); -// assert(aFrame->boneIndexes[child]>=0); -// assert(aoldFrame->boneIndexes[child]>=0); + assert(child >= 0 && child < BC.header->numBones); + // assert(bFrame->boneIndexes[child]>=0); + // assert(boldFrame->boneIndexes[child]>=0); + // assert(aFrame->boneIndexes[child]>=0); + // assert(aoldFrame->boneIndexes[child]>=0); // decide where the transformed bone is going // are we blending with another frame of anim? - if (TB.blendMode) - { + if (TB.blendMode) { float backlerp = TB.blendFrame - (int)TB.blendFrame; float frontlerp = 1.0 - backlerp; -// MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[3].matrix,compBonePointer[bFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[4].matrix,compBonePointer[boldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[3].matrix, child, BC.header, TB.blendFrame); UnCompressBone(tbone[4].matrix, child, BC.header, TB.blendOldFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) - + (frontlerp * ((float *)&tbone[4])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[5])[j] = (backlerp * ((float *)&tbone[3])[j]) + (frontlerp * ((float *)&tbone[4])[j]); } } - // - // lerp this bone - use the temp space on the ref entity to put the bone transforms into - // - if (!TB.backlerp) - { -// MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // + // lerp this bone - use the temp space on the ref entity to put the bone transforms into + // + if (!TB.backlerp) { + // MC_UnCompress(tbone[2].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[2].matrix, child, BC.header, TB.currentFrame); // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } - } - else - { + } + } else { float frontlerp = 1.0 - TB.backlerp; -// MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); -// MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[0].matrix,compBonePointer[aFrame->boneIndexes[child]].Comp); + // MC_UnCompress(tbone[1].matrix,compBonePointer[aoldFrame->boneIndexes[child]].Comp); UnCompressBone(tbone[0].matrix, child, BC.header, TB.newFrame); UnCompressBone(tbone[1].matrix, child, BC.header, TB.currentFrame); - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) - + (frontlerp * ((float *)&tbone[1])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.backlerp * ((float *)&tbone[0])[j]) + (frontlerp * ((float *)&tbone[1])[j]); } // blend in the other frame if we need to - if (TB.blendMode) - { + if (TB.blendMode) { float blendFrontlerp = 1.0 - TB.blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) - + (blendFrontlerp * ((float *)&tbone[5])[j]); + for (j = 0; j < 12; j++) { + ((float *)&tbone[2])[j] = (TB.blendLerp * ((float *)&tbone[2])[j]) + (blendFrontlerp * ((float *)&tbone[5])[j]); } } - if (!child) - { + if (!child) { // now multiply by the root matrix, so we can offset this model should we need to Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &tbone[2]); - } + } } // figure out where the bone hirearchy info is offsets = (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)BC.header + sizeof(mdxaHeader_t) + offsets->offsets[child]); -// skel = BC.mSkels[child]; - //rww - removed mSkels - - int parent=BC.mFinalBones[child].parent; - assert((parent==-1&&child==0)||(parent>=0&&parent<(int)BC.mBones.size())); - if (angleOverride & BONE_ANGLES_REPLACE) - { - bool isRag=!!(angleOverride & BONE_ANGLES_RAGDOLL); - if (!isRag) - { //do the same for ik.. I suppose. + // skel = BC.mSkels[child]; + // rww - removed mSkels + + int parent = BC.mFinalBones[child].parent; + assert((parent == -1 && child == 0) || (parent >= 0 && parent < (int)BC.mBones.size())); + if (angleOverride & BONE_ANGLES_REPLACE) { + bool isRag = !!(angleOverride & BONE_ANGLES_RAGDOLL); + if (!isRag) { // do the same for ik.. I suppose. isRag = !!(angleOverride & BONE_ANGLES_IK); } mdxaBone_t &bone = BC.mFinalBones[child].boneMatrix; boneInfo_t &boneOverride = boneList[boneListIndex]; - if (isRag) - { + if (isRag) { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // this is crazy, we are gonna drive the animation to ID while we are doing post mults to compensate. - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); - static mdxaBone_t toMatrix = - { - { - { 1.0f, 0.0f, 0.0f, 0.0f }, - { 0.0f, 1.0f, 0.0f, 0.0f }, - { 0.0f, 0.0f, 1.0f, 0.0f } - } - }; - toMatrix.matrix[0][0]=matrixScale; - toMatrix.matrix[1][1]=matrixScale; - toMatrix.matrix[2][2]=matrixScale; - toMatrix.matrix[0][3]=temp.matrix[0][3]; - toMatrix.matrix[1][3]=temp.matrix[1][3]; - toMatrix.matrix[2][3]=temp.matrix[2][3]; - - Multiply_3x4Matrix(&temp, &toMatrix,&skel->BasePoseMatInv); //dest first arg + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); + static mdxaBone_t toMatrix = {{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}}}; + toMatrix.matrix[0][0] = matrixScale; + toMatrix.matrix[1][1] = matrixScale; + toMatrix.matrix[2][2] = matrixScale; + toMatrix.matrix[0][3] = temp.matrix[0][3]; + toMatrix.matrix[1][3] = temp.matrix[1][3]; + toMatrix.matrix[2][3] = temp.matrix[2][3]; + + Multiply_3x4Matrix(&temp, &toMatrix, &skel->BasePoseMatInv); // dest first arg float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp>0.0f) - { + if (blendLerp > 0.0f) { // has started - if (blendLerp>1.0f) - { + if (blendLerp > 1.0f) { // done -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); - memcpy (&bone,&temp, sizeof(mdxaBone_t)); - } - else - { -// mdxaBone_t lerp; + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&temp); + memcpy(&bone, &temp, sizeof(mdxaBone_t)); + } else { + // mdxaBone_t lerp; // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&tbone[2])[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&tbone[2])[j]); } -// Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); + // Multiply_3x4Matrix(&bone, &BC.mFinalBones[parent].boneMatrix,&lerp); } } - } - else - { + } else { mdxaBone_t temp, firstPass; // give us the matrix the animation thinks we should have, so we can get the correct X&Y coors Multiply_3x4Matrix(&firstPass, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); // are we attempting to blend with the base animation? and still within blend time? - if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) - { + if (boneOverride.boneBlendTime && (((boneOverride.boneBlendTime + boneOverride.boneBlendStart) < BC.incomingTime))) { // ok, we are supposed to be blending. Work out lerp float blendTime = BC.incomingTime - boneList[boneListIndex].boneBlendStart; float blendLerp = (blendTime / boneList[boneListIndex].boneBlendTime); - if (blendLerp <= 1) - { - if (blendLerp < 0) - { + if (blendLerp <= 1) { + if (blendLerp < 0) { assert(0); } // now work out the matrix we want to get *to* - firstPass is where we are coming *from* Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1817,51 +1524,39 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&temp, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&temp, &newMatrixTemp, &skel->BasePoseMatInv); // now do the blend into the destination float blendFrontlerp = 1.0 - blendLerp; - for ( j = 0 ; j < 12 ; j++ ) - { - ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) - + (blendFrontlerp * ((float *)&firstPass)[j]); + for (j = 0; j < 12; j++) { + ((float *)&bone)[j] = (blendLerp * ((float *)&temp)[j]) + (blendFrontlerp * ((float *)&firstPass)[j]); } - } - else - { + } else { bone = firstPass; } } // no, so just override it directly - else - { + else { - Multiply_3x4Matrix(&temp,&firstPass, &skel->BasePoseMat); - float matrixScale = VectorLength((float*)&temp); + Multiply_3x4Matrix(&temp, &firstPass, &skel->BasePoseMat); + float matrixScale = VectorLength((float *)&temp); - mdxaBone_t newMatrixTemp; + mdxaBone_t newMatrixTemp; - if (HackadelicOnClient) - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x]*matrixScale; + if (HackadelicOnClient) { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.newMatrix.matrix[i][x] * matrixScale; } } newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; - } - else - { - for (int i=0; i<3;i++) - { - for(int x=0;x<3; x++) - { - newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x]*matrixScale; + } else { + for (int i = 0; i < 3; i++) { + for (int x = 0; x < 3; x++) { + newMatrixTemp.matrix[i][x] = boneOverride.matrix.matrix[i][x] * matrixScale; } } @@ -1870,86 +1565,57 @@ void G2_TransformBone (int child,CBoneCache &BC) newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; } - Multiply_3x4Matrix(&bone, &newMatrixTemp,&skel->BasePoseMatInv); + Multiply_3x4Matrix(&bone, &newMatrixTemp, &skel->BasePoseMatInv); } } - } - else if (angleOverride & BONE_ANGLES_PREMULT) - { - if ((angleOverride&BONE_ANGLES_RAGDOLL) || (angleOverride&BONE_ANGLES_IK)) - { - mdxaBone_t tmp; - if (!child) - { - if (HackadelicOnClient) - { + } else if (angleOverride & BONE_ANGLES_PREMULT) { + if ((angleOverride & BONE_ANGLES_RAGDOLL) || (angleOverride & BONE_ANGLES_IK)) { + mdxaBone_t tmp; + if (!child) { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { - if (HackadelicOnClient) - { + } else { + if (HackadelicOnClient) { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&tmp, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tmp, &tbone[2]); - } - else - { - if (!child) - { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tmp, &tbone[2]); + } else { + if (!child) { // use the in coming root matrix as our basis - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.rootMatrix, &boneList[boneListIndex].matrix); } - } - else - { + } else { // convert from 3x4 matrix to a 4x4 matrix - if (HackadelicOnClient) - { + if (HackadelicOnClient) { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].newMatrix); - } - else - { + } else { Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &boneList[boneListIndex].matrix); } } } - } - else - // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely - if (child) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); - } + } else + // now transform the matrix by it's parent, asumming we have a parent, and we aren't overriding the angles absolutely + if (child) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &BC.mFinalBones[parent].boneMatrix, &tbone[2]); + } // now multiply our resulting bone by an override matrix should we need to - if (angleOverride & BONE_ANGLES_POSTMULT) - { - mdxaBone_t tempMatrix; - memcpy (&tempMatrix,&BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); - if (HackadelicOnClient) - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); - } - else - { - Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); + if (angleOverride & BONE_ANGLES_POSTMULT) { + mdxaBone_t tempMatrix; + memcpy(&tempMatrix, &BC.mFinalBones[child].boneMatrix, sizeof(mdxaBone_t)); + if (HackadelicOnClient) { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].newMatrix); + } else { + Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix, &tempMatrix, &boneList[boneListIndex].matrix); } } /* @@ -1969,20 +1635,16 @@ void G2_TransformBone (int child,CBoneCache &BC) Multiply_3x4Matrix(&BC.mFinalBones[child].boneMatrix,&tempMatrix,&skel->BasePoseMatInv); } */ - //rwwFIXMEFIXME: Care? - + // rwwFIXMEFIXME: Care? } -void G2_SetUpBolts( mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, boltInfo_v &boltList) -{ - mdxaSkel_t *skel; +void G2_SetUpBolts(mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, boltInfo_v &boltList) { + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); - for (size_t i=0; ioffsets[boltList[i].boneNumber]); Multiply_3x4Matrix(&boltList[i].position, &bonePtr[boltList[i].boneNumber].second, &skel->BasePoseMat); @@ -1990,13 +1652,12 @@ void G2_SetUpBolts( mdxaHeader_t *header, CGhoul2Info &ghoul2, mdxaBone_v &boneP } } -//rww - RAGDOLL_BEGIN -#define GHOUL2_RAG_STARTED 0x0010 -//rww - RAGDOLL_END -//rwwFIXMEFIXME: Move this into the stupid header or something. +// rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +// rww - RAGDOLL_END +// rwwFIXMEFIXME: Move this into the stupid header or something. -void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time,bool smooth=true) -{ +void G2_TransformGhoulBones(boneInfo_v &rootBoneList, mdxaBone_t &rootMatrix, CGhoul2Info &ghoul2, int time, bool smooth = true) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_TransformGhoulBones.Start(); G2PerformanceCounter_G2_TransformGhoulBones++; @@ -2017,37 +1678,33 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh aHeader = animModel->mdxa; assert(aHeader); */ - model_t *currentModel = (model_t *)ghoul2.currentModel; - mdxaHeader_t *aHeader = (mdxaHeader_t *)ghoul2.aHeader; - + model_t *currentModel = (model_t *)ghoul2.currentModel; + mdxaHeader_t *aHeader = (mdxaHeader_t *)ghoul2.aHeader; assert(ghoul2.aHeader); assert(ghoul2.currentModel); assert(ghoul2.currentModel->mdxm); - if (!aHeader->numBones) - { + if (!aHeader->numBones) { assert(0); // this would be strange return; } - if (!ghoul2.mBoneCache) - { - ghoul2.mBoneCache=new CBoneCache(currentModel,aHeader); + if (!ghoul2.mBoneCache) { + ghoul2.mBoneCache = new CBoneCache(currentModel, aHeader); #ifdef _FULL_G2_LEAK_CHECKING g_Ghoul2Allocations += sizeof(*ghoul2.mBoneCache); #endif } - ghoul2.mBoneCache->mod=currentModel; - ghoul2.mBoneCache->header=aHeader; - assert(ghoul2.mBoneCache->mBones.size()==(unsigned)aHeader->numBones); + ghoul2.mBoneCache->mod = currentModel; + ghoul2.mBoneCache->header = aHeader; + assert(ghoul2.mBoneCache->mBones.size() == (unsigned)aHeader->numBones); - ghoul2.mBoneCache->mSmoothingActive=false; - ghoul2.mBoneCache->mUnsquash=false; + ghoul2.mBoneCache->mSmoothingActive = false; + ghoul2.mBoneCache->mUnsquash = false; // master smoothing control - if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue( "dedicated" )) - { - ghoul2.mBoneCache->mLastTouch=ghoul2.mBoneCache->mLastLastTouch; + if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue("dedicated")) { + ghoul2.mBoneCache->mLastTouch = ghoul2.mBoneCache->mLastLastTouch; /* float val=r_Ghoul2AnimSmooth->value; if (smooth&&val>0.0f&&val<1.0f) @@ -2071,34 +1728,21 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh */ // master smoothing control - float val=r_Ghoul2AnimSmooth->value; - if (val>0.0f&&val<1.0f) - { - //if (ghoul2.mFlags&GHOUL2_RESERVED_FOR_RAGDOLL) + float val = r_Ghoul2AnimSmooth->value; + if (val > 0.0f && val < 1.0f) { + // if (ghoul2.mFlags&GHOUL2_RESERVED_FOR_RAGDOLL) #if 1 - if(ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) - { + if (ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) { val = 0.9f; - } - else if(ghoul2.mFlags & GHOUL2_RAG_STARTED) - { - for (size_t k=0;ktime-250 && - bone.firstCollisionTime time) - { + } else if (ghoul2.mFlags & GHOUL2_RAG_STARTED) { + for (size_t k = 0; k < rootBoneList.size(); k++) { + boneInfo_t &bone = rootBoneList[k]; + if (bone.flags & BONE_ANGLES_RAGDOLL) { + if (bone.firstCollisionTime && bone.firstCollisionTime > time - 250 && bone.firstCollisionTime < time) { + val = 0.9f; //(val+0.8f)/2.0f; + } else if (bone.airTime > time) { val = 0.2f; - } - else - { + } else { val = 0.8f; } break; @@ -2107,80 +1751,70 @@ void G2_TransformGhoulBones(boneInfo_v &rootBoneList,mdxaBone_t &rootMatrix, CGh } #endif -// ghoul2.mBoneCache->mSmoothFactor=(val + 1.0f-pow(1.0f-val,50.0f/dif))/2.0f; // meaningless formula - ghoul2.mBoneCache->mSmoothFactor=val; // meaningless formula - ghoul2.mBoneCache->mSmoothingActive=true; + // ghoul2.mBoneCache->mSmoothFactor=(val + 1.0f-pow(1.0f-val,50.0f/dif))/2.0f; // meaningless formula + ghoul2.mBoneCache->mSmoothFactor = val; // meaningless formula + ghoul2.mBoneCache->mSmoothingActive = true; - if (r_Ghoul2UnSqashAfterSmooth->integer) - { - ghoul2.mBoneCache->mUnsquash=true; + if (r_Ghoul2UnSqashAfterSmooth->integer) { + ghoul2.mBoneCache->mUnsquash = true; } } - } - else - { - ghoul2.mBoneCache->mSmoothFactor=1.0f; + } else { + ghoul2.mBoneCache->mSmoothFactor = 1.0f; } ghoul2.mBoneCache->mCurrentTouch++; -//rww - RAGDOLL_BEGIN - if (HackadelicOnClient) - { - ghoul2.mBoneCache->mLastLastTouch=ghoul2.mBoneCache->mCurrentTouch; - ghoul2.mBoneCache->mCurrentTouchRender=ghoul2.mBoneCache->mCurrentTouch; - } - else - { - ghoul2.mBoneCache->mCurrentTouchRender=0; + // rww - RAGDOLL_BEGIN + if (HackadelicOnClient) { + ghoul2.mBoneCache->mLastLastTouch = ghoul2.mBoneCache->mCurrentTouch; + ghoul2.mBoneCache->mCurrentTouchRender = ghoul2.mBoneCache->mCurrentTouch; + } else { + ghoul2.mBoneCache->mCurrentTouchRender = 0; } -//rww - RAGDOLL_END + // rww - RAGDOLL_END - ghoul2.mBoneCache->frameSize = 0;// can be deleted in new G2 format //(size_t)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); + ghoul2.mBoneCache->frameSize = 0; // can be deleted in new G2 format //(size_t)( &((mdxaFrame_t *)0)->boneIndexes[ ghoul2.aHeader->numBones ] ); - ghoul2.mBoneCache->rootBoneList=&rootBoneList; - ghoul2.mBoneCache->rootMatrix=rootMatrix; - ghoul2.mBoneCache->incomingTime=time; + ghoul2.mBoneCache->rootBoneList = &rootBoneList; + ghoul2.mBoneCache->rootMatrix = rootMatrix; + ghoul2.mBoneCache->incomingTime = time; - SBoneCalc &TB=ghoul2.mBoneCache->Root(); - TB.newFrame=0; - TB.currentFrame=0; - TB.backlerp=0.0f; - TB.blendFrame=0; - TB.blendOldFrame=0; - TB.blendMode=false; - TB.blendLerp=0; + SBoneCalc &TB = ghoul2.mBoneCache->Root(); + TB.newFrame = 0; + TB.currentFrame = 0; + TB.backlerp = 0.0f; + TB.blendFrame = 0; + TB.blendOldFrame = 0; + TB.blendMode = false; + TB.blendLerp = 0; #ifdef G2_PERFORMANCE_ANALYSIS G2Time_G2_TransformGhoulBones += G2PerformanceTimer_G2_TransformGhoulBones.End(); #endif } - #define MDX_TAG_ORIGIN 2 //====================================================================== // // Surface Manipulation code - // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, surfaceInfo_t *surfInfo, model_t *mod) -{ - mdxmVertex_t *v, *vert0, *vert1, *vert2; - matrix3_t axes, sides; - float pTri[3][3], d; - int j, k; +void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, surfaceInfo_t *surfInfo, model_t *mod) { + mdxmVertex_t *v, *vert0, *vert1, *vert2; + matrix3_t axes, sides; + float pTri[3][3], d; + int j, k; // now there are two types of tag surface - model ones and procedural generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; - int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface((void*)mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -2189,63 +1823,69 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt // decide where the original verts are - vert0 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert0+= index0; + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; - vert1 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert1+= index1; + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; - vert2 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert2+= index2; + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; // clear out the triangle verts to be - VectorClear( pTri[0] ); - VectorClear( pTri[1] ); - VectorClear( pTri[2] ); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); -// mdxmWeight_t *w; + // mdxmWeight_t *w; - int *piBoneRefs = (int*) ((byte*)originalSurf + originalSurf->ofsBoneReferences); + int *piBoneRefs = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); // now go and transform just the points we need from the surface that was hit originally -// w = vert0->weights; + // w = vert0->weights; float fTotalWeight = 0.0f; - int iNumWeights = G2_GetVertWeights( vert0 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert0, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert0, k, fTotalWeight, iNumWeights ); - - pTri[0][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[0][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[0][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); + + pTri[0][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } -// w = vert1->weights; + // w = vert1->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert1 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert1, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert1, k, fTotalWeight, iNumWeights ); - - pTri[1][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[1][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[1][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); + + pTri[1][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } -// w = vert2->weights; + // w = vert2->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert2 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert2, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert2, k, fTotalWeight, iNumWeights ); - - pTri[2][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[2][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[2][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); + + pTri[2][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); } - vec3_t normal; + vec3_t normal; vec3_t up; vec3_t right; vec3_t vec0, vec1; @@ -2253,9 +1893,12 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt float baryCentricK = 1.0 - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); // now we have the model transformed into model space, now generate an origin. - boltList[boltNum].position.matrix[0][3] = (pTri[0][0] * surfInfo->genBarycentricI) + (pTri[1][0] * surfInfo->genBarycentricJ) + (pTri[2][0] * baryCentricK); - boltList[boltNum].position.matrix[1][3] = (pTri[0][1] * surfInfo->genBarycentricI) + (pTri[1][1] * surfInfo->genBarycentricJ) + (pTri[2][1] * baryCentricK); - boltList[boltNum].position.matrix[2][3] = (pTri[0][2] * surfInfo->genBarycentricI) + (pTri[1][2] * surfInfo->genBarycentricJ) + (pTri[2][2] * baryCentricK); + boltList[boltNum].position.matrix[0][3] = + (pTri[0][0] * surfInfo->genBarycentricI) + (pTri[1][0] * surfInfo->genBarycentricJ) + (pTri[2][0] * baryCentricK); + boltList[boltNum].position.matrix[1][3] = + (pTri[0][1] * surfInfo->genBarycentricI) + (pTri[1][1] * surfInfo->genBarycentricJ) + (pTri[2][1] * baryCentricK); + boltList[boltNum].position.matrix[2][3] = + (pTri[0][2] * surfInfo->genBarycentricI) + (pTri[1][2] * surfInfo->genBarycentricJ) + (pTri[2][2] * baryCentricK); // generate a normal to this new triangle VectorSubtract(pTri[0], pTri[1], vec0); @@ -2285,74 +1928,72 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt // right is always straight - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector boltList[boltNum].position.matrix[0][2] = right[0]; boltList[boltNum].position.matrix[1][2] = right[1]; boltList[boltNum].position.matrix[2][2] = right[2]; - } // no, we are looking at a normal model tag - else - { - int *piBoneRefs = (int*) ((byte*)surface + surface->ofsBoneReferences); + else { + int *piBoneRefs = (int *)((byte *)surface + surface->ofsBoneReferences); - // whip through and actually transform each vertex - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - for ( j = 0; j < 3; j++ ) - { -// mdxmWeight_t *w; + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + for (j = 0; j < 3; j++) { + // mdxmWeight_t *w; - VectorClear( pTri[j] ); - // w = v->weights; + VectorClear(pTri[j]); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); - - //bone = bonePtr + piBoneRefs[w->boneIndex]; - pTri[j][0] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3] ); - pTri[j][1] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3] ); - pTri[j][2] += fBoneWeight * ( DotProduct( bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords ) + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3] ); - } - - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; - } - - // clear out used arrays - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); - - // work out actual sides of the tag triangle - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j+1)%3][0] - pTri[j][0]; - sides[j][1] = pTri[(j+1)%3][1] - pTri[j][1]; - sides[j][2] = pTri[(j+1)%3][2] - pTri[j][2]; - } - - // do math trig to work out what the matrix will be from this triangle's translated position - VectorNormalize2( sides[iG2_TRISIDE_LONGEST], axes[0] ); - VectorNormalize2( sides[iG2_TRISIDE_SHORTEST], axes[1] ); - - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize2( axes[0], axes[0] ); - - CrossProduct( sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2] ); - VectorNormalize2( axes[2], axes[2] ); - - // set up location in world space of the origin point in out going matrix - boltList[boltNum].position.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - boltList[boltNum].position.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - boltList[boltNum].position.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; - - // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + + // bone = bonePtr + piBoneRefs[w->boneIndex]; + pTri[j][0] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } + + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); + + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } + + // do math trig to work out what the matrix will be from this triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + + // project shortest side so that it is exactly 90 degrees to the longer side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); + + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); + + // set up location in world space of the origin point in out going matrix + boltList[boltNum].position.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + boltList[boltNum].position.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + boltList[boltNum].position.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + + // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly boltList[boltNum].position.matrix[0][0] = axes[1][0]; boltList[boltNum].position.matrix[0][1] = axes[0][0]; boltList[boltNum].position.matrix[0][2] = -axes[2][0]; @@ -2365,27 +2006,21 @@ void G2_ProcessSurfaceBolt(mdxaBone_v &bonePtr, mdxmSurface_t *surface, int bolt boltList[boltNum].position.matrix[2][1] = axes[0][2]; boltList[boltNum].position.matrix[2][2] = -axes[2][2]; } - } - // now go through all the generated surfaces that aren't included in the model surface hierarchy and create the correct bolt info for them -void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) -{ +void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.Start(); #endif // look through the surfaces off the end of the pre-defined model surfaces - for (size_t i=0; i< ghoul2.mSlist.size(); i++) - { + for (size_t i = 0; i < ghoul2.mSlist.size(); i++) { // only look for bolts if we are actually a generated surface, and not just an overriden one - if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) - { - // well alrighty then. Lets see if there is a bolt that is attempting to use it + if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) { + // well alrighty then. Lets see if there is a bolt that is attempting to use it int boltNum = G2_Find_Bolt_Surface_Num(ghoul2.mBltlist, i, G2SURFACEFLAG_GENERATED); // yes - ok, processing time. - if (boltNum != -1) - { + if (boltNum != -1) { G2_ProcessSurfaceBolt(bonePtr, NULL, boltNum, ghoul2.mBltlist, &ghoul2.mSlist[i], mod_t); } } @@ -2395,191 +2030,165 @@ void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, m #endif } -void RenderSurfaces(CRenderSurface &RS) //also ended up just ripping right from SP. +void RenderSurfaces(CRenderSurface &RS) // also ended up just ripping right from SP. { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_RenderSurfaces.Start(); #endif - int i; - const shader_t *shader = 0; - int offFlags = 0; + int i; + const shader_t *shader = 0; + int offFlags = 0; #ifdef _G2_GORE - bool drawGore = true; + bool drawGore = true; #endif assert(RS.currentModel); assert(RS.currentModel->mdxm); // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)RS.currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)RS.currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!offFlags) - { - if ( RS.cust_shader ) - { - shader = RS.cust_shader; - } - else if ( RS.skin ) - { - int j; + if (!offFlags) { + if (RS.cust_shader) { + shader = RS.cust_shader; + } else if (RS.skin) { + int j; // match the surface name to something in the skin file shader = tr.defaultShader; - for ( j = 0 ; j < RS.skin->numSurfaces ; j++ ) - { + for (j = 0; j < RS.skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( RS.skin->surfaces[j]->name, surfInfo->name ) ) - { - shader = (shader_t*)RS.skin->surfaces[j]->shader; + if (!strcmp(RS.skin->surfaces[j]->name, surfInfo->name)) { + shader = (shader_t *)RS.skin->surfaces[j]->shader; break; } } - } - else - { - shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } else { + shader = R_GetShaderByHandle(surfInfo->shaderIndex); } - //rww - catch surfaces with bad shaders - //assert(shader != tr.defaultShader); - //Alright, this is starting to annoy me because of the state of the assets. Disabling for now. - // we will add shadows even if the main object isn't visible in the view - // stencil shadows can't do personal models unless I polyhedron clip - //using z-fail now so can do personal models -rww - if ( /*!RS.personalModel - && */r_shadows->integer == 2 -// && RS.fogNum == 0 - && (RS.renderfx & RF_SHADOW_PLANE ) - && !(RS.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + // rww - catch surfaces with bad shaders + // assert(shader != tr.defaultShader); + // Alright, this is starting to annoy me because of the state of the assets. Disabling for now. + // we will add shadows even if the main object isn't visible in the view + // stencil shadows can't do personal models unless I polyhedron clip + // using z-fail now so can do personal models -rww + if (/*!RS.personalModel + && */ r_shadows->integer == 2 + // && RS.fogNum == 0 + && (RS.renderfx & RF_SHADOW_PLANE) && !(RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && + shader->sort == + SS_OPAQUE) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = new CRenderableSurface; - if (surface->numVerts >= SHADER_MAX_VERTEXES/2) - { //we need numVerts*2 xyz slots free in tess to do shadow, if this surf is going to exceed that then let's try the lowest lod -rww - mdxmSurface_t *lowsurface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.currentModel->numLods-1); + if (surface->numVerts >= + SHADER_MAX_VERTEXES / + 2) { // we need numVerts*2 xyz slots free in tess to do shadow, if this surf is going to exceed that then let's try the lowest lod -rww + mdxmSurface_t *lowsurface = (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.currentModel->numLods - 1); newSurf->surfaceData = lowsurface; - } - else - { + } else { newSurf->surfaceData = surface; } newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, tr.shadowShader, 0, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, tr.shadowShader, 0, qfalse); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 -// && RS.fogNum == 0 - && (RS.renderfx & RF_SHADOW_PLANE ) - && shader->sort == SS_OPAQUE ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + if (r_shadows->integer == 3 + // && RS.fogNum == 0 + && (RS.renderfx & RF_SHADOW_PLANE) && + shader->sort == + SS_OPAQUE) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = new CRenderableSurface; newSurf->surfaceData = surface; newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, tr.projectionShadowShader, 0, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, tr.projectionShadowShader, 0, qfalse); } // don't add third_person objects if not viewing through a portal - if ( !RS.personalModel ) - { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out + if (!RS.personalModel) { // set the surface info to point at the where the transformed bone list is going to be for when the surface gets rendered out CRenderableSurface *newSurf = new CRenderableSurface; newSurf->surfaceData = surface; newSurf->boneCache = RS.boneCache; - R_AddDrawSurf( (surfaceType_t *)newSurf, (shader_t *)shader, RS.fogNum, qfalse ); + R_AddDrawSurf((surfaceType_t *)newSurf, (shader_t *)shader, RS.fogNum, qfalse); #ifdef _G2_GORE - if (RS.gore_set && drawGore) - { + if (RS.gore_set && drawGore) { int curTime = G2API_GetTime(tr.refdef.time); - std::pair::iterator,std::multimap::iterator> range= + std::pair::iterator, std::multimap::iterator> range = RS.gore_set->mGoreRecords.equal_range(RS.surfaceNum); - std::multimap::iterator k,kcur; - CRenderableSurface *last=newSurf; - for (k=range.first;k!=range.second;) - { - kcur=k; + std::multimap::iterator k, kcur; + CRenderableSurface *last = newSurf; + for (k = range.first; k != range.second;) { + kcur = k; ++k; - GoreTextureCoordinates *tex=FindGoreRecord((*kcur).second.mGoreTag); - if (!tex || // it is gone, lets get rid of it - (kcur->second.mDeleteTime && curTime>=kcur->second.mDeleteTime)) // out of time + GoreTextureCoordinates *tex = FindGoreRecord((*kcur).second.mGoreTag); + if (!tex || // it is gone, lets get rid of it + (kcur->second.mDeleteTime && curTime >= kcur->second.mDeleteTime)) // out of time { - if (tex) - { + if (tex) { (*tex).~GoreTextureCoordinates(); - //I don't know what's going on here, it should call the destructor for - //this when it erases the record but sometimes it doesn't. -rww + // I don't know what's going on here, it should call the destructor for + // this when it erases the record but sometimes it doesn't. -rww } RS.gore_set->mGoreRecords.erase(kcur); - } - else if (tex->tex[RS.lod]) - { + } else if (tex->tex[RS.lod]) { CRenderableSurface *newSurf2 = AllocRS(); - *newSurf2=*newSurf; - newSurf2->goreChain=0; - newSurf2->alternateTex=tex->tex[RS.lod]; - newSurf2->scale=1.0f; - newSurf2->fade=1.0f; - newSurf2->impactTime=1.0f; // done with - int magicFactor42=500; // ms, impact time - if (curTime>(*kcur).second.mGoreGrowStartTime && curTime<(*kcur).second.mGoreGrowStartTime+magicFactor42) - { - newSurf2->impactTime=float(curTime-(*kcur).second.mGoreGrowStartTime)/float(magicFactor42); // linear + *newSurf2 = *newSurf; + newSurf2->goreChain = 0; + newSurf2->alternateTex = tex->tex[RS.lod]; + newSurf2->scale = 1.0f; + newSurf2->fade = 1.0f; + newSurf2->impactTime = 1.0f; // done with + int magicFactor42 = 500; // ms, impact time + if (curTime > (*kcur).second.mGoreGrowStartTime && curTime < (*kcur).second.mGoreGrowStartTime + magicFactor42) { + newSurf2->impactTime = float(curTime - (*kcur).second.mGoreGrowStartTime) / float(magicFactor42); // linear } - if (curTime<(*kcur).second.mGoreGrowEndTime) - { - newSurf2->scale=1.0f/((curTime-(*kcur).second.mGoreGrowStartTime)*(*kcur).second.mGoreGrowFactor + (*kcur).second.mGoreGrowOffset); - if (newSurf2->scale<1.0f) - { - newSurf2->scale=1.0f; + if (curTime < (*kcur).second.mGoreGrowEndTime) { + newSurf2->scale = + 1.0f / ((curTime - (*kcur).second.mGoreGrowStartTime) * (*kcur).second.mGoreGrowFactor + (*kcur).second.mGoreGrowOffset); + if (newSurf2->scale < 1.0f) { + newSurf2->scale = 1.0f; } } shader_t *gshader; - if ((*kcur).second.shader) - { - gshader=R_GetShaderByHandle((*kcur).second.shader); - } - else - { - gshader=R_GetShaderByHandle(goreShader); + if ((*kcur).second.shader) { + gshader = R_GetShaderByHandle((*kcur).second.shader); + } else { + gshader = R_GetShaderByHandle(goreShader); } // Set fade on surf. - //Only if we have a fade time set, and let us fade on rgb if we want -rww - if ((*kcur).second.mDeleteTime && (*kcur).second.mFadeTime) - { - if ((*kcur).second.mDeleteTime - curTime < (*kcur).second.mFadeTime) - { - newSurf2->fade=(float)((*kcur).second.mDeleteTime - curTime)/(*kcur).second.mFadeTime; - if ((*kcur).second.mFadeRGB) - { //RGB fades are scaled from 2.0f to 3.0f (simply to differentiate) + // Only if we have a fade time set, and let us fade on rgb if we want -rww + if ((*kcur).second.mDeleteTime && (*kcur).second.mFadeTime) { + if ((*kcur).second.mDeleteTime - curTime < (*kcur).second.mFadeTime) { + newSurf2->fade = (float)((*kcur).second.mDeleteTime - curTime) / (*kcur).second.mFadeTime; + if ((*kcur).second.mFadeRGB) { // RGB fades are scaled from 2.0f to 3.0f (simply to differentiate) newSurf2->fade += 2.0f; - if (newSurf2->fade < 2.01f) - { + if (newSurf2->fade < 2.01f) { newSurf2->fade = 2.01f; } } } } - last->goreChain=newSurf2; - last=newSurf2; - R_AddDrawSurf( (surfaceType_t *)newSurf2,gshader, RS.fogNum, qfalse ); + last->goreChain = newSurf2; + last = newSurf2; + R_AddDrawSurf((surfaceType_t *)newSurf2, gshader, RS.fogNum, qfalse); } } } @@ -2588,14 +2197,12 @@ void RenderSurfaces(CRenderSurface &RS) //also ended up just ripping right from } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { RS.surfaceNum = surfInfo->childIndexes[i]; RenderSurfaces(RS); } @@ -2606,53 +2213,46 @@ void RenderSurfaces(CRenderSurface &RS) //also ended up just ripping right from } // Go through the model and deal with just the surfaces that are tagged as bolt on points - this is for the server side skeleton construction -void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, - mdxaBone_v &bonePtr, model_t *currentModel, int lod, boltInfo_v &boltList) -{ +void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, mdxaBone_v &bonePtr, model_t *currentModel, int lod, boltInfo_v &boltList) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_ProcessModelBoltSurfaces.Start(); #endif - int i; - int offFlags = 0; + int i; + int offFlags = 0; // back track and get the surfinfo struct for this surface - mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); - mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); - mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->mdxm + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); // see if we have an override surface in the surface list - surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // is this surface considered a bolt surface? - if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) - { + if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) { // well alrighty then. Lets see if there is a bolt that is attempting to use it int boltNum = G2_Find_Bolt_Surface_Num(boltList, surfaceNum, 0); // yes - ok, processing time. - if (boltNum != -1) - { + if (boltNum != -1) { G2_ProcessSurfaceBolt(bonePtr, surface, boltNum, boltList, surfOverride, currentModel); } } // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { return; } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { ProcessModelBoltSurfaces(surfInfo->childIndexes[i], rootSList, bonePtr, currentModel, lod, boltList); } @@ -2661,55 +2261,48 @@ void ProcessModelBoltSurfaces(int surfaceNum, surfaceInfo_v &rootSList, #endif } - // build the used bone list so when doing bone transforms we can determine if we need to do it or not -void G2_ConstructUsedBoneList(CConstructBoneList &CBL) -{ - int i, j; - int offFlags = 0; +void G2_ConstructUsedBoneList(CConstructBoneList &CBL) { + int i, j; + int offFlags = 0; // back track and get the surfinfo struct for this surface - const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); - const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)CBL.currentModel->mdxm + sizeof(mdxmHeader_t)); - const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); - const model_t *mod_a = R_GetModelByHandle(CBL.currentModel->mdxm->animIndex); - const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); - const mdxaSkel_t *skel, *childSkel; + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)CBL.currentModel->mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const model_t *mod_a = R_GetModelByHandle(CBL.currentModel->mdxm->animIndex); + const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel, *childSkel; // see if we have an override surface in the surface list - const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); // really, we should use the default flags for this surface unless it's been overriden offFlags = surfInfo->flags; // set the off flags if we have some - if (surfOverride) - { + if (surfOverride) { offFlags = surfOverride->offFlags; } // if this surface is not off, add it to the shader render list - if (!(offFlags & G2SURFACEFLAG_OFF)) - { - int *bonesReferenced = (int *)((byte*)surface + surface->ofsBoneReferences); + if (!(offFlags & G2SURFACEFLAG_OFF)) { + int *bonesReferenced = (int *)((byte *)surface + surface->ofsBoneReferences); // now whip through the bones this surface uses - for (i=0; inumBoneReferences;i++) - { + for (i = 0; i < surface->numBoneReferences; i++) { int iBoneIndex = bonesReferenced[i]; CBL.boneUsedList[iBoneIndex] = 1; // now go and check all the descendant bones attached to this bone and see if any have the always flag on them. If so, activate them - skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); + skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); // for every child bone... - for (j=0; j< skel->numChildren; j++) - { + for (j = 0; j < skel->numChildren; j++) { // get the skel data struct for each child bone of the referenced bone - childSkel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); + childSkel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); // does it have the always on flag on? - if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) - { + if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) { // yes, make sure it's in the list of bones to be transformed. CBL.boneUsedList[skel->children[j]] = 1; } @@ -2718,94 +2311,77 @@ void G2_ConstructUsedBoneList(CConstructBoneList &CBL) // now we need to ensure that the parents of this bone are actually active... // int iParentBone = skel->parent; - while (iParentBone != -1) - { - if (CBL.boneUsedList[iParentBone]) // no need to go higher + while (iParentBone != -1) { + if (CBL.boneUsedList[iParentBone]) // no need to go higher break; CBL.boneUsedList[iParentBone] = 1; skel = (mdxaSkel_t *)((byte *)mod_a->mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iParentBone]); iParentBone = skel->parent; } } - } - else - // if we are turning off all descendants, then stop this recursion now - if (offFlags & G2SURFACEFLAG_NODESCENDANTS) - { - return; - } + } else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) { + return; + } // now recursively call for the children - for (i=0; i< surfInfo->numChildren; i++) - { + for (i = 0; i < surfInfo->numChildren; i++) { CBL.surfaceNum = surfInfo->childIndexes[i]; G2_ConstructUsedBoneList(CBL); } } - // sort all the ghoul models in this list so if they go in reference order. This will ensure the bolt on's are attached to the right place // on the previous model, since it ensures the model being attached to is built and rendered first. // NOTE!! This assumes at least one model will NOT have a parent. If it does - we are screwed -static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int * const modelList, int * const modelCount) -{ - int startPoint, endPoint; - int i, boltTo, j; +static void G2_Sort_Models(CGhoul2Info_v &ghoul2, int *const modelList, int *const modelCount) { + int startPoint, endPoint; + int i, boltTo, j; *modelCount = 0; // first walk all the possible ghoul2 models, and stuff the out array with those with no parents - for (i=0; i> MODEL_SHIFT) & MODEL_AND; // is it any of the models we just added to the list? - for (j=startPoint; jmdxm); // point at first lod list - byte *current = (byte*)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); + byte *current = (byte *)((intptr_t)mod->mdxm + (intptr_t)mod->mdxm->ofsLODs); int i; - //walk the lods - assert(lod>=0&&lodmdxm->numLODs); - for (i=0; i= 0 && lod < mod->mdxm->numLODs); + for (i = 0; i < lod; i++) { mdxmLOD_t *lodData = (mdxmLOD_t *)current; current += lodData->ofsEnd; } @@ -2841,7 +2415,7 @@ void *G2_FindSurface_BC(const model_s *mod, int index, int lod) mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; // we are now looking at the offset array - assert(index>=0&&indexmdxm->numSurfaces); + assert(index >= 0 && index < mod->mdxm->numSurfaces); current += indexes->offsets[index]; return (void *)current; @@ -2850,22 +2424,21 @@ void *G2_FindSurface_BC(const model_s *mod, int index, int lod) //#define G2EVALRENDER // We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place -void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, const model_t *mod,mdxaBone_t &retMatrix) -{ - mdxmVertex_t *v, *vert0, *vert1, *vert2; - matrix3_t axes, sides; - float pTri[3][3], d; - int j, k; +void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int boltNum, boltInfo_v &boltList, const surfaceInfo_t *surfInfo, + const model_t *mod, mdxaBone_t &retMatrix) { + mdxmVertex_t *v, *vert0, *vert1, *vert2; + matrix3_t axes, sides; + float pTri[3][3], d; + int j, k; // now there are two types of tag surface - model ones and procedural generated types - lets decide which one we have here. - if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) - { + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) { int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; - int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; // find original surface our original poly was in. - mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); - mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + mdxmSurface_t *originalSurf = (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); // get the original polys indexes int index0 = originalTriangleIndexes[polyNumber].indexes[0]; @@ -2873,82 +2446,79 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, int index2 = originalTriangleIndexes[polyNumber].indexes[2]; // decide where the original verts are - vert0 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert0+=index0; + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; - vert1 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert1+=index1; + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; - vert2 = (mdxmVertex_t *) ((byte *)originalSurf + originalSurf->ofsVerts); - vert2+=index2; + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; // clear out the triangle verts to be - VectorClear( pTri[0] ); - VectorClear( pTri[1] ); - VectorClear( pTri[2] ); - int *piBoneReferences = (int*) ((byte*)originalSurf + originalSurf->ofsBoneReferences); + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + int *piBoneReferences = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); -// mdxmWeight_t *w; + // mdxmWeight_t *w; // now go and transform just the points we need from the surface that was hit originally -// w = vert0->weights; + // w = vert0->weights; float fTotalWeight = 0.0f; - int iNumWeights = G2_GetVertWeights( vert0 ); - for ( k = 0 ; k < iNumWeights ; k++ ) - { - int iBoneIndex = G2_GetVertBoneIndex( vert0, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert0, k, fTotalWeight, iNumWeights ); + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[0][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert0->vertCoords ) + bone.matrix[0][3] ); - pTri[0][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert0->vertCoords ) + bone.matrix[1][3] ); - pTri[0][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert0->vertCoords ) + bone.matrix[2][3] ); + pTri[0][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert0->vertCoords) + bone.matrix[0][3]); + pTri[0][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert0->vertCoords) + bone.matrix[1][3]); + pTri[0][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert0->vertCoords) + bone.matrix[2][3]); } -// w = vert1->weights; + // w = vert1->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert1 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert1, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert1, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[1][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert1->vertCoords ) + bone.matrix[0][3] ); - pTri[1][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert1->vertCoords ) + bone.matrix[1][3] ); - pTri[1][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert1->vertCoords ) + bone.matrix[2][3] ); + pTri[1][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert1->vertCoords) + bone.matrix[0][3]); + pTri[1][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert1->vertCoords) + bone.matrix[1][3]); + pTri[1][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert1->vertCoords) + bone.matrix[2][3]); } -// w = vert2->weights; + // w = vert2->weights; fTotalWeight = 0.0f; - iNumWeights = G2_GetVertWeights( vert2 ); - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( vert2, k ); - float fBoneWeight = G2_GetVertBoneWeight( vert2, k, fTotalWeight, iNumWeights ); + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[2][0] += fBoneWeight * ( DotProduct( bone.matrix[0], vert2->vertCoords ) + bone.matrix[0][3] ); - pTri[2][1] += fBoneWeight * ( DotProduct( bone.matrix[1], vert2->vertCoords ) + bone.matrix[1][3] ); - pTri[2][2] += fBoneWeight * ( DotProduct( bone.matrix[2], vert2->vertCoords ) + bone.matrix[2][3] ); + pTri[2][0] += fBoneWeight * (DotProduct(bone.matrix[0], vert2->vertCoords) + bone.matrix[0][3]); + pTri[2][1] += fBoneWeight * (DotProduct(bone.matrix[1], vert2->vertCoords) + bone.matrix[1][3]); + pTri[2][2] += fBoneWeight * (DotProduct(bone.matrix[2], vert2->vertCoords) + bone.matrix[2][3]); } - vec3_t normal; + vec3_t normal; vec3_t up; vec3_t right; vec3_t vec0, vec1; @@ -2988,79 +2558,74 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, // right is always straight - CrossProduct( normal, up, right ); + CrossProduct(normal, up, right); // that's the up vector retMatrix.matrix[0][2] = right[0]; retMatrix.matrix[1][2] = right[1]; retMatrix.matrix[2][2] = right[2]; - } // no, we are looking at a normal model tag - else - { - // whip through and actually transform each vertex - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); - for ( j = 0; j < 3; j++ ) - { -// mdxmWeight_t *w; + else { + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + int *piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); + for (j = 0; j < 3; j++) { + // mdxmWeight_t *w; - VectorClear( pTri[j] ); - // w = v->weights; + VectorClear(pTri[j]); + // w = v->weights; - const int iNumWeights = G2_GetVertWeights( v ); + const int iNumWeights = G2_GetVertWeights(v); float fTotalWeight = 0.0f; - for ( k = 0 ; k < iNumWeights ; k++) - { - int iBoneIndex = G2_GetVertBoneIndex( v, k ); - float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + for (k = 0; k < iNumWeights; k++) { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); #ifdef G2EVALRENDER - const mdxaBone_t &bone=boneCache.EvalRender(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.EvalRender(piBoneReferences[iBoneIndex]); #else - const mdxaBone_t &bone=boneCache.Eval(piBoneReferences[iBoneIndex]); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); #endif - pTri[j][0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); - pTri[j][1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); - pTri[j][2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); - } + pTri[j][0] += fBoneWeight * (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + pTri[j][1] += fBoneWeight * (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + pTri[j][2] += fBoneWeight * (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); + } - v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; - } + v++; // = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } - // clear out used arrays - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); - // work out actual sides of the tag triangle - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[(j+1)%3][0] - pTri[j][0]; - sides[j][1] = pTri[(j+1)%3][1] - pTri[j][1]; - sides[j][2] = pTri[(j+1)%3][2] - pTri[j][2]; - } + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } - // do math trig to work out what the matrix will be from this triangle's translated position - VectorNormalize2( sides[iG2_TRISIDE_LONGEST], axes[0] ); - VectorNormalize2( sides[iG2_TRISIDE_SHORTEST], axes[1] ); + // do math trig to work out what the matrix will be from this triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize2( axes[0], axes[0] ); + // project shortest side so that it is exactly 90 degrees to the longer side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); - CrossProduct( sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2] ); - VectorNormalize2( axes[2], axes[2] ); + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); - // set up location in world space of the origin point in out going matrix - retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; - retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; - retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + // set up location in world space of the origin point in out going matrix + retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; - // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly + // copy axis to matrix - do some magic to orient minus Y to positive X and so on so bolt on stuff is oriented correctly retMatrix.matrix[0][0] = axes[1][0]; retMatrix.matrix[0][1] = axes[0][0]; retMatrix.matrix[0][2] = -axes[2][0]; @@ -3073,29 +2638,26 @@ void G2_ProcessSurfaceBolt2(CBoneCache &boneCache, const mdxmSurface_t *surface, retMatrix.matrix[2][1] = axes[0][2]; retMatrix.matrix[2][2] = -axes[2][2]; } - } -void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix) -{ - if (!ghoul2.mBoneCache) - { - retMatrix=identityMatrix; +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2, int boltNum, const vec3_t scale, mdxaBone_t &retMatrix) { + if (!ghoul2.mBoneCache) { + retMatrix = identityMatrix; return; } assert(ghoul2.mBoneCache); - CBoneCache &boneCache=*ghoul2.mBoneCache; + CBoneCache &boneCache = *ghoul2.mBoneCache; assert(boneCache.mod); - boltInfo_v &boltList=ghoul2.mBltlist; + boltInfo_v &boltList = ghoul2.mBltlist; - //Raz: This was causing a client crash when rendering a model with no valid g2 bolts, such as Ragnos =] - if ( boltList.size() < 1 ) { - retMatrix=identityMatrix; + // Raz: This was causing a client crash when rendering a model with no valid g2 bolts, such as Ragnos =] + if (boltList.size() < 1) { + retMatrix = identityMatrix; return; } - assert(boltNum>=0&&boltNum<(int)boltList.size()); -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. + assert(boltNum >= 0 && boltNum < (int)boltList.size()); +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. if (boltNum < 0 || boltNum >= boltList.size()) { char fName[MAX_QPATH]; @@ -3123,87 +2685,73 @@ void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxa Com_Error(ERR_DROP, "Write down or save this error message, show it to Rich\nBad bolt index on model %s (filename %s), index %i boltlink %i\n", mName, fName, boltNum, bLink); } #endif - if (boltList[boltNum].boneNumber>=0) - { - mdxaSkel_t *skel; + if (boltList[boltNum].boneNumber >= 0) { + mdxaSkel_t *skel; mdxaSkelOffsets_t *offsets; offsets = (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); skel = (mdxaSkel_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t) + offsets->offsets[boltList[boltNum].boneNumber]); Multiply_3x4Matrix(&retMatrix, (mdxaBone_t *)&boneCache.EvalUnsmooth(boltList[boltNum].boneNumber), &skel->BasePoseMat); - } - else if (boltList[boltNum].surfaceNumber>=0) - { - const surfaceInfo_t *surfInfo=0; + } else if (boltList[boltNum].surfaceNumber >= 0) { + const surfaceInfo_t *surfInfo = 0; { - for (size_t i=0;isurface<10000) - { - surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod,surfInfo->surface, 0); + if (!surface && surfInfo && surfInfo->surface < 10000) { + surface = (mdxmSurface_t *)G2_FindSurface_BC(boneCache.mod, surfInfo->surface, 0); } - G2_ProcessSurfaceBolt2(boneCache,surface,boltNum,boltList,surfInfo,(model_t *)boneCache.mod,retMatrix); - } - else - { - // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix - retMatrix=identityMatrix; + G2_ProcessSurfaceBolt2(boneCache, surface, boltNum, boltList, surfInfo, (model_t *)boneCache.mod, retMatrix); + } else { + // we have a bolt without a bone or surface, not a huge problem but we ought to at least clear the bolt matrix + retMatrix = identityMatrix; } } -static void RootMatrix(CGhoul2Info_v &ghoul2,int time,const vec3_t scale,mdxaBone_t &retMatrix) -{ +static void RootMatrix(CGhoul2Info_v &ghoul2, int time, const vec3_t scale, mdxaBone_t &retMatrix) { int i; - for (i=0; ivalue); } @@ -3212,74 +2760,68 @@ static inline bool bInShadowRange(vec3_t location) R_AddGHOULSurfaces ============== */ -void R_AddGhoulSurfaces( trRefEntity_t *ent ) { +void R_AddGhoulSurfaces(trRefEntity_t *ent) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_R_AddGHOULSurfaces.Start(); #endif - shader_t *cust_shader = 0; + shader_t *cust_shader = 0; #ifdef _G2_GORE - shader_t *gore_shader = 0; + shader_t *gore_shader = 0; #endif - int fogNum = 0; - qboolean personalModel; - int cull; - int i, whichLod, j; - skin_t *skin; - int modelCount; - mdxaBone_t rootMatrix; - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->e.ghoul2); - - if ( !ghoul2.IsValid() ) - { + int fogNum = 0; + qboolean personalModel; + int cull; + int i, whichLod, j; + skin_t *skin; + int modelCount; + mdxaBone_t rootMatrix; + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->e.ghoul2); + + if (!ghoul2.IsValid()) { return; } // if we don't want server ghoul2 models and this is one, or we just don't want ghoul2 models at all, then return - if (r_noServerGhoul2->integer) - { + if (r_noServerGhoul2->integer) { return; } - if (!G2_SetupModelPointers(ghoul2)) - { + if (!G2_SetupModelPointers(ghoul2)) { return; } - int currentTime=G2API_GetTime(tr.refdef.time); - + int currentTime = G2API_GetTime(tr.refdef.time); // cull the entire model if merged bounding box of both frames // is outside the view frustum. - cull = R_GCullModel (ent ); - if ( cull == CULL_OUT ) - { + cull = R_GCullModel(ent); + if (cull == CULL_OUT) { return; } - HackadelicOnClient=true; + HackadelicOnClient = true; // are any of these models setting a new origin? - RootMatrix(ghoul2,currentTime, ent->e.modelScale,rootMatrix); + RootMatrix(ghoul2, currentTime, ent->e.modelScale, rootMatrix); - // don't add third_person objects if not in a portal + // don't add third_person objects if not in a portal personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); int modelList[256]; - assert(ghoul2.size()<=255); - modelList[255]=548; + assert(ghoul2.size() <= 255); + modelList[255] = 548; // set up lighting now that we know we aren't culled - if ( !personalModel || r_shadows->integer > 1 ) { - R_SetupEntityLighting( &tr.refdef, ent ); + if (!personalModel || r_shadows->integer > 1) { + R_SetupEntityLighting(&tr.refdef, ent); } // see if we are in a fog volume - fogNum = R_GComputeFogNum( ent ); + fogNum = R_GComputeFogNum(ent); // order sort the ghoul 2 models so bolt ons get bolted to the right model G2_Sort_Models(ghoul2, modelList, &modelCount); - assert(modelList[255]==548); + assert(modelList[255] == 548); #ifdef _G2_GORE - if (goreShader == -1) - { - goreShader=RE_RegisterShader("gfx/damage/burnmark1"); + if (goreShader == -1) { + goreShader = RE_RegisterShader("gfx/damage/burnmark1"); } #endif @@ -3287,75 +2829,62 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent ) { G2_GenerateWorldMatrix(ent->e.angles, ent->e.origin); // walk each possible model for this entity and try rendering it out - for (j=0; je.customShader) - { - cust_shader = R_GetShaderByHandle(ent->e.customShader ); - } - else - { + if (ent->e.customShader) { + cust_shader = R_GetShaderByHandle(ent->e.customShader); + } else { cust_shader = NULL; // figure out the custom skin thing - if (ghoul2[i].mCustomSkin) - { - skin = R_GetSkinByHandle(ghoul2[i].mCustomSkin ); - } - else if (ent->e.customSkin) - { - skin = R_GetSkinByHandle(ent->e.customSkin ); - } - else if ( ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins ) - { - skin = R_GetSkinByHandle( ghoul2[i].mSkin ); + if (ghoul2[i].mCustomSkin) { + skin = R_GetSkinByHandle(ghoul2[i].mCustomSkin); + } else if (ent->e.customSkin) { + skin = R_GetSkinByHandle(ent->e.customSkin); + } else if (ghoul2[i].mSkin > 0 && ghoul2[i].mSkin < tr.numSkins) { + skin = R_GetSkinByHandle(ghoul2[i].mSkin); } } - if (j&&ghoul2[i].mModelBoltLink != -1) - { - int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (j && ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; - G2_GetBoltMatrixLow(ghoul2[boltMod],boltNum,ent->e.modelScale,bolt); - G2_TransformGhoulBones(ghoul2[i].mBlist,bolt, ghoul2[i],currentTime); - } - else - { - G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i],currentTime); + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, ent->e.modelScale, bolt); + G2_TransformGhoulBones(ghoul2[i].mBlist, bolt, ghoul2[i], currentTime); + } else { + G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i], currentTime); } - whichLod = G2_ComputeLOD( ent, ghoul2[i].currentModel, ghoul2[i].mLodBias ); - G2_FindOverrideSurface(-1,ghoul2[i].mSlist); //reset the quick surface override lookup; + whichLod = G2_ComputeLOD(ent, ghoul2[i].currentModel, ghoul2[i].mLodBias); + G2_FindOverrideSurface(-1, ghoul2[i].mSlist); // reset the quick surface override lookup; #ifdef _G2_GORE - CGoreSet *gore=0; - if (ghoul2[i].mGoreSetTag) - { - gore=FindGoreSet(ghoul2[i].mGoreSetTag); + CGoreSet *gore = 0; + if (ghoul2[i].mGoreSetTag) { + gore = FindGoreSet(ghoul2[i].mGoreSetTag); if (!gore) // my gore is gone, so remove it { - ghoul2[i].mGoreSetTag=0; + ghoul2[i].mGoreSetTag = 0; } } - CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, (model_t *)ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist, gore_shader, gore); + CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, + (model_t *)ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist, gore_shader, gore); #else - CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, (model_t *)ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist); + CRenderSurface RS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, cust_shader, fogNum, personalModel, ghoul2[i].mBoneCache, ent->e.renderfx, skin, + (model_t *)ghoul2[i].currentModel, whichLod, ghoul2[i].mBltlist); #endif - if (!personalModel && (RS.renderfx & RF_SHADOW_PLANE) && !bInShadowRange(ent->e.origin)) - { + if (!personalModel && (RS.renderfx & RF_SHADOW_PLANE) && !bInShadowRange(ent->e.origin)) { RS.renderfx |= RF_NOSHADOW; } RenderSurfaces(RS); } } - HackadelicOnClient=false; + HackadelicOnClient = false; #ifdef G2_PERFORMANCE_ANALYSIS G2Time_R_AddGHOULSurfaces += G2PerformanceTimer_R_AddGHOULSurfaces.End(); @@ -3366,22 +2895,16 @@ void R_AddGhoulSurfaces( trRefEntity_t *ent ) { qboolean G2API_OverrideServerWithClientData(CGhoul2Info *serverInstance); #endif -bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) -{ +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum) { G2_SetupModelPointers(ghlInfo); // not sure if I still need this test, probably - if (ghlInfo->mSkelFrameNum!=frameNum|| - !ghlInfo->mBoneCache|| - ghlInfo->mBoneCache->mod!=ghlInfo->currentModel) - { + if (ghlInfo->mSkelFrameNum != frameNum || !ghlInfo->mBoneCache || ghlInfo->mBoneCache->mod != ghlInfo->currentModel) { #ifdef _G2_LISTEN_SERVER_OPT - if (ghlInfo->entityNum != ENTITYNUM_NONE && - G2API_OverrideServerWithClientData(ghlInfo)) - { //if we can manage this, then we don't have to reconstruct + if (ghlInfo->entityNum != ENTITYNUM_NONE && G2API_OverrideServerWithClientData(ghlInfo)) { // if we can manage this, then we don't have to reconstruct return false; } #endif - ghlInfo->mSkelFrameNum=frameNum; + ghlInfo->mSkelFrameNum = frameNum; return true; } return false; @@ -3392,46 +2915,39 @@ bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) G2_ConstructGhoulSkeleton - builds a complete skeleton for all ghoul models in a CGhoul2Info_v class - using LOD 0 ============== */ -void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool checkForNewOrigin,const vec3_t scale) -{ +void G2_ConstructGhoulSkeleton(CGhoul2Info_v &ghoul2, const int frameNum, bool checkForNewOrigin, const vec3_t scale) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_G2_ConstructGhoulSkeleton.Start(); #endif - int i, j; - int modelCount; - mdxaBone_t rootMatrix; + int i, j; + int modelCount; + mdxaBone_t rootMatrix; int modelList[256]; - assert(ghoul2.size()<=255); - modelList[255]=548; + assert(ghoul2.size() <= 255); + modelList[255] = 548; - if (checkForNewOrigin) - { - RootMatrix(ghoul2,frameNum,scale,rootMatrix); - } - else - { + if (checkForNewOrigin) { + RootMatrix(ghoul2, frameNum, scale, rootMatrix); + } else { rootMatrix = identityMatrix; } G2_Sort_Models(ghoul2, modelList, &modelCount); - assert(modelList[255]==548); + assert(modelList[255] == 548); - for (j=0; j> MODEL_SHIFT) & MODEL_AND; - int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + if (ghoul2[i].mValid) { + if (j && ghoul2[i].mModelBoltLink != -1) { + int boltMod = (ghoul2[i].mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; mdxaBone_t bolt; - G2_GetBoltMatrixLow(ghoul2[boltMod],boltNum,scale,bolt); - G2_TransformGhoulBones(ghoul2[i].mBlist,bolt,ghoul2[i],frameNum,checkForNewOrigin); + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, scale, bolt); + G2_TransformGhoulBones(ghoul2[i].mBlist, bolt, ghoul2[i], frameNum, checkForNewOrigin); } #ifdef _G2_LISTEN_SERVER_OPT else if (ghoul2[i].entityNum == ENTITYNUM_NONE || ghoul2[i].mSkelFrameNum != frameNum) @@ -3439,7 +2955,7 @@ void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool ch else #endif { - G2_TransformGhoulBones(ghoul2[i].mBlist,rootMatrix,ghoul2[i],frameNum,checkForNewOrigin); + G2_TransformGhoulBones(ghoul2[i].mBlist, rootMatrix, ghoul2[i], frameNum, checkForNewOrigin); } } } @@ -3448,40 +2964,37 @@ void G2_ConstructGhoulSkeleton( CGhoul2Info_v &ghoul2,const int frameNum,bool ch #endif } -static inline float G2_GetVertBoneWeightNotSlow( const mdxmVertex_t *pVert, const int iWeightNum) -{ +static inline float G2_GetVertBoneWeightNotSlow(const mdxmVertex_t *pVert, const int iWeightNum) { float fBoneWeight; int iTemp = pVert->BoneWeightings[iWeightNum]; - iTemp|= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT+(iWeightNum*2)) ) & iG2_BONEWEIGHT_TOPBITS_AND; + iTemp |= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT + (iWeightNum * 2))) & iG2_BONEWEIGHT_TOPBITS_AND; fBoneWeight = fG2_BONEWEIGHT_RECIPROCAL_MULT * iTemp; return fBoneWeight; } -//This is a slightly mangled version of the same function from the sof2sp base. -//It provides a pretty significant performance increase over the existing one. -void RB_SurfaceGhoul( CRenderableSurface *surf ) -{ +// This is a slightly mangled version of the same function from the sof2sp base. +// It provides a pretty significant performance increase over the existing one. +void RB_SurfaceGhoul(CRenderableSurface *surf) { #ifdef G2_PERFORMANCE_ANALYSIS G2PerformanceTimer_RB_SurfaceGhoul.Start(); #endif - static int j, k; - static int baseIndex, baseVertex; - static int numVerts; - static mdxmVertex_t *v; - static int *triangles; - static int indexes; - static glIndex_t *tessIndexes; + static int j, k; + static int baseIndex, baseVertex; + static int numVerts; + static mdxmVertex_t *v; + static int *triangles; + static int indexes; + static glIndex_t *tessIndexes; static mdxmVertexTexCoord_t *pTexCoords; - static int *piBoneReferences; + static int *piBoneReferences; #ifdef _G2_GORE - if (surf->alternateTex) - { + if (surf->alternateTex) { // a gore surface ready to go. /* @@ -3494,95 +3007,83 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) sizeof(int)*newNumTris*3; // new indecies */ - int *data=(int *)surf->alternateTex; - numVerts=*data++; - indexes=(*data++); + int *data = (int *)surf->alternateTex; + numVerts = *data++; + indexes = (*data++); // first up, sanity check our numbers - RB_CheckOverflow(numVerts,indexes); - indexes*=3; + RB_CheckOverflow(numVerts, indexes); + indexes *= 3; - data+=numVerts; + data += numVerts; baseIndex = tess.numIndexes; baseVertex = tess.numVertexes; - memcpy(&tess.xyz[baseVertex][0],data,sizeof(float)*4*numVerts); - data+=4*numVerts; - memcpy(&tess.normal[baseVertex][0],data,sizeof(float)*4*numVerts); - data+=4*numVerts; - assert(numVerts>0); + memcpy(&tess.xyz[baseVertex][0], data, sizeof(float) * 4 * numVerts); + data += 4 * numVerts; + memcpy(&tess.normal[baseVertex][0], data, sizeof(float) * 4 * numVerts); + data += 4 * numVerts; + assert(numVerts > 0); - //float *texCoords = tess.texCoords[0][baseVertex]; + // float *texCoords = tess.texCoords[0][baseVertex]; float *texCoords = tess.texCoords[baseVertex][0]; int hack = baseVertex; - //rww - since the array is arranged as such we cannot increment - //the relative memory position to get where we want. Maybe this - //is why sof2 has the texCoords array reversed. In any case, I - //am currently too lazy to get around it. - //Or can you += array[.][x]+2? - if (surf->scale>1.0f) - { - for ( j = 0; j < numVerts; j++) - { - texCoords[0]=((*(float *)data)-0.5f)*surf->scale+0.5f; + // rww - since the array is arranged as such we cannot increment + // the relative memory position to get where we want. Maybe this + // is why sof2 has the texCoords array reversed. In any case, I + // am currently too lazy to get around it. + // Or can you += array[.][x]+2? + if (surf->scale > 1.0f) { + for (j = 0; j < numVerts; j++) { + texCoords[0] = ((*(float *)data) - 0.5f) * surf->scale + 0.5f; data++; - texCoords[1]=((*(float *)data)-0.5f)*surf->scale+0.5f; + texCoords[1] = ((*(float *)data) - 0.5f) * surf->scale + 0.5f; data++; - //texCoords+=2;// Size of gore (s,t). + // texCoords+=2;// Size of gore (s,t). hack++; texCoords = tess.texCoords[hack][0]; } - } - else - { - for (j=0;jfade) - { + // now check for fade overrides -rww + if (surf->fade) { static int lFade; static int j; - if (surf->fade<1.0) - { + if (surf->fade < 1.0) { tess.fading = true; - lFade = Q_ftol(254.4f*surf->fade); + lFade = Q_ftol(254.4f * surf->fade); - for (j=0;jfade > 2.0f && surf->fade < 3.0f) - { //hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww + } else if (surf->fade > 2.0f && surf->fade < 3.0f) { // hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww tess.fading = true; - lFade = Q_ftol(254.4f*(surf->fade-2.0f)); + lFade = Q_ftol(254.4f * (surf->fade - 2.0f)); - for (j=0;jsurfaceData; + mdxmSurface_t *surface = surf->surfaceData; CBoneCache *bones = surf->boneCache; -#ifndef _G2_GORE //we use this later, for gore +#ifndef _G2_GORE // we use this later, for gore delete surf; #endif // first up, sanity check our numbers - RB_CheckOverflow( surface->numVerts, surface->numTriangles ); + RB_CheckOverflow(surface->numVerts, surface->numTriangles); // // deform the vertexes by the lerped bones @@ -3609,7 +3110,7 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) // first up, sanity check our numbers baseVertex = tess.numVertexes; - triangles = (int *) ((byte *)surface + surface->ofsTriangles); + triangles = (int *)((byte *)surface + surface->ofsTriangles); baseIndex = tess.numIndexes; #if 0 indexes = surface->numTriangles * 3; @@ -3620,20 +3121,20 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) #else indexes = surface->numTriangles; //*3; //unrolled 3 times, don't multiply tessIndexes = &tess.indexes[baseIndex]; - for (j = 0 ; j < indexes ; j++) { + for (j = 0; j < indexes; j++) { *tessIndexes++ = baseVertex + *triangles++; *tessIndexes++ = baseVertex + *triangles++; *tessIndexes++ = baseVertex + *triangles++; } - tess.numIndexes += indexes*3; + tess.numIndexes += indexes * 3; #endif numVerts = surface->numVerts; - piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + piBoneReferences = (int *)((byte *)surface + surface->ofsBoneReferences); baseVertex = tess.numVertexes; - v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); - pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + pTexCoords = (mdxmVertexTexCoord_t *)&v[numVerts]; // if (r_ghoul2fastnormals&&r_ghoul2fastnormals->integer==0) #if 0 @@ -3681,81 +3182,73 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) else { #endif - float fTotalWeight; - float fBoneWeight; - float t1; - float t2; - const mdxaBone_t *bone; - const mdxaBone_t *bone2; - for ( j = 0; j < numVerts; j++, baseVertex++,v++ ) - { - - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, 0 )]); - int iNumWeights = G2_GetVertWeights( v ); - tess.normal[baseVertex][0] = DotProduct( bone->matrix[0], v->normal ); - tess.normal[baseVertex][1] = DotProduct( bone->matrix[1], v->normal ); - tess.normal[baseVertex][2] = DotProduct( bone->matrix[2], v->normal ); - - if (iNumWeights==1) - { - tess.xyz[baseVertex][0] = ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] = ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] = ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } - else - { - fBoneWeight = G2_GetVertBoneWeightNotSlow( v, 0); - if (iNumWeights==2) - { - bone2 = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, 1 )]); - /* - useless transposition - tess.xyz[baseVertex][0] = - v[0]*(w*(bone->matrix[0][0]-bone2->matrix[0][0])+bone2->matrix[0][0])+ - v[1]*(w*(bone->matrix[0][1]-bone2->matrix[0][1])+bone2->matrix[0][1])+ - v[2]*(w*(bone->matrix[0][2]-bone2->matrix[0][2])+bone2->matrix[0][2])+ - w*(bone->matrix[0][3]-bone2->matrix[0][3]) + bone2->matrix[0][3]; - */ - t1 = ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - t2 = ( DotProduct( bone2->matrix[0], v->vertCoords ) + bone2->matrix[0][3] ); - tess.xyz[baseVertex][0] = fBoneWeight * (t1-t2) + t2; - t1 = ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - t2 = ( DotProduct( bone2->matrix[1], v->vertCoords ) + bone2->matrix[1][3] ); - tess.xyz[baseVertex][1] = fBoneWeight * (t1-t2) + t2; - t1 = ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - t2 = ( DotProduct( bone2->matrix[2], v->vertCoords ) + bone2->matrix[2][3] ); - tess.xyz[baseVertex][2] = fBoneWeight * (t1-t2) + t2; + float fTotalWeight; + float fBoneWeight; + float t1; + float t2; + const mdxaBone_t *bone; + const mdxaBone_t *bone2; + for (j = 0; j < numVerts; j++, baseVertex++, v++) { + + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, 0)]); + int iNumWeights = G2_GetVertWeights(v); + tess.normal[baseVertex][0] = DotProduct(bone->matrix[0], v->normal); + tess.normal[baseVertex][1] = DotProduct(bone->matrix[1], v->normal); + tess.normal[baseVertex][2] = DotProduct(bone->matrix[2], v->normal); + + if (iNumWeights == 1) { + tess.xyz[baseVertex][0] = (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] = (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] = (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + } else { + fBoneWeight = G2_GetVertBoneWeightNotSlow(v, 0); + if (iNumWeights == 2) { + bone2 = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, 1)]); + /* + useless transposition + tess.xyz[baseVertex][0] = + v[0]*(w*(bone->matrix[0][0]-bone2->matrix[0][0])+bone2->matrix[0][0])+ + v[1]*(w*(bone->matrix[0][1]-bone2->matrix[0][1])+bone2->matrix[0][1])+ + v[2]*(w*(bone->matrix[0][2]-bone2->matrix[0][2])+bone2->matrix[0][2])+ + w*(bone->matrix[0][3]-bone2->matrix[0][3]) + bone2->matrix[0][3]; + */ + t1 = (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + t2 = (DotProduct(bone2->matrix[0], v->vertCoords) + bone2->matrix[0][3]); + tess.xyz[baseVertex][0] = fBoneWeight * (t1 - t2) + t2; + t1 = (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + t2 = (DotProduct(bone2->matrix[1], v->vertCoords) + bone2->matrix[1][3]); + tess.xyz[baseVertex][1] = fBoneWeight * (t1 - t2) + t2; + t1 = (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + t2 = (DotProduct(bone2->matrix[2], v->vertCoords) + bone2->matrix[2][3]); + tess.xyz[baseVertex][2] = fBoneWeight * (t1 - t2) + t2; + } else { + + tess.xyz[baseVertex][0] = fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] = fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] = fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); + + fTotalWeight = fBoneWeight; + for (k = 1; k < iNumWeights - 1; k++) { + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, k)]); + fBoneWeight = G2_GetVertBoneWeightNotSlow(v, k); + fTotalWeight += fBoneWeight; + + tess.xyz[baseVertex][0] += fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] += fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] += fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); } - else - { - - tess.xyz[baseVertex][0] = fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] = fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] = fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - - fTotalWeight=fBoneWeight; - for (k=1; k < iNumWeights-1 ; k++) - { - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, k )]); - fBoneWeight = G2_GetVertBoneWeightNotSlow( v, k); - fTotalWeight += fBoneWeight; - - tess.xyz[baseVertex][0] += fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] += fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] += fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } - bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex( v, k )]); - fBoneWeight = 1.0f-fTotalWeight; + bone = &bones->EvalRender(piBoneReferences[G2_GetVertBoneIndex(v, k)]); + fBoneWeight = 1.0f - fTotalWeight; - tess.xyz[baseVertex][0] += fBoneWeight * ( DotProduct( bone->matrix[0], v->vertCoords ) + bone->matrix[0][3] ); - tess.xyz[baseVertex][1] += fBoneWeight * ( DotProduct( bone->matrix[1], v->vertCoords ) + bone->matrix[1][3] ); - tess.xyz[baseVertex][2] += fBoneWeight * ( DotProduct( bone->matrix[2], v->vertCoords ) + bone->matrix[2][3] ); - } + tess.xyz[baseVertex][0] += fBoneWeight * (DotProduct(bone->matrix[0], v->vertCoords) + bone->matrix[0][3]); + tess.xyz[baseVertex][1] += fBoneWeight * (DotProduct(bone->matrix[1], v->vertCoords) + bone->matrix[1][3]); + tess.xyz[baseVertex][2] += fBoneWeight * (DotProduct(bone->matrix[2], v->vertCoords) + bone->matrix[2][3]); } - - tess.texCoords[baseVertex][0][0] = pTexCoords[j].texCoords[0]; - tess.texCoords[baseVertex][0][1] = pTexCoords[j].texCoords[1]; } + + tess.texCoords[baseVertex][0][0] = pTexCoords[j].texCoords[0]; + tess.texCoords[baseVertex][0][1] = pTexCoords[j].texCoords[1]; + } #if 0 } #endif @@ -3763,11 +3256,9 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) #ifdef _G2_GORE CRenderableSurface *storeSurf = surf; - while (surf->goreChain) - { - surf=(CRenderableSurface *)surf->goreChain; - if (surf->alternateTex) - { + while (surf->goreChain) { + surf = (CRenderableSurface *)surf->goreChain; + if (surf->alternateTex) { // get a gore surface ready to go. /* @@ -3780,30 +3271,25 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) sizeof(int)*newNumTris*3; // new indecies */ - int *data=(int *)surf->alternateTex; - int gnumVerts=*data++; + int *data = (int *)surf->alternateTex; + int gnumVerts = *data++; data++; - float *fdata=(float *)data; - fdata+=gnumVerts; - for (j=0;j=0&&data[j]= 0 && data[j] < numVerts); + memcpy(fdata, &tess.xyz[tess.numVertexes + data[j]][0], sizeof(float) * 3); + fdata += 4; } - for (j=0;j=0&&data[j]= 0 && data[j] < numVerts); + memcpy(fdata, &tess.normal[tess.numVertexes + data[j]][0], sizeof(float) * 3); + fdata += 4; } - } - else - { + } else { assert(0); } - } // NOTE: This is required because a ghoul model might need to be rendered twice a frame (don't cringe, @@ -3811,8 +3297,7 @@ void RB_SurfaceGhoul( CRenderableSurface *surf ) // the glow is rendered _second_!!! If that changes, change this! extern bool g_bRenderGlowingObjects; extern bool g_bDynamicGlowSupported; - if ( !tess.shader->hasGlow || g_bRenderGlowingObjects || !g_bDynamicGlowSupported || !r_DynamicGlow->integer ) - { + if (!tess.shader->hasGlow || g_bRenderGlowingObjects || !g_bDynamicGlowSupported || !r_DynamicGlow->integer) { delete storeSurf; } #endif @@ -3840,401 +3325,396 @@ Complete list of all 72 bones: */ int OldToNewRemapTable[72] = { -0,// Bone 0: "model_root": Parent: "" (index -1) -1,// Bone 1: "pelvis": Parent: "model_root" (index 0) -2,// Bone 2: "Motion": Parent: "pelvis" (index 1) -3,// Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) -4,// Bone 4: "lfemurX": Parent: "pelvis" (index 1) -5,// Bone 5: "ltibia": Parent: "pelvis" (index 1) -6,// Bone 6: "ltalus": Parent: "pelvis" (index 1) -6,// Bone 7: "ltarsal": Parent: "pelvis" (index 1) -7,// Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) -8,// Bone 9: "rfemurX": Parent: "pelvis" (index 1) -9,// Bone10: "rtibia": Parent: "pelvis" (index 1) -10,// Bone11: "rtalus": Parent: "pelvis" (index 1) -10,// Bone12: "rtarsal": Parent: "pelvis" (index 1) -11,// Bone13: "lower_lumbar": Parent: "pelvis" (index 1) -12,// Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) -13,// Bone15: "thoracic": Parent: "upper_lumbar" (index 14) -14,// Bone16: "cervical": Parent: "thoracic" (index 15) -15,// Bone17: "cranium": Parent: "cervical" (index 16) -16,// Bone18: "ceyebrow": Parent: "face_always_" (index 71) -17,// Bone19: "jaw": Parent: "face_always_" (index 71) -18,// Bone20: "lblip2": Parent: "face_always_" (index 71) -19,// Bone21: "leye": Parent: "face_always_" (index 71) -20,// Bone22: "rblip2": Parent: "face_always_" (index 71) -21,// Bone23: "ltlip2": Parent: "face_always_" (index 71) -22,// Bone24: "rtlip2": Parent: "face_always_" (index 71) -23,// Bone25: "reye": Parent: "face_always_" (index 71) -24,// Bone26: "rclavical": Parent: "thoracic" (index 15) -25,// Bone27: "rhumerus": Parent: "thoracic" (index 15) -26,// Bone28: "rhumerusX": Parent: "thoracic" (index 15) -27,// Bone29: "rradius": Parent: "thoracic" (index 15) -28,// Bone30: "rradiusX": Parent: "thoracic" (index 15) -29,// Bone31: "rhand": Parent: "thoracic" (index 15) -29,// Bone32: "mc7": Parent: "thoracic" (index 15) -34,// Bone33: "r_d5_j1": Parent: "thoracic" (index 15) -35,// Bone34: "r_d5_j2": Parent: "thoracic" (index 15) -35,// Bone35: "r_d5_j3": Parent: "thoracic" (index 15) -30,// Bone36: "r_d1_j1": Parent: "thoracic" (index 15) -31,// Bone37: "r_d1_j2": Parent: "thoracic" (index 15) -31,// Bone38: "r_d1_j3": Parent: "thoracic" (index 15) -32,// Bone39: "r_d2_j1": Parent: "thoracic" (index 15) -33,// Bone40: "r_d2_j2": Parent: "thoracic" (index 15) -33,// Bone41: "r_d2_j3": Parent: "thoracic" (index 15) -32,// Bone42: "r_d3_j1": Parent: "thoracic" (index 15) -33,// Bone43: "r_d3_j2": Parent: "thoracic" (index 15) -33,// Bone44: "r_d3_j3": Parent: "thoracic" (index 15) -34,// Bone45: "r_d4_j1": Parent: "thoracic" (index 15) -35,// Bone46: "r_d4_j2": Parent: "thoracic" (index 15) -35,// Bone47: "r_d4_j3": Parent: "thoracic" (index 15) -36,// Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) -37,// Bone49: "lclavical": Parent: "thoracic" (index 15) -38,// Bone50: "lhumerus": Parent: "thoracic" (index 15) -39,// Bone51: "lhumerusX": Parent: "thoracic" (index 15) -40,// Bone52: "lradius": Parent: "thoracic" (index 15) -41,// Bone53: "lradiusX": Parent: "thoracic" (index 15) -42,// Bone54: "lhand": Parent: "thoracic" (index 15) -42,// Bone55: "mc5": Parent: "thoracic" (index 15) -43,// Bone56: "l_d5_j1": Parent: "thoracic" (index 15) -44,// Bone57: "l_d5_j2": Parent: "thoracic" (index 15) -44,// Bone58: "l_d5_j3": Parent: "thoracic" (index 15) -43,// Bone59: "l_d4_j1": Parent: "thoracic" (index 15) -44,// Bone60: "l_d4_j2": Parent: "thoracic" (index 15) -44,// Bone61: "l_d4_j3": Parent: "thoracic" (index 15) -45,// Bone62: "l_d3_j1": Parent: "thoracic" (index 15) -46,// Bone63: "l_d3_j2": Parent: "thoracic" (index 15) -46,// Bone64: "l_d3_j3": Parent: "thoracic" (index 15) -45,// Bone65: "l_d2_j1": Parent: "thoracic" (index 15) -46,// Bone66: "l_d2_j2": Parent: "thoracic" (index 15) -46,// Bone67: "l_d2_j3": Parent: "thoracic" (index 15) -47,// Bone68: "l_d1_j1": Parent: "thoracic" (index 15) -48,// Bone69: "l_d1_j2": Parent: "thoracic" (index 15) -48,// Bone70: "l_d1_j3": Parent: "thoracic" (index 15) -52// Bone71: "face_always_": Parent: "cranium" (index 17) + 0, // Bone 0: "model_root": Parent: "" (index -1) + 1, // Bone 1: "pelvis": Parent: "model_root" (index 0) + 2, // Bone 2: "Motion": Parent: "pelvis" (index 1) + 3, // Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) + 4, // Bone 4: "lfemurX": Parent: "pelvis" (index 1) + 5, // Bone 5: "ltibia": Parent: "pelvis" (index 1) + 6, // Bone 6: "ltalus": Parent: "pelvis" (index 1) + 6, // Bone 7: "ltarsal": Parent: "pelvis" (index 1) + 7, // Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) + 8, // Bone 9: "rfemurX": Parent: "pelvis" (index 1) + 9, // Bone10: "rtibia": Parent: "pelvis" (index 1) + 10, // Bone11: "rtalus": Parent: "pelvis" (index 1) + 10, // Bone12: "rtarsal": Parent: "pelvis" (index 1) + 11, // Bone13: "lower_lumbar": Parent: "pelvis" (index 1) + 12, // Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) + 13, // Bone15: "thoracic": Parent: "upper_lumbar" (index 14) + 14, // Bone16: "cervical": Parent: "thoracic" (index 15) + 15, // Bone17: "cranium": Parent: "cervical" (index 16) + 16, // Bone18: "ceyebrow": Parent: "face_always_" (index 71) + 17, // Bone19: "jaw": Parent: "face_always_" (index 71) + 18, // Bone20: "lblip2": Parent: "face_always_" (index 71) + 19, // Bone21: "leye": Parent: "face_always_" (index 71) + 20, // Bone22: "rblip2": Parent: "face_always_" (index 71) + 21, // Bone23: "ltlip2": Parent: "face_always_" (index 71) + 22, // Bone24: "rtlip2": Parent: "face_always_" (index 71) + 23, // Bone25: "reye": Parent: "face_always_" (index 71) + 24, // Bone26: "rclavical": Parent: "thoracic" (index 15) + 25, // Bone27: "rhumerus": Parent: "thoracic" (index 15) + 26, // Bone28: "rhumerusX": Parent: "thoracic" (index 15) + 27, // Bone29: "rradius": Parent: "thoracic" (index 15) + 28, // Bone30: "rradiusX": Parent: "thoracic" (index 15) + 29, // Bone31: "rhand": Parent: "thoracic" (index 15) + 29, // Bone32: "mc7": Parent: "thoracic" (index 15) + 34, // Bone33: "r_d5_j1": Parent: "thoracic" (index 15) + 35, // Bone34: "r_d5_j2": Parent: "thoracic" (index 15) + 35, // Bone35: "r_d5_j3": Parent: "thoracic" (index 15) + 30, // Bone36: "r_d1_j1": Parent: "thoracic" (index 15) + 31, // Bone37: "r_d1_j2": Parent: "thoracic" (index 15) + 31, // Bone38: "r_d1_j3": Parent: "thoracic" (index 15) + 32, // Bone39: "r_d2_j1": Parent: "thoracic" (index 15) + 33, // Bone40: "r_d2_j2": Parent: "thoracic" (index 15) + 33, // Bone41: "r_d2_j3": Parent: "thoracic" (index 15) + 32, // Bone42: "r_d3_j1": Parent: "thoracic" (index 15) + 33, // Bone43: "r_d3_j2": Parent: "thoracic" (index 15) + 33, // Bone44: "r_d3_j3": Parent: "thoracic" (index 15) + 34, // Bone45: "r_d4_j1": Parent: "thoracic" (index 15) + 35, // Bone46: "r_d4_j2": Parent: "thoracic" (index 15) + 35, // Bone47: "r_d4_j3": Parent: "thoracic" (index 15) + 36, // Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) + 37, // Bone49: "lclavical": Parent: "thoracic" (index 15) + 38, // Bone50: "lhumerus": Parent: "thoracic" (index 15) + 39, // Bone51: "lhumerusX": Parent: "thoracic" (index 15) + 40, // Bone52: "lradius": Parent: "thoracic" (index 15) + 41, // Bone53: "lradiusX": Parent: "thoracic" (index 15) + 42, // Bone54: "lhand": Parent: "thoracic" (index 15) + 42, // Bone55: "mc5": Parent: "thoracic" (index 15) + 43, // Bone56: "l_d5_j1": Parent: "thoracic" (index 15) + 44, // Bone57: "l_d5_j2": Parent: "thoracic" (index 15) + 44, // Bone58: "l_d5_j3": Parent: "thoracic" (index 15) + 43, // Bone59: "l_d4_j1": Parent: "thoracic" (index 15) + 44, // Bone60: "l_d4_j2": Parent: "thoracic" (index 15) + 44, // Bone61: "l_d4_j3": Parent: "thoracic" (index 15) + 45, // Bone62: "l_d3_j1": Parent: "thoracic" (index 15) + 46, // Bone63: "l_d3_j2": Parent: "thoracic" (index 15) + 46, // Bone64: "l_d3_j3": Parent: "thoracic" (index 15) + 45, // Bone65: "l_d2_j1": Parent: "thoracic" (index 15) + 46, // Bone66: "l_d2_j2": Parent: "thoracic" (index 15) + 46, // Bone67: "l_d2_j3": Parent: "thoracic" (index 15) + 47, // Bone68: "l_d1_j1": Parent: "thoracic" (index 15) + 48, // Bone69: "l_d1_j2": Parent: "thoracic" (index 15) + 48, // Bone70: "l_d1_j3": Parent: "thoracic" (index 15) + 52 // Bone71: "face_always_": Parent: "cranium" (index 17) }; - /* Bone 0: "model_root": - Parent: "" (index -1) - #Kids: 1 - Child 0: (index 1), name "pelvis" + Parent: "" (index -1) + #Kids: 1 + Child 0: (index 1), name "pelvis" Bone 1: "pelvis": - Parent: "model_root" (index 0) - #Kids: 4 - Child 0: (index 2), name "Motion" - Child 1: (index 3), name "lfemurYZ" - Child 2: (index 7), name "rfemurYZ" - Child 3: (index 11), name "lower_lumbar" + Parent: "model_root" (index 0) + #Kids: 4 + Child 0: (index 2), name "Motion" + Child 1: (index 3), name "lfemurYZ" + Child 2: (index 7), name "rfemurYZ" + Child 3: (index 11), name "lower_lumbar" Bone 2: "Motion": - Parent: "pelvis" (index 1) - #Kids: 0 + Parent: "pelvis" (index 1) + #Kids: 0 Bone 3: "lfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 4), name "lfemurX" - Child 1: (index 5), name "ltibia" - Child 2: (index 49), name "ltail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 4), name "lfemurX" + Child 1: (index 5), name "ltibia" + Child 2: (index 49), name "ltail" Bone 4: "lfemurX": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 5: "ltibia": - Parent: "lfemurYZ" (index 3) - #Kids: 1 - Child 0: (index 6), name "ltalus" + Parent: "lfemurYZ" (index 3) + #Kids: 1 + Child 0: (index 6), name "ltalus" Bone 6: "ltalus": - Parent: "ltibia" (index 5) - #Kids: 0 + Parent: "ltibia" (index 5) + #Kids: 0 Bone 7: "rfemurYZ": - Parent: "pelvis" (index 1) - #Kids: 3 - Child 0: (index 8), name "rfemurX" - Child 1: (index 9), name "rtibia" - Child 2: (index 50), name "rtail" + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 8), name "rfemurX" + Child 1: (index 9), name "rtibia" + Child 2: (index 50), name "rtail" Bone 8: "rfemurX": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 9: "rtibia": - Parent: "rfemurYZ" (index 7) - #Kids: 1 - Child 0: (index 10), name "rtalus" + Parent: "rfemurYZ" (index 7) + #Kids: 1 + Child 0: (index 10), name "rtalus" Bone 10: "rtalus": - Parent: "rtibia" (index 9) - #Kids: 0 + Parent: "rtibia" (index 9) + #Kids: 0 Bone 11: "lower_lumbar": - Parent: "pelvis" (index 1) - #Kids: 1 - Child 0: (index 12), name "upper_lumbar" + Parent: "pelvis" (index 1) + #Kids: 1 + Child 0: (index 12), name "upper_lumbar" Bone 12: "upper_lumbar": - Parent: "lower_lumbar" (index 11) - #Kids: 1 - Child 0: (index 13), name "thoracic" + Parent: "lower_lumbar" (index 11) + #Kids: 1 + Child 0: (index 13), name "thoracic" Bone 13: "thoracic": - Parent: "upper_lumbar" (index 12) - #Kids: 5 - Child 0: (index 14), name "cervical" - Child 1: (index 24), name "rclavical" - Child 2: (index 25), name "rhumerus" - Child 3: (index 37), name "lclavical" - Child 4: (index 38), name "lhumerus" + Parent: "upper_lumbar" (index 12) + #Kids: 5 + Child 0: (index 14), name "cervical" + Child 1: (index 24), name "rclavical" + Child 2: (index 25), name "rhumerus" + Child 3: (index 37), name "lclavical" + Child 4: (index 38), name "lhumerus" Bone 14: "cervical": - Parent: "thoracic" (index 13) - #Kids: 1 - Child 0: (index 15), name "cranium" + Parent: "thoracic" (index 13) + #Kids: 1 + Child 0: (index 15), name "cranium" Bone 15: "cranium": - Parent: "cervical" (index 14) - #Kids: 1 - Child 0: (index 52), name "face_always_" + Parent: "cervical" (index 14) + #Kids: 1 + Child 0: (index 52), name "face_always_" Bone 16: "ceyebrow": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 17: "jaw": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 18: "lblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 19: "leye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 20: "rblip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 21: "ltlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 22: "rtlip2": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 23: "reye": - Parent: "face_always_" (index 52) - #Kids: 0 + Parent: "face_always_" (index 52) + #Kids: 0 Bone 24: "rclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 25: "rhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 26), name "rhumerusX" - Child 1: (index 27), name "rradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 26), name "rhumerusX" + Child 1: (index 27), name "rradius" Bone 26: "rhumerusX": - Parent: "rhumerus" (index 25) - #Kids: 0 + Parent: "rhumerus" (index 25) + #Kids: 0 Bone 27: "rradius": - Parent: "rhumerus" (index 25) - #Kids: 9 - Child 0: (index 28), name "rradiusX" - Child 1: (index 29), name "rhand" - Child 2: (index 30), name "r_d1_j1" - Child 3: (index 31), name "r_d1_j2" - Child 4: (index 32), name "r_d2_j1" - Child 5: (index 33), name "r_d2_j2" - Child 6: (index 34), name "r_d4_j1" - Child 7: (index 35), name "r_d4_j2" - Child 8: (index 36), name "rhang_tag_bone" + Parent: "rhumerus" (index 25) + #Kids: 9 + Child 0: (index 28), name "rradiusX" + Child 1: (index 29), name "rhand" + Child 2: (index 30), name "r_d1_j1" + Child 3: (index 31), name "r_d1_j2" + Child 4: (index 32), name "r_d2_j1" + Child 5: (index 33), name "r_d2_j2" + Child 6: (index 34), name "r_d4_j1" + Child 7: (index 35), name "r_d4_j2" + Child 8: (index 36), name "rhang_tag_bone" Bone 28: "rradiusX": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 29: "rhand": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 30: "r_d1_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 31: "r_d1_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 32: "r_d2_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 33: "r_d2_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 34: "r_d4_j1": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 35: "r_d4_j2": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 36: "rhang_tag_bone": - Parent: "rradius" (index 27) - #Kids: 0 + Parent: "rradius" (index 27) + #Kids: 0 Bone 37: "lclavical": - Parent: "thoracic" (index 13) - #Kids: 0 + Parent: "thoracic" (index 13) + #Kids: 0 Bone 38: "lhumerus": - Parent: "thoracic" (index 13) - #Kids: 2 - Child 0: (index 39), name "lhumerusX" - Child 1: (index 40), name "lradius" + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 39), name "lhumerusX" + Child 1: (index 40), name "lradius" Bone 39: "lhumerusX": - Parent: "lhumerus" (index 38) - #Kids: 0 + Parent: "lhumerus" (index 38) + #Kids: 0 Bone 40: "lradius": - Parent: "lhumerus" (index 38) - #Kids: 9 - Child 0: (index 41), name "lradiusX" - Child 1: (index 42), name "lhand" - Child 2: (index 43), name "l_d4_j1" - Child 3: (index 44), name "l_d4_j2" - Child 4: (index 45), name "l_d2_j1" - Child 5: (index 46), name "l_d2_j2" - Child 6: (index 47), name "l_d1_j1" - Child 7: (index 48), name "l_d1_j2" - Child 8: (index 51), name "lhang_tag_bone" + Parent: "lhumerus" (index 38) + #Kids: 9 + Child 0: (index 41), name "lradiusX" + Child 1: (index 42), name "lhand" + Child 2: (index 43), name "l_d4_j1" + Child 3: (index 44), name "l_d4_j2" + Child 4: (index 45), name "l_d2_j1" + Child 5: (index 46), name "l_d2_j2" + Child 6: (index 47), name "l_d1_j1" + Child 7: (index 48), name "l_d1_j2" + Child 8: (index 51), name "lhang_tag_bone" Bone 41: "lradiusX": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 42: "lhand": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 43: "l_d4_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 44: "l_d4_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 45: "l_d2_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 46: "l_d2_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 47: "l_d1_j1": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 48: "l_d1_j2": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 49: "ltail": - Parent: "lfemurYZ" (index 3) - #Kids: 0 + Parent: "lfemurYZ" (index 3) + #Kids: 0 Bone 50: "rtail": - Parent: "rfemurYZ" (index 7) - #Kids: 0 + Parent: "rfemurYZ" (index 7) + #Kids: 0 Bone 51: "lhang_tag_bone": - Parent: "lradius" (index 40) - #Kids: 0 + Parent: "lradius" (index 40) + #Kids: 0 Bone 52: "face_always_": - Parent: "cranium" (index 15) - #Kids: 8 - Child 0: (index 16), name "ceyebrow" - Child 1: (index 17), name "jaw" - Child 2: (index 18), name "lblip2" - Child 3: (index 19), name "leye" - Child 4: (index 20), name "rblip2" - Child 5: (index 21), name "ltlip2" - Child 6: (index 22), name "rtlip2" - Child 7: (index 23), name "reye" + Parent: "cranium" (index 15) + #Kids: 8 + Child 0: (index 16), name "ceyebrow" + Child 1: (index 17), name "jaw" + Child 2: (index 18), name "lblip2" + Child 3: (index 19), name "leye" + Child 4: (index 20), name "rblip2" + Child 5: (index 21), name "ltlip2" + Child 6: (index 22), name "rtlip2" + Child 7: (index 23), name "reye" */ - -qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - mdxmSurfHierarchy_t *surfInfo; +qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + mdxmSurfHierarchy_t *surfInfo; #ifdef Q3_BIG_ENDIAN - int k; - mdxmTriangle_t *tri; - mdxmVertex_t *v; - int *boneRef; - mdxmLODSurfOffset_t *indexes; - mdxmVertexTexCoord_t *pTexCoords; - mdxmHierarchyOffsets_t *surfIndexes; + int k; + mdxmTriangle_t *tri; + mdxmVertex_t *v; + int *boneRef; + mdxmLODSurfOffset_t *indexes; + mdxmVertexTexCoord_t *pTexCoords; + mdxmHierarchyOffsets_t *surfIndexes; #endif - pinmodel= (mdxmHeader_t *)buffer; + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXM_VERSION) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXM_VERSION); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", mod_name, version, MDXM_VERSION); return qfalse; } - mod->type = MOD_MDXM; + mod->type = MOD_MDXM; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxm = mod->mdxm = (mdxmHeader_t*) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mdxm = mod->mdxm = (mdxmHeader_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); assert(bAlreadyCached == bAlreadyFound); - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -4242,8 +3722,8 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -4256,59 +3736,50 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean } // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterModel(va ("%s.gla",mdxm->animName)); + mdxm->animIndex = RE_RegisterModel(va("%s.gla", mdxm->animName)); - if (!mdxm->animIndex) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); + if (!mdxm->animIndex) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } bool isAnOldModelFile = false; - if (mdxm->numBones == 72 && strstr(mdxm->animName,"_humanoid") ) - { + if (mdxm->numBones == 72 && strstr(mdxm->animName, "_humanoid")) { isAnOldModelFile = true; } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); #ifdef Q3_BIG_ENDIAN surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); #endif - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->flags); LL(surfInfo->numChildren); LL(surfInfo->parentIndex); - Q_strlwr(surfInfo->name); //just in case - if ( !strcmp( &surfInfo->name[strlen(surfInfo->name)-4],"_off") ) - { - surfInfo->name[strlen(surfInfo->name)-4]=0; //remove "_off" from name + Q_strlwr(surfInfo->name); // just in case + if (!strcmp(&surfInfo->name[strlen(surfInfo->name) - 4], "_off")) { + surfInfo->name[strlen(surfInfo->name) - 4] = 0; // remove "_off" from name } // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } - shader_t *sh; + shader_t *sh; // get the shader name - sh = R_FindShader( surfInfo->shader, lightmapsNone, stylesDefault, qtrue ); + sh = R_FindShader(surfInfo->shader, lightmapsNone, stylesDefault, qtrue); // insert it in the surface list - if ( sh->defaultShader ) - { + if (sh->defaultShader) { surfInfo->shaderIndex = 0; - } - else - { + } else { surfInfo->shaderIndex = sh->index; } @@ -4321,20 +3792,18 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean #endif // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (size_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->thisSurfaceIndex); LL(surf->ofsHeader); LL(surf->numVerts); @@ -4347,13 +3816,11 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean triCount += surf->numTriangles; - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", - mod_name, SHADER_MAX_VERTEXES, surf->numVerts ); + if (surf->numVerts > SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i verts on a surface (%i)", mod_name, SHADER_MAX_VERTEXES, surf->numVerts); } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", - mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles ); + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", mod_name, SHADER_MAX_INDEXES / 3, surf->numTriangles); } // change to surface identifier @@ -4365,27 +3832,24 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean LL(indexes->offsets[surf->thisSurfaceIndex]); // do all the bone reference data - boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { - LL(boneRef[j]); + boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { + LL(boneRef[j]); } // swap all the triangles - tri = (mdxmTriangle_t *) ( (byte *)surf + surf->ofsTriangles ); - for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) - { + tri = (mdxmTriangle_t *)((byte *)surf + surf->ofsTriangles); + for (j = 0; j < surf->numTriangles; j++, tri++) { LL(tri->indexes[0]); LL(tri->indexes[1]); LL(tri->indexes[2]); } // swap all the vertexes - v = (mdxmVertex_t *) ( (byte *)surf + surf->ofsVerts ); - pTexCoords = (mdxmVertexTexCoord_t *) &v[surf->numVerts]; + v = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); + pTexCoords = (mdxmVertexTexCoord_t *)&v[surf->numVerts]; - for ( j = 0 ; j < surf->numVerts ; j++ ) - { + for (j = 0; j < surf->numVerts; j++) { LF(v->normal[0]); LF(v->normal[1]); LF(v->normal[2]); @@ -4403,27 +3867,22 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean } #endif - if (isAnOldModelFile) - { - int *boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { + if (isAnOldModelFile) { + int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { assert(boneRef[j] >= 0 && boneRef[j] < 72); - if (boneRef[j] >= 0 && boneRef[j] < 72) - { - boneRef[j]=OldToNewRemapTable[boneRef[j]]; - } - else - { - boneRef[j]=0; + if (boneRef[j] >= 0 && boneRef[j] < 72) { + boneRef[j] = OldToNewRemapTable[boneRef[j]]; + } else { + boneRef[j] = 0; } } } // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; } @@ -4432,52 +3891,24 @@ qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean #ifdef CREATE_LIMB_HIERARCHY -#define NUM_ROOTPARENTS 4 -#define NUM_OTHERPARENTS 12 -#define NUM_BOTTOMBONES 4 +#define NUM_ROOTPARENTS 4 +#define NUM_OTHERPARENTS 12 +#define NUM_BOTTOMBONES 4 -#define CHILD_PADDING 4 //I don't know, I guess this can be changed. +#define CHILD_PADDING 4 // I don't know, I guess this can be changed. -static const char *rootParents[NUM_ROOTPARENTS] = -{ - "rfemurYZ", - "rhumerus", - "lfemurYZ", - "lhumerus" -}; +static const char *rootParents[NUM_ROOTPARENTS] = {"rfemurYZ", "rhumerus", "lfemurYZ", "lhumerus"}; -static const char *otherParents[NUM_OTHERPARENTS] = -{ - "rhumerusX", - "rradius", - "rradiusX", - "lhumerusX", - "lradius", - "lradiusX", - "rfemurX", - "rtibia", - "rtalus", - "lfemurX", - "ltibia", - "ltalus" -}; +static const char *otherParents[NUM_OTHERPARENTS] = {"rhumerusX", "rradius", "rradiusX", "lhumerusX", "lradius", "lradiusX", + "rfemurX", "rtibia", "rtalus", "lfemurX", "ltibia", "ltalus"}; -static const char *bottomBones[NUM_BOTTOMBONES] = -{ - "rtarsal", - "rhand", - "ltarsal", - "lhand" -}; +static const char *bottomBones[NUM_BOTTOMBONES] = {"rtarsal", "rhand", "ltarsal", "lhand"}; -qboolean BoneIsRootParent(char *name) -{ +qboolean BoneIsRootParent(char *name) { int i = 0; - while (i < NUM_ROOTPARENTS) - { - if (!Q_stricmp(name, rootParents[i])) - { + while (i < NUM_ROOTPARENTS) { + if (!Q_stricmp(name, rootParents[i])) { return qtrue; } @@ -4487,14 +3918,11 @@ qboolean BoneIsRootParent(char *name) return qfalse; } -qboolean BoneIsOtherParent(char *name) -{ +qboolean BoneIsOtherParent(char *name) { int i = 0; - while (i < NUM_OTHERPARENTS) - { - if (!Q_stricmp(name, otherParents[i])) - { + while (i < NUM_OTHERPARENTS) { + if (!Q_stricmp(name, otherParents[i])) { return qtrue; } @@ -4504,14 +3932,11 @@ qboolean BoneIsOtherParent(char *name) return qfalse; } -qboolean BoneIsBottom(char *name) -{ +qboolean BoneIsBottom(char *name) { int i = 0; - while (i < NUM_BOTTOMBONES) - { - if (!Q_stricmp(name, bottomBones[i])) - { + while (i < NUM_BOTTOMBONES) { + if (!Q_stricmp(name, bottomBones[i])) { return qtrue; } @@ -4521,24 +3946,22 @@ qboolean BoneIsBottom(char *name) return qfalse; } -void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) -{ +void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) { int i = 0; - //where the next bone starts - byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex+1]); + // where the next bone starts + byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex + 1]); int size = (*endMarker - nextBone); - memmove((nextBone+CHILD_PADDING), nextBone, size); + memmove((nextBone + CHILD_PADDING), nextBone, size); memset(nextBone, 0, CHILD_PADDING); *endMarker += CHILD_PADDING; - //Move the whole thing down CHILD_PADDING amount in memory, clear the new preceding space, and increment the end pointer. + // Move the whole thing down CHILD_PADDING amount in memory, clear the new preceding space, and increment the end pointer. - i = boneIndex+1; + i = boneIndex + 1; - //Now add CHILD_PADDING amount to every offset beginning at the offset of the bone that was moved. - while (i < mdxa->numBones) - { + // Now add CHILD_PADDING amount to every offset beginning at the offset of the bone that was moved. + while (i < mdxa->numBones) { offsets->offsets[i] += CHILD_PADDING; i++; } @@ -4546,77 +3969,49 @@ void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneInd mdxa->ofsFrames += CHILD_PADDING; mdxa->ofsCompBonePool += CHILD_PADDING; mdxa->ofsEnd += CHILD_PADDING; - //ofsSkel does not need to be updated because we are only moving memory after that point. + // ofsSkel does not need to be updated because we are only moving memory after that point. } -//Proper/desired hierarchy list -static const char *BoneHierarchyList[] = -{ - "lfemurYZ", - "lfemurX", - "ltibia", - "ltalus", - "ltarsal", - - "rfemurYZ", - "rfemurX", - "rtibia", - "rtalus", - "rtarsal", - - "lhumerus", - "lhumerusX", - "lradius", - "lradiusX", - "lhand", - - "rhumerus", - "rhumerusX", - "rradius", - "rradiusX", - "rhand", - - 0 -}; +// Proper/desired hierarchy list +static const char *BoneHierarchyList[] = {"lfemurYZ", "lfemurX", "ltibia", "ltalus", "ltarsal", -//Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. -int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSkel_t *boneInfo, qboolean child) -{ + "rfemurYZ", "rfemurX", "rtibia", "rtalus", "rtarsal", + + "lhumerus", "lhumerusX", "lradius", "lradiusX", "lhand", + + "rhumerus", "rhumerusX", "rradius", "rradiusX", "rhand", + + 0}; + +// Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. +int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSkel_t *boneInfo, qboolean child) { int i = 0; int matchindex = -1; mdxaSkel_t *bone; const char *match = NULL; - while (BoneHierarchyList[i]) - { - if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) - { //we have a match, the slot above this will be our desired parent. (or below for child) - if (child) - { - match = BoneHierarchyList[i+1]; - } - else - { - match = BoneHierarchyList[i-1]; + while (BoneHierarchyList[i]) { + if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) { // we have a match, the slot above this will be our desired parent. (or below for child) + if (child) { + match = BoneHierarchyList[i + 1]; + } else { + match = BoneHierarchyList[i - 1]; } break; } i++; } - if (!match) - { //no good + if (!match) { // no good return -1; } i = 0; - while (i < mdxa->numBones) - { + while (i < mdxa->numBones) { bone = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (bone && !Q_stricmp(bone->name, match)) - { //this is the one + if (bone && !Q_stricmp(bone->name, match)) { // this is the one matchindex = i; break; } @@ -4626,54 +4021,52 @@ int BoneParentChildIndex(mdxaHeader_t *mdxa, mdxaSkelOffsets_t *offsets, mdxaSke return matchindex; } -#endif //CREATE_LIMB_HIERARCHY +#endif // CREATE_LIMB_HIERARCHY /* ================= R_LoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; #ifdef CREATE_LIMB_HIERARCHY - int oSize = 0; - byte *sizeMarker; + int oSize = 0; + byte *sizeMarker; #endif #ifdef Q3_BIG_ENDIAN - int j, k, i; - mdxaSkel_t *boneInfo; - mdxaSkelOffsets_t *offsets; - int maxBoneIndex = 0; - mdxaCompQuatBone_t *pCompBonePool; - unsigned short *pwIn; - mdxaIndex_t *pIndex; - int tmp; + int j, k, i; + mdxaSkel_t *boneInfo; + mdxaSkelOffsets_t *offsets; + int maxBoneIndex = 0; + mdxaCompQuatBone_t *pCompBonePool; + unsigned short *pwIn; + mdxaIndex_t *pIndex; + int tmp; #endif - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MDXA_VERSION) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", - mod_name, version, MDXA_VERSION); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", mod_name, version, MDXA_VERSION); return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; @@ -4681,24 +4074,23 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean oSize = size; int childNumber = (NUM_ROOTPARENTS + NUM_OTHERPARENTS); - size += (childNumber*(CHILD_PADDING*8)); //Allocate us some extra space so we can shift memory down. -#endif //CREATE_LIMB_HIERARCHY + size += (childNumber * (CHILD_PADDING * 8)); // Allocate us some extra space so we can shift memory down. +#endif // CREATE_LIMB_HIERARCHY - mdxa = mod->mdxa = (mdxaHeader_t*) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, - #ifdef CREATE_LIMB_HIERARCHY - NULL, // I think this'll work, can't really test on PC - #else - buffer, - #endif - mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = mod->mdxa = (mdxaHeader_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, +#ifdef CREATE_LIMB_HIERARCHY + NULL, // I think this'll work, can't really test on PC +#else + buffer, +#endif + mod_name, &bAlreadyFound, TAG_MODEL_GLA); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { #ifdef CREATE_LIMB_HIERARCHY - memcpy( mdxa, buffer, oSize ); + memcpy(mdxa, buffer, oSize); #else // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since @@ -4707,12 +4099,12 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); + assert(mdxa == buffer); // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing #endif LL(mdxa->ident); LL(mdxa->version); - //LF(mdxa->fScale); + // LF(mdxa->fScale); LL(mdxa->numFrames); LL(mdxa->ofsFrames); LL(mdxa->numBones); @@ -4722,9 +4114,8 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean } #ifdef CREATE_LIMB_HIERARCHY - if (!bAlreadyFound) - { - mdxaSkel_t *boneParent; + if (!bAlreadyFound) { + mdxaSkel_t *boneParent; #if 0 //#ifdef _M_IX86 mdxaSkel_t *boneInfo; int i, k; @@ -4732,84 +4123,65 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean sizeMarker = (byte *)mdxa + mdxa->ofsEnd; - //rww - This is probably temporary until we put actual hierarchy in for the models. - //It is necessary for the correct operation of ragdoll. - mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + // rww - This is probably temporary until we put actual hierarchy in for the models. + // It is necessary for the correct operation of ragdoll. + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for ( i = 0 ; i < mdxa->numBones ; i++) - { + for (i = 0; i < mdxa->numBones; i++) { boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); - if (boneInfo) - { + if (boneInfo) { char *bname = boneInfo->name; - if (BoneIsRootParent(bname)) - { //These are the main parent bones. We don't want to change their parents, but we want to give them children. + if (BoneIsRootParent(bname)) { // These are the main parent bones. We don't want to change their parents, but we want to give them children. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; - boneInfo->children[boneInfo->numChildren-1] = newChild; - } - else - { + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } - } - else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) - { - if (!BoneIsBottom(bname)) - { //unless it's last in the chain it has the next bone as a child. + } else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) { + if (!BoneIsBottom(bname)) { // unless it's last in the chain it has the next bone as a child. ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); - if (newChild != -1) - { + if (newChild != -1) { boneInfo->numChildren++; - boneInfo->children[boneInfo->numChildren-1] = newChild; - } - else - { + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } else { assert(!"Failed to find matching child for bone in hierarchy creation"); } } - //Before we set the parent we want to remove this as a child for whoever was parenting it. + // Before we set the parent we want to remove this as a child for whoever was parenting it. int oldParent = boneInfo->parent; - if (oldParent > -1) - { + if (oldParent > -1) { boneParent = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[oldParent]); - } - else - { + } else { boneParent = NULL; } - if (boneParent) - { + if (boneParent) { k = 0; - while (k < boneParent->numChildren) - { - if (boneParent->children[k] == i) - { //this bone is the child + while (k < boneParent->numChildren) { + if (boneParent->children[k] == i) { // this bone is the child k++; - while (k < boneParent->numChildren) - { - boneParent->children[k-1] = boneParent->children[k]; + while (k < boneParent->numChildren) { + boneParent->children[k - 1] = boneParent->children[k]; k++; } - boneParent->children[k-1] = 0; + boneParent->children[k - 1] = 0; boneParent->numChildren--; break; } @@ -4817,54 +4189,46 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean } } - //Now that we have cleared the original parent of ownership, mark the bone's new parent. + // Now that we have cleared the original parent of ownership, mark the bone's new parent. int newParent = BoneParentChildIndex(mdxa, offsets, boneInfo, qfalse); - if (newParent != -1) - { + if (newParent != -1) { boneInfo->parent = newParent; - } - else - { + } else { assert(!"Failed to find matching parent for bone in hierarchy creation"); } } } } } -#endif //CREATE_LIMB_HIERARCHY +#endif // CREATE_LIMB_HIERARCHY - if ( mdxa->numFrames < 1 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name ); + if (mdxa->numFrames < 1) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } #ifdef Q3_BIG_ENDIAN // swap the bone info offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for ( i = 0; i < mdxa->numBones ; i++ ) - { + for (i = 0; i < mdxa->numBones; i++) { LL(offsets->offsets[i]); - boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); LL(boneInfo->flags); LL(boneInfo->parent); - for ( j = 0; j < 3; j++ ) - { - for ( k = 0; k < 4; k++) - { + for (j = 0; j < 3; j++) { + for (k = 0; k < 4; k++) { LF(boneInfo->BasePoseMat.matrix[j][k]); LF(boneInfo->BasePoseMatInv.matrix[j][k]); } } LL(boneInfo->numChildren); - for (k=0; knumChildren; k++) - { + for (k = 0; k < boneInfo->numChildren; k++) { LL(boneInfo->children[k]); } } @@ -4874,34 +4238,26 @@ qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean // Find the largest index by iterating through all frames. // It is not guaranteed that the compressed bone pool resides // at the end of the file. - for(i = 0; i < mdxa->numFrames; i++){ - for(j = 0; j < mdxa->numBones; j++){ - k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex - pIndex = (mdxaIndex_t *) ((byte *)mdxa + mdxa->ofsFrames + k); - tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); + for (i = 0; i < mdxa->numFrames; i++) { + for (j = 0; j < mdxa->numBones; j++) { + k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex + pIndex = (mdxaIndex_t *)((byte *)mdxa + mdxa->ofsFrames + k); + tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); - if(maxBoneIndex < tmp){ + if (maxBoneIndex < tmp) { maxBoneIndex = tmp; } } } // Swap the compressed bones. - pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)mdxa + mdxa->ofsCompBonePool); - for ( i = 0 ; i <= maxBoneIndex ; i++ ) - { - pwIn = (unsigned short *) pCompBonePool[i].Comp; + pCompBonePool = (mdxaCompQuatBone_t *)((byte *)mdxa + mdxa->ofsCompBonePool); + for (i = 0; i <= maxBoneIndex; i++) { + pwIn = (unsigned short *)pCompBonePool[i].Comp; - for ( k = 0 ; k < 7 ; k++ ) + for (k = 0; k < 7; k++) LS(pwIn[k]); } #endif return qtrue; } - - - - - - - diff --git a/codemp/rd-vanilla/tr_image.cpp b/codemp/rd-vanilla/tr_image.cpp index 23de173e30..9d961f0fa6 100644 --- a/codemp/rd-vanilla/tr_image.cpp +++ b/codemp/rd-vanilla/tr_image.cpp @@ -28,39 +28,37 @@ along with this program; if not, see . #include -static byte s_intensitytable[256]; +static byte s_intensitytable[256]; static unsigned char s_gammatable[256]; -int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; -int gl_filter_max = GL_LINEAR; +int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; +int gl_filter_max = GL_LINEAR; //#define FILE_HASH_SIZE 1024 // actually the shader code still needs this (from another module, great), -//static image_t* hashTable[FILE_HASH_SIZE]; +// static image_t* hashTable[FILE_HASH_SIZE]; /* ** R_GammaCorrect */ -void R_GammaCorrect( byte *buffer, int bufSize ) { +void R_GammaCorrect(byte *buffer, int bufSize) { int i; - for ( i = 0; i < bufSize; i++ ) { + for (i = 0; i < bufSize; i++) { buffer[i] = s_gammatable[buffer[i]]; } } typedef struct textureMode_s { const char *name; - int minimize, maximize; + int minimize, maximize; } textureMode_t; -textureMode_t modes[] = { - {"GL_NEAREST", GL_NEAREST, GL_NEAREST}, - {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, - {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, - {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR} -}; +textureMode_t modes[] = {{"GL_NEAREST", GL_NEAREST, GL_NEAREST}, + {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR}}; static const size_t numTextureModes = ARRAY_LEN(modes); @@ -69,20 +67,20 @@ static const size_t numTextureModes = ARRAY_LEN(modes); GL_TextureMode =============== */ -void GL_TextureMode( const char *string ) { - size_t i; - image_t *glt; +void GL_TextureMode(const char *string) { + size_t i; + image_t *glt; - for ( i = 0; i < numTextureModes ; i++ ) { - if ( !Q_stricmp( modes[i].name, string ) ) { + for (i = 0; i < numTextureModes; i++) { + if (!Q_stricmp(modes[i].name, string)) { break; } } - if ( i == numTextureModes ) { - ri.Printf( PRINT_ALL, "bad filter name\n" ); - for ( i = 0; i < numTextureModes ; i++ ) { - ri.Printf( PRINT_ALL, "%s\n", modes[i].name ); + if (i == numTextureModes) { + ri.Printf(PRINT_ALL, "bad filter name\n"); + for (i = 0; i < numTextureModes; i++) { + ri.Printf(PRINT_ALL, "%s\n", modes[i].name); } return; } @@ -91,20 +89,19 @@ void GL_TextureMode( const char *string ) { gl_filter_max = modes[i].maximize; // If the level they requested is less than possible, set the max possible... - if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy ); + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy); // change all the existing mipmap texture objects - R_Images_StartIteration(); - while ( (glt = R_Images_GetNextIteration()) != NULL) - { - if ( glt->mipmap ) { - GL_Bind (glt); + R_Images_StartIteration(); + while ((glt = R_Images_GetNextIteration()) != NULL) { + if (glt->mipmap) { + GL_Bind(glt); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); - if(glConfig.maxTextureFilterAnisotropy>0) { - if(r_ext_texture_filter_anisotropic->integer>1) { + if (glConfig.maxTextureFilterAnisotropy > 0) { + if (r_ext_texture_filter_anisotropic->integer > 1) { qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); } else { qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); @@ -116,27 +113,26 @@ void GL_TextureMode( const char *string ) { // makeup a nice clean, consistant name to query for and file under, for map<> usage... // -static char *GenerateImageMappingName( const char *name ) -{ +static char *GenerateImageMappingName(const char *name) { static char sName[MAX_QPATH]; - int i=0; - char letter; + int i = 0; + char letter; - while (name[i] != '\0' && iframeUsed == tr.frameCount- 1 ) {//it has already been advanced for the next frame, so... - if (bUseFormat) - { - float bytePerTex = R_BytesPerTex (pImage->internalFormat); + R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { + if (pImage->frameUsed == tr.frameCount - 1) { // it has already been advanced for the next frame, so... + if (bUseFormat) { + float bytePerTex = R_BytesPerTex(pImage->internalFormat); total += bytePerTex * (pImage->width * pImage->height); - } - else - { + } else { total += pImage->width * pImage->height; } } @@ -224,88 +215,85 @@ float R_SumOfUsedImages( qboolean bUseFormat ) R_ImageList_f =============== */ -void R_ImageList_f( void ) { - int i=0; - image_t *image; - int texels=0; - float texBytes = 0.0f; +void R_ImageList_f(void) { + int i = 0; + image_t *image; + int texels = 0; + float texBytes = 0.0f; const char *yesno[] = {"no ", "yes"}; - ri.Printf( PRINT_ALL, "\n -w-- -h-- -mm- -if-- wrap --name-------\n"); + ri.Printf(PRINT_ALL, "\n -w-- -h-- -mm- -if-- wrap --name-------\n"); int iNumImages = R_Images_StartIteration(); - while ( (image = R_Images_GetNextIteration()) != NULL) - { - texels += image->width*image->height; - texBytes += image->width*image->height * R_BytesPerTex (image->internalFormat); - ri.Printf( PRINT_ALL, "%4i: %4i %4i %s ", - i, image->width, image->height, yesno[image->mipmap] ); - switch ( image->internalFormat ) { + while ((image = R_Images_GetNextIteration()) != NULL) { + texels += image->width * image->height; + texBytes += image->width * image->height * R_BytesPerTex(image->internalFormat); + ri.Printf(PRINT_ALL, "%4i: %4i %4i %s ", i, image->width, image->height, yesno[image->mipmap]); + switch (image->internalFormat) { case 1: - ri.Printf( PRINT_ALL, "I " ); + ri.Printf(PRINT_ALL, "I "); break; case 2: - ri.Printf( PRINT_ALL, "IA " ); + ri.Printf(PRINT_ALL, "IA "); break; case 3: - ri.Printf( PRINT_ALL, "RGB " ); + ri.Printf(PRINT_ALL, "RGB "); break; case 4: - ri.Printf( PRINT_ALL, "RGBA " ); + ri.Printf(PRINT_ALL, "RGBA "); break; case GL_RGBA8: - ri.Printf( PRINT_ALL, "RGBA8" ); + ri.Printf(PRINT_ALL, "RGBA8"); break; case GL_RGB8: - ri.Printf( PRINT_ALL, "RGB8" ); + ri.Printf(PRINT_ALL, "RGB8"); break; case GL_RGB4_S3TC: - ri.Printf( PRINT_ALL, "S3TC " ); + ri.Printf(PRINT_ALL, "S3TC "); break; case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: - ri.Printf( PRINT_ALL, "DXT1 " ); + ri.Printf(PRINT_ALL, "DXT1 "); break; case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - ri.Printf( PRINT_ALL, "DXT5 " ); + ri.Printf(PRINT_ALL, "DXT5 "); break; case GL_RGBA4: - ri.Printf( PRINT_ALL, "RGBA4" ); + ri.Printf(PRINT_ALL, "RGBA4"); break; case GL_RGB5: - ri.Printf( PRINT_ALL, "RGB5 " ); + ri.Printf(PRINT_ALL, "RGB5 "); break; default: - ri.Printf( PRINT_ALL, "???? " ); + ri.Printf(PRINT_ALL, "???? "); } - switch ( image->wrapClampMode ) { + switch (image->wrapClampMode) { case GL_REPEAT: - ri.Printf( PRINT_ALL, "rept " ); + ri.Printf(PRINT_ALL, "rept "); break; case GL_CLAMP: - ri.Printf( PRINT_ALL, "clmp " ); + ri.Printf(PRINT_ALL, "clmp "); break; case GL_CLAMP_TO_EDGE: - ri.Printf( PRINT_ALL, "clpE " ); + ri.Printf(PRINT_ALL, "clpE "); break; default: - ri.Printf( PRINT_ALL, "%4i ", image->wrapClampMode ); + ri.Printf(PRINT_ALL, "%4i ", image->wrapClampMode); break; } - ri.Printf( PRINT_ALL, "%s\n", image->imgName ); + ri.Printf(PRINT_ALL, "%s\n", image->imgName); i++; } - ri.Printf( PRINT_ALL, " ---------\n"); - ri.Printf( PRINT_ALL, " -w-- -h-- -mm- -if- wrap --name-------\n"); - ri.Printf( PRINT_ALL, " %i total texels (not including mipmaps)\n", texels ); - ri.Printf( PRINT_ALL, " %.2fMB total texture mem (not including mipmaps)\n", texBytes/1048576.0f ); - ri.Printf( PRINT_ALL, " %i total images\n\n", iNumImages ); + ri.Printf(PRINT_ALL, " ---------\n"); + ri.Printf(PRINT_ALL, " -w-- -h-- -mm- -if- wrap --name-------\n"); + ri.Printf(PRINT_ALL, " %i total texels (not including mipmaps)\n", texels); + ri.Printf(PRINT_ALL, " %.2fMB total texture mem (not including mipmaps)\n", texBytes / 1048576.0f); + ri.Printf(PRINT_ALL, " %i total images\n\n", iNumImages); } //======================================================================= - /* ================ R_LightScaleTexture @@ -314,48 +302,37 @@ Scale up the pixel values in a texture to increase the lighting range ================ */ -void R_LightScaleTexture (unsigned *in, int inwidth, int inheight, qboolean only_gamma ) -{ - if ( only_gamma ) - { - if ( !glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders ) - { - int i, c; - byte *p; +void R_LightScaleTexture(unsigned *in, int inwidth, int inheight, qboolean only_gamma) { + if (only_gamma) { + if (!glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) { + int i, c; + byte *p; p = (byte *)in; - c = inwidth*inheight; - for (i=0 ; i> 1; outHeight = inHeight >> 1; - temp = (unsigned int *)Hunk_AllocateTempMemory( outWidth * outHeight * 4 ); + temp = (unsigned int *)Hunk_AllocateTempMemory(outWidth * outHeight * 4); inWidthMask = inWidth - 1; inHeightMask = inHeight - 1; - for ( i = 0 ; i < outHeight ; i++ ) { - for ( j = 0 ; j < outWidth ; j++ ) { - outpix = (byte *) ( temp + i * outWidth + j ); - for ( k = 0 ; k < 4 ; k++ ) { - total = - 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 1 * ((byte *)&in[ ((i*2-1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 4 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k] + - - 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2)&inWidthMask) ])[k] + - 2 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask) ])[k] + - 1 * ((byte *)&in[ ((i*2+2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask) ])[k]; + for (i = 0; i < outHeight; i++) { + for (j = 0; j < outWidth; j++) { + outpix = (byte *)(temp + i * outWidth + j); + for (k = 0; k < 4; k++) { + total = 1 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 1 * ((byte *)&in[((i * 2 - 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 2 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 2 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 4 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 1) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k] + + + 1 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 - 1) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2) & inWidthMask)])[k] + + 2 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 1) & inWidthMask)])[k] + + 1 * ((byte *)&in[((i * 2 + 2) & inHeightMask) * inWidth + ((j * 2 + 2) & inWidthMask)])[k]; outpix[k] = total / 36; } } } - memcpy( in, temp, outWidth * outHeight * 4 ); - Hunk_FreeTempMemory( temp ); + memcpy(in, temp, outWidth * outHeight * 4); + Hunk_FreeTempMemory(temp); } /* @@ -428,17 +403,17 @@ R_MipMap Operates in place, quartering the size of the texture ================ */ -static void R_MipMap (byte *in, int width, int height) { - int i, j; - byte *out; - int row; +static void R_MipMap(byte *in, int width, int height) { + int i, j; + byte *out; + int row; - if ( !r_simpleMipMaps->integer ) { - R_MipMap2( (unsigned *)in, width, height ); + if (!r_simpleMipMaps->integer) { + R_MipMap2((unsigned *)in, width, height); return; } - if ( width == 1 && height == 1 ) { + if (width == 1 && height == 1) { return; } @@ -447,28 +422,27 @@ static void R_MipMap (byte *in, int width, int height) { width >>= 1; height >>= 1; - if ( width == 0 || height == 0 ) { - width += height; // get largest - for (i=0 ; i>1; - out[1] = ( in[1] + in[5] )>>1; - out[2] = ( in[2] + in[6] )>>1; - out[3] = ( in[3] + in[7] )>>1; + if (width == 0 || height == 0) { + width += height; // get largest + for (i = 0; i < width; i++, out += 4, in += 8) { + out[0] = (in[0] + in[4]) >> 1; + out[1] = (in[1] + in[5]) >> 1; + out[2] = (in[2] + in[6]) >> 1; + out[3] = (in[3] + in[7]) >> 1; } return; } - for (i=0 ; i>2; - out[1] = (in[1] + in[5] + in[row+1] + in[row+5])>>2; - out[2] = (in[2] + in[6] + in[row+2] + in[row+6])>>2; - out[3] = (in[3] + in[7] + in[row+3] + in[row+7])>>2; + for (i = 0; i < height; i++, in += row) { + for (j = 0; j < width; j++, out += 4, in += 8) { + out[0] = (in[0] + in[4] + in[row + 0] + in[row + 4]) >> 2; + out[1] = (in[1] + in[5] + in[row + 1] + in[row + 5]) >> 2; + out[2] = (in[2] + in[6] + in[row + 2] + in[row + 6]) >> 2; + out[3] = (in[3] + in[7] + in[row + 3] + in[row + 7]) >> 2; } } } - /* ================== R_BlendOverTexture @@ -476,68 +450,46 @@ R_BlendOverTexture Apply a color blend over a set of pixels ================== */ -static void R_BlendOverTexture( byte *data, int pixelCount, byte blend[4] ) { - int i; - int inverseAlpha; - int premult[3]; +static void R_BlendOverTexture(byte *data, int pixelCount, byte blend[4]) { + int i; + int inverseAlpha; + int premult[3]; inverseAlpha = 255 - blend[3]; premult[0] = blend[0] * blend[3]; premult[1] = blend[1] * blend[3]; premult[2] = blend[2] * blend[3]; - for ( i = 0 ; i < pixelCount ; i++, data+=4 ) { - data[0] = ( data[0] * inverseAlpha + premult[0] ) >> 9; - data[1] = ( data[1] * inverseAlpha + premult[1] ) >> 9; - data[2] = ( data[2] * inverseAlpha + premult[2] ) >> 9; + for (i = 0; i < pixelCount; i++, data += 4) { + data[0] = (data[0] * inverseAlpha + premult[0]) >> 9; + data[1] = (data[1] * inverseAlpha + premult[1]) >> 9; + data[2] = (data[2] * inverseAlpha + premult[2]) >> 9; } } -byte mipBlendColors[16][4] = { - {0,0,0,0}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, - {255,0,0,128}, - {0,255,0,128}, - {0,0,255,128}, +byte mipBlendColors[16][4] = { + {0, 0, 0, 0}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, + {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, {255, 0, 0, 128}, {0, 255, 0, 128}, {0, 0, 255, 128}, }; - - - - -class CStringComparator -{ -public: - bool operator()(const char *s1, const char *s2) const { return(strcmp(s1, s2) < 0); } +class CStringComparator { + public: + bool operator()(const char *s1, const char *s2) const { return (strcmp(s1, s2) < 0); } }; -typedef std::map AllocatedImages_t; +typedef std::map AllocatedImages_t; AllocatedImages_t AllocatedImages; AllocatedImages_t::iterator itAllocatedImages; -int giTextureBindNum = 1024; // will be set to this anyway at runtime, but wtf? - +int giTextureBindNum = 1024; // will be set to this anyway at runtime, but wtf? // return = number of images in the list, for those interested // -int R_Images_StartIteration(void) -{ +int R_Images_StartIteration(void) { itAllocatedImages = AllocatedImages.begin(); return AllocatedImages.size(); } -image_t *R_Images_GetNextIteration(void) -{ +image_t *R_Images_GetNextIteration(void) { if (itAllocatedImages == AllocatedImages.end()) return NULL; @@ -546,60 +498,46 @@ image_t *R_Images_GetNextIteration(void) return pImage; } -// clean up anything to do with an image_t struct, but caller will have to clear the internal to an image_t struct ready for either struct free() or overwrite... +// clean up anything to do with an image_t struct, but caller will have to clear the internal to an image_t struct ready for either struct free() or +// overwrite... // // (avoid using ri->xxxx stuff here in case running on dedicated) // -static void R_Images_DeleteImageContents( image_t *pImage ) -{ - assert(pImage); // should never be called with NULL - if (pImage) - { - qglDeleteTextures( 1, &pImage->texnum ); +static void R_Images_DeleteImageContents(image_t *pImage) { + assert(pImage); // should never be called with NULL + if (pImage) { + qglDeleteTextures(1, &pImage->texnum); Z_Free(pImage); } } - - - - /* =============== Upload32 =============== */ -static void Upload32( unsigned *data, - GLenum format, - qboolean mipmap, - qboolean picmip, - qboolean isLightmap, - qboolean allowTC, - int *pformat, - word *pUploadWidth, word *pUploadHeight, bool bRectangle = false ) -{ +static void Upload32(unsigned *data, GLenum format, qboolean mipmap, qboolean picmip, qboolean isLightmap, qboolean allowTC, int *pformat, word *pUploadWidth, + word *pUploadHeight, bool bRectangle = false) { GLuint uiTarget = GL_TEXTURE_2D; - if ( bRectangle ) - { + if (bRectangle) { uiTarget = GL_TEXTURE_RECTANGLE_ARB; } - if (format == GL_RGBA) - { - int samples; - int i, c; - byte *scan; - float rMax = 0, gMax = 0, bMax = 0; - int width = *pUploadWidth; - int height = *pUploadHeight; + if (format == GL_RGBA) { + int samples; + int i, c; + byte *scan; + float rMax = 0, gMax = 0, bMax = 0; + int width = *pUploadWidth; + int height = *pUploadHeight; // // perform optional picmip operation // - if ( picmip ) { - for(i = 0; i < r_picmip->integer; i++) { - R_MipMap( (byte *)data, width, height ); + if (picmip) { + for (i = 0; i < r_picmip->integer; i++) { + R_MipMap((byte *)data, width, height); width >>= 1; height >>= 1; if (width < 1) { @@ -616,8 +554,8 @@ static void Upload32( unsigned *data, // scale both axis down equally so we don't have to // deal with a half mip resampling // - while ( width > glConfig.maxTextureSize || height > glConfig.maxTextureSize ) { - R_MipMap( (byte *)data, width, height ); + while (width > glConfig.maxTextureSize || height > glConfig.maxTextureSize) { + R_MipMap((byte *)data, width, height); width >>= 1; height >>= 1; } @@ -626,84 +564,57 @@ static void Upload32( unsigned *data, // scan the texture for each channel's max values // and verify if the alpha channel is being used or not // - c = width*height; + c = width * height; scan = ((byte *)data); samples = 3; - for ( i = 0; i < c; i++ ) - { - if ( scan[i*4+0] > rMax ) - { - rMax = scan[i*4+0]; + for (i = 0; i < c; i++) { + if (scan[i * 4 + 0] > rMax) { + rMax = scan[i * 4 + 0]; } - if ( scan[i*4+1] > gMax ) - { - gMax = scan[i*4+1]; + if (scan[i * 4 + 1] > gMax) { + gMax = scan[i * 4 + 1]; } - if ( scan[i*4+2] > bMax ) - { - bMax = scan[i*4+2]; + if (scan[i * 4 + 2] > bMax) { + bMax = scan[i * 4 + 2]; } - if ( scan[i*4 + 3] != 255 ) - { + if (scan[i * 4 + 3] != 255) { samples = 4; break; } } // select proper internal format - if ( samples == 3 ) - { - if ( glConfig.textureCompression == TC_S3TC && allowTC ) - { + if (samples == 3) { + if (glConfig.textureCompression == TC_S3TC && allowTC) { *pformat = GL_RGB4_S3TC; - } - else if ( glConfig.textureCompression == TC_S3TC_DXT && allowTC ) - { // Compress purely color - no alpha - if ( r_texturebits->integer == 16 ) { - *pformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; //this format cuts to 16 bit - } - else {//if we aren't using 16 bit then, use 32 bit compression + } else if (glConfig.textureCompression == TC_S3TC_DXT && allowTC) { // Compress purely color - no alpha + if (r_texturebits->integer == 16) { + *pformat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; // this format cuts to 16 bit + } else { // if we aren't using 16 bit then, use 32 bit compression *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; } - } - else if ( isLightmap && r_texturebitslm->integer > 0 ) - { + } else if (isLightmap && r_texturebitslm->integer > 0) { int lmBits = r_texturebitslm->integer & 0x30; // 16 or 32 // Allow different bit depth when we are a lightmap - if ( lmBits == 16 ) + if (lmBits == 16) *pformat = GL_RGB5; else *pformat = GL_RGB8; - } - else if ( r_texturebits->integer == 16 ) - { + } else if (r_texturebits->integer == 16) { *pformat = GL_RGB5; - } - else if ( r_texturebits->integer == 32 ) - { + } else if (r_texturebits->integer == 32) { *pformat = GL_RGB8; - } - else - { + } else { *pformat = 3; } - } - else if ( samples == 4 ) - { - if ( glConfig.textureCompression == TC_S3TC_DXT && allowTC) - { // Compress both alpha and color + } else if (samples == 4) { + if (glConfig.textureCompression == TC_S3TC_DXT && allowTC) { // Compress both alpha and color *pformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - } - else if ( r_texturebits->integer == 16 ) - { + } else if (r_texturebits->integer == 16) { *pformat = GL_RGBA4; - } - else if ( r_texturebits->integer == 32 ) - { + } else if (r_texturebits->integer == 32) { *pformat = GL_RGBA8; - } - else - { + } else { *pformat = 4; } } @@ -712,24 +623,21 @@ static void Upload32( unsigned *data, *pUploadHeight = height; // copy or resample data as appropriate for first MIP level - if (!mipmap) - { - qglTexImage2D( uiTarget, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + if (!mipmap) { + qglTexImage2D(uiTarget, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); goto done; } - R_LightScaleTexture (data, width, height, (qboolean)!mipmap ); + R_LightScaleTexture(data, width, height, (qboolean)!mipmap); - qglTexImage2D( uiTarget, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexImage2D(uiTarget, 0, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - if (mipmap) - { - int miplevel; + if (mipmap) { + int miplevel; miplevel = 0; - while (width > 1 || height > 1) - { - R_MipMap( (byte *)data, width, height ); + while (width > 1 || height > 1) { + R_MipMap((byte *)data, width, height); width >>= 1; height >>= 1; if (width < 1) @@ -738,71 +646,58 @@ static void Upload32( unsigned *data, height = 1; miplevel++; - if ( r_colorMipLevels->integer ) - { - R_BlendOverTexture( (byte *)data, width * height, mipBlendColors[miplevel] ); + if (r_colorMipLevels->integer) { + R_BlendOverTexture((byte *)data, width * height, mipBlendColors[miplevel]); } - qglTexImage2D( uiTarget, miplevel, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexImage2D(uiTarget, miplevel, *pformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } } - } - else - { + } else { } done: - if (mipmap) - { + if (mipmap) { qglTexParameterf(uiTarget, GL_TEXTURE_MIN_FILTER, gl_filter_min); qglTexParameterf(uiTarget, GL_TEXTURE_MAG_FILTER, gl_filter_max); - if(r_ext_texture_filter_anisotropic->integer>1 && glConfig.maxTextureFilterAnisotropy>0) - { - qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value ); + if (r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0) { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); } - } - else - { - qglTexParameterf(uiTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameterf(uiTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } else { + qglTexParameterf(uiTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameterf(uiTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } GL_CheckErrors(); } -static void GL_ResetBinds(void) -{ - memset( glState.currenttextures, 0, sizeof( glState.currenttextures ) ); - if ( qglActiveTextureARB ) { - GL_SelectTexture( 1 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); - GL_SelectTexture( 0 ); - qglBindTexture( GL_TEXTURE_2D, 0 ); +static void GL_ResetBinds(void) { + memset(glState.currenttextures, 0, sizeof(glState.currenttextures)); + if (qglActiveTextureARB) { + GL_SelectTexture(1); + qglBindTexture(GL_TEXTURE_2D, 0); + GL_SelectTexture(0); + qglBindTexture(GL_TEXTURE_2D, 0); } else { - qglBindTexture( GL_TEXTURE_2D, 0 ); + qglBindTexture(GL_TEXTURE_2D, 0); } } - // special function used in conjunction with "devmapbsp"... // // (avoid using ri->xxxx stuff here in case running on dedicated) // -void R_Images_DeleteLightMaps(void) -{ - for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* empty */) - { +void R_Images_DeleteLightMaps(void) { + for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* empty */) { image_t *pImage = (*itImage).second; - if (pImage->imgName[0] == '*' && strstr(pImage->imgName,"lightmap")) // loose check, but should be ok + if (pImage->imgName[0] == '*' && strstr(pImage->imgName, "lightmap")) // loose check, but should be ok { R_Images_DeleteImageContents(pImage); AllocatedImages.erase(itImage++); - } - else - { + } else { ++itImage; } } @@ -812,31 +707,25 @@ void R_Images_DeleteLightMaps(void) // special function currently only called by Dissolve code... // -void R_Images_DeleteImage(image_t *pImage) -{ +void R_Images_DeleteImage(image_t *pImage) { // Even though we supply the image handle, we need to get the corresponding iterator entry... // AllocatedImages_t::iterator itImage = AllocatedImages.find(pImage->imgName); - if (itImage != AllocatedImages.end()) - { + if (itImage != AllocatedImages.end()) { R_Images_DeleteImageContents(pImage); AllocatedImages.erase(itImage); - } - else - { + } else { assert(0); } } // called only at app startup, vid_restart, app-exit // -void R_Images_Clear(void) -{ +void R_Images_Clear(void) { image_t *pImage; // int iNumImages = - R_Images_StartIteration(); - while ( (pImage = R_Images_GetNextIteration()) != NULL) - { + R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { R_Images_DeleteImageContents(pImage); } @@ -845,52 +734,45 @@ void R_Images_Clear(void) giTextureBindNum = 1024; } +void RE_RegisterImages_Info_f(void) { + image_t *pImage = NULL; + int iImage = 0; + int iTexels = 0; -void RE_RegisterImages_Info_f( void ) -{ - image_t *pImage = NULL; - int iImage = 0; - int iTexels = 0; - - int iNumImages = R_Images_StartIteration(); - while ( (pImage = R_Images_GetNextIteration()) != NULL) - { - ri.Printf( PRINT_ALL, "%d: (%4dx%4dy) \"%s\"",iImage, pImage->width, pImage->height, pImage->imgName); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED ", levused %d",pImage->iLastLevelUsedOn); - ri.Printf( PRINT_ALL, "\n"); + int iNumImages = R_Images_StartIteration(); + while ((pImage = R_Images_GetNextIteration()) != NULL) { + ri.Printf(PRINT_ALL, "%d: (%4dx%4dy) \"%s\"", iImage, pImage->width, pImage->height, pImage->imgName); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED ", levused %d", pImage->iLastLevelUsedOn); + ri.Printf(PRINT_ALL, "\n"); iTexels += pImage->width * pImage->height; iImage++; } - ri.Printf( PRINT_ALL, "%d Images. %d (%.2fMB) texels total, (not including mipmaps)\n",iNumImages, iTexels, (float)iTexels / 1024.0f / 1024.0f); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterMedia_GetLevel(): %d",RE_RegisterMedia_GetLevel()); + ri.Printf(PRINT_ALL, "%d Images. %d (%.2fMB) texels total, (not including mipmaps)\n", iNumImages, iTexels, (float)iTexels / 1024.0f / 1024.0f); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterMedia_GetLevel(): %d", RE_RegisterMedia_GetLevel()); } // currently, this just goes through all the images and dumps any not referenced on this level... // -qboolean RE_RegisterImages_LevelLoadEnd(void) -{ - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterImages_LevelLoadEnd():\n"); +qboolean RE_RegisterImages_LevelLoadEnd(void) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterImages_LevelLoadEnd():\n"); -// int iNumImages = AllocatedImages.size(); // more for curiosity, really. + // int iNumImages = AllocatedImages.size(); // more for curiosity, really. qboolean imageDeleted = qtrue; - for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* blank */) - { + for (AllocatedImages_t::iterator itImage = AllocatedImages.begin(); itImage != AllocatedImages.end(); /* blank */) { qboolean bEraseOccured = qfalse; image_t *pImage = (*itImage).second; // don't un-register system shaders (*fog, *dlight, *white, *default), but DO de-register lightmaps ("*/lightmap%d") - if (pImage->imgName[0] != '*' || strchr(pImage->imgName,'/')) - { + if (pImage->imgName[0] != '*' || strchr(pImage->imgName, '/')) { // image used on this level? // - if ( pImage->iLastLevelUsedOn != RE_RegisterMedia_GetLevel() ) - { + if (pImage->iLastLevelUsedOn != RE_RegisterMedia_GetLevel()) { // nope, so dump it... // - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Dumping image \"%s\"\n",pImage->imgName); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Dumping image \"%s\"\n", pImage->imgName); R_Images_DeleteImageContents(pImage); @@ -900,37 +782,32 @@ qboolean RE_RegisterImages_LevelLoadEnd(void) } } - if ( !bEraseOccured ) - { + if (!bEraseOccured) { ++itImage; } } - // this check can be deleted AFAIC, it seems to be just a quake thing... // -// iNumImages = R_Images_StartIteration(); -// if (iNumImages > MAX_DRAWIMAGES) -// { -// ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Level uses %d images, old limit was MAX_DRAWIMAGES (%d)\n", iNumImages, MAX_DRAWIMAGES); -// } + // iNumImages = R_Images_StartIteration(); + // if (iNumImages > MAX_DRAWIMAGES) + // { + // ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Level uses %d images, old limit was MAX_DRAWIMAGES (%d)\n", iNumImages, MAX_DRAWIMAGES); + // } - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterImages_LevelLoadEnd(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterImages_LevelLoadEnd(): Ok\n"); GL_ResetBinds(); return imageDeleted; } - - // returns image_t struct if we already have this, else NULL. No disk-open performed // (important for creating default images). // // This is called by both R_FindImageFile and anything that creates default images... // -static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode ) -{ +static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode) { if (!name) { return NULL; } @@ -941,21 +818,20 @@ static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboole // see if the image is already loaded // AllocatedImages_t::iterator itAllocatedImage = AllocatedImages.find(pName); - if (itAllocatedImage != AllocatedImages.end()) - { + if (itAllocatedImage != AllocatedImages.end()) { image_t *pImage = (*itAllocatedImage).second; // the white image can be used with any set of parms, but other mismatches are errors... // - if ( strcmp( pName, "*white" ) ) { - if ( pImage->mipmap != !!mipmap ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed mipmap parm\n", pName ); + if (strcmp(pName, "*white")) { + if (pImage->mipmap != !!mipmap) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed mipmap parm\n", pName); } - if ( pImage->allowPicmip != !!allowPicmip ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed allowPicmip parm\n", pName ); + if (pImage->allowPicmip != !!allowPicmip) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed allowPicmip parm\n", pName); } - if ( pImage->wrapClampMode != glWrapClampMode ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed glWrapClampMode parm\n", pName ); + if (pImage->wrapClampMode != glWrapClampMode) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: reused image %s with mixed glWrapClampMode parm\n", pName); } } @@ -967,8 +843,6 @@ static image_t *R_FindImageFile_NoLoad(const char *name, qboolean mipmap, qboole return NULL; } - - /* ================ R_CreateImage @@ -976,42 +850,39 @@ R_CreateImage This is the only way any image_t are created ================ */ -image_t *R_CreateImage( const char *name, const byte *pic, int width, int height, - GLenum format, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode, bool bRectangle ) -{ - image_t *image; - qboolean isLightmap = qfalse; - - if (strlen(name) >= MAX_QPATH ) { - Com_Error (ERR_DROP, "R_CreateImage: \"%s\" is too long\n", name); +image_t *R_CreateImage(const char *name, const byte *pic, int width, int height, GLenum format, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, + int glWrapClampMode, bool bRectangle) { + image_t *image; + qboolean isLightmap = qfalse; + + if (strlen(name) >= MAX_QPATH) { + Com_Error(ERR_DROP, "R_CreateImage: \"%s\" is too long\n", name); } - if(glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { + if (glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { glWrapClampMode = GL_CLAMP_TO_EDGE; } - if (name[0] == '*') - { - const char *psLightMapNameSearchPos = strrchr(name,'/'); - if ( psLightMapNameSearchPos && !strncmp( psLightMapNameSearchPos+1, "lightmap", 8 ) ) { + if (name[0] == '*') { + const char *psLightMapNameSearchPos = strrchr(name, '/'); + if (psLightMapNameSearchPos && !strncmp(psLightMapNameSearchPos + 1, "lightmap", 8)) { isLightmap = qtrue; } } - if ( (width&(width-1)) || (height&(height-1)) ) - { - Com_Error( ERR_FATAL, "R_CreateImage: %s dimensions (%i x %i) not power of 2!\n",name,width,height); + if ((width & (width - 1)) || (height & (height - 1))) { + Com_Error(ERR_FATAL, "R_CreateImage: %s dimensions (%i x %i) not power of 2!\n", name, width, height); } - image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode ); + image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode); if (image) { return image; } - image = (image_t*) Z_Malloc( sizeof( image_t ), TAG_IMAGE_T, qtrue ); -// memset(image,0,sizeof(*image)); // qtrue above does this + image = (image_t *)Z_Malloc(sizeof(image_t), TAG_IMAGE_T, qtrue); + // memset(image,0,sizeof(*image)); // qtrue above does this - image->texnum = 1024 + giTextureBindNum++; // ++ is of course staggeringly important... + image->texnum = 1024 + giTextureBindNum++; // ++ is of course staggeringly important... // record which map it was used on... // @@ -1026,47 +897,37 @@ image_t *R_CreateImage( const char *name, const byte *pic, int width, int height image->height = height; image->wrapClampMode = glWrapClampMode; - if ( qglActiveTextureARB ) { - GL_SelectTexture( 0 ); + if (qglActiveTextureARB) { + GL_SelectTexture(0); } GLuint uiTarget = GL_TEXTURE_2D; - if ( bRectangle ) - { - qglDisable( uiTarget ); + if (bRectangle) { + qglDisable(uiTarget); uiTarget = GL_TEXTURE_RECTANGLE_ARB; - qglEnable( uiTarget ); - glWrapClampMode = GL_CLAMP_TO_EDGE; // default mode supported by rectangle. - qglBindTexture( uiTarget, image->texnum ); - } - else - { + qglEnable(uiTarget); + glWrapClampMode = GL_CLAMP_TO_EDGE; // default mode supported by rectangle. + qglBindTexture(uiTarget, image->texnum); + } else { GL_Bind(image); } - Upload32( (unsigned *)pic, format, - (qboolean)image->mipmap, - allowPicmip, - isLightmap, - allowTC, - &image->internalFormat, - &image->width, - &image->height, bRectangle ); + Upload32((unsigned *)pic, format, (qboolean)image->mipmap, allowPicmip, isLightmap, allowTC, &image->internalFormat, &image->width, &image->height, + bRectangle); - qglTexParameterf( uiTarget, GL_TEXTURE_WRAP_S, glWrapClampMode ); - qglTexParameterf( uiTarget, GL_TEXTURE_WRAP_T, glWrapClampMode ); + qglTexParameterf(uiTarget, GL_TEXTURE_WRAP_S, glWrapClampMode); + qglTexParameterf(uiTarget, GL_TEXTURE_WRAP_T, glWrapClampMode); - qglBindTexture( uiTarget, 0 ); //jfm: i don't know why this is here, but it breaks lightmaps when there's only 1 - glState.currenttextures[glState.currenttmu] = 0; //mark it not bound + qglBindTexture(uiTarget, 0); // jfm: i don't know why this is here, but it breaks lightmaps when there's only 1 + glState.currenttextures[glState.currenttmu] = 0; // mark it not bound const char *psNewName = GenerateImageMappingName(name); Q_strncpyz(image->imgName, psNewName, sizeof(image->imgName)); - AllocatedImages[ image->imgName ] = image; + AllocatedImages[image->imgName] = image; - if ( bRectangle ) - { - qglDisable( uiTarget ); - qglEnable( GL_TEXTURE_2D ); + if (bRectangle) { + qglDisable(uiTarget); + qglEnable(GL_TEXTURE_2D); } return image; @@ -1080,12 +941,12 @@ Finds or loads the given image. Returns NULL if it fails, not a default image. ============== */ -image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode ) { - image_t *image; - int width, height; - byte *pic; +image_t *R_FindImageFile(const char *name, qboolean mipmap, qboolean allowPicmip, qboolean allowTC, int glWrapClampMode) { + image_t *image; + int width, height; + byte *pic; - if (!name || ri.Cvar_VariableIntegerValue( "dedicated" ) ) // stop ghoul2 horribleness as regards image loading from server + if (!name || ri.Cvar_VariableIntegerValue("dedicated")) // stop ghoul2 horribleness as regards image loading from server { return NULL; } @@ -1093,11 +954,11 @@ image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmi // need to do this here as well as in R_CreateImage, or R_FindImageFile_NoLoad() may complain about // different clamp parms used... // - if(glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { + if (glConfig.clampToEdgeAvailable && glWrapClampMode == GL_CLAMP) { glWrapClampMode = GL_CLAMP_TO_EDGE; } - image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode ); + image = R_FindImageFile_NoLoad(name, mipmap, allowPicmip, allowTC, glWrapClampMode); if (image) { return image; } @@ -1105,87 +966,76 @@ image_t *R_FindImageFile( const char *name, qboolean mipmap, qboolean allowPicmi // // load the pic from disk // - R_LoadImage( name, &pic, &width, &height ); - if ( pic == NULL ) { // if we dont get a successful load - return NULL; // bail + R_LoadImage(name, &pic, &width, &height); + if (pic == NULL) { // if we dont get a successful load + return NULL; // bail } - // refuse to find any files not power of 2 dims... // - if ( (width&(width-1)) || (height&(height-1)) ) - { - ri.Printf( PRINT_ALL, "Refusing to load non-power-2-dims(%d,%d) pic \"%s\"...\n", width,height,name ); + if ((width & (width - 1)) || (height & (height - 1))) { + ri.Printf(PRINT_ALL, "Refusing to load non-power-2-dims(%d,%d) pic \"%s\"...\n", width, height, name); return NULL; } - image = R_CreateImage( ( char * ) name, pic, width, height, GL_RGBA, mipmap, allowPicmip, allowTC, glWrapClampMode ); - Z_Free( pic ); + image = R_CreateImage((char *)name, pic, width, height, GL_RGBA, mipmap, allowPicmip, allowTC, glWrapClampMode); + Z_Free(pic); return image; } - /* ================ R_CreateDlightImage ================ */ -#define DLIGHT_SIZE 16 -static void R_CreateDlightImage( void ) -{ - int width, height; - byte *pic; +#define DLIGHT_SIZE 16 +static void R_CreateDlightImage(void) { + int width, height; + byte *pic; R_LoadImage("gfx/2d/dlight", &pic, &width, &height); - if (pic) - { - tr.dlightImage = R_CreateImage("*dlight", pic, width, height, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP ); + if (pic) { + tr.dlightImage = R_CreateImage("*dlight", pic, width, height, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP); Z_Free(pic); - } - else - { // if we dont get a successful load - int x,y; - byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; - int b; + } else { // if we dont get a successful load + int x, y; + byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; + int b; // make a centered inverse-square falloff blob for dynamic lighting - for (x=0 ; x 255) { b = 255; - } else if ( b < 75 ) { + } else if (b < 75) { b = 0; } - data[y][x][0] = - data[y][x][1] = - data[y][x][2] = b; + data[y][x][0] = data[y][x][1] = data[y][x][2] = b; data[y][x][3] = 255; } } - tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP ); + tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, GL_RGBA, qfalse, qfalse, qfalse, GL_CLAMP); } } - /* ================= R_InitFogTable ================= */ -void R_InitFogTable( void ) { - int i; - float d; - float exp; +void R_InitFogTable(void) { + int i; + float d; + float exp; exp = 0.5; - for ( i = 0 ; i < FOG_TABLE_SIZE ; i++ ) { - d = pow ( (float)i/(FOG_TABLE_SIZE-1), exp ); + for (i = 0; i < FOG_TABLE_SIZE; i++) { + d = pow((float)i / (FOG_TABLE_SIZE - 1), exp); tr.fogTable[i] = d; } @@ -1200,28 +1050,28 @@ This is called for each texel of the fog texture on startup and for each vertex of transparent shaders in fog dynamically ================ */ -float R_FogFactor( float s, float t ) { - float d; +float R_FogFactor(float s, float t) { + float d; - s -= 1.0/512; - if ( s < 0 ) { + s -= 1.0 / 512; + if (s < 0) { return 0; } - if ( t < 1.0/32 ) { + if (t < 1.0 / 32) { return 0; } - if ( t < 31.0/32 ) { - s *= (t - 1.0f/32.0f) / (30.0f/32.0f); + if (t < 31.0 / 32) { + s *= (t - 1.0f / 32.0f) / (30.0f / 32.0f); } // we need to leave a lot of clamp range s *= 8; - if ( s > 1.0 ) { + if (s > 1.0) { s = 1.0; } - d = tr.fogTable[ (int)(s * (FOG_TABLE_SIZE-1)) ]; + d = tr.fogTable[(int)(s * (FOG_TABLE_SIZE - 1))]; return d; } @@ -1231,39 +1081,37 @@ float R_FogFactor( float s, float t ) { R_CreateFogImage ================ */ -#define FOG_S 256 -#define FOG_T 32 -static void R_CreateFogImage( void ) { - int x,y; - byte *data; - float d; - float borderColor[4]; +#define FOG_S 256 +#define FOG_T 32 +static void R_CreateFogImage(void) { + int x, y; + byte *data; + float d; + float borderColor[4]; - data = (unsigned char *)Hunk_AllocateTempMemory( FOG_S * FOG_T * 4 ); + data = (unsigned char *)Hunk_AllocateTempMemory(FOG_S * FOG_T * 4); // S is distance, T is depth - for (x=0 ; xinteger > glConfig.vidWidth ) - { + if (r_DynamicGlowWidth->integer > glConfig.vidWidth) { r_DynamicGlowWidth->integer = glConfig.vidWidth; } - if ( r_DynamicGlowHeight->integer > glConfig.vidHeight ) - { + if (r_DynamicGlowHeight->integer > glConfig.vidHeight) { r_DynamicGlowHeight->integer = glConfig.vidHeight; } tr.blurImage = 1024 + giTextureBindNum++; - qglBindTexture( GL_TEXTURE_RECTANGLE_ARB, tr.blurImage ); - qglTexImage2D( GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA16, r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer, 0, GL_RGB, GL_FLOAT, 0 ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP ); - qglTexParameteri( GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP ); - qglDisable( GL_TEXTURE_RECTANGLE_ARB ); - - if ( glConfigExt.doGammaCorrectionWithShaders ) - { - qglEnable( GL_TEXTURE_3D ); + qglBindTexture(GL_TEXTURE_RECTANGLE_ARB, tr.blurImage); + qglTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA16, r_DynamicGlowWidth->integer, r_DynamicGlowHeight->integer, 0, GL_RGB, GL_FLOAT, 0); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP); + qglTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP); + qglDisable(GL_TEXTURE_RECTANGLE_ARB); + + if (glConfigExt.doGammaCorrectionWithShaders) { + qglEnable(GL_TEXTURE_3D); tr.gammaCorrectLUTImage = 1024 + giTextureBindNum++; qglBindTexture(GL_TEXTURE_3D, tr.gammaCorrectLUTImage); qglTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, 64, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); @@ -1375,20 +1208,18 @@ void R_CreateBuiltinImages( void ) { // with overbright bits active, we need an image which is some fraction of full color, // for default lightmaps, etc - for (x=0 ; xinteger; - if ( !glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders ) { - tr.overbrightBits = 0; // need hardware gamma for overbright + if (!glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) { + tr.overbrightBits = 0; // need hardware gamma for overbright } // never overbright in windowed mode - if ( !glConfig.isFullscreen ) - { + if (!glConfig.isFullscreen) { tr.overbrightBits = 0; } - if ( tr.overbrightBits > 1 ) { + if (tr.overbrightBits > 1) { tr.overbrightBits = 1; } - if ( tr.overbrightBits < 0 ) { + if (tr.overbrightBits < 0) { tr.overbrightBits = 0; } - tr.identityLight = 1.0f / ( 1 << tr.overbrightBits ); + tr.identityLight = 1.0f / (1 << tr.overbrightBits); tr.identityLightByte = 255 * tr.identityLight; - - if ( r_intensity->value < 1.0f ) { - ri.Cvar_Set( "r_intensity", "1" ); + if (r_intensity->value < 1.0f) { + ri.Cvar_Set("r_intensity", "1"); } - if ( r_gamma->value < 0.5f ) { - ri.Cvar_Set( "r_gamma", "0.5" ); - } else if ( r_gamma->value > 3.0f ) { - ri.Cvar_Set( "r_gamma", "3.0" ); + if (r_gamma->value < 0.5f) { + ri.Cvar_Set("r_gamma", "0.5"); + } else if (r_gamma->value > 3.0f) { + ri.Cvar_Set("r_gamma", "3.0"); } g = r_gamma->value; shift = tr.overbrightBits; - if ( !glConfigExt.doGammaCorrectionWithShaders ) - { - for ( i = 0; i < 256; i++ ) { - if ( g == 1 ) { + if (!glConfigExt.doGammaCorrectionWithShaders) { + for (i = 0; i < 256; i++) { + if (g == 1) { inf = i; } else { - inf = 255 * pow ( i/255.0f, 1.0f / g ) + 0.5f; + inf = 255 * pow(i / 255.0f, 1.0f / g) + 0.5f; } inf <<= shift; if (inf < 0) { @@ -1464,13 +1291,12 @@ void R_SetColorMappings( void ) { s_gammatable[i] = inf; } - if ( glConfig.deviceSupportsGamma ) - { - ri.WIN_SetGamma( &glConfig, s_gammatable, s_gammatable, s_gammatable ); + if (glConfig.deviceSupportsGamma) { + ri.WIN_SetGamma(&glConfig, s_gammatable, s_gammatable, s_gammatable); } } - for (i=0 ; i<256 ; i++) { + for (i = 0; i < 256; i++) { j = i * r_intensity->value; if (j > 255) { j = 255; @@ -1479,23 +1305,17 @@ void R_SetColorMappings( void ) { } } -void R_SetGammaCorrectionLUT() -{ - if ( glConfigExt.doGammaCorrectionWithShaders ) - { +void R_SetGammaCorrectionLUT() { + if (glConfigExt.doGammaCorrectionWithShaders) { int inf; int shift = tr.overbrightBits; float g = r_gamma->value; byte gammaCorrected[64]; - for ( int i = 0; i < 64; i++ ) - { - if ( g == 1.0f ) - { + for (int i = 0; i < 64; i++) { + if (g == 1.0f) { inf = (int)(((float)i / 63.0f) * 255.0f + 0.5f); - } - else - { + } else { inf = (int)(255.0f * pow((float)i / 63.0f, 1.0f / g) + 0.5f); } @@ -1504,12 +1324,9 @@ void R_SetGammaCorrectionLUT() byte *lutTable = (byte *)ri.Hunk_AllocateTempMemory(64 * 64 * 64 * 3); byte *write = lutTable; - for ( int z = 0; z < 64; z++ ) - { - for ( int y = 0; y < 64; y++ ) - { - for ( int x = 0; x < 64; x++ ) - { + for (int z = 0; z < 64; z++) { + for (int y = 0; y < 64; y++) { + for (int x = 0; x < 64; x++) { *write++ = gammaCorrected[x]; *write++ = gammaCorrected[y]; *write++ = gammaCorrected[z]; @@ -1530,9 +1347,9 @@ void R_SetGammaCorrectionLUT() R_InitImages =============== */ -void R_InitImages( void ) { - //memset(hashTable, 0, sizeof(hashTable)); // DO NOT DO THIS NOW (because of image cacheing) -ste. - // build brightness translation tables +void R_InitImages(void) { + // memset(hashTable, 0, sizeof(hashTable)); // DO NOT DO THIS NOW (because of image cacheing) -ste. + // build brightness translation tables R_SetColorMappings(); // create default texture and white texture @@ -1548,9 +1365,8 @@ R_DeleteTextures */ // (only gets called during vid_restart now (and app exit), not during map load) // -void R_DeleteTextures( void ) { +void R_DeleteTextures(void) { R_Images_Clear(); GL_ResetBinds(); } - diff --git a/codemp/rd-vanilla/tr_init.cpp b/codemp/rd-vanilla/tr_init.cpp index ef4944ab0c..1c3fd1ae61 100644 --- a/codemp/rd-vanilla/tr_init.cpp +++ b/codemp/rd-vanilla/tr_init.cpp @@ -31,181 +31,179 @@ along with this program; if not, see . #include "qcommon/MiniHeap.h" #include "ghoul2/g2_local.h" -glconfig_t glConfig; +glconfig_t glConfig; glconfigExt_t glConfigExt; -glstate_t glState; -window_t window; +glstate_t glState; +window_t window; -static void GfxInfo_f( void ); +static void GfxInfo_f(void); -cvar_t *r_verbose; -cvar_t *r_ignore; +cvar_t *r_verbose; +cvar_t *r_ignore; -cvar_t *r_detailTextures; +cvar_t *r_detailTextures; -cvar_t *r_znear; +cvar_t *r_znear; -cvar_t *r_skipBackEnd; +cvar_t *r_skipBackEnd; -cvar_t *r_measureOverdraw; +cvar_t *r_measureOverdraw; -cvar_t *r_inGameVideo; -cvar_t *r_fastsky; -cvar_t *r_drawSun; -cvar_t *r_dynamiclight; +cvar_t *r_inGameVideo; +cvar_t *r_fastsky; +cvar_t *r_drawSun; +cvar_t *r_dynamiclight; // rjr - removed for hacking cvar_t *r_dlightBacks; -cvar_t *r_lodbias; -cvar_t *r_lodscale; -cvar_t *r_autolodscalevalue; - -cvar_t *r_norefresh; -cvar_t *r_drawentities; -cvar_t *r_drawworld; -cvar_t *r_drawfog; -cvar_t *r_speeds; -cvar_t *r_fullbright; -cvar_t *r_novis; -cvar_t *r_nocull; -cvar_t *r_facePlaneCull; -cvar_t *r_cullRoofFaces; //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww -cvar_t *r_roofCullCeilDist; //ceiling distance cull tolerance -rww -cvar_t *r_roofCullFloorDist; //floor distance cull tolerance -rww -cvar_t *r_showcluster; -cvar_t *r_nocurves; - -cvar_t *r_autoMap; //automap renderside toggle for debugging -rww -cvar_t *r_autoMapBackAlpha; //alpha of automap bg -rww -cvar_t *r_autoMapDisable; //don't calc it (since it's slow in debug) -rww - -cvar_t *r_dlightStyle; -cvar_t *r_surfaceSprites; -cvar_t *r_surfaceWeather; - -cvar_t *r_windSpeed; -cvar_t *r_windAngle; -cvar_t *r_windGust; -cvar_t *r_windDampFactor; -cvar_t *r_windPointForce; -cvar_t *r_windPointX; -cvar_t *r_windPointY; - -cvar_t *r_allowExtensions; - -cvar_t *r_ext_compressed_textures; -cvar_t *r_ext_compressed_lightmaps; -cvar_t *r_ext_preferred_tc_method; -cvar_t *r_ext_gamma_control; -cvar_t *r_ext_multitexture; -cvar_t *r_ext_compiled_vertex_array; -cvar_t *r_ext_texture_env_add; -cvar_t *r_ext_texture_filter_anisotropic; -cvar_t *r_gammaShaders; - -cvar_t *r_environmentMapping; - -cvar_t *r_DynamicGlow; -cvar_t *r_DynamicGlowPasses; -cvar_t *r_DynamicGlowDelta; -cvar_t *r_DynamicGlowIntensity; -cvar_t *r_DynamicGlowSoft; -cvar_t *r_DynamicGlowWidth; -cvar_t *r_DynamicGlowHeight; - -cvar_t *r_ignoreGLErrors; -cvar_t *r_logFile; - -cvar_t *r_primitives; -cvar_t *r_texturebits; -cvar_t *r_texturebitslm; - -cvar_t *r_lightmap; -cvar_t *r_vertexLight; -cvar_t *r_uiFullScreen; -cvar_t *r_shadows; -cvar_t *r_shadowRange; -cvar_t *r_flares; -cvar_t *r_nobind; -cvar_t *r_singleShader; -cvar_t *r_colorMipLevels; -cvar_t *r_picmip; -cvar_t *r_showtris; -cvar_t *r_showsky; -cvar_t *r_shownormals; -cvar_t *r_finish; -cvar_t *r_clear; -cvar_t *r_markcount; -cvar_t *r_textureMode; -cvar_t *r_offsetFactor; -cvar_t *r_offsetUnits; -cvar_t *r_gamma; -cvar_t *r_intensity; -cvar_t *r_lockpvs; -cvar_t *r_noportals; -cvar_t *r_portalOnly; - -cvar_t *r_subdivisions; -cvar_t *r_lodCurveError; - - - -cvar_t *r_overBrightBits; -cvar_t *r_mapOverBrightBits; - -cvar_t *r_debugSurface; -cvar_t *r_simpleMipMaps; - -cvar_t *r_showImages; - -cvar_t *r_ambientScale; -cvar_t *r_directedScale; -cvar_t *r_debugLight; -cvar_t *r_debugSort; - -cvar_t *r_marksOnTriangleMeshes; - -cvar_t *r_aspectCorrectFonts; +cvar_t *r_lodbias; +cvar_t *r_lodscale; +cvar_t *r_autolodscalevalue; + +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawworld; +cvar_t *r_drawfog; +cvar_t *r_speeds; +cvar_t *r_fullbright; +cvar_t *r_novis; +cvar_t *r_nocull; +cvar_t *r_facePlaneCull; +cvar_t *r_cullRoofFaces; // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww +cvar_t *r_roofCullCeilDist; // ceiling distance cull tolerance -rww +cvar_t *r_roofCullFloorDist; // floor distance cull tolerance -rww +cvar_t *r_showcluster; +cvar_t *r_nocurves; + +cvar_t *r_autoMap; // automap renderside toggle for debugging -rww +cvar_t *r_autoMapBackAlpha; // alpha of automap bg -rww +cvar_t *r_autoMapDisable; // don't calc it (since it's slow in debug) -rww + +cvar_t *r_dlightStyle; +cvar_t *r_surfaceSprites; +cvar_t *r_surfaceWeather; + +cvar_t *r_windSpeed; +cvar_t *r_windAngle; +cvar_t *r_windGust; +cvar_t *r_windDampFactor; +cvar_t *r_windPointForce; +cvar_t *r_windPointX; +cvar_t *r_windPointY; + +cvar_t *r_allowExtensions; + +cvar_t *r_ext_compressed_textures; +cvar_t *r_ext_compressed_lightmaps; +cvar_t *r_ext_preferred_tc_method; +cvar_t *r_ext_gamma_control; +cvar_t *r_ext_multitexture; +cvar_t *r_ext_compiled_vertex_array; +cvar_t *r_ext_texture_env_add; +cvar_t *r_ext_texture_filter_anisotropic; +cvar_t *r_gammaShaders; + +cvar_t *r_environmentMapping; + +cvar_t *r_DynamicGlow; +cvar_t *r_DynamicGlowPasses; +cvar_t *r_DynamicGlowDelta; +cvar_t *r_DynamicGlowIntensity; +cvar_t *r_DynamicGlowSoft; +cvar_t *r_DynamicGlowWidth; +cvar_t *r_DynamicGlowHeight; + +cvar_t *r_ignoreGLErrors; +cvar_t *r_logFile; + +cvar_t *r_primitives; +cvar_t *r_texturebits; +cvar_t *r_texturebitslm; + +cvar_t *r_lightmap; +cvar_t *r_vertexLight; +cvar_t *r_uiFullScreen; +cvar_t *r_shadows; +cvar_t *r_shadowRange; +cvar_t *r_flares; +cvar_t *r_nobind; +cvar_t *r_singleShader; +cvar_t *r_colorMipLevels; +cvar_t *r_picmip; +cvar_t *r_showtris; +cvar_t *r_showsky; +cvar_t *r_shownormals; +cvar_t *r_finish; +cvar_t *r_clear; +cvar_t *r_markcount; +cvar_t *r_textureMode; +cvar_t *r_offsetFactor; +cvar_t *r_offsetUnits; +cvar_t *r_gamma; +cvar_t *r_intensity; +cvar_t *r_lockpvs; +cvar_t *r_noportals; +cvar_t *r_portalOnly; + +cvar_t *r_subdivisions; +cvar_t *r_lodCurveError; + +cvar_t *r_overBrightBits; +cvar_t *r_mapOverBrightBits; + +cvar_t *r_debugSurface; +cvar_t *r_simpleMipMaps; + +cvar_t *r_showImages; + +cvar_t *r_ambientScale; +cvar_t *r_directedScale; +cvar_t *r_debugLight; +cvar_t *r_debugSort; + +cvar_t *r_marksOnTriangleMeshes; + +cvar_t *r_aspectCorrectFonts; // the limits apply to the sum of all scenes in a frame -- // the main view, all the 3D icons, etc -#define DEFAULT_MAX_POLYS 600 -#define DEFAULT_MAX_POLYVERTS 3000 -cvar_t *r_maxpolys; -cvar_t *r_maxpolyverts; -int max_polys; -int max_polyverts; +#define DEFAULT_MAX_POLYS 600 +#define DEFAULT_MAX_POLYVERTS 3000 +cvar_t *r_maxpolys; +cvar_t *r_maxpolyverts; +int max_polys; +int max_polyverts; -cvar_t *r_modelpoolmegs; +cvar_t *r_modelpoolmegs; /* Ghoul2 Insert Start */ #ifdef _DEBUG -cvar_t *r_noPrecacheGLA; +cvar_t *r_noPrecacheGLA; #endif -cvar_t *r_noServerGhoul2; -cvar_t *r_Ghoul2AnimSmooth=0; -cvar_t *r_Ghoul2UnSqashAfterSmooth=0; -//cvar_t *r_Ghoul2UnSqash; -//cvar_t *r_Ghoul2TimeBase=0; from single player -//cvar_t *r_Ghoul2NoLerp; -//cvar_t *r_Ghoul2NoBlend; -//cvar_t *r_Ghoul2BlendMultiplier=0; - -cvar_t *broadsword=0; -cvar_t *broadsword_kickbones=0; -cvar_t *broadsword_kickorigin=0; -cvar_t *broadsword_playflop=0; -cvar_t *broadsword_dontstopanim=0; -cvar_t *broadsword_waitforshot=0; -cvar_t *broadsword_smallbbox=0; -cvar_t *broadsword_extra1=0; -cvar_t *broadsword_extra2=0; - -cvar_t *broadsword_effcorr=0; -cvar_t *broadsword_ragtobase=0; -cvar_t *broadsword_dircap=0; +cvar_t *r_noServerGhoul2; +cvar_t *r_Ghoul2AnimSmooth = 0; +cvar_t *r_Ghoul2UnSqashAfterSmooth = 0; +// cvar_t *r_Ghoul2UnSqash; +// cvar_t *r_Ghoul2TimeBase=0; from single player +// cvar_t *r_Ghoul2NoLerp; +// cvar_t *r_Ghoul2NoBlend; +// cvar_t *r_Ghoul2BlendMultiplier=0; + +cvar_t *broadsword = 0; +cvar_t *broadsword_kickbones = 0; +cvar_t *broadsword_kickorigin = 0; +cvar_t *broadsword_playflop = 0; +cvar_t *broadsword_dontstopanim = 0; +cvar_t *broadsword_waitforshot = 0; +cvar_t *broadsword_smallbbox = 0; +cvar_t *broadsword_extra1 = 0; +cvar_t *broadsword_extra2 = 0; + +cvar_t *broadsword_effcorr = 0; +cvar_t *broadsword_ragtobase = 0; +cvar_t *broadsword_dircap = 0; /* Ghoul2 Insert End @@ -216,7 +214,7 @@ cvar_t *se_language; cvar_t *r_aviMotionJpegQuality; cvar_t *r_screenshotJpegQuality; -cvar_t *r_patchStitching; +cvar_t *r_patchStitching; #if !defined(__APPLE__) PFNGLSTENCILOPSEPARATEPROC qglStencilOpSeparate; @@ -271,27 +269,25 @@ PFNGLUNLOCKARRAYSEXTPROC qglUnlockArraysEXT; bool g_bTextureRectangleHack = false; void RE_SetLightStyle(int style, int color); -void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ); +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal); -void R_Splash() -{ +void R_Splash() { image_t *pImage; -/* const char* s = ri.Cvar_VariableString("se_language"); - if (Q_stricmp(s,"english")) - { - pImage = R_FindImageFile( "menu/splash_eur", qfalse, qfalse, qfalse, GL_CLAMP); - } - else - { - pImage = R_FindImageFile( "menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); - } -*/ - pImage = R_FindImageFile( "menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); - extern void RB_SetGL2D (void); + /* const char* s = ri.Cvar_VariableString("se_language"); + if (Q_stricmp(s,"english")) + { + pImage = R_FindImageFile( "menu/splash_eur", qfalse, qfalse, qfalse, GL_CLAMP); + } + else + { + pImage = R_FindImageFile( "menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); + } + */ + pImage = R_FindImageFile("menu/splash", qfalse, qfalse, qfalse, GL_CLAMP); + extern void RB_SetGL2D(void); RB_SetGL2D(); - if (pImage ) - {//invalid paths? - GL_Bind( pImage ); + if (pImage) { // invalid paths? + GL_Bind(pImage); } GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); @@ -302,16 +298,15 @@ void R_Splash() const float y1 = 240 - height / 2; const float y2 = 240 + height / 2; - - qglBegin (GL_TRIANGLE_STRIP); - qglTexCoord2f( 0, 0 ); - qglVertex2f(x1, y1); - qglTexCoord2f( 1 , 0 ); - qglVertex2f(x2, y1); - qglTexCoord2f( 0, 1 ); - qglVertex2f(x1, y2); - qglTexCoord2f( 1, 1 ); - qglVertex2f(x2, y2); + qglBegin(GL_TRIANGLE_STRIP); + qglTexCoord2f(0, 0); + qglVertex2f(x1, y1); + qglTexCoord2f(1, 0); + qglVertex2f(x2, y1); + qglTexCoord2f(0, 1); + qglVertex2f(x1, y2); + qglTexCoord2f(1, 1); + qglVertex2f(x2, y2); qglEnd(); ri.WIN_Present(&window); @@ -323,105 +318,76 @@ void R_Splash() Cannot use strstr directly to differentiate between (for eg) reg_combiners and reg_combiners2 */ -static void GLW_InitTextureCompression( void ) -{ +static void GLW_InitTextureCompression(void) { bool newer_tc, old_tc; // Check for available tc methods. newer_tc = ri.GL_ExtensionSupported("GL_ARB_texture_compression") && ri.GL_ExtensionSupported("GL_EXT_texture_compression_s3tc"); old_tc = ri.GL_ExtensionSupported("GL_S3_s3tc"); - if ( old_tc ) - { - Com_Printf ("...GL_S3_s3tc available\n" ); + if (old_tc) { + Com_Printf("...GL_S3_s3tc available\n"); } - if ( newer_tc ) - { - Com_Printf ("...GL_EXT_texture_compression_s3tc available\n" ); + if (newer_tc) { + Com_Printf("...GL_EXT_texture_compression_s3tc available\n"); } - if ( !r_ext_compressed_textures->value ) - { + if (!r_ext_compressed_textures->value) { // Compressed textures are off glConfig.textureCompression = TC_NONE; - Com_Printf ("...ignoring texture compression\n" ); - } - else if ( !old_tc && !newer_tc ) - { + Com_Printf("...ignoring texture compression\n"); + } else if (!old_tc && !newer_tc) { // Requesting texture compression, but no method found glConfig.textureCompression = TC_NONE; - Com_Printf ("...no supported texture compression method found\n" ); - Com_Printf (".....ignoring texture compression\n" ); - } - else - { + Com_Printf("...no supported texture compression method found\n"); + Com_Printf(".....ignoring texture compression\n"); + } else { // some form of supported texture compression is avaiable, so see if the user has a preference - if ( r_ext_preferred_tc_method->integer == TC_NONE ) - { + if (r_ext_preferred_tc_method->integer == TC_NONE) { // No preference, so pick the best - if ( newer_tc ) - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { - Com_Printf ("...no tc preference specified\n" ); - Com_Printf (".....using GL_S3_s3tc\n" ); + } else { + Com_Printf("...no tc preference specified\n"); + Com_Printf(".....using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } - } - else - { + } else { // User has specified a preference, now see if this request can be honored - if ( old_tc && newer_tc ) - { + if (old_tc && newer_tc) { // both are avaiable, so we can use the desired tc method - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { - Com_Printf ("...using preferred tc method, GL_S3_s3tc\n" ); + if (r_ext_preferred_tc_method->integer == TC_S3TC) { + Com_Printf("...using preferred tc method, GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { - Com_Printf ("...using preferred tc method, GL_EXT_texture_compression_s3tc\n" ); + } else { + Com_Printf("...using preferred tc method, GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Both methods are not available, so this gets trickier - if ( r_ext_preferred_tc_method->integer == TC_S3TC ) - { + if (r_ext_preferred_tc_method->integer == TC_S3TC) { // Preferring to user older compression - if ( old_tc ) - { - Com_Printf ("...using GL_S3_s3tc\n" ); + if (old_tc) { + Com_Printf("...using GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_S3_s3tc not available\n" ); - Com_Printf (".....falling back to GL_EXT_texture_compression_s3tc\n" ); + Com_Printf("...preferred tc method, GL_S3_s3tc not available\n"); + Com_Printf(".....falling back to GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; } - } - else - { + } else { // Preferring to user newer compression - if ( newer_tc ) - { - Com_Printf ("...using GL_EXT_texture_compression_s3tc\n" ); + if (newer_tc) { + Com_Printf("...using GL_EXT_texture_compression_s3tc\n"); glConfig.textureCompression = TC_S3TC_DXT; - } - else - { + } else { // Drat, preference can't be honored - Com_Printf ("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n" ); - Com_Printf (".....falling back to GL_S3_s3tc\n" ); + Com_Printf("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n"); + Com_Printf(".....falling back to GL_S3_s3tc\n"); glConfig.textureCompression = TC_S3TC; } } @@ -437,182 +403,145 @@ GLimp_InitExtensions */ extern bool g_bDynamicGlowSupported; extern bool g_bARBShadersAvailable; -static void GLimp_InitExtensions( void ) -{ - if ( !r_allowExtensions->integer ) - { - Com_Printf ("*** IGNORING OPENGL EXTENSIONS ***\n" ); +static void GLimp_InitExtensions(void) { + if (!r_allowExtensions->integer) { + Com_Printf("*** IGNORING OPENGL EXTENSIONS ***\n"); g_bDynamicGlowSupported = false; - ri.Cvar_Set( "r_DynamicGlow","0" ); + ri.Cvar_Set("r_DynamicGlow", "0"); return; } - Com_Printf ("Initializing OpenGL extensions\n" ); + Com_Printf("Initializing OpenGL extensions\n"); // Select our tc scheme GLW_InitTextureCompression(); // GL_EXT_texture_env_add glConfig.textureEnvAddAvailable = qfalse; - if ( ri.GL_ExtensionSupported( "GL_EXT_texture_env_add" ) ) - { - if ( r_ext_texture_env_add->integer ) - { + if (ri.GL_ExtensionSupported("GL_EXT_texture_env_add")) { + if (r_ext_texture_env_add->integer) { glConfig.textureEnvAddAvailable = qtrue; - Com_Printf ("...using GL_EXT_texture_env_add\n" ); - } - else - { + Com_Printf("...using GL_EXT_texture_env_add\n"); + } else { glConfig.textureEnvAddAvailable = qfalse; - Com_Printf ("...ignoring GL_EXT_texture_env_add\n" ); + Com_Printf("...ignoring GL_EXT_texture_env_add\n"); } - } - else - { - Com_Printf ("...GL_EXT_texture_env_add not found\n" ); + } else { + Com_Printf("...GL_EXT_texture_env_add not found\n"); } // GL_EXT_texture_filter_anisotropic glConfig.maxTextureFilterAnisotropy = 0; - if ( ri.GL_ExtensionSupported( "GL_EXT_texture_filter_anisotropic" ) ) - { - qglGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy ); - Com_Printf ("...GL_EXT_texture_filter_anisotropic available\n" ); - - if ( r_ext_texture_filter_anisotropic->integer > 1 ) - { - Com_Printf ("...using GL_EXT_texture_filter_anisotropic\n" ); - } - else - { - Com_Printf ("...ignoring GL_EXT_texture_filter_anisotropic\n" ); + if (ri.GL_ExtensionSupported("GL_EXT_texture_filter_anisotropic")) { + qglGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy); + Com_Printf("...GL_EXT_texture_filter_anisotropic available\n"); + + if (r_ext_texture_filter_anisotropic->integer > 1) { + Com_Printf("...using GL_EXT_texture_filter_anisotropic\n"); + } else { + Com_Printf("...ignoring GL_EXT_texture_filter_anisotropic\n"); } - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); - if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) - { - ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); + if (r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy) { + ri.Cvar_SetValue("r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy); } - } - else - { - Com_Printf ("...GL_EXT_texture_filter_anisotropic not found\n" ); - ri.Cvar_Set( "r_ext_texture_filter_anisotropic_avail", "0" ); + } else { + Com_Printf("...GL_EXT_texture_filter_anisotropic not found\n"); + ri.Cvar_Set("r_ext_texture_filter_anisotropic_avail", "0"); } // GL_EXT_clamp_to_edge glConfig.clampToEdgeAvailable = qtrue; - Com_Printf ("...using GL_EXT_texture_edge_clamp\n" ); + Com_Printf("...using GL_EXT_texture_edge_clamp\n"); // GL_ARB_multitexture qglMultiTexCoord2fARB = NULL; qglActiveTextureARB = NULL; qglClientActiveTextureARB = NULL; - if ( ri.GL_ExtensionSupported( "GL_ARB_multitexture" ) ) - { - if ( r_ext_multitexture->integer ) - { - qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) ri.GL_GetProcAddress( "glMultiTexCoord2fARB" ); - qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) ri.GL_GetProcAddress( "glActiveTextureARB" ); - qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) ri.GL_GetProcAddress( "glClientActiveTextureARB" ); - - if ( qglActiveTextureARB ) - { - qglGetIntegerv( GL_MAX_TEXTURE_UNITS_ARB, &glConfig.maxActiveTextures ); - - if ( glConfig.maxActiveTextures > 1 ) - { - Com_Printf ("...using GL_ARB_multitexture\n" ); - } - else - { + if (ri.GL_ExtensionSupported("GL_ARB_multitexture")) { + if (r_ext_multitexture->integer) { + qglMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC)ri.GL_GetProcAddress("glMultiTexCoord2fARB"); + qglActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)ri.GL_GetProcAddress("glActiveTextureARB"); + qglClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)ri.GL_GetProcAddress("glClientActiveTextureARB"); + + if (qglActiveTextureARB) { + qglGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &glConfig.maxActiveTextures); + + if (glConfig.maxActiveTextures > 1) { + Com_Printf("...using GL_ARB_multitexture\n"); + } else { qglMultiTexCoord2fARB = NULL; qglActiveTextureARB = NULL; qglClientActiveTextureARB = NULL; - Com_Printf ("...not using GL_ARB_multitexture, < 2 texture units\n" ); + Com_Printf("...not using GL_ARB_multitexture, < 2 texture units\n"); } } + } else { + Com_Printf("...ignoring GL_ARB_multitexture\n"); } - else - { - Com_Printf ("...ignoring GL_ARB_multitexture\n" ); - } - } - else - { - Com_Printf ("...GL_ARB_multitexture not found\n" ); + } else { + Com_Printf("...GL_ARB_multitexture not found\n"); } // GL_EXT_compiled_vertex_array qglLockArraysEXT = NULL; qglUnlockArraysEXT = NULL; - if ( ri.GL_ExtensionSupported( "GL_EXT_compiled_vertex_array" ) ) - { - if ( r_ext_compiled_vertex_array->integer ) - { - Com_Printf ("...using GL_EXT_compiled_vertex_array\n" ); - qglLockArraysEXT = ( PFNGLLOCKARRAYSEXTPROC ) ri.GL_GetProcAddress( "glLockArraysEXT" ); - qglUnlockArraysEXT = ( PFNGLUNLOCKARRAYSEXTPROC ) ri.GL_GetProcAddress( "glUnlockArraysEXT" ); + if (ri.GL_ExtensionSupported("GL_EXT_compiled_vertex_array")) { + if (r_ext_compiled_vertex_array->integer) { + Com_Printf("...using GL_EXT_compiled_vertex_array\n"); + qglLockArraysEXT = (PFNGLLOCKARRAYSEXTPROC)ri.GL_GetProcAddress("glLockArraysEXT"); + qglUnlockArraysEXT = (PFNGLUNLOCKARRAYSEXTPROC)ri.GL_GetProcAddress("glUnlockArraysEXT"); if (!qglLockArraysEXT || !qglUnlockArraysEXT) { - Com_Error (ERR_FATAL, "bad getprocaddress"); + Com_Error(ERR_FATAL, "bad getprocaddress"); } + } else { + Com_Printf("...ignoring GL_EXT_compiled_vertex_array\n"); } - else - { - Com_Printf ("...ignoring GL_EXT_compiled_vertex_array\n" ); - } - } - else - { - Com_Printf ("...GL_EXT_compiled_vertex_array not found\n" ); + } else { + Com_Printf("...GL_EXT_compiled_vertex_array not found\n"); } bool bNVRegisterCombiners = false; // Register Combiners. - if ( ri.GL_ExtensionSupported( "GL_NV_register_combiners" ) ) - { + if (ri.GL_ExtensionSupported("GL_NV_register_combiners")) { // NOTE: This extension requires multitexture support (over 2 units). - if ( glConfig.maxActiveTextures >= 2 ) - { + if (glConfig.maxActiveTextures >= 2) { bNVRegisterCombiners = true; // Register Combiners function pointer address load. - AReis // NOTE: VV guys will _definetly_ not be able to use regcoms. Pixel Shaders are just as good though :-) // NOTE: Also, this is an nVidia specific extension (of course), so fragment shaders would serve the same purpose // if we needed some kind of fragment/pixel manipulation support. - qglCombinerParameterfvNV = (PFNGLCOMBINERPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glCombinerParameterfvNV" ); - qglCombinerParameterivNV = (PFNGLCOMBINERPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glCombinerParameterivNV" ); - qglCombinerParameterfNV = (PFNGLCOMBINERPARAMETERFNVPROC)ri.GL_GetProcAddress( "glCombinerParameterfNV" ); - qglCombinerParameteriNV = (PFNGLCOMBINERPARAMETERINVPROC)ri.GL_GetProcAddress( "glCombinerParameteriNV" ); - qglCombinerInputNV = (PFNGLCOMBINERINPUTNVPROC)ri.GL_GetProcAddress( "glCombinerInputNV" ); - qglCombinerOutputNV = (PFNGLCOMBINEROUTPUTNVPROC)ri.GL_GetProcAddress( "glCombinerOutputNV" ); - qglFinalCombinerInputNV = (PFNGLFINALCOMBINERINPUTNVPROC)ri.GL_GetProcAddress( "glFinalCombinerInputNV" ); - qglGetCombinerInputParameterfvNV = (PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetCombinerInputParameterfvNV" ); - qglGetCombinerInputParameterivNV = (PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetCombinerInputParameterivNV" ); - qglGetCombinerOutputParameterfvNV = (PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetCombinerOutputParameterfvNV" ); - qglGetCombinerOutputParameterivNV = (PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetCombinerOutputParameterivNV" ); - qglGetFinalCombinerInputParameterfvNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress( "glGetFinalCombinerInputParameterfvNV" ); - qglGetFinalCombinerInputParameterivNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress( "glGetFinalCombinerInputParameterivNV" ); + qglCombinerParameterfvNV = (PFNGLCOMBINERPARAMETERFVNVPROC)ri.GL_GetProcAddress("glCombinerParameterfvNV"); + qglCombinerParameterivNV = (PFNGLCOMBINERPARAMETERIVNVPROC)ri.GL_GetProcAddress("glCombinerParameterivNV"); + qglCombinerParameterfNV = (PFNGLCOMBINERPARAMETERFNVPROC)ri.GL_GetProcAddress("glCombinerParameterfNV"); + qglCombinerParameteriNV = (PFNGLCOMBINERPARAMETERINVPROC)ri.GL_GetProcAddress("glCombinerParameteriNV"); + qglCombinerInputNV = (PFNGLCOMBINERINPUTNVPROC)ri.GL_GetProcAddress("glCombinerInputNV"); + qglCombinerOutputNV = (PFNGLCOMBINEROUTPUTNVPROC)ri.GL_GetProcAddress("glCombinerOutputNV"); + qglFinalCombinerInputNV = (PFNGLFINALCOMBINERINPUTNVPROC)ri.GL_GetProcAddress("glFinalCombinerInputNV"); + qglGetCombinerInputParameterfvNV = (PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetCombinerInputParameterfvNV"); + qglGetCombinerInputParameterivNV = (PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetCombinerInputParameterivNV"); + qglGetCombinerOutputParameterfvNV = (PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetCombinerOutputParameterfvNV"); + qglGetCombinerOutputParameterivNV = (PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetCombinerOutputParameterivNV"); + qglGetFinalCombinerInputParameterfvNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)ri.GL_GetProcAddress("glGetFinalCombinerInputParameterfvNV"); + qglGetFinalCombinerInputParameterivNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)ri.GL_GetProcAddress("glGetFinalCombinerInputParameterivNV"); // Validate the functions we need. - if ( !qglCombinerParameterfvNV || !qglCombinerParameterivNV || !qglCombinerParameterfNV || !qglCombinerParameteriNV || !qglCombinerInputNV || - !qglCombinerOutputNV || !qglFinalCombinerInputNV || !qglGetCombinerInputParameterfvNV || !qglGetCombinerInputParameterivNV || - !qglGetCombinerOutputParameterfvNV || !qglGetCombinerOutputParameterivNV || !qglGetFinalCombinerInputParameterfvNV || !qglGetFinalCombinerInputParameterivNV ) - { + if (!qglCombinerParameterfvNV || !qglCombinerParameterivNV || !qglCombinerParameterfNV || !qglCombinerParameteriNV || !qglCombinerInputNV || + !qglCombinerOutputNV || !qglFinalCombinerInputNV || !qglGetCombinerInputParameterfvNV || !qglGetCombinerInputParameterivNV || + !qglGetCombinerOutputParameterfvNV || !qglGetCombinerOutputParameterivNV || !qglGetFinalCombinerInputParameterfvNV || + !qglGetFinalCombinerInputParameterivNV) { bNVRegisterCombiners = false; qglCombinerParameterfvNV = NULL; qglCombinerParameteriNV = NULL; - Com_Printf ("...GL_NV_register_combiners failed\n" ); + Com_Printf("...GL_NV_register_combiners failed\n"); } - } - else - { + } else { bNVRegisterCombiners = false; - Com_Printf ("...ignoring GL_NV_register_combiners\n" ); + Com_Printf("...ignoring GL_NV_register_combiners\n"); } - } - else - { + } else { bNVRegisterCombiners = false; - Com_Printf ("...GL_NV_register_combiners not found\n" ); + Com_Printf("...GL_NV_register_combiners not found\n"); } // NOTE: Vertex and Fragment Programs are very dependant on each other - this is actually a @@ -621,96 +550,83 @@ static void GLimp_InitExtensions( void ) // Vertex Programs. bool bARBVertexProgram = false; - if ( ri.GL_ExtensionSupported( "GL_ARB_vertex_program" ) ) - { + if (ri.GL_ExtensionSupported("GL_ARB_vertex_program")) { bARBVertexProgram = true; - } - else - { + } else { bARBVertexProgram = false; - Com_Printf ("...GL_ARB_vertex_program not found\n" ); + Com_Printf("...GL_ARB_vertex_program not found\n"); } // Fragment Programs. bool bARBFragmentProgram = false; - if ( ri.GL_ExtensionSupported( "GL_ARB_fragment_program" ) ) - { + if (ri.GL_ExtensionSupported("GL_ARB_fragment_program")) { bARBFragmentProgram = true; - } - else - { + } else { bARBFragmentProgram = false; - Com_Printf ("...GL_ARB_fragment_program not found\n" ); + Com_Printf("...GL_ARB_fragment_program not found\n"); } // If we support one or the other, load the shared function pointers. - if ( bARBVertexProgram || bARBFragmentProgram ) - { - qglProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC) ri.GL_GetProcAddress("glProgramStringARB"); - qglBindProgramARB = (PFNGLBINDPROGRAMARBPROC) ri.GL_GetProcAddress("glBindProgramARB"); - qglDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC) ri.GL_GetProcAddress("glDeleteProgramsARB"); - qglGenProgramsARB = (PFNGLGENPROGRAMSARBPROC) ri.GL_GetProcAddress("glGenProgramsARB"); - qglProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4dARB"); - qglProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4dvARB"); - qglProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4fARB"); - qglProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC) ri.GL_GetProcAddress("glProgramEnvParameter4fvARB"); - qglProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4dARB"); - qglProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4dvARB"); - qglProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4fARB"); - qglProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) ri.GL_GetProcAddress("glProgramLocalParameter4fvARB"); - qglGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC) ri.GL_GetProcAddress("glGetProgramEnvParameterdvARB"); - qglGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC) ri.GL_GetProcAddress("glGetProgramEnvParameterfvARB"); - qglGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) ri.GL_GetProcAddress("glGetProgramLocalParameterdvARB"); - qglGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) ri.GL_GetProcAddress("glGetProgramLocalParameterfvARB"); - qglGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC) ri.GL_GetProcAddress("glGetProgramivARB"); - qglGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC) ri.GL_GetProcAddress("glGetProgramStringARB"); - qglIsProgramARB = (PFNGLISPROGRAMARBPROC) ri.GL_GetProcAddress("glIsProgramARB"); + if (bARBVertexProgram || bARBFragmentProgram) { + qglProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)ri.GL_GetProcAddress("glProgramStringARB"); + qglBindProgramARB = (PFNGLBINDPROGRAMARBPROC)ri.GL_GetProcAddress("glBindProgramARB"); + qglDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)ri.GL_GetProcAddress("glDeleteProgramsARB"); + qglGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)ri.GL_GetProcAddress("glGenProgramsARB"); + qglProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4dARB"); + qglProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4dvARB"); + qglProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4fARB"); + qglProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC)ri.GL_GetProcAddress("glProgramEnvParameter4fvARB"); + qglProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4dARB"); + qglProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4dvARB"); + qglProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4fARB"); + qglProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)ri.GL_GetProcAddress("glProgramLocalParameter4fvARB"); + qglGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC)ri.GL_GetProcAddress("glGetProgramEnvParameterdvARB"); + qglGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC)ri.GL_GetProcAddress("glGetProgramEnvParameterfvARB"); + qglGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC)ri.GL_GetProcAddress("glGetProgramLocalParameterdvARB"); + qglGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC)ri.GL_GetProcAddress("glGetProgramLocalParameterfvARB"); + qglGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC)ri.GL_GetProcAddress("glGetProgramivARB"); + qglGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC)ri.GL_GetProcAddress("glGetProgramStringARB"); + qglIsProgramARB = (PFNGLISPROGRAMARBPROC)ri.GL_GetProcAddress("glIsProgramARB"); // Validate the functions we need. - if ( !qglProgramStringARB || !qglBindProgramARB || !qglDeleteProgramsARB || !qglGenProgramsARB || - !qglProgramEnvParameter4dARB || !qglProgramEnvParameter4dvARB || !qglProgramEnvParameter4fARB || - !qglProgramEnvParameter4fvARB || !qglProgramLocalParameter4dARB || !qglProgramLocalParameter4dvARB || - !qglProgramLocalParameter4fARB || !qglProgramLocalParameter4fvARB || !qglGetProgramEnvParameterdvARB || - !qglGetProgramEnvParameterfvARB || !qglGetProgramLocalParameterdvARB || !qglGetProgramLocalParameterfvARB || - !qglGetProgramivARB || !qglGetProgramStringARB || !qglIsProgramARB ) - { + if (!qglProgramStringARB || !qglBindProgramARB || !qglDeleteProgramsARB || !qglGenProgramsARB || !qglProgramEnvParameter4dARB || + !qglProgramEnvParameter4dvARB || !qglProgramEnvParameter4fARB || !qglProgramEnvParameter4fvARB || !qglProgramLocalParameter4dARB || + !qglProgramLocalParameter4dvARB || !qglProgramLocalParameter4fARB || !qglProgramLocalParameter4fvARB || !qglGetProgramEnvParameterdvARB || + !qglGetProgramEnvParameterfvARB || !qglGetProgramLocalParameterdvARB || !qglGetProgramLocalParameterfvARB || !qglGetProgramivARB || + !qglGetProgramStringARB || !qglIsProgramARB) { bARBVertexProgram = false; bARBFragmentProgram = false; - qglGenProgramsARB = NULL; //clear ptrs that get checked + qglGenProgramsARB = NULL; // clear ptrs that get checked qglProgramEnvParameter4fARB = NULL; - Com_Printf ("...ignoring GL_ARB_vertex_program\n" ); - Com_Printf ("...ignoring GL_ARB_fragment_program\n" ); + Com_Printf("...ignoring GL_ARB_vertex_program\n"); + Com_Printf("...ignoring GL_ARB_fragment_program\n"); } } // Figure out which texture rectangle extension to use. bool bTexRectSupported = false; - if ( Q_stricmpn( glConfig.vendor_string, "ATI Technologies",16 )==0 - && Q_stricmpn( glConfig.version_string, "1.3.3",5 )==0 - && glConfig.version_string[5] < '9' ) //1.3.34 and 1.3.37 and 1.3.38 are broken for sure, 1.3.39 is not + if (Q_stricmpn(glConfig.vendor_string, "ATI Technologies", 16) == 0 && Q_stricmpn(glConfig.version_string, "1.3.3", 5) == 0 && + glConfig.version_string[5] < '9') // 1.3.34 and 1.3.37 and 1.3.38 are broken for sure, 1.3.39 is not { g_bTextureRectangleHack = true; } - if ( ri.GL_ExtensionSupported( "GL_NV_texture_rectangle" ) || ri.GL_ExtensionSupported( "GL_EXT_texture_rectangle" ) ) - { + if (ri.GL_ExtensionSupported("GL_NV_texture_rectangle") || ri.GL_ExtensionSupported("GL_EXT_texture_rectangle")) { bTexRectSupported = true; } - // Find out how many general combiners they have. - #define GL_MAX_GENERAL_COMBINERS_NV 0x854D +// Find out how many general combiners they have. +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D GLint iNumGeneralCombiners = 0; - if(bNVRegisterCombiners) - qglGetIntegerv( GL_MAX_GENERAL_COMBINERS_NV, &iNumGeneralCombiners ); + if (bNVRegisterCombiners) + qglGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &iNumGeneralCombiners); glConfigExt.doGammaCorrectionWithShaders = qfalse; - if ( r_gammaShaders->integer && qglActiveTextureARB && bTexRectSupported && bARBVertexProgram && bARBFragmentProgram ) - { + if (r_gammaShaders->integer && qglActiveTextureARB && bTexRectSupported && bARBVertexProgram && bARBFragmentProgram) { #if !defined(__APPLE__) qglTexImage3D = (PFNGLTEXIMAGE3DPROC)ri.GL_GetProcAddress("glTexImage3D"); qglTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)ri.GL_GetProcAddress("glTexSubImage3D"); - if ( qglTexImage3D && qglTexSubImage3D ) - { + if (qglTexImage3D && qglTexSubImage3D) { glConfigExt.doGammaCorrectionWithShaders = qtrue; } #else @@ -719,23 +635,19 @@ static void GLimp_InitExtensions( void ) } // Only allow dynamic glows/flares if they have the hardware - if ( bTexRectSupported && bARBVertexProgram && qglActiveTextureARB && glConfig.maxActiveTextures >= 4 && - ( ( bNVRegisterCombiners && iNumGeneralCombiners >= 2 ) || bARBFragmentProgram ) ) - { + if (bTexRectSupported && bARBVertexProgram && qglActiveTextureARB && glConfig.maxActiveTextures >= 4 && + ((bNVRegisterCombiners && iNumGeneralCombiners >= 2) || bARBFragmentProgram)) { g_bDynamicGlowSupported = true; // this would overwrite any achived setting gwg // ri.Cvar_Set( "r_DynamicGlow", "1" ); - } - else - { + } else { g_bDynamicGlowSupported = false; - ri.Cvar_Set( "r_DynamicGlow","0" ); + ri.Cvar_Set("r_DynamicGlow", "0"); } #if !defined(__APPLE__) qglStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)ri.GL_GetProcAddress("glStencilOpSeparate"); - if ( qglStencilOpSeparate ) - { + if (qglStencilOpSeparate) { glConfigExt.doStencilShadowsInOneDrawcall = qtrue; } #else @@ -744,30 +656,27 @@ static void GLimp_InitExtensions( void ) } // Truncates the GL extensions string by only allowing up to 'maxExtensions' extensions in the string. -static const char *TruncateGLExtensionsString (const char *extensionsString, int maxExtensions) -{ +static const char *TruncateGLExtensionsString(const char *extensionsString, int maxExtensions) { const char *p = extensionsString; const char *q; int numExtensions = 0; - size_t extensionsLen = strlen (extensionsString); + size_t extensionsLen = strlen(extensionsString); char *truncatedExtensions; - while ( (q = strchr (p, ' ')) != NULL && numExtensions < maxExtensions ) - { + while ((q = strchr(p, ' ')) != NULL && numExtensions < maxExtensions) { p = q + 1; numExtensions++; } - if ( q != NULL ) - { + if (q != NULL) { // We still have more extensions. We'll call this the end extensionsLen = p - extensionsString - 1; } truncatedExtensions = (char *)Hunk_Alloc(extensionsLen + 1, h_low); - Q_strncpyz (truncatedExtensions, extensionsString, extensionsLen + 1); + Q_strncpyz(truncatedExtensions, extensionsString, extensionsLen + 1); return truncatedExtensions; } @@ -780,8 +689,7 @@ static const char *TruncateGLExtensionsString (const char *extensionsString, int ** setting variables, checking GL constants, and reporting the gfx system config ** to the user. */ -static void InitOpenGL( void ) -{ +static void InitOpenGL(void) { // // initialize OS specific portions of the renderer // @@ -793,40 +701,37 @@ static void InitOpenGL( void ) // - r_gamma // - if ( glConfig.vidWidth == 0 ) - { - windowDesc_t windowDesc = { GRAPHICS_API_OPENGL }; + if (glConfig.vidWidth == 0) { + windowDesc_t windowDesc = {GRAPHICS_API_OPENGL}; memset(&glConfig, 0, sizeof(glConfig)); memset(&glConfigExt, 0, sizeof(glConfigExt)); window = ri.WIN_Init(&windowDesc, &glConfig); - Com_Printf( "GL_RENDERER: %s\n", (char *)qglGetString (GL_RENDERER) ); + Com_Printf("GL_RENDERER: %s\n", (char *)qglGetString(GL_RENDERER)); // get our config strings - glConfig.vendor_string = (const char *)qglGetString (GL_VENDOR); - glConfig.renderer_string = (const char *)qglGetString (GL_RENDERER); - glConfig.version_string = (const char *)qglGetString (GL_VERSION); - glConfig.extensions_string = (const char *)qglGetString (GL_EXTENSIONS); + glConfig.vendor_string = (const char *)qglGetString(GL_VENDOR); + glConfig.renderer_string = (const char *)qglGetString(GL_RENDERER); + glConfig.version_string = (const char *)qglGetString(GL_VERSION); + glConfig.extensions_string = (const char *)qglGetString(GL_EXTENSIONS); glConfigExt.originalExtensionString = glConfig.extensions_string; glConfig.extensions_string = TruncateGLExtensionsString(glConfigExt.originalExtensionString, 128); // OpenGL driver constants - qglGetIntegerv( GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize ); + qglGetIntegerv(GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize); // stubbed or broken drivers may have reported 0... glConfig.maxTextureSize = Q_max(0, glConfig.maxTextureSize); // initialize extensions - GLimp_InitExtensions( ); + GLimp_InitExtensions(); // set default state GL_SetDefaultState(); - R_Splash(); //get something on screen asap - } - else - { + R_Splash(); // get something on screen asap + } else { // set default state GL_SetDefaultState(); } @@ -837,43 +742,43 @@ static void InitOpenGL( void ) GL_CheckErrors ================== */ -void GL_CheckErrors( void ) { +void GL_CheckErrors(void) { #if defined(_DEBUG) - GLenum err; - char s[64]; - - err = qglGetError(); - if ( err == GL_NO_ERROR ) { - return; - } - if ( r_ignoreGLErrors->integer ) { - return; - } - switch( err ) { - case GL_INVALID_ENUM: - strcpy( s, "GL_INVALID_ENUM" ); - break; - case GL_INVALID_VALUE: - strcpy( s, "GL_INVALID_VALUE" ); - break; - case GL_INVALID_OPERATION: - strcpy( s, "GL_INVALID_OPERATION" ); - break; - case GL_STACK_OVERFLOW: - strcpy( s, "GL_STACK_OVERFLOW" ); - break; - case GL_STACK_UNDERFLOW: - strcpy( s, "GL_STACK_UNDERFLOW" ); - break; - case GL_OUT_OF_MEMORY: - strcpy( s, "GL_OUT_OF_MEMORY" ); - break; - default: - Com_sprintf( s, sizeof(s), "%i", err); - break; - } - - Com_Error( ERR_FATAL, "GL_CheckErrors: %s", s ); + GLenum err; + char s[64]; + + err = qglGetError(); + if (err == GL_NO_ERROR) { + return; + } + if (r_ignoreGLErrors->integer) { + return; + } + switch (err) { + case GL_INVALID_ENUM: + strcpy(s, "GL_INVALID_ENUM"); + break; + case GL_INVALID_VALUE: + strcpy(s, "GL_INVALID_VALUE"); + break; + case GL_INVALID_OPERATION: + strcpy(s, "GL_INVALID_OPERATION"); + break; + case GL_STACK_OVERFLOW: + strcpy(s, "GL_STACK_OVERFLOW"); + break; + case GL_STACK_UNDERFLOW: + strcpy(s, "GL_STACK_UNDERFLOW"); + break; + case GL_OUT_OF_MEMORY: + strcpy(s, "GL_OUT_OF_MEMORY"); + break; + default: + Com_sprintf(s, sizeof(s), "%i", err); + break; + } + + Com_Error(ERR_FATAL, "GL_CheckErrors: %s", s); #endif } @@ -902,8 +807,7 @@ Return value must be freed with Hunk_FreeTempMemory() ================== */ -byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen) -{ +byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *padlen) { byte *buffer, *bufstart; int padwidth, linelen; GLint packAlign; @@ -916,7 +820,7 @@ byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *pa // Allocate a few more bytes so that we can choose an alignment we like buffer = (byte *)Hunk_AllocateTempMemory(padwidth * height + *offset + packAlign - 1); - bufstart = (byte *)PADP((intptr_t) buffer + *offset, packAlign); + bufstart = (byte *)PADP((intptr_t)buffer + *offset, packAlign); qglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, bufstart); *offset = bufstart - buffer; @@ -930,7 +834,7 @@ byte *RB_ReadPixels(int x, int y, int width, int height, size_t *offset, int *pa R_TakeScreenshot ================== */ -void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { +void R_TakeScreenshot(int x, int y, int width, int height, char *fileName) { byte *allbuf, *buffer; byte *srcptr, *destptr; byte *endline, *endmem; @@ -942,13 +846,13 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { allbuf = RB_ReadPixels(x, y, width, height, &offset, &padlen); buffer = allbuf + offset - 18; - Com_Memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type + Com_Memset(buffer, 0, 18); + buffer[2] = 2; // uncompressed type buffer[12] = width & 255; buffer[13] = width >> 8; buffer[14] = height & 255; buffer[15] = height >> 8; - buffer[16] = 24; // pixel size + buffer[16] = 24; // pixel size // swap rgb to bgr and remove padding from line endings linelen = width * 3; @@ -956,12 +860,10 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { srcptr = destptr = allbuf + offset; endmem = srcptr + (linelen + padlen) * height; - while(srcptr < endmem) - { + while (srcptr < endmem) { endline = srcptr + linelen; - while(srcptr < endline) - { + while (srcptr < endline) { temp = srcptr[0]; *destptr++ = srcptr[2]; *destptr++ = srcptr[1]; @@ -977,7 +879,7 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { memcount = linelen * height; // gamma correct - if(glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) + if (glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) R_GammaCorrect(allbuf + offset, memcount); ri.FS_WriteFile(fileName, buffer, memcount + 18); @@ -990,14 +892,14 @@ void R_TakeScreenshot( int x, int y, int width, int height, char *fileName ) { R_TakeScreenshotPNG ================== */ -void R_TakeScreenshotPNG( int x, int y, int width, int height, char *fileName ) { - byte *buffer=NULL; - size_t offset=0; - int padlen=0; - - buffer = RB_ReadPixels( x, y, width, height, &offset, &padlen ); - RE_SavePNG( fileName, buffer, width, height, 3 ); - ri.Hunk_FreeTempMemory( buffer ); +void R_TakeScreenshotPNG(int x, int y, int width, int height, char *fileName) { + byte *buffer = NULL; + size_t offset = 0; + int padlen = 0; + + buffer = RB_ReadPixels(x, y, width, height, &offset, &padlen); + RE_SavePNG(fileName, buffer, width, height, 3); + ri.Hunk_FreeTempMemory(buffer); } /* @@ -1005,7 +907,7 @@ void R_TakeScreenshotPNG( int x, int y, int width, int height, char *fileName ) R_TakeScreenshotJPEG ================== */ -void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) { +void R_TakeScreenshotJPEG(int x, int y, int width, int height, char *fileName) { byte *buffer; size_t offset = 0, memcount; int padlen; @@ -1014,7 +916,7 @@ void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) memcount = (width * 3 + padlen) * height; // gamma correct - if(glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) + if (glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) R_GammaCorrect(buffer + offset, memcount); RE_SaveJPG(fileName, r_screenshotJpegQuality->integer, width, height, buffer + offset, padlen); @@ -1026,14 +928,14 @@ void R_TakeScreenshotJPEG( int x, int y, int width, int height, char *fileName ) R_ScreenshotFilename ================== */ -void R_ScreenshotFilename( char *buf, int bufSize, const char *ext ) { +void R_ScreenshotFilename(char *buf, int bufSize, const char *ext) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "screenshots/shot%s%s", timeStr, ext ); + Com_sprintf(buf, bufSize, "screenshots/shot%s%s", timeStr, ext); } /* @@ -1045,47 +947,47 @@ the menu system, sampled down from full screen distorted images ==================== */ #define LEVELSHOTSIZE 256 -static void R_LevelShot( void ) { - char checkname[MAX_OSPATH]; - byte *buffer; - byte *source, *allsource; - byte *src, *dst; - size_t offset = 0; - int padlen; - int x, y; - int r, g, b; - float xScale, yScale; - int xx, yy; - - Com_sprintf( checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName ); +static void R_LevelShot(void) { + char checkname[MAX_OSPATH]; + byte *buffer; + byte *source, *allsource; + byte *src, *dst; + size_t offset = 0; + int padlen; + int x, y; + int r, g, b; + float xScale, yScale; + int xx, yy; + + Com_sprintf(checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName); allsource = RB_ReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, &offset, &padlen); source = allsource + offset; - buffer = (byte *)ri.Hunk_AllocateTempMemory(LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18); - Com_Memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type + buffer = (byte *)ri.Hunk_AllocateTempMemory(LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18); + Com_Memset(buffer, 0, 18); + buffer[2] = 2; // uncompressed type buffer[12] = LEVELSHOTSIZE & 255; buffer[13] = LEVELSHOTSIZE >> 8; buffer[14] = LEVELSHOTSIZE & 255; buffer[15] = LEVELSHOTSIZE >> 8; - buffer[16] = 24; // pixel size + buffer[16] = 24; // pixel size // resample from source - xScale = glConfig.vidWidth / (4.0*LEVELSHOTSIZE); - yScale = glConfig.vidHeight / (3.0*LEVELSHOTSIZE); - for ( y = 0 ; y < LEVELSHOTSIZE ; y++ ) { - for ( x = 0 ; x < LEVELSHOTSIZE ; x++ ) { + xScale = glConfig.vidWidth / (4.0 * LEVELSHOTSIZE); + yScale = glConfig.vidHeight / (3.0 * LEVELSHOTSIZE); + for (y = 0; y < LEVELSHOTSIZE; y++) { + for (x = 0; x < LEVELSHOTSIZE; x++) { r = g = b = 0; - for ( yy = 0 ; yy < 3 ; yy++ ) { - for ( xx = 0 ; xx < 4 ; xx++ ) { - src = source + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) ); + for (yy = 0; yy < 3; yy++) { + for (xx = 0; xx < 4; xx++) { + src = source + 3 * (glConfig.vidWidth * (int)((y * 3 + yy) * yScale) + (int)((x * 4 + xx) * xScale)); r += src[0]; g += src[1]; b += src[2]; } } - dst = buffer + 18 + 3 * ( y * LEVELSHOTSIZE + x ); + dst = buffer + 18 + 3 * (y * LEVELSHOTSIZE + x); dst[0] = b / 12; dst[1] = g / 12; dst[2] = r / 12; @@ -1093,16 +995,16 @@ static void R_LevelShot( void ) { } // gamma correct - if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders ) { - R_GammaCorrect( buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 ); + if ((tr.overbrightBits > 0) && glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) { + R_GammaCorrect(buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3); } - ri.FS_WriteFile( checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18 ); + ri.FS_WriteFile(checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 + 18); - ri.Hunk_FreeTempMemory( buffer ); - ri.Hunk_FreeTempMemory( allsource ); + ri.Hunk_FreeTempMemory(buffer); + ri.Hunk_FreeTempMemory(allsource); - ri.Printf( PRINT_ALL, "[skipnotify]Wrote %s\n", checkname ); + ri.Printf(PRINT_ALL, "[skipnotify]Wrote %s\n", checkname); } /* @@ -1117,36 +1019,35 @@ screenshot [filename] Doesn't print the pacifier message if there is a second arg ================== */ -void R_ScreenShotTGA_f (void) { +void R_ScreenShotTGA_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.tga", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.tga", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".tga" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".tga"); - if ( ri.FS_FileExists( checkname ) ) { - ri.Printf( PRINT_ALL, "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + ri.Printf(PRINT_ALL, "ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshot(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - ri.Printf( PRINT_ALL, "[skipnotify]Wrote %s\n", checkname ); + if (!silent) + ri.Printf(PRINT_ALL, "[skipnotify]Wrote %s\n", checkname); } /* @@ -1161,67 +1062,65 @@ screenshot [filename] Doesn't print the pacifier message if there is a second arg ================== */ -void R_ScreenShotPNG_f (void) { +void R_ScreenShotPNG_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.png", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.png", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".png" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".png"); - if ( ri.FS_FileExists( checkname ) ) { - ri.Printf( PRINT_ALL, "ScreenShot: Couldn't create a file\n"); + if (ri.FS_FileExists(checkname)) { + ri.Printf(PRINT_ALL, "ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshotPNG( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshotPNG(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - ri.Printf( PRINT_ALL, "[skipnotify]Wrote %s\n", checkname ); + if (!silent) + ri.Printf(PRINT_ALL, "[skipnotify]Wrote %s\n", checkname); } -void R_ScreenShot_f (void) { +void R_ScreenShot_f(void) { char checkname[MAX_OSPATH] = {0}; qboolean silent = qfalse; - if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + if (!strcmp(ri.Cmd_Argv(1), "levelshot")) { R_LevelShot(); return; } - if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + if (!strcmp(ri.Cmd_Argv(1), "silent")) silent = qtrue; - if ( ri.Cmd_Argc() == 2 && !silent ) { + if (ri.Cmd_Argc() == 2 && !silent) { // explicit filename - Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.jpg", ri.Cmd_Argv( 1 ) ); - } - else { + Com_sprintf(checkname, sizeof(checkname), "screenshots/%s.jpg", ri.Cmd_Argv(1)); + } else { // timestamp the file - R_ScreenshotFilename( checkname, sizeof( checkname ), ".jpg" ); + R_ScreenshotFilename(checkname, sizeof(checkname), ".jpg"); - if ( ri.FS_FileExists( checkname ) ) { - ri.Printf( PRINT_ALL, "ScreenShot: Couldn't create a file\n" ); + if (ri.FS_FileExists(checkname)) { + ri.Printf(PRINT_ALL, "ScreenShot: Couldn't create a file\n"); return; - } + } } - R_TakeScreenshotJPEG( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname ); + R_TakeScreenshotJPEG(0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname); - if ( !silent ) - ri.Printf( PRINT_ALL, "[skipnotify]Wrote %s\n", checkname ); + if (!silent) + ri.Printf(PRINT_ALL, "[skipnotify]Wrote %s\n", checkname); } /* @@ -1229,12 +1128,11 @@ void R_ScreenShot_f (void) { RB_TakeVideoFrameCmd ================== */ -const void *RB_TakeVideoFrameCmd( const void *data ) -{ - const videoFrameCommand_t *cmd; - byte *cBuf; - size_t memcount, linelen; - int padwidth, avipadwidth, padlen, avipadlen; +const void *RB_TakeVideoFrameCmd(const void *data) { + const videoFrameCommand_t *cmd; + byte *cBuf; + size_t memcount, linelen; + int padwidth, avipadwidth, padlen, avipadlen; GLint packAlign; cmd = (const videoFrameCommand_t *)data; @@ -1252,24 +1150,18 @@ const void *RB_TakeVideoFrameCmd( const void *data ) cBuf = (byte *)PADP(cmd->captureBuffer, packAlign); - qglReadPixels(0, 0, cmd->width, cmd->height, GL_RGB, - GL_UNSIGNED_BYTE, cBuf); + qglReadPixels(0, 0, cmd->width, cmd->height, GL_RGB, GL_UNSIGNED_BYTE, cBuf); memcount = padwidth * cmd->height; // gamma correct - if(glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) + if (glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) R_GammaCorrect(cBuf, memcount); - if(cmd->motionJpeg) - { - memcount = RE_SaveJPGToBuffer(cmd->encodeBuffer, linelen * cmd->height, - r_aviMotionJpegQuality->integer, - cmd->width, cmd->height, cBuf, padlen); + if (cmd->motionJpeg) { + memcount = RE_SaveJPGToBuffer(cmd->encodeBuffer, linelen * cmd->height, r_aviMotionJpegQuality->integer, cmd->width, cmd->height, cBuf, padlen); ri.CL_WriteAVIVideoFrame(cmd->encodeBuffer, memcount); - } - else - { + } else { byte *lineend, *memend; byte *srcptr, *destptr; @@ -1278,11 +1170,9 @@ const void *RB_TakeVideoFrameCmd( const void *data ) memend = srcptr + memcount; // swap R and B and remove line paddings - while(srcptr < memend) - { + while (srcptr < memend) { lineend = srcptr + linelen; - while(srcptr < lineend) - { + while (srcptr < lineend) { *destptr++ = srcptr[2]; *destptr++ = srcptr[1]; *destptr++ = srcptr[0]; @@ -1306,46 +1196,45 @@ const void *RB_TakeVideoFrameCmd( const void *data ) /* ** GL_SetDefaultState */ -void GL_SetDefaultState( void ) -{ - qglClearDepth( 1.0f ); +void GL_SetDefaultState(void) { + qglClearDepth(1.0f); qglCullFace(GL_FRONT); - qglColor4f (1,1,1,1); + qglColor4f(1, 1, 1, 1); // initialize downstream texture unit if we're running // in a multitexture environment - if ( qglActiveTextureARB ) { - GL_SelectTexture( 1 ); - GL_TextureMode( r_textureMode->string ); - GL_TexEnv( GL_MODULATE ); - qglDisable( GL_TEXTURE_2D ); - GL_SelectTexture( 0 ); + if (qglActiveTextureARB) { + GL_SelectTexture(1); + GL_TextureMode(r_textureMode->string); + GL_TexEnv(GL_MODULATE); + qglDisable(GL_TEXTURE_2D); + GL_SelectTexture(0); } qglEnable(GL_TEXTURE_2D); - GL_TextureMode( r_textureMode->string ); - GL_TexEnv( GL_MODULATE ); + GL_TextureMode(r_textureMode->string); + GL_TexEnv(GL_MODULATE); - qglShadeModel( GL_SMOOTH ); - qglDepthFunc( GL_LEQUAL ); + qglShadeModel(GL_SMOOTH); + qglDepthFunc(GL_LEQUAL); // the vertex array is always enabled, but the color and texture // arrays are enabled and disabled around the compiled vertex array call - qglEnableClientState (GL_VERTEX_ARRAY); + qglEnableClientState(GL_VERTEX_ARRAY); // // make sure our GL state vector is set correctly // glState.glStateBits = GLS_DEPTHTEST_DISABLE | GLS_DEPTHMASK_TRUE; - qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - qglDepthMask( GL_TRUE ); - qglDisable( GL_DEPTH_TEST ); - qglEnable( GL_SCISSOR_TEST ); - qglDisable( GL_CULL_FACE ); - qglDisable( GL_BLEND ); + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + qglDepthMask(GL_TRUE); + qglDisable(GL_DEPTH_TEST); + qglEnable(GL_SCISSOR_TEST); + qglDisable(GL_CULL_FACE); + qglDisable(GL_BLEND); } /* @@ -1355,14 +1244,12 @@ R_PrintLongString Workaround for ri.Printf's 1024 characters buffer limit. ================ */ -void R_PrintLongString(const char *string) -{ +void R_PrintLongString(const char *string) { char buffer[1024]; const char *p = string; int remainingLength = strlen(string); - while (remainingLength > 0) - { + while (remainingLength > 0) { // Take as much characters as possible from the string without splitting words between buffers // This avoids the client console splitting a word up when one half fits on the current line, // but the second half would have to be written on a new line @@ -1379,8 +1266,8 @@ void R_PrintLongString(const char *string) charsToTake = remainingLength; } - Q_strncpyz( buffer, p, charsToTake + 1 ); - ri.Printf( PRINT_ALL, "%s", buffer ); + Q_strncpyz(buffer, p, charsToTake + 1); + ri.Printf(PRINT_ALL, "%s", buffer); remainingLength -= charsToTake; p += charsToTake; } @@ -1392,26 +1279,12 @@ GfxInfo_f ================ */ extern bool g_bTextureRectangleHack; -void GfxInfo_f( void ) -{ - const char *enablestrings[] = - { - "disabled", - "enabled" - }; - const char *fsstrings[] = - { - "windowed", - "fullscreen" - }; - const char *noborderstrings[] = - { - "", - "noborder " - }; +void GfxInfo_f(void) { + const char *enablestrings[] = {"disabled", "enabled"}; + const char *fsstrings[] = {"windowed", "fullscreen"}; + const char *noborderstrings[] = {"", "noborder "}; - const char *tc_table[] = - { + const char *tc_table[] = { "None", "GL_S3_s3tc", "GL_EXT_texture_compression_s3tc", @@ -1420,129 +1293,116 @@ void GfxInfo_f( void ) int fullscreen = ri.Cvar_VariableIntegerValue("r_fullscreen"); int noborder = ri.Cvar_VariableIntegerValue("r_noborder"); - ri.Printf( PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string ); - ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string ); - ri.Printf( PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string ); - R_PrintLongString( glConfigExt.originalExtensionString ); - ri.Printf( PRINT_ALL, "\n"); - ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize ); - ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_UNITS_ARB: %d\n", glConfig.maxActiveTextures ); - ri.Printf( PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); - ri.Printf( PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", - ri.Cvar_VariableIntegerValue("r_mode"), - glConfig.vidWidth, glConfig.vidHeight, - fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], - fsstrings[fullscreen == 1] ); - if ( glConfig.displayFrequency ) - { - ri.Printf( PRINT_ALL, "%d\n", glConfig.displayFrequency ); - } - else - { - ri.Printf( PRINT_ALL, "N/A\n" ); - } - if ( glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders ) - { - ri.Printf( PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits ); - } - else - { - ri.Printf( PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits ); + ri.Printf(PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string); + ri.Printf(PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string); + ri.Printf(PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string); + R_PrintLongString(glConfigExt.originalExtensionString); + ri.Printf(PRINT_ALL, "\n"); + ri.Printf(PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize); + ri.Printf(PRINT_ALL, "GL_MAX_TEXTURE_UNITS_ARB: %d\n", glConfig.maxActiveTextures); + ri.Printf(PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits); + ri.Printf(PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", ri.Cvar_VariableIntegerValue("r_mode"), glConfig.vidWidth, glConfig.vidHeight, + fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], fsstrings[fullscreen == 1]); + if (glConfig.displayFrequency) { + ri.Printf(PRINT_ALL, "%d\n", glConfig.displayFrequency); + } else { + ri.Printf(PRINT_ALL, "N/A\n"); + } + if (glConfig.deviceSupportsGamma && !glConfigExt.doGammaCorrectionWithShaders) { + ri.Printf(PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits); + } else { + ri.Printf(PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits); } // rendering primitives { - int primitives; + int primitives; // default is to use triangles if compiled vertex arrays are present - ri.Printf( PRINT_ALL, "rendering primitives: " ); + ri.Printf(PRINT_ALL, "rendering primitives: "); primitives = r_primitives->integer; - if ( primitives == 0 ) { - if ( qglLockArraysEXT ) { + if (primitives == 0) { + if (qglLockArraysEXT) { primitives = 2; } else { primitives = 1; } } - if ( primitives == -1 ) { - ri.Printf( PRINT_ALL, "none\n" ); - } else if ( primitives == 2 ) { - ri.Printf( PRINT_ALL, "single glDrawElements\n" ); - } else if ( primitives == 1 ) { - ri.Printf( PRINT_ALL, "multiple glArrayElement\n" ); - } else if ( primitives == 3 ) { - ri.Printf( PRINT_ALL, "multiple glColor4ubv + glTexCoord2fv + glVertex3fv\n" ); + if (primitives == -1) { + ri.Printf(PRINT_ALL, "none\n"); + } else if (primitives == 2) { + ri.Printf(PRINT_ALL, "single glDrawElements\n"); + } else if (primitives == 1) { + ri.Printf(PRINT_ALL, "multiple glArrayElement\n"); + } else if (primitives == 3) { + ri.Printf(PRINT_ALL, "multiple glColor4ubv + glTexCoord2fv + glVertex3fv\n"); } } - ri.Printf( PRINT_ALL, "texturemode: %s\n", r_textureMode->string ); - ri.Printf( PRINT_ALL, "picmip: %d\n", r_picmip->integer ); - ri.Printf( PRINT_ALL, "texture bits: %d\n", r_texturebits->integer ); - if ( r_texturebitslm->integer > 0 ) - ri.Printf( PRINT_ALL, "lightmap texture bits: %d\n", r_texturebitslm->integer ); - ri.Printf( PRINT_ALL, "multitexture: %s\n", enablestrings[qglActiveTextureARB != 0] ); - ri.Printf( PRINT_ALL, "compiled vertex arrays: %s\n", enablestrings[qglLockArraysEXT != 0 ] ); - ri.Printf( PRINT_ALL, "texenv add: %s\n", enablestrings[glConfig.textureEnvAddAvailable != 0] ); - ri.Printf( PRINT_ALL, "compressed textures: %s\n", enablestrings[glConfig.textureCompression != TC_NONE] ); - ri.Printf( PRINT_ALL, "compressed lightmaps: %s\n", enablestrings[(r_ext_compressed_lightmaps->integer != 0 && glConfig.textureCompression != TC_NONE)] ); - ri.Printf( PRINT_ALL, "texture compression method: %s\n", tc_table[glConfig.textureCompression] ); - ri.Printf( PRINT_ALL, "anisotropic filtering: %s ", enablestrings[(r_ext_texture_filter_anisotropic->integer != 0) && glConfig.maxTextureFilterAnisotropy] ); - if (r_ext_texture_filter_anisotropic->integer != 0 && glConfig.maxTextureFilterAnisotropy) - { + ri.Printf(PRINT_ALL, "texturemode: %s\n", r_textureMode->string); + ri.Printf(PRINT_ALL, "picmip: %d\n", r_picmip->integer); + ri.Printf(PRINT_ALL, "texture bits: %d\n", r_texturebits->integer); + if (r_texturebitslm->integer > 0) + ri.Printf(PRINT_ALL, "lightmap texture bits: %d\n", r_texturebitslm->integer); + ri.Printf(PRINT_ALL, "multitexture: %s\n", enablestrings[qglActiveTextureARB != 0]); + ri.Printf(PRINT_ALL, "compiled vertex arrays: %s\n", enablestrings[qglLockArraysEXT != 0]); + ri.Printf(PRINT_ALL, "texenv add: %s\n", enablestrings[glConfig.textureEnvAddAvailable != 0]); + ri.Printf(PRINT_ALL, "compressed textures: %s\n", enablestrings[glConfig.textureCompression != TC_NONE]); + ri.Printf(PRINT_ALL, "compressed lightmaps: %s\n", enablestrings[(r_ext_compressed_lightmaps->integer != 0 && glConfig.textureCompression != TC_NONE)]); + ri.Printf(PRINT_ALL, "texture compression method: %s\n", tc_table[glConfig.textureCompression]); + ri.Printf(PRINT_ALL, "anisotropic filtering: %s ", enablestrings[(r_ext_texture_filter_anisotropic->integer != 0) && glConfig.maxTextureFilterAnisotropy]); + if (r_ext_texture_filter_anisotropic->integer != 0 && glConfig.maxTextureFilterAnisotropy) { if (Q_isintegral(r_ext_texture_filter_anisotropic->value)) - ri.Printf( PRINT_ALL, "(%i of ", (int)r_ext_texture_filter_anisotropic->value); + ri.Printf(PRINT_ALL, "(%i of ", (int)r_ext_texture_filter_anisotropic->value); else - ri.Printf( PRINT_ALL, "(%f of ", r_ext_texture_filter_anisotropic->value); + ri.Printf(PRINT_ALL, "(%f of ", r_ext_texture_filter_anisotropic->value); if (Q_isintegral(glConfig.maxTextureFilterAnisotropy)) - ri.Printf( PRINT_ALL, "%i)\n", (int)glConfig.maxTextureFilterAnisotropy); + ri.Printf(PRINT_ALL, "%i)\n", (int)glConfig.maxTextureFilterAnisotropy); else - ri.Printf( PRINT_ALL, "%f)\n", glConfig.maxTextureFilterAnisotropy); + ri.Printf(PRINT_ALL, "%f)\n", glConfig.maxTextureFilterAnisotropy); } - ri.Printf( PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_DynamicGlow->integer ? 1 : 0] ); - if (g_bTextureRectangleHack) ri.Printf( PRINT_ALL, "Dynamic Glow ATI BAD DRIVER HACK %s\n", enablestrings[g_bTextureRectangleHack] ); + ri.Printf(PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_DynamicGlow->integer ? 1 : 0]); + if (g_bTextureRectangleHack) + ri.Printf(PRINT_ALL, "Dynamic Glow ATI BAD DRIVER HACK %s\n", enablestrings[g_bTextureRectangleHack]); - if ( r_finish->integer ) { - ri.Printf( PRINT_ALL, "Forcing glFinish\n" ); + if (r_finish->integer) { + ri.Printf(PRINT_ALL, "Forcing glFinish\n"); } int displayRefresh = ri.Cvar_VariableIntegerValue("r_displayRefresh"); - if ( displayRefresh ) { - ri.Printf( PRINT_ALL, "Display refresh set to %d\n", displayRefresh); + if (displayRefresh) { + ri.Printf(PRINT_ALL, "Display refresh set to %d\n", displayRefresh); } - if (tr.world) - { - ri.Printf( PRINT_ALL, "Light Grid size set to (%.2f %.2f %.2f)\n", tr.world->lightGridSize[0], tr.world->lightGridSize[1], tr.world->lightGridSize[2] ); + if (tr.world) { + ri.Printf(PRINT_ALL, "Light Grid size set to (%.2f %.2f %.2f)\n", tr.world->lightGridSize[0], tr.world->lightGridSize[1], tr.world->lightGridSize[2]); } } -void R_AtiHackToggle_f(void) -{ - g_bTextureRectangleHack = !g_bTextureRectangleHack; -} +void R_AtiHackToggle_f(void) { g_bTextureRectangleHack = !g_bTextureRectangleHack; } typedef struct consoleCommand_s { - const char *cmd; - xcommand_t func; + const char *cmd; + xcommand_t func; } consoleCommand_t; -static consoleCommand_t commands[] = { - { "imagelist", R_ImageList_f }, - { "shaderlist", R_ShaderList_f }, - { "skinlist", R_SkinList_f }, - { "fontlist", R_FontList_f }, - { "screenshot", R_ScreenShot_f }, - { "screenshot_png", R_ScreenShotPNG_f }, - { "screenshot_tga", R_ScreenShotTGA_f }, - { "gfxinfo", GfxInfo_f }, - { "r_atihack", R_AtiHackToggle_f }, - { "r_we", R_WorldEffect_f }, - { "imagecacheinfo", RE_RegisterImages_Info_f }, - { "modellist", R_Modellist_f }, - { "modelcacheinfo", RE_RegisterModels_Info_f }, +static consoleCommand_t commands[] = { + {"imagelist", R_ImageList_f}, + {"shaderlist", R_ShaderList_f}, + {"skinlist", R_SkinList_f}, + {"fontlist", R_FontList_f}, + {"screenshot", R_ScreenShot_f}, + {"screenshot_png", R_ScreenShotPNG_f}, + {"screenshot_tga", R_ScreenShotTGA_f}, + {"gfxinfo", GfxInfo_f}, + {"r_atihack", R_AtiHackToggle_f}, + {"r_we", R_WorldEffect_f}, + {"imagecacheinfo", RE_RegisterImages_Info_f}, + {"modellist", R_Modellist_f}, + {"modelcacheinfo", RE_RegisterModels_Info_f}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); #ifdef _DEBUG #define MIN_PRIMITIVES -1 @@ -1556,211 +1416,205 @@ static const size_t numCommands = ARRAY_LEN( commands ); R_Register =============== */ -void R_Register( void ) -{ - //FIXME: lol badness +void R_Register(void) { + // FIXME: lol badness se_language = ri.Cvar_Get("se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, ""); // // latched and archived variables // - r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compress_textures", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compressed_lightmaps = ri.Cvar_Get( "r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_preferred_tc_method = ri.Cvar_Get( "r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_gamma_control = ri.Cvar_Get( "r_ext_gamma_control", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_ext_texture_filter_anisotropic = ri.Cvar_Get( "r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND, "" ); - r_gammaShaders = ri.Cvar_Get( "r_gammaShaders", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_environmentMapping = ri.Cvar_Get( "r_environmentMapping", "1", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlow = ri.Cvar_Get( "r_DynamicGlow", "0", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowPasses = ri.Cvar_Get( "r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowDelta = ri.Cvar_Get( "r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowIntensity = ri.Cvar_Get( "r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowSoft = ri.Cvar_Get( "r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND, "" ); - r_DynamicGlowWidth = ri.Cvar_Get( "r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_DynamicGlowHeight = ri.Cvar_Get( "r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_picmip = ri.Cvar_Get( "r_picmip", "0", CVAR_ARCHIVE|CVAR_LATCH, "" ); - ri.Cvar_CheckRange( r_picmip, 0, 16, qtrue ); - r_colorMipLevels = ri.Cvar_Get( "r_colorMipLevels", "0", CVAR_LATCH, "" ); - r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_texturebitslm = ri.Cvar_Get( "r_texturebitslm", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_overBrightBits = ri.Cvar_Get( "r_overBrightBits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_mapOverBrightBits = ri.Cvar_Get( "r_mapOverBrightBits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE|CVAR_LATCH, "" ); - r_uiFullScreen = ri.Cvar_Get( "r_uifullscreen", "0", CVAR_NONE, "" ); - r_subdivisions = ri.Cvar_Get( "r_subdivisions", "4", CVAR_ARCHIVE_ND|CVAR_LATCH, "" ); - ri.Cvar_CheckRange( r_subdivisions, 0, 80, qfalse ); - - r_fullbright = ri.Cvar_Get( "r_fullbright", "0", CVAR_CHEAT, "" ); - r_intensity = ri.Cvar_Get( "r_intensity", "1", CVAR_LATCH, "" ); - r_singleShader = ri.Cvar_Get( "r_singleShader", "0", CVAR_CHEAT|CVAR_LATCH, "" ); - r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE_ND, "" ); - r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE_ND, "" ); - r_autolodscalevalue = ri.Cvar_Get( "r_autolodscalevalue", "0", CVAR_ROM, "" ); - r_flares = ri.Cvar_Get( "r_flares", "1", CVAR_ARCHIVE_ND, "" ); - - r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_ARCHIVE_ND, "" ); - ri.Cvar_CheckRange( r_znear, 0.001f, 10, qfalse ); - r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND, "" ); - r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE_ND, "" ); - r_inGameVideo = ri.Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE_ND, "" ); - r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE_ND, "" ); - r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE, "" ); + r_allowExtensions = ri.Cvar_Get("r_allowExtensions", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compressed_textures = ri.Cvar_Get("r_ext_compress_textures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compressed_lightmaps = ri.Cvar_Get("r_ext_compress_lightmaps", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_preferred_tc_method = ri.Cvar_Get("r_ext_preferred_tc_method", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_gamma_control = ri.Cvar_Get("r_ext_gamma_control", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_multitexture = ri.Cvar_Get("r_ext_multitexture", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_compiled_vertex_array = ri.Cvar_Get("r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_texture_env_add = ri.Cvar_Get("r_ext_texture_env_add", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_ext_texture_filter_anisotropic = ri.Cvar_Get("r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE_ND, ""); + r_gammaShaders = ri.Cvar_Get("r_gammaShaders", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_environmentMapping = ri.Cvar_Get("r_environmentMapping", "1", CVAR_ARCHIVE_ND, ""); + r_DynamicGlow = ri.Cvar_Get("r_DynamicGlow", "0", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowPasses = ri.Cvar_Get("r_DynamicGlowPasses", "5", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowDelta = ri.Cvar_Get("r_DynamicGlowDelta", "0.8f", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowIntensity = ri.Cvar_Get("r_DynamicGlowIntensity", "1.13f", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowSoft = ri.Cvar_Get("r_DynamicGlowSoft", "1", CVAR_ARCHIVE_ND, ""); + r_DynamicGlowWidth = ri.Cvar_Get("r_DynamicGlowWidth", "320", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_DynamicGlowHeight = ri.Cvar_Get("r_DynamicGlowHeight", "240", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_picmip = ri.Cvar_Get("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_picmip, 0, 16, qtrue); + r_colorMipLevels = ri.Cvar_Get("r_colorMipLevels", "0", CVAR_LATCH, ""); + r_detailTextures = ri.Cvar_Get("r_detailtextures", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_texturebits = ri.Cvar_Get("r_texturebits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_texturebitslm = ri.Cvar_Get("r_texturebitslm", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_overBrightBits = ri.Cvar_Get("r_overBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_mapOverBrightBits = ri.Cvar_Get("r_mapOverBrightBits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_simpleMipMaps = ri.Cvar_Get("r_simpleMipMaps", "1", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + r_vertexLight = ri.Cvar_Get("r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_uiFullScreen = ri.Cvar_Get("r_uifullscreen", "0", CVAR_NONE, ""); + r_subdivisions = ri.Cvar_Get("r_subdivisions", "4", CVAR_ARCHIVE_ND | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_subdivisions, 0, 80, qfalse); + + r_fullbright = ri.Cvar_Get("r_fullbright", "0", CVAR_CHEAT, ""); + r_intensity = ri.Cvar_Get("r_intensity", "1", CVAR_LATCH, ""); + r_singleShader = ri.Cvar_Get("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH, ""); + r_lodCurveError = ri.Cvar_Get("r_lodCurveError", "250", CVAR_ARCHIVE_ND, ""); + r_lodbias = ri.Cvar_Get("r_lodbias", "0", CVAR_ARCHIVE_ND, ""); + r_autolodscalevalue = ri.Cvar_Get("r_autolodscalevalue", "0", CVAR_ROM, ""); + r_flares = ri.Cvar_Get("r_flares", "1", CVAR_ARCHIVE_ND, ""); + + r_znear = ri.Cvar_Get("r_znear", "4", CVAR_ARCHIVE_ND, ""); + ri.Cvar_CheckRange(r_znear, 0.001f, 10, qfalse); + r_ignoreGLErrors = ri.Cvar_Get("r_ignoreGLErrors", "1", CVAR_ARCHIVE_ND, ""); + r_fastsky = ri.Cvar_Get("r_fastsky", "0", CVAR_ARCHIVE_ND, ""); + r_inGameVideo = ri.Cvar_Get("r_inGameVideo", "1", CVAR_ARCHIVE_ND, ""); + r_drawSun = ri.Cvar_Get("r_drawSun", "0", CVAR_ARCHIVE_ND, ""); + r_dynamiclight = ri.Cvar_Get("r_dynamiclight", "1", CVAR_ARCHIVE, ""); // rjr - removed for hacking -// r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "1", CVAR_CHEAT, "" ); - r_finish = ri.Cvar_Get( "r_finish", "0", CVAR_ARCHIVE_ND, "" ); - r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, "" ); - r_markcount = ri.Cvar_Get( "r_markcount", "100", CVAR_ARCHIVE_ND, "" ); - r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE_ND, "" ); - r_facePlaneCull = ri.Cvar_Get( "r_facePlaneCull", "1", CVAR_ARCHIVE_ND, "" ); - r_cullRoofFaces = ri.Cvar_Get( "r_cullRoofFaces", "0", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_roofCullCeilDist = ri.Cvar_Get( "r_roofCullCeilDist", "256", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_roofCullFloorDist = ri.Cvar_Get( "r_roofCeilFloorDist", "128", CVAR_CHEAT, "" ); //attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww - r_primitives = ri.Cvar_Get( "r_primitives", "0", CVAR_ARCHIVE_ND, "" ); - ri.Cvar_CheckRange( r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue ); - r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.6", CVAR_CHEAT, "" ); - r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT, "" ); - r_autoMap = ri.Cvar_Get( "r_autoMap", "0", CVAR_ARCHIVE_ND, "" ); //automap renderside toggle for debugging -rww - r_autoMapBackAlpha = ri.Cvar_Get( "r_autoMapBackAlpha", "0", CVAR_NONE, "" ); //alpha of automap bg -rww - r_autoMapDisable = ri.Cvar_Get( "r_autoMapDisable", "1", CVAR_NONE, "" ); - r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_CHEAT, "" ); - r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP, "" ); - r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT, "" ); - r_dlightStyle = ri.Cvar_Get( "r_dlightStyle", "1", CVAR_TEMP, "" ); - r_surfaceSprites = ri.Cvar_Get( "r_surfaceSprites", "1", CVAR_ARCHIVE_ND, "" ); - r_surfaceWeather = ri.Cvar_Get( "r_surfaceWeather", "0", CVAR_TEMP, "" ); - r_windSpeed = ri.Cvar_Get( "r_windSpeed", "0", CVAR_NONE, "" ); - r_windAngle = ri.Cvar_Get( "r_windAngle", "0", CVAR_NONE, "" ); - r_windGust = ri.Cvar_Get( "r_windGust", "0", CVAR_NONE, "" ); - r_windDampFactor = ri.Cvar_Get( "r_windDampFactor", "0.1", CVAR_NONE, "" ); - r_windPointForce = ri.Cvar_Get( "r_windPointForce", "0", CVAR_NONE, "" ); - r_windPointX = ri.Cvar_Get( "r_windPointX", "0", CVAR_NONE, "" ); - r_windPointY = ri.Cvar_Get( "r_windPointY", "0", CVAR_NONE, "" ); - r_nocurves = ri.Cvar_Get( "r_nocurves", "0", CVAR_CHEAT, "" ); - r_drawworld = ri.Cvar_Get( "r_drawworld", "1", CVAR_CHEAT, "" ); - r_drawfog = ri.Cvar_Get( "r_drawfog", "2", CVAR_CHEAT, "" ); - r_lightmap = ri.Cvar_Get( "r_lightmap", "0", CVAR_CHEAT, "" ); - r_portalOnly = ri.Cvar_Get( "r_portalOnly", "0", CVAR_CHEAT, "" ); - r_skipBackEnd = ri.Cvar_Get( "r_skipBackEnd", "0", CVAR_CHEAT, "" ); - r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT, "" ); - r_lodscale = ri.Cvar_Get( "r_lodscale", "5", CVAR_NONE, "" ); - r_norefresh = ri.Cvar_Get( "r_norefresh", "0", CVAR_CHEAT, "" ); - r_drawentities = ri.Cvar_Get( "r_drawentities", "1", CVAR_CHEAT, "" ); - r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_CHEAT, "" ); - r_nocull = ri.Cvar_Get( "r_nocull", "0", CVAR_CHEAT, "" ); - r_novis = ri.Cvar_Get( "r_novis", "0", CVAR_CHEAT, "" ); - r_showcluster = ri.Cvar_Get( "r_showcluster", "0", CVAR_CHEAT, "" ); - r_speeds = ri.Cvar_Get( "r_speeds", "0", CVAR_CHEAT, "" ); - r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT, "" ); - r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT, "" ); - r_debugSurface = ri.Cvar_Get( "r_debugSurface", "0", CVAR_CHEAT, "" ); - r_nobind = ri.Cvar_Get( "r_nobind", "0", CVAR_CHEAT, "" ); - r_showtris = ri.Cvar_Get( "r_showtris", "0", CVAR_CHEAT, "" ); - r_showsky = ri.Cvar_Get( "r_showsky", "0", CVAR_CHEAT, "" ); - r_shownormals = ri.Cvar_Get( "r_shownormals", "0", CVAR_CHEAT, "" ); - r_clear = ri.Cvar_Get( "r_clear", "0", CVAR_CHEAT, "" ); - r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT, "" ); - r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT, "" ); - r_lockpvs = ri.Cvar_Get( "r_lockpvs", "0", CVAR_CHEAT, "" ); - r_noportals = ri.Cvar_Get( "r_noportals", "0", CVAR_CHEAT, "" ); - r_shadows = ri.Cvar_Get( "cg_shadows", "1", CVAR_NONE, "" ); - r_shadowRange = ri.Cvar_Get( "r_shadowRange", "1000", CVAR_NONE, "" ); - r_marksOnTriangleMeshes = ri.Cvar_Get( "r_marksOnTriangleMeshes", "0", CVAR_ARCHIVE_ND, "" ); - r_aspectCorrectFonts = ri.Cvar_Get( "r_aspectCorrectFonts", "0", CVAR_ARCHIVE, "" ); - r_maxpolys = ri.Cvar_Get( "r_maxpolys", XSTRING( DEFAULT_MAX_POLYS ), CVAR_NONE, "" ); - r_maxpolyverts = ri.Cvar_Get( "r_maxpolyverts", XSTRING( DEFAULT_MAX_POLYVERTS ), CVAR_NONE, "" ); + // r_dlightBacks = ri.Cvar_Get( "r_dlightBacks", "1", CVAR_CHEAT, "" ); + r_finish = ri.Cvar_Get("r_finish", "0", CVAR_ARCHIVE_ND, ""); + r_textureMode = ri.Cvar_Get("r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, ""); + r_markcount = ri.Cvar_Get("r_markcount", "100", CVAR_ARCHIVE_ND, ""); + r_gamma = ri.Cvar_Get("r_gamma", "1", CVAR_ARCHIVE_ND, ""); + r_facePlaneCull = ri.Cvar_Get("r_facePlaneCull", "1", CVAR_ARCHIVE_ND, ""); + r_cullRoofFaces = + ri.Cvar_Get("r_cullRoofFaces", "0", CVAR_CHEAT, ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_roofCullCeilDist = ri.Cvar_Get("r_roofCullCeilDist", "256", CVAR_CHEAT, + ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_roofCullFloorDist = ri.Cvar_Get("r_roofCeilFloorDist", "128", CVAR_CHEAT, + ""); // attempted smart method of culling out upwards facing surfaces on roofs for automap shots -rww + r_primitives = ri.Cvar_Get("r_primitives", "0", CVAR_ARCHIVE_ND, ""); + ri.Cvar_CheckRange(r_primitives, MIN_PRIMITIVES, MAX_PRIMITIVES, qtrue); + r_ambientScale = ri.Cvar_Get("r_ambientScale", "0.6", CVAR_CHEAT, ""); + r_directedScale = ri.Cvar_Get("r_directedScale", "1", CVAR_CHEAT, ""); + r_autoMap = ri.Cvar_Get("r_autoMap", "0", CVAR_ARCHIVE_ND, ""); // automap renderside toggle for debugging -rww + r_autoMapBackAlpha = ri.Cvar_Get("r_autoMapBackAlpha", "0", CVAR_NONE, ""); // alpha of automap bg -rww + r_autoMapDisable = ri.Cvar_Get("r_autoMapDisable", "1", CVAR_NONE, ""); + r_showImages = ri.Cvar_Get("r_showImages", "0", CVAR_CHEAT, ""); + r_debugLight = ri.Cvar_Get("r_debuglight", "0", CVAR_TEMP, ""); + r_debugSort = ri.Cvar_Get("r_debugSort", "0", CVAR_CHEAT, ""); + r_dlightStyle = ri.Cvar_Get("r_dlightStyle", "1", CVAR_TEMP, ""); + r_surfaceSprites = ri.Cvar_Get("r_surfaceSprites", "1", CVAR_ARCHIVE_ND, ""); + r_surfaceWeather = ri.Cvar_Get("r_surfaceWeather", "0", CVAR_TEMP, ""); + r_windSpeed = ri.Cvar_Get("r_windSpeed", "0", CVAR_NONE, ""); + r_windAngle = ri.Cvar_Get("r_windAngle", "0", CVAR_NONE, ""); + r_windGust = ri.Cvar_Get("r_windGust", "0", CVAR_NONE, ""); + r_windDampFactor = ri.Cvar_Get("r_windDampFactor", "0.1", CVAR_NONE, ""); + r_windPointForce = ri.Cvar_Get("r_windPointForce", "0", CVAR_NONE, ""); + r_windPointX = ri.Cvar_Get("r_windPointX", "0", CVAR_NONE, ""); + r_windPointY = ri.Cvar_Get("r_windPointY", "0", CVAR_NONE, ""); + r_nocurves = ri.Cvar_Get("r_nocurves", "0", CVAR_CHEAT, ""); + r_drawworld = ri.Cvar_Get("r_drawworld", "1", CVAR_CHEAT, ""); + r_drawfog = ri.Cvar_Get("r_drawfog", "2", CVAR_CHEAT, ""); + r_lightmap = ri.Cvar_Get("r_lightmap", "0", CVAR_CHEAT, ""); + r_portalOnly = ri.Cvar_Get("r_portalOnly", "0", CVAR_CHEAT, ""); + r_skipBackEnd = ri.Cvar_Get("r_skipBackEnd", "0", CVAR_CHEAT, ""); + r_measureOverdraw = ri.Cvar_Get("r_measureOverdraw", "0", CVAR_CHEAT, ""); + r_lodscale = ri.Cvar_Get("r_lodscale", "5", CVAR_NONE, ""); + r_norefresh = ri.Cvar_Get("r_norefresh", "0", CVAR_CHEAT, ""); + r_drawentities = ri.Cvar_Get("r_drawentities", "1", CVAR_CHEAT, ""); + r_ignore = ri.Cvar_Get("r_ignore", "1", CVAR_CHEAT, ""); + r_nocull = ri.Cvar_Get("r_nocull", "0", CVAR_CHEAT, ""); + r_novis = ri.Cvar_Get("r_novis", "0", CVAR_CHEAT, ""); + r_showcluster = ri.Cvar_Get("r_showcluster", "0", CVAR_CHEAT, ""); + r_speeds = ri.Cvar_Get("r_speeds", "0", CVAR_CHEAT, ""); + r_verbose = ri.Cvar_Get("r_verbose", "0", CVAR_CHEAT, ""); + r_logFile = ri.Cvar_Get("r_logFile", "0", CVAR_CHEAT, ""); + r_debugSurface = ri.Cvar_Get("r_debugSurface", "0", CVAR_CHEAT, ""); + r_nobind = ri.Cvar_Get("r_nobind", "0", CVAR_CHEAT, ""); + r_showtris = ri.Cvar_Get("r_showtris", "0", CVAR_CHEAT, ""); + r_showsky = ri.Cvar_Get("r_showsky", "0", CVAR_CHEAT, ""); + r_shownormals = ri.Cvar_Get("r_shownormals", "0", CVAR_CHEAT, ""); + r_clear = ri.Cvar_Get("r_clear", "0", CVAR_CHEAT, ""); + r_offsetFactor = ri.Cvar_Get("r_offsetfactor", "-1", CVAR_CHEAT, ""); + r_offsetUnits = ri.Cvar_Get("r_offsetunits", "-2", CVAR_CHEAT, ""); + r_lockpvs = ri.Cvar_Get("r_lockpvs", "0", CVAR_CHEAT, ""); + r_noportals = ri.Cvar_Get("r_noportals", "0", CVAR_CHEAT, ""); + r_shadows = ri.Cvar_Get("cg_shadows", "1", CVAR_NONE, ""); + r_shadowRange = ri.Cvar_Get("r_shadowRange", "1000", CVAR_NONE, ""); + r_marksOnTriangleMeshes = ri.Cvar_Get("r_marksOnTriangleMeshes", "0", CVAR_ARCHIVE_ND, ""); + r_aspectCorrectFonts = ri.Cvar_Get("r_aspectCorrectFonts", "0", CVAR_ARCHIVE, ""); + r_maxpolys = ri.Cvar_Get("r_maxpolys", XSTRING(DEFAULT_MAX_POLYS), CVAR_NONE, ""); + r_maxpolyverts = ri.Cvar_Get("r_maxpolyverts", XSTRING(DEFAULT_MAX_POLYVERTS), CVAR_NONE, ""); /* Ghoul2 Insert Start */ #ifdef _DEBUG - r_noPrecacheGLA = ri.Cvar_Get( "r_noPrecacheGLA", "0", CVAR_CHEAT, "" ); + r_noPrecacheGLA = ri.Cvar_Get("r_noPrecacheGLA", "0", CVAR_CHEAT, ""); #endif - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", CVAR_CHEAT, "" ); - r_Ghoul2AnimSmooth = ri.Cvar_Get( "r_ghoul2animsmooth", "0.3", CVAR_NONE, "" ); - r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get( "r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, "" ); - broadsword = ri.Cvar_Get( "broadsword", "0", CVAR_ARCHIVE_ND, "" ); - broadsword_kickbones = ri.Cvar_Get( "broadsword_kickbones", "1", CVAR_NONE, "" ); - broadsword_kickorigin = ri.Cvar_Get( "broadsword_kickorigin", "1", CVAR_NONE, "" ); - broadsword_dontstopanim = ri.Cvar_Get( "broadsword_dontstopanim", "0", CVAR_NONE, "" ); - broadsword_waitforshot = ri.Cvar_Get( "broadsword_waitforshot", "0", CVAR_NONE, "" ); - broadsword_playflop = ri.Cvar_Get( "broadsword_playflop", "1", CVAR_NONE, "" ); - broadsword_smallbbox = ri.Cvar_Get( "broadsword_smallbbox", "0", CVAR_NONE, "" ); - broadsword_extra1 = ri.Cvar_Get( "broadsword_extra1", "0", CVAR_NONE, "" ); - broadsword_extra2 = ri.Cvar_Get( "broadsword_extra2", "0", CVAR_NONE, "" ); - broadsword_effcorr = ri.Cvar_Get( "broadsword_effcorr", "1", CVAR_NONE, "" ); - broadsword_ragtobase = ri.Cvar_Get( "broadsword_ragtobase", "2", CVAR_NONE, "" ); - broadsword_dircap = ri.Cvar_Get( "broadsword_dircap", "64", CVAR_NONE, "" ); -/* -Ghoul2 Insert End -*/ - r_modelpoolmegs = ri.Cvar_Get("r_modelpoolmegs", "20", CVAR_ARCHIVE, "" ); - if (ri.Sys_LowPhysicalMemory() ) + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", CVAR_CHEAT, ""); + r_Ghoul2AnimSmooth = ri.Cvar_Get("r_ghoul2animsmooth", "0.3", CVAR_NONE, ""); + r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get("r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, ""); + broadsword = ri.Cvar_Get("broadsword", "0", CVAR_ARCHIVE_ND, ""); + broadsword_kickbones = ri.Cvar_Get("broadsword_kickbones", "1", CVAR_NONE, ""); + broadsword_kickorigin = ri.Cvar_Get("broadsword_kickorigin", "1", CVAR_NONE, ""); + broadsword_dontstopanim = ri.Cvar_Get("broadsword_dontstopanim", "0", CVAR_NONE, ""); + broadsword_waitforshot = ri.Cvar_Get("broadsword_waitforshot", "0", CVAR_NONE, ""); + broadsword_playflop = ri.Cvar_Get("broadsword_playflop", "1", CVAR_NONE, ""); + broadsword_smallbbox = ri.Cvar_Get("broadsword_smallbbox", "0", CVAR_NONE, ""); + broadsword_extra1 = ri.Cvar_Get("broadsword_extra1", "0", CVAR_NONE, ""); + broadsword_extra2 = ri.Cvar_Get("broadsword_extra2", "0", CVAR_NONE, ""); + broadsword_effcorr = ri.Cvar_Get("broadsword_effcorr", "1", CVAR_NONE, ""); + broadsword_ragtobase = ri.Cvar_Get("broadsword_ragtobase", "2", CVAR_NONE, ""); + broadsword_dircap = ri.Cvar_Get("broadsword_dircap", "64", CVAR_NONE, ""); + /* + Ghoul2 Insert End + */ + r_modelpoolmegs = ri.Cvar_Get("r_modelpoolmegs", "20", CVAR_ARCHIVE, ""); + if (ri.Sys_LowPhysicalMemory()) ri.Cvar_Set("r_modelpoolmegs", "0"); - r_aviMotionJpegQuality = ri.Cvar_Get( "r_aviMotionJpegQuality", "90", CVAR_ARCHIVE_ND, "" ); - r_screenshotJpegQuality = ri.Cvar_Get( "r_screenshotJpegQuality", "95", CVAR_ARCHIVE_ND, "" ); + r_aviMotionJpegQuality = ri.Cvar_Get("r_aviMotionJpegQuality", "90", CVAR_ARCHIVE_ND, ""); + r_screenshotJpegQuality = ri.Cvar_Get("r_screenshotJpegQuality", "95", CVAR_ARCHIVE_ND, ""); - ri.Cvar_CheckRange( r_aviMotionJpegQuality, 10, 100, qtrue ); - ri.Cvar_CheckRange( r_screenshotJpegQuality, 10, 100, qtrue ); + ri.Cvar_CheckRange(r_aviMotionJpegQuality, 10, 100, qtrue); + ri.Cvar_CheckRange(r_screenshotJpegQuality, 10, 100, qtrue); - r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces" ); + r_patchStitching = ri.Cvar_Get("r_patchStitching", "1", CVAR_ARCHIVE, "Enable stitching of neighbouring patch surfaces"); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_AddCommand( commands[i].cmd, commands[i].func, "" ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_AddCommand(commands[i].cmd, commands[i].func, ""); } - /* =============== R_Init =============== */ -extern void R_InitWorldEffects(void); //tr_WorldEffects.cpp -void R_Init( void ) { +extern void R_InitWorldEffects(void); // tr_WorldEffects.cpp +void R_Init(void) { int i; byte *ptr; -// ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); + // ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); // clear all our internal state - memset( &tr, 0, sizeof( tr ) ); - memset( &backEnd, 0, sizeof( backEnd ) ); - memset( &tess, 0, sizeof( tess ) ); + memset(&tr, 0, sizeof(tr)); + memset(&backEnd, 0, sizeof(backEnd)); + memset(&tess, 0, sizeof(tess)); -// Swap_Init(); + // Swap_Init(); #ifndef FINAL_BUILD - if ( (intptr_t)tess.xyz & 15 ) { - ri.Printf( PRINT_ALL, "WARNING: tess.xyz not 16 byte aligned\n" ); + if ((intptr_t)tess.xyz & 15) { + ri.Printf(PRINT_ALL, "WARNING: tess.xyz not 16 byte aligned\n"); } #endif // // init function tables // - for ( i = 0; i < FUNCTABLE_SIZE; i++ ) - { - tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) ); - tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f; + for (i = 0; i < FUNCTABLE_SIZE; i++) { + tr.sinTable[i] = sin(DEG2RAD(i * 360.0f / ((float)(FUNCTABLE_SIZE - 1)))); + tr.squareTable[i] = (i < FUNCTABLE_SIZE / 2) ? 1.0f : -1.0f; tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE; tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i]; - if ( i < FUNCTABLE_SIZE / 2 ) - { - if ( i < FUNCTABLE_SIZE / 4 ) - { - tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 ); - } - else - { - tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4]; + if (i < FUNCTABLE_SIZE / 2) { + if (i < FUNCTABLE_SIZE / 4) { + tr.triangleTable[i] = (float)i / (FUNCTABLE_SIZE / 4); + } else { + tr.triangleTable[i] = 1.0f - tr.triangleTable[i - FUNCTABLE_SIZE / 4]; } - } - else - { - tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2]; + } else { + tr.triangleTable[i] = -tr.triangleTable[i - FUNCTABLE_SIZE / 2]; } } R_InitFogTable(); @@ -1769,18 +1623,17 @@ void R_Init( void ) { R_NoiseInit(); R_Register(); - max_polys = Q_min( r_maxpolys->integer, DEFAULT_MAX_POLYS ); - max_polyverts = Q_min( r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS ); + max_polys = Q_min(r_maxpolys->integer, DEFAULT_MAX_POLYS); + max_polyverts = Q_min(r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS); - ptr = (byte *)Hunk_Alloc( sizeof( *backEndData ) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low); - backEndData = (backEndData_t *) ptr; - backEndData->polys = (srfPoly_t *) ((char *) ptr + sizeof( *backEndData )); - backEndData->polyVerts = (polyVert_t *) ((char *) ptr + sizeof( *backEndData ) + sizeof(srfPoly_t) * max_polys); + ptr = (byte *)Hunk_Alloc(sizeof(*backEndData) + sizeof(srfPoly_t) * max_polys + sizeof(polyVert_t) * max_polyverts, h_low); + backEndData = (backEndData_t *)ptr; + backEndData->polys = (srfPoly_t *)((char *)ptr + sizeof(*backEndData)); + backEndData->polyVerts = (polyVert_t *)((char *)ptr + sizeof(*backEndData) + sizeof(srfPoly_t) * max_polys); R_InitNextFrame(); - for(i = 0; i < MAX_LIGHT_STYLES; i++) - { + for (i = 0; i < MAX_LIGHT_STYLES; i++) { RE_SetLightStyle(i, -1); } InitOpenGL(); @@ -1792,22 +1645,22 @@ void R_Init( void ) { R_InitFonts(); R_ModelInit(); -// re.G2VertSpaceServer = &IHeapAllocator_singleton; - R_InitDecals ( ); + // re.G2VertSpaceServer = &IHeapAllocator_singleton; + R_InitDecals(); R_InitWorldEffects(); #if defined(_DEBUG) - int err = qglGetError(); - if ( err != GL_NO_ERROR ) - ri.Printf( PRINT_ALL, "glGetError() = 0x%x\n", err); + int err = qglGetError(); + if (err != GL_NO_ERROR) + ri.Printf(PRINT_ALL, "glGetError() = 0x%x\n", err); #endif RestoreGhoul2InfoArray(); // print info GfxInfo_f(); -// ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); + // ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); } /* @@ -1815,75 +1668,65 @@ void R_Init( void ) { RE_Shutdown =============== */ -void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { +void RE_Shutdown(qboolean destroyWindow, qboolean restarting) { -// ri.Printf( PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow ); + // ri.Printf( PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow ); - for ( size_t i = 0; i < numCommands; i++ ) - ri.Cmd_RemoveCommand( commands[i].cmd ); + for (size_t i = 0; i < numCommands; i++) + ri.Cmd_RemoveCommand(commands[i].cmd); - if ( r_DynamicGlow && r_DynamicGlow->integer ) - { + if (r_DynamicGlow && r_DynamicGlow->integer) { // Release the Glow Vertex Shader. - if ( tr.glowVShader ) - { - qglDeleteProgramsARB( 1, &tr.glowVShader ); + if (tr.glowVShader) { + qglDeleteProgramsARB(1, &tr.glowVShader); } // Release Pixel Shader. - if ( tr.glowPShader ) - { - if ( qglCombinerParameteriNV ) - { + if (tr.glowPShader) { + if (qglCombinerParameteriNV) { // Release the Glow Regcom call list. - qglDeleteLists( tr.glowPShader, 1 ); - } - else if ( qglGenProgramsARB ) - { + qglDeleteLists(tr.glowPShader, 1); + } else if (qglGenProgramsARB) { // Release the Glow Fragment Shader. - qglDeleteProgramsARB( 1, &tr.glowPShader ); + qglDeleteProgramsARB(1, &tr.glowPShader); } } - if ( tr.gammaCorrectVtxShader ) - { + if (tr.gammaCorrectVtxShader) { qglDeleteProgramsARB(1, &tr.gammaCorrectVtxShader); } - if ( tr.gammaCorrectPxShader ) - { + if (tr.gammaCorrectPxShader) { qglDeleteProgramsARB(1, &tr.gammaCorrectPxShader); } // Release the scene glow texture. - qglDeleteTextures( 1, &tr.screenGlow ); + qglDeleteTextures(1, &tr.screenGlow); // Release the scene texture. - qglDeleteTextures( 1, &tr.sceneImage ); + qglDeleteTextures(1, &tr.sceneImage); qglDeleteTextures(1, &tr.gammaCorrectLUTImage); // Release the blur texture. - qglDeleteTextures( 1, &tr.blurImage ); + qglDeleteTextures(1, &tr.blurImage); } R_ShutdownWorldEffects(); R_ShutdownFonts(); - if ( tr.registered ) { + if (tr.registered) { R_IssuePendingRenderCommands(); - if (destroyWindow) - { - R_DeleteTextures(); // only do this for vid_restart now, not during things like map load + if (destroyWindow) { + R_DeleteTextures(); // only do this for vid_restart now, not during things like map load - if ( restarting ) - { + if (restarting) { SaveGhoul2InfoArray(); } } } // shut down platform specific OpenGL stuff - if ( destroyWindow ) { + if (destroyWindow) { ri.WIN_Shutdown(); } @@ -1897,18 +1740,16 @@ RE_EndRegistration Touch all images to make sure they are resident ============= */ -void RE_EndRegistration( void ) { +void RE_EndRegistration(void) { R_IssuePendingRenderCommands(); if (!ri.Sys_LowPhysicalMemory()) { RB_ShowImages(); } } -void RE_GetLightStyle(int style, color4ub_t color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_GetLightStyle: %d is out of range", (int)style ); +void RE_GetLightStyle(int style, color4ub_t color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_GetLightStyle: %d is out of range", (int)style); return; } @@ -1916,50 +1757,48 @@ void RE_GetLightStyle(int style, color4ub_t color) baDest->i = baSource->i; } -void RE_SetLightStyle(int style, int color) -{ - if (style >= MAX_LIGHT_STYLES) - { - Com_Error( ERR_FATAL, "RE_SetLightStyle: %d is out of range", (int)style ); +void RE_SetLightStyle(int style, int color) { + if (style >= MAX_LIGHT_STYLES) { + Com_Error(ERR_FATAL, "RE_SetLightStyle: %d is out of range", (int)style); return; } byteAlias_t *ba = (byteAlias_t *)&styleColors[style]; - if ( ba->i != color) { + if (ba->i != color) { ba->i = color; } } -static void SetRangedFog( float range ) { tr.rangedFog = range; } +static void SetRangedFog(float range) { tr.rangedFog = range; } extern qboolean gG2_GBMNoReconstruct; extern qboolean gG2_GBMUseSPMethod; -static void G2API_BoltMatrixReconstruction( qboolean reconstruct ) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } -static void G2API_BoltMatrixSPMethod( qboolean spMethod ) { gG2_GBMUseSPMethod = spMethod; } - -extern float tr_distortionAlpha; //opaque -extern float tr_distortionStretch; //no stretch override -extern qboolean tr_distortionPrePost; //capture before postrender phase? -extern qboolean tr_distortionNegate; //negative blend mode -static void SetRefractionProperties( float distortionAlpha, float distortionStretch, qboolean distortionPrePost, qboolean distortionNegate ) { +static void G2API_BoltMatrixReconstruction(qboolean reconstruct) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } +static void G2API_BoltMatrixSPMethod(qboolean spMethod) { gG2_GBMUseSPMethod = spMethod; } + +extern float tr_distortionAlpha; // opaque +extern float tr_distortionStretch; // no stretch override +extern qboolean tr_distortionPrePost; // capture before postrender phase? +extern qboolean tr_distortionNegate; // negative blend mode +static void SetRefractionProperties(float distortionAlpha, float distortionStretch, qboolean distortionPrePost, qboolean distortionNegate) { tr_distortionAlpha = distortionAlpha; tr_distortionStretch = distortionStretch; tr_distortionPrePost = distortionPrePost; tr_distortionNegate = distortionNegate; } -static float GetDistanceCull( void ) { return tr.distanceCull; } +static float GetDistanceCull(void) { return tr.distanceCull; } -static void GetRealRes( int *w, int *h ) { +static void GetRealRes(int *w, int *h) { *w = glConfig.vidWidth; *h = glConfig.vidHeight; } -extern void R_SVModelInit( void ); //tr_model.cpp -extern void R_AutomapElevationAdjustment( float newHeight ); //tr_world.cpp -extern qboolean R_InitializeWireframeAutomap( void ); //tr_world.cpp +extern void R_SVModelInit(void); // tr_model.cpp +extern void R_AutomapElevationAdjustment(float newHeight); // tr_world.cpp +extern qboolean R_InitializeWireframeAutomap(void); // tr_world.cpp -extern qhandle_t RE_RegisterServerSkin( const char *name ); +extern qhandle_t RE_RegisterServerSkin(const char *name); /* @@@@@@@@@@@@@@@@@@@@@ @@ -1968,197 +1807,197 @@ GetRefAPI @@@@@@@@@@@@@@@@@@@@@ */ extern "C" { -Q_EXPORT refexport_t* QDECL GetRefAPI( int apiVersion, refimport_t *rimp ) { +Q_EXPORT refexport_t *QDECL GetRefAPI(int apiVersion, refimport_t *rimp) { static refexport_t re; - assert( rimp ); + assert(rimp); ri = *rimp; - memset( &re, 0, sizeof( re ) ); + memset(&re, 0, sizeof(re)); - if ( apiVersion != REF_API_VERSION ) { - ri.Printf( PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion ); + if (apiVersion != REF_API_VERSION) { + ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", REF_API_VERSION, apiVersion); return NULL; } // the RE_ functions are Renderer Entry points re.Shutdown = RE_Shutdown; - re.BeginRegistration = RE_BeginRegistration; - re.RegisterModel = RE_RegisterModel; - re.RegisterServerModel = RE_RegisterServerModel; - re.RegisterSkin = RE_RegisterSkin; - re.RegisterServerSkin = RE_RegisterServerSkin; - re.RegisterShader = RE_RegisterShader; - re.RegisterShaderNoMip = RE_RegisterShaderNoMip; - re.ShaderNameFromIndex = RE_ShaderNameFromIndex; - re.LoadWorld = RE_LoadWorldMap; - re.SetWorldVisData = RE_SetWorldVisData; - re.EndRegistration = RE_EndRegistration; - re.BeginFrame = RE_BeginFrame; - re.EndFrame = RE_EndFrame; - re.MarkFragments = R_MarkFragments; - re.LerpTag = R_LerpTag; - re.ModelBounds = R_ModelBounds; - re.DrawRotatePic = RE_RotatePic; - re.DrawRotatePic2 = RE_RotatePic2; - re.ClearScene = RE_ClearScene; - re.ClearDecals = RE_ClearDecals; - re.AddRefEntityToScene = RE_AddRefEntityToScene; - re.AddMiniRefEntityToScene = RE_AddMiniRefEntityToScene; - re.AddPolyToScene = RE_AddPolyToScene; - re.AddDecalToScene = RE_AddDecalToScene; - re.LightForPoint = R_LightForPoint; - re.AddLightToScene = RE_AddLightToScene; - re.AddAdditiveLightToScene = RE_AddAdditiveLightToScene; - - re.RenderScene = RE_RenderScene; - re.SetColor = RE_SetColor; - re.DrawStretchPic = RE_StretchPic; - re.DrawStretchRaw = RE_StretchRaw; - re.UploadCinematic = RE_UploadCinematic; - - re.RegisterFont = RE_RegisterFont; - re.Font_StrLenPixels = RE_Font_StrLenPixels; - re.Font_StrLenChars = RE_Font_StrLenChars; - re.Font_HeightPixels = RE_Font_HeightPixels; - re.Font_DrawString = RE_Font_DrawString; - re.Language_IsAsian = Language_IsAsian; - re.Language_UsesSpaces = Language_UsesSpaces; - re.AnyLanguage_ReadCharFromString = AnyLanguage_ReadCharFromString; - - re.RemapShader = R_RemapShader; - re.GetEntityToken = R_GetEntityToken; - re.inPVS = R_inPVS; - re.GetLightStyle = RE_GetLightStyle; - re.SetLightStyle = RE_SetLightStyle; - re.GetBModelVerts = RE_GetBModelVerts; + re.BeginRegistration = RE_BeginRegistration; + re.RegisterModel = RE_RegisterModel; + re.RegisterServerModel = RE_RegisterServerModel; + re.RegisterSkin = RE_RegisterSkin; + re.RegisterServerSkin = RE_RegisterServerSkin; + re.RegisterShader = RE_RegisterShader; + re.RegisterShaderNoMip = RE_RegisterShaderNoMip; + re.ShaderNameFromIndex = RE_ShaderNameFromIndex; + re.LoadWorld = RE_LoadWorldMap; + re.SetWorldVisData = RE_SetWorldVisData; + re.EndRegistration = RE_EndRegistration; + re.BeginFrame = RE_BeginFrame; + re.EndFrame = RE_EndFrame; + re.MarkFragments = R_MarkFragments; + re.LerpTag = R_LerpTag; + re.ModelBounds = R_ModelBounds; + re.DrawRotatePic = RE_RotatePic; + re.DrawRotatePic2 = RE_RotatePic2; + re.ClearScene = RE_ClearScene; + re.ClearDecals = RE_ClearDecals; + re.AddRefEntityToScene = RE_AddRefEntityToScene; + re.AddMiniRefEntityToScene = RE_AddMiniRefEntityToScene; + re.AddPolyToScene = RE_AddPolyToScene; + re.AddDecalToScene = RE_AddDecalToScene; + re.LightForPoint = R_LightForPoint; + re.AddLightToScene = RE_AddLightToScene; + re.AddAdditiveLightToScene = RE_AddAdditiveLightToScene; + + re.RenderScene = RE_RenderScene; + re.SetColor = RE_SetColor; + re.DrawStretchPic = RE_StretchPic; + re.DrawStretchRaw = RE_StretchRaw; + re.UploadCinematic = RE_UploadCinematic; + + re.RegisterFont = RE_RegisterFont; + re.Font_StrLenPixels = RE_Font_StrLenPixels; + re.Font_StrLenChars = RE_Font_StrLenChars; + re.Font_HeightPixels = RE_Font_HeightPixels; + re.Font_DrawString = RE_Font_DrawString; + re.Language_IsAsian = Language_IsAsian; + re.Language_UsesSpaces = Language_UsesSpaces; + re.AnyLanguage_ReadCharFromString = AnyLanguage_ReadCharFromString; + + re.RemapShader = R_RemapShader; + re.GetEntityToken = R_GetEntityToken; + re.inPVS = R_inPVS; + re.GetLightStyle = RE_GetLightStyle; + re.SetLightStyle = RE_SetLightStyle; + re.GetBModelVerts = RE_GetBModelVerts; // missing from 1.01 - re.SetRangedFog = SetRangedFog; - re.SetRefractionProperties = SetRefractionProperties; - re.GetDistanceCull = GetDistanceCull; - re.GetRealRes = GetRealRes; - re.AutomapElevationAdjustment = R_AutomapElevationAdjustment; //tr_world.cpp - re.InitializeWireframeAutomap = R_InitializeWireframeAutomap; //tr_world.cpp - re.AddWeatherZone = RE_AddWeatherZone; - re.WorldEffectCommand = RE_WorldEffectCommand; - re.RegisterMedia_LevelLoadBegin = RE_RegisterMedia_LevelLoadBegin; - re.RegisterMedia_LevelLoadEnd = RE_RegisterMedia_LevelLoadEnd; - re.RegisterMedia_GetLevel = RE_RegisterMedia_GetLevel; - re.RegisterImages_LevelLoadEnd = RE_RegisterImages_LevelLoadEnd; - re.RegisterModels_LevelLoadEnd = RE_RegisterModels_LevelLoadEnd; + re.SetRangedFog = SetRangedFog; + re.SetRefractionProperties = SetRefractionProperties; + re.GetDistanceCull = GetDistanceCull; + re.GetRealRes = GetRealRes; + re.AutomapElevationAdjustment = R_AutomapElevationAdjustment; // tr_world.cpp + re.InitializeWireframeAutomap = R_InitializeWireframeAutomap; // tr_world.cpp + re.AddWeatherZone = RE_AddWeatherZone; + re.WorldEffectCommand = RE_WorldEffectCommand; + re.RegisterMedia_LevelLoadBegin = RE_RegisterMedia_LevelLoadBegin; + re.RegisterMedia_LevelLoadEnd = RE_RegisterMedia_LevelLoadEnd; + re.RegisterMedia_GetLevel = RE_RegisterMedia_GetLevel; + re.RegisterImages_LevelLoadEnd = RE_RegisterImages_LevelLoadEnd; + re.RegisterModels_LevelLoadEnd = RE_RegisterModels_LevelLoadEnd; // AVI recording - re.TakeVideoFrame = RE_TakeVideoFrame; + re.TakeVideoFrame = RE_TakeVideoFrame; // G2 stuff - re.InitSkins = R_InitSkins; - re.InitShaders = R_InitShaders; - re.SVModelInit = R_SVModelInit; - re.HunkClearCrap = RE_HunkClearCrap; + re.InitSkins = R_InitSkins; + re.InitShaders = R_InitShaders; + re.SVModelInit = R_SVModelInit; + re.HunkClearCrap = RE_HunkClearCrap; // G2API - re.G2API_AddBolt = G2API_AddBolt; - re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; - re.G2API_AddSurface = G2API_AddSurface; - re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; - re.G2API_AttachEnt = G2API_AttachEnt; - re.G2API_AttachG2Model = G2API_AttachG2Model; - re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; - re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; - re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; - re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; - re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; - re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; - re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; - re.G2API_CollisionDetect = G2API_CollisionDetect; - re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; - re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; - re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; - re.G2API_DetachG2Model = G2API_DetachG2Model; - re.G2API_DoesBoneExist = G2API_DoesBoneExist; - re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; - re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; - re.G2API_GetAnimFileName = G2API_GetAnimFileName; - re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; - re.G2API_GetAnimRange = G2API_GetAnimRange; - re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; - re.G2API_GetBoneAnim = G2API_GetBoneAnim; - re.G2API_GetBoneIndex = G2API_GetBoneIndex; - re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; - re.G2API_GetGLAName = G2API_GetGLAName; - re.G2API_GetModelName = G2API_GetModelName; - re.G2API_GetParentSurface = G2API_GetParentSurface; - re.G2API_GetRagBonePos = G2API_GetRagBonePos; - re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; - re.G2API_GetSurfaceName = G2API_GetSurfaceName; - re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; - re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; - re.G2API_GetTime = G2API_GetTime; - re.G2API_Ghoul2Size = G2API_Ghoul2Size; - re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; - re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; - re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; - re.G2API_IKMove = G2API_IKMove; - re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; - re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; - re.G2API_IsPaused = G2API_IsPaused; - re.G2API_ListBones = G2API_ListBones; - re.G2API_ListSurfaces = G2API_ListSurfaces; - re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; - re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; - re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; - re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; - re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; - re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; - re.G2API_RagEffectorKick = G2API_RagEffectorKick; - re.G2API_RagForceSolve = G2API_RagForceSolve; - re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; - re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; - re.G2API_RemoveBolt = G2API_RemoveBolt; - re.G2API_RemoveBone = G2API_RemoveBone; - re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; - re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; - re.G2API_RemoveSurface = G2API_RemoveSurface; - re.G2API_ResetRagDoll = G2API_ResetRagDoll; - re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; - re.G2API_SetBoltInfo = G2API_SetBoltInfo; - re.G2API_SetBoneAngles = G2API_SetBoneAngles; - re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; - re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; - re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; - re.G2API_SetBoneAnim = G2API_SetBoneAnim; - re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; - re.G2API_SetBoneIKState = G2API_SetBoneIKState; - re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; - re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; - re.G2API_SetLodBias = G2API_SetLodBias; - re.G2API_SetNewOrigin = G2API_SetNewOrigin; - re.G2API_SetRagDoll = G2API_SetRagDoll; - re.G2API_SetRootSurface = G2API_SetRootSurface; - re.G2API_SetShader = G2API_SetShader; - re.G2API_SetSkin = G2API_SetSkin; - re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; - re.G2API_SetTime = G2API_SetTime; - re.G2API_SkinlessModel = G2API_SkinlessModel; - re.G2API_StopBoneAngles = G2API_StopBoneAngles; - re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; - re.G2API_StopBoneAnim = G2API_StopBoneAnim; - re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; - - #ifdef _G2_GORE - re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; - re.G2API_AddSkinGore = G2API_AddSkinGore; - re.G2API_ClearSkinGore = G2API_ClearSkinGore; - #endif // _SOF2 + re.G2API_AddBolt = G2API_AddBolt; + re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; + re.G2API_AddSurface = G2API_AddSurface; + re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; + re.G2API_AttachEnt = G2API_AttachEnt; + re.G2API_AttachG2Model = G2API_AttachG2Model; + re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; + re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; + re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; + re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; + re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; + re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; + re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; + re.G2API_CollisionDetect = G2API_CollisionDetect; + re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; + re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; + re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; + re.G2API_DetachG2Model = G2API_DetachG2Model; + re.G2API_DoesBoneExist = G2API_DoesBoneExist; + re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; + re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; + re.G2API_GetAnimFileName = G2API_GetAnimFileName; + re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; + re.G2API_GetAnimRange = G2API_GetAnimRange; + re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; + re.G2API_GetBoneAnim = G2API_GetBoneAnim; + re.G2API_GetBoneIndex = G2API_GetBoneIndex; + re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; + re.G2API_GetGLAName = G2API_GetGLAName; + re.G2API_GetModelName = G2API_GetModelName; + re.G2API_GetParentSurface = G2API_GetParentSurface; + re.G2API_GetRagBonePos = G2API_GetRagBonePos; + re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; + re.G2API_GetSurfaceName = G2API_GetSurfaceName; + re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; + re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; + re.G2API_GetTime = G2API_GetTime; + re.G2API_Ghoul2Size = G2API_Ghoul2Size; + re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; + re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; + re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; + re.G2API_IKMove = G2API_IKMove; + re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; + re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; + re.G2API_IsPaused = G2API_IsPaused; + re.G2API_ListBones = G2API_ListBones; + re.G2API_ListSurfaces = G2API_ListSurfaces; + re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; + re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; + re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; + re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; + re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; + re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; + re.G2API_RagEffectorKick = G2API_RagEffectorKick; + re.G2API_RagForceSolve = G2API_RagForceSolve; + re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; + re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; + re.G2API_RemoveBolt = G2API_RemoveBolt; + re.G2API_RemoveBone = G2API_RemoveBone; + re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; + re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; + re.G2API_RemoveSurface = G2API_RemoveSurface; + re.G2API_ResetRagDoll = G2API_ResetRagDoll; + re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; + re.G2API_SetBoltInfo = G2API_SetBoltInfo; + re.G2API_SetBoneAngles = G2API_SetBoneAngles; + re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; + re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; + re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; + re.G2API_SetBoneAnim = G2API_SetBoneAnim; + re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; + re.G2API_SetBoneIKState = G2API_SetBoneIKState; + re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; + re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; + re.G2API_SetLodBias = G2API_SetLodBias; + re.G2API_SetNewOrigin = G2API_SetNewOrigin; + re.G2API_SetRagDoll = G2API_SetRagDoll; + re.G2API_SetRootSurface = G2API_SetRootSurface; + re.G2API_SetShader = G2API_SetShader; + re.G2API_SetSkin = G2API_SetSkin; + re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; + re.G2API_SetTime = G2API_SetTime; + re.G2API_SkinlessModel = G2API_SkinlessModel; + re.G2API_StopBoneAngles = G2API_StopBoneAngles; + re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; + re.G2API_StopBoneAnim = G2API_StopBoneAnim; + re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; + +#ifdef _G2_GORE + re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; + re.G2API_AddSkinGore = G2API_AddSkinGore; + re.G2API_ClearSkinGore = G2API_ClearSkinGore; +#endif // _SOF2 // this is set in R_Init - //re.G2VertSpaceServer = G2VertSpaceServer; + // re.G2VertSpaceServer = G2VertSpaceServer; - re.ext.Font_StrLenPixels = RE_Font_StrLenPixelsNew; + re.ext.Font_StrLenPixels = RE_Font_StrLenPixelsNew; return &re; } -} //extern "C" +} // extern "C" diff --git a/codemp/rd-vanilla/tr_light.cpp b/codemp/rd-vanilla/tr_light.cpp index baa71e8847..a9096a69bf 100644 --- a/codemp/rd-vanilla/tr_light.cpp +++ b/codemp/rd-vanilla/tr_light.cpp @@ -25,13 +25,12 @@ along with this program; if not, see . #include "tr_local.h" -#define DLIGHT_AT_RADIUS 16 +#define DLIGHT_AT_RADIUS 16 // at the edge of a dlight's influence, this amount of light will be added -#define DLIGHT_MINIMUM_RADIUS 16 +#define DLIGHT_MINIMUM_RADIUS 16 // never calculate a range less than this to prevent huge light numbers - /* =============== R_TransformDlights @@ -41,15 +40,15 @@ Used by both the front end (for DlightBmodel) and the back end (before doing the lighting calculation) =============== */ -void R_TransformDlights( int count, dlight_t *dl, orientationr_t *ori) { - int i; - vec3_t temp; - - for ( i = 0 ; i < count ; i++, dl++ ) { - VectorSubtract( dl->origin, ori->origin, temp ); - dl->transformed[0] = DotProduct( temp, ori->axis[0] ); - dl->transformed[1] = DotProduct( temp, ori->axis[1] ); - dl->transformed[2] = DotProduct( temp, ori->axis[2] ); +void R_TransformDlights(int count, dlight_t *dl, orientationr_t *ori) { + int i; + vec3_t temp; + + for (i = 0; i < count; i++, dl++) { + VectorSubtract(dl->origin, ori->origin, temp); + dl->transformed[0] = DotProduct(temp, ori->axis[0]); + dl->transformed[1] = DotProduct(temp, ori->axis[1]); + dl->transformed[2] = DotProduct(temp, ori->axis[2]); } } @@ -60,32 +59,30 @@ R_DlightBmodel Determine which dynamic lights may effect this bmodel ============= */ -void R_DlightBmodel( bmodel_t *bmodel, bool NoLight ) -{ //rwwRMG - modified args - int i, j; - dlight_t *dl; - int mask; - msurface_t *surf; +void R_DlightBmodel(bmodel_t *bmodel, bool NoLight) { // rwwRMG - modified args + int i, j; + dlight_t *dl; + int mask; + msurface_t *surf; // transform all the lights - R_TransformDlights( tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori ); + R_TransformDlights(tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori); mask = 0; - if (!NoLight) - { - for ( i=0 ; itransformed[j] - bmodel->bounds[1][j] > dl->radius ) { + for (j = 0; j < 3; j++) { + if (dl->transformed[j] - bmodel->bounds[1][j] > dl->radius) { break; } - if ( bmodel->bounds[0][j] - dl->transformed[j] > dl->radius ) { + if (bmodel->bounds[0][j] - dl->transformed[j] > dl->radius) { break; } } - if ( j < 3 ) { + if (j < 3) { continue; } @@ -98,19 +95,18 @@ void R_DlightBmodel( bmodel_t *bmodel, bool NoLight ) tr.currentEntity->dlightBits = mask; // set the dlight bits in all the surfaces - for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { + for (i = 0; i < bmodel->numSurfaces; i++) { surf = bmodel->firstSurface + i; - if ( *surf->data == SF_FACE ) { + if (*surf->data == SF_FACE) { ((srfSurfaceFace_t *)surf->data)->dlightBits = mask; - } else if ( *surf->data == SF_GRID ) { + } else if (*surf->data == SF_GRID) { ((srfGridMesh_t *)surf->data)->dlightBits = mask; - } else if ( *surf->data == SF_TRIANGLES ) { + } else if (*surf->data == SF_TRIANGLES) { ((srfTriangles_t *)surf->data)->dlightBits = mask; } } } - /* ============================================================================= @@ -119,11 +115,11 @@ LIGHT SAMPLING ============================================================================= */ -extern cvar_t *r_ambientScale; -extern cvar_t *r_directedScale; -extern cvar_t *r_debugLight; +extern cvar_t *r_ambientScale; +extern cvar_t *r_directedScale; +extern cvar_t *r_debugLight; -//rwwRMG - VectorScaleVector is now a #define +// rwwRMG - VectorScaleVector is now a #define /* ================= @@ -131,50 +127,49 @@ R_SetupEntityLightingGrid ================= */ -static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { - vec3_t lightOrigin; - int pos[3]; - int i, j; - float frac[3]; - int gridStep[3]; - vec3_t direction; - float totalFactor; - unsigned short *startGridPos; - - if (r_fullbright->integer) - { +static void R_SetupEntityLightingGrid(trRefEntity_t *ent) { + vec3_t lightOrigin; + int pos[3]; + int i, j; + float frac[3]; + int gridStep[3]; + vec3_t direction; + float totalFactor; + unsigned short *startGridPos; + + if (r_fullbright->integer) { ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = 255.0; ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = 255.0; - VectorCopy( tr.sunDirection, ent->lightDir ); + VectorCopy(tr.sunDirection, ent->lightDir); return; } - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } - VectorSubtract( lightOrigin, tr.world->lightGridOrigin, lightOrigin ); - for ( i = 0 ; i < 3 ; i++ ) { - float v; + VectorSubtract(lightOrigin, tr.world->lightGridOrigin, lightOrigin); + for (i = 0; i < 3; i++) { + float v; - v = lightOrigin[i]*tr.world->lightGridInverseSize[i]; - pos[i] = floor( v ); + v = lightOrigin[i] * tr.world->lightGridInverseSize[i]; + pos[i] = floor(v); frac[i] = v - pos[i]; - if ( pos[i] < 0 ) { + if (pos[i] < 0) { pos[i] = 0; - } else if ( pos[i] >= tr.world->lightGridBounds[i] - 1 ) { + } else if (pos[i] >= tr.world->lightGridBounds[i] - 1) { pos[i] = tr.world->lightGridBounds[i] - 1; } } - VectorClear( ent->ambientLight ); - VectorClear( ent->directedLight ); - VectorClear( direction ); + VectorClear(ent->ambientLight); + VectorClear(ent->directedLight); + VectorClear(direction); // trilerp the light value gridStep[0] = 1; @@ -183,17 +178,17 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { startGridPos = tr.world->lightGridArray + (pos[0] * gridStep[0] + pos[1] * gridStep[1] + pos[2] * gridStep[2]); totalFactor = 0; - for ( i = 0 ; i < 8 ; i++ ) { - float factor; - mgrid_t *data; - unsigned short *gridPos; - int lat, lng; - vec3_t normal; + for (i = 0; i < 8; i++) { + float factor; + mgrid_t *data; + unsigned short *gridPos; + int lat, lng; + vec3_t normal; factor = 1.0; gridPos = startGridPos; - for ( j = 0 ; j < 3 ; j++ ) { - if ( i & (1<= tr.world->lightGridArray + tr.world->numGridArrayElements) - {//we've gone off the array somehow + if (gridPos >= tr.world->lightGridArray + tr.world->numGridArrayElements) { // we've gone off the array somehow continue; } data = tr.world->lightGridData + *gridPos; - if ( data->styles[0] == LS_LSNONE ) - { - continue; // ignore samples in walls + if (data->styles[0] == LS_LSNONE) { + continue; // ignore samples in walls } totalFactor += factor; - for(j=0;jstyles[j] != LS_LSNONE) - { - const byte style= data->styles[j]; + for (j = 0; j < MAXLIGHTMAPS; j++) { + if (data->styles[j] != LS_LSNONE) { + const byte style = data->styles[j]; ent->ambientLight[0] += factor * data->ambientLight[j][0] * styleColors[style][0] / 255.0f; ent->ambientLight[1] += factor * data->ambientLight[j][1] * styleColors[style][1] / 255.0f; @@ -227,17 +218,15 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { ent->directedLight[0] += factor * data->directLight[j][0] * styleColors[style][0] / 255.0f; ent->directedLight[1] += factor * data->directLight[j][1] * styleColors[style][1] / 255.0f; ent->directedLight[2] += factor * data->directLight[j][2] * styleColors[style][2] / 255.0f; - } - else - { + } else { break; } } lat = data->latLong[1]; lng = data->latLong[0]; - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) @@ -247,50 +236,48 @@ static void R_SetupEntityLightingGrid( trRefEntity_t *ent ) { normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; normal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; - VectorMA( direction, factor, normal, direction ); + VectorMA(direction, factor, normal, direction); } - if ( totalFactor > 0 && totalFactor < 0.99 ) - { + if (totalFactor > 0 && totalFactor < 0.99) { totalFactor = 1.0 / totalFactor; - VectorScale( ent->ambientLight, totalFactor, ent->ambientLight ); - VectorScale( ent->directedLight, totalFactor, ent->directedLight ); + VectorScale(ent->ambientLight, totalFactor, ent->ambientLight); + VectorScale(ent->directedLight, totalFactor, ent->directedLight); } - VectorScale( ent->ambientLight, r_ambientScale->value, ent->ambientLight ); - VectorScale( ent->directedLight, r_directedScale->value, ent->directedLight ); + VectorScale(ent->ambientLight, r_ambientScale->value, ent->ambientLight); + VectorScale(ent->directedLight, r_directedScale->value, ent->directedLight); - VectorNormalize2( direction, ent->lightDir ); + VectorNormalize2(direction, ent->lightDir); } - /* =============== LogLight =============== */ -static void LogLight( trRefEntity_t *ent ) { - int max1, max2; +static void LogLight(trRefEntity_t *ent) { + int max1, max2; - if ( !(ent->e.renderfx & RF_FIRST_PERSON ) ) { + if (!(ent->e.renderfx & RF_FIRST_PERSON)) { return; } max1 = ent->ambientLight[0]; - if ( ent->ambientLight[1] > max1 ) { + if (ent->ambientLight[1] > max1) { max1 = ent->ambientLight[1]; - } else if ( ent->ambientLight[2] > max1 ) { + } else if (ent->ambientLight[2] > max1) { max1 = ent->ambientLight[2]; } max2 = ent->directedLight[0]; - if ( ent->directedLight[1] > max2 ) { + if (ent->directedLight[1] > max2) { max2 = ent->directedLight[1]; - } else if ( ent->directedLight[2] > max2 ) { + } else if (ent->directedLight[2] > max2) { max2 = ent->directedLight[2]; } - ri.Printf( PRINT_ALL, "amb:%i dir:%i\n", max1, max2 ); + ri.Printf(PRINT_ALL, "amb:%i dir:%i\n", max1, max2); } /* @@ -301,17 +288,17 @@ Calculates all the lighting values that will be used by the Calc_* functions ================= */ -void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { - int i; - dlight_t *dl; - float power; - vec3_t dir; - float d; - vec3_t lightDir; - vec3_t lightOrigin; +void R_SetupEntityLighting(const trRefdef_t *refdef, trRefEntity_t *ent) { + int i; + dlight_t *dl; + float power; + vec3_t dir; + float d; + vec3_t lightDir; + vec3_t lightOrigin; // lighting calculations - if ( ent->lightingCalculated ) { + if (ent->lightingCalculated) { return; } ent->lightingCalculated = qtrue; @@ -319,47 +306,38 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { // // trace a sample point down to find ambient light // - if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + if (ent->e.renderfx & RF_LIGHTING_ORIGIN) { // seperate lightOrigins are needed so an object that is // sinking into the ground can still be lit, and so // multi-part models can be lit identically - VectorCopy( ent->e.lightingOrigin, lightOrigin ); + VectorCopy(ent->e.lightingOrigin, lightOrigin); } else { - VectorCopy( ent->e.origin, lightOrigin ); + VectorCopy(ent->e.origin, lightOrigin); } // if NOWORLDMODEL, only use dynamic lights (menu system, etc) - if ( !(refdef->rdflags & RDF_NOWORLDMODEL ) - && tr.world->lightGridData ) { - R_SetupEntityLightingGrid( ent ); + if (!(refdef->rdflags & RDF_NOWORLDMODEL) && tr.world->lightGridData) { + R_SetupEntityLightingGrid(ent); } else { - ent->ambientLight[0] = ent->ambientLight[1] = - ent->ambientLight[2] = tr.identityLight * 150; - ent->directedLight[0] = ent->directedLight[1] = - ent->directedLight[2] = tr.identityLight * 150; - VectorCopy( tr.sunDirection, ent->lightDir ); + ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = tr.identityLight * 150; + ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = tr.identityLight * 150; + VectorCopy(tr.sunDirection, ent->lightDir); } // bonus items and view weapons have a fixed minimum add - if ( 1 /* ent->e.renderfx & RF_MINLIGHT */ ) { + if (1 /* ent->e.renderfx & RF_MINLIGHT */) { // give everything a minimum light add ent->ambientLight[0] += tr.identityLight * 32; ent->ambientLight[1] += tr.identityLight * 32; ent->ambientLight[2] += tr.identityLight * 32; } - if (ent->e.renderfx & RF_MINLIGHT) - { //the minlight flag is now for items rotating on their holo thing - if (ent->e.shaderRGBA[0] == 255 && - ent->e.shaderRGBA[1] == 255 && - ent->e.shaderRGBA[2] == 0) - { + if (ent->e.renderfx & RF_MINLIGHT) { // the minlight flag is now for items rotating on their holo thing + if (ent->e.shaderRGBA[0] == 255 && ent->e.shaderRGBA[1] == 255 && ent->e.shaderRGBA[2] == 0) { ent->ambientLight[0] += tr.identityLight * 255; ent->ambientLight[1] += tr.identityLight * 255; ent->ambientLight[2] += tr.identityLight * 0; - } - else - { + } else { ent->ambientLight[0] += tr.identityLight * 16; ent->ambientLight[1] += tr.identityLight * 96; ent->ambientLight[2] += tr.identityLight * 150; @@ -369,46 +347,46 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { // // modify the light by dynamic lights // - d = VectorLength( ent->directedLight ); - VectorScale( ent->lightDir, d, lightDir ); + d = VectorLength(ent->directedLight); + VectorScale(ent->lightDir, d, lightDir); - for ( i = 0 ; i < refdef->num_dlights ; i++ ) { + for (i = 0; i < refdef->num_dlights; i++) { dl = &refdef->dlights[i]; - VectorSubtract( dl->origin, lightOrigin, dir ); - d = VectorNormalize( dir ); + VectorSubtract(dl->origin, lightOrigin, dir); + d = VectorNormalize(dir); - power = DLIGHT_AT_RADIUS * ( dl->radius * dl->radius ); - if ( d < DLIGHT_MINIMUM_RADIUS ) { + power = DLIGHT_AT_RADIUS * (dl->radius * dl->radius); + if (d < DLIGHT_MINIMUM_RADIUS) { d = DLIGHT_MINIMUM_RADIUS; } - d = power / ( d * d ); + d = power / (d * d); - VectorMA( ent->directedLight, d, dl->color, ent->directedLight ); - VectorMA( lightDir, d, dir, lightDir ); + VectorMA(ent->directedLight, d, dl->color, ent->directedLight); + VectorMA(lightDir, d, dir, lightDir); } // clamp ambient - for ( i = 0 ; i < 3 ; i++ ) { - if ( ent->ambientLight[i] > tr.identityLightByte ) { + for (i = 0; i < 3; i++) { + if (ent->ambientLight[i] > tr.identityLightByte) { ent->ambientLight[i] = tr.identityLightByte; } } - if ( r_debugLight->integer ) { - LogLight( ent ); + if (r_debugLight->integer) { + LogLight(ent); } // save out the byte packet version - ((byte *)&ent->ambientLightInt)[0] = Q_ftol( ent->ambientLight[0] ); - ((byte *)&ent->ambientLightInt)[1] = Q_ftol( ent->ambientLight[1] ); - ((byte *)&ent->ambientLightInt)[2] = Q_ftol( ent->ambientLight[2] ); + ((byte *)&ent->ambientLightInt)[0] = Q_ftol(ent->ambientLight[0]); + ((byte *)&ent->ambientLightInt)[1] = Q_ftol(ent->ambientLight[1]); + ((byte *)&ent->ambientLightInt)[2] = Q_ftol(ent->ambientLight[2]); ((byte *)&ent->ambientLightInt)[3] = 0xff; // transform the direction to local space - VectorNormalize( lightDir ); - ent->lightDir[0] = DotProduct( lightDir, ent->e.axis[0] ); - ent->lightDir[1] = DotProduct( lightDir, ent->e.axis[1] ); - ent->lightDir[2] = DotProduct( lightDir, ent->e.axis[2] ); + VectorNormalize(lightDir); + ent->lightDir[0] = DotProduct(lightDir, ent->e.axis[0]); + ent->lightDir[1] = DotProduct(lightDir, ent->e.axis[1]); + ent->lightDir[2] = DotProduct(lightDir, ent->e.axis[2]); } /* @@ -416,16 +394,15 @@ void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { R_LightForPoint ================= */ -int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) -{ +int R_LightForPoint(vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir) { trRefEntity_t ent; - if ( tr.world->lightGridData == NULL ) + if (tr.world->lightGridData == NULL) return qfalse; memset(&ent, 0, sizeof(ent)); - VectorCopy( point, ent.e.origin ); - R_SetupEntityLightingGrid( &ent ); + VectorCopy(point, ent.e.origin); + R_SetupEntityLightingGrid(&ent); VectorCopy(ent.ambientLight, ambientLight); VectorCopy(ent.directedLight, directedLight); VectorCopy(ent.lightDir, lightDir); diff --git a/codemp/rd-vanilla/tr_main.cpp b/codemp/rd-vanilla/tr_main.cpp index d649836c23..a55a77e543 100644 --- a/codemp/rd-vanilla/tr_main.cpp +++ b/codemp/rd-vanilla/tr_main.cpp @@ -25,22 +25,18 @@ along with this program; if not, see . #include "tr_local.h" #include "ghoul2/g2_local.h" -trGlobals_t tr; +trGlobals_t tr; -static float s_flipMatrix[16] = { +static float s_flipMatrix[16] = { // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - 0, 0, -1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -}; + 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}; -refimport_t ri; +refimport_t ri; // entities that will have procedurally generated surfaces will just // point at this for their sorting surface -surfaceType_t entitySurface = SF_ENTITY; +surfaceType_t entitySurface = SF_ENTITY; /* ================= @@ -49,110 +45,103 @@ R_CullLocalBox Returns CULL_IN, CULL_CLIP, or CULL_OUT ================= */ -int R_CullLocalBox (const vec3_t bounds[2]) { - int i, j; - vec3_t transformed[8]; - float dists[8]; - vec3_t v; - cplane_t *frust; - int anyBack; - int front, back; - - if ( r_nocull->integer==1 ) { +int R_CullLocalBox(const vec3_t bounds[2]) { + int i, j; + vec3_t transformed[8]; + float dists[8]; + vec3_t v; + cplane_t *frust; + int anyBack; + int front, back; + + if (r_nocull->integer == 1) { return CULL_CLIP; } // transform into world space - for (i = 0 ; i < 8 ; i++) { - v[0] = bounds[i&1][0]; - v[1] = bounds[(i>>1)&1][1]; - v[2] = bounds[(i>>2)&1][2]; - - VectorCopy( tr.ori.origin, transformed[i] ); - VectorMA( transformed[i], v[0], tr.ori.axis[0], transformed[i] ); - VectorMA( transformed[i], v[1], tr.ori.axis[1], transformed[i] ); - VectorMA( transformed[i], v[2], tr.ori.axis[2], transformed[i] ); + for (i = 0; i < 8; i++) { + v[0] = bounds[i & 1][0]; + v[1] = bounds[(i >> 1) & 1][1]; + v[2] = bounds[(i >> 2) & 1][2]; + + VectorCopy(tr.ori.origin, transformed[i]); + VectorMA(transformed[i], v[0], tr.ori.axis[0], transformed[i]); + VectorMA(transformed[i], v[1], tr.ori.axis[1], transformed[i]); + VectorMA(transformed[i], v[2], tr.ori.axis[2], transformed[i]); } // check against frustum planes anyBack = 0; - for (i = 0 ; i < 4 ; i++) { + for (i = 0; i < 4; i++) { frust = &tr.viewParms.frustum[i]; front = back = 0; - for (j = 0 ; j < 8 ; j++) { + for (j = 0; j < 8; j++) { dists[j] = DotProduct(transformed[j], frust->normal); - if ( dists[j] > frust->dist ) { + if (dists[j] > frust->dist) { front = 1; - if ( back ) { - break; // a point is in front + if (back) { + break; // a point is in front } } else { back = 1; } } - if ( !front ) { + if (!front) { // all points were behind one of the planes return CULL_OUT; } anyBack |= back; } - if ( !anyBack ) { - return CULL_IN; // completely inside frustum + if (!anyBack) { + return CULL_IN; // completely inside frustum } - return CULL_CLIP; // partially clipped + return CULL_CLIP; // partially clipped } /* ** R_CullLocalPointAndRadius */ -int R_CullLocalPointAndRadius( const vec3_t pt, float radius ) -{ +int R_CullLocalPointAndRadius(const vec3_t pt, float radius) { vec3_t transformed; - R_LocalPointToWorld( pt, transformed ); + R_LocalPointToWorld(pt, transformed); - return R_CullPointAndRadius( transformed, radius ); + return R_CullPointAndRadius(transformed, radius); } /* ** R_CullPointAndRadius */ -int R_CullPointAndRadius( const vec3_t pt, float radius ) -{ - int i; - float dist; - cplane_t *frust; +int R_CullPointAndRadius(const vec3_t pt, float radius) { + int i; + float dist; + cplane_t *frust; qboolean mightBeClipped = qfalse; - if ( r_nocull->integer==1 ) { + if (r_nocull->integer == 1) { return CULL_CLIP; } // check against frustum planes - for (i = 0 ; i < 4 ; i++) - { + for (i = 0; i < 4; i++) { frust = &tr.viewParms.frustum[i]; - dist = DotProduct( pt, frust->normal) - frust->dist; - if ( dist < -radius ) - { + dist = DotProduct(pt, frust->normal) - frust->dist; + if (dist < -radius) { return CULL_OUT; - } - else if ( dist <= radius ) - { + } else if (dist <= radius) { mightBeClipped = qtrue; } } - if ( mightBeClipped ) - { + if (mightBeClipped) { return CULL_CLIP; } - return CULL_IN; // completely inside frustum + return CULL_IN; // completely inside frustum } /* @@ -161,7 +150,7 @@ R_LocalNormalToWorld ================= */ -void R_LocalNormalToWorld (const vec3_t local, vec3_t world) { +void R_LocalNormalToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2]; @@ -173,7 +162,7 @@ R_LocalPointToWorld ================= */ -void R_LocalPointToWorld (const vec3_t local, vec3_t world) { +void R_LocalPointToWorld(const vec3_t local, vec3_t world) { world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0] + tr.ori.origin[0]; world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1] + tr.ori.origin[1]; world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2] + tr.ori.origin[2]; @@ -187,8 +176,7 @@ R_WorldNormalToEntity ================= */ -void R_WorldNormalToEntity (const vec3_t worldvec, vec3_t entvec) -{ +void R_WorldNormalToEntity(const vec3_t worldvec, vec3_t entvec) { entvec[0] = -worldvec[0] * preTransEntMatrix[0] - worldvec[1] * preTransEntMatrix[4] + worldvec[2] * preTransEntMatrix[8]; entvec[1] = -worldvec[0] * preTransEntMatrix[1] - worldvec[1] * preTransEntMatrix[5] + worldvec[2] * preTransEntMatrix[9]; entvec[2] = -worldvec[0] * preTransEntMatrix[2] - worldvec[1] * preTransEntMatrix[6] + worldvec[2] * preTransEntMatrix[10]; @@ -214,7 +202,7 @@ R_WorldToLocal ================= */ -void R_WorldToLocal (vec3_t world, vec3_t local) { +void R_WorldToLocal(vec3_t world, vec3_t local) { local[0] = DotProduct(world, tr.ori.axis[0]); local[1] = DotProduct(world, tr.ori.axis[1]); local[2] = DotProduct(world, tr.ori.axis[2]); @@ -226,24 +214,16 @@ R_TransformModelToClip ========================== */ -void R_TransformModelToClip( const vec3_t src, const float *modelMatrix, const float *projectionMatrix, - vec4_t eye, vec4_t dst ) { +void R_TransformModelToClip(const vec3_t src, const float *modelMatrix, const float *projectionMatrix, vec4_t eye, vec4_t dst) { int i; - for ( i = 0 ; i < 4 ; i++ ) { - eye[i] = - src[0] * modelMatrix[ i + 0 * 4 ] + - src[1] * modelMatrix[ i + 1 * 4 ] + - src[2] * modelMatrix[ i + 2 * 4 ] + - 1 * modelMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + eye[i] = src[0] * modelMatrix[i + 0 * 4] + src[1] * modelMatrix[i + 1 * 4] + src[2] * modelMatrix[i + 2 * 4] + 1 * modelMatrix[i + 3 * 4]; } - for ( i = 0 ; i < 4 ; i++ ) { - dst[i] = - eye[0] * projectionMatrix[ i + 0 * 4 ] + - eye[1] * projectionMatrix[ i + 1 * 4 ] + - eye[2] * projectionMatrix[ i + 2 * 4 ] + - eye[3] * projectionMatrix[ i + 3 * 4 ]; + for (i = 0; i < 4; i++) { + dst[i] = eye[0] * projectionMatrix[i + 0 * 4] + eye[1] * projectionMatrix[i + 1 * 4] + eye[2] * projectionMatrix[i + 2 * 4] + + eye[3] * projectionMatrix[i + 3 * 4]; } } @@ -253,36 +233,31 @@ R_TransformClipToWindow ========================== */ -void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ) { +void R_TransformClipToWindow(const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window) { normalized[0] = clip[0] / clip[3]; normalized[1] = clip[1] / clip[3]; - normalized[2] = ( clip[2] + clip[3] ) / ( 2 * clip[3] ); + normalized[2] = (clip[2] + clip[3]) / (2 * clip[3]); - window[0] = 0.5f * ( 1.0f + normalized[0] ) * view->viewportWidth; - window[1] = 0.5f * ( 1.0f + normalized[1] ) * view->viewportHeight; + window[0] = 0.5f * (1.0f + normalized[0]) * view->viewportWidth; + window[1] = 0.5f * (1.0f + normalized[1]) * view->viewportHeight; window[2] = normalized[2]; - window[0] = (int) ( window[0] + 0.5 ); - window[1] = (int) ( window[1] + 0.5 ); + window[0] = (int)(window[0] + 0.5); + window[1] = (int)(window[1] + 0.5); } - /* ========================== myGlMultMatrix ========================== */ -void myGlMultMatrix( const float *a, const float *b, float *out ) { - int i, j; - - for ( i = 0 ; i < 4 ; i++ ) { - for ( j = 0 ; j < 4 ; j++ ) { - out[ i * 4 + j ] = - a [ i * 4 + 0 ] * b [ 0 * 4 + j ] - + a [ i * 4 + 1 ] * b [ 1 * 4 + j ] - + a [ i * 4 + 2 ] * b [ 2 * 4 + j ] - + a [ i * 4 + 3 ] * b [ 3 * 4 + j ]; +void myGlMultMatrix(const float *a, const float *b, float *out) { + int i, j; + + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + out[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] + a[i * 4 + 1] * b[1 * 4 + j] + a[i * 4 + 2] * b[2 * 4 + j] + a[i * 4 + 3] * b[3 * 4 + j]; } } } @@ -296,22 +271,21 @@ Does NOT produce any GL calls Called by both the front end and the back end ================= */ -void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, - orientationr_t *ori ) { -// float glMatrix[16]; - vec3_t delta; - float axisLength; +void R_RotateForEntity(const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *ori) { + // float glMatrix[16]; + vec3_t delta; + float axisLength; - if ( ent->e.reType != RT_MODEL ) { + if (ent->e.reType != RT_MODEL) { *ori = viewParms->world; return; } - VectorCopy( ent->e.origin, ori->origin ); + VectorCopy(ent->e.origin, ori->origin); - VectorCopy( ent->e.axis[0], ori->axis[0] ); - VectorCopy( ent->e.axis[1], ori->axis[1] ); - VectorCopy( ent->e.axis[2], ori->axis[2] ); + VectorCopy(ent->e.axis[0], ori->axis[0]); + VectorCopy(ent->e.axis[1], ori->axis[1]); + VectorCopy(ent->e.axis[2], ori->axis[2]); preTransEntMatrix[0] = ori->axis[0][0]; preTransEntMatrix[4] = ori->axis[1][0]; @@ -333,16 +307,16 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, preTransEntMatrix[11] = 0; preTransEntMatrix[15] = 1; - myGlMultMatrix( preTransEntMatrix, viewParms->world.modelMatrix, ori->modelMatrix ); + myGlMultMatrix(preTransEntMatrix, viewParms->world.modelMatrix, ori->modelMatrix); // calculate the viewer origin in the model's space // needed for fog, specular, and environment mapping - VectorSubtract( viewParms->ori.origin, ori->origin, delta ); + VectorSubtract(viewParms->ori.origin, ori->origin, delta); // compensate for scale in the axes if necessary - if ( ent->e.nonNormalizedAxes ) { - axisLength = VectorLength( ent->e.axis[0] ); - if ( !axisLength ) { + if (ent->e.nonNormalizedAxes) { + axisLength = VectorLength(ent->e.axis[0]); + if (!axisLength) { axisLength = 0; } else { axisLength = 1.0f / axisLength; @@ -351,9 +325,9 @@ void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, axisLength = 1.0f; } - ori->viewOrigin[0] = DotProduct( delta, ori->axis[0] ) * axisLength; - ori->viewOrigin[1] = DotProduct( delta, ori->axis[1] ) * axisLength; - ori->viewOrigin[2] = DotProduct( delta, ori->axis[2] ) * axisLength; + ori->viewOrigin[0] = DotProduct(delta, ori->axis[0]) * axisLength; + ori->viewOrigin[1] = DotProduct(delta, ori->axis[1]) * axisLength; + ori->viewOrigin[2] = DotProduct(delta, ori->axis[2]) * axisLength; } /* @@ -363,19 +337,18 @@ R_RotateForViewer Sets up the modelview matrix for a given viewParm ================= */ -void R_RotateForViewer (void) -{ - float viewerMatrix[16]; - vec3_t origin; +void R_RotateForViewer(void) { + float viewerMatrix[16]; + vec3_t origin; - memset (&tr.ori, 0, sizeof(tr.ori)); + memset(&tr.ori, 0, sizeof(tr.ori)); tr.ori.axis[0][0] = 1; tr.ori.axis[1][1] = 1; tr.ori.axis[2][2] = 1; - VectorCopy (tr.viewParms.ori.origin, tr.ori.viewOrigin); + VectorCopy(tr.viewParms.ori.origin, tr.ori.viewOrigin); // transform by the camera placement - VectorCopy( tr.viewParms.ori.origin, origin ); + VectorCopy(tr.viewParms.ori.origin, origin); viewerMatrix[0] = tr.viewParms.ori.axis[0][0]; viewerMatrix[4] = tr.viewParms.ori.axis[0][1]; @@ -399,29 +372,24 @@ void R_RotateForViewer (void) // convert from our coordinate system (looking down X) // to OpenGL's coordinate system (looking down -Z) - myGlMultMatrix( viewerMatrix, s_flipMatrix, tr.ori.modelMatrix ); + myGlMultMatrix(viewerMatrix, s_flipMatrix, tr.ori.modelMatrix); tr.viewParms.world = tr.ori; - } /* ** SetFarClip */ -static void SetFarClip( void ) -{ - float farthestCornerDistance = 0; - int i; +static void SetFarClip(void) { + float farthestCornerDistance = 0; + int i; // if not rendering the world (icons, menus, etc) // set a 2k far clip plane - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { - if (tr.refdef.rdflags & RDF_AUTOMAP) - { //override the zfar then + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { + if (tr.refdef.rdflags & RDF_AUTOMAP) { // override the zfar then tr.viewParms.zFar = 32768.0f; - } - else - { + } else { tr.viewParms.zFar = 2048.0f; } return; @@ -430,49 +398,38 @@ static void SetFarClip( void ) // // set far clipping planes dynamically // - for ( i = 0; i < 8; i++ ) - { + for (i = 0; i < 8; i++) { vec3_t v; float distance; - if ( i & 1 ) - { + if (i & 1) { v[0] = tr.viewParms.visBounds[0][0]; - } - else - { + } else { v[0] = tr.viewParms.visBounds[1][0]; } - if ( i & 2 ) - { + if (i & 2) { v[1] = tr.viewParms.visBounds[0][1]; - } - else - { + } else { v[1] = tr.viewParms.visBounds[1][1]; } - if ( i & 4 ) - { + if (i & 4) { v[2] = tr.viewParms.visBounds[0][2]; - } - else - { + } else { v[2] = tr.viewParms.visBounds[1][2]; } distance = DistanceSquared(tr.viewParms.ori.origin, v); - if ( distance > farthestCornerDistance ) - { + if (distance > farthestCornerDistance) { farthestCornerDistance = distance; } } // Bring in the zFar to the distanceCull distance // The sky renders at zFar so need to move it out a little // ...and make sure there is a minimum zfar to prevent problems - tr.viewParms.zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf( farthestCornerDistance )); + tr.viewParms.zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf(farthestCornerDistance)); /* if (r_shadows->integer == 2) @@ -482,16 +439,15 @@ static void SetFarClip( void ) */ } - /* =============== R_SetupProjection =============== */ -void R_SetupProjection( void ) { - float xmin, xmax, ymin, ymax; - float width, height, depth; - float zNear, zFar; +void R_SetupProjection(void) { + float xmin, xmax, ymin, ymax; + float width, height, depth; + float zNear, zFar; // dynamically compute far clip plane distance SetFarClip(); @@ -499,13 +455,13 @@ void R_SetupProjection( void ) { // // set up projection matrix // - zNear = r_znear->value; - zFar = tr.viewParms.zFar; + zNear = r_znear->value; + zFar = tr.viewParms.zFar; - ymax = zNear * tan( tr.refdef.fov_y * M_PI / 360.0f ); + ymax = zNear * tan(tr.refdef.fov_y * M_PI / 360.0f); ymin = -ymax; - xmax = zNear * tan( tr.refdef.fov_x * M_PI / 360.0f ); + xmax = zNear * tan(tr.refdef.fov_x * M_PI / 360.0f); xmin = -xmax; width = xmax - xmin; @@ -514,17 +470,17 @@ void R_SetupProjection( void ) { tr.viewParms.projectionMatrix[0] = 2 * zNear / width; tr.viewParms.projectionMatrix[4] = 0; - tr.viewParms.projectionMatrix[8] = ( xmax + xmin ) / width; // normally 0 + tr.viewParms.projectionMatrix[8] = (xmax + xmin) / width; // normally 0 tr.viewParms.projectionMatrix[12] = 0; tr.viewParms.projectionMatrix[1] = 0; tr.viewParms.projectionMatrix[5] = 2 * zNear / height; - tr.viewParms.projectionMatrix[9] = ( ymax + ymin ) / height; // normally 0 + tr.viewParms.projectionMatrix[9] = (ymax + ymin) / height; // normally 0 tr.viewParms.projectionMatrix[13] = 0; tr.viewParms.projectionMatrix[2] = 0; tr.viewParms.projectionMatrix[6] = 0; - tr.viewParms.projectionMatrix[10] = -( zFar + zNear ) / depth; + tr.viewParms.projectionMatrix[10] = -(zFar + zNear) / depth; tr.viewParms.projectionMatrix[14] = -2 * zFar * zNear / depth; tr.viewParms.projectionMatrix[3] = 0; @@ -540,86 +496,84 @@ R_SetupFrustum Setup that culling frustum planes for the current view ================= */ -void R_SetupFrustum (void) { - int i; - float xs, xc; - float ang; +void R_SetupFrustum(void) { + int i; + float xs, xc; + float ang; ang = tr.viewParms.fovX / 180 * M_PI * 0.5f; - xs = sin( ang ); - xc = cos( ang ); + xs = sin(ang); + xc = cos(ang); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[0].normal ); - VectorMA( tr.viewParms.frustum[0].normal, xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[0].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[0].normal); + VectorMA(tr.viewParms.frustum[0].normal, xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[0].normal); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[1].normal ); - VectorMA( tr.viewParms.frustum[1].normal, -xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[1].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[1].normal); + VectorMA(tr.viewParms.frustum[1].normal, -xc, tr.viewParms.ori.axis[1], tr.viewParms.frustum[1].normal); ang = tr.viewParms.fovY / 180 * M_PI * 0.5f; - xs = sin( ang ); - xc = cos( ang ); + xs = sin(ang); + xc = cos(ang); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[2].normal ); - VectorMA( tr.viewParms.frustum[2].normal, xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[2].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[2].normal); + VectorMA(tr.viewParms.frustum[2].normal, xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[2].normal); - VectorScale( tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[3].normal ); - VectorMA( tr.viewParms.frustum[3].normal, -xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[3].normal ); + VectorScale(tr.viewParms.ori.axis[0], xs, tr.viewParms.frustum[3].normal); + VectorMA(tr.viewParms.frustum[3].normal, -xc, tr.viewParms.ori.axis[2], tr.viewParms.frustum[3].normal); - for (i=0 ; i<4 ; i++) { + for (i = 0; i < 4; i++) { tr.viewParms.frustum[i].type = PLANE_NON_AXIAL; - tr.viewParms.frustum[i].dist = DotProduct (tr.viewParms.ori.origin, tr.viewParms.frustum[i].normal); - SetPlaneSignbits( &tr.viewParms.frustum[i] ); + tr.viewParms.frustum[i].dist = DotProduct(tr.viewParms.ori.origin, tr.viewParms.frustum[i].normal); + SetPlaneSignbits(&tr.viewParms.frustum[i]); } } - /* ================= R_MirrorPoint ================= */ -void R_MirrorPoint (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - vec3_t local; - vec3_t transformed; - float d; +void R_MirrorPoint(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + vec3_t local; + vec3_t transformed; + float d; - VectorSubtract( in, surface->origin, local ); + VectorSubtract(in, surface->origin, local); - VectorClear( transformed ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(transformed); + for (i = 0; i < 3; i++) { d = DotProduct(local, surface->axis[i]); - VectorMA( transformed, d, camera->axis[i], transformed ); + VectorMA(transformed, d, camera->axis[i], transformed); } - VectorAdd( transformed, camera->origin, out ); + VectorAdd(transformed, camera->origin, out); } -void R_MirrorVector (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { - int i; - float d; +void R_MirrorVector(vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + float d; - VectorClear( out ); - for ( i = 0 ; i < 3 ; i++ ) { + VectorClear(out); + for (i = 0; i < 3; i++) { d = DotProduct(in, surface->axis[i]); - VectorMA( out, d, camera->axis[i], out ); + VectorMA(out, d, camera->axis[i], out); } } - /* ============= R_PlaneForSurface ============= */ -void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { - srfTriangles_t *tri; - srfPoly_t *poly; - drawVert_t *v1, *v2, *v3; - vec4_t plane4; +void R_PlaneForSurface(surfaceType_t *surfType, cplane_t *plane) { + srfTriangles_t *tri; + srfPoly_t *poly; + drawVert_t *v1, *v2, *v3; + vec4_t plane4; if (!surfType) { - memset (plane, 0, sizeof(*plane)); + memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -632,18 +586,18 @@ void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { v1 = tri->verts + tri->indexes[0]; v2 = tri->verts + tri->indexes[1]; v3 = tri->verts + tri->indexes[2]; - PlaneFromPoints( plane4, v1->xyz, v2->xyz, v3->xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, v1->xyz, v2->xyz, v3->xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; case SF_POLY: poly = (srfPoly_t *)surfType; - PlaneFromPoints( plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz ); - VectorCopy( plane4, plane->normal ); + PlaneFromPoints(plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz); + VectorCopy(plane4, plane->normal); plane->dist = plane4[3]; return; default: - memset (plane, 0, sizeof(*plane)); + memset(plane, 0, sizeof(*plane)); plane->normal[0] = 1; return; } @@ -659,67 +613,63 @@ be moving and rotating. Returns qtrue if it should be mirrored ================= */ -qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, - orientation_t *surface, orientation_t *camera, - vec3_t pvsOrigin, qboolean *mirror ) { - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; - vec3_t transformed; +qboolean R_GetPortalOrientations(drawSurf_t *drawSurf, int entityNum, orientation_t *surface, orientation_t *camera, vec3_t pvsOrigin, qboolean *mirror) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; + vec3_t transformed; // create plane axis for the portal we are seeing - R_PlaneForSurface( drawSurf->surface, &originalPlane ); + R_PlaneForSurface(drawSurf->surface, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) { + if (entityNum != REFENTITYNUM_WORLD) { tr.currentEntityNum = entityNum; tr.currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(tr.currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); } else { plane = originalPlane; } - VectorCopy( plane.normal, surface->axis[0] ); - PerpendicularVector( surface->axis[1], surface->axis[0] ); - CrossProduct( surface->axis[0], surface->axis[1], surface->axis[2] ); + VectorCopy(plane.normal, surface->axis[0]); + PerpendicularVector(surface->axis[1], surface->axis[0]); + CrossProduct(surface->axis[0], surface->axis[1], surface->axis[2]); // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // get the pvsOrigin from the entity - VectorCopy( e->e.oldorigin, pvsOrigin ); + VectorCopy(e->e.oldorigin, pvsOrigin); // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) { - VectorScale( plane.normal, plane.dist, surface->origin ); - VectorCopy( surface->origin, camera->origin ); - VectorSubtract( vec3_origin, surface->axis[0], camera->axis[0] ); - VectorCopy( surface->axis[1], camera->axis[1] ); - VectorCopy( surface->axis[2], camera->axis[2] ); + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { + VectorScale(plane.normal, plane.dist, surface->origin); + VectorCopy(surface->origin, camera->origin); + VectorSubtract(vec3_origin, surface->axis[0], camera->axis[0]); + VectorCopy(surface->axis[1], camera->axis[1]); + VectorCopy(surface->axis[2], camera->axis[2]); *mirror = qtrue; return qtrue; @@ -727,38 +677,37 @@ qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, // project the origin onto the surface plane to get // an origin point we can rotate around - d = DotProduct( e->e.origin, plane.normal ) - plane.dist; - VectorMA( e->e.origin, -d, surface->axis[0], surface->origin ); + d = DotProduct(e->e.origin, plane.normal) - plane.dist; + VectorMA(e->e.origin, -d, surface->axis[0], surface->origin); // now get the camera origin and orientation - VectorCopy( e->e.oldorigin, camera->origin ); - AxisCopy( e->e.axis, camera->axis ); - VectorSubtract( vec3_origin, camera->axis[0], camera->axis[0] ); - VectorSubtract( vec3_origin, camera->axis[1], camera->axis[1] ); + VectorCopy(e->e.oldorigin, camera->origin); + AxisCopy(e->e.axis, camera->axis); + VectorSubtract(vec3_origin, camera->axis[0], camera->axis[0]); + VectorSubtract(vec3_origin, camera->axis[1], camera->axis[1]); // optionally rotate - if ( e->e.oldframe ) { + if (e->e.oldframe) { // if a speed is specified - if ( e->e.frame ) { + if (e->e.frame) { // continuous rotate - d = (tr.refdef.time/1000.0f) * e->e.frame; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + d = (tr.refdef.time / 1000.0f) * e->e.frame; + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } else { // bobbing rotate, with skinNum being the rotation offset - d = sin( tr.refdef.time * 0.003f ); + d = sin(tr.refdef.time * 0.003f); d = e->e.skinNum + d * 4; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } - } - else if ( e->e.skinNum ) { + } else if (e->e.skinNum) { d = e->e.skinNum; - VectorCopy( camera->axis[1], transformed ); - RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); - CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + VectorCopy(camera->axis[1], transformed); + RotatePointAroundVector(camera->axis[1], camera->axis[0], transformed, d); + CrossProduct(camera->axis[0], camera->axis[1], camera->axis[2]); } *mirror = qfalse; return qtrue; @@ -773,63 +722,55 @@ qboolean R_GetPortalOrientations( drawSurf_t *drawSurf, int entityNum, // to see a surface before the server has communicated the matching // portal surface entity, so we don't want to print anything here... - //ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); + // ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); return qfalse; } -static qboolean IsMirror( const drawSurf_t *drawSurf, int entityNum ) -{ - int i; - cplane_t originalPlane, plane; - trRefEntity_t *e; - float d; +static qboolean IsMirror(const drawSurf_t *drawSurf, int entityNum) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; // create plane axis for the portal we are seeing - R_PlaneForSurface( drawSurf->surface, &originalPlane ); + R_PlaneForSurface(drawSurf->surface, &originalPlane); // rotate the plane if necessary - if ( entityNum != REFENTITYNUM_WORLD ) - { + if (entityNum != REFENTITYNUM_WORLD) { tr.currentEntityNum = entityNum; tr.currentEntity = &tr.refdef.entities[entityNum]; // get the orientation of the entity - R_RotateForEntity( tr.currentEntity, &tr.viewParms, &tr.ori ); + R_RotateForEntity(tr.currentEntity, &tr.viewParms, &tr.ori); // rotate the plane, but keep the non-rotated version for matching // against the portalSurface entities - R_LocalNormalToWorld( originalPlane.normal, plane.normal ); - plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + R_LocalNormalToWorld(originalPlane.normal, plane.normal); + plane.dist = originalPlane.dist + DotProduct(plane.normal, tr.ori.origin); // translate the original plane - originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); - } - else - { + originalPlane.dist = originalPlane.dist + DotProduct(originalPlane.normal, tr.ori.origin); + } else { plane = originalPlane; } // locate the portal entity closest to this plane. // origin will be the origin of the portal, origin2 will be // the origin of the camera - for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) - { + for (i = 0; i < tr.refdef.num_entities; i++) { e = &tr.refdef.entities[i]; - if ( e->e.reType != RT_PORTALSURFACE ) { + if (e->e.reType != RT_PORTALSURFACE) { continue; } - d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; - if ( d > 64 || d < -64) { + d = DotProduct(e->e.origin, originalPlane.normal) - originalPlane.dist; + if (d > 64 || d < -64) { continue; } // if the entity is just a mirror, don't use as a camera point - if ( e->e.oldorigin[0] == e->e.origin[0] && - e->e.oldorigin[1] == e->e.origin[1] && - e->e.oldorigin[2] == e->e.origin[2] ) - { + if (e->e.oldorigin[0] == e->e.origin[0] && e->e.oldorigin[1] == e->e.origin[1] && e->e.oldorigin[2] == e->e.origin[2]) { return qtrue; } @@ -843,12 +784,12 @@ static qboolean IsMirror( const drawSurf_t *drawSurf, int entityNum ) ** ** Determines if a surface is completely offscreen. */ -static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128] ) { +static qboolean SurfIsOffscreen(const drawSurf_t *drawSurf, vec4_t clipDest[128]) { float shortest = 100000000; int entityNum; int numTriangles; shader_t *shader; - int fogNum; + int fogNum; int dlighted; vec4_t clip, eye; int i; @@ -857,26 +798,21 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 R_RotateForViewer(); - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted ); - RB_BeginSurface( shader, fogNum ); - rb_surfaceTable[ *drawSurf->surface ]( drawSurf->surface ); - assert( tess.numVertexes < 128 ); - for ( i = 0; i < tess.numVertexes; i++ ) - { + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &fogNum, &dlighted); + RB_BeginSurface(shader, fogNum); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); + assert(tess.numVertexes < 128); + for (i = 0; i < tess.numVertexes; i++) { int j; unsigned int pointFlags = 0; - R_TransformModelToClip( tess.xyz[i], tr.ori.modelMatrix, tr.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(tess.xyz[i], tr.ori.modelMatrix, tr.viewParms.projectionMatrix, eye, clip); - for ( j = 0; j < 3; j++ ) - { - if ( clip[j] >= clip[3] ) - { - pointFlags |= (1 << (j*2)); - } - else if ( clip[j] <= -clip[3] ) - { - pointFlags |= ( 1 << (j*2+1)); + for (j = 0; j < 3; j++) { + if (clip[j] >= clip[3]) { + pointFlags |= (1 << (j * 2)); + } else if (clip[j] <= -clip[3]) { + pointFlags |= (1 << (j * 2 + 1)); } } pointAnd &= pointFlags; @@ -884,8 +820,7 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 } // trivially reject - if ( pointAnd ) - { + if (pointAnd) { return qtrue; } @@ -896,39 +831,33 @@ static qboolean SurfIsOffscreen( const drawSurf_t *drawSurf, vec4_t clipDest[128 // we have in the game right now. numTriangles = tess.numIndexes / 3; - for ( i = 0; i < tess.numIndexes; i += 3 ) - { + for (i = 0; i < tess.numIndexes; i += 3) { vec3_t normal; float dot; float len; - VectorSubtract( tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal ); + VectorSubtract(tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal); - len = VectorLengthSquared( normal ); // lose the sqrt - if ( len < shortest ) - { + len = VectorLengthSquared(normal); // lose the sqrt + if (len < shortest) { shortest = len; } - if ( ( dot = DotProduct( normal, tess.normal[tess.indexes[i]] ) ) >= 0 ) - { + if ((dot = DotProduct(normal, tess.normal[tess.indexes[i]])) >= 0) { numTriangles--; } } - if ( !numTriangles ) - { + if (!numTriangles) { return qtrue; } // mirrors can early out at this point, since we don't do a fade over distance // with them (although we could) - if ( IsMirror( drawSurf, entityNum ) ) - { + if (IsMirror(drawSurf, entityNum)) { return qfalse; } - if ( shortest > (tess.shader->portalRange*tess.shader->portalRange) ) - { + if (shortest > (tess.shader->portalRange * tess.shader->portalRange)) { return qtrue; } @@ -942,24 +871,24 @@ R_MirrorViewBySurface Returns qtrue if another view has been rendered ======================== */ -qboolean R_MirrorViewBySurface (drawSurf_t *drawSurf, int entityNum) { - vec4_t clipDest[128]; - viewParms_t newParms; - viewParms_t oldParms; - orientation_t surface, camera; +qboolean R_MirrorViewBySurface(drawSurf_t *drawSurf, int entityNum) { + vec4_t clipDest[128]; + viewParms_t newParms; + viewParms_t oldParms; + orientation_t surface, camera; // don't recursively mirror if (tr.viewParms.isPortal) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "WARNING: recursive mirror/portal found\n" ); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "WARNING: recursive mirror/portal found\n"); return qfalse; } - if ( r_noportals->integer || (r_fastsky->integer == 1) ) { + if (r_noportals->integer || (r_fastsky->integer == 1)) { return qfalse; } // trivially reject portal/mirror - if ( SurfIsOffscreen( drawSurf, clipDest ) ) { + if (SurfIsOffscreen(drawSurf, clipDest)) { return qfalse; } @@ -968,24 +897,23 @@ qboolean R_MirrorViewBySurface (drawSurf_t *drawSurf, int entityNum) { newParms = tr.viewParms; newParms.isPortal = qtrue; - if ( !R_GetPortalOrientations( drawSurf, entityNum, &surface, &camera, - newParms.pvsOrigin, &newParms.isMirror ) ) { - return qfalse; // bad portal, no portalentity + if (!R_GetPortalOrientations(drawSurf, entityNum, &surface, &camera, newParms.pvsOrigin, &newParms.isMirror)) { + return qfalse; // bad portal, no portalentity } - R_MirrorPoint (oldParms.ori.origin, &surface, &camera, newParms.ori.origin ); + R_MirrorPoint(oldParms.ori.origin, &surface, &camera, newParms.ori.origin); - VectorSubtract( vec3_origin, camera.axis[0], newParms.portalPlane.normal ); - newParms.portalPlane.dist = DotProduct( camera.origin, newParms.portalPlane.normal ); + VectorSubtract(vec3_origin, camera.axis[0], newParms.portalPlane.normal); + newParms.portalPlane.dist = DotProduct(camera.origin, newParms.portalPlane.normal); - R_MirrorVector (oldParms.ori.axis[0], &surface, &camera, newParms.ori.axis[0]); - R_MirrorVector (oldParms.ori.axis[1], &surface, &camera, newParms.ori.axis[1]); - R_MirrorVector (oldParms.ori.axis[2], &surface, &camera, newParms.ori.axis[2]); + R_MirrorVector(oldParms.ori.axis[0], &surface, &camera, newParms.ori.axis[0]); + R_MirrorVector(oldParms.ori.axis[1], &surface, &camera, newParms.ori.axis[1]); + R_MirrorVector(oldParms.ori.axis[2], &surface, &camera, newParms.ori.axis[2]); // OPTIMIZE: restrict the viewport on the mirrored view // render the mirror view - R_RenderView (&newParms); + R_RenderView(&newParms); tr.viewParms = oldParms; @@ -999,25 +927,25 @@ R_SpriteFogNum See if a sprite is inside a fog volume ================= */ -int R_SpriteFogNum( trRefEntity_t *ent ) { - int i, j; - fog_t *fog; +int R_SpriteFogNum(trRefEntity_t *ent) { + int i, j; + fog_t *fog; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j]) { break; } - if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + if (ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -1038,27 +966,26 @@ DRAWSURF SORTING R_Radix =============== */ -static QINLINE void R_Radix( int byte, int size, drawSurf_t *source, drawSurf_t *dest ) -{ - int count[ 256 ] = { 0 }; - int index[ 256 ]; - int i; - unsigned char *sortKey = NULL; - unsigned char *end = NULL; +static QINLINE void R_Radix(int byte, int size, drawSurf_t *source, drawSurf_t *dest) { + int count[256] = {0}; + int index[256]; + int i; + unsigned char *sortKey = NULL; + unsigned char *end = NULL; - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - end = sortKey + ( size * sizeof( drawSurf_t ) ); - for( ; sortKey < end; sortKey += sizeof( drawSurf_t ) ) - ++count[ *sortKey ]; + sortKey = ((unsigned char *)&source[0].sort) + byte; + end = sortKey + (size * sizeof(drawSurf_t)); + for (; sortKey < end; sortKey += sizeof(drawSurf_t)) + ++count[*sortKey]; - index[ 0 ] = 0; + index[0] = 0; - for( i = 1; i < 256; ++i ) - index[ i ] = index[ i - 1 ] + count[ i - 1 ]; + for (i = 1; i < 256; ++i) + index[i] = index[i - 1] + count[i - 1]; - sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; - for( i = 0; i < size; ++i, sortKey += sizeof( drawSurf_t ) ) - dest[ index[ *sortKey ]++ ] = source[ i ]; + sortKey = ((unsigned char *)&source[0].sort) + byte; + for (i = 0; i < size; ++i, sortKey += sizeof(drawSurf_t)) + dest[index[*sortKey]++] = source[i]; } /* @@ -1068,20 +995,19 @@ R_RadixSort Radix sort with 4 byte size buckets =============== */ -static void R_RadixSort( drawSurf_t *source, int size ) -{ - static drawSurf_t scratch[ MAX_DRAWSURFS ]; +static void R_RadixSort(drawSurf_t *source, int size) { + static drawSurf_t scratch[MAX_DRAWSURFS]; #ifdef Q3_LITTLE_ENDIAN - R_Radix( 0, size, source, scratch ); - R_Radix( 1, size, scratch, source ); - R_Radix( 2, size, source, scratch ); - R_Radix( 3, size, scratch, source ); + R_Radix(0, size, source, scratch); + R_Radix(1, size, scratch, source); + R_Radix(2, size, source, scratch); + R_Radix(3, size, scratch, source); #else - R_Radix( 3, size, source, scratch ); - R_Radix( 2, size, scratch, source ); - R_Radix( 1, size, source, scratch ); - R_Radix( 0, size, scratch, source ); -#endif //Q3_LITTLE_ENDIAN + R_Radix(3, size, source, scratch); + R_Radix(2, size, scratch, source); + R_Radix(1, size, source, scratch); + R_Radix(0, size, scratch, source); +#endif // Q3_LITTLE_ENDIAN } //========================================================================================== @@ -1091,17 +1017,15 @@ static void R_RadixSort( drawSurf_t *source, int size ) R_AddDrawSurf ================= */ -void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader, - int fogIndex, int dlightMap ) { - int index; +void R_AddDrawSurf(surfaceType_t *surface, shader_t *shader, int fogIndex, int dlightMap) { + int index; - if (tr.refdef.rdflags & RDF_NOFOG) - { + if (tr.refdef.rdflags & RDF_NOFOG) { fogIndex = 0; } - if ( (shader->surfaceFlags & SURF_FORCESIGHT) && !(tr.refdef.rdflags & RDF_ForceSightOn) ) - { //if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw + if ((shader->surfaceFlags & SURF_FORCESIGHT) && + !(tr.refdef.rdflags & RDF_ForceSightOn)) { // if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw return; } @@ -1110,8 +1034,7 @@ void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader, index = tr.refdef.numDrawSurfs & DRAWSURF_MASK; // the sort data is packed into a single 32 bit value so it can be // compared quickly during the qsorting process - tr.refdef.drawSurfs[index].sort = (shader->sortedIndex << QSORT_SHADERNUM_SHIFT) - | tr.shiftedEntityNum | ( fogIndex << QSORT_FOGNUM_SHIFT ) | (int)dlightMap; + tr.refdef.drawSurfs[index].sort = (shader->sortedIndex << QSORT_SHADERNUM_SHIFT) | tr.shiftedEntityNum | (fogIndex << QSORT_FOGNUM_SHIFT) | (int)dlightMap; tr.refdef.drawSurfs[index].surface = surface; tr.refdef.numDrawSurfs++; } @@ -1121,11 +1044,10 @@ void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader, R_DecomposeSort ================= */ -void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader, - int *fogNum, int *dlightMap ) { - *fogNum = ( sort >> QSORT_FOGNUM_SHIFT ) & 31; - *shader = tr.sortedShaders[ ( sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1) ]; - *entityNum = ( sort >> QSORT_REFENTITYNUM_SHIFT ) & REFENTITYNUM_MASK; +void R_DecomposeSort(unsigned sort, int *entityNum, shader_t **shader, int *fogNum, int *dlightMap) { + *fogNum = (sort >> QSORT_FOGNUM_SHIFT) & 31; + *shader = tr.sortedShaders[(sort >> QSORT_SHADERNUM_SHIFT) & (MAX_SHADERS - 1)]; + *entityNum = (sort >> QSORT_REFENTITYNUM_SHIFT) & REFENTITYNUM_MASK; *dlightMap = sort & 3; } @@ -1134,55 +1056,55 @@ void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader, R_SortDrawSurfs ================= */ -void R_SortDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { - shader_t *shader; - int fogNum; - int entityNum; - int dlighted; - int i; +void R_SortDrawSurfs(drawSurf_t *drawSurfs, int numDrawSurfs) { + shader_t *shader; + int fogNum; + int entityNum; + int dlighted; + int i; // it is possible for some views to not have any surfaces - if ( numDrawSurfs < 1 ) { + if (numDrawSurfs < 1) { // we still need to add it for hyperspace cases - R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); + R_AddDrawSurfCmd(drawSurfs, numDrawSurfs); return; } // if we overflowed MAX_DRAWSURFS, the drawsurfs // wrapped around in the buffer and we will be missing // the first surfaces, not the last ones - if ( numDrawSurfs > MAX_DRAWSURFS ) { + if (numDrawSurfs > MAX_DRAWSURFS) { numDrawSurfs = MAX_DRAWSURFS; } // sort the drawsurfs by sort type, then orientation, then shader - R_RadixSort( drawSurfs, numDrawSurfs ); + R_RadixSort(drawSurfs, numDrawSurfs); // check for any pass through drawing, which // may cause another view to be rendered first - for ( i = 0 ; i < numDrawSurfs ; i++ ) { - R_DecomposeSort( (drawSurfs+i)->sort, &entityNum, &shader, &fogNum, &dlighted ); + for (i = 0; i < numDrawSurfs; i++) { + R_DecomposeSort((drawSurfs + i)->sort, &entityNum, &shader, &fogNum, &dlighted); - if ( shader->sort > SS_PORTAL ) { + if (shader->sort > SS_PORTAL) { break; } // no shader should ever have this sort type - if ( shader->sort == SS_BAD ) { - Com_Error (ERR_DROP, "Shader '%s'with sort == SS_BAD", shader->name ); + if (shader->sort == SS_BAD) { + Com_Error(ERR_DROP, "Shader '%s'with sort == SS_BAD", shader->name); } // if the mirror was completely clipped away, we may need to check another surface - if ( R_MirrorViewBySurface( (drawSurfs+i), entityNum) ) { + if (R_MirrorViewBySurface((drawSurfs + i), entityNum)) { // this is a debug option to see exactly what is being mirrored - if ( r_portalOnly->integer ) { + if (r_portalOnly->integer) { return; } - break; // only one mirror view at a time + break; // only one mirror view at a time } } - R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); + R_AddDrawSurfCmd(drawSurfs, numDrawSurfs); } /* @@ -1190,17 +1112,15 @@ void R_SortDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { R_AddEntitySurfaces ============= */ -void R_AddEntitySurfaces (void) { - trRefEntity_t *ent; - shader_t *shader; +void R_AddEntitySurfaces(void) { + trRefEntity_t *ent; + shader_t *shader; - if ( !r_drawentities->integer ) { + if (!r_drawentities->integer) { return; } - for ( tr.currentEntityNum = 0; - tr.currentEntityNum < tr.refdef.num_entities; - tr.currentEntityNum++ ) { + for (tr.currentEntityNum = 0; tr.currentEntityNum < tr.refdef.num_entities; tr.currentEntityNum++) { ent = tr.currentEntity = &tr.refdef.entities[tr.currentEntityNum]; assert(ent->e.renderfx >= 0); @@ -1215,14 +1135,14 @@ void R_AddEntitySurfaces (void) { // we don't want the hacked weapon position showing in // mirrors, because the true body position will already be drawn // - if ( (ent->e.renderfx & RF_FIRST_PERSON) && tr.viewParms.isPortal) { + if ((ent->e.renderfx & RF_FIRST_PERSON) && tr.viewParms.isPortal) { continue; } // simple generated models, like sprites and beams, are not culled - switch ( ent->e.reType ) { + switch (ent->e.reType) { case RT_PORTALSURFACE: - break; // don't draw anything + break; // don't draw anything case RT_SPRITE: case RT_BEAM: case RT_ORIENTED_QUAD: @@ -1234,85 +1154,79 @@ void R_AddEntitySurfaces (void) { // self blood sprites, talk balloons, etc should not be drawn in the primary // view. We can't just do this check for all entities, because md3 // entities may still want to cast shadows from them - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { continue; } - shader = R_GetShaderByHandle( ent->e.customShader ); - R_AddDrawSurf( &entitySurface, shader, R_SpriteFogNum( ent ), 0 ); + shader = R_GetShaderByHandle(ent->e.customShader); + R_AddDrawSurf(&entitySurface, shader, R_SpriteFogNum(ent), 0); break; case RT_MODEL: // we must set up parts of tr.ori for model culling - R_RotateForEntity( ent, &tr.viewParms, &tr.ori ); + R_RotateForEntity(ent, &tr.viewParms, &tr.ori); - tr.currentModel = R_GetModelByHandle( ent->e.hModel ); + tr.currentModel = R_GetModelByHandle(ent->e.hModel); if (!tr.currentModel) { - R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, 0 ); + R_AddDrawSurf(&entitySurface, tr.defaultShader, 0, 0); } else { - switch ( tr.currentModel->type ) { + switch (tr.currentModel->type) { case MOD_MESH: - R_AddMD3Surfaces( ent ); + R_AddMD3Surfaces(ent); break; case MOD_BRUSH: - R_AddBrushModelSurfaces( ent ); + R_AddBrushModelSurfaces(ent); break; -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ case MOD_MDXM: - //g2r - if (ent->e.ghoul2) - { - R_AddGhoulSurfaces( ent); + // g2r + if (ent->e.ghoul2) { + R_AddGhoulSurfaces(ent); } - break; - case MOD_BAD: // null model axis - if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) - { - if (!(ent->e.renderfx & RF_SHADOW_ONLY)) - { + break; + case MOD_BAD: // null model axis + if ((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + if (!(ent->e.renderfx & RF_SHADOW_ONLY)) { break; } } - if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) - { - R_AddGhoulSurfaces( ent); - break; - } + if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) { + R_AddGhoulSurfaces(ent); + break; + } - R_AddDrawSurf( &entitySurface, tr.defaultShader, 0, false ); + R_AddDrawSurf(&entitySurface, tr.defaultShader, 0, false); break; -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ default: - Com_Error( ERR_DROP, "R_AddEntitySurfaces: Bad modeltype" ); + Com_Error(ERR_DROP, "R_AddEntitySurfaces: Bad modeltype"); break; } } break; case RT_ENT_CHAIN: - shader = R_GetShaderByHandle( ent->e.customShader ); - R_AddDrawSurf( &entitySurface, shader, R_SpriteFogNum( ent ), false ); + shader = R_GetShaderByHandle(ent->e.customShader); + R_AddDrawSurf(&entitySurface, shader, R_SpriteFogNum(ent), false); break; default: - Com_Error( ERR_DROP, "R_AddEntitySurfaces: Bad reType" ); + Com_Error(ERR_DROP, "R_AddEntitySurfaces: Bad reType"); } } - } - /* ==================== R_GenerateDrawSurfs ==================== */ -void R_GenerateDrawSurfs( void ) { - R_AddWorldSurfaces (); +void R_GenerateDrawSurfs(void) { + R_AddWorldSurfaces(); R_AddPolygonSurfaces(); @@ -1321,9 +1235,9 @@ void R_GenerateDrawSurfs( void ) { // this needs to be done before entities are // added, because they use the projection // matrix for lod calculation - R_SetupProjection (); + R_SetupProjection(); - R_AddEntitySurfaces (); + R_AddEntitySurfaces(); } /* @@ -1331,30 +1245,30 @@ void R_GenerateDrawSurfs( void ) { R_DebugPolygon ================ */ -void R_DebugPolygon( int color, int numPoints, float *points ) { - int i; +void R_DebugPolygon(int color, int numPoints, float *points) { + int i; - GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + GL_State(GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); // draw solid shade - qglColor3f( color&1, (color>>1)&1, (color>>2)&1 ); - qglBegin( GL_POLYGON ); - for ( i = 0 ; i < numPoints ; i++ ) { - qglVertex3fv( points + i * 3 ); + qglColor3f(color & 1, (color >> 1) & 1, (color >> 2) & 1); + qglBegin(GL_POLYGON); + for (i = 0; i < numPoints; i++) { + qglVertex3fv(points + i * 3); } qglEnd(); // draw wireframe outline - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); - qglDepthRange( 0, 0 ); - qglColor3f( 1, 1, 1 ); - qglBegin( GL_POLYGON ); - for ( i = 0 ; i < numPoints ; i++ ) { - qglVertex3fv( points + i * 3 ); + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); + qglDepthRange(0, 0); + qglColor3f(1, 1, 1); + qglBegin(GL_POLYGON); + for (i = 0; i < numPoints; i++) { + qglVertex3fv(points + i * 3); } qglEnd(); - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } /* @@ -1364,20 +1278,19 @@ R_DebugGraphics Visualization aid for movement clipping debugging ==================== */ -void R_DebugGraphics( void ) { - if ( !r_debugSurface->integer ) { +void R_DebugGraphics(void) { + if (!r_debugSurface->integer) { return; } // the render thread can't make callbacks to the main thread R_IssuePendingRenderCommands(); - GL_Bind( tr.whiteImage); - GL_Cull( CT_FRONT_SIDED ); - ri.CM_DrawDebugSurface( R_DebugPolygon ); + GL_Bind(tr.whiteImage); + GL_Cull(CT_FRONT_SIDED); + ri.CM_DrawDebugSurface(R_DebugPolygon); } - /* ================ R_RenderView @@ -1386,10 +1299,10 @@ A view may be either the actual camera view, or a mirror / remote location ================ */ -void R_RenderView (viewParms_t *parms) { - int firstDrawSurf; +void R_RenderView(viewParms_t *parms) { + int firstDrawSurf; - if ( parms->viewportWidth <= 0 || parms->viewportHeight <= 0 ) { + if (parms->viewportWidth <= 0 || parms->viewportHeight <= 0) { return; } @@ -1404,13 +1317,13 @@ void R_RenderView (viewParms_t *parms) { tr.viewCount++; // set viewParms.world - R_RotateForViewer (); + R_RotateForViewer(); - R_SetupFrustum (); + R_SetupFrustum(); R_GenerateDrawSurfs(); - R_SortDrawSurfs( tr.refdef.drawSurfs + firstDrawSurf, tr.refdef.numDrawSurfs - firstDrawSurf ); + R_SortDrawSurfs(tr.refdef.drawSurfs + firstDrawSurf, tr.refdef.numDrawSurfs - firstDrawSurf); // draw main system development information (surface outlines, etc) R_DebugGraphics(); diff --git a/codemp/rd-vanilla/tr_marks.cpp b/codemp/rd-vanilla/tr_marks.cpp index d77da90ebe..2eb897492c 100644 --- a/codemp/rd-vanilla/tr_marks.cpp +++ b/codemp/rd-vanilla/tr_marks.cpp @@ -25,9 +25,9 @@ along with this program; if not, see . #include "tr_local.h" -#define MAX_VERTS_ON_POLY 64 +#define MAX_VERTS_ON_POLY 64 -#define MARKER_OFFSET 0 // 1 +#define MARKER_OFFSET 0 // 1 /* ============= @@ -36,22 +36,21 @@ R_ChopPolyBehindPlane Out must have space for two more vertexes than in ============= */ -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 -static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], - int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], - vec3_t normal, float dist, float epsilon) { - float dists[MAX_VERTS_ON_POLY+4] = { 0 }; - int sides[MAX_VERTS_ON_POLY+4] = { 0 }; - int counts[3]; - float dot; - int i, j; - float *p1, *p2, *clip; - float d; +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 +static void R_ChopPolyBehindPlane(int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], vec3_t normal, + float dist, float epsilon) { + float dists[MAX_VERTS_ON_POLY + 4] = {0}; + int sides[MAX_VERTS_ON_POLY + 4] = {0}; + int counts[3]; + float dot; + int i, j; + float *p1, *p2, *clip; + float d; // don't clip if it might overflow - if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) { + if (numInPoints >= MAX_VERTS_ON_POLY - 2) { *numOutPoints = 0; return; } @@ -59,13 +58,13 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON counts[0] = counts[1] = counts[2] = 0; // determine sides for each point - for ( i = 0 ; i < numInPoints ; i++ ) { - dot = DotProduct( inPoints[i], normal ); + for (i = 0; i < numInPoints; i++) { + dot = DotProduct(inPoints[i], normal); dot -= dist; dists[i] = dot; - if ( dot > epsilon ) { + if (dot > epsilon) { sides[i] = SIDE_FRONT; - } else if ( dot < -epsilon ) { + } else if (dot < -epsilon) { sides[i] = SIDE_BACK; } else { sides[i] = SIDE_ON; @@ -77,40 +76,40 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON *numOutPoints = 0; - if ( !counts[0] ) { + if (!counts[0]) { return; } - if ( !counts[1] ) { + if (!counts[1]) { *numOutPoints = numInPoints; - memcpy( outPoints, inPoints, numInPoints * sizeof(vec3_t) ); + memcpy(outPoints, inPoints, numInPoints * sizeof(vec3_t)); return; } - for ( i = 0 ; i < numInPoints ; i++ ) { + for (i = 0; i < numInPoints; i++) { p1 = inPoints[i]; - clip = outPoints[ *numOutPoints ]; + clip = outPoints[*numOutPoints]; - if ( sides[i] == SIDE_ON ) { - VectorCopy( p1, clip ); + if (sides[i] == SIDE_ON) { + VectorCopy(p1, clip); (*numOutPoints)++; continue; } - if ( sides[i] == SIDE_FRONT ) { - VectorCopy( p1, clip ); + if (sides[i] == SIDE_FRONT) { + VectorCopy(p1, clip); (*numOutPoints)++; - clip = outPoints[ *numOutPoints ]; + clip = outPoints[*numOutPoints]; } - if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) { + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) { continue; } // generate a split point - p2 = inPoints[ (i+1) % numInPoints ]; + p2 = inPoints[(i + 1) % numInPoints]; - d = dists[i] - dists[i+1]; - if ( d == 0 ) { + d = dists[i] - dists[i + 1]; + if (d == 0) { dot = 0; } else { dot = dists[i] / d; @@ -118,8 +117,8 @@ static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON // clip xyz - for (j=0 ; j<3 ; j++) { - clip[j] = p1[j] + dot * ( p2[j] - p1[j] ); + for (j = 0; j < 3; j++) { + clip[j] = p1[j] + dot * (p2[j] - p1[j]); } (*numOutPoints)++; @@ -134,12 +133,12 @@ R_BoxSurfaces_r */ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **list, int listsize, int *listlength, vec3_t dir) { - int s, c; - msurface_t *surf, **mark; + int s, c; + msurface_t *surf, **mark; // do the tail recursion in a loop - while ( node->contents == -1 ) { - s = BoxOnPlaneSide( mins, maxs, node->plane ); + while (node->contents == -1) { + s = BoxOnPlaneSide(mins, maxs, node->plane); if (s == 1) { node = node->children[0]; } else if (s == 2) { @@ -155,33 +154,31 @@ void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **li c = node->nummarksurfaces; while (c--) { // - if (*listlength >= listsize) break; + if (*listlength >= listsize) + break; // surf = *mark; // check if the surface has NOIMPACT or NOMARKS set - if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) ) - || ( surf->shader->contentFlags & CONTENTS_FOG ) ) { + if ((surf->shader->surfaceFlags & (SURF_NOIMPACT | SURF_NOMARKS)) || (surf->shader->contentFlags & CONTENTS_FOG)) { surf->viewCount = tr.viewCount; } // extra check for surfaces to avoid list overflows else if (*(surf->data) == SF_FACE) { // the face plane should go through the box - s = BoxOnPlaneSide( mins, maxs, &(( srfSurfaceFace_t * ) surf->data)->plane ); + s = BoxOnPlaneSide(mins, maxs, &((srfSurfaceFace_t *)surf->data)->plane); if (s == 1 || s == 2) { surf->viewCount = tr.viewCount; - } else if (DotProduct((( srfSurfaceFace_t * ) surf->data)->plane.normal, dir) > -0.5) { - // don't add faces that make sharp angles with the projection direction + } else if (DotProduct(((srfSurfaceFace_t *)surf->data)->plane.normal, dir) > -0.5) { + // don't add faces that make sharp angles with the projection direction surf->viewCount = tr.viewCount; } - } - else if (*(surfaceType_t *) (surf->data) != SF_GRID && - *(surfaceType_t *) (surf->data) != SF_TRIANGLES) + } else if (*(surfaceType_t *)(surf->data) != SF_GRID && *(surfaceType_t *)(surf->data) != SF_TRIANGLES) surf->viewCount = tr.viewCount; // check the viewCount because the surface may have // already been added if it spans multiple leafs if (surf->viewCount != tr.viewCount) { surf->viewCount = tr.viewCount; - list[*listlength] = (surfaceType_t *) surf->data; + list[*listlength] = (surfaceType_t *)surf->data; (*listlength)++; } mark++; @@ -194,36 +191,31 @@ R_AddMarkFragments ================= */ -void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], - int numPlanes, vec3_t *normals, float *dists, - int maxPoints, vec3_t pointBuffer, - int maxFragments, markFragment_t *fragmentBuffer, - int *returnedPoints, int *returnedFragments, - vec3_t mins, vec3_t maxs) { +void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], int numPlanes, vec3_t *normals, float *dists, int maxPoints, + vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer, int *returnedPoints, int *returnedFragments, vec3_t mins, + vec3_t maxs) { int pingPong, i; - markFragment_t *mf; + markFragment_t *mf; // chop the surface by all the bounding planes of the to be projected polygon pingPong = 0; - for ( i = 0 ; i < numPlanes ; i++ ) { + for (i = 0; i < numPlanes; i++) { - R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong], - &numClipPoints, clipPoints[!pingPong], - normals[i], dists[i], 0.5 ); + R_ChopPolyBehindPlane(numClipPoints, clipPoints[pingPong], &numClipPoints, clipPoints[!pingPong], normals[i], dists[i], 0.5); pingPong ^= 1; - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { break; } } // completely clipped away? - if ( numClipPoints == 0 ) { + if (numClipPoints == 0) { return; } // add this fragment to the returned list - if ( numClipPoints + (*returnedPoints) > maxPoints ) { - return; // not enough space for this polygon + if (numClipPoints + (*returnedPoints) > maxPoints) { + return; // not enough space for this polygon } /* // all the clip points should be within the bounding box @@ -241,7 +233,7 @@ void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POL mf = fragmentBuffer + (*returnedFragments); mf->firstPoint = (*returnedPoints); mf->numPoints = numClipPoints; - memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t) ); + memcpy(pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t)); (*returnedPoints) += numClipPoints; (*returnedFragments)++; @@ -253,48 +245,49 @@ R_MarkFragments ================= */ -int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, - int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) { - int numsurfaces, numPlanes; - int i, j, k, m, n; - surfaceType_t *surfaces[64]; - vec3_t mins, maxs; - int returnedFragments; - int returnedPoints; - vec3_t normals[MAX_VERTS_ON_POLY+2]; - float dists[MAX_VERTS_ON_POLY+2]; - vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; - int numClipPoints; - float *v; - srfGridMesh_t *cv; - drawVert_t *dv; - vec3_t normal; - vec3_t projectionDir; - vec3_t v1, v2; - int *indexes; - - //increment view count for double check prevention +int R_MarkFragments(int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, + markFragment_t *fragmentBuffer) { + int numsurfaces, numPlanes; + int i, j, k, m, n; + surfaceType_t *surfaces[64]; + vec3_t mins, maxs; + int returnedFragments; + int returnedPoints; + vec3_t normals[MAX_VERTS_ON_POLY + 2]; + float dists[MAX_VERTS_ON_POLY + 2]; + vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; + int numClipPoints; + float *v; + srfGridMesh_t *cv; + drawVert_t *dv; + vec3_t normal; + vec3_t projectionDir; + vec3_t v1, v2; + int *indexes; + + // increment view count for double check prevention tr.viewCount++; // - VectorNormalize2( projection, projectionDir ); + VectorNormalize2(projection, projectionDir); // find all the brushes that are to be considered - ClearBounds( mins, maxs ); - for ( i = 0 ; i < numPoints ; i++ ) { - vec3_t temp; + ClearBounds(mins, maxs); + for (i = 0; i < numPoints; i++) { + vec3_t temp; - AddPointToBounds( points[i], mins, maxs ); - VectorAdd( points[i], projection, temp ); - AddPointToBounds( temp, mins, maxs ); + AddPointToBounds(points[i], mins, maxs); + VectorAdd(points[i], projection, temp); + AddPointToBounds(temp, mins, maxs); // make sure we get all the leafs (also the one(s) in front of the hit surface) - VectorMA( points[i], -20, projectionDir, temp ); - AddPointToBounds( temp, mins, maxs ); + VectorMA(points[i], -20, projectionDir, temp); + AddPointToBounds(temp, mins, maxs); } - if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY; + if (numPoints > MAX_VERTS_ON_POLY) + numPoints = MAX_VERTS_ON_POLY; // create the bounding planes for the to be projected polygon - for ( i = 0 ; i < numPoints ; i++ ) { - VectorSubtract(points[(i+1)%numPoints], points[i], v1); + for (i = 0; i < numPoints; i++) { + VectorSubtract(points[(i + 1) % numPoints], points[i], v1); VectorAdd(points[i], projection, v2); VectorSubtract(points[i], v2, v2); CrossProduct(v1, v2, normals[i]); @@ -304,26 +297,26 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio // add near and far clipping planes for projection VectorCopy(projectionDir, normals[numPoints]); dists[numPoints] = DotProduct(normals[numPoints], points[0]) - 32; - VectorCopy(projectionDir, normals[numPoints+1]); - VectorInverse(normals[numPoints+1]); - dists[numPoints+1] = DotProduct(normals[numPoints+1], points[0]) - 20; + VectorCopy(projectionDir, normals[numPoints + 1]); + VectorInverse(normals[numPoints + 1]); + dists[numPoints + 1] = DotProduct(normals[numPoints + 1], points[0]) - 20; numPlanes = numPoints + 2; numsurfaces = 0; R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir); - //assert(numsurfaces <= 64); - //assert(numsurfaces != 64); + // assert(numsurfaces <= 64); + // assert(numsurfaces != 64); returnedPoints = 0; returnedFragments = 0; - for ( i = 0 ; i < numsurfaces ; i++ ) { + for (i = 0; i < numsurfaces; i++) { if (*surfaces[i] == SF_GRID) { - cv = (srfGridMesh_t *) surfaces[i]; - for ( m = 0 ; m < cv->height - 1 ; m++ ) { - for ( n = 0 ; n < cv->width - 1 ; n++ ) { + cv = (srfGridMesh_t *)surfaces[i]; + for (m = 0; m < cv->height - 1; m++) { + for (n = 0; n < cv->width - 1; n++) { // We triangulate the grid and chop all triangles within // the bounding planes of the to be projected polygon. // LOD is not taken into account, not such a big deal though. @@ -362,14 +355,11 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.1) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } @@ -377,8 +367,8 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[1].normal, clipPoints[0][0]); VectorCopy(dv[cv->width].xyz, clipPoints[0][1]); VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]); - VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]); - VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width+1].normal, clipPoints[0][2]); + VectorCopy(dv[cv->width + 1].xyz, clipPoints[0][2]); + VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width + 1].normal, clipPoints[0][2]); // check the normal of this triangle VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1); VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2); @@ -386,69 +376,56 @@ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projectio VectorNormalizeFast(normal); if (DotProduct(normal, projectionDir) < -0.05) { // add the fragments of this triangle - R_AddMarkFragments(numClipPoints, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, + R_AddMarkFragments(numClipPoints, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } } - } - else if (*surfaces[i] == SF_FACE) { + } else if (*surfaces[i] == SF_FACE) { - srfSurfaceFace_t *surf = ( srfSurfaceFace_t * ) surfaces[i]; + srfSurfaceFace_t *surf = (srfSurfaceFace_t *)surfaces[i]; // check the normal of this face if (DotProduct(surf->plane.normal, projectionDir) > -0.5) { continue; } - indexes = (int *)( (byte *)surf + surf->ofsIndices ); - for ( k = 0 ; k < surf->numIndices ; k += 3 ) { - for ( j = 0 ; j < 3 ; j++ ) { - v = surf->points[0] + VERTEXSIZE * indexes[k+j];; - VectorMA( v, MARKER_OFFSET, surf->plane.normal, clipPoints[0][j] ); + indexes = (int *)((byte *)surf + surf->ofsIndices); + for (k = 0; k < surf->numIndices; k += 3) { + for (j = 0; j < 3; j++) { + v = surf->points[0] + VERTEXSIZE * indexes[k + j]; + ; + VectorMA(v, MARKER_OFFSET, surf->plane.normal, clipPoints[0][j]); } // add the fragments of this face - R_AddMarkFragments( 3 , clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, - &returnedPoints, &returnedFragments, mins, maxs); - if ( returnedFragments == maxFragments ) { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } continue; - } - else if(*surfaces[i] == SF_TRIANGLES && r_marksOnTriangleMeshes->integer) { + } else if (*surfaces[i] == SF_TRIANGLES && r_marksOnTriangleMeshes->integer) { - srfTriangles_t *surf = (srfTriangles_t *) surfaces[i]; + srfTriangles_t *surf = (srfTriangles_t *)surfaces[i]; - for (k = 0; k < surf->numIndexes; k += 3) - { - for(j = 0; j < 3; j++) - { + for (k = 0; k < surf->numIndexes; k += 3) { + for (j = 0; j < 3; j++) { v = surf->verts[surf->indexes[k + j]].xyz; VectorMA(v, MARKER_OFFSET, surf->verts[surf->indexes[k + j]].normal, clipPoints[0][j]); } // add the fragments of this face - R_AddMarkFragments(3, clipPoints, - numPlanes, normals, dists, - maxPoints, pointBuffer, - maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); - if(returnedFragments == maxFragments) - { - return returnedFragments; // not enough space for more fragments + R_AddMarkFragments(3, clipPoints, numPlanes, normals, dists, maxPoints, pointBuffer, maxFragments, fragmentBuffer, &returnedPoints, + &returnedFragments, mins, maxs); + if (returnedFragments == maxFragments) { + return returnedFragments; // not enough space for more fragments } } } } return returnedFragments; } - diff --git a/codemp/rd-vanilla/tr_mesh.cpp b/codemp/rd-vanilla/tr_mesh.cpp index 938a060530..971b99498e 100644 --- a/codemp/rd-vanilla/tr_mesh.cpp +++ b/codemp/rd-vanilla/tr_mesh.cpp @@ -25,38 +25,33 @@ along with this program; if not, see . #include "tr_local.h" -float ProjectRadius( float r, vec3_t location ) -{ +float ProjectRadius(float r, vec3_t location) { float pr; float dist; float c; - vec3_t p; + vec3_t p; float width; float depth; - c = DotProduct( tr.viewParms.ori.axis[0], tr.viewParms.ori.origin ); - dist = DotProduct( tr.viewParms.ori.axis[0], location ) - c; + c = DotProduct(tr.viewParms.ori.axis[0], tr.viewParms.ori.origin); + dist = DotProduct(tr.viewParms.ori.axis[0], location) - c; - if ( dist <= 0 ) + if (dist <= 0) return 0; p[0] = 0; - p[1] = Q_fabs( r ); + p[1] = Q_fabs(r); p[2] = -dist; - width = p[0] * tr.viewParms.projectionMatrix[1] + - p[1] * tr.viewParms.projectionMatrix[5] + - p[2] * tr.viewParms.projectionMatrix[9] + - tr.viewParms.projectionMatrix[13]; + width = p[0] * tr.viewParms.projectionMatrix[1] + p[1] * tr.viewParms.projectionMatrix[5] + p[2] * tr.viewParms.projectionMatrix[9] + + tr.viewParms.projectionMatrix[13]; - depth = p[0] * tr.viewParms.projectionMatrix[3] + - p[1] * tr.viewParms.projectionMatrix[7] + - p[2] * tr.viewParms.projectionMatrix[11] + - tr.viewParms.projectionMatrix[15]; + depth = p[0] * tr.viewParms.projectionMatrix[3] + p[1] * tr.viewParms.projectionMatrix[7] + p[2] * tr.viewParms.projectionMatrix[11] + + tr.viewParms.projectionMatrix[15]; pr = width / depth; - if ( pr > 1.0f ) + if (pr > 1.0f) pr = 1.0f; return pr; @@ -67,22 +62,19 @@ float ProjectRadius( float r, vec3_t location ) R_CullModel ============= */ -static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { - vec3_t bounds[2]; - md3Frame_t *oldFrame, *newFrame; - int i; +static int R_CullModel(md3Header_t *header, trRefEntity_t *ent) { + vec3_t bounds[2]; + md3Frame_t *oldFrame, *newFrame; + int i; // compute frame pointers - newFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame; - oldFrame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.oldframe; + newFrame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.frame; + oldFrame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.oldframe; // cull bounding sphere ONLY if this is not an upscaled entity - if ( !ent->e.nonNormalizedAxes ) - { - if ( ent->e.frame == ent->e.oldframe ) - { - switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) - { + if (!ent->e.nonNormalizedAxes) { + if (ent->e.frame == ent->e.oldframe) { + switch (R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius)) { case CULL_OUT: tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; @@ -95,32 +87,24 @@ static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { tr.pc.c_sphere_cull_md3_clip++; break; } - } - else - { + } else { int sphereCull, sphereCullB; - sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); - if ( newFrame == oldFrame ) { + sphereCull = R_CullLocalPointAndRadius(newFrame->localOrigin, newFrame->radius); + if (newFrame == oldFrame) { sphereCullB = sphereCull; } else { - sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + sphereCullB = R_CullLocalPointAndRadius(oldFrame->localOrigin, oldFrame->radius); } - if ( sphereCull == sphereCullB ) - { - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == sphereCullB) { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_md3_out++; return CULL_OUT; - } - else if ( sphereCull == CULL_IN ) - { + } else if (sphereCull == CULL_IN) { tr.pc.c_sphere_cull_md3_in++; return CULL_IN; - } - else - { + } else { tr.pc.c_sphere_cull_md3_clip++; } } @@ -128,13 +112,12 @@ static int R_CullModel( md3Header_t *header, trRefEntity_t *ent ) { } // calculate a bounding box in the current coordinate system - for (i = 0 ; i < 3 ; i++) { + for (i = 0; i < 3; i++) { bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; } - switch ( R_CullLocalBox( bounds ) ) - { + switch (R_CullLocalBox(bounds)) { case CULL_IN: tr.pc.c_box_cull_md3_in++; return CULL_IN; @@ -156,20 +139,19 @@ RE_GetModelBounds (qhandle_t)hModel and (int)frame need to be set ================= */ -//rwwRMG - added -void RE_GetModelBounds(refEntity_t *refEnt, vec3_t bounds1, vec3_t bounds2) -{ - md3Frame_t *frame; - md3Header_t *header; - model_t *model; +// rwwRMG - added +void RE_GetModelBounds(refEntity_t *refEnt, vec3_t bounds1, vec3_t bounds2) { + md3Frame_t *frame; + md3Header_t *header; + model_t *model; assert(refEnt); - model = R_GetModelByHandle( refEnt->hModel ); + model = R_GetModelByHandle(refEnt->hModel); assert(model); header = model->md3[0]; assert(header); - frame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + refEnt->frame; + frame = (md3Frame_t *)((byte *)header + header->ofsFrames) + refEnt->frame; assert(frame); VectorCopy(frame->bounds[0], bounds1); @@ -182,66 +164,54 @@ R_ComputeLOD ================= */ -int R_ComputeLOD( trRefEntity_t *ent ) { +int R_ComputeLOD(trRefEntity_t *ent) { float radius; float flod, lodscale; float projectedRadius; md3Frame_t *frame; int lod; - if ( tr.currentModel->numLods < 2 ) - { + if (tr.currentModel->numLods < 2) { // model has only 1 LOD level, skip computations and bias lod = 0; - } - else - { + } else { // multiple LODs exist, so compute projected bounding sphere // and use that as a criteria for selecting LOD - frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames ); + frame = (md3Frame_t *)(((unsigned char *)tr.currentModel->md3[0]) + tr.currentModel->md3[0]->ofsFrames); frame += ent->e.frame; - radius = RadiusFromBounds( frame->bounds[0], frame->bounds[1] ); + radius = RadiusFromBounds(frame->bounds[0], frame->bounds[1]); - if ( ( projectedRadius = ProjectRadius( radius, ent->e.origin ) ) != 0 ) - { - lodscale = (r_lodscale->value+r_autolodscalevalue->value); - if ( lodscale > 20 ) - { + if ((projectedRadius = ProjectRadius(radius, ent->e.origin)) != 0) { + lodscale = (r_lodscale->value + r_autolodscalevalue->value); + if (lodscale > 20) { lodscale = 20; - } - else if ( lodscale < 0 ) - { + } else if (lodscale < 0) { lodscale = 0; } flod = 1.0f - projectedRadius * lodscale; - } - else - { + } else { // object intersects near view plane, e.g. view weapon flod = 0; } flod *= tr.currentModel->numLods; - lod = Q_ftol( flod ); + lod = Q_ftol(flod); - if ( lod < 0 ) - { + if (lod < 0) { lod = 0; - } - else if ( lod >= tr.currentModel->numLods ) - { + } else if (lod >= tr.currentModel->numLods) { lod = tr.currentModel->numLods - 1; } } lod += r_lodbias->integer; - if ( lod >= tr.currentModel->numLods ) + if (lod >= tr.currentModel->numLods) lod = tr.currentModel->numLods - 1; - if ( lod < 0 ) + if (lod < 0) lod = 0; return lod; @@ -253,30 +223,30 @@ R_ComputeFogNum ================= */ -int R_ComputeFogNum( md3Header_t *header, trRefEntity_t *ent ) { - int i, j; - fog_t *fog; - md3Frame_t *md3Frame; - vec3_t localOrigin; +int R_ComputeFogNum(md3Header_t *header, trRefEntity_t *ent) { + int i, j; + fog_t *fog; + md3Frame_t *md3Frame; + vec3_t localOrigin; - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return 0; } // FIXME: non-normalized axis issues - md3Frame = ( md3Frame_t * ) ( ( byte * ) header + header->ofsFrames ) + ent->e.frame; - VectorAdd( ent->e.origin, md3Frame->localOrigin, localOrigin ); - for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + md3Frame = (md3Frame_t *)((byte *)header + header->ofsFrames) + ent->e.frame; + VectorAdd(ent->e.origin, md3Frame->localOrigin, localOrigin); + for (i = 1; i < tr.world->numfogs; i++) { fog = &tr.world->fogs[i]; - for ( j = 0 ; j < 3 ; j++ ) { - if ( localOrigin[j] - md3Frame->radius >= fog->bounds[1][j] ) { + for (j = 0; j < 3; j++) { + if (localOrigin[j] - md3Frame->radius >= fog->bounds[1][j]) { break; } - if ( localOrigin[j] + md3Frame->radius <= fog->bounds[0][j] ) { + if (localOrigin[j] + md3Frame->radius <= fog->bounds[0][j]) { break; } } - if ( j == 3 ) { + if (j == 3) { return i; } } @@ -290,21 +260,21 @@ R_AddMD3Surfaces ================= */ -void R_AddMD3Surfaces( trRefEntity_t *ent ) { - int i; - md3Header_t *header = 0; - md3Surface_t *surface = 0; - md3Shader_t *md3Shader = 0; - shader_t *shader = 0; - int cull; - int lod; - int fogNum; - qboolean personalModel; +void R_AddMD3Surfaces(trRefEntity_t *ent) { + int i; + md3Header_t *header = 0; + md3Surface_t *surface = 0; + md3Shader_t *md3Shader = 0; + shader_t *shader = 0; + int cull; + int lod; + int fogNum; + qboolean personalModel; // don't add third_person objects if not in a portal personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); - if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + if (ent->e.renderfx & RF_WRAP_FRAMES) { ent->e.frame %= tr.currentModel->md3[0]->numFrames; ent->e.oldframe %= tr.currentModel->md3[0]->numFrames; } @@ -315,21 +285,17 @@ void R_AddMD3Surfaces( trRefEntity_t *ent ) { // when the surfaces are rendered, they don't need to be // range checked again. // - if ( (ent->e.frame >= tr.currentModel->md3[0]->numFrames) - || (ent->e.frame < 0) - || (ent->e.oldframe >= tr.currentModel->md3[0]->numFrames) - || (ent->e.oldframe < 0) ) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", - ent->e.oldframe, ent->e.frame, - tr.currentModel->name ); - ent->e.frame = 0; - ent->e.oldframe = 0; + if ((ent->e.frame >= tr.currentModel->md3[0]->numFrames) || (ent->e.frame < 0) || (ent->e.oldframe >= tr.currentModel->md3[0]->numFrames) || + (ent->e.oldframe < 0)) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", ent->e.oldframe, ent->e.frame, tr.currentModel->name); + ent->e.frame = 0; + ent->e.oldframe = 0; } // // compute LOD // - lod = R_ComputeLOD( ent ); + lod = R_ComputeLOD(ent); header = tr.currentModel->md3[lod]; @@ -337,86 +303,76 @@ void R_AddMD3Surfaces( trRefEntity_t *ent ) { // cull the entire model if merged bounding box of both frames // is outside the view frustum. // - cull = R_CullModel ( header, ent ); - if ( cull == CULL_OUT ) { + cull = R_CullModel(header, ent); + if (cull == CULL_OUT) { return; } // // set up lighting now that we know we aren't culled // - if ( !personalModel || r_shadows->integer > 1 ) { - R_SetupEntityLighting( &tr.refdef, ent ); + if (!personalModel || r_shadows->integer > 1) { + R_SetupEntityLighting(&tr.refdef, ent); } // // see if we are in a fog volume // - fogNum = R_ComputeFogNum( header, ent ); + fogNum = R_ComputeFogNum(header, ent); // // draw all surfaces // - surface = (md3Surface_t *)( (byte *)header + header->ofsSurfaces ); - for ( i = 0 ; i < header->numSurfaces ; i++ ) { + surface = (md3Surface_t *)((byte *)header + header->ofsSurfaces); + for (i = 0; i < header->numSurfaces; i++) { - if ( ent->e.customShader ) { - shader = R_GetShaderByHandle( ent->e.customShader ); - } else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) { + if (ent->e.customShader) { + shader = R_GetShaderByHandle(ent->e.customShader); + } else if (ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) { skin_t *skin; - int j; + int j; - skin = R_GetSkinByHandle( ent->e.customSkin ); + skin = R_GetSkinByHandle(ent->e.customSkin); // match the surface name to something in the skin file shader = tr.defaultShader; - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { + for (j = 0; j < skin->numSurfaces; j++) { // the names have both been lowercased - if ( !strcmp( skin->surfaces[j]->name, surface->name ) ) { + if (!strcmp(skin->surfaces[j]->name, surface->name)) { shader = (shader_t *)skin->surfaces[j]->shader; break; } } if (shader == tr.defaultShader) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); + } else if (shader->defaultShader) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "WARNING: shader %s in skin %s not found\n", shader->name, skin->name); } - else if (shader->defaultShader) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "WARNING: shader %s in skin %s not found\n", shader->name, skin->name); - } - } else if ( surface->numShaders <= 0 ) { + } else if (surface->numShaders <= 0) { shader = tr.defaultShader; } else { - md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders ); + md3Shader = (md3Shader_t *)((byte *)surface + surface->ofsShaders); md3Shader += ent->e.skinNum % surface->numShaders; - shader = tr.shaders[ md3Shader->shaderIndex ]; + shader = tr.shaders[md3Shader->shaderIndex]; } - // we will add shadows even if the main object isn't visible in the view // stencil shadows can't do personal models unless I polyhedron clip - if ( !personalModel - && r_shadows->integer == 2 - && fogNum == 0 - && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, tr.shadowShader, 0, qfalse ); + if (!personalModel && r_shadows->integer == 2 && fogNum == 0 && !(ent->e.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, tr.shadowShader, 0, qfalse); } // projection shadows work fine with personal models - if ( r_shadows->integer == 3 - && fogNum == 0 - && (ent->e.renderfx & RF_SHADOW_PLANE ) - && shader->sort == SS_OPAQUE ) { - R_AddDrawSurf( (surfaceType_t *)surface, tr.projectionShadowShader, 0, qfalse ); + if (r_shadows->integer == 3 && fogNum == 0 && (ent->e.renderfx & RF_SHADOW_PLANE) && shader->sort == SS_OPAQUE) { + R_AddDrawSurf((surfaceType_t *)surface, tr.projectionShadowShader, 0, qfalse); } // don't add third_person objects if not viewing through a portal - if ( !personalModel ) { - R_AddDrawSurf( (surfaceType_t *)surface, shader, fogNum, qfalse ); + if (!personalModel) { + R_AddDrawSurf((surfaceType_t *)surface, shader, fogNum, qfalse); } - surface = (md3Surface_t *)( (byte *)surface + surface->ofsEnd ); + surface = (md3Surface_t *)((byte *)surface + surface->ofsEnd); } - } diff --git a/codemp/rd-vanilla/tr_model.cpp b/codemp/rd-vanilla/tr_model.cpp index 92c30ce4bd..c78576741e 100644 --- a/codemp/rd-vanilla/tr_model.cpp +++ b/codemp/rd-vanilla/tr_model.cpp @@ -25,184 +25,156 @@ along with this program; if not, see . #include "tr_local.h" #include "qcommon/disablewarnings.h" -#include "qcommon/sstring.h" // #include +#include "qcommon/sstring.h" // #include #include #include -#define LL(x) x=LittleLong(x) -#define LS(x) x=LittleShort(x) -#define LF(x) x=LittleFloat(x) +#define LL(x) x = LittleLong(x) +#define LS(x) x = LittleShort(x) +#define LF(x) x = LittleFloat(x) -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached ); +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *name, qboolean &bAlreadyCached); /* Ghoul2 Insert Start */ -typedef struct modelHash_s -{ - char name[MAX_QPATH]; - qhandle_t handle; - struct modelHash_s *next; +typedef struct modelHash_s { + char name[MAX_QPATH]; + qhandle_t handle; + struct modelHash_s *next; -}modelHash_t; +} modelHash_t; -#define FILE_HASH_SIZE 1024 -static modelHash_t *mhHashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 +static modelHash_t *mhHashTable[FILE_HASH_SIZE]; /* Ghoul2 Insert End */ - // This stuff looks a bit messy, but it's kept here as black box, and nothing appears in any .H files for other // modules to worry about. I may make another module for this sometime. // -typedef std::pair StringOffsetAndShaderIndexDest_t; -typedef std::vector ShaderRegisterData_t; -struct CachedEndianedModelBinary_s -{ - void *pModelDiskImage; - int iAllocSize; // may be useful for mem-query, but I don't actually need it +typedef std::pair StringOffsetAndShaderIndexDest_t; +typedef std::vector ShaderRegisterData_t; +struct CachedEndianedModelBinary_s { + void *pModelDiskImage; + int iAllocSize; // may be useful for mem-query, but I don't actually need it ShaderRegisterData_t ShaderRegisterData; - int iLastLevelUsedOn; - int iPAKFileCheckSum; // else -1 if not from PAK - + int iLastLevelUsedOn; + int iPAKFileCheckSum; // else -1 if not from PAK - CachedEndianedModelBinary_s() - { - pModelDiskImage = 0; - iAllocSize = 0; + CachedEndianedModelBinary_s() { + pModelDiskImage = 0; + iAllocSize = 0; ShaderRegisterData.clear(); - iLastLevelUsedOn = -1; - iPAKFileCheckSum = -1; + iLastLevelUsedOn = -1; + iPAKFileCheckSum = -1; } }; typedef struct CachedEndianedModelBinary_s CachedEndianedModelBinary_t; -typedef std::map CachedModels_t; -CachedModels_t *CachedModels = NULL; // the important cache item. +typedef std::map CachedModels_t; +CachedModels_t *CachedModels = NULL; // the important cache item. -void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke) -{ +void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { - assert(0); // should never happen, means that we're being called on a model that wasn't loaded - } - else - { - int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; - int iPokeOffset = (char*) piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; + if (ModelBin.pModelDiskImage == NULL) { + assert(0); // should never happen, means that we're being called on a model that wasn't loaded + } else { + int iNameOffset = psShaderName - (char *)ModelBin.pModelDiskImage; + int iPokeOffset = (char *)piShaderIndexPoke - (char *)ModelBin.pModelDiskImage; - ModelBin.ShaderRegisterData.push_back( StringOffsetAndShaderIndexDest_t( iNameOffset,iPokeOffset) ); + ModelBin.ShaderRegisterData.push_back(StringOffsetAndShaderIndexDest_t(iNameOffset, iPokeOffset)); } } - -static const byte FakeGLAFile[] = -{ -0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x01, 0x00, 0x00, 0x00, -0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, -0x26, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, -0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, -0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, -0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, -0x00, 0x80, 0x00, 0x80, 0x00, 0x80 -}; - -void RE_LoadWorldMap_Actual( const char *name, world_t &worldData, int index ); +static const byte FakeGLAFile[] = { + 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0x3F, 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x26, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6C, 0x74, 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, + 0xFF, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80}; + +void RE_LoadWorldMap_Actual(const char *name, world_t &worldData, int index); // returns qtrue if loaded, and sets the supplied qbool to true if it was from cache (instead of disk) // (which we need to know to avoid LittleLong()ing everything again (well, the Mac needs to know anyway)... // // don't use ri->xxx functions in case running on dedicated... // -qboolean RE_RegisterModels_GetDiskFile( const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) -{ +qboolean RE_RegisterModels_GetDiskFile(const char *psModelFileName, void **ppvBuffer, qboolean *pqbAlreadyCached) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // didn't have it cached, so try the disk... // - // special case intercept first... + // special case intercept first... + // + if (!strcmp(sDEFAULT_GLA_NAME ".gla", psModelFileName)) { + // return fake params as though it was found on disk... // - if (!strcmp(sDEFAULT_GLA_NAME ".gla" , psModelFileName)) - { - // return fake params as though it was found on disk... - // - void *pvFakeGLAFile = Z_Malloc( sizeof(FakeGLAFile), TAG_FILESYS, qfalse ); - memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); - *ppvBuffer = pvFakeGLAFile; - *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well - return qtrue; - } + void *pvFakeGLAFile = Z_Malloc(sizeof(FakeGLAFile), TAG_FILESYS, qfalse); + memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof(FakeGLAFile)); + *ppvBuffer = pvFakeGLAFile; + *pqbAlreadyCached = qfalse; // faking it like this should mean that it works fine on the Mac as well + return qtrue; + } - ri.FS_ReadFile( sModelName, ppvBuffer ); + ri.FS_ReadFile(sModelName, ppvBuffer); *pqbAlreadyCached = qfalse; - qboolean bSuccess = !!(*ppvBuffer)?qtrue:qfalse; + qboolean bSuccess = !!(*ppvBuffer) ? qtrue : qfalse; - if (bSuccess) - { - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_GetDiskFile(): Disk-loading \"%s\"\n",psModelFileName); + if (bSuccess) { + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_GetDiskFile(): Disk-loading \"%s\"\n", psModelFileName); } return bSuccess; - } - else - { + } else { *ppvBuffer = ModelBin.pModelDiskImage; *pqbAlreadyCached = qtrue; return qtrue; } } - // if return == true, no further action needed by the caller... // // don't use ri->xxx functions in case running on dedicated // -void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) -{ +void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // ... then this entry has only just been created, ie we need to load it fully... // // new, instead of doing a Z_Malloc and assigning that we just morph the disk buffer alloc @@ -210,49 +182,41 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const // // ... groan, but not if doing a limb hierarchy creation (some VV stuff?), in which case it's NULL // - if ( pvDiskBufferIfJustLoaded ) - { - Z_MorphMallocTag( pvDiskBufferIfJustLoaded, eTag ); - } - else - { - pvDiskBufferIfJustLoaded = Z_Malloc(iSize,eTag, qfalse ); + if (pvDiskBufferIfJustLoaded) { + Z_MorphMallocTag(pvDiskBufferIfJustLoaded, eTag); + } else { + pvDiskBufferIfJustLoaded = Z_Malloc(iSize, eTag, qfalse); } - ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; - ModelBin.iAllocSize = iSize; + ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; + ModelBin.iAllocSize = iSize; int iCheckSum; - if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) - { - ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 + if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) { + ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 } *pqbAlreadyFound = qfalse; - } - else - { + } else { // if we already had this model entry, then re-register all the shaders it wanted... // int iEntries = ModelBin.ShaderRegisterData.size(); - for (int i=0; idefaultShader ) - { + if (sh->defaultShader) { *piShaderPokePtr = 0; } else { *piShaderPokePtr = sh->index; } } - *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary + *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary } ModelBin.iLastLevelUsedOn = RE_RegisterMedia_GetLevel(); @@ -262,46 +226,38 @@ void *RE_RegisterModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const // Unfortunately the dedicated server also hates shader loading. So we need an alternate of this func. // -void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) -{ +void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, const char *psModelFileName, qboolean *pqbAlreadyFound, memtag_t eTag) { char sModelName[MAX_QPATH]; assert(CachedModels); - Q_strncpyz(sModelName,psModelFileName,sizeof(sModelName)); - Q_strlwr (sModelName); + Q_strncpyz(sModelName, psModelFileName, sizeof(sModelName)); + Q_strlwr(sModelName); CachedEndianedModelBinary_t &ModelBin = (*CachedModels)[sModelName]; - if (ModelBin.pModelDiskImage == NULL) - { + if (ModelBin.pModelDiskImage == NULL) { // new, instead of doing a Z_Malloc and assigning that we just morph the disk buffer alloc // then don't thrown it away on return - cuts down on mem overhead // // ... groan, but not if doing a limb hierarchy creation (some VV stuff?), in which case it's NULL // - if ( pvDiskBufferIfJustLoaded ) - { - Z_MorphMallocTag( pvDiskBufferIfJustLoaded, eTag ); - } - else - { - pvDiskBufferIfJustLoaded = Z_Malloc(iSize,eTag, qfalse ); + if (pvDiskBufferIfJustLoaded) { + Z_MorphMallocTag(pvDiskBufferIfJustLoaded, eTag); + } else { + pvDiskBufferIfJustLoaded = Z_Malloc(iSize, eTag, qfalse); } - ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; - ModelBin.iAllocSize = iSize; + ModelBin.pModelDiskImage = pvDiskBufferIfJustLoaded; + ModelBin.iAllocSize = iSize; int iCheckSum; - if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) - { - ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 + if (ri.FS_FileIsInPAK(sModelName, &iCheckSum) == 1) { + ModelBin.iPAKFileCheckSum = iCheckSum; // else ModelBin's constructor will leave it as -1 } *pqbAlreadyFound = qfalse; - } - else - { + } else { // if we already had this model entry, then re-register all the shaders it wanted... // /* @@ -324,8 +280,8 @@ void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, } } */ - //No. Bad. - *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary + // No. Bad. + *pqbAlreadyFound = qtrue; // tell caller not to re-Endian or re-Shader this binary } ModelBin.iLastLevelUsedOn = RE_RegisterMedia_GetLevel(); @@ -335,169 +291,143 @@ void *RE_RegisterServerModels_Malloc(int iSize, void *pvDiskBufferIfJustLoaded, // dump any models not being used by this level if we're running low on memory... // -static int GetModelDataAllocSize(void) -{ - return Z_MemSize( TAG_MODEL_MD3) + - Z_MemSize( TAG_MODEL_GLM) + - Z_MemSize( TAG_MODEL_GLA); -} +static int GetModelDataAllocSize(void) { return Z_MemSize(TAG_MODEL_MD3) + Z_MemSize(TAG_MODEL_GLM) + Z_MemSize(TAG_MODEL_GLA); } extern cvar_t *r_modelpoolmegs; // // return qtrue if at least one cached model was freed (which tells z_malloc()-fail recoveryt code to try again) // extern qboolean gbInsideRegisterModel; -qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) -{ +qboolean RE_RegisterModels_LevelLoadEnd(qboolean bDeleteEverythingNotUsedThisLevel /* = qfalse */) { qboolean bAtLeastoneModelFreed = qfalse; assert(CachedModels); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd():\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd():\n"); - if (gbInsideRegisterModel) - { - ri.Printf( PRINT_DEVELOPER, "(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); - } - else - { - int iLoadedModelBytes = GetModelDataAllocSize(); - const int iMaxModelBytes= r_modelpoolmegs->integer * 1024 * 1024; + if (gbInsideRegisterModel) { + ri.Printf(PRINT_DEVELOPER, "(Inside RE_RegisterModel (z_malloc recovery?), exiting...\n"); + } else { + int iLoadedModelBytes = GetModelDataAllocSize(); + const int iMaxModelBytes = r_modelpoolmegs->integer * 1024 * 1024; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end() && ( bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes ); ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); + itModel != CachedModels->end() && (bDeleteEverythingNotUsedThisLevel || iLoadedModelBytes > iMaxModelBytes);) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; qboolean bDeleteThis = qfalse; - if (bDeleteEverythingNotUsedThisLevel) - { + if (bDeleteEverythingNotUsedThisLevel) { bDeleteThis = (CachedModel.iLastLevelUsedOn != RE_RegisterMedia_GetLevel()) ? qtrue : qfalse; - } - else - { + } else { bDeleteThis = (CachedModel.iLastLevelUsedOn < RE_RegisterMedia_GetLevel()) ? qtrue : qfalse; } // if it wasn't used on this level, dump it... // - if (bDeleteThis) - { + if (bDeleteThis) { const char *psModelName = (*itModel).first.c_str(); - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Dumping \"%s\"", psModelName); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Dumping \"%s\"", psModelName); - #ifdef _DEBUG - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED ", used on lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif +#ifdef _DEBUG + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED ", used on lvl %d\n", CachedModel.iLastLevelUsedOn); +#endif if (CachedModel.pModelDiskImage) { Z_Free(CachedModel.pModelDiskImage); - //CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. + // CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. bAtLeastoneModelFreed = qtrue; } CachedModels->erase(itModel++); iLoadedModelBytes = GetModelDataAllocSize(); - } - else - { + } else { ++itModel; } } } - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "RE_RegisterModels_LevelLoadEnd(): Ok\n"); return bAtLeastoneModelFreed; } - - // scan through all loaded models and see if their PAK checksums are still valid with the current pure PAK lists, // dump any that aren't (so people can't cheat by using models with huge spikes that show through walls etc) // // (avoid using ri->xxxx stuff here in case running on dedicated) // -static void RE_RegisterModels_DumpNonPure(void) -{ - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure():\n"); +static void RE_RegisterModels_DumpNonPure(void) { + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure():\n"); - if(!CachedModels) { + if (!CachedModels) { return; } - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); /* empty */) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); /* empty */) { qboolean bEraseOccured = qfalse; - const char *psModelName = (*itModel).first.c_str(); + const char *psModelName = (*itModel).first.c_str(); CachedEndianedModelBinary_t &CachedModel = (*itModel).second; int iCheckSum = -1; int iInPak = ri.FS_FileIsInPAK(psModelName, &iCheckSum); - if (iInPak == -1 || iCheckSum != CachedModel.iPAKFileCheckSum) - { - if (Q_stricmp(sDEFAULT_GLA_NAME ".gla" , psModelName)) // don't dump "*default.gla", that's program internal anyway + if (iInPak == -1 || iCheckSum != CachedModel.iPAKFileCheckSum) { + if (Q_stricmp(sDEFAULT_GLA_NAME ".gla", psModelName)) // don't dump "*default.gla", that's program internal anyway { // either this is not from a PAK, or it's from a non-pure one, so ditch it... // - ri.Printf( PRINT_DEVELOPER, "Dumping none pure model \"%s\"", psModelName); + ri.Printf(PRINT_DEVELOPER, "Dumping none pure model \"%s\"", psModelName); if (CachedModel.pModelDiskImage) { Z_Free(CachedModel.pModelDiskImage); - //CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. + // CachedModel.pModelDiskImage = NULL; // REM for reference, erase() call below negates the need for it. } CachedModels->erase(itModel++); bEraseOccured = qtrue; } } - if ( !bEraseOccured ) - { + if (!bEraseOccured) { ++itModel; } } - ri.Printf( PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure(): Ok\n"); + ri.Printf(PRINT_DEVELOPER, "RE_RegisterModels_DumpNonPure(): Ok\n"); } -void RE_RegisterModels_Info_f( void ) -{ +void RE_RegisterModels_Info_f(void) { int iTotalBytes = 0; - if(!CachedModels) { - ri.Printf( PRINT_ALL, "%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + if (!CachedModels) { + ri.Printf(PRINT_ALL, "%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); return; } int iModels = CachedModels->size(); - int iModel = 0; + int iModel = 0; - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel,iModel++) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ++itModel, iModel++) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; - ri.Printf( PRINT_ALL, "%d/%d: \"%s\" (%d bytes)",iModel,iModels,(*itModel).first.c_str(),CachedModel.iAllocSize ); + ri.Printf(PRINT_ALL, "%d/%d: \"%s\" (%d bytes)", iModel, iModels, (*itModel).first.c_str(), CachedModel.iAllocSize); - #ifdef _DEBUG - ri.Printf( PRINT_ALL, ", lvl %d\n",CachedModel.iLastLevelUsedOn); - #endif +#ifdef _DEBUG + ri.Printf(PRINT_ALL, ", lvl %d\n", CachedModel.iLastLevelUsedOn); +#endif iTotalBytes += CachedModel.iAllocSize; } - ri.Printf( PRINT_ALL, "%d bytes total (%.2fMB)\n",iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); + ri.Printf(PRINT_ALL, "%d bytes total (%.2fMB)\n", iTotalBytes, (float)iTotalBytes / 1024.0f / 1024.0f); } - // (don't use ri->xxx functions since the renderer may not be running here)... // -static void RE_RegisterModels_DeleteAll(void) -{ - if(!CachedModels) { - return; //argh! +static void RE_RegisterModels_DeleteAll(void) { + if (!CachedModels) { + return; // argh! } - for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end(); ) - { + for (CachedModels_t::iterator itModel = CachedModels->begin(); itModel != CachedModels->end();) { CachedEndianedModelBinary_t &CachedModel = (*itModel).second; if (CachedModel.pModelDiskImage) { @@ -508,38 +438,32 @@ static void RE_RegisterModels_DeleteAll(void) } } - // do not use ri->xxx functions in here, the renderer may not be running (ie. if on a dedicated server)... // -static int giRegisterMedia_CurrentLevel=0; -void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) -{ +static int giRegisterMedia_CurrentLevel = 0; +void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) { // for development purposes we may want to ditch certain media just before loading a map... // - bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; -// bool bDeleteBSP = eForceReload == eForceReload_BSP || eForceReload == eForceReload_ALL; + bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; + // bool bDeleteBSP = eForceReload == eForceReload_BSP || eForceReload == eForceReload_ALL; - if (bDeleteModels) - { + if (bDeleteModels) { RE_RegisterModels_DeleteAll(); - } - else - { - if ( ri.Cvar_VariableIntegerValue( "sv_pure" ) ) - { + } else { + if (ri.Cvar_VariableIntegerValue("sv_pure")) { RE_RegisterModels_DumpNonPure(); } } tr.numBSPModels = 0; -// not used in MP codebase... -// -// if (bDeleteBSP) -// { -// CM_DeleteCachedMap(); - R_Images_DeleteLightMaps(); // always do this now, makes no real load time difference, and lets designers work ok -// } + // not used in MP codebase... + // + // if (bDeleteBSP) + // { + // CM_DeleteCachedMap(); + R_Images_DeleteLightMaps(); // always do this now, makes no real load time difference, and lets designers work ok + // } // at some stage I'll probably want to put some special logic here, like not incrementing the level number // when going into a map like "brig" or something, so returning to the previous level doesn't require an @@ -548,41 +472,34 @@ void RE_RegisterMedia_LevelLoadBegin(const char *psMapName, ForceReload_e eForce // only bump level number if we're not on the same level. // Note that this will hide uncached models, which is perhaps a bad thing?... // - static char sPrevMapName[MAX_QPATH]={0}; - if (Q_stricmp( psMapName,sPrevMapName )) - { - Q_strncpyz( sPrevMapName, psMapName, sizeof(sPrevMapName) ); + static char sPrevMapName[MAX_QPATH] = {0}; + if (Q_stricmp(psMapName, sPrevMapName)) { + Q_strncpyz(sPrevMapName, psMapName, sizeof(sPrevMapName)); giRegisterMedia_CurrentLevel++; } } -int RE_RegisterMedia_GetLevel(void) -{ - return giRegisterMedia_CurrentLevel; -} +int RE_RegisterMedia_GetLevel(void) { return giRegisterMedia_CurrentLevel; } // this is now only called by the client, so should be ok to dump media... // -void RE_RegisterMedia_LevelLoadEnd(void) -{ +void RE_RegisterMedia_LevelLoadEnd(void) { RE_RegisterModels_LevelLoadEnd(qfalse); RE_RegisterImages_LevelLoadEnd(); ri.SND_RegisterAudio_LevelLoadEnd(qfalse); -// RE_InitDissolve(); + // RE_InitDissolve(); ri.S_RestartMusic(); } - - /* ** R_GetModelByHandle */ -model_t *R_GetModelByHandle( qhandle_t index ) { - model_t *mod; +model_t *R_GetModelByHandle(qhandle_t index) { + model_t *mod; // out of range gets the defualt model - if ( index < 1 || index >= tr.numModels ) { + if (index < 1 || index >= tr.numModels) { return tr.models[0]; } @@ -596,14 +513,14 @@ model_t *R_GetModelByHandle( qhandle_t index ) { /* ** R_AllocModel */ -model_t *R_AllocModel( void ) { - model_t *mod; +model_t *R_AllocModel(void) { + model_t *mod; - if ( tr.numModels == MAX_MOD_KNOWN ) { + if (tr.numModels == MAX_MOD_KNOWN) { return NULL; } - mod = (struct model_s *)Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), h_low ); + mod = (struct model_s *)Hunk_Alloc(sizeof(*tr.models[tr.numModels]), h_low); mod->index = tr.numModels; tr.models[tr.numModels] = mod; tr.numModels++; @@ -620,33 +537,34 @@ Ghoul2 Insert Start return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } - hash &= (size-1); + hash &= (size - 1); return hash; } -void RE_InsertModelIntoHash(const char *name, model_t *mod) -{ - int hash; - modelHash_t *mh; +void RE_InsertModelIntoHash(const char *name, model_t *mod) { + int hash; + modelHash_t *mh; hash = generateHashValue(name, FILE_HASH_SIZE); // insert this file into the hash table so we can look it up faster later - mh = (modelHash_t*)Hunk_Alloc( sizeof( modelHash_t ), h_low ); + mh = (modelHash_t *)Hunk_Alloc(sizeof(modelHash_t), h_low); mh->next = mhHashTable[hash]; mh->handle = mod->index; @@ -657,43 +575,42 @@ void RE_InsertModelIntoHash(const char *name, model_t *mod) Ghoul2 Insert End */ -//rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. -//You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated -//server is running, which is the entire point of having these seperate functions. If anything major -//is changed in the non-server-only versions of these functions it would be wise to incorporate it -//here as well. +// rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. +// You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated +// server is running, which is the entire point of having these seperate functions. If anything major +// is changed in the non-server-only versions of these functions it would be wise to incorporate it +// here as well. /* ================= ServerLoadMDXA - load a Ghoul 2 animation file ================= */ -qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { +qboolean ServerLoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { - mdxaHeader_t *pinmodel, *mdxa; - int version; - int size; + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; #ifdef Q3_BIG_ENDIAN - int j, k, i; - mdxaSkel_t *boneInfo; - mdxaSkelOffsets_t *offsets; - int maxBoneIndex = 0; - mdxaCompQuatBone_t *pCompBonePool; - unsigned short *pwIn; - mdxaIndex_t *pIndex; - int tmp; + int j, k, i; + mdxaSkel_t *boneInfo; + mdxaSkelOffsets_t *offsets; + int maxBoneIndex = 0; + mdxaCompQuatBone_t *pCompBonePool; + unsigned short *pwIn; + mdxaIndex_t *pIndex; + int tmp; #endif - pinmodel = (mdxaHeader_t *)buffer; + pinmodel = (mdxaHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } @@ -702,17 +619,16 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool return qfalse; } - mod->type = MOD_MDXA; - mod->dataSize += size; + mod->type = MOD_MDXA; + mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxa = mod->mdxa = (mdxaHeader_t*) //Hunk_Alloc( size ); - RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mdxa = mod->mdxa = (mdxaHeader_t *) // Hunk_Alloc( size ); + RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -720,12 +636,12 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxa == buffer ); -// memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxa == buffer); + // memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing LL(mdxa->ident); LL(mdxa->version); - //LF(mdxa->fScale); + // LF(mdxa->fScale); LL(mdxa->numFrames); LL(mdxa->ofsFrames); LL(mdxa->numBones); @@ -734,36 +650,31 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool LL(mdxa->ofsEnd); } - if ( mdxa->numFrames < 1 ) { + if (mdxa->numFrames < 1) { return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + if (bAlreadyFound) { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... } #ifdef Q3_BIG_ENDIAN // swap the bone info offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); - for ( i = 0; i < mdxa->numBones ; i++ ) - { + for (i = 0; i < mdxa->numBones; i++) { LL(offsets->offsets[i]); - boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + boneInfo = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); LL(boneInfo->flags); LL(boneInfo->parent); - for ( j = 0; j < 3; j++ ) - { - for ( k = 0; k < 4; k++) - { + for (j = 0; j < 3; j++) { + for (k = 0; k < 4; k++) { LF(boneInfo->BasePoseMat.matrix[j][k]); LF(boneInfo->BasePoseMatInv.matrix[j][k]); } } LL(boneInfo->numChildren); - for (k=0; knumChildren; k++) - { + for (k = 0; k < boneInfo->numChildren; k++) { LL(boneInfo->children[k]); } } @@ -773,25 +684,24 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool // Find the largest index by iterating through all frames. // It is not guaranteed that the compressed bone pool resides // at the end of the file. - for(i = 0; i < mdxa->numFrames; i++){ - for(j = 0; j < mdxa->numBones; j++){ - k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex - pIndex = (mdxaIndex_t *) ((byte *)mdxa + mdxa->ofsFrames + k); - tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); + for (i = 0; i < mdxa->numFrames; i++) { + for (j = 0; j < mdxa->numBones; j++) { + k = (i * mdxa->numBones * 3) + (j * 3); // iOffsetToIndex + pIndex = (mdxaIndex_t *)((byte *)mdxa + mdxa->ofsFrames + k); + tmp = (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); - if(maxBoneIndex < tmp){ + if (maxBoneIndex < tmp) { maxBoneIndex = tmp; } } } // Swap the compressed bones. - pCompBonePool = (mdxaCompQuatBone_t *) ((byte *)mdxa + mdxa->ofsCompBonePool); - for ( i = 0 ; i <= maxBoneIndex ; i++ ) - { - pwIn = (unsigned short *) pCompBonePool[i].Comp; + pCompBonePool = (mdxaCompQuatBone_t *)((byte *)mdxa + mdxa->ofsCompBonePool); + for (i = 0; i <= maxBoneIndex; i++) { + pwIn = (unsigned short *)pCompBonePool[i].Comp; - for ( k = 0 ; k < 7 ; k++ ) + for (k = 0; k < 7; k++) LS(pwIn[k]); } #endif @@ -803,36 +713,34 @@ qboolean ServerLoadMDXA( model_t *mod, void *buffer, const char *mod_name, qbool ServerLoadMDXM - load a Ghoul 2 Mesh file ================= */ -qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i,l, j; - mdxmHeader_t *pinmodel, *mdxm; - mdxmLOD_t *lod; - mdxmSurface_t *surf; - int version; - int size; - //shader_t *sh; - mdxmSurfHierarchy_t *surfInfo; +qboolean ServerLoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + // shader_t *sh; + mdxmSurfHierarchy_t *surfInfo; #ifdef Q3_BIG_ENDIAN - int k; - mdxmTriangle_t *tri; - mdxmVertex_t *v; - int *boneRef; - mdxmLODSurfOffset_t *indexes; - mdxmVertexTexCoord_t *pTexCoords; - mdxmHierarchyOffsets_t *surfIndexes; + int k; + mdxmTriangle_t *tri; + mdxmVertex_t *v; + int *boneRef; + mdxmLODSurfOffset_t *indexes; + mdxmVertexTexCoord_t *pTexCoords; + mdxmHierarchyOffsets_t *surfIndexes; #endif - - pinmodel= (mdxmHeader_t *)buffer; + pinmodel = (mdxmHeader_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = (pinmodel->version); - size = (pinmodel->ofsEnd); + size = (pinmodel->ofsEnd); - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } @@ -841,17 +749,16 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool return qfalse; } - mod->type = MOD_MDXM; + mod->type = MOD_MDXM; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mdxm = mod->mdxm = (mdxmHeader_t*) //Hunk_Alloc( size ); - RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mdxm = mod->mdxm = (mdxmHeader_t *) // Hunk_Alloc( size ); + RE_RegisterServerModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -859,8 +766,8 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mdxm == buffer ); -// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + assert(mdxm == buffer); + // memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing LL(mdxm->ident); LL(mdxm->version); @@ -873,36 +780,32 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool } // first up, go load in the animation file we need that has the skeletal animation info for this model - mdxm->animIndex = RE_RegisterServerModel(va ("%s.gla",mdxm->animName)); - if (!mdxm->animIndex) - { + mdxm->animIndex = RE_RegisterServerModel(va("%s.gla", mdxm->animName)); + if (!mdxm->animIndex) { return qfalse; } - mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + mod->numLods = mdxm->numLODs - 1; // copy this up to the model for ease of use - it wil get inced after this. - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... } - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); + surfInfo = (mdxmSurfHierarchy_t *)((byte *)mdxm + mdxm->ofsSurfHierarchy); #ifdef Q3_BIG_ENDIAN surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); #endif - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surfInfo->numChildren); LL(surfInfo->parentIndex); // do all the children indexs - for (j=0; jnumChildren; j++) - { + for (j = 0; j < surfInfo->numChildren; j++) { LL(surfInfo->childIndexes[j]); } // We will not be using shaders on the server. - //sh = 0; + // sh = 0; // insert it in the surface list surfInfo->shaderIndex = 0; @@ -916,20 +819,18 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool #endif // find the next surface - surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); - } + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + (intptr_t)(&((mdxmSurfHierarchy_t *)0)->childIndexes[surfInfo->numChildren])); + } // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) - lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); - for ( l = 0 ; l < mdxm->numLODs ; l++) - { - int triCount = 0; + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + for (l = 0; l < mdxm->numLODs; l++) { + int triCount = 0; LL(lod->ofsEnd); // swap all the surfaces - surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); - for ( i = 0 ; i < mdxm->numSurfaces ; i++) - { + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + for (i = 0; i < mdxm->numSurfaces; i++) { LL(surf->thisSurfaceIndex); LL(surf->ofsHeader); LL(surf->numVerts); @@ -942,10 +843,10 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool triCount += surf->numTriangles; - if ( surf->numVerts > SHADER_MAX_VERTEXES ) { + if (surf->numVerts > SHADER_MAX_VERTEXES) { return qfalse; } - if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { + if (surf->numTriangles * 3 > SHADER_MAX_INDEXES) { return qfalse; } @@ -959,28 +860,24 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool LL(indexes->offsets[surf->thisSurfaceIndex]); // do all the bone reference data - boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); - for ( j = 0 ; j < surf->numBoneReferences ; j++ ) - { - LL(boneRef[j]); + boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + for (j = 0; j < surf->numBoneReferences; j++) { + LL(boneRef[j]); } - // swap all the triangles - tri = (mdxmTriangle_t *) ( (byte *)surf + surf->ofsTriangles ); - for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) - { + tri = (mdxmTriangle_t *)((byte *)surf + surf->ofsTriangles); + for (j = 0; j < surf->numTriangles; j++, tri++) { LL(tri->indexes[0]); LL(tri->indexes[1]); LL(tri->indexes[2]); } // swap all the vertexes - v = (mdxmVertex_t *) ( (byte *)surf + surf->ofsVerts ); - pTexCoords = (mdxmVertexTexCoord_t *) &v[surf->numVerts]; + v = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); + pTexCoords = (mdxmVertexTexCoord_t *)&v[surf->numVerts]; - for ( j = 0 ; j < surf->numVerts ; j++ ) - { + for (j = 0; j < surf->numVerts; j++) { LF(v->normal[0]); LF(v->normal[1]); LF(v->normal[2]); @@ -999,11 +896,11 @@ qboolean ServerLoadMDXM( model_t *mod, void *buffer, const char *mod_name, qbool #endif // find the next surface - surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); } // find the next LOD - lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); } return qtrue; @@ -1016,33 +913,33 @@ RE_RegisterServerModel Same as RE_RegisterModel, except used by the server to handle ghoul2 instance models. ==================== */ -qhandle_t RE_RegisterServerModel( const char *name ) { - model_t *mod; - unsigned *buf; - int lod; - int ident; - qboolean loaded; -// qhandle_t hModel; - int numLoaded; -/* -Ghoul2 Insert Start -*/ - int hash; - modelHash_t *mh; -/* -Ghoul2 Insert End -*/ - - if (!r_noServerGhoul2) - { //keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing though. - r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", 0, ""); - } - - if ( !name || !name[0] ) { +qhandle_t RE_RegisterServerModel(const char *name) { + model_t *mod; + unsigned *buf; + int lod; + int ident; + qboolean loaded; + // qhandle_t hModel; + int numLoaded; + /* + Ghoul2 Insert Start + */ + int hash; + modelHash_t *mh; + /* + Ghoul2 Insert End + */ + + if (!r_noServerGhoul2) { // keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing + // though. + r_noServerGhoul2 = ri.Cvar_Get("r_noserverghoul2", "0", 0, ""); + } + + if (!name || !name[0]) { return 0; } - if ( strlen( name ) >= MAX_QPATH ) { + if (strlen(name) >= MAX_QPATH) { return 0; } @@ -1051,25 +948,25 @@ Ghoul2 Insert End // // see if the model is already loaded // - for (mh=mhHashTable[hash]; mh; mh=mh->next) { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { if (Q_stricmp(mh->name, name) == 0) { return mh->handle; } } - if ( ( mod = R_AllocModel() ) == NULL ) { + if ((mod = R_AllocModel()) == NULL) { return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); // make sure the render thread is stopped R_IssuePendingRenderCommands(); int iLODStart = 0; - if (strstr (name, ".md3")) { - iLODStart = MD3_MAX_LODS-1; // this loads the md3s in reverse so they can be biased + if (strstr(name, ".md3")) { + iLODStart = MD3_MAX_LODS - 1; // this loads the md3s in reverse so they can be biased } mod->numLods = 0; @@ -1078,58 +975,55 @@ Ghoul2 Insert End // numLoaded = 0; - for ( lod = iLODStart; lod >= 0 ; lod-- ) { + for (lod = iLODStart; lod >= 0; lod--) { char filename[1024]; - strcpy( filename, name ); + strcpy(filename, name); - if ( lod != 0 ) { + if (lod != 0) { char namebuf[80]; - if ( strrchr( filename, '.' ) ) { - *strrchr( filename, '.' ) = 0; + if (strrchr(filename, '.')) { + *strrchr(filename, '.') = 0; } - sprintf( namebuf, "_%d.md3", lod ); - strcat( filename, namebuf ); + sprintf(namebuf, "_%d.md3", lod); + strcat(filename, namebuf); } qboolean bAlreadyCached = qfalse; - if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) - { + if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) { continue; } - //loadmodel = mod; // this seems to be fairly pointless + // loadmodel = mod; // this seems to be fairly pointless // important that from now on we pass 'filename' instead of 'name' to all model load functions, // because 'filename' accounts for any LOD mangling etc so guarantees unique lookups for yet more // internal caching... // ident = *(unsigned *)buf; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(ident); } - switch (ident) - { //if you're trying to register anything else as a model type on the server, you are out of luck + switch (ident) { // if you're trying to register anything else as a model type on the server, you are out of luck - case MDXA_IDENT: - loaded = ServerLoadMDXA( mod, buf, filename, bAlreadyCached ); - break; - case MDXM_IDENT: - loaded = ServerLoadMDXM( mod, buf, filename, bAlreadyCached ); - break; - default: - goto fail; + case MDXA_IDENT: + loaded = ServerLoadMDXA(mod, buf, filename, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = ServerLoadMDXM(mod, buf, filename, bAlreadyCached); + break; + default: + goto fail; } - if (!bAlreadyCached){ // important to check!! - ri.FS_FreeFile (buf); + if (!bAlreadyCached) { // important to check!! + ri.FS_FreeFile(buf); } - if ( !loaded ) { - if ( lod == 0 ) { + if (!loaded) { + if (lod == 0) { goto fail; } else { break; @@ -1140,23 +1034,23 @@ Ghoul2 Insert End } } - if ( numLoaded ) { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for ( lod-- ; lod >= 0 ; lod-- ) { + for (lod--; lod >= 0; lod--) { mod->numLods++; - mod->md3[lod] = mod->md3[lod+1]; + mod->md3[lod] = mod->md3[lod + 1]; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ - RE_InsertModelIntoHash(name, mod); - return mod->index; -/* -Ghoul2 Insert End -*/ + RE_InsertModelIntoHash(name, mod); + return mod->index; + /* + Ghoul2 Insert End + */ } fail: @@ -1167,7 +1061,6 @@ Ghoul2 Insert End return 0; } - /* ==================== RE_RegisterModel @@ -1180,40 +1073,40 @@ optimization to prevent disk rescanning if they are asked for again. ==================== */ -static qhandle_t RE_RegisterModel_Actual( const char *name ) { - model_t *mod; - unsigned *buf; - int lod; - int ident; - qboolean loaded; -// qhandle_t hModel; - int numLoaded; -/* -Ghoul2 Insert Start -*/ - int hash; - modelHash_t *mh; -/* -Ghoul2 Insert End -*/ - - if ( !name || !name[0] ) { - ri.Printf( PRINT_ALL, "RE_RegisterModel: NULL name\n" ); +static qhandle_t RE_RegisterModel_Actual(const char *name) { + model_t *mod; + unsigned *buf; + int lod; + int ident; + qboolean loaded; + // qhandle_t hModel; + int numLoaded; + /* + Ghoul2 Insert Start + */ + int hash; + modelHash_t *mh; + /* + Ghoul2 Insert End + */ + + if (!name || !name[0]) { + ri.Printf(PRINT_ALL, "RE_RegisterModel: NULL name\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Model name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Model name exceeds MAX_QPATH\n"); return 0; } -/* -Ghoul2 Insert Start -*/ -// if (!tr.registered) { -// ri.Printf( PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel (%s) called before ready!\n",name ); -// return 0; -// } + /* + Ghoul2 Insert Start + */ + // if (!tr.registered) { + // ri.Printf( PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel (%s) called before ready!\n",name ); + // return 0; + // } // // search the currently loaded models // @@ -1222,34 +1115,31 @@ Ghoul2 Insert Start // // see if the model is already loaded // - for (mh=mhHashTable[hash]; mh; mh=mh->next) { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { if (Q_stricmp(mh->name, name) == 0) { return mh->handle; } } -// for ( hModel = 1 ; hModel < tr.numModels; hModel++ ) { -// mod = tr.models[hModel]; -// if ( !strcmp( mod->name, name ) ) { -// if( mod->type == MOD_BAD ) { -// return 0; -// } -// return hModel; -// } -// } + // for ( hModel = 1 ; hModel < tr.numModels; hModel++ ) { + // mod = tr.models[hModel]; + // if ( !strcmp( mod->name, name ) ) { + // if( mod->type == MOD_BAD ) { + // return 0; + // } + // return hModel; + // } + // } - if (name[0] == '#') - { - char temp[MAX_QPATH]; + if (name[0] == '#') { + char temp[MAX_QPATH]; tr.numBSPModels++; RE_LoadWorldMap_Actual(va("maps/%s.bsp", name + 1), tr.bspModels[tr.numBSPModels - 1], tr.numBSPModels); Com_sprintf(temp, MAX_QPATH, "*%d-0", tr.numBSPModels); hash = generateHashValue(temp, FILE_HASH_SIZE); - for (mh=mhHashTable[hash]; mh; mh=mh->next) - { - if (Q_stricmp(mh->name, temp) == 0) - { + for (mh = mhHashTable[hash]; mh; mh = mh->next) { + if (Q_stricmp(mh->name, temp) == 0) { return mh->handle; } } @@ -1257,34 +1147,32 @@ Ghoul2 Insert Start return 0; } - if (name[0] == '*') - { // don't create a bad model for a bsp model - if (Q_stricmp(name, "*default.gla")) - { + if (name[0] == '*') { // don't create a bad model for a bsp model + if (Q_stricmp(name, "*default.gla")) { return 0; } } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // allocate a new model_t - if ( ( mod = R_AllocModel() ) == NULL ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + if ((mod = R_AllocModel()) == NULL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); return 0; } // only set the name after the model has been successfully loaded - Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + Q_strncpyz(mod->name, name, sizeof(mod->name)); // make sure the render thread is stopped R_IssuePendingRenderCommands(); int iLODStart = 0; - if (strstr (name, ".md3")) { - iLODStart = MD3_MAX_LODS-1; // this loads the md3s in reverse so they can be biased + if (strstr(name, ".md3")) { + iLODStart = MD3_MAX_LODS - 1; // this loads the md3s in reverse so they can be biased } mod->numLods = 0; @@ -1293,67 +1181,64 @@ Ghoul2 Insert End // numLoaded = 0; - for ( lod = iLODStart; lod >= 0 ; lod-- ) { + for (lod = iLODStart; lod >= 0; lod--) { char filename[1024]; - strcpy( filename, name ); + strcpy(filename, name); - if ( lod != 0 ) { + if (lod != 0) { char namebuf[80]; - if ( strrchr( filename, '.' ) ) { - *strrchr( filename, '.' ) = 0; + if (strrchr(filename, '.')) { + *strrchr(filename, '.') = 0; } - sprintf( namebuf, "_%d.md3", lod ); - strcat( filename, namebuf ); + sprintf(namebuf, "_%d.md3", lod); + strcat(filename, namebuf); } qboolean bAlreadyCached = qfalse; - if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) - { + if (!RE_RegisterModels_GetDiskFile(filename, (void **)&buf, &bAlreadyCached)) { continue; } - //loadmodel = mod; // this seems to be fairly pointless + // loadmodel = mod; // this seems to be fairly pointless // important that from now on we pass 'filename' instead of 'name' to all model load functions, // because 'filename' accounts for any LOD mangling etc so guarantees unique lookups for yet more // internal caching... // ident = *(unsigned *)buf; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(ident); } - switch (ident) - { - // if you add any new types of model load in this switch-case, tell me, - // or copy what I've done with the cache scheme (-ste). - // - case MDXA_IDENT: - loaded = R_LoadMDXA( mod, buf, filename, bAlreadyCached ); - break; + switch (ident) { + // if you add any new types of model load in this switch-case, tell me, + // or copy what I've done with the cache scheme (-ste). + // + case MDXA_IDENT: + loaded = R_LoadMDXA(mod, buf, filename, bAlreadyCached); + break; - case MDXM_IDENT: - loaded = R_LoadMDXM( mod, buf, filename, bAlreadyCached ); - break; + case MDXM_IDENT: + loaded = R_LoadMDXM(mod, buf, filename, bAlreadyCached); + break; - case MD3_IDENT: - loaded = R_LoadMD3( mod, lod, buf, filename, bAlreadyCached ); - break; + case MD3_IDENT: + loaded = R_LoadMD3(mod, lod, buf, filename, bAlreadyCached); + break; - default: - ri.Printf( PRINT_ALL, S_COLOR_YELLOW"RE_RegisterModel: unknown fileid for %s\n", filename); - goto fail; + default: + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel: unknown fileid for %s\n", filename); + goto fail; } - if (!bAlreadyCached){ // important to check!! - ri.FS_FreeFile (buf); + if (!bAlreadyCached) { // important to check!! + ri.FS_FreeFile(buf); } - if ( !loaded ) { - if ( lod == 0 ) { + if (!loaded) { + if (lod == 0) { goto fail; } else { break; @@ -1364,40 +1249,40 @@ Ghoul2 Insert End // if we have a valid model and are biased // so that we won't see any higher detail ones, // stop loading them - if ( lod <= r_lodbias->integer ) { + if (lod <= r_lodbias->integer) { break; } } } - if ( numLoaded ) { + if (numLoaded) { // duplicate into higher lod spots that weren't // loaded, in case the user changes r_lodbias on the fly - for ( lod-- ; lod >= 0 ; lod-- ) { + for (lod--; lod >= 0; lod--) { mod->numLods++; - mod->md3[lod] = mod->md3[lod+1]; + mod->md3[lod] = mod->md3[lod + 1]; } -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ #ifdef _DEBUG - if (r_noPrecacheGLA && r_noPrecacheGLA->integer && ident == MDXA_IDENT) - { //I expect this will cause leaks, but I don't care because it's a debugging utility. - return mod->index; - } + if (r_noPrecacheGLA && r_noPrecacheGLA->integer && + ident == MDXA_IDENT) { // I expect this will cause leaks, but I don't care because it's a debugging utility. + return mod->index; + } #endif - RE_InsertModelIntoHash(name, mod); - return mod->index; -/* -Ghoul2 Insert End -*/ + RE_InsertModelIntoHash(name, mod); + return mod->index; + /* + Ghoul2 Insert End + */ } #ifdef _DEBUG else { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW"RE_RegisterModel: couldn't load %s\n", name); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "RE_RegisterModel: couldn't load %s\n", name); } #endif @@ -1409,77 +1294,68 @@ Ghoul2 Insert End return 0; } - // wrapper function needed to avoid problems with mid-function returns so I can safely use this bool to tell the // z_malloc-fail recovery code whether it's safe to ditch any model caches... // qboolean gbInsideRegisterModel = qfalse; -qhandle_t RE_RegisterModel( const char *name ) -{ +qhandle_t RE_RegisterModel(const char *name) { const qboolean bWhatitwas = gbInsideRegisterModel; - gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! + gbInsideRegisterModel = qtrue; // !!!!!!!!!!!!!! - qhandle_t q = RE_RegisterModel_Actual( name ); + qhandle_t q = RE_RegisterModel_Actual(name); gbInsideRegisterModel = bWhatitwas; return q; } - - - /* ================= R_LoadMD3 ================= */ -static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { - int i, j; - md3Header_t *pinmodel; - md3Surface_t *surf; - int version; - int size; +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) { + int i, j; + md3Header_t *pinmodel; + md3Surface_t *surf; + int version; + int size; #ifdef Q3_BIG_ENDIAN - md3Frame_t *frame; - md3Triangle_t *tri; - md3St_t *st; - md3XyzNormal_t *xyz; - md3Tag_t *tag; + md3Frame_t *frame; + md3Triangle_t *tri; + md3St_t *st; + md3XyzNormal_t *xyz; + md3Tag_t *tag; #endif - - pinmodel= (md3Header_t *)buffer; + pinmodel = (md3Header_t *)buffer; // // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... // version = pinmodel->version; - size = pinmodel->ofsEnd; + size = pinmodel->ofsEnd; - if (!bAlreadyCached) - { + if (!bAlreadyCached) { LL(version); LL(size); } if (version != MD3_VERSION) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMD3: %s has wrong version (%i should be %i)\n", - mod_name, version, MD3_VERSION); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMD3: %s has wrong version (%i should be %i)\n", mod_name, version, MD3_VERSION); return qfalse; } - mod->type = MOD_MESH; + mod->type = MOD_MESH; mod->dataSize += size; qboolean bAlreadyFound = qfalse; - mod->md3[lod] = (md3Header_t *) //Hunk_Alloc( size ); - RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); + mod->md3[lod] = (md3Header_t *) // Hunk_Alloc( size ); + RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_MD3); - assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? - if (!bAlreadyFound) - { + if (!bAlreadyFound) { // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since // we've hijacked that memory block... @@ -1487,8 +1363,8 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ // Aaaargh. Kill me now... // bAlreadyCached = qtrue; - assert( mod->md3[lod] == buffer ); -// memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing + assert(mod->md3[lod] == buffer); + // memcpy( mod->md3[lod], buffer, size ); // and don't do this now, since it's the same thing LL(mod->md3[lod]->ident); LL(mod->md3[lod]->version); @@ -1501,22 +1377,21 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ LL(mod->md3[lod]->ofsEnd); } - if ( mod->md3[lod]->numFrames < 1 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_LoadMD3: %s has no frames\n", mod_name ); + if (mod->md3[lod]->numFrames < 1) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_LoadMD3: %s has no frames\n", mod_name); return qfalse; } - if (bAlreadyFound) - { - return qtrue; // All done. Stop, go no further, do not pass Go... + if (bAlreadyFound) { + return qtrue; // All done. Stop, go no further, do not pass Go... } #ifdef Q3_BIG_ENDIAN // swap all the frames - frame = (md3Frame_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsFrames ); - for ( i = 0 ; i < mod->md3[lod]->numFrames ; i++, frame++) { + frame = (md3Frame_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsFrames); + for (i = 0; i < mod->md3[lod]->numFrames; i++, frame++) { LF(frame->radius); - for ( j = 0 ; j < 3 ; j++ ) { + for (j = 0; j < 3; j++) { LF(frame->bounds[0][j]); LF(frame->bounds[1][j]); LF(frame->localOrigin[j]); @@ -1524,9 +1399,9 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ } // swap all the tags - tag = (md3Tag_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsTags ); - for ( i = 0 ; i < mod->md3[lod]->numTags * mod->md3[lod]->numFrames ; i++, tag++) { - for ( j = 0 ; j < 3 ; j++ ) { + tag = (md3Tag_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsTags); + for (i = 0; i < mod->md3[lod]->numTags * mod->md3[lod]->numFrames; i++, tag++) { + for (j = 0; j < 3; j++) { LF(tag->origin[j]); LF(tag->axis[0][j]); LF(tag->axis[1][j]); @@ -1536,75 +1411,74 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // swap all the surfaces - surf = (md3Surface_t *) ( (byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces ); - for ( i = 0 ; i < mod->md3[lod]->numSurfaces ; i++) { - LL(surf->flags); - LL(surf->numFrames); - LL(surf->numShaders); - LL(surf->numTriangles); - LL(surf->ofsTriangles); - LL(surf->numVerts); - LL(surf->ofsShaders); - LL(surf->ofsSt); - LL(surf->ofsXyzNormals); - LL(surf->ofsEnd); - - if ( surf->numVerts >= SHADER_MAX_VERTEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i verts on %s (%i)", - mod_name, SHADER_MAX_VERTEXES - 1, surf->name[0] ? surf->name : "a surface", surf->numVerts ); + surf = (md3Surface_t *)((byte *)mod->md3[lod] + mod->md3[lod]->ofsSurfaces); + for (i = 0; i < mod->md3[lod]->numSurfaces; i++) { + LL(surf->flags); + LL(surf->numFrames); + LL(surf->numShaders); + LL(surf->numTriangles); + LL(surf->ofsTriangles); + LL(surf->numVerts); + LL(surf->ofsShaders); + LL(surf->ofsSt); + LL(surf->ofsXyzNormals); + LL(surf->ofsEnd); + + if (surf->numVerts >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i verts on %s (%i)", mod_name, SHADER_MAX_VERTEXES - 1, surf->name[0] ? surf->name : "a surface", + surf->numVerts); } - if ( surf->numTriangles*3 >= SHADER_MAX_INDEXES ) { - Com_Error (ERR_DROP, "R_LoadMD3: %s has more than %i triangles on %s (%i)", - mod_name, ( SHADER_MAX_INDEXES / 3 ) - 1, surf->name[0] ? surf->name : "a surface", surf->numTriangles ); + if (surf->numTriangles * 3 >= SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "R_LoadMD3: %s has more than %i triangles on %s (%i)", mod_name, (SHADER_MAX_INDEXES / 3) - 1, + surf->name[0] ? surf->name : "a surface", surf->numTriangles); } // change to surface identifier surf->ident = SF_MD3; // lowercase the surface name so skin compares are faster - Q_strlwr( surf->name ); + Q_strlwr(surf->name); // strip off a trailing _1 or _2 // this is a crutch for q3data being a mess - j = strlen( surf->name ); - if ( j > 2 && surf->name[j-2] == '_' ) { - surf->name[j-2] = 0; + j = strlen(surf->name); + if (j > 2 && surf->name[j - 2] == '_') { + surf->name[j - 2] = 0; } - // register the shaders - md3Shader_t *shader; - shader = (md3Shader_t *) ( (byte *)surf + surf->ofsShaders ); - for ( j = 0 ; j < surf->numShaders ; j++, shader++ ) { - shader_t *sh; - - sh = R_FindShader( shader->name, lightmapsNone, stylesDefault, qtrue ); - if ( sh->defaultShader ) { + // register the shaders + md3Shader_t *shader; + shader = (md3Shader_t *)((byte *)surf + surf->ofsShaders); + for (j = 0; j < surf->numShaders; j++, shader++) { + shader_t *sh; + + sh = R_FindShader(shader->name, lightmapsNone, stylesDefault, qtrue); + if (sh->defaultShader) { shader->shaderIndex = 0; } else { shader->shaderIndex = sh->index; } RE_RegisterModels_StoreShaderRequest(mod_name, &shader->name[0], &shader->shaderIndex); - } + } #ifdef Q3_BIG_ENDIAN // swap all the triangles - tri = (md3Triangle_t *) ( (byte *)surf + surf->ofsTriangles ); - for ( j = 0 ; j < surf->numTriangles ; j++, tri++ ) { + tri = (md3Triangle_t *)((byte *)surf + surf->ofsTriangles); + for (j = 0; j < surf->numTriangles; j++, tri++) { LL(tri->indexes[0]); LL(tri->indexes[1]); LL(tri->indexes[2]); } // swap all the ST - st = (md3St_t *) ( (byte *)surf + surf->ofsSt ); - for ( j = 0 ; j < surf->numVerts ; j++, st++ ) { + st = (md3St_t *)((byte *)surf + surf->ofsSt); + for (j = 0; j < surf->numVerts; j++, st++) { LF(st->st[0]); LF(st->st[1]); } // swap all the XyzNormals - xyz = (md3XyzNormal_t *) ( (byte *)surf + surf->ofsXyzNormals ); - for ( j = 0 ; j < surf->numVerts * surf->numFrames ; j++, xyz++ ) - { + xyz = (md3XyzNormal_t *)((byte *)surf + surf->ofsXyzNormals); + for (j = 0; j < surf->numVerts * surf->numFrames; j++, xyz++) { LS(xyz->xyz[0]); LS(xyz->xyz[1]); LS(xyz->xyz[2]); @@ -1614,18 +1488,17 @@ static qboolean R_LoadMD3 (model_t *mod, int lod, void *buffer, const char *mod_ #endif // find the next surface - surf = (md3Surface_t *)( (byte *)surf + surf->ofsEnd ); + surf = (md3Surface_t *)((byte *)surf + surf->ofsEnd); } return qtrue; } - //============================================================================= /* ** RE_BeginRegistration */ -void RE_BeginRegistration( glconfig_t *glconfigOut ) { +void RE_BeginRegistration(glconfig_t *glconfigOut) { R_Init(); @@ -1633,10 +1506,10 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { R_IssuePendingRenderCommands(); - tr.viewCluster = -1; // force markleafs to regenerate + tr.viewCluster = -1; // force markleafs to regenerate // rww - 9-13-01 [1-26-01-sof2] - //R_ClearFlares(); + // R_ClearFlares(); RE_ClearScene(); @@ -1645,27 +1518,22 @@ void RE_BeginRegistration( glconfig_t *glconfigOut ) { // NOTE: this sucks, for some reason the first stretch pic is never drawn // without this we'd see a white flash on a level load because the very // first time the level shot would not be drawn -// RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0); + // RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0); } //============================================================================= -void R_SVModelInit() -{ - R_ModelInit(); -} +void R_SVModelInit() { R_ModelInit(); } /* =============== R_ModelInit =============== */ -void R_ModelInit( void ) -{ - model_t *mod; +void R_ModelInit(void) { + model_t *mod; - if(!CachedModels) - { + if (!CachedModels) { CachedModels = new CachedModels_t; } @@ -1678,8 +1546,7 @@ void R_ModelInit( void ) } extern void KillTheShaderHashTable(void); -void RE_HunkClearCrap(void) -{ //get your dirty sticky assets off me, you damn dirty hunk! +void RE_HunkClearCrap(void) { // get your dirty sticky assets off me, you damn dirty hunk! KillTheShaderHashTable(); tr.numModels = 0; memset(mhHashTable, 0, sizeof(mhHashTable)); @@ -1687,71 +1554,66 @@ void RE_HunkClearCrap(void) tr.numSkins = 0; } -void R_ModelFree(void) -{ - if(CachedModels) { +void R_ModelFree(void) { + if (CachedModels) { RE_RegisterModels_DeleteAll(); delete CachedModels; CachedModels = NULL; } } - - /* ================ R_Modellist_f ================ */ -void R_Modellist_f( void ) { - int i, j; - model_t *mod; - int total; - int lods; +void R_Modellist_f(void) { + int i, j; + model_t *mod; + int total; + int lods; total = 0; - for ( i = 1 ; i < tr.numModels; i++ ) { + for (i = 1; i < tr.numModels; i++) { mod = tr.models[i]; lods = 1; - for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) { - if ( mod->md3[j] && mod->md3[j] != mod->md3[j-1] ) { + for (j = 1; j < MD3_MAX_LODS; j++) { + if (mod->md3[j] && mod->md3[j] != mod->md3[j - 1]) { lods++; } } - ri.Printf( PRINT_ALL, "%8i : (%i) %s\n",mod->dataSize, lods, mod->name ); + ri.Printf(PRINT_ALL, "%8i : (%i) %s\n", mod->dataSize, lods, mod->name); total += mod->dataSize; } - ri.Printf( PRINT_ALL, "%8i : Total models\n", total ); + ri.Printf(PRINT_ALL, "%8i : Total models\n", total); -#if 0 // not working right with new hunk +#if 0 // not working right with new hunk if ( tr.world ) { ri.Printf( PRINT_ALL, "\n%8i : %s\n", tr.world->dataSize, tr.world->name ); } #endif } - //============================================================================= - /* ================ R_GetTag ================ */ -static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { - md3Tag_t *tag; - int i; +static md3Tag_t *R_GetTag(md3Header_t *mod, int frame, const char *tagName) { + md3Tag_t *tag; + int i; - if ( frame >= mod->numFrames ) { + if (frame >= mod->numFrames) { // it is possible to have a bad frame while changing models, so don't error frame = mod->numFrames - 1; } tag = (md3Tag_t *)((byte *)mod + mod->ofsTags) + frame * mod->numTags; - for ( i = 0 ; i < mod->numTags ; i++, tag++ ) { - if ( !strcmp( tag->name, tagName ) ) { - return tag; // found it + for (i = 0; i < mod->numTags; i++, tag++) { + if (!strcmp(tag->name, tagName)) { + return tag; // found it } } @@ -1763,74 +1625,70 @@ static md3Tag_t *R_GetTag( md3Header_t *mod, int frame, const char *tagName ) { R_LerpTag ================ */ -int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, - float frac, const char *tagName ) { - md3Tag_t *start, *end; - int i; - float frontLerp, backLerp; - model_t *model; - - model = R_GetModelByHandle( handle ); - if ( !model->md3[0] ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); +int R_LerpTag(orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, float frac, const char *tagName) { + md3Tag_t *start, *end; + int i; + float frontLerp, backLerp; + model_t *model; + + model = R_GetModelByHandle(handle); + if (!model->md3[0]) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } - start = R_GetTag( model->md3[0], startFrame, tagName ); - end = R_GetTag( model->md3[0], endFrame, tagName ); - if ( !start || !end ) { - AxisClear( tag->axis ); - VectorClear( tag->origin ); + start = R_GetTag(model->md3[0], startFrame, tagName); + end = R_GetTag(model->md3[0], endFrame, tagName); + if (!start || !end) { + AxisClear(tag->axis); + VectorClear(tag->origin); return qfalse; } frontLerp = frac; backLerp = 1.0f - frac; - for ( i = 0 ; i < 3 ; i++ ) { - tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; - tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; - tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; - tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; + for (i = 0; i < 3; i++) { + tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; + tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; + tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; + tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; } - VectorNormalize( tag->axis[0] ); - VectorNormalize( tag->axis[1] ); - VectorNormalize( tag->axis[2] ); + VectorNormalize(tag->axis[0]); + VectorNormalize(tag->axis[1]); + VectorNormalize(tag->axis[2]); return qtrue; } - /* ==================== R_ModelBounds ==================== */ -void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) { - model_t *model; - md3Header_t *header; - md3Frame_t *frame; +void R_ModelBounds(qhandle_t handle, vec3_t mins, vec3_t maxs) { + model_t *model; + md3Header_t *header; + md3Frame_t *frame; - model = R_GetModelByHandle( handle ); + model = R_GetModelByHandle(handle); - if ( model->bmodel ) { - VectorCopy( model->bmodel->bounds[0], mins ); - VectorCopy( model->bmodel->bounds[1], maxs ); + if (model->bmodel) { + VectorCopy(model->bmodel->bounds[0], mins); + VectorCopy(model->bmodel->bounds[1], maxs); return; } - if ( !model->md3[0] ) { - VectorClear( mins ); - VectorClear( maxs ); + if (!model->md3[0]) { + VectorClear(mins); + VectorClear(maxs); return; } header = model->md3[0]; - frame = (md3Frame_t *)( (byte *)header + header->ofsFrames ); + frame = (md3Frame_t *)((byte *)header + header->ofsFrames); - VectorCopy( frame->bounds[0], mins ); - VectorCopy( frame->bounds[1], maxs ); + VectorCopy(frame->bounds[0], mins); + VectorCopy(frame->bounds[1], maxs); } - - diff --git a/codemp/rd-vanilla/tr_quicksprite.cpp b/codemp/rd-vanilla/tr_quicksprite.cpp index add8d2d2cb..88026c924b 100644 --- a/codemp/rd-vanilla/tr_quicksprite.cpp +++ b/codemp/rd-vanilla/tr_quicksprite.cpp @@ -27,59 +27,44 @@ along with this program; if not, see . #include "tr_quicksprite.h" -void R_BindAnimatedImage( textureBundle_t *bundle ); - +void R_BindAnimatedImage(textureBundle_t *bundle); ////////////////////////////////////////////////////////////////////// // Singleton System ////////////////////////////////////////////////////////////////////// CQuickSpriteSystem SQuickSprite; - ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// -CQuickSpriteSystem::CQuickSpriteSystem() : - mTexBundle(NULL), - mGLStateBits(0), - mFogIndex(-1), - mUseFog(qfalse), - mNextVert(0) -{ +CQuickSpriteSystem::CQuickSpriteSystem() : mTexBundle(NULL), mGLStateBits(0), mFogIndex(-1), mUseFog(qfalse), mNextVert(0) { int i; - memset( mVerts, 0, sizeof( mVerts ) ); - memset( mFogTextureCoords, 0, sizeof( mFogTextureCoords ) ); - memset( mColors, 0, sizeof( mColors ) ); + memset(mVerts, 0, sizeof(mVerts)); + memset(mFogTextureCoords, 0, sizeof(mFogTextureCoords)); + memset(mColors, 0, sizeof(mColors)); - for (i=0; iinteger != 2 || mFogIndex != tr.world->globalFog)) - { + // only for software fog pass (global soft/volumetric) -rww + if (mUseFog && (r_drawfog->integer != 2 || mFogIndex != tr.world->globalFog)) { fog_t *fog = tr.world->fogs + mFogIndex; // // render the fog pass // - GL_Bind( tr.fogImage ); - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL ); + GL_Bind(tr.fogImage); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL); // // set arrays and lock // - qglTexCoordPointer( 2, GL_FLOAT, 0, mFogTextureCoords); -// qglEnableClientState( GL_TEXTURE_COORD_ARRAY); // Done above + qglTexCoordPointer(2, GL_FLOAT, 0, mFogTextureCoords); + // qglEnableClientState( GL_TEXTURE_COORD_ARRAY); // Done above - qglDisableClientState( GL_COLOR_ARRAY ); + qglDisableClientState(GL_COLOR_ARRAY); qglColor4ubv((GLubyte *)&fog->colorInt); -// qglVertexPointer (3, GL_FLOAT, 16, mVerts); // Done above + // qglVertexPointer (3, GL_FLOAT, 16, mVerts); // Done above qglDrawArrays(GL_QUADS, 0, mNextVert); @@ -157,61 +140,48 @@ void CQuickSpriteSystem::Flush(void) // // unlock arrays // - if (qglUnlockArraysEXT) - { + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } - mNextVert=0; + mNextVert = 0; } - -void CQuickSpriteSystem::StartGroup(textureBundle_t *bundle, uint32_t glbits, int fogIndex ) -{ +void CQuickSpriteSystem::StartGroup(textureBundle_t *bundle, uint32_t glbits, int fogIndex) { mNextVert = 0; mTexBundle = bundle; mGLStateBits = glbits; - if (fogIndex != -1) - { + if (fogIndex != -1) { mUseFog = qtrue; mFogIndex = fogIndex; - } - else - { + } else { mUseFog = qfalse; } qglDisable(GL_CULL_FACE); } - -void CQuickSpriteSystem::EndGroup(void) -{ +void CQuickSpriteSystem::EndGroup(void) { Flush(); - qglColor4ub(255,255,255,255); + qglColor4ub(255, 255, 255, 255); qglEnable(GL_CULL_FACE); } - - - -void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) -{ +void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) { float *curcoord; float *curfogtexcoord; uint32_t *curcolor; - if (mNextVert>SHADER_MAX_VERTEXES-4) - { + if (mNextVert > SHADER_MAX_VERTEXES - 4) { Flush(); } curcoord = mVerts[mNextVert]; // This is 16*sizeof(float) because, pointdata comes from a float[16] - memcpy(curcoord, pointdata, 16*sizeof(float)); + memcpy(curcoord, pointdata, 16 * sizeof(float)); // Set up color curcolor = &mColors[mNextVert]; @@ -220,8 +190,7 @@ void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) *curcolor++ = *(uint32_t *)color; *curcolor++ = *(uint32_t *)color; - if (fog) - { + if (fog) { curfogtexcoord = &mFogTextureCoords[mNextVert][0]; *curfogtexcoord++ = fog[0]; *curfogtexcoord++ = fog[1]; @@ -235,12 +204,10 @@ void CQuickSpriteSystem::Add(float *pointdata, color4ub_t color, vec2_t fog) *curfogtexcoord++ = fog[0]; *curfogtexcoord++ = fog[1]; - mUseFog=qtrue; - } - else - { - mUseFog=qfalse; + mUseFog = qtrue; + } else { + mUseFog = qfalse; } - mNextVert+=4; + mNextVert += 4; } diff --git a/codemp/rd-vanilla/tr_scene.cpp b/codemp/rd-vanilla/tr_scene.cpp index 9c0025485a..60b2a81318 100644 --- a/codemp/rd-vanilla/tr_scene.cpp +++ b/codemp/rd-vanilla/tr_scene.cpp @@ -28,24 +28,24 @@ along with this program; if not, see . #include "qcommon/matcomp.h" #include "qcommon/disablewarnings.h" -static int r_firstSceneDrawSurf; +static int r_firstSceneDrawSurf; -static int r_numdlights; -static int r_firstSceneDlight; +static int r_numdlights; +static int r_firstSceneDlight; -static int r_numentities; -static int r_firstSceneEntity; -static int r_numminientities; -static int r_firstSceneMiniEntity; -static int refEntParent = -1; +static int r_numentities; +static int r_firstSceneEntity; +static int r_numminientities; +static int r_firstSceneMiniEntity; +static int refEntParent = -1; -static int r_numpolys; -static int r_firstScenePoly; +static int r_numpolys; +static int r_firstScenePoly; -static int r_numpolyverts; +static int r_numpolyverts; -int skyboxportal; -int drawskyboxportal; +int skyboxportal; +int drawskyboxportal; /* ==================== @@ -53,7 +53,7 @@ R_InitNextFrame ==================== */ -void R_InitNextFrame( void ) { +void R_InitNextFrame(void) { backEndData->commands.used = 0; r_firstSceneDrawSurf = 0; @@ -73,14 +73,13 @@ void R_InitNextFrame( void ) { r_numpolyverts = 0; } - /* ==================== RE_ClearScene ==================== */ -void RE_ClearScene( void ) { +void RE_ClearScene(void) { r_firstSceneDlight = r_numdlights; r_firstSceneEntity = r_numentities; r_firstScenePoly = r_numpolys; @@ -103,17 +102,17 @@ R_AddPolygonSurfaces Adds all the scene's polys into this view's drawsurf list ===================== */ -void R_AddPolygonSurfaces( void ) { - int i; - shader_t *sh; - srfPoly_t *poly; +void R_AddPolygonSurfaces(void) { + int i; + shader_t *sh; + srfPoly_t *poly; tr.currentEntityNum = REFENTITYNUM_WORLD; tr.shiftedEntityNum = tr.currentEntityNum << QSORT_REFENTITYNUM_SHIFT; - for ( i = 0, poly = tr.refdef.polys; i < tr.refdef.numPolys ; i++, poly++ ) { - sh = R_GetShaderByHandle( poly->hShader ); - R_AddDrawSurf( (surfaceType_t *)poly, sh, poly->fogIndex, qfalse ); + for (i = 0, poly = tr.refdef.polys; i < tr.refdef.numPolys; i++, poly++) { + sh = R_GetShaderByHandle(poly->hShader); + R_AddDrawSurf((surfaceType_t *)poly, sh, poly->fogIndex, qfalse); } } @@ -123,31 +122,31 @@ RE_AddPolyToScene ===================== */ -void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys ) { - srfPoly_t *poly; - int i, j; - int fogIndex; - fog_t *fog; - vec3_t bounds[2]; - - if ( !tr.registered ) { +void RE_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys) { + srfPoly_t *poly; + int i, j; + int fogIndex; + fog_t *fog; + vec3_t bounds[2]; + + if (!tr.registered) { return; } - if ( !hShader ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: NULL poly shader\n"); + if (!hShader) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: NULL poly shader\n"); return; } - for ( j = 0; j < numPolys; j++ ) { - if ( r_numpolyverts + numVerts >= max_polyverts || r_numpolys >= max_polys ) { - /* - NOTE TTimo this was initially a PRINT_WARNING - but it happens a lot with high fighting scenes and particles - since we don't plan on changing the const and making for room for those effects - simply cut this message to developer only - */ - ri.Printf( PRINT_DEVELOPER, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); + for (j = 0; j < numPolys; j++) { + if (r_numpolyverts + numVerts >= max_polyverts || r_numpolys >= max_polys) { + /* + NOTE TTimo this was initially a PRINT_WARNING + but it happens a lot with high fighting scenes and particles + since we don't plan on changing the const and making for room for those effects + simply cut this message to developer only + */ + ri.Printf(PRINT_DEVELOPER, S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); return; } @@ -157,38 +156,34 @@ void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts poly->numVerts = numVerts; poly->verts = &backEndData->polyVerts[r_numpolyverts]; - memcpy( poly->verts, &verts[numVerts*j], numVerts * sizeof( *verts ) ); + memcpy(poly->verts, &verts[numVerts * j], numVerts * sizeof(*verts)); // done. r_numpolys++; r_numpolyverts += numVerts; // if no world is loaded - if ( tr.world == NULL ) { + if (tr.world == NULL) { fogIndex = 0; } // see if it is in a fog volume - else if ( tr.world->numfogs == 1 ) { + else if (tr.world->numfogs == 1) { fogIndex = 0; } else { // find which fog volume the poly is in - VectorCopy( poly->verts[0].xyz, bounds[0] ); - VectorCopy( poly->verts[0].xyz, bounds[1] ); - for ( i = 1 ; i < poly->numVerts ; i++ ) { - AddPointToBounds( poly->verts[i].xyz, bounds[0], bounds[1] ); + VectorCopy(poly->verts[0].xyz, bounds[0]); + VectorCopy(poly->verts[0].xyz, bounds[1]); + for (i = 1; i < poly->numVerts; i++) { + AddPointToBounds(poly->verts[i].xyz, bounds[0], bounds[1]); } - for ( fogIndex = 1 ; fogIndex < tr.world->numfogs ; fogIndex++ ) { + for (fogIndex = 1; fogIndex < tr.world->numfogs; fogIndex++) { fog = &tr.world->fogs[fogIndex]; - if ( bounds[1][0] >= fog->bounds[0][0] - && bounds[1][1] >= fog->bounds[0][1] - && bounds[1][2] >= fog->bounds[0][2] - && bounds[0][0] <= fog->bounds[1][0] - && bounds[0][1] <= fog->bounds[1][1] - && bounds[0][2] <= fog->bounds[1][2] ) { + if (bounds[1][0] >= fog->bounds[0][0] && bounds[1][1] >= fog->bounds[0][1] && bounds[1][2] >= fog->bounds[0][2] && + bounds[0][0] <= fog->bounds[1][0] && bounds[0][1] <= fog->bounds[1][1] && bounds[0][2] <= fog->bounds[1][2]) { break; } } - if ( fogIndex == tr.world->numfogs ) { + if (fogIndex == tr.world->numfogs) { fogIndex = 0; } } @@ -196,22 +191,20 @@ void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts } } - //================================================================================= - /* ===================== RE_AddRefEntityToScene ===================== */ -void RE_AddRefEntityToScene( const refEntity_t *ent ) { - if ( !tr.registered ) { +void RE_AddRefEntityToScene(const refEntity_t *ent) { + if (!tr.registered) { return; } - if ( r_numentities >= MAX_REFENTITIES ) { + if (r_numentities >= MAX_REFENTITIES) { ri.Printf(PRINT_DEVELOPER, "RE_AddRefEntityToScene: Dropping refEntity, reached MAX_REFENTITIES\n"); return; } @@ -227,32 +220,28 @@ void RE_AddRefEntityToScene( const refEntity_t *ent ) { assert(!ent || ent->renderfx >= 0); - if (ent->reType == RT_ENT_CHAIN) - { //minirefents must die. + if (ent->reType == RT_ENT_CHAIN) { // minirefents must die. return; } #ifdef _DEBUG - if (ent->reType == RT_MODEL) - { + if (ent->reType == RT_MODEL) { assert(ent->hModel || ent->ghoul2 || ent->customShader); } #endif - if ( (int)ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) { - Com_Error( ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType ); + if ((int)ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE) { + Com_Error(ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType); } backEndData->entities[r_numentities].e = *ent; backEndData->entities[r_numentities].lightingCalculated = qfalse; - if (ent->ghoul2) - { - CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->ghoul2); + if (ent->ghoul2) { + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->ghoul2); - if (!ghoul2[0].mModel) - { - ri.Printf( PRINT_ALL, "Your ghoul2 instance has no model!\n"); + if (!ghoul2[0].mModel) { + ri.Printf(PRINT_ALL, "Your ghoul2 instance has no model!\n"); } } @@ -266,13 +255,12 @@ void RE_AddRefEntityToScene( const refEntity_t *ent ) { else { */ - refEntParent = -1; + refEntParent = -1; //} r_numentities++; } - /************************************************************************************************ * RE_AddMiniRefEntityToScene * * Adds a mini ref ent to the scene. If the input parameter is null, it signifies the end * @@ -286,42 +274,37 @@ void RE_AddRefEntityToScene( const refEntity_t *ent ) { * none * * * ************************************************************************************************/ -void RE_AddMiniRefEntityToScene( const miniRefEntity_t *ent ) -{ +void RE_AddMiniRefEntityToScene(const miniRefEntity_t *ent) { #if 0 refEntity_t *parent; #endif - if ( !tr.registered ) - { + if (!tr.registered) { return; } - if (!ent) - { + if (!ent) { refEntParent = -1; return; } -#if 1 //i hate you minirefent! - refEntity_t tempEnt; +#if 1 // i hate you minirefent! + refEntity_t tempEnt; memcpy(&tempEnt, ent, sizeof(*ent)); - memset(((char *)&tempEnt)+sizeof(*ent), 0, sizeof(tempEnt) - sizeof(*ent)); + memset(((char *)&tempEnt) + sizeof(*ent), 0, sizeof(tempEnt) - sizeof(*ent)); RE_AddRefEntityToScene(&tempEnt); #else - if ( ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) - { - Com_Error( ERR_DROP, "RE_AddMiniRefEntityToScene: bad reType %i", ent->reType ); + if (ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE) { + Com_Error(ERR_DROP, "RE_AddMiniRefEntityToScene: bad reType %i", ent->reType); } - if (!r_numentities || refEntParent == -1 || r_numminientities >= MAX_MINI_ENTITIES) - { //rww - add it as a refent also if we run out of minis -// Com_Error( ERR_DROP, "RE_AddMiniRefEntityToScene: mini without parent ref ent"); - refEntity_t tempEnt; + if (!r_numentities || refEntParent == -1 || r_numminientities >= MAX_MINI_ENTITIES) { // rww - add it as a refent also if we run out of minis + // Com_Error( ERR_DROP, "RE_AddMiniRefEntityToScene: mini without parent ref ent"); + refEntity_t tempEnt; memcpy(&tempEnt, ent, sizeof(*ent)); - memset(((char *)&tempEnt)+sizeof(*ent), 0, sizeof(tempEnt) - sizeof(*ent)); + memset(((char *)&tempEnt) + sizeof(*ent), 0, sizeof(tempEnt) - sizeof(*ent)); RE_AddRefEntityToScene(&tempEnt); return; } @@ -340,20 +323,20 @@ RE_AddDynamicLightToScene ===================== */ -void RE_AddDynamicLightToScene( const vec3_t org, float intensity, float r, float g, float b, int additive ) { - dlight_t *dl; +void RE_AddDynamicLightToScene(const vec3_t org, float intensity, float r, float g, float b, int additive) { + dlight_t *dl; - if ( !tr.registered ) { + if (!tr.registered) { return; } - if ( r_numdlights >= MAX_DLIGHTS ) { + if (r_numdlights >= MAX_DLIGHTS) { return; } - if ( intensity <= 0 ) { + if (intensity <= 0) { return; } dl = &backEndData->dlights[r_numdlights++]; - VectorCopy (org, dl->origin); + VectorCopy(org, dl->origin); dl->radius = intensity; dl->color[0] = r; dl->color[1] = g; @@ -367,9 +350,7 @@ RE_AddLightToScene ===================== */ -void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - RE_AddDynamicLightToScene( org, intensity, r, g, b, qfalse ); -} +void RE_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { RE_AddDynamicLightToScene(org, intensity, r, g, b, qfalse); } /* ===================== @@ -377,9 +358,7 @@ RE_AddAdditiveLightToScene ===================== */ -void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - RE_AddDynamicLightToScene( org, intensity, r, g, b, qtrue ); -} +void RE_AddAdditiveLightToScene(const vec3_t org, float intensity, float r, float g, float b) { RE_AddDynamicLightToScene(org, intensity, r, g, b, qtrue); } /* @@@@@@@@@@@@@@@@@@@@@ @@ -394,27 +373,27 @@ to handle mirrors, */ void RE_RenderWorldEffects(void); void RE_RenderAutoMap(void); -void RE_RenderScene( const refdef_t *fd ) { - viewParms_t parms; - int startTime; - static int lastTime = 0; +void RE_RenderScene(const refdef_t *fd) { + viewParms_t parms; + int startTime; + static int lastTime = 0; - if ( !tr.registered ) { + if (!tr.registered) { return; } - GLimp_LogComment( "====== RE_RenderScene =====\n" ); + GLimp_LogComment("====== RE_RenderScene =====\n"); - if ( r_norefresh->integer ) { + if (r_norefresh->integer) { return; } - startTime = ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ); + startTime = ri.Milliseconds() * ri.Cvar_VariableValue("timescale"); - if (!tr.world && !( fd->rdflags & RDF_NOWORLDMODEL ) ) { - Com_Error (ERR_DROP, "R_RenderScene: NULL worldmodel"); + if (!tr.world && !(fd->rdflags & RDF_NOWORLDMODEL)) { + Com_Error(ERR_DROP, "R_RenderScene: NULL worldmodel"); } - memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) ); + memcpy(tr.refdef.text, fd->text, sizeof(tr.refdef.text)); tr.refdef.x = fd->x; tr.refdef.y = fd->y; @@ -423,40 +402,31 @@ void RE_RenderScene( const refdef_t *fd ) { tr.refdef.fov_x = fd->fov_x; tr.refdef.fov_y = fd->fov_y; - VectorCopy( fd->vieworg, tr.refdef.vieworg ); - VectorCopy( fd->viewaxis[0], tr.refdef.viewaxis[0] ); - VectorCopy( fd->viewaxis[1], tr.refdef.viewaxis[1] ); - VectorCopy( fd->viewaxis[2], tr.refdef.viewaxis[2] ); + VectorCopy(fd->vieworg, tr.refdef.vieworg); + VectorCopy(fd->viewaxis[0], tr.refdef.viewaxis[0]); + VectorCopy(fd->viewaxis[1], tr.refdef.viewaxis[1]); + VectorCopy(fd->viewaxis[2], tr.refdef.viewaxis[2]); tr.refdef.time = fd->time; tr.refdef.frametime = fd->time - lastTime; - if (fd->rdflags & RDF_SKYBOXPORTAL) - { + if (fd->rdflags & RDF_SKYBOXPORTAL) { skyboxportal = 1; - } - else - { + } else { // pasted this from SP // cdr - only change last time for the real render, not the portal lastTime = fd->time; } - if (fd->rdflags & RDF_DRAWSKYBOX) - { + if (fd->rdflags & RDF_DRAWSKYBOX) { drawskyboxportal = 1; - } - else - { + } else { drawskyboxportal = 0; } - if (tr.refdef.frametime > 500) - { + if (tr.refdef.frametime > 500) { tr.refdef.frametime = 500; - } - else if (tr.refdef.frametime < 0) - { + } else if (tr.refdef.frametime < 0) { tr.refdef.frametime = 0; } tr.refdef.rdflags = fd->rdflags; @@ -464,24 +434,23 @@ void RE_RenderScene( const refdef_t *fd ) { // copy the areamask data over and note if it has changed, which // will force a reset of the visible leafs even if the view hasn't moved tr.refdef.areamaskModified = qfalse; - if ( ! (tr.refdef.rdflags & RDF_NOWORLDMODEL) ) { - int areaDiff; - int i; + if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) { + int areaDiff; + int i; // compare the area bits areaDiff = 0; - for (i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++) { + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { areaDiff |= ((int *)tr.refdef.areamask)[i] ^ ((int *)fd->areamask)[i]; ((int *)tr.refdef.areamask)[i] = ((int *)fd->areamask)[i]; } - if ( areaDiff ) { + if (areaDiff) { // a door just opened or something tr.refdef.areamaskModified = qtrue; } } - // derived info tr.refdef.floatTime = tr.refdef.time * 0.001f; @@ -498,9 +467,8 @@ void RE_RenderScene( const refdef_t *fd ) { // Add the decals here because decals add polys and we need to ensure // that the polys are added before the the renderer is prepared - if ( !(tr.refdef.rdflags & RDF_NOWORLDMODEL) ) - { - R_AddDecals ( ); + if (!(tr.refdef.rdflags & RDF_NOWORLDMODEL)) { + R_AddDecals(); } tr.refdef.numPolys = r_numpolys - r_firstScenePoly; @@ -508,8 +476,7 @@ void RE_RenderScene( const refdef_t *fd ) { // turn off dynamic lighting globally by clearing all the // dlights if it needs to be disabled or if vertex lighting is enabled - if ( r_dynamiclight->integer == 0 || - r_vertexLight->integer == 1 ) { + if (r_dynamiclight->integer == 0 || r_vertexLight->integer == 1) { tr.refdef.num_dlights = 0; } @@ -527,9 +494,9 @@ void RE_RenderScene( const refdef_t *fd ) { // The refdef takes 0-at-the-top y coordinates, so // convert to GL's 0-at-the-bottom space // - memset( &parms, 0, sizeof( parms ) ); + memset(&parms, 0, sizeof(parms)); parms.viewportX = tr.refdef.x; - parms.viewportY = glConfig.vidHeight - ( tr.refdef.y + tr.refdef.height ); + parms.viewportY = glConfig.vidHeight - (tr.refdef.y + tr.refdef.height); parms.viewportWidth = tr.refdef.width; parms.viewportHeight = tr.refdef.height; parms.isPortal = qfalse; @@ -537,14 +504,14 @@ void RE_RenderScene( const refdef_t *fd ) { parms.fovX = tr.refdef.fov_x; parms.fovY = tr.refdef.fov_y; - VectorCopy( fd->vieworg, parms.ori.origin ); - VectorCopy( fd->viewaxis[0], parms.ori.axis[0] ); - VectorCopy( fd->viewaxis[1], parms.ori.axis[1] ); - VectorCopy( fd->viewaxis[2], parms.ori.axis[2] ); + VectorCopy(fd->vieworg, parms.ori.origin); + VectorCopy(fd->viewaxis[0], parms.ori.axis[0]); + VectorCopy(fd->viewaxis[1], parms.ori.axis[1]); + VectorCopy(fd->viewaxis[2], parms.ori.axis[2]); - VectorCopy( fd->vieworg, parms.pvsOrigin ); + VectorCopy(fd->vieworg, parms.pvsOrigin); - R_RenderView( &parms ); + R_RenderView(&parms); // the next scene rendered in this frame will tack on after this one r_firstSceneDrawSurf = tr.refdef.numDrawSurfs; @@ -555,17 +522,16 @@ void RE_RenderScene( const refdef_t *fd ) { refEntParent = -1; - tr.frontEndMsec += ri.Milliseconds()*ri.Cvar_VariableValue( "timescale" ) - startTime; + tr.frontEndMsec += ri.Milliseconds() * ri.Cvar_VariableValue("timescale") - startTime; RE_RenderWorldEffects(); - if (tr.refdef.rdflags & RDF_AUTOMAP) - { + if (tr.refdef.rdflags & RDF_AUTOMAP) { RE_RenderAutoMap(); } } -#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. +#if 0 // rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. int R_GetRNumEntities(void) { return r_numentities; diff --git a/codemp/rd-vanilla/tr_shade.cpp b/codemp/rd-vanilla/tr_shade.cpp index 1172804e70..7aa69e23f1 100644 --- a/codemp/rd-vanilla/tr_shade.cpp +++ b/codemp/rd-vanilla/tr_shade.cpp @@ -33,10 +33,10 @@ along with this program; if not, see . This file deals with applying shaders to surface data in the tess struct. */ -shaderCommands_t tess; -static qboolean setArraysOnce; +shaderCommands_t tess; +static qboolean setArraysOnce; -color4ub_t styleColors[MAX_LIGHT_STYLES]; +color4ub_t styleColors[MAX_LIGHT_STYLES]; extern bool g_bRenderGlowingObjects; @@ -47,15 +47,15 @@ R_ArrayElementDiscrete This is just for OpenGL conformance testing, it should never be the fastest ================ */ -static void APIENTRY R_ArrayElementDiscrete( GLint index ) { - qglColor4ubv( tess.svars.colors[ index ] ); - if ( glState.currenttmu ) { - qglMultiTexCoord2fARB( 0, tess.svars.texcoords[ 0 ][ index ][0], tess.svars.texcoords[ 0 ][ index ][1] ); - qglMultiTexCoord2fARB( 1, tess.svars.texcoords[ 1 ][ index ][0], tess.svars.texcoords[ 1 ][ index ][1] ); +static void APIENTRY R_ArrayElementDiscrete(GLint index) { + qglColor4ubv(tess.svars.colors[index]); + if (glState.currenttmu) { + qglMultiTexCoord2fARB(0, tess.svars.texcoords[0][index][0], tess.svars.texcoords[0][index][1]); + qglMultiTexCoord2fARB(1, tess.svars.texcoords[1][index][0], tess.svars.texcoords[1][index][1]); } else { - qglTexCoord2fv( tess.svars.texcoords[ 0 ][ index ] ); + qglTexCoord2fv(tess.svars.texcoords[0][index]); } - qglVertex3fv( tess.xyz[ index ] ); + qglVertex3fv(tess.xyz[index]); } /* @@ -64,25 +64,25 @@ R_DrawStripElements =================== */ -static int c_vertexes; // for seeing how long our average strips are -static int c_begins; -static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void ( APIENTRY *element )(GLint) ) { +static int c_vertexes; // for seeing how long our average strips are +static int c_begins; +static void R_DrawStripElements(int numIndexes, const glIndex_t *indexes, void(APIENTRY *element)(GLint)) { int i; glIndex_t last[3]; qboolean even; c_begins++; - if ( numIndexes <= 0 ) { + if (numIndexes <= 0) { return; } - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); // prime the strip - element( indexes[0] ); - element( indexes[1] ); - element( indexes[2] ); + element(indexes[0]); + element(indexes[1]); + element(indexes[2]); c_vertexes += 3; last[0] = indexes[0]; @@ -91,59 +91,51 @@ static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void even = qfalse; - for ( i = 3; i < numIndexes; i += 3 ) - { + for (i = 3; i < numIndexes; i += 3) { // odd numbered triangle in potential strip - if ( !even ) - { + if (!even) { // check previous triangle to see if we're continuing a strip - if ( ( indexes[i+0] == last[2] ) && ( indexes[i+1] == last[1] ) ) - { - element( indexes[i+2] ); + if ((indexes[i + 0] == last[2]) && (indexes[i + 1] == last[1])) { + element(indexes[i + 2]); c_vertexes++; - assert( (int)indexes[i+2] < tess.numVertexes ); + assert((int)indexes[i + 2] < tess.numVertexes); even = qtrue; } // otherwise we're done with this strip so finish it and start // a new one - else - { + else { qglEnd(); - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); c_begins++; - element( indexes[i+0] ); - element( indexes[i+1] ); - element( indexes[i+2] ); + element(indexes[i + 0]); + element(indexes[i + 1]); + element(indexes[i + 2]); c_vertexes += 3; even = qfalse; } - } - else - { + } else { // check previous triangle to see if we're continuing a strip - if ( ( last[2] == indexes[i+1] ) && ( last[0] == indexes[i+0] ) ) - { - element( indexes[i+2] ); + if ((last[2] == indexes[i + 1]) && (last[0] == indexes[i + 0])) { + element(indexes[i + 2]); c_vertexes++; even = qfalse; } // otherwise we're done with this strip so finish it and start // a new one - else - { + else { qglEnd(); - qglBegin( GL_TRIANGLE_STRIP ); + qglBegin(GL_TRIANGLE_STRIP); c_begins++; - element( indexes[i+0] ); - element( indexes[i+1] ); - element( indexes[i+2] ); + element(indexes[i + 0]); + element(indexes[i + 1]); + element(indexes[i + 2]); c_vertexes += 3; even = qfalse; @@ -151,16 +143,14 @@ static void R_DrawStripElements( int numIndexes, const glIndex_t *indexes, void } // cache the last three vertices - last[0] = indexes[i+0]; - last[1] = indexes[i+1]; - last[2] = indexes[i+2]; + last[0] = indexes[i + 0]; + last[1] = indexes[i + 1]; + last[2] = indexes[i + 2]; } qglEnd(); } - - /* ================== R_DrawElements @@ -170,45 +160,38 @@ instead of using the single glDrawElements call that may be inefficient without compiled vertex arrays. ================== */ -static void R_DrawElements( int numIndexes, const glIndex_t *indexes ) { - int primitives; +static void R_DrawElements(int numIndexes, const glIndex_t *indexes) { + int primitives; primitives = r_primitives->integer; // default is to use triangles if compiled vertex arrays are present - if ( primitives == 0 ) { - if ( qglLockArraysEXT ) { + if (primitives == 0) { + if (qglLockArraysEXT) { primitives = 2; } else { primitives = 1; } } - - if ( primitives == 2 ) { - qglDrawElements( GL_TRIANGLES, - numIndexes, - GL_INDEX_TYPE, - indexes ); + if (primitives == 2) { + qglDrawElements(GL_TRIANGLES, numIndexes, GL_INDEX_TYPE, indexes); return; } - if ( primitives == 1 ) { - R_DrawStripElements( numIndexes, indexes, qglArrayElement ); + if (primitives == 1) { + R_DrawStripElements(numIndexes, indexes, qglArrayElement); return; } - if ( primitives == 3 ) { - R_DrawStripElements( numIndexes, indexes, R_ArrayElementDiscrete ); + if (primitives == 3) { + R_DrawStripElements(numIndexes, indexes, R_ArrayElementDiscrete); return; } // anything else will cause no drawing } - - - /* ============================================================= @@ -225,57 +208,49 @@ R_BindAnimatedImage */ // de-static'd because tr_quicksprite wants it -void R_BindAnimatedImage( textureBundle_t *bundle ) { - int index; +void R_BindAnimatedImage(textureBundle_t *bundle) { + int index; - if ( bundle->isVideoMap ) { + if (bundle->isVideoMap) { ri.CIN_RunCinematic(bundle->videoMapHandle); ri.CIN_UploadCinematic(bundle->videoMapHandle); return; } - if ((r_fullbright->value /*|| tr.refdef.doFullbright */) && bundle->isLightmap) - { - GL_Bind( tr.whiteImage ); + if ((r_fullbright->value /*|| tr.refdef.doFullbright */) && bundle->isLightmap) { + GL_Bind(tr.whiteImage); return; } - if ( bundle->numImageAnimations <= 1 ) { - GL_Bind( bundle->image ); + if (bundle->numImageAnimations <= 1) { + GL_Bind(bundle->image); return; } - if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) - { + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX) { index = backEnd.currentEntity->e.skinNum; - } - else - { + } else { // it is necessary to do this messy calc to make sure animations line up // exactly with waveforms of the same frequency - index = Q_ftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index = Q_ftol(tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE); index >>= FUNCTABLE_SIZE2; - if ( index < 0 ) { - index = 0; // may happen with shader time offsets + if (index < 0) { + index = 0; // may happen with shader time offsets } } - if ( bundle->oneShotAnimMap ) - { - if ( index >= bundle->numImageAnimations ) - { + if (bundle->oneShotAnimMap) { + if (index >= bundle->numImageAnimations) { // stick on last frame index = bundle->numImageAnimations - 1; } - } - else - { + } else { // loop index %= bundle->numImageAnimations; } - GL_Bind( *((image_t**)bundle->image + index) ); + GL_Bind(*((image_t **)bundle->image + index)); } /* @@ -285,37 +260,36 @@ DrawTris Draws triangle outlines for debugging ================ */ -static void DrawTris (shaderCommands_t *input) { - if (input->numVertexes <= 0) { - return; - } +static void DrawTris(shaderCommands_t *input) { + if (input->numVertexes <= 0) { + return; + } - GL_Bind( tr.whiteImage ); - qglColor3f (1,1,1); + GL_Bind(tr.whiteImage); + qglColor3f(1, 1, 1); - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE ); - qglDepthRange( 0, 0 ); + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE); + qglDepthRange(0, 0); - qglDisableClientState (GL_COLOR_ARRAY); - qglDisableClientState (GL_TEXTURE_COORD_ARRAY); + qglDisableClientState(GL_COLOR_ARRAY); + qglDisableClientState(GL_TEXTURE_COORD_ARRAY); - qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, input->xyz); // padded for SIMD if (qglLockArraysEXT) { qglLockArraysEXT(0, input->numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } - /* ================ DrawNormals @@ -323,24 +297,24 @@ DrawNormals Draws vertex normals for debugging ================ */ -static void DrawNormals (shaderCommands_t *input) { - int i; - vec3_t temp; - - GL_Bind( tr.whiteImage ); - qglColor3f (1,1,1); - qglDepthRange( 0, 0 ); // never occluded - GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE ); - - qglBegin (GL_LINES); - for (i = 0 ; i < input->numVertexes ; i++) { - qglVertex3fv (input->xyz[i]); - VectorMA (input->xyz[i], 2, input->normal[i], temp); - qglVertex3fv (temp); +static void DrawNormals(shaderCommands_t *input) { + int i; + vec3_t temp; + + GL_Bind(tr.whiteImage); + qglColor3f(1, 1, 1); + qglDepthRange(0, 0); // never occluded + GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE); + + qglBegin(GL_LINES); + for (i = 0; i < input->numVertexes; i++) { + qglVertex3fv(input->xyz[i]); + VectorMA(input->xyz[i], 2, input->normal[i], temp); + qglVertex3fv(temp); } - qglEnd (); + qglEnd(); - qglDepthRange( 0, 1 ); + qglDepthRange(0, 1); } /* @@ -352,14 +326,14 @@ because a surface may be forced to perform a RB_End due to overflow. ============== */ -void RB_BeginSurface( shader_t *shader, int fogNum ) { +void RB_BeginSurface(shader_t *shader, int fogNum) { shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader; tess.numIndexes = 0; tess.numVertexes = 0; tess.shader = state; tess.fogNum = fogNum; - tess.dlightBits = 0; // will be OR'd in by surface functions + tess.dlightBits = 0; // will be OR'd in by surface functions tess.xstages = state->stages; tess.numPasses = state->numUnfoggedPasses; tess.currentStageIteratorFunc = shader->sky ? RB_StageIteratorSky : RB_StageIteratorGeneric; @@ -384,52 +358,52 @@ t0 = most upstream according to spec t1 = most downstream according to spec =================== */ -static void DrawMultitextured( shaderCommands_t *input, int stage ) { - shaderStage_t *pStage; +static void DrawMultitextured(shaderCommands_t *input, int stage) { + shaderStage_t *pStage; pStage = &tess.xstages[stage]; - GL_State( pStage->stateBits ); + GL_State(pStage->stateBits); // this is an ugly hack to work around a GeForce driver // bug with multitexture and clip planes - if ( backEnd.viewParms.isPortal ) { - qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + if (backEnd.viewParms.isPortal) { + qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } // // base // - GL_SelectTexture( 0 ); - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] ); - R_BindAnimatedImage( &pStage->bundle[0] ); + GL_SelectTexture(0); + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[0]); + R_BindAnimatedImage(&pStage->bundle[0]); // // lightmap/secondary pass // - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); - if ( r_lightmap->integer ) { - GL_TexEnv( GL_REPLACE ); + if (r_lightmap->integer) { + GL_TexEnv(GL_REPLACE); } else { - GL_TexEnv( tess.shader->multitextureEnv ); + GL_TexEnv(tess.shader->multitextureEnv); } - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[1]); - R_BindAnimatedImage( &pStage->bundle[1] ); + R_BindAnimatedImage(&pStage->bundle[1]); - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); // // disable texturing on TEXTURE1, then select TEXTURE0 // - //qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); - qglDisable( GL_TEXTURE_2D ); + // qglDisableClientState( GL_TEXTURE_COORD_ARRAY ); + qglDisable(GL_TEXTURE_2D); - GL_SelectTexture( 0 ); + GL_SelectTexture(0); } /* @@ -439,87 +413,74 @@ ProjectDlightTexture Perform dynamic lighting with another rendering pass =================== */ -static void ProjectDlightTexture2( void ) { - int i, l; - vec3_t origin; - byte clipBits[SHADER_MAX_VERTEXES]; - float texCoordsArray[SHADER_MAX_VERTEXES][2]; - float oldTexCoordsArray[SHADER_MAX_VERTEXES][2]; - float vertCoordsArray[SHADER_MAX_VERTEXES][4]; - unsigned int colorArray[SHADER_MAX_VERTEXES]; - glIndex_t hitIndexes[SHADER_MAX_INDEXES]; - int numIndexes; - float radius; - int fogging; +static void ProjectDlightTexture2(void) { + int i, l; + vec3_t origin; + byte clipBits[SHADER_MAX_VERTEXES]; + float texCoordsArray[SHADER_MAX_VERTEXES][2]; + float oldTexCoordsArray[SHADER_MAX_VERTEXES][2]; + float vertCoordsArray[SHADER_MAX_VERTEXES][4]; + unsigned int colorArray[SHADER_MAX_VERTEXES]; + glIndex_t hitIndexes[SHADER_MAX_INDEXES]; + int numIndexes; + float radius; + int fogging; shaderStage_t *dStage; - vec3_t posa; - vec3_t posb; - vec3_t posc; - vec3_t dist; - vec3_t e1; - vec3_t e2; - vec3_t normal; - float fac,modulate; - vec3_t floatColor; + vec3_t posa; + vec3_t posb; + vec3_t posc; + vec3_t dist; + vec3_t e1; + vec3_t e2; + vec3_t normal; + float fac, modulate; + vec3_t floatColor; byte colorTemp[4]; - int needResetVerts=0; + int needResetVerts = 0; - if ( !backEnd.refdef.num_dlights ) - { + if (!backEnd.refdef.num_dlights) { return; } - for ( l = 0 ; l < backEnd.refdef.num_dlights ; l++ ) - { - dlight_t *dl; + for (l = 0; l < backEnd.refdef.num_dlights; l++) { + dlight_t *dl; - if ( !( tess.dlightBits & ( 1 << l ) ) ) { - continue; // this surface definately doesn't have any of this light + if (!(tess.dlightBits & (1 << l))) { + continue; // this surface definately doesn't have any of this light } dl = &backEnd.refdef.dlights[l]; - VectorCopy( dl->transformed, origin ); + VectorCopy(dl->transformed, origin); radius = dl->radius; - int clipall = 63; - for ( i = 0 ; i < tess.numVertexes ; i++) - { - int clip; - VectorSubtract( origin, tess.xyz[i], dist ); + int clipall = 63; + for (i = 0; i < tess.numVertexes; i++) { + int clip; + VectorSubtract(origin, tess.xyz[i], dist); clip = 0; - if ( dist[0] < -radius ) - { + if (dist[0] < -radius) { clip |= 1; - } - else if ( dist[0] > radius ) - { + } else if (dist[0] > radius) { clip |= 2; } - if ( dist[1] < -radius ) - { + if (dist[1] < -radius) { clip |= 4; - } - else if ( dist[1] > radius ) - { + } else if (dist[1] > radius) { clip |= 8; } - if ( dist[2] < -radius ) - { + if (dist[2] < -radius) { clip |= 16; - } - else if ( dist[2] > radius ) - { + } else if (dist[2] > radius) { clip |= 32; } clipBits[i] = clip; clipall &= clip; } - if ( clipall ) - { - continue; // this surface doesn't have any of this light + if (clipall) { + continue; // this surface doesn't have any of this light } floatColor[0] = dl->color[0] * 255.0f; floatColor[1] = dl->color[1] * 255.0f; @@ -527,77 +488,71 @@ static void ProjectDlightTexture2( void ) { // build a list of triangles that need light numIndexes = 0; - for ( i = 0 ; i < tess.numIndexes ; i += 3 ) - { - int a, b, c; + for (i = 0; i < tess.numIndexes; i += 3) { + int a, b, c; a = tess.indexes[i]; - b = tess.indexes[i+1]; - c = tess.indexes[i+2]; - if ( clipBits[a] & clipBits[b] & clipBits[c] ) - { - continue; // not lighted + b = tess.indexes[i + 1]; + c = tess.indexes[i + 2]; + if (clipBits[a] & clipBits[b] & clipBits[c]) { + continue; // not lighted } // copy the vertex positions - VectorCopy(tess.xyz[a],posa); - VectorCopy(tess.xyz[b],posb); - VectorCopy(tess.xyz[c],posc); - - VectorSubtract( posa, posb,e1); - VectorSubtract( posc, posb,e2); - CrossProduct(e1,e2,normal); -// rjr - removed for hacking if ( (!r_dlightBacks->integer && DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f) || // backface - if ( DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f || // backface - DotProduct(normal,normal) < 1E-8f) // junk triangle + VectorCopy(tess.xyz[a], posa); + VectorCopy(tess.xyz[b], posb); + VectorCopy(tess.xyz[c], posc); + + VectorSubtract(posa, posb, e1); + VectorSubtract(posc, posb, e2); + CrossProduct(e1, e2, normal); + // rjr - removed for hacking if ( (!r_dlightBacks->integer && DotProduct(normal,origin)-DotProduct(normal,posa) <= 0.0f) || // backface + if (DotProduct(normal, origin) - DotProduct(normal, posa) <= 0.0f || // backface + DotProduct(normal, normal) < 1E-8f) // junk triangle { continue; } VectorNormalize(normal); - fac=DotProduct(normal,origin)-DotProduct(normal,posa); - if (fac >= radius) // out of range + fac = DotProduct(normal, origin) - DotProduct(normal, posa); + if (fac >= radius) // out of range { continue; } - modulate = 1.0f-((fac*fac) / (radius*radius)); - fac = 0.5f/sqrtf(radius*radius - fac*fac); + modulate = 1.0f - ((fac * fac) / (radius * radius)); + fac = 0.5f / sqrtf(radius * radius - fac * fac); // save the verts - VectorCopy(posa,vertCoordsArray[numIndexes]); - VectorCopy(posb,vertCoordsArray[numIndexes+1]); - VectorCopy(posc,vertCoordsArray[numIndexes+2]); + VectorCopy(posa, vertCoordsArray[numIndexes]); + VectorCopy(posb, vertCoordsArray[numIndexes + 1]); + VectorCopy(posc, vertCoordsArray[numIndexes + 2]); // now we need e1 and e2 to be an orthonormal basis - if (DotProduct(e1,e1) > DotProduct(e2,e2)) - { + if (DotProduct(e1, e1) > DotProduct(e2, e2)) { VectorNormalize(e1); - CrossProduct(e1,normal,e2); - } - else - { + CrossProduct(e1, normal, e2); + } else { VectorNormalize(e2); - CrossProduct(normal,e2,e1); + CrossProduct(normal, e2, e1); } - VectorScale(e1,fac,e1); - VectorScale(e2,fac,e2); + VectorScale(e1, fac, e1); + VectorScale(e2, fac, e2); - VectorSubtract( posa, origin,dist); - texCoordsArray[numIndexes][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posa, origin, dist); + texCoordsArray[numIndexes][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes][1] = DotProduct(dist, e2) + 0.5f; - VectorSubtract( posb, origin,dist); - texCoordsArray[numIndexes+1][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes+1][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posb, origin, dist); + texCoordsArray[numIndexes + 1][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes + 1][1] = DotProduct(dist, e2) + 0.5f; - VectorSubtract( posc, origin,dist); - texCoordsArray[numIndexes+2][0]=DotProduct(dist,e1)+0.5f; - texCoordsArray[numIndexes+2][1]=DotProduct(dist,e2)+0.5f; + VectorSubtract(posc, origin, dist); + texCoordsArray[numIndexes + 2][0] = DotProduct(dist, e1) + 0.5f; + texCoordsArray[numIndexes + 2][1] = DotProduct(dist, e2) + 0.5f; - if ((texCoordsArray[numIndexes][0] < 0.0f && texCoordsArray[numIndexes+1][0] < 0.0f && texCoordsArray[numIndexes+2][0] < 0.0f) || - (texCoordsArray[numIndexes][0] > 1.0f && texCoordsArray[numIndexes+1][0] > 1.0f && texCoordsArray[numIndexes+2][0] > 1.0f) || - (texCoordsArray[numIndexes][1] < 0.0f && texCoordsArray[numIndexes+1][1] < 0.0f && texCoordsArray[numIndexes+2][1] < 0.0f) || - (texCoordsArray[numIndexes][1] > 1.0f && texCoordsArray[numIndexes+1][1] > 1.0f && texCoordsArray[numIndexes+2][1] > 1.0f) ) - { + if ((texCoordsArray[numIndexes][0] < 0.0f && texCoordsArray[numIndexes + 1][0] < 0.0f && texCoordsArray[numIndexes + 2][0] < 0.0f) || + (texCoordsArray[numIndexes][0] > 1.0f && texCoordsArray[numIndexes + 1][0] > 1.0f && texCoordsArray[numIndexes + 2][0] > 1.0f) || + (texCoordsArray[numIndexes][1] < 0.0f && texCoordsArray[numIndexes + 1][1] < 0.0f && texCoordsArray[numIndexes + 2][1] < 0.0f) || + (texCoordsArray[numIndexes][1] > 1.0f && texCoordsArray[numIndexes + 1][1] > 1.0f && texCoordsArray[numIndexes + 2][1] > 1.0f)) { continue; // didn't end up hitting this tri } /* old code, get from the svars = wrong @@ -608,12 +563,12 @@ static void ProjectDlightTexture2( void ) { oldTexCoordsArray[numIndexes+2][0]=tess.svars.texcoords[0][c][0]; oldTexCoordsArray[numIndexes+2][1]=tess.svars.texcoords[0][c][1]; */ - oldTexCoordsArray[numIndexes][0]=tess.texCoords[a][0][0]; - oldTexCoordsArray[numIndexes][1]=tess.texCoords[a][0][1]; - oldTexCoordsArray[numIndexes+1][0]=tess.texCoords[b][0][0]; - oldTexCoordsArray[numIndexes+1][1]=tess.texCoords[b][0][1]; - oldTexCoordsArray[numIndexes+2][0]=tess.texCoords[c][0][0]; - oldTexCoordsArray[numIndexes+2][1]=tess.texCoords[c][0][1]; + oldTexCoordsArray[numIndexes][0] = tess.texCoords[a][0][0]; + oldTexCoordsArray[numIndexes][1] = tess.texCoords[a][0][1]; + oldTexCoordsArray[numIndexes + 1][0] = tess.texCoords[b][0][0]; + oldTexCoordsArray[numIndexes + 1][1] = tess.texCoords[b][0][1]; + oldTexCoordsArray[numIndexes + 2][0] = tess.texCoords[c][0][0]; + oldTexCoordsArray[numIndexes + 2][1] = tess.texCoords[c][0][1]; colorTemp[0] = Q_ftol(floatColor[0] * modulate); colorTemp[1] = Q_ftol(floatColor[1] * modulate); @@ -626,170 +581,149 @@ static void ProjectDlightTexture2( void ) { colorArray[numIndexes + 2] = ba->ui; hitIndexes[numIndexes] = numIndexes; - hitIndexes[numIndexes+1] = numIndexes+1; - hitIndexes[numIndexes+2] = numIndexes+2; + hitIndexes[numIndexes + 1] = numIndexes + 1; + hitIndexes[numIndexes + 2] = numIndexes + 2; numIndexes += 3; - if (numIndexes>=SHADER_MAX_VERTEXES-3) - { + if (numIndexes >= SHADER_MAX_VERTEXES - 3) { break; // we are out of space, so we are done :) } } - if ( !numIndexes ) { + if (!numIndexes) { continue; } - //don't have fog enabled when we redraw with alpha test, or it will double over - //and screw the tri up -rww - if (r_drawfog->value == 2 && - tr.world && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't have fog enabled when we redraw with alpha test, or it will double over + // and screw the tri up -rww + if (r_drawfog->value == 2 && tr.world && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { fogging = qglIsEnabled(GL_FOG); - if (fogging) - { + if (fogging) { qglDisable(GL_FOG); } - } - else - { + } else { fogging = 0; } - dStage = NULL; - if (tess.shader && qglActiveTextureARB) - { + if (tess.shader && qglActiveTextureARB) { int i = 0; - while (i < tess.shader->numUnfoggedPasses) - { - const int blendBits = (GLS_SRCBLEND_BITS+GLS_DSTBLEND_BITS); - if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || - (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && - (tess.shader->stages[i].stateBits & blendBits) == 0 ) - { //only use non-lightmap opaque stages - dStage = &tess.shader->stages[i]; + while (i < tess.shader->numUnfoggedPasses) { + const int blendBits = (GLS_SRCBLEND_BITS + GLS_DSTBLEND_BITS); + if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods && + tess.shader->stages[i].bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[0].tcGen != TCGEN_FOG) || + (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods && + tess.shader->stages[i].bundle[1].tcGen != TCGEN_ENVIRONMENT_MAPPED && tess.shader->stages[i].bundle[1].tcGen != TCGEN_FOG)) && + (tess.shader->stages[i].stateBits & blendBits) == 0) { // only use non-lightmap opaque stages + dStage = &tess.shader->stages[i]; break; } i++; } } - if (!needResetVerts) - { - needResetVerts=1; - if (qglUnlockArraysEXT) - { + if (!needResetVerts) { + needResetVerts = 1; + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } } - qglVertexPointer (3, GL_FLOAT, 16, vertCoordsArray); // padded for SIMD + qglVertexPointer(3, GL_FLOAT, 16, vertCoordsArray); // padded for SIMD - if (dStage) - { - GL_SelectTexture( 0 ); + if (dStage) { + GL_SelectTexture(0); GL_State(0); - qglTexCoordPointer( 2, GL_FLOAT, 0, oldTexCoordsArray[0] ); - if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) - { - R_BindAnimatedImage( &dStage->bundle[0] ); - } - else - { - R_BindAnimatedImage( &dStage->bundle[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, oldTexCoordsArray[0]); + if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods && + dStage->bundle[0].tcGen != TCGEN_ENVIRONMENT_MAPPED && dStage->bundle[0].tcGen != TCGEN_FOG) { + R_BindAnimatedImage(&dStage->bundle[0]); + } else { + R_BindAnimatedImage(&dStage->bundle[1]); } - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); - GL_Bind( tr.dlightImage ); - GL_TexEnv( GL_MODULATE ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); + GL_Bind(tr.dlightImage); + GL_TexEnv(GL_MODULATE); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); // | GLS_ATEST_GT_0); - GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL);// | GLS_ATEST_GT_0); + R_DrawElements(numIndexes, hitIndexes); - R_DrawElements( numIndexes, hitIndexes ); - - qglDisable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); GL_SelectTexture(0); - } - else - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); + } else { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); - GL_Bind( tr.dlightImage ); + GL_Bind(tr.dlightImage); // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light // where they aren't rendered - if ( dl->additive ) { - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); - } - else { - GL_State( GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); + if (dl->additive) { + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); + } else { + GL_State(GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); } - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); } - if (fogging) - { + if (fogging) { qglEnable(GL_FOG); } backEnd.pc.c_totalIndexes += numIndexes; backEnd.pc.c_dlightIndexes += numIndexes; } - if (needResetVerts) - { - qglVertexPointer (3, GL_FLOAT, 16, tess.xyz); // padded for SIMD - if (qglLockArraysEXT) - { + if (needResetVerts) { + qglVertexPointer(3, GL_FLOAT, 16, tess.xyz); // padded for SIMD + if (qglLockArraysEXT) { qglLockArraysEXT(0, tess.numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } } } -static void ProjectDlightTexture( void ) { - int i, l; - vec3_t origin; - float *texCoords; - byte *colors; - byte clipBits[SHADER_MAX_VERTEXES]; - float texCoordsArray[SHADER_MAX_VERTEXES][2]; - byte colorArray[SHADER_MAX_VERTEXES][4]; - glIndex_t hitIndexes[SHADER_MAX_INDEXES]; - int numIndexes; - float scale; - float radius; - int fogging; - vec3_t floatColor; +static void ProjectDlightTexture(void) { + int i, l; + vec3_t origin; + float *texCoords; + byte *colors; + byte clipBits[SHADER_MAX_VERTEXES]; + float texCoordsArray[SHADER_MAX_VERTEXES][2]; + byte colorArray[SHADER_MAX_VERTEXES][4]; + glIndex_t hitIndexes[SHADER_MAX_INDEXES]; + int numIndexes; + float scale; + float radius; + int fogging; + vec3_t floatColor; shaderStage_t *dStage; - if ( !backEnd.refdef.num_dlights ) { + if (!backEnd.refdef.num_dlights) { return; } - for ( l = 0 ; l < backEnd.refdef.num_dlights ; l++ ) { - dlight_t *dl; + for (l = 0; l < backEnd.refdef.num_dlights; l++) { + dlight_t *dl; - if ( !( tess.dlightBits & ( 1 << l ) ) ) { - continue; // this surface definately doesn't have any of this light + if (!(tess.dlightBits & (1 << l))) { + continue; // this surface definately doesn't have any of this light } texCoords = texCoordsArray[0]; colors = colorArray[0]; dl = &backEnd.refdef.dlights[l]; - VectorCopy( dl->transformed, origin ); + VectorCopy(dl->transformed, origin); radius = dl->radius; scale = 1.0f / radius; @@ -797,37 +731,29 @@ static void ProjectDlightTexture( void ) { floatColor[1] = dl->color[1] * 255.0f; floatColor[2] = dl->color[2] * 255.0f; - for ( i = 0 ; i < tess.numVertexes ; i++, texCoords += 2, colors += 4 ) { - vec3_t dist; - int clip; - float modulate; + for (i = 0; i < tess.numVertexes; i++, texCoords += 2, colors += 4) { + vec3_t dist; + int clip; + float modulate; backEnd.pc.c_dlightVertexes++; - VectorSubtract( origin, tess.xyz[i], dist ); + VectorSubtract(origin, tess.xyz[i], dist); int l = 1; int bestIndex = 0; float greatest = tess.normal[i][0]; - if (greatest < 0.0f) - { + if (greatest < 0.0f) { greatest = -greatest; } - if (VectorCompare(tess.normal[i], vec3_origin)) - { //damn you terrain! + if (VectorCompare(tess.normal[i], vec3_origin)) { // damn you terrain! bestIndex = 2; - } - else - { - while (l < 3) - { - if ((tess.normal[i][l] > greatest && tess.normal[i][l] > 0.0f) || - (tess.normal[i][l] < -greatest && tess.normal[i][l] < 0.0f)) - { + } else { + while (l < 3) { + if ((tess.normal[i][l] > greatest && tess.normal[i][l] > 0.0f) || (tess.normal[i][l] < -greatest && tess.normal[i][l] < 0.0f)) { greatest = tess.normal[i][l]; - if (greatest < 0.0f) - { + if (greatest < 0.0f) { greatest = -greatest; } bestIndex = l; @@ -841,96 +767,63 @@ static void ProjectDlightTexture( void ) { const float maxGroundScale = 1.4f; const float lightScaleTolerance = 0.1f; - if (bestIndex == 2) - { - dUse = origin[2]-tess.xyz[i][2]; - if (dUse < 0.0f) - { + if (bestIndex == 2) { + dUse = origin[2] - tess.xyz[i][2]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxGroundScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxGroundScale) { dUse = maxGroundScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (VectorCompare(tess.normal[i], vec3_origin) || - tess.normal[i][0] > lightScaleTolerance || - tess.normal[i][0] < -lightScaleTolerance || - tess.normal[i][1] > lightScaleTolerance || - tess.normal[i][1] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (VectorCompare(tess.normal[i], vec3_origin) || tess.normal[i][0] > lightScaleTolerance || tess.normal[i][0] < -lightScaleTolerance || + tess.normal[i][1] > lightScaleTolerance || tess.normal[i][1] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[0] * scale; texCoords[1] = 0.5f + dist[1] * scale; - } - else if (bestIndex == 1) - { - dUse = origin[1]-tess.xyz[i][1]; - if (dUse < 0.0f) - { + } else if (bestIndex == 1) { + dUse = origin[1] - tess.xyz[i][1]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxScale) { dUse = maxScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (tess.normal[i][0] > lightScaleTolerance || - tess.normal[i][0] < -lightScaleTolerance || - tess.normal[i][2] > lightScaleTolerance || - tess.normal[i][2] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (tess.normal[i][0] > lightScaleTolerance || tess.normal[i][0] < -lightScaleTolerance || tess.normal[i][2] > lightScaleTolerance || + tess.normal[i][2] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[0] * scale; texCoords[1] = 0.5f + dist[2] * scale; - } - else - { - dUse = origin[0]-tess.xyz[i][0]; - if (dUse < 0.0f) - { + } else { + dUse = origin[0] - tess.xyz[i][0]; + if (dUse < 0.0f) { dUse = -dUse; } - dUse = (radius*0.5f)/dUse; - if (dUse > maxScale) - { + dUse = (radius * 0.5f) / dUse; + if (dUse > maxScale) { dUse = maxScale; - } - else if (dUse < 0.1f) - { + } else if (dUse < 0.1f) { dUse = 0.1f; } - if (tess.normal[i][2] > lightScaleTolerance || - tess.normal[i][2] < -lightScaleTolerance || - tess.normal[i][1] > lightScaleTolerance || - tess.normal[i][1] < -lightScaleTolerance) - { //if not perfectly flat, we must use a constant dist + if (tess.normal[i][2] > lightScaleTolerance || tess.normal[i][2] < -lightScaleTolerance || tess.normal[i][1] > lightScaleTolerance || + tess.normal[i][1] < -lightScaleTolerance) { // if not perfectly flat, we must use a constant dist scale = 1.0f / radius; - } - else - { - scale = 1.0f / (radius*dUse); + } else { + scale = 1.0f / (radius * dUse); } texCoords[0] = 0.5f + dist[1] * scale; @@ -938,26 +831,26 @@ static void ProjectDlightTexture( void ) { } clip = 0; - if ( texCoords[0] < 0.0f ) { + if (texCoords[0] < 0.0f) { clip |= 1; - } else if ( texCoords[0] > 1.0f ) { + } else if (texCoords[0] > 1.0f) { clip |= 2; } - if ( texCoords[1] < 0.0f ) { + if (texCoords[1] < 0.0f) { clip |= 4; - } else if ( texCoords[1] > 1.0f ) { + } else if (texCoords[1] > 1.0f) { clip |= 8; } // modulate the strength based on the height and color - if ( dist[bestIndex] > radius ) { + if (dist[bestIndex] > radius) { clip |= 16; modulate = 0.0f; - } else if ( dist[bestIndex] < -radius ) { + } else if (dist[bestIndex] < -radius) { clip |= 32; modulate = 0.0f; } else { dist[bestIndex] = Q_fabs(dist[bestIndex]); - if ( dist[bestIndex] < radius * 0.5f ) { + if (dist[bestIndex] < radius * 0.5f) { modulate = 1.0f; } else { modulate = 2.0f * (radius - dist[bestIndex]) * scale; @@ -973,115 +866,98 @@ static void ProjectDlightTexture( void ) { // build a list of triangles that need light numIndexes = 0; - for ( i = 0 ; i < tess.numIndexes ; i += 3 ) { - int a, b, c; + for (i = 0; i < tess.numIndexes; i += 3) { + int a, b, c; a = tess.indexes[i]; - b = tess.indexes[i+1]; - c = tess.indexes[i+2]; - if ( clipBits[a] & clipBits[b] & clipBits[c] ) { - continue; // not lighted + b = tess.indexes[i + 1]; + c = tess.indexes[i + 2]; + if (clipBits[a] & clipBits[b] & clipBits[c]) { + continue; // not lighted } hitIndexes[numIndexes] = a; - hitIndexes[numIndexes+1] = b; - hitIndexes[numIndexes+2] = c; + hitIndexes[numIndexes + 1] = b; + hitIndexes[numIndexes + 2] = c; numIndexes += 3; } - if ( !numIndexes ) { + if (!numIndexes) { continue; } - //don't have fog enabled when we redraw with alpha test, or it will double over - //and screw the tri up -rww - if (r_drawfog->value == 2 && - tr.world && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't have fog enabled when we redraw with alpha test, or it will double over + // and screw the tri up -rww + if (r_drawfog->value == 2 && tr.world && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { fogging = qglIsEnabled(GL_FOG); - if (fogging) - { + if (fogging) { qglDisable(GL_FOG); } - } - else - { + } else { fogging = 0; } - dStage = NULL; - if (tess.shader && qglActiveTextureARB) - { + if (tess.shader && qglActiveTextureARB) { int i = 0; - while (i < tess.shader->numUnfoggedPasses) - { - const int blendBits = (GLS_SRCBLEND_BITS+GLS_DSTBLEND_BITS); + while (i < tess.shader->numUnfoggedPasses) { + const int blendBits = (GLS_SRCBLEND_BITS + GLS_DSTBLEND_BITS); if (((tess.shader->stages[i].bundle[0].image && !tess.shader->stages[i].bundle[0].isLightmap && !tess.shader->stages[i].bundle[0].numTexMods) || - (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && !tess.shader->stages[i].bundle[1].numTexMods)) && - (tess.shader->stages[i].stateBits & blendBits) == 0 ) - { //only use non-lightmap opaque stages - dStage = &tess.shader->stages[i]; + (tess.shader->stages[i].bundle[1].image && !tess.shader->stages[i].bundle[1].isLightmap && + !tess.shader->stages[i].bundle[1].numTexMods)) && + (tess.shader->stages[i].stateBits & blendBits) == 0) { // only use non-lightmap opaque stages + dStage = &tess.shader->stages[i]; break; } i++; } } - if (dStage) - { - GL_SelectTexture( 0 ); + if (dStage) { + GL_SelectTexture(0); GL_State(0); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); - if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods) - { - R_BindAnimatedImage( &dStage->bundle[0] ); - } - else - { - R_BindAnimatedImage( &dStage->bundle[1] ); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); + if (dStage->bundle[0].image && !dStage->bundle[0].isLightmap && !dStage->bundle[0].numTexMods) { + R_BindAnimatedImage(&dStage->bundle[0]); + } else { + R_BindAnimatedImage(&dStage->bundle[1]); } - GL_SelectTexture( 1 ); - qglEnable( GL_TEXTURE_2D ); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); - GL_Bind( tr.dlightImage ); - GL_TexEnv( GL_MODULATE ); + GL_SelectTexture(1); + qglEnable(GL_TEXTURE_2D); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); + GL_Bind(tr.dlightImage); + GL_TexEnv(GL_MODULATE); - GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL);// | GLS_ATEST_GT_0); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); // | GLS_ATEST_GT_0); - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); - qglDisable( GL_TEXTURE_2D ); + qglDisable(GL_TEXTURE_2D); GL_SelectTexture(0); - } - else - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglTexCoordPointer( 2, GL_FLOAT, 0, texCoordsArray[0] ); + } else { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, texCoordsArray[0]); - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, colorArray ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, colorArray); - GL_Bind( tr.dlightImage ); + GL_Bind(tr.dlightImage); // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light // where they aren't rendered - if ( dl->additive ) { - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); - } - else { - GL_State( GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL ); + if (dl->additive) { + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); + } else { + GL_State(GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ONE | GLS_DEPTHFUNC_EQUAL); } - R_DrawElements( numIndexes, hitIndexes ); + R_DrawElements(numIndexes, hitIndexes); } - if (fogging) - { + if (fogging) { qglEnable(GL_FOG); } @@ -1097,34 +973,34 @@ RB_FogPass Blends a fog texture on top of everything else =================== */ -static void RB_FogPass( void ) { - fog_t *fog; - int i; +static void RB_FogPass(void) { + fog_t *fog; + int i; - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, tess.svars.colors); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); fog = tr.world->fogs + tess.fogNum; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; ba->i = fog->colorInt; } - RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[0] ); + RB_CalcFogTexCoords((float *)tess.svars.texcoords[0]); - GL_Bind( tr.fogImage ); + GL_Bind(tr.fogImage); - if ( tess.shader->fogPass == FP_EQUAL ) { - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL ); + if (tess.shader->fogPass == FP_EQUAL) { + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL); } else { - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); } - R_DrawElements( tess.numIndexes, tess.indexes ); + R_DrawElements(tess.numIndexes, tess.indexes); } /* @@ -1133,17 +1009,15 @@ ComputeColors =============== */ -static void ComputeColors( shaderStage_t *pStage, int forceRGBGen ) -{ - int i; - color4ub_t *colors = tess.svars.colors; +static void ComputeColors(shaderStage_t *pStage, int forceRGBGen) { + int i; + color4ub_t *colors = tess.svars.colors; qboolean killGen = qfalse; - alphaGen_t forceAlphaGen = pStage->alphaGen;//set this up so we can override below + alphaGen_t forceAlphaGen = pStage->alphaGen; // set this up so we can override below - if ( tess.shader != tr.projectionShadowShader && tess.shader != tr.shadowShader && - ( backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1|RF_DISINTEGRATE2))) - { - RB_CalcDisintegrateColors( (unsigned char *)tess.svars.colors ); + if (tess.shader != tr.projectionShadowShader && tess.shader != tr.shadowShader && + (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2))) { + RB_CalcDisintegrateColors((unsigned char *)tess.svars.colors); RB_CalcDisintegrateVertDeform(); // We've done some custom alpha and color stuff, so we can skip the rest. Let it do fog though @@ -1153,238 +1027,202 @@ static void ComputeColors( shaderStage_t *pStage, int forceRGBGen ) // // rgbGen // - if ( !forceRGBGen ) - { + if (!forceRGBGen) { forceRGBGen = pStage->rgbGen; } - if ( backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC ) // does not work for rotated models, technically, this should also be a CGEN type, but that would entail adding new shader commands....which is too much work for one thing + if (backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC) // does not work for rotated models, technically, this should also be a CGEN type, but that would + // entail adding new shader commands....which is too much work for one thing { - int i; - float *normal, dot; + int i; + float *normal, dot; unsigned char *color; - int numVertexes; + int numVertexes; normal = tess.normal[0]; color = tess.svars.colors[0]; numVertexes = tess.numVertexes; - for ( i = 0 ; i < numVertexes ; i++, normal += 4, color += 4) - { - dot = DotProduct( normal, backEnd.refdef.viewaxis[0] ); + for (i = 0; i < numVertexes; i++, normal += 4, color += 4) { + dot = DotProduct(normal, backEnd.refdef.viewaxis[0]); dot *= dot * dot * dot; - if ( dot < 0.2f ) // so low, so just clamp it + if (dot < 0.2f) // so low, so just clamp it { dot = 0.0f; } - color[0] = color[1] = color[2] = color[3] = Q_ftol( backEnd.currentEntity->e.shaderRGBA[0] * (1-dot) ); + color[0] = color[1] = color[2] = color[3] = Q_ftol(backEnd.currentEntity->e.shaderRGBA[0] * (1 - dot)); } killGen = qtrue; } - if (killGen) - { + if (killGen) { goto avoidGen; } // // rgbGen // - switch ( forceRGBGen ) - { - case CGEN_IDENTITY: - memset( tess.svars.colors, 0xff, tess.numVertexes * 4 ); - break; - default: - case CGEN_IDENTITY_LIGHTING: - memset( tess.svars.colors, tr.identityLightByte, tess.numVertexes * 4 ); - break; - case CGEN_LIGHTING_DIFFUSE: - RB_CalcDiffuseColor( ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_LIGHTING_DIFFUSE_ENTITY: - RB_CalcDiffuseEntityColor( ( unsigned char * ) tess.svars.colors ); - if ( forceAlphaGen == AGEN_IDENTITY && - backEnd.currentEntity->e.shaderRGBA[3] == 0xff - ) - { - forceAlphaGen = AGEN_SKIP; //already got it in this set since it does all 4 components - } - break; - case CGEN_EXACT_VERTEX: - memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) ); - break; - case CGEN_CONST: - for ( i = 0; i < tess.numVertexes; i++ ) { - byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], - *baSource = (byteAlias_t *)&pStage->constantColor; - baDest->i = baSource->i; - } - break; - case CGEN_VERTEX: - if ( tr.identityLight == 1 ) - { - memcpy( tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof( tess.vertexColors[0] ) ); - } - else - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = tess.vertexColors[i][0] * tr.identityLight; - tess.svars.colors[i][1] = tess.vertexColors[i][1] * tr.identityLight; - tess.svars.colors[i][2] = tess.vertexColors[i][2] * tr.identityLight; - tess.svars.colors[i][3] = tess.vertexColors[i][3]; - } + switch (forceRGBGen) { + case CGEN_IDENTITY: + memset(tess.svars.colors, 0xff, tess.numVertexes * 4); + break; + default: + case CGEN_IDENTITY_LIGHTING: + memset(tess.svars.colors, tr.identityLightByte, tess.numVertexes * 4); + break; + case CGEN_LIGHTING_DIFFUSE: + RB_CalcDiffuseColor((unsigned char *)tess.svars.colors); + break; + case CGEN_LIGHTING_DIFFUSE_ENTITY: + RB_CalcDiffuseEntityColor((unsigned char *)tess.svars.colors); + if (forceAlphaGen == AGEN_IDENTITY && backEnd.currentEntity->e.shaderRGBA[3] == 0xff) { + forceAlphaGen = AGEN_SKIP; // already got it in this set since it does all 4 components + } + break; + case CGEN_EXACT_VERTEX: + memcpy(tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof(tess.vertexColors[0])); + break; + case CGEN_CONST: + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], *baSource = (byteAlias_t *)&pStage->constantColor; + baDest->i = baSource->i; + } + break; + case CGEN_VERTEX: + if (tr.identityLight == 1) { + memcpy(tess.svars.colors, tess.vertexColors, tess.numVertexes * sizeof(tess.vertexColors[0])); + } else { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = tess.vertexColors[i][0] * tr.identityLight; + tess.svars.colors[i][1] = tess.vertexColors[i][1] * tr.identityLight; + tess.svars.colors[i][2] = tess.vertexColors[i][2] * tr.identityLight; + tess.svars.colors[i][3] = tess.vertexColors[i][3]; } - break; - case CGEN_ONE_MINUS_VERTEX: - if ( tr.identityLight == 1 ) - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = 255 - tess.vertexColors[i][0]; - tess.svars.colors[i][1] = 255 - tess.vertexColors[i][1]; - tess.svars.colors[i][2] = 255 - tess.vertexColors[i][2]; - } + } + break; + case CGEN_ONE_MINUS_VERTEX: + if (tr.identityLight == 1) { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = 255 - tess.vertexColors[i][0]; + tess.svars.colors[i][1] = 255 - tess.vertexColors[i][1]; + tess.svars.colors[i][2] = 255 - tess.vertexColors[i][2]; } - else - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - tess.svars.colors[i][0] = ( 255 - tess.vertexColors[i][0] ) * tr.identityLight; - tess.svars.colors[i][1] = ( 255 - tess.vertexColors[i][1] ) * tr.identityLight; - tess.svars.colors[i][2] = ( 255 - tess.vertexColors[i][2] ) * tr.identityLight; - } + } else { + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.colors[i][0] = (255 - tess.vertexColors[i][0]) * tr.identityLight; + tess.svars.colors[i][1] = (255 - tess.vertexColors[i][1]) * tr.identityLight; + tess.svars.colors[i][2] = (255 - tess.vertexColors[i][2]) * tr.identityLight; } - break; - case CGEN_FOG: - { - fog_t *fog; + } + break; + case CGEN_FOG: { + fog_t *fog; - fog = tr.world->fogs + tess.fogNum; + fog = tr.world->fogs + tess.fogNum; - for ( i = 0; i < tess.numVertexes; i++ ) { - byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; - ba->i = fog->colorInt; - } - } - break; - case CGEN_WAVEFORM: - RB_CalcWaveColor( &pStage->rgbWave, ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_ENTITY: - RB_CalcColorFromEntity( ( unsigned char * ) tess.svars.colors ); - if ( forceAlphaGen == AGEN_IDENTITY && - backEnd.currentEntity->e.shaderRGBA[3] == 0xff - ) - { - forceAlphaGen = AGEN_SKIP; //already got it in this set since it does all 4 components - } - break; - case CGEN_ONE_MINUS_ENTITY: - RB_CalcColorFromOneMinusEntity( ( unsigned char * ) tess.svars.colors ); - break; - case CGEN_LIGHTMAPSTYLE: - for ( i = 0; i < tess.numVertexes; i++ ) - { - byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], - *baSource = (byteAlias_t *)&styleColors[pStage->lightmapStyle]; - baDest->i = baSource->i; - } - break; + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *ba = (byteAlias_t *)&tess.svars.colors[i]; + ba->i = fog->colorInt; + } + } break; + case CGEN_WAVEFORM: + RB_CalcWaveColor(&pStage->rgbWave, (unsigned char *)tess.svars.colors); + break; + case CGEN_ENTITY: + RB_CalcColorFromEntity((unsigned char *)tess.svars.colors); + if (forceAlphaGen == AGEN_IDENTITY && backEnd.currentEntity->e.shaderRGBA[3] == 0xff) { + forceAlphaGen = AGEN_SKIP; // already got it in this set since it does all 4 components + } + break; + case CGEN_ONE_MINUS_ENTITY: + RB_CalcColorFromOneMinusEntity((unsigned char *)tess.svars.colors); + break; + case CGEN_LIGHTMAPSTYLE: + for (i = 0; i < tess.numVertexes; i++) { + byteAlias_t *baDest = (byteAlias_t *)&tess.svars.colors[i], *baSource = (byteAlias_t *)&styleColors[pStage->lightmapStyle]; + baDest->i = baSource->i; + } + break; } // // alphaGen // - switch ( pStage->alphaGen ) - { + switch (pStage->alphaGen) { case AGEN_SKIP: break; case AGEN_IDENTITY: - if ( forceRGBGen != CGEN_IDENTITY ) { - if ( ( forceRGBGen == CGEN_VERTEX && tr.identityLight != 1 ) || - forceRGBGen != CGEN_VERTEX ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + if (forceRGBGen != CGEN_IDENTITY) { + if ((forceRGBGen == CGEN_VERTEX && tr.identityLight != 1) || forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = 0xff; } } } break; case AGEN_CONST: - if ( forceRGBGen != CGEN_CONST ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + if (forceRGBGen != CGEN_CONST) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = pStage->constantColor[3]; } } break; case AGEN_WAVEFORM: - RB_CalcWaveAlpha( &pStage->alphaWave, ( unsigned char * ) tess.svars.colors ); + RB_CalcWaveAlpha(&pStage->alphaWave, (unsigned char *)tess.svars.colors); break; case AGEN_LIGHTING_SPECULAR: - RB_CalcSpecularAlpha( ( unsigned char * ) tess.svars.colors ); + RB_CalcSpecularAlpha((unsigned char *)tess.svars.colors); break; case AGEN_ENTITY: - RB_CalcAlphaFromEntity( ( unsigned char * ) tess.svars.colors ); + RB_CalcAlphaFromEntity((unsigned char *)tess.svars.colors); break; case AGEN_ONE_MINUS_ENTITY: - RB_CalcAlphaFromOneMinusEntity( ( unsigned char * ) tess.svars.colors ); + RB_CalcAlphaFromOneMinusEntity((unsigned char *)tess.svars.colors); break; - case AGEN_VERTEX: - if ( forceRGBGen != CGEN_VERTEX ) { - for ( i = 0; i < tess.numVertexes; i++ ) { + case AGEN_VERTEX: + if (forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = tess.vertexColors[i][3]; } } - break; - case AGEN_ONE_MINUS_VERTEX: - for ( i = 0; i < tess.numVertexes; i++ ) - { + break; + case AGEN_ONE_MINUS_VERTEX: + for (i = 0; i < tess.numVertexes; i++) { tess.svars.colors[i][3] = 255 - tess.vertexColors[i][3]; - } - break; - case AGEN_PORTAL: - { - unsigned char alpha; - - for ( i = 0; i < tess.numVertexes; i++ ) - { - float len; - vec3_t v; + } + break; + case AGEN_PORTAL: { + unsigned char alpha; - VectorSubtract( tess.xyz[i], backEnd.viewParms.ori.origin, v ); - len = VectorLength( v ); + for (i = 0; i < tess.numVertexes; i++) { + float len; + vec3_t v; - len /= tess.shader->portalRange; + VectorSubtract(tess.xyz[i], backEnd.viewParms.ori.origin, v); + len = VectorLength(v); - if ( len < 0 ) - { - alpha = 0; - } - else if ( len > 1 ) - { - alpha = 0xff; - } - else - { - alpha = len * 0xff; - } + len /= tess.shader->portalRange; - tess.svars.colors[i][3] = alpha; + if (len < 0) { + alpha = 0; + } else if (len > 1) { + alpha = 0xff; + } else { + alpha = len * 0xff; } + + tess.svars.colors[i][3] = alpha; } - break; + } break; case AGEN_BLEND: - if ( forceRGBGen != CGEN_VERTEX ) - { - for ( i = 0; i < tess.numVertexes; i++ ) - { - colors[i][3] = tess.vertexAlphas[i][pStage->index]; //rwwRMG - added support + if (forceRGBGen != CGEN_VERTEX) { + for (i = 0; i < tess.numVertexes; i++) { + colors[i][3] = tess.vertexAlphas[i][pStage->index]; // rwwRMG - added support } } break; @@ -1395,18 +1233,16 @@ static void ComputeColors( shaderStage_t *pStage, int forceRGBGen ) // // fog adjustment for colors to fade out as fog increases // - if ( tess.fogNum ) - { - switch ( pStage->adjustColorsForFog ) - { + if (tess.fogNum) { + switch (pStage->adjustColorsForFog) { case ACFF_MODULATE_RGB: - RB_CalcModulateColorsByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateColorsByFog((unsigned char *)tess.svars.colors); break; case ACFF_MODULATE_ALPHA: - RB_CalcModulateAlphasByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateAlphasByFog((unsigned char *)tess.svars.colors); break; case ACFF_MODULATE_RGBA: - RB_CalcModulateRGBAsByFog( ( unsigned char * ) tess.svars.colors ); + RB_CalcModulateRGBAsByFog((unsigned char *)tess.svars.colors); break; case ACFF_NONE: break; @@ -1419,68 +1255,66 @@ static void ComputeColors( shaderStage_t *pStage, int forceRGBGen ) ComputeTexCoords =============== */ -static void ComputeTexCoords( shaderStage_t *pStage ) { - int i; - int b; - float *texcoords; +static void ComputeTexCoords(shaderStage_t *pStage) { + int i; + int b; + float *texcoords; - for ( b = 0; b < NUM_TEXTURE_BUNDLES; b++ ) { + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { int tm; - texcoords = (float *)tess.svars.texcoords[b]; + texcoords = (float *)tess.svars.texcoords[b]; // // generate the texture coordinates // - switch ( pStage->bundle[b].tcGen ) - { + switch (pStage->bundle[b].tcGen) { case TCGEN_IDENTITY: - memset( tess.svars.texcoords[b], 0, sizeof( float ) * 2 * tess.numVertexes ); + memset(tess.svars.texcoords[b], 0, sizeof(float) * 2 * tess.numVertexes); break; case TCGEN_TEXTURE: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { tess.svars.texcoords[b][i][0] = tess.texCoords[i][0][0]; tess.svars.texcoords[b][i][1] = tess.texCoords[i][0][1]; } break; case TCGEN_LIGHTMAP: - for ( i = 0 ; i < tess.numVertexes ; i++,texcoords+=2 ) { + for (i = 0; i < tess.numVertexes; i++, texcoords += 2) { texcoords[0] = tess.texCoords[i][1][0]; texcoords[1] = tess.texCoords[i][1][1]; } break; case TCGEN_LIGHTMAP1: - for ( i = 0 ; i < tess.numVertexes ; i++,texcoords+=2 ) { + for (i = 0; i < tess.numVertexes; i++, texcoords += 2) { texcoords[0] = tess.texCoords[i][2][0]; texcoords[1] = tess.texCoords[i][2][1]; } break; case TCGEN_LIGHTMAP2: - for ( i = 0 ; i < tess.numVertexes ; i++,texcoords+=2 ) { + for (i = 0; i < tess.numVertexes; i++, texcoords += 2) { texcoords[0] = tess.texCoords[i][3][0]; texcoords[1] = tess.texCoords[i][3][1]; } break; case TCGEN_LIGHTMAP3: - for ( i = 0 ; i < tess.numVertexes ; i++,texcoords+=2 ) { + for (i = 0; i < tess.numVertexes; i++, texcoords += 2) { texcoords[0] = tess.texCoords[i][4][0]; texcoords[1] = tess.texCoords[i][4][1]; } break; case TCGEN_VECTOR: - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - tess.svars.texcoords[b][i][0] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[0] ); - tess.svars.texcoords[b][i][1] = DotProduct( tess.xyz[i], pStage->bundle[b].tcGenVectors[1] ); + for (i = 0; i < tess.numVertexes; i++) { + tess.svars.texcoords[b][i][0] = DotProduct(tess.xyz[i], pStage->bundle[b].tcGenVectors[0]); + tess.svars.texcoords[b][i][1] = DotProduct(tess.xyz[i], pStage->bundle[b].tcGenVectors[1]); } break; case TCGEN_FOG: - RB_CalcFogTexCoords( ( float * ) tess.svars.texcoords[b] ); + RB_CalcFogTexCoords((float *)tess.svars.texcoords[b]); break; case TCGEN_ENVIRONMENT_MAPPED: - if ( r_environmentMapping->integer ) { - RB_CalcEnvironmentTexCoords( ( float * ) tess.svars.texcoords[b] ); - } - else { - memset( tess.svars.texcoords[b], 0, sizeof( float ) * 2 * tess.numVertexes ); + if (r_environmentMapping->integer) { + RB_CalcEnvironmentTexCoords((float *)tess.svars.texcoords[b]); + } else { + memset(tess.svars.texcoords[b], 0, sizeof(float) * 2 * tess.numVertexes); } break; case TCGEN_BAD: @@ -1490,64 +1324,55 @@ static void ComputeTexCoords( shaderStage_t *pStage ) { // // alter texture coordinates // - for ( tm = 0; tm < pStage->bundle[b].numTexMods ; tm++ ) { - switch ( pStage->bundle[b].texMods[tm].type ) - { + for (tm = 0; tm < pStage->bundle[b].numTexMods; tm++) { + switch (pStage->bundle[b].texMods[tm].type) { case TMOD_NONE: - tm = TR_MAX_TEXMODS; // break out of for loop + tm = TR_MAX_TEXMODS; // break out of for loop break; case TMOD_TURBULENT: - RB_CalcTurbulentTexCoords( &pStage->bundle[b].texMods[tm].wave, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcTurbulentTexCoords(&pStage->bundle[b].texMods[tm].wave, (float *)tess.svars.texcoords[b]); break; case TMOD_ENTITY_TRANSLATE: - RB_CalcScrollTexCoords( backEnd.currentEntity->e.shaderTexCoord, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScrollTexCoords(backEnd.currentEntity->e.shaderTexCoord, (float *)tess.svars.texcoords[b]); break; case TMOD_SCROLL: - RB_CalcScrollTexCoords( pStage->bundle[b].texMods[tm].translate, //scroll unioned - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScrollTexCoords(pStage->bundle[b].texMods[tm].translate, // scroll unioned + (float *)tess.svars.texcoords[b]); break; case TMOD_SCALE: - RB_CalcScaleTexCoords( pStage->bundle[b].texMods[tm].translate, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcScaleTexCoords(pStage->bundle[b].texMods[tm].translate, (float *)tess.svars.texcoords[b]); break; case TMOD_STRETCH: - RB_CalcStretchTexCoords( &pStage->bundle[b].texMods[tm].wave, - ( float * ) tess.svars.texcoords[b] ); + RB_CalcStretchTexCoords(&pStage->bundle[b].texMods[tm].wave, (float *)tess.svars.texcoords[b]); break; case TMOD_TRANSFORM: - RB_CalcTransformTexCoords( &pStage->bundle[b].texMods[tm], - ( float * ) tess.svars.texcoords[b] ); + RB_CalcTransformTexCoords(&pStage->bundle[b].texMods[tm], (float *)tess.svars.texcoords[b]); break; case TMOD_ROTATE: - RB_CalcRotateTexCoords( pStage->bundle[b].texMods[tm].translate[0], - ( float * ) tess.svars.texcoords[b] ); + RB_CalcRotateTexCoords(pStage->bundle[b].texMods[tm].translate[0], (float *)tess.svars.texcoords[b]); break; default: - Com_Error( ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'\n", pStage->bundle[b].texMods[tm].type, tess.shader->name ); + Com_Error(ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'\n", pStage->bundle[b].texMods[tm].type, tess.shader->name); break; } } } } -void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) -{ - int i; +void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) { + int i; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = TR_ForceEntAlpha; } } @@ -1555,44 +1380,35 @@ void ForceAlpha(unsigned char *dstColors, int TR_ForceEntAlpha) /* ** RB_IterateStagesGeneric */ -static vec4_t GLFogOverrideColors[GLFOGOVERRIDE_MAX] = -{ - { 0.0, 0.0, 0.0, 1.0 }, // GLFOGOVERRIDE_NONE - { 0.0, 0.0, 0.0, 1.0 }, // GLFOGOVERRIDE_BLACK - { 1.0, 1.0, 1.0, 1.0 } // GLFOGOVERRIDE_WHITE +static vec4_t GLFogOverrideColors[GLFOGOVERRIDE_MAX] = { + {0.0, 0.0, 0.0, 1.0}, // GLFOGOVERRIDE_NONE + {0.0, 0.0, 0.0, 1.0}, // GLFOGOVERRIDE_BLACK + {1.0, 1.0, 1.0, 1.0} // GLFOGOVERRIDE_WHITE }; -static const float logtestExp2 = (sqrt( -log( 1.0 / 255.0 ) )); -extern bool tr_stencilled; //tr_backend.cpp -static void RB_IterateStagesGeneric( shaderCommands_t *input ) -{ +static const float logtestExp2 = (sqrt(-log(1.0 / 255.0))); +extern bool tr_stencilled; // tr_backend.cpp +static void RB_IterateStagesGeneric(shaderCommands_t *input) { int stage; - bool UseGLFog = false; - bool FogColorChange = false; - fog_t *fog = NULL; + bool UseGLFog = false; + bool FogColorChange = false; + fog_t *fog = NULL; - if (tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs) - && r_drawfog->value == 2) - { // only gl fog global fog and the "special fog" + if (tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs) && + r_drawfog->value == 2) { // only gl fog global fog and the "special fog" fog = tr.world->fogs + tess.fogNum; - if (tr.rangedFog) - { //ranged fog, used for sniper scope + if (tr.rangedFog) { // ranged fog, used for sniper scope float fStart = fog->parms.depthForOpaque; - if (tr.rangedFog < 0.0f) - { //special designer override + if (tr.rangedFog < 0.0f) { // special designer override fStart = -tr.rangedFog; - } - else - { - //the greater tr.rangedFog is, the more fog we will get between the view point and cull distance - if ((tr.distanceCull-fStart) < tr.rangedFog) - { //assure a minimum range between fog beginning and cutoff distance - fStart = tr.distanceCull-tr.rangedFog; + } else { + // the greater tr.rangedFog is, the more fog we will get between the view point and cull distance + if ((tr.distanceCull - fStart) < tr.rangedFog) { // assure a minimum range between fog beginning and cutoff distance + fStart = tr.distanceCull - tr.rangedFog; - if (fStart < 16.0f) - { + if (fStart < 16.0f) { fStart = 16.0f; } } @@ -1602,133 +1418,105 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) qglFogf(GL_FOG_START, fStart); qglFogf(GL_FOG_END, tr.distanceCull); - } - else - { + } else { qglFogi(GL_FOG_MODE, GL_EXP2); qglFogf(GL_FOG_DENSITY, logtestExp2 / fog->parms.depthForOpaque); } - if ( g_bRenderGlowingObjects ) - { - const float fogColor[3] = { 0.0f, 0.0f, 0.0f }; - qglFogfv(GL_FOG_COLOR, fogColor ); - } - else - { + if (g_bRenderGlowingObjects) { + const float fogColor[3] = {0.0f, 0.0f, 0.0f}; + qglFogfv(GL_FOG_COLOR, fogColor); + } else { qglFogfv(GL_FOG_COLOR, fog->parms.color); } qglEnable(GL_FOG); UseGLFog = true; } - for ( stage = 0; stage < input->shader->numUnfoggedPasses; stage++ ) - { + for (stage = 0; stage < input->shader->numUnfoggedPasses; stage++) { shaderStage_t *pStage = &tess.xstages[stage]; int forceRGBGen = 0; int stateBits = 0; - if ( !pStage->active ) - { + if (!pStage->active) { break; } // Reject this stage if it's not a glow stage but we are doing a glow pass. - if ( g_bRenderGlowingObjects && !pStage->glow ) - { + if (g_bRenderGlowingObjects && !pStage->glow) { continue; } - if ( stage && r_lightmap->integer && !( pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap || pStage->bundle[0].vertexLightmap ) ) - { + if (stage && r_lightmap->integer && !(pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap || pStage->bundle[0].vertexLightmap)) { break; } stateBits = pStage->stateBits; - if ( backEnd.currentEntity ) - { + if (backEnd.currentEntity) { assert(backEnd.currentEntity->e.renderfx >= 0); - if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1 ) - { - // we want to be able to rip a hole in the thing being disintegrated, and by doing the depth-testing it avoids some kinds of artefacts, but will probably introduce others? + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1) { + // we want to be able to rip a hole in the thing being disintegrated, and by doing the depth-testing it avoids some kinds of artefacts, but will + // probably introduce others? stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHMASK_TRUE | GLS_ATEST_GE_C0; } - if ( backEnd.currentEntity->e.renderfx & RF_RGB_TINT ) - {//want to use RGBGen from ent + if (backEnd.currentEntity->e.renderfx & RF_RGB_TINT) { // want to use RGBGen from ent forceRGBGen = CGEN_ENTITY; } } - if (pStage->ss && pStage->ss->surfaceSpriteType) - { + if (pStage->ss && pStage->ss->surfaceSpriteType) { // We check for surfacesprites AFTER drawing everything else continue; } - if (UseGLFog) - { - if (pStage->mGLFogColorOverride) - { + if (UseGLFog) { + if (pStage->mGLFogColorOverride) { qglFogfv(GL_FOG_COLOR, GLFogOverrideColors[pStage->mGLFogColorOverride]); FogColorChange = true; - } - else if (FogColorChange && fog) - { + } else if (FogColorChange && fog) { FogColorChange = false; qglFogfv(GL_FOG_COLOR, fog->parms.color); } } - if (!input->fading) - { //this means ignore this, while we do a fade-out - ComputeColors( pStage, forceRGBGen ); + if (!input->fading) { // this means ignore this, while we do a fade-out + ComputeColors(pStage, forceRGBGen); } - ComputeTexCoords( pStage ); + ComputeTexCoords(pStage); - if ( !setArraysOnce ) - { - qglEnableClientState( GL_COLOR_ARRAY ); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, input->svars.colors ); + if (!setArraysOnce) { + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, input->svars.colors); } // // do multitexture // - if ( pStage->bundle[1].image != 0 ) - { - DrawMultitextured( input, stage ); - } - else - { + if (pStage->bundle[1].image != 0) { + DrawMultitextured(input, stage); + } else { static bool lStencilled = false; - if ( !setArraysOnce ) - { - qglTexCoordPointer( 2, GL_FLOAT, 0, input->svars.texcoords[0] ); + if (!setArraysOnce) { + qglTexCoordPointer(2, GL_FLOAT, 0, input->svars.texcoords[0]); } // // set state // - if ( (tess.shader == tr.distortionShader) || - (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_DISTORTION)) ) - { //special distortion effect -rww - //tr.screenImage should have been set for this specific entity before we got in here. - GL_Bind( tr.screenImage ); + if ((tess.shader == tr.distortionShader) || + (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_DISTORTION))) { // special distortion effect -rww + // tr.screenImage should have been set for this specific entity before we got in here. + GL_Bind(tr.screenImage); GL_Cull(CT_TWO_SIDED); - } - else if ( pStage->bundle[0].vertexLightmap && ( r_vertexLight->integer && !r_uiFullScreen->integer ) && r_lightmap->integer ) - { - GL_Bind( tr.whiteImage ); - } - else - R_BindAnimatedImage( &pStage->bundle[0] ); + } else if (pStage->bundle[0].vertexLightmap && (r_vertexLight->integer && !r_uiFullScreen->integer) && r_lightmap->integer) { + GL_Bind(tr.whiteImage); + } else + R_BindAnimatedImage(&pStage->bundle[0]); - if (tess.shader == tr.distortionShader && - glConfig.stencilBits >= 4) - { //draw it to the stencil buffer! + if (tess.shader == tr.distortionShader && glConfig.stencilBits >= 4) { // draw it to the stencil buffer! tr_stencilled = true; lStencilled = true; qglEnable(GL_STENCIL_TEST); @@ -1736,52 +1524,42 @@ static void RB_IterateStagesGeneric( shaderCommands_t *input ) qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - //don't depthmask, don't blend.. don't do anything + // don't depthmask, don't blend.. don't do anything GL_State(0); - } - else if (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA)) - { - ForceAlpha((unsigned char *) tess.svars.colors, backEnd.currentEntity->e.shaderRGBA[3]); - if (backEnd.currentEntity->e.renderfx & RF_ALPHA_DEPTH) - { //depth write, so faces through the model will be stomped over by nearer ones. this works because - //we draw RF_FORCE_ENT_ALPHA stuff after everything else, including standard alpha surfs. + } else if (backEnd.currentEntity && (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA)) { + ForceAlpha((unsigned char *)tess.svars.colors, backEnd.currentEntity->e.shaderRGBA[3]); + if (backEnd.currentEntity->e.renderfx & + RF_ALPHA_DEPTH) { // depth write, so faces through the model will be stomped over by nearer ones. this works because + // we draw RF_FORCE_ENT_ALPHA stuff after everything else, including standard alpha surfs. GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHMASK_TRUE); - } - else - { + } else { GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); } - } - else - { - GL_State( stateBits ); + } else { + GL_State(stateBits); } // // draw // - R_DrawElements( input->numIndexes, input->indexes ); + R_DrawElements(input->numIndexes, input->indexes); - if (lStencilled) - { //re-enable the color buffer, disable stencil test + if (lStencilled) { // re-enable the color buffer, disable stencil test lStencilled = false; qglDisable(GL_STENCIL_TEST); qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } } } - if (FogColorChange) - { + if (FogColorChange) { qglFogfv(GL_FOG_COLOR, fog->parms.color); } } - /* ** RB_StageIteratorGeneric */ -void RB_StageIteratorGeneric( void ) -{ +void RB_StageIteratorGeneric(void) { shaderCommands_t *input; int stage; @@ -1792,23 +1570,21 @@ void RB_StageIteratorGeneric( void ) // // log this call // - if ( r_logFile->integer ) - { + if (r_logFile->integer) { // don't just call LogComment, or we will get // a call to va() every frame! - GLimp_LogComment( va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name) ); + GLimp_LogComment(va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name)); } // // set face culling appropriately // - GL_Cull( input->shader->cullType ); + GL_Cull(input->shader->cullType); // set polygon offset if necessary - if ( input->shader->polygonOffset ) - { - qglEnable( GL_POLYGON_OFFSET_FILL ); - qglPolygonOffset( r_offsetFactor->value, r_offsetUnits->value ); + if (input->shader->polygonOffset) { + qglEnable(GL_POLYGON_OFFSET_FILL); + qglPolygonOffset(r_offsetFactor->value, r_offsetUnits->value); } // @@ -1817,58 +1593,49 @@ void RB_StageIteratorGeneric( void ) // to avoid compiling those arrays since they will change // during multipass rendering // - if ( tess.numPasses > 1 || input->shader->multitextureEnv ) - { + if (tess.numPasses > 1 || input->shader->multitextureEnv) { setArraysOnce = qfalse; - qglDisableClientState (GL_COLOR_ARRAY); - qglDisableClientState (GL_TEXTURE_COORD_ARRAY); - } - else - { + qglDisableClientState(GL_COLOR_ARRAY); + qglDisableClientState(GL_TEXTURE_COORD_ARRAY); + } else { setArraysOnce = qtrue; - qglEnableClientState( GL_COLOR_ARRAY); - qglColorPointer( 4, GL_UNSIGNED_BYTE, 0, tess.svars.colors ); + qglEnableClientState(GL_COLOR_ARRAY); + qglColorPointer(4, GL_UNSIGNED_BYTE, 0, tess.svars.colors); - qglEnableClientState( GL_TEXTURE_COORD_ARRAY); - qglTexCoordPointer( 2, GL_FLOAT, 0, tess.svars.texcoords[0] ); + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglTexCoordPointer(2, GL_FLOAT, 0, tess.svars.texcoords[0]); } // // lock XYZ // - qglVertexPointer (3, GL_FLOAT, 16, input->xyz); // padded for SIMD - if (qglLockArraysEXT) - { + qglVertexPointer(3, GL_FLOAT, 16, input->xyz); // padded for SIMD + if (qglLockArraysEXT) { qglLockArraysEXT(0, input->numVertexes); - GLimp_LogComment( "glLockArraysEXT\n" ); + GLimp_LogComment("glLockArraysEXT\n"); } // // enable color and texcoord arrays after the lock if necessary // - if ( !setArraysOnce ) - { - qglEnableClientState( GL_TEXTURE_COORD_ARRAY ); - qglEnableClientState( GL_COLOR_ARRAY ); + if (!setArraysOnce) { + qglEnableClientState(GL_TEXTURE_COORD_ARRAY); + qglEnableClientState(GL_COLOR_ARRAY); } // // call shader function // - RB_IterateStagesGeneric( input ); + RB_IterateStagesGeneric(input); // // now do any dynamic lighting needed // - if ( tess.dlightBits && tess.shader->sort <= SS_OPAQUE - && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY) ) ) { - if (r_dlightStyle->integer>0) - { + if (tess.dlightBits && tess.shader->sort <= SS_OPAQUE && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY))) { + if (r_dlightStyle->integer > 0) { ProjectDlightTexture2(); - } - else - { + } else { ProjectDlightTexture(); } } @@ -1876,54 +1643,44 @@ void RB_StageIteratorGeneric( void ) // // now do fog // - if (tr.world && (tess.fogNum != tr.world->globalFog || r_drawfog->value != 2) && r_drawfog->value && tess.fogNum && tess.shader->fogPass) - { + if (tr.world && (tess.fogNum != tr.world->globalFog || r_drawfog->value != 2) && r_drawfog->value && tess.fogNum && tess.shader->fogPass) { RB_FogPass(); } // // unlock arrays // - if (qglUnlockArraysEXT) - { + if (qglUnlockArraysEXT) { qglUnlockArraysEXT(); - GLimp_LogComment( "glUnlockArraysEXT\n" ); + GLimp_LogComment("glUnlockArraysEXT\n"); } // // reset polygon offset // - if ( input->shader->polygonOffset ) - { - qglDisable( GL_POLYGON_OFFSET_FILL ); + if (input->shader->polygonOffset) { + qglDisable(GL_POLYGON_OFFSET_FILL); } // Now check for surfacesprites. - if (r_surfaceSprites->integer) - { - for ( stage = 1; stage < tess.shader->numUnfoggedPasses; stage++ ) - { - if (tess.xstages[stage].ss && tess.xstages[stage].ss->surfaceSpriteType) - { // Draw the surfacesprite + if (r_surfaceSprites->integer) { + for (stage = 1; stage < tess.shader->numUnfoggedPasses; stage++) { + if (tess.xstages[stage].ss && tess.xstages[stage].ss->surfaceSpriteType) { // Draw the surfacesprite RB_DrawSurfaceSprites(&tess.xstages[stage], input); } } } - //don't disable the hardware fog til after we do surface sprites - if (r_drawfog->value == 2 && - tess.fogNum && tess.shader->fogPass && - (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) - { + // don't disable the hardware fog til after we do surface sprites + if (r_drawfog->value == 2 && tess.fogNum && tess.shader->fogPass && (tess.fogNum == tr.world->globalFog || tess.fogNum == tr.world->numfogs)) { qglDisable(GL_FOG); } } - /* ** RB_EndSurface */ -void RB_EndSurface( void ) { +void RB_EndSurface(void) { shaderCommands_t *input; input = &tess; @@ -1932,40 +1689,34 @@ void RB_EndSurface( void ) { return; } - if (input->indexes[SHADER_MAX_INDEXES-1] != 0) { - Com_Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); + if (input->indexes[SHADER_MAX_INDEXES - 1] != 0) { + Com_Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); } - if (input->xyz[SHADER_MAX_VERTEXES-1][0] != 0) { - Com_Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); + if (input->xyz[SHADER_MAX_VERTEXES - 1][0] != 0) { + Com_Error(ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); } - if ( tess.shader == tr.shadowShader ) { + if (tess.shader == tr.shadowShader) { RB_ShadowTessEnd(); return; } // for debugging of sort order issues, stop rendering after a given sort value - if ( r_debugSort->integer && r_debugSort->integer < tess.shader->sort ) { + if (r_debugSort->integer && r_debugSort->integer < tess.shader->sort) { return; } - if ( skyboxportal ) - { + if (skyboxportal) { // world - if(!(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) - { - if(tess.currentStageIteratorFunc == RB_StageIteratorSky) - { // don't process these tris at all + if (!(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) { + if (tess.currentStageIteratorFunc == RB_StageIteratorSky) { // don't process these tris at all return; } } // portal sky - else - { - if(!drawskyboxportal) - { - if( !(tess.currentStageIteratorFunc == RB_StageIteratorSky)) - { // /only/ process sky tris + else { + if (!drawskyboxportal) { + if (!(tess.currentStageIteratorFunc == RB_StageIteratorSky)) { // /only/ process sky tris return; } } @@ -1979,8 +1730,7 @@ void RB_EndSurface( void ) { backEnd.pc.c_vertexes += tess.numVertexes; backEnd.pc.c_indexes += tess.numIndexes; backEnd.pc.c_totalIndexes += tess.numIndexes * tess.numPasses; - if (tess.fogNum && tess.shader->fogPass && r_drawfog->value == 1) - { + if (tess.fogNum && tess.shader->fogPass && r_drawfog->value == 1) { backEnd.pc.c_totalIndexes += tess.numIndexes; } @@ -1992,15 +1742,14 @@ void RB_EndSurface( void ) { // // draw debugging stuff // - if ( r_showtris->integer ) { - DrawTris (input); + if (r_showtris->integer) { + DrawTris(input); } - if ( r_shownormals->integer ) { - DrawNormals (input); + if (r_shownormals->integer) { + DrawNormals(input); } // clear shader so we can tell we don't have any unclosed surfaces tess.numIndexes = 0; - GLimp_LogComment( "----------\n" ); + GLimp_LogComment("----------\n"); } - diff --git a/codemp/rd-vanilla/tr_shade_calc.cpp b/codemp/rd-vanilla/tr_shade_calc.cpp index 254bdddf30..4e871f5031 100644 --- a/codemp/rd-vanilla/tr_shade_calc.cpp +++ b/codemp/rd-vanilla/tr_shade_calc.cpp @@ -26,13 +26,11 @@ along with this program; if not, see . #include "tr_local.h" #include "../rd-common/tr_common.h" +#define WAVEVALUE(table, base, amplitude, phase, freq) \ + ((base) + table[Q_ftol((((phase) + tess.shaderTime * (freq)) * FUNCTABLE_SIZE)) & FUNCTABLE_MASK] * (amplitude)) -#define WAVEVALUE( table, base, amplitude, phase, freq ) ((base) + table[ Q_ftol( ( ( (phase) + tess.shaderTime * (freq) ) * FUNCTABLE_SIZE ) ) & FUNCTABLE_MASK ] * (amplitude)) - -static float *TableForFunc( genFunc_t func ) -{ - switch ( func ) - { +static float *TableForFunc(genFunc_t func) { + switch (func) { case GF_SIN: return tr.sinTable; case GF_TRIANGLE: @@ -48,7 +46,7 @@ static float *TableForFunc( genFunc_t func ) break; } - Com_Error( ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'\n", func, tess.shader->name ); + Com_Error(ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'\n", func, tess.shader->name); return NULL; } @@ -57,35 +55,31 @@ static float *TableForFunc( genFunc_t func ) ** ** Evaluates a given waveForm_t, referencing backEnd.refdef.time directly */ -static float EvalWaveForm( const waveForm_t *wf ) -{ - float *table; +static float EvalWaveForm(const waveForm_t *wf) { + float *table; - if ( wf->func == GF_NOISE ) { - return ( wf->base + R_NoiseGet4f( 0, 0, 0, ( backEnd.refdef.floatTime + wf->phase ) * wf->frequency ) * wf->amplitude ); + if (wf->func == GF_NOISE) { + return (wf->base + R_NoiseGet4f(0, 0, 0, (backEnd.refdef.floatTime + wf->phase) * wf->frequency) * wf->amplitude); } else if (wf->func == GF_RAND) { - if( GetNoiseTime( backEnd.refdef.time + wf->phase ) <= wf->frequency ) { + if (GetNoiseTime(backEnd.refdef.time + wf->phase) <= wf->frequency) { return (wf->base + wf->amplitude); } else { return wf->base; } } - table = TableForFunc( wf->func ); + table = TableForFunc(wf->func); - return WAVEVALUE( table, wf->base, wf->amplitude, wf->phase, wf->frequency ); + return WAVEVALUE(table, wf->base, wf->amplitude, wf->phase, wf->frequency); } -static float EvalWaveFormClamped( const waveForm_t *wf ) -{ - float glow = EvalWaveForm( wf ); +static float EvalWaveFormClamped(const waveForm_t *wf) { + float glow = EvalWaveForm(wf); - if ( glow < 0 ) - { + if (glow < 0) { return 0; } - if ( glow > 1 ) - { + if (glow > 1) { return 1; } @@ -95,12 +89,11 @@ static float EvalWaveFormClamped( const waveForm_t *wf ) /* ** RB_CalcStretchTexCoords */ -void RB_CalcStretchTexCoords( const waveForm_t *wf, float *st ) -{ +void RB_CalcStretchTexCoords(const waveForm_t *wf, float *st) { float p; texModInfo_t tmi; - p = 1.0f / EvalWaveForm( wf ); + p = 1.0f / EvalWaveForm(wf); tmi.matrix[0][0] = p; tmi.matrix[1][0] = 0; @@ -110,7 +103,7 @@ void RB_CalcStretchTexCoords( const waveForm_t *wf, float *st ) tmi.matrix[1][1] = p; tmi.translate[1] = 0.5f - 0.5f * p; - RB_CalcTransformTexCoords( &tmi, st ); + RB_CalcTransformTexCoords(&tmi, st); } /* @@ -127,42 +120,33 @@ RB_CalcDeformVertexes ======================== */ -void RB_CalcDeformVertexes( deformStage_t *ds ) -{ +void RB_CalcDeformVertexes(deformStage_t *ds) { int i; - vec3_t offset; - float scale; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float *table; + vec3_t offset; + float scale; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float *table; - if ( ds->deformationWave.frequency == 0 ) - { - scale = EvalWaveForm( &ds->deformationWave ); + if (ds->deformationWave.frequency == 0) { + scale = EvalWaveForm(&ds->deformationWave); - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - VectorScale( normal, scale, offset ); + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + VectorScale(normal, scale, offset); xyz[0] += offset[0]; xyz[1] += offset[1]; xyz[2] += offset[2]; } - } - else - { - table = TableForFunc( ds->deformationWave.func ); + } else { + table = TableForFunc(ds->deformationWave.func); - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - float off = ( xyz[0] + xyz[1] + xyz[2] ) * ds->deformationSpread; + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + float off = (xyz[0] + xyz[1] + xyz[2]) * ds->deformationSpread; - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase + off, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase + off, ds->deformationWave.frequency); - VectorScale( normal, scale, offset ); + VectorScale(normal, scale, offset); xyz[0] += offset[0]; xyz[1] += offset[1]; @@ -178,29 +162,26 @@ RB_CalcDeformNormals Wiggle the normals for wavy environment mapping ========================= */ -void RB_CalcDeformNormals( deformStage_t *ds ) { +void RB_CalcDeformNormals(deformStage_t *ds) { int i; - float scale; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; + float scale; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) { + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { scale = 0.98f; - scale = R_NoiseGet4f( xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - normal[ 0 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + normal[0] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - normal[ 1 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + normal[1] += ds->deformationWave.amplitude * scale; scale = 0.98f; - scale = R_NoiseGet4f( 200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, - tess.shaderTime * ds->deformationWave.frequency ); - normal[ 2 ] += ds->deformationWave.amplitude * scale; + scale = R_NoiseGet4f(200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, tess.shaderTime * ds->deformationWave.frequency); + normal[2] += ds->deformationWave.amplitude * scale; - VectorNormalizeFast( normal ); + VectorNormalizeFast(normal); } } @@ -210,9 +191,8 @@ RB_CalcBulgeVertexes ======================== */ -void RB_CalcBulgeVertexes( deformStage_t *ds ) -{ - //Old bulge code: +void RB_CalcBulgeVertexes(deformStage_t *ds) { + // Old bulge code: /* int i; const float *st = ( const float * ) tess.texCoords[0]; @@ -236,36 +216,31 @@ void RB_CalcBulgeVertexes( deformStage_t *ds ) } */ - int i; - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float scale; + int i; + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float scale; - if ( ds->bulgeSpeed == 0.0f && ds->bulgeWidth == 0.0f ) - { + if (ds->bulgeSpeed == 0.0f && ds->bulgeWidth == 0.0f) { // We don't have a speed and width, so just use height to expand uniformly - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { xyz[0] += normal[0] * ds->bulgeHeight; xyz[1] += normal[1] * ds->bulgeHeight; xyz[2] += normal[2] * ds->bulgeHeight; } - } - else - { + } else { // I guess do some extra dumb stuff..the fact that it uses ST seems bad though because skin pages may be set up in certain ways that can cause // very noticeable seams on sufaces ( like on the huge ion_cannon ). - const float *st = ( const float * ) tess.texCoords[0]; - float now; - int off; + const float *st = (const float *)tess.texCoords[0]; + float now; + int off; now = backEnd.refdef.time * ds->bulgeSpeed * 0.001f; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4, st += 2 * NUM_TEX_COORDS, normal += 4 ) - { - off = (float)( FUNCTABLE_SIZE / (M_PI*2) ) * ( st[0] * ds->bulgeWidth + now ); + for (i = 0; i < tess.numVertexes; i++, xyz += 4, st += 2 * NUM_TEX_COORDS, normal += 4) { + off = (float)(FUNCTABLE_SIZE / (M_PI * 2)) * (st[0] * ds->bulgeWidth + now); - scale = tr.sinTable[ off & FUNCTABLE_MASK ] * ds->bulgeHeight; + scale = tr.sinTable[off & FUNCTABLE_MASK] * ds->bulgeHeight; xyz[0] += normal[0] * scale; xyz[1] += normal[1] * scale; @@ -274,7 +249,6 @@ void RB_CalcBulgeVertexes( deformStage_t *ds ) } } - /* ====================== RB_CalcMoveVertexes @@ -282,29 +256,25 @@ RB_CalcMoveVertexes A deformation that can move an entire surface along a wave path ====================== */ -void RB_CalcMoveVertexes( deformStage_t *ds ) { - int i; - float *xyz; - float *table; - float scale; - vec3_t offset; +void RB_CalcMoveVertexes(deformStage_t *ds) { + int i; + float *xyz; + float *table; + float scale; + vec3_t offset; - table = TableForFunc( ds->deformationWave.func ); + table = TableForFunc(ds->deformationWave.func); - scale = WAVEVALUE( table, ds->deformationWave.base, - ds->deformationWave.amplitude, - ds->deformationWave.phase, - ds->deformationWave.frequency ); + scale = WAVEVALUE(table, ds->deformationWave.base, ds->deformationWave.amplitude, ds->deformationWave.phase, ds->deformationWave.frequency); - VectorScale( ds->moveVector, scale, offset ); + VectorScale(ds->moveVector, scale, offset); - xyz = ( float * ) tess.xyz; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - VectorAdd( xyz, offset, xyz ); + xyz = (float *)tess.xyz; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + VectorAdd(xyz, offset, xyz); } } - /* ============= DeformText @@ -312,45 +282,45 @@ DeformText Change a polygon into a bunch of text polygons ============= */ -void DeformText( const char *text ) { - int i; - vec3_t origin, width, height; - int len; - int ch; - byte color[4]; - float bottom, top; - vec3_t mid; +void DeformText(const char *text) { + int i; + vec3_t origin, width, height; + int len; + int ch; + byte color[4]; + float bottom, top; + vec3_t mid; height[0] = 0; height[1] = 0; height[2] = -1; - CrossProduct( tess.normal[0], height, width ); + CrossProduct(tess.normal[0], height, width); // find the midpoint of the box - VectorClear( mid ); + VectorClear(mid); bottom = 999999; top = -999999; - for ( i = 0 ; i < 4 ; i++ ) { - VectorAdd( tess.xyz[i], mid, mid ); - if ( tess.xyz[i][2] < bottom ) { + for (i = 0; i < 4; i++) { + VectorAdd(tess.xyz[i], mid, mid); + if (tess.xyz[i][2] < bottom) { bottom = tess.xyz[i][2]; } - if ( tess.xyz[i][2] > top ) { + if (tess.xyz[i][2] > top) { top = tess.xyz[i][2]; } } - VectorScale( mid, 0.25f, origin ); + VectorScale(mid, 0.25f, origin); // determine the individual character size height[0] = 0; height[1] = 0; - height[2] = ( top - bottom ) * 0.5f; + height[2] = (top - bottom) * 0.5f; - VectorScale( width, height[2] * -0.75f, width ); + VectorScale(width, height[2] * -0.75f, width); // determine the starting position - len = strlen( text ); - VectorMA( origin, (len-1), width, origin ); + len = strlen(text); + VectorMA(origin, (len - 1), width, origin); // clear the shader indexes tess.numIndexes = 0; @@ -359,24 +329,24 @@ void DeformText( const char *text ) { color[0] = color[1] = color[2] = color[3] = 255; // draw each character - for ( i = 0 ; i < len ; i++ ) { + for (i = 0; i < len; i++) { ch = text[i]; ch &= 255; - if ( ch != ' ' ) { - int row, col; - float frow, fcol, size; + if (ch != ' ') { + int row, col; + float frow, fcol, size; - row = ch>>4; - col = ch&15; + row = ch >> 4; + col = ch & 15; - frow = row*0.0625f; - fcol = col*0.0625f; + frow = row * 0.0625f; + fcol = col * 0.0625f; size = 0.0625f; - RB_AddQuadStampExt( origin, width, height, color, fcol, frow, fcol + size, frow + size ); + RB_AddQuadStampExt(origin, width, height, color, fcol, frow, fcol + size, frow + size); } - VectorMA( origin, -2, width, origin ); + VectorMA(origin, -2, width, origin); } } @@ -385,10 +355,10 @@ void DeformText( const char *text ) { GlobalVectorToLocal ================== */ -static void GlobalVectorToLocal( const vec3_t in, vec3_t out ) { - out[0] = DotProduct( in, backEnd.ori.axis[0] ); - out[1] = DotProduct( in, backEnd.ori.axis[1] ); - out[2] = DotProduct( in, backEnd.ori.axis[2] ); +static void GlobalVectorToLocal(const vec3_t in, vec3_t out) { + out[0] = DotProduct(in, backEnd.ori.axis[0]); + out[1] = DotProduct(in, backEnd.ori.axis[1]); + out[2] = DotProduct(in, backEnd.ori.axis[2]); } /* @@ -399,35 +369,35 @@ Assuming all the triangles for this shader are independent quads, rebuild them as forward facing sprites ===================== */ -static void AutospriteDeform( void ) { - int i; - int oldVerts; - float *xyz; - vec3_t mid, delta; - float radius; - vec3_t left, up; - vec3_t leftDir, upDir; - - if ( tess.numVertexes & 3 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Autosprite shader %s had odd vertex count", tess.shader->name ); +static void AutospriteDeform(void) { + int i; + int oldVerts; + float *xyz; + vec3_t mid, delta; + float radius; + vec3_t left, up; + vec3_t leftDir, upDir; + + if (tess.numVertexes & 3) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "Autosprite shader %s had odd vertex count", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Autosprite shader %s had odd index count", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "Autosprite shader %s had odd index count", tess.shader->name); } oldVerts = tess.numVertexes; tess.numVertexes = 0; tess.numIndexes = 0; - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[1], leftDir ); - GlobalVectorToLocal( backEnd.viewParms.ori.axis[2], upDir ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[1], leftDir); + GlobalVectorToLocal(backEnd.viewParms.ori.axis[2], upDir); } else { - VectorCopy( backEnd.viewParms.ori.axis[1], leftDir ); - VectorCopy( backEnd.viewParms.ori.axis[2], upDir ); + VectorCopy(backEnd.viewParms.ori.axis[1], leftDir); + VectorCopy(backEnd.viewParms.ori.axis[2], upDir); } - for ( i = 0 ; i < oldVerts ; i+=4 ) { + for (i = 0; i < oldVerts; i += 4) { // find the midpoint xyz = tess.xyz[i]; @@ -435,34 +405,33 @@ static void AutospriteDeform( void ) { mid[1] = 0.25f * (xyz[1] + xyz[5] + xyz[9] + xyz[13]); mid[2] = 0.25f * (xyz[2] + xyz[6] + xyz[10] + xyz[14]); - VectorSubtract( xyz, mid, delta ); - radius = VectorLength( delta ) * 0.707f; // / sqrt(2) + VectorSubtract(xyz, mid, delta); + radius = VectorLength(delta) * 0.707f; // / sqrt(2) - VectorScale( leftDir, radius, left ); - VectorScale( upDir, radius, up ); + VectorScale(leftDir, radius, left); + VectorScale(upDir, radius, up); - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - // compensate for scale in the axes if necessary - if ( backEnd.currentEntity->e.nonNormalizedAxes ) { - float axisLength; - axisLength = VectorLength( backEnd.currentEntity->e.axis[0] ); - if ( !axisLength ) { - axisLength = 0; - } else { - axisLength = 1.0f / axisLength; - } - VectorScale(left, axisLength, left); - VectorScale(up, axisLength, up); - } - - RB_AddQuadStamp( mid, left, up, tess.vertexColors[i] ); + // compensate for scale in the axes if necessary + if (backEnd.currentEntity->e.nonNormalizedAxes) { + float axisLength; + axisLength = VectorLength(backEnd.currentEntity->e.axis[0]); + if (!axisLength) { + axisLength = 0; + } else { + axisLength = 1.0f / axisLength; + } + VectorScale(left, axisLength, left); + VectorScale(up, axisLength, up); + } + + RB_AddQuadStamp(mid, left, up, tess.vertexColors[i]); } } - /* ===================== Autosprite2Deform @@ -470,43 +439,36 @@ Autosprite2Deform Autosprite2 will pivot a rectangular quad along the center of its long axis ===================== */ -int edgeVerts[6][2] = { - { 0, 1 }, - { 0, 2 }, - { 0, 3 }, - { 1, 2 }, - { 1, 3 }, - { 2, 3 } -}; - -static void Autosprite2Deform( void ) { - int i, j, k; - int indexes; - float *xyz; - vec3_t forward; - - if ( tess.numVertexes & 3 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Autosprite2 shader %s had odd vertex count", tess.shader->name ); +int edgeVerts[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}}; + +static void Autosprite2Deform(void) { + int i, j, k; + int indexes; + float *xyz; + vec3_t forward; + + if (tess.numVertexes & 3) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "Autosprite2 shader %s had odd vertex count", tess.shader->name); } - if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Autosprite2 shader %s had odd index count", tess.shader->name ); + if (tess.numIndexes != (tess.numVertexes >> 2) * 6) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "Autosprite2 shader %s had odd index count", tess.shader->name); } - if ( backEnd.currentEntity != &tr.worldEntity ) { - GlobalVectorToLocal( backEnd.viewParms.ori.axis[0], forward ); + if (backEnd.currentEntity != &tr.worldEntity) { + GlobalVectorToLocal(backEnd.viewParms.ori.axis[0], forward); } else { - VectorCopy( backEnd.viewParms.ori.axis[0], forward ); + VectorCopy(backEnd.viewParms.ori.axis[0], forward); } // this is a lot of work for two triangles... // we could precalculate a lot of it is an issue, but it would mess up // the shader abstraction - for ( i = 0, indexes = 0 ; i < tess.numVertexes ; i+=4, indexes+=6 ) { - float lengths[2]; - int nums[2]; - vec3_t mid[2]; - vec3_t major, minor; - float *v1, *v2; + for (i = 0, indexes = 0; i < tess.numVertexes; i += 4, indexes += 6) { + float lengths[2]; + int nums[2]; + vec3_t mid[2]; + vec3_t major, minor; + float *v1, *v2; // find the midpoint xyz = tess.xyz[i]; @@ -515,28 +477,28 @@ static void Autosprite2Deform( void ) { nums[0] = nums[1] = 0; lengths[0] = lengths[1] = 999999; - for ( j = 0 ; j < 6 ; j++ ) { - float l; - vec3_t temp; + for (j = 0; j < 6; j++) { + float l; + vec3_t temp; v1 = xyz + 4 * edgeVerts[j][0]; v2 = xyz + 4 * edgeVerts[j][1]; - VectorSubtract( v1, v2, temp ); + VectorSubtract(v1, v2, temp); - l = DotProduct( temp, temp ); - if ( l < lengths[0] ) { + l = DotProduct(temp, temp); + if (l < lengths[0]) { nums[1] = nums[0]; lengths[1] = lengths[0]; nums[0] = j; lengths[0] = l; - } else if ( l < lengths[1] ) { + } else if (l < lengths[1]) { nums[1] = j; lengths[1] = l; } } - for ( j = 0 ; j < 2 ; j++ ) { + for (j = 0; j < 2; j++) { v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; @@ -546,69 +508,68 @@ static void Autosprite2Deform( void ) { } // find the vector of the major axis - VectorSubtract( mid[1], mid[0], major ); + VectorSubtract(mid[1], mid[0], major); // cross this with the view direction to get minor axis - CrossProduct( major, forward, minor ); - VectorNormalize( minor ); + CrossProduct(major, forward, minor); + VectorNormalize(minor); // re-project the points - for ( j = 0 ; j < 2 ; j++ ) { - float l; + for (j = 0; j < 2; j++) { + float l; v1 = xyz + 4 * edgeVerts[nums[j]][0]; v2 = xyz + 4 * edgeVerts[nums[j]][1]; - l = 0.5 * sqrt( lengths[j] ); + l = 0.5 * sqrt(lengths[j]); // we need to see which direction this edge // is used to determine direction of projection - for ( k = 0 ; k < 5 ; k++ ) { - if ( tess.indexes[ indexes + k ] == (unsigned)(i + edgeVerts[nums[j]][0]) - && tess.indexes[ indexes + k + 1 ] == (unsigned)(i + edgeVerts[nums[j]][1]) ) { + for (k = 0; k < 5; k++) { + if (tess.indexes[indexes + k] == (unsigned)(i + edgeVerts[nums[j]][0]) && + tess.indexes[indexes + k + 1] == (unsigned)(i + edgeVerts[nums[j]][1])) { break; } } - if ( k == 5 ) { - VectorMA( mid[j], l, minor, v1 ); - VectorMA( mid[j], -l, minor, v2 ); + if (k == 5) { + VectorMA(mid[j], l, minor, v1); + VectorMA(mid[j], -l, minor, v2); } else { - VectorMA( mid[j], -l, minor, v1 ); - VectorMA( mid[j], l, minor, v2 ); + VectorMA(mid[j], -l, minor, v1); + VectorMA(mid[j], l, minor, v2); } } } } - /* ===================== RB_DeformTessGeometry ===================== */ -void RB_DeformTessGeometry( void ) { - int i; - deformStage_t *ds; +void RB_DeformTessGeometry(void) { + int i; + deformStage_t *ds; - for ( i = 0 ; i < tess.shader->numDeforms ; i++ ) { - ds = tess.shader->deforms[ i ]; + for (i = 0; i < tess.shader->numDeforms; i++) { + ds = tess.shader->deforms[i]; - switch ( ds->deformation ) { - case DEFORM_NONE: - break; + switch (ds->deformation) { + case DEFORM_NONE: + break; case DEFORM_NORMALS: - RB_CalcDeformNormals( ds ); + RB_CalcDeformNormals(ds); break; case DEFORM_WAVE: - RB_CalcDeformVertexes( ds ); + RB_CalcDeformVertexes(ds); break; case DEFORM_BULGE: - RB_CalcBulgeVertexes( ds ); + RB_CalcBulgeVertexes(ds); break; case DEFORM_MOVE: - RB_CalcMoveVertexes( ds ); + RB_CalcMoveVertexes(ds); break; case DEFORM_PROJECTION_SHADOW: RB_ProjectionShadowDeform(); @@ -627,7 +588,7 @@ void RB_DeformTessGeometry( void ) { case DEFORM_TEXT5: case DEFORM_TEXT6: case DEFORM_TEXT7: - DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] ); + DeformText(backEnd.refdef.text[ds->deformation - DEFORM_TEXT0]); break; } } @@ -641,22 +602,20 @@ COLORS ==================================================================== */ - /* ** RB_CalcColorFromEntity */ -void RB_CalcColorFromEntity( unsigned char *dstColors ) -{ - int i; - int *pColors = ( int * ) dstColors; +void RB_CalcColorFromEntity(unsigned char *dstColors) { + int i; + int *pColors = (int *)dstColors; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; const byteAlias_t *ba = (byteAlias_t *)&backEnd.currentEntity->e.shaderRGBA; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *pColors++ = ba->i; } } @@ -664,23 +623,22 @@ void RB_CalcColorFromEntity( unsigned char *dstColors ) /* ** RB_CalcColorFromOneMinusEntity */ -void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ) -{ - int i; - int *pColors = ( int * ) dstColors; +void RB_CalcColorFromOneMinusEntity(unsigned char *dstColors) { + int i; + int *pColors = (int *)dstColors; unsigned char invModulate[4]; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; invModulate[0] = 255 - backEnd.currentEntity->e.shaderRGBA[0]; invModulate[1] = 255 - backEnd.currentEntity->e.shaderRGBA[1]; invModulate[2] = 255 - backEnd.currentEntity->e.shaderRGBA[2]; - invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3]; // this trashes alpha, but the AGEN block fixes it + invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3]; // this trashes alpha, but the AGEN block fixes it byteAlias_t *ba = (byteAlias_t *)&invModulate; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *pColors++ = ba->i; } } @@ -688,17 +646,15 @@ void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ) /* ** RB_CalcAlphaFromEntity */ -void RB_CalcAlphaFromEntity( unsigned char *dstColors ) -{ - int i; +void RB_CalcAlphaFromEntity(unsigned char *dstColors) { + int i; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = backEnd.currentEntity->e.shaderRGBA[3]; } } @@ -706,17 +662,15 @@ void RB_CalcAlphaFromEntity( unsigned char *dstColors ) /* ** RB_CalcAlphaFromOneMinusEntity */ -void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors ) -{ - int i; +void RB_CalcAlphaFromOneMinusEntity(unsigned char *dstColors) { + int i; - if ( !backEnd.currentEntity ) + if (!backEnd.currentEntity) return; dstColors += 3; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { *dstColors = 0xff - backEnd.currentEntity->e.shaderRGBA[3]; } } @@ -724,34 +678,31 @@ void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors ) /* ** RB_CalcWaveColor */ -void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors ) -{ +void RB_CalcWaveColor(const waveForm_t *wf, unsigned char *dstColors) { int i; int v; float glow; - int *colors = ( int * ) dstColors; - byte color[4]; - + int *colors = (int *)dstColors; + byte color[4]; - if ( wf->func == GF_NOISE ) { - glow = wf->base + R_NoiseGet4f( 0, 0, 0, ( tess.shaderTime + wf->phase ) * wf->frequency ) * wf->amplitude; + if (wf->func == GF_NOISE) { + glow = wf->base + R_NoiseGet4f(0, 0, 0, (tess.shaderTime + wf->phase) * wf->frequency) * wf->amplitude; } else { - glow = EvalWaveForm( wf ) * tr.identityLight; + glow = EvalWaveForm(wf) * tr.identityLight; } - if ( glow < 0 ) { + if (glow < 0) { glow = 0; - } - else if ( glow > 1 ) { + } else if (glow > 1) { glow = 1; } - v = Q_ftol( 255 * glow ); + v = Q_ftol(255 * glow); color[0] = color[1] = color[2] = v; color[3] = 255; byteAlias_t *ba = (byteAlias_t *)&color; - for ( i = 0; i < tess.numVertexes; i++ ) { + for (i = 0; i < tess.numVertexes; i++) { *colors++ = ba->i; } } @@ -759,18 +710,16 @@ void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors ) /* ** RB_CalcWaveAlpha */ -void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors ) -{ +void RB_CalcWaveAlpha(const waveForm_t *wf, unsigned char *dstColors) { int i; int v; float glow; - glow = EvalWaveFormClamped( wf ); + glow = EvalWaveFormClamped(wf); v = 255 * glow; - for ( i = 0; i < tess.numVertexes; i++, dstColors += 4 ) - { + for (i = 0; i < tess.numVertexes; i++, dstColors += 4) { dstColors[3] = v; } } @@ -778,17 +727,17 @@ void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors ) /* ** RB_CalcModulateColorsByFog */ -void RB_CalcModulateColorsByFog( unsigned char *colors ) { - int i; - float texCoords[SHADER_MAX_VERTEXES][2]; +void RB_CalcModulateColorsByFog(unsigned char *colors) { + int i; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[0] *= f; colors[1] *= f; colors[2] *= f; @@ -798,17 +747,17 @@ void RB_CalcModulateColorsByFog( unsigned char *colors ) { /* ** RB_CalcModulateAlphasByFog */ -void RB_CalcModulateAlphasByFog( unsigned char *colors ) { - int i; - float texCoords[SHADER_MAX_VERTEXES][2]; +void RB_CalcModulateAlphasByFog(unsigned char *colors) { + int i; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[3] *= f; } } @@ -816,17 +765,17 @@ void RB_CalcModulateAlphasByFog( unsigned char *colors ) { /* ** RB_CalcModulateRGBAsByFog */ -void RB_CalcModulateRGBAsByFog( unsigned char *colors ) { - int i; - float texCoords[SHADER_MAX_VERTEXES][2]; +void RB_CalcModulateRGBAsByFog(unsigned char *colors) { + int i; + float texCoords[SHADER_MAX_VERTEXES][2]; // calculate texcoords so we can derive density // this is not wasted, because it would only have // been previously called if the surface was opaque - RB_CalcFogTexCoords( texCoords[0] ); + RB_CalcFogTexCoords(texCoords[0]); - for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { - float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + for (i = 0; i < tess.numVertexes; i++, colors += 4) { + float f = 1.0 - R_FogFactor(texCoords[i][0], texCoords[i][1]); colors[0] *= f; colors[1] *= f; colors[2] *= f; @@ -834,7 +783,6 @@ void RB_CalcModulateRGBAsByFog( unsigned char *colors ) { } } - /* ==================================================================== @@ -852,24 +800,24 @@ projected textures, but I don't trust the drivers and it doesn't fit our shader data. ======================== */ -void RB_CalcFogTexCoords( float *st ) { - int i; - float *v; - float s, t; - float eyeT; - qboolean eyeOutside; - fog_t *fog; - vec3_t localVec; - vec4_t fogDistanceVector, fogDepthVector; +void RB_CalcFogTexCoords(float *st) { + int i; + float *v; + float s, t; + float eyeT; + qboolean eyeOutside; + fog_t *fog; + vec3_t localVec; + vec4_t fogDistanceVector, fogDepthVector; fog = tr.world->fogs + tess.fogNum; // all fogging distance is based on world Z units - VectorSubtract( backEnd.ori.origin, backEnd.viewParms.ori.origin, localVec ); + VectorSubtract(backEnd.ori.origin, backEnd.viewParms.ori.origin, localVec); fogDistanceVector[0] = -backEnd.ori.modelMatrix[2]; fogDistanceVector[1] = -backEnd.ori.modelMatrix[6]; fogDistanceVector[2] = -backEnd.ori.modelMatrix[10]; - fogDistanceVector[3] = DotProduct( localVec, backEnd.viewParms.ori.axis[0] ); + fogDistanceVector[3] = DotProduct(localVec, backEnd.viewParms.ori.axis[0]); // scale the fog vectors based on the fog's thickness fogDistanceVector[0] *= fog->tcScale; @@ -878,18 +826,15 @@ void RB_CalcFogTexCoords( float *st ) { fogDistanceVector[3] *= fog->tcScale; // rotate the gradient vector for this orientation - if ( fog->hasSurface ) { - fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + - fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; - fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + - fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; - fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + - fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; - fogDepthVector[3] = -fog->surface[3] + DotProduct( backEnd.ori.origin, fog->surface ); - - eyeT = DotProduct( backEnd.ori.viewOrigin, fogDepthVector ) + fogDepthVector[3]; + if (fog->hasSurface) { + fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; + fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; + fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; + fogDepthVector[3] = -fog->surface[3] + DotProduct(backEnd.ori.origin, fog->surface); + + eyeT = DotProduct(backEnd.ori.viewOrigin, fogDepthVector) + fogDepthVector[3]; } else { - eyeT = 1; // non-surface fog always has eye inside + eyeT = 1; // non-surface fog always has eye inside fogDepthVector[0] = fogDepthVector[1] = fogDepthVector[2] = 0.0f; fogDepthVector[3] = 1.0f; @@ -898,66 +843,62 @@ void RB_CalcFogTexCoords( float *st ) { // see if the viewpoint is outside // this is needed for clipping distance even for constant fog - if ( eyeT < 0 ) { + if (eyeT < 0) { eyeOutside = qtrue; } else { eyeOutside = qfalse; } - fogDistanceVector[3] += 1.0/512; + fogDistanceVector[3] += 1.0 / 512; // calculate density for each point - for (i = 0, v = tess.xyz[0] ; i < tess.numVertexes ; i++, v += 4) { + for (i = 0, v = tess.xyz[0]; i < tess.numVertexes; i++, v += 4) { // calculate the length in fog - s = DotProduct( v, fogDistanceVector ) + fogDistanceVector[3]; - t = DotProduct( v, fogDepthVector ) + fogDepthVector[3]; + s = DotProduct(v, fogDistanceVector) + fogDistanceVector[3]; + t = DotProduct(v, fogDepthVector) + fogDepthVector[3]; // partially clipped fogs use the T axis - if ( eyeOutside ) { - if ( t < 1.0 ) { - t = 1.0/32; // point is outside, so no fogging + if (eyeOutside) { + if (t < 1.0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 1.0/32 + 30.0/32 * t / ( t - eyeT ); // cut the distance at the fog plane + t = 1.0 / 32 + 30.0 / 32 * t / (t - eyeT); // cut the distance at the fog plane } } else { - if ( t < 0 ) { - t = 1.0/32; // point is outside, so no fogging + if (t < 0) { + t = 1.0 / 32; // point is outside, so no fogging } else { - t = 31.0/32; + t = 31.0 / 32; } } - st[0] = Q_isnan (s) ? 0.0f : s; - st[1] = Q_isnan (s) ? 0.0f : t; + st[0] = Q_isnan(s) ? 0.0f : s; + st[1] = Q_isnan(s) ? 0.0f : t; st += 2; } } - - /* ** RB_CalcEnvironmentTexCoords */ -void RB_CalcEnvironmentTexCoords( float *st ) -{ - int i; - float *v, *normal; - vec3_t viewer, reflected; - float d; +void RB_CalcEnvironmentTexCoords(float *st) { + int i; + float *v, *normal; + vec3_t viewer, reflected; + float d; v = tess.xyz[0]; normal = tess.normal[0]; - for (i = 0 ; i < tess.numVertexes ; i++, v += 4, normal += 4, st += 2 ) - { - VectorSubtract (backEnd.ori.viewOrigin, v, viewer); - VectorNormalizeFast (viewer); + for (i = 0; i < tess.numVertexes; i++, v += 4, normal += 4, st += 2) { + VectorSubtract(backEnd.ori.viewOrigin, v, viewer); + VectorNormalizeFast(viewer); - d = DotProduct (normal, viewer); + d = DotProduct(normal, viewer); - reflected[0] = normal[0]*2*d - viewer[0]; - reflected[1] = normal[1]*2*d - viewer[1]; - reflected[2] = normal[2]*2*d - viewer[2]; + reflected[0] = normal[0] * 2 * d - viewer[0]; + reflected[1] = normal[1] * 2 * d - viewer[1]; + reflected[2] = normal[2] * 2 * d - viewer[2]; st[0] = 0.5 + reflected[1] * 0.5; st[1] = 0.5 - reflected[2] * 0.5; @@ -967,32 +908,28 @@ void RB_CalcEnvironmentTexCoords( float *st ) /* ** RB_CalcTurbulentTexCoords */ -void RB_CalcTurbulentTexCoords( const waveForm_t *wf, float *st ) -{ +void RB_CalcTurbulentTexCoords(const waveForm_t *wf, float *st) { int i; float now; - now = ( wf->phase + tess.shaderTime * wf->frequency ); + now = (wf->phase + tess.shaderTime * wf->frequency); - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { float s = st[0]; float t = st[1]; - st[0] = s + tr.sinTable[ ( ( int ) ( ( ( tess.xyz[i][0] + tess.xyz[i][2] )* 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude; - st[1] = t + tr.sinTable[ ( ( int ) ( ( tess.xyz[i][1] * 1.0/128 * 0.125 + now ) * FUNCTABLE_SIZE ) ) & ( FUNCTABLE_MASK ) ] * wf->amplitude; + st[0] = s + tr.sinTable[((int)(((tess.xyz[i][0] + tess.xyz[i][2]) * 1.0 / 128 * 0.125 + now) * FUNCTABLE_SIZE)) & (FUNCTABLE_MASK)] * wf->amplitude; + st[1] = t + tr.sinTable[((int)((tess.xyz[i][1] * 1.0 / 128 * 0.125 + now) * FUNCTABLE_SIZE)) & (FUNCTABLE_MASK)] * wf->amplitude; } } /* ** RB_CalcScaleTexCoords */ -void RB_CalcScaleTexCoords( const float scale[2], float *st ) -{ +void RB_CalcScaleTexCoords(const float scale[2], float *st) { int i; - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { st[0] *= scale[0]; st[1] *= scale[1]; } @@ -1001,8 +938,7 @@ void RB_CalcScaleTexCoords( const float scale[2], float *st ) /* ** RB_CalcScrollTexCoords */ -void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) -{ +void RB_CalcScrollTexCoords(const float scrollSpeed[2], float *st) { int i; float timeScale = tess.shaderTime; float adjustedScrollS, adjustedScrollT; @@ -1012,11 +948,10 @@ void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) // clamp so coordinates don't continuously get larger, causing problems // with hardware limits - adjustedScrollS = adjustedScrollS - floor( adjustedScrollS ); - adjustedScrollT = adjustedScrollT - floor( adjustedScrollT ); + adjustedScrollS = adjustedScrollS - floor(adjustedScrollS); + adjustedScrollT = adjustedScrollT - floor(adjustedScrollT); - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { st[0] += adjustedScrollS; st[1] += adjustedScrollT; } @@ -1025,12 +960,10 @@ void RB_CalcScrollTexCoords( const float scrollSpeed[2], float *st ) /* ** RB_CalcTransformTexCoords */ -void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *st ) -{ +void RB_CalcTransformTexCoords(const texModInfo_t *tmi, float *st) { int i; - for ( i = 0; i < tess.numVertexes; i++, st += 2 ) - { + for (i = 0; i < tess.numVertexes; i++, st += 2) { float s = st[0]; float t = st[1]; @@ -1042,8 +975,7 @@ void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *st ) /* ** RB_CalcRotateTexCoords */ -void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) -{ +void RB_CalcRotateTexCoords(float degsPerSecond, float *st) { float timeScale = tess.shaderTime; float degs; int index; @@ -1051,10 +983,10 @@ void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) texModInfo_t tmi; degs = -degsPerSecond * timeScale; - index = degs * ( FUNCTABLE_SIZE / 360.0f ); + index = degs * (FUNCTABLE_SIZE / 360.0f); - sinValue = tr.sinTable[ index & FUNCTABLE_MASK ]; - cosValue = tr.sinTable[ ( index + FUNCTABLE_SIZE / 4 ) & FUNCTABLE_MASK ]; + sinValue = tr.sinTable[index & FUNCTABLE_MASK]; + cosValue = tr.sinTable[(index + FUNCTABLE_SIZE / 4) & FUNCTABLE_MASK]; tmi.matrix[0][0] = cosValue; tmi.matrix[1][0] = -sinValue; @@ -1064,29 +996,24 @@ void RB_CalcRotateTexCoords( float degsPerSecond, float *st ) tmi.matrix[1][1] = cosValue; tmi.translate[1] = 0.5 - 0.5 * sinValue - 0.5 * cosValue; - RB_CalcTransformTexCoords( &tmi, st ); + RB_CalcTransformTexCoords(&tmi, st); } - - - - - /* ** RB_CalcSpecularAlpha ** ** Calculates specular coefficient and places it in the alpha channel */ -vec3_t lightOrigin = { -960, 1980, 96 }; // FIXME: track dynamically +vec3_t lightOrigin = {-960, 1980, 96}; // FIXME: track dynamically -void RB_CalcSpecularAlpha( unsigned char *alphas ) { - int i; - float *v, *normal; - vec3_t viewer, reflected; - float l, d; - int b; - vec3_t lightDir; - int numVertexes; +void RB_CalcSpecularAlpha(unsigned char *alphas) { + int i; + float *v, *normal; + vec3_t viewer, reflected; + float l, d; + int b; + vec3_t lightDir; + int numVertexes; v = tess.xyz[0]; normal = tess.normal[0]; @@ -1094,36 +1021,36 @@ void RB_CalcSpecularAlpha( unsigned char *alphas ) { alphas += 3; numVertexes = tess.numVertexes; - for (i = 0 ; i < numVertexes ; i++, v += 4, normal += 4, alphas += 4) { + for (i = 0; i < numVertexes; i++, v += 4, normal += 4, alphas += 4) { float ilength; if (backEnd.currentEntity && - (backEnd.currentEntity->e.hModel||backEnd.currentEntity->e.ghoul2) ) //this is a model so we can use world lights instead fake light + (backEnd.currentEntity->e.hModel || backEnd.currentEntity->e.ghoul2)) // this is a model so we can use world lights instead fake light { - VectorCopy (backEnd.currentEntity->lightDir, lightDir); + VectorCopy(backEnd.currentEntity->lightDir, lightDir); } else { - VectorSubtract( lightOrigin, v, lightDir ); - VectorNormalizeFast( lightDir ); + VectorSubtract(lightOrigin, v, lightDir); + VectorNormalizeFast(lightDir); } // calculate the specular color - d = 2 * DotProduct (normal, lightDir); + d = 2 * DotProduct(normal, lightDir); // we don't optimize for the d < 0 case since this tends to // cause visual artifacts such as faceted "snapping" - reflected[0] = normal[0]*d - lightDir[0]; - reflected[1] = normal[1]*d - lightDir[1]; - reflected[2] = normal[2]*d - lightDir[2]; + reflected[0] = normal[0] * d - lightDir[0]; + reflected[1] = normal[1] * d - lightDir[1]; + reflected[2] = normal[2] * d - lightDir[2]; - VectorSubtract (backEnd.ori.viewOrigin, v, viewer); - ilength = Q_rsqrt( DotProduct( viewer, viewer ) ); - l = DotProduct (reflected, viewer); + VectorSubtract(backEnd.ori.viewOrigin, v, viewer); + ilength = Q_rsqrt(DotProduct(viewer, viewer)); + l = DotProduct(reflected, viewer); l *= ilength; if (l < 0) { b = 0; } else { - l = l*l; - l = l*l; + l = l * l; + l = l * l; b = l * 255; if (b > 255) { b = 255; @@ -1139,53 +1066,52 @@ void RB_CalcSpecularAlpha( unsigned char *alphas ) { ** ** The basic vertex lighting calc */ -void RB_CalcDiffuseColor( unsigned char *colors ) -{ - int i, j; - float *v, *normal; - float incoming; - trRefEntity_t *ent; - int ambientLightInt; - vec3_t ambientLight; - vec3_t lightDir; - vec3_t directedLight; - int numVertexes; +void RB_CalcDiffuseColor(unsigned char *colors) { + int i, j; + float *v, *normal; + float incoming; + trRefEntity_t *ent; + int ambientLightInt; + vec3_t ambientLight; + vec3_t lightDir; + vec3_t directedLight; + int numVertexes; ent = backEnd.currentEntity; ambientLightInt = ent->ambientLightInt; - VectorCopy( ent->ambientLight, ambientLight ); - VectorCopy( ent->directedLight, directedLight ); - VectorCopy( ent->lightDir, lightDir ); + VectorCopy(ent->ambientLight, ambientLight); + VectorCopy(ent->directedLight, directedLight); + VectorCopy(ent->lightDir, lightDir); v = tess.xyz[0]; normal = tess.normal[0]; numVertexes = tess.numVertexes; - for (i = 0 ; i < numVertexes ; i++, v += 4, normal += 4) { - incoming = DotProduct (normal, lightDir); - if ( incoming <= 0 ) { - *(int *)&colors[i*4] = ambientLightInt; + for (i = 0; i < numVertexes; i++, v += 4, normal += 4) { + incoming = DotProduct(normal, lightDir); + if (incoming <= 0) { + *(int *)&colors[i * 4] = ambientLightInt; continue; } - j = Q_ftol( ambientLight[0] + incoming * directedLight[0] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[0] + incoming * directedLight[0]); + if (j > 255) { j = 255; } - colors[i*4+0] = j; + colors[i * 4 + 0] = j; - j = Q_ftol( ambientLight[1] + incoming * directedLight[1] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[1] + incoming * directedLight[1]); + if (j > 255) { j = 255; } - colors[i*4+1] = j; + colors[i * 4 + 1] = j; - j = Q_ftol( ambientLight[2] + incoming * directedLight[2] ); - if ( j > 255 ) { + j = Q_ftol(ambientLight[2] + incoming * directedLight[2]); + if (j > 255) { j = 255; } - colors[i*4+2] = j; + colors[i * 4 + 2] = j; - colors[i*4+3] = 255; + colors[i * 4 + 3] = 255; } } @@ -1194,36 +1120,34 @@ void RB_CalcDiffuseColor( unsigned char *colors ) ** ** The basic vertex lighting calc * Entity Color */ -void RB_CalcDiffuseEntityColor( unsigned char *colors ) -{ - int i; - float *v, *normal; - float incoming; - trRefEntity_t *ent; - int ambientLightInt; - vec3_t ambientLight; - vec3_t lightDir; - vec3_t directedLight; - int numVertexes; - float j,r,g,b; - - if ( !backEnd.currentEntity ) - {//error, use the normal lighting +void RB_CalcDiffuseEntityColor(unsigned char *colors) { + int i; + float *v, *normal; + float incoming; + trRefEntity_t *ent; + int ambientLightInt; + vec3_t ambientLight; + vec3_t lightDir; + vec3_t directedLight; + int numVertexes; + float j, r, g, b; + + if (!backEnd.currentEntity) { // error, use the normal lighting RB_CalcDiffuseColor(colors); } ent = backEnd.currentEntity; - VectorCopy( ent->ambientLight, ambientLight ); - VectorCopy( ent->directedLight, directedLight ); - VectorCopy( ent->lightDir, lightDir ); + VectorCopy(ent->ambientLight, ambientLight); + VectorCopy(ent->directedLight, directedLight); + VectorCopy(ent->lightDir, lightDir); - r = backEnd.currentEntity->e.shaderRGBA[0]/255.0f; - g = backEnd.currentEntity->e.shaderRGBA[1]/255.0f; - b = backEnd.currentEntity->e.shaderRGBA[2]/255.0f; + r = backEnd.currentEntity->e.shaderRGBA[0] / 255.0f; + g = backEnd.currentEntity->e.shaderRGBA[1] / 255.0f; + b = backEnd.currentEntity->e.shaderRGBA[2] / 255.0f; - ((byte *)&ambientLightInt)[0] = Q_ftol( r*ent->ambientLight[0] ); - ((byte *)&ambientLightInt)[1] = Q_ftol( g*ent->ambientLight[1] ); - ((byte *)&ambientLightInt)[2] = Q_ftol( b*ent->ambientLight[2] ); + ((byte *)&ambientLightInt)[0] = Q_ftol(r * ent->ambientLight[0]); + ((byte *)&ambientLightInt)[1] = Q_ftol(g * ent->ambientLight[1]); + ((byte *)&ambientLightInt)[2] = Q_ftol(b * ent->ambientLight[2]); ((byte *)&ambientLightInt)[3] = backEnd.currentEntity->e.shaderRGBA[3]; v = tess.xyz[0]; @@ -1231,43 +1155,41 @@ void RB_CalcDiffuseEntityColor( unsigned char *colors ) numVertexes = tess.numVertexes; - for ( i = 0 ; i < numVertexes ; i++, v += 4, normal += 4) - { - incoming = DotProduct (normal, lightDir); - if ( incoming <= 0 ) { - *(int *)&colors[i*4] = ambientLightInt; + for (i = 0; i < numVertexes; i++, v += 4, normal += 4) { + incoming = DotProduct(normal, lightDir); + if (incoming <= 0) { + *(int *)&colors[i * 4] = ambientLightInt; continue; } - j = ( ambientLight[0] + incoming * directedLight[0] ); - if ( j > 255 ) { + j = (ambientLight[0] + incoming * directedLight[0]); + if (j > 255) { j = 255; } - colors[i*4+0] = Q_ftol(j*r); + colors[i * 4 + 0] = Q_ftol(j * r); - j = ( ambientLight[1] + incoming * directedLight[1] ); - if ( j > 255 ) { + j = (ambientLight[1] + incoming * directedLight[1]); + if (j > 255) { j = 255; } - colors[i*4+1] = Q_ftol(j*g); + colors[i * 4 + 1] = Q_ftol(j * g); - j = ( ambientLight[2] + incoming * directedLight[2] ); - if ( j > 255 ) { + j = (ambientLight[2] + incoming * directedLight[2]); + if (j > 255) { j = 255; } - colors[i*4+2] = Q_ftol(j*b); + colors[i * 4 + 2] = Q_ftol(j * b); - colors[i*4+3] = backEnd.currentEntity->e.shaderRGBA[3]; + colors[i * 4 + 3] = backEnd.currentEntity->e.shaderRGBA[3]; } } //--------------------------------------------------------- -void RB_CalcDisintegrateColors( unsigned char *colors ) -{ - int i, numVertexes; - float dis, threshold; - float *v; - vec3_t temp; - refEntity_t *ent; +void RB_CalcDisintegrateColors(unsigned char *colors) { + int i, numVertexes; + float dis, threshold; + float *v; + vec3_t temp; + refEntity_t *ent; ent = &backEnd.currentEntity->e; v = tess.xyz[0]; @@ -1277,112 +1199,89 @@ void RB_CalcDisintegrateColors( unsigned char *colors ) numVertexes = tess.numVertexes; - if ( ent->renderfx & RF_DISINTEGRATE1 ) - { + if (ent->renderfx & RF_DISINTEGRATE1) { // this handles the blacken and fading out of the regular player model - for ( i = 0 ; i < numVertexes ; i++, v += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, v, temp ); + for (i = 0; i < numVertexes; i++, v += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, v, temp); - dis = VectorLengthSquared( temp ); + dis = VectorLengthSquared(temp); - if ( dis < threshold * threshold ) - { + if (dis < threshold * threshold) { // completely disintegrated - colors[i*4+3] = 0x00; - } - else if ( dis < threshold * threshold + 60 ) - { + colors[i * 4 + 3] = 0x00; + } else if (dis < threshold * threshold + 60) { // blacken before fading out - colors[i*4+0] = 0x0; - colors[i*4+1] = 0x0; - colors[i*4+2] = 0x0; - colors[i*4+3] = 0xff; - } - else if ( dis < threshold * threshold + 150 ) - { + colors[i * 4 + 0] = 0x0; + colors[i * 4 + 1] = 0x0; + colors[i * 4 + 2] = 0x0; + colors[i * 4 + 3] = 0xff; + } else if (dis < threshold * threshold + 150) { // darken more - colors[i*4+0] = 0x6f; - colors[i*4+1] = 0x6f; - colors[i*4+2] = 0x6f; - colors[i*4+3] = 0xff; - } - else if ( dis < threshold * threshold + 180 ) - { + colors[i * 4 + 0] = 0x6f; + colors[i * 4 + 1] = 0x6f; + colors[i * 4 + 2] = 0x6f; + colors[i * 4 + 3] = 0xff; + } else if (dis < threshold * threshold + 180) { // darken at edge of burn - colors[i*4+0] = 0xaf; - colors[i*4+1] = 0xaf; - colors[i*4+2] = 0xaf; - colors[i*4+3] = 0xff; - } - else - { + colors[i * 4 + 0] = 0xaf; + colors[i * 4 + 1] = 0xaf; + colors[i * 4 + 2] = 0xaf; + colors[i * 4 + 3] = 0xff; + } else { // not burning at all yet - colors[i*4+0] = 0xff; - colors[i*4+1] = 0xff; - colors[i*4+2] = 0xff; - colors[i*4+3] = 0xff; + colors[i * 4 + 0] = 0xff; + colors[i * 4 + 1] = 0xff; + colors[i * 4 + 2] = 0xff; + colors[i * 4 + 3] = 0xff; } } - } - else if ( ent->renderfx & RF_DISINTEGRATE2 ) - { + } else if (ent->renderfx & RF_DISINTEGRATE2) { // this handles the glowing, burning bit that scales away from the model - for ( i = 0 ; i < numVertexes ; i++, v += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, v, temp ); + for (i = 0; i < numVertexes; i++, v += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, v, temp); - dis = VectorLengthSquared( temp ); + dis = VectorLengthSquared(temp); - if ( dis < threshold * threshold ) - { + if (dis < threshold * threshold) { // done burning - colors[i*4+0] = 0x00; - colors[i*4+1] = 0x00; - colors[i*4+2] = 0x00; - colors[i*4+3] = 0x00; - } - else - { + colors[i * 4 + 0] = 0x00; + colors[i * 4 + 1] = 0x00; + colors[i * 4 + 2] = 0x00; + colors[i * 4 + 3] = 0x00; + } else { // still full burn - colors[i*4+0] = 0xff; - colors[i*4+1] = 0xff; - colors[i*4+2] = 0xff; - colors[i*4+3] = 0xff; + colors[i * 4 + 0] = 0xff; + colors[i * 4 + 1] = 0xff; + colors[i * 4 + 2] = 0xff; + colors[i * 4 + 3] = 0xff; } } } } //--------------------------------------------------------- -void RB_CalcDisintegrateVertDeform( void ) -{ - float *xyz = ( float * ) tess.xyz; - float *normal = ( float * ) tess.normal; - float scale; - vec3_t temp; - - if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2 ) - { - float threshold = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; - - for ( int i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4 ) - { - VectorSubtract( backEnd.currentEntity->e.oldorigin, xyz, temp ); +void RB_CalcDisintegrateVertDeform(void) { + float *xyz = (float *)tess.xyz; + float *normal = (float *)tess.normal; + float scale; + vec3_t temp; - scale = VectorLengthSquared( temp ); + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2) { + float threshold = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; - if ( scale < threshold * threshold ) - { + for (int i = 0; i < tess.numVertexes; i++, xyz += 4, normal += 4) { + VectorSubtract(backEnd.currentEntity->e.oldorigin, xyz, temp); + + scale = VectorLengthSquared(temp); + + if (scale < threshold * threshold) { xyz[0] += normal[0] * 2.0f; xyz[1] += normal[1] * 2.0f; xyz[2] += normal[2] * 0.5f; - } - else if ( scale < threshold * threshold + 50 ) - { + } else if (scale < threshold * threshold + 50) { xyz[0] += normal[0] * 1.0f; xyz[1] += normal[1] * 1.0f; -// xyz[2] += normal[2] * 1; + // xyz[2] += normal[2] * 1; } } } diff --git a/codemp/rd-vanilla/tr_shader.cpp b/codemp/rd-vanilla/tr_shader.cpp index 5fdc4ea61e..d7a241c138 100644 --- a/codemp/rd-vanilla/tr_shader.cpp +++ b/codemp/rd-vanilla/tr_shader.cpp @@ -29,9 +29,9 @@ static char *s_shaderText; // the shader is parsed into these global variables, then copied into // dynamically allocated memory if it is valid. -static shaderStage_t stages[MAX_SHADER_STAGES]; -static shader_t shader; -static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; +static shaderStage_t stages[MAX_SHADER_STAGES]; +static shader_t shader; +static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; // Hash value (generated using the generateHashValueForText function) for the original // retail JKA shader for gfx/2d/wedge. @@ -41,73 +41,37 @@ static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; // retail JKA shader for gfx/menus/radar/arrow_w. #define RETAIL_ARROW_W_SHADER_HASH (1650186) -#define FILE_HASH_SIZE 1024 -static shader_t* hashTable[FILE_HASH_SIZE]; +#define FILE_HASH_SIZE 1024 +static shader_t *hashTable[FILE_HASH_SIZE]; -#define MAX_SHADERTEXT_HASH 2048 -static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = { 0 }; +#define MAX_SHADERTEXT_HASH 2048 +static char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = {0}; -void KillTheShaderHashTable(void) -{ - memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); -} +void KillTheShaderHashTable(void) { memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); } -qboolean ShaderHashTableExists(void) -{ - if (shaderTextHashTable[0]) - { +qboolean ShaderHashTableExists(void) { + if (shaderTextHashTable[0]) { return qtrue; } return qfalse; } -const int lightmapsNone[MAXLIGHTMAPS] = -{ - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE, - LIGHTMAP_NONE -}; +const int lightmapsNone[MAXLIGHTMAPS] = {LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE, LIGHTMAP_NONE}; -const int lightmaps2d[MAXLIGHTMAPS] = -{ - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D, - LIGHTMAP_2D -}; +const int lightmaps2d[MAXLIGHTMAPS] = {LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D, LIGHTMAP_2D}; -const int lightmapsVertex[MAXLIGHTMAPS] = -{ - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX, - LIGHTMAP_BY_VERTEX -}; +const int lightmapsVertex[MAXLIGHTMAPS] = {LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX, LIGHTMAP_BY_VERTEX}; -const int lightmapsFullBright[MAXLIGHTMAPS] = -{ - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE, - LIGHTMAP_WHITEIMAGE -}; +const int lightmapsFullBright[MAXLIGHTMAPS] = {LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE, LIGHTMAP_WHITEIMAGE}; -const byte stylesDefault[MAXLIGHTMAPS] = -{ - LS_NORMAL, - LS_LSNONE, - LS_LSNONE, - LS_LSNONE -}; +const byte stylesDefault[MAXLIGHTMAPS] = {LS_NORMAL, LS_LSNONE, LS_LSNONE, LS_LSNONE}; -static void ClearGlobalShader(void) -{ - int i; +static void ClearGlobalShader(void) { + int i; - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; } @@ -115,13 +79,11 @@ static void ClearGlobalShader(void) shader.contentFlags = CONTENTS_SOLID | CONTENTS_OPAQUE; } -static uint32_t generateHashValueForText( const char *string, size_t length ) -{ +static uint32_t generateHashValueForText(const char *string, size_t length) { int i = 0; uint32_t hash = 0; - while ( length-- ) - { + while (length--) { hash += string[i] * (i + 119); i++; } @@ -134,56 +96,59 @@ static uint32_t generateHashValueForText( const char *string, size_t length ) return a hash value for the filename ================ */ -static long generateHashValue( const char *fname, const int size ) { - int i; - long hash; - char letter; +static long generateHashValue(const char *fname, const int size) { + int i; + long hash; + char letter; hash = 0; i = 0; while (fname[i] != '\0') { letter = tolower((unsigned char)fname[i]); - if (letter =='.') break; // don't include extension - if (letter =='\\') letter = '/'; // damn path names - if (letter == PATH_SEP) letter = '/'; // damn path names - hash+=(long)(letter)*(i+119); + if (letter == '.') + break; // don't include extension + if (letter == '\\') + letter = '/'; // damn path names + if (letter == PATH_SEP) + letter = '/'; // damn path names + hash += (long)(letter) * (i + 119); i++; } hash = (hash ^ (hash >> 10) ^ (hash >> 20)); - hash &= (size-1); + hash &= (size - 1); return hash; } void R_RemapShader(const char *shaderName, const char *newShaderName, const char *timeOffset) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh, *sh2; - qhandle_t h; + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh, *sh2; + qhandle_t h; - sh = R_FindShaderByName( shaderName ); + sh = R_FindShaderByName(shaderName); if (sh == NULL || sh == tr.defaultShader) { h = RE_RegisterShaderLightMap(shaderName, lightmapsNone, stylesDefault); sh = R_GetShaderByHandle(h); } if (sh == NULL || sh == tr.defaultShader) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: R_RemapShader: shader %s not found\n", shaderName ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: R_RemapShader: shader %s not found\n", shaderName); return; } - sh2 = R_FindShaderByName( newShaderName ); + sh2 = R_FindShaderByName(newShaderName); if (sh2 == NULL || sh2 == tr.defaultShader) { h = RE_RegisterShaderLightMap(newShaderName, lightmapsNone, stylesDefault); sh2 = R_GetShaderByHandle(h); } if (sh2 == NULL || sh2 == tr.defaultShader) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: R_RemapShader: new shader %s not found\n", newShaderName ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: R_RemapShader: new shader %s not found\n", newShaderName); return; } // remap all the shaders with the given name // even tho they might have different lightmaps - COM_StripExtension( shaderName, strippedName, sizeof( strippedName ) ); + COM_StripExtension(shaderName, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); for (sh = hashTable[hash]; sh; sh = sh->next) { if (Q_stricmp(sh->name, strippedName) == 0) { @@ -204,110 +169,82 @@ void R_RemapShader(const char *shaderName, const char *newShaderName, const char ParseVector =============== */ -qboolean ParseVector( const char **text, int count, float *v ) { - char *token; - int i; +qboolean ParseVector(const char **text, int count, float *v) { + char *token; + int i; // FIXME: spaces are currently required after parens, should change parseext... - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "(" ) ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "(")) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } - for ( i = 0 ; i < count ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing vector element in shader '%s'\n", shader.name ); + for (i = 0; i < count; i++) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing vector element in shader '%s'\n", shader.name); return qfalse; } - v[i] = atof( token ); + v[i] = atof(token); } - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, ")" ) ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, ")")) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parenthesis in shader '%s'\n", shader.name); return qfalse; } return qtrue; } - /* =============== NameToAFunc =============== */ -static unsigned NameToAFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "GT0" ) ) - { +static unsigned NameToAFunc(const char *funcname) { + if (!Q_stricmp(funcname, "GT0")) { return GLS_ATEST_GT_0; - } - else if ( !Q_stricmp( funcname, "LT128" ) ) - { + } else if (!Q_stricmp(funcname, "LT128")) { return GLS_ATEST_LT_80; - } - else if ( !Q_stricmp( funcname, "GE128" ) ) - { + } else if (!Q_stricmp(funcname, "GE128")) { return GLS_ATEST_GE_80; - } - else if ( !Q_stricmp( funcname, "GE192" ) ) - { + } else if (!Q_stricmp(funcname, "GE192")) { return GLS_ATEST_GE_C0; } - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", funcname, shader.name); return 0; } - /* =============== NameToSrcBlendMode =============== */ -static int NameToSrcBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToSrcBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_SRCBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_SRCBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_COLOR")) { return GLS_SRCBLEND_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_COLOR")) { return GLS_SRCBLEND_ONE_MINUS_DST_COLOR; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_SRCBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_SRCBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA_SATURATE")) { return GLS_SRCBLEND_ALPHA_SATURATE; } - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_SRCBLEND_ONE; } @@ -316,42 +253,26 @@ static int NameToSrcBlendMode( const char *name ) NameToDstBlendMode =============== */ -static int NameToDstBlendMode( const char *name ) -{ - if ( !Q_stricmp( name, "GL_ONE" ) ) - { +static int NameToDstBlendMode(const char *name) { + if (!Q_stricmp(name, "GL_ONE")) { return GLS_DSTBLEND_ONE; - } - else if ( !Q_stricmp( name, "GL_ZERO" ) ) - { + } else if (!Q_stricmp(name, "GL_ZERO")) { return GLS_DSTBLEND_ZERO; - } - else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_ALPHA")) { return GLS_DSTBLEND_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } - else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_DST_ALPHA")) { return GLS_DSTBLEND_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_DST_ALPHA")) { return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA; - } - else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_SRC_COLOR")) { return GLS_DSTBLEND_SRC_COLOR; - } - else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) - { + } else if (!Q_stricmp(name, "GL_ONE_MINUS_SRC_COLOR")) { return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; } - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name); return GLS_DSTBLEND_ONE; } @@ -360,325 +281,271 @@ static int NameToDstBlendMode( const char *name ) NameToGenFunc =============== */ -static genFunc_t NameToGenFunc( const char *funcname ) -{ - if ( !Q_stricmp( funcname, "sin" ) ) - { +static genFunc_t NameToGenFunc(const char *funcname) { + if (!Q_stricmp(funcname, "sin")) { return GF_SIN; - } - else if ( !Q_stricmp( funcname, "square" ) ) - { + } else if (!Q_stricmp(funcname, "square")) { return GF_SQUARE; - } - else if ( !Q_stricmp( funcname, "triangle" ) ) - { + } else if (!Q_stricmp(funcname, "triangle")) { return GF_TRIANGLE; - } - else if ( !Q_stricmp( funcname, "sawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "sawtooth")) { return GF_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "inversesawtooth" ) ) - { + } else if (!Q_stricmp(funcname, "inversesawtooth")) { return GF_INVERSE_SAWTOOTH; - } - else if ( !Q_stricmp( funcname, "noise" ) ) - { + } else if (!Q_stricmp(funcname, "noise")) { return GF_NOISE; - } - else if ( !Q_stricmp( funcname, "random" ) ) - { + } else if (!Q_stricmp(funcname, "random")) { return GF_RAND; } - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name); return GF_SIN; } - /* =================== ParseWaveForm =================== */ -static void ParseWaveForm( const char **text, waveForm_t *wave ) -{ +static void ParseWaveForm(const char **text, waveForm_t *wave) { char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->func = NameToGenFunc( token ); + wave->func = NameToGenFunc(token); // BASE, AMP, PHASE, FREQ - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->base = atof( token ); + wave->base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->amplitude = atof( token ); + wave->amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->phase = atof( token ); + wave->phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing waveform parm in shader '%s'\n", shader.name); return; } - wave->frequency = atof( token ); + wave->frequency = atof(token); } - /* =================== ParseTexMod =================== */ -static void ParseTexMod( const char *_text, shaderStage_t *stage ) -{ +static void ParseTexMod(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; texModInfo_t *tmi; - if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) { - Com_Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name ); + if (stage->bundle[0].numTexMods == TR_MAX_TEXMODS) { + Com_Error(ERR_DROP, "ERROR: too many tcMod stages in shader '%s'\n", shader.name); return; } tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods]; stage->bundle[0].numTexMods++; - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); // // turb // - if ( !Q_stricmp( token, "turb" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "turb")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.base = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.amplitude = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + tmi->wave.phase = atof(token); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod turb in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_TURBULENT; } // // scale // - else if ( !Q_stricmp( token, "scale" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scale unioned + tmi->translate[0] = atof(token); // scale unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scale unioned + tmi->translate[1] = atof(token); // scale unioned tmi->type = TMOD_SCALE; } // // scroll // - else if ( !Q_stricmp( token, "scroll" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "scroll")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); //scroll unioned - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + tmi->translate[0] = atof(token); // scroll unioned + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing scale scroll parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); //scroll unioned + tmi->translate[1] = atof(token); // scroll unioned tmi->type = TMOD_SCROLL; } // // stretch // - else if ( !Q_stricmp( token, "stretch" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "stretch")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.func = NameToGenFunc( token ); + tmi->wave.func = NameToGenFunc(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.base = atof( token ); + tmi->wave.base = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.amplitude = atof( token ); + tmi->wave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.phase = atof( token ); + tmi->wave.phase = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing stretch parms in shader '%s'\n", shader.name); return; } - tmi->wave.frequency = atof( token ); + tmi->wave.frequency = atof(token); tmi->type = TMOD_STRETCH; } // // transform // - else if ( !Q_stricmp( token, "transform" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "transform")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][0] = atof( token ); + tmi->matrix[0][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[0][1] = atof( token ); + tmi->matrix[0][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][0] = atof( token ); + tmi->matrix[1][0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->matrix[1][1] = atof( token ); + tmi->matrix[1][1] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[0] = atof( token ); + tmi->translate[0] = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing transform parms in shader '%s'\n", shader.name); return; } - tmi->translate[1] = atof( token ); + tmi->translate[1] = atof(token); tmi->type = TMOD_TRANSFORM; } // // rotate // - else if ( !Q_stricmp( token, "rotate" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rotate")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name); return; } - tmi->translate[0]= atof( token ); //rotateSpeed unioned + tmi->translate[0] = atof(token); // rotateSpeed unioned tmi->type = TMOD_ROTATE; } // // entityTranslate // - else if ( !Q_stricmp( token, "entityTranslate" ) ) - { + else if (!Q_stricmp(token, "entityTranslate")) { tmi->type = TMOD_ENTITY_TRANSLATE; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name); } } - - /* /////===== Part of the VERTIGON system =====///// =================== @@ -689,113 +556,93 @@ ParseSurfaceSprites // // NOTE: This parsing function used to be 12 pages long and very complex. The new version of surfacesprites // utilizes optional parameters parsed in ParseSurfaceSpriteOptional. -static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSprites(const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; float width, height, density, fadedist; - int sstype=SURFSPRITE_NONE; + int sstype = SURFSPRITE_NONE; // // spritetype // - token = COM_ParseExt( text, qfalse ); + token = COM_ParseExt(text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - if (!Q_stricmp(token, "vertical")) - { + if (!Q_stricmp(token, "vertical")) { sstype = SURFSPRITE_VERTICAL; - } - else if (!Q_stricmp(token, "oriented")) - { + } else if (!Q_stricmp(token, "oriented")) { sstype = SURFSPRITE_ORIENTED; - } - else if (!Q_stricmp(token, "effect")) - { + } else if (!Q_stricmp(token, "effect")) { sstype = SURFSPRITE_EFFECT; - } - else if (!Q_stricmp(token, "flattened")) - { + } else if (!Q_stricmp(token, "flattened")) { sstype = SURFSPRITE_FLATTENED; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", shader.name); return; } // // width // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - width=atof(token); - if (width <= 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", shader.name ); + width = atof(token); + if (width <= 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", shader.name); return; } // // height // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - height=atof(token); - if (height <= 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", shader.name ); + height = atof(token); + if (height <= 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", shader.name); return; } // // density // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - density=atof(token); - if (density <= 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", shader.name ); + density = atof(token); + if (density <= 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", shader.name); return; } // // fadedist // - token = COM_ParseExt( text, qfalse ); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", shader.name); return; } - fadedist=atof(token); - if (fadedist < 32) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name ); + fadedist = atof(token); + if (fadedist < 32) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid fadedist (%f < 32) in shader '%s'\n", fadedist, shader.name); return; } - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // These are all set by the command lines. @@ -806,7 +653,7 @@ static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) stage->ss->fadeDist = fadedist; // These are defaults that can be overwritten. - stage->ss->fadeMax = fadedist*1.33; + stage->ss->fadeMax = fadedist * 1.33; stage->ss->fadeScale = 0.0; stage->ss->wind = 0.0; stage->ss->windIdle = 0.0; @@ -818,16 +665,13 @@ static void ParseSurfaceSprites( const char *_text, shaderStage_t *stage ) stage->ss->vertSkew = 0.0f; // These are effect parameters that need defaults nonetheless. - stage->ss->fxDuration = 1000; // 1 second + stage->ss->fxDuration = 1000; // 1 second stage->ss->fxGrow[0] = 0.0; stage->ss->fxGrow[1] = 0.0; stage->ss->fxAlphaStart = 1.0; stage->ss->fxAlphaEnd = 0.0; } - - - /* /////===== Part of the VERTIGON system =====///// =========================== @@ -851,150 +695,129 @@ ParseSurfaceSpritesOptional // // Optional parameters that will override the defaults set in the surfacesprites command above. // -static void ParseSurfaceSpritesOptional( const char *param, const char *_text, shaderStage_t *stage ) -{ +static void ParseSurfaceSpritesOptional(const char *param, const char *_text, shaderStage_t *stage) { const char *token; const char **text = &_text; - float value; + float value; - if (!stage->ss) - { - stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + if (!stage->ss) { + stage->ss = (surfaceSprite_t *)Hunk_Alloc(sizeof(surfaceSprite_t), h_low); } // // fademax // - if (!Q_stricmp(param, "ssFademax")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFademax")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= stage->ss->fadeDist) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, shader.name ); + if (value <= stage->ss->fadeDist) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, + shader.name); return; } - stage->ss->fadeMax=value; + stage->ss->fadeMax = value; return; } // // fadescale // - if (!Q_stricmp(param, "ssFadescale")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFadescale")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name); return; } value = atof(token); - stage->ss->fadeScale=value; + stage->ss->fadeScale = value; return; } // // variance // - if (!Q_stricmp(param, "ssVariance")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVariance")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name); return; } - stage->ss->variance[0]=value; + stage->ss->variance[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name); return; } - stage->ss->variance[1]=value; + stage->ss->variance[1] = value; return; } // // hangdown // - if (!Q_stricmp(param, "ssHangdown")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssHangdown")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_DOWN; + stage->ss->facing = SURFSPRITE_FACING_DOWN; return; } // // anyangle // - if (!Q_stricmp(param, "ssAnyangle")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssAnyangle")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_ANY; + stage->ss->facing = SURFSPRITE_FACING_ANY; return; } // // faceup // - if (!Q_stricmp(param, "ssFaceup")) - { - if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFaceup")) { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name); return; } - stage->ss->facing=SURFSPRITE_FACING_UP; + stage->ss->facing = SURFSPRITE_FACING_UP; return; } // // wind // - if (!Q_stricmp(param, "ssWind")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWind")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name); return; } - stage->ss->wind=value; - if (stage->ss->windIdle <= 0) - { // Also override the windidle, it usually is the same as wind + stage->ss->wind = value; + if (stage->ss->windIdle <= 0) { // Also override the windidle, it usually is the same as wind stage->ss->windIdle = value; } return; @@ -1003,144 +826,123 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // windidle // - if (!Q_stricmp(param, "ssWindidle")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssWindidle")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name); return; } - stage->ss->windIdle=value; + stage->ss->windIdle = value; return; } // // vertskew // - if (!Q_stricmp(param, "ssVertskew")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssVertskew")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name ); + if (value < 0.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name); return; } - stage->ss->vertSkew=value; + stage->ss->vertSkew = value; return; } // // fxduration // - if (!Q_stricmp(param, "ssFXDuration")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXDuration")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name); return; } value = atof(token); - if (value <= 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name ); + if (value <= 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name); return; } - stage->ss->fxDuration=value; + stage->ss->fxDuration = value; return; } // // fxgrow // - if (!Q_stricmp(param, "ssFXGrow")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXGrow")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[0]=value; + stage->ss->fxGrow[0] = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name ); + if (value < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name); return; } - stage->ss->fxGrow[1]=value; + stage->ss->fxGrow[1] = value; return; } // // fxalpharange // - if (!Q_stricmp(param, "ssFXAlphaRange")) - { - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXAlphaRange")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaStart=value; + stage->ss->fxAlphaStart = value; - token = COM_ParseExt( text, qfalse); - if (token[0]==0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } value = atof(token); - if (value < 0 || value > 1.0) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name ); + if (value < 0 || value > 1.0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name); return; } - stage->ss->fxAlphaEnd=value; + stage->ss->fxAlphaEnd = value; return; } // // fxweather // - if (!Q_stricmp(param, "ssFXWeather")) - { - if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name ); + if (!Q_stricmp(param, "ssFXWeather")) { + if (stage->ss->surfaceSpriteType != SURFSPRITE_EFFECT) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name); return; } stage->ss->surfaceSpriteType = SURFSPRITE_WEATHERFX; @@ -1150,76 +952,60 @@ static void ParseSurfaceSpritesOptional( const char *param, const char *_text, s // // invalid ss command. // - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name); return; } - /* =================== ParseStage =================== */ -static qboolean ParseStage( shaderStage_t *stage, const char **text ) -{ +static qboolean ParseStage(shaderStage_t *stage, const char **text) { char *token; int depthMaskBits = GLS_DEPTHMASK_TRUE, blendSrcBits = 0, blendDstBits = 0, atestBits = 0, depthFuncBits = 0; qboolean depthMaskExplicit = qfalse; stage->active = qtrue; - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: no matching '}' found\n" ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: no matching '}' found\n"); return qfalse; } - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // // map // - else if ( !Q_stricmp( token, "map" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "map")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "$whiteimage" ) ) - { + if (!Q_stricmp(token, "$whiteimage")) { stage->bundle[0].image = tr.whiteImage; continue; - } - else if ( !Q_stricmp( token, "$lightmap" ) ) - { + } else if (!Q_stricmp(token, "$lightmap")) { stage->bundle[0].isLightmap = qtrue; - if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) - { + if (shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps) { #ifndef FINAL_BUILD - ri.Printf( PRINT_ALL, S_COLOR_RED"Lightmap requested but none available for shader %s\n", shader.name); + ri.Printf(PRINT_ALL, S_COLOR_RED "Lightmap requested but none available for shader %s\n", shader.name); #endif stage->bundle[0].image = tr.whiteImage; - } - else - { + } else { stage->bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; } continue; - } - else - { - stage->bundle[0].image = R_FindImageFile( token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_REPEAT ); - if ( !stage->bundle[0].image ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + } else { + stage->bundle[0].image = R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_REPEAT); + if (!stage->bundle[0].image) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1227,75 +1013,68 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // clampmap // - else if ( !Q_stricmp( token, "clampmap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "clampmap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'clampmap' keyword in shader '%s'\n", shader.name); return qfalse; } - stage->bundle[0].image = R_FindImageFile( token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_CLAMP ); - if ( !stage->bundle[0].image ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + stage->bundle[0].image = R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, GL_CLAMP); + if (!stage->bundle[0].image) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } } // // animMap .... // - else if ( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampanimMap" ) || !Q_stricmp( token, "oneshotanimMap" )) - { - #define MAX_IMAGE_ANIMATIONS 32 + else if (!Q_stricmp(token, "animMap") || !Q_stricmp(token, "clampanimMap") || !Q_stricmp(token, "oneshotanimMap")) { +#define MAX_IMAGE_ANIMATIONS 32 image_t *images[MAX_IMAGE_ANIMATIONS]; - bool bClamp = !Q_stricmp( token, "clampanimMap" ); - bool oneShot = !Q_stricmp( token, "oneshotanimMap" ); + bool bClamp = !Q_stricmp(token, "clampanimMap"); + bool oneShot = !Q_stricmp(token, "oneshotanimMap"); - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap":"clampanimMap"), shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for '%s' keyword in shader '%s'\n", (bClamp ? "animMap" : "clampanimMap"), + shader.name); return qfalse; } - stage->bundle[0].imageAnimationSpeed = atof( token ); + stage->bundle[0].imageAnimationSpeed = atof(token); stage->bundle[0].oneShotAnimMap = oneShot; // parse up to MAX_IMAGE_ANIMATIONS animations - while ( 1 ) { - int num; + while (1) { + int num; - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { break; } num = stage->bundle[0].numImageAnimations; - if ( num < MAX_IMAGE_ANIMATIONS ) { - images[num] = R_FindImageFile( token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, bClamp?GL_CLAMP:GL_REPEAT ); - if ( !images[num] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + if (num < MAX_IMAGE_ANIMATIONS) { + images[num] = + R_FindImageFile(token, (qboolean)!shader.noMipMaps, (qboolean)!shader.noPicMip, (qboolean)!shader.noTC, bClamp ? GL_CLAMP : GL_REPEAT); + if (!images[num]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name); return qfalse; } stage->bundle[0].numImageAnimations++; } } // Copy image ptrs into an array of ptrs - stage->bundle[0].image = (image_t*) Hunk_Alloc( stage->bundle[0].numImageAnimations * sizeof( image_t* ), h_low ); - memcpy( stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof( image_t* ) ); - } - else if ( !Q_stricmp( token, "videoMap" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name ); + stage->bundle[0].image = (image_t *)Hunk_Alloc(stage->bundle[0].numImageAnimations * sizeof(image_t *), h_low); + memcpy(stage->bundle[0].image, images, stage->bundle[0].numImageAnimations * sizeof(image_t *)); + } else if (!Q_stricmp(token, "videoMap")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name); return qfalse; } - stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic( token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader)); + stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic(token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader)); if (stage->bundle[0].videoMapHandle != -1) { stage->bundle[0].isVideoMap = qtrue; - assert (stage->bundle[0].videoMapHandlebundle[0].videoMapHandle < NUM_SCRATCH_IMAGES); stage->bundle[0].image = tr.scratchImage[stage->bundle[0].videoMapHandle]; } } @@ -1303,322 +1082,238 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // alphafunc // - else if ( !Q_stricmp( token, "alphaFunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaFunc")) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name); return qfalse; } - atestBits = NameToAFunc( token ); + atestBits = NameToAFunc(token); } // // depthFunc // - else if ( !Q_stricmp( token, "depthfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "depthfunc")) { + token = COM_ParseExt(text, qfalse); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name ); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name); return qfalse; } - if ( !Q_stricmp( token, "lequal" ) ) - { + if (!Q_stricmp(token, "lequal")) { depthFuncBits = 0; - } - else if ( !Q_stricmp( token, "equal" ) ) - { + } else if (!Q_stricmp(token, "equal")) { depthFuncBits = GLS_DEPTHFUNC_EQUAL; - } - else if ( !Q_stricmp( token, "disable" ) ) - { + } else if (!Q_stricmp(token, "disable")) { depthFuncBits = GLS_DEPTHTEST_DISABLE; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name); continue; } } // // detail // - else if ( !Q_stricmp( token, "detail" ) ) - { + else if (!Q_stricmp(token, "detail")) { stage->isDetail = qtrue; } // // blendfunc // or blendfunc // - else if ( !Q_stricmp( token, "blendfunc" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "blendfunc")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } // check for "simple" blends first - if ( !Q_stricmp( token, "add" ) ) { + if (!Q_stricmp(token, "add")) { blendSrcBits = GLS_SRCBLEND_ONE; blendDstBits = GLS_DSTBLEND_ONE; - } else if ( !Q_stricmp( token, "filter" ) ) { + } else if (!Q_stricmp(token, "filter")) { blendSrcBits = GLS_SRCBLEND_DST_COLOR; blendDstBits = GLS_DSTBLEND_ZERO; - } else if ( !Q_stricmp( token, "blend" ) ) { + } else if (!Q_stricmp(token, "blend")) { blendSrcBits = GLS_SRCBLEND_SRC_ALPHA; blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } else { // complex double blends - blendSrcBits = NameToSrcBlendMode( token ); + blendSrcBits = NameToSrcBlendMode(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name); continue; } - blendDstBits = NameToDstBlendMode( token ); + blendDstBits = NameToDstBlendMode(token); } // clear depth mask for blended surfaces - if ( !depthMaskExplicit ) - { + if (!depthMaskExplicit) { depthMaskBits = 0; } } // // rgbGen // - else if ( !Q_stricmp( token, "rgbGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "rgbGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->rgbWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->rgbWave); stage->rgbGen = CGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - vec3_t color; + } else if (!Q_stricmp(token, "const")) { + vec3_t color; - VectorClear( color ); + VectorClear(color); - ParseVector( text, 3, color ); + ParseVector(text, 3, color); stage->constantColor[0] = 255 * color[0]; stage->constantColor[1] = 255 * color[1]; stage->constantColor[2] = 255 * color[2]; stage->rgbGen = CGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->rgbGen = CGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "identityLighting" ) ) - { + } else if (!Q_stricmp(token, "identityLighting")) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->rgbGen = CGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->rgbGen = CGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->rgbGen = CGEN_VERTEX; - if ( stage->alphaGen == 0 ) { + if (stage->alphaGen == 0) { stage->alphaGen = AGEN_VERTEX; } - } - else if ( !Q_stricmp( token, "exactVertex" ) ) - { + } else if (!Q_stricmp(token, "exactVertex")) { stage->rgbGen = CGEN_EXACT_VERTEX; - } - else if ( !Q_stricmp( token, "lightingDiffuse" ) ) - { + } else if (!Q_stricmp(token, "lightingDiffuse")) { stage->rgbGen = CGEN_LIGHTING_DIFFUSE; - } - else if ( !Q_stricmp( token, "lightingDiffuseEntity" ) ) - { - if (shader.lightmapIndex[0] != LIGHTMAP_NONE) - { - ri.Printf( PRINT_ALL, S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name ); + } else if (!Q_stricmp(token, "lightingDiffuseEntity")) { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) { + ri.Printf(PRINT_ALL, S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name); } stage->rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->rgbGen = CGEN_ONE_MINUS_VERTEX; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // alphaGen // - else if ( !Q_stricmp( token, "alphaGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "alphaGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "wave" ) ) - { - ParseWaveForm( text, &stage->alphaWave ); + if (!Q_stricmp(token, "wave")) { + ParseWaveForm(text, &stage->alphaWave); stage->alphaGen = AGEN_WAVEFORM; - } - else if ( !Q_stricmp( token, "const" ) ) - { - token = COM_ParseExt( text, qfalse ); - stage->constantColor[3] = 255 * atof( token ); + } else if (!Q_stricmp(token, "const")) { + token = COM_ParseExt(text, qfalse); + stage->constantColor[3] = 255 * atof(token); stage->alphaGen = AGEN_CONST; - } - else if ( !Q_stricmp( token, "identity" ) ) - { + } else if (!Q_stricmp(token, "identity")) { stage->alphaGen = AGEN_IDENTITY; - } - else if ( !Q_stricmp( token, "entity" ) ) - { + } else if (!Q_stricmp(token, "entity")) { stage->alphaGen = AGEN_ENTITY; - } - else if ( !Q_stricmp( token, "oneMinusEntity" ) ) - { + } else if (!Q_stricmp(token, "oneMinusEntity")) { stage->alphaGen = AGEN_ONE_MINUS_ENTITY; - } - else if ( !Q_stricmp( token, "vertex" ) ) - { + } else if (!Q_stricmp(token, "vertex")) { stage->alphaGen = AGEN_VERTEX; - } - else if ( !Q_stricmp( token, "lightingSpecular" ) ) - { + } else if (!Q_stricmp(token, "lightingSpecular")) { stage->alphaGen = AGEN_LIGHTING_SPECULAR; - } - else if ( !Q_stricmp( token, "oneMinusVertex" ) ) - { + } else if (!Q_stricmp(token, "oneMinusVertex")) { stage->alphaGen = AGEN_ONE_MINUS_VERTEX; - } - else if ( !Q_stricmp( token, "dot" ) ) - { + } else if (!Q_stricmp(token, "dot")) { stage->alphaGen = AGEN_DOT; - } - else if ( !Q_stricmp( token, "oneMinusDot" ) ) - { + } else if (!Q_stricmp(token, "oneMinusDot")) { stage->alphaGen = AGEN_ONE_MINUS_DOT; - } - else if ( !Q_stricmp( token, "portal" ) ) - { + } else if (!Q_stricmp(token, "portal")) { stage->alphaGen = AGEN_PORTAL; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { shader.portalRange = 256; - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name ); - } - else - { - shader.portalRange = atof( token ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", + shader.name); + } else { + shader.portalRange = atof(token); } - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name); continue; } } // // tcGen // - else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing texgen parm in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "texgen") || !Q_stricmp(token, "tcGen")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing texgen parm in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "environment" ) ) - { + if (!Q_stricmp(token, "environment")) { stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED; - } - else if ( !Q_stricmp( token, "lightmap" ) ) - { + } else if (!Q_stricmp(token, "lightmap")) { stage->bundle[0].tcGen = TCGEN_LIGHTMAP; - } - else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) ) - { + } else if (!Q_stricmp(token, "texture") || !Q_stricmp(token, "base")) { stage->bundle[0].tcGen = TCGEN_TEXTURE; - } - else if ( !Q_stricmp( token, "vector" ) ) - { - stage->bundle[0].tcGenVectors = ( vec3_t *) Hunk_Alloc( 2 * sizeof( vec3_t ), h_low ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] ); - ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] ); + } else if (!Q_stricmp(token, "vector")) { + stage->bundle[0].tcGenVectors = (vec3_t *)Hunk_Alloc(2 * sizeof(vec3_t), h_low); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[0]); + ParseVector(text, 3, stage->bundle[0].tcGenVectors[1]); stage->bundle[0].tcGen = TCGEN_VECTOR; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown texgen parm in shader '%s'\n", shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown texgen parm in shader '%s'\n", shader.name); } } // // tcMod <...> // - else if ( !Q_stricmp( token, "tcMod" ) ) - { + else if (!Q_stricmp(token, "tcMod")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseTexMod( buffer, stage ); + ParseTexMod(buffer, stage); continue; } // // depthmask // - else if ( !Q_stricmp( token, "depthwrite" ) ) - { + else if (!Q_stricmp(token, "depthwrite")) { depthMaskBits = GLS_DEPTHMASK_TRUE; depthMaskExplicit = qtrue; continue; } // If this stage has glow... GLOWXXX - else if ( Q_stricmp( token, "glow" ) == 0 ) - { + else if (Q_stricmp(token, "glow") == 0) { stage->glow = true; continue; @@ -1626,20 +1321,18 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // surfaceSprites ... // - else if ( !Q_stricmp( token, "surfaceSprites" ) ) - { + else if (!Q_stricmp(token, "surfaceSprites")) { char buffer[1024] = ""; - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSprites( buffer, stage ); + ParseSurfaceSprites(buffer, stage); continue; } @@ -1656,28 +1349,25 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // ssGrow // ssWeather // - else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS + else if (!Q_stricmpn(token, "ss", 2)) // <--- NOTE ONLY COMPARING FIRST TWO LETTERS { char buffer[1024] = ""; char param[128]; - strcpy(param,token); + strcpy(param, token); - while ( 1 ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) + while (1) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) break; - Q_strcat( buffer, sizeof( buffer ), token ); - Q_strcat( buffer, sizeof( buffer ), " " ); + Q_strcat(buffer, sizeof(buffer), token); + Q_strcat(buffer, sizeof(buffer), " "); } - ParseSurfaceSpritesOptional( param, buffer, stage ); + ParseSurfaceSpritesOptional(param, buffer, stage); continue; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name); return qfalse; } } @@ -1685,31 +1375,26 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // if cgen isn't explicitly specified, use either identity or identitylighting // - if ( stage->rgbGen == CGEN_BAD ) { - if ( //blendSrcBits == 0 || - blendSrcBits == GLS_SRCBLEND_ONE || - blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) { + if (stage->rgbGen == CGEN_BAD) { + if ( // blendSrcBits == 0 || + blendSrcBits == GLS_SRCBLEND_ONE || blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) { stage->rgbGen = CGEN_IDENTITY_LIGHTING; } else { stage->rgbGen = CGEN_IDENTITY; } } - // // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending // - if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && - ( blendDstBits == GLS_DSTBLEND_ZERO ) ) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ZERO)) { blendDstBits = blendSrcBits = 0; depthMaskBits = GLS_DEPTHMASK_TRUE; } // decide which agens we can skip - if ( stage->alphaGen == AGEN_IDENTITY ) { - if ( stage->rgbGen == CGEN_IDENTITY - || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) { + if (stage->alphaGen == AGEN_IDENTITY) { + if (stage->rgbGen == CGEN_IDENTITY || stage->rgbGen == CGEN_LIGHTING_DIFFUSE) { stage->alphaGen = AGEN_SKIP; } } @@ -1717,10 +1402,7 @@ static qboolean ParseStage( shaderStage_t *stage, const char **text ) // // compute state bits // - stage->stateBits = depthMaskBits | - blendSrcBits | blendDstBits | - atestBits | - depthFuncBits; + stage->stateBits = depthMaskBits | blendSrcBits | blendDstBits | atestBits | depthFuncBits; return qtrue; } @@ -1739,149 +1421,136 @@ deformVertexes autoSprite2 deformVertexes text[0-7] =============== */ -static void ParseDeform( const char **text ) { - char *token; - deformStage_t *ds; +static void ParseDeform(const char **text) { + char *token; + deformStage_t *ds; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deform parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deform parm in shader '%s'\n", shader.name); return; } - if ( shader.numDeforms == MAX_SHADER_DEFORMS ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name ); + if (shader.numDeforms == MAX_SHADER_DEFORMS) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name); return; } - shader.deforms[ shader.numDeforms ] = (deformStage_t *)Hunk_Alloc( sizeof( deformStage_t ), h_low ); + shader.deforms[shader.numDeforms] = (deformStage_t *)Hunk_Alloc(sizeof(deformStage_t), h_low); - ds = shader.deforms[ shader.numDeforms ]; + ds = shader.deforms[shader.numDeforms]; shader.numDeforms++; - if ( !Q_stricmp( token, "projectionShadow" ) ) { + if (!Q_stricmp(token, "projectionShadow")) { ds->deformation = DEFORM_PROJECTION_SHADOW; return; } - if ( !Q_stricmp( token, "autosprite" ) ) { + if (!Q_stricmp(token, "autosprite")) { ds->deformation = DEFORM_AUTOSPRITE; return; } - if ( !Q_stricmp( token, "autosprite2" ) ) { + if (!Q_stricmp(token, "autosprite2")) { ds->deformation = DEFORM_AUTOSPRITE2; return; } - if ( !Q_stricmpn( token, "text", 4 ) ) { - int n; + if (!Q_stricmpn(token, "text", 4)) { + int n; n = token[4] - '0'; - if ( n < 0 || n > 7 ) { + if (n < 0 || n > 7) { n = 0; } ds->deformation = (deform_t)(DEFORM_TEXT0 + n); return; } - if ( !Q_stricmp( token, "bulge" ) ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "bulge")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeWidth = atof( token ); + ds->bulgeWidth = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeHeight = atof( token ); + ds->bulgeHeight = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name); return; } - ds->bulgeSpeed = atof( token ); + ds->bulgeSpeed = atof(token); ds->deformation = DEFORM_BULGE; return; } - if ( !Q_stricmp( token, "wave" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "wave")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - if ( atof( token ) != 0 ) - { - ds->deformationSpread = 1.0f / atof( token ); - } - else - { + if (atof(token) != 0) { + ds->deformationSpread = 1.0f / atof(token); + } else { ds->deformationSpread = 100.0f; - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_WAVE; return; } - if ( !Q_stricmp( token, "normal" ) ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + if (!Q_stricmp(token, "normal")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.amplitude = atof( token ); + ds->deformationWave.amplitude = atof(token); - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->deformationWave.frequency = atof( token ); + ds->deformationWave.frequency = atof(token); ds->deformation = DEFORM_NORMALS; return; } - if ( !Q_stricmp( token, "move" ) ) { - int i; + if (!Q_stricmp(token, "move")) { + int i; - for ( i = 0 ; i < 3 ; i++ ) { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + for (i = 0; i < 3; i++) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name); return; } - ds->moveVector[i] = atof( token ); + ds->moveVector[i] = atof(token); } - ParseWaveForm( text, &ds->deformationWave ); + ParseWaveForm(text, &ds->deformationWave); ds->deformation = DEFORM_MOVE; return; } - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name ); + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name); } - /* =============== ParseSkyParms @@ -1889,27 +1558,27 @@ ParseSkyParms skyParms =============== */ -static void ParseSkyParms( const char **text ) { - char *token; - const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; - char pathname[MAX_QPATH]; - int i; +static void ParseSkyParms(const char **text) { + char *token; + const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; + char pathname[MAX_QPATH]; + int i; - shader.sky = (skyParms_t *)Hunk_Alloc( sizeof( skyParms_t ), h_low ); + shader.sky = (skyParms_t *)Hunk_Alloc(sizeof(skyParms_t), h_low); // outerbox - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name); return; } - if ( strcmp( token, "-" ) ) { - for (i=0 ; i<6 ; i++) { - Com_sprintf( pathname, sizeof(pathname), "%s_%s", token, suf[i] ); - shader.sky->outerbox[i] = R_FindImageFile( ( char * ) pathname, qtrue, qtrue, (qboolean)!shader.noTC, GL_CLAMP ); - if ( !shader.sky->outerbox[i] ) { + if (strcmp(token, "-")) { + for (i = 0; i < 6; i++) { + Com_sprintf(pathname, sizeof(pathname), "%s_%s", token, suf[i]); + shader.sky->outerbox[i] = R_FindImageFile((char *)pathname, qtrue, qtrue, (qboolean)!shader.noTC, GL_CLAMP); + if (!shader.sky->outerbox[i]) { if (i) { - shader.sky->outerbox[i] = shader.sky->outerbox[i-1];//not found, so let's use the previous image + shader.sky->outerbox[i] = shader.sky->outerbox[i - 1]; // not found, so let's use the previous image } else { shader.sky->outerbox[i] = tr.defaultImage; } @@ -1918,70 +1587,68 @@ static void ParseSkyParms( const char **text ) { } // cloudheight - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name); return; } - shader.sky->cloudHeight = atof( token ); - if ( !shader.sky->cloudHeight ) { + shader.sky->cloudHeight = atof(token); + if (!shader.sky->cloudHeight) { shader.sky->cloudHeight = 512; } - R_InitSkyTexCoords( shader.sky->cloudHeight ); + R_InitSkyTexCoords(shader.sky->cloudHeight); // innerbox - token = COM_ParseExt( text, qfalse ); - if ( strcmp( token, "-" ) ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "-")) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name); } } - /* ================= ParseSort ================= */ -static void ParseSort( const char **text ) { - char *token; +static void ParseSort(const char **text) { + char *token; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing sort parameter in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing sort parameter in shader '%s'\n", shader.name); return; } - if ( !Q_stricmp( token, "portal" ) ) { + if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; - } else if ( !Q_stricmp( token, "sky" ) ) { + } else if (!Q_stricmp(token, "sky")) { shader.sort = SS_ENVIRONMENT; - } else if ( !Q_stricmp( token, "opaque" ) ) { + } else if (!Q_stricmp(token, "opaque")) { shader.sort = SS_OPAQUE; - } else if ( !Q_stricmp( token, "decal" ) ) { + } else if (!Q_stricmp(token, "decal")) { shader.sort = SS_DECAL; - } else if ( !Q_stricmp( token, "seeThrough" ) ) { + } else if (!Q_stricmp(token, "seeThrough")) { shader.sort = SS_SEE_THROUGH; - } else if ( !Q_stricmp( token, "banner" ) ) { + } else if (!Q_stricmp(token, "banner")) { shader.sort = SS_BANNER; - } else if ( !Q_stricmp( token, "additive" ) ) { + } else if (!Q_stricmp(token, "additive")) { shader.sort = SS_BLEND1; - } else if ( !Q_stricmp( token, "nearest" ) ) { + } else if (!Q_stricmp(token, "nearest")) { shader.sort = SS_NEAREST; - } else if ( !Q_stricmp( token, "underwater" ) ) { + } else if (!Q_stricmp(token, "underwater")) { shader.sort = SS_UNDERWATER; - } else if ( !Q_stricmp( token, "inside" ) ) { + } else if (!Q_stricmp(token, "inside")) { shader.sort = SS_INSIDE; - } else if ( !Q_stricmp( token, "mid_inside" ) ) { + } else if (!Q_stricmp(token, "mid_inside")) { shader.sort = SS_MID_INSIDE; - } else if ( !Q_stricmp( token, "middle" ) ) { + } else if (!Q_stricmp(token, "middle")) { shader.sort = SS_MIDDLE; - } else if ( !Q_stricmp( token, "mid_outside" ) ) { + } else if (!Q_stricmp(token, "mid_outside")) { shader.sort = SS_MID_OUTSIDE; - } else if ( !Q_stricmp( token, "outside" ) ) { + } else if (!Q_stricmp(token, "outside")) { shader.sort = SS_OUTSIDE; - } - else { - shader.sort = atof( token ); + } else { + shader.sort = atof(token); } } @@ -1990,80 +1657,71 @@ static void ParseSort( const char **text ) { ParseMaterial ================= */ -const char *materialNames[MATERIAL_LAST] = -{ - MATERIALS -}; +const char *materialNames[MATERIAL_LAST] = {MATERIALS}; -void ParseMaterial( const char **text ) -{ - char *token; - int i; +void ParseMaterial(const char **text) { + char *token; + int i; - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name); return; } - for(i = 0; i < MATERIAL_LAST; i++) - { - if ( !Q_stricmp( token, materialNames[i] ) ) - { + for (i = 0; i < MATERIAL_LAST; i++) { + if (!Q_stricmp(token, materialNames[i])) { shader.surfaceFlags |= i; break; } } } - // this table is also present in q3map typedef struct infoParm_s { - const char *name; - uint32_t clearSolid, surfaceFlags, contents; + const char *name; + uint32_t clearSolid, surfaceFlags, contents; } infoParm_t; -infoParm_t infoParms[] = { +infoParm_t infoParms[] = { // Game content Flags - { "nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE }, // special hack to clear solid flag - { "nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE }, // special hack to clear opaque flag - { "lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA }, // very damaging - { "slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME }, // mildly damaging - { "water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER }, // - { "fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering - { "shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP }, // block shots, but not people - { "playerclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP }, // block only the player - { "monsterclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP }, // - { "botclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP }, // for bots - { "trigger", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER }, // - { "nodrop", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc) - { "terrain", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN }, // use special terrain collsion - { "ladder", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER }, // climb up in it like water - { "abseil", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL }, // can abseil down this brush - { "outside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE }, // volume is considered to be in the outside (i.e. not indoors) - { "inside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE }, // volume is considered to be inside (i.e. indoors) - - { "detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL }, // don't include in structural bsp - { "trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT }, // surface has an alpha component + {"nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE}, // special hack to clear solid flag + {"nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE}, // special hack to clear opaque flag + {"lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA}, // very damaging + {"slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME}, // mildly damaging + {"water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER}, // + {"fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering + {"shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP}, // block shots, but not people + {"playerclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP}, // block only the player + {"monsterclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP}, // + {"botclip", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP}, // for bots + {"trigger", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER}, // + {"nodrop", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP}, // don't drop items or leave bodies (death fog, lava, etc) + {"terrain", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN}, // use special terrain collsion + {"ladder", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER}, // climb up in it like water + {"abseil", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL}, // can abseil down this brush + {"outside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE}, // volume is considered to be in the outside (i.e. not indoors) + {"inside", ~(CONTENTS_SOLID | CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE}, // volume is considered to be inside (i.e. indoors) + + {"detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL}, // don't include in structural bsp + {"trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT}, // surface has an alpha component /* Game surface flags */ - { "sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE }, // emit light from an environment map - { "slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE }, // - - { "nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE }, // - { "noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE }, // don't make impact explosions or marks - { "nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE }, // don't make impact marks, but still explode - { "nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE }, // don't generate a drawsurface (or a lightmap) - { "nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE }, // - { "nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE }, // don't ever add dynamic lights - { "metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE }, // - { "nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE }, // No misc ents on this surface - { "forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE }, // - { "forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE }, // only visible with force sight + {"sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE}, // emit light from an environment map + {"slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE}, // + + {"nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE}, // + {"noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE}, // don't make impact explosions or marks + {"nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE}, // don't make impact marks, but still explode + {"nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE}, // don't generate a drawsurface (or a lightmap) + {"nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE}, // + {"nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE}, // don't ever add dynamic lights + {"metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE}, // + {"nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE}, // No misc ents on this surface + {"forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE}, // + {"forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE}, // only visible with force sight }; - /* =============== ParseSurfaceParm @@ -2071,14 +1729,14 @@ ParseSurfaceParm surfaceparm =============== */ -static void ParseSurfaceParm( const char **text ) { - char *token; - int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); - int i; - - token = COM_ParseExt( text, qfalse ); - for ( i = 0 ; i < numInfoParms ; i++ ) { - if ( !Q_stricmp( token, infoParms[i].name ) ) { +static void ParseSurfaceParm(const char **text) { + char *token; + int numInfoParms = sizeof(infoParms) / sizeof(infoParms[0]); + int i; + + token = COM_ParseExt(text, qfalse); + for (i = 0; i < numInfoParms; i++) { + if (!Q_stricmp(token, infoParms[i].name)) { shader.surfaceFlags |= infoParms[i].surfaceFlags; shader.contentFlags |= infoParms[i].contents; shader.contentFlags &= infoParms[i].clearSolid; @@ -2096,165 +1754,142 @@ shader. Parse it into the global shader variable. Later functions will optimize it. ================= */ -static qboolean ParseShader( const char **text ) -{ +static qboolean ParseShader(const char **text) { char *token; const char *begin = *text; int s; s = 0; - token = COM_ParseExt( text, qtrue ); - if ( token[0] != '{' ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name ); + token = COM_ParseExt(text, qtrue); + if (token[0] != '{') { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name); return qfalse; } - while ( 1 ) - { - token = COM_ParseExt( text, qtrue ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: no concluding '}' in shader %s\n", shader.name ); + while (1) { + token = COM_ParseExt(text, qtrue); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: no concluding '}' in shader %s\n", shader.name); return qfalse; } // end of shader definition - if ( token[0] == '}' ) - { + if (token[0] == '}') { break; } // stage definition - else if ( token[0] == '{' ) - { - if ( s >= MAX_SHADER_STAGES ) { - ri.Printf( PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES ); + else if (token[0] == '{') { + if (s >= MAX_SHADER_STAGES) { + ri.Printf(PRINT_WARNING, "WARNING: too many stages in shader %s (max is %i)\n", shader.name, MAX_SHADER_STAGES); return qfalse; } - if ( !ParseStage( &stages[s], text ) ) - { + if (!ParseStage(&stages[s], text)) { return qfalse; } stages[s].active = qtrue; - if ( stages[s].glow ) - { + if (stages[s].glow) { shader.hasGlow = true; } s++; continue; } // skip stuff that only the QuakeEdRadient needs - else if ( !Q_stricmpn( token, "qer", 3 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "qer", 3)) { + SkipRestOfLine(text); continue; } // material deprecated as of 11 Jan 01 // material undeprecated as of 7 May 01 - q3map_material deprecated - else if ( !Q_stricmp( token, "material" ) || !Q_stricmp( token, "q3map_material" ) ) - { - ParseMaterial( text ); + else if (!Q_stricmp(token, "material") || !Q_stricmp(token, "q3map_material")) { + ParseMaterial(text); } // sun parms - else if ( !Q_stricmp( token, "sun" ) || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunLight[0] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[1] = atof( token ); - token = COM_ParseExt( text, qfalse ); - tr.sunLight[2] = atof( token ); - - VectorNormalize( tr.sunLight ); - - token = COM_ParseExt( text, qfalse ); - float a = atof( token ); - VectorScale( tr.sunLight, a, tr.sunLight); - - token = COM_ParseExt( text, qfalse ); - a = atof( token ); + else if (!Q_stricmp(token, "sun") || !Q_stricmp(token, "q3map_sun") || !Q_stricmp(token, "q3map_sunExt")) { + token = COM_ParseExt(text, qfalse); + tr.sunLight[0] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[1] = atof(token); + token = COM_ParseExt(text, qfalse); + tr.sunLight[2] = atof(token); + + VectorNormalize(tr.sunLight); + + token = COM_ParseExt(text, qfalse); + float a = atof(token); + VectorScale(tr.sunLight, a, tr.sunLight); + + token = COM_ParseExt(text, qfalse); + a = atof(token); a = a / 180 * M_PI; - token = COM_ParseExt( text, qfalse ); - float b = atof( token ); + token = COM_ParseExt(text, qfalse); + float b = atof(token); b = b / 180 * M_PI; - tr.sunDirection[0] = cos( a ) * cos( b ); - tr.sunDirection[1] = sin( a ) * cos( b ); - tr.sunDirection[2] = sin( b ); + tr.sunDirection[0] = cos(a) * cos(b); + tr.sunDirection[1] = sin(a) * cos(b); + tr.sunDirection[2] = sin(b); - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // q3map_surfacelight deprecated as of 16 Jul 01 - else if ( !Q_stricmp( token, "surfacelight" ) || !Q_stricmp( token, "q3map_surfacelight" ) ) - { - token = COM_ParseExt( text, qfalse ); - tr.sunSurfaceLight = atoi( token ); - } - else if ( !Q_stricmp( token, "lightColor" ) ) - { + else if (!Q_stricmp(token, "surfacelight") || !Q_stricmp(token, "q3map_surfacelight")) { + token = COM_ParseExt(text, qfalse); + tr.sunSurfaceLight = atoi(token); + } else if (!Q_stricmp(token, "lightColor")) { /* if ( !ParseVector( text, 3, tr.sunAmbient ) ) { return qfalse; } */ - //SP skips this so I'm skipping it here too. - SkipRestOfLine( text ); + // SP skips this so I'm skipping it here too. + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "deformvertexes" ) || !Q_stricmp( token, "deform" )) { - ParseDeform( text ); + } else if (!Q_stricmp(token, "deformvertexes") || !Q_stricmp(token, "deform")) { + ParseDeform(text); continue; - } - else if ( !Q_stricmp( token, "tesssize" ) ) { - SkipRestOfLine( text ); + } else if (!Q_stricmp(token, "tesssize")) { + SkipRestOfLine(text); continue; - } - else if ( !Q_stricmp( token, "clampTime" ) ) { - token = COM_ParseExt( text, qfalse ); + } else if (!Q_stricmp(token, "clampTime")) { + token = COM_ParseExt(text, qfalse); if (token[0]) { shader.clampTime = atof(token); } } // skip stuff that only the q3map needs - else if ( !Q_stricmpn( token, "q3map", 5 ) ) { - SkipRestOfLine( text ); + else if (!Q_stricmpn(token, "q3map", 5)) { + SkipRestOfLine(text); continue; } // skip stuff that only q3map or the server needs - else if ( !Q_stricmp( token, "surfaceParm" ) ) { - ParseSurfaceParm( text ); + else if (!Q_stricmp(token, "surfaceParm")) { + ParseSurfaceParm(text); continue; } // no mip maps - else if ( !Q_stricmp( token, "nomipmaps" ) ) - { + else if (!Q_stricmp(token, "nomipmaps")) { shader.noMipMaps = true; shader.noPicMip = true; continue; } // no picmip adjustment - else if ( !Q_stricmp( token, "nopicmip" ) ) - { + else if (!Q_stricmp(token, "nopicmip")) { shader.noPicMip = true; continue; - } - else if ( !Q_stricmp( token, "noglfog" ) ) - { + } else if (!Q_stricmp(token, "noglfog")) { shader.fogPass = FP_NONE; continue; } // polygonOffset - else if ( !Q_stricmp( token, "polygonOffset" ) ) - { + else if (!Q_stricmp(token, "polygonOffset")) { shader.polygonOffset = true; continue; - } - else if ( !Q_stricmp( token, "noTC" ) ) - { + } else if (!Q_stricmp(token, "noTC")) { shader.noTC = true; continue; } @@ -2262,82 +1897,66 @@ static qboolean ParseShader( const char **text ) // to be merged into one batch. This is a savings for smoke // puffs and blood, but can't be used for anything where the // shader calcs (not the surface function) reference the entity color or scroll - else if ( !Q_stricmp( token, "entityMergable" ) ) - { + else if (!Q_stricmp(token, "entityMergable")) { shader.entityMergable = true; continue; } // fogParms - else if ( !Q_stricmp( token, "fogParms" ) ) - { - shader.fogParms = (fogParms_t *)Hunk_Alloc( sizeof( fogParms_t ), h_low ); - if ( !ParseVector( text, 3, shader.fogParms->color ) ) { + else if (!Q_stricmp(token, "fogParms")) { + shader.fogParms = (fogParms_t *)Hunk_Alloc(sizeof(fogParms_t), h_low); + if (!ParseVector(text, 3, shader.fogParms->color)) { return qfalse; } - token = COM_ParseExt( text, qfalse ); - if ( !token[0] ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name ); + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name); continue; } - shader.fogParms->depthForOpaque = atof( token ); + shader.fogParms->depthForOpaque = atof(token); // skip any old gradient directions - SkipRestOfLine( text ); + SkipRestOfLine(text); continue; } // portal - else if ( !Q_stricmp(token, "portal") ) - { + else if (!Q_stricmp(token, "portal")) { shader.sort = SS_PORTAL; continue; } // skyparms - else if ( !Q_stricmp( token, "skyparms" ) ) - { - ParseSkyParms( text ); + else if (!Q_stricmp(token, "skyparms")) { + ParseSkyParms(text); continue; } // light determines flaring in q3map, not needed here - else if ( !Q_stricmp(token, "light") ) - { - token = COM_ParseExt( text, qfalse ); + else if (!Q_stricmp(token, "light")) { + token = COM_ParseExt(text, qfalse); continue; } // cull - else if ( !Q_stricmp( token, "cull") ) - { - token = COM_ParseExt( text, qfalse ); - if ( token[0] == 0 ) - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing cull parms in shader '%s'\n", shader.name ); + else if (!Q_stricmp(token, "cull")) { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: missing cull parms in shader '%s'\n", shader.name); continue; } - if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) ) - { + if (!Q_stricmp(token, "none") || !Q_stricmp(token, "twosided") || !Q_stricmp(token, "disable")) { shader.cullType = CT_TWO_SIDED; - } - else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) ) - { + } else if (!Q_stricmp(token, "back") || !Q_stricmp(token, "backside") || !Q_stricmp(token, "backsided")) { shader.cullType = CT_BACK_SIDED; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name); } continue; } // sort - else if ( !Q_stricmp( token, "sort" ) ) - { - ParseSort( text ); + else if (!Q_stricmp(token, "sort")) { + ParseSort(text); continue; - } - else - { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name ); + } else { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name); return qfalse; } } @@ -2345,7 +1964,7 @@ static qboolean ParseShader( const char **text ) // // ignore shaders that don't have any stages, unless it is a sky or fog // - if ( s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG ) ) { + if (s == 0 && !shader.sky && !(shader.contentFlags & CONTENTS_FOG)) { return qfalse; } @@ -2359,10 +1978,8 @@ static qboolean ParseShader( const char **text ) // We match against the retail version of gfx/2d/wedge by calculating the // hash value of the shader text, and comparing it against a precalculated // value. - uint32_t shaderHash = generateHashValueForText( begin, *text - begin ); - if ( shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && - Q_stricmp( shader.name, "gfx/2d/wedge" ) == 0 ) - { + uint32_t shaderHash = generateHashValueForText(begin, *text - begin); + if (shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && Q_stricmp(shader.name, "gfx/2d/wedge") == 0) { stages[0].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); stages[0].stateBits |= GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; } @@ -2373,11 +1990,9 @@ static qboolean ParseShader( const char **text ) // functioned because rgbGen identity doesn't work with setcolor. // // We match against retail version of gfx/menus/radar/arrow_w by calculating - // the hash value of the shader text, and comparing it against a + // the hash value of the shader text, and comparing it against a // precalculated value. - if ( shaderHash == RETAIL_ARROW_W_SHADER_HASH && - Q_stricmp( shader.name, "gfx/menus/radar/arrow_w" ) == 0 ) - { + if (shaderHash == RETAIL_ARROW_W_SHADER_HASH && Q_stricmp(shader.name, "gfx/menus/radar/arrow_w") == 0) { stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; } @@ -2394,43 +2009,34 @@ SHADER OPTIMIZATION AND FOGGING */ typedef struct collapse_s { - int blendA; - int blendB; + int blendA; + int blendB; - int multitextureEnv; - int multitextureBlend; + int multitextureEnv; + int multitextureBlend; } collapse_t; -static collapse_t collapse[] = { - { 0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, 0 }, +static collapse_t collapse[] = { + {0, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, 0}, - { 0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, 0 }, + {0, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, 0}, - { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, - GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR }, + {GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO, GL_MODULATE, GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR}, - { 0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, - GL_ADD, 0 }, + {0, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GL_ADD, 0}, - { GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, - GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE }, + {GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE, GL_ADD, GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE}, #if 0 { 0, GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_SRCBLEND_SRC_ALPHA, GL_DECAL, 0 }, #endif - { -1 } -}; + {-1}}; /* ================ CollapseMultitexture @@ -2439,16 +2045,16 @@ Attempt to combine two stages into a single multitexture stage FIXME: I think modulated add + modulated add collapses incorrectly ================= */ -static qboolean CollapseMultitexture( void ) { +static qboolean CollapseMultitexture(void) { int abits, bbits; int i; textureBundle_t tmpBundle; - if ( !qglActiveTextureARB ) { + if (!qglActiveTextureARB) { return qfalse; } // make sure both stages are active - if ( !stages[0].active || !stages[1].active ) { + if (!stages[0].active || !stages[1].active) { return qfalse; } @@ -2456,85 +2062,70 @@ static qboolean CollapseMultitexture( void ) { bbits = stages[1].stateBits; // make sure that both stages have identical state other than blend modes - if ( ( abits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) != - ( bbits & ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE ) ) ) { + if ((abits & ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE)) != (bbits & ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS | GLS_DEPTHMASK_TRUE))) { return qfalse; } - abits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); - bbits &= ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + abits &= (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); + bbits &= (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); // search for a valid multitexture blend function - for ( i = 0; collapse[i].blendA != -1 ; i++ ) { - if ( abits == collapse[i].blendA - && bbits == collapse[i].blendB ) { + for (i = 0; collapse[i].blendA != -1; i++) { + if (abits == collapse[i].blendA && bbits == collapse[i].blendB) { break; } } // nothing found - if ( collapse[i].blendA == -1 ) { + if (collapse[i].blendA == -1) { return qfalse; } // GL_ADD is a separate extension - if ( collapse[i].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable ) { + if (collapse[i].multitextureEnv == GL_ADD && !glConfig.textureEnvAddAvailable) { return qfalse; } // make sure waveforms have identical parameters - if ( ( stages[0].rgbGen != stages[1].rgbGen ) || - ( stages[0].alphaGen != stages[1].alphaGen ) ) { + if ((stages[0].rgbGen != stages[1].rgbGen) || (stages[0].alphaGen != stages[1].alphaGen)) { return qfalse; } // an add collapse can only have identity colors - if ( collapse[i].multitextureEnv == GL_ADD && stages[0].rgbGen != CGEN_IDENTITY ) { + if (collapse[i].multitextureEnv == GL_ADD && stages[0].rgbGen != CGEN_IDENTITY) { return qfalse; } - if ( stages[0].rgbGen == CGEN_WAVEFORM ) - { - if ( memcmp( &stages[0].rgbWave, - &stages[1].rgbWave, - sizeof( stages[0].rgbWave ) ) ) - { + if (stages[0].rgbGen == CGEN_WAVEFORM) { + if (memcmp(&stages[0].rgbWave, &stages[1].rgbWave, sizeof(stages[0].rgbWave))) { return qfalse; } } - if ( stages[0].alphaGen == AGEN_WAVEFORM ) - { - if ( memcmp( &stages[0].alphaWave, - &stages[1].alphaWave, - sizeof( stages[0].alphaWave ) ) ) - { + if (stages[0].alphaGen == AGEN_WAVEFORM) { + if (memcmp(&stages[0].alphaWave, &stages[1].alphaWave, sizeof(stages[0].alphaWave))) { return qfalse; } } - // make sure that lightmaps are in bundle 1 for 3dfx - if ( stages[0].bundle[0].isLightmap ) - { + if (stages[0].bundle[0].isLightmap) { tmpBundle = stages[0].bundle[0]; stages[0].bundle[0] = stages[1].bundle[0]; stages[0].bundle[1] = tmpBundle; - } - else - { + } else { stages[0].bundle[1] = stages[1].bundle[0]; } // set the new blend state bits shader.multitextureEnv = collapse[i].multitextureEnv; - stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + stages[0].stateBits &= ~(GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); stages[0].stateBits |= collapse[i].multitextureBlend; // // move down subsequent shaders // - memmove( &stages[1], &stages[2], sizeof( stages[0] ) * ( MAX_SHADER_STAGES - 2 ) ); - memset( &stages[MAX_SHADER_STAGES-1], 0, sizeof( stages[0] ) ); + memmove(&stages[1], &stages[2], sizeof(stages[0]) * (MAX_SHADER_STAGES - 2)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(stages[0])); return qtrue; } @@ -2550,77 +2141,71 @@ sortedIndex. ============== */ extern bool gServerSkinHack; -static void FixRenderCommandList( int newShader ) { - if( !gServerSkinHack ) { - renderCommandList_t *cmdList = &backEndData->commands; +static void FixRenderCommandList(int newShader) { + if (!gServerSkinHack) { + renderCommandList_t *cmdList = &backEndData->commands; - if( cmdList ) { + if (cmdList) { const void *curCmd = cmdList->cmds; - while ( 1 ) { + while (1) { curCmd = PADP(curCmd, sizeof(void *)); - switch ( *(const int *)curCmd ) { - case RC_SET_COLOR: - { + switch (*(const int *)curCmd) { + case RC_SET_COLOR: { const setColorCommand_t *sc_cmd = (const setColorCommand_t *)curCmd; curCmd = (const void *)(sc_cmd + 1); break; - } - case RC_STRETCH_PIC: - { + } + case RC_STRETCH_PIC: { const stretchPicCommand_t *sp_cmd = (const stretchPicCommand_t *)curCmd; curCmd = (const void *)(sp_cmd + 1); break; - } - case RC_ROTATE_PIC: - { + } + case RC_ROTATE_PIC: { const rotatePicCommand_t *sp_cmd = (const rotatePicCommand_t *)curCmd; curCmd = (const void *)(sp_cmd + 1); break; - } - case RC_ROTATE_PIC2: - { + } + case RC_ROTATE_PIC2: { const rotatePicCommand_t *sp_cmd = (const rotatePicCommand_t *)curCmd; curCmd = (const void *)(sp_cmd + 1); break; - } - case RC_DRAW_SURFS: - { + } + case RC_DRAW_SURFS: { int i; - drawSurf_t *drawSurf; - shader_t *shader; - int fogNum; - int entityNum; - int dlightMap; - int sortedIndex; - const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd; - - for( i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++ ) { - R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &fogNum, &dlightMap ); - sortedIndex = (( drawSurf->sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1)); - if( sortedIndex >= newShader ) { + drawSurf_t *drawSurf; + shader_t *shader; + int fogNum; + int entityNum; + int dlightMap; + int sortedIndex; + const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd; + + for (i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++) { + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &fogNum, &dlightMap); + sortedIndex = ((drawSurf->sort >> QSORT_SHADERNUM_SHIFT) & (MAX_SHADERS - 1)); + if (sortedIndex >= newShader) { sortedIndex++; - drawSurf->sort = (sortedIndex << QSORT_SHADERNUM_SHIFT) | (entityNum << QSORT_REFENTITYNUM_SHIFT) | ( fogNum << QSORT_FOGNUM_SHIFT ) | (int)dlightMap; + drawSurf->sort = (sortedIndex << QSORT_SHADERNUM_SHIFT) | (entityNum << QSORT_REFENTITYNUM_SHIFT) | (fogNum << QSORT_FOGNUM_SHIFT) | + (int)dlightMap; } } curCmd = (const void *)(ds_cmd + 1); break; - } + } case RC_DRAW_BUFFER: case RC_WORLD_EFFECTS: - case RC_AUTO_MAP: - { + case RC_AUTO_MAP: { const drawBufferCommand_t *db_cmd = (const drawBufferCommand_t *)curCmd; curCmd = (const void *)(db_cmd + 1); break; - } - case RC_SWAP_BUFFERS: - { + } + case RC_SWAP_BUFFERS: { const swapBuffersCommand_t *sb_cmd = (const swapBuffersCommand_t *)curCmd; curCmd = (const void *)(sb_cmd + 1); break; - } + } case RC_END_OF_LIST: default: return; @@ -2641,84 +2226,80 @@ shaders. Sets shader->sortedIndex ============== */ -static void SortNewShader( void ) { - int i; - float sort; - shader_t *newShader; +static void SortNewShader(void) { + int i; + float sort; + shader_t *newShader; - newShader = tr.shaders[ tr.numShaders - 1 ]; + newShader = tr.shaders[tr.numShaders - 1]; sort = newShader->sort; - for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) { - if ( tr.sortedShaders[ i ]->sort <= sort ) { + for (i = tr.numShaders - 2; i >= 0; i--) { + if (tr.sortedShaders[i]->sort <= sort) { break; } - tr.sortedShaders[i+1] = tr.sortedShaders[i]; - tr.sortedShaders[i+1]->sortedIndex++; + tr.sortedShaders[i + 1] = tr.sortedShaders[i]; + tr.sortedShaders[i + 1]->sortedIndex++; } // Arnout: fix rendercommandlist // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 - FixRenderCommandList( i+1 ); + FixRenderCommandList(i + 1); - newShader->sortedIndex = i+1; - tr.sortedShaders[i+1] = newShader; + newShader->sortedIndex = i + 1; + tr.sortedShaders[i + 1] = newShader; } - /* ==================== GeneratePermanentShader ==================== */ -static shader_t *GeneratePermanentShader( void ) { - shader_t *newShader; - int i, b; - int size; - - if ( tr.numShaders == MAX_SHADERS ) { - //ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); - ri.Printf( PRINT_ALL, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); +static shader_t *GeneratePermanentShader(void) { + shader_t *newShader; + int i, b; + int size; + + if (tr.numShaders == MAX_SHADERS) { + // ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); + ri.Printf(PRINT_ALL, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); return tr.defaultShader; } - newShader = (struct shader_s *)ri.Hunk_Alloc( sizeof( shader_t ), h_low ); + newShader = (struct shader_s *)ri.Hunk_Alloc(sizeof(shader_t), h_low); *newShader = shader; - if ( shader.sort <= /*SS_OPAQUE*/SS_SEE_THROUGH ) { + if (shader.sort <= /*SS_OPAQUE*/ SS_SEE_THROUGH) { newShader->fogPass = FP_EQUAL; - } else if ( shader.contentFlags & CONTENTS_FOG ) { + } else if (shader.contentFlags & CONTENTS_FOG) { newShader->fogPass = FP_LE; } - tr.shaders[ tr.numShaders ] = newShader; + tr.shaders[tr.numShaders] = newShader; newShader->index = tr.numShaders; - tr.sortedShaders[ tr.numShaders ] = newShader; + tr.sortedShaders[tr.numShaders] = newShader; newShader->sortedIndex = tr.numShaders; tr.numShaders++; - size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof( stages[0] ) : sizeof( stages[0] ); - newShader->stages = (shaderStage_t *) Hunk_Alloc( size, h_low ); + size = newShader->numUnfoggedPasses ? newShader->numUnfoggedPasses * sizeof(stages[0]) : sizeof(stages[0]); + newShader->stages = (shaderStage_t *)Hunk_Alloc(size, h_low); - for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) { - if ( !stages[i].active ) { + for (i = 0; i < newShader->numUnfoggedPasses; i++) { + if (!stages[i].active) { break; } newShader->stages[i] = stages[i]; - for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) { - if (newShader->stages[i].bundle[b].numTexMods) - { - size = newShader->stages[i].bundle[b].numTexMods * sizeof( texModInfo_t ); - newShader->stages[i].bundle[b].texMods = (texModInfo_t *)Hunk_Alloc( size, h_low ); - memcpy( newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size ); - } - else - { - newShader->stages[i].bundle[b].texMods = 0; //clear the globabl ptr jic + for (b = 0; b < NUM_TEXTURE_BUNDLES; b++) { + if (newShader->stages[i].bundle[b].numTexMods) { + size = newShader->stages[i].bundle[b].numTexMods * sizeof(texModInfo_t); + newShader->stages[i].bundle[b].texMods = (texModInfo_t *)Hunk_Alloc(size, h_low); + memcpy(newShader->stages[i].bundle[b].texMods, stages[i].bundle[b].texMods, size); + } else { + newShader->stages[i].bundle[b].texMods = 0; // clear the globabl ptr jic } } } @@ -2743,7 +2324,7 @@ what it is supposed to look like. OUTPUT: Number of stages after the collapse (in the case of surfacesprites this isn't one). ================= */ -//rww - no longer used, at least for now. destroys alpha shaders completely. +// rww - no longer used, at least for now. destroys alpha shaders completely. #if 0 static int VertexLightingCollapse( void ) { int stage, nextopenstage; @@ -2856,10 +2437,10 @@ Returns a freshly allocated shader with all the needed info from the current global working shader ========================= */ -static shader_t *FinishShader( void ) { - int stage, lmStage, stageIndex; //rwwRMG - stageIndex for AGEN_BLEND - qboolean hasLightmapStage; - qboolean vertexLightmap; +static shader_t *FinishShader(void) { + int stage, lmStage, stageIndex; // rwwRMG - stageIndex for AGEN_BLEND + qboolean hasLightmapStage; + qboolean vertexLightmap; hasLightmapStage = qfalse; vertexLightmap = qfalse; @@ -2867,106 +2448,91 @@ static shader_t *FinishShader( void ) { // // set sky stuff appropriate // - if ( shader.sky ) { + if (shader.sky) { shader.sort = SS_ENVIRONMENT; } // // set polygon offset // - if ( shader.polygonOffset && !shader.sort ) { + if (shader.polygonOffset && !shader.sort) { shader.sort = SS_DECAL; } - for(lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) - { + for (lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) { shaderStage_t *pStage = &stages[lmStage]; - if (pStage->active && pStage->bundle[0].isLightmap) - { + if (pStage->active && pStage->bundle[0].isLightmap) { break; } } - if (lmStage < MAX_SHADER_STAGES) - { - if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) - { - if (lmStage == 0) //< MAX_SHADER_STAGES-1) - {//copy the rest down over the lightmap slot - memmove(&stages[lmStage], &stages[lmStage+1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES-lmStage-1)); - memset(&stages[MAX_SHADER_STAGES-1], 0, sizeof(shaderStage_t)); - //change blending on the moved down stage + if (lmStage < MAX_SHADER_STAGES) { + if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { + if (lmStage == 0) //< MAX_SHADER_STAGES-1) + { // copy the rest down over the lightmap slot + memmove(&stages[lmStage], &stages[lmStage + 1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES - lmStage - 1)); + memset(&stages[MAX_SHADER_STAGES - 1], 0, sizeof(shaderStage_t)); + // change blending on the moved down stage stages[lmStage].stateBits = GLS_DEFAULT; } - //change anything that was moved down (or the *white if LM is first) to use vertex color + // change anything that was moved down (or the *white if LM is first) to use vertex color stages[lmStage].rgbGen = CGEN_EXACT_VERTEX; stages[lmStage].alphaGen = AGEN_SKIP; - lmStage = MAX_SHADER_STAGES; //skip the style checking below + lmStage = MAX_SHADER_STAGES; // skip the style checking below } } - if (lmStage < MAX_SHADER_STAGES)// && !r_fullbright->value) + if (lmStage < MAX_SHADER_STAGES) // && !r_fullbright->value) { - int numStyles; - int i; + int numStyles; + int i; - for(numStyles=0;numStyles= LS_UNUSED) - { + for (numStyles = 0; numStyles < MAXLIGHTMAPS; numStyles++) { + if (shader.styles[numStyles] >= LS_UNUSED) { break; } } numStyles--; - if (numStyles > 0) - { - for(i=MAX_SHADER_STAGES-1;i>lmStage+numStyles;i--) - { - stages[i] = stages[i-numStyles]; + if (numStyles > 0) { + for (i = MAX_SHADER_STAGES - 1; i > lmStage + numStyles; i--) { + stages[i] = stages[i - numStyles]; } - for(i=0;iactive ) { + if (!pStage->active) { break; } - // check for a missing texture - if ( !pStage->bundle[0].image ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "Shader %s has a stage with no image\n", shader.name ); + // check for a missing texture + if (!pStage->bundle[0].image) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "Shader %s has a stage with no image\n", shader.name); pStage->active = qfalse; stage++; continue; @@ -2975,56 +2541,52 @@ static shader_t *FinishShader( void ) { // // ditch this stage if it's detail and detail textures are disabled // - if ( pStage->isDetail && !r_detailTextures->integer ) { + if (pStage->isDetail && !r_detailTextures->integer) { int index; - for ( index=stage+1; indexindex = stageIndex; //rwwRMG - needed for AGEN_BLEND + pStage->index = stageIndex; // rwwRMG - needed for AGEN_BLEND // // default texture coordinate generation // - if ( pStage->bundle[0].isLightmap ) { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].isLightmap) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_LIGHTMAP; } hasLightmapStage = qtrue; } else { - if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + if (pStage->bundle[0].tcGen == TCGEN_BAD) { pStage->bundle[0].tcGen = TCGEN_TEXTURE; } } - - // not a true lightmap but we want to leave existing - // behaviour in place and not print out a warning - //if (pStage->rgbGen == CGEN_VERTEX) { - // vertexLightmap = qtrue; - //} - - + // not a true lightmap but we want to leave existing + // behaviour in place and not print out a warning + // if (pStage->rgbGen == CGEN_VERTEX) { + // vertexLightmap = qtrue; + //} // // determine sort order and fog color adjustment // - if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) && - ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) { + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) && (stages[0].stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS))) { int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS; int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS; @@ -3035,32 +2597,27 @@ static shader_t *FinishShader( void ) { // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA // modulate, additive - if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) || - ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) { + if (((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) || + ((blendSrcBits == GLS_SRCBLEND_ZERO) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR))) { pStage->adjustColorsForFog = ACFF_MODULATE_RGB; } // strict blend - else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_SRC_ALPHA) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA; } // premultiplied alpha - else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) - { + else if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)) { pStage->adjustColorsForFog = ACFF_MODULATE_RGBA; } else { // we can't adjust this one correctly, so it won't be exactly correct in fog } // don't screw with sort order if this is a portal or environment - if ( !shader.sort ) { + if (!shader.sort) { // see through item, like a grill or grate - if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) - { + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) { shader.sort = SS_SEE_THROUGH; - } - else - { + } else { /* if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) { @@ -3077,125 +2634,98 @@ static shader_t *FinishShader( void ) { shader.sort = SS_BLEND0; } */ - if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) - { + if ((blendSrcBits == GLS_SRCBLEND_ONE) && (blendDstBits == GLS_DSTBLEND_ONE)) { // GL_ONE GL_ONE needs to come a bit later shader.sort = SS_BLEND1; - } - else - { + } else { shader.sort = SS_BLEND0; } } } } - //rww - begin hw fog - if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) - { + // rww - begin hw fog + if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_ONE) && - pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE) && + pStage->alphaGen == AGEN_LIGHTING_SPECULAR && stage) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ZERO)) - { + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO)) { pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && stage) - { // + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && stage) { // pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES-1 && - stages[stage+1].bundle[0].isLightmap) - { // multiple light map blending + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == 0 && pStage->bundle[0].isLightmap && stage < MAX_SHADER_STAGES - 1 && + stages[stage + 1].bundle[0].isLightmap) { // multiple light map blending pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO) && pStage->bundle[0].isLightmap) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO) && + pStage->bundle[0].isLightmap) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_WHITE; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_DST_COLOR|GLS_DSTBLEND_ZERO)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else if ((pStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) - { //I don't know, it works. -rww + } else if ((pStage->stateBits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == + (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) { // I don't know, it works. -rww pStage->mGLFogColorOverride = GLFOGOVERRIDE_BLACK; - } - else - { + } else { pStage->mGLFogColorOverride = GLFOGOVERRIDE_NONE; } - //rww - end hw fog + // rww - end hw fog - stageIndex++; //rwwRMG - needed for AGEN_BLEND + stageIndex++; // rwwRMG - needed for AGEN_BLEND stage++; } // there are times when you will need to manually apply a sort to // opaque alpha tested shaders that have later blend passes - if ( !shader.sort ) { + if (!shader.sort) { shader.sort = SS_OPAQUE; } // // if we are in r_vertexLight mode, never use a lightmap texture // - if ( stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer) ) { - //stage = VertexLightingCollapse(); - //rww - since this does bad things, I am commenting it out for now. If you want to attempt a fix, feel free. + if (stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer)) { + // stage = VertexLightingCollapse(); + // rww - since this does bad things, I am commenting it out for now. If you want to attempt a fix, feel free. hasLightmapStage = qfalse; } // // look for multitexture potential // - if ( stage > 1 && CollapseMultitexture() ) { + if (stage > 1 && CollapseMultitexture()) { stage--; } - if ( shader.lightmapIndex[0] >= 0 && !hasLightmapStage ) - { - if (vertexLightmap) - { -// ri.DPrintf( "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name ); - } - else - { - ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name ); + if (shader.lightmapIndex[0] >= 0 && !hasLightmapStage) { + if (vertexLightmap) { + // ri.DPrintf( "WARNING: shader '%s' has VERTEX forced lightmap!\n", shader.name ); + } else { + ri.Printf(PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name); memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); memcpy(shader.styles, stylesDefault, sizeof(shader.styles)); } } - // // compute number of passes // shader.numUnfoggedPasses = stage; // fogonly shaders don't have any normal passes - if ( stage == 0 && !shader.sky ) { + if (stage == 0 && !shader.sky) { shader.sort = SS_FOG; } - for ( stage = 1; stage < shader.numUnfoggedPasses; stage++ ) - { + for (stage = 1; stage < shader.numUnfoggedPasses; stage++) { // Make sure stage is non detail and active - if(stages[stage].isDetail || !stages[stage].active) - { + if (stages[stage].isDetail || !stages[stage].active) { break; } // MT lightmaps are always in bundle 1 - if(stages[stage].bundle[0].isLightmap) - { + if (stages[stage].bundle[0].isLightmap) { continue; } } @@ -3217,7 +2747,7 @@ return NULL if not found If found, it will return a valid shader ===================== */ -static const char *FindShaderInShaderText( const char *shadername ) { +static const char *FindShaderInShaderText(const char *shadername) { char *token; const char *p; @@ -3225,41 +2755,39 @@ static const char *FindShaderInShaderText( const char *shadername ) { hash = generateHashValue(shadername, MAX_SHADERTEXT_HASH); - if ( shaderTextHashTable[hash] ) { + if (shaderTextHashTable[hash]) { for (i = 0; shaderTextHashTable[hash][i]; i++) { p = shaderTextHashTable[hash][i]; token = COM_ParseExt(&p, qtrue); - if ( !Q_stricmp( token, shadername ) ) + if (!Q_stricmp(token, shadername)) return p; } } p = s_shaderText; - if ( !p ) { + if (!p) { return NULL; } // look for label - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( !Q_stricmp( token, shadername ) ) { + if (!Q_stricmp(token, shadername)) { return p; - } - else { + } else { // skip the definition - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } } return NULL; } - /* ================== R_FindShaderByName @@ -3268,23 +2796,23 @@ Will always return a valid shader, but it might be the default shader if the real one can't be found. ================== */ -shader_t *R_FindShaderByName( const char *name ) { - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindShaderByName(const char *name) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( (name==NULL) || (name[0] == 0) ) { + if ((name == NULL) || (name[0] == 0)) { return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader @@ -3298,26 +2826,19 @@ shader_t *R_FindShaderByName( const char *name ) { return tr.defaultShader; } +inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) { + int i; -inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapIndex, const byte *styles) -{ - int i; - - if (Q_stricmp(sh->name, name)) - { + if (Q_stricmp(sh->name, name)) { return qfalse; } - if (!sh->defaultShader) - { - for(i=0;ilightmapIndex[i] != lightmapIndex[i]) - { + if (!sh->defaultShader) { + for (i = 0; i < MAXLIGHTMAPS; i++) { + if (sh->lightmapIndex[i] != lightmapIndex[i]) { return qfalse; } - if (sh->styles[i] != styles[i]) - { + if (sh->styles[i] != styles[i]) { return qfalse; } } @@ -3333,41 +2854,38 @@ inline qboolean IsShader(shader_t *sh, const char *name, const int *lightmapInde an external lightmap image and/or sets the index to a valid number =============== */ -#define EXTERNAL_LIGHTMAP "lm_%04d.tga" // THIS MUST BE IN SYNC WITH Q3MAP2 -static inline const int *R_FindLightmap( const int *lightmapIndex ) -{ - image_t *image; - char fileName[ MAX_QPATH ]; +#define EXTERNAL_LIGHTMAP "lm_%04d.tga" // THIS MUST BE IN SYNC WITH Q3MAP2 +static inline const int *R_FindLightmap(const int *lightmapIndex) { + image_t *image; + char fileName[MAX_QPATH]; // don't bother with vertex lighting - if( *lightmapIndex < 0 ) + if (*lightmapIndex < 0) return lightmapIndex; // does this lightmap already exist? - if( *lightmapIndex < tr.numLightmaps && tr.lightmaps[ *lightmapIndex ] != NULL ) + if (*lightmapIndex < tr.numLightmaps && tr.lightmaps[*lightmapIndex] != NULL) return lightmapIndex; // bail if no world dir - if( tr.worldDir[0] == '\0' ) - { + if (tr.worldDir[0] == '\0') { return lightmapsVertex; } // sync up render thread, because we're going to have to load an image - //R_SyncRenderThread(); + // R_SyncRenderThread(); // attempt to load an external lightmap - Com_sprintf( fileName, sizeof(fileName), "%s/" EXTERNAL_LIGHTMAP, tr.worldDir, *lightmapIndex ); - image = R_FindImageFile( fileName, qfalse, qfalse, (qboolean)r_ext_compressed_lightmaps->integer, GL_CLAMP ); - if( image == NULL ) - { + Com_sprintf(fileName, sizeof(fileName), "%s/" EXTERNAL_LIGHTMAP, tr.worldDir, *lightmapIndex); + image = R_FindImageFile(fileName, qfalse, qfalse, (qboolean)r_ext_compressed_lightmaps->integer, GL_CLAMP); + if (image == NULL) { return lightmapsVertex; } // add it to the lightmap list - if( *lightmapIndex >= tr.numLightmaps ) + if (*lightmapIndex >= tr.numLightmaps) tr.numLightmaps = *lightmapIndex + 1; - tr.lightmaps[ *lightmapIndex ] = image; + tr.lightmaps[*lightmapIndex] = image; return lightmapIndex; } @@ -3399,36 +2917,34 @@ most world construction surfaces. =============== */ -shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ) -{ - char strippedName[MAX_QPATH]; - char fileName[MAX_QPATH]; - int hash; - const char *shaderText; - image_t *image; - shader_t *sh; - - if ( name[0] == 0 ) { +shader_t *R_FindShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + char fileName[MAX_QPATH]; + int hash; + const char *shaderText; + image_t *image; + shader_t *sh; + + if (name[0] == 0) { return tr.defaultShader; } // use (fullbright) vertex lighting if the bsp file doesn't have // lightmaps -/* if ( lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps ) - { - lightmapIndex = lightmapsVertex; - }*/ + /* if ( lightmapIndex[0] >= 0 && lightmapIndex[0] >= tr.numLightmaps ) + { + lightmapIndex = lightmapsVertex; + }*/ - lightmapIndex = R_FindLightmap( lightmapIndex ); + lightmapIndex = R_FindLightmap(lightmapIndex); - if ( lightmapIndex[0] < LIGHTMAP_2D ) - { + if (lightmapIndex[0] < LIGHTMAP_2D) { // negative lightmap indexes cause stray pointers (think tr.lightmaps[lightmapIndex]) - ri.Printf( PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndex[0] ); + ri.Printf(PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndex[0]); lightmapIndex = lightmapsVertex; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); @@ -3440,8 +2956,7 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, strippedName, lightmapIndex, styles)) - { + if (IsShader(sh, strippedName, lightmapIndex, styles)) { return sh; } } @@ -3455,9 +2970,9 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * // // attempt to define shader from an explicit parameter file // - shaderText = FindShaderInShaderText( strippedName ); - if ( shaderText ) { - if ( !ParseShader( &shaderText ) ) { + shaderText = FindShaderInShaderText(strippedName); + if (shaderText) { + if (!ParseShader(&shaderText)) { // had errors, so use default shader shader.defaultShader = true; } @@ -3465,44 +2980,41 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * return sh; } - // // if not defined in the in-memory shader descriptions, // look for a single TGA, BMP, or PCX // - COM_StripExtension( name, fileName, sizeof( fileName ) ); - image = R_FindImageFile( fileName, mipRawImage, mipRawImage, qtrue, mipRawImage ? GL_REPEAT : GL_CLAMP ); - if ( !image ) { - ri.Printf( PRINT_DEVELOPER, S_COLOR_RED "Couldn't find image for shader %s\n", name ); + COM_StripExtension(name, fileName, sizeof(fileName)); + image = R_FindImageFile(fileName, mipRawImage, mipRawImage, qtrue, mipRawImage ? GL_REPEAT : GL_CLAMP); + if (!image) { + ri.Printf(PRINT_DEVELOPER, S_COLOR_RED "Couldn't find image for shader %s\n", name); shader.defaultShader = true; return FinishShader(); } // // create the default shading commands // - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image = tr.whiteImage; stages[0].active = qtrue; @@ -3518,8 +3030,8 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * stages[0].bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; stages[0].bundle[0].isLightmap = qtrue; stages[0].active = qtrue; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image = image; @@ -3531,17 +3043,16 @@ shader_t *R_FindShader( const char *name, const int *lightmapIndex, const byte * return FinishShader(); } -shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ) -{ - char strippedName[MAX_QPATH]; - int hash; - shader_t *sh; +shader_t *R_FindServerShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; - if ( name[0] == 0 ) { + if (name[0] == 0) { return tr.defaultShader; } - COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + COM_StripExtension(name, strippedName, sizeof(strippedName)); hash = generateHashValue(strippedName, FILE_HASH_SIZE); @@ -3553,8 +3064,7 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, strippedName, lightmapIndex, styles)) - { + if (IsShader(sh, strippedName, lightmapIndex, styles)) { return sh; } } @@ -3570,8 +3080,8 @@ shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const } qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte *styles, image_t *image, qboolean mipRawImage) { - int i, hash; - shader_t *sh; + int i, hash; + shader_t *sh; hash = generateHashValue(name, FILE_HASH_SIZE); @@ -3579,61 +3089,58 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte // only gets called from tr_font.c with lightmapIndex == LIGHTMAP_2D // but better safe than sorry. // Doesn't actually ever get called in JA at all - if ( lightmapIndex[0] >= tr.numLightmaps ) { + if (lightmapIndex[0] >= tr.numLightmaps) { lightmapIndex = (int *)lightmapsFullBright; } // // see if the shader is already loaded // - for (sh=hashTable[hash]; sh; sh=sh->next) { + for (sh = hashTable[hash]; sh; sh = sh->next) { // NOTE: if there was no shader or image available with the name strippedName // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we // have to check all default shaders otherwise for every call to R_FindShader // with that same strippedName a new default shader is created. - if (IsShader(sh, name, lightmapIndex, styles)) - { + if (IsShader(sh, name, lightmapIndex, styles)) { return sh->index; } } // clear the global shader - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); Q_strncpyz(shader.name, name, sizeof(shader.name)); memcpy(shader.lightmapIndex, lightmapIndex, sizeof(shader.lightmapIndex)); memcpy(shader.styles, styles, sizeof(shader.styles)); - for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + for (i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; } // // create the default shading commands // - if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + if (shader.lightmapIndex[0] == LIGHTMAP_NONE) { // dynamic colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) { // explicit colors at vertexes stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_EXACT_VERTEX; stages[0].alphaGen = AGEN_SKIP; stages[0].stateBits = GLS_DEFAULT; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + } else if (shader.lightmapIndex[0] == LIGHTMAP_2D) { // GUI elements stages[0].bundle[0].image = image; stages[0].active = qtrue; stages[0].rgbGen = CGEN_VERTEX; stages[0].alphaGen = AGEN_VERTEX; - stages[0].stateBits = GLS_DEPTHTEST_DISABLE | - GLS_SRCBLEND_SRC_ALPHA | - GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; - } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if (shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE) { // fullbright level stages[0].bundle[0].image = tr.whiteImage; stages[0].active = qtrue; @@ -3649,8 +3156,8 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte stages[0].bundle[0].image = tr.lightmaps[shader.lightmapIndex[0]]; stages[0].bundle[0].isLightmap = qtrue; stages[0].active = qtrue; - stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation - // for identitylight + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight stages[0].stateBits = GLS_DEFAULT; stages[1].bundle[0].image = image; @@ -3660,10 +3167,9 @@ qhandle_t RE_RegisterShaderFromImage(const char *name, int *lightmapIndex, byte } sh = FinishShader(); - return sh->index; + return sh->index; } - /* ==================== RE_RegisterShader @@ -3675,30 +3181,28 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndex, const byte *styles ) -{ - shader_t *sh; +qhandle_t RE_RegisterShaderLightMap(const char *name, const int *lightmapIndex, const byte *styles) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmapIndex, styles, qtrue ); + sh = R_FindShader(name, lightmapIndex, styles, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShader @@ -3710,29 +3214,28 @@ This should really only be used for explicit shaders, because there is no way to ask for different implicit lighting modes (vertex, lightmap, etc) ==================== */ -qhandle_t RE_RegisterShader( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShader(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qtrue ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qtrue); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - /* ==================== RE_RegisterShaderNoMip @@ -3740,37 +3243,34 @@ RE_RegisterShaderNoMip For menu graphics that should never be picmiped ==================== */ -qhandle_t RE_RegisterShaderNoMip( const char *name ) { - shader_t *sh; +qhandle_t RE_RegisterShaderNoMip(const char *name) { + shader_t *sh; - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Shader name exceeds MAX_QPATH\n"); return 0; } - sh = R_FindShader( name, lightmaps2d, stylesDefault, qfalse ); + sh = R_FindShader(name, lightmaps2d, stylesDefault, qfalse); // we want to return 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again - if ( sh->defaultShader ) { + if (sh->defaultShader) { return 0; } return sh->index; } - -//added for ui -rww -const char *RE_ShaderNameFromIndex(int index) -{ +// added for ui -rww +const char *RE_ShaderNameFromIndex(int index) { assert(index >= 0 && index < tr.numShaders && tr.shaders[index]); return tr.shaders[index]->name; } - /* ==================== R_GetShaderByHandle @@ -3779,13 +3279,13 @@ When a handle is passed in by another module, this range checks it and returns a valid (possibly default) shader_t to be used internally. ==================== */ -shader_t *R_GetShaderByHandle( qhandle_t hShader ) { - if ( hShader < 0 ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); +shader_t *R_GetShaderByHandle(qhandle_t hShader) { + if (hShader < 0) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } - if ( hShader >= tr.numShaders ) { - ri.Printf( PRINT_ALL, S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + if (hShader >= tr.numShaders) { + ri.Printf(PRINT_ALL, S_COLOR_YELLOW "R_GetShaderByHandle: out of range hShader '%d'\n", hShader); return tr.defaultShader; } return tr.shaders[hShader]; @@ -3799,148 +3299,126 @@ Dump information on all valid shaders to the console A second parameter will cause it to print in sorted order =============== */ -void R_ShaderList_f (void) { - int i; - int count; - shader_t *shader; +void R_ShaderList_f(void) { + int i; + int count; + shader_t *shader; - ri.Printf( PRINT_ALL, "-----------------------\n"); + ri.Printf(PRINT_ALL, "-----------------------\n"); count = 0; - for ( i = 0 ; i < tr.numShaders ; i++ ) { - if ( ri.Cmd_Argc() > 1 ) { + for (i = 0; i < tr.numShaders; i++) { + if (ri.Cmd_Argc() > 1) { shader = tr.sortedShaders[i]; } else { shader = tr.shaders[i]; } - ri.Printf( PRINT_ALL, "%i ", shader->numUnfoggedPasses ); + ri.Printf(PRINT_ALL, "%i ", shader->numUnfoggedPasses); - if (shader->lightmapIndex[0] >= 0 ) { - ri.Printf( PRINT_ALL, "L "); + if (shader->lightmapIndex[0] >= 0) { + ri.Printf(PRINT_ALL, "L "); } else { - ri.Printf( PRINT_ALL, " "); - } - if ( shader->multitextureEnv == GL_ADD ) { - ri.Printf( PRINT_ALL, "MT(a) " ); - } else if ( shader->multitextureEnv == GL_MODULATE ) { - ri.Printf( PRINT_ALL, "MT(m) " ); - } else if ( shader->multitextureEnv == GL_DECAL ) { - ri.Printf( PRINT_ALL, "MT(d) " ); + ri.Printf(PRINT_ALL, " "); + } + if (shader->multitextureEnv == GL_ADD) { + ri.Printf(PRINT_ALL, "MT(a) "); + } else if (shader->multitextureEnv == GL_MODULATE) { + ri.Printf(PRINT_ALL, "MT(m) "); + } else if (shader->multitextureEnv == GL_DECAL) { + ri.Printf(PRINT_ALL, "MT(d) "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->explicitlyDefined ) { - ri.Printf( PRINT_ALL, "E " ); + if (shader->explicitlyDefined) { + ri.Printf(PRINT_ALL, "E "); } else { - ri.Printf( PRINT_ALL, " " ); + ri.Printf(PRINT_ALL, " "); } - if ( shader->sky ) - { - ri.Printf( PRINT_ALL, "sky " ); + if (shader->sky) { + ri.Printf(PRINT_ALL, "sky "); } else { - ri.Printf( PRINT_ALL, "gen " ); + ri.Printf(PRINT_ALL, "gen "); } - if ( shader->defaultShader ) { - ri.Printf( PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); + if (shader->defaultShader) { + ri.Printf(PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); } else { - ri.Printf( PRINT_ALL, ": %s\n", shader->name); + ri.Printf(PRINT_ALL, ": %s\n", shader->name); } count++; } - ri.Printf( PRINT_ALL, "%i total shaders\n", count); - ri.Printf( PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "%i total shaders\n", count); + ri.Printf(PRINT_ALL, "------------------\n"); } -int COM_CompressShader( char *data_p ) -{ +int COM_CompressShader(char *data_p) { char *in, *out; int c; qboolean newline = qfalse, whitespace = qfalse; in = out = data_p; - if ( in ) - { - while ( (c = *in) != 0 ) - { + if (in) { + while ((c = *in) != 0) { // skip double slash comments - if ( c == '/' && in[1] == '/' ) - { - while ( *in && *in != '\n' ) - { + if (c == '/' && in[1] == '/') { + while (*in && *in != '\n') { in++; } } // skip number sign comments - else if ( c == '#' ) - { - while ( *in && *in != '\n' ) - { + else if (c == '#') { + while (*in && *in != '\n') { in++; } } // skip /* */ comments - else if ( c == '/' && in[1] == '*' ) - { - while ( *in && (*in != '*' || in[1] != '/') ) + else if (c == '/' && in[1] == '*') { + while (*in && (*in != '*' || in[1] != '/')) in++; - if ( *in ) + if (*in) in += 2; } // record when we hit a newline - else if ( c == '\n' || c == '\r' ) - { + else if (c == '\n' || c == '\r') { newline = qtrue; in++; } // record when we hit whitespace - else if ( c == ' ' || c == '\t' ) - { + else if (c == ' ' || c == '\t') { whitespace = qtrue; in++; // an actual token - } - else - { + } else { // if we have a pending newline, emit it (and it counts as whitespace) - if ( newline ) - { + if (newline) { *out++ = '\n'; newline = qfalse; whitespace = qfalse; - } if ( whitespace ) - { + } + if (whitespace) { *out++ = ' '; whitespace = qfalse; } // copy quoted strings unmolested - if ( c == '"' ) - { + if (c == '"') { *out++ = c; in++; - while ( 1 ) - { + while (1) { c = *in; - if ( c && c != '"' ) - { + if (c && c != '"') { *out++ = c; in++; - } - else - { + } else { break; } } - if ( c == '"' ) - { + if (c == '"') { *out++ = c; in++; } - } - else - { + } else { *out = c; out++; in++; @@ -3961,9 +3439,8 @@ Finds and loads all .shader files, combining them into a single large text block that can be scanned for shader names ===================== */ -#define MAX_SHADER_FILES 4096 -static void ScanAndLoadShaderFiles( void ) -{ +#define MAX_SHADER_FILES 4096 +static void ScanAndLoadShaderFiles(void) { char **shaderFiles; char *buffers[MAX_SHADER_FILES]; const char *p; @@ -3976,59 +3453,52 @@ static void ScanAndLoadShaderFiles( void ) long sum = 0, summand; // scan for shader files - shaderFiles = ri.FS_ListFiles( "shaders", ".shader", &numShaderFiles ); + shaderFiles = ri.FS_ListFiles("shaders", ".shader", &numShaderFiles); - if ( !shaderFiles || !numShaderFiles ) - { - ri.Error( ERR_FATAL, "ERROR: no shader files found" ); + if (!shaderFiles || !numShaderFiles) { + ri.Error(ERR_FATAL, "ERROR: no shader files found"); return; } - if ( numShaderFiles > MAX_SHADER_FILES ) { + if (numShaderFiles > MAX_SHADER_FILES) { numShaderFiles = MAX_SHADER_FILES; } // load and parse shader files - for ( i = 0; i < numShaderFiles; i++ ) - { + for (i = 0; i < numShaderFiles; i++) { char filename[MAX_QPATH]; - Com_sprintf( filename, sizeof( filename ), "shaders/%s", shaderFiles[i] ); - ri.Printf( PRINT_DEVELOPER, "...loading '%s'\n", filename ); - summand = ri.FS_ReadFile( filename, (void **)&buffers[i] ); + Com_sprintf(filename, sizeof(filename), "shaders/%s", shaderFiles[i]); + ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); + summand = ri.FS_ReadFile(filename, (void **)&buffers[i]); - if ( !buffers[i] ) { - ri.Error( ERR_DROP, "Couldn't load %s", filename ); + if (!buffers[i]) { + ri.Error(ERR_DROP, "Couldn't load %s", filename); } // Do a simple check on the shader structure in that file to make sure one bad shader file cannot fuck up all other shaders. p = buffers[i]; COM_BeginParseSession(filename); - while(1) - { + while (1) { token = COM_ParseExt(&p, qtrue); - if(!*token) + if (!*token) break; Q_strncpyz(shaderName, token, sizeof(shaderName)); shaderLine = COM_GetCurrentParseLine(); - if ( token[0] == '#' ) - { - ri.Printf( PRINT_WARNING, "WARNING: Deprecated shader comment \"%s\" on line %d in file %s. Ignoring line.\n", - shaderName, shaderLine, filename ); - SkipRestOfLine( &p ); + if (token[0] == '#') { + ri.Printf(PRINT_WARNING, "WARNING: Deprecated shader comment \"%s\" on line %d in file %s. Ignoring line.\n", shaderName, shaderLine, + filename); + SkipRestOfLine(&p); continue; } token = COM_ParseExt(&p, qtrue); - if(token[0] != '{' || token[1] != '\0') - { - ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing opening brace", - filename, shaderName, shaderLine); - if (token[0]) - { + if (token[0] != '{' || token[1] != '\0') { + ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing opening brace", filename, shaderName, shaderLine); + if (token[0]) { ri.Printf(PRINT_WARNING, " (found \"%s\" on line %d)", token, COM_GetCurrentParseLine()); } ri.Printf(PRINT_WARNING, ".\n"); @@ -4037,96 +3507,91 @@ static void ScanAndLoadShaderFiles( void ) break; } - if(!SkipBracedSection(&p, 1)) - { - ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing closing brace.\n", - filename, shaderName, shaderLine); + if (!SkipBracedSection(&p, 1)) { + ri.Printf(PRINT_WARNING, "WARNING: Ignoring shader file %s. Shader \"%s\" on line %d missing closing brace.\n", filename, shaderName, + shaderLine); ri.FS_FreeFile(buffers[i]); buffers[i] = NULL; break; } } - if (buffers[i]) sum += summand; } // build single large buffer - s_shaderText = (char *)ri.Hunk_Alloc( sum + numShaderFiles*2, h_low ); - s_shaderText[ 0 ] = '\0'; + s_shaderText = (char *)ri.Hunk_Alloc(sum + numShaderFiles * 2, h_low); + s_shaderText[0] = '\0'; textEnd = s_shaderText; // free in reverse order, so the temp files are all dumped - for ( i = numShaderFiles - 1; i >= 0 ; i-- ) - { - if ( !buffers[i] ) + for (i = numShaderFiles - 1; i >= 0; i--) { + if (!buffers[i]) continue; - strcat( textEnd, buffers[i] ); - strcat( textEnd, "\n" ); - textEnd += strlen( textEnd ); - ri.FS_FreeFile( buffers[i] ); + strcat(textEnd, buffers[i]); + strcat(textEnd, "\n"); + textEnd += strlen(textEnd); + ri.FS_FreeFile(buffers[i]); } - COM_CompressShader( s_shaderText ); + COM_CompressShader(s_shaderText); // free up memory - ri.FS_FreeFileList( shaderFiles ); + ri.FS_FreeFileList(shaderFiles); memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); size = 0; p = s_shaderText; // look for shader names - while ( 1 ) { - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + while (1) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( token[0] == '#' ) - { - SkipRestOfLine( &p ); + if (token[0] == '#') { + SkipRestOfLine(&p); continue; } hash = generateHashValue(token, MAX_SHADERTEXT_HASH); shaderTextHashTableSizes[hash]++; size++; - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } size += MAX_SHADERTEXT_HASH; - hashMem = (char *)ri.Hunk_Alloc( size * sizeof(char *), h_low ); + hashMem = (char *)ri.Hunk_Alloc(size * sizeof(char *), h_low); for (i = 0; i < MAX_SHADERTEXT_HASH; i++) { - shaderTextHashTable[i] = (char **) hashMem; - hashMem = ((char *) hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *)); + shaderTextHashTable[i] = (char **)hashMem; + hashMem = ((char *)hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *)); } memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); p = s_shaderText; // look for shader names - while ( 1 ) { + while (1) { oldp = (char *)p; - token = COM_ParseExt( &p, qtrue ); - if ( token[0] == 0 ) { + token = COM_ParseExt(&p, qtrue); + if (token[0] == 0) { break; } - if ( token[0] == '#' ) - { - SkipRestOfLine( &p ); + if (token[0] == '#') { + SkipRestOfLine(&p); continue; } hash = generateHashValue(token, MAX_SHADERTEXT_HASH); shaderTextHashTable[hash][shaderTextHashTableSizes[hash]++] = oldp; - SkipBracedSection( &p, 0 ); + SkipBracedSection(&p, 0); } return; @@ -4137,18 +3602,18 @@ static void ScanAndLoadShaderFiles( void ) CreateInternalShaders ==================== */ -static void CreateInternalShaders( void ) { +static void CreateInternalShaders(void) { tr.numShaders = 0; // init the default shader - memset( &shader, 0, sizeof( shader ) ); - memset( &stages, 0, sizeof( stages ) ); + memset(&shader, 0, sizeof(shader)); + memset(&stages, 0, sizeof(stages)); - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "", sizeof(shader.name)); memcpy(shader.lightmapIndex, lightmapsNone, sizeof(shader.lightmapIndex)); memcpy(shader.styles, stylesDefault, sizeof(shader.styles)); - for ( int i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + for (int i = 0; i < MAX_SHADER_STAGES; i++) { stages[i].bundle[0].texMods = texMods[i]; } @@ -4158,12 +3623,12 @@ static void CreateInternalShaders( void ) { tr.defaultShader = FinishShader(); // shadow shader is just a marker - Q_strncpyz( shader.name, "", sizeof( shader.name ) ); - shader.sort = SS_BANNER; //SS_STENCIL_SHADOW; + Q_strncpyz(shader.name, "", sizeof(shader.name)); + shader.sort = SS_BANNER; // SS_STENCIL_SHADOW; tr.shadowShader = FinishShader(); // distortion shader is just a marker - Q_strncpyz( shader.name, "internal_distortion", sizeof( shader.name ) ); + Q_strncpyz(shader.name, "internal_distortion", sizeof(shader.name)); shader.sort = SS_BLEND0; shader.defaultShader = qfalse; tr.distortionShader = FinishShader(); @@ -4172,10 +3637,10 @@ static void CreateInternalShaders( void ) { ARB_InitGPUShaders(); } -static void CreateExternalShaders( void ) { - tr.projectionShadowShader = R_FindShader( "projectionShadow", lightmapsNone, stylesDefault, qtrue ); +static void CreateExternalShaders(void) { + tr.projectionShadowShader = R_FindShader("projectionShadow", lightmapsNone, stylesDefault, qtrue); tr.projectionShadowShader->sort = SS_STENCIL_SHADOW; - tr.sunShader = R_FindShader( "sun", lightmapsNone, stylesDefault, qtrue ); + tr.sunShader = R_FindShader("sun", lightmapsNone, stylesDefault, qtrue); } /* @@ -4183,14 +3648,12 @@ static void CreateExternalShaders( void ) { R_InitShaders ================== */ -void R_InitShaders(qboolean server) -{ - //ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); +void R_InitShaders(qboolean server) { + // ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); memset(hashTable, 0, sizeof(hashTable)); - if ( !server ) - { + if (!server) { CreateInternalShaders(); ScanAndLoadShaderFiles(); diff --git a/codemp/rd-vanilla/tr_shadows.cpp b/codemp/rd-vanilla/tr_shadows.cpp index d5480fc62c..df3ca9312a 100644 --- a/codemp/rd-vanilla/tr_shadows.cpp +++ b/codemp/rd-vanilla/tr_shadows.cpp @@ -23,7 +23,6 @@ along with this program; if not, see . #include "tr_local.h" - /* for a projection shadow: @@ -39,43 +38,43 @@ along with this program; if not, see . #define _STENCIL_REVERSE typedef struct edgeDef_s { - int i2; - int facing; + int i2; + int facing; } edgeDef_t; -#define MAX_EDGE_DEFS 32 +#define MAX_EDGE_DEFS 32 -static edgeDef_t edgeDefs[SHADER_MAX_VERTEXES][MAX_EDGE_DEFS]; -static int numEdgeDefs[SHADER_MAX_VERTEXES]; -static int facing[SHADER_MAX_INDEXES/3]; -static vec3_t shadowXyz[SHADER_MAX_VERTEXES]; +static edgeDef_t edgeDefs[SHADER_MAX_VERTEXES][MAX_EDGE_DEFS]; +static int numEdgeDefs[SHADER_MAX_VERTEXES]; +static int facing[SHADER_MAX_INDEXES / 3]; +static vec3_t shadowXyz[SHADER_MAX_VERTEXES]; -void R_AddEdgeDef( int i1, int i2, int facing ) { - int c; +void R_AddEdgeDef(int i1, int i2, int facing) { + int c; - c = numEdgeDefs[ i1 ]; - if ( c == MAX_EDGE_DEFS ) { - return; // overflow + c = numEdgeDefs[i1]; + if (c == MAX_EDGE_DEFS) { + return; // overflow } - edgeDefs[ i1 ][ c ].i2 = i2; - edgeDefs[ i1 ][ c ].facing = facing; + edgeDefs[i1][c].i2 = i2; + edgeDefs[i1][c].facing = facing; - numEdgeDefs[ i1 ]++; + numEdgeDefs[i1]++; } -void R_RenderShadowEdges( void ) { - int i; - int c; - int j; - int i2; +void R_RenderShadowEdges(void) { + int i; + int c; + int j; + int i2; #if 0 int c_edges, c_rejected; int c2, k; int hit[2]; #endif #ifdef _STENCIL_REVERSE - int numTris; - int o1, o2, o3; + int numTris; + int o1, o2, o3; #endif // an edge is NOT a silhouette edge if its face doesn't face the light, @@ -87,45 +86,44 @@ void R_RenderShadowEdges( void ) { c_rejected = 0; #endif - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - c = numEdgeDefs[ i ]; - for ( j = 0 ; j < c ; j++ ) { - if ( !edgeDefs[ i ][ j ].facing ) { + for (i = 0; i < tess.numVertexes; i++) { + c = numEdgeDefs[i]; + for (j = 0; j < c; j++) { + if (!edgeDefs[i][j].facing) { continue; } - //with this system we can still get edges shared by more than 2 tris which - //produces artifacts including seeing the shadow through walls. So for now - //we are going to render all edges even though it is a tiny bit slower. -rww + // with this system we can still get edges shared by more than 2 tris which + // produces artifacts including seeing the shadow through walls. So for now + // we are going to render all edges even though it is a tiny bit slower. -rww #if 1 - i2 = edgeDefs[ i ][ j ].i2; - qglBegin( GL_TRIANGLE_STRIP ); - qglVertex3fv( tess.xyz[ i ] ); - qglVertex3fv( shadowXyz[ i ] ); - qglVertex3fv( tess.xyz[ i2 ] ); - qglVertex3fv( shadowXyz[ i2 ] ); + i2 = edgeDefs[i][j].i2; + qglBegin(GL_TRIANGLE_STRIP); + qglVertex3fv(tess.xyz[i]); + qglVertex3fv(shadowXyz[i]); + qglVertex3fv(tess.xyz[i2]); + qglVertex3fv(shadowXyz[i2]); qglEnd(); #else hit[0] = 0; hit[1] = 0; - i2 = edgeDefs[ i ][ j ].i2; - c2 = numEdgeDefs[ i2 ]; - for ( k = 0 ; k < c2 ; k++ ) { - if ( edgeDefs[ i2 ][ k ].i2 == i ) { - hit[ edgeDefs[ i2 ][ k ].facing ]++; + i2 = edgeDefs[i][j].i2; + c2 = numEdgeDefs[i2]; + for (k = 0; k < c2; k++) { + if (edgeDefs[i2][k].i2 == i) { + hit[edgeDefs[i2][k].facing]++; } } // if it doesn't share the edge with another front facing // triangle, it is a sil edge - if (hit[1] != 1) - { - qglBegin( GL_TRIANGLE_STRIP ); - qglVertex3fv( tess.xyz[ i ] ); - qglVertex3fv( shadowXyz[ i ] ); - qglVertex3fv( tess.xyz[ i2 ] ); - qglVertex3fv( shadowXyz[ i2 ] ); + if (hit[1] != 1) { + qglBegin(GL_TRIANGLE_STRIP); + qglVertex3fv(tess.xyz[i]); + qglVertex3fv(shadowXyz[i]); + qglVertex3fv(tess.xyz[i2]); + qglVertex3fv(shadowXyz[i2]); qglEnd(); c_edges++; } else { @@ -136,30 +134,28 @@ void R_RenderShadowEdges( void ) { } #ifdef _STENCIL_REVERSE - //Carmack Reverse method requires that volumes - //be capped properly -rww + // Carmack Reverse method requires that volumes + // be capped properly -rww numTris = tess.numIndexes / 3; - for ( i = 0 ; i < numTris ; i++ ) - { - if ( !facing[i] ) - { + for (i = 0; i < numTris; i++) { + if (!facing[i]) { continue; } - o1 = tess.indexes[ i*3 + 0 ]; - o2 = tess.indexes[ i*3 + 1 ]; - o3 = tess.indexes[ i*3 + 2 ]; + o1 = tess.indexes[i * 3 + 0]; + o2 = tess.indexes[i * 3 + 1]; + o3 = tess.indexes[i * 3 + 2]; qglBegin(GL_TRIANGLES); - qglVertex3fv(tess.xyz[o1]); - qglVertex3fv(tess.xyz[o2]); - qglVertex3fv(tess.xyz[o3]); + qglVertex3fv(tess.xyz[o1]); + qglVertex3fv(tess.xyz[o2]); + qglVertex3fv(tess.xyz[o3]); qglEnd(); qglBegin(GL_TRIANGLES); - qglVertex3fv(shadowXyz[o3]); - qglVertex3fv(shadowXyz[o2]); - qglVertex3fv(shadowXyz[o1]); + qglVertex3fv(shadowXyz[o3]); + qglVertex3fv(shadowXyz[o2]); + qglVertex3fv(shadowXyz[o1]); qglEnd(); } #endif @@ -179,9 +175,8 @@ triangleFromEdge[ v1 ][ v2 ] } ================= */ -void RB_DoShadowTessEnd( vec3_t lightPos ); -void RB_ShadowTessEnd( void ) -{ +void RB_DoShadowTessEnd(vec3_t lightPos); +void RB_ShadowTessEnd(void) { #if 0 if (backEnd.currentEntity && (backEnd.currentEntity->directedLight[0] || @@ -217,150 +212,134 @@ void RB_ShadowTessEnd( void ) RB_DoShadowTessEnd(dl->transformed); -#else //old ents-only way +#else // old ents-only way RB_DoShadowTessEnd(NULL); #endif } -void RB_DoShadowTessEnd( vec3_t lightPos ) -{ - int i; - int numTris; - vec3_t lightDir; +void RB_DoShadowTessEnd(vec3_t lightPos) { + int i; + int numTris; + vec3_t lightDir; - if ( glConfig.stencilBits < 4 ) { + if (glConfig.stencilBits < 4) { return; } -#if 1 //controlled method - try to keep shadows in range so they don't show through so much -rww - vec3_t worldxyz; - vec3_t entLight; - float groundDist; +#if 1 // controlled method - try to keep shadows in range so they don't show through so much -rww + vec3_t worldxyz; + vec3_t entLight; + float groundDist; - VectorCopy( backEnd.currentEntity->lightDir, entLight ); + VectorCopy(backEnd.currentEntity->lightDir, entLight); entLight[2] = 0.0f; VectorNormalize(entLight); - //Oh well, just cast them straight down no matter what onto the ground plane. - //This presets no chance of screwups and still looks better than a stupid - //shader blob. - VectorSet(lightDir, entLight[0]*0.3f, entLight[1]*0.3f, 1.0f); + // Oh well, just cast them straight down no matter what onto the ground plane. + // This presets no chance of screwups and still looks better than a stupid + // shader blob. + VectorSet(lightDir, entLight[0] * 0.3f, entLight[1] * 0.3f, 1.0f); // project vertexes away from light direction - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - //add or.origin to vert xyz to end up with world oriented coord, then figure - //out the ground pos for the vert to project the shadow volume to + for (i = 0; i < tess.numVertexes; i++) { + // add or.origin to vert xyz to end up with world oriented coord, then figure + // out the ground pos for the vert to project the shadow volume to VectorAdd(tess.xyz[i], backEnd.ori.origin, worldxyz); groundDist = worldxyz[2] - backEnd.currentEntity->e.shadowPlane; - groundDist += 16.0f; //fudge factor - VectorMA( tess.xyz[i], -groundDist, lightDir, shadowXyz[i] ); + groundDist += 16.0f; // fudge factor + VectorMA(tess.xyz[i], -groundDist, lightDir, shadowXyz[i]); } #else - if (lightPos) - { - for ( i = 0 ; i < tess.numVertexes ; i++ ) - { - shadowXyz[i][0] = tess.xyz[i][0]+(( tess.xyz[i][0]-lightPos[0] )*128.0f); - shadowXyz[i][1] = tess.xyz[i][1]+(( tess.xyz[i][1]-lightPos[1] )*128.0f); - shadowXyz[i][2] = tess.xyz[i][2]+(( tess.xyz[i][2]-lightPos[2] )*128.0f); + if (lightPos) { + for (i = 0; i < tess.numVertexes; i++) { + shadowXyz[i][0] = tess.xyz[i][0] + ((tess.xyz[i][0] - lightPos[0]) * 128.0f); + shadowXyz[i][1] = tess.xyz[i][1] + ((tess.xyz[i][1] - lightPos[1]) * 128.0f); + shadowXyz[i][2] = tess.xyz[i][2] + ((tess.xyz[i][2] - lightPos[2]) * 128.0f); } - } - else - { - VectorCopy( backEnd.currentEntity->lightDir, lightDir ); + } else { + VectorCopy(backEnd.currentEntity->lightDir, lightDir); // project vertexes away from light direction - for ( i = 0 ; i < tess.numVertexes ; i++ ) { - VectorMA( tess.xyz[i], -512, lightDir, shadowXyz[i] ); + for (i = 0; i < tess.numVertexes; i++) { + VectorMA(tess.xyz[i], -512, lightDir, shadowXyz[i]); } } #endif // decide which triangles face the light - memset( numEdgeDefs, 0, 4 * tess.numVertexes ); + memset(numEdgeDefs, 0, 4 * tess.numVertexes); numTris = tess.numIndexes / 3; - for ( i = 0 ; i < numTris ; i++ ) { - int i1, i2, i3; - vec3_t d1, d2, normal; - float *v1, *v2, *v3; - float d; - - i1 = tess.indexes[ i*3 + 0 ]; - i2 = tess.indexes[ i*3 + 1 ]; - i3 = tess.indexes[ i*3 + 2 ]; - - v1 = tess.xyz[ i1 ]; - v2 = tess.xyz[ i2 ]; - v3 = tess.xyz[ i3 ]; - - if (!lightPos) - { - VectorSubtract( v2, v1, d1 ); - VectorSubtract( v3, v1, d2 ); - CrossProduct( d1, d2, normal ); - - d = DotProduct( normal, lightDir ); - } - else - { + for (i = 0; i < numTris; i++) { + int i1, i2, i3; + vec3_t d1, d2, normal; + float *v1, *v2, *v3; + float d; + + i1 = tess.indexes[i * 3 + 0]; + i2 = tess.indexes[i * 3 + 1]; + i3 = tess.indexes[i * 3 + 2]; + + v1 = tess.xyz[i1]; + v2 = tess.xyz[i2]; + v3 = tess.xyz[i3]; + + if (!lightPos) { + VectorSubtract(v2, v1, d1); + VectorSubtract(v3, v1, d2); + CrossProduct(d1, d2, normal); + + d = DotProduct(normal, lightDir); + } else { float planeEq[4]; - planeEq[0] = v1[1]*(v2[2]-v3[2]) + v2[1]*(v3[2]-v1[2]) + v3[1]*(v1[2]-v2[2]); - planeEq[1] = v1[2]*(v2[0]-v3[0]) + v2[2]*(v3[0]-v1[0]) + v3[2]*(v1[0]-v2[0]); - planeEq[2] = v1[0]*(v2[1]-v3[1]) + v2[0]*(v3[1]-v1[1]) + v3[0]*(v1[1]-v2[1]); - planeEq[3] = -( v1[0]*( v2[1]*v3[2] - v3[1]*v2[2] ) + - v2[0]*(v3[1]*v1[2] - v1[1]*v3[2]) + - v3[0]*(v1[1]*v2[2] - v2[1]*v1[2]) ); - - d = planeEq[0]*lightPos[0]+ - planeEq[1]*lightPos[1]+ - planeEq[2]*lightPos[2]+ - planeEq[3]; + planeEq[0] = v1[1] * (v2[2] - v3[2]) + v2[1] * (v3[2] - v1[2]) + v3[1] * (v1[2] - v2[2]); + planeEq[1] = v1[2] * (v2[0] - v3[0]) + v2[2] * (v3[0] - v1[0]) + v3[2] * (v1[0] - v2[0]); + planeEq[2] = v1[0] * (v2[1] - v3[1]) + v2[0] * (v3[1] - v1[1]) + v3[0] * (v1[1] - v2[1]); + planeEq[3] = -(v1[0] * (v2[1] * v3[2] - v3[1] * v2[2]) + v2[0] * (v3[1] * v1[2] - v1[1] * v3[2]) + v3[0] * (v1[1] * v2[2] - v2[1] * v1[2])); + + d = planeEq[0] * lightPos[0] + planeEq[1] * lightPos[1] + planeEq[2] * lightPos[2] + planeEq[3]; } - if ( d > 0 ) { - facing[ i ] = 1; + if (d > 0) { + facing[i] = 1; } else { - facing[ i ] = 0; + facing[i] = 0; } // create the edges - R_AddEdgeDef( i1, i2, facing[ i ] ); - R_AddEdgeDef( i2, i3, facing[ i ] ); - R_AddEdgeDef( i3, i1, facing[ i ] ); + R_AddEdgeDef(i1, i2, facing[i]); + R_AddEdgeDef(i2, i3, facing[i]); + R_AddEdgeDef(i3, i1, facing[i]); } - GL_Bind( tr.whiteImage ); - //qglEnable( GL_CULL_FACE ); - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); + GL_Bind(tr.whiteImage); + // qglEnable( GL_CULL_FACE ); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); #ifndef _DEBUG_STENCIL_SHADOWS - qglColor3f( 0.2f, 0.2f, 0.2f ); + qglColor3f(0.2f, 0.2f, 0.2f); // don't write to the color buffer - qglColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); + qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - qglEnable( GL_STENCIL_TEST ); - qglStencilFunc( GL_ALWAYS, 1, 255 ); + qglEnable(GL_STENCIL_TEST); + qglStencilFunc(GL_ALWAYS, 1, 255); #else - qglColor3f( 1.0f, 0.0f, 0.0f ); + qglColor3f(1.0f, 0.0f, 0.0f); qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - //qglDisable(GL_DEPTH_TEST); + // qglDisable(GL_DEPTH_TEST); #endif #ifdef _STENCIL_REVERSE qglDepthFunc(GL_LESS); - //now using the Carmack Reverse -rww - if ( glConfigExt.doStencilShadowsInOneDrawcall ) - { + // now using the Carmack Reverse -rww + if (glConfigExt.doStencilShadowsInOneDrawcall) { GL_Cull(CT_TWO_SIDED); qglStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_KEEP); qglStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_KEEP); R_RenderShadowEdges(); qglDisable(GL_STENCIL_TEST); - } - else - { + } else { GL_Cull(CT_FRONT_SIDED); qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP); @@ -375,38 +354,37 @@ void RB_DoShadowTessEnd( vec3_t lightPos ) qglDepthFunc(GL_LEQUAL); #else // mirrors have the culling order reversed - if ( backEnd.viewParms.isMirror ) { - qglCullFace( GL_FRONT ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR ); + if (backEnd.viewParms.isMirror) { + qglCullFace(GL_FRONT); + qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); R_RenderShadowEdges(); - qglCullFace( GL_BACK ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR ); + qglCullFace(GL_BACK); + qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR); R_RenderShadowEdges(); } else { - qglCullFace( GL_BACK ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_INCR ); + qglCullFace(GL_BACK); + qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR); R_RenderShadowEdges(); - qglCullFace( GL_FRONT ); - qglStencilOp( GL_KEEP, GL_KEEP, GL_DECR ); + qglCullFace(GL_FRONT); + qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR); R_RenderShadowEdges(); } #endif // reenable writing to the color buffer - qglColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); - + qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + #ifdef _DEBUG_STENCIL_SHADOWS qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif } - /* ================= RB_ShadowFinish @@ -417,11 +395,11 @@ because otherwise shadows from different body parts would overlap and double darken. ================= */ -void RB_ShadowFinish( void ) { - if ( r_shadows->integer != 2 ) { +void RB_ShadowFinish(void) { + if (r_shadows->integer != 2) { return; } - if ( glConfig.stencilBits < 4 ) { + if (glConfig.stencilBits < 4) { return; } @@ -429,69 +407,66 @@ void RB_ShadowFinish( void ) { return; #endif - qglEnable( GL_STENCIL_TEST ); - qglStencilFunc( GL_NOTEQUAL, 0, 255 ); + qglEnable(GL_STENCIL_TEST); + qglStencilFunc(GL_NOTEQUAL, 0, 255); - qglStencilOp( GL_KEEP, GL_KEEP, GL_KEEP ); + qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); bool planeZeroBack = false; - if (qglIsEnabled(GL_CLIP_PLANE0)) - { + if (qglIsEnabled(GL_CLIP_PLANE0)) { planeZeroBack = true; - qglDisable (GL_CLIP_PLANE0); + qglDisable(GL_CLIP_PLANE0); } GL_Cull(CT_TWO_SIDED); - //qglDisable (GL_CULL_FACE); + // qglDisable (GL_CULL_FACE); - GL_Bind( tr.whiteImage ); + GL_Bind(tr.whiteImage); qglPushMatrix(); - qglLoadIdentity (); + qglLoadIdentity(); -// qglColor3f( 0.6f, 0.6f, 0.6f ); -// GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO ); + // qglColor3f( 0.6f, 0.6f, 0.6f ); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO ); -// qglColor3f( 1, 0, 0 ); -// GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); + // qglColor3f( 1, 0, 0 ); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO ); - qglColor4f( 0.0f, 0.0f, 0.0f, 0.5f ); - //GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); - GL_State( GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + qglColor4f(0.0f, 0.0f, 0.0f, 0.5f); + // GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); - qglBegin( GL_QUADS ); - qglVertex3f( -100, 100, -10 ); - qglVertex3f( 100, 100, -10 ); - qglVertex3f( 100, -100, -10 ); - qglVertex3f( -100, -100, -10 ); - qglEnd (); + qglBegin(GL_QUADS); + qglVertex3f(-100, 100, -10); + qglVertex3f(100, 100, -10); + qglVertex3f(100, -100, -10); + qglVertex3f(-100, -100, -10); + qglEnd(); - qglColor4f(1,1,1,1); - qglDisable( GL_STENCIL_TEST ); - if (planeZeroBack) - { - qglEnable (GL_CLIP_PLANE0); + qglColor4f(1, 1, 1, 1); + qglDisable(GL_STENCIL_TEST); + if (planeZeroBack) { + qglEnable(GL_CLIP_PLANE0); } qglPopMatrix(); } - /* ================= RB_ProjectionShadowDeform ================= */ -void RB_ProjectionShadowDeform( void ) { - float *xyz; - int i; - float h; - vec3_t ground; - vec3_t light; - float groundDist; - float d; - vec3_t lightDir; - - xyz = ( float * ) tess.xyz; +void RB_ProjectionShadowDeform(void) { + float *xyz; + int i; + float h; + vec3_t ground; + vec3_t light; + float groundDist; + float d; + vec3_t lightDir; + + xyz = (float *)tess.xyz; ground[0] = backEnd.ori.axis[0][2]; ground[1] = backEnd.ori.axis[1][2]; @@ -499,12 +474,12 @@ void RB_ProjectionShadowDeform( void ) { groundDist = backEnd.ori.origin[2] - backEnd.currentEntity->e.shadowPlane; - VectorCopy( backEnd.currentEntity->lightDir, lightDir ); - d = DotProduct( lightDir, ground ); + VectorCopy(backEnd.currentEntity->lightDir, lightDir); + d = DotProduct(lightDir, ground); // don't let the shadows get too long or go negative - if ( d < 0.5 ) { - VectorMA( lightDir, (0.5 - d), ground, lightDir ); - d = DotProduct( lightDir, ground ); + if (d < 0.5) { + VectorMA(lightDir, (0.5 - d), ground, lightDir); + d = DotProduct(lightDir, ground); } d = 1.0 / d; @@ -512,8 +487,8 @@ void RB_ProjectionShadowDeform( void ) { light[1] = lightDir[1] * d; light[2] = lightDir[2] * d; - for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { - h = DotProduct( xyz, ground ) + groundDist; + for (i = 0; i < tess.numVertexes; i++, xyz += 4) { + h = DotProduct(xyz, ground) + groundDist; xyz[0] -= light[0] * h; xyz[1] -= light[1] * h; @@ -521,18 +496,17 @@ void RB_ProjectionShadowDeform( void ) { } } -//update tr.screenImage -void RB_CaptureScreenImage(void) -{ +// update tr.screenImage +void RB_CaptureScreenImage(void) { int radX = 2048; int radY = 2048; - int x = glConfig.vidWidth/2; - int y = glConfig.vidHeight/2; + int x = glConfig.vidWidth / 2; + int y = glConfig.vidHeight / 2; int cX, cY; - GL_Bind( tr.screenImage ); - //using this method, we could pixel-filter the texture and all sorts of crazy stuff. - //but, it is slow as hell. + GL_Bind(tr.screenImage); + // using this method, we could pixel-filter the texture and all sorts of crazy stuff. + // but, it is slow as hell. /* static byte *tmp = NULL; if (!tmp) @@ -543,67 +517,54 @@ void RB_CaptureScreenImage(void) qglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 512, 512, 0, GL_RGBA, GL_UNSIGNED_BYTE, tmp); */ - if (radX > glConfig.maxTextureSize) - { + if (radX > glConfig.maxTextureSize) { radX = glConfig.maxTextureSize; } - if (radY > glConfig.maxTextureSize) - { + if (radY > glConfig.maxTextureSize) { radY = glConfig.maxTextureSize; } - while (glConfig.vidWidth < radX) - { + while (glConfig.vidWidth < radX) { radX /= 2; } - while (glConfig.vidHeight < radY) - { + while (glConfig.vidHeight < radY) { radY /= 2; } - cX = x-(radX/2); - cY = y-(radY/2); + cX = x - (radX / 2); + cY = y - (radY / 2); - if (cX+radX > glConfig.vidWidth) - { //would it go off screen? - cX = glConfig.vidWidth-radX; - } - else if (cX < 0) - { //cap it off at 0 + if (cX + radX > glConfig.vidWidth) { // would it go off screen? + cX = glConfig.vidWidth - radX; + } else if (cX < 0) { // cap it off at 0 cX = 0; } - if (cY+radY > glConfig.vidHeight) - { //would it go off screen? - cY = glConfig.vidHeight-radY; - } - else if (cY < 0) - { //cap it off at 0 + if (cY + radY > glConfig.vidHeight) { // would it go off screen? + cY = glConfig.vidHeight - radY; + } else if (cY < 0) { // cap it off at 0 cY = 0; } qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, cX, cY, radX, radY, 0); } -//yeah.. not really shadow-related.. but it's stencil-related. -rww -float tr_distortionAlpha = 1.0f; //opaque -float tr_distortionStretch = 0.0f; //no stretch override -qboolean tr_distortionPrePost = qfalse; //capture before postrender phase? -qboolean tr_distortionNegate = qfalse; //negative blend mode -void RB_DistortionFill(void) -{ +// yeah.. not really shadow-related.. but it's stencil-related. -rww +float tr_distortionAlpha = 1.0f; // opaque +float tr_distortionStretch = 0.0f; // no stretch override +qboolean tr_distortionPrePost = qfalse; // capture before postrender phase? +qboolean tr_distortionNegate = qfalse; // negative blend mode +void RB_DistortionFill(void) { float alpha = tr_distortionAlpha; float spost = 0.0f; float spost2 = 0.0f; - if ( glConfig.stencilBits < 4 ) - { + if (glConfig.stencilBits < 4) { return; } - //ok, cap the stupid thing now I guess - if (!tr_distortionPrePost) - { + // ok, cap the stupid thing now I guess + if (!tr_distortionPrePost) { RB_CaptureScreenImage(); } @@ -611,10 +572,10 @@ void RB_DistortionFill(void) qglStencilFunc(GL_NOTEQUAL, 0, 0xFFFFFFFF); qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); - qglDisable (GL_CLIP_PLANE0); - GL_Cull( CT_TWO_SIDED ); + qglDisable(GL_CLIP_PLANE0); + GL_Cull(CT_TWO_SIDED); - //reset the view matrices and go into ortho mode + // reset the view matrices and go into ortho mode qglMatrixMode(GL_PROJECTION); qglPushMatrix(); qglLoadIdentity(); @@ -623,101 +584,86 @@ void RB_DistortionFill(void) qglPushMatrix(); qglLoadIdentity(); - if (tr_distortionStretch) - { //override + if (tr_distortionStretch) { // override spost = tr_distortionStretch; spost2 = tr_distortionStretch; - } - else - { //do slow stretchy effect - spost = sin(tr.refdef.time*0.0005f); - if (spost < 0.0f) - { + } else { // do slow stretchy effect + spost = sin(tr.refdef.time * 0.0005f); + if (spost < 0.0f) { spost = -spost; } spost *= 0.2f; - spost2 = sin(tr.refdef.time*0.0005f); - if (spost2 < 0.0f) - { + spost2 = sin(tr.refdef.time * 0.0005f); + if (spost2 < 0.0f) { spost2 = -spost2; } spost2 *= 0.08f; } - if (alpha != 1.0f) - { //blend - GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_ALPHA); - } - else - { //be sure to reset the draw state + if (alpha != 1.0f) { // blend + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_SRC_ALPHA); + } else { // be sure to reset the draw state GL_State(0); } qglBegin(GL_QUADS); - qglColor4f(1.0f, 1.0f, 1.0f, alpha); - qglTexCoord2f(0+spost2, 1-spost); - qglVertex2f(0, 0); + qglColor4f(1.0f, 1.0f, 1.0f, alpha); + qglTexCoord2f(0 + spost2, 1 - spost); + qglVertex2f(0, 0); - qglTexCoord2f(0+spost2, 0+spost); - qglVertex2f(0, glConfig.vidHeight); + qglTexCoord2f(0 + spost2, 0 + spost); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 0+spost); - qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); + qglTexCoord2f(1 - spost2, 0 + spost); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 1-spost); - qglVertex2f(glConfig.vidWidth, 0); + qglTexCoord2f(1 - spost2, 1 - spost); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); - if (tr_distortionAlpha == 1.0f && tr_distortionStretch == 0.0f) - { //no overrides - if (tr_distortionNegate) - { //probably the crazy alternate saber trail + if (tr_distortionAlpha == 1.0f && tr_distortionStretch == 0.0f) { // no overrides + if (tr_distortionNegate) { // probably the crazy alternate saber trail alpha = 0.8f; - GL_State(GLS_SRCBLEND_ZERO|GLS_DSTBLEND_ONE_MINUS_SRC_COLOR); - } - else - { + GL_State(GLS_SRCBLEND_ZERO | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR); + } else { alpha = 0.5f; - GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_ALPHA); + GL_State(GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_SRC_ALPHA); } - spost = sin(tr.refdef.time*0.0008f); - if (spost < 0.0f) - { + spost = sin(tr.refdef.time * 0.0008f); + if (spost < 0.0f) { spost = -spost; } spost *= 0.08f; - spost2 = sin(tr.refdef.time*0.0008f); - if (spost2 < 0.0f) - { + spost2 = sin(tr.refdef.time * 0.0008f); + if (spost2 < 0.0f) { spost2 = -spost2; } spost2 *= 0.2f; qglBegin(GL_QUADS); - qglColor4f(1.0f, 1.0f, 1.0f, alpha); - qglTexCoord2f(0+spost2, 1-spost); - qglVertex2f(0, 0); + qglColor4f(1.0f, 1.0f, 1.0f, alpha); + qglTexCoord2f(0 + spost2, 1 - spost); + qglVertex2f(0, 0); - qglTexCoord2f(0+spost2, 0+spost); - qglVertex2f(0, glConfig.vidHeight); + qglTexCoord2f(0 + spost2, 0 + spost); + qglVertex2f(0, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 0+spost); - qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); + qglTexCoord2f(1 - spost2, 0 + spost); + qglVertex2f(glConfig.vidWidth, glConfig.vidHeight); - qglTexCoord2f(1-spost2, 1-spost); - qglVertex2f(glConfig.vidWidth, 0); + qglTexCoord2f(1 - spost2, 1 - spost); + qglVertex2f(glConfig.vidWidth, 0); qglEnd(); } - //pop the view matrices back + // pop the view matrices back qglMatrixMode(GL_PROJECTION); qglPopMatrix(); qglMatrixMode(GL_MODELVIEW); qglPopMatrix(); - qglDisable( GL_STENCIL_TEST ); + qglDisable(GL_STENCIL_TEST); } - diff --git a/codemp/rd-vanilla/tr_skin.cpp b/codemp/rd-vanilla/tr_skin.cpp index 57ff06618c..ae5441388a 100644 --- a/codemp/rd-vanilla/tr_skin.cpp +++ b/codemp/rd-vanilla/tr_skin.cpp @@ -30,8 +30,8 @@ SKINS ============================================================================ */ -static char *CommaParse( char **data_p ); -//can't be dec'd here since we need it for non-dedicated builds now as well. +static char *CommaParse(char **data_p); +// can't be dec'd here since we need it for non-dedicated builds now as well. /* =============== @@ -42,9 +42,8 @@ RE_RegisterSkin bool gServerSkinHack = false; - -shader_t *R_FindServerShader( const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage ); -static char *CommaParse( char **data_p ); +shader_t *R_FindServerShader(const char *name, const int *lightmapIndex, const byte *styles, qboolean mipRawImage); +static char *CommaParse(char **data_p); /* =============== RE_SplitSkins @@ -53,47 +52,42 @@ return= true if three part skins found output= qualified names to three skins if return is true, undefined if false =============== */ -bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) -{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; - if (strchr(INname, '|')) - { +bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) { // INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; + if (strchr(INname, '|')) { char name[MAX_QPATH]; strcpy(name, INname); char *p = strchr(name, '|'); - *p=0; + *p = 0; p++; - //fill in the base path - strcpy (skinhead, name); - strcpy (skintorso, name); - strcpy (skinlower, name); + // fill in the base path + strcpy(skinhead, name); + strcpy(skintorso, name); + strcpy(skinlower, name); - //now get the the individual files + // now get the the individual files - //advance to second + // advance to second char *p2 = strchr(p, '|'); - if (!p2) - { + if (!p2) { return false; } - *p2=0; + *p2 = 0; p2++; - strcat (skinhead, p); - strcat (skinhead, ".skin"); - + strcat(skinhead, p); + strcat(skinhead, ".skin"); - //advance to third + // advance to third p = strchr(p2, '|'); - if (!p) - { + if (!p) { return false; } - *p=0; + *p = 0; p++; - strcat (skintorso,p2); - strcat (skintorso, ".skin"); + strcat(skintorso, p2); + strcat(skintorso, ".skin"); - strcat (skinlower,p); - strcat (skinlower, ".skin"); + strcat(skinlower, p); + strcat(skinlower, ".skin"); return true; } @@ -101,158 +95,148 @@ bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *sk } // given a name, go get the skin we want and return -qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin) -{ - skin_t *skin; - skinSurface_t *surf; - char *text, *text_p; - char *token; - char surfName[MAX_QPATH]; +qhandle_t RE_RegisterIndividualSkin(const char *name, qhandle_t hSkin) { + skin_t *skin; + skinSurface_t *surf; + char *text, *text_p; + char *token; + char surfName[MAX_QPATH]; // load and parse the skin file - ri.FS_ReadFile( name, (void **)&text ); - if ( !text ) { + ri.FS_ReadFile(name, (void **)&text); + if (!text) { #ifndef FINAL_BUILD - ri.Printf( PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name ); + ri.Printf(PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name); #endif return 0; } - assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append + assert(tr.skins[hSkin]); // should already be setup, but might be an 3part append skin = tr.skins[hSkin]; text_p = text; - while ( text_p && *text_p ) { + while (text_p && *text_p) { // get surface name - token = CommaParse( &text_p ); - Q_strncpyz( surfName, token, sizeof( surfName ) ); + token = CommaParse(&text_p); + Q_strncpyz(surfName, token, sizeof(surfName)); - if ( !token[0] ) { + if (!token[0]) { break; } // lowercase the surface name so skin compares are faster - Q_strlwr( surfName ); + Q_strlwr(surfName); - if ( *text_p == ',' ) { + if (*text_p == ',') { text_p++; } - if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one... + if (!strncmp(token, "tag_", 4)) { // these aren't in there, but just in case you load an id style one... continue; } // parse the shader name - token = CommaParse( &text_p ); + token = CommaParse(&text_p); - if ( !strcmp( &surfName[strlen(surfName)-4], "_off") ) - { - if ( !strcmp( token ,"*off" ) ) - { - continue; //don't need these double offs + if (!strcmp(&surfName[strlen(surfName) - 4], "_off")) { + if (!strcmp(token, "*off")) { + continue; // don't need these double offs } - surfName[strlen(surfName)-4] = 0; //remove the "_off" + surfName[strlen(surfName) - 4] = 0; // remove the "_off" } - if ( (unsigned)skin->numSurfaces >= ARRAY_LEN( skin->surfaces ) ) - { - assert( ARRAY_LEN( skin->surfaces ) > (unsigned)skin->numSurfaces ); - ri.Printf( PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int )ARRAY_LEN( skin->surfaces ) ); + if ((unsigned)skin->numSurfaces >= ARRAY_LEN(skin->surfaces)) { + assert(ARRAY_LEN(skin->surfaces) > (unsigned)skin->numSurfaces); + ri.Printf(PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) more than %u surfaces!\n", name, (unsigned int)ARRAY_LEN(skin->surfaces)); break; } - surf = (skinSurface_t *) Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low ); + surf = (skinSurface_t *)Hunk_Alloc(sizeof(*skin->surfaces[0]), h_low); skin->surfaces[skin->numSurfaces] = (_skinSurface_t *)surf; - Q_strncpyz( surf->name, surfName, sizeof( surf->name ) ); + Q_strncpyz(surf->name, surfName, sizeof(surf->name)); - if (gServerSkinHack) surf->shader = R_FindServerShader( token, lightmapsNone, stylesDefault, qtrue ); - else surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue ); + if (gServerSkinHack) + surf->shader = R_FindServerShader(token, lightmapsNone, stylesDefault, qtrue); + else + surf->shader = R_FindShader(token, lightmapsNone, stylesDefault, qtrue); skin->numSurfaces++; } - ri.FS_FreeFile( text ); - + ri.FS_FreeFile(text); // never let a skin have 0 shaders - if ( skin->numSurfaces == 0 ) { - return 0; // use default skin + if (skin->numSurfaces == 0) { + return 0; // use default skin } return hSkin; } -qhandle_t RE_RegisterSkin( const char *name ) { - qhandle_t hSkin; - skin_t *skin; +qhandle_t RE_RegisterSkin(const char *name) { + qhandle_t hSkin; + skin_t *skin; - if ( !name || !name[0] ) { - ri.Printf( PRINT_ALL, "Empty name passed to RE_RegisterSkin\n" ); + if (!name || !name[0]) { + ri.Printf(PRINT_ALL, "Empty name passed to RE_RegisterSkin\n"); return 0; } - if ( strlen( name ) >= MAX_QPATH ) { - ri.Printf( PRINT_ALL, "Skin name exceeds MAX_QPATH\n" ); + if (strlen(name) >= MAX_QPATH) { + ri.Printf(PRINT_ALL, "Skin name exceeds MAX_QPATH\n"); return 0; } // see if the skin is already loaded - for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) { + for (hSkin = 1; hSkin < tr.numSkins; hSkin++) { skin = tr.skins[hSkin]; - if ( !Q_stricmp( skin->name, name ) ) { - if( skin->numSurfaces == 0 ) { - return 0; // default skin + if (!Q_stricmp(skin->name, name)) { + if (skin->numSurfaces == 0) { + return 0; // default skin } return hSkin; } } // allocate a new skin - if ( tr.numSkins == MAX_SKINS ) { - ri.Printf( PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); + if (tr.numSkins == MAX_SKINS) { + ri.Printf(PRINT_ALL, "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name); return 0; } tr.numSkins++; - skin = (struct skin_s *)Hunk_Alloc( sizeof( skin_t ), h_low ); + skin = (struct skin_s *)Hunk_Alloc(sizeof(skin_t), h_low); tr.skins[hSkin] = skin; - Q_strncpyz( skin->name, name, sizeof( skin->name ) ); + Q_strncpyz(skin->name, name, sizeof(skin->name)); skin->numSurfaces = 0; // make sure the render thread is stopped R_IssuePendingRenderCommands(); // If not a .skin file, load as a single shader - if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) { -/* skin->numSurfaces = 1; - skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); - skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); - return hSkin; -*/ + if (strcmp(name + strlen(name) - 5, ".skin")) { + /* skin->numSurfaces = 1; + skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); + skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + return hSkin; + */ } - char skinhead[MAX_QPATH]={0}; - char skintorso[MAX_QPATH]={0}; - char skinlower[MAX_QPATH]={0}; - if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) ) - {//three part + char skinhead[MAX_QPATH] = {0}; + char skintorso[MAX_QPATH] = {0}; + char skinlower[MAX_QPATH] = {0}; + if (RE_SplitSkins(name, (char *)&skinhead, (char *)&skintorso, (char *)&skinlower)) { // three part hSkin = RE_RegisterIndividualSkin(skinhead, hSkin); - if (hSkin && strcmp(skinhead, skintorso)) - { + if (hSkin && strcmp(skinhead, skintorso)) { hSkin = RE_RegisterIndividualSkin(skintorso, hSkin); } - if (hSkin && strcmp(skinhead, skinlower) && strcmp(skintorso, skinlower)) - { + if (hSkin && strcmp(skinhead, skinlower) && strcmp(skintorso, skinlower)) { hSkin = RE_RegisterIndividualSkin(skinlower, hSkin); } - } - else - {//single skin + } else { // single skin hSkin = RE_RegisterIndividualSkin(name, hSkin); } - return(hSkin); + return (hSkin); } - - /* ================== CommaParse @@ -261,76 +245,65 @@ This is unfortunate, but the skin files aren't compatible with our normal parsing rules. ================== */ -static char *CommaParse( char **data_p ) { +static char *CommaParse(char **data_p) { int c = 0, len; char *data; - static char com_token[MAX_TOKEN_CHARS]; + static char com_token[MAX_TOKEN_CHARS]; data = *data_p; len = 0; com_token[0] = 0; // make sure incoming data is valid - if ( !data ) { + if (!data) { *data_p = NULL; return com_token; } - while ( 1 ) { + while (1) { // skip whitespace - while( (c = *(const unsigned char* /*eurofix*/)data) <= ' ') { - if( !c ) { + while ((c = *(const unsigned char * /*eurofix*/)data) <= ' ') { + if (!c) { break; } data++; } - c = *data; // skip double slash comments - if ( c == '/' && data[1] == '/' ) - { + if (c == '/' && data[1] == '/') { while (*data && *data != '\n') data++; } // skip /* */ comments - else if ( c=='/' && data[1] == '*' ) - { - while ( *data && ( *data != '*' || data[1] != '/' ) ) - { + else if (c == '/' && data[1] == '*') { + while (*data && (*data != '*' || data[1] != '/')) { data++; } - if ( *data ) - { + if (*data) { data += 2; } - } - else - { + } else { break; } } - if ( c == 0 ) { + if (c == 0) { return ""; } // handle quoted strings - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } - if (len < MAX_TOKEN_CHARS - 1) - { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } @@ -338,20 +311,18 @@ static char *CommaParse( char **data_p ) { } // parse a regular word - do - { - if (len < MAX_TOKEN_CHARS - 1) - { + do { + if (len < MAX_TOKEN_CHARS - 1) { com_token[len] = c; len++; } data++; c = *data; - } while (c>32 && c != ',' ); + } while (c > 32 && c != ','); com_token[len] = 0; - *data_p = ( char * ) data; + *data_p = (char *)data; return com_token; } @@ -362,13 +333,11 @@ RE_RegisterServerSkin Mangled version of the above function to load .skin files on the server. =============== */ -qhandle_t RE_RegisterServerSkin( const char *name ) { +qhandle_t RE_RegisterServerSkin(const char *name) { qhandle_t r; - if (ri.Cvar_VariableIntegerValue( "cl_running" ) && - ri.Com_TheHunkMarkHasBeenMade() && - ShaderHashTableExists()) - { //If the client is running then we can go straight into the normal registerskin func + if (ri.Cvar_VariableIntegerValue("cl_running") && ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) { // If the client is running then we can go straight into the normal registerskin func return RE_RegisterSkin(name); } @@ -384,16 +353,16 @@ qhandle_t RE_RegisterServerSkin( const char *name ) { R_InitSkins =============== */ -void R_InitSkins( void ) { - skin_t *skin; +void R_InitSkins(void) { + skin_t *skin; tr.numSkins = 1; // make the default skin have all default shaders - skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc( sizeof( skin_t ), h_low ); - Q_strncpyz( skin->name, "", sizeof( skin->name ) ); + skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc(sizeof(skin_t), h_low); + Q_strncpyz(skin->name, "", sizeof(skin->name)); skin->numSurfaces = 1; - skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc( sizeof( skinSurface_t ), h_low ); + skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc(sizeof(skinSurface_t), h_low); skin->surfaces[0]->shader = tr.defaultShader; } @@ -402,11 +371,11 @@ void R_InitSkins( void ) { R_GetSkinByHandle =============== */ -skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { - if ( hSkin < 1 || hSkin >= tr.numSkins ) { +skin_t *R_GetSkinByHandle(qhandle_t hSkin) { + if (hSkin < 1 || hSkin >= tr.numSkins) { return tr.skins[0]; } - return tr.skins[ hSkin ]; + return tr.skins[hSkin]; } /* @@ -414,20 +383,19 @@ skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { R_SkinList_f =============== */ -void R_SkinList_f( void ) { - int i, j; - skin_t *skin; +void R_SkinList_f(void) { + int i, j; + skin_t *skin; - ri.Printf( PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "------------------\n"); - for ( i = 0 ; i < tr.numSkins ; i++ ) { + for (i = 0; i < tr.numSkins; i++) { skin = tr.skins[i]; - ri.Printf( PRINT_ALL, "%3i:%s\n", i, skin->name ); - for ( j = 0 ; j < skin->numSurfaces ; j++ ) { - ri.Printf( PRINT_ALL, " %s = %s\n", - skin->surfaces[j]->name, ((shader_t* )skin->surfaces[j]->shader)->name ); + ri.Printf(PRINT_ALL, "%3i:%s\n", i, skin->name); + for (j = 0; j < skin->numSurfaces; j++) { + ri.Printf(PRINT_ALL, " %s = %s\n", skin->surfaces[j]->name, ((shader_t *)skin->surfaces[j]->shader)->name); } } - ri.Printf( PRINT_ALL, "------------------\n"); + ri.Printf(PRINT_ALL, "------------------\n"); } diff --git a/codemp/rd-vanilla/tr_sky.cpp b/codemp/rd-vanilla/tr_sky.cpp index 77ee0aba0c..aaa190c44f 100644 --- a/codemp/rd-vanilla/tr_sky.cpp +++ b/codemp/rd-vanilla/tr_sky.cpp @@ -24,11 +24,11 @@ along with this program; if not, see . // tr_sky.c #include "tr_local.h" -#define SKY_SUBDIVISIONS 8 -#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS/2) +#define SKY_SUBDIVISIONS 8 +#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS / 2) -static float s_cloudTexCoords[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; -static float s_cloudTexP[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; +static float s_cloudTexCoords[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; +static float s_cloudTexP[6][SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; extern bool g_bRenderGlowingObjects; @@ -40,72 +40,56 @@ POLYGON TO BOX SIDE PROJECTION =================================================================================== */ -static vec3_t sky_clip[6] = -{ - {1,1,0}, - {1,-1,0}, - {0,-1,1}, - {0,1,1}, - {1,0,1}, - {-1,0,1} -}; +static vec3_t sky_clip[6] = {{1, 1, 0}, {1, -1, 0}, {0, -1, 1}, {0, 1, 1}, {1, 0, 1}, {-1, 0, 1}}; -static float sky_mins[2][6], sky_maxs[2][6]; -static float sky_min, sky_max; +static float sky_mins[2][6], sky_maxs[2][6]; +static float sky_min, sky_max; /* ================ AddSkyPolygon ================ */ -static void AddSkyPolygon (int nump, vec3_t vecs) -{ - int i,j; - vec3_t v, av; - float s, t, dv; - int axis; - float *vp; +static void AddSkyPolygon(int nump, vec3_t vecs) { + int i, j; + vec3_t v, av; + float s, t, dv; + int axis; + float *vp; // s = [0]/[2], t = [1]/[2] - static int floato_st[6][3] = - { - {-2,3,1}, - {2,3,-1}, + static int floato_st[6][3] = { + {-2, 3, 1}, + {2, 3, -1}, - {1,3,2}, - {-1,3,-2}, + {1, 3, 2}, + {-1, 3, -2}, - {-2,-1,3}, - {-2,1,-3} + {-2, -1, 3}, + {-2, 1, -3} - // {-1,2,3}, - // {1,2,-3} + // {-1,2,3}, + // {1,2,-3} }; // decide which face it maps to - VectorCopy (vec3_origin, v); - for (i=0, vp=vecs ; i av[1] && av[0] > av[2]) - { + if (av[0] > av[1] && av[0] > av[2]) { if (v[0] < 0) axis = 1; else axis = 0; - } - else if (av[1] > av[2] && av[1] > av[0]) - { + } else if (av[1] > av[2] && av[1] > av[0]) { if (v[1] < 0) axis = 3; else axis = 2; - } - else - { + } else { if (v[2] < 0) axis = 5; else @@ -113,25 +97,24 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } // project new texture coords - for (i=0 ; i 0) dv = vecs[j - 1]; else dv = -vecs[-j - 1]; if (dv < 0.001) - continue; // don't divide by zero + continue; // don't divide by zero j = floato_st[axis][0]; if (j < 0) - s = -vecs[-j -1] / dv; + s = -vecs[-j - 1] / dv; else - s = vecs[j-1] / dv; + s = vecs[j - 1] / dv; j = floato_st[axis][1]; if (j < 0) - t = -vecs[-j -1] / dv; + t = -vecs[-j - 1] / dv; else - t = vecs[j-1] / dv; + t = vecs[j - 1] / dv; if (s < sky_mins[0][axis]) sky_mins[0][axis] = s; @@ -144,92 +127,81 @@ static void AddSkyPolygon (int nump, vec3_t vecs) } } -#define ON_EPSILON 0.1f // point on plane side epsilon -#define MAX_CLIP_VERTS 64 +#define ON_EPSILON 0.1f // point on plane side epsilon +#define MAX_CLIP_VERTS 64 /* ================ ClipSkyPolygon ================ */ -static void ClipSkyPolygon (int nump, vec3_t vecs, int stage) -{ - float *norm; - float *v; - qboolean front, back; - float d, e; - float dists[MAX_CLIP_VERTS]; - int sides[MAX_CLIP_VERTS]; - vec3_t newv[2][MAX_CLIP_VERTS]; - int newc[2]; - int i, j; - - if (nump > MAX_CLIP_VERTS-2) - Com_Error (ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); - if (stage == 6) - { // fully clipped, so draw it - AddSkyPolygon (nump, vecs); +static void ClipSkyPolygon(int nump, vec3_t vecs, int stage) { + float *norm; + float *v; + qboolean front, back; + float d, e; + float dists[MAX_CLIP_VERTS]; + int sides[MAX_CLIP_VERTS]; + vec3_t newv[2][MAX_CLIP_VERTS]; + int newc[2]; + int i, j; + + if (nump > MAX_CLIP_VERTS - 2) + Com_Error(ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); + if (stage == 6) { // fully clipped, so draw it + AddSkyPolygon(nump, vecs); return; } front = back = qfalse; norm = sky_clip[stage]; - for (i=0, v = vecs ; i ON_EPSILON) - { + for (i = 0, v = vecs; i < nump; i++, v += 3) { + d = DotProduct(v, norm); + if (d > ON_EPSILON) { front = qtrue; sides[i] = SIDE_FRONT; - } - else if (d < -ON_EPSILON) - { + } else if (d < -ON_EPSILON) { back = qtrue; sides[i] = SIDE_BACK; - } - else + } else sides[i] = SIDE_ON; dists[i] = d; } - if (!front || !back) - { // not clipped - ClipSkyPolygon (nump, vecs, stage+1); + if (!front || !back) { // not clipped + ClipSkyPolygon(nump, vecs, stage + 1); return; } // clip it sides[i] = sides[0]; dists[i] = dists[0]; - VectorCopy (vecs, (vecs+(i*3)) ); + VectorCopy(vecs, (vecs + (i * 3))); newc[0] = newc[1] = 0; - for (i=0, v = vecs ; inumIndexes; i += 3 ) - { - for (j = 0 ; j < 3 ; j++) - { - VectorSubtract( input->xyz[input->indexes[i+j]], - backEnd.viewParms.ori.origin, - p[j] ); + for (i = 0; i < input->numIndexes; i += 3) { + for (j = 0; j < 3; j++) { + VectorSubtract(input->xyz[input->indexes[i + j]], backEnd.viewParms.ori.origin, p[j]); } - ClipSkyPolygon( 3, p[0], 0 ); + ClipSkyPolygon(3, p[0], 0); } } @@ -293,123 +260,99 @@ CLOUD VERTEX GENERATION ** ** Parms: s, t range from -1 to 1 */ -static void MakeSkyVec( float s, float t, int axis, float outSt[2], vec3_t outXYZ ) -{ +static void MakeSkyVec(float s, float t, int axis, float outSt[2], vec3_t outXYZ) { // 1 = s, 2 = t, 3 = 2048 - static int st_to_vec[6][3] = - { - {3,-1,2}, - {-3,1,2}, + static int st_to_vec[6][3] = { + {3, -1, 2}, {-3, 1, 2}, - {1,3,2}, - {-1,-3,2}, + {1, 3, 2}, {-1, -3, 2}, - {-2,-1,3}, // 0 degrees yaw, look straight up - {2,-1,-3} // look straight down + {-2, -1, 3}, // 0 degrees yaw, look straight up + {2, -1, -3} // look straight down }; - vec3_t b; - int j, k; - float boxSize; + vec3_t b; + int j, k; + float boxSize; - boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) - b[0] = s*boxSize; - b[1] = t*boxSize; + boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + b[0] = s * boxSize; + b[1] = t * boxSize; b[2] = boxSize; - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { k = st_to_vec[axis][j]; - if (k < 0) - { + if (k < 0) { outXYZ[j] = -b[-k - 1]; - } - else - { + } else { outXYZ[j] = b[k - 1]; } } // avoid bilerp seam - s = (s+1)*0.5; - t = (t+1)*0.5; - if (s < sky_min) - { + s = (s + 1) * 0.5; + t = (t + 1) * 0.5; + if (s < sky_min) { s = sky_min; - } - else if (s > sky_max) - { + } else if (s > sky_max) { s = sky_max; } - if (t < sky_min) - { + if (t < sky_min) { t = sky_min; - } - else if (t > sky_max) - { + } else if (t > sky_max) { t = sky_max; } t = 1.0 - t; - - if ( outSt ) - { + if (outSt) { outSt[0] = s; outSt[1] = t; } } -static vec3_t s_skyPoints[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; -static float s_skyTexCoords[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; +static vec3_t s_skyPoints[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1]; +static float s_skyTexCoords[SKY_SUBDIVISIONS + 1][SKY_SUBDIVISIONS + 1][2]; -static void DrawSkySide( struct image_s *image, const int mins[2], const int maxs[2] ) -{ +static void DrawSkySide(struct image_s *image, const int mins[2], const int maxs[2]) { int s, t; - GL_Bind( image ); + GL_Bind(image); + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t < maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + qglBegin(GL_TRIANGLE_STRIP); - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t < maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - qglBegin( GL_TRIANGLE_STRIP ); + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { + qglTexCoord2fv(s_skyTexCoords[t][s]); + qglVertex3fv(s_skyPoints[t][s]); - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - qglTexCoord2fv( s_skyTexCoords[t][s] ); - qglVertex3fv( s_skyPoints[t][s] ); - - qglTexCoord2fv( s_skyTexCoords[t+1][s] ); - qglVertex3fv( s_skyPoints[t+1][s] ); + qglTexCoord2fv(s_skyTexCoords[t + 1][s]); + qglVertex3fv(s_skyPoints[t + 1][s]); } qglEnd(); } } -static void DrawSkyBox( shader_t *shader ) -{ - int i; +static void DrawSkyBox(shader_t *shader) { + int i; sky_min = 0; sky_max = 1; - memset( s_skyTexCoords, 0, sizeof( s_skyTexCoords ) ); + memset(s_skyTexCoords, 0, sizeof(s_skyTexCoords)); - for (i=0 ; i<6 ; i++) - { + for (i = 0; i < 6; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } @@ -418,48 +361,39 @@ static void DrawSkyBox( shader_t *shader ) sky_maxs_subd[0] = sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS; sky_maxs_subd[1] = sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - s_skyTexCoords[t][s], - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, + s_skyTexCoords[t][s], s_skyPoints[t][s]); } } - DrawSkySide( shader->sky->outerbox[i], - sky_mins_subd, - sky_maxs_subd ); + DrawSkySide(shader->sky->outerbox[i], sky_mins_subd, sky_maxs_subd); } - } -static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean addIndexes ) -{ +static void FillCloudySkySide(const int mins[2], const int maxs[2], qboolean addIndexes) { int s, t; int vertexStart = tess.numVertexes; int tHeight, sWidth; @@ -467,69 +401,59 @@ static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean ad tHeight = maxs[1] - mins[1] + 1; sWidth = maxs[0] - mins[0] + 1; - for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - VectorAdd( s_skyPoints[t][s], backEnd.viewParms.ori.origin, tess.xyz[tess.numVertexes] ); + for (t = mins[1] + HALF_SKY_SUBDIVISIONS; t <= maxs[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = mins[0] + HALF_SKY_SUBDIVISIONS; s <= maxs[0] + HALF_SKY_SUBDIVISIONS; s++) { + VectorAdd(s_skyPoints[t][s], backEnd.viewParms.ori.origin, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0]; tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1]; tess.numVertexes++; - if ( tess.numVertexes >= SHADER_MAX_VERTEXES ) - { - Com_Error( ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()\n" ); + if (tess.numVertexes >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()\n"); } } } // only add indexes for one pass, otherwise it would draw multiple times for each pass - if ( addIndexes ) { - for ( t = 0; t < tHeight-1; t++ ) - { - for ( s = 0; s < sWidth-1; s++ ) - { - tess.indexes[tess.numIndexes] = vertexStart + s + t * ( sWidth ); + if (addIndexes) { + for (t = 0; t < tHeight - 1; t++) { + for (s = 0; s < sWidth - 1; s++) { + tess.indexes[tess.numIndexes] = vertexStart + s + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + ( t + 1 ) * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + (t + 1) * (sWidth); tess.numIndexes++; - tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * (sWidth); tess.numIndexes++; } } } } -static void FillCloudBox( const shader_t *shader, int stage ) -{ +static void FillCloudBox(const shader_t *shader, int stage) { int i; - for ( i =0; i < 6; i++ ) - { + for (i = 0; i < 6; i++) { int sky_mins_subd[2], sky_maxs_subd[2]; int s, t; float MIN_T; - if ( 1 ) // FIXME? shader->sky->fullClouds ) + if (1) // FIXME? shader->sky->fullClouds ) { MIN_T = -HALF_SKY_SUBDIVISIONS; // still don't want to draw the bottom, even if fullClouds - if ( i == 5 ) + if (i == 5) continue; - } - else - { - switch( i ) - { + } else { + switch (i) { case 0: case 1: case 2: @@ -539,59 +463,52 @@ static void FillCloudBox( const shader_t *shader, int stage ) case 5: // don't draw clouds beneath you continue; - case 4: // top + case 4: // top default: MIN_T = -HALF_SKY_SUBDIVISIONS; break; } } - sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; - sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[0][i] = floor(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS) / HALF_SKY_SUBDIVISIONS; - if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || - ( sky_mins[1][i] >= sky_maxs[1][i] ) ) - { + if ((sky_mins[0][i] >= sky_maxs[0][i]) || (sky_mins[1][i] >= sky_maxs[1][i])) { continue; } - sky_mins_subd[0] = Q_ftol( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ); - sky_mins_subd[1] = Q_ftol( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ); - sky_maxs_subd[0] = Q_ftol( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ); - sky_maxs_subd[1] = Q_ftol( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ); + sky_mins_subd[0] = Q_ftol(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS); + sky_mins_subd[1] = Q_ftol(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[0] = Q_ftol(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[1] = Q_ftol(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS); - if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_mins_subd[1] < MIN_T ) + if (sky_mins_subd[1] < MIN_T) sky_mins_subd[1] = MIN_T; - else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS) sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + if (sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; - else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; - if ( sky_maxs_subd[1] < MIN_T ) + if (sky_maxs_subd[1] < MIN_T) sky_maxs_subd[1] = MIN_T; - else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + else if (sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS) sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; // // iterate through the subdivisions // - for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) - { - for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) - { - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - s_skyPoints[t][s] ); + for (t = sky_mins_subd[1] + HALF_SKY_SUBDIVISIONS; t <= sky_maxs_subd[1] + HALF_SKY_SUBDIVISIONS; t++) { + for (s = sky_mins_subd[0] + HALF_SKY_SUBDIVISIONS; s <= sky_maxs_subd[0] + HALF_SKY_SUBDIVISIONS; s++) { + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + s_skyPoints[t][s]); s_skyTexCoords[t][s][0] = s_cloudTexCoords[i][t][s][0]; s_skyTexCoords[t][s][1] = s_cloudTexCoords[i][t][s][1]; @@ -599,28 +516,28 @@ static void FillCloudBox( const shader_t *shader, int stage ) } // only add indexes for first stage - FillCloudySkySide( sky_mins_subd, sky_maxs_subd, (qboolean)( stage == 0 ) ); + FillCloudySkySide(sky_mins_subd, sky_maxs_subd, (qboolean)(stage == 0)); } } /* ** R_BuildCloudData */ -void R_BuildCloudData( shaderCommands_t *input ) { +void R_BuildCloudData(shaderCommands_t *input) { int i; - assert( input->shader->sky ); + assert(input->shader->sky); - sky_min = 1.0 / 256.0f; // FIXME: not correct? + sky_min = 1.0 / 256.0f; // FIXME: not correct? sky_max = 255.0 / 256.0f; // set up for drawing tess.numIndexes = 0; tess.numVertexes = 0; - if ( input->shader->sky->cloudHeight ) { - for ( i=0; ishader->numUnfoggedPasses; i++ ) - FillCloudBox( input->shader, i ); + if (input->shader->sky->cloudHeight) { + for (i = 0; i < input->shader->numUnfoggedPasses; i++) + FillCloudBox(input->shader, i); } } @@ -628,9 +545,8 @@ void R_BuildCloudData( shaderCommands_t *input ) { ** R_InitSkyTexCoords ** Called when a sky shader is parsed */ -#define SQR( a ) ((a)*(a)) -void R_InitSkyTexCoords( float heightCloud ) -{ +#define SQR(a) ((a) * (a)) +void R_InitSkyTexCoords(float heightCloud) { int i, s, t; float radiusWorld = 4096; float p; @@ -642,41 +558,31 @@ void R_InitSkyTexCoords( float heightCloud ) // a world hasn't been bounded backEnd.viewParms.zFar = 1024; - for ( i = 0; i < 6; i++ ) - { - for ( t = 0; t <= SKY_SUBDIVISIONS; t++ ) - { - for ( s = 0; s <= SKY_SUBDIVISIONS; s++ ) - { + for (i = 0; i < 6; i++) { + for (t = 0; t <= SKY_SUBDIVISIONS; t++) { + for (s = 0; s <= SKY_SUBDIVISIONS; s++) { // compute vector from view origin to sky side integral point - MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, - i, - NULL, - skyVec ); + MakeSkyVec((s - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, (t - HALF_SKY_SUBDIVISIONS) / (float)HALF_SKY_SUBDIVISIONS, i, NULL, + skyVec); // compute parametric value 'p' that intersects with cloud layer - p = ( 1.0f / ( 2 * DotProduct( skyVec, skyVec ) ) ) * - ( -2 * skyVec[2] * radiusWorld + - 2 * sqrt( SQR( skyVec[2] ) * SQR( radiusWorld ) + - 2 * SQR( skyVec[0] ) * radiusWorld * heightCloud + - SQR( skyVec[0] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[1] ) * radiusWorld * heightCloud + - SQR( skyVec[1] ) * SQR( heightCloud ) + - 2 * SQR( skyVec[2] ) * radiusWorld * heightCloud + - SQR( skyVec[2] ) * SQR( heightCloud ) ) ); + p = (1.0f / (2 * DotProduct(skyVec, skyVec))) * + (-2 * skyVec[2] * radiusWorld + + 2 * sqrt(SQR(skyVec[2]) * SQR(radiusWorld) + 2 * SQR(skyVec[0]) * radiusWorld * heightCloud + SQR(skyVec[0]) * SQR(heightCloud) + + 2 * SQR(skyVec[1]) * radiusWorld * heightCloud + SQR(skyVec[1]) * SQR(heightCloud) + + 2 * SQR(skyVec[2]) * radiusWorld * heightCloud + SQR(skyVec[2]) * SQR(heightCloud))); s_cloudTexP[i][t][s] = p; // compute intersection point based on p - VectorScale( skyVec, p, v ); + VectorScale(skyVec, p, v); v[2] += radiusWorld; // compute vector from world origin to intersection point 'v' - VectorNormalize( v ); + VectorNormalize(v); - sRad = Q_acos( v[0] ); - tRad = Q_acos( v[1] ); + sRad = Q_acos(v[0]); + tRad = Q_acos(v[1]); s_cloudTexCoords[i][t][s][0] = sRad; s_cloudTexCoords[i][t][s][1] = tRad; @@ -690,96 +596,93 @@ void R_InitSkyTexCoords( float heightCloud ) /* ** RB_DrawSun */ -void RB_DrawSun( void ) { - float size; - float dist; - vec3_t origin, vec1, vec2; - vec3_t temp; +void RB_DrawSun(void) { + float size; + float dist; + vec3_t origin, vec1, vec2; + vec3_t temp; - if ( !backEnd.skyRenderedThisView ) { + if (!backEnd.skyRenderedThisView) { return; } - if ( !r_drawSun->integer ) { + if (!r_drawSun->integer) { return; } - qglLoadMatrixf( backEnd.viewParms.world.modelMatrix ); - qglTranslatef (backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); + qglLoadMatrixf(backEnd.viewParms.world.modelMatrix); + qglTranslatef(backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); - dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) size = dist * 0.4; - VectorScale( tr.sunDirection, dist, origin ); - PerpendicularVector( vec1, tr.sunDirection ); - CrossProduct( tr.sunDirection, vec1, vec2 ); + VectorScale(tr.sunDirection, dist, origin); + PerpendicularVector(vec1, tr.sunDirection); + CrossProduct(tr.sunDirection, vec1, vec2); - VectorScale( vec1, size, vec1 ); - VectorScale( vec2, size, vec2 ); + VectorScale(vec1, size, vec1); + VectorScale(vec2, size, vec2); // farthest depth range - qglDepthRange( 1.0, 1.0 ); + qglDepthRange(1.0, 1.0); // FIXME: use quad stamp - RB_BeginSurface( tr.sunShader, tess.fogNum ); - VectorCopy( origin, temp ); - VectorSubtract( temp, vec1, temp ); - VectorSubtract( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorAdd( temp, vec1, temp ); - VectorSubtract( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorAdd( temp, vec1, temp ); - VectorAdd( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1; - tess.texCoords[tess.numVertexes][0][1] = 1; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - VectorCopy( origin, temp ); - VectorSubtract( temp, vec1, temp ); - VectorAdd( temp, vec2, temp ); - VectorCopy( temp, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1; - tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = 255; - tess.vertexColors[tess.numVertexes][1] = 255; - tess.vertexColors[tess.numVertexes][2] = 255; - tess.numVertexes++; - - tess.indexes[tess.numIndexes++] = 0; - tess.indexes[tess.numIndexes++] = 1; - tess.indexes[tess.numIndexes++] = 2; - tess.indexes[tess.numIndexes++] = 0; - tess.indexes[tess.numIndexes++] = 2; - tess.indexes[tess.numIndexes++] = 3; + RB_BeginSurface(tr.sunShader, tess.fogNum); + VectorCopy(origin, temp); + VectorSubtract(temp, vec1, temp); + VectorSubtract(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 0; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorAdd(temp, vec1, temp); + VectorSubtract(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 1; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorAdd(temp, vec1, temp); + VectorAdd(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = 1; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + VectorCopy(origin, temp); + VectorSubtract(temp, vec1, temp); + VectorAdd(temp, vec2, temp); + VectorCopy(temp, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = 0; + tess.vertexColors[tess.numVertexes][0] = 255; + tess.vertexColors[tess.numVertexes][1] = 255; + tess.vertexColors[tess.numVertexes][2] = 255; + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 1; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 3; RB_EndSurface(); // back to normal depth range - qglDepthRange( 0.0, 1.0 ); + qglDepthRange(0.0, 1.0); } - - - /* ================ RB_StageIteratorSky @@ -789,63 +692,58 @@ All of the visible sky triangles are in tess Other things could be stuck in here, like birds in the sky, etc ================ */ -void RB_StageIteratorSky( void ) -{ - if ( g_bRenderGlowingObjects ) +void RB_StageIteratorSky(void) { + if (g_bRenderGlowingObjects) return; - if ( r_fastsky->integer ) { + if (r_fastsky->integer) { return; } - if (skyboxportal && !(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) - { + if (skyboxportal && !(backEnd.refdef.rdflags & RDF_SKYBOXPORTAL)) { return; } // go through all the polygons and project them onto // the sky box to see which blocks on each side need // to be drawn - RB_ClipSkyPolygons( &tess ); + RB_ClipSkyPolygons(&tess); // r_showsky will let all the sky blocks be drawn in // front of everything to allow developers to see how // much sky is getting sucked in - if ( r_showsky->integer ) { - qglDepthRange( 0.0, 0.0 ); + if (r_showsky->integer) { + qglDepthRange(0.0, 0.0); } else { - qglDepthRange( 1.0, 1.0 ); + qglDepthRange(1.0, 1.0); } // draw the outer skybox - if ( tess.shader->sky->outerbox[0] && tess.shader->sky->outerbox[0] != tr.defaultImage ) { - qglColor3f( tr.identityLight, tr.identityLight, tr.identityLight ); + if (tess.shader->sky->outerbox[0] && tess.shader->sky->outerbox[0] != tr.defaultImage) { + qglColor3f(tr.identityLight, tr.identityLight, tr.identityLight); - qglPushMatrix (); - GL_State( 0 ); - qglTranslatef (backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); + qglPushMatrix(); + GL_State(0); + qglTranslatef(backEnd.viewParms.ori.origin[0], backEnd.viewParms.ori.origin[1], backEnd.viewParms.ori.origin[2]); - DrawSkyBox( tess.shader ); + DrawSkyBox(tess.shader); qglPopMatrix(); } // generate the vertexes for all the clouds, which will be drawn // by the generic shader routine - R_BuildCloudData( &tess ); + R_BuildCloudData(&tess); - if (tess.numIndexes && tess.numVertexes) - { + if (tess.numIndexes && tess.numVertexes) { RB_StageIteratorGeneric(); } // draw the inner skybox - // back to normal depth range - qglDepthRange( 0.0, 1.0 ); + qglDepthRange(0.0, 1.0); // note that sky was drawn so we will draw a sun later backEnd.skyRenderedThisView = qtrue; } - diff --git a/codemp/rd-vanilla/tr_subs.cpp b/codemp/rd-vanilla/tr_subs.cpp index 1f6d1dbc3e..3878e897f3 100644 --- a/codemp/rd-vanilla/tr_subs.cpp +++ b/codemp/rd-vanilla/tr_subs.cpp @@ -24,10 +24,9 @@ along with this program; if not, see . // tr_subs.cpp - common function replacements for modular renderer #include "tr_local.h" -void QDECL Com_Printf( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Printf(const char *msg, ...) { + va_list argptr; + char text[1024]; va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); @@ -36,10 +35,9 @@ void QDECL Com_Printf( const char *msg, ... ) ri.Printf(PRINT_ALL, "%s", text); } -void QDECL Com_OPrintf( const char *msg, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_OPrintf(const char *msg, ...) { + va_list argptr; + char text[1024]; va_start(argptr, msg); Q_vsnprintf(text, sizeof(text), msg, argptr); @@ -48,10 +46,9 @@ void QDECL Com_OPrintf( const char *msg, ... ) ri.OPrintf("%s", text); } -void QDECL Com_Error( int level, const char *error, ... ) -{ - va_list argptr; - char text[1024]; +void QDECL Com_Error(int level, const char *error, ...) { + va_list argptr; + char text[1024]; va_start(argptr, error); Q_vsnprintf(text, sizeof(text), error, argptr); @@ -61,35 +58,19 @@ void QDECL Com_Error( int level, const char *error, ... ) } // HUNK -void *Hunk_AllocateTempMemory( int size ) { - return ri.Hunk_AllocateTempMemory( size ); -} +void *Hunk_AllocateTempMemory(int size) { return ri.Hunk_AllocateTempMemory(size); } -void Hunk_FreeTempMemory( void *buf ) { - ri.Hunk_FreeTempMemory( buf ); -} +void Hunk_FreeTempMemory(void *buf) { ri.Hunk_FreeTempMemory(buf); } -void *Hunk_Alloc( int size, ha_pref preference ) { - return ri.Hunk_Alloc( size, preference ); -} +void *Hunk_Alloc(int size, ha_pref preference) { return ri.Hunk_Alloc(size, preference); } -int Hunk_MemoryRemaining( void ) { - return ri.Hunk_MemoryRemaining(); -} +int Hunk_MemoryRemaining(void) { return ri.Hunk_MemoryRemaining(); } // ZONE -void *Z_Malloc( int iSize, memtag_t eTag, qboolean bZeroit, int iAlign ) { - return ri.Z_Malloc( iSize, eTag, bZeroit, iAlign ); -} +void *Z_Malloc(int iSize, memtag_t eTag, qboolean bZeroit, int iAlign) { return ri.Z_Malloc(iSize, eTag, bZeroit, iAlign); } -void Z_Free( void *ptr ) { - ri.Z_Free( ptr ); -} +void Z_Free(void *ptr) { ri.Z_Free(ptr); } -int Z_MemSize( memtag_t eTag ) { - return ri.Z_MemSize( eTag ); -} +int Z_MemSize(memtag_t eTag) { return ri.Z_MemSize(eTag); } -void Z_MorphMallocTag( void *pvBuffer, memtag_t eDesiredTag ) { - ri.Z_MorphMallocTag( pvBuffer, eDesiredTag ); -} +void Z_MorphMallocTag(void *pvBuffer, memtag_t eDesiredTag) { ri.Z_MorphMallocTag(pvBuffer, eDesiredTag); } diff --git a/codemp/rd-vanilla/tr_surface.cpp b/codemp/rd-vanilla/tr_surface.cpp index 3be021dce6..e29bf95838 100644 --- a/codemp/rd-vanilla/tr_surface.cpp +++ b/codemp/rd-vanilla/tr_surface.cpp @@ -38,92 +38,87 @@ It is safe to actually issue drawing commands here if you don't want to use the shader system. */ - //============================================================================ - /* ============== RB_CheckOverflow ============== */ -void RB_CheckOverflow( int verts, int indexes ) { - if (tess.numVertexes + verts < SHADER_MAX_VERTEXES - && tess.numIndexes + indexes < SHADER_MAX_INDEXES) { +void RB_CheckOverflow(int verts, int indexes) { + if (tess.numVertexes + verts < SHADER_MAX_VERTEXES && tess.numIndexes + indexes < SHADER_MAX_INDEXES) { return; } RB_EndSurface(); - if ( verts >= SHADER_MAX_VERTEXES ) { - Com_Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES ); + if (verts >= SHADER_MAX_VERTEXES) { + Com_Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES); } - if ( indexes >= SHADER_MAX_INDEXES ) { - Com_Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES ); + if (indexes >= SHADER_MAX_INDEXES) { + Com_Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES); } - RB_BeginSurface(tess.shader, tess.fogNum ); + RB_BeginSurface(tess.shader, tess.fogNum); } - /* ============== RB_AddQuadStampExt ============== */ -void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2 ) { - vec3_t normal; - int ndx; +void RB_AddQuadStampExt(vec3_t origin, vec3_t left, vec3_t up, byte *color, float s1, float t1, float s2, float t2) { + vec3_t normal; + int ndx; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); ndx = tess.numVertexes; // triangle indexes for a simple quad - tess.indexes[ tess.numIndexes ] = ndx; - tess.indexes[ tess.numIndexes + 1 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 2 ] = ndx + 3; + tess.indexes[tess.numIndexes] = ndx; + tess.indexes[tess.numIndexes + 1] = ndx + 1; + tess.indexes[tess.numIndexes + 2] = ndx + 3; - tess.indexes[ tess.numIndexes + 3 ] = ndx + 3; - tess.indexes[ tess.numIndexes + 4 ] = ndx + 1; - tess.indexes[ tess.numIndexes + 5 ] = ndx + 2; + tess.indexes[tess.numIndexes + 3] = ndx + 3; + tess.indexes[tess.numIndexes + 4] = ndx + 1; + tess.indexes[tess.numIndexes + 5] = ndx + 2; tess.xyz[ndx][0] = origin[0] + left[0] + up[0]; tess.xyz[ndx][1] = origin[1] + left[1] + up[1]; tess.xyz[ndx][2] = origin[2] + left[2] + up[2]; - tess.xyz[ndx+1][0] = origin[0] - left[0] + up[0]; - tess.xyz[ndx+1][1] = origin[1] - left[1] + up[1]; - tess.xyz[ndx+1][2] = origin[2] - left[2] + up[2]; + tess.xyz[ndx + 1][0] = origin[0] - left[0] + up[0]; + tess.xyz[ndx + 1][1] = origin[1] - left[1] + up[1]; + tess.xyz[ndx + 1][2] = origin[2] - left[2] + up[2]; - tess.xyz[ndx+2][0] = origin[0] - left[0] - up[0]; - tess.xyz[ndx+2][1] = origin[1] - left[1] - up[1]; - tess.xyz[ndx+2][2] = origin[2] - left[2] - up[2]; - - tess.xyz[ndx+3][0] = origin[0] + left[0] - up[0]; - tess.xyz[ndx+3][1] = origin[1] + left[1] - up[1]; - tess.xyz[ndx+3][2] = origin[2] + left[2] - up[2]; + tess.xyz[ndx + 2][0] = origin[0] - left[0] - up[0]; + tess.xyz[ndx + 2][1] = origin[1] - left[1] - up[1]; + tess.xyz[ndx + 2][2] = origin[2] - left[2] - up[2]; + tess.xyz[ndx + 3][0] = origin[0] + left[0] - up[0]; + tess.xyz[ndx + 3][1] = origin[1] + left[1] - up[1]; + tess.xyz[ndx + 3][2] = origin[2] + left[2] - up[2]; // constant normal all the way around - VectorSubtract( vec3_origin, backEnd.viewParms.ori.axis[0], normal ); + VectorSubtract(vec3_origin, backEnd.viewParms.ori.axis[0], normal); - tess.normal[ndx][0] = tess.normal[ndx+1][0] = tess.normal[ndx+2][0] = tess.normal[ndx+3][0] = normal[0]; - tess.normal[ndx][1] = tess.normal[ndx+1][1] = tess.normal[ndx+2][1] = tess.normal[ndx+3][1] = normal[1]; - tess.normal[ndx][2] = tess.normal[ndx+1][2] = tess.normal[ndx+2][2] = tess.normal[ndx+3][2] = normal[2]; + tess.normal[ndx][0] = tess.normal[ndx + 1][0] = tess.normal[ndx + 2][0] = tess.normal[ndx + 3][0] = normal[0]; + tess.normal[ndx][1] = tess.normal[ndx + 1][1] = tess.normal[ndx + 2][1] = tess.normal[ndx + 3][1] = normal[1]; + tess.normal[ndx][2] = tess.normal[ndx + 1][2] = tess.normal[ndx + 2][2] = tess.normal[ndx + 3][2] = normal[2]; // standard square texture coordinates tess.texCoords[ndx][0][0] = tess.texCoords[ndx][1][0] = s1; tess.texCoords[ndx][0][1] = tess.texCoords[ndx][1][1] = t1; - tess.texCoords[ndx+1][0][0] = tess.texCoords[ndx+1][1][0] = s2; - tess.texCoords[ndx+1][0][1] = tess.texCoords[ndx+1][1][1] = t1; + tess.texCoords[ndx + 1][0][0] = tess.texCoords[ndx + 1][1][0] = s2; + tess.texCoords[ndx + 1][0][1] = tess.texCoords[ndx + 1][1][1] = t1; - tess.texCoords[ndx+2][0][0] = tess.texCoords[ndx+2][1][0] = s2; - tess.texCoords[ndx+2][0][1] = tess.texCoords[ndx+2][1][1] = t2; + tess.texCoords[ndx + 2][0][0] = tess.texCoords[ndx + 2][1][0] = s2; + tess.texCoords[ndx + 2][0][1] = tess.texCoords[ndx + 2][1][1] = t2; - tess.texCoords[ndx+3][0][0] = tess.texCoords[ndx+3][1][0] = s1; - tess.texCoords[ndx+3][0][1] = tess.texCoords[ndx+3][1][1] = t2; + tess.texCoords[ndx + 3][0][0] = tess.texCoords[ndx + 3][1][0] = s1; + tess.texCoords[ndx + 3][0][1] = tess.texCoords[ndx + 3][1][1] = t2; // constant color all the way around // should this be identity and let the shader specify from entity? @@ -137,7 +132,6 @@ void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, flo baDest = (byteAlias_t *)&tess.vertexColors[ndx + 3]; baDest->ui = baSource->ui; - tess.numVertexes += 4; tess.numIndexes += 6; } @@ -147,94 +141,86 @@ void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, byte *color, flo RB_AddQuadStamp ============== */ -void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, byte *color ) { - RB_AddQuadStampExt( origin, left, up, color, 0, 0, 1, 1 ); -} +void RB_AddQuadStamp(vec3_t origin, vec3_t left, vec3_t up, byte *color) { RB_AddQuadStampExt(origin, left, up, color, 0, 0, 1, 1); } /* ============== RB_SurfaceSprite ============== */ -static void RB_SurfaceSprite( void ) { - vec3_t left, up; - float radius; +static void RB_SurfaceSprite(void) { + vec3_t left, up; + float radius; // calculate the xyz locations for the four corners radius = backEnd.currentEntity->e.radius; - if ( backEnd.currentEntity->e.rotation == 0 ) { - VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); - VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); + if (backEnd.currentEntity->e.rotation == 0) { + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); } else { - float s, c; - float ang; + float s, c; + float ang; ang = M_PI * backEnd.currentEntity->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); } - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA); } - /* ======================= RB_SurfaceOrientedQuad ======================= */ -static void RB_SurfaceOrientedQuad( void ) -{ - vec3_t left, up; - float radius; +static void RB_SurfaceOrientedQuad(void) { + vec3_t left, up; + float radius; // calculate the xyz locations for the four corners radius = backEnd.currentEntity->e.radius; -// MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); - VectorCopy( backEnd.currentEntity->e.axis[1], left ); - VectorCopy( backEnd.currentEntity->e.axis[2], up ); + // MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); + VectorCopy(backEnd.currentEntity->e.axis[1], left); + VectorCopy(backEnd.currentEntity->e.axis[2], up); - if ( backEnd.currentEntity->e.rotation == 0 ) - { - VectorScale( left, radius, left ); - VectorScale( up, radius, up ); - } - else - { - vec3_t tempLeft, tempUp; - float s, c; - float ang; + if (backEnd.currentEntity->e.rotation == 0) { + VectorScale(left, radius, left); + VectorScale(up, radius, up); + } else { + vec3_t tempLeft, tempUp; + float s, c; + float ang; ang = M_PI * backEnd.currentEntity->e.rotation / 180; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); // Use a temp so we don't trash the values we'll need later - VectorScale( left, c * radius, tempLeft ); - VectorMA( tempLeft, -s * radius, up, tempLeft ); + VectorScale(left, c * radius, tempLeft); + VectorMA(tempLeft, -s * radius, up, tempLeft); - VectorScale( up, c * radius, tempUp ); - VectorMA( tempUp, s * radius, left, up ); // no need to use the temp anymore, so copy into the dest vector ( up ) + VectorScale(up, c * radius, tempUp); + VectorMA(tempUp, s * radius, left, up); // no need to use the temp anymore, so copy into the dest vector ( up ) // This was copied for safekeeping, we're done, so we can move it back to left - VectorCopy( tempLeft, left ); + VectorCopy(tempLeft, left); } - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(backEnd.currentEntity->e.origin, left, up, backEnd.currentEntity->e.shaderRGBA); } /* @@ -242,25 +228,24 @@ static void RB_SurfaceOrientedQuad( void ) RB_SurfacePolychain ============= */ -void RB_SurfacePolychain( srfPoly_t *p ) { - int i; - int numv; +void RB_SurfacePolychain(srfPoly_t *p) { + int i; + int numv; - RB_CHECKOVERFLOW( p->numVerts, 3*(p->numVerts - 2) ); + RB_CHECKOVERFLOW(p->numVerts, 3 * (p->numVerts - 2)); // fan triangles into the tess array numv = tess.numVertexes; - for ( i = 0; i < p->numVerts; i++ ) { - VectorCopy( p->verts[i].xyz, tess.xyz[numv] ); + for (i = 0; i < p->numVerts; i++) { + VectorCopy(p->verts[i].xyz, tess.xyz[numv]); tess.texCoords[numv][0][0] = p->verts[i].st[0]; tess.texCoords[numv][0][1] = p->verts[i].st[1]; - byteAlias_t *baDest = (byteAlias_t *)&tess.vertexColors[numv++], - *baSource = (byteAlias_t *)&p->verts[ i ].modulate; + byteAlias_t *baDest = (byteAlias_t *)&tess.vertexColors[numv++], *baSource = (byteAlias_t *)&p->verts[i].modulate; baDest->i = baSource->i; } // generate fan indexes into the tess array - for ( i = 0; i < p->numVerts-2; i++ ) { + for (i = 0; i < p->numVerts - 2; i++) { tess.indexes[tess.numIndexes + 0] = tess.numVertexes; tess.indexes[tess.numIndexes + 1] = tess.numVertexes + i + 1; tess.indexes[tess.numIndexes + 2] = tess.numVertexes + i + 2; @@ -270,18 +255,18 @@ void RB_SurfacePolychain( srfPoly_t *p ) { tess.numVertexes = numv; } -inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { +inline static uint32_t ComputeFinalVertexColor(const byte *colors) { int k; byteAlias_t result; uint32_t r, g, b; - for ( k=0; k<4; k++ ) + for (k = 0; k < 4; k++) result.b[k] = colors[k]; - if (tess.shader->lightmapIndex[0] != LIGHTMAP_BY_VERTEX ) + if (tess.shader->lightmapIndex[0] != LIGHTMAP_BY_VERTEX) return result.ui; - if ( r_fullbright->integer ) { + if (r_fullbright->integer) { result.b[0] = 255; result.b[1] = 255; result.b[2] = 255; @@ -289,21 +274,20 @@ inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { } // an optimization could be added here to compute the style[0] (which is always the world normal light) r = g = b = 0; - for( k=0; kstyles[k] < LS_UNUSED ) { + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->styles[k] < LS_UNUSED) { byte *styleColor = styleColors[tess.shader->styles[k]]; r += (uint32_t)(*colors++) * (uint32_t)(*styleColor++); g += (uint32_t)(*colors++) * (uint32_t)(*styleColor++); b += (uint32_t)(*colors++) * (uint32_t)(*styleColor); colors++; - } - else + } else break; } - result.b[0] = Com_Clamp( 0, 255, r >> 8 ); - result.b[1] = Com_Clamp( 0, 255, g >> 8 ); - result.b[2] = Com_Clamp( 0, 255, b >> 8 ); + result.b[0] = Com_Clamp(0, 255, r >> 8); + result.b[1] = Com_Clamp(0, 255, g >> 8); + result.b[2] = Com_Clamp(0, 255, b >> 8); return result.ui; } @@ -313,33 +297,32 @@ inline static uint32_t ComputeFinalVertexColor( const byte *colors ) { RB_SurfaceTriangles ============= */ -void RB_SurfaceTriangles( srfTriangles_t *srf ) { - int i, k; - drawVert_t *dv; - float *xyz, *normal, *texCoords; - byte *color; - int dlightBits; +void RB_SurfaceTriangles(srfTriangles_t *srf) { + int i, k; + drawVert_t *dv; + float *xyz, *normal, *texCoords; + byte *color; + int dlightBits; dlightBits = srf->dlightBits; tess.dlightBits |= dlightBits; - RB_CHECKOVERFLOW( srf->numVerts, srf->numIndexes ); + RB_CHECKOVERFLOW(srf->numVerts, srf->numIndexes); - for ( i = 0 ; i < srf->numIndexes ; i += 3 ) { - tess.indexes[ tess.numIndexes + i + 0 ] = tess.numVertexes + srf->indexes[ i + 0 ]; - tess.indexes[ tess.numIndexes + i + 1 ] = tess.numVertexes + srf->indexes[ i + 1 ]; - tess.indexes[ tess.numIndexes + i + 2 ] = tess.numVertexes + srf->indexes[ i + 2 ]; + for (i = 0; i < srf->numIndexes; i += 3) { + tess.indexes[tess.numIndexes + i + 0] = tess.numVertexes + srf->indexes[i + 0]; + tess.indexes[tess.numIndexes + i + 1] = tess.numVertexes + srf->indexes[i + 1]; + tess.indexes[tess.numIndexes + i + 2] = tess.numVertexes + srf->indexes[i + 2]; } tess.numIndexes += srf->numIndexes; dv = srf->verts; - xyz = tess.xyz[ tess.numVertexes ]; - normal = tess.normal[ tess.numVertexes ]; - texCoords = tess.texCoords[ tess.numVertexes ][0]; - color = tess.vertexColors[ tess.numVertexes ]; + xyz = tess.xyz[tess.numVertexes]; + normal = tess.normal[tess.numVertexes]; + texCoords = tess.texCoords[tess.numVertexes][0]; + color = tess.vertexColors[tess.numVertexes]; - for ( i = 0 ; i < srf->numVerts ; i++, dv++) - { + for (i = 0; i < srf->numVerts; i++, dv++) { xyz[0] = dv->xyz[0]; xyz[1] = dv->xyz[1]; xyz[2] = dv->xyz[2]; @@ -353,46 +336,39 @@ void RB_SurfaceTriangles( srfTriangles_t *srf ) { texCoords[0] = dv->st[0]; texCoords[1] = dv->st[1]; - for(k=0;klightmapIndex[k] >= 0) - { - texCoords[2+(k*2)] = dv->lightmap[k][0]; - texCoords[2+(k*2)+1] = dv->lightmap[k][1]; - } - else - { // can't have an empty slot in the middle, so we are done + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->lightmapIndex[k] >= 0) { + texCoords[2 + (k * 2)] = dv->lightmap[k][0]; + texCoords[2 + (k * 2) + 1] = dv->lightmap[k][1]; + } else { // can't have an empty slot in the middle, so we are done break; } } - texCoords += NUM_TEX_COORDS*2; + texCoords += NUM_TEX_COORDS * 2; *(unsigned *)color = ComputeFinalVertexColor((byte *)dv->color); color += 4; } - for ( i = 0 ; i < srf->numVerts ; i++ ) { - tess.vertexDlightBits[ tess.numVertexes + i] = dlightBits; + for (i = 0; i < srf->numVerts; i++) { + tess.vertexDlightBits[tess.numVertexes + i] = dlightBits; } tess.numVertexes += srf->numVerts; } - - /* ============== RB_SurfaceBeam ============== */ -static void RB_SurfaceBeam( void ) -{ +static void RB_SurfaceBeam(void) { #define NUM_BEAM_SEGS 6 refEntity_t *e; - int i; + int i; vec3_t perpvec; vec3_t direction, normalized_direction; - vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; + vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; vec3_t oldorigin, origin; e = &backEnd.currentEntity->e; @@ -409,30 +385,29 @@ static void RB_SurfaceBeam( void ) normalized_direction[1] = direction[1] = oldorigin[1] - origin[1]; normalized_direction[2] = direction[2] = oldorigin[2] - origin[2]; - if ( VectorNormalize( normalized_direction ) == 0 ) + if (VectorNormalize(normalized_direction) == 0) return; - PerpendicularVector( perpvec, normalized_direction ); + PerpendicularVector(perpvec, normalized_direction); - VectorScale( perpvec, 4, perpvec ); + VectorScale(perpvec, 4, perpvec); - for ( i = 0; i < NUM_BEAM_SEGS ; i++ ) - { - RotatePointAroundVector( start_points[i], normalized_direction, perpvec, (360.0/NUM_BEAM_SEGS)*i ); -// VectorAdd( start_points[i], origin, start_points[i] ); - VectorAdd( start_points[i], direction, end_points[i] ); + for (i = 0; i < NUM_BEAM_SEGS; i++) { + RotatePointAroundVector(start_points[i], normalized_direction, perpvec, (360.0 / NUM_BEAM_SEGS) * i); + // VectorAdd( start_points[i], origin, start_points[i] ); + VectorAdd(start_points[i], direction, end_points[i]); } - GL_Bind( tr.whiteImage ); + GL_Bind(tr.whiteImage); - GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); - qglColor3f( 1, 0, 0 ); + qglColor3f(1, 0, 0); - qglBegin( GL_TRIANGLE_STRIP ); - for ( i = 0; i <= NUM_BEAM_SEGS; i++ ) { - qglVertex3fv( start_points[ i % NUM_BEAM_SEGS] ); - qglVertex3fv( end_points[ i % NUM_BEAM_SEGS] ); + qglBegin(GL_TRIANGLE_STRIP); + for (i = 0; i <= NUM_BEAM_SEGS; i++) { + qglVertex3fv(start_points[i % NUM_BEAM_SEGS]); + qglVertex3fv(end_points[i % NUM_BEAM_SEGS]); } qglEnd(); } @@ -440,53 +415,49 @@ static void RB_SurfaceBeam( void ) //------------------ // DoSprite //------------------ -static void DoSprite( vec3_t origin, float radius, float rotation ) -{ - float s, c; - float ang; - vec3_t left, up; +static void DoSprite(vec3_t origin, float radius, float rotation) { + float s, c; + float ang; + vec3_t left, up; ang = M_PI * rotation / 180.0f; - s = sin( ang ); - c = cos( ang ); + s = sin(ang); + c = cos(ang); - VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); - VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + VectorScale(backEnd.viewParms.ori.axis[1], c * radius, left); + VectorMA(left, -s * radius, backEnd.viewParms.ori.axis[2], left); - VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); - VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + VectorScale(backEnd.viewParms.ori.axis[2], c * radius, up); + VectorMA(up, s * radius, backEnd.viewParms.ori.axis[1], up); - if ( backEnd.viewParms.isMirror ) - { - VectorSubtract( vec3_origin, left, left ); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( origin, left, up, backEnd.currentEntity->e.shaderRGBA ); + RB_AddQuadStamp(origin, left, up, backEnd.currentEntity->e.shaderRGBA); } //------------------ // RB_SurfaceSaber //------------------ -static void RB_SurfaceSaberGlow() -{ - vec3_t end; +static void RB_SurfaceSaberGlow() { + vec3_t end; refEntity_t *e; e = &backEnd.currentEntity->e; // Render the glow part of the blade - for ( float i = e->saberLength; i > 0; i -= e->radius * 0.65f ) - { - VectorMA( e->origin, i, e->axis[0], end ); + for (float i = e->saberLength; i > 0; i -= e->radius * 0.65f) { + VectorMA(e->origin, i, e->axis[0], end); - DoSprite( end, e->radius, 0.0f );//Q_flrand(0.0f, 1.0f) * 360.0f ); + DoSprite(end, e->radius, 0.0f); // Q_flrand(0.0f, 1.0f) * 360.0f ); e->radius += 0.017f; } // Big hilt sprite // Please don't kill me Pat...I liked the hilt glow blob, but wanted a subtle pulse.:) Feel free to ditch it if you don't like it. --Jeff // Please don't kill me Jeff... The pulse is good, but now I want the halo bigger if the saber is shorter... --Pat - DoSprite( e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f );//Q_flrand(0.0f, 1.0f) * 360.0f ); + DoSprite(e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f); // Q_flrand(0.0f, 1.0f) * 360.0f ); } /* @@ -508,28 +479,27 @@ RB_SurfaceLine // startRGB, endRGB // -static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) -{ - float spanWidth2; - int vbase; +static void DoLine(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth) { + float spanWidth2; + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; spanWidth2 = -spanWidth; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];// * 0.25;//wtf??not sure why the code would be doing this - tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];// * 0.25; - tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];// * 0.25; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; // * 0.25;//wtf??not sure why the code would be doing this + tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; // * 0.25; + tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; // * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = 0; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; @@ -537,19 +507,19 @@ static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; @@ -565,25 +535,24 @@ static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float tess.indexes[tess.numIndexes++] = vbase + 3; } -static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2 ) -{ - int vbase; +static void DoLine2(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2) { + int vbase; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];// * 0.25;//wtf??not sure why the code would be doing this - tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];// * 0.25; - tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];// * 0.25; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; // * 0.25;//wtf??not sure why the code would be doing this + tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; // * 0.25; + tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; // * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( start, -spanWidth, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + VectorMA(start, -spanWidth, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; tess.texCoords[tess.numVertexes][0][1] = 0; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; @@ -591,19 +560,19 @@ static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, floa tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; tess.numVertexes++; - VectorMA( end, -spanWidth2, up, tess.xyz[tess.numVertexes] ); - tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; - tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorMA(end, -spanWidth2, up, tess.xyz[tess.numVertexes]); + tess.texCoords[tess.numVertexes][0][0] = 1; // backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1; // backEnd.currentEntity->e.shaderTexCoord[1]; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; @@ -619,51 +588,50 @@ static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, floa tess.indexes[tess.numIndexes++] = vbase + 3; } -static void DoLine_Oriented( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) -{ - float spanWidth2; - int vbase; +static void DoLine_Oriented(const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth) { + float spanWidth2; + int vbase; vbase = tess.numVertexes; spanWidth2 = -spanWidth; // FIXME: use quad stamp? - VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = 0; - tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0];// * 0.25; - tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1];// * 0.25; - tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2];// * 0.25; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; // * 0.25; + tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; // * 0.25; + tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; // * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(start, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 1; tess.texCoords[tess.numVertexes][0][1] = 0; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 0; tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; - VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + VectorMA(end, spanWidth2, up, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = 1; tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; tess.vertexColors[tess.numVertexes][0] = backEnd.currentEntity->e.shaderRGBA[0]; tess.vertexColors[tess.numVertexes][1] = backEnd.currentEntity->e.shaderRGBA[1]; tess.vertexColors[tess.numVertexes][2] = backEnd.currentEntity->e.shaderRGBA[2]; - tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3];// * 0.25; + tess.vertexColors[tess.numVertexes][3] = backEnd.currentEntity->e.shaderRGBA[3]; // * 0.25; tess.numVertexes++; tess.indexes[tess.numIndexes++] = vbase; @@ -678,42 +646,40 @@ static void DoLine_Oriented( const vec3_t start, const vec3_t end, const vec3_t //----------------- // RB_SurfaceLine //----------------- -static void RB_SurfaceLine( void ) -{ +static void RB_SurfaceLine(void) { refEntity_t *e; - vec3_t right; - vec3_t start, end; - vec3_t v1, v2; + vec3_t right; + vec3_t start, end; + vec3_t v1, v2; e = &backEnd.currentEntity->e; - VectorCopy( e->oldorigin, end ); - VectorCopy( e->origin, start ); + VectorCopy(e->oldorigin, end); + VectorCopy(e->origin, start); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); - DoLine( start, end, right, e->radius); + DoLine(start, end, right, e->radius); } -static void RB_SurfaceOrientedLine( void ) -{ +static void RB_SurfaceOrientedLine(void) { refEntity_t *e; - vec3_t right; - vec3_t start, end; + vec3_t right; + vec3_t start, end; e = &backEnd.currentEntity->e; - VectorCopy( e->oldorigin, end ); - VectorCopy( e->origin, start ); + VectorCopy(e->oldorigin, end); + VectorCopy(e->origin, start); // compute side vector - VectorNormalize( e->axis[1] ); + VectorNormalize(e->axis[1]); VectorCopy(e->axis[1], right); - DoLine_Oriented( start, end, right, e->data.line.width*0.5 ); + DoLine_Oriented(start, end, right, e->data.line.width * 0.5); } /* @@ -725,18 +691,16 @@ RB_SurfaceCylinder #define NUM_CYLINDER_SEGMENTS 32 // FIXME: use quad stamp? -static void DoCylinderPart(polyVert_t *verts) -{ - int vbase; - int i; +static void DoCylinderPart(polyVert_t *verts) { + int vbase; + int i; - RB_CHECKOVERFLOW( 4, 6 ); + RB_CHECKOVERFLOW(4, 6); vbase = tess.numVertexes; - for (i=0; i<4; i++) - { - VectorCopy( verts->xyz, tess.xyz[tess.numVertexes] ); + for (i = 0; i < 4; i++) { + VectorCopy(verts->xyz, tess.xyz[tess.numVertexes]); tess.texCoords[tess.numVertexes][0][0] = verts->st[0]; tess.texCoords[tess.numVertexes][0][1] = verts->st[1]; tess.vertexColors[tess.numVertexes][0] = verts->modulate[0]; @@ -760,73 +724,68 @@ static void DoCylinderPart(polyVert_t *verts) // e->oldorigin holds the top point // e->radius holds the radius -static void RB_SurfaceCylinder( void ) -{ - static polyVert_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS], verts[4]; - vec3_t vr, vu, midpoint, v1; - float detail, length; - int i; - int segments; +static void RB_SurfaceCylinder(void) { + static polyVert_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS], verts[4]; + vec3_t vr, vu, midpoint, v1; + float detail, length; + int i; + int segments; refEntity_t *e; - int nextSegment; + int nextSegment; e = &backEnd.currentEntity->e; - //Work out the detail level of this cylinder - VectorAdd( e->origin, e->oldorigin, midpoint ); - VectorScale(midpoint, 0.5f, midpoint); // Average start and end + // Work out the detail level of this cylinder + VectorAdd(e->origin, e->oldorigin, midpoint); + VectorScale(midpoint, 0.5f, midpoint); // Average start and end - VectorSubtract( midpoint, backEnd.viewParms.ori.origin, midpoint ); - length = VectorNormalize( midpoint ); + VectorSubtract(midpoint, backEnd.viewParms.ori.origin, midpoint); + length = VectorNormalize(midpoint); // this doesn't need to be perfect....just a rough compensation for zoom level is enough length *= (backEnd.viewParms.fovX / 90.0f); - detail = 1 - ((float) length / 1024 ); + detail = 1 - ((float)length / 1024); segments = NUM_CYLINDER_SEGMENTS * detail; // 3 is the absolute minimum, but the pop between 3-8 is too noticeable - if ( segments < 8 ) - { + if (segments < 8) { segments = 8; } - if ( segments > NUM_CYLINDER_SEGMENTS ) - { + if (segments > NUM_CYLINDER_SEGMENTS) { segments = NUM_CYLINDER_SEGMENTS; } - //Get the direction vector - MakeNormalVectors( e->axis[0], vr, vu ); + // Get the direction vector + MakeNormalVectors(e->axis[0], vr, vu); - VectorScale( vu, e->radius, v1 ); // size1 - VectorScale( vu, e->rotation, vu ); // size2 + VectorScale(vu, e->radius, v1); // size1 + VectorScale(vu, e->rotation, vu); // size2 // Calculate the step around the cylinder detail = 360.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { - //Upper ring - RotatePointAroundVector( upper_points[i].xyz, e->axis[0], vu, detail * i ); - VectorAdd( upper_points[i].xyz, e->origin, upper_points[i].xyz ); + for (i = 0; i < segments; i++) { + // Upper ring + RotatePointAroundVector(upper_points[i].xyz, e->axis[0], vu, detail * i); + VectorAdd(upper_points[i].xyz, e->origin, upper_points[i].xyz); - //Lower ring - RotatePointAroundVector( lower_points[i].xyz, e->axis[0], v1, detail * i ); - VectorAdd( lower_points[i].xyz, e->oldorigin, lower_points[i].xyz ); + // Lower ring + RotatePointAroundVector(lower_points[i].xyz, e->axis[0], v1, detail * i); + VectorAdd(lower_points[i].xyz, e->oldorigin, lower_points[i].xyz); } // Calculate the texture coords so the texture can wrap around the whole cylinder detail = 1.0f / (float)segments; - for ( i = 0; i < segments; i++ ) - { - if ( i + 1 < segments ) + for (i = 0; i < segments; i++) { + if (i + 1 < segments) nextSegment = i + 1; else nextSegment = 0; - VectorCopy( upper_points[i].xyz, verts[0].xyz ); + VectorCopy(upper_points[i].xyz, verts[0].xyz); verts[0].st[1] = 1.0f; verts[0].st[0] = detail * i; verts[0].modulate[0] = (byte)(e->shaderRGBA[0]); @@ -834,7 +793,7 @@ static void RB_SurfaceCylinder( void ) verts[0].modulate[2] = (byte)(e->shaderRGBA[2]); verts[0].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( lower_points[i].xyz, verts[1].xyz ); + VectorCopy(lower_points[i].xyz, verts[1].xyz); verts[1].st[1] = 0.0f; verts[1].st[0] = detail * i; verts[1].modulate[0] = (byte)(e->shaderRGBA[0]); @@ -842,17 +801,17 @@ static void RB_SurfaceCylinder( void ) verts[1].modulate[2] = (byte)(e->shaderRGBA[2]); verts[1].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( lower_points[nextSegment].xyz, verts[2].xyz ); + VectorCopy(lower_points[nextSegment].xyz, verts[2].xyz); verts[2].st[1] = 0.0f; - verts[2].st[0] = detail * ( i + 1 ); + verts[2].st[0] = detail * (i + 1); verts[2].modulate[0] = (byte)(e->shaderRGBA[0]); verts[2].modulate[1] = (byte)(e->shaderRGBA[1]); verts[2].modulate[2] = (byte)(e->shaderRGBA[2]); verts[2].modulate[3] = (byte)(e->shaderRGBA[3]); - VectorCopy( upper_points[nextSegment].xyz, verts[3].xyz ); + VectorCopy(upper_points[nextSegment].xyz, verts[3].xyz); verts[3].st[1] = 1.0f; - verts[3].st[0] = detail * ( i + 1 ); + verts[3].st[0] = detail * (i + 1); verts[3].modulate[0] = (byte)(e->shaderRGBA[0]); verts[3].modulate[1] = (byte)(e->shaderRGBA[1]); verts[3].modulate[2] = (byte)(e->shaderRGBA[2]); @@ -886,43 +845,41 @@ static float Q_crandom( int *seed ) { static void CreateShape() //---------------------------------------------------------------------------- { - VectorSet( sh1, 0.66f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f, - 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f ); + VectorSet(sh1, 0.66f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f, 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f); // it seems to look best to have a point on one side of the ideal line, then the other point on the other side. - VectorSet( sh2, 0.33f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd - -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right - -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f );// up + VectorSet(sh2, 0.33f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right + -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f); // up } //---------------------------------------------------------------------------- -static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count ) +static void ApplyShape(vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count) //---------------------------------------------------------------------------- { - vec3_t point1, point2, fwd; - vec3_t rt, up; - float perc, dis; + vec3_t point1, point2, fwd; + vec3_t rt, up; + float perc, dis; - if ( count < 1 ) - { + if (count < 1) { // done recursing - DoLine2( start, end, right, sradius, eradius ); + DoLine2(start, end, right, sradius, eradius); return; } - CreateShape(); + CreateShape(); - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ) * 0.7f; - MakeNormalVectors( fwd, rt, up ); + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd) * 0.7f; + MakeNormalVectors(fwd, rt, up); perc = sh1[0]; - VectorScale( start, perc, point1 ); - VectorMA( point1, 1.0f - perc, end, point1 ); - VectorMA( point1, dis * sh1[1], rt, point1 ); - VectorMA( point1, dis * sh1[2], up, point1 ); + VectorScale(start, perc, point1); + VectorMA(point1, 1.0f - perc, end, point1); + VectorMA(point1, dis * sh1[1], rt, point1); + VectorMA(point1, dis * sh1[2], up, point1); // do a quick and dirty interpolation of the radius at that point float rads1, rads2; @@ -931,104 +888,97 @@ static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, f rads2 = sradius * 0.333f + eradius * 0.666f; // recursion - ApplyShape( start, point1, right, sradius, rads1, count - 1 ); + ApplyShape(start, point1, right, sradius, rads1, count - 1); perc = sh2[0]; - VectorScale( start, perc, point2 ); - VectorMA( point2, 1.0f - perc, end, point2 ); - VectorMA( point2, dis * sh2[1], rt, point2 ); - VectorMA( point2, dis * sh2[2], up, point2 ); + VectorScale(start, perc, point2); + VectorMA(point2, 1.0f - perc, end, point2); + VectorMA(point2, dis * sh2[1], rt, point2); + VectorMA(point2, dis * sh2[2], up, point2); // recursion - ApplyShape( point2, point1, right, rads1, rads2, count - 1 ); - ApplyShape( point2, end, right, rads2, eradius, count - 1 ); + ApplyShape(point2, point1, right, rads1, rads2, count - 1); + ApplyShape(point2, end, right, rads2, eradius, count - 1); } //---------------------------------------------------------------------------- -static void DoBoltSeg( vec3_t start, vec3_t end, vec3_t right, float radius ) +static void DoBoltSeg(vec3_t start, vec3_t end, vec3_t right, float radius) //---------------------------------------------------------------------------- { refEntity_t *e; vec3_t fwd, old; - vec3_t cur, off={10,10,10}; + vec3_t cur, off = {10, 10, 10}; vec3_t rt, up; vec3_t temp; - int i; - float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; + int i; + float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; e = &backEnd.currentEntity->e; - VectorSubtract( end, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(end, start, fwd); + dis = VectorNormalize(fwd); - MakeNormalVectors( fwd, rt, up ); + MakeNormalVectors(fwd, rt, up); - VectorCopy( start, old ); + VectorCopy(start, old); oldRadius = newRadius = radius; - for ( i = 20; i <= dis; i+= 20 ) - { + for (i = 20; i <= dis; i += 20) { // because of our large step size, we may not actually draw to the end. In this case, fudge our percent so that we are basically complete - if ( i + 20 > dis ) - { + if (i + 20 > dis) { perc = 1.0f; - } - else - { + } else { // percentage of the amount of line completed perc = (float)i / dis; } // create our level of deviation for this point - VectorScale( fwd, Q_crandom(&e->frame) * 3.0f, temp ); // move less in fwd direction, chaos also does not affect this - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], rt, temp ); // move more in direction perpendicular to line, angles is really the chaos - VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], up, temp ); // move more in direction perpendicular to line + VectorScale(fwd, Q_crandom(&e->frame) * 3.0f, temp); // move less in fwd direction, chaos also does not affect this + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], rt, temp); // move more in direction perpendicular to line, angles is really the chaos + VectorMA(temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], up, temp); // move more in direction perpendicular to line // track our total level of offset from the ideal line - VectorAdd( off, temp, off ); + VectorAdd(off, temp, off); - // Move from start to end, always adding our current level of offset from the ideal line + // Move from start to end, always adding our current level of offset from the ideal line // Even though we are adding a random offset.....by nature, we always move from exactly start....to end - VectorAdd( start, off, cur ); - VectorScale( cur, 1.0f - perc, cur ); - VectorMA( cur, perc, end, cur ); + VectorAdd(start, off, cur); + VectorScale(cur, 1.0f - perc, cur); + VectorMA(cur, perc, end, cur); - if ( e->renderfx & RF_TAPERED ) - { + if (e->renderfx & RF_TAPERED) { // This does pretty close to perfect tapering since apply shape interpolates the old and new as it goes along. // by using one minus the square, the radius stays fairly constant, then drops off quickly at the very point of the bolt - oldRadius = radius * (1.0f-oldPerc*oldPerc); - newRadius = radius * (1.0f-perc*perc); + oldRadius = radius * (1.0f - oldPerc * oldPerc); + newRadius = radius * (1.0f - perc * perc); } // Apply the random shape to our line seg to give it some micro-detail-jaggy-coolness. - ApplyShape( cur, old, right, newRadius, oldRadius, LIGHTNING_RECURSION_LEVEL ); + ApplyShape(cur, old, right, newRadius, oldRadius, LIGHTNING_RECURSION_LEVEL); // randomly split off to create little tendrils, but don't do it too close to the end and especially if we are not even of the forked variety - if ( ( e->renderfx & RF_FORKED ) && f_count > 0 && Q_random(&e->frame) > 0.94f && radius * (1.0f - perc) > 0.2f ) - { + if ((e->renderfx & RF_FORKED) && f_count > 0 && Q_random(&e->frame) > 0.94f && radius * (1.0f - perc) > 0.2f) { vec3_t newDest; f_count--; // Pick a point somewhere between the current point and the final endpoint - VectorAdd( cur, e->oldorigin, newDest ); - VectorScale( newDest, 0.5f, newDest ); + VectorAdd(cur, e->oldorigin, newDest); + VectorScale(newDest, 0.5f, newDest); // And then add some crazy offset - for ( int t = 0; t < 3; t++ ) - { + for (int t = 0; t < 3; t++) { newDest[t] += Q_crandom(&e->frame) * 80; } // we could branch off using OLD and NEWDEST, but that would allow multiple forks...whereas, we just want simpler brancing - DoBoltSeg( cur, newDest, right, newRadius ); + DoBoltSeg(cur, newDest, right, newRadius); } // Current point along the line becomes our new old attach point - VectorCopy( cur, old ); + VectorCopy(cur, old); oldPerc = perc; } } @@ -1038,125 +988,114 @@ static void RB_SurfaceElectricity() //------------------------------------------ { refEntity_t *e; - vec3_t right, fwd; - vec3_t start, end; - vec3_t v1, v2; - float radius, perc = 1.0f, dis; + vec3_t right, fwd; + vec3_t start, end; + vec3_t v1, v2; + float radius, perc = 1.0f, dis; e = &backEnd.currentEntity->e; radius = e->radius; - VectorCopy( e->origin, start ); + VectorCopy(e->origin, start); - VectorSubtract( e->oldorigin, start, fwd ); - dis = VectorNormalize( fwd ); + VectorSubtract(e->oldorigin, start, fwd); + dis = VectorNormalize(fwd); // see if we should grow from start to end - if ( e->renderfx & RF_GROW ) - { - perc = 1.0f - ( e->axis[0][2]/*endTime*/ - tr.refdef.time ) / e->axis[0][1]/*duration*/; + if (e->renderfx & RF_GROW) { + perc = 1.0f - (e->axis[0][2] /*endTime*/ - tr.refdef.time) / e->axis[0][1] /*duration*/; - if ( perc > 1.0f ) - { + if (perc > 1.0f) { perc = 1.0f; - } - else if ( perc < 0.0f ) - { + } else if (perc < 0.0f) { perc = 0.0f; } } - VectorMA( start, perc * dis, fwd, e->oldorigin ); - VectorCopy( e->oldorigin, end ); + VectorMA(start, perc * dis, fwd, e->oldorigin); + VectorCopy(e->oldorigin, end); // compute side vector - VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); - VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); - CrossProduct( v1, v2, right ); - VectorNormalize( right ); + VectorSubtract(start, backEnd.viewParms.ori.origin, v1); + VectorSubtract(end, backEnd.viewParms.ori.origin, v2); + CrossProduct(v1, v2, right); + VectorNormalize(right); - DoBoltSeg( start, end, right, radius ); + DoBoltSeg(start, end, right, radius); } //================================================================================ - /* ** VectorArrayNormalize * * The inputs to this routing seem to always be close to length = 1.0 (about 0.6 to 2.0) * This means that we don't have to worry about zero length or enormously long vectors. */ -static void VectorArrayNormalize(vec4_t *normals, unsigned int count) -{ -// assert(count); +static void VectorArrayNormalize(vec4_t *normals, unsigned int count) { + // assert(count); #if idppc - { - register float half = 0.5; - register float one = 1.0; - float *components = (float *)normals; - - // Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction, - // runs *much* faster than calling sqrt(). We'll use a single Newton-Raphson - // refinement step to get a little more precision. This seems to yeild results - // that are correct to 3 decimal places and usually correct to at least 4 (sometimes 5). - // (That is, for the given input range of about 0.6 to 2.0). - do { - float x, y, z; - float B, y0, y1; - - x = components[0]; - y = components[1]; - z = components[2]; - components += 4; - B = x*x + y*y + z*z; + { + register float half = 0.5; + register float one = 1.0; + float *components = (float *)normals; + + // Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction, + // runs *much* faster than calling sqrt(). We'll use a single Newton-Raphson + // refinement step to get a little more precision. This seems to yeild results + // that are correct to 3 decimal places and usually correct to at least 4 (sometimes 5). + // (That is, for the given input range of about 0.6 to 2.0). + do { + float x, y, z; + float B, y0, y1; + + x = components[0]; + y = components[1]; + z = components[2]; + components += 4; + B = x * x + y * y + z * z; #ifdef __GNUC__ - asm("frsqrte %0,%1" : "=f" (y0) : "f" (B)); + asm("frsqrte %0,%1" : "=f"(y0) : "f"(B)); #else y0 = __frsqrte(B); #endif - y1 = y0 + half*y0*(one - B*y0*y0); - - x = x * y1; - y = y * y1; - components[-4] = x; - z = z * y1; - components[-3] = y; - components[-2] = z; - } while(count--); - } + y1 = y0 + half * y0 * (one - B * y0 * y0); + + x = x * y1; + y = y * y1; + components[-4] = x; + z = z * y1; + components[-3] = y; + components[-2] = z; + } while (count--); + } #else // No assembly version for this architecture, or C_ONLY defined // given the input, it's safe to call VectorNormalizeFast - while (count--) { - VectorNormalizeFast(normals[0]); - normals++; - } + while (count--) { + VectorNormalizeFast(normals[0]); + normals++; + } #endif - } - - /* ** LerpMeshVertexes */ -static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) -{ - short *oldXyz, *newXyz, *oldNormals, *newNormals; - float *outXyz, *outNormal; - float oldXyzScale, newXyzScale; - float oldNormalScale, newNormalScale; - int vertNum; +static void LerpMeshVertexes(md3Surface_t *surf, float backlerp) { + short *oldXyz, *newXyz, *oldNormals, *newNormals; + float *outXyz, *outNormal; + float oldXyzScale, newXyzScale; + float oldNormalScale, newNormalScale; + int vertNum; unsigned lat, lng; - int numVerts; + int numVerts; outXyz = tess.xyz[tess.numVertexes]; outNormal = tess.normal[tess.numVertexes]; - newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) - + (backEnd.currentEntity->e.frame * surf->numVerts * 4); + newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + (backEnd.currentEntity->e.frame * surf->numVerts * 4); newNormals = newXyz + 3; newXyzScale = MD3_XYZ_SCALE * (1.0 - backlerp); @@ -1164,46 +1103,39 @@ static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) numVerts = surf->numVerts; - if ( backlerp == 0 ) { + if (backlerp == 0) { // // just copy the vertexes // - for (vertNum=0 ; vertNum < numVerts ; vertNum++, - newXyz += 4, newNormals += 4, - outXyz += 4, outNormal += 4) - { + for (vertNum = 0; vertNum < numVerts; vertNum++, newXyz += 4, newNormals += 4, outXyz += 4, outNormal += 4) { outXyz[0] = newXyz[0] * newXyzScale; outXyz[1] = newXyz[1] * newXyzScale; outXyz[2] = newXyz[2] * newXyzScale; - lat = ( newNormals[0] >> 8 ) & 0xff; - lng = ( newNormals[0] & 0xff ); - lat *= (FUNCTABLE_SIZE/256); - lng *= (FUNCTABLE_SIZE/256); + lat = (newNormals[0] >> 8) & 0xff; + lng = (newNormals[0] & 0xff); + lat *= (FUNCTABLE_SIZE / 256); + lng *= (FUNCTABLE_SIZE / 256); // decode X as cos( lat ) * sin( long ) // decode Y as sin( lat ) * sin( long ) // decode Z as cos( long ) - outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + outNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + outNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; } } else { // // interpolate and copy the vertex and normal // - oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) - + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); + oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); oldNormals = oldXyz + 3; oldXyzScale = MD3_XYZ_SCALE * backlerp; oldNormalScale = backlerp; - for (vertNum=0 ; vertNum < numVerts ; vertNum++, - oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, - outXyz += 4, outNormal += 4) - { + for (vertNum = 0; vertNum < numVerts; vertNum++, oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, outXyz += 4, outNormal += 4) { vec3_t uncompressedOldNormal, uncompressedNewNormal; // interpolate the xyz @@ -1212,31 +1144,31 @@ static void LerpMeshVertexes (md3Surface_t *surf, float backlerp) outXyz[2] = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale; // FIXME: interpolate lat/long instead? - lat = ( newNormals[0] >> 8 ) & 0xff; - lng = ( newNormals[0] & 0xff ); + lat = (newNormals[0] >> 8) & 0xff; + lng = (newNormals[0] & 0xff); lat *= 4; lng *= 4; - uncompressedNewNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedNewNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; uncompressedNewNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - uncompressedNewNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + uncompressedNewNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; - lat = ( oldNormals[0] >> 8 ) & 0xff; - lng = ( oldNormals[0] & 0xff ); + lat = (oldNormals[0] >> 8) & 0xff; + lng = (oldNormals[0] & 0xff); lat *= 4; lng *= 4; - uncompressedOldNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedOldNormal[0] = tr.sinTable[(lat + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK] * tr.sinTable[lng]; uncompressedOldNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; - uncompressedOldNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + uncompressedOldNormal[2] = tr.sinTable[(lng + (FUNCTABLE_SIZE / 4)) & FUNCTABLE_MASK]; outNormal[0] = uncompressedOldNormal[0] * oldNormalScale + uncompressedNewNormal[0] * newNormalScale; outNormal[1] = uncompressedOldNormal[1] * oldNormalScale + uncompressedNewNormal[1] * newNormalScale; outNormal[2] = uncompressedOldNormal[2] * oldNormalScale + uncompressedNewNormal[2] * newNormalScale; -// VectorNormalize (outNormal); + // VectorNormalize (outNormal); } - VectorArrayNormalize((vec4_t *)tess.normal[tess.numVertexes], numVerts); - } + VectorArrayNormalize((vec4_t *)tess.normal[tess.numVertexes], numVerts); + } } /* @@ -1245,74 +1177,72 @@ RB_SurfaceMesh ============= */ void RB_SurfaceMesh(md3Surface_t *surface) { - int j; - float backlerp; - int *triangles; - float *texCoords; - int indexes; - int Bob, Doug; - int numVerts; - - if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) { + int j; + float backlerp; + int *triangles; + float *texCoords; + int indexes; + int Bob, Doug; + int numVerts; + + if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) { backlerp = 0; - } else { + } else { backlerp = backEnd.currentEntity->e.backlerp; } - RB_CHECKOVERFLOW( surface->numVerts, surface->numTriangles*3 ); + RB_CHECKOVERFLOW(surface->numVerts, surface->numTriangles * 3); - LerpMeshVertexes (surface, backlerp); + LerpMeshVertexes(surface, backlerp); - triangles = (int *) ((byte *)surface + surface->ofsTriangles); + triangles = (int *)((byte *)surface + surface->ofsTriangles); indexes = surface->numTriangles * 3; Bob = tess.numIndexes; Doug = tess.numVertexes; - for (j = 0 ; j < indexes ; j++) { + for (j = 0; j < indexes; j++) { tess.indexes[Bob + j] = Doug + triangles[j]; } tess.numIndexes += indexes; - texCoords = (float *) ((byte *)surface + surface->ofsSt); + texCoords = (float *)((byte *)surface + surface->ofsSt); numVerts = surface->numVerts; - for ( j = 0; j < numVerts; j++ ) { - tess.texCoords[Doug + j][0][0] = texCoords[j*2+0]; - tess.texCoords[Doug + j][0][1] = texCoords[j*2+1]; + for (j = 0; j < numVerts; j++) { + tess.texCoords[Doug + j][0][0] = texCoords[j * 2 + 0]; + tess.texCoords[Doug + j][0][1] = texCoords[j * 2 + 1]; // FIXME: fill in lightmapST for completeness? } tess.numVertexes += surface->numVerts; - } - /* ============== RB_SurfaceFace ============== */ -void RB_SurfaceFace( srfSurfaceFace_t *surf ) { - int i, j, k; +void RB_SurfaceFace(srfSurfaceFace_t *surf) { + int i, j, k; unsigned int *indices; - glIndex_t *tessIndexes; - float *v; - float *normal; - int ndx; - int Bob; - int numPoints; - int dlightBits; - byteAlias_t ba; + glIndex_t *tessIndexes; + float *v; + float *normal; + int ndx; + int Bob; + int numPoints; + int dlightBits; + byteAlias_t ba; - RB_CHECKOVERFLOW( surf->numPoints, surf->numIndices ); + RB_CHECKOVERFLOW(surf->numPoints, surf->numIndices); dlightBits = surf->dlightBits; tess.dlightBits |= dlightBits; - indices = ( unsigned * ) ( ( ( char * ) surf ) + surf->ofsIndices ); + indices = (unsigned *)(((char *)surf) + surf->ofsIndices); Bob = tess.numVertexes; tessIndexes = tess.indexes + tess.numIndexes; - for ( i = surf->numIndices-1 ; i >= 0 ; i-- ) { + for (i = surf->numIndices - 1; i >= 0; i--) { tessIndexes[i] = indices[i] + Bob; } @@ -1324,33 +1254,28 @@ void RB_SurfaceFace( srfSurfaceFace_t *surf ) { numPoints = surf->numPoints; - //if ( tess.shader->needsNormal ) + // if ( tess.shader->needsNormal ) { normal = surf->plane.normal; - for ( i = 0, ndx = tess.numVertexes; i < numPoints; i++, ndx++ ) { - VectorCopy( normal, tess.normal[ndx] ); + for (i = 0, ndx = tess.numVertexes; i < numPoints; i++, ndx++) { + VectorCopy(normal, tess.normal[ndx]); } } - for ( i = 0, v = surf->points[0], ndx = tess.numVertexes; i < numPoints; i++, v += VERTEXSIZE, ndx++ ) - { - VectorCopy( v, tess.xyz[ndx]); + for (i = 0, v = surf->points[0], ndx = tess.numVertexes; i < numPoints; i++, v += VERTEXSIZE, ndx++) { + VectorCopy(v, tess.xyz[ndx]); tess.texCoords[ndx][0][0] = v[3]; tess.texCoords[ndx][0][1] = v[4]; - for(k=0;klightmapIndex[k] >= 0) - { - tess.texCoords[ndx][k+1][0] = v[VERTEX_LM+(k*2)]; - tess.texCoords[ndx][k+1][1] = v[VERTEX_LM+(k*2)+1]; - } - else - { + for (k = 0; k < MAXLIGHTMAPS; k++) { + if (tess.shader->lightmapIndex[k] >= 0) { + tess.texCoords[ndx][k + 1][0] = v[VERTEX_LM + (k * 2)]; + tess.texCoords[ndx][k + 1][1] = v[VERTEX_LM + (k * 2) + 1]; + } else { break; } } - ba.ui = ComputeFinalVertexColor( (byte *)&v[VERTEX_COLOR] ); - for ( j=0; j<4; j++ ) + ba.ui = ComputeFinalVertexColor((byte *)&v[VERTEX_COLOR]); + for (j = 0; j < 4; j++) tess.vertexColors[ndx][j] = ba.b[j]; tess.vertexDlightBits[ndx] = dlightBits; } @@ -1358,31 +1283,27 @@ void RB_SurfaceFace( srfSurfaceFace_t *surf ) { tess.numVertexes += surf->numPoints; } - -static float LodErrorForVolume( vec3_t local, float radius ) { - vec3_t world; - float d; +static float LodErrorForVolume(vec3_t local, float radius) { + vec3_t world; + float d; // never let it go negative - if ( r_lodCurveError->value < 0 ) { + if (r_lodCurveError->value < 0) { return 0; } - world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + - local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; - world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + - local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; - world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + - local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; + world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; + world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; + world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; - VectorSubtract( world, backEnd.viewParms.ori.origin, world ); - d = DotProduct( world, backEnd.viewParms.ori.axis[0] ); + VectorSubtract(world, backEnd.viewParms.ori.origin, world); + d = DotProduct(world, backEnd.viewParms.ori.axis[0]); - if ( d < 0 ) { + if (d < 0) { d = -d; } d -= radius; - if ( d < 1 ) { + if (d < 1) { d = 1; } @@ -1396,79 +1317,78 @@ RB_SurfaceGrid Just copy the grid of points and triangulate ============= */ -void RB_SurfaceGrid( srfGridMesh_t *cv ) { - int i, j, k; - float *xyz; - float *texCoords; - float *normal; +void RB_SurfaceGrid(srfGridMesh_t *cv) { + int i, j, k; + float *xyz; + float *texCoords; + float *normal; unsigned char *color; - drawVert_t *dv; - int rows, irows, vrows; - int used; - int widthTable[MAX_GRID_SIZE]; - int heightTable[MAX_GRID_SIZE]; - float lodError; - int lodWidth, lodHeight; - int numVertexes; - int dlightBits; - int *vDlightBits; + drawVert_t *dv; + int rows, irows, vrows; + int used; + int widthTable[MAX_GRID_SIZE]; + int heightTable[MAX_GRID_SIZE]; + float lodError; + int lodWidth, lodHeight; + int numVertexes; + int dlightBits; + int *vDlightBits; dlightBits = cv->dlightBits; tess.dlightBits |= dlightBits; // determine the allowable discrepance - lodError = LodErrorForVolume( cv->lodOrigin, cv->lodRadius ); + lodError = LodErrorForVolume(cv->lodOrigin, cv->lodRadius); // determine which rows and columns of the subdivision // we are actually going to use widthTable[0] = 0; lodWidth = 1; - for ( i = 1 ; i < cv->width-1 ; i++ ) { - if ( cv->widthLodError[i] <= lodError ) { + for (i = 1; i < cv->width - 1; i++) { + if (cv->widthLodError[i] <= lodError) { widthTable[lodWidth] = i; lodWidth++; } } - widthTable[lodWidth] = cv->width-1; + widthTable[lodWidth] = cv->width - 1; lodWidth++; heightTable[0] = 0; lodHeight = 1; - for ( i = 1 ; i < cv->height-1 ; i++ ) { - if ( cv->heightLodError[i] <= lodError ) { + for (i = 1; i < cv->height - 1; i++) { + if (cv->heightLodError[i] <= lodError) { heightTable[lodHeight] = i; lodHeight++; } } - heightTable[lodHeight] = cv->height-1; + heightTable[lodHeight] = cv->height - 1; lodHeight++; - // very large grids may have more points or indexes than can be fit // in the tess structure, so we may have to issue it in multiple passes used = 0; rows = 0; - while ( used < lodHeight - 1 ) { + while (used < lodHeight - 1) { // see how many rows of both verts and indexes we can add without overflowing do { - vrows = ( SHADER_MAX_VERTEXES - tess.numVertexes ) / lodWidth; - irows = ( SHADER_MAX_INDEXES - tess.numIndexes ) / ( lodWidth * 6 ); + vrows = (SHADER_MAX_VERTEXES - tess.numVertexes) / lodWidth; + irows = (SHADER_MAX_INDEXES - tess.numIndexes) / (lodWidth * 6); // if we don't have enough space for at least one strip, flush the buffer - if ( vrows < 2 || irows < 1 ) { + if (vrows < 2 || irows < 1) { RB_EndSurface(); - RB_BeginSurface(tess.shader, tess.fogNum ); + RB_BeginSurface(tess.shader, tess.fogNum); } else { break; } - } while ( 1 ); + } while (1); rows = irows; - if ( vrows < irows + 1 ) { + if (vrows < irows + 1) { rows = vrows - 1; } - if ( used + rows > lodHeight ) { + if (used + rows > lodHeight) { rows = lodHeight - used; } @@ -1477,13 +1397,12 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { xyz = tess.xyz[numVertexes]; normal = tess.normal[numVertexes]; texCoords = tess.texCoords[numVertexes][0]; - color = ( unsigned char * ) &tess.vertexColors[numVertexes]; + color = (unsigned char *)&tess.vertexColors[numVertexes]; vDlightBits = &tess.vertexDlightBits[numVertexes]; - for ( i = 0 ; i < rows ; i++ ) { - for ( j = 0 ; j < lodWidth ; j++ ) { - dv = cv->verts + heightTable[ used + i ] * cv->width - + widthTable[ j ]; + for (i = 0; i < rows; i++) { + for (j = 0; j < lodWidth; j++) { + dv = cv->verts + heightTable[used + i] * cv->width + widthTable[j]; xyz[0] = dv->xyz[0]; xyz[1] = dv->xyz[1]; @@ -1492,14 +1411,13 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { texCoords[0] = dv->st[0]; texCoords[1] = dv->st[1]; - for(k=0;klightmap[k][0]; - texCoords[2+(k*2)+1]= dv->lightmap[k][1]; + for (k = 0; k < MAXLIGHTMAPS; k++) { + texCoords[2 + (k * 2)] = dv->lightmap[k][0]; + texCoords[2 + (k * 2) + 1] = dv->lightmap[k][1]; } - texCoords += NUM_TEX_COORDS*2; + texCoords += NUM_TEX_COORDS * 2; - //if ( needsNormal ) + // if ( needsNormal ) { normal[0] = dv->normal[0]; normal[1] = dv->normal[1]; @@ -1515,29 +1433,29 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { // add the indexes { - int numIndexes; - int w, h; + int numIndexes; + int w, h; h = rows - 1; w = lodWidth - 1; numIndexes = tess.numIndexes; - for (i = 0 ; i < h ; i++) { - for (j = 0 ; j < w ; j++) { - int v1, v2, v3, v4; + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) { + int v1, v2, v3, v4; // vertex order to be reckognized as tristrips - v1 = numVertexes + i*lodWidth + j + 1; + v1 = numVertexes + i * lodWidth + j + 1; v2 = v1 - 1; v3 = v2 + lodWidth; v4 = v3 + 1; tess.indexes[numIndexes] = v2; - tess.indexes[numIndexes+1] = v3; - tess.indexes[numIndexes+2] = v1; + tess.indexes[numIndexes + 1] = v3; + tess.indexes[numIndexes + 2] = v1; - tess.indexes[numIndexes+3] = v1; - tess.indexes[numIndexes+4] = v3; - tess.indexes[numIndexes+5] = v4; + tess.indexes[numIndexes + 3] = v1; + tess.indexes[numIndexes + 4] = v3; + tess.indexes[numIndexes + 5] = v4; numIndexes += 6; } } @@ -1551,7 +1469,6 @@ void RB_SurfaceGrid( srfGridMesh_t *cv ) { } } - /* =========================================================================== @@ -1567,22 +1484,22 @@ RB_SurfaceAxis Draws x/y/z lines from the origin for orientation debugging =================== */ -static void RB_SurfaceAxis( void ) { - GL_Bind( tr.whiteImage ); - GL_State( GLS_DEFAULT ); - qglLineWidth( 3 ); - qglBegin( GL_LINES ); - qglColor3f( 1,0,0 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 16,0,0 ); - qglColor3f( 0,1,0 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 0,16,0 ); - qglColor3f( 0,0,1 ); - qglVertex3f( 0,0,0 ); - qglVertex3f( 0,0,16 ); +static void RB_SurfaceAxis(void) { + GL_Bind(tr.whiteImage); + GL_State(GLS_DEFAULT); + qglLineWidth(3); + qglBegin(GL_LINES); + qglColor3f(1, 0, 0); + qglVertex3f(0, 0, 0); + qglVertex3f(16, 0, 0); + qglColor3f(0, 1, 0); + qglVertex3f(0, 0, 0); + qglVertex3f(0, 16, 0); + qglColor3f(0, 0, 1); + qglVertex3f(0, 0, 0); + qglVertex3f(0, 0, 16); qglEnd(); - qglLineWidth( 1 ); + qglLineWidth(1); } //=========================================================================== @@ -1594,8 +1511,8 @@ RB_SurfaceEntity Entities that have a single procedurally generated surface ==================== */ -void RB_SurfaceEntity( surfaceType_t *surfType ) { - switch( backEnd.currentEntity->e.reType ) { +void RB_SurfaceEntity(surfaceType_t *surfType) { + switch (backEnd.currentEntity->e.reType) { case RT_SPRITE: RB_SurfaceSprite(); break; @@ -1620,31 +1537,28 @@ void RB_SurfaceEntity( surfaceType_t *surfType ) { case RT_CYLINDER: RB_SurfaceCylinder(); break; - case RT_ENT_CHAIN: - { - int i, count, start; - static trRefEntity_t tempEnt = *backEnd.currentEntity; - //rww - if not static then currentEntity is garbage because - //this is a local. This was not static in sof2.. but I guess - //they never check ce.renderfx so it didn't show up. + case RT_ENT_CHAIN: { + int i, count, start; + static trRefEntity_t tempEnt = *backEnd.currentEntity; + // rww - if not static then currentEntity is garbage because + // this is a local. This was not static in sof2.. but I guess + // they never check ce.renderfx so it didn't show up. - start = backEnd.currentEntity->e.uRefEnt.uMini.miniStart; - count = backEnd.currentEntity->e.uRefEnt.uMini.miniCount; - assert(count > 0); - backEnd.currentEntity = &tempEnt; + start = backEnd.currentEntity->e.uRefEnt.uMini.miniStart; + count = backEnd.currentEntity->e.uRefEnt.uMini.miniCount; + assert(count > 0); + backEnd.currentEntity = &tempEnt; - assert(backEnd.currentEntity->e.renderfx >= 0); + assert(backEnd.currentEntity->e.renderfx >= 0); - for(i=0;ie, &backEnd.refdef.miniEntities[start+i], sizeof(backEnd.refdef.miniEntities[start+i])); + for (i = 0; i < count; i++) { + memcpy(&backEnd.currentEntity->e, &backEnd.refdef.miniEntities[start + i], sizeof(backEnd.refdef.miniEntities[start + i])); - assert(backEnd.currentEntity->e.renderfx >= 0); + assert(backEnd.currentEntity->e.renderfx >= 0); - RB_SurfaceEntity(surfType); - } + RB_SurfaceEntity(surfType); } - break; + } break; default: RB_SurfaceAxis(); break; @@ -1652,9 +1566,7 @@ void RB_SurfaceEntity( surfaceType_t *surfType ) { return; } -void RB_SurfaceBad( surfaceType_t *surfType ) { - ri.Printf( PRINT_ALL, "Bad surface tesselated.\n" ); -} +void RB_SurfaceBad(surfaceType_t *surfType) { ri.Printf(PRINT_ALL, "Bad surface tesselated.\n"); } /* ================== @@ -1663,75 +1575,72 @@ RB_TestZFlare This is called at surface tesselation time ================== */ -static bool RB_TestZFlare( vec3_t point) { - int i; - vec4_t eye, clip, normalized, window; +static bool RB_TestZFlare(vec3_t point) { + int i; + vec4_t eye, clip, normalized, window; // if the point is off the screen, don't bother adding it // calculate screen coordinates and depth - R_TransformModelToClip( point, backEnd.ori.modelMatrix, - backEnd.viewParms.projectionMatrix, eye, clip ); + R_TransformModelToClip(point, backEnd.ori.modelMatrix, backEnd.viewParms.projectionMatrix, eye, clip); // check to see if the point is completely off screen - for ( i = 0 ; i < 3 ; i++ ) { - if ( clip[i] >= clip[3] || clip[i] <= -clip[3] ) { + for (i = 0; i < 3; i++) { + if (clip[i] >= clip[3] || clip[i] <= -clip[3]) { return qfalse; } } - R_TransformClipToWindow( clip, &backEnd.viewParms, normalized, window ); + R_TransformClipToWindow(clip, &backEnd.viewParms, normalized, window); - if ( window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth - || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight ) { - return qfalse; // shouldn't happen, since we check the clip[] above, except for FP rounding + if (window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight) { + return qfalse; // shouldn't happen, since we check the clip[] above, except for FP rounding } -//do test - float depth = 0.0f; - bool visible; - float screenZ; + // do test + float depth = 0.0f; + bool visible; + float screenZ; // read back the z buffer contents - if ( r_flares->integer !=1 ) { //skipping the the z-test + if (r_flares->integer != 1) { // skipping the the z-test return true; } // doing a readpixels is as good as doing a glFinish(), so // don't bother with another sync glState.finishCalled = qfalse; - qglReadPixels( backEnd.viewParms.viewportX + window[0],backEnd.viewParms.viewportY + window[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth ); + qglReadPixels(backEnd.viewParms.viewportX + window[0], backEnd.viewParms.viewportY + window[1], 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth); - screenZ = backEnd.viewParms.projectionMatrix[14] / - ( ( 2*depth - 1 ) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10] ); + screenZ = backEnd.viewParms.projectionMatrix[14] / ((2 * depth - 1) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10]); - visible = ( -eye[2] - -screenZ ) < 24; + visible = (-eye[2] - -screenZ) < 24; return visible; } -void RB_SurfaceFlare( srfFlare_t *surf ) { - vec3_t left, up; - float radius; - byte color[4]; - vec3_t dir; - vec3_t origin; - float d, dist; +void RB_SurfaceFlare(srfFlare_t *surf) { + vec3_t left, up; + float radius; + byte color[4]; + vec3_t dir; + vec3_t origin; + float d, dist; - if ( !r_flares->integer ) { + if (!r_flares->integer) { return; } - if (!RB_TestZFlare( surf->origin ) ) { + if (!RB_TestZFlare(surf->origin)) { return; } // calculate the xyz locations for the four corners - VectorMA( surf->origin, 3, surf->normal, origin ); - float* snormal = surf->normal; + VectorMA(surf->origin, 3, surf->normal, origin); + float *snormal = surf->normal; - VectorSubtract( origin, backEnd.viewParms.ori.origin, dir ); - dist = VectorNormalize( dir ); + VectorSubtract(origin, backEnd.viewParms.ori.origin, dir); + dist = VectorNormalize(dir); - d = -DotProduct( dir, snormal ); - if ( d < 0 ) { + d = -DotProduct(dir, snormal); + if (d < 0) { d = -d; } @@ -1740,53 +1649,48 @@ void RB_SurfaceFlare( srfFlare_t *surf ) { color[0] = d * 255; color[1] = d * 255; color[2] = d * 255; - color[3] = 255; //only gets used if the shader has cgen exact_vertex! + color[3] = 255; // only gets used if the shader has cgen exact_vertex! - radius = tess.shader->portalRange ? tess.shader->portalRange: 30; - if (dist < 512.0f) - { + radius = tess.shader->portalRange ? tess.shader->portalRange : 30; + if (dist < 512.0f) { radius = radius * dist / 512.0f; } - if (radius<5.0f) - { + if (radius < 5.0f) { radius = 5.0f; } - VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); - VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); - if ( backEnd.viewParms.isMirror ) { - VectorSubtract( vec3_origin, left, left ); + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); } - RB_AddQuadStamp( origin, left, up, color ); + RB_AddQuadStamp(origin, left, up, color); } - -void RB_SurfaceDisplayList( srfDisplayList_t *surf ) { +void RB_SurfaceDisplayList(srfDisplayList_t *surf) { // all appropriate state must be set in RB_BeginSurface // this isn't implemented yet... - qglCallList( surf->listNum ); -} - -void RB_SurfaceSkip( void *surf ) { + qglCallList(surf->listNum); } - -void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])( void *) = { - (void(*)(void*))RB_SurfaceBad, // SF_BAD, - (void(*)(void*))RB_SurfaceSkip, // SF_SKIP, - (void(*)(void*))RB_SurfaceFace, // SF_FACE, - (void(*)(void*))RB_SurfaceGrid, // SF_GRID, - (void(*)(void*))RB_SurfaceTriangles, // SF_TRIANGLES, - (void(*)(void*))RB_SurfacePolychain, // SF_POLY, - (void(*)(void*))RB_SurfaceMesh, // SF_MD3, -/* -Ghoul2 Insert Start -*/ - (void(*)(void*))RB_SurfaceGhoul, // SF_MDX, -/* -Ghoul2 Insert End -*/ - (void(*)(void*))RB_SurfaceFlare, // SF_FLARE, - (void(*)(void*))RB_SurfaceEntity, // SF_ENTITY - (void(*)(void*))RB_SurfaceDisplayList // SF_DISPLAY_LIST +void RB_SurfaceSkip(void *surf) {} + +void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *) = { + (void (*)(void *))RB_SurfaceBad, // SF_BAD, + (void (*)(void *))RB_SurfaceSkip, // SF_SKIP, + (void (*)(void *))RB_SurfaceFace, // SF_FACE, + (void (*)(void *))RB_SurfaceGrid, // SF_GRID, + (void (*)(void *))RB_SurfaceTriangles, // SF_TRIANGLES, + (void (*)(void *))RB_SurfacePolychain, // SF_POLY, + (void (*)(void *))RB_SurfaceMesh, // SF_MD3, + /* + Ghoul2 Insert Start + */ + (void (*)(void *))RB_SurfaceGhoul, // SF_MDX, + /* + Ghoul2 Insert End + */ + (void (*)(void *))RB_SurfaceFlare, // SF_FLARE, + (void (*)(void *))RB_SurfaceEntity, // SF_ENTITY + (void (*)(void *))RB_SurfaceDisplayList // SF_DISPLAY_LIST }; diff --git a/codemp/rd-vanilla/tr_surfacesprites.cpp b/codemp/rd-vanilla/tr_surfacesprites.cpp index 0a02f21051..3d4d34cc48 100644 --- a/codemp/rd-vanilla/tr_surfacesprites.cpp +++ b/codemp/rd-vanilla/tr_surfacesprites.cpp @@ -27,7 +27,6 @@ along with this program; if not, see . #include "tr_quicksprite.h" #include "tr_WorldEffects.h" - /////===== Part of the VERTIGON system =====///// // The surfacesprites are a simple system. When a polygon with this shader stage on it is drawn, // there are randomly distributed images (defined by the shader stage) placed on the surface. @@ -36,86 +35,65 @@ along with this program; if not, see . // The vertigons are applied as part of the renderer backend. That is, they access OpenGL calls directly. - unsigned char randomindex, randominterval; const float randomchart[256] = { - 0.6554f, 0.6909f, 0.4806f, 0.6218f, 0.5717f, 0.3896f, 0.0677f, 0.7356f, - 0.8333f, 0.1105f, 0.4445f, 0.8161f, 0.4689f, 0.0433f, 0.7152f, 0.0336f, - 0.0186f, 0.9140f, 0.1626f, 0.6553f, 0.8340f, 0.7094f, 0.2020f, 0.8087f, - 0.9119f, 0.8009f, 0.1339f, 0.8492f, 0.9173f, 0.5003f, 0.6012f, 0.6117f, - 0.5525f, 0.5787f, 0.1586f, 0.3293f, 0.9273f, 0.7791f, 0.8589f, 0.4985f, - 0.0883f, 0.8545f, 0.2634f, 0.4727f, 0.3624f, 0.1631f, 0.7825f, 0.0662f, - 0.6704f, 0.3510f, 0.7525f, 0.9486f, 0.4685f, 0.1535f, 0.1545f, 0.1121f, - 0.4724f, 0.8483f, 0.3833f, 0.1917f, 0.8207f, 0.3885f, 0.9702f, 0.9200f, - 0.8348f, 0.7501f, 0.6675f, 0.4994f, 0.0301f, 0.5225f, 0.8011f, 0.1696f, - 0.5351f, 0.2752f, 0.2962f, 0.7550f, 0.5762f, 0.7303f, 0.2835f, 0.4717f, - 0.1818f, 0.2739f, 0.6914f, 0.7748f, 0.7640f, 0.8355f, 0.7314f, 0.5288f, - 0.7340f, 0.6692f, 0.6813f, 0.2810f, 0.8057f, 0.0648f, 0.8749f, 0.9199f, - 0.1462f, 0.5237f, 0.3014f, 0.4994f, 0.0278f, 0.4268f, 0.7238f, 0.5107f, - 0.1378f, 0.7303f, 0.7200f, 0.3819f, 0.2034f, 0.7157f, 0.5552f, 0.4887f, - 0.0871f, 0.3293f, 0.2892f, 0.4545f, 0.0088f, 0.1404f, 0.0275f, 0.0238f, - 0.0515f, 0.4494f, 0.7206f, 0.2893f, 0.6060f, 0.5785f, 0.4182f, 0.5528f, - 0.9118f, 0.8742f, 0.3859f, 0.6030f, 0.3495f, 0.4550f, 0.9875f, 0.6900f, - 0.6416f, 0.2337f, 0.7431f, 0.9788f, 0.6181f, 0.2464f, 0.4661f, 0.7621f, - 0.7020f, 0.8203f, 0.8869f, 0.2145f, 0.7724f, 0.6093f, 0.6692f, 0.9686f, - 0.5609f, 0.0310f, 0.2248f, 0.2950f, 0.2365f, 0.1347f, 0.2342f, 0.1668f, - 0.3378f, 0.4330f, 0.2775f, 0.9901f, 0.7053f, 0.7266f, 0.4840f, 0.2820f, - 0.5733f, 0.4555f, 0.6049f, 0.0770f, 0.4760f, 0.6060f, 0.4159f, 0.3427f, - 0.1234f, 0.7062f, 0.8569f, 0.1878f, 0.9057f, 0.9399f, 0.8139f, 0.1407f, - 0.1794f, 0.9123f, 0.9493f, 0.2827f, 0.9934f, 0.0952f, 0.4879f, 0.5160f, - 0.4118f, 0.4873f, 0.3642f, 0.7470f, 0.0866f, 0.5172f, 0.6365f, 0.2676f, - 0.2407f, 0.7223f, 0.5761f, 0.1143f, 0.7137f, 0.2342f, 0.3353f, 0.6880f, - 0.2296f, 0.6023f, 0.6027f, 0.4138f, 0.5408f, 0.9859f, 0.1503f, 0.7238f, - 0.6054f, 0.2477f, 0.6804f, 0.1432f, 0.4540f, 0.9776f, 0.8762f, 0.7607f, - 0.9025f, 0.9807f, 0.0652f, 0.8661f, 0.7663f, 0.2586f, 0.3994f, 0.0335f, - 0.7328f, 0.0166f, 0.9589f, 0.4348f, 0.5493f, 0.7269f, 0.6867f, 0.6614f, - 0.6800f, 0.7804f, 0.5591f, 0.8381f, 0.0910f, 0.7573f, 0.8985f, 0.3083f, - 0.3188f, 0.8481f, 0.2356f, 0.6736f, 0.4770f, 0.4560f, 0.6266f, 0.4677f -}; + 0.6554f, 0.6909f, 0.4806f, 0.6218f, 0.5717f, 0.3896f, 0.0677f, 0.7356f, 0.8333f, 0.1105f, 0.4445f, 0.8161f, 0.4689f, 0.0433f, 0.7152f, 0.0336f, + 0.0186f, 0.9140f, 0.1626f, 0.6553f, 0.8340f, 0.7094f, 0.2020f, 0.8087f, 0.9119f, 0.8009f, 0.1339f, 0.8492f, 0.9173f, 0.5003f, 0.6012f, 0.6117f, + 0.5525f, 0.5787f, 0.1586f, 0.3293f, 0.9273f, 0.7791f, 0.8589f, 0.4985f, 0.0883f, 0.8545f, 0.2634f, 0.4727f, 0.3624f, 0.1631f, 0.7825f, 0.0662f, + 0.6704f, 0.3510f, 0.7525f, 0.9486f, 0.4685f, 0.1535f, 0.1545f, 0.1121f, 0.4724f, 0.8483f, 0.3833f, 0.1917f, 0.8207f, 0.3885f, 0.9702f, 0.9200f, + 0.8348f, 0.7501f, 0.6675f, 0.4994f, 0.0301f, 0.5225f, 0.8011f, 0.1696f, 0.5351f, 0.2752f, 0.2962f, 0.7550f, 0.5762f, 0.7303f, 0.2835f, 0.4717f, + 0.1818f, 0.2739f, 0.6914f, 0.7748f, 0.7640f, 0.8355f, 0.7314f, 0.5288f, 0.7340f, 0.6692f, 0.6813f, 0.2810f, 0.8057f, 0.0648f, 0.8749f, 0.9199f, + 0.1462f, 0.5237f, 0.3014f, 0.4994f, 0.0278f, 0.4268f, 0.7238f, 0.5107f, 0.1378f, 0.7303f, 0.7200f, 0.3819f, 0.2034f, 0.7157f, 0.5552f, 0.4887f, + 0.0871f, 0.3293f, 0.2892f, 0.4545f, 0.0088f, 0.1404f, 0.0275f, 0.0238f, 0.0515f, 0.4494f, 0.7206f, 0.2893f, 0.6060f, 0.5785f, 0.4182f, 0.5528f, + 0.9118f, 0.8742f, 0.3859f, 0.6030f, 0.3495f, 0.4550f, 0.9875f, 0.6900f, 0.6416f, 0.2337f, 0.7431f, 0.9788f, 0.6181f, 0.2464f, 0.4661f, 0.7621f, + 0.7020f, 0.8203f, 0.8869f, 0.2145f, 0.7724f, 0.6093f, 0.6692f, 0.9686f, 0.5609f, 0.0310f, 0.2248f, 0.2950f, 0.2365f, 0.1347f, 0.2342f, 0.1668f, + 0.3378f, 0.4330f, 0.2775f, 0.9901f, 0.7053f, 0.7266f, 0.4840f, 0.2820f, 0.5733f, 0.4555f, 0.6049f, 0.0770f, 0.4760f, 0.6060f, 0.4159f, 0.3427f, + 0.1234f, 0.7062f, 0.8569f, 0.1878f, 0.9057f, 0.9399f, 0.8139f, 0.1407f, 0.1794f, 0.9123f, 0.9493f, 0.2827f, 0.9934f, 0.0952f, 0.4879f, 0.5160f, + 0.4118f, 0.4873f, 0.3642f, 0.7470f, 0.0866f, 0.5172f, 0.6365f, 0.2676f, 0.2407f, 0.7223f, 0.5761f, 0.1143f, 0.7137f, 0.2342f, 0.3353f, 0.6880f, + 0.2296f, 0.6023f, 0.6027f, 0.4138f, 0.5408f, 0.9859f, 0.1503f, 0.7238f, 0.6054f, 0.2477f, 0.6804f, 0.1432f, 0.4540f, 0.9776f, 0.8762f, 0.7607f, + 0.9025f, 0.9807f, 0.0652f, 0.8661f, 0.7663f, 0.2586f, 0.3994f, 0.0335f, 0.7328f, 0.0166f, 0.9589f, 0.4348f, 0.5493f, 0.7269f, 0.6867f, 0.6614f, + 0.6800f, 0.7804f, 0.5591f, 0.8381f, 0.0910f, 0.7573f, 0.8985f, 0.3083f, 0.3188f, 0.8481f, 0.2356f, 0.6736f, 0.4770f, 0.4560f, 0.6266f, 0.4677f}; #define WIND_DAMP_INTERVAL 50 #define WIND_GUST_TIME 2500.0 #define WIND_GUST_DECAY (1.0 / WIND_GUST_TIME) -int lastSSUpdateTime = 0; -float curWindSpeed=0; -float curWindGust=5; -float curWeatherAmount=1; -vec3_t curWindBlowVect={0,0,0}, targetWindBlowVect={0,0,0}; -vec3_t curWindGrassDir={0,0,0}, targetWindGrassDir={0,0,0}; -int totalsurfsprites=0, sssurfaces=0; +int lastSSUpdateTime = 0; +float curWindSpeed = 0; +float curWindGust = 5; +float curWeatherAmount = 1; +vec3_t curWindBlowVect = {0, 0, 0}, targetWindBlowVect = {0, 0, 0}; +vec3_t curWindGrassDir = {0, 0, 0}, targetWindGrassDir = {0, 0, 0}; +int totalsurfsprites = 0, sssurfaces = 0; -qboolean curWindPointActive=qfalse; +qboolean curWindPointActive = qfalse; float curWindPointForce = 0; vec3_t curWindPoint; -int nextGustTime=0; -float gustLeft=0; +int nextGustTime = 0; +float gustLeft = 0; -qboolean standardfovinitialized=qfalse; -float standardfovx = 90, standardscalex = 1.0; -float rangescalefactor=1.0; +qboolean standardfovinitialized = qfalse; +float standardfovx = 90, standardscalex = 1.0; +float rangescalefactor = 1.0; -vec3_t ssrightvectors[4]; -vec3_t ssfwdvector; -int rightvectorcount; +vec3_t ssrightvectors[4]; +vec3_t ssfwdvector; +int rightvectorcount; -trRefEntity_t *ssLastEntityDrawn=NULL; -vec3_t ssViewOrigin, ssViewRight, ssViewUp; +trRefEntity_t *ssLastEntityDrawn = NULL; +vec3_t ssViewOrigin, ssViewRight, ssViewUp; - -static void R_SurfaceSpriteFrameUpdate(void) -{ - float dtime, dampfactor; // Time since last update and damping time for wind changes +static void R_SurfaceSpriteFrameUpdate(void) { + float dtime, dampfactor; // Time since last update and damping time for wind changes float ratio; vec3_t ang, diff, retwindvec; float targetspeed; - vec3_t up={0,0,1}; + vec3_t up = {0, 0, 1}; if (backEnd.refdef.time == lastSSUpdateTime) return; - if (backEnd.refdef.time < lastSSUpdateTime) - { // Time is BEFORE the last update time, so reset everything. + if (backEnd.refdef.time < lastSSUpdateTime) { // Time is BEFORE the last update time, so reset everything. curWindGust = 5; curWindSpeed = r_windSpeed->value; nextGustTime = 0; @@ -128,34 +106,24 @@ static void R_SurfaceSpriteFrameUpdate(void) // Adjust for an FOV. If things look twice as wide on the screen, pretend the shaders have twice the range. // ASSUMPTION HERE IS THAT "standard" fov is the first one rendered. - if (!standardfovinitialized) - { // This isn't initialized yet. - if (backEnd.refdef.fov_x > 50 && backEnd.refdef.fov_x < 135) // I don't consider anything below 50 or above 135 to be "normal". + if (!standardfovinitialized) { // This isn't initialized yet. + if (backEnd.refdef.fov_x > 50 && backEnd.refdef.fov_x < 135) // I don't consider anything below 50 or above 135 to be "normal". { standardfovx = backEnd.refdef.fov_x; - standardscalex = tan(standardfovx * 0.5 * (M_PI/180.0f)); + standardscalex = tan(standardfovx * 0.5 * (M_PI / 180.0f)); standardfovinitialized = qtrue; - } - else - { + } else { standardfovx = 90; - standardscalex = tan(standardfovx * 0.5 * (M_PI/180.0f)); + standardscalex = tan(standardfovx * 0.5 * (M_PI / 180.0f)); } - rangescalefactor = 1.0; // Don't multiply the shader range by anything. - } - else if (standardfovx == backEnd.refdef.fov_x) - { // This is the standard FOV (or higher), don't multiply the shader range. + rangescalefactor = 1.0; // Don't multiply the shader range by anything. + } else if (standardfovx == backEnd.refdef.fov_x) { // This is the standard FOV (or higher), don't multiply the shader range. rangescalefactor = 1.0; - } - else - { // We are using a non-standard FOV. We need to multiply the range of the shader by a scale factor. - if (backEnd.refdef.fov_x > 135) - { - rangescalefactor = standardscalex / tan(135.0f * 0.5f * (M_PI/180.0f)); - } - else - { - rangescalefactor = standardscalex / tan(backEnd.refdef.fov_x * 0.5 * (M_PI/180.0f)); + } else { // We are using a non-standard FOV. We need to multiply the range of the shader by a scale factor. + if (backEnd.refdef.fov_x > 135) { + rangescalefactor = standardscalex / tan(135.0f * 0.5f * (M_PI / 180.0f)); + } else { + rangescalefactor = standardscalex / tan(backEnd.refdef.fov_x * 0.5 * (M_PI / 180.0f)); } } @@ -171,111 +139,90 @@ static void R_SurfaceSpriteFrameUpdate(void) VectorScale(ssViewRight, 0.866f, ssrightvectors[1]); VectorMA(ssrightvectors[1], -0.5f, ssfwdvector, ssrightvectors[1]); - // Right two has a big nudge forward (30 degrees). VectorScale(ssViewRight, 0.866f, ssrightvectors[2]); VectorMA(ssrightvectors[2], 0.5f, ssfwdvector, ssrightvectors[2]); - // Right three has a nudge back (10 degrees). VectorScale(ssViewRight, 0.985f, ssrightvectors[3]); VectorMA(ssrightvectors[3], -0.174f, ssfwdvector, ssrightvectors[3]); - // Update the wind. // If it is raining, get the windspeed from the rain system rather than the cvar - if (R_IsRaining() || R_IsPuffing()) - { + if (R_IsRaining() || R_IsPuffing()) { curWeatherAmount = 1.0; - } - else - { + } else { curWeatherAmount = r_surfaceWeather->value; } - if (R_GetWindSpeed(targetspeed)) - { // We successfully got a speed from the rain system. + if (R_GetWindSpeed(targetspeed)) { // We successfully got a speed from the rain system. // Set the windgust to 5, since that looks pretty good. targetspeed *= 0.3f; - if (targetspeed >= 1.0) - { - curWindGust = 300/targetspeed; - } - else - { + if (targetspeed >= 1.0) { + curWindGust = 300 / targetspeed; + } else { curWindGust = 0; } - } - else - { // Use the cvar. - targetspeed = r_windSpeed->value; // Minimum gust delay, in seconds. + } else { // Use the cvar. + targetspeed = r_windSpeed->value; // Minimum gust delay, in seconds. curWindGust = r_windGust->value; } - if (targetspeed > 0 && curWindGust) - { - if (gustLeft > 0) - { // We are gusting + if (targetspeed > 0 && curWindGust) { + if (gustLeft > 0) { // We are gusting // Add an amount to the target wind speed targetspeed *= 1.0 + gustLeft; - gustLeft -= (float)(backEnd.refdef.time - lastSSUpdateTime)*WIND_GUST_DECAY; - if (gustLeft <= 0) - { - nextGustTime = backEnd.refdef.time + (curWindGust*1000)*flrand(1.0f,4.0f); + gustLeft -= (float)(backEnd.refdef.time - lastSSUpdateTime) * WIND_GUST_DECAY; + if (gustLeft <= 0) { + nextGustTime = backEnd.refdef.time + (curWindGust * 1000) * flrand(1.0f, 4.0f); } - } - else if (backEnd.refdef.time >= nextGustTime) - { // See if there is another right now + } else if (backEnd.refdef.time >= nextGustTime) { // See if there is another right now // Gust next time, mano - gustLeft = flrand(0.75f,1.5f); + gustLeft = flrand(0.75f, 1.5f); } } // See if there is a weather system that will tell us a windspeed. - if (R_GetWindVector(retwindvec)) - { - retwindvec[2]=0; + if (R_GetWindVector(retwindvec)) { + retwindvec[2] = 0; VectorScale(retwindvec, -1.0f, retwindvec); vectoangles(retwindvec, ang); - } - else - { // Calculate the target wind vector based off cvars + } else { // Calculate the target wind vector based off cvars ang[YAW] = r_windAngle->value; } ang[PITCH] = -90.0 + targetspeed; - if (ang[PITCH]>-45.0) - { + if (ang[PITCH] > -45.0) { ang[PITCH] = -45.0; } ang[ROLL] = 0; - if (targetspeed>0) - { -// ang[YAW] += cos(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; -// ang[PITCH] += sin(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; + if (targetspeed > 0) { + // ang[YAW] += cos(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; + // ang[PITCH] += sin(tr.refdef.time*0.01+flrand(-1.0,1.0))*targetspeed*0.5; } // Get the grass wind vector first AngleVectors(ang, targetWindGrassDir, NULL, NULL); - targetWindGrassDir[2]-=1.0; -// VectorScale(targetWindGrassDir, targetspeed, targetWindGrassDir); + targetWindGrassDir[2] -= 1.0; + // VectorScale(targetWindGrassDir, targetspeed, targetWindGrassDir); // Now get the general wind vector (no pitch) - ang[PITCH]=0; + ang[PITCH] = 0; AngleVectors(ang, targetWindBlowVect, NULL, NULL); // Start calculating a smoothing factor so wind doesn't change abruptly between speeds. - dampfactor = 1.0-r_windDampFactor->value; // We must exponent the amount LEFT rather than the amount bled off - dtime = (float)(backEnd.refdef.time - lastSSUpdateTime) * (1.0/(float)WIND_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". + dampfactor = 1.0 - r_windDampFactor->value; // We must exponent the amount LEFT rather than the amount bled off + dtime = + (float)(backEnd.refdef.time - lastSSUpdateTime) * (1.0 / (float)WIND_DAMP_INTERVAL); // Our dampfactor is geared towards a time interval equal to "1". // Note that since there are a finite number of "practical" delta millisecond values possible, // the ratio should be initialized into a chart ultimately. ratio = pow(dampfactor, dtime); // Apply this ratio to the windspeed... - curWindSpeed = targetspeed - (ratio * (targetspeed-curWindSpeed)); + curWindSpeed = targetspeed - (ratio * (targetspeed - curWindSpeed)); // Use the curWindSpeed to calculate the final target wind vector (with speed) VectorScale(targetWindBlowVect, curWindSpeed, targetWindBlowVect); @@ -289,144 +236,120 @@ static void R_SurfaceSpriteFrameUpdate(void) lastSSUpdateTime = backEnd.refdef.time; curWindPointForce = r_windPointForce->value - (ratio * (r_windPointForce->value - curWindPointForce)); - if (curWindPointForce < 0.01) - { + if (curWindPointForce < 0.01) { curWindPointActive = qfalse; - } - else - { + } else { curWindPointActive = qtrue; curWindPoint[0] = r_windPointX->value; curWindPoint[1] = r_windPointY->value; curWindPoint[2] = 0; } - if (r_surfaceSprites->integer >= 2) - { - ri.Printf( PRINT_ALL, "Surfacesprites Drawn: %d, on %d surfaces\n", totalsurfsprites, sssurfaces); + if (r_surfaceSprites->integer >= 2) { + ri.Printf(PRINT_ALL, "Surfacesprites Drawn: %d, on %d surfaces\n", totalsurfsprites, sssurfaces); } - totalsurfsprites=0; - sssurfaces=0; + totalsurfsprites = 0; + sssurfaces = 0; } - - ///////////////////////////////////////////// // Surface sprite calculation and drawing. ///////////////////////////////////////////// -#define FADE_RANGE 250.0 -#define WINDPOINT_RADIUS 750.0 +#define FADE_RANGE 250.0 +#define WINDPOINT_RADIUS 750.0 float SSVertAlpha[SHADER_MAX_VERTEXES]; float SSVertWindForce[SHADER_MAX_VERTEXES]; vec2_t SSVertWindDir[SHADER_MAX_VERTEXES]; -qboolean SSAdditiveTransparency=qfalse; -qboolean SSUsingFog=qfalse; - +qboolean SSAdditiveTransparency = qfalse; +qboolean SSUsingFog = qfalse; ///////////////////////////////////////////// // Vertical surface sprites -static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte light, - byte alpha, float wind, float windidle, vec2_t fog, int hangdown, vec2_t skew, bool flattened) -{ +static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float wind, float windidle, vec2_t fog, int hangdown, + vec2_t skew, bool flattened) { vec3_t loc2, right; float angle; float windsway; float points[16]; color4ub_t color; - angle = ((loc[0]+loc[1])*0.02+(tr.refdef.time*0.0015)); + angle = ((loc[0] + loc[1]) * 0.02 + (tr.refdef.time * 0.0015)); - if (windidle>0.0) - { - windsway = (height*windidle*0.075); - loc2[0] = loc[0]+skew[0]+cos(angle)*windsway; - loc2[1] = loc[1]+skew[1]+sin(angle)*windsway; + if (windidle > 0.0) { + windsway = (height * windidle * 0.075); + loc2[0] = loc[0] + skew[0] + cos(angle) * windsway; + loc2[1] = loc[1] + skew[1] + sin(angle) * windsway; - if (hangdown) - { - loc2[2] = loc[2]-height; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } - else - { - loc2[2] = loc[2]+height; - } - } - else - { - loc2[0] = loc[0]+skew[0]; - loc2[1] = loc[1]+skew[1]; - if (hangdown) - { - loc2[2] = loc[2]-height; - } - else - { - loc2[2] = loc[2]+height; + } else { + loc2[0] = loc[0] + skew[0]; + loc2[1] = loc[1] + skew[1]; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } } - if (wind>0.0 && curWindSpeed > 0.001) - { - windsway = (height*wind*0.075); + if (wind > 0.0 && curWindSpeed > 0.001) { + windsway = (height * wind * 0.075); // Add the angle - VectorMA(loc2, height*wind, curWindGrassDir, loc2); + VectorMA(loc2, height * wind, curWindGrassDir, loc2); // Bob up and down - if (curWindSpeed < 40.0) - { - windsway *= curWindSpeed*(1.0/100.0); - } - else - { + if (curWindSpeed < 40.0) { + windsway *= curWindSpeed * (1.0 / 100.0); + } else { windsway *= 0.4f; } - loc2[2] += sin(angle*2.5)*windsway; + loc2[2] += sin(angle * 2.5) * windsway; } - if ( flattened ) - { - right[0] = sin( DEG2RAD( loc[0] ) ) * width; - right[1] = cos( DEG2RAD( loc[0] ) ) * height; + if (flattened) { + right[0] = sin(DEG2RAD(loc[0])) * width; + right[1] = cos(DEG2RAD(loc[0])) * height; right[2] = 0.0f; - } - else - { - VectorScale(ssrightvectors[rightvectorcount], width*0.5, right); + } else { + VectorScale(ssrightvectors[rightvectorcount], width * 0.5, right); } - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; // Bottom right -// VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right -// VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left -// VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0] + ssfwdvector[0] * width * 0.2; points[9] = loc2[1] - right[1] + ssfwdvector[1] * width * 0.2; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left -// VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -436,10 +359,8 @@ static void RB_VerticalSurfaceSprite(vec3_t loc, float width, float height, byte SQuickSprite.Add(points, color, fog); } -static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float height, byte light, - byte alpha, float wind, float windidle, vec2_t fog, - int hangdown, vec2_t skew, vec2_t winddiff, float windforce, bool flattened) -{ +static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float height, byte light, byte alpha, float wind, float windidle, vec2_t fog, + int hangdown, vec2_t skew, vec2_t winddiff, float windforce, bool flattened) { vec3_t loc2, right; float angle; float windsway; @@ -449,80 +370,69 @@ static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float hei if (windforce > 1) windforce = 1; -// wind += 1.0-windforce; + // wind += 1.0-windforce; - angle = (loc[0]+loc[1])*0.02+(tr.refdef.time*0.0015); + angle = (loc[0] + loc[1]) * 0.02 + (tr.refdef.time * 0.0015); - if (curWindSpeed <80.0) - { - windsway = (height*windidle*0.1)*(1.0+windforce); - loc2[0] = loc[0]+skew[0]+cos(angle)*windsway; - loc2[1] = loc[1]+skew[1]+sin(angle)*windsway; - } - else - { - loc2[0] = loc[0]+skew[0]; - loc2[1] = loc[1]+skew[1]; + if (curWindSpeed < 80.0) { + windsway = (height * windidle * 0.1) * (1.0 + windforce); + loc2[0] = loc[0] + skew[0] + cos(angle) * windsway; + loc2[1] = loc[1] + skew[1] + sin(angle) * windsway; + } else { + loc2[0] = loc[0] + skew[0]; + loc2[1] = loc[1] + skew[1]; } - if (hangdown) - { - loc2[2] = loc[2]-height; - } - else - { - loc2[2] = loc[2]+height; + if (hangdown) { + loc2[2] = loc[2] - height; + } else { + loc2[2] = loc[2] + height; } - if (curWindSpeed > 0.001) - { + if (curWindSpeed > 0.001) { // Add the angle - VectorMA(loc2, height*wind, curWindGrassDir, loc2); + VectorMA(loc2, height * wind, curWindGrassDir, loc2); } - loc2[0] += height*winddiff[0]*windforce; - loc2[1] += height*winddiff[1]*windforce; - loc2[2] -= height*windforce*(0.75 + 0.15*sin((tr.refdef.time + 500*windforce)*0.01)); + loc2[0] += height * winddiff[0] * windforce; + loc2[1] += height * winddiff[1] * windforce; + loc2[2] -= height * windforce * (0.75 + 0.15 * sin((tr.refdef.time + 500 * windforce) * 0.01)); - if ( flattened ) - { - right[0] = sin( DEG2RAD( loc[0] ) ) * width; - right[1] = cos( DEG2RAD( loc[0] ) ) * height; + if (flattened) { + right[0] = sin(DEG2RAD(loc[0])) * width; + right[1] = cos(DEG2RAD(loc[0])) * height; right[2] = 0.0f; - } - else - { - VectorScale(ssrightvectors[rightvectorcount], width*0.5, right); + } else { + VectorScale(ssrightvectors[rightvectorcount], width * 0.5, right); } - - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; // Bottom right -// VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right -// VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left -// VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0] + ssfwdvector[0] * width * 0.15; points[9] = loc2[1] - right[1] + ssfwdvector[1] * width * 0.15; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left -// VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -532,23 +442,22 @@ static void RB_VerticalSurfaceSpriteWindPoint(vec3_t loc, float width, float hei SQuickSprite.Add(points, color, fog); } -static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawVerticalSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; vec2_t fog1, fog2, fog3; vec2_t winddiff1, winddiff2, winddiff3; - float windforce1, windforce2, windforce3; + float windforce1, windforce2, windforce3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; vec3_t curpoint; float width, height; @@ -556,145 +465,118 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ byte randomindex2; - vec2_t skew={0,0}; + vec2_t skew = {0, 0}; vec2_t fogv; vec2_t winddiffv; - float windforce=0; - qboolean usewindpoint = (qboolean) !! (curWindPointActive && stage->ss->wind > 0); + float windforce = 0; + qboolean usewindpoint = (qboolean) !!(curWindPointActive && stage->ss->wind > 0); - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); + float faderange = FADE_RANGE / (cutdist - fadedist); - if (faderange > 1.0) - { // Don't want to force a new fade_rand + if (faderange > 1.0) { // Don't want to force a new fade_rand faderange = 1.0; } // Quickly calc all the alphas and windstuff for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0 - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; } // Wind only needs initialization once per tess. - if (usewindpoint && !tess.SSInitializedWind) - { - for (curvert=0; curvertnumVertexes;curvert++) - { // Calc wind at each point - dist[0]=input->xyz[curvert][0] - curWindPoint[0]; - dist[1]=input->xyz[curvert][1] - curWindPoint[1]; - step = (dist[0]*dist[0] + dist[1]*dist[1]); // dist squared - - if (step >= (float)(WINDPOINT_RADIUS*WINDPOINT_RADIUS)) - { // No wind + if (usewindpoint && !tess.SSInitializedWind) { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc wind at each point + dist[0] = input->xyz[curvert][0] - curWindPoint[0]; + dist[1] = input->xyz[curvert][1] - curWindPoint[1]; + step = (dist[0] * dist[0] + dist[1] * dist[1]); // dist squared + + if (step >= (float)(WINDPOINT_RADIUS * WINDPOINT_RADIUS)) { // No wind SSVertWindDir[curvert][0] = 0; SSVertWindDir[curvert][1] = 0; - SSVertWindForce[curvert]=0; // Should be < 1 - } - else - { - if (step<1) - { // Don't want to divide by zero + SSVertWindForce[curvert] = 0; // Should be < 1 + } else { + if (step < 1) { // Don't want to divide by zero SSVertWindDir[curvert][0] = 0; SSVertWindDir[curvert][1] = 0; SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind; - } - else - { - step = Q_rsqrt(step); // Equals 1 over the distance. + } else { + step = Q_rsqrt(step); // Equals 1 over the distance. SSVertWindDir[curvert][0] = dist[0] * step; SSVertWindDir[curvert][1] = dist[1] * step; - step = 1.0 - (1.0 / (step * WINDPOINT_RADIUS)); // 1- (dist/maxradius) = a scale from 0 to 1 linearly dropping off - SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind * step; // *step means divide by the distance. + step = 1.0 - (1.0 / (step * WINDPOINT_RADIUS)); // 1- (dist/maxradius) = a scale from 0 to 1 linearly dropping off + SSVertWindForce[curvert] = curWindPointForce * stage->ss->wind * step; // *step means divide by the distance. } } } tess.SSInitializedWind = qtrue; } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - fog1[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog1[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog1[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog1[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff1[0] = SSVertWindDir[curvert][0]; winddiff1[1] = SSVertWindDir[curvert][1]; windforce1 = SSVertWindForce[curvert]; - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - fog2[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog2[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog2[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog2[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff2[0] = SSVertWindDir[curvert][0]; winddiff2[1] = SSVertWindDir[curvert][1]; windforce2 = SSVertWindForce[curvert]; - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (stage->ss->facing) - { // Hang down - if (input->normal[curvert][2] > -0.5) - { + if (stage->ss->facing) { // Hang down + if (input->normal[curvert][2] > -0.5) { continue; } - } - else - { // Point up - if (input->normal[curvert][2] < 0.5) - { + } else { // Point up + if (input->normal[curvert][2] < 0.5) { continue; } } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - fog3[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog3[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog3[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog3[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); winddiff3[0] = SSVertWindDir[curvert][0]; winddiff3[1] = SSVertWindDir[curvert][1]; windforce3 = SSVertWindForce[curvert]; - if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) - { + if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) { continue; } @@ -705,121 +587,102 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0) { // Insanely small abhorrent triangle. continue; } step = stage->ss->density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd rightvectorcount = 0; - for (posi=0; posi<1.0; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - fa=posi+randomchart[randomindex]*step; + for (posi = 0; posi < 1.0; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + fa = posi + randomchart[randomindex] * step; randomindex += randominterval; - fb=posj+randomchart[randomindex]*step; + fb = posj + randomchart[randomindex] * step; randomindex += randominterval; - rightvectorcount=(rightvectorcount+1)&3; + rightvectorcount = (rightvectorcount + 1) & 3; - if (fa>1.0) + if (fa > 1.0) continue; - if (fb>(1.0-fa)) + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0 to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex]; randomindex += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0 - ((thisspritesfadestart-alphapos)/faderange); - if (alpha > 0.0) - { + alpha = 1.0 - ((thisspritesfadestart - alphapos) / faderange); + if (alpha > 0.0) { if (alpha > 1.0) - alpha=1.0; + alpha = 1.0; - if (SSUsingFog) - { - fogv[0] = fog1[0]*fa + fog2[0]*fb + fog3[0]*fc; - fogv[1] = fog1[1]*fa + fog2[1]*fb + fog3[1]*fc; + if (SSUsingFog) { + fogv[0] = fog1[0] * fa + fog2[0] * fb + fog3[0] * fc; + fogv[1] = fog1[1] * fa + fog2[1] * fb + fog3[1] * fc; } - if (usewindpoint) - { - winddiffv[0] = winddiff1[0]*fa + winddiff2[0]*fb + winddiff3[0]*fc; - winddiffv[1] = winddiff1[1]*fa + winddiff2[1]*fb + winddiff3[1]*fc; - windforce = windforce1*fa + windforce2*fb + windforce3*fc; + if (usewindpoint) { + winddiffv[0] = winddiff1[0] * fa + winddiff2[0] * fb + winddiff3[0] * fc; + winddiffv[1] = winddiff1[1] * fa + winddiff2[1] * fb + winddiff3[1] * fc; + windforce = windforce1 * fa + windforce2 * fb + windforce3 * fc; } VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + light = l1 * fa + l2 * fb + l3 * fc; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } randomindex2 = randomindex; - width = stage->ss->width*(1.0 + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0 + (stage->ss->variance[1]*randomchart[randomindex2++])); - if (randomchart[randomindex2++]>0.5) - { + width = stage->ss->width * (1.0 + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0 + (stage->ss->variance[1] * randomchart[randomindex2++])); + if (randomchart[randomindex2++] > 0.5) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0) - { - width *= 1.0 + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0) { + width *= 1.0 + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (stage->ss->vertSkew != 0) - { // flrand(-vertskew, vertskew) - skew[0] = height * ((stage->ss->vertSkew*2.0f*randomchart[randomindex2++])-stage->ss->vertSkew); - skew[1] = height * ((stage->ss->vertSkew*2.0f*randomchart[randomindex2++])-stage->ss->vertSkew); + if (stage->ss->vertSkew != 0) { // flrand(-vertskew, vertskew) + skew[0] = height * ((stage->ss->vertSkew * 2.0f * randomchart[randomindex2++]) - stage->ss->vertSkew); + skew[1] = height * ((stage->ss->vertSkew * 2.0f * randomchart[randomindex2++]) - stage->ss->vertSkew); } - if (usewindpoint && windforce > 0 && stage->ss->wind > 0.0) - { - if (SSUsingFog) - { - RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, fogv, stage->ss->facing, skew, - winddiffv, windforce, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + if (usewindpoint && windforce > 0 && stage->ss->wind > 0.0) { + if (SSUsingFog) { + RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, + fogv, stage->ss->facing, skew, winddiffv, windforce, + SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, + NULL, stage->ss->facing, skew, winddiffv, windforce, + SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); } - else - { - RB_VerticalSurfaceSpriteWindPoint(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, NULL, stage->ss->facing, skew, - winddiffv, windforce, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); - } - } - else - { - if (SSUsingFog) - { - RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, fogv, stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); - } - else - { - RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), - stage->ss->wind, stage->ss->windIdle, NULL, stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + if (SSUsingFog) { + RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, fogv, + stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); + } else { + RB_VerticalSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), stage->ss->wind, stage->ss->windIdle, NULL, + stage->ss->facing, skew, SURFSPRITE_FLATTENED == stage->ss->surfaceSpriteType); } } @@ -830,82 +693,77 @@ static void RB_DrawVerticalSurfaceSprites( shaderStage_t *stage, shaderCommands_ } } - ///////////////////////////////////////////// // Oriented surface sprites -static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, vec2_t fog, int faceup) -{ +static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, vec2_t fog, int faceup) { vec3_t loc2, right; float points[16]; color4ub_t color; - color[0]=light; - color[1]=light; - color[2]=light; - color[3]=alpha; + color[0] = light; + color[1] = light; + color[2] = light; + color[3] = alpha; - if (faceup) - { + if (faceup) { width *= 0.5; height *= 0.5; // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + width; points[1] = loc[1] - width; points[2] = loc[2] + 1.0; points[3] = 0; // Top right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[4] = loc[0] + width; points[5] = loc[1] + width; points[6] = loc[2] + 1.0; points[7] = 0; // Top left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[8] = loc[0] - width; points[9] = loc[1] + width; points[10] = loc[2] + 1.0; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - width; points[13] = loc[1] - width; points[14] = loc[2] + 1.0; points[15] = 0; - } - else - { + } else { VectorMA(loc, height, ssViewUp, loc2); - VectorScale(ssViewRight, width*0.5, right); + VectorScale(ssViewRight, width * 0.5, right); // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right - // VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left - // VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0]; points[9] = loc2[1] - right[1]; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -916,21 +774,20 @@ static void RB_OrientedSurfaceSprite(vec3_t loc, float width, float height, byte SQuickSprite.Add(points, color, fog); } -static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawOrientedSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea, minnormal; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; vec2_t fog1, fog2, fog3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; vec3_t curpoint; float width, height; @@ -938,74 +795,64 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ byte randomindex2; vec2_t fogv; - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); + float faderange = FADE_RANGE / (cutdist - fadedist); - if (faderange > 1.0) - { // Don't want to force a new fade_rand + if (faderange > 1.0) { // Don't want to force a new fade_rand faderange = 1.0; } - if (stage->ss->facing) - { // Faceup sprite. + if (stage->ss->facing) { // Faceup sprite. minnormal = 0.99f; - } - else - { // Normal oriented sprite + } else { // Normal oriented sprite minnormal = 0.5f; } // Quickly calc all the alphas for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc alpha at each point VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0 - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - fog1[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog1[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog1[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog1[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - fog2[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog2[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog2[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog2[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - fog3[0] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)); - fog3[1] = *((float *)(tess.svars.texcoords[0])+(curvert<<1)+1); + fog3[0] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1)); + fog3[1] = *((float *)(tess.svars.texcoords[0]) + (curvert << 1) + 1); - if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) - { + if (a1 <= 0.0 && a2 <= 0.0 && a3 <= 0.0) { continue; } @@ -1016,86 +863,75 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0) { // Insanely small abhorrent triangle. continue; } step = stage->ss->density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd - for (posi=0; posi<1.0; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - fa=posi+randomchart[randomindex]*step; + for (posi = 0; posi < 1.0; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + fa = posi + randomchart[randomindex] * step; randomindex += randominterval; - if (fa>1.0) + if (fa > 1.0) continue; - fb=posj+randomchart[randomindex]*step; + fb = posj + randomchart[randomindex] * step; randomindex += randominterval; - if (fb>(1.0-fa)) + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0 to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex]; randomindex += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0 - ((thisspritesfadestart-alphapos)/faderange); + alpha = 1.0 - ((thisspritesfadestart - alphapos) / faderange); randomindex += randominterval; - if (alpha > 0.0) - { + if (alpha > 0.0) { if (alpha > 1.0) - alpha=1.0; + alpha = 1.0; - if (SSUsingFog) - { - fogv[0] = fog1[0]*fa + fog2[0]*fb + fog3[0]*fc; - fogv[1] = fog1[1]*fa + fog2[1]*fb + fog3[1]*fc; + if (SSUsingFog) { + fogv[0] = fog1[0] * fa + fog2[0] * fb + fog3[0] * fc; + fogv[1] = fog1[1] * fa + fog2[1] * fb + fog3[1] * fc; } VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + light = l1 * fa + l2 * fb + l3 * fc; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } randomindex2 = randomindex; - width = stage->ss->width*(1.0 + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0 + (stage->ss->variance[1]*randomchart[randomindex2++])); - if (randomchart[randomindex2++]>0.5) - { + width = stage->ss->width * (1.0 + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0 + (stage->ss->variance[1] * randomchart[randomindex2++])); + if (randomchart[randomindex2++] > 0.5) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0) - { - width *= 1.0 + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0) { + width *= 1.0 + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (SSUsingFog) - { - RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), fogv, stage->ss->facing); - } - else - { - RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0), NULL, stage->ss->facing); + if (SSUsingFog) { + RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), fogv, stage->ss->facing); + } else { + RB_OrientedSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0), NULL, stage->ss->facing); } totalsurfsprites++; @@ -1105,82 +941,77 @@ static void RB_DrawOrientedSurfaceSprites( shaderStage_t *stage, shaderCommands_ } } - ///////////////////////////////////////////// // Effect surface sprites -static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float life, int faceup) -{ +static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte light, byte alpha, float life, int faceup) { vec3_t loc2, right; float points[16]; color4ub_t color; - color[0]=light; //light; - color[1]=light; //light; - color[2]=light; //light; - color[3]=alpha; //alpha; + color[0] = light; // light; + color[1] = light; // light; + color[2] = light; // light; + color[3] = alpha; // alpha; - if (faceup) - { + if (faceup) { width *= 0.5; height *= 0.5; // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + width; points[1] = loc[1] - width; points[2] = loc[2] + 1.0; points[3] = 0; // Top right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[4] = loc[0] + width; points[5] = loc[1] + width; points[6] = loc[2] + 1.0; points[7] = 0; // Top left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[8] = loc[0] - width; points[9] = loc[1] + width; points[10] = loc[2] + 1.0; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - width; points[13] = loc[1] - width; points[14] = loc[2] + 1.0; points[15] = 0; - } - else - { + } else { VectorMA(loc, height, ssViewUp, loc2); - VectorScale(ssViewRight, width*0.5, right); + VectorScale(ssViewRight, width * 0.5, right); // Bottom right - // VectorAdd(loc, right, point); + // VectorAdd(loc, right, point); points[0] = loc[0] + right[0]; points[1] = loc[1] + right[1]; points[2] = loc[2] + right[2]; points[3] = 0; // Top right - // VectorAdd(loc2, right, point); + // VectorAdd(loc2, right, point); points[4] = loc2[0] + right[0]; points[5] = loc2[1] + right[1]; points[6] = loc2[2] + right[2]; points[7] = 0; // Top left - // VectorSubtract(loc2, right, point); + // VectorSubtract(loc2, right, point); points[8] = loc2[0] - right[0]; points[9] = loc2[1] - right[1]; points[10] = loc2[2] - right[2]; points[11] = 0; // Bottom left - // VectorSubtract(loc, right, point); + // VectorSubtract(loc, right, point); points[12] = loc[0] - right[0]; points[13] = loc[1] - right[1]; points[14] = loc[2] - right[2]; @@ -1191,20 +1022,19 @@ static void RB_EffectSurfaceSprite(vec3_t loc, float width, float height, byte l SQuickSprite.Add(points, color, NULL); } -static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ +static void RB_DrawEffectSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { int curindex, curvert; - vec3_t dist; + vec3_t dist; float triarea, minnormal; vec2_t vec1to2, vec1to3; - vec3_t v1,v2,v3; - float a1,a2,a3; - float l1,l2,l3; + vec3_t v1, v2, v3; + float a1, a2, a3; + float l1, l2, l3; float posi, posj; float step; - float fa,fb,fc; + float fa, fb, fc; float effecttime, effectpos; float density; @@ -1213,99 +1043,82 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t float alpha, alphapos, thisspritesfadestart, light; byte randomindex2; - float cutdist=stage->ss->fadeMax*rangescalefactor, cutdist2=cutdist*cutdist; - float fadedist=stage->ss->fadeDist*rangescalefactor, fadedist2=fadedist*fadedist; + float cutdist = stage->ss->fadeMax * rangescalefactor, cutdist2 = cutdist * cutdist; + float fadedist = stage->ss->fadeDist * rangescalefactor, fadedist2 = fadedist * fadedist; float fxalpha = stage->ss->fxAlphaEnd - stage->ss->fxAlphaStart; - qboolean fadeinout=qfalse; + qboolean fadeinout = qfalse; assert(cutdist2 != fadedist2); - float inv_fadediff = 1.0/(cutdist2-fadedist2); + float inv_fadediff = 1.0 / (cutdist2 - fadedist2); // The faderange is the fraction amount it takes for these sprites to fade out, assuming an ideal fade range of 250 - float faderange = FADE_RANGE/(cutdist-fadedist); - if (faderange > 1.0f) - { // Don't want to force a new fade_rand + float faderange = FADE_RANGE / (cutdist - fadedist); + if (faderange > 1.0f) { // Don't want to force a new fade_rand faderange = 1.0f; } - if (stage->ss->facing) - { // Faceup sprite. + if (stage->ss->facing) { // Faceup sprite. minnormal = 0.99f; - } - else - { // Normal oriented sprite + } else { // Normal oriented sprite minnormal = 0.5f; } // Make the object fade in. - if (stage->ss->fxAlphaEnd < 0.05 && stage->ss->height >= 0.1 && stage->ss->width >= 0.1) - { // The sprite fades out, and it doesn't start at a pinpoint. Let's fade it in. - fadeinout=qtrue; + if (stage->ss->fxAlphaEnd < 0.05 && stage->ss->height >= 0.1 && + stage->ss->width >= 0.1) { // The sprite fades out, and it doesn't start at a pinpoint. Let's fade it in. + fadeinout = qtrue; } - if (stage->ss->surfaceSpriteType == SURFSPRITE_WEATHERFX) - { // This effect is affected by weather settings. - if (curWeatherAmount < 0.01) - { // Don't show these effects + if (stage->ss->surfaceSpriteType == SURFSPRITE_WEATHERFX) { // This effect is affected by weather settings. + if (curWeatherAmount < 0.01) { // Don't show these effects return; - } - else - { + } else { density = stage->ss->density / curWeatherAmount; } - } - else - { + } else { density = stage->ss->density; } // Quickly calc all the alphas for each vertex - for (curvert=0; curvertnumVertexes; curvert++) - { + for (curvert = 0; curvert < input->numVertexes; curvert++) { // Calc alpha at each point VectorSubtract(ssViewOrigin, input->xyz[curvert], dist); SSVertAlpha[curvert] = 1.0f - (VectorLengthSquared(dist) - fadedist2) * inv_fadediff; - // Note this is the proper equation, but isn't used right now because it would be just a tad slower. + // Note this is the proper equation, but isn't used right now because it would be just a tad slower. // Formula for alpha is 1.0f - ((len-fade)/(cut-fade)) // Which is equal to (1.0+fade/(cut-fade)) - (len/(cut-fade)) // So mult=1/(cut-fade), and base=(1+fade*mult). - // SSVertAlpha[curvert] = fadebase - (VectorLength(dist) * fademult); - + // SSVertAlpha[curvert] = fadebase - (VectorLength(dist) * fademult); } - for (curindex=0; curindexnumIndexes-2; curindex+=3) - { + for (curindex = 0; curindex < input->numIndexes - 2; curindex += 3) { curvert = input->indexes[curindex]; VectorCopy(input->xyz[curvert], v1); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l1 = input->vertexColors[curvert][2]; a1 = SSVertAlpha[curvert]; - curvert = input->indexes[curindex+1]; + curvert = input->indexes[curindex + 1]; VectorCopy(input->xyz[curvert], v2); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l2 = input->vertexColors[curvert][2]; a2 = SSVertAlpha[curvert]; - curvert = input->indexes[curindex+2]; + curvert = input->indexes[curindex + 2]; VectorCopy(input->xyz[curvert], v3); - if (input->normal[curvert][2] < minnormal) - { + if (input->normal[curvert][2] < minnormal) { continue; } l3 = input->vertexColors[curvert][2]; a3 = SSVertAlpha[curvert]; - if (a1 <= 0.0f && a2 <= 0.0f && a3 <= 0.0f) - { + if (a1 <= 0.0f && a2 <= 0.0f && a3 <= 0.0f) { continue; } @@ -1316,105 +1129,89 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t vec1to3[1] = v3[1] - v1[1]; // Now get the cross product of this sum. - triarea = vec1to3[0]*vec1to2[1] - vec1to3[1]*vec1to2[0]; - triarea=fabs(triarea); - if (triarea <= 1.0f) - { // Insanely small abhorrent triangle. + triarea = vec1to3[0] * vec1to2[1] - vec1to3[1] * vec1to2[0]; + triarea = fabs(triarea); + if (triarea <= 1.0f) { // Insanely small abhorrent triangle. continue; } step = density * Q_rsqrt(triarea); - randomindex = (byte)(v1[0]+v1[1]+v2[0]+v2[1]+v3[0]+v3[1]); - randominterval = (byte)(v1[0]+v2[1]+v3[2])|0x03; // Make sure the interval is at least 3, and always odd + randomindex = (byte)(v1[0] + v1[1] + v2[0] + v2[1] + v3[0] + v3[1]); + randominterval = (byte)(v1[0] + v2[1] + v3[2]) | 0x03; // Make sure the interval is at least 3, and always odd - for (posi=0; posi<1.0f; posi+=step) - { - for (posj=0; posj<(1.0-posi); posj+=step) - { - effecttime = (tr.refdef.time+10000.0*randomchart[randomindex])/stage->ss->fxDuration; + for (posi = 0; posi < 1.0f; posi += step) { + for (posj = 0; posj < (1.0 - posi); posj += step) { + effecttime = (tr.refdef.time + 10000.0 * randomchart[randomindex]) / stage->ss->fxDuration; effectpos = (float)effecttime - (int)effecttime; - randomindex2 = randomindex+effecttime; + randomindex2 = randomindex + effecttime; randomindex += randominterval; - fa=posi+randomchart[randomindex2++]*step; - if (fa>1.0f) + fa = posi + randomchart[randomindex2++] * step; + if (fa > 1.0f) continue; - fb=posj+randomchart[randomindex2++]*step; - if (fb>(1.0-fa)) + fb = posj + randomchart[randomindex2++] * step; + if (fb > (1.0 - fa)) continue; - fc = 1.0-fa-fb; + fc = 1.0 - fa - fb; // total alpha, minus random factor so some things fade out sooner. - alphapos = a1*fa + a2*fb + a3*fc; + alphapos = a1 * fa + a2 * fb + a3 * fc; // Note that the alpha at this point is a value from 1.0f to 0.0, but represents when to START fading - thisspritesfadestart = faderange + (1.0-faderange) * randomchart[randomindex2]; + thisspritesfadestart = faderange + (1.0 - faderange) * randomchart[randomindex2]; randomindex2 += randominterval; // Find where the alpha is relative to the fadestart, and calc the real alpha to draw at. - alpha = 1.0f - ((thisspritesfadestart-alphapos)/faderange); - if (alpha > 0.0f) - { + alpha = 1.0f - ((thisspritesfadestart - alphapos) / faderange); + if (alpha > 0.0f) { if (alpha > 1.0f) - alpha=1.0f; + alpha = 1.0f; VectorScale(v1, fa, curpoint); VectorMA(curpoint, fb, v2, curpoint); VectorMA(curpoint, fc, v3, curpoint); - light = l1*fa + l2*fb + l3*fc; + light = l1 * fa + l2 * fb + l3 * fc; randomindex2 = randomindex; - width = stage->ss->width*(1.0f + (stage->ss->variance[0]*randomchart[randomindex2])); - height = stage->ss->height*(1.0f + (stage->ss->variance[1]*randomchart[randomindex2++])); + width = stage->ss->width * (1.0f + (stage->ss->variance[0] * randomchart[randomindex2])); + height = stage->ss->height * (1.0f + (stage->ss->variance[1] * randomchart[randomindex2++])); - width = width + (effectpos*stage->ss->fxGrow[0]*width); - height = height + (effectpos*stage->ss->fxGrow[1]*height); + width = width + (effectpos * stage->ss->fxGrow[0] * width); + height = height + (effectpos * stage->ss->fxGrow[1] * height); // If we want to fade in and out, that's different than a straight fade. - if (fadeinout) - { - if (effectpos > 0.5) - { // Fade out - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*(effectpos-0.5)*2.0)); - } - else - { // Fade in - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*(0.5-effectpos)*2.0)); + if (fadeinout) { + if (effectpos > 0.5) { // Fade out + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * (effectpos - 0.5) * 2.0)); + } else { // Fade in + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * (0.5 - effectpos) * 2.0)); } - } - else - { // Normal fade - alpha = alpha*(stage->ss->fxAlphaStart+(fxalpha*effectpos)); + } else { // Normal fade + alpha = alpha * (stage->ss->fxAlphaStart + (fxalpha * effectpos)); } - if (SSAdditiveTransparency) - { // Additive transparency, scale light value -// light *= alpha; - light = (128 + (light*0.5))*alpha; + if (SSAdditiveTransparency) { // Additive transparency, scale light value + // light *= alpha; + light = (128 + (light * 0.5)) * alpha; alpha = 1.0; } - if (randomchart[randomindex2]>0.5f) - { + if (randomchart[randomindex2] > 0.5f) { width = -width; } - if (stage->ss->fadeScale!=0 && alphapos < 1.0f) - { - width *= 1.0f + (stage->ss->fadeScale*(1.0-alphapos)); + if (stage->ss->fadeScale != 0 && alphapos < 1.0f) { + width *= 1.0f + (stage->ss->fadeScale * (1.0 - alphapos)); } - if (stage->ss->wind>0.0f && curWindSpeed > 0.001) - { + if (stage->ss->wind > 0.0f && curWindSpeed > 0.001) { vec3_t drawpoint; - VectorMA(curpoint, effectpos*stage->ss->wind, curWindBlowVect, drawpoint); - RB_EffectSurfaceSprite(drawpoint, width, height, (byte)light, (byte)(alpha*255.0f), stage->ss->fxDuration, stage->ss->facing); - } - else - { - RB_EffectSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha*255.0f), stage->ss->fxDuration, stage->ss->facing); + VectorMA(curpoint, effectpos * stage->ss->wind, curWindBlowVect, drawpoint); + RB_EffectSurfaceSprite(drawpoint, width, height, (byte)light, (byte)(alpha * 255.0f), stage->ss->fxDuration, stage->ss->facing); + } else { + RB_EffectSurfaceSprite(curpoint, width, height, (byte)light, (byte)(alpha * 255.0f), stage->ss->fxDuration, stage->ss->facing); } totalsurfsprites++; @@ -1424,64 +1221,51 @@ static void RB_DrawEffectSurfaceSprites( shaderStage_t *stage, shaderCommands_t } } -extern void R_WorldToLocal (vec3_t world, vec3_t localVec) ; +extern void R_WorldToLocal(vec3_t world, vec3_t localVec); extern float preTransEntMatrix[16], invEntMatrix[16]; extern void R_InvertMatrix(float *sourcemat, float *destmat); -void RB_DrawSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) -{ - uint32_t glbits=stage->stateBits; +void RB_DrawSurfaceSprites(shaderStage_t *stage, shaderCommands_t *input) { + uint32_t glbits = stage->stateBits; R_SurfaceSpriteFrameUpdate(); // // Check fog // - if ( tess.fogNum && tess.shader->fogPass && r_drawfog->value) - { + if (tess.fogNum && tess.shader->fogPass && r_drawfog->value) { SSUsingFog = qtrue; SQuickSprite.StartGroup(&stage->bundle[0], glbits, tess.fogNum); - } - else - { + } else { SSUsingFog = qfalse; SQuickSprite.StartGroup(&stage->bundle[0], glbits); } // Special provision in case the transparency is additive. - if ((glbits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) - { // Additive transparency, scale light value - SSAdditiveTransparency=qtrue; - } - else - { - SSAdditiveTransparency=qfalse; + if ((glbits & (GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE)) { // Additive transparency, scale light value + SSAdditiveTransparency = qtrue; + } else { + SSAdditiveTransparency = qfalse; } - - //Check if this is a new entity transformation (incl. world entity), and update the appropriate vectors if so. - if (backEnd.currentEntity != ssLastEntityDrawn) - { - if (backEnd.currentEntity == &tr.worldEntity) - { // Drawing the world, so our job is dead-easy, in the viewparms + // Check if this is a new entity transformation (incl. world entity), and update the appropriate vectors if so. + if (backEnd.currentEntity != ssLastEntityDrawn) { + if (backEnd.currentEntity == &tr.worldEntity) { // Drawing the world, so our job is dead-easy, in the viewparms VectorCopy(backEnd.viewParms.ori.origin, ssViewOrigin); VectorCopy(backEnd.viewParms.ori.axis[1], ssViewRight); VectorCopy(backEnd.viewParms.ori.axis[2], ssViewUp); - } - else - { // Drawing an entity, so we need to transform the viewparms to the model's coordinate system -// R_WorldPointToEntity (backEnd.viewParms.ori.origin, ssViewOrigin); - R_WorldNormalToEntity (backEnd.viewParms.ori.axis[1], ssViewRight); - R_WorldNormalToEntity (backEnd.viewParms.ori.axis[2], ssViewUp); + } else { // Drawing an entity, so we need to transform the viewparms to the model's coordinate system + // R_WorldPointToEntity (backEnd.viewParms.ori.origin, ssViewOrigin); + R_WorldNormalToEntity(backEnd.viewParms.ori.axis[1], ssViewRight); + R_WorldNormalToEntity(backEnd.viewParms.ori.axis[2], ssViewUp); VectorCopy(backEnd.ori.viewOrigin, ssViewOrigin); -// R_WorldToLocal(backEnd.viewParms.ori.axis[1], ssViewRight); -// R_WorldToLocal(backEnd.viewParms.ori.axis[2], ssViewUp); + // R_WorldToLocal(backEnd.viewParms.ori.axis[1], ssViewRight); + // R_WorldToLocal(backEnd.viewParms.ori.axis[2], ssViewUp); } ssLastEntityDrawn = backEnd.currentEntity; } - switch(stage->ss->surfaceSpriteType) - { + switch (stage->ss->surfaceSpriteType) { case SURFSPRITE_FLATTENED: case SURFSPRITE_VERTICAL: RB_DrawVerticalSurfaceSprites(stage, input); @@ -1499,4 +1283,3 @@ void RB_DrawSurfaceSprites( shaderStage_t *stage, shaderCommands_t *input) sssurfaces++; } - diff --git a/codemp/rd-vanilla/tr_terrain.cpp b/codemp/rd-vanilla/tr_terrain.cpp index ce1a0b372f..4332f11d38 100644 --- a/codemp/rd-vanilla/tr_terrain.cpp +++ b/codemp/rd-vanilla/tr_terrain.cpp @@ -12,22 +12,20 @@ #include "qcommon/cm_landscape.h" #include "tr_landscape.h" -cvar_t *r_drawTerrain; -cvar_t *r_showFrameVariance; -cvar_t *r_terrainTessellate; -cvar_t *r_terrainWaterOffset; +cvar_t *r_drawTerrain; +cvar_t *r_showFrameVariance; +cvar_t *r_terrainTessellate; +cvar_t *r_terrainWaterOffset; -static int TerrainFog = 0; -static float TerrainDistanceCull; +static int TerrainFog = 0; +static float TerrainDistanceCull; // // Render the tree. // -void CTRPatch::RenderCorner(ivec5_t corner) -{ - if((corner[3] < 0) || (tess.registration != corner[4])) - { - CTerVert *vert; +void CTRPatch::RenderCorner(ivec5_t corner) { + if ((corner[3] < 0) || (tess.registration != corner[4])) { + CTerVert *vert; vert = mRenderMap + (corner[1] * owner->GetRealWidth()) + corner[0]; @@ -37,28 +35,24 @@ void CTRPatch::RenderCorner(ivec5_t corner) *(ulong *)tess.vertexColors[tess.numVertexes] = *(ulong *)vert->tint; *(ulong *)tess.vertexAlphas[tess.numVertexes] = corner[2]; - tess.texCoords[tess.numVertexes][0][0] = vert->tex[0]; //rwwRMG - reverse coords array from sof2 + tess.texCoords[tess.numVertexes][0][0] = vert->tex[0]; // rwwRMG - reverse coords array from sof2 tess.texCoords[tess.numVertexes][0][1] = vert->tex[1]; tess.indexes[tess.numIndexes++] = tess.numVertexes; corner[3] = tess.numVertexes++; corner[4] = tess.registration; - } - else - { + } else { tess.indexes[tess.numIndexes++] = corner[3]; } } -void CTRPatch::RecurseRender(int depth, ivec5_t left, ivec5_t right, ivec5_t apex) -{ +void CTRPatch::RecurseRender(int depth, ivec5_t left, ivec5_t right, ivec5_t apex) { // All non-leaf nodes have both children, so just check for one - if (depth >= 0) - { - ivec5_t center; - byte *centerAlphas; - byte *leftAlphas; - byte *rightAlphas; + if (depth >= 0) { + ivec5_t center; + byte *centerAlphas; + byte *leftAlphas; + byte *rightAlphas; // Work out the centre of the hypoteneuse center[0] = (left[0] + right[0]) >> 1; @@ -78,31 +72,26 @@ void CTRPatch::RecurseRender(int depth, ivec5_t left, ivec5_t right, ivec5_t ape center[3] = -1; center[4] = 0; - if (apex[0] == left[0] && apex[0] == center[0]) - { + if (apex[0] == left[0] && apex[0] == center[0]) { depth = 0; } - RecurseRender(depth-1, apex, left, center); - RecurseRender(depth-1, right, apex, center); - } - else - { - if (left[0] == right[0] && left[0] == apex[0]) - { + RecurseRender(depth - 1, apex, left, center); + RecurseRender(depth - 1, right, apex, center); + } else { + if (left[0] == right[0] && left[0] == apex[0]) { return; } - if (left[1] == right[1] && left[1] == apex[1]) - { + if (left[1] == right[1] && left[1] == apex[1]) { return; } // A leaf node! Output a triangle to be rendered. RB_CheckOverflow(4, 4); -// assert(left[0] != right[0] || left[1] != right[1]); -// assert(left[0] != apex[0] || left[1] != apex[1]); + // assert(left[0] != right[0] || left[1] != right[1]); + // assert(left[0] != apex[0] || left[1] != apex[1]); - RenderCorner(left); + RenderCorner(left); RenderCorner(right); RenderCorner(apex); } @@ -113,52 +102,43 @@ void CTRPatch::RecurseRender(int depth, ivec5_t left, ivec5_t right, ivec5_t ape // // The order of triangles is critical to the subdivision working -void CTRPatch::Render(int Part) -{ - ivec5_t TL, TR, BL, BR; +void CTRPatch::Render(int Part) { + ivec5_t TL, TR, BL, BR; VectorSet5M(TL, 0, 0, TEXTURE_ALPHA_TL, -1, 0); VectorSet5M(TR, owner->GetTerxels(), 0, TEXTURE_ALPHA_TR, -1, 0); VectorSet5M(BL, 0, owner->GetTerxels(), TEXTURE_ALPHA_BL, -1, 0); VectorSet5M(BR, owner->GetTerxels(), owner->GetTerxels(), TEXTURE_ALPHA_BR, -1, 0); - if ((Part & PI_TOP) && mTLShader) - { -/* float d; + if ((Part & PI_TOP) && mTLShader) { + /* float d; - d = DotProduct (backEnd.refdef.vieworg, mNormal[0]) - mDistance[0]; + d = DotProduct (backEnd.refdef.vieworg, mNormal[0]) - mDistance[0]; - if (d <= 0.0)*/ - { - RecurseRender(r_terrainTessellate->integer, BL, TR, TL); - } + if (d <= 0.0)*/ + { RecurseRender(r_terrainTessellate->integer, BL, TR, TL); } } - if ((Part & PI_BOTTOM) && mBRShader) - { -/* float d; + if ((Part & PI_BOTTOM) && mBRShader) { + /* float d; - d = DotProduct (backEnd.refdef.vieworg, mNormal[1]) - mDistance[1]; + d = DotProduct (backEnd.refdef.vieworg, mNormal[1]) - mDistance[1]; - if (d >= 0.0)*/ - { - RecurseRender(r_terrainTessellate->integer, TR, BL, BR); - } + if (d >= 0.0)*/ + { RecurseRender(r_terrainTessellate->integer, TR, BL, BR); } } } // // At this point the patch is visible and at least part of it is below water level // -int CTRPatch::RenderWaterVert(int x, int y) -{ - CTerVert *vert; +int CTRPatch::RenderWaterVert(int x, int y) { + CTerVert *vert; vert = mRenderMap + x + (y * owner->GetRealWidth()); - if(vert->tessRegistration == tess.registration) - { - return(vert->tessIndex); + if (vert->tessRegistration == tess.registration) { + return (vert->tessIndex); } tess.xyz[tess.numVertexes][0] = vert->coords[0]; tess.xyz[tess.numVertexes][1] = vert->coords[1]; @@ -166,18 +146,17 @@ int CTRPatch::RenderWaterVert(int x, int y) *(ulong *)tess.vertexColors[tess.numVertexes] = 0xffffffff; - tess.texCoords[tess.numVertexes][0][0] = vert->tex[0]; //rwwRMG - reverse coords from sof2mp + tess.texCoords[tess.numVertexes][0][0] = vert->tex[0]; // rwwRMG - reverse coords from sof2mp tess.texCoords[tess.numVertexes][0][1] = vert->tex[1]; vert->tessIndex = tess.numVertexes; vert->tessRegistration = tess.registration; tess.numVertexes++; - return(vert->tessIndex); + return (vert->tessIndex); } -void CTRPatch::RenderWater(void) -{ +void CTRPatch::RenderWater(void) { RB_CheckOverflow(4, 6); // Get the neighbouring patches @@ -197,28 +176,20 @@ void CTRPatch::RenderWater(void) tess.indexes[tess.numIndexes++] = BR; } -const bool CTRPatch::HasWater(void) const -{ - owner->SetRealWaterHeight( owner->GetBaseWaterHeight() + r_terrainWaterOffset->integer ); - return(common->GetMins()[2] < owner->GetWaterHeight()); +const bool CTRPatch::HasWater(void) const { + owner->SetRealWaterHeight(owner->GetBaseWaterHeight() + r_terrainWaterOffset->integer); + return (common->GetMins()[2] < owner->GetWaterHeight()); } -void CTRPatch::SetVisibility(bool visCheck) -{ - if(visCheck) - { - if(DistanceSquared(mCenter, backEnd.refdef.vieworg) > TerrainDistanceCull) - { +void CTRPatch::SetVisibility(bool visCheck) { + if (visCheck) { + if (DistanceSquared(mCenter, backEnd.refdef.vieworg) > TerrainDistanceCull) { misVisible = false; - } - else - { + } else { // Set the visibility of the patch misVisible = !ri.CM_CullWorldBox(backEnd.viewParms.frustum, GetBounds()); } - } - else - { + } else { misVisible = true; } } @@ -257,45 +228,37 @@ void CTRPatch::CalcNormal(void) // // Reset all patches, recompute variance if needed // -void CTRLandScape::Reset(bool visCheck) -{ - int x, y; - CTRPatch *patch; +void CTRLandScape::Reset(bool visCheck) { + int x, y; + CTRPatch *patch; TerrainDistanceCull = tr.distanceCull + mPatchSize; TerrainDistanceCull *= TerrainDistanceCull; // Go through the patches performing resets, compute variances, and linking. - for(y = mPatchMiny; y < mPatchMaxy; y++) - { - for(x = mPatchMinx; x < mPatchMaxx; x++, patch++) - { + for (y = mPatchMiny; y < mPatchMaxy; y++) { + for (x = mPatchMinx; x < mPatchMaxx; x++, patch++) { patch = GetPatch(x, y); patch->SetVisibility(visCheck); } } } - // // Render each patch of the landscape & adjust the frame variance. // -void CTRLandScape::Render(void) -{ - int x, y; - CTRPatch *patch; - TPatchInfo *current; - int i; +void CTRLandScape::Render(void) { + int x, y; + CTRPatch *patch; + TPatchInfo *current; + int i; // Render all the visible patches current = mSortedPatches; - for(i=0;imPatch->isVisible()) - { - if (tess.shader != current->mShader) - { + for (i = 0; i < mSortedCount; i++) { + if (current->mPatch->isVisible()) { + if (tess.shader != current->mShader) { RB_EndSurface(); RB_BeginSurface(current->mShader, TerrainFog); } @@ -307,17 +270,13 @@ void CTRLandScape::Render(void) // Render all the water for visible patches // Done as a separate iteration to reduce the number of tesses created - if(mWaterShader && (mWaterShader != tr.defaultShader)) - { - RB_BeginSurface( mWaterShader, tr.world->globalFog ); + if (mWaterShader && (mWaterShader != tr.defaultShader)) { + RB_BeginSurface(mWaterShader, tr.world->globalFog); - for(y = mPatchMiny; y < mPatchMaxy; y++ ) - { - for(x = mPatchMinx; x < mPatchMaxx; x++ ) - { + for (y = mPatchMiny; y < mPatchMaxy; y++) { + for (x = mPatchMinx; x < mPatchMaxx; x++) { patch = GetPatch(x, y); - if(patch->isVisible() && patch->HasWater()) - { + if (patch->isVisible() && patch->HasWater()) { patch->RenderWater(); } } @@ -326,11 +285,10 @@ void CTRLandScape::Render(void) } } -void CTRLandScape::CalculateRegion(void) -{ - vec3_t mins, maxs, size, offset; +void CTRLandScape::CalculateRegion(void) { + vec3_t mins, maxs, size, offset; -#if _DEBUG +#if _DEBUG mCycleCount++; #endif VectorCopy(GetPatchSize(), size); @@ -349,17 +307,14 @@ void CTRLandScape::CalculateRegion(void) mPatchMaxy = Com_Clampi(0, GetBlockHeight(), ceilf(maxs[1] / size[1])); } -void CTRLandScape::CalculateRealCoords(void) -{ - int x, y; +void CTRLandScape::CalculateRealCoords(void) { + int x, y; // Work out the real world coordinates of each heightmap entry - for(y = 0; y < GetRealHeight(); y++) - { - for(x = 0; x < GetRealWidth(); x++) - { - ivec3_t icoords; - int offset; + for (y = 0; y < GetRealHeight(); y++) { + for (x = 0; x < GetRealWidth(); x++) { + ivec3_t icoords; + int offset; offset = (y * GetRealWidth()) + x; @@ -369,16 +324,13 @@ void CTRLandScape::CalculateRealCoords(void) } } -void CTRLandScape::CalculateNormals(void) -{ - int x, y, offset = 0; +void CTRLandScape::CalculateNormals(void) { + int x, y, offset = 0; // Work out the normals for every face - for(y = 0; y < GetHeight(); y++) - { - for(x = 0; x < GetWidth(); x++) - { - vec3_t vcenter, vleft; + for (y = 0; y < GetHeight(); y++) { + for (x = 0; x < GetWidth(); x++) { + vec3_t vcenter, vleft; offset = (y * GetRealWidth()) + x; @@ -393,46 +345,38 @@ void CTRLandScape::CalculateNormals(void) } // Duplicate bottom line offset = GetHeight() * GetRealWidth(); - for(x = 0; x < GetRealWidth(); x++) - { + for (x = 0; x < GetRealWidth(); x++) { VectorCopy(mRenderMap[offset - GetRealWidth() + x].normal, mRenderMap[offset + x].normal); } } -void CTRLandScape::CalculateLighting(void) -{ - int x, y, offset = 0; +void CTRLandScape::CalculateLighting(void) { + int x, y, offset = 0; // Work out the vertex normal (average of every attached face normal) and apply to the direction of the light - for(y = 0; y < GetHeight(); y++) - { - for(x = 0; x < GetWidth(); x++) - { - vec3_t ambient; - vec3_t directed, direction; - vec3_t total, tint; - float dp; + for (y = 0; y < GetHeight(); y++) { + for (x = 0; x < GetWidth(); x++) { + vec3_t ambient; + vec3_t directed, direction; + vec3_t total, tint; + float dp; offset = (y * GetRealWidth()) + x; // Work out average normal - VectorCopy(GetRenderMap(x, y)->normal, total); - VectorAdd(total, GetRenderMap(x + 1, y)->normal, total); - VectorAdd(total, GetRenderMap(x + 1, y + 1)->normal, total); - VectorAdd(total, GetRenderMap(x, y + 1)->normal, total); + VectorCopy(GetRenderMap(x, y)->normal, total); + VectorAdd(total, GetRenderMap(x + 1, y)->normal, total); + VectorAdd(total, GetRenderMap(x + 1, y + 1)->normal, total); + VectorAdd(total, GetRenderMap(x, y + 1)->normal, total); VectorNormalize(total); - if (!R_LightForPoint(mRenderMap[offset].coords, ambient, directed, direction)) - { - mRenderMap[offset].tint[0] = - mRenderMap[offset].tint[1] = - mRenderMap[offset].tint[2] = 255 >> tr.overbrightBits; + if (!R_LightForPoint(mRenderMap[offset].coords, ambient, directed, direction)) { + mRenderMap[offset].tint[0] = mRenderMap[offset].tint[1] = mRenderMap[offset].tint[2] = 255 >> tr.overbrightBits; mRenderMap[offset].tint[3] = 255; continue; } - if(mRenderMap[offset].coords[2] < common->GetBaseWaterHeight()) - { + if (mRenderMap[offset].coords[2] < common->GetBaseWaterHeight()) { VectorScale(ambient, 0.75f, ambient); } @@ -442,9 +386,9 @@ void CTRLandScape::CalculateLighting(void) VectorScale(ambient, (1.0 - dp) * 0.5, ambient); VectorMA(ambient, dp, directed, tint); - mRenderMap[offset].tint[0] = (byte)Com_Clampi(0.0f, 255.0f, tint[0] ) >> tr.overbrightBits; - mRenderMap[offset].tint[1] = (byte)Com_Clampi(0.0f, 255.0f, tint[1] ) >> tr.overbrightBits; - mRenderMap[offset].tint[2] = (byte)Com_Clampi(0.0f, 255.0f, tint[2] ) >> tr.overbrightBits; + mRenderMap[offset].tint[0] = (byte)Com_Clampi(0.0f, 255.0f, tint[0]) >> tr.overbrightBits; + mRenderMap[offset].tint[1] = (byte)Com_Clampi(0.0f, 255.0f, tint[1]) >> tr.overbrightBits; + mRenderMap[offset].tint[2] = (byte)Com_Clampi(0.0f, 255.0f, tint[2]) >> tr.overbrightBits; mRenderMap[offset].tint[3] = 0xff; /* @@ -460,8 +404,7 @@ void CTRLandScape::CalculateLighting(void) } // Duplicate bottom line offset = GetHeight() * GetRealWidth(); - for(x = 0; x < GetRealWidth(); x++) - { + for (x = 0; x < GetRealWidth(); x++) { mRenderMap[offset + x].tint[0] = mRenderMap[offset - GetRealWidth() + x].tint[0]; mRenderMap[offset + x].tint[1] = mRenderMap[offset - GetRealWidth() + x].tint[1]; mRenderMap[offset + x].tint[2] = mRenderMap[offset - GetRealWidth() + x].tint[2]; @@ -469,14 +412,11 @@ void CTRLandScape::CalculateLighting(void) } } -void CTRLandScape::CalculateTextureCoords(void) -{ - int x, y; +void CTRLandScape::CalculateTextureCoords(void) { + int x, y; - for(y = 0; y < GetRealHeight(); y++) - { - for(x = 0; x < GetRealWidth(); x++) - { + for (y = 0; y < GetRealHeight(); y++) { + for (x = 0; x < GetRealWidth(); x++) { int offset = (y * GetRealWidth()) + x; mRenderMap[offset].tex[0] = x * mTextureScale * GetTerxelSize()[0]; @@ -485,37 +425,31 @@ void CTRLandScape::CalculateTextureCoords(void) } } -void CTRLandScape::SetShaders(const int height, const qhandle_t shader) -{ - int i; +void CTRLandScape::SetShaders(const int height, const qhandle_t shader) { + int i; - for(i = height; shader && (i < HEIGHT_RESOLUTION); i++) - { - if(!mHeightDetails[i].GetShader()) - { + for (i = height; shader && (i < HEIGHT_RESOLUTION); i++) { + if (!mHeightDetails[i].GetShader()) { mHeightDetails[i].SetShader(shader); } } } -void CTRLandScape::LoadTerrainDef(const char *td) -{ - char terrainDef[MAX_QPATH]; - CGenericParser2 parse; - CGPGroup *basegroup, *classes, *items; +void CTRLandScape::LoadTerrainDef(const char *td) { + char terrainDef[MAX_QPATH]; + CGenericParser2 parse; + CGPGroup *basegroup, *classes, *items; Com_sprintf(terrainDef, MAX_QPATH, "ext_data/RMG/%s.terrain", td); - ri.Printf( PRINT_ALL, "R_Terrain: Loading and parsing terrainDef %s.....\n", td); + ri.Printf(PRINT_ALL, "R_Terrain: Loading and parsing terrainDef %s.....\n", td); mWaterShader = NULL; - mFlatShader = NULL_HANDLE; + mFlatShader = NULL_HANDLE; - if(!Com_ParseTextFile(terrainDef, parse)) - { + if (!Com_ParseTextFile(terrainDef, parse)) { Com_sprintf(terrainDef, MAX_QPATH, "ext_data/arioche/%s.terrain", td); - if(!Com_ParseTextFile(terrainDef, parse)) - { - ri.Printf( PRINT_ALL, "Could not open %s\n", terrainDef); + if (!Com_ParseTextFile(terrainDef, parse)) { + ri.Printf(PRINT_ALL, "Could not open %s\n", terrainDef); return; } } @@ -524,40 +458,31 @@ void CTRLandScape::LoadTerrainDef(const char *td) // The root { } struct classes = basegroup->GetSubGroups(); - while(classes) - { + while (classes) { items = classes->GetSubGroups(); - while(items) - { - const char* type = items->GetName ( ); + while (items) { + const char *type = items->GetName(); - if(!Q_stricmp( type, "altitudetexture")) - { - int height; - const char *shaderName; - qhandle_t shader; + if (!Q_stricmp(type, "altitudetexture")) { + int height; + const char *shaderName; + qhandle_t shader; // Height must exist - the rest are optional height = atol(items->FindPairValue("height", "0")); // Shader for this height shaderName = items->FindPairValue("shader", ""); - if(strlen(shaderName)) - { + if (strlen(shaderName)) { shader = RE_RegisterShader(shaderName); - if(shader) - { + if (shader) { SetShaders(height, shader); } } - } - else if(!Q_stricmp(type, "water")) - { + } else if (!Q_stricmp(type, "water")) { mWaterShader = R_GetShaderByHandle(RE_RegisterShader(items->FindPairValue("shader", ""))); - } - else if(!Q_stricmp(type, "flattexture")) - { - mFlatShader = RE_RegisterShader ( items->FindPairValue("shader", "") ); + } else if (!Q_stricmp(type, "flattexture")) { + mFlatShader = RE_RegisterShader(items->FindPairValue("shader", "")); } items = (CGPGroup *)items->GetNext(); @@ -568,118 +493,94 @@ void CTRLandScape::LoadTerrainDef(const char *td) Com_ParseTextFileDestroy(parse); } -qhandle_t CTRLandScape::GetBlendedShader(qhandle_t a, qhandle_t b, qhandle_t c, bool surfaceSprites) -{ - qhandle_t blended; +qhandle_t CTRLandScape::GetBlendedShader(qhandle_t a, qhandle_t b, qhandle_t c, bool surfaceSprites) { + qhandle_t blended; // Special case single pass shader - if((a == b) && (a == c)) - { - return(a); + if ((a == b) && (a == c)) { + return (a); } - blended = R_CreateBlendedShader(a, b, c, surfaceSprites ); - return(blended); + blended = R_CreateBlendedShader(a, b, c, surfaceSprites); + return (blended); } -static int ComparePatchInfo(const TPatchInfo *arg1, const TPatchInfo *arg2) -{ - shader_t *s1, *s2; +static int ComparePatchInfo(const TPatchInfo *arg1, const TPatchInfo *arg2) { + shader_t *s1, *s2; - if ((arg1->mPart & PI_TOP)) - { + if ((arg1->mPart & PI_TOP)) { s1 = arg1->mPatch->GetTLShader(); - } - else - { + } else { s1 = arg1->mPatch->GetBRShader(); } - if ((arg2->mPart & PI_TOP)) - { + if ((arg2->mPart & PI_TOP)) { s2 = arg2->mPatch->GetTLShader(); - } - else - { + } else { s2 = arg2->mPatch->GetBRShader(); } - if (s1 < s2) - { + if (s1 < s2) { return -1; - } - else if (s1 > s2) - { + } else if (s1 > s2) { return 1; } return 0; } -void CTRLandScape::CalculateShaders(void) -{ - int x, y; - int width, height; - int offset; -// int offsets[4]; - qhandle_t handles[4]; - CTRPatch *patch; - qhandle_t *shaders; - TPatchInfo *current = mSortedPatches; +void CTRLandScape::CalculateShaders(void) { + int x, y; + int width, height; + int offset; + // int offsets[4]; + qhandle_t handles[4]; + CTRPatch *patch; + qhandle_t *shaders; + TPatchInfo *current = mSortedPatches; - width = GetWidth ( ) / common->GetTerxels ( ); - height = GetHeight ( ) / common->GetTerxels ( ); + width = GetWidth() / common->GetTerxels(); + height = GetHeight() / common->GetTerxels(); - shaders = new qhandle_t [ (width+1) * (height+1) ]; + shaders = new qhandle_t[(width + 1) * (height + 1)]; // On the first pass determine all of the shaders for the entire // terrain assuming no flat ground offset = 0; - for ( y = 0; y < height + 1; y ++ ) - { - if ( y <= height ) - { - offset = common->GetTerxels ( ) * y * GetRealWidth ( ); - } - else - { - offset = common->GetTerxels ( ) * (y-1) * GetRealWidth ( ); - offset += GetRealWidth ( ); + for (y = 0; y < height + 1; y++) { + if (y <= height) { + offset = common->GetTerxels() * y * GetRealWidth(); + } else { + offset = common->GetTerxels() * (y - 1) * GetRealWidth(); + offset += GetRealWidth(); } - for ( x = 0; x < width + 1; x ++, offset += common->GetTerxels ( ) ) - { + for (x = 0; x < width + 1; x++, offset += common->GetTerxels()) { // Save the shader - shaders[y * width + x] = GetHeightDetail(mRenderMap[offset].height)->GetShader ( ); + shaders[y * width + x] = GetHeightDetail(mRenderMap[offset].height)->GetShader(); } } // On the second pass determine flat ground and replace the shader // at that point with the flat ground shader - if ( mFlatShader ) - { - for ( y = 1; y < height; y ++ ) - { - for ( x = 1; x < width; x ++ ) - { - int offset; - int xx; - int yy; - byte* flattenMap = common->GetFlattenMap ( ); - bool flat = false; - - offset = (x) * common->GetTerxels ( ); - offset += (y) * common->GetTerxels ( ) * GetRealWidth(); + if (mFlatShader) { + for (y = 1; y < height; y++) { + for (x = 1; x < width; x++) { + int offset; + int xx; + int yy; + byte *flattenMap = common->GetFlattenMap(); + bool flat = false; + + offset = (x)*common->GetTerxels(); + offset += (y)*common->GetTerxels() * GetRealWidth(); offset -= GetRealWidth(); offset -= 1; - for ( yy = 0; yy < 3 && !flat; yy++ ) - { - for ( xx = 0; xx < 3 && !flat; xx++ ) - { - if ( flattenMap [ offset + xx] & 0x80) - { + for (yy = 0; yy < 3 && !flat; yy++) { + for (xx = 0; xx < 3 && !flat; xx++) { + if (flattenMap[offset + xx] & 0x80) { flat = true; break; } @@ -688,52 +589,50 @@ void CTRLandScape::CalculateShaders(void) offset += GetRealWidth(); } -/* - // Calculate the height map offset - offset = x * common->GetTerxels ( ); - offset += (y * common->GetTerxels ( ) * GetRealWidth()); - - // Calculate the offsets around this particular shader location - offsets[INDEX_TL] = offset - 1 - GetRealWidth(); - offsets[INDEX_TR] = offsets[INDEX_TL] + 1; - offsets[INDEX_BL] = offsets[INDEX_TL] + GetRealWidth(); - offsets[INDEX_BR] = offsets[INDEX_BL] + 1; - - // If not equal to the top left one then skip - if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_TL]].height ) - { - continue; - } - - // If not equal to the top right one then skip - if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_TR]].height ) - { - continue; - } - - // If not equal to the bottom left one then skip - if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_BL]].height ) - { - continue; - } - - // If not equal to the bottom right one then skip - if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_BR]].height ) - { - continue; - } - */ + /* + // Calculate the height map offset + offset = x * common->GetTerxels ( ); + offset += (y * common->GetTerxels ( ) * GetRealWidth()); + + // Calculate the offsets around this particular shader location + offsets[INDEX_TL] = offset - 1 - GetRealWidth(); + offsets[INDEX_TR] = offsets[INDEX_TL] + 1; + offsets[INDEX_BL] = offsets[INDEX_TL] + GetRealWidth(); + offsets[INDEX_BR] = offsets[INDEX_BL] + 1; + + // If not equal to the top left one then skip + if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_TL]].height ) + { + continue; + } + + // If not equal to the top right one then skip + if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_TR]].height ) + { + continue; + } + + // If not equal to the bottom left one then skip + if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_BL]].height ) + { + continue; + } + + // If not equal to the bottom right one then skip + if ( mRenderMap[offset].height != mRenderMap[offsets[INDEX_BR]].height ) + { + continue; + } + */ // This shader is now a flat shader - if ( flat ) - { + if (flat) { shaders[y * width + x] = mFlatShader; } #ifdef _DEBUG - Com_OPrintf("Flat Area: %f %f\n", - GetMins()[0] + (GetMaxs()[0]-GetMins()[0])/width * x, - GetMins()[1] + (GetMaxs()[1]-GetMins()[1])/height * y ); + Com_OPrintf("Flat Area: %f %f\n", GetMins()[0] + (GetMaxs()[0] - GetMins()[0]) / width * x, + GetMins()[1] + (GetMaxs()[1] - GetMins()[1]) / height * y); #endif } } @@ -742,22 +641,16 @@ void CTRLandScape::CalculateShaders(void) // Now that the shaders have been determined, set them for each patch patch = mTRPatches; mSortedCount = 0; - for ( y = 0; y < height; y ++ ) - { - for ( x = 0; x < width; x ++, patch++ ) - { + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++, patch++) { bool surfaceSprites = true; - handles[INDEX_TL] = shaders[ x + y * width ]; - handles[INDEX_TR] = shaders[ x + 1 + y * width ]; - handles[INDEX_BL] = shaders[ x + (y + 1) * width ]; - handles[INDEX_BR] = shaders[ x + 1 + (y + 1) * width ]; + handles[INDEX_TL] = shaders[x + y * width]; + handles[INDEX_TR] = shaders[x + 1 + y * width]; + handles[INDEX_BL] = shaders[x + (y + 1) * width]; + handles[INDEX_BR] = shaders[x + 1 + (y + 1) * width]; - if ( handles[INDEX_TL] == mFlatShader || - handles[INDEX_TR] == mFlatShader || - handles[INDEX_BL] == mFlatShader || - handles[INDEX_BR] == mFlatShader ) - { + if (handles[INDEX_TL] == mFlatShader || handles[INDEX_TR] == mFlatShader || handles[INDEX_BL] == mFlatShader || handles[INDEX_BR] == mFlatShader) { surfaceSprites = false; } @@ -767,12 +660,9 @@ void CTRLandScape::CalculateShaders(void) current->mPart = PI_TOP; patch->SetBRShader(GetBlendedShader(handles[INDEX_TR], handles[INDEX_BL], handles[INDEX_BR], surfaceSprites)); - if (patch->GetBRShader() == current->mShader) - { + if (patch->GetBRShader() == current->mShader) { current->mPart |= PI_BOTTOM; - } - else - { + } else { mSortedCount++; current++; @@ -788,21 +678,16 @@ void CTRLandScape::CalculateShaders(void) // Cleanup our temporary array delete[] shaders; - qsort(mSortedPatches, mSortedCount, sizeof(*mSortedPatches), (int (QDECL *)(const void *,const void *))ComparePatchInfo); - + qsort(mSortedPatches, mSortedCount, sizeof(*mSortedPatches), (int(QDECL *)(const void *, const void *))ComparePatchInfo); } -void CTRPatch::SetRenderMap(const int x, const int y) -{ - mRenderMap = localowner->GetRenderMap(x, y); -} +void CTRPatch::SetRenderMap(const int x, const int y) { mRenderMap = localowner->GetRenderMap(x, y); } -void InitRendererPatches( CCMPatch *patch, void *userdata ) -{ - int tx, ty, bx, by; - CTRPatch *localpatch; - CCMLandScape *owner; - CTRLandScape *localowner; +void InitRendererPatches(CCMPatch *patch, void *userdata) { + int tx, ty, bx, by; + CTRPatch *localpatch; + CCMLandScape *owner; + CTRLandScape *localowner; // Set owning landscape localowner = (CTRLandScape *)userdata; @@ -822,47 +707,40 @@ void InitRendererPatches( CCMPatch *patch, void *userdata ) localpatch->SetLocalOwner(localowner); localpatch->SetRenderMap(tx, ty); localpatch->SetCenter(); -// localpatch->CalcNormal(); + // localpatch->CalcNormal(); } -void CTRLandScape::CopyHeightMap(void) -{ - const CCMLandScape *common = GetCommon(); - const byte *heightMap = common->GetHeightMap(); - CTerVert *renderMap = mRenderMap; - int i; +void CTRLandScape::CopyHeightMap(void) { + const CCMLandScape *common = GetCommon(); + const byte *heightMap = common->GetHeightMap(); + CTerVert *renderMap = mRenderMap; + int i; - for(i = 0; i < common->GetRealArea(); i++) - { + for (i = 0; i < common->GetRealArea(); i++) { renderMap->height = *heightMap; renderMap++; heightMap++; } } -CTRLandScape::~CTRLandScape(void) -{ - if(mTRPatches) - { +CTRLandScape::~CTRLandScape(void) { + if (mTRPatches) { Z_Free(mTRPatches); mTRPatches = NULL; } - if (mSortedPatches) - { + if (mSortedPatches) { Z_Free(mSortedPatches); mSortedPatches = 0; } - if(mRenderMap) - { + if (mRenderMap) { Z_Free(mRenderMap); mRenderMap = NULL; } } -CTRLandScape::CTRLandScape(const char *configstring) -{ - int shaderNum; - const CCMLandScape *common; +CTRLandScape::CTRLandScape(const char *configstring) { + int shaderNum; + const CCMLandScape *common; memset(this, 0, sizeof(*this)); @@ -899,7 +777,7 @@ CTRLandScape::CTRLandScape(const char *configstring) // Calculate texture coords (not projected - real) CalculateTextureCoords(); - ri.Printf( PRINT_ALL, "R_Terrain: Creating renderer patches.....\n"); + ri.Printf(PRINT_ALL, "R_Terrain: Creating renderer patches.....\n"); // Initialise all terrain patches mTRPatches = (CTRPatch *)Z_Malloc(sizeof(CTRPatch) * common->GetBlockCount(), TAG_R_TERRAIN); @@ -912,20 +790,20 @@ CTRLandScape::CTRLandScape(const char *configstring) CalculateShaders(); // Get the contents shader - shaderNum = atol(Info_ValueForKey(configstring, "shader"));; + shaderNum = atol(Info_ValueForKey(configstring, "shader")); + ; mShader = R_GetShaderByHandle(R_GetShaderByNum(shaderNum, *tr.world)); mPatchSize = VectorLength(common->GetPatchSize()); -#if _DEBUG +#if _DEBUG mCycleCount = 0; #endif } // --------------------------------------------------------------------- -void RB_SurfaceTerrain( surfaceInfo_t *surf ) -{ +void RB_SurfaceTerrain(surfaceInfo_t *surf) { /* if(backEnd.refdef.rdflags & RDF_PROJECTION2D) { @@ -939,77 +817,64 @@ void RB_SurfaceTerrain( surfaceInfo_t *surf ) landscape->CalculateRegion(); landscape->Reset(); -// landscape->Tessellate(); + // landscape->Tessellate(); landscape->Render(); } -void R_CalcTerrainVisBounds(CTRLandScape *landscape) -{ +void R_CalcTerrainVisBounds(CTRLandScape *landscape) { const CCMLandScape *common = landscape->GetCommon(); // Set up the visbounds using terrain data - if ( common->GetMins()[0] < tr.viewParms.visBounds[0][0] ) - { + if (common->GetMins()[0] < tr.viewParms.visBounds[0][0]) { tr.viewParms.visBounds[0][0] = common->GetMins()[0]; } - if ( common->GetMins()[1] < tr.viewParms.visBounds[0][1] ) - { + if (common->GetMins()[1] < tr.viewParms.visBounds[0][1]) { tr.viewParms.visBounds[0][1] = common->GetMins()[1]; } - if ( common->GetMins()[2] < tr.viewParms.visBounds[0][2] ) - { + if (common->GetMins()[2] < tr.viewParms.visBounds[0][2]) { tr.viewParms.visBounds[0][2] = common->GetMins()[2]; } - if ( common->GetMaxs()[0] > tr.viewParms.visBounds[1][0] ) - { + if (common->GetMaxs()[0] > tr.viewParms.visBounds[1][0]) { tr.viewParms.visBounds[1][0] = common->GetMaxs()[0]; } - if ( common->GetMaxs()[1] > tr.viewParms.visBounds[1][1] ) - { + if (common->GetMaxs()[1] > tr.viewParms.visBounds[1][1]) { tr.viewParms.visBounds[1][1] = common->GetMaxs()[1]; } - if ( common->GetMaxs()[2] > tr.viewParms.visBounds[1][2] ) - { + if (common->GetMaxs()[2] > tr.viewParms.visBounds[1][2]) { tr.viewParms.visBounds[1][2] = common->GetMaxs()[2]; } } -void R_AddTerrainSurfaces(void) -{ - CTRLandScape *landscape; +void R_AddTerrainSurfaces(void) { + CTRLandScape *landscape; - if (!r_drawTerrain->integer || (tr.refdef.rdflags & RDF_NOWORLDMODEL)) - { + if (!r_drawTerrain->integer || (tr.refdef.rdflags & RDF_NOWORLDMODEL)) { return; } landscape = tr.landScape.landscape; - if(landscape) - { - R_AddDrawSurf( (surfaceType_t *)(&tr.landScape), landscape->GetShader(), 0, qfalse ); + if (landscape) { + R_AddDrawSurf((surfaceType_t *)(&tr.landScape), landscape->GetShader(), 0, qfalse); R_CalcTerrainVisBounds(landscape); } } -void RE_InitRendererTerrain( const char *info ) -{ - //CTRLandScape *ls; +void RE_InitRendererTerrain(const char *info) { + // CTRLandScape *ls; - if ( !info || !info[0] ) - { - ri.Printf( PRINT_ALL, "RE_RegisterTerrain: NULL name\n" ); + if (!info || !info[0]) { + ri.Printf(PRINT_ALL, "RE_RegisterTerrain: NULL name\n"); return; } - ri.Printf( PRINT_ALL, "R_Terrain: Creating RENDERER data.....\n"); + ri.Printf(PRINT_ALL, "R_Terrain: Creating RENDERER data.....\n"); // Create and register a new landscape structure - /*ls = */new CTRLandScape(info); + /*ls = */ new CTRLandScape(info); } -void R_TerrainInit(void) -{ +void R_TerrainInit(void) { tr.landScape.surfaceType = SF_TERRAIN; tr.landScape.landscape = NULL; @@ -1022,14 +887,12 @@ void R_TerrainInit(void) tr.distanceCullSquared = tr.distanceCull * tr.distanceCull; } -void R_TerrainShutdown(void) -{ - CTRLandScape *ls; +void R_TerrainShutdown(void) { + CTRLandScape *ls; -// ri.Printf( PRINT_ALL, "R_Terrain: Shutting down RENDERER terrain.....\n"); + // ri.Printf( PRINT_ALL, "R_Terrain: Shutting down RENDERER terrain.....\n"); ls = tr.landScape.landscape; - if(ls) - { + if (ls) { ri.CM_ShutdownTerrain(0); delete ls; tr.landScape.landscape = NULL; diff --git a/codemp/rd-vanilla/tr_world.cpp b/codemp/rd-vanilla/tr_world.cpp index 5216830090..ff002235b6 100644 --- a/codemp/rd-vanilla/tr_world.cpp +++ b/codemp/rd-vanilla/tr_world.cpp @@ -23,11 +23,7 @@ along with this program; if not, see . #include "tr_local.h" -inline void Q_CastShort2Float(float *f, const short *s) -{ - *f = ((float)*s); -} - +inline void Q_CastShort2Float(float *f, const short *s) { *f = ((float)*s); } /* ================= @@ -37,12 +33,12 @@ Returns true if the grid is completely culled away. Also sets the clipped hint bit in tess ================= */ -static qboolean R_CullTriSurf( srfTriangles_t *cv ) { - int boxCull; +static qboolean R_CullTriSurf(srfTriangles_t *cv) { + int boxCull; - boxCull = R_CullLocalBox( cv->bounds ); + boxCull = R_CullLocalBox(cv->bounds); - if ( boxCull == CULL_OUT ) { + if (boxCull == CULL_OUT) { return qtrue; } return qfalse; @@ -56,57 +52,47 @@ Returns true if the grid is completely culled away. Also sets the clipped hint bit in tess ================= */ -static qboolean R_CullGrid( srfGridMesh_t *cv ) { - int boxCull; - int sphereCull; +static qboolean R_CullGrid(srfGridMesh_t *cv) { + int boxCull; + int sphereCull; - if ( r_nocurves->integer ) { + if (r_nocurves->integer) { return qtrue; } - if ( tr.currentEntityNum != REFENTITYNUM_WORLD ) { - sphereCull = R_CullLocalPointAndRadius( cv->localOrigin, cv->meshRadius ); + if (tr.currentEntityNum != REFENTITYNUM_WORLD) { + sphereCull = R_CullLocalPointAndRadius(cv->localOrigin, cv->meshRadius); } else { - sphereCull = R_CullPointAndRadius( cv->localOrigin, cv->meshRadius ); + sphereCull = R_CullPointAndRadius(cv->localOrigin, cv->meshRadius); } boxCull = CULL_OUT; // check for trivial reject - if ( sphereCull == CULL_OUT ) - { + if (sphereCull == CULL_OUT) { tr.pc.c_sphere_cull_patch_out++; return qtrue; } // check bounding box if necessary - else if ( sphereCull == CULL_CLIP ) - { + else if (sphereCull == CULL_CLIP) { tr.pc.c_sphere_cull_patch_clip++; - boxCull = R_CullLocalBox( cv->meshBounds ); + boxCull = R_CullLocalBox(cv->meshBounds); - if ( boxCull == CULL_OUT ) - { + if (boxCull == CULL_OUT) { tr.pc.c_box_cull_patch_out++; return qtrue; - } - else if ( boxCull == CULL_IN ) - { + } else if (boxCull == CULL_IN) { tr.pc.c_box_cull_patch_in++; - } - else - { + } else { tr.pc.c_box_cull_patch_clip++; } - } - else - { + } else { tr.pc.c_sphere_cull_patch_in++; } return qfalse; } - /* ================ R_CullSurface @@ -117,42 +103,39 @@ added to the sorting list. This will also allow mirrors on both sides of a model without recursion. ================ */ -static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { +static qboolean R_CullSurface(surfaceType_t *surface, shader_t *shader) { srfSurfaceFace_t *sface; - float d; + float d; - if ( r_nocull->integer ) { + if (r_nocull->integer) { return qfalse; } - if ( *surface == SF_GRID ) { - return R_CullGrid( (srfGridMesh_t *)surface ); + if (*surface == SF_GRID) { + return R_CullGrid((srfGridMesh_t *)surface); } - if ( *surface == SF_TRIANGLES ) { - return R_CullTriSurf( (srfTriangles_t *)surface ); + if (*surface == SF_TRIANGLES) { + return R_CullTriSurf((srfTriangles_t *)surface); } - if ( *surface != SF_FACE ) { + if (*surface != SF_FACE) { return qfalse; } - if ( shader->cullType == CT_TWO_SIDED ) { + if (shader->cullType == CT_TWO_SIDED) { return qfalse; } // face culling - if ( !r_facePlaneCull->integer ) { + if (!r_facePlaneCull->integer) { return qfalse; } - sface = ( srfSurfaceFace_t * ) surface; + sface = (srfSurfaceFace_t *)surface; - if (r_cullRoofFaces->integer) - { //Very slow, but this is only intended for taking shots for automap images. - if (sface->plane.normal[2] > 0.0f && - sface->numPoints > 0) - { //it's facing up I guess + if (r_cullRoofFaces->integer) { // Very slow, but this is only intended for taking shots for automap images. + if (sface->plane.normal[2] > 0.0f && sface->numPoints > 0) { // it's facing up I guess static int i; static trace_t tr; static vec3_t basePoint; @@ -160,69 +143,61 @@ static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { static vec3_t nNormal; static vec3_t v; - //The fact that this point is in the middle of the array has no relation to the - //orientation in the surface outline. - basePoint[0] = sface->points[sface->numPoints/2][0]; - basePoint[1] = sface->points[sface->numPoints/2][1]; - basePoint[2] = sface->points[sface->numPoints/2][2]; + // The fact that this point is in the middle of the array has no relation to the + // orientation in the surface outline. + basePoint[0] = sface->points[sface->numPoints / 2][0]; + basePoint[1] = sface->points[sface->numPoints / 2][1]; + basePoint[2] = sface->points[sface->numPoints / 2][2]; basePoint[2] += 2.0f; - //the endpoint will be 8192 units from the chosen point - //in the direction of the surface normal + // the endpoint will be 8192 units from the chosen point + // in the direction of the surface normal - //just go straight up I guess, for now (slight hack) + // just go straight up I guess, for now (slight hack) VectorSet(nNormal, 0.0f, 0.0f, 1.0f); VectorMA(basePoint, 8192.0f, nNormal, endPoint); - ri.CM_BoxTrace(&tr, basePoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID|CONTENTS_TERRAIN), qfalse); + ri.CM_BoxTrace(&tr, basePoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID | CONTENTS_TERRAIN), qfalse); - if (!tr.startsolid && - !tr.allsolid && - (tr.fraction == 1.0f || (tr.surfaceFlags & SURF_NOIMPACT))) - { //either hit nothing or sky, so this surface is near the top of the level I guess. Or the floor of a really tall room, but if that's the case we're just screwed. + if (!tr.startsolid && !tr.allsolid && + (tr.fraction == 1.0f || + (tr.surfaceFlags & SURF_NOIMPACT))) { // either hit nothing or sky, so this surface is near the top of the level I guess. Or the floor of a + // really tall room, but if that's the case we're just screwed. VectorSubtract(basePoint, tr.endpos, v); - if (tr.fraction == 1.0f || VectorLength(v) < r_roofCullCeilDist->value) - { //ignore it if it's not close to the top, unless it just hit nothing - //Let's try to dig back into the brush based on the negative direction of the plane, - //and if we pop out on the other side we'll see if it's ground or not. + if (tr.fraction == 1.0f || VectorLength(v) < r_roofCullCeilDist->value) { // ignore it if it's not close to the top, unless it just hit nothing + // Let's try to dig back into the brush based on the negative direction of the plane, + // and if we pop out on the other side we'll see if it's ground or not. i = 4; VectorCopy(sface->plane.normal, nNormal); VectorInverse(nNormal); - while (i < 4096) - { + while (i < 4096) { VectorMA(basePoint, i, nNormal, endPoint); - ri.CM_BoxTrace(&tr, endPoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID|CONTENTS_TERRAIN), qfalse); - if (!tr.startsolid && - !tr.allsolid && - tr.fraction == 1.0f) - { //in the clear + ri.CM_BoxTrace(&tr, endPoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID | CONTENTS_TERRAIN), qfalse); + if (!tr.startsolid && !tr.allsolid && tr.fraction == 1.0f) { // in the clear break; } i++; } - if (i < 4096) - { //Make sure we got into clearance + if (i < 4096) { // Make sure we got into clearance VectorCopy(endPoint, basePoint); basePoint[2] -= 2.0f; - //just go straight down I guess, for now (slight hack) + // just go straight down I guess, for now (slight hack) VectorSet(nNormal, 0.0f, 0.0f, -1.0f); VectorMA(basePoint, 4096.0f, nNormal, endPoint); - //trace a second time from the clear point in the inverse normal direction of the surface. - //If we hit something within a set amount of units, we will assume it's a bridge type object - //and leave it to be drawn. Otherwise we will assume it is a roof or other obstruction and - //cull it out. - ri.CM_BoxTrace(&tr, basePoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID|CONTENTS_TERRAIN), qfalse); + // trace a second time from the clear point in the inverse normal direction of the surface. + // If we hit something within a set amount of units, we will assume it's a bridge type object + // and leave it to be drawn. Otherwise we will assume it is a roof or other obstruction and + // cull it out. + ri.CM_BoxTrace(&tr, basePoint, endPoint, NULL, NULL, 0, (CONTENTS_SOLID | CONTENTS_TERRAIN), qfalse); - if (!tr.startsolid && - !tr.allsolid && - (tr.fraction != 1.0f && !(tr.surfaceFlags & SURF_NOIMPACT))) - { //if we hit nothing or a noimpact going down then this is probably "ground". + if (!tr.startsolid && !tr.allsolid && + (tr.fraction != 1.0f && + !(tr.surfaceFlags & SURF_NOIMPACT))) { // if we hit nothing or a noimpact going down then this is probably "ground". VectorSubtract(basePoint, tr.endpos, endPoint); - if (VectorLength(endPoint) > r_roofCullCeilDist->value) - { //128 (by default) is our maximum tolerance, above that will be removed + if (VectorLength(endPoint) > r_roofCullCeilDist->value) { // 128 (by default) is our maximum tolerance, above that will be removed return qtrue; } } @@ -232,17 +207,17 @@ static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { } } - d = DotProduct (tr.ori.viewOrigin, sface->plane.normal); + d = DotProduct(tr.ori.viewOrigin, sface->plane.normal); // don't cull exactly on the plane, because there are levels of rounding // through the BSP, ICD, and hardware that may cause pixel gaps if an // epsilon isn't allowed here - if ( shader->cullType == CT_FRONT_SIDED ) { - if ( d < sface->plane.dist - 8 ) { + if (shader->cullType == CT_FRONT_SIDED) { + if (d < sface->plane.dist - 8) { return qtrue; } } else { - if ( d > sface->plane.dist + 8 ) { + if (d > sface->plane.dist + 8) { return qtrue; } } @@ -250,24 +225,24 @@ static qboolean R_CullSurface( surfaceType_t *surface, shader_t *shader ) { return qfalse; } -static int R_DlightFace( srfSurfaceFace_t *face, int dlightBits ) { - float d; - int i; - dlight_t *dl; +static int R_DlightFace(srfSurfaceFace_t *face, int dlightBits) { + float d; + int i; + dlight_t *dl; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - d = DotProduct( dl->origin, face->plane.normal ) - face->plane.dist; - if ( !VectorCompare(face->plane.normal, vec3_origin) && (d < -dl->radius || d > dl->radius) ) { + d = DotProduct(dl->origin, face->plane.normal) - face->plane.dist; + if (!VectorCompare(face->plane.normal, vec3_origin) && (d < -dl->radius || d > dl->radius)) { // dlight doesn't reach the plane - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } - if ( !dlightBits ) { + if (!dlightBits) { tr.pc.c_dlightSurfacesCulled++; } @@ -275,27 +250,24 @@ static int R_DlightFace( srfSurfaceFace_t *face, int dlightBits ) { return dlightBits; } -static int R_DlightGrid( srfGridMesh_t *grid, int dlightBits ) { - int i; - dlight_t *dl; +static int R_DlightGrid(srfGridMesh_t *grid, int dlightBits) { + int i; + dlight_t *dl; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { - if ( ! ( dlightBits & ( 1 << i ) ) ) { + for (i = 0; i < tr.refdef.num_dlights; i++) { + if (!(dlightBits & (1 << i))) { continue; } dl = &tr.refdef.dlights[i]; - if ( dl->origin[0] - dl->radius > grid->meshBounds[1][0] - || dl->origin[0] + dl->radius < grid->meshBounds[0][0] - || dl->origin[1] - dl->radius > grid->meshBounds[1][1] - || dl->origin[1] + dl->radius < grid->meshBounds[0][1] - || dl->origin[2] - dl->radius > grid->meshBounds[1][2] - || dl->origin[2] + dl->radius < grid->meshBounds[0][2] ) { + if (dl->origin[0] - dl->radius > grid->meshBounds[1][0] || dl->origin[0] + dl->radius < grid->meshBounds[0][0] || + dl->origin[1] - dl->radius > grid->meshBounds[1][1] || dl->origin[1] + dl->radius < grid->meshBounds[0][1] || + dl->origin[2] - dl->radius > grid->meshBounds[1][2] || dl->origin[2] + dl->radius < grid->meshBounds[0][2]) { // dlight doesn't reach the bounds - dlightBits &= ~( 1 << i ); + dlightBits &= ~(1 << i); } } - if ( !dlightBits ) { + if (!dlightBits) { tr.pc.c_dlightSurfacesCulled++; } @@ -303,8 +275,7 @@ static int R_DlightGrid( srfGridMesh_t *grid, int dlightBits ) { return dlightBits; } - -static int R_DlightTrisurf( srfTriangles_t *surf, int dlightBits ) { +static int R_DlightTrisurf(srfTriangles_t *surf, int dlightBits) { // FIXME: more dlight culling to trisurfs... surf->dlightBits = dlightBits; return dlightBits; @@ -346,26 +317,24 @@ that is touched by one or more dlights, so try to throw out more dlights if possible. ==================== */ -static int R_DlightSurface( msurface_t *surf, int dlightBits ) { - if ( *surf->data == SF_FACE ) { - dlightBits = R_DlightFace( (srfSurfaceFace_t *)surf->data, dlightBits ); - } else if ( *surf->data == SF_GRID ) { - dlightBits = R_DlightGrid( (srfGridMesh_t *)surf->data, dlightBits ); - } else if ( *surf->data == SF_TRIANGLES ) { - dlightBits = R_DlightTrisurf( (srfTriangles_t *)surf->data, dlightBits ); +static int R_DlightSurface(msurface_t *surf, int dlightBits) { + if (*surf->data == SF_FACE) { + dlightBits = R_DlightFace((srfSurfaceFace_t *)surf->data, dlightBits); + } else if (*surf->data == SF_GRID) { + dlightBits = R_DlightGrid((srfGridMesh_t *)surf->data, dlightBits); + } else if (*surf->data == SF_TRIANGLES) { + dlightBits = R_DlightTrisurf((srfTriangles_t *)surf->data, dlightBits); } else { dlightBits = 0; } - if ( dlightBits ) { + if (dlightBits) { tr.pc.c_dlightSurfaces++; } return dlightBits; } - - #ifdef _ALT_AUTOMAP_METHOD static bool tr_drawingAutoMap = false; #endif @@ -376,23 +345,15 @@ static float g_playerHeight = 0.0f; R_AddWorldSurface ====================== */ -static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noViewCount = qfalse ) -{ - if (!noViewCount) - { - if ( surf->viewCount == tr.viewCount ) - { +static void R_AddWorldSurface(msurface_t *surf, int dlightBits, qboolean noViewCount = qfalse) { + if (!noViewCount) { + if (surf->viewCount == tr.viewCount) { // already in this view, but lets make sure all the dlight bits are set - if ( *surf->data == SF_FACE ) - { + if (*surf->data == SF_FACE) { ((srfSurfaceFace_t *)surf->data)->dlightBits |= dlightBits; - } - else if ( *surf->data == SF_GRID ) - { + } else if (*surf->data == SF_GRID) { ((srfGridMesh_t *)surf->data)->dlightBits |= dlightBits; - } - else if ( *surf->data == SF_TRIANGLES ) - { + } else if (*surf->data == SF_TRIANGLES) { ((srfTriangles_t *)surf->data)->dlightBits |= dlightBits; } return; @@ -409,11 +370,11 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView R_AddDrawSurf( surf->data, tr.shadowShader, surf->fogIndex, dlightBits ); } */ - //world shadows? + // world shadows? // try to cull before dlighting or adding #ifdef _ALT_AUTOMAP_METHOD - if (!tr_drawingAutoMap && R_CullSurface( surf->data, surf->shader ) ) + if (!tr_drawingAutoMap && R_CullSurface(surf->data, surf->shader)) #else if (R_CullSurface(surf->data, surf->shader)) #endif @@ -422,18 +383,16 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView } // check for dlighting - if ( dlightBits ) { - dlightBits = R_DlightSurface( surf, dlightBits ); - dlightBits = ( dlightBits != 0 ); + if (dlightBits) { + dlightBits = R_DlightSurface(surf, dlightBits); + dlightBits = (dlightBits != 0); } #ifdef _ALT_AUTOMAP_METHOD - if (tr_drawingAutoMap) - { - // if (g_playerHeight != g_lastHeight || - // !g_lastHeightValid) - if (*surf->data == SF_FACE) - { //only do this if we need to + if (tr_drawingAutoMap) { + // if (g_playerHeight != g_lastHeight || + // !g_lastHeightValid) + if (*surf->data == SF_FACE) { // only do this if we need to bool completelyTransparent = true; int i = 0; srfSurfaceFace_t *face = (srfSurfaceFace_t *)surf->data; @@ -444,79 +403,63 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView float e; bool polyStarted = false; - while (i < face->numIndices) - { + while (i < face->numIndices) { point = &face->points[indices[i]][0]; - //base the color on the elevation... for now, just check the first point height - if (point[2] < g_playerHeight) - { - e = point[2]-g_playerHeight; - } - else - { - e = g_playerHeight-point[2]; + // base the color on the elevation... for now, just check the first point height + if (point[2] < g_playerHeight) { + e = point[2] - g_playerHeight; + } else { + e = g_playerHeight - point[2]; } - if (e < 0.0f) - { + if (e < 0.0f) { e = -e; } - //set alpha and color based on relative height of point - alpha = e/256.0f; + // set alpha and color based on relative height of point + alpha = e / 256.0f; e /= 512.0f; - //cap color - if (e > 1.0f) - { + // cap color + if (e > 1.0f) { e = 1.0f; - } - else if (e < 0.0f) - { + } else if (e < 0.0f) { e = 0.0f; } - VectorSet(color, e, 1.0f-e, 0.0f); + VectorSet(color, e, 1.0f - e, 0.0f); - //cap alpha - if (alpha > 1.0f) - { + // cap alpha + if (alpha > 1.0f) { alpha = 1.0f; - } - else if (alpha < 0.0f) - { + } else if (alpha < 0.0f) { alpha = 0.0f; } - if (alpha != 1.0f) - { //this point is not entirely alpha'd out, so still draw the surface + if (alpha != 1.0f) { // this point is not entirely alpha'd out, so still draw the surface completelyTransparent = false; } - if (!completelyTransparent) - { - if (!polyStarted) - { + if (!completelyTransparent) { + if (!polyStarted) { qglBegin(GL_POLYGON); polyStarted = true; } - qglColor4f(color[0], color[1], color[2], 1.0f-alpha); + qglColor4f(color[0], color[1], color[2], 1.0f - alpha); qglVertex3f(point[i], point[i], point[2]); } i++; } - if (polyStarted) - { + if (polyStarted) { qglEnd(); } } - } - else + } else #endif { - R_AddDrawSurf( surf->data, surf->shader, surf->fogIndex, dlightBits ); + R_AddDrawSurf(surf->data, surf->shader, surf->fogIndex, dlightBits); } } @@ -533,90 +476,84 @@ static void R_AddWorldSurface( msurface_t *surf, int dlightBits, qboolean noView R_AddBrushModelSurfaces ================= */ -void R_AddBrushModelSurfaces ( trRefEntity_t *ent ) { - bmodel_t *bmodel; - int clip; - model_t *pModel; - int i; +void R_AddBrushModelSurfaces(trRefEntity_t *ent) { + bmodel_t *bmodel; + int clip; + model_t *pModel; + int i; - pModel = R_GetModelByHandle( ent->e.hModel ); + pModel = R_GetModelByHandle(ent->e.hModel); bmodel = pModel->bmodel; - clip = R_CullLocalBox( bmodel->bounds ); - if ( clip == CULL_OUT ) { + clip = R_CullLocalBox(bmodel->bounds); + if (clip == CULL_OUT) { return; } - if(pModel->bspInstance) - { //rwwRMG - added + if (pModel->bspInstance) { // rwwRMG - added R_SetupEntityLighting(&tr.refdef, ent); } - //rww - Take this into account later? -// if ( !ri.Cvar_VariableIntegerValue( "com_RMG" ) ) -// { // don't dlight bmodels on rmg, as multiple copies of the same instance will light up - R_DlightBmodel( bmodel, false ); -// } -// else -// { -// R_DlightBmodel( bmodel, true ); -// } + // rww - Take this into account later? + // if ( !ri.Cvar_VariableIntegerValue( "com_RMG" ) ) + // { // don't dlight bmodels on rmg, as multiple copies of the same instance will light up + R_DlightBmodel(bmodel, false); + // } + // else + // { + // R_DlightBmodel( bmodel, true ); + // } - for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { - R_AddWorldSurface( bmodel->firstSurface + i, tr.currentEntity->dlightBits, qtrue ); + for (i = 0; i < bmodel->numSurfaces; i++) { + R_AddWorldSurface(bmodel->firstSurface + i, tr.currentEntity->dlightBits, qtrue); } } -float GetQuadArea( vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4 ) -{ - vec3_t vec1, vec2, dis1, dis2; +float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) { + vec3_t vec1, vec2, dis1, dis2; // Get area of tri1 - VectorSubtract( v1, v2, vec1 ); - VectorSubtract( v1, v4, vec2 ); - CrossProduct( vec1, vec2, dis1 ); - VectorScale( dis1, 0.25f, dis1 ); + VectorSubtract(v1, v2, vec1); + VectorSubtract(v1, v4, vec2); + CrossProduct(vec1, vec2, dis1); + VectorScale(dis1, 0.25f, dis1); // Get area of tri2 - VectorSubtract( v3, v2, vec1 ); - VectorSubtract( v3, v4, vec2 ); - CrossProduct( vec1, vec2, dis2 ); - VectorScale( dis2, 0.25f, dis2 ); + VectorSubtract(v3, v2, vec1); + VectorSubtract(v3, v4, vec2); + CrossProduct(vec1, vec2, dis2); + VectorScale(dis2, 0.25f, dis2); // Return addition of disSqr of each tri area - return ( dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + - dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2] ); + return (dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2]); } -void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) -{ - msurface_t *surfs; - srfSurfaceFace_t *face; - bmodel_t *bmodel; - model_t *pModel; - int i; +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) { + msurface_t *surfs; + srfSurfaceFace_t *face; + bmodel_t *bmodel; + model_t *pModel; + int i; // Not sure if we really need to track the best two candidates - int maxDist[2]={0,0}; - int maxIndx[2]={0,0}; - int dist = 0; - float dot1, dot2; + int maxDist[2] = {0, 0}; + int maxIndx[2] = {0, 0}; + int dist = 0; + float dot1, dot2; - pModel = R_GetModelByHandle( bmodelIndex ); + pModel = R_GetModelByHandle(bmodelIndex); bmodel = pModel->bmodel; // Loop through all surfaces on the brush and find the best two candidates - for ( i = 0 ; i < bmodel->numSurfaces; i++ ) - { + for (i = 0; i < bmodel->numSurfaces; i++) { surfs = bmodel->firstSurface + i; - face = ( srfSurfaceFace_t *)surfs->data; + face = (srfSurfaceFace_t *)surfs->data; // It seems that the safest way to handle this is by finding the area of the faces - dist = GetQuadArea( face->points[0], face->points[1], face->points[2], face->points[3] ); + dist = GetQuadArea(face->points[0], face->points[1], face->points[2], face->points[3]); // Check against the highest max - if ( dist > maxDist[0] ) - { + if (dist > maxDist[0]) { // Shuffle our current maxes down maxDist[1] = maxDist[0]; maxIndx[1] = maxIndx[0]; @@ -625,8 +562,7 @@ void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) maxIndx[0] = i; } // Check against the second highest max - else if ( dist >= maxDist[1] ) - { + else if (dist >= maxDist[1]) { // just stomp the old maxDist[1] = dist; maxIndx[1] = i; @@ -635,33 +571,27 @@ void RE_GetBModelVerts( int bmodelIndex, vec3_t *verts, vec3_t normal ) // Hopefully we've found two best case candidates. Now we should see which of these faces the viewer surfs = bmodel->firstSurface + maxIndx[0]; - face = ( srfSurfaceFace_t *)surfs->data; - dot1 = DotProduct( face->plane.normal, tr.refdef.viewaxis[0] ); + face = (srfSurfaceFace_t *)surfs->data; + dot1 = DotProduct(face->plane.normal, tr.refdef.viewaxis[0]); surfs = bmodel->firstSurface + maxIndx[1]; - face = ( srfSurfaceFace_t *)surfs->data; - dot2 = DotProduct( face->plane.normal, tr.refdef.viewaxis[0] ); + face = (srfSurfaceFace_t *)surfs->data; + dot2 = DotProduct(face->plane.normal, tr.refdef.viewaxis[0]); - if ( dot2 < dot1 && dot2 < 0.0f ) - { + if (dot2 < dot1 && dot2 < 0.0f) { i = maxIndx[1]; // use the second face - } - else if ( dot1 < dot2 && dot1 < 0.0f ) - { + } else if (dot1 < dot2 && dot1 < 0.0f) { i = maxIndx[0]; // use the first face - } - else - { // Possibly only have one face, so may as well use the first face, which also should be the best one - //i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen + } else { // Possibly only have one face, so may as well use the first face, which also should be the best one + // i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen i = maxIndx[0]; // use the first face } surfs = bmodel->firstSurface + i; - face = ( srfSurfaceFace_t *)surfs->data; + face = (srfSurfaceFace_t *)surfs->data; - for ( int t = 0; t < 4; t++ ) - { - VectorCopy( face->points[t], verts[t] ); + for (int t = 0; t < 4; t++) { + VectorCopy(face->points[t], verts[t]); } } @@ -679,71 +609,62 @@ WIREFRAME AUTOMAP GENERATION SYSTEM - BEGIN ============================================================= */ #ifndef _ALT_AUTOMAP_METHOD -typedef struct wireframeSurfPoint_s -{ - vec3_t xyz; - float alpha; - vec3_t color; +typedef struct wireframeSurfPoint_s { + vec3_t xyz; + float alpha; + vec3_t color; } wireframeSurfPoint_t; -typedef struct wireframeMapSurf_s -{ - bool completelyTransparent; +typedef struct wireframeMapSurf_s { + bool completelyTransparent; - int numPoints; - wireframeSurfPoint_t *points; + int numPoints; + wireframeSurfPoint_t *points; - wireframeMapSurf_s *next; + wireframeMapSurf_s *next; } wireframeMapSurf_t; -typedef struct wireframeMap_s -{ - wireframeMapSurf_t *surfs; +typedef struct wireframeMap_s { + wireframeMapSurf_t *surfs; } wireframeMap_t; static wireframeMap_t g_autoMapFrame; static wireframeMapSurf_t **g_autoMapNextFree = NULL; -static bool g_autoMapValid = false; //set to true of g_autoMapFrame is valid. +static bool g_autoMapValid = false; // set to true of g_autoMapFrame is valid. -//get the next available wireframe automap surface. -rww -static inline wireframeMapSurf_t *R_GetNewWireframeMapSurf(void) -{ +// get the next available wireframe automap surface. -rww +static inline wireframeMapSurf_t *R_GetNewWireframeMapSurf(void) { wireframeMapSurf_t **next = &g_autoMapFrame.surfs; - if (g_autoMapNextFree) - { //save us the time of going through the entire linked list from root + if (g_autoMapNextFree) { // save us the time of going through the entire linked list from root next = g_autoMapNextFree; } - while (*next) - { //iterate through until we find the next unused one + while (*next) { // iterate through until we find the next unused one next = &(*next)->next; } - //allocate memory for it and pass it back + // allocate memory for it and pass it back (*next) = (wireframeMapSurf_t *)Z_Malloc(sizeof(wireframeMapSurf_t), TAG_ALL, qtrue); g_autoMapNextFree = &(*next)->next; return (*next); } -//evaluate a surface, see if it is valid for being part of the -//wireframe map render. -rww -static inline void R_EvaluateWireframeSurf(msurface_t *surf) -{ - if (*surf->data == SF_FACE) - { +// evaluate a surface, see if it is valid for being part of the +// wireframe map render. -rww +static inline void R_EvaluateWireframeSurf(msurface_t *surf) { + if (*surf->data == SF_FACE) { srfSurfaceFace_t *face = (srfSurfaceFace_t *)surf->data; float *points = &face->points[0][0]; int numPoints = face->numIndices; int *indices = (int *)((byte *)face + face->ofsIndices); - //byte *indices = (byte *)(face + face->ofsIndices); + // byte *indices = (byte *)(face + face->ofsIndices); - if (points && numPoints > 0) - { //we can add it + if (points && numPoints > 0) { // we can add it int i = 0; wireframeMapSurf_t *nextSurf = R_GetNewWireframeMapSurf(); -#if 0 //doing in realtime now +#if 0 // doing in realtime now float e; //base the color on the elevation... for now, just check the first point height @@ -767,30 +688,23 @@ static inline void R_EvaluateWireframeSurf(msurface_t *surf) VectorSet(color, e, 1.0f-e, 0.0f); #endif - //now go through the indices and add a point for each - nextSurf->points = (wireframeSurfPoint_t *)Z_Malloc(sizeof(wireframeSurfPoint_t)*face->numIndices, TAG_ALL, qtrue); + // now go through the indices and add a point for each + nextSurf->points = (wireframeSurfPoint_t *)Z_Malloc(sizeof(wireframeSurfPoint_t) * face->numIndices, TAG_ALL, qtrue); nextSurf->numPoints = face->numIndices; - while (i < face->numIndices) - { + while (i < face->numIndices) { points = &face->points[indices[i]][0]; VectorCopy(points, nextSurf->points[i].xyz); i++; } } - } - else if (*surf->data == SF_TRIANGLES) - { - //srfTriangles_t *surfTri = (srfTriangles_t *)surf->data; - return; //not handled - } - else if (*surf->data == SF_GRID) - { - //srfGridMesh_t *gridMesh = (srfGridMesh_t *)surf->data; - return; //not handled - } - else - { //...unknown type? + } else if (*surf->data == SF_TRIANGLES) { + // srfTriangles_t *surfTri = (srfTriangles_t *)surf->data; + return; // not handled + } else if (*surf->data == SF_GRID) { + // srfGridMesh_t *gridMesh = (srfGridMesh_t *)surf->data; + return; // not handled + } else { //...unknown type? return; } } @@ -847,28 +761,22 @@ static inline bool R_NodeHasOppositeFaces(mnode_t *node) } #endif -//recursively called for each node to go through the surfaces on that -//node and generate the wireframe map. -rww -static inline void R_RecursiveWireframeSurf(mnode_t *node) -{ +// recursively called for each node to go through the surfaces on that +// node and generate the wireframe map. -rww +static inline void R_RecursiveWireframeSurf(mnode_t *node) { int c; msurface_t *surf, **mark; - if (!node) - { + if (!node) { return; } - while (1) - { - if (!node || - node->visframe != tr.visCount) - { //not valid, stop this chain of recursion + while (1) { + if (!node || node->visframe != tr.visCount) { // not valid, stop this chain of recursion return; } - if ( node->contents != -1 ) - { + if (node->contents != -1) { break; } @@ -880,8 +788,7 @@ static inline void R_RecursiveWireframeSurf(mnode_t *node) // add the individual surfaces mark = node->firstmarksurface; c = node->nummarksurfaces; - while (c--) - { + while (c--) { // the surface may have already been added if it // spans multiple leafs surf = *mark; @@ -890,118 +797,104 @@ static inline void R_RecursiveWireframeSurf(mnode_t *node) } } -//generates a wireframe model of the map for the automap view -rww -static void R_GenerateWireframeMap(mnode_t *baseNode) -{ +// generates a wireframe model of the map for the automap view -rww +static void R_GenerateWireframeMap(mnode_t *baseNode) { int i; - //initialize data to all 0 + // initialize data to all 0 memset(&g_autoMapFrame, 0, sizeof(g_autoMapFrame)); - //take the hit for this frame, mark all of these things as visible - //so we know which are valid for automap generation, but only the - //ones that are facing outside the world! (well, ideally.) - for (i = 0; i < tr.world->numnodes; i++) - { - if (tr.world->nodes[i].contents != CONTENTS_SOLID) - { -#if 0 //doesn't work, I take it surfs on nodes are not related to surfs on brushes + // take the hit for this frame, mark all of these things as visible + // so we know which are valid for automap generation, but only the + // ones that are facing outside the world! (well, ideally.) + for (i = 0; i < tr.world->numnodes; i++) { + if (tr.world->nodes[i].contents != CONTENTS_SOLID) { +#if 0 // doesn't work, I take it surfs on nodes are not related to surfs on brushes if (!R_NodeHasOppositeFaces(&tr.world->nodes[i])) #endif - { - tr.world->nodes[i].visframe = tr.visCount; - } + { tr.world->nodes[i].visframe = tr.visCount; } } } - //now start the recursive evaluation + // now start the recursive evaluation R_RecursiveWireframeSurf(baseNode); } -//clear out the wireframe map data -rww -void R_DestroyWireframeMap(void) -{ +// clear out the wireframe map data -rww +void R_DestroyWireframeMap(void) { wireframeMapSurf_t *next; wireframeMapSurf_t *last; - if (!g_autoMapValid) - { //not valid to begin with + if (!g_autoMapValid) { // not valid to begin with return; } next = g_autoMapFrame.surfs; - while (next) - { - //free memory allocated for points on this surface + while (next) { + // free memory allocated for points on this surface Z_Free(next->points); - //get the next surface + // get the next surface last = next; next = next->next; - //free memory for this surface + // free memory for this surface Z_Free(last); } - //invalidate everything + // invalidate everything memset(&g_autoMapFrame, 0, sizeof(g_autoMapFrame)); g_autoMapValid = false; g_autoMapNextFree = NULL; } -//save 3d automap data to file -rww -qboolean R_WriteWireframeMapToFile(void) -{ +// save 3d automap data to file -rww +qboolean R_WriteWireframeMapToFile(void) { fileHandle_t f; int requiredSize = 0; wireframeMapSurf_t *surf = g_autoMapFrame.surfs; byte *out, *rOut; - //let's go through and see how much space we're going to need to stuff all this - //data into - while (surf) - { - //memory for each point - requiredSize += sizeof(wireframeSurfPoint_t)*surf->numPoints; + // let's go through and see how much space we're going to need to stuff all this + // data into + while (surf) { + // memory for each point + requiredSize += sizeof(wireframeSurfPoint_t) * surf->numPoints; - //memory for numPoints + // memory for numPoints requiredSize += sizeof(int); surf = surf->next; } - if (requiredSize <= 0) - { //nothing to do..? + if (requiredSize <= 0) { // nothing to do..? return qfalse; } - f = ri.FS_FOpenFileWrite("blahblah.bla", qtrue); - if (!f) - { //can't create? + if (!f) { // can't create? return qfalse; } - //allocate the memory we will need - out = (byte *)Z_Malloc(requiredSize, TAG_ALL, qtrue); + // allocate the memory we will need + out = (byte *)Z_Malloc(requiredSize, TAG_ALL, qtrue); rOut = out; - //now go through and put the data into the memory + // now go through and put the data into the memory surf = g_autoMapFrame.surfs; - while (surf) - { - memcpy(out, surf, (sizeof(wireframeSurfPoint_t)*surf->numPoints) + sizeof(int)); + while (surf) { + memcpy(out, surf, (sizeof(wireframeSurfPoint_t) * surf->numPoints) + sizeof(int)); - //memory for each point - out += sizeof(wireframeSurfPoint_t)*surf->numPoints; + // memory for each point + out += sizeof(wireframeSurfPoint_t) * surf->numPoints; - //memory for numPoints + // memory for numPoints out += sizeof(int); surf = surf->next; } - //now write the buffer, and close + // now write the buffer, and close ri.FS_Write(rOut, requiredSize, f); Z_Free(rOut); ri.FS_FCloseFile(f); @@ -1009,9 +902,8 @@ qboolean R_WriteWireframeMapToFile(void) return qtrue; } -//load 3d automap data from file -rww -qboolean R_GetWireframeMapFromFile(void) -{ +// load 3d automap data from file -rww +qboolean R_GetWireframeMapFromFile(void) { wireframeMapSurf_t *surfs, *rSurfs; wireframeMapSurf_t *newSurf; fileHandle_t f; @@ -1020,8 +912,7 @@ qboolean R_GetWireframeMapFromFile(void) int stepBytes; len = ri.FS_FOpenFileRead("blahblah.bla", &f, qfalse); - if (!f || len <= 0) - { //it doesn't exist + if (!f || len <= 0) { // it doesn't exist return qfalse; } @@ -1029,26 +920,25 @@ qboolean R_GetWireframeMapFromFile(void) rSurfs = surfs; ri.FS_Read(surfs, len, f); - while (i < len) - { + while (i < len) { newSurf = R_GetNewWireframeMapSurf(); - newSurf->points = (wireframeSurfPoint_t *)Z_Malloc(sizeof(wireframeSurfPoint_t)*surfs->numPoints, TAG_ALL, qtrue); + newSurf->points = (wireframeSurfPoint_t *)Z_Malloc(sizeof(wireframeSurfPoint_t) * surfs->numPoints, TAG_ALL, qtrue); - //copy the surf data into the new surf - //note - the surfs->points pointer is NOT pointing to valid memory, a pointer to that - //pointer is actually what we want to use as the location of the point offsets. - memcpy(newSurf->points, &surfs->points, sizeof(wireframeSurfPoint_t)*surfs->numPoints); + // copy the surf data into the new surf + // note - the surfs->points pointer is NOT pointing to valid memory, a pointer to that + // pointer is actually what we want to use as the location of the point offsets. + memcpy(newSurf->points, &surfs->points, sizeof(wireframeSurfPoint_t) * surfs->numPoints); newSurf->numPoints = surfs->numPoints; - //the size of the point data, plus an int (the number of points) - stepBytes = (sizeof(wireframeSurfPoint_t)*surfs->numPoints) + sizeof(int); + // the size of the point data, plus an int (the number of points) + stepBytes = (sizeof(wireframeSurfPoint_t) * surfs->numPoints) + sizeof(int); i += stepBytes; - //increment the pointer to the start of the next surface - surfs = (wireframeMapSurf_t *)((byte *)surfs+stepBytes); + // increment the pointer to the start of the next surface + surfs = (wireframeMapSurf_t *)((byte *)surfs + stepBytes); } - //it should end up being equal, if not something was wrong with this file. + // it should end up being equal, if not something was wrong with this file. assert(i == len); ri.FS_FCloseFile(f); @@ -1056,19 +946,15 @@ qboolean R_GetWireframeMapFromFile(void) return qtrue; } -//create everything, after destroying any existing data -rww -qboolean R_InitializeWireframeAutomap(void) -{ - if (r_autoMapDisable && r_autoMapDisable->integer) - { +// create everything, after destroying any existing data -rww +qboolean R_InitializeWireframeAutomap(void) { + if (r_autoMapDisable && r_autoMapDisable->integer) { return qfalse; } - if (tr.world && - tr.world->nodes) - { + if (tr.world && tr.world->nodes) { R_DestroyWireframeMap(); -#if 0 //file load-save +#if 0 // file load-save if (!R_GetWireframeMapFromFile()) { //first try loading the data from a file. If there is none, generate it. R_GenerateWireframeMap(tr.world->nodes); @@ -1076,7 +962,7 @@ qboolean R_InitializeWireframeAutomap(void) //now write it to file, since we have generated it successfully. R_WriteWireframeMapToFile(); } -#else //always generate +#else // always generate R_GenerateWireframeMap(tr.world->nodes); #endif g_autoMapValid = true; @@ -1084,33 +970,28 @@ qboolean R_InitializeWireframeAutomap(void) return (qboolean)g_autoMapValid; } -#endif //0 +#endif // 0 /* ============================================================= WIREFRAME AUTOMAP GENERATION SYSTEM - END ============================================================= */ -void R_AutomapElevationAdjustment(float newHeight) -{ - g_playerHeight = newHeight; -} +void R_AutomapElevationAdjustment(float newHeight) { g_playerHeight = newHeight; } #ifdef _ALT_AUTOMAP_METHOD -//adjust the player height for gradient elevation colors -rww -qboolean R_InitializeWireframeAutomap(void) -{ //yoink +// adjust the player height for gradient elevation colors -rww +qboolean R_InitializeWireframeAutomap(void) { // yoink return qtrue; } #endif -//draw the automap with the given transformation matrix -rww -#define QUADINFINITY 16777216 +// draw the automap with the given transformation matrix -rww +#define QUADINFINITY 16777216 static float g_lastHeight = 0.0f; static bool g_lastHeightValid = false; -static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ); -const void *R_DrawWireframeAutomap(const void *data) -{ +static void R_RecursiveWorldNode(mnode_t *node, int planeBits, int dlightBits); +const void *R_DrawWireframeAutomap(const void *data) { const drawBufferCommand_t *cmd = (const drawBufferCommand_t *)data; float e = 0.0f; float alpha; @@ -1119,19 +1000,17 @@ const void *R_DrawWireframeAutomap(const void *data) int i; #endif - if (!r_autoMap || !r_autoMap->integer) - { + if (!r_autoMap || !r_autoMap->integer) { return (const void *)(cmd + 1); } #ifndef _ALT_AUTOMAP_METHOD - if (!g_autoMapValid) - { //data is not valid, don't draw + if (!g_autoMapValid) { // data is not valid, don't draw return (const void *)(cmd + 1); } #endif -#if 0 //instead of this method, just do the automap as a new "scene" +#if 0 // instead of this method, just do the automap as a new "scene" //projection matrix mode qglMatrixMode(GL_PROJECTION); @@ -1147,11 +1026,11 @@ const void *R_DrawWireframeAutomap(const void *data) qglRotatef(angles[2], 1.0f, 0.0f, 0.0f); #endif - //disable 2d texturing - qglDisable( GL_TEXTURE_2D ); + // disable 2d texturing + qglDisable(GL_TEXTURE_2D); - //now draw the backdrop -#if 0 //this does no good sadly, because of the issue of having to clear with a second scene + // now draw the backdrop +#if 0 // this does no good sadly, because of the issue of having to clear with a second scene //in order for global fog clearing to work. if (r_autoMapBackAlpha && r_autoMapBackAlpha->value) { //specify the automap background alpha @@ -1174,107 +1053,82 @@ const void *R_DrawWireframeAutomap(const void *data) alpha = 1.0f; GL_State(0); } - //black + // black qglColor4f(0.0f, 0.0f, 0.0f, alpha); - //draw a black backdrop + // draw a black backdrop qglPushMatrix(); - qglLoadIdentity(); //get the ident matrix + qglLoadIdentity(); // get the ident matrix - qglBegin( GL_QUADS ); - qglVertex3f( -QUADINFINITY, QUADINFINITY, -(backEnd.viewParms.zFar-1) ); - qglVertex3f( QUADINFINITY, QUADINFINITY, -(backEnd.viewParms.zFar-1) ); - qglVertex3f( QUADINFINITY, -QUADINFINITY, -(backEnd.viewParms.zFar-1) ); - qglVertex3f( -QUADINFINITY, -QUADINFINITY, -(backEnd.viewParms.zFar-1) ); - qglEnd (); + qglBegin(GL_QUADS); + qglVertex3f(-QUADINFINITY, QUADINFINITY, -(backEnd.viewParms.zFar - 1)); + qglVertex3f(QUADINFINITY, QUADINFINITY, -(backEnd.viewParms.zFar - 1)); + qglVertex3f(QUADINFINITY, -QUADINFINITY, -(backEnd.viewParms.zFar - 1)); + qglVertex3f(-QUADINFINITY, -QUADINFINITY, -(backEnd.viewParms.zFar - 1)); + qglEnd(); - //pop back the viewmatrix + // pop back the viewmatrix qglPopMatrix(); - - //set the mode to line draw - if (r_autoMap->integer == 2) - { //line mode - GL_State(GLS_POLYMODE_LINE|GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_COLOR|GLS_DEPTHMASK_TRUE); - } - else - { //fill mode - //GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_COLOR|GLS_DEPTHMASK_TRUE); + // set the mode to line draw + if (r_autoMap->integer == 2) { // line mode + GL_State(GLS_POLYMODE_LINE | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_SRC_COLOR | GLS_DEPTHMASK_TRUE); + } else { // fill mode + // GL_State(GLS_SRCBLEND_SRC_ALPHA|GLS_DSTBLEND_SRC_COLOR|GLS_DEPTHMASK_TRUE); GL_State(GLS_DEPTHMASK_TRUE); } - //set culling + // set culling GL_Cull(CT_TWO_SIDED); #ifndef _ALT_AUTOMAP_METHOD - //Draw the triangles - while (s) - { - //first, loop through and set the alpha on every point for this surf. - //if the alpha ends up being completely transparent for every point, we don't even - //need to draw it - if (g_playerHeight != g_lastHeight || - !g_lastHeightValid) - { //only do this if we need to + // Draw the triangles + while (s) { + // first, loop through and set the alpha on every point for this surf. + // if the alpha ends up being completely transparent for every point, we don't even + // need to draw it + if (g_playerHeight != g_lastHeight || !g_lastHeightValid) { // only do this if we need to i = 0; s->completelyTransparent = true; - while (i < s->numPoints) - { - //base the color on the elevation... for now, just check the first point height - if (s->points[i].xyz[2] < g_playerHeight) - { - e = s->points[i].xyz[2]-g_playerHeight; + while (i < s->numPoints) { + // base the color on the elevation... for now, just check the first point height + if (s->points[i].xyz[2] < g_playerHeight) { + e = s->points[i].xyz[2] - g_playerHeight; + } else { + e = g_playerHeight - s->points[i].xyz[2]; } - else - { - e = g_playerHeight-s->points[i].xyz[2]; - } - if (e < 0.0f) - { + if (e < 0.0f) { e = -e; } - if (r_autoMap->integer != 2) - { //fill mode - if (s->points[i].xyz[2] > (g_playerHeight+64.0f)) - { + if (r_autoMap->integer != 2) { // fill mode + if (s->points[i].xyz[2] > (g_playerHeight + 64.0f)) { s->points[i].alpha = 1.0f; + } else { + s->points[i].alpha = e / 256.0f; } - else - { - s->points[i].alpha = e/256.0f; - } - } - else - { - //set alpha and color based on relative height of point - s->points[i].alpha = e/256.0f; + } else { + // set alpha and color based on relative height of point + s->points[i].alpha = e / 256.0f; } e /= 512.0f; - //cap color - if (e > 1.0f) - { + // cap color + if (e > 1.0f) { e = 1.0f; - } - else if (e < 0.0f) - { + } else if (e < 0.0f) { e = 0.0f; } - VectorSet(s->points[i].color, e, 1.0f-e, 0.0f); + VectorSet(s->points[i].color, e, 1.0f - e, 0.0f); - //cap alpha - if (s->points[i].alpha > 1.0f) - { + // cap alpha + if (s->points[i].alpha > 1.0f) { s->points[i].alpha = 1.0f; - } - else if (s->points[i].alpha < 0.0f) - { + } else if (s->points[i].alpha < 0.0f) { s->points[i].alpha = 0.0f; } - if (s->points[i].alpha != 1.0f) - { //this point is not entirely alpha'd out, so still draw the surface + if (s->points[i].alpha != 1.0f) { // this point is not entirely alpha'd out, so still draw the surface s->completelyTransparent = false; } @@ -1282,31 +1136,35 @@ const void *R_DrawWireframeAutomap(const void *data) } } - if (s->completelyTransparent) - { + if (s->completelyTransparent) { s = s->next; continue; } i = 0; qglBegin(GL_TRIANGLES); - while (i < s->numPoints) - { - if (r_autoMap->integer == 2 || s->numPoints < 3) - { //line mode or not enough verts on surface + while (i < s->numPoints) { + if (r_autoMap->integer == 2 || s->numPoints < 3) { // line mode or not enough verts on surface qglColor4f(s->points[i].color[0], s->points[i].color[1], s->points[i].color[2], s->points[i].alpha); - } - else - { //fill mode + } else { // fill mode vec3_t planeNormal; float fAlpha = s->points[i].alpha; - planeNormal[0] = s->points[0].xyz[1]*(s->points[1].xyz[2]-s->points[2].xyz[2]) + s->points[1].xyz[1]*(s->points[2].xyz[2]-s->points[0].xyz[2]) + s->points[2].xyz[1]*(s->points[0].xyz[2]-s->points[1].xyz[2]); - planeNormal[1] = s->points[0].xyz[2]*(s->points[1].xyz[0]-s->points[2].xyz[0]) + s->points[1].xyz[2]*(s->points[2].xyz[0]-s->points[0].xyz[0]) + s->points[2].xyz[2]*(s->points[0].xyz[0]-s->points[1].xyz[0]); - planeNormal[2] = s->points[0].xyz[0]*(s->points[1].xyz[1]-s->points[2].xyz[1]) + s->points[1].xyz[0]*(s->points[2].xyz[1]-s->points[0].xyz[1]) + s->points[2].xyz[0]*(s->points[0].xyz[1]-s->points[1].xyz[1]); - - if (planeNormal[0] < 0.0f) planeNormal[0] = -planeNormal[0]; - if (planeNormal[1] < 0.0f) planeNormal[1] = -planeNormal[1]; - if (planeNormal[2] < 0.0f) planeNormal[2] = -planeNormal[2]; + planeNormal[0] = s->points[0].xyz[1] * (s->points[1].xyz[2] - s->points[2].xyz[2]) + + s->points[1].xyz[1] * (s->points[2].xyz[2] - s->points[0].xyz[2]) + + s->points[2].xyz[1] * (s->points[0].xyz[2] - s->points[1].xyz[2]); + planeNormal[1] = s->points[0].xyz[2] * (s->points[1].xyz[0] - s->points[2].xyz[0]) + + s->points[1].xyz[2] * (s->points[2].xyz[0] - s->points[0].xyz[0]) + + s->points[2].xyz[2] * (s->points[0].xyz[0] - s->points[1].xyz[0]); + planeNormal[2] = s->points[0].xyz[0] * (s->points[1].xyz[1] - s->points[2].xyz[1]) + + s->points[1].xyz[0] * (s->points[2].xyz[1] - s->points[0].xyz[1]) + + s->points[2].xyz[0] * (s->points[0].xyz[1] - s->points[1].xyz[1]); + + if (planeNormal[0] < 0.0f) + planeNormal[0] = -planeNormal[0]; + if (planeNormal[1] < 0.0f) + planeNormal[1] = -planeNormal[1]; + if (planeNormal[2] < 0.0f) + planeNormal[2] = -planeNormal[2]; /* if (s->points[i].xyz[2] > g_playerHeight+64.0f && @@ -1316,8 +1174,8 @@ const void *R_DrawWireframeAutomap(const void *data) } */ - //qglColor4f(planeNormal[0], planeNormal[1], planeNormal[2], fAlpha); - qglColor4f(s->points[i].color[0], s->points[i].color[1], 1.0f-planeNormal[2], fAlpha); + // qglColor4f(planeNormal[0], planeNormal[1], planeNormal[2], fAlpha); + qglColor4f(s->points[i].color[0], s->points[i].color[1], 1.0f - planeNormal[2], fAlpha); } qglVertex3f(s->points[i].xyz[0], s->points[i].xyz[1], s->points[i].xyz[2]); i++; @@ -1327,49 +1185,45 @@ const void *R_DrawWireframeAutomap(const void *data) } #else tr_drawingAutoMap = true; - R_RecursiveWorldNode( tr.world->nodes, 15, 0 ); + R_RecursiveWorldNode(tr.world->nodes, 15, 0); tr_drawingAutoMap = false; #endif g_lastHeight = g_playerHeight; g_lastHeightValid = true; -#if 0 //instead of this method, just do the automap as a new "scene" +#if 0 // instead of this method, just do the automap as a new "scene" //pop back the view matrix qglPopMatrix(); #endif - //reenable 2d texturing - qglEnable( GL_TEXTURE_2D ); + // reenable 2d texturing + qglEnable(GL_TEXTURE_2D); - //white color/full alpha + // white color/full alpha qglColor4f(1.0f, 1.0f, 1.0f, 1.0f); return (const void *)(cmd + 1); } - /* ================ R_RecursiveWorldNode ================ */ -static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) { +static void R_RecursiveWorldNode(mnode_t *node, int planeBits, int dlightBits) { - do - { - int newDlights[2]; + do { + int newDlights[2]; #ifdef _ALT_AUTOMAP_METHOD - if (tr_drawingAutoMap) - { + if (tr_drawingAutoMap) { node->visframe = tr.visCount; } #endif // if the node wasn't marked as potentially visible, exit - if (node->visframe != tr.visCount) - { + if (node->visframe != tr.visCount) { return; } @@ -1377,56 +1231,55 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) // inside can be visible OPTIMIZE: don't do this all the way to leafs? #ifdef _ALT_AUTOMAP_METHOD - if ( r_nocull->integer!=1 && !tr_drawingAutoMap ) + if (r_nocull->integer != 1 && !tr_drawingAutoMap) #else - if (r_nocull->integer!=1) + if (r_nocull->integer != 1) #endif { - int r; + int r; - if ( planeBits & 1 ) { + if (planeBits & 1) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[0]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~1; // all descendants will also be in front + if (r == 1) { + planeBits &= ~1; // all descendants will also be in front } } - if ( planeBits & 2 ) { + if (planeBits & 2) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[1]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~2; // all descendants will also be in front + if (r == 1) { + planeBits &= ~2; // all descendants will also be in front } } - if ( planeBits & 4 ) { + if (planeBits & 4) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[2]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~4; // all descendants will also be in front + if (r == 1) { + planeBits &= ~4; // all descendants will also be in front } } - if ( planeBits & 8 ) { + if (planeBits & 8) { r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[3]); if (r == 2) { - return; // culled + return; // culled } - if ( r == 1 ) { - planeBits &= ~8; // all descendants will also be in front + if (r == 1) { + planeBits &= ~8; // all descendants will also be in front } } - } - if ( node->contents != -1 ) { + if (node->contents != -1) { break; } @@ -1434,71 +1287,66 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) // since we don't care about sort orders, just go positive to negative // determine which dlights are needed - if ( r_nocull->integer!=2 ) - { + if (r_nocull->integer != 2) { newDlights[0] = 0; newDlights[1] = 0; - if ( dlightBits ) - { - int i; - for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) - { - dlight_t *dl; - float dist; + if (dlightBits) { + int i; + for (i = 0; i < tr.refdef.num_dlights; i++) { + dlight_t *dl; + float dist; - if ( dlightBits & ( 1 << i ) ) { + if (dlightBits & (1 << i)) { dl = &tr.refdef.dlights[i]; - dist = DotProduct( dl->origin, node->plane->normal ) - node->plane->dist; + dist = DotProduct(dl->origin, node->plane->normal) - node->plane->dist; - if ( dist > -dl->radius ) { - newDlights[0] |= ( 1 << i ); + if (dist > -dl->radius) { + newDlights[0] |= (1 << i); } - if ( dist < dl->radius ) { - newDlights[1] |= ( 1 << i ); + if (dist < dl->radius) { + newDlights[1] |= (1 << i); } } } } - } - else - { + } else { newDlights[0] = dlightBits; newDlights[1] = dlightBits; } // recurse down the children, front side first - R_RecursiveWorldNode (node->children[0], planeBits, newDlights[0] ); + R_RecursiveWorldNode(node->children[0], planeBits, newDlights[0]); // tail recurse node = node->children[1]; dlightBits = newDlights[1]; - } while ( 1 ); + } while (1); { // leaf node, so add mark surfaces - int c; - msurface_t *surf, **mark; + int c; + msurface_t *surf, **mark; tr.pc.c_leafs++; // add to z buffer bounds - if ( node->mins[0] < tr.viewParms.visBounds[0][0] ) { + if (node->mins[0] < tr.viewParms.visBounds[0][0]) { tr.viewParms.visBounds[0][0] = node->mins[0]; } - if ( node->mins[1] < tr.viewParms.visBounds[0][1] ) { + if (node->mins[1] < tr.viewParms.visBounds[0][1]) { tr.viewParms.visBounds[0][1] = node->mins[1]; } - if ( node->mins[2] < tr.viewParms.visBounds[0][2] ) { + if (node->mins[2] < tr.viewParms.visBounds[0][2]) { tr.viewParms.visBounds[0][2] = node->mins[2]; } - if ( node->maxs[0] > tr.viewParms.visBounds[1][0] ) { + if (node->maxs[0] > tr.viewParms.visBounds[1][0]) { tr.viewParms.visBounds[1][0] = node->maxs[0]; } - if ( node->maxs[1] > tr.viewParms.visBounds[1][1] ) { + if (node->maxs[1] > tr.viewParms.visBounds[1][1]) { tr.viewParms.visBounds[1][1] = node->maxs[1]; } - if ( node->maxs[2] > tr.viewParms.visBounds[1][2] ) { + if (node->maxs[2] > tr.viewParms.visBounds[1][2]) { tr.viewParms.visBounds[1][2] = node->maxs[2]; } @@ -1509,11 +1357,10 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) // the surface may have already been added if it // spans multiple leafs surf = *mark; - R_AddWorldSurface( surf, dlightBits ); + R_AddWorldSurface(surf, dlightBits); mark++; } } - } /* @@ -1521,22 +1368,22 @@ static void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits ) R_PointInLeaf =============== */ -static mnode_t *R_PointInLeaf( const vec3_t p ) { - mnode_t *node; - float d; - cplane_t *plane; +static mnode_t *R_PointInLeaf(const vec3_t p) { + mnode_t *node; + float d; + cplane_t *plane; - if ( !tr.world ) { - Com_Error (ERR_DROP, "R_PointInLeaf: bad model"); + if (!tr.world) { + Com_Error(ERR_DROP, "R_PointInLeaf: bad model"); } node = tr.world->nodes; - while( 1 ) { + while (1) { if (node->contents != -1) { break; } plane = node->plane; - d = DotProduct (p,plane->normal) - plane->dist; + d = DotProduct(p, plane->normal) - plane->dist; if (d > 0) { node = node->children[0]; } else { @@ -1552,8 +1399,8 @@ static mnode_t *R_PointInLeaf( const vec3_t p ) { R_ClusterPVS ============== */ -static const byte *R_ClusterPVS (int cluster) { - if (!tr.world || !tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters ) { +static const byte *R_ClusterPVS(int cluster) { + if (!tr.world || !tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters) { return tr.world->novis; } @@ -1565,19 +1412,19 @@ static const byte *R_ClusterPVS (int cluster) { R_inPVS ================= */ -qboolean R_inPVS( const vec3_t p1, const vec3_t p2, byte *mask ) { - int leafnum; - int cluster; +qboolean R_inPVS(const vec3_t p1, const vec3_t p2, byte *mask) { + int leafnum; + int cluster; - leafnum = ri.CM_PointLeafnum (p1); - cluster = ri.CM_LeafCluster (leafnum); + leafnum = ri.CM_PointLeafnum(p1); + cluster = ri.CM_LeafCluster(leafnum); - //agh, the damn snapshot mask doesn't work for this - mask = (byte *) ri.CM_ClusterPVS (cluster); + // agh, the damn snapshot mask doesn't work for this + mask = (byte *)ri.CM_ClusterPVS(cluster); - leafnum = ri.CM_PointLeafnum (p2); - cluster = ri.CM_LeafCluster (leafnum); - if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) ) + leafnum = ri.CM_PointLeafnum(p2); + cluster = ri.CM_LeafCluster(leafnum); + if (mask && (!(mask[cluster >> 3] & (1 << (cluster & 7))))) return qfalse; return qtrue; @@ -1591,43 +1438,42 @@ Mark the leaves and nodes that are in the PVS for the current cluster =============== */ -static void R_MarkLeaves (void) { - const byte *vis; - mnode_t *leaf, *parent; - int i; - int cluster; +static void R_MarkLeaves(void) { + const byte *vis; + mnode_t *leaf, *parent; + int i; + int cluster; // lockpvs lets designers walk around to determine the // extent of the current pvs - if ( r_lockpvs->integer ) { + if (r_lockpvs->integer) { return; } // current viewcluster - leaf = R_PointInLeaf( tr.viewParms.pvsOrigin ); + leaf = R_PointInLeaf(tr.viewParms.pvsOrigin); cluster = leaf->cluster; // if the cluster is the same and the area visibility matrix // hasn't changed, we don't need to mark everything again // if r_showcluster was just turned on, remark everything - if ( tr.viewCluster == cluster && !tr.refdef.areamaskModified - && !r_showcluster->modified ) { + if (tr.viewCluster == cluster && !tr.refdef.areamaskModified && !r_showcluster->modified) { return; } - if ( r_showcluster->modified || r_showcluster->integer ) { + if (r_showcluster->modified || r_showcluster->integer) { r_showcluster->modified = qfalse; - if ( r_showcluster->integer ) { - ri.Printf( PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area ); + if (r_showcluster->integer) { + ri.Printf(PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area); } } tr.visCount++; tr.viewCluster = cluster; - if ( r_novis->integer || tr.viewCluster == -1 ) { - for (i=0 ; inumnodes ; i++) { + if (r_novis->integer || tr.viewCluster == -1) { + for (i = 0; i < tr.world->numnodes; i++) { if (tr.world->nodes[i].contents != CONTENTS_SOLID) { tr.world->nodes[i].visframe = tr.visCount; } @@ -1635,22 +1481,22 @@ static void R_MarkLeaves (void) { return; } - vis = R_ClusterPVS (tr.viewCluster); + vis = R_ClusterPVS(tr.viewCluster); - for (i=0,leaf=tr.world->nodes ; inumnodes ; i++, leaf++) { + for (i = 0, leaf = tr.world->nodes; i < tr.world->numnodes; i++, leaf++) { cluster = leaf->cluster; - if ( cluster < 0 || cluster >= tr.world->numClusters ) { + if (cluster < 0 || cluster >= tr.world->numClusters) { continue; } // check general pvs - if ( !(vis[cluster>>3] & (1<<(cluster&7))) ) { + if (!(vis[cluster >> 3] & (1 << (cluster & 7)))) { continue; } // check for door connection - if ( (tr.refdef.areamask[leaf->area>>3] & (1<<(leaf->area&7)) ) ) { - continue; // not visible + if ((tr.refdef.areamask[leaf->area >> 3] & (1 << (leaf->area & 7)))) { + continue; // not visible } parent = leaf; @@ -1668,12 +1514,12 @@ static void R_MarkLeaves (void) { R_AddWorldSurfaces ============= */ -void R_AddWorldSurfaces (void) { - if ( !r_drawworld->integer ) { +void R_AddWorldSurfaces(void) { + if (!r_drawworld->integer) { return; } - if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + if (tr.refdef.rdflags & RDF_NOWORLDMODEL) { return; } @@ -1681,15 +1527,15 @@ void R_AddWorldSurfaces (void) { tr.shiftedEntityNum = tr.currentEntityNum << QSORT_REFENTITYNUM_SHIFT; // determine which leaves are in the PVS / areamask - R_MarkLeaves (); + R_MarkLeaves(); // clear out the visible min/max - ClearBounds( tr.viewParms.visBounds[0], tr.viewParms.visBounds[1] ); + ClearBounds(tr.viewParms.visBounds[0], tr.viewParms.visBounds[1]); // perform frustum culling and add all the potentially visible surfaces - if ( tr.refdef.num_dlights > 32 ) { - tr.refdef.num_dlights = 32 ; + if (tr.refdef.num_dlights > 32) { + tr.refdef.num_dlights = 32; } - R_RecursiveWorldNode( tr.world->nodes, 15, ( 1 << tr.refdef.num_dlights ) - 1 ); + R_RecursiveWorldNode(tr.world->nodes, 15, (1 << tr.refdef.num_dlights) - 1); } diff --git a/codemp/server/NPCNav/navigator.cpp b/codemp/server/NPCNav/navigator.cpp index 3331687cd3..c7d6da937f 100644 --- a/codemp/server/NPCNav/navigator.cpp +++ b/codemp/server/NPCNav/navigator.cpp @@ -33,40 +33,33 @@ unsigned int timeGetTime(void); #include "../sv_gameapi.h" -//Global navigator -CNavigator navigator; -//this was in the game before. But now it's all handled in the engine, and we make navigator. calls -//via traps. +// Global navigator +CNavigator navigator; +// this was in the game before. But now it's all handled in the engine, and we make navigator. calls +// via traps. -cvar_t *d_altRoutes; -cvar_t *d_patched; +cvar_t *d_altRoutes; +cvar_t *d_patched; -void NAV_CvarInit() -{ +void NAV_CvarInit() { d_altRoutes = Cvar_Get("d_altRoutes", "0", CVAR_CHEAT); d_patched = Cvar_Get("d_patched", "0", CVAR_CHEAT); } -void NAV_Free() -{ - navigator.Free(); -} - -static vec3_t wpMaxs = { 16, 16, 32 }; -static vec3_t wpMins = { -16, -16, -24+STEPSIZE };//WTF: was 16??!!! +void NAV_Free() { navigator.Free(); } +static vec3_t wpMaxs = {16, 16, 32}; +static vec3_t wpMins = {-16, -16, -24 + STEPSIZE}; // WTF: was 16??!!! static byte CHECKED_NO = 0; static byte CHECKED_FAILED = 1; static byte CHECKED_PASSED = 2; - -#if AI_TIMERS -int GetTime ( int lastTime ) -{ - int curtime; - static int timeBase = 0; - static qboolean initialized = qfalse; +#if AI_TIMERS +int GetTime(int lastTime) { + int curtime; + static int timeBase = 0; + static qboolean initialized = qfalse; if (!initialized) { timeBase = timeGetTime(); @@ -84,16 +77,13 @@ CEdge ------------------------- */ -CEdge::CEdge( int first, int second, int cost ) -{ - m_first = first; - m_second = second; - m_cost = cost; +CEdge::CEdge(int first, int second, int cost) { + m_first = first; + m_second = second; + m_cost = cost; } -CEdge::~CEdge( void ) -{ -} +CEdge::~CEdge(void) {} /* ------------------------- @@ -101,19 +91,17 @@ CNode ------------------------- */ -CNode::CNode( void ) -{ - m_numEdges = 0; - m_radius = 0; - m_ranks = NULL; +CNode::CNode(void) { + m_numEdges = 0; + m_radius = 0; + m_ranks = NULL; } -CNode::~CNode( void ) -{ +CNode::~CNode(void) { m_edges.clear(); - if ( m_ranks ) - delete [] m_ranks; + if (m_ranks) + delete[] m_ranks; } /* @@ -122,11 +110,10 @@ Create ------------------------- */ -CNode *CNode::Create( vec3_t position, int flags, int radius, int ID ) -{ - CNode *node = new CNode; +CNode *CNode::Create(vec3_t position, int flags, int radius, int ID) { + CNode *node = new CNode; - VectorCopy( position, node->m_position ); + VectorCopy(position, node->m_position); node->m_flags = flags; node->m_ID = ID; @@ -141,10 +128,7 @@ Create ------------------------- */ -CNode *CNode::Create( void ) -{ - return new CNode; -} +CNode *CNode::Create(void) { return new CNode; } /* ------------------------- @@ -152,34 +136,30 @@ AddEdge ------------------------- */ -void CNode::AddEdge( int ID, int cost, int flags ) -{ - if ( m_numEdges ) - {//already have at least 1 - //see if it exists already - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( (*ei).ID == ID ) - {//found it - (*ei).cost = cost; - (*ei).flags = flags; +void CNode::AddEdge(int ID, int cost, int flags) { + if (m_numEdges) { // already have at least 1 + // see if it exists already + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if ((*ei).ID == ID) { // found it + (*ei).cost = cost; + (*ei).flags = flags; return; } } } - edge_t edge; + edge_t edge; - edge.ID = ID; - edge.cost = cost; - edge.flags = flags; + edge.ID = ID; + edge.cost = cost; + edge.flags = flags; - STL_INSERT( m_edges, edge ); + STL_INSERT(m_edges, edge); m_numEdges++; - assert( m_numEdges < 9 );//8 is the max + assert(m_numEdges < 9); // 8 is the max } /* @@ -188,15 +168,12 @@ GetEdge ------------------------- */ -int CNode::GetEdgeNumToNode( int ID ) -{ +int CNode::GetEdgeNumToNode(int ID) { int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( (*ei).ID == ID ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if ((*ei).ID == ID) { return count; } @@ -211,11 +188,10 @@ AddRank ------------------------- */ -void CNode::AddRank( int ID, int rank ) -{ - assert( m_ranks ); +void CNode::AddRank(int ID, int rank) { + assert(m_ranks); - m_ranks[ ID ] = rank; + m_ranks[ID] = rank; } /* @@ -224,8 +200,7 @@ Draw ------------------------- */ -void CNode::Draw( qboolean showRadius ) -{ //rwwFIXMEFIXME: ... +void CNode::Draw(qboolean showRadius) { // rwwFIXMEFIXME: ... /* CG_DrawNode( m_position, NODE_NORMAL ); if( showRadius ) @@ -241,18 +216,15 @@ GetEdge ------------------------- */ -int CNode::GetEdge( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +int CNode::GetEdge(int edgeNum) { + if (edgeNum > m_numEdges) return -1; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).ID; } @@ -268,18 +240,15 @@ GetEdgeCost ------------------------- */ -int CNode::GetEdgeCost( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +int CNode::GetEdgeCost(int edgeNum) { + if (edgeNum > m_numEdges) return Q3_INFINITE; // return -1; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).cost; } @@ -295,18 +264,15 @@ GetEdgeFlags ------------------------- */ -byte CNode::GetEdgeFlags( int edgeNum ) -{ - if ( edgeNum > m_numEdges ) +byte CNode::GetEdgeFlags(int edgeNum) { + if (edgeNum > m_numEdges) return 0; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { return (*ei).flags; } @@ -322,25 +288,21 @@ SetEdgeFlags ------------------------- */ -void CNode::SetEdgeFlags( int edgeNum, int newFlags ) -{ - if ( edgeNum > m_numEdges ) +void CNode::SetEdgeFlags(int edgeNum, int newFlags) { + if (edgeNum > m_numEdges) return; int count = 0; - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - if ( count == edgeNum ) - { + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { + if (count == edgeNum) { (*ei).flags = newFlags; return; } count++; } - } /* ------------------------- @@ -348,18 +310,16 @@ InitRanks ------------------------- */ -void CNode::InitRanks( int size ) -{ - //Clear it if it's already allocated - if ( m_ranks != NULL ) - { - delete [] m_ranks; +void CNode::InitRanks(int size) { + // Clear it if it's already allocated + if (m_ranks != NULL) { + delete[] m_ranks; m_ranks = NULL; } m_ranks = new int[size]; - memset( m_ranks, -1, sizeof(int)*size ); + memset(m_ranks, -1, sizeof(int) * size); } /* @@ -368,50 +328,43 @@ GetRank ------------------------- */ -int CNode::GetRank( int ID ) -{ - assert( m_ranks ); +int CNode::GetRank(int ID) { + assert(m_ranks); - return m_ranks[ ID ]; + return m_ranks[ID]; } - /* ------------------------- Save ------------------------- */ -int CNode::Save( int numNodes, fileHandle_t file ) -{ - //Write out the header +int CNode::Save(int numNodes, fileHandle_t file) { + // Write out the header unsigned int header = NODE_HEADER_ID; - FS_Write( &header, sizeof( header ), file ); + FS_Write(&header, sizeof(header), file); - //Write out the basic information + // Write out the basic information int i; - for ( i = 0; i < 3; i++ ) - FS_Write( &m_position[i], sizeof( float ), file ); + for (i = 0; i < 3; i++) + FS_Write(&m_position[i], sizeof(float), file); - FS_Write( &m_flags, sizeof( m_flags ), file ); - FS_Write( &m_ID, sizeof( m_ID ), file ); - FS_Write( &m_radius, sizeof( m_radius ), file ); + FS_Write(&m_flags, sizeof(m_flags), file); + FS_Write(&m_ID, sizeof(m_ID), file); + FS_Write(&m_radius, sizeof(m_radius), file); - //Write out the edge information - FS_Write( &m_numEdges, sizeof( m_numEdges ), file ); + // Write out the edge information + FS_Write(&m_numEdges, sizeof(m_numEdges), file); - edge_v::iterator ei; - STL_ITERATE( ei, m_edges ) - { - FS_Write( &(*ei), sizeof( edge_t ), file ); - } + edge_v::iterator ei; + STL_ITERATE(ei, m_edges) { FS_Write(&(*ei), sizeof(edge_t), file); } - //Write out the node ranks - FS_Write( &numNodes, sizeof( numNodes ), file ); + // Write out the node ranks + FS_Write(&numNodes, sizeof(numNodes), file); - for ( i = 0; i < numNodes; i++ ) - { - FS_Write( &m_ranks[i], sizeof( int ), file ); + for (i = 0; i < numNodes; i++) { + FS_Write(&m_ranks[i], sizeof(int), file); } return true; @@ -423,47 +376,44 @@ Load ------------------------- */ -int CNode::Load( int numNodes, fileHandle_t file ) -{ +int CNode::Load(int numNodes, fileHandle_t file) { unsigned int header; - FS_Read( &header, sizeof(header), file ); + FS_Read(&header, sizeof(header), file); - //Validate the header - if ( header != NODE_HEADER_ID ) + // Validate the header + if (header != NODE_HEADER_ID) return false; - //Get the basic information + // Get the basic information int i; - for ( i = 0; i < 3; i++ ) - FS_Read( &m_position[i], sizeof( float ), file ); + for (i = 0; i < 3; i++) + FS_Read(&m_position[i], sizeof(float), file); - FS_Read( &m_flags, sizeof( m_flags ), file ); - FS_Read( &m_ID, sizeof( m_ID ), file ); - FS_Read( &m_radius, sizeof( m_radius ), file ); + FS_Read(&m_flags, sizeof(m_flags), file); + FS_Read(&m_ID, sizeof(m_ID), file); + FS_Read(&m_radius, sizeof(m_radius), file); - //Get the edge information - FS_Read( &m_numEdges, sizeof( m_numEdges ), file ); + // Get the edge information + FS_Read(&m_numEdges, sizeof(m_numEdges), file); - for ( i = 0; i < m_numEdges; i++ ) - { - edge_t edge; + for (i = 0; i < m_numEdges; i++) { + edge_t edge; - FS_Read( &edge, sizeof( edge_t ), file ); + FS_Read(&edge, sizeof(edge_t), file); - STL_INSERT( m_edges, edge ); + STL_INSERT(m_edges, edge); } - //Read the node ranks - int numRanks; + // Read the node ranks + int numRanks; - FS_Read( &numRanks, sizeof( numRanks ), file ); + FS_Read(&numRanks, sizeof(numRanks), file); - //Allocate the memory - InitRanks( numRanks ); + // Allocate the memory + InitRanks(numRanks); - for ( i = 0; i < numRanks; i++ ) - { - FS_Read( &m_ranks[i], sizeof( int ), file ); + for (i = 0; i < numRanks; i++) { + FS_Read(&m_ranks[i], sizeof(int), file); } return true; @@ -475,8 +425,7 @@ CNavigator ------------------------- */ -CNavigator::CNavigator( void ) -{ +CNavigator::CNavigator(void) { #if 0 // RAVEN... why u make it so hard to double link list cvars if (!d_altRoutes || !d_patched) { @@ -485,9 +434,7 @@ CNavigator::CNavigator( void ) #endif } -CNavigator::~CNavigator( void ) -{ -} +CNavigator::~CNavigator(void) {} /* ------------------------- @@ -495,14 +442,10 @@ FlagAllNodes ------------------------- */ -void CNavigator::FlagAllNodes( int newFlag ) -{ - node_v::iterator ni; +void CNavigator::FlagAllNodes(int newFlag) { + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->AddFlag( newFlag ); - } + STL_ITERATE(ni, m_nodes) { (*ni)->AddFlag(newFlag); } } /* @@ -511,11 +454,10 @@ GetChar ------------------------- */ -char CNavigator::GetChar( fileHandle_t file ) -{ +char CNavigator::GetChar(fileHandle_t file) { char value; - FS_Read( &value, sizeof( value ), file ); + FS_Read(&value, sizeof(value), file); return value; } @@ -526,11 +468,10 @@ GetInt ------------------------- */ -int CNavigator::GetInt( fileHandle_t file ) -{ +int CNavigator::GetInt(fileHandle_t file) { int value; - FS_Read( &value, sizeof( value ), file ); + FS_Read(&value, sizeof(value), file); return value; } @@ -541,11 +482,10 @@ GetFloat ------------------------- */ -float CNavigator::GetFloat( fileHandle_t file ) -{ +float CNavigator::GetFloat(fileHandle_t file) { float value; - FS_Read( &value, sizeof( value ), file ); + FS_Read(&value, sizeof(value), file); return value; } @@ -556,11 +496,10 @@ GetLong ------------------------- */ -long CNavigator::GetLong( fileHandle_t file ) -{ +long CNavigator::GetLong(fileHandle_t file) { int value; - FS_Read( &value, sizeof( value ), file ); + FS_Read(&value, sizeof(value), file); return value; } @@ -571,10 +510,8 @@ Init ------------------------- */ -void CNavigator::Init( void ) -{ - if (!d_altRoutes || !d_patched) - { +void CNavigator::Init(void) { + if (!d_altRoutes || !d_patched) { NAV_CvarInit(); } @@ -587,14 +524,10 @@ Free ------------------------- */ -void CNavigator::Free( void ) -{ - node_v::iterator ni; +void CNavigator::Free(void) { + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - delete (*ni); - } + STL_ITERATE(ni, m_nodes) { delete (*ni); } m_nodes.clear(); m_edgeLookupMap.clear(); @@ -606,62 +539,55 @@ Load ------------------------- */ -bool CNavigator::Load( const char *filename, int checksum ) -{ - fileHandle_t file; +bool CNavigator::Load(const char *filename, int checksum) { + fileHandle_t file; // Free previous map just in case. jampgame doesn't do this by default... Free(); - //Attempt to load the file - FS_FOpenFileByMode( va( "maps/%s.nav", filename ), &file, FS_READ ); + // Attempt to load the file + FS_FOpenFileByMode(va("maps/%s.nav", filename), &file, FS_READ); - //See if we succeeded - if ( file == 0 ) + // See if we succeeded + if (file == 0) return false; - //Check the header id - int navID = GetLong( file ); + // Check the header id + int navID = GetLong(file); - if ( navID != NAV_HEADER_ID ) - { - FS_FCloseFile( file ); + if (navID != NAV_HEADER_ID) { + FS_FCloseFile(file); return false; } - //Check the checksum to see if this file is out of date - int check = GetInt( file ); + // Check the checksum to see if this file is out of date + int check = GetInt(file); - if ( check != checksum ) - { - FS_FCloseFile( file ); + if (check != checksum) { + FS_FCloseFile(file); return false; } - int numNodes = GetInt( file ); + int numNodes = GetInt(file); - for ( int i = 0; i < numNodes; i++ ) - { - CNode *node = CNode::Create(); + for (int i = 0; i < numNodes; i++) { + CNode *node = CNode::Create(); - if ( node->Load( numNodes, file ) == false ) - { - FS_FCloseFile( file ); + if (node->Load(numNodes, file) == false) { + FS_FCloseFile(file); return false; } - STL_INSERT( m_nodes, node ); + STL_INSERT(m_nodes, node); } - //read in the failed edges - FS_Read( &failedEdges, sizeof( failedEdges ), file ); - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { + // read in the failed edges + FS_Read(&failedEdges, sizeof(failedEdges), file); + for (int j = 0; j < MAX_FAILED_EDGES; j++) { m_edgeLookupMap.insert(std::pair(failedEdges[j].startID, j)); } - - FS_FCloseFile( file ); + FS_FCloseFile(file); return true; } @@ -672,41 +598,37 @@ Save ------------------------- */ -bool CNavigator::Save( const char *filename, int checksum ) -{ - fileHandle_t file; +bool CNavigator::Save(const char *filename, int checksum) { + fileHandle_t file; - //Attempt to load the file - FS_FOpenFileByMode( va( "maps/%s.nav", filename ), &file, FS_WRITE ); + // Attempt to load the file + FS_FOpenFileByMode(va("maps/%s.nav", filename), &file, FS_WRITE); - if ( file == 0 ) + if (file == 0) return false; - //Write out the header id + // Write out the header id unsigned int id = NAV_HEADER_ID; - FS_Write( &id, sizeof (id), file ); + FS_Write(&id, sizeof(id), file); - //Write out the checksum - FS_Write( &checksum, sizeof( checksum ), file ); + // Write out the checksum + FS_Write(&checksum, sizeof(checksum), file); - int numNodes = m_nodes.size(); + int numNodes = m_nodes.size(); - //Write out the number of nodes to follow - FS_Write( &numNodes, sizeof(numNodes), file ); + // Write out the number of nodes to follow + FS_Write(&numNodes, sizeof(numNodes), file); - //Write out all the nodes - node_v::iterator ni; + // Write out all the nodes + node_v::iterator ni; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->Save( numNodes, file ); - } + STL_ITERATE(ni, m_nodes) { (*ni)->Save(numNodes, file); } - //write out failed edges - FS_Write( &failedEdges, sizeof( failedEdges ), file ); + // write out failed edges + FS_Write(&failedEdges, sizeof(failedEdges), file); - FS_FCloseFile( file ); + FS_FCloseFile(file); return true; } @@ -717,20 +639,18 @@ AddRawPoint ------------------------- */ -int CNavigator::AddRawPoint( vec3_t point, int flags, int radius ) -{ - CNode *node = CNode::Create( point, flags, radius, m_nodes.size() ); +int CNavigator::AddRawPoint(vec3_t point, int flags, int radius) { + CNode *node = CNode::Create(point, flags, radius, m_nodes.size()); - if ( node == NULL ) - { - Com_Error( ERR_DROP, "Error adding node!\n" ); + if (node == NULL) { + Com_Error(ERR_DROP, "Error adding node!\n"); return -1; } - //TODO: Validate the position - //TODO: Correct stuck waypoints + // TODO: Validate the position + // TODO: Correct stuck waypoints - STL_INSERT( m_nodes, node ); + STL_INSERT(m_nodes, node); return node->GetID(); } @@ -741,52 +661,48 @@ GetEdgeCost ------------------------- */ -int CNavigator::GetEdgeCost( CNode *first, CNode *second ) -{ - trace_t trace; - vec3_t start, end; - vec3_t mins, maxs; +int CNavigator::GetEdgeCost(CNode *first, CNode *second) { + trace_t trace; + vec3_t start, end; + vec3_t mins, maxs; - //Setup the player size - VectorSet( mins, -8, -8, -8 ); - VectorSet( maxs, 8, 8, 8 ); + // Setup the player size + VectorSet(mins, -8, -8, -8); + VectorSet(maxs, 8, 8, 8); - //Setup the points - first->GetPosition( start ); - second->GetPosition( end ); + // Setup the points + first->GetPosition(start); + second->GetPosition(end); - SV_Trace( &trace, start, mins, maxs, end, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 10 ); + SV_Trace(&trace, start, mins, maxs, end, ENTITYNUM_NONE, MASK_SOLID, qfalse, 0, 10); - if ( trace.fraction < 1.0f || trace.allsolid || trace.startsolid ) + if (trace.fraction < 1.0f || trace.allsolid || trace.startsolid) return Q3_INFINITE; // return -1; - //Connection successful, return the cost - return Distance( start, end ); + // Connection successful, return the cost + return Distance(start, end); } -void CNavigator::SetEdgeCost( int ID1, int ID2, int cost ) -{ - if( (ID1 == -1) || (ID2 == -1) ) - {//not valid nodes, must have come from the ClearAllFailedEdges initization-type calls +void CNavigator::SetEdgeCost(int ID1, int ID2, int cost) { + if ((ID1 == -1) || (ID2 == -1)) { // not valid nodes, must have come from the ClearAllFailedEdges initization-type calls return; } - CNode *node1 = m_nodes[ID1]; - CNode *node2 = m_nodes[ID2]; + CNode *node1 = m_nodes[ID1]; + CNode *node2 = m_nodes[ID2]; - if ( cost == -1 ) - {//they want us to calc it - //FIXME: can we just remember this instead of recalcing every time? - vec3_t pos1, pos2; + if (cost == -1) { // they want us to calc it + // FIXME: can we just remember this instead of recalcing every time? + vec3_t pos1, pos2; - node1->GetPosition( pos1 ); - node2->GetPosition( pos2 ); - cost = Distance( pos1, pos2 ); + node1->GetPosition(pos1); + node2->GetPosition(pos2); + cost = Distance(pos1, pos2); } - //set it - node1->AddEdge( ID2, cost ); - node2->AddEdge( ID1, cost ); + // set it + node1->AddEdge(ID2, cost); + node2->AddEdge(ID1, cost); } /* @@ -795,23 +711,21 @@ AddNodeEdges ------------------------- */ -void CNavigator::AddNodeEdges( CNode *node, int addDist, edge_l &edgeList, bool *checkedNodes ) -{ - //Add all edge - for ( int i = 0; i < node->GetNumEdges(); i++ ) - { - //Make sure we don't add an old edge twice - if ( checkedNodes[ node->GetEdge( i ) ] == true ) +void CNavigator::AddNodeEdges(CNode *node, int addDist, edge_l &edgeList, bool *checkedNodes) { + // Add all edge + for (int i = 0; i < node->GetNumEdges(); i++) { + // Make sure we don't add an old edge twice + if (checkedNodes[node->GetEdge(i)] == true) continue; - //Get the node - CNode *nextNode = m_nodes[ node->GetEdge( i ) ]; + // Get the node + CNode *nextNode = m_nodes[node->GetEdge(i)]; - //This node has now been checked - checkedNodes[ nextNode->GetID() ] = true; + // This node has now been checked + checkedNodes[nextNode->GetID()] = true; - //Add it to the list - STL_INSERT( edgeList, CEdge( nextNode->GetID(), node->GetID(), addDist + ( node->GetEdgeCost( i ) ) ) ); + // Add it to the list + STL_INSERT(edgeList, CEdge(nextNode->GetID(), node->GetID(), addDist + (node->GetEdgeCost(i)))); } } @@ -821,69 +735,64 @@ CalculatePath ------------------------- */ -void CNavigator::CalculatePath( CNode *node ) -{ - int curRank = 0; +void CNavigator::CalculatePath(CNode *node) { + int curRank = 0; - CPriorityQueue *pathList = new CPriorityQueue(); - byte *checked; + CPriorityQueue *pathList = new CPriorityQueue(); + byte *checked; - //Init the completion table - checked = new byte[ m_nodes.size() ]; - memset( checked, 0, m_nodes.size() ); + // Init the completion table + checked = new byte[m_nodes.size()]; + memset(checked, 0, m_nodes.size()); - //Mark this node as checked - checked[ node->GetID() ] = true; - node->AddRank( node->GetID(), curRank++ ); + // Mark this node as checked + checked[node->GetID()] = true; + node->AddRank(node->GetID(), curRank++); - //Add all initial nodes + // Add all initial nodes int i; - for ( i = 0; i < node->GetNumEdges(); i++ ) - { - CNode *nextNode = m_nodes[ node->GetEdge(i) ]; + for (i = 0; i < node->GetNumEdges(); i++) { + CNode *nextNode = m_nodes[node->GetEdge(i)]; assert(nextNode); - checked[ nextNode->GetID() ] = true; + checked[nextNode->GetID()] = true; - pathList->Push( new CEdge( nextNode->GetID(), nextNode->GetID(), node->GetEdgeCost(i) ) ); + pathList->Push(new CEdge(nextNode->GetID(), nextNode->GetID(), node->GetEdgeCost(i))); } - //float minDist; - CEdge *test; + // float minDist; + CEdge *test; - //Now flood fill all the others - while ( !pathList->Empty() ) - { - //minDist = Q3_INFINITE; - test = pathList->Pop(); + // Now flood fill all the others + while (!pathList->Empty()) { + // minDist = Q3_INFINITE; + test = pathList->Pop(); - CNode *testNode = m_nodes[ (*test).m_first ]; - assert( testNode ); + CNode *testNode = m_nodes[(*test).m_first]; + assert(testNode); - node->AddRank( testNode->GetID(), curRank++ ); + node->AddRank(testNode->GetID(), curRank++); - //Add in all the new edges - for ( i = 0; i < testNode->GetNumEdges(); i++ ) - { - CNode *addNode = m_nodes[ testNode->GetEdge(i) ]; - assert( addNode ); + // Add in all the new edges + for (i = 0; i < testNode->GetNumEdges(); i++) { + CNode *addNode = m_nodes[testNode->GetEdge(i)]; + assert(addNode); - if ( checked[ addNode->GetID() ] ) + if (checked[addNode->GetID()]) continue; - int newDist = (*test).m_cost + testNode->GetEdgeCost(i); - pathList->Push( new CEdge( addNode->GetID(), (*test).m_second, newDist ) ); + int newDist = (*test).m_cost + testNode->GetEdgeCost(i); + pathList->Push(new CEdge(addNode->GetID(), (*test).m_second, newDist)); - checked[ addNode->GetID() ] = true; + checked[addNode->GetID()] = true; } delete test; - } - node->RemoveFlag( NF_RECALC ); + node->RemoveFlag(NF_RECALC); delete pathList; - delete [] checked; + delete[] checked; } /* @@ -891,24 +800,21 @@ void CNavigator::CalculatePath( CNode *node ) CalculatePaths ------------------------- */ -void CNavigator::CalculatePaths( qboolean recalc ) -{ +void CNavigator::CalculatePaths(qboolean recalc) { #if _HARD_CONNECT #else #endif - for ( size_t i = 0; i < m_nodes.size(); i++ ) - { - //Allocate the needed memory - m_nodes[i]->InitRanks( m_nodes.size() ); + for (size_t i = 0; i < m_nodes.size(); i++) { + // Allocate the needed memory + m_nodes[i]->InitRanks(m_nodes.size()); } - for ( size_t i = 0; i < m_nodes.size(); i++ ) - { - CalculatePath( m_nodes[i] ); + for (size_t i = 0; i < m_nodes.size(); i++) { + CalculatePath(m_nodes[i]); } - if(!recalc) //Mike says doesn't need to happen on recalc + if (!recalc) // Mike says doesn't need to happen on recalc { GVM_NAV_FindCombatPointWaypoints(); } @@ -922,39 +828,30 @@ ShowNodes ------------------------- */ -void CNavigator::ShowNodes( void ) -{ - node_v::iterator ni; +void CNavigator::ShowNodes(void) { + node_v::iterator ni; - vec3_t position; + vec3_t position; qboolean showRadius; - float dist, - radius; + float dist, radius; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->GetPosition( position ); + STL_ITERATE(ni, m_nodes) { + (*ni)->GetPosition(position); showRadius = qfalse; - //if( NAVDEBUG_showRadius ) - if (0) - { - dist = DistanceSquared( SV_GentityNum(0)->r.currentOrigin, position ); + // if( NAVDEBUG_showRadius ) + if (0) { + dist = DistanceSquared(SV_GentityNum(0)->r.currentOrigin, position); radius = (*ni)->GetRadius(); // if player within node radius or 256, draw radius (sometimes the radius is really small, so we check for 256 to catch everything) - if( (dist <= radius*radius) || dist <= 65536 ) - { + if ((dist <= radius * radius) || dist <= 65536) { showRadius = qtrue; } + } else { + dist = DistanceSquared(SV_GentityNum(0)->r.currentOrigin, position); } - else - { - dist = DistanceSquared( SV_GentityNum(0)->r.currentOrigin, position ); - } - if ( dist < 1048576 ) - { - if ( SV_inPVS( SV_GentityNum(0)->r.currentOrigin, position ) ) - { + if (dist < 1048576) { + if (SV_inPVS(SV_GentityNum(0)->r.currentOrigin, position)) { (*ni)->Draw(showRadius); } } @@ -967,57 +864,51 @@ ShowEdges ------------------------- */ -typedef std::map < int, bool > drawMap_m; +typedef std::map drawMap_m; -void CNavigator::ShowEdges( void ) -{ - node_v::iterator ni; - vec3_t start, end; +void CNavigator::ShowEdges(void) { + node_v::iterator ni; + vec3_t start, end; - drawMap_m *drawMap; + drawMap_m *drawMap; - drawMap = new drawMap_m[ m_nodes.size() ]; + drawMap = new drawMap_m[m_nodes.size()]; - STL_ITERATE( ni, m_nodes ) - { - (*ni)->GetPosition( start ); - if ( DistanceSquared( SV_GentityNum(0)->r.currentOrigin, start ) >= 1048576 ) - { + STL_ITERATE(ni, m_nodes) { + (*ni)->GetPosition(start); + if (DistanceSquared(SV_GentityNum(0)->r.currentOrigin, start) >= 1048576) { continue; } - if (!SV_inPVS(SV_GentityNum(0)->r.currentOrigin, start)) - { + if (!SV_inPVS(SV_GentityNum(0)->r.currentOrigin, start)) { continue; } - //Attempt to draw each connection - for ( int i = 0; i < (*ni)->GetNumEdges(); i++ ) - { - int id = (*ni)->GetEdge( i ); + // Attempt to draw each connection + for (int i = 0; i < (*ni)->GetNumEdges(); i++) { + int id = (*ni)->GetEdge(i); - if ( id == -1 ) + if (id == -1) continue; - //Already drawn? - if ( drawMap[(*ni)->GetID()].find( id ) != drawMap[(*ni)->GetID()].end() ) + // Already drawn? + if (drawMap[(*ni)->GetID()].find(id) != drawMap[(*ni)->GetID()].end()) continue; - //BYTE flags = (*ni)->GetEdgeFlags( i ); + // BYTE flags = (*ni)->GetEdgeFlags( i ); - CNode *node = m_nodes[id]; + CNode *node = m_nodes[id]; - node->GetPosition( end ); + node->GetPosition(end); - //Set this as drawn + // Set this as drawn drawMap[id][(*ni)->GetID()] = true; - if ( DistanceSquared( SV_GentityNum(0)->r.currentOrigin, end ) >= 1048576 ) - { + if (DistanceSquared(SV_GentityNum(0)->r.currentOrigin, end) >= 1048576) { continue; } - if ( !SV_inPVS( SV_GentityNum(0)->r.currentOrigin, end ) ) + if (!SV_inPVS(SV_GentityNum(0)->r.currentOrigin, end)) continue; /* @@ -1028,83 +919,68 @@ void CNavigator::ShowEdges( void ) else CG_DrawEdge( start, end, EDGE_NORMAL ); */ - //rwwFIXMEFIXME: ... + // rwwFIXMEFIXME: ... } } - delete [] drawMap; + delete[] drawMap; } -int CNavigator::GetNodeRadius( int nodeID ) -{ - if ( m_nodes.size() == 0 ) +int CNavigator::GetNodeRadius(int nodeID) { + if (m_nodes.size() == 0) return 0; return m_nodes[nodeID]->GetRadius(); } -void CNavigator::CheckBlockedEdges( void ) -{ - CNode *start, *end; - vec3_t p1, p2; - int flags, first, second; - trace_t trace; +void CNavigator::CheckBlockedEdges(void) { + CNode *start, *end; + vec3_t p1, p2; + int flags, first, second; + trace_t trace; qboolean failed; - int edgeNum; - node_v::iterator ni; - - //Go through all edges and test the ones that were blocked - STL_ITERATE( ni, m_nodes ) - { - //Attempt to draw each connection - for ( edgeNum = 0; edgeNum < (*ni)->GetNumEdges(); edgeNum++ ) - { - flags = (*ni)->GetEdgeFlags( edgeNum ); - if ( (flags&EFLAG_BLOCKED) ) - { - first = (*ni)->GetID(); - second = (*ni)->GetEdge( edgeNum ); - start = m_nodes[first]; - end = m_nodes[second]; - failed = qfalse; - - start->GetPosition( p1 ); - end->GetPosition( p2 ); - - //FIXME: can't we just store the trace.entityNum from the HardConnect trace? So we don't have to do another trace here... - SV_Trace( &trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 10 ); - - if ( trace.entityNum < ENTITYNUM_WORLD && (trace.fraction < 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue) ) - {//could be assumed, since failed before - if ( GVM_NAV_EntIsDoor( trace.entityNum ) ) - {//door - if ( !GVM_NAV_EntIsUnlockedDoor( trace.entityNum ) ) - {//locked door + int edgeNum; + node_v::iterator ni; + + // Go through all edges and test the ones that were blocked + STL_ITERATE(ni, m_nodes) { + // Attempt to draw each connection + for (edgeNum = 0; edgeNum < (*ni)->GetNumEdges(); edgeNum++) { + flags = (*ni)->GetEdgeFlags(edgeNum); + if ((flags & EFLAG_BLOCKED)) { + first = (*ni)->GetID(); + second = (*ni)->GetEdge(edgeNum); + start = m_nodes[first]; + end = m_nodes[second]; + failed = qfalse; + + start->GetPosition(p1); + end->GetPosition(p2); + + // FIXME: can't we just store the trace.entityNum from the HardConnect trace? So we don't have to do another trace here... + SV_Trace(&trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, 10); + + if (trace.entityNum < ENTITYNUM_WORLD && + (trace.fraction < 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue)) { // could be assumed, since failed before + if (GVM_NAV_EntIsDoor(trace.entityNum)) { // door + if (!GVM_NAV_EntIsUnlockedDoor(trace.entityNum)) { // locked door failed = qtrue; } - } - else - { - if ( GVM_NAV_EntIsBreakable( trace.entityNum ) ) - {//do same for breakable brushes/models/glass? + } else { + if (GVM_NAV_EntIsBreakable(trace.entityNum)) { // do same for breakable brushes/models/glass? failed = qtrue; - } - else if ( GVM_NAV_EntIsRemovableUsable( trace.entityNum ) ) - { + } else if (GVM_NAV_EntIsRemovableUsable(trace.entityNum)) { failed = qtrue; - } - else if ( trace.allsolid || trace.startsolid ) - {//FIXME: the entitynum would be none here, so how do we know if this is stuck inside an ent or the world? - } - else - {//FIXME: what about func_plats and scripted movers? + } else if (trace.allsolid || + trace + .startsolid) { // FIXME: the entitynum would be none here, so how do we know if this is stuck inside an ent or the world? + } else { // FIXME: what about func_plats and scripted movers? } } } - if ( failed ) - { - //could add the EFLAG_FAILED to the two edges, but we stopped doing that since it was pointless - AddFailedEdge( ENTITYNUM_NONE, first, second ); + if (failed) { + // could add the EFLAG_FAILED to the two edges, but we stopped doing that since it was pointless + AddFailedEdge(ENTITYNUM_NONE, first, second); } } } @@ -1119,33 +995,31 @@ HardConnect ------------------------- */ -void CNavigator::HardConnect( int first, int second ) -{ - CNode *start, *end; +void CNavigator::HardConnect(int first, int second) { + CNode *start, *end; - start = m_nodes[first]; - end = m_nodes[second]; + start = m_nodes[first]; + end = m_nodes[second]; - vec3_t p1, p2; + vec3_t p1, p2; - start->GetPosition( p1 ); - end->GetPosition( p2 ); + start->GetPosition(p1); + end->GetPosition(p2); - trace_t trace; + trace_t trace; - int flags = EFLAG_NONE; + int flags = EFLAG_NONE; - SV_Trace( &trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID|CONTENTS_BOTCLIP|CONTENTS_MONSTERCLIP, qfalse, 0, 10 ); + SV_Trace(&trace, p1, wpMins, wpMaxs, p2, ENTITYNUM_NONE, MASK_SOLID | CONTENTS_BOTCLIP | CONTENTS_MONSTERCLIP, qfalse, 0, 10); - int cost = Distance( p1, p2 ); + int cost = Distance(p1, p2); - if ( trace.fraction != 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue ) - { + if (trace.fraction != 1.0f || trace.startsolid == qtrue || trace.allsolid == qtrue) { flags |= EFLAG_BLOCKED; } - start->AddEdge( second, cost, flags ); - end->AddEdge( first, cost, flags ); + start->AddEdge(second, cost, flags); + end->AddEdge(first, cost, flags); } #endif @@ -1156,16 +1030,14 @@ TestNodePath ------------------------- */ -int CNavigator::TestNodePath( sharedEntity_t *ent, int okToHitEntNum, vec3_t position, qboolean includeEnts ) -{ //rwwFIXMEFIXME: Share clipmask? - int clipmask = MASK_SOLID;//ent->clipmask; +int CNavigator::TestNodePath(sharedEntity_t *ent, int okToHitEntNum, vec3_t position, qboolean includeEnts) { // rwwFIXMEFIXME: Share clipmask? + int clipmask = MASK_SOLID; // ent->clipmask; - if ( !includeEnts ) - { + if (!includeEnts) { clipmask &= ~CONTENTS_BODY; } - //Check the path - if ( GVM_NAV_ClearPathToPoint( ent->s.number, ent->r.mins, ent->r.maxs, position, clipmask, okToHitEntNum ) == false ) + // Check the path + if (GVM_NAV_ClearPathToPoint(ent->s.number, ent->r.mins, ent->r.maxs, position, clipmask, okToHitEntNum) == false) return false; return true; @@ -1177,10 +1049,7 @@ TestNodeLOS ------------------------- */ -int CNavigator::TestNodeLOS( sharedEntity_t *ent, vec3_t position ) -{ - return GVM_NPC_ClearLOS2( ent->s.number, position ); -} +int CNavigator::TestNodeLOS(sharedEntity_t *ent, vec3_t position) { return GVM_NPC_ClearLOS2(ent->s.number, position); } /* ------------------------- @@ -1188,56 +1057,49 @@ TestBestFirst ------------------------- */ -int CNavigator::TestBestFirst( sharedEntity_t *ent, int lastID, int flags ) -{ - //Must be a valid one to begin with - if ( lastID == NODE_NONE ) +int CNavigator::TestBestFirst(sharedEntity_t *ent, int lastID, int flags) { + // Must be a valid one to begin with + if (lastID == NODE_NONE) return NODE_NONE; - if ( lastID >= (int)m_nodes.size() ) + if (lastID >= (int)m_nodes.size()) return NODE_NONE; - //Get the info - vec3_t nodePos; - CNode *node = m_nodes[ lastID ]; - CNode *testNode; - int numEdges = node->GetNumEdges(); - float dist; + // Get the info + vec3_t nodePos; + CNode *node = m_nodes[lastID]; + CNode *testNode; + int numEdges = node->GetNumEdges(); + float dist; - node->GetPosition( nodePos ); + node->GetPosition(nodePos); - //Setup our last node as our root, and search for a closer one according to its edges - int bestNode = ( TestNodePath( ent, ENTITYNUM_NONE, nodePos, qtrue ) ) ? lastID : NODE_NONE; - float bestDist = ( bestNode == NODE_NONE ) ? Q3_INFINITE : DistanceSquared( ent->r.currentOrigin, nodePos ); + // Setup our last node as our root, and search for a closer one according to its edges + int bestNode = (TestNodePath(ent, ENTITYNUM_NONE, nodePos, qtrue)) ? lastID : NODE_NONE; + float bestDist = (bestNode == NODE_NONE) ? Q3_INFINITE : DistanceSquared(ent->r.currentOrigin, nodePos); - //Test all these edges first - for ( int i = 0; i < numEdges; i++ ) - { - //Get this node and its distance - testNode = m_nodes[ node->GetEdge(i) ]; + // Test all these edges first + for (int i = 0; i < numEdges; i++) { + // Get this node and its distance + testNode = m_nodes[node->GetEdge(i)]; - if ( NodeFailed( ent, testNode->GetID() ) ) - { + if (NodeFailed(ent, testNode->GetID())) { continue; } - testNode->GetPosition( nodePos ); + testNode->GetPosition(nodePos); - dist = DistanceSquared( ent->r.currentOrigin, nodePos ); + dist = DistanceSquared(ent->r.currentOrigin, nodePos); - //Test against current best - if ( dist < bestDist ) - { - //See if this node is valid - if ( CheckedNode(testNode->GetID(),ent->s.number) == CHECKED_PASSED || TestNodePath( ent, ENTITYNUM_NONE, nodePos, qtrue ) ) - { + // Test against current best + if (dist < bestDist) { + // See if this node is valid + if (CheckedNode(testNode->GetID(), ent->s.number) == CHECKED_PASSED || TestNodePath(ent, ENTITYNUM_NONE, nodePos, qtrue)) { bestDist = dist; bestNode = testNode->GetID(); - SetCheckedNode(testNode->GetID(),ent->s.number,CHECKED_PASSED); - } - else - { - SetCheckedNode(testNode->GetID(),ent->s.number,CHECKED_FAILED); + SetCheckedNode(testNode->GetID(), ent->s.number, CHECKED_PASSED); + } else { + SetCheckedNode(testNode->GetID(), ent->s.number, CHECKED_FAILED); } } } @@ -1251,61 +1113,55 @@ CollectNearestNodes ------------------------- */ -#define NODE_COLLECT_MAX 16 //Maximum # of nodes collected at any time -#define NODE_COLLECT_RADIUS 512 //Default radius to search for nodes in -#define NODE_COLLECT_RADIUS_SQR ( NODE_COLLECT_RADIUS * NODE_COLLECT_RADIUS ) - -int CNavigator::CollectNearestNodes( vec3_t origin, int radius, int maxCollect, nodeChain_l &nodeChain ) -{ - node_v::iterator ni; - float dist; - vec3_t position; - int collected = 0; - bool added = false; - - //Get a distance rating for each node in the system - STL_ITERATE( ni, m_nodes ) - { - //If we've got our quota, then stop looking - //Get the distance to the node - (*ni)->GetPosition( position ); - dist = DistanceSquared( position, origin ); - - //Must be within our radius range - if ( dist > (float) ( radius * radius ) ) +#define NODE_COLLECT_MAX 16 // Maximum # of nodes collected at any time +#define NODE_COLLECT_RADIUS 512 // Default radius to search for nodes in +#define NODE_COLLECT_RADIUS_SQR (NODE_COLLECT_RADIUS * NODE_COLLECT_RADIUS) + +int CNavigator::CollectNearestNodes(vec3_t origin, int radius, int maxCollect, nodeChain_l &nodeChain) { + node_v::iterator ni; + float dist; + vec3_t position; + int collected = 0; + bool added = false; + + // Get a distance rating for each node in the system + STL_ITERATE(ni, m_nodes) { + // If we've got our quota, then stop looking + // Get the distance to the node + (*ni)->GetPosition(position); + dist = DistanceSquared(position, origin); + + // Must be within our radius range + if (dist > (float)(radius * radius)) continue; - nodeList_t nChain; - nodeChain_l::iterator nci; + nodeList_t nChain; + nodeChain_l::iterator nci; - //Always add the first node - if ( nodeChain.size() == 0 ) - { + // Always add the first node + if (nodeChain.size() == 0) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nodeChain.begin(), nChain ); + nodeChain.insert(nodeChain.begin(), nChain); continue; } added = false; - //Compare it to what we already have - STL_ITERATE( nci, nodeChain ) - { - //If we're less, than this entry, then insert before it - if ( dist < (*nci).distance ) - { + // Compare it to what we already have + STL_ITERATE(nci, nodeChain) { + // If we're less, than this entry, then insert before it + if (dist < (*nci).distance) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nci, nChain ); + nodeChain.insert(nci, nChain); collected = nodeChain.size(); added = true; - //If we've hit our collection limit, throw off the oldest one - if ( (int)nodeChain.size() > maxCollect ) - { + // If we've hit our collection limit, throw off the oldest one + if ((int)nodeChain.size() > maxCollect) { nodeChain.pop_back(); } @@ -1313,188 +1169,160 @@ int CNavigator::CollectNearestNodes( vec3_t origin, int radius, int maxCollect, } } - //Otherwise, always pad out the collection if possible so we don't miss anything - if ( ( added == false ) && ( (int)nodeChain.size() < maxCollect ) ) - { + // Otherwise, always pad out the collection if possible so we don't miss anything + if ((added == false) && ((int)nodeChain.size() < maxCollect)) { nChain.nodeID = (*ni)->GetID(); nChain.distance = dist; - nodeChain.insert( nodeChain.end(), nChain ); + nodeChain.insert(nodeChain.end(), nChain); } } return collected; } -int CNavigator::GetBestPathBetweenEnts( sharedEntity_t *ent, sharedEntity_t *goal, int flags ) -{ - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetBestPathBetweenEnts(sharedEntity_t *ent, sharedEntity_t *goal, int flags) { + // Must have nodes + if (m_nodes.size() == 0) return NODE_NONE; -#define MAX_Z_DELTA 18 +#define MAX_Z_DELTA 18 - nodeChain_l nodeChain; - nodeChain_l::iterator nci; - nodeChain_l nodeChain2; - nodeChain_l::iterator nci2; + nodeChain_l nodeChain; + nodeChain_l::iterator nci; + nodeChain_l nodeChain2; + nodeChain_l::iterator nci2; - //Collect all nodes within a certain radius - CollectNearestNodes( ent->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain ); - CollectNearestNodes( goal->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain2 ); + // Collect all nodes within a certain radius + CollectNearestNodes(ent->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain); + CollectNearestNodes(goal->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain2); - vec3_t position; - vec3_t position2; - int radius; - int cost, pathCost, bestCost = Q3_INFINITE; - CNode *node, *node2; - int nodeNum, nodeNum2; - int nextNode = NODE_NONE, bestNode = NODE_NONE; - int nodeFlags = 0; -// bool recalc = false; + vec3_t position; + vec3_t position2; + int radius; + int cost, pathCost, bestCost = Q3_INFINITE; + CNode *node, *node2; + int nodeNum, nodeNum2; + int nextNode = NODE_NONE, bestNode = NODE_NONE; + int nodeFlags = 0; + // bool recalc = false; ent->waypoint = NODE_NONE; goal->waypoint = NODE_NONE; - //Look through all nodes - STL_ITERATE( nci, nodeChain ) - { + // Look through all nodes + STL_ITERATE(nci, nodeChain) { node = m_nodes[(*nci).nodeID]; nodeNum = (*nci).nodeID; - node->GetPosition( position ); + node->GetPosition(position); - if ( CheckedNode(nodeNum,ent->s.number) == CHECKED_FAILED ) - {//already checked this node against ent and it failed + if (CheckedNode(nodeNum, ent->s.number) == CHECKED_FAILED) { // already checked this node against ent and it failed continue; } - if ( CheckedNode(nodeNum,ent->s.number) == CHECKED_PASSED ) - {//already checked this node against ent and it passed - } - else - {//haven't checked this node against ent yet - if ( NodeFailed( ent, nodeNum ) ) - { - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + if (CheckedNode(nodeNum, ent->s.number) == CHECKED_PASSED) { // already checked this node against ent and it passed + } else { // haven't checked this node against ent yet + if (NodeFailed(ent, nodeNum)) { + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } - //okay, since we only have to do this once, let's check to see if this node is even usable (could help us short-circuit a whole loop of the dest nodes) - radius = node->GetRadius(); - - //If we're not within the known clear radius of this node OR out of Z height range... - if ( (int)(*nci).distance >= (radius*radius) || ( fabs( position[2] - ent->r.currentOrigin[2] ) >= MAX_Z_DELTA ) ) - { - //We're not *within* this node, so check clear path, etc. - - //FIXME: any way to call G_FindClosestPointOnLineSegment and see if I can at least get to the waypoint's path - if ( flags & NF_CLEAR_PATH )//|| flags & NF_CLEAR_LOS ) - {//need a clear path or LOS - if ( !SV_inPVS( ent->r.currentOrigin, position ) ) - {//not even potentially clear - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + // okay, since we only have to do this once, let's check to see if this node is even usable (could help us short-circuit a whole loop of the dest + // nodes) + radius = node->GetRadius(); + + // If we're not within the known clear radius of this node OR out of Z height range... + if ((int)(*nci).distance >= (radius * radius) || (fabs(position[2] - ent->r.currentOrigin[2]) >= MAX_Z_DELTA)) { + // We're not *within* this node, so check clear path, etc. + + // FIXME: any way to call G_FindClosestPointOnLineSegment and see if I can at least get to the waypoint's path + if (flags & NF_CLEAR_PATH) //|| flags & NF_CLEAR_LOS ) + { // need a clear path or LOS + if (!SV_inPVS(ent->r.currentOrigin, position)) { // not even potentially clear + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( ent, goal->s.number, position, qtrue ) == false ) - { - SetCheckedNode( nodeNum, ent->s.number, CHECKED_FAILED ); + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(ent, goal->s.number, position, qtrue) == false) { + SetCheckedNode(nodeNum, ent->s.number, CHECKED_FAILED); continue; } } - }//otherwise, inside the node so it must be clear (?) - SetCheckedNode( nodeNum, ent->s.number, CHECKED_PASSED ); + } // otherwise, inside the node so it must be clear (?) + SetCheckedNode(nodeNum, ent->s.number, CHECKED_PASSED); } - if ( d_altRoutes->integer ) - { - //calc the paths for this node if they're out of date + if (d_altRoutes->integer) { + // calc the paths for this node if they're out of date nodeFlags = node->GetFlags(); - if ( (nodeFlags&NF_RECALC) ) - { - //Com_Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", svs.time, nodeNum ); - CalculatePath( node ); + if ((nodeFlags & NF_RECALC)) { + // Com_Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", svs.time, nodeNum ); + CalculatePath(node); } } - STL_ITERATE( nci2, nodeChain2 ) - { + STL_ITERATE(nci2, nodeChain2) { node2 = m_nodes[(*nci2).nodeID]; nodeNum2 = (*nci2).nodeID; - if ( d_altRoutes->integer ) - { - //calc the paths for this node if they're out of date + if (d_altRoutes->integer) { + // calc the paths for this node if they're out of date nodeFlags = node2->GetFlags(); - if ( (nodeFlags&NF_RECALC) ) - { - //Com_Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", svs.time, nodeNum2 ); - CalculatePath( node2 ); + if ((nodeFlags & NF_RECALC)) { + // Com_Printf( S_COLOR_CYAN"%d recalcing paths from node %d\n", svs.time, nodeNum2 ); + CalculatePath(node2); } } - node2->GetPosition( position2 ); - //Okay, first get the entire path cost, including distance to first node from ents' positions - cost = floor(Distance( ent->r.currentOrigin, position ) + Distance( goal->r.currentOrigin, position2 )); + node2->GetPosition(position2); + // Okay, first get the entire path cost, including distance to first node from ents' positions + cost = floor(Distance(ent->r.currentOrigin, position) + Distance(goal->r.currentOrigin, position2)); - if ( d_altRoutes->integer ) - { - nextNode = GetBestNodeAltRoute( (*nci).nodeID, (*nci2).nodeID, &pathCost, bestNode ); + if (d_altRoutes->integer) { + nextNode = GetBestNodeAltRoute((*nci).nodeID, (*nci2).nodeID, &pathCost, bestNode); cost += pathCost; - } - else - { - cost += GetPathCost( (*nci).nodeID, (*nci2).nodeID ); + } else { + cost += GetPathCost((*nci).nodeID, (*nci2).nodeID); } - if ( cost >= bestCost ) - { + if (cost >= bestCost) { continue; } - //okay, this is the shortest path we've found yet, check clear path, etc. - if ( CheckedNode( nodeNum2, goal->s.number ) == CHECKED_FAILED ) - {//already checked this node against goal and it failed + // okay, this is the shortest path we've found yet, check clear path, etc. + if (CheckedNode(nodeNum2, goal->s.number) == CHECKED_FAILED) { // already checked this node against goal and it failed continue; } - if ( CheckedNode( nodeNum2, goal->s.number ) == CHECKED_PASSED ) - {//already checked this node against goal and it passed - } - else - {//haven't checked this node against goal yet - if ( NodeFailed( goal, nodeNum2 ) ) - { - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + if (CheckedNode(nodeNum2, goal->s.number) == CHECKED_PASSED) { // already checked this node against goal and it passed + } else { // haven't checked this node against goal yet + if (NodeFailed(goal, nodeNum2)) { + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } - radius = node2->GetRadius(); + radius = node2->GetRadius(); - //If we're not within the known clear radius of this node OR out of Z height range... - if ( (int)(*nci2).distance >= (radius*radius) || ( fabs( position2[2] - goal->r.currentOrigin[2] ) >= MAX_Z_DELTA ) ) - { - //We're not *within* this node, so check clear path, etc. + // If we're not within the known clear radius of this node OR out of Z height range... + if ((int)(*nci2).distance >= (radius * radius) || (fabs(position2[2] - goal->r.currentOrigin[2]) >= MAX_Z_DELTA)) { + // We're not *within* this node, so check clear path, etc. - if ( flags & NF_CLEAR_PATH )//|| flags & NF_CLEAR_LOS ) - {//need a clear path or LOS - if ( !SV_inPVS( goal->r.currentOrigin, position2 ) ) - {//not even potentially clear - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + if (flags & NF_CLEAR_PATH) //|| flags & NF_CLEAR_LOS ) + { // need a clear path or LOS + if (!SV_inPVS(goal->r.currentOrigin, position2)) { // not even potentially clear + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( goal, ent->s.number, position2, qfalse ) == false )//qtrue? + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(goal, ent->s.number, position2, qfalse) == false) // qtrue? { - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_FAILED ); + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_FAILED); continue; } } - }//otherwise, inside the node so it must be clear (?) - SetCheckedNode( nodeNum2, goal->s.number, CHECKED_PASSED ); + } // otherwise, inside the node so it must be clear (?) + SetCheckedNode(nodeNum2, goal->s.number, CHECKED_PASSED); } bestCost = cost; @@ -1504,11 +1332,9 @@ int CNavigator::GetBestPathBetweenEnts( sharedEntity_t *ent, sharedEntity_t *goa } } - if ( !d_altRoutes->integer ) - {//bestNode would not have been set by GetBestNodeAltRoute above, so get it here - if ( ent->waypoint != NODE_NONE && goal->waypoint != NODE_NONE ) - {//have 2 valid waypoints which means a valid path - bestNode = GetBestNodeAltRoute( ent->waypoint, goal->waypoint, &bestCost, NODE_NONE ); + if (!d_altRoutes->integer) { // bestNode would not have been set by GetBestNodeAltRoute above, so get it here + if (ent->waypoint != NODE_NONE && goal->waypoint != NODE_NONE) { // have 2 valid waypoints which means a valid path + bestNode = GetBestNodeAltRoute(ent->waypoint, goal->waypoint, &bestCost, NODE_NONE); } } return bestNode; @@ -1520,85 +1346,73 @@ GetNearestWaypoint ------------------------- */ -int CNavigator::GetNearestNode( sharedEntity_t *ent, int lastID, int flags, int targetID ) -{ - int bestNode = NODE_NONE; - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetNearestNode(sharedEntity_t *ent, int lastID, int flags, int targetID) { + int bestNode = NODE_NONE; + // Must have nodes + if (m_nodes.size() == 0) return NODE_NONE; - if ( targetID == NODE_NONE ) - { - //Try and find an early match using our last node - bestNode = TestBestFirst( ent, lastID, flags ); + if (targetID == NODE_NONE) { + // Try and find an early match using our last node + bestNode = TestBestFirst(ent, lastID, flags); - if ( bestNode != NODE_NONE ) + if (bestNode != NODE_NONE) return bestNode; - }//else can't rely on testing last, we want best to targetID + } // else can't rely on testing last, we want best to targetID -///////////////////////////////////////////////// + ///////////////////////////////////////////////// -#define MAX_Z_DELTA 18 +#define MAX_Z_DELTA 18 -///////////////////////////////////////////////// + ///////////////////////////////////////////////// - nodeChain_l nodeChain; - nodeChain_l::iterator nci; + nodeChain_l nodeChain; + nodeChain_l::iterator nci; - //Collect all nodes within a certain radius - CollectNearestNodes( ent->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain ); + // Collect all nodes within a certain radius + CollectNearestNodes(ent->r.currentOrigin, NODE_COLLECT_RADIUS, NODE_COLLECT_MAX, nodeChain); - vec3_t position; - int radius; - int dist, bestDist = Q3_INFINITE; - CNode *node; + vec3_t position; + int radius; + int dist, bestDist = Q3_INFINITE; + CNode *node; - //Look through all nodes - STL_ITERATE( nci, nodeChain ) - { + // Look through all nodes + STL_ITERATE(nci, nodeChain) { node = m_nodes[(*nci).nodeID]; - node->GetPosition( position ); + node->GetPosition(position); - radius = node->GetRadius(); + radius = node->GetRadius(); - if ( NodeFailed( ent, (*nci).nodeID ) ) - { + if (NodeFailed(ent, (*nci).nodeID)) { continue; } - //Are we within the known clear radius of this node? - if ( (int)(*nci).distance < (radius*radius) ) - { - //Do a z-difference sanity check - if ( fabs( position[2] - ent->r.currentOrigin[2] ) < MAX_Z_DELTA ) - { - //Found one + // Are we within the known clear radius of this node? + if ((int)(*nci).distance < (radius * radius)) { + // Do a z-difference sanity check + if (fabs(position[2] - ent->r.currentOrigin[2]) < MAX_Z_DELTA) { + // Found one return (*nci).nodeID; } } - //We're not *within* this node, so... - if ( CheckedNode((*nci).nodeID,ent->s.number) == CHECKED_FAILED ) - { + // We're not *within* this node, so... + if (CheckedNode((*nci).nodeID, ent->s.number) == CHECKED_FAILED) { continue; - } - else if ( CheckedNode((*nci).nodeID,ent->s.number) == CHECKED_FAILED ) - { + } else if (CheckedNode((*nci).nodeID, ent->s.number) == CHECKED_FAILED) { continue; - } - else - { - //Do we need a clear path? - if ( flags & NF_CLEAR_PATH ) - { - if ( TestNodePath( ent, ENTITYNUM_NONE, position, qfalse ) == false )//qtrue? + } else { + // Do we need a clear path? + if (flags & NF_CLEAR_PATH) { + if (TestNodePath(ent, ENTITYNUM_NONE, position, qfalse) == false) // qtrue? { - SetCheckedNode((*nci).nodeID,ent->s.number,CHECKED_FAILED); + SetCheckedNode((*nci).nodeID, ent->s.number, CHECKED_FAILED); continue; } } - //Do we need a clear line of sight? + // Do we need a clear line of sight? /* if ( flags & NF_CLEAR_LOS ) { @@ -1609,26 +1423,22 @@ int CNavigator::GetNearestNode( sharedEntity_t *ent, int lastID, int flags, int } } */ - SetCheckedNode((*nci).nodeID,ent->s.number,CHECKED_PASSED); + SetCheckedNode((*nci).nodeID, ent->s.number, CHECKED_PASSED); } - if ( targetID != WAYPOINT_NONE ) - {//we want to find the one with the shortest route here - dist = GetPathCost( (*nci).nodeID, targetID ); - if ( dist < bestDist ) - { + if (targetID != WAYPOINT_NONE) { // we want to find the one with the shortest route here + dist = GetPathCost((*nci).nodeID, targetID); + if (dist < bestDist) { bestDist = dist; bestNode = (*nci).nodeID; } - } - else - {//first one we find is fine + } else { // first one we find is fine bestNode = (*nci).nodeID; break; } } - //Found one, we're done + // Found one, we're done return bestNode; } @@ -1638,217 +1448,183 @@ ShowPath ------------------------- */ -void CNavigator::ShowPath( int start, int end ) -{ - //Validate the start position - if ( ( start < 0 ) || ( start >= (int)m_nodes.size() ) ) +void CNavigator::ShowPath(int start, int end) { + // Validate the start position + if ((start < 0) || (start >= (int)m_nodes.size())) return; - //Validate the end position - if ( ( end < 0 ) || ( end >= (int)m_nodes.size() ) ) + // Validate the end position + if ((end < 0) || (end >= (int)m_nodes.size())) return; - CNode *startNode = m_nodes[ start ]; - CNode *endNode = m_nodes[ end ]; + CNode *startNode = m_nodes[start]; + CNode *endNode = m_nodes[end]; - CNode *moveNode = startNode; - CNode *testNode = NULL; + CNode *moveNode = startNode; + CNode *testNode = NULL; - int bestNode; - vec3_t startPos, endPos; + int bestNode; + vec3_t startPos, endPos; - int runAway = 0; + int runAway = 0; - //Draw out our path - while ( moveNode != endNode ) - { - bestNode = GetBestNode( moveNode->GetID(), end ); + // Draw out our path + while (moveNode != endNode) { + bestNode = GetBestNode(moveNode->GetID(), end); - //Some nodes may be fragmented - if ( bestNode == -1 ) - { - Com_Printf("No connection possible between node %d and %d\n", start, end ); + // Some nodes may be fragmented + if (bestNode == -1) { + Com_Printf("No connection possible between node %d and %d\n", start, end); return; } - //This is our next node on the path - testNode = m_nodes[ bestNode ]; + // This is our next node on the path + testNode = m_nodes[bestNode]; - //Get their origins - moveNode->GetPosition( startPos ); - testNode->GetPosition( endPos ); + // Get their origins + moveNode->GetPosition(startPos); + testNode->GetPosition(endPos); - //Draw the edge - //rwwFIXMEFIXME: ... - //CG_DrawEdge( startPos, endPos, EDGE_PATH ); + // Draw the edge + // rwwFIXMEFIXME: ... + // CG_DrawEdge( startPos, endPos, EDGE_PATH ); - //Take a new best node + // Take a new best node moveNode = testNode; - if ( runAway++ > 64 ) - { + if (runAway++ > 64) { Com_Printf("Potential Run-away path!\n"); return; } } } -static std::map CheckedNodes; -void CNavigator::ClearCheckedNodes( void ) -{ - CheckedNodes.clear(); -} +static std::map CheckedNodes; +void CNavigator::ClearCheckedNodes(void) { CheckedNodes.clear(); } -byte CNavigator::CheckedNode(int wayPoint,int ent) -{ - //assert(wayPoint>=0&&wayPoint= MAX_STORED_WAYPOINTS) - { +byte CNavigator::CheckedNode(int wayPoint, int ent) { + // assert(wayPoint>=0&&wayPoint= MAX_STORED_WAYPOINTS) { return CHECKED_NO; } - assert(ent>=0&&ent::iterator f=CheckedNodes.find(wayPoint*MAX_GENTITIES+ent); - if (f!=CheckedNodes.end()) - { + assert(ent >= 0 && ent < MAX_GENTITIES); + std::map::iterator f = CheckedNodes.find(wayPoint * MAX_GENTITIES + ent); + if (f != CheckedNodes.end()) { return (*f).second; } return CHECKED_NO; } -void CNavigator::SetCheckedNode(int wayPoint,int ent,byte value) -{ - //assert(wayPoint>=0&&wayPoint= MAX_STORED_WAYPOINTS) - { +void CNavigator::SetCheckedNode(int wayPoint, int ent, byte value) { + // assert(wayPoint>=0&&wayPoint= MAX_STORED_WAYPOINTS) { return; } - assert(ent>=0&&ent= 0 && ent < MAX_GENTITIES); + assert(value == CHECKED_FAILED || value == CHECKED_PASSED); + CheckedNodes[wayPoint * MAX_GENTITIES + ent] = value; } -#define CHECK_FAILED_EDGE_INTERVAL 1000 -#define CHECK_FAILED_EDGE_INTITIAL 5000//10000 +#define CHECK_FAILED_EDGE_INTERVAL 1000 +#define CHECK_FAILED_EDGE_INTITIAL 5000 // 10000 -void CNavigator::CheckFailedNodes( sharedEntity_t *ent ) -{ - vec3_t nodePos; - int j; +void CNavigator::CheckFailedNodes(sharedEntity_t *ent) { + vec3_t nodePos; + int j; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - if ( ent->failedWaypointCheckTime && ent->failedWaypointCheckTime < svs.time ) - { + if (ent->failedWaypointCheckTime && ent->failedWaypointCheckTime < svs.time) { int failed = 0; - //do this only once every 1 second - for ( j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] != 0 ) - { + // do this only once every 1 second + for (j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] != 0) { failed++; //-1 because 0 is a valid node but also the default, so we add one when we add one - m_nodes[ent->failedWaypoints[j]-1]->GetPosition( nodePos ); - if ( !GVM_NAV_ClearPathToPoint( ent->s.number, ent->r.mins, ent->r.maxs, nodePos, (CONTENTS_SOLID|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP), ENTITYNUM_NONE ) ) - {//no path clear of architecture, so clear this since we can't check against entities + m_nodes[ent->failedWaypoints[j] - 1]->GetPosition(nodePos); + if (!GVM_NAV_ClearPathToPoint(ent->s.number, ent->r.mins, ent->r.maxs, nodePos, (CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP), + ENTITYNUM_NONE)) { // no path clear of architecture, so clear this since we can't check against entities ent->failedWaypoints[j] = 0; failed--; } - //have clear architectural path, now check against ents only - else if ( GVM_NAV_ClearPathToPoint( ent->s.number, ent->r.mins, ent->r.maxs, nodePos, CONTENTS_BODY, ENTITYNUM_NONE ) ) - {//clear of ents, too, so all clear, clear this one out + // have clear architectural path, now check against ents only + else if (GVM_NAV_ClearPathToPoint(ent->s.number, ent->r.mins, ent->r.maxs, nodePos, CONTENTS_BODY, + ENTITYNUM_NONE)) { // clear of ents, too, so all clear, clear this one out ent->failedWaypoints[j] = 0; failed--; } } } - if ( !failed ) - { + if (!failed) { ent->failedWaypointCheckTime = 0; - } - else - { - ent->failedWaypointCheckTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + } else { + ent->failedWaypointCheckTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); } } } -void CNavigator::AddFailedNode( sharedEntity_t *ent, int nodeID ) -{ +void CNavigator::AddFailedNode(sharedEntity_t *ent, int nodeID) { int j; - for ( j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( ent->failedWaypoints[j] == 0 ) - { - ent->failedWaypoints[j] = nodeID+1;//+1 because 0 is the default value and that's a valid node, so we take the +1 out when we check the node above - if ( !ent->failedWaypointCheckTime ) - { + for (j = 0; j < MAX_FAILED_NODES; j++) { + if (ent->failedWaypoints[j] == 0) { + ent->failedWaypoints[j] = + nodeID + 1; //+1 because 0 is the default value and that's a valid node, so we take the +1 out when we check the node above + if (!ent->failedWaypointCheckTime) { ent->failedWaypointCheckTime = svs.time + CHECK_FAILED_EDGE_INTITIAL; } return; } - if ( ent->failedWaypoints[j] == nodeID+1 ) - {//already have this one marked as failed + if (ent->failedWaypoints[j] == nodeID + 1) { // already have this one marked as failed return; } } - if ( j == MAX_FAILED_NODES )//check not needed, but... - {//ran out of failed nodes, get rid of first one, shift rest up - for ( j = 0; j < MAX_FAILED_NODES-1; j++ ) - { - ent->failedWaypoints[j] = ent->failedWaypoints[j+1]; + if (j == MAX_FAILED_NODES) // check not needed, but... + { // ran out of failed nodes, get rid of first one, shift rest up + for (j = 0; j < MAX_FAILED_NODES - 1; j++) { + ent->failedWaypoints[j] = ent->failedWaypoints[j + 1]; } } - ent->failedWaypoints[MAX_FAILED_NODES-1] = nodeID+1; - if ( !ent->failedWaypointCheckTime ) - { + ent->failedWaypoints[MAX_FAILED_NODES - 1] = nodeID + 1; + if (!ent->failedWaypointCheckTime) { ent->failedWaypointCheckTime = svs.time + CHECK_FAILED_EDGE_INTITIAL; } } -qboolean CNavigator::NodeFailed( sharedEntity_t *ent, int nodeID ) -{ - for ( int j = 0; j < MAX_FAILED_NODES; j++ ) - { - if ( (ent->failedWaypoints[j]-1) == nodeID ) - { +qboolean CNavigator::NodeFailed(sharedEntity_t *ent, int nodeID) { + for (int j = 0; j < MAX_FAILED_NODES; j++) { + if ((ent->failedWaypoints[j] - 1) == nodeID) { return qtrue; } } return qfalse; } -qboolean CNavigator::NodesAreNeighbors( int startID, int endID ) -{//See if these 2 are neighbors - if ( startID == endID ) - { +qboolean CNavigator::NodesAreNeighbors(int startID, int endID) { // See if these 2 are neighbors + if (startID == endID) { return qfalse; } CNode *start = m_nodes[startID]; - int nextID = -1; - //NOTE: we only check start because we assume all connections are 2-way - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { + int nextID = -1; + // NOTE: we only check start because we assume all connections are 2-way + for (int i = 0; i < start->GetNumEdges(); i++) { nextID = start->GetEdge(i); - if ( nextID == endID ) - { + if (nextID == endID) { return qtrue; } } - //not neighbors + // not neighbors return qfalse; } -void CNavigator::ClearFailedEdge( failedEdge_t *failedEdge ) -{ - if ( !failedEdge ) - { +void CNavigator::ClearFailedEdge(failedEdge_t *failedEdge) { + if (!failedEdge) { return; } - //clear the edge failed flags + // clear the edge failed flags /* CNode *node = m_nodes[failedEdge->startID]; int edgeNum = node->GetEdgeNumToNode( failedEdge->endID ); @@ -1866,41 +1642,34 @@ void CNavigator::ClearFailedEdge( failedEdge_t *failedEdge ) node->SetEdgeFlags( edgeNum, flags ); } */ - //clear failedEdge info - SetEdgeCost( failedEdge->startID, failedEdge->endID, -1 ); + // clear failedEdge info + SetEdgeCost(failedEdge->startID, failedEdge->endID, -1); failedEdge->startID = failedEdge->endID = WAYPOINT_NONE; failedEdge->entID = ENTITYNUM_NONE; failedEdge->checkTime = 0; } -void CNavigator::ClearAllFailedEdges( void ) -{ - memset( &failedEdges, WAYPOINT_NONE, sizeof( failedEdges ) ); - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { - ClearFailedEdge( &failedEdges[j] ); +void CNavigator::ClearAllFailedEdges(void) { + memset(&failedEdges, WAYPOINT_NONE, sizeof(failedEdges)); + for (int j = 0; j < MAX_FAILED_EDGES; j++) { + ClearFailedEdge(&failedEdges[j]); } } -int CNavigator::EdgeFailed( int startID, int endID ) -{ - //OPTIMIZED WAY (bjg 01/02) - //find in lookup map - std::pair findValue; +int CNavigator::EdgeFailed(int startID, int endID) { + // OPTIMIZED WAY (bjg 01/02) + // find in lookup map + std::pair findValue; findValue = m_edgeLookupMap.equal_range(startID); - while ( findValue.first != findValue.second ) - { - if( failedEdges[findValue.first->second].endID == endID) - { + while (findValue.first != findValue.second) { + if (failedEdges[findValue.first->second].endID == endID) { return findValue.first->second; } ++findValue.first; } findValue = m_edgeLookupMap.equal_range(endID); - while ( findValue.first != findValue.second ) - { - if( failedEdges[findValue.first->second].endID == startID) - { + while (findValue.first != findValue.second) { + if (failedEdges[findValue.first->second].endID == startID) { return findValue.first->second; } ++findValue.first; @@ -1908,7 +1677,7 @@ int CNavigator::EdgeFailed( int startID, int endID ) return -1; - //Old way (linear search) + // Old way (linear search) /* for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) { @@ -1931,69 +1700,60 @@ int CNavigator::EdgeFailed( int startID, int endID ) */ } -void CNavigator::AddFailedEdge( int entID, int startID, int endID ) -{ - int j;//, nextID; +void CNavigator::AddFailedEdge(int entID, int startID, int endID) { + int j; //, nextID; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - if ( d_patched->integer ) - {//use patch-style navigation - if ( startID == endID ) - {//not an edge! + if (d_patched->integer) { // use patch-style navigation + if (startID == endID) { // not an edge! return; } } - //Validate the ent number - if ( ( entID < 0 ) || ( entID > ENTITYNUM_NONE ) ) - { + // Validate the ent number + if ((entID < 0) || (entID > ENTITYNUM_NONE)) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"NAV ERROR: envalid ent %d\n", entID ); - assert(0&&"invalid entID"); + Com_Printf(S_COLOR_RED "NAV ERROR: envalid ent %d\n", entID); + assert(0 && "invalid entID"); #endif return; } - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) - { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"NAV ERROR: tried to fail invalid waypoint %d\n", startID ); - assert(0&&"invalid failed edge"); + Com_Printf(S_COLOR_RED "NAV ERROR: tried to fail invalid waypoint %d\n", startID); + assert(0 && "invalid failed edge"); #endif return; } - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) - { + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) { #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"NAV ERROR: tried to fail invalid waypoint %d\n", endID ); - assert(0&&"invalid failed edge"); + Com_Printf(S_COLOR_RED "NAV ERROR: tried to fail invalid waypoint %d\n", endID); + assert(0 && "invalid failed edge"); #endif return; } - //First see if we already have this one - if ( (j = EdgeFailed( startID, endID )) != -1 ) - { - //just remember this guy instead + // First see if we already have this one + if ((j = EdgeFailed(startID, endID)) != -1) { + // just remember this guy instead failedEdges[j].entID = entID; return; } - //Okay, new one, find an empty slot - for ( j = 0; j < MAX_FAILED_EDGES; j++ ) - { - if ( failedEdges[j].startID == WAYPOINT_NONE ) - { + // Okay, new one, find an empty slot + for (j = 0; j < MAX_FAILED_EDGES; j++) { + if (failedEdges[j].startID == WAYPOINT_NONE) { failedEdges[j].startID = startID; failedEdges[j].endID = endID; - //Check one second from now to see if it's clear - failedEdges[j].checkTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + // Check one second from now to see if it's clear + failedEdges[j].checkTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); m_edgeLookupMap.insert(std::pair(startID, j)); @@ -2022,10 +1782,10 @@ void CNavigator::AddFailedEdge( int entID, int startID, int endID ) } */ - //Remember who needed it + // Remember who needed it failedEdges[j].entID = entID; - //set the edge failed flags + // set the edge failed flags /* CNode *node = m_nodes[startID]; int edgeNum = node->GetEdgeNumToNode( endID ); @@ -2044,217 +1804,182 @@ void CNavigator::AddFailedEdge( int entID, int startID, int endID ) } */ - //stuff the index to this one in our lookup map + // stuff the index to this one in our lookup map - //now recalc all the paths! - if ( pathsCalculated ) - { - //reconnect the nodes and mark every node's flag NF_RECALC - //Com_Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", svs.time ); - SetEdgeCost( startID, endID, Q3_INFINITE ); - FlagAllNodes( NF_RECALC ); + // now recalc all the paths! + if (pathsCalculated) { + // reconnect the nodes and mark every node's flag NF_RECALC + // Com_Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", svs.time ); + SetEdgeCost(startID, endID, Q3_INFINITE); + FlagAllNodes(NF_RECALC); } return; } } #ifndef FINAL_BUILD - Com_Printf( S_COLOR_RED"NAV ERROR: too many blocked waypoint connections (%d)!!!\n", j ); + Com_Printf(S_COLOR_RED "NAV ERROR: too many blocked waypoint connections (%d)!!!\n", j); #endif } -qboolean CNavigator::CheckFailedEdge( failedEdge_t *failedEdge ) -{ - if ( !failedEdge ) - { +qboolean CNavigator::CheckFailedEdge(failedEdge_t *failedEdge) { + if (!failedEdge) { return qfalse; } - //Every 1 second, see if our failed edges are clear - if ( failedEdge->checkTime < svs.time ) - { - if ( failedEdge->startID != WAYPOINT_NONE ) - { - vec3_t start, end, mins, maxs; - int ignore, clipmask; - sharedEntity_t *ent = SV_GentityNum(failedEdge->entID); //(failedEdge->entIDentID]:NULL; - int hitEntNum; + // Every 1 second, see if our failed edges are clear + if (failedEdge->checkTime < svs.time) { + if (failedEdge->startID != WAYPOINT_NONE) { + vec3_t start, end, mins, maxs; + int ignore, clipmask; + sharedEntity_t *ent = SV_GentityNum(failedEdge->entID); //(failedEdge->entIDentID]:NULL; + int hitEntNum; - if ( !ent || /*!ent->inuse || !ent->client || ent->health <= 0*/ (ent->s.eType != ET_PLAYER && ent->s.eType != ET_NPC) || - (ent->s.eFlags & EF_DEAD)) - { - VectorSet( mins, -15, -15, DEFAULT_MINS_2+STEPSIZE ); - VectorSet( maxs, 15, 15, DEFAULT_MAXS_2 ); + if (!ent || /*!ent->inuse || !ent->client || ent->health <= 0*/ (ent->s.eType != ET_PLAYER && ent->s.eType != ET_NPC) || + (ent->s.eFlags & EF_DEAD)) { + VectorSet(mins, -15, -15, DEFAULT_MINS_2 + STEPSIZE); + VectorSet(maxs, 15, 15, DEFAULT_MAXS_2); ignore = ENTITYNUM_NONE; clipmask = MASK_NPCSOLID; - } - else - { - VectorCopy( ent->r.mins, mins ); + } else { + VectorCopy(ent->r.mins, mins); mins[2] += STEPSIZE; - VectorCopy( ent->r.maxs, maxs ); + VectorCopy(ent->r.maxs, maxs); ignore = failedEdge->entID; - clipmask = MASK_SOLID;//ent->clipmask; //rwwFIXMEFIXME: share clipmask? + clipmask = MASK_SOLID; // ent->clipmask; //rwwFIXMEFIXME: share clipmask? } - if ( maxs[2] < mins[2] ) - {//don't invert bounding box + if (maxs[2] < mins[2]) { // don't invert bounding box maxs[2] = mins[2]; } - m_nodes[failedEdge->startID]->GetPosition( start ); - m_nodes[failedEdge->endID]->GetPosition( end ); + m_nodes[failedEdge->startID]->GetPosition(start); + m_nodes[failedEdge->endID]->GetPosition(end); - //See if it's NAV_ClearPath... + // See if it's NAV_ClearPath... #if 0 hitEntNum = NAVNEW_ClearPathBetweenPoints( start, end, mins, maxs, ignore, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP );//NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? #else - trace_t trace; + trace_t trace; - //Test if they're even conceivably close to one another - if ( !SV_inPVS( start, end ) ) - { + // Test if they're even conceivably close to one another + if (!SV_inPVS(start, end)) { return qfalse; } - SV_Trace( &trace, start, mins, maxs, end, ignore, clipmask|CONTENTS_MONSTERCLIP|CONTENTS_BOTCLIP, qfalse, 0, 10 );//NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? + SV_Trace(&trace, start, mins, maxs, end, ignore, clipmask | CONTENTS_MONSTERCLIP | CONTENTS_BOTCLIP, qfalse, 0, + 10); // NOTE: should we really always include monsterclip (physically blocks NPCs) and botclip (do not enter)? - if( trace.startsolid == qtrue || trace.allsolid == qtrue ) - { + if (trace.startsolid == qtrue || trace.allsolid == qtrue) { return qfalse; } hitEntNum = trace.entityNum; #endif - //if we did hit something, see if it's just an auto-door and allow it - if ( hitEntNum != ENTITYNUM_NONE && GVM_NAV_EntIsUnlockedDoor( hitEntNum ) ) - { + // if we did hit something, see if it's just an auto-door and allow it + if (hitEntNum != ENTITYNUM_NONE && GVM_NAV_EntIsUnlockedDoor(hitEntNum)) { hitEntNum = ENTITYNUM_NONE; - } - else if ( hitEntNum == failedEdge->entID ) - {//don't hit the person who initially marked the edge failed + } else if (hitEntNum == failedEdge->entID) { // don't hit the person who initially marked the edge failed hitEntNum = ENTITYNUM_NONE; } - if ( hitEntNum == ENTITYNUM_NONE ) - { - //If so, clear it - ClearFailedEdge( failedEdge ); + if (hitEntNum == ENTITYNUM_NONE) { + // If so, clear it + ClearFailedEdge(failedEdge); return qtrue; - } - else - { - //Check again in one second - failedEdge->checkTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand( 0, 1000 ); + } else { + // Check again in one second + failedEdge->checkTime = svs.time + CHECK_FAILED_EDGE_INTERVAL + Q_irand(0, 1000); } } } return qfalse; } -void CNavigator::CheckAllFailedEdges( void ) -{ - failedEdge_t *failedEdge; - qboolean clearedAny = qfalse; +void CNavigator::CheckAllFailedEdges(void) { + failedEdge_t *failedEdge; + qboolean clearedAny = qfalse; - //Must have nodes - if ( m_nodes.size() == 0 ) + // Must have nodes + if (m_nodes.size() == 0) return; - for ( int j = 0; j < MAX_FAILED_EDGES; j++ ) - { + for (int j = 0; j < MAX_FAILED_EDGES; j++) { failedEdge = &failedEdges[j]; - clearedAny = CheckFailedEdge( failedEdge )?qtrue:clearedAny; + clearedAny = CheckFailedEdge(failedEdge) ? qtrue : clearedAny; } - if ( clearedAny ) - {//need to recalc the paths - if ( pathsCalculated ) - { - //reconnect the nodes and mark every node's flag NF_RECALC - //Com_Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", svs.time ); - FlagAllNodes( NF_RECALC ); + if (clearedAny) { // need to recalc the paths + if (pathsCalculated) { + // reconnect the nodes and mark every node's flag NF_RECALC + // Com_Printf( S_COLOR_CYAN"%d marking all nodes for recalc\n", svs.time ); + FlagAllNodes(NF_RECALC); } } } -qboolean CNavigator::RouteBlocked( int startID, int testEdgeID, int endID, int rejectRank ) -{ - int nextID, edgeID, lastID, bestNextID = NODE_NONE; - int bestRank = rejectRank; - int testRank; - qboolean allEdgesFailed; - CNode *end; - CNode *next; +qboolean CNavigator::RouteBlocked(int startID, int testEdgeID, int endID, int rejectRank) { + int nextID, edgeID, lastID, bestNextID = NODE_NONE; + int bestRank = rejectRank; + int testRank; + qboolean allEdgesFailed; + CNode *end; + CNode *next; - - if ( EdgeFailed( startID, testEdgeID ) != -1 ) - { + if (EdgeFailed(startID, testEdgeID) != -1) { return qtrue; } - if ( testEdgeID == endID ) - {//Neighbors, checked out, all clear + if (testEdgeID == endID) { // Neighbors, checked out, all clear return qfalse; } - //Okay, first edge is clear, now check rest of route! - end = m_nodes[ endID ]; + // Okay, first edge is clear, now check rest of route! + end = m_nodes[endID]; nextID = testEdgeID; lastID = startID; - while( 1 ) - { - next = m_nodes[ nextID ]; + while (1) { + next = m_nodes[nextID]; allEdgesFailed = qtrue; - for ( int i = 0; i < next->GetNumEdges(); i++ ) - { + for (int i = 0; i < next->GetNumEdges(); i++) { edgeID = next->GetEdge(i); - if ( edgeID == lastID ) - {//Don't backtrack + if (edgeID == lastID) { // Don't backtrack continue; } - if ( edgeID == startID ) - {//Don't loop around + if (edgeID == startID) { // Don't loop around continue; } - if ( EdgeFailed( nextID, edgeID ) != -1 ) - { - //This edge blocked, check next + if (EdgeFailed(nextID, edgeID) != -1) { + // This edge blocked, check next continue; } - if ( edgeID == endID ) - {//We got there all clear! + if (edgeID == endID) { // We got there all clear! return qfalse; } - //Still going... - testRank = end->GetRank( edgeID ); + // Still going... + testRank = end->GetRank(edgeID); - if ( testRank < 0 ) - {//No route this way + if (testRank < 0) { // No route this way continue; } - //Is the rank good enough? - if ( testRank < bestRank ) - { + // Is the rank good enough? + if (testRank < bestRank) { bestNextID = edgeID; bestRank = testRank; allEdgesFailed = qfalse; } } - if ( allEdgesFailed ) - { - //This route has no clear way of getting to end + if (allEdgesFailed) { + // This route has no clear way of getting to end return qtrue; - } - else - { + } else { lastID = nextID; nextID = bestNextID; } @@ -2267,96 +1992,80 @@ GetBestNodeAltRoute ------------------------- */ -int CNavigator::GetBestNodeAltRoute( int startID, int endID, int *pathCost, int rejectID ) -{ - //Must have nodes - if ( m_nodes.size() == 0 ) +int CNavigator::GetBestNodeAltRoute(int startID, int endID, int *pathCost, int rejectID) { + // Must have nodes + if (m_nodes.size() == 0) return WAYPOINT_NONE; - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Is it the same node? - if ( startID == endID ) - { - if ( !d_altRoutes->integer || EdgeFailed( startID, endID ) == -1 ) - { + // Is it the same node? + if (startID == endID) { + if (!d_altRoutes->integer || EdgeFailed(startID, endID) == -1) { return startID; - } - else - { + } else { return WAYPOINT_NONE; } } - CNode *start = m_nodes[ startID ]; + CNode *start = m_nodes[startID]; - int bestNode = -1; - int bestRank = Q3_INFINITE; - int testRank, rejectRank = Q3_INFINITE; - int bestCost = Q3_INFINITE; + int bestNode = -1; + int bestRank = Q3_INFINITE; + int testRank, rejectRank = Q3_INFINITE; + int bestCost = Q3_INFINITE; *pathCost = 0; - //Find the minimum rank of the edge(s) we want to reject as paths - if ( rejectID != WAYPOINT_NONE ) - { - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - if ( start->GetEdge(i) == rejectID ) - { - rejectRank = GetPathCost( startID, endID );//end->GetRank( start->GetEdge(i) ); + // Find the minimum rank of the edge(s) we want to reject as paths + if (rejectID != WAYPOINT_NONE) { + for (int i = 0; i < start->GetNumEdges(); i++) { + if (start->GetEdge(i) == rejectID) { + rejectRank = GetPathCost(startID, endID); // end->GetRank( start->GetEdge(i) ); break; } } } - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - testRank = GetPathCost( edgeID, endID );//end->GetRank( edgeID ); + testRank = GetPathCost(edgeID, endID); // end->GetRank( edgeID ); - //Make sure it's not worse than our reject rank - if ( testRank >= rejectRank ) + // Make sure it's not worse than our reject rank + if (testRank >= rejectRank) continue; - //Found one - if ( edgeID == endID ) - { - if ( !d_altRoutes->integer || !RouteBlocked( startID, edgeID, endID, rejectRank ) ) - { - *pathCost += start->GetEdgeCost( i ); + // Found one + if (edgeID == endID) { + if (!d_altRoutes->integer || !RouteBlocked(startID, edgeID, endID, rejectRank)) { + *pathCost += start->GetEdgeCost(i); return edgeID; - } - else - {//this is blocked, can't consider it + } else { // this is blocked, can't consider it continue; } } - //No possible connection - if ( testRank == NODE_NONE ) - { + // No possible connection + if (testRank == NODE_NONE) { *pathCost = Q3_INFINITE; return NODE_NONE; } - //Found a better one - if ( testRank < bestRank ) - { - //FIXME: make sure all the edges down from startID through edgeID to endID + // Found a better one + if (testRank < bestRank) { + // FIXME: make sure all the edges down from startID through edgeID to endID // does NOT include a failedEdge... - if ( !d_altRoutes->integer || !RouteBlocked( startID, edgeID, endID, rejectRank ) ) - { + if (!d_altRoutes->integer || !RouteBlocked(startID, edgeID, endID, rejectRank)) { bestNode = edgeID; bestRank = testRank; - bestCost = start->GetEdgeCost(i)+testRank; + bestCost = start->GetEdgeCost(i) + testRank; } } } @@ -2372,10 +2081,9 @@ overloaded so you don't have to pass a pathCost int pointer in ------------------------- */ -int CNavigator::GetBestNodeAltRoute( int startID, int endID, int rejectID ) -{ - int junk; - return GetBestNodeAltRoute( startID, endID, &junk, rejectID ); +int CNavigator::GetBestNodeAltRoute(int startID, int endID, int rejectID) { + int junk; + return GetBestNodeAltRoute(startID, endID, &junk, rejectID); } /* ------------------------- @@ -2383,59 +2091,53 @@ GetBestNode ------------------------- */ -int CNavigator::GetBestNode( int startID, int endID, int rejectID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +int CNavigator::GetBestNode(int startID, int endID, int rejectID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return WAYPOINT_NONE; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return WAYPOINT_NONE; - if ( startID == endID ) + if (startID == endID) return startID; - CNode *start = m_nodes[ startID ]; - CNode *end = m_nodes[ endID ]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - int bestNode = -1; - int bestRank = Q3_INFINITE; - int testRank, rejectRank = 0; + int bestNode = -1; + int bestRank = Q3_INFINITE; + int testRank, rejectRank = 0; - if ( rejectID != WAYPOINT_NONE ) - { - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - if ( start->GetEdge(i) == rejectID ) - { - rejectRank = end->GetRank( start->GetEdge(i) ); + if (rejectID != WAYPOINT_NONE) { + for (int i = 0; i < start->GetNumEdges(); i++) { + if (start->GetEdge(i) == rejectID) { + rejectRank = end->GetRank(start->GetEdge(i)); break; } } } - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - //Found one - if ( edgeID == endID ) + // Found one + if (edgeID == endID) return edgeID; - testRank = end->GetRank( edgeID ); + testRank = end->GetRank(edgeID); - //Found one - if ( testRank <= rejectRank ) + // Found one + if (testRank <= rejectRank) continue; - //No possible connection - if ( testRank == NODE_NONE ) + // No possible connection + if (testRank == NODE_NONE) return NODE_NONE; - //Found a better one - if ( testRank < bestRank ) - { + // Found a better one + if (testRank < bestRank) { bestNode = edgeID; bestRank = testRank; } @@ -2450,15 +2152,14 @@ GetNodePosition ------------------------- */ -int CNavigator::GetNodePosition( int nodeID, vec3_t out ) -{ - //Validate the number - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodePosition(int nodeID, vec3_t out) { + // Validate the number + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return false; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - node->GetPosition( out ); + node->GetPosition(out); return true; } @@ -2469,14 +2170,13 @@ GetNodeNumEdges ------------------------- */ -int CNavigator::GetNodeNumEdges( int nodeID ) -{ - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodeNumEdges(int nodeID) { + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return -1; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - assert( node ); + assert(node); return node->GetNumEdges(); } @@ -2487,16 +2187,15 @@ GetNodeEdge ------------------------- */ -int CNavigator::GetNodeEdge( int nodeID, int edge ) -{ - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetNodeEdge(int nodeID, int edge) { + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return -1; - CNode *node = m_nodes[ nodeID ]; + CNode *node = m_nodes[nodeID]; - assert( node ); + assert(node); - return node->GetEdge( edge ); + return node->GetEdge(edge); } /* @@ -2505,31 +2204,29 @@ Connected ------------------------- */ -bool CNavigator::Connected( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +bool CNavigator::Connected(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return false; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return false; - if ( startID == endID ) + if (startID == endID) return true; - CNode *start = m_nodes[ startID ]; - CNode *end = m_nodes[ endID ]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - for ( int i = 0; i < start->GetNumEdges(); i++ ) - { - int edgeID = start->GetEdge(i); + for (int i = 0; i < start->GetNumEdges(); i++) { + int edgeID = start->GetEdge(i); - //Found one - if ( edgeID == endID ) + // Found one + if (edgeID == endID) return true; - if ( ( end->GetRank( edgeID ) ) != NODE_NONE ) + if ((end->GetRank(edgeID)) != NODE_NONE) return true; } @@ -2542,78 +2239,70 @@ GetPathCost ------------------------- */ -unsigned int CNavigator::GetPathCost( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +unsigned int CNavigator::GetPathCost(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - CNode *startNode = m_nodes[ startID ]; + CNode *startNode = m_nodes[startID]; - if ( !startNode->GetNumEdges() ) - {//WTF? Solitary waypoint! Bad designer! - return Q3_INFINITE; // return 0; + if (!startNode->GetNumEdges()) { // WTF? Solitary waypoint! Bad designer! + return Q3_INFINITE; // return 0; } - CNode *endNode = m_nodes[ endID ]; + CNode *endNode = m_nodes[endID]; - CNode *moveNode = startNode; + CNode *moveNode = startNode; - int bestNode; - int pathCost = 0; - int bestCost; + int bestNode; + int pathCost = 0; + int bestCost; - int bestRank; - int testRank; + int bestRank; + int testRank; - int dontScrewUp = 0; + int dontScrewUp = 0; - //Draw out our path - while ( moveNode != endNode ) - { + // Draw out our path + while (moveNode != endNode) { bestRank = WORLD_SIZE; bestNode = -1; bestCost = 0; - for ( int i = 0; i < moveNode->GetNumEdges(); i++ ) - { - int edgeID = moveNode->GetEdge(i); + for (int i = 0; i < moveNode->GetNumEdges(); i++) { + int edgeID = moveNode->GetEdge(i); - //Done - if ( edgeID == endID ) - { - return pathCost + moveNode->GetEdgeCost( i ); + // Done + if (edgeID == endID) { + return pathCost + moveNode->GetEdgeCost(i); } - testRank = endNode->GetRank( edgeID ); + testRank = endNode->GetRank(edgeID); - //No possible connection - if ( testRank == NODE_NONE ) - { + // No possible connection + if (testRank == NODE_NONE) { return Q3_INFINITE; // return 0; } - //Found a better one - if ( testRank < bestRank ) - { + // Found a better one + if (testRank < bestRank) { bestNode = edgeID; bestRank = testRank; - bestCost = moveNode->GetEdgeCost( i ); + bestCost = moveNode->GetEdgeCost(i); } } pathCost += bestCost; - //Take a new best node - moveNode = m_nodes[ bestNode ]; + // Take a new best node + moveNode = m_nodes[bestNode]; dontScrewUp++; - if (dontScrewUp > 40000) - { //ok, I think something probably screwed up. + if (dontScrewUp > 40000) { // ok, I think something probably screwed up. break; } } @@ -2627,20 +2316,19 @@ GetEdgeCost ------------------------- */ -unsigned int CNavigator::GetEdgeCost( int startID, int endID ) -{ - //Validate the start position - if ( ( startID < 0 ) || ( startID >= (int)m_nodes.size() ) ) +unsigned int CNavigator::GetEdgeCost(int startID, int endID) { + // Validate the start position + if ((startID < 0) || (startID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - //Validate the end position - if ( ( endID < 0 ) || ( endID >= (int)m_nodes.size() ) ) + // Validate the end position + if ((endID < 0) || (endID >= (int)m_nodes.size())) return Q3_INFINITE; // return 0; - CNode *start = m_nodes[startID]; - CNode *end = m_nodes[endID]; + CNode *start = m_nodes[startID]; + CNode *end = m_nodes[endID]; - return GetEdgeCost( start, end ); + return GetEdgeCost(start, end); } /* @@ -2649,45 +2337,42 @@ GetProjectedNode ------------------------- */ -int CNavigator::GetProjectedNode( vec3_t origin, int nodeID ) -{ - //Validate the start position - if ( ( nodeID < 0 ) || ( nodeID >= (int)m_nodes.size() ) ) +int CNavigator::GetProjectedNode(vec3_t origin, int nodeID) { + // Validate the start position + if ((nodeID < 0) || (nodeID >= (int)m_nodes.size())) return NODE_NONE; - CNode *node = m_nodes[nodeID]; - CNode *tempNode; + CNode *node = m_nodes[nodeID]; + CNode *tempNode; - float bestDot = 0.0f; - int bestNode = NODE_NONE; + float bestDot = 0.0f; + int bestNode = NODE_NONE; - vec3_t targetDir, basePos, tempDir, tempPos; - float dot; + vec3_t targetDir, basePos, tempDir, tempPos; + float dot; - //Setup our target direction - node->GetPosition( basePos ); + // Setup our target direction + node->GetPosition(basePos); - VectorSubtract( origin, basePos, targetDir ); - VectorNormalize( targetDir ); + VectorSubtract(origin, basePos, targetDir); + VectorNormalize(targetDir); - //Go through all the edges - for ( int i = 0; i < node->GetNumEdges(); i++ ) - { + // Go through all the edges + for (int i = 0; i < node->GetNumEdges(); i++) { tempNode = m_nodes[node->GetEdge(i)]; - tempNode->GetPosition( tempPos ); + tempNode->GetPosition(tempPos); - VectorSubtract( tempPos, basePos, tempDir ); - VectorNormalize( tempDir ); //FIXME: Retain the length here if you want it + VectorSubtract(tempPos, basePos, tempDir); + VectorNormalize(tempDir); // FIXME: Retain the length here if you want it - dot = DotProduct( targetDir, tempDir ); + dot = DotProduct(targetDir, tempDir); - if ( dot < 0.0f ) + if (dot < 0.0f) continue; - if ( dot > bestDot ) - { - bestDot = dot; - bestNode = tempNode->GetID(); + if (dot > bestDot) { + bestDot = dot; + bestNode = tempNode->GetID(); } } @@ -2699,22 +2384,16 @@ int CNavigator::GetProjectedNode( vec3_t origin, int nodeID ) ////////////////////////////////////////////////////////////////// // Helper pop_mHeap algorithm class ////////////////////////////////////////////////////////////////// -class NodeTotalGreater -{ -public: - bool operator()( CEdge * first, CEdge * second ) const { - return( first->m_cost > second->m_cost ); - } +class NodeTotalGreater { + public: + bool operator()(CEdge *first, CEdge *second) const { return (first->m_cost > second->m_cost); } }; - ////////////////////////////////////////////////////////////////// // Destructor - Deallocate any remaining pointers in the queue ////////////////////////////////////////////////////////////////// -CPriorityQueue::~CPriorityQueue() -{ - while (!Empty()) - { +CPriorityQueue::~CPriorityQueue() { + while (!Empty()) { delete Pop(); } } @@ -2722,12 +2401,9 @@ CPriorityQueue::~CPriorityQueue() ////////////////////////////////////////////////////////////////// // Standard Iterative Search ////////////////////////////////////////////////////////////////// -CEdge* CPriorityQueue::Find(int npNum) -{ - for(std::vector::iterator HeapIter=mHeap.begin(); HeapIter!=mHeap.end(); ++HeapIter) - { - if ((*HeapIter)->m_first == npNum) - { +CEdge *CPriorityQueue::Find(int npNum) { + for (std::vector::iterator HeapIter = mHeap.begin(); HeapIter != mHeap.end(); ++HeapIter) { + if ((*HeapIter)->m_first == npNum) { return *HeapIter; } } @@ -2737,56 +2413,47 @@ CEdge* CPriorityQueue::Find(int npNum) ////////////////////////////////////////////////////////////////// // Remove Node And Resort ////////////////////////////////////////////////////////////////// -CEdge* CPriorityQueue::Pop() -{ - CEdge *edge = mHeap.front(); +CEdge *CPriorityQueue::Pop() { + CEdge *edge = mHeap.front(); - //pop_mHeap will move the node at the front to the position N - //and then sort the mHeap to make positions 1 through N-1 correct - //(STL makes no assumptions about your data and doesn't want to change - //the size of the container.) - std::pop_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater() ); + // pop_mHeap will move the node at the front to the position N + // and then sort the mHeap to make positions 1 through N-1 correct + //(STL makes no assumptions about your data and doesn't want to change + // the size of the container.) + std::pop_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater()); - //pop_back() will actually remove the last element from the mHeap - //now the mHeap is sorted for positions 1 through N - mHeap.pop_back(); + // pop_back() will actually remove the last element from the mHeap + // now the mHeap is sorted for positions 1 through N + mHeap.pop_back(); - return( edge ); + return (edge); } ////////////////////////////////////////////////////////////////// // Add New Node And Resort ////////////////////////////////////////////////////////////////// -void CPriorityQueue::Push(CEdge* theEdge ) -{ - //Pushes the node onto the back of the mHeap - mHeap.push_back( theEdge ); +void CPriorityQueue::Push(CEdge *theEdge) { + // Pushes the node onto the back of the mHeap + mHeap.push_back(theEdge); - //Sorts the new element into the mHeap - std::push_heap( mHeap.begin(), mHeap.end(), NodeTotalGreater() ); + // Sorts the new element into the mHeap + std::push_heap(mHeap.begin(), mHeap.end(), NodeTotalGreater()); } ////////////////////////////////////////////////////////////////// // Find The Node In Question And Resort mHeap Around It ////////////////////////////////////////////////////////////////// -void CPriorityQueue::Update( CEdge* edge ) -{ - for(std::vector::iterator i=mHeap.begin(); i!=mHeap.end(); ++i) - { - if( (*i)->m_first == edge->m_first ) - { //Found node - resort from this position in the mHeap - //(its total value was changed before this function was called) - std::push_heap( mHeap.begin(), i+1, NodeTotalGreater() ); - return; - } - } +void CPriorityQueue::Update(CEdge *edge) { + for (std::vector::iterator i = mHeap.begin(); i != mHeap.end(); ++i) { + if ((*i)->m_first == edge->m_first) { // Found node - resort from this position in the mHeap + //(its total value was changed before this function was called) + std::push_heap(mHeap.begin(), i + 1, NodeTotalGreater()); + return; + } + } } ////////////////////////////////////////////////////////////////// // Just a wrapper for stl empty function. ////////////////////////////////////////////////////////////////// -bool CPriorityQueue::Empty() -{ - return( mHeap.empty() ); -}; - +bool CPriorityQueue::Empty() { return (mHeap.empty()); }; diff --git a/codemp/server/sv_bot.cpp b/codemp/server/sv_bot.cpp index 3dfa473a63..d3909e3496 100644 --- a/codemp/server/sv_bot.cpp +++ b/codemp/server/sv_bot.cpp @@ -27,8 +27,7 @@ along with this program; if not, see . #include "qcommon/cm_public.h" #include "server/sv_gameapi.h" -typedef struct bot_debugpoly_s -{ +typedef struct bot_debugpoly_s { int inuse; int color; int numPoints; @@ -38,52 +37,44 @@ typedef struct bot_debugpoly_s static bot_debugpoly_t *debugpolygons; int bot_maxdebugpolys; -extern botlib_export_t *botlib_export; -int bot_enable; +extern botlib_export_t *botlib_export; +int bot_enable; static int gWPNum = 0; static wpobject_t *gWPArray[MAX_WPARRAY_SIZE]; -static int NotWithinRange(int base, int extent) -{ - if (extent > base && base+5 >= extent) - { +static int NotWithinRange(int base, int extent) { + if (extent > base && base + 5 >= extent) { return 0; } - if (extent < base && base-5 <= extent) - { + if (extent < base && base - 5 <= extent) { return 0; } return 1; } -int SV_OrgVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) -{ +int SV_OrgVisibleBox(vec3_t org1, vec3_t mins, vec3_t maxs, vec3_t org2, int ignore) { trace_t tr; - SV_Trace(&tr, org1, mins, maxs, org2, ignore, MASK_SOLID, 0, 0, 10); - if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) - { + if (tr.fraction == 1 && !tr.startsolid && !tr.allsolid) { return 1; } return 0; } -void *BotVMShift( intptr_t ptr ); +void *BotVMShift(intptr_t ptr); -void SV_BotWaypointReception(int wpnum, wpobject_t **wps) -{ +void SV_BotWaypointReception(int wpnum, wpobject_t **wps) { int i = 0; gWPNum = wpnum; - while (i < gWPNum) - { + while (i < gWPNum) { gWPArray[i] = wps[i]; i++; } @@ -94,8 +85,7 @@ void SV_BotWaypointReception(int wpnum, wpobject_t **wps) SV_BotCalculatePaths ================== */ -void SV_BotCalculatePaths( int /*rmg*/ ) -{ +void SV_BotCalculatePaths(int /*rmg*/) { int i; int c; int forceJumpable; @@ -104,8 +94,7 @@ void SV_BotCalculatePaths( int /*rmg*/ ) vec3_t a; vec3_t mins, maxs; - if (!gWPNum) - { + if (!gWPNum) { return; } @@ -114,17 +103,14 @@ void SV_BotCalculatePaths( int /*rmg*/ ) mins[2] = -15; //-1 maxs[0] = 15; maxs[1] = 15; - maxs[2] = 15; //1 + maxs[2] = 15; // 1 - //now clear out all the neighbor data before we recalculate + // now clear out all the neighbor data before we recalculate i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->neighbornum) - { - while (gWPArray[i]->neighbornum >= 0) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse && gWPArray[i]->neighbornum) { + while (gWPArray[i]->neighbornum >= 0) { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].num = 0; gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 0; gWPArray[i]->neighbornum--; @@ -137,40 +123,29 @@ void SV_BotCalculatePaths( int /*rmg*/ ) i = 0; - while (i < gWPNum) - { - if (gWPArray[i] && gWPArray[i]->inuse) - { + while (i < gWPNum) { + if (gWPArray[i] && gWPArray[i]->inuse) { c = 0; - while (c < gWPNum) - { - if (gWPArray[c] && gWPArray[c]->inuse && i != c && - NotWithinRange(i, c)) - { + while (c < gWPNum) { + if (gWPArray[c] && gWPArray[c]->inuse && i != c && NotWithinRange(i, c)) { VectorSubtract(gWPArray[i]->origin, gWPArray[c]->origin, a); nLDist = VectorLength(a); - forceJumpable = qfalse;//CanForceJumpTo(i, c, nLDist); + forceJumpable = qfalse; // CanForceJumpTo(i, c, nLDist); - if ((nLDist < maxNeighborDist || forceJumpable) && - ((int)gWPArray[i]->origin[2] == (int)gWPArray[c]->origin[2] || forceJumpable) && - (SV_OrgVisibleBox(gWPArray[i]->origin, mins, maxs, gWPArray[c]->origin, ENTITYNUM_NONE) || forceJumpable)) - { + if ((nLDist < maxNeighborDist || forceJumpable) && ((int)gWPArray[i]->origin[2] == (int)gWPArray[c]->origin[2] || forceJumpable) && + (SV_OrgVisibleBox(gWPArray[i]->origin, mins, maxs, gWPArray[c]->origin, ENTITYNUM_NONE) || forceJumpable)) { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].num = c; - if (forceJumpable && ((int)gWPArray[i]->origin[2] != (int)gWPArray[c]->origin[2] || nLDist < maxNeighborDist)) - { - gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 999;//forceJumpable; //FJSR - } - else - { + if (forceJumpable && ((int)gWPArray[i]->origin[2] != (int)gWPArray[c]->origin[2] || nLDist < maxNeighborDist)) { + gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 999; // forceJumpable; //FJSR + } else { gWPArray[i]->neighbors[gWPArray[i]->neighbornum].forceJumpTo = 0; } gWPArray[i]->neighbornum++; } - if (gWPArray[i]->neighbornum >= MAX_NEIGHBOR_SIZE) - { + if (gWPArray[i]->neighbornum >= MAX_NEIGHBOR_SIZE) { break; } } @@ -187,21 +162,21 @@ SV_BotAllocateClient ================== */ int SV_BotAllocateClient(void) { - int i; - client_t *cl; + int i; + client_t *cl; // find a client slot - for ( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) { - if ( cl->state == CS_FREE ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (cl->state == CS_FREE) { break; } } - if ( i == sv_maxclients->integer ) { + if (i == sv_maxclients->integer) { return -1; } - cl->gentity = SV_GentityNum( i ); + cl->gentity = SV_GentityNum(i); cl->gentity->s.number = i; cl->state = CS_ACTIVE; cl->lastPacketTime = svs.time; @@ -217,21 +192,21 @@ int SV_BotAllocateClient(void) { SV_BotFreeClient ================== */ -void SV_BotFreeClient( int clientNum ) { - client_t *cl; +void SV_BotFreeClient(int clientNum) { + client_t *cl; - if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { - Com_Error( ERR_DROP, "SV_BotFreeClient: bad clientNum: %i", clientNum ); + if (clientNum < 0 || clientNum >= sv_maxclients->integer) { + Com_Error(ERR_DROP, "SV_BotFreeClient: bad clientNum: %i", clientNum); } cl = &svs.clients[clientNum]; cl->state = CS_FREE; cl->name[0] = 0; - if ( cl->gentity ) { + if (cl->gentity) { cl->gentity->r.svFlags &= ~SVF_BOT; } - if ( cl->demo.demorecording ) { - SV_StopRecordDemo( cl ); + if (cl->demo.demorecording) { + SV_StopRecordDemo(cl); } } @@ -247,31 +222,38 @@ void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *poin if (!debugpolygons) return; - //bot debugging - if (!bot_debug) bot_debug = Cvar_Get("bot_debug", "0", 0); + // bot debugging + if (!bot_debug) + bot_debug = Cvar_Get("bot_debug", "0", 0); // if (bot_enable && bot_debug->integer) { - //show reachabilities - if (!bot_reachability) bot_reachability = Cvar_Get("bot_reachability", "0", 0); - //show ground faces only - if (!bot_groundonly) bot_groundonly = Cvar_Get("bot_groundonly", "1", 0); - //get the hightlight area - if (!bot_highlightarea) bot_highlightarea = Cvar_Get("bot_highlightarea", "0", 0); + // show reachabilities + if (!bot_reachability) + bot_reachability = Cvar_Get("bot_reachability", "0", 0); + // show ground faces only + if (!bot_groundonly) + bot_groundonly = Cvar_Get("bot_groundonly", "1", 0); + // get the hightlight area + if (!bot_highlightarea) + bot_highlightarea = Cvar_Get("bot_highlightarea", "0", 0); // parm0 = 0; - if (svs.clients[0].lastUsercmd.buttons & BUTTON_ATTACK) parm0 |= 1; - if (bot_reachability->integer) parm0 |= 2; - if (bot_groundonly->integer) parm0 |= 4; + if (svs.clients[0].lastUsercmd.buttons & BUTTON_ATTACK) + parm0 |= 1; + if (bot_reachability->integer) + parm0 |= 2; + if (bot_groundonly->integer) + parm0 |= 4; botlib_export->BotLibVarSet("bot_highlightarea", bot_highlightarea->string); - botlib_export->Test(parm0, NULL, svs.clients[0].gentity->r.currentOrigin, - svs.clients[0].gentity->r.currentAngles); - } //end if - //draw all debug polys + botlib_export->Test(parm0, NULL, svs.clients[0].gentity->r.currentOrigin, svs.clients[0].gentity->r.currentAngles); + } // end if + // draw all debug polys for (i = 0; i < bot_maxdebugpolys; i++) { poly = &debugpolygons[i]; - if (!poly->inuse) continue; - drawPoly(poly->color, poly->numPoints, (float *) poly->points); - //Com_Printf("poly %i, numpoints = %d\n", i, poly->numPoints); + if (!poly->inuse) + continue; + drawPoly(poly->color, poly->numPoints, (float *)poly->points); + // Com_Printf("poly %i, numpoints = %d\n", i, poly->numPoints); } } @@ -280,8 +262,7 @@ void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *poin BotImport_Print ================== */ -void QDECL BotImport_Print(int type, char *fmt, ...) -{ +void QDECL BotImport_Print(int type, char *fmt, ...) { char str[2048]; va_list ap; @@ -289,31 +270,31 @@ void QDECL BotImport_Print(int type, char *fmt, ...) Q_vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); - switch(type) { - case PRT_MESSAGE: { - Com_Printf("%s", str); - break; - } - case PRT_WARNING: { - Com_Printf(S_COLOR_YELLOW "Warning: %s", str); - break; - } - case PRT_ERROR: { - Com_Printf(S_COLOR_RED "Error: %s", str); - break; - } - case PRT_FATAL: { - Com_Printf(S_COLOR_RED "Fatal: %s", str); - break; - } - case PRT_EXIT: { - Com_Error(ERR_DROP, S_COLOR_RED "Exit: %s", str); - break; - } - default: { - Com_Printf("unknown print type\n"); - break; - } + switch (type) { + case PRT_MESSAGE: { + Com_Printf("%s", str); + break; + } + case PRT_WARNING: { + Com_Printf(S_COLOR_YELLOW "Warning: %s", str); + break; + } + case PRT_ERROR: { + Com_Printf(S_COLOR_RED "Error: %s", str); + break; + } + case PRT_FATAL: { + Com_Printf(S_COLOR_RED "Fatal: %s", str); + break; + } + case PRT_EXIT: { + Com_Error(ERR_DROP, S_COLOR_RED "Exit: %s", str); + break; + } + default: { + Com_Printf("unknown print type\n"); + break; + } } } @@ -326,7 +307,7 @@ void BotImport_Trace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec3_t ma trace_t trace; SV_Trace(&trace, start, mins, maxs, end, passent, contentmask, qfalse, 0, 10); - //copy the trace information + // copy the trace information bsptrace->allsolid = (qboolean)trace.allsolid; bsptrace->startsolid = (qboolean)trace.startsolid; bsptrace->fraction = trace.fraction; @@ -351,7 +332,7 @@ void BotImport_EntityTrace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec trace_t trace; SV_ClipToEntity(&trace, start, mins, maxs, end, entnum, contentmask, qfalse); - //copy the trace information + // copy the trace information bsptrace->allsolid = (qboolean)trace.allsolid; bsptrace->startsolid = (qboolean)trace.startsolid; bsptrace->fraction = trace.fraction; @@ -367,33 +348,26 @@ void BotImport_EntityTrace(bsp_trace_t *bsptrace, vec3_t start, vec3_t mins, vec bsptrace->contents = 0; } - /* ================== BotImport_PointContents ================== */ -int BotImport_PointContents(vec3_t point) { - return SV_PointContents(point, -1); -} +int BotImport_PointContents(vec3_t point) { return SV_PointContents(point, -1); } /* ================== BotImport_inPVS ================== */ -int BotImport_inPVS(vec3_t p1, vec3_t p2) { - return SV_inPVS (p1, p2); -} +int BotImport_inPVS(vec3_t p1, vec3_t p2) { return SV_inPVS(p1, p2); } /* ================== BotImport_BSPEntityData ================== */ -char *BotImport_BSPEntityData(void) { - return CM_EntityString(); -} +char *BotImport_BSPEntityData(void) { return CM_EntityString(); } /* ================== @@ -404,11 +378,11 @@ void BotImport_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t outmin clipHandle_t h; vec3_t mins, maxs; float max; - int i; + int i; h = CM_InlineModel(modelnum); CM_ModelBounds(h, mins, maxs); - //if the model is rotated + // if the model is rotated if ((angles[0] || angles[1] || angles[2])) { // expand for rotation @@ -418,9 +392,12 @@ void BotImport_BSPModelMinsMaxsOrigin(int modelnum, vec3_t angles, vec3_t outmin maxs[i] = max; } } - if (outmins) VectorCopy(mins, outmins); - if (outmaxs) VectorCopy(maxs, outmaxs); - if (origin) VectorClear(origin); + if (outmins) + VectorCopy(mins, outmins); + if (outmaxs) + VectorCopy(maxs, outmaxs); + if (origin) + VectorClear(origin); } /* @@ -431,7 +408,7 @@ BotImport_GetMemoryGame void *Bot_GetMemoryGame(int size) { void *ptr; - ptr = Z_Malloc( size, TAG_BOTGAME, qtrue ); + ptr = Z_Malloc(size, TAG_BOTGAME, qtrue); return ptr; } @@ -441,9 +418,7 @@ void *Bot_GetMemoryGame(int size) { BotImport_FreeMemoryGame ================== */ -void Bot_FreeMemoryGame(void *ptr) { - Z_Free(ptr); -} +void Bot_FreeMemoryGame(void *ptr) { Z_Free(ptr); } /* ================== @@ -453,7 +428,7 @@ BotImport_GetMemory void *BotImport_GetMemory(int size) { void *ptr; - ptr = Z_Malloc( size, TAG_BOTLIB, qtrue ); + ptr = Z_Malloc(size, TAG_BOTLIB, qtrue); return ptr; } @@ -462,20 +437,18 @@ void *BotImport_GetMemory(int size) { BotImport_FreeMemory ================== */ -void BotImport_FreeMemory(void *ptr) { - Z_Free(ptr); -} +void BotImport_FreeMemory(void *ptr) { Z_Free(ptr); } /* ================= BotImport_HunkAlloc ================= */ -void *BotImport_HunkAlloc( int size ) { - if( Hunk_CheckMark() ) { - Com_Error( ERR_DROP, "SV_Bot_HunkAlloc: Alloc with marks already set\n" ); +void *BotImport_HunkAlloc(int size) { + if (Hunk_CheckMark()) { + Com_Error(ERR_DROP, "SV_Bot_HunkAlloc: Alloc with marks already set\n"); } - return Hunk_Alloc( size, h_high ); + return Hunk_Alloc(size, h_high); } /* @@ -490,7 +463,7 @@ int BotImport_DebugPolygonCreate(int color, int numPoints, vec3_t *points) { if (!debugpolygons) return 0; - for (i = 1; i < bot_maxdebugpolys; i++) { + for (i = 1; i < bot_maxdebugpolys; i++) { if (!debugpolygons[i].inuse) break; } @@ -513,7 +486,8 @@ BotImport_DebugPolygonShow void BotImport_DebugPolygonShow(int id, int color, int numPoints, vec3_t *points) { bot_debugpoly_t *poly; - if (!debugpolygons) return; + if (!debugpolygons) + return; poly = &debugpolygons[id]; poly->inuse = qtrue; poly->color = color; @@ -526,9 +500,9 @@ void BotImport_DebugPolygonShow(int id, int color, int numPoints, vec3_t *points BotImport_DebugPolygonDelete ================== */ -void BotImport_DebugPolygonDelete(int id) -{ - if (!debugpolygons) return; +void BotImport_DebugPolygonDelete(int id) { + if (!debugpolygons) + return; debugpolygons[id].inuse = qfalse; } @@ -547,9 +521,7 @@ int BotImport_DebugLineCreate(void) { BotImport_DebugLineDelete ================== */ -void BotImport_DebugLineDelete(int line) { - BotImport_DebugPolygonDelete(line); -} +void BotImport_DebugLineDelete(int line) { BotImport_DebugPolygonDelete(line); } /* ================== @@ -562,17 +534,18 @@ void BotImport_DebugLineShow(int line, vec3_t start, vec3_t end, int color) { VectorCopy(start, points[0]); VectorCopy(start, points[1]); - //points[1][2] -= 2; + // points[1][2] -= 2; VectorCopy(end, points[2]); - //points[2][2] -= 2; + // points[2][2] -= 2; VectorCopy(end, points[3]); - VectorSubtract(end, start, dir); VectorNormalize(dir); dot = DotProduct(dir, up); - if (dot > 0.99 || dot < -0.99) VectorSet(cross, 1, 0, 0); - else CrossProduct(dir, up, cross); + if (dot > 0.99 || dot < -0.99) + VectorSet(cross, 1, 0, 0); + else + CrossProduct(dir, up, cross); VectorNormalize(cross); @@ -589,22 +562,20 @@ void BotImport_DebugLineShow(int line, vec3_t start, vec3_t end, int color) { SV_BotClientCommand ================== */ -void BotClientCommand( int client, char *command ) { - SV_ExecuteClientCommand( &svs.clients[client], command, qtrue ); -} +void BotClientCommand(int client, char *command) { SV_ExecuteClientCommand(&svs.clients[client], command, qtrue); } /* ================== SV_BotFrame ================== */ -void SV_BotFrame( int time ) { +void SV_BotFrame(int time) { if (!bot_enable) return; - //NOTE: maybe the game is already shutdown + // NOTE: maybe the game is already shutdown if (!svs.gameStarted) return; - GVM_BotAIStartFrame( time ); + GVM_BotAIStartFrame(time); } /* @@ -612,13 +583,13 @@ void SV_BotFrame( int time ) { SV_BotLibSetup =============== */ -int SV_BotLibSetup( void ) { +int SV_BotLibSetup(void) { if (!bot_enable) { return 0; } - if ( !botlib_export ) { - Com_Printf( S_COLOR_RED "Error: SV_BotLibSetup without SV_BotInitBotLib\n" ); + if (!botlib_export) { + Com_Printf(S_COLOR_RED "Error: SV_BotLibSetup without SV_BotInitBotLib\n"); return -1; } @@ -633,9 +604,9 @@ Called when either the entire server is being killed, or it is changing to a different game directory. =============== */ -int SV_BotLibShutdown( void ) { +int SV_BotLibShutdown(void) { - if ( !botlib_export ) { + if (!botlib_export) { return -1; } @@ -649,48 +620,47 @@ SV_BotInitCvars */ void SV_BotInitCvars(void) { - Cvar_Get("bot_enable", "1", 0); //enable the bot - Cvar_Get("bot_developer", "0", CVAR_CHEAT); //bot developer mode - Cvar_Get("bot_debug", "0", CVAR_CHEAT); //enable bot debugging - Cvar_Get("bot_maxdebugpolys", "2", 0); //maximum number of debug polys - Cvar_Get("bot_groundonly", "1", 0); //only show ground faces of areas - Cvar_Get("bot_reachability", "0", 0); //show all reachabilities to other areas - Cvar_Get("bot_visualizejumppads", "0", CVAR_CHEAT); //show jumppads - Cvar_Get("bot_forceclustering", "0", 0); //force cluster calculations - Cvar_Get("bot_forcereachability", "0", 0); //force reachability calculations - Cvar_Get("bot_forcewrite", "0", 0); //force writing aas file - Cvar_Get("bot_aasoptimize", "0", 0); //no aas file optimisation - Cvar_Get("bot_saveroutingcache", "0", 0); //save routing cache - Cvar_Get("bot_thinktime", "100", CVAR_CHEAT); //msec the bots thinks - Cvar_Get("bot_reloadcharacters", "0", 0); //reload the bot characters each time - Cvar_Get("bot_testichat", "0", 0); //test ichats - Cvar_Get("bot_testrchat", "0", 0); //test rchats - Cvar_Get("bot_testsolid", "0", CVAR_CHEAT); //test for solid areas - Cvar_Get("bot_testclusters", "0", CVAR_CHEAT); //test the AAS clusters - Cvar_Get("bot_fastchat", "0", 0); //fast chatting bots - Cvar_Get("bot_nochat", "0", 0); //disable chats - Cvar_Get("bot_pause", "0", CVAR_CHEAT); //pause the bots thinking - Cvar_Get("bot_report", "0", CVAR_CHEAT); //get a full report in ctf - Cvar_Get("bot_grapple", "0", 0); //enable grapple - Cvar_Get("bot_rocketjump", "1", 0); //enable rocket jumping - Cvar_Get("bot_challenge", "0", 0); //challenging bot - Cvar_Get("bot_minplayers", "0", 0); //minimum players in a team or the game - Cvar_Get("bot_interbreedchar", "", CVAR_CHEAT); //bot character used for interbreeding - Cvar_Get("bot_interbreedbots", "10", CVAR_CHEAT); //number of bots used for interbreeding - Cvar_Get("bot_interbreedcycle", "20", CVAR_CHEAT); //bot interbreeding cycle - Cvar_Get("bot_interbreedwrite", "", CVAR_CHEAT); //write interbreeded bots to this file -} - -extern botlib_export_t *GetBotLibAPI( int apiVersion, botlib_import_t *import ); + Cvar_Get("bot_enable", "1", 0); // enable the bot + Cvar_Get("bot_developer", "0", CVAR_CHEAT); // bot developer mode + Cvar_Get("bot_debug", "0", CVAR_CHEAT); // enable bot debugging + Cvar_Get("bot_maxdebugpolys", "2", 0); // maximum number of debug polys + Cvar_Get("bot_groundonly", "1", 0); // only show ground faces of areas + Cvar_Get("bot_reachability", "0", 0); // show all reachabilities to other areas + Cvar_Get("bot_visualizejumppads", "0", CVAR_CHEAT); // show jumppads + Cvar_Get("bot_forceclustering", "0", 0); // force cluster calculations + Cvar_Get("bot_forcereachability", "0", 0); // force reachability calculations + Cvar_Get("bot_forcewrite", "0", 0); // force writing aas file + Cvar_Get("bot_aasoptimize", "0", 0); // no aas file optimisation + Cvar_Get("bot_saveroutingcache", "0", 0); // save routing cache + Cvar_Get("bot_thinktime", "100", CVAR_CHEAT); // msec the bots thinks + Cvar_Get("bot_reloadcharacters", "0", 0); // reload the bot characters each time + Cvar_Get("bot_testichat", "0", 0); // test ichats + Cvar_Get("bot_testrchat", "0", 0); // test rchats + Cvar_Get("bot_testsolid", "0", CVAR_CHEAT); // test for solid areas + Cvar_Get("bot_testclusters", "0", CVAR_CHEAT); // test the AAS clusters + Cvar_Get("bot_fastchat", "0", 0); // fast chatting bots + Cvar_Get("bot_nochat", "0", 0); // disable chats + Cvar_Get("bot_pause", "0", CVAR_CHEAT); // pause the bots thinking + Cvar_Get("bot_report", "0", CVAR_CHEAT); // get a full report in ctf + Cvar_Get("bot_grapple", "0", 0); // enable grapple + Cvar_Get("bot_rocketjump", "1", 0); // enable rocket jumping + Cvar_Get("bot_challenge", "0", 0); // challenging bot + Cvar_Get("bot_minplayers", "0", 0); // minimum players in a team or the game + Cvar_Get("bot_interbreedchar", "", CVAR_CHEAT); // bot character used for interbreeding + Cvar_Get("bot_interbreedbots", "10", CVAR_CHEAT); // number of bots used for interbreeding + Cvar_Get("bot_interbreedcycle", "20", CVAR_CHEAT); // bot interbreeding cycle + Cvar_Get("bot_interbreedwrite", "", CVAR_CHEAT); // write interbreeded bots to this file +} + +extern botlib_export_t *GetBotLibAPI(int apiVersion, botlib_import_t *import); // there's no such thing as this now, since the zone is unlimited, but I have to provide something // so it doesn't run out of control alloc-wise (since the bot code calls this in a while() loop to free // up bot mem until zone has > 1MB available again. So, simulate a reasonable limit... // -static int bot_Z_AvailableMemory(void) -{ - const int iMaxBOTLIBMem = 8 * 1024 * 1024; // adjust accordingly. - return iMaxBOTLIBMem - Z_MemSize( TAG_BOTLIB ); +static int bot_Z_AvailableMemory(void) { + const int iMaxBOTLIBMem = 8 * 1024 * 1024; // adjust accordingly. + return iMaxBOTLIBMem - Z_MemSize(TAG_BOTLIB); } /* @@ -699,9 +669,10 @@ SV_BotInitBotLib ================== */ void SV_BotInitBotLib(void) { - botlib_import_t botlib_import; + botlib_import_t botlib_import; - if (debugpolygons) Z_Free(debugpolygons); + if (debugpolygons) + Z_Free(debugpolygons); bot_maxdebugpolys = Cvar_VariableIntegerValue("bot_maxdebugpolys"); debugpolygons = (struct bot_debugpoly_s *)Z_Malloc(sizeof(bot_debugpoly_t) * bot_maxdebugpolys, TAG_BOTLIB, qtrue); @@ -714,10 +685,10 @@ void SV_BotInitBotLib(void) { botlib_import.BSPModelMinsMaxsOrigin = BotImport_BSPModelMinsMaxsOrigin; botlib_import.BotClientCommand = BotClientCommand; - //memory management + // memory management botlib_import.GetMemory = BotImport_GetMemory; botlib_import.FreeMemory = BotImport_FreeMemory; - botlib_import.AvailableMemory = bot_Z_AvailableMemory; //Z_AvailableMemory; + botlib_import.AvailableMemory = bot_Z_AvailableMemory; // Z_AvailableMemory; botlib_import.HunkAlloc = BotImport_HunkAlloc; // file system access @@ -727,20 +698,19 @@ void SV_BotInitBotLib(void) { botlib_import.FS_FCloseFile = FS_FCloseFile; botlib_import.FS_Seek = FS_Seek; - //debug lines + // debug lines botlib_import.DebugLineCreate = BotImport_DebugLineCreate; botlib_import.DebugLineDelete = BotImport_DebugLineDelete; botlib_import.DebugLineShow = BotImport_DebugLineShow; - //debug polygons + // debug polygons botlib_import.DebugPolygonCreate = BotImport_DebugPolygonCreate; botlib_import.DebugPolygonDelete = BotImport_DebugPolygonDelete; - botlib_export = (botlib_export_t *)GetBotLibAPI( BOTLIB_API_VERSION, &botlib_import ); + botlib_export = (botlib_export_t *)GetBotLibAPI(BOTLIB_API_VERSION, &botlib_import); assert(botlib_export); } - // // * * * BOT AI CODE IS BELOW THIS POINT * * * // @@ -750,26 +720,25 @@ void SV_BotInitBotLib(void) { SV_BotGetConsoleMessage ================== */ -int SV_BotGetConsoleMessage( int client, char *buf, int size ) -{ - client_t *cl; - int index; +int SV_BotGetConsoleMessage(int client, char *buf, int size) { + client_t *cl; + int index; cl = &svs.clients[client]; cl->lastPacketTime = svs.time; - if ( cl->reliableAcknowledge == cl->reliableSequence ) { + if (cl->reliableAcknowledge == cl->reliableSequence) { return qfalse; } cl->reliableAcknowledge++; - index = cl->reliableAcknowledge & ( MAX_RELIABLE_COMMANDS - 1 ); + index = cl->reliableAcknowledge & (MAX_RELIABLE_COMMANDS - 1); - if ( !cl->reliableCommands[index][0] ) { + if (!cl->reliableCommands[index][0]) { return qfalse; } - Q_strncpyz( buf, cl->reliableCommands[index], size ); + Q_strncpyz(buf, cl->reliableCommands[index], size); return qtrue; } @@ -800,9 +769,9 @@ int EntityInPVS( int client, int entityNum ) { SV_BotGetSnapshotEntity ================== */ -int SV_BotGetSnapshotEntity( int client, int sequence ) { - client_t *cl; - clientSnapshot_t *frame; +int SV_BotGetSnapshotEntity(int client, int sequence) { + client_t *cl; + clientSnapshot_t *frame; cl = &svs.clients[client]; frame = &cl->frames[cl->netchan.outgoingSequence & PACKET_MASK]; @@ -811,4 +780,3 @@ int SV_BotGetSnapshotEntity( int client, int sequence ) { } return svs.snapshotEntities[(frame->first_entity + sequence) % svs.numSnapshotEntities].number; } - diff --git a/codemp/server/sv_ccmds.cpp b/codemp/server/sv_ccmds.cpp index 47c2deb879..bc27a8600a 100644 --- a/codemp/server/sv_ccmds.cpp +++ b/codemp/server/sv_ccmds.cpp @@ -36,14 +36,13 @@ These commands can only be entered from stdin or by a remote operator datagram =============================================================================== */ -const char *SV_GetStringEdString(char *refSection, char *refName) -{ - //Well, it would've been lovely doing it the above way, but it would mean mixing - //languages for the client depending on what the server is. So we'll mark this as - //a stringed reference with @@@ and send the refname to the client, and when it goes - //to print it will get scanned for the stringed reference indication and dealt with - //properly. - static char text[1024]={0}; +const char *SV_GetStringEdString(char *refSection, char *refName) { + // Well, it would've been lovely doing it the above way, but it would mean mixing + // languages for the client depending on what the server is. So we'll mark this as + // a stringed reference with @@@ and send the refname to the client, and when it goes + // to print it will get scanned for the stringed reference indication and dealt with + // properly. + static char text[1024] = {0}; Com_sprintf(text, sizeof(text), "@@@%s", refName); return text; } @@ -55,59 +54,58 @@ SV_GetPlayerByHandle Returns the player with player id or name from Cmd_Argv(1) ================== */ -static client_t *SV_GetPlayerByHandle( void ) { - client_t *cl; - int i; - char *s; - char cleanName[64]; +static client_t *SV_GetPlayerByHandle(void) { + client_t *cl; + int i; + char *s; + char cleanName[64]; // make sure server is running - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return NULL; } - if ( Cmd_Argc() < 2 ) { - Com_Printf( "No player specified.\n" ); + if (Cmd_Argc() < 2) { + Com_Printf("No player specified.\n"); return NULL; } s = Cmd_Argv(1); // Check whether this is a numeric player handle - for(i = 0; s[i] >= '0' && s[i] <= '9'; i++); + for (i = 0; s[i] >= '0' && s[i] <= '9'; i++) + ; - if(!s[i]) - { + if (!s[i]) { int plid = atoi(s); // Check for numeric playerid match - if(plid >= 0 && plid < sv_maxclients->integer) - { + if (plid >= 0 && plid < sv_maxclients->integer) { cl = &svs.clients[plid]; - if(cl->state) + if (cl->state) return cl; } } // check for a name match - for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) { - if ( !cl->state ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if ( !Q_stricmp( cl->name, s ) ) { + if (!Q_stricmp(cl->name, s)) { return cl; } - Q_strncpyz( cleanName, cl->name, sizeof(cleanName) ); - Q_StripColor( cleanName ); - //Q_CleanStr( cleanName ); - if ( !Q_stricmp( cleanName, s ) ) { + Q_strncpyz(cleanName, cl->name, sizeof(cleanName)); + Q_StripColor(cleanName); + // Q_CleanStr( cleanName ); + if (!Q_stricmp(cleanName, s)) { return cl; } } - Com_Printf( "Player %s is not on the server\n", s ); + Com_Printf("Player %s is not on the server\n", s); return NULL; } @@ -119,19 +117,19 @@ SV_GetPlayerByNum Returns the player with idnum from Cmd_Argv(1) ================== */ -static client_t *SV_GetPlayerByNum( void ) { - client_t *cl; - int i; - int idnum; - char *s; +static client_t *SV_GetPlayerByNum(void) { + client_t *cl; + int i; + int idnum; + char *s; // make sure server is running - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return NULL; } - if ( Cmd_Argc() < 2 ) { - Com_Printf( "No player specified.\n" ); + if (Cmd_Argc() < 2) { + Com_Printf("No player specified.\n"); return NULL; } @@ -139,19 +137,19 @@ static client_t *SV_GetPlayerByNum( void ) { for (i = 0; s[i]; i++) { if (s[i] < '0' || s[i] > '9') { - Com_Printf( "Bad slot number: %s\n", s); + Com_Printf("Bad slot number: %s\n", s); return NULL; } } - idnum = atoi( s ); - if ( idnum < 0 || idnum >= sv_maxclients->integer ) { - Com_Printf( "Bad client slot: %i\n", idnum ); + idnum = atoi(s); + if (idnum < 0 || idnum >= sv_maxclients->integer) { + Com_Printf("Bad client slot: %i\n", idnum); return NULL; } cl = &svs.clients[idnum]; - if ( !cl->state ) { - Com_Printf( "Client %i is not active\n", idnum ); + if (!cl->state) { + Com_Printf("Client %i is not active\n", idnum); return NULL; } return cl; @@ -166,33 +164,33 @@ SV_Map_f Restart the server on a different map ================== */ -static void SV_Map_f( void ) { - char *cmd = NULL, *map = NULL; - qboolean killBots=qfalse, cheat=qfalse; - char expanded[MAX_QPATH] = {0}, mapname[MAX_QPATH] = {0}; +static void SV_Map_f(void) { + char *cmd = NULL, *map = NULL; + qboolean killBots = qfalse, cheat = qfalse; + char expanded[MAX_QPATH] = {0}, mapname[MAX_QPATH] = {0}; map = Cmd_Argv(1); - if ( !map ) + if (!map) return; // make sure the level exists before trying to change, so that // a typo at the server console won't end the game - if (strchr (map, '\\') ) { - Com_Printf ("Can't have mapnames with a \\\n"); + if (strchr(map, '\\')) { + Com_Printf("Can't have mapnames with a \\\n"); return; } - Com_sprintf (expanded, sizeof(expanded), "maps/%s.bsp", map); - if ( FS_ReadFile (expanded, NULL) == -1 ) { - Com_Printf ("Can't find map %s\n", expanded); + Com_sprintf(expanded, sizeof(expanded), "maps/%s.bsp", map); + if (FS_ReadFile(expanded, NULL) == -1) { + Com_Printf("Can't find map %s\n", expanded); return; } // force latched values to get set - Cvar_Get ("g_gametype", "0", CVAR_SERVERINFO | CVAR_LATCH ); + Cvar_Get("g_gametype", "0", CVAR_SERVERINFO | CVAR_LATCH); cmd = Cmd_Argv(0); - if ( !Q_stricmpn( cmd, "devmap", 6 ) ) { + if (!Q_stricmpn(cmd, "devmap", 6)) { cheat = qtrue; killBots = qtrue; } else { @@ -204,31 +202,28 @@ static void SV_Map_f( void ) { // and thus nuke the arguments of the map command Q_strncpyz(mapname, map, sizeof(mapname)); - ForceReload_e eForceReload = eForceReload_NOTHING; // default for normal load + ForceReload_e eForceReload = eForceReload_NOTHING; // default for normal load -// if ( !Q_stricmp( cmd, "devmapbsp") ) { // not relevant in MP codebase -// eForceReload = eForceReload_BSP; -// } -// else - if ( !Q_stricmp( cmd, "devmapmdl") ) { + // if ( !Q_stricmp( cmd, "devmapbsp") ) { // not relevant in MP codebase + // eForceReload = eForceReload_BSP; + // } + // else + if (!Q_stricmp(cmd, "devmapmdl")) { eForceReload = eForceReload_MODELS; - } - else - if ( !Q_stricmp( cmd, "devmapall") ) { + } else if (!Q_stricmp(cmd, "devmapall")) { eForceReload = eForceReload_ALL; } // start up the map - SV_SpawnServer( mapname, killBots, eForceReload ); + SV_SpawnServer(mapname, killBots, eForceReload); // set the cheat value // if the level was started with "map ", then // cheats will not be allowed. If started with "devmap " // then cheats will be allowed - Cvar_Set( "sv_cheats", cheat ? "1" : "0" ); + Cvar_Set("sv_cheats", cheat ? "1" : "0"); } - /* ================ SV_MapRestart_f @@ -237,50 +232,49 @@ Completely restarts a level, but doesn't send a new gamestate to the clients. This allows fair starts with variable load times. ================ */ -static void SV_MapRestart_f( void ) { - int i; - client_t *client; - char *denied; - qboolean isBot; - int delay; +static void SV_MapRestart_f(void) { + int i; + client_t *client; + char *denied; + qboolean isBot; + int delay; // make sure we aren't restarting twice in the same frame - if ( com_frameTime == sv.serverId ) { + if (com_frameTime == sv.serverId) { return; } // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( sv.restartTime ) { + if (sv.restartTime) { return; } - if (Cmd_Argc() > 1 ) { - delay = atoi( Cmd_Argv(1) ); - } - else { + if (Cmd_Argc() > 1) { + delay = atoi(Cmd_Argv(1)); + } else { delay = 5; } - if( delay ) { + if (delay) { sv.restartTime = sv.time + delay * 1000; - SV_SetConfigstring( CS_WARMUP, va("%i", sv.restartTime) ); + SV_SetConfigstring(CS_WARMUP, va("%i", sv.restartTime)); return; } // check for changes in variables that can't just be restarted // check for maxclients change - if ( sv_maxclients->modified || sv_gametype->modified ) { - char mapname[MAX_QPATH]; + if (sv_maxclients->modified || sv_gametype->modified) { + char mapname[MAX_QPATH]; - Com_Printf( "variable change -- restarting.\n" ); + Com_Printf("variable change -- restarting.\n"); // restart the map the slow way - Q_strncpyz( mapname, Cvar_VariableString( "mapname" ), sizeof( mapname ) ); + Q_strncpyz(mapname, Cvar_VariableString("mapname"), sizeof(mapname)); - SV_SpawnServer( mapname, qfalse, eForceReload_NOTHING ); + SV_SpawnServer(mapname, qfalse, eForceReload_NOTHING); return; } @@ -293,15 +287,15 @@ static void SV_MapRestart_f( void ) { // generate a new serverid // TTimo - don't update restartedserverId there, otherwise we won't deal correctly with multiple map_restart sv.serverId = com_frameTime; - Cvar_Set( "sv_serverid", va("%i", sv.serverId ) ); + Cvar_Set("sv_serverid", va("%i", sv.serverId)); - time( &sv.realMapTimeStarted ); + time(&sv.realMapTimeStarted); sv.demosPruned = qfalse; // if a map_restart occurs while a client is changing maps, we need // to give them the correct time so that when they finish loading // they don't violate the backwards time check in cl_cgame.c - for (i=0 ; iinteger ; i++) { + for (i = 0; i < sv_maxclients->integer; i++) { if (svs.clients[i].state == CS_PRIMED) { svs.clients[i].oldServerTime = sv.restartTime; } @@ -316,8 +310,8 @@ static void SV_MapRestart_f( void ) { SV_RestartGame(); // run a few frames to allow everything to settle - for ( i = 0 ;i < 3 ; i++ ) { - GVM_RunFrame( sv.time ); + for (i = 0; i < 3; i++) { + GVM_RunFrame(sv.time); sv.time += 100; svs.time += 100; } @@ -326,37 +320,36 @@ static void SV_MapRestart_f( void ) { sv.restarting = qfalse; // connect and begin all the clients - for (i=0 ; iinteger ; i++) { + for (i = 0; i < sv_maxclients->integer; i++) { client = &svs.clients[i]; // send the new gamestate to all connected clients - if ( client->state < CS_CONNECTED) { + if (client->state < CS_CONNECTED) { continue; } - if ( client->netchan.remoteAddress.type == NA_BOT ) { + if (client->netchan.remoteAddress.type == NA_BOT) { isBot = qtrue; } else { isBot = qfalse; } // add the map_restart command - SV_AddServerCommand( client, "map_restart\n" ); + SV_AddServerCommand(client, "map_restart\n"); // connect the client again, without the firstTime flag - denied = GVM_ClientConnect( i, qfalse, isBot ); - if ( denied ) { + denied = GVM_ClientConnect(i, qfalse, isBot); + if (denied) { // this generally shouldn't happen, because the client // was connected before the level change - SV_DropClient( client, denied ); - Com_Printf( "SV_MapRestart_f(%d): dropped client %i - denied!\n", delay, i ); + SV_DropClient(client, denied); + Com_Printf("SV_MapRestart_f(%d): dropped client %i - denied!\n", delay, i); continue; } - if(client->state == CS_ACTIVE) + if (client->state == CS_ACTIVE) SV_ClientEnterWorld(client, &client->lastUsercmd); - else - { + else { // If we don't reset client->lastUsercmd and are restarting during map load, // the client will hang because we'll use the last Usercmd from the previous map, // which is wrong obviously. @@ -365,7 +358,7 @@ static void SV_MapRestart_f( void ) { } // run another frame to allow things to look at all the players - GVM_RunFrame( sv.time ); + GVM_RunFrame(sv.time); sv.time += 100; svs.time += 100; @@ -379,36 +372,36 @@ static void SV_MapRestart_f( void ) { SV_KickBlankPlayers ================== */ -static void SV_KickBlankPlayers( void ) { - client_t *cl; - int i; - char cleanName[64]; +static void SV_KickBlankPlayers(void) { + client_t *cl; + int i; + char cleanName[64]; // make sure server is running - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return; } // check for a name match - for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) { - if ( !cl->state ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) { + if (cl->netchan.remoteAddress.type == NA_LOOPBACK) { continue; } - if ( !Q_stricmp( cl->name, "" ) ) { - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + if (!Q_stricmp(cl->name, "")) { + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie continue; } - Q_strncpyz( cleanName, cl->name, sizeof(cleanName) ); - Q_StripColor( cleanName ); - //Q_CleanStr( cleanName ); - if ( !Q_stricmp( cleanName, "" ) ) { - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + Q_strncpyz(cleanName, cl->name, sizeof(cleanName)); + Q_StripColor(cleanName); + // Q_CleanStr( cleanName ); + if (!Q_stricmp(cleanName, "")) { + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } } } @@ -420,61 +413,59 @@ SV_Kick_f Kick a user off of the server ================== */ -static void SV_Kick_f( void ) { - client_t *cl; - int i; +static void SV_Kick_f(void) { + client_t *cl; + int i; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) { - Com_Printf ("Usage: kick \nkick all = kick everyone\nkick allbots = kick all bots\n"); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: kick \nkick all = kick everyone\nkick allbots = kick all bots\n"); return; } - if (!Q_stricmp(Cmd_Argv(1), "Padawan")) - { //if you try to kick the default name, also try to kick "" + if (!Q_stricmp(Cmd_Argv(1), "Padawan")) { // if you try to kick the default name, also try to kick "" SV_KickBlankPlayers(); } cl = SV_GetPlayerByHandle(); - if ( !cl ) { - if ( !Q_stricmp(Cmd_Argv(1), "all") ) { - for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) { - if ( !cl->state ) { + if (!cl) { + if (!Q_stricmp(Cmd_Argv(1), "all")) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) { + if (cl->netchan.remoteAddress.type == NA_LOOPBACK) { continue; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } - } - else if ( !Q_stricmp(Cmd_Argv(1), "allbots") ) { - for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++ ) { - if ( !cl->state ) { + } else if (!Q_stricmp(Cmd_Argv(1), "allbots")) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if( cl->netchan.remoteAddress.type != NA_BOT ) { + if (cl->netchan.remoteAddress.type != NA_BOT) { continue; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } } return; } - if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) { + if (cl->netchan.remoteAddress.type == NA_LOOPBACK) { Com_Printf("Cannot kick host player\n"); return; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } /* @@ -484,27 +475,27 @@ SV_KickBots_f Kick all bots off of the server ================== */ -static void SV_KickBots_f( void ) { - client_t *cl; - int i; +static void SV_KickBots_f(void) { + client_t *cl; + int i; // make sure server is running - if( !com_sv_running->integer ) { + if (!com_sv_running->integer) { Com_Printf("Server is not running.\n"); return; } - for( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) { - if( !cl->state ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if( cl->netchan.remoteAddress.type != NA_BOT ) { + if (cl->netchan.remoteAddress.type != NA_BOT) { continue; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } } /* @@ -514,27 +505,27 @@ SV_KickAll_f Kick all users off of the server ================== */ -static void SV_KickAll_f( void ) { +static void SV_KickAll_f(void) { client_t *cl; int i; // make sure server is running - if( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - for( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ ) { - if( !cl->state ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) { + if (cl->netchan.remoteAddress.type == NA_LOOPBACK) { continue; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } } @@ -545,31 +536,31 @@ SV_KickNum_f Kick a user off of the server ================== */ -static void SV_KickNum_f( void ) { - client_t *cl; +static void SV_KickNum_f(void) { + client_t *cl; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) { - Com_Printf ("Usage: %s \n", Cmd_Argv(0)); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: %s \n", Cmd_Argv(0)); return; } cl = SV_GetPlayerByNum(); - if ( !cl ) { + if (!cl) { return; } - if( cl->netchan.remoteAddress.type == NA_LOOPBACK ) { + if (cl->netchan.remoteAddress.type == NA_LOOPBACK) { Com_Printf("Cannot kick host player\n"); return; } - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","WAS_KICKED")); // "was kicked" ); - cl->lastPacketTime = svs.time; // in case there is a funny zombie + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "WAS_KICKED")); // "was kicked" ); + cl->lastPacketTime = svs.time; // in case there is a funny zombie } /* @@ -579,68 +570,63 @@ SV_RehashBans_f Load saved bans from file. ================== */ -static void SV_RehashBans_f( void ) -{ +static void SV_RehashBans_f(void) { int index, filelen; fileHandle_t readfrom; char *textbuf, *curpos, *maskpos, *newlinepos, *endpos; char filepath[MAX_QPATH]; // make sure server is running - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return; } serverBansCount = 0; - if ( !sv_banFile->string || !*sv_banFile->string ) + if (!sv_banFile->string || !*sv_banFile->string) return; - Com_sprintf( filepath, sizeof( filepath ), "%s/%s", FS_GetCurrentGameDir(), sv_banFile->string ); + Com_sprintf(filepath, sizeof(filepath), "%s/%s", FS_GetCurrentGameDir(), sv_banFile->string); - if ( (filelen = FS_SV_FOpenFileRead( filepath, &readfrom )) >= 0 ) - { - if ( filelen < 2 ) - { + if ((filelen = FS_SV_FOpenFileRead(filepath, &readfrom)) >= 0) { + if (filelen < 2) { // Don't bother if file is too short. - FS_FCloseFile( readfrom ); + FS_FCloseFile(readfrom); return; } - curpos = textbuf = (char *)Z_Malloc( filelen, TAG_TEMP_WORKSPACE ); + curpos = textbuf = (char *)Z_Malloc(filelen, TAG_TEMP_WORKSPACE); - filelen = FS_Read( textbuf, filelen, readfrom ); - FS_FCloseFile( readfrom ); + filelen = FS_Read(textbuf, filelen, readfrom); + FS_FCloseFile(readfrom); endpos = textbuf + filelen; - for ( index = 0; index < SERVER_MAXBANS && curpos + 2 < endpos; index++ ) - { + for (index = 0; index < SERVER_MAXBANS && curpos + 2 < endpos; index++) { // find the end of the address string - for ( maskpos = curpos + 2; maskpos < endpos && *maskpos != ' '; maskpos++ ); + for (maskpos = curpos + 2; maskpos < endpos && *maskpos != ' '; maskpos++) + ; - if ( maskpos + 1 >= endpos ) + if (maskpos + 1 >= endpos) break; *maskpos = '\0'; maskpos++; // find the end of the subnet specifier - for ( newlinepos = maskpos; newlinepos < endpos && *newlinepos != '\n'; newlinepos++ ); + for (newlinepos = maskpos; newlinepos < endpos && *newlinepos != '\n'; newlinepos++) + ; - if ( newlinepos >= endpos ) + if (newlinepos >= endpos) break; *newlinepos = '\0'; - if ( NET_StringToAdr( curpos + 2, &serverBans[index].ip ) ) - { + if (NET_StringToAdr(curpos + 2, &serverBans[index].ip)) { serverBans[index].isexception = (qboolean)(curpos[0] != '0'); - serverBans[index].subnet = atoi( maskpos ); + serverBans[index].subnet = atoi(maskpos); - if ( serverBans[index].ip.type == NA_IP && - (serverBans[index].subnet < 1 || serverBans[index].subnet > 32) ) - { + if (serverBans[index].ip.type == NA_IP && (serverBans[index].subnet < 1 || serverBans[index].subnet > 32)) { serverBans[index].subnet = 32; } } @@ -650,7 +636,7 @@ static void SV_RehashBans_f( void ) serverBansCount = index; - Z_Free( textbuf ); + Z_Free(textbuf); } } @@ -661,32 +647,28 @@ SV_WriteBans Save bans to file. ================== */ -static void SV_WriteBans( void ) -{ +static void SV_WriteBans(void) { int index; fileHandle_t writeto; char filepath[MAX_QPATH]; - if ( !sv_banFile->string || !*sv_banFile->string ) + if (!sv_banFile->string || !*sv_banFile->string) return; - Com_sprintf( filepath, sizeof( filepath ), "%s/%s", FS_GetCurrentGameDir(), sv_banFile->string ); + Com_sprintf(filepath, sizeof(filepath), "%s/%s", FS_GetCurrentGameDir(), sv_banFile->string); - if ( (writeto = FS_SV_FOpenFileWrite( filepath )) ) - { + if ((writeto = FS_SV_FOpenFileWrite(filepath))) { char writebuf[128]; serverBan_t *curban; - for ( index = 0; index < serverBansCount; index++ ) - { + for (index = 0; index < serverBansCount; index++) { curban = &serverBans[index]; - Com_sprintf( writebuf, sizeof( writebuf ), "%d %s %d\n", - curban->isexception, NET_AdrToString( curban->ip ), curban->subnet ); - FS_Write( writebuf, strlen( writebuf ), writeto ); + Com_sprintf(writebuf, sizeof(writebuf), "%d %s %d\n", curban->isexception, NET_AdrToString(curban->ip), curban->subnet); + FS_Write(writebuf, strlen(writebuf), writeto); } - FS_FCloseFile( writeto ); + FS_FCloseFile(writeto); } } @@ -698,15 +680,13 @@ Remove a ban or an exception from the list. ================== */ -static qboolean SV_DelBanEntryFromList( int index ) { - if ( index == serverBansCount - 1 ) +static qboolean SV_DelBanEntryFromList(int index) { + if (index == serverBansCount - 1) serverBansCount--; - else if ( index < (int)ARRAY_LEN( serverBans ) - 1 ) - { - memmove( serverBans + index, serverBans + index + 1, (serverBansCount - index - 1) * sizeof( *serverBans ) ); + else if (index < (int)ARRAY_LEN(serverBans) - 1) { + memmove(serverBans + index, serverBans + index + 1, (serverBansCount - index - 1) * sizeof(*serverBans)); serverBansCount--; - } - else + } else return qtrue; return qfalse; @@ -720,33 +700,28 @@ Parse a CIDR notation type string and return a netadr_t and suffix by reference ================== */ -static qboolean SV_ParseCIDRNotation( netadr_t *dest, int *mask, char *adrstr ) -{ +static qboolean SV_ParseCIDRNotation(netadr_t *dest, int *mask, char *adrstr) { char *suffix; - suffix = strchr( adrstr, '/' ); - if ( suffix ) - { + suffix = strchr(adrstr, '/'); + if (suffix) { *suffix = '\0'; suffix++; } - if ( !NET_StringToAdr( adrstr, dest ) ) + if (!NET_StringToAdr(adrstr, dest)) return qtrue; - if ( suffix ) - { - *mask = atoi( suffix ); + if (suffix) { + *mask = atoi(suffix); - if ( dest->type == NA_IP ) - { - if ( *mask < 1 || *mask > 32 ) + if (dest->type == NA_IP) { + if (*mask < 1 || *mask > 32) *mask = 32; - } - else + } else *mask = 32; } - //else if ( dest->type == NA_IP ) + // else if ( dest->type == NA_IP ) // *mask = 32; else *mask = 32; @@ -762,8 +737,7 @@ Ban a user from being able to play on this server based on his ip address. ================== */ -static void SV_AddBanToList( qboolean isexception ) -{ +static void SV_AddBanToList(qboolean isexception) { char *banstring; char addy2[NET_ADDRSTRMAXLEN]; netadr_t ip; @@ -771,101 +745,82 @@ static void SV_AddBanToList( qboolean isexception ) serverBan_t *curban; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } argc = Cmd_Argc(); - if ( argc < 2 || argc > 3 ) - { - Com_Printf( "Usage: %s (ip[/subnet] | clientnum [subnet])\n", Cmd_Argv( 0 ) ); + if (argc < 2 || argc > 3) { + Com_Printf("Usage: %s (ip[/subnet] | clientnum [subnet])\n", Cmd_Argv(0)); return; } - if ( serverBansCount >= (int)ARRAY_LEN( serverBans ) ) - { - Com_Printf( "Error: Maximum number of bans/exceptions exceeded.\n" ); + if (serverBansCount >= (int)ARRAY_LEN(serverBans)) { + Com_Printf("Error: Maximum number of bans/exceptions exceeded.\n"); return; } - banstring = Cmd_Argv( 1 ); + banstring = Cmd_Argv(1); - if ( strchr( banstring, '.' ) /*|| strchr( banstring, ':' )*/ ) - { + if (strchr(banstring, '.') /*|| strchr( banstring, ':' )*/) { // This is an ip address, not a client num. - if ( SV_ParseCIDRNotation( &ip, &mask, banstring ) ) - { - Com_Printf( "Error: Invalid address %s\n", banstring ); + if (SV_ParseCIDRNotation(&ip, &mask, banstring)) { + Com_Printf("Error: Invalid address %s\n", banstring); return; } - } - else - { + } else { client_t *cl; // client num. cl = SV_GetPlayerByNum(); - if ( !cl ) - { - Com_Printf( "Error: Playernum %s does not exist.\n", Cmd_Argv( 1 ) ); + if (!cl) { + Com_Printf("Error: Playernum %s does not exist.\n", Cmd_Argv(1)); return; } ip = cl->netchan.remoteAddress; - if ( argc == 3 ) - { - mask = atoi( Cmd_Argv( 2 ) ); + if (argc == 3) { + mask = atoi(Cmd_Argv(2)); - if ( ip.type == NA_IP ) - { - if ( mask < 1 || mask > 32 ) + if (ip.type == NA_IP) { + if (mask < 1 || mask > 32) mask = 32; - } - else + } else mask = 32; - } - else + } else mask = 32; } - if ( ip.type != NA_IP ) - { - Com_Printf( "Error: Can ban players connected via the internet only.\n" ); + if (ip.type != NA_IP) { + Com_Printf("Error: Can ban players connected via the internet only.\n"); return; } // first check whether a conflicting ban exists that would supersede the new one. - for ( index = 0; index < serverBansCount; index++ ) - { + for (index = 0; index < serverBansCount; index++) { curban = &serverBans[index]; - if ( curban->subnet <= mask ) - { - if ( (curban->isexception || !isexception) && NET_CompareBaseAdrMask( curban->ip, ip, curban->subnet ) ) - { - Q_strncpyz( addy2, NET_AdrToString( ip ), sizeof( addy2 ) ); + if (curban->subnet <= mask) { + if ((curban->isexception || !isexception) && NET_CompareBaseAdrMask(curban->ip, ip, curban->subnet)) { + Q_strncpyz(addy2, NET_AdrToString(ip), sizeof(addy2)); - Com_Printf( "Error: %s %s/%d supersedes %s %s/%d\n", curban->isexception ? "Exception" : "Ban", - NET_AdrToString( curban->ip ), curban->subnet, - isexception ? "exception" : "ban", addy2, mask ); + Com_Printf("Error: %s %s/%d supersedes %s %s/%d\n", curban->isexception ? "Exception" : "Ban", NET_AdrToString(curban->ip), curban->subnet, + isexception ? "exception" : "ban", addy2, mask); return; } } - if ( curban->subnet >= mask ) - { - if ( !curban->isexception && isexception && NET_CompareBaseAdrMask( curban->ip, ip, mask ) ) - { - Q_strncpyz( addy2, NET_AdrToString( curban->ip ), sizeof( addy2 ) ); - - Com_Printf( "Error: %s %s/%d supersedes already existing %s %s/%d\n", isexception ? "Exception" : "Ban", - NET_AdrToString( ip ), mask, - curban->isexception ? "exception" : "ban", addy2, curban->subnet ); + if (curban->subnet >= mask) { + if (!curban->isexception && isexception && NET_CompareBaseAdrMask(curban->ip, ip, mask)) { + Q_strncpyz(addy2, NET_AdrToString(curban->ip), sizeof(addy2)); + + Com_Printf("Error: %s %s/%d supersedes already existing %s %s/%d\n", isexception ? "Exception" : "Ban", NET_AdrToString(ip), mask, + curban->isexception ? "exception" : "ban", addy2, curban->subnet); return; } } @@ -873,12 +828,11 @@ static void SV_AddBanToList( qboolean isexception ) // now delete bans that are superseded by the new one index = 0; - while ( index < serverBansCount ) - { + while (index < serverBansCount) { curban = &serverBans[index]; - if ( curban->subnet > mask && (!curban->isexception || isexception) && NET_CompareBaseAdrMask( curban->ip, ip, mask ) ) - SV_DelBanEntryFromList( index ); + if (curban->subnet > mask && (!curban->isexception || isexception) && NET_CompareBaseAdrMask(curban->ip, ip, mask)) + SV_DelBanEntryFromList(index); else index++; } @@ -891,8 +845,7 @@ static void SV_AddBanToList( qboolean isexception ) SV_WriteBans(); - Com_Printf( "Added %s: %s/%d\n", isexception ? "ban exception" : "ban", - NET_AdrToString( ip ), mask ); + Com_Printf("Added %s: %s/%d\n", isexception ? "ban exception" : "ban", NET_AdrToString(ip), mask); } /* @@ -903,79 +856,60 @@ Remove a ban or an exception from the list. ================== */ -static void SV_DelBanFromList( qboolean isexception ) -{ +static void SV_DelBanFromList(qboolean isexception) { int index, count = 0, todel, mask; netadr_t ip; char *banstring; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) - { - Com_Printf( "Usage: %s (ip[/subnet] | num)\n", Cmd_Argv( 0 ) ); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: %s (ip[/subnet] | num)\n", Cmd_Argv(0)); return; } - banstring = Cmd_Argv( 1 ); + banstring = Cmd_Argv(1); - if ( strchr( banstring, '.' ) || strchr( banstring, ':' ) ) - { + if (strchr(banstring, '.') || strchr(banstring, ':')) { serverBan_t *curban; - if ( SV_ParseCIDRNotation( &ip, &mask, banstring ) ) - { - Com_Printf( "Error: Invalid address %s\n", banstring ); + if (SV_ParseCIDRNotation(&ip, &mask, banstring)) { + Com_Printf("Error: Invalid address %s\n", banstring); return; } index = 0; - while ( index < serverBansCount ) - { + while (index < serverBansCount) { curban = &serverBans[index]; - if ( curban->isexception == isexception && - curban->subnet >= mask && - NET_CompareBaseAdrMask( curban->ip, ip, mask ) ) - { - Com_Printf( "Deleting %s %s/%d\n", - isexception ? "exception" : "ban", - NET_AdrToString( curban->ip ), curban->subnet ); + if (curban->isexception == isexception && curban->subnet >= mask && NET_CompareBaseAdrMask(curban->ip, ip, mask)) { + Com_Printf("Deleting %s %s/%d\n", isexception ? "exception" : "ban", NET_AdrToString(curban->ip), curban->subnet); - SV_DelBanEntryFromList( index ); - } - else + SV_DelBanEntryFromList(index); + } else index++; } - } - else - { - todel = atoi( Cmd_Argv( 1 ) ); + } else { + todel = atoi(Cmd_Argv(1)); - if ( todel < 1 || todel > serverBansCount ) - { - Com_Printf( "Error: Invalid ban number given\n" ); + if (todel < 1 || todel > serverBansCount) { + Com_Printf("Error: Invalid ban number given\n"); return; } - for ( index = 0; index < serverBansCount; index++ ) - { - if ( serverBans[index].isexception == isexception ) - { + for (index = 0; index < serverBansCount; index++) { + if (serverBans[index].isexception == isexception) { count++; - if ( count == todel ) - { - Com_Printf( "Deleting %s %s/%d\n", - isexception ? "exception" : "ban", - NET_AdrToString( serverBans[index].ip ), serverBans[index].subnet ); + if (count == todel) { + Com_Printf("Deleting %s %s/%d\n", isexception ? "exception" : "ban", NET_AdrToString(serverBans[index].ip), serverBans[index].subnet); - SV_DelBanEntryFromList( index ); + SV_DelBanEntryFromList(index); break; } @@ -986,7 +920,6 @@ static void SV_DelBanFromList( qboolean isexception ) SV_WriteBans(); } - /* ================== SV_ListBans_f @@ -995,39 +928,32 @@ List all bans and exceptions on console ================== */ -static void SV_ListBans_f( void ) -{ +static void SV_ListBans_f(void) { int index, count; serverBan_t *ban; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } // List all bans - for ( index = count = 0; index < serverBansCount; index++ ) - { + for (index = count = 0; index < serverBansCount; index++) { ban = &serverBans[index]; - if ( !ban->isexception ) - { + if (!ban->isexception) { count++; - Com_Printf( "Ban #%d: %s/%d\n", count, - NET_AdrToString( ban->ip ), ban->subnet ); + Com_Printf("Ban #%d: %s/%d\n", count, NET_AdrToString(ban->ip), ban->subnet); } } // List all exceptions - for ( index = count = 0; index < serverBansCount; index++ ) - { + for (index = count = 0; index < serverBansCount; index++) { ban = &serverBans[index]; - if ( ban->isexception ) - { + if (ban->isexception) { count++; - Com_Printf( "Except #%d: %s/%d\n", count, - NET_AdrToString( ban->ip ), ban->subnet ); + Com_Printf("Except #%d: %s/%d\n", count, NET_AdrToString(ban->ip), ban->subnet); } } } @@ -1040,11 +966,10 @@ Delete all bans and exceptions. ================== */ -static void SV_FlushBans_f( void ) -{ +static void SV_FlushBans_f(void) { // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } @@ -1053,37 +978,25 @@ static void SV_FlushBans_f( void ) // empty the ban file. SV_WriteBans(); - Com_Printf( "All bans and exceptions have been deleted.\n" ); + Com_Printf("All bans and exceptions have been deleted.\n"); } -static void SV_BanAddr_f( void ) -{ - SV_AddBanToList( qfalse ); -} +static void SV_BanAddr_f(void) { SV_AddBanToList(qfalse); } -static void SV_ExceptAddr_f( void ) -{ - SV_AddBanToList( qtrue ); -} +static void SV_ExceptAddr_f(void) { SV_AddBanToList(qtrue); } -static void SV_BanDel_f( void ) -{ - SV_DelBanFromList( qfalse ); -} +static void SV_BanDel_f(void) { SV_DelBanFromList(qfalse); } -static void SV_ExceptDel_f( void ) -{ - SV_DelBanFromList( qtrue ); -} +static void SV_ExceptDel_f(void) { SV_DelBanFromList(qtrue); } -static const char *SV_CalcUptime( void ) { - static char buf[MAX_STRING_CHARS / 4] = { '\0' }; - char tmp[64] = { '\0' }; +static const char *SV_CalcUptime(void) { + static char buf[MAX_STRING_CHARS / 4] = {'\0'}; + char tmp[64] = {'\0'}; time_t currTime; - time( &currTime ); + time(&currTime); - int secs = difftime( currTime, svs.startTime ); + int secs = difftime(currTime, svs.startTime); int mins = secs / 60; int hours = mins / 60; int days = hours / 24; @@ -1091,16 +1004,16 @@ static const char *SV_CalcUptime( void ) { secs %= 60; mins %= 60; hours %= 24; - //days %= 365; + // days %= 365; buf[0] = '\0'; - if ( days > 0 ) { - Com_sprintf( tmp, sizeof(tmp), "%i days ", days ); - Q_strcat( buf, sizeof(buf), tmp ); + if (days > 0) { + Com_sprintf(tmp, sizeof(tmp), "%i days ", days); + Q_strcat(buf, sizeof(buf), tmp); } - Com_sprintf( tmp, sizeof(tmp), "%ih%im%is", hours, mins, secs ); - Q_strcat( buf, sizeof(buf), tmp ); + Com_sprintf(tmp, sizeof(tmp), "%ih%im%is", hours, mins, secs); + Q_strcat(buf, sizeof(buf), tmp); return buf; } @@ -1110,38 +1023,33 @@ static const char *SV_CalcUptime( void ) { SV_Status_f ================ */ -static void SV_Status_f( void ) -{ - int i, humans, bots; - client_t *cl; - playerState_t *ps; - const char *s; - int ping; - char state[32]; - qboolean avoidTruncation = qfalse; +static void SV_Status_f(void) { + int i, humans, bots; + client_t *cl; + playerState_t *ps; + const char *s; + int ping; + char state[32]; + qboolean avoidTruncation = qfalse; // make sure server is running - if ( !com_sv_running->integer ) - { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() > 1 ) - { - if (!Q_stricmp("notrunc", Cmd_Argv(1))) - { + if (Cmd_Argc() > 1) { + if (!Q_stricmp("notrunc", Cmd_Argv(1))) { avoidTruncation = qtrue; } } humans = bots = 0; - for ( i = 0 ; i < sv_maxclients->integer ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { - if ( svs.clients[i].netchan.remoteAddress.type != NA_BOT ) { + for (i = 0; i < sv_maxclients->integer; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { + if (svs.clients[i].netchan.remoteAddress.type != NA_BOT) { humans++; - } - else { + } else { bots++; } } @@ -1157,72 +1065,54 @@ static void SV_Status_f( void ) #define STATUS_OS "Unknown" #endif - const char *ded_table[] = - { + const char *ded_table[] = { "listen", "lan dedicated", "public dedicated", }; - char hostname[MAX_HOSTNAMELENGTH] = { 0 }; + char hostname[MAX_HOSTNAMELENGTH] = {0}; - Q_strncpyz( hostname, sv_hostname->string, sizeof(hostname) ); - Q_StripColor( hostname ); + Q_strncpyz(hostname, sv_hostname->string, sizeof(hostname)); + Q_StripColor(hostname); - Com_Printf( "hostname: %s^7\n", hostname ); - Com_Printf( "version : %s %i\n", VERSION_STRING_DOTTED, PROTOCOL_VERSION ); - Com_Printf( "game : %s\n", FS_GetCurrentGameDir() ); - Com_Printf( "udp/ip : %s:%i os(%s) type(%s)\n", Cvar_VariableString( "net_ip" ), Cvar_VariableIntegerValue( "net_port" ), STATUS_OS, ded_table[com_dedicated->integer] ); - Com_Printf( "map : %s gametype(%i)\n", sv_mapname->string, sv_gametype->integer ); - Com_Printf( "players : %i humans, %i bots (%i max)\n", humans, bots, sv_maxclients->integer - sv_privateClients->integer ); - Com_Printf( "uptime : %s\n", SV_CalcUptime() ); + Com_Printf("hostname: %s^7\n", hostname); + Com_Printf("version : %s %i\n", VERSION_STRING_DOTTED, PROTOCOL_VERSION); + Com_Printf("game : %s\n", FS_GetCurrentGameDir()); + Com_Printf("udp/ip : %s:%i os(%s) type(%s)\n", Cvar_VariableString("net_ip"), Cvar_VariableIntegerValue("net_port"), STATUS_OS, + ded_table[com_dedicated->integer]); + Com_Printf("map : %s gametype(%i)\n", sv_mapname->string, sv_gametype->integer); + Com_Printf("players : %i humans, %i bots (%i max)\n", humans, bots, sv_maxclients->integer - sv_privateClients->integer); + Com_Printf("uptime : %s\n", SV_CalcUptime()); - Com_Printf ("cl score ping name address rate \n"); - Com_Printf ("-- ----- ---- --------------- --------------------------------------- -----\n"); - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) - { - if ( !cl->state ) + Com_Printf("cl score ping name address rate \n"); + Com_Printf("-- ----- ---- --------------- --------------------------------------- -----\n"); + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) continue; - if ( cl->state == CS_CONNECTED ) - Q_strncpyz( state, "CON ", sizeof( state ) ); - else if ( cl->state == CS_ZOMBIE ) - Q_strncpyz( state, "ZMB ", sizeof( state ) ); + if (cl->state == CS_CONNECTED) + Q_strncpyz(state, "CON ", sizeof(state)); + else if (cl->state == CS_ZOMBIE) + Q_strncpyz(state, "ZMB ", sizeof(state)); else { ping = cl->ping < 9999 ? cl->ping : 9999; - Com_sprintf( state, sizeof(state), "%4i", ping ); + Com_sprintf(state, sizeof(state), "%4i", ping); } - ps = SV_GameClientNum( i ); - s = NET_AdrToString( cl->netchan.remoteAddress ); - - if (!avoidTruncation) - { - Com_Printf ("%2i %5i %s %-15.15s ^7%39s %5i\n", - i, - ps->persistant[PERS_SCORE], - state, - cl->name, - s, - cl->rate - ); - } - else - { - Com_Printf ("%2i %5i %s %s ^7%39s %5i\n", - i, - ps->persistant[PERS_SCORE], - state, - cl->name, - s, - cl->rate - ); + ps = SV_GameClientNum(i); + s = NET_AdrToString(cl->netchan.remoteAddress); + + if (!avoidTruncation) { + Com_Printf("%2i %5i %s %-15.15s ^7%39s %5i\n", i, ps->persistant[PERS_SCORE], state, cl->name, s, cl->rate); + } else { + Com_Printf("%2i %5i %s %s ^7%39s %5i\n", i, ps->persistant[PERS_SCORE], state, cl->name, s, cl->rate); } } - Com_Printf ("\n"); + Com_Printf("\n"); } -char *SV_ExpandNewlines( char *in ); +char *SV_ExpandNewlines(char *in); #define SVSAY_PREFIX "Server^7\x19: " /* @@ -1231,26 +1121,26 @@ SV_ConSay_f ================== */ static void SV_ConSay_f(void) { - char text[MAX_SAY_TEXT] = {0}; + char text[MAX_SAY_TEXT] = {0}; - if( !com_dedicated->integer ) { - Com_Printf( "Server is not dedicated.\n" ); + if (!com_dedicated->integer) { + Com_Printf("Server is not dedicated.\n"); return; } // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc () < 2 ) { + if (Cmd_Argc() < 2) { return; } - Cmd_ArgsBuffer( text, sizeof(text) ); + Cmd_ArgsBuffer(text, sizeof(text)); - Com_Printf ("broadcast: chat \"" SVSAY_PREFIX "%s\\n\"\n", SV_ExpandNewlines((char *)text) ); + Com_Printf("broadcast: chat \"" SVSAY_PREFIX "%s\\n\"\n", SV_ExpandNewlines((char *)text)); SV_SendServerCommand(NULL, "chat \"" SVSAY_PREFIX "%s\"\n", text); } @@ -1262,178 +1152,151 @@ SV_ConTell_f ================== */ static void SV_ConTell_f(void) { - char text[MAX_SAY_TEXT] = {0}; - client_t *cl; + char text[MAX_SAY_TEXT] = {0}; + client_t *cl; - if( !com_dedicated->integer ) { - Com_Printf( "Server is not dedicated.\n" ); + if (!com_dedicated->integer) { + Com_Printf("Server is not dedicated.\n"); return; } // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc () < 3 ) { - Com_Printf ("Usage: svtell \n"); + if (Cmd_Argc() < 3) { + Com_Printf("Usage: svtell \n"); return; } cl = SV_GetPlayerByNum(); - if ( !cl ) { + if (!cl) { return; } - Cmd_ArgsFromBuffer( 2, text, sizeof(text) ); + Cmd_ArgsFromBuffer(2, text, sizeof(text)); - Com_Printf ("tell: svtell to %s" S_COLOR_WHITE ": %s\n", cl->name, SV_ExpandNewlines((char *)text) ); + Com_Printf("tell: svtell to %s" S_COLOR_WHITE ": %s\n", cl->name, SV_ExpandNewlines((char *)text)); SV_SendServerCommand(cl, "chat \"" SVTELL_PREFIX S_COLOR_MAGENTA "%s" S_COLOR_WHITE "\"\n", text); } const char *forceToggleNamePrints[NUM_FORCE_POWERS] = { - "HEAL", - "JUMP", - "SPEED", - "PUSH", - "PULL", - "MINDTRICK", - "GRIP", - "LIGHTNING", - "DARK RAGE", - "PROTECT", - "ABSORB", - "TEAM HEAL", - "TEAM REPLENISH", - "DRAIN", - "SEEING", - "SABER OFFENSE", - "SABER DEFENSE", - "SABER THROW", + "HEAL", "JUMP", "SPEED", "PUSH", "PULL", "MINDTRICK", "GRIP", "LIGHTNING", "DARK RAGE", + "PROTECT", "ABSORB", "TEAM HEAL", "TEAM REPLENISH", "DRAIN", "SEEING", "SABER OFFENSE", "SABER DEFENSE", "SABER THROW", }; -static void SV_ForceToggle_f( void ) { +static void SV_ForceToggle_f(void) { int bits = Cvar_VariableIntegerValue("g_forcePowerDisable"); int i, val; char *s; // make sure server is running - if( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) { - for ( i = 0; i= 0 && val < NUM_FORCE_POWERS) { + if (val >= 0 && val < NUM_FORCE_POWERS) { bits ^= (1 << val); Cvar_SetValue("g_forcePowerDisable", bits); - Com_Printf( "%s %s^7\n", forceToggleNamePrints[val], (bits & (1<integer == GT_DUEL || sv_gametype->integer == GT_POWERDUEL ) { + if (sv_gametype->integer == GT_DUEL || sv_gametype->integer == GT_POWERDUEL) { cvarStr = "g_duelWeaponDisable"; - bits = Cvar_VariableIntegerValue( "g_duelWeaponDisable" ); - } - else { + bits = Cvar_VariableIntegerValue("g_duelWeaponDisable"); + } else { cvarStr = "g_weaponDisable"; - bits = Cvar_VariableIntegerValue( "g_weaponDisable" ); + bits = Cvar_VariableIntegerValue("g_weaponDisable"); } // make sure server is running - if( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) { - for ( i = 0; i= 0 && val < WP_NUM_WEAPONS) { + if (val >= 0 && val < WP_NUM_WEAPONS) { bits ^= (1 << val); Cvar_SetValue(cvarStr, bits); - Com_Printf( "%s %s^7\n", weaponToggleNamePrints[val], (bits & (1 << val)) ? "^2Enabled" : "^1Disabled" ); - } - else { - for ( i = 0; iinteger ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - Com_Printf ("Server info settings:\n"); - Info_Print ( Cvar_InfoString( CVAR_SERVERINFO ) ); + Com_Printf("Server info settings:\n"); + Info_Print(Cvar_InfoString(CVAR_SERVERINFO)); } /* @@ -1473,15 +1334,15 @@ SV_Systeminfo_f Examine or change the serverinfo string =========== */ -static void SV_Systeminfo_f( void ) { +static void SV_Systeminfo_f(void) { // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - Com_Printf ("System info settings:\n"); - Info_Print ( Cvar_InfoString_Big( CVAR_SYSTEMINFO ) ); + Com_Printf("System info settings:\n"); + Info_Print(Cvar_InfoString_Big(CVAR_SYSTEMINFO)); } /* @@ -1491,28 +1352,28 @@ SV_DumpUser_f Examine all a users info strings FIXME: move to game =========== */ -static void SV_DumpUser_f( void ) { - client_t *cl; +static void SV_DumpUser_f(void) { + client_t *cl; // make sure server is running - if ( !com_sv_running->integer ) { - Com_Printf( "Server is not running.\n" ); + if (!com_sv_running->integer) { + Com_Printf("Server is not running.\n"); return; } - if ( Cmd_Argc() != 2 ) { - Com_Printf ("Usage: dumpuser \n"); + if (Cmd_Argc() != 2) { + Com_Printf("Usage: dumpuser \n"); return; } cl = SV_GetPlayerByHandle(); - if ( !cl ) { + if (!cl) { return; } - Com_Printf( "userinfo\n" ); - Com_Printf( "--------\n" ); - Info_Print( cl->userinfo ); + Com_Printf("userinfo\n"); + Com_Printf("--------\n"); + Info_Print(cl->userinfo); } /* @@ -1520,49 +1381,47 @@ static void SV_DumpUser_f( void ) { SV_KillServer ================= */ -static void SV_KillServer_f( void ) { - SV_Shutdown( "killserver" ); -} +static void SV_KillServer_f(void) { SV_Shutdown("killserver"); } -void SV_WriteDemoMessage ( client_t *cl, msg_t *msg, int headerBytes ) { - int len, swlen; +void SV_WriteDemoMessage(client_t *cl, msg_t *msg, int headerBytes) { + int len, swlen; // write the packet sequence len = cl->netchan.outgoingSequence; - swlen = LittleLong( len ); - FS_Write( &swlen, 4, cl->demo.demofile ); + swlen = LittleLong(len); + FS_Write(&swlen, 4, cl->demo.demofile); // skip the packet sequencing information len = msg->cursize - headerBytes; - swlen = LittleLong( len ); - FS_Write( &swlen, 4, cl->demo.demofile ); - FS_Write( msg->data + headerBytes, len, cl->demo.demofile ); + swlen = LittleLong(len); + FS_Write(&swlen, 4, cl->demo.demofile); + FS_Write(msg->data + headerBytes, len, cl->demo.demofile); } -void SV_StopRecordDemo( client_t *cl ) { - int len; +void SV_StopRecordDemo(client_t *cl) { + int len; - if ( !cl->demo.demorecording ) { - Com_Printf( "Client %d is not recording a demo.\n", cl - svs.clients ); + if (!cl->demo.demorecording) { + Com_Printf("Client %d is not recording a demo.\n", cl - svs.clients); return; } // finish up len = -1; - FS_Write (&len, 4, cl->demo.demofile); - FS_Write (&len, 4, cl->demo.demofile); - FS_FCloseFile (cl->demo.demofile); + FS_Write(&len, 4, cl->demo.demofile); + FS_Write(&len, 4, cl->demo.demofile); + FS_FCloseFile(cl->demo.demofile); cl->demo.demofile = 0; cl->demo.demorecording = qfalse; - Com_Printf ("Stopped demo for client %d.\n", cl - svs.clients); + Com_Printf("Stopped demo for client %d.\n", cl - svs.clients); } // stops all recording demos void SV_StopAutoRecordDemos() { - if ( svs.clients && sv_autoDemo->integer ) { - for ( client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++ ) { - if ( client->demo.demorecording) { - SV_StopRecordDemo( client ); + if (svs.clients && sv_autoDemo->integer) { + for (client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++) { + if (client->demo.demorecording) { + SV_StopRecordDemo(client); } } } @@ -1575,30 +1434,30 @@ SV_StopRecording_f stop recording a demo ==================== */ -void SV_StopRecord_f( void ) { - int i; +void SV_StopRecord_f(void) { + int i; client_t *cl = NULL; - if ( Cmd_Argc() == 2 ) { - int clIndex = atoi( Cmd_Argv( 1 ) ); - if ( clIndex < 0 || clIndex >= sv_maxclients->integer ) { - Com_Printf( "Unknown client number %d.\n", clIndex ); + if (Cmd_Argc() == 2) { + int clIndex = atoi(Cmd_Argv(1)); + if (clIndex < 0 || clIndex >= sv_maxclients->integer) { + Com_Printf("Unknown client number %d.\n", clIndex); return; } cl = &svs.clients[clIndex]; } else { for (i = 0; i < sv_maxclients->integer; i++) { - if ( svs.clients[i].demo.demorecording ) { + if (svs.clients[i].demo.demorecording) { cl = &svs.clients[i]; break; } } - if ( cl == NULL ) { - Com_Printf( "No demo being recorded.\n" ); + if (cl == NULL) { + Com_Printf("No demo being recorded.\n"); return; } } - SV_StopRecordDemo( cl ); + SV_StopRecordDemo(cl); } /* @@ -1606,42 +1465,42 @@ void SV_StopRecord_f( void ) { SV_DemoFilename ================== */ -void SV_DemoFilename( char *buf, int bufSize ) { +void SV_DemoFilename(char *buf, int bufSize) { time_t rawtime; char timeStr[32] = {0}; // should really only reach ~19 chars - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime - Com_sprintf( buf, bufSize, "demo%s", timeStr ); + Com_sprintf(buf, bufSize, "demo%s", timeStr); } // defined in sv_client.cpp -extern void SV_CreateClientGameStateMessage( client_t *client, msg_t* msg ); +extern void SV_CreateClientGameStateMessage(client_t *client, msg_t *msg); -void SV_RecordDemo( client_t *cl, char *demoName ) { - char name[MAX_OSPATH]; - byte bufData[MAX_MSGLEN]; - msg_t msg; - int len; +void SV_RecordDemo(client_t *cl, char *demoName) { + char name[MAX_OSPATH]; + byte bufData[MAX_MSGLEN]; + msg_t msg; + int len; - if ( cl->demo.demorecording ) { - Com_Printf( "Already recording.\n" ); + if (cl->demo.demorecording) { + Com_Printf("Already recording.\n"); return; } - if ( cl->state != CS_ACTIVE ) { - Com_Printf( "Client is not active.\n" ); + if (cl->state != CS_ACTIVE) { + Com_Printf("Client is not active.\n"); return; } // open the demo file - Q_strncpyz( cl->demo.demoName, demoName, sizeof( cl->demo.demoName ) ); - Com_sprintf( name, sizeof( name ), "demos/%s.dm_%d", cl->demo.demoName, PROTOCOL_VERSION ); - Com_Printf( "recording to %s.\n", name ); - cl->demo.demofile = FS_FOpenFileWrite( name ); - if ( !cl->demo.demofile ) { - Com_Printf ("ERROR: couldn't open.\n"); + Q_strncpyz(cl->demo.demoName, demoName, sizeof(cl->demo.demoName)); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", cl->demo.demoName, PROTOCOL_VERSION); + Com_Printf("recording to %s.\n", name); + cl->demo.demofile = FS_FOpenFileWrite(name); + if (!cl->demo.demofile) { + Com_Printf("ERROR: couldn't open.\n"); return; } cl->demo.demorecording = qtrue; @@ -1649,173 +1508,172 @@ void SV_RecordDemo( client_t *cl, char *demoName ) { // don't start saving messages until a non-delta compressed message is received cl->demo.demowaiting = qtrue; - cl->demo.isBot = ( cl->netchan.remoteAddress.type == NA_BOT ) ? qtrue : qfalse; + cl->demo.isBot = (cl->netchan.remoteAddress.type == NA_BOT) ? qtrue : qfalse; cl->demo.botReliableAcknowledge = cl->reliableSent; // write out the gamestate message - MSG_Init( &msg, bufData, sizeof( bufData ) ); + MSG_Init(&msg, bufData, sizeof(bufData)); // NOTE, MRE: all server->client messages now acknowledge int tmp = cl->reliableSent; - SV_CreateClientGameStateMessage( cl, &msg ); + SV_CreateClientGameStateMessage(cl, &msg); cl->reliableSent = tmp; // finished writing the client packet - MSG_WriteByte( &msg, svc_EOF ); + MSG_WriteByte(&msg, svc_EOF); // write it to the demo file - len = LittleLong( cl->netchan.outgoingSequence - 1 ); - FS_Write( &len, 4, cl->demo.demofile ); + len = LittleLong(cl->netchan.outgoingSequence - 1); + FS_Write(&len, 4, cl->demo.demofile); - len = LittleLong( msg.cursize ); - FS_Write( &len, 4, cl->demo.demofile ); - FS_Write( msg.data, msg.cursize, cl->demo.demofile ); + len = LittleLong(msg.cursize); + FS_Write(&len, 4, cl->demo.demofile); + FS_Write(msg.data, msg.cursize, cl->demo.demofile); // the rest of the demo file will be copied from net messages } -void SV_AutoRecordDemo( client_t *cl ) { +void SV_AutoRecordDemo(client_t *cl) { char demoName[MAX_OSPATH]; char demoFolderName[MAX_OSPATH]; char demoFileName[MAX_OSPATH]; - char *demoNames[] = { demoFolderName, demoFileName }; + char *demoNames[] = {demoFolderName, demoFileName}; char date[MAX_OSPATH]; char folderDate[MAX_OSPATH]; char folderTreeDate[MAX_OSPATH]; char demoPlayerName[MAX_NAME_LENGTH]; time_t rawtime; - struct tm * timeinfo; - time( &rawtime ); - timeinfo = localtime( &rawtime ); - strftime( date, sizeof( date ), "%Y-%m-%d_%H-%M-%S", timeinfo ); - timeinfo = localtime( &sv.realMapTimeStarted ); - strftime( folderDate, sizeof( folderDate ), "%Y-%m-%d_%H-%M-%S", timeinfo ); - strftime( folderTreeDate, sizeof( folderTreeDate ), "%Y/%m/%d", timeinfo ); - Q_strncpyz( demoPlayerName, cl->name, sizeof( demoPlayerName ) ); - Q_CleanStr( demoPlayerName ); - Com_sprintf( demoFileName, sizeof( demoFileName ), "%d %s %s %s", - cl - svs.clients, demoPlayerName, Cvar_VariableString( "mapname" ), date ); - Com_sprintf( demoFolderName, sizeof( demoFolderName ), "%s %s", Cvar_VariableString( "mapname" ), folderDate ); + struct tm *timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + strftime(date, sizeof(date), "%Y-%m-%d_%H-%M-%S", timeinfo); + timeinfo = localtime(&sv.realMapTimeStarted); + strftime(folderDate, sizeof(folderDate), "%Y-%m-%d_%H-%M-%S", timeinfo); + strftime(folderTreeDate, sizeof(folderTreeDate), "%Y/%m/%d", timeinfo); + Q_strncpyz(demoPlayerName, cl->name, sizeof(demoPlayerName)); + Q_CleanStr(demoPlayerName); + Com_sprintf(demoFileName, sizeof(demoFileName), "%d %s %s %s", cl - svs.clients, demoPlayerName, Cvar_VariableString("mapname"), date); + Com_sprintf(demoFolderName, sizeof(demoFolderName), "%s %s", Cvar_VariableString("mapname"), folderDate); // sanitize filename - for ( char **start = demoNames; start - demoNames < (ptrdiff_t)ARRAY_LEN( demoNames ); start++ ) { - Q_strstrip( *start, "\n\r;:.?*<>|\\/\"", NULL ); + for (char **start = demoNames; start - demoNames < (ptrdiff_t)ARRAY_LEN(demoNames); start++) { + Q_strstrip(*start, "\n\r;:.?*<>|\\/\"", NULL); } - Com_sprintf( demoName, sizeof( demoName ), "autorecord/%s/%s/%s", folderTreeDate, demoFolderName, demoFileName ); - SV_RecordDemo( cl, demoName ); + Com_sprintf(demoName, sizeof(demoName), "autorecord/%s/%s/%s", folderTreeDate, demoFolderName, demoFileName); + SV_RecordDemo(cl, demoName); } -static time_t SV_ExtractTimeFromDemoFolder( char *folder ) { - char *slash = strrchr( folder, '/' ); - if ( slash ) { +static time_t SV_ExtractTimeFromDemoFolder(char *folder) { + char *slash = strrchr(folder, '/'); + if (slash) { folder = slash + 1; } - size_t timeLen = strlen( "0000-00-00_00-00-00" ); - if ( strlen( folder ) < timeLen ) { + size_t timeLen = strlen("0000-00-00_00-00-00"); + if (strlen(folder) < timeLen) { return 0; } struct tm timeinfo; timeinfo.tm_isdst = 0; - int numMatched = sscanf( folder + ( strlen(folder) - timeLen ), "%4d-%2d-%2d_%2d-%2d-%2d", - &timeinfo.tm_year, &timeinfo.tm_mon, &timeinfo.tm_mday, &timeinfo.tm_hour, &timeinfo.tm_min, &timeinfo.tm_sec); - if ( numMatched < 6 ) { + int numMatched = sscanf(folder + (strlen(folder) - timeLen), "%4d-%2d-%2d_%2d-%2d-%2d", &timeinfo.tm_year, &timeinfo.tm_mon, &timeinfo.tm_mday, + &timeinfo.tm_hour, &timeinfo.tm_min, &timeinfo.tm_sec); + if (numMatched < 6) { // parsing failed return 0; } timeinfo.tm_year -= 1900; timeinfo.tm_mon--; - return mktime( &timeinfo ); + return mktime(&timeinfo); } -static int QDECL SV_DemoFolderTimeComparator( const void *arg1, const void *arg2 ) { +static int QDECL SV_DemoFolderTimeComparator(const void *arg1, const void *arg2) { char *left = (char *)arg1, *right = (char *)arg2; - time_t leftTime = SV_ExtractTimeFromDemoFolder( left ); - time_t rightTime = SV_ExtractTimeFromDemoFolder( right ); - if ( leftTime == 0 && rightTime == 0 ) { - return -strcmp( left, right ); - } else if ( leftTime == 0 ) { + time_t leftTime = SV_ExtractTimeFromDemoFolder(left); + time_t rightTime = SV_ExtractTimeFromDemoFolder(right); + if (leftTime == 0 && rightTime == 0) { + return -strcmp(left, right); + } else if (leftTime == 0) { return 1; - } else if ( rightTime == 0 ) { + } else if (rightTime == 0) { return -1; } return rightTime - leftTime; } // returns number of folders found. pass NULL result pointer for just a count. -static int SV_FindLeafFolders( const char *baseFolder, char *result, int maxResults, int maxFolderLength ) { - char *fileList = (char *)Z_Malloc( MAX_OSPATH * maxResults, TAG_FILESYS ); // too big for stack since this is recursive +static int SV_FindLeafFolders(const char *baseFolder, char *result, int maxResults, int maxFolderLength) { + char *fileList = (char *)Z_Malloc(MAX_OSPATH * maxResults, TAG_FILESYS); // too big for stack since this is recursive char fullFolder[MAX_OSPATH]; int resultCount = 0; char *fileName; int i; - int numFiles = FS_GetFileList( baseFolder, "/", fileList, MAX_OSPATH * maxResults ); + int numFiles = FS_GetFileList(baseFolder, "/", fileList, MAX_OSPATH * maxResults); fileName = fileList; - for ( i = 0; i < numFiles; i++ ) { - if ( Q_stricmp( fileName, "." ) && Q_stricmp( fileName, ".." ) ) { + for (i = 0; i < numFiles; i++) { + if (Q_stricmp(fileName, ".") && Q_stricmp(fileName, "..")) { char *nextResult = NULL; - Com_sprintf( fullFolder, sizeof( fullFolder ), "%s/%s", baseFolder, fileName ); - if ( result != NULL ) { + Com_sprintf(fullFolder, sizeof(fullFolder), "%s/%s", baseFolder, fileName); + if (result != NULL) { nextResult = &result[maxFolderLength * resultCount]; } - int newResults = SV_FindLeafFolders( fullFolder, nextResult, maxResults - resultCount, maxFolderLength ); + int newResults = SV_FindLeafFolders(fullFolder, nextResult, maxResults - resultCount, maxFolderLength); resultCount += newResults; - if ( result != NULL && resultCount >= maxResults ) { + if (result != NULL && resultCount >= maxResults) { break; } - if ( newResults == 0 ) { - if ( result != NULL ) { - Q_strncpyz( &result[maxFolderLength * resultCount], fullFolder, maxFolderLength ); + if (newResults == 0) { + if (result != NULL) { + Q_strncpyz(&result[maxFolderLength * resultCount], fullFolder, maxFolderLength); } resultCount++; - if ( result != NULL && resultCount >= maxResults ) { + if (result != NULL && resultCount >= maxResults) { break; } } } - fileName += strlen( fileName ) + 1; + fileName += strlen(fileName) + 1; } - Z_Free( fileList ); + Z_Free(fileList); return resultCount; } // starts demo recording on all active clients void SV_BeginAutoRecordDemos() { - if ( sv_autoDemo->integer ) { - for ( client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++ ) { - if ( client->state == CS_ACTIVE && !client->demo.demorecording ) { - if ( client->netchan.remoteAddress.type != NA_BOT || sv_autoDemoBots->integer ) { - SV_AutoRecordDemo( client ); + if (sv_autoDemo->integer) { + for (client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++) { + if (client->state == CS_ACTIVE && !client->demo.demorecording) { + if (client->netchan.remoteAddress.type != NA_BOT || sv_autoDemoBots->integer) { + SV_AutoRecordDemo(client); } } } - if ( sv_autoDemoMaxMaps->integer > 0 && sv.demosPruned == qfalse ) { + if (sv_autoDemoMaxMaps->integer > 0 && sv.demosPruned == qfalse) { char autorecordDirList[500 * MAX_OSPATH], tmpFileList[5 * MAX_OSPATH]; - int autorecordDirListCount = SV_FindLeafFolders( "demos/autorecord", autorecordDirList, 500, MAX_OSPATH ); + int autorecordDirListCount = SV_FindLeafFolders("demos/autorecord", autorecordDirList, 500, MAX_OSPATH); int i; - qsort( autorecordDirList, autorecordDirListCount, MAX_OSPATH, SV_DemoFolderTimeComparator ); - for ( i = sv_autoDemoMaxMaps->integer; i < autorecordDirListCount; i++ ) { + qsort(autorecordDirList, autorecordDirListCount, MAX_OSPATH, SV_DemoFolderTimeComparator); + for (i = sv_autoDemoMaxMaps->integer; i < autorecordDirListCount; i++) { char *folder = &autorecordDirList[i * MAX_OSPATH], *slash = NULL; - FS_HomeRmdir( folder, qtrue ); + FS_HomeRmdir(folder, qtrue); // if this folder was the last thing in its parent folder (and its parent isn't the root folder), // also delete the parent. for (;;) { - slash = strrchr( folder, '/' ); - if ( slash == NULL ) { + slash = strrchr(folder, '/'); + if (slash == NULL) { break; } slash[0] = '\0'; - if ( !strcmp( folder, "demos/autorecord" ) ) { + if (!strcmp(folder, "demos/autorecord")) { break; } - int numFiles = FS_GetFileList( folder, "", tmpFileList, sizeof( tmpFileList ) ); - int numFolders = FS_GetFileList( folder, "/", tmpFileList, sizeof( tmpFileList ) ); + int numFiles = FS_GetFileList(folder, "", tmpFileList, sizeof(tmpFileList)); + int numFolders = FS_GetFileList(folder, "/", tmpFileList, sizeof(tmpFileList)); // numFolders will include . and .. - if ( numFiles == 0 && numFolders == 2 ) { + if (numFiles == 0 && numFolders == 2) { // dangling empty folder, delete - FS_HomeRmdir( folder, qfalse ); + FS_HomeRmdir(folder, qfalse); } else { break; } @@ -1827,83 +1685,78 @@ void SV_BeginAutoRecordDemos() { } // code is a merge of the cl_main.cpp function of the same name and SV_SendClientGameState in sv_client.cpp -static void SV_Record_f( void ) { - char demoName[MAX_OSPATH]; - char name[MAX_OSPATH]; - int i; - char *s; - client_t *cl; - - if ( svs.clients == NULL ) { - Com_Printf( "cannot record server demo - null svs.clients\n" ); +static void SV_Record_f(void) { + char demoName[MAX_OSPATH]; + char name[MAX_OSPATH]; + int i; + char *s; + client_t *cl; + + if (svs.clients == NULL) { + Com_Printf("cannot record server demo - null svs.clients\n"); return; } - if ( Cmd_Argc() > 3 ) { - Com_Printf( "record \n" ); + if (Cmd_Argc() > 3) { + Com_Printf("record \n"); return; } - - if ( Cmd_Argc() == 3 ) { - int clIndex = atoi( Cmd_Argv( 2 ) ); - if ( clIndex < 0 || clIndex >= sv_maxclients->integer ) { - Com_Printf( "Unknown client number %d.\n", clIndex ); + if (Cmd_Argc() == 3) { + int clIndex = atoi(Cmd_Argv(2)); + if (clIndex < 0 || clIndex >= sv_maxclients->integer) { + Com_Printf("Unknown client number %d.\n", clIndex); return; } cl = &svs.clients[clIndex]; } else { - for ( i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++, cl++ ) - { - if ( !cl->state ) - { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (!cl->state) { continue; } - if ( cl->demo.demorecording ) - { + if (cl->demo.demorecording) { continue; } - if ( cl->state == CS_ACTIVE ) - { + if (cl->state == CS_ACTIVE) { break; } } } if (cl - svs.clients >= sv_maxclients->integer) { - Com_Printf( "No active client could be found.\n" ); + Com_Printf("No active client could be found.\n"); return; } - if ( cl->demo.demorecording ) { - Com_Printf( "Already recording.\n" ); + if (cl->demo.demorecording) { + Com_Printf("Already recording.\n"); return; } - if ( cl->state != CS_ACTIVE ) { - Com_Printf( "Client is not active.\n" ); + if (cl->state != CS_ACTIVE) { + Com_Printf("Client is not active.\n"); return; } - if ( Cmd_Argc() >= 2 ) { - s = Cmd_Argv( 1 ); - Q_strncpyz( demoName, s, sizeof( demoName ) ); - Com_sprintf( name, sizeof( name ), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); + if (Cmd_Argc() >= 2) { + s = Cmd_Argv(1); + Q_strncpyz(demoName, s, sizeof(demoName)); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION); } else { // timestamp the file - SV_DemoFilename( demoName, sizeof( demoName ) ); + SV_DemoFilename(demoName, sizeof(demoName)); - Com_sprintf (name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION ); + Com_sprintf(name, sizeof(name), "demos/%s.dm_%d", demoName, PROTOCOL_VERSION); - if ( FS_FileExists( name ) ) { - Com_Printf( "Record: Couldn't create a file\n"); + if (FS_FileExists(name)) { + Com_Printf("Record: Couldn't create a file\n"); return; - } + } } - SV_RecordDemo( cl, demoName ); + SV_RecordDemo(cl, demoName); } /* @@ -1911,17 +1764,17 @@ static void SV_Record_f( void ) { SV_WhitelistIP_f ================= */ -static void SV_WhitelistIP_f( void ) { - if ( Cmd_Argc() < 2 ) { - Com_Printf ("Usage: whitelistip ...\n"); +static void SV_WhitelistIP_f(void) { + if (Cmd_Argc() < 2) { + Com_Printf("Usage: whitelistip ...\n"); return; } - for ( int i = 1; i < Cmd_Argc(); i++ ) { - netadr_t adr; + for (int i = 1; i < Cmd_Argc(); i++) { + netadr_t adr; - if ( NET_StringToAdr( Cmd_Argv(i), &adr ) ) { - SVC_WhitelistAdr( adr ); + if (NET_StringToAdr(Cmd_Argv(i), &adr)) { + SVC_WhitelistAdr(adr); Com_Printf("Added %s to the IP whitelist\n", NET_AdrToString(adr)); } else { Com_Printf("Incorrect IP address: %s\n", Cmd_Argv(i)); @@ -1936,9 +1789,9 @@ static void SV_WhitelistIP_f( void ) { SV_CompleteMapName ================== */ -static void SV_CompleteMapName( char *args, int argNum ) { - if ( argNum == 2 ) - Field_CompleteFilename( "maps", "bsp", qtrue, qfalse ); +static void SV_CompleteMapName(char *args, int argNum) { + if (argNum == 2) + Field_CompleteFilename("maps", "bsp", qtrue, qfalse); } /* @@ -1946,50 +1799,50 @@ static void SV_CompleteMapName( char *args, int argNum ) { SV_AddOperatorCommands ================== */ -void SV_AddOperatorCommands( void ) { - static qboolean initialized; +void SV_AddOperatorCommands(void) { + static qboolean initialized; - if ( initialized ) { + if (initialized) { return; } initialized = qtrue; - Cmd_AddCommand ("heartbeat", SV_Heartbeat_f, "Sends a heartbeat to the masterserver" ); - Cmd_AddCommand ("kick", SV_Kick_f, "Kick a user from the server" ); - Cmd_AddCommand ("kickbots", SV_KickBots_f, "Kick all bots from the server" ); - Cmd_AddCommand ("kickall", SV_KickAll_f, "Kick all users from the server" ); - Cmd_AddCommand ("kicknum", SV_KickNum_f, "Kick a user from the server by userid" ); - Cmd_AddCommand ("clientkick", SV_KickNum_f, "Kick a user from the server by userid" ); - Cmd_AddCommand ("status", SV_Status_f, "Prints status of server and connected clients" ); - Cmd_AddCommand ("serverinfo", SV_Serverinfo_f, "Prints the serverinfo that is visible in the server browsers" ); - Cmd_AddCommand ("systeminfo", SV_Systeminfo_f, "Prints the systeminfo variables that are replicated to clients" ); - Cmd_AddCommand ("dumpuser", SV_DumpUser_f, "Prints the userinfo for a given userid" ); - Cmd_AddCommand ("map_restart", SV_MapRestart_f, "Restart the current map" ); - Cmd_AddCommand ("sectorlist", SV_SectorList_f); - Cmd_AddCommand ("map", SV_Map_f, "Load a new map with cheats disabled" ); - Cmd_SetCommandCompletionFunc( "map", SV_CompleteMapName ); - Cmd_AddCommand ("devmap", SV_Map_f, "Load a new map with cheats enabled" ); - Cmd_SetCommandCompletionFunc( "devmap", SV_CompleteMapName ); -// Cmd_AddCommand ("devmapbsp", SV_Map_f); // not used in MP codebase, no server BSP_cacheing - Cmd_AddCommand ("devmapmdl", SV_Map_f, "Load a new map with cheats enabled" ); - Cmd_SetCommandCompletionFunc( "devmapmdl", SV_CompleteMapName ); - Cmd_AddCommand ("devmapall", SV_Map_f, "Load a new map with cheats enabled" ); - Cmd_SetCommandCompletionFunc( "devmapall", SV_CompleteMapName ); - Cmd_AddCommand ("killserver", SV_KillServer_f, "Shuts the server down and disconnects all clients" ); - Cmd_AddCommand ("svsay", SV_ConSay_f, "Broadcast server messages to clients" ); - Cmd_AddCommand ("svtell", SV_ConTell_f, "Private message from the server to a user" ); - Cmd_AddCommand ("forcetoggle", SV_ForceToggle_f, "Toggle g_forcePowerDisable bits" ); - Cmd_AddCommand ("weapontoggle", SV_WeaponToggle_f, "Toggle g_weaponDisable bits" ); - Cmd_AddCommand ("svrecord", SV_Record_f, "Record a server-side demo" ); - Cmd_AddCommand ("svstoprecord", SV_StopRecord_f, "Stop recording a server-side demo" ); - Cmd_AddCommand ("sv_rehashbans", SV_RehashBans_f, "Reloads banlist from file" ); - Cmd_AddCommand ("sv_listbans", SV_ListBans_f, "Lists bans" ); - Cmd_AddCommand ("sv_banaddr", SV_BanAddr_f, "Bans a user" ); - Cmd_AddCommand ("sv_exceptaddr", SV_ExceptAddr_f, "Adds a ban exception for a user" ); - Cmd_AddCommand ("sv_bandel", SV_BanDel_f, "Removes a ban" ); - Cmd_AddCommand ("sv_exceptdel", SV_ExceptDel_f, "Removes a ban exception" ); - Cmd_AddCommand ("sv_flushbans", SV_FlushBans_f, "Removes all bans and exceptions" ); - Cmd_AddCommand ("whitelistip", SV_WhitelistIP_f, "Add IP to the whitelist" ); + Cmd_AddCommand("heartbeat", SV_Heartbeat_f, "Sends a heartbeat to the masterserver"); + Cmd_AddCommand("kick", SV_Kick_f, "Kick a user from the server"); + Cmd_AddCommand("kickbots", SV_KickBots_f, "Kick all bots from the server"); + Cmd_AddCommand("kickall", SV_KickAll_f, "Kick all users from the server"); + Cmd_AddCommand("kicknum", SV_KickNum_f, "Kick a user from the server by userid"); + Cmd_AddCommand("clientkick", SV_KickNum_f, "Kick a user from the server by userid"); + Cmd_AddCommand("status", SV_Status_f, "Prints status of server and connected clients"); + Cmd_AddCommand("serverinfo", SV_Serverinfo_f, "Prints the serverinfo that is visible in the server browsers"); + Cmd_AddCommand("systeminfo", SV_Systeminfo_f, "Prints the systeminfo variables that are replicated to clients"); + Cmd_AddCommand("dumpuser", SV_DumpUser_f, "Prints the userinfo for a given userid"); + Cmd_AddCommand("map_restart", SV_MapRestart_f, "Restart the current map"); + Cmd_AddCommand("sectorlist", SV_SectorList_f); + Cmd_AddCommand("map", SV_Map_f, "Load a new map with cheats disabled"); + Cmd_SetCommandCompletionFunc("map", SV_CompleteMapName); + Cmd_AddCommand("devmap", SV_Map_f, "Load a new map with cheats enabled"); + Cmd_SetCommandCompletionFunc("devmap", SV_CompleteMapName); + // Cmd_AddCommand ("devmapbsp", SV_Map_f); // not used in MP codebase, no server BSP_cacheing + Cmd_AddCommand("devmapmdl", SV_Map_f, "Load a new map with cheats enabled"); + Cmd_SetCommandCompletionFunc("devmapmdl", SV_CompleteMapName); + Cmd_AddCommand("devmapall", SV_Map_f, "Load a new map with cheats enabled"); + Cmd_SetCommandCompletionFunc("devmapall", SV_CompleteMapName); + Cmd_AddCommand("killserver", SV_KillServer_f, "Shuts the server down and disconnects all clients"); + Cmd_AddCommand("svsay", SV_ConSay_f, "Broadcast server messages to clients"); + Cmd_AddCommand("svtell", SV_ConTell_f, "Private message from the server to a user"); + Cmd_AddCommand("forcetoggle", SV_ForceToggle_f, "Toggle g_forcePowerDisable bits"); + Cmd_AddCommand("weapontoggle", SV_WeaponToggle_f, "Toggle g_weaponDisable bits"); + Cmd_AddCommand("svrecord", SV_Record_f, "Record a server-side demo"); + Cmd_AddCommand("svstoprecord", SV_StopRecord_f, "Stop recording a server-side demo"); + Cmd_AddCommand("sv_rehashbans", SV_RehashBans_f, "Reloads banlist from file"); + Cmd_AddCommand("sv_listbans", SV_ListBans_f, "Lists bans"); + Cmd_AddCommand("sv_banaddr", SV_BanAddr_f, "Bans a user"); + Cmd_AddCommand("sv_exceptaddr", SV_ExceptAddr_f, "Adds a ban exception for a user"); + Cmd_AddCommand("sv_bandel", SV_BanDel_f, "Removes a ban"); + Cmd_AddCommand("sv_exceptdel", SV_ExceptDel_f, "Removes a ban exception"); + Cmd_AddCommand("sv_flushbans", SV_FlushBans_f, "Removes all bans and exceptions"); + Cmd_AddCommand("whitelistip", SV_WhitelistIP_f, "Add IP to the whitelist"); } /* @@ -1997,7 +1850,7 @@ void SV_AddOperatorCommands( void ) { SV_RemoveOperatorCommands ================== */ -void SV_RemoveOperatorCommands( void ) { +void SV_RemoveOperatorCommands(void) { #if 0 // removing these won't let the server start again Cmd_RemoveCommand ("heartbeat"); @@ -2013,4 +1866,3 @@ void SV_RemoveOperatorCommands( void ) { Cmd_RemoveCommand ("svsay"); #endif } - diff --git a/codemp/server/sv_challenge.cpp b/codemp/server/sv_challenge.cpp index 147c48da58..1c7ec5573d 100644 --- a/codemp/server/sv_challenge.cpp +++ b/codemp/server/sv_challenge.cpp @@ -38,8 +38,7 @@ BufferToHexString Format a byte buffer as a lower-case hex string. ==================== */ -static const char *BufferToHexString(byte *buffer, size_t bufferLen) -{ +static const char *BufferToHexString(byte *buffer, size_t bufferLen) { static char hexString[1023]; static const size_t maxBufferLen = (sizeof(hexString) - 1) / 2; static const char *hex = "0123456789abcdef"; @@ -62,8 +61,7 @@ SV_ChallengeInit Initialize the HMAC context for generating challenges. ==================== */ -void SV_ChallengeInit() -{ +void SV_ChallengeInit() { if (challengerInitialized) { SV_ChallengeShutdown(); } @@ -90,8 +88,7 @@ SV_ChallengeShutdown Clear the HMAC context used to generate challenges. ==================== */ -void SV_ChallengeShutdown() -{ +void SV_ChallengeShutdown() { if (challengerInitialized) { memset(&challenger, 0, sizeof(challenger)); challengerInitialized = qfalse; @@ -105,15 +102,14 @@ SV_CreateChallenge (internal) Create a challenge for the given client address and timestamp. ==================== */ -static int SV_CreateChallenge(int timestamp, netadr_t from) -{ +static int SV_CreateChallenge(int timestamp, netadr_t from) { const char *clientParams = NET_AdrToString(from); size_t clientParamsLen = strlen(clientParams); // Create an unforgeable, temporal challenge for this client using HMAC(secretKey, clientParams + timestamp) byte digest[MD5_DIGEST_SIZE]; - HMAC_MD5_Update(&challenger, (byte*)clientParams, clientParamsLen); - HMAC_MD5_Update(&challenger, (byte*)×tamp, sizeof(timestamp)); + HMAC_MD5_Update(&challenger, (byte *)clientParams, clientParamsLen); + HMAC_MD5_Update(&challenger, (byte *)×tamp, sizeof(timestamp)); HMAC_MD5_Final(&challenger, digest); HMAC_MD5_Reset(&challenger); @@ -126,8 +122,8 @@ static int SV_CreateChallenge(int timestamp, netadr_t from) challenge |= (unsigned int)(timestamp & 0x1) << 31; #ifdef DEBUG_SV_CHALLENGE - if ( com_developer->integer ) { - Com_Printf( "Generated challenge %d (timestamp = %d) for %s\n", challenge, timestamp, NET_AdrToString( from ) ); + if (com_developer->integer) { + Com_Printf("Generated challenge %d (timestamp = %d) for %s\n", challenge, timestamp, NET_AdrToString(from)); } #endif @@ -141,8 +137,7 @@ SV_CreateChallenge Create an unforgeable, temporal challenge for the given client address. ==================== */ -int SV_CreateChallenge(netadr_t from) -{ +int SV_CreateChallenge(netadr_t from) { if (!challengerInitialized) { Com_Error(ERR_FATAL, "SV_CreateChallenge: The challenge subsystem has not been initialized"); } @@ -160,8 +155,7 @@ SV_VerifyChallenge Verify a challenge received by the client matches the expected challenge. ==================== */ -qboolean SV_VerifyChallenge(int receivedChallenge, netadr_t from) -{ +qboolean SV_VerifyChallenge(int receivedChallenge, netadr_t from) { if (!challengerInitialized) { Com_Error(ERR_FATAL, "SV_VerifyChallenge: The challenge subsystem has not been initialized"); } @@ -176,8 +170,8 @@ qboolean SV_VerifyChallenge(int receivedChallenge, netadr_t from) int challengeTimestamp = currentTimestamp - (currentPeriod ^ challengePeriod); #ifdef DEBUG_SV_CHALLENGE - if ( com_developer->integer ) { - Com_Printf( "Verifying challenge %d (timestamp = %d) for %s\n", receivedChallenge, challengeTimestamp, NET_AdrToString( from ) ); + if (com_developer->integer) { + Com_Printf("Verifying challenge %d (timestamp = %d) for %s\n", receivedChallenge, challengeTimestamp, NET_AdrToString(from)); } #endif diff --git a/codemp/server/sv_client.cpp b/codemp/server/sv_client.cpp index 073fbbe6a4..ee1014128d 100644 --- a/codemp/server/sv_client.cpp +++ b/codemp/server/sv_client.cpp @@ -35,7 +35,7 @@ along with this program; if not, see . #include "server/sv_gameapi.h" -static void SV_CloseDownload( client_t *cl ); +static void SV_CloseDownload(client_t *cl); /* ================= @@ -59,9 +59,9 @@ to their packets, to make it more difficult for malicious servers to hi-jack client connections. ================= */ -void SV_GetChallenge( netadr_t from ) { - int challenge; - int clientChallenge; +void SV_GetChallenge(netadr_t from) { + int challenge; + int clientChallenge; // ignore if we are in single player /* @@ -69,8 +69,7 @@ void SV_GetChallenge( netadr_t from ) { return; } */ - if (Cvar_VariableValue("ui_singlePlayerActive")) - { + if (Cvar_VariableValue("ui_singlePlayerActive")) { return; } @@ -80,7 +79,7 @@ void SV_GetChallenge( netadr_t from ) { // Grab the client's challenge to echo back (if given) clientChallenge = atoi(Cmd_Argv(1)); - NET_OutOfBandPrint( NS_SERVER, from, "challengeResponse %i %i", challenge, clientChallenge ); + NET_OutOfBandPrint(NS_SERVER, from, "challengeResponse %i %i", challenge, clientChallenge); } /* @@ -91,29 +90,25 @@ Check whether a certain address is banned ================== */ -static qboolean SV_IsBanned( netadr_t *from, qboolean isexception ) -{ +static qboolean SV_IsBanned(netadr_t *from, qboolean isexception) { int index; serverBan_t *curban; - if ( !serverBansCount ) { + if (!serverBansCount) { return qfalse; } - if ( !isexception ) - { + if (!isexception) { // If this is a query for a ban, first check whether the client is excepted - if ( SV_IsBanned( from, qtrue ) ) + if (SV_IsBanned(from, qtrue)) return qfalse; } - for ( index = 0; index < serverBansCount; index++ ) - { + for (index = 0; index < serverBansCount; index++) { curban = &serverBans[index]; - if ( curban->isexception == isexception ) - { - if ( NET_CompareBaseAdrMask( curban->ip, *from, curban->subnet ) ) + if (curban->isexception == isexception) { + if (NET_CompareBaseAdrMask(curban->ip, *from, curban->subnet)) return qtrue; } } @@ -128,63 +123,59 @@ SV_DirectConnect A "connect" OOB command has been received ================== */ -void SV_DirectConnect( netadr_t from ) { - char userinfo[MAX_INFO_STRING]; - int i; - client_t *cl, *newcl; - client_t temp; +void SV_DirectConnect(netadr_t from) { + char userinfo[MAX_INFO_STRING]; + int i; + client_t *cl, *newcl; + client_t temp; sharedEntity_t *ent; - int clientNum; - int version; - int qport; - int challenge; - char *password; - int startIndex; - char *denied; - int count; - char *ip; - - Com_DPrintf ("SVC_DirectConnect ()\n"); + int clientNum; + int version; + int qport; + int challenge; + char *password; + int startIndex; + char *denied; + int count; + char *ip; + + Com_DPrintf("SVC_DirectConnect ()\n"); // Check whether this client is banned. - if ( SV_IsBanned( &from, qfalse ) ) - { - NET_OutOfBandPrint( NS_SERVER, from, "print\nYou are banned from this server.\n" ); - Com_DPrintf( " rejected connect from %s (banned)\n", NET_AdrToString(from) ); + if (SV_IsBanned(&from, qfalse)) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nYou are banned from this server.\n"); + Com_DPrintf(" rejected connect from %s (banned)\n", NET_AdrToString(from)); return; } - Q_strncpyz( userinfo, Cmd_Argv(1), sizeof(userinfo) ); + Q_strncpyz(userinfo, Cmd_Argv(1), sizeof(userinfo)); - version = atoi( Info_ValueForKey( userinfo, "protocol" ) ); - if ( version != PROTOCOL_VERSION ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\nServer uses protocol version %i (yours is %i).\n", PROTOCOL_VERSION, version ); - Com_DPrintf (" rejected connect from version %i\n", version); + version = atoi(Info_ValueForKey(userinfo, "protocol")); + if (version != PROTOCOL_VERSION) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nServer uses protocol version %i (yours is %i).\n", PROTOCOL_VERSION, version); + Com_DPrintf(" rejected connect from version %i\n", version); return; } - challenge = atoi( Info_ValueForKey( userinfo, "challenge" ) ); - qport = atoi( Info_ValueForKey( userinfo, "qport" ) ); + challenge = atoi(Info_ValueForKey(userinfo, "challenge")); + qport = atoi(Info_ValueForKey(userinfo, "qport")); // quick reject - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { -/* This was preventing sv_reconnectlimit from working. It seems like commenting this - out has solved the problem. HOwever, if there is a future problem then it could - be this. + /* This was preventing sv_reconnectlimit from working. It seems like commenting this + out has solved the problem. HOwever, if there is a future problem then it could + be this. - if ( cl->state == CS_FREE ) { - continue; - } -*/ + if ( cl->state == CS_FREE ) { + continue; + } + */ - if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) - && ( cl->netchan.qport == qport - || from.port == cl->netchan.remoteAddress.port ) ) { - if (( svs.time - cl->lastConnectTime) - < (sv_reconnectlimit->integer * 1000)) { - NET_OutOfBandPrint( NS_SERVER, from, "print\nReconnect rejected : too soon\n" ); - Com_DPrintf ("%s:reconnect rejected : too soon\n", NET_AdrToString (from)); + if (NET_CompareBaseAdr(from, cl->netchan.remoteAddress) && (cl->netchan.qport == qport || from.port == cl->netchan.remoteAddress.port)) { + if ((svs.time - cl->lastConnectTime) < (sv_reconnectlimit->integer * 1000)) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nReconnect rejected : too soon\n"); + Com_DPrintf("%s:reconnect rejected : too soon\n", NET_AdrToString(from)); return; } break; @@ -192,46 +183,42 @@ void SV_DirectConnect( netadr_t from ) { } // don't let "ip" overflow userinfo string - if ( NET_IsLocalAddress (from) ) + if (NET_IsLocalAddress(from)) ip = "localhost"; else - ip = (char *)NET_AdrToString( from ); - if( ( strlen( ip ) + strlen( userinfo ) + 4 ) >= MAX_INFO_STRING ) { - NET_OutOfBandPrint( NS_SERVER, from, - "print\nUserinfo string length exceeded. " - "Try removing setu cvars from your config.\n" ); + ip = (char *)NET_AdrToString(from); + if ((strlen(ip) + strlen(userinfo) + 4) >= MAX_INFO_STRING) { + NET_OutOfBandPrint(NS_SERVER, from, + "print\nUserinfo string length exceeded. " + "Try removing setu cvars from your config.\n"); return; } - Info_SetValueForKey( userinfo, "ip", ip ); + Info_SetValueForKey(userinfo, "ip", ip); // see if the challenge is valid (localhost clients don't need to challenge) - if (!NET_IsLocalAddress(from)) - { + if (!NET_IsLocalAddress(from)) { // Verify the received challenge against the expected challenge - if (!SV_VerifyChallenge(challenge, from)) - { - NET_OutOfBandPrint( NS_SERVER, from, "print\nIncorrect challenge for your address.\n" ); + if (!SV_VerifyChallenge(challenge, from)) { + NET_OutOfBandPrint(NS_SERVER, from, "print\nIncorrect challenge for your address.\n"); return; } } newcl = &temp; - Com_Memset (newcl, 0, sizeof(client_t)); + Com_Memset(newcl, 0, sizeof(client_t)); // if there is already a slot for this ip, reuse it - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { - if ( cl->state == CS_FREE ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (cl->state == CS_FREE) { continue; } - if ( NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) - && ( cl->netchan.qport == qport - || from.port == cl->netchan.remoteAddress.port ) ) { - Com_Printf ("%s:reconnect\n", NET_AdrToString (from)); + if (NET_CompareBaseAdr(from, cl->netchan.remoteAddress) && (cl->netchan.qport == qport || from.port == cl->netchan.remoteAddress.port)) { + Com_Printf("%s:reconnect\n", NET_AdrToString(from)); newcl = cl; // VVFIXME - both SOF2 and Wolf remove this call, claiming it blows away the user's info // disconnect the client from the game first so any flags the // player might have are dropped - GVM_ClientDisconnect( newcl - svs.clients ); + GVM_ClientDisconnect(newcl - svs.clients); // goto gotnewcl; } @@ -248,8 +235,8 @@ void SV_DirectConnect( netadr_t from ) { // servers so we can play without having to kick people. // check for privateClient password - password = Info_ValueForKey( userinfo, "password" ); - if ( !strcmp( password, sv_privatePassword->string ) ) { + password = Info_ValueForKey(userinfo, "password"); + if (!strcmp(password, sv_privatePassword->string)) { startIndex = 0; } else { // skip past the reserved slots @@ -257,7 +244,7 @@ void SV_DirectConnect( netadr_t from ) { } newcl = NULL; - for ( i = startIndex; i < sv_maxclients->integer ; i++ ) { + for (i = startIndex; i < sv_maxclients->integer; i++) { cl = &svs.clients[i]; if (cl->state == CS_FREE) { newcl = cl; @@ -265,10 +252,10 @@ void SV_DirectConnect( netadr_t from ) { } } - if ( !newcl ) { - if ( NET_IsLocalAddress( from ) ) { + if (!newcl) { + if (NET_IsLocalAddress(from)) { count = 0; - for ( i = startIndex; i < sv_maxclients->integer ; i++ ) { + for (i = startIndex; i < sv_maxclients->integer; i++) { cl = &svs.clients[i]; if (cl->netchan.remoteAddress.type == NA_BOT) { count++; @@ -278,16 +265,14 @@ void SV_DirectConnect( netadr_t from ) { if (count >= sv_maxclients->integer - startIndex) { SV_DropClient(&svs.clients[sv_maxclients->integer - 1], "only bots on server"); newcl = &svs.clients[sv_maxclients->integer - 1]; - } - else { - Com_Error( ERR_FATAL, "server is full on local connect\n" ); + } else { + Com_Error(ERR_FATAL, "server is full on local connect\n"); return; } - } - else { + } else { const char *SV_GetStringEdString(char *refSection, char *refName); - NET_OutOfBandPrint( NS_SERVER, from, va("print\n%s\n", SV_GetStringEdString("MP_SVGAME","SERVER_IS_FULL"))); - Com_DPrintf ("Rejected a connection.\n"); + NET_OutOfBandPrint(NS_SERVER, from, va("print\n%s\n", SV_GetStringEdString("MP_SVGAME", "SERVER_IS_FULL"))); + Com_DPrintf("Rejected a connection.\n"); return; } } @@ -303,32 +288,32 @@ void SV_DirectConnect( netadr_t from ) { // this is the only place a client_t is ever initialized *newcl = temp; clientNum = newcl - svs.clients; - ent = SV_GentityNum( clientNum ); + ent = SV_GentityNum(clientNum); newcl->gentity = ent; // save the challenge newcl->challenge = challenge; // save the address - Netchan_Setup (NS_SERVER, &newcl->netchan , from, qport); + Netchan_Setup(NS_SERVER, &newcl->netchan, from, qport); // save the userinfo - Q_strncpyz( newcl->userinfo, userinfo, sizeof(newcl->userinfo) ); + Q_strncpyz(newcl->userinfo, userinfo, sizeof(newcl->userinfo)); // get the game a chance to reject this connection or modify the userinfo - denied = GVM_ClientConnect( clientNum, qtrue, qfalse ); // firstTime = qtrue - if ( denied ) { - NET_OutOfBandPrint( NS_SERVER, from, "print\n%s\n", denied ); - Com_DPrintf ("Game rejected a connection: %s.\n", denied); + denied = GVM_ClientConnect(clientNum, qtrue, qfalse); // firstTime = qtrue + if (denied) { + NET_OutOfBandPrint(NS_SERVER, from, "print\n%s\n", denied); + Com_DPrintf("Game rejected a connection: %s.\n", denied); return; } - SV_UserinfoChanged( newcl ); + SV_UserinfoChanged(newcl); // send the connect packet to the client - NET_OutOfBandPrint( NS_SERVER, from, "connectResponse" ); + NET_OutOfBandPrint(NS_SERVER, from, "connectResponse"); - Com_DPrintf( "Going from CS_FREE to CS_CONNECTED for %s\n", newcl->name ); + Com_DPrintf("Going from CS_FREE to CS_CONNECTED for %s\n", newcl->name); newcl->state = CS_CONNECTED; newcl->nextSnapshotTime = svs.time; @@ -340,23 +325,22 @@ void SV_DirectConnect( netadr_t from ) { // gamestate message was not just sent, forcing a retransmit newcl->gamestateMessageNum = -1; - newcl->lastUserInfoChange = 0; //reset the delay - newcl->lastUserInfoCount = 0; //reset the count + newcl->lastUserInfoChange = 0; // reset the delay + newcl->lastUserInfoCount = 0; // reset the count // if this was the first client on the server, or the last client // the server can hold, send a heartbeat to the master. count = 0; - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (svs.clients[i].state >= CS_CONNECTED) { count++; } } - if ( count == 1 || count == sv_maxclients->integer ) { + if (count == 1 || count == sv_maxclients->integer) { SV_Heartbeat_f(); } } - /* ===================== SV_DropClient @@ -366,107 +350,107 @@ or unwillingly. This is NOT called if the entire server is quiting or crashing -- SV_FinalMessage() will handle that ===================== */ -void SV_DropClient( client_t *drop, const char *reason ) { - int i; +void SV_DropClient(client_t *drop, const char *reason) { + int i; const bool isBot = drop->netchan.remoteAddress.type == NA_BOT; - if ( drop->state == CS_ZOMBIE ) { - return; // already dropped + if (drop->state == CS_ZOMBIE) { + return; // already dropped } // Kill any download - SV_CloseDownload( drop ); + SV_CloseDownload(drop); // tell everyone why they got dropped - SV_SendServerCommand( NULL, "print \"%s" S_COLOR_WHITE " %s\n\"", drop->name, reason ); + SV_SendServerCommand(NULL, "print \"%s" S_COLOR_WHITE " %s\n\"", drop->name, reason); // call the prog function for removing a client // this will remove the body, among other things - GVM_ClientDisconnect( drop - svs.clients ); + GVM_ClientDisconnect(drop - svs.clients); // add the disconnect command - SV_SendServerCommand( drop, "disconnect \"%s\"", reason ); + SV_SendServerCommand(drop, "disconnect \"%s\"", reason); - if ( isBot ) { - SV_BotFreeClient( drop - svs.clients ); + if (isBot) { + SV_BotFreeClient(drop - svs.clients); } // nuke user info - SV_SetUserinfo( drop - svs.clients, "" ); + SV_SetUserinfo(drop - svs.clients, ""); - if ( isBot ) { + if (isBot) { // bots shouldn't go zombie, as there's no real net connection. drop->state = CS_FREE; } else { - Com_DPrintf( "Going to CS_ZOMBIE for %s\n", drop->name ); - drop->state = CS_ZOMBIE; // become free in a few seconds + Com_DPrintf("Going to CS_ZOMBIE for %s\n", drop->name); + drop->state = CS_ZOMBIE; // become free in a few seconds } - if ( drop->demo.demorecording ) { - SV_StopRecordDemo( drop ); + if (drop->demo.demorecording) { + SV_StopRecordDemo(drop); } // if this was the last client on the server, send a heartbeat // to the master so it is known the server is empty // send a heartbeat now so the master will get up to date info // if there is already a slot for this ip, reuse it - for (i=0 ; i < sv_maxclients->integer ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = 0; i < sv_maxclients->integer; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { break; } } - if ( i == sv_maxclients->integer ) { + if (i == sv_maxclients->integer) { SV_Heartbeat_f(); } } -void SV_CreateClientGameStateMessage( client_t *client, msg_t *msg ) { - int start; - entityState_t *base, nullstate; +void SV_CreateClientGameStateMessage(client_t *client, msg_t *msg) { + int start; + entityState_t *base, nullstate; // NOTE, MRE: all server->client messages now acknowledge // let the client know which reliable clientCommands we have received - MSG_WriteLong( msg, client->lastClientCommand ); + MSG_WriteLong(msg, client->lastClientCommand); // send any server commands waiting to be sent first. // we have to do this cause we send the client->reliableSequence // with a gamestate and it sets the clc.serverCommandSequence at // the client side - SV_UpdateServerCommandsToClient( client, msg ); + SV_UpdateServerCommandsToClient(client, msg); // send the gamestate - MSG_WriteByte( msg, svc_gamestate ); - MSG_WriteLong( msg, client->reliableSequence ); + MSG_WriteByte(msg, svc_gamestate); + MSG_WriteLong(msg, client->reliableSequence); // write the configstrings - for ( start = 0 ; start < MAX_CONFIGSTRINGS ; start++ ) { + for (start = 0; start < MAX_CONFIGSTRINGS; start++) { if (sv.configstrings[start][0]) { - MSG_WriteByte( msg, svc_configstring ); - MSG_WriteShort( msg, start ); - MSG_WriteBigString( msg, sv.configstrings[start] ); + MSG_WriteByte(msg, svc_configstring); + MSG_WriteShort(msg, start); + MSG_WriteBigString(msg, sv.configstrings[start]); } } // write the baselines - Com_Memset( &nullstate, 0, sizeof( nullstate ) ); - for ( start = 0 ; start < MAX_GENTITIES; start++ ) { + Com_Memset(&nullstate, 0, sizeof(nullstate)); + for (start = 0; start < MAX_GENTITIES; start++) { base = &sv.svEntities[start].baseline; - if ( !base->number ) { + if (!base->number) { continue; } - MSG_WriteByte( msg, svc_baseline ); - MSG_WriteDeltaEntity( msg, &nullstate, base, qtrue ); + MSG_WriteByte(msg, svc_baseline); + MSG_WriteDeltaEntity(msg, &nullstate, base, qtrue); } - MSG_WriteByte( msg, svc_EOF ); + MSG_WriteByte(msg, svc_EOF); - MSG_WriteLong( msg, client - svs.clients); + MSG_WriteLong(msg, client - svs.clients); // write the checksum feed - MSG_WriteLong( msg, sv.checksumFeed); + MSG_WriteLong(msg, sv.checksumFeed); // For old RMG system. - MSG_WriteShort ( msg, 0 ); + MSG_WriteShort(msg, 0); } /* @@ -480,26 +464,25 @@ It will be resent if the client acknowledges a later message but has the wrong gamestate. ================ */ -void SV_SendClientGameState( client_t *client ) { - msg_t msg; - byte msgBuffer[MAX_MSGLEN]; +void SV_SendClientGameState(client_t *client) { + msg_t msg; + byte msgBuffer[MAX_MSGLEN]; - MSG_Init( &msg, msgBuffer, sizeof( msgBuffer ) ); + MSG_Init(&msg, msgBuffer, sizeof(msgBuffer)); // MW - my attempt to fix illegible server message errors caused by // packet fragmentation of initial snapshot. - while(client->state&&client->netchan.unsentFragments) - { + while (client->state && client->netchan.unsentFragments) { // send additional message fragments if the last message // was too large to send at once - Com_Printf ("[ISM]SV_SendClientGameState() [2] for %s, writing out old fragments\n", client->name); + Com_Printf("[ISM]SV_SendClientGameState() [2] for %s, writing out old fragments\n", client->name); SV_Netchan_TransmitNextFragment(&client->netchan); } - Com_DPrintf ("SV_SendClientGameState() for %s\n", client->name); - Com_DPrintf( "Going from CS_CONNECTED to CS_PRIMED for %s\n", client->name ); - if ( client->state == CS_CONNECTED ) + Com_DPrintf("SV_SendClientGameState() for %s\n", client->name); + Com_DPrintf("Going from CS_CONNECTED to CS_PRIMED for %s\n", client->name); + if (client->state == CS_CONNECTED) client->state = CS_PRIMED; client->pureAuthentic = 0; client->gotCP = qfalse; @@ -509,35 +492,33 @@ void SV_SendClientGameState( client_t *client ) { // gamestate message was not just sent, forcing a retransmit client->gamestateMessageNum = client->netchan.outgoingSequence; - SV_CreateClientGameStateMessage( client, &msg ); + SV_CreateClientGameStateMessage(client, &msg); // deliver this to the client - SV_SendMessageToClient( &msg, client ); + SV_SendMessageToClient(&msg, client); } +void SV_SendClientMapChange(client_t *client) { + msg_t msg; + byte msgBuffer[MAX_MSGLEN]; -void SV_SendClientMapChange( client_t *client ) -{ - msg_t msg; - byte msgBuffer[MAX_MSGLEN]; - - MSG_Init( &msg, msgBuffer, sizeof( msgBuffer ) ); + MSG_Init(&msg, msgBuffer, sizeof(msgBuffer)); // NOTE, MRE: all server->client messages now acknowledge // let the client know which reliable clientCommands we have received - MSG_WriteLong( &msg, client->lastClientCommand ); + MSG_WriteLong(&msg, client->lastClientCommand); // send any server commands waiting to be sent first. // we have to do this cause we send the client->reliableSequence // with a gamestate and it sets the clc.serverCommandSequence at // the client side - SV_UpdateServerCommandsToClient( client, &msg ); + SV_UpdateServerCommandsToClient(client, &msg); // send the gamestate - MSG_WriteByte( &msg, svc_mapchange ); + MSG_WriteByte(&msg, svc_mapchange); // deliver this to the client - SV_SendMessageToClient( &msg, client ); + SV_SendMessageToClient(&msg, client); } /* @@ -545,40 +526,40 @@ void SV_SendClientMapChange( client_t *client ) SV_ClientEnterWorld ================== */ -void SV_ClientEnterWorld( client_t *client, usercmd_t *cmd ) { - int clientNum; +void SV_ClientEnterWorld(client_t *client, usercmd_t *cmd) { + int clientNum; sharedEntity_t *ent; - Com_DPrintf( "Going from CS_PRIMED to CS_ACTIVE for %s\n", client->name ); + Com_DPrintf("Going from CS_PRIMED to CS_ACTIVE for %s\n", client->name); client->state = CS_ACTIVE; if (sv_autoWhitelist->integer) { - SVC_WhitelistAdr( client->netchan.remoteAddress ); + SVC_WhitelistAdr(client->netchan.remoteAddress); } // resend all configstrings using the cs commands since these are // no longer sent when the client is CS_PRIMED - SV_UpdateConfigstrings( client ); + SV_UpdateConfigstrings(client); // set up the entity for the client clientNum = client - svs.clients; - ent = SV_GentityNum( clientNum ); + ent = SV_GentityNum(clientNum); ent->s.number = clientNum; client->gentity = ent; - client->lastUserInfoChange = 0; //reset the delay - client->lastUserInfoCount = 0; //reset the count + client->lastUserInfoChange = 0; // reset the delay + client->lastUserInfoCount = 0; // reset the count client->deltaMessage = -1; - client->nextSnapshotTime = svs.time; // generate a snapshot immediately + client->nextSnapshotTime = svs.time; // generate a snapshot immediately - if(cmd) + if (cmd) memcpy(&client->lastUsercmd, cmd, sizeof(client->lastUsercmd)); else memset(&client->lastUsercmd, '\0', sizeof(client->lastUsercmd)); // call the game begin function - GVM_ClientBegin( client - svs.clients ); + GVM_ClientBegin(client - svs.clients); SV_BeginAutoRecordDemos(); } @@ -598,12 +579,12 @@ SV_CloseDownload clear/free any download vars ================== */ -static void SV_CloseDownload( client_t *cl ) { +static void SV_CloseDownload(client_t *cl) { int i; // EOF if (cl->download) { - FS_FCloseFile( cl->download ); + FS_FCloseFile(cl->download); } cl->download = 0; *cl->downloadName = 0; @@ -611,11 +592,10 @@ static void SV_CloseDownload( client_t *cl ) { // Free the temporary buffer space for (i = 0; i < MAX_DOWNLOAD_WINDOW; i++) { if (cl->downloadBlocks[i]) { - Z_Free( cl->downloadBlocks[i] ); + Z_Free(cl->downloadBlocks[i]); cl->downloadBlocks[i] = NULL; } } - } /* @@ -625,14 +605,14 @@ SV_StopDownload_f Abort a download if in progress ================== */ -static void SV_StopDownload_f( client_t *cl ) { - if ( cl->state == CS_ACTIVE ) +static void SV_StopDownload_f(client_t *cl) { + if (cl->state == CS_ACTIVE) return; if (*cl->downloadName) - Com_DPrintf( "clientDownload: %d : file \"%s\" aborted\n", cl - svs.clients, cl->downloadName ); + Com_DPrintf("clientDownload: %d : file \"%s\" aborted\n", cl - svs.clients, cl->downloadName); - SV_CloseDownload( cl ); + SV_CloseDownload(cl); } /* @@ -642,11 +622,11 @@ SV_DoneDownload_f Downloads are finished ================== */ -static void SV_DoneDownload_f( client_t *cl ) { - if ( cl->state == CS_ACTIVE ) +static void SV_DoneDownload_f(client_t *cl) { + if (cl->state == CS_ACTIVE) return; - Com_DPrintf( "clientDownload: %s Done\n", cl->name); + Com_DPrintf("clientDownload: %s Done\n", cl->name); // resend the game state to update any clients that entered during the download SV_SendClientGameState(cl); } @@ -659,20 +639,19 @@ The argument will be the last acknowledged block from the client, it should be the same as cl->downloadClientBlock ================== */ -static void SV_NextDownload_f( client_t *cl ) -{ - int block = atoi( Cmd_Argv(1) ); +static void SV_NextDownload_f(client_t *cl) { + int block = atoi(Cmd_Argv(1)); - if ( cl->state == CS_ACTIVE ) + if (cl->state == CS_ACTIVE) return; if (block == cl->downloadClientBlock) { - Com_DPrintf( "clientDownload: %d : client acknowledge of block %d\n", cl - svs.clients, block ); + Com_DPrintf("clientDownload: %d : client acknowledge of block %d\n", cl - svs.clients, block); // Find out if we are done. A zero-length block indicates EOF if (cl->downloadBlockSize[cl->downloadClientBlock % MAX_DOWNLOAD_WINDOW] == 0) { - Com_Printf( "clientDownload: %d : file \"%s\" completed\n", cl - svs.clients, cl->downloadName ); - SV_CloseDownload( cl ); + Com_Printf("clientDownload: %d : file \"%s\" completed\n", cl - svs.clients, cl->downloadName); + SV_CloseDownload(cl); return; } @@ -683,7 +662,7 @@ static void SV_NextDownload_f( client_t *cl ) // We aren't getting an acknowledge for the correct block, drop the client // FIXME: this is bad... the client will never parse the disconnect message // because the cgame isn't loaded yet - SV_DropClient( cl, "broken download" ); + SV_DropClient(cl, "broken download"); } /* @@ -691,16 +670,16 @@ static void SV_NextDownload_f( client_t *cl ) SV_BeginDownload_f ================== */ -static void SV_BeginDownload_f( client_t *cl ) { - if ( cl->state == CS_ACTIVE ) +static void SV_BeginDownload_f(client_t *cl) { + if (cl->state == CS_ACTIVE) return; // Kill any existing download - SV_CloseDownload( cl ); + SV_CloseDownload(cl); // cl->downloadName is non-zero now, SV_WriteDownloadToClient will see this and open // the file itself - Q_strncpyz( cl->downloadName, Cmd_Argv(1), sizeof(cl->downloadName) ); + Q_strncpyz(cl->downloadName, Cmd_Argv(1), sizeof(cl->downloadName)); } /* @@ -711,8 +690,7 @@ Check to see if the client wants a file, open it if needed and start pumping the Fill up msg with data ================== */ -void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) -{ +void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) { int curindex; int rate; int blockspersnap; @@ -722,24 +700,21 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) int numRefPaks; if (!*cl->downloadName) - return; // Nothing being downloaded + return; // Nothing being downloaded - if(!cl->download) - { + if (!cl->download) { qboolean idPack = qfalse; qboolean missionPack = qfalse; - // Chop off filename extension. + // Chop off filename extension. Com_sprintf(pakbuf, sizeof(pakbuf), "%s", cl->downloadName); pakptr = strrchr(pakbuf, '.'); - if(pakptr) - { + if (pakptr) { *pakptr = '\0'; // Check for pk3 filename extension - if(!Q_stricmp(pakptr + 1, "pk3")) - { + if (!Q_stricmp(pakptr + 1, "pk3")) { const char *referencedPaks = FS_ReferencedPakNames(); // Check whether the file appears in the list of referenced @@ -747,10 +722,8 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) Cmd_TokenizeStringIgnoreQuotes(referencedPaks); numRefPaks = Cmd_Argc(); - for(curindex = 0; curindex < numRefPaks; curindex++) - { - if(!FS_FilenameCompare(Cmd_Argv(curindex), pakbuf)) - { + for (curindex = 0; curindex < numRefPaks; curindex++) { + if (!FS_FilenameCompare(Cmd_Argv(curindex), pakbuf)) { unreferenced = 0; // now that we know the file is referenced, @@ -768,59 +741,57 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) cl->download = 0; // We open the file here - if ( !sv_allowDownload->integer || - idPack || unreferenced || - ( cl->downloadSize = FS_SV_FOpenFileRead( cl->downloadName, &cl->download ) ) < 0 ) { + if (!sv_allowDownload->integer || idPack || unreferenced || (cl->downloadSize = FS_SV_FOpenFileRead(cl->downloadName, &cl->download)) < 0) { // cannot auto-download file - if(unreferenced) - { - Com_Printf("clientDownload: %d : \"%s\" is not referenced and cannot be downloaded.\n", (int) (cl - svs.clients), cl->downloadName); + if (unreferenced) { + Com_Printf("clientDownload: %d : \"%s\" is not referenced and cannot be downloaded.\n", (int)(cl - svs.clients), cl->downloadName); Com_sprintf(errorMessage, sizeof(errorMessage), "File \"%s\" is not referenced and cannot be downloaded.", cl->downloadName); - } - else if (idPack) { - Com_Printf("clientDownload: %d : \"%s\" cannot download id pk3 files\n", (int) (cl - svs.clients), cl->downloadName); - if(missionPack) - { - Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload Team Arena file \"%s\"\n" - "The Team Arena mission pack can be found in your local game store.", cl->downloadName); - } - else - { + } else if (idPack) { + Com_Printf("clientDownload: %d : \"%s\" cannot download id pk3 files\n", (int)(cl - svs.clients), cl->downloadName); + if (missionPack) { + Com_sprintf(errorMessage, sizeof(errorMessage), + "Cannot autodownload Team Arena file \"%s\"\n" + "The Team Arena mission pack can be found in your local game store.", + cl->downloadName); + } else { Com_sprintf(errorMessage, sizeof(errorMessage), "Cannot autodownload id pk3 file \"%s\"", cl->downloadName); } - } - else if ( !sv_allowDownload->integer ) { - Com_Printf("clientDownload: %d : \"%s\" download disabled\n", (int) (cl - svs.clients), cl->downloadName); + } else if (!sv_allowDownload->integer) { + Com_Printf("clientDownload: %d : \"%s\" download disabled\n", (int)(cl - svs.clients), cl->downloadName); if (sv_pure->integer) { - Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n" - "You will need to get this file elsewhere before you " - "can connect to this pure server.\n", cl->downloadName); + Com_sprintf(errorMessage, sizeof(errorMessage), + "Could not download \"%s\" because autodownloading is disabled on the server.\n\n" + "You will need to get this file elsewhere before you " + "can connect to this pure server.\n", + cl->downloadName); } else { - Com_sprintf(errorMessage, sizeof(errorMessage), "Could not download \"%s\" because autodownloading is disabled on the server.\n\n" - "The server you are connecting to is not a pure server, " - "set autodownload to No in your settings and you might be " - "able to join the game anyway.\n", cl->downloadName); + Com_sprintf(errorMessage, sizeof(errorMessage), + "Could not download \"%s\" because autodownloading is disabled on the server.\n\n" + "The server you are connecting to is not a pure server, " + "set autodownload to No in your settings and you might be " + "able to join the game anyway.\n", + cl->downloadName); } } else { - // NOTE TTimo this is NOT supposed to happen unless bug in our filesystem scheme? - // if the pk3 is referenced, it must have been found somewhere in the filesystem - Com_Printf("clientDownload: %d : \"%s\" file not found on server\n", (int) (cl - svs.clients), cl->downloadName); + // NOTE TTimo this is NOT supposed to happen unless bug in our filesystem scheme? + // if the pk3 is referenced, it must have been found somewhere in the filesystem + Com_Printf("clientDownload: %d : \"%s\" file not found on server\n", (int)(cl - svs.clients), cl->downloadName); Com_sprintf(errorMessage, sizeof(errorMessage), "File \"%s\" not found on server for autodownloading.\n", cl->downloadName); } - MSG_WriteByte( msg, svc_download ); - MSG_WriteShort( msg, 0 ); // client is expecting block zero - MSG_WriteLong( msg, -1 ); // illegal file size - MSG_WriteString( msg, errorMessage ); + MSG_WriteByte(msg, svc_download); + MSG_WriteShort(msg, 0); // client is expecting block zero + MSG_WriteLong(msg, -1); // illegal file size + MSG_WriteString(msg, errorMessage); *cl->downloadName = 0; - if(cl->download) + if (cl->download) FS_FCloseFile(cl->download); return; } - Com_Printf( "clientDownload: %d : beginning \"%s\"\n", (int) (cl - svs.clients), cl->downloadName ); + Com_Printf("clientDownload: %d : beginning \"%s\"\n", (int)(cl - svs.clients), cl->downloadName); // Init cl->downloadCurrentBlock = cl->downloadClientBlock = cl->downloadXmitBlock = 0; @@ -829,15 +800,14 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) } // Perform any reads that we need to - while (cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW && - cl->downloadSize != cl->downloadCount) { + while (cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW && cl->downloadSize != cl->downloadCount) { curindex = (cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW); if (!cl->downloadBlocks[curindex]) - cl->downloadBlocks[curindex] = (unsigned char *)Z_Malloc( MAX_DOWNLOAD_BLKSIZE, TAG_DOWNLOAD, qtrue ); + cl->downloadBlocks[curindex] = (unsigned char *)Z_Malloc(MAX_DOWNLOAD_BLKSIZE, TAG_DOWNLOAD, qtrue); - cl->downloadBlockSize[curindex] = FS_Read( cl->downloadBlocks[curindex], MAX_DOWNLOAD_BLKSIZE, cl->download ); + cl->downloadBlockSize[curindex] = FS_Read(cl->downloadBlocks[curindex], MAX_DOWNLOAD_BLKSIZE, cl->download); if (cl->downloadBlockSize[curindex] < 0) { // EOF right now @@ -852,14 +822,12 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) } // Check to see if we have eof condition and add the EOF block - if (cl->downloadCount == cl->downloadSize && - !cl->downloadEOF && - cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW) { + if (cl->downloadCount == cl->downloadSize && !cl->downloadEOF && cl->downloadCurrentBlock - cl->downloadClientBlock < MAX_DOWNLOAD_WINDOW) { cl->downloadBlockSize[cl->downloadCurrentBlock % MAX_DOWNLOAD_WINDOW] = 0; cl->downloadCurrentBlock++; - cl->downloadEOF = qtrue; // We have added the EOF block + cl->downloadEOF = qtrue; // We have added the EOF block } // Loop up to window size times based on how many blocks we can fit in the @@ -868,11 +836,11 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) // based on the rate, how many bytes can we fit in the snapMsec time of the client // normal rate / snapshotMsec calculation rate = cl->rate; - if ( sv_maxRate->integer ) { - if ( sv_maxRate->integer < 1000 ) { - Cvar_Set( "sv_MaxRate", "1000" ); + if (sv_maxRate->integer) { + if (sv_maxRate->integer < 1000) { + Cvar_Set("sv_MaxRate", "1000"); } - if ( sv_maxRate->integer < rate ) { + if (sv_maxRate->integer < rate) { rate = sv_maxRate->integer; } } @@ -880,8 +848,7 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) if (!rate) { blockspersnap = 1; } else { - blockspersnap = ( (rate * cl->snapshotMsec) / 1000 + MAX_DOWNLOAD_BLKSIZE ) / - MAX_DOWNLOAD_BLKSIZE; + blockspersnap = ((rate * cl->snapshotMsec) / 1000 + MAX_DOWNLOAD_BLKSIZE) / MAX_DOWNLOAD_BLKSIZE; } if (blockspersnap < 0) @@ -898,8 +865,8 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) if (cl->downloadXmitBlock == cl->downloadCurrentBlock) { // We have transmitted the complete window, should we start resending? - //FIXME: This uses a hardcoded one second timeout for lost blocks - //the timeout should be based on client rate somehow + // FIXME: This uses a hardcoded one second timeout for lost blocks + // the timeout should be based on client rate somehow if (svs.time - cl->downloadSendTime > 1000) cl->downloadXmitBlock = cl->downloadClientBlock; else @@ -909,21 +876,21 @@ void SV_WriteDownloadToClient(client_t *cl, msg_t *msg) // Send current block curindex = (cl->downloadXmitBlock % MAX_DOWNLOAD_WINDOW); - MSG_WriteByte( msg, svc_download ); - MSG_WriteShort( msg, cl->downloadXmitBlock ); + MSG_WriteByte(msg, svc_download); + MSG_WriteShort(msg, cl->downloadXmitBlock); // block zero is special, contains file size - if ( cl->downloadXmitBlock == 0 ) - MSG_WriteLong( msg, cl->downloadSize ); + if (cl->downloadXmitBlock == 0) + MSG_WriteLong(msg, cl->downloadSize); - MSG_WriteShort( msg, cl->downloadBlockSize[curindex] ); + MSG_WriteShort(msg, cl->downloadBlockSize[curindex]); // Write the block - if ( cl->downloadBlockSize[curindex] ) { - MSG_WriteData( msg, cl->downloadBlocks[curindex], cl->downloadBlockSize[curindex] ); + if (cl->downloadBlockSize[curindex]) { + MSG_WriteData(msg, cl->downloadBlocks[curindex], cl->downloadBlockSize[curindex]); } - Com_DPrintf( "clientDownload: %d : writing block %d\n", (int) (cl - svs.clients), cl->downloadXmitBlock ); + Com_DPrintf("clientDownload: %d : writing block %d\n", (int)(cl - svs.clients), cl->downloadXmitBlock); // Move on to the next block // It will get sent with next snap shot. The rate will keep us in line. @@ -941,9 +908,9 @@ The client is going to disconnect, so remove the connection immediately FIXME: ================= */ const char *SV_GetStringEdString(char *refSection, char *refName); -static void SV_Disconnect_f( client_t *cl ) { -// SV_DropClient( cl, "disconnected" ); - SV_DropClient( cl, SV_GetStringEdString("MP_SVGAME","DISCONNECTED") ); +static void SV_Disconnect_f(client_t *cl) { + // SV_DropClient( cl, "disconnected" ); + SV_DropClient(cl, SV_GetStringEdString("MP_SVGAME", "DISCONNECTED")); } /* @@ -959,7 +926,7 @@ This routine would be a bit simpler with a goto but i abstained ================= */ -static void SV_VerifyPaks_f( client_t *cl ) { +static void SV_VerifyPaks_f(client_t *cl) { int nChkSum1, nChkSum2, nClientPaks, nServerPaks, i, j, nCurArg; int nClientChkSum[1024]; int nServerChkSum[1024]; @@ -970,12 +937,12 @@ static void SV_VerifyPaks_f( client_t *cl ) { // certain pk3 files, namely we want the client to have loaded the // ui and cgame that we think should be loaded based on the pure setting // - if ( sv_pure->integer != 0 ) { + if (sv_pure->integer != 0) { bGood = qtrue; nChkSum1 = nChkSum2 = 0; // we run the game, so determine which cgame and ui the client "should" be running - //dlls are valid too now -rww + // dlls are valid too now -rww bGood = (qboolean)(FS_FileIsInPAK("cgamex86.dll", &nChkSum1) == 1); if (bGood) @@ -997,13 +964,13 @@ static void SV_VerifyPaks_f( client_t *cl ) { } // verify first to be the cgame checksum pArg = Cmd_Argv(nCurArg++); - if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum1 ) { + if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum1) { bGood = qfalse; break; } // verify the second to be the ui checksum pArg = Cmd_Argv(nCurArg++); - if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum2 ) { + if (!pArg || *pArg == '@' || atoi(pArg) != nChkSum2) { bGood = qfalse; break; } @@ -1040,7 +1007,7 @@ static void SV_VerifyPaks_f( client_t *cl ) { // get the pure checksums of the pk3 files loaded by the server pPaks = FS_LoadedPakPureChecksums(); - Cmd_TokenizeString( pPaks ); + Cmd_TokenizeString(pPaks); nServerPaks = Cmd_Argc(); if (nServerPaks > 1024) nServerPaks = 1024; @@ -1061,7 +1028,7 @@ static void SV_VerifyPaks_f( client_t *cl ) { break; } } - if ( bGood == qfalse ) { + if (bGood == qfalse) { break; } @@ -1084,13 +1051,12 @@ static void SV_VerifyPaks_f( client_t *cl ) { if (bGood) { cl->pureAuthentic = 1; - } - else { + } else { cl->pureAuthentic = 0; cl->nextSnapshotTime = -1; cl->state = CS_ACTIVE; - SV_SendClientSnapshot( cl ); - SV_DropClient( cl, "Unpure client detected. Invalid .PK3 files referenced!" ); + SV_SendClientSnapshot(cl); + SV_DropClient(cl, "Unpure client detected. Invalid .PK3 files referenced!"); } } } @@ -1100,7 +1066,7 @@ static void SV_VerifyPaks_f( client_t *cl ) { SV_ResetPureClient_f ================= */ -static void SV_ResetPureClient_f( client_t *cl ) { +static void SV_ResetPureClient_f(client_t *cl) { cl->pureAuthentic = 0; cl->gotCP = qfalse; } @@ -1113,34 +1079,31 @@ Pull specific info from a newly changed userinfo string into a more C friendly form. ================= */ -void SV_UserinfoChanged( client_t *cl ) { - char *val=NULL, *ip=NULL; - int i=0, len=0; +void SV_UserinfoChanged(client_t *cl) { + char *val = NULL, *ip = NULL; + int i = 0, len = 0; // name for C code - Q_strncpyz( cl->name, Info_ValueForKey (cl->userinfo, "name"), sizeof(cl->name) ); + Q_strncpyz(cl->name, Info_ValueForKey(cl->userinfo, "name"), sizeof(cl->name)); // rate command // if the client is on the same subnet as the server and we aren't running an // internet public server, assume they don't need a rate choke - if ( Sys_IsLANAddress( cl->netchan.remoteAddress ) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1 ) { - cl->rate = 100000; // lans should not rate limit + if (Sys_IsLANAddress(cl->netchan.remoteAddress) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1) { + cl->rate = 100000; // lans should not rate limit } else { - val = Info_ValueForKey (cl->userinfo, "rate"); - if (sv_ratePolicy->integer == 1) - { + val = Info_ValueForKey(cl->userinfo, "rate"); + if (sv_ratePolicy->integer == 1) { // NOTE: what if server sets some dumb sv_clientRate value? cl->rate = sv_clientRate->integer; - } - else if( sv_ratePolicy->integer == 2) - { + } else if (sv_ratePolicy->integer == 2) { i = atoi(val); if (!i) { - i = sv_maxRate->integer; //FIXME old code was 3000 here, should increase to 5000 instead or maxRate? + i = sv_maxRate->integer; // FIXME old code was 3000 here, should increase to 5000 instead or maxRate? } i = Com_Clampi(1000, 100000, i); - i = Com_Clampi( sv_minRate->integer, sv_maxRate->integer, i ); + i = Com_Clampi(sv_minRate->integer, sv_maxRate->integer, i); if (i != cl->rate) { cl->rate = i; } @@ -1148,15 +1111,14 @@ void SV_UserinfoChanged( client_t *cl ) { } // snaps command - //Note: cl->snapshotMsec is also validated in sv_main.cpp -> SV_CheckCvars if sv_fps, sv_snapsMin or sv_snapsMax is changed + // Note: cl->snapshotMsec is also validated in sv_main.cpp -> SV_CheckCvars if sv_fps, sv_snapsMin or sv_snapsMax is changed int minSnaps = Com_Clampi(1, sv_snapsMax->integer, sv_snapsMin->integer); // between 1 and sv_snapsMax ( 1 <-> 40 ) int maxSnaps = Q_min(sv_fps->integer, sv_snapsMax->integer); // can't produce more than sv_fps snapshots/sec, but can send less than sv_fps snapshots/sec val = Info_ValueForKey(cl->userinfo, "snaps"); cl->wishSnaps = atoi(val); if (!cl->wishSnaps) cl->wishSnaps = maxSnaps; - if (sv_snapsPolicy->integer == 1) - { + if (sv_snapsPolicy->integer == 1) { cl->wishSnaps = sv_fps->integer; i = 1000 / sv_fps->integer; if (i != cl->snapshotMsec) { @@ -1164,9 +1126,7 @@ void SV_UserinfoChanged( client_t *cl ) { cl->nextSnapshotTime = -1; cl->snapshotMsec = i; } - } - else if (sv_snapsPolicy->integer == 2) - { + } else if (sv_snapsPolicy->integer == 2) { i = 1000 / Com_Clampi(minSnaps, maxSnaps, cl->wishSnaps); if (i != cl->snapshotMsec) { // Reset next snapshot so we avoid desync between server frame time and snapshot send time @@ -1178,81 +1138,76 @@ void SV_UserinfoChanged( client_t *cl ) { // TTimo // maintain the IP information // the banning code relies on this being consistently present - if( NET_IsLocalAddress(cl->netchan.remoteAddress) ) + if (NET_IsLocalAddress(cl->netchan.remoteAddress)) ip = "localhost"; else - ip = (char*)NET_AdrToString( cl->netchan.remoteAddress ); + ip = (char *)NET_AdrToString(cl->netchan.remoteAddress); - val = Info_ValueForKey( cl->userinfo, "ip" ); - if( val[0] ) - len = strlen( ip ) - strlen( val ) + strlen( cl->userinfo ); + val = Info_ValueForKey(cl->userinfo, "ip"); + if (val[0]) + len = strlen(ip) - strlen(val) + strlen(cl->userinfo); else - len = strlen( ip ) + 4 + strlen( cl->userinfo ); + len = strlen(ip) + 4 + strlen(cl->userinfo); - if( len >= MAX_INFO_STRING ) - SV_DropClient( cl, "userinfo string length exceeded" ); + if (len >= MAX_INFO_STRING) + SV_DropClient(cl, "userinfo string length exceeded"); else - Info_SetValueForKey( cl->userinfo, "ip", ip ); + Info_SetValueForKey(cl->userinfo, "ip", ip); } -#define INFO_CHANGE_MIN_INTERVAL 6000 //6 seconds is reasonable I suppose -#define INFO_CHANGE_MAX_COUNT 3 //only allow 3 changes within the 6 seconds +#define INFO_CHANGE_MIN_INTERVAL 6000 // 6 seconds is reasonable I suppose +#define INFO_CHANGE_MAX_COUNT 3 // only allow 3 changes within the 6 seconds /* ================== SV_UpdateUserinfo_f ================== */ -static void SV_UpdateUserinfo_f( client_t *cl ) { +static void SV_UpdateUserinfo_f(client_t *cl) { char *arg = Cmd_Argv(1); // Stop random empty /userinfo calls without hurting anything - if( !arg || !*arg ) + if (!arg || !*arg) return; - Q_strncpyz( cl->userinfo, arg, sizeof(cl->userinfo) ); + Q_strncpyz(cl->userinfo, arg, sizeof(cl->userinfo)); #ifdef FINAL_BUILD - if (cl->lastUserInfoChange > svs.time) - { + if (cl->lastUserInfoChange > svs.time) { cl->lastUserInfoCount++; - if (cl->lastUserInfoCount >= INFO_CHANGE_MAX_COUNT) - { - // SV_SendServerCommand(cl, "print \"Warning: Too many info changes, last info ignored\n\"\n"); + if (cl->lastUserInfoCount >= INFO_CHANGE_MAX_COUNT) { + // SV_SendServerCommand(cl, "print \"Warning: Too many info changes, last info ignored\n\"\n"); SV_SendServerCommand(cl, "print \"@@@TOO_MANY_INFO\n\"\n"); return; } - } - else + } else #endif { cl->lastUserInfoCount = 0; cl->lastUserInfoChange = svs.time + INFO_CHANGE_MIN_INTERVAL; } - SV_UserinfoChanged( cl ); + SV_UserinfoChanged(cl); // call prog code to allow overrides - GVM_ClientUserinfoChanged( cl - svs.clients ); + GVM_ClientUserinfoChanged(cl - svs.clients); } typedef struct ucmd_s { - const char *name; - void (*func)( client_t *cl ); + const char *name; + void (*func)(client_t *cl); } ucmd_t; -static ucmd_t ucmds[] = { - {"userinfo", SV_UpdateUserinfo_f}, - {"disconnect", SV_Disconnect_f}, - {"cp", SV_VerifyPaks_f}, - {"vdr", SV_ResetPureClient_f}, - {"download", SV_BeginDownload_f}, - {"nextdl", SV_NextDownload_f}, - {"stopdl", SV_StopDownload_f}, - {"donedl", SV_DoneDownload_f}, +static ucmd_t ucmds[] = {{"userinfo", SV_UpdateUserinfo_f}, + {"disconnect", SV_Disconnect_f}, + {"cp", SV_VerifyPaks_f}, + {"vdr", SV_ResetPureClient_f}, + {"download", SV_BeginDownload_f}, + {"nextdl", SV_NextDownload_f}, + {"stopdl", SV_StopDownload_f}, + {"donedl", SV_DoneDownload_f}, - {NULL, NULL} -}; + {NULL, NULL}}; /* ================== @@ -1261,16 +1216,16 @@ SV_ExecuteClientCommand Also called by bot code ================== */ -void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK ) { - ucmd_t *u; +void SV_ExecuteClientCommand(client_t *cl, const char *s, qboolean clientOK) { + ucmd_t *u; qboolean bProcessed = qfalse; - Cmd_TokenizeString( s ); + Cmd_TokenizeString(s); // see if it is a server level command - for (u=ucmds ; u->name ; u++) { - if (!strcmp (Cmd_Argv(0), u->name) ) { - u->func( cl ); + for (u = ucmds; u->name; u++) { + if (!strcmp(Cmd_Argv(0), u->name)) { + u->func(cl); bProcessed = qtrue; break; } @@ -1280,18 +1235,17 @@ void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK ) { // pass unknown strings to the game if (!u->name && sv.state == SS_GAME && (cl->state == CS_ACTIVE || cl->state == CS_PRIMED)) { // strip \r \n and ; - if ( sv_filterCommands->integer ) { - Cmd_Args_Sanitize( MAX_CVAR_VALUE_STRING, "\n\r", " " ); - if ( sv_filterCommands->integer == 2 ) { + if (sv_filterCommands->integer) { + Cmd_Args_Sanitize(MAX_CVAR_VALUE_STRING, "\n\r", " "); + if (sv_filterCommands->integer == 2) { // also strip ';' for callvote - Cmd_Args_Sanitize( MAX_CVAR_VALUE_STRING, ";", " " ); + Cmd_Args_Sanitize(MAX_CVAR_VALUE_STRING, ";", " "); } } - GVM_ClientCommand( cl - svs.clients ); + GVM_ClientCommand(cl - svs.clients); } - } - else if (!bProcessed) - Com_DPrintf( "client text ignored for %s: %s\n", cl->name, Cmd_Argv(0) ); + } else if (!bProcessed) + Com_DPrintf("client text ignored for %s: %s\n", cl->name, Cmd_Argv(0)); } /* @@ -1299,26 +1253,25 @@ void SV_ExecuteClientCommand( client_t *cl, const char *s, qboolean clientOK ) { SV_ClientCommand =============== */ -static qboolean SV_ClientCommand( client_t *cl, msg_t *msg ) { - int seq; - const char *s; +static qboolean SV_ClientCommand(client_t *cl, msg_t *msg) { + int seq; + const char *s; qboolean clientOk = qtrue; - seq = MSG_ReadLong( msg ); - s = MSG_ReadString( msg ); + seq = MSG_ReadLong(msg); + s = MSG_ReadString(msg); // see if we have already executed it - if ( cl->lastClientCommand >= seq ) { + if (cl->lastClientCommand >= seq) { return qtrue; } - Com_DPrintf( "clientCommand: %s : %i : %s\n", cl->name, seq, s ); + Com_DPrintf("clientCommand: %s : %i : %s\n", cl->name, seq, s); // drop the connection if we have somehow lost commands - if ( seq > cl->lastClientCommand + 1 ) { - Com_Printf( "Client %s lost %i clientCommands\n", cl->name, - seq - cl->lastClientCommand + 1 ); - SV_DropClient( cl, "Lost reliable commands" ); + if (seq > cl->lastClientCommand + 1) { + Com_Printf("Client %s lost %i clientCommands\n", cl->name, seq - cl->lastClientCommand + 1); + SV_DropClient(cl, "Lost reliable commands"); return qfalse; } @@ -1329,36 +1282,30 @@ static qboolean SV_ClientCommand( client_t *cl, msg_t *msg ) { // but not other people // We don't do this when the client hasn't been active yet since its // normal to spam a lot of commands when downloading - if ( !com_cl_running->integer && - cl->state >= CS_ACTIVE && - sv_floodProtect->integer ) - { + if (!com_cl_running->integer && cl->state >= CS_ACTIVE && sv_floodProtect->integer) { const int floodTime = (sv_floodProtect->integer == 1) ? 1000 : sv_floodProtect->integer; - if ( svs.time < (cl->lastReliableTime + floodTime) ) { + if (svs.time < (cl->lastReliableTime + floodTime)) { // ignore any other text messages from this client but let them keep playing // TTimo - moved the ignored verbose to the actual processing in SV_ExecuteClientCommand, only printing if the core doesn't intercept clientOk = qfalse; - } - else { + } else { cl->lastReliableTime = svs.time; } - if ( sv_floodProtectSlow->integer ) { + if (sv_floodProtectSlow->integer) { cl->lastReliableTime = svs.time; } } - SV_ExecuteClientCommand( cl, s, clientOk ); + SV_ExecuteClientCommand(cl, s, clientOk); cl->lastClientCommand = seq; Com_sprintf(cl->lastClientCommandString, sizeof(cl->lastClientCommandString), "%s", s); - return qtrue; // continue procesing + return qtrue; // continue procesing } - //================================================================================== - /* ================== SV_ClientThink @@ -1366,14 +1313,14 @@ SV_ClientThink Also called by bot code ================== */ -void SV_ClientThink (client_t *cl, usercmd_t *cmd) { +void SV_ClientThink(client_t *cl, usercmd_t *cmd) { cl->lastUsercmd = *cmd; - if ( cl->state != CS_ACTIVE ) { - return; // may have been kicked during the last usercmd + if (cl->state != CS_ACTIVE) { + return; // may have been kicked during the last usercmd } - GVM_ClientThink( cl - svs.clients, NULL ); + GVM_ClientThink(cl - svs.clients, NULL); } /* @@ -1388,28 +1335,28 @@ On very fast clients, there may be multiple usercmd packed into each of the backup packets. ================== */ -static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) { - int i, key; - int cmdCount; - usercmd_t nullcmd; - usercmd_t cmds[MAX_PACKET_USERCMDS]; - usercmd_t *cmd, *oldcmd; - - if ( delta ) { +static void SV_UserMove(client_t *cl, msg_t *msg, qboolean delta) { + int i, key; + int cmdCount; + usercmd_t nullcmd; + usercmd_t cmds[MAX_PACKET_USERCMDS]; + usercmd_t *cmd, *oldcmd; + + if (delta) { cl->deltaMessage = cl->messageAcknowledge; } else { cl->deltaMessage = -1; } - cmdCount = MSG_ReadByte( msg ); + cmdCount = MSG_ReadByte(msg); - if ( cmdCount < 1 ) { - Com_Printf( "cmdCount < 1\n" ); + if (cmdCount < 1) { + Com_Printf("cmdCount < 1\n"); return; } - if ( cmdCount > MAX_PACKET_USERCMDS ) { - Com_Printf( "cmdCount > MAX_PACKET_USERCMDS\n" ); + if (cmdCount > MAX_PACKET_USERCMDS) { + Com_Printf("cmdCount > MAX_PACKET_USERCMDS\n"); return; } @@ -1418,16 +1365,16 @@ static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) { // also use the message acknowledge key ^= cl->messageAcknowledge; // also use the last acknowledged server command in the key - key ^= Com_HashKey(cl->reliableCommands[ cl->reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ], 32); + key ^= Com_HashKey(cl->reliableCommands[cl->reliableAcknowledge & (MAX_RELIABLE_COMMANDS - 1)], 32); - Com_Memset( &nullcmd, 0, sizeof(nullcmd) ); + Com_Memset(&nullcmd, 0, sizeof(nullcmd)); oldcmd = &nullcmd; - for ( i = 0 ; i < cmdCount ; i++ ) { + for (i = 0; i < cmdCount; i++) { cmd = &cmds[i]; - MSG_ReadDeltaUsercmdKey( msg, key, oldcmd, cmd ); - if ( sv_legacyFixes->integer ) { + MSG_ReadDeltaUsercmdKey(msg, key, oldcmd, cmd); + if (sv_legacyFixes->integer) { // block "charge jump" and other nonsense - if ( cmd->forcesel == FP_LEVITATION || cmd->forcesel >= NUM_FORCE_POWERS ) { + if (cmd->forcesel == FP_LEVITATION || cmd->forcesel >= NUM_FORCE_POWERS) { cmd->forcesel = 0xFFu; } @@ -1438,36 +1385,35 @@ static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) { } // save time for ping calculation - cl->frames[ cl->messageAcknowledge & PACKET_MASK ].messageAcked = svs.time; + cl->frames[cl->messageAcknowledge & PACKET_MASK].messageAcked = svs.time; // TTimo // catch the no-cp-yet situation before SV_ClientEnterWorld // if CS_ACTIVE, then it's time to trigger a new gamestate emission // if not, then we are getting remaining parasite usermove commands, which we should ignore if (sv_pure->integer != 0 && cl->pureAuthentic == 0 && !cl->gotCP) { - if (cl->state == CS_ACTIVE) - { + if (cl->state == CS_ACTIVE) { // we didn't get a cp yet, don't assume anything and just send the gamestate all over again - Com_DPrintf( "%s: didn't get cp command, resending gamestate\n", cl->name); - SV_SendClientGameState( cl ); + Com_DPrintf("%s: didn't get cp command, resending gamestate\n", cl->name); + SV_SendClientGameState(cl); } return; } // if this is the first usercmd we have received // this gamestate, put the client into the world - if ( cl->state == CS_PRIMED ) { - SV_ClientEnterWorld( cl, &cmds[0] ); + if (cl->state == CS_PRIMED) { + SV_ClientEnterWorld(cl, &cmds[0]); // the moves can be processed normaly } // a bad cp command was sent, drop the client if (sv_pure->integer != 0 && cl->pureAuthentic == 0) { - SV_DropClient( cl, "Cannot validate pure client!"); + SV_DropClient(cl, "Cannot validate pure client!"); return; } - if ( cl->state != CS_ACTIVE ) { + if (cl->state != CS_ACTIVE) { cl->deltaMessage = -1; return; } @@ -1475,25 +1421,24 @@ static void SV_UserMove( client_t *cl, msg_t *msg, qboolean delta ) { // usually, the first couple commands will be duplicates // of ones we have previously received, but the servertimes // in the commands will cause them to be immediately discarded - for ( i = 0 ; i < cmdCount ; i++ ) { + for (i = 0; i < cmdCount; i++) { // if this is a cmd from before a map_restart ignore it - if ( cmds[i].serverTime > cmds[cmdCount-1].serverTime ) { + if (cmds[i].serverTime > cmds[cmdCount - 1].serverTime) { continue; } // extremely lagged or cmd from before a map_restart - //if ( cmds[i].serverTime > svs.time + 3000 ) { + // if ( cmds[i].serverTime > svs.time + 3000 ) { // continue; //} // don't execute if this is an old cmd which is already executed // these old cmds are included when cl_packetdup > 0 - if ( cmds[i].serverTime <= cl->lastUsercmd.serverTime ) { + if (cmds[i].serverTime <= cl->lastUsercmd.serverTime) { continue; } - SV_ClientThink (cl, &cmds[ i ]); + SV_ClientThink(cl, &cmds[i]); } } - /* =========================================================================== @@ -1509,23 +1454,23 @@ SV_ExecuteClientMessage Parse a client packet =================== */ -void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) { - int c; - int serverId; +void SV_ExecuteClientMessage(client_t *cl, msg_t *msg) { + int c; + int serverId; MSG_Bitstream(msg); - serverId = MSG_ReadLong( msg ); - cl->messageAcknowledge = MSG_ReadLong( msg ); + serverId = MSG_ReadLong(msg); + cl->messageAcknowledge = MSG_ReadLong(msg); if (cl->messageAcknowledge < 0) { // usually only hackers create messages like this // it is more annoying for them to let them hanging - //SV_DropClient( cl, "illegible client message" ); + // SV_DropClient( cl, "illegible client message" ); return; } - cl->reliableAcknowledge = MSG_ReadLong( msg ); + cl->reliableAcknowledge = MSG_ReadLong(msg); // NOTE: when the client message is fux0red the acknowledgement numbers // can be out of range, this could cause the server to send thousands of server @@ -1533,7 +1478,7 @@ void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) { if (cl->reliableAcknowledge < cl->reliableSequence - MAX_RELIABLE_COMMANDS) { // usually only hackers create messages like this // it is more annoying for them to let them hanging - //SV_DropClient( cl, "illegible client message" ); + // SV_DropClient( cl, "illegible client message" ); cl->reliableAcknowledge = cl->reliableSequence; return; } @@ -1549,8 +1494,8 @@ void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) { // don't drop as long as previous command was a nextdl, after a dl is done, downloadName is set back to "" // but we still need to read the next message to move to next download or send gamestate // I don't like this hack though, it must have been working fine at some point, suspecting the fix is somewhere else - if ( serverId != sv.serverId && !*cl->downloadName && !strstr(cl->lastClientCommandString, "nextdl") ) { - if ( serverId >= sv.restartedServerId && serverId < sv.serverId ) { // TTimo - use a comparison here to catch multiple map_restart + if (serverId != sv.serverId && !*cl->downloadName && !strstr(cl->lastClientCommandString, "nextdl")) { + if (serverId >= sv.restartedServerId && serverId < sv.serverId) { // TTimo - use a comparison here to catch multiple map_restart // they just haven't caught the map_restart yet Com_DPrintf("%s : ignoring pre map_restart / outdated client message\n", cl->name); return; @@ -1558,47 +1503,46 @@ void SV_ExecuteClientMessage( client_t *cl, msg_t *msg ) { // if we can tell that the client has dropped the last // gamestate we sent them, resend it // Fix for https://bugzilla.icculus.org/show_bug.cgi?id=6324 - if ( cl->state != CS_ACTIVE && cl->messageAcknowledge > cl->gamestateMessageNum ) { - Com_DPrintf( "%s : dropped gamestate, resending\n", cl->name ); - SV_SendClientGameState( cl ); + if (cl->state != CS_ACTIVE && cl->messageAcknowledge > cl->gamestateMessageNum) { + Com_DPrintf("%s : dropped gamestate, resending\n", cl->name); + SV_SendClientGameState(cl); } return; } // this client has acknowledged the new gamestate so it's // safe to start sending it the real time again - if( cl->oldServerTime && serverId == sv.serverId ) { - Com_DPrintf( "%s acknowledged gamestate\n", cl->name ); + if (cl->oldServerTime && serverId == sv.serverId) { + Com_DPrintf("%s acknowledged gamestate\n", cl->name); cl->oldServerTime = 0; } // read optional clientCommand strings do { - c = MSG_ReadByte( msg ); - if ( c == clc_EOF ) { + c = MSG_ReadByte(msg); + if (c == clc_EOF) { break; } - if ( c != clc_clientCommand ) { + if (c != clc_clientCommand) { break; } - if ( !SV_ClientCommand( cl, msg ) ) { - return; // we couldn't execute it because of the flood protection + if (!SV_ClientCommand(cl, msg)) { + return; // we couldn't execute it because of the flood protection } if (cl->state == CS_ZOMBIE) { - return; // disconnect command + return; // disconnect command } - } while ( 1 ); + } while (1); // read the usercmd_t - if ( c == clc_move ) { - SV_UserMove( cl, msg, qtrue ); - } else if ( c == clc_moveNoDelta ) { - SV_UserMove( cl, msg, qfalse ); - } else if ( c != clc_EOF ) { - Com_Printf( "WARNING: bad command byte for client %i\n", cl - svs.clients ); + if (c == clc_move) { + SV_UserMove(cl, msg, qtrue); + } else if (c == clc_moveNoDelta) { + SV_UserMove(cl, msg, qfalse); + } else if (c != clc_EOF) { + Com_Printf("WARNING: bad command byte for client %i\n", cl - svs.clients); } -// if ( msg->readcount != msg->cursize ) { -// Com_Printf( "WARNING: Junk at end of packet for client %i\n", cl - svs.clients ); -// } + // if ( msg->readcount != msg->cursize ) { + // Com_Printf( "WARNING: Junk at end of packet for client %i\n", cl - svs.clients ); + // } } - diff --git a/codemp/server/sv_game.cpp b/codemp/server/sv_game.cpp index 807394ed2e..46adff4ba7 100644 --- a/codemp/server/sv_game.cpp +++ b/codemp/server/sv_game.cpp @@ -35,42 +35,42 @@ along with this program; if not, see . // these functions must be used instead of pointer arithmetic, because // the game allocates gentities with private information after the server shared part -int SV_NumForGentity( sharedEntity_t *ent ) { - int num; +int SV_NumForGentity(sharedEntity_t *ent) { + int num; - num = ( (byte *)ent - (byte *)sv.gentities ) / sv.gentitySize; + num = ((byte *)ent - (byte *)sv.gentities) / sv.gentitySize; return num; } -sharedEntity_t *SV_GentityNum( int num ) { +sharedEntity_t *SV_GentityNum(int num) { sharedEntity_t *ent; - ent = (sharedEntity_t *)((byte *)sv.gentities + sv.gentitySize*(num)); + ent = (sharedEntity_t *)((byte *)sv.gentities + sv.gentitySize * (num)); return ent; } -playerState_t *SV_GameClientNum( int num ) { - playerState_t *ps; +playerState_t *SV_GameClientNum(int num) { + playerState_t *ps; - ps = (playerState_t *)((byte *)sv.gameClients + sv.gameClientSize*(num)); + ps = (playerState_t *)((byte *)sv.gameClients + sv.gameClientSize * (num)); return ps; } -svEntity_t *SV_SvEntityForGentity( sharedEntity_t *gEnt ) { - if ( !gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" ); +svEntity_t *SV_SvEntityForGentity(sharedEntity_t *gEnt) { + if (!gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "SV_SvEntityForGentity: bad gEnt"); } - return &sv.svEntities[ gEnt->s.number ]; + return &sv.svEntities[gEnt->s.number]; } -sharedEntity_t *SV_GEntityForSvEntity( svEntity_t *svEnt ) { - int num; +sharedEntity_t *SV_GEntityForSvEntity(svEntity_t *svEnt) { + int num; num = svEnt - sv.svEntities; - return SV_GentityNum( num ); + return SV_GentityNum(num); } /* @@ -80,25 +80,24 @@ SV_inPVS Also checks portalareas so that doors block sight ================= */ -qboolean SV_inPVS (const vec3_t p1, const vec3_t p2) -{ - int leafnum; - int cluster; - int area1, area2; - byte *mask; - - leafnum = CM_PointLeafnum (p1); - cluster = CM_LeafCluster (leafnum); - area1 = CM_LeafArea (leafnum); - mask = CM_ClusterPVS (cluster); - - leafnum = CM_PointLeafnum (p2); - cluster = CM_LeafCluster (leafnum); - area2 = CM_LeafArea (leafnum); - if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) ) +qboolean SV_inPVS(const vec3_t p1, const vec3_t p2) { + int leafnum; + int cluster; + int area1, area2; + byte *mask; + + leafnum = CM_PointLeafnum(p1); + cluster = CM_LeafCluster(leafnum); + area1 = CM_LeafArea(leafnum); + mask = CM_ClusterPVS(cluster); + + leafnum = CM_PointLeafnum(p2); + cluster = CM_LeafCluster(leafnum); + area2 = CM_LeafArea(leafnum); + if (mask && (!(mask[cluster >> 3] & (1 << (cluster & 7))))) return qfalse; - if (!CM_AreasConnected (area1, area2)) - return qfalse; // a door blocks sight + if (!CM_AreasConnected(area1, area2)) + return qfalse; // a door blocks sight return qtrue; } @@ -111,8 +110,8 @@ SV_ShutdownGameProgs Called every time a map changes =============== */ -void SV_ShutdownGameProgs( void ) { - if ( !svs.gameStarted ) { +void SV_ShutdownGameProgs(void) { + if (!svs.gameStarted) { return; } SV_UnbindGame(); @@ -126,20 +125,19 @@ Called on a normal map change, not on a map_restart =============== */ -void SV_InitGameProgs( void ) { - //FIXME these are temp while I make bots run in vm - extern int bot_enable; +void SV_InitGameProgs(void) { + // FIXME these are temp while I make bots run in vm + extern int bot_enable; - cvar_t *var = Cvar_Get( "bot_enable", "1", CVAR_LATCH ); + cvar_t *var = Cvar_Get("bot_enable", "1", CVAR_LATCH); bot_enable = var ? var->integer : 0; svs.gameStarted = qtrue; SV_BindGame(); - SV_InitGame( qfalse ); + SV_InitGame(qfalse); } - /* ==================== SV_GameCommand @@ -147,8 +145,8 @@ SV_GameCommand See if the current console command is claimed by the game ==================== */ -qboolean SV_GameCommand( void ) { - if ( sv.state != SS_GAME ) { +qboolean SV_GameCommand(void) { + if (sv.state != SS_GAME) { return qfalse; } diff --git a/codemp/server/sv_gameapi.cpp b/codemp/server/sv_gameapi.cpp index d216669abf..9018721a92 100644 --- a/codemp/server/sv_gameapi.cpp +++ b/codemp/server/sv_gameapi.cpp @@ -19,7 +19,7 @@ along with this program; if not, see . */ // sv_gameapi.cpp -- interface to the game dll -//Anything above this #include will be ignored by the compiler +// Anything above this #include will be ignored by the compiler #include "server.h" #include "botlib/botlib.h" @@ -31,374 +31,376 @@ along with this program; if not, see . #include "qcommon/timing.h" #include "NPCNav/navigator.h" -botlib_export_t *botlib_export; +botlib_export_t *botlib_export; // game interface static gameExport_t *ge; // game export table -static vm_t *gvm; // game vm, valid for legacy and new api +static vm_t *gvm; // game vm, valid for legacy and new api // // game vmMain calls // -void GVM_InitGame( int levelTime, int randomSeed, int restart ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_INIT, levelTime, randomSeed, restart ); +void GVM_InitGame(int levelTime, int randomSeed, int restart) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_INIT, levelTime, randomSeed, restart); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->InitGame( levelTime, randomSeed, restart ); + ge->InitGame(levelTime, randomSeed, restart); } -void GVM_ShutdownGame( int restart ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_SHUTDOWN, restart ); +void GVM_ShutdownGame(int restart) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_SHUTDOWN, restart); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ShutdownGame( restart ); + ge->ShutdownGame(restart); } -char *GVM_ClientConnect( int clientNum, qboolean firstTime, qboolean isBot ) { - if ( gvm->isLegacy ) - return (char *)VM_Call( gvm, GAME_CLIENT_CONNECT, clientNum, firstTime, isBot ); - VMSwap v( gvm ); +char *GVM_ClientConnect(int clientNum, qboolean firstTime, qboolean isBot) { + if (gvm->isLegacy) + return (char *)VM_Call(gvm, GAME_CLIENT_CONNECT, clientNum, firstTime, isBot); + VMSwap v(gvm); - return ge->ClientConnect( clientNum, firstTime, isBot ); + return ge->ClientConnect(clientNum, firstTime, isBot); } -void GVM_ClientBegin( int clientNum ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_CLIENT_BEGIN, clientNum ); +void GVM_ClientBegin(int clientNum) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_CLIENT_BEGIN, clientNum); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ClientBegin( clientNum, qtrue ); + ge->ClientBegin(clientNum, qtrue); } -qboolean GVM_ClientUserinfoChanged( int clientNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_CLIENT_USERINFO_CHANGED, clientNum ); - VMSwap v( gvm ); +qboolean GVM_ClientUserinfoChanged(int clientNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_CLIENT_USERINFO_CHANGED, clientNum); + VMSwap v(gvm); - return ge->ClientUserinfoChanged( clientNum ); + return ge->ClientUserinfoChanged(clientNum); } -void GVM_ClientDisconnect( int clientNum ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_CLIENT_DISCONNECT, clientNum ); +void GVM_ClientDisconnect(int clientNum) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_CLIENT_DISCONNECT, clientNum); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ClientDisconnect( clientNum ); + ge->ClientDisconnect(clientNum); } -void GVM_ClientCommand( int clientNum ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_CLIENT_COMMAND, clientNum ); +void GVM_ClientCommand(int clientNum) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_CLIENT_COMMAND, clientNum); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ClientCommand( clientNum ); + ge->ClientCommand(clientNum); } -void GVM_ClientThink( int clientNum, usercmd_t *ucmd ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_CLIENT_THINK, clientNum, reinterpret_cast< intptr_t >( ucmd ) ); +void GVM_ClientThink(int clientNum, usercmd_t *ucmd) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_CLIENT_THINK, clientNum, reinterpret_cast(ucmd)); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ClientThink( clientNum, ucmd ); + ge->ClientThink(clientNum, ucmd); } -void GVM_RunFrame( int levelTime ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_RUN_FRAME, levelTime ); +void GVM_RunFrame(int levelTime) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_RUN_FRAME, levelTime); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->RunFrame( levelTime ); + ge->RunFrame(levelTime); } -qboolean GVM_ConsoleCommand( void ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_CONSOLE_COMMAND ); - VMSwap v( gvm ); +qboolean GVM_ConsoleCommand(void) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_CONSOLE_COMMAND); + VMSwap v(gvm); return ge->ConsoleCommand(); } -int GVM_BotAIStartFrame( int time ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, BOTAI_START_FRAME, time ); - VMSwap v( gvm ); +int GVM_BotAIStartFrame(int time) { + if (gvm->isLegacy) + return VM_Call(gvm, BOTAI_START_FRAME, time); + VMSwap v(gvm); - return ge->BotAIStartFrame( time ); + return ge->BotAIStartFrame(time); } -void GVM_ROFF_NotetrackCallback( int entID, const char *notetrack ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ROFF_NOTETRACK_CALLBACK, entID, reinterpret_cast< intptr_t >( notetrack ) ); +void GVM_ROFF_NotetrackCallback(int entID, const char *notetrack) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ROFF_NOTETRACK_CALLBACK, entID, reinterpret_cast(notetrack)); return; } - VMSwap v( gvm ); + VMSwap v(gvm); - ge->ROFF_NotetrackCallback( entID, notetrack ); + ge->ROFF_NotetrackCallback(entID, notetrack); } -void GVM_SpawnRMGEntity( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_SPAWN_RMG_ENTITY ); +void GVM_SpawnRMGEntity(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_SPAWN_RMG_ENTITY); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->SpawnRMGEntity(); } -int GVM_ICARUS_PlaySound( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_PLAYSOUND ); - VMSwap v( gvm ); +int GVM_ICARUS_PlaySound(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_PLAYSOUND); + VMSwap v(gvm); return ge->ICARUS_PlaySound(); } -qboolean GVM_ICARUS_Set( void ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_ICARUS_SET ); - VMSwap v( gvm ); +qboolean GVM_ICARUS_Set(void) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_ICARUS_SET); + VMSwap v(gvm); return ge->ICARUS_Set(); } -void GVM_ICARUS_Lerp2Pos( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_LERP2POS ); +void GVM_ICARUS_Lerp2Pos(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_LERP2POS); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Lerp2Pos(); } -void GVM_ICARUS_Lerp2Origin( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_LERP2ORIGIN ); +void GVM_ICARUS_Lerp2Origin(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_LERP2ORIGIN); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Lerp2Origin(); } -void GVM_ICARUS_Lerp2Angles( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_LERP2ANGLES ); +void GVM_ICARUS_Lerp2Angles(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_LERP2ANGLES); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Lerp2Angles(); } -int GVM_ICARUS_GetTag( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_GETTAG ); - VMSwap v( gvm ); +int GVM_ICARUS_GetTag(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_GETTAG); + VMSwap v(gvm); return ge->ICARUS_GetTag(); } -void GVM_ICARUS_Lerp2Start( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_LERP2START ); +void GVM_ICARUS_Lerp2Start(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_LERP2START); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Lerp2Start(); } -void GVM_ICARUS_Lerp2End( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_LERP2END ); +void GVM_ICARUS_Lerp2End(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_LERP2END); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Lerp2End(); } -void GVM_ICARUS_Use( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_USE ); +void GVM_ICARUS_Use(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_USE); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Use(); } -void GVM_ICARUS_Kill( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_KILL ); +void GVM_ICARUS_Kill(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_KILL); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Kill(); } -void GVM_ICARUS_Remove( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_REMOVE ); +void GVM_ICARUS_Remove(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_REMOVE); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Remove(); } -void GVM_ICARUS_Play( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_PLAY ); +void GVM_ICARUS_Play(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_PLAY); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_Play(); } -int GVM_ICARUS_GetFloat( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_GETFLOAT ); - VMSwap v( gvm ); +int GVM_ICARUS_GetFloat(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_GETFLOAT); + VMSwap v(gvm); return ge->ICARUS_GetFloat(); } -int GVM_ICARUS_GetVector( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_GETVECTOR ); - VMSwap v( gvm ); +int GVM_ICARUS_GetVector(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_GETVECTOR); + VMSwap v(gvm); return ge->ICARUS_GetVector(); } -int GVM_ICARUS_GetString( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_GETSTRING ); - VMSwap v( gvm ); +int GVM_ICARUS_GetString(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_GETSTRING); + VMSwap v(gvm); return ge->ICARUS_GetString(); } -void GVM_ICARUS_SoundIndex( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_ICARUS_SOUNDINDEX ); +void GVM_ICARUS_SoundIndex(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_ICARUS_SOUNDINDEX); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->ICARUS_SoundIndex(); } -int GVM_ICARUS_GetSetIDForString( void ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_ICARUS_GETSETIDFORSTRING ); - VMSwap v( gvm ); +int GVM_ICARUS_GetSetIDForString(void) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_ICARUS_GETSETIDFORSTRING); + VMSwap v(gvm); return ge->ICARUS_GetSetIDForString(); } -qboolean GVM_NAV_ClearPathToPoint( int entID, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEnt ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_CLEARPATHTOPOINT, entID, reinterpret_cast< intptr_t >( pmins ), reinterpret_cast< intptr_t >( pmaxs ), reinterpret_cast< intptr_t >( point ), clipmask, okToHitEnt ); - VMSwap v( gvm ); +qboolean GVM_NAV_ClearPathToPoint(int entID, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask, int okToHitEnt) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_CLEARPATHTOPOINT, entID, reinterpret_cast(pmins), reinterpret_cast(pmaxs), + reinterpret_cast(point), clipmask, okToHitEnt); + VMSwap v(gvm); - return ge->NAV_ClearPathToPoint( entID, pmins, pmaxs, point, clipmask, okToHitEnt ); + return ge->NAV_ClearPathToPoint(entID, pmins, pmaxs, point, clipmask, okToHitEnt); } -qboolean GVM_NPC_ClearLOS2( int entID, const vec3_t end ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_CLEARLOS, entID, reinterpret_cast< intptr_t >( end ) ); - VMSwap v( gvm ); +qboolean GVM_NPC_ClearLOS2(int entID, const vec3_t end) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_CLEARLOS, entID, reinterpret_cast(end)); + VMSwap v(gvm); - return ge->NPC_ClearLOS2( entID, end ); + return ge->NPC_ClearLOS2(entID, end); } -int GVM_NAVNEW_ClearPathBetweenPoints( vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_NAV_CLEARPATHBETWEENPOINTS, reinterpret_cast< intptr_t >( start ), reinterpret_cast< intptr_t >( end ), reinterpret_cast< intptr_t >( mins ), reinterpret_cast< intptr_t >( maxs ), ignore, clipmask ); - VMSwap v( gvm ); +int GVM_NAVNEW_ClearPathBetweenPoints(vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, int ignore, int clipmask) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_NAV_CLEARPATHBETWEENPOINTS, reinterpret_cast(start), reinterpret_cast(end), + reinterpret_cast(mins), reinterpret_cast(maxs), ignore, clipmask); + VMSwap v(gvm); - return ge->NAVNEW_ClearPathBetweenPoints( start, end, mins, maxs, ignore, clipmask ); + return ge->NAVNEW_ClearPathBetweenPoints(start, end, mins, maxs, ignore, clipmask); } -qboolean GVM_NAV_CheckNodeFailedForEnt( int entID, int nodeNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_CHECKNODEFAILEDFORENT, entID, nodeNum ); - VMSwap v( gvm ); +qboolean GVM_NAV_CheckNodeFailedForEnt(int entID, int nodeNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_CHECKNODEFAILEDFORENT, entID, nodeNum); + VMSwap v(gvm); - return ge->NAV_CheckNodeFailedForEnt( entID, nodeNum ); + return ge->NAV_CheckNodeFailedForEnt(entID, nodeNum); } -qboolean GVM_NAV_EntIsUnlockedDoor( int entityNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_ENTISUNLOCKEDDOOR, entityNum ); - VMSwap v( gvm ); +qboolean GVM_NAV_EntIsUnlockedDoor(int entityNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_ENTISUNLOCKEDDOOR, entityNum); + VMSwap v(gvm); - return ge->NAV_EntIsUnlockedDoor( entityNum ); + return ge->NAV_EntIsUnlockedDoor(entityNum); } -qboolean GVM_NAV_EntIsDoor( int entityNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_ENTISDOOR, entityNum ); - VMSwap v( gvm ); +qboolean GVM_NAV_EntIsDoor(int entityNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_ENTISDOOR, entityNum); + VMSwap v(gvm); - return ge->NAV_EntIsDoor( entityNum ); + return ge->NAV_EntIsDoor(entityNum); } -qboolean GVM_NAV_EntIsBreakable( int entityNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_ENTISBREAKABLE, entityNum ); - VMSwap v( gvm ); +qboolean GVM_NAV_EntIsBreakable(int entityNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_ENTISBREAKABLE, entityNum); + VMSwap v(gvm); - return ge->NAV_EntIsBreakable( entityNum ); + return ge->NAV_EntIsBreakable(entityNum); } -qboolean GVM_NAV_EntIsRemovableUsable( int entNum ) { - if ( gvm->isLegacy ) - return (qboolean)VM_Call( gvm, GAME_NAV_ENTISREMOVABLEUSABLE, entNum ); - VMSwap v( gvm ); +qboolean GVM_NAV_EntIsRemovableUsable(int entNum) { + if (gvm->isLegacy) + return (qboolean)VM_Call(gvm, GAME_NAV_ENTISREMOVABLEUSABLE, entNum); + VMSwap v(gvm); - return ge->NAV_EntIsRemovableUsable( entNum ); + return ge->NAV_EntIsRemovableUsable(entNum); } -void GVM_NAV_FindCombatPointWaypoints( void ) { - if ( gvm->isLegacy ) { - VM_Call( gvm, GAME_NAV_FINDCOMBATPOINTWAYPOINTS ); +void GVM_NAV_FindCombatPointWaypoints(void) { + if (gvm->isLegacy) { + VM_Call(gvm, GAME_NAV_FINDCOMBATPOINTWAYPOINTS); return; } - VMSwap v( gvm ); + VMSwap v(gvm); ge->NAV_FindCombatPointWaypoints(); } -int GVM_BG_GetItemIndexByTag( int tag, int type ) { - if ( gvm->isLegacy ) - return VM_Call( gvm, GAME_GETITEMINDEXBYTAG, tag, type ); - VMSwap v( gvm ); +int GVM_BG_GetItemIndexByTag(int tag, int type) { + if (gvm->isLegacy) + return VM_Call(gvm, GAME_GETITEMINDEXBYTAG, tag, type); + VMSwap v(gvm); - return ge->BG_GetItemIndexByTag( tag, type ); + return ge->BG_GetItemIndexByTag(tag, type); } // @@ -411,22 +413,22 @@ int GVM_BG_GetItemIndexByTag( int tag, int type ) { siegePers_t sv_siegePersData = {qfalse, 0, 0}; extern float g_svCullDist; -int CM_ModelContents( clipHandle_t model, int subBSPIndex ); -int CM_LoadSubBSP( const char *name, qboolean clientload ); -int CM_FindSubBSP( int modelIndex ); -char *CM_SubBSPEntityString( int index ); -qboolean Q3_TaskIDPending( sharedEntity_t *ent, taskID_t taskType ); -void Q3_TaskIDSet( sharedEntity_t *ent, taskID_t taskType, int taskID ); -void Q3_TaskIDComplete( sharedEntity_t *ent, taskID_t taskType ); -void Q3_SetVar( int taskID, int entID, const char *type_name, const char *data ); -int Q3_VariableDeclared( const char *name ); -int Q3_GetFloatVariable( const char *name, float *value ); -int Q3_GetStringVariable( const char *name, const char **value ); -int Q3_GetVectorVariable( const char *name, vec3_t value ); -void SV_BotWaypointReception( int wpnum, wpobject_t **wps ); -void SV_BotCalculatePaths( int rmg ); - -static void SV_LocateGameData( sharedEntity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *clients, int sizeofGameClient ) { +int CM_ModelContents(clipHandle_t model, int subBSPIndex); +int CM_LoadSubBSP(const char *name, qboolean clientload); +int CM_FindSubBSP(int modelIndex); +char *CM_SubBSPEntityString(int index); +qboolean Q3_TaskIDPending(sharedEntity_t *ent, taskID_t taskType); +void Q3_TaskIDSet(sharedEntity_t *ent, taskID_t taskType, int taskID); +void Q3_TaskIDComplete(sharedEntity_t *ent, taskID_t taskType); +void Q3_SetVar(int taskID, int entID, const char *type_name, const char *data); +int Q3_VariableDeclared(const char *name); +int Q3_GetFloatVariable(const char *name, float *value); +int Q3_GetStringVariable(const char *name, const char **value); +int Q3_GetVectorVariable(const char *name, vec3_t value); +void SV_BotWaypointReception(int wpnum, wpobject_t **wps); +void SV_BotCalculatePaths(int rmg); + +static void SV_LocateGameData(sharedEntity_t *gEnts, int numGEntities, int sizeofGEntity_t, playerState_t *clients, int sizeofGameClient) { sv.gentities = gEnts; sv.gentitySize = sizeofGEntity_t; sv.num_entities = numGEntities; @@ -435,151 +437,141 @@ static void SV_LocateGameData( sharedEntity_t *gEnts, int numGEntities, int size sv.gameClientSize = sizeofGameClient; } -static void SV_GameDropClient( int clientNum, const char *reason ) { - if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { +static void SV_GameDropClient(int clientNum, const char *reason) { + if (clientNum < 0 || clientNum >= sv_maxclients->integer) { return; } - SV_DropClient( svs.clients + clientNum, reason ); + SV_DropClient(svs.clients + clientNum, reason); } -static void SV_GameSendServerCommand( int clientNum, const char *text ) { - if ( clientNum == -1 ) { - SV_SendServerCommand( NULL, "%s", text ); +static void SV_GameSendServerCommand(int clientNum, const char *text) { + if (clientNum == -1) { + SV_SendServerCommand(NULL, "%s", text); } else { - if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { + if (clientNum < 0 || clientNum >= sv_maxclients->integer) { return; } - SV_SendServerCommand( svs.clients + clientNum, "%s", text ); + SV_SendServerCommand(svs.clients + clientNum, "%s", text); } } -static qboolean SV_EntityContact( const vec3_t mins, const vec3_t maxs, const sharedEntity_t *gEnt, int capsule ) { - const float *origin, *angles; - clipHandle_t ch; - trace_t trace; +static qboolean SV_EntityContact(const vec3_t mins, const vec3_t maxs, const sharedEntity_t *gEnt, int capsule) { + const float *origin, *angles; + clipHandle_t ch; + trace_t trace; // check for exact collision origin = gEnt->r.currentOrigin; angles = gEnt->r.currentAngles; - ch = SV_ClipHandleForEntity( gEnt ); - CM_TransformedBoxTrace ( &trace, vec3_origin, vec3_origin, mins, maxs, - ch, -1, origin, angles, capsule ); + ch = SV_ClipHandleForEntity(gEnt); + CM_TransformedBoxTrace(&trace, vec3_origin, vec3_origin, mins, maxs, ch, -1, origin, angles, capsule); return (qboolean)trace.startsolid; } -static void SV_SetBrushModel( sharedEntity_t *ent, const char *name ) { - clipHandle_t h; - vec3_t mins, maxs; +static void SV_SetBrushModel(sharedEntity_t *ent, const char *name) { + clipHandle_t h; + vec3_t mins, maxs; - if (!name) - { - Com_Error( ERR_DROP, "SV_SetBrushModel: NULL" ); + if (!name) { + Com_Error(ERR_DROP, "SV_SetBrushModel: NULL"); } - if (name[0] == '*') - { - ent->s.modelindex = atoi( name + 1 ); + if (name[0] == '*') { + ent->s.modelindex = atoi(name + 1); - if (sv.mLocalSubBSPIndex != -1) - { + if (sv.mLocalSubBSPIndex != -1) { ent->s.modelindex += sv.mLocalSubBSPModelOffset; } - h = CM_InlineModel( ent->s.modelindex ); + h = CM_InlineModel(ent->s.modelindex); CM_ModelBounds(h, mins, maxs); - VectorCopy (mins, ent->r.mins); - VectorCopy (maxs, ent->r.maxs); + VectorCopy(mins, ent->r.mins); + VectorCopy(maxs, ent->r.maxs); ent->r.bmodel = qtrue; - ent->r.contents = CM_ModelContents( h, -1 ); - } - else if (name[0] == '#') - { + ent->r.contents = CM_ModelContents(h, -1); + } else if (name[0] == '#') { ent->s.modelindex = CM_LoadSubBSP(va("maps/%s.bsp", name + 1), qfalse); - CM_ModelBounds( ent->s.modelindex, mins, maxs ); + CM_ModelBounds(ent->s.modelindex, mins, maxs); - VectorCopy (mins, ent->r.mins); - VectorCopy (maxs, ent->r.maxs); + VectorCopy(mins, ent->r.mins); + VectorCopy(maxs, ent->r.maxs); ent->r.bmodel = qtrue; - //rwwNOTE: We don't ever want to set contents -1, it includes CONTENTS_LIGHTSABER. - //Lots of stuff will explode if there's a brush with CONTENTS_LIGHTSABER that isn't attached to a client owner. - //ent->contents = -1; // we don't know exactly what is in the brushes - h = CM_InlineModel( ent->s.modelindex ); - ent->r.contents = CM_ModelContents( h, CM_FindSubBSP(ent->s.modelindex) ); - } - else - { - Com_Error( ERR_DROP, "SV_SetBrushModel: %s isn't a brush model", name ); + // rwwNOTE: We don't ever want to set contents -1, it includes CONTENTS_LIGHTSABER. + // Lots of stuff will explode if there's a brush with CONTENTS_LIGHTSABER that isn't attached to a client owner. + // ent->contents = -1; // we don't know exactly what is in the brushes + h = CM_InlineModel(ent->s.modelindex); + ent->r.contents = CM_ModelContents(h, CM_FindSubBSP(ent->s.modelindex)); + } else { + Com_Error(ERR_DROP, "SV_SetBrushModel: %s isn't a brush model", name); } } -static qboolean SV_inPVSIgnorePortals( const vec3_t p1, const vec3_t p2 ) { - int leafnum, cluster; -// int area1, area2; - byte *mask; +static qboolean SV_inPVSIgnorePortals(const vec3_t p1, const vec3_t p2) { + int leafnum, cluster; + // int area1, area2; + byte *mask; - leafnum = CM_PointLeafnum( p1 ); - cluster = CM_LeafCluster( leafnum ); -// area1 = CM_LeafArea( leafnum ); - mask = CM_ClusterPVS( cluster ); + leafnum = CM_PointLeafnum(p1); + cluster = CM_LeafCluster(leafnum); + // area1 = CM_LeafArea( leafnum ); + mask = CM_ClusterPVS(cluster); - leafnum = CM_PointLeafnum( p2 ); - cluster = CM_LeafCluster( leafnum ); -// area2 = CM_LeafArea( leafnum ); + leafnum = CM_PointLeafnum(p2); + cluster = CM_LeafCluster(leafnum); + // area2 = CM_LeafArea( leafnum ); - if ( mask && (!(mask[cluster>>3] & (1<<(cluster&7)) ) ) ) + if (mask && (!(mask[cluster >> 3] & (1 << (cluster & 7))))) return qfalse; return qtrue; } -static void SV_GetServerinfo( char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetServerinfo: bufferSize == %i", bufferSize ); +static void SV_GetServerinfo(char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetServerinfo: bufferSize == %i", bufferSize); return; } - Q_strncpyz( buffer, Cvar_InfoString( CVAR_SERVERINFO ), bufferSize ); + Q_strncpyz(buffer, Cvar_InfoString(CVAR_SERVERINFO), bufferSize); } -static void SV_AdjustAreaPortalState( sharedEntity_t *ent, qboolean open ) { - svEntity_t *svEnt; +static void SV_AdjustAreaPortalState(sharedEntity_t *ent, qboolean open) { + svEntity_t *svEnt; - svEnt = SV_SvEntityForGentity( ent ); - if ( svEnt->areanum2 == -1 ) + svEnt = SV_SvEntityForGentity(ent); + if (svEnt->areanum2 == -1) return; - CM_AdjustAreaPortalState( svEnt->areanum, svEnt->areanum2, open ); + CM_AdjustAreaPortalState(svEnt->areanum, svEnt->areanum2, open); } -static void SV_GetUsercmd( int clientNum, usercmd_t *cmd ) { - if ( clientNum < 0 || clientNum >= sv_maxclients->integer ) { - Com_Error( ERR_DROP, "SV_GetUsercmd: bad clientNum:%i", clientNum ); +static void SV_GetUsercmd(int clientNum, usercmd_t *cmd) { + if (clientNum < 0 || clientNum >= sv_maxclients->integer) { + Com_Error(ERR_DROP, "SV_GetUsercmd: bad clientNum:%i", clientNum); return; } *cmd = svs.clients[clientNum].lastUsercmd; } static sharedEntity_t gLocalModifier; -static sharedEntity_t *ConvertedEntity( sharedEntity_t *ent ) { //Return an entity with the memory shifted around to allow reading/modifying VM memory +static sharedEntity_t *ConvertedEntity(sharedEntity_t *ent) { // Return an entity with the memory shifted around to allow reading/modifying VM memory int i = 0; assert(ent); gLocalModifier.s = ent->s; gLocalModifier.r = ent->r; - while (i < NUM_TIDS) - { + while (i < NUM_TIDS) { gLocalModifier.taskID[i] = ent->taskID[i]; i++; } i = 0; gLocalModifier.parms = (parms_t *)VM_ArgPtr((intptr_t)ent->parms); - while (i < NUM_BSETS) - { + while (i < NUM_BSETS) { gLocalModifier.behaviorSet[i] = (char *)VM_ArgPtr((intptr_t)ent->behaviorSet[i]); i++; } @@ -595,11 +587,11 @@ static sharedEntity_t *ConvertedEntity( sharedEntity_t *ent ) { //Return an enti return &gLocalModifier; } -static const char *SV_SetActiveSubBSP( int index ) { - if ( index >= 0 ) { - sv.mLocalSubBSPIndex = CM_FindSubBSP( index ); +static const char *SV_SetActiveSubBSP(int index) { + if (index >= 0) { + sv.mLocalSubBSPIndex = CM_FindSubBSP(index); sv.mLocalSubBSPModelOffset = index; - sv.mLocalSubBSPEntityParsePoint = CM_SubBSPEntityString( sv.mLocalSubBSPIndex ); + sv.mLocalSubBSPEntityParsePoint = CM_SubBSPEntityString(sv.mLocalSubBSPIndex); return sv.mLocalSubBSPEntityParsePoint; } @@ -607,1051 +599,741 @@ static const char *SV_SetActiveSubBSP( int index ) { return NULL; } -static qboolean SV_GetEntityToken( char *buffer, int bufferSize ) { +static qboolean SV_GetEntityToken(char *buffer, int bufferSize) { char *s; - if ( sv.mLocalSubBSPIndex == -1 ) { - s = COM_Parse( (const char **)&sv.entityParsePoint ); - Q_strncpyz( buffer, s, bufferSize ); - if ( !sv.entityParsePoint && !s[0] ) + if (sv.mLocalSubBSPIndex == -1) { + s = COM_Parse((const char **)&sv.entityParsePoint); + Q_strncpyz(buffer, s, bufferSize); + if (!sv.entityParsePoint && !s[0]) return qfalse; else return qtrue; - } - else { - s = COM_Parse( (const char **)&sv.mLocalSubBSPEntityParsePoint); - Q_strncpyz( buffer, s, bufferSize ); - if ( !sv.mLocalSubBSPEntityParsePoint && !s[0] ) + } else { + s = COM_Parse((const char **)&sv.mLocalSubBSPEntityParsePoint); + Q_strncpyz(buffer, s, bufferSize); + if (!sv.mLocalSubBSPEntityParsePoint && !s[0]) return qfalse; else return qtrue; } } -static void SV_PrecisionTimerStart( void **timer ) { - timing_c *newTimer = new timing_c; //create the new timer - *timer = newTimer; //assign the pointer within the pointer to point at the mem addr of our new timer - newTimer->Start(); //start the timer +static void SV_PrecisionTimerStart(void **timer) { + timing_c *newTimer = new timing_c; // create the new timer + *timer = newTimer; // assign the pointer within the pointer to point at the mem addr of our new timer + newTimer->Start(); // start the timer } -static int SV_PrecisionTimerEnd( void *timer ) { +static int SV_PrecisionTimerEnd(void *timer) { int r; - timing_c *theTimer = (timing_c *)timer; //this is the pointer we assigned in start, so we can directly cast it back - r = theTimer->End(); //get the result - delete theTimer; //delete the timer since we're done with it - return r; //return the result + timing_c *theTimer = (timing_c *)timer; // this is the pointer we assigned in start, so we can directly cast it back + r = theTimer->End(); // get the result + delete theTimer; // delete the timer since we're done with it + return r; // return the result } -static void SV_RegisterSharedMemory( char *memory ) { - sv.mSharedMemory = memory; -} +static void SV_RegisterSharedMemory(char *memory) { sv.mSharedMemory = memory; } -static void SV_SetServerCull( float cullDistance ) { - g_svCullDist = cullDistance; -} +static void SV_SetServerCull(float cullDistance) { g_svCullDist = cullDistance; } -static void SV_SiegePersSet( siegePers_t *siegePers ) { - sv_siegePersData = *siegePers; -} +static void SV_SiegePersSet(siegePers_t *siegePers) { sv_siegePersData = *siegePers; } -static void SV_SiegePersGet( siegePers_t *siegePers ) { - *siegePers = sv_siegePersData; -} +static void SV_SiegePersGet(siegePers_t *siegePers) { *siegePers = sv_siegePersData; } -qboolean SV_ROFF_Clean( void ) { - return theROFFSystem.Clean( qfalse ); -} +qboolean SV_ROFF_Clean(void) { return theROFFSystem.Clean(qfalse); } -void SV_ROFF_UpdateEntities( void ) { - theROFFSystem.UpdateEntities( qfalse ); -} +void SV_ROFF_UpdateEntities(void) { theROFFSystem.UpdateEntities(qfalse); } -int SV_ROFF_Cache( char *file ) { - return theROFFSystem.Cache( file, qfalse ); -} +int SV_ROFF_Cache(char *file) { return theROFFSystem.Cache(file, qfalse); } -qboolean SV_ROFF_Play( int entID, int roffID, qboolean doTranslation ) { - return theROFFSystem.Play( entID, roffID, doTranslation, qfalse ); -} +qboolean SV_ROFF_Play(int entID, int roffID, qboolean doTranslation) { return theROFFSystem.Play(entID, roffID, doTranslation, qfalse); } -qboolean SV_ROFF_Purge_Ent( int entID ) { - return theROFFSystem.PurgeEnt( entID, qfalse ); -} +qboolean SV_ROFF_Purge_Ent(int entID) { return theROFFSystem.PurgeEnt(entID, qfalse); } -static qboolean SV_ICARUS_RegisterScript( const char *name, qboolean bCalledDuringInterrogate ) { - return (qboolean)ICARUS_RegisterScript( name, bCalledDuringInterrogate ); +static qboolean SV_ICARUS_RegisterScript(const char *name, qboolean bCalledDuringInterrogate) { + return (qboolean)ICARUS_RegisterScript(name, bCalledDuringInterrogate); } -static qboolean SV_ICARUS_ValidEnt( sharedEntity_t *ent ) { - return (qboolean)ICARUS_ValidEnt( ent ); -} +static qboolean SV_ICARUS_ValidEnt(sharedEntity_t *ent) { return (qboolean)ICARUS_ValidEnt(ent); } -static qboolean ICARUS_IsInitialized( int entID ) { - if ( !gSequencers[entID] || !gTaskManagers[entID] ) +static qboolean ICARUS_IsInitialized(int entID) { + if (!gSequencers[entID] || !gTaskManagers[entID]) return qfalse; return qtrue; } -static qboolean ICARUS_MaintainTaskManager( int entID ) { - if ( gTaskManagers[entID] ) { +static qboolean ICARUS_MaintainTaskManager(int entID) { + if (gTaskManagers[entID]) { gTaskManagers[entID]->Update(); return qtrue; } return qfalse; } -static qboolean ICARUS_IsRunning( int entID ) { - if ( !gTaskManagers[entID] || !gTaskManagers[entID]->IsRunning() ) +static qboolean ICARUS_IsRunning(int entID) { + if (!gTaskManagers[entID] || !gTaskManagers[entID]->IsRunning()) return qfalse; return qtrue; } -static qboolean ICARUS_TaskIDPending( sharedEntity_t *ent, int taskID ) { - return Q3_TaskIDPending( ent, (taskID_t)taskID ); -} +static qboolean ICARUS_TaskIDPending(sharedEntity_t *ent, int taskID) { return Q3_TaskIDPending(ent, (taskID_t)taskID); } -static void SV_ICARUS_TaskIDSet( sharedEntity_t *ent, int taskType, int taskID ) { - Q3_TaskIDSet( ent, (taskID_t)taskType, taskID ); -} +static void SV_ICARUS_TaskIDSet(sharedEntity_t *ent, int taskType, int taskID) { Q3_TaskIDSet(ent, (taskID_t)taskType, taskID); } -static void SV_ICARUS_TaskIDComplete( sharedEntity_t *ent, int taskType ) { - Q3_TaskIDComplete( ent, (taskID_t)taskType ); -} +static void SV_ICARUS_TaskIDComplete(sharedEntity_t *ent, int taskType) { Q3_TaskIDComplete(ent, (taskID_t)taskType); } -static int SV_ICARUS_GetStringVariable( const char *name, const char *value ) { +static int SV_ICARUS_GetStringVariable(const char *name, const char *value) { const char *rec = (const char *)value; - return Q3_GetStringVariable( name, (const char **)&rec ); -} -static int SV_ICARUS_GetVectorVariable( const char *name, const vec3_t value ) { - return Q3_GetVectorVariable( name, (float *)value ); + return Q3_GetStringVariable(name, (const char **)&rec); } +static int SV_ICARUS_GetVectorVariable(const char *name, const vec3_t value) { return Q3_GetVectorVariable(name, (float *)value); } -static void SV_Nav_Init( void ) { - navigator.Init(); -} +static void SV_Nav_Init(void) { navigator.Init(); } -static void SV_Nav_Free( void ) { - navigator.Free(); -} +static void SV_Nav_Free(void) { navigator.Free(); } -static qboolean SV_Nav_Load( const char *filename, int checksum ) { - return (qboolean)navigator.Load( filename, checksum ); -} +static qboolean SV_Nav_Load(const char *filename, int checksum) { return (qboolean)navigator.Load(filename, checksum); } -static qboolean SV_Nav_Save( const char *filename, int checksum ) { - return (qboolean)navigator.Save( filename, checksum ); -} +static qboolean SV_Nav_Save(const char *filename, int checksum) { return (qboolean)navigator.Save(filename, checksum); } -static int SV_Nav_AddRawPoint( vec3_t point, int flags, int radius ) { - return navigator.AddRawPoint( point, flags, radius ); -} +static int SV_Nav_AddRawPoint(vec3_t point, int flags, int radius) { return navigator.AddRawPoint(point, flags, radius); } -static void SV_Nav_CalculatePaths( qboolean recalc ) { - navigator.CalculatePaths( recalc ); -} +static void SV_Nav_CalculatePaths(qboolean recalc) { navigator.CalculatePaths(recalc); } -static void SV_Nav_HardConnect( int first, int second ) { - navigator.HardConnect( first, second ); -} +static void SV_Nav_HardConnect(int first, int second) { navigator.HardConnect(first, second); } -static void SV_Nav_ShowNodes( void ) { - navigator.ShowNodes(); -} +static void SV_Nav_ShowNodes(void) { navigator.ShowNodes(); } -static void SV_Nav_ShowEdges( void ) { - navigator.ShowEdges(); -} +static void SV_Nav_ShowEdges(void) { navigator.ShowEdges(); } -static void SV_Nav_ShowPath( int start, int end ) { - navigator.ShowPath( start, end ); -} +static void SV_Nav_ShowPath(int start, int end) { navigator.ShowPath(start, end); } -static int SV_Nav_GetNearestNode( sharedEntity_t *ent, int lastID, int flags, int targetID ) { - return navigator.GetNearestNode( ent, lastID, flags, targetID ); -} +static int SV_Nav_GetNearestNode(sharedEntity_t *ent, int lastID, int flags, int targetID) { return navigator.GetNearestNode(ent, lastID, flags, targetID); } -static int SV_Nav_GetBestNode( int startID, int endID, int rejectID ) { - return navigator.GetBestNode( startID, endID, rejectID ); -} +static int SV_Nav_GetBestNode(int startID, int endID, int rejectID) { return navigator.GetBestNode(startID, endID, rejectID); } -static int SV_Nav_GetNodePosition( int nodeID, vec3_t out ) { - return navigator.GetNodePosition( nodeID, out ); -} +static int SV_Nav_GetNodePosition(int nodeID, vec3_t out) { return navigator.GetNodePosition(nodeID, out); } -static int SV_Nav_GetNodeNumEdges( int nodeID ) { - return navigator.GetNodeNumEdges( nodeID ); -} +static int SV_Nav_GetNodeNumEdges(int nodeID) { return navigator.GetNodeNumEdges(nodeID); } -static int SV_Nav_GetNodeEdge( int nodeID, int edge ) { - return navigator.GetNodeEdge( nodeID, edge ); -} +static int SV_Nav_GetNodeEdge(int nodeID, int edge) { return navigator.GetNodeEdge(nodeID, edge); } -static int SV_Nav_GetNumNodes( void ) { - return navigator.GetNumNodes(); -} +static int SV_Nav_GetNumNodes(void) { return navigator.GetNumNodes(); } -static qboolean SV_Nav_Connected( int startID, int endID ) { - return (qboolean)navigator.Connected( startID, endID ); -} +static qboolean SV_Nav_Connected(int startID, int endID) { return (qboolean)navigator.Connected(startID, endID); } -static int SV_Nav_GetPathCost( int startID, int endID ) { - return navigator.GetPathCost( startID, endID ); -} +static int SV_Nav_GetPathCost(int startID, int endID) { return navigator.GetPathCost(startID, endID); } -static int SV_Nav_GetEdgeCost( int startID, int endID ) { - return navigator.GetEdgeCost( startID, endID ); -} +static int SV_Nav_GetEdgeCost(int startID, int endID) { return navigator.GetEdgeCost(startID, endID); } -static int SV_Nav_GetProjectedNode( vec3_t origin, int nodeID ) { - return navigator.GetProjectedNode( origin, nodeID ); -} +static int SV_Nav_GetProjectedNode(vec3_t origin, int nodeID) { return navigator.GetProjectedNode(origin, nodeID); } -static void SV_Nav_CheckFailedNodes( sharedEntity_t *ent ) { - navigator.CheckFailedNodes( ent ); -} +static void SV_Nav_CheckFailedNodes(sharedEntity_t *ent) { navigator.CheckFailedNodes(ent); } -static void SV_Nav_AddFailedNode( sharedEntity_t *ent, int nodeID ) { - navigator.AddFailedNode( ent, nodeID ); -} +static void SV_Nav_AddFailedNode(sharedEntity_t *ent, int nodeID) { navigator.AddFailedNode(ent, nodeID); } -static qboolean SV_Nav_NodeFailed( sharedEntity_t *ent, int nodeID ) { - return navigator.NodeFailed( ent, nodeID ); -} +static qboolean SV_Nav_NodeFailed(sharedEntity_t *ent, int nodeID) { return navigator.NodeFailed(ent, nodeID); } -static qboolean SV_Nav_NodesAreNeighbors( int startID, int endID ) { - return navigator.NodesAreNeighbors( startID, endID ); -} +static qboolean SV_Nav_NodesAreNeighbors(int startID, int endID) { return navigator.NodesAreNeighbors(startID, endID); } -static void SV_Nav_ClearFailedEdge( failedEdge_t *failedEdge ) { - navigator.ClearFailedEdge( failedEdge ); -} +static void SV_Nav_ClearFailedEdge(failedEdge_t *failedEdge) { navigator.ClearFailedEdge(failedEdge); } -static void SV_Nav_ClearAllFailedEdges( void ) { - navigator.ClearAllFailedEdges(); -} +static void SV_Nav_ClearAllFailedEdges(void) { navigator.ClearAllFailedEdges(); } -static int SV_Nav_EdgeFailed( int startID, int endID ) { - return navigator.EdgeFailed( startID, endID ); -} +static int SV_Nav_EdgeFailed(int startID, int endID) { return navigator.EdgeFailed(startID, endID); } -static void SV_Nav_AddFailedEdge( int entID, int startID, int endID ) { - navigator.AddFailedEdge( entID, startID, endID ); -} +static void SV_Nav_AddFailedEdge(int entID, int startID, int endID) { navigator.AddFailedEdge(entID, startID, endID); } -static qboolean SV_Nav_CheckFailedEdge( failedEdge_t *failedEdge ) { - return navigator.CheckFailedEdge( failedEdge ); -} +static qboolean SV_Nav_CheckFailedEdge(failedEdge_t *failedEdge) { return navigator.CheckFailedEdge(failedEdge); } -static void SV_Nav_CheckAllFailedEdges( void ) { - navigator.CheckAllFailedEdges(); -} +static void SV_Nav_CheckAllFailedEdges(void) { navigator.CheckAllFailedEdges(); } -static qboolean SV_Nav_RouteBlocked( int startID, int testEdgeID, int endID, int rejectRank ) { - return navigator.RouteBlocked( startID, testEdgeID, endID, rejectRank ); +static qboolean SV_Nav_RouteBlocked(int startID, int testEdgeID, int endID, int rejectRank) { + return navigator.RouteBlocked(startID, testEdgeID, endID, rejectRank); } -static int SV_Nav_GetBestNodeAltRoute( int startID, int endID, int *pathCost, int rejectID ) { - return navigator.GetBestNodeAltRoute( startID, endID, pathCost, rejectID ); +static int SV_Nav_GetBestNodeAltRoute(int startID, int endID, int *pathCost, int rejectID) { + return navigator.GetBestNodeAltRoute(startID, endID, pathCost, rejectID); } -static int SV_Nav_GetBestNodeAltRoute2( int startID, int endID, int rejectID ) { - return navigator.GetBestNodeAltRoute( startID, endID, rejectID ); -} +static int SV_Nav_GetBestNodeAltRoute2(int startID, int endID, int rejectID) { return navigator.GetBestNodeAltRoute(startID, endID, rejectID); } -static int SV_Nav_GetBestPathBetweenEnts( sharedEntity_t *ent, sharedEntity_t *goal, int flags ) { - return navigator.GetBestPathBetweenEnts( ent, goal, flags ); -} +static int SV_Nav_GetBestPathBetweenEnts(sharedEntity_t *ent, sharedEntity_t *goal, int flags) { return navigator.GetBestPathBetweenEnts(ent, goal, flags); } -static int SV_Nav_GetNodeRadius( int nodeID ) { - return navigator.GetNodeRadius( nodeID ); -} +static int SV_Nav_GetNodeRadius(int nodeID) { return navigator.GetNodeRadius(nodeID); } -static void SV_Nav_CheckBlockedEdges( void ) { - navigator.CheckBlockedEdges(); -} +static void SV_Nav_CheckBlockedEdges(void) { navigator.CheckBlockedEdges(); } -static void SV_Nav_ClearCheckedNodes( void ) { - navigator.ClearCheckedNodes(); -} +static void SV_Nav_ClearCheckedNodes(void) { navigator.ClearCheckedNodes(); } -static int SV_Nav_CheckedNode( int wayPoint, int ent ) { - return navigator.CheckedNode( wayPoint, ent ); -} +static int SV_Nav_CheckedNode(int wayPoint, int ent) { return navigator.CheckedNode(wayPoint, ent); } -static void SV_Nav_SetCheckedNode( int wayPoint, int ent, int value ) { - navigator.SetCheckedNode( wayPoint, ent, value ); -} +static void SV_Nav_SetCheckedNode(int wayPoint, int ent, int value) { navigator.SetCheckedNode(wayPoint, ent, value); } -static void SV_Nav_FlagAllNodes( int newFlag ) { - navigator.FlagAllNodes( newFlag ); -} +static void SV_Nav_FlagAllNodes(int newFlag) { navigator.FlagAllNodes(newFlag); } -static qboolean SV_Nav_GetPathsCalculated( void ) { - return navigator.pathsCalculated; -} +static qboolean SV_Nav_GetPathsCalculated(void) { return navigator.pathsCalculated; } -static void SV_Nav_SetPathsCalculated( qboolean newVal ) { - navigator.pathsCalculated = newVal; -} +static void SV_Nav_SetPathsCalculated(qboolean newVal) { navigator.pathsCalculated = newVal; } -static int SV_BotLoadCharacter( char *charfile, float skill ) { - return botlib_export->ai.BotLoadCharacter( charfile, skill ); -} +static int SV_BotLoadCharacter(char *charfile, float skill) { return botlib_export->ai.BotLoadCharacter(charfile, skill); } -static void SV_BotFreeCharacter( int character ) { - botlib_export->ai.BotFreeCharacter( character ); -} +static void SV_BotFreeCharacter(int character) { botlib_export->ai.BotFreeCharacter(character); } -static float SV_Characteristic_Float( int character, int index ) { - return botlib_export->ai.Characteristic_Float( character, index ); -} +static float SV_Characteristic_Float(int character, int index) { return botlib_export->ai.Characteristic_Float(character, index); } -static float SV_Characteristic_BFloat( int character, int index, float min, float max ) { - return botlib_export->ai.Characteristic_BFloat( character, index, min, max ); +static float SV_Characteristic_BFloat(int character, int index, float min, float max) { + return botlib_export->ai.Characteristic_BFloat(character, index, min, max); } -static int SV_Characteristic_Integer( int character, int index ) { - return botlib_export->ai.Characteristic_Integer( character, index ); -} +static int SV_Characteristic_Integer(int character, int index) { return botlib_export->ai.Characteristic_Integer(character, index); } -static int SV_Characteristic_BInteger( int character, int index, int min, int max ) { - return botlib_export->ai.Characteristic_BInteger( character, index, min, max ); +static int SV_Characteristic_BInteger(int character, int index, int min, int max) { + return botlib_export->ai.Characteristic_BInteger(character, index, min, max); } -static void SV_Characteristic_String( int character, int index, char *buf, int size ) { - botlib_export->ai.Characteristic_String( character, index, buf, size ); -} +static void SV_Characteristic_String(int character, int index, char *buf, int size) { botlib_export->ai.Characteristic_String(character, index, buf, size); } -static int SV_BotAllocChatState( void ) { - return botlib_export->ai.BotAllocChatState(); -} +static int SV_BotAllocChatState(void) { return botlib_export->ai.BotAllocChatState(); } -static void SV_BotFreeChatState( int handle ) { - botlib_export->ai.BotFreeChatState( handle ); -} +static void SV_BotFreeChatState(int handle) { botlib_export->ai.BotFreeChatState(handle); } -static void SV_BotQueueConsoleMessage( int chatstate, int type, char *message ) { - botlib_export->ai.BotQueueConsoleMessage( chatstate, type, message ); -} +static void SV_BotQueueConsoleMessage(int chatstate, int type, char *message) { botlib_export->ai.BotQueueConsoleMessage(chatstate, type, message); } -static void SV_BotRemoveConsoleMessage( int chatstate, int handle ) { - botlib_export->ai.BotRemoveConsoleMessage( chatstate, handle ); -} +static void SV_BotRemoveConsoleMessage(int chatstate, int handle) { botlib_export->ai.BotRemoveConsoleMessage(chatstate, handle); } -static int SV_BotNextConsoleMessage( int chatstate, void *cm ) { - return botlib_export->ai.BotNextConsoleMessage( chatstate, (bot_consolemessage_s *)cm ); -} +static int SV_BotNextConsoleMessage(int chatstate, void *cm) { return botlib_export->ai.BotNextConsoleMessage(chatstate, (bot_consolemessage_s *)cm); } -static int SV_BotNumConsoleMessages( int chatstate ) { - return botlib_export->ai.BotNumConsoleMessages( chatstate ); -} +static int SV_BotNumConsoleMessages(int chatstate) { return botlib_export->ai.BotNumConsoleMessages(chatstate); } -static void SV_BotInitialChat( int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { - botlib_export->ai.BotInitialChat( chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); +static void SV_BotInitialChat(int chatstate, char *type, int mcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, + char *var7) { + botlib_export->ai.BotInitialChat(chatstate, type, mcontext, var0, var1, var2, var3, var4, var5, var6, var7); } -static int SV_BotReplyChat( int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, char *var6, char *var7 ) { - return botlib_export->ai.BotReplyChat( chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7 ); +static int SV_BotReplyChat(int chatstate, char *message, int mcontext, int vcontext, char *var0, char *var1, char *var2, char *var3, char *var4, char *var5, + char *var6, char *var7) { + return botlib_export->ai.BotReplyChat(chatstate, message, mcontext, vcontext, var0, var1, var2, var3, var4, var5, var6, var7); } -static int SV_BotChatLength( int chatstate ) { - return botlib_export->ai.BotChatLength( chatstate ); -} +static int SV_BotChatLength(int chatstate) { return botlib_export->ai.BotChatLength(chatstate); } -static void SV_BotEnterChat( int chatstate, int client, int sendto ) { - botlib_export->ai.BotEnterChat( chatstate, client, sendto ); -} +static void SV_BotEnterChat(int chatstate, int client, int sendto) { botlib_export->ai.BotEnterChat(chatstate, client, sendto); } -static int SV_StringContains( char *str1, char *str2, int casesensitive ) { - return botlib_export->ai.StringContains( str1, str2, casesensitive ); -} +static int SV_StringContains(char *str1, char *str2, int casesensitive) { return botlib_export->ai.StringContains(str1, str2, casesensitive); } -static int SV_BotFindMatch( char *str, void *match, unsigned long int context ) { - return botlib_export->ai.BotFindMatch( str, (bot_match_s *)match, context ); -} +static int SV_BotFindMatch(char *str, void *match, unsigned long int context) { return botlib_export->ai.BotFindMatch(str, (bot_match_s *)match, context); } -static void SV_BotMatchVariable( void *match, int variable, char *buf, int size ) { - botlib_export->ai.BotMatchVariable( (bot_match_s *)match, variable, buf, size ); +static void SV_BotMatchVariable(void *match, int variable, char *buf, int size) { + botlib_export->ai.BotMatchVariable((bot_match_s *)match, variable, buf, size); } -static void SV_UnifyWhiteSpaces( char *string ) { - botlib_export->ai.UnifyWhiteSpaces( string ); -} +static void SV_UnifyWhiteSpaces(char *string) { botlib_export->ai.UnifyWhiteSpaces(string); } -static void SV_BotReplaceSynonyms( char *string, unsigned long int context ) { - botlib_export->ai.BotReplaceSynonyms( string, context ); -} +static void SV_BotReplaceSynonyms(char *string, unsigned long int context) { botlib_export->ai.BotReplaceSynonyms(string, context); } -static int SV_BotLoadChatFile( int chatstate, char *chatfile, char *chatname ) { - return botlib_export->ai.BotLoadChatFile( chatstate, chatfile, chatname ); -} +static int SV_BotLoadChatFile(int chatstate, char *chatfile, char *chatname) { return botlib_export->ai.BotLoadChatFile(chatstate, chatfile, chatname); } -static void SV_BotSetChatGender( int chatstate, int gender ) { - botlib_export->ai.BotSetChatGender( chatstate, gender ); -} +static void SV_BotSetChatGender(int chatstate, int gender) { botlib_export->ai.BotSetChatGender(chatstate, gender); } -static void SV_BotSetChatName( int chatstate, char *name, int client ) { - botlib_export->ai.BotSetChatName( chatstate, name, client ); -} +static void SV_BotSetChatName(int chatstate, char *name, int client) { botlib_export->ai.BotSetChatName(chatstate, name, client); } -static void SV_BotResetGoalState( int goalstate ) { - botlib_export->ai.BotResetGoalState( goalstate ); -} +static void SV_BotResetGoalState(int goalstate) { botlib_export->ai.BotResetGoalState(goalstate); } -static void SV_BotResetAvoidGoals( int goalstate ) { - botlib_export->ai.BotResetAvoidGoals( goalstate ); -} +static void SV_BotResetAvoidGoals(int goalstate) { botlib_export->ai.BotResetAvoidGoals(goalstate); } -static void SV_BotPushGoal( int goalstate, void *goal ) { - botlib_export->ai.BotPushGoal( goalstate, (bot_goal_s *)goal ); -} +static void SV_BotPushGoal(int goalstate, void *goal) { botlib_export->ai.BotPushGoal(goalstate, (bot_goal_s *)goal); } -static void SV_BotPopGoal( int goalstate ) { - botlib_export->ai.BotPopGoal( goalstate ); -} +static void SV_BotPopGoal(int goalstate) { botlib_export->ai.BotPopGoal(goalstate); } -static void SV_BotEmptyGoalStack( int goalstate ) { - botlib_export->ai.BotEmptyGoalStack( goalstate ); -} +static void SV_BotEmptyGoalStack(int goalstate) { botlib_export->ai.BotEmptyGoalStack(goalstate); } -static void SV_BotDumpAvoidGoals( int goalstate ) { - botlib_export->ai.BotDumpAvoidGoals( goalstate ); -} +static void SV_BotDumpAvoidGoals(int goalstate) { botlib_export->ai.BotDumpAvoidGoals(goalstate); } -static void SV_BotDumpGoalStack( int goalstate ) { - botlib_export->ai.BotDumpGoalStack( goalstate ); -} +static void SV_BotDumpGoalStack(int goalstate) { botlib_export->ai.BotDumpGoalStack(goalstate); } -static void SV_BotGoalName( int number, char *name, int size ) { - botlib_export->ai.BotGoalName( number, name, size ); -} +static void SV_BotGoalName(int number, char *name, int size) { botlib_export->ai.BotGoalName(number, name, size); } -static int SV_BotGetTopGoal( int goalstate, void *goal ) { - return botlib_export->ai.BotGetTopGoal( goalstate, (bot_goal_s *)goal ); -} +static int SV_BotGetTopGoal(int goalstate, void *goal) { return botlib_export->ai.BotGetTopGoal(goalstate, (bot_goal_s *)goal); } -static int SV_BotGetSecondGoal( int goalstate, void *goal ) { - return botlib_export->ai.BotGetSecondGoal( goalstate, (bot_goal_s *)goal ); -} +static int SV_BotGetSecondGoal(int goalstate, void *goal) { return botlib_export->ai.BotGetSecondGoal(goalstate, (bot_goal_s *)goal); } -static int SV_BotChooseLTGItem( int goalstate, vec3_t origin, int *inventory, int travelflags ) { - return botlib_export->ai.BotChooseLTGItem( goalstate, origin, inventory, travelflags ); +static int SV_BotChooseLTGItem(int goalstate, vec3_t origin, int *inventory, int travelflags) { + return botlib_export->ai.BotChooseLTGItem(goalstate, origin, inventory, travelflags); } -static int SV_BotChooseNBGItem( int goalstate, vec3_t origin, int *inventory, int travelflags, void *ltg, float maxtime ) { - return botlib_export->ai.BotChooseNBGItem( goalstate, origin, inventory, travelflags, (bot_goal_s *)ltg, maxtime ); +static int SV_BotChooseNBGItem(int goalstate, vec3_t origin, int *inventory, int travelflags, void *ltg, float maxtime) { + return botlib_export->ai.BotChooseNBGItem(goalstate, origin, inventory, travelflags, (bot_goal_s *)ltg, maxtime); } -static int SV_BotTouchingGoal( vec3_t origin, void *goal ) { - return botlib_export->ai.BotTouchingGoal( origin, (bot_goal_s *)goal ); -} +static int SV_BotTouchingGoal(vec3_t origin, void *goal) { return botlib_export->ai.BotTouchingGoal(origin, (bot_goal_s *)goal); } -static int SV_BotItemGoalInVisButNotVisible( int viewer, vec3_t eye, vec3_t viewangles, void *goal ) { - return botlib_export->ai.BotItemGoalInVisButNotVisible( viewer, eye, viewangles, (bot_goal_s *)goal ); +static int SV_BotItemGoalInVisButNotVisible(int viewer, vec3_t eye, vec3_t viewangles, void *goal) { + return botlib_export->ai.BotItemGoalInVisButNotVisible(viewer, eye, viewangles, (bot_goal_s *)goal); } -static int SV_BotGetLevelItemGoal( int index, char *classname, void *goal ) { - return botlib_export->ai.BotGetLevelItemGoal( index, classname, (bot_goal_s *)goal ); +static int SV_BotGetLevelItemGoal(int index, char *classname, void *goal) { + return botlib_export->ai.BotGetLevelItemGoal(index, classname, (bot_goal_s *)goal); } -static float SV_BotAvoidGoalTime( int goalstate, int number ) { - return botlib_export->ai.BotAvoidGoalTime( goalstate, number ); -} +static float SV_BotAvoidGoalTime(int goalstate, int number) { return botlib_export->ai.BotAvoidGoalTime(goalstate, number); } -static void SV_BotInitLevelItems( void ) { - botlib_export->ai.BotInitLevelItems(); -} +static void SV_BotInitLevelItems(void) { botlib_export->ai.BotInitLevelItems(); } -static void SV_BotUpdateEntityItems( void ) { - botlib_export->ai.BotUpdateEntityItems(); -} +static void SV_BotUpdateEntityItems(void) { botlib_export->ai.BotUpdateEntityItems(); } -static int SV_BotLoadItemWeights( int goalstate, char *filename ) { - return botlib_export->ai.BotLoadItemWeights( goalstate, filename ); -} +static int SV_BotLoadItemWeights(int goalstate, char *filename) { return botlib_export->ai.BotLoadItemWeights(goalstate, filename); } -static void SV_BotFreeItemWeights( int goalstate ) { - botlib_export->ai.BotFreeItemWeights( goalstate ); -} +static void SV_BotFreeItemWeights(int goalstate) { botlib_export->ai.BotFreeItemWeights(goalstate); } -static void SV_BotSaveGoalFuzzyLogic( int goalstate, char *filename ) { - botlib_export->ai.BotSaveGoalFuzzyLogic( goalstate, filename ); -} +static void SV_BotSaveGoalFuzzyLogic(int goalstate, char *filename) { botlib_export->ai.BotSaveGoalFuzzyLogic(goalstate, filename); } -static int SV_BotAllocGoalState( int state ) { - return botlib_export->ai.BotAllocGoalState( state ); -} +static int SV_BotAllocGoalState(int state) { return botlib_export->ai.BotAllocGoalState(state); } -static void SV_BotFreeGoalState( int handle ) { - botlib_export->ai.BotFreeGoalState( handle ); -} +static void SV_BotFreeGoalState(int handle) { botlib_export->ai.BotFreeGoalState(handle); } -static void SV_BotResetMoveState( int movestate ) { - botlib_export->ai.BotResetMoveState( movestate ); -} +static void SV_BotResetMoveState(int movestate) { botlib_export->ai.BotResetMoveState(movestate); } -static void SV_BotMoveToGoal( void *result, int movestate, void *goal, int travelflags ) { - botlib_export->ai.BotMoveToGoal( (bot_moveresult_s *)result, movestate, (bot_goal_s *)goal, travelflags ); +static void SV_BotMoveToGoal(void *result, int movestate, void *goal, int travelflags) { + botlib_export->ai.BotMoveToGoal((bot_moveresult_s *)result, movestate, (bot_goal_s *)goal, travelflags); } -static int SV_BotMoveInDirection( int movestate, vec3_t dir, float speed, int type ) { - return botlib_export->ai.BotMoveInDirection( movestate, dir, speed, type ); -} +static int SV_BotMoveInDirection(int movestate, vec3_t dir, float speed, int type) { return botlib_export->ai.BotMoveInDirection(movestate, dir, speed, type); } -static void SV_BotResetAvoidReach( int movestate ) { - botlib_export->ai.BotResetAvoidReach( movestate ); -} +static void SV_BotResetAvoidReach(int movestate) { botlib_export->ai.BotResetAvoidReach(movestate); } -static void SV_BotResetLastAvoidReach( int movestate ) { - botlib_export->ai.BotResetLastAvoidReach( movestate ); -} +static void SV_BotResetLastAvoidReach(int movestate) { botlib_export->ai.BotResetLastAvoidReach(movestate); } -static int SV_BotReachabilityArea( vec3_t origin, int testground ) { - return botlib_export->ai.BotReachabilityArea( origin, testground ); -} +static int SV_BotReachabilityArea(vec3_t origin, int testground) { return botlib_export->ai.BotReachabilityArea(origin, testground); } -static int SV_BotMovementViewTarget( int movestate, void *goal, int travelflags, float lookahead, vec3_t target ) { - return botlib_export->ai.BotMovementViewTarget( movestate, (bot_goal_s *)goal, travelflags, lookahead, target ); +static int SV_BotMovementViewTarget(int movestate, void *goal, int travelflags, float lookahead, vec3_t target) { + return botlib_export->ai.BotMovementViewTarget(movestate, (bot_goal_s *)goal, travelflags, lookahead, target); } -static int SV_BotAllocMoveState( void ) { - return botlib_export->ai.BotAllocMoveState(); -} +static int SV_BotAllocMoveState(void) { return botlib_export->ai.BotAllocMoveState(); } -static void SV_BotFreeMoveState( int handle ) { - botlib_export->ai.BotFreeMoveState( handle ); -} +static void SV_BotFreeMoveState(int handle) { botlib_export->ai.BotFreeMoveState(handle); } -static void SV_BotInitMoveState( int handle, void *initmove ) { - botlib_export->ai.BotInitMoveState( handle, (bot_initmove_s *)initmove ); -} +static void SV_BotInitMoveState(int handle, void *initmove) { botlib_export->ai.BotInitMoveState(handle, (bot_initmove_s *)initmove); } -static int SV_BotChooseBestFightWeapon( int weaponstate, int *inventory ) { - return botlib_export->ai.BotChooseBestFightWeapon( weaponstate, inventory ); -} +static int SV_BotChooseBestFightWeapon(int weaponstate, int *inventory) { return botlib_export->ai.BotChooseBestFightWeapon(weaponstate, inventory); } -static void SV_BotGetWeaponInfo( int weaponstate, int weapon, void *weaponinfo ) { - botlib_export->ai.BotGetWeaponInfo( weaponstate, weapon, (weaponinfo_s *)weaponinfo ); +static void SV_BotGetWeaponInfo(int weaponstate, int weapon, void *weaponinfo) { + botlib_export->ai.BotGetWeaponInfo(weaponstate, weapon, (weaponinfo_s *)weaponinfo); } -static int SV_BotLoadWeaponWeights( int weaponstate, char *filename ) { - return botlib_export->ai.BotLoadWeaponWeights( weaponstate, filename ); -} +static int SV_BotLoadWeaponWeights(int weaponstate, char *filename) { return botlib_export->ai.BotLoadWeaponWeights(weaponstate, filename); } -static int SV_BotAllocWeaponState( void ) { - return botlib_export->ai.BotAllocWeaponState(); -} +static int SV_BotAllocWeaponState(void) { return botlib_export->ai.BotAllocWeaponState(); } -static void SV_BotFreeWeaponState( int weaponstate ) { - botlib_export->ai.BotFreeWeaponState( weaponstate ); -} +static void SV_BotFreeWeaponState(int weaponstate) { botlib_export->ai.BotFreeWeaponState(weaponstate); } -static void SV_BotResetWeaponState( int weaponstate ) { - botlib_export->ai.BotResetWeaponState( weaponstate ); -} +static void SV_BotResetWeaponState(int weaponstate) { botlib_export->ai.BotResetWeaponState(weaponstate); } -static int SV_GeneticParentsAndChildSelection( int numranks, float *ranks, int *parent1, int *parent2, int *child ) { - return botlib_export->ai.GeneticParentsAndChildSelection( numranks, ranks, parent1, parent2, child ); +static int SV_GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child) { + return botlib_export->ai.GeneticParentsAndChildSelection(numranks, ranks, parent1, parent2, child); } -static void SV_BotInterbreedGoalFuzzyLogic( int parent1, int parent2, int child ) { - botlib_export->ai.BotInterbreedGoalFuzzyLogic( parent1, parent2, child ); -} +static void SV_BotInterbreedGoalFuzzyLogic(int parent1, int parent2, int child) { botlib_export->ai.BotInterbreedGoalFuzzyLogic(parent1, parent2, child); } -static void SV_BotMutateGoalFuzzyLogic( int goalstate, float range ) { - botlib_export->ai.BotMutateGoalFuzzyLogic( goalstate, range ); -} +static void SV_BotMutateGoalFuzzyLogic(int goalstate, float range) { botlib_export->ai.BotMutateGoalFuzzyLogic(goalstate, range); } -static int SV_BotGetNextCampSpotGoal( int num, void *goal ) { - return botlib_export->ai.BotGetNextCampSpotGoal( num, (bot_goal_s *)goal ); -} +static int SV_BotGetNextCampSpotGoal(int num, void *goal) { return botlib_export->ai.BotGetNextCampSpotGoal(num, (bot_goal_s *)goal); } -static int SV_BotGetMapLocationGoal( char *name, void *goal ) { - return botlib_export->ai.BotGetMapLocationGoal( name, (bot_goal_s *)goal ); -} +static int SV_BotGetMapLocationGoal(char *name, void *goal) { return botlib_export->ai.BotGetMapLocationGoal(name, (bot_goal_s *)goal); } -static int SV_BotNumInitialChats( int chatstate, char *type ) { - return botlib_export->ai.BotNumInitialChats( chatstate, type ); -} +static int SV_BotNumInitialChats(int chatstate, char *type) { return botlib_export->ai.BotNumInitialChats(chatstate, type); } -static void SV_BotGetChatMessage( int chatstate, char *buf, int size ) { - botlib_export->ai.BotGetChatMessage( chatstate, buf, size ); -} +static void SV_BotGetChatMessage(int chatstate, char *buf, int size) { botlib_export->ai.BotGetChatMessage(chatstate, buf, size); } -static void SV_BotRemoveFromAvoidGoals( int goalstate, int number ) { - botlib_export->ai.BotRemoveFromAvoidGoals( goalstate, number ); -} +static void SV_BotRemoveFromAvoidGoals(int goalstate, int number) { botlib_export->ai.BotRemoveFromAvoidGoals(goalstate, number); } -static int SV_BotPredictVisiblePosition( vec3_t origin, int areanum, void *goal, int travelflags, vec3_t target ) { - return botlib_export->ai.BotPredictVisiblePosition( origin, areanum, (bot_goal_s *)goal, travelflags, target ); +static int SV_BotPredictVisiblePosition(vec3_t origin, int areanum, void *goal, int travelflags, vec3_t target) { + return botlib_export->ai.BotPredictVisiblePosition(origin, areanum, (bot_goal_s *)goal, travelflags, target); } -static void SV_BotSetAvoidGoalTime( int goalstate, int number, float avoidtime ) { - botlib_export->ai.BotSetAvoidGoalTime( goalstate, number, avoidtime ); -} +static void SV_BotSetAvoidGoalTime(int goalstate, int number, float avoidtime) { botlib_export->ai.BotSetAvoidGoalTime(goalstate, number, avoidtime); } -static void SV_BotAddAvoidSpot( int movestate, vec3_t origin, float radius, int type ) { - botlib_export->ai.BotAddAvoidSpot( movestate, origin, radius, type ); -} +static void SV_BotAddAvoidSpot(int movestate, vec3_t origin, float radius, int type) { botlib_export->ai.BotAddAvoidSpot(movestate, origin, radius, type); } -static int SV_BotLibSetup( void ) { - return botlib_export->BotLibSetup(); -} +static int SV_BotLibSetup(void) { return botlib_export->BotLibSetup(); } -static int SV_BotLibShutdown( void ) { - return botlib_export->BotLibShutdown(); -} +static int SV_BotLibShutdown(void) { return botlib_export->BotLibShutdown(); } -static int SV_BotLibVarSet( char *var_name, char *value ) { - return botlib_export->BotLibVarSet( var_name, value ); -} +static int SV_BotLibVarSet(char *var_name, char *value) { return botlib_export->BotLibVarSet(var_name, value); } -static int SV_BotLibVarGet( char *var_name, char *value, int size ) { - return botlib_export->BotLibVarGet( var_name, value, size ); -} +static int SV_BotLibVarGet(char *var_name, char *value, int size) { return botlib_export->BotLibVarGet(var_name, value, size); } -static int SV_BotLibDefine( char *string ) { - return botlib_export->PC_AddGlobalDefine( string ); -} +static int SV_BotLibDefine(char *string) { return botlib_export->PC_AddGlobalDefine(string); } -static int SV_BotLibStartFrame( float time ) { - return botlib_export->BotLibStartFrame( time ); -} +static int SV_BotLibStartFrame(float time) { return botlib_export->BotLibStartFrame(time); } -static int SV_BotLibLoadMap( const char *mapname ) { - return botlib_export->BotLibLoadMap( mapname ); -} +static int SV_BotLibLoadMap(const char *mapname) { return botlib_export->BotLibLoadMap(mapname); } -static int SV_BotLibUpdateEntity( int ent, void *bue ) { - return botlib_export->BotLibUpdateEntity( ent, (bot_entitystate_t *)bue ); -} +static int SV_BotLibUpdateEntity(int ent, void *bue) { return botlib_export->BotLibUpdateEntity(ent, (bot_entitystate_t *)bue); } -static int SV_BotLibTest( int parm0, char *parm1, vec3_t parm2, vec3_t parm3 ) { - return botlib_export->Test( parm0, parm1, parm2, parm3 ); -} +static int SV_BotLibTest(int parm0, char *parm1, vec3_t parm2, vec3_t parm3) { return botlib_export->Test(parm0, parm1, parm2, parm3); } -static int SV_BotGetServerCommand( int clientNum, char *message, int size ) { - return SV_BotGetConsoleMessage( clientNum, message, size ); -} +static int SV_BotGetServerCommand(int clientNum, char *message, int size) { return SV_BotGetConsoleMessage(clientNum, message, size); } -static void SV_BotUserCommand( int clientNum, usercmd_t *ucmd ) { - SV_ClientThink( &svs.clients[clientNum], ucmd ); -} +static void SV_BotUserCommand(int clientNum, usercmd_t *ucmd) { SV_ClientThink(&svs.clients[clientNum], ucmd); } -static int SV_AAS_EnableRoutingArea( int areanum, int enable ) { - return botlib_export->aas.AAS_EnableRoutingArea( areanum, enable ); -} +static int SV_AAS_EnableRoutingArea(int areanum, int enable) { return botlib_export->aas.AAS_EnableRoutingArea(areanum, enable); } -static int SV_AAS_BBoxAreas( vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas ) { - return botlib_export->aas.AAS_BBoxAreas( absmins, absmaxs, areas, maxareas ); +static int SV_AAS_BBoxAreas(vec3_t absmins, vec3_t absmaxs, int *areas, int maxareas) { + return botlib_export->aas.AAS_BBoxAreas(absmins, absmaxs, areas, maxareas); } -static int SV_AAS_AreaInfo( int areanum, void *info ) { - return botlib_export->aas.AAS_AreaInfo( areanum, (aas_areainfo_s *)info ); -} +static int SV_AAS_AreaInfo(int areanum, void *info) { return botlib_export->aas.AAS_AreaInfo(areanum, (aas_areainfo_s *)info); } -static void SV_AAS_EntityInfo( int entnum, void *info ) { - botlib_export->aas.AAS_EntityInfo( entnum, (aas_entityinfo_s *)info ); -} +static void SV_AAS_EntityInfo(int entnum, void *info) { botlib_export->aas.AAS_EntityInfo(entnum, (aas_entityinfo_s *)info); } -static int SV_AAS_Initialized( void ) { - return botlib_export->aas.AAS_Initialized(); -} +static int SV_AAS_Initialized(void) { return botlib_export->aas.AAS_Initialized(); } -static void SV_AAS_PresenceTypeBoundingBox( int presencetype, vec3_t mins, vec3_t maxs ) { - botlib_export->aas.AAS_PresenceTypeBoundingBox( presencetype, mins, maxs ); +static void SV_AAS_PresenceTypeBoundingBox(int presencetype, vec3_t mins, vec3_t maxs) { + botlib_export->aas.AAS_PresenceTypeBoundingBox(presencetype, mins, maxs); } -static float SV_AAS_Time( void ) { - return botlib_export->aas.AAS_Time(); -} +static float SV_AAS_Time(void) { return botlib_export->aas.AAS_Time(); } -static int SV_AAS_PointAreaNum( vec3_t point ) { - return botlib_export->aas.AAS_PointAreaNum( point ); -} +static int SV_AAS_PointAreaNum(vec3_t point) { return botlib_export->aas.AAS_PointAreaNum(point); } -static int SV_AAS_TraceAreas( vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas ) { - return botlib_export->aas.AAS_TraceAreas( start, end, areas, points, maxareas ); +static int SV_AAS_TraceAreas(vec3_t start, vec3_t end, int *areas, vec3_t *points, int maxareas) { + return botlib_export->aas.AAS_TraceAreas(start, end, areas, points, maxareas); } -static int SV_AAS_PointContents( vec3_t point ) { - return botlib_export->aas.AAS_PointContents( point ); -} +static int SV_AAS_PointContents(vec3_t point) { return botlib_export->aas.AAS_PointContents(point); } -static int SV_AAS_NextBSPEntity( int ent ) { - return botlib_export->aas.AAS_NextBSPEntity( ent ); -} +static int SV_AAS_NextBSPEntity(int ent) { return botlib_export->aas.AAS_NextBSPEntity(ent); } -static int SV_AAS_ValueForBSPEpairKey( int ent, char *key, char *value, int size ) { - return botlib_export->aas.AAS_ValueForBSPEpairKey( ent, key, value, size ); -} +static int SV_AAS_ValueForBSPEpairKey(int ent, char *key, char *value, int size) { return botlib_export->aas.AAS_ValueForBSPEpairKey(ent, key, value, size); } -static int SV_AAS_VectorForBSPEpairKey( int ent, char *key, vec3_t v ) { - return botlib_export->aas.AAS_VectorForBSPEpairKey( ent, key, v ); -} +static int SV_AAS_VectorForBSPEpairKey(int ent, char *key, vec3_t v) { return botlib_export->aas.AAS_VectorForBSPEpairKey(ent, key, v); } -static int SV_AAS_FloatForBSPEpairKey( int ent, char *key, float *value ) { - return botlib_export->aas.AAS_FloatForBSPEpairKey( ent, key, value ); -} +static int SV_AAS_FloatForBSPEpairKey(int ent, char *key, float *value) { return botlib_export->aas.AAS_FloatForBSPEpairKey(ent, key, value); } -static int SV_AAS_IntForBSPEpairKey( int ent, char *key, int *value ) { - return botlib_export->aas.AAS_IntForBSPEpairKey( ent, key, value ); -} +static int SV_AAS_IntForBSPEpairKey(int ent, char *key, int *value) { return botlib_export->aas.AAS_IntForBSPEpairKey(ent, key, value); } -static int SV_AAS_AreaReachability( int areanum ) { - return botlib_export->aas.AAS_AreaReachability( areanum ); -} +static int SV_AAS_AreaReachability(int areanum) { return botlib_export->aas.AAS_AreaReachability(areanum); } -static int SV_AAS_AreaTravelTimeToGoalArea( int areanum, vec3_t origin, int goalareanum, int travelflags ) { - return botlib_export->aas.AAS_AreaTravelTimeToGoalArea( areanum, origin, goalareanum, travelflags ); +static int SV_AAS_AreaTravelTimeToGoalArea(int areanum, vec3_t origin, int goalareanum, int travelflags) { + return botlib_export->aas.AAS_AreaTravelTimeToGoalArea(areanum, origin, goalareanum, travelflags); } -static int SV_AAS_Swimming( vec3_t origin ) { - return botlib_export->aas.AAS_Swimming( origin ); -} +static int SV_AAS_Swimming(vec3_t origin) { return botlib_export->aas.AAS_Swimming(origin); } -static int SV_AAS_PredictClientMovement( void *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, int maxframes, float frametime, int stopevent, int stopareanum, int visualize ) { - return botlib_export->aas.AAS_PredictClientMovement( (aas_clientmove_s *)move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, maxframes, frametime, stopevent, stopareanum, visualize ); +static int SV_AAS_PredictClientMovement(void *move, int entnum, vec3_t origin, int presencetype, int onground, vec3_t velocity, vec3_t cmdmove, int cmdframes, + int maxframes, float frametime, int stopevent, int stopareanum, int visualize) { + return botlib_export->aas.AAS_PredictClientMovement((aas_clientmove_s *)move, entnum, origin, presencetype, onground, velocity, cmdmove, cmdframes, + maxframes, frametime, stopevent, stopareanum, visualize); } -static int SV_AAS_AlternativeRouteGoals( vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, void *altroutegoals, int maxaltroutegoals, int type ) { - return botlib_export->aas.AAS_AlternativeRouteGoals( start, startareanum, goal, goalareanum, travelflags, (aas_altroutegoal_s *)altroutegoals, maxaltroutegoals, type ); +static int SV_AAS_AlternativeRouteGoals(vec3_t start, int startareanum, vec3_t goal, int goalareanum, int travelflags, void *altroutegoals, + int maxaltroutegoals, int type) { + return botlib_export->aas.AAS_AlternativeRouteGoals(start, startareanum, goal, goalareanum, travelflags, (aas_altroutegoal_s *)altroutegoals, + maxaltroutegoals, type); } -static int SV_AAS_PredictRoute( void *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, int stopcontents, int stoptfl, int stopareanum ) { - return botlib_export->aas.AAS_PredictRoute( (aas_predictroute_s *)route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, stopcontents, stoptfl, stopareanum ); +static int SV_AAS_PredictRoute(void *route, int areanum, vec3_t origin, int goalareanum, int travelflags, int maxareas, int maxtime, int stopevent, + int stopcontents, int stoptfl, int stopareanum) { + return botlib_export->aas.AAS_PredictRoute((aas_predictroute_s *)route, areanum, origin, goalareanum, travelflags, maxareas, maxtime, stopevent, + stopcontents, stoptfl, stopareanum); } -static int SV_AAS_PointReachabilityAreaIndex( vec3_t point ) { - return botlib_export->aas.AAS_PointReachabilityAreaIndex( point ); -} +static int SV_AAS_PointReachabilityAreaIndex(vec3_t point) { return botlib_export->aas.AAS_PointReachabilityAreaIndex(point); } -static void SV_EA_Say( int client, char *str ) { - botlib_export->ea.EA_Say( client, str ); -} +static void SV_EA_Say(int client, char *str) { botlib_export->ea.EA_Say(client, str); } -static void SV_EA_SayTeam( int client, char *str ) { - botlib_export->ea.EA_SayTeam( client, str ); -} +static void SV_EA_SayTeam(int client, char *str) { botlib_export->ea.EA_SayTeam(client, str); } -static void SV_EA_Command( int client, char *command ) { - botlib_export->ea.EA_Command( client, command ); -} +static void SV_EA_Command(int client, char *command) { botlib_export->ea.EA_Command(client, command); } -static void SV_EA_Action( int client, int action ) { - botlib_export->ea.EA_Action( client, action ); -} +static void SV_EA_Action(int client, int action) { botlib_export->ea.EA_Action(client, action); } -static void SV_EA_Gesture( int client ) { - botlib_export->ea.EA_Gesture( client ); -} +static void SV_EA_Gesture(int client) { botlib_export->ea.EA_Gesture(client); } -static void SV_EA_Talk( int client ) { - botlib_export->ea.EA_Talk( client ); -} +static void SV_EA_Talk(int client) { botlib_export->ea.EA_Talk(client); } -static void SV_EA_Attack( int client ) { - botlib_export->ea.EA_Attack( client ); -} +static void SV_EA_Attack(int client) { botlib_export->ea.EA_Attack(client); } -static void SV_EA_Alt_Attack( int client ) { - botlib_export->ea.EA_Alt_Attack( client ); -} +static void SV_EA_Alt_Attack(int client) { botlib_export->ea.EA_Alt_Attack(client); } -static void SV_EA_ForcePower( int client ) { - botlib_export->ea.EA_ForcePower( client ); -} +static void SV_EA_ForcePower(int client) { botlib_export->ea.EA_ForcePower(client); } -static void SV_EA_Use( int client ) { - botlib_export->ea.EA_Use( client ); -} +static void SV_EA_Use(int client) { botlib_export->ea.EA_Use(client); } -static void SV_EA_Respawn( int client ) { - botlib_export->ea.EA_Respawn( client ); -} +static void SV_EA_Respawn(int client) { botlib_export->ea.EA_Respawn(client); } -static void SV_EA_Crouch( int client ) { - botlib_export->ea.EA_Crouch( client ); -} +static void SV_EA_Crouch(int client) { botlib_export->ea.EA_Crouch(client); } -static void SV_EA_MoveUp( int client ) { - botlib_export->ea.EA_MoveUp( client ); -} +static void SV_EA_MoveUp(int client) { botlib_export->ea.EA_MoveUp(client); } -static void SV_EA_MoveDown( int client ) { - botlib_export->ea.EA_MoveDown( client ); -} +static void SV_EA_MoveDown(int client) { botlib_export->ea.EA_MoveDown(client); } -static void SV_EA_MoveForward( int client ) { - botlib_export->ea.EA_MoveForward( client ); -} +static void SV_EA_MoveForward(int client) { botlib_export->ea.EA_MoveForward(client); } -static void SV_EA_MoveBack( int client ) { - botlib_export->ea.EA_MoveBack( client ); -} +static void SV_EA_MoveBack(int client) { botlib_export->ea.EA_MoveBack(client); } -static void SV_EA_MoveLeft( int client ) { - botlib_export->ea.EA_MoveLeft( client ); -} +static void SV_EA_MoveLeft(int client) { botlib_export->ea.EA_MoveLeft(client); } -static void SV_EA_MoveRight( int client ) { - botlib_export->ea.EA_MoveRight( client ); -} +static void SV_EA_MoveRight(int client) { botlib_export->ea.EA_MoveRight(client); } -static void SV_EA_SelectWeapon( int client, int weapon ) { - botlib_export->ea.EA_SelectWeapon( client, weapon ); -} +static void SV_EA_SelectWeapon(int client, int weapon) { botlib_export->ea.EA_SelectWeapon(client, weapon); } -static void SV_EA_Jump( int client ) { - botlib_export->ea.EA_Jump( client ); -} +static void SV_EA_Jump(int client) { botlib_export->ea.EA_Jump(client); } -static void SV_EA_DelayedJump( int client ) { - botlib_export->ea.EA_DelayedJump( client ); -} +static void SV_EA_DelayedJump(int client) { botlib_export->ea.EA_DelayedJump(client); } -static void SV_EA_Move( int client, vec3_t dir, float speed ) { - botlib_export->ea.EA_Move( client, dir, speed ); -} +static void SV_EA_Move(int client, vec3_t dir, float speed) { botlib_export->ea.EA_Move(client, dir, speed); } -static void SV_EA_View( int client, vec3_t viewangles ) { - botlib_export->ea.EA_View( client, viewangles ); -} +static void SV_EA_View(int client, vec3_t viewangles) { botlib_export->ea.EA_View(client, viewangles); } -static void SV_EA_EndRegular( int client, float thinktime ) { - botlib_export->ea.EA_EndRegular( client, thinktime ); -} +static void SV_EA_EndRegular(int client, float thinktime) { botlib_export->ea.EA_EndRegular(client, thinktime); } -static void SV_EA_GetInput( int client, float thinktime, void *input ) { - botlib_export->ea.EA_GetInput( client, thinktime, (bot_input_t *)input ); -} +static void SV_EA_GetInput(int client, float thinktime, void *input) { botlib_export->ea.EA_GetInput(client, thinktime, (bot_input_t *)input); } -static void SV_EA_ResetInput( int client ) { - botlib_export->ea.EA_ResetInput( client ); -} +static void SV_EA_ResetInput(int client) { botlib_export->ea.EA_ResetInput(client); } -static int SV_PC_LoadSource( const char *filename ) { - return botlib_export->PC_LoadSourceHandle( filename ); -} +static int SV_PC_LoadSource(const char *filename) { return botlib_export->PC_LoadSourceHandle(filename); } -static int SV_PC_FreeSource( int handle ) { - return botlib_export->PC_FreeSourceHandle( handle ); -} +static int SV_PC_FreeSource(int handle) { return botlib_export->PC_FreeSourceHandle(handle); } -static int SV_PC_ReadToken( int handle, pc_token_t *pc_token ) { - return botlib_export->PC_ReadTokenHandle( handle, pc_token ); -} +static int SV_PC_ReadToken(int handle, pc_token_t *pc_token) { return botlib_export->PC_ReadTokenHandle(handle, pc_token); } -static int SV_PC_SourceFileAndLine( int handle, char *filename, int *line ) { - return botlib_export->PC_SourceFileAndLine( handle, filename, line ); -} +static int SV_PC_SourceFileAndLine(int handle, char *filename, int *line) { return botlib_export->PC_SourceFileAndLine(handle, filename, line); } -static qhandle_t SV_RE_RegisterSkin( const char *name ) { - return re->RegisterServerSkin( name ); -} +static qhandle_t SV_RE_RegisterSkin(const char *name) { return re->RegisterServerSkin(name); } -static int SV_CM_RegisterTerrain( const char *config ) { - return 0; -} +static int SV_CM_RegisterTerrain(const char *config) { return 0; } -static void SV_RMG_Init( void ) { } +static void SV_RMG_Init(void) {} -static void SV_G2API_ListModelSurfaces( void *ghlInfo ) { - re->G2API_ListSurfaces( (CGhoul2Info *)ghlInfo ); -} +static void SV_G2API_ListModelSurfaces(void *ghlInfo) { re->G2API_ListSurfaces((CGhoul2Info *)ghlInfo); } -static void SV_G2API_ListModelBones( void *ghlInfo, int frame ) { - re->G2API_ListBones( (CGhoul2Info *)ghlInfo, frame ); -} +static void SV_G2API_ListModelBones(void *ghlInfo, int frame) { re->G2API_ListBones((CGhoul2Info *)ghlInfo, frame); } -static void SV_G2API_SetGhoul2ModelIndexes( void *ghoul2, qhandle_t *modelList, qhandle_t *skinList ) { - if ( !ghoul2 ) return; - re->G2API_SetGhoul2ModelIndexes( *((CGhoul2Info_v *)ghoul2), modelList, skinList ); +static void SV_G2API_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { + if (!ghoul2) + return; + re->G2API_SetGhoul2ModelIndexes(*((CGhoul2Info_v *)ghoul2), modelList, skinList); } -static qboolean SV_G2API_HaveWeGhoul2Models( void *ghoul2) { - if ( !ghoul2 ) return qfalse; - return re->G2API_HaveWeGhoul2Models( *((CGhoul2Info_v *)ghoul2) ); +static qboolean SV_G2API_HaveWeGhoul2Models(void *ghoul2) { + if (!ghoul2) + return qfalse; + return re->G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ghoul2)); } -static qboolean SV_G2API_GetBoltMatrix( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); +static qboolean SV_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean SV_G2API_GetBoltMatrix_NoReconstruct( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; - re->G2API_BoltMatrixReconstruction( qfalse ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); +static qboolean SV_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; + re->G2API_BoltMatrixReconstruction(qfalse); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static qboolean SV_G2API_GetBoltMatrix_NoRecNoRot( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { - if ( !ghoul2 ) return qfalse; - re->G2API_BoltMatrixReconstruction( qfalse ); - re->G2API_BoltMatrixSPMethod( qtrue ); - return re->G2API_GetBoltMatrix( *((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale ); +static qboolean SV_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + if (!ghoul2) + return qfalse; + re->G2API_BoltMatrixReconstruction(qfalse); + re->G2API_BoltMatrixSPMethod(qtrue); + return re->G2API_GetBoltMatrix(*((CGhoul2Info_v *)ghoul2), modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale); } -static int SV_G2API_InitGhoul2Model( void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias ) { +static int SV_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 1; + g_G2AllocServer = 1; #endif - return re->G2API_InitGhoul2Model( (CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias ); + return re->G2API_InitGhoul2Model((CGhoul2Info_v **)ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } -static qboolean SV_G2API_SetSkin( void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin ) { - if ( !ghoul2 ) return qfalse; +static qboolean SV_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_SetSkin( g2, modelIndex, customSkin, renderSkin ); + return re->G2API_SetSkin(g2, modelIndex, customSkin, renderSkin); } -static void SV_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - if ( !ghoul2 ) return; - re->G2API_CollisionDetect( collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceServer, traceFlags, useLod, fRadius ); +static void SV_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) + return; + re->G2API_CollisionDetect(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceServer, + traceFlags, useLod, fRadius); } -static void SV_G2API_CollisionDetectCache( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { - if ( !ghoul2 ) return; - re->G2API_CollisionDetectCache( collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceServer, traceFlags, useLod, fRadius ); +static void SV_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + if (!ghoul2) + return; + re->G2API_CollisionDetectCache(collRecMap, *((CGhoul2Info_v *)ghoul2), angles, position, frameNumber, entNum, rayStart, rayEnd, scale, G2VertSpaceServer, + traceFlags, useLod, fRadius); } -static void SV_G2API_CleanGhoul2Models( void **ghoul2Ptr ) { +static void SV_G2API_CleanGhoul2Models(void **ghoul2Ptr) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 1; + g_G2AllocServer = 1; #endif - re->G2API_CleanGhoul2Models( (CGhoul2Info_v **)ghoul2Ptr ); + re->G2API_CleanGhoul2Models((CGhoul2Info_v **)ghoul2Ptr); } -static qboolean SV_G2API_SetBoneAngles( void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, const int forward, qhandle_t *modelList, int blendTime , int currentTime ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetBoneAngles( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName, angles, flags, (const Eorientations)up, (const Eorientations)right, (const Eorientations)forward, modelList, blendTime , currentTime ); +static qboolean SV_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { + if (!ghoul2) + return qfalse; + return re->G2API_SetBoneAngles(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, angles, flags, (const Eorientations)up, (const Eorientations)right, + (const Eorientations)forward, modelList, blendTime, currentTime); } -static qboolean SV_G2API_SetBoneAnim( void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame, const int blendTime ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetBoneAnim( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime ); +static qboolean SV_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + if (!ghoul2) + return qfalse; + return re->G2API_SetBoneAnim(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); } -static qboolean SV_G2API_GetBoneAnim( void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList, const int modelIndex ) { - if ( !ghoul2 ) return qfalse; +static qboolean SV_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_GetBoneAnim( g2, modelIndex, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList ); + return re->G2API_GetBoneAnim(g2, modelIndex, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList); } -static void SV_G2API_GetGLAName( void *ghoul2, int modelIndex, char *fillBuf ) { - if ( !ghoul2 ) - { +static void SV_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { + if (!ghoul2) { fillBuf[0] = '\0'; return; } - char *tmp = re->G2API_GetGLAName( *((CGhoul2Info_v *)ghoul2), modelIndex ); - if ( tmp ) - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetGLAName(*((CGhoul2Info_v *)ghoul2), modelIndex); + if (tmp) + strcpy(fillBuf, tmp); else fillBuf[0] = '\0'; } -static int SV_G2API_CopyGhoul2Instance( void *g2From, void *g2To, int modelIndex ) { - if ( !g2From || !g2To ) return 0; - return re->G2API_CopyGhoul2Instance( *((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex ); +static int SV_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { + if (!g2From || !g2To) + return 0; + return re->G2API_CopyGhoul2Instance(*((CGhoul2Info_v *)g2From), *((CGhoul2Info_v *)g2To), modelIndex); } -static void SV_G2API_CopySpecificGhoul2Model( void *g2From, int modelFrom, void *g2To, int modelTo ) { - if ( !g2From || !g2To ) return; - re->G2API_CopySpecificG2Model( *((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo ); +static void SV_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { + if (!g2From || !g2To) + return; + re->G2API_CopySpecificG2Model(*((CGhoul2Info_v *)g2From), modelFrom, *((CGhoul2Info_v *)g2To), modelTo); } -static void SV_G2API_DuplicateGhoul2Instance( void *g2From, void **g2To ) { +static void SV_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 1; + g_G2AllocServer = 1; #endif - if ( !g2From || !g2To ) return; - re->G2API_DuplicateGhoul2Instance( *((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To ); + if (!g2From || !g2To) + return; + re->G2API_DuplicateGhoul2Instance(*((CGhoul2Info_v *)g2From), (CGhoul2Info_v **)g2To); } -static qboolean SV_G2API_HasGhoul2ModelOnIndex( void *ghlInfo, int modelIndex ) { - return re->G2API_HasGhoul2ModelOnIndex( (CGhoul2Info_v **)ghlInfo, modelIndex ); -} +static qboolean SV_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { return re->G2API_HasGhoul2ModelOnIndex((CGhoul2Info_v **)ghlInfo, modelIndex); } -static qboolean SV_G2API_RemoveGhoul2Model( void *ghlInfo, int modelIndex ) { +static qboolean SV_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { #ifdef _FULL_G2_LEAK_CHECKING - g_G2AllocServer = 1; + g_G2AllocServer = 1; #endif - return re->G2API_RemoveGhoul2Model( (CGhoul2Info_v **)ghlInfo, modelIndex ); + return re->G2API_RemoveGhoul2Model((CGhoul2Info_v **)ghlInfo, modelIndex); } -static qboolean SV_G2API_RemoveGhoul2Models( void *ghlInfo ) { +static qboolean SV_G2API_RemoveGhoul2Models(void *ghlInfo) { #ifdef _FULL_G2_LEAK_CHECKING g_G2AllocServer = 1; #endif - return re->G2API_RemoveGhoul2Models( (CGhoul2Info_v **)ghlInfo ); + return re->G2API_RemoveGhoul2Models((CGhoul2Info_v **)ghlInfo); } -static int SV_G2API_Ghoul2Size( void *ghlInfo ) { - if ( !ghlInfo ) return 0; - return re->G2API_Ghoul2Size( *((CGhoul2Info_v *)ghlInfo) ); +static int SV_G2API_Ghoul2Size(void *ghlInfo) { + if (!ghlInfo) + return 0; + return re->G2API_Ghoul2Size(*((CGhoul2Info_v *)ghlInfo)); } -static int SV_G2API_AddBolt( void *ghoul2, int modelIndex, const char *boneName ) { - if ( !ghoul2 ) return -1; - return re->G2API_AddBolt( *((CGhoul2Info_v *)ghoul2), modelIndex, boneName ); +static int SV_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { + if (!ghoul2) + return -1; + return re->G2API_AddBolt(*((CGhoul2Info_v *)ghoul2), modelIndex, boneName); } -static void SV_G2API_SetBoltInfo( void *ghoul2, int modelIndex, int boltInfo ) { - if ( !ghoul2 ) return; - re->G2API_SetBoltInfo( *((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo ); +static void SV_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { + if (!ghoul2) + return; + re->G2API_SetBoltInfo(*((CGhoul2Info_v *)ghoul2), modelIndex, boltInfo); } -static qboolean SV_G2API_SetRootSurface( void *ghoul2, const int modelIndex, const char *surfaceName ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetRootSurface( *((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName ); +static qboolean SV_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const char *surfaceName) { + if (!ghoul2) + return qfalse; + return re->G2API_SetRootSurface(*((CGhoul2Info_v *)ghoul2), modelIndex, surfaceName); } -static qboolean SV_G2API_SetSurfaceOnOff( void *ghoul2, const char *surfaceName, const int flags ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetSurfaceOnOff( *((CGhoul2Info_v *)ghoul2), surfaceName, flags ); +static qboolean SV_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { + if (!ghoul2) + return qfalse; + return re->G2API_SetSurfaceOnOff(*((CGhoul2Info_v *)ghoul2), surfaceName, flags); } -static qboolean SV_G2API_SetNewOrigin( void *ghoul2, const int boltIndex ) { - if ( !ghoul2 ) return qfalse; - return re->G2API_SetNewOrigin( *((CGhoul2Info_v *)ghoul2), boltIndex ); +static qboolean SV_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { + if (!ghoul2) + return qfalse; + return re->G2API_SetNewOrigin(*((CGhoul2Info_v *)ghoul2), boltIndex); } -static qboolean SV_G2API_DoesBoneExist( void *ghoul2, int modelIndex, const char *boneName ) { - if ( !ghoul2 ) return qfalse; +static qboolean SV_G2API_DoesBoneExist(void *ghoul2, int modelIndex, const char *boneName) { + if (!ghoul2) + return qfalse; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_DoesBoneExist( g2, modelIndex, boneName ); + return re->G2API_DoesBoneExist(g2, modelIndex, boneName); } -static int SV_G2API_GetSurfaceRenderStatus( void *ghoul2, const int modelIndex, const char *surfaceName ) { - if ( !ghoul2 ) return -1; +static int SV_G2API_GetSurfaceRenderStatus(void *ghoul2, const int modelIndex, const char *surfaceName) { + if (!ghoul2) + return -1; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_GetSurfaceRenderStatus( g2, modelIndex, surfaceName ); + return re->G2API_GetSurfaceRenderStatus(g2, modelIndex, surfaceName); } -static void SV_G2API_AbsurdSmoothing( void *ghoul2, qboolean status ) { - if ( !ghoul2 ) return; +static void SV_G2API_AbsurdSmoothing(void *ghoul2, qboolean status) { + if (!ghoul2) + return; CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - re->G2API_AbsurdSmoothing( g2, status ); + re->G2API_AbsurdSmoothing(g2, status); } -static void SV_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { - if ( !ghoul2 ) return; +static void SV_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { + if (!ghoul2) + return; CRagDollParams rdParams; - if ( !params ) { - re->G2API_ResetRagDoll( *((CGhoul2Info_v *)ghoul2) ); + if (!params) { + re->G2API_ResetRagDoll(*((CGhoul2Info_v *)ghoul2)); return; } - VectorCopy( params->angles, rdParams.angles ); - VectorCopy( params->position, rdParams.position ); - VectorCopy( params->scale, rdParams.scale ); - VectorCopy( params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset ); - VectorCopy( params->pelvisPositionOffset, rdParams.pelvisPositionOffset ); + VectorCopy(params->angles, rdParams.angles); + VectorCopy(params->position, rdParams.position); + VectorCopy(params->scale, rdParams.scale); + VectorCopy(params->pelvisAnglesOffset, rdParams.pelvisAnglesOffset); + VectorCopy(params->pelvisPositionOffset, rdParams.pelvisPositionOffset); rdParams.fImpactStrength = params->fImpactStrength; rdParams.fShotStrength = params->fShotStrength; @@ -1666,139 +1348,129 @@ static void SV_G2API_SetRagDoll( void *ghoul2, sharedRagDollParams_t *params ) { rdParams.RagPhase = (CRagDollParams::ERagPhase)params->RagPhase; rdParams.effectorsToTurnOff = (CRagDollParams::ERagEffector)params->effectorsToTurnOff; - re->G2API_SetRagDoll( *((CGhoul2Info_v *)ghoul2), &rdParams ); + re->G2API_SetRagDoll(*((CGhoul2Info_v *)ghoul2), &rdParams); } -static void SV_G2API_AnimateG2Models( void *ghoul2, int time, sharedRagDollUpdateParams_t *params ) { +static void SV_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { CRagDollUpdateParams rduParams; - if ( !params ) + if (!params) return; - VectorCopy( params->angles, rduParams.angles ); - VectorCopy( params->position, rduParams.position ); - VectorCopy( params->scale, rduParams.scale ); - VectorCopy( params->velocity, rduParams.velocity ); + VectorCopy(params->angles, rduParams.angles); + VectorCopy(params->position, rduParams.position); + VectorCopy(params->scale, rduParams.scale); + VectorCopy(params->velocity, rduParams.velocity); rduParams.me = params->me; rduParams.settleFrame = params->settleFrame; - re->G2API_AnimateG2ModelsRag( *((CGhoul2Info_v *)ghoul2), time, &rduParams ); + re->G2API_AnimateG2ModelsRag(*((CGhoul2Info_v *)ghoul2), time, &rduParams); } -static qboolean SV_G2API_RagPCJConstraint( void *ghoul2, const char *boneName, vec3_t min, vec3_t max ) { - return re->G2API_RagPCJConstraint( *((CGhoul2Info_v *)ghoul2), boneName, min, max ); +static qboolean SV_G2API_RagPCJConstraint(void *ghoul2, const char *boneName, vec3_t min, vec3_t max) { + return re->G2API_RagPCJConstraint(*((CGhoul2Info_v *)ghoul2), boneName, min, max); } -static qboolean SV_G2API_RagPCJGradientSpeed( void *ghoul2, const char *boneName, const float speed ) { - return re->G2API_RagPCJGradientSpeed( *((CGhoul2Info_v *)ghoul2), boneName, speed ); +static qboolean SV_G2API_RagPCJGradientSpeed(void *ghoul2, const char *boneName, const float speed) { + return re->G2API_RagPCJGradientSpeed(*((CGhoul2Info_v *)ghoul2), boneName, speed); } -static qboolean SV_G2API_RagEffectorGoal( void *ghoul2, const char *boneName, vec3_t pos ) { - return re->G2API_RagEffectorGoal( *((CGhoul2Info_v *)ghoul2), boneName, pos ); +static qboolean SV_G2API_RagEffectorGoal(void *ghoul2, const char *boneName, vec3_t pos) { + return re->G2API_RagEffectorGoal(*((CGhoul2Info_v *)ghoul2), boneName, pos); } -static qboolean SV_G2API_GetRagBonePos( void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale ) { - return re->G2API_GetRagBonePos( *((CGhoul2Info_v *)ghoul2), boneName, pos, entAngles, entPos, entScale ); +static qboolean SV_G2API_GetRagBonePos(void *ghoul2, const char *boneName, vec3_t pos, vec3_t entAngles, vec3_t entPos, vec3_t entScale) { + return re->G2API_GetRagBonePos(*((CGhoul2Info_v *)ghoul2), boneName, pos, entAngles, entPos, entScale); } -static qboolean SV_G2API_RagEffectorKick( void *ghoul2, const char *boneName, vec3_t velocity ) { - return re->G2API_RagEffectorKick( *((CGhoul2Info_v *)ghoul2), boneName, velocity ); +static qboolean SV_G2API_RagEffectorKick(void *ghoul2, const char *boneName, vec3_t velocity) { + return re->G2API_RagEffectorKick(*((CGhoul2Info_v *)ghoul2), boneName, velocity); } -static qboolean SV_G2API_RagForceSolve( void *ghoul2, qboolean force ) { - return re->G2API_RagForceSolve( *((CGhoul2Info_v *)ghoul2), force ); -} +static qboolean SV_G2API_RagForceSolve(void *ghoul2, qboolean force) { return re->G2API_RagForceSolve(*((CGhoul2Info_v *)ghoul2), force); } -static qboolean SV_G2API_SetBoneIKState( void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params ) { - return re->G2API_SetBoneIKState( *((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params ); +static qboolean SV_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { + return re->G2API_SetBoneIKState(*((CGhoul2Info_v *)ghoul2), time, boneName, ikState, params); } -static qboolean SV_G2API_IKMove( void *ghoul2, int time, sharedIKMoveParams_t *params ) { - return re->G2API_IKMove( *((CGhoul2Info_v *)ghoul2), time, params ); -} +static qboolean SV_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { return re->G2API_IKMove(*((CGhoul2Info_v *)ghoul2), time, params); } -static qboolean SV_G2API_RemoveBone( void *ghoul2, const char *boneName, int modelIndex ) { +static qboolean SV_G2API_RemoveBone(void *ghoul2, const char *boneName, int modelIndex) { CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - return re->G2API_RemoveBone( g2, modelIndex, boneName ); + return re->G2API_RemoveBone(g2, modelIndex, boneName); } -static void SV_G2API_AttachInstanceToEntNum( void *ghoul2, int entityNum, qboolean server ) { - re->G2API_AttachInstanceToEntNum( *((CGhoul2Info_v *)ghoul2), entityNum, server ); +static void SV_G2API_AttachInstanceToEntNum(void *ghoul2, int entityNum, qboolean server) { + re->G2API_AttachInstanceToEntNum(*((CGhoul2Info_v *)ghoul2), entityNum, server); } -static void SV_G2API_ClearAttachedInstance( int entityNum ) { - re->G2API_ClearAttachedInstance( entityNum ); -} +static void SV_G2API_ClearAttachedInstance(int entityNum) { re->G2API_ClearAttachedInstance(entityNum); } -static void SV_G2API_CleanEntAttachments( void ) { - re->G2API_CleanEntAttachments(); -} +static void SV_G2API_CleanEntAttachments(void) { re->G2API_CleanEntAttachments(); } -static qboolean SV_G2API_OverrideServer( void *serverInstance ) { +static qboolean SV_G2API_OverrideServer(void *serverInstance) { CGhoul2Info_v &g2 = *((CGhoul2Info_v *)serverInstance); - return re->G2API_OverrideServerWithClientData( g2, 0 ); + return re->G2API_OverrideServerWithClientData(g2, 0); } -static void SV_G2API_GetSurfaceName( void *ghoul2, int surfNumber, int modelIndex, char *fillBuf ) { +static void SV_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { CGhoul2Info_v &g2 = *((CGhoul2Info_v *)ghoul2); - char *tmp = re->G2API_GetSurfaceName( g2, modelIndex, surfNumber ); - strcpy( fillBuf, tmp ); + char *tmp = re->G2API_GetSurfaceName(g2, modelIndex, surfNumber); + strcpy(fillBuf, tmp); } -static void GVM_Cvar_Set( const char *var_name, const char *value ) { - Cvar_VM_Set( var_name, value, VM_GAME ); -} +static void GVM_Cvar_Set(const char *var_name, const char *value) { Cvar_VM_Set(var_name, value, VM_GAME); } // legacy syscall -intptr_t SV_GameSystemCalls( intptr_t *args ) { - switch( args[0] ) { +intptr_t SV_GameSystemCalls(intptr_t *args) { + switch (args[0]) { - //rww - alright, DO NOT EVER add a game/cgame/ui generic call without adding a trap to match, and - //all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also - //all be in the same order, and start at 100. + // rww - alright, DO NOT EVER add a game/cgame/ui generic call without adding a trap to match, and + // all of these traps must be shared and have cases in sv_game, cl_cgame, and cl_ui. They must also + // all be in the same order, and start at 100. case TRAP_MEMSET: - Com_Memset( VMA(1), args[2], args[3] ); + Com_Memset(VMA(1), args[2], args[3]); return 0; case TRAP_MEMCPY: - Com_Memcpy( VMA(1), VMA(2), args[3] ); + Com_Memcpy(VMA(1), VMA(2), args[3]); return 0; case TRAP_STRNCPY: - strncpy( (char *)VMA(1), (const char *)VMA(2), args[3] ); + strncpy((char *)VMA(1), (const char *)VMA(2), args[3]); return args[1]; case TRAP_SIN: - return FloatAsInt( sin( VMF(1) ) ); + return FloatAsInt(sin(VMF(1))); case TRAP_COS: - return FloatAsInt( cos( VMF(1) ) ); + return FloatAsInt(cos(VMF(1))); case TRAP_ATAN2: - return FloatAsInt( atan2( VMF(1), VMF(2) ) ); + return FloatAsInt(atan2(VMF(1), VMF(2))); case TRAP_SQRT: - return FloatAsInt( sqrt( VMF(1) ) ); + return FloatAsInt(sqrt(VMF(1))); case TRAP_MATRIXMULTIPLY: - MatrixMultiply( (vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3) ); + MatrixMultiply((vec3_t *)VMA(1), (vec3_t *)VMA(2), (vec3_t *)VMA(3)); return 0; case TRAP_ANGLEVECTORS: - AngleVectors( (const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4) ); + AngleVectors((const float *)VMA(1), (float *)VMA(2), (float *)VMA(3), (float *)VMA(4)); return 0; case TRAP_PERPENDICULARVECTOR: - PerpendicularVector( (float *)VMA(1), (const float *)VMA(2) ); + PerpendicularVector((float *)VMA(1), (const float *)VMA(2)); return 0; case TRAP_FLOOR: - return FloatAsInt( floor( VMF(1) ) ); + return FloatAsInt(floor(VMF(1))); case TRAP_CEIL: - return FloatAsInt( ceil( VMF(1) ) ); + return FloatAsInt(ceil(VMF(1))); case TRAP_TESTPRINTINT: return 0; @@ -1807,168 +1479,171 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; case TRAP_ACOS: - return FloatAsInt( Q_acos( VMF(1) ) ); + return FloatAsInt(Q_acos(VMF(1))); case TRAP_ASIN: - return FloatAsInt( Q_asin( VMF(1) ) ); + return FloatAsInt(Q_asin(VMF(1))); case G_PRINT: - Com_Printf( "%s", VMA(1) ); + Com_Printf("%s", VMA(1)); return 0; case G_ERROR: - Com_Error( ERR_DROP, "%s", VMA(1) ); + Com_Error(ERR_DROP, "%s", VMA(1)); return 0; case G_MILLISECONDS: return Sys_Milliseconds(); case G_PRECISIONTIMER_START: - SV_PrecisionTimerStart( (void **)VMA(1) ); + SV_PrecisionTimerStart((void **)VMA(1)); return 0; case G_PRECISIONTIMER_END: - return SV_PrecisionTimerEnd( (void *)args[1] ); + return SV_PrecisionTimerEnd((void *)args[1]); case G_CVAR_REGISTER: - Cvar_Register( (vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4] ); + Cvar_Register((vmCvar_t *)VMA(1), (const char *)VMA(2), (const char *)VMA(3), args[4]); return 0; case G_CVAR_UPDATE: - Cvar_Update( (vmCvar_t *)VMA(1) ); + Cvar_Update((vmCvar_t *)VMA(1)); return 0; case G_CVAR_SET: - Cvar_VM_Set( (const char *)VMA(1), (const char *)VMA(2), VM_GAME ); + Cvar_VM_Set((const char *)VMA(1), (const char *)VMA(2), VM_GAME); return 0; case G_CVAR_VARIABLE_INTEGER_VALUE: - return Cvar_VariableIntegerValue( (const char *)VMA(1) ); + return Cvar_VariableIntegerValue((const char *)VMA(1)); case G_CVAR_VARIABLE_STRING_BUFFER: - Cvar_VariableStringBuffer( (const char *)VMA(1), (char *)VMA(2), args[3] ); + Cvar_VariableStringBuffer((const char *)VMA(1), (char *)VMA(2), args[3]); return 0; case G_ARGC: return Cmd_Argc(); case G_ARGV: - Cmd_ArgvBuffer( args[1], (char *)VMA(2), args[3] ); + Cmd_ArgvBuffer(args[1], (char *)VMA(2), args[3]); return 0; case G_SEND_CONSOLE_COMMAND: - Cbuf_ExecuteText( args[1], (const char *)VMA(2) ); + Cbuf_ExecuteText(args[1], (const char *)VMA(2)); return 0; case G_FS_FOPEN_FILE: - return FS_FOpenFileByMode( (const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3] ); + return FS_FOpenFileByMode((const char *)VMA(1), (int *)VMA(2), (fsMode_t)args[3]); case G_FS_READ: - FS_Read( VMA(1), args[2], args[3] ); + FS_Read(VMA(1), args[2], args[3]); return 0; case G_FS_WRITE: - FS_Write( VMA(1), args[2], args[3] ); + FS_Write(VMA(1), args[2], args[3]); return 0; case G_FS_FCLOSE_FILE: - FS_FCloseFile( args[1] ); + FS_FCloseFile(args[1]); return 0; case G_FS_GETFILELIST: - return FS_GetFileList( (const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4] ); + return FS_GetFileList((const char *)VMA(1), (const char *)VMA(2), (char *)VMA(3), args[4]); case G_LOCATE_GAME_DATA: - SV_LocateGameData( (sharedEntity_t *)VMA(1), args[2], args[3], (struct playerState_s *)VMA(4), args[5] ); + SV_LocateGameData((sharedEntity_t *)VMA(1), args[2], args[3], (struct playerState_s *)VMA(4), args[5]); return 0; case G_DROP_CLIENT: - SV_GameDropClient( args[1], (const char *)VMA(2) ); + SV_GameDropClient(args[1], (const char *)VMA(2)); return 0; case G_SEND_SERVER_COMMAND: - SV_GameSendServerCommand( args[1], (const char *)VMA(2) ); + SV_GameSendServerCommand(args[1], (const char *)VMA(2)); return 0; case G_LINKENTITY: - SV_LinkEntity( (sharedEntity_t *)VMA(1) ); + SV_LinkEntity((sharedEntity_t *)VMA(1)); return 0; case G_UNLINKENTITY: - SV_UnlinkEntity( (sharedEntity_t *)VMA(1) ); + SV_UnlinkEntity((sharedEntity_t *)VMA(1)); return 0; case G_ENTITIES_IN_BOX: - return SV_AreaEntities( (const float *)VMA(1), (const float *)VMA(2), (int *)VMA(3), args[4] ); + return SV_AreaEntities((const float *)VMA(1), (const float *)VMA(2), (int *)VMA(3), args[4]); case G_ENTITY_CONTACT: - return SV_EntityContact( (const float *)VMA(1), (const float *)VMA(2), (const sharedEntity_t *)VMA(3), /*int capsule*/ qfalse ); + return SV_EntityContact((const float *)VMA(1), (const float *)VMA(2), (const sharedEntity_t *)VMA(3), /*int capsule*/ qfalse); case G_ENTITY_CONTACTCAPSULE: - return SV_EntityContact( (const float *)VMA(1), (const float *)VMA(2), (const sharedEntity_t *)VMA(3), /*int capsule*/ qtrue ); + return SV_EntityContact((const float *)VMA(1), (const float *)VMA(2), (const sharedEntity_t *)VMA(3), /*int capsule*/ qtrue); case G_TRACE: - SV_Trace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], /*int capsule*/ qfalse, /*args[8]*/0, args[9] ); + SV_Trace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + /*int capsule*/ qfalse, /*args[8]*/ 0, args[9]); return 0; case G_G2TRACE: - SV_Trace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], /*int capsule*/ qfalse, args[8], args[9] ); + SV_Trace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + /*int capsule*/ qfalse, args[8], args[9]); return 0; case G_TRACECAPSULE: - SV_Trace( (trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], /*int capsule*/ qtrue, args[8], args[9] ); + SV_Trace((trace_t *)VMA(1), (const float *)VMA(2), (const float *)VMA(3), (const float *)VMA(4), (const float *)VMA(5), args[6], args[7], + /*int capsule*/ qtrue, args[8], args[9]); return 0; case G_POINT_CONTENTS: - return SV_PointContents( (const float *)VMA(1), args[2] ); + return SV_PointContents((const float *)VMA(1), args[2]); case G_SET_SERVER_CULL: - SV_SetServerCull( VMF( 1 ) ); + SV_SetServerCull(VMF(1)); return 0; case G_SET_BRUSH_MODEL: - SV_SetBrushModel( (sharedEntity_t *)VMA(1), (const char *)VMA(2) ); + SV_SetBrushModel((sharedEntity_t *)VMA(1), (const char *)VMA(2)); return 0; case G_IN_PVS: - return SV_inPVS( (const float *)VMA(1), (const float *)VMA(2) ); + return SV_inPVS((const float *)VMA(1), (const float *)VMA(2)); case G_IN_PVS_IGNORE_PORTALS: - return SV_inPVSIgnorePortals( (const float *)VMA(1), (const float *)VMA(2) ); + return SV_inPVSIgnorePortals((const float *)VMA(1), (const float *)VMA(2)); case G_SET_CONFIGSTRING: - SV_SetConfigstring( args[1], (const char *)VMA(2) ); + SV_SetConfigstring(args[1], (const char *)VMA(2)); return 0; case G_GET_CONFIGSTRING: - SV_GetConfigstring( args[1], (char *)VMA(2), args[3] ); + SV_GetConfigstring(args[1], (char *)VMA(2), args[3]); return 0; case G_SET_USERINFO: - SV_SetUserinfo( args[1], (const char *)VMA(2) ); + SV_SetUserinfo(args[1], (const char *)VMA(2)); return 0; case G_GET_USERINFO: - SV_GetUserinfo( args[1], (char *)VMA(2), args[3] ); + SV_GetUserinfo(args[1], (char *)VMA(2), args[3]); return 0; case G_GET_SERVERINFO: - SV_GetServerinfo( (char *)VMA(1), args[2] ); + SV_GetServerinfo((char *)VMA(1), args[2]); return 0; case G_ADJUST_AREA_PORTAL_STATE: - SV_AdjustAreaPortalState( (sharedEntity_t *)VMA(1), (qboolean)args[2] ); + SV_AdjustAreaPortalState((sharedEntity_t *)VMA(1), (qboolean)args[2]); return 0; case G_AREAS_CONNECTED: - return CM_AreasConnected( args[1], args[2] ); + return CM_AreasConnected(args[1], args[2]); case G_BOT_ALLOCATE_CLIENT: return SV_BotAllocateClient(); case G_BOT_FREE_CLIENT: - SV_BotFreeClient( args[1] ); + SV_BotFreeClient(args[1]); return 0; case G_GET_USERCMD: - SV_GetUsercmd( args[1], (struct usercmd_s *)VMA(2) ); + SV_GetUsercmd(args[1], (struct usercmd_s *)VMA(2)); return 0; case G_SIEGEPERSSET: - SV_SiegePersSet( (siegePers_t *)VMA( 1 ) ); + SV_SiegePersSet((siegePers_t *)VMA(1)); return 0; case G_SIEGEPERSGET: - SV_SiegePersGet( (siegePers_t *)VMA( 1 ) ); + SV_SiegePersGet((siegePers_t *)VMA(1)); return 0; - //rwwRMG - see below + // rwwRMG - see below /* case G_GET_ENTITY_TOKEN: { @@ -1994,14 +1669,14 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; */ case G_DEBUG_POLYGON_CREATE: - return BotImport_DebugPolygonCreate( args[1], args[2], (float (*)[3])VMA(3) ); + return BotImport_DebugPolygonCreate(args[1], args[2], (float(*)[3])VMA(3)); case G_DEBUG_POLYGON_DELETE: - BotImport_DebugPolygonDelete( args[1] ); + BotImport_DebugPolygonDelete(args[1]); return 0; case G_REAL_TIME: - return Com_RealTime( (struct qtime_s *)VMA(1) ); + return Com_RealTime((struct qtime_s *)VMA(1)); case G_SNAPVECTOR: - Sys_SnapVector( (float *)VMA(1) ); + Sys_SnapVector((float *)VMA(1)); return 0; case SP_GETSTRINGTEXTSTRING: @@ -2016,15 +1691,15 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; case G_ROFF_CACHE: - return SV_ROFF_Cache( (char *)VMA(1) ); + return SV_ROFF_Cache((char *)VMA(1)); case G_ROFF_PLAY: - return SV_ROFF_Play( args[1], args[2], (qboolean)args[3] ); + return SV_ROFF_Play(args[1], args[2], (qboolean)args[3]); case G_ROFF_PURGE_ENT: - return SV_ROFF_Purge_Ent( args[1] ); + return SV_ROFF_Purge_Ent(args[1]); - //rww - dynamic vm memory allocation! + // rww - dynamic vm memory allocation! case G_TRUEMALLOC: VM_Shifted_Alloc((void **)VMA(1), args[2]); return 0; @@ -2032,7 +1707,7 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { VM_Shifted_Free((void **)VMA(1)); return 0; - //rww - icarus traps + // rww - icarus traps case G_ICARUS_RUNSCRIPT: return ICARUS_RunScript(ConvertedEntity((sharedEntity_t *)VMA(1)), (const char *)VMA(2)); @@ -2047,13 +1722,13 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return ICARUS_ValidEnt(ConvertedEntity((sharedEntity_t *)VMA(1))); case G_ICARUS_ISINITIALIZED: - return ICARUS_IsInitialized( args[1] ); + return ICARUS_IsInitialized(args[1]); case G_ICARUS_MAINTAINTASKMANAGER: - return ICARUS_MaintainTaskManager( args[1] ); + return ICARUS_MaintainTaskManager(args[1]); case G_ICARUS_ISRUNNING: - return ICARUS_IsRunning( args[1] ); + return ICARUS_IsRunning(args[1]); case G_ICARUS_TASKIDPENDING: return Q3_TaskIDPending((sharedEntity_t *)VMA(1), (taskID_t)args[2]); @@ -2075,14 +1750,14 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; case G_ICARUS_TASKIDSET: - //rww - note that we are passing in the true entity here. - //This is because we allow modification of certain non-pointer values, - //which is valid. + // rww - note that we are passing in the true entity here. + // This is because we allow modification of certain non-pointer values, + // which is valid. Q3_TaskIDSet((sharedEntity_t *)VMA(1), (taskID_t)args[2], args[3]); return 0; case G_ICARUS_TASKIDCOMPLETE: - //same as above. + // same as above. Q3_TaskIDComplete((sharedEntity_t *)VMA(1), (taskID_t)args[2]); return 0; @@ -2096,17 +1771,15 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { case G_ICARUS_GETFLOATVARIABLE: return Q3_GetFloatVariable((const char *)VMA(1), (float *)VMA(2)); - case G_ICARUS_GETSTRINGVARIABLE: - { - const char *rec = (const char *)VMA(2); - return Q3_GetStringVariable((const char *)VMA(1), (const char **)&rec); - } + case G_ICARUS_GETSTRINGVARIABLE: { + const char *rec = (const char *)VMA(2); + return Q3_GetStringVariable((const char *)VMA(1), (const char **)&rec); + } case G_ICARUS_GETVECTORVARIABLE: return Q3_GetVectorVariable((const char *)VMA(1), (float *)VMA(2)); - - //rww - BEGIN NPC NAV TRAPS + // rww - BEGIN NPC NAV TRAPS case G_NAV_INIT: navigator.Init(); return 0; @@ -2209,10 +1882,10 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { case G_NAV_SETPATHSCALCULATED: navigator.pathsCalculated = (qboolean)args[1]; return 0; - //rww - END NPC NAV TRAPS + // rww - END NPC NAV TRAPS case G_SET_SHARED_BUFFER: - SV_RegisterSharedMemory( (char *)VMA(1) ); + SV_RegisterSharedMemory((char *)VMA(1)); return 0; //==================================== @@ -2221,292 +1894,296 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { case BOTLIB_SHUTDOWN: return SV_BotLibShutdown(); case BOTLIB_LIBVAR_SET: - return botlib_export->BotLibVarSet( (char *)VMA(1), (char *)VMA(2) ); + return botlib_export->BotLibVarSet((char *)VMA(1), (char *)VMA(2)); case BOTLIB_LIBVAR_GET: - return botlib_export->BotLibVarGet( (char *)VMA(1), (char *)VMA(2), args[3] ); + return botlib_export->BotLibVarGet((char *)VMA(1), (char *)VMA(2), args[3]); case BOTLIB_PC_ADD_GLOBAL_DEFINE: - return botlib_export->PC_AddGlobalDefine( (char *)VMA(1) ); + return botlib_export->PC_AddGlobalDefine((char *)VMA(1)); case BOTLIB_PC_LOAD_SOURCE: - return botlib_export->PC_LoadSourceHandle( (const char *)VMA(1) ); + return botlib_export->PC_LoadSourceHandle((const char *)VMA(1)); case BOTLIB_PC_FREE_SOURCE: - return botlib_export->PC_FreeSourceHandle( args[1] ); + return botlib_export->PC_FreeSourceHandle(args[1]); case BOTLIB_PC_READ_TOKEN: - return botlib_export->PC_ReadTokenHandle( args[1], (struct pc_token_s *)VMA(2) ); + return botlib_export->PC_ReadTokenHandle(args[1], (struct pc_token_s *)VMA(2)); case BOTLIB_PC_SOURCE_FILE_AND_LINE: - return botlib_export->PC_SourceFileAndLine( args[1], (char *)VMA(2), (int *)VMA(3) ); + return botlib_export->PC_SourceFileAndLine(args[1], (char *)VMA(2), (int *)VMA(3)); case BOTLIB_START_FRAME: - return botlib_export->BotLibStartFrame( VMF(1) ); + return botlib_export->BotLibStartFrame(VMF(1)); case BOTLIB_LOAD_MAP: - return botlib_export->BotLibLoadMap( (const char *)VMA(1) ); + return botlib_export->BotLibLoadMap((const char *)VMA(1)); case BOTLIB_UPDATENTITY: - return botlib_export->BotLibUpdateEntity( args[1], (struct bot_entitystate_s *)VMA(2) ); + return botlib_export->BotLibUpdateEntity(args[1], (struct bot_entitystate_s *)VMA(2)); case BOTLIB_TEST: - return botlib_export->Test( args[1], (char *)VMA(2), (float *)VMA(3), (float *)VMA(4) ); + return botlib_export->Test(args[1], (char *)VMA(2), (float *)VMA(3), (float *)VMA(4)); case BOTLIB_GET_SNAPSHOT_ENTITY: - return SV_BotGetSnapshotEntity( args[1], args[2] ); + return SV_BotGetSnapshotEntity(args[1], args[2]); case BOTLIB_GET_CONSOLE_MESSAGE: - return SV_BotGetConsoleMessage( args[1], (char *)VMA(2), args[3] ); + return SV_BotGetConsoleMessage(args[1], (char *)VMA(2), args[3]); case BOTLIB_USER_COMMAND: - SV_ClientThink( &svs.clients[args[1]], (struct usercmd_s *)VMA(2) ); + SV_ClientThink(&svs.clients[args[1]], (struct usercmd_s *)VMA(2)); return 0; case BOTLIB_AAS_BBOX_AREAS: - return botlib_export->aas.AAS_BBoxAreas( (float *)VMA(1), (float *)VMA(2), (int *)VMA(3), args[4] ); + return botlib_export->aas.AAS_BBoxAreas((float *)VMA(1), (float *)VMA(2), (int *)VMA(3), args[4]); case BOTLIB_AAS_AREA_INFO: - return botlib_export->aas.AAS_AreaInfo( args[1], (struct aas_areainfo_s *)VMA(2) ); + return botlib_export->aas.AAS_AreaInfo(args[1], (struct aas_areainfo_s *)VMA(2)); case BOTLIB_AAS_ALTERNATIVE_ROUTE_GOAL: - return botlib_export->aas.AAS_AlternativeRouteGoals( (float *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], (struct aas_altroutegoal_s *)VMA(6), args[7], args[8] ); + return botlib_export->aas.AAS_AlternativeRouteGoals((float *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], (struct aas_altroutegoal_s *)VMA(6), + args[7], args[8]); case BOTLIB_AAS_ENTITY_INFO: - botlib_export->aas.AAS_EntityInfo( args[1], (struct aas_entityinfo_s *)VMA(2) ); + botlib_export->aas.AAS_EntityInfo(args[1], (struct aas_entityinfo_s *)VMA(2)); return 0; case BOTLIB_AAS_INITIALIZED: return botlib_export->aas.AAS_Initialized(); case BOTLIB_AAS_PRESENCE_TYPE_BOUNDING_BOX: - botlib_export->aas.AAS_PresenceTypeBoundingBox( args[1], (float *)VMA(2), (float *)VMA(3) ); + botlib_export->aas.AAS_PresenceTypeBoundingBox(args[1], (float *)VMA(2), (float *)VMA(3)); return 0; case BOTLIB_AAS_TIME: - return FloatAsInt( botlib_export->aas.AAS_Time() ); + return FloatAsInt(botlib_export->aas.AAS_Time()); case BOTLIB_AAS_POINT_AREA_NUM: - return botlib_export->aas.AAS_PointAreaNum( (float *)VMA(1) ); + return botlib_export->aas.AAS_PointAreaNum((float *)VMA(1)); case BOTLIB_AAS_POINT_REACHABILITY_AREA_INDEX: - return botlib_export->aas.AAS_PointReachabilityAreaIndex( (float *)VMA(1) ); + return botlib_export->aas.AAS_PointReachabilityAreaIndex((float *)VMA(1)); case BOTLIB_AAS_TRACE_AREAS: - return botlib_export->aas.AAS_TraceAreas( (float *)VMA(1), (float *)VMA(2), (int *)VMA(3), (float (*)[3])VMA(4), args[5] ); + return botlib_export->aas.AAS_TraceAreas((float *)VMA(1), (float *)VMA(2), (int *)VMA(3), (float(*)[3])VMA(4), args[5]); case BOTLIB_AAS_POINT_CONTENTS: - return botlib_export->aas.AAS_PointContents( (float *)VMA(1) ); + return botlib_export->aas.AAS_PointContents((float *)VMA(1)); case BOTLIB_AAS_NEXT_BSP_ENTITY: - return botlib_export->aas.AAS_NextBSPEntity( args[1] ); + return botlib_export->aas.AAS_NextBSPEntity(args[1]); case BOTLIB_AAS_VALUE_FOR_BSP_EPAIR_KEY: - return botlib_export->aas.AAS_ValueForBSPEpairKey( args[1], (char *)VMA(2), (char *)VMA(3), args[4] ); + return botlib_export->aas.AAS_ValueForBSPEpairKey(args[1], (char *)VMA(2), (char *)VMA(3), args[4]); case BOTLIB_AAS_VECTOR_FOR_BSP_EPAIR_KEY: - return botlib_export->aas.AAS_VectorForBSPEpairKey( args[1], (char *)VMA(2), (float *)VMA(3) ); + return botlib_export->aas.AAS_VectorForBSPEpairKey(args[1], (char *)VMA(2), (float *)VMA(3)); case BOTLIB_AAS_FLOAT_FOR_BSP_EPAIR_KEY: - return botlib_export->aas.AAS_FloatForBSPEpairKey( args[1], (char *)VMA(2), (float *)VMA(3) ); + return botlib_export->aas.AAS_FloatForBSPEpairKey(args[1], (char *)VMA(2), (float *)VMA(3)); case BOTLIB_AAS_INT_FOR_BSP_EPAIR_KEY: - return botlib_export->aas.AAS_IntForBSPEpairKey( args[1], (char *)VMA(2), (int *)VMA(3) ); + return botlib_export->aas.AAS_IntForBSPEpairKey(args[1], (char *)VMA(2), (int *)VMA(3)); case BOTLIB_AAS_AREA_REACHABILITY: - return botlib_export->aas.AAS_AreaReachability( args[1] ); + return botlib_export->aas.AAS_AreaReachability(args[1]); case BOTLIB_AAS_AREA_TRAVEL_TIME_TO_GOAL_AREA: - return botlib_export->aas.AAS_AreaTravelTimeToGoalArea( args[1], (float *)VMA(2), args[3], args[4] ); + return botlib_export->aas.AAS_AreaTravelTimeToGoalArea(args[1], (float *)VMA(2), args[3], args[4]); case BOTLIB_AAS_ENABLE_ROUTING_AREA: - return botlib_export->aas.AAS_EnableRoutingArea( args[1], args[2] ); + return botlib_export->aas.AAS_EnableRoutingArea(args[1], args[2]); case BOTLIB_AAS_PREDICT_ROUTE: - return botlib_export->aas.AAS_PredictRoute( (struct aas_predictroute_s *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11] ); + return botlib_export->aas.AAS_PredictRoute((struct aas_predictroute_s *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], args[6], args[7], args[8], + args[9], args[10], args[11]); case BOTLIB_AAS_SWIMMING: - return botlib_export->aas.AAS_Swimming( (float *)VMA(1) ); + return botlib_export->aas.AAS_Swimming((float *)VMA(1)); case BOTLIB_AAS_PREDICT_CLIENT_MOVEMENT: - return botlib_export->aas.AAS_PredictClientMovement( (struct aas_clientmove_s *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], - (float *)VMA(6), (float *)VMA(7), args[8], args[9], VMF(10), args[11], args[12], args[13] ); + return botlib_export->aas.AAS_PredictClientMovement((struct aas_clientmove_s *)VMA(1), args[2], (float *)VMA(3), args[4], args[5], (float *)VMA(6), + (float *)VMA(7), args[8], args[9], VMF(10), args[11], args[12], args[13]); case BOTLIB_EA_SAY: - botlib_export->ea.EA_Say( args[1], (char *)VMA(2) ); + botlib_export->ea.EA_Say(args[1], (char *)VMA(2)); return 0; case BOTLIB_EA_SAY_TEAM: - botlib_export->ea.EA_SayTeam( args[1], (char *)VMA(2) ); + botlib_export->ea.EA_SayTeam(args[1], (char *)VMA(2)); return 0; case BOTLIB_EA_COMMAND: - botlib_export->ea.EA_Command( args[1], (char *)VMA(2) ); + botlib_export->ea.EA_Command(args[1], (char *)VMA(2)); return 0; case BOTLIB_EA_ACTION: - botlib_export->ea.EA_Action( args[1], args[2] ); + botlib_export->ea.EA_Action(args[1], args[2]); break; case BOTLIB_EA_GESTURE: - botlib_export->ea.EA_Gesture( args[1] ); + botlib_export->ea.EA_Gesture(args[1]); return 0; case BOTLIB_EA_TALK: - botlib_export->ea.EA_Talk( args[1] ); + botlib_export->ea.EA_Talk(args[1]); return 0; case BOTLIB_EA_ATTACK: - botlib_export->ea.EA_Attack( args[1] ); + botlib_export->ea.EA_Attack(args[1]); return 0; case BOTLIB_EA_ALT_ATTACK: - botlib_export->ea.EA_Alt_Attack( args[1] ); + botlib_export->ea.EA_Alt_Attack(args[1]); return 0; case BOTLIB_EA_FORCEPOWER: - botlib_export->ea.EA_ForcePower( args[1] ); + botlib_export->ea.EA_ForcePower(args[1]); return 0; case BOTLIB_EA_USE: - botlib_export->ea.EA_Use( args[1] ); + botlib_export->ea.EA_Use(args[1]); return 0; case BOTLIB_EA_RESPAWN: - botlib_export->ea.EA_Respawn( args[1] ); + botlib_export->ea.EA_Respawn(args[1]); return 0; case BOTLIB_EA_CROUCH: - botlib_export->ea.EA_Crouch( args[1] ); + botlib_export->ea.EA_Crouch(args[1]); return 0; case BOTLIB_EA_MOVE_UP: - botlib_export->ea.EA_MoveUp( args[1] ); + botlib_export->ea.EA_MoveUp(args[1]); return 0; case BOTLIB_EA_MOVE_DOWN: - botlib_export->ea.EA_MoveDown( args[1] ); + botlib_export->ea.EA_MoveDown(args[1]); return 0; case BOTLIB_EA_MOVE_FORWARD: - botlib_export->ea.EA_MoveForward( args[1] ); + botlib_export->ea.EA_MoveForward(args[1]); return 0; case BOTLIB_EA_MOVE_BACK: - botlib_export->ea.EA_MoveBack( args[1] ); + botlib_export->ea.EA_MoveBack(args[1]); return 0; case BOTLIB_EA_MOVE_LEFT: - botlib_export->ea.EA_MoveLeft( args[1] ); + botlib_export->ea.EA_MoveLeft(args[1]); return 0; case BOTLIB_EA_MOVE_RIGHT: - botlib_export->ea.EA_MoveRight( args[1] ); + botlib_export->ea.EA_MoveRight(args[1]); return 0; case BOTLIB_EA_SELECT_WEAPON: - botlib_export->ea.EA_SelectWeapon( args[1], args[2] ); + botlib_export->ea.EA_SelectWeapon(args[1], args[2]); return 0; case BOTLIB_EA_JUMP: - botlib_export->ea.EA_Jump( args[1] ); + botlib_export->ea.EA_Jump(args[1]); return 0; case BOTLIB_EA_DELAYED_JUMP: - botlib_export->ea.EA_DelayedJump( args[1] ); + botlib_export->ea.EA_DelayedJump(args[1]); return 0; case BOTLIB_EA_MOVE: - botlib_export->ea.EA_Move( args[1], (float *)VMA(2), VMF(3) ); + botlib_export->ea.EA_Move(args[1], (float *)VMA(2), VMF(3)); return 0; case BOTLIB_EA_VIEW: - botlib_export->ea.EA_View( args[1], (float *)VMA(2) ); + botlib_export->ea.EA_View(args[1], (float *)VMA(2)); return 0; case BOTLIB_EA_END_REGULAR: - botlib_export->ea.EA_EndRegular( args[1], VMF(2) ); + botlib_export->ea.EA_EndRegular(args[1], VMF(2)); return 0; case BOTLIB_EA_GET_INPUT: - botlib_export->ea.EA_GetInput( args[1], VMF(2), (struct bot_input_s *)VMA(3) ); + botlib_export->ea.EA_GetInput(args[1], VMF(2), (struct bot_input_s *)VMA(3)); return 0; case BOTLIB_EA_RESET_INPUT: - botlib_export->ea.EA_ResetInput( args[1] ); + botlib_export->ea.EA_ResetInput(args[1]); return 0; case BOTLIB_AI_LOAD_CHARACTER: - return botlib_export->ai.BotLoadCharacter( (char *)VMA(1), VMF(2) ); + return botlib_export->ai.BotLoadCharacter((char *)VMA(1), VMF(2)); case BOTLIB_AI_FREE_CHARACTER: - botlib_export->ai.BotFreeCharacter( args[1] ); + botlib_export->ai.BotFreeCharacter(args[1]); return 0; case BOTLIB_AI_CHARACTERISTIC_FLOAT: - return FloatAsInt( botlib_export->ai.Characteristic_Float( args[1], args[2] ) ); + return FloatAsInt(botlib_export->ai.Characteristic_Float(args[1], args[2])); case BOTLIB_AI_CHARACTERISTIC_BFLOAT: - return FloatAsInt( botlib_export->ai.Characteristic_BFloat( args[1], args[2], VMF(3), VMF(4) ) ); + return FloatAsInt(botlib_export->ai.Characteristic_BFloat(args[1], args[2], VMF(3), VMF(4))); case BOTLIB_AI_CHARACTERISTIC_INTEGER: - return botlib_export->ai.Characteristic_Integer( args[1], args[2] ); + return botlib_export->ai.Characteristic_Integer(args[1], args[2]); case BOTLIB_AI_CHARACTERISTIC_BINTEGER: - return botlib_export->ai.Characteristic_BInteger( args[1], args[2], args[3], args[4] ); + return botlib_export->ai.Characteristic_BInteger(args[1], args[2], args[3], args[4]); case BOTLIB_AI_CHARACTERISTIC_STRING: - botlib_export->ai.Characteristic_String( args[1], args[2], (char *)VMA(3), args[4] ); + botlib_export->ai.Characteristic_String(args[1], args[2], (char *)VMA(3), args[4]); return 0; case BOTLIB_AI_ALLOC_CHAT_STATE: return botlib_export->ai.BotAllocChatState(); case BOTLIB_AI_FREE_CHAT_STATE: - botlib_export->ai.BotFreeChatState( args[1] ); + botlib_export->ai.BotFreeChatState(args[1]); return 0; case BOTLIB_AI_QUEUE_CONSOLE_MESSAGE: - botlib_export->ai.BotQueueConsoleMessage( args[1], args[2], (char *)VMA(3) ); + botlib_export->ai.BotQueueConsoleMessage(args[1], args[2], (char *)VMA(3)); return 0; case BOTLIB_AI_REMOVE_CONSOLE_MESSAGE: - botlib_export->ai.BotRemoveConsoleMessage( args[1], args[2] ); + botlib_export->ai.BotRemoveConsoleMessage(args[1], args[2]); return 0; case BOTLIB_AI_NEXT_CONSOLE_MESSAGE: - return botlib_export->ai.BotNextConsoleMessage( args[1], (struct bot_consolemessage_s *)VMA(2) ); + return botlib_export->ai.BotNextConsoleMessage(args[1], (struct bot_consolemessage_s *)VMA(2)); case BOTLIB_AI_NUM_CONSOLE_MESSAGE: - return botlib_export->ai.BotNumConsoleMessages( args[1] ); + return botlib_export->ai.BotNumConsoleMessages(args[1]); case BOTLIB_AI_INITIAL_CHAT: - botlib_export->ai.BotInitialChat( args[1], (char *)VMA(2), args[3], (char *)VMA(4), (char *)VMA(5), (char *)VMA(6), (char *)VMA(7), (char *)VMA(8), (char *)VMA(9), (char *)VMA(10), (char *)VMA(11) ); + botlib_export->ai.BotInitialChat(args[1], (char *)VMA(2), args[3], (char *)VMA(4), (char *)VMA(5), (char *)VMA(6), (char *)VMA(7), (char *)VMA(8), + (char *)VMA(9), (char *)VMA(10), (char *)VMA(11)); return 0; case BOTLIB_AI_NUM_INITIAL_CHATS: - return botlib_export->ai.BotNumInitialChats( args[1], (char *)VMA(2) ); + return botlib_export->ai.BotNumInitialChats(args[1], (char *)VMA(2)); case BOTLIB_AI_REPLY_CHAT: - return botlib_export->ai.BotReplyChat( args[1], (char *)VMA(2), args[3], args[4], (char *)VMA(5), (char *)VMA(6), (char *)VMA(7), (char *)VMA(8), (char *)VMA(9), (char *)VMA(10), (char *)VMA(11), (char *)VMA(12) ); + return botlib_export->ai.BotReplyChat(args[1], (char *)VMA(2), args[3], args[4], (char *)VMA(5), (char *)VMA(6), (char *)VMA(7), (char *)VMA(8), + (char *)VMA(9), (char *)VMA(10), (char *)VMA(11), (char *)VMA(12)); case BOTLIB_AI_CHAT_LENGTH: - return botlib_export->ai.BotChatLength( args[1] ); + return botlib_export->ai.BotChatLength(args[1]); case BOTLIB_AI_ENTER_CHAT: - botlib_export->ai.BotEnterChat( args[1], args[2], args[3] ); + botlib_export->ai.BotEnterChat(args[1], args[2], args[3]); return 0; case BOTLIB_AI_GET_CHAT_MESSAGE: - botlib_export->ai.BotGetChatMessage( args[1], (char *)VMA(2), args[3] ); + botlib_export->ai.BotGetChatMessage(args[1], (char *)VMA(2), args[3]); return 0; case BOTLIB_AI_STRING_CONTAINS: - return botlib_export->ai.StringContains( (char *)VMA(1), (char *)VMA(2), args[3] ); + return botlib_export->ai.StringContains((char *)VMA(1), (char *)VMA(2), args[3]); case BOTLIB_AI_FIND_MATCH: - return botlib_export->ai.BotFindMatch( (char *)VMA(1), (struct bot_match_s *)VMA(2), args[3] ); + return botlib_export->ai.BotFindMatch((char *)VMA(1), (struct bot_match_s *)VMA(2), args[3]); case BOTLIB_AI_MATCH_VARIABLE: - botlib_export->ai.BotMatchVariable( (struct bot_match_s *)VMA(1), args[2], (char *)VMA(3), args[4] ); + botlib_export->ai.BotMatchVariable((struct bot_match_s *)VMA(1), args[2], (char *)VMA(3), args[4]); return 0; case BOTLIB_AI_UNIFY_WHITE_SPACES: - botlib_export->ai.UnifyWhiteSpaces( (char *)VMA(1) ); + botlib_export->ai.UnifyWhiteSpaces((char *)VMA(1)); return 0; case BOTLIB_AI_REPLACE_SYNONYMS: - botlib_export->ai.BotReplaceSynonyms( (char *)VMA(1), args[2] ); + botlib_export->ai.BotReplaceSynonyms((char *)VMA(1), args[2]); return 0; case BOTLIB_AI_LOAD_CHAT_FILE: - return botlib_export->ai.BotLoadChatFile( args[1], (char *)VMA(2), (char *)VMA(3) ); + return botlib_export->ai.BotLoadChatFile(args[1], (char *)VMA(2), (char *)VMA(3)); case BOTLIB_AI_SET_CHAT_GENDER: - botlib_export->ai.BotSetChatGender( args[1], args[2] ); + botlib_export->ai.BotSetChatGender(args[1], args[2]); return 0; case BOTLIB_AI_SET_CHAT_NAME: - botlib_export->ai.BotSetChatName( args[1], (char *)VMA(2), args[3] ); + botlib_export->ai.BotSetChatName(args[1], (char *)VMA(2), args[3]); return 0; case BOTLIB_AI_RESET_GOAL_STATE: - botlib_export->ai.BotResetGoalState( args[1] ); + botlib_export->ai.BotResetGoalState(args[1]); return 0; case BOTLIB_AI_RESET_AVOID_GOALS: - botlib_export->ai.BotResetAvoidGoals( args[1] ); + botlib_export->ai.BotResetAvoidGoals(args[1]); return 0; case BOTLIB_AI_REMOVE_FROM_AVOID_GOALS: - botlib_export->ai.BotRemoveFromAvoidGoals( args[1], args[2] ); + botlib_export->ai.BotRemoveFromAvoidGoals(args[1], args[2]); return 0; case BOTLIB_AI_PUSH_GOAL: - botlib_export->ai.BotPushGoal( args[1], (struct bot_goal_s *)VMA(2) ); + botlib_export->ai.BotPushGoal(args[1], (struct bot_goal_s *)VMA(2)); return 0; case BOTLIB_AI_POP_GOAL: - botlib_export->ai.BotPopGoal( args[1] ); + botlib_export->ai.BotPopGoal(args[1]); return 0; case BOTLIB_AI_EMPTY_GOAL_STACK: - botlib_export->ai.BotEmptyGoalStack( args[1] ); + botlib_export->ai.BotEmptyGoalStack(args[1]); return 0; case BOTLIB_AI_DUMP_AVOID_GOALS: - botlib_export->ai.BotDumpAvoidGoals( args[1] ); + botlib_export->ai.BotDumpAvoidGoals(args[1]); return 0; case BOTLIB_AI_DUMP_GOAL_STACK: - botlib_export->ai.BotDumpGoalStack( args[1] ); + botlib_export->ai.BotDumpGoalStack(args[1]); return 0; case BOTLIB_AI_GOAL_NAME: - botlib_export->ai.BotGoalName( args[1], (char *)VMA(2), args[3] ); + botlib_export->ai.BotGoalName(args[1], (char *)VMA(2), args[3]); return 0; case BOTLIB_AI_GET_TOP_GOAL: - return botlib_export->ai.BotGetTopGoal( args[1], (struct bot_goal_s *)VMA(2) ); + return botlib_export->ai.BotGetTopGoal(args[1], (struct bot_goal_s *)VMA(2)); case BOTLIB_AI_GET_SECOND_GOAL: - return botlib_export->ai.BotGetSecondGoal( args[1], (struct bot_goal_s *)VMA(2) ); + return botlib_export->ai.BotGetSecondGoal(args[1], (struct bot_goal_s *)VMA(2)); case BOTLIB_AI_CHOOSE_LTG_ITEM: - return botlib_export->ai.BotChooseLTGItem( args[1], (float *)VMA(2), (int *)VMA(3), args[4] ); + return botlib_export->ai.BotChooseLTGItem(args[1], (float *)VMA(2), (int *)VMA(3), args[4]); case BOTLIB_AI_CHOOSE_NBG_ITEM: - return botlib_export->ai.BotChooseNBGItem( args[1], (float *)VMA(2), (int *)VMA(3), args[4], (struct bot_goal_s *)VMA(5), VMF(6) ); + return botlib_export->ai.BotChooseNBGItem(args[1], (float *)VMA(2), (int *)VMA(3), args[4], (struct bot_goal_s *)VMA(5), VMF(6)); case BOTLIB_AI_TOUCHING_GOAL: - return botlib_export->ai.BotTouchingGoal( (float *)VMA(1), (struct bot_goal_s *)VMA(2) ); + return botlib_export->ai.BotTouchingGoal((float *)VMA(1), (struct bot_goal_s *)VMA(2)); case BOTLIB_AI_ITEM_GOAL_IN_VIS_BUT_NOT_VISIBLE: - return botlib_export->ai.BotItemGoalInVisButNotVisible( args[1], (float *)VMA(2), (float *)VMA(3), (struct bot_goal_s *)VMA(4) ); + return botlib_export->ai.BotItemGoalInVisButNotVisible(args[1], (float *)VMA(2), (float *)VMA(3), (struct bot_goal_s *)VMA(4)); case BOTLIB_AI_GET_LEVEL_ITEM_GOAL: - return botlib_export->ai.BotGetLevelItemGoal( args[1], (char *)VMA(2), (struct bot_goal_s *)VMA(3) ); + return botlib_export->ai.BotGetLevelItemGoal(args[1], (char *)VMA(2), (struct bot_goal_s *)VMA(3)); case BOTLIB_AI_GET_NEXT_CAMP_SPOT_GOAL: - return botlib_export->ai.BotGetNextCampSpotGoal( args[1], (struct bot_goal_s *)VMA(2) ); + return botlib_export->ai.BotGetNextCampSpotGoal(args[1], (struct bot_goal_s *)VMA(2)); case BOTLIB_AI_GET_MAP_LOCATION_GOAL: - return botlib_export->ai.BotGetMapLocationGoal( (char *)VMA(1), (struct bot_goal_s *)VMA(2) ); + return botlib_export->ai.BotGetMapLocationGoal((char *)VMA(1), (struct bot_goal_s *)VMA(2)); case BOTLIB_AI_AVOID_GOAL_TIME: - return FloatAsInt( botlib_export->ai.BotAvoidGoalTime( args[1], args[2] ) ); + return FloatAsInt(botlib_export->ai.BotAvoidGoalTime(args[1], args[2])); case BOTLIB_AI_SET_AVOID_GOAL_TIME: - botlib_export->ai.BotSetAvoidGoalTime( args[1], args[2], VMF(3)); + botlib_export->ai.BotSetAvoidGoalTime(args[1], args[2], VMF(3)); return 0; case BOTLIB_AI_INIT_LEVEL_ITEMS: botlib_export->ai.BotInitLevelItems(); @@ -2515,71 +2192,71 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { botlib_export->ai.BotUpdateEntityItems(); return 0; case BOTLIB_AI_LOAD_ITEM_WEIGHTS: - return botlib_export->ai.BotLoadItemWeights( args[1], (char *)VMA(2) ); + return botlib_export->ai.BotLoadItemWeights(args[1], (char *)VMA(2)); case BOTLIB_AI_FREE_ITEM_WEIGHTS: - botlib_export->ai.BotFreeItemWeights( args[1] ); + botlib_export->ai.BotFreeItemWeights(args[1]); return 0; case BOTLIB_AI_INTERBREED_GOAL_FUZZY_LOGIC: - botlib_export->ai.BotInterbreedGoalFuzzyLogic( args[1], args[2], args[3] ); + botlib_export->ai.BotInterbreedGoalFuzzyLogic(args[1], args[2], args[3]); return 0; case BOTLIB_AI_SAVE_GOAL_FUZZY_LOGIC: - botlib_export->ai.BotSaveGoalFuzzyLogic( args[1], (char *)VMA(2) ); + botlib_export->ai.BotSaveGoalFuzzyLogic(args[1], (char *)VMA(2)); return 0; case BOTLIB_AI_MUTATE_GOAL_FUZZY_LOGIC: - botlib_export->ai.BotMutateGoalFuzzyLogic( args[1], VMF(2) ); + botlib_export->ai.BotMutateGoalFuzzyLogic(args[1], VMF(2)); return 0; case BOTLIB_AI_ALLOC_GOAL_STATE: - return botlib_export->ai.BotAllocGoalState( args[1] ); + return botlib_export->ai.BotAllocGoalState(args[1]); case BOTLIB_AI_FREE_GOAL_STATE: - botlib_export->ai.BotFreeGoalState( args[1] ); + botlib_export->ai.BotFreeGoalState(args[1]); return 0; case BOTLIB_AI_RESET_MOVE_STATE: - botlib_export->ai.BotResetMoveState( args[1] ); + botlib_export->ai.BotResetMoveState(args[1]); return 0; case BOTLIB_AI_ADD_AVOID_SPOT: - botlib_export->ai.BotAddAvoidSpot( args[1], (float *)VMA(2), VMF(3), args[4] ); + botlib_export->ai.BotAddAvoidSpot(args[1], (float *)VMA(2), VMF(3), args[4]); return 0; case BOTLIB_AI_MOVE_TO_GOAL: - botlib_export->ai.BotMoveToGoal( (struct bot_moveresult_s *)VMA(1), args[2], (struct bot_goal_s *)VMA(3), args[4] ); + botlib_export->ai.BotMoveToGoal((struct bot_moveresult_s *)VMA(1), args[2], (struct bot_goal_s *)VMA(3), args[4]); return 0; case BOTLIB_AI_MOVE_IN_DIRECTION: - return botlib_export->ai.BotMoveInDirection( args[1], (float *)VMA(2), VMF(3), args[4] ); + return botlib_export->ai.BotMoveInDirection(args[1], (float *)VMA(2), VMF(3), args[4]); case BOTLIB_AI_RESET_AVOID_REACH: - botlib_export->ai.BotResetAvoidReach( args[1] ); + botlib_export->ai.BotResetAvoidReach(args[1]); return 0; case BOTLIB_AI_RESET_LAST_AVOID_REACH: - botlib_export->ai.BotResetLastAvoidReach( args[1] ); + botlib_export->ai.BotResetLastAvoidReach(args[1]); return 0; case BOTLIB_AI_REACHABILITY_AREA: - return botlib_export->ai.BotReachabilityArea( (float *)VMA(1), args[2] ); + return botlib_export->ai.BotReachabilityArea((float *)VMA(1), args[2]); case BOTLIB_AI_MOVEMENT_VIEW_TARGET: - return botlib_export->ai.BotMovementViewTarget( args[1], (struct bot_goal_s *)VMA(2), args[3], VMF(4), (float *)VMA(5) ); + return botlib_export->ai.BotMovementViewTarget(args[1], (struct bot_goal_s *)VMA(2), args[3], VMF(4), (float *)VMA(5)); case BOTLIB_AI_PREDICT_VISIBLE_POSITION: - return botlib_export->ai.BotPredictVisiblePosition( (float *)VMA(1), args[2], (struct bot_goal_s *)VMA(3), args[4], (float *)VMA(5) ); + return botlib_export->ai.BotPredictVisiblePosition((float *)VMA(1), args[2], (struct bot_goal_s *)VMA(3), args[4], (float *)VMA(5)); case BOTLIB_AI_ALLOC_MOVE_STATE: return botlib_export->ai.BotAllocMoveState(); case BOTLIB_AI_FREE_MOVE_STATE: - botlib_export->ai.BotFreeMoveState( args[1] ); + botlib_export->ai.BotFreeMoveState(args[1]); return 0; case BOTLIB_AI_INIT_MOVE_STATE: - botlib_export->ai.BotInitMoveState( args[1], (struct bot_initmove_s *)VMA(2) ); + botlib_export->ai.BotInitMoveState(args[1], (struct bot_initmove_s *)VMA(2)); return 0; case BOTLIB_AI_CHOOSE_BEST_FIGHT_WEAPON: - return botlib_export->ai.BotChooseBestFightWeapon( args[1], (int *)VMA(2) ); + return botlib_export->ai.BotChooseBestFightWeapon(args[1], (int *)VMA(2)); case BOTLIB_AI_GET_WEAPON_INFO: - botlib_export->ai.BotGetWeaponInfo( args[1], args[2], (struct weaponinfo_s *)VMA(3) ); + botlib_export->ai.BotGetWeaponInfo(args[1], args[2], (struct weaponinfo_s *)VMA(3)); return 0; case BOTLIB_AI_LOAD_WEAPON_WEIGHTS: - return botlib_export->ai.BotLoadWeaponWeights( args[1], (char *)VMA(2) ); + return botlib_export->ai.BotLoadWeaponWeights(args[1], (char *)VMA(2)); case BOTLIB_AI_ALLOC_WEAPON_STATE: return botlib_export->ai.BotAllocWeaponState(); case BOTLIB_AI_FREE_WEAPON_STATE: - botlib_export->ai.BotFreeWeaponState( args[1] ); + botlib_export->ai.BotFreeWeaponState(args[1]); return 0; case BOTLIB_AI_RESET_WEAPON_STATE: - botlib_export->ai.BotResetWeaponState( args[1] ); + botlib_export->ai.BotResetWeaponState(args[1]); return 0; case BOTLIB_AI_GENETIC_PARENTS_AND_CHILD_SELECTION: @@ -2589,41 +2266,43 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return re->RegisterServerSkin((const char *)VMA(1)); case G_G2_LISTBONES: - SV_G2API_ListModelBones( VMA(1), args[2] ); + SV_G2API_ListModelBones(VMA(1), args[2]); return 0; case G_G2_LISTSURFACES: - SV_G2API_ListModelSurfaces( VMA(1) ); + SV_G2API_ListModelSurfaces(VMA(1)); return 0; case G_G2_HAVEWEGHOULMODELS: - return SV_G2API_HaveWeGhoul2Models( VMA(1) ); + return SV_G2API_HaveWeGhoul2Models(VMA(1)); case G_G2_SETMODELS: - SV_G2API_SetGhoul2ModelIndexes( VMA(1),(qhandle_t *)VMA(2),(qhandle_t *)VMA(3)); + SV_G2API_SetGhoul2ModelIndexes(VMA(1), (qhandle_t *)VMA(2), (qhandle_t *)VMA(3)); return 0; case G_G2_GETBOLT: - return SV_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return SV_G2API_GetBoltMatrix(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case G_G2_GETBOLT_NOREC: - return SV_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return SV_G2API_GetBoltMatrix_NoReconstruct(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case G_G2_GETBOLT_NOREC_NOROT: - return SV_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5),(const float *)VMA(6), args[7], (qhandle_t *)VMA(8), (float *)VMA(9)); + return SV_G2API_GetBoltMatrix_NoRecNoRot(VMA(1), args[2], args[3], (mdxaBone_t *)VMA(4), (const float *)VMA(5), (const float *)VMA(6), args[7], + (qhandle_t *)VMA(8), (float *)VMA(9)); case G_G2_INITGHOUL2MODEL: #ifdef _FULL_G2_LEAK_CHECKING g_G2AllocServer = 1; #endif - return SV_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t) args[4], - (qhandle_t) args[5], args[6], args[7]); + return SV_G2API_InitGhoul2Model((void **)VMA(1), (const char *)VMA(2), args[3], (qhandle_t)args[4], (qhandle_t)args[5], args[6], args[7]); case G_G2_SETSKIN: return SV_G2API_SetSkin(VMA(1), args[2], args[3], args[4]); case G_G2_SIZE: - return SV_G2API_Ghoul2Size ( VMA(1) ); + return SV_G2API_Ghoul2Size(VMA(1)); case G_G2_ADDBOLT: return SV_G2API_AddBolt(VMA(1), args[2], (const char *)VMA(3)); @@ -2633,20 +2312,18 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; case G_G2_ANGLEOVERRIDE: - return SV_G2API_SetBoneAngles(VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], - (const Eorientations) args[6], (const Eorientations) args[7], (const Eorientations) args[8], - (qhandle_t *)VMA(9), args[10], args[11] ); + return SV_G2API_SetBoneAngles(VMA(1), args[2], (const char *)VMA(3), (float *)VMA(4), args[5], (const Eorientations)args[6], + (const Eorientations)args[7], (const Eorientations)args[8], (qhandle_t *)VMA(9), args[10], args[11]); case G_G2_PLAYANIM: - return SV_G2API_SetBoneAnim(VMA(1), args[2], (const char *)VMA(3), args[4], args[5], - args[6], VMF(7), args[8], VMF(9), args[10]); + return SV_G2API_SetBoneAnim(VMA(1), args[2], (const char *)VMA(3), args[4], args[5], args[6], VMF(7), args[8], VMF(9), args[10]); case G_G2_GETBONEANIM: - return SV_G2API_GetBoneAnim(VMA(1), (const char*)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), - (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), (int *)VMA(9), args[10]); + return SV_G2API_GetBoneAnim(VMA(1), (const char *)VMA(2), args[3], (float *)VMA(4), (int *)VMA(5), (int *)VMA(6), (int *)VMA(7), (float *)VMA(8), + (int *)VMA(9), args[10]); case G_G2_GETGLANAME: - SV_G2API_GetGLAName( VMA(1), args[2], (char *)VMA(3) ); + SV_G2API_GetGLAName(VMA(1), args[2], (char *)VMA(3)); return 0; case G_G2_COPYGHOUL2INSTANCE: @@ -2670,14 +2347,14 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { #ifdef _FULL_G2_LEAK_CHECKING g_G2AllocServer = 1; #endif - //return (int)G2API_RemoveGhoul2Model((CGhoul2Info_v **)args[1], args[2]); + // return (int)G2API_RemoveGhoul2Model((CGhoul2Info_v **)args[1], args[2]); return (int)SV_G2API_RemoveGhoul2Model((void **)VMA(1), args[2]); case G_G2_REMOVEGHOUL2MODELS: #ifdef _FULL_G2_LEAK_CHECKING g_G2AllocServer = 1; #endif - //return (int)G2API_RemoveGhoul2Models((CGhoul2Info_v **)args[1]); + // return (int)G2API_RemoveGhoul2Models((CGhoul2Info_v **)args[1]); return (int)SV_G2API_RemoveGhoul2Models((void **)VMA(1)); case G_G2_CLEANMODELS: @@ -2685,25 +2362,27 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { g_G2AllocServer = 1; #endif SV_G2API_CleanGhoul2Models((void **)VMA(1)); - // re->G2API_CleanGhoul2Models((CGhoul2Info_v **)args[1]); + // re->G2API_CleanGhoul2Models((CGhoul2Info_v **)args[1]); return 0; case G_G2_COLLISIONDETECT: - SV_G2API_CollisionDetect ( (CollisionRecord_t*)VMA(1), VMA(2), (const float*)VMA(3), (const float*)VMA(4), args[5], args[6], (float*)VMA(7), (float*)VMA(8), (float*)VMA(9), args[10], args[11], VMF(12) ); + SV_G2API_CollisionDetect((CollisionRecord_t *)VMA(1), VMA(2), (const float *)VMA(3), (const float *)VMA(4), args[5], args[6], (float *)VMA(7), + (float *)VMA(8), (float *)VMA(9), args[10], args[11], VMF(12)); return 0; case G_G2_COLLISIONDETECTCACHE: - SV_G2API_CollisionDetectCache ( (CollisionRecord_t*)VMA(1), VMA(2), (const float*)VMA(3), (const float*)VMA(4), args[5], args[6], (float*)VMA(7), (float*)VMA(8), (float*)VMA(9), args[10], args[11], VMF(12) ); + SV_G2API_CollisionDetectCache((CollisionRecord_t *)VMA(1), VMA(2), (const float *)VMA(3), (const float *)VMA(4), args[5], args[6], (float *)VMA(7), + (float *)VMA(8), (float *)VMA(9), args[10], args[11], VMF(12)); return 0; case G_G2_SETROOTSURFACE: return SV_G2API_SetRootSurface(VMA(1), args[2], (const char *)VMA(3)); case G_G2_SETSURFACEONOFF: - return SV_G2API_SetSurfaceOnOff(VMA(1), (const char *)VMA(2), /*(const int)VMA(3)*/args[3]); + return SV_G2API_SetSurfaceOnOff(VMA(1), (const char *)VMA(2), /*(const int)VMA(3)*/ args[3]); case G_G2_SETNEWORIGIN: - return SV_G2API_SetNewOrigin(VMA(1), /*(const int)VMA(2)*/args[2]); + return SV_G2API_SetNewOrigin(VMA(1), /*(const int)VMA(2)*/ args[2]); case G_G2_DOESBONEEXIST: return SV_G2API_DoesBoneExist(VMA(1), args[2], (const char *)VMA(3)); @@ -2716,14 +2395,14 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return 0; case G_G2_SETRAGDOLL: - SV_G2API_SetRagDoll( VMA(1), (sharedRagDollParams_t *)VMA(2) ); + SV_G2API_SetRagDoll(VMA(1), (sharedRagDollParams_t *)VMA(2)); return 0; case G_G2_ANIMATEG2MODELS: - SV_G2API_AnimateG2Models( VMA(1), args[2], (sharedRagDollUpdateParams_t *)VMA(3) ); + SV_G2API_AnimateG2Models(VMA(1), args[2], (sharedRagDollUpdateParams_t *)VMA(3)); return 0; - //additional ragdoll options -rww + // additional ragdoll options -rww case G_G2_RAGPCJCONSTRAINT: return SV_G2API_RagPCJConstraint(VMA(1), (const char *)VMA(2), (float *)VMA(3), (float *)VMA(4)); case G_G2_RAGPCJGRADIENTSPEED: @@ -2782,349 +2461,349 @@ intptr_t SV_GameSystemCalls( intptr_t *args ) { return SV_GetEntityToken((char *)VMA(1), args[2]); default: - Com_Error( ERR_DROP, "Bad game system trap: %ld", (long int) args[0] ); + Com_Error(ERR_DROP, "Bad game system trap: %ld", (long int)args[0]); } return -1; } -void SV_InitGame( qboolean restart ) { - int i=0; +void SV_InitGame(qboolean restart) { + int i = 0; client_t *cl = NULL; // clear level pointers sv.entityParsePoint = CM_EntityString(); - for ( i=0, cl=svs.clients; iinteger; i++, cl++ ) + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) cl->gentity = NULL; - GVM_InitGame( sv.time, Com_Milliseconds(), restart ); + GVM_InitGame(sv.time, Com_Milliseconds(), restart); } -void SV_BindGame( void ) { +void SV_BindGame(void) { static gameImport_t gi; - gameExport_t *ret; - GetGameAPI_t GetGameAPI; - char dllName[MAX_OSPATH] = "jampgame" ARCH_STRING DLL_EXT; - - memset( &gi, 0, sizeof( gi ) ); - - gvm = VM_Create( VM_GAME ); - if ( gvm && !gvm->isLegacy ) { - gi.Print = Com_Printf; - gi.Error = Com_Error; - gi.Milliseconds = Com_Milliseconds; - gi.PrecisionTimerStart = SV_PrecisionTimerStart; - gi.PrecisionTimerEnd = SV_PrecisionTimerEnd; - gi.SV_RegisterSharedMemory = SV_RegisterSharedMemory; - gi.RealTime = Com_RealTime; - gi.TrueMalloc = VM_Shifted_Alloc; - gi.TrueFree = VM_Shifted_Free; - gi.SnapVector = Sys_SnapVector; - gi.Cvar_Register = Cvar_Register; - gi.Cvar_Set = GVM_Cvar_Set; - gi.Cvar_Update = Cvar_Update; - gi.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; - gi.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; - gi.Argc = Cmd_Argc; - gi.Argv = Cmd_ArgvBuffer; - gi.FS_Close = FS_FCloseFile; - gi.FS_GetFileList = FS_GetFileList; - gi.FS_Open = FS_FOpenFileByMode; - gi.FS_Read = FS_Read; - gi.FS_Write = FS_Write; - gi.AdjustAreaPortalState = SV_AdjustAreaPortalState; - gi.AreasConnected = CM_AreasConnected; - gi.DebugPolygonCreate = BotImport_DebugPolygonCreate; - gi.DebugPolygonDelete = BotImport_DebugPolygonDelete; - gi.DropClient = SV_GameDropClient; - gi.EntitiesInBox = SV_AreaEntities; - gi.EntityContact = SV_EntityContact; - gi.Trace = SV_Trace; - gi.GetConfigstring = SV_GetConfigstring; - gi.GetEntityToken = SV_GetEntityToken; - gi.GetServerinfo = SV_GetServerinfo; - gi.GetUsercmd = SV_GetUsercmd; - gi.GetUserinfo = SV_GetUserinfo; - gi.InPVS = SV_inPVS; - gi.InPVSIgnorePortals = SV_inPVSIgnorePortals; - gi.LinkEntity = SV_LinkEntity; - gi.LocateGameData = SV_LocateGameData; - gi.PointContents = SV_PointContents; - gi.SendConsoleCommand = Cbuf_ExecuteText; - gi.SendServerCommand = SV_GameSendServerCommand; - gi.SetBrushModel = SV_SetBrushModel; - gi.SetConfigstring = SV_SetConfigstring; - gi.SetServerCull = SV_SetServerCull; - gi.SetUserinfo = SV_SetUserinfo; - gi.SiegePersSet = SV_SiegePersSet; - gi.SiegePersGet = SV_SiegePersGet; - gi.UnlinkEntity = SV_UnlinkEntity; - gi.ROFF_Clean = SV_ROFF_Clean; - gi.ROFF_UpdateEntities = SV_ROFF_UpdateEntities; - gi.ROFF_Cache = SV_ROFF_Cache; - gi.ROFF_Play = SV_ROFF_Play; - gi.ROFF_Purge_Ent = SV_ROFF_Purge_Ent; - gi.ICARUS_RunScript = ICARUS_RunScript; - gi.ICARUS_RegisterScript = SV_ICARUS_RegisterScript; - gi.ICARUS_Init = ICARUS_Init; - gi.ICARUS_ValidEnt = SV_ICARUS_ValidEnt; - gi.ICARUS_IsInitialized = ICARUS_IsInitialized; - gi.ICARUS_MaintainTaskManager = ICARUS_MaintainTaskManager; - gi.ICARUS_IsRunning = ICARUS_IsRunning; - gi.ICARUS_TaskIDPending = ICARUS_TaskIDPending; - gi.ICARUS_InitEnt = ICARUS_InitEnt; - gi.ICARUS_FreeEnt = ICARUS_FreeEnt; - gi.ICARUS_AssociateEnt = ICARUS_AssociateEnt; - gi.ICARUS_Shutdown = ICARUS_Shutdown; - gi.ICARUS_TaskIDSet = SV_ICARUS_TaskIDSet; - gi.ICARUS_TaskIDComplete = SV_ICARUS_TaskIDComplete; - gi.ICARUS_SetVar = Q3_SetVar; - gi.ICARUS_VariableDeclared = Q3_VariableDeclared; - gi.ICARUS_GetFloatVariable = Q3_GetFloatVariable; - gi.ICARUS_GetStringVariable = SV_ICARUS_GetStringVariable; - gi.ICARUS_GetVectorVariable = SV_ICARUS_GetVectorVariable; - gi.Nav_Init = SV_Nav_Init; - gi.Nav_Free = SV_Nav_Free; - gi.Nav_Load = SV_Nav_Load; - gi.Nav_Save = SV_Nav_Save; - gi.Nav_AddRawPoint = SV_Nav_AddRawPoint; - gi.Nav_CalculatePaths = SV_Nav_CalculatePaths; - gi.Nav_HardConnect = SV_Nav_HardConnect; - gi.Nav_ShowNodes = SV_Nav_ShowNodes; - gi.Nav_ShowEdges = SV_Nav_ShowEdges; - gi.Nav_ShowPath = SV_Nav_ShowPath; - gi.Nav_GetNearestNode = SV_Nav_GetNearestNode; - gi.Nav_GetBestNode = SV_Nav_GetBestNode; - gi.Nav_GetNodePosition = SV_Nav_GetNodePosition; - gi.Nav_GetNodeNumEdges = SV_Nav_GetNodeNumEdges; - gi.Nav_GetNodeEdge = SV_Nav_GetNodeEdge; - gi.Nav_GetNumNodes = SV_Nav_GetNumNodes; - gi.Nav_Connected = SV_Nav_Connected; - gi.Nav_GetPathCost = SV_Nav_GetPathCost; - gi.Nav_GetEdgeCost = SV_Nav_GetEdgeCost; - gi.Nav_GetProjectedNode = SV_Nav_GetProjectedNode; - gi.Nav_CheckFailedNodes = SV_Nav_CheckFailedNodes; - gi.Nav_AddFailedNode = SV_Nav_AddFailedNode; - gi.Nav_NodeFailed = SV_Nav_NodeFailed; - gi.Nav_NodesAreNeighbors = SV_Nav_NodesAreNeighbors; - gi.Nav_ClearFailedEdge = SV_Nav_ClearFailedEdge; - gi.Nav_ClearAllFailedEdges = SV_Nav_ClearAllFailedEdges; - gi.Nav_EdgeFailed = SV_Nav_EdgeFailed; - gi.Nav_AddFailedEdge = SV_Nav_AddFailedEdge; - gi.Nav_CheckFailedEdge = SV_Nav_CheckFailedEdge; - gi.Nav_CheckAllFailedEdges = SV_Nav_CheckAllFailedEdges; - gi.Nav_RouteBlocked = SV_Nav_RouteBlocked; - gi.Nav_GetBestNodeAltRoute = SV_Nav_GetBestNodeAltRoute; - gi.Nav_GetBestNodeAltRoute2 = SV_Nav_GetBestNodeAltRoute2; - gi.Nav_GetBestPathBetweenEnts = SV_Nav_GetBestPathBetweenEnts; - gi.Nav_GetNodeRadius = SV_Nav_GetNodeRadius; - gi.Nav_CheckBlockedEdges = SV_Nav_CheckBlockedEdges; - gi.Nav_ClearCheckedNodes = SV_Nav_ClearCheckedNodes; - gi.Nav_CheckedNode = SV_Nav_CheckedNode; - gi.Nav_SetCheckedNode = SV_Nav_SetCheckedNode; - gi.Nav_FlagAllNodes = SV_Nav_FlagAllNodes; - gi.Nav_GetPathsCalculated = SV_Nav_GetPathsCalculated; - gi.Nav_SetPathsCalculated = SV_Nav_SetPathsCalculated; - gi.BotAllocateClient = SV_BotAllocateClient; - gi.BotFreeClient = SV_BotFreeClient; - gi.BotLoadCharacter = SV_BotLoadCharacter; - gi.BotFreeCharacter = SV_BotFreeCharacter; - gi.Characteristic_Float = SV_Characteristic_Float; - gi.Characteristic_BFloat = SV_Characteristic_BFloat; - gi.Characteristic_Integer = SV_Characteristic_Integer; - gi.Characteristic_BInteger = SV_Characteristic_BInteger; - gi.Characteristic_String = SV_Characteristic_String; - gi.BotAllocChatState = SV_BotAllocChatState; - gi.BotFreeChatState = SV_BotFreeChatState; - gi.BotQueueConsoleMessage = SV_BotQueueConsoleMessage; - gi.BotRemoveConsoleMessage = SV_BotRemoveConsoleMessage; - gi.BotNextConsoleMessage = SV_BotNextConsoleMessage; - gi.BotNumConsoleMessages = SV_BotNumConsoleMessages; - gi.BotInitialChat = SV_BotInitialChat; - gi.BotReplyChat = SV_BotReplyChat; - gi.BotChatLength = SV_BotChatLength; - gi.BotEnterChat = SV_BotEnterChat; - gi.StringContains = SV_StringContains; - gi.BotFindMatch = SV_BotFindMatch; - gi.BotMatchVariable = SV_BotMatchVariable; - gi.UnifyWhiteSpaces = SV_UnifyWhiteSpaces; - gi.BotReplaceSynonyms = SV_BotReplaceSynonyms; - gi.BotLoadChatFile = SV_BotLoadChatFile; - gi.BotSetChatGender = SV_BotSetChatGender; - gi.BotSetChatName = SV_BotSetChatName; - gi.BotResetGoalState = SV_BotResetGoalState; - gi.BotResetAvoidGoals = SV_BotResetAvoidGoals; - gi.BotPushGoal = SV_BotPushGoal; - gi.BotPopGoal = SV_BotPopGoal; - gi.BotEmptyGoalStack = SV_BotEmptyGoalStack; - gi.BotDumpAvoidGoals = SV_BotDumpAvoidGoals; - gi.BotDumpGoalStack = SV_BotDumpGoalStack; - gi.BotGoalName = SV_BotGoalName; - gi.BotGetTopGoal = SV_BotGetTopGoal; - gi.BotGetSecondGoal = SV_BotGetSecondGoal; - gi.BotChooseLTGItem = SV_BotChooseLTGItem; - gi.BotChooseNBGItem = SV_BotChooseNBGItem; - gi.BotTouchingGoal = SV_BotTouchingGoal; - gi.BotItemGoalInVisButNotVisible = SV_BotItemGoalInVisButNotVisible; - gi.BotGetLevelItemGoal = SV_BotGetLevelItemGoal; - gi.BotAvoidGoalTime = SV_BotAvoidGoalTime; - gi.BotInitLevelItems = SV_BotInitLevelItems; - gi.BotUpdateEntityItems = SV_BotUpdateEntityItems; - gi.BotLoadItemWeights = SV_BotLoadItemWeights; - gi.BotFreeItemWeights = SV_BotFreeItemWeights; - gi.BotSaveGoalFuzzyLogic = SV_BotSaveGoalFuzzyLogic; - gi.BotAllocGoalState = SV_BotAllocGoalState; - gi.BotFreeGoalState = SV_BotFreeGoalState; - gi.BotResetMoveState = SV_BotResetMoveState; - gi.BotMoveToGoal = SV_BotMoveToGoal; - gi.BotMoveInDirection = SV_BotMoveInDirection; - gi.BotResetAvoidReach = SV_BotResetAvoidReach; - gi.BotResetLastAvoidReach = SV_BotResetLastAvoidReach; - gi.BotReachabilityArea = SV_BotReachabilityArea; - gi.BotMovementViewTarget = SV_BotMovementViewTarget; - gi.BotAllocMoveState = SV_BotAllocMoveState; - gi.BotFreeMoveState = SV_BotFreeMoveState; - gi.BotInitMoveState = SV_BotInitMoveState; - gi.BotChooseBestFightWeapon = SV_BotChooseBestFightWeapon; - gi.BotGetWeaponInfo = SV_BotGetWeaponInfo; - gi.BotLoadWeaponWeights = SV_BotLoadWeaponWeights; - gi.BotAllocWeaponState = SV_BotAllocWeaponState; - gi.BotFreeWeaponState = SV_BotFreeWeaponState; - gi.BotResetWeaponState = SV_BotResetWeaponState; - gi.GeneticParentsAndChildSelection = SV_GeneticParentsAndChildSelection; - gi.BotInterbreedGoalFuzzyLogic = SV_BotInterbreedGoalFuzzyLogic; - gi.BotMutateGoalFuzzyLogic = SV_BotMutateGoalFuzzyLogic; - gi.BotGetNextCampSpotGoal = SV_BotGetNextCampSpotGoal; - gi.BotGetMapLocationGoal = SV_BotGetMapLocationGoal; - gi.BotNumInitialChats = SV_BotNumInitialChats; - gi.BotGetChatMessage = SV_BotGetChatMessage; - gi.BotRemoveFromAvoidGoals = SV_BotRemoveFromAvoidGoals; - gi.BotPredictVisiblePosition = SV_BotPredictVisiblePosition; - gi.BotSetAvoidGoalTime = SV_BotSetAvoidGoalTime; - gi.BotAddAvoidSpot = SV_BotAddAvoidSpot; - gi.BotLibSetup = SV_BotLibSetup; - gi.BotLibShutdown = SV_BotLibShutdown; - gi.BotLibVarSet = SV_BotLibVarSet; - gi.BotLibVarGet = SV_BotLibVarGet; - gi.BotLibDefine = SV_BotLibDefine; - gi.BotLibStartFrame = SV_BotLibStartFrame; - gi.BotLibLoadMap = SV_BotLibLoadMap; - gi.BotLibUpdateEntity = SV_BotLibUpdateEntity; - gi.BotLibTest = SV_BotLibTest; - gi.BotGetSnapshotEntity = SV_BotGetSnapshotEntity; - gi.BotGetServerCommand = SV_BotGetServerCommand; - gi.BotUserCommand = SV_BotUserCommand; - gi.BotUpdateWaypoints = SV_BotWaypointReception; - gi.BotCalculatePaths = SV_BotCalculatePaths; - gi.AAS_EnableRoutingArea = SV_AAS_EnableRoutingArea; - gi.AAS_BBoxAreas = SV_AAS_BBoxAreas; - gi.AAS_AreaInfo = SV_AAS_AreaInfo; - gi.AAS_EntityInfo = SV_AAS_EntityInfo; - gi.AAS_Initialized = SV_AAS_Initialized; - gi.AAS_PresenceTypeBoundingBox = SV_AAS_PresenceTypeBoundingBox; - gi.AAS_Time = SV_AAS_Time; - gi.AAS_PointAreaNum = SV_AAS_PointAreaNum; - gi.AAS_TraceAreas = SV_AAS_TraceAreas; - gi.AAS_PointContents = SV_AAS_PointContents; - gi.AAS_NextBSPEntity = SV_AAS_NextBSPEntity; - gi.AAS_ValueForBSPEpairKey = SV_AAS_ValueForBSPEpairKey; - gi.AAS_VectorForBSPEpairKey = SV_AAS_VectorForBSPEpairKey; - gi.AAS_FloatForBSPEpairKey = SV_AAS_FloatForBSPEpairKey; - gi.AAS_IntForBSPEpairKey = SV_AAS_IntForBSPEpairKey; - gi.AAS_AreaReachability = SV_AAS_AreaReachability; - gi.AAS_AreaTravelTimeToGoalArea = SV_AAS_AreaTravelTimeToGoalArea; - gi.AAS_Swimming = SV_AAS_Swimming; - gi.AAS_PredictClientMovement = SV_AAS_PredictClientMovement; - gi.AAS_AlternativeRouteGoals = SV_AAS_AlternativeRouteGoals; - gi.AAS_PredictRoute = SV_AAS_PredictRoute; - gi.AAS_PointReachabilityAreaIndex = SV_AAS_PointReachabilityAreaIndex; - gi.EA_Say = SV_EA_Say; - gi.EA_SayTeam = SV_EA_SayTeam; - gi.EA_Command = SV_EA_Command; - gi.EA_Action = SV_EA_Action; - gi.EA_Gesture = SV_EA_Gesture; - gi.EA_Talk = SV_EA_Talk; - gi.EA_Attack = SV_EA_Attack; - gi.EA_Alt_Attack = SV_EA_Alt_Attack; - gi.EA_ForcePower = SV_EA_ForcePower; - gi.EA_Use = SV_EA_Use; - gi.EA_Respawn = SV_EA_Respawn; - gi.EA_Crouch = SV_EA_Crouch; - gi.EA_MoveUp = SV_EA_MoveUp; - gi.EA_MoveDown = SV_EA_MoveDown; - gi.EA_MoveForward = SV_EA_MoveForward; - gi.EA_MoveBack = SV_EA_MoveBack; - gi.EA_MoveLeft = SV_EA_MoveLeft; - gi.EA_MoveRight = SV_EA_MoveRight; - gi.EA_SelectWeapon = SV_EA_SelectWeapon; - gi.EA_Jump = SV_EA_Jump; - gi.EA_DelayedJump = SV_EA_DelayedJump; - gi.EA_Move = SV_EA_Move; - gi.EA_View = SV_EA_View; - gi.EA_EndRegular = SV_EA_EndRegular; - gi.EA_GetInput = SV_EA_GetInput; - gi.EA_ResetInput = SV_EA_ResetInput; - gi.PC_LoadSource = SV_PC_LoadSource; - gi.PC_FreeSource = SV_PC_FreeSource; - gi.PC_ReadToken = SV_PC_ReadToken; - gi.PC_SourceFileAndLine = SV_PC_SourceFileAndLine; - gi.R_RegisterSkin = SV_RE_RegisterSkin; - gi.SetActiveSubBSP = SV_SetActiveSubBSP; - gi.CM_RegisterTerrain = SV_CM_RegisterTerrain; - gi.RMG_Init = SV_RMG_Init; - gi.G2API_ListModelBones = SV_G2API_ListModelBones; - gi.G2API_ListModelSurfaces = SV_G2API_ListModelSurfaces; - gi.G2API_HaveWeGhoul2Models = SV_G2API_HaveWeGhoul2Models; - gi.G2API_SetGhoul2ModelIndexes = SV_G2API_SetGhoul2ModelIndexes; - gi.G2API_GetBoltMatrix = SV_G2API_GetBoltMatrix; - gi.G2API_GetBoltMatrix_NoReconstruct = SV_G2API_GetBoltMatrix_NoReconstruct; - gi.G2API_GetBoltMatrix_NoRecNoRot = SV_G2API_GetBoltMatrix_NoRecNoRot; - gi.G2API_InitGhoul2Model = SV_G2API_InitGhoul2Model; - gi.G2API_SetSkin = SV_G2API_SetSkin; - gi.G2API_Ghoul2Size = SV_G2API_Ghoul2Size; - gi.G2API_AddBolt = SV_G2API_AddBolt; - gi.G2API_SetBoltInfo = SV_G2API_SetBoltInfo; - gi.G2API_SetBoneAngles = SV_G2API_SetBoneAngles; - gi.G2API_SetBoneAnim = SV_G2API_SetBoneAnim; - gi.G2API_GetBoneAnim = SV_G2API_GetBoneAnim; - gi.G2API_GetGLAName = SV_G2API_GetGLAName; - gi.G2API_CopyGhoul2Instance = SV_G2API_CopyGhoul2Instance; - gi.G2API_CopySpecificGhoul2Model = SV_G2API_CopySpecificGhoul2Model; - gi.G2API_DuplicateGhoul2Instance = SV_G2API_DuplicateGhoul2Instance; - gi.G2API_HasGhoul2ModelOnIndex = SV_G2API_HasGhoul2ModelOnIndex; - gi.G2API_RemoveGhoul2Model = SV_G2API_RemoveGhoul2Model; - gi.G2API_RemoveGhoul2Models = SV_G2API_RemoveGhoul2Models; - gi.G2API_CleanGhoul2Models = SV_G2API_CleanGhoul2Models; - gi.G2API_CollisionDetect = SV_G2API_CollisionDetect; - gi.G2API_CollisionDetectCache = SV_G2API_CollisionDetectCache; - gi.G2API_SetRootSurface = SV_G2API_SetRootSurface; - gi.G2API_SetSurfaceOnOff = SV_G2API_SetSurfaceOnOff; - gi.G2API_SetNewOrigin = SV_G2API_SetNewOrigin; - gi.G2API_DoesBoneExist = SV_G2API_DoesBoneExist; - gi.G2API_GetSurfaceRenderStatus = SV_G2API_GetSurfaceRenderStatus; - gi.G2API_AbsurdSmoothing = SV_G2API_AbsurdSmoothing; - gi.G2API_SetRagDoll = SV_G2API_SetRagDoll; - gi.G2API_AnimateG2Models = SV_G2API_AnimateG2Models; - gi.G2API_RagPCJConstraint = SV_G2API_RagPCJConstraint; - gi.G2API_RagPCJGradientSpeed = SV_G2API_RagPCJGradientSpeed; - gi.G2API_RagEffectorGoal = SV_G2API_RagEffectorGoal; - gi.G2API_GetRagBonePos = SV_G2API_GetRagBonePos; - gi.G2API_RagEffectorKick = SV_G2API_RagEffectorKick; - gi.G2API_RagForceSolve = SV_G2API_RagForceSolve; - gi.G2API_SetBoneIKState = SV_G2API_SetBoneIKState; - gi.G2API_IKMove = SV_G2API_IKMove; - gi.G2API_RemoveBone = SV_G2API_RemoveBone; - gi.G2API_AttachInstanceToEntNum = SV_G2API_AttachInstanceToEntNum; - gi.G2API_ClearAttachedInstance = SV_G2API_ClearAttachedInstance; - gi.G2API_CleanEntAttachments = SV_G2API_CleanEntAttachments; - gi.G2API_OverrideServer = SV_G2API_OverrideServer; - gi.G2API_GetSurfaceName = SV_G2API_GetSurfaceName; + gameExport_t *ret; + GetGameAPI_t GetGameAPI; + char dllName[MAX_OSPATH] = "jampgame" ARCH_STRING DLL_EXT; + + memset(&gi, 0, sizeof(gi)); + + gvm = VM_Create(VM_GAME); + if (gvm && !gvm->isLegacy) { + gi.Print = Com_Printf; + gi.Error = Com_Error; + gi.Milliseconds = Com_Milliseconds; + gi.PrecisionTimerStart = SV_PrecisionTimerStart; + gi.PrecisionTimerEnd = SV_PrecisionTimerEnd; + gi.SV_RegisterSharedMemory = SV_RegisterSharedMemory; + gi.RealTime = Com_RealTime; + gi.TrueMalloc = VM_Shifted_Alloc; + gi.TrueFree = VM_Shifted_Free; + gi.SnapVector = Sys_SnapVector; + gi.Cvar_Register = Cvar_Register; + gi.Cvar_Set = GVM_Cvar_Set; + gi.Cvar_Update = Cvar_Update; + gi.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; + gi.Cvar_VariableStringBuffer = Cvar_VariableStringBuffer; + gi.Argc = Cmd_Argc; + gi.Argv = Cmd_ArgvBuffer; + gi.FS_Close = FS_FCloseFile; + gi.FS_GetFileList = FS_GetFileList; + gi.FS_Open = FS_FOpenFileByMode; + gi.FS_Read = FS_Read; + gi.FS_Write = FS_Write; + gi.AdjustAreaPortalState = SV_AdjustAreaPortalState; + gi.AreasConnected = CM_AreasConnected; + gi.DebugPolygonCreate = BotImport_DebugPolygonCreate; + gi.DebugPolygonDelete = BotImport_DebugPolygonDelete; + gi.DropClient = SV_GameDropClient; + gi.EntitiesInBox = SV_AreaEntities; + gi.EntityContact = SV_EntityContact; + gi.Trace = SV_Trace; + gi.GetConfigstring = SV_GetConfigstring; + gi.GetEntityToken = SV_GetEntityToken; + gi.GetServerinfo = SV_GetServerinfo; + gi.GetUsercmd = SV_GetUsercmd; + gi.GetUserinfo = SV_GetUserinfo; + gi.InPVS = SV_inPVS; + gi.InPVSIgnorePortals = SV_inPVSIgnorePortals; + gi.LinkEntity = SV_LinkEntity; + gi.LocateGameData = SV_LocateGameData; + gi.PointContents = SV_PointContents; + gi.SendConsoleCommand = Cbuf_ExecuteText; + gi.SendServerCommand = SV_GameSendServerCommand; + gi.SetBrushModel = SV_SetBrushModel; + gi.SetConfigstring = SV_SetConfigstring; + gi.SetServerCull = SV_SetServerCull; + gi.SetUserinfo = SV_SetUserinfo; + gi.SiegePersSet = SV_SiegePersSet; + gi.SiegePersGet = SV_SiegePersGet; + gi.UnlinkEntity = SV_UnlinkEntity; + gi.ROFF_Clean = SV_ROFF_Clean; + gi.ROFF_UpdateEntities = SV_ROFF_UpdateEntities; + gi.ROFF_Cache = SV_ROFF_Cache; + gi.ROFF_Play = SV_ROFF_Play; + gi.ROFF_Purge_Ent = SV_ROFF_Purge_Ent; + gi.ICARUS_RunScript = ICARUS_RunScript; + gi.ICARUS_RegisterScript = SV_ICARUS_RegisterScript; + gi.ICARUS_Init = ICARUS_Init; + gi.ICARUS_ValidEnt = SV_ICARUS_ValidEnt; + gi.ICARUS_IsInitialized = ICARUS_IsInitialized; + gi.ICARUS_MaintainTaskManager = ICARUS_MaintainTaskManager; + gi.ICARUS_IsRunning = ICARUS_IsRunning; + gi.ICARUS_TaskIDPending = ICARUS_TaskIDPending; + gi.ICARUS_InitEnt = ICARUS_InitEnt; + gi.ICARUS_FreeEnt = ICARUS_FreeEnt; + gi.ICARUS_AssociateEnt = ICARUS_AssociateEnt; + gi.ICARUS_Shutdown = ICARUS_Shutdown; + gi.ICARUS_TaskIDSet = SV_ICARUS_TaskIDSet; + gi.ICARUS_TaskIDComplete = SV_ICARUS_TaskIDComplete; + gi.ICARUS_SetVar = Q3_SetVar; + gi.ICARUS_VariableDeclared = Q3_VariableDeclared; + gi.ICARUS_GetFloatVariable = Q3_GetFloatVariable; + gi.ICARUS_GetStringVariable = SV_ICARUS_GetStringVariable; + gi.ICARUS_GetVectorVariable = SV_ICARUS_GetVectorVariable; + gi.Nav_Init = SV_Nav_Init; + gi.Nav_Free = SV_Nav_Free; + gi.Nav_Load = SV_Nav_Load; + gi.Nav_Save = SV_Nav_Save; + gi.Nav_AddRawPoint = SV_Nav_AddRawPoint; + gi.Nav_CalculatePaths = SV_Nav_CalculatePaths; + gi.Nav_HardConnect = SV_Nav_HardConnect; + gi.Nav_ShowNodes = SV_Nav_ShowNodes; + gi.Nav_ShowEdges = SV_Nav_ShowEdges; + gi.Nav_ShowPath = SV_Nav_ShowPath; + gi.Nav_GetNearestNode = SV_Nav_GetNearestNode; + gi.Nav_GetBestNode = SV_Nav_GetBestNode; + gi.Nav_GetNodePosition = SV_Nav_GetNodePosition; + gi.Nav_GetNodeNumEdges = SV_Nav_GetNodeNumEdges; + gi.Nav_GetNodeEdge = SV_Nav_GetNodeEdge; + gi.Nav_GetNumNodes = SV_Nav_GetNumNodes; + gi.Nav_Connected = SV_Nav_Connected; + gi.Nav_GetPathCost = SV_Nav_GetPathCost; + gi.Nav_GetEdgeCost = SV_Nav_GetEdgeCost; + gi.Nav_GetProjectedNode = SV_Nav_GetProjectedNode; + gi.Nav_CheckFailedNodes = SV_Nav_CheckFailedNodes; + gi.Nav_AddFailedNode = SV_Nav_AddFailedNode; + gi.Nav_NodeFailed = SV_Nav_NodeFailed; + gi.Nav_NodesAreNeighbors = SV_Nav_NodesAreNeighbors; + gi.Nav_ClearFailedEdge = SV_Nav_ClearFailedEdge; + gi.Nav_ClearAllFailedEdges = SV_Nav_ClearAllFailedEdges; + gi.Nav_EdgeFailed = SV_Nav_EdgeFailed; + gi.Nav_AddFailedEdge = SV_Nav_AddFailedEdge; + gi.Nav_CheckFailedEdge = SV_Nav_CheckFailedEdge; + gi.Nav_CheckAllFailedEdges = SV_Nav_CheckAllFailedEdges; + gi.Nav_RouteBlocked = SV_Nav_RouteBlocked; + gi.Nav_GetBestNodeAltRoute = SV_Nav_GetBestNodeAltRoute; + gi.Nav_GetBestNodeAltRoute2 = SV_Nav_GetBestNodeAltRoute2; + gi.Nav_GetBestPathBetweenEnts = SV_Nav_GetBestPathBetweenEnts; + gi.Nav_GetNodeRadius = SV_Nav_GetNodeRadius; + gi.Nav_CheckBlockedEdges = SV_Nav_CheckBlockedEdges; + gi.Nav_ClearCheckedNodes = SV_Nav_ClearCheckedNodes; + gi.Nav_CheckedNode = SV_Nav_CheckedNode; + gi.Nav_SetCheckedNode = SV_Nav_SetCheckedNode; + gi.Nav_FlagAllNodes = SV_Nav_FlagAllNodes; + gi.Nav_GetPathsCalculated = SV_Nav_GetPathsCalculated; + gi.Nav_SetPathsCalculated = SV_Nav_SetPathsCalculated; + gi.BotAllocateClient = SV_BotAllocateClient; + gi.BotFreeClient = SV_BotFreeClient; + gi.BotLoadCharacter = SV_BotLoadCharacter; + gi.BotFreeCharacter = SV_BotFreeCharacter; + gi.Characteristic_Float = SV_Characteristic_Float; + gi.Characteristic_BFloat = SV_Characteristic_BFloat; + gi.Characteristic_Integer = SV_Characteristic_Integer; + gi.Characteristic_BInteger = SV_Characteristic_BInteger; + gi.Characteristic_String = SV_Characteristic_String; + gi.BotAllocChatState = SV_BotAllocChatState; + gi.BotFreeChatState = SV_BotFreeChatState; + gi.BotQueueConsoleMessage = SV_BotQueueConsoleMessage; + gi.BotRemoveConsoleMessage = SV_BotRemoveConsoleMessage; + gi.BotNextConsoleMessage = SV_BotNextConsoleMessage; + gi.BotNumConsoleMessages = SV_BotNumConsoleMessages; + gi.BotInitialChat = SV_BotInitialChat; + gi.BotReplyChat = SV_BotReplyChat; + gi.BotChatLength = SV_BotChatLength; + gi.BotEnterChat = SV_BotEnterChat; + gi.StringContains = SV_StringContains; + gi.BotFindMatch = SV_BotFindMatch; + gi.BotMatchVariable = SV_BotMatchVariable; + gi.UnifyWhiteSpaces = SV_UnifyWhiteSpaces; + gi.BotReplaceSynonyms = SV_BotReplaceSynonyms; + gi.BotLoadChatFile = SV_BotLoadChatFile; + gi.BotSetChatGender = SV_BotSetChatGender; + gi.BotSetChatName = SV_BotSetChatName; + gi.BotResetGoalState = SV_BotResetGoalState; + gi.BotResetAvoidGoals = SV_BotResetAvoidGoals; + gi.BotPushGoal = SV_BotPushGoal; + gi.BotPopGoal = SV_BotPopGoal; + gi.BotEmptyGoalStack = SV_BotEmptyGoalStack; + gi.BotDumpAvoidGoals = SV_BotDumpAvoidGoals; + gi.BotDumpGoalStack = SV_BotDumpGoalStack; + gi.BotGoalName = SV_BotGoalName; + gi.BotGetTopGoal = SV_BotGetTopGoal; + gi.BotGetSecondGoal = SV_BotGetSecondGoal; + gi.BotChooseLTGItem = SV_BotChooseLTGItem; + gi.BotChooseNBGItem = SV_BotChooseNBGItem; + gi.BotTouchingGoal = SV_BotTouchingGoal; + gi.BotItemGoalInVisButNotVisible = SV_BotItemGoalInVisButNotVisible; + gi.BotGetLevelItemGoal = SV_BotGetLevelItemGoal; + gi.BotAvoidGoalTime = SV_BotAvoidGoalTime; + gi.BotInitLevelItems = SV_BotInitLevelItems; + gi.BotUpdateEntityItems = SV_BotUpdateEntityItems; + gi.BotLoadItemWeights = SV_BotLoadItemWeights; + gi.BotFreeItemWeights = SV_BotFreeItemWeights; + gi.BotSaveGoalFuzzyLogic = SV_BotSaveGoalFuzzyLogic; + gi.BotAllocGoalState = SV_BotAllocGoalState; + gi.BotFreeGoalState = SV_BotFreeGoalState; + gi.BotResetMoveState = SV_BotResetMoveState; + gi.BotMoveToGoal = SV_BotMoveToGoal; + gi.BotMoveInDirection = SV_BotMoveInDirection; + gi.BotResetAvoidReach = SV_BotResetAvoidReach; + gi.BotResetLastAvoidReach = SV_BotResetLastAvoidReach; + gi.BotReachabilityArea = SV_BotReachabilityArea; + gi.BotMovementViewTarget = SV_BotMovementViewTarget; + gi.BotAllocMoveState = SV_BotAllocMoveState; + gi.BotFreeMoveState = SV_BotFreeMoveState; + gi.BotInitMoveState = SV_BotInitMoveState; + gi.BotChooseBestFightWeapon = SV_BotChooseBestFightWeapon; + gi.BotGetWeaponInfo = SV_BotGetWeaponInfo; + gi.BotLoadWeaponWeights = SV_BotLoadWeaponWeights; + gi.BotAllocWeaponState = SV_BotAllocWeaponState; + gi.BotFreeWeaponState = SV_BotFreeWeaponState; + gi.BotResetWeaponState = SV_BotResetWeaponState; + gi.GeneticParentsAndChildSelection = SV_GeneticParentsAndChildSelection; + gi.BotInterbreedGoalFuzzyLogic = SV_BotInterbreedGoalFuzzyLogic; + gi.BotMutateGoalFuzzyLogic = SV_BotMutateGoalFuzzyLogic; + gi.BotGetNextCampSpotGoal = SV_BotGetNextCampSpotGoal; + gi.BotGetMapLocationGoal = SV_BotGetMapLocationGoal; + gi.BotNumInitialChats = SV_BotNumInitialChats; + gi.BotGetChatMessage = SV_BotGetChatMessage; + gi.BotRemoveFromAvoidGoals = SV_BotRemoveFromAvoidGoals; + gi.BotPredictVisiblePosition = SV_BotPredictVisiblePosition; + gi.BotSetAvoidGoalTime = SV_BotSetAvoidGoalTime; + gi.BotAddAvoidSpot = SV_BotAddAvoidSpot; + gi.BotLibSetup = SV_BotLibSetup; + gi.BotLibShutdown = SV_BotLibShutdown; + gi.BotLibVarSet = SV_BotLibVarSet; + gi.BotLibVarGet = SV_BotLibVarGet; + gi.BotLibDefine = SV_BotLibDefine; + gi.BotLibStartFrame = SV_BotLibStartFrame; + gi.BotLibLoadMap = SV_BotLibLoadMap; + gi.BotLibUpdateEntity = SV_BotLibUpdateEntity; + gi.BotLibTest = SV_BotLibTest; + gi.BotGetSnapshotEntity = SV_BotGetSnapshotEntity; + gi.BotGetServerCommand = SV_BotGetServerCommand; + gi.BotUserCommand = SV_BotUserCommand; + gi.BotUpdateWaypoints = SV_BotWaypointReception; + gi.BotCalculatePaths = SV_BotCalculatePaths; + gi.AAS_EnableRoutingArea = SV_AAS_EnableRoutingArea; + gi.AAS_BBoxAreas = SV_AAS_BBoxAreas; + gi.AAS_AreaInfo = SV_AAS_AreaInfo; + gi.AAS_EntityInfo = SV_AAS_EntityInfo; + gi.AAS_Initialized = SV_AAS_Initialized; + gi.AAS_PresenceTypeBoundingBox = SV_AAS_PresenceTypeBoundingBox; + gi.AAS_Time = SV_AAS_Time; + gi.AAS_PointAreaNum = SV_AAS_PointAreaNum; + gi.AAS_TraceAreas = SV_AAS_TraceAreas; + gi.AAS_PointContents = SV_AAS_PointContents; + gi.AAS_NextBSPEntity = SV_AAS_NextBSPEntity; + gi.AAS_ValueForBSPEpairKey = SV_AAS_ValueForBSPEpairKey; + gi.AAS_VectorForBSPEpairKey = SV_AAS_VectorForBSPEpairKey; + gi.AAS_FloatForBSPEpairKey = SV_AAS_FloatForBSPEpairKey; + gi.AAS_IntForBSPEpairKey = SV_AAS_IntForBSPEpairKey; + gi.AAS_AreaReachability = SV_AAS_AreaReachability; + gi.AAS_AreaTravelTimeToGoalArea = SV_AAS_AreaTravelTimeToGoalArea; + gi.AAS_Swimming = SV_AAS_Swimming; + gi.AAS_PredictClientMovement = SV_AAS_PredictClientMovement; + gi.AAS_AlternativeRouteGoals = SV_AAS_AlternativeRouteGoals; + gi.AAS_PredictRoute = SV_AAS_PredictRoute; + gi.AAS_PointReachabilityAreaIndex = SV_AAS_PointReachabilityAreaIndex; + gi.EA_Say = SV_EA_Say; + gi.EA_SayTeam = SV_EA_SayTeam; + gi.EA_Command = SV_EA_Command; + gi.EA_Action = SV_EA_Action; + gi.EA_Gesture = SV_EA_Gesture; + gi.EA_Talk = SV_EA_Talk; + gi.EA_Attack = SV_EA_Attack; + gi.EA_Alt_Attack = SV_EA_Alt_Attack; + gi.EA_ForcePower = SV_EA_ForcePower; + gi.EA_Use = SV_EA_Use; + gi.EA_Respawn = SV_EA_Respawn; + gi.EA_Crouch = SV_EA_Crouch; + gi.EA_MoveUp = SV_EA_MoveUp; + gi.EA_MoveDown = SV_EA_MoveDown; + gi.EA_MoveForward = SV_EA_MoveForward; + gi.EA_MoveBack = SV_EA_MoveBack; + gi.EA_MoveLeft = SV_EA_MoveLeft; + gi.EA_MoveRight = SV_EA_MoveRight; + gi.EA_SelectWeapon = SV_EA_SelectWeapon; + gi.EA_Jump = SV_EA_Jump; + gi.EA_DelayedJump = SV_EA_DelayedJump; + gi.EA_Move = SV_EA_Move; + gi.EA_View = SV_EA_View; + gi.EA_EndRegular = SV_EA_EndRegular; + gi.EA_GetInput = SV_EA_GetInput; + gi.EA_ResetInput = SV_EA_ResetInput; + gi.PC_LoadSource = SV_PC_LoadSource; + gi.PC_FreeSource = SV_PC_FreeSource; + gi.PC_ReadToken = SV_PC_ReadToken; + gi.PC_SourceFileAndLine = SV_PC_SourceFileAndLine; + gi.R_RegisterSkin = SV_RE_RegisterSkin; + gi.SetActiveSubBSP = SV_SetActiveSubBSP; + gi.CM_RegisterTerrain = SV_CM_RegisterTerrain; + gi.RMG_Init = SV_RMG_Init; + gi.G2API_ListModelBones = SV_G2API_ListModelBones; + gi.G2API_ListModelSurfaces = SV_G2API_ListModelSurfaces; + gi.G2API_HaveWeGhoul2Models = SV_G2API_HaveWeGhoul2Models; + gi.G2API_SetGhoul2ModelIndexes = SV_G2API_SetGhoul2ModelIndexes; + gi.G2API_GetBoltMatrix = SV_G2API_GetBoltMatrix; + gi.G2API_GetBoltMatrix_NoReconstruct = SV_G2API_GetBoltMatrix_NoReconstruct; + gi.G2API_GetBoltMatrix_NoRecNoRot = SV_G2API_GetBoltMatrix_NoRecNoRot; + gi.G2API_InitGhoul2Model = SV_G2API_InitGhoul2Model; + gi.G2API_SetSkin = SV_G2API_SetSkin; + gi.G2API_Ghoul2Size = SV_G2API_Ghoul2Size; + gi.G2API_AddBolt = SV_G2API_AddBolt; + gi.G2API_SetBoltInfo = SV_G2API_SetBoltInfo; + gi.G2API_SetBoneAngles = SV_G2API_SetBoneAngles; + gi.G2API_SetBoneAnim = SV_G2API_SetBoneAnim; + gi.G2API_GetBoneAnim = SV_G2API_GetBoneAnim; + gi.G2API_GetGLAName = SV_G2API_GetGLAName; + gi.G2API_CopyGhoul2Instance = SV_G2API_CopyGhoul2Instance; + gi.G2API_CopySpecificGhoul2Model = SV_G2API_CopySpecificGhoul2Model; + gi.G2API_DuplicateGhoul2Instance = SV_G2API_DuplicateGhoul2Instance; + gi.G2API_HasGhoul2ModelOnIndex = SV_G2API_HasGhoul2ModelOnIndex; + gi.G2API_RemoveGhoul2Model = SV_G2API_RemoveGhoul2Model; + gi.G2API_RemoveGhoul2Models = SV_G2API_RemoveGhoul2Models; + gi.G2API_CleanGhoul2Models = SV_G2API_CleanGhoul2Models; + gi.G2API_CollisionDetect = SV_G2API_CollisionDetect; + gi.G2API_CollisionDetectCache = SV_G2API_CollisionDetectCache; + gi.G2API_SetRootSurface = SV_G2API_SetRootSurface; + gi.G2API_SetSurfaceOnOff = SV_G2API_SetSurfaceOnOff; + gi.G2API_SetNewOrigin = SV_G2API_SetNewOrigin; + gi.G2API_DoesBoneExist = SV_G2API_DoesBoneExist; + gi.G2API_GetSurfaceRenderStatus = SV_G2API_GetSurfaceRenderStatus; + gi.G2API_AbsurdSmoothing = SV_G2API_AbsurdSmoothing; + gi.G2API_SetRagDoll = SV_G2API_SetRagDoll; + gi.G2API_AnimateG2Models = SV_G2API_AnimateG2Models; + gi.G2API_RagPCJConstraint = SV_G2API_RagPCJConstraint; + gi.G2API_RagPCJGradientSpeed = SV_G2API_RagPCJGradientSpeed; + gi.G2API_RagEffectorGoal = SV_G2API_RagEffectorGoal; + gi.G2API_GetRagBonePos = SV_G2API_GetRagBonePos; + gi.G2API_RagEffectorKick = SV_G2API_RagEffectorKick; + gi.G2API_RagForceSolve = SV_G2API_RagForceSolve; + gi.G2API_SetBoneIKState = SV_G2API_SetBoneIKState; + gi.G2API_IKMove = SV_G2API_IKMove; + gi.G2API_RemoveBone = SV_G2API_RemoveBone; + gi.G2API_AttachInstanceToEntNum = SV_G2API_AttachInstanceToEntNum; + gi.G2API_ClearAttachedInstance = SV_G2API_ClearAttachedInstance; + gi.G2API_CleanEntAttachments = SV_G2API_CleanEntAttachments; + gi.G2API_OverrideServer = SV_G2API_OverrideServer; + gi.G2API_GetSurfaceName = SV_G2API_GetSurfaceName; GetGameAPI = (GetGameAPI_t)gvm->GetModuleAPI; - ret = GetGameAPI( GAME_API_VERSION, &gi ); - if ( !ret ) { - //free VM? + ret = GetGameAPI(GAME_API_VERSION, &gi); + if (!ret) { + // free VM? svs.gameStarted = qfalse; - Com_Error( ERR_FATAL, "GetGameAPI failed on %s", dllName ); + Com_Error(ERR_FATAL, "GetGameAPI failed on %s", dllName); } ge = ret; @@ -3132,29 +2811,29 @@ void SV_BindGame( void ) { } // fall back to legacy syscall/vm_call api - gvm = VM_CreateLegacy( VM_GAME, SV_GameSystemCalls ); - if ( !gvm ) { + gvm = VM_CreateLegacy(VM_GAME, SV_GameSystemCalls); + if (!gvm) { svs.gameStarted = qfalse; - Com_Error( ERR_DROP, "VM_CreateLegacy on game failed" ); + Com_Error(ERR_DROP, "VM_CreateLegacy on game failed"); } } -void SV_UnbindGame( void ) { - GVM_ShutdownGame( qfalse ); - VM_Free( gvm ); +void SV_UnbindGame(void) { + GVM_ShutdownGame(qfalse); + VM_Free(gvm); gvm = NULL; } -void SV_RestartGame( void ) { - GVM_ShutdownGame( qtrue ); +void SV_RestartGame(void) { + GVM_ShutdownGame(qtrue); - gvm = VM_Restart( gvm ); + gvm = VM_Restart(gvm); SV_BindGame(); - if ( !gvm ) { + if (!gvm) { svs.gameStarted = qfalse; - Com_Error( ERR_DROP, "VM_Restart on game failed" ); + Com_Error(ERR_DROP, "VM_Restart on game failed"); return; } - SV_InitGame( qtrue ); + SV_InitGame(qtrue); } diff --git a/codemp/server/sv_init.cpp b/codemp/server/sv_init.cpp index be62b91bf1..268af523bc 100644 --- a/codemp/server/sv_init.cpp +++ b/codemp/server/sv_init.cpp @@ -37,42 +37,36 @@ Creates and sends the server command necessary to update the CS index for the given client =============== */ -static void SV_SendConfigstring(client_t *client, int index) -{ +static void SV_SendConfigstring(client_t *client, int index) { int maxChunkSize = MAX_STRING_CHARS - 24; int len; len = strlen(sv.configstrings[index]); - if( len >= maxChunkSize ) { - int sent = 0; - int remaining = len; - char *cmd; - char buf[MAX_STRING_CHARS]; + if (len >= maxChunkSize) { + int sent = 0; + int remaining = len; + char *cmd; + char buf[MAX_STRING_CHARS]; - while (remaining > 0 ) { - if ( sent == 0 ) { + while (remaining > 0) { + if (sent == 0) { cmd = "bcs0"; - } - else if( remaining < maxChunkSize ) { + } else if (remaining < maxChunkSize) { cmd = "bcs2"; - } - else { + } else { cmd = "bcs1"; } - Q_strncpyz( buf, &sv.configstrings[index][sent], - maxChunkSize ); + Q_strncpyz(buf, &sv.configstrings[index][sent], maxChunkSize); - SV_SendServerCommand( client, "%s %i \"%s\"\n", cmd, - index, buf ); + SV_SendServerCommand(client, "%s %i \"%s\"\n", cmd, index, buf); sent += (maxChunkSize - 1); remaining -= (maxChunkSize - 1); } } else { // standard cs, just send it - SV_SendServerCommand( client, "cs %i \"%s\"\n", index, - sv.configstrings[index] ); + SV_SendServerCommand(client, "cs %i \"%s\"\n", index, sv.configstrings[index]); } } @@ -84,18 +78,16 @@ Called when a client goes from CS_PRIMED to CS_ACTIVE. Updates all Configstring indexes that have changed while the client was in CS_PRIMED =============== */ -void SV_UpdateConfigstrings(client_t *client) -{ +void SV_UpdateConfigstrings(client_t *client) { int index; - for( index = 0; index < MAX_CONFIGSTRINGS; index++ ) { + for (index = 0; index < MAX_CONFIGSTRINGS; index++) { // if the CS hasn't changed since we went to CS_PRIMED, ignore - if(!client->csUpdated[index]) + if (!client->csUpdated[index]) continue; // do not always send server info to all clients - if ( index == CS_SERVERINFO && client->gentity && - (client->gentity->r.svFlags & SVF_NOSERVERINFO) ) { + if (index == CS_SERVERINFO && client->gentity && (client->gentity->r.svFlags & SVF_NOSERVERINFO)) { continue; } SV_SendConfigstring(client, index); @@ -109,40 +101,40 @@ SV_SetConfigstring =============== */ -void SV_SetConfigstring (int index, const char *val) { - int i; - client_t *client; +void SV_SetConfigstring(int index, const char *val) { + int i; + client_t *client; - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error (ERR_DROP, "SV_SetConfigstring: bad index %i\n", index); + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "SV_SetConfigstring: bad index %i\n", index); } - if ( !val ) { + if (!val) { val = ""; } // don't bother broadcasting an update if no change - if ( !strcmp( val, sv.configstrings[ index ] ) ) { + if (!strcmp(val, sv.configstrings[index])) { return; } // change the string in sv - Z_Free( sv.configstrings[index] ); - sv.configstrings[index] = CopyString( val ); + Z_Free(sv.configstrings[index]); + sv.configstrings[index] = CopyString(val); // send it to all the clients if we aren't // spawning a new server - if ( sv.state == SS_GAME || sv.restarting ) { + if (sv.state == SS_GAME || sv.restarting) { // send the data to all relevent clients - for (i = 0, client = svs.clients; i < sv_maxclients->integer ; i++, client++) { - if ( client->state < CS_ACTIVE ) { - if ( client->state == CS_PRIMED ) - client->csUpdated[ index ] = qtrue; + for (i = 0, client = svs.clients; i < sv_maxclients->integer; i++, client++) { + if (client->state < CS_ACTIVE) { + if (client->state == CS_PRIMED) + client->csUpdated[index] = qtrue; continue; } // do not always send server info to all clients - if ( index == CS_SERVERINFO && client->gentity && (client->gentity->r.svFlags & SVF_NOSERVERINFO) ) { + if (index == CS_SERVERINFO && client->gentity && (client->gentity->r.svFlags & SVF_NOSERVERINFO)) { continue; } @@ -157,19 +149,19 @@ SV_GetConfigstring =============== */ -void SV_GetConfigstring( int index, char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetConfigstring: bufferSize == %i", bufferSize ); +void SV_GetConfigstring(int index, char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetConfigstring: bufferSize == %i", bufferSize); } - if ( index < 0 || index >= MAX_CONFIGSTRINGS ) { - Com_Error (ERR_DROP, "SV_GetConfigstring: bad index %i\n", index); + if (index < 0 || index >= MAX_CONFIGSTRINGS) { + Com_Error(ERR_DROP, "SV_GetConfigstring: bad index %i\n", index); } - if ( !sv.configstrings[index] ) { + if (!sv.configstrings[index]) { buffer[0] = 0; return; } - Q_strncpyz( buffer, sv.configstrings[index], bufferSize ); + Q_strncpyz(buffer, sv.configstrings[index], bufferSize); } /* @@ -178,17 +170,17 @@ SV_SetUserinfo =============== */ -void SV_SetUserinfo( int index, const char *val ) { - if ( index < 0 || index >= sv_maxclients->integer ) { - Com_Error (ERR_DROP, "SV_SetUserinfo: bad index %i\n", index); +void SV_SetUserinfo(int index, const char *val) { + if (index < 0 || index >= sv_maxclients->integer) { + Com_Error(ERR_DROP, "SV_SetUserinfo: bad index %i\n", index); } - if ( !val ) { + if (!val) { val = ""; } - Q_strncpyz( svs.clients[index].userinfo, val, sizeof( svs.clients[ index ].userinfo ) ); - Q_strncpyz( svs.clients[index].name, Info_ValueForKey( val, "name" ), sizeof(svs.clients[index].name) ); + Q_strncpyz(svs.clients[index].userinfo, val, sizeof(svs.clients[index].userinfo)); + Q_strncpyz(svs.clients[index].name, Info_ValueForKey(val, "name"), sizeof(svs.clients[index].name)); } /* @@ -197,14 +189,14 @@ SV_GetUserinfo =============== */ -void SV_GetUserinfo( int index, char *buffer, int bufferSize ) { - if ( bufferSize < 1 ) { - Com_Error( ERR_DROP, "SV_GetUserinfo: bufferSize == %i", bufferSize ); +void SV_GetUserinfo(int index, char *buffer, int bufferSize) { + if (bufferSize < 1) { + Com_Error(ERR_DROP, "SV_GetUserinfo: bufferSize == %i", bufferSize); } - if ( index < 0 || index >= sv_maxclients->integer ) { - Com_Error (ERR_DROP, "SV_GetUserinfo: bad index %i\n", index); + if (index < 0 || index >= sv_maxclients->integer) { + Com_Error(ERR_DROP, "SV_GetUserinfo: bad index %i\n", index); } - Q_strncpyz( buffer, svs.clients[ index ].userinfo, bufferSize ); + Q_strncpyz(buffer, svs.clients[index].userinfo, bufferSize); } /* @@ -216,11 +208,11 @@ to the clients -- only the fields that differ from the baseline will be transmitted ================ */ -void SV_CreateBaseline( void ) { +void SV_CreateBaseline(void) { sharedEntity_t *svent; - int entnum; + int entnum; - for ( entnum = 1; entnum < sv.num_entities ; entnum++ ) { + for (entnum = 1; entnum < sv.num_entities; entnum++) { svent = SV_GentityNum(entnum); if (!svent->r.linked) { continue; @@ -240,16 +232,16 @@ SV_BoundMaxClients =============== */ -void SV_BoundMaxClients( int minimum ) { +void SV_BoundMaxClients(int minimum) { // get the current maxclients value - Cvar_Get( "sv_maxclients", "8", 0 ); + Cvar_Get("sv_maxclients", "8", 0); sv_maxclients->modified = qfalse; - if ( sv_maxclients->integer < minimum ) { - Cvar_Set( "sv_maxclients", va("%i", minimum) ); - } else if ( sv_maxclients->integer > MAX_CLIENTS ) { - Cvar_Set( "sv_maxclients", va("%i", MAX_CLIENTS) ); + if (sv_maxclients->integer < minimum) { + Cvar_Set("sv_maxclients", va("%i", minimum)); + } else if (sv_maxclients->integer > MAX_CLIENTS) { + Cvar_Set("sv_maxclients", va("%i", MAX_CLIENTS)); } } @@ -263,17 +255,17 @@ NOT cause this to be called, unless the game is exited to the menu system first. =============== */ -void SV_Startup( void ) { - if ( svs.initialized ) { - Com_Error( ERR_FATAL, "SV_Startup: svs.initialized" ); +void SV_Startup(void) { + if (svs.initialized) { + Com_Error(ERR_FATAL, "SV_Startup: svs.initialized"); } - SV_BoundMaxClients( 1 ); + SV_BoundMaxClients(1); - svs.clients = (struct client_s *)Z_Malloc (sizeof(client_t) * sv_maxclients->integer, TAG_CLIENTS, qtrue ); - if ( com_dedicated->integer ) { + svs.clients = (struct client_s *)Z_Malloc(sizeof(client_t) * sv_maxclients->integer, TAG_CLIENTS, qtrue); + if (com_dedicated->integer) { svs.numSnapshotEntities = sv_maxclients->integer * PACKET_BACKUP * MAX_SNAPSHOT_ENTITIES; - Cvar_Set( "r_ghoul2animsmooth", "0"); - Cvar_Set( "r_ghoul2unsqashaftersmooth", "0"); + Cvar_Set("r_ghoul2animsmooth", "0"); + Cvar_Set("r_ghoul2unsqashaftersmooth", "0"); } else { // we don't need nearly as many when playing locally @@ -283,19 +275,18 @@ void SV_Startup( void ) { svs.initialized = qtrue; // Don't respect sv_killserver unless a server is actually running - if ( sv_killserver->integer ) { - Cvar_Set( "sv_killserver", "0" ); + if (sv_killserver->integer) { + Cvar_Set("sv_killserver", "0"); } - Cvar_Set( "sv_running", "1" ); + Cvar_Set("sv_running", "1"); } /* Ghoul2 Insert Start */ - void SV_InitSV(void) -{ +void SV_InitSV(void) { // clear out most of the sv struct memset(&sv, 0, (sizeof(sv))); sv.mLocalSubBSPIndex = -1; @@ -309,16 +300,16 @@ Ghoul2 Insert End SV_ChangeMaxClients ================== */ -void SV_ChangeMaxClients( void ) { - int oldMaxClients; - int i; - client_t *oldClients; - int count; +void SV_ChangeMaxClients(void) { + int oldMaxClients; + int i; + client_t *oldClients; + int count; // get the highest client number in use count = 0; - for ( i = 0 ; i < sv_maxclients->integer ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = 0; i < sv_maxclients->integer; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { if (i > count) count = i; } @@ -327,42 +318,41 @@ void SV_ChangeMaxClients( void ) { oldMaxClients = sv_maxclients->integer; // never go below the highest client number in use - SV_BoundMaxClients( count ); + SV_BoundMaxClients(count); // if still the same - if ( sv_maxclients->integer == oldMaxClients ) { + if (sv_maxclients->integer == oldMaxClients) { return; } - oldClients = (struct client_s *)Hunk_AllocateTempMemory( count * sizeof(client_t) ); + oldClients = (struct client_s *)Hunk_AllocateTempMemory(count * sizeof(client_t)); // copy the clients to hunk memory - for ( i = 0 ; i < count ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = 0; i < count; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { oldClients[i] = svs.clients[i]; - } - else { + } else { Com_Memset(&oldClients[i], 0, sizeof(client_t)); } } // free old clients arrays - Z_Free( svs.clients ); + Z_Free(svs.clients); // allocate new clients - svs.clients = (struct client_s *)Z_Malloc ( sv_maxclients->integer * sizeof(client_t), TAG_CLIENTS, qtrue ); - Com_Memset( svs.clients, 0, sv_maxclients->integer * sizeof(client_t) ); + svs.clients = (struct client_s *)Z_Malloc(sv_maxclients->integer * sizeof(client_t), TAG_CLIENTS, qtrue); + Com_Memset(svs.clients, 0, sv_maxclients->integer * sizeof(client_t)); // copy the clients over - for ( i = 0 ; i < count ; i++ ) { - if ( oldClients[i].state >= CS_CONNECTED ) { + for (i = 0; i < count; i++) { + if (oldClients[i].state >= CS_CONNECTED) { svs.clients[i] = oldClients[i]; } } // free the old clients on the hunk - Hunk_FreeTempMemory( oldClients ); + Hunk_FreeTempMemory(oldClients); // allocate new snapshot entities - if ( com_dedicated->integer ) { + if (com_dedicated->integer) { svs.numSnapshotEntities = sv_maxclients->integer * PACKET_BACKUP * MAX_SNAPSHOT_ENTITIES; } else { // we don't need nearly as many when playing locally @@ -378,25 +368,25 @@ SV_ClearServer void SV_ClearServer(void) { int i; - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { - if ( sv.configstrings[i] ) { - Z_Free( sv.configstrings[i] ); + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { + if (sv.configstrings[i]) { + Z_Free(sv.configstrings[i]); } } -// CM_ClearMap(); + // CM_ClearMap(); /* Ghoul2 Insert Start */ // nope, can't do this anymore.. sv contains entitystates with STL in them. -// memset (&sv, 0, sizeof(sv)); - SV_InitSV(); -/* -Ghoul2 Insert End -*/ -// Com_Memset (&sv, 0, sizeof(sv)); + // memset (&sv, 0, sizeof(sv)); + SV_InitSV(); + /* + Ghoul2 Insert End + */ + // Com_Memset (&sv, 0, sizeof(sv)); } /* @@ -407,38 +397,32 @@ SV_TouchCGame ================ */ void SV_TouchCGame(void) { - fileHandle_t f; + fileHandle_t f; char filename[MAX_QPATH]; - Com_sprintf( filename, sizeof(filename), "cgamex86.dll" ); + Com_sprintf(filename, sizeof(filename), "cgamex86.dll"); - FS_FOpenFileRead( filename, &f, qfalse ); - if ( f ) { - FS_FCloseFile( f ); + FS_FOpenFileRead(filename, &f, qfalse); + if (f) { + FS_FCloseFile(f); } } -void SV_SendMapChange(void) -{ - int i; +void SV_SendMapChange(void) { + int i; - if (svs.clients) - { - for (i=0 ; iinteger ; i++) - { - if (svs.clients[i].state >= CS_CONNECTED) - { - if ( svs.clients[i].netchan.remoteAddress.type != NA_BOT || - svs.clients[i].demo.demorecording ) - { - SV_SendClientMapChange( &svs.clients[i] ) ; + if (svs.clients) { + for (i = 0; i < sv_maxclients->integer; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { + if (svs.clients[i].netchan.remoteAddress.type != NA_BOT || svs.clients[i].demo.demorecording) { + SV_SendClientMapChange(&svs.clients[i]); } } } } } -extern void SV_SendClientGameState( client_t *client ); +extern void SV_SendClientGameState(client_t *client); /* ================ SV_SpawnServer @@ -448,12 +432,12 @@ clients along with it. This is NOT called for map_restart ================ */ -void SV_SpawnServer( char *server, qboolean killBots, ForceReload_e eForceReload ) { - int i; - int checksum; - qboolean isBot; - char systemInfo[16384]; - const char *p; +void SV_SpawnServer(char *server, qboolean killBots, ForceReload_e eForceReload) { + int i; + int checksum; + qboolean isBot; + char systemInfo[16384]; + const char *p; SV_StopAutoRecordDemos(); @@ -465,21 +449,20 @@ void SV_SpawnServer( char *server, qboolean killBots, ForceReload_e eForceReload SV_ShutdownGameProgs(); svs.gameStarted = qfalse; - Com_Printf ("------ Server Initialization ------\n"); - Com_Printf ("Server: %s\n",server); + Com_Printf("------ Server Initialization ------\n"); + Com_Printf("Server: %s\n", server); -/* -Ghoul2 Insert Start -*/ - // de allocate the snapshot entities - if (svs.snapshotEntities) - { + /* + Ghoul2 Insert Start + */ + // de allocate the snapshot entities + if (svs.snapshotEntities) { delete[] svs.snapshotEntities; svs.snapshotEntities = NULL; } -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ SV_SendMapChange(); @@ -489,7 +472,7 @@ Ghoul2 Insert End #ifndef DEDICATED // make sure all the client stuff is unloaded - CL_ShutdownAll( qfalse ); + CL_ShutdownAll(qfalse); #endif CM_ClearMap(); @@ -501,21 +484,21 @@ Ghoul2 Insert End re->InitShaders(qtrue); // init client structures and svs.numSnapshotEntities - if ( !Cvar_VariableValue("sv_running") ) { + if (!Cvar_VariableValue("sv_running")) { SV_Startup(); } else { // check for maxclients change - if ( sv_maxclients->modified ) { + if (sv_maxclients->modified) { SV_ChangeMaxClients(); } } SV_SendMapChange(); -/* -Ghoul2 Insert Start -*/ - // clear out those shaders, images and Models as long as this + /* + Ghoul2 Insert Start + */ + // clear out those shaders, images and Models as long as this // isnt a dedicated server. /* if ( !com_dedicated->integer ) @@ -530,8 +513,7 @@ Ghoul2 Insert Start } else */ - if (com_dedicated->integer) - { + if (com_dedicated->integer) { re->SVModelInit(); } @@ -540,21 +522,21 @@ Ghoul2 Insert Start // clear pak references FS_ClearPakReferences(0); -/* -Ghoul2 Insert Start -*/ + /* + Ghoul2 Insert Start + */ // allocate the snapshot entities on the hunk -// svs.snapshotEntities = (struct entityState_s *)Hunk_Alloc( sizeof(entityState_t)*svs.numSnapshotEntities, h_high ); + // svs.snapshotEntities = (struct entityState_s *)Hunk_Alloc( sizeof(entityState_t)*svs.numSnapshotEntities, h_high ); svs.nextSnapshotEntities = 0; // allocate the snapshot entities svs.snapshotEntities = new entityState_s[svs.numSnapshotEntities]; // we CAN afford to do this here, since we know the STL vectors in Ghoul2 are empty - memset(svs.snapshotEntities, 0, sizeof(entityState_t)*svs.numSnapshotEntities); + memset(svs.snapshotEntities, 0, sizeof(entityState_t) * svs.numSnapshotEntities); -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ // toggle the server bit so clients can detect that a // server has changed @@ -562,10 +544,10 @@ Ghoul2 Insert End // set nextmap to the same map, but it may be overriden // by the game startup or another console command - Cvar_Set( "nextmap", "map_restart 0"); -// Cvar_Set( "nextmap", va("map %s", server) ); + Cvar_Set("nextmap", "map_restart 0"); + // Cvar_Set( "nextmap", va("map %s", server) ); - for (i=0 ; iinteger ; i++) { + for (i = 0; i < sv_maxclients->integer; i++) { // save when the server started for each client already connected if (svs.clients[i].state >= CS_CONNECTED) { svs.clients[i].oldServerTime = svs.time; @@ -574,41 +556,41 @@ Ghoul2 Insert End // wipe the entire per-level structure SV_ClearServer(); - for ( i = 0 ; i < MAX_CONFIGSTRINGS ; i++ ) { + for (i = 0; i < MAX_CONFIGSTRINGS; i++) { sv.configstrings[i] = CopyString(""); } - //rww - RAGDOLL_BEGIN - re->G2API_SetTime(sv.time,0); - //rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + re->G2API_SetTime(sv.time, 0); + // rww - RAGDOLL_END // make sure we are not paused Cvar_Set("cl_paused", "0"); // get a new checksum feed and restart the file system srand(Com_Milliseconds()); - sv.checksumFeed = ( ((int) rand() << 16) ^ rand() ) ^ Com_Milliseconds(); - FS_Restart( sv.checksumFeed ); + sv.checksumFeed = (((int)rand() << 16) ^ rand()) ^ Com_Milliseconds(); + FS_Restart(sv.checksumFeed); - CM_LoadMap( va("maps/%s.bsp", server), qfalse, &checksum ); + CM_LoadMap(va("maps/%s.bsp", server), qfalse, &checksum); SV_SendMapChange(); // set serverinfo visible name - Cvar_Set( "mapname", server ); + Cvar_Set("mapname", server); - Cvar_Set( "sv_mapChecksum", va("%i",checksum) ); + Cvar_Set("sv_mapChecksum", va("%i", checksum)); // serverid should be different each time sv.serverId = com_frameTime; sv.restartedServerId = sv.serverId; // I suppose the init here is just to be safe - Cvar_Set( "sv_serverid", va("%i", sv.serverId ) ); + Cvar_Set("sv_serverid", va("%i", sv.serverId)); - time( &sv.realMapTimeStarted ); + time(&sv.realMapTimeStarted); sv.demosPruned = qfalse; // clear physics interaction links - SV_ClearWorld (); + SV_ClearWorld(); // media configstring setting should be done during // the loading stage, so connected clients don't have @@ -622,112 +604,109 @@ Ghoul2 Insert End sv_gametype->modified = qfalse; // run a few frames to allow everything to settle - for ( i = 0 ;i < 3 ; i++ ) { - //rww - RAGDOLL_BEGIN - re->G2API_SetTime(sv.time,0); - //rww - RAGDOLL_END - GVM_RunFrame( sv.time ); - SV_BotFrame( sv.time ); + for (i = 0; i < 3; i++) { + // rww - RAGDOLL_BEGIN + re->G2API_SetTime(sv.time, 0); + // rww - RAGDOLL_END + GVM_RunFrame(sv.time); + SV_BotFrame(sv.time); sv.time += 100; svs.time += 100; } - //rww - RAGDOLL_BEGIN - re->G2API_SetTime(sv.time,0); - //rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + re->G2API_SetTime(sv.time, 0); + // rww - RAGDOLL_END // create a baseline for more efficient communications - SV_CreateBaseline (); + SV_CreateBaseline(); - for (i=0 ; iinteger ; i++) { + for (i = 0; i < sv_maxclients->integer; i++) { // send the new gamestate to all connected clients if (svs.clients[i].state >= CS_CONNECTED) { - char *denied; + char *denied; - if ( svs.clients[i].netchan.remoteAddress.type == NA_BOT ) { - if ( killBots ) { - SV_DropClient( &svs.clients[i], "" ); + if (svs.clients[i].netchan.remoteAddress.type == NA_BOT) { + if (killBots) { + SV_DropClient(&svs.clients[i], ""); continue; } isBot = qtrue; - } - else { + } else { isBot = qfalse; } // connect the client again - denied = GVM_ClientConnect( i, qfalse, isBot ); // firstTime = qfalse - if ( denied ) { + denied = GVM_ClientConnect(i, qfalse, isBot); // firstTime = qfalse + if (denied) { // this generally shouldn't happen, because the client // was connected before the level change - SV_DropClient( &svs.clients[i], denied ); + SV_DropClient(&svs.clients[i], denied); } else { - if( !isBot ) { + if (!isBot) { // when we get the next packet from a connected client, // the new gamestate will be sent svs.clients[i].state = CS_CONNECTED; - } - else { - client_t *client; - sharedEntity_t *ent; + } else { + client_t *client; + sharedEntity_t *ent; client = &svs.clients[i]; client->state = CS_ACTIVE; - ent = SV_GentityNum( i ); + ent = SV_GentityNum(i); ent->s.number = i; client->gentity = ent; client->deltaMessage = -1; - client->nextSnapshotTime = svs.time; // generate a snapshot immediately + client->nextSnapshotTime = svs.time; // generate a snapshot immediately - GVM_ClientBegin( i ); + GVM_ClientBegin(i); } } } } // run another frame to allow things to look at all the players - GVM_RunFrame( sv.time ); - SV_BotFrame( sv.time ); + GVM_RunFrame(sv.time); + SV_BotFrame(sv.time); sv.time += 100; svs.time += 100; - //rww - RAGDOLL_BEGIN - re->G2API_SetTime(sv.time,0); - //rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + re->G2API_SetTime(sv.time, 0); + // rww - RAGDOLL_END - if ( sv_pure->integer ) { + if (sv_pure->integer) { // the server sends these to the clients so they will only // load pk3s also loaded at the server p = FS_LoadedPakChecksums(); - Cvar_Set( "sv_paks", p ); + Cvar_Set("sv_paks", p); if (strlen(p) == 0) { - Com_Printf( "WARNING: sv_pure set but no PK3 files loaded\n" ); + Com_Printf("WARNING: sv_pure set but no PK3 files loaded\n"); } p = FS_LoadedPakNames(); - Cvar_Set( "sv_pakNames", p ); + Cvar_Set("sv_pakNames", p); // if a dedicated pure server we need to touch the cgame because it could be in a // seperate pk3 file and the client will need to load the latest cgame.qvm - if ( com_dedicated->integer ) { + if (com_dedicated->integer) { SV_TouchCGame(); } - } - else { - Cvar_Set( "sv_paks", "" ); - Cvar_Set( "sv_pakNames", "" ); + } else { + Cvar_Set("sv_paks", ""); + Cvar_Set("sv_pakNames", ""); } // the server sends these to the clients so they can figure // out which pk3s should be auto-downloaded p = FS_ReferencedPakChecksums(); - Cvar_Set( "sv_referencedPaks", p ); + Cvar_Set("sv_referencedPaks", p); p = FS_ReferencedPakNames(); - Cvar_Set( "sv_referencedPakNames", p ); + Cvar_Set("sv_referencedPakNames", p); // save systeminfo and serverinfo strings - Q_strncpyz( systemInfo, Cvar_InfoString_Big( CVAR_SYSTEMINFO ), sizeof( systemInfo ) ); + Q_strncpyz(systemInfo, Cvar_InfoString_Big(CVAR_SYSTEMINFO), sizeof(systemInfo)); cvar_modifiedFlags &= ~CVAR_SYSTEMINFO; - SV_SetConfigstring( CS_SYSTEMINFO, systemInfo ); + SV_SetConfigstring(CS_SYSTEMINFO, systemInfo); - SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) ); + SV_SetConfigstring(CS_SERVERINFO, Cvar_InfoString(CVAR_SERVERINFO)); cvar_modifiedFlags &= ~CVAR_SERVERINFO; // any media configstring setting now should issue a warning @@ -748,18 +727,17 @@ Ghoul2 Insert End } */ - for ( client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++) { + for (client_t *client = svs.clients; client - svs.clients < sv_maxclients->integer; client++) { // bots will not request gamestate, so it must be manually sent // cannot do this above where it says it will because mapname is not set at that time - if ( client->netchan.remoteAddress.type == NA_BOT && client->demo.demorecording ) { - SV_SendClientGameState( client ); + if (client->netchan.remoteAddress.type == NA_BOT && client->demo.demorecording) { + SV_SendClientGameState(client); } } SV_BeginAutoRecordDemos(); } - /* =============== SV_Init @@ -775,7 +753,6 @@ void SV_BotInitBotLib(void); IHeapAllocator *G2VertSpaceServer = NULL; CMiniHeap IHeapAllocator_singleton(G2_VERT_SPACE_SERVER_SIZE * 1024); - /* ================ CL_RefPrintf @@ -783,61 +760,59 @@ CL_RefPrintf DLL glue ================ */ -void QDECL SV_RefPrintf( int print_level, const char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; +void QDECL SV_RefPrintf(int print_level, const char *fmt, ...) { + va_list argptr; + char msg[MAXPRINTMSG]; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf(msg, sizeof(msg), fmt, argptr); - va_end (argptr); - - if ( print_level == PRINT_ALL ) { - Com_Printf ("%s", msg); - } else if ( print_level == PRINT_WARNING ) { - Com_Printf (S_COLOR_YELLOW "%s", msg); // yellow - } else if ( print_level == PRINT_DEVELOPER ) { - Com_DPrintf (S_COLOR_RED "%s", msg); // red + va_end(argptr); + + if (print_level == PRINT_ALL) { + Com_Printf("%s", msg); + } else if (print_level == PRINT_WARNING) { + Com_Printf(S_COLOR_YELLOW "%s", msg); // yellow + } else if (print_level == PRINT_DEVELOPER) { + Com_DPrintf(S_COLOR_RED "%s", msg); // red } } qboolean Com_TheHunkMarkHasBeenMade(void); -//qcommon/vm.cpp +// qcommon/vm.cpp extern vm_t *currentVM; -//qcommon/cm_load.cpp +// qcommon/cm_load.cpp extern void *gpvCachedMapDiskImage; extern qboolean gbUsingCachedMapDataRightNow; -static char *GetSharedMemory( void ) { return sv.mSharedMemory; } -static vm_t *GetCurrentVM( void ) { return currentVM; } -static void *CM_GetCachedMapDiskImage( void ) { return gpvCachedMapDiskImage; } -static void CM_SetCachedMapDiskImage( void *ptr ) { gpvCachedMapDiskImage = ptr; } -static void CM_SetUsingCache( qboolean usingCache ) { gbUsingCachedMapDataRightNow = usingCache; } +static char *GetSharedMemory(void) { return sv.mSharedMemory; } +static vm_t *GetCurrentVM(void) { return currentVM; } +static void *CM_GetCachedMapDiskImage(void) { return gpvCachedMapDiskImage; } +static void CM_SetCachedMapDiskImage(void *ptr) { gpvCachedMapDiskImage = ptr; } +static void CM_SetUsingCache(qboolean usingCache) { gbUsingCachedMapDataRightNow = usingCache; } -//server stuff D: -extern void SV_GetConfigstring( int index, char *buffer, int bufferSize ); -extern void SV_SetConfigstring( int index, const char *val ); +// server stuff D: +extern void SV_GetConfigstring(int index, char *buffer, int bufferSize); +extern void SV_SetConfigstring(int index, const char *val); -static IHeapAllocator *GetG2VertSpaceServer( void ) { - return G2VertSpaceServer; -} +static IHeapAllocator *GetG2VertSpaceServer(void) { return G2VertSpaceServer; } -refexport_t *re = NULL; +refexport_t *re = NULL; -static void SV_InitRef( void ) { +static void SV_InitRef(void) { static refimport_t ri; refexport_t *ret; - Com_Printf( "----- Initializing Renderer ----\n" ); + Com_Printf("----- Initializing Renderer ----\n"); - memset( &ri, 0, sizeof( ri ) ); + memset(&ri, 0, sizeof(ri)); - //set up the import table + // set up the import table ri.Printf = SV_RefPrintf; ri.Error = Com_Error; ri.OPrintf = Com_OPrintf; - ri.Milliseconds = Sys_Milliseconds2; //FIXME: unix+mac need this + ri.Milliseconds = Sys_Milliseconds2; // FIXME: unix+mac need this ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.Hunk_Alloc = Hunk_Alloc; @@ -875,144 +850,144 @@ static void SV_InitRef( void ) { ri.FS_WriteFile = FS_WriteFile; ri.CM_BoxTrace = CM_BoxTrace; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; -// ri.CM_CullWorldBox = CM_CullWorldBox; -// ri.CM_TerrainPatchIterate = CM_TerrainPatchIterate; -// ri.CM_RegisterTerrain = CM_RegisterTerrain; -// ri.CM_ShutdownTerrain = CM_ShutdownTerrain; + // ri.CM_CullWorldBox = CM_CullWorldBox; + // ri.CM_TerrainPatchIterate = CM_TerrainPatchIterate; + // ri.CM_RegisterTerrain = CM_RegisterTerrain; + // ri.CM_ShutdownTerrain = CM_ShutdownTerrain; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_LeafArea = CM_LeafArea; ri.CM_LeafCluster = CM_LeafCluster; ri.CM_PointLeafnum = CM_PointLeafnum; ri.CM_PointContents = CM_PointContents; ri.Com_TheHunkMarkHasBeenMade = Com_TheHunkMarkHasBeenMade; -// ri.S_RestartMusic = S_RestartMusic; -// ri.SND_RegisterAudio_LevelLoadEnd = SND_RegisterAudio_LevelLoadEnd; -// ri.CIN_RunCinematic = CIN_RunCinematic; -// ri.CIN_PlayCinematic = CIN_PlayCinematic; -// ri.CIN_UploadCinematic = CIN_UploadCinematic; -// ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; + // ri.S_RestartMusic = S_RestartMusic; + // ri.SND_RegisterAudio_LevelLoadEnd = SND_RegisterAudio_LevelLoadEnd; + // ri.CIN_RunCinematic = CIN_RunCinematic; + // ri.CIN_PlayCinematic = CIN_PlayCinematic; + // ri.CIN_UploadCinematic = CIN_UploadCinematic; + // ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; // g2 data access ri.GetSharedMemory = GetSharedMemory; // (c)g vm callbacks ri.GetCurrentVM = GetCurrentVM; -// ri.CGVMLoaded = CGVMLoaded; -// ri.CGVM_RagCallback = CGVM_RagCallback; + // ri.CGVMLoaded = CGVMLoaded; + // ri.CGVM_RagCallback = CGVM_RagCallback; // ugly win32 backend ri.CM_GetCachedMapDiskImage = CM_GetCachedMapDiskImage; ri.CM_SetCachedMapDiskImage = CM_SetCachedMapDiskImage; ri.CM_SetUsingCache = CM_SetUsingCache; - //FIXME: Might have to do something about this... + // FIXME: Might have to do something about this... ri.GetG2VertSpaceServer = GetG2VertSpaceServer; G2VertSpaceServer = &IHeapAllocator_singleton; - ret = GetRefAPI( REF_API_VERSION, &ri ); + ret = GetRefAPI(REF_API_VERSION, &ri); -// Com_Printf( "-------------------------------\n"); + // Com_Printf( "-------------------------------\n"); - if ( !ret ) { - Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); + if (!ret) { + Com_Error(ERR_FATAL, "Couldn't initialize refresh"); } re = ret; } #endif -void SV_Init (void) { +void SV_Init(void) { - time( &svs.startTime ); + time(&svs.startTime); - SV_AddOperatorCommands (); + SV_AddOperatorCommands(); // serverinfo vars - Cvar_Get ("dmflags", "0", CVAR_SERVERINFO); - Cvar_Get ("fraglimit", "20", CVAR_SERVERINFO); - Cvar_Get ("timelimit", "0", CVAR_SERVERINFO); - Cvar_Get ("capturelimit", "0", CVAR_SERVERINFO); + Cvar_Get("dmflags", "0", CVAR_SERVERINFO); + Cvar_Get("fraglimit", "20", CVAR_SERVERINFO); + Cvar_Get("timelimit", "0", CVAR_SERVERINFO); + Cvar_Get("capturelimit", "0", CVAR_SERVERINFO); // Get these to establish them and to make sure they have a default before the menus decide to stomp them. - Cvar_Get ("g_maxHolocronCarry", "3", CVAR_SERVERINFO); - Cvar_Get ("g_privateDuel", "1", CVAR_SERVERINFO ); - Cvar_Get ("g_saberLocking", "1", CVAR_SERVERINFO ); - Cvar_Get ("g_maxForceRank", "7", CVAR_SERVERINFO ); - Cvar_Get ("duel_fraglimit", "10", CVAR_SERVERINFO); - Cvar_Get ("g_forceBasedTeams", "0", CVAR_SERVERINFO); - Cvar_Get ("g_duelWeaponDisable", "1", CVAR_SERVERINFO); - - sv_gametype = Cvar_Get ("g_gametype", "0", CVAR_SERVERINFO | CVAR_LATCH, "Server gametype value" ); - sv_needpass = Cvar_Get ("g_needpass", "0", CVAR_SERVERINFO | CVAR_ROM, "Server needs password to join" ); - Cvar_Get ("sv_keywords", "", CVAR_SERVERINFO); - Cvar_Get ("protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_ROM); - sv_mapname = Cvar_Get ("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM); - sv_privateClients = Cvar_Get ("sv_privateClients", "0", CVAR_SERVERINFO, "Number of reserved client slots available with password" ); - Cvar_CheckRange( sv_privateClients, 0, MAX_CLIENTS, qtrue ); - sv_hostname = Cvar_Get ("sv_hostname", "*Jedi*", CVAR_SERVERINFO | CVAR_ARCHIVE, "The name of the server that is displayed in the serverlist" ); - sv_maxclients = Cvar_Get ("sv_maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH, "Max. connected clients" ); - - - //cvar_t *sv_ratePolicy; // 1-2 - //cvar_t *sv_clientRate; - sv_ratePolicy = Cvar_Get( "sv_ratePolicy", "1", CVAR_ARCHIVE_ND, "Determines which policy of enforcement is used for client's \"rate\" cvar" ); + Cvar_Get("g_maxHolocronCarry", "3", CVAR_SERVERINFO); + Cvar_Get("g_privateDuel", "1", CVAR_SERVERINFO); + Cvar_Get("g_saberLocking", "1", CVAR_SERVERINFO); + Cvar_Get("g_maxForceRank", "7", CVAR_SERVERINFO); + Cvar_Get("duel_fraglimit", "10", CVAR_SERVERINFO); + Cvar_Get("g_forceBasedTeams", "0", CVAR_SERVERINFO); + Cvar_Get("g_duelWeaponDisable", "1", CVAR_SERVERINFO); + + sv_gametype = Cvar_Get("g_gametype", "0", CVAR_SERVERINFO | CVAR_LATCH, "Server gametype value"); + sv_needpass = Cvar_Get("g_needpass", "0", CVAR_SERVERINFO | CVAR_ROM, "Server needs password to join"); + Cvar_Get("sv_keywords", "", CVAR_SERVERINFO); + Cvar_Get("protocol", va("%i", PROTOCOL_VERSION), CVAR_SERVERINFO | CVAR_ROM); + sv_mapname = Cvar_Get("mapname", "nomap", CVAR_SERVERINFO | CVAR_ROM); + sv_privateClients = Cvar_Get("sv_privateClients", "0", CVAR_SERVERINFO, "Number of reserved client slots available with password"); + Cvar_CheckRange(sv_privateClients, 0, MAX_CLIENTS, qtrue); + sv_hostname = Cvar_Get("sv_hostname", "*Jedi*", CVAR_SERVERINFO | CVAR_ARCHIVE, "The name of the server that is displayed in the serverlist"); + sv_maxclients = Cvar_Get("sv_maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH, "Max. connected clients"); + + // cvar_t *sv_ratePolicy; // 1-2 + // cvar_t *sv_clientRate; + sv_ratePolicy = Cvar_Get("sv_ratePolicy", "1", CVAR_ARCHIVE_ND, "Determines which policy of enforcement is used for client's \"rate\" cvar"); Cvar_CheckRange(sv_ratePolicy, 1, 2, qtrue); - sv_clientRate = Cvar_Get( "sv_clientRate", "50000", CVAR_ARCHIVE_ND); - sv_minRate = Cvar_Get ("sv_minRate", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Min bandwidth rate allowed on server. Use 0 for unlimited." ); - sv_maxRate = Cvar_Get ("sv_maxRate", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Max bandwidth rate allowed on server. Use 0 for unlimited." ); - sv_minPing = Cvar_Get ("sv_minPing", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO ); - sv_maxPing = Cvar_Get ("sv_maxPing", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO ); - sv_floodProtect = Cvar_Get ("sv_floodProtect", "1", CVAR_ARCHIVE | CVAR_SERVERINFO, "Protect against flooding of server commands" ); - sv_floodProtectSlow = Cvar_Get ("sv_floodProtectSlow", "1", CVAR_ARCHIVE | CVAR_SERVERINFO, "Use original method of delaying commands with flood protection" ); + sv_clientRate = Cvar_Get("sv_clientRate", "50000", CVAR_ARCHIVE_ND); + sv_minRate = Cvar_Get("sv_minRate", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Min bandwidth rate allowed on server. Use 0 for unlimited."); + sv_maxRate = Cvar_Get("sv_maxRate", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Max bandwidth rate allowed on server. Use 0 for unlimited."); + sv_minPing = Cvar_Get("sv_minPing", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO); + sv_maxPing = Cvar_Get("sv_maxPing", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO); + sv_floodProtect = Cvar_Get("sv_floodProtect", "1", CVAR_ARCHIVE | CVAR_SERVERINFO, "Protect against flooding of server commands"); + sv_floodProtectSlow = + Cvar_Get("sv_floodProtectSlow", "1", CVAR_ARCHIVE | CVAR_SERVERINFO, "Use original method of delaying commands with flood protection"); // systeminfo - Cvar_Get ("sv_cheats", "1", CVAR_SYSTEMINFO | CVAR_ROM, "Allow cheats on server if set to 1" ); - sv_serverid = Cvar_Get ("sv_serverid", "0", CVAR_SYSTEMINFO | CVAR_ROM ); - sv_pure = Cvar_Get ("sv_pure", "0", CVAR_SYSTEMINFO, "Pure server" ); - Cvar_Get ("sv_paks", "", CVAR_SYSTEMINFO | CVAR_ROM ); - Cvar_Get ("sv_pakNames", "", CVAR_SYSTEMINFO | CVAR_ROM ); - Cvar_Get ("sv_referencedPaks", "", CVAR_SYSTEMINFO | CVAR_ROM ); - Cvar_Get ("sv_referencedPakNames", "", CVAR_SYSTEMINFO | CVAR_ROM ); + Cvar_Get("sv_cheats", "1", CVAR_SYSTEMINFO | CVAR_ROM, "Allow cheats on server if set to 1"); + sv_serverid = Cvar_Get("sv_serverid", "0", CVAR_SYSTEMINFO | CVAR_ROM); + sv_pure = Cvar_Get("sv_pure", "0", CVAR_SYSTEMINFO, "Pure server"); + Cvar_Get("sv_paks", "", CVAR_SYSTEMINFO | CVAR_ROM); + Cvar_Get("sv_pakNames", "", CVAR_SYSTEMINFO | CVAR_ROM); + Cvar_Get("sv_referencedPaks", "", CVAR_SYSTEMINFO | CVAR_ROM); + Cvar_Get("sv_referencedPakNames", "", CVAR_SYSTEMINFO | CVAR_ROM); // server vars - sv_rconPassword = Cvar_Get ("rconPassword", "", CVAR_TEMP ); - sv_privatePassword = Cvar_Get ("sv_privatePassword", "", CVAR_TEMP ); - sv_snapsMin = Cvar_Get ("sv_snapsMin", "10", CVAR_ARCHIVE_ND ); // 1 <=> sv_snapsMax - sv_snapsMax = Cvar_Get ("sv_snapsMax", "40", CVAR_ARCHIVE_ND ); // sv_snapsMin <=> sv_fps - sv_snapsPolicy = Cvar_Get ("sv_snapsPolicy", "1", CVAR_ARCHIVE_ND, "Determines which policy of enforcement is used for client's \"snaps\" cvar"); + sv_rconPassword = Cvar_Get("rconPassword", "", CVAR_TEMP); + sv_privatePassword = Cvar_Get("sv_privatePassword", "", CVAR_TEMP); + sv_snapsMin = Cvar_Get("sv_snapsMin", "10", CVAR_ARCHIVE_ND); // 1 <=> sv_snapsMax + sv_snapsMax = Cvar_Get("sv_snapsMax", "40", CVAR_ARCHIVE_ND); // sv_snapsMin <=> sv_fps + sv_snapsPolicy = Cvar_Get("sv_snapsPolicy", "1", CVAR_ARCHIVE_ND, "Determines which policy of enforcement is used for client's \"snaps\" cvar"); Cvar_CheckRange(sv_snapsPolicy, 0, 2, qtrue); - sv_fps = Cvar_Get ("sv_fps", "40", CVAR_SERVERINFO, "Server frames per second" ); - sv_timeout = Cvar_Get ("sv_timeout", "200", CVAR_TEMP ); - sv_zombietime = Cvar_Get ("sv_zombietime", "2", CVAR_TEMP ); - Cvar_Get ("nextmap", "", CVAR_TEMP ); + sv_fps = Cvar_Get("sv_fps", "40", CVAR_SERVERINFO, "Server frames per second"); + sv_timeout = Cvar_Get("sv_timeout", "200", CVAR_TEMP); + sv_zombietime = Cvar_Get("sv_zombietime", "2", CVAR_TEMP); + Cvar_Get("nextmap", "", CVAR_TEMP); - sv_allowDownload = Cvar_Get ("sv_allowDownload", "0", CVAR_SERVERINFO, "Allow clients to download mod files via UDP from the server"); - sv_master[0] = Cvar_Get ("sv_master1", MASTER_SERVER_NAME, CVAR_PROTECTED ); - sv_master[1] = Cvar_Get ("sv_master2", JKHUB_MASTER_SERVER_NAME, CVAR_PROTECTED); - for(int index = 2; index < MAX_MASTER_SERVERS; index++) - sv_master[index] = Cvar_Get(va("sv_master%d", index + 1), "", CVAR_ARCHIVE_ND|CVAR_PROTECTED); - sv_reconnectlimit = Cvar_Get ("sv_reconnectlimit", "3", 0); - sv_showghoultraces = Cvar_Get ("sv_showghoultraces", "0", 0); - sv_showloss = Cvar_Get ("sv_showloss", "0", 0); - sv_padPackets = Cvar_Get ("sv_padPackets", "0", 0); - sv_killserver = Cvar_Get ("sv_killserver", "0", 0); - sv_mapChecksum = Cvar_Get ("sv_mapChecksum", "", CVAR_ROM); - sv_lanForceRate = Cvar_Get ("sv_lanForceRate", "1", CVAR_ARCHIVE_ND ); + sv_allowDownload = Cvar_Get("sv_allowDownload", "0", CVAR_SERVERINFO, "Allow clients to download mod files via UDP from the server"); + sv_master[0] = Cvar_Get("sv_master1", MASTER_SERVER_NAME, CVAR_PROTECTED); + sv_master[1] = Cvar_Get("sv_master2", JKHUB_MASTER_SERVER_NAME, CVAR_PROTECTED); + for (int index = 2; index < MAX_MASTER_SERVERS; index++) + sv_master[index] = Cvar_Get(va("sv_master%d", index + 1), "", CVAR_ARCHIVE_ND | CVAR_PROTECTED); + sv_reconnectlimit = Cvar_Get("sv_reconnectlimit", "3", 0); + sv_showghoultraces = Cvar_Get("sv_showghoultraces", "0", 0); + sv_showloss = Cvar_Get("sv_showloss", "0", 0); + sv_padPackets = Cvar_Get("sv_padPackets", "0", 0); + sv_killserver = Cvar_Get("sv_killserver", "0", 0); + sv_mapChecksum = Cvar_Get("sv_mapChecksum", "", CVAR_ROM); + sv_lanForceRate = Cvar_Get("sv_lanForceRate", "1", CVAR_ARCHIVE_ND); - sv_filterCommands = Cvar_Get( "sv_filterCommands", "1", CVAR_ARCHIVE ); + sv_filterCommands = Cvar_Get("sv_filterCommands", "1", CVAR_ARCHIVE); -// sv_debugserver = Cvar_Get ("sv_debugserver", "0", 0); + // sv_debugserver = Cvar_Get ("sv_debugserver", "0", 0); - sv_autoDemo = Cvar_Get( "sv_autoDemo", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Automatically take server-side demos" ); - sv_autoDemoBots = Cvar_Get( "sv_autoDemoBots", "0", CVAR_ARCHIVE_ND, "Record server-side demos for bots" ); - sv_autoDemoMaxMaps = Cvar_Get( "sv_autoDemoMaxMaps", "0", CVAR_ARCHIVE_ND ); + sv_autoDemo = Cvar_Get("sv_autoDemo", "0", CVAR_ARCHIVE_ND | CVAR_SERVERINFO, "Automatically take server-side demos"); + sv_autoDemoBots = Cvar_Get("sv_autoDemoBots", "0", CVAR_ARCHIVE_ND, "Record server-side demos for bots"); + sv_autoDemoMaxMaps = Cvar_Get("sv_autoDemoMaxMaps", "0", CVAR_ARCHIVE_ND); - sv_legacyFixes = Cvar_Get( "sv_legacyFixes", "1", CVAR_ARCHIVE ); + sv_legacyFixes = Cvar_Get("sv_legacyFixes", "1", CVAR_ARCHIVE); - sv_banFile = Cvar_Get( "sv_banFile", "serverbans.dat", CVAR_ARCHIVE, "File to use to store bans and exceptions" ); + sv_banFile = Cvar_Get("sv_banFile", "serverbans.dat", CVAR_ARCHIVE, "File to use to store bans and exceptions"); - sv_maxOOBRate = Cvar_Get("sv_maxOOBRate", "1000", CVAR_ARCHIVE, "Maximum rate of handling incoming server commands" ); - sv_maxOOBRateIP = Cvar_Get("sv_maxOOBRateIP", "1", CVAR_ARCHIVE, "Maximum rate of handling incoming server commands per IP address" ); - sv_autoWhitelist = Cvar_Get("sv_autoWhitelist", "1", CVAR_ARCHIVE, "Save player IPs to allow them using server during DOS attack" ); + sv_maxOOBRate = Cvar_Get("sv_maxOOBRate", "1000", CVAR_ARCHIVE, "Maximum rate of handling incoming server commands"); + sv_maxOOBRateIP = Cvar_Get("sv_maxOOBRateIP", "1", CVAR_ARCHIVE, "Maximum rate of handling incoming server commands per IP address"); + sv_autoWhitelist = Cvar_Get("sv_autoWhitelist", "1", CVAR_ARCHIVE, "Save player IPs to allow them using server during DOS attack"); // initialize bot cvars so they are listed and can be set before loading the botlib SV_BotInitCvars(); @@ -1033,7 +1008,6 @@ void SV_Init (void) { #endif } - /* ================== SV_FinalMessage @@ -1044,28 +1018,27 @@ not just stuck on the outgoing message list, because the server is going to totally exit after returning from this function. ================== */ -void SV_FinalMessage( char *message ) { - int i, j; - client_t *cl; +void SV_FinalMessage(char *message) { + int i, j; + client_t *cl; // send it twice, ignoring rate - for ( j = 0 ; j < 2 ; j++ ) { - for (i=0, cl = svs.clients ; i < sv_maxclients->integer ; i++, cl++) { + for (j = 0; j < 2; j++) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { if (cl->state >= CS_CONNECTED) { // don't send a disconnect to a local client - if ( cl->netchan.remoteAddress.type != NA_LOOPBACK ) { - SV_SendServerCommand( cl, "print \"%s\"", message ); - SV_SendServerCommand( cl, "disconnect" ); + if (cl->netchan.remoteAddress.type != NA_LOOPBACK) { + SV_SendServerCommand(cl, "print \"%s\"", message); + SV_SendServerCommand(cl, "disconnect"); } // force a snapshot to be sent cl->nextSnapshotTime = -1; - SV_SendClientSnapshot( cl ); + SV_SendClientSnapshot(cl); } } } } - /* ================ SV_Shutdown @@ -1074,17 +1047,15 @@ Called when each game quits, before Sys_Quit or Sys_Error ================ */ -void SV_Shutdown( char *finalmsg ) -{ - if ( !com_sv_running || !com_sv_running->integer ) - { +void SV_Shutdown(char *finalmsg) { + if (!com_sv_running || !com_sv_running->integer) { return; } -// Com_Printf( "----- Server Shutdown -----\n" ); + // Com_Printf( "----- Server Shutdown -----\n" ); - if ( svs.clients && !com_errorEntered ) { - SV_FinalMessage( finalmsg ); + if (svs.clients && !com_errorEntered) { + SV_FinalMessage(finalmsg); } SV_RemoveOperatorCommands(); @@ -1092,32 +1063,31 @@ void SV_Shutdown( char *finalmsg ) SV_ChallengeShutdown(); SV_ShutdownGameProgs(); svs.gameStarted = qfalse; -/* -Ghoul2 Insert Start -*/ - // de allocate the snapshot entities - if (svs.snapshotEntities) - { + /* + Ghoul2 Insert Start + */ + // de allocate the snapshot entities + if (svs.snapshotEntities) { delete[] svs.snapshotEntities; svs.snapshotEntities = NULL; } // free current level SV_ClearServer(); - CM_ClearMap();//jfm: add a clear here since it's commented out in clearServer. This prevents crashing cmShaderTable on exit. + CM_ClearMap(); // jfm: add a clear here since it's commented out in clearServer. This prevents crashing cmShaderTable on exit. // free server static data - if ( svs.clients ) { - Z_Free( svs.clients ); + if (svs.clients) { + Z_Free(svs.clients); } - Com_Memset( &svs, 0, sizeof( svs ) ); + Com_Memset(&svs, 0, sizeof(svs)); - Cvar_Set( "sv_running", "0" ); + Cvar_Set("sv_running", "0"); Cvar_Set("ui_singlePlayerActive", "0"); -// Com_Printf( "---------------------------\n" ); + // Com_Printf( "---------------------------\n" ); // disconnect any local clients - if( sv_killserver->integer != 2 ) - CL_Disconnect( qfalse ); + if (sv_killserver->integer != 2) + CL_Disconnect(qfalse); } diff --git a/codemp/server/sv_main.cpp b/codemp/server/sv_main.cpp index 1bb2f7daf6..0b6766035c 100644 --- a/codemp/server/sv_main.cpp +++ b/codemp/server/sv_main.cpp @@ -27,51 +27,51 @@ along with this program; if not, see . #include "ghoul2/ghoul2_shared.h" #include "sv_gameapi.h" -serverStatic_t svs; // persistant server info -server_t sv; // local server - -cvar_t *sv_snapsMin; // minimum snapshots/sec a client can request, also limited by sv_snapsMax -cvar_t *sv_snapsMax; // maximum snapshots/sec a client can request, also limited by sv_fps -cvar_t *sv_snapsPolicy; // 0-2 -cvar_t *sv_fps = NULL; // time rate for running non-clients -cvar_t *sv_timeout; // seconds without any message -cvar_t *sv_zombietime; // seconds to sink messages after disconnect -cvar_t *sv_rconPassword; // password for remote server commands -cvar_t *sv_privatePassword; // password for the privateClient slots -cvar_t *sv_maxclients; -cvar_t *sv_privateClients; // number of clients reserved for password -cvar_t *sv_hostname; -cvar_t *sv_allowDownload; -cvar_t *sv_master[MAX_MASTER_SERVERS]; // master server ip address -cvar_t *sv_reconnectlimit; // minimum seconds between connect messages -cvar_t *sv_showghoultraces; // report ghoul2 traces -cvar_t *sv_showloss; // report when usercmds are lost -cvar_t *sv_padPackets; // add nop bytes to messages -cvar_t *sv_killserver; // menu system can set to 1 to shut server down -cvar_t *sv_mapname; -cvar_t *sv_mapChecksum; -cvar_t *sv_serverid; -cvar_t *sv_ratePolicy; // 1-2 -cvar_t *sv_clientRate; -cvar_t *sv_minRate; -cvar_t *sv_maxRate; -cvar_t *sv_minPing; -cvar_t *sv_maxPing; -cvar_t *sv_gametype; -cvar_t *sv_pure; -cvar_t *sv_floodProtect; -cvar_t *sv_floodProtectSlow; -cvar_t *sv_lanForceRate; // dedicated 1 (LAN) server forces local client rates to 99999 (bug #491) -cvar_t *sv_needpass; -cvar_t *sv_filterCommands; // strict filtering on commands (1: strip ['\r', '\n'], 2: also strip ';') -cvar_t *sv_autoDemo; -cvar_t *sv_autoDemoBots; -cvar_t *sv_autoDemoMaxMaps; -cvar_t *sv_legacyFixes; -cvar_t *sv_banFile; -cvar_t *sv_maxOOBRate; -cvar_t *sv_maxOOBRateIP; -cvar_t *sv_autoWhitelist; +serverStatic_t svs; // persistant server info +server_t sv; // local server + +cvar_t *sv_snapsMin; // minimum snapshots/sec a client can request, also limited by sv_snapsMax +cvar_t *sv_snapsMax; // maximum snapshots/sec a client can request, also limited by sv_fps +cvar_t *sv_snapsPolicy; // 0-2 +cvar_t *sv_fps = NULL; // time rate for running non-clients +cvar_t *sv_timeout; // seconds without any message +cvar_t *sv_zombietime; // seconds to sink messages after disconnect +cvar_t *sv_rconPassword; // password for remote server commands +cvar_t *sv_privatePassword; // password for the privateClient slots +cvar_t *sv_maxclients; +cvar_t *sv_privateClients; // number of clients reserved for password +cvar_t *sv_hostname; +cvar_t *sv_allowDownload; +cvar_t *sv_master[MAX_MASTER_SERVERS]; // master server ip address +cvar_t *sv_reconnectlimit; // minimum seconds between connect messages +cvar_t *sv_showghoultraces; // report ghoul2 traces +cvar_t *sv_showloss; // report when usercmds are lost +cvar_t *sv_padPackets; // add nop bytes to messages +cvar_t *sv_killserver; // menu system can set to 1 to shut server down +cvar_t *sv_mapname; +cvar_t *sv_mapChecksum; +cvar_t *sv_serverid; +cvar_t *sv_ratePolicy; // 1-2 +cvar_t *sv_clientRate; +cvar_t *sv_minRate; +cvar_t *sv_maxRate; +cvar_t *sv_minPing; +cvar_t *sv_maxPing; +cvar_t *sv_gametype; +cvar_t *sv_pure; +cvar_t *sv_floodProtect; +cvar_t *sv_floodProtectSlow; +cvar_t *sv_lanForceRate; // dedicated 1 (LAN) server forces local client rates to 99999 (bug #491) +cvar_t *sv_needpass; +cvar_t *sv_filterCommands; // strict filtering on commands (1: strip ['\r', '\n'], 2: also strip ';') +cvar_t *sv_autoDemo; +cvar_t *sv_autoDemoBots; +cvar_t *sv_autoDemoMaxMaps; +cvar_t *sv_legacyFixes; +cvar_t *sv_banFile; +cvar_t *sv_maxOOBRate; +cvar_t *sv_maxOOBRateIP; +cvar_t *sv_autoWhitelist; serverBan_t serverBans[SERVER_MAXBANS]; int serverBansCount = 0; @@ -91,13 +91,13 @@ SV_ExpandNewlines Converts newlines to "\n" so a line prints nicer =============== */ -char *SV_ExpandNewlines( char *in ) { - static char string[1024]; - size_t l; +char *SV_ExpandNewlines(char *in) { + static char string[1024]; + size_t l; l = 0; - while ( *in && l < sizeof(string) - 3 ) { - if ( *in == '\n' ) { + while (*in && l < sizeof(string) - 3) { + if (*in == '\n') { string[l++] = '\\'; string[l++] = 'n'; } else { @@ -118,11 +118,11 @@ The given command will be transmitted to the client, and is guaranteed to not have future snapshot_t executed before it is executed ====================== */ -void SV_AddServerCommand( client_t *client, const char *cmd ) { - int index, i; +void SV_AddServerCommand(client_t *client, const char *cmd) { + int index, i; // do not send commands until the gamestate has been sent - if ( client->state < CS_PRIMED ) { + if (client->state < CS_PRIMED) { return; } @@ -131,20 +131,19 @@ void SV_AddServerCommand( client_t *client, const char *cmd ) { // we must drop the connection // we check == instead of >= so a broadcast print added by SV_DropClient() // doesn't cause a recursive drop client - if ( client->reliableSequence - client->reliableAcknowledge == MAX_RELIABLE_COMMANDS + 1 ) { - Com_Printf( "===== pending server commands =====\n" ); - for ( i = client->reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) { - Com_Printf( "cmd %5d: %s\n", i, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] ); + if (client->reliableSequence - client->reliableAcknowledge == MAX_RELIABLE_COMMANDS + 1) { + Com_Printf("===== pending server commands =====\n"); + for (i = client->reliableAcknowledge + 1; i <= client->reliableSequence; i++) { + Com_Printf("cmd %5d: %s\n", i, client->reliableCommands[i & (MAX_RELIABLE_COMMANDS - 1)]); } - Com_Printf( "cmd %5d: %s\n", i, cmd ); - SV_DropClient( client, "Server command overflow" ); + Com_Printf("cmd %5d: %s\n", i, cmd); + SV_DropClient(client, "Server command overflow"); return; } - index = client->reliableSequence & ( MAX_RELIABLE_COMMANDS - 1 ); - Q_strncpyz( client->reliableCommands[ index ], cmd, sizeof( client->reliableCommands[ index ] ) ); + index = client->reliableSequence & (MAX_RELIABLE_COMMANDS - 1); + Q_strncpyz(client->reliableCommands[index], cmd, sizeof(client->reliableCommands[index])); } - /* ================= SV_SendServerCommand @@ -155,40 +154,39 @@ A NULL client will broadcast to all clients ================= */ void QDECL SV_SendServerCommand(client_t *cl, const char *fmt, ...) { - va_list argptr; - byte message[MAX_MSGLEN]; - client_t *client; - int j; + va_list argptr; + byte message[MAX_MSGLEN]; + client_t *client; + int j; - va_start (argptr,fmt); + va_start(argptr, fmt); Q_vsnprintf((char *)message, sizeof(message), fmt, argptr); - va_end (argptr); + va_end(argptr); // Fix to http://aluigi.altervista.org/adv/q3msgboom-adv.txt // The actual cause of the bug is probably further downstream // and should maybe be addressed later, but this certainly // fixes the problem for now - if ( strlen ((char *)message) > 1022 ) { + if (strlen((char *)message) > 1022) { return; } - if ( cl != NULL ) { - SV_AddServerCommand( cl, (char *)message ); + if (cl != NULL) { + SV_AddServerCommand(cl, (char *)message); return; } // hack to echo broadcast prints to console - if ( com_dedicated->integer && !Q_strncmp( (char *)message, "print", 5) ) { - Com_Printf ("broadcast: %s\n", SV_ExpandNewlines((char *)message) ); + if (com_dedicated->integer && !Q_strncmp((char *)message, "print", 5)) { + Com_Printf("broadcast: %s\n", SV_ExpandNewlines((char *)message)); } // send the data to all relevent clients - for (j = 0, client = svs.clients; j < sv_maxclients->integer ; j++, client++) { - SV_AddServerCommand( client, (char *)message ); + for (j = 0, client = svs.clients; j < sv_maxclients->integer; j++, client++) { + SV_AddServerCommand(client, (char *)message); } } - /* ============================================================================== @@ -196,18 +194,15 @@ MASTER SERVER FUNCTIONS ============================================================================== */ -#define NEW_RESOLVE_DURATION 86400000 //24 hours +#define NEW_RESOLVE_DURATION 86400000 // 24 hours static int g_lastResolveTime[MAX_MASTER_SERVERS]; -static inline bool SV_MasterNeedsResolving(int server, int time) -{ //refresh every so often regardless of if the actual address was modified -rww - if (g_lastResolveTime[server] > time) - { //time flowed backwards? +static inline bool SV_MasterNeedsResolving(int server, int time) { // refresh every so often regardless of if the actual address was modified -rww + if (g_lastResolveTime[server] > time) { // time flowed backwards? return true; } - if ((time-g_lastResolveTime[server]) > NEW_RESOLVE_DURATION) - { //it's time again + if ((time - g_lastResolveTime[server]) > NEW_RESOLVE_DURATION) { // it's time again return true; } @@ -225,63 +220,63 @@ changes from empty to non-empty, and full to non-full, but not on every player enter or exit. ================ */ -#define HEARTBEAT_MSEC 300*1000 -#define HEARTBEAT_GAME "QuakeArena-1" -void SV_MasterHeartbeat( void ) { - static netadr_t adr[MAX_MASTER_SERVERS]; - int i; - int time; +#define HEARTBEAT_MSEC 300 * 1000 +#define HEARTBEAT_GAME "QuakeArena-1" +void SV_MasterHeartbeat(void) { + static netadr_t adr[MAX_MASTER_SERVERS]; + int i; + int time; // "dedicated 1" is for lan play, "dedicated 2" is for inet public play - if ( !com_dedicated || com_dedicated->integer != 2 ) { - return; // only dedicated servers send heartbeats + if (!com_dedicated || com_dedicated->integer != 2) { + return; // only dedicated servers send heartbeats } // if not time yet, don't send anything - if ( svs.time < svs.nextHeartbeatTime ) { + if (svs.time < svs.nextHeartbeatTime) { return; } svs.nextHeartbeatTime = svs.time + HEARTBEAT_MSEC; - //we need to use this instead of svs.time since svs.time resets over map changes (or rather - //every time the game restarts), and we don't really need to resolve every map change + // we need to use this instead of svs.time since svs.time resets over map changes (or rather + // every time the game restarts), and we don't really need to resolve every map change time = Com_Milliseconds(); // send to group masters - for ( i = 0 ; i < MAX_MASTER_SERVERS ; i++ ) { - if ( !sv_master[i]->string[0] ) { + for (i = 0; i < MAX_MASTER_SERVERS; i++) { + if (!sv_master[i]->string[0]) { continue; } // see if we haven't already resolved the name // resolving usually causes hitches on win95, so only // do it when needed - if ( sv_master[i]->modified || SV_MasterNeedsResolving(i, time) ) { + if (sv_master[i]->modified || SV_MasterNeedsResolving(i, time)) { sv_master[i]->modified = qfalse; g_lastResolveTime[i] = time; - Com_Printf( "Resolving %s\n", sv_master[i]->string ); - if ( !NET_StringToAdr( sv_master[i]->string, &adr[i] ) ) { + Com_Printf("Resolving %s\n", sv_master[i]->string); + if (!NET_StringToAdr(sv_master[i]->string, &adr[i])) { // if the address failed to resolve, clear it // so we don't take repeated dns hits - Com_Printf( "Couldn't resolve address: %s\n", sv_master[i]->string ); - Cvar_Set( sv_master[i]->name, "" ); + Com_Printf("Couldn't resolve address: %s\n", sv_master[i]->string); + Cvar_Set(sv_master[i]->name, ""); sv_master[i]->modified = qfalse; continue; } - if ( !strstr( ":", sv_master[i]->string ) ) { - adr[i].port = BigShort( PORT_MASTER ); + if (!strstr(":", sv_master[i]->string)) { + adr[i].port = BigShort(PORT_MASTER); } - Com_Printf( "%s resolved to %s\n", sv_master[i]->string, NET_AdrToString(adr[i]) ); + Com_Printf("%s resolved to %s\n", sv_master[i]->string, NET_AdrToString(adr[i])); - SVC_WhitelistAdr( adr[i] ); + SVC_WhitelistAdr(adr[i]); } - Com_Printf ("Sending heartbeat to %s\n", sv_master[i]->string ); + Com_Printf("Sending heartbeat to %s\n", sv_master[i]->string); // this command should be changed if the server info / status format // ever incompatably changes - NET_OutOfBandPrint( NS_SERVER, adr[i], "heartbeat %s\n", HEARTBEAT_GAME ); + NET_OutOfBandPrint(NS_SERVER, adr[i], "heartbeat %s\n", HEARTBEAT_GAME); } } @@ -292,7 +287,7 @@ SV_MasterShutdown Informs all masters that this server is going down ================= */ -void SV_MasterShutdown( void ) { +void SV_MasterShutdown(void) { // send a hearbeat right now svs.nextHeartbeatTime = -9999; SV_MasterHeartbeat(); @@ -305,7 +300,6 @@ void SV_MasterShutdown( void ) { // it will be removed from the list } - /* ============================================================================== @@ -323,7 +317,7 @@ Find or allocate a bucket for an address */ #include -static leakyBucket_t *SVC_BucketForAddress( netadr_t address, int burst, int period, int now ) { +static leakyBucket_t *SVC_BucketForAddress(netadr_t address, int burst, int period, int now) { static std::map bucketMap; static int lastGC = 0; @@ -369,15 +363,15 @@ static leakyBucket_t *SVC_BucketForAddress( netadr_t address, int burst, int per SVC_RateLimit ================ */ -qboolean SVC_RateLimit( leakyBucket_t *bucket, int burst, int period, int now ) { - qboolean block = qfalse; +qboolean SVC_RateLimit(leakyBucket_t *bucket, int burst, int period, int now) { + qboolean block = qfalse; - if ( bucket != NULL ) { + if (bucket != NULL) { int interval = now - bucket->lastTime; int expired = interval / period; int expiredRemainder = interval % period; - if ( expired > bucket->burst || interval < 0 ) { + if (expired > bucket->burst || interval < 0) { bucket->burst = 0; bucket->lastTime = now; } else { @@ -385,7 +379,7 @@ qboolean SVC_RateLimit( leakyBucket_t *bucket, int burst, int period, int now ) bucket->lastTime = now - expiredRemainder; } - if ( bucket->burst < burst ) { + if (bucket->burst < burst) { bucket->burst++; } else { block = qtrue; @@ -402,10 +396,10 @@ SVC_RateLimitAddress Rate limit for a particular address ================ */ -qboolean SVC_RateLimitAddress( netadr_t from, int burst, int period, int now ) { - leakyBucket_t *bucket = SVC_BucketForAddress( from, burst, period, now ); +qboolean SVC_RateLimitAddress(netadr_t from, int burst, int period, int now) { + leakyBucket_t *bucket = SVC_BucketForAddress(from, burst, period, now); - return SVC_RateLimit( bucket, burst, period, now ); + return SVC_RateLimit(bucket, burst, period, now); } /* @@ -417,15 +411,15 @@ and all connected players. Used for getting detailed information after the simple info query. ================ */ -void SVC_Status( netadr_t from ) { - char player[1024]; - char status[MAX_MSGLEN]; - int i; - client_t *cl; - playerState_t *ps; - int statusLength; - int playerLength; - char infostring[MAX_INFO_STRING]; +void SVC_Status(netadr_t from) { + char player[1024]; + char status[MAX_MSGLEN]; + int i; + client_t *cl; + playerState_t *ps; + int statusLength; + int playerLength; + char infostring[MAX_INFO_STRING]; // ignore if we are in single player /* @@ -435,34 +429,33 @@ void SVC_Status( netadr_t from ) { */ // A maximum challenge length of 128 should be more than plenty. - if(strlen(Cmd_Argv(1)) > 128) + if (strlen(Cmd_Argv(1)) > 128) return; - Q_strncpyz( infostring, Cvar_InfoString( CVAR_SERVERINFO ), sizeof( infostring ) ); + Q_strncpyz(infostring, Cvar_InfoString(CVAR_SERVERINFO), sizeof(infostring)); // echo back the parameter to status. so master servers can use it as a challenge // to prevent timed spoofed reply packets that add ghost servers - Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) ); + Info_SetValueForKey(infostring, "challenge", Cmd_Argv(1)); status[0] = 0; statusLength = 0; - for (i=0 ; i < sv_maxclients->integer ; i++) { + for (i = 0; i < sv_maxclients->integer; i++) { cl = &svs.clients[i]; - if ( cl->state >= CS_CONNECTED ) { - ps = SV_GameClientNum( i ); - Com_sprintf (player, sizeof(player), "%i %i \"%s\"\n", - ps->persistant[PERS_SCORE], cl->ping, cl->name); + if (cl->state >= CS_CONNECTED) { + ps = SV_GameClientNum(i); + Com_sprintf(player, sizeof(player), "%i %i \"%s\"\n", ps->persistant[PERS_SCORE], cl->ping, cl->name); playerLength = strlen(player); - if (statusLength + playerLength >= (int)sizeof(status) ) { - break; // can't hold any more + if (statusLength + playerLength >= (int)sizeof(status)) { + break; // can't hold any more } - strcpy (status + statusLength, player); + strcpy(status + statusLength, player); statusLength += playerLength; } } - NET_OutOfBandPrint( NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status ); + NET_OutOfBandPrint(NS_SERVER, from, "statusResponse\n%s\n%s", infostring, status); } /* @@ -473,10 +466,10 @@ Responds with a short info message that should be enough to determine if a user is interested in a server to do a full status ================ */ -void SVC_Info( netadr_t from ) { - int i, count, humans, wDisable; - char *gamedir; - char infostring[MAX_INFO_STRING]; +void SVC_Info(netadr_t from) { + int i, count, humans, wDisable; + char *gamedir; + char infostring[MAX_INFO_STRING]; // ignore if we are in single player /* @@ -485,8 +478,7 @@ void SVC_Info( netadr_t from ) { } */ - if (Cvar_VariableValue("ui_singlePlayerActive")) - { + if (Cvar_VariableValue("ui_singlePlayerActive")) { return; } @@ -496,15 +488,15 @@ void SVC_Info( netadr_t from ) { */ // A maximum challenge length of 128 should be more than plenty. - if(strlen(Cmd_Argv(1)) > 128) + if (strlen(Cmd_Argv(1)) > 128) return; // don't count privateclients count = humans = 0; - for ( i = sv_privateClients->integer ; i < sv_maxclients->integer ; i++ ) { - if ( svs.clients[i].state >= CS_CONNECTED ) { + for (i = sv_privateClients->integer; i < sv_maxclients->integer; i++) { + if (svs.clients[i].state >= CS_CONNECTED) { count++; - if ( svs.clients[i].netchan.remoteAddress.type != NA_BOT ) { + if (svs.clients[i].netchan.remoteAddress.type != NA_BOT) { humans++; } } @@ -514,43 +506,39 @@ void SVC_Info( netadr_t from ) { // echo back the parameter to status. so servers can use it as a challenge // to prevent timed spoofed reply packets that add ghost servers - Info_SetValueForKey( infostring, "challenge", Cmd_Argv(1) ); - - Info_SetValueForKey( infostring, "protocol", va("%i", PROTOCOL_VERSION) ); - Info_SetValueForKey( infostring, "hostname", sv_hostname->string ); - Info_SetValueForKey( infostring, "mapname", sv_mapname->string ); - Info_SetValueForKey( infostring, "clients", va("%i", count) ); - Info_SetValueForKey( infostring, "g_humanplayers", va("%i", humans) ); - Info_SetValueForKey( infostring, "sv_maxclients", - va("%i", sv_maxclients->integer - sv_privateClients->integer ) ); - Info_SetValueForKey( infostring, "gametype", va("%i", sv_gametype->integer ) ); - Info_SetValueForKey( infostring, "needpass", va("%i", sv_needpass->integer ) ); - Info_SetValueForKey( infostring, "truejedi", va("%i", Cvar_VariableIntegerValue( "g_jediVmerc" ) ) ); - if ( sv_gametype->integer == GT_DUEL || sv_gametype->integer == GT_POWERDUEL ) - { - wDisable = Cvar_VariableIntegerValue( "g_duelWeaponDisable" ); - } - else - { - wDisable = Cvar_VariableIntegerValue( "g_weaponDisable" ); + Info_SetValueForKey(infostring, "challenge", Cmd_Argv(1)); + + Info_SetValueForKey(infostring, "protocol", va("%i", PROTOCOL_VERSION)); + Info_SetValueForKey(infostring, "hostname", sv_hostname->string); + Info_SetValueForKey(infostring, "mapname", sv_mapname->string); + Info_SetValueForKey(infostring, "clients", va("%i", count)); + Info_SetValueForKey(infostring, "g_humanplayers", va("%i", humans)); + Info_SetValueForKey(infostring, "sv_maxclients", va("%i", sv_maxclients->integer - sv_privateClients->integer)); + Info_SetValueForKey(infostring, "gametype", va("%i", sv_gametype->integer)); + Info_SetValueForKey(infostring, "needpass", va("%i", sv_needpass->integer)); + Info_SetValueForKey(infostring, "truejedi", va("%i", Cvar_VariableIntegerValue("g_jediVmerc"))); + if (sv_gametype->integer == GT_DUEL || sv_gametype->integer == GT_POWERDUEL) { + wDisable = Cvar_VariableIntegerValue("g_duelWeaponDisable"); + } else { + wDisable = Cvar_VariableIntegerValue("g_weaponDisable"); } - Info_SetValueForKey( infostring, "wdisable", va("%i", wDisable ) ); - Info_SetValueForKey( infostring, "fdisable", va("%i", Cvar_VariableIntegerValue( "g_forcePowerDisable" ) ) ); - //Info_SetValueForKey( infostring, "pure", va("%i", sv_pure->integer ) ); - Info_SetValueForKey( infostring, "autodemo", va("%i", sv_autoDemo->integer ) ); + Info_SetValueForKey(infostring, "wdisable", va("%i", wDisable)); + Info_SetValueForKey(infostring, "fdisable", va("%i", Cvar_VariableIntegerValue("g_forcePowerDisable"))); + // Info_SetValueForKey( infostring, "pure", va("%i", sv_pure->integer ) ); + Info_SetValueForKey(infostring, "autodemo", va("%i", sv_autoDemo->integer)); - if( sv_minPing->integer ) { - Info_SetValueForKey( infostring, "minPing", va("%i", sv_minPing->integer) ); + if (sv_minPing->integer) { + Info_SetValueForKey(infostring, "minPing", va("%i", sv_minPing->integer)); } - if( sv_maxPing->integer ) { - Info_SetValueForKey( infostring, "maxPing", va("%i", sv_maxPing->integer) ); + if (sv_maxPing->integer) { + Info_SetValueForKey(infostring, "maxPing", va("%i", sv_maxPing->integer)); } - gamedir = Cvar_VariableString( "fs_game" ); - if( *gamedir ) { - Info_SetValueForKey( infostring, "game", gamedir ); + gamedir = Cvar_VariableString("fs_game"); + if (*gamedir) { + Info_SetValueForKey(infostring, "game", gamedir); } - NET_OutOfBandPrint( NS_SERVER, from, "infoResponse\n%s", infostring ); + NET_OutOfBandPrint(NS_SERVER, from, "infoResponse\n%s", infostring); } /* @@ -559,9 +547,7 @@ SVC_FlushRedirect ================ */ -void SV_FlushRedirect( char *outputbuf ) { - NET_OutOfBandPrint( NS_SERVER, svs.redirectAddress, "print\n%s", outputbuf ); -} +void SV_FlushRedirect(char *outputbuf) { NET_OutOfBandPrint(NS_SERVER, svs.redirectAddress, "print\n%s", outputbuf); } /* =============== @@ -572,32 +558,31 @@ Shift down the remaining args Redirect all printfs =============== */ -void SVC_RemoteCommand( netadr_t from, msg_t *msg ) { - qboolean valid; - char remaining[1024]; +void SVC_RemoteCommand(netadr_t from, msg_t *msg) { + qboolean valid; + char remaining[1024]; // TTimo - scaled down to accumulate, but not overflow anything network wise, print wise etc. // (OOB messages are the bottleneck here) -#define SV_OUTPUTBUF_LENGTH (1024 - 16) - char sv_outputbuf[SV_OUTPUTBUF_LENGTH]; - char *cmd_aux; +#define SV_OUTPUTBUF_LENGTH (1024 - 16) + char sv_outputbuf[SV_OUTPUTBUF_LENGTH]; + char *cmd_aux; - if ( !strlen( sv_rconPassword->string ) || - strcmp (Cmd_Argv(1), sv_rconPassword->string) ) { + if (!strlen(sv_rconPassword->string) || strcmp(Cmd_Argv(1), sv_rconPassword->string)) { valid = qfalse; - Com_Printf ("Bad rcon from %s: %s\n", NET_AdrToString (from), Cmd_ArgsFrom(2) ); + Com_Printf("Bad rcon from %s: %s\n", NET_AdrToString(from), Cmd_ArgsFrom(2)); } else { valid = qtrue; - Com_Printf ("Rcon from %s: %s\n", NET_AdrToString (from), Cmd_ArgsFrom(2) ); + Com_Printf("Rcon from %s: %s\n", NET_AdrToString(from), Cmd_ArgsFrom(2)); } // start redirecting all print outputs to the packet svs.redirectAddress = from; - Com_BeginRedirect (sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect); + Com_BeginRedirect(sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect); - if ( !strlen( sv_rconPassword->string ) ) { - Com_Printf ("No rconpassword set.\n"); - } else if ( !valid ) { - Com_Printf ("Bad rconpassword.\n"); + if (!strlen(sv_rconPassword->string)) { + Com_Printf("No rconpassword set.\n"); + } else if (!valid) { + Com_Printf("Bad rconpassword.\n"); } else { remaining[0] = 0; @@ -606,31 +591,31 @@ void SVC_RemoteCommand( netadr_t from, msg_t *msg ) { // extract the command by walking // since the cmd formatting can fuckup (amount of spaces), using a dumb step by step parsing cmd_aux = Cmd_Cmd(); - cmd_aux+=4; - while(cmd_aux[0]==' ') + cmd_aux += 4; + while (cmd_aux[0] == ' ') cmd_aux++; - while(cmd_aux[0] && cmd_aux[0]!=' ') // password + while (cmd_aux[0] && cmd_aux[0] != ' ') // password cmd_aux++; - while(cmd_aux[0]==' ') + while (cmd_aux[0] == ' ') cmd_aux++; - Q_strcat( remaining, sizeof(remaining), cmd_aux); + Q_strcat(remaining, sizeof(remaining), cmd_aux); - Cmd_ExecuteString (remaining); + Cmd_ExecuteString(remaining); } - Com_EndRedirect (); + Com_EndRedirect(); } // dos protection whitelist -#define WHITELIST_FILE "ipwhitelist.dat" +#define WHITELIST_FILE "ipwhitelist.dat" #include -static std::set svc_whitelist; +static std::set svc_whitelist; -void SVC_LoadWhitelist( void ) { +void SVC_LoadWhitelist(void) { fileHandle_t f; int32_t *data = NULL; int len = FS_SV_FOpenFileRead(WHITELIST_FILE, &f); @@ -654,7 +639,7 @@ void SVC_LoadWhitelist( void ) { data = NULL; } -void SVC_WhitelistAdr( netadr_t adr ) { +void SVC_WhitelistAdr(netadr_t adr) { fileHandle_t f; if (adr.type != NA_IP) { @@ -677,7 +662,7 @@ void SVC_WhitelistAdr( netadr_t adr ) { FS_FCloseFile(f); } -static qboolean SVC_IsWhitelisted( netadr_t adr ) { +static qboolean SVC_IsWhitelisted(netadr_t adr) { if (adr.type == NA_IP) { return (qboolean)(svc_whitelist.find(adr.ipi) != svc_whitelist.end()); } else { @@ -695,13 +680,13 @@ Clients that are in the game can still send connectionless packets. ================= */ -void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) { - static leakyBucket_t bucket; - static int dropped = 0; - static int lastMsg = 0; - int now = Sys_Milliseconds(); - char *s; - char *c; +void SV_ConnectionlessPacket(netadr_t from, msg_t *msg) { + static leakyBucket_t bucket; + static int dropped = 0; + static int lastMsg = 0; + int now = Sys_Milliseconds(); + char *s; + char *c; if (sv_maxOOBRateIP->integer) { int rate = Com_Clampi(1, 1000, sv_maxOOBRateIP->integer); @@ -736,46 +721,44 @@ void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) { lastMsg = now; } - MSG_BeginReadingOOB( msg ); - MSG_ReadLong( msg ); // skip the -1 marker + MSG_BeginReadingOOB(msg); + MSG_ReadLong(msg); // skip the -1 marker if (!Q_strncmp("connect", (const char *)&msg->data[4], 7)) { Huff_Decompress(msg, 12); } - s = MSG_ReadStringLine( msg ); - Cmd_TokenizeString( s ); + s = MSG_ReadStringLine(msg); + Cmd_TokenizeString(s); c = Cmd_Argv(0); - if ( com_developer->integer ) { - Com_Printf( "SV packet %s : %s\n", NET_AdrToString( from ), c ); + if (com_developer->integer) { + Com_Printf("SV packet %s : %s\n", NET_AdrToString(from), c); } if (!Q_stricmp(c, "getstatus")) { - SVC_Status( from ); + SVC_Status(from); } else if (!Q_stricmp(c, "getinfo")) { - SVC_Info( from ); + SVC_Info(from); } else if (!Q_stricmp(c, "getchallenge")) { - SV_GetChallenge( from ); + SV_GetChallenge(from); } else if (!Q_stricmp(c, "connect")) { - SV_DirectConnect( from ); + SV_DirectConnect(from); } else if (!Q_stricmp(c, "ipAuthorize")) { // ... } else if (!Q_stricmp(c, "rcon")) { - SVC_RemoteCommand( from, msg ); + SVC_RemoteCommand(from, msg); } else if (!Q_stricmp(c, "disconnect")) { // if a client starts up a local server, we may see some spurious // server disconnect messages when their new server sees our final // sequenced messages to the old client } else { - if ( com_developer->integer ) { - Com_Printf( "bad connectionless packet from %s:\n%s\n", - NET_AdrToString( from ), s ); + if (com_developer->integer) { + Com_Printf("bad connectionless packet from %s:\n%s\n", NET_AdrToString(from), s); } } } - //============================================================================ /* @@ -783,29 +766,29 @@ void SV_ConnectionlessPacket( netadr_t from, msg_t *msg ) { SV_ReadPackets ================= */ -void SV_PacketEvent( netadr_t from, msg_t *msg ) { - int i; - client_t *cl; - int qport; +void SV_PacketEvent(netadr_t from, msg_t *msg) { + int i; + client_t *cl; + int qport; // check for connectionless packet (0xffffffff) first - if ( msg->cursize >= 4 && *(int *)msg->data == -1) { - SV_ConnectionlessPacket( from, msg ); + if (msg->cursize >= 4 && *(int *)msg->data == -1) { + SV_ConnectionlessPacket(from, msg); return; } // read the qport out of the message so we can fix up // stupid address translating routers - MSG_BeginReadingOOB( msg ); - MSG_ReadLong( msg ); // sequence number - qport = MSG_ReadShort( msg ) & 0xffff; + MSG_BeginReadingOOB(msg); + MSG_ReadLong(msg); // sequence number + qport = MSG_ReadShort(msg) & 0xffff; // find which client the message is from - for (i=0, cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { if (cl->state == CS_FREE) { continue; } - if ( !NET_CompareBaseAdr( from, cl->netchan.remoteAddress ) ) { + if (!NET_CompareBaseAdr(from, cl->netchan.remoteAddress)) { continue; } // it is possible to have multiple clients from a single IP @@ -818,7 +801,7 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // some address translating routers periodically change UDP // port assignments if (cl->netchan.remoteAddress.port != from.port) { - Com_Printf( "SV_ReadPackets: fixing up a translated port\n" ); + Com_Printf("SV_ReadPackets: fixing up a translated port\n"); cl->netchan.remoteAddress.port = from.port; } @@ -828,8 +811,8 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // to make sure they don't need to retransmit the final // reliable message, but they don't do any other processing if (cl->state != CS_ZOMBIE) { - cl->lastPacketTime = svs.time; // don't timeout - SV_ExecuteClientMessage( cl, msg ); + cl->lastPacketTime = svs.time; // don't timeout + SV_ExecuteClientMessage(cl, msg); } } return; @@ -837,10 +820,9 @@ void SV_PacketEvent( netadr_t from, msg_t *msg ) { // if we received a sequenced packet from an address we don't recognize, // send an out of band disconnect packet to it - NET_OutOfBandPrint( NS_SERVER, from, "disconnect" ); + NET_OutOfBandPrint(NS_SERVER, from, "disconnect"); } - /* =================== SV_CalcPings @@ -848,32 +830,32 @@ SV_CalcPings Updates the cl->ping variables =================== */ -void SV_CalcPings( void ) { - int i, j; - client_t *cl; - int total, count; - int delta; - playerState_t *ps; - - for (i=0 ; i < sv_maxclients->integer ; i++) { +void SV_CalcPings(void) { + int i, j; + client_t *cl; + int total, count; + int delta; + playerState_t *ps; + + for (i = 0; i < sv_maxclients->integer; i++) { cl = &svs.clients[i]; - if ( cl->state != CS_ACTIVE ) { + if (cl->state != CS_ACTIVE) { cl->ping = 999; continue; } - if ( !cl->gentity ) { + if (!cl->gentity) { cl->ping = 999; continue; } - if ( cl->gentity->r.svFlags & SVF_BOT ) { + if (cl->gentity->r.svFlags & SVF_BOT) { cl->ping = 0; continue; } total = 0; count = 0; - for ( j = 0 ; j < PACKET_BACKUP ; j++ ) { - if ( cl->frames[j].messageAcked <= 0 ) { + for (j = 0; j < PACKET_BACKUP; j++) { + if (cl->frames[j].messageAcked <= 0) { continue; } delta = cl->frames[j].messageAcked - cl->frames[j].messageSent; @@ -883,14 +865,14 @@ void SV_CalcPings( void ) { if (!count) { cl->ping = 999; } else { - cl->ping = total/count; - if ( cl->ping > 999 ) { + cl->ping = total / count; + if (cl->ping > 999) { cl->ping = 999; } } // let the game dll know about the ping - ps = SV_GameClientNum( i ); + ps = SV_GameClientNum(i); ps->ping = cl->ping; } } @@ -908,33 +890,32 @@ for a few seconds to make sure any final reliable message gets resent if necessary ================== */ -void SV_CheckTimeouts( void ) { - int i; - client_t *cl; - int droppoint; - int zombiepoint; +void SV_CheckTimeouts(void) { + int i; + client_t *cl; + int droppoint; + int zombiepoint; droppoint = svs.time - 1000 * sv_timeout->integer; zombiepoint = svs.time - 1000 * sv_zombietime->integer; - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { // message times may be wrong across a changelevel if (cl->lastPacketTime > svs.time) { cl->lastPacketTime = svs.time; } - if (cl->state == CS_ZOMBIE - && cl->lastPacketTime < zombiepoint) { - Com_DPrintf( "Going from CS_ZOMBIE to CS_FREE for %s\n", cl->name ); - cl->state = CS_FREE; // can now be reused + if (cl->state == CS_ZOMBIE && cl->lastPacketTime < zombiepoint) { + Com_DPrintf("Going from CS_ZOMBIE to CS_FREE for %s\n", cl->name); + cl->state = CS_FREE; // can now be reused continue; } - if ( cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint) { + if (cl->state >= CS_CONNECTED && cl->lastPacketTime < droppoint) { // wait several frames so a debugger session doesn't // cause a timeout - if ( ++cl->timeoutCount > 5 ) { - SV_DropClient (cl, "timed out"); - cl->state = CS_FREE; // don't bother with zombie state + if (++cl->timeoutCount > 5) { + SV_DropClient(cl, "timed out"); + cl->state = CS_FREE; // don't bother with zombie state } } else { cl->timeoutCount = 0; @@ -942,30 +923,29 @@ void SV_CheckTimeouts( void ) { } } - /* ================== SV_CheckPaused ================== */ -qboolean SV_CheckPaused( void ) { - int count; - client_t *cl; - int i; +qboolean SV_CheckPaused(void) { + int count; + client_t *cl; + int i; - if ( !cl_paused->integer ) { + if (!cl_paused->integer) { return qfalse; } // only pause if there is just a single client connected count = 0; - for (i=0,cl=svs.clients ; i < sv_maxclients->integer ; i++,cl++) { - if ( cl->state >= CS_CONNECTED && cl->netchan.remoteAddress.type != NA_BOT ) { + for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { + if (cl->state >= CS_CONNECTED && cl->netchan.remoteAddress.type != NA_BOT) { count++; } } - if ( count > 1 ) { + if (count > 1) { // don't pause if (sv_paused->integer) Cvar_Set("sv_paused", "0"); @@ -982,46 +962,39 @@ qboolean SV_CheckPaused( void ) { SV_CheckCvars ================== */ -void SV_CheckCvars( void ) { +void SV_CheckCvars(void) { static int lastModHostname = -1, lastModFramerate = -1, lastModSnapsMin = -1, lastModSnapsMax = -1; static int lastModSnapsPolicy = -1, lastModRatePolicy = -1, lastModClientRate = -1; static int lastModMaxRate = -1, lastModMinRate = -1; qboolean changed = qfalse; - if ( sv_hostname->modificationCount != lastModHostname ) { + if (sv_hostname->modificationCount != lastModHostname) { char hostname[MAX_INFO_STRING]; char *c = hostname; lastModHostname = sv_hostname->modificationCount; - strcpy( hostname, sv_hostname->string ); - while( *c ) - { - if ( (*c == '\\') || (*c == ';') || (*c == '"')) - { + strcpy(hostname, sv_hostname->string); + while (*c) { + if ((*c == '\\') || (*c == ';') || (*c == '"')) { *c = '.'; changed = qtrue; } c++; } - if( changed ) - { - Cvar_Set("sv_hostname", hostname ); + if (changed) { + Cvar_Set("sv_hostname", hostname); } } // check limits on client "rate" values based on server settings - if ( sv_clientRate->modificationCount != lastModClientRate || - sv_minRate->modificationCount != lastModMinRate || - sv_maxRate->modificationCount != lastModMaxRate || - sv_ratePolicy->modificationCount != lastModRatePolicy ) - { + if (sv_clientRate->modificationCount != lastModClientRate || sv_minRate->modificationCount != lastModMinRate || + sv_maxRate->modificationCount != lastModMaxRate || sv_ratePolicy->modificationCount != lastModRatePolicy) { sv_clientRate->modificationCount = lastModClientRate; sv_maxRate->modificationCount = lastModMaxRate; sv_minRate->modificationCount = lastModMinRate; sv_ratePolicy->modificationCount = lastModRatePolicy; - if (sv_ratePolicy->integer == 1) - { + if (sv_ratePolicy->integer == 1) { // NOTE: what if server sets some dumb sv_clientRate value? client_t *cl = NULL; int i = 0; @@ -1030,18 +1003,15 @@ void SV_CheckCvars( void ) { // if the client is on the same subnet as the server and we aren't running an // internet public server, assume they don't need a rate choke if (Sys_IsLANAddress(cl->netchan.remoteAddress) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1) { - cl->rate = 100000; // lans should not rate limit - } - else { + cl->rate = 100000; // lans should not rate limit + } else { int val = sv_clientRate->integer; if (val != cl->rate) { cl->rate = val; } } } - } - else if (sv_ratePolicy->integer == 2) - { + } else if (sv_ratePolicy->integer == 2) { // NOTE: what if server sets some dumb sv_clientRate value? client_t *cl = NULL; int i = 0; @@ -1050,15 +1020,14 @@ void SV_CheckCvars( void ) { // if the client is on the same subnet as the server and we aren't running an // internet public server, assume they don't need a rate choke if (Sys_IsLANAddress(cl->netchan.remoteAddress) && com_dedicated->integer != 2 && sv_lanForceRate->integer == 1) { - cl->rate = 100000; // lans should not rate limit - } - else { + cl->rate = 100000; // lans should not rate limit + } else { int val = cl->rate; if (!val) { val = sv_maxRate->integer; } - val = Com_Clampi( 1000, 90000, val ); - val = Com_Clampi( sv_minRate->integer, sv_maxRate->integer, val ); + val = Com_Clampi(1000, 90000, val); + val = Com_Clampi(sv_minRate->integer, sv_maxRate->integer, val); if (val != cl->rate) { cl->rate = val; } @@ -1068,18 +1037,14 @@ void SV_CheckCvars( void ) { } // check limits on client "snaps" value based on server framerate and snapshot rate - if ( sv_fps->modificationCount != lastModFramerate || - sv_snapsMin->modificationCount != lastModSnapsMin || - sv_snapsMax->modificationCount != lastModSnapsMax || - sv_snapsPolicy->modificationCount != lastModSnapsPolicy ) - { + if (sv_fps->modificationCount != lastModFramerate || sv_snapsMin->modificationCount != lastModSnapsMin || + sv_snapsMax->modificationCount != lastModSnapsMax || sv_snapsPolicy->modificationCount != lastModSnapsPolicy) { lastModFramerate = sv_fps->modificationCount; lastModSnapsMin = sv_snapsMin->modificationCount; lastModSnapsMax = sv_snapsMax->modificationCount; lastModSnapsPolicy = sv_snapsPolicy->modificationCount; - if (sv_snapsPolicy->integer == 1) - { + if (sv_snapsPolicy->integer == 1) { client_t *cl = NULL; int i = 0; @@ -1091,13 +1056,12 @@ void SV_CheckCvars( void ) { cl->snapshotMsec = val; } } - } - else if (sv_snapsPolicy->integer == 2) - { + } else if (sv_snapsPolicy->integer == 2) { client_t *cl = NULL; int i = 0; int minSnaps = Com_Clampi(1, sv_snapsMax->integer, sv_snapsMin->integer); // between 1 and sv_snapsMax ( 1 <-> 40 ) - int maxSnaps = Q_min(sv_fps->integer, sv_snapsMax->integer); // can't produce more than sv_fps snapshots/sec, but can send less than sv_fps snapshots/sec + int maxSnaps = + Q_min(sv_fps->integer, sv_snapsMax->integer); // can't produce more than sv_fps snapshots/sec, but can send less than sv_fps snapshots/sec for (i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++) { int val = 1000 / Com_Clampi(minSnaps, maxSnaps, cl->wishSnaps); @@ -1117,20 +1081,17 @@ SV_FrameMsec Return time in millseconds until processing of the next server frame. ================== */ -int SV_FrameMsec() -{ - if(sv_fps) - { +int SV_FrameMsec() { + if (sv_fps) { int frameMsec; frameMsec = 1000.0f / sv_fps->value; - if(frameMsec < sv.timeResidual) + if (frameMsec < sv.timeResidual) return 0; else return frameMsec - sv.timeResidual; - } - else + } else return 1; } @@ -1142,101 +1103,102 @@ Player movement occurs as a result of packet events, which happen before SV_Frame is called ================== */ -void SV_Frame( int msec ) { - int frameMsec; - int startTime; +void SV_Frame(int msec) { + int frameMsec; + int startTime; // the menu kills the server with this cvar - if ( sv_killserver->integer ) { - SV_Shutdown ("Server was killed.\n"); - Cvar_Set( "sv_killserver", "0" ); + if (sv_killserver->integer) { + SV_Shutdown("Server was killed.\n"); + Cvar_Set("sv_killserver", "0"); return; } - if ( !com_sv_running->integer ) { + if (!com_sv_running->integer) { return; } // allow pause if only the local client is connected - if ( SV_CheckPaused() ) { + if (SV_CheckPaused()) { return; } // if it isn't time for the next frame, do nothing - if ( sv_fps->integer < 1 ) { - Cvar_Set( "sv_fps", "10" ); + if (sv_fps->integer < 1) { + Cvar_Set("sv_fps", "10"); } frameMsec = 1000 / sv_fps->integer * com_timescale->value; // don't let it scale below 1ms - if(frameMsec < 1) - { + if (frameMsec < 1) { Cvar_Set("timescale", va("%f", sv_fps->integer / 1000.0f)); frameMsec = 1; } sv.timeResidual += msec; - if (!com_dedicated->integer) SV_BotFrame( sv.time + sv.timeResidual ); + if (!com_dedicated->integer) + SV_BotFrame(sv.time + sv.timeResidual); // if time is about to hit the 32nd bit, kick all clients // and clear sv.time, rather // than checking for negative time wraparound everywhere. // 2giga-milliseconds = 23 days, so it won't be too often - if ( svs.time > 0x70000000 ) { - SV_Shutdown( "Restarting server due to time wrapping" ); - Cbuf_AddText( va( "map %s\n", Cvar_VariableString( "mapname" ) ) ); + if (svs.time > 0x70000000) { + SV_Shutdown("Restarting server due to time wrapping"); + Cbuf_AddText(va("map %s\n", Cvar_VariableString("mapname"))); return; } // this can happen considerably earlier when lots of clients play and the map doesn't change - if ( svs.nextSnapshotEntities >= 0x7FFFFFFE - svs.numSnapshotEntities ) { - SV_Shutdown( "Restarting server due to numSnapshotEntities wrapping" ); - Cbuf_AddText( va( "map %s\n", Cvar_VariableString( "mapname" ) ) ); + if (svs.nextSnapshotEntities >= 0x7FFFFFFE - svs.numSnapshotEntities) { + SV_Shutdown("Restarting server due to numSnapshotEntities wrapping"); + Cbuf_AddText(va("map %s\n", Cvar_VariableString("mapname"))); return; } - if( sv.restartTime && sv.time >= sv.restartTime ) { + if (sv.restartTime && sv.time >= sv.restartTime) { sv.restartTime = 0; - Cbuf_AddText( "map_restart 0\n" ); + Cbuf_AddText("map_restart 0\n"); return; } // update infostrings if anything has been changed - if ( cvar_modifiedFlags & CVAR_SERVERINFO ) { - SV_SetConfigstring( CS_SERVERINFO, Cvar_InfoString( CVAR_SERVERINFO ) ); + if (cvar_modifiedFlags & CVAR_SERVERINFO) { + SV_SetConfigstring(CS_SERVERINFO, Cvar_InfoString(CVAR_SERVERINFO)); cvar_modifiedFlags &= ~CVAR_SERVERINFO; } - if ( cvar_modifiedFlags & CVAR_SYSTEMINFO ) { - SV_SetConfigstring( CS_SYSTEMINFO, Cvar_InfoString_Big( CVAR_SYSTEMINFO ) ); + if (cvar_modifiedFlags & CVAR_SYSTEMINFO) { + SV_SetConfigstring(CS_SYSTEMINFO, Cvar_InfoString_Big(CVAR_SYSTEMINFO)); cvar_modifiedFlags &= ~CVAR_SYSTEMINFO; } - if ( com_speeds->integer ) { - startTime = Sys_Milliseconds (); + if (com_speeds->integer) { + startTime = Sys_Milliseconds(); } else { - startTime = 0; // quite a compiler warning + startTime = 0; // quite a compiler warning } // update ping based on the all received frames SV_CalcPings(); - if (com_dedicated->integer) SV_BotFrame( sv.time ); + if (com_dedicated->integer) + SV_BotFrame(sv.time); // run the game simulation in chunks - while ( sv.timeResidual >= frameMsec ) { + while (sv.timeResidual >= frameMsec) { sv.timeResidual -= frameMsec; svs.time += frameMsec; sv.time += frameMsec; // let everything in the world think and move - GVM_RunFrame( sv.time ); + GVM_RunFrame(sv.time); } - //rww - RAGDOLL_BEGIN - re->G2API_SetTime(sv.time,0); - //rww - RAGDOLL_END + // rww - RAGDOLL_BEGIN + re->G2API_SetTime(sv.time, 0); + // rww - RAGDOLL_END - if ( com_speeds->integer ) { - time_game = Sys_Milliseconds () - startTime; + if (com_speeds->integer) { + time_game = Sys_Milliseconds() - startTime; } // check timeouts @@ -1252,4 +1214,3 @@ void SV_Frame( int msec ) { } //============================================================================ - diff --git a/codemp/server/sv_net_chan.cpp b/codemp/server/sv_net_chan.cpp index 24b2915e03..42cbe74bfb 100644 --- a/codemp/server/sv_net_chan.cpp +++ b/codemp/server/sv_net_chan.cpp @@ -34,29 +34,29 @@ SV_Netchan_Encode ============== */ -static void SV_Netchan_Encode( client_t *client, msg_t *msg ) { +static void SV_Netchan_Encode(client_t *client, msg_t *msg) { long /*reliableAcknowledge,*/ i, index; byte key, *string; - int srdc, sbit; - qboolean soob; + int srdc, sbit; + qboolean soob; - if ( msg->cursize < SV_ENCODE_START ) { + if (msg->cursize < SV_ENCODE_START) { return; } - srdc = msg->readcount; - sbit = msg->bit; - soob = msg->oob; + srdc = msg->readcount; + sbit = msg->bit; + soob = msg->oob; - msg->bit = 0; - msg->readcount = 0; - msg->oob = qfalse; + msg->bit = 0; + msg->readcount = 0; + msg->oob = qfalse; - /*reliableAcknowledge =*/ MSG_ReadLong(msg); + /*reliableAcknowledge =*/MSG_ReadLong(msg); - msg->oob = soob; - msg->bit = sbit; - msg->readcount = srdc; + msg->oob = soob; + msg->bit = sbit; + msg->readcount = srdc; string = (byte *)client->lastClientCommandString; index = 0; @@ -66,12 +66,10 @@ static void SV_Netchan_Encode( client_t *client, msg_t *msg ) { // modify the key with the last received and with this message acknowledged client command if (!string[index]) index = 0; - if (/*string[index] > 127 ||*/ // eurofix: remove this so we can chat in european languages... -ste - string[index] == '%') - { + if (/*string[index] > 127 ||*/ // eurofix: remove this so we can chat in european languages... -ste + string[index] == '%') { key ^= '.' << (i & 1); - } - else { + } else { key ^= string[index] << (i & 1); } index++; @@ -91,27 +89,27 @@ SV_Netchan_Decode ============== */ -static void SV_Netchan_Decode( client_t *client, msg_t *msg ) { +static void SV_Netchan_Decode(client_t *client, msg_t *msg) { int serverId, messageAcknowledge, reliableAcknowledge; int i, index, srdc, sbit; qboolean soob; byte key, *string; - srdc = msg->readcount; - sbit = msg->bit; - soob = msg->oob; + srdc = msg->readcount; + sbit = msg->bit; + soob = msg->oob; - msg->oob = qfalse; + msg->oob = qfalse; - serverId = MSG_ReadLong(msg); + serverId = MSG_ReadLong(msg); messageAcknowledge = MSG_ReadLong(msg); reliableAcknowledge = MSG_ReadLong(msg); - msg->oob = soob; - msg->bit = sbit; - msg->readcount = srdc; + msg->oob = soob; + msg->bit = sbit; + msg->readcount = srdc; - string = (byte *)client->reliableCommands[ reliableAcknowledge & (MAX_RELIABLE_COMMANDS-1) ]; + string = (byte *)client->reliableCommands[reliableAcknowledge & (MAX_RELIABLE_COMMANDS - 1)]; index = 0; // key = client->challenge ^ serverId ^ messageAcknowledge; @@ -119,12 +117,10 @@ static void SV_Netchan_Decode( client_t *client, msg_t *msg ) { // modify the key with the last sent and acknowledged server command if (!string[index]) index = 0; - if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste - string[index] == '%') - { + if (/*string[index] > 127 || */ // eurofix: remove this so we can chat in european languages... -ste + string[index] == '%') { key ^= '.' << (i & 1); - } - else { + } else { key ^= string[index] << (i & 1); } index++; @@ -139,10 +135,7 @@ static void SV_Netchan_Decode( client_t *client, msg_t *msg ) { SV_Netchan_TransmitNextFragment ================= */ -void SV_Netchan_TransmitNextFragment( netchan_t *chan ) { - Netchan_TransmitNextFragment( chan ); -} - +void SV_Netchan_TransmitNextFragment(netchan_t *chan) { Netchan_TransmitNextFragment(chan); } /* =============== @@ -150,15 +143,15 @@ SV_Netchan_Transmit ================ */ -void SV_Netchan_Transmit( client_t *client, msg_t *msg) { //int length, const byte *data ) { -// int i; - MSG_WriteByte( msg, svc_EOF ); -// for(i=SV_ENCODE_START;icursize;i++) { -// chksum[i-SV_ENCODE_START] = msg->data[i]; -// } -// Huff_Compress( msg, SV_ENCODE_START ); - SV_Netchan_Encode( client, msg ); - Netchan_Transmit( &client->netchan, msg->cursize, msg->data ); +void SV_Netchan_Transmit(client_t *client, msg_t *msg) { // int length, const byte *data ) { + // int i; + MSG_WriteByte(msg, svc_EOF); + // for(i=SV_ENCODE_START;icursize;i++) { + // chksum[i-SV_ENCODE_START] = msg->data[i]; + // } + // Huff_Compress( msg, SV_ENCODE_START ); + SV_Netchan_Encode(client, msg); + Netchan_Transmit(&client->netchan, msg->cursize, msg->data); } /* @@ -166,19 +159,18 @@ void SV_Netchan_Transmit( client_t *client, msg_t *msg) { //int length, const by Netchan_SV_Process ================= */ -qboolean SV_Netchan_Process( client_t *client, msg_t *msg ) { +qboolean SV_Netchan_Process(client_t *client, msg_t *msg) { int ret; -// int i; - ret = Netchan_Process( &client->netchan, msg ); + // int i; + ret = Netchan_Process(&client->netchan, msg); if (!ret) return qfalse; - SV_Netchan_Decode( client, msg ); -// Huff_Decompress( msg, SV_DECODE_START ); -// for(i=SV_DECODE_START+msg->readcount;icursize;i++) { -// if (msg->data[i] != chksum[i-(SV_DECODE_START+msg->readcount)]) { -// Com_Error(ERR_DROP,"bad\n"); -// } -// } + SV_Netchan_Decode(client, msg); + // Huff_Decompress( msg, SV_DECODE_START ); + // for(i=SV_DECODE_START+msg->readcount;icursize;i++) { + // if (msg->data[i] != chksum[i-(SV_DECODE_START+msg->readcount)]) { + // Com_Error(ERR_DROP,"bad\n"); + // } + // } return qtrue; } - diff --git a/codemp/server/sv_snapshot.cpp b/codemp/server/sv_snapshot.cpp index b8515bf376..00b0612529 100644 --- a/codemp/server/sv_snapshot.cpp +++ b/codemp/server/sv_snapshot.cpp @@ -53,14 +53,14 @@ SV_EmitPacketEntities Writes a delta update of an entityState_t list to the message. ============= */ -static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg ) { - entityState_t *oldent, *newent; - int oldindex, newindex; - int oldnum, newnum; - int from_num_entities; +static void SV_EmitPacketEntities(clientSnapshot_t *from, clientSnapshot_t *to, msg_t *msg) { + entityState_t *oldent, *newent; + int oldindex, newindex; + int oldnum, newnum; + int from_num_entities; // generate the delta update - if ( !from ) { + if (!from) { from_num_entities = 0; } else { from_num_entities = from->num_entities; @@ -70,89 +70,86 @@ static void SV_EmitPacketEntities( clientSnapshot_t *from, clientSnapshot_t *to, oldent = NULL; newindex = 0; oldindex = 0; - while ( newindex < to->num_entities || oldindex < from_num_entities ) { - if ( newindex >= to->num_entities ) { + while (newindex < to->num_entities || oldindex < from_num_entities) { + if (newindex >= to->num_entities) { newnum = 9999; } else { - newent = &svs.snapshotEntities[(to->first_entity+newindex) % svs.numSnapshotEntities]; + newent = &svs.snapshotEntities[(to->first_entity + newindex) % svs.numSnapshotEntities]; newnum = newent->number; } - if ( oldindex >= from_num_entities ) { + if (oldindex >= from_num_entities) { oldnum = 9999; } else { - oldent = &svs.snapshotEntities[(from->first_entity+oldindex) % svs.numSnapshotEntities]; + oldent = &svs.snapshotEntities[(from->first_entity + oldindex) % svs.numSnapshotEntities]; oldnum = oldent->number; } - if ( newnum == oldnum ) { + if (newnum == oldnum) { // delta update from old position // because the force parm is qfalse, this will not result // in any bytes being emited if the entity has not changed at all - MSG_WriteDeltaEntity (msg, oldent, newent, qfalse ); + MSG_WriteDeltaEntity(msg, oldent, newent, qfalse); oldindex++; newindex++; continue; } - if ( newnum < oldnum ) { + if (newnum < oldnum) { // this is a new entity, send it from the baseline - MSG_WriteDeltaEntity (msg, &sv.svEntities[newnum].baseline, newent, qtrue ); + MSG_WriteDeltaEntity(msg, &sv.svEntities[newnum].baseline, newent, qtrue); newindex++; continue; } - if ( newnum > oldnum ) { + if (newnum > oldnum) { // the old entity isn't present in the new message - MSG_WriteDeltaEntity (msg, oldent, NULL, qtrue ); + MSG_WriteDeltaEntity(msg, oldent, NULL, qtrue); oldindex++; continue; } } - MSG_WriteBits( msg, (MAX_GENTITIES-1), GENTITYNUM_BITS ); // end of packetentities + MSG_WriteBits(msg, (MAX_GENTITIES - 1), GENTITYNUM_BITS); // end of packetentities } - - /* ================== SV_WriteSnapshotToClient ================== */ -static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) { - clientSnapshot_t *frame, *oldframe; - int lastframe; - int i; - int snapFlags; - int deltaMessage; +static void SV_WriteSnapshotToClient(client_t *client, msg_t *msg) { + clientSnapshot_t *frame, *oldframe; + int lastframe; + int i; + int snapFlags; + int deltaMessage; // this is the snapshot we are creating - frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ]; + frame = &client->frames[client->netchan.outgoingSequence & PACKET_MASK]; // bots never acknowledge, but it doesn't matter since the only use case is for serverside demos // in which case we can delta against the very last message every time deltaMessage = client->deltaMessage; - if ( client->demo.isBot ) { + if (client->demo.isBot) { client->deltaMessage = client->netchan.outgoingSequence; } // try to use a previous frame as the source for delta compressing the snapshot - if ( deltaMessage <= 0 || client->state != CS_ACTIVE ) { + if (deltaMessage <= 0 || client->state != CS_ACTIVE) { // client is asking for a retransmit oldframe = NULL; lastframe = 0; - } else if ( client->netchan.outgoingSequence - deltaMessage - >= (PACKET_BACKUP - 3) ) { + } else if (client->netchan.outgoingSequence - deltaMessage >= (PACKET_BACKUP - 3)) { // client hasn't gotten a good message through in a long time - Com_DPrintf ("%s: Delta request from out of date packet.\n", client->name); + Com_DPrintf("%s: Delta request from out of date packet.\n", client->name); oldframe = NULL; lastframe = 0; - } else if ( client->demo.demorecording && client->demo.demowaiting ) { + } else if (client->demo.demorecording && client->demo.demowaiting) { // demo is waiting for a non-delta-compressed frame for this client, so don't delta compress oldframe = NULL; lastframe = 0; - } else if ( client->demo.minDeltaFrame > deltaMessage ) { + } else if (client->demo.minDeltaFrame > deltaMessage) { // we saved a non-delta frame to the demo and sent it to the client, but the client didn't ack it // we can't delta against an old frame that's not in the demo without breaking the demo. so send // non-delta frames until the client acks. @@ -160,118 +157,111 @@ static void SV_WriteSnapshotToClient( client_t *client, msg_t *msg ) { lastframe = 0; } else { // we have a valid snapshot to delta from - oldframe = &client->frames[ deltaMessage & PACKET_MASK ]; + oldframe = &client->frames[deltaMessage & PACKET_MASK]; lastframe = client->netchan.outgoingSequence - deltaMessage; // the snapshot's entities may still have rolled off the buffer, though - if ( oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities ) { - Com_DPrintf ("%s: Delta request from out of date entities.\n", client->name); + if (oldframe->first_entity <= svs.nextSnapshotEntities - svs.numSnapshotEntities) { + Com_DPrintf("%s: Delta request from out of date entities.\n", client->name); oldframe = NULL; lastframe = 0; } } - if ( oldframe == NULL ) { - if ( client->demo.demowaiting ) { + if (oldframe == NULL) { + if (client->demo.demowaiting) { // this is a non-delta frame, so we can delta against it in the demo client->demo.minDeltaFrame = client->netchan.outgoingSequence; } client->demo.demowaiting = qfalse; } - MSG_WriteByte (msg, svc_snapshot); + MSG_WriteByte(msg, svc_snapshot); // NOTE, MRE: now sent at the start of every message from server to client // let the client know which reliable clientCommands we have received - //MSG_WriteLong( msg, client->lastClientCommand ); + // MSG_WriteLong( msg, client->lastClientCommand ); // send over the current server time so the client can drift // its view of time to try to match - if( client->oldServerTime && - !( client->demo.demorecording && client->demo.isBot ) ) { + if (client->oldServerTime && !(client->demo.demorecording && client->demo.isBot)) { // The server has not yet got an acknowledgement of the // new gamestate from this client, so continue to send it // a time as if the server has not restarted. Note from // the client's perspective this time is strictly speaking // incorrect, but since it'll be busy loading a map at // the time it doesn't really matter. - MSG_WriteLong (msg, sv.time + client->oldServerTime); + MSG_WriteLong(msg, sv.time + client->oldServerTime); } else { - MSG_WriteLong (msg, sv.time); + MSG_WriteLong(msg, sv.time); } // what we are delta'ing from - MSG_WriteByte (msg, lastframe); + MSG_WriteByte(msg, lastframe); snapFlags = svs.snapFlagServerBit; - if ( client->rateDelayed ) { + if (client->rateDelayed) { snapFlags |= SNAPFLAG_RATE_DELAYED; } - if ( client->state != CS_ACTIVE ) { + if (client->state != CS_ACTIVE) { snapFlags |= SNAPFLAG_NOT_ACTIVE; } - MSG_WriteByte (msg, snapFlags); + MSG_WriteByte(msg, snapFlags); // send over the areabits - MSG_WriteByte (msg, frame->areabytes); - MSG_WriteData (msg, frame->areabits, frame->areabytes); + MSG_WriteByte(msg, frame->areabytes); + MSG_WriteData(msg, frame->areabits, frame->areabytes); // delta encode the playerstate - if ( oldframe ) { + if (oldframe) { #ifdef _ONEBIT_COMBO - MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps, frame->pDeltaOneBit, frame->pDeltaNumBit ); + MSG_WriteDeltaPlayerstate(msg, &oldframe->ps, &frame->ps, frame->pDeltaOneBit, frame->pDeltaNumBit); #else - MSG_WriteDeltaPlayerstate( msg, &oldframe->ps, &frame->ps ); + MSG_WriteDeltaPlayerstate(msg, &oldframe->ps, &frame->ps); #endif - if (frame->ps.m_iVehicleNum) - { //then write the vehicle's playerstate too - if (!oldframe->ps.m_iVehicleNum) - { //if last frame didn't have vehicle, then the old vps isn't gonna delta - //properly (because our vps on the client could be anything) + if (frame->ps.m_iVehicleNum) { // then write the vehicle's playerstate too + if (!oldframe->ps.m_iVehicleNum) { // if last frame didn't have vehicle, then the old vps isn't gonna delta + // properly (because our vps on the client could be anything) #ifdef _ONEBIT_COMBO - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->vps, NULL, NULL, qtrue ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->vps, NULL, NULL, qtrue); #else - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->vps, qtrue ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->vps, qtrue); #endif - } - else - { + } else { #ifdef _ONEBIT_COMBO - MSG_WriteDeltaPlayerstate( msg, &oldframe->vps, &frame->vps, frame->pDeltaOneBitVeh, frame->pDeltaNumBitVeh, qtrue ); + MSG_WriteDeltaPlayerstate(msg, &oldframe->vps, &frame->vps, frame->pDeltaOneBitVeh, frame->pDeltaNumBitVeh, qtrue); #else - MSG_WriteDeltaPlayerstate( msg, &oldframe->vps, &frame->vps, qtrue ); + MSG_WriteDeltaPlayerstate(msg, &oldframe->vps, &frame->vps, qtrue); #endif } } } else { #ifdef _ONEBIT_COMBO - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps, NULL, NULL ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->ps, NULL, NULL); #else - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->ps ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->ps); #endif - if (frame->ps.m_iVehicleNum) - { //then write the vehicle's playerstate too + if (frame->ps.m_iVehicleNum) { // then write the vehicle's playerstate too #ifdef _ONEBIT_COMBO - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->vps, NULL, NULL, qtrue ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->vps, NULL, NULL, qtrue); #else - MSG_WriteDeltaPlayerstate( msg, NULL, &frame->vps, qtrue ); + MSG_WriteDeltaPlayerstate(msg, NULL, &frame->vps, qtrue); #endif } } // delta encode the entities - SV_EmitPacketEntities (oldframe, frame, msg); + SV_EmitPacketEntities(oldframe, frame, msg); // padding for rate debugging - if ( sv_padPackets->integer ) { - for ( i = 0 ; i < sv_padPackets->integer ; i++ ) { - MSG_WriteByte (msg, svc_nop); + if (sv_padPackets->integer) { + for (i = 0; i < sv_padPackets->integer; i++) { + MSG_WriteByte(msg, svc_nop); } } } - /* ================== SV_UpdateServerCommandsToClient @@ -279,21 +269,21 @@ SV_UpdateServerCommandsToClient (re)send all server commands the client hasn't acknowledged yet ================== */ -void SV_UpdateServerCommandsToClient( client_t *client, msg_t *msg ) { - int i; - int reliableAcknowledge; +void SV_UpdateServerCommandsToClient(client_t *client, msg_t *msg) { + int i; + int reliableAcknowledge; - if ( client->demo.isBot && client->demo.demorecording ) { + if (client->demo.isBot && client->demo.demorecording) { reliableAcknowledge = client->demo.botReliableAcknowledge; } else { reliableAcknowledge = client->reliableAcknowledge; } // write any unacknowledged serverCommands - for ( i = reliableAcknowledge + 1 ; i <= client->reliableSequence ; i++ ) { - MSG_WriteByte( msg, svc_serverCommand ); - MSG_WriteLong( msg, i ); - MSG_WriteString( msg, client->reliableCommands[ i & (MAX_RELIABLE_COMMANDS-1) ] ); + for (i = reliableAcknowledge + 1; i <= client->reliableSequence; i++) { + MSG_WriteByte(msg, svc_serverCommand); + MSG_WriteLong(msg, i); + MSG_WriteString(msg, client->reliableCommands[i & (MAX_RELIABLE_COMMANDS - 1)]); } client->reliableSent = client->reliableSequence; } @@ -307,8 +297,8 @@ Build a client snapshot structure */ typedef struct snapshotEntityNumbers_s { - int numSnapshotEntities; - int snapshotEntities[MAX_SNAPSHOT_ENTITIES]; + int numSnapshotEntities; + int snapshotEntities[MAX_SNAPSHOT_ENTITIES]; } snapshotEntityNumbers_t; /* @@ -316,42 +306,41 @@ typedef struct snapshotEntityNumbers_s { SV_QsortEntityNumbers ======================= */ -static int QDECL SV_QsortEntityNumbers( const void *a, const void *b ) { - int *ea, *eb; +static int QDECL SV_QsortEntityNumbers(const void *a, const void *b) { + int *ea, *eb; ea = (int *)a; eb = (int *)b; - if ( *ea == *eb ) { - Com_Error( ERR_DROP, "SV_QsortEntityStates: duplicated entity" ); + if (*ea == *eb) { + Com_Error(ERR_DROP, "SV_QsortEntityStates: duplicated entity"); } - if ( *ea < *eb ) { + if (*ea < *eb) { return -1; } return 1; } - /* =============== SV_AddEntToSnapshot =============== */ -static void SV_AddEntToSnapshot( svEntity_t *svEnt, sharedEntity_t *gEnt, snapshotEntityNumbers_t *eNums ) { +static void SV_AddEntToSnapshot(svEntity_t *svEnt, sharedEntity_t *gEnt, snapshotEntityNumbers_t *eNums) { // if we have already added this entity to this snapshot, don't add again - if ( svEnt->snapshotCounter == sv.snapshotCounter ) { + if (svEnt->snapshotCounter == sv.snapshotCounter) { return; } svEnt->snapshotCounter = sv.snapshotCounter; // if we are full, silently discard entities - if ( eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES ) { + if (eNums->numSnapshotEntities == MAX_SNAPSHOT_ENTITIES) { return; } - eNums->snapshotEntities[ eNums->numSnapshotEntities ] = gEnt->s.number; + eNums->snapshotEntities[eNums->numSnapshotEntities] = gEnt->s.number; eNums->numSnapshotEntities++; } @@ -361,141 +350,135 @@ SV_AddEntitiesVisibleFromPoint =============== */ float g_svCullDist = -1.0f; -static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *frame, - snapshotEntityNumbers_t *eNums, qboolean portal ) { - int e, i; +static void SV_AddEntitiesVisibleFromPoint(vec3_t origin, clientSnapshot_t *frame, snapshotEntityNumbers_t *eNums, qboolean portal) { + int e, i; sharedEntity_t *ent; - svEntity_t *svEnt; - int l; - int clientarea, clientcluster; - int leafnum; - byte *clientpvs; - byte *bitvector; - vec3_t difference; - float length, radius; + svEntity_t *svEnt; + int l; + int clientarea, clientcluster; + int leafnum; + byte *clientpvs; + byte *bitvector; + vec3_t difference; + float length, radius; // during an error shutdown message we may need to transmit // the shutdown message after the server has shutdown, so // specfically check for it - if ( !sv.state ) { + if (!sv.state) { return; } - leafnum = CM_PointLeafnum (origin); - clientarea = CM_LeafArea (leafnum); - clientcluster = CM_LeafCluster (leafnum); + leafnum = CM_PointLeafnum(origin); + clientarea = CM_LeafArea(leafnum); + clientcluster = CM_LeafCluster(leafnum); // calculate the visible areas - frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea ); + frame->areabytes = CM_WriteAreaBits(frame->areabits, clientarea); - clientpvs = CM_ClusterPVS (clientcluster); + clientpvs = CM_ClusterPVS(clientcluster); - for ( e = 0 ; e < sv.num_entities ; e++ ) { + for (e = 0; e < sv.num_entities; e++) { ent = SV_GentityNum(e); // never send entities that aren't linked in - if ( !ent->r.linked ) { + if (!ent->r.linked) { continue; } - if (ent->s.eFlags & EF_PERMANENT) - { // he's permanent, so don't send him down! + if (ent->s.eFlags & EF_PERMANENT) { // he's permanent, so don't send him down! continue; } if (ent->s.number != e) { - Com_DPrintf ("FIXING ENT->S.NUMBER!!!\n"); + Com_DPrintf("FIXING ENT->S.NUMBER!!!\n"); ent->s.number = e; } // entities can be flagged to explicitly not be sent to the client - if ( ent->r.svFlags & SVF_NOCLIENT ) { + if (ent->r.svFlags & SVF_NOCLIENT) { continue; } // entities can be flagged to be sent to only one client - if ( ent->r.svFlags & SVF_SINGLECLIENT ) { - if ( ent->r.singleClient != frame->ps.clientNum ) { + if (ent->r.svFlags & SVF_SINGLECLIENT) { + if (ent->r.singleClient != frame->ps.clientNum) { continue; } } // entities can be flagged to be sent to everyone but one client - if ( ent->r.svFlags & SVF_NOTSINGLECLIENT ) { - if ( ent->r.singleClient == frame->ps.clientNum ) { + if (ent->r.svFlags & SVF_NOTSINGLECLIENT) { + if (ent->r.singleClient == frame->ps.clientNum) { continue; } } - svEnt = SV_SvEntityForGentity( ent ); + svEnt = SV_SvEntityForGentity(ent); // don't double add an entity through portals - if ( svEnt->snapshotCounter == sv.snapshotCounter ) { + if (svEnt->snapshotCounter == sv.snapshotCounter) { continue; } // entities can request not to be sent to certain clients (NOTE: always send to ourselves) - if ( e != frame->ps.clientNum && (ent->r.svFlags & SVF_BROADCASTCLIENTS) - && !(ent->r.broadcastClients[frame->ps.clientNum/32] & (1 << (frame->ps.clientNum % 32))) ) - { + if (e != frame->ps.clientNum && (ent->r.svFlags & SVF_BROADCASTCLIENTS) && + !(ent->r.broadcastClients[frame->ps.clientNum / 32] & (1 << (frame->ps.clientNum % 32)))) { continue; } // broadcast entities are always sent, and so is the main player so we don't see noclip weirdness - if ( (ent->r.svFlags & SVF_BROADCAST) || e == frame->ps.clientNum - || (ent->r.broadcastClients[frame->ps.clientNum/32] & (1 << (frame->ps.clientNum % 32))) ) - { - SV_AddEntToSnapshot( svEnt, ent, eNums ); + if ((ent->r.svFlags & SVF_BROADCAST) || e == frame->ps.clientNum || + (ent->r.broadcastClients[frame->ps.clientNum / 32] & (1 << (frame->ps.clientNum % 32)))) { + SV_AddEntToSnapshot(svEnt, ent, eNums); continue; } - if (ent->s.isPortalEnt) - { //rww - portal entities are always sent as well - SV_AddEntToSnapshot( svEnt, ent, eNums ); + if (ent->s.isPortalEnt) { // rww - portal entities are always sent as well + SV_AddEntToSnapshot(svEnt, ent, eNums); continue; } // ignore if not touching a PV leaf // check area - if ( !CM_AreasConnected( clientarea, svEnt->areanum ) ) { + if (!CM_AreasConnected(clientarea, svEnt->areanum)) { // doors can legally straddle two areas, so // we may need to check another one - if ( !CM_AreasConnected( clientarea, svEnt->areanum2 ) ) { - continue; // blocked by a door + if (!CM_AreasConnected(clientarea, svEnt->areanum2)) { + continue; // blocked by a door } } bitvector = clientpvs; // check individual leafs - if ( !svEnt->numClusters ) { + if (!svEnt->numClusters) { continue; } l = 0; - for ( i=0 ; i < svEnt->numClusters ; i++ ) { + for (i = 0; i < svEnt->numClusters; i++) { l = svEnt->clusternums[i]; - if ( bitvector[l >> 3] & (1 << (l&7) ) ) { + if (bitvector[l >> 3] & (1 << (l & 7))) { break; } } // if we haven't found it to be visible, // check overflow clusters that coudln't be stored - if ( i == svEnt->numClusters ) { - if ( svEnt->lastCluster ) { - for ( ; l <= svEnt->lastCluster ; l++ ) { - if ( bitvector[l >> 3] & (1 << (l&7) ) ) { + if (i == svEnt->numClusters) { + if (svEnt->lastCluster) { + for (; l <= svEnt->lastCluster; l++) { + if (bitvector[l >> 3] & (1 << (l & 7))) { break; } } - if ( l == svEnt->lastCluster ) { - continue; // not visible + if (l == svEnt->lastCluster) { + continue; // not visible } } else { continue; } } - if (g_svCullDist != -1.0f) - { //do a distance cull check + if (g_svCullDist != -1.0f) { // do a distance cull check VectorAdd(ent->r.absmax, ent->r.absmin, difference); VectorScale(difference, 0.5f, difference); VectorSubtract(origin, difference, difference); @@ -504,25 +487,24 @@ static void SV_AddEntitiesVisibleFromPoint( vec3_t origin, clientSnapshot_t *fra // calculate the diameter VectorSubtract(ent->r.absmax, ent->r.absmin, difference); radius = VectorLength(difference); - if (length-radius >= g_svCullDist) - { //then don't add it + if (length - radius >= g_svCullDist) { // then don't add it continue; } } // add it - SV_AddEntToSnapshot( svEnt, ent, eNums ); + SV_AddEntToSnapshot(svEnt, ent, eNums); // if its a portal entity, add everything visible from its camera position - if ( ent->r.svFlags & SVF_PORTAL ) { - if ( ent->s.generic1 ) { + if (ent->r.svFlags & SVF_PORTAL) { + if (ent->s.generic1) { vec3_t dir; VectorSubtract(ent->s.origin, origin, dir); - if ( VectorLengthSquared(dir) > (float) ent->s.generic1 * ent->s.generic1 ) { + if (VectorLengthSquared(dir) > (float)ent->s.generic1 * ent->s.generic1) { continue; } } - SV_AddEntitiesVisibleFromPoint( ent->s.origin2, frame, eNums, qtrue ); + SV_AddEntitiesVisibleFromPoint(ent->s.origin2, frame, eNums, qtrue); } } } @@ -540,51 +522,49 @@ currently doesn't. For viewing through other player's eyes, client can be something other than client->gentity ============= */ -static void SV_BuildClientSnapshot( client_t *client ) { - vec3_t org; - clientSnapshot_t *frame; - snapshotEntityNumbers_t entityNumbers; - int i; - sharedEntity_t *ent; - entityState_t *state; - svEntity_t *svEnt; - sharedEntity_t *clent; - playerState_t *ps; +static void SV_BuildClientSnapshot(client_t *client) { + vec3_t org; + clientSnapshot_t *frame; + snapshotEntityNumbers_t entityNumbers; + int i; + sharedEntity_t *ent; + entityState_t *state; + svEntity_t *svEnt; + sharedEntity_t *clent; + playerState_t *ps; // bump the counter used to prevent double adding sv.snapshotCounter++; // this is the frame we are creating - frame = &client->frames[ client->netchan.outgoingSequence & PACKET_MASK ]; + frame = &client->frames[client->netchan.outgoingSequence & PACKET_MASK]; // clear everything in this snapshot entityNumbers.numSnapshotEntities = 0; - Com_Memset( frame->areabits, 0, sizeof( frame->areabits ) ); + Com_Memset(frame->areabits, 0, sizeof(frame->areabits)); frame->num_entities = 0; clent = client->gentity; - if ( !clent || client->state == CS_ZOMBIE ) { + if (!clent || client->state == CS_ZOMBIE) { return; } // grab the current playerState_t - ps = SV_GameClientNum( client - svs.clients ); + ps = SV_GameClientNum(client - svs.clients); frame->ps = *ps; #ifdef _ONEBIT_COMBO frame->pDeltaOneBit = &ps->deltaOneBits; frame->pDeltaNumBit = &ps->deltaNumBits; #endif - if (ps->m_iVehicleNum) - { //get the vehicle's playerstate too then + if (ps->m_iVehicleNum) { // get the vehicle's playerstate too then sharedEntity_t *veh = SV_GentityNum(ps->m_iVehicleNum); - if (veh && veh->playerState) - { //Now VMA it and we've got ourselves a playerState + if (veh && veh->playerState) { // Now VMA it and we've got ourselves a playerState playerState_t *vps = ((playerState_t *)VM_ArgPtr((intptr_t)veh->playerState)); - frame->vps = *vps; + frame->vps = *vps; #ifdef _ONEBIT_COMBO frame->pDeltaOneBitVeh = &vps->deltaOneBits; frame->pDeltaNumBitVeh = &vps->deltaNumBits; @@ -592,55 +572,52 @@ static void SV_BuildClientSnapshot( client_t *client ) { } } - int clientNum; + int clientNum; // never send client's own entity, because it can // be regenerated from the playerstate clientNum = frame->ps.clientNum; - if ( clientNum < 0 || clientNum >= MAX_GENTITIES ) { - Com_Error( ERR_DROP, "SV_SvEntityForGentity: bad gEnt" ); + if (clientNum < 0 || clientNum >= MAX_GENTITIES) { + Com_Error(ERR_DROP, "SV_SvEntityForGentity: bad gEnt"); } - svEnt = &sv.svEntities[ clientNum ]; + svEnt = &sv.svEntities[clientNum]; svEnt->snapshotCounter = sv.snapshotCounter; - // find the client's viewpoint - VectorCopy( ps->origin, org ); + VectorCopy(ps->origin, org); org[2] += ps->viewheight; // add all the entities directly visible to the eye, which // may include portal entities that merge other viewpoints - SV_AddEntitiesVisibleFromPoint( org, frame, &entityNumbers, qfalse ); + SV_AddEntitiesVisibleFromPoint(org, frame, &entityNumbers, qfalse); // if there were portals visible, there may be out of order entities // in the list which will need to be resorted for the delta compression // to work correctly. This also catches the error condition // of an entity being included twice. - qsort( entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities, - sizeof( entityNumbers.snapshotEntities[0] ), SV_QsortEntityNumbers ); + qsort(entityNumbers.snapshotEntities, entityNumbers.numSnapshotEntities, sizeof(entityNumbers.snapshotEntities[0]), SV_QsortEntityNumbers); // now that all viewpoint's areabits have been OR'd together, invert // all of them to make it a mask vector, which is what the renderer wants - for ( i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++ ) { + for (i = 0; i < MAX_MAP_AREA_BYTES / 4; i++) { ((int *)frame->areabits)[i] = ((int *)frame->areabits)[i] ^ -1; } // copy the entity states out frame->num_entities = 0; frame->first_entity = svs.nextSnapshotEntities; - for ( i = 0 ; i < entityNumbers.numSnapshotEntities ; i++ ) { + for (i = 0; i < entityNumbers.numSnapshotEntities; i++) { ent = SV_GentityNum(entityNumbers.snapshotEntities[i]); state = &svs.snapshotEntities[svs.nextSnapshotEntities % svs.numSnapshotEntities]; *state = ent->s; svs.nextSnapshotEntities++; // this should never hit, map should always be restarted first in SV_Frame - if ( svs.nextSnapshotEntities >= 0x7FFFFFFE ) { + if (svs.nextSnapshotEntities >= 0x7FFFFFFE) { Com_Error(ERR_FATAL, "svs.nextSnapshotEntities wrapped"); } frame->num_entities++; } } - /* ==================== SV_RateMsec @@ -649,39 +626,39 @@ Return the number of msec a given size message is supposed to take to clear, based on the current rate ==================== */ -#define HEADER_RATE_BYTES 48 // include our header, IP header, and some overhead -static int SV_RateMsec( client_t *client, int messageSize ) { - int rate; - int rateMsec; +#define HEADER_RATE_BYTES 48 // include our header, IP header, and some overhead +static int SV_RateMsec(client_t *client, int messageSize) { + int rate; + int rateMsec; // individual messages will never be larger than fragment size - if ( messageSize > 1500 ) { + if (messageSize > 1500) { messageSize = 1500; } rate = client->rate; - if ( sv_maxRate->integer ) { - if ( sv_maxRate->integer < 1000 ) { - Cvar_Set( "sv_MaxRate", "1000" ); + if (sv_maxRate->integer) { + if (sv_maxRate->integer < 1000) { + Cvar_Set("sv_MaxRate", "1000"); } - if ( sv_maxRate->integer < rate ) { + if (sv_maxRate->integer < rate) { rate = sv_maxRate->integer; } } - if ( sv_minRate->integer ) { - if ( sv_minRate->integer < 1000 ) { - Cvar_Set( "sv_minRate", "1000" ); + if (sv_minRate->integer) { + if (sv_minRate->integer < 1000) { + Cvar_Set("sv_minRate", "1000"); } - if ( sv_minRate->integer > rate ) { + if (sv_minRate->integer > rate) { rate = sv_minRate->integer; } } - rateMsec = ( messageSize + HEADER_RATE_BYTES ) * 1000 / ((int) (rate * com_timescale->value)); + rateMsec = (messageSize + HEADER_RATE_BYTES) * 1000 / ((int)(rate * com_timescale->value)); return rateMsec; } -extern void SV_WriteDemoMessage ( client_t *cl, msg_t *msg, int headerBytes ); +extern void SV_WriteDemoMessage(client_t *cl, msg_t *msg, int headerBytes); /* ======================= SV_SendMessageToClient @@ -689,16 +666,15 @@ SV_SendMessageToClient Called by SV_SendClientSnapshot and SV_SendClientGameState ======================= */ -void SV_SendMessageToClient( msg_t *msg, client_t *client ) { - int rateMsec; +void SV_SendMessageToClient(msg_t *msg, client_t *client) { + int rateMsec; // MW - my attempt to fix illegible server message errors caused by // packet fragmentation of initial snapshot. - while(client->state&&client->netchan.unsentFragments) - { + while (client->state && client->netchan.unsentFragments) { // send additional message fragments if the last message // was too large to send at once - Com_Printf ("[ISM]SV_SendClientGameState() [1] for %s, writing out old fragments\n", client->name); + Com_Printf("[ISM]SV_SendClientGameState() [1] for %s, writing out old fragments\n", client->name); SV_Netchan_TransmitNextFragment(&client->netchan); } @@ -708,37 +684,37 @@ void SV_SendMessageToClient( msg_t *msg, client_t *client ) { client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1; // save the message to demo. this must happen before sending over network as that encodes the backing databuf - if ( client->demo.demorecording && !client->demo.demowaiting ) { + if (client->demo.demorecording && !client->demo.demowaiting) { msg_t msgcopy = *msg; - MSG_WriteByte( &msgcopy, svc_EOF ); - SV_WriteDemoMessage( client, &msgcopy, 0 ); + MSG_WriteByte(&msgcopy, svc_EOF); + SV_WriteDemoMessage(client, &msgcopy, 0); } // bots need to have their snapshots built, but // they query them directly without needing to be sent - if ( client->demo.isBot ) { + if (client->demo.isBot) { client->netchan.outgoingSequence++; client->demo.botReliableAcknowledge = client->reliableSent; return; } // send the datagram - SV_Netchan_Transmit( client, msg ); //msg->cursize, msg->data ); + SV_Netchan_Transmit(client, msg); // msg->cursize, msg->data ); // set nextSnapshotTime based on rate and requested number of updates // local clients get snapshots every server frame // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=491 // added sv_lanForceRate check - if ( client->netchan.remoteAddress.type == NA_LOOPBACK || (sv_lanForceRate->integer && Sys_IsLANAddress (client->netchan.remoteAddress)) ) { - client->nextSnapshotTime = svs.time + ((int) (1000.0 / sv_fps->integer * com_timescale->value)); + if (client->netchan.remoteAddress.type == NA_LOOPBACK || (sv_lanForceRate->integer && Sys_IsLANAddress(client->netchan.remoteAddress))) { + client->nextSnapshotTime = svs.time + ((int)(1000.0 / sv_fps->integer * com_timescale->value)); return; } // normal rate / snapshotMsec calculation - rateMsec = SV_RateMsec( client, msg->cursize ); + rateMsec = SV_RateMsec(client, msg->cursize); - if ( rateMsec < client->snapshotMsec ) { + if (rateMsec < client->snapshotMsec) { // never send more packets than this, no matter what the rate is at rateMsec = client->snapshotMsec; client->rateDelayed = qfalse; @@ -746,20 +722,19 @@ void SV_SendMessageToClient( msg_t *msg, client_t *client ) { client->rateDelayed = qtrue; } - client->nextSnapshotTime = svs.time + ((int) (rateMsec * com_timescale->value)); + client->nextSnapshotTime = svs.time + ((int)(rateMsec * com_timescale->value)); // don't pile up empty snapshots while connecting - if ( client->state != CS_ACTIVE ) { + if (client->state != CS_ACTIVE) { // a gigantic connection message may have already put the nextSnapshotTime // more than a second away, so don't shorten it // do shorten if client is downloading - if ( !*client->downloadName && client->nextSnapshotTime < svs.time + ((int) (1000.0 * com_timescale->value)) ) { - client->nextSnapshotTime = svs.time + ((int) (1000 * com_timescale->value)); + if (!*client->downloadName && client->nextSnapshotTime < svs.time + ((int)(1000.0 * com_timescale->value))) { + client->nextSnapshotTime = svs.time + ((int)(1000 * com_timescale->value)); } } } - /* ======================= SV_SendClientSnapshot @@ -768,26 +743,24 @@ Also called by SV_FinalMessage ======================= */ -extern cvar_t *fs_gamedirvar; -void SV_SendClientSnapshot( client_t *client ) { - byte msg_buf[MAX_MSGLEN]; - msg_t msg; +extern cvar_t *fs_gamedirvar; +void SV_SendClientSnapshot(client_t *client) { + byte msg_buf[MAX_MSGLEN]; + msg_t msg; - if (!client->sentGamedir) - { //rww - if this is the case then make sure there is an svc_setgame sent before this snap + if (!client->sentGamedir) { // rww - if this is the case then make sure there is an svc_setgame sent before this snap int i = 0; - MSG_Init (&msg, msg_buf, sizeof(msg_buf)); + MSG_Init(&msg, msg_buf, sizeof(msg_buf)); - //have to include this for each message. - MSG_WriteLong( &msg, client->lastClientCommand ); + // have to include this for each message. + MSG_WriteLong(&msg, client->lastClientCommand); - MSG_WriteByte (&msg, svc_setgame); + MSG_WriteByte(&msg, svc_setgame); const char *gamedir = FS_GetCurrentGameDir(true); - while (gamedir[i]) - { + while (gamedir[i]) { MSG_WriteByte(&msg, gamedir[i]); i++; } @@ -795,12 +768,11 @@ void SV_SendClientSnapshot( client_t *client ) { // MW - my attempt to fix illegible server message errors caused by // packet fragmentation of initial snapshot. - //rww - reusing this code here - while(client->state&&client->netchan.unsentFragments) - { + // rww - reusing this code here + while (client->state && client->netchan.unsentFragments) { // send additional message fragments if the last message // was too large to send at once - Com_Printf ("[ISM]SV_SendClientGameState() [1] for %s, writing out old fragments\n", client->name); + Com_Printf("[ISM]SV_SendClientGameState() [1] for %s, writing out old fragments\n", client->name); SV_Netchan_TransmitNextFragment(&client->netchan); } @@ -810,83 +782,80 @@ void SV_SendClientSnapshot( client_t *client ) { client->frames[client->netchan.outgoingSequence & PACKET_MASK].messageAcked = -1; // send the datagram - SV_Netchan_Transmit( client, &msg ); //msg->cursize, msg->data ); + SV_Netchan_Transmit(client, &msg); // msg->cursize, msg->data ); client->sentGamedir = qtrue; } // build the snapshot - SV_BuildClientSnapshot( client ); + SV_BuildClientSnapshot(client); - if ( sv_autoDemo->integer && !client->demo.demorecording ) { - if ( client->netchan.remoteAddress.type != NA_BOT || sv_autoDemoBots->integer ) { + if (sv_autoDemo->integer && !client->demo.demorecording) { + if (client->netchan.remoteAddress.type != NA_BOT || sv_autoDemoBots->integer) { SV_BeginAutoRecordDemos(); } } // bots need to have their snapshots built, but // they query them directly without needing to be sent - if ( client->netchan.remoteAddress.type == NA_BOT && !client->demo.demorecording ) { + if (client->netchan.remoteAddress.type == NA_BOT && !client->demo.demorecording) { return; } - MSG_Init (&msg, msg_buf, sizeof(msg_buf)); + MSG_Init(&msg, msg_buf, sizeof(msg_buf)); msg.allowoverflow = qtrue; // NOTE, MRE: all server->client messages now acknowledge // let the client know which reliable clientCommands we have received - MSG_WriteLong( &msg, client->lastClientCommand ); + MSG_WriteLong(&msg, client->lastClientCommand); // (re)send any reliable server commands - SV_UpdateServerCommandsToClient( client, &msg ); + SV_UpdateServerCommandsToClient(client, &msg); // send over all the relevant entityState_t // and the playerState_t - SV_WriteSnapshotToClient( client, &msg ); + SV_WriteSnapshotToClient(client, &msg); // Add any download data if the client is downloading - SV_WriteDownloadToClient( client, &msg ); + SV_WriteDownloadToClient(client, &msg); // check for overflow - if ( msg.overflowed ) { - Com_Printf ("WARNING: msg overflowed for %s\n", client->name); - MSG_Clear (&msg); + if (msg.overflowed) { + Com_Printf("WARNING: msg overflowed for %s\n", client->name); + MSG_Clear(&msg); } - SV_SendMessageToClient( &msg, client ); + SV_SendMessageToClient(&msg, client); } - /* ======================= SV_SendClientMessages ======================= */ -void SV_SendClientMessages( void ) { - int i; - client_t *c; +void SV_SendClientMessages(void) { + int i; + client_t *c; // send a message to each connected client - for (i=0, c = svs.clients ; i < sv_maxclients->integer ; i++, c++) { + for (i = 0, c = svs.clients; i < sv_maxclients->integer; i++, c++) { if (!c->state) { - continue; // not connected + continue; // not connected } - if ( svs.time < c->nextSnapshotTime ) { - continue; // not time yet + if (svs.time < c->nextSnapshotTime) { + continue; // not time yet } // send additional message fragments if the last message // was too large to send at once - if ( c->netchan.unsentFragments ) { - c->nextSnapshotTime = svs.time + - SV_RateMsec( c, c->netchan.unsentLength - c->netchan.unsentFragmentStart ); - SV_Netchan_TransmitNextFragment( &c->netchan ); + if (c->netchan.unsentFragments) { + c->nextSnapshotTime = svs.time + SV_RateMsec(c, c->netchan.unsentLength - c->netchan.unsentFragmentStart); + SV_Netchan_TransmitNextFragment(&c->netchan); continue; } // generate and send a new message - SV_SendClientSnapshot( c ); + SV_SendClientSnapshot(c); } } - diff --git a/codemp/server/sv_world.cpp b/codemp/server/sv_world.cpp index 309f721178..eb406a97de 100644 --- a/codemp/server/sv_world.cpp +++ b/codemp/server/sv_world.cpp @@ -36,22 +36,20 @@ given entity. If the entity is a bsp model, the headnode will be returned, otherwise a custom box tree will be constructed. ================ */ -clipHandle_t SV_ClipHandleForEntity( const sharedEntity_t *ent ) { - if ( ent->r.bmodel ) { +clipHandle_t SV_ClipHandleForEntity(const sharedEntity_t *ent) { + if (ent->r.bmodel) { // explicit hulls in the BSP model - return CM_InlineModel( ent->s.modelindex ); + return CM_InlineModel(ent->s.modelindex); } - if ( ent->r.svFlags & SVF_CAPSULE ) { + if (ent->r.svFlags & SVF_CAPSULE) { // create a temp capsule from bounding box sizes - return CM_TempBoxModel( ent->r.mins, ent->r.maxs, qtrue ); + return CM_TempBoxModel(ent->r.mins, ent->r.maxs, qtrue); } // create a temp tree from bounding box sizes - return CM_TempBoxModel( ent->r.mins, ent->r.maxs, qfalse ); + return CM_TempBoxModel(ent->r.mins, ent->r.maxs, qfalse); } - - /* =============================================================================== @@ -66,37 +64,36 @@ them, which prevents having to deal with multiple fragments of a single entity. */ typedef struct worldSector_s { - int axis; // -1 = leaf node - float dist; - struct worldSector_s *children[2]; - svEntity_t *entities; + int axis; // -1 = leaf node + float dist; + struct worldSector_s *children[2]; + svEntity_t *entities; } worldSector_t; -#define AREA_DEPTH 4 -#define AREA_NODES 64 - -worldSector_t sv_worldSectors[AREA_NODES]; -int sv_numworldSectors; +#define AREA_DEPTH 4 +#define AREA_NODES 64 +worldSector_t sv_worldSectors[AREA_NODES]; +int sv_numworldSectors; /* =============== SV_SectorList_f =============== */ -void SV_SectorList_f( void ) { - int i, c; - worldSector_t *sec; - svEntity_t *ent; +void SV_SectorList_f(void) { + int i, c; + worldSector_t *sec; + svEntity_t *ent; - for ( i = 0 ; i < AREA_NODES ; i++ ) { + for (i = 0; i < AREA_NODES; i++) { sec = &sv_worldSectors[i]; c = 0; - for ( ent = sec->entities ; ent ; ent = ent->nextEntityInWorldSector ) { + for (ent = sec->entities; ent; ent = ent->nextEntityInWorldSector) { c++; } - Com_Printf( "sector %i: %i entities\n", i, c ); + Com_Printf("sector %i: %i entities\n", i, c); } } @@ -107,10 +104,10 @@ SV_CreateworldSector Builds a uniformly subdivided tree for the given world size =============== */ -worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { - worldSector_t *anode; - vec3_t size; - vec3_t mins1, maxs1, mins2, maxs2; +worldSector_t *SV_CreateworldSector(int depth, vec3_t mins, vec3_t maxs) { + worldSector_t *anode; + vec3_t size; + vec3_t mins1, maxs1, mins2, maxs2; anode = &sv_worldSectors[sv_numworldSectors]; sv_numworldSectors++; @@ -121,7 +118,7 @@ worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { return anode; } - VectorSubtract (maxs, mins, size); + VectorSubtract(maxs, mins, size); if (size[0] > size[1]) { anode->axis = 0; } else { @@ -129,15 +126,15 @@ worldSector_t *SV_CreateworldSector( int depth, vec3_t mins, vec3_t maxs ) { } anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]); - VectorCopy (mins, mins1); - VectorCopy (mins, mins2); - VectorCopy (maxs, maxs1); - VectorCopy (maxs, maxs2); + VectorCopy(mins, mins1); + VectorCopy(mins, mins2); + VectorCopy(maxs, maxs1); + VectorCopy(maxs, maxs2); maxs1[anode->axis] = mins2[anode->axis] = anode->dist; - anode->children[0] = SV_CreateworldSector (depth+1, mins2, maxs2); - anode->children[1] = SV_CreateworldSector (depth+1, mins1, maxs1); + anode->children[0] = SV_CreateworldSector(depth + 1, mins2, maxs2); + anode->children[1] = SV_CreateworldSector(depth + 1, mins1, maxs1); return anode; } @@ -148,115 +145,110 @@ SV_ClearWorld =============== */ -void SV_ClearWorld( void ) { - clipHandle_t h; - vec3_t mins, maxs; +void SV_ClearWorld(void) { + clipHandle_t h; + vec3_t mins, maxs; - Com_Memset( sv_worldSectors, 0, sizeof(sv_worldSectors) ); + Com_Memset(sv_worldSectors, 0, sizeof(sv_worldSectors)); sv_numworldSectors = 0; // get world map bounds - h = CM_InlineModel( 0 ); - CM_ModelBounds( h, mins, maxs ); - SV_CreateworldSector( 0, mins, maxs ); + h = CM_InlineModel(0); + CM_ModelBounds(h, mins, maxs); + SV_CreateworldSector(0, mins, maxs); } - /* =============== SV_UnlinkEntity =============== */ -void SV_UnlinkEntity( sharedEntity_t *gEnt ) { - svEntity_t *ent; - svEntity_t *scan; - worldSector_t *ws; +void SV_UnlinkEntity(sharedEntity_t *gEnt) { + svEntity_t *ent; + svEntity_t *scan; + worldSector_t *ws; - ent = SV_SvEntityForGentity( gEnt ); + ent = SV_SvEntityForGentity(gEnt); gEnt->r.linked = qfalse; ws = ent->worldSector; - if ( !ws ) { - return; // not linked in anywhere + if (!ws) { + return; // not linked in anywhere } ent->worldSector = NULL; - if ( ws->entities == ent ) { + if (ws->entities == ent) { ws->entities = ent->nextEntityInWorldSector; return; } - for ( scan = ws->entities ; scan ; scan = scan->nextEntityInWorldSector ) { - if ( scan->nextEntityInWorldSector == ent ) { + for (scan = ws->entities; scan; scan = scan->nextEntityInWorldSector) { + if (scan->nextEntityInWorldSector == ent) { scan->nextEntityInWorldSector = ent->nextEntityInWorldSector; return; } } - Com_Printf( "WARNING: SV_UnlinkEntity: not found in worldSector\n" ); + Com_Printf("WARNING: SV_UnlinkEntity: not found in worldSector\n"); } - /* =============== SV_LinkEntity =============== */ -#define MAX_TOTAL_ENT_LEAFS 128 -void SV_LinkEntity( sharedEntity_t *gEnt ) { - worldSector_t *node; - int leafs[MAX_TOTAL_ENT_LEAFS]; - int cluster; - int num_leafs; - int i, j, k; - int area; - int lastLeaf; - float *origin, *angles; - svEntity_t *ent; - - ent = SV_SvEntityForGentity( gEnt ); - - if ( ent->worldSector ) { - SV_UnlinkEntity( gEnt ); // unlink from old position +#define MAX_TOTAL_ENT_LEAFS 128 +void SV_LinkEntity(sharedEntity_t *gEnt) { + worldSector_t *node; + int leafs[MAX_TOTAL_ENT_LEAFS]; + int cluster; + int num_leafs; + int i, j, k; + int area; + int lastLeaf; + float *origin, *angles; + svEntity_t *ent; + + ent = SV_SvEntityForGentity(gEnt); + + if (ent->worldSector) { + SV_UnlinkEntity(gEnt); // unlink from old position } // encode the size into the entityState_t for client prediction - if ( gEnt->r.bmodel ) { - gEnt->s.solid = SOLID_BMODEL; // a solid_box will never create this value - } else if ( gEnt->r.contents & ( CONTENTS_SOLID | CONTENTS_BODY ) ) { + if (gEnt->r.bmodel) { + gEnt->s.solid = SOLID_BMODEL; // a solid_box will never create this value + } else if (gEnt->r.contents & (CONTENTS_SOLID | CONTENTS_BODY)) { // assume that x/y are equal and symetric i = gEnt->r.maxs[0]; - if (i<1) + if (i < 1) i = 1; - if (i>255) + if (i > 255) i = 255; // z is not symetric j = (-gEnt->r.mins[2]); - if (j<1) + if (j < 1) j = 1; - if (j>255) + if (j > 255) j = 255; // and z maxs can be negative... - k = (gEnt->r.maxs[2]+32); - if (k<1) + k = (gEnt->r.maxs[2] + 32); + if (k < 1) k = 1; - if (k>255) + if (k > 255) k = 255; - gEnt->s.solid = (k<<16) | (j<<8) | i; + gEnt->s.solid = (k << 16) | (j << 8) | i; - if (gEnt->s.solid == SOLID_BMODEL) - { //yikes, this would make everything explode violently. - gEnt->s.solid = (k<<16) | (j<<8) | (i-1); + if (gEnt->s.solid == SOLID_BMODEL) { // yikes, this would make everything explode violently. + gEnt->s.solid = (k << 16) | (j << 8) | (i - 1); } - } - else - { + } else { gEnt->s.solid = 0; } @@ -265,19 +257,19 @@ void SV_LinkEntity( sharedEntity_t *gEnt ) { angles = gEnt->r.currentAngles; // set the abs box - if ( gEnt->r.bmodel && (angles[0] || angles[1] || angles[2]) ) { + if (gEnt->r.bmodel && (angles[0] || angles[1] || angles[2])) { // expand for rotation - float max; + float max; - max = RadiusFromBounds( gEnt->r.mins, gEnt->r.maxs ); - for (i=0 ; i<3 ; i++) { + max = RadiusFromBounds(gEnt->r.mins, gEnt->r.maxs); + for (i = 0; i < 3; i++) { gEnt->r.absmin[i] = origin[i] - max; gEnt->r.absmax[i] = origin[i] + max; } } else { // normal - VectorAdd (origin, gEnt->r.mins, gEnt->r.absmin); - VectorAdd (origin, gEnt->r.maxs, gEnt->r.absmax); + VectorAdd(origin, gEnt->r.mins, gEnt->r.absmin); + VectorAdd(origin, gEnt->r.maxs, gEnt->r.absmax); } // because movement is clipped an epsilon away from an actual edge, @@ -295,27 +287,24 @@ void SV_LinkEntity( sharedEntity_t *gEnt ) { ent->areanum = -1; ent->areanum2 = -1; - //get all leafs, including solids - num_leafs = CM_BoxLeafnums( gEnt->r.absmin, gEnt->r.absmax, - leafs, MAX_TOTAL_ENT_LEAFS, &lastLeaf ); + // get all leafs, including solids + num_leafs = CM_BoxLeafnums(gEnt->r.absmin, gEnt->r.absmax, leafs, MAX_TOTAL_ENT_LEAFS, &lastLeaf); // if none of the leafs were inside the map, the // entity is outside the world and can be considered unlinked - if ( !num_leafs ) { + if (!num_leafs) { return; } // set areas, even from clusters that don't fit in the entity array - for (i=0 ; iareanum != -1 && ent->areanum != area) { if (ent->areanum2 != -1 && ent->areanum2 != area && sv.state == SS_LOADING) { - Com_DPrintf ("Object %i touching 3 areas at %f %f %f\n", - gEnt->s.number, - gEnt->r.absmin[0], gEnt->r.absmin[1], gEnt->r.absmin[2]); + Com_DPrintf("Object %i touching 3 areas at %f %f %f\n", gEnt->s.number, gEnt->r.absmin[0], gEnt->r.absmin[1], gEnt->r.absmin[2]); } ent->areanum2 = area; } else { @@ -326,35 +315,34 @@ void SV_LinkEntity( sharedEntity_t *gEnt ) { // store as many explicit clusters as we can ent->numClusters = 0; - for (i=0 ; i < num_leafs ; i++) { - cluster = CM_LeafCluster( leafs[i] ); - if ( cluster != -1 ) { + for (i = 0; i < num_leafs; i++) { + cluster = CM_LeafCluster(leafs[i]); + if (cluster != -1) { ent->clusternums[ent->numClusters++] = cluster; - if ( ent->numClusters == MAX_ENT_CLUSTERS ) { + if (ent->numClusters == MAX_ENT_CLUSTERS) { break; } } } // store off a last cluster if we need to - if ( i != num_leafs ) { - ent->lastCluster = CM_LeafCluster( lastLeaf ); + if (i != num_leafs) { + ent->lastCluster = CM_LeafCluster(lastLeaf); } gEnt->r.linkcount++; // find the first world sector node that the ent's box crosses node = sv_worldSectors; - while (1) - { + while (1) { if (node->axis == -1) break; - if ( gEnt->r.absmin[node->axis] > node->dist) + if (gEnt->r.absmin[node->axis] > node->dist) node = node->children[0]; - else if ( gEnt->r.absmax[node->axis] < node->dist) + else if (gEnt->r.absmax[node->axis] < node->dist) node = node->children[1]; else - break; // crosses the node + break; // crosses the node } // link it in @@ -376,39 +364,34 @@ bounds. This does NOT mean that they actually touch in the case of bmodels. */ typedef struct areaParms_s { - const float *mins; - const float *maxs; - int *list; - int count, maxcount; + const float *mins; + const float *maxs; + int *list; + int count, maxcount; } areaParms_t; - /* ==================== SV_AreaEntities_r ==================== */ -void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { - svEntity_t *check, *next; +void SV_AreaEntities_r(worldSector_t *node, areaParms_t *ap) { + svEntity_t *check, *next; sharedEntity_t *gcheck; - for ( check = node->entities ; check ; check = next ) { + for (check = node->entities; check; check = next) { next = check->nextEntityInWorldSector; - gcheck = SV_GEntityForSvEntity( check ); + gcheck = SV_GEntityForSvEntity(check); - if ( gcheck->r.absmin[0] > ap->maxs[0] - || gcheck->r.absmin[1] > ap->maxs[1] - || gcheck->r.absmin[2] > ap->maxs[2] - || gcheck->r.absmax[0] < ap->mins[0] - || gcheck->r.absmax[1] < ap->mins[1] - || gcheck->r.absmax[2] < ap->mins[2]) { + if (gcheck->r.absmin[0] > ap->maxs[0] || gcheck->r.absmin[1] > ap->maxs[1] || gcheck->r.absmin[2] > ap->maxs[2] || gcheck->r.absmax[0] < ap->mins[0] || + gcheck->r.absmax[1] < ap->mins[1] || gcheck->r.absmax[2] < ap->mins[2]) { continue; } - if ( ap->count == ap->maxcount ) { - Com_DPrintf ("SV_AreaEntities: MAXCOUNT\n"); + if (ap->count == ap->maxcount) { + Com_DPrintf("SV_AreaEntities: MAXCOUNT\n"); return; } @@ -417,15 +400,15 @@ void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { } if (node->axis == -1) { - return; // terminal node + return; // terminal node } // recurse down both sides - if ( ap->maxs[node->axis] > node->dist ) { - SV_AreaEntities_r ( node->children[0], ap ); + if (ap->maxs[node->axis] > node->dist) { + SV_AreaEntities_r(node->children[0], ap); } - if ( ap->mins[node->axis] < node->dist ) { - SV_AreaEntities_r ( node->children[1], ap ); + if (ap->mins[node->axis] < node->dist) { + SV_AreaEntities_r(node->children[1], ap); } } @@ -434,8 +417,8 @@ void SV_AreaEntities_r( worldSector_t *node, areaParms_t *ap ) { SV_AreaEntities ================ */ -int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount ) { - areaParms_t ap; +int SV_AreaEntities(const vec3_t mins, const vec3_t maxs, int *entityList, int maxcount) { + areaParms_t ap; ap.mins = mins; ap.maxs = maxs; @@ -443,82 +426,75 @@ int SV_AreaEntities( const vec3_t mins, const vec3_t maxs, int *entityList, int ap.count = 0; ap.maxcount = maxcount; - SV_AreaEntities_r( sv_worldSectors, &ap ); + SV_AreaEntities_r(sv_worldSectors, &ap); return ap.count; } - - //=========================================================================== - typedef struct moveclip_s { - vec3_t boxmins, boxmaxs;// enclose the test object along entire move - const float *mins; - const float *maxs; // size of the moving object -/* -Ghoul2 Insert Start -*/ - vec3_t start; - - vec3_t end; - - int passEntityNum; - int contentmask; - int capsule; - - int traceFlags; - int useLod; - trace_t trace; // make sure nothing goes under here for Ghoul2 collision purposes -/* -Ghoul2 Insert End -*/ + vec3_t boxmins, boxmaxs; // enclose the test object along entire move + const float *mins; + const float *maxs; // size of the moving object + /* + Ghoul2 Insert Start + */ + vec3_t start; + + vec3_t end; + + int passEntityNum; + int contentmask; + int capsule; + + int traceFlags; + int useLod; + trace_t trace; // make sure nothing goes under here for Ghoul2 collision purposes + /* + Ghoul2 Insert End + */ } moveclip_t; - /* ==================== SV_ClipToEntity ==================== */ -void SV_ClipToEntity( trace_t *trace, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int entityNum, int contentmask, int capsule ) { - sharedEntity_t *touch; - clipHandle_t clipHandle; - float *origin, *angles; +void SV_ClipToEntity(trace_t *trace, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int entityNum, int contentmask, int capsule) { + sharedEntity_t *touch; + clipHandle_t clipHandle; + float *origin, *angles; - touch = SV_GentityNum( entityNum ); + touch = SV_GentityNum(entityNum); Com_Memset(trace, 0, sizeof(trace_t)); // if it doesn't have any brushes of a type we // are looking for, ignore it - if ( ! ( contentmask & touch->r.contents ) ) { + if (!(contentmask & touch->r.contents)) { trace->fraction = 1.0; return; } // might intersect, so do an exact clip - clipHandle = SV_ClipHandleForEntity (touch); + clipHandle = SV_ClipHandleForEntity(touch); origin = touch->r.currentOrigin; angles = touch->r.currentAngles; - if ( !touch->r.bmodel ) { - angles = vec3_origin; // boxes don't rotate + if (!touch->r.bmodel) { + angles = vec3_origin; // boxes don't rotate } - CM_TransformedBoxTrace ( trace, (float *)start, (float *)end, - (float *)mins, (float *)maxs, clipHandle, contentmask, - origin, angles, capsule); + CM_TransformedBoxTrace(trace, (float *)start, (float *)end, (float *)mins, (float *)maxs, clipHandle, contentmask, origin, angles, capsule); - if ( trace->fraction < 1 ) { + if (trace->fraction < 1) { trace->entityNum = touch->s.number; } } - /* ==================== SV_ClipMoveToEntities @@ -526,8 +502,7 @@ SV_ClipMoveToEntities ==================== */ #ifndef FINAL_BUILD -static float VectorDistance(vec3_t p1, vec3_t p2) -{ +static float VectorDistance(vec3_t p1, vec3_t p2) { vec3_t dir; VectorSubtract(p2, p1, dir); @@ -535,116 +510,103 @@ static float VectorDistance(vec3_t p1, vec3_t p2) } #endif -static void SV_ClipMoveToEntities( moveclip_t *clip ) { - static int touchlist[MAX_GENTITIES]; - int i, num; +static void SV_ClipMoveToEntities(moveclip_t *clip) { + static int touchlist[MAX_GENTITIES]; + int i, num; sharedEntity_t *touch; - int passOwnerNum; - trace_t trace, oldTrace= {0}; - clipHandle_t clipHandle; - float *origin, *angles; - int thisOwnerShared = 1; + int passOwnerNum; + trace_t trace, oldTrace = {0}; + clipHandle_t clipHandle; + float *origin, *angles; + int thisOwnerShared = 1; - num = SV_AreaEntities( clip->boxmins, clip->boxmaxs, touchlist, MAX_GENTITIES); + num = SV_AreaEntities(clip->boxmins, clip->boxmaxs, touchlist, MAX_GENTITIES); - if ( clip->passEntityNum != ENTITYNUM_NONE ) { - passOwnerNum = ( SV_GentityNum( clip->passEntityNum ) )->r.ownerNum; - if ( passOwnerNum == ENTITYNUM_NONE ) { + if (clip->passEntityNum != ENTITYNUM_NONE) { + passOwnerNum = (SV_GentityNum(clip->passEntityNum))->r.ownerNum; + if (passOwnerNum == ENTITYNUM_NONE) { passOwnerNum = -1; } } else { passOwnerNum = -1; } - if ( SV_GentityNum(clip->passEntityNum)->r.svFlags & SVF_OWNERNOTSHARED ) - { + if (SV_GentityNum(clip->passEntityNum)->r.svFlags & SVF_OWNERNOTSHARED) { thisOwnerShared = 0; } - for ( i=0 ; itrace.allsolid ) { + for (i = 0; i < num; i++) { + if (clip->trace.allsolid) { return; } - touch = SV_GentityNum( touchlist[i] ); + touch = SV_GentityNum(touchlist[i]); // see if we should ignore this entity - if ( clip->passEntityNum != ENTITYNUM_NONE ) { - if ( touchlist[i] == clip->passEntityNum ) { - continue; // don't clip against the pass entity + if (clip->passEntityNum != ENTITYNUM_NONE) { + if (touchlist[i] == clip->passEntityNum) { + continue; // don't clip against the pass entity } - if ( touch->r.ownerNum == clip->passEntityNum) { - if (touch->r.svFlags & SVF_OWNERNOTSHARED) - { - if ( clip->contentmask != (MASK_SHOT | CONTENTS_LIGHTSABER) && - clip->contentmask != (MASK_SHOT)) - { //it's not a laser hitting the other "missile", don't care then + if (touch->r.ownerNum == clip->passEntityNum) { + if (touch->r.svFlags & SVF_OWNERNOTSHARED) { + if (clip->contentmask != (MASK_SHOT | CONTENTS_LIGHTSABER) && + clip->contentmask != (MASK_SHOT)) { // it's not a laser hitting the other "missile", don't care then continue; } - } - else - { - continue; // don't clip against own missiles + } else { + continue; // don't clip against own missiles } } - if ( touch->r.ownerNum == passOwnerNum && - !(touch->r.svFlags & SVF_OWNERNOTSHARED) && - thisOwnerShared ) { - continue; // don't clip against other missiles from our owner + if (touch->r.ownerNum == passOwnerNum && !(touch->r.svFlags & SVF_OWNERNOTSHARED) && thisOwnerShared) { + continue; // don't clip against other missiles from our owner } - if (touch->s.eType == ET_MISSILE && - !(touch->r.svFlags & SVF_OWNERNOTSHARED) && - touch->r.ownerNum == passOwnerNum) - { //blah, hack + if (touch->s.eType == ET_MISSILE && !(touch->r.svFlags & SVF_OWNERNOTSHARED) && touch->r.ownerNum == passOwnerNum) { // blah, hack continue; } } // if it doesn't have any brushes of a type we // are looking for, ignore it - if ( ! ( clip->contentmask & touch->r.contents ) ) { + if (!(clip->contentmask & touch->r.contents)) { continue; } - if ((clip->contentmask == (MASK_SHOT|CONTENTS_LIGHTSABER) || clip->contentmask == MASK_SHOT) && (touch->r.contents > 0 && (touch->r.contents & CONTENTS_NOSHOT))) - { + if ((clip->contentmask == (MASK_SHOT | CONTENTS_LIGHTSABER) || clip->contentmask == MASK_SHOT) && + (touch->r.contents > 0 && (touch->r.contents & CONTENTS_NOSHOT))) { continue; } // might intersect, so do an exact clip - clipHandle = SV_ClipHandleForEntity (touch); + clipHandle = SV_ClipHandleForEntity(touch); origin = touch->r.currentOrigin; angles = touch->r.currentAngles; - - if ( !touch->r.bmodel ) { - angles = vec3_origin; // boxes don't rotate + if (!touch->r.bmodel) { + angles = vec3_origin; // boxes don't rotate } - CM_TransformedBoxTrace ( &trace, (float *)clip->start, (float *)clip->end, - (float *)clip->mins, (float *)clip->maxs, clipHandle, clip->contentmask, - origin, angles, clip->capsule); - + CM_TransformedBoxTrace(&trace, (float *)clip->start, (float *)clip->end, (float *)clip->mins, (float *)clip->maxs, clipHandle, clip->contentmask, + origin, angles, clip->capsule); - if (clip->traceFlags & G2TRFLAG_DOGHOULTRACE) - { // keep these older variables around for a bit, incase we need to replace them in the Ghoul2 Collision check + if (clip->traceFlags & + G2TRFLAG_DOGHOULTRACE) { // keep these older variables around for a bit, incase we need to replace them in the Ghoul2 Collision check oldTrace = clip->trace; } - if ( trace.allsolid ) { + if (trace.allsolid) { clip->trace.allsolid = qtrue; trace.entityNum = touch->s.number; - } else if ( trace.startsolid ) { + } else if (trace.startsolid) { clip->trace.startsolid = qtrue; trace.entityNum = touch->s.number; - //rww - added this because we want to get the number of an ent even if our trace starts inside it. + // rww - added this because we want to get the number of an ent even if our trace starts inside it. clip->trace.entityNum = touch->s.number; } - if ( trace.fraction < clip->trace.fraction ) { - byte oldStart; + if (trace.fraction < clip->trace.fraction) { + byte oldStart; // make sure we keep a startsolid from a previous trace oldStart = clip->trace.startsolid; @@ -701,106 +663,87 @@ Ghoul2 Insert Start } } #else - //rww - since this is multiplayer and we don't have the luxury of violating networking rules in horrible ways, - //this must be done somewhat differently. - if ((clip->traceFlags & G2TRFLAG_DOGHOULTRACE) && trace.entityNum == touch->s.number && touch->ghoul2 && ((clip->traceFlags & G2TRFLAG_HITCORPSES) || !(touch->s.eFlags & EF_DEAD))) - { //standard behavior will be to ignore g2 col on dead ents, but if traceFlags is set to allow, then we'll try g2 col on EF_DEAD people too. + // rww - since this is multiplayer and we don't have the luxury of violating networking rules in horrible ways, + // this must be done somewhat differently. + if ((clip->traceFlags & G2TRFLAG_DOGHOULTRACE) && trace.entityNum == touch->s.number && touch->ghoul2 && + ((clip->traceFlags & G2TRFLAG_HITCORPSES) || + !(touch->s.eFlags & EF_DEAD))) { // standard behavior will be to ignore g2 col on dead ents, but if traceFlags is set to allow, then we'll try g2 + // col on EF_DEAD people too. static G2Trace_t G2Trace; vec3_t angles; float fRadius = 0.0f; int tN = 0; int bestTr = -1; - if (clip->mins[0] || - clip->maxs[0]) - { - fRadius=(clip->maxs[0]-clip->mins[0])/2.0f; + if (clip->mins[0] || clip->maxs[0]) { + fRadius = (clip->maxs[0] - clip->mins[0]) / 2.0f; } - if (clip->traceFlags & G2TRFLAG_THICK) - { //if using this flag, make sure it's at least 1.0f - if (fRadius < 1.0f) - { + if (clip->traceFlags & G2TRFLAG_THICK) { // if using this flag, make sure it's at least 1.0f + if (fRadius < 1.0f) { fRadius = 1.0f; } } - memset (&G2Trace, 0, sizeof(G2Trace)); - while (tN < MAX_G2_COLLISIONS) - { + memset(&G2Trace, 0, sizeof(G2Trace)); + while (tN < MAX_G2_COLLISIONS) { G2Trace[tN].mEntityNum = -1; tN++; } - if (touch->s.number < MAX_CLIENTS) - { + if (touch->s.number < MAX_CLIENTS) { VectorCopy(touch->s.apos.trBase, angles); - } - else - { + } else { VectorCopy(touch->r.currentAngles, angles); } angles[ROLL] = angles[PITCH] = 0; - //I would think that you could trace from trace.endpos instead of clip->start, but that causes it to miss sometimes.. Not sure what it's off, but if it could be done like that, it would probably - //be faster. + // I would think that you could trace from trace.endpos instead of clip->start, but that causes it to miss sometimes.. Not sure what it's off, but + // if it could be done like that, it would probably be faster. #ifndef FINAL_BUILD - if (sv_showghoultraces->integer) - { - Com_Printf( "Ghoul2 trace lod=%1d length=%6.0f to %s\n",clip->useLod,VectorDistance(clip->start, clip->end), re->G2API_GetModelName (*(CGhoul2Info_v *)touch->ghoul2, 0)); + if (sv_showghoultraces->integer) { + Com_Printf("Ghoul2 trace lod=%1d length=%6.0f to %s\n", clip->useLod, VectorDistance(clip->start, clip->end), + re->G2API_GetModelName(*(CGhoul2Info_v *)touch->ghoul2, 0)); } #endif - if (com_optvehtrace && - com_optvehtrace->integer && - touch->s.eType == ET_NPC && - touch->s.NPC_class == CLASS_VEHICLE && - touch->m_pVehicle) - { //for vehicles cache the transform data. - re->G2API_CollisionDetectCache(G2Trace, *((CGhoul2Info_v *)touch->ghoul2), angles, touch->r.currentOrigin, sv.time, touch->s.number, clip->start, clip->end, touch->modelScale, G2VertSpaceServer, 0, clip->useLod, fRadius); - } - else - { - re->G2API_CollisionDetect(G2Trace, *((CGhoul2Info_v *)touch->ghoul2), angles, touch->r.currentOrigin, sv.time, touch->s.number, clip->start, clip->end, touch->modelScale, G2VertSpaceServer, 0, clip->useLod, fRadius); + if (com_optvehtrace && com_optvehtrace->integer && touch->s.eType == ET_NPC && touch->s.NPC_class == CLASS_VEHICLE && + touch->m_pVehicle) { // for vehicles cache the transform data. + re->G2API_CollisionDetectCache(G2Trace, *((CGhoul2Info_v *)touch->ghoul2), angles, touch->r.currentOrigin, sv.time, touch->s.number, + clip->start, clip->end, touch->modelScale, G2VertSpaceServer, 0, clip->useLod, fRadius); + } else { + re->G2API_CollisionDetect(G2Trace, *((CGhoul2Info_v *)touch->ghoul2), angles, touch->r.currentOrigin, sv.time, touch->s.number, clip->start, + clip->end, touch->modelScale, G2VertSpaceServer, 0, clip->useLod, fRadius); } tN = 0; - while (tN < MAX_G2_COLLISIONS) - { - if (G2Trace[tN].mEntityNum == touch->s.number) - { //ok, valid + while (tN < MAX_G2_COLLISIONS) { + if (G2Trace[tN].mEntityNum == touch->s.number) { // ok, valid bestTr = tN; break; - } - else if (G2Trace[tN].mEntityNum == -1) - { //there should not be any after the first -1 + } else if (G2Trace[tN].mEntityNum == -1) { // there should not be any after the first -1 break; } tN++; } - if (bestTr == -1) - { //Well then, put the trace back to the old one. + if (bestTr == -1) { // Well then, put the trace back to the old one. clip->trace = oldTrace; - } - else - { //Otherwise, set the endpos/normal/etc. to the model location hit instead of leaving it out in space. + } else { // Otherwise, set the endpos/normal/etc. to the model location hit instead of leaving it out in space. VectorCopy(G2Trace[bestTr].mCollisionPosition, clip->trace.endpos); VectorCopy(G2Trace[bestTr].mCollisionNormal, clip->trace.plane.normal); - if (clip->traceFlags & G2TRFLAG_GETSURFINDEX) - { //we have requested that surfaceFlags be stomped over with the g2 hit surface index. - if (clip->trace.entityNum == G2Trace[bestTr].mEntityNum) - { + if (clip->traceFlags & G2TRFLAG_GETSURFINDEX) { // we have requested that surfaceFlags be stomped over with the g2 hit surface index. + if (clip->trace.entityNum == G2Trace[bestTr].mEntityNum) { clip->trace.surfaceFlags = G2Trace[bestTr].mSurfaceIndex; } } } } #endif -/* -Ghoul2 Insert End -*/ + /* + Ghoul2 Insert End + */ } } @@ -815,42 +758,43 @@ passEntityNum and entities owned by passEntityNum are explicitly not checked. /* Ghoul2 Insert Start */ -void SV_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule, int traceFlags, int useLod ) { -/* -Ghoul2 Insert End -*/ - moveclip_t clip; - int i; - - if ( !mins ) { +void SV_Trace(trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int passEntityNum, int contentmask, int capsule, + int traceFlags, int useLod) { + /* + Ghoul2 Insert End + */ + moveclip_t clip; + int i; + + if (!mins) { mins = vec3_origin; } - if ( !maxs ) { + if (!maxs) { maxs = vec3_origin; } - Com_Memset ( &clip, 0, sizeof ( moveclip_t ) ); + Com_Memset(&clip, 0, sizeof(moveclip_t)); // clip to world - CM_BoxTrace( &clip.trace, start, end, mins, maxs, 0, contentmask, capsule ); + CM_BoxTrace(&clip.trace, start, end, mins, maxs, 0, contentmask, capsule); clip.trace.entityNum = clip.trace.fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; - if ( clip.trace.fraction == 0 ) { + if (clip.trace.fraction == 0) { *results = clip.trace; - return; // blocked immediately by the world + return; // blocked immediately by the world } clip.contentmask = contentmask; -/* -Ghoul2 Insert Start -*/ - VectorCopy( start, clip.start ); + /* + Ghoul2 Insert Start + */ + VectorCopy(start, clip.start); clip.traceFlags = traceFlags; clip.useLod = useLod; -/* -Ghoul2 Insert End -*/ -// VectorCopy( clip.trace.endpos, clip.end ); - VectorCopy( end, clip.end ); + /* + Ghoul2 Insert End + */ + // VectorCopy( clip.trace.endpos, clip.end ); + VectorCopy(end, clip.end); clip.mins = mins; clip.maxs = maxs; clip.passEntityNum = passEntityNum; @@ -860,8 +804,8 @@ Ghoul2 Insert End // we can limit it to the part of the move not // already clipped off by the world, which can be // a significant savings for line of sight and shot traces - for ( i=0 ; i<3 ; i++ ) { - if ( end[i] > start[i] ) { + for (i = 0; i < 3; i++) { + if (end[i] > start[i]) { clip.boxmins[i] = clip.start[i] + clip.mins[i] - 1; clip.boxmaxs[i] = clip.end[i] + clip.maxs[i] + 1; } else { @@ -871,45 +815,41 @@ Ghoul2 Insert End } // clip to other solid entities - SV_ClipMoveToEntities ( &clip ); + SV_ClipMoveToEntities(&clip); *results = clip.trace; } - - /* ============= SV_PointContents ============= */ -int SV_PointContents( const vec3_t p, int passEntityNum ) { - int touch[MAX_GENTITIES]; +int SV_PointContents(const vec3_t p, int passEntityNum) { + int touch[MAX_GENTITIES]; sharedEntity_t *hit; - int i, num; - int contents, c2; - clipHandle_t clipHandle; + int i, num; + int contents, c2; + clipHandle_t clipHandle; // get base contents from world - contents = CM_PointContents( p, 0 ); + contents = CM_PointContents(p, 0); // or in contents from all the other entities - num = SV_AreaEntities( p, p, touch, MAX_GENTITIES ); + num = SV_AreaEntities(p, p, touch, MAX_GENTITIES); - for ( i=0 ; ir.currentOrigin, hit->r.currentAngles); + c2 = CM_TransformedPointContents(p, clipHandle, hit->r.currentOrigin, hit->r.currentAngles); contents |= c2; } return contents; } - - diff --git a/codemp/ui/ui_atoms.c b/codemp/ui/ui_atoms.c index b9703a73aa..a8d7fb9c04 100644 --- a/codemp/ui/ui_atoms.c +++ b/codemp/ui/ui_atoms.c @@ -29,69 +29,63 @@ along with this program; if not, see . #include "ui_local.h" #define NUM_UI_ARGSTRS (4) -#define UI_ARGSTR_MASK (NUM_UI_ARGSTRS-1) +#define UI_ARGSTR_MASK (NUM_UI_ARGSTRS - 1) static char tempArgStrs[NUM_UI_ARGSTRS][MAX_STRING_CHARS]; -static char *UI_Argv( int arg ) { - static int index=0; +static char *UI_Argv(int arg) { + static int index = 0; char *s = tempArgStrs[index++ & UI_ARGSTR_MASK]; - trap->Cmd_Argv( arg, s, MAX_STRING_CHARS ); + trap->Cmd_Argv(arg, s, MAX_STRING_CHARS); return s; } #define NUM_UI_CVARSTRS (4) -#define UI_CVARSTR_MASK (NUM_UI_CVARSTRS-1) +#define UI_CVARSTR_MASK (NUM_UI_CVARSTRS - 1) static char tempCvarStrs[NUM_UI_CVARSTRS][MAX_CVAR_VALUE_STRING]; -char *UI_Cvar_VariableString( const char *name ) { - static int index=0; +char *UI_Cvar_VariableString(const char *name) { + static int index = 0; char *s = tempCvarStrs[index++ & UI_ARGSTR_MASK]; - trap->Cvar_VariableStringBuffer( name, s, MAX_CVAR_VALUE_STRING ); + trap->Cvar_VariableStringBuffer(name, s, MAX_CVAR_VALUE_STRING); return s; } -static void UI_Cache_f( void ) { +static void UI_Cache_f(void) { Display_CacheAll(); - if ( trap->Cmd_Argc() == 2 ) { + if (trap->Cmd_Argc() == 2) { int i; - for ( i=0; iPrint( "model %s\n", uiInfo.q3HeadNames[i] ); + for (i = 0; i < uiInfo.q3HeadCount; i++) { + trap->Print("model %s\n", uiInfo.q3HeadNames[i]); } } } -static void UI_OpenMenu_f( void ) { +static void UI_OpenMenu_f(void) { Menus_CloseAll(); - if ( Menus_ActivateByName( UI_Argv( 1 ) ) ) - trap->Key_SetCatcher( KEYCATCH_UI ); + if (Menus_ActivateByName(UI_Argv(1))) + trap->Key_SetCatcher(KEYCATCH_UI); } -static void UI_OpenSiegeMenu_f( void ) { - if ( trap->Cvar_VariableValue( "g_gametype" ) == GT_SIEGE ) { +static void UI_OpenSiegeMenu_f(void) { + if (trap->Cvar_VariableValue("g_gametype") == GT_SIEGE) { Menus_CloseAll(); - if ( Menus_ActivateByName( UI_Argv( 1 ) ) ) - trap->Key_SetCatcher( KEYCATCH_UI ); + if (Menus_ActivateByName(UI_Argv(1))) + trap->Key_SetCatcher(KEYCATCH_UI); } } typedef struct consoleCommand_s { - const char *cmd; - void (*func)(void); + const char *cmd; + void (*func)(void); } consoleCommand_t; -int cmdcmp( const void *a, const void *b ) { - return Q_stricmp( (const char *)a, ((consoleCommand_t*)b)->cmd ); -} +int cmdcmp(const void *a, const void *b) { return Q_stricmp((const char *)a, ((consoleCommand_t *)b)->cmd); } -static consoleCommand_t commands[] = { - { "ui_cache", UI_Cache_f }, - { "ui_load", UI_Load }, - { "ui_openmenu", UI_OpenMenu_f }, - { "ui_opensiegemenu", UI_OpenSiegeMenu_f }, - { "ui_report", UI_Report }, +static consoleCommand_t commands[] = { + {"ui_cache", UI_Cache_f}, {"ui_load", UI_Load}, {"ui_openmenu", UI_OpenMenu_f}, {"ui_opensiegemenu", UI_OpenSiegeMenu_f}, {"ui_report", UI_Report}, }; -static const size_t numCommands = ARRAY_LEN( commands ); +static const size_t numCommands = ARRAY_LEN(commands); /* ================= @@ -101,48 +95,46 @@ The string has been tokenized and can be retrieved with Cmd_Argc() / Cmd_Argv() ================= */ -qboolean UI_ConsoleCommand( int realTime ) { +qboolean UI_ConsoleCommand(int realTime) { consoleCommand_t *command = NULL; uiInfo.uiDC.frameTime = realTime - uiInfo.uiDC.realTime; uiInfo.uiDC.realTime = realTime; - command = (consoleCommand_t *)Q_LinearSearch( UI_Argv( 0 ), commands, numCommands, sizeof( commands[0] ), cmdcmp ); + command = (consoleCommand_t *)Q_LinearSearch(UI_Argv(0), commands, numCommands, sizeof(commands[0]), cmdcmp); - if ( !command ) + if (!command) return qfalse; command->func(); return qtrue; } -void UI_DrawHandlePic( float x, float y, float w, float h, qhandle_t hShader ) { - float s0; - float s1; - float t0; - float t1; +void UI_DrawHandlePic(float x, float y, float w, float h, qhandle_t hShader) { + float s0; + float s1; + float t0; + float t1; - if( w < 0 ) { // flip about vertical - w = -w; + if (w < 0) { // flip about vertical + w = -w; s0 = 1; s1 = 0; - } - else { + } else { s0 = 0; s1 = 1; } - if( h < 0 ) { // flip about horizontal - h = -h; + if (h < 0) { // flip about horizontal + h = -h; t0 = 1; t1 = 0; - } - else { + } else { t0 = 0; t1 = 1; } - trap->R_DrawStretchPic( x, y, w, h, s0, t0, s1, t1, hShader ); + trap->R_DrawStretchPic(x, y, w, h, s0, t0, s1, t1, hShader); } /* @@ -152,20 +144,20 @@ UI_FillRect Coordinates are 640*480 virtual values ================= */ -void UI_FillRect( float x, float y, float width, float height, const float *color ) { - trap->R_SetColor( color ); - trap->R_DrawStretchPic( x, y, width, height, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap->R_SetColor( NULL ); +void UI_FillRect(float x, float y, float width, float height, const float *color) { + trap->R_SetColor(color); + trap->R_DrawStretchPic(x, y, width, height, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap->R_SetColor(NULL); } void UI_DrawSides(float x, float y, float w, float h) { - trap->R_DrawStretchPic( x, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap->R_DrawStretchPic( x + w - 1, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap->R_DrawStretchPic(x, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap->R_DrawStretchPic(x + w - 1, y, 1, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } void UI_DrawTopBottom(float x, float y, float w, float h) { - trap->R_DrawStretchPic( x, y, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap->R_DrawStretchPic( x, y + h - 1, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap->R_DrawStretchPic(x, y, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap->R_DrawStretchPic(x, y + h - 1, w, 1, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } /* ================ @@ -174,11 +166,11 @@ UI_DrawRect Coordinates are 640*480 virtual values ================= */ -void UI_DrawRect( float x, float y, float width, float height, const float *color ) { - trap->R_SetColor( color ); +void UI_DrawRect(float x, float y, float width, float height, const float *color) { + trap->R_SetColor(color); UI_DrawTopBottom(x, y, width, height); UI_DrawSides(x, y, width, height); - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } diff --git a/codemp/ui/ui_cvar.c b/codemp/ui/ui_cvar.c index 3b9cf3b289..eeeaa1b6d8 100644 --- a/codemp/ui/ui_cvar.c +++ b/codemp/ui/ui_cvar.c @@ -27,21 +27,19 @@ along with this program; if not, see . // Cvar callbacks // -static int UI_GetScreenshotFormatForString( const char *str ) { - if ( !Q_stricmp(str, "jpg") || !Q_stricmp(str, "jpeg") ) +static int UI_GetScreenshotFormatForString(const char *str) { + if (!Q_stricmp(str, "jpg") || !Q_stricmp(str, "jpeg")) return SSF_JPEG; - else if ( !Q_stricmp(str, "tga") ) + else if (!Q_stricmp(str, "tga")) return SSF_TGA; - else if ( !Q_stricmp(str, "png") ) + else if (!Q_stricmp(str, "png")) return SSF_PNG; else return -1; } -static const char *UI_GetScreenshotFormatString( int format ) -{ - switch ( format ) - { +static const char *UI_GetScreenshotFormatString(int format) { + switch (format) { default: case SSF_JPEG: return "jpg"; @@ -52,84 +50,76 @@ static const char *UI_GetScreenshotFormatString( int format ) } } -static void UI_UpdateScreenshot( void ) -{ +static void UI_UpdateScreenshot(void) { qboolean changed = qfalse; // check some things - if ( ui_screenshotType.string[0] && isalpha( ui_screenshotType.string[0] ) ) - { - int ssf = UI_GetScreenshotFormatForString( ui_screenshotType.string ); - if ( ssf == -1 ) - { - trap->Print( "UI Screenshot Format Type '%s' unrecognised, defaulting to JPEG\n", ui_screenshotType.string ); + if (ui_screenshotType.string[0] && isalpha(ui_screenshotType.string[0])) { + int ssf = UI_GetScreenshotFormatForString(ui_screenshotType.string); + if (ssf == -1) { + trap->Print("UI Screenshot Format Type '%s' unrecognised, defaulting to JPEG\n", ui_screenshotType.string); uiInfo.uiDC.screenshotFormat = SSF_JPEG; changed = qtrue; - } - else + } else uiInfo.uiDC.screenshotFormat = ssf; - } - else if ( ui_screenshotType.integer < SSF_JPEG || ui_screenshotType.integer > SSF_PNG ) - { - trap->Print( "ui_screenshotType %i is out of range, defaulting to 0 (JPEG)\n", ui_screenshotType.integer ); + } else if (ui_screenshotType.integer < SSF_JPEG || ui_screenshotType.integer > SSF_PNG) { + trap->Print("ui_screenshotType %i is out of range, defaulting to 0 (JPEG)\n", ui_screenshotType.integer); uiInfo.uiDC.screenshotFormat = SSF_JPEG; changed = qtrue; - } - else { - uiInfo.uiDC.screenshotFormat = atoi( ui_screenshotType.string ); + } else { + uiInfo.uiDC.screenshotFormat = atoi(ui_screenshotType.string); changed = qtrue; } - if ( changed ) { - trap->Cvar_Set( "ui_screenshotType", UI_GetScreenshotFormatString( uiInfo.uiDC.screenshotFormat ) ); - trap->Cvar_Update( &ui_screenshotType ); + if (changed) { + trap->Cvar_Set("ui_screenshotType", UI_GetScreenshotFormatString(uiInfo.uiDC.screenshotFormat)); + trap->Cvar_Update(&ui_screenshotType); } } - // // Cvar table // typedef struct cvarTable_s { - vmCvar_t *vmCvar; - char *cvarName; - char *defaultString; - void (*update)( void ); - uint32_t cvarFlags; + vmCvar_t *vmCvar; + char *cvarName; + char *defaultString; + void (*update)(void); + uint32_t cvarFlags; } cvarTable_t; #define XCVAR_DECL - #include "ui_xcvar.h" +#include "ui_xcvar.h" #undef XCVAR_DECL static const cvarTable_t uiCvarTable[] = { - #define XCVAR_LIST - #include "ui_xcvar.h" - #undef XCVAR_LIST +#define XCVAR_LIST +#include "ui_xcvar.h" +#undef XCVAR_LIST }; -static const size_t uiCvarTableSize = ARRAY_LEN( uiCvarTable ); +static const size_t uiCvarTableSize = ARRAY_LEN(uiCvarTable); -void UI_RegisterCvars( void ) { +void UI_RegisterCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=uiCvarTable; iCvar_Register( cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags ); - if ( cv->update ) + for (i = 0, cv = uiCvarTable; i < uiCvarTableSize; i++, cv++) { + trap->Cvar_Register(cv->vmCvar, cv->cvarName, cv->defaultString, cv->cvarFlags); + if (cv->update) cv->update(); } } -void UI_UpdateCvars( void ) { +void UI_UpdateCvars(void) { size_t i = 0; const cvarTable_t *cv = NULL; - for ( i=0, cv=uiCvarTable; ivmCvar ) { + for (i = 0, cv = uiCvarTable; i < uiCvarTableSize; i++, cv++) { + if (cv->vmCvar) { int modCount = cv->vmCvar->modificationCount; - trap->Cvar_Update( cv->vmCvar ); - if ( cv->vmCvar->modificationCount != modCount ) { - if ( cv->update ) + trap->Cvar_Update(cv->vmCvar); + if (cv->vmCvar->modificationCount != modCount) { + if (cv->update) cv->update(); } } diff --git a/codemp/ui/ui_force.c b/codemp/ui/ui_force.c index 898ad36880..16c72998bd 100644 --- a/codemp/ui/ui_force.c +++ b/codemp/ui/ui_force.c @@ -38,8 +38,8 @@ int uiJediNonJedi = -1; int uiForceRank = FORCE_MASTERY_JEDI_KNIGHT; int uiMaxRank = MAX_FORCE_RANK; int uiMaxPoints = 20; -int uiForceUsed = 0; -int uiForceAvailable=0; +int uiForceUsed = 0; +int uiForceAvailable = 0; extern const char *UI_TeamName(int team); @@ -48,74 +48,74 @@ qboolean gTouchedForce = qfalse; void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow); qboolean uiForcePowersDisabled[NUM_FORCE_POWERS] = { - qfalse,//FP_HEAL,//instant - qfalse,//FP_LEVITATION,//hold/duration - qfalse,//FP_SPEED,//duration - qfalse,//FP_PUSH,//hold/duration - qfalse,//FP_PULL,//hold/duration - qfalse,//FP_TELEPATHY,//instant - qfalse,//FP_GRIP,//hold/duration - qfalse,//FP_LIGHTNING,//hold/duration - qfalse,//FP_RAGE,//duration - qfalse,//FP_PROTECT, - qfalse,//FP_ABSORB, - qfalse,//FP_TEAM_HEAL, - qfalse,//FP_TEAM_FORCE, - qfalse,//FP_DRAIN, - qfalse,//FP_SEE, - qfalse,//FP_SABER_OFFENSE, - qfalse,//FP_SABER_DEFENSE, - qfalse//FP_SABERTHROW, + qfalse, // FP_HEAL,//instant + qfalse, // FP_LEVITATION,//hold/duration + qfalse, // FP_SPEED,//duration + qfalse, // FP_PUSH,//hold/duration + qfalse, // FP_PULL,//hold/duration + qfalse, // FP_TELEPATHY,//instant + qfalse, // FP_GRIP,//hold/duration + qfalse, // FP_LIGHTNING,//hold/duration + qfalse, // FP_RAGE,//duration + qfalse, // FP_PROTECT, + qfalse, // FP_ABSORB, + qfalse, // FP_TEAM_HEAL, + qfalse, // FP_TEAM_FORCE, + qfalse, // FP_DRAIN, + qfalse, // FP_SEE, + qfalse, // FP_SABER_OFFENSE, + qfalse, // FP_SABER_DEFENSE, + qfalse // FP_SABERTHROW, }; int uiForcePowersRank[NUM_FORCE_POWERS] = { - 0,//FP_HEAL = 0,//instant - 1,//FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point) - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - 0,//FP_TELEPATHY,//instant - 0,//FP_GRIP,//hold/duration - 0,//FP_LIGHTNING,//hold/duration - 0,//FP_RAGE,//duration - 0,//FP_PROTECT, - 0,//FP_ABSORB, - 0,//FP_TEAM_HEAL, - 0,//FP_TEAM_FORCE, - 0,//FP_DRAIN, - 0,//FP_SEE, - 1,//FP_SABER_OFFENSE, //default to 1 point in attack - 1,//FP_SABER_DEFENSE, //defualt to 1 point in defense - 0//FP_SABERTHROW, + 0, // FP_HEAL = 0,//instant + 1, // FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point) + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + 0, // FP_TELEPATHY,//instant + 0, // FP_GRIP,//hold/duration + 0, // FP_LIGHTNING,//hold/duration + 0, // FP_RAGE,//duration + 0, // FP_PROTECT, + 0, // FP_ABSORB, + 0, // FP_TEAM_HEAL, + 0, // FP_TEAM_FORCE, + 0, // FP_DRAIN, + 0, // FP_SEE, + 1, // FP_SABER_OFFENSE, //default to 1 point in attack + 1, // FP_SABER_DEFENSE, //defualt to 1 point in defense + 0 // FP_SABERTHROW, }; -int uiForcePowerDarkLight[NUM_FORCE_POWERS] = //0 == neutral -{ //nothing should be usable at rank 0.. - FORCE_LIGHTSIDE,//FP_HEAL,//instant - 0,//FP_LEVITATION,//hold/duration - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - FORCE_LIGHTSIDE,//FP_TELEPATHY,//instant - FORCE_DARKSIDE,//FP_GRIP,//hold/duration - FORCE_DARKSIDE,//FP_LIGHTNING,//hold/duration - FORCE_DARKSIDE,//FP_RAGE,//duration - FORCE_LIGHTSIDE,//FP_PROTECT,//duration - FORCE_LIGHTSIDE,//FP_ABSORB,//duration - FORCE_LIGHTSIDE,//FP_TEAM_HEAL,//instant - FORCE_DARKSIDE,//FP_TEAM_FORCE,//instant - FORCE_DARKSIDE,//FP_DRAIN,//hold/duration - 0,//FP_SEE,//duration - 0,//FP_SABER_OFFENSE, - 0,//FP_SABER_DEFENSE, - 0//FP_SABERTHROW, - //NUM_FORCE_POWERS +int uiForcePowerDarkLight[NUM_FORCE_POWERS] = // 0 == neutral + { + // nothing should be usable at rank 0.. + FORCE_LIGHTSIDE, // FP_HEAL,//instant + 0, // FP_LEVITATION,//hold/duration + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + FORCE_LIGHTSIDE, // FP_TELEPATHY,//instant + FORCE_DARKSIDE, // FP_GRIP,//hold/duration + FORCE_DARKSIDE, // FP_LIGHTNING,//hold/duration + FORCE_DARKSIDE, // FP_RAGE,//duration + FORCE_LIGHTSIDE, // FP_PROTECT,//duration + FORCE_LIGHTSIDE, // FP_ABSORB,//duration + FORCE_LIGHTSIDE, // FP_TEAM_HEAL,//instant + FORCE_DARKSIDE, // FP_TEAM_FORCE,//instant + FORCE_DARKSIDE, // FP_DRAIN,//hold/duration + 0, // FP_SEE,//duration + 0, // FP_SABER_OFFENSE, + 0, // FP_SABER_DEFENSE, + 0 // FP_SABERTHROW, + // NUM_FORCE_POWERS }; int uiForceStarShaders[NUM_FORCE_STAR_IMAGES][2]; int uiSaberColorShaders[NUM_SABER_COLORS]; -void UI_InitForceShaders(void) -{ +void UI_InitForceShaders(void) { uiForceStarShaders[0][0] = trap->R_RegisterShaderNoMip("forcestar0"); uiForceStarShaders[0][1] = trap->R_RegisterShaderNoMip("forcestar0"); uiForceStarShaders[1][0] = trap->R_RegisterShaderNoMip("forcecircle1"); @@ -135,51 +135,43 @@ void UI_InitForceShaders(void) uiForceStarShaders[8][0] = trap->R_RegisterShaderNoMip("forcecircle8"); uiForceStarShaders[8][1] = trap->R_RegisterShaderNoMip("forcestar8"); - uiSaberColorShaders[SABER_RED] = trap->R_RegisterShaderNoMip("menu/art/saber_red"); - uiSaberColorShaders[SABER_ORANGE] = trap->R_RegisterShaderNoMip("menu/art/saber_orange"); - uiSaberColorShaders[SABER_YELLOW] = trap->R_RegisterShaderNoMip("menu/art/saber_yellow"); - uiSaberColorShaders[SABER_GREEN] = trap->R_RegisterShaderNoMip("menu/art/saber_green"); - uiSaberColorShaders[SABER_BLUE] = trap->R_RegisterShaderNoMip("menu/art/saber_blue"); - uiSaberColorShaders[SABER_PURPLE] = trap->R_RegisterShaderNoMip("menu/art/saber_purple"); + uiSaberColorShaders[SABER_RED] = trap->R_RegisterShaderNoMip("menu/art/saber_red"); + uiSaberColorShaders[SABER_ORANGE] = trap->R_RegisterShaderNoMip("menu/art/saber_orange"); + uiSaberColorShaders[SABER_YELLOW] = trap->R_RegisterShaderNoMip("menu/art/saber_yellow"); + uiSaberColorShaders[SABER_GREEN] = trap->R_RegisterShaderNoMip("menu/art/saber_green"); + uiSaberColorShaders[SABER_BLUE] = trap->R_RegisterShaderNoMip("menu/art/saber_blue"); + uiSaberColorShaders[SABER_PURPLE] = trap->R_RegisterShaderNoMip("menu/art/saber_purple"); } // Draw the stars spent on the current force power -void UI_DrawForceStars(rectDef_t *rect, float scale, vec4_t color, int textStyle, int forceindex, int val, int min, int max) -{ - int i,pad = 4; - int xPos,width = 16; +void UI_DrawForceStars(rectDef_t *rect, float scale, vec4_t color, int textStyle, int forceindex, int val, int min, int max) { + int i, pad = 4; + int xPos, width = 16; int starcolor; - if (val < min || val > max) - { + if (val < min || val > max) { val = min; } - if (1) // if (val) + if (1) // if (val) { xPos = rect->x; - for (i=FORCE_LEVEL_1;i<=max;i++) - { + for (i = FORCE_LEVEL_1; i <= max; i++) { starcolor = bgForcePowerCost[forceindex][i]; - if (uiForcePowersDisabled[forceindex]) - { + if (uiForcePowersDisabled[forceindex]) { vec4_t grColor = {0.2f, 0.2f, 0.2f, 1.0f}; trap->R_SetColor(grColor); } - if (val >= i) - { // Draw a star. - UI_DrawHandlePic( xPos, rect->y+6, width, width, uiForceStarShaders[starcolor][1] ); - } - else - { // Draw a circle. - UI_DrawHandlePic( xPos, rect->y+6, width, width, uiForceStarShaders[starcolor][0] ); + if (val >= i) { // Draw a star. + UI_DrawHandlePic(xPos, rect->y + 6, width, width, uiForceStarShaders[starcolor][1]); + } else { // Draw a circle. + UI_DrawHandlePic(xPos, rect->y + 6, width, width, uiForceStarShaders[starcolor][0]); } - if (uiForcePowersDisabled[forceindex]) - { + if (uiForcePowersDisabled[forceindex]) { trap->R_SetColor(NULL); } @@ -189,44 +181,33 @@ void UI_DrawForceStars(rectDef_t *rect, float scale, vec4_t color, int textStyle } // Set the client's force power layout. -void UI_UpdateClientForcePowers(const char *teamArg) -{ - trap->Cvar_Set( "forcepowers", va("%i-%i-%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i", - uiForceRank, uiForceSide, uiForcePowersRank[0], uiForcePowersRank[1], - uiForcePowersRank[2], uiForcePowersRank[3], uiForcePowersRank[4], - uiForcePowersRank[5], uiForcePowersRank[6], uiForcePowersRank[7], - uiForcePowersRank[8], uiForcePowersRank[9], uiForcePowersRank[10], - uiForcePowersRank[11], uiForcePowersRank[12], uiForcePowersRank[13], - uiForcePowersRank[14], uiForcePowersRank[15], uiForcePowersRank[16], - uiForcePowersRank[17]) ); - - if (gTouchedForce) - { - if (teamArg && teamArg[0]) - { - trap->Cmd_ExecuteText( EXEC_APPEND, va("forcechanged \"%s\"\n", teamArg) ); - } - else - { - trap->Cmd_ExecuteText( EXEC_APPEND, "forcechanged\n" ); +void UI_UpdateClientForcePowers(const char *teamArg) { + trap->Cvar_Set("forcepowers", + va("%i-%i-%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i", uiForceRank, uiForceSide, uiForcePowersRank[0], uiForcePowersRank[1], uiForcePowersRank[2], + uiForcePowersRank[3], uiForcePowersRank[4], uiForcePowersRank[5], uiForcePowersRank[6], uiForcePowersRank[7], uiForcePowersRank[8], + uiForcePowersRank[9], uiForcePowersRank[10], uiForcePowersRank[11], uiForcePowersRank[12], uiForcePowersRank[13], uiForcePowersRank[14], + uiForcePowersRank[15], uiForcePowersRank[16], uiForcePowersRank[17])); + + if (gTouchedForce) { + if (teamArg && teamArg[0]) { + trap->Cmd_ExecuteText(EXEC_APPEND, va("forcechanged \"%s\"\n", teamArg)); + } else { + trap->Cmd_ExecuteText(EXEC_APPEND, "forcechanged\n"); } } gTouchedForce = qfalse; } -int UI_TranslateFCFIndex(int index) -{ - if (uiForceSide == FORCE_LIGHTSIDE) - { - return index-uiInfo.forceConfigLightIndexBegin; +int UI_TranslateFCFIndex(int index) { + if (uiForceSide == FORCE_LIGHTSIDE) { + return index - uiInfo.forceConfigLightIndexBegin; } - return index-uiInfo.forceConfigDarkIndexBegin; + return index - uiInfo.forceConfigDarkIndexBegin; } -void UI_SaveForceTemplate() -{ +void UI_SaveForceTemplate() { char *selectedName = UI_Cvar_VariableString("ui_SaveFCF"); char fcfString[512]; char forceStringValue[4]; @@ -236,23 +217,18 @@ void UI_SaveForceTemplate() int i = 0; qboolean foundFeederItem = qfalse; - if (!selectedName || !selectedName[0]) - { + if (!selectedName || !selectedName[0]) { Com_Printf("You did not provide a name for the template.\n"); return; } - if (uiForceSide == FORCE_LIGHTSIDE) - { //write it into the light side folder + if (uiForceSide == FORCE_LIGHTSIDE) { // write it into the light side folder trap->FS_Open(va("forcecfg/light/%s.fcf", selectedName), &f, FS_WRITE); - } - else - { //if it isn't light it must be dark + } else { // if it isn't light it must be dark trap->FS_Open(va("forcecfg/dark/%s.fcf", selectedName), &f, FS_WRITE); } - if (!f) - { + if (!f) { Com_Printf("There was an error writing the template file (read-only?).\n"); return; } @@ -260,33 +236,28 @@ void UI_SaveForceTemplate() Com_sprintf(fcfString, sizeof(fcfString), "%i-%i-", uiForceRank, uiForceSide); strPlace = strlen(fcfString); - while (forcePlace < NUM_FORCE_POWERS) - { + while (forcePlace < NUM_FORCE_POWERS) { Com_sprintf(forceStringValue, sizeof(forceStringValue), "%i", uiForcePowersRank[forcePlace]); - //Just use the force digit even if multiple digits. Shouldn't be longer than 1. + // Just use the force digit even if multiple digits. Shouldn't be longer than 1. fcfString[strPlace] = forceStringValue[0]; strPlace++; forcePlace++; } fcfString[strPlace] = '\n'; - fcfString[strPlace+1] = 0; + fcfString[strPlace + 1] = 0; trap->FS_Write(fcfString, strlen(fcfString), f); trap->FS_Close(f); Com_Printf("Template saved as \"%s\".\n", selectedName); - //Now, update the FCF list + // Now, update the FCF list UI_LoadForceConfig_List(); - //Then, scroll through and select the template for the file we just saved - while (i < uiInfo.forceConfigCount) - { - if (!Q_stricmp(uiInfo.forceConfigNames[i], selectedName)) - { - if ((uiForceSide == FORCE_LIGHTSIDE && uiInfo.forceConfigSide[i]) || - (uiForceSide == FORCE_DARKSIDE && !uiInfo.forceConfigSide[i])) - { + // Then, scroll through and select the template for the file we just saved + while (i < uiInfo.forceConfigCount) { + if (!Q_stricmp(uiInfo.forceConfigNames[i], selectedName)) { + if ((uiForceSide == FORCE_LIGHTSIDE && uiInfo.forceConfigSide[i]) || (uiForceSide == FORCE_DARKSIDE && !uiInfo.forceConfigSide[i])) { Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, UI_TranslateFCFIndex(i), NULL); foundFeederItem = qtrue; } @@ -295,18 +266,15 @@ void UI_SaveForceTemplate() i++; } - //Else, go back to 0 - if (!foundFeederItem) - { + // Else, go back to 0 + if (!foundFeederItem) { Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, 0, NULL); } } - // -extern qboolean UI_TrueJediEnabled( void ); -void UpdateForceUsed() -{ +extern qboolean UI_TrueJediEnabled(void); +void UpdateForceUsed() { int curpower, currank; menuDef_t *menu; @@ -317,68 +285,49 @@ void UpdateForceUsed() uiForceAvailable = forceMasteryPoints[uiForceRank]; // Make sure that we have one freebie in jump. - if (uiForcePowersRank[FP_LEVITATION]<1) - { - uiForcePowersRank[FP_LEVITATION]=1; + if (uiForcePowersRank[FP_LEVITATION] < 1) { + uiForcePowersRank[FP_LEVITATION] = 1; } - if ( UI_TrueJediEnabled() ) - {//true jedi mode is set - if ( uiJediNonJedi == -1 ) - { + if (UI_TrueJediEnabled()) { // true jedi mode is set + if (uiJediNonJedi == -1) { int x = 0; qboolean clear = qfalse, update = qfalse; uiJediNonJedi = FORCE_NONJEDI; - while ( x < NUM_FORCE_POWERS ) - {//if any force power is set, we must be a jedi - if ( x == FP_LEVITATION || x == FP_SABER_OFFENSE ) - { - if ( uiForcePowersRank[x] > 1 ) - { + while (x < NUM_FORCE_POWERS) { // if any force power is set, we must be a jedi + if (x == FP_LEVITATION || x == FP_SABER_OFFENSE) { + if (uiForcePowersRank[x] > 1) { uiJediNonJedi = FORCE_JEDI; break; - } - else if ( uiForcePowersRank[x] > 0 ) - { + } else if (uiForcePowersRank[x] > 0) { clear = qtrue; } - } - else if ( uiForcePowersRank[x] > 0 ) - { + } else if (uiForcePowersRank[x] > 0) { uiJediNonJedi = FORCE_JEDI; break; } x++; } - if ( uiJediNonJedi == FORCE_JEDI ) - { - if ( uiForcePowersRank[FP_SABER_OFFENSE] < 1 ) - { - uiForcePowersRank[FP_SABER_OFFENSE]=1; + if (uiJediNonJedi == FORCE_JEDI) { + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1) { + uiForcePowersRank[FP_SABER_OFFENSE] = 1; update = qtrue; } - } - else if ( clear ) - { + } else if (clear) { x = 0; - while ( x < NUM_FORCE_POWERS ) - {//clear all force + while (x < NUM_FORCE_POWERS) { // clear all force uiForcePowersRank[x] = 0; x++; } update = qtrue; } - if ( update ) - { + if (update) { int myTeam; myTeam = (int)(trap->Cvar_VariableValue("ui_myteam")); - if ( myTeam != TEAM_SPECTATOR ) - { - UI_UpdateClientForcePowers(UI_TeamName(myTeam));//will cause him to respawn, if it's been 5 seconds since last one - } - else - { - UI_UpdateClientForcePowers(NULL);//just update powers + if (myTeam != TEAM_SPECTATOR) { + UI_UpdateClientForcePowers(UI_TeamName(myTeam)); // will cause him to respawn, if it's been 5 seconds since last one + } else { + UI_UpdateClientForcePowers(NULL); // just update powers } } } @@ -386,50 +335,39 @@ void UpdateForceUsed() menu = Menus_FindByName("ingame_playerforce"); // Set the cost of the saberattack according to whether its free. - if (ui_freeSaber.integer) - { // Make saber free + if (ui_freeSaber.integer) { // Make saber free bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 0; bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 0; // Make sure that we have one freebie in saber if applicable. - if (uiForcePowersRank[FP_SABER_OFFENSE]<1) - { - uiForcePowersRank[FP_SABER_OFFENSE]=1; + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1) { + uiForcePowersRank[FP_SABER_OFFENSE] = 1; } - if (uiForcePowersRank[FP_SABER_DEFENSE]<1) - { - uiForcePowersRank[FP_SABER_DEFENSE]=1; + if (uiForcePowersRank[FP_SABER_DEFENSE] < 1) { + uiForcePowersRank[FP_SABER_DEFENSE] = 1; } - if (menu) - { + if (menu) { Menu_ShowItemByName(menu, "setFP_SABER_DEFENSE", qtrue); Menu_ShowItemByName(menu, "setfp_saberthrow", qtrue); Menu_ShowItemByName(menu, "effectentry", qtrue); Menu_ShowItemByName(menu, "effectfield", qtrue); Menu_ShowItemByName(menu, "nosaber", qfalse); } - } - else - { // Make saber normal cost + } else { // Make saber normal cost bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 1; bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 1; // Also, check if there is no saberattack. If there isn't, there had better not be any defense or throw! - if (uiForcePowersRank[FP_SABER_OFFENSE]<1) - { - uiForcePowersRank[FP_SABER_DEFENSE]=0; - uiForcePowersRank[FP_SABERTHROW]=0; - if (menu) - { + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1) { + uiForcePowersRank[FP_SABER_DEFENSE] = 0; + uiForcePowersRank[FP_SABERTHROW] = 0; + if (menu) { Menu_ShowItemByName(menu, "setfp_saberdefend", qfalse); Menu_ShowItemByName(menu, "setfp_saberthrow", qfalse); Menu_ShowItemByName(menu, "effectentry", qfalse); Menu_ShowItemByName(menu, "effectfield", qfalse); Menu_ShowItemByName(menu, "nosaber", qtrue); } - } - else - { - if (menu) - { + } else { + if (menu) { Menu_ShowItemByName(menu, "setfp_saberdefend", qtrue); Menu_ShowItemByName(menu, "setfp_saberthrow", qtrue); Menu_ShowItemByName(menu, "effectentry", qtrue); @@ -440,33 +378,24 @@ void UpdateForceUsed() } // Make sure that we're still legal. - for (curpower=0;curpower=NUM_FORCE_POWER_LEVELS) - uiForcePowersRank[curpower]=(NUM_FORCE_POWER_LEVELS-1); - - for (currank=FORCE_LEVEL_1;currank<=uiForcePowersRank[curpower];currank++) - { // Check on this force power - if (uiForcePowersRank[curpower]>0) - { // Do not charge the player for the one freebie in jump, or if there is one in saber. - if ( (curpower == FP_LEVITATION && currank == FORCE_LEVEL_1) || - (curpower == FP_SABER_OFFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer) || - (curpower == FP_SABER_DEFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer) ) - { + for (curpower = 0; curpower < NUM_FORCE_POWERS; curpower++) { // Make sure that our ranks are within legal limits. + if (uiForcePowersRank[curpower] < 0) + uiForcePowersRank[curpower] = 0; + else if (uiForcePowersRank[curpower] >= NUM_FORCE_POWER_LEVELS) + uiForcePowersRank[curpower] = (NUM_FORCE_POWER_LEVELS - 1); + + for (currank = FORCE_LEVEL_1; currank <= uiForcePowersRank[curpower]; currank++) { // Check on this force power + if (uiForcePowersRank[curpower] > 0) { // Do not charge the player for the one freebie in jump, or if there is one in saber. + if ((curpower == FP_LEVITATION && currank == FORCE_LEVEL_1) || + (curpower == FP_SABER_OFFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer) || + (curpower == FP_SABER_DEFENSE && currank == FORCE_LEVEL_1 && ui_freeSaber.integer)) { // Do nothing (written this way for clarity) - } - else - { // Check if we can accrue the cost of this power. - if (bgForcePowerCost[curpower][currank] > uiForceAvailable) - { // We can't afford this power. Break to the next one. + } else { // Check if we can accrue the cost of this power. + if (bgForcePowerCost[curpower][currank] > uiForceAvailable) { // We can't afford this power. Break to the next one. // Remove this power from the player's roster. - uiForcePowersRank[curpower] = currank-1; + uiForcePowersRank[curpower] = currank - 1; break; - } - else - { // Sure we can afford it. + } else { // Sure we can afford it. uiForceUsed += bgForcePowerCost[curpower][currank]; uiForceAvailable -= bgForcePowerCost[curpower][currank]; } @@ -474,14 +403,11 @@ void UpdateForceUsed() } } } - } - -//Mostly parts of other functions merged into one another. -//Puts the current UI stuff into a string, legalizes it, and then reads it back out. -void UI_ReadLegalForce(void) -{ +// Mostly parts of other functions merged into one another. +// Puts the current UI stuff into a string, legalizes it, and then reads it back out. +void UI_ReadLegalForce(void) { char fcfString[512]; char forceStringValue[4]; int strPlace = 0; @@ -496,28 +422,25 @@ void UI_ReadLegalForce(void) int forceTeam = 0; qboolean updateForceLater = qfalse; - //First, stick them into a string. + // First, stick them into a string. Com_sprintf(fcfString, sizeof(fcfString), "%i-%i-", uiForceRank, uiForceSide); strPlace = strlen(fcfString); - while (forcePlace < NUM_FORCE_POWERS) - { + while (forcePlace < NUM_FORCE_POWERS) { Com_sprintf(forceStringValue, sizeof(forceStringValue), "%i", uiForcePowersRank[forcePlace]); - //Just use the force digit even if multiple digits. Shouldn't be longer than 1. + // Just use the force digit even if multiple digits. Shouldn't be longer than 1. fcfString[strPlace] = forceStringValue[0]; strPlace++; forcePlace++; } fcfString[strPlace] = '\n'; - fcfString[strPlace+1] = 0; + fcfString[strPlace + 1] = 0; info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) )) - { - switch((int)(trap->Cvar_VariableValue("ui_myteam"))) - { + if (atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) { + switch ((int)(trap->Cvar_VariableValue("ui_myteam"))) { case TEAM_RED: forceTeam = FORCE_DARKSIDE; break; @@ -528,17 +451,16 @@ void UI_ReadLegalForce(void) break; } } - //Second, legalize them. - if (!BG_LegalizedForcePowers(fcfString, sizeof (fcfString), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi( Info_ValueForKey( info, "g_gametype" )), 0)) - { //if they were illegal, we should refresh them. + // Second, legalize them. + if (!BG_LegalizedForcePowers(fcfString, sizeof(fcfString), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi(Info_ValueForKey(info, "g_gametype")), + 0)) { // if they were illegal, we should refresh them. updateForceLater = qtrue; } - //Lastly, put them back into the UI storage from the legalized string + // Lastly, put them back into the UI storage from the legalized string i = 0; - while (fcfString[i] && fcfString[i] != '-') - { + while (fcfString[i] && fcfString[i] != '-') { singleBuf[c] = fcfString[i]; c++; i++; @@ -549,16 +471,14 @@ void UI_ReadLegalForce(void) iBuf = atoi(singleBuf); - if (iBuf > uiMaxRank || iBuf < 0) - { //this force config uses a rank level higher than our currently restricted level.. so we can't use it - //FIXME: Print a message indicating this to the user - // return; + if (iBuf > uiMaxRank || iBuf < 0) { // this force config uses a rank level higher than our currently restricted level.. so we can't use it + // FIXME: Print a message indicating this to the user + // return; } uiForceRank = iBuf; - while (fcfString[i] && fcfString[i] != '-') - { + while (fcfString[i] && fcfString[i] != '-') { singleBuf[c] = fcfString[i]; c++; i++; @@ -569,16 +489,13 @@ void UI_ReadLegalForce(void) uiForceSide = atoi(singleBuf); - if (uiForceSide != FORCE_LIGHTSIDE && - uiForceSide != FORCE_DARKSIDE) - { + if (uiForceSide != FORCE_LIGHTSIDE && uiForceSide != FORCE_DARKSIDE) { uiForceSide = FORCE_LIGHTSIDE; return; } - //clear out the existing powers - while (c < NUM_FORCE_POWERS) - { + // clear out the existing powers + while (c < NUM_FORCE_POWERS) { uiForcePowersRank[c] = 0; c++; } @@ -586,34 +503,29 @@ void UI_ReadLegalForce(void) uiForceAvailable = forceMasteryPoints[uiForceRank]; gTouchedForce = qtrue; - for (c=0;fcfString[i]&&c FORCE_LEVEL_3 || forcePowerRank < 0) - { //err.. not correct - continue; // skip this power + if (forcePowerRank > FORCE_LEVEL_3 || forcePowerRank < 0) { // err.. not correct + continue; // skip this power } - if (uiForcePowerDarkLight[c] && uiForcePowerDarkLight[c] != uiForceSide) - { //Apparently the user has crafted a force config that has powers that don't fit with the config's side. - continue; // skip this power + if (uiForcePowerDarkLight[c] && + uiForcePowerDarkLight[c] != uiForceSide) { // Apparently the user has crafted a force config that has powers that don't fit with the config's side. + continue; // skip this power } // Accrue cost for each assigned rank for this power. - for (currank=FORCE_LEVEL_1;currank<=forcePowerRank;currank++) - { - if (bgForcePowerCost[c][currank] > uiForceAvailable) - { // Break out, we can't afford any more power. + for (currank = FORCE_LEVEL_1; currank <= forcePowerRank; currank++) { + if (bgForcePowerCost[c][currank] > uiForceAvailable) { // Break out, we can't afford any more power. break; } // Pay for this rank of this power. @@ -624,73 +536,61 @@ void UI_ReadLegalForce(void) } } - if (uiForcePowersRank[FP_LEVITATION] < 1) - { - uiForcePowersRank[FP_LEVITATION]=1; + if (uiForcePowersRank[FP_LEVITATION] < 1) { + uiForcePowersRank[FP_LEVITATION] = 1; } - if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer) - { - uiForcePowersRank[FP_SABER_OFFENSE]=1; + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer) { + uiForcePowersRank[FP_SABER_OFFENSE] = 1; } - if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer) - { - uiForcePowersRank[FP_SABER_DEFENSE]=1; + if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer) { + uiForcePowersRank[FP_SABER_DEFENSE] = 1; } UpdateForceUsed(); - if (updateForceLater) - { + if (updateForceLater) { gTouchedForce = qtrue; UI_UpdateClientForcePowers(NULL); } } -void UI_UpdateForcePowers() -{ +void UI_UpdateForcePowers() { char *forcePowers = UI_Cvar_VariableString("forcepowers"); char readBuf[256]; int i = 0, i_f = 0, i_r = 0; uiForceSide = 0; - if (forcePowers && forcePowers[0]) - { - while (forcePowers[i]) - { + if (forcePowers && forcePowers[0]) { + while (forcePowers[i]) { i_r = 0; - while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255) - { + while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255) { readBuf[i_r] = forcePowers[i]; i_r++; i++; } readBuf[i_r] = '\0'; - if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-') - { + if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-') { uiForceSide = 0; goto validitycheck; } uiForceRank = atoi(readBuf); i_r = 0; - if (uiForceRank > uiMaxRank) - { + if (uiForceRank > uiMaxRank) { uiForceRank = uiMaxRank; } i++; - while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255) - { + while (forcePowers[i] && forcePowers[i] != '-' && i_r < 255) { readBuf[i_r] = forcePowers[i]; i_r++; i++; } readBuf[i_r] = '\0'; - if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-') - { + if (i_r >= 255 || !forcePowers[i] || forcePowers[i] != '-') { uiForceSide = 0; goto validitycheck; } @@ -701,29 +601,20 @@ void UI_UpdateForcePowers() i_f = FP_HEAL; - while (forcePowers[i] && i_f < NUM_FORCE_POWERS) - { + while (forcePowers[i] && i_f < NUM_FORCE_POWERS) { readBuf[0] = forcePowers[i]; readBuf[1] = '\0'; uiForcePowersRank[i_f] = atoi(readBuf); - if (i_f == FP_LEVITATION && - uiForcePowersRank[i_f] < 1) - { + if (i_f == FP_LEVITATION && uiForcePowersRank[i_f] < 1) { uiForcePowersRank[i_f] = 1; } - if (i_f == FP_SABER_OFFENSE && - uiForcePowersRank[i_f] < 1 && - ui_freeSaber.integer) - { + if (i_f == FP_SABER_OFFENSE && uiForcePowersRank[i_f] < 1 && ui_freeSaber.integer) { uiForcePowersRank[i_f] = 1; } - if (i_f == FP_SABER_DEFENSE && - uiForcePowersRank[i_f] < 1 && - ui_freeSaber.integer) - { + if (i_f == FP_SABER_DEFENSE && uiForcePowersRank[i_f] < 1 && ui_freeSaber.integer) { uiForcePowersRank[i_f] = 1; } @@ -731,8 +622,7 @@ void UI_UpdateForcePowers() i++; } - if (i_f < NUM_FORCE_POWERS) - { //info for all the powers wasn't there.. + if (i_f < NUM_FORCE_POWERS) { // info for all the powers wasn't there.. uiForceSide = 0; goto validitycheck; } @@ -742,27 +632,18 @@ void UI_UpdateForcePowers() validitycheck: - if (!uiForceSide) - { + if (!uiForceSide) { uiForceSide = 1; uiForceRank = 1; i = 0; - while (i < NUM_FORCE_POWERS) - { - if (i == FP_LEVITATION) - { + while (i < NUM_FORCE_POWERS) { + if (i == FP_LEVITATION) { uiForcePowersRank[i] = 1; - } - else if (i == FP_SABER_OFFENSE && ui_freeSaber.integer) - { + } else if (i == FP_SABER_OFFENSE && ui_freeSaber.integer) { uiForcePowersRank[i] = 1; - } - else if (i == FP_SABER_DEFENSE && ui_freeSaber.integer) - { + } else if (i == FP_SABER_DEFENSE && ui_freeSaber.integer) { uiForcePowersRank[i] = 1; - } - else - { + } else { uiForcePowersRank[i] = 0; } @@ -774,60 +655,46 @@ void UI_UpdateForcePowers() UpdateForceUsed(); } -extern int uiSkinColor; -extern int uiHoldSkinColor; +extern int uiSkinColor; +extern int uiHoldSkinColor; -qboolean UI_SkinColor_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) -{ - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { - int i = num; +qboolean UI_SkinColor_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { + int i = num; - if (key == A_MOUSE2) - { - i--; - } - else - { - i++; - } + if (key == A_MOUSE2) { + i--; + } else { + i++; + } - if (i < min) - { - i = max; - } - else if (i > max) - { - i = min; - } + if (i < min) { + i = max; + } else if (i > max) { + i = min; + } - num = i; + num = i; - uiSkinColor = num; + uiSkinColor = num; - uiHoldSkinColor = uiSkinColor; + uiHoldSkinColor = uiSkinColor; - UI_FeederSelection(FEEDER_Q3HEADS, uiInfo.q3SelectedHead, NULL); + UI_FeederSelection(FEEDER_Q3HEADS, uiInfo.q3SelectedHead, NULL); - return qtrue; - } - return qfalse; + return qtrue; + } + return qfalse; } - - - -qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) -{ +qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) { char info[MAX_INFO_VALUE]; info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) )) - { - switch((int)(trap->Cvar_VariableValue("ui_myteam"))) - { + if (atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) { + switch ((int)(trap->Cvar_VariableValue("ui_myteam"))) { case TEAM_RED: return qfalse; case TEAM_BLUE: @@ -837,29 +704,22 @@ qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int } } - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { int i = num; int x = 0; - //update the feeder item selection, it might be different depending on side + // update the feeder item selection, it might be different depending on side Menu_SetFeederSelection(NULL, FEEDER_FORCECFG, 0, NULL); - if (key == A_MOUSE2) - { + if (key == A_MOUSE2) { i--; - } - else - { + } else { i++; } - if (i < min) - { + if (i < min) { i = max; - } - else if (i > max) - { + } else if (i > max) { i = min; } @@ -868,10 +728,8 @@ qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int uiForceSide = num; // Resetting power ranks based on if light or dark side is chosen - while (x < NUM_FORCE_POWERS) - { - if (uiForcePowerDarkLight[x] && uiForceSide != uiForcePowerDarkLight[x]) - { + while (x < NUM_FORCE_POWERS) { + if (uiForcePowerDarkLight[x] && uiForceSide != uiForcePowerDarkLight[x]) { uiForcePowersRank[x] = 0; } x++; @@ -885,38 +743,29 @@ qboolean UI_ForceSide_HandleKey(int flags, float *special, int key, int num, int return qfalse; } -qboolean UI_JediNonJedi_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) -{ +qboolean UI_JediNonJedi_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) { char info[MAX_INFO_VALUE]; info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if ( !UI_TrueJediEnabled() ) - {//true jedi mode is not set + if (!UI_TrueJediEnabled()) { // true jedi mode is not set return qfalse; } - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { int i = num; int x = 0; - if (key == A_MOUSE2) - { + if (key == A_MOUSE2) { i--; - } - else - { + } else { i++; } - if (i < min) - { + if (i < min) { i = max; - } - else if (i > max) - { + } else if (i > max) { i = min; } @@ -925,31 +774,22 @@ qboolean UI_JediNonJedi_HandleKey(int flags, float *special, int key, int num, i uiJediNonJedi = num; // Resetting power ranks based on if light or dark side is chosen - if ( !num ) - {//not a jedi? + if (!num) { // not a jedi? int myTeam = (int)(trap->Cvar_VariableValue("ui_myteam")); - while ( x < NUM_FORCE_POWERS ) - {//clear all force powers + while (x < NUM_FORCE_POWERS) { // clear all force powers uiForcePowersRank[x] = 0; x++; } - if ( myTeam != TEAM_SPECTATOR ) - { - UI_UpdateClientForcePowers(UI_TeamName(myTeam));//will cause him to respawn, if it's been 5 seconds since last one - } - else - { - UI_UpdateClientForcePowers(NULL);//just update powers + if (myTeam != TEAM_SPECTATOR) { + UI_UpdateClientForcePowers(UI_TeamName(myTeam)); // will cause him to respawn, if it's been 5 seconds since last one + } else { + UI_UpdateClientForcePowers(NULL); // just update powers } - } - else if ( num ) - {//a jedi, set the minimums, hopefuly they know to set the rest! - if ( uiForcePowersRank[FP_LEVITATION] < FORCE_LEVEL_1 ) - {//force jump 1 minimum + } else if (num) { // a jedi, set the minimums, hopefuly they know to set the rest! + if (uiForcePowersRank[FP_LEVITATION] < FORCE_LEVEL_1) { // force jump 1 minimum uiForcePowersRank[FP_LEVITATION] = FORCE_LEVEL_1; } - if ( uiForcePowersRank[FP_SABER_OFFENSE] < FORCE_LEVEL_1 ) - {//saber attack 1, minimum + if (uiForcePowersRank[FP_SABER_OFFENSE] < FORCE_LEVEL_1) { // saber attack 1, minimum uiForcePowersRank[FP_SABER_OFFENSE] = FORCE_LEVEL_1; } } @@ -962,124 +802,94 @@ qboolean UI_JediNonJedi_HandleKey(int flags, float *special, int key, int num, i return qfalse; } -qboolean UI_ForceMaxRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) -{ - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { - int i = num; +qboolean UI_ForceMaxRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { + int i = num; - if (key == A_MOUSE2) - { - i--; - } - else - { - i++; - } + if (key == A_MOUSE2) { + i--; + } else { + i++; + } - if (i < min) - { - i = max; - } - else if (i > max) - { - i = min; - } + if (i < min) { + i = max; + } else if (i > max) { + i = min; + } - num = i; + num = i; - uiMaxRank = num; + uiMaxRank = num; - trap->Cvar_Set( "g_maxForceRank", va("%i", num)); + trap->Cvar_Set("g_maxForceRank", va("%i", num)); - // The update force used will remove overallocated powers automatically. - UpdateForceUsed(); + // The update force used will remove overallocated powers automatically. + UpdateForceUsed(); - gTouchedForce = qtrue; + gTouchedForce = qtrue; - return qtrue; - } - return qfalse; + return qtrue; + } + return qfalse; } - // This function will either raise or lower a power by one rank. -qboolean UI_ForcePowerRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) -{ +qboolean UI_ForcePowerRank_HandleKey(int flags, float *special, int key, int num, int min, int max, int type) { qboolean raising; - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER || key == A_BACKSPACE) - { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER || key == A_BACKSPACE) { int forcepower, rank; - //this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index - forcepower = (type-UI_FORCE_RANK)-1; + // this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index + forcepower = (type - UI_FORCE_RANK) - 1; - //the power is disabled on the server - if (uiForcePowersDisabled[forcepower]) - { + // the power is disabled on the server + if (uiForcePowersDisabled[forcepower]) { return qtrue; } // If we are not on the same side as a power, or if we are not of any rank at all. - if (uiForcePowerDarkLight[forcepower] && uiForceSide != uiForcePowerDarkLight[forcepower]) - { + if (uiForcePowerDarkLight[forcepower] && uiForceSide != uiForcePowerDarkLight[forcepower]) { return qtrue; - } - else if (forcepower == FP_SABER_DEFENSE || forcepower == FP_SABERTHROW) - { // Saberdefend and saberthrow can't be bought if there is no saberattack - if (uiForcePowersRank[FP_SABER_OFFENSE] < 1) - { + } else if (forcepower == FP_SABER_DEFENSE || forcepower == FP_SABERTHROW) { // Saberdefend and saberthrow can't be bought if there is no saberattack + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1) { return qtrue; } } - if (type == UI_FORCE_RANK_LEVITATION) - { + if (type == UI_FORCE_RANK_LEVITATION) { min += 1; } - if (type == UI_FORCE_RANK_SABERATTACK && ui_freeSaber.integer) - { + if (type == UI_FORCE_RANK_SABERATTACK && ui_freeSaber.integer) { min += 1; } - if (type == UI_FORCE_RANK_SABERDEFEND && ui_freeSaber.integer) - { + if (type == UI_FORCE_RANK_SABERDEFEND && ui_freeSaber.integer) { min += 1; } - if (key == A_MOUSE2 || key == A_BACKSPACE) - { // Lower a point. - if (uiForcePowersRank[forcepower]<=min) - { + if (key == A_MOUSE2 || key == A_BACKSPACE) { // Lower a point. + if (uiForcePowersRank[forcepower] <= min) { return qtrue; } raising = qfalse; - } - else - { // Raise a point. - if (uiForcePowersRank[forcepower]>=max) - { + } else { // Raise a point. + if (uiForcePowersRank[forcepower] >= max) { return qtrue; } raising = qtrue; } - if (raising) - { // Check if we can accrue the cost of this power. - rank = uiForcePowersRank[forcepower]+1; - if (bgForcePowerCost[forcepower][rank] > uiForceAvailable) - { // We can't afford this power. Abandon ship. + if (raising) { // Check if we can accrue the cost of this power. + rank = uiForcePowersRank[forcepower] + 1; + if (bgForcePowerCost[forcepower][rank] > uiForceAvailable) { // We can't afford this power. Abandon ship. return qtrue; - } - else - { // Sure we can afford it. + } else { // Sure we can afford it. uiForceUsed += bgForcePowerCost[forcepower][rank]; uiForceAvailable -= bgForcePowerCost[forcepower][rank]; - uiForcePowersRank[forcepower]=rank; + uiForcePowersRank[forcepower] = rank; } - } - else - { // Lower the point. + } else { // Lower the point. rank = uiForcePowersRank[forcepower]; uiForceUsed -= bgForcePowerCost[forcepower][rank]; uiForceAvailable += bgForcePowerCost[forcepower][rank]; @@ -1095,29 +905,28 @@ qboolean UI_ForcePowerRank_HandleKey(int flags, float *special, int key, int num return qfalse; } - int gCustRank = 0; int gCustSide = 0; int gCustPowersRank[NUM_FORCE_POWERS] = { - 0,//FP_HEAL = 0,//instant - 1,//FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point) - 0,//FP_SPEED,//duration - 0,//FP_PUSH,//hold/duration - 0,//FP_PULL,//hold/duration - 0,//FP_TELEPATHY,//instant - 0,//FP_GRIP,//hold/duration - 0,//FP_LIGHTNING,//hold/duration - 0,//FP_RAGE,//duration - 0,//FP_PROTECT, - 0,//FP_ABSORB, - 0,//FP_TEAM_HEAL, - 0,//FP_TEAM_FORCE, - 0,//FP_DRAIN, - 0,//FP_SEE, - 0,//FP_SABER_OFFENSE, - 0,//FP_SABER_DEFENSE, - 0//FP_SABERTHROW, + 0, // FP_HEAL = 0,//instant + 1, // FP_LEVITATION,//hold/duration, this one defaults to 1 (gives a free point) + 0, // FP_SPEED,//duration + 0, // FP_PUSH,//hold/duration + 0, // FP_PULL,//hold/duration + 0, // FP_TELEPATHY,//instant + 0, // FP_GRIP,//hold/duration + 0, // FP_LIGHTNING,//hold/duration + 0, // FP_RAGE,//duration + 0, // FP_PROTECT, + 0, // FP_ABSORB, + 0, // FP_TEAM_HEAL, + 0, // FP_TEAM_FORCE, + 0, // FP_DRAIN, + 0, // FP_SEE, + 0, // FP_SABER_OFFENSE, + 0, // FP_SABER_DEFENSE, + 0 // FP_SABERTHROW, }; /* @@ -1125,8 +934,7 @@ int gCustPowersRank[NUM_FORCE_POWERS] = { UI_ForceConfigHandle ================= */ -void UI_ForceConfigHandle( int oldindex, int newindex ) -{ +void UI_ForceConfigHandle(int oldindex, int newindex) { fileHandle_t f; int len = 0; int i = 0; @@ -1137,12 +945,10 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) char info[MAX_INFO_VALUE]; int forceTeam = 0; - if (oldindex == 0) - { //switching out from custom config, so first shove the current values into the custom storage + if (oldindex == 0) { // switching out from custom config, so first shove the current values into the custom storage i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { gCustPowersRank[i] = uiForcePowersRank[i]; i++; } @@ -1150,14 +956,12 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) gCustSide = uiForceSide; } - if (newindex == 0) - { //switching back to custom, shove the values back in from the custom storage + if (newindex == 0) { // switching back to custom, shove the values back in from the custom storage i = 0; uiForceUsed = 0; gTouchedForce = qtrue; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { uiForcePowersRank[i] = gCustPowersRank[i]; uiForceUsed += uiForcePowersRank[i]; i++; @@ -1169,40 +973,33 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) return; } - //If we made it here, we want to load in a new config - if (uiForceSide == FORCE_LIGHTSIDE) - { //we should only be displaying lightside configs, so.. look in the light folder + // If we made it here, we want to load in a new config + if (uiForceSide == FORCE_LIGHTSIDE) { // we should only be displaying lightside configs, so.. look in the light folder newindex += uiInfo.forceConfigLightIndexBegin; if (newindex >= uiInfo.forceConfigCount) return; len = trap->FS_Open(va("forcecfg/light/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ); - } - else - { //else dark + } else { // else dark newindex += uiInfo.forceConfigDarkIndexBegin; - if (newindex >= uiInfo.forceConfigCount || newindex > uiInfo.forceConfigLightIndexBegin) - { //dark gets read in before light + if (newindex >= uiInfo.forceConfigCount || newindex > uiInfo.forceConfigLightIndexBegin) { // dark gets read in before light return; } len = trap->FS_Open(va("forcecfg/dark/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ); } - if (len <= 0) - { //This should not have happened. But, before we quit out, attempt searching the other light/dark folder for the file. + if (len <= 0) { // This should not have happened. But, before we quit out, attempt searching the other light/dark folder for the file. if (uiForceSide == FORCE_LIGHTSIDE) len = trap->FS_Open(va("forcecfg/dark/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ); else len = trap->FS_Open(va("forcecfg/light/%s.fcf", uiInfo.forceConfigNames[newindex]), &f, FS_READ); - if (len <= 0) - { //still failure? Oh well. + if (len <= 0) { // still failure? Oh well. return; } } - if (len >= 8192) - { - trap->FS_Close( f ); + if (len >= 8192) { + trap->FS_Close(f); return; } @@ -1215,10 +1012,8 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) )) - { - switch((int)(trap->Cvar_VariableValue("ui_myteam"))) - { + if (atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) { + switch ((int)(trap->Cvar_VariableValue("ui_myteam"))) { case TEAM_RED: forceTeam = FORCE_DARKSIDE; break; @@ -1230,13 +1025,12 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) } } - BG_LegalizedForcePowers(fcfBuffer, sizeof (fcfBuffer), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi( Info_ValueForKey( info, "g_gametype" )), 0); - //legalize the config based on the max rank + BG_LegalizedForcePowers(fcfBuffer, sizeof(fcfBuffer), uiMaxRank, ui_freeSaber.integer, forceTeam, atoi(Info_ValueForKey(info, "g_gametype")), 0); + // legalize the config based on the max rank - //now that we're done with the handle, it's time to parse our force data out of the string - //we store strings in rank-side-xxxxxxxxx format (where the x's are individual force power levels) - while (fcfBuffer[i] && fcfBuffer[i] != '-') - { + // now that we're done with the handle, it's time to parse our force data out of the string + // we store strings in rank-side-xxxxxxxxx format (where the x's are individual force power levels) + while (fcfBuffer[i] && fcfBuffer[i] != '-') { singleBuf[c] = fcfBuffer[i]; c++; i++; @@ -1247,16 +1041,14 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) iBuf = atoi(singleBuf); - if (iBuf > uiMaxRank || iBuf < 0) - { //this force config uses a rank level higher than our currently restricted level.. so we can't use it - //FIXME: Print a message indicating this to the user + if (iBuf > uiMaxRank || iBuf < 0) { // this force config uses a rank level higher than our currently restricted level.. so we can't use it + // FIXME: Print a message indicating this to the user return; } uiForceRank = iBuf; - while (fcfBuffer[i] && fcfBuffer[i] != '-') - { + while (fcfBuffer[i] && fcfBuffer[i] != '-') { singleBuf[c] = fcfBuffer[i]; c++; i++; @@ -1267,16 +1059,13 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) uiForceSide = atoi(singleBuf); - if (uiForceSide != FORCE_LIGHTSIDE && - uiForceSide != FORCE_DARKSIDE) - { + if (uiForceSide != FORCE_LIGHTSIDE && uiForceSide != FORCE_DARKSIDE) { uiForceSide = FORCE_LIGHTSIDE; return; } - //clear out the existing powers - while (c < NUM_FORCE_POWERS) - { + // clear out the existing powers + while (c < NUM_FORCE_POWERS) { /* if (c==FP_LEVITATION) { @@ -1295,7 +1084,7 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) uiForcePowersRank[c] = 0; } */ - //rww - don't need to do these checks. Just trust whatever the saber config says. + // rww - don't need to do these checks. Just trust whatever the saber config says. uiForcePowersRank[c] = 0; c++; } @@ -1303,34 +1092,29 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) uiForceAvailable = forceMasteryPoints[uiForceRank]; gTouchedForce = qtrue; - for (c=0;fcfBuffer[i]&&c FORCE_LEVEL_3 || forcePowerRank < 0) - { //err.. not correct - continue; // skip this power + if (forcePowerRank > FORCE_LEVEL_3 || forcePowerRank < 0) { // err.. not correct + continue; // skip this power } - if (uiForcePowerDarkLight[c] && uiForcePowerDarkLight[c] != uiForceSide) - { //Apparently the user has crafted a force config that has powers that don't fit with the config's side. - continue; // skip this power + if (uiForcePowerDarkLight[c] && + uiForcePowerDarkLight[c] != uiForceSide) { // Apparently the user has crafted a force config that has powers that don't fit with the config's side. + continue; // skip this power } // Accrue cost for each assigned rank for this power. - for (currank=FORCE_LEVEL_1;currank<=forcePowerRank;currank++) - { - if (bgForcePowerCost[c][currank] > uiForceAvailable) - { // Break out, we can't afford any more power. + for (currank = FORCE_LEVEL_1; currank <= forcePowerRank; currank++) { + if (bgForcePowerCost[c][currank] > uiForceAvailable) { // Break out, we can't afford any more power. break; } // Pay for this rank of this power. @@ -1341,17 +1125,14 @@ void UI_ForceConfigHandle( int oldindex, int newindex ) } } - if (uiForcePowersRank[FP_LEVITATION] < 1) - { - uiForcePowersRank[FP_LEVITATION]=1; + if (uiForcePowersRank[FP_LEVITATION] < 1) { + uiForcePowersRank[FP_LEVITATION] = 1; } - if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer) - { - uiForcePowersRank[FP_SABER_OFFENSE]=1; + if (uiForcePowersRank[FP_SABER_OFFENSE] < 1 && ui_freeSaber.integer) { + uiForcePowersRank[FP_SABER_OFFENSE] = 1; } - if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer) - { - uiForcePowersRank[FP_SABER_DEFENSE]=1; + if (uiForcePowersRank[FP_SABER_DEFENSE] < 1 && ui_freeSaber.integer) { + uiForcePowersRank[FP_SABER_DEFENSE] = 1; } UpdateForceUsed(); diff --git a/codemp/ui/ui_gameinfo.c b/codemp/ui/ui_gameinfo.c index f348d9cf19..dcce2eb089 100644 --- a/codemp/ui/ui_gameinfo.c +++ b/codemp/ui/ui_gameinfo.c @@ -27,79 +27,74 @@ along with this program; if not, see . #include "ui_local.h" - // // arena and bot info // +int ui_numBots; +static char *ui_botInfos[MAX_BOTS]; -int ui_numBots; -static char *ui_botInfos[MAX_BOTS]; - -static int ui_numArenas; -static char *ui_arenaInfos[MAX_ARENAS]; +static int ui_numArenas; +static char *ui_arenaInfos[MAX_ARENAS]; /* =============== UI_ParseInfos =============== */ -int UI_ParseInfos( char *buf, int max, char *infos[] ) { - char *token; - int count; - char key[MAX_TOKEN_CHARS]; - char info[MAX_INFO_STRING]; +int UI_ParseInfos(char *buf, int max, char *infos[]) { + char *token; + int count; + char key[MAX_TOKEN_CHARS]; + char info[MAX_INFO_STRING]; count = 0; - COM_BeginParseSession ("UI_ParseInfos"); - while ( 1 ) { - token = COM_Parse( (const char **)&buf ); - if ( !token[0] ) { + COM_BeginParseSession("UI_ParseInfos"); + while (1) { + token = COM_Parse((const char **)&buf); + if (!token[0]) { break; } - if ( strcmp( token, "{" ) ) { - Com_Printf( "Missing { in info file\n" ); + if (strcmp(token, "{")) { + Com_Printf("Missing { in info file\n"); break; } - if ( count == max ) { - Com_Printf( "Max infos exceeded\n" ); + if (count == max) { + Com_Printf("Max infos exceeded\n"); break; } info[0] = '\0'; - while ( 1 ) { - token = COM_ParseExt( (const char **)&buf, qtrue ); - if ( !token[0] ) { - Com_Printf( "Unexpected end of info file\n" ); + while (1) { + token = COM_ParseExt((const char **)&buf, qtrue); + if (!token[0]) { + Com_Printf("Unexpected end of info file\n"); break; } - if ( !strcmp( token, "}" ) ) { + if (!strcmp(token, "}")) { break; } - Q_strncpyz( key, token, sizeof( key ) ); + Q_strncpyz(key, token, sizeof(key)); - token = COM_ParseExt( (const char **)&buf, qfalse ); - if ( !token[0] ) { - strcpy( token, "" ); + token = COM_ParseExt((const char **)&buf, qfalse); + if (!token[0]) { + strcpy(token, ""); } - Info_SetValueForKey( info, key, token ); + Info_SetValueForKey(info, key, token); } - //NOTE: extra space for arena number - infos[count] = (char *) UI_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1); + // NOTE: extra space for arena number + infos[count] = (char *)UI_Alloc(strlen(info) + strlen("\\num\\") + strlen(va("%d", MAX_ARENAS)) + 1); if (infos[count]) { strcpy(infos[count], info); #ifndef FINAL_BUILD - if (trap->Cvar_VariableValue("com_buildScript")) - { + if (trap->Cvar_VariableValue("com_buildScript")) { char *botFile = Info_ValueForKey(info, "personality"); - if (botFile && botFile[0]) - { + if (botFile && botFile[0]) { int fh = 0; trap->FS_Open(botFile, &fh, FS_READ); - if (fh) - { + if (fh) { trap->FS_Close(fh); } } @@ -116,27 +111,27 @@ int UI_ParseInfos( char *buf, int max, char *infos[] ) { UI_LoadArenasFromFile =============== */ -static void UI_LoadArenasFromFile( char *filename ) { - int len; - fileHandle_t f; - char buf[MAX_ARENAS_TEXT]; - - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "file not found: %s\n", filename ); +static void UI_LoadArenasFromFile(char *filename) { + int len; + fileHandle_t f; + char buf[MAX_ARENAS_TEXT]; + + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "file not found: %s\n", filename); return; } - if ( len >= MAX_ARENAS_TEXT ) { - trap->Print( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_ARENAS_TEXT ); - trap->FS_Close( f ); + if (len >= MAX_ARENAS_TEXT) { + trap->Print(S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_ARENAS_TEXT); + trap->FS_Close(f); return; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); + trap->FS_Close(f); - ui_numArenas += UI_ParseInfos( buf, MAX_ARENAS - ui_numArenas, &ui_arenaInfos[ui_numArenas] ); + ui_numArenas += UI_ParseInfos(buf, MAX_ARENAS - ui_numArenas, &ui_arenaInfos[ui_numArenas]); } /* @@ -146,33 +141,33 @@ UI_LoadArenas */ #define MAPSBUFSIZE (MAX_MAPS * 64) -void UI_LoadArenas( void ) { - int numdirs; - char filename[MAX_QPATH]; - char dirlist[MAPSBUFSIZE]; - char* dirptr; - int i, n; - int dirlen; - char *type; +void UI_LoadArenas(void) { + int numdirs; + char filename[MAX_QPATH]; + char dirlist[MAPSBUFSIZE]; + char *dirptr; + int i, n; + int dirlen; + char *type; ui_numArenas = 0; uiInfo.mapCount = 0; // get all arenas from .arena files - numdirs = trap->FS_GetFileList( "scripts", ".arena", dirlist, ARRAY_LEN( dirlist ) ); - dirptr = dirlist; - for (i = 0; i < numdirs; i++, dirptr += dirlen+1) { + numdirs = trap->FS_GetFileList("scripts", ".arena", dirlist, ARRAY_LEN(dirlist)); + dirptr = dirlist; + for (i = 0; i < numdirs; i++, dirptr += dirlen + 1) { dirlen = strlen(dirptr); strcpy(filename, "scripts/"); strcat(filename, dirptr); UI_LoadArenasFromFile(filename); } -// trap->Print( "%i arenas parsed\n", ui_numArenas ); + // trap->Print( "%i arenas parsed\n", ui_numArenas ); if (UI_OutOfMemory()) { - trap->Print(S_COLOR_YELLOW"WARNING: not anough memory in pool to load all arenas\n"); + trap->Print(S_COLOR_YELLOW "WARNING: not anough memory in pool to load all arenas\n"); } - for( n = 0; n < ui_numArenas; n++ ) { + for (n = 0; n < ui_numArenas; n++) { // determine type uiInfo.mapList[uiInfo.mapCount].cinematic = -1; @@ -182,36 +177,36 @@ void UI_LoadArenas( void ) { uiInfo.mapList[uiInfo.mapCount].imageName = String_Alloc(va("levelshots/%s", uiInfo.mapList[uiInfo.mapCount].mapLoadName)); uiInfo.mapList[uiInfo.mapCount].typeBits = 0; - type = Info_ValueForKey( ui_arenaInfos[n], "type" ); + type = Info_ValueForKey(ui_arenaInfos[n], "type"); // if no type specified, it will be treated as "ffa" - if( *type ) { - if( strstr( type, "ffa" ) ) { + if (*type) { + if (strstr(type, "ffa")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_FFA); uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_TEAM); uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_JEDIMASTER); } - if( strstr( type, "holocron" ) ) { + if (strstr(type, "holocron")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_HOLOCRON); } - if( strstr( type, "jedimaster" ) ) { + if (strstr(type, "jedimaster")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_JEDIMASTER); } - if( strstr( type, "duel" ) ) { + if (strstr(type, "duel")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_DUEL); uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_POWERDUEL); } - if( strstr( type, "powerduel" ) ) { + if (strstr(type, "powerduel")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_DUEL); uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_POWERDUEL); } - if( strstr( type, "siege" ) ) { + if (strstr(type, "siege")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_SIEGE); } - if( strstr( type, "ctf" ) ) { + if (strstr(type, "ctf")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_CTF); uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_CTY); } - if( strstr( type, "cty" ) ) { + if (strstr(type, "cty")) { uiInfo.mapList[uiInfo.mapCount].typeBits |= (1 << GT_CTY); } } else { @@ -226,55 +221,52 @@ void UI_LoadArenas( void ) { } } - /* =============== UI_LoadBotsFromFile =============== */ -static void UI_LoadBotsFromFile( char *filename ) { - int len; - fileHandle_t f; - char buf[MAX_BOTS_TEXT]; - char *stopMark; - - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "file not found: %s\n", filename ); +static void UI_LoadBotsFromFile(char *filename) { + int len; + fileHandle_t f; + char buf[MAX_BOTS_TEXT]; + char *stopMark; + + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "file not found: %s\n", filename); return; } - if ( len >= MAX_BOTS_TEXT ) { - trap->Print( S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_BOTS_TEXT ); - trap->FS_Close( f ); + if (len >= MAX_BOTS_TEXT) { + trap->Print(S_COLOR_RED "file too large: %s is %i, max allowed is %i", filename, len, MAX_BOTS_TEXT); + trap->FS_Close(f); return; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; stopMark = strstr(buf, "@STOPHERE"); - //This bot is in place as a mark for modview's bot viewer. - //If we hit it just stop and trace back to the beginning of the bot define and cut the string off. - //This is only done in the UI and not the game so that "test" bots can be added manually and still - //not show up in the menu. - if (stopMark) - { + // This bot is in place as a mark for modview's bot viewer. + // If we hit it just stop and trace back to the beginning of the bot define and cut the string off. + // This is only done in the UI and not the game so that "test" bots can be added manually and still + // not show up in the menu. + if (stopMark) { int startPoint = stopMark - buf; - while (buf[startPoint] != '{') - { + while (buf[startPoint] != '{') { startPoint--; } buf[startPoint] = 0; } - trap->FS_Close( f ); + trap->FS_Close(f); COM_Compress(buf); - ui_numBots += UI_ParseInfos( buf, MAX_BOTS - ui_numBots, &ui_botInfos[ui_numBots] ); + ui_numBots += UI_ParseInfos(buf, MAX_BOTS - ui_numBots, &ui_botInfos[ui_numBots]); } /* @@ -282,64 +274,61 @@ static void UI_LoadBotsFromFile( char *filename ) { UI_LoadBots =============== */ -void UI_LoadBots( void ) { - vmCvar_t botsFile; - int numdirs; - char filename[128]; - char dirlist[1024]; - char* dirptr; - int i; - int dirlen; +void UI_LoadBots(void) { + vmCvar_t botsFile; + int numdirs; + char filename[128]; + char dirlist[1024]; + char *dirptr; + int i; + int dirlen; ui_numBots = 0; - trap->Cvar_Register( &botsFile, "g_botsFile", "", CVAR_INIT|CVAR_ROM ); - if( *botsFile.string ) { + trap->Cvar_Register(&botsFile, "g_botsFile", "", CVAR_INIT | CVAR_ROM); + if (*botsFile.string) { UI_LoadBotsFromFile(botsFile.string); - } - else { + } else { UI_LoadBotsFromFile("botfiles/bots.txt"); } // get all bots from .bot files - numdirs = trap->FS_GetFileList("scripts", ".bot", dirlist, 1024 ); - dirptr = dirlist; - for (i = 0; i < numdirs; i++, dirptr += dirlen+1) { + numdirs = trap->FS_GetFileList("scripts", ".bot", dirlist, 1024); + dirptr = dirlist; + for (i = 0; i < numdirs; i++, dirptr += dirlen + 1) { dirlen = strlen(dirptr); strcpy(filename, "scripts/"); strcat(filename, dirptr); UI_LoadBotsFromFile(filename); } -// trap->Print( "%i bots parsed\n", ui_numBots ); + // trap->Print( "%i bots parsed\n", ui_numBots ); } - /* =============== UI_GetBotInfoByNumber =============== */ -char *UI_GetBotInfoByNumber( int num ) { - if( num < 0 || num >= ui_numBots ) { - trap->Print( S_COLOR_RED "Invalid bot number: %i\n", num ); +char *UI_GetBotInfoByNumber(int num) { + if (num < 0 || num >= ui_numBots) { + trap->Print(S_COLOR_RED "Invalid bot number: %i\n", num); return NULL; } return ui_botInfos[num]; } - /* =============== UI_GetBotInfoByName =============== */ -char *UI_GetBotInfoByName( const char *name ) { - int n; - char *value; +char *UI_GetBotInfoByName(const char *name) { + int n; + char *value; - for ( n = 0; n < ui_numBots ; n++ ) { - value = Info_ValueForKey( ui_botInfos[n], "name" ); - if ( !Q_stricmp( value, name ) ) { + for (n = 0; n < ui_numBots; n++) { + value = Info_ValueForKey(ui_botInfos[n], "name"); + if (!Q_stricmp(value, name)) { return ui_botInfos[n]; } } @@ -347,15 +336,12 @@ char *UI_GetBotInfoByName( const char *name ) { return NULL; } -int UI_GetNumBots() { - return ui_numBots; -} - +int UI_GetNumBots() { return ui_numBots; } -char *UI_GetBotNameByNumber( int num ) { +char *UI_GetBotNameByNumber(int num) { char *info = UI_GetBotInfoByNumber(num); if (info) { - return Info_ValueForKey( info, "name" ); + return Info_ValueForKey(info, "name"); } return "Kyle"; } diff --git a/codemp/ui/ui_main.c b/codemp/ui/ui_main.c index 45501d9479..066c214b59 100644 --- a/codemp/ui/ui_main.c +++ b/codemp/ui/ui_main.c @@ -44,215 +44,173 @@ USER INTERFACE MAIN #include "game/bg_saga.h" #include "ui_shared.h" -NORETURN_PTR void (*Com_Error)( int level, const char *error, ... ); -void (*Com_Printf)( const char *msg, ... ); +NORETURN_PTR void (*Com_Error)(int level, const char *error, ...); +void (*Com_Printf)(const char *msg, ...); -extern void UI_SaberAttachToChar( itemDef_t *item ); +extern void UI_SaberAttachToChar(itemDef_t *item); -const char *forcepowerDesc[NUM_FORCE_POWERS] = -{ - "@MENUS_OF_EFFECT_JEDI_ONLY_NEFFECT", - "@MENUS_DURATION_IMMEDIATE_NAREA", - "@MENUS_DURATION_5_SECONDS_NAREA", - "@MENUS_DURATION_INSTANTANEOUS", - "@MENUS_INSTANTANEOUS_EFFECT_NAREA", - "@MENUS_DURATION_VARIABLE_20", - "@MENUS_DURATION_INSTANTANEOUS_NAREA", - "@MENUS_OF_EFFECT_LIVING_PERSONS", - "@MENUS_DURATION_VARIABLE_10", - "@MENUS_DURATION_VARIABLE_NAREA", - "@MENUS_DURATION_CONTINUOUS_NAREA", - "@MENUS_OF_EFFECT_JEDI_ALLIES_NEFFECT", - "@MENUS_EFFECT_JEDI_ALLIES_NEFFECT", - "@MENUS_VARIABLE_NAREA_OF_EFFECT", - "@MENUS_EFFECT_NAREA_OF_EFFECT", - "@SP_INGAME_FORCE_SABER_OFFENSE_DESC", - "@SP_INGAME_FORCE_SABER_DEFENSE_DESC", - "@SP_INGAME_FORCE_SABER_THROW_DESC" -}; +const char *forcepowerDesc[NUM_FORCE_POWERS] = { + "@MENUS_OF_EFFECT_JEDI_ONLY_NEFFECT", "@MENUS_DURATION_IMMEDIATE_NAREA", "@MENUS_DURATION_5_SECONDS_NAREA", "@MENUS_DURATION_INSTANTANEOUS", + "@MENUS_INSTANTANEOUS_EFFECT_NAREA", "@MENUS_DURATION_VARIABLE_20", "@MENUS_DURATION_INSTANTANEOUS_NAREA", "@MENUS_OF_EFFECT_LIVING_PERSONS", + "@MENUS_DURATION_VARIABLE_10", "@MENUS_DURATION_VARIABLE_NAREA", "@MENUS_DURATION_CONTINUOUS_NAREA", "@MENUS_OF_EFFECT_JEDI_ALLIES_NEFFECT", + "@MENUS_EFFECT_JEDI_ALLIES_NEFFECT", "@MENUS_VARIABLE_NAREA_OF_EFFECT", "@MENUS_EFFECT_NAREA_OF_EFFECT", "@SP_INGAME_FORCE_SABER_OFFENSE_DESC", + "@SP_INGAME_FORCE_SABER_DEFENSE_DESC", "@SP_INGAME_FORCE_SABER_THROW_DESC"}; // Movedata Sounds -enum -{ - MDS_NONE = 0, - MDS_FORCE_JUMP, - MDS_ROLL, - MDS_SABER, - MDS_MOVE_SOUNDS_MAX -}; +enum { MDS_NONE = 0, MDS_FORCE_JUMP, MDS_ROLL, MDS_SABER, MDS_MOVE_SOUNDS_MAX }; -enum -{ - MD_ACROBATICS = 0, - MD_SINGLE_FAST, - MD_SINGLE_MEDIUM, - MD_SINGLE_STRONG, - MD_DUAL_SABERS, - MD_SABER_STAFF, - MD_MOVE_TITLE_MAX -}; +enum { MD_ACROBATICS = 0, MD_SINGLE_FAST, MD_SINGLE_MEDIUM, MD_SINGLE_STRONG, MD_DUAL_SABERS, MD_SABER_STAFF, MD_MOVE_TITLE_MAX }; // Some hard coded badness // At some point maybe this should be externalized to a .dat file -const char *datapadMoveTitleData[MD_MOVE_TITLE_MAX] = -{ -"@MENUS_ACROBATICS", -"@MENUS_SINGLE_FAST", -"@MENUS_SINGLE_MEDIUM", -"@MENUS_SINGLE_STRONG", -"@MENUS_DUAL_SABERS", -"@MENUS_SABER_STAFF", +const char *datapadMoveTitleData[MD_MOVE_TITLE_MAX] = { + "@MENUS_ACROBATICS", "@MENUS_SINGLE_FAST", "@MENUS_SINGLE_MEDIUM", "@MENUS_SINGLE_STRONG", "@MENUS_DUAL_SABERS", "@MENUS_SABER_STAFF", }; -const char *datapadMoveTitleBaseAnims[MD_MOVE_TITLE_MAX] = -{ -"BOTH_RUN1", -"BOTH_SABERFAST_STANCE", -"BOTH_STAND2", -"BOTH_SABERSLOW_STANCE", -"BOTH_SABERDUAL_STANCE", -"BOTH_SABERSTAFF_STANCE", +const char *datapadMoveTitleBaseAnims[MD_MOVE_TITLE_MAX] = { + "BOTH_RUN1", "BOTH_SABERFAST_STANCE", "BOTH_STAND2", "BOTH_SABERSLOW_STANCE", "BOTH_SABERDUAL_STANCE", "BOTH_SABERSTAFF_STANCE", }; #define MAX_MOVES 16 -typedef struct datpadmovedata_s -{ - const char *title; - const char *desc; - const char *anim; - short sound; +typedef struct datpadmovedata_s { + const char *title; + const char *desc; + const char *anim; + short sound; } datpadmovedata_t; static datpadmovedata_t datapadMoveData[MD_MOVE_TITLE_MAX][MAX_MOVES] = { - {// Acrobatics - { "@MENUS_FORCE_JUMP1", "@MENUS_FORCE_JUMP1_DESC", "BOTH_FORCEJUMP1", MDS_FORCE_JUMP }, - { "@MENUS_FORCE_FLIP", "@MENUS_FORCE_FLIP_DESC", "BOTH_FLIP_F", MDS_FORCE_JUMP }, - { "@MENUS_ROLL", "@MENUS_ROLL_DESC", "BOTH_ROLL_F", MDS_ROLL }, - { "@MENUS_BACKFLIP_OFF_WALL", "@MENUS_BACKFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_BACK1", MDS_FORCE_JUMP }, - { "@MENUS_SIDEFLIP_OFF_WALL", "@MENUS_SIDEFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_WALL_RUN", "@MENUS_WALL_RUN_DESC", "BOTH_WALL_RUN_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_WALL_GRAB_JUMP", "@MENUS_WALL_GRAB_JUMP_DESC", "BOTH_FORCEWALLREBOUND_FORWARD",MDS_FORCE_JUMP }, - { "@MENUS_RUN_UP_WALL_BACKFLIP", "@MENUS_RUN_UP_WALL_BACKFLIP_DESC", "BOTH_FORCEWALLRUNFLIP_START", MDS_FORCE_JUMP }, - { "@MENUS_JUMPUP_FROM_KNOCKDOWN", "@MENUS_JUMPUP_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN3", MDS_NONE }, - { "@MENUS_JUMPKICK_FROM_KNOCKDOWN", "@MENUS_JUMPKICK_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN2", MDS_NONE }, - { "@MENUS_ROLL_FROM_KNOCKDOWN", "@MENUS_ROLL_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN1", MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, + { + // Acrobatics + {"@MENUS_FORCE_JUMP1", "@MENUS_FORCE_JUMP1_DESC", "BOTH_FORCEJUMP1", MDS_FORCE_JUMP}, + {"@MENUS_FORCE_FLIP", "@MENUS_FORCE_FLIP_DESC", "BOTH_FLIP_F", MDS_FORCE_JUMP}, + {"@MENUS_ROLL", "@MENUS_ROLL_DESC", "BOTH_ROLL_F", MDS_ROLL}, + {"@MENUS_BACKFLIP_OFF_WALL", "@MENUS_BACKFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_BACK1", MDS_FORCE_JUMP}, + {"@MENUS_SIDEFLIP_OFF_WALL", "@MENUS_SIDEFLIP_OFF_WALL_DESC", "BOTH_WALL_FLIP_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_WALL_RUN", "@MENUS_WALL_RUN_DESC", "BOTH_WALL_RUN_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_WALL_GRAB_JUMP", "@MENUS_WALL_GRAB_JUMP_DESC", "BOTH_FORCEWALLREBOUND_FORWARD", MDS_FORCE_JUMP}, + {"@MENUS_RUN_UP_WALL_BACKFLIP", "@MENUS_RUN_UP_WALL_BACKFLIP_DESC", "BOTH_FORCEWALLRUNFLIP_START", MDS_FORCE_JUMP}, + {"@MENUS_JUMPUP_FROM_KNOCKDOWN", "@MENUS_JUMPUP_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN3", MDS_NONE}, + {"@MENUS_JUMPKICK_FROM_KNOCKDOWN", "@MENUS_JUMPKICK_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN2", MDS_NONE}, + {"@MENUS_ROLL_FROM_KNOCKDOWN", "@MENUS_ROLL_FROM_KNOCKDOWN_DESC", "BOTH_KNOCKDOWN1", MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, }, - {//Single Saber, Fast Style - { "@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER }, - { "@MENUS_LUNGE_ATTACK", "@MENUS_LUNGE_ATTACK_DESC", "BOTH_LUNGE2_B__T_", MDS_SABER }, - { "@MENUS_FAST_ATTACK_KATA", "@MENUS_FAST_ATTACK_KATA_DESC", "BOTH_A1_SPECIAL", MDS_SABER }, - { "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, - { "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, + { + // Single Saber, Fast Style + {"@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER}, + {"@MENUS_LUNGE_ATTACK", "@MENUS_LUNGE_ATTACK_DESC", "BOTH_LUNGE2_B__T_", MDS_SABER}, + {"@MENUS_FAST_ATTACK_KATA", "@MENUS_FAST_ATTACK_KATA_DESC", "BOTH_A1_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, }, - {//Single Saber, Medium Style - { "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, - { "@MENUS_FLIP_ATTACK", "@MENUS_FLIP_ATTACK_DESC", "BOTH_JUMPFLIPSLASHDOWN1", MDS_FORCE_JUMP }, - { "@MENUS_MEDIUM_ATTACK_KATA", "@MENUS_MEDIUM_ATTACK_KATA_DESC", "BOTH_A2_SPECIAL", MDS_SABER }, - { "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, - { "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, + { + // Single Saber, Medium Style + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_FLIP_ATTACK", "@MENUS_FLIP_ATTACK_DESC", "BOTH_JUMPFLIPSLASHDOWN1", MDS_FORCE_JUMP}, + {"@MENUS_MEDIUM_ATTACK_KATA", "@MENUS_MEDIUM_ATTACK_KATA_DESC", "BOTH_A2_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, }, - {//Single Saber, Strong Style - { "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, - { "@MENUS_JUMP_ATTACK", "@MENUS_JUMP_ATTACK_DESC", "BOTH_FORCELEAP2_T__B_", MDS_FORCE_JUMP }, - { "@MENUS_STRONG_ATTACK_KATA", "@MENUS_STRONG_ATTACK_KATA_DESC", "BOTH_A3_SPECIAL", MDS_SABER }, - { "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP }, - { "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, + { + // Single Saber, Strong Style + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_JUMP_ATTACK", "@MENUS_JUMP_ATTACK_DESC", "BOTH_FORCELEAP2_T__B_", MDS_FORCE_JUMP}, + {"@MENUS_STRONG_ATTACK_KATA", "@MENUS_STRONG_ATTACK_KATA_DESC", "BOTH_A3_SPECIAL", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN", MDS_FORCE_JUMP}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, }, - {//Dual Sabers - { "@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER }, - { "@MENUS_FLIP_FORWARD_ATTACK", "@MENUS_FLIP_FORWARD_ATTACK_DESC", "BOTH_JUMPATTACK6", MDS_FORCE_JUMP }, - { "@MENUS_DUAL_SABERS_TWIRL", "@MENUS_DUAL_SABERS_TWIRL_DESC", "BOTH_SPINATTACK6", MDS_SABER }, - { "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_DUAL", MDS_FORCE_JUMP }, - { "@MENUS_DUAL_SABER_BARRIER", "@MENUS_DUAL_SABER_BARRIER_DESC", "BOTH_A6_SABERPROTECT", MDS_SABER }, - { "@MENUS_DUAL_STAB_FRONT_BACK", "@MENUS_DUAL_STAB_FRONT_BACK_DESC", "BOTH_A6_FB", MDS_SABER }, - { "@MENUS_DUAL_STAB_LEFT_RIGHT", "@MENUS_DUAL_STAB_LEFT_RIGHT_DESC", "BOTH_A6_LR", MDS_SABER }, - { "@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP }, - { "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB_DESC", "BOTH_ROLL_STAB", MDS_SABER }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, + { + // Dual Sabers + {"@MENUS_SLASH_BACK", "@MENUS_SLASH_BACK_DESC", "BOTH_ATTACK_BACK", MDS_SABER}, + {"@MENUS_FLIP_FORWARD_ATTACK", "@MENUS_FLIP_FORWARD_ATTACK_DESC", "BOTH_JUMPATTACK6", MDS_FORCE_JUMP}, + {"@MENUS_DUAL_SABERS_TWIRL", "@MENUS_DUAL_SABERS_TWIRL_DESC", "BOTH_SPINATTACK6", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_DUAL", MDS_FORCE_JUMP}, + {"@MENUS_DUAL_SABER_BARRIER", "@MENUS_DUAL_SABER_BARRIER_DESC", "BOTH_A6_SABERPROTECT", MDS_SABER}, + {"@MENUS_DUAL_STAB_FRONT_BACK", "@MENUS_DUAL_STAB_FRONT_BACK_DESC", "BOTH_A6_FB", MDS_SABER}, + {"@MENUS_DUAL_STAB_LEFT_RIGHT", "@MENUS_DUAL_STAB_LEFT_RIGHT_DESC", "BOTH_A6_LR", MDS_SABER}, + {"@MENUS_CARTWHEEL", "@MENUS_CARTWHEEL_DESC", "BOTH_ARIAL_RIGHT", MDS_FORCE_JUMP}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, }, {// Saber Staff - { "@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER }, - { "@MENUS_BACK_FLIP_ATTACK", "@MENUS_BACK_FLIP_ATTACK_DESC", "BOTH_JUMPATTACK7", MDS_FORCE_JUMP }, - { "@MENUS_SABER_STAFF_TWIRL", "@MENUS_SABER_STAFF_TWIRL_DESC", "BOTH_SPINATTACK7", MDS_SABER }, - { "@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_STAFF", MDS_FORCE_JUMP }, - { "@MENUS_SPINNING_KATA", "@MENUS_SPINNING_KATA_DESC", "BOTH_A7_SOULCAL", MDS_SABER }, - { "@MENUS_KICK1", "@MENUS_KICK1_DESC", "BOTH_A7_KICK_F", MDS_FORCE_JUMP }, - { "@MENUS_JUMP_KICK", "@MENUS_JUMP_KICK_DESC", "BOTH_A7_KICK_F_AIR", MDS_FORCE_JUMP }, - { "@MENUS_BUTTERFLY_ATTACK", "@MENUS_BUTTERFLY_ATTACK_DESC", "BOTH_BUTTERFLY_FR1", MDS_SABER }, - { "@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE }, - { NULL, NULL, NULL, MDS_NONE } - } -}; + {"@MENUS_STAB_BACK", "@MENUS_STAB_BACK_DESC", "BOTH_A2_STABBACK1", MDS_SABER}, + {"@MENUS_BACK_FLIP_ATTACK", "@MENUS_BACK_FLIP_ATTACK_DESC", "BOTH_JUMPATTACK7", MDS_FORCE_JUMP}, + {"@MENUS_SABER_STAFF_TWIRL", "@MENUS_SABER_STAFF_TWIRL_DESC", "BOTH_SPINATTACK7", MDS_SABER}, + {"@MENUS_ATTACK_ENEMYONGROUND", "@MENUS_ATTACK_ENEMYONGROUND_DESC", "BOTH_STABDOWN_STAFF", MDS_FORCE_JUMP}, + {"@MENUS_SPINNING_KATA", "@MENUS_SPINNING_KATA_DESC", "BOTH_A7_SOULCAL", MDS_SABER}, + {"@MENUS_KICK1", "@MENUS_KICK1_DESC", "BOTH_A7_KICK_F", MDS_FORCE_JUMP}, + {"@MENUS_JUMP_KICK", "@MENUS_JUMP_KICK_DESC", "BOTH_A7_KICK_F_AIR", MDS_FORCE_JUMP}, + {"@MENUS_BUTTERFLY_ATTACK", "@MENUS_BUTTERFLY_ATTACK_DESC", "BOTH_BUTTERFLY_FR1", MDS_SABER}, + {"@MENUS_BOTH_ROLL_STAB", "@MENUS_BOTH_ROLL_STAB2_DESC", "BOTH_ROLL_STAB", MDS_SABER}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}, + {NULL, NULL, NULL, MDS_NONE}}}; static siegeClassDesc_t g_UIClassDescriptions[MAX_SIEGE_CLASSES]; static siegeTeam_t *siegeTeam1 = NULL, *siegeTeam2 = NULL; static int g_UIGloballySelectedSiegeClass = -1; -//Cut down version of the stuff used in the game code -//This is just the bare essentials of what we need to load animations properly for ui ghoul2 models. -//This function doesn't need to be sync'd with the BG_ version in bg_panimate.c unless some sort of fundamental change -//is made. Just make sure the variables/functions accessed in ui_shared.c exist in both modules. -qboolean UIPAFtextLoaded = qfalse; -animation_t uiHumanoidAnimations[MAX_TOTALANIMATIONS]; //humanoid animations are the only ones that are statically allocated. +// Cut down version of the stuff used in the game code +// This is just the bare essentials of what we need to load animations properly for ui ghoul2 models. +// This function doesn't need to be sync'd with the BG_ version in bg_panimate.c unless some sort of fundamental change +// is made. Just make sure the variables/functions accessed in ui_shared.c exist in both modules. +qboolean UIPAFtextLoaded = qfalse; +animation_t uiHumanoidAnimations[MAX_TOTALANIMATIONS]; // humanoid animations are the only ones that are statically allocated. bgLoadedAnim_t bgAllAnims[MAX_ANIM_FILES]; -int uiNumAllAnims = 1; //start off at 0, because 0 will always be assigned to humanoid. +int uiNumAllAnims = 1; // start off at 0, because 0 will always be assigned to humanoid. -animation_t *UI_AnimsetAlloc(void) -{ - assert (uiNumAllAnims < MAX_ANIM_FILES); - bgAllAnims[uiNumAllAnims].anims = (animation_t *) BG_Alloc(sizeof(animation_t)*MAX_TOTALANIMATIONS); +animation_t *UI_AnimsetAlloc(void) { + assert(uiNumAllAnims < MAX_ANIM_FILES); + bgAllAnims[uiNumAllAnims].anims = (animation_t *)BG_Alloc(sizeof(animation_t) * MAX_TOTALANIMATIONS); return bgAllAnims[uiNumAllAnims].anims; } @@ -267,47 +225,38 @@ models/players/visor/animation.cfg, etc ====================== */ static char UIPAFtext[60000]; -int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) -{ - char *text_p; - int len; - int i; - char *token; - float fps; - int usedIndex = -1; - int nextIndex = uiNumAllAnims; - - fileHandle_t f; - int animNum; - - if (!isHumanoid) - { +int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid) { + char *text_p; + int len; + int i; + char *token; + float fps; + int usedIndex = -1; + int nextIndex = uiNumAllAnims; + + fileHandle_t f; + int animNum; + + if (!isHumanoid) { i = 1; - while (i < uiNumAllAnims) - { //see if it's been loaded already - if (!Q_stricmp(bgAllAnims[i].filename, filename)) - { + while (i < uiNumAllAnims) { // see if it's been loaded already + if (!Q_stricmp(bgAllAnims[i].filename, filename)) { animset = bgAllAnims[i].anims; - return i; //alright, we already have it. + return i; // alright, we already have it. } i++; } - //Looks like it has not yet been loaded. Allocate space for the anim set if we need to, and continue along. - if (!animset) - { - if (strstr(filename, "players/_humanoid/")) - { //then use the static humanoid set. + // Looks like it has not yet been loaded. Allocate space for the anim set if we need to, and continue along. + if (!animset) { + if (strstr(filename, "players/_humanoid/")) { // then use the static humanoid set. animset = uiHumanoidAnimations; isHumanoid = qtrue; nextIndex = 0; - } - else - { + } else { animset = UI_AnimsetAlloc(); - if (!animset) - { + if (!animset) { assert(!"Anim set alloc failed!"); return -1; } @@ -315,115 +264,99 @@ int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i } } #ifdef _DEBUG - else - { + else { assert(animset); } #endif // load the file - if (!UIPAFtextLoaded || !isHumanoid) - { //rww - We are always using the same animation config now. So only load it once. - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { + if (!UIPAFtextLoaded || !isHumanoid) { // rww - We are always using the same animation config now. So only load it once. + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { return -1; } - if ( len >= sizeof( UIPAFtext ) - 1 ) { - trap->FS_Close( f ); + if (len >= sizeof(UIPAFtext) - 1) { + trap->FS_Close(f); Com_Error(ERR_DROP, "%s exceeds the allowed ui-side animation buffer!", filename); } - trap->FS_Read( UIPAFtext, len, f ); + trap->FS_Read(UIPAFtext, len, f); UIPAFtext[len] = 0; - trap->FS_Close( f ); - } - else - { - return 0; //humanoid index + trap->FS_Close(f); + } else { + return 0; // humanoid index } // parse the text text_p = UIPAFtext; - //FIXME: have some way of playing anims backwards... negative numFrames? + // FIXME: have some way of playing anims backwards... negative numFrames? - //initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 - for(i = 0; i < MAX_ANIMATIONS; i++) - { + // initialize anim array so that from 0 to MAX_ANIMATIONS, set default values of 0 1 0 100 + for (i = 0; i < MAX_ANIMATIONS; i++) { animset[i].firstFrame = 0; animset[i].numFrames = 0; animset[i].loopFrames = -1; animset[i].frameLerp = 100; -// animset[i].initialLerp = 100; + // animset[i].initialLerp = 100; } - COM_BeginParseSession ("UI_ParseAnimationFile"); + COM_BeginParseSession("UI_ParseAnimationFile"); // read information for each frame - while(1) - { - token = COM_Parse( (const char **)(&text_p) ); + while (1) { + token = COM_Parse((const char **)(&text_p)); - if ( !token || !token[0]) - { + if (!token || !token[0]) { break; } animNum = GetIDForString(animTable, token); - if(animNum == -1) - { + if (animNum == -1) { //#ifndef FINAL_BUILD #ifdef _DEBUG - //Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, filename); + // Com_Printf(S_COLOR_RED"WARNING: Unknown token %s in %s\n", token, filename); #endif continue; } - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].firstFrame = atoi( token ); + animset[animNum].firstFrame = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].numFrames = atoi( token ); + animset[animNum].numFrames = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - animset[animNum].loopFrames = atoi( token ); + animset[animNum].loopFrames = atoi(token); - token = COM_Parse( (const char **)(&text_p) ); - if ( !token ) - { + token = COM_Parse((const char **)(&text_p)); + if (!token) { break; } - fps = atof( token ); - if ( fps == 0 ) - { - fps = 1;//Don't allow divide by zero error + fps = atof(token); + if (fps == 0) { + fps = 1; // Don't allow divide by zero error } - if ( fps < 0 ) - {//backwards + if (fps < 0) { // backwards animset[animNum].frameLerp = floor(1000.0f / fps); - } - else - { + } else { animset[animNum].frameLerp = ceil(1000.0f / fps); } -// animset[animNum].initialLerp = ceil(1000.0f / fabs(fps)); + // animset[animNum].initialLerp = ceil(1000.0f / fabs(fps)); } #ifdef _DEBUG - //Check the array, and print the ones that have nothing in them. + // Check the array, and print the ones that have nothing in them. /* for(i = 0; i < MAX_ANIMATIONS; i++) { @@ -438,27 +371,21 @@ int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i */ #endif // _DEBUG - if (isHumanoid) - { + if (isHumanoid) { bgAllAnims[0].anims = animset; Q_strncpyz(bgAllAnims[0].filename, filename, sizeof(bgAllAnims[0].filename)); UIPAFtextLoaded = qtrue; usedIndex = 0; - } - else - { + } else { bgAllAnims[nextIndex].anims = animset; Q_strncpyz(bgAllAnims[nextIndex].filename, filename, sizeof(bgAllAnims[nextIndex].filename)); usedIndex = nextIndex; - if (nextIndex) - { //don't bother increasing the number if this ended up as a humanoid load. + if (nextIndex) { // don't bother increasing the number if this ended up as a humanoid load. uiNumAllAnims++; - } - else - { + } else { UIPAFtextLoaded = qtrue; usedIndex = 0; } @@ -467,95 +394,80 @@ int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean i return usedIndex; } -//menuDef_t *Menus_FindByName(const char *p); +// menuDef_t *Menus_FindByName(const char *p); void Menu_ShowItemByName(menuDef_t *menu, const char *p, qboolean bShow); - void UpdateForceUsed(); -char holdSPString[MAX_STRING_CHARS]={0}; +char holdSPString[MAX_STRING_CHARS] = {0}; uiInfo_t uiInfo; static void UI_StartServerRefresh(qboolean full); -static void UI_StopServerRefresh( void ); -static void UI_DoServerRefresh( void ); +static void UI_StopServerRefresh(void); +static void UI_DoServerRefresh(void); static void UI_BuildServerDisplayList(int force); static void UI_BuildServerStatus(qboolean force); static void UI_BuildFindPlayerList(qboolean force); -static int QDECL UI_ServersQsortCompare( const void *arg1, const void *arg2 ); +static int QDECL UI_ServersQsortCompare(const void *arg1, const void *arg2); static int UI_MapCountByGameType(qboolean singlePlayer); -static int UI_HeadCountByColor( void ); +static int UI_HeadCountByColor(void); static void UI_ParseGameInfo(const char *teamFile); static const char *UI_SelectedMap(int index, int *actual); static int UI_GetIndexFromSelection(int actual); -static void UI_SiegeClassCnt( const int team ); +static void UI_SiegeClassCnt(const int team); -int uiSkinColor=TEAM_FREE; -int uiHoldSkinColor=TEAM_FREE; // Stores the skin color so that in non-team games, the player screen remembers the team you chose, in case you're coming back from the force powers screen. +int uiSkinColor = TEAM_FREE; +int uiHoldSkinColor = TEAM_FREE; // Stores the skin color so that in non-team games, the player screen remembers the team you chose, in case you're coming back + // from the force powers screen. static const char *skillLevels[] = { "SKILL1", // "Initiate" "SKILL2", // "Padawan" "SKILL3", // "Jedi" "SKILL4", // "Jedi Knight" - "SKILL5" // "Jedi Master" + "SKILL5" // "Jedi Master" }; -static const size_t numSkillLevels = ARRAY_LEN( skillLevels ); +static const size_t numSkillLevels = ARRAY_LEN(skillLevels); static const char *gameTypes[GT_MAX_GAME_TYPE] = { - "FFA", - "Holocron", - "JediMaster", - "Duel", - "PowerDuel", - "SP", - "Team FFA", - "Siege", - "CTF", - "CTY", + "FFA", "Holocron", "JediMaster", "Duel", "PowerDuel", "SP", "Team FFA", "Siege", "CTF", "CTY", }; -static const int numGameTypes = ARRAY_LEN( gameTypes ); +static const int numGameTypes = ARRAY_LEN(gameTypes); -static char* netNames[] = { - "???", - "UDP", - NULL -}; +static char *netNames[] = {"???", "UDP", NULL}; -static const int numNetNames = ARRAY_LEN( netNames ) - 1; +static const int numNetNames = ARRAY_LEN(netNames) - 1; const char *UI_GetStringEdString(const char *refSection, const char *refName); const char *UI_TeamName(int team) { - if (team==TEAM_RED) + if (team == TEAM_RED) return "RED"; - else if (team==TEAM_BLUE) + else if (team == TEAM_BLUE) return "BLUE"; - else if (team==TEAM_SPECTATOR) + else if (team == TEAM_SPECTATOR) return "SPECTATOR"; return "FREE"; } // returns either string or NULL for OOR... // -static const char *GetCRDelineatedString( const char *psStripFileRef, const char *psStripStringRef, int iIndex) -{ +static const char *GetCRDelineatedString(const char *psStripFileRef, const char *psStripStringRef, int iIndex) { static char sTemp[256]; const char *psList = UI_GetStringEdString(psStripFileRef, psStripStringRef); char *p; - while (iIndex--) - { - psList = strchr(psList,'\n'); - if (!psList){ - return NULL; // OOR + while (iIndex--) { + psList = strchr(psList, '\n'); + if (!psList) { + return NULL; // OOR } psList++; } - Q_strncpyz(sTemp,psList, sizeof(sTemp)); - p = strchr(sTemp,'\n'); + Q_strncpyz(sTemp, psList, sizeof(sTemp)); + p = strchr(sTemp, '\n'); if (p) { *p = '\0'; } @@ -563,26 +475,25 @@ static const char *GetCRDelineatedString( const char *psStripFileRef, const char return sTemp; } -static const char *GetMonthAbbrevString( int iMonth ) -{ - const char *p = GetCRDelineatedString("MP_INGAME","MONTHS", iMonth); +static const char *GetMonthAbbrevString(int iMonth) { + const char *p = GetCRDelineatedString("MP_INGAME", "MONTHS", iMonth); - return p ? p : "Jan"; // sanity + return p ? p : "Jan"; // sanity } -#define UIAS_LOCAL 0 -#define UIAS_GLOBAL1 1 -#define UIAS_GLOBAL2 2 -#define UIAS_GLOBAL3 3 -#define UIAS_GLOBAL4 4 -#define UIAS_GLOBAL5 5 -#define UIAS_FAVORITES 6 +#define UIAS_LOCAL 0 +#define UIAS_GLOBAL1 1 +#define UIAS_GLOBAL2 2 +#define UIAS_GLOBAL3 3 +#define UIAS_GLOBAL4 4 +#define UIAS_GLOBAL5 5 +#define UIAS_FAVORITES 6 -#define UI_MAX_MASTER_SERVERS 5 +#define UI_MAX_MASTER_SERVERS 5 // Convert ui's net source to AS_* used by trap calls. -int UI_SourceForLAN( void ) { - switch ( ui_netSource.integer ) { +int UI_SourceForLAN(void) { + switch (ui_netSource.integer) { default: case UIAS_LOCAL: return AS_LOCAL; @@ -606,15 +517,14 @@ static const char *netSources[] = { }; static const int numNetSources = ARRAY_LEN(netSources); */ -static const int numNetSources = 7; // now hard-entered in StringEd file -static const char *GetNetSourceString(int iSource) -{ +static const int numNetSources = 7; // now hard-entered in StringEd file +static const char *GetNetSourceString(int iSource) { static char result[256] = {0}; - Q_strncpyz( result, GetCRDelineatedString( "MP_INGAME", "NET_SOURCES", UI_SourceForLAN() ), sizeof(result) ); + Q_strncpyz(result, GetCRDelineatedString("MP_INGAME", "NET_SOURCES", UI_SourceForLAN()), sizeof(result)); - if ( iSource >= UIAS_GLOBAL1 && iSource <= UIAS_GLOBAL5 ) { - Q_strcat( result, sizeof(result), va( " %d", iSource ) ); + if (iSource >= UIAS_GLOBAL1 && iSource <= UIAS_GLOBAL5) { + Q_strcat(result, sizeof(result), va(" %d", iSource)); } return result; @@ -622,49 +532,49 @@ static const char *GetNetSourceString(int iSource) void AssetCache(void) { int n; - //if (Assets.textFont == NULL) { - //} - //Com_Printf("Menu Size: %i bytes\n", sizeof(Menus)); - uiInfo.uiDC.Assets.gradientBar = trap->R_RegisterShaderNoMip( ASSET_GRADIENTBAR ); - uiInfo.uiDC.Assets.fxBasePic = trap->R_RegisterShaderNoMip( ART_FX_BASE ); - uiInfo.uiDC.Assets.fxPic[0] = trap->R_RegisterShaderNoMip( ART_FX_RED ); - uiInfo.uiDC.Assets.fxPic[1] = trap->R_RegisterShaderNoMip( ART_FX_ORANGE );//trap->R_RegisterShaderNoMip( ART_FX_YELLOW ); - uiInfo.uiDC.Assets.fxPic[2] = trap->R_RegisterShaderNoMip( ART_FX_YELLOW );//trap->R_RegisterShaderNoMip( ART_FX_GREEN ); - uiInfo.uiDC.Assets.fxPic[3] = trap->R_RegisterShaderNoMip( ART_FX_GREEN );//trap->R_RegisterShaderNoMip( ART_FX_TEAL ); - uiInfo.uiDC.Assets.fxPic[4] = trap->R_RegisterShaderNoMip( ART_FX_BLUE ); - uiInfo.uiDC.Assets.fxPic[5] = trap->R_RegisterShaderNoMip( ART_FX_PURPLE );//trap->R_RegisterShaderNoMip( ART_FX_CYAN ); - uiInfo.uiDC.Assets.fxPic[6] = trap->R_RegisterShaderNoMip( ART_FX_WHITE ); - uiInfo.uiDC.Assets.scrollBar = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR ); - uiInfo.uiDC.Assets.scrollBarArrowDown = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWDOWN ); - uiInfo.uiDC.Assets.scrollBarArrowUp = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWUP ); - uiInfo.uiDC.Assets.scrollBarArrowLeft = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWLEFT ); - uiInfo.uiDC.Assets.scrollBarArrowRight = trap->R_RegisterShaderNoMip( ASSET_SCROLLBAR_ARROWRIGHT ); - uiInfo.uiDC.Assets.scrollBarThumb = trap->R_RegisterShaderNoMip( ASSET_SCROLL_THUMB ); - uiInfo.uiDC.Assets.sliderBar = trap->R_RegisterShaderNoMip( ASSET_SLIDER_BAR ); - uiInfo.uiDC.Assets.sliderThumb = trap->R_RegisterShaderNoMip( ASSET_SLIDER_THUMB ); + // if (Assets.textFont == NULL) { + // } + // Com_Printf("Menu Size: %i bytes\n", sizeof(Menus)); + uiInfo.uiDC.Assets.gradientBar = trap->R_RegisterShaderNoMip(ASSET_GRADIENTBAR); + uiInfo.uiDC.Assets.fxBasePic = trap->R_RegisterShaderNoMip(ART_FX_BASE); + uiInfo.uiDC.Assets.fxPic[0] = trap->R_RegisterShaderNoMip(ART_FX_RED); + uiInfo.uiDC.Assets.fxPic[1] = trap->R_RegisterShaderNoMip(ART_FX_ORANGE); // trap->R_RegisterShaderNoMip( ART_FX_YELLOW ); + uiInfo.uiDC.Assets.fxPic[2] = trap->R_RegisterShaderNoMip(ART_FX_YELLOW); // trap->R_RegisterShaderNoMip( ART_FX_GREEN ); + uiInfo.uiDC.Assets.fxPic[3] = trap->R_RegisterShaderNoMip(ART_FX_GREEN); // trap->R_RegisterShaderNoMip( ART_FX_TEAL ); + uiInfo.uiDC.Assets.fxPic[4] = trap->R_RegisterShaderNoMip(ART_FX_BLUE); + uiInfo.uiDC.Assets.fxPic[5] = trap->R_RegisterShaderNoMip(ART_FX_PURPLE); // trap->R_RegisterShaderNoMip( ART_FX_CYAN ); + uiInfo.uiDC.Assets.fxPic[6] = trap->R_RegisterShaderNoMip(ART_FX_WHITE); + uiInfo.uiDC.Assets.scrollBar = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR); + uiInfo.uiDC.Assets.scrollBarArrowDown = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWDOWN); + uiInfo.uiDC.Assets.scrollBarArrowUp = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWUP); + uiInfo.uiDC.Assets.scrollBarArrowLeft = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWLEFT); + uiInfo.uiDC.Assets.scrollBarArrowRight = trap->R_RegisterShaderNoMip(ASSET_SCROLLBAR_ARROWRIGHT); + uiInfo.uiDC.Assets.scrollBarThumb = trap->R_RegisterShaderNoMip(ASSET_SCROLL_THUMB); + uiInfo.uiDC.Assets.sliderBar = trap->R_RegisterShaderNoMip(ASSET_SLIDER_BAR); + uiInfo.uiDC.Assets.sliderThumb = trap->R_RegisterShaderNoMip(ASSET_SLIDER_THUMB); // Icons for various server settings. - uiInfo.uiDC.Assets.needPass = trap->R_RegisterShaderNoMip( "gfx/menus/needpass" ); - uiInfo.uiDC.Assets.noForce = trap->R_RegisterShaderNoMip( "gfx/menus/noforce" ); - uiInfo.uiDC.Assets.forceRestrict = trap->R_RegisterShaderNoMip( "gfx/menus/forcerestrict" ); - uiInfo.uiDC.Assets.saberOnly = trap->R_RegisterShaderNoMip( "gfx/menus/saberonly" ); - uiInfo.uiDC.Assets.trueJedi = trap->R_RegisterShaderNoMip( "gfx/menus/truejedi" ); + uiInfo.uiDC.Assets.needPass = trap->R_RegisterShaderNoMip("gfx/menus/needpass"); + uiInfo.uiDC.Assets.noForce = trap->R_RegisterShaderNoMip("gfx/menus/noforce"); + uiInfo.uiDC.Assets.forceRestrict = trap->R_RegisterShaderNoMip("gfx/menus/forcerestrict"); + uiInfo.uiDC.Assets.saberOnly = trap->R_RegisterShaderNoMip("gfx/menus/saberonly"); + uiInfo.uiDC.Assets.trueJedi = trap->R_RegisterShaderNoMip("gfx/menus/truejedi"); - for( n = 0; n < NUM_CROSSHAIRS; n++ ) { - uiInfo.uiDC.Assets.crosshairShader[n] = trap->R_RegisterShaderNoMip( va("gfx/2d/crosshair%c", 'a' + n ) ); + for (n = 0; n < NUM_CROSSHAIRS; n++) { + uiInfo.uiDC.Assets.crosshairShader[n] = trap->R_RegisterShaderNoMip(va("gfx/2d/crosshair%c", 'a' + n)); } } void _UI_DrawSides(float x, float y, float w, float h, float size) { size *= uiInfo.uiDC.xscale; - trap->R_DrawStretchPic( x, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap->R_DrawStretchPic( x + w - size, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap->R_DrawStretchPic(x, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap->R_DrawStretchPic(x + w - size, y, size, h, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } void _UI_DrawTopBottom(float x, float y, float w, float h, float size) { size *= uiInfo.uiDC.yscale; - trap->R_DrawStretchPic( x, y, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); - trap->R_DrawStretchPic( x, y + h - size, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader ); + trap->R_DrawStretchPic(x, y, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); + trap->R_DrawStretchPic(x, y + h - size, w, size, 0, 0, 0, 0, uiInfo.uiDC.whiteShader); } /* ================ @@ -673,150 +583,150 @@ UI_DrawRect Coordinates are 640*480 virtual values ================= */ -void _UI_DrawRect( float x, float y, float width, float height, float size, const float *color ) { - trap->R_SetColor( color ); +void _UI_DrawRect(float x, float y, float width, float height, float size, const float *color) { + trap->R_SetColor(color); _UI_DrawTopBottom(x, y, width, height, size); _UI_DrawSides(x, y, width, height, size); - trap->R_SetColor( NULL ); + trap->R_SetColor(NULL); } -int MenuFontToHandle(int iMenuFont) -{ - switch (iMenuFont) - { - case 1: return uiInfo.uiDC.Assets.qhSmallFont; - case 2: return uiInfo.uiDC.Assets.qhMediumFont; - case 3: return uiInfo.uiDC.Assets.qhBigFont; - case 4: return uiInfo.uiDC.Assets.qhSmall2Font; +int MenuFontToHandle(int iMenuFont) { + switch (iMenuFont) { + case 1: + return uiInfo.uiDC.Assets.qhSmallFont; + case 2: + return uiInfo.uiDC.Assets.qhMediumFont; + case 3: + return uiInfo.uiDC.Assets.qhBigFont; + case 4: + return uiInfo.uiDC.Assets.qhSmall2Font; } - return uiInfo.uiDC.Assets.qhMediumFont; // 0; + return uiInfo.uiDC.Assets.qhMediumFont; // 0; } -int Text_Width(const char *text, float scale, int iMenuFont) -{ +int Text_Width(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap->R_Font_StrLenPixels(text, iFontIndex, scale); } -int Text_Height(const char *text, float scale, int iMenuFont) -{ +int Text_Height(const char *text, float scale, int iMenuFont) { int iFontIndex = MenuFontToHandle(iMenuFont); return trap->R_Font_HeightPixels(iFontIndex, scale); } -void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont) -{ +void Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont) { int iStyleOR = 0; int iFontIndex = MenuFontToHandle(iMenuFont); // // kludge.. convert JK2 menu styles to SOF2 printstring ctrl codes... // - switch (style) - { - case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text - case ITEM_TEXTSTYLE_BLINK: iStyleOR = (int)STYLE_BLINK;break; // JK2 fast blinking - case ITEM_TEXTSTYLE_PULSE: iStyleOR = (int)STYLE_BLINK;break; // JK2 slow pulsing - case ITEM_TEXTSTYLE_SHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow - case ITEM_TEXTSTYLE_OUTLINED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow - case ITEM_TEXTSTYLE_OUTLINESHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow - case ITEM_TEXTSTYLE_SHADOWEDMORE: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow - } - - trap->R_Font_DrawString( x, // int ox - y, // int oy - text, // const char *text - color, // paletteRGBA_c c - iStyleOR | iFontIndex, // const int iFontHandle - !limit?-1:limit, // iCharLimit (-1 = none) - scale // const float scale = 1.0f - ); -} - - -void Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int limit, int style, int iMenuFont) -{ + switch (style) { + case ITEM_TEXTSTYLE_NORMAL: + iStyleOR = 0; + break; // JK2 normal text + case ITEM_TEXTSTYLE_BLINK: + iStyleOR = (int)STYLE_BLINK; + break; // JK2 fast blinking + case ITEM_TEXTSTYLE_PULSE: + iStyleOR = (int)STYLE_BLINK; + break; // JK2 slow pulsing + case ITEM_TEXTSTYLE_SHADOWED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow + case ITEM_TEXTSTYLE_OUTLINED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow + case ITEM_TEXTSTYLE_OUTLINESHADOWED: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow + case ITEM_TEXTSTYLE_SHADOWEDMORE: + iStyleOR = (int)STYLE_DROPSHADOW; + break; // JK2 drop shadow + } + + trap->R_Font_DrawString(x, // int ox + y, // int oy + text, // const char *text + color, // paletteRGBA_c c + iStyleOR | iFontIndex, // const int iFontHandle + !limit ? -1 : limit, // iCharLimit (-1 = none) + scale // const float scale = 1.0f + ); +} + +void Text_PaintWithCursor(float x, float y, float scale, vec4_t color, const char *text, int cursorPos, char cursor, int limit, int style, int iMenuFont) { Text_Paint(x, y, scale, color, text, 0, limit, style, iMenuFont); // now print the cursor as well... (excuse the braces, it's for porting C++ to C) // { char sTemp[1024]; - int iCopyCount = limit > 0 ? Q_min( (int)strlen( text ), limit ) : (int)strlen( text ); - iCopyCount = Q_min( iCopyCount, cursorPos ); - iCopyCount = Q_min( iCopyCount, (int)sizeof( sTemp )-1 ); + int iCopyCount = limit > 0 ? Q_min((int)strlen(text), limit) : (int)strlen(text); + iCopyCount = Q_min(iCopyCount, cursorPos); + iCopyCount = Q_min(iCopyCount, (int)sizeof(sTemp) - 1); - // copy text into temp buffer for pixel measure... - // - strncpy(sTemp,text,iCopyCount); - sTemp[iCopyCount] = '\0'; + // copy text into temp buffer for pixel measure... + // + strncpy(sTemp, text, iCopyCount); + sTemp[iCopyCount] = '\0'; - { - int iFontIndex = MenuFontToHandle( iMenuFont ); - int iNextXpos = trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale ); + { + int iFontIndex = MenuFontToHandle(iMenuFont); + int iNextXpos = trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale); - Text_Paint(x+iNextXpos, y, scale, color, va("%c",cursor), 0, limit, style|ITEM_TEXTSTYLE_BLINK, iMenuFont); - } + Text_Paint(x + iNextXpos, y, scale, color, va("%c", cursor), 0, limit, style | ITEM_TEXTSTYLE_BLINK, iMenuFont); + } } } - // maxX param is initially an X limit, but is also used as feedback. 0 = text was clipped to fit within, else maxX = next pos // -static void Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char* text, float adjust, int limit, int iMenuFont) -{ +static void Text_Paint_Limit(float *maxX, float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int iMenuFont) { // this is kinda dirty, but... // int iFontIndex = MenuFontToHandle(iMenuFont); - //float fMax = *maxX; + // float fMax = *maxX; int iPixelLen = trap->R_Font_StrLenPixels(text, iFontIndex, scale); - if (x + iPixelLen > *maxX) - { + if (x + iPixelLen > *maxX) { // whole text won't fit, so we need to print just the amount that does... // Ok, this is slow and tacky, but only called occasionally, and it works... // - char sTemp[4096]={0}; // lazy assumption + char sTemp[4096] = {0}; // lazy assumption const char *psText = text; char *psOut = &sTemp[0]; char *psOutLastGood = psOut; unsigned int uiLetter; - while (*psText && (x + trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale)<=*maxX) - && psOut < &sTemp[sizeof(sTemp)-1] // sanity - ) - { + while (*psText && (x + trap->R_Font_StrLenPixels(sTemp, iFontIndex, scale) <= *maxX) && psOut < &sTemp[sizeof(sTemp) - 1] // sanity + ) { int iAdvanceCount; psOutLastGood = psOut; uiLetter = trap->R_AnyLanguage_ReadCharFromString(psText, &iAdvanceCount, NULL); psText += iAdvanceCount; - if (uiLetter > 255) - { - *psOut++ = uiLetter>>8; - *psOut++ = uiLetter&0xFF; - } - else - { - *psOut++ = uiLetter&0xFF; + if (uiLetter > 255) { + *psOut++ = uiLetter >> 8; + *psOut++ = uiLetter & 0xFF; + } else { + *psOut++ = uiLetter & 0xFF; } } *psOutLastGood = '\0'; - *maxX = 0; // feedback + *maxX = 0; // feedback Text_Paint(x, y, scale, color, sTemp, adjust, limit, ITEM_TEXTSTYLE_NORMAL, iMenuFont); - } - else - { + } else { // whole text fits fine, so print it all... // - *maxX = x + iPixelLen; // feedback the next position, as the caller expects + *maxX = x + iPixelLen; // feedback the next position, as the caller expects Text_Paint(x, y, scale, color, text, adjust, limit, ITEM_TEXTSTYLE_NORMAL, iMenuFont); } } @@ -836,32 +746,32 @@ UI_BuildPlayerList =============== */ static void UI_BuildPlayerList() { - uiClientState_t cs; - int n, count, team, team2, playerTeamNumber; - char info[MAX_INFO_STRING]; + uiClientState_t cs; + int n, count, team, team2, playerTeamNumber; + char info[MAX_INFO_STRING]; - trap->GetClientState( &cs ); - trap->GetConfigString( CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING ); + trap->GetClientState(&cs); + trap->GetConfigString(CS_PLAYERS + cs.clientNum, info, MAX_INFO_STRING); uiInfo.playerNumber = cs.clientNum; uiInfo.teamLeader = atoi(Info_ValueForKey(info, "tl")); team = atoi(Info_ValueForKey(info, "t")); - trap->GetConfigString( CS_SERVERINFO, info, sizeof(info) ); - count = atoi( Info_ValueForKey( info, "sv_maxclients" ) ); + trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); + count = atoi(Info_ValueForKey(info, "sv_maxclients")); uiInfo.playerCount = 0; uiInfo.myTeamCount = 0; playerTeamNumber = 0; - for( n = 0; n < count; n++ ) { - trap->GetConfigString( CS_PLAYERS + n, info, MAX_INFO_STRING ); + for (n = 0; n < count; n++) { + trap->GetConfigString(CS_PLAYERS + n, info, MAX_INFO_STRING); if (info[0]) { - Q_strncpyz( uiInfo.playerNames[uiInfo.playerCount], Info_ValueForKey( info, "n" ), MAX_NETNAME ); - Q_StripColor( uiInfo.playerNames[uiInfo.playerCount] ); + Q_strncpyz(uiInfo.playerNames[uiInfo.playerCount], Info_ValueForKey(info, "n"), MAX_NETNAME); + Q_StripColor(uiInfo.playerNames[uiInfo.playerCount]); uiInfo.playerIndexes[uiInfo.playerCount] = n; uiInfo.playerCount++; team2 = atoi(Info_ValueForKey(info, "t")); if (team2 == team && n != uiInfo.playerNumber) { - Q_strncpyz( uiInfo.teamNames[uiInfo.myTeamCount], Info_ValueForKey( info, "n" ), MAX_NETNAME ); - Q_StripColor( uiInfo.teamNames[uiInfo.myTeamCount] ); + Q_strncpyz(uiInfo.teamNames[uiInfo.myTeamCount], Info_ValueForKey(info, "n"), MAX_NETNAME); + Q_StripColor(uiInfo.teamNames[uiInfo.myTeamCount]); uiInfo.teamClientNums[uiInfo.myTeamCount] = n; if (uiInfo.playerNumber == n) { playerTeamNumber = uiInfo.myTeamCount; @@ -880,24 +790,20 @@ static void UI_BuildPlayerList() { n = 0; } - if (n < uiInfo.myTeamCount) { trap->Cvar_Set("cg_selectedPlayerName", uiInfo.teamNames[n]); - } - else - { + } else { trap->Cvar_Set("cg_selectedPlayerName", "Everyone"); } - if (!team || team == TEAM_SPECTATOR || !uiInfo.teamLeader) - { + if (!team || team == TEAM_SPECTATOR || !uiInfo.teamLeader) { n = uiInfo.myTeamCount; trap->Cvar_Set("cg_selectedPlayer", va("%d", n)); trap->Cvar_Set("cg_selectedPlayerName", "N/A"); } } -void UI_SetActiveMenu( uiMenuCommand_t menu ) { +void UI_SetActiveMenu(uiMenuCommand_t menu) { char buf[256]; // this should be the ONLY way the menu system is brought up @@ -905,63 +811,58 @@ void UI_SetActiveMenu( uiMenuCommand_t menu ) { if (Menu_Count() > 0) { vec3_t v; v[0] = v[1] = v[2] = 0; - switch ( menu ) { + switch (menu) { case UIMENU_NONE: - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); Menus_CloseAll(); return; - case UIMENU_MAIN: - { - // trap->Cvar_Set( "sv_killserver", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); - // trap->S_StartLocalSound( trap_S_RegisterSound("sound/misc/menu_background.wav", qfalse) , CHAN_LOCAL_SOUND ); - // trap->S_StartBackgroundTrack("sound/misc/menu_background.wav", NULL); - if (uiInfo.inGameLoad) - UI_LoadNonIngame(); + case UIMENU_MAIN: { + // trap->Cvar_Set( "sv_killserver", "1" ); + trap->Key_SetCatcher(KEYCATCH_UI); + // trap->S_StartLocalSound( trap_S_RegisterSound("sound/misc/menu_background.wav", qfalse) , CHAN_LOCAL_SOUND ); + // trap->S_StartBackgroundTrack("sound/misc/menu_background.wav", NULL); + if (uiInfo.inGameLoad) + UI_LoadNonIngame(); - Menus_CloseAll(); - Menus_ActivateByName("main"); - trap->Cvar_VariableStringBuffer("com_errorMessage", buf, sizeof(buf)); + Menus_CloseAll(); + Menus_ActivateByName("main"); + trap->Cvar_VariableStringBuffer("com_errorMessage", buf, sizeof(buf)); - if (buf[0]) - { - if (!ui_singlePlayerActive.integer) - { - Menus_ActivateByName("error_popmenu"); - } - else - { - trap->Cvar_Set("com_errorMessage", ""); - } + if (buf[0]) { + if (!ui_singlePlayerActive.integer) { + Menus_ActivateByName("error_popmenu"); + } else { + trap->Cvar_Set("com_errorMessage", ""); } - return; } + return; + } case UIMENU_TEAM: - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_ActivateByName("team"); return; case UIMENU_POSTGAME: - //trap->Cvar_Set( "sv_killserver", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + // trap->Cvar_Set( "sv_killserver", "1" ); + trap->Key_SetCatcher(KEYCATCH_UI); if (uiInfo.inGameLoad) UI_LoadNonIngame(); Menus_CloseAll(); Menus_ActivateByName("endofgame"); return; case UIMENU_INGAME: - trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Cvar_Set("cl_paused", "1"); + trap->Key_SetCatcher(KEYCATCH_UI); UI_BuildPlayerList(); Menus_CloseAll(); Menus_ActivateByName("ingame"); return; case UIMENU_PLAYERCONFIG: // trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); UI_BuildPlayerList(); Menus_CloseAll(); Menus_ActivateByName("ingame_player"); @@ -969,7 +870,7 @@ void UI_SetActiveMenu( uiMenuCommand_t menu ) { return; case UIMENU_PLAYERFORCE: // trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); UI_BuildPlayerList(); Menus_CloseAll(); Menus_ActivateByName("ingame_playerforce"); @@ -977,13 +878,13 @@ void UI_SetActiveMenu( uiMenuCommand_t menu ) { return; case UIMENU_SIEGEMESSAGE: // trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("siege_popmenu"); return; case UIMENU_SIEGEOBJECTIVES: // trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("ingame_siegeobjectives"); return; @@ -991,12 +892,11 @@ void UI_SetActiveMenu( uiMenuCommand_t menu ) { // trap->Cvar_Set( "cl_paused", "1" ); // No chatin non-siege games. - if (trap->Cvar_VariableValue( "g_gametype" ) < GT_TEAM) - { + if (trap->Cvar_VariableValue("g_gametype") < GT_TEAM) { return; } - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("ingame_voicechat"); return; @@ -1004,7 +904,7 @@ void UI_SetActiveMenu( uiMenuCommand_t menu ) { Menus_CloseAll(); return; case UIMENU_CLASSSEL: - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("ingame_siegeclass"); return; @@ -1029,17 +929,14 @@ extern int FPMessageTime; void Text_PaintCenter(float x, float y, float scale, vec4_t color, const char *text, float adjust, int iMenuFont); -const char *UI_GetStringEdString(const char *refSection, const char *refName) -{ - static char text[1024]={0}; +const char *UI_GetStringEdString(const char *refSection, const char *refName) { + static char text[1024] = {0}; trap->SE_GetStringTextString(va("%s_%s", refSection, refName), text, sizeof(text)); return text; } -void UI_SetColor( const float *rgba ) { - trap->R_SetColor( rgba ); -} +void UI_SetColor(const float *rgba) { trap->R_SetColor(rgba); } /* ================= @@ -1049,7 +946,7 @@ _UI_Shutdown void UI_CleanupGhoul2(void); void UI_FreeAllSpecies(void); -void UI_Shutdown( void ) { +void UI_Shutdown(void) { trap->LAN_SaveCachedServers(); UI_CleanupGhoul2(); UI_FreeAllSpecies(); @@ -1058,25 +955,25 @@ void UI_Shutdown( void ) { char *defaultMenu = NULL; char *GetMenuBuffer(const char *filename) { - int len; - fileHandle_t f; + int len; + fileHandle_t f; static char buf[MAX_MENUFILE]; - len = trap->FS_Open( filename, &f, FS_READ ); - if ( !f ) { - trap->Print( S_COLOR_RED "menu file not found: %s, using default\n", filename ); + len = trap->FS_Open(filename, &f, FS_READ); + if (!f) { + trap->Print(S_COLOR_RED "menu file not found: %s, using default\n", filename); return defaultMenu; } - if ( len >= MAX_MENUFILE ) { - trap->Print( S_COLOR_RED "menu file too large: %s is %i, max allowed is %i\n", filename, len, MAX_MENUFILE ); - trap->FS_Close( f ); + if (len >= MAX_MENUFILE) { + trap->Print(S_COLOR_RED "menu file too large: %s is %i, max allowed is %i\n", filename, len, MAX_MENUFILE); + trap->FS_Close(f); return defaultMenu; } - trap->FS_Read( buf, len, f ); + trap->FS_Read(buf, len, f); buf[len] = 0; - trap->FS_Close( f ); - //COM_Compress(buf); + trap->FS_Close(f); + // COM_Compress(buf); return buf; } @@ -1089,7 +986,7 @@ qboolean Asset_Parse(int handle) { return qfalse; } - while ( 1 ) { + while (1) { memset(&token, 0, sizeof(pc_token_t)); if (!trap->PC_ReadToken(handle, &token)) @@ -1102,10 +999,10 @@ qboolean Asset_Parse(int handle) { // font if (Q_stricmp(token.string, "font") == 0) { int pointSize; - if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle,&pointSize)) { + if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } - //trap->R_RegisterFont(tempStr, pointSize, &uiInfo.uiDC.Assets.textFont); + // trap->R_RegisterFont(tempStr, pointSize, &uiInfo.uiDC.Assets.textFont); uiInfo.uiDC.Assets.qhMediumFont = trap->R_RegisterFont(token.string); uiInfo.uiDC.Assets.fontRegistered = qtrue; continue; @@ -1113,42 +1010,40 @@ qboolean Asset_Parse(int handle) { if (Q_stricmp(token.string, "smallFont") == 0) { int pointSize; - if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle,&pointSize)) { + if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } - //trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.smallFont); + // trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.smallFont); uiInfo.uiDC.Assets.qhSmallFont = trap->R_RegisterFont(token.string); continue; } if (Q_stricmp(token.string, "small2Font") == 0) { int pointSize; - if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle,&pointSize)) { + if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } - //trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.smallFont); + // trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.smallFont); uiInfo.uiDC.Assets.qhSmall2Font = trap->R_RegisterFont(token.string); continue; } if (Q_stricmp(token.string, "bigFont") == 0) { int pointSize; - if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle,&pointSize)) { + if (!trap->PC_ReadToken(handle, &token) || !PC_Int_Parse(handle, &pointSize)) { return qfalse; } - //trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.bigFont); + // trap->R_RegisterFont(token, pointSize, &uiInfo.uiDC.Assets.bigFont); uiInfo.uiDC.Assets.qhBigFont = trap->R_RegisterFont(token.string); continue; } - if (Q_stricmp(token.string, "cursor") == 0) - { - if (!PC_String_Parse(handle, &uiInfo.uiDC.Assets.cursorStr)) - { - Com_Printf(S_COLOR_YELLOW,"Bad 1st parameter for keyword 'cursor'"); + if (Q_stricmp(token.string, "cursor") == 0) { + if (!PC_String_Parse(handle, &uiInfo.uiDC.Assets.cursorStr)) { + Com_Printf(S_COLOR_YELLOW, "Bad 1st parameter for keyword 'cursor'"); return qfalse; } - uiInfo.uiDC.Assets.cursor = trap->R_RegisterShaderNoMip( uiInfo.uiDC.Assets.cursorStr); + uiInfo.uiDC.Assets.cursor = trap->R_RegisterShaderNoMip(uiInfo.uiDC.Assets.cursorStr); continue; } @@ -1166,7 +1061,7 @@ qboolean Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - uiInfo.uiDC.Assets.menuEnterSound = trap->S_RegisterSound( token.string ); + uiInfo.uiDC.Assets.menuEnterSound = trap->S_RegisterSound(token.string); continue; } @@ -1175,7 +1070,7 @@ qboolean Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - uiInfo.uiDC.Assets.menuExitSound = trap->S_RegisterSound( token.string ); + uiInfo.uiDC.Assets.menuExitSound = trap->S_RegisterSound(token.string); continue; } @@ -1184,7 +1079,7 @@ qboolean Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - uiInfo.uiDC.Assets.itemFocusSound = trap->S_RegisterSound( token.string ); + uiInfo.uiDC.Assets.itemFocusSound = trap->S_RegisterSound(token.string); continue; } @@ -1193,7 +1088,7 @@ qboolean Asset_Parse(int handle) { if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - uiInfo.uiDC.Assets.menuBuzzSound = trap->S_RegisterSound( token.string ); + uiInfo.uiDC.Assets.menuBuzzSound = trap->S_RegisterSound(token.string); continue; } @@ -1240,96 +1135,77 @@ qboolean Asset_Parse(int handle) { continue; } - if (Q_stricmp(token.string, "moveRollSound") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.moveRollSound = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "moveRollSound") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.moveRollSound = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "moveJumpSound") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.moveJumpSound = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "moveJumpSound") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.moveJumpSound = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound1") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound1 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound1") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound1 = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound2") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound2 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound2") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound2 = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound3") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound3 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound3") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound3 = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound4") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound4 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound4") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound4 = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound5") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound5 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound5") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound5 = trap->S_RegisterSound(token.string); } continue; } - if (Q_stricmp(token.string, "datapadmoveSaberSound6") == 0) - { - if (trap->PC_ReadToken(handle,&token)) - { - uiInfo.uiDC.Assets.datapadmoveSaberSound6 = trap->S_RegisterSound( token.string ); + if (Q_stricmp(token.string, "datapadmoveSaberSound6") == 0) { + if (trap->PC_ReadToken(handle, &token)) { + uiInfo.uiDC.Assets.datapadmoveSaberSound6 = trap->S_RegisterSound(token.string); } continue; } // precaching various sound files used in the menus - if (Q_stricmp(token.string, "precacheSound") == 0) - { + if (Q_stricmp(token.string, "precacheSound") == 0) { const char *tempStr; - if (PC_Script_Parse(handle, &tempStr)) - { + if (PC_Script_Parse(handle, &tempStr)) { char *soundFile; - do - { + do { soundFile = COM_ParseExt(&tempStr, qfalse); if (soundFile[0] != 0 && soundFile[0] != ';') { - trap->S_RegisterSound( soundFile); + trap->S_RegisterSound(soundFile); } } while (soundFile[0]); } @@ -1339,39 +1215,39 @@ qboolean Asset_Parse(int handle) { return qfalse; } -void UI_Report( void ) { +void UI_Report(void) { String_Report(); - //Font_Report(); + // Font_Report(); } void UI_ParseMenu(const char *menuFile) { int handle; pc_token_t token; - //Com_Printf("Parsing menu file: %s\n", menuFile); + // Com_Printf("Parsing menu file: %s\n", menuFile); handle = trap->PC_LoadSource(menuFile); if (!handle) { return; } - while ( 1 ) { + while (1) { memset(&token, 0, sizeof(pc_token_t)); - if (!trap->PC_ReadToken( handle, &token )) { + if (!trap->PC_ReadToken(handle, &token)) { break; } - //if ( Q_stricmp( token, "{" ) ) { + // if ( Q_stricmp( token, "{" ) ) { // Com_Printf( "Missing { in menu file\n" ); // break; - //} + // } - //if ( menuCount == MAX_MENUS ) { + // if ( menuCount == MAX_MENUS ) { // Com_Printf( "Too many menus!\n" ); // break; - //} + // } - if ( token.string[0] == '}' ) { + if (token.string[0] == '}') { break; } @@ -1400,16 +1276,16 @@ qboolean Load_Menu(int handle) { return qfalse; } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) return qfalse; - if ( token.string[0] == 0 ) { + if (token.string[0] == 0) { return qfalse; } - if ( token.string[0] == '}' ) { + if (token.string[0] == '}') { return qtrue; } @@ -1421,16 +1297,16 @@ qboolean Load_Menu(int handle) { void UI_LoadMenus(const char *menuFile, qboolean reset) { pc_token_t token; int handle; -// int start = trap->Milliseconds(); + // int start = trap->Milliseconds(); - trap->PC_LoadGlobalDefines ( "ui/jamp/menudef.h" ); + trap->PC_LoadGlobalDefines("ui/jamp/menudef.h"); - handle = trap->PC_LoadSource( menuFile ); + handle = trap->PC_LoadSource(menuFile); if (!handle) { - Com_Printf( S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile ); - handle = trap->PC_LoadSource( "ui/jampmenus.txt" ); + Com_Printf(S_COLOR_YELLOW "menu file not found: %s, using default\n", menuFile); + handle = trap->PC_LoadSource("ui/jampmenus.txt"); if (!handle) { - trap->Error( ERR_DROP, S_COLOR_RED "default menu file not found: ui/jampmenus.txt, unable to continue!\n" ); + trap->Error(ERR_DROP, S_COLOR_RED "default menu file not found: ui/jampmenus.txt, unable to continue!\n"); } } @@ -1438,14 +1314,14 @@ void UI_LoadMenus(const char *menuFile, qboolean reset) { Menu_Reset(); } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) break; - if( token.string[0] == 0 || token.string[0] == '}') { + if (token.string[0] == 0 || token.string[0] == '}') { break; } - if ( token.string[0] == '}' ) { + if (token.string[0] == '}') { break; } @@ -1458,32 +1334,27 @@ void UI_LoadMenus(const char *menuFile, qboolean reset) { } } -// Com_Printf("UI menu load time = %d milli seconds\n", trap->Milliseconds() - start); + // Com_Printf("UI menu load time = %d milli seconds\n", trap->Milliseconds() - start); - trap->PC_FreeSource( handle ); + trap->PC_FreeSource(handle); - trap->PC_RemoveAllGlobalDefines ( ); + trap->PC_RemoveAllGlobalDefines(); } -void UI_Load( void ) { +void UI_Load(void) { char *menuSet; char lastName[1024]; menuDef_t *menu = Menu_GetFocused(); if (menu && menu->window.name) { Q_strncpyz(lastName, menu->window.name, sizeof(lastName)); - } - else - { + } else { lastName[0] = 0; } - if (uiInfo.inGameLoad) - { + if (uiInfo.inGameLoad) { menuSet = "ui/jampingame.txt"; - } - else - { + } else { menuSet = UI_Cvar_VariableString("ui_menuFilesMP"); } if (menuSet == NULL || menuSet[0] == '\0') { @@ -1505,25 +1376,26 @@ void UI_Load( void ) { Menus_ActivateByName(lastName); } -char sAll[15] = {0}; -char sJediAcademy[30] = {0}; -const char *UI_FilterDescription( int value ) { - if ( value <= 0 || value > uiInfo.modCount ) { +char sAll[15] = {0}; +char sJediAcademy[30] = {0}; +const char *UI_FilterDescription(int value) { + if (value <= 0 || value > uiInfo.modCount) { return sAll; } return uiInfo.modList[value - 1].modDescr; } -const char *UI_FilterDir( int value ) { - if ( value <= 0 || value > uiInfo.modCount ) { +const char *UI_FilterDir(int value) { + if (value <= 0 || value > uiInfo.modCount) { return ""; } return uiInfo.modList[value - 1].modName; } -static const char *handicapValues[] = {"None","95","90","85","80","75","70","65","60","55","50","45","40","35","30","25","20","15","10","5",NULL}; +static const char *handicapValues[] = {"None", "95", "90", "85", "80", "75", "70", "65", "60", "55", "50", + "45", "40", "35", "30", "25", "20", "15", "10", "5", NULL}; static void UI_DrawHandicap(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int i, h; @@ -1551,52 +1423,45 @@ static void UI_SetCapFragLimits(qboolean uiVars) { } } -static const char* UI_GetGameTypeName(int gtEnum) -{ - switch ( gtEnum ) - { +static const char *UI_GetGameTypeName(int gtEnum) { + switch (gtEnum) { case GT_FFA: - return UI_GetStringEdString("MENUS", "FREE_FOR_ALL");//"Free For All"; + return UI_GetStringEdString("MENUS", "FREE_FOR_ALL"); //"Free For All"; case GT_HOLOCRON: - return UI_GetStringEdString("MENUS", "HOLOCRON_FFA");//"Holocron FFA"; + return UI_GetStringEdString("MENUS", "HOLOCRON_FFA"); //"Holocron FFA"; case GT_JEDIMASTER: - return UI_GetStringEdString("MENUS", "SAGA");//"Jedi Master";?? + return UI_GetStringEdString("MENUS", "SAGA"); //"Jedi Master";?? case GT_SINGLE_PLAYER: - return UI_GetStringEdString("MENUS", "SAGA");//"Team FFA"; + return UI_GetStringEdString("MENUS", "SAGA"); //"Team FFA"; case GT_DUEL: - return UI_GetStringEdString("MENUS", "DUEL");//"Team FFA"; + return UI_GetStringEdString("MENUS", "DUEL"); //"Team FFA"; case GT_POWERDUEL: - return UI_GetStringEdString("MENUS", "POWERDUEL");//"Team FFA"; + return UI_GetStringEdString("MENUS", "POWERDUEL"); //"Team FFA"; case GT_TEAM: - return UI_GetStringEdString("MENUS", "TEAM_FFA");//"Team FFA"; + return UI_GetStringEdString("MENUS", "TEAM_FFA"); //"Team FFA"; case GT_SIEGE: - return UI_GetStringEdString("MENUS", "SIEGE");//"Siege"; + return UI_GetStringEdString("MENUS", "SIEGE"); //"Siege"; case GT_CTF: - return UI_GetStringEdString("MENUS", "CAPTURE_THE_FLAG");//"Capture the Flag"; + return UI_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"); //"Capture the Flag"; case GT_CTY: - return UI_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI");//"Capture the Ysalamiri"; + return UI_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"); //"Capture the Ysalamiri"; } - return UI_GetStringEdString("MENUS", "SAGA");//"Team FFA"; + return UI_GetStringEdString("MENUS", "SAGA"); //"Team FFA"; } - - // ui_gameType assumes gametype 0 is -1 ALL and will not show -static void UI_DrawGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ +static void UI_DrawGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { Text_Paint(rect->x, rect->y, scale, color, UI_GetGameTypeName(uiInfo.gameTypes[ui_gametype.integer].gtEnum), 0, 0, textStyle, iMenuFont); } -static void UI_DrawNetGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ - if (ui_netGametype.integer < 0 || ui_netGametype.integer >= uiInfo.numGameTypes) - { +static void UI_DrawNetGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { + if (ui_netGametype.integer < 0 || ui_netGametype.integer >= uiInfo.numGameTypes) { trap->Cvar_Set("ui_netGametype", "0"); trap->Cvar_Update(&ui_netGametype); trap->Cvar_Set("ui_actualNetGametype", "0"); trap->Cvar_Update(&ui_actualNetGametype); } - Text_Paint(rect->x, rect->y, scale, color, UI_GetGameTypeName(uiInfo.gameTypes[ui_netGametype.integer].gtEnum) , 0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, UI_GetGameTypeName(uiInfo.gameTypes[ui_netGametype.integer].gtEnum), 0, 0, textStyle, iMenuFont); } static void UI_DrawAutoSwitch(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { @@ -1604,8 +1469,7 @@ static void UI_DrawAutoSwitch(rectDef_t *rect, float scale, vec4_t color, int te const char *switchString = "AUTOSWITCH1"; const char *stripString = NULL; - switch(switchVal) - { + switch (switchVal) { case 2: switchString = "AUTOSWITCH2"; break; @@ -1621,21 +1485,18 @@ static void UI_DrawAutoSwitch(rectDef_t *rect, float scale, vec4_t color, int te stripString = UI_GetStringEdString("MP_INGAME", (char *)switchString); - if (stripString) - { + if (stripString) { Text_Paint(rect->x, rect->y, scale, color, stripString, 0, 0, textStyle, iMenuFont); } } -static void UI_DrawJoinGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ - if (ui_joinGametype.integer < 0 || ui_joinGametype.integer > uiInfo.numJoinGameTypes) - { +static void UI_DrawJoinGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { + if (ui_joinGametype.integer < 0 || ui_joinGametype.integer > uiInfo.numJoinGameTypes) { trap->Cvar_Set("ui_joinGametype", "0"); trap->Cvar_Update(&ui_joinGametype); } - Text_Paint(rect->x, rect->y, scale, color, UI_GetGameTypeName(uiInfo.joinGameTypes[ui_joinGametype.integer].gtEnum) , 0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, UI_GetGameTypeName(uiInfo.joinGameTypes[ui_joinGametype.integer].gtEnum), 0, 0, textStyle, iMenuFont); } static int UI_TeamIndexFromName(const char *name) { @@ -1656,15 +1517,15 @@ static void UI_DrawClanLogo(rectDef_t *rect, float scale, vec4_t color) { int i; i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); if (i >= 0 && i < uiInfo.teamCount) { - trap->R_SetColor( color ); + trap->R_SetColor(color); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); - uiInfo.teamList[i].teamIcon_Metal = trap->R_RegisterShaderNoMip(va("%s_metal",uiInfo.teamList[i].imageName)); + uiInfo.teamList[i].teamIcon_Metal = trap->R_RegisterShaderNoMip(va("%s_metal", uiInfo.teamList[i].imageName)); uiInfo.teamList[i].teamIcon_Name = trap->R_RegisterShaderNoMip(va("%s_name", uiInfo.teamList[i].imageName)); } - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon); trap->R_SetColor(NULL); } } @@ -1675,21 +1536,21 @@ static void UI_DrawClanCinematic(rectDef_t *rect, float scale, vec4_t color) { if (i >= 0 && i < uiInfo.teamCount) { if (uiInfo.teamList[i].cinematic >= -2) { if (uiInfo.teamList[i].cinematic == -1) { - uiInfo.teamList[i].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.teamList[i].imageName), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); + uiInfo.teamList[i].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.teamList[i].imageName), 0, 0, 0, 0, (CIN_loop | CIN_silent)); } if (uiInfo.teamList[i].cinematic >= 0) { trap->CIN_RunCinematic(uiInfo.teamList[i].cinematic); trap->CIN_SetExtents(uiInfo.teamList[i].cinematic, rect->x, rect->y, rect->w, rect->h); trap->CIN_DrawCinematic(uiInfo.teamList[i].cinematic); } else { - trap->R_SetColor( color ); - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Metal); + trap->R_SetColor(color); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon_Metal); trap->R_SetColor(NULL); uiInfo.teamList[i].cinematic = -2; } } else { - trap->R_SetColor( color ); - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon); + trap->R_SetColor(color); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.teamList[i].teamIcon); trap->R_SetColor(NULL); } } @@ -1697,7 +1558,7 @@ static void UI_DrawClanCinematic(rectDef_t *rect, float scale, vec4_t color) { static void UI_DrawPreviewCinematic(rectDef_t *rect, float scale, vec4_t color) { if (uiInfo.previewMovie > -2) { - uiInfo.previewMovie = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.movieList[uiInfo.movieIndex]), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); + uiInfo.previewMovie = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.movieList[uiInfo.movieIndex]), 0, 0, 0, 0, (CIN_loop | CIN_silent)); if (uiInfo.previewMovie >= 0) { trap->CIN_RunCinematic(uiInfo.previewMovie); trap->CIN_SetExtents(uiInfo.previewMovie, rect->x, rect->y, rect->w, rect->h); @@ -1710,40 +1571,35 @@ static void UI_DrawPreviewCinematic(rectDef_t *rect, float scale, vec4_t color) static void UI_DrawSkill(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int i; - i = trap->Cvar_VariableValue( "g_spSkill" ); + i = trap->Cvar_VariableValue("g_spSkill"); if (i < 1 || i > numSkillLevels) { i = 1; } - Text_Paint(rect->x, rect->y, scale, color, (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[i-1]),0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[i - 1]), 0, 0, textStyle, iMenuFont); } -static void UI_DrawGenericNum(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int type,int iMenuFont) -{ +static void UI_DrawGenericNum(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int type, int iMenuFont) { int i; char s[256]; i = val; - if (i < min || i > max) - { + if (i < min || i > max) { i = min; } Com_sprintf(s, sizeof(s), "%i\0", val); - Text_Paint(rect->x, rect->y, scale, color, s,0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, s, 0, 0, textStyle, iMenuFont); } -static void UI_DrawForceMastery(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) -{ +static void UI_DrawForceMastery(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) { int i; char *s; i = val; - if (i < min) - { + if (i < min) { i = min; } - if (i > max) - { + if (i > max) { i = max; } @@ -1751,31 +1607,28 @@ static void UI_DrawForceMastery(rectDef_t *rect, float scale, vec4_t color, int Text_Paint(rect->x, rect->y, scale, color, s, 0, 0, textStyle, iMenuFont); } -static void UI_DrawSkinColor(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) -{ +static void UI_DrawSkinColor(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) { char s[256]; - switch(val) - { + switch (val) { case TEAM_RED: trap->SE_GetStringTextString("MENUS_TEAM_RED", s, sizeof(s)); -// Com_sprintf(s, sizeof(s), "Red\0"); + // Com_sprintf(s, sizeof(s), "Red\0"); break; case TEAM_BLUE: trap->SE_GetStringTextString("MENUS_TEAM_BLUE", s, sizeof(s)); -// Com_sprintf(s, sizeof(s), "Blue\0"); + // Com_sprintf(s, sizeof(s), "Blue\0"); break; default: trap->SE_GetStringTextString("MENUS_DEFAULT", s, sizeof(s)); -// Com_sprintf(s, sizeof(s), "Default\0"); + // Com_sprintf(s, sizeof(s), "Default\0"); break; } Text_Paint(rect->x, rect->y, scale, color, s, 0, 0, textStyle, iMenuFont); } -static void UI_DrawForceSide(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) -{ +static void UI_DrawForceSide(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) { char s[256]; menuDef_t *menu; @@ -1784,10 +1637,8 @@ static void UI_DrawForceSide(rectDef_t *rect, float scale, vec4_t color, int tex info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if (atoi( Info_ValueForKey( info, "g_forceBasedTeams" ) )) - { - switch((int)(trap->Cvar_VariableValue("ui_myteam"))) - { + if (atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) { + switch ((int)(trap->Cvar_VariableValue("ui_myteam"))) { case TEAM_RED: uiForceSide = FORCE_DARKSIDE; color[0] = 0.2f; @@ -1805,79 +1656,63 @@ static void UI_DrawForceSide(rectDef_t *rect, float scale, vec4_t color, int tex } } - if (val == FORCE_LIGHTSIDE) - { - trap->SE_GetStringTextString("MENUS_FORCEDESC_LIGHT",s, sizeof(s)); + if (val == FORCE_LIGHTSIDE) { + trap->SE_GetStringTextString("MENUS_FORCEDESC_LIGHT", s, sizeof(s)); menu = Menus_FindByName("forcealloc"); - if (menu) - { + if (menu) { Menu_ShowItemByName(menu, "lightpowers", qtrue); Menu_ShowItemByName(menu, "darkpowers", qfalse); Menu_ShowItemByName(menu, "darkpowers_team", qfalse); - Menu_ShowItemByName(menu, "lightpowers_team", qtrue);//(ui_gameType.integer >= GT_TEAM)); - + Menu_ShowItemByName(menu, "lightpowers_team", qtrue); //(ui_gameType.integer >= GT_TEAM)); } menu = Menus_FindByName("ingame_playerforce"); - if (menu) - { + if (menu) { Menu_ShowItemByName(menu, "lightpowers", qtrue); Menu_ShowItemByName(menu, "darkpowers", qfalse); Menu_ShowItemByName(menu, "darkpowers_team", qfalse); - Menu_ShowItemByName(menu, "lightpowers_team", qtrue);//(ui_gameType.integer >= GT_TEAM)); + Menu_ShowItemByName(menu, "lightpowers_team", qtrue); //(ui_gameType.integer >= GT_TEAM)); } - } - else - { - trap->SE_GetStringTextString("MENUS_FORCEDESC_DARK",s, sizeof(s)); + } else { + trap->SE_GetStringTextString("MENUS_FORCEDESC_DARK", s, sizeof(s)); menu = Menus_FindByName("forcealloc"); - if (menu) - { + if (menu) { Menu_ShowItemByName(menu, "lightpowers", qfalse); Menu_ShowItemByName(menu, "lightpowers_team", qfalse); Menu_ShowItemByName(menu, "darkpowers", qtrue); - Menu_ShowItemByName(menu, "darkpowers_team", qtrue);//(ui_gameType.integer >= GT_TEAM)); + Menu_ShowItemByName(menu, "darkpowers_team", qtrue); //(ui_gameType.integer >= GT_TEAM)); } menu = Menus_FindByName("ingame_playerforce"); - if (menu) - { + if (menu) { Menu_ShowItemByName(menu, "lightpowers", qfalse); Menu_ShowItemByName(menu, "lightpowers_team", qfalse); Menu_ShowItemByName(menu, "darkpowers", qtrue); - Menu_ShowItemByName(menu, "darkpowers_team", qtrue);//(ui_gameType.integer >= GT_TEAM)); + Menu_ShowItemByName(menu, "darkpowers_team", qtrue); //(ui_gameType.integer >= GT_TEAM)); } } - Text_Paint(rect->x, rect->y, scale, color, s,0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, s, 0, 0, textStyle, iMenuFont); } -qboolean UI_HasSetSaberOnly( const char *info, const int gametype ) -{ +qboolean UI_HasSetSaberOnly(const char *info, const int gametype) { int i = 0; int wDisable = 0; - if ( gametype == GT_JEDIMASTER ) - { //set to 0 + if (gametype == GT_JEDIMASTER) { // set to 0 return qfalse; } - if (gametype == GT_DUEL || gametype == GT_POWERDUEL) - { + if (gametype == GT_DUEL || gametype == GT_POWERDUEL) { wDisable = atoi(Info_ValueForKey(info, "g_duelWeaponDisable")); - } - else - { + } else { wDisable = atoi(Info_ValueForKey(info, "g_weaponDisable")); } - while (i < WP_NUM_WEAPONS) - { - if (!(wDisable & (1 << i)) && - i != WP_SABER && i != WP_NONE) - { + while (i < WP_NUM_WEAPONS) { + if (!(wDisable & (1 << i)) && i != WP_SABER && i != WP_NONE) { return qfalse; } @@ -1887,16 +1722,12 @@ qboolean UI_HasSetSaberOnly( const char *info, const int gametype ) return qtrue; } -static qboolean UI_AllForceDisabled(int force) -{ +static qboolean UI_AllForceDisabled(int force) { int i; - if (force) - { - for (i=0;iGetConfigString( CS_SERVERINFO, info, sizeof(info) ); + trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - //already have serverinfo at this point for stuff below. Don't bother trying to use ui_forcePowerDisable. - //if (ui_forcePowerDisable.integer) - //if (atoi(Info_ValueForKey(info, "g_forcePowerDisable"))) + // already have serverinfo at this point for stuff below. Don't bother trying to use ui_forcePowerDisable. + // if (ui_forcePowerDisable.integer) + // if (atoi(Info_ValueForKey(info, "g_forcePowerDisable"))) disabledForce = atoi(Info_ValueForKey(info, "g_forcePowerDisable")); allForceDisabled = UI_AllForceDisabled(disabledForce); gametype = atoi(Info_ValueForKey(info, "g_gametype")); saberOnly = UI_HasSetSaberOnly(info, gametype); - if ( gametype == GT_HOLOCRON - || gametype == GT_JEDIMASTER - || saberOnly - || allForceDisabled ) - { + if (gametype == GT_HOLOCRON || gametype == GT_JEDIMASTER || saberOnly || allForceDisabled) { trueJedi = 0; - } - else - { - trueJedi = atoi( Info_ValueForKey( info, "g_jediVmerc" ) ); + } else { + trueJedi = atoi(Info_ValueForKey(info, "g_jediVmerc")); } return (trueJedi != 0); } -static void UI_DrawJediNonJedi(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) -{ +static void UI_DrawJediNonJedi(rectDef_t *rect, float scale, vec4_t color, int textStyle, int val, int min, int max, int iMenuFont) { int i; char s[256]; - //menuDef_t *menu; + // menuDef_t *menu; char info[MAX_INFO_VALUE]; i = val; - if (i < min || i > max) - { + if (i < min || i > max) { i = min; } info[0] = '\0'; trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if ( !UI_TrueJediEnabled() ) - {//true jedi mode is not on, do not draw this button type + if (!UI_TrueJediEnabled()) { // true jedi mode is not on, do not draw this button type return; } - if ( val == FORCE_NONJEDI ) - trap->SE_GetStringTextString("MENUS_NO",s, sizeof(s)); + if (val == FORCE_NONJEDI) + trap->SE_GetStringTextString("MENUS_NO", s, sizeof(s)); else - trap->SE_GetStringTextString("MENUS_YES",s, sizeof(s)); + trap->SE_GetStringTextString("MENUS_YES", s, sizeof(s)); - Text_Paint(rect->x, rect->y, scale, color, s,0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, s, 0, 0, textStyle, iMenuFont); } static void UI_DrawTeamName(rectDef_t *rect, float scale, vec4_t color, qboolean blue, int textStyle, int iMenuFont) { int i; i = UI_TeamIndexFromName(UI_Cvar_VariableString((blue) ? "ui_blueTeam" : "ui_redTeam")); if (i >= 0 && i < uiInfo.teamCount) { - Text_Paint(rect->x, rect->y, scale, color, va("%s: %s", (blue) ? "Blue" : "Red", uiInfo.teamList[i].teamName),0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, va("%s: %s", (blue) ? "Blue" : "Red", uiInfo.teamList[i].teamName), 0, 0, textStyle, iMenuFont); } } -static void UI_DrawTeamMember(rectDef_t *rect, float scale, vec4_t color, qboolean blue, int num, int textStyle, int iMenuFont) -{ +static void UI_DrawTeamMember(rectDef_t *rect, float scale, vec4_t color, qboolean blue, int num, int textStyle, int iMenuFont) { // 0 - None // 1 - Human // 2..NumCharacters - Bot int value = trap->Cvar_VariableValue(va(blue ? "ui_blueteam%i" : "ui_redteam%i", num)); const char *text; - int maxcl = trap->Cvar_VariableValue( "sv_maxClients" ); + int maxcl = trap->Cvar_VariableValue("sv_maxClients"); vec4_t finalColor; int numval = num; numval *= 2; - if (blue) - { + if (blue) { numval -= 1; } @@ -1998,8 +1817,7 @@ static void UI_DrawTeamMember(rectDef_t *rect, float scale, vec4_t color, qboole finalColor[2] = color[2]; finalColor[3] = color[3]; - if (numval > maxcl) - { + if (numval > maxcl) { finalColor[0] *= 0.5; finalColor[1] *= 0.5; finalColor[2] *= 0.5; @@ -2007,23 +1825,18 @@ static void UI_DrawTeamMember(rectDef_t *rect, float scale, vec4_t color, qboole value = -1; } - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) - { - if (value > 1 ) - { + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) { + if (value > 1) { value = 1; } } if (value <= 1) { - if (value == -1) - { - //text = "Closed"; + if (value == -1) { + // text = "Closed"; text = UI_GetStringEdString("MENUS", "CLOSED"); - } - else - { - //text = "Human"; + } else { + // text = "Human"; text = UI_GetStringEdString("MENUS", "HUMAN"); } } else { @@ -2055,9 +1868,9 @@ static void UI_DrawMapPreview(rectDef_t *rect, float scale, vec4_t color, qboole } if (uiInfo.mapList[map].levelShot > 0) { - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.mapList[map].levelShot); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.mapList[map].levelShot); } else { - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, trap->R_RegisterShaderNoMip("menu/art/unknownmap_mp")); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, trap->R_RegisterShaderNoMip("menu/art/unknownmap_mp")); } } @@ -2076,7 +1889,7 @@ static void UI_DrawMapCinematic(rectDef_t *rect, float scale, vec4_t color, qboo if (uiInfo.mapList[map].cinematic >= -1) { if (uiInfo.mapList[map].cinematic == -1) { - uiInfo.mapList[map].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[map].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); + uiInfo.mapList[map].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[map].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent)); } if (uiInfo.mapList[map].cinematic >= 0) { trap->CIN_RunCinematic(uiInfo.mapList[map].cinematic); @@ -2090,188 +1903,142 @@ static void UI_DrawMapCinematic(rectDef_t *rect, float scale, vec4_t color, qboo } } -static void UI_SetForceDisabled(int force) -{ +static void UI_SetForceDisabled(int force) { int i = 0; - if (force) - { - while (i < NUM_FORCE_POWERS) - { - if (force & (1 << i)) - { + if (force) { + while (i < NUM_FORCE_POWERS) { + if (force & (1 << i)) { uiForcePowersDisabled[i] = qtrue; - if (i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE) - { + if (i != FP_LEVITATION && i != FP_SABER_OFFENSE && i != FP_SABER_DEFENSE) { uiForcePowersRank[i] = 0; - } - else - { - if (i == FP_LEVITATION) - { + } else { + if (i == FP_LEVITATION) { uiForcePowersRank[i] = 1; - } - else - { + } else { uiForcePowersRank[i] = 3; } } - } - else - { + } else { uiForcePowersDisabled[i] = qfalse; } i++; } - } - else - { + } else { i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { uiForcePowersDisabled[i] = qfalse; i++; } } } // The game type on create server has changed - make the HUMAN/BOTS fields active -void UpdateBotButtons(void) -{ +void UpdateBotButtons(void) { menuDef_t *menu; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return; } - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) - { + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) { Menu_ShowItemByName(menu, "humanbotfield", qfalse); Menu_ShowItemByName(menu, "humanbotnonfield", qtrue); - } - else - { + } else { Menu_ShowItemByName(menu, "humanbotfield", qtrue); Menu_ShowItemByName(menu, "humanbotnonfield", qfalse); } - } -void UpdateForceStatus() -{ +void UpdateForceStatus() { menuDef_t *menu; // Currently we don't make a distinction between those that wish to play Jedi of lower than maximum skill. -/* if (ui_forcePowerDisable.integer) - { - uiForceRank = 0; - uiForceAvailable = 0; - uiForceUsed = 0; - } - else - { - uiForceRank = uiMaxRank; - uiForceUsed = 0; - uiForceAvailable = forceMasteryPoints[uiForceRank]; - } -*/ + /* if (ui_forcePowerDisable.integer) + { + uiForceRank = 0; + uiForceAvailable = 0; + uiForceUsed = 0; + } + else + { + uiForceRank = uiMaxRank; + uiForceUsed = 0; + uiForceAvailable = forceMasteryPoints[uiForceRank]; + } + */ menu = Menus_FindByName("ingame_player"); - if (menu) - { - char info[MAX_INFO_STRING]; - int disabledForce = 0; + if (menu) { + char info[MAX_INFO_STRING]; + int disabledForce = 0; qboolean trueJedi = qfalse, allForceDisabled = qfalse; - trap->GetConfigString( CS_SERVERINFO, info, sizeof(info) ); + trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - //already have serverinfo at this point for stuff below. Don't bother trying to use ui_forcePowerDisable. - //if (ui_forcePowerDisable.integer) - //if (atoi(Info_ValueForKey(info, "g_forcePowerDisable"))) + // already have serverinfo at this point for stuff below. Don't bother trying to use ui_forcePowerDisable. + // if (ui_forcePowerDisable.integer) + // if (atoi(Info_ValueForKey(info, "g_forcePowerDisable"))) disabledForce = atoi(Info_ValueForKey(info, "g_forcePowerDisable")); allForceDisabled = UI_AllForceDisabled(disabledForce); trueJedi = UI_TrueJediEnabled(); - if ( !trueJedi || allForceDisabled ) - { + if (!trueJedi || allForceDisabled) { Menu_ShowItemByName(menu, "jedinonjedi", qfalse); - } - else - { + } else { Menu_ShowItemByName(menu, "jedinonjedi", qtrue); } - if ( allForceDisabled == qtrue || (trueJedi && uiJediNonJedi == FORCE_NONJEDI) ) - { // No force stuff + if (allForceDisabled == qtrue || (trueJedi && uiJediNonJedi == FORCE_NONJEDI)) { // No force stuff Menu_ShowItemByName(menu, "noforce", qtrue); Menu_ShowItemByName(menu, "yesforce", qfalse); // We don't want the saber explanation to say "configure saber attack 1" since we can't. Menu_ShowItemByName(menu, "sabernoneconfigme", qfalse); - } - else - { + } else { UI_SetForceDisabled(disabledForce); Menu_ShowItemByName(menu, "noforce", qfalse); Menu_ShowItemByName(menu, "yesforce", qtrue); } - //Moved this to happen after it's done with force power disabling stuff - if (uiForcePowersRank[FP_SABER_OFFENSE] > 0 || ui_freeSaber.integer) - { // Show lightsaber stuff. + // Moved this to happen after it's done with force power disabling stuff + if (uiForcePowersRank[FP_SABER_OFFENSE] > 0 || ui_freeSaber.integer) { // Show lightsaber stuff. Menu_ShowItemByName(menu, "nosaber", qfalse); Menu_ShowItemByName(menu, "yessaber", qtrue); - } - else - { + } else { Menu_ShowItemByName(menu, "nosaber", qtrue); Menu_ShowItemByName(menu, "yessaber", qfalse); } // The leftmost button should be "apply" unless you are in spectator, where you can join any team. - if ((int)(trap->Cvar_VariableValue("ui_myteam")) != TEAM_SPECTATOR) - { + if ((int)(trap->Cvar_VariableValue("ui_myteam")) != TEAM_SPECTATOR) { Menu_ShowItemByName(menu, "playerapply", qtrue); Menu_ShowItemByName(menu, "playerforcejoin", qfalse); Menu_ShowItemByName(menu, "playerforcered", qtrue); Menu_ShowItemByName(menu, "playerforceblue", qtrue); Menu_ShowItemByName(menu, "playerforcespectate", qtrue); - } - else - { + } else { // Set or reset buttons based on choices - if (atoi(Info_ValueForKey(info, "g_gametype")) >= GT_TEAM) - { // This is a team-based game. + if (atoi(Info_ValueForKey(info, "g_gametype")) >= GT_TEAM) { // This is a team-based game. Menu_ShowItemByName(menu, "playerforcespectate", qtrue); // This is disabled, always show both sides from spectator. - if ( 0 && atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) - { // Show red or blue based on what side is chosen. - if (uiForceSide==FORCE_LIGHTSIDE) - { + if (0 && atoi(Info_ValueForKey(info, "g_forceBasedTeams"))) { // Show red or blue based on what side is chosen. + if (uiForceSide == FORCE_LIGHTSIDE) { Menu_ShowItemByName(menu, "playerforcered", qfalse); Menu_ShowItemByName(menu, "playerforceblue", qtrue); - } - else if (uiForceSide==FORCE_DARKSIDE) - { + } else if (uiForceSide == FORCE_DARKSIDE) { Menu_ShowItemByName(menu, "playerforcered", qtrue); Menu_ShowItemByName(menu, "playerforceblue", qfalse); - } - else - { + } else { Menu_ShowItemByName(menu, "playerforcered", qtrue); Menu_ShowItemByName(menu, "playerforceblue", qtrue); } - } - else - { + } else { Menu_ShowItemByName(menu, "playerforcered", qtrue); Menu_ShowItemByName(menu, "playerforceblue", qtrue); } - } - else - { + } else { Menu_ShowItemByName(menu, "playerforcered", qfalse); Menu_ShowItemByName(menu, "playerforceblue", qfalse); } @@ -2282,12 +2049,10 @@ void UpdateForceStatus() } } - if ( !UI_TrueJediEnabled() ) - {// Take the current team and force a skin color based on it. - char info[MAX_INFO_STRING]; + if (!UI_TrueJediEnabled()) { // Take the current team and force a skin color based on it. + char info[MAX_INFO_STRING]; - switch((int)(trap->Cvar_VariableValue("ui_myteam"))) - { + switch ((int)(trap->Cvar_VariableValue("ui_myteam"))) { case TEAM_RED: uiSkinColor = TEAM_RED; break; @@ -2295,13 +2060,11 @@ void UpdateForceStatus() uiSkinColor = TEAM_BLUE; break; default: - trap->GetConfigString( CS_SERVERINFO, info, sizeof(info) ); + trap->GetConfigString(CS_SERVERINFO, info, sizeof(info)); - if (atoi(Info_ValueForKey(info, "g_gametype")) >= GT_TEAM) - { + if (atoi(Info_ValueForKey(info, "g_gametype")) >= GT_TEAM) { uiSkinColor = TEAM_FREE; - } - else // A bit of a hack so non-team games will remember which skin set you chose in the player menu + } else // A bit of a hack so non-team games will remember which skin set you chose in the player menu { uiSkinColor = uiHoldSkinColor; } @@ -2310,23 +2073,21 @@ void UpdateForceStatus() } } -static void UI_DrawNetSource(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ +static void UI_DrawNetSource(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { if (ui_netSource.integer < 0 || ui_netSource.integer >= numNetSources) { trap->Cvar_Set("ui_netSource", "0"); trap->Cvar_Update(&ui_netSource); } - trap->SE_GetStringTextString("MENUS_SOURCE", holdSPString, sizeof(holdSPString) ); - Text_Paint(rect->x, rect->y, scale, color, va("%s %s",holdSPString, - GetNetSourceString(ui_netSource.integer)), 0, 0, textStyle, iMenuFont); + trap->SE_GetStringTextString("MENUS_SOURCE", holdSPString, sizeof(holdSPString)); + Text_Paint(rect->x, rect->y, scale, color, va("%s %s", holdSPString, GetNetSourceString(ui_netSource.integer)), 0, 0, textStyle, iMenuFont); } static void UI_DrawNetMapPreview(rectDef_t *rect, float scale, vec4_t color) { if (uiInfo.serverStatus.currentServerPreview > 0) { - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.serverStatus.currentServerPreview); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.serverStatus.currentServerPreview); } else { - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, trap->R_RegisterShaderNoMip("menu/art/unknownmap_mp")); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, trap->R_RegisterShaderNoMip("menu/art/unknownmap_mp")); } } @@ -2345,25 +2106,24 @@ static void UI_DrawNetMapCinematic(rectDef_t *rect, float scale, vec4_t color) { } } -static void UI_DrawNetFilter(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ +static void UI_DrawNetFilter(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { trap->SE_GetStringTextString("MENUS_GAME", holdSPString, sizeof(holdSPString)); - Text_Paint(rect->x, rect->y, scale, color, va("%s %s",holdSPString, UI_FilterDescription( ui_serverFilterType.integer )), 0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, va("%s %s", holdSPString, UI_FilterDescription(ui_serverFilterType.integer)), 0, 0, textStyle, iMenuFont); } static void UI_DrawTier(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int i; - i = trap->Cvar_VariableValue( "ui_currentTier" ); + i = trap->Cvar_VariableValue("ui_currentTier"); if (i < 0 || i >= uiInfo.tierCount) { i = 0; } - Text_Paint(rect->x, rect->y, scale, color, va("Tier: %s", uiInfo.tierList[i].tierName),0, 0, textStyle, iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, va("Tier: %s", uiInfo.tierList[i].tierName), 0, 0, textStyle, iMenuFont); } static void UI_DrawTierMap(rectDef_t *rect, int index) { int i; - i = trap->Cvar_VariableValue( "ui_currentTier" ); + i = trap->Cvar_VariableValue("ui_currentTier"); if (i < 0 || i >= uiInfo.tierCount) { i = 0; } @@ -2372,7 +2132,7 @@ static void UI_DrawTierMap(rectDef_t *rect, int index) { uiInfo.tierList[i].mapHandles[index] = trap->R_RegisterShaderNoMip(va("levelshots/%s", uiInfo.tierList[i].maps[index])); } - UI_DrawHandlePic( rect->x, rect->y, rect->w, rect->h, uiInfo.tierList[i].mapHandles[index]); + UI_DrawHandlePic(rect->x, rect->y, rect->w, rect->h, uiInfo.tierList[i].mapHandles[index]); } static const char *UI_EnglishMapName(const char *map) { @@ -2387,7 +2147,7 @@ static const char *UI_EnglishMapName(const char *map) { static void UI_DrawTierMapName(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int i, j; - i = trap->Cvar_VariableValue( "ui_currentTier" ); + i = trap->Cvar_VariableValue("ui_currentTier"); if (i < 0 || i >= uiInfo.tierCount) { i = 0; } @@ -2401,7 +2161,7 @@ static void UI_DrawTierMapName(rectDef_t *rect, float scale, vec4_t color, int t static void UI_DrawTierGameType(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int i, j; - i = trap->Cvar_VariableValue( "ui_currentTier" ); + i = trap->Cvar_VariableValue("ui_currentTier"); if (i < 0 || i >= uiInfo.tierCount) { i = 0; } @@ -2410,7 +2170,7 @@ static void UI_DrawTierGameType(rectDef_t *rect, float scale, vec4_t color, int j = 0; } - Text_Paint(rect->x, rect->y, scale, color, uiInfo.gameTypes[uiInfo.tierList[i].gameTypes[j]].gameType , 0, 0, textStyle,iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, uiInfo.gameTypes[uiInfo.tierList[i].gameTypes[j]].gameType, 0, 0, textStyle, iMenuFont); } static const char *UI_AIFromName(const char *name) { @@ -2439,15 +2199,15 @@ static void UI_DrawOpponent(rectDef_t *rect) { strcpy(headmodel, UI_Cvar_VariableString("ui_opponentModel")); team[0] = '\0'; - memset( &info2, 0, sizeof(playerInfo_t) ); - viewangles[YAW] = 180 - 10; - viewangles[PITCH] = 0; - viewangles[ROLL] = 0; - VectorClear( moveangles ); - UI_PlayerInfo_SetModel( &info2, model, headmodel, ""); - UI_PlayerInfo_SetInfo( &info2, TORSO_WEAPONREADY3, TORSO_WEAPONREADY3, viewangles, vec3_origin, WP_BRYAR_PISTOL, qfalse ); + memset( &info2, 0, sizeof(playerInfo_t) ); + viewangles[YAW] = 180 - 10; + viewangles[PITCH] = 0; + viewangles[ROLL] = 0; + VectorClear( moveangles ); + UI_PlayerInfo_SetModel( &info2, model, headmodel, ""); + UI_PlayerInfo_SetInfo( &info2, TORSO_WEAPONREADY3, TORSO_WEAPONREADY3, viewangles, vec3_origin, WP_BRYAR_PISTOL, qfalse ); UI_RegisterClientModelname( &info2, model, headmodel, team); - updateOpponentModel = qfalse; + updateOpponentModel = qfalse; } UI_DrawPlayer( rect->x, rect->y, rect->w, rect->h, &info2, uiInfo.uiDC.realTime / 2); @@ -2463,11 +2223,11 @@ static void UI_NextOpponent() { } if (i == j) { i++; - if ( i >= uiInfo.teamCount) { + if (i >= uiInfo.teamCount) { i = 0; } } - trap->Cvar_Set( "ui_opponentName", uiInfo.teamList[i].teamName ); + trap->Cvar_Set("ui_opponentName", uiInfo.teamList[i].teamName); } static void UI_PriorOpponent() { @@ -2479,14 +2239,14 @@ static void UI_PriorOpponent() { } if (i == j) { i--; - if ( i < 0) { + if (i < 0) { i = uiInfo.teamCount - 1; } } - trap->Cvar_Set( "ui_opponentName", uiInfo.teamList[i].teamName ); + trap->Cvar_Set("ui_opponentName", uiInfo.teamList[i].teamName); } -static void UI_DrawPlayerLogo(rectDef_t *rect, vec3_t color) { +static void UI_DrawPlayerLogo(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2499,7 +2259,7 @@ static void UI_DrawPlayerLogo(rectDef_t *rect, vec3_t color) { trap->R_SetColor(NULL); } -static void UI_DrawPlayerLogoMetal(rectDef_t *rect, vec3_t color) { +static void UI_DrawPlayerLogoMetal(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2512,7 +2272,7 @@ static void UI_DrawPlayerLogoMetal(rectDef_t *rect, vec3_t color) { trap->R_SetColor(NULL); } -static void UI_DrawPlayerLogoName(rectDef_t *rect, vec3_t color) { +static void UI_DrawPlayerLogoName(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2525,7 +2285,7 @@ static void UI_DrawPlayerLogoName(rectDef_t *rect, vec3_t color) { trap->R_SetColor(NULL); } -static void UI_DrawOpponentLogo(rectDef_t *rect, vec3_t color) { +static void UI_DrawOpponentLogo(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2538,7 +2298,7 @@ static void UI_DrawOpponentLogo(rectDef_t *rect, vec3_t color) { trap->R_SetColor(NULL); } -static void UI_DrawOpponentLogoMetal(rectDef_t *rect, vec3_t color) { +static void UI_DrawOpponentLogoMetal(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2551,7 +2311,7 @@ static void UI_DrawOpponentLogoMetal(rectDef_t *rect, vec3_t color) { trap->R_SetColor(NULL); } -static void UI_DrawOpponentLogoName(rectDef_t *rect, vec3_t color) { +static void UI_DrawOpponentLogoName(rectDef_t *rect, vec3_t color) { int i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName")); if (uiInfo.teamList[i].teamIcon == -1) { uiInfo.teamList[i].teamIcon = trap->R_RegisterShaderNoMip(uiInfo.teamList[i].imageName); @@ -2581,64 +2341,56 @@ static int UI_OwnerDrawWidth(int ownerDraw, float scale) { const char *s = NULL; switch (ownerDraw) { - case UI_HANDICAP: - h = Com_Clamp( 5, 100, trap->Cvar_VariableValue("handicap") ); - i = 20 - h / 5; - s = handicapValues[i]; - break; - case UI_SKIN_COLOR: - switch(uiSkinColor) - { + case UI_HANDICAP: + h = Com_Clamp(5, 100, trap->Cvar_VariableValue("handicap")); + i = 20 - h / 5; + s = handicapValues[i]; + break; + case UI_SKIN_COLOR: + switch (uiSkinColor) { case TEAM_RED: -// s = "Red"; + // s = "Red"; s = (char *)UI_GetStringEdString("MENUS", "TEAM_RED"); break; case TEAM_BLUE: -// s = "Blue"; + // s = "Blue"; s = (char *)UI_GetStringEdString("MENUS", "TEAM_BLUE"); break; default: -// s = "Default"; + // s = "Default"; s = (char *)UI_GetStringEdString("MENUS", "DEFAULT"); break; } break; - case UI_FORCE_SIDE: + case UI_FORCE_SIDE: i = uiForceSide; if (i < 1 || i > 2) { i = 1; } - if (i == FORCE_LIGHTSIDE) - { -// s = "Light"; + if (i == FORCE_LIGHTSIDE) { + // s = "Light"; s = (char *)UI_GetStringEdString("MENUS", "FORCEDESC_LIGHT"); - } - else - { -// s = "Dark"; + } else { + // s = "Dark"; s = (char *)UI_GetStringEdString("MENUS", "FORCEDESC_DARK"); } break; - case UI_JEDI_NONJEDI: + case UI_JEDI_NONJEDI: i = uiJediNonJedi; - if (i < 0 || i > 1) - { + if (i < 0 || i > 1) { i = 0; } - if (i == FORCE_NONJEDI) - { -// s = "Non-Jedi"; + if (i == FORCE_NONJEDI) { + // s = "Non-Jedi"; s = (char *)UI_GetStringEdString("MENUS", "NO"); - } - else - { -// s = "Jedi"; + } else { + // s = "Jedi"; s = (char *)UI_GetStringEdString("MENUS", "YES"); } break; - case UI_FORCE_RANK: + case UI_FORCE_RANK: i = uiForceRank; if (i < 1 || i > MAX_FORCE_RANK) { i = 1; @@ -2664,135 +2416,128 @@ static int UI_OwnerDrawWidth(int ownerDraw, float scale) { case UI_FORCE_RANK_SABERATTACK: case UI_FORCE_RANK_SABERDEFEND: case UI_FORCE_RANK_SABERTHROW: - findex = (ownerDraw - UI_FORCE_RANK)-1; - //this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index + findex = (ownerDraw - UI_FORCE_RANK) - 1; + // this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index i = uiForcePowersRank[findex]; - if (i < 0 || i > NUM_FORCE_POWER_LEVELS-1) - { + if (i < 0 || i > NUM_FORCE_POWER_LEVELS - 1) { i = 0; } s = va("%i", uiForcePowersRank[findex]); break; - case UI_CLANNAME: + case UI_CLANNAME: s = UI_Cvar_VariableString("ui_teamName"); - break; - case UI_GAMETYPE: + break; + case UI_GAMETYPE: s = uiInfo.gameTypes[ui_gametype.integer].gameType; - break; - case UI_SKILL: - i = trap->Cvar_VariableValue( "g_spSkill" ); + break; + case UI_SKILL: + i = trap->Cvar_VariableValue("g_spSkill"); if (i < 1 || i > numSkillLevels) { i = 1; } - s = (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[i-1]); - break; - case UI_BLUETEAMNAME: + s = (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[i - 1]); + break; + case UI_BLUETEAMNAME: i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_blueTeam")); if (i >= 0 && i < uiInfo.teamCount) { s = va("%s: %s", (char *)UI_GetStringEdString("MENUS", "TEAM_BLUE"), uiInfo.teamList[i].teamName); } - break; - case UI_REDTEAMNAME: + break; + case UI_REDTEAMNAME: i = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_redTeam")); if (i >= 0 && i < uiInfo.teamCount) { - s = va("%s: %s", (char *)UI_GetStringEdString("MENUS", "TEAM_RED"), uiInfo.teamList[i].teamName); - } - break; - case UI_BLUETEAM1: - case UI_BLUETEAM2: - case UI_BLUETEAM3: - case UI_BLUETEAM4: - case UI_BLUETEAM5: - case UI_BLUETEAM6: - case UI_BLUETEAM7: - case UI_BLUETEAM8: - if (ownerDraw <= UI_BLUETEAM5) - { - iUse = ownerDraw-UI_BLUETEAM1 + 1; - } - else - { - iUse = ownerDraw-274; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines - } + s = va("%s: %s", (char *)UI_GetStringEdString("MENUS", "TEAM_RED"), uiInfo.teamList[i].teamName); + } + break; + case UI_BLUETEAM1: + case UI_BLUETEAM2: + case UI_BLUETEAM3: + case UI_BLUETEAM4: + case UI_BLUETEAM5: + case UI_BLUETEAM6: + case UI_BLUETEAM7: + case UI_BLUETEAM8: + if (ownerDraw <= UI_BLUETEAM5) { + iUse = ownerDraw - UI_BLUETEAM1 + 1; + } else { + iUse = ownerDraw - 274; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + } - value = trap->Cvar_VariableValue(va("ui_blueteam%i", iUse)); - if (value <= 1) { - text = "Human"; - } else { - value -= 2; - if (value >= uiInfo.aliasCount) { - value = 1; - } - text = uiInfo.aliasList[value].name; - } - s = va("%i. %s", iUse, text); - break; - case UI_REDTEAM1: - case UI_REDTEAM2: - case UI_REDTEAM3: - case UI_REDTEAM4: - case UI_REDTEAM5: - case UI_REDTEAM6: - case UI_REDTEAM7: - case UI_REDTEAM8: - if (ownerDraw <= UI_REDTEAM5) - { - iUse = ownerDraw-UI_REDTEAM1 + 1; - } - else - { - iUse = ownerDraw-277; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + value = trap->Cvar_VariableValue(va("ui_blueteam%i", iUse)); + if (value <= 1) { + text = "Human"; + } else { + value -= 2; + if (value >= uiInfo.aliasCount) { + value = 1; } + text = uiInfo.aliasList[value].name; + } + s = va("%i. %s", iUse, text); + break; + case UI_REDTEAM1: + case UI_REDTEAM2: + case UI_REDTEAM3: + case UI_REDTEAM4: + case UI_REDTEAM5: + case UI_REDTEAM6: + case UI_REDTEAM7: + case UI_REDTEAM8: + if (ownerDraw <= UI_REDTEAM5) { + iUse = ownerDraw - UI_REDTEAM1 + 1; + } else { + iUse = ownerDraw - 277; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + } - value = trap->Cvar_VariableValue(va("ui_redteam%i", iUse)); - if (value <= 1) { - text = "Human"; - } else { - value -= 2; - if (value >= uiInfo.aliasCount) { - value = 1; - } - text = uiInfo.aliasList[value].name; - } - s = va("%i. %s", iUse, text); - break; - case UI_NETSOURCE: - if (ui_netSource.integer < 0 || ui_netSource.integer >= numNetSources) { - trap->Cvar_Set("ui_netSource", "0"); - trap->Cvar_Update(&ui_netSource); + value = trap->Cvar_VariableValue(va("ui_redteam%i", iUse)); + if (value <= 1) { + text = "Human"; + } else { + value -= 2; + if (value >= uiInfo.aliasCount) { + value = 1; } - trap->SE_GetStringTextString("MENUS_SOURCE", holdSPString, sizeof(holdSPString)); - s = va("%s %s", holdSPString, GetNetSourceString(ui_netSource.integer)); - break; - case UI_NETFILTER: - trap->SE_GetStringTextString("MENUS_GAME", holdSPString, sizeof(holdSPString)); - s = va("%s %s", holdSPString, UI_FilterDescription( ui_serverFilterType.integer ) ); - break; - case UI_TIER: - break; - case UI_TIER_MAPNAME: - break; - case UI_TIER_GAMETYPE: - break; - case UI_ALLMAPS_SELECTION: - break; - case UI_OPPONENT_NAME: - break; - case UI_KEYBINDSTATUS: - if (Display_KeyBindPending()) { - s = UI_GetStringEdString("MP_INGAME", "WAITING_FOR_NEW_KEY"); - } else { + text = uiInfo.aliasList[value].name; + } + s = va("%i. %s", iUse, text); + break; + case UI_NETSOURCE: + if (ui_netSource.integer < 0 || ui_netSource.integer >= numNetSources) { + trap->Cvar_Set("ui_netSource", "0"); + trap->Cvar_Update(&ui_netSource); + } + trap->SE_GetStringTextString("MENUS_SOURCE", holdSPString, sizeof(holdSPString)); + s = va("%s %s", holdSPString, GetNetSourceString(ui_netSource.integer)); + break; + case UI_NETFILTER: + trap->SE_GetStringTextString("MENUS_GAME", holdSPString, sizeof(holdSPString)); + s = va("%s %s", holdSPString, UI_FilterDescription(ui_serverFilterType.integer)); + break; + case UI_TIER: + break; + case UI_TIER_MAPNAME: + break; + case UI_TIER_GAMETYPE: + break; + case UI_ALLMAPS_SELECTION: + break; + case UI_OPPONENT_NAME: + break; + case UI_KEYBINDSTATUS: + if (Display_KeyBindPending()) { + s = UI_GetStringEdString("MP_INGAME", "WAITING_FOR_NEW_KEY"); + } else { // s = "Press ENTER or CLICK to change, Press BACKSPACE to clear"; - } - break; - case UI_SERVERREFRESHDATE: - s = UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)); - break; - default: - break; - } + } + break; + case UI_SERVERREFRESHDATE: + s = UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)); + break; + default: + break; + } if (s) { return Text_Width(s, scale, 0); @@ -2800,41 +2545,39 @@ static int UI_OwnerDrawWidth(int ownerDraw, float scale) { return 0; } -static void UI_DrawBotName(rectDef_t *rect, float scale, vec4_t color, int textStyle,int iMenuFont) -{ +static void UI_DrawBotName(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { int value = uiInfo.botIndex; const char *text = ""; if (value >= UI_GetNumBots()) { value = 0; } text = UI_GetBotNameByNumber(value); - Text_Paint(rect->x, rect->y, scale, color, text, 0, 0, textStyle,iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, text, 0, 0, textStyle, iMenuFont); } -static void UI_DrawBotSkill(rectDef_t *rect, float scale, vec4_t color, int textStyle,int iMenuFont) -{ - if (uiInfo.skillIndex >= 0 && uiInfo.skillIndex < numSkillLevels) - { - Text_Paint(rect->x, rect->y, scale, color, (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[uiInfo.skillIndex]), 0, 0, textStyle,iMenuFont); +static void UI_DrawBotSkill(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { + if (uiInfo.skillIndex >= 0 && uiInfo.skillIndex < numSkillLevels) { + Text_Paint(rect->x, rect->y, scale, color, (char *)UI_GetStringEdString("MP_INGAME", (char *)skillLevels[uiInfo.skillIndex]), 0, 0, textStyle, + iMenuFont); } } -static void UI_DrawRedBlue(rectDef_t *rect, float scale, vec4_t color, int textStyle,int iMenuFont) -{ - Text_Paint(rect->x, rect->y, scale, color, (uiInfo.redBlue == 0) ? UI_GetStringEdString("MP_INGAME","RED") : UI_GetStringEdString("MP_INGAME","BLUE"), 0, 0, textStyle,iMenuFont); +static void UI_DrawRedBlue(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { + Text_Paint(rect->x, rect->y, scale, color, (uiInfo.redBlue == 0) ? UI_GetStringEdString("MP_INGAME", "RED") : UI_GetStringEdString("MP_INGAME", "BLUE"), 0, + 0, textStyle, iMenuFont); } static void UI_DrawCrosshair(rectDef_t *rect, float scale, vec4_t color) { float size = 32.0f; - trap->R_SetColor( color ); + trap->R_SetColor(color); if (uiInfo.currentCrosshair < 0 || uiInfo.currentCrosshair >= NUM_CROSSHAIRS) { uiInfo.currentCrosshair = 0; } - size = Q_min( rect->w, rect->h ); - UI_DrawHandlePic( rect->x, rect->y, size, size, uiInfo.uiDC.Assets.crosshairShader[uiInfo.currentCrosshair]); - trap->R_SetColor( NULL ); + size = Q_min(rect->w, rect->h); + UI_DrawHandlePic(rect->x, rect->y, size, size, uiInfo.uiDC.Assets.crosshairShader[uiInfo.currentCrosshair]); + trap->R_SetColor(NULL); } static void UI_DrawSelectedPlayer(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { @@ -2845,22 +2588,18 @@ static void UI_DrawSelectedPlayer(rectDef_t *rect, float scale, vec4_t color, in Text_Paint(rect->x, rect->y, scale, color, UI_Cvar_VariableString("cg_selectedPlayerName"), 0, 0, textStyle, iMenuFont); } -static void UI_DrawServerRefreshDate(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) -{ - if (uiInfo.serverStatus.refreshActive) - { +static void UI_DrawServerRefreshDate(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { + if (uiInfo.serverStatus.refreshActive) { vec4_t lowLight, newColor; lowLight[0] = 0.8 * color[0]; lowLight[1] = 0.8 * color[1]; lowLight[2] = 0.8 * color[2]; lowLight[3] = 0.8 * color[3]; - LerpColor(color,lowLight,newColor,0.5+0.5*sin((float)(uiInfo.uiDC.realTime / PULSE_DIVISOR))); + LerpColor(color, lowLight, newColor, 0.5 + 0.5 * sin((float)(uiInfo.uiDC.realTime / PULSE_DIVISOR))); trap->SE_GetStringTextString("MP_INGAME_GETTINGINFOFORSERVERS", holdSPString, sizeof(holdSPString)); - Text_Paint(rect->x, rect->y, scale, newColor, va((char *) holdSPString, trap->LAN_GetServerCount(UI_SourceForLAN())), 0, 0, textStyle, iMenuFont); - } - else - { + Text_Paint(rect->x, rect->y, scale, newColor, va((char *)holdSPString, trap->LAN_GetServerCount(UI_SourceForLAN())), 0, 0, textStyle, iMenuFont); + } else { char buff[64]; Q_strncpyz(buff, UI_Cvar_VariableString(va("ui_lastServerRefresh_%i", ui_netSource.integer)), sizeof(buff)); trap->SE_GetStringTextString("MP_INGAME_SERVER_REFRESHTIME", holdSPString, sizeof(holdSPString)); @@ -2901,25 +2640,27 @@ static void UI_DrawServerMOTD(rectDef_t *rect, float scale, vec4_t color, int iM uiInfo.serverStatus.motdPaintX2 = -1; } } else { - //serverStatus.motdPaintX--; + // serverStatus.motdPaintX--; uiInfo.serverStatus.motdPaintX -= 2; if (uiInfo.serverStatus.motdPaintX2 >= 0) { - //serverStatus.motdPaintX2--; + // serverStatus.motdPaintX2--; uiInfo.serverStatus.motdPaintX2 -= 2; } } } maxX = rect->x + rect->w - 2; - Text_Paint_Limit(&maxX, uiInfo.serverStatus.motdPaintX, rect->y + rect->h - 3, scale, color, &uiInfo.serverStatus.motd[uiInfo.serverStatus.motdOffset], 0, 0, iMenuFont); + Text_Paint_Limit(&maxX, uiInfo.serverStatus.motdPaintX, rect->y + rect->h - 3, scale, color, &uiInfo.serverStatus.motd[uiInfo.serverStatus.motdOffset], + 0, 0, iMenuFont); if (uiInfo.serverStatus.motdPaintX2 >= 0) { float maxX2 = rect->x + rect->w - 2; - Text_Paint_Limit(&maxX2, uiInfo.serverStatus.motdPaintX2, rect->y + rect->h - 3, scale, color, uiInfo.serverStatus.motd, 0, uiInfo.serverStatus.motdOffset, iMenuFont); + Text_Paint_Limit(&maxX2, uiInfo.serverStatus.motdPaintX2, rect->y + rect->h - 3, scale, color, uiInfo.serverStatus.motd, 0, + uiInfo.serverStatus.motdOffset, iMenuFont); } if (uiInfo.serverStatus.motdOffset && maxX > 0) { // if we have an offset ( we are skipping the first part of the string ) and we fit the string if (uiInfo.serverStatus.motdPaintX2 == -1) { - uiInfo.serverStatus.motdPaintX2 = rect->x + rect->w - 2; + uiInfo.serverStatus.motdPaintX2 = rect->x + rect->w - 2; } } else { uiInfo.serverStatus.motdPaintX2 = -1; @@ -2927,42 +2668,41 @@ static void UI_DrawServerMOTD(rectDef_t *rect, float scale, vec4_t color, int iM } } -static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int textStyle,int iMenuFont) { +static void UI_DrawKeyBindStatus(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { if (Display_KeyBindPending()) { - Text_Paint(rect->x, rect->y, scale, color, UI_GetStringEdString("MP_INGAME", "WAITING_FOR_NEW_KEY"), 0, 0, textStyle,iMenuFont); + Text_Paint(rect->x, rect->y, scale, color, UI_GetStringEdString("MP_INGAME", "WAITING_FOR_NEW_KEY"), 0, 0, textStyle, iMenuFont); } else { -// Text_Paint(rect->x, rect->y, scale, color, "Press ENTER or CLICK to change, Press BACKSPACE to clear", 0, 0, textStyle,iMenuFont); + // Text_Paint(rect->x, rect->y, scale, color, "Press ENTER or CLICK to change, Press BACKSPACE to clear", 0, 0, textStyle,iMenuFont); } } -static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textStyle,int iMenuFont) -{ +static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textStyle, int iMenuFont) { char buff[4096] = {0}; char *extensionName; - int y, i=0; + int y, i = 0; - Text_Paint(rect->x + 2, rect->y, scale, color, va("GL_VENDOR: %s", uiInfo.uiDC.glconfig.vendor_string), 0, rect->w, textStyle,iMenuFont); - Text_Paint(rect->x + 2, rect->y + 15, scale, color, va("GL_VERSION: %s: %s", uiInfo.uiDC.glconfig.version_string,uiInfo.uiDC.glconfig.renderer_string), 0, rect->w, textStyle,iMenuFont); - Text_Paint(rect->x + 2, rect->y + 30, scale, color, va ("GL_PIXELFORMAT: color(%d-bits) Z(%d-bits) stencil(%d-bits)", uiInfo.uiDC.glconfig.colorBits, uiInfo.uiDC.glconfig.depthBits, uiInfo.uiDC.glconfig.stencilBits), 0, rect->w, textStyle,iMenuFont); + Text_Paint(rect->x + 2, rect->y, scale, color, va("GL_VENDOR: %s", uiInfo.uiDC.glconfig.vendor_string), 0, rect->w, textStyle, iMenuFont); + Text_Paint(rect->x + 2, rect->y + 15, scale, color, va("GL_VERSION: %s: %s", uiInfo.uiDC.glconfig.version_string, uiInfo.uiDC.glconfig.renderer_string), 0, + rect->w, textStyle, iMenuFont); + Text_Paint(rect->x + 2, rect->y + 30, scale, color, + va("GL_PIXELFORMAT: color(%d-bits) Z(%d-bits) stencil(%d-bits)", uiInfo.uiDC.glconfig.colorBits, uiInfo.uiDC.glconfig.depthBits, + uiInfo.uiDC.glconfig.stencilBits), + 0, rect->w, textStyle, iMenuFont); // build null terminated extension strings Q_strncpyz(buff, uiInfo.uiDC.glconfig.extensions_string, sizeof(buff)); y = rect->y + 45; - extensionName = strtok (buff, " "); - while ( y < rect->y + rect->h && extensionName != NULL ) - { - if ( (i % 2) == 0 ) - { - Text_Paint (rect->x + 2, y, scale, color, extensionName, 0, (rect->w / 2), textStyle, iMenuFont); - } - else - { - Text_Paint (rect->x + rect->w / 2, y, scale, color, extensionName, 0, (rect->w / 2), textStyle, iMenuFont); + extensionName = strtok(buff, " "); + while (y < rect->y + rect->h && extensionName != NULL) { + if ((i % 2) == 0) { + Text_Paint(rect->x + 2, y, scale, color, extensionName, 0, (rect->w / 2), textStyle, iMenuFont); + } else { + Text_Paint(rect->x + rect->w / 2, y, scale, color, extensionName, 0, (rect->w / 2), textStyle, iMenuFont); y += 11; } - extensionName = strtok (NULL, " "); + extensionName = strtok(NULL, " "); i++; } } @@ -2972,8 +2712,7 @@ static void UI_DrawGLInfo(rectDef_t *rect, float scale, vec4_t color, int textSt UI_Version ================= */ -static void UI_Version(rectDef_t *rect, float scale, vec4_t color, int iMenuFont) -{ +static void UI_Version(rectDef_t *rect, float scale, vec4_t color, int iMenuFont) { int width; width = uiInfo.uiDC.textWidth(JK_VERSION, scale, iMenuFont); @@ -2988,8 +2727,8 @@ UI_OwnerDraw */ // FIXME: table drive // -static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, float scale, vec4_t color, qhandle_t shader, int textStyle,int iMenuFont) -{ +static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float text_y, int ownerDraw, int ownerDrawFlags, int align, float special, + float scale, vec4_t color, qhandle_t shader, int textStyle, int iMenuFont) { rectDef_t rect; int findex; int drawRank = 0, iUse = 0; @@ -2999,29 +2738,28 @@ static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float rect.w = w; rect.h = h; - switch (ownerDraw) - { - case UI_HANDICAP: - UI_DrawHandicap(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_SKIN_COLOR: - UI_DrawSkinColor(&rect, scale, color, textStyle, uiSkinColor, TEAM_FREE, TEAM_BLUE, iMenuFont); - break; + switch (ownerDraw) { + case UI_HANDICAP: + UI_DrawHandicap(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_SKIN_COLOR: + UI_DrawSkinColor(&rect, scale, color, textStyle, uiSkinColor, TEAM_FREE, TEAM_BLUE, iMenuFont); + break; case UI_FORCE_SIDE: - UI_DrawForceSide(&rect, scale, color, textStyle, uiForceSide, 1, 2, iMenuFont); - break; + UI_DrawForceSide(&rect, scale, color, textStyle, uiForceSide, 1, 2, iMenuFont); + break; case UI_JEDI_NONJEDI: - UI_DrawJediNonJedi(&rect, scale, color, textStyle, uiJediNonJedi, 0, 1, iMenuFont); - break; - case UI_FORCE_POINTS: - UI_DrawGenericNum(&rect, scale, color, textStyle, uiForceAvailable, 1, forceMasteryPoints[MAX_FORCE_RANK], ownerDraw,iMenuFont); - break; + UI_DrawJediNonJedi(&rect, scale, color, textStyle, uiJediNonJedi, 0, 1, iMenuFont); + break; + case UI_FORCE_POINTS: + UI_DrawGenericNum(&rect, scale, color, textStyle, uiForceAvailable, 1, forceMasteryPoints[MAX_FORCE_RANK], ownerDraw, iMenuFont); + break; case UI_FORCE_MASTERY_SET: - UI_DrawForceMastery(&rect, scale, color, textStyle, uiForceRank, 0, MAX_FORCE_RANK, iMenuFont); - break; - case UI_FORCE_RANK: - UI_DrawForceMastery(&rect, scale, color, textStyle, uiForceRank, 0, MAX_FORCE_RANK, iMenuFont); - break; + UI_DrawForceMastery(&rect, scale, color, textStyle, uiForceRank, 0, MAX_FORCE_RANK, iMenuFont); + break; + case UI_FORCE_RANK: + UI_DrawForceMastery(&rect, scale, color, textStyle, uiForceRank, 0, MAX_FORCE_RANK, iMenuFont); + break; case UI_FORCE_RANK_HEAL: case UI_FORCE_RANK_LEVITATION: case UI_FORCE_RANK_SPEED: @@ -3041,219 +2779,213 @@ static void UI_OwnerDraw(float x, float y, float w, float h, float text_x, float case UI_FORCE_RANK_SABERDEFEND: case UI_FORCE_RANK_SABERTHROW: -// uiForceRank -/* - uiForceUsed - // Only fields for white stars - if (uiForceUsed<3) - { - Menu_ShowItemByName(menu, "lightpowers_team", qtrue); - } - else if (uiForceUsed<6) - { - Menu_ShowItemByName(menu, "lightpowers_team", qtrue); - } -*/ + // uiForceRank + /* + uiForceUsed + // Only fields for white stars + if (uiForceUsed<3) + { + Menu_ShowItemByName(menu, "lightpowers_team", qtrue); + } + else if (uiForceUsed<6) + { + Menu_ShowItemByName(menu, "lightpowers_team", qtrue); + } + */ - findex = (ownerDraw - UI_FORCE_RANK)-1; - //this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index - if (uiForcePowerDarkLight[findex] && uiForceSide != uiForcePowerDarkLight[findex]) - { + findex = (ownerDraw - UI_FORCE_RANK) - 1; + // this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index + if (uiForcePowerDarkLight[findex] && uiForceSide != uiForcePowerDarkLight[findex]) { color[0] *= 0.5; color[1] *= 0.5; color[2] *= 0.5; } -/* else if (uiForceRank < UI_ForceColorMinRank[bgForcePowerCost[findex][FORCE_LEVEL_1]]) - { - color[0] *= 0.5; - color[1] *= 0.5; - color[2] *= 0.5; + /* else if (uiForceRank < UI_ForceColorMinRank[bgForcePowerCost[findex][FORCE_LEVEL_1]]) + { + color[0] *= 0.5; + color[1] *= 0.5; + color[2] *= 0.5; + } + */ + drawRank = uiForcePowersRank[findex]; + + UI_DrawForceStars(&rect, scale, color, textStyle, findex, drawRank, 0, NUM_FORCE_POWER_LEVELS - 1); + break; + case UI_EFFECTS: + break; + case UI_PLAYERMODEL: + // UI_DrawPlayerModel(&rect); + break; + case UI_CLANNAME: + UI_DrawClanName(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_CLANLOGO: + UI_DrawClanLogo(&rect, scale, color); + break; + case UI_CLANCINEMATIC: + UI_DrawClanCinematic(&rect, scale, color); + break; + case UI_PREVIEWCINEMATIC: + UI_DrawPreviewCinematic(&rect, scale, color); + break; + case UI_GAMETYPE: + UI_DrawGameType(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_NETGAMETYPE: + UI_DrawNetGameType(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_AUTOSWITCHLIST: + UI_DrawAutoSwitch(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_JOINGAMETYPE: + UI_DrawJoinGameType(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_MAPPREVIEW: + UI_DrawMapPreview(&rect, scale, color, qtrue); + break; + case UI_MAP_TIMETOBEAT: + break; + case UI_MAPCINEMATIC: + UI_DrawMapCinematic(&rect, scale, color, qfalse); + break; + case UI_STARTMAPCINEMATIC: + UI_DrawMapCinematic(&rect, scale, color, qtrue); + break; + case UI_SKILL: + UI_DrawSkill(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_TOTALFORCESTARS: + // UI_DrawTotalForceStars(&rect, scale, color, textStyle); + break; + case UI_BLUETEAMNAME: + UI_DrawTeamName(&rect, scale, color, qtrue, textStyle, iMenuFont); + break; + case UI_REDTEAMNAME: + UI_DrawTeamName(&rect, scale, color, qfalse, textStyle, iMenuFont); + break; + case UI_BLUETEAM1: + case UI_BLUETEAM2: + case UI_BLUETEAM3: + case UI_BLUETEAM4: + case UI_BLUETEAM5: + case UI_BLUETEAM6: + case UI_BLUETEAM7: + case UI_BLUETEAM8: + if (ownerDraw <= UI_BLUETEAM5) { + iUse = ownerDraw - UI_BLUETEAM1 + 1; + } else { + iUse = ownerDraw - 274; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines } -*/ drawRank = uiForcePowersRank[findex]; - - UI_DrawForceStars(&rect, scale, color, textStyle, findex, drawRank, 0, NUM_FORCE_POWER_LEVELS-1); - break; - case UI_EFFECTS: - break; - case UI_PLAYERMODEL: - //UI_DrawPlayerModel(&rect); - break; - case UI_CLANNAME: - UI_DrawClanName(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_CLANLOGO: - UI_DrawClanLogo(&rect, scale, color); - break; - case UI_CLANCINEMATIC: - UI_DrawClanCinematic(&rect, scale, color); - break; - case UI_PREVIEWCINEMATIC: - UI_DrawPreviewCinematic(&rect, scale, color); - break; - case UI_GAMETYPE: - UI_DrawGameType(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_NETGAMETYPE: - UI_DrawNetGameType(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_AUTOSWITCHLIST: - UI_DrawAutoSwitch(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_JOINGAMETYPE: - UI_DrawJoinGameType(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_MAPPREVIEW: - UI_DrawMapPreview(&rect, scale, color, qtrue); - break; - case UI_MAP_TIMETOBEAT: - break; - case UI_MAPCINEMATIC: - UI_DrawMapCinematic(&rect, scale, color, qfalse); - break; - case UI_STARTMAPCINEMATIC: - UI_DrawMapCinematic(&rect, scale, color, qtrue); - break; - case UI_SKILL: - UI_DrawSkill(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_TOTALFORCESTARS: -// UI_DrawTotalForceStars(&rect, scale, color, textStyle); - break; - case UI_BLUETEAMNAME: - UI_DrawTeamName(&rect, scale, color, qtrue, textStyle, iMenuFont); - break; - case UI_REDTEAMNAME: - UI_DrawTeamName(&rect, scale, color, qfalse, textStyle, iMenuFont); - break; - case UI_BLUETEAM1: - case UI_BLUETEAM2: - case UI_BLUETEAM3: - case UI_BLUETEAM4: - case UI_BLUETEAM5: - case UI_BLUETEAM6: - case UI_BLUETEAM7: - case UI_BLUETEAM8: - if (ownerDraw <= UI_BLUETEAM5) - { - iUse = ownerDraw-UI_BLUETEAM1 + 1; - } - else - { - iUse = ownerDraw-274; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines - } - UI_DrawTeamMember(&rect, scale, color, qtrue, iUse, textStyle, iMenuFont); - break; - case UI_REDTEAM1: - case UI_REDTEAM2: - case UI_REDTEAM3: - case UI_REDTEAM4: - case UI_REDTEAM5: - case UI_REDTEAM6: - case UI_REDTEAM7: - case UI_REDTEAM8: - if (ownerDraw <= UI_REDTEAM5) - { - iUse = ownerDraw-UI_REDTEAM1 + 1; - } - else - { - iUse = ownerDraw-277; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + UI_DrawTeamMember(&rect, scale, color, qtrue, iUse, textStyle, iMenuFont); + break; + case UI_REDTEAM1: + case UI_REDTEAM2: + case UI_REDTEAM3: + case UI_REDTEAM4: + case UI_REDTEAM5: + case UI_REDTEAM6: + case UI_REDTEAM7: + case UI_REDTEAM8: + if (ownerDraw <= UI_REDTEAM5) { + iUse = ownerDraw - UI_REDTEAM1 + 1; + } else { + iUse = ownerDraw - 277; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + } + UI_DrawTeamMember(&rect, scale, color, qfalse, iUse, textStyle, iMenuFont); + break; + case UI_NETSOURCE: + UI_DrawNetSource(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_NETMAPPREVIEW: + UI_DrawNetMapPreview(&rect, scale, color); + break; + case UI_NETMAPCINEMATIC: + UI_DrawNetMapCinematic(&rect, scale, color); + break; + case UI_NETFILTER: + UI_DrawNetFilter(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_TIER: + UI_DrawTier(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_OPPONENTMODEL: + // UI_DrawOpponent(&rect); + break; + case UI_TIERMAP1: + UI_DrawTierMap(&rect, 0); + break; + case UI_TIERMAP2: + UI_DrawTierMap(&rect, 1); + break; + case UI_TIERMAP3: + UI_DrawTierMap(&rect, 2); + break; + case UI_PLAYERLOGO: + UI_DrawPlayerLogo(&rect, color); + break; + case UI_PLAYERLOGO_METAL: + UI_DrawPlayerLogoMetal(&rect, color); + break; + case UI_PLAYERLOGO_NAME: + UI_DrawPlayerLogoName(&rect, color); + break; + case UI_OPPONENTLOGO: + UI_DrawOpponentLogo(&rect, color); + break; + case UI_OPPONENTLOGO_METAL: + UI_DrawOpponentLogoMetal(&rect, color); + break; + case UI_OPPONENTLOGO_NAME: + UI_DrawOpponentLogoName(&rect, color); + break; + case UI_TIER_MAPNAME: + UI_DrawTierMapName(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_TIER_GAMETYPE: + UI_DrawTierGameType(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_ALLMAPS_SELECTION: + UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qtrue, iMenuFont); + break; + case UI_MAPS_SELECTION: + UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qfalse, iMenuFont); + break; + case UI_OPPONENT_NAME: + UI_DrawOpponentName(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_BOTNAME: + UI_DrawBotName(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_BOTSKILL: + UI_DrawBotSkill(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_REDBLUE: + UI_DrawRedBlue(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_CROSSHAIR: + UI_DrawCrosshair(&rect, scale, color); + break; + case UI_SELECTEDPLAYER: + UI_DrawSelectedPlayer(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_SERVERREFRESHDATE: + UI_DrawServerRefreshDate(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_SERVERMOTD: + UI_DrawServerMOTD(&rect, scale, color, iMenuFont); + break; + case UI_GLINFO: + UI_DrawGLInfo(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_KEYBINDSTATUS: + UI_DrawKeyBindStatus(&rect, scale, color, textStyle, iMenuFont); + break; + case UI_VERSION: + UI_Version(&rect, scale, color, iMenuFont); + break; + default: + break; } - UI_DrawTeamMember(&rect, scale, color, qfalse, iUse, textStyle, iMenuFont); - break; - case UI_NETSOURCE: - UI_DrawNetSource(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_NETMAPPREVIEW: - UI_DrawNetMapPreview(&rect, scale, color); - break; - case UI_NETMAPCINEMATIC: - UI_DrawNetMapCinematic(&rect, scale, color); - break; - case UI_NETFILTER: - UI_DrawNetFilter(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_TIER: - UI_DrawTier(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_OPPONENTMODEL: - //UI_DrawOpponent(&rect); - break; - case UI_TIERMAP1: - UI_DrawTierMap(&rect, 0); - break; - case UI_TIERMAP2: - UI_DrawTierMap(&rect, 1); - break; - case UI_TIERMAP3: - UI_DrawTierMap(&rect, 2); - break; - case UI_PLAYERLOGO: - UI_DrawPlayerLogo(&rect, color); - break; - case UI_PLAYERLOGO_METAL: - UI_DrawPlayerLogoMetal(&rect, color); - break; - case UI_PLAYERLOGO_NAME: - UI_DrawPlayerLogoName(&rect, color); - break; - case UI_OPPONENTLOGO: - UI_DrawOpponentLogo(&rect, color); - break; - case UI_OPPONENTLOGO_METAL: - UI_DrawOpponentLogoMetal(&rect, color); - break; - case UI_OPPONENTLOGO_NAME: - UI_DrawOpponentLogoName(&rect, color); - break; - case UI_TIER_MAPNAME: - UI_DrawTierMapName(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_TIER_GAMETYPE: - UI_DrawTierGameType(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_ALLMAPS_SELECTION: - UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qtrue, iMenuFont); - break; - case UI_MAPS_SELECTION: - UI_DrawAllMapsSelection(&rect, scale, color, textStyle, qfalse, iMenuFont); - break; - case UI_OPPONENT_NAME: - UI_DrawOpponentName(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_BOTNAME: - UI_DrawBotName(&rect, scale, color, textStyle,iMenuFont); - break; - case UI_BOTSKILL: - UI_DrawBotSkill(&rect, scale, color, textStyle,iMenuFont); - break; - case UI_REDBLUE: - UI_DrawRedBlue(&rect, scale, color, textStyle,iMenuFont); - break; - case UI_CROSSHAIR: - UI_DrawCrosshair(&rect, scale, color); - break; - case UI_SELECTEDPLAYER: - UI_DrawSelectedPlayer(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_SERVERREFRESHDATE: - UI_DrawServerRefreshDate(&rect, scale, color, textStyle, iMenuFont); - break; - case UI_SERVERMOTD: - UI_DrawServerMOTD(&rect, scale, color, iMenuFont); - break; - case UI_GLINFO: - UI_DrawGLInfo(&rect,scale, color, textStyle, iMenuFont); - break; - case UI_KEYBINDSTATUS: - UI_DrawKeyBindStatus(&rect,scale, color, textStyle,iMenuFont); - break; - case UI_VERSION: - UI_Version(&rect, scale, color, iMenuFont); - break; - default: - break; - } } static qboolean UI_OwnerDrawVisible(int flags) { @@ -3261,16 +2993,14 @@ static qboolean UI_OwnerDrawVisible(int flags) { while (flags) { if (flags & UI_SHOW_FFA) { - if (trap->Cvar_VariableValue("g_gametype") != GT_FFA && - trap->Cvar_VariableValue("g_gametype") != GT_HOLOCRON && + if (trap->Cvar_VariableValue("g_gametype") != GT_FFA && trap->Cvar_VariableValue("g_gametype") != GT_HOLOCRON && trap->Cvar_VariableValue("g_gametype") != GT_JEDIMASTER) { vis = qfalse; } flags &= ~UI_SHOW_FFA; } if (flags & UI_SHOW_NOTFFA) { - if (trap->Cvar_VariableValue("g_gametype") == GT_FFA || - trap->Cvar_VariableValue("g_gametype") == GT_HOLOCRON || + if (trap->Cvar_VariableValue("g_gametype") == GT_FFA || trap->Cvar_VariableValue("g_gametype") == GT_HOLOCRON || trap->Cvar_VariableValue("g_gametype") != GT_JEDIMASTER) { vis = qfalse; } @@ -3314,25 +3044,25 @@ static qboolean UI_OwnerDrawVisible(int flags) { flags &= ~UI_SHOW_NOTFAVORITESERVERS; } if (flags & UI_SHOW_ANYTEAMGAME) { - if (uiInfo.gameTypes[ui_gametype.integer].gtEnum <= GT_TEAM ) { + if (uiInfo.gameTypes[ui_gametype.integer].gtEnum <= GT_TEAM) { vis = qfalse; } flags &= ~UI_SHOW_ANYTEAMGAME; } if (flags & UI_SHOW_ANYNONTEAMGAME) { - if (uiInfo.gameTypes[ui_gametype.integer].gtEnum > GT_TEAM ) { + if (uiInfo.gameTypes[ui_gametype.integer].gtEnum > GT_TEAM) { vis = qfalse; } flags &= ~UI_SHOW_ANYNONTEAMGAME; } if (flags & UI_SHOW_NETANYTEAMGAME) { - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum <= GT_TEAM ) { + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum <= GT_TEAM) { vis = qfalse; } flags &= ~UI_SHOW_NETANYTEAMGAME; } if (flags & UI_SHOW_NETANYNONTEAMGAME) { - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum > GT_TEAM ) { + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum > GT_TEAM) { vis = qfalse; } flags &= ~UI_SHOW_NETANYNONTEAMGAME; @@ -3346,7 +3076,7 @@ static qboolean UI_OwnerDrawVisible(int flags) { static qboolean UI_Handicap_HandleKey(int flags, float *special, int key) { if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { int h; - h = Com_Clamp( 5, 100, trap->Cvar_VariableValue("handicap") ); + h = Com_Clamp(5, 100, trap->Cvar_VariableValue("handicap")); if (key == A_MOUSE2) { h -= 5; } else { @@ -3357,331 +3087,233 @@ static qboolean UI_Handicap_HandleKey(int flags, float *special, int key) { } else if (h < 5) { h = 100; } - trap->Cvar_Set( "handicap", va( "%i", h) ); + trap->Cvar_Set("handicap", va("%i", h)); return qtrue; } return qfalse; } -extern void Item_RunScript(itemDef_t *item, const char *s); //from ui_shared; +extern void Item_RunScript(itemDef_t *item, const char *s); // from ui_shared; // For hot keys on the chat main menu. -static qboolean UI_Chat_Main_HandleKey(int key) -{ +static qboolean UI_Chat_Main_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "attack"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "defend"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "request"); - } - else if ((key == A_4) || ( key == A_STRING)) - { + } else if ((key == A_4) || (key == A_STRING)) { item = Menu_FindItemByName(menu, "reply"); - } - else if ((key == A_5) || ( key == A_PERCENT)) - { + } else if ((key == A_5) || (key == A_PERCENT)) { item = Menu_FindItemByName(menu, "spot"); - } - else if ((key == A_6) || ( key == A_CARET)) - { + } else if ((key == A_6) || (key == A_CARET)) { item = Menu_FindItemByName(menu, "tactics"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Attack_HandleKey(int key) -{ +static qboolean UI_Chat_Attack_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "att_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "att_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "att_03"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Defend_HandleKey(int key) -{ +static qboolean UI_Chat_Defend_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "def_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "def_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "def_03"); - } - else if ((key == A_4) || ( key == A_STRING)) - { + } else if ((key == A_4) || (key == A_STRING)) { item = Menu_FindItemByName(menu, "def_04"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Request_HandleKey(int key) -{ +static qboolean UI_Chat_Request_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "req_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "req_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "req_03"); - } - else if ((key == A_4) || ( key == A_STRING)) - { + } else if ((key == A_4) || (key == A_STRING)) { item = Menu_FindItemByName(menu, "req_04"); - } - else if ((key == A_5) || ( key == A_PERCENT)) - { + } else if ((key == A_5) || (key == A_PERCENT)) { item = Menu_FindItemByName(menu, "req_05"); - } - else if ((key == A_6) || ( key == A_CARET)) - { + } else if ((key == A_6) || (key == A_CARET)) { item = Menu_FindItemByName(menu, "req_06"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Reply_HandleKey(int key) -{ +static qboolean UI_Chat_Reply_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "rep_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "rep_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "rep_03"); - } - else if ((key == A_4) || ( key == A_STRING)) - { + } else if ((key == A_4) || (key == A_STRING)) { item = Menu_FindItemByName(menu, "rep_04"); - } - else if ((key == A_5) || ( key == A_PERCENT)) - { + } else if ((key == A_5) || (key == A_PERCENT)) { item = Menu_FindItemByName(menu, "rep_05"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Spot_HandleKey(int key) -{ +static qboolean UI_Chat_Spot_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "spot_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "spot_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "spot_03"); - } - else if ((key == A_4) || ( key == A_STRING)) - { - item = Menu_FindItemByName(menu, "spot_04"); - } - else if ((key == A_5) || (key == A_PERCENT)) - { + } else if ((key == A_4) || (key == A_STRING)) { + item = Menu_FindItemByName(menu, "spot_04"); + } else if ((key == A_5) || (key == A_PERCENT)) { item = Menu_FindItemByName(menu, "spot_05"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); } // For hot keys on the chat main menu. -static qboolean UI_Chat_Tactical_HandleKey(int key) -{ +static qboolean UI_Chat_Tactical_HandleKey(int key) { menuDef_t *menu; itemDef_t *item; menu = Menu_GetFocused(); - if (!menu) - { + if (!menu) { return (qfalse); } - if ((key == A_1) || ( key == A_PLING)) - { + if ((key == A_1) || (key == A_PLING)) { item = Menu_FindItemByName(menu, "tac_01"); - } - else if ((key == A_2) || ( key == A_AT)) - { + } else if ((key == A_2) || (key == A_AT)) { item = Menu_FindItemByName(menu, "tac_02"); - } - else if ((key == A_3) || ( key == A_HASH)) - { + } else if ((key == A_3) || (key == A_HASH)) { item = Menu_FindItemByName(menu, "tac_03"); - } - else if ((key == A_4) || ( key == A_STRING)) - { + } else if ((key == A_4) || (key == A_STRING)) { item = Menu_FindItemByName(menu, "tac_04"); - } - else if ((key == A_5) || ( key == A_PERCENT)) - { + } else if ((key == A_5) || (key == A_PERCENT)) { item = Menu_FindItemByName(menu, "tac_05"); - } - else if ((key == A_6) || ( key == A_CARET)) - { + } else if ((key == A_6) || (key == A_CARET)) { item = Menu_FindItemByName(menu, "tac_06"); - } - else - { + } else { return (qfalse); } - if (item) - { - Item_RunScript(item, item->action); + if (item) { + Item_RunScript(item, item->action); } return (qtrue); @@ -3713,7 +3345,7 @@ static qboolean UI_GameType_HandleKey(int flags, float *special, int key, qboole trap->Cvar_Update(&ui_gametype); UI_SetCapFragLimits(qtrue); if (resetMap && oldCount != UI_MapCountByGameType(qtrue)) { - trap->Cvar_Set( "ui_currentMap", "0"); + trap->Cvar_Set("ui_currentMap", "0"); trap->Cvar_Update(&ui_currentMap); Menu_SetFeederSelection(NULL, FEEDER_MAPS, 0, NULL); } @@ -3723,71 +3355,56 @@ static qboolean UI_GameType_HandleKey(int flags, float *special, int key, qboole } // If we're in the solo menu, don't let them see siege maps. -static qboolean UI_InSoloMenu( void ) -{ +static qboolean UI_InSoloMenu(void) { menuDef_t *menu; itemDef_t *item; char *name = "solo_gametypefield"; - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { + if (!menu) { return (qfalse); } item = Menu_FindItemByName(menu, name); - if (item) - { + if (item) { return qtrue; } return (qfalse); } -static qboolean UI_NetGameType_HandleKey(int flags, float *special, int key) -{ - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) - { +static qboolean UI_NetGameType_HandleKey(int flags, float *special, int key) { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { int value = ui_netGametype.integer; - if (key == A_MOUSE2) - { + if (key == A_MOUSE2) { value--; - if (UI_InSoloMenu()) - { - if (uiInfo.gameTypes[value].gtEnum == GT_SIEGE) - { + if (UI_InSoloMenu()) { + if (uiInfo.gameTypes[value].gtEnum == GT_SIEGE) { value--; } } - } - else - { + } else { value++; - if (UI_InSoloMenu()) - { - if (uiInfo.gameTypes[value].gtEnum == GT_SIEGE) - { + if (UI_InSoloMenu()) { + if (uiInfo.gameTypes[value].gtEnum == GT_SIEGE) { value++; } } } - if (value < 0) - { + if (value < 0) { value = uiInfo.numGameTypes - 1; - } - else if (value >= uiInfo.numGameTypes) - { + } else if (value >= uiInfo.numGameTypes) { value = 0; } - trap->Cvar_Set( "ui_netGametype", va("%d", value)); + trap->Cvar_Set("ui_netGametype", va("%d", value)); trap->Cvar_Update(&ui_netGametype); - trap->Cvar_Set( "ui_actualNetGametype", va("%d", uiInfo.gameTypes[ui_netGametype.integer].gtEnum)); + trap->Cvar_Set("ui_actualNetGametype", va("%d", uiInfo.gameTypes[ui_netGametype.integer].gtEnum)); trap->Cvar_Update(&ui_actualNetGametype); - trap->Cvar_Set( "ui_currentNetMap", "0"); + trap->Cvar_Set("ui_currentNetMap", "0"); trap->Cvar_Update(&ui_currentNetMap); UI_MapCountByGameType(qfalse); Menu_SetFeederSelection(NULL, FEEDER_ALLMAPS, 0, NULL); @@ -3806,16 +3423,13 @@ static qboolean UI_AutoSwitch_HandleKey(int flags, float *special, int key) { switchVal++; } - if (switchVal < 0) - { + if (switchVal < 0) { switchVal = 2; - } - else if (switchVal >= 3) - { + } else if (switchVal >= 3) { switchVal = 0; } - trap->Cvar_Set( "cg_autoswitch", va("%i", switchVal)); + trap->Cvar_Set("cg_autoswitch", va("%i", switchVal)); return qtrue; } return qfalse; @@ -3837,7 +3451,7 @@ static qboolean UI_JoinGameType_HandleKey(int flags, float *special, int key) { value = 0; } - trap->Cvar_Set( "ui_joinGametype", va("%d", value)); + trap->Cvar_Set("ui_joinGametype", va("%d", value)); trap->Cvar_Update(&ui_joinGametype); UI_BuildServerDisplayList(qtrue); return qtrue; @@ -3847,7 +3461,7 @@ static qboolean UI_JoinGameType_HandleKey(int flags, float *special, int key) { static qboolean UI_Skill_HandleKey(int flags, float *special, int key) { if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { - int i = trap->Cvar_VariableValue( "g_spSkill" ); + int i = trap->Cvar_VariableValue("g_spSkill"); if (key == A_MOUSE2) { i--; @@ -3885,7 +3499,7 @@ static qboolean UI_TeamName_HandleKey(int flags, float *special, int key, qboole i = uiInfo.teamCount - 1; } - trap->Cvar_Set( (blue) ? "ui_blueTeam" : "ui_redTeam", uiInfo.teamList[i].teamName); + trap->Cvar_Set((blue) ? "ui_blueTeam" : "ui_redTeam", uiInfo.teamList[i].teamName); return qtrue; } @@ -3899,23 +3513,20 @@ static qboolean UI_TeamMember_HandleKey(int flags, float *special, int key, qboo // 2..NumCharacters - Bot char *cvar = va(blue ? "ui_blueteam%i" : "ui_redteam%i", num); int value = trap->Cvar_VariableValue(cvar); - int maxcl = trap->Cvar_VariableValue( "sv_maxClients" ); + int maxcl = trap->Cvar_VariableValue("sv_maxClients"); int numval = num; numval *= 2; - if (blue) - { + if (blue) { numval -= 1; } - if (numval > maxcl) - { + if (numval > maxcl) { return qfalse; } - if (value < 1) - { + if (value < 1) { value = 1; } @@ -3955,15 +3566,13 @@ static qboolean UI_NetSource_HandleKey(int flags, float *special, int key) { value++; } - if(value >= UIAS_GLOBAL1 && value <= UIAS_GLOBAL5) - { + if (value >= UIAS_GLOBAL1 && value <= UIAS_GLOBAL5) { char masterstr[2], cvarname[sizeof("sv_master1")]; - while(value >= UIAS_GLOBAL1 && value <= UIAS_GLOBAL5) - { + while (value >= UIAS_GLOBAL1 && value <= UIAS_GLOBAL5) { Com_sprintf(cvarname, sizeof(cvarname), "sv_master%d", value); trap->Cvar_VariableStringBuffer(cvarname, masterstr, sizeof(masterstr)); - if(*masterstr) + if (*masterstr) break; if (key == A_MOUSE2) { @@ -3980,7 +3589,7 @@ static qboolean UI_NetSource_HandleKey(int flags, float *special, int key) { value = numNetSources - 1; } - trap->Cvar_Set( "ui_netSource", va("%d", value)); + trap->Cvar_Set("ui_netSource", va("%d", value)); trap->Cvar_Update(&ui_netSource); UI_BuildServerDisplayList(qtrue); @@ -4008,7 +3617,7 @@ static qboolean UI_NetFilter_HandleKey(int flags, float *special, int key) { value = uiInfo.modCount; } - trap->Cvar_Set( "ui_serverFilterType", va("%d", value)); + trap->Cvar_Set("ui_serverFilterType", va("%d", value)); trap->Cvar_Update(&ui_serverFilterType); UI_BuildServerDisplayList(qtrue); @@ -4031,7 +3640,7 @@ static qboolean UI_OpponentName_HandleKey(int flags, float *special, int key) { static qboolean UI_BotName_HandleKey(int flags, float *special, int key) { if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER || key == A_KP_ENTER) { -// int game = trap->Cvar_VariableValue("g_gametype"); + // int game = trap->Cvar_VariableValue("g_gametype"); int value = uiInfo.botIndex; if (key == A_MOUSE2) { @@ -4049,10 +3658,10 @@ static qboolean UI_BotName_HandleKey(int flags, float *special, int key) { } } else { */ - if (value >= UI_GetNumBots()/* + 2*/) { + if (value >= UI_GetNumBots() /* + 2*/) { value = 0; } else if (value < 0) { - value = UI_GetNumBots()/* + 2*/ - 1; + value = UI_GetNumBots() /* + 2*/ - 1; } //} uiInfo.botIndex = value; @@ -4071,7 +3680,7 @@ static qboolean UI_BotSkill_HandleKey(int flags, float *special, int key) { if (uiInfo.skillIndex >= numSkillLevels) { uiInfo.skillIndex = 0; } else if (uiInfo.skillIndex < 0) { - uiInfo.skillIndex = numSkillLevels-1; + uiInfo.skillIndex = numSkillLevels - 1; } return qtrue; } @@ -4128,11 +3737,11 @@ static qboolean UI_SelectedPlayer_HandleKey(int flags, float *special, int key) } if (selected == uiInfo.myTeamCount) { - trap->Cvar_Set( "cg_selectedPlayerName", "Everyone"); + trap->Cvar_Set("cg_selectedPlayerName", "Everyone"); } else { - trap->Cvar_Set( "cg_selectedPlayerName", uiInfo.teamNames[selected]); + trap->Cvar_Set("cg_selectedPlayerName", uiInfo.teamNames[selected]); } - trap->Cvar_Set( "cg_selectedPlayer", va("%d", selected)); + trap->Cvar_Set("cg_selectedPlayer", va("%d", selected)); } return qfalse; } @@ -4163,23 +3772,23 @@ static qboolean UI_VoiceChat_HandleKey(int flags, float *special, int key) static qboolean UI_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, int key) { int findex, iUse = 0; - switch (ownerDraw) { - case UI_HANDICAP: - return UI_Handicap_HandleKey(flags, special, key); - break; - case UI_SKIN_COLOR: - return UI_SkinColor_HandleKey(flags, special, key, uiSkinColor, TEAM_FREE, TEAM_BLUE, ownerDraw); - break; - case UI_FORCE_SIDE: - return UI_ForceSide_HandleKey(flags, special, key, uiForceSide, 1, 2, ownerDraw); - break; - case UI_JEDI_NONJEDI: - return UI_JediNonJedi_HandleKey(flags, special, key, uiJediNonJedi, 0, 1, ownerDraw); - break; + switch (ownerDraw) { + case UI_HANDICAP: + return UI_Handicap_HandleKey(flags, special, key); + break; + case UI_SKIN_COLOR: + return UI_SkinColor_HandleKey(flags, special, key, uiSkinColor, TEAM_FREE, TEAM_BLUE, ownerDraw); + break; + case UI_FORCE_SIDE: + return UI_ForceSide_HandleKey(flags, special, key, uiForceSide, 1, 2, ownerDraw); + break; + case UI_JEDI_NONJEDI: + return UI_JediNonJedi_HandleKey(flags, special, key, uiJediNonJedi, 0, 1, ownerDraw); + break; case UI_FORCE_MASTERY_SET: - return UI_ForceMaxRank_HandleKey(flags, special, key, uiForceRank, 1, MAX_FORCE_RANK, ownerDraw); - break; - case UI_FORCE_RANK: + return UI_ForceMaxRank_HandleKey(flags, special, key, uiForceRank, 1, MAX_FORCE_RANK, ownerDraw); + break; + case UI_FORCE_RANK: break; case UI_CHAT_MAIN: return UI_Chat_Main_HandleKey(key); @@ -4220,115 +3829,107 @@ static qboolean UI_OwnerDrawHandleKey(int ownerDraw, int flags, float *special, case UI_FORCE_RANK_SABERATTACK: case UI_FORCE_RANK_SABERDEFEND: case UI_FORCE_RANK_SABERTHROW: - findex = (ownerDraw - UI_FORCE_RANK)-1; - //this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index - return UI_ForcePowerRank_HandleKey(flags, special, key, uiForcePowersRank[findex], 0, NUM_FORCE_POWER_LEVELS-1, ownerDraw); - break; - case UI_EFFECTS: - break; - case UI_GAMETYPE: - return UI_GameType_HandleKey(flags, special, key, qtrue); - break; - case UI_NETGAMETYPE: - return UI_NetGameType_HandleKey(flags, special, key); - break; - case UI_AUTOSWITCHLIST: - return UI_AutoSwitch_HandleKey(flags, special, key); - break; - case UI_JOINGAMETYPE: - return UI_JoinGameType_HandleKey(flags, special, key); - break; - case UI_SKILL: - return UI_Skill_HandleKey(flags, special, key); - break; - case UI_BLUETEAMNAME: - return UI_TeamName_HandleKey(flags, special, key, qtrue); - break; - case UI_REDTEAMNAME: - return UI_TeamName_HandleKey(flags, special, key, qfalse); - break; - case UI_BLUETEAM1: - case UI_BLUETEAM2: - case UI_BLUETEAM3: - case UI_BLUETEAM4: - case UI_BLUETEAM5: - case UI_BLUETEAM6: - case UI_BLUETEAM7: - case UI_BLUETEAM8: - if (ownerDraw <= UI_BLUETEAM5) - { - iUse = ownerDraw-UI_BLUETEAM1 + 1; - } - else - { - iUse = ownerDraw-274; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines - } - - UI_TeamMember_HandleKey(flags, special, key, qtrue, iUse); - break; - case UI_REDTEAM1: - case UI_REDTEAM2: - case UI_REDTEAM3: - case UI_REDTEAM4: - case UI_REDTEAM5: - case UI_REDTEAM6: - case UI_REDTEAM7: - case UI_REDTEAM8: - if (ownerDraw <= UI_REDTEAM5) - { - iUse = ownerDraw-UI_REDTEAM1 + 1; - } - else - { - iUse = ownerDraw-277; //unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines - } - UI_TeamMember_HandleKey(flags, special, key, qfalse, iUse); - break; - case UI_NETSOURCE: - UI_NetSource_HandleKey(flags, special, key); - break; - case UI_NETFILTER: - UI_NetFilter_HandleKey(flags, special, key); - break; - case UI_OPPONENT_NAME: - UI_OpponentName_HandleKey(flags, special, key); - break; - case UI_BOTNAME: - return UI_BotName_HandleKey(flags, special, key); - break; - case UI_BOTSKILL: - return UI_BotSkill_HandleKey(flags, special, key); - break; - case UI_REDBLUE: - UI_RedBlue_HandleKey(flags, special, key); - break; - case UI_CROSSHAIR: - UI_Crosshair_HandleKey(flags, special, key); - break; - case UI_SELECTEDPLAYER: - UI_SelectedPlayer_HandleKey(flags, special, key); - break; + findex = (ownerDraw - UI_FORCE_RANK) - 1; + // this will give us the index as long as UI_FORCE_RANK is always one below the first force rank index + return UI_ForcePowerRank_HandleKey(flags, special, key, uiForcePowersRank[findex], 0, NUM_FORCE_POWER_LEVELS - 1, ownerDraw); + break; + case UI_EFFECTS: + break; + case UI_GAMETYPE: + return UI_GameType_HandleKey(flags, special, key, qtrue); + break; + case UI_NETGAMETYPE: + return UI_NetGameType_HandleKey(flags, special, key); + break; + case UI_AUTOSWITCHLIST: + return UI_AutoSwitch_HandleKey(flags, special, key); + break; + case UI_JOINGAMETYPE: + return UI_JoinGameType_HandleKey(flags, special, key); + break; + case UI_SKILL: + return UI_Skill_HandleKey(flags, special, key); + break; + case UI_BLUETEAMNAME: + return UI_TeamName_HandleKey(flags, special, key, qtrue); + break; + case UI_REDTEAMNAME: + return UI_TeamName_HandleKey(flags, special, key, qfalse); + break; + case UI_BLUETEAM1: + case UI_BLUETEAM2: + case UI_BLUETEAM3: + case UI_BLUETEAM4: + case UI_BLUETEAM5: + case UI_BLUETEAM6: + case UI_BLUETEAM7: + case UI_BLUETEAM8: + if (ownerDraw <= UI_BLUETEAM5) { + iUse = ownerDraw - UI_BLUETEAM1 + 1; + } else { + iUse = ownerDraw - 274; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + } + + UI_TeamMember_HandleKey(flags, special, key, qtrue, iUse); + break; + case UI_REDTEAM1: + case UI_REDTEAM2: + case UI_REDTEAM3: + case UI_REDTEAM4: + case UI_REDTEAM5: + case UI_REDTEAM6: + case UI_REDTEAM7: + case UI_REDTEAM8: + if (ownerDraw <= UI_REDTEAM5) { + iUse = ownerDraw - UI_REDTEAM1 + 1; + } else { + iUse = ownerDraw - 277; // unpleasent hack because I don't want to move up all the UI_BLAHTEAM# defines + } + UI_TeamMember_HandleKey(flags, special, key, qfalse, iUse); + break; + case UI_NETSOURCE: + UI_NetSource_HandleKey(flags, special, key); + break; + case UI_NETFILTER: + UI_NetFilter_HandleKey(flags, special, key); + break; + case UI_OPPONENT_NAME: + UI_OpponentName_HandleKey(flags, special, key); + break; + case UI_BOTNAME: + return UI_BotName_HandleKey(flags, special, key); + break; + case UI_BOTSKILL: + return UI_BotSkill_HandleKey(flags, special, key); + break; + case UI_REDBLUE: + UI_RedBlue_HandleKey(flags, special, key); + break; + case UI_CROSSHAIR: + UI_Crosshair_HandleKey(flags, special, key); + break; + case UI_SELECTEDPLAYER: + UI_SelectedPlayer_HandleKey(flags, special, key); + break; // case UI_VOICECHAT: // UI_VoiceChat_HandleKey(flags, special, key); // break; - default: - break; - } + default: + break; + } - return qfalse; + return qfalse; } -static float UI_GetValue(int ownerDraw) { - return 0; -} +static float UI_GetValue(int ownerDraw) { return 0; } /* ================= UI_ServersQsortCompare ================= */ -static int QDECL UI_ServersQsortCompare( const void *arg1, const void *arg2 ) { - return trap->LAN_CompareServers( UI_SourceForLAN(), uiInfo.serverStatus.sortKey, uiInfo.serverStatus.sortDir, *(int*)arg1, *(int*)arg2); +static int QDECL UI_ServersQsortCompare(const void *arg1, const void *arg2) { + return trap->LAN_CompareServers(UI_SourceForLAN(), uiInfo.serverStatus.sortKey, uiInfo.serverStatus.sortDir, *(int *)arg1, *(int *)arg2); } /* @@ -4337,14 +3938,14 @@ UI_ServersSort ================= */ void UI_ServersSort(int column, qboolean force) { - if ( !force ) { - if ( uiInfo.serverStatus.sortKey == column ) { + if (!force) { + if (uiInfo.serverStatus.sortKey == column) { return; } } uiInfo.serverStatus.sortKey = column; - qsort( &uiInfo.serverStatus.displayServers[0], uiInfo.serverStatus.numDisplayServers, sizeof(int), UI_ServersQsortCompare); + qsort(&uiInfo.serverStatus.displayServers[0], uiInfo.serverStatus.numDisplayServers, sizeof(int), UI_ServersQsortCompare); } #define MODSBUFSIZE (MAX_MODS * MAX_QPATH) @@ -4355,31 +3956,30 @@ UI_LoadMods =============== */ static void UI_LoadMods() { - int numdirs; - char dirlist[MODSBUFSIZE]; - char *dirptr; - char *descptr; - int i; - int dirlen; - char version[MAX_CVAR_VALUE_STRING] = {0}; + int numdirs; + char dirlist[MODSBUFSIZE]; + char *dirptr; + char *descptr; + int i; + int dirlen; + char version[MAX_CVAR_VALUE_STRING] = {0}; trap->SE_GetStringTextString("MENUS_ALL", sAll, sizeof(sAll)); // To still display base game with old engine - Q_strncpyz( version, UI_Cvar_VariableString( "version" ), sizeof(version) ); - if ( strstr( version, "2003" ) ) { + Q_strncpyz(version, UI_Cvar_VariableString("version"), sizeof(version)); + if (strstr(version, "2003")) { trap->SE_GetStringTextString("MENUS_JEDI_ACADEMY", sJediAcademy, sizeof(sJediAcademy)); uiInfo.modList[0].modName = String_Alloc(""); uiInfo.modList[0].modDescr = String_Alloc(sJediAcademy); uiInfo.modCount = 1; - } - else + } else uiInfo.modCount = 0; - numdirs = trap->FS_GetFileList( "$modlist", "", dirlist, sizeof(dirlist) ); - dirptr = dirlist; - for( i = 0; i < numdirs; i++ ) { - dirlen = strlen( dirptr ) + 1; + numdirs = trap->FS_GetFileList("$modlist", "", dirlist, sizeof(dirlist)); + dirptr = dirlist; + for (i = 0; i < numdirs; i++) { + dirlen = strlen(dirptr) + 1; descptr = dirptr + dirlen; uiInfo.modList[uiInfo.modCount].modName = String_Alloc(dirptr); uiInfo.modList[uiInfo.modCount].modDescr = String_Alloc(descptr); @@ -4397,21 +3997,21 @@ UI_LoadMovies =============== */ static void UI_LoadMovies() { - char movielist[4096]; - char *moviename; - int i, len; + char movielist[4096]; + char *moviename; + int i, len; - uiInfo.movieCount = trap->FS_GetFileList( "video", "roq", movielist, 4096 ); + uiInfo.movieCount = trap->FS_GetFileList("video", "roq", movielist, 4096); if (uiInfo.movieCount) { if (uiInfo.movieCount > MAX_MOVIES) { uiInfo.movieCount = MAX_MOVIES; } moviename = movielist; - for ( i = 0; i < uiInfo.movieCount; i++ ) { - len = strlen( moviename ); + for (i = 0; i < uiInfo.movieCount; i++) { + len = strlen(moviename); if (!Q_stricmp(moviename + len - 4, ".roq")) { - moviename[len-4] = '\0'; + moviename[len - 4] = '\0'; } Q_strupr(moviename); uiInfo.movieList[i] = String_Alloc(moviename); @@ -4426,8 +4026,7 @@ UI_LoadDemos =============== */ #define MAX_DEMO_FOLDER_DEPTH (8) -typedef struct loadDemoContext_s -{ +typedef struct loadDemoContext_s { int depth; qboolean warned; char demoList[MAX_DEMOLIST]; @@ -4435,21 +4034,18 @@ typedef struct loadDemoContext_s char *dirListHead; } loadDemoContext_t; -static void UI_LoadDemosInDirectory( loadDemoContext_t *ctx, const char *directory ) -{ +static void UI_LoadDemosInDirectory(loadDemoContext_t *ctx, const char *directory) { char *demoname = NULL; char demoExt[32] = {0}; - int protocol = trap->Cvar_VariableValue( "com_protocol" ); - int protocolLegacy = trap->Cvar_VariableValue( "com_legacyprotocol" ); + int protocol = trap->Cvar_VariableValue("com_protocol"); + int protocolLegacy = trap->Cvar_VariableValue("com_legacyprotocol"); char *dirListEnd; int j; - if ( ctx->depth > MAX_DEMO_FOLDER_DEPTH ) - { - if ( !ctx->warned ) - { + if (ctx->depth > MAX_DEMO_FOLDER_DEPTH) { + if (!ctx->warned) { ctx->warned = qtrue; - Com_Printf( S_COLOR_YELLOW "WARNING: Maximum demo folder depth (%d) was reached.\n", MAX_DEMO_FOLDER_DEPTH ); + Com_Printf(S_COLOR_YELLOW "WARNING: Maximum demo folder depth (%d) was reached.\n", MAX_DEMO_FOLDER_DEPTH); } return; @@ -4457,101 +4053,91 @@ static void UI_LoadDemosInDirectory( loadDemoContext_t *ctx, const char *directo ctx->depth++; - if ( !protocol ) - protocol = trap->Cvar_VariableValue( "protocol" ); - if ( protocolLegacy == protocol ) + if (!protocol) + protocol = trap->Cvar_VariableValue("protocol"); + if (protocolLegacy == protocol) protocolLegacy = 0; - Com_sprintf( demoExt, sizeof( demoExt ), ".%s%d", DEMO_EXTENSION, protocol); + Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMO_EXTENSION, protocol); - uiInfo.demoCount += trap->FS_GetFileList( directory, demoExt, ctx->demoList, sizeof( ctx->demoList ) ); + uiInfo.demoCount += trap->FS_GetFileList(directory, demoExt, ctx->demoList, sizeof(ctx->demoList)); demoname = ctx->demoList; - for ( j = 0; j < 2; j++ ) - { - if ( uiInfo.demoCount > MAX_DEMOS ) + for (j = 0; j < 2; j++) { + if (uiInfo.demoCount > MAX_DEMOS) uiInfo.demoCount = MAX_DEMOS; - for( ; uiInfo.loadedDemos 0 && uiInfo.demoCount < MAX_DEMOS ) - { - Com_sprintf( demoExt, sizeof( demoExt ), ".%s%d", DEMO_EXTENSION, protocolLegacy ); - uiInfo.demoCount += trap->FS_GetFileList( directory, demoExt, ctx->demoList, sizeof( ctx->demoList ) ); + if (!j) { + if (protocolLegacy > 0 && uiInfo.demoCount < MAX_DEMOS) { + Com_sprintf(demoExt, sizeof(demoExt), ".%s%d", DEMO_EXTENSION, protocolLegacy); + uiInfo.demoCount += trap->FS_GetFileList(directory, demoExt, ctx->demoList, sizeof(ctx->demoList)); demoname = ctx->demoList; - } - else + } else break; } } - dirListEnd = ctx->directoryList + sizeof( ctx->directoryList ); - if ( ctx->dirListHead < dirListEnd ) - { + dirListEnd = ctx->directoryList + sizeof(ctx->directoryList); + if (ctx->dirListHead < dirListEnd) { int i; int dirListSpaceRemaining = dirListEnd - ctx->dirListHead; - int numFiles = trap->FS_GetFileList( directory, "/", ctx->dirListHead, dirListSpaceRemaining ); + int numFiles = trap->FS_GetFileList(directory, "/", ctx->dirListHead, dirListSpaceRemaining); char *dirList; char *childDirListBase; char *fileName; // Find end of this list so we have a base pointer for the child folders to use dirList = ctx->dirListHead; - for ( i = 0; i < numFiles; i++ ) - { - ctx->dirListHead += strlen( ctx->dirListHead ) + 1; + for (i = 0; i < numFiles; i++) { + ctx->dirListHead += strlen(ctx->dirListHead) + 1; } ctx->dirListHead++; // Iterate through child directories childDirListBase = ctx->dirListHead; fileName = dirList; - for ( i = 0; i < numFiles; i++ ) - { - size_t len = strlen( fileName ); + for (i = 0; i < numFiles; i++) { + size_t len = strlen(fileName); - if ( Q_stricmp( fileName, "." ) && Q_stricmp( fileName, ".." ) && len ) - UI_LoadDemosInDirectory( ctx, va( "%s/%s", directory, fileName ) ); + if (Q_stricmp(fileName, ".") && Q_stricmp(fileName, "..") && len) + UI_LoadDemosInDirectory(ctx, va("%s/%s", directory, fileName)); ctx->dirListHead = childDirListBase; - fileName += len+1; + fileName += len + 1; } - assert( (fileName + 1) == childDirListBase ); + assert((fileName + 1) == childDirListBase); } ctx->depth--; } -static void InitLoadDemoContext( loadDemoContext_t *ctx ) -{ +static void InitLoadDemoContext(loadDemoContext_t *ctx) { ctx->warned = qfalse; ctx->depth = 0; ctx->dirListHead = ctx->directoryList; } -static void UI_LoadDemos( void ) -{ +static void UI_LoadDemos(void) { loadDemoContext_t loadDemoContext; - InitLoadDemoContext( &loadDemoContext ); + InitLoadDemoContext(&loadDemoContext); uiInfo.demoCount = 0; uiInfo.loadedDemos = 0; - memset( uiInfo.demoList, 0, sizeof( uiInfo.demoList ) ); - UI_LoadDemosInDirectory( &loadDemoContext, DEMO_DIRECTORY ); + memset(uiInfo.demoList, 0, sizeof(uiInfo.demoList)); + UI_LoadDemosInDirectory(&loadDemoContext, DEMO_DIRECTORY); } static qboolean UI_SetNextMap(int actual, int index) { @@ -4570,7 +4156,7 @@ static void UI_StartSkirmish(qboolean next) { float skill; char buff[MAX_STRING_CHARS]; - temp = trap->Cvar_VariableValue( "g_gametype" ); + temp = trap->Cvar_VariableValue("g_gametype"); trap->Cvar_Set("ui_gameType", va("%i", temp)); if (next) { @@ -4587,9 +4173,9 @@ static void UI_StartSkirmish(qboolean next) { } g = uiInfo.gameTypes[ui_gametype.integer].gtEnum; - trap->Cvar_SetValue( "g_gametype", g ); - trap->Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", uiInfo.mapList[ui_currentMap.integer].mapLoadName) ); - skill = trap->Cvar_VariableValue( "g_spSkill" ); + trap->Cvar_SetValue("g_gametype", g); + trap->Cmd_ExecuteText(EXEC_APPEND, va("wait ; wait ; map %s\n", uiInfo.mapList[ui_currentMap.integer].mapLoadName)); + skill = trap->Cvar_VariableValue("g_spSkill"); trap->Cvar_Set("ui_scoreMap", uiInfo.mapList[ui_currentMap.integer].mapName); k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_opponentName")); @@ -4597,28 +4183,37 @@ static void UI_StartSkirmish(qboolean next) { trap->Cvar_Set("ui_singlePlayerActive", "1"); // set up sp overrides, will be replaced on postgame - temp = trap->Cvar_VariableValue( "capturelimit" ); trap->Cvar_Set("ui_saveCaptureLimit", va("%i", temp)); - temp = trap->Cvar_VariableValue( "fraglimit" ); trap->Cvar_Set("ui_saveFragLimit", va("%i", temp)); - temp = trap->Cvar_VariableValue( "duel_fraglimit" ); trap->Cvar_Set("ui_saveDuelLimit", va("%i", temp)); + temp = trap->Cvar_VariableValue("capturelimit"); + trap->Cvar_Set("ui_saveCaptureLimit", va("%i", temp)); + temp = trap->Cvar_VariableValue("fraglimit"); + trap->Cvar_Set("ui_saveFragLimit", va("%i", temp)); + temp = trap->Cvar_VariableValue("duel_fraglimit"); + trap->Cvar_Set("ui_saveDuelLimit", va("%i", temp)); UI_SetCapFragLimits(qfalse); - temp = trap->Cvar_VariableValue( "cg_drawTimer" ); trap->Cvar_Set("ui_drawTimer", va("%i", temp)); - temp = trap->Cvar_VariableValue( "g_doWarmup" ); trap->Cvar_Set("ui_doWarmup", va("%i", temp)); - temp = trap->Cvar_VariableValue( "g_friendlyFire" ); trap->Cvar_Set("ui_friendlyFire", va("%i", temp)); - temp = trap->Cvar_VariableValue( "sv_maxClients" ); trap->Cvar_Set("ui_maxClients", va("%i", temp)); - temp = trap->Cvar_VariableValue( "g_warmup" ); trap->Cvar_Set("ui_Warmup", va("%i", temp)); - temp = trap->Cvar_VariableValue( "sv_pure" ); trap->Cvar_Set("ui_pure", va("%i", temp)); + temp = trap->Cvar_VariableValue("cg_drawTimer"); + trap->Cvar_Set("ui_drawTimer", va("%i", temp)); + temp = trap->Cvar_VariableValue("g_doWarmup"); + trap->Cvar_Set("ui_doWarmup", va("%i", temp)); + temp = trap->Cvar_VariableValue("g_friendlyFire"); + trap->Cvar_Set("ui_friendlyFire", va("%i", temp)); + temp = trap->Cvar_VariableValue("sv_maxClients"); + trap->Cvar_Set("ui_maxClients", va("%i", temp)); + temp = trap->Cvar_VariableValue("g_warmup"); + trap->Cvar_Set("ui_Warmup", va("%i", temp)); + temp = trap->Cvar_VariableValue("sv_pure"); + trap->Cvar_Set("ui_pure", va("%i", temp)); trap->Cvar_Set("cg_cameraOrbit", "0"); -// trap->Cvar_Set("cg_thirdPerson", "0"); + // trap->Cvar_Set("cg_thirdPerson", "0"); trap->Cvar_Set("cg_drawTimer", "1"); trap->Cvar_Set("g_doWarmup", "1"); trap->Cvar_Set("g_warmup", "15"); trap->Cvar_Set("sv_pure", "0"); trap->Cvar_Set("g_friendlyFire", "0"); -// trap->Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName")); -// trap->Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName")); + // trap->Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName")); + // trap->Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName")); if (trap->Cvar_VariableValue("ui_recordSPDemo")) { Com_sprintf(buff, MAX_STRING_CHARS, "%s_%i", uiInfo.mapList[ui_currentMap.integer].mapLoadName, g); @@ -4630,184 +4225,179 @@ static void UI_StartSkirmish(qboolean next) { if (g == GT_DUEL || g == GT_POWERDUEL) { temp = uiInfo.mapList[ui_currentMap.integer].teamMembers * 2; trap->Cvar_Set("sv_maxClients", va("%d", temp)); - Com_sprintf( buff, sizeof(buff), "wait ; addbot %s %f "", %i \n", uiInfo.mapList[ui_currentMap.integer].opponentName, skill, delay); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + Com_sprintf(buff, sizeof(buff), + "wait ; addbot %s %f " + ", %i \n", + uiInfo.mapList[ui_currentMap.integer].opponentName, skill, delay); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); } else if (g == GT_HOLOCRON || g == GT_JEDIMASTER) { temp = uiInfo.mapList[ui_currentMap.integer].teamMembers * 2; trap->Cvar_Set("sv_maxClients", va("%d", temp)); - for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers; i++) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_HOLOCRON) ? "" : "Blue", delay, uiInfo.teamList[k].teamMembers[i]); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + for (i = 0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers; i++) { + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, + (g == GT_HOLOCRON) ? "" : "Blue", delay, uiInfo.teamList[k].teamMembers[i]); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); delay += 500; } k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); - for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers-1; i++) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_HOLOCRON) ? "" : "Red", delay, uiInfo.teamList[k].teamMembers[i]); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + for (i = 0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers - 1; i++) { + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, + (g == GT_HOLOCRON) ? "" : "Red", delay, uiInfo.teamList[k].teamMembers[i]); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); delay += 500; } } else { temp = uiInfo.mapList[ui_currentMap.integer].teamMembers * 2; trap->Cvar_Set("sv_maxClients", va("%d", temp)); - for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers; i++) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Blue", delay, uiInfo.teamList[k].teamMembers[i]); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + for (i = 0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers; i++) { + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Blue", + delay, uiInfo.teamList[k].teamMembers[i]); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); delay += 500; } k = UI_TeamIndexFromName(UI_Cvar_VariableString("ui_teamName")); - for (i =0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers-1; i++) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Red", delay, uiInfo.teamList[k].teamMembers[i]); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + for (i = 0; i < uiInfo.mapList[ui_currentMap.integer].teamMembers - 1; i++) { + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s %i %s\n", UI_AIFromName(uiInfo.teamList[k].teamMembers[i]), skill, (g == GT_FFA) ? "" : "Red", + delay, uiInfo.teamList[k].teamMembers[i]); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); delay += 500; } } - if (g >= GT_TEAM ) { - trap->Cmd_ExecuteText( EXEC_APPEND, "wait 5; team Red\n" ); + if (g >= GT_TEAM) { + trap->Cmd_ExecuteText(EXEC_APPEND, "wait 5; team Red\n"); } } static void UI_Update(const char *name) { - int val = trap->Cvar_VariableValue(name); + int val = trap->Cvar_VariableValue(name); - if (Q_stricmp(name, "s_khz") == 0) - { - trap->Cmd_ExecuteText( EXEC_APPEND, "snd_restart\n" ); + if (Q_stricmp(name, "s_khz") == 0) { + trap->Cmd_ExecuteText(EXEC_APPEND, "snd_restart\n"); return; } - if ( !Q_stricmp( name, "ui_SetName" ) ) { + if (!Q_stricmp(name, "ui_SetName")) { char buf[MAX_NETNAME] = {0}; - Q_strncpyz( buf, UI_Cvar_VariableString( "ui_Name" ), sizeof( buf ) ); - trap->Cvar_Set( "name", buf ); - } - else if (Q_stricmp(name, "ui_setRate") == 0) { + Q_strncpyz(buf, UI_Cvar_VariableString("ui_Name"), sizeof(buf)); + trap->Cvar_Set("name", buf); + } else if (Q_stricmp(name, "ui_setRate") == 0) { float rate = trap->Cvar_VariableValue("rate"); if (rate >= 5000) { trap->Cvar_Set("cl_maxpackets", "30"); trap->Cvar_Set("cl_packetdup", "1"); } else if (rate >= 4000) { trap->Cvar_Set("cl_maxpackets", "15"); - trap->Cvar_Set("cl_packetdup", "2"); // favor less prediction errors when there's packet loss + trap->Cvar_Set("cl_packetdup", "2"); // favor less prediction errors when there's packet loss } else { trap->Cvar_Set("cl_maxpackets", "15"); - trap->Cvar_Set("cl_packetdup", "1"); // favor lower bandwidth + trap->Cvar_Set("cl_packetdup", "1"); // favor lower bandwidth } - } - else if ( !Q_stricmp( name, "ui_GetName" ) ) { + } else if (!Q_stricmp(name, "ui_GetName")) { char buf[MAX_NETNAME] = {0}; - Q_strncpyz( buf, UI_Cvar_VariableString( "name" ), sizeof( buf ) ); - trap->Cvar_Set( "ui_Name", buf ); - } - else if (Q_stricmp(name, "ui_r_colorbits") == 0) - { - switch (val) - { - case 0: - trap->Cvar_SetValue( "ui_r_depthbits", 0 ); - break; + Q_strncpyz(buf, UI_Cvar_VariableString("name"), sizeof(buf)); + trap->Cvar_Set("ui_Name", buf); + } else if (Q_stricmp(name, "ui_r_colorbits") == 0) { + switch (val) { + case 0: + trap->Cvar_SetValue("ui_r_depthbits", 0); + break; - case 16: - trap->Cvar_SetValue( "ui_r_depthbits", 16 ); - break; + case 16: + trap->Cvar_SetValue("ui_r_depthbits", 16); + break; - case 32: - trap->Cvar_SetValue( "ui_r_depthbits", 24 ); - break; + case 32: + trap->Cvar_SetValue("ui_r_depthbits", 24); + break; } - } - else if (Q_stricmp(name, "ui_r_lodbias") == 0) - { - switch (val) - { - case 0: - trap->Cvar_SetValue( "ui_r_subdivisions", 4 ); - break; - case 1: - trap->Cvar_SetValue( "ui_r_subdivisions", 12 ); - break; + } else if (Q_stricmp(name, "ui_r_lodbias") == 0) { + switch (val) { + case 0: + trap->Cvar_SetValue("ui_r_subdivisions", 4); + break; + case 1: + trap->Cvar_SetValue("ui_r_subdivisions", 12); + break; - case 2: - trap->Cvar_SetValue( "ui_r_subdivisions", 20 ); - break; + case 2: + trap->Cvar_SetValue("ui_r_subdivisions", 20); + break; } - } - else if (Q_stricmp(name, "ui_r_glCustom") == 0) - { - switch (val) - { - case 0: // high quality - - trap->Cvar_SetValue( "ui_r_fullScreen", 1 ); - trap->Cvar_SetValue( "ui_r_subdivisions", 4 ); - trap->Cvar_SetValue( "ui_r_lodbias", 0 ); - trap->Cvar_SetValue( "ui_r_colorbits", 32 ); - trap->Cvar_SetValue( "ui_r_depthbits", 24 ); - trap->Cvar_SetValue( "ui_r_picmip", 0 ); - trap->Cvar_SetValue( "ui_r_mode", 4 ); - trap->Cvar_SetValue( "ui_r_texturebits", 32 ); - trap->Cvar_SetValue( "ui_r_fastSky", 0 ); - trap->Cvar_SetValue( "ui_r_inGameVideo", 1 ); - // trap->Cvar_SetValue( "ui_cg_shadows", 2 );//stencil - trap->Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" ); + } else if (Q_stricmp(name, "ui_r_glCustom") == 0) { + switch (val) { + case 0: // high quality + + trap->Cvar_SetValue("ui_r_fullScreen", 1); + trap->Cvar_SetValue("ui_r_subdivisions", 4); + trap->Cvar_SetValue("ui_r_lodbias", 0); + trap->Cvar_SetValue("ui_r_colorbits", 32); + trap->Cvar_SetValue("ui_r_depthbits", 24); + trap->Cvar_SetValue("ui_r_picmip", 0); + trap->Cvar_SetValue("ui_r_mode", 4); + trap->Cvar_SetValue("ui_r_texturebits", 32); + trap->Cvar_SetValue("ui_r_fastSky", 0); + trap->Cvar_SetValue("ui_r_inGameVideo", 1); + // trap->Cvar_SetValue( "ui_cg_shadows", 2 );//stencil + trap->Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR"); break; case 1: // normal - trap->Cvar_SetValue( "ui_r_fullScreen", 1 ); - trap->Cvar_SetValue( "ui_r_subdivisions", 4 ); - trap->Cvar_SetValue( "ui_r_lodbias", 0 ); - trap->Cvar_SetValue( "ui_r_colorbits", 0 ); - trap->Cvar_SetValue( "ui_r_depthbits", 24 ); - trap->Cvar_SetValue( "ui_r_picmip", 1 ); - trap->Cvar_SetValue( "ui_r_mode", 3 ); - trap->Cvar_SetValue( "ui_r_texturebits", 0 ); - trap->Cvar_SetValue( "ui_r_fastSky", 0 ); - trap->Cvar_SetValue( "ui_r_inGameVideo", 1 ); - // trap->Cvar_SetValue( "ui_cg_shadows", 2 ); - trap->Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR" ); + trap->Cvar_SetValue("ui_r_fullScreen", 1); + trap->Cvar_SetValue("ui_r_subdivisions", 4); + trap->Cvar_SetValue("ui_r_lodbias", 0); + trap->Cvar_SetValue("ui_r_colorbits", 0); + trap->Cvar_SetValue("ui_r_depthbits", 24); + trap->Cvar_SetValue("ui_r_picmip", 1); + trap->Cvar_SetValue("ui_r_mode", 3); + trap->Cvar_SetValue("ui_r_texturebits", 0); + trap->Cvar_SetValue("ui_r_fastSky", 0); + trap->Cvar_SetValue("ui_r_inGameVideo", 1); + // trap->Cvar_SetValue( "ui_cg_shadows", 2 ); + trap->Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_LINEAR"); break; case 2: // fast - trap->Cvar_SetValue( "ui_r_fullScreen", 1 ); - trap->Cvar_SetValue( "ui_r_subdivisions", 12 ); - trap->Cvar_SetValue( "ui_r_lodbias", 1 ); - trap->Cvar_SetValue( "ui_r_colorbits", 0 ); - trap->Cvar_SetValue( "ui_r_depthbits", 0 ); - trap->Cvar_SetValue( "ui_r_picmip", 2 ); - trap->Cvar_SetValue( "ui_r_mode", 3 ); - trap->Cvar_SetValue( "ui_r_texturebits", 0 ); - trap->Cvar_SetValue( "ui_r_fastSky", 1 ); - trap->Cvar_SetValue( "ui_r_inGameVideo", 0 ); - // trap->Cvar_SetValue( "ui_cg_shadows", 1 ); - trap->Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" ); + trap->Cvar_SetValue("ui_r_fullScreen", 1); + trap->Cvar_SetValue("ui_r_subdivisions", 12); + trap->Cvar_SetValue("ui_r_lodbias", 1); + trap->Cvar_SetValue("ui_r_colorbits", 0); + trap->Cvar_SetValue("ui_r_depthbits", 0); + trap->Cvar_SetValue("ui_r_picmip", 2); + trap->Cvar_SetValue("ui_r_mode", 3); + trap->Cvar_SetValue("ui_r_texturebits", 0); + trap->Cvar_SetValue("ui_r_fastSky", 1); + trap->Cvar_SetValue("ui_r_inGameVideo", 0); + // trap->Cvar_SetValue( "ui_cg_shadows", 1 ); + trap->Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST"); break; case 3: // fastest - trap->Cvar_SetValue( "ui_r_fullScreen", 1 ); - trap->Cvar_SetValue( "ui_r_subdivisions", 20 ); - trap->Cvar_SetValue( "ui_r_lodbias", 2 ); - trap->Cvar_SetValue( "ui_r_colorbits", 16 ); - trap->Cvar_SetValue( "ui_r_depthbits", 16 ); - trap->Cvar_SetValue( "ui_r_mode", 3 ); - trap->Cvar_SetValue( "ui_r_picmip", 3 ); - trap->Cvar_SetValue( "ui_r_texturebits", 16 ); - trap->Cvar_SetValue( "ui_r_fastSky", 1 ); - trap->Cvar_SetValue( "ui_r_inGameVideo", 0 ); - // trap->Cvar_SetValue( "ui_cg_shadows", 0 ); - trap->Cvar_Set( "ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST" ); + trap->Cvar_SetValue("ui_r_fullScreen", 1); + trap->Cvar_SetValue("ui_r_subdivisions", 20); + trap->Cvar_SetValue("ui_r_lodbias", 2); + trap->Cvar_SetValue("ui_r_colorbits", 16); + trap->Cvar_SetValue("ui_r_depthbits", 16); + trap->Cvar_SetValue("ui_r_mode", 3); + trap->Cvar_SetValue("ui_r_picmip", 3); + trap->Cvar_SetValue("ui_r_texturebits", 16); + trap->Cvar_SetValue("ui_r_fastSky", 1); + trap->Cvar_SetValue("ui_r_inGameVideo", 0); + // trap->Cvar_SetValue( "ui_cg_shadows", 0 ); + trap->Cvar_Set("ui_r_texturemode", "GL_LINEAR_MIPMAP_NEAREST"); break; } - } - else if (Q_stricmp(name, "ui_mousePitch") == 0) - { - if (val == 0) trap->Cvar_SetValue( "m_pitch", 0.022f ); - else trap->Cvar_SetValue( "m_pitch", -0.022f ); - } - else if (Q_stricmp(name, "ui_mousePitchVeh") == 0) - { - if (val == 0) trap->Cvar_SetValue( "m_pitchVeh", 0.022f ); - else trap->Cvar_SetValue( "m_pitchVeh", -0.022f ); + } else if (Q_stricmp(name, "ui_mousePitch") == 0) { + if (val == 0) + trap->Cvar_SetValue("m_pitch", 0.022f); + else + trap->Cvar_SetValue("m_pitch", -0.022f); + } else if (Q_stricmp(name, "ui_mousePitchVeh") == 0) { + if (val == 0) + trap->Cvar_SetValue("m_pitchVeh", 0.022f); + else + trap->Cvar_SetValue("m_pitchVeh", -0.022f); } } @@ -4820,46 +4410,39 @@ UI_DeferMenuScript Return true if the menu script should be deferred for later =============== */ -static qboolean UI_DeferMenuScript ( char **args ) -{ - const char* name; +static qboolean UI_DeferMenuScript(char **args) { + const char *name; // Whats the reason for being deferred? - if (!String_Parse( (char**)args, &name)) - { + if (!String_Parse((char **)args, &name)) { return qfalse; } // Handle the custom cases - if ( !Q_stricmp ( name, "VideoSetup" ) ) - { - const char* warningMenuName; - qboolean deferred; + if (!Q_stricmp(name, "VideoSetup")) { + const char *warningMenuName; + qboolean deferred; // No warning menu specified - if ( !String_Parse( (char**)args, &warningMenuName) ) - { + if (!String_Parse((char **)args, &warningMenuName)) { return qfalse; } // Defer if the video options were modified - deferred = trap->Cvar_VariableValue ( "ui_r_modified" ) ? qtrue : qfalse; + deferred = trap->Cvar_VariableValue("ui_r_modified") ? qtrue : qfalse; - if ( deferred ) - { + if (deferred) { // Open the warning menu Menus_OpenByName(warningMenuName); } return deferred; - } - else if ( !Q_stricmp ( name, "RulesBackout" ) ) - { + } else if (!Q_stricmp(name, "RulesBackout")) { qboolean deferred; - deferred = trap->Cvar_VariableValue ( "ui_rules_backout" ) ? qtrue : qfalse ; + deferred = trap->Cvar_VariableValue("ui_rules_backout") ? qtrue : qfalse; - trap->Cvar_Set ( "ui_rules_backout", "0" ); + trap->Cvar_Set("ui_rules_backout", "0"); return deferred; } @@ -4876,26 +4459,25 @@ their real counterparts. This is to create a interface which allows you to discard your changes if you did something you didnt want ================= */ -void UI_UpdateVideoSetup ( void ) -{ - trap->Cvar_Set ( "r_mode", UI_Cvar_VariableString ( "ui_r_mode" ) ); - trap->Cvar_Set ( "r_fullscreen", UI_Cvar_VariableString ( "ui_r_fullscreen" ) ); - trap->Cvar_Set ( "r_colorbits", UI_Cvar_VariableString ( "ui_r_colorbits" ) ); - trap->Cvar_Set ( "r_lodbias", UI_Cvar_VariableString ( "ui_r_lodbias" ) ); - trap->Cvar_Set ( "r_picmip", UI_Cvar_VariableString ( "ui_r_picmip" ) ); - trap->Cvar_Set ( "r_texturebits", UI_Cvar_VariableString ( "ui_r_texturebits" ) ); - trap->Cvar_Set ( "r_texturemode", UI_Cvar_VariableString ( "ui_r_texturemode" ) ); - trap->Cvar_Set ( "r_detailtextures", UI_Cvar_VariableString ( "ui_r_detailtextures" ) ); - trap->Cvar_Set ( "r_ext_compress_textures", UI_Cvar_VariableString ( "ui_r_ext_compress_textures" ) ); - trap->Cvar_Set ( "r_depthbits", UI_Cvar_VariableString ( "ui_r_depthbits" ) ); - trap->Cvar_Set ( "r_subdivisions", UI_Cvar_VariableString ( "ui_r_subdivisions" ) ); - trap->Cvar_Set ( "r_fastSky", UI_Cvar_VariableString ( "ui_r_fastSky" ) ); - trap->Cvar_Set ( "r_inGameVideo", UI_Cvar_VariableString ( "ui_r_inGameVideo" ) ); - trap->Cvar_Set ( "r_allowExtensions", UI_Cvar_VariableString ( "ui_r_allowExtensions" ) ); - trap->Cvar_Set ( "cg_shadows", UI_Cvar_VariableString ( "ui_cg_shadows" ) ); - trap->Cvar_Set ( "ui_r_modified", "0" ); - - trap->Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" ); +void UI_UpdateVideoSetup(void) { + trap->Cvar_Set("r_mode", UI_Cvar_VariableString("ui_r_mode")); + trap->Cvar_Set("r_fullscreen", UI_Cvar_VariableString("ui_r_fullscreen")); + trap->Cvar_Set("r_colorbits", UI_Cvar_VariableString("ui_r_colorbits")); + trap->Cvar_Set("r_lodbias", UI_Cvar_VariableString("ui_r_lodbias")); + trap->Cvar_Set("r_picmip", UI_Cvar_VariableString("ui_r_picmip")); + trap->Cvar_Set("r_texturebits", UI_Cvar_VariableString("ui_r_texturebits")); + trap->Cvar_Set("r_texturemode", UI_Cvar_VariableString("ui_r_texturemode")); + trap->Cvar_Set("r_detailtextures", UI_Cvar_VariableString("ui_r_detailtextures")); + trap->Cvar_Set("r_ext_compress_textures", UI_Cvar_VariableString("ui_r_ext_compress_textures")); + trap->Cvar_Set("r_depthbits", UI_Cvar_VariableString("ui_r_depthbits")); + trap->Cvar_Set("r_subdivisions", UI_Cvar_VariableString("ui_r_subdivisions")); + trap->Cvar_Set("r_fastSky", UI_Cvar_VariableString("ui_r_fastSky")); + trap->Cvar_Set("r_inGameVideo", UI_Cvar_VariableString("ui_r_inGameVideo")); + trap->Cvar_Set("r_allowExtensions", UI_Cvar_VariableString("ui_r_allowExtensions")); + trap->Cvar_Set("cg_shadows", UI_Cvar_VariableString("ui_cg_shadows")); + trap->Cvar_Set("ui_r_modified", "0"); + + trap->Cmd_ExecuteText(EXEC_APPEND, "vid_restart;"); } /* @@ -4906,80 +4488,75 @@ Retrieves the current actual video settings into the temporary user interface versions of the cvars. ================= */ -void UI_GetVideoSetup ( void ) -{ - trap->Cvar_Register ( NULL, "ui_r_glCustom", "4", CVAR_INTERNAL|CVAR_ARCHIVE ); +void UI_GetVideoSetup(void) { + trap->Cvar_Register(NULL, "ui_r_glCustom", "4", CVAR_INTERNAL | CVAR_ARCHIVE); // Make sure the cvars are registered as read only. - trap->Cvar_Register ( NULL, "ui_r_mode", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_fullscreen", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_colorbits", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_lodbias", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_picmip", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_texturebits", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_texturemode", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_detailtextures", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_ext_compress_textures", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_depthbits", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_subdivisions", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_fastSky", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_inGameVideo", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_allowExtensions", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_cg_shadows", "0", CVAR_ROM|CVAR_INTERNAL ); - trap->Cvar_Register ( NULL, "ui_r_modified", "0", CVAR_ROM|CVAR_INTERNAL ); + trap->Cvar_Register(NULL, "ui_r_mode", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_fullscreen", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_colorbits", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_lodbias", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_picmip", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_texturebits", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_texturemode", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_detailtextures", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_ext_compress_textures", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_depthbits", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_subdivisions", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_fastSky", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_inGameVideo", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_allowExtensions", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_cg_shadows", "0", CVAR_ROM | CVAR_INTERNAL); + trap->Cvar_Register(NULL, "ui_r_modified", "0", CVAR_ROM | CVAR_INTERNAL); // Copy over the real video cvars into their temporary counterparts - trap->Cvar_Set ( "ui_r_mode", UI_Cvar_VariableString ( "r_mode" ) ); - trap->Cvar_Set ( "ui_r_colorbits", UI_Cvar_VariableString ( "r_colorbits" ) ); - trap->Cvar_Set ( "ui_r_fullscreen", UI_Cvar_VariableString ( "r_fullscreen" ) ); - trap->Cvar_Set ( "ui_r_lodbias", UI_Cvar_VariableString ( "r_lodbias" ) ); - trap->Cvar_Set ( "ui_r_picmip", UI_Cvar_VariableString ( "r_picmip" ) ); - trap->Cvar_Set ( "ui_r_texturebits", UI_Cvar_VariableString ( "r_texturebits" ) ); - trap->Cvar_Set ( "ui_r_texturemode", UI_Cvar_VariableString ( "r_texturemode" ) ); - trap->Cvar_Set ( "ui_r_detailtextures", UI_Cvar_VariableString ( "r_detailtextures" ) ); - trap->Cvar_Set ( "ui_r_ext_compress_textures", UI_Cvar_VariableString ( "r_ext_compress_textures" ) ); - trap->Cvar_Set ( "ui_r_depthbits", UI_Cvar_VariableString ( "r_depthbits" ) ); - trap->Cvar_Set ( "ui_r_subdivisions", UI_Cvar_VariableString ( "r_subdivisions" ) ); - trap->Cvar_Set ( "ui_r_fastSky", UI_Cvar_VariableString ( "r_fastSky" ) ); - trap->Cvar_Set ( "ui_r_inGameVideo", UI_Cvar_VariableString ( "r_inGameVideo" ) ); - trap->Cvar_Set ( "ui_r_allowExtensions", UI_Cvar_VariableString ( "r_allowExtensions" ) ); - trap->Cvar_Set ( "ui_cg_shadows", UI_Cvar_VariableString ( "cg_shadows" ) ); - trap->Cvar_Set ( "ui_r_modified", "0" ); + trap->Cvar_Set("ui_r_mode", UI_Cvar_VariableString("r_mode")); + trap->Cvar_Set("ui_r_colorbits", UI_Cvar_VariableString("r_colorbits")); + trap->Cvar_Set("ui_r_fullscreen", UI_Cvar_VariableString("r_fullscreen")); + trap->Cvar_Set("ui_r_lodbias", UI_Cvar_VariableString("r_lodbias")); + trap->Cvar_Set("ui_r_picmip", UI_Cvar_VariableString("r_picmip")); + trap->Cvar_Set("ui_r_texturebits", UI_Cvar_VariableString("r_texturebits")); + trap->Cvar_Set("ui_r_texturemode", UI_Cvar_VariableString("r_texturemode")); + trap->Cvar_Set("ui_r_detailtextures", UI_Cvar_VariableString("r_detailtextures")); + trap->Cvar_Set("ui_r_ext_compress_textures", UI_Cvar_VariableString("r_ext_compress_textures")); + trap->Cvar_Set("ui_r_depthbits", UI_Cvar_VariableString("r_depthbits")); + trap->Cvar_Set("ui_r_subdivisions", UI_Cvar_VariableString("r_subdivisions")); + trap->Cvar_Set("ui_r_fastSky", UI_Cvar_VariableString("r_fastSky")); + trap->Cvar_Set("ui_r_inGameVideo", UI_Cvar_VariableString("r_inGameVideo")); + trap->Cvar_Set("ui_r_allowExtensions", UI_Cvar_VariableString("r_allowExtensions")); + trap->Cvar_Set("ui_cg_shadows", UI_Cvar_VariableString("cg_shadows")); + trap->Cvar_Set("ui_r_modified", "0"); } // If the game type is siege, hide the addbot button. I would have done a cvar text on that item, // but it already had one on it. -static void UI_SetBotButton ( void ) -{ - int gameType = trap->Cvar_VariableValue( "g_gametype" ); +static void UI_SetBotButton(void) { + int gameType = trap->Cvar_VariableValue("g_gametype"); int server; menuDef_t *menu; itemDef_t *item; char *name = "addBot"; - server = trap->Cvar_VariableValue( "sv_running" ); + server = trap->Cvar_VariableValue("sv_running"); // If in siege or a client, don't show add bot button - if ((gameType==GT_SIEGE) || (server==0)) // If it's not siege, don't worry about it + if ((gameType == GT_SIEGE) || (server == 0)) // If it's not siege, don't worry about it { - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { + if (!menu) { return; } item = Menu_FindItemByName(menu, name); - if (item) - { + if (item) { Menu_ShowItemByName(menu, name, qfalse); } } } // Update the model cvar and everything is good. -static void UI_UpdateCharacterCvars ( void ) -{ +static void UI_UpdateCharacterCvars(void) { char skin[MAX_QPATH]; char model[MAX_QPATH]; char head[MAX_QPATH]; @@ -4991,124 +4568,102 @@ static void UI_UpdateCharacterCvars ( void ) trap->Cvar_VariableStringBuffer("ui_char_skin_torso", torso, sizeof(torso)); trap->Cvar_VariableStringBuffer("ui_char_skin_legs", legs, sizeof(legs)); - Com_sprintf( skin, sizeof( skin ), "%s/%s|%s|%s", - model, - head, - torso, - legs - ); + Com_sprintf(skin, sizeof(skin), "%s/%s|%s|%s", model, head, torso, legs); - trap->Cvar_Set ( "model", skin ); - - trap->Cvar_Set ( "char_color_red", UI_Cvar_VariableString ( "ui_char_color_red" ) ); - trap->Cvar_Set ( "char_color_green", UI_Cvar_VariableString ( "ui_char_color_green" ) ); - trap->Cvar_Set ( "char_color_blue", UI_Cvar_VariableString ( "ui_char_color_blue" ) ); - trap->Cvar_Set ( "ui_selectedModelIndex", "-1"); + trap->Cvar_Set("model", skin); + trap->Cvar_Set("char_color_red", UI_Cvar_VariableString("ui_char_color_red")); + trap->Cvar_Set("char_color_green", UI_Cvar_VariableString("ui_char_color_green")); + trap->Cvar_Set("char_color_blue", UI_Cvar_VariableString("ui_char_color_blue")); + trap->Cvar_Set("ui_selectedModelIndex", "-1"); } -static void UI_GetCharacterCvars ( void ) -{ +static void UI_GetCharacterCvars(void) { char *model; char *skin; int i; - trap->Cvar_Set ( "ui_char_color_red", UI_Cvar_VariableString ( "char_color_red" ) ); - trap->Cvar_Set ( "ui_char_color_green", UI_Cvar_VariableString ( "char_color_green" ) ); - trap->Cvar_Set ( "ui_char_color_blue", UI_Cvar_VariableString ( "char_color_blue" ) ); + trap->Cvar_Set("ui_char_color_red", UI_Cvar_VariableString("char_color_red")); + trap->Cvar_Set("ui_char_color_green", UI_Cvar_VariableString("char_color_green")); + trap->Cvar_Set("ui_char_color_blue", UI_Cvar_VariableString("char_color_blue")); - model = UI_Cvar_VariableString ( "model" ); - skin = strrchr(model,'/'); - if (skin && strchr(model,'|')) //we have a multipart custom jedi + model = UI_Cvar_VariableString("model"); + skin = strrchr(model, '/'); + if (skin && strchr(model, '|')) // we have a multipart custom jedi { char skinhead[MAX_QPATH]; char skintorso[MAX_QPATH]; char skinlower[MAX_QPATH]; char *p2; - *skin=0; + *skin = 0; skin++; - //now get the the individual files + // now get the the individual files - //advance to second + // advance to second p2 = strchr(skin, '|'); assert(p2); - *p2=0; + *p2 = 0; p2++; - Q_strncpyz (skinhead, skin, sizeof(skinhead)); + Q_strncpyz(skinhead, skin, sizeof(skinhead)); - - //advance to third + // advance to third skin = strchr(p2, '|'); assert(skin); - *skin=0; + *skin = 0; skin++; - Q_strncpyz (skintorso,p2, sizeof(skintorso)); - - Q_strncpyz (skinlower,skin, sizeof(skinlower)); - + Q_strncpyz(skintorso, p2, sizeof(skintorso)); + Q_strncpyz(skinlower, skin, sizeof(skinlower)); trap->Cvar_Set("ui_char_model", model); trap->Cvar_Set("ui_char_skin_head", skinhead); trap->Cvar_Set("ui_char_skin_torso", skintorso); trap->Cvar_Set("ui_char_skin_legs", skinlower); - for (i = 0; i < uiInfo.playerSpeciesCount; i++) - { - if ( !Q_stricmp(model, uiInfo.playerSpecies[i].Name) ) - { + for (i = 0; i < uiInfo.playerSpeciesCount; i++) { + if (!Q_stricmp(model, uiInfo.playerSpecies[i].Name)) { uiInfo.playerSpeciesIndex = i; break; } } - } - else - { - model = UI_Cvar_VariableString ( "ui_char_model" ); - for (i = 0; i < uiInfo.playerSpeciesCount; i++) - { - if ( !Q_stricmp(model, uiInfo.playerSpecies[i].Name) ) - { + } else { + model = UI_Cvar_VariableString("ui_char_model"); + for (i = 0; i < uiInfo.playerSpeciesCount; i++) { + if (!Q_stricmp(model, uiInfo.playerSpecies[i].Name)) { uiInfo.playerSpeciesIndex = i; - return; //FOUND IT, don't fall through + return; // FOUND IT, don't fall through } } - //nope, didn't find it. - uiInfo.playerSpeciesIndex = 0;//jic + // nope, didn't find it. + uiInfo.playerSpeciesIndex = 0; // jic trap->Cvar_Set("ui_char_model", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name); trap->Cvar_Set("ui_char_skin_head", "head_a1"); - trap->Cvar_Set("ui_char_skin_torso","torso_a1"); + trap->Cvar_Set("ui_char_skin_torso", "torso_a1"); trap->Cvar_Set("ui_char_skin_legs", "lower_a1"); } } -void UI_SetSiegeObjectiveGraphicPos(menuDef_t *menu,const char *itemName,const char *cvarName) -{ - itemDef_t *item; - char cvarBuf[1024]; - const char *holdVal; - char *holdBuf; +void UI_SetSiegeObjectiveGraphicPos(menuDef_t *menu, const char *itemName, const char *cvarName) { + itemDef_t *item; + char cvarBuf[1024]; + const char *holdVal; + char *holdBuf; item = Menu_FindItemByName(menu, itemName); - if (item) - { + if (item) { // get cvar data trap->Cvar_VariableStringBuffer(cvarName, cvarBuf, sizeof(cvarBuf)); holdBuf = cvarBuf; - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.x = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.y = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.w = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.h = atof(holdVal); item->window.rect.x = item->window.rectClient.x; @@ -5123,51 +4678,42 @@ void UI_SetSiegeObjectiveGraphicPos(menuDef_t *menu,const char *itemName,const c } } -void UI_FindCurrentSiegeTeamClass( void ) -{ +void UI_FindCurrentSiegeTeamClass(void) { menuDef_t *menu; int myTeam = (int)(trap->Cvar_VariableValue("ui_myteam")); char *itemname; itemDef_t *item; - int baseClass; + int baseClass; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - if (( myTeam != TEAM_RED ) && ( myTeam != TEAM_BLUE )) - { + if ((myTeam != TEAM_RED) && (myTeam != TEAM_BLUE)) { return; } // If the player is on a team, - if ( myTeam == TEAM_RED ) - { + if (myTeam == TEAM_RED) { itemDef_t *item; - item = (itemDef_t *) Menu_FindItemByName(menu, "onteam1" ); - if (item) - { - Item_RunScript(item, item->action); + item = (itemDef_t *)Menu_FindItemByName(menu, "onteam1"); + if (item) { + Item_RunScript(item, item->action); } - } - else if ( myTeam == TEAM_BLUE ) - { + } else if (myTeam == TEAM_BLUE) { itemDef_t *item; - item = (itemDef_t *) Menu_FindItemByName(menu, "onteam2" ); - if (item) - { - Item_RunScript(item, item->action); + item = (itemDef_t *)Menu_FindItemByName(menu, "onteam2"); + if (item) { + Item_RunScript(item, item->action); } } - baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); // Find correct class button and activate it. - switch ( baseClass ) { + switch (baseClass) { case SPC_INFANTRY: itemname = "class1_button"; break; @@ -5190,145 +4736,127 @@ void UI_FindCurrentSiegeTeamClass( void ) return; } - item = (itemDef_t *) Menu_FindItemByName(menu, itemname ); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName(menu, itemname); + if (item) { Item_RunScript(item, item->action); } } -void UI_UpdateSiegeObjectiveGraphics( void ) -{ +void UI_UpdateSiegeObjectiveGraphics(void) { menuDef_t *menu; - int teamI,objI; + int teamI, objI; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } // Hiding a bunch of fields because the opening section of the siege menu was getting too long - Menu_ShowGroup(menu,"class_button",qfalse); - Menu_ShowGroup(menu,"class_count",qfalse); - Menu_ShowGroup(menu,"feeders",qfalse); - Menu_ShowGroup(menu,"classdescription",qfalse); - Menu_ShowGroup(menu,"minidesc",qfalse); - Menu_ShowGroup(menu,"obj_longdesc",qfalse); - Menu_ShowGroup(menu,"objective_pic",qfalse); - Menu_ShowGroup(menu,"stats",qfalse); - Menu_ShowGroup(menu,"forcepowerlevel",qfalse); + Menu_ShowGroup(menu, "class_button", qfalse); + Menu_ShowGroup(menu, "class_count", qfalse); + Menu_ShowGroup(menu, "feeders", qfalse); + Menu_ShowGroup(menu, "classdescription", qfalse); + Menu_ShowGroup(menu, "minidesc", qfalse); + Menu_ShowGroup(menu, "obj_longdesc", qfalse); + Menu_ShowGroup(menu, "objective_pic", qfalse); + Menu_ShowGroup(menu, "stats", qfalse); + Menu_ShowGroup(menu, "forcepowerlevel", qfalse); // Get objective icons for each team - for (teamI=1;teamI<3;teamI++) - { - for (objI=1;objI<8;objI++) - { - Menu_SetItemBackground(menu,va("tm%i_icon%i",teamI,objI),va("*team%i_objective%i_mapicon",teamI,objI)); - Menu_SetItemBackground(menu,va("tm%i_l_icon%i",teamI,objI),va("*team%i_objective%i_mapicon",teamI,objI)); + for (teamI = 1; teamI < 3; teamI++) { + for (objI = 1; objI < 8; objI++) { + Menu_SetItemBackground(menu, va("tm%i_icon%i", teamI, objI), va("*team%i_objective%i_mapicon", teamI, objI)); + Menu_SetItemBackground(menu, va("tm%i_l_icon%i", teamI, objI), va("*team%i_objective%i_mapicon", teamI, objI)); } } // Now get their placement on the map - for (teamI=1;teamI<3;teamI++) - { - for (objI=1;objI<8;objI++) - { - UI_SetSiegeObjectiveGraphicPos(menu,va("tm%i_icon%i",teamI,objI),va("team%i_objective%i_mappos",teamI,objI)); + for (teamI = 1; teamI < 3; teamI++) { + for (objI = 1; objI < 8; objI++) { + UI_SetSiegeObjectiveGraphicPos(menu, va("tm%i_icon%i", teamI, objI), va("team%i_objective%i_mappos", teamI, objI)); } } - } -saber_colors_t TranslateSaberColor( const char *name ); +saber_colors_t TranslateSaberColor(const char *name); -static void UI_UpdateSaberCvars ( void ) -{ +static void UI_UpdateSaberCvars(void) { saber_colors_t colorI; - trap->Cvar_Set ( "saber1", UI_Cvar_VariableString ( "ui_saber" ) ); - trap->Cvar_Set ( "saber2", UI_Cvar_VariableString ( "ui_saber2" ) ); + trap->Cvar_Set("saber1", UI_Cvar_VariableString("ui_saber")); + trap->Cvar_Set("saber2", UI_Cvar_VariableString("ui_saber2")); - colorI = TranslateSaberColor( UI_Cvar_VariableString ( "ui_saber_color" ) ); - trap->Cvar_Set ( "color1", va("%d",colorI)); - trap->Cvar_Set ( "g_saber_color", UI_Cvar_VariableString ( "ui_saber_color" )); + colorI = TranslateSaberColor(UI_Cvar_VariableString("ui_saber_color")); + trap->Cvar_Set("color1", va("%d", colorI)); + trap->Cvar_Set("g_saber_color", UI_Cvar_VariableString("ui_saber_color")); - colorI = TranslateSaberColor( UI_Cvar_VariableString ( "ui_saber2_color" ) ); - trap->Cvar_Set ( "color2", va("%d",colorI) ); - trap->Cvar_Set ( "g_saber2_color", UI_Cvar_VariableString ( "ui_saber2_color" )); + colorI = TranslateSaberColor(UI_Cvar_VariableString("ui_saber2_color")); + trap->Cvar_Set("color2", va("%d", colorI)); + trap->Cvar_Set("g_saber2_color", UI_Cvar_VariableString("ui_saber2_color")); } // More hard coded goodness for the menus. -static void UI_SetSaberBoxesandHilts (void) -{ +static void UI_SetSaberBoxesandHilts(void) { menuDef_t *menu; itemDef_t *item; - qboolean getBig = qfalse; + qboolean getBig = qfalse; char sType[MAX_QPATH]; - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { + if (!menu) { return; } - trap->Cvar_VariableStringBuffer( "ui_saber_type", sType, sizeof(sType) ); + trap->Cvar_VariableStringBuffer("ui_saber_type", sType, sizeof(sType)); - if ( Q_stricmp( "dual", sType ) != 0 ) - { -// trap->Cvar_Set("ui_saber", "single_1"); -// trap->Cvar_Set("ui_saber2", "single_1"); + if (Q_stricmp("dual", sType) != 0) { + // trap->Cvar_Set("ui_saber", "single_1"); + // trap->Cvar_Set("ui_saber2", "single_1"); getBig = qtrue; } - else if (Q_stricmp( "staff", sType ) != 0 ) - { -// trap->Cvar_Set("ui_saber", "dual_1"); -// trap->Cvar_Set("ui_saber2", "none"); + else if (Q_stricmp("staff", sType) != 0) { + // trap->Cvar_Set("ui_saber", "dual_1"); + // trap->Cvar_Set("ui_saber2", "none"); getBig = qtrue; } - if (!getBig) - { + if (!getBig) { return; } - item = (itemDef_t *) Menu_FindItemByName(menu, "box2middle" ); + item = (itemDef_t *)Menu_FindItemByName(menu, "box2middle"); - if(item) - { + if (item) { item->window.rect.x = 212; item->window.rect.y = 126; item->window.rect.w = 219; item->window.rect.h = 44; } - item = (itemDef_t *) Menu_FindItemByName(menu, "box2bottom" ); + item = (itemDef_t *)Menu_FindItemByName(menu, "box2bottom"); - if(item) - { + if (item) { item->window.rect.x = 212; item->window.rect.y = 170; item->window.rect.w = 219; item->window.rect.h = 60; } - item = (itemDef_t *) Menu_FindItemByName(menu, "box3middle" ); + item = (itemDef_t *)Menu_FindItemByName(menu, "box3middle"); - if(item) - { + if (item) { item->window.rect.x = 418; item->window.rect.y = 126; item->window.rect.w = 219; item->window.rect.h = 44; } - item = (itemDef_t *) Menu_FindItemByName(menu, "box3bottom" ); + item = (itemDef_t *)Menu_FindItemByName(menu, "box3bottom"); - if(item) - { + if (item) { item->window.rect.x = 418; item->window.rect.y = 170; item->window.rect.w = 219; @@ -5336,24 +4864,20 @@ static void UI_SetSaberBoxesandHilts (void) } } -extern qboolean UI_SaberSkinForSaber( const char *saberName, char *saberSkin ); -extern qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTimeLength ); -extern qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ); +extern qboolean UI_SaberSkinForSaber(const char *saberName, char *saberSkin); +extern qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name, int *runTimeLength); +extern qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName); -static void UI_UpdateSaberType( void ) -{ +static void UI_UpdateSaberType(void) { char sType[MAX_QPATH]; - trap->Cvar_VariableStringBuffer( "ui_saber_type", sType, sizeof(sType) ); + trap->Cvar_VariableStringBuffer("ui_saber_type", sType, sizeof(sType)); - if ( Q_stricmp( "single", sType ) == 0 || - Q_stricmp( "staff", sType ) == 0 ) - { - trap->Cvar_Set( "ui_saber2", "" ); + if (Q_stricmp("single", sType) == 0 || Q_stricmp("staff", sType) == 0) { + trap->Cvar_Set("ui_saber2", ""); } } -static void UI_UpdateSaberHilt( qboolean secondSaber ) -{ +static void UI_UpdateSaberHilt(qboolean secondSaber) { menuDef_t *menu; itemDef_t *item; char model[MAX_QPATH]; @@ -5361,77 +4885,64 @@ static void UI_UpdateSaberHilt( qboolean secondSaber ) char skinPath[MAX_QPATH]; char *itemName; char *saberCvarName; - int animRunLength; + int animRunLength; - menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) + menu = Menu_GetFocused(); // Get current menu (either video or ingame video, I would assume) - if (!menu) - { + if (!menu) { return; } - if ( secondSaber ) - { + if (secondSaber) { itemName = "saber2"; saberCvarName = "ui_saber2"; - } - else - { + } else { itemName = "saber"; saberCvarName = "ui_saber"; } - item = (itemDef_t *) Menu_FindItemByName(menu, itemName ); + item = (itemDef_t *)Menu_FindItemByName(menu, itemName); - if(!item) - { - Com_Error( ERR_FATAL, "UI_UpdateSaberHilt: Could not find item (%s) in menu (%s)", itemName, menu->window.name); + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateSaberHilt: Could not find item (%s) in menu (%s)", itemName, menu->window.name); } - trap->Cvar_VariableStringBuffer( saberCvarName, model, sizeof(model) ); + trap->Cvar_VariableStringBuffer(saberCvarName, model, sizeof(model)); item->text = model; - //read this from the sabers.cfg - if ( UI_SaberModelForSaber( model, modelPath ) ) - {//successfully found a model - ItemParse_asset_model_go( item, modelPath, &animRunLength );//set the model - //get the customSkin, if any - //COM_StripExtension( modelPath, skinPath ); - //COM_DefaultExtension( skinPath, sizeof( skinPath ), ".skin" ); - if ( UI_SaberSkinForSaber( model, skinPath ) ) - { - ItemParse_model_g2skin_go( item, skinPath );//apply the skin - } - else - { - ItemParse_model_g2skin_go( item, NULL );//apply the skin + // read this from the sabers.cfg + if (UI_SaberModelForSaber(model, modelPath)) { // successfully found a model + ItemParse_asset_model_go(item, modelPath, &animRunLength); // set the model + // get the customSkin, if any + // COM_StripExtension( modelPath, skinPath ); + // COM_DefaultExtension( skinPath, sizeof( skinPath ), ".skin" ); + if (UI_SaberSkinForSaber(model, skinPath)) { + ItemParse_model_g2skin_go(item, skinPath); // apply the skin + } else { + ItemParse_model_g2skin_go(item, NULL); // apply the skin } } } -static void UI_UpdateSaberColor( qboolean secondSaber ) -{ -} +static void UI_UpdateSaberColor(qboolean secondSaber) {} -const char *SaberColorToString( saber_colors_t color ); +const char *SaberColorToString(saber_colors_t color); -static void UI_GetSaberCvars ( void ) -{ -// trap->Cvar_Set ( "ui_saber_type", UI_Cvar_VariableString ( "g_saber_type" ) ); - trap->Cvar_Set ( "ui_saber", UI_Cvar_VariableString ( "saber1" ) ); - trap->Cvar_Set ( "ui_saber2", UI_Cvar_VariableString ( "saber2" )); +static void UI_GetSaberCvars(void) { + // trap->Cvar_Set ( "ui_saber_type", UI_Cvar_VariableString ( "g_saber_type" ) ); + trap->Cvar_Set("ui_saber", UI_Cvar_VariableString("saber1")); + trap->Cvar_Set("ui_saber2", UI_Cvar_VariableString("saber2")); trap->Cvar_Set("g_saber_color", SaberColorToString(trap->Cvar_VariableValue("color1"))); trap->Cvar_Set("g_saber2_color", SaberColorToString(trap->Cvar_VariableValue("color2"))); - trap->Cvar_Set ( "ui_saber_color", UI_Cvar_VariableString ( "g_saber_color" ) ); - trap->Cvar_Set ( "ui_saber2_color", UI_Cvar_VariableString ( "g_saber2_color" ) ); + trap->Cvar_Set("ui_saber_color", UI_Cvar_VariableString("g_saber_color")); + trap->Cvar_Set("ui_saber2_color", UI_Cvar_VariableString("g_saber2_color")); } -extern qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ); +extern qboolean ItemParse_model_g2anim_go(itemDef_t *item, const char *animName); -void UI_UpdateCharacterSkin( void ) -{ +void UI_UpdateCharacterSkin(void) { menuDef_t *menu; itemDef_t *item; char skin[MAX_QPATH]; @@ -5440,18 +4951,16 @@ void UI_UpdateCharacterSkin( void ) char torso[MAX_QPATH]; char legs[MAX_QPATH]; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - item = (itemDef_t *) Menu_FindItemByName(menu, "character"); + item = (itemDef_t *)Menu_FindItemByName(menu, "character"); - if (!item) - { - Com_Error( ERR_FATAL, "UI_UpdateCharacterSkin: Could not find item (character) in menu (%s)", menu->window.name); + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateCharacterSkin: Could not find item (character) in menu (%s)", menu->window.name); } trap->Cvar_VariableStringBuffer("ui_char_model", model, sizeof(model)); @@ -5459,18 +4968,12 @@ void UI_UpdateCharacterSkin( void ) trap->Cvar_VariableStringBuffer("ui_char_skin_torso", torso, sizeof(torso)); trap->Cvar_VariableStringBuffer("ui_char_skin_legs", legs, sizeof(legs)); - Com_sprintf( skin, sizeof( skin ), "models/players/%s/|%s|%s|%s", - model, - head, - torso, - legs - ); + Com_sprintf(skin, sizeof(skin), "models/players/%s/|%s|%s|%s", model, head, torso, legs); - ItemParse_model_g2skin_go( item, skin ); + ItemParse_model_g2skin_go(item, skin); } -static void UI_ResetCharacterListBoxes( void ) -{ +static void UI_ResetCharacterListBoxes(void) { itemDef_t *item; menuDef_t *menu; @@ -5478,47 +4981,38 @@ static void UI_ResetCharacterListBoxes( void ) menu = Menu_GetFocused(); - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "headlistbox"); - if (item) - { + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "headlistbox"); + if (item) { listPtr = item->typeData.listbox; - if( listPtr ) - { + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "torsolistbox"); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "torsolistbox"); + if (item) { listPtr = item->typeData.listbox; - if( listPtr ) - { + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "lowerlistbox"); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "lowerlistbox"); + if (item) { listPtr = item->typeData.listbox; - if( listPtr ) - { + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "colorbox"); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "colorbox"); + if (item) { listPtr = item->typeData.listbox; - if( listPtr ) - { + if (listPtr) { listPtr->cursorPos = 0; } item->cursorPos = 0; @@ -5526,42 +5020,38 @@ static void UI_ResetCharacterListBoxes( void ) } } -const char *saberSingleHiltInfo [MAX_SABER_HILTS]; -const char *saberStaffHiltInfo [MAX_SABER_HILTS]; +const char *saberSingleHiltInfo[MAX_SABER_HILTS]; +const char *saberStaffHiltInfo[MAX_SABER_HILTS]; -qboolean UI_SaberProperNameForSaber( const char *saberName, char *saberProperName ); -void WP_SaberGetHiltInfo( const char *singleHilts[MAX_SABER_HILTS], const char *staffHilts[MAX_SABER_HILTS] ); +qboolean UI_SaberProperNameForSaber(const char *saberName, char *saberProperName); +void WP_SaberGetHiltInfo(const char *singleHilts[MAX_SABER_HILTS], const char *staffHilts[MAX_SABER_HILTS]); -static void UI_UpdateCharacter( qboolean changedModel ) -{ +static void UI_UpdateCharacter(qboolean changedModel) { menuDef_t *menu; itemDef_t *item; char modelPath[MAX_QPATH]; - int animRunLength; + int animRunLength; - menu = Menu_GetFocused(); // Get current menu + menu = Menu_GetFocused(); // Get current menu - if (!menu) - { + if (!menu) { return; } - item = (itemDef_t *) Menu_FindItemByName(menu, "character"); + item = (itemDef_t *)Menu_FindItemByName(menu, "character"); - if (!item) - { - Com_Error( ERR_FATAL, "UI_UpdateCharacter: Could not find item (character) in menu (%s)", menu->window.name); + if (!item) { + Com_Error(ERR_FATAL, "UI_UpdateCharacter: Could not find item (character) in menu (%s)", menu->window.name); } - ItemParse_model_g2anim_go( item, ui_char_anim.string ); + ItemParse_model_g2anim_go(item, ui_char_anim.string); - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", UI_Cvar_VariableString ( "ui_char_model" ) ); - ItemParse_asset_model_go( item, modelPath, &animRunLength ); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", UI_Cvar_VariableString("ui_char_model")); + ItemParse_asset_model_go(item, modelPath, &animRunLength); - if ( changedModel ) - {//set all skins to first skin since we don't know you always have all skins - //FIXME: could try to keep the same spot in each list as you swtich models - UI_FeederSelection(FEEDER_PLAYER_SKIN_HEAD, 0, item); //fixme, this is not really the right item!! + if (changedModel) { // set all skins to first skin since we don't know you always have all skins + // FIXME: could try to keep the same spot in each list as you swtich models + UI_FeederSelection(FEEDER_PLAYER_SKIN_HEAD, 0, item); // fixme, this is not really the right item!! UI_FeederSelection(FEEDER_PLAYER_SKIN_TORSO, 0, item); UI_FeederSelection(FEEDER_PLAYER_SKIN_LEGS, 0, item); UI_FeederSelection(FEEDER_COLORCHOICES, 0, item); @@ -5574,29 +5064,24 @@ static void UI_UpdateCharacter( qboolean changedModel ) UI_CheckServerName ================== */ -static void UI_CheckServerName( void ) -{ - qboolean changed = qfalse; +static void UI_CheckServerName(void) { + qboolean changed = qfalse; char hostname[MAX_HOSTNAMELENGTH] = {0}; char *c = hostname; - trap->Cvar_VariableStringBuffer( "sv_hostname", hostname, sizeof( hostname ) ); + trap->Cvar_VariableStringBuffer("sv_hostname", hostname, sizeof(hostname)); - while( *c ) - { - if ( (*c == '\\') || (*c == ';') || (*c == '"')) - { + while (*c) { + if ((*c == '\\') || (*c == ';') || (*c == '"')) { *c = '.'; changed = qtrue; } c++; } - if( changed ) - { - trap->Cvar_Set("sv_hostname", hostname ); + if (changed) { + trap->Cvar_Set("sv_hostname", hostname); } - } /* @@ -5604,30 +5089,26 @@ static void UI_CheckServerName( void ) UI_CheckPassword ================== */ -static qboolean UI_CheckPassword( void ) -{ +static qboolean UI_CheckPassword(void) { static char info[MAX_STRING_CHARS]; int index = uiInfo.serverStatus.currentServer; - if( (index < 0) || (index >= uiInfo.serverStatus.numDisplayServers) ) - { // warning? + if ((index < 0) || (index >= uiInfo.serverStatus.numDisplayServers)) { // warning? return qfalse; } trap->LAN_GetServerInfo(UI_SourceForLAN(), uiInfo.serverStatus.displayServers[index], info, MAX_STRING_CHARS); - if ( atoi(Info_ValueForKey(info, "needpass")) ) - { + if (atoi(Info_ValueForKey(info, "needpass"))) { Menus_OpenByName("password_request"); return qfalse; - } // This isn't going to make it (too late in dev), like James said I should check to see when we receive // a packet *if* we do indeed get a 0 ping just make it 1 so then a 0 ping is guaranteed to be bad /* // also check ping! - ping = atoi(Info_ValueForKey(info, "ping")); + ping = atoi(Info_ValueForKey(info, "ping")); // NOTE : PING -- it's very questionable as to whether a ping of < 0 or <= 0 indicates a bad server // what I do know, is that getting "ping" from the ServerInfo on a bad server returns 0. // So I'm left with no choice but to not allow you to enter a server with a ping of 0 @@ -5646,159 +5127,132 @@ static qboolean UI_CheckPassword( void ) UI_JoinServer ================== */ -static void UI_JoinServer( void ) -{ +static void UI_JoinServer(void) { char buff[1024] = {0}; -// trap->Cvar_Set("cg_thirdPerson", "0"); + // trap->Cvar_Set("cg_thirdPerson", "0"); trap->Cvar_Set("cg_cameraOrbit", "0"); trap->Cvar_Set("ui_singlePlayerActive", "0"); - if (uiInfo.serverStatus.currentServer >= 0 && uiInfo.serverStatus.currentServer < uiInfo.serverStatus.numDisplayServers) - { - trap->LAN_GetServerAddressString(UI_SourceForLAN()/*ui_netSource.integer*/, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, sizeof( buff ) ); - trap->Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", buff ) ); + if (uiInfo.serverStatus.currentServer >= 0 && uiInfo.serverStatus.currentServer < uiInfo.serverStatus.numDisplayServers) { + trap->LAN_GetServerAddressString(UI_SourceForLAN() /*ui_netSource.integer*/, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], + buff, sizeof(buff)); + trap->Cmd_ExecuteText(EXEC_APPEND, va("connect %s\n", buff)); } - } -int UI_SiegeClassNum( siegeClass_t *scl ) { - int i=0; - for ( i=0; iCvar_Set(va("ui_class_weapon%i", i), "gfx/2d/select"); i++; } - //now for inventory items + // now for inventory items i = 0; - while (i < HI_NUM_HOLDABLE) - { + while (i < HI_NUM_HOLDABLE) { trap->Cvar_Set(va("ui_class_item%i", i), "gfx/2d/select"); i++; } - //now for force powers + // now for force powers i = 0; - while (i < NUM_FORCE_POWERS) - { + while (i < NUM_FORCE_POWERS) { trap->Cvar_Set(va("ui_class_power%i", i), "gfx/2d/select"); i++; } - //now health and armor + // now health and armor trap->Cvar_Set("ui_class_health", "0"); trap->Cvar_Set("ui_class_armor", "0"); trap->Cvar_Set("ui_class_icon", ""); - if (!scl) - { //no select? + if (!scl) { // no select? return; } - //set cvars for which weaps we have + // set cvars for which weaps we have i = 0; - trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with - while (i < WP_NUM_WEAPONS) - { + trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with + while (i < WP_NUM_WEAPONS) { - if (scl->weapons & (1<weapons & (1 << i)) { + if (i == WP_SABER) { // we want to see what kind of saber they have, and set the cvar based on that char saberType[1024]; - if (scl->saber1[0] && - scl->saber2[0]) - { - Q_strncpyz(saberType, "gfx/hud/w_icon_duallightsaber", sizeof( saberType ) ); - } //fixme: need saber data access on ui to determine if staff, "gfx/hud/w_icon_saberstaff" - else - { + if (scl->saber1[0] && scl->saber2[0]) { + Q_strncpyz(saberType, "gfx/hud/w_icon_duallightsaber", sizeof(saberType)); + } // fixme: need saber data access on ui to determine if staff, "gfx/hud/w_icon_saberstaff" + else { char buf[1024]; - if (scl->saber1[0] && UI_SaberTypeForSaber(scl->saber1, buf)) - { - if ( !Q_stricmp( buf, "SABER_STAFF" ) ) - { - Q_strncpyz(saberType,"gfx/hud/w_icon_saberstaff", sizeof( saberType ) ); - } - else - { - Q_strncpyz(saberType,"gfx/hud/w_icon_lightsaber", sizeof( saberType ) ); + if (scl->saber1[0] && UI_SaberTypeForSaber(scl->saber1, buf)) { + if (!Q_stricmp(buf, "SABER_STAFF")) { + Q_strncpyz(saberType, "gfx/hud/w_icon_saberstaff", sizeof(saberType)); + } else { + Q_strncpyz(saberType, "gfx/hud/w_icon_lightsaber", sizeof(saberType)); } - } - else - { - Q_strncpyz(saberType,"gfx/hud/w_icon_lightsaber", sizeof( saberType ) ); + } else { + Q_strncpyz(saberType, "gfx/hud/w_icon_lightsaber", sizeof(saberType)); } } trap->Cvar_Set(va("ui_class_weapon%i", count), saberType); trap->Cvar_Set(va("ui_class_weapondesc%i", count), "@MENUS_AN_ELEGANT_WEAPON_FOR"); count++; - trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with - } - else - { - gitem_t *item = BG_FindItemForWeapon( i ); + trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with + } else { + gitem_t *item = BG_FindItemForWeapon(i); trap->Cvar_Set(va("ui_class_weapon%i", count), item->icon); trap->Cvar_Set(va("ui_class_weapondesc%i", count), item->description); count++; - trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with + trap->Cvar_Set(va("ui_class_weapondesc%i", count), " "); // Blank it out to start with } } i++; } - //now for inventory items + // now for inventory items i = 0; count = 0; - while (i < HI_NUM_HOLDABLE) - { - if (scl->invenItems & (1<invenItems & (1 << i)) { gitem_t *item = BG_FindItemForHoldable(i); trap->Cvar_Set(va("ui_class_item%i", count), item->icon); trap->Cvar_Set(va("ui_class_itemdesc%i", count), item->description); count++; - } - else - { + } else { trap->Cvar_Set(va("ui_class_itemdesc%i", count), " "); } i++; } - //now for force powers + // now for force powers i = 0; count = 0; - while (i < NUM_FORCE_POWERS) - { - trap->Cvar_Set(va("ui_class_powerlevel%i", i), "0"); // Zero this out to start. - if (i<9) - { - trap->Cvar_Set(va("ui_class_powerlevelslot%i", i), "0"); // Zero this out to start. + while (i < NUM_FORCE_POWERS) { + trap->Cvar_Set(va("ui_class_powerlevel%i", i), "0"); // Zero this out to start. + if (i < 9) { + trap->Cvar_Set(va("ui_class_powerlevelslot%i", i), "0"); // Zero this out to start. } - if (scl->forcePowerLevels[i]) - { - trap->Cvar_Set(va("ui_class_powerlevel%i", count), va("%i",scl->forcePowerLevels[i])); + if (scl->forcePowerLevels[i]) { + trap->Cvar_Set(va("ui_class_powerlevel%i", count), va("%i", scl->forcePowerLevels[i])); trap->Cvar_Set(va("ui_class_power%i", count), HolocronIcons[i]); count++; } @@ -5806,44 +5260,35 @@ void UI_SiegeSetCvarsForClass( siegeClass_t *scl ) { i++; } - //now health and armor + // now health and armor trap->Cvar_Set("ui_class_health", va("%i", scl->maxhealth)); trap->Cvar_Set("ui_class_armor", va("%i", scl->maxarmor)); trap->Cvar_Set("ui_class_speed", va("%3.2f", scl->speed)); - //now get the icon path based on the shader index - if (scl->classShader) - { + // now get the icon path based on the shader index + if (scl->classShader) { trap->R_ShaderNameFromIndex(shader, scl->classShader); - } - else - { //no shader + } else { // no shader shader[0] = 0; } trap->Cvar_Set("ui_class_icon", shader); } static int g_siegedFeederForcedSet = 0; -void UI_UpdateCvarsForClass(const int team,const int baseClass,const int index) -{ - siegeClass_t *holdClass=0; +void UI_UpdateCvarsForClass(const int team, const int baseClass, const int index) { + siegeClass_t *holdClass = 0; char *holdBuf; // Is it a valid team - if ((team == SIEGETEAM_TEAM1) || - (team == SIEGETEAM_TEAM2)) - { + if ((team == SIEGETEAM_TEAM1) || (team == SIEGETEAM_TEAM2)) { // Is it a valid base class? - if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) - { + if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) { // A valid index? - if ((index>=0) && (index < BG_SiegeCountBaseClass( team, baseClass ))) - { - if (!g_siegedFeederForcedSet) - { - holdClass = BG_GetClassOnBaseClass( team, baseClass, index); - if (holdClass) //clicked a valid item + if ((index >= 0) && (index < BG_SiegeCountBaseClass(team, baseClass))) { + if (!g_siegedFeederForcedSet) { + holdClass = BG_GetClassOnBaseClass(team, baseClass, index); + if (holdClass) // clicked a valid item { g_UIGloballySelectedSiegeClass = UI_SiegeClassNum(holdClass); trap->Cvar_Set("ui_classDesc", g_UIClassDescriptions[g_UIGloballySelectedSiegeClass].desc); @@ -5852,63 +5297,60 @@ void UI_UpdateCvarsForClass(const int team,const int baseClass,const int index) UI_SiegeSetCvarsForClass(holdClass); holdBuf = BG_GetUIPortraitFile(team, baseClass, index); - if (holdBuf) - { - trap->Cvar_Set("ui_classPortrait",holdBuf); + if (holdBuf) { + trap->Cvar_Set("ui_classPortrait", holdBuf); } } } g_siegedFeederForcedSet = 0; - } - else - { + } else { trap->Cvar_Set("ui_classDesc", " "); } } } - } -void UI_ClampMaxPlayers( void ) { +void UI_ClampMaxPlayers(void) { // duel requires 2 players - if ( uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_DUEL ) { - if ( (int)trap->Cvar_VariableValue( "sv_maxClients" ) < 2 ) - trap->Cvar_Set( "sv_maxClients", "2" ); + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_DUEL) { + if ((int)trap->Cvar_VariableValue("sv_maxClients") < 2) + trap->Cvar_Set("sv_maxClients", "2"); } // power duel requires 3 players - else if ( uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_POWERDUEL ) { - if ( (int)trap->Cvar_VariableValue( "sv_maxClients" ) < 3 ) - trap->Cvar_Set( "sv_maxClients", "3" ); + else if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_POWERDUEL) { + if ((int)trap->Cvar_VariableValue("sv_maxClients") < 3) + trap->Cvar_Set("sv_maxClients", "3"); } // can never exceed MAX_CLIENTS - if ( (int)trap->Cvar_VariableValue( "sv_maxClients" ) > MAX_CLIENTS ) { - trap->Cvar_Set( "sv_maxClients", XSTRING(MAX_CLIENTS) ); + if ((int)trap->Cvar_VariableValue("sv_maxClients") > MAX_CLIENTS) { + trap->Cvar_Set("sv_maxClients", XSTRING(MAX_CLIENTS)); } } -void UI_UpdateSiegeStatusIcons( void ) { - menuDef_t *menu = Menu_GetFocused(); +void UI_UpdateSiegeStatusIcons(void) { + menuDef_t *menu = Menu_GetFocused(); - if ( menu ) { - int i=0; - for ( i= 0; i< 7; i++ ) Menu_SetItemBackground( menu, va( "wpnicon0%d", i ), va( "*ui_class_weapon%d", i ) ); - for ( i= 0; i< 7; i++ ) Menu_SetItemBackground( menu, va( "itemicon0%d", i ), va( "*ui_class_item%d", i ) ); - for ( i= 0; i<10; i++ ) Menu_SetItemBackground( menu, va( "forceicon0%d", i ), va( "*ui_class_power%d", i ) ); - for ( i=10; i<15; i++ ) Menu_SetItemBackground( menu, va( "forceicon%d", i ), va( "*ui_class_power%d", i ) ); + if (menu) { + int i = 0; + for (i = 0; i < 7; i++) + Menu_SetItemBackground(menu, va("wpnicon0%d", i), va("*ui_class_weapon%d", i)); + for (i = 0; i < 7; i++) + Menu_SetItemBackground(menu, va("itemicon0%d", i), va("*ui_class_item%d", i)); + for (i = 0; i < 10; i++) + Menu_SetItemBackground(menu, va("forceicon0%d", i), va("*ui_class_power%d", i)); + for (i = 10; i < 15; i++) + Menu_SetItemBackground(menu, va("forceicon%d", i), va("*ui_class_power%d", i)); } } -static void UI_RunMenuScript(char **args) -{ +static void UI_RunMenuScript(char **args) { const char *name, *name2; char buff[1024]; - if (String_Parse(args, &name)) - { - if (Q_stricmp(name, "StartServer") == 0) - { + if (String_Parse(args, &name)) { + if (Q_stricmp(name, "StartServer") == 0) { int i, added = 0; float skill; int warmupTime = 0; @@ -5921,88 +5363,77 @@ static void UI_RunMenuScript(char **args) // trap->Cvar_Set("ui_singlePlayerActive", "0"); // if a solo game is started, automatically turn dedicated off here (don't want to do it in the menu, might get annoying) - if( trap->Cvar_VariableValue( "ui_singlePlayerActive" ) ) - { - trap->Cvar_Set( "dedicated", "0" ); - } - else - { - trap->Cvar_SetValue( "dedicated", Com_Clamp( 0, 2, ui_dedicated.integer ) ); + if (trap->Cvar_VariableValue("ui_singlePlayerActive")) { + trap->Cvar_Set("dedicated", "0"); + } else { + trap->Cvar_SetValue("dedicated", Com_Clamp(0, 2, ui_dedicated.integer)); } - trap->Cvar_SetValue( "g_gametype", Com_Clamp( 0, GT_MAX_GAME_TYPE, uiInfo.gameTypes[ui_netGametype.integer].gtEnum ) ); - //trap->Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName")); - //trap->Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName")); - trap->Cmd_ExecuteText( EXEC_APPEND, va( "wait ; wait ; map %s\n", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName ) ); - skill = trap->Cvar_VariableValue( "g_spSkill" ); + trap->Cvar_SetValue("g_gametype", Com_Clamp(0, GT_MAX_GAME_TYPE, uiInfo.gameTypes[ui_netGametype.integer].gtEnum)); + // trap->Cvar_Set("g_redTeam", UI_Cvar_VariableString("ui_teamName")); + // trap->Cvar_Set("g_blueTeam", UI_Cvar_VariableString("ui_opponentName")); + trap->Cmd_ExecuteText(EXEC_APPEND, va("wait ; wait ; map %s\n", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName)); + skill = trap->Cvar_VariableValue("g_spSkill"); - //Cap the warmup values in case the user tries a dumb setting. - warmupTime = trap->Cvar_VariableValue( "g_warmup" ); - doWarmup = trap->Cvar_VariableValue( "g_doWarmup" ); + // Cap the warmup values in case the user tries a dumb setting. + warmupTime = trap->Cvar_VariableValue("g_warmup"); + doWarmup = trap->Cvar_VariableValue("g_doWarmup"); - if (doWarmup && warmupTime < 1) - { + if (doWarmup && warmupTime < 1) { trap->Cvar_Set("g_doWarmup", "0"); } - if (warmupTime < 5) - { + if (warmupTime < 5) { trap->Cvar_Set("g_warmup", "5"); } - if (warmupTime > 120) - { + if (warmupTime > 120) { trap->Cvar_Set("g_warmup", "120"); } - if (trap->Cvar_VariableValue( "g_gametype" ) == GT_DUEL || - trap->Cvar_VariableValue( "g_gametype" ) == GT_POWERDUEL) - { //always set fraglimit 1 when starting a duel game + if (trap->Cvar_VariableValue("g_gametype") == GT_DUEL || + trap->Cvar_VariableValue("g_gametype") == GT_POWERDUEL) { // always set fraglimit 1 when starting a duel game trap->Cvar_Set("fraglimit", "1"); trap->Cvar_Set("timelimit", "0"); } - for (i = 0; i < PLAYERS_PER_TEAM; i++) - { - int bot = trap->Cvar_VariableValue( va("ui_blueteam%i", i+1)); - int maxcl = trap->Cvar_VariableValue( "sv_maxClients" ); + for (i = 0; i < PLAYERS_PER_TEAM; i++) { + int bot = trap->Cvar_VariableValue(va("ui_blueteam%i", i + 1)); + int maxcl = trap->Cvar_VariableValue("sv_maxClients"); - if (bot > 1) - { - int numval = i+1; + if (bot > 1) { + int numval = i + 1; numval *= 2; numval -= 1; - if (numval <= maxcl) - { + if (numval <= maxcl) { if (ui_actualNetGametype.integer >= GT_TEAM) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s\n", UI_GetBotNameByNumber(bot-2), skill, "Blue"); + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s\n", UI_GetBotNameByNumber(bot - 2), skill, "Blue"); } else { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f \n", UI_GetBotNameByNumber(bot-2), skill); + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f \n", UI_GetBotNameByNumber(bot - 2), skill); } - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); added++; } } - bot = trap->Cvar_VariableValue( va("ui_redteam%i", i+1)); + bot = trap->Cvar_VariableValue(va("ui_redteam%i", i + 1)); if (bot > 1) { - int numval = i+1; + int numval = i + 1; numval *= 2; - if (numval <= maxcl) - { + if (numval <= maxcl) { if (ui_actualNetGametype.integer >= GT_TEAM) { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f %s\n", UI_GetBotNameByNumber(bot-2), skill, "Red"); + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f %s\n", UI_GetBotNameByNumber(bot - 2), skill, "Red"); } else { - Com_sprintf( buff, sizeof(buff), "addbot \"%s\" %f \n", UI_GetBotNameByNumber(bot-2), skill); + Com_sprintf(buff, sizeof(buff), "addbot \"%s\" %f \n", UI_GetBotNameByNumber(bot - 2), skill); } - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); added++; } } - if (added >= maxcl) - { //this means the client filled up all their slots in the UI with bots. So stretch out an extra slot for them, and then stop adding bots. - trap->Cvar_Set("sv_maxClients", va("%i", added+1)); + if (added >= maxcl) { // this means the client filled up all their slots in the UI with bots. So stretch out an extra slot for them, and then + // stop adding bots. + trap->Cvar_Set("sv_maxClients", va("%i", added + 1)); break; } } @@ -6015,10 +5446,10 @@ static void UI_RunMenuScript(char **args) UI_GameType_HandleKey(0, 0, A_MOUSE1, qfalse); UI_GameType_HandleKey(0, 0, A_MOUSE2, qfalse); } else if (Q_stricmp(name, "resetDefaults") == 0) { - trap->Cmd_ExecuteText( EXEC_APPEND, "cvar_restart\n"); + trap->Cmd_ExecuteText(EXEC_APPEND, "cvar_restart\n"); Controls_SetDefaults(); - trap->Cmd_ExecuteText( EXEC_APPEND, "exec mpdefault.cfg\n"); - trap->Cmd_ExecuteText( EXEC_APPEND, "vid_restart\n" ); + trap->Cmd_ExecuteText(EXEC_APPEND, "exec mpdefault.cfg\n"); + trap->Cmd_ExecuteText(EXEC_APPEND, "vid_restart\n"); } else if (Q_stricmp(name, "loadArenas") == 0) { UI_LoadArenas(); @@ -6049,15 +5480,15 @@ static void UI_RunMenuScript(char **args) if (uiInfo.previewMovie >= 0) { trap->CIN_StopCinematic(uiInfo.previewMovie); } - trap->Cmd_ExecuteText( EXEC_APPEND, va("cinematic %s.roq 2\n", uiInfo.movieList[uiInfo.movieIndex])); + trap->Cmd_ExecuteText(EXEC_APPEND, va("cinematic %s.roq 2\n", uiInfo.movieList[uiInfo.movieIndex])); } else if (Q_stricmp(name, "RunMod") == 0) { - trap->Cvar_Set( "fs_game", uiInfo.modList[uiInfo.modIndex].modName); - trap->Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" ); + trap->Cvar_Set("fs_game", uiInfo.modList[uiInfo.modIndex].modName); + trap->Cmd_ExecuteText(EXEC_APPEND, "vid_restart;"); } else if (Q_stricmp(name, "RunDemo") == 0) { - trap->Cmd_ExecuteText( EXEC_APPEND, va("demo \"%s\"\n", uiInfo.demoList[uiInfo.demoIndex])); + trap->Cmd_ExecuteText(EXEC_APPEND, va("demo \"%s\"\n", uiInfo.demoList[uiInfo.demoIndex])); } else if (Q_stricmp(name, "Quake3") == 0) { - trap->Cvar_Set( "fs_game", ""); - trap->Cmd_ExecuteText( EXEC_APPEND, "vid_restart;" ); + trap->Cvar_Set("fs_game", ""); + trap->Cmd_ExecuteText(EXEC_APPEND, "vid_restart;"); } else if (Q_stricmp(name, "closeJoin") == 0) { if (uiInfo.serverStatus.refreshActive) { UI_StopServerRefresh(); @@ -6075,16 +5506,17 @@ static void UI_RunMenuScript(char **args) uiInfo.nextServerStatusRefresh = 0; uiInfo.nextFindPlayerRefresh = 0; } else if (Q_stricmp(name, "UpdateFilter") == 0) { - trap->Cvar_Update( &ui_netSource ); + trap->Cvar_Update(&ui_netSource); if (ui_netSource.integer == UIAS_LOCAL || !uiInfo.serverStatus.numDisplayServers) { UI_StartServerRefresh(qtrue); } UI_BuildServerDisplayList(qtrue); - UI_FeederSelection(FEEDER_SERVERS, 0, NULL ); + UI_FeederSelection(FEEDER_SERVERS, 0, NULL); UI_LoadMods(); } else if (Q_stricmp(name, "ServerStatus") == 0) { - trap->LAN_GetServerAddressString(UI_SourceForLAN(), uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], uiInfo.serverStatusAddress, sizeof(uiInfo.serverStatusAddress)); + trap->LAN_GetServerAddressString(UI_SourceForLAN(), uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], + uiInfo.serverStatusAddress, sizeof(uiInfo.serverStatusAddress)); UI_BuildServerStatus(qtrue); } else if (Q_stricmp(name, "FoundPlayerServerStatus") == 0) { Q_strncpyz(uiInfo.serverStatusAddress, uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer], sizeof(uiInfo.serverStatusAddress)); @@ -6095,66 +5527,46 @@ static void UI_RunMenuScript(char **args) // clear the displayed server status info uiInfo.serverStatusInfo.numLines = 0; Menu_SetFeederSelection(NULL, FEEDER_FINDPLAYER, 0, NULL); - } - else if (Q_stricmp(name, "checkservername") == 0) - { + } else if (Q_stricmp(name, "checkservername") == 0) { UI_CheckServerName(); - } - else if (Q_stricmp(name, "checkpassword") == 0) - { - if( UI_CheckPassword() ) - { + } else if (Q_stricmp(name, "checkpassword") == 0) { + if (UI_CheckPassword()) { UI_JoinServer(); } - } - else if (Q_stricmp(name, "JoinServer") == 0) - { + } else if (Q_stricmp(name, "JoinServer") == 0) { UI_JoinServer(); - } - else if (Q_stricmp(name, "FoundPlayerJoinServer") == 0) { + } else if (Q_stricmp(name, "FoundPlayerJoinServer") == 0) { trap->Cvar_Set("ui_singlePlayerActive", "0"); if (uiInfo.currentFoundPlayerServer >= 0 && uiInfo.currentFoundPlayerServer < uiInfo.numFoundPlayerServers) { - trap->Cmd_ExecuteText( EXEC_APPEND, va( "connect %s\n", uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer] ) ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("connect %s\n", uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer])); } } else if (Q_stricmp(name, "Quit") == 0) { trap->Cvar_Set("ui_singlePlayerActive", "0"); - trap->Cmd_ExecuteText( EXEC_NOW, "quit"); + trap->Cmd_ExecuteText(EXEC_NOW, "quit"); } else if (Q_stricmp(name, "Controls") == 0) { - trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Cvar_Set("cl_paused", "1"); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("setup_menu2"); - } - else if (Q_stricmp(name, "Leave") == 0) - { - trap->Cmd_ExecuteText( EXEC_APPEND, "disconnect\n" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + } else if (Q_stricmp(name, "Leave") == 0) { + trap->Cmd_ExecuteText(EXEC_APPEND, "disconnect\n"); + trap->Key_SetCatcher(KEYCATCH_UI); Menus_CloseAll(); Menus_ActivateByName("main"); - } - else if (Q_stricmp(name, "getvideosetup") == 0) - { - UI_GetVideoSetup ( ); - } - else if (Q_stricmp(name, "getsaberhiltinfo") == 0) - { + } else if (Q_stricmp(name, "getvideosetup") == 0) { + UI_GetVideoSetup(); + } else if (Q_stricmp(name, "getsaberhiltinfo") == 0) { WP_SaberGetHiltInfo(saberSingleHiltInfo, saberStaffHiltInfo); } // On the solo game creation screen, we can't see siege maps - else if (Q_stricmp(name, "checkforsiege") == 0) - { - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) - { + else if (Q_stricmp(name, "checkforsiege") == 0) { + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) { // fake out the handler to advance to the next game type UI_NetGameType_HandleKey(0, NULL, A_MOUSE1); } - } - else if (Q_stricmp(name, "updatevideosetup") == 0) - { - UI_UpdateVideoSetup ( ); - } - else if (Q_stricmp(name, "ServerSort") == 0) - { + } else if (Q_stricmp(name, "updatevideosetup") == 0) { + UI_UpdateVideoSetup(); + } else if (Q_stricmp(name, "ServerSort") == 0) { int sortColumn; if (Int_Parse(args, &sortColumn)) { // if same column we're already sorting on then flip the direction @@ -6169,103 +5581,89 @@ static void UI_RunMenuScript(char **args) } else if (Q_stricmp(name, "SkirmishStart") == 0) { UI_StartSkirmish(qfalse); } else if (Q_stricmp(name, "closeingame") == 0) { - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); Menus_CloseAll(); } else if (Q_stricmp(name, "voteMap") == 0) { - if (ui_currentNetMap.integer >=0 && ui_currentNetMap.integer < uiInfo.mapCount) { - trap->Cmd_ExecuteText( EXEC_APPEND, va("callvote map %s\n",uiInfo.mapList[ui_currentNetMap.integer].mapLoadName) ); + if (ui_currentNetMap.integer >= 0 && ui_currentNetMap.integer < uiInfo.mapCount) { + trap->Cmd_ExecuteText(EXEC_APPEND, va("callvote map %s\n", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName)); } } else if (Q_stricmp(name, "voteKick") == 0) { if (uiInfo.playerIndex >= 0 && uiInfo.playerIndex < uiInfo.playerCount) { - //trap->Cmd_ExecuteText( EXEC_APPEND, va("callvote kick \"%s\"\n",uiInfo.playerNames[uiInfo.playerIndex]) ); - trap->Cmd_ExecuteText( EXEC_APPEND, va("callvote clientkick \"%i\"\n",uiInfo.playerIndexes[uiInfo.playerIndex]) ); + // trap->Cmd_ExecuteText( EXEC_APPEND, va("callvote kick \"%s\"\n",uiInfo.playerNames[uiInfo.playerIndex]) ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("callvote clientkick \"%i\"\n", uiInfo.playerIndexes[uiInfo.playerIndex])); } } else if (Q_stricmp(name, "voteGame") == 0) { if (ui_netGametype.integer >= 0 && ui_netGametype.integer < uiInfo.numGameTypes) { - trap->Cmd_ExecuteText( EXEC_APPEND, va("callvote g_gametype %i\n",uiInfo.gameTypes[ui_netGametype.integer].gtEnum) ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("callvote g_gametype %i\n", uiInfo.gameTypes[ui_netGametype.integer].gtEnum)); } } else if (Q_stricmp(name, "voteLeader") == 0) { if (uiInfo.teamIndex >= 0 && uiInfo.teamIndex < uiInfo.myTeamCount) { - trap->Cmd_ExecuteText( EXEC_APPEND, va("callteamvote leader \"%s\"\n",uiInfo.teamNames[uiInfo.teamIndex]) ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("callteamvote leader \"%s\"\n", uiInfo.teamNames[uiInfo.teamIndex])); } } else if (Q_stricmp(name, "addBot") == 0) { if (trap->Cvar_VariableValue("g_gametype") >= GT_TEAM) { - trap->Cmd_ExecuteText( EXEC_APPEND, va("addbot \"%s\" %i %s\n", UI_GetBotNameByNumber(uiInfo.botIndex), uiInfo.skillIndex+1, (uiInfo.redBlue == 0) ? "Red" : "Blue") ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("addbot \"%s\" %i %s\n", UI_GetBotNameByNumber(uiInfo.botIndex), uiInfo.skillIndex + 1, + (uiInfo.redBlue == 0) ? "Red" : "Blue")); } else { - trap->Cmd_ExecuteText( EXEC_APPEND, va("addbot \"%s\" %i %s\n", UI_GetBotNameByNumber(uiInfo.botIndex), uiInfo.skillIndex+1, (uiInfo.redBlue == 0) ? "Red" : "Blue") ); + trap->Cmd_ExecuteText(EXEC_APPEND, va("addbot \"%s\" %i %s\n", UI_GetBotNameByNumber(uiInfo.botIndex), uiInfo.skillIndex + 1, + (uiInfo.redBlue == 0) ? "Red" : "Blue")); } - } else if (Q_stricmp(name, "addFavorite") == 0) - { - if (ui_netSource.integer != UIAS_FAVORITES) - { + } else if (Q_stricmp(name, "addFavorite") == 0) { + if (ui_netSource.integer != UIAS_FAVORITES) { char name[MAX_HOSTNAMELENGTH] = {0}; char addr[MAX_ADDRESSLENGTH] = {0}; int res; trap->LAN_GetServerInfo(UI_SourceForLAN(), uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, MAX_STRING_CHARS); name[0] = addr[0] = '\0'; - Q_strncpyz(name, Info_ValueForKey(buff, "hostname"), sizeof( name ) ); - Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), sizeof( addr ) ); - if (strlen(name) > 0 && strlen(addr) > 0) - { + Q_strncpyz(name, Info_ValueForKey(buff, "hostname"), sizeof(name)); + Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), sizeof(addr)); + if (strlen(name) > 0 && strlen(addr) > 0) { res = trap->LAN_AddServer(AS_FAVORITES, name, addr); - if (res == 0) - { + if (res == 0) { // server already in the list Com_Printf("Favorite already in list\n"); - } - else if (res == -1) - { + } else if (res == -1) { // list full Com_Printf("Favorite list full\n"); - } - else - { + } else { // successfully added Com_Printf("Added favorite server %s\n", addr); } } } - } - else if (Q_stricmp(name, "deleteFavorite") == 0) - { - if (ui_netSource.integer == UIAS_FAVORITES) - { + } else if (Q_stricmp(name, "deleteFavorite") == 0) { + if (ui_netSource.integer == UIAS_FAVORITES) { char addr[MAX_ADDRESSLENGTH] = {0}; trap->LAN_GetServerInfo(AS_FAVORITES, uiInfo.serverStatus.displayServers[uiInfo.serverStatus.currentServer], buff, MAX_STRING_CHARS); addr[0] = '\0'; - Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), sizeof( addr ) ); - if (strlen(addr) > 0) - { + Q_strncpyz(addr, Info_ValueForKey(buff, "addr"), sizeof(addr)); + if (strlen(addr) > 0) { trap->LAN_RemoveServer(AS_FAVORITES, addr); } } - } - else if (Q_stricmp(name, "createFavorite") == 0) - { + } else if (Q_stricmp(name, "createFavorite") == 0) { // if (ui_netSource.integer == UIAS_FAVORITES) - //rww - don't know why this check was here.. why would you want to only add new favorites when the filter was favorites? + // rww - don't know why this check was here.. why would you want to only add new favorites when the filter was favorites? { char name[MAX_HOSTNAMELENGTH] = {0}; char addr[MAX_ADDRESSLENGTH] = {0}; int res; name[0] = addr[0] = '\0'; - Q_strncpyz(name, UI_Cvar_VariableString("ui_favoriteName"), sizeof( name ) ); - Q_strncpyz(addr, UI_Cvar_VariableString("ui_favoriteAddress"), sizeof( addr ) ); + Q_strncpyz(name, UI_Cvar_VariableString("ui_favoriteName"), sizeof(name)); + Q_strncpyz(addr, UI_Cvar_VariableString("ui_favoriteAddress"), sizeof(addr)); if (/*strlen(name) > 0 &&*/ strlen(addr) > 0) { res = trap->LAN_AddServer(AS_FAVORITES, name, addr); if (res == 0) { // server already in the list Com_Printf("Favorite already in list\n"); - } - else if (res == -1) { + } else if (res == -1) { // list full Com_Printf("Favorite list full\n"); - } - else { + } else { // successfully added Com_Printf("Added favorite server %s\n", addr); } @@ -6276,23 +5674,23 @@ static void UI_RunMenuScript(char **args) if (String_Parse(args, &orders)) { int selectedPlayer = trap->Cvar_VariableValue("cg_selectedPlayer"); if (selectedPlayer < uiInfo.myTeamCount) { - Q_strncpyz( buff, orders, sizeof( buff ) ); - trap->Cmd_ExecuteText( EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer]) ); - trap->Cmd_ExecuteText( EXEC_APPEND, "\n" ); + Q_strncpyz(buff, orders, sizeof(buff)); + trap->Cmd_ExecuteText(EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer])); + trap->Cmd_ExecuteText(EXEC_APPEND, "\n"); } else { int i; for (i = 0; i < uiInfo.myTeamCount; i++) { if (uiInfo.playerNumber == uiInfo.teamClientNums[i]) { continue; } - Com_sprintf( buff, sizeof( buff ), orders, uiInfo.teamClientNums[i] ); - trap->Cmd_ExecuteText( EXEC_APPEND, buff ); - trap->Cmd_ExecuteText( EXEC_APPEND, "\n" ); + Com_sprintf(buff, sizeof(buff), orders, uiInfo.teamClientNums[i]); + trap->Cmd_ExecuteText(EXEC_APPEND, buff); + trap->Cmd_ExecuteText(EXEC_APPEND, "\n"); } } - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); Menus_CloseAll(); } } else if (Q_stricmp(name, "voiceOrdersTeam") == 0) { @@ -6300,12 +5698,12 @@ static void UI_RunMenuScript(char **args) if (String_Parse(args, &orders)) { int selectedPlayer = trap->Cvar_VariableValue("cg_selectedPlayer"); if (selectedPlayer == uiInfo.myTeamCount) { - trap->Cmd_ExecuteText( EXEC_APPEND, orders ); - trap->Cmd_ExecuteText( EXEC_APPEND, "\n" ); + trap->Cmd_ExecuteText(EXEC_APPEND, orders); + trap->Cmd_ExecuteText(EXEC_APPEND, "\n"); } - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); Menus_CloseAll(); } } else if (Q_stricmp(name, "voiceOrders") == 0) { @@ -6313,147 +5711,108 @@ static void UI_RunMenuScript(char **args) if (String_Parse(args, &orders)) { int selectedPlayer = trap->Cvar_VariableValue("cg_selectedPlayer"); - if (selectedPlayer == uiInfo.myTeamCount) - { + if (selectedPlayer == uiInfo.myTeamCount) { selectedPlayer = -1; - Q_strncpyz( buff, orders, sizeof( buff ) ); - trap->Cmd_ExecuteText( EXEC_APPEND, va(buff, selectedPlayer) ); - } - else - { - Q_strncpyz( buff, orders, sizeof( buff ) ); - trap->Cmd_ExecuteText( EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer]) ); + Q_strncpyz(buff, orders, sizeof(buff)); + trap->Cmd_ExecuteText(EXEC_APPEND, va(buff, selectedPlayer)); + } else { + Q_strncpyz(buff, orders, sizeof(buff)); + trap->Cmd_ExecuteText(EXEC_APPEND, va(buff, uiInfo.teamClientNums[selectedPlayer])); } - trap->Cmd_ExecuteText( EXEC_APPEND, "\n" ); + trap->Cmd_ExecuteText(EXEC_APPEND, "\n"); - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); Menus_CloseAll(); } - } - else if (Q_stricmp(name, "setForce") == 0) - { + } else if (Q_stricmp(name, "setForce") == 0) { const char *teamArg; - if (String_Parse(args, &teamArg)) - { - if ( Q_stricmp( "none", teamArg ) == 0 ) - { + if (String_Parse(args, &teamArg)) { + if (Q_stricmp("none", teamArg) == 0) { UI_UpdateClientForcePowers(NULL); - } - else if ( Q_stricmp( "same", teamArg ) == 0 ) - {//stay on current team + } else if (Q_stricmp("same", teamArg) == 0) { // stay on current team int myTeam = (int)(trap->Cvar_VariableValue("ui_myteam")); - if ( myTeam != TEAM_SPECTATOR ) - { - UI_UpdateClientForcePowers(UI_TeamName(myTeam));//will cause him to respawn, if it's been 5 seconds since last one - } - else - { - UI_UpdateClientForcePowers(NULL);//just update powers + if (myTeam != TEAM_SPECTATOR) { + UI_UpdateClientForcePowers(UI_TeamName(myTeam)); // will cause him to respawn, if it's been 5 seconds since last one + } else { + UI_UpdateClientForcePowers(NULL); // just update powers } - } - else - { + } else { UI_UpdateClientForcePowers(teamArg); } - } - else - { + } else { UI_UpdateClientForcePowers(NULL); } - } - else if (Q_stricmp(name, "setsiegeclassandteam") == 0) - { + } else if (Q_stricmp(name, "setsiegeclassandteam") == 0) { int team = (int)trap->Cvar_VariableValue("ui_holdteam"); int oldteam = (int)trap->Cvar_VariableValue("ui_startsiegeteam"); - qboolean goTeam = qtrue; - char newclassString[512]; - char startclassString[512]; + qboolean goTeam = qtrue; + char newclassString[512]; + char startclassString[512]; - trap->Cvar_VariableStringBuffer( "ui_mySiegeClass", newclassString, sizeof(newclassString) ); - trap->Cvar_VariableStringBuffer( "ui_startsiegeclass", startclassString, sizeof(startclassString) ); + trap->Cvar_VariableStringBuffer("ui_mySiegeClass", newclassString, sizeof(newclassString)); + trap->Cvar_VariableStringBuffer("ui_startsiegeclass", startclassString, sizeof(startclassString)); // Was just a spectator - is still just a spectator - if ((oldteam == team) && (oldteam == 3)) - { + if ((oldteam == team) && (oldteam == 3)) { goTeam = qfalse; } // If new team and class match old team and class, just return to the game. - else if (oldteam == team) - { // Classes match? - if (g_UIGloballySelectedSiegeClass != -1) - { - if (!strcmp(startclassString,bgSiegeClasses[g_UIGloballySelectedSiegeClass].name)) - { + else if (oldteam == team) { // Classes match? + if (g_UIGloballySelectedSiegeClass != -1) { + if (!strcmp(startclassString, bgSiegeClasses[g_UIGloballySelectedSiegeClass].name)) { goTeam = qfalse; } } } - if (goTeam) - { - if (team == 1) // Team red + if (goTeam) { + if (team == 1) // Team red { trap->Cvar_Set("ui_team", va("%d", team)); - } - else if (team == 2) // Team blue + } else if (team == 2) // Team blue { trap->Cvar_Set("ui_team", va("%d", team)); - } - else if (team == 3) // Team spectator + } else if (team == 3) // Team spectator { trap->Cvar_Set("ui_team", va("%d", team)); } - if (g_UIGloballySelectedSiegeClass != -1) - { - trap->Cmd_ExecuteText( EXEC_APPEND, va("siegeclass \"%s\"\n", bgSiegeClasses[g_UIGloballySelectedSiegeClass].name) ); + if (g_UIGloballySelectedSiegeClass != -1) { + trap->Cmd_ExecuteText(EXEC_APPEND, va("siegeclass \"%s\"\n", bgSiegeClasses[g_UIGloballySelectedSiegeClass].name)); } } - } - else if (Q_stricmp(name, "setBotButton") == 0) - { + } else if (Q_stricmp(name, "setBotButton") == 0) { UI_SetBotButton(); - } - else if (Q_stricmp(name, "saveTemplate") == 0) { + } else if (Q_stricmp(name, "saveTemplate") == 0) { UI_SaveForceTemplate(); } else if (Q_stricmp(name, "refreshForce") == 0) { UI_UpdateForcePowers(); } else if (Q_stricmp(name, "glCustom") == 0) { trap->Cvar_Set("ui_r_glCustom", "4"); - } - else if (Q_stricmp(name, "setMovesListDefault") == 0) - { + } else if (Q_stricmp(name, "setMovesListDefault") == 0) { uiInfo.movesTitleIndex = 2; - } - else if (Q_stricmp(name, "resetMovesList") == 0) - { + } else if (Q_stricmp(name, "resetMovesList") == 0) { menuDef_t *menu; menu = Menus_FindByName("rulesMenu_moves"); - //update saber models - if (menu) - { - itemDef_t *item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { - UI_SaberAttachToChar( item ); + // update saber models + if (menu) { + itemDef_t *item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { + UI_SaberAttachToChar(item); } } - trap->Cvar_Set( "ui_move_desc", " " ); - } - else if (Q_stricmp(name, "resetcharacterlistboxes") == 0) - { + trap->Cvar_Set("ui_move_desc", " "); + } else if (Q_stricmp(name, "resetcharacterlistboxes") == 0) { UI_ResetCharacterListBoxes(); - } - else if (Q_stricmp(name, "setMoveCharacter") == 0) - { + } else if (Q_stricmp(name, "setMoveCharacter") == 0) { itemDef_t *item; menuDef_t *menu; modelDef_t *modelPtr; - int animRunLength; + int animRunLength; UI_GetCharacterCvars(); @@ -6461,48 +5820,34 @@ static void UI_RunMenuScript(char **args) menu = Menus_FindByName("rulesMenu_moves"); - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { modelPtr = item->typeData.model; - if (modelPtr) - { + if (modelPtr) { char modelPath[MAX_QPATH]; uiInfo.movesBaseAnim = datapadMoveTitleBaseAnims[uiInfo.movesTitleIndex]; - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); - uiInfo.moveAnimTime = 0 ; + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); + uiInfo.moveAnimTime = 0; - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", UI_Cvar_VariableString ( "ui_char_model" ) ); - ItemParse_asset_model_go( item, modelPath, &animRunLength); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", UI_Cvar_VariableString("ui_char_model")); + ItemParse_asset_model_go(item, modelPath, &animRunLength); UI_UpdateCharacterSkin(); - UI_SaberAttachToChar( item ); + UI_SaberAttachToChar(item); } } } - } - else if (Q_stricmp(name, "character") == 0) - { - UI_UpdateCharacter( qfalse ); - } - else if (Q_stricmp(name, "characterchanged") == 0) - { - UI_UpdateCharacter( qtrue ); - } - else if (Q_stricmp(name, "updatecharcvars") == 0 - || (Q_stricmp(name, "updatecharmodel") == 0) ) - { + } else if (Q_stricmp(name, "character") == 0) { + UI_UpdateCharacter(qfalse); + } else if (Q_stricmp(name, "characterchanged") == 0) { + UI_UpdateCharacter(qtrue); + } else if (Q_stricmp(name, "updatecharcvars") == 0 || (Q_stricmp(name, "updatecharmodel") == 0)) { UI_UpdateCharacterCvars(); - } - else if (Q_stricmp(name, "getcharcvars") == 0) - { + } else if (Q_stricmp(name, "getcharcvars") == 0) { UI_GetCharacterCvars(); - } - else if (Q_stricmp(name, "char_skin") == 0) - { + } else if (Q_stricmp(name, "char_skin") == 0) { UI_UpdateCharacterSkin(); } #if 0 @@ -6627,206 +5972,145 @@ static void UI_RunMenuScript(char **args) #endif // If this is siege, change all the bots to humans, because we faked it earlier // swapping humans for bots on the menu - else if (Q_stricmp(name, "setSiegeNoBots") == 0) - { - int blueValue,redValue,i; + else if (Q_stricmp(name, "setSiegeNoBots") == 0) { + int blueValue, redValue, i; - if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) - { - //hmm, I guess I'll set bot_minplayers to 0 here too. -rww + if (uiInfo.gameTypes[ui_netGametype.integer].gtEnum == GT_SIEGE) { + // hmm, I guess I'll set bot_minplayers to 0 here too. -rww trap->Cvar_Set("bot_minplayers", "0"); - for (i=1;i<9;i++) - { - blueValue = trap->Cvar_VariableValue(va("ui_blueteam%i",i )); - if (blueValue>1) - { - trap->Cvar_Set(va("ui_blueteam%i",i ), "1"); + for (i = 1; i < 9; i++) { + blueValue = trap->Cvar_VariableValue(va("ui_blueteam%i", i)); + if (blueValue > 1) { + trap->Cvar_Set(va("ui_blueteam%i", i), "1"); } - redValue = trap->Cvar_VariableValue(va("ui_redteam%i",i )); - if (redValue>1) - { - trap->Cvar_Set(va("ui_redteam%i",i ), "1"); + redValue = trap->Cvar_VariableValue(va("ui_redteam%i", i)); + if (redValue > 1) { + trap->Cvar_Set(va("ui_redteam%i", i), "1"); } - } } - } - else if (Q_stricmp(name, "clearmouseover") == 0) - { + } else if (Q_stricmp(name, "clearmouseover") == 0) { itemDef_t *item; menuDef_t *menu = Menu_GetFocused(); - if (menu) - { - int count,j; + if (menu) { + int count, j; const char *itemName; String_Parse(args, &itemName); count = Menu_ItemsMatchingGroup(menu, itemName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( menu, j, itemName); - if (item != NULL) - { + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber(menu, j, itemName); + if (item != NULL) { item->window.flags &= ~WINDOW_MOUSEOVER; } } } - } - else if (Q_stricmp(name, "updateForceStatus") == 0) - { + } else if (Q_stricmp(name, "updateForceStatus") == 0) { UpdateForceStatus(); - } - else if (Q_stricmp(name, "update") == 0) - { - if (String_Parse(args, &name2)) - { + } else if (Q_stricmp(name, "update") == 0) { + if (String_Parse(args, &name2)) { UI_Update(name2); } - } - else if (Q_stricmp(name, "setBotButtons") == 0) - { + } else if (Q_stricmp(name, "setBotButtons") == 0) { UpdateBotButtons(); - } - else if (Q_stricmp(name, "getsabercvars") == 0) - { + } else if (Q_stricmp(name, "getsabercvars") == 0) { UI_GetSaberCvars(); - } - else if (Q_stricmp(name, "setsaberboxesandhilts") == 0) - { + } else if (Q_stricmp(name, "setsaberboxesandhilts") == 0) { UI_SetSaberBoxesandHilts(); - } - else if (Q_stricmp(name, "saber_type") == 0) - { + } else if (Q_stricmp(name, "saber_type") == 0) { UI_UpdateSaberType(); - } - else if (Q_stricmp(name, "saber_hilt") == 0) - { - UI_UpdateSaberHilt( qfalse ); - } - else if (Q_stricmp(name, "saber_color") == 0) - { - UI_UpdateSaberColor( qfalse ); - } - else if (Q_stricmp(name, "setscreensaberhilt") == 0) - { + } else if (Q_stricmp(name, "saber_hilt") == 0) { + UI_UpdateSaberHilt(qfalse); + } else if (Q_stricmp(name, "saber_color") == 0) { + UI_UpdateSaberColor(qfalse); + } else if (Q_stricmp(name, "setscreensaberhilt") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "hiltbut"); - if (item) - { - if (saberSingleHiltInfo[item->cursorPos]) - { - trap->Cvar_Set( "ui_saber", saberSingleHiltInfo[item->cursorPos] ); + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "hiltbut"); + if (item) { + if (saberSingleHiltInfo[item->cursorPos]) { + trap->Cvar_Set("ui_saber", saberSingleHiltInfo[item->cursorPos]); } } } - } - else if (Q_stricmp(name, "setscreensaberhilt1") == 0) - { + } else if (Q_stricmp(name, "setscreensaberhilt1") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "hiltbut1"); - if (item) - { - if (saberSingleHiltInfo[item->cursorPos]) - { - trap->Cvar_Set( "ui_saber", saberSingleHiltInfo[item->cursorPos] ); + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "hiltbut1"); + if (item) { + if (saberSingleHiltInfo[item->cursorPos]) { + trap->Cvar_Set("ui_saber", saberSingleHiltInfo[item->cursorPos]); } } } - } - else if (Q_stricmp(name, "setscreensaberhilt2") == 0) - { + } else if (Q_stricmp(name, "setscreensaberhilt2") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "hiltbut2"); - if (item) - { - if (saberSingleHiltInfo[item->cursorPos]) - { - trap->Cvar_Set( "ui_saber2", saberSingleHiltInfo[item->cursorPos] ); + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "hiltbut2"); + if (item) { + if (saberSingleHiltInfo[item->cursorPos]) { + trap->Cvar_Set("ui_saber2", saberSingleHiltInfo[item->cursorPos]); } } } - } - else if (Q_stricmp(name, "setscreensaberstaff") == 0) - { + } else if (Q_stricmp(name, "setscreensaberstaff") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "hiltbut_staves"); - if (item) - { - if (saberSingleHiltInfo[item->cursorPos]) - { - trap->Cvar_Set( "ui_saber", saberStaffHiltInfo[item->cursorPos] ); + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "hiltbut_staves"); + if (item) { + if (saberSingleHiltInfo[item->cursorPos]) { + trap->Cvar_Set("ui_saber", saberStaffHiltInfo[item->cursorPos]); } } } - } - else if (Q_stricmp(name, "saber2_hilt") == 0) - { - UI_UpdateSaberHilt( qtrue ); - } - else if (Q_stricmp(name, "saber2_color") == 0) - { - UI_UpdateSaberColor( qtrue ); - } - else if (Q_stricmp(name, "updatesabercvars") == 0) - { + } else if (Q_stricmp(name, "saber2_hilt") == 0) { + UI_UpdateSaberHilt(qtrue); + } else if (Q_stricmp(name, "saber2_color") == 0) { + UI_UpdateSaberColor(qtrue); + } else if (Q_stricmp(name, "updatesabercvars") == 0) { UI_UpdateSaberCvars(); - } - else if (Q_stricmp(name, "updatesiegeobjgraphics") == 0) - { + } else if (Q_stricmp(name, "updatesiegeobjgraphics") == 0) { int team = (int)trap->Cvar_VariableValue("ui_team"); trap->Cvar_Set("ui_holdteam", va("%d", team)); UI_UpdateSiegeObjectiveGraphics(); - } - else if (Q_stricmp(name, "setsiegeobjbuttons") == 0) - { + } else if (Q_stricmp(name, "setsiegeobjbuttons") == 0) { const char *itemArg; const char *cvarLitArg; const char *cvarNormalArg; - char string[512]; - char string2[512]; + char string[512]; + char string2[512]; menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { // Set the new item to the background - if (String_Parse(args, &itemArg)) - { + if (String_Parse(args, &itemArg)) { // Set the old button to it's original background - trap->Cvar_VariableStringBuffer( "currentObjMapIconItem", string, sizeof(string) ); - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, string); - if (item) - { + trap->Cvar_VariableStringBuffer("currentObjMapIconItem", string, sizeof(string)); + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, string); + if (item) { // A cvar holding the name of a cvar - how crazy is that? - trap->Cvar_VariableStringBuffer( "currentObjMapIconBackground", string, sizeof(string) ); - trap->Cvar_VariableStringBuffer( string, string2, sizeof(string2) ); + trap->Cvar_VariableStringBuffer("currentObjMapIconBackground", string, sizeof(string)); + trap->Cvar_VariableStringBuffer(string, string2, sizeof(string2)); Menu_SetItemBackground(menu, item->window.name, string2); // Re-enable this button @@ -6834,17 +6118,14 @@ static void UI_RunMenuScript(char **args) } // Set the new item to the given background - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, itemArg); - if (item) - { // store item name - trap->Cvar_Set("currentObjMapIconItem", item->window.name); - if (String_Parse(args, &cvarNormalArg)) - { // Store normal background + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, itemArg); + if (item) { // store item name + trap->Cvar_Set("currentObjMapIconItem", item->window.name); + if (String_Parse(args, &cvarNormalArg)) { // Store normal background trap->Cvar_Set("currentObjMapIconBackground", cvarNormalArg); // Get higlight background - if (String_Parse(args, &cvarLitArg)) - { // set hightlight background - trap->Cvar_VariableStringBuffer( cvarLitArg, string, sizeof(string) ); + if (String_Parse(args, &cvarLitArg)) { // set hightlight background + trap->Cvar_VariableStringBuffer(cvarLitArg, string, sizeof(string)); Menu_SetItemBackground(menu, item->window.name, string); // Disable button Menu_ItemDisable(menu, item->window.name, qtrue); @@ -6853,19 +6134,14 @@ static void UI_RunMenuScript(char **args) } } } - } - else if (Q_stricmp(name, "updatesiegeclasscnt") == 0) - { + } else if (Q_stricmp(name, "updatesiegeclasscnt") == 0) { const char *teamArg; - if (String_Parse(args, &teamArg)) - { + if (String_Parse(args, &teamArg)) { UI_SiegeClassCnt(atoi(teamArg)); } - } - else if (Q_stricmp(name, "updatesiegecvars") == 0) - { - int team,baseClass; + } else if (Q_stricmp(name, "updatesiegecvars") == 0) { + int team, baseClass; team = (int)trap->Cvar_VariableValue("ui_holdteam"); baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); @@ -6873,255 +6149,198 @@ static void UI_RunMenuScript(char **args) UI_UpdateCvarsForClass(team, baseClass, 0); } // Save current team and class - else if (Q_stricmp(name, "setteamclassicons") == 0) - { + else if (Q_stricmp(name, "setteamclassicons") == 0) { int team = (int)trap->Cvar_VariableValue("ui_holdteam"); - char classString[512]; + char classString[512]; - trap->Cvar_VariableStringBuffer( "ui_mySiegeClass", classString, sizeof(classString) ); + trap->Cvar_VariableStringBuffer("ui_mySiegeClass", classString, sizeof(classString)); trap->Cvar_Set("ui_startsiegeteam", va("%d", team)); - trap->Cvar_Set( "ui_startsiegeclass", classString); + trap->Cvar_Set("ui_startsiegeclass", classString); // If player is already on a team, set up icons to show it. UI_FindCurrentSiegeTeamClass(); - } - else if (Q_stricmp(name, "updatesiegeweapondesc") == 0) - { + } else if (Q_stricmp(name, "updatesiegeweapondesc") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_weapons_feed"); - if (item) - { - char info[MAX_INFO_VALUE]; - trap->Cvar_VariableStringBuffer( va("ui_class_weapondesc%i", item->cursorPos), info, sizeof(info) ); - trap->Cvar_Set( "ui_itemforceinvdesc", info ); + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_weapons_feed"); + if (item) { + char info[MAX_INFO_VALUE]; + trap->Cvar_VariableStringBuffer(va("ui_class_weapondesc%i", item->cursorPos), info, sizeof(info)); + trap->Cvar_Set("ui_itemforceinvdesc", info); } } - } - else if (Q_stricmp(name, "updatesiegeinventorydesc") == 0) - { + } else if (Q_stricmp(name, "updatesiegeinventorydesc") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_inventory_feed"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_inventory_feed"); + if (item) { char info[MAX_INFO_VALUE]; - trap->Cvar_VariableStringBuffer( va("ui_class_itemdesc%i", item->cursorPos), info, sizeof(info) ); - trap->Cvar_Set( "ui_itemforceinvdesc", info ); + trap->Cvar_VariableStringBuffer(va("ui_class_itemdesc%i", item->cursorPos), info, sizeof(info)); + trap->Cvar_Set("ui_itemforceinvdesc", info); } } - } - else if (Q_stricmp(name, "updatesiegeforcedesc") == 0) - { + } else if (Q_stricmp(name, "updatesiegeforcedesc") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_force_feed"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_force_feed"); + if (item) { int i; char info[MAX_STRING_CHARS]; - trap->Cvar_VariableStringBuffer( va("ui_class_power%i", item->cursorPos), info, sizeof(info) ); + trap->Cvar_VariableStringBuffer(va("ui_class_power%i", item->cursorPos), info, sizeof(info)); - //count them up - for (i=0;i< NUM_FORCE_POWERS;i++) - { - if (!strcmp(HolocronIcons[i],info)) - { - trap->Cvar_Set( "ui_itemforceinvdesc", forcepowerDesc[i] ); + // count them up + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (!strcmp(HolocronIcons[i], info)) { + trap->Cvar_Set("ui_itemforceinvdesc", forcepowerDesc[i]); } } } } - } - else if (Q_stricmp(name, "resetitemdescription") == 0) - { + } else if (Q_stricmp(name, "resetitemdescription") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "itemdescription"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "itemdescription"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { listPtr->startPos = 0; listPtr->cursorPos = 0; } item->cursorPos = 0; } - } - } - else if (Q_stricmp(name, "resetsiegelistboxes") == 0) - { + } + } else if (Q_stricmp(name, "resetsiegelistboxes") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "description"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "description"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { listPtr->startPos = 0; } item->cursorPos = 0; } } - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_weapons_feed"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_weapons_feed"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { listPtr->startPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_inventory_feed"); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_inventory_feed"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { listPtr->startPos = 0; } item->cursorPos = 0; } - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_force_feed"); - if (item) - { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_force_feed"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { listPtr->startPos = 0; } item->cursorPos = 0; } } - } - else if (Q_stricmp(name, "updatesiegestatusicons") == 0) - { + } else if (Q_stricmp(name, "updatesiegestatusicons") == 0) { UI_UpdateSiegeStatusIcons(); - } - else if (Q_stricmp(name, "setcurrentNetMap") == 0) - { + } else if (Q_stricmp(name, "setcurrentNetMap") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "maplist"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "maplist"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { - trap->Cvar_Set("ui_currentNetMap", va("%d",listPtr->cursorPos)); + if (listPtr) { + trap->Cvar_Set("ui_currentNetMap", va("%d", listPtr->cursorPos)); } } } - } - else if (Q_stricmp(name, "resetmaplist") == 0) - { + } else if (Q_stricmp(name, "resetmaplist") == 0) { menuDef_t *menu; itemDef_t *item; - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "maplist"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "maplist"); + if (item) { uiInfo.uiDC.feederSelection(item->special, item->cursorPos, item); } } - } - else if (Q_stricmp(name, "getmousepitch") == 0) - { + } else if (Q_stricmp(name, "getmousepitch") == 0) { trap->Cvar_Set("ui_mousePitch", (trap->Cvar_VariableValue("m_pitch") >= 0) ? "0" : "1"); - } - else if (Q_stricmp(name, "clampmaxplayers") == 0) - { + } else if (Q_stricmp(name, "clampmaxplayers") == 0) { UI_ClampMaxPlayers(); - } - else if ( Q_stricmp( name, "LaunchSP" ) == 0 ) - { + } else if (Q_stricmp(name, "LaunchSP") == 0) { // TODO for MAC_PORT - } - else - { + } else { Com_Printf("unknown UI script %s\n", name); } } } -static void UI_GetTeamColor(vec4_t *color) { -} - -void UI_SetSiegeTeams(void) -{ - char info[MAX_INFO_VALUE]; - char *mapname = NULL; - char levelname[MAX_QPATH]; - char btime[1024]; - char teams[2048]; - char teamInfo[MAX_SIEGE_INFO_SIZE]; - char team1[1024]; - char team2[1024]; - int len = 0; - int gametype; - fileHandle_t f; - - //Get the map name from the server info - if (trap->GetConfigString( CS_SERVERINFO, info, sizeof(info) )) - { - mapname = Info_ValueForKey( info, "mapname" ); - } +static void UI_GetTeamColor(vec4_t *color) {} - if (!mapname || !mapname[0]) - { +void UI_SetSiegeTeams(void) { + char info[MAX_INFO_VALUE]; + char *mapname = NULL; + char levelname[MAX_QPATH]; + char btime[1024]; + char teams[2048]; + char teamInfo[MAX_SIEGE_INFO_SIZE]; + char team1[1024]; + char team2[1024]; + int len = 0; + int gametype; + fileHandle_t f; + + // Get the map name from the server info + if (trap->GetConfigString(CS_SERVERINFO, info, sizeof(info))) { + mapname = Info_ValueForKey(info, "mapname"); + } + + if (!mapname || !mapname[0]) { return; } gametype = atoi(Info_ValueForKey(info, "g_gametype")); - //If the server we are connected to is not siege we cannot choose a class anyway - if (gametype != GT_SIEGE) - { + // If the server we are connected to is not siege we cannot choose a class anyway + if (gametype != GT_SIEGE) { return; } Com_sprintf(levelname, sizeof(levelname), "maps/%s.siege", mapname); - if (!levelname[0]) - { + if (!levelname[0]) { return; } @@ -7131,58 +6350,45 @@ void UI_SetSiegeTeams(void) return; } if (len >= MAX_SIEGE_INFO_SIZE) { - trap->FS_Close( f ); + trap->FS_Close(f); return; } trap->FS_Read(siege_info, len, f); - siege_info[len] = 0; //ensure null terminated + siege_info[len] = 0; // ensure null terminated trap->FS_Close(f); - //Found the .siege file + // Found the .siege file - if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) - { + if (BG_SiegeGetValueGroup(siege_info, "Teams", teams)) { char buf[1024]; trap->Cvar_VariableStringBuffer("cg_siegeTeam1", buf, 1024); - if (buf[0] && Q_stricmp(buf, "none")) - { - Q_strncpyz( team1, buf, sizeof( team1 ) ); - } - else - { + if (buf[0] && Q_stricmp(buf, "none")) { + Q_strncpyz(team1, buf, sizeof(team1)); + } else { BG_SiegeGetPairedValue(teams, "team1", team1); } trap->Cvar_VariableStringBuffer("cg_siegeTeam2", buf, 1024); - if (buf[0] && Q_stricmp(buf, "none")) - { - Q_strncpyz( team2, buf, sizeof( team2 ) ); - } - else - { + if (buf[0] && Q_stricmp(buf, "none")) { + Q_strncpyz(team2, buf, sizeof(team2)); + } else { BG_SiegeGetPairedValue(teams, "team2", team2); } - } - else - { + } else { return; } - //Set the team themes so we know what classes to make available for selection - if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) - { + // Set the team themes so we know what classes to make available for selection + if (BG_SiegeGetValueGroup(siege_info, team1, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM1, btime); } } - if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) - { - if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) - { + if (BG_SiegeGetValueGroup(siege_info, team2, teamInfo)) { + if (BG_SiegeGetPairedValue(teamInfo, "UseTeam", btime)) { BG_SiegeSetTeamTheme(SIEGETEAM_TEAM2, btime); } } @@ -7190,9 +6396,8 @@ void UI_SetSiegeTeams(void) siegeTeam1 = BG_SiegeFindThemeForTeam(SIEGETEAM_TEAM1); siegeTeam2 = BG_SiegeFindThemeForTeam(SIEGETEAM_TEAM2); - //set the default description for the default selection - if (!siegeTeam1 || !siegeTeam1->classes[0]) - { + // set the default description for the default selection + if (!siegeTeam1 || !siegeTeam1->classes[0]) { Com_Error(ERR_DROP, "Error loading teams in UI"); } @@ -7200,16 +6405,15 @@ void UI_SetSiegeTeams(void) Menu_SetFeederSelection(NULL, FEEDER_SIEGE_TEAM2, -1, NULL); } -static void UI_SiegeClassCnt( const int team ) -{ +static void UI_SiegeClassCnt(const int team) { UI_SetSiegeTeams(); - trap->Cvar_Set("ui_infantry_cnt", va("%d", BG_SiegeCountBaseClass(team,0))); - trap->Cvar_Set("ui_vanguard_cnt", va("%d", BG_SiegeCountBaseClass(team,1))); - trap->Cvar_Set("ui_support_cnt", va("%d", BG_SiegeCountBaseClass(team,2))); - trap->Cvar_Set("ui_jedi_cnt", va("%d", BG_SiegeCountBaseClass(team,3))); - trap->Cvar_Set("ui_demo_cnt", va("%d", BG_SiegeCountBaseClass(team,4))); - trap->Cvar_Set("ui_heavy_cnt", va("%d", BG_SiegeCountBaseClass(team,5))); + trap->Cvar_Set("ui_infantry_cnt", va("%d", BG_SiegeCountBaseClass(team, 0))); + trap->Cvar_Set("ui_vanguard_cnt", va("%d", BG_SiegeCountBaseClass(team, 1))); + trap->Cvar_Set("ui_support_cnt", va("%d", BG_SiegeCountBaseClass(team, 2))); + trap->Cvar_Set("ui_jedi_cnt", va("%d", BG_SiegeCountBaseClass(team, 3))); + trap->Cvar_Set("ui_demo_cnt", va("%d", BG_SiegeCountBaseClass(team, 4))); + trap->Cvar_Set("ui_heavy_cnt", va("%d", BG_SiegeCountBaseClass(team, 5))); } /* @@ -7224,13 +6428,13 @@ static int UI_MapCountByGameType(qboolean singlePlayer) { if (game == GT_TEAM) game = GT_FFA; - //Since GT_CTY uses the same entities as CTF, use the same map sets - if ( game == GT_CTY ) + // Since GT_CTY uses the same entities as CTF, use the same map sets + if (game == GT_CTY) game = GT_CTF; for (i = 0; i < uiInfo.mapCount; i++) { uiInfo.mapList[i].active = qfalse; - if ( uiInfo.mapList[i].typeBits & (1 << game)) { + if (uiInfo.mapList[i].typeBits & (1 << game)) { if (singlePlayer) { if (!(uiInfo.mapList[i].typeBits & (1 << GT_SINGLE_PLAYER))) { continue; @@ -7244,16 +6448,16 @@ static int UI_MapCountByGameType(qboolean singlePlayer) { } qboolean UI_hasSkinForBase(const char *base, const char *team) { - char test[1024]; - fileHandle_t f; + char test[1024]; + fileHandle_t f; - Com_sprintf( test, sizeof( test ), "models/players/%s/%s/lower_default.skin", base, team ); + Com_sprintf(test, sizeof(test), "models/players/%s/%s/lower_default.skin", base, team); trap->FS_Open(test, &f, FS_READ); if (f != 0) { trap->FS_Close(f); return qtrue; } - Com_sprintf( test, sizeof( test ), "models/players/characters/%s/%s/lower_default.skin", base, team ); + Com_sprintf(test, sizeof(test), "models/players/characters/%s/%s/lower_default.skin", base, team); trap->FS_Open(test, &f, FS_READ); if (f != 0) { trap->FS_Close(f); @@ -7273,31 +6477,28 @@ static int UI_HeadCountByColor(void) { c = 0; - switch(uiSkinColor) - { - case TEAM_BLUE: - teamname = "/blue"; - break; - case TEAM_RED: - teamname = "/red"; - break; - default: - teamname = "/default"; + switch (uiSkinColor) { + case TEAM_BLUE: + teamname = "/blue"; + break; + case TEAM_RED: + teamname = "/red"; + break; + default: + teamname = "/default"; } // Count each head with this color - for (i=0; i uiInfo.serverStatus.numDisplayServers ) { + if (position < 0 || position > uiInfo.serverStatus.numDisplayServers) { return; } - trap->LAN_GetServerInfo( UI_SourceForLAN(), num, info, sizeof(info) ); + trap->LAN_GetServerInfo(UI_SourceForLAN(), num, info, sizeof(info)); uiInfo.serverStatus.numDisplayServers++; for (i = uiInfo.serverStatus.numDisplayServers; i > position; i--) { - uiInfo.serverStatus.displayServers[i] = uiInfo.serverStatus.displayServers[i-1]; + uiInfo.serverStatus.displayServers[i] = uiInfo.serverStatus.displayServers[i - 1]; } uiInfo.serverStatus.displayServers[position] = num; } @@ -7359,7 +6557,7 @@ static void UI_RemoveServerFromDisplayList(int num) { if (uiInfo.serverStatus.displayServers[i] == num) { uiInfo.serverStatus.numDisplayServers--; for (j = i; j < uiInfo.serverStatus.numDisplayServers; j++) { - uiInfo.serverStatus.displayServers[j] = uiInfo.serverStatus.displayServers[j+1]; + uiInfo.serverStatus.displayServers[j] = uiInfo.serverStatus.displayServers[j + 1]; } return; } @@ -7379,14 +6577,14 @@ static void UI_BinaryServerInsertion(int num) { mid = len; offset = 0; res = 0; - while(mid > 0) { + while (mid > 0) { mid = len >> 1; // - res = trap->LAN_CompareServers( UI_SourceForLAN(), uiInfo.serverStatus.sortKey, - uiInfo.serverStatus.sortDir, num, uiInfo.serverStatus.displayServers[offset+mid]); + res = trap->LAN_CompareServers(UI_SourceForLAN(), uiInfo.serverStatus.sortKey, uiInfo.serverStatus.sortDir, num, + uiInfo.serverStatus.displayServers[offset + mid]); // if equal if (res == 0) { - UI_InsertServerIntoDisplayList(num, offset+mid); + UI_InsertServerIntoDisplayList(num, offset + mid); return; } // if larger @@ -7411,25 +6609,25 @@ UI_BuildServerDisplayList ================== */ static void UI_BuildServerDisplayList(int force) { - int i, count, clients, maxClients, ping, game, len, passw/*, visible*/; + int i, count, clients, maxClients, ping, game, len, passw /*, visible*/; char info[MAX_STRING_CHARS]; -// qboolean startRefresh = qtrue; TTimo: unused + // qboolean startRefresh = qtrue; TTimo: unused static int numinvisible; - int lanSource; + int lanSource; if (!(force || uiInfo.uiDC.realTime > uiInfo.serverStatus.nextDisplayRefresh)) { return; } // if we shouldn't reset - if ( force == 2 ) { + if (force == 2) { force = 0; } // do motd updates here too - trap->Cvar_VariableStringBuffer( "cl_motdString", uiInfo.serverStatus.motd, sizeof(uiInfo.serverStatus.motd) ); + trap->Cvar_VariableStringBuffer("cl_motdString", uiInfo.serverStatus.motd, sizeof(uiInfo.serverStatus.motd)); len = strlen(uiInfo.serverStatus.motd); if (len == 0) { - Q_strncpyz( uiInfo.serverStatus.motd, "Welcome to Jedi Academy MP!", sizeof( uiInfo.serverStatus.motd ) ); + Q_strncpyz(uiInfo.serverStatus.motd, "Welcome to Jedi Academy MP!", sizeof(uiInfo.serverStatus.motd)); len = strlen(uiInfo.serverStatus.motd); } if (len != uiInfo.serverStatus.motdLen) { @@ -7452,7 +6650,7 @@ static void UI_BuildServerDisplayList(int force) { // get the server count (comes from the master) count = trap->LAN_GetServerCount(lanSource); - if (count == -1 || (ui_netSource.integer == UIAS_LOCAL && count == 0) ) { + if (count == -1 || (ui_netSource.integer == UIAS_LOCAL && count == 0)) { // still waiting on a response from the master uiInfo.serverStatus.numDisplayServers = 0; uiInfo.serverStatus.numPlayersOnServers = 0; @@ -7460,20 +6658,20 @@ static void UI_BuildServerDisplayList(int force) { return; } - trap->Cvar_Update( &ui_browserFilterInvalidInfo ); - trap->Cvar_Update( &ui_browserShowEmpty ); - trap->Cvar_Update( &ui_browserShowFull ); - trap->Cvar_Update( &ui_browserShowPasswordProtected ); - trap->Cvar_Update( &ui_serverFilterType ); - trap->Cvar_Update( &ui_joinGametype ); + trap->Cvar_Update(&ui_browserFilterInvalidInfo); + trap->Cvar_Update(&ui_browserShowEmpty); + trap->Cvar_Update(&ui_browserShowFull); + trap->Cvar_Update(&ui_browserShowPasswordProtected); + trap->Cvar_Update(&ui_serverFilterType); + trap->Cvar_Update(&ui_joinGametype); -// visible = qfalse; + // visible = qfalse; for (i = 0; i < count; i++) { // if we already got info for this server if (!trap->LAN_ServerIsVisible(lanSource, i)) { continue; } -// visible = qtrue; + // visible = qtrue; // get the ping for this server ping = trap->LAN_GetServerPing(lanSource, i); if (ping > 0 || ui_netSource.integer == UIAS_FAVORITES) { @@ -7481,8 +6679,8 @@ static void UI_BuildServerDisplayList(int force) { trap->LAN_GetServerInfo(lanSource, i, info, MAX_STRING_CHARS); // don't list servers with invalid info - if ( ui_browserFilterInvalidInfo.integer != 0 && !UI_ServerInfoIsValid( info ) ) { - trap->LAN_MarkServerVisible( lanSource, i, qfalse ); + if (ui_browserFilterInvalidInfo.integer != 0 && !UI_ServerInfoIsValid(info)) { + trap->LAN_MarkServerVisible(lanSource, i, qfalse); continue; } @@ -7504,7 +6702,7 @@ static void UI_BuildServerDisplayList(int force) { } } - if ( ui_browserShowPasswordProtected.integer == 0 ) { + if (ui_browserShowPasswordProtected.integer == 0) { passw = atoi(Info_ValueForKey(info, "needpass")); if (passw && !ui_browserShowPasswordProtected.integer) { trap->LAN_MarkServerVisible(lanSource, i, qfalse); @@ -7521,7 +6719,7 @@ static void UI_BuildServerDisplayList(int force) { } if (ui_serverFilterType.integer > 0 && ui_serverFilterType.integer <= uiInfo.modCount) { - if (Q_stricmp(Info_ValueForKey(info, "game"), UI_FilterDir( ui_serverFilterType.integer ) ) != 0) { + if (Q_stricmp(Info_ValueForKey(info, "game"), UI_FilterDir(ui_serverFilterType.integer)) != 0) { trap->LAN_MarkServerVisible(lanSource, i, qfalse); continue; } @@ -7543,35 +6741,25 @@ static void UI_BuildServerDisplayList(int force) { uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime; // if there were no servers visible for ping updates -// if (!visible) { -// UI_StopServerRefresh(); -// uiInfo.serverStatus.nextDisplayRefresh = 0; -// } + // if (!visible) { + // UI_StopServerRefresh(); + // uiInfo.serverStatus.nextDisplayRefresh = 0; + // } } typedef struct serverStatusCvar_s { char *name, *altName; } serverStatusCvar_t; -serverStatusCvar_t serverStatusCvars[] = { - {"sv_hostname", "Name"}, - {"Address", ""}, - {"gamename", "Game name"}, - {"g_gametype", "Game type"}, - {"mapname", "Map"}, - {"version", ""}, - {"protocol", ""}, - {"timelimit", ""}, - {"fraglimit", ""}, - {NULL, NULL} -}; +serverStatusCvar_t serverStatusCvars[] = {{"sv_hostname", "Name"}, {"Address", ""}, {"gamename", "Game name"}, {"g_gametype", "Game type"}, {"mapname", "Map"}, + {"version", ""}, {"protocol", ""}, {"timelimit", ""}, {"fraglimit", ""}, {NULL, NULL}}; /* ================== UI_SortServerStatusInfo ================== */ -static void UI_SortServerStatusInfo( serverStatusInfo_t *info ) { +static void UI_SortServerStatusInfo(serverStatusInfo_t *info) { int i, j, index, numLines; char *tmp1, *tmp2; @@ -7579,13 +6767,13 @@ static void UI_SortServerStatusInfo( serverStatusInfo_t *info ) { // replace the gametype number by FFA, CTF etc. // index = 0; - numLines = Com_Clampi( 0, MAX_SERVERSTATUS_LINES, info->numLines ); + numLines = Com_Clampi(0, MAX_SERVERSTATUS_LINES, info->numLines); for (i = 0; serverStatusCvars[i].name; i++) { for (j = 0; j < numLines; j++) { - if ( !info->lines[j][1] || info->lines[j][1][0] ) { + if (!info->lines[j][1] || info->lines[j][1][0]) { continue; } - if ( !Q_stricmp(serverStatusCvars[i].name, info->lines[j][0]) ) { + if (!Q_stricmp(serverStatusCvars[i].name, info->lines[j][0])) { // swap lines tmp1 = info->lines[index][0]; tmp2 = info->lines[index][3]; @@ -7594,7 +6782,7 @@ static void UI_SortServerStatusInfo( serverStatusInfo_t *info ) { info->lines[j][0] = tmp1; info->lines[j][3] = tmp2; // - if ( strlen(serverStatusCvars[i].altName) ) { + if (strlen(serverStatusCvars[i].altName)) { info->lines[index][0] = serverStatusCvars[i].altName; } index++; @@ -7608,16 +6796,16 @@ static void UI_SortServerStatusInfo( serverStatusInfo_t *info ) { UI_GetServerStatusInfo ================== */ -static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t *info ) { +static int UI_GetServerStatusInfo(const char *serverAddress, serverStatusInfo_t *info) { char *p, *score, *ping, *name; int i, len; if (!info) { - trap->LAN_ServerStatus( serverAddress, NULL, 0); + trap->LAN_ServerStatus(serverAddress, NULL, 0); return qfalse; } memset(info, 0, sizeof(*info)); - if ( trap->LAN_ServerStatus( serverAddress, info->text, sizeof(info->text)) ) { + if (trap->LAN_ServerStatus(serverAddress, info->text, sizeof(info->text))) { Q_strncpyz(info->address, serverAddress, sizeof(info->address)); p = info->text; info->numLines = 0; @@ -7629,7 +6817,8 @@ static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t // get the cvars while (p && *p) { p = strchr(p, '\\'); - if (!p) break; + if (!p) + break; *p++ = '\0'; if (*p == '\\') break; @@ -7637,7 +6826,8 @@ static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t info->lines[info->numLines][1] = ""; info->lines[info->numLines][2] = ""; p = strchr(p, '\\'); - if (!p) break; + if (!p) + break; *p++ = '\0'; info->lines[info->numLines][3] = p; @@ -7646,7 +6836,7 @@ static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t break; } // get the player list - if (info->numLines < MAX_SERVERSTATUS_LINES-3) { + if (info->numLines < MAX_SERVERSTATUS_LINES - 3) { // empty line info->lines[info->numLines][0] = ""; info->lines[info->numLines][1] = ""; @@ -7676,7 +6866,7 @@ static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t break; *p++ = '\0'; name = p; - Com_sprintf(&info->pings[len], sizeof(info->pings)-len, "%d", i); + Com_sprintf(&info->pings[len], sizeof(info->pings) - len, "%d", i); info->lines[info->numLines][0] = &info->pings[len]; len += strlen(&info->pings[len]) + 1; info->lines[info->numLines][1] = score; @@ -7693,7 +6883,7 @@ static int UI_GetServerStatusInfo( const char *serverAddress, serverStatusInfo_t i++; } } - UI_SortServerStatusInfo( info ); + UI_SortServerStatusInfo(info); return qtrue; } return qfalse; @@ -7708,20 +6898,19 @@ static void UI_BuildFindPlayerList(qboolean force) { static int numFound, numTimeOuts; int i, j, resend; serverStatusInfo_t info; - char name[MAX_NAME_LENGTH+2]; + char name[MAX_NAME_LENGTH + 2]; char infoString[MAX_STRING_CHARS]; - int lanSource; + int lanSource; if (!force) { if (!uiInfo.nextFindPlayerRefresh || uiInfo.nextFindPlayerRefresh > uiInfo.uiDC.realTime) { return; } - } - else { + } else { memset(&uiInfo.pendingServerStatus, 0, sizeof(uiInfo.pendingServerStatus)); uiInfo.numFoundPlayerServers = 0; uiInfo.currentFoundPlayerServer = 0; - trap->Cvar_VariableStringBuffer( "ui_findPlayer", uiInfo.findPlayerName, sizeof(uiInfo.findPlayerName)); + trap->Cvar_VariableStringBuffer("ui_findPlayer", uiInfo.findPlayerName, sizeof(uiInfo.findPlayerName)); Q_StripColor(uiInfo.findPlayerName); // should have a string of some length if (!strlen(uiInfo.findPlayerName)) { @@ -7735,15 +6924,15 @@ static void UI_BuildFindPlayerList(qboolean force) { } trap->Cvar_Set("cl_serverStatusResendTime", va("%d", resend)); // reset all server status requests - trap->LAN_ServerStatus( NULL, NULL, 0); + trap->LAN_ServerStatus(NULL, NULL, 0); // uiInfo.numFoundPlayerServers = 1; trap->SE_GetStringTextString("MENUS_SEARCHING", holdSPString, sizeof(holdSPString)); - trap->Cvar_Set( "ui_playerServersFound", va( holdSPString,uiInfo.pendingServerStatus.num, numFound)); - // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], - // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), - // "searching %d...", uiInfo.pendingServerStatus.num); + trap->Cvar_Set("ui_playerServersFound", va(holdSPString, uiInfo.pendingServerStatus.num, numFound)); + // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], + // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), + // "searching %d...", uiInfo.pendingServerStatus.num); numFound = 0; numTimeOuts++; } @@ -7751,13 +6940,13 @@ static void UI_BuildFindPlayerList(qboolean force) { // if this pending server is valid if (uiInfo.pendingServerStatus.server[i].valid) { // try to get the server status for this server - if (UI_GetServerStatusInfo( uiInfo.pendingServerStatus.server[i].adrstr, &info ) ) { + if (UI_GetServerStatusInfo(uiInfo.pendingServerStatus.server[i].adrstr, &info)) { // numFound++; // parse through the server status lines for (j = 0; j < info.numLines; j++) { // should have ping info - if ( !info.lines[j][2] || !info.lines[j][2][0] ) { + if (!info.lines[j][2] || !info.lines[j][2][0]) { continue; } // clean string first @@ -7766,17 +6955,14 @@ static void UI_BuildFindPlayerList(qboolean force) { // if the player name is a substring if (Q_stristr(name, uiInfo.findPlayerName)) { // add to found server list if we have space (always leave space for a line with the number found) - if (uiInfo.numFoundPlayerServers < MAX_FOUNDPLAYER_SERVERS-1) { + if (uiInfo.numFoundPlayerServers < MAX_FOUNDPLAYER_SERVERS - 1) { // - Q_strncpyz(uiInfo.foundPlayerServerAddresses[uiInfo.numFoundPlayerServers-1], - uiInfo.pendingServerStatus.server[i].adrstr, - sizeof(uiInfo.foundPlayerServerAddresses[0])); - Q_strncpyz(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], - uiInfo.pendingServerStatus.server[i].name, - sizeof(uiInfo.foundPlayerServerNames[0])); + Q_strncpyz(uiInfo.foundPlayerServerAddresses[uiInfo.numFoundPlayerServers - 1], uiInfo.pendingServerStatus.server[i].adrstr, + sizeof(uiInfo.foundPlayerServerAddresses[0])); + Q_strncpyz(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers - 1], uiInfo.pendingServerStatus.server[i].name, + sizeof(uiInfo.foundPlayerServerNames[0])); uiInfo.numFoundPlayerServers++; - } - else { + } else { // can't add any more so we're done uiInfo.pendingServerStatus.num = uiInfo.serverStatus.numDisplayServers; } @@ -7784,10 +6970,10 @@ static void UI_BuildFindPlayerList(qboolean force) { } trap->SE_GetStringTextString("MENUS_SEARCHING", holdSPString, sizeof(holdSPString)); - trap->Cvar_Set( "ui_playerServersFound", va( holdSPString,uiInfo.pendingServerStatus.num, numFound)); - // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], - // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), - // "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound); + trap->Cvar_Set("ui_playerServersFound", va(holdSPString, uiInfo.pendingServerStatus.num, numFound)); + // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], + // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), + // "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound); // retrieved the server status so reuse this spot uiInfo.pendingServerStatus.server[i].valid = qfalse; } @@ -7799,7 +6985,7 @@ static void UI_BuildFindPlayerList(qboolean force) { numTimeOuts++; } // reset server status request for this address - UI_GetServerStatusInfo( uiInfo.pendingServerStatus.server[i].adrstr, NULL ); + UI_GetServerStatusInfo(uiInfo.pendingServerStatus.server[i].adrstr, NULL); // reuse pending slot uiInfo.pendingServerStatus.server[i].valid = qfalse; // if we didn't try to get the status of all servers in the main browser yet @@ -7807,18 +6993,19 @@ static void UI_BuildFindPlayerList(qboolean force) { uiInfo.pendingServerStatus.server[i].startTime = uiInfo.uiDC.realTime; lanSource = UI_SourceForLAN(); trap->LAN_GetServerAddressString(lanSource, uiInfo.serverStatus.displayServers[uiInfo.pendingServerStatus.num], - uiInfo.pendingServerStatus.server[i].adrstr, sizeof(uiInfo.pendingServerStatus.server[i].adrstr)); + uiInfo.pendingServerStatus.server[i].adrstr, sizeof(uiInfo.pendingServerStatus.server[i].adrstr)); trap->LAN_GetServerInfo(lanSource, uiInfo.serverStatus.displayServers[uiInfo.pendingServerStatus.num], infoString, sizeof(infoString)); - Q_strncpyz(uiInfo.pendingServerStatus.server[i].name, Info_ValueForKey(infoString, "hostname"), sizeof(uiInfo.pendingServerStatus.server[0].name)); + Q_strncpyz(uiInfo.pendingServerStatus.server[i].name, Info_ValueForKey(infoString, "hostname"), + sizeof(uiInfo.pendingServerStatus.server[0].name)); uiInfo.pendingServerStatus.server[i].valid = qtrue; uiInfo.pendingServerStatus.num++; trap->SE_GetStringTextString("MENUS_SEARCHING", holdSPString, sizeof(holdSPString)); - trap->Cvar_Set( "ui_playerServersFound", va( holdSPString,uiInfo.pendingServerStatus.num, numFound)); + trap->Cvar_Set("ui_playerServersFound", va(holdSPString, uiInfo.pendingServerStatus.num, numFound)); - // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], - // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), - // "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound); + // Com_sprintf(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1], + // sizeof(uiInfo.foundPlayerServerNames[uiInfo.numFoundPlayerServers-1]), + // "searching %d/%d...", uiInfo.pendingServerStatus.num, numFound); } } } @@ -7830,23 +7017,14 @@ static void UI_BuildFindPlayerList(qboolean force) { // if still trying to retrieve server status info if (i < MAX_SERVERSTATUSREQUESTS) { uiInfo.nextFindPlayerRefresh = uiInfo.uiDC.realTime + 25; - } - else { + } else { trap->SE_GetStringTextString("MENUS_SERVERS_FOUNDWITH", holdSPString, sizeof(holdSPString)); // add a line that shows the number of servers found - if (!uiInfo.numFoundPlayerServers) - { - trap->Cvar_Set( "ui_playerServersFound", va( holdSPString, - 0, - "s", - uiInfo.findPlayerName) ); - } - else - { - trap->Cvar_Set( "ui_playerServersFound", va( holdSPString, - uiInfo.numFoundPlayerServers-1, - uiInfo.numFoundPlayerServers == 2 ? "":"s", - uiInfo.findPlayerName) ); + if (!uiInfo.numFoundPlayerServers) { + trap->Cvar_Set("ui_playerServersFound", va(holdSPString, 0, "s", uiInfo.findPlayerName)); + } else { + trap->Cvar_Set("ui_playerServersFound", + va(holdSPString, uiInfo.numFoundPlayerServers - 1, uiInfo.numFoundPlayerServers == 2 ? "" : "s", uiInfo.findPlayerName)); } uiInfo.nextFindPlayerRefresh = 0; // show the server status info for the selected server @@ -7868,21 +7046,20 @@ static void UI_BuildServerStatus(qboolean force) { if (!uiInfo.nextServerStatusRefresh || uiInfo.nextServerStatusRefresh > uiInfo.uiDC.realTime) { return; } - } - else { + } else { Menu_SetFeederSelection(NULL, FEEDER_SERVERSTATUS, 0, NULL); uiInfo.serverStatusInfo.numLines = 0; // reset all server status requests - trap->LAN_ServerStatus( NULL, NULL, 0); + trap->LAN_ServerStatus(NULL, NULL, 0); } - if (uiInfo.serverStatus.currentServer < 0 || uiInfo.serverStatus.currentServer > uiInfo.serverStatus.numDisplayServers || uiInfo.serverStatus.numDisplayServers == 0) { + if (uiInfo.serverStatus.currentServer < 0 || uiInfo.serverStatus.currentServer > uiInfo.serverStatus.numDisplayServers || + uiInfo.serverStatus.numDisplayServers == 0) { return; } - if (UI_GetServerStatusInfo( uiInfo.serverStatusAddress, &uiInfo.serverStatusInfo ) ) { + if (UI_GetServerStatusInfo(uiInfo.serverStatusAddress, &uiInfo.serverStatusInfo)) { uiInfo.nextServerStatusRefresh = 0; - UI_GetServerStatusInfo( uiInfo.serverStatusAddress, NULL ); - } - else { + UI_GetServerStatusInfo(uiInfo.serverStatusAddress, NULL); + } else { uiInfo.nextServerStatusRefresh = uiInfo.uiDC.realTime + 500; } } @@ -7892,203 +7069,172 @@ static void UI_BuildServerStatus(qboolean force) { UI_FeederCount ================== */ -static int UI_FeederCount(float feederID) -{ - int team,baseClass,count=0,i; +static int UI_FeederCount(float feederID) { + int team, baseClass, count = 0, i; static char info[MAX_STRING_CHARS]; - switch ( (int)feederID ) - { - case FEEDER_SABER_SINGLE_INFO: + switch ((int)feederID) { + case FEEDER_SABER_SINGLE_INFO: - for (i=0;inumClasses; - case FEEDER_SIEGE_TEAM2: - if (!siegeTeam2) - { - UI_SetSiegeTeams(); - if (!siegeTeam2) - { - return 0; - } + } + return siegeTeam1->numClasses; + case FEEDER_SIEGE_TEAM2: + if (!siegeTeam2) { + UI_SetSiegeTeams(); + if (!siegeTeam2) { + return 0; } - return siegeTeam2->numClasses; + } + return siegeTeam2->numClasses; - case FEEDER_FORCECFG: - if (uiForceSide == FORCE_LIGHTSIDE) - { - return uiInfo.forceConfigCount-uiInfo.forceConfigLightIndexBegin; - } - else - { - return uiInfo.forceConfigLightIndexBegin+1; - } - //return uiInfo.forceConfigCount; + case FEEDER_FORCECFG: + if (uiForceSide == FORCE_LIGHTSIDE) { + return uiInfo.forceConfigCount - uiInfo.forceConfigLightIndexBegin; + } else { + return uiInfo.forceConfigLightIndexBegin + 1; + } + // return uiInfo.forceConfigCount; - case FEEDER_CINEMATICS: - return uiInfo.movieCount; + case FEEDER_CINEMATICS: + return uiInfo.movieCount; - case FEEDER_MAPS: - case FEEDER_ALLMAPS: - return UI_MapCountByGameType(feederID == FEEDER_MAPS ? qtrue : qfalse); + case FEEDER_MAPS: + case FEEDER_ALLMAPS: + return UI_MapCountByGameType(feederID == FEEDER_MAPS ? qtrue : qfalse); - case FEEDER_SERVERS: - return uiInfo.serverStatus.numDisplayServers; + case FEEDER_SERVERS: + return uiInfo.serverStatus.numDisplayServers; - case FEEDER_SERVERSTATUS: - return Com_Clampi( 0, MAX_SERVERSTATUS_LINES, uiInfo.serverStatusInfo.numLines ); + case FEEDER_SERVERSTATUS: + return Com_Clampi(0, MAX_SERVERSTATUS_LINES, uiInfo.serverStatusInfo.numLines); - case FEEDER_FINDPLAYER: - return uiInfo.numFoundPlayerServers; + case FEEDER_FINDPLAYER: + return uiInfo.numFoundPlayerServers; - case FEEDER_PLAYER_LIST: - if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) - { - uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000; - UI_BuildPlayerList(); - } - return uiInfo.playerCount; + case FEEDER_PLAYER_LIST: + if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) { + uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000; + UI_BuildPlayerList(); + } + return uiInfo.playerCount; - case FEEDER_TEAM_LIST: - if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) - { - uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000; - UI_BuildPlayerList(); - } - return uiInfo.myTeamCount; + case FEEDER_TEAM_LIST: + if (uiInfo.uiDC.realTime > uiInfo.playerRefresh) { + uiInfo.playerRefresh = uiInfo.uiDC.realTime + 3000; + UI_BuildPlayerList(); + } + return uiInfo.myTeamCount; - case FEEDER_MODS: - return uiInfo.modCount; + case FEEDER_MODS: + return uiInfo.modCount; - case FEEDER_DEMOS: - return uiInfo.demoCount; + case FEEDER_DEMOS: + return uiInfo.demoCount; - case FEEDER_MOVES : + case FEEDER_MOVES: - for (i=0;iCvar_VariableValue("ui_team"); - baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); + case FEEDER_SIEGE_BASE_CLASS: + team = (int)trap->Cvar_VariableValue("ui_team"); + baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); - if ((team == SIEGETEAM_TEAM1) || - (team == SIEGETEAM_TEAM2)) - { - // Is it a valid base class? - if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) - { - return (BG_SiegeCountBaseClass( team, baseClass )); - } + if ((team == SIEGETEAM_TEAM1) || (team == SIEGETEAM_TEAM2)) { + // Is it a valid base class? + if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) { + return (BG_SiegeCountBaseClass(team, baseClass)); } - return 0; + } + return 0; - // Get the count of weapons - case FEEDER_SIEGE_CLASS_WEAPONS: - //count them up - for (i=0;i< WP_NUM_WEAPONS;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_weapon%i", i), info, sizeof(info) ); - if (Q_stricmp(info,"gfx/2d/select")!=0) - { - count++; - } + // Get the count of weapons + case FEEDER_SIEGE_CLASS_WEAPONS: + // count them up + for (i = 0; i < WP_NUM_WEAPONS; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_weapon%i", i), info, sizeof(info)); + if (Q_stricmp(info, "gfx/2d/select") != 0) { + count++; } + } - return count; + return count; - // Get the count of inventory - case FEEDER_SIEGE_CLASS_INVENTORY: - //count them up - for (i=0;i< HI_NUM_HOLDABLE;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_item%i", i), info, sizeof(info) ); - // A hack so health and ammo dispenser icons don't show up. - if ((Q_stricmp(info,"gfx/2d/select")!=0) && - (Q_stricmp(info,"gfx/hud/i_icon_healthdisp")!=0) && - (Q_stricmp(info,"gfx/hud/i_icon_ammodisp")!=0)) - { - count++; - } + // Get the count of inventory + case FEEDER_SIEGE_CLASS_INVENTORY: + // count them up + for (i = 0; i < HI_NUM_HOLDABLE; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_item%i", i), info, sizeof(info)); + // A hack so health and ammo dispenser icons don't show up. + if ((Q_stricmp(info, "gfx/2d/select") != 0) && (Q_stricmp(info, "gfx/hud/i_icon_healthdisp") != 0) && + (Q_stricmp(info, "gfx/hud/i_icon_ammodisp") != 0)) { + count++; } - return count; + } + return count; - // Get the count of force powers - case FEEDER_SIEGE_CLASS_FORCE: - //count them up - for (i=0;i< NUM_FORCE_POWERS;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_power%i", i), info, sizeof(info) ); - if (Q_stricmp(info,"gfx/2d/select")!=0) - { - count++; - } + // Get the count of force powers + case FEEDER_SIEGE_CLASS_FORCE: + // count them up + for (i = 0; i < NUM_FORCE_POWERS; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_power%i", i), info, sizeof(info)); + if (Q_stricmp(info, "gfx/2d/select") != 0) { + count++; } - return count; + } + return count; } return 0; @@ -8119,34 +7265,28 @@ UI_HeadCountByColor */ static const char *UI_SelectedTeamHead(int index, int *actual) { char *teamname; - int i,c=0; + int i, c = 0; - switch(uiSkinColor) - { - case TEAM_BLUE: - teamname = "/blue"; - break; - case TEAM_RED: - teamname = "/red"; - break; - default: - teamname = "/default"; - break; + switch (uiSkinColor) { + case TEAM_BLUE: + teamname = "/blue"; + break; + case TEAM_RED: + teamname = "/red"; + break; + default: + teamname = "/default"; + break; } // Count each head with this color - for (i=0; i= 0 && index < uiInfo.forceConfigCount) { - if (index == 0) - { //always show "custom" + if (index == 0) { // always show "custom" return uiInfo.forceConfigNames[index]; - } - else - { - if (uiForceSide == FORCE_LIGHTSIDE) - { + } else { + if (uiForceSide == FORCE_LIGHTSIDE) { index += uiInfo.forceConfigLightIndexBegin; - if (index < 0) - { + if (index < 0) { return NULL; } - if (index >= uiInfo.forceConfigCount) - { + if (index >= uiInfo.forceConfigCount) { return NULL; } return uiInfo.forceConfigNames[index]; - } - else if (uiForceSide == FORCE_DARKSIDE) - { + } else if (uiForceSide == FORCE_DARKSIDE) { index += uiInfo.forceConfigDarkIndexBegin; - if (index < 0) - { + if (index < 0) { return NULL; } - if (index > uiInfo.forceConfigLightIndexBegin) - { //dark gets read in before light + if (index > uiInfo.forceConfigLightIndexBegin) { // dark gets read in before light return NULL; } - if (index >= uiInfo.forceConfigCount) - { + if (index >= uiInfo.forceConfigCount) { return NULL; } return uiInfo.forceConfigNames[index]; - } - else - { + } else { return NULL; } } @@ -8301,119 +7418,101 @@ static const char *UI_FeederItemText(float feederID, int index, int column, // UI_UpdatePendingPings(); } switch (column) { - case SORT_HOST : - if (ping <= 0) { - return Info_ValueForKey(info, "addr"); - } else { - int gametype = atoi( Info_ValueForKey( info, "gametype" ) ); - //check for password - if ( atoi(Info_ValueForKey(info, "needpass")) ) - { - *handle3 = uiInfo.uiDC.Assets.needPass; + case SORT_HOST: + if (ping <= 0) { + return Info_ValueForKey(info, "addr"); + } else { + int gametype = atoi(Info_ValueForKey(info, "gametype")); + // check for password + if (atoi(Info_ValueForKey(info, "needpass"))) { + *handle3 = uiInfo.uiDC.Assets.needPass; + } + // check for saberonly and restricted force powers + if (gametype != GT_JEDIMASTER) { + qboolean saberOnly = qtrue; + qboolean restrictedForce = qfalse; + qboolean allForceDisabled = qfalse; + int wDisable, i = 0; + + // check force + restrictedForce = atoi(Info_ValueForKey(info, "fdisable")); + if (UI_AllForceDisabled(restrictedForce)) { // all force powers are disabled + allForceDisabled = qtrue; + *handle2 = uiInfo.uiDC.Assets.noForce; + } else if (restrictedForce) { // at least one force power is disabled + *handle2 = uiInfo.uiDC.Assets.forceRestrict; } - //check for saberonly and restricted force powers - if ( gametype != GT_JEDIMASTER ) - { - qboolean saberOnly = qtrue; - qboolean restrictedForce = qfalse; - qboolean allForceDisabled = qfalse; - int wDisable, i = 0; - - //check force - restrictedForce = atoi(Info_ValueForKey(info, "fdisable")); - if ( UI_AllForceDisabled( restrictedForce ) ) - {//all force powers are disabled - allForceDisabled = qtrue; - *handle2 = uiInfo.uiDC.Assets.noForce; - } - else if ( restrictedForce ) - {//at least one force power is disabled - *handle2 = uiInfo.uiDC.Assets.forceRestrict; - } - - //check weaps - wDisable = atoi(Info_ValueForKey(info, "wdisable")); - while ( i < WP_NUM_WEAPONS ) - { - if ( !(wDisable & (1 << i)) && i != WP_SABER && i != WP_NONE ) - { - saberOnly = qfalse; - } - - i++; - } - if ( saberOnly ) - { - *handle1 = uiInfo.uiDC.Assets.saberOnly; - } - else if ( atoi(Info_ValueForKey(info, "truejedi")) != 0 ) - { - if ( gametype != GT_HOLOCRON - && gametype != GT_JEDIMASTER - && !saberOnly - && !allForceDisabled ) - {//truejedi is on and allowed in this mode - *handle1 = uiInfo.uiDC.Assets.trueJedi; - } - } - } - if ( ui_netSource.integer == UIAS_LOCAL ) { - int nettype = atoi(Info_ValueForKey(info, "nettype")); + // check weaps + wDisable = atoi(Info_ValueForKey(info, "wdisable")); - if (nettype < 0 || nettype >= numNetNames) { - nettype = 0; + while (i < WP_NUM_WEAPONS) { + if (!(wDisable & (1 << i)) && i != WP_SABER && i != WP_NONE) { + saberOnly = qfalse; } - Com_sprintf( hostname, sizeof(hostname), "%s [%s]", - Info_ValueForKey(info, "hostname"), - netNames[nettype] ); - return hostname; + i++; } - else { - if (atoi(Info_ValueForKey(info, "sv_allowAnonymous")) != 0) { // anonymous server - Com_sprintf( hostname, sizeof(hostname), "(A) %s", - Info_ValueForKey(info, "hostname")); - } else { - Com_sprintf( hostname, sizeof(hostname), "%s", - Info_ValueForKey(info, "hostname")); + if (saberOnly) { + *handle1 = uiInfo.uiDC.Assets.saberOnly; + } else if (atoi(Info_ValueForKey(info, "truejedi")) != 0) { + if (gametype != GT_HOLOCRON && gametype != GT_JEDIMASTER && !saberOnly && + !allForceDisabled) { // truejedi is on and allowed in this mode + *handle1 = uiInfo.uiDC.Assets.trueJedi; } - return hostname; } } - case SORT_MAP : - return Info_ValueForKey(info, "mapname"); - case SORT_CLIENTS : - Com_sprintf( clientBuff, sizeof(clientBuff), "%s (%s)", Info_ValueForKey(info, "clients"), Info_ValueForKey(info, "sv_maxclients")); - return clientBuff; - case SORT_GAME : - game = atoi(Info_ValueForKey(info, "gametype")); - if (game >= 0 && game < numGameTypes) { - Q_strncpyz( needPass, gameTypes[game], sizeof( needPass ) ); - } else { - if ( ping <= 0 ) - Q_strncpyz( needPass, "Inactive", sizeof( needPass ) ); - Q_strncpyz( needPass, "Unknown", sizeof( needPass ) ); - } + if (ui_netSource.integer == UIAS_LOCAL) { + int nettype = atoi(Info_ValueForKey(info, "nettype")); + + if (nettype < 0 || nettype >= numNetNames) { + nettype = 0; + } - return needPass; - case SORT_PING : - if (ping <= 0) { - return "..."; + Com_sprintf(hostname, sizeof(hostname), "%s [%s]", Info_ValueForKey(info, "hostname"), netNames[nettype]); + return hostname; } else { - return Info_ValueForKey(info, "ping"); + if (atoi(Info_ValueForKey(info, "sv_allowAnonymous")) != 0) { // anonymous server + Com_sprintf(hostname, sizeof(hostname), "(A) %s", Info_ValueForKey(info, "hostname")); + } else { + Com_sprintf(hostname, sizeof(hostname), "%s", Info_ValueForKey(info, "hostname")); + } + return hostname; } + } + case SORT_MAP: + return Info_ValueForKey(info, "mapname"); + case SORT_CLIENTS: + Com_sprintf(clientBuff, sizeof(clientBuff), "%s (%s)", Info_ValueForKey(info, "clients"), Info_ValueForKey(info, "sv_maxclients")); + return clientBuff; + case SORT_GAME: + game = atoi(Info_ValueForKey(info, "gametype")); + if (game >= 0 && game < numGameTypes) { + Q_strncpyz(needPass, gameTypes[game], sizeof(needPass)); + } else { + if (ping <= 0) + Q_strncpyz(needPass, "Inactive", sizeof(needPass)); + Q_strncpyz(needPass, "Unknown", sizeof(needPass)); + } + + return needPass; + case SORT_PING: + if (ping <= 0) { + return "..."; + } else { + return Info_ValueForKey(info, "ping"); + } } } } else if (feederID == FEEDER_SERVERSTATUS) { - if ( index >= 0 && index < uiInfo.serverStatusInfo.numLines ) { - if ( column >= 0 && column < 4 ) { + if (index >= 0 && index < uiInfo.serverStatusInfo.numLines) { + if (column >= 0 && column < 4) { return uiInfo.serverStatusInfo.lines[index][column]; } } } else if (feederID == FEEDER_FINDPLAYER) { - if ( index >= 0 && index < uiInfo.numFoundPlayerServers ) { - //return uiInfo.foundPlayerServerAddresses[index]; + if (index >= 0 && index < uiInfo.numFoundPlayerServers) { + // return uiInfo.foundPlayerServerAddresses[index]; return uiInfo.foundPlayerServerNames[index]; } } else if (feederID == FEEDER_PLAYER_LIST) { @@ -8440,187 +7539,141 @@ static const char *UI_FeederItemText(float feederID, int index, int column, if (index >= 0 && index < uiInfo.demoCount) { return uiInfo.demoList[index]; } - } - else if (feederID == FEEDER_MOVES) - { + } else if (feederID == FEEDER_MOVES) { return datapadMoveData[uiInfo.movesTitleIndex][index].title; - } - else if (feederID == FEEDER_MOVES_TITLES) - { + } else if (feederID == FEEDER_MOVES_TITLES) { return datapadMoveTitleData[index]; - } - else if (feederID == FEEDER_PLAYER_SPECIES) - { - if (index >= 0 && index < uiInfo.playerSpeciesCount) - { + } else if (feederID == FEEDER_PLAYER_SPECIES) { + if (index >= 0 && index < uiInfo.playerSpeciesCount) { return uiInfo.playerSpecies[index].Name; - } - } - else if (feederID == FEEDER_LANGUAGES) - { + } + } else if (feederID == FEEDER_LANGUAGES) { return 0; - } - else if (feederID == FEEDER_COLORCHOICES) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { - *handle1 = trap->R_RegisterShaderNoMip( uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); + } else if (feederID == FEEDER_COLORCHOICES) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { + *handle1 = trap->R_RegisterShaderNoMip(uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader; } - } - else if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { - *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { + *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name; } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { - *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { + *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name; } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { - *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { + *handle1 = trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name; } - } - else if (feederID == FEEDER_SIEGE_BASE_CLASS) - { + } else if (feederID == FEEDER_SIEGE_BASE_CLASS) { return ""; - } - else if (feederID == FEEDER_SIEGE_CLASS_WEAPONS) - { + } else if (feederID == FEEDER_SIEGE_CLASS_WEAPONS) { return ""; } return ""; } static qhandle_t UI_FeederItemImage(float feederID, int index) { - int validCnt,i; + int validCnt, i; static char info[MAX_STRING_CHARS]; - if (feederID == FEEDER_SABER_SINGLE_INFO) - { + if (feederID == FEEDER_SABER_SINGLE_INFO) { return 0; - } - else if (feederID == FEEDER_SABER_STAFF_INFO) - { + } else if (feederID == FEEDER_SABER_STAFF_INFO) { return 0; - } - else if (feederID == FEEDER_Q3HEADS) - { + } else if (feederID == FEEDER_Q3HEADS) { int actual = 0; UI_SelectedTeamHead(index, &actual); index = actual; - if (index >= 0 && index < uiInfo.q3HeadCount) - { //we want it to load them as it draws them, like the TA feeder - //return uiInfo.q3HeadIcons[index]; + if (index >= 0 && index < uiInfo.q3HeadCount) { // we want it to load them as it draws them, like the TA feeder + // return uiInfo.q3HeadIcons[index]; int selModel = trap->Cvar_VariableValue("ui_selectedModelIndex"); - if (selModel != -1) - { - if (uiInfo.q3SelectedHead != selModel) - { + if (selModel != -1) { + if (uiInfo.q3SelectedHead != selModel) { uiInfo.q3SelectedHead = selModel; - //UI_FeederSelection(FEEDER_Q3HEADS, uiInfo.q3SelectedHead); + // UI_FeederSelection(FEEDER_Q3HEADS, uiInfo.q3SelectedHead); Menu_SetFeederSelection(NULL, FEEDER_Q3HEADS, selModel, NULL); } } - if (!uiInfo.q3HeadIcons[index]) - { //this isn't the best way of doing this I guess, but I didn't want a whole seperate string array - //for storing shader names. I can't just replace q3HeadNames with the shader name, because we - //print what's in q3HeadNames and the icon name would look funny. + if (!uiInfo.q3HeadIcons[index]) { // this isn't the best way of doing this I guess, but I didn't want a whole seperate string array + // for storing shader names. I can't just replace q3HeadNames with the shader name, because we + // print what's in q3HeadNames and the icon name would look funny. char iconNameFromSkinName[256]; int i = 0; int skinPlace; i = strlen(uiInfo.q3HeadNames[index]); - while (uiInfo.q3HeadNames[index][i] != '/') - { + while (uiInfo.q3HeadNames[index][i] != '/') { i--; } i++; - skinPlace = i; //remember that this is where the skin name begins + skinPlace = i; // remember that this is where the skin name begins - //now, build a full path out of what's in q3HeadNames, into iconNameFromSkinName + // now, build a full path out of what's in q3HeadNames, into iconNameFromSkinName Com_sprintf(iconNameFromSkinName, sizeof(iconNameFromSkinName), "models/players/%s", uiInfo.q3HeadNames[index]); i = strlen(iconNameFromSkinName); - while (iconNameFromSkinName[i] != '/') - { + while (iconNameFromSkinName[i] != '/') { i--; } i++; - iconNameFromSkinName[i] = 0; //terminate, and append.. + iconNameFromSkinName[i] = 0; // terminate, and append.. Q_strcat(iconNameFromSkinName, 256, "icon_"); - //and now, for the final step, append the skin name from q3HeadNames onto the end of iconNameFromSkinName + // and now, for the final step, append the skin name from q3HeadNames onto the end of iconNameFromSkinName i = strlen(iconNameFromSkinName); - while (uiInfo.q3HeadNames[index][skinPlace]) - { + while (uiInfo.q3HeadNames[index][skinPlace]) { iconNameFromSkinName[i] = uiInfo.q3HeadNames[index][skinPlace]; i++; skinPlace++; } iconNameFromSkinName[i] = 0; - //and now we are ready to register (thankfully this will only happen once) + // and now we are ready to register (thankfully this will only happen once) uiInfo.q3HeadIcons[index] = trap->R_RegisterShaderNoMip(iconNameFromSkinName); } return uiInfo.q3HeadIcons[index]; } - } - else if (feederID == FEEDER_SIEGE_TEAM1) - { - if (!siegeTeam1) - { + } else if (feederID == FEEDER_SIEGE_TEAM1) { + if (!siegeTeam1) { UI_SetSiegeTeams(); - if (!siegeTeam1) - { + if (!siegeTeam1) { return 0; } } - if (siegeTeam1->classes[index]) - { + if (siegeTeam1->classes[index]) { return siegeTeam1->classes[index]->uiPortraitShader; } return 0; - } - else if (feederID == FEEDER_SIEGE_TEAM2) - { - if (!siegeTeam2) - { + } else if (feederID == FEEDER_SIEGE_TEAM2) { + if (!siegeTeam2) { UI_SetSiegeTeams(); - if (!siegeTeam2) - { + if (!siegeTeam2) { return 0; } } - if (siegeTeam2->classes[index]) - { + if (siegeTeam2->classes[index]) { return siegeTeam2->classes[index]->uiPortraitShader; } return 0; - } - else if (feederID == FEEDER_ALLMAPS || feederID == FEEDER_MAPS) - { + } else if (feederID == FEEDER_ALLMAPS || feederID == FEEDER_MAPS) { int actual; UI_SelectedMap(index, &actual); index = actual; @@ -8630,243 +7683,182 @@ static qhandle_t UI_FeederItemImage(float feederID, int index) { } return uiInfo.mapList[index].levelShot; } - } - else if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadIcons[index]; - return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadIcons[index]; + return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name)); } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoIcons[index]; - return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoIcons[index]; + return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name)); } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { - //return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegIcons[index]; - return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { + // return uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegIcons[index]; + return trap->R_RegisterShaderNoMip(va("models/players/%s/icon_%s", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Name, + uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name)); } - } - else if (feederID == FEEDER_COLORCHOICES) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { - return trap->R_RegisterShaderNoMip( uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); + } else if (feederID == FEEDER_COLORCHOICES) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { + return trap->R_RegisterShaderNoMip(uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].shader); } } - else if ( feederID == FEEDER_SIEGE_BASE_CLASS) - { - int team,baseClass; + else if (feederID == FEEDER_SIEGE_BASE_CLASS) { + int team, baseClass; team = (int)trap->Cvar_VariableValue("ui_team"); baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); - if ((team == SIEGETEAM_TEAM1) || - (team == SIEGETEAM_TEAM2)) - { + if ((team == SIEGETEAM_TEAM1) || (team == SIEGETEAM_TEAM2)) { // Is it a valid base class? - if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) - { - if (index >= 0) - { - return(BG_GetUIPortrait(team, baseClass, index)); + if ((baseClass >= SPC_INFANTRY) && (baseClass < SPC_MAX)) { + if (index >= 0) { + return (BG_GetUIPortrait(team, baseClass, index)); } } } - } - else if ( feederID == FEEDER_SIEGE_CLASS_WEAPONS) - { + } else if (feederID == FEEDER_SIEGE_CLASS_WEAPONS) { validCnt = 0; - //count them up - for (i=0;i< WP_NUM_WEAPONS;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_weapon%i", i), info, sizeof(info) ); - if (Q_stricmp(info,"gfx/2d/select")!=0) - { - if (validCnt == index) - { - return(trap->R_RegisterShaderNoMip(info)); + // count them up + for (i = 0; i < WP_NUM_WEAPONS; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_weapon%i", i), info, sizeof(info)); + if (Q_stricmp(info, "gfx/2d/select") != 0) { + if (validCnt == index) { + return (trap->R_RegisterShaderNoMip(info)); } validCnt++; } } - } - else if ( feederID == FEEDER_SIEGE_CLASS_INVENTORY) - { + } else if (feederID == FEEDER_SIEGE_CLASS_INVENTORY) { validCnt = 0; - //count them up - for (i=0;i< HI_NUM_HOLDABLE;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_item%i", i), info, sizeof(info) ); + // count them up + for (i = 0; i < HI_NUM_HOLDABLE; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_item%i", i), info, sizeof(info)); // A hack so health and ammo dispenser icons don't show up. - if ((Q_stricmp(info,"gfx/2d/select")!=0) - && (Q_stricmp(info,"gfx/hud/i_icon_healthdisp")!=0) && - (Q_stricmp(info,"gfx/hud/i_icon_ammodisp")!=0)) - { - if (validCnt == index) - { - return(trap->R_RegisterShaderNoMip(info)); + if ((Q_stricmp(info, "gfx/2d/select") != 0) && (Q_stricmp(info, "gfx/hud/i_icon_healthdisp") != 0) && + (Q_stricmp(info, "gfx/hud/i_icon_ammodisp") != 0)) { + if (validCnt == index) { + return (trap->R_RegisterShaderNoMip(info)); } validCnt++; } } - } - else if ( feederID == FEEDER_SIEGE_CLASS_FORCE) - { - int slotI=0; + } else if (feederID == FEEDER_SIEGE_CLASS_FORCE) { + int slotI = 0; static char info2[MAX_STRING_CHARS]; menuDef_t *menu; itemDef_t *item; - validCnt = 0; - - menu = Menu_GetFocused(); // Get current menu - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "base_class_force_feed"); - if (item) - { + menu = Menu_GetFocused(); // Get current menu + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "base_class_force_feed"); + if (item) { listBoxDef_t *listPtr = item->typeData.listbox; - if (listPtr) - { + if (listPtr) { slotI = listPtr->startPos; } } } - //count them up - for (i=0;i< NUM_FORCE_POWERS;i++) - { - trap->Cvar_VariableStringBuffer( va("ui_class_power%i", i), info, sizeof(info) ); - if (Q_stricmp(info,"gfx/2d/select")!=0) - { - if (validCnt == index) - { - trap->Cvar_VariableStringBuffer( va("ui_class_powerlevel%i", validCnt), info2, sizeof(info2) ); + // count them up + for (i = 0; i < NUM_FORCE_POWERS; i++) { + trap->Cvar_VariableStringBuffer(va("ui_class_power%i", i), info, sizeof(info)); + if (Q_stricmp(info, "gfx/2d/select") != 0) { + if (validCnt == index) { + trap->Cvar_VariableStringBuffer(va("ui_class_powerlevel%i", validCnt), info2, sizeof(info2)); - trap->Cvar_Set(va("ui_class_powerlevelslot%i", index-slotI), info2); - return(trap->R_RegisterShaderNoMip(info)); + trap->Cvar_Set(va("ui_class_powerlevelslot%i", index - slotI), info2); + return (trap->R_RegisterShaderNoMip(info)); } validCnt++; } } } - return 0; + return 0; } -qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) -{ +qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) { static char info[MAX_STRING_CHARS]; const int feederID = feederFloat; - if (feederID == FEEDER_Q3HEADS) - { + if (feederID == FEEDER_Q3HEADS) { int actual = 0; UI_SelectedTeamHead(index, &actual); uiInfo.q3SelectedHead = index; trap->Cvar_Set("ui_selectedModelIndex", va("%i", index)); index = actual; - if (index >= 0 && index < uiInfo.q3HeadCount) - { - trap->Cvar_Set( "model", uiInfo.q3HeadNames[index]); //standard model - trap->Cvar_Set ( "char_color_red", "255" ); //standard colors - trap->Cvar_Set ( "char_color_green", "255" ); - trap->Cvar_Set ( "char_color_blue", "255" ); + if (index >= 0 && index < uiInfo.q3HeadCount) { + trap->Cvar_Set("model", uiInfo.q3HeadNames[index]); // standard model + trap->Cvar_Set("char_color_red", "255"); // standard colors + trap->Cvar_Set("char_color_green", "255"); + trap->Cvar_Set("char_color_blue", "255"); } - } - else if (feederID == FEEDER_MOVES) - { + } else if (feederID == FEEDER_MOVES) { itemDef_t *item; menuDef_t *menu; modelDef_t *modelPtr; menu = Menus_FindByName("rulesMenu_moves"); - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { modelPtr = item->typeData.model; - if (modelPtr) - { + if (modelPtr) { char modelPath[MAX_QPATH]; int animRunLength; - ItemParse_model_g2anim_go( item, datapadMoveData[uiInfo.movesTitleIndex][index].anim ); + ItemParse_model_g2anim_go(item, datapadMoveData[uiInfo.movesTitleIndex][index].anim); - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", UI_Cvar_VariableString ( "ui_char_model" ) ); - ItemParse_asset_model_go( item, modelPath, &animRunLength ); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", UI_Cvar_VariableString("ui_char_model")); + ItemParse_asset_model_go(item, modelPath, &animRunLength); UI_UpdateCharacterSkin(); uiInfo.moveAnimTime = uiInfo.uiDC.realTime + animRunLength; - if (datapadMoveData[uiInfo.movesTitleIndex][index].anim) - { + if (datapadMoveData[uiInfo.movesTitleIndex][index].anim) { // Play sound for anim - if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_FORCE_JUMP) - { - trap->S_StartLocalSound( uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL ); - } - else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_ROLL) - { - trap->S_StartLocalSound( uiInfo.uiDC.Assets.moveRollSound, CHAN_LOCAL ); - } - else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_SABER) - { + if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_FORCE_JUMP) { + trap->S_StartLocalSound(uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL); + } else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_ROLL) { + trap->S_StartLocalSound(uiInfo.uiDC.Assets.moveRollSound, CHAN_LOCAL); + } else if (datapadMoveData[uiInfo.movesTitleIndex][index].sound == MDS_SABER) { // Randomly choose one sound - int soundI = Q_irand( 1, 6 ); + int soundI = Q_irand(1, 6); sfxHandle_t *soundPtr; soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound1; - if (soundI == 2) - { + if (soundI == 2) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound2; - } - else if (soundI == 3) - { + } else if (soundI == 3) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound3; - } - else if (soundI == 4) - { + } else if (soundI == 4) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound4; - } - else if (soundI == 5) - { + } else if (soundI == 5) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound5; - } - else if (soundI == 6) - { + } else if (soundI == 6) { soundPtr = &uiInfo.uiDC.Assets.datapadmoveSaberSound6; } - trap->S_StartLocalSound( *soundPtr, CHAN_LOCAL ); + trap->S_StartLocalSound(*soundPtr, CHAN_LOCAL); } - if (datapadMoveData[uiInfo.movesTitleIndex][index].desc) - { - trap->Cvar_Set( "ui_move_desc", datapadMoveData[uiInfo.movesTitleIndex][index].desc); + if (datapadMoveData[uiInfo.movesTitleIndex][index].desc) { + trap->Cvar_Set("ui_move_desc", datapadMoveData[uiInfo.movesTitleIndex][index].desc); } } - UI_SaberAttachToChar( item ); + UI_SaberAttachToChar(item); } } } - } - else if (feederID == FEEDER_MOVES_TITLES) - { + } else if (feederID == FEEDER_MOVES_TITLES) { itemDef_t *item; menuDef_t *menu; modelDef_t *modelPtr; @@ -8875,98 +7867,77 @@ qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) uiInfo.movesBaseAnim = datapadMoveTitleBaseAnims[uiInfo.movesTitleIndex]; menu = Menus_FindByName("rulesMenu_moves"); - if (menu) - { - item = (itemDef_t *) Menu_FindItemByName((menuDef_t *) menu, "character"); - if (item) - { + if (menu) { + item = (itemDef_t *)Menu_FindItemByName((menuDef_t *)menu, "character"); + if (item) { modelPtr = item->typeData.model; - if (modelPtr) - { + if (modelPtr) { char modelPath[MAX_QPATH]; - int animRunLength; + int animRunLength; uiInfo.movesBaseAnim = datapadMoveTitleBaseAnims[uiInfo.movesTitleIndex]; - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", UI_Cvar_VariableString ( "ui_char_model" ) ); - ItemParse_asset_model_go( item, modelPath, &animRunLength ); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", UI_Cvar_VariableString("ui_char_model")); + ItemParse_asset_model_go(item, modelPath, &animRunLength); UI_UpdateCharacterSkin(); - } } } - } - else if (feederID == FEEDER_SIEGE_TEAM1) - { - if (!g_siegedFeederForcedSet) - { + } else if (feederID == FEEDER_SIEGE_TEAM1) { + if (!g_siegedFeederForcedSet) { g_UIGloballySelectedSiegeClass = UI_SiegeClassNum(siegeTeam1->classes[index]); trap->Cvar_Set("ui_classDesc", g_UIClassDescriptions[g_UIGloballySelectedSiegeClass].desc); - //g_siegedFeederForcedSet = 1; - //Menu_SetFeederSelection(NULL, FEEDER_SIEGE_TEAM2, -1, NULL); + // g_siegedFeederForcedSet = 1; + // Menu_SetFeederSelection(NULL, FEEDER_SIEGE_TEAM2, -1, NULL); UI_SiegeSetCvarsForClass(siegeTeam1->classes[index]); } g_siegedFeederForcedSet = 0; - } - else if (feederID == FEEDER_SIEGE_TEAM2) - { - if (!g_siegedFeederForcedSet) - { + } else if (feederID == FEEDER_SIEGE_TEAM2) { + if (!g_siegedFeederForcedSet) { g_UIGloballySelectedSiegeClass = UI_SiegeClassNum(siegeTeam2->classes[index]); trap->Cvar_Set("ui_classDesc", g_UIClassDescriptions[g_UIGloballySelectedSiegeClass].desc); - //g_siegedFeederForcedSet = 1; - //Menu_SetFeederSelection(NULL, FEEDER_SIEGE_TEAM2, -1, NULL); + // g_siegedFeederForcedSet = 1; + // Menu_SetFeederSelection(NULL, FEEDER_SIEGE_TEAM2, -1, NULL); UI_SiegeSetCvarsForClass(siegeTeam2->classes[index]); } g_siegedFeederForcedSet = 0; - } - else if (feederID == FEEDER_FORCECFG) - { + } else if (feederID == FEEDER_FORCECFG) { int newindex = index; - if (uiForceSide == FORCE_LIGHTSIDE) - { + if (uiForceSide == FORCE_LIGHTSIDE) { newindex += uiInfo.forceConfigLightIndexBegin; - if (newindex >= uiInfo.forceConfigCount) - { + if (newindex >= uiInfo.forceConfigCount) { return qfalse; } - } - else - { //else dark + } else { // else dark newindex += uiInfo.forceConfigDarkIndexBegin; - if (newindex >= uiInfo.forceConfigCount || newindex > uiInfo.forceConfigLightIndexBegin) - { //dark gets read in before light + if (newindex >= uiInfo.forceConfigCount || newindex > uiInfo.forceConfigLightIndexBegin) { // dark gets read in before light return qfalse; } } - if (index >= 0 && index < uiInfo.forceConfigCount) - { - UI_ForceConfigHandle(uiInfo.forceConfigSelected, index); - uiInfo.forceConfigSelected = index; + if (index >= 0 && index < uiInfo.forceConfigCount) { + UI_ForceConfigHandle(uiInfo.forceConfigSelected, index); + uiInfo.forceConfigSelected = index; } - } - else if (feederID == FEEDER_MAPS || feederID == FEEDER_ALLMAPS) - { + } else if (feederID == FEEDER_MAPS || feederID == FEEDER_ALLMAPS) { int actual, map; const char *checkValid = NULL; map = (feederID == FEEDER_ALLMAPS) ? ui_currentNetMap.integer : ui_currentMap.integer; if (uiInfo.mapList[map].cinematic >= 0) { - trap->CIN_StopCinematic(uiInfo.mapList[map].cinematic); - uiInfo.mapList[map].cinematic = -1; + trap->CIN_StopCinematic(uiInfo.mapList[map].cinematic); + uiInfo.mapList[map].cinematic = -1; } checkValid = UI_SelectedMap(index, &actual); - if (!checkValid || !checkValid[0]) - { //this isn't a valid map to select, so reselect the current + if (!checkValid || !checkValid[0]) { // this isn't a valid map to select, so reselect the current index = ui_mapIndex.integer; UI_SelectedMap(index, &actual); } @@ -8978,13 +7949,15 @@ qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) if (feederID == FEEDER_MAPS) { trap->Cvar_Set("ui_currentMap", va("%d", actual)); trap->Cvar_Update(&ui_currentMap); - uiInfo.mapList[ui_currentMap.integer].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); - //trap->Cvar_Set("ui_opponentModel", uiInfo.mapList[ui_currentMap.integer].opponentName); - //updateOpponentModel = qtrue; + uiInfo.mapList[ui_currentMap.integer].cinematic = + trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent)); + // trap->Cvar_Set("ui_opponentModel", uiInfo.mapList[ui_currentMap.integer].opponentName); + // updateOpponentModel = qtrue; } else { trap->Cvar_Set("ui_currentNetMap", va("%d", actual)); trap->Cvar_Update(&ui_currentNetMap); - uiInfo.mapList[ui_currentNetMap.integer].cinematic = trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); + uiInfo.mapList[ui_currentNetMap.integer].cinematic = + trap->CIN_PlayCinematic(va("%s.roq", uiInfo.mapList[ui_currentNetMap.integer].mapLoadName), 0, 0, 0, 0, (CIN_loop | CIN_silent)); } } else if (feederID == FEEDER_SERVERS) { @@ -8998,14 +7971,14 @@ qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) } mapName = Info_ValueForKey(info, "mapname"); if (mapName && *mapName) { - uiInfo.serverStatus.currentServerCinematic = trap->CIN_PlayCinematic(va("%s.roq", mapName), 0, 0, 0, 0, (CIN_loop | CIN_silent) ); + uiInfo.serverStatus.currentServerCinematic = trap->CIN_PlayCinematic(va("%s.roq", mapName), 0, 0, 0, 0, (CIN_loop | CIN_silent)); } } else if (feederID == FEEDER_SERVERSTATUS) { // } else if (feederID == FEEDER_FINDPLAYER) { uiInfo.currentFoundPlayerServer = index; // - if ( index < uiInfo.numFoundPlayerServers-1) { + if (index < uiInfo.numFoundPlayerServers - 1) { // build a new server status for this server Q_strncpyz(uiInfo.serverStatusAddress, uiInfo.foundPlayerServerAddresses[uiInfo.currentFoundPlayerServer], sizeof(uiInfo.serverStatusAddress)); Menu_SetFeederSelection(NULL, FEEDER_SERVERSTATUS, 0, NULL); @@ -9025,85 +7998,57 @@ qboolean UI_FeederSelection(float feederFloat, int index, itemDef_t *item) uiInfo.previewMovie = -1; } else if (feederID == FEEDER_DEMOS) { uiInfo.demoIndex = index; - } - else if (feederID == FEEDER_COLORCHOICES) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) - { + } else if (feederID == FEEDER_COLORCHOICES) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].ColorCount) { Item_RunScript(item, uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].Color[index].actionText); } - } - else if (feederID == FEEDER_PLAYER_SKIN_HEAD) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_HEAD) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHeadCount) { trap->Cvar_Set("ui_char_skin_head", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinHead[index].name); } - } - else if (feederID == FEEDER_PLAYER_SKIN_TORSO) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_TORSO) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorsoCount) { trap->Cvar_Set("ui_char_skin_torso", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinTorso[index].name); } - } - else if (feederID == FEEDER_PLAYER_SKIN_LEGS) - { - if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) - { + } else if (feederID == FEEDER_PLAYER_SKIN_LEGS) { + if (index >= 0 && index < uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLegCount) { trap->Cvar_Set("ui_char_skin_legs", uiInfo.playerSpecies[uiInfo.playerSpeciesIndex].SkinLeg[index].name); } - } - else if (feederID == FEEDER_PLAYER_SPECIES) - { - if (index >= 0 && index < uiInfo.playerSpeciesCount) - { + } else if (feederID == FEEDER_PLAYER_SPECIES) { + if (index >= 0 && index < uiInfo.playerSpeciesCount) { uiInfo.playerSpeciesIndex = index; } - } - else if (feederID == FEEDER_LANGUAGES) - { + } else if (feederID == FEEDER_LANGUAGES) { uiInfo.languageCountIndex = index; - } - else if ( feederID == FEEDER_SIEGE_BASE_CLASS ) - { - int team,baseClass; + } else if (feederID == FEEDER_SIEGE_BASE_CLASS) { + int team, baseClass; team = (int)trap->Cvar_VariableValue("ui_team"); baseClass = (int)trap->Cvar_VariableValue("ui_siege_class"); UI_UpdateCvarsForClass(team, baseClass, index); - } - else if (feederID == FEEDER_SIEGE_CLASS_WEAPONS) - { -// trap->Cvar_VariableStringBuffer( va("ui_class_weapondesc%i", index), info, sizeof(info) ); -// trap->Cvar_Set( "ui_itemforceinvdesc", info ); - } - else if (feederID == FEEDER_SIEGE_CLASS_INVENTORY) - { -// trap->Cvar_VariableStringBuffer( va("ui_class_itemdesc%i", index), info, sizeof(info) ); -// trap->Cvar_Set( "ui_itemforceinvdesc", info ); - } - else if (feederID == FEEDER_SIEGE_CLASS_FORCE) - { + } else if (feederID == FEEDER_SIEGE_CLASS_WEAPONS) { + // trap->Cvar_VariableStringBuffer( va("ui_class_weapondesc%i", index), info, sizeof(info) ); + // trap->Cvar_Set( "ui_itemforceinvdesc", info ); + } else if (feederID == FEEDER_SIEGE_CLASS_INVENTORY) { + // trap->Cvar_VariableStringBuffer( va("ui_class_itemdesc%i", index), info, sizeof(info) ); + // trap->Cvar_Set( "ui_itemforceinvdesc", info ); + } else if (feederID == FEEDER_SIEGE_CLASS_FORCE) { int i; -// int validCnt = 0; + // int validCnt = 0; - trap->Cvar_VariableStringBuffer( va("ui_class_power%i", index), info, sizeof(info) ); + trap->Cvar_VariableStringBuffer(va("ui_class_power%i", index), info, sizeof(info)); - //count them up - for (i=0;i< NUM_FORCE_POWERS;i++) - { - if (!strcmp(HolocronIcons[i],info)) - { - trap->Cvar_Set( "ui_itemforceinvdesc", forcepowerDesc[i] ); + // count them up + for (i = 0; i < NUM_FORCE_POWERS; i++) { + if (!strcmp(HolocronIcons[i], info)) { + trap->Cvar_Set("ui_itemforceinvdesc", forcepowerDesc[i]); } } } return qtrue; } - static qboolean GameType_Parse(char **p, qboolean join) { char *token; @@ -9119,21 +8064,22 @@ static qboolean GameType_Parse(char **p, qboolean join) { uiInfo.numGameTypes = 0; } - while ( 1 ) { + while (1) { token = COM_ParseExt((const char **)p, qtrue); if (Q_stricmp(token, "}") == 0) { return qtrue; } - if ( !token || token[0] == 0 ) { + if (!token || token[0] == 0) { return qfalse; } if (token[0] == '{') { // two tokens per line, character name and sex if (join) { - if (!String_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gameType) || !Int_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gtEnum)) { + if (!String_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gameType) || + !Int_Parse(p, &uiInfo.joinGameTypes[uiInfo.numJoinGameTypes].gtEnum)) { return qfalse; } } else { @@ -9176,20 +8122,20 @@ static qboolean MapList_Parse(char **p) { uiInfo.mapCount = 0; - while ( 1 ) { + while (1) { token = COM_ParseExt((const char **)p, qtrue); if (Q_stricmp(token, "}") == 0) { return qtrue; } - if ( !token || token[0] == 0 ) { + if (!token || token[0] == 0) { return qfalse; } if (token[0] == '{') { - if (!String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapName) || !String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapLoadName) - ||!Int_Parse(p, &uiInfo.mapList[uiInfo.mapCount].teamMembers) ) { + if (!String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapName) || !String_Parse(p, &uiInfo.mapList[uiInfo.mapCount].mapLoadName) || + !Int_Parse(p, &uiInfo.mapList[uiInfo.mapCount].teamMembers)) { return qfalse; } @@ -9208,12 +8154,13 @@ static qboolean MapList_Parse(char **p) { } } - //mapList[mapCount].imageName = String_Alloc(va("levelshots/%s", mapList[mapCount].mapLoadName)); - //if (uiInfo.mapCount == 0) { - // only load the first cinematic, selection loads the others - // uiInfo.mapList[uiInfo.mapCount].cinematic = trap->CIN_PlayCinematic(va("%s.roq",uiInfo.mapList[uiInfo.mapCount].mapLoadName), qfalse, qfalse, qtrue, 0, 0, 0, 0); + // mapList[mapCount].imageName = String_Alloc(va("levelshots/%s", mapList[mapCount].mapLoadName)); + // if (uiInfo.mapCount == 0) { + // only load the first cinematic, selection loads the others + // uiInfo.mapList[uiInfo.mapCount].cinematic = trap->CIN_PlayCinematic(va("%s.roq",uiInfo.mapList[uiInfo.mapCount].mapLoadName), qfalse, qfalse, + // qtrue, 0, 0, 0, 0); //} - uiInfo.mapList[uiInfo.mapCount].cinematic = -1; + uiInfo.mapList[uiInfo.mapCount].cinematic = -1; uiInfo.mapList[uiInfo.mapCount].levelShot = trap->R_RegisterShaderNoMip(va("levelshots/%s_small", uiInfo.mapList[uiInfo.mapCount].mapLoadName)); if (uiInfo.mapCount < MAX_MAPS) { @@ -9227,10 +8174,10 @@ static qboolean MapList_Parse(char **p) { } static void UI_ParseGameInfo(const char *teamFile) { - char *token; + char *token; char *p; char *buff = NULL; - //int mode = 0; TTimo: unused + // int mode = 0; TTimo: unused buff = GetMenuBuffer(teamFile); if (!buff) { @@ -9239,15 +8186,15 @@ static void UI_ParseGameInfo(const char *teamFile) { p = buff; - COM_BeginParseSession ("UI_ParseGameInfo"); + COM_BeginParseSession("UI_ParseGameInfo"); - while ( 1 ) { - token = COM_ParseExt( (const char **)(&p), qtrue ); - if( !token || token[0] == 0 || token[0] == '}') { + while (1) { + token = COM_ParseExt((const char **)(&p), qtrue); + if (!token || token[0] == 0 || token[0] == '}') { break; } - if ( Q_stricmp( token, "}" ) == 0 ) { + if (Q_stricmp(token, "}") == 0) { break; } @@ -9273,26 +8220,23 @@ static void UI_ParseGameInfo(const char *teamFile) { // start a new menu MapList_Parse(&p); } - } } static void UI_Pause(qboolean b) { if (b) { // pause the game and set the ui keycatcher - trap->Cvar_Set( "cl_paused", "1" ); - trap->Key_SetCatcher( KEYCATCH_UI ); + trap->Cvar_Set("cl_paused", "1"); + trap->Key_SetCatcher(KEYCATCH_UI); } else { // unpause the game and clear the ui keycatcher - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); } } -static int UI_PlayCinematic(const char *name, float x, float y, float w, float h) { - return trap->CIN_PlayCinematic(name, x, y, w, h, (CIN_loop | CIN_silent)); -} +static int UI_PlayCinematic(const char *name, float x, float y, float w, float h) { return trap->CIN_PlayCinematic(name, x, y, w, h, (CIN_loop | CIN_silent)); } static void UI_StopCinematic(int handle) { if (handle >= 0) { @@ -9326,10 +8270,7 @@ static void UI_DrawCinematic(int handle, float x, float y, float w, float h) { trap->CIN_DrawCinematic(handle); } -static void UI_RunCinematicFrame(int handle) { - trap->CIN_RunCinematic(handle); -} - +static void UI_RunCinematicFrame(int handle) { trap->CIN_RunCinematic(handle); } /* ================= @@ -9337,86 +8278,72 @@ UI_LoadForceConfig_List ================= Looks in the directory for force config files (.fcf) and loads the name in */ -void UI_LoadForceConfig_List( void ) -{ - int numfiles = 0; - char filelist[2048]; - char configname[128]; - char *fileptr = NULL; - int j = 0; - int filelen = 0; - qboolean lightSearch = qfalse; +void UI_LoadForceConfig_List(void) { + int numfiles = 0; + char filelist[2048]; + char configname[128]; + char *fileptr = NULL; + int j = 0; + int filelen = 0; + qboolean lightSearch = qfalse; uiInfo.forceConfigCount = 0; - Com_sprintf( uiInfo.forceConfigNames[uiInfo.forceConfigCount], sizeof(uiInfo.forceConfigNames[uiInfo.forceConfigCount]), "Custom"); + Com_sprintf(uiInfo.forceConfigNames[uiInfo.forceConfigCount], sizeof(uiInfo.forceConfigNames[uiInfo.forceConfigCount]), "Custom"); uiInfo.forceConfigCount++; - //Always reserve index 0 as the "custom" config + // Always reserve index 0 as the "custom" config nextSearch: - if (lightSearch) - { //search light side folder - numfiles = trap->FS_GetFileList("forcecfg/light", "fcf", filelist, 2048 ); - uiInfo.forceConfigLightIndexBegin = uiInfo.forceConfigCount-1; - } - else - { //search dark side folder - numfiles = trap->FS_GetFileList("forcecfg/dark", "fcf", filelist, 2048 ); - uiInfo.forceConfigDarkIndexBegin = uiInfo.forceConfigCount-1; + if (lightSearch) { // search light side folder + numfiles = trap->FS_GetFileList("forcecfg/light", "fcf", filelist, 2048); + uiInfo.forceConfigLightIndexBegin = uiInfo.forceConfigCount - 1; + } else { // search dark side folder + numfiles = trap->FS_GetFileList("forcecfg/dark", "fcf", filelist, 2048); + uiInfo.forceConfigDarkIndexBegin = uiInfo.forceConfigCount - 1; } fileptr = filelist; - for (j=0; jFS_Open(fpath, &f, FS_READ); - if (!f) - { //not there, try png + if (!f) { // not there, try png Com_sprintf(fpath, MAX_QPATH, "models/players/%s/icon_%s.png", dirptr, skinname); trap->FS_Open(fpath, &f, FS_READ); } - if (!f) - { //not there, try tga + if (!f) { // not there, try tga Com_sprintf(fpath, MAX_QPATH, "models/players/%s/icon_%s.tga", dirptr, skinname); trap->FS_Open(fpath, &f, FS_READ); } - if (f) - { + if (f) { trap->FS_Close(f); return qtrue; } @@ -9424,64 +8351,57 @@ static qboolean bIsImageFile(const char* dirptr, const char* skinname) return qfalse; } - /* ================= PlayerModel_BuildList ================= */ -static void UI_BuildQ3Model_List( void ) -{ - int numdirs; - int numfiles; - char dirlist[2048]; - char filelist[2048]; - char skinname[64]; - char* dirptr; - char* fileptr; - char* check; - int i; - int j, k, p, s; - int dirlen; - int filelen; +static void UI_BuildQ3Model_List(void) { + int numdirs; + int numfiles; + char dirlist[2048]; + char filelist[2048]; + char skinname[64]; + char *dirptr; + char *fileptr; + char *check; + int i; + int j, k, p, s; + int dirlen; + int filelen; uiInfo.q3HeadCount = 0; // iterate directory of all player models - numdirs = trap->FS_GetFileList("models/players", "/", dirlist, 2048 ); - dirptr = dirlist; - for (i=0; iFS_GetFileList("models/players", "/", dirlist, 2048); + dirptr = dirlist; + for (i = 0; i < numdirs && uiInfo.q3HeadCount < MAX_Q3PLAYERMODELS; i++, dirptr += dirlen + 1) { dirlen = strlen(dirptr); - if (dirlen && dirptr[dirlen-1]=='/') dirptr[dirlen-1]='\0'; + if (dirlen && dirptr[dirlen - 1] == '/') + dirptr[dirlen - 1] = '\0'; - if (!strcmp(dirptr,".") || !strcmp(dirptr,"..")) + if (!strcmp(dirptr, ".") || !strcmp(dirptr, "..")) continue; - - numfiles = trap->FS_GetFileList( va("models/players/%s",dirptr), "skin", filelist, 2048 ); - fileptr = filelist; - for (j=0; jFS_GetFileList(va("models/players/%s", dirptr), "skin", filelist, 2048); + fileptr = filelist; + for (j = 0; j < numfiles && uiInfo.q3HeadCount < MAX_Q3PLAYERMODELS; j++, fileptr += filelen + 1) { int skinLen = 0; filelen = strlen(fileptr); - COM_StripExtension(fileptr,skinname, sizeof( skinname ) ); + COM_StripExtension(fileptr, skinname, sizeof(skinname)); skinLen = strlen(skinname); k = 0; - while (k < skinLen && skinname[k] && skinname[k] != '_') - { + while (k < skinLen && skinname[k] && skinname[k] != '_') { k++; } - if (skinname[k] == '_') - { + if (skinname[k] == '_') { p = 0; - while (skinname[k]) - { + while (skinname[k]) { skinname[p] = skinname[k]; k++; p++; @@ -9497,63 +8417,53 @@ static void UI_BuildQ3Model_List( void ) if (f) */ check = &skinname[1]; - if (bIsImageFile(dirptr, check)) - { //if it exists + if (bIsImageFile(dirptr, check)) { // if it exists qboolean iconExists = qfalse; - //trap->FS_Close(f); + // trap->FS_Close(f); - if (skinname[0] == '_') - { //change character to append properly + if (skinname[0] == '_') { // change character to append properly skinname[0] = '/'; } s = 0; - while (s < uiInfo.q3HeadCount) - { //check for dupes - if (!Q_stricmp(va("%s%s", dirptr, skinname), uiInfo.q3HeadNames[s])) - { + while (s < uiInfo.q3HeadCount) { // check for dupes + if (!Q_stricmp(va("%s%s", dirptr, skinname), uiInfo.q3HeadNames[s])) { iconExists = qtrue; break; } s++; } - if (iconExists) - { + if (iconExists) { continue; } - Com_sprintf( uiInfo.q3HeadNames[uiInfo.q3HeadCount], sizeof(uiInfo.q3HeadNames[uiInfo.q3HeadCount]), va("%s%s", dirptr, skinname)); - uiInfo.q3HeadIcons[uiInfo.q3HeadCount++] = 0;//trap->R_RegisterShaderNoMip(fpath); - //rww - we are now registering them as they are drawn like the TA feeder, so as to decrease UI load time. + Com_sprintf(uiInfo.q3HeadNames[uiInfo.q3HeadCount], sizeof(uiInfo.q3HeadNames[uiInfo.q3HeadCount]), va("%s%s", dirptr, skinname)); + uiInfo.q3HeadIcons[uiInfo.q3HeadCount++] = 0; // trap->R_RegisterShaderNoMip(fpath); + // rww - we are now registering them as they are drawn like the TA feeder, so as to decrease UI load time. } - if (uiInfo.q3HeadCount >= MAX_Q3PLAYERMODELS) - { + if (uiInfo.q3HeadCount >= MAX_Q3PLAYERMODELS) { return; } } } - } -void UI_SiegeInit(void) -{ - //Load the player class types +void UI_SiegeInit(void) { + // Load the player class types BG_SiegeLoadClasses(g_UIClassDescriptions); - if (!bgNumSiegeClasses) - { //We didn't find any?! + if (!bgNumSiegeClasses) { // We didn't find any?! Com_Error(ERR_DROP, "Couldn't find any player classes for Siege"); } - //Now load the teams since we have class data. + // Now load the teams since we have class data. BG_SiegeLoadTeams(); - if (!bgNumSiegeTeams) - { //React same as with classes. + if (!bgNumSiegeTeams) { // React same as with classes. Com_Error(ERR_DROP, "Couldn't find any player teams for Siege"); } } @@ -9563,11 +8473,10 @@ void UI_SiegeInit(void) UI_ParseColorData ================= */ -//static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t &species) -static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t *species,char* file) -{ - const char *token; - const char *p; +// static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t &species) +static qboolean UI_ParseColorData(char *buf, playerSpeciesInfo_t *species, char *file) { + const char *token; + const char *p; p = buf; COM_BeginParseSession(file); @@ -9575,47 +8484,40 @@ static qboolean UI_ParseColorData(char* buf, playerSpeciesInfo_t *species,char* species->ColorMax = 16; species->Color = (playerColor_t *)malloc(species->ColorMax * sizeof(playerColor_t)); - while ( p ) - { - token = COM_ParseExt( &p, qtrue ); //looking for the shader - if ( token[0] == 0 ) - { + while (p) { + token = COM_ParseExt(&p, qtrue); // looking for the shader + if (token[0] == 0) { return species->ColorCount; } - if (species->ColorCount >= species->ColorMax) - { + if (species->ColorCount >= species->ColorMax) { species->ColorMax *= 2; species->Color = (playerColor_t *)realloc(species->Color, species->ColorMax * sizeof(playerColor_t)); } memset(&species->Color[species->ColorCount], 0, sizeof(playerColor_t)); - Q_strncpyz( species->Color[species->ColorCount].shader, token, MAX_QPATH ); + Q_strncpyz(species->Color[species->ColorCount].shader, token, MAX_QPATH); - token = COM_ParseExt( &p, qtrue ); //looking for action block { - if ( token[0] != '{' ) - { + token = COM_ParseExt(&p, qtrue); // looking for action block { + if (token[0] != '{') { return qfalse; } - token = COM_ParseExt( &p, qtrue ); //looking for action commands - while (token[0] != '}') - { - if ( token[0] == 0) - { //EOF + token = COM_ParseExt(&p, qtrue); // looking for action commands + while (token[0] != '}') { + if (token[0] == 0) { // EOF return qfalse; } Q_strcat(species->Color[species->ColorCount].actionText, ACTION_BUFFER_SIZE, token); Q_strcat(species->Color[species->ColorCount].actionText, ACTION_BUFFER_SIZE, " "); - token = COM_ParseExt( &p, qtrue ); //looking for action commands or final } + token = COM_ParseExt(&p, qtrue); // looking for action commands or final } } - species->ColorCount++; //next color please + species->ColorCount++; // next color please } - return qtrue;//never get here + return qtrue; // never get here } -static void UI_FreeSpecies( playerSpeciesInfo_t *species ) -{ +static void UI_FreeSpecies(playerSpeciesInfo_t *species) { free(species->SkinHead); free(species->SkinTorso); free(species->SkinLeg); @@ -9623,12 +8525,10 @@ static void UI_FreeSpecies( playerSpeciesInfo_t *species ) memset(species, 0, sizeof(playerSpeciesInfo_t)); } -void UI_FreeAllSpecies( void ) -{ +void UI_FreeAllSpecies(void) { int i; - for (i = 0; i < uiInfo.playerSpeciesCount; i++) - { + for (i = 0; i < uiInfo.playerSpeciesCount; i++) { UI_FreeSpecies(&uiInfo.playerSpecies[i]); } free(uiInfo.playerSpecies); @@ -9639,25 +8539,23 @@ void UI_FreeAllSpecies( void ) UI_BuildPlayerModel_List ================= */ -static void UI_BuildPlayerModel_List( qboolean inGameLoad ) -{ +static void UI_BuildPlayerModel_List(qboolean inGameLoad) { static const size_t DIR_LIST_SIZE = 16384; - int numdirs; - size_t dirListSize = DIR_LIST_SIZE; - char stackDirList[8192]; - char *dirlist; - char* dirptr; - int dirlen; - int i; - int j; + int numdirs; + size_t dirListSize = DIR_LIST_SIZE; + char stackDirList[8192]; + char *dirlist; + char *dirptr; + int dirlen; + int i; + int j; dirlist = malloc(DIR_LIST_SIZE); - if ( !dirlist ) - { + if (!dirlist) { Com_Printf(S_COLOR_YELLOW "WARNING: Failed to allocate %u bytes of memory for player model " - "directory list. Using stack allocated buffer of %u bytes instead.", - DIR_LIST_SIZE, sizeof(stackDirList)); + "directory list. Using stack allocated buffer of %u bytes instead.", + DIR_LIST_SIZE, sizeof(stackDirList)); dirlist = stackDirList; dirListSize = sizeof(stackDirList); @@ -9669,46 +8567,40 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) uiInfo.playerSpecies = (playerSpeciesInfo_t *)malloc(uiInfo.playerSpeciesMax * sizeof(playerSpeciesInfo_t)); // iterate directory of all player models - numdirs = trap->FS_GetFileList("models/players", "/", dirlist, dirListSize ); - dirptr = dirlist; - for (i=0; iFS_GetFileList("models/players", "/", dirlist, dirListSize); + dirptr = dirlist; + for (i = 0; i < numdirs; i++, dirptr += dirlen + 1) { + char *fileptr; + int filelen; int f = 0; char fpath[MAX_QPATH]; dirlen = strlen(dirptr); - if (dirlen) - { - if (dirptr[dirlen-1]=='/') - dirptr[dirlen-1]='\0'; - } - else - { + if (dirlen) { + if (dirptr[dirlen - 1] == '/') + dirptr[dirlen - 1] = '\0'; + } else { continue; } - if (!strcmp(dirptr,".") || !strcmp(dirptr,"..")) + if (!strcmp(dirptr, ".") || !strcmp(dirptr, "..")) continue; Com_sprintf(fpath, sizeof(fpath), "models/players/%s/PlayerChoice.txt", dirptr); filelen = trap->FS_Open(fpath, &f, FS_READ); - if (f) - { - char filelist[2048]; + if (f) { + char filelist[2048]; playerSpeciesInfo_t *species; - char skinname[64]; - int numfiles; - int iSkinParts=0; - char *buffer = NULL; + char skinname[64]; + int numfiles; + int iSkinParts = 0; + char *buffer = NULL; buffer = malloc(filelen + 1); - if(!buffer) - { - trap->FS_Close( f ); + if (!buffer) { + trap->FS_Close(f); Com_Error(ERR_FATAL, "Could not allocate buffer to read %s", fpath); } @@ -9717,19 +8609,17 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) buffer[filelen] = 0; - //record this species - if (uiInfo.playerSpeciesCount >= uiInfo.playerSpeciesMax) - { + // record this species + if (uiInfo.playerSpeciesCount >= uiInfo.playerSpeciesMax) { uiInfo.playerSpeciesMax *= 2; - uiInfo.playerSpecies = (playerSpeciesInfo_t *)realloc(uiInfo.playerSpecies, uiInfo.playerSpeciesMax*sizeof(playerSpeciesInfo_t)); + uiInfo.playerSpecies = (playerSpeciesInfo_t *)realloc(uiInfo.playerSpecies, uiInfo.playerSpeciesMax * sizeof(playerSpeciesInfo_t)); } species = &uiInfo.playerSpecies[uiInfo.playerSpeciesCount]; memset(species, 0, sizeof(playerSpeciesInfo_t)); - Q_strncpyz( species->Name, dirptr, MAX_QPATH ); + Q_strncpyz(species->Name, dirptr, MAX_QPATH); - if (!UI_ParseColorData(buffer,species,fpath)) - { - Com_Printf(S_COLOR_RED"UI_BuildPlayerModel_List: Errors parsing '%s'\n", fpath); + if (!UI_ParseColorData(buffer, species, fpath)) { + Com_Printf(S_COLOR_RED "UI_BuildPlayerModel_List: Errors parsing '%s'\n", fpath); } species->SkinHeadMax = 8; @@ -9742,92 +8632,77 @@ static void UI_BuildPlayerModel_List( qboolean inGameLoad ) free(buffer); - numfiles = trap->FS_GetFileList( va("models/players/%s",dirptr), ".skin", filelist, sizeof(filelist) ); - fileptr = filelist; - for (j=0; jCvar_VariableValue("fs_copyfiles") > 0 ) - { - trap->FS_Open(va("models/players/%s/%s",dirptr,fileptr), &f, FS_READ); + numfiles = trap->FS_GetFileList(va("models/players/%s", dirptr), ".skin", filelist, sizeof(filelist)); + fileptr = filelist; + for (j = 0; j < numfiles; j++, fileptr += filelen + 1) { + if (trap->Cvar_VariableValue("fs_copyfiles") > 0) { + trap->FS_Open(va("models/players/%s/%s", dirptr, fileptr), &f, FS_READ); if (f) trap->FS_Close(f); } filelen = strlen(fileptr); - COM_StripExtension(fileptr,skinname,sizeof(skinname)); + COM_StripExtension(fileptr, skinname, sizeof(skinname)); - if (bIsImageFile(dirptr, skinname)) - { //if it exists - if (Q_stricmpn(skinname,"head_",5) == 0) - { - if (species->SkinHeadCount >= species->SkinHeadMax) - { + if (bIsImageFile(dirptr, skinname)) { // if it exists + if (Q_stricmpn(skinname, "head_", 5) == 0) { + if (species->SkinHeadCount >= species->SkinHeadMax) { species->SkinHeadMax *= 2; - species->SkinHead = (skinName_t *)realloc(species->SkinHead, species->SkinHeadMax*sizeof(skinName_t)); + species->SkinHead = (skinName_t *)realloc(species->SkinHead, species->SkinHeadMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinHead[species->SkinHeadCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<0; - } else - if (Q_stricmpn(skinname,"torso_",6) == 0) - { - if (species->SkinTorsoCount >= species->SkinTorsoMax) - { + iSkinParts |= 1 << 0; + } else if (Q_stricmpn(skinname, "torso_", 6) == 0) { + if (species->SkinTorsoCount >= species->SkinTorsoMax) { species->SkinTorsoMax *= 2; - species->SkinTorso = (skinName_t *)realloc(species->SkinTorso, species->SkinTorsoMax*sizeof(skinName_t)); + species->SkinTorso = (skinName_t *)realloc(species->SkinTorso, species->SkinTorsoMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinTorso[species->SkinTorsoCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<1; - } else - if (Q_stricmpn(skinname,"lower_",6) == 0) - { - if (species->SkinLegCount >= species->SkinLegMax) - { + iSkinParts |= 1 << 1; + } else if (Q_stricmpn(skinname, "lower_", 6) == 0) { + if (species->SkinLegCount >= species->SkinLegMax) { species->SkinLegMax *= 2; - species->SkinLeg = (skinName_t *)realloc(species->SkinLeg, species->SkinLegMax*sizeof(skinName_t)); + species->SkinLeg = (skinName_t *)realloc(species->SkinLeg, species->SkinLegMax * sizeof(skinName_t)); } Q_strncpyz(species->SkinLeg[species->SkinLegCount++].name, skinname, SKIN_LENGTH); - iSkinParts |= 1<<2; + iSkinParts |= 1 << 2; } } } - if (iSkinParts != 7) - { //didn't get a skin for each, then skip this model. + if (iSkinParts != 7) { // didn't get a skin for each, then skip this model. UI_FreeSpecies(species); continue; } uiInfo.playerSpeciesCount++; - if (!inGameLoad && ui_PrecacheModels.integer) - { + if (!inGameLoad && ui_PrecacheModels.integer) { int g2Model; void *ghoul2 = 0; - Com_sprintf( fpath, sizeof( fpath ), "models/players/%s/model.glm", dirptr ); + Com_sprintf(fpath, sizeof(fpath), "models/players/%s/model.glm", dirptr); g2Model = trap->G2API_InitGhoul2Model(&ghoul2, fpath, 0, 0, 0, 0, 0); - if (g2Model >= 0) - { -// trap->G2API_RemoveGhoul2Model( &ghoul2, 0 ); - trap->G2API_CleanGhoul2Models (&ghoul2); + if (g2Model >= 0) { + // trap->G2API_RemoveGhoul2Model( &ghoul2, 0 ); + trap->G2API_CleanGhoul2Models(&ghoul2); } } } } - if ( dirlist != stackDirList ) - { + if (dirlist != stackDirList) { free(dirlist); } } -static qhandle_t UI_RegisterShaderNoMip( const char *name ) { - if ( *name == '*' ) { +static qhandle_t UI_RegisterShaderNoMip(const char *name) { + if (*name == '*') { char buf[MAX_CVAR_VALUE_STRING]; - trap->Cvar_VariableStringBuffer( name+1, buf, sizeof( buf ) ); + trap->Cvar_VariableStringBuffer(name + 1, buf, sizeof(buf)); - if ( buf[0] ) - return trap->R_RegisterShaderNoMip( buf ); + if (buf[0]) + return trap->R_RegisterShaderNoMip(buf); } - return trap->R_RegisterShaderNoMip( name ); + return trap->R_RegisterShaderNoMip(name); } /* @@ -9835,18 +8710,18 @@ static qhandle_t UI_RegisterShaderNoMip( const char *name ) { UI_Init ================= */ -void UI_Init( qboolean inGameLoad ) { +void UI_Init(qboolean inGameLoad) { const char *menuSet; - Rand_Init( trap->Milliseconds() ); + Rand_Init(trap->Milliseconds()); // Get the list of possible languages - uiInfo.languageCount = trap->SE_GetNumLanguages(); // this does a dir scan, so use carefully + uiInfo.languageCount = trap->SE_GetNumLanguages(); // this does a dir scan, so use carefully uiInfo.inGameLoad = inGameLoad; - //initialize all these cvars to "0" - UI_SiegeSetCvarsForClass( NULL ); + // initialize all these cvars to "0" + UI_SiegeSetCvarsForClass(NULL); UI_SiegeInit(); @@ -9856,80 +8731,79 @@ void UI_Init( qboolean inGameLoad ) { UI_InitMemory(); // cache redundant calulations - trap->GetGlconfig( &uiInfo.uiDC.glconfig ); + trap->GetGlconfig(&uiInfo.uiDC.glconfig); // for 640x480 virtualized screen - uiInfo.uiDC.yscale = uiInfo.uiDC.glconfig.vidHeight * (1.0/480.0); - uiInfo.uiDC.xscale = uiInfo.uiDC.glconfig.vidWidth * (1.0/640.0); - if ( uiInfo.uiDC.glconfig.vidWidth * 480 > uiInfo.uiDC.glconfig.vidHeight * 640 ) { + uiInfo.uiDC.yscale = uiInfo.uiDC.glconfig.vidHeight * (1.0 / 480.0); + uiInfo.uiDC.xscale = uiInfo.uiDC.glconfig.vidWidth * (1.0 / 640.0); + if (uiInfo.uiDC.glconfig.vidWidth * 480 > uiInfo.uiDC.glconfig.vidHeight * 640) { // wide screen - uiInfo.uiDC.bias = 0.5 * ( uiInfo.uiDC.glconfig.vidWidth - ( uiInfo.uiDC.glconfig.vidHeight * (640.0/480.0) ) ); - } - else { + uiInfo.uiDC.bias = 0.5 * (uiInfo.uiDC.glconfig.vidWidth - (uiInfo.uiDC.glconfig.vidHeight * (640.0 / 480.0))); + } else { // no wide screen uiInfo.uiDC.bias = 0; } - //UI_Load(); - uiInfo.uiDC.registerShaderNoMip = UI_RegisterShaderNoMip; - uiInfo.uiDC.setColor = &UI_SetColor; - uiInfo.uiDC.drawHandlePic = &UI_DrawHandlePic; - uiInfo.uiDC.drawStretchPic = trap->R_DrawStretchPic; - uiInfo.uiDC.drawText = &Text_Paint; - uiInfo.uiDC.textWidth = &Text_Width; - uiInfo.uiDC.textHeight = &Text_Height; - uiInfo.uiDC.registerModel = trap->R_RegisterModel; - uiInfo.uiDC.modelBounds = trap->R_ModelBounds; - uiInfo.uiDC.fillRect = &UI_FillRect; - uiInfo.uiDC.drawRect = &_UI_DrawRect; - uiInfo.uiDC.drawSides = &_UI_DrawSides; - uiInfo.uiDC.drawTopBottom = &_UI_DrawTopBottom; - uiInfo.uiDC.clearScene = trap->R_ClearScene; - uiInfo.uiDC.drawSides = &_UI_DrawSides; - uiInfo.uiDC.addRefEntityToScene = trap->R_AddRefEntityToScene; - uiInfo.uiDC.renderScene = trap->R_RenderScene; - uiInfo.uiDC.RegisterFont = trap->R_RegisterFont; - uiInfo.uiDC.Font_StrLenPixels = trap->R_Font_StrLenPixels; - uiInfo.uiDC.Font_StrLenChars = trap->R_Font_StrLenChars; - uiInfo.uiDC.Font_HeightPixels = trap->R_Font_HeightPixels; - uiInfo.uiDC.Font_DrawString = trap->R_Font_DrawString; - uiInfo.uiDC.Language_IsAsian = trap->R_Language_IsAsian; - uiInfo.uiDC.Language_UsesSpaces = trap->R_Language_UsesSpaces; - uiInfo.uiDC.AnyLanguage_ReadCharFromString = trap->R_AnyLanguage_ReadCharFromString; - uiInfo.uiDC.ownerDrawItem = &UI_OwnerDraw; - uiInfo.uiDC.getValue = &UI_GetValue; - uiInfo.uiDC.ownerDrawVisible = &UI_OwnerDrawVisible; - uiInfo.uiDC.runScript = &UI_RunMenuScript; - uiInfo.uiDC.deferScript = &UI_DeferMenuScript; - uiInfo.uiDC.getTeamColor = &UI_GetTeamColor; - uiInfo.uiDC.setCVar = trap->Cvar_Set; - uiInfo.uiDC.getCVarString = trap->Cvar_VariableStringBuffer; - uiInfo.uiDC.getCVarValue = trap->Cvar_VariableValue; - uiInfo.uiDC.drawTextWithCursor = &Text_PaintWithCursor; - uiInfo.uiDC.setOverstrikeMode = trap->Key_SetOverstrikeMode; - uiInfo.uiDC.getOverstrikeMode = trap->Key_GetOverstrikeMode; - uiInfo.uiDC.startLocalSound = trap->S_StartLocalSound; - uiInfo.uiDC.ownerDrawHandleKey = &UI_OwnerDrawHandleKey; - uiInfo.uiDC.feederCount = &UI_FeederCount; - uiInfo.uiDC.feederItemImage = &UI_FeederItemImage; - uiInfo.uiDC.feederItemText = &UI_FeederItemText; - uiInfo.uiDC.feederSelection = &UI_FeederSelection; - uiInfo.uiDC.setBinding = trap->Key_SetBinding; - uiInfo.uiDC.getBindingBuf = trap->Key_GetBindingBuf; - uiInfo.uiDC.keynumToStringBuf = trap->Key_KeynumToStringBuf; - uiInfo.uiDC.executeText = trap->Cmd_ExecuteText; - uiInfo.uiDC.Error = Com_Error; - uiInfo.uiDC.Print = Com_Printf; - uiInfo.uiDC.Pause = &UI_Pause; - uiInfo.uiDC.ownerDrawWidth = &UI_OwnerDrawWidth; - uiInfo.uiDC.registerSound = trap->S_RegisterSound; - uiInfo.uiDC.startBackgroundTrack = trap->S_StartBackgroundTrack; - uiInfo.uiDC.stopBackgroundTrack = trap->S_StopBackgroundTrack; - uiInfo.uiDC.playCinematic = &UI_PlayCinematic; - uiInfo.uiDC.stopCinematic = &UI_StopCinematic; - uiInfo.uiDC.drawCinematic = &UI_DrawCinematic; - uiInfo.uiDC.runCinematicFrame = &UI_RunCinematicFrame; - uiInfo.uiDC.ext.Font_StrLenPixels = trap->ext.R_Font_StrLenPixels; + // UI_Load(); + uiInfo.uiDC.registerShaderNoMip = UI_RegisterShaderNoMip; + uiInfo.uiDC.setColor = &UI_SetColor; + uiInfo.uiDC.drawHandlePic = &UI_DrawHandlePic; + uiInfo.uiDC.drawStretchPic = trap->R_DrawStretchPic; + uiInfo.uiDC.drawText = &Text_Paint; + uiInfo.uiDC.textWidth = &Text_Width; + uiInfo.uiDC.textHeight = &Text_Height; + uiInfo.uiDC.registerModel = trap->R_RegisterModel; + uiInfo.uiDC.modelBounds = trap->R_ModelBounds; + uiInfo.uiDC.fillRect = &UI_FillRect; + uiInfo.uiDC.drawRect = &_UI_DrawRect; + uiInfo.uiDC.drawSides = &_UI_DrawSides; + uiInfo.uiDC.drawTopBottom = &_UI_DrawTopBottom; + uiInfo.uiDC.clearScene = trap->R_ClearScene; + uiInfo.uiDC.drawSides = &_UI_DrawSides; + uiInfo.uiDC.addRefEntityToScene = trap->R_AddRefEntityToScene; + uiInfo.uiDC.renderScene = trap->R_RenderScene; + uiInfo.uiDC.RegisterFont = trap->R_RegisterFont; + uiInfo.uiDC.Font_StrLenPixels = trap->R_Font_StrLenPixels; + uiInfo.uiDC.Font_StrLenChars = trap->R_Font_StrLenChars; + uiInfo.uiDC.Font_HeightPixels = trap->R_Font_HeightPixels; + uiInfo.uiDC.Font_DrawString = trap->R_Font_DrawString; + uiInfo.uiDC.Language_IsAsian = trap->R_Language_IsAsian; + uiInfo.uiDC.Language_UsesSpaces = trap->R_Language_UsesSpaces; + uiInfo.uiDC.AnyLanguage_ReadCharFromString = trap->R_AnyLanguage_ReadCharFromString; + uiInfo.uiDC.ownerDrawItem = &UI_OwnerDraw; + uiInfo.uiDC.getValue = &UI_GetValue; + uiInfo.uiDC.ownerDrawVisible = &UI_OwnerDrawVisible; + uiInfo.uiDC.runScript = &UI_RunMenuScript; + uiInfo.uiDC.deferScript = &UI_DeferMenuScript; + uiInfo.uiDC.getTeamColor = &UI_GetTeamColor; + uiInfo.uiDC.setCVar = trap->Cvar_Set; + uiInfo.uiDC.getCVarString = trap->Cvar_VariableStringBuffer; + uiInfo.uiDC.getCVarValue = trap->Cvar_VariableValue; + uiInfo.uiDC.drawTextWithCursor = &Text_PaintWithCursor; + uiInfo.uiDC.setOverstrikeMode = trap->Key_SetOverstrikeMode; + uiInfo.uiDC.getOverstrikeMode = trap->Key_GetOverstrikeMode; + uiInfo.uiDC.startLocalSound = trap->S_StartLocalSound; + uiInfo.uiDC.ownerDrawHandleKey = &UI_OwnerDrawHandleKey; + uiInfo.uiDC.feederCount = &UI_FeederCount; + uiInfo.uiDC.feederItemImage = &UI_FeederItemImage; + uiInfo.uiDC.feederItemText = &UI_FeederItemText; + uiInfo.uiDC.feederSelection = &UI_FeederSelection; + uiInfo.uiDC.setBinding = trap->Key_SetBinding; + uiInfo.uiDC.getBindingBuf = trap->Key_GetBindingBuf; + uiInfo.uiDC.keynumToStringBuf = trap->Key_KeynumToStringBuf; + uiInfo.uiDC.executeText = trap->Cmd_ExecuteText; + uiInfo.uiDC.Error = Com_Error; + uiInfo.uiDC.Print = Com_Printf; + uiInfo.uiDC.Pause = &UI_Pause; + uiInfo.uiDC.ownerDrawWidth = &UI_OwnerDrawWidth; + uiInfo.uiDC.registerSound = trap->S_RegisterSound; + uiInfo.uiDC.startBackgroundTrack = trap->S_StartBackgroundTrack; + uiInfo.uiDC.stopBackgroundTrack = trap->S_StopBackgroundTrack; + uiInfo.uiDC.playCinematic = &UI_PlayCinematic; + uiInfo.uiDC.stopCinematic = &UI_StopCinematic; + uiInfo.uiDC.drawCinematic = &UI_DrawCinematic; + uiInfo.uiDC.runCinematicFrame = &UI_RunCinematicFrame; + uiInfo.uiDC.ext.Font_StrLenPixels = trap->ext.R_Font_StrLenPixels; Init_Display(&uiInfo.uiDC); @@ -9937,8 +8811,8 @@ void UI_Init( qboolean inGameLoad ) { String_Init(); - uiInfo.uiDC.cursor = trap->R_RegisterShaderNoMip( "menu/art/3_cursor2" ); - uiInfo.uiDC.whiteShader = trap->R_RegisterShaderNoMip( "white" ); + uiInfo.uiDC.cursor = trap->R_RegisterShaderNoMip("menu/art/3_cursor2"); + uiInfo.uiDC.whiteShader = trap->R_RegisterShaderNoMip("white"); AssetCache(); @@ -9954,23 +8828,20 @@ void UI_Init( qboolean inGameLoad ) { } #if 1 - if (inGameLoad) - { + if (inGameLoad) { UI_LoadMenus("ui/jampingame.txt", qtrue); - } - else if (!ui_bypassMainMenuLoad.integer) - { + } else if (!ui_bypassMainMenuLoad.integer) { UI_LoadMenus(menuSet, qtrue); } -#else //this was adding quite a giant amount of time to the load time +#else // this was adding quite a giant amount of time to the load time UI_LoadMenus(menuSet, qtrue); UI_LoadMenus("ui/jampingame.txt", qtrue); #endif { char buf[MAX_NETNAME] = {0}; - Q_strncpyz( buf, UI_Cvar_VariableString( "name" ), sizeof( buf ) ); - trap->Cvar_Register( NULL, "ui_Name", buf, CVAR_INTERNAL ); + Q_strncpyz(buf, UI_Cvar_VariableString("name"), sizeof(buf)); + trap->Cvar_Register(NULL, "ui_Name", buf, CVAR_INTERNAL); } Menus_CloseAll(); @@ -9992,39 +8863,38 @@ void UI_Init( qboolean inGameLoad ) { uiInfo.serverStatus.currentServerCinematic = -1; uiInfo.previewMovie = -1; - trap->Cvar_Register(NULL, "debug_protocol", "", 0 ); + trap->Cvar_Register(NULL, "debug_protocol", "", 0); trap->Cvar_Set("ui_actualNetGameType", va("%d", ui_netGametype.integer)); trap->Cvar_Update(&ui_actualNetGametype); } -#define UI_FPS_FRAMES 4 -void UI_Refresh( int realtime ) -{ +#define UI_FPS_FRAMES 4 +void UI_Refresh(int realtime) { static int index; - static int previousTimes[UI_FPS_FRAMES]; + static int previousTimes[UI_FPS_FRAMES]; - //if ( !( trap->Key_GetCatcher() & KEYCATCH_UI ) ) { + // if ( !( trap->Key_GetCatcher() & KEYCATCH_UI ) ) { // return; - //} + // } trap->G2API_SetTime(realtime, 0); trap->G2API_SetTime(realtime, 1); - //ghoul2 timer must be explicitly updated during ui rendering. + // ghoul2 timer must be explicitly updated during ui rendering. uiInfo.uiDC.frameTime = realtime - uiInfo.uiDC.realTime; uiInfo.uiDC.realTime = realtime; previousTimes[index % UI_FPS_FRAMES] = uiInfo.uiDC.frameTime; index++; - if ( index > UI_FPS_FRAMES ) { + if (index > UI_FPS_FRAMES) { int i, total; // average multiple frames together to smooth changes out a bit total = 0; - for ( i = 0 ; i < UI_FPS_FRAMES ; i++ ) { + for (i = 0; i < UI_FPS_FRAMES; i++) { total += previousTimes[i]; } - if ( !total ) { + if (!total) { total = 1; } uiInfo.uiDC.FPS = 1000 * UI_FPS_FRAMES / total; @@ -10043,33 +8913,29 @@ void UI_Refresh( int realtime ) UI_BuildFindPlayerList(qfalse); } // draw cursor - UI_SetColor( NULL ); + UI_SetColor(NULL); if (Menu_Count() > 0 && (trap->Key_GetCatcher() & KEYCATCH_UI)) { - UI_DrawHandlePic( (float)uiInfo.uiDC.cursorx, (float)uiInfo.uiDC.cursory, 40.0f, 40.0f, uiInfo.uiDC.Assets.cursor); - //UI_DrawHandlePic( uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory, 48, 48, uiInfo.uiDC.Assets.cursor); + UI_DrawHandlePic((float)uiInfo.uiDC.cursorx, (float)uiInfo.uiDC.cursory, 40.0f, 40.0f, uiInfo.uiDC.Assets.cursor); + // UI_DrawHandlePic( uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory, 48, 48, uiInfo.uiDC.Assets.cursor); } - if (ui_rankChange.integer) - { + if (ui_rankChange.integer) { FPMessageTime = realtime + 3000; - if (!parsedFPMessage[0] /*&& uiMaxRank > ui_rankChange.integer*/) - { + if (!parsedFPMessage[0] /*&& uiMaxRank > ui_rankChange.integer*/) { const char *printMessage = UI_GetStringEdString("MP_INGAME", "SET_NEW_RANK"); int i = 0; int p = 0; int linecount = 0; - while (printMessage[i] && p < 1024) - { + while (printMessage[i] && p < 1024) { parsedFPMessage[p] = printMessage[i]; p++; i++; linecount++; - if (linecount > 64 && printMessage[i] == ' ') - { + if (linecount > 64 && printMessage[i] == ' ') { parsedFPMessage[p] = '\n'; p++; linecount = 0; @@ -10078,7 +8944,7 @@ void UI_Refresh( int realtime ) parsedFPMessage[p] = '\0'; } - //if (uiMaxRank > ui_rankChange.integer) + // if (uiMaxRank > ui_rankChange.integer) { uiMaxRank = ui_rankChange.integer; uiForceRank = uiMaxRank; @@ -10094,31 +8960,26 @@ void UI_Refresh( int realtime ) uiForceUsed = 0; */ - //Use BG_LegalizedForcePowers and transfer the result into the UI force settings + // Use BG_LegalizedForcePowers and transfer the result into the UI force settings UI_ReadLegalForce(); } - if (ui_freeSaber.integer && uiForcePowersRank[FP_SABER_OFFENSE] < 1) - { + if (ui_freeSaber.integer && uiForcePowersRank[FP_SABER_OFFENSE] < 1) { uiForcePowersRank[FP_SABER_OFFENSE] = 1; } - if (ui_freeSaber.integer && uiForcePowersRank[FP_SABER_DEFENSE] < 1) - { + if (ui_freeSaber.integer && uiForcePowersRank[FP_SABER_DEFENSE] < 1) { uiForcePowersRank[FP_SABER_DEFENSE] = 1; } trap->Cvar_Set("ui_rankChange", "0"); - //remember to update the force power count after changing the max rank + // remember to update the force power count after changing the max rank UpdateForceUsed(); } - if (ui_freeSaber.integer) - { + if (ui_freeSaber.integer) { bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 0; bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 0; - } - else - { + } else { bgForcePowerCost[FP_SABER_OFFENSE][FORCE_LEVEL_1] = 1; bgForcePowerCost[FP_SABER_DEFENSE][FORCE_LEVEL_1] = 1; } @@ -10149,7 +9010,7 @@ void UI_Refresh( int realtime ) Text_Paint(10, 0, 1, txtCol, parsedFPMessage, 0, 1024, txtStyle, FONT_MEDIUM); } */ - //For now, don't bother. + // For now, don't bother. } /* @@ -10157,25 +9018,25 @@ void UI_Refresh( int realtime ) UI_KeyEvent ================= */ -void UI_KeyEvent( int key, qboolean down ) { +void UI_KeyEvent(int key, qboolean down) { if (Menu_Count() > 0) { menuDef_t *menu = Menu_GetFocused(); if (menu) { if (key == A_ESCAPE && down && !Menus_AnyFullScreenVisible()) { Menus_CloseAll(); } else { - Menu_HandleKey(menu, key, down ); + Menu_HandleKey(menu, key, down); } } else { - trap->Key_SetCatcher( trap->Key_GetCatcher() & ~KEYCATCH_UI ); + trap->Key_SetCatcher(trap->Key_GetCatcher() & ~KEYCATCH_UI); trap->Key_ClearStates(); - trap->Cvar_Set( "cl_paused", "0" ); + trap->Cvar_Set("cl_paused", "0"); } } - //if ((s > 0) && (s != menu_null_sound)) { - // trap->S_StartLocalSound( s, CHAN_LOCAL_SOUND ); - //} + // if ((s > 0) && (s != menu_null_sound)) { + // trap->S_StartLocalSound( s, CHAN_LOCAL_SOUND ); + //} } /* @@ -10183,8 +9044,7 @@ void UI_KeyEvent( int key, qboolean down ) { UI_MouseEvent ================= */ -void UI_MouseEvent( int dx, int dy ) -{ +void UI_MouseEvent(int dx, int dy) { // update mouse screen position uiInfo.uiDC.cursorx += dx; if (uiInfo.uiDC.cursorx < 0) @@ -10199,39 +9059,36 @@ void UI_MouseEvent( int dx, int dy ) uiInfo.uiDC.cursory = SCREEN_HEIGHT; if (Menu_Count() > 0) { - //menuDef_t *menu = Menu_GetFocused(); - //Menu_HandleMouseMove(menu, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); + // menuDef_t *menu = Menu_GetFocused(); + // Menu_HandleMouseMove(menu, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); Display_MouseMove(NULL, uiInfo.uiDC.cursorx, uiInfo.uiDC.cursory); } } -static void UI_ReadableSize ( char *buf, int bufsize, int value ) -{ - if (value > 1024*1024*1024 ) { // gigs - Com_sprintf( buf, bufsize, "%d", value / (1024*1024*1024) ); - Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d GB", - (value % (1024*1024*1024))*100 / (1024*1024*1024) ); - } else if (value > 1024*1024 ) { // megs - Com_sprintf( buf, bufsize, "%d", value / (1024*1024) ); - Com_sprintf( buf+strlen(buf), bufsize-strlen(buf), ".%02d MB", - (value % (1024*1024))*100 / (1024*1024) ); - } else if (value > 1024 ) { // kilos - Com_sprintf( buf, bufsize, "%d KB", value / 1024 ); +static void UI_ReadableSize(char *buf, int bufsize, int value) { + if (value > 1024 * 1024 * 1024) { // gigs + Com_sprintf(buf, bufsize, "%d", value / (1024 * 1024 * 1024)); + Com_sprintf(buf + strlen(buf), bufsize - strlen(buf), ".%02d GB", (value % (1024 * 1024 * 1024)) * 100 / (1024 * 1024 * 1024)); + } else if (value > 1024 * 1024) { // megs + Com_sprintf(buf, bufsize, "%d", value / (1024 * 1024)); + Com_sprintf(buf + strlen(buf), bufsize - strlen(buf), ".%02d MB", (value % (1024 * 1024)) * 100 / (1024 * 1024)); + } else if (value > 1024) { // kilos + Com_sprintf(buf, bufsize, "%d KB", value / 1024); } else { // bytes - Com_sprintf( buf, bufsize, "%d bytes", value ); + Com_sprintf(buf, bufsize, "%d bytes", value); } } // Assumes time is in msec -static void UI_PrintTime ( char *buf, int bufsize, int time ) { - time /= 1000; // change to seconds +static void UI_PrintTime(char *buf, int bufsize, int time) { + time /= 1000; // change to seconds if (time > 3600) { // in the hours range - Com_sprintf( buf, bufsize, "%d hr %2d min", time / 3600, (time % 3600) / 60 ); + Com_sprintf(buf, bufsize, "%d hr %2d min", time / 3600, (time % 3600) / 60); } else if (time > 60) { // mins - Com_sprintf( buf, bufsize, "%2d min %2d sec", time / 60, time % 60 ); + Com_sprintf(buf, bufsize, "%2d min %2d sec", time / 60, time % 60); } else { // secs - Com_sprintf( buf, bufsize, "%2d sec", time ); + Com_sprintf(buf, bufsize, "%2d sec", time); } } @@ -10240,7 +9097,7 @@ void Text_PaintCenter(float x, float y, float scale, vec4_t color, const char *t Text_Paint(x - len / 2, y, scale, color, text, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, iMenuFont); } -static void UI_DisplayDownloadInfo( const char *downloadName, float centerPoint, float yStart, float scale, int iMenuFont) { +static void UI_DisplayDownloadInfo(const char *downloadName, float centerPoint, float yStart, float scale, int iMenuFont) { char sDownLoading[256]; char sEstimatedTimeLeft[256]; char sTransferRate[256]; @@ -10256,24 +9113,24 @@ static void UI_DisplayDownloadInfo( const char *downloadName, float centerPoint, vec4_t colorLtGreyAlpha = {0, 0, 0, .5}; - UI_FillRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, colorLtGreyAlpha ); - - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 0); // "Downloading:" - Q_strncpyz(sDownLoading,s?s:"", sizeof(sDownLoading)); - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 1); // "Estimated time left:" - Q_strncpyz(sEstimatedTimeLeft,s?s:"", sizeof(sEstimatedTimeLeft)); - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 2); // "Transfer rate:" - Q_strncpyz(sTransferRate,s?s:"", sizeof(sTransferRate)); - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 3); // "of" - Q_strncpyz(sOf,s?s:"", sizeof(sOf)); - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 4); // "copied" - Q_strncpyz(sCopied,s?s:"", sizeof(sCopied)); - s = GetCRDelineatedString("MENUS","DOWNLOAD_STUFF", 5); // "sec." - Q_strncpyz(sSec,s?s:"", sizeof(sSec)); - - downloadSize = trap->Cvar_VariableValue( "cl_downloadSize" ); - downloadCount = trap->Cvar_VariableValue( "cl_downloadCount" ); - downloadTime = trap->Cvar_VariableValue( "cl_downloadTime" ); + UI_FillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, colorLtGreyAlpha); + + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 0); // "Downloading:" + Q_strncpyz(sDownLoading, s ? s : "", sizeof(sDownLoading)); + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 1); // "Estimated time left:" + Q_strncpyz(sEstimatedTimeLeft, s ? s : "", sizeof(sEstimatedTimeLeft)); + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 2); // "Transfer rate:" + Q_strncpyz(sTransferRate, s ? s : "", sizeof(sTransferRate)); + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 3); // "of" + Q_strncpyz(sOf, s ? s : "", sizeof(sOf)); + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 4); // "copied" + Q_strncpyz(sCopied, s ? s : "", sizeof(sCopied)); + s = GetCRDelineatedString("MENUS", "DOWNLOAD_STUFF", 5); // "sec." + Q_strncpyz(sSec, s ? s : "", sizeof(sSec)); + + downloadSize = trap->Cvar_VariableValue("cl_downloadSize"); + downloadCount = trap->Cvar_VariableValue("cl_downloadCount"); + downloadTime = trap->Cvar_VariableValue("cl_downloadTime"); leftWidth = 320; @@ -10284,48 +9141,47 @@ static void UI_DisplayDownloadInfo( const char *downloadName, float centerPoint, Text_PaintCenter(centerPoint, yStart + 248, scale, colorWhite, sTransferRate, 0, iMenuFont); if (downloadSize > 0) { - s = va( "%s (%d%%)", downloadName, (int)( (float)downloadCount * 100.0f / downloadSize ) ); + s = va("%s (%d%%)", downloadName, (int)((float)downloadCount * 100.0f / downloadSize)); } else { s = downloadName; } - Text_PaintCenter(centerPoint, yStart+136, scale, colorWhite, s, 0, iMenuFont); + Text_PaintCenter(centerPoint, yStart + 136, scale, colorWhite, s, 0, iMenuFont); - UI_ReadableSize( dlSizeBuf, sizeof dlSizeBuf, downloadCount ); - UI_ReadableSize( totalSizeBuf, sizeof totalSizeBuf, downloadSize ); + UI_ReadableSize(dlSizeBuf, sizeof dlSizeBuf, downloadCount); + UI_ReadableSize(totalSizeBuf, sizeof totalSizeBuf, downloadSize); if (downloadCount < 4096 || !downloadTime) { - Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, "estimating", 0, iMenuFont); - Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 216, scale, colorWhite, "estimating", 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); } else { if ((uiInfo.uiDC.realTime - downloadTime) / 1000) { xferRate = downloadCount / ((uiInfo.uiDC.realTime - downloadTime) / 1000); } else { xferRate = 0; } - UI_ReadableSize( xferRateBuf, sizeof xferRateBuf, xferRate ); + UI_ReadableSize(xferRateBuf, sizeof xferRateBuf, xferRate); // Extrapolate estimated completion time if (downloadSize && xferRate) { int n = downloadSize / xferRate; // estimated time for entire d/l in secs // We do it in K (/1024) because we'd overflow around 4MB - UI_PrintTime ( dlTimeBuf, sizeof dlTimeBuf, - (n - (((downloadCount/1024) * n) / (downloadSize/1024))) * 1000); + UI_PrintTime(dlTimeBuf, sizeof dlTimeBuf, (n - (((downloadCount / 1024) * n) / (downloadSize / 1024))) * 1000); - Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, dlTimeBuf, 0, iMenuFont); - Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 216, scale, colorWhite, dlTimeBuf, 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); } else { - Text_PaintCenter(leftWidth, yStart+216, scale, colorWhite, "estimating", 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 216, scale, colorWhite, "estimating", 0, iMenuFont); if (downloadSize) { - Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 160, scale, colorWhite, va("(%s %s %s %s)", dlSizeBuf, sOf, totalSizeBuf, sCopied), 0, iMenuFont); } else { - Text_PaintCenter(leftWidth, yStart+160, scale, colorWhite, va("(%s %s)", dlSizeBuf, sCopied), 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 160, scale, colorWhite, va("(%s %s)", dlSizeBuf, sCopied), 0, iMenuFont); } } if (xferRate) { - Text_PaintCenter(leftWidth, yStart+272, scale, colorWhite, va("%s/%s", xferRateBuf,sSec), 0, iMenuFont); + Text_PaintCenter(leftWidth, yStart + 272, scale, colorWhite, va("%s/%s", xferRateBuf, sSec), 0, iMenuFont); } } } @@ -10338,10 +9194,10 @@ This will also be overlaid on the cgame info screen during loading to prevent it from blinking away too rapidly on local or lan games. ======================== */ -void UI_DrawConnectScreen( qboolean overlay ) { +void UI_DrawConnectScreen(qboolean overlay) { const char *s; - uiClientState_t cstate; - char info[MAX_INFO_VALUE]; + uiClientState_t cstate; + char info[MAX_INFO_VALUE]; char text[256]; float centerPoint, yStart, scale; @@ -10349,72 +9205,66 @@ void UI_DrawConnectScreen( qboolean overlay ) { menuDef_t *menu = Menus_FindByName("Connect"); - - if ( !overlay && menu ) { + if (!overlay && menu) { Menu_Paint(menu, qtrue); } if (!overlay) { centerPoint = 320; yStart = 130; - scale = 1.0f; // -ste + scale = 1.0f; // -ste } else { centerPoint = 320; yStart = 32; - scale = 1.0f; // -ste + scale = 1.0f; // -ste return; } // see what information we should display - trap->GetClientState( &cstate ); - + trap->GetClientState(&cstate); info[0] = '\0'; - if( trap->GetConfigString( CS_SERVERINFO, info, sizeof(info) ) ) { + if (trap->GetConfigString(CS_SERVERINFO, info, sizeof(info))) { trap->SE_GetStringTextString("MENUS_LOADING_MAPNAME", sStringEdTemp, sizeof(sStringEdTemp)); - Text_PaintCenter(centerPoint, yStart, scale, colorWhite, va( /*"Loading %s"*/sStringEdTemp, Info_ValueForKey( info, "mapname" )), 0, FONT_MEDIUM); + Text_PaintCenter(centerPoint, yStart, scale, colorWhite, va(/*"Loading %s"*/ sStringEdTemp, Info_ValueForKey(info, "mapname")), 0, FONT_MEDIUM); } - if (!Q_stricmp(cstate.servername,"localhost")) { + if (!Q_stricmp(cstate.servername, "localhost")) { trap->SE_GetStringTextString("MENUS_STARTING_UP", sStringEdTemp, sizeof(sStringEdTemp)); Text_PaintCenter(centerPoint, yStart + 48, scale, colorWhite, sStringEdTemp, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); } else { trap->SE_GetStringTextString("MENUS_CONNECTING_TO", sStringEdTemp, sizeof(sStringEdTemp)); - Q_strncpyz(text, va(/*"Connecting to %s"*/sStringEdTemp, cstate.servername), sizeof(text)); - Text_PaintCenter(centerPoint, yStart + 48, scale, colorWhite,text , ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); + Q_strncpyz(text, va(/*"Connecting to %s"*/ sStringEdTemp, cstate.servername), sizeof(text)); + Text_PaintCenter(centerPoint, yStart + 48, scale, colorWhite, text, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM); } // display global MOTD at bottom - Text_PaintCenter(centerPoint, 425, scale, colorWhite, Info_ValueForKey( cstate.updateInfoString, "motd" ), 0, FONT_MEDIUM); + Text_PaintCenter(centerPoint, 425, scale, colorWhite, Info_ValueForKey(cstate.updateInfoString, "motd"), 0, FONT_MEDIUM); // print any server info (server full, bad version, etc) - if ( cstate.connState < CA_CONNECTED ) { + if (cstate.connState < CA_CONNECTED) { Text_PaintCenter(centerPoint, yStart + 176, scale, colorWhite, cstate.messageString, 0, FONT_MEDIUM); } - switch ( cstate.connState ) { - case CA_CONNECTING: - { - trap->SE_GetStringTextString("MENUS_AWAITING_CONNECTION", sStringEdTemp, sizeof(sStringEdTemp)); - s = va(/*"Awaiting connection...%i"*/sStringEdTemp, cstate.connectPacketCount); - } - break; - case CA_CHALLENGING: - { - trap->SE_GetStringTextString("MENUS_AWAITING_CHALLENGE", sStringEdTemp, sizeof(sStringEdTemp)); - s = va(/*"Awaiting challenge...%i"*/sStringEdTemp, cstate.connectPacketCount); - } - break; + switch (cstate.connState) { + case CA_CONNECTING: { + trap->SE_GetStringTextString("MENUS_AWAITING_CONNECTION", sStringEdTemp, sizeof(sStringEdTemp)); + s = va(/*"Awaiting connection...%i"*/ sStringEdTemp, cstate.connectPacketCount); + } break; + case CA_CHALLENGING: { + trap->SE_GetStringTextString("MENUS_AWAITING_CHALLENGE", sStringEdTemp, sizeof(sStringEdTemp)); + s = va(/*"Awaiting challenge...%i"*/ sStringEdTemp, cstate.connectPacketCount); + } break; case CA_CONNECTED: { char downloadName[MAX_INFO_VALUE]; - trap->Cvar_VariableStringBuffer( "cl_downloadName", downloadName, sizeof(downloadName) ); - if (*downloadName) { - UI_DisplayDownloadInfo( downloadName, centerPoint, yStart, scale, FONT_MEDIUM ); - return; - } + trap->Cvar_VariableStringBuffer("cl_downloadName", downloadName, sizeof(downloadName)); + if (*downloadName) { + UI_DisplayDownloadInfo(downloadName, centerPoint, yStart, scale, FONT_MEDIUM); + return; } + } trap->SE_GetStringTextString("MENUS_AWAITING_GAMESTATE", sStringEdTemp, sizeof(sStringEdTemp)); - s = /*"Awaiting gamestate..."*/sStringEdTemp; + s = /*"Awaiting gamestate..."*/ sStringEdTemp; break; case CA_LOADING: return; @@ -10424,7 +9274,7 @@ void UI_DrawConnectScreen( qboolean overlay ) { return; } - if (Q_stricmp(cstate.servername,"localhost")) { + if (Q_stricmp(cstate.servername, "localhost")) { Text_PaintCenter(centerPoint, yStart + 80, scale, colorWhite, s, 0, FONT_MEDIUM); } // password required / connection rejected information goes here @@ -10435,8 +9285,7 @@ void UI_DrawConnectScreen( qboolean overlay ) { ArenaServers_StopRefresh ================= */ -static void UI_StopServerRefresh( void ) -{ +static void UI_StopServerRefresh(void) { int count; if (!uiInfo.serverStatus.refreshActive) { @@ -10444,14 +9293,11 @@ static void UI_StopServerRefresh( void ) return; } uiInfo.serverStatus.refreshActive = qfalse; - Com_Printf("%d servers listed in browser with %d players.\n", - uiInfo.serverStatus.numDisplayServers, - uiInfo.serverStatus.numPlayersOnServers); + Com_Printf("%d servers listed in browser with %d players.\n", uiInfo.serverStatus.numDisplayServers, uiInfo.serverStatus.numPlayersOnServers); count = trap->LAN_GetServerCount(UI_SourceForLAN()); if (count - uiInfo.serverStatus.numDisplayServers > 0) { - Com_Printf("%d servers not listed due to filters, packet loss, invalid info, or pings higher than %d\n", - count - uiInfo.serverStatus.numDisplayServers, - (int) trap->Cvar_VariableValue("cl_maxPing")); + Com_Printf("%d servers not listed due to filters, packet loss, invalid info, or pings higher than %d\n", count - uiInfo.serverStatus.numDisplayServers, + (int)trap->Cvar_VariableValue("cl_maxPing")); } } @@ -10460,8 +9306,7 @@ static void UI_StopServerRefresh( void ) UI_DoServerRefresh ================= */ -static void UI_DoServerRefresh( void ) -{ +static void UI_DoServerRefresh(void) { qboolean wait = qfalse; if (!uiInfo.serverStatus.refreshActive) { @@ -10503,14 +9348,14 @@ static void UI_DoServerRefresh( void ) UI_StartServerRefresh ================= */ -static void UI_StartServerRefresh(qboolean full) -{ - char *ptr; - int lanSource; +static void UI_StartServerRefresh(qboolean full) { + char *ptr; + int lanSource; qtime_t q; trap->RealTime(&q); - trap->Cvar_Set( va("ui_lastServerRefresh_%i", ui_netSource.integer), va("%s-%i, %i @ %i:%02i", GetMonthAbbrevString(q.tm_mon),q.tm_mday, 1900+q.tm_year,q.tm_hour,q.tm_min)); + trap->Cvar_Set(va("ui_lastServerRefresh_%i", ui_netSource.integer), + va("%s-%i, %i @ %i:%02i", GetMonthAbbrevString(q.tm_mon), q.tm_mday, 1900 + q.tm_year, q.tm_hour, q.tm_min)); if (!full) { UI_UpdatePendingPings(); @@ -10528,20 +9373,19 @@ static void UI_StartServerRefresh(qboolean full) // reset all the pings trap->LAN_ResetPings(lanSource); // - if( ui_netSource.integer == UIAS_LOCAL ) { - trap->Cmd_ExecuteText( EXEC_NOW, "localservers\n" ); + if (ui_netSource.integer == UIAS_LOCAL) { + trap->Cmd_ExecuteText(EXEC_NOW, "localservers\n"); uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 1000; return; } uiInfo.serverStatus.refreshtime = uiInfo.uiDC.realTime + 5000; - if( ui_netSource.integer >= UIAS_GLOBAL1 && ui_netSource.integer <= UIAS_GLOBAL5 ) { + if (ui_netSource.integer >= UIAS_GLOBAL1 && ui_netSource.integer <= UIAS_GLOBAL5) { ptr = UI_Cvar_VariableString("debug_protocol"); if (strlen(ptr)) { - trap->Cmd_ExecuteText( EXEC_NOW, va( "globalservers %d %s full empty\n", ui_netSource.integer-1, ptr)); - } - else { - trap->Cmd_ExecuteText( EXEC_NOW, va( "globalservers %d %d full empty\n", ui_netSource.integer-1, (int)trap->Cvar_VariableValue( "protocol" ) ) ); + trap->Cmd_ExecuteText(EXEC_NOW, va("globalservers %d %s full empty\n", ui_netSource.integer - 1, ptr)); + } else { + trap->Cmd_ExecuteText(EXEC_NOW, va("globalservers %d %d full empty\n", ui_netSource.integer - 1, (int)trap->Cvar_VariableValue("protocol"))); } } } @@ -10554,32 +9398,31 @@ GetModuleAPI uiImport_t *trap = NULL; -Q_EXPORT uiExport_t* QDECL GetModuleAPI( int apiVersion, uiImport_t *import ) -{ +Q_EXPORT uiExport_t *QDECL GetModuleAPI(int apiVersion, uiImport_t *import) { static uiExport_t uie = {0}; - assert( import ); + assert(import); trap = import; - Com_Printf = trap->Print; - Com_Error = trap->Error; + Com_Printf = trap->Print; + Com_Error = trap->Error; - memset( &uie, 0, sizeof( uie ) ); + memset(&uie, 0, sizeof(uie)); - if ( apiVersion != UI_API_VERSION ) { - trap->Print( "Mismatched UI_API_VERSION: expected %i, got %i\n", UI_API_VERSION, apiVersion ); + if (apiVersion != UI_API_VERSION) { + trap->Print("Mismatched UI_API_VERSION: expected %i, got %i\n", UI_API_VERSION, apiVersion); return NULL; } - uie.Init = UI_Init; - uie.Shutdown = UI_Shutdown; - uie.KeyEvent = UI_KeyEvent; - uie.MouseEvent = UI_MouseEvent; - uie.Refresh = UI_Refresh; - uie.IsFullscreen = Menus_AnyFullScreenVisible; - uie.SetActiveMenu = UI_SetActiveMenu; - uie.ConsoleCommand = UI_ConsoleCommand; - uie.DrawConnectScreen = UI_DrawConnectScreen; - uie.MenuReset = Menu_Reset; + uie.Init = UI_Init; + uie.Shutdown = UI_Shutdown; + uie.KeyEvent = UI_KeyEvent; + uie.MouseEvent = UI_MouseEvent; + uie.Refresh = UI_Refresh; + uie.IsFullscreen = Menus_AnyFullScreenVisible; + uie.SetActiveMenu = UI_SetActiveMenu; + uie.ConsoleCommand = UI_ConsoleCommand; + uie.DrawConnectScreen = UI_DrawConnectScreen; + uie.MenuReset = Menu_Reset; return &uie; } @@ -10590,15 +9433,14 @@ vmMain ============ */ -Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, - intptr_t arg5, intptr_t arg6, intptr_t arg7, intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11 ) -{ - switch ( command ) { +Q_EXPORT intptr_t vmMain(int command, intptr_t arg0, intptr_t arg1, intptr_t arg2, intptr_t arg3, intptr_t arg4, intptr_t arg5, intptr_t arg6, intptr_t arg7, + intptr_t arg8, intptr_t arg9, intptr_t arg10, intptr_t arg11) { + switch (command) { case UI_GETAPIVERSION: return UI_LEGACY_API_VERSION; case UI_INIT: - UI_Init( arg0 ); + UI_Init(arg0); return 0; case UI_SHUTDOWN: @@ -10606,29 +9448,29 @@ Q_EXPORT intptr_t vmMain( int command, intptr_t arg0, intptr_t arg1, intptr_t ar return 0; case UI_KEY_EVENT: - UI_KeyEvent( arg0, arg1 ); + UI_KeyEvent(arg0, arg1); return 0; case UI_MOUSE_EVENT: - UI_MouseEvent( arg0, arg1 ); + UI_MouseEvent(arg0, arg1); return 0; case UI_REFRESH: - UI_Refresh( arg0 ); + UI_Refresh(arg0); return 0; case UI_IS_FULLSCREEN: return Menus_AnyFullScreenVisible(); case UI_SET_ACTIVE_MENU: - UI_SetActiveMenu( arg0 ); + UI_SetActiveMenu(arg0); return 0; case UI_CONSOLE_COMMAND: return UI_ConsoleCommand(arg0); case UI_DRAW_CONNECT_SCREEN: - UI_DrawConnectScreen( arg0 ); + UI_DrawConnectScreen(arg0); return 0; case UI_MENU_RESET: diff --git a/codemp/ui/ui_saber.c b/codemp/ui/ui_saber.c index 4894171229..a4b5b35588 100644 --- a/codemp/ui/ui_saber.c +++ b/codemp/ui/ui_saber.c @@ -31,14 +31,14 @@ USER INTERFACE SABER LOADING & DISPLAY CODE #include "ui_local.h" #include "ui_shared.h" -void WP_SaberLoadParms( void ); -qboolean WP_SaberParseParm( const char *saberName, const char *parmname, char *saberData ); -saber_colors_t TranslateSaberColor( const char *name ); -const char *SaberColorToString( saber_colors_t color ); -saber_styles_t TranslateSaberStyle( const char *name ); -saberType_t TranslateSaberType( const char *name ); +void WP_SaberLoadParms(void); +qboolean WP_SaberParseParm(const char *saberName, const char *parmname, char *saberData); +saber_colors_t TranslateSaberColor(const char *name); +const char *SaberColorToString(saber_colors_t color); +saber_styles_t TranslateSaberStyle(const char *name); +saberType_t TranslateSaberType(const char *name); -qboolean ui_saber_parms_parsed = qfalse; +qboolean ui_saber_parms_parsed = qfalse; static qhandle_t redSaberGlowShader; static qhandle_t redSaberCoreShader; @@ -53,117 +53,88 @@ static qhandle_t blueSaberCoreShader; static qhandle_t purpleSaberGlowShader; static qhandle_t purpleSaberCoreShader; -void UI_CacheSaberGlowGraphics( void ) -{//FIXME: these get fucked by vid_restarts - redSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/red_glow" ); - redSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/red_line" ); - orangeSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/orange_glow" ); - orangeSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/orange_line" ); - yellowSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/yellow_glow" ); - yellowSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/yellow_line" ); - greenSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/green_glow" ); - greenSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/green_line" ); - blueSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/blue_glow" ); - blueSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/blue_line" ); - purpleSaberGlowShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/purple_glow" ); - purpleSaberCoreShader = trap->R_RegisterShaderNoMip( "gfx/effects/sabers/purple_line" ); +void UI_CacheSaberGlowGraphics(void) { // FIXME: these get fucked by vid_restarts + redSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/red_glow"); + redSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/red_line"); + orangeSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/orange_glow"); + orangeSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/orange_line"); + yellowSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/yellow_glow"); + yellowSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/yellow_line"); + greenSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/green_glow"); + greenSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/green_line"); + blueSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/blue_glow"); + blueSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/blue_line"); + purpleSaberGlowShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/purple_glow"); + purpleSaberCoreShader = trap->R_RegisterShaderNoMip("gfx/effects/sabers/purple_line"); } -qboolean UI_SaberModelForSaber( const char *saberName, char *saberModel ) -{ - return WP_SaberParseParm( saberName, "saberModel", saberModel ); -} +qboolean UI_SaberModelForSaber(const char *saberName, char *saberModel) { return WP_SaberParseParm(saberName, "saberModel", saberModel); } -qboolean UI_SaberSkinForSaber( const char *saberName, char *saberSkin ) -{ - return WP_SaberParseParm( saberName, "customSkin", saberSkin ); -} +qboolean UI_SaberSkinForSaber(const char *saberName, char *saberSkin) { return WP_SaberParseParm(saberName, "customSkin", saberSkin); } -qboolean UI_SaberTypeForSaber( const char *saberName, char *saberType ) -{ - return WP_SaberParseParm( saberName, "saberType", saberType ); -} +qboolean UI_SaberTypeForSaber(const char *saberName, char *saberType) { return WP_SaberParseParm(saberName, "saberType", saberType); } -int UI_SaberNumBladesForSaber( const char *saberName ) -{ +int UI_SaberNumBladesForSaber(const char *saberName) { int numBlades; - char numBladesString[8]={0}; - WP_SaberParseParm( saberName, "numBlades", numBladesString ); - numBlades = atoi( numBladesString ); - if ( numBlades < 1 ) - { + char numBladesString[8] = {0}; + WP_SaberParseParm(saberName, "numBlades", numBladesString); + numBlades = atoi(numBladesString); + if (numBlades < 1) { numBlades = 1; - } - else if ( numBlades > 8 ) - { + } else if (numBlades > 8) { numBlades = 8; } return numBlades; } -qboolean UI_SaberShouldDrawBlade( const char *saberName, int bladeNum ) -{ +qboolean UI_SaberShouldDrawBlade(const char *saberName, int bladeNum) { int bladeStyle2Start = 0, noBlade = 0; - char bladeStyle2StartString[8]={0}; - char noBladeString[8]={0}; - WP_SaberParseParm( saberName, "bladeStyle2Start", bladeStyle2StartString ); - if ( bladeStyle2StartString[0] ) - { - bladeStyle2Start = atoi( bladeStyle2StartString ); - } - if ( bladeStyle2Start - && bladeNum >= bladeStyle2Start ) - {//use second blade style - WP_SaberParseParm( saberName, "noBlade2", noBladeString ); - if ( noBladeString[0] ) - { - noBlade = atoi( noBladeString ); + char bladeStyle2StartString[8] = {0}; + char noBladeString[8] = {0}; + WP_SaberParseParm(saberName, "bladeStyle2Start", bladeStyle2StartString); + if (bladeStyle2StartString[0]) { + bladeStyle2Start = atoi(bladeStyle2StartString); + } + if (bladeStyle2Start && bladeNum >= bladeStyle2Start) { // use second blade style + WP_SaberParseParm(saberName, "noBlade2", noBladeString); + if (noBladeString[0]) { + noBlade = atoi(noBladeString); } - } - else - {//use first blade style - WP_SaberParseParm( saberName, "noBlade", noBladeString ); - if ( noBladeString[0] ) - { - noBlade = atoi( noBladeString ); + } else { // use first blade style + WP_SaberParseParm(saberName, "noBlade", noBladeString); + if (noBladeString[0]) { + noBlade = atoi(noBladeString); } } - return ((qboolean)(noBlade==0)); + return ((qboolean)(noBlade == 0)); } -qboolean UI_IsSaberTwoHanded( const char *saberName ) -{ +qboolean UI_IsSaberTwoHanded(const char *saberName) { int twoHanded; - char twoHandedString[8]={0}; - WP_SaberParseParm( saberName, "twoHanded", twoHandedString ); - if ( !twoHandedString[0] ) - {//not defined defaults to "no" + char twoHandedString[8] = {0}; + WP_SaberParseParm(saberName, "twoHanded", twoHandedString); + if (!twoHandedString[0]) { // not defined defaults to "no" return qfalse; } - twoHanded = atoi( twoHandedString ); - return ((qboolean)(twoHanded!=0)); + twoHanded = atoi(twoHandedString); + return ((qboolean)(twoHanded != 0)); } -float UI_SaberBladeLengthForSaber( const char *saberName, int bladeNum ) -{ - char lengthString[8]={0}; - float length = 40.0f; - WP_SaberParseParm( saberName, "saberLength", lengthString ); - if ( lengthString[0] ) - { - length = atof( lengthString ); - if ( length < 0.0f ) - { +float UI_SaberBladeLengthForSaber(const char *saberName, int bladeNum) { + char lengthString[8] = {0}; + float length = 40.0f; + WP_SaberParseParm(saberName, "saberLength", lengthString); + if (lengthString[0]) { + length = atof(lengthString); + if (length < 0.0f) { length = 0.0f; } } - WP_SaberParseParm( saberName, va("saberLength%d", bladeNum+1), lengthString ); - if ( lengthString[0] ) - { - length = atof( lengthString ); - if ( length < 0.0f ) - { + WP_SaberParseParm(saberName, va("saberLength%d", bladeNum + 1), lengthString); + if (lengthString[0]) { + length = atof(lengthString); + if (length < 0.0f) { length = 0.0f; } } @@ -171,26 +142,21 @@ float UI_SaberBladeLengthForSaber( const char *saberName, int bladeNum ) return length; } -float UI_SaberBladeRadiusForSaber( const char *saberName, int bladeNum ) -{ - char radiusString[8]={0}; - float radius = 3.0f; - WP_SaberParseParm( saberName, "saberRadius", radiusString ); - if ( radiusString[0] ) - { - radius = atof( radiusString ); - if ( radius < 0.0f ) - { +float UI_SaberBladeRadiusForSaber(const char *saberName, int bladeNum) { + char radiusString[8] = {0}; + float radius = 3.0f; + WP_SaberParseParm(saberName, "saberRadius", radiusString); + if (radiusString[0]) { + radius = atof(radiusString); + if (radius < 0.0f) { radius = 0.0f; } } - WP_SaberParseParm( saberName, va("saberRadius%d", bladeNum+1), radiusString ); - if ( radiusString[0] ) - { - radius = atof( radiusString ); - if ( radius < 0.0f ) - { + WP_SaberParseParm(saberName, va("saberRadius%d", bladeNum + 1), radiusString); + if (radiusString[0]) { + radius = atof(radiusString); + if (radius < 0.0f) { radius = 0.0f; } } @@ -198,104 +164,91 @@ float UI_SaberBladeRadiusForSaber( const char *saberName, int bladeNum ) return radius; } -qboolean UI_SaberProperNameForSaber( const char *saberName, char *saberProperName ) -{ - char stringedSaberName[1024]; - qboolean ret = WP_SaberParseParm( saberName, "name", stringedSaberName ); +qboolean UI_SaberProperNameForSaber(const char *saberName, char *saberProperName) { + char stringedSaberName[1024]; + qboolean ret = WP_SaberParseParm(saberName, "name", stringedSaberName); // if it's a stringed reference translate it - if( ret && stringedSaberName[0] == '@') - { + if (ret && stringedSaberName[0] == '@') { trap->SE_GetStringTextString(&stringedSaberName[1], saberProperName, 1024); - } - else - { + } else { // no stringed so just use it as it - strcpy( saberProperName, stringedSaberName ); + strcpy(saberProperName, stringedSaberName); } return ret; } -qboolean UI_SaberValidForPlayerInMP( const char *saberName ) -{ - char allowed [8]={0}; - if ( !WP_SaberParseParm( saberName, "notInMP", allowed ) ) - {//not defined, default is yes +qboolean UI_SaberValidForPlayerInMP(const char *saberName) { + char allowed[8] = {0}; + if (!WP_SaberParseParm(saberName, "notInMP", allowed)) { // not defined, default is yes return qtrue; } - if ( !allowed[0] ) - {//not defined, default is yes + if (!allowed[0]) { // not defined, default is yes return qtrue; - } - else - {//return value - return ((qboolean)(atoi(allowed)==0)); + } else { // return value + return ((qboolean)(atoi(allowed) == 0)); } } -void UI_SaberLoadParms( void ) -{ +void UI_SaberLoadParms(void) { ui_saber_parms_parsed = qtrue; UI_CacheSaberGlowGraphics(); WP_SaberLoadParms(); } -void UI_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color ) -{ - vec3_t mid, rgb={1,1,1}; - qhandle_t blade = 0, glow = 0; +void UI_DoSaber(vec3_t origin, vec3_t dir, float length, float lengthMax, float radius, saber_colors_t color) { + vec3_t mid, rgb = {1, 1, 1}; + qhandle_t blade = 0, glow = 0; refEntity_t saber; float radiusmult; float radiusRange; float radiusStart; - if ( length < 0.5f ) - { + if (length < 0.5f) { // if the thing is so short, just forget even adding me. return; } // Find the midpoint of the saber for lighting purposes - VectorMA( origin, length * 0.5f, dir, mid ); + VectorMA(origin, length * 0.5f, dir, mid); - switch( color ) - { - case SABER_RED: - glow = redSaberGlowShader; - blade = redSaberCoreShader; - VectorSet( rgb, 1.0f, 0.2f, 0.2f ); - break; - case SABER_ORANGE: - glow = orangeSaberGlowShader; - blade = orangeSaberCoreShader; - VectorSet( rgb, 1.0f, 0.5f, 0.1f ); - break; - case SABER_YELLOW: - glow = yellowSaberGlowShader; - blade = yellowSaberCoreShader; - VectorSet( rgb, 1.0f, 1.0f, 0.2f ); - break; - case SABER_GREEN: - glow = greenSaberGlowShader; - blade = greenSaberCoreShader; - VectorSet( rgb, 0.2f, 1.0f, 0.2f ); - break; - case SABER_BLUE: - glow = blueSaberGlowShader; - blade = blueSaberCoreShader; - VectorSet( rgb, 0.2f, 0.4f, 1.0f ); - break; - case SABER_PURPLE: - glow = purpleSaberGlowShader; - blade = purpleSaberCoreShader; - VectorSet( rgb, 0.9f, 0.2f, 1.0f ); - break; - default: - break; + switch (color) { + case SABER_RED: + glow = redSaberGlowShader; + blade = redSaberCoreShader; + VectorSet(rgb, 1.0f, 0.2f, 0.2f); + break; + case SABER_ORANGE: + glow = orangeSaberGlowShader; + blade = orangeSaberCoreShader; + VectorSet(rgb, 1.0f, 0.5f, 0.1f); + break; + case SABER_YELLOW: + glow = yellowSaberGlowShader; + blade = yellowSaberCoreShader; + VectorSet(rgb, 1.0f, 1.0f, 0.2f); + break; + case SABER_GREEN: + glow = greenSaberGlowShader; + blade = greenSaberCoreShader; + VectorSet(rgb, 0.2f, 1.0f, 0.2f); + break; + case SABER_BLUE: + glow = blueSaberGlowShader; + blade = blueSaberCoreShader; + VectorSet(rgb, 0.2f, 0.4f, 1.0f); + break; + case SABER_PURPLE: + glow = purpleSaberGlowShader; + blade = purpleSaberCoreShader; + VectorSet(rgb, 0.9f, 0.2f, 1.0f); + break; + default: + break; } - memset( &saber, 0, sizeof( refEntity_t )); + memset(&saber, 0, sizeof(refEntity_t)); // Saber glow is it's own ref type because it uses a ton of sprites, otherwise it would eat up too many // refEnts to do each glow blob individually @@ -303,395 +256,342 @@ void UI_DoSaber( vec3_t origin, vec3_t dir, float length, float lengthMax, float // Jeff, I did this because I foolishly wished to have a bright halo as the saber is unleashed. // It's not quite what I'd hoped tho. If you have any ideas, go for it! --Pat - if (length < lengthMax ) - { - radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. - } - else - { + if (length < lengthMax) { + radiusmult = 1.0 + (2.0 / length); // Note this creates a curve, and length cannot be < 0.5. + } else { radiusmult = 1.0; } radiusRange = radius * 0.075f; - radiusStart = radius-radiusRange; + radiusStart = radius - radiusRange; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; - //saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (2.8f + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - VectorCopy( origin, saber.origin ); - VectorCopy( dir, saber.axis[0] ); + VectorCopy(origin, saber.origin); + VectorCopy(dir, saber.axis[0]); saber.reType = RT_SABER_GLOW; saber.customShader = glow; saber.shaderRGBA[0] = saber.shaderRGBA[1] = saber.shaderRGBA[2] = saber.shaderRGBA[3] = 0xff; - //saber.renderfx = rfx; + // saber.renderfx = rfx; - trap->R_AddRefEntityToScene( &saber ); + trap->R_AddRefEntityToScene(&saber); // Do the hot core - VectorMA( origin, length, dir, saber.origin ); - VectorMA( origin, -1, dir, saber.oldorigin ); + VectorMA(origin, length, dir, saber.origin); + VectorMA(origin, -1, dir, saber.oldorigin); saber.customShader = blade; saber.reType = RT_LINE; - radiusStart = radius/3.0f; - saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange)*radiusmult; -// saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; + radiusStart = radius / 3.0f; + saber.radius = (radiusStart + Q_flrand(-1.0f, 1.0f) * radiusRange) * radiusmult; + // saber.radius = (1.0 + Q_flrand(-1.0f, 1.0f) * 0.2f)*radiusmult; - trap->R_AddRefEntityToScene( &saber ); + trap->R_AddRefEntityToScene(&saber); } -void UI_SaberDrawBlade( itemDef_t *item, char *saberName, int saberModel, saberType_t saberType, vec3_t origin, vec3_t angles, int bladeNum ) -{ +void UI_SaberDrawBlade(itemDef_t *item, char *saberName, int saberModel, saberType_t saberType, vec3_t origin, vec3_t angles, int bladeNum) { char bladeColorString[MAX_QPATH]; saber_colors_t bladeColor; - float bladeLength,bladeRadius; - vec3_t bladeOrigin={0}; - matrix3_t axis; -// vec3_t angles={0}; - mdxaBone_t boltMatrix; + float bladeLength, bladeRadius; + vec3_t bladeOrigin = {0}; + matrix3_t axis; + // vec3_t angles={0}; + mdxaBone_t boltMatrix; qboolean tagHack = qfalse; char *tagName; int bolt; float scale; - memset (axis, 0, sizeof (axis)); + memset(axis, 0, sizeof(axis)); - if ( (item->flags&ITF_ISSABER) && saberModel < 2 ) + if ((item->flags & ITF_ISSABER) && saberModel < 2) { + trap->Cvar_VariableStringBuffer("ui_saber_color", bladeColorString, sizeof(bladeColorString)); + } else // if ( item->flags&ITF_ISSABER2 ) - presumed { - trap->Cvar_VariableStringBuffer("ui_saber_color", bladeColorString, sizeof(bladeColorString) ); - } - else//if ( item->flags&ITF_ISSABER2 ) - presumed - { - trap->Cvar_VariableStringBuffer("ui_saber2_color", bladeColorString, sizeof(bladeColorString) ); + trap->Cvar_VariableStringBuffer("ui_saber2_color", bladeColorString, sizeof(bladeColorString)); } - if ( !trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2),saberModel) ) - {//invalid index! + if (!trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2), saberModel)) { // invalid index! return; } - bladeColor = TranslateSaberColor( bladeColorString ); + bladeColor = TranslateSaberColor(bladeColorString); - bladeLength = UI_SaberBladeLengthForSaber( saberName, bladeNum ); - bladeRadius = UI_SaberBladeRadiusForSaber( saberName, bladeNum ); + bladeLength = UI_SaberBladeLengthForSaber(saberName, bladeNum); + bladeRadius = UI_SaberBladeRadiusForSaber(saberName, bladeNum); - tagName = va( "*blade%d", bladeNum+1 ); - bolt = trap->G2API_AddBolt( item->ghoul2,saberModel, tagName ); + tagName = va("*blade%d", bladeNum + 1); + bolt = trap->G2API_AddBolt(item->ghoul2, saberModel, tagName); - if ( bolt == -1 ) - { + if (bolt == -1) { tagHack = qtrue; - //hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models - bolt = trap->G2API_AddBolt( item->ghoul2,saberModel, "*flash" ); - if ( bolt == -1 ) - {//no tag_flash either?!! + // hmm, just fall back to the most basic tag (this will also make it work with pre-JKA saber models + bolt = trap->G2API_AddBolt(item->ghoul2, saberModel, "*flash"); + if (bolt == -1) { // no tag_flash either?!! bolt = 0; } } -// angles[PITCH] = curYaw; -// angles[ROLL] = 0; + // angles[PITCH] = curYaw; + // angles[ROLL] = 0; - trap->G2API_GetBoltMatrix( item->ghoul2, saberModel, bolt, &boltMatrix, angles, origin, uiInfo.uiDC.realTime, NULL, vec3_origin );//NULL was cgs.model_draw + trap->G2API_GetBoltMatrix(item->ghoul2, saberModel, bolt, &boltMatrix, angles, origin, uiInfo.uiDC.realTime, NULL, vec3_origin); // NULL was cgs.model_draw // work the matrix axis stuff into the original axis and origins used. BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, bladeOrigin); - BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, axis[0]);//front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) - // ...changed this back to NEGATIVE_Y - BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, axis[1]);//right ... and changed this to NEGATIVE_X - BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, axis[2]);//up + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_Y, axis[0]); // front (was NEGATIVE_Y, but the md3->glm exporter screws up this tag somethin' awful) + // ...changed this back to NEGATIVE_Y + BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, axis[1]); // right ... and changed this to NEGATIVE_X + BG_GiveMeVectorFromMatrix(&boltMatrix, POSITIVE_Z, axis[2]); // up // Where do I get scale from? -// scale = DC->xscale; + // scale = DC->xscale; scale = 1.0f; - if ( tagHack ) - { - switch ( saberType ) - { + if (tagHack) { + switch (saberType) { case SABER_SINGLE: - VectorMA( bladeOrigin, scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, scale, axis[0], bladeOrigin); break; case SABER_DAGGER: case SABER_LANCE: break; case SABER_STAFF: - if ( bladeNum == 0 ) - { - VectorMA( bladeOrigin, 12*scale, axis[0], bladeOrigin ); + if (bladeNum == 0) { + VectorMA(bladeOrigin, 12 * scale, axis[0], bladeOrigin); } - if ( bladeNum == 1 ) - { - VectorScale( axis[0], -1, axis[0] ); - VectorMA( bladeOrigin, 12*scale, axis[0], bladeOrigin ); + if (bladeNum == 1) { + VectorScale(axis[0], -1, axis[0]); + VectorMA(bladeOrigin, 12 * scale, axis[0], bladeOrigin); } break; case SABER_BROAD: - if ( bladeNum == 0 ) - { - VectorMA( bladeOrigin, -1*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, 1*scale, axis[1], bladeOrigin ); + if (bladeNum == 0) { + VectorMA(bladeOrigin, -1 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 1) { + VectorMA(bladeOrigin, 1 * scale, axis[1], bladeOrigin); } break; case SABER_PRONG: - if ( bladeNum == 0 ) - { - VectorMA( bladeOrigin, -3*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, 3*scale, axis[1], bladeOrigin ); + if (bladeNum == 0) { + VectorMA(bladeOrigin, -3 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 1) { + VectorMA(bladeOrigin, 3 * scale, axis[1], bladeOrigin); } break; case SABER_ARC: - VectorSubtract( axis[1], axis[2], axis[1] ); - VectorNormalize( axis[1] ); - switch ( bladeNum ) - { + VectorSubtract(axis[1], axis[2], axis[1]); + VectorNormalize(axis[1]); + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], 0.75f, axis[0] ); - VectorScale( axis[1], 0.25f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], 0.75f, axis[0]); + VectorScale(axis[1], 0.25f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 1: - VectorScale( axis[0], 0.25f, axis[0] ); - VectorScale( axis[1], 0.75f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorScale(axis[0], 0.25f, axis[0]); + VectorScale(axis[1], 0.75f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 2: - VectorMA( bladeOrigin, -8*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -0.25f, axis[0] ); - VectorScale( axis[1], 0.75f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, -8 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -0.25f, axis[0]); + VectorScale(axis[1], 0.75f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; case 3: - VectorMA( bladeOrigin, -16*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -0.75f, axis[0] ); - VectorScale( axis[1], 0.25f, axis[1] ); - VectorAdd( axis[0], axis[1], axis[0] ); + VectorMA(bladeOrigin, -16 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -0.75f, axis[0]); + VectorScale(axis[1], 0.25f, axis[1]); + VectorAdd(axis[0], axis[1], axis[0]); break; } break; case SABER_SAI: - if ( bladeNum == 1 ) - { - VectorMA( bladeOrigin, -3*scale, axis[1], bladeOrigin ); - } - else if ( bladeNum == 2 ) - { - VectorMA( bladeOrigin, 3*scale, axis[1], bladeOrigin ); + if (bladeNum == 1) { + VectorMA(bladeOrigin, -3 * scale, axis[1], bladeOrigin); + } else if (bladeNum == 2) { + VectorMA(bladeOrigin, 3 * scale, axis[1], bladeOrigin); } break; case SABER_CLAW: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); break; case 1: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[1], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[1], bladeOrigin); break; case 2: - VectorMA( bladeOrigin, 2*scale, axis[0], bladeOrigin ); - VectorMA( bladeOrigin, 2*scale, axis[2], bladeOrigin ); - VectorMA( bladeOrigin, -2*scale, axis[1], bladeOrigin ); + VectorMA(bladeOrigin, 2 * scale, axis[0], bladeOrigin); + VectorMA(bladeOrigin, 2 * scale, axis[2], bladeOrigin); + VectorMA(bladeOrigin, -2 * scale, axis[1], bladeOrigin); break; } break; case SABER_STAR: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 1: - VectorScale( axis[0], 0.33f, axis[0] ); - VectorScale( axis[2], 0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], 0.33f, axis[0]); + VectorScale(axis[2], 0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 2: - VectorScale( axis[0], -0.33f, axis[0] ); - VectorScale( axis[2], 0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -0.33f, axis[0]); + VectorScale(axis[2], 0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 3: - VectorScale( axis[0], -1, axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -1, axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 4: - VectorScale( axis[0], -0.33f, axis[0] ); - VectorScale( axis[2], -0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], -0.33f, axis[0]); + VectorScale(axis[2], -0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; case 5: - VectorScale( axis[0], 0.33f, axis[0] ); - VectorScale( axis[2], -0.67f, axis[2] ); - VectorAdd( axis[0], axis[2], axis[0] ); - VectorMA( bladeOrigin, 8*scale, axis[0], bladeOrigin ); + VectorScale(axis[0], 0.33f, axis[0]); + VectorScale(axis[2], -0.67f, axis[2]); + VectorAdd(axis[0], axis[2], axis[0]); + VectorMA(bladeOrigin, 8 * scale, axis[0], bladeOrigin); break; } break; case SABER_TRIDENT: - switch ( bladeNum ) - { + switch (bladeNum) { case 0: - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 1: - VectorMA( bladeOrigin, -6*scale, axis[1], bladeOrigin ); - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, -6 * scale, axis[1], bladeOrigin); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 2: - VectorMA( bladeOrigin, 6*scale, axis[1], bladeOrigin ); - VectorMA( bladeOrigin, 24*scale, axis[0], bladeOrigin ); + VectorMA(bladeOrigin, 6 * scale, axis[1], bladeOrigin); + VectorMA(bladeOrigin, 24 * scale, axis[0], bladeOrigin); break; case 3: - VectorMA( bladeOrigin, -32*scale, axis[0], bladeOrigin ); - VectorScale( axis[0], -1, axis[0] ); + VectorMA(bladeOrigin, -32 * scale, axis[0], bladeOrigin); + VectorScale(axis[0], -1, axis[0]); break; } break; case SABER_SITH_SWORD: - //no blade + // no blade break; default: break; } } - if ( saberType == SABER_SITH_SWORD ) - {//draw no blade + if (saberType == SABER_SITH_SWORD) { // draw no blade return; } - UI_DoSaber( bladeOrigin, axis[0], bladeLength, bladeLength, bladeRadius, bladeColor ); + UI_DoSaber(bladeOrigin, axis[0], bladeLength, bladeLength, bladeRadius, bladeColor); } -void UI_GetSaberForMenu( char *saber, int saberNum ) -{ - char saberTypeString[MAX_QPATH]={0}; +void UI_GetSaberForMenu(char *saber, int saberNum) { + char saberTypeString[MAX_QPATH] = {0}; saberType_t saberType = SABER_NONE; - if ( saberNum == 0 ) - { - trap->Cvar_VariableStringBuffer("ui_saber", saber, MAX_QPATH ); - if ( !UI_SaberValidForPlayerInMP( saber ) ) - { - trap->Cvar_Set( "ui_saber", DEFAULT_SABER ); - trap->Cvar_VariableStringBuffer("ui_saber", saber, MAX_QPATH ); + if (saberNum == 0) { + trap->Cvar_VariableStringBuffer("ui_saber", saber, MAX_QPATH); + if (!UI_SaberValidForPlayerInMP(saber)) { + trap->Cvar_Set("ui_saber", DEFAULT_SABER); + trap->Cvar_VariableStringBuffer("ui_saber", saber, MAX_QPATH); } - } - else - { - trap->Cvar_VariableStringBuffer("ui_saber2", saber, MAX_QPATH ); - if ( !UI_SaberValidForPlayerInMP( saber ) ) - { - trap->Cvar_Set( "ui_saber2", DEFAULT_SABER ); - trap->Cvar_VariableStringBuffer("ui_saber2", saber, MAX_QPATH ); + } else { + trap->Cvar_VariableStringBuffer("ui_saber2", saber, MAX_QPATH); + if (!UI_SaberValidForPlayerInMP(saber)) { + trap->Cvar_Set("ui_saber2", DEFAULT_SABER); + trap->Cvar_VariableStringBuffer("ui_saber2", saber, MAX_QPATH); } } - //read this from the sabers.cfg - UI_SaberTypeForSaber( saber, saberTypeString ); - if ( saberTypeString[0] ) - { - saberType = TranslateSaberType( saberTypeString ); + // read this from the sabers.cfg + UI_SaberTypeForSaber(saber, saberTypeString); + if (saberTypeString[0]) { + saberType = TranslateSaberType(saberTypeString); } - switch ( uiInfo.movesTitleIndex ) - { - case 0://MD_ACROBATICS: + switch (uiInfo.movesTitleIndex) { + case 0: // MD_ACROBATICS: break; - case 1://MD_SINGLE_FAST: - case 2://MD_SINGLE_MEDIUM: - case 3://MD_SINGLE_STRONG: - if ( saberType != SABER_SINGLE ) - { + case 1: // MD_SINGLE_FAST: + case 2: // MD_SINGLE_MEDIUM: + case 3: // MD_SINGLE_STRONG: + if (saberType != SABER_SINGLE) { Q_strncpyz(saber, DEFAULT_SABER, MAX_QPATH); } break; - case 4://MD_DUAL_SABERS: - if ( saberType != SABER_SINGLE ) - { + case 4: // MD_DUAL_SABERS: + if (saberType != SABER_SINGLE) { Q_strncpyz(saber, DEFAULT_SABER, MAX_QPATH); } break; - case 5://MD_SABER_STAFF: - if ( saberType == SABER_SINGLE || saberType == SABER_NONE ) - { + case 5: // MD_SABER_STAFF: + if (saberType == SABER_SINGLE || saberType == SABER_NONE) { Q_strncpyz(saber, DEFAULT_SABER_STAFF, MAX_QPATH); } break; } } -void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, vec3_t angles ) -{ - //NOTE: only allows one saber type in view at a time +void UI_SaberDrawBlades(itemDef_t *item, vec3_t origin, vec3_t angles) { + // NOTE: only allows one saber type in view at a time char saber[MAX_QPATH]; int saberNum = 0; int saberModel = 0; - int numSabers = 1; + int numSabers = 1; - if ( (item->flags&ITF_ISCHARACTER)//hacked sabermoves sabers in character's hand - && uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/ ) - { + if ((item->flags & ITF_ISCHARACTER) // hacked sabermoves sabers in character's hand + && uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/) { numSabers = 2; } - for ( saberNum = 0; saberNum < numSabers; saberNum++ ) - { - if ( (item->flags&ITF_ISCHARACTER) )//hacked sabermoves sabers in character's hand + for (saberNum = 0; saberNum < numSabers; saberNum++) { + if ((item->flags & ITF_ISCHARACTER)) // hacked sabermoves sabers in character's hand { - UI_GetSaberForMenu( saber, saberNum ); + UI_GetSaberForMenu(saber, saberNum); saberModel = saberNum + 1; - } - else if ( (item->flags&ITF_ISSABER) ) - { - trap->Cvar_VariableStringBuffer("ui_saber", saber, sizeof(saber) ); - if ( !UI_SaberValidForPlayerInMP( saber ) ) - { - trap->Cvar_Set( "ui_saber", DEFAULT_SABER ); - trap->Cvar_VariableStringBuffer("ui_saber", saber, sizeof(saber) ); + } else if ((item->flags & ITF_ISSABER)) { + trap->Cvar_VariableStringBuffer("ui_saber", saber, sizeof(saber)); + if (!UI_SaberValidForPlayerInMP(saber)) { + trap->Cvar_Set("ui_saber", DEFAULT_SABER); + trap->Cvar_VariableStringBuffer("ui_saber", saber, sizeof(saber)); } saberModel = 0; - } - else if ( (item->flags&ITF_ISSABER2) ) - { - trap->Cvar_VariableStringBuffer("ui_saber2", saber, sizeof(saber) ); - if ( !UI_SaberValidForPlayerInMP( saber ) ) - { - trap->Cvar_Set( "ui_saber2", DEFAULT_SABER ); - trap->Cvar_VariableStringBuffer("ui_saber2", saber, sizeof(saber) ); + } else if ((item->flags & ITF_ISSABER2)) { + trap->Cvar_VariableStringBuffer("ui_saber2", saber, sizeof(saber)); + if (!UI_SaberValidForPlayerInMP(saber)) { + trap->Cvar_Set("ui_saber2", DEFAULT_SABER); + trap->Cvar_VariableStringBuffer("ui_saber2", saber, sizeof(saber)); } saberModel = 0; - } - else - { + } else { return; } - if ( saber[0] ) - { + if (saber[0]) { saberType_t saberType; int curBlade = 0; - int numBlades = UI_SaberNumBladesForSaber( saber ); - if ( numBlades ) - {//okay, here we go, time to draw each blade... - char saberTypeString[MAX_QPATH]={0}; - UI_SaberTypeForSaber( saber, saberTypeString ); - saberType = TranslateSaberType( saberTypeString ); - for ( curBlade = 0; curBlade < numBlades; curBlade++ ) - { - if ( UI_SaberShouldDrawBlade( saber, curBlade ) ) - { - UI_SaberDrawBlade( item, saber, saberModel, saberType, origin, angles, curBlade ); + int numBlades = UI_SaberNumBladesForSaber(saber); + if (numBlades) { // okay, here we go, time to draw each blade... + char saberTypeString[MAX_QPATH] = {0}; + UI_SaberTypeForSaber(saber, saberTypeString); + saberType = TranslateSaberType(saberTypeString); + for (curBlade = 0; curBlade < numBlades; curBlade++) { + if (UI_SaberShouldDrawBlade(saber, curBlade)) { + UI_SaberDrawBlade(item, saber, saberModel, saberType, origin, angles, curBlade); } } } @@ -699,59 +599,46 @@ void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, vec3_t angles ) } } -void UI_SaberAttachToChar( itemDef_t *item ) -{ - int numSabers = 1; - int saberNum = 0; +void UI_SaberAttachToChar(itemDef_t *item) { + int numSabers = 1; + int saberNum = 0; - if ( trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2),2) ) - {//remove any extra models + if (trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2), 2)) { // remove any extra models trap->G2API_RemoveGhoul2Model(&(item->ghoul2), 2); } - if ( trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2),1) ) - {//remove any extra models + if (trap->G2API_HasGhoul2ModelOnIndex(&(item->ghoul2), 1)) { // remove any extra models trap->G2API_RemoveGhoul2Model(&(item->ghoul2), 1); } - if ( uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/ ) - { + if (uiInfo.movesTitleIndex == 4 /*MD_DUAL_SABERS*/) { numSabers = 2; } - for ( saberNum = 0; saberNum < numSabers; saberNum++ ) - { - //bolt sabers + for (saberNum = 0; saberNum < numSabers; saberNum++) { + // bolt sabers char modelPath[MAX_QPATH]; char skinPath[MAX_QPATH]; char saber[MAX_QPATH]; - UI_GetSaberForMenu( saber, saberNum ); + UI_GetSaberForMenu(saber, saberNum); - if ( UI_SaberModelForSaber( saber, modelPath ) ) - {//successfully found a model - int g2Saber = trap->G2API_InitGhoul2Model( &(item->ghoul2), modelPath, 0, 0, 0, 0, 0 ); //add the model - if ( g2Saber ) - { + if (UI_SaberModelForSaber(saber, modelPath)) { // successfully found a model + int g2Saber = trap->G2API_InitGhoul2Model(&(item->ghoul2), modelPath, 0, 0, 0, 0, 0); // add the model + if (g2Saber) { int boltNum; - //get the customSkin, if any - if ( UI_SaberSkinForSaber( saber, skinPath ) ) - { + // get the customSkin, if any + if (UI_SaberSkinForSaber(saber, skinPath)) { int g2skin = trap->R_RegisterSkin(skinPath); - trap->G2API_SetSkin( item->ghoul2, g2Saber, 0, g2skin );//this is going to set the surfs on/off matching the skin file - } - else - { - trap->G2API_SetSkin( item->ghoul2, g2Saber, 0, 0 );//turn off custom skin - } - if ( saberNum == 0 ) - { - boltNum = trap->G2API_AddBolt( item->ghoul2, 0, "*r_hand"); + trap->G2API_SetSkin(item->ghoul2, g2Saber, 0, g2skin); // this is going to set the surfs on/off matching the skin file + } else { + trap->G2API_SetSkin(item->ghoul2, g2Saber, 0, 0); // turn off custom skin } - else - { - boltNum = trap->G2API_AddBolt( item->ghoul2, 0, "*l_hand"); + if (saberNum == 0) { + boltNum = trap->G2API_AddBolt(item->ghoul2, 0, "*r_hand"); + } else { + boltNum = trap->G2API_AddBolt(item->ghoul2, 0, "*l_hand"); } - trap->G2API_AttachG2Model( item->ghoul2, g2Saber, item->ghoul2, boltNum, 0); + trap->G2API_AttachG2Model(item->ghoul2, g2Saber, item->ghoul2, boltNum, 0); } } } diff --git a/codemp/ui/ui_shared.c b/codemp/ui/ui_shared.c index f2ed6d56f9..7e3ef8ad87 100644 --- a/codemp/ui/ui_shared.c +++ b/codemp/ui/ui_shared.c @@ -26,43 +26,43 @@ along with this program; if not, see . // string allocation/managment #ifdef _CGAME - #include "cgame/cg_local.h" +#include "cgame/cg_local.h" #elif UI_BUILD - #include "ui/ui_local.h" +#include "ui/ui_local.h" #endif #include "ui_shared.h" #include "game/bg_public.h" #include "game/anims.h" #include "ghoul2/G2.h" -extern stringID_table_t animTable [MAX_ANIMATIONS+1]; -extern void UI_UpdateCharacterSkin( void ); +extern stringID_table_t animTable[MAX_ANIMATIONS + 1]; +extern void UI_UpdateCharacterSkin(void); const char *HolocronIcons[NUM_FORCE_POWERS] = { - "gfx/mp/f_icon_lt_heal", //FP_HEAL, - "gfx/mp/f_icon_levitation", //FP_LEVITATION, - "gfx/mp/f_icon_speed", //FP_SPEED, - "gfx/mp/f_icon_push", //FP_PUSH, - "gfx/mp/f_icon_pull", //FP_PULL, - "gfx/mp/f_icon_lt_telepathy", //FP_TELEPATHY, - "gfx/mp/f_icon_dk_grip", //FP_GRIP, - "gfx/mp/f_icon_dk_l1", //FP_LIGHTNING, - "gfx/mp/f_icon_dk_rage", //FP_RAGE, - "gfx/mp/f_icon_lt_protect", //FP_PROTECT, - "gfx/mp/f_icon_lt_absorb", //FP_ABSORB, - "gfx/mp/f_icon_lt_healother", //FP_TEAM_HEAL, - "gfx/mp/f_icon_dk_forceother", //FP_TEAM_FORCE, - "gfx/mp/f_icon_dk_drain", //FP_DRAIN, - "gfx/mp/f_icon_sight", //FP_SEE, - "gfx/mp/f_icon_saber_attack", //FP_SABER_OFFENSE, - "gfx/mp/f_icon_saber_defend", //FP_SABER_DEFENSE, - "gfx/mp/f_icon_saber_throw" //FP_SABERTHROW + "gfx/mp/f_icon_lt_heal", // FP_HEAL, + "gfx/mp/f_icon_levitation", // FP_LEVITATION, + "gfx/mp/f_icon_speed", // FP_SPEED, + "gfx/mp/f_icon_push", // FP_PUSH, + "gfx/mp/f_icon_pull", // FP_PULL, + "gfx/mp/f_icon_lt_telepathy", // FP_TELEPATHY, + "gfx/mp/f_icon_dk_grip", // FP_GRIP, + "gfx/mp/f_icon_dk_l1", // FP_LIGHTNING, + "gfx/mp/f_icon_dk_rage", // FP_RAGE, + "gfx/mp/f_icon_lt_protect", // FP_PROTECT, + "gfx/mp/f_icon_lt_absorb", // FP_ABSORB, + "gfx/mp/f_icon_lt_healother", // FP_TEAM_HEAL, + "gfx/mp/f_icon_dk_forceother", // FP_TEAM_FORCE, + "gfx/mp/f_icon_dk_drain", // FP_DRAIN, + "gfx/mp/f_icon_sight", // FP_SEE, + "gfx/mp/f_icon_saber_attack", // FP_SABER_OFFENSE, + "gfx/mp/f_icon_saber_defend", // FP_SABER_DEFENSE, + "gfx/mp/f_icon_saber_throw" // FP_SABERTHROW }; -#define SCROLL_TIME_START 500 -#define SCROLL_TIME_ADJUST 150 -#define SCROLL_TIME_ADJUSTOFFSET 40 -#define SCROLL_TIME_FLOOR 20 +#define SCROLL_TIME_START 500 +#define SCROLL_TIME_ADJUST 150 +#define SCROLL_TIME_ADJUSTOFFSET 40 +#define SCROLL_TIME_FLOOR 20 typedef struct scrollInfo_s { int nextScrollTime; @@ -76,22 +76,22 @@ typedef struct scrollInfo_s { } scrollInfo_t; #ifdef UI_BUILD // Defined in ui_main.c, not in the namespace - // Some extern functions hoisted from the middle of this file to get all the non-cgame, - // non-namespace stuff together - extern void UI_SaberDrawBlades( itemDef_t *item, vec3_t origin, vec3_t angles ); +// Some extern functions hoisted from the middle of this file to get all the non-cgame, +// non-namespace stuff together +extern void UI_SaberDrawBlades(itemDef_t *item, vec3_t origin, vec3_t angles); - extern void UI_SaberLoadParms( void ); - extern qboolean ui_saber_parms_parsed; - extern void UI_CacheSaberGlowGraphics( void ); +extern void UI_SaberLoadParms(void); +extern qboolean ui_saber_parms_parsed; +extern void UI_CacheSaberGlowGraphics(void); #endif // qboolean Item_SetFocus(itemDef_t *item, float x, float y); static scrollInfo_t scrollInfo; -static void (*captureFunc) (void *p) = NULL; +static void (*captureFunc)(void *p) = NULL; static void *captureData = NULL; -static itemDef_t *itemCapture = NULL; // item that has the mouse captured ( if any ) +static itemDef_t *itemCapture = NULL; // item that has the mouse captured ( if any ) displayContextDef_t *DC = NULL; @@ -101,8 +101,8 @@ static qboolean g_editingField = qfalse; static itemDef_t *g_bindItem = NULL; static itemDef_t *g_editItem = NULL; -menuDef_t Menus[MAX_MENUS]; // defined menus -int menuCount = 0; // how many +menuDef_t Menus[MAX_MENUS]; // defined menus +int menuCount = 0; // how many menuDef_t *menuStack[MAX_OPEN_MENUS]; int openMenuCount = 0; @@ -120,31 +120,27 @@ qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down); itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu); itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu); static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y); -static void Item_TextScroll_BuildLines ( itemDef_t* item ); -void Menu_SetItemText(const menuDef_t *menu,const char *itemName, const char *text); -extern qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTimeLength ); -extern qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ); - +static void Item_TextScroll_BuildLines(itemDef_t *item); +void Menu_SetItemText(const menuDef_t *menu, const char *itemName, const char *text); +extern qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name, int *runTimeLength); +extern qboolean ItemParse_model_g2anim_go(itemDef_t *item, const char *animName); #ifdef _CGAME -#define MEM_POOL_SIZE (128 * 1024) +#define MEM_POOL_SIZE (128 * 1024) #else -#define MEM_POOL_SIZE (4 * 1024 * 1024) +#define MEM_POOL_SIZE (4 * 1024 * 1024) #endif static char memoryPool[MEM_POOL_SIZE]; static int allocPoint; static qboolean outOfMemory; -typedef struct itemFlagsDef_s { +typedef struct itemFlagsDef_s { const char *string; int value; } itemFlagsDef_t; -itemFlagsDef_t itemFlags[] = { - { "WINDOW_INACTIVE", WINDOW_INACTIVE }, - { NULL, 0 } -}; +itemFlagsDef_t itemFlags[] = {{"WINDOW_INACTIVE", WINDOW_INACTIVE}, {NULL, 0}}; extern int MenuFontToHandle(int iMenuFont); @@ -153,10 +149,10 @@ extern int MenuFontToHandle(int iMenuFont); UI_Alloc =============== */ -void *UI_Alloc( int size ) { - char *p; +void *UI_Alloc(int size) { + char *p; - if ( allocPoint + size > MEM_POOL_SIZE ) { + if (allocPoint + size > MEM_POOL_SIZE) { outOfMemory = qtrue; if (DC->Print) { DC->Print("UI_Alloc: Failure. Out of memory!\n"); @@ -166,7 +162,7 @@ void *UI_Alloc( int size ) { p = &memoryPool[allocPoint]; - allocPoint += ( size + 15 ) & ~15; + allocPoint += (size + 15) & ~15; return p; } @@ -176,14 +172,12 @@ void *UI_Alloc( int size ) { UI_InitMemory =============== */ -void UI_InitMemory( void ) { +void UI_InitMemory(void) { allocPoint = 0; outOfMemory = qfalse; } -qboolean UI_OutOfMemory( void ) { - return outOfMemory; -} +qboolean UI_OutOfMemory(void) { return outOfMemory; } #define HASH_TABLE_SIZE 2048 /* @@ -192,18 +186,18 @@ return a hash value for the string ================ */ static unsigned hashForString(const char *str) { - int i; - unsigned hash; - char letter; + int i; + unsigned hash; + char letter; hash = 0; i = 0; while (str[i] != '\0') { letter = tolower((unsigned char)str[i]); - hash+=(unsigned)(letter)*(i+119); + hash += (unsigned)(letter) * (i + 119); i++; } - hash &= (HASH_TABLE_SIZE-1); + hash &= (HASH_TABLE_SIZE - 1); return hash; } @@ -218,7 +212,6 @@ static char strPool[STRING_POOL_SIZE]; static int strHandleCount = 0; static stringDef_t *strHandle[HASH_TABLE_SIZE]; - const char *String_Alloc(const char *p) { int len; unsigned hash; @@ -251,12 +244,11 @@ const char *String_Alloc(const char *p) { str = strHandle[hash]; last = str; - while (last && last->next) - { + while (last && last->next) { last = last->next; } - str = (stringDef_t *) UI_Alloc(sizeof(stringDef_t)); + str = (stringDef_t *)UI_Alloc(sizeof(stringDef_t)); str->next = NULL; str->str = &strPool[ph]; if (last) { @@ -267,8 +259,8 @@ const char *String_Alloc(const char *p) { return &strPool[ph]; } - //Increase STRING_POOL_SIZE. - Com_Printf( S_COLOR_RED, "String pool has been exhausted.\n" ); + // Increase STRING_POOL_SIZE. + Com_Printf(S_COLOR_RED, "String pool has been exhausted.\n"); return NULL; } @@ -343,9 +335,9 @@ void PC_SourceError(int handle, char *format, ...) { va_list argptr; static char string[4096]; - va_start (argptr, format); - Q_vsnprintf (string, sizeof( string ), format, argptr); - va_end (argptr); + va_start(argptr, format); + Q_vsnprintf(string, sizeof(string), format, argptr); + va_end(argptr); filename[0] = '\0'; line = 0; @@ -359,14 +351,12 @@ void PC_SourceError(int handle, char *format, ...) { LerpColor ================= */ -void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t) -{ +void LerpColor(vec4_t a, vec4_t b, vec4_t c, float t) { int i; // lerp and clamp each component - for (i=0; i<4; i++) - { - c[i] = a[i] + t*(b[i]-a[i]); + for (i = 0; i < 4; i++) { + c[i] = a[i] + t * (b[i] - a[i]); if (c[i] < 0) c[i] = 0; else if (c[i] > 1.0) @@ -380,7 +370,7 @@ Float_Parse ================= */ qboolean Float_Parse(char **p, float *f) { - char *token; + char *token; token = COM_ParseExt((const char **)p, qfalse); if (token && token[0] != 0) { *f = atof(token); @@ -399,11 +389,11 @@ qboolean PC_Float_Parse(int handle, float *f) { pc_token_t token; int negative = qfalse; - if ( !trap->PC_ReadToken( handle, &token ) ) + if (!trap->PC_ReadToken(handle, &token)) return qfalse; - if ( token.string[0] == '-' ) { - if ( !trap->PC_ReadToken( handle, &token ) ) + if (token.string[0] == '-') { + if (!trap->PC_ReadToken(handle, &token)) return qfalse; negative = qtrue; } @@ -460,7 +450,7 @@ Int_Parse ================= */ qboolean Int_Parse(char **p, int *i) { - char *token; + char *token; token = COM_ParseExt((const char **)p, qfalse); if (token && token[0] != 0) { @@ -493,7 +483,7 @@ qboolean PC_Int_Parse(int handle, int *i) { } *i = token.intvalue; if (negative) - *i = - *i; + *i = -*i; return qtrue; } @@ -544,7 +534,7 @@ qboolean String_Parse(char **p, const char **out) { token = COM_ParseExt((const char **)p, qfalse); if (token && token[0] != 0) { *(out) = String_Alloc(token); - return *(out)!=NULL; + return *(out) != NULL; } return qfalse; } @@ -554,23 +544,18 @@ qboolean String_Parse(char **p, const char **out) { PC_String_Parse ================= */ -qboolean PC_String_Parse(int handle, const char **out) -{ - static char* squiggy = "}"; - pc_token_t token; +qboolean PC_String_Parse(int handle, const char **out) { + static char *squiggy = "}"; + pc_token_t token; - if (!trap->PC_ReadToken(handle, &token)) - { + if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } // Save some memory by not return the end squiggy as an allocated string - if ( !Q_stricmp ( token.string, "}" ) ) - { + if (!Q_stricmp(token.string, "}")) { *(out) = squiggy; - } - else - { + } else { *(out) = String_Alloc(token.string); } return qtrue; @@ -592,10 +577,10 @@ qboolean PC_Script_Parse(int handle, const char **out) { if (!trap->PC_ReadToken(handle, &token)) return qfalse; if (Q_stricmp(token.string, "{") != 0) { - return qfalse; + return qfalse; } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) return qfalse; @@ -624,17 +609,15 @@ Init_Display Initializes the display with a structure to all the drawing routines ================== */ -void Init_Display(displayContextDef_t *dc) { - DC = dc; -} +void Init_Display(displayContextDef_t *dc) { DC = dc; } // type and style painting void GradientBar_Paint(rectDef_t *rect, vec4_t color) { // gradient bar takes two paints - DC->setColor( color ); + DC->setColor(color); DC->drawHandlePic(rect->x, rect->y, rect->w, rect->h, DC->Assets.gradientBar); - DC->setColor( NULL ); + DC->setColor(NULL); } /* @@ -653,19 +636,18 @@ void Window_Init(windowDef_t *w) { } void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboolean bFlags, float fadeAmount) { - if ( *flags & ( WINDOW_FADINGOUT | WINDOW_FADINGIN ) ) { - if ( DC->realTime > *nextTime ) { + if (*flags & (WINDOW_FADINGOUT | WINDOW_FADINGIN)) { + if (DC->realTime > *nextTime) { *nextTime = DC->realTime + offsetTime; - if ( *flags & WINDOW_FADINGOUT ) { + if (*flags & WINDOW_FADINGOUT) { *f -= fadeAmount; - if ( bFlags && *f <= 0.0 ) - *flags &= ~( WINDOW_FADINGOUT | WINDOW_VISIBLE ); - } - else { + if (bFlags && *f <= 0.0) + *flags &= ~(WINDOW_FADINGOUT | WINDOW_VISIBLE); + } else { *f += fadeAmount; - if ( *f >= clamp ) { + if (*f >= clamp) { *f = clamp; - if ( bFlags ) + if (bFlags) *flags &= ~WINDOW_FADINGIN; } } @@ -673,113 +655,102 @@ void Fade(int *flags, float *f, float clamp, int *nextTime, int offsetTime, qboo } } -void Window_Paint(windowDef_t *w, float fadeAmount, float fadeClamp, float fadeCycle) -{ - //float bordersize = 0; +void Window_Paint(windowDef_t *w, float fadeAmount, float fadeClamp, float fadeCycle) { + // float bordersize = 0; vec4_t color; rectDef_t fillRect; - if ( w == NULL ) + if (w == NULL) return; - if ( debugMode ) { + if (debugMode) { color[0] = color[1] = color[2] = color[3] = 1; DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, 1, color); } - if ( w->style == 0 && w->border == 0 ) + if (w->style == 0 && w->border == 0) return; fillRect = w->rect; - if ( w->border != 0 ) { + if (w->border != 0) { fillRect.x += w->borderSize; fillRect.y += w->borderSize; fillRect.w -= w->borderSize + 1; fillRect.h -= w->borderSize + 1; } - if ( w->style == WINDOW_STYLE_FILLED ) { + if (w->style == WINDOW_STYLE_FILLED) { // box, but possible a shader that needs filled - if ( w->background ) { - Fade( &w->flags, &w->backColor[3], fadeClamp, &w->nextTime, fadeCycle, qtrue, fadeAmount ); - DC->setColor( w->backColor ); - DC->drawHandlePic( fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background ); - DC->setColor( NULL ); - } - else { - DC->fillRect( fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->backColor ); + if (w->background) { + Fade(&w->flags, &w->backColor[3], fadeClamp, &w->nextTime, fadeCycle, qtrue, fadeAmount); + DC->setColor(w->backColor); + DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background); + DC->setColor(NULL); + } else { + DC->fillRect(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->backColor); } - } - else if ( w->style == WINDOW_STYLE_GRADIENT ) { + } else if (w->style == WINDOW_STYLE_GRADIENT) { GradientBar_Paint(&fillRect, w->backColor); - } - else if ( w->style == WINDOW_STYLE_SHADER ) { + } else if (w->style == WINDOW_STYLE_SHADER) { #ifndef _CGAME - if ( w->flags & WINDOW_PLAYERCOLOR ) { - vec4_t color; - color[0] = ui_char_color_red.integer/255.0f; - color[1] = ui_char_color_green.integer/255.0f; - color[2] = ui_char_color_blue.integer/255.0f; + if (w->flags & WINDOW_PLAYERCOLOR) { + vec4_t color; + color[0] = ui_char_color_red.integer / 255.0f; + color[1] = ui_char_color_green.integer / 255.0f; + color[2] = ui_char_color_blue.integer / 255.0f; color[3] = 1; - DC->setColor( color ); + DC->setColor(color); } #endif // - if ( w->flags & WINDOW_FORECOLORSET ) + if (w->flags & WINDOW_FORECOLORSET) DC->setColor(w->foreColor); - DC->drawHandlePic( fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background ); - DC->setColor( NULL ); - } - else if ( w->style == WINDOW_STYLE_TEAMCOLOR ) { - if ( DC->getTeamColor ) { - DC->getTeamColor( &color ); - DC->fillRect( fillRect.x, fillRect.y, fillRect.w, fillRect.h, color ); - } - } - else if ( w->style == WINDOW_STYLE_CINEMATIC ) { - if ( w->cinematic == -1 ) { - w->cinematic = DC->playCinematic( w->cinematicName, fillRect.x, fillRect.y, fillRect.w, fillRect.h ); - if ( w->cinematic == -1 ) + DC->drawHandlePic(fillRect.x, fillRect.y, fillRect.w, fillRect.h, w->background); + DC->setColor(NULL); + } else if (w->style == WINDOW_STYLE_TEAMCOLOR) { + if (DC->getTeamColor) { + DC->getTeamColor(&color); + DC->fillRect(fillRect.x, fillRect.y, fillRect.w, fillRect.h, color); + } + } else if (w->style == WINDOW_STYLE_CINEMATIC) { + if (w->cinematic == -1) { + w->cinematic = DC->playCinematic(w->cinematicName, fillRect.x, fillRect.y, fillRect.w, fillRect.h); + if (w->cinematic == -1) w->cinematic = -2; } - if ( w->cinematic >= 0 ) { - DC->runCinematicFrame( w->cinematic ); - DC->drawCinematic( w->cinematic, fillRect.x, fillRect.y, fillRect.w, fillRect.h ); + if (w->cinematic >= 0) { + DC->runCinematicFrame(w->cinematic); + DC->drawCinematic(w->cinematic, fillRect.x, fillRect.y, fillRect.w, fillRect.h); } } - if ( w->border == WINDOW_BORDER_FULL ) { + if (w->border == WINDOW_BORDER_FULL) { // full // HACK HACK HACK - if ( w->style == WINDOW_STYLE_TEAMCOLOR ) { - if ( color[0] > 0 ) { + if (w->style == WINDOW_STYLE_TEAMCOLOR) { + if (color[0] > 0) { // red color[0] = 1; color[1] = color[2] = .5; - } - else { + } else { color[2] = 1; color[0] = color[1] = .5; } color[3] = 1; - DC->drawRect( w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, color ); - } - else - DC->drawRect( w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, w->borderColor ); - } - else if (w->border == WINDOW_BORDER_HORZ) { + DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, color); + } else + DC->drawRect(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize, w->borderColor); + } else if (w->border == WINDOW_BORDER_HORZ) { // top/bottom - DC->setColor( w->borderColor ); - DC->drawTopBottom( w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize ); - DC->setColor( NULL ); - } - else if (w->border == WINDOW_BORDER_VERT) { + DC->setColor(w->borderColor); + DC->drawTopBottom(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize); + DC->setColor(NULL); + } else if (w->border == WINDOW_BORDER_VERT) { // left right - DC->setColor( w->borderColor ); - DC->drawSides( w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize ); - DC->setColor( NULL ); - } - else if ( w->border == WINDOW_BORDER_KCGRADIENT ) { + DC->setColor(w->borderColor); + DC->drawSides(w->rect.x, w->rect.y, w->rect.w, w->rect.h, w->borderSize); + DC->setColor(NULL); + } else if (w->border == WINDOW_BORDER_KCGRADIENT) { // this is just two gradient bars along each horz edge rectDef_t r = w->rect; r.h = w->borderSize; @@ -789,8 +760,7 @@ void Window_Paint(windowDef_t *w, float fadeAmount, float fadeClamp, float fadeC } } -void Item_SetScreenCoords(itemDef_t *item, float x, float y) -{ +void Item_SetScreenCoords(itemDef_t *item, float x, float y) { if (item == NULL) return; @@ -808,32 +778,31 @@ void Item_SetScreenCoords(itemDef_t *item, float x, float y) item->textRect.w = 0; item->textRect.h = 0; - if ( item->type == ITEM_TYPE_TEXTSCROLL ) { + if (item->type == ITEM_TYPE_TEXTSCROLL) { textScrollDef_t *scrollPtr = item->typeData.textscroll; - if ( scrollPtr ) { + if (scrollPtr) { scrollPtr->startPos = 0; scrollPtr->endPos = 0; } - Item_TextScroll_BuildLines ( item ); + Item_TextScroll_BuildLines(item); } } // FIXME: consolidate this with nearby stuff -void Item_UpdatePosition(itemDef_t *item) -{ +void Item_UpdatePosition(itemDef_t *item) { float x, y; menuDef_t *menu; if (item == NULL || item->parent == NULL) return; - menu = (menuDef_t *) item->parent; + menu = (menuDef_t *)item->parent; x = menu->window.rect.x; y = menu->window.rect.y; - if ( menu->window.border != 0 ) { + if (menu->window.border != 0) { x += menu->window.borderSize; y += menu->window.borderSize; } @@ -852,55 +821,53 @@ void Menu_UpdatePosition(menuDef_t *menu) { x = menu->window.rect.x; y = menu->window.rect.y; - if ( menu->window.border != 0 ) { + if (menu->window.border != 0) { x += menu->window.borderSize; y += menu->window.borderSize; } - for ( i=0; iitemCount; i++ ) { - Item_SetScreenCoords( menu->items[i], x, y ); + for (i = 0; i < menu->itemCount; i++) { + Item_SetScreenCoords(menu->items[i], x, y); } } void Menu_PostParse(menuDef_t *menu) { - if ( menu == NULL ) + if (menu == NULL) return; - if ( menu->fullScreen ) { + if (menu->fullScreen) { menu->window.rect.x = 0; menu->window.rect.y = 0; menu->window.rect.w = 640; menu->window.rect.h = 480; } - Menu_UpdatePosition( menu ); + Menu_UpdatePosition(menu); } itemDef_t *Menu_ClearFocus(menuDef_t *menu) { int i; itemDef_t *ret = NULL; - if ( menu == NULL ) + if (menu == NULL) return NULL; - for ( i=0; iitemCount; i++ ) { - if ( menu->items[i]->window.flags & WINDOW_HASFOCUS ) + for (i = 0; i < menu->itemCount; i++) { + if (menu->items[i]->window.flags & WINDOW_HASFOCUS) ret = menu->items[i]; menu->items[i]->window.flags &= ~WINDOW_HASFOCUS; - if ( menu->items[i]->leaveFocus ) - Item_RunScript( menu->items[i], menu->items[i]->leaveFocus ); + if (menu->items[i]->leaveFocus) + Item_RunScript(menu->items[i], menu->items[i]->leaveFocus); } return ret; } -qboolean IsVisible(int flags) { - return (flags & WINDOW_VISIBLE && !(flags & WINDOW_FADINGOUT)); -} +qboolean IsVisible(int flags) { return (flags & WINDOW_VISIBLE && !(flags & WINDOW_FADINGOUT)); } qboolean Rect_ContainsPoint(rectDef_t *rect, float x, float y) { - if ( rect ) { - if ( x > rect->x && x < rect->x + rect->w && y > rect->y && y < rect->y + rect->h ) + if (rect) { + if (x > rect->x && x < rect->x + rect->w && y > rect->y && y < rect->y + rect->h) return qtrue; } return qfalse; @@ -910,13 +877,13 @@ int Menu_ItemsMatchingGroup(menuDef_t *menu, const char *name) { int i; int count = 0; - for ( i=0; iitemCount; i++ ) { - if ( !VALIDSTRING( menu->items[i]->window.name ) && !VALIDSTRING( menu->items[i]->window.group ) ) { - Com_Printf( S_COLOR_YELLOW "WARNING: item has neither name or group\n" ); + for (i = 0; i < menu->itemCount; i++) { + if (!VALIDSTRING(menu->items[i]->window.name) && !VALIDSTRING(menu->items[i]->window.group)) { + Com_Printf(S_COLOR_YELLOW "WARNING: item has neither name or group\n"); continue; } - if ( !Q_stricmp( menu->items[i]->window.name, name ) || ( VALIDSTRING( menu->items[i]->window.group ) && !Q_stricmp( menu->items[i]->window.group, name ) ) ) + if (!Q_stricmp(menu->items[i]->window.name, name) || (VALIDSTRING(menu->items[i]->window.group) && !Q_stricmp(menu->items[i]->window.group, name))) count++; } @@ -937,38 +904,28 @@ itemDef_t *Menu_GetMatchingItemByNumber(menuDef_t *menu, int index, const char * return NULL; } -qboolean Script_SetColor ( itemDef_t *item, char **args ) -{ +qboolean Script_SetColor(itemDef_t *item, char **args) { const char *name; int i; float f; vec4_t *out; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { out = NULL; - if (Q_stricmp(name, "backcolor") == 0) - { + if (Q_stricmp(name, "backcolor") == 0) { out = &item->window.backColor; item->window.flags |= WINDOW_BACKCOLORSET; - } - else if (Q_stricmp(name, "forecolor") == 0) - { + } else if (Q_stricmp(name, "forecolor") == 0) { out = &item->window.foreColor; item->window.flags |= WINDOW_FORECOLORSET; - } - else if (Q_stricmp(name, "bordercolor") == 0) - { + } else if (Q_stricmp(name, "bordercolor") == 0) { out = &item->window.borderColor; } - if (out) - { - for (i = 0; i < 4; i++) - { - if (!Float_Parse(args, &f)) - { + if (out) { + for (i = 0; i < 4; i++) { + if (!Float_Parse(args, &f)) { return qtrue; } (*out)[i] = f; @@ -979,65 +936,53 @@ qboolean Script_SetColor ( itemDef_t *item, char **args ) return qtrue; } -qboolean Script_SetAsset(itemDef_t *item, char **args) -{ +qboolean Script_SetAsset(itemDef_t *item, char **args) { const char *name; // expecting name to set asset to - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { // check for a model - if (item->type == ITEM_TYPE_MODEL) - { + if (item->type == ITEM_TYPE_MODEL) { } } return qtrue; } -qboolean Script_SetBackground(itemDef_t *item, char **args) -{ +qboolean Script_SetBackground(itemDef_t *item, char **args) { const char *name; // expecting name to set asset to - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { item->window.background = DC->registerShaderNoMip(name); } return qtrue; } -qboolean Script_SetItemRectCvar(itemDef_t *item, char **args) -{ - const char *itemName; - const char *cvarName; - char cvarBuf[1024]; - const char *holdVal; - char *holdBuf; - itemDef_t *item2=0; - menuDef_t *menu; +qboolean Script_SetItemRectCvar(itemDef_t *item, char **args) { + const char *itemName; + const char *cvarName; + char cvarBuf[1024]; + const char *holdVal; + char *holdBuf; + itemDef_t *item2 = 0; + menuDef_t *menu; // expecting item group and cvar to get value from - if (String_Parse(args, &itemName) && String_Parse(args, &cvarName)) - { - item2 = Menu_FindItemByName((menuDef_t *) item->parent, itemName); + if (String_Parse(args, &itemName) && String_Parse(args, &cvarName)) { + item2 = Menu_FindItemByName((menuDef_t *)item->parent, itemName); - if (item2) - { + if (item2) { // get cvar data DC->getCVarString(cvarName, cvarBuf, sizeof(cvarBuf)); holdBuf = cvarBuf; - if (String_Parse(&holdBuf,&holdVal)) - { - menu = (menuDef_t *) item->parent; + if (String_Parse(&holdBuf, &holdVal)) { + menu = (menuDef_t *)item->parent; item2->window.rectClient.x = atof(holdVal) + menu->window.rect.x; - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item2->window.rectClient.y = atof(holdVal) + menu->window.rect.y; - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item2->window.rectClient.w = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item2->window.rectClient.h = atof(holdVal); item2->window.rect.x = item2->window.rectClient.x; @@ -1054,41 +999,36 @@ qboolean Script_SetItemRectCvar(itemDef_t *item, char **args) } // Default values in case things screw up - if (item2) - { + if (item2) { item2->window.rectClient.x = 0; item2->window.rectClient.y = 0; item2->window.rectClient.w = 0; item2->window.rectClient.h = 0; } -// Com_Printf(S_COLOR_YELLOW"WARNING: SetItemRectCvar: problems. Set cvar to 0's\n" ); + // Com_Printf(S_COLOR_YELLOW"WARNING: SetItemRectCvar: problems. Set cvar to 0's\n" ); return qtrue; } -qboolean Script_SetItemBackground(itemDef_t *item, char **args) -{ +qboolean Script_SetItemBackground(itemDef_t *item, char **args) { const char *itemName; const char *name; // expecting name of shader - if (String_Parse(args, &itemName) && String_Parse(args, &name)) - { - Menu_SetItemBackground((menuDef_t *) item->parent, itemName, name); + if (String_Parse(args, &itemName) && String_Parse(args, &name)) { + Menu_SetItemBackground((menuDef_t *)item->parent, itemName, name); } return qtrue; } -qboolean Script_SetItemText(itemDef_t *item, char **args) -{ +qboolean Script_SetItemText(itemDef_t *item, char **args) { const char *itemName; const char *text; // expecting text - if (String_Parse(args, &itemName) && String_Parse(args, &text)) - { - Menu_SetItemText((menuDef_t *) item->parent, itemName, text); + if (String_Parse(args, &itemName) && String_Parse(args, &text)) { + Menu_SetItemText((menuDef_t *)item->parent, itemName, text); } return qtrue; } @@ -1108,23 +1048,19 @@ itemDef_t *Menu_FindItemByName(menuDef_t *menu, const char *p) { return NULL; } -qboolean Script_SetTeamColor(itemDef_t *item, char **args) -{ - if (DC->getTeamColor) - { +qboolean Script_SetTeamColor(itemDef_t *item, char **args) { + if (DC->getTeamColor) { int i; vec4_t color; DC->getTeamColor(&color); - for (i = 0; i < 4; i++) - { + for (i = 0; i < 4; i++) { item->window.backColor[i] = color[i]; } } return qtrue; } -qboolean Script_SetItemColor(itemDef_t *item, char **args) -{ +qboolean Script_SetItemColor(itemDef_t *item, char **args) { const char *itemname; const char *name; vec4_t color; @@ -1132,51 +1068,39 @@ qboolean Script_SetItemColor(itemDef_t *item, char **args) vec4_t *out; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &itemname) && String_Parse(args, &name)) - { - itemDef_t *item2; - int j,count; + if (String_Parse(args, &itemname) && String_Parse(args, &name)) { + itemDef_t *item2; + int j, count; char buff[1024]; // Is is specifying a cvar to get the item name from? - if (itemname[0] == '*') - { + if (itemname[0] == '*') { itemname += 1; - DC->getCVarString(itemname, buff, sizeof(buff)); + DC->getCVarString(itemname, buff, sizeof(buff)); itemname = buff; } - count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, itemname); + count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, itemname); - if (!Color_Parse(args, &color)) - { + if (!Color_Parse(args, &color)) { return qtrue; } - for (j = 0; j < count; j++) - { - item2 = Menu_GetMatchingItemByNumber((menuDef_t *) item->parent, j, itemname); - if (item2 != NULL) - { + for (j = 0; j < count; j++) { + item2 = Menu_GetMatchingItemByNumber((menuDef_t *)item->parent, j, itemname); + if (item2 != NULL) { out = NULL; - if (Q_stricmp(name, "backcolor") == 0) - { + if (Q_stricmp(name, "backcolor") == 0) { out = &item2->window.backColor; - } - else if (Q_stricmp(name, "forecolor") == 0) - { + } else if (Q_stricmp(name, "forecolor") == 0) { out = &item2->window.foreColor; item2->window.flags |= WINDOW_FORECOLORSET; - } - else if (Q_stricmp(name, "bordercolor") == 0) - { + } else if (Q_stricmp(name, "bordercolor") == 0) { out = &item2->window.borderColor; } - if (out) - { - for (i = 0; i < 4; i++) - { + if (out) { + for (i = 0; i < 4; i++) { (*out)[i] = color[i]; } } @@ -1187,54 +1111,44 @@ qboolean Script_SetItemColor(itemDef_t *item, char **args) return qtrue; } -qboolean Script_SetItemColorCvar(itemDef_t *item, char **args) -{ +qboolean Script_SetItemColorCvar(itemDef_t *item, char **args) { const char *itemname; - char *colorCvarName,*holdBuf,*holdVal; + char *colorCvarName, *holdBuf, *holdVal; char cvarBuf[1024]; const char *name; - vec4_t color = { 0.0f }; + vec4_t color = {0.0f}; int i; vec4_t *out; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &itemname) && String_Parse(args, &name)) - { - itemDef_t *item2; - int j,count; + if (String_Parse(args, &itemname) && String_Parse(args, &name)) { + itemDef_t *item2; + int j, count; char buff[1024]; // Is is specifying a cvar to get the item name from? - if (itemname[0] == '*') - { + if (itemname[0] == '*') { itemname += 1; - DC->getCVarString(itemname, buff, sizeof(buff)); + DC->getCVarString(itemname, buff, sizeof(buff)); itemname = buff; } - count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, itemname); + count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, itemname); // Get the cvar with the color - if (!String_Parse(args,(const char **) &colorCvarName)) - { + if (!String_Parse(args, (const char **)&colorCvarName)) { return qtrue; - } - else - { + } else { DC->getCVarString(colorCvarName, cvarBuf, sizeof(cvarBuf)); holdBuf = cvarBuf; - if (String_Parse(&holdBuf,(const char **) &holdVal)) - { + if (String_Parse(&holdBuf, (const char **)&holdVal)) { color[0] = atof(holdVal); - if (String_Parse(&holdBuf,(const char **) &holdVal)) - { + if (String_Parse(&holdBuf, (const char **)&holdVal)) { color[1] = atof(holdVal); - if (String_Parse(&holdBuf,(const char **) &holdVal)) - { + if (String_Parse(&holdBuf, (const char **)&holdVal)) { color[2] = atof(holdVal); - if (String_Parse(&holdBuf,(const char **) &holdVal)) - { + if (String_Parse(&holdBuf, (const char **)&holdVal)) { color[3] = atof(holdVal); } } @@ -1242,30 +1156,21 @@ qboolean Script_SetItemColorCvar(itemDef_t *item, char **args) } } - for (j = 0; j < count; j++) - { - item2 = Menu_GetMatchingItemByNumber((menuDef_t *) item->parent, j, itemname); - if (item2 != NULL) - { + for (j = 0; j < count; j++) { + item2 = Menu_GetMatchingItemByNumber((menuDef_t *)item->parent, j, itemname); + if (item2 != NULL) { out = NULL; - if (Q_stricmp(name, "backcolor") == 0) - { + if (Q_stricmp(name, "backcolor") == 0) { out = &item2->window.backColor; - } - else if (Q_stricmp(name, "forecolor") == 0) - { + } else if (Q_stricmp(name, "forecolor") == 0) { out = &item2->window.foreColor; item2->window.flags |= WINDOW_FORECOLORSET; - } - else if (Q_stricmp(name, "bordercolor") == 0) - { + } else if (Q_stricmp(name, "bordercolor") == 0) { out = &item2->window.borderColor; } - if (out) - { - for (i = 0; i < 4; i++) - { + if (out) { + for (i = 0; i < 4; i++) { (*out)[i] = color[i]; } } @@ -1276,38 +1181,32 @@ qboolean Script_SetItemColorCvar(itemDef_t *item, char **args) return qtrue; } -qboolean Script_SetItemRect(itemDef_t *item, char **args) -{ +qboolean Script_SetItemRect(itemDef_t *item, char **args) { const char *itemname; rectDef_t *out; rectDef_t rect; - menuDef_t *menu; + menuDef_t *menu; // expecting type of color to set and 4 args for the color - if (String_Parse(args, &itemname)) - { + if (String_Parse(args, &itemname)) { itemDef_t *item2; int j; - int count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, itemname); + int count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, itemname); - if (!Rect_Parse(args, &rect)) - { + if (!Rect_Parse(args, &rect)) { return qtrue; } - menu = (menuDef_t *) item->parent; + menu = (menuDef_t *)item->parent; - for (j = 0; j < count; j++) - { + for (j = 0; j < count; j++) { item2 = Menu_GetMatchingItemByNumber(menu, j, itemname); - if (item2 != NULL) - { + if (item2 != NULL) { out = &item2->window.rect; - if (out) - { - item2->window.rect.x = rect.x + menu->window.rect.x; - item2->window.rect.y = rect.y + menu->window.rect.y; + if (out) { + item2->window.rect.x = rect.x + menu->window.rect.x; + item2->window.rect.y = rect.y + menu->window.rect.y; item2->window.rect.w = rect.w; item2->window.rect.h = rect.h; } @@ -1317,23 +1216,17 @@ qboolean Script_SetItemRect(itemDef_t *item, char **args) return qtrue; } -void Menu_ShowGroup (menuDef_t *menu, const char *groupName, qboolean showFlag) -{ +void Menu_ShowGroup(menuDef_t *menu, const char *groupName, qboolean showFlag) { itemDef_t *item; - int count,j; + int count, j; - count = Menu_ItemsMatchingGroup( menu, groupName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( menu, j, groupName); - if (item != NULL) - { - if (showFlag) - { + count = Menu_ItemsMatchingGroup(menu, groupName); + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber(menu, j, groupName); + if (item != NULL) { + if (showFlag) { item->window.flags |= WINDOW_VISIBLE; - } - else - { + } else { item->window.flags &= ~(WINDOW_VISIBLE | WINDOW_HASFOCUS); } } @@ -1396,9 +1289,7 @@ void Menus_ShowByName(const char *p) { } } -void Menus_OpenByName(const char *p) { - Menus_ActivateByName(p); -} +void Menus_OpenByName(const char *p) { Menus_ActivateByName(p); } static void Menu_RunCloseScript(menuDef_t *menu) { if (menu && menu->window.flags & WINDOW_VISIBLE && menu->onClose) { @@ -1408,13 +1299,11 @@ static void Menu_RunCloseScript(menuDef_t *menu) { } } -void Menus_CloseByName ( const char *p ) -{ +void Menus_CloseByName(const char *p) { menuDef_t *menu = Menus_FindByName(p); // If the menu wasnt found just exit - if (menu == NULL) - { + if (menu == NULL) { return; } @@ -1422,12 +1311,10 @@ void Menus_CloseByName ( const char *p ) Menu_RunCloseScript(menu); // If this window had the focus then take it away - if ( menu->window.flags & WINDOW_HASFOCUS ) - { + if (menu->window.flags & WINDOW_HASFOCUS) { // If there is something still in the open menu list then // set it to have focus now - if ( openMenuCount ) - { + if (openMenuCount) { // Subtract one from the open menu count to prepare to // remove the top menu from the list openMenuCount -= 1; @@ -1446,15 +1333,13 @@ void Menus_CloseByName ( const char *p ) int FPMessageTime = 0; -void Menus_CloseAll() -{ +void Menus_CloseAll() { int i; g_waitingForKey = qfalse; - for (i = 0; i < menuCount; i++) - { - Menu_RunCloseScript ( &Menus[i] ); + for (i = 0; i < menuCount; i++) { + Menu_RunCloseScript(&Menus[i]); Menus[i].window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); } @@ -1464,87 +1349,68 @@ void Menus_CloseAll() FPMessageTime = 0; } -qboolean Script_Show(itemDef_t *item, char **args) -{ +qboolean Script_Show(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_ShowItemByName((menuDef_t *) item->parent, name, qtrue); + if (String_Parse(args, &name)) { + Menu_ShowItemByName((menuDef_t *)item->parent, name, qtrue); } return qtrue; } -qboolean Script_Hide(itemDef_t *item, char **args) -{ +qboolean Script_Hide(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_ShowItemByName((menuDef_t *) item->parent, name, qfalse); + if (String_Parse(args, &name)) { + Menu_ShowItemByName((menuDef_t *)item->parent, name, qfalse); } return qtrue; } -qboolean Script_FadeIn(itemDef_t *item, char **args) -{ +qboolean Script_FadeIn(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_FadeItemByName((menuDef_t *) item->parent, name, qfalse); + if (String_Parse(args, &name)) { + Menu_FadeItemByName((menuDef_t *)item->parent, name, qfalse); } return qtrue; } -qboolean Script_FadeOut(itemDef_t *item, char **args) -{ +qboolean Script_FadeOut(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { - Menu_FadeItemByName((menuDef_t *) item->parent, name, qtrue); + if (String_Parse(args, &name)) { + Menu_FadeItemByName((menuDef_t *)item->parent, name, qtrue); } return qtrue; } -qboolean Script_Open(itemDef_t *item, char **args) -{ +qboolean Script_Open(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { Menus_OpenByName(name); } return qtrue; } -qboolean Script_Close(itemDef_t *item, char **args) -{ +qboolean Script_Close(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { - if (Q_stricmp(name, "all") == 0) - { + if (String_Parse(args, &name)) { + if (Q_stricmp(name, "all") == 0) { Menus_CloseAll(); - } - else - { + } else { Menus_CloseByName(name); } } return qtrue; } -void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t *rectFrom, const rectDef_t *rectTo, int time, float amt) -{ +void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t *rectFrom, const rectDef_t *rectTo, int time, float amt) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - for (i = 0; i < count; i++) - { + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if (!rectFrom) - { - rectFrom = &item->window.rect; //if there are more than one of these with the same name, they'll all use the FIRST one's FROM. + if (item != NULL) { + if (!rectFrom) { + rectFrom = &item->window.rect; // if there are more than one of these with the same name, they'll all use the FIRST one's FROM. } item->window.flags |= (WINDOW_INTRANSITION | WINDOW_VISIBLE); item->window.offsetTime = time; @@ -1565,24 +1431,19 @@ void Menu_TransitionItemByName(menuDef_t *menu, const char *p, const rectDef_t * Menu_Transition3ItemByName ================= */ -//JLF +// JLF #define _TRANS3 #ifdef _TRANS3 -void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx, const float miny, const float minz, - const float maxx, const float maxy, const float maxz, const float fovtx, const float fovty, - const int time, const float amt) -{ +void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx, const float miny, const float minz, const float maxx, const float maxy, + const float maxz, const float fovtx, const float fovty, const int time, const float amt) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); - modelDef_t * modelptr; - for (i = 0; i < count; i++) - { + modelDef_t *modelptr; + for (i = 0; i < count; i++) { item = Menu_GetMatchingItemByNumber(menu, i, p); - if (item != NULL) - { - if ( item->type == ITEM_TYPE_MODEL ) - { + if (item != NULL) { + if (item->type == ITEM_TYPE_MODEL) { modelptr = item->typeData.model; item->window.flags |= (WINDOW_INTRANSITIONMODEL | WINDOW_VISIBLE); @@ -1592,14 +1453,14 @@ void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); VectorSet(modelptr->g2mins2, minx, miny, minz); -// //modelptr->g2maxs2.x= maxx; -// modelptr->g2maxs2.y= maxy; -// modelptr->g2maxs2.z= maxz; -// modelptr->g2mins2.x= minx; -// modelptr->g2mins2.y= miny; -// modelptr->g2mins2.z= minz; + // //modelptr->g2maxs2.x= maxx; + // modelptr->g2maxs2.y= maxy; + // modelptr->g2maxs2.z= maxz; + // modelptr->g2mins2.x= minx; + // modelptr->g2mins2.y= miny; + // modelptr->g2mins2.z= minz; -// VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); + // VectorSet(modelptr->g2maxs2, maxx, maxy, maxz); modelptr->g2maxsEffect[0] = fabs(modelptr->g2maxs2[0] - modelptr->g2maxs[0]) / amt; modelptr->g2maxsEffect[1] = fabs(modelptr->g2maxs2[1] - modelptr->g2maxs[1]) / amt; @@ -1609,7 +1470,6 @@ void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx modelptr->g2minsEffect[1] = fabs(modelptr->g2mins2[1] - modelptr->g2mins[1]) / amt; modelptr->g2minsEffect[2] = fabs(modelptr->g2mins2[2] - modelptr->g2mins[2]) / amt; - modelptr->fov_Effectx = fabs(modelptr->fov_x2 - modelptr->fov_x) / amt; modelptr->fov_Effecty = fabs(modelptr->fov_y2 - modelptr->fov_y) / amt; } @@ -1619,10 +1479,10 @@ void Menu_Transition3ItemByName(menuDef_t *menu, const char *p, const float minx #endif -#define MAX_DEFERRED_SCRIPT 2048 +#define MAX_DEFERRED_SCRIPT 2048 -char ui_deferredScript [ MAX_DEFERRED_SCRIPT ]; -itemDef_t* ui_deferredScriptItem = NULL; +char ui_deferredScript[MAX_DEFERRED_SCRIPT]; +itemDef_t *ui_deferredScriptItem = NULL; /* ================= @@ -1632,16 +1492,14 @@ Defers the rest of the script based on the defer condition. The deferred portion of the script can later be run with the "rundeferred" ================= */ -qboolean Script_Defer ( itemDef_t* item, char **args ) -{ +qboolean Script_Defer(itemDef_t *item, char **args) { // Should the script be deferred? - if ( DC->deferScript ( (char**)args ) ) - { + if (DC->deferScript((char **)args)) { // Need the item the script was being run on ui_deferredScriptItem = item; // Save the rest of the script - Q_strncpyz ( ui_deferredScript, *args, MAX_DEFERRED_SCRIPT ); + Q_strncpyz(ui_deferredScript, *args, MAX_DEFERRED_SCRIPT); // No more running return qfalse; @@ -1659,40 +1517,34 @@ Runs the last deferred script, there can only be one script deferred at a time so be careful of recursion ================= */ -qboolean Script_RunDeferred ( itemDef_t* item, char **args ) -{ +qboolean Script_RunDeferred(itemDef_t *item, char **args) { // Make sure there is something to run. - if ( !ui_deferredScript[0] || !ui_deferredScriptItem ) - { + if (!ui_deferredScript[0] || !ui_deferredScriptItem) { return qtrue; } // Run the deferred script now - Item_RunScript ( ui_deferredScriptItem, ui_deferredScript ); + Item_RunScript(ui_deferredScriptItem, ui_deferredScript); return qtrue; } -qboolean Script_Transition(itemDef_t *item, char **args) -{ +qboolean Script_Transition(itemDef_t *item, char **args) { const char *name; rectDef_t rectFrom, rectTo; int time; float amt; - if (String_Parse(args, &name)) - { - if ( Rect_Parse(args, &rectFrom) && Rect_Parse(args, &rectTo) && Int_Parse(args, &time) && Float_Parse(args, &amt)) - { - Menu_TransitionItemByName((menuDef_t *) item->parent, name, &rectFrom, &rectTo, time, amt); + if (String_Parse(args, &name)) { + if (Rect_Parse(args, &rectFrom) && Rect_Parse(args, &rectTo) && Int_Parse(args, &time) && Float_Parse(args, &amt)) { + Menu_TransitionItemByName((menuDef_t *)item->parent, name, &rectFrom, &rectTo, time, amt); } } return qtrue; } -void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, float cx, float cy, int time) -{ +void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, float cx, float cy, int time) { itemDef_t *item; int i; int count = Menu_ItemsMatchingGroup(menu, p); @@ -1710,18 +1562,15 @@ void Menu_OrbitItemByName(menuDef_t *menu, const char *p, float x, float y, floa } } -void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) -{ - int j,count; +void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) { + int j, count; itemDef_t *itemFound; count = Menu_ItemsMatchingGroup(menu, name); // Loop through all items that have this name - for (j = 0; j < count; j++) - { - itemFound = Menu_GetMatchingItemByNumber( menu, j, name); - if (itemFound != NULL) - { + for (j = 0; j < count; j++) { + itemFound = Menu_GetMatchingItemByNumber(menu, j, name); + if (itemFound != NULL) { itemFound->disabled = disableFlag; // Just in case it had focus itemFound->window.flags &= ~WINDOW_MOUSEOVER; @@ -1730,28 +1579,24 @@ void Menu_ItemDisable(menuDef_t *menu, const char *name, qboolean disableFlag) } // Set item disable flags -qboolean Script_Disable(itemDef_t *item, char **args) -{ +qboolean Script_Disable(itemDef_t *item, char **args) { char *name; - int value; + int value; menuDef_t *menu; - if (String_Parse(args, (const char **)&name)) - { + if (String_Parse(args, (const char **)&name)) { char buff[1024]; // Is is specifying a cvar to get the item name from? - if (name[0] == '*') - { + if (name[0] == '*') { name += 1; - DC->getCVarString(name, buff, sizeof(buff)); + DC->getCVarString(name, buff, sizeof(buff)); name = buff; } - if ( Int_Parse(args, &value)) - { + if (Int_Parse(args, &value)) { menu = Menu_GetFocused(); - Menu_ItemDisable(menu, name,value); + Menu_ItemDisable(menu, name, value); } } @@ -1759,42 +1604,36 @@ qboolean Script_Disable(itemDef_t *item, char **args) } // Scale the given item instantly. -qboolean Script_Scale(itemDef_t *item, char **args) -{ +qboolean Script_Scale(itemDef_t *item, char **args) { const char *name; float scale; - int j,count; + int j, count; itemDef_t *itemFound; rectDef_t rectTo; - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { char buff[1024]; // Is is specifying a cvar to get the item name from? - if (name[0] == '*') - { + if (name[0] == '*') { name += 1; - DC->getCVarString(name, buff, sizeof(buff)); + DC->getCVarString(name, buff, sizeof(buff)); name = buff; } - count = Menu_ItemsMatchingGroup((menuDef_t *) item->parent, name); + count = Menu_ItemsMatchingGroup((menuDef_t *)item->parent, name); - if ( Float_Parse(args, &scale)) - { - for (j = 0; j < count; j++) - { - itemFound = Menu_GetMatchingItemByNumber( (menuDef_t *) item->parent, j, name); - if (itemFound != NULL) - { + if (Float_Parse(args, &scale)) { + for (j = 0; j < count; j++) { + itemFound = Menu_GetMatchingItemByNumber((menuDef_t *)item->parent, j, name); + if (itemFound != NULL) { rectTo.h = itemFound->window.rect.h * scale; rectTo.w = itemFound->window.rect.w * scale; - rectTo.x = itemFound->window.rect.x + ((itemFound->window.rect.h - rectTo.h)/2); - rectTo.y = itemFound->window.rect.y + ((itemFound->window.rect.w - rectTo.w)/2); + rectTo.x = itemFound->window.rect.x + ((itemFound->window.rect.h - rectTo.h) / 2); + rectTo.y = itemFound->window.rect.y + ((itemFound->window.rect.w - rectTo.w) / 2); - Menu_TransitionItemByName((menuDef_t *) item->parent, name, 0, &rectTo, 1, 1); + Menu_TransitionItemByName((menuDef_t *)item->parent, name, 0, &rectTo, 1, 1); } } } @@ -1803,40 +1642,35 @@ qboolean Script_Scale(itemDef_t *item, char **args) return qtrue; } -qboolean Script_Orbit(itemDef_t *item, char **args) -{ +qboolean Script_Orbit(itemDef_t *item, char **args) { const char *name; float cx, cy, x, y; int time; - if (String_Parse(args, &name)) - { - if ( Float_Parse(args, &x) && Float_Parse(args, &y) && Float_Parse(args, &cx) && Float_Parse(args, &cy) && Int_Parse(args, &time) ) - { - Menu_OrbitItemByName((menuDef_t *) item->parent, name, x, y, cx, cy, time); + if (String_Parse(args, &name)) { + if (Float_Parse(args, &x) && Float_Parse(args, &y) && Float_Parse(args, &cx) && Float_Parse(args, &cy) && Int_Parse(args, &time)) { + Menu_OrbitItemByName((menuDef_t *)item->parent, name, x, y, cx, cy, time); } } return qtrue; } -qboolean Script_SetFocus(itemDef_t *item, char **args) -{ +qboolean Script_SetFocus(itemDef_t *item, char **args) { const char *name; itemDef_t *focusItem; if (String_Parse(args, &name)) { - focusItem = Menu_FindItemByName((menuDef_t *) item->parent, name); + focusItem = Menu_FindItemByName((menuDef_t *)item->parent, name); if (focusItem && !(focusItem->window.flags & WINDOW_DECORATION) && !(focusItem->window.flags & WINDOW_HASFOCUS)) { - Menu_ClearFocus((menuDef_t *) item->parent); + Menu_ClearFocus((menuDef_t *)item->parent); focusItem->window.flags |= WINDOW_HASFOCUS; - if (focusItem->onFocus) { Item_RunScript(focusItem, focusItem->onFocus); } if (DC->Assets.itemFocusSound) { - DC->startLocalSound( DC->Assets.itemFocusSound, CHAN_LOCAL_SOUND ); + DC->startLocalSound(DC->Assets.itemFocusSound, CHAN_LOCAL_SOUND); } } } @@ -1844,11 +1678,9 @@ qboolean Script_SetFocus(itemDef_t *item, char **args) return qtrue; } -qboolean Script_SetPlayerModel(itemDef_t *item, char **args) -{ +qboolean Script_SetPlayerModel(itemDef_t *item, char **args) { const char *name; - if (String_Parse(args, &name)) - { + if (String_Parse(args, &name)) { DC->setCVar("model", name); } @@ -1860,16 +1692,11 @@ qboolean Script_SetPlayerModel(itemDef_t *item, char **args) ParseRect ================= */ -qboolean ParseRect(const char **p, rectDef_t *r) -{ - if (!COM_ParseFloat(p, &r->x)) - { - if (!COM_ParseFloat(p, &r->y)) - { - if (!COM_ParseFloat(p, &r->w)) - { - if (!COM_ParseFloat(p, &r->h)) - { +qboolean ParseRect(const char **p, rectDef_t *r) { + if (!COM_ParseFloat(p, &r->x)) { + if (!COM_ParseFloat(p, &r->y)) { + if (!COM_ParseFloat(p, &r->w)) { + if (!COM_ParseFloat(p, &r->h)) { return qtrue; } } @@ -1886,22 +1713,17 @@ uses current origin instead of specifing a starting origin transition2 lfvscr 25 0 202 264 20 25 ================= */ -qboolean Script_Transition2(itemDef_t *item, char **args) -{ +qboolean Script_Transition2(itemDef_t *item, char **args) { const char *name; rectDef_t rectTo; int time; float amt; - if (String_Parse(args, &name)) - { - if ( ParseRect((const char **) args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat((const char **) args, &amt)) - { - Menu_TransitionItemByName((menuDef_t *) item->parent, name, 0, &rectTo, time, amt); - } - else - { - Com_Printf(S_COLOR_YELLOW"WARNING: Script_Transition2: error parsing '%s'\n", name ); + if (String_Parse(args, &name)) { + if (ParseRect((const char **)args, &rectTo) && Int_Parse(args, &time) && !COM_ParseFloat((const char **)args, &amt)) { + Menu_TransitionItemByName((menuDef_t *)item->parent, name, 0, &rectTo, time, amt); + } else { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name); } } @@ -1921,53 +1743,37 @@ uses current origin instead of specifing a starting origin transition3 lfvscr (min extent) (max extent) (fovx,y) 20 25 ================= */ -qboolean Script_Transition3(itemDef_t *item, char **args) -{ +qboolean Script_Transition3(itemDef_t *item, char **args) { const char *name = NULL, *value = NULL; float minx, miny, minz, maxx, maxy, maxz, fovtx, fovty; int time; float amt; - if (String_Parse(args, &name)) - { - if (String_Parse( args, &value)) - { + if (String_Parse(args, &name)) { + if (String_Parse(args, &value)) { minx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { miny = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { minz = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxy = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { maxz = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { fovtx = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { fovty = atof(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { time = atoi(value); - if (String_Parse( args, &value)) - { + if (String_Parse(args, &value)) { amt = atof(value); - //set up the variables - Menu_Transition3ItemByName((menuDef_t *) item->parent, - name, - minx, miny, minz, - maxx, maxy, maxz, - fovtx, fovty, - time, amt); + // set up the variables + Menu_Transition3ItemByName((menuDef_t *)item->parent, name, minx, miny, minz, maxx, maxy, maxz, fovtx, fovty, + time, amt); return qtrue; } @@ -1981,18 +1787,16 @@ qboolean Script_Transition3(itemDef_t *item, char **args) } } } - if ( name ) { - Com_Printf( S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name ); + if (name) { + Com_Printf(S_COLOR_YELLOW "WARNING: Script_Transition2: error parsing '%s'\n", name); } return qtrue; } #endif -qboolean Script_SetCvar(itemDef_t *item, char **args) -{ +qboolean Script_SetCvar(itemDef_t *item, char **args) { const char *cvar, *val; - if (String_Parse(args, &cvar) && String_Parse(args, &val)) - { + if (String_Parse(args, &cvar) && String_Parse(args, &val)) { DC->setCVar(cvar, val); } return qtrue; @@ -2033,119 +1837,104 @@ qboolean Script_playLooped(itemDef_t *item, char **args) { return qtrue; } -commandDef_t commandList[] = -{ - {"fadein", &Script_FadeIn}, // group/name - {"fadeout", &Script_FadeOut}, // group/name - {"show", &Script_Show}, // group/name - {"hide", &Script_Hide}, // group/name - {"setcolor", &Script_SetColor}, // works on this - {"open", &Script_Open}, // nenu - {"close", &Script_Close}, // menu - {"setasset", &Script_SetAsset}, // works on this - {"setbackground", &Script_SetBackground}, // works on this - {"setitemrectcvar", &Script_SetItemRectCvar}, // group/name - {"setitembackground", &Script_SetItemBackground},// group/name - {"setitemtext", &Script_SetItemText}, // group/name - {"setitemcolor", &Script_SetItemColor}, // group/name - {"setitemcolorcvar", &Script_SetItemColorCvar},// group/name - {"setitemrect", &Script_SetItemRect}, // group/name - {"setteamcolor", &Script_SetTeamColor}, // sets this background color to team color - {"setfocus", &Script_SetFocus}, // sets focus - {"setplayermodel", &Script_SetPlayerModel}, // sets model - {"transition", &Script_Transition}, // group/name - {"setcvar", &Script_SetCvar}, // name - {"setcvartocvar", &Script_SetCvarToCvar}, // name - {"exec", &Script_Exec}, // group/name - {"play", &Script_Play}, // group/name - {"playlooped", &Script_playLooped}, // group/name - {"orbit", &Script_Orbit}, // group/name - {"scale", &Script_Scale}, // group/name - {"disable", &Script_Disable}, // group/name - {"defer", &Script_Defer}, // - {"rundeferred", &Script_RunDeferred}, // - {"transition2", &Script_Transition2}, // group/name +commandDef_t commandList[] = { + {"fadein", &Script_FadeIn}, // group/name + {"fadeout", &Script_FadeOut}, // group/name + {"show", &Script_Show}, // group/name + {"hide", &Script_Hide}, // group/name + {"setcolor", &Script_SetColor}, // works on this + {"open", &Script_Open}, // nenu + {"close", &Script_Close}, // menu + {"setasset", &Script_SetAsset}, // works on this + {"setbackground", &Script_SetBackground}, // works on this + {"setitemrectcvar", &Script_SetItemRectCvar}, // group/name + {"setitembackground", &Script_SetItemBackground}, // group/name + {"setitemtext", &Script_SetItemText}, // group/name + {"setitemcolor", &Script_SetItemColor}, // group/name + {"setitemcolorcvar", &Script_SetItemColorCvar}, // group/name + {"setitemrect", &Script_SetItemRect}, // group/name + {"setteamcolor", &Script_SetTeamColor}, // sets this background color to team color + {"setfocus", &Script_SetFocus}, // sets focus + {"setplayermodel", &Script_SetPlayerModel}, // sets model + {"transition", &Script_Transition}, // group/name + {"setcvar", &Script_SetCvar}, // name + {"setcvartocvar", &Script_SetCvarToCvar}, // name + {"exec", &Script_Exec}, // group/name + {"play", &Script_Play}, // group/name + {"playlooped", &Script_playLooped}, // group/name + {"orbit", &Script_Orbit}, // group/name + {"scale", &Script_Scale}, // group/name + {"disable", &Script_Disable}, // group/name + {"defer", &Script_Defer}, // + {"rundeferred", &Script_RunDeferred}, // + {"transition2", &Script_Transition2}, // group/name }; // Set all the items within a given menu, with the given itemName, to the given shader -void Menu_SetItemBackground(const menuDef_t *menu,const char *itemName, const char *background) -{ - itemDef_t *item; - int j, count; +void Menu_SetItemBackground(const menuDef_t *menu, const char *itemName, const char *background) { + itemDef_t *item; + int j, count; - if (!menu) // No menu??? + if (!menu) // No menu??? { return; } - count = Menu_ItemsMatchingGroup( (menuDef_t *) menu, itemName); + count = Menu_ItemsMatchingGroup((menuDef_t *)menu, itemName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( (menuDef_t *) menu, j, itemName); - if (item != NULL) - { + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber((menuDef_t *)menu, j, itemName); + if (item != NULL) { item->window.background = DC->registerShaderNoMip(background); } } } // Set all the items within a given menu, with the given itemName, to the given text -void Menu_SetItemText(const menuDef_t *menu,const char *itemName, const char *text) -{ - itemDef_t *item; - int j, count; +void Menu_SetItemText(const menuDef_t *menu, const char *itemName, const char *text) { + itemDef_t *item; + int j, count; - if (!menu) // No menu??? + if (!menu) // No menu??? { return; } - count = Menu_ItemsMatchingGroup( (menuDef_t *) menu, itemName); + count = Menu_ItemsMatchingGroup((menuDef_t *)menu, itemName); - for (j = 0; j < count; j++) - { - item = Menu_GetMatchingItemByNumber( (menuDef_t *) menu, j, itemName); - if (item != NULL) - { - if (text[0] == '*') - { - item->text = NULL; // Null this out because this would take presidence over cvar text. - item->cvar = text+1; - switch ( item->type ) - { - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_SLIDER: - case ITEM_TYPE_TEXT: - { - if ( item->typeData.edit ) - { - item->typeData.edit->minVal = -1; - item->typeData.edit->maxVal = -1; - item->typeData.edit->defVal = -1; - } - break; + for (j = 0; j < count; j++) { + item = Menu_GetMatchingItemByNumber((menuDef_t *)menu, j, itemName); + if (item != NULL) { + if (text[0] == '*') { + item->text = NULL; // Null this out because this would take presidence over cvar text. + item->cvar = text + 1; + switch (item->type) { + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_SLIDER: + case ITEM_TYPE_TEXT: { + if (item->typeData.edit) { + item->typeData.edit->minVal = -1; + item->typeData.edit->maxVal = -1; + item->typeData.edit->defVal = -1; } - default: - break; + break; } - } - else - { + default: + break; + } + } else { item->text = text; - if ( item->type == ITEM_TYPE_TEXTSCROLL ) - { + if (item->type == ITEM_TYPE_TEXTSCROLL) { textScrollDef_t *scrollPtr = item->typeData.textscroll; - if ( scrollPtr ) - { + if (scrollPtr) { scrollPtr->startPos = 0; scrollPtr->endPos = 0; } - Item_TextScroll_BuildLines ( item ); + Item_TextScroll_BuildLines(item); } } } @@ -2154,42 +1943,34 @@ void Menu_SetItemText(const menuDef_t *menu,const char *itemName, const char *te int scriptCommandCount = sizeof(commandList) / sizeof(commandDef_t); -void Item_RunScript(itemDef_t *item, const char *s) -{ +void Item_RunScript(itemDef_t *item, const char *s) { char script[2048], *p; int i; qboolean bRan; script[0] = 0; - if (item && s && s[0]) - { + if (item && s && s[0]) { Q_strcat(script, 2048, s); p = script; - while (1) - { + while (1) { const char *command; // expect command then arguments, ; ends command, NULL ends script - if (!String_Parse(&p, &command)) - { + if (!String_Parse(&p, &command)) { return; } - if (command[0] == ';' && command[1] == '\0') - { + if (command[0] == ';' && command[1] == '\0') { continue; } bRan = qfalse; - for (i = 0; i < scriptCommandCount; i++) - { - if (Q_stricmp(command, commandList[i].name) == 0) - { + for (i = 0; i < scriptCommandCount; i++) { + if (Q_stricmp(command, commandList[i].name) == 0) { // Allow a script command to stop processing the script - if ( !commandList[i].handler(item, &p) ) - { + if (!commandList[i].handler(item, &p)) { return; } @@ -2199,53 +1980,49 @@ void Item_RunScript(itemDef_t *item, const char *s) } // not in our auto list, pass to handler - if (!bRan) - { + if (!bRan) { DC->runScript(&p); } } } } - qboolean Item_EnableShowViaCvar(itemDef_t *item, int flag) { - char script[2048], *p; - if (item && item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) { + char script[2048], *p; + if (item && item->enableCvar && *item->enableCvar && item->cvarTest && *item->cvarTest) { char buff[2048]; - DC->getCVarString(item->cvarTest, buff, sizeof(buff)); - - Q_strncpyz(script, item->enableCvar, 2048); - p = script; - while (1) { - const char *val; - // expect value then ; or NULL, NULL ends list - if (!String_Parse(&p, &val)) { + DC->getCVarString(item->cvarTest, buff, sizeof(buff)); + + Q_strncpyz(script, item->enableCvar, 2048); + p = script; + while (1) { + const char *val; + // expect value then ; or NULL, NULL ends list + if (!String_Parse(&p, &val)) { return (item->cvarFlags & flag) ? qfalse : qtrue; - } + } - if (val[0] == ';' && val[1] == '\0') { - continue; - } + if (val[0] == ';' && val[1] == '\0') { + continue; + } // enable it if any of the values are true if (item->cvarFlags & flag) { - if (Q_stricmp(buff, val) == 0) { + if (Q_stricmp(buff, val) == 0) { return qtrue; } } else { // disable it if any of the values are true - if (Q_stricmp(buff, val) == 0) { + if (Q_stricmp(buff, val) == 0) { return qfalse; } } - - } + } return (item->cvarFlags & flag) ? qfalse : qtrue; - } + } return qtrue; } - // will optionaly set focus to this item qboolean Item_SetFocus(itemDef_t *item, float x, float y) { int i; @@ -2258,11 +2035,10 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) { return qfalse; } - parent = (menuDef_t*)item->parent; + parent = (menuDef_t *)item->parent; // items can be enabled and disabled - if (item->disabled) - { + if (item->disabled) { return qfalse; } @@ -2282,16 +2058,13 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) { r = item->textRect; r.y -= r.h; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { item->window.flags |= WINDOW_HASFOCUS; if (item->focusSound) { sfx = &item->focusSound; } playSound = qtrue; - } - else - { + } else { if (oldFocus) { oldFocus->window.flags |= WINDOW_HASFOCUS; if (oldFocus->onFocus) { @@ -2300,7 +2073,7 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) { } } } else { - item->window.flags |= WINDOW_HASFOCUS; + item->window.flags |= WINDOW_HASFOCUS; if (item->onFocus) { Item_RunScript(item, item->onFocus); } @@ -2311,7 +2084,7 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) { } if (playSound && sfx) { - DC->startLocalSound( *sfx, CHAN_LOCAL_SOUND ); + DC->startLocalSound(*sfx, CHAN_LOCAL_SOUND); } for (i = 0; i < parent->itemCount; i++) { @@ -2324,36 +2097,30 @@ qboolean Item_SetFocus(itemDef_t *item, float x, float y) { return qtrue; } -int Item_TextScroll_MaxScroll ( itemDef_t *item ) -{ +int Item_TextScroll_MaxScroll(itemDef_t *item) { textScrollDef_t *scrollPtr = item->typeData.textscroll; int count = scrollPtr->iLineCount; - int max = count - (int)(item->window.rect.h / scrollPtr->lineHeight) + 1; + int max = count - (int)(item->window.rect.h / scrollPtr->lineHeight) + 1; - if (max < 0) - { + if (max < 0) { return 0; } return max; } -int Item_TextScroll_ThumbPosition ( itemDef_t *item ) -{ +int Item_TextScroll_ThumbPosition(itemDef_t *item) { float max, pos, size; textScrollDef_t *scrollPtr = item->typeData.textscroll; - max = Item_TextScroll_MaxScroll ( item ); + max = Item_TextScroll_MaxScroll(item); size = item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; - if (max > 0) - { - pos = (size-SCROLLBAR_SIZE) / (float) max; - } - else - { - pos = 0; + if (max > 0) { + pos = (size - SCROLLBAR_SIZE) / (float)max; + } else { + pos = 0; } pos *= scrollPtr->startPos; @@ -2361,18 +2128,15 @@ int Item_TextScroll_ThumbPosition ( itemDef_t *item ) return item->window.rect.y + 1 + SCROLLBAR_SIZE + pos; } -int Item_TextScroll_ThumbDrawPosition ( itemDef_t *item ) -{ +int Item_TextScroll_ThumbDrawPosition(itemDef_t *item) { int min, max; - if (itemCapture == item) - { + if (itemCapture == item) { min = item->window.rect.y + SCROLLBAR_SIZE + 1; - max = item->window.rect.y + item->window.rect.h - 2*SCROLLBAR_SIZE - 1; + max = item->window.rect.y + item->window.rect.h - 2 * SCROLLBAR_SIZE - 1; - if (DC->cursory >= min + SCROLLBAR_SIZE/2 && DC->cursory <= max + SCROLLBAR_SIZE/2) - { - return DC->cursory - SCROLLBAR_SIZE/2; + if (DC->cursory >= min + SCROLLBAR_SIZE / 2 && DC->cursory <= max + SCROLLBAR_SIZE / 2) { + return DC->cursory - SCROLLBAR_SIZE / 2; } return Item_TextScroll_ThumbPosition(item); @@ -2381,93 +2145,78 @@ int Item_TextScroll_ThumbDrawPosition ( itemDef_t *item ) return Item_TextScroll_ThumbPosition(item); } -int Item_TextScroll_OverLB ( itemDef_t *item, float x, float y ) -{ - rectDef_t r; - int thumbstart; +int Item_TextScroll_OverLB(itemDef_t *item, float x, float y) { + rectDef_t r; + int thumbstart; r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; r.y = item->window.rect.y; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } thumbstart = Item_TextScroll_ThumbPosition(item); r.y = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.y = item->window.rect.y + SCROLLBAR_SIZE; r.h = thumbstart - r.y; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.y = thumbstart + SCROLLBAR_SIZE; r.h = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } return 0; } -void Item_TextScroll_MouseEnter (itemDef_t *item, float x, float y) -{ +void Item_TextScroll_MouseEnter(itemDef_t *item, float x, float y) { item->window.flags &= ~(WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN); item->window.flags |= Item_TextScroll_OverLB(item, x, y); } -qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qboolean force) -{ +qboolean Item_TextScroll_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) { textScrollDef_t *scrollPtr = item->typeData.textscroll; - int max; - int viewmax; + int max; + int viewmax; - if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) - { + if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) { max = Item_TextScroll_MaxScroll(item); viewmax = (item->window.rect.h / scrollPtr->lineHeight); - if ( key == A_CURSOR_UP || key == A_KP_8 ) - { + if (key == A_CURSOR_UP || key == A_KP_8) { scrollPtr->startPos--; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } return qtrue; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 ) - { + if (key == A_CURSOR_DOWN || key == A_KP_2) { scrollPtr->startPos++; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } return qtrue; } - if ( key == A_MWHEELUP ) - { - int count = trap->Key_IsDown( A_CTRL ) ? 5 : 1; + if (key == A_MWHEELUP) { + int count = trap->Key_IsDown(A_CTRL) ? 5 : 1; scrollPtr->startPos -= count; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -2475,12 +2224,10 @@ qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qb Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qtrue; } - if ( key == A_MWHEELDOWN ) - { - int count = trap->Key_IsDown( A_CTRL ) ? 5 : 1; + if (key == A_MWHEELDOWN) { + int count = trap->Key_IsDown(A_CTRL) ? 5 : 1; scrollPtr->startPos += count; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -2490,78 +2237,58 @@ qboolean Item_TextScroll_HandleKey ( itemDef_t *item, int key, qboolean down, qb } // mouse hit - if (key == A_MOUSE1 || key == A_MOUSE2) - { - if (item->window.flags & WINDOW_LB_LEFTARROW) - { + if (key == A_MOUSE1 || key == A_MOUSE2) { + if (item->window.flags & WINDOW_LB_LEFTARROW) { scrollPtr->startPos--; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_RIGHTARROW) - { + } else if (item->window.flags & WINDOW_LB_RIGHTARROW) { // one down scrollPtr->startPos++; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_PGUP) - { + } else if (item->window.flags & WINDOW_LB_PGUP) { // page up scrollPtr->startPos -= viewmax; - if (scrollPtr->startPos < 0) - { + if (scrollPtr->startPos < 0) { scrollPtr->startPos = 0; } - } - else if (item->window.flags & WINDOW_LB_PGDN) - { + } else if (item->window.flags & WINDOW_LB_PGDN) { // page down scrollPtr->startPos += viewmax; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } - } - else if (item->window.flags & WINDOW_LB_THUMB) - { + } else if (item->window.flags & WINDOW_LB_THUMB) { // Display_SetCaptureItem(item); } return qtrue; } - if ( key == A_HOME || key == A_KP_7) - { + if (key == A_HOME || key == A_KP_7) { // home scrollPtr->startPos = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) - { + if (key == A_END || key == A_KP_1) { // end scrollPtr->startPos = max; return qtrue; } - if (key == A_PAGE_UP || key == A_KP_9 ) - { + if (key == A_PAGE_UP || key == A_KP_9) { scrollPtr->startPos -= viewmax; - if (scrollPtr->startPos < 0) - { - scrollPtr->startPos = 0; + if (scrollPtr->startPos < 0) { + scrollPtr->startPos = 0; } return qtrue; } - if ( key == A_PAGE_DOWN || key == A_KP_3 ) - { + if (key == A_PAGE_DOWN || key == A_KP_3) { scrollPtr->startPos += viewmax; - if (scrollPtr->startPos > max) - { + if (scrollPtr->startPos > max) { scrollPtr->startPos = max; } return qtrue; @@ -2578,8 +2305,7 @@ int Item_ListBox_MaxScroll(itemDef_t *item) { if (item->window.flags & WINDOW_HORIZONTAL) { max = count - (item->window.rect.w / listPtr->elementWidth) + 1; - } - else { + } else { max = count - (item->window.rect.h / listPtr->elementHeight) + 1; } if (max < 0) { @@ -2596,17 +2322,16 @@ int Item_ListBox_ThumbPosition(itemDef_t *item) { if (item->window.flags & WINDOW_HORIZONTAL) { size = item->window.rect.w - (SCROLLBAR_SIZE * 2) - 2; if (max > 0) { - pos = (size-SCROLLBAR_SIZE) / (float) max; + pos = (size - SCROLLBAR_SIZE) / (float)max; } else { pos = 0; } pos *= listPtr->startPos; return item->window.rect.x + 1 + SCROLLBAR_SIZE + pos; - } - else { + } else { size = item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; if (max > 0) { - pos = (size-SCROLLBAR_SIZE) / (float) max; + pos = (size - SCROLLBAR_SIZE) / (float)max; } else { pos = 0; } @@ -2615,41 +2340,28 @@ int Item_ListBox_ThumbPosition(itemDef_t *item) { } } -int Item_ListBox_ThumbDrawPosition(itemDef_t *item) -{ +int Item_ListBox_ThumbDrawPosition(itemDef_t *item) { int min, max; - if (itemCapture == item) - { - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (itemCapture == item) { + if (item->window.flags & WINDOW_HORIZONTAL) { min = item->window.rect.x + SCROLLBAR_SIZE + 1; - max = item->window.rect.x + item->window.rect.w - 2*SCROLLBAR_SIZE - 1; - if (DC->cursorx >= min + SCROLLBAR_SIZE/2 && DC->cursorx <= max + SCROLLBAR_SIZE/2) - { - return DC->cursorx - SCROLLBAR_SIZE/2; - } - else - { + max = item->window.rect.x + item->window.rect.w - 2 * SCROLLBAR_SIZE - 1; + if (DC->cursorx >= min + SCROLLBAR_SIZE / 2 && DC->cursorx <= max + SCROLLBAR_SIZE / 2) { + return DC->cursorx - SCROLLBAR_SIZE / 2; + } else { return Item_ListBox_ThumbPosition(item); } - } - else - { + } else { min = item->window.rect.y + SCROLLBAR_SIZE + 1; - max = item->window.rect.y + item->window.rect.h - 2*SCROLLBAR_SIZE - 1; - if (DC->cursory >= min + SCROLLBAR_SIZE/2 && DC->cursory <= max + SCROLLBAR_SIZE/2) - { - return DC->cursory - SCROLLBAR_SIZE/2; - } - else - { + max = item->window.rect.y + item->window.rect.h - 2 * SCROLLBAR_SIZE - 1; + if (DC->cursory >= min + SCROLLBAR_SIZE / 2 && DC->cursory <= max + SCROLLBAR_SIZE / 2) { + return DC->cursory - SCROLLBAR_SIZE / 2; + } else { return Item_ListBox_ThumbPosition(item); } } - } - else - { + } else { return Item_ListBox_ThumbPosition(item); } } @@ -2679,11 +2391,11 @@ float Item_Slider_ThumbPosition(itemDef_t *item) { range = editDef->maxVal - editDef->minVal; value -= editDef->minVal; value /= range; - //value /= (editDef->maxVal - editDef->minVal); + // value /= (editDef->maxVal - editDef->minVal); value *= SLIDER_WIDTH; x += value; // vm fuckage - //x = x + (((float)value / editDef->maxVal) * SLIDER_WIDTH); + // x = x + (((float)value / editDef->maxVal) * SLIDER_WIDTH); return x; } @@ -2701,115 +2413,96 @@ int Item_Slider_OverSlider(itemDef_t *item, float x, float y) { return 0; } -int Item_ListBox_OverLB(itemDef_t *item, float x, float y) -{ +int Item_ListBox_OverLB(itemDef_t *item, float x, float y) { rectDef_t r; listBoxDef_t *listPtr; int thumbstart; listPtr = item->typeData.listbox; - if (item->window.flags & WINDOW_HORIZONTAL) - { + if (item->window.flags & WINDOW_HORIZONTAL) { // check if on left arrow r.x = item->window.rect.x; r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } // check if on right arrow r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } // check if on thumb thumbstart = Item_ListBox_ThumbPosition(item); r.x = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.x = item->window.rect.x + SCROLLBAR_SIZE; r.w = thumbstart - r.x; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.x = thumbstart + SCROLLBAR_SIZE; r.w = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } } // Vertical Scroll - else - { + else { // Multiple rows and columns (since it's more than twice as wide as an element) - if (( item->window.rect.w > (listPtr->elementWidth*2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) - { + if ((item->window.rect.w > (listPtr->elementWidth * 2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) { r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; r.y = item->window.rect.y; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } thumbstart = Item_ListBox_ThumbPosition(item); r.y = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } - } - else - { + } else { r.x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE; r.y = item->window.rect.y; r.h = r.w = SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_LEFTARROW; } r.y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_RIGHTARROW; } thumbstart = Item_ListBox_ThumbPosition(item); r.y = thumbstart; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_THUMB; } r.y = item->window.rect.y + SCROLLBAR_SIZE; r.h = thumbstart - r.y; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGUP; } r.y = thumbstart + SCROLLBAR_SIZE; r.h = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { return WINDOW_LB_PGDN; } } @@ -2817,73 +2510,58 @@ int Item_ListBox_OverLB(itemDef_t *item, float x, float y) return 0; } - -void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y) -{ +void Item_ListBox_MouseEnter(itemDef_t *item, float x, float y) { rectDef_t r; listBoxDef_t *listPtr = item->typeData.listbox; item->window.flags &= ~(WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN); item->window.flags |= Item_ListBox_OverLB(item, x, y); - if (item->window.flags & WINDOW_HORIZONTAL) - { - if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) - { + if (item->window.flags & WINDOW_HORIZONTAL) { + if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) { // check for selection hit as we have exausted buttons and thumb - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { r.x = item->window.rect.x; r.y = item->window.rect.y; r.h = item->window.rect.h - SCROLLBAR_SIZE; r.w = item->window.rect.w - listPtr->drawPadding; - if (Rect_ContainsPoint(&r, x, y)) - { - listPtr->cursorPos = (int)((x - r.x) / listPtr->elementWidth) + listPtr->startPos; - if (listPtr->cursorPos >= listPtr->endPos) - { + if (Rect_ContainsPoint(&r, x, y)) { + listPtr->cursorPos = (int)((x - r.x) / listPtr->elementWidth) + listPtr->startPos; + if (listPtr->cursorPos >= listPtr->endPos) { listPtr->cursorPos = listPtr->endPos; } } - } - else - { + } else { // text hit.. } } } // Window Vertical Scroll - else if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) - { + else if (!(item->window.flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW | WINDOW_LB_THUMB | WINDOW_LB_PGUP | WINDOW_LB_PGDN))) { // Calc which element the mouse is over r.x = item->window.rect.x; r.y = item->window.rect.y; r.w = item->window.rect.w - SCROLLBAR_SIZE; r.h = item->window.rect.h - listPtr->drawPadding; - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { // Multiple rows and columns (since it's more than twice as wide as an element) - if (( item->window.rect.w > (listPtr->elementWidth*2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) - { - int row,column,rowLength; + if ((item->window.rect.w > (listPtr->elementWidth * 2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) { + int row, column, rowLength; row = (int)((y - 2 - r.y) / listPtr->elementHeight); - rowLength = (int) r.w / listPtr->elementWidth; + rowLength = (int)r.w / listPtr->elementWidth; column = (int)((x - r.x) / listPtr->elementWidth); - listPtr->cursorPos = (row * rowLength)+column + listPtr->startPos; - if (listPtr->cursorPos >= listPtr->endPos) - { + listPtr->cursorPos = (row * rowLength) + column + listPtr->startPos; + if (listPtr->cursorPos >= listPtr->endPos) { listPtr->cursorPos = listPtr->endPos; } } // single column - else - { - listPtr->cursorPos = (int)((y - 2 - r.y) / listPtr->elementHeight) + listPtr->startPos; - if (listPtr->cursorPos > listPtr->endPos) - { - listPtr->cursorPos = listPtr->endPos; + else { + listPtr->cursorPos = (int)((y - 2 - r.y) / listPtr->elementHeight) + listPtr->startPos; + if (listPtr->cursorPos > listPtr->endPos) { + listPtr->cursorPos = listPtr->endPos; } } } @@ -2899,8 +2577,7 @@ void Item_MouseEnter(itemDef_t *item, float x, float y) { // in the text rect? // items can be enabled and disabled - if (item->disabled) - { + if (item->disabled) { return; } @@ -2913,8 +2590,7 @@ void Item_MouseEnter(itemDef_t *item, float x, float y) { return; } - if (Rect_ContainsPoint(&r, x, y)) - { + if (Rect_ContainsPoint(&r, x, y)) { if (!(item->window.flags & WINDOW_MOUSEOVERTEXT)) { Item_RunScript(item, item->mouseEnterText); item->window.flags |= WINDOW_MOUSEOVERTEXT; @@ -2938,56 +2614,50 @@ void Item_MouseEnter(itemDef_t *item, float x, float y) { if (item->type == ITEM_TYPE_LISTBOX) { Item_ListBox_MouseEnter(item, x, y); - } - else if ( item->type == ITEM_TYPE_TEXTSCROLL ) - { - Item_TextScroll_MouseEnter ( item, x, y ); + } else if (item->type == ITEM_TYPE_TEXTSCROLL) { + Item_TextScroll_MouseEnter(item, x, y); } } } } void Item_MouseLeave(itemDef_t *item) { - if (item) { - if (item->window.flags & WINDOW_MOUSEOVERTEXT) { - Item_RunScript(item, item->mouseExitText); - item->window.flags &= ~WINDOW_MOUSEOVERTEXT; - } - Item_RunScript(item, item->mouseExit); - item->window.flags &= ~(WINDOW_LB_RIGHTARROW | WINDOW_LB_LEFTARROW); - } + if (item) { + if (item->window.flags & WINDOW_MOUSEOVERTEXT) { + Item_RunScript(item, item->mouseExitText); + item->window.flags &= ~WINDOW_MOUSEOVERTEXT; + } + Item_RunScript(item, item->mouseExit); + item->window.flags &= ~(WINDOW_LB_RIGHTARROW | WINDOW_LB_LEFTARROW); + } } itemDef_t *Menu_HitTest(menuDef_t *menu, float x, float y) { - int i; - for (i = 0; i < menu->itemCount; i++) { - if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { - return menu->items[i]; - } - } - return NULL; + int i; + for (i = 0; i < menu->itemCount; i++) { + if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { + return menu->items[i]; + } + } + return NULL; } void Item_SetMouseOver(itemDef_t *item, qboolean focus) { - if (item) { - if (focus) { - item->window.flags |= WINDOW_MOUSEOVER; - } else { - item->window.flags &= ~WINDOW_MOUSEOVER; - } - } + if (item) { + if (focus) { + item->window.flags |= WINDOW_MOUSEOVER; + } else { + item->window.flags &= ~WINDOW_MOUSEOVER; + } + } } - qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) { - if (item && DC->ownerDrawHandleKey) - { + if (item && DC->ownerDrawHandleKey) { - // yep this is an ugly hack - if( key == A_MOUSE1 || key == A_MOUSE2 ) - { - switch( item->window.ownerDraw ) - { + // yep this is an ugly hack + if (key == A_MOUSE1 || key == A_MOUSE2) { + switch (item->window.ownerDraw) { case UI_FORCE_SIDE: case UI_FORCE_RANK_HEAL: case UI_FORCE_RANK_LEVITATION: @@ -3007,32 +2677,27 @@ qboolean Item_OwnerDraw_HandleKey(itemDef_t *item, int key) { case UI_FORCE_RANK_SABERATTACK: case UI_FORCE_RANK_SABERDEFEND: case UI_FORCE_RANK_SABERTHROW: - if(!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) ) - { + if (!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { return qfalse; } break; + } } - } - - return DC->ownerDrawHandleKey(item->window.ownerDraw, item->window.ownerDrawFlags, &item->special, key); - } - return qfalse; + return DC->ownerDrawHandleKey(item->window.ownerDraw, item->window.ownerDrawFlags, &item->special, key); + } + return qfalse; } - qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolean force) { listBoxDef_t *listPtr = item->typeData.listbox; int count = DC->feederCount(item->special); int max, viewmax; - if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) - { + if (force || (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS)) { max = Item_ListBox_MaxScroll(item); if (item->window.flags & WINDOW_HORIZONTAL) { viewmax = (item->window.rect.w / listPtr->elementWidth); - if ( key == A_CURSOR_LEFT || key == A_KP_4 ) - { + if (key == A_CURSOR_LEFT || key == A_KP_4) { if (!listPtr->notselectable) { listPtr->cursorPos--; if (listPtr->cursorPos < 0) { @@ -3048,16 +2713,14 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos--; if (listPtr->startPos < 0) listPtr->startPos = 0; } return qtrue; } - if ( key == A_CURSOR_RIGHT || key == A_KP_6 ) - { + if (key == A_CURSOR_RIGHT || key == A_KP_6) { if (!listPtr->notselectable) { listPtr->cursorPos++; if (listPtr->cursorPos < listPtr->startPos) { @@ -3065,7 +2728,7 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea return qfalse; } if (listPtr->cursorPos >= count) { - listPtr->cursorPos = count-1; + listPtr->cursorPos = count - 1; return qfalse; } if (listPtr->cursorPos >= listPtr->startPos + viewmax) { @@ -3073,11 +2736,10 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos++; if (listPtr->startPos >= count) - listPtr->startPos = count-1; + listPtr->startPos = count - 1; } return qtrue; } @@ -3086,17 +2748,13 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea else { // Multiple rows and columns (since it's more than twice as wide as an element) - if (( item->window.rect.w > (listPtr->elementWidth*2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) - { + if ((item->window.rect.w > (listPtr->elementWidth * 2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) { viewmax = (item->window.rect.w / listPtr->elementWidth); - } - else - { + } else { viewmax = (item->window.rect.h / listPtr->elementHeight); } - if ( key == A_CURSOR_UP || key == A_KP_8 ) - { + if (key == A_CURSOR_UP || key == A_KP_8) { if (!listPtr->notselectable) { listPtr->cursorPos--; if (listPtr->cursorPos < 0) { @@ -3112,16 +2770,14 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos--; if (listPtr->startPos < 0) listPtr->startPos = 0; } return qtrue; } - if ( key == A_CURSOR_DOWN || key == A_KP_2 ) - { + if (key == A_CURSOR_DOWN || key == A_KP_2) { if (!listPtr->notselectable) { listPtr->cursorPos++; if (listPtr->cursorPos < listPtr->startPos) { @@ -3129,7 +2785,7 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea return qfalse; } if (listPtr->cursorPos >= count) { - listPtr->cursorPos = count-1; + listPtr->cursorPos = count - 1; return qfalse; } if (listPtr->cursorPos >= listPtr->startPos + viewmax) { @@ -3137,8 +2793,7 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos++; if (listPtr->startPos > max) listPtr->startPos = max; @@ -3146,12 +2801,10 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea return qtrue; } - if ( key == A_MWHEELUP ) - { - int count = trap->Key_IsDown( A_CTRL ) ? 5 : 1; + if (key == A_MWHEELUP) { + int count = trap->Key_IsDown(A_CTRL) ? 5 : 1; listPtr->startPos -= ((int)item->special == FEEDER_Q3HEADS) ? viewmax : count; - if (listPtr->startPos < 0) - { + if (listPtr->startPos < 0) { listPtr->startPos = 0; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -3159,12 +2812,10 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qtrue; } - if ( key == A_MWHEELDOWN ) - { - int count = trap->Key_IsDown( A_CTRL ) ? 5 : 1; + if (key == A_MWHEELDOWN) { + int count = trap->Key_IsDown(A_CTRL) ? 5 : 1; listPtr->startPos += ((int)item->special == FEEDER_Q3HEADS) ? viewmax : count; - if (listPtr->startPos > max) - { + if (listPtr->startPos > max) { listPtr->startPos = max; Display_MouseMove(NULL, DC->cursorx, DC->cursory); return qfalse; @@ -3206,31 +2857,30 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea Item_RunScript(item, listPtr->doubleClick); } lastListBoxClickTime = DC->realTime + DOUBLE_CLICK_DELAY; -// if (item->cursorPos != listPtr->cursorPos) + // if (item->cursorPos != listPtr->cursorPos) { int prePos = item->cursorPos; item->cursorPos = listPtr->cursorPos; - if (!DC->feederSelection(item->special, item->cursorPos, item)) - { + if (!DC->feederSelection(item->special, item->cursorPos, item)) { item->cursorPos = listPtr->cursorPos = prePos; } } } return qtrue; } - if ( key == A_HOME || key == A_KP_7) { + if (key == A_HOME || key == A_KP_7) { // home listPtr->startPos = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) { + if (key == A_END || key == A_KP_1) { // end listPtr->startPos = max; return qtrue; } - if (key == A_PAGE_UP || key == A_KP_9 ) { + if (key == A_PAGE_UP || key == A_KP_9) { // page up if (!listPtr->notselectable) { listPtr->cursorPos -= viewmax; @@ -3245,8 +2895,7 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos -= viewmax; if (listPtr->startPos < 0) { listPtr->startPos = 0; @@ -3254,7 +2903,7 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } return qtrue; } - if ( key == A_PAGE_DOWN || key == A_KP_3 ) { + if (key == A_PAGE_DOWN || key == A_KP_3) { // page down if (!listPtr->notselectable) { listPtr->cursorPos += viewmax; @@ -3262,15 +2911,14 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea listPtr->startPos = listPtr->cursorPos; } if (listPtr->cursorPos >= count) { - listPtr->cursorPos = count-1; + listPtr->cursorPos = count - 1; } if (listPtr->cursorPos >= listPtr->startPos + viewmax) { listPtr->startPos = listPtr->cursorPos - viewmax + 1; } item->cursorPos = listPtr->cursorPos; DC->feederSelection(item->special, item->cursorPos, NULL); - } - else { + } else { listPtr->startPos += viewmax; if (listPtr->startPos > max) { listPtr->startPos = max; @@ -3283,17 +2931,14 @@ qboolean Item_ListBox_HandleKey(itemDef_t *item, int key, qboolean down, qboolea } qboolean Item_YesNo_HandleKey(itemDef_t *item, int key) { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) - { - if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) - { - DC->setCVar(item->cvar, va("%i", !DC->getCVarValue(item->cvar))); - return qtrue; + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS && item->cvar) { + if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { + DC->setCVar(item->cvar, va("%i", !DC->getCVarValue(item->cvar))); + return qtrue; } - } - - return qfalse; + } + return qfalse; } int Item_Multi_CountSettings(itemDef_t *item) { @@ -3311,7 +2956,7 @@ int Item_Multi_FindCvarByValue(itemDef_t *item) { multiDef_t *multiPtr = item->typeData.multi; if (multiPtr) { if (multiPtr->strDef) { - DC->getCVarString(item->cvar, buff, sizeof(buff)); + DC->getCVarString(item->cvar, buff, sizeof(buff)); } else { value = DC->getCVarValue(item->cvar); } @@ -3321,11 +2966,11 @@ int Item_Multi_FindCvarByValue(itemDef_t *item) { return i; } } else { - if (multiPtr->cvarValue[i] == value) { - return i; - } - } - } + if (multiPtr->cvarValue[i] == value) { + return i; + } + } + } } return 0; } @@ -3335,92 +2980,66 @@ const char *Item_Multi_Setting(itemDef_t *item) { float value = 0; int i; multiDef_t *multiPtr = item->typeData.multi; - if (multiPtr) - { - if (multiPtr->strDef) - { - if (item->cvar) - { - DC->getCVarString(item->cvar, buff, sizeof(buff)); + if (multiPtr) { + if (multiPtr->strDef) { + if (item->cvar) { + DC->getCVarString(item->cvar, buff, sizeof(buff)); } - } - else - { - if (item->cvar) // Was a cvar given? + } else { + if (item->cvar) // Was a cvar given? { value = DC->getCVarValue(item->cvar); } } - for (i = 0; i < multiPtr->count; i++) - { - if (multiPtr->strDef) - { - if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->strDef) { + if (Q_stricmp(buff, multiPtr->cvarStr[i]) == 0) { return multiPtr->cvarList[i]; } - } - else - { - if (multiPtr->cvarValue[i] == value) - { + } else { + if (multiPtr->cvarValue[i] == value) { return multiPtr->cvarList[i]; - } - } - } + } + } + } } return "@MENUS_CUSTOM"; } -qboolean Item_Multi_HandleKey(itemDef_t *item, int key) -{ +qboolean Item_Multi_HandleKey(itemDef_t *item, int key) { multiDef_t *multiPtr = item->typeData.multi; - if (multiPtr) - { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS) - { - if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3 || key == A_MWHEELDOWN || key == A_MWHEELUP) - { + if (multiPtr) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && item->window.flags & WINDOW_HASFOCUS) { + if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3 || key == A_MWHEELDOWN || key == A_MWHEELUP) { int current = Item_Multi_FindCvarByValue(item); int max = Item_Multi_CountSettings(item); - if (key == A_MOUSE2 || key == A_CURSOR_LEFT || key == A_MWHEELDOWN) // Xbox uses CURSOR_LEFT - // if (key == A_MOUSE2 || key == A_CURSOR_LEFT) // Xbox uses CURSOR_LEFT + if (key == A_MOUSE2 || key == A_CURSOR_LEFT || key == A_MWHEELDOWN) // Xbox uses CURSOR_LEFT + // if (key == A_MOUSE2 || key == A_CURSOR_LEFT) // Xbox uses CURSOR_LEFT { current--; - if ( current < 0 ) - { - current = max-1; + if (current < 0) { + current = max - 1; } - } - else - { + } else { current++; - if ( current >= max ) - { + if (current >= max) { current = 0; } } - if (multiPtr->strDef) - { + if (multiPtr->strDef) { DC->setCVar(item->cvar, multiPtr->cvarStr[current]); - } - else - { + } else { float value = multiPtr->cvarValue[current]; - if (((float)((int) value)) == value) - { - DC->setCVar(item->cvar, va("%i", (int) value )); - } - else - { - DC->setCVar(item->cvar, va("%f", value )); + if (((float)((int)value)) == value) { + DC->setCVar(item->cvar, va("%i", (int)value)); + } else { + DC->setCVar(item->cvar, va("%f", value)); } } - if (item->special) - {//its a feeder? + if (item->special) { // its a feeder? DC->feederSelection(item->special, current, item); } @@ -3428,39 +3047,36 @@ qboolean Item_Multi_HandleKey(itemDef_t *item, int key) } } } - return qfalse; + return qfalse; } // Leaving an edit field so reset it so it prints from the beginning. -void Leaving_EditField(itemDef_t *item) -{ +void Leaving_EditField(itemDef_t *item) { // switching fields so reset printed text of edit field - if ((g_editingField==qtrue) && (item->type==ITEM_TYPE_EDITFIELD)) - { + if ((g_editingField == qtrue) && (item->type == ITEM_TYPE_EDITFIELD)) { editFieldDef_t *editPtr = item->typeData.edit; - if (editPtr) - { + if (editPtr) { editPtr->paintOffset = 0; } } } #ifdef UI_BUILD -qboolean Item_TextField_HandleKey( itemDef_t *item, int key ); -void Item_TextField_Paste( itemDef_t *item ) { - int pasteLen, i; - char buff[2048] = { 0 }; +qboolean Item_TextField_HandleKey(itemDef_t *item, int key); +void Item_TextField_Paste(itemDef_t *item) { + int pasteLen, i; + char buff[2048] = {0}; - trap->GetClipboardData( buff, sizeof(buff) ); + trap->GetClipboardData(buff, sizeof(buff)); - if ( !*buff ) { + if (!*buff) { return; } // send as if typed, so insert / overstrike works properly - pasteLen = strlen( buff ); - for ( i = 0; i < pasteLen; i++ ) { - Item_TextField_HandleKey( item, buff[i]|K_CHAR_FLAG ); + pasteLen = strlen(buff); + for (i = 0; i < pasteLen; i++) { + Item_TextField_HandleKey(item, buff[i] | K_CHAR_FLAG); } } #endif @@ -3479,34 +3095,34 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { if (editPtr->maxChars && len > editPtr->maxChars) { len = editPtr->maxChars; } - if ( key & K_CHAR_FLAG ) { + if (key & K_CHAR_FLAG) { key &= ~K_CHAR_FLAG; #ifdef UI_BUILD - if ( key == 'v' - 'a' + 1 ) { // ctrl-v is paste - Item_TextField_Paste( item ); + if (key == 'v' - 'a' + 1) { // ctrl-v is paste + Item_TextField_Paste(item); return qtrue; } #endif - if (key == 'h' - 'a' + 1 ) { // ctrl-h is backspace - if ( item->cursorPos > 0 ) { - memmove( &buff[item->cursorPos - 1], &buff[item->cursorPos], len + 1 - item->cursorPos); + if (key == 'h' - 'a' + 1) { // ctrl-h is backspace + if (item->cursorPos > 0) { + memmove(&buff[item->cursorPos - 1], &buff[item->cursorPos], len + 1 - item->cursorPos); item->cursorPos--; if (item->cursorPos < editPtr->paintOffset) { editPtr->paintOffset--; } } DC->setCVar(item->cvar, buff); - return qtrue; + return qtrue; } // // ignore any non printable chars // - if ( key < 32 || !item->cvar) { - return qtrue; - } + if (key < 32 || !item->cvar) { + return qtrue; + } if (item->type == ITEM_TYPE_NUMERICFIELD) { if (key < '0' || key > '9') { @@ -3515,10 +3131,10 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { } if (!DC->getOverstrikeMode()) { - if (( len == MAX_EDITFIELD - 1 ) || (editPtr->maxChars && len >= editPtr->maxChars)) { + if ((len == MAX_EDITFIELD - 1) || (editPtr->maxChars && len >= editPtr->maxChars)) { return qtrue; } - memmove( &buff[item->cursorPos + 1], &buff[item->cursorPos], len + 1 - item->cursorPos ); + memmove(&buff[item->cursorPos + 1], &buff[item->cursorPos], len + 1 - item->cursorPos); } else { if (editPtr->maxChars && item->cursorPos >= editPtr->maxChars) { return qtrue; @@ -3527,13 +3143,10 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { buff[item->cursorPos] = key; - //rww - nul-terminate! - if (item->cursorPos+1 < 2048) - { - buff[item->cursorPos+1] = 0; - } - else - { + // rww - nul-terminate! + if (item->cursorPos + 1 < 2048) { + buff[item->cursorPos + 1] = 0; + } else { buff[item->cursorPos] = 0; } @@ -3548,16 +3161,15 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { } else { - if ( key == A_DELETE || key == A_KP_PERIOD ) { - if ( item->cursorPos < len ) { - memmove( buff + item->cursorPos, buff + item->cursorPos + 1, len - item->cursorPos); + if (key == A_DELETE || key == A_KP_PERIOD) { + if (item->cursorPos < len) { + memmove(buff + item->cursorPos, buff + item->cursorPos + 1, len - item->cursorPos); DC->setCVar(item->cvar, buff); } return qtrue; } - if ( key == A_CURSOR_RIGHT || key == A_KP_6 ) - { + if (key == A_CURSOR_RIGHT || key == A_KP_6) { if (editPtr->maxPaintChars && item->cursorPos >= editPtr->maxPaintChars && item->cursorPos < len) { item->cursorPos++; editPtr->paintOffset++; @@ -3569,9 +3181,8 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { return qtrue; } - if ( key == A_CURSOR_LEFT || key == A_KP_4 ) - { - if ( item->cursorPos > 0 ) { + if (key == A_CURSOR_LEFT || key == A_KP_4) { + if (item->cursorPos > 0) { item->cursorPos--; } if (item->cursorPos < editPtr->paintOffset) { @@ -3580,71 +3191,64 @@ qboolean Item_TextField_HandleKey(itemDef_t *item, int key) { return qtrue; } - if ( key == A_HOME || key == A_KP_7) {// || ( tolower(key) == 'a' && trap->Key_IsDown( K_CTRL ) ) ) { + if (key == A_HOME || key == A_KP_7) { // || ( tolower(key) == 'a' && trap->Key_IsDown( K_CTRL ) ) ) { item->cursorPos = 0; editPtr->paintOffset = 0; return qtrue; } - if ( key == A_END || key == A_KP_1) {// ( tolower(key) == 'e' && trap->Key_IsDown( K_CTRL ) ) ) { + if (key == A_END || key == A_KP_1) { // ( tolower(key) == 'e' && trap->Key_IsDown( K_CTRL ) ) ) { item->cursorPos = len; - if(item->cursorPos > editPtr->maxPaintChars) { + if (item->cursorPos > editPtr->maxPaintChars) { editPtr->paintOffset = len - editPtr->maxPaintChars; } return qtrue; } - if ( key == A_INSERT || key == A_KP_0 ) { + if (key == A_INSERT || key == A_KP_0) { DC->setOverstrikeMode(!DC->getOverstrikeMode()); return qtrue; } } - if (key == A_TAB || key == A_CURSOR_DOWN || key == A_KP_2) - { + if (key == A_TAB || key == A_CURSOR_DOWN || key == A_KP_2) { // switching fields so reset printed text of edit field Leaving_EditField(item); g_editingField = qfalse; - newItem = Menu_SetNextCursorItem((menuDef_t *) item->parent); - if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) - { + newItem = Menu_SetNextCursorItem((menuDef_t *)item->parent); + if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) { g_editItem = newItem; g_editingField = qtrue; } } - if (key == A_CURSOR_UP || key == A_KP_8) - { + if (key == A_CURSOR_UP || key == A_KP_8) { // switching fields so reset printed text of edit field Leaving_EditField(item); g_editingField = qfalse; - newItem = Menu_SetPrevCursorItem((menuDef_t *) item->parent); - if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) - { + newItem = Menu_SetPrevCursorItem((menuDef_t *)item->parent); + if (newItem && (newItem->type == ITEM_TYPE_EDITFIELD || newItem->type == ITEM_TYPE_NUMERICFIELD)) { g_editItem = newItem; g_editingField = qtrue; } } - // if ( key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE) { - if ( key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE || (key == A_MOUSE1 && !Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) )) { - DC->setOverstrikeMode( qfalse ); + // if ( key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE) { + if (key == A_ENTER || key == A_KP_ENTER || key == A_ESCAPE || (key == A_MOUSE1 && !Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory))) { + DC->setOverstrikeMode(qfalse); return qfalse; } return qtrue; } return qfalse; - } -static void Scroll_TextScroll_AutoFunc (void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; +static void Scroll_TextScroll_AutoFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; - if (DC->realTime > si->nextScrollTime) - { + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -3652,40 +3256,33 @@ static void Scroll_TextScroll_AutoFunc (void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } } -static void Scroll_TextScroll_ThumbFunc(void *p) -{ - scrollInfo_t *si = (scrollInfo_t*)p; - rectDef_t r; - int pos; - int max; +static void Scroll_TextScroll_ThumbFunc(void *p) { + scrollInfo_t *si = (scrollInfo_t *)p; + rectDef_t r; + int pos; + int max; textScrollDef_t *scrollPtr = si->item->typeData.textscroll; - if (DC->cursory != si->yStart) - { + if (DC->cursory != si->yStart) { r.x = si->item->window.rect.x + si->item->window.rect.w - SCROLLBAR_SIZE - 1; r.y = si->item->window.rect.y + SCROLLBAR_SIZE + 1; - r.h = si->item->window.rect.h - (SCROLLBAR_SIZE*2) - 2; + r.h = si->item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; r.w = SCROLLBAR_SIZE; max = Item_TextScroll_MaxScroll(si->item); // - pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * max / (r.h - SCROLLBAR_SIZE); - if (pos < 0) - { + pos = (DC->cursory - r.y - SCROLLBAR_SIZE / 2) * max / (r.h - SCROLLBAR_SIZE); + if (pos < 0) { pos = 0; - } - else if (pos > max) - { + } else if (pos > max) { pos = max; } @@ -3693,8 +3290,7 @@ static void Scroll_TextScroll_ThumbFunc(void *p) si->yStart = DC->cursory; } - if (DC->realTime > si->nextScrollTime) - { + if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox // so it calls it directly @@ -3702,18 +3298,16 @@ static void Scroll_TextScroll_ThumbFunc(void *p) si->nextScrollTime = DC->realTime + si->adjustValue; } - if (DC->realTime > si->nextAdjustTime) - { + if (DC->realTime > si->nextAdjustTime) { si->nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - if (si->adjustValue > SCROLL_TIME_FLOOR) - { + if (si->adjustValue > SCROLL_TIME_FLOOR) { si->adjustValue -= SCROLL_TIME_ADJUSTOFFSET; } } } static void Scroll_ListBox_AutoFunc(void *p) { - scrollInfo_t *si = (scrollInfo_t*)p; + scrollInfo_t *si = (scrollInfo_t *)p; if (DC->realTime > si->nextScrollTime) { // need to scroll which is done by simulating a click to the item // this is done a bit sideways as the autoscroll "knows" that the item is a listbox @@ -3731,7 +3325,7 @@ static void Scroll_ListBox_AutoFunc(void *p) { } static void Scroll_ListBox_ThumbFunc(void *p) { - scrollInfo_t *si = (scrollInfo_t*)p; + scrollInfo_t *si = (scrollInfo_t *)p; rectDef_t r; int pos, max; @@ -3743,46 +3337,40 @@ static void Scroll_ListBox_ThumbFunc(void *p) { r.x = si->item->window.rect.x + SCROLLBAR_SIZE + 1; r.y = si->item->window.rect.y + si->item->window.rect.h - SCROLLBAR_SIZE - 1; r.h = SCROLLBAR_SIZE; - r.w = si->item->window.rect.w - (SCROLLBAR_SIZE*2) - 2; + r.w = si->item->window.rect.w - (SCROLLBAR_SIZE * 2) - 2; max = Item_ListBox_MaxScroll(si->item); // - pos = (DC->cursorx - r.x - SCROLLBAR_SIZE/2) * max / (r.w - SCROLLBAR_SIZE); + pos = (DC->cursorx - r.x - SCROLLBAR_SIZE / 2) * max / (r.w - SCROLLBAR_SIZE); if (pos < 0) { pos = 0; - } - else if (pos > max) { + } else if (pos > max) { pos = max; } listPtr->startPos = pos; si->xStart = DC->cursorx; - } - else if (DC->cursory != si->yStart) { + } else if (DC->cursory != si->yStart) { r.x = si->item->window.rect.x + si->item->window.rect.w - SCROLLBAR_SIZE - 1; r.y = si->item->window.rect.y + SCROLLBAR_SIZE + 1; - r.h = si->item->window.rect.h - (SCROLLBAR_SIZE*2) - 2; + r.h = si->item->window.rect.h - (SCROLLBAR_SIZE * 2) - 2; r.w = SCROLLBAR_SIZE; max = Item_ListBox_MaxScroll(si->item); // Multiple rows and columns (since it's more than twice as wide as an element) - if (( si->item->window.rect.w > (listPtr->elementWidth*2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) - { + if ((si->item->window.rect.w > (listPtr->elementWidth * 2)) && (listPtr->elementStyle == LISTBOX_IMAGE)) { int rowLength, rowMax; rowLength = si->item->window.rect.w / listPtr->elementWidth; rowMax = max / rowLength; - pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * rowMax / (r.h - SCROLLBAR_SIZE); + pos = (DC->cursory - r.y - SCROLLBAR_SIZE / 2) * rowMax / (r.h - SCROLLBAR_SIZE); pos *= rowLength; - } - else - { - pos = (DC->cursory - r.y - SCROLLBAR_SIZE/2) * max / (r.h - SCROLLBAR_SIZE); + } else { + pos = (DC->cursory - r.y - SCROLLBAR_SIZE / 2) * max / (r.h - SCROLLBAR_SIZE); } if (pos < 0) { pos = 0; - } - else if (pos > max) { + } else if (pos > max) { pos = max; } listPtr->startPos = pos; @@ -3807,7 +3395,7 @@ static void Scroll_ListBox_ThumbFunc(void *p) { static void Scroll_Slider_ThumbFunc(void *p) { float x, value, cursorx; - scrollInfo_t *si = (scrollInfo_t*)p; + scrollInfo_t *si = (scrollInfo_t *)p; editFieldDef_t *editDef = si->item->typeData.edit; if (si->item->text) { @@ -3830,89 +3418,80 @@ static void Scroll_Slider_ThumbFunc(void *p) { DC->setCVar(si->item->cvar, va("%f", value)); } -void Item_StartCapture(itemDef_t *item, int key) -{ +void Item_StartCapture(itemDef_t *item, int key) { int flags; - switch (item->type) - { - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_LISTBOX: - { - flags = Item_ListBox_OverLB(item, DC->cursorx, DC->cursory); - if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) { - scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; - scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - scrollInfo.adjustValue = SCROLL_TIME_START; - scrollInfo.scrollKey = key; - scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; - scrollInfo.item = item; - captureData = &scrollInfo; - captureFunc = &Scroll_ListBox_AutoFunc; - itemCapture = item; - } else if (flags & WINDOW_LB_THUMB) { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_ListBox_ThumbFunc; - itemCapture = item; - } - break; + switch (item->type) { + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_LISTBOX: { + flags = Item_ListBox_OverLB(item, DC->cursorx, DC->cursory); + if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) { + scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; + scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; + scrollInfo.adjustValue = SCROLL_TIME_START; + scrollInfo.scrollKey = key; + scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; + scrollInfo.item = item; + captureData = &scrollInfo; + captureFunc = &Scroll_ListBox_AutoFunc; + itemCapture = item; + } else if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_ListBox_ThumbFunc; + itemCapture = item; } + break; + } - case ITEM_TYPE_TEXTSCROLL: - flags = Item_TextScroll_OverLB (item, DC->cursorx, DC->cursory); - if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) - { - scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; - scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; - scrollInfo.adjustValue = SCROLL_TIME_START; - scrollInfo.scrollKey = key; - scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; - scrollInfo.item = item; - captureData = &scrollInfo; - captureFunc = &Scroll_TextScroll_AutoFunc; - itemCapture = item; - } - else if (flags & WINDOW_LB_THUMB) - { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_TextScroll_ThumbFunc; - itemCapture = item; - } - break; + case ITEM_TYPE_TEXTSCROLL: + flags = Item_TextScroll_OverLB(item, DC->cursorx, DC->cursory); + if (flags & (WINDOW_LB_LEFTARROW | WINDOW_LB_RIGHTARROW)) { + scrollInfo.nextScrollTime = DC->realTime + SCROLL_TIME_START; + scrollInfo.nextAdjustTime = DC->realTime + SCROLL_TIME_ADJUST; + scrollInfo.adjustValue = SCROLL_TIME_START; + scrollInfo.scrollKey = key; + scrollInfo.scrollDir = (flags & WINDOW_LB_LEFTARROW) ? qtrue : qfalse; + scrollInfo.item = item; + captureData = &scrollInfo; + captureFunc = &Scroll_TextScroll_AutoFunc; + itemCapture = item; + } else if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_TextScroll_ThumbFunc; + itemCapture = item; + } + break; - case ITEM_TYPE_SLIDER: - { - flags = Item_Slider_OverSlider(item, DC->cursorx, DC->cursory); - if (flags & WINDOW_LB_THUMB) { - scrollInfo.scrollKey = key; - scrollInfo.item = item; - scrollInfo.xStart = DC->cursorx; - scrollInfo.yStart = DC->cursory; - captureData = &scrollInfo; - captureFunc = &Scroll_Slider_ThumbFunc; - itemCapture = item; - } - break; + case ITEM_TYPE_SLIDER: { + flags = Item_Slider_OverSlider(item, DC->cursorx, DC->cursory); + if (flags & WINDOW_LB_THUMB) { + scrollInfo.scrollKey = key; + scrollInfo.item = item; + scrollInfo.xStart = DC->cursorx; + scrollInfo.yStart = DC->cursory; + captureData = &scrollInfo; + captureFunc = &Scroll_Slider_ThumbFunc; + itemCapture = item; } + break; + } } } -void Item_StopCapture(itemDef_t *item) { - -} +void Item_StopCapture(itemDef_t *item) {} qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) { float x, value, width, work; - //DC->Print("slider handle key\n"); + // DC->Print("slider handle key\n"); if (item->window.flags & WINDOW_HASFOCUS && item->cvar && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { if (key == A_MOUSE1 || key == A_ENTER || key == A_MOUSE2 || key == A_MOUSE3) { editFieldDef_t *editDef = item->typeData.edit; @@ -3929,9 +3508,9 @@ qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) { testRect.x = x; value = (float)SLIDER_THUMB_WIDTH / 2; testRect.x -= value; - //DC->Print("slider x: %f\n", testRect.x); + // DC->Print("slider x: %f\n", testRect.x); testRect.w = (SLIDER_WIDTH + (float)SLIDER_THUMB_WIDTH / 2); - //DC->Print("slider w: %f\n", testRect.w); + // DC->Print("slider w: %f\n", testRect.w); if (Rect_ContainsPoint(&testRect, DC->cursorx, DC->cursory)) { work = DC->cursorx - x; value = work / width; @@ -3945,11 +3524,10 @@ qboolean Item_Slider_HandleKey(itemDef_t *item, int key, qboolean down) { } } } - //DC->Print("slider handle key exit\n"); + // DC->Print("slider handle key exit\n"); return qfalse; } - qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) { if (itemCapture) { Item_StopCapture(itemCapture); @@ -3957,7 +3535,7 @@ qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) { captureFunc = 0; captureData = NULL; } else { - if ( down && ( key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3 ) ) { + if (down && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) { Item_StartCapture(item, key); } } @@ -3978,16 +3556,14 @@ qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) { break; case ITEM_TYPE_EDITFIELD: case ITEM_TYPE_NUMERICFIELD: - if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER) - { + if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_ENTER) { editFieldDef_t *editPtr = item->typeData.edit; - if (item->cvar && editPtr) - { + if (item->cvar && editPtr) { editPtr->paintOffset = 0; } - //return Item_TextField_HandleKey(item, key); + // return Item_TextField_HandleKey(item, key); } return qfalse; break; @@ -4015,27 +3591,24 @@ qboolean Item_HandleKey(itemDef_t *item, int key, qboolean down) { case ITEM_TYPE_SLIDER: return Item_Slider_HandleKey(item, key, down); break; - //case ITEM_TYPE_IMAGE: - // Item_Image_Paint(item); - // break; + // case ITEM_TYPE_IMAGE: + // Item_Image_Paint(item); + // break; default: return qfalse; break; } } - -//JLFACCEPT MPMOVED +// JLFACCEPT MPMOVED /* ----------------------------------------- Item_HandleAccept If Item has an accept script, run it. ------------------------------------------- */ -qboolean Item_HandleAccept(itemDef_t * item) -{ - if (item->accept) - { +qboolean Item_HandleAccept(itemDef_t *item) { + if (item->accept) { Item_RunScript(item, item->accept); return qtrue; } @@ -4043,32 +3616,28 @@ qboolean Item_HandleAccept(itemDef_t * item) } void Item_Action(itemDef_t *item) { - if (item) { - Item_RunScript(item, item->action); - } + if (item) { + Item_RunScript(item, item->action); + } } - - itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu) { qboolean wrapped = qfalse; int oldCursor = menu->cursorItem; if (menu->cursorItem < 0) { - menu->cursorItem = menu->itemCount-1; + menu->cursorItem = menu->itemCount - 1; wrapped = qtrue; } - while (menu->cursorItem > -1) - { + while (menu->cursorItem > -1) { menu->cursorItem--; if (menu->cursorItem < 0) { - if (wrapped) - { + if (wrapped) { break; } wrapped = qtrue; - menu->cursorItem = menu->itemCount -1; + menu->cursorItem = menu->itemCount - 1; } if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) { @@ -4078,33 +3647,30 @@ itemDef_t *Menu_SetPrevCursorItem(menuDef_t *menu) { } menu->cursorItem = oldCursor; return NULL; - } itemDef_t *Menu_SetNextCursorItem(menuDef_t *menu) { - qboolean wrapped = qfalse; + qboolean wrapped = qfalse; int oldCursor = menu->cursorItem; + if (menu->cursorItem == -1) { + menu->cursorItem = 0; + wrapped = qtrue; + } - if (menu->cursorItem == -1) { - menu->cursorItem = 0; - wrapped = qtrue; - } - - while (menu->cursorItem < menu->itemCount) { + while (menu->cursorItem < menu->itemCount) { - menu->cursorItem++; - if (menu->cursorItem >= menu->itemCount && !wrapped) { - wrapped = qtrue; - menu->cursorItem = 0; - } + menu->cursorItem++; + if (menu->cursorItem >= menu->itemCount && !wrapped) { + wrapped = qtrue; + menu->cursorItem = 0; + } if (Item_SetFocus(menu->items[menu->cursorItem], DC->cursorx, DC->cursory)) { Menu_HandleMouseMove(menu, menu->items[menu->cursorItem]->window.rect.x + 1, menu->items[menu->cursorItem]->window.rect.y + 1); - return menu->items[menu->cursorItem]; - } - - } + return menu->items[menu->cursorItem]; + } + } menu->cursorItem = oldCursor; return NULL; @@ -4121,12 +3687,12 @@ static void Menu_CloseCinematics(menuDef_t *menu) { if (menu) { int i; Window_CloseCinematic(&menu->window); - for (i = 0; i < menu->itemCount; i++) { - Window_CloseCinematic(&menu->items[i]->window); + for (i = 0; i < menu->itemCount; i++) { + Window_CloseCinematic(&menu->items[i]->window); if (menu->items[i]->type == ITEM_TYPE_OWNERDRAW) { - DC->stopCinematic(0-menu->items[i]->window.ownerDraw); + DC->stopCinematic(0 - menu->items[i]->window.ownerDraw); } - } + } } } @@ -4137,7 +3703,7 @@ static void Display_CloseCinematics() { } } -void Menus_Activate(menuDef_t *menu) { +void Menus_Activate(menuDef_t *menu) { menu->window.flags |= (WINDOW_HASFOCUS | WINDOW_VISIBLE); if (menu->onOpen) { @@ -4147,13 +3713,12 @@ void Menus_Activate(menuDef_t *menu) { } if (menu->soundName && *menu->soundName) { -// DC->stopBackgroundTrack(); // you don't want to do this since it will reset s_rawend + // DC->stopBackgroundTrack(); // you don't want to do this since it will reset s_rawend DC->startBackgroundTrack(menu->soundName, menu->soundName, qfalse); } menu->appearanceTime = 0; Display_CloseCinematics(); - } int Display_VisibleMenuCount() { @@ -4182,7 +3747,7 @@ void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) { if (Menu_OverActiveItem(&Menus[i], DC->cursorx, DC->cursory)) { Menu_RunCloseScript(menu); menu->window.flags &= ~(WINDOW_HASFOCUS | WINDOW_VISIBLE); - // Menus_Activate(&Menus[i]); + // Menus_Activate(&Menus[i]); Menu_HandleMouseMove(&Menus[i], DC->cursorx, DC->cursory); Menu_HandleKey(&Menus[i], key, down); } @@ -4197,7 +3762,6 @@ void Menus_HandleOOBClick(menuDef_t *menu, int key, qboolean down) { } } - void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { int i; itemDef_t *item = NULL; @@ -4207,24 +3771,18 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { return; } - if (g_editingField && down) - { - if (!Item_TextField_HandleKey(g_editItem, key)) - { + if (g_editingField && down) { + if (!Item_TextField_HandleKey(g_editItem, key)) { g_editingField = qfalse; g_editItem = NULL; return; - } - else if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3) - { + } else if (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3) { // switching fields so reset printed text of edit field Leaving_EditField(g_editItem); g_editingField = qfalse; g_editItem = NULL; Display_MouseMove(NULL, DC->cursorx, DC->cursory); - } - else if (key == A_TAB || key == A_CURSOR_UP || key == A_CURSOR_DOWN) - { + } else if (key == A_TAB || key == A_CURSOR_UP || key == A_CURSOR_DOWN) { return; } } @@ -4232,11 +3790,10 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { if (menu == NULL) { return; } - // see if the mouse is within the window bounds and if so is this a mouse click - if (down && !(menu->window.flags & WINDOW_POPUP) && !Rect_ContainsPoint(&menu->window.rect, DC->cursorx, DC->cursory)) - { + // see if the mouse is within the window bounds and if so is this a mouse click + if (down && !(menu->window.flags & WINDOW_POPUP) && !Rect_ContainsPoint(&menu->window.rect, DC->cursorx, DC->cursory)) { static qboolean inHandleKey = qfalse; - if (!inHandleKey && ( key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3 ) ) { + if (!inHandleKey && (key == A_MOUSE1 || key == A_MOUSE2 || key == A_MOUSE3)) { inHandleKey = qtrue; Menus_HandleOOBClick(menu, key, down); inHandleKey = qfalse; @@ -4252,17 +3809,14 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { } // Ignore if disabled - if (item && item->disabled) - { + if (item && item->disabled) { return; } if (item != NULL) { - if (Item_HandleKey(item, key, down)) - { + if (Item_HandleKey(item, key, down)) { // It is possible for an item to be disable after Item_HandleKey is run (like in Voice Chat) - if (!item->disabled) - { + if (!item->disabled) { Item_Action(item); } return; @@ -4274,143 +3828,136 @@ void Menu_HandleKey(menuDef_t *menu, int key, qboolean down) { } // default handling - switch ( key ) { + switch (key) { - case A_F11: - if (DC->getCVarValue("developer")) { - debugMode ^= 1; - } - break; + case A_F11: + if (DC->getCVarValue("developer")) { + debugMode ^= 1; + } + break; - case A_F12: - if (DC->getCVarValue("developer")) { - switch ( DC->screenshotFormat ) { - case SSF_JPEG: - DC->executeText(EXEC_APPEND, "screenshot\n"); - break; - case SSF_TGA: - DC->executeText(EXEC_APPEND, "screenshot_tga\n"); - break; - case SSF_PNG: - DC->executeText(EXEC_APPEND, "screenshot_png\n"); - break; - default: - if (DC->Print) { - DC->Print(S_COLOR_YELLOW "Menu_HandleKey[F12]: Unknown screenshot format assigned! This should not happen.\n"); - } - break; + case A_F12: + if (DC->getCVarValue("developer")) { + switch (DC->screenshotFormat) { + case SSF_JPEG: + DC->executeText(EXEC_APPEND, "screenshot\n"); + break; + case SSF_TGA: + DC->executeText(EXEC_APPEND, "screenshot_tga\n"); + break; + case SSF_PNG: + DC->executeText(EXEC_APPEND, "screenshot_png\n"); + break; + default: + if (DC->Print) { + DC->Print(S_COLOR_YELLOW "Menu_HandleKey[F12]: Unknown screenshot format assigned! This should not happen.\n"); } + break; } - break; - case A_KP_8: - case A_CURSOR_UP: - Menu_SetPrevCursorItem(menu); - break; + } + break; + case A_KP_8: + case A_CURSOR_UP: + Menu_SetPrevCursorItem(menu); + break; - case A_ESCAPE: - if (!g_waitingForKey && menu->onESC) { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onESC); - } - g_waitingForKey = qfalse; - break; - case A_TAB: - case A_KP_2: - case A_CURSOR_DOWN: - Menu_SetNextCursorItem(menu); - break; + case A_ESCAPE: + if (!g_waitingForKey && menu->onESC) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onESC); + } + g_waitingForKey = qfalse; + break; + case A_TAB: + case A_KP_2: + case A_CURSOR_DOWN: + Menu_SetNextCursorItem(menu); + break; - case A_MOUSE1: - case A_MOUSE2: - if (item) { - if (item->type == ITEM_TYPE_TEXT) { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { - Item_Action(item); - } - } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { - Item_Action(item); - item->cursorPos = 0; - g_editingField = qtrue; - g_editItem = item; - //DC->setOverstrikeMode(qtrue); - } + case A_MOUSE1: + case A_MOUSE2: + if (item) { + if (item->type == ITEM_TYPE_TEXT) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { + Item_Action(item); } + } else if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { + Item_Action(item); + item->cursorPos = 0; + g_editingField = qtrue; + g_editItem = item; + // DC->setOverstrikeMode(qtrue); + } + } - //JLFACCEPT -// add new types here as needed -/* Notes: - Most controls will use the dpad to move through the selection possibilies. Buttons are the only exception. - Buttons will be assumed to all be on one menu together. If the start or A button is pressed on a control focus, that - means that the menu is accepted and move onto the next menu. If the start or A button is pressed on a button focus it - should just process the action and not support the accept functionality. -*/ + // JLFACCEPT + // add new types here as needed + /* Notes: + Most controls will use the dpad to move through the selection possibilies. Buttons are the only exception. + Buttons will be assumed to all be on one menu together. If the start or A button is pressed on a control focus, that + means that the menu is accepted and move onto the next menu. If the start or A button is pressed on a button focus it + should just process the action and not support the accept functionality. + */ -//JLFACCEPT MPMOVED - else if ( item->type == ITEM_TYPE_MULTI || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_SLIDER) - { - if (Item_HandleAccept(item)) - { - //Item processed it overriding the menu processing - return; - } - else if (menu->onAccept) - { - itemDef_t it; - it.parent = menu; - Item_RunScript(&it, menu->onAccept); - } + // JLFACCEPT MPMOVED + else if (item->type == ITEM_TYPE_MULTI || item->type == ITEM_TYPE_YESNO || item->type == ITEM_TYPE_SLIDER) { + if (Item_HandleAccept(item)) { + // Item processed it overriding the menu processing + return; + } else if (menu->onAccept) { + itemDef_t it; + it.parent = menu; + Item_RunScript(&it, menu->onAccept); } -//END JLFACCEPT - else { - if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - { + } + // END JLFACCEPT + else { + if (Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) { - Item_Action(item); - } + Item_Action(item); } } - break; + } + break; - case A_JOY0: - case A_JOY1: - case A_JOY2: - case A_JOY3: - case A_JOY4: - case A_AUX0: - case A_AUX1: - case A_AUX2: - case A_AUX3: - case A_AUX4: - case A_AUX5: - case A_AUX6: - case A_AUX7: - case A_AUX8: - case A_AUX9: - case A_AUX10: - case A_AUX11: - case A_AUX12: - case A_AUX13: - case A_AUX14: - case A_AUX15: - case A_AUX16: - break; - case A_KP_ENTER: - case A_ENTER: - if (item) { - if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { - item->cursorPos = 0; - g_editingField = qtrue; - g_editItem = item; - //DC->setOverstrikeMode(qtrue); - } else { - Item_Action(item); - } + case A_JOY0: + case A_JOY1: + case A_JOY2: + case A_JOY3: + case A_JOY4: + case A_AUX0: + case A_AUX1: + case A_AUX2: + case A_AUX3: + case A_AUX4: + case A_AUX5: + case A_AUX6: + case A_AUX7: + case A_AUX8: + case A_AUX9: + case A_AUX10: + case A_AUX11: + case A_AUX12: + case A_AUX13: + case A_AUX14: + case A_AUX15: + case A_AUX16: + break; + case A_KP_ENTER: + case A_ENTER: + if (item) { + if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) { + item->cursorPos = 0; + g_editingField = qtrue; + g_editItem = item; + // DC->setOverstrikeMode(qtrue); + } else { + Item_Action(item); } - break; + } + break; } } @@ -4423,14 +3970,12 @@ void ToWindowCoords(float *x, float *y, windowDef_t *window) { *y += window->rect.y; } -void Rect_ToWindowCoords(rectDef_t *rect, windowDef_t *window) { - ToWindowCoords(&rect->x, &rect->y, window); -} +void Rect_ToWindowCoords(rectDef_t *rect, windowDef_t *window) { ToWindowCoords(&rect->x, &rect->y, window); } void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *text) { const char *textPtr = (text) ? text : item->text; - if (textPtr == NULL ) { + if (textPtr == NULL) { return; } @@ -4440,18 +3985,14 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t // keeps us from computing the widths and heights more than once if (*width == 0 || (item->type == ITEM_TYPE_OWNERDRAW && item->textalignment == ITEM_ALIGN_CENTER) #ifndef _CGAME - || (item->text && item->text[0]=='@' && item->asset != se_language.modificationCount ) //string package language changed + || (item->text && item->text[0] == '@' && item->asset != se_language.modificationCount) // string package language changed #endif - ) - { + ) { int originalWidth = DC->textWidth(textPtr, item->textscale, item->iMenuFont); - if (item->type == ITEM_TYPE_OWNERDRAW && (item->textalignment == ITEM_ALIGN_CENTER || item->textalignment == ITEM_ALIGN_RIGHT)) - { + if (item->type == ITEM_TYPE_OWNERDRAW && (item->textalignment == ITEM_ALIGN_CENTER || item->textalignment == ITEM_ALIGN_RIGHT)) { originalWidth += DC->ownerDrawWidth(item->window.ownerDraw, item->textscale); - } - else if (item->type == ITEM_TYPE_EDITFIELD && item->textalignment == ITEM_ALIGN_CENTER && item->cvar) - { + } else if (item->type == ITEM_TYPE_EDITFIELD && item->textalignment == ITEM_ALIGN_CENTER && item->cvar) { char buff[256]; DC->getCVarString(item->cvar, buff, 256); originalWidth += DC->textWidth(buff, item->textscale, item->iMenuFont); @@ -4472,8 +4013,8 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t ToWindowCoords(&item->textRect.x, &item->textRect.y, &item->window); #ifndef _CGAME - if (item->text && item->text[0]=='@' )//string package - {//mark language + if (item->text && item->text[0] == '@') // string package + { // mark language item->asset = se_language.modificationCount; } #endif @@ -4482,7 +4023,7 @@ void Item_SetTextExtents(itemDef_t *item, int *width, int *height, const char *t void Item_TextColor(itemDef_t *item, vec4_t *newColor) { vec4_t lowLight; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount); @@ -4491,20 +4032,19 @@ void Item_TextColor(itemDef_t *item, vec4_t *newColor) { lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,*newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) { + LerpColor(parent->focusColor, lowLight, *newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime / BLINK_DIVISOR) & 1)) { lowLight[0] = 0.8 * item->window.foreColor[0]; lowLight[1] = 0.8 * item->window.foreColor[1]; lowLight[2] = 0.8 * item->window.foreColor[2]; lowLight[3] = 0.8 * item->window.foreColor[3]; - LerpColor(item->window.foreColor,lowLight,*newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); + LerpColor(item->window.foreColor, lowLight, *newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } else { memcpy(newColor, &item->window.foreColor, sizeof(vec4_t)); // items can be enabled and disabled based on cvars } - if (item->disabled) - { + if (item->disabled) { memcpy(newColor, &parent->disableColor, sizeof(vec4_t)); } @@ -4519,7 +4059,7 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) { char text[2048]; const char *p, *textPtr, *newLinePtr; char buff[2048]; - int height, len, textWidth, newLine, newLineWidth; //int width; + int height, len, textWidth, newLine, newLineWidth; // int width; float y; vec4_t color; @@ -4529,29 +4069,27 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) { if (item->text == NULL) { if (item->cvar == NULL) { return; - } - else { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else { + } else { textPtr = item->text; } - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - trap->SE_GetStringTextString( &textPtr[1], text, sizeof(text)); + trap->SE_GetStringTextString(&textPtr[1], text, sizeof(text)); textPtr = text; } if (*textPtr == '\0') { return; } Item_TextColor(item, &color); - //Item_SetTextExtents(item, &width, &height, textPtr); - //if (item->value == 0) + // Item_SetTextExtents(item, &width, &height, textPtr); + // if (item->value == 0) //{ // item->value = (int)(0.5 + (float)DC->textWidth(textPtr, item->textscale, item->font) / item->window.rect.w); - //} + // } height = DC->textHeight(textPtr, item->textscale, item->iMenuFont); y = item->textaligny; @@ -4560,14 +4098,14 @@ void Item_Text_AutoWrapped_Paint(itemDef_t *item) { newLine = 0; newLineWidth = 0; p = textPtr; - while (p) { //findmeste (this will break widechar languages)! + while (p) { // findmeste (this will break widechar languages)! if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\0') { newLine = len; - newLinePtr = p+1; + newLinePtr = p + 1; newLineWidth = textWidth; } textWidth = DC->textWidth(buff, item->textscale, 0); - if ( (newLine && textWidth > item->window.rect.w) || *p == '\n' || *p == '\0') { + if ((newLine && textWidth > item->window.rect.w) || *p == '\n' || *p == '\0') { if (len) { if (item->textalignment == ITEM_ALIGN_LEFT) { item->textRect.x = item->textalignx; @@ -4612,18 +4150,16 @@ void Item_Text_Wrapped_Paint(itemDef_t *item) { if (item->text == NULL) { if (item->cvar == NULL) { return; - } - else { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else { + } else { textPtr = item->text; } - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - trap->SE_GetStringTextString( &textPtr[1], text, sizeof(text)); + trap->SE_GetStringTextString(&textPtr[1], text, sizeof(text)); textPtr = text; } if (*textPtr == '\0') { @@ -4638,12 +4174,12 @@ void Item_Text_Wrapped_Paint(itemDef_t *item) { start = textPtr; p = strchr(textPtr, '\r'); while (p && *p) { - strncpy(buff, start, p-start+1); - buff[p-start] = '\0'; + strncpy(buff, start, p - start + 1); + buff[p - start] = '\0'; DC->drawText(x, y, item->textscale, color, buff, 0, 0, item->textStyle, item->iMenuFont); y += height + 2; start += p - start + 1; - p = strchr(p+1, '\r'); + p = strchr(p + 1, '\r'); } DC->drawText(x, y, item->textscale, color, start, 0, 0, item->textStyle, item->iMenuFont); } @@ -4666,18 +4202,16 @@ void Item_Text_Paint(itemDef_t *item) { if (item->text == NULL) { if (item->cvar == NULL) { return; - } - else { + } else { DC->getCVarString(item->cvar, text, sizeof(text)); textPtr = text; } - } - else { + } else { textPtr = item->text; } - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - trap->SE_GetStringTextString( &textPtr[1], text, sizeof(text)); + trap->SE_GetStringTextString(&textPtr[1], text, sizeof(text)); textPtr = text; } @@ -4688,21 +4222,21 @@ void Item_Text_Paint(itemDef_t *item) { return; } - Item_TextColor(item, &color); DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, textPtr, 0, 0, item->textStyle, item->iMenuFont); - if (item->text2) // Is there a second line of text? + if (item->text2) // Is there a second line of text? { textPtr = item->text2; - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - trap->SE_GetStringTextString( &textPtr[1], text, sizeof(text)); + trap->SE_GetStringTextString(&textPtr[1], text, sizeof(text)); textPtr = text; } Item_TextColor(item, &color); - DC->drawText(item->textRect.x + item->text2alignx, item->textRect.y + item->text2aligny, item->textscale, color, textPtr, 0, 0, item->textStyle,item->iMenuFont); + DC->drawText(item->textRect.x + item->text2alignx, item->textRect.y + item->text2aligny, item->textscale, color, textPtr, 0, 0, item->textStyle, + item->iMenuFont); } } @@ -4710,7 +4244,7 @@ void Item_TextField_Paint(itemDef_t *item) { char buff[1024]; vec4_t newColor, lowLight; int offset; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; editFieldDef_t *editPtr = item->typeData.edit; Item_Text_Paint(item); @@ -4719,20 +4253,20 @@ void Item_TextField_Paint(itemDef_t *item) { if (item->cvar) { DC->getCVarString(item->cvar, buff, sizeof(buff)); - if (buff[0] == '@') // string reference + if (buff[0] == '@') // string reference { - trap->SE_GetStringTextString( &buff[1], buff, sizeof(buff)); + trap->SE_GetStringTextString(&buff[1], buff, sizeof(buff)); } } - parent = (menuDef_t*)item->parent; + parent = (menuDef_t *)item->parent; if (item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } else { memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t)); } @@ -4740,67 +4274,65 @@ void Item_TextField_Paint(itemDef_t *item) { offset = (item->text && *item->text) ? 8 : 0; if (item->window.flags & WINDOW_HASFOCUS && g_editingField) { char cursor = DC->getOverstrikeMode() ? '_' : '|'; - DC->drawTextWithCursor(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, item->cursorPos - editPtr->paintOffset , cursor, item->window.rect.w, item->textStyle, item->iMenuFont); + DC->drawTextWithCursor(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, + item->cursorPos - editPtr->paintOffset, cursor, item->window.rect.w, item->textStyle, item->iMenuFont); } else { - DC->drawText(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, 0, item->window.rect.w, item->textStyle,item->iMenuFont); + DC->drawText(item->textRect.x + item->textRect.w + offset, item->textRect.y, item->textscale, newColor, buff + editPtr->paintOffset, 0, + item->window.rect.w, item->textStyle, item->iMenuFont); } } void Item_YesNo_Paint(itemDef_t *item) { - char sYES[20]; - char sNO[20]; + char sYES[20]; + char sNO[20]; vec4_t color; float value; const char *yesnovalue; value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0; - trap->SE_GetStringTextString("MENUS_YES",sYES, sizeof(sYES)); - trap->SE_GetStringTextString("MENUS_NO", sNO, sizeof(sNO)); + trap->SE_GetStringTextString("MENUS_YES", sYES, sizeof(sYES)); + trap->SE_GetStringTextString("MENUS_NO", sNO, sizeof(sNO)); -//JLFYESNO MPMOVED + // JLFYESNO MPMOVED if (item->invertYesNo) yesnovalue = (value == 0) ? sYES : sNO; else yesnovalue = (value != 0) ? sYES : sNO; Item_TextColor(item, &color); - if (item->text) - { - Item_Text_Paint(item); - DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, yesnovalue, 0, 0, item->textStyle, item->iMenuFont); - } - else - { - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, yesnovalue , 0, 0, item->textStyle, item->iMenuFont); - } - -/* JLF ORIGINAL CODE if (item->text) { Item_Text_Paint(item); -// DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle); - DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle,item->iMenuFont); + DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, yesnovalue, 0, 0, item->textStyle, item->iMenuFont); } else { -// DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle); - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle,item->iMenuFont); + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, color, yesnovalue, 0, 0, item->textStyle, item->iMenuFont); } -*/ + + /* JLF ORIGINAL CODE + if (item->text) { + Item_Text_Paint(item); + // DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, + item->textStyle); DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, + item->textStyle,item->iMenuFont); } else { + // DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle); + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? sYES : sNO, 0, 0, item->textStyle,item->iMenuFont); + } + */ } void Item_Multi_Paint(itemDef_t *item) { vec4_t color; const char *text = ""; - char temp[MAX_STRING_CHARS]; + char temp[MAX_STRING_CHARS]; text = Item_Multi_Setting(item); - if (*text == '@') // string reference + if (*text == '@') // string reference { - trap->SE_GetStringTextString( &text[1] , temp, sizeof(temp)); + trap->SE_GetStringTextString(&text[1], temp, sizeof(temp)); text = temp; } // Is is specifying a cvar to get the item name from? - else if (*text == '*') - { + else if (*text == '*') { DC->getCVarString(&text[1], temp, sizeof(temp)); text = temp; } @@ -4808,89 +4340,87 @@ void Item_Multi_Paint(itemDef_t *item) { Item_TextColor(item, &color); if (item->text) { Item_Text_Paint(item); - DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, text, 0, 0, item->textStyle,item->iMenuFont); + DC->drawText(item->textRect.x + item->textRect.w + 8, item->textRect.y, item->textscale, color, text, 0, 0, item->textStyle, item->iMenuFont); } else { - //JLF added xoffset - DC->drawText(item->textRect.x+item->xoffset, item->textRect.y, item->textscale, color, text, 0, 0, item->textStyle,item->iMenuFont); - } -} - -static const char *g_bindCommands[] = { - "+altattack", - "+attack", - "+back", - "+button2", - "+force_drain", - "+force_grip", - "+force_lightning", - "+forward", - "+left", - "+lookdown", - "+lookup", - "+mlook", - "+movedown", - "+moveleft", - "+moveright", - "+moveup", - "+right", - "+scores", - "+speed", - "+strafe", - "+use", - "+useforce", - "automap_button", - "automap_toggle", - "bow", - "centerview", - "cg_thirdperson !", - "engage_duel", - "flourish", - "force_absorb", - "force_distract", - "force_forcepowerother", - "force_heal", - "force_healother", - "force_protect", - "force_pull", - "force_rage", - "force_seeing", - "force_speed", - "force_throw", - "forcenext", - "forceprev", - "gloat", - "invnext", - "invprev", - "meditate", - "messagemode", - "messagemode2", - "messagemode3", - "messagemode4", - "saberAttackCycle", - "taunt", - "use_bacta", - "use_electrobinoculars", - "use_field", - "use_seeker", - "use_sentry", - "voicechat", - "weapnext", - "weapon 1", - "weapon 10", - "weapon 11", - "weapon 12", - "weapon 13", - "weapon 2", - "weapon 3", - "weapon 4", - "weapon 5", - "weapon 6", - "weapon 7", - "weapon 8", - "weapon 9", - "weapprev", - "zoom" -}; + // JLF added xoffset + DC->drawText(item->textRect.x + item->xoffset, item->textRect.y, item->textscale, color, text, 0, 0, item->textStyle, item->iMenuFont); + } +} + +static const char *g_bindCommands[] = {"+altattack", + "+attack", + "+back", + "+button2", + "+force_drain", + "+force_grip", + "+force_lightning", + "+forward", + "+left", + "+lookdown", + "+lookup", + "+mlook", + "+movedown", + "+moveleft", + "+moveright", + "+moveup", + "+right", + "+scores", + "+speed", + "+strafe", + "+use", + "+useforce", + "automap_button", + "automap_toggle", + "bow", + "centerview", + "cg_thirdperson !", + "engage_duel", + "flourish", + "force_absorb", + "force_distract", + "force_forcepowerother", + "force_heal", + "force_healother", + "force_protect", + "force_pull", + "force_rage", + "force_seeing", + "force_speed", + "force_throw", + "forcenext", + "forceprev", + "gloat", + "invnext", + "invprev", + "meditate", + "messagemode", + "messagemode2", + "messagemode3", + "messagemode4", + "saberAttackCycle", + "taunt", + "use_bacta", + "use_electrobinoculars", + "use_field", + "use_seeker", + "use_sentry", + "voicechat", + "weapnext", + "weapon 1", + "weapon 10", + "weapon 11", + "weapon 12", + "weapon 13", + "weapon 2", + "weapon 3", + "weapon 4", + "weapon 5", + "weapon 6", + "weapon 7", + "weapon 8", + "weapon 9", + "weapprev", + "zoom"}; #define g_bindCount ARRAY_LEN(g_bindCommands) @@ -4901,21 +4431,20 @@ static int g_bindKeys[g_bindCount][2]; Controls_GetKeyAssignment ================= */ -static void Controls_GetKeyAssignment( const char *command, int *twokeys ) -{ - int count; - int j; - char b[256]; +static void Controls_GetKeyAssignment(const char *command, int *twokeys) { + int count; + int j; + char b[256]; twokeys[0] = twokeys[1] = -1; count = 0; - for ( j=0; jgetBindingBuf( j, b, sizeof( b ) ); - if ( *b && !Q_stricmp( b, command ) ) { + for (j = 0; j < MAX_KEYS; j++) { + DC->getBindingBuf(j, b, sizeof(b)); + if (*b && !Q_stricmp(b, command)) { twokeys[count] = j; count++; - if ( count == 2 ) + if (count == 2) break; } } @@ -4926,13 +4455,12 @@ static void Controls_GetKeyAssignment( const char *command, int *twokeys ) Controls_GetConfig ================= */ -void Controls_GetConfig( void ) -{ - size_t i; +void Controls_GetConfig(void) { + size_t i; // iterate each command, get its numeric binding - for ( i=0; i < g_bindCount; i++ ) - Controls_GetKeyAssignment( g_bindCommands[i], g_bindKeys[i] ); + for (i = 0; i < g_bindCount; i++) + Controls_GetKeyAssignment(g_bindCommands[i], g_bindKeys[i]); } /* @@ -4940,37 +4468,35 @@ void Controls_GetConfig( void ) Controls_SetConfig ================= */ -void Controls_SetConfig( void ) -{ - size_t i; +void Controls_SetConfig(void) { + size_t i; // iterate each command, get its numeric binding - for ( i=0; isetBinding( g_bindKeys[i][0], g_bindCommands[i] ); + for (i = 0; i < g_bindCount; i++) { + if (g_bindKeys[i][0] != -1) { + DC->setBinding(g_bindKeys[i][0], g_bindCommands[i]); - if ( g_bindKeys[i][1] != -1 ) - DC->setBinding( g_bindKeys[i][1], g_bindCommands[i] ); + if (g_bindKeys[i][1] != -1) + DC->setBinding(g_bindKeys[i][1], g_bindCommands[i]); } } } -void Controls_SetDefaults( void ) -{ - size_t i; +void Controls_SetDefaults(void) { + size_t i; - for ( i=0; ikeynumToStringBuf( b1, keyname[0], sizeof( keyname[0] ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(keyname[0]); - DC->keynumToStringBuf( b2, keyname[1], sizeof( keyname[1] ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(keyname[1]); + DC->keynumToStringBuf(b1, keyname[0], sizeof(keyname[0])); + // do NOT do this or it corrupts asian text!!! Q_strupr(keyname[0]); + DC->keynumToStringBuf(b2, keyname[1], sizeof(keyname[1])); + // do NOT do this or it corrupts asian text!!! Q_strupr(keyname[1]); - trap->SE_GetStringTextString( "MENUS_KEYBIND_OR", sOR, sizeof( sOR ) ); + trap->SE_GetStringTextString("MENUS_KEYBIND_OR", sOR, sizeof(sOR)); - Com_sprintf( g_nameBind, sizeof( g_nameBind ), "%s %s %s", keyname[0], sOR, keyname[1] ); - } - else { - DC->keynumToStringBuf( b1, g_nameBind, sizeof( g_nameBind ) ); -// do NOT do this or it corrupts asian text!!! Q_strupr(g_nameBind); + Com_sprintf(g_nameBind, sizeof(g_nameBind), "%s %s %s", keyname[0], sOR, keyname[1]); + } else { + DC->keynumToStringBuf(b1, g_nameBind, sizeof(g_nameBind)); + // do NOT do this or it corrupts asian text!!! Q_strupr(g_nameBind); } return; } } - Q_strncpyz( g_nameBind, "???", sizeof( g_nameBind ) ); + Q_strncpyz(g_nameBind, "???", sizeof(g_nameBind)); } void Item_Slider_Paint(itemDef_t *item) { vec4_t newColor, lowLight; float x, y; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; if (item->window.flags & WINDOW_HASFOCUS) { lowLight[0] = 0.8 * parent->focusColor[0]; lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } else { memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t)); } @@ -5036,177 +4561,158 @@ void Item_Slider_Paint(itemDef_t *item) { x = item->window.rect.x; } DC->setColor(newColor); - DC->drawHandlePic( x, y, SLIDER_WIDTH, SLIDER_HEIGHT, DC->Assets.sliderBar ); + DC->drawHandlePic(x, y, SLIDER_WIDTH, SLIDER_HEIGHT, DC->Assets.sliderBar); x = Item_Slider_ThumbPosition(item); - DC->drawHandlePic( x - (SLIDER_THUMB_WIDTH / 2), y - 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb ); + DC->drawHandlePic(x - (SLIDER_THUMB_WIDTH / 2), y - 2, SLIDER_THUMB_WIDTH, SLIDER_THUMB_HEIGHT, DC->Assets.sliderThumb); } -void Item_Bind_Paint(itemDef_t *item) -{ +void Item_Bind_Paint(itemDef_t *item) { vec4_t newColor, lowLight; float value; int maxChars = 0; - float textScale,textWidth; - int textHeight,yAdj,startingXPos; + float textScale, textWidth; + int textHeight, yAdj, startingXPos; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; editFieldDef_t *editPtr = item->typeData.edit; - if (editPtr) - { + if (editPtr) { maxChars = editPtr->maxPaintChars; } value = (item->cvar) ? DC->getCVarValue(item->cvar) : 0; - if (item->window.flags & WINDOW_HASFOCUS) - { - if (g_bindItem == item) - { + if (item->window.flags & WINDOW_HASFOCUS) { + if (g_bindItem == item) { lowLight[0] = 0.8f * 1.0f; lowLight[1] = 0.8f * 0.0f; lowLight[2] = 0.8f * 0.0f; lowLight[3] = 0.8f * 1.0f; - } - else - { + } else { lowLight[0] = 0.8f * parent->focusColor[0]; lowLight[1] = 0.8f * parent->focusColor[1]; lowLight[2] = 0.8f * parent->focusColor[2]; lowLight[3] = 0.8f * parent->focusColor[3]; } - LerpColor(parent->focusColor,lowLight,newColor,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } - else - { + LerpColor(parent->focusColor, lowLight, newColor, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else { memcpy(&newColor, &item->window.foreColor, sizeof(vec4_t)); } - if (item->text) - { + if (item->text) { Item_Text_Paint(item); BindingFromName(item->cvar); // If the text runs past the limit bring the scale down until it fits. textScale = item->textscale; - textWidth = DC->textWidth(g_nameBind,(float) textScale, item->iMenuFont); + textWidth = DC->textWidth(g_nameBind, (float)textScale, item->iMenuFont); startingXPos = (item->textRect.x + item->textRect.w + 8); - while ((startingXPos + textWidth) >= SCREEN_WIDTH) - { + while ((startingXPos + textWidth) >= SCREEN_WIDTH) { textScale -= .05f; - textWidth = DC->textWidth(g_nameBind,(float) textScale, item->iMenuFont); + textWidth = DC->textWidth(g_nameBind, (float)textScale, item->iMenuFont); } // Try to adjust it's y placement if the scale has changed. yAdj = 0; - if (textScale != item->textscale) - { + if (textScale != item->textscale) { textHeight = DC->textHeight(g_nameBind, item->textscale, item->iMenuFont); yAdj = textHeight - DC->textHeight(g_nameBind, textScale, item->iMenuFont); } - DC->drawText(startingXPos, item->textRect.y + yAdj, textScale, newColor, g_nameBind, 0, maxChars, item->textStyle,item->iMenuFont); - } - else - { - DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "FIXME" : "FIXME", 0, maxChars, item->textStyle,item->iMenuFont); + DC->drawText(startingXPos, item->textRect.y + yAdj, textScale, newColor, g_nameBind, 0, maxChars, item->textStyle, item->iMenuFont); + } else { + DC->drawText(item->textRect.x, item->textRect.y, item->textscale, newColor, (value != 0) ? "FIXME" : "FIXME", 0, maxChars, item->textStyle, + item->iMenuFont); } } -qboolean Display_KeyBindPending( void ) { - return g_waitingForKey; -} +qboolean Display_KeyBindPending(void) { return g_waitingForKey; } qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) { int id; - if ( key == A_MOUSE1 && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && !g_waitingForKey ) { + if (key == A_MOUSE1 && Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory) && !g_waitingForKey) { if (down) { g_waitingForKey = qtrue; g_bindItem = item; } return qtrue; - } - else if ( key == A_ENTER && !g_waitingForKey ) { - if ( down ) { + } else if (key == A_ENTER && !g_waitingForKey) { + if (down) { g_waitingForKey = qtrue; g_bindItem = item; } return qtrue; - } - else { - if ( !g_waitingForKey || g_bindItem == NULL ) { + } else { + if (!g_waitingForKey || g_bindItem == NULL) { return qfalse; } - if ( key & K_CHAR_FLAG ) { + if (key & K_CHAR_FLAG) { return qtrue; } - switch ( key ) { - case A_ESCAPE: - g_waitingForKey = qfalse; - return qtrue; + switch (key) { + case A_ESCAPE: + g_waitingForKey = qfalse; + return qtrue; - case A_BACKSPACE: - id = BindingIDFromName(item->cvar); - if (id != -1) - { - if ( g_bindKeys[id][0] != -1 ) - DC->setBinding(g_bindKeys[id][0], ""); + case A_BACKSPACE: + id = BindingIDFromName(item->cvar); + if (id != -1) { + if (g_bindKeys[id][0] != -1) + DC->setBinding(g_bindKeys[id][0], ""); - if ( g_bindKeys[id][1] != -1 ) - DC->setBinding(g_bindKeys[id][1], ""); + if (g_bindKeys[id][1] != -1) + DC->setBinding(g_bindKeys[id][1], ""); - g_bindKeys[id][0] = -1; - g_bindKeys[id][1] = -1; - } - Controls_SetConfig(); - g_waitingForKey = qfalse; - g_bindItem = NULL; - return qtrue; + g_bindKeys[id][0] = -1; + g_bindKeys[id][1] = -1; + } + Controls_SetConfig(); + g_waitingForKey = qfalse; + g_bindItem = NULL; + return qtrue; - case '`': - return qtrue; + case '`': + return qtrue; } } - if ( key != -1 ) { - size_t i; + if (key != -1) { + size_t i; - for ( i=0; icvar ); + id = BindingIDFromName(item->cvar); - if ( id != -1 ) { - if ( key == -1 ) { - if( g_bindKeys[id][0] != -1 ) { - DC->setBinding( g_bindKeys[id][0], "" ); + if (id != -1) { + if (key == -1) { + if (g_bindKeys[id][0] != -1) { + DC->setBinding(g_bindKeys[id][0], ""); g_bindKeys[id][0] = -1; } - if( g_bindKeys[id][1] != -1 ) { - DC->setBinding( g_bindKeys[id][1], "" ); + if (g_bindKeys[id][1] != -1) { + DC->setBinding(g_bindKeys[id][1], ""); g_bindKeys[id][1] = -1; } - } - else if ( g_bindKeys[id][0] == -1 ) + } else if (g_bindKeys[id][0] == -1) g_bindKeys[id][0] = key; - else if ( g_bindKeys[id][0] != key && g_bindKeys[id][1] == -1 ) + else if (g_bindKeys[id][0] != key && g_bindKeys[id][1] == -1) g_bindKeys[id][1] = key; else { - DC->setBinding( g_bindKeys[id][0], "" ); - DC->setBinding( g_bindKeys[id][1], "" ); + DC->setBinding(g_bindKeys[id][0], ""); + DC->setBinding(g_bindKeys[id][1], ""); g_bindKeys[id][0] = key; g_bindKeys[id][1] = -1; } @@ -5219,161 +4725,146 @@ qboolean Item_Bind_HandleKey(itemDef_t *item, int key, qboolean down) { } // scale the model should we need to -void UI_ScaleModelAxis( refEntity_t *ent ) -{ - if ( ent->modelScale[0] && ent->modelScale[0] != 1.0f ) { - VectorScale( ent->axis[0], ent->modelScale[0] , ent->axis[0] ); +void UI_ScaleModelAxis(refEntity_t *ent) { + if (ent->modelScale[0] && ent->modelScale[0] != 1.0f) { + VectorScale(ent->axis[0], ent->modelScale[0], ent->axis[0]); ent->nonNormalizedAxes = qtrue; } - if ( ent->modelScale[1] && ent->modelScale[1] != 1.0f ) { - VectorScale( ent->axis[1], ent->modelScale[1] , ent->axis[1] ); + if (ent->modelScale[1] && ent->modelScale[1] != 1.0f) { + VectorScale(ent->axis[1], ent->modelScale[1], ent->axis[1]); ent->nonNormalizedAxes = qtrue; } - if ( ent->modelScale[2] && ent->modelScale[2] != 1.0f ) { - VectorScale( ent->axis[2], ent->modelScale[2] , ent->axis[2] ); + if (ent->modelScale[2] && ent->modelScale[2] != 1.0f) { + VectorScale(ent->axis[2], ent->modelScale[2], ent->axis[2]); ent->nonNormalizedAxes = qtrue; } } #ifndef _CGAME -extern void UI_SaberAttachToChar( itemDef_t *item ); +extern void UI_SaberAttachToChar(itemDef_t *item); #endif -void Item_Model_Paint(itemDef_t *item) -{ +void Item_Model_Paint(itemDef_t *item) { float x, y, w, h; refdef_t refdef; - refEntity_t ent; - vec3_t mins, maxs, origin; - vec3_t angles; + refEntity_t ent; + vec3_t mins, maxs, origin; + vec3_t angles; modelDef_t *modelPtr = item->typeData.model; - if (modelPtr == NULL) - { + if (modelPtr == NULL) { return; } // a moves datapad anim is playing #ifdef UI_BUILD - if (uiInfo.moveAnimTime && (uiInfo.moveAnimTime < uiInfo.uiDC.realTime)) - { - if (modelPtr) - { + if (uiInfo.moveAnimTime && (uiInfo.moveAnimTime < uiInfo.uiDC.realTime)) { + if (modelPtr) { char modelPath[MAX_QPATH]; - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", UI_Cvar_VariableString ( "ui_char_model" ) ); - //HACKHACKHACK: check for any multi-part anim sequences, and play the next anim, if needbe - switch( modelPtr->g2anim ) - { + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", UI_Cvar_VariableString("ui_char_model")); + // HACKHACKHACK: check for any multi-part anim sequences, and play the next anim, if needbe + switch (modelPtr->g2anim) { case BOTH_FORCEWALLREBOUND_FORWARD: case BOTH_FORCEJUMP1: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCEINAIR1].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); - if ( !uiInfo.moveAnimTime ) - { + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCEINAIR1].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); + if (!uiInfo.moveAnimTime) { uiInfo.moveAnimTime = 500; } uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCEINAIR1: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCELAND1].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCELAND1].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCEWALLRUNFLIP_START: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCEWALLRUNFLIP_END].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCEWALLRUNFLIP_END].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; case BOTH_FORCELONGLEAP_START: - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCELONGLEAP_LAND].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCELONGLEAP_LAND].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN3://on front - into force getup - trap->S_StartLocalSound( uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_FORCE_GETUP_F1].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + case BOTH_KNOCKDOWN3: // on front - into force getup + trap->S_StartLocalSound(uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_FORCE_GETUP_F1].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN2://on back - kick forward getup - trap->S_StartLocalSound( uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_GETUP_BROLL_F].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + case BOTH_KNOCKDOWN2: // on back - kick forward getup + trap->S_StartLocalSound(uiInfo.uiDC.Assets.moveJumpSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_GETUP_BROLL_F].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; - case BOTH_KNOCKDOWN1://on back - roll-away - trap->S_StartLocalSound( uiInfo.uiDC.Assets.moveRollSound, CHAN_LOCAL ); - ItemParse_model_g2anim_go( item, animTable[BOTH_GETUP_BROLL_R].name ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + case BOTH_KNOCKDOWN1: // on back - roll-away + trap->S_StartLocalSound(uiInfo.uiDC.Assets.moveRollSound, CHAN_LOCAL); + ItemParse_model_g2anim_go(item, animTable[BOTH_GETUP_BROLL_R].name); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime += uiInfo.uiDC.realTime; break; default: - ItemParse_model_g2anim_go( item, uiInfo.movesBaseAnim ); - ItemParse_asset_model_go( item, modelPath, &uiInfo.moveAnimTime ); + ItemParse_model_g2anim_go(item, uiInfo.movesBaseAnim); + ItemParse_asset_model_go(item, modelPath, &uiInfo.moveAnimTime); uiInfo.moveAnimTime = 0; break; } UI_UpdateCharacterSkin(); - //update saber models - UI_SaberAttachToChar( item ); + // update saber models + UI_SaberAttachToChar(item); } } #endif // setup the refdef - memset( &refdef, 0, sizeof( refdef ) ); + memset(&refdef, 0, sizeof(refdef)); refdef.rdflags = RDF_NOWORLDMODEL; - AxisClear( refdef.viewaxis ); - x = item->window.rect.x+1; - y = item->window.rect.y+1; - w = item->window.rect.w-2; - h = item->window.rect.h-2; + AxisClear(refdef.viewaxis); + x = item->window.rect.x + 1; + y = item->window.rect.y + 1; + w = item->window.rect.w - 2; + h = item->window.rect.h - 2; refdef.x = x * DC->xscale; refdef.y = y * DC->yscale; refdef.width = w * DC->xscale; refdef.height = h * DC->yscale; - if (item->ghoul2) - { //ghoul2 models don't have bounds, so we have to parse them. + if (item->ghoul2) { // ghoul2 models don't have bounds, so we have to parse them. VectorCopy(modelPtr->g2mins, mins); VectorCopy(modelPtr->g2maxs, maxs); - if (!mins[0] && !mins[1] && !mins[2] && - !maxs[0] && !maxs[1] && !maxs[2]) - { //we'll use defaults then I suppose. + if (!mins[0] && !mins[1] && !mins[2] && !maxs[0] && !maxs[1] && !maxs[2]) { // we'll use defaults then I suppose. VectorSet(mins, -16, -16, -24); VectorSet(maxs, 16, 16, 32); } - } - else - { - DC->modelBounds( item->asset, mins, maxs ); + } else { + DC->modelBounds(item->asset, mins, maxs); } - origin[2] = -0.5 * ( mins[2] + maxs[2] ); - origin[1] = 0.5 * ( mins[1] + maxs[1] ); + origin[2] = -0.5 * (mins[2] + maxs[2]); + origin[1] = 0.5 * (mins[1] + maxs[1]); // calculate distance so the model nearly fills the box - if (qtrue) - { - float len = 0.5 * ( maxs[2] - mins[2] ); - origin[0] = len / 0.268; // len / tan( fov/2 ) - //origin[0] = len / tan(w/2); - } - else - { + if (qtrue) { + float len = 0.5 * (maxs[2] - mins[2]); + origin[0] = len / 0.268; // len / tan( fov/2 ) + // origin[0] = len / tan(w/2); + } else { origin[0] = item->textscale; } refdef.fov_x = (modelPtr->fov_x) ? modelPtr->fov_x : (int)((float)refdef.width / 640.0f * 90.0f); - refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : atan2( refdef.height, refdef.width / tan( refdef.fov_x / 360 * M_PI ) ) * ( 360 / M_PI ); + refdef.fov_y = (modelPtr->fov_y) ? modelPtr->fov_y : atan2(refdef.height, refdef.width / tan(refdef.fov_x / 360 * M_PI)) * (360 / M_PI); - //refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f); - //refdef.fov_y = atan2( refdef.height, refdef.width / tan( refdef.fov_x / 360 * M_PI ) ) * ( 360 / M_PI ); + // refdef.fov_x = (int)((float)refdef.width / 640.0f * 90.0f); + // refdef.fov_y = atan2( refdef.height, refdef.width / tan( refdef.fov_x / 360 * M_PI ) ) * ( 360 / M_PI ); DC->clearScene(); @@ -5381,33 +4872,24 @@ void Item_Model_Paint(itemDef_t *item) // add the model - memset( &ent, 0, sizeof(ent) ); + memset(&ent, 0, sizeof(ent)); // use item storage to track - if ( (item->flags&ITF_ISANYSABER) && !(item->flags&ITF_ISCHARACTER) ) - {//hack to put saber on it's side - if (modelPtr->rotationSpeed) - { - VectorSet( angles, modelPtr->angle+(float)refdef.time/modelPtr->rotationSpeed, 0, 90 ); - } - else - { - VectorSet( angles, modelPtr->angle, 0, 90 ); + if ((item->flags & ITF_ISANYSABER) && !(item->flags & ITF_ISCHARACTER)) { // hack to put saber on it's side + if (modelPtr->rotationSpeed) { + VectorSet(angles, modelPtr->angle + (float)refdef.time / modelPtr->rotationSpeed, 0, 90); + } else { + VectorSet(angles, modelPtr->angle, 0, 90); } - } - else if (modelPtr->rotationSpeed) - { - VectorSet( angles, 0, modelPtr->angle + (float)refdef.time/modelPtr->rotationSpeed, 0 ); - } - else - { - VectorSet( angles, 0, modelPtr->angle, 0 ); + } else if (modelPtr->rotationSpeed) { + VectorSet(angles, 0, modelPtr->angle + (float)refdef.time / modelPtr->rotationSpeed, 0); + } else { + VectorSet(angles, 0, modelPtr->angle, 0); } - AnglesToAxis( angles, ent.axis ); + AnglesToAxis(angles, ent.axis); - if (item->ghoul2) - { + if (item->ghoul2) { ent.ghoul2 = item->ghoul2; ent.radius = 1000; ent.customSkin = modelPtr->g2skin; @@ -5415,50 +4897,42 @@ void Item_Model_Paint(itemDef_t *item) VectorCopy(modelPtr->g2scale, ent.modelScale); UI_ScaleModelAxis(&ent); #ifndef _CGAME - if ( (item->flags&ITF_ISCHARACTER) ) - { + if ((item->flags & ITF_ISCHARACTER)) { ent.shaderRGBA[0] = ui_char_color_red.integer; ent.shaderRGBA[1] = ui_char_color_green.integer; ent.shaderRGBA[2] = ui_char_color_blue.integer; ent.shaderRGBA[3] = 255; -// UI_TalkingHead(item); + // UI_TalkingHead(item); } - if ( item->flags&ITF_ISANYSABER ) - {//UGH, draw the saber blade! - UI_SaberDrawBlades( item, origin, angles ); + if (item->flags & ITF_ISANYSABER) { // UGH, draw the saber blade! + UI_SaberDrawBlades(item, origin, angles); } #endif - } - else - { + } else { ent.hModel = item->asset; } - VectorCopy( origin, ent.origin ); - VectorCopy( ent.origin, ent.oldorigin ); + VectorCopy(origin, ent.origin); + VectorCopy(ent.origin, ent.oldorigin); // Set up lighting - VectorCopy( origin, ent.lightingOrigin ); + VectorCopy(origin, ent.lightingOrigin); ent.renderfx = RF_LIGHTING_ORIGIN | RF_NOSHADOW; - DC->addRefEntityToScene( &ent ); - DC->renderScene( &refdef ); - + DC->addRefEntityToScene(&ent); + DC->renderScene(&refdef); } - void Item_Image_Paint(itemDef_t *item) { if (item == NULL) { return; } - DC->drawHandlePic(item->window.rect.x+1, item->window.rect.y+1, item->window.rect.w-2, item->window.rect.h-2, item->asset); + DC->drawHandlePic(item->window.rect.x + 1, item->window.rect.y + 1, item->window.rect.w - 2, item->window.rect.h - 2, item->asset); } - -void Item_TextScroll_Paint(itemDef_t *item) -{ +void Item_TextScroll_Paint(itemDef_t *item) { char cvartext[1024]; float x, y, size, count, thumb; - int i; + int i; textScrollDef_t *scrollPtr = item->typeData.textscroll; count = scrollPtr->iLineCount; @@ -5471,45 +4945,40 @@ void Item_TextScroll_Paint(itemDef_t *item) scrollPtr->endPos = scrollPtr->startPos; size = item->window.rect.h - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size+1, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, SCROLLBAR_SIZE, size + 1, DC->Assets.scrollBar); y += size - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowDown); // thumb thumb = Item_TextScroll_ThumbDrawPosition(item); - if (thumb > y - SCROLLBAR_SIZE - 1) - { + if (thumb > y - SCROLLBAR_SIZE - 1) { thumb = y - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(x, thumb, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); - if (item->cvar) - { + if (item->cvar) { DC->getCVarString(item->cvar, cvartext, sizeof(cvartext)); item->text = cvartext; - Item_TextScroll_BuildLines ( item ); + Item_TextScroll_BuildLines(item); } // adjust size for item painting size = item->window.rect.h - 2; - x = item->window.rect.x + item->textalignx + 1; - y = item->window.rect.y + item->textaligny + 1; + x = item->window.rect.x + item->textalignx + 1; + y = item->window.rect.y + item->textaligny + 1; - for (i = scrollPtr->startPos; i < count; i++) - { + for (i = scrollPtr->startPos; i < count; i++) { const char *text; text = scrollPtr->pLines[i]; - if (!text) - { + if (!text) { continue; } DC->drawText(x + 4, y, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle, item->iMenuFont); size -= scrollPtr->lineHeight; - if (size < scrollPtr->lineHeight) - { + if (size < scrollPtr->lineHeight) { scrollPtr->drawPadding = scrollPtr->lineHeight - size; break; } @@ -5523,12 +4992,12 @@ void Item_TextScroll_Paint(itemDef_t *item) // Draw routine for list boxes void Item_ListBox_Paint(itemDef_t *item) { - float x, y, sizeWidth, count, i, i2,sizeHeight, thumb; + float x, y, sizeWidth, count, i, i2, sizeHeight, thumb; int startPos; qhandle_t image; qhandle_t optionalImage1, optionalImage2, optionalImage3; listBoxDef_t *listPtr = item->typeData.listbox; -//JLF MPMOVED + // JLF MPMOVED // the listbox is horizontal or vertical and has a fixed size scroll bar going either direction // elements are enumerated from the DC and either text or image handles are acquired from the DC as well @@ -5536,129 +5005,110 @@ void Item_ListBox_Paint(itemDef_t *item) { // there is no clipping available so only the last completely visible item is painted count = DC->feederCount(item->special); - if (listPtr->startPos > (count?count-1:count)) - {//probably changed feeders, so reset + if (listPtr->startPos > (count ? count - 1 : count)) { // probably changed feeders, so reset listPtr->startPos = 0; } -//JLF END - if (item->cursorPos > (count?count-1:count)) - {//probably changed feeders, so reset - item->cursorPos = (count?count-1:count); + // JLF END + if (item->cursorPos > (count ? count - 1 : count)) { // probably changed feeders, so reset + item->cursorPos = (count ? count - 1 : count); // NOTE : might consider moving this to any spot in here we change the cursor position - DC->feederSelection( item->special, item->cursorPos, NULL ); + DC->feederSelection(item->special, item->cursorPos, NULL); } - - // default is vertical if horizontal flag is not here - if (item->window.flags & WINDOW_HORIZONTAL) - { -#ifdef _DEBUG + if (item->window.flags & WINDOW_HORIZONTAL) { +#ifdef _DEBUG const char *text; #endif -//JLF new variable (code just indented) MPMOVED - if (!listPtr->scrollhidden) - { - // draw scrollbar in bottom of the window - // bar - if (Item_ListBox_MaxScroll(item) > 0) - { + // JLF new variable (code just indented) MPMOVED + if (!listPtr->scrollhidden) { + // draw scrollbar in bottom of the window + // bar + if (Item_ListBox_MaxScroll(item) > 0) { x = item->window.rect.x + 1; y = item->window.rect.y + item->window.rect.h - SCROLLBAR_SIZE - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowLeft); x += SCROLLBAR_SIZE - 1; sizeWidth = item->window.rect.w - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, sizeWidth+1, SCROLLBAR_SIZE, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, sizeWidth + 1, SCROLLBAR_SIZE, DC->Assets.scrollBar); x += sizeWidth - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowRight); // thumb - thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item); + thumb = Item_ListBox_ThumbDrawPosition(item); // Item_ListBox_ThumbPosition(item); if (thumb > x - SCROLLBAR_SIZE - 1) { thumb = x - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(thumb, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); - } - else if (listPtr->startPos > 0) - { + } else if (listPtr->startPos > 0) { listPtr->startPos = 0; } } -//JLF end + // JLF end // listPtr->endPos = listPtr->startPos; sizeWidth = item->window.rect.w - 2; // items // size contains max available space - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { // fit = 0; x = item->window.rect.x + 1; y = item->window.rect.y + 1; - for (i = listPtr->startPos; i < count; i++) - { + for (i = listPtr->startPos; i < count; i++) { // always draw at least one // which may overdraw the box if it is too small for the element image = DC->feederItemImage(item->special, i); - if (image) - { + if (image) { #ifndef _CGAME - if (item->window.flags & WINDOW_PLAYERCOLOR) - { - vec4_t color; + if (item->window.flags & WINDOW_PLAYERCOLOR) { + vec4_t color; - color[0] = ui_char_color_red.integer/COLOR_MAX; - color[1] = ui_char_color_green.integer/COLOR_MAX; - color[2] = ui_char_color_blue.integer/COLOR_MAX; + color[0] = ui_char_color_red.integer / COLOR_MAX; + color[1] = ui_char_color_green.integer / COLOR_MAX; + color[2] = ui_char_color_blue.integer / COLOR_MAX; color[3] = 1.0f; DC->setColor(color); } #endif - DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); + DC->drawHandlePic(x + 1, y + 1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); } - if (i == item->cursorPos) - { - DC->drawRect(x, y, listPtr->elementWidth-1, listPtr->elementHeight-1, item->window.borderSize, item->window.borderColor); + if (i == item->cursorPos) { + DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor); } sizeWidth -= listPtr->elementWidth; - if (sizeWidth < listPtr->elementWidth) - { - listPtr->drawPadding = sizeWidth; //listPtr->elementWidth - size; + if (sizeWidth < listPtr->elementWidth) { + listPtr->drawPadding = sizeWidth; // listPtr->elementWidth - size; break; } x += listPtr->elementWidth; listPtr->endPos++; // fit++; } - } - else - { + } else { // } -#ifdef _DEBUG +#ifdef _DEBUG // Show pic name text = DC->feederItemText(item->special, item->cursorPos, 0, &optionalImage1, &optionalImage2, &optionalImage3); - if (text) - { - DC->drawText(item->window.rect.x, item->window.rect.y+item->window.rect.h, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle, item->iMenuFont); + if (text) { + DC->drawText(item->window.rect.x, item->window.rect.y + item->window.rect.h, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle, + item->iMenuFont); } #endif } // A vertical list box - else - { - //JLF new variable (code idented with if) - if (!listPtr->scrollhidden) - { + else { + // JLF new variable (code idented with if) + if (!listPtr->scrollhidden) { // draw scrollbar to right side of the window x = item->window.rect.x + item->window.rect.w - SCROLLBAR_SIZE - 1; - if ( (int)item->special == FEEDER_Q3HEADS ) + if ((int)item->special == FEEDER_Q3HEADS) x -= 2; y = item->window.rect.y + 1; @@ -5667,67 +5117,59 @@ void Item_ListBox_Paint(itemDef_t *item) { listPtr->endPos = listPtr->startPos; sizeHeight = item->window.rect.h - (SCROLLBAR_SIZE * 2); - DC->drawHandlePic(x, y, SCROLLBAR_SIZE, sizeHeight+1, DC->Assets.scrollBar); + DC->drawHandlePic(x, y, SCROLLBAR_SIZE, sizeHeight + 1, DC->Assets.scrollBar); y += sizeHeight - 1; DC->drawHandlePic(x, y, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarArrowDown); // thumb - thumb = Item_ListBox_ThumbDrawPosition(item);//Item_ListBox_ThumbPosition(item); + thumb = Item_ListBox_ThumbDrawPosition(item); // Item_ListBox_ThumbPosition(item); if (thumb > y - SCROLLBAR_SIZE - 1) { thumb = y - SCROLLBAR_SIZE - 1; } DC->drawHandlePic(x, thumb, SCROLLBAR_SIZE, SCROLLBAR_SIZE, DC->Assets.scrollBarThumb); } -//JLF end + // JLF end // adjust size for item painting sizeWidth = item->window.rect.w - 2; sizeHeight = item->window.rect.h - 2; - if (listPtr->elementStyle == LISTBOX_IMAGE) - { + if (listPtr->elementStyle == LISTBOX_IMAGE) { // Multiple rows and columns (since it's more than twice as wide as an element) - if ( item->window.rect.w > (listPtr->elementWidth*2) ) - { + if (item->window.rect.w > (listPtr->elementWidth * 2)) { startPos = listPtr->startPos; x = item->window.rect.x + 1; y = item->window.rect.y + 1; // Next row - for (i2 = startPos; i2 < count; i2++) - { + for (i2 = startPos; i2 < count; i2++) { x = item->window.rect.x + 1; sizeWidth = item->window.rect.w - 2; // print a row - for (i = startPos; i < count; i++) - { + for (i = startPos; i < count; i++) { // always draw at least one // which may overdraw the box if it is too small for the element image = DC->feederItemImage(item->special, i); - if (image) - { - #ifndef _CGAME - if (item->window.flags & WINDOW_PLAYERCOLOR) - { - vec4_t color; - - color[0] = ui_char_color_red.integer/COLOR_MAX; - color[1] = ui_char_color_green.integer/COLOR_MAX; - color[2] = ui_char_color_blue.integer/COLOR_MAX; + if (image) { +#ifndef _CGAME + if (item->window.flags & WINDOW_PLAYERCOLOR) { + vec4_t color; + + color[0] = ui_char_color_red.integer / COLOR_MAX; + color[1] = ui_char_color_green.integer / COLOR_MAX; + color[2] = ui_char_color_blue.integer / COLOR_MAX; color[3] = 1.0f; DC->setColor(color); } - #endif - DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); +#endif + DC->drawHandlePic(x + 1, y + 1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); } - if (i == item->cursorPos) - { - DC->drawRect(x, y, listPtr->elementWidth-1, listPtr->elementHeight-1, item->window.borderSize, item->window.borderColor); + if (i == item->cursorPos) { + DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor); } sizeWidth -= listPtr->elementWidth; - if (sizeWidth < listPtr->elementWidth) - { - listPtr->drawPadding = sizeWidth; //listPtr->elementWidth - size; + if (sizeWidth < listPtr->elementWidth) { + listPtr->drawPadding = sizeWidth; // listPtr->elementWidth - size; break; } x += listPtr->elementWidth; @@ -5735,9 +5177,8 @@ void Item_ListBox_Paint(itemDef_t *item) { } sizeHeight -= listPtr->elementHeight; - if (sizeHeight < listPtr->elementHeight) - { - listPtr->drawPadding = sizeHeight; //listPtr->elementWidth - size; + if (sizeHeight < listPtr->elementHeight) { + listPtr->drawPadding = sizeHeight; // listPtr->elementWidth - size; break; } // NOTE : Is endPos supposed to be valid or not? It was being used as a valid entry but I changed those @@ -5745,33 +5186,27 @@ void Item_ListBox_Paint(itemDef_t *item) { listPtr->endPos++; startPos = listPtr->endPos; y += listPtr->elementHeight; - } } // single column - else - { + else { x = item->window.rect.x + 1; y = item->window.rect.y + 1; - for (i = listPtr->startPos; i < count; i++) - { + for (i = listPtr->startPos; i < count; i++) { // always draw at least one // which may overdraw the box if it is too small for the element image = DC->feederItemImage(item->special, i); - if (image) - { - DC->drawHandlePic(x+1, y+1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); + if (image) { + DC->drawHandlePic(x + 1, y + 1, listPtr->elementWidth - 2, listPtr->elementHeight - 2, image); } - if (i == item->cursorPos) - { + if (i == item->cursorPos) { DC->drawRect(x, y, listPtr->elementWidth - 1, listPtr->elementHeight - 1, item->window.borderSize, item->window.borderColor); } listPtr->endPos++; sizeHeight -= listPtr->elementHeight; - if (sizeHeight < listPtr->elementHeight) - { + if (sizeHeight < listPtr->elementHeight) { listPtr->drawPadding = listPtr->elementHeight - sizeHeight; break; } @@ -5779,100 +5214,91 @@ void Item_ListBox_Paint(itemDef_t *item) { // fit++; } } - } - else - { + } else { x = item->window.rect.x + 1; y = item->window.rect.y + 1; -//JLF MPMOVED + // JLF MPMOVED y = item->window.rect.y + 1 - listPtr->elementHeight; i = listPtr->startPos; for (; i < count; i++) -//JLF END + // JLF END { const char *text; // always draw at least one // which may overdraw the box if it is too small for the element if (listPtr->numColumns > 0) { - int j;//, subX = listPtr->elementHeight; + int j; //, subX = listPtr->elementHeight; - for (j = 0; j < listPtr->numColumns; j++) - { - char temp[MAX_STRING_CHARS]; + for (j = 0; j < listPtr->numColumns; j++) { + char temp[MAX_STRING_CHARS]; int imageStartX = listPtr->columnInfo[j].pos; text = DC->feederItemText(item->special, i, j, &optionalImage1, &optionalImage2, &optionalImage3); - if( !text ) - { + if (!text) { continue; } - if (text[0]=='@') - { - trap->SE_GetStringTextString( &text[1] , temp, sizeof(temp)); + if (text[0] == '@') { + trap->SE_GetStringTextString(&text[1], temp, sizeof(temp)); text = temp; } /* if (optionalImage >= 0) { - DC->drawHandlePic(x + 4 + listPtr->columnInfo[j].pos, y - 1 + listPtr->elementHeight / 2, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); + DC->drawHandlePic(x + 4 + listPtr->columnInfo[j].pos, y - 1 + listPtr->elementHeight / 2, listPtr->columnInfo[j].width, + listPtr->columnInfo[j].width, optionalImage); } else */ - if ( text ) - { -//JLF MPMOVED + if (text) { + // JLF MPMOVED int textyOffset; textyOffset = 0; -// DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, listPtr->columnInfo[j].maxChars, item->textStyle); - //WAS LAST DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y, item->textscale, item->window.foreColor, text, 0, listPtr->columnInfo[j].maxChars, item->textStyle, item->iMenuFont); - DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight+ textyOffset + item->textaligny, item->textscale, item->window.foreColor, text, 0,listPtr->columnInfo[j].maxChars, item->textStyle, item->iMenuFont); - - -//JLF END + // DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight, item->textscale, + //item->window.foreColor, text, 0, listPtr->columnInfo[j].maxChars, item->textStyle); + // WAS LAST DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y, item->textscale, item->window.foreColor, text, 0, + // listPtr->columnInfo[j].maxChars, item->textStyle, item->iMenuFont); + DC->drawText(x + 4 + listPtr->columnInfo[j].pos, y + listPtr->elementHeight + textyOffset + item->textaligny, item->textscale, + item->window.foreColor, text, 0, listPtr->columnInfo[j].maxChars, item->textStyle, item->iMenuFont); + + // JLF END } - if ( j < listPtr->numColumns - 1 ) - { - imageStartX = listPtr->columnInfo[j+1].pos; + if (j < listPtr->numColumns - 1) { + imageStartX = listPtr->columnInfo[j + 1].pos; } - DC->setColor( NULL ); - if (optionalImage3 >= 0) - { - DC->drawHandlePic(imageStartX - listPtr->elementHeight*3, y+listPtr->elementHeight+2, listPtr->elementHeight, listPtr->elementHeight, optionalImage3); + DC->setColor(NULL); + if (optionalImage3 >= 0) { + DC->drawHandlePic(imageStartX - listPtr->elementHeight * 3, y + listPtr->elementHeight + 2, listPtr->elementHeight, + listPtr->elementHeight, optionalImage3); } - if (optionalImage2 >= 0) - { - DC->drawHandlePic(imageStartX - listPtr->elementHeight*2, y+listPtr->elementHeight+2, listPtr->elementHeight, listPtr->elementHeight, optionalImage2); + if (optionalImage2 >= 0) { + DC->drawHandlePic(imageStartX - listPtr->elementHeight * 2, y + listPtr->elementHeight + 2, listPtr->elementHeight, + listPtr->elementHeight, optionalImage2); } - if (optionalImage1 >= 0) - { - DC->drawHandlePic(imageStartX - listPtr->elementHeight, y+listPtr->elementHeight+2, listPtr->elementHeight, listPtr->elementHeight, optionalImage1); + if (optionalImage1 >= 0) { + DC->drawHandlePic(imageStartX - listPtr->elementHeight, y + listPtr->elementHeight + 2, listPtr->elementHeight, + listPtr->elementHeight, optionalImage1); } } - } - else - { - text = DC->feederItemText(item->special, i, 0, &optionalImage1, &optionalImage2, &optionalImage3 ); - if ( optionalImage1 >= 0 || optionalImage2 >= 0 || optionalImage3 >= 0) - { - //DC->drawHandlePic(x + 4 + listPtr->elementHeight, y, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); - } - else if (text) - { -// DC->drawText(x + 4, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle); + } else { + text = DC->feederItemText(item->special, i, 0, &optionalImage1, &optionalImage2, &optionalImage3); + if (optionalImage1 >= 0 || optionalImage2 >= 0 || optionalImage3 >= 0) { + // DC->drawHandlePic(x + 4 + listPtr->elementHeight, y, listPtr->columnInfo[j].width, listPtr->columnInfo[j].width, optionalImage); + } else if (text) { + // DC->drawText(x + 4, y + listPtr->elementHeight, item->textscale, item->window.foreColor, text, 0, 0, + //item->textStyle); DC->drawText(x + 4, y + item->textaligny, item->textscale, item->window.foreColor, text, 0, 0, item->textStyle, item->iMenuFont); } } - if (i == item->cursorPos) - { - DC->fillRect(x + 2, y + listPtr->elementHeight + 2, item->window.rect.w - SCROLLBAR_SIZE - 4, listPtr->elementHeight, item->window.outlineColor); + if (i == item->cursorPos) { + DC->fillRect(x + 2, y + listPtr->elementHeight + 2, item->window.rect.w - SCROLLBAR_SIZE - 4, listPtr->elementHeight, + item->window.outlineColor); } sizeHeight -= listPtr->elementHeight; - if (sizeHeight < listPtr->elementHeight) - { + if (sizeHeight < listPtr->elementHeight) { listPtr->drawPadding = listPtr->elementHeight - sizeHeight; break; } @@ -5884,7 +5310,6 @@ void Item_ListBox_Paint(itemDef_t *item) { } } - void Item_OwnerDraw_Paint(itemDef_t *item) { if (item == NULL) { @@ -5893,7 +5318,7 @@ void Item_OwnerDraw_Paint(itemDef_t *item) { if (DC->ownerDrawItem) { vec4_t color, lowLight; - menuDef_t *parent = (menuDef_t*)item->parent; + menuDef_t *parent = (menuDef_t *)item->parent; Fade(&item->window.flags, &item->window.foreColor[3], parent->fadeClamp, &item->window.nextTime, parent->fadeCycle, qtrue, parent->fadeAmount); memcpy(&color, &item->window.foreColor, sizeof(color)); if (item->numColors > 0 && DC->getValue) { @@ -5913,57 +5338,58 @@ void Item_OwnerDraw_Paint(itemDef_t *item) { lowLight[1] = 0.8 * parent->focusColor[1]; lowLight[2] = 0.8 * parent->focusColor[2]; lowLight[3] = 0.8 * parent->focusColor[3]; - LerpColor(parent->focusColor,lowLight,color,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); - } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime/BLINK_DIVISOR) & 1)) { + LerpColor(parent->focusColor, lowLight, color, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); + } else if (item->textStyle == ITEM_TEXTSTYLE_BLINK && !((DC->realTime / BLINK_DIVISOR) & 1)) { lowLight[0] = 0.8 * item->window.foreColor[0]; lowLight[1] = 0.8 * item->window.foreColor[1]; lowLight[2] = 0.8 * item->window.foreColor[2]; lowLight[3] = 0.8 * item->window.foreColor[3]; - LerpColor(item->window.foreColor,lowLight,color,0.5+0.5*sin((float)(DC->realTime / PULSE_DIVISOR))); + LerpColor(item->window.foreColor, lowLight, color, 0.5 + 0.5 * sin((float)(DC->realTime / PULSE_DIVISOR))); } - if ( item->disabled ) - memcpy( color, parent->disableColor, sizeof( vec4_t ) ); + if (item->disabled) + memcpy(color, parent->disableColor, sizeof(vec4_t)); - if ( item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar( item, CVAR_ENABLE ) ) - memcpy( color, parent->disableColor, sizeof( vec4_t ) ); + if (item->cvarFlags & (CVAR_ENABLE | CVAR_DISABLE) && !Item_EnableShowViaCvar(item, CVAR_ENABLE)) + memcpy(color, parent->disableColor, sizeof(vec4_t)); if (item->text) { Item_Text_Paint(item); - if (item->text[0]) { - // +8 is an offset kludge to properly align owner draw items that have text combined with them - DC->ownerDrawItem(item->textRect.x + item->textRect.w + 8, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle,item->iMenuFont); - } else { - DC->ownerDrawItem(item->textRect.x + item->textRect.w, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle,item->iMenuFont); - } + if (item->text[0]) { + // +8 is an offset kludge to properly align owner draw items that have text combined with them + DC->ownerDrawItem(item->textRect.x + item->textRect.w + 8, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, + item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, + item->window.background, item->textStyle, item->iMenuFont); } else { - DC->ownerDrawItem(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->textalignx, item->textaligny, item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, item->window.background, item->textStyle,item->iMenuFont); + DC->ownerDrawItem(item->textRect.x + item->textRect.w, item->window.rect.y, item->window.rect.w, item->window.rect.h, 0, item->textaligny, + item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, + item->window.background, item->textStyle, item->iMenuFont); + } + } else { + DC->ownerDrawItem(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, item->textalignx, item->textaligny, + item->window.ownerDraw, item->window.ownerDrawFlags, item->alignment, item->special, item->textscale, color, + item->window.background, item->textStyle, item->iMenuFont); } } } - -void Item_Paint(itemDef_t *item) -{ - vec4_t red; +void Item_Paint(itemDef_t *item) { + vec4_t red; menuDef_t *parent; - int xPos,textWidth; - vec4_t color = {1, 1, 1, 1}; + int xPos, textWidth; + vec4_t color = {1, 1, 1, 1}; red[0] = red[3] = 1; red[1] = red[2] = 0; - if (item == NULL) - { + if (item == NULL) { return; } - parent = (menuDef_t*)item->parent; + parent = (menuDef_t *)item->parent; - if (item->window.flags & WINDOW_ORBITING) - { - if (DC->realTime > item->window.nextTime) - { + if (item->window.flags & WINDOW_ORBITING) { + if (DC->realTime > item->window.nextTime) { float rx, ry, a, c, s, w, h; item->window.nextTime = DC->realTime + item->window.offsetTime; @@ -5981,113 +5407,78 @@ void Item_Paint(itemDef_t *item) } } - - if (item->window.flags & WINDOW_INTRANSITION) - { - if (DC->realTime > item->window.nextTime) - { + if (item->window.flags & WINDOW_INTRANSITION) { + if (DC->realTime > item->window.nextTime) { int done = 0; item->window.nextTime = DC->realTime + item->window.offsetTime; // transition the x,y - if (item->window.rectClient.x == item->window.rectEffects.x) - { + if (item->window.rectClient.x == item->window.rectEffects.x) { done++; - } - else - { - if (item->window.rectClient.x < item->window.rectEffects.x) - { + } else { + if (item->window.rectClient.x < item->window.rectEffects.x) { item->window.rectClient.x += item->window.rectEffects2.x; - if (item->window.rectClient.x > item->window.rectEffects.x) - { + if (item->window.rectClient.x > item->window.rectEffects.x) { item->window.rectClient.x = item->window.rectEffects.x; done++; } - } - else - { + } else { item->window.rectClient.x -= item->window.rectEffects2.x; - if (item->window.rectClient.x < item->window.rectEffects.x) - { + if (item->window.rectClient.x < item->window.rectEffects.x) { item->window.rectClient.x = item->window.rectEffects.x; done++; } } } - if (item->window.rectClient.y == item->window.rectEffects.y) - { + if (item->window.rectClient.y == item->window.rectEffects.y) { done++; - } - else - { - if (item->window.rectClient.y < item->window.rectEffects.y) - { + } else { + if (item->window.rectClient.y < item->window.rectEffects.y) { item->window.rectClient.y += item->window.rectEffects2.y; - if (item->window.rectClient.y > item->window.rectEffects.y) - { + if (item->window.rectClient.y > item->window.rectEffects.y) { item->window.rectClient.y = item->window.rectEffects.y; done++; } - } - else - { + } else { item->window.rectClient.y -= item->window.rectEffects2.y; - if (item->window.rectClient.y < item->window.rectEffects.y) - { + if (item->window.rectClient.y < item->window.rectEffects.y) { item->window.rectClient.y = item->window.rectEffects.y; done++; } } } - if (item->window.rectClient.w == item->window.rectEffects.w) - { + if (item->window.rectClient.w == item->window.rectEffects.w) { done++; - } - else - { - if (item->window.rectClient.w < item->window.rectEffects.w) - { + } else { + if (item->window.rectClient.w < item->window.rectEffects.w) { item->window.rectClient.w += item->window.rectEffects2.w; - if (item->window.rectClient.w > item->window.rectEffects.w) - { + if (item->window.rectClient.w > item->window.rectEffects.w) { item->window.rectClient.w = item->window.rectEffects.w; done++; } - } - else - { + } else { item->window.rectClient.w -= item->window.rectEffects2.w; - if (item->window.rectClient.w < item->window.rectEffects.w) - { + if (item->window.rectClient.w < item->window.rectEffects.w) { item->window.rectClient.w = item->window.rectEffects.w; done++; } } } - if (item->window.rectClient.h == item->window.rectEffects.h) - { + if (item->window.rectClient.h == item->window.rectEffects.h) { done++; - } - else - { - if (item->window.rectClient.h < item->window.rectEffects.h) - { + } else { + if (item->window.rectClient.h < item->window.rectEffects.h) { item->window.rectClient.h += item->window.rectEffects2.h; - if (item->window.rectClient.h > item->window.rectEffects.h) - { + if (item->window.rectClient.h > item->window.rectEffects.h) { item->window.rectClient.h = item->window.rectEffects.h; done++; } - } - else - { + } else { item->window.rectClient.h -= item->window.rectEffects2.h; - if (item->window.rectClient.h < item->window.rectEffects.h) - { + if (item->window.rectClient.h < item->window.rectEffects.h) { item->window.rectClient.h = item->window.rectEffects.h; done++; } @@ -6096,265 +5487,187 @@ void Item_Paint(itemDef_t *item) Item_UpdatePosition(item); - if (done == 4) - { + if (done == 4) { item->window.flags &= ~WINDOW_INTRANSITION; } - } } #ifdef _TRANS3 -//JLF begin model transition stuff - if (item->window.flags & WINDOW_INTRANSITIONMODEL) - { - if ( item->type == ITEM_TYPE_MODEL) - { -//fields ing modelptr -// vec3_t g2mins2, g2maxs2, g2minsEffect, g2maxsEffect; -// float fov_x2, fov_y2, fov_Effectx, fov_Effecty; + // JLF begin model transition stuff + if (item->window.flags & WINDOW_INTRANSITIONMODEL) { + if (item->type == ITEM_TYPE_MODEL) { + // fields ing modelptr + // vec3_t g2mins2, g2maxs2, g2minsEffect, g2maxsEffect; + // float fov_x2, fov_y2, fov_Effectx, fov_Effecty; - modelDef_t * modelptr = item->typeData.model; + modelDef_t *modelptr = item->typeData.model; - if (DC->realTime > item->window.nextTime) - { + if (DC->realTime > item->window.nextTime) { int done = 0; item->window.nextTime = DC->realTime + item->window.offsetTime; - -// transition the x,y,z max - if (modelptr->g2maxs[0] == modelptr->g2maxs2[0]) - { + // transition the x,y,z max + if (modelptr->g2maxs[0] == modelptr->g2maxs2[0]) { done++; - } - else - { - if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) - { + } else { + if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) { modelptr->g2maxs[0] += modelptr->g2maxsEffect[0]; - if (modelptr->g2maxs[0] > modelptr->g2maxs2[0]) - { + if (modelptr->g2maxs[0] > modelptr->g2maxs2[0]) { modelptr->g2maxs[0] = modelptr->g2maxs2[0]; done++; } - } - else - { + } else { modelptr->g2maxs[0] -= modelptr->g2maxsEffect[0]; - if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) - { + if (modelptr->g2maxs[0] < modelptr->g2maxs2[0]) { modelptr->g2maxs[0] = modelptr->g2maxs2[0]; done++; } } } -//y - if (modelptr->g2maxs[1] == modelptr->g2maxs2[1]) - { + // y + if (modelptr->g2maxs[1] == modelptr->g2maxs2[1]) { done++; - } - else - { - if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) - { + } else { + if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) { modelptr->g2maxs[1] += modelptr->g2maxsEffect[1]; - if (modelptr->g2maxs[1] > modelptr->g2maxs2[1]) - { + if (modelptr->g2maxs[1] > modelptr->g2maxs2[1]) { modelptr->g2maxs[1] = modelptr->g2maxs2[1]; done++; } - } - else - { + } else { modelptr->g2maxs[1] -= modelptr->g2maxsEffect[1]; - if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) - { + if (modelptr->g2maxs[1] < modelptr->g2maxs2[1]) { modelptr->g2maxs[1] = modelptr->g2maxs2[1]; done++; } } } + // z -//z - - if (modelptr->g2maxs[2] == modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] == modelptr->g2maxs2[2]) { done++; - } - else - { - if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) - { + } else { + if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) { modelptr->g2maxs[2] += modelptr->g2maxsEffect[2]; - if (modelptr->g2maxs[2] > modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] > modelptr->g2maxs2[2]) { modelptr->g2maxs[2] = modelptr->g2maxs2[2]; done++; } - } - else - { + } else { modelptr->g2maxs[2] -= modelptr->g2maxsEffect[2]; - if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) - { + if (modelptr->g2maxs[2] < modelptr->g2maxs2[2]) { modelptr->g2maxs[2] = modelptr->g2maxs2[2]; done++; } } } -// transition the x,y,z min - if (modelptr->g2mins[0] == modelptr->g2mins2[0]) - { + // transition the x,y,z min + if (modelptr->g2mins[0] == modelptr->g2mins2[0]) { done++; - } - else - { - if (modelptr->g2mins[0] < modelptr->g2mins2[0]) - { + } else { + if (modelptr->g2mins[0] < modelptr->g2mins2[0]) { modelptr->g2mins[0] += modelptr->g2minsEffect[0]; - if (modelptr->g2mins[0] > modelptr->g2mins2[0]) - { + if (modelptr->g2mins[0] > modelptr->g2mins2[0]) { modelptr->g2mins[0] = modelptr->g2mins2[0]; done++; } - } - else - { + } else { modelptr->g2mins[0] -= modelptr->g2minsEffect[0]; - if (modelptr->g2mins[0] < modelptr->g2mins2[0]) - { + if (modelptr->g2mins[0] < modelptr->g2mins2[0]) { modelptr->g2mins[0] = modelptr->g2mins2[0]; done++; } } } -//y - if (modelptr->g2mins[1] == modelptr->g2mins2[1]) - { + // y + if (modelptr->g2mins[1] == modelptr->g2mins2[1]) { done++; - } - else - { - if (modelptr->g2mins[1] < modelptr->g2mins2[1]) - { + } else { + if (modelptr->g2mins[1] < modelptr->g2mins2[1]) { modelptr->g2mins[1] += modelptr->g2minsEffect[1]; - if (modelptr->g2mins[1] > modelptr->g2mins2[1]) - { + if (modelptr->g2mins[1] > modelptr->g2mins2[1]) { modelptr->g2mins[1] = modelptr->g2mins2[1]; done++; } - } - else - { + } else { modelptr->g2mins[1] -= modelptr->g2minsEffect[1]; - if (modelptr->g2mins[1] < modelptr->g2mins2[1]) - { + if (modelptr->g2mins[1] < modelptr->g2mins2[1]) { modelptr->g2mins[1] = modelptr->g2mins2[1]; done++; } } } + // z -//z - - if (modelptr->g2mins[2] == modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] == modelptr->g2mins2[2]) { done++; - } - else - { - if (modelptr->g2mins[2] < modelptr->g2mins2[2]) - { + } else { + if (modelptr->g2mins[2] < modelptr->g2mins2[2]) { modelptr->g2mins[2] += modelptr->g2minsEffect[2]; - if (modelptr->g2mins[2] > modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] > modelptr->g2mins2[2]) { modelptr->g2mins[2] = modelptr->g2mins2[2]; done++; } - } - else - { + } else { modelptr->g2mins[2] -= modelptr->g2minsEffect[2]; - if (modelptr->g2mins[2] < modelptr->g2mins2[2]) - { + if (modelptr->g2mins[2] < modelptr->g2mins2[2]) { modelptr->g2mins[2] = modelptr->g2mins2[2]; done++; } } } - - -//fovx - if (modelptr->fov_x == modelptr->fov_x2) - { + // fovx + if (modelptr->fov_x == modelptr->fov_x2) { done++; - } - else - { - if (modelptr->fov_x < modelptr->fov_x2) - { + } else { + if (modelptr->fov_x < modelptr->fov_x2) { modelptr->fov_x += modelptr->fov_Effectx; - if (modelptr->fov_x > modelptr->fov_x2) - { + if (modelptr->fov_x > modelptr->fov_x2) { modelptr->fov_x = modelptr->fov_x2; done++; } - } - else - { + } else { modelptr->fov_x -= modelptr->fov_Effectx; - if (modelptr->fov_x < modelptr->fov_x2) - { + if (modelptr->fov_x < modelptr->fov_x2) { modelptr->fov_x = modelptr->fov_x2; done++; } } } -//fovy - if (modelptr->fov_y == modelptr->fov_y2) - { + // fovy + if (modelptr->fov_y == modelptr->fov_y2) { done++; - } - else - { - if (modelptr->fov_y < modelptr->fov_y2) - { + } else { + if (modelptr->fov_y < modelptr->fov_y2) { modelptr->fov_y += modelptr->fov_Effecty; - if (modelptr->fov_y > modelptr->fov_y2) - { + if (modelptr->fov_y > modelptr->fov_y2) { modelptr->fov_y = modelptr->fov_y2; done++; } - } - else - { + } else { modelptr->fov_y -= modelptr->fov_Effecty; - if (modelptr->fov_y < modelptr->fov_y2) - { + if (modelptr->fov_y < modelptr->fov_y2) { modelptr->fov_y = modelptr->fov_y2; done++; } } } - if (done == 5) - { + if (done == 5) { item->window.flags &= ~WINDOW_INTRANSITIONMODEL; } - } } } #endif -//JLF end transition stuff for models - - + // JLF end transition stuff for models if (item->window.ownerDrawFlags && DC->ownerDrawVisible) { if (!DC->ownerDrawVisible(item->window.ownerDrawFlags)) { @@ -6364,8 +5677,7 @@ void Item_Paint(itemDef_t *item) } } - if (item->disabled && item->disabledHidden) - { + if (item->disabled && item->disabledHidden) { return; } @@ -6375,66 +5687,55 @@ void Item_Paint(itemDef_t *item) } } - if (item->window.flags & WINDOW_TIMEDVISIBLE) { - + if (item->window.flags & WINDOW_TIMEDVISIBLE) { } - if (!(item->window.flags & WINDOW_VISIBLE)) - { + if (!(item->window.flags & WINDOW_VISIBLE)) { return; } - - if (item->window.flags & WINDOW_MOUSEOVER) - { - if (item->descText && !Display_KeyBindPending()) - { + if (item->window.flags & WINDOW_MOUSEOVER) { + if (item->descText && !Display_KeyBindPending()) { // Make DOUBLY sure that this item should have desctext. // NOTE : we can't just check the mouse position on this, what if we TABBED // to the current menu item -- in that case our mouse isn't over the item. // Removing the WINDOW_MOUSEOVER flag just prevents the item's OnExit script from running - // if (!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) - // { // It isn't something that should, because it isn't live anymore. - // item->window.flags &= ~WINDOW_MOUSEOVER; - // } - // else - { // Draw the desctext + // if (!Rect_ContainsPoint(&item->window.rect, DC->cursorx, DC->cursory)) + // { // It isn't something that should, because it isn't live anymore. + // item->window.flags &= ~WINDOW_MOUSEOVER; + // } + // else + { // Draw the desctext const char *textPtr = item->descText; char temp[MAX_STRING_CHARS] = {0}; - if (*textPtr == '@') // string reference + if (*textPtr == '@') // string reference { - trap->SE_GetStringTextString( &textPtr[1], temp, sizeof(temp)); + trap->SE_GetStringTextString(&textPtr[1], temp, sizeof(temp)); textPtr = temp; } Item_TextColor(item, &color); - {// stupid C language + { // stupid C language float fDescScale = parent->descScale ? parent->descScale : 1; float fDescScaleCopy = fDescScale; int iYadj = 0; - while (1) - { - textWidth = DC->textWidth(textPtr,fDescScale, FONT_SMALL2); - - if (parent->descAlignment == ITEM_ALIGN_RIGHT) - { - xPos = parent->descX - textWidth; // Right justify - } - else if (parent->descAlignment == ITEM_ALIGN_CENTER) - { - xPos = parent->descX - (textWidth/2); // Center justify - } - else // Left justify + while (1) { + textWidth = DC->textWidth(textPtr, fDescScale, FONT_SMALL2); + + if (parent->descAlignment == ITEM_ALIGN_RIGHT) { + xPos = parent->descX - textWidth; // Right justify + } else if (parent->descAlignment == ITEM_ALIGN_CENTER) { + xPos = parent->descX - (textWidth / 2); // Center justify + } else // Left justify { xPos = parent->descX; } - if (parent->descAlignment == ITEM_ALIGN_CENTER) - { + if (parent->descAlignment == ITEM_ALIGN_CENTER) { // only this one will auto-shrink the scale until we eventually fit... // - if (xPos + textWidth > (SCREEN_WIDTH-4)) { + if (xPos + textWidth > (SCREEN_WIDTH - 4)) { fDescScale -= 0.001f; continue; } @@ -6442,8 +5743,7 @@ void Item_Paint(itemDef_t *item) // Try to adjust it's y placement if the scale has changed... // - if (fDescScale != fDescScaleCopy) - { + if (fDescScale != fDescScaleCopy) { int iOriginalTextHeight = DC->textHeight(textPtr, fDescScaleCopy, FONT_MEDIUM); iYadj = iOriginalTextHeight - DC->textHeight(textPtr, fDescScale, FONT_MEDIUM); } @@ -6457,24 +5757,17 @@ void Item_Paint(itemDef_t *item) } // paint the rect first.. - Window_Paint(&item->window, parent->fadeAmount , parent->fadeClamp, parent->fadeCycle); + Window_Paint(&item->window, parent->fadeAmount, parent->fadeClamp, parent->fadeCycle); // Draw box to show rectangle extents, in debug mode - if (debugMode) - { + if (debugMode) { vec4_t color; color[1] = color[3] = 1; color[0] = color[2] = 0; - DC->drawRect( - item->window.rect.x, - item->window.rect.y, - item->window.rect.w, - item->window.rect.h, - 1, - color); + DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, color); } - //DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, red); + // DC->drawRect(item->window.rect.x, item->window.rect.y, item->window.rect.w, item->window.rect.h, 1, red); switch (item->type) { case ITEM_TYPE_OWNERDRAW: @@ -6498,11 +5791,11 @@ void Item_Paint(itemDef_t *item) Item_ListBox_Paint(item); break; case ITEM_TYPE_TEXTSCROLL: - Item_TextScroll_Paint ( item ); + Item_TextScroll_Paint(item); break; - //case ITEM_TYPE_IMAGE: - // Item_Image_Paint(item); - // break; + // case ITEM_TYPE_IMAGE: + // Item_Image_Paint(item); + // break; case ITEM_TYPE_MODEL: Item_Model_Paint(item); break; @@ -6522,8 +5815,8 @@ void Item_Paint(itemDef_t *item) break; } - //FIXME: this might be bad - DC->setColor( NULL ); + // FIXME: this might be bad + DC->setColor(NULL); } void Menu_Init(menuDef_t *menu) { @@ -6569,8 +5862,6 @@ void Menu_ScrollFeeder(menuDef_t *menu, int feeder, qboolean down) { } } - - void Menu_SetFeederSelection(menuDef_t *menu, int feeder, int index, const char *name) { if (menu == NULL) { if (name == NULL) { @@ -6597,40 +5888,39 @@ void Menu_SetFeederSelection(menuDef_t *menu, int feeder, int index, const char } } -qboolean Menus_AnyFullScreenVisible( void ) { - int i; - for (i = 0; i < menuCount; i++) { - if (Menus[i].window.flags & WINDOW_VISIBLE && Menus[i].fullScreen) { +qboolean Menus_AnyFullScreenVisible(void) { + int i; + for (i = 0; i < menuCount; i++) { + if (Menus[i].window.flags & WINDOW_VISIBLE && Menus[i].fullScreen) { return qtrue; - } - } - return qfalse; + } + } + return qfalse; } menuDef_t *Menus_ActivateByName(const char *p) { - int i; - menuDef_t *m = NULL; + int i; + menuDef_t *m = NULL; menuDef_t *focus = Menu_GetFocused(); - for (i = 0; i < menuCount; i++) { - if (Q_stricmp(Menus[i].window.name, p) == 0) { - m = &Menus[i]; + for (i = 0; i < menuCount; i++) { + if (Q_stricmp(Menus[i].window.name, p) == 0) { + m = &Menus[i]; Menus_Activate(m); if (openMenuCount < MAX_OPEN_MENUS && focus != NULL) { menuStack[openMenuCount++] = focus; } - } else { - Menus[i].window.flags &= ~WINDOW_HASFOCUS; - } - } + } else { + Menus[i].window.flags &= ~WINDOW_HASFOCUS; + } + } Display_CloseCinematics(); // Want to handle a mouse move on the new menu in case your already over an item - Menu_HandleMouseMove ( m, DC->cursorx, DC->cursory ); + Menu_HandleMouseMove(m, DC->cursorx, DC->cursory); return m; } - void Item_Init(itemDef_t *item) { memset(item, 0, sizeof(itemDef_t)); item->textscale = 0.55f; @@ -6638,20 +5928,20 @@ void Item_Init(itemDef_t *item) { } void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) { - int i, pass; - qboolean focusSet = qfalse; + int i, pass; + qboolean focusSet = qfalse; - itemDef_t *overItem; - if (menu == NULL) { - return; - } + itemDef_t *overItem; + if (menu == NULL) { + return; + } - if (!(menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { - return; - } + if (!(menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { + return; + } if (itemCapture) { - //Item_MouseMove(itemCapture, x, y); + // Item_MouseMove(itemCapture, x, y); return; } @@ -6659,19 +5949,18 @@ void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) { return; } - // FIXME: this is the whole issue of focus vs. mouse over.. - // need a better overall solution as i don't like going through everything twice - for (pass = 0; pass < 2; pass++) { - for (i = 0; i < menu->itemCount; i++) { - // turn off focus each item - // menu->items[i].window.flags &= ~WINDOW_HASFOCUS; + // FIXME: this is the whole issue of focus vs. mouse over.. + // need a better overall solution as i don't like going through everything twice + for (pass = 0; pass < 2; pass++) { + for (i = 0; i < menu->itemCount; i++) { + // turn off focus each item + // menu->items[i].window.flags &= ~WINDOW_HASFOCUS; - if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { - continue; - } + if (!(menu->items[i]->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED))) { + continue; + } - if (menu->items[i]->disabled) - { + if (menu->items[i]->disabled) { continue; } @@ -6684,9 +5973,7 @@ void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) { continue; } - - - if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { + if (Rect_ContainsPoint(&menu->items[i]->window.rect, x, y)) { if (pass == 1) { overItem = menu->items[i]; if (overItem->type == ITEM_TYPE_TEXT && overItem->text) { @@ -6706,13 +5993,12 @@ void Menu_HandleMouseMove(menuDef_t *menu, float x, float y) { } } } - } else if (menu->items[i]->window.flags & WINDOW_MOUSEOVER) { - Item_MouseLeave(menu->items[i]); - Item_SetMouseOver(menu->items[i], qfalse); - } - } - } - + } else if (menu->items[i]->window.flags & WINDOW_MOUSEOVER) { + Item_MouseLeave(menu->items[i]); + Item_SetMouseOver(menu->items[i], qfalse); + } + } + } } void Menu_Paint(menuDef_t *menu, qboolean forcePaint) { @@ -6722,7 +6008,7 @@ void Menu_Paint(menuDef_t *menu, qboolean forcePaint) { return; } - if (!(menu->window.flags & WINDOW_VISIBLE) && !forcePaint) { + if (!(menu->window.flags & WINDOW_VISIBLE) && !forcePaint) { return; } @@ -6738,32 +6024,28 @@ void Menu_Paint(menuDef_t *menu, qboolean forcePaint) { if (menu->fullScreen) { // implies a background shader // FIXME: make sure we have a default shader if fullscreen is set with no background - DC->drawHandlePic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, menu->window.background ); + DC->drawHandlePic(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, menu->window.background); } else if (menu->window.background) { // this allows a background shader without being full screen - //UI_DrawHandlePic(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, menu->backgroundShader); + // UI_DrawHandlePic(menu->window.rect.x, menu->window.rect.y, menu->window.rect.w, menu->window.rect.h, menu->backgroundShader); } // paint the background and or border - Window_Paint(&menu->window, menu->fadeAmount, menu->fadeClamp, menu->fadeCycle ); + Window_Paint(&menu->window, menu->fadeAmount, menu->fadeClamp, menu->fadeCycle); // Loop through all items for the menu and paint them - for (i = 0; i < menu->itemCount; i++) - { - if (!menu->items[i]->appearanceSlot) - { + for (i = 0; i < menu->itemCount; i++) { + if (!menu->items[i]->appearanceSlot) { Item_Paint(menu->items[i]); - } - else // Timed order of appearance + } else // Timed order of appearance { - if (menu->appearanceTime < DC->realTime) // Time to show another item + if (menu->appearanceTime < DC->realTime) // Time to show another item { menu->appearanceTime = DC->realTime + menu->appearanceIncrement; menu->appearanceCnt++; } - if (menu->items[i]->appearanceSlot<=menu->appearanceCnt) - { + if (menu->items[i]->appearanceSlot <= menu->appearanceCnt) { Item_Paint(menu->items[i]); } } @@ -6782,55 +6064,47 @@ void Menu_Paint(menuDef_t *menu, qboolean forcePaint) { Item_ValidateTypeData =============== */ -void Item_ValidateTypeData(itemDef_t *item) -{ - if (item->typeData.data) - { +void Item_ValidateTypeData(itemDef_t *item) { + if (item->typeData.data) { return; } - switch ( item->type ) - { - case ITEM_TYPE_LISTBOX: - { - item->typeData.listbox = (listBoxDef_t *)UI_Alloc(sizeof(listBoxDef_t)); - memset(item->typeData.listbox, 0, sizeof(listBoxDef_t)); - break; - } - case ITEM_TYPE_TEXT: - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_SLIDER: - { - item->typeData.edit = (editFieldDef_t *)UI_Alloc(sizeof(editFieldDef_t)); - memset(item->typeData.edit, 0, sizeof(editFieldDef_t)); + switch (item->type) { + case ITEM_TYPE_LISTBOX: { + item->typeData.listbox = (listBoxDef_t *)UI_Alloc(sizeof(listBoxDef_t)); + memset(item->typeData.listbox, 0, sizeof(listBoxDef_t)); + break; + } + case ITEM_TYPE_TEXT: + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_SLIDER: { + item->typeData.edit = (editFieldDef_t *)UI_Alloc(sizeof(editFieldDef_t)); + memset(item->typeData.edit, 0, sizeof(editFieldDef_t)); - if ( item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD ) - item->typeData.edit->maxPaintChars = MAX_EDITFIELD; - break; - } - case ITEM_TYPE_MULTI: - { - item->typeData.multi = (multiDef_t *)UI_Alloc(sizeof(multiDef_t)); - memset(item->typeData.multi, 0, sizeof(multiDef_t)); - break; - } - case ITEM_TYPE_MODEL: - { - item->typeData.model = (modelDef_t *)UI_Alloc(sizeof(modelDef_t)); - memset(item->typeData.model, 0, sizeof(modelDef_t)); - break; - } - case ITEM_TYPE_TEXTSCROLL: - { - item->typeData.textscroll = (textScrollDef_t *)UI_Alloc(sizeof(textScrollDef_t)); - memset(item->typeData.textscroll, 0, sizeof(textScrollDef_t)); - break; - } - default: - break; + if (item->type == ITEM_TYPE_EDITFIELD || item->type == ITEM_TYPE_NUMERICFIELD) + item->typeData.edit->maxPaintChars = MAX_EDITFIELD; + break; + } + case ITEM_TYPE_MULTI: { + item->typeData.multi = (multiDef_t *)UI_Alloc(sizeof(multiDef_t)); + memset(item->typeData.multi, 0, sizeof(multiDef_t)); + break; + } + case ITEM_TYPE_MODEL: { + item->typeData.model = (modelDef_t *)UI_Alloc(sizeof(modelDef_t)); + memset(item->typeData.model, 0, sizeof(modelDef_t)); + break; + } + case ITEM_TYPE_TEXTSCROLL: { + item->typeData.textscroll = (textScrollDef_t *)UI_Alloc(sizeof(textScrollDef_t)); + memset(item->typeData.textscroll, 0, sizeof(textScrollDef_t)); + break; + } + default: + break; } } @@ -6840,10 +6114,9 @@ Keyword Hash =============== */ -#define KEYWORDHASH_SIZE 512 +#define KEYWORDHASH_SIZE 512 -typedef struct keywordHash_s -{ +typedef struct keywordHash_s { char *keyword; qboolean (*func)(itemDef_t *item, int handle); struct keywordHash_s *next; @@ -6859,7 +6132,7 @@ static int KeywordHash_Key(char *keyword) { else hash += keyword[i] * (119 + i); } - hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE-1); + hash = (hash ^ (hash >> 10) ^ (hash >> 20)) & (KEYWORDHASH_SIZE - 1); return hash; } @@ -6867,17 +6140,16 @@ static void KeywordHash_Add(keywordHash_t *table[], keywordHash_t *key) { int hash; hash = KeywordHash_Key(key->keyword); -/* - if (table[hash]) { - int collision = qtrue; - } -*/ + /* + if (table[hash]) { + int collision = qtrue; + } + */ key->next = table[hash]; table[hash] = key; } -static keywordHash_t *KeywordHash_Find(keywordHash_t *table[], char *keyword) -{ +static keywordHash_t *KeywordHash_Find(keywordHash_t *table[], char *keyword) { keywordHash_t *key; int hash; @@ -6896,7 +6168,7 @@ Item Keyword Parse functions */ // name -qboolean ItemParse_name( itemDef_t *item, int handle ) { +qboolean ItemParse_name(itemDef_t *item, int handle) { if (!PC_String_Parse(handle, &item->window.name)) { return qfalse; } @@ -6904,7 +6176,7 @@ qboolean ItemParse_name( itemDef_t *item, int handle ) { } // name -qboolean ItemParse_focusSound( itemDef_t *item, int handle ) { +qboolean ItemParse_focusSound(itemDef_t *item, int handle) { pc_token_t token; if (!trap->PC_ReadToken(handle, &token)) { return qfalse; @@ -6913,9 +6185,8 @@ qboolean ItemParse_focusSound( itemDef_t *item, int handle ) { return qtrue; } - // text -qboolean ItemParse_text( itemDef_t *item, int handle ) { +qboolean ItemParse_text(itemDef_t *item, int handle) { if (!PC_String_Parse(handle, &item->text)) { return qfalse; } @@ -6928,35 +6199,28 @@ ItemParse_descText text =============== */ -qboolean ItemParse_descText( itemDef_t *item, int handle) -{ +qboolean ItemParse_descText(itemDef_t *item, int handle) { - if (!PC_String_Parse(handle, &item->descText)) - { + if (!PC_String_Parse(handle, &item->descText)) { return qfalse; } return qtrue; - } - /* =============== ItemParse_text text =============== */ -qboolean ItemParse_text2( itemDef_t *item, int handle) -{ +qboolean ItemParse_text2(itemDef_t *item, int handle) { - if (!PC_String_Parse(handle, &item->text2)) - { + if (!PC_String_Parse(handle, &item->text2)) { return qfalse; } return qtrue; - } /* @@ -6964,10 +6228,8 @@ qboolean ItemParse_text2( itemDef_t *item, int handle) ItemParse_text2alignx =============== */ -qboolean ItemParse_text2alignx( itemDef_t *item, int handle) -{ - if (!PC_Float_Parse(handle, &item->text2alignx)) - { +qboolean ItemParse_text2alignx(itemDef_t *item, int handle) { + if (!PC_Float_Parse(handle, &item->text2alignx)) { return qfalse; } return qtrue; @@ -6978,17 +6240,15 @@ qboolean ItemParse_text2alignx( itemDef_t *item, int handle) ItemParse_text2aligny =============== */ -qboolean ItemParse_text2aligny( itemDef_t *item, int handle) -{ - if (!PC_Float_Parse(handle, &item->text2aligny)) - { +qboolean ItemParse_text2aligny(itemDef_t *item, int handle) { + if (!PC_Float_Parse(handle, &item->text2aligny)) { return qfalse; } return qtrue; } // group -qboolean ItemParse_group( itemDef_t *item, int handle ) { +qboolean ItemParse_group(itemDef_t *item, int handle) { if (!PC_String_Parse(handle, &item->window.group)) { return qfalse; } @@ -6997,34 +6257,29 @@ qboolean ItemParse_group( itemDef_t *item, int handle ) { typedef struct uiG2PtrTracker_s uiG2PtrTracker_t; -struct uiG2PtrTracker_s -{ +struct uiG2PtrTracker_s { void *ghoul2; uiG2PtrTracker_t *next; }; uiG2PtrTracker_t *ui_G2PtrTracker = NULL; -//rww - UI G2 shared management functions. +// rww - UI G2 shared management functions. -//Insert the pointer into our chain so we can keep track of it for freeing. -void UI_InsertG2Pointer(void *ghoul2) -{ +// Insert the pointer into our chain so we can keep track of it for freeing. +void UI_InsertG2Pointer(void *ghoul2) { uiG2PtrTracker_t **nextFree = &ui_G2PtrTracker; - while ((*nextFree) && (*nextFree)->ghoul2) - { //check if it has a ghoul2, if not we can reuse it. + while ((*nextFree) && (*nextFree)->ghoul2) { // check if it has a ghoul2, if not we can reuse it. nextFree = &((*nextFree)->next); } - if (!nextFree) - { //shouldn't happen + if (!nextFree) { // shouldn't happen assert(0); return; } - if (!(*nextFree)) - { //if we aren't reusing a chain then allocate space for it. + if (!(*nextFree)) { // if we aren't reusing a chain then allocate space for it. (*nextFree) = (uiG2PtrTracker_t *)BG_Alloc(sizeof(uiG2PtrTracker_t)); (*nextFree)->next = NULL; } @@ -7032,20 +6287,16 @@ void UI_InsertG2Pointer(void *ghoul2) (*nextFree)->ghoul2 = ghoul2; } -//Remove a ghoul2 pointer from the chain if it's there. -void UI_ClearG2Pointer(void *ghoul2) -{ +// Remove a ghoul2 pointer from the chain if it's there. +void UI_ClearG2Pointer(void *ghoul2) { uiG2PtrTracker_t *next = ui_G2PtrTracker; - if (!ghoul2) - { + if (!ghoul2) { return; } - while (next) - { - if (next->ghoul2 == ghoul2) - { //found it, set it to null so we can reuse this link. + while (next) { + if (next->ghoul2 == ghoul2) { // found it, set it to null so we can reuse this link. next->ghoul2 = NULL; break; } @@ -7054,14 +6305,12 @@ void UI_ClearG2Pointer(void *ghoul2) } } -//Called on shutdown, cleans up all the ghoul2 instances laying around. -void UI_CleanupGhoul2(void) -{ +// Called on shutdown, cleans up all the ghoul2 instances laying around. +void UI_CleanupGhoul2(void) { uiG2PtrTracker_t *next = ui_G2PtrTracker; - while (next) - { - if (next->ghoul2 && trap->G2_HaveWeGhoul2Models(next->ghoul2)) //found a g2 instance, clean it. + while (next) { + if (next->ghoul2 && trap->G2_HaveWeGhoul2Models(next->ghoul2)) // found a g2 instance, clean it. trap->G2API_CleanGhoul2Models(&next->ghoul2); next = next->next; @@ -7077,53 +6326,45 @@ ItemParse_asset_model asset_model =============== */ -qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTimeLength ) -{ +qboolean ItemParse_asset_model_go(itemDef_t *item, const char *name, int *runTimeLength) { #ifdef UI_BUILD int g2Model; modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; - *runTimeLength =0.0f; + *runTimeLength = 0.0f; - if (!Q_stricmp(&name[strlen(name) - 4], ".glm")) - { //it's a ghoul2 model then - if ( item->ghoul2 ) - { - UI_ClearG2Pointer(item->ghoul2); //remove from tracking list - trap->G2API_CleanGhoul2Models(&item->ghoul2); //remove ghoul info + if (!Q_stricmp(&name[strlen(name) - 4], ".glm")) { // it's a ghoul2 model then + if (item->ghoul2) { + UI_ClearG2Pointer(item->ghoul2); // remove from tracking list + trap->G2API_CleanGhoul2Models(&item->ghoul2); // remove ghoul info item->flags &= ~ITF_G2VALID; } g2Model = trap->G2API_InitGhoul2Model(&item->ghoul2, name, 0, modelPtr->g2skin, 0, 0, 0); - if (g2Model >= 0) - { - UI_InsertG2Pointer(item->ghoul2); //remember it so we can free it when the ui shuts down. + if (g2Model >= 0) { + UI_InsertG2Pointer(item->ghoul2); // remember it so we can free it when the ui shuts down. item->flags |= ITF_G2VALID; - if (modelPtr->g2anim) - { //does the menu request this model be playing an animation? -// DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim); + if (modelPtr->g2anim) { // does the menu request this model be playing an animation? + // DC->g2hilev_SetAnim(&item->ghoul2[0], "model_root", modelPtr->g2anim); char GLAName[MAX_QPATH]; GLAName[0] = 0; trap->G2API_GetGLAName(item->ghoul2, 0, GLAName); - if (GLAName[0]) - { + if (GLAName[0]) { int animIndex; char *slash; - slash = Q_strrchr( GLAName, '/' ); + slash = Q_strrchr(GLAName, '/'); - if ( slash ) - { //If this isn't true the gla path must be messed up somehow. + if (slash) { // If this isn't true the gla path must be messed up somehow. strcpy(slash, "/animation.cfg"); animIndex = UI_ParseAnimationFile(GLAName, NULL, qfalse); - if (animIndex != -1) - { //We parsed out the animation info for whatever model this is + if (animIndex != -1) { // We parsed out the animation info for whatever model this is animation_t *anim = &bgAllAnims[animIndex].anims[modelPtr->g2anim]; int sFrame = anim->firstFrame; @@ -7133,23 +6374,21 @@ qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTim float animSpeed = 50.0f / anim->frameLerp; int blendTime = 150; - if (anim->loopFrames != -1) - { + if (anim->loopFrames != -1) { flags |= BONE_ANIM_OVERRIDE_LOOP; } trap->G2API_SetBoneAnim(item->ghoul2, 0, "model_root", sFrame, eFrame, flags, animSpeed, time, -1, blendTime); - *runTimeLength =((anim->frameLerp * (anim->numFrames-2))); + *runTimeLength = ((anim->frameLerp * (anim->numFrames - 2))); } } } } - if ( modelPtr->g2skin ) - { -// DC->g2_SetSkin( &item->ghoul2[0], 0, modelPtr->g2skin );//this is going to set the surfs on/off matching the skin file - //trap->G2API_InitGhoul2Model(&item->ghoul2, name, 0, modelPtr->g2skin, 0, 0, 0); - //ahh, what are you doing?! + if (modelPtr->g2skin) { + // DC->g2_SetSkin( &item->ghoul2[0], 0, modelPtr->g2skin );//this is going to set the surfs on/off matching the skin file + // trap->G2API_InitGhoul2Model(&item->ghoul2, name, 0, modelPtr->g2skin, 0, 0, 0); + // ahh, what are you doing?! trap->G2API_SetSkin(item->ghoul2, 0, modelPtr->g2skin, modelPtr->g2skin); } } @@ -7159,9 +6398,7 @@ qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTim Com_Error(ERR_FATAL, "%s does not exist.", name); } */ - } - else if(!(item->asset)) - { //guess it's just an md3 + } else if (!(item->asset)) { // guess it's just an md3 item->asset = DC->registerModel(name); item->flags &= ~ITF_G2VALID; } @@ -7169,7 +6406,7 @@ qboolean ItemParse_asset_model_go( itemDef_t *item, const char *name,int *runTim return qtrue; } -qboolean ItemParse_asset_model( itemDef_t *item, int handle ) { +qboolean ItemParse_asset_model(itemDef_t *item, int handle) { int animRunLength; pc_token_t token; @@ -7180,20 +6417,19 @@ qboolean ItemParse_asset_model( itemDef_t *item, int handle ) { } #ifdef UI_BUILD - if (!Q_stricmp(token.string,"ui_char_model") ) - { + if (!Q_stricmp(token.string, "ui_char_model")) { char modelPath[MAX_QPATH] = {0}; char ui_char_model[MAX_QPATH] = {0}; - trap->Cvar_VariableStringBuffer("ui_char_model", ui_char_model, sizeof(ui_char_model) ); - Com_sprintf( modelPath, sizeof( modelPath ), "models/players/%s/model.glm", ui_char_model ); - return (ItemParse_asset_model_go( item, modelPath, &animRunLength )); + trap->Cvar_VariableStringBuffer("ui_char_model", ui_char_model, sizeof(ui_char_model)); + Com_sprintf(modelPath, sizeof(modelPath), "models/players/%s/model.glm", ui_char_model); + return (ItemParse_asset_model_go(item, modelPath, &animRunLength)); } #endif - return (ItemParse_asset_model_go( item, token.string, &animRunLength )); + return (ItemParse_asset_model_go(item, token.string, &animRunLength)); } // asset_shader -qboolean ItemParse_asset_shader( itemDef_t *item, int handle ) { +qboolean ItemParse_asset_shader(itemDef_t *item, int handle) { pc_token_t token; if (!trap->PC_ReadToken(handle, &token)) { return qfalse; @@ -7203,7 +6439,7 @@ qboolean ItemParse_asset_shader( itemDef_t *item, int handle ) { } // model_origin -qboolean ItemParse_model_origin( itemDef_t *item, int handle ) { +qboolean ItemParse_model_origin(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7219,7 +6455,7 @@ qboolean ItemParse_model_origin( itemDef_t *item, int handle ) { } // model_fovx -qboolean ItemParse_model_fovx( itemDef_t *item, int handle ) { +qboolean ItemParse_model_fovx(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7231,7 +6467,7 @@ qboolean ItemParse_model_fovx( itemDef_t *item, int handle ) { } // model_fovy -qboolean ItemParse_model_fovy( itemDef_t *item, int handle ) { +qboolean ItemParse_model_fovy(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7243,7 +6479,7 @@ qboolean ItemParse_model_fovy( itemDef_t *item, int handle ) { } // model_rotation -qboolean ItemParse_model_rotation( itemDef_t *item, int handle ) { +qboolean ItemParse_model_rotation(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7255,7 +6491,7 @@ qboolean ItemParse_model_rotation( itemDef_t *item, int handle ) { } // model_angle -qboolean ItemParse_model_angle( itemDef_t *item, int handle ) { +qboolean ItemParse_model_angle(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7267,7 +6503,7 @@ qboolean ItemParse_model_angle( itemDef_t *item, int handle ) { } // model_g2mins -qboolean ItemParse_model_g2mins( itemDef_t *item, int handle ) { +qboolean ItemParse_model_g2mins(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7283,7 +6519,7 @@ qboolean ItemParse_model_g2mins( itemDef_t *item, int handle ) { } // model_g2maxs -qboolean ItemParse_model_g2maxs( itemDef_t *item, int handle ) { +qboolean ItemParse_model_g2maxs(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7299,7 +6535,7 @@ qboolean ItemParse_model_g2maxs( itemDef_t *item, int handle ) { } // model_g2scale -qboolean ItemParse_model_g2scale( itemDef_t *item, int handle ) { +qboolean ItemParse_model_g2scale(itemDef_t *item, int handle) { modelDef_t *modelPtr; Item_ValidateTypeData(item); modelPtr = item->typeData.model; @@ -7314,7 +6550,7 @@ qboolean ItemParse_model_g2scale( itemDef_t *item, int handle ) { return qfalse; } -qboolean ItemParse_model_g2skin( itemDef_t *item, int handle ) { +qboolean ItemParse_model_g2skin(itemDef_t *item, int handle) { modelDef_t *modelPtr; pc_token_t token; @@ -7325,8 +6561,7 @@ qboolean ItemParse_model_g2skin( itemDef_t *item, int handle ) { return qfalse; } - if (!token.string[0]) - { //it was parsed correctly so still return true. + if (!token.string[0]) { // it was parsed correctly so still return true. return qtrue; } @@ -7336,7 +6571,7 @@ qboolean ItemParse_model_g2skin( itemDef_t *item, int handle ) { } // model_g2anim -qboolean ItemParse_model_g2anim( itemDef_t *item, int handle ) { +qboolean ItemParse_model_g2anim(itemDef_t *item, int handle) { modelDef_t *modelPtr; pc_token_t token; int i = 0; @@ -7348,15 +6583,12 @@ qboolean ItemParse_model_g2anim( itemDef_t *item, int handle ) { return qfalse; } - if ( !token.string[0]) - { //it was parsed correctly so still return true. + if (!token.string[0]) { // it was parsed correctly so still return true. return qtrue; } - while (i < MAX_ANIMATIONS) - { - if (!Q_stricmp(token.string, animTable[i].name)) - { //found it + while (i < MAX_ANIMATIONS) { + if (!Q_stricmp(token.string, animTable[i].name)) { // found it modelPtr->g2anim = i; return qtrue; } @@ -7368,16 +6600,14 @@ qboolean ItemParse_model_g2anim( itemDef_t *item, int handle ) { } // model_g2skin -qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ) -{ +qboolean ItemParse_model_g2skin_go(itemDef_t *item, const char *skinName) { modelDef_t *modelPtr; int defSkin; Item_ValidateTypeData(item); modelPtr = item->typeData.model; - if (!skinName || !skinName[0]) - { //it was parsed correctly so still return true. + if (!skinName || !skinName[0]) { // it was parsed correctly so still return true. modelPtr->g2skin = 0; trap->G2API_SetSkin(item->ghoul2, 0, 0, 0); @@ -7385,8 +6615,7 @@ qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ) } // set skin - if ( item->ghoul2 ) - { + if (item->ghoul2) { defSkin = trap->R_RegisterSkin(skinName); trap->G2API_SetSkin(item->ghoul2, 0, defSkin, defSkin); } @@ -7395,23 +6624,19 @@ qboolean ItemParse_model_g2skin_go( itemDef_t *item, const char *skinName ) } // model_g2anim -qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ) -{ +qboolean ItemParse_model_g2anim_go(itemDef_t *item, const char *animName) { modelDef_t *modelPtr; int i = 0; Item_ValidateTypeData(item); modelPtr = item->typeData.model; - if (!animName || !animName[0]) - { //it was parsed correctly so still return true. + if (!animName || !animName[0]) { // it was parsed correctly so still return true. return qtrue; } - while (i < MAX_ANIMATIONS) - { - if (!Q_stricmp(animName, animTable[i].name)) - { //found it + while (i < MAX_ANIMATIONS) { + if (!Q_stricmp(animName, animTable[i].name)) { // found it modelPtr->g2anim = animTable[i].id; return qtrue; } @@ -7423,16 +6648,14 @@ qboolean ItemParse_model_g2anim_go( itemDef_t *item, const char *animName ) } // Get the cvar, get the values and stuff them in the rect structure. -qboolean ItemParse_rectcvar( itemDef_t *item, int handle ) -{ - char cvarBuf[1024]; - const char *holdVal; - char *holdBuf; +qboolean ItemParse_rectcvar(itemDef_t *item, int handle) { + char cvarBuf[1024]; + const char *holdVal; + char *holdBuf; // get Cvar name pc_token_t token; - if (!trap->PC_ReadToken(handle, &token)) - { + if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } @@ -7440,17 +6663,13 @@ qboolean ItemParse_rectcvar( itemDef_t *item, int handle ) DC->getCVarString(token.string, cvarBuf, sizeof(cvarBuf)); holdBuf = cvarBuf; - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.x = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.y = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.w = atof(holdVal); - if (String_Parse(&holdBuf,&holdVal)) - { + if (String_Parse(&holdBuf, &holdVal)) { item->window.rectClient.h = atof(holdVal); return qtrue; } @@ -7463,7 +6682,7 @@ qboolean ItemParse_rectcvar( itemDef_t *item, int handle ) } // rect -qboolean ItemParse_rect( itemDef_t *item, int handle ) { +qboolean ItemParse_rect(itemDef_t *item, int handle) { if (!PC_Rect_Parse(handle, &item->window.rectClient)) { return qfalse; } @@ -7476,28 +6695,23 @@ ItemParse_flag flag =============== */ -qboolean ItemParse_flag( itemDef_t *item, int handle) -{ +qboolean ItemParse_flag(itemDef_t *item, int handle) { int i; pc_token_t token; - if (!trap->PC_ReadToken(handle, &token)) - { + if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - for ( i=0; itemFlags[i].string; i++ ) - { - if (Q_stricmp(token.string,itemFlags[i].string)==0) - { + for (i = 0; itemFlags[i].string; i++) { + if (Q_stricmp(token.string, itemFlags[i].string) == 0) { item->window.flags |= itemFlags[i].value; break; } } - if (itemFlags[i].string == NULL) - { - Com_Printf( S_COLOR_YELLOW "Unknown item style value '%s'\n", token.string ); + if (itemFlags[i].string == NULL) { + Com_Printf(S_COLOR_YELLOW "Unknown item style value '%s'\n", token.string); } return qtrue; @@ -7509,10 +6723,8 @@ ItemParse_style style =============== */ -qboolean ItemParse_style( itemDef_t *item, int handle) -{ - if (!PC_Int_Parse(handle, &item->window.style)) - { +qboolean ItemParse_style(itemDef_t *item, int handle) { + if (!PC_Int_Parse(handle, &item->window.style)) { Com_Printf(S_COLOR_YELLOW "Unknown item style value\n"); return qfalse; } @@ -7521,13 +6733,13 @@ qboolean ItemParse_style( itemDef_t *item, int handle) } // decoration -qboolean ItemParse_decoration( itemDef_t *item, int handle ) { +qboolean ItemParse_decoration(itemDef_t *item, int handle) { item->window.flags |= WINDOW_DECORATION; return qtrue; } // notselectable -qboolean ItemParse_notselectable( itemDef_t *item, int handle ) { +qboolean ItemParse_notselectable(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); listPtr = item->typeData.listbox; @@ -7543,33 +6755,31 @@ ItemParse_scrollhidden scrollhidden =============== */ -qboolean ItemParse_scrollhidden( itemDef_t *item , int handle) -{ +qboolean ItemParse_scrollhidden(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); listPtr = item->typeData.listbox; - if (item->type == ITEM_TYPE_LISTBOX && listPtr) - { + if (item->type == ITEM_TYPE_LISTBOX && listPtr) { listPtr->scrollhidden = qtrue; } return qtrue; } // manually wrapped -qboolean ItemParse_wrapped( itemDef_t *item, int handle ) { +qboolean ItemParse_wrapped(itemDef_t *item, int handle) { item->window.flags |= WINDOW_WRAPPED; return qtrue; } // auto wrapped -qboolean ItemParse_autowrapped( itemDef_t *item, int handle ) { +qboolean ItemParse_autowrapped(itemDef_t *item, int handle) { item->window.flags |= WINDOW_AUTOWRAPPED; return qtrue; } // horizontalscroll -qboolean ItemParse_horizontalscroll( itemDef_t *item, int handle ) { +qboolean ItemParse_horizontalscroll(itemDef_t *item, int handle) { item->window.flags |= WINDOW_HORIZONTAL; return qtrue; } @@ -7580,10 +6790,8 @@ ItemParse_type type =============== */ -qboolean ItemParse_type( itemDef_t *item, int handle ) -{ - if (!PC_Int_Parse(handle, &item->type)) - { +qboolean ItemParse_type(itemDef_t *item, int handle) { + if (!PC_Int_Parse(handle, &item->type)) { return qfalse; } Item_ValidateTypeData(item); @@ -7592,7 +6800,7 @@ qboolean ItemParse_type( itemDef_t *item, int handle ) // elementwidth, used for listbox image elements // uses textalignx for storage -qboolean ItemParse_elementwidth( itemDef_t *item, int handle ) { +qboolean ItemParse_elementwidth(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); @@ -7605,7 +6813,7 @@ qboolean ItemParse_elementwidth( itemDef_t *item, int handle ) { // elementheight, used for listbox image elements // uses textaligny for storage -qboolean ItemParse_elementheight( itemDef_t *item, int handle ) { +qboolean ItemParse_elementheight(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); @@ -7617,7 +6825,7 @@ qboolean ItemParse_elementheight( itemDef_t *item, int handle ) { } // feeder -qboolean ItemParse_feeder( itemDef_t *item, int handle ) { +qboolean ItemParse_feeder(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->special)) { return qfalse; } @@ -7626,7 +6834,7 @@ qboolean ItemParse_feeder( itemDef_t *item, int handle ) { // elementtype, used to specify what type of elements a listbox contains // uses textstyle for storage -qboolean ItemParse_elementtype( itemDef_t *item, int handle ) { +qboolean ItemParse_elementtype(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); @@ -7638,7 +6846,7 @@ qboolean ItemParse_elementtype( itemDef_t *item, int handle ) { } // columns sets a number of columns and an x pos and width per.. -qboolean ItemParse_columns( itemDef_t *item, int handle ) { +qboolean ItemParse_columns(itemDef_t *item, int handle) { int i; listBoxDef_t *listPtr; @@ -7665,21 +6873,21 @@ qboolean ItemParse_columns( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_border( itemDef_t *item, int handle ) { +qboolean ItemParse_border(itemDef_t *item, int handle) { if (!PC_Int_Parse(handle, &item->window.border)) { return qfalse; } return qtrue; } -qboolean ItemParse_bordersize( itemDef_t *item, int handle ) { +qboolean ItemParse_bordersize(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->window.borderSize)) { return qfalse; } return qtrue; } -qboolean ItemParse_visible( itemDef_t *item, int handle ) { +qboolean ItemParse_visible(itemDef_t *item, int handle) { int i; if (!PC_Int_Parse(handle, &i)) { @@ -7691,7 +6899,7 @@ qboolean ItemParse_visible( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_ownerdraw( itemDef_t *item, int handle ) { +qboolean ItemParse_ownerdraw(itemDef_t *item, int handle) { if (!PC_Int_Parse(handle, &item->window.ownerDraw)) { return qfalse; } @@ -7699,7 +6907,7 @@ qboolean ItemParse_ownerdraw( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_align( itemDef_t *item, int handle ) { +qboolean ItemParse_align(itemDef_t *item, int handle) { if (!PC_Int_Parse(handle, &item->alignment)) { return qfalse; } @@ -7713,18 +6921,13 @@ ItemParse_isCharacter Sets item flag showing this is a character =============== */ -qboolean ItemParse_isCharacter( itemDef_t *item, int handle ) -{ +qboolean ItemParse_isCharacter(itemDef_t *item, int handle) { int flag; - if (PC_Int_Parse(handle, &flag)) - { - if ( flag ) - { + if (PC_Int_Parse(handle, &flag)) { + if (flag) { item->flags |= ITF_ISCHARACTER; - } - else - { + } else { item->flags &= ~ITF_ISCHARACTER; } return qtrue; @@ -7737,10 +6940,8 @@ qboolean ItemParse_isCharacter( itemDef_t *item, int handle ) ItemParse_textalign =============== */ -qboolean ItemParse_textalign( itemDef_t *item, int handle ) -{ - if (!PC_Int_Parse(handle, &item->textalignment)) - { +qboolean ItemParse_textalign(itemDef_t *item, int handle) { + if (!PC_Int_Parse(handle, &item->textalignment)) { Com_Printf(S_COLOR_YELLOW "Unknown text alignment value\n"); return qfalse; @@ -7749,28 +6950,28 @@ qboolean ItemParse_textalign( itemDef_t *item, int handle ) return qtrue; } -qboolean ItemParse_textalignx( itemDef_t *item, int handle ) { +qboolean ItemParse_textalignx(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->textalignx)) { return qfalse; } return qtrue; } -qboolean ItemParse_textaligny( itemDef_t *item, int handle ) { +qboolean ItemParse_textaligny(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->textaligny)) { return qfalse; } return qtrue; } -qboolean ItemParse_textscale( itemDef_t *item, int handle ) { +qboolean ItemParse_textscale(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->textscale)) { return qfalse; } return qtrue; } -qboolean ItemParse_textstyle( itemDef_t *item, int handle ) { +qboolean ItemParse_textstyle(itemDef_t *item, int handle) { if (!PC_Int_Parse(handle, &item->textStyle)) { return qfalse; } @@ -7782,11 +6983,9 @@ qboolean ItemParse_textstyle( itemDef_t *item, int handle ) { ItemParse_invertyesno =============== */ -//JLFYESNO MPMOVED -qboolean ItemParse_invertyesno( itemDef_t *item, int handle) -{ - if (!PC_Int_Parse(handle, &item->invertYesNo)) - { +// JLFYESNO MPMOVED +qboolean ItemParse_invertyesno(itemDef_t *item, int handle) { + if (!PC_Int_Parse(handle, &item->invertYesNo)) { return qfalse; } return qtrue; @@ -7797,17 +6996,14 @@ qboolean ItemParse_invertyesno( itemDef_t *item, int handle) ItemParse_xoffset (used for yes/no and multi) =============== */ -qboolean ItemParse_xoffset( itemDef_t *item, int handle) -{ - if (PC_Int_Parse(handle, &item->xoffset)) - { +qboolean ItemParse_xoffset(itemDef_t *item, int handle) { + if (PC_Int_Parse(handle, &item->xoffset)) { return qfalse; } return qtrue; } - -qboolean ItemParse_backcolor( itemDef_t *item, int handle ) { +qboolean ItemParse_backcolor(itemDef_t *item, int handle) { int i; float f; @@ -7815,12 +7011,12 @@ qboolean ItemParse_backcolor( itemDef_t *item, int handle ) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - item->window.backColor[i] = f; + item->window.backColor[i] = f; } return qtrue; } -qboolean ItemParse_forecolor( itemDef_t *item, int handle ) { +qboolean ItemParse_forecolor(itemDef_t *item, int handle) { int i; float f; @@ -7829,19 +7025,18 @@ qboolean ItemParse_forecolor( itemDef_t *item, int handle ) { return qfalse; } - if (f < 0) - { //special case for player color + if (f < 0) { // special case for player color item->window.flags |= WINDOW_PLAYERCOLOR; return qtrue; } - item->window.foreColor[i] = f; + item->window.foreColor[i] = f; item->window.flags |= WINDOW_FORECOLORSET; } return qtrue; } -qboolean ItemParse_bordercolor( itemDef_t *item, int handle ) { +qboolean ItemParse_bordercolor(itemDef_t *item, int handle) { int i; float f; @@ -7849,19 +7044,19 @@ qboolean ItemParse_bordercolor( itemDef_t *item, int handle ) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - item->window.borderColor[i] = f; + item->window.borderColor[i] = f; } return qtrue; } -qboolean ItemParse_outlinecolor( itemDef_t *item, int handle ) { - if (!PC_Color_Parse(handle, &item->window.outlineColor)){ +qboolean ItemParse_outlinecolor(itemDef_t *item, int handle) { + if (!PC_Color_Parse(handle, &item->window.outlineColor)) { return qfalse; } return qtrue; } -qboolean ItemParse_background( itemDef_t *item, int handle ) { +qboolean ItemParse_background(itemDef_t *item, int handle) { pc_token_t token; if (!trap->PC_ReadToken(handle, &token)) { @@ -7871,14 +7066,14 @@ qboolean ItemParse_background( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_cinematic( itemDef_t *item, int handle ) { +qboolean ItemParse_cinematic(itemDef_t *item, int handle) { if (!PC_String_Parse(handle, &item->window.cinematicName)) { return qfalse; } return qtrue; } -qboolean ItemParse_doubleClick( itemDef_t *item, int handle ) { +qboolean ItemParse_doubleClick(itemDef_t *item, int handle) { listBoxDef_t *listPtr; Item_ValidateTypeData(item); @@ -7890,114 +7085,106 @@ qboolean ItemParse_doubleClick( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_onFocus( itemDef_t *item, int handle ) { +qboolean ItemParse_onFocus(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->onFocus)) { return qfalse; } return qtrue; } -qboolean ItemParse_leaveFocus( itemDef_t *item, int handle ) { +qboolean ItemParse_leaveFocus(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->leaveFocus)) { return qfalse; } return qtrue; } -qboolean ItemParse_mouseEnter( itemDef_t *item, int handle ) { +qboolean ItemParse_mouseEnter(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->mouseEnter)) { return qfalse; } return qtrue; } -qboolean ItemParse_mouseExit( itemDef_t *item, int handle ) { +qboolean ItemParse_mouseExit(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->mouseExit)) { return qfalse; } return qtrue; } -qboolean ItemParse_mouseEnterText( itemDef_t *item, int handle ) { +qboolean ItemParse_mouseEnterText(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->mouseEnterText)) { return qfalse; } return qtrue; } -qboolean ItemParse_mouseExitText( itemDef_t *item, int handle ) { +qboolean ItemParse_mouseExitText(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->mouseExitText)) { return qfalse; } return qtrue; } -qboolean ItemParse_action( itemDef_t *item, int handle ) { +qboolean ItemParse_action(itemDef_t *item, int handle) { if (!PC_Script_Parse(handle, &item->action)) { return qfalse; } return qtrue; } -qboolean ItemParse_special( itemDef_t *item, int handle ) { +qboolean ItemParse_special(itemDef_t *item, int handle) { if (!PC_Float_Parse(handle, &item->special)) { return qfalse; } return qtrue; } -qboolean ItemParse_cvarTest( itemDef_t *item, int handle ) { +qboolean ItemParse_cvarTest(itemDef_t *item, int handle) { if (!PC_String_Parse(handle, &item->cvarTest)) { return qfalse; } return qtrue; } -qboolean ItemParse_cvar( itemDef_t *item, int handle ) -{ +qboolean ItemParse_cvar(itemDef_t *item, int handle) { Item_ValidateTypeData(item); - if (!PC_String_Parse(handle, &item->cvar)) - { + if (!PC_String_Parse(handle, &item->cvar)) { return qfalse; } - switch ( item->type ) - { - case ITEM_TYPE_EDITFIELD: - case ITEM_TYPE_NUMERICFIELD: - case ITEM_TYPE_YESNO: - case ITEM_TYPE_BIND: - case ITEM_TYPE_SLIDER: - case ITEM_TYPE_TEXT: - { - if ( item->typeData.edit ) - { - item->typeData.edit->minVal = -1; - item->typeData.edit->maxVal = -1; - item->typeData.edit->defVal = -1; - } - break; + switch (item->type) { + case ITEM_TYPE_EDITFIELD: + case ITEM_TYPE_NUMERICFIELD: + case ITEM_TYPE_YESNO: + case ITEM_TYPE_BIND: + case ITEM_TYPE_SLIDER: + case ITEM_TYPE_TEXT: { + if (item->typeData.edit) { + item->typeData.edit->minVal = -1; + item->typeData.edit->maxVal = -1; + item->typeData.edit->defVal = -1; } + break; + } } return qtrue; } -qboolean ItemParse_font( itemDef_t *item, int handle ) -{ +qboolean ItemParse_font(itemDef_t *item, int handle) { Item_ValidateTypeData(item); - if (!PC_Int_Parse(handle, &item->iMenuFont)) - { + if (!PC_Int_Parse(handle, &item->iMenuFont)) { return qfalse; } return qtrue; } - -qboolean ItemParse_maxChars( itemDef_t *item, int handle ) { +qboolean ItemParse_maxChars(itemDef_t *item, int handle) { editFieldDef_t *editPtr; Item_ValidateTypeData(item); - editPtr = (editFieldDef_t*)item->typeData.edit; + editPtr = (editFieldDef_t *)item->typeData.edit; if (!editPtr || !PC_Int_Parse(handle, &editPtr->maxChars)) { return qfalse; @@ -8005,11 +7192,11 @@ qboolean ItemParse_maxChars( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_maxPaintChars( itemDef_t *item, int handle ) { +qboolean ItemParse_maxPaintChars(itemDef_t *item, int handle) { editFieldDef_t *editPtr; Item_ValidateTypeData(item); - editPtr = (editFieldDef_t*)item->typeData.edit; + editPtr = (editFieldDef_t *)item->typeData.edit; if (!editPtr || !PC_Int_Parse(handle, &editPtr->maxPaintChars)) { return qfalse; @@ -8017,7 +7204,7 @@ qboolean ItemParse_maxPaintChars( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_maxLineChars( itemDef_t *item, int handle ) { +qboolean ItemParse_maxLineChars(itemDef_t *item, int handle) { textScrollDef_t *scrollPtr; Item_ValidateTypeData(item); @@ -8029,7 +7216,7 @@ qboolean ItemParse_maxLineChars( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_lineHeight( itemDef_t *item, int handle ) { +qboolean ItemParse_lineHeight(itemDef_t *item, int handle) { textScrollDef_t *scrollPtr; int height; @@ -8043,7 +7230,7 @@ qboolean ItemParse_lineHeight( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_cvarFloat( itemDef_t *item, int handle ) { +qboolean ItemParse_cvarFloat(itemDef_t *item, int handle) { editFieldDef_t *editPtr; Item_ValidateTypeData(item); @@ -8052,9 +7239,7 @@ qboolean ItemParse_cvarFloat( itemDef_t *item, int handle ) { if (!editPtr) return qfalse; - if (PC_String_Parse(handle, &item->cvar) && - PC_Float_Parse(handle, &editPtr->defVal) && - PC_Float_Parse(handle, &editPtr->minVal) && + if (PC_String_Parse(handle, &item->cvar) && PC_Float_Parse(handle, &editPtr->defVal) && PC_Float_Parse(handle, &editPtr->minVal) && PC_Float_Parse(handle, &editPtr->maxVal)) { return qtrue; } @@ -8066,7 +7251,7 @@ char currLanguage[32][128]; static const char languageString[32] = "@MENUS_MYLANGUAGE"; #endif -qboolean ItemParse_cvarStrList( itemDef_t *item, int handle ) { +qboolean ItemParse_cvarStrList(itemDef_t *item, int handle) { pc_token_t token; multiDef_t *multiPtr; int pass; @@ -8080,33 +7265,28 @@ qboolean ItemParse_cvarStrList( itemDef_t *item, int handle ) { multiPtr->count = 0; multiPtr->strDef = qtrue; - if (!trap->PC_ReadToken(handle, &token)) - { + if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - if (!Q_stricmp(token.string,"feeder") && item->special == FEEDER_PLAYER_SPECIES) - { + if (!Q_stricmp(token.string, "feeder") && item->special == FEEDER_PLAYER_SPECIES) { #ifndef _CGAME - for (; multiPtr->count < uiInfo.playerSpeciesCount; multiPtr->count++) - { - multiPtr->cvarList[multiPtr->count] = String_Alloc(Q_strupr(va("@MENUS_%s",uiInfo.playerSpecies[multiPtr->count].Name ))); //look up translation - multiPtr->cvarStr[multiPtr->count] = uiInfo.playerSpecies[multiPtr->count].Name; //value + for (; multiPtr->count < uiInfo.playerSpeciesCount; multiPtr->count++) { + multiPtr->cvarList[multiPtr->count] = String_Alloc(Q_strupr(va("@MENUS_%s", uiInfo.playerSpecies[multiPtr->count].Name))); // look up translation + multiPtr->cvarStr[multiPtr->count] = uiInfo.playerSpecies[multiPtr->count].Name; // value } #endif return qtrue; } // languages - if (!Q_stricmp(token.string,"feeder") && item->special == FEEDER_LANGUAGES) - { + if (!Q_stricmp(token.string, "feeder") && item->special == FEEDER_LANGUAGES) { #ifdef UI_BUILD - for (; multiPtr->count < uiInfo.languageCount; multiPtr->count++) - { + for (; multiPtr->count < uiInfo.languageCount; multiPtr->count++) { // The displayed text - trap->SE_GetLanguageName( (const int) multiPtr->count,(char *) currLanguage[multiPtr->count] ); // eg "English" + trap->SE_GetLanguageName((const int)multiPtr->count, (char *)currLanguage[multiPtr->count]); // eg "English" multiPtr->cvarList[multiPtr->count] = languageString; // The cvar value that goes into se_language - trap->SE_GetLanguageName( (const int) multiPtr->count,(char *) currLanguage[multiPtr->count] ); + trap->SE_GetLanguageName((const int)multiPtr->count, (char *)currLanguage[multiPtr->count]); multiPtr->cvarStr[multiPtr->count] = currLanguage[multiPtr->count]; } #endif @@ -8118,18 +7298,16 @@ qboolean ItemParse_cvarStrList( itemDef_t *item, int handle ) { } pass = 0; - while ( 1 ) { - char* psString; + while (1) { + char *psString; - if (!PC_String_Parse(handle, (const char **)&psString)) - { + if (!PC_String_Parse(handle, (const char **)&psString)) { PC_SourceError(handle, "end of file inside menu item"); return qfalse; } - //a normal StringAlloc ptr - if (psString) - { + // a normal StringAlloc ptr + if (psString) { if (*psString == '}') { return qtrue; } @@ -8150,13 +7328,11 @@ qboolean ItemParse_cvarStrList( itemDef_t *item, int handle ) { return qfalse; } } - } return qfalse; } -qboolean ItemParse_cvarFloatList( itemDef_t *item, int handle ) -{ +qboolean ItemParse_cvarFloatList(itemDef_t *item, int handle) { pc_token_t token; multiDef_t *multiPtr; @@ -8169,62 +7345,50 @@ qboolean ItemParse_cvarFloatList( itemDef_t *item, int handle ) multiPtr->count = 0; multiPtr->strDef = qfalse; - if (!trap->PC_ReadToken(handle, &token)) - { + if (!trap->PC_ReadToken(handle, &token)) { return qfalse; } - if (*token.string != '{') - { + if (*token.string != '{') { return qfalse; } - while ( 1 ) - { - char* string; + while (1) { + char *string; - if ( !PC_String_Parse ( handle, (const char **)&string ) ) - { + if (!PC_String_Parse(handle, (const char **)&string)) { PC_SourceError(handle, "end of file inside menu item"); return qfalse; } - //a normal StringAlloc ptr - if (string) - { - if (*string == '}') - { + // a normal StringAlloc ptr + if (string) { + if (*string == '}') { return qtrue; } - if (*string == ',' || *string == ';') - { + if (*string == ',' || *string == ';') { continue; } } multiPtr->cvarList[multiPtr->count] = string; - if (!PC_Float_Parse(handle, &multiPtr->cvarValue[multiPtr->count])) - { + if (!PC_Float_Parse(handle, &multiPtr->cvarValue[multiPtr->count])) { return qfalse; } multiPtr->count++; - if (multiPtr->count >= MAX_MULTI_CVARS) - { + if (multiPtr->count >= MAX_MULTI_CVARS) { return qfalse; } - } return qfalse; } -qboolean ItemParse_addColorRange( itemDef_t *item, int handle ) { +qboolean ItemParse_addColorRange(itemDef_t *item, int handle) { colorRangeDef_t color; - if (PC_Float_Parse(handle, &color.low) && - PC_Float_Parse(handle, &color.high) && - PC_Color_Parse(handle, &color.color) ) { + if (PC_Float_Parse(handle, &color.low) && PC_Float_Parse(handle, &color.high) && PC_Color_Parse(handle, &color.color)) { if (item->numColors < MAX_COLOR_RANGES) { memcpy(&item->colorRanges[item->numColors], &color, sizeof(color)); item->numColors++; @@ -8234,7 +7398,7 @@ qboolean ItemParse_addColorRange( itemDef_t *item, int handle ) { return qfalse; } -qboolean ItemParse_ownerdrawFlag( itemDef_t *item, int handle ) { +qboolean ItemParse_ownerdrawFlag(itemDef_t *item, int handle) { int i; if (!PC_Int_Parse(handle, &i)) { return qfalse; @@ -8243,7 +7407,7 @@ qboolean ItemParse_ownerdrawFlag( itemDef_t *item, int handle ) { return qtrue; } -qboolean ItemParse_enableCvar( itemDef_t *item, int handle ) { +qboolean ItemParse_enableCvar(itemDef_t *item, int handle) { if (PC_Script_Parse(handle, &item->enableCvar)) { item->cvarFlags = CVAR_ENABLE; return qtrue; @@ -8251,7 +7415,7 @@ qboolean ItemParse_enableCvar( itemDef_t *item, int handle ) { return qfalse; } -qboolean ItemParse_disableCvar( itemDef_t *item, int handle ) { +qboolean ItemParse_disableCvar(itemDef_t *item, int handle) { if (PC_Script_Parse(handle, &item->enableCvar)) { item->cvarFlags = CVAR_DISABLE; return qtrue; @@ -8259,7 +7423,7 @@ qboolean ItemParse_disableCvar( itemDef_t *item, int handle ) { return qfalse; } -qboolean ItemParse_showCvar( itemDef_t *item, int handle ) { +qboolean ItemParse_showCvar(itemDef_t *item, int handle) { if (PC_Script_Parse(handle, &item->enableCvar)) { item->cvarFlags = CVAR_SHOW; return qtrue; @@ -8267,7 +7431,7 @@ qboolean ItemParse_showCvar( itemDef_t *item, int handle ) { return qfalse; } -qboolean ItemParse_hideCvar( itemDef_t *item, int handle ) { +qboolean ItemParse_hideCvar(itemDef_t *item, int handle) { if (PC_Script_Parse(handle, &item->enableCvar)) { item->cvarFlags = CVAR_HIDE; return qtrue; @@ -8280,34 +7444,26 @@ qboolean ItemParse_hideCvar( itemDef_t *item, int handle ) { ItemParse_align =============== */ -qboolean ItemParse_Appearance_slot( itemDef_t *item, int handle ) -{ - if (!PC_Int_Parse(handle, &item->appearanceSlot)) - { +qboolean ItemParse_Appearance_slot(itemDef_t *item, int handle) { + if (!PC_Int_Parse(handle, &item->appearanceSlot)) { return qfalse; } return qtrue; } -qboolean ItemParse_isSaber( itemDef_t *item, int handle ) -{ +qboolean ItemParse_isSaber(itemDef_t *item, int handle) { #ifndef _CGAME - int i; + int i; - if (PC_Int_Parse(handle, &i)) - { - if ( i ) - { + if (PC_Int_Parse(handle, &i)) { + if (i) { item->flags |= ITF_ISSABER; UI_CacheSaberGlowGraphics(); - if ( !ui_saber_parms_parsed ) - { + if (!ui_saber_parms_parsed) { UI_SaberLoadParms(); } - } - else - { + } else { item->flags &= ~ITF_ISSABER; } @@ -8317,23 +7473,17 @@ qboolean ItemParse_isSaber( itemDef_t *item, int handle ) return qfalse; } -qboolean ItemParse_isSaber2( itemDef_t *item, int handle ) -{ +qboolean ItemParse_isSaber2(itemDef_t *item, int handle) { #ifndef _CGAME - int i; - if (PC_Int_Parse(handle, &i)) - { - if ( i ) - { + int i; + if (PC_Int_Parse(handle, &i)) { + if (i) { item->flags |= ITF_ISSABER2; UI_CacheSaberGlowGraphics(); - if ( !ui_saber_parms_parsed ) - { + if (!ui_saber_parms_parsed) { UI_SaberLoadParms(); } - } - else - { + } else { item->flags &= ~ITF_ISSABER2; } @@ -8344,101 +7494,97 @@ qboolean ItemParse_isSaber2( itemDef_t *item, int handle ) return qfalse; } -keywordHash_t itemParseKeywords[] = { - {"action", ItemParse_action, NULL }, - {"addColorRange", ItemParse_addColorRange, NULL }, - {"align", ItemParse_align, NULL }, - {"autowrapped", ItemParse_autowrapped, NULL }, - {"appearance_slot", ItemParse_Appearance_slot, NULL }, - {"asset_model", ItemParse_asset_model, NULL }, - {"asset_shader", ItemParse_asset_shader, NULL }, - {"backcolor", ItemParse_backcolor, NULL }, - {"background", ItemParse_background, NULL }, - {"border", ItemParse_border, NULL }, - {"bordercolor", ItemParse_bordercolor, NULL }, - {"bordersize", ItemParse_bordersize, NULL }, - {"cinematic", ItemParse_cinematic, NULL }, - {"columns", ItemParse_columns, NULL }, - {"cvar", ItemParse_cvar, NULL }, - {"cvarFloat", ItemParse_cvarFloat, NULL }, - {"cvarFloatList", ItemParse_cvarFloatList, NULL }, - {"cvarStrList", ItemParse_cvarStrList, NULL }, - {"cvarTest", ItemParse_cvarTest, NULL }, - {"desctext", ItemParse_descText, NULL }, - {"decoration", ItemParse_decoration, NULL }, - {"disableCvar", ItemParse_disableCvar, NULL }, - {"doubleclick", ItemParse_doubleClick, NULL }, - {"elementheight", ItemParse_elementheight, NULL }, - {"elementtype", ItemParse_elementtype, NULL }, - {"elementwidth", ItemParse_elementwidth, NULL }, - {"enableCvar", ItemParse_enableCvar, NULL }, - {"feeder", ItemParse_feeder, NULL }, - {"flag", ItemParse_flag, NULL }, - {"focusSound", ItemParse_focusSound, NULL }, - {"font", ItemParse_font, NULL }, - {"forecolor", ItemParse_forecolor, NULL }, - {"group", ItemParse_group, NULL }, - {"hideCvar", ItemParse_hideCvar, NULL }, - {"horizontalscroll", ItemParse_horizontalscroll, NULL }, - {"isCharacter", ItemParse_isCharacter, NULL }, - {"isSaber", ItemParse_isSaber, NULL }, - {"isSaber2", ItemParse_isSaber2, NULL }, - {"leaveFocus", ItemParse_leaveFocus, NULL }, - {"maxChars", ItemParse_maxChars, NULL }, - {"maxPaintChars", ItemParse_maxPaintChars, NULL }, - {"model_angle", ItemParse_model_angle, NULL }, - {"model_fovx", ItemParse_model_fovx, NULL }, - {"model_fovy", ItemParse_model_fovy, NULL }, - {"model_origin", ItemParse_model_origin, NULL }, - {"model_rotation", ItemParse_model_rotation, NULL }, - //rww - g2 begin - {"model_g2mins", ItemParse_model_g2mins, NULL }, - {"model_g2maxs", ItemParse_model_g2maxs, NULL }, - {"model_g2scale", ItemParse_model_g2scale, NULL }, - {"model_g2skin", ItemParse_model_g2skin, NULL }, - {"model_g2anim", ItemParse_model_g2anim, NULL }, - //rww - g2 end - {"mouseEnter", ItemParse_mouseEnter, NULL }, - {"mouseEnterText", ItemParse_mouseEnterText, NULL }, - {"mouseExit", ItemParse_mouseExit, NULL }, - {"mouseExitText", ItemParse_mouseExitText, NULL }, - {"name", ItemParse_name, NULL }, - {"notselectable", ItemParse_notselectable, NULL }, - {"onFocus", ItemParse_onFocus, NULL }, - {"outlinecolor", ItemParse_outlinecolor, NULL }, - {"ownerdraw", ItemParse_ownerdraw, NULL }, - {"ownerdrawFlag", ItemParse_ownerdrawFlag, NULL }, - {"rect", ItemParse_rect, NULL }, - {"rectcvar", ItemParse_rectcvar, NULL }, - {"showCvar", ItemParse_showCvar, NULL }, - {"special", ItemParse_special, NULL }, - {"style", ItemParse_style, NULL }, - {"text", ItemParse_text, NULL }, - {"textalign", ItemParse_textalign, NULL }, - {"textalignx", ItemParse_textalignx, NULL }, - {"textaligny", ItemParse_textaligny, NULL }, - {"textscale", ItemParse_textscale, NULL }, - {"textstyle", ItemParse_textstyle, NULL }, - {"text2", ItemParse_text2, NULL }, - {"text2alignx", ItemParse_text2alignx, NULL }, - {"text2aligny", ItemParse_text2aligny, NULL }, - {"type", ItemParse_type, NULL }, - {"visible", ItemParse_visible, NULL }, - {"wrapped", ItemParse_wrapped, NULL }, - - // Text scroll specific - {"maxLineChars", ItemParse_maxLineChars, NULL }, - {"lineHeight", ItemParse_lineHeight, NULL }, - {"invertyesno", ItemParse_invertyesno, NULL }, - //JLF MPMOVED - {"scrollhidden", ItemParse_scrollhidden, NULL }, - {"xoffset ", ItemParse_xoffset, NULL }, - //JLF end - - - - {0, 0, 0 } -}; +keywordHash_t itemParseKeywords[] = {{"action", ItemParse_action, NULL}, + {"addColorRange", ItemParse_addColorRange, NULL}, + {"align", ItemParse_align, NULL}, + {"autowrapped", ItemParse_autowrapped, NULL}, + {"appearance_slot", ItemParse_Appearance_slot, NULL}, + {"asset_model", ItemParse_asset_model, NULL}, + {"asset_shader", ItemParse_asset_shader, NULL}, + {"backcolor", ItemParse_backcolor, NULL}, + {"background", ItemParse_background, NULL}, + {"border", ItemParse_border, NULL}, + {"bordercolor", ItemParse_bordercolor, NULL}, + {"bordersize", ItemParse_bordersize, NULL}, + {"cinematic", ItemParse_cinematic, NULL}, + {"columns", ItemParse_columns, NULL}, + {"cvar", ItemParse_cvar, NULL}, + {"cvarFloat", ItemParse_cvarFloat, NULL}, + {"cvarFloatList", ItemParse_cvarFloatList, NULL}, + {"cvarStrList", ItemParse_cvarStrList, NULL}, + {"cvarTest", ItemParse_cvarTest, NULL}, + {"desctext", ItemParse_descText, NULL}, + {"decoration", ItemParse_decoration, NULL}, + {"disableCvar", ItemParse_disableCvar, NULL}, + {"doubleclick", ItemParse_doubleClick, NULL}, + {"elementheight", ItemParse_elementheight, NULL}, + {"elementtype", ItemParse_elementtype, NULL}, + {"elementwidth", ItemParse_elementwidth, NULL}, + {"enableCvar", ItemParse_enableCvar, NULL}, + {"feeder", ItemParse_feeder, NULL}, + {"flag", ItemParse_flag, NULL}, + {"focusSound", ItemParse_focusSound, NULL}, + {"font", ItemParse_font, NULL}, + {"forecolor", ItemParse_forecolor, NULL}, + {"group", ItemParse_group, NULL}, + {"hideCvar", ItemParse_hideCvar, NULL}, + {"horizontalscroll", ItemParse_horizontalscroll, NULL}, + {"isCharacter", ItemParse_isCharacter, NULL}, + {"isSaber", ItemParse_isSaber, NULL}, + {"isSaber2", ItemParse_isSaber2, NULL}, + {"leaveFocus", ItemParse_leaveFocus, NULL}, + {"maxChars", ItemParse_maxChars, NULL}, + {"maxPaintChars", ItemParse_maxPaintChars, NULL}, + {"model_angle", ItemParse_model_angle, NULL}, + {"model_fovx", ItemParse_model_fovx, NULL}, + {"model_fovy", ItemParse_model_fovy, NULL}, + {"model_origin", ItemParse_model_origin, NULL}, + {"model_rotation", ItemParse_model_rotation, NULL}, + // rww - g2 begin + {"model_g2mins", ItemParse_model_g2mins, NULL}, + {"model_g2maxs", ItemParse_model_g2maxs, NULL}, + {"model_g2scale", ItemParse_model_g2scale, NULL}, + {"model_g2skin", ItemParse_model_g2skin, NULL}, + {"model_g2anim", ItemParse_model_g2anim, NULL}, + // rww - g2 end + {"mouseEnter", ItemParse_mouseEnter, NULL}, + {"mouseEnterText", ItemParse_mouseEnterText, NULL}, + {"mouseExit", ItemParse_mouseExit, NULL}, + {"mouseExitText", ItemParse_mouseExitText, NULL}, + {"name", ItemParse_name, NULL}, + {"notselectable", ItemParse_notselectable, NULL}, + {"onFocus", ItemParse_onFocus, NULL}, + {"outlinecolor", ItemParse_outlinecolor, NULL}, + {"ownerdraw", ItemParse_ownerdraw, NULL}, + {"ownerdrawFlag", ItemParse_ownerdrawFlag, NULL}, + {"rect", ItemParse_rect, NULL}, + {"rectcvar", ItemParse_rectcvar, NULL}, + {"showCvar", ItemParse_showCvar, NULL}, + {"special", ItemParse_special, NULL}, + {"style", ItemParse_style, NULL}, + {"text", ItemParse_text, NULL}, + {"textalign", ItemParse_textalign, NULL}, + {"textalignx", ItemParse_textalignx, NULL}, + {"textaligny", ItemParse_textaligny, NULL}, + {"textscale", ItemParse_textscale, NULL}, + {"textstyle", ItemParse_textstyle, NULL}, + {"text2", ItemParse_text2, NULL}, + {"text2alignx", ItemParse_text2alignx, NULL}, + {"text2aligny", ItemParse_text2aligny, NULL}, + {"type", ItemParse_type, NULL}, + {"visible", ItemParse_visible, NULL}, + {"wrapped", ItemParse_wrapped, NULL}, + + // Text scroll specific + {"maxLineChars", ItemParse_maxLineChars, NULL}, + {"lineHeight", ItemParse_lineHeight, NULL}, + {"invertyesno", ItemParse_invertyesno, NULL}, + // JLF MPMOVED + {"scrollhidden", ItemParse_scrollhidden, NULL}, + {"xoffset ", ItemParse_xoffset, NULL}, + // JLF end + + {0, 0, 0}}; keywordHash_t *itemParseKeywordHash[KEYWORDHASH_SIZE]; @@ -8462,76 +7608,72 @@ Item_ApplyHacks Hacks to fix issues with Team Arena menu scripts =============== */ -static void Item_ApplyHacks( itemDef_t *item ) { -#if !defined(_WIN32) || ( defined(_WIN32) && defined(idx64) ) - if ( item->type == ITEM_TYPE_MULTI && item->cvar && !Q_stricmp( item->cvar, "s_UseOpenAL" ) ) { - if( item->parent ) - { +static void Item_ApplyHacks(itemDef_t *item) { +#if !defined(_WIN32) || (defined(_WIN32) && defined(idx64)) + if (item->type == ITEM_TYPE_MULTI && item->cvar && !Q_stricmp(item->cvar, "s_UseOpenAL")) { + if (item->parent) { menuDef_t *parent = (menuDef_t *)item->parent; - VectorSet4( parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f ); + VectorSet4(parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f); item->disabled = qtrue; // Just in case it had focus item->window.flags &= ~WINDOW_MOUSEOVER; - Com_Printf( "Disabling eax field because current platform does not support EAX.\n"); + Com_Printf("Disabling eax field because current platform does not support EAX.\n"); } } - if ( item->type == ITEM_TYPE_TEXT && item->window.name && !Q_stricmp( item->window.name, "eax_icon") && item->cvarTest && !Q_stricmp( item->cvarTest, "s_UseOpenAL" ) && item->enableCvar && (item->cvarFlags & CVAR_HIDE) ) { - if( item->parent ) - { + if (item->type == ITEM_TYPE_TEXT && item->window.name && !Q_stricmp(item->window.name, "eax_icon") && item->cvarTest && + !Q_stricmp(item->cvarTest, "s_UseOpenAL") && item->enableCvar && (item->cvarFlags & CVAR_HIDE)) { + if (item->parent) { menuDef_t *parent = (menuDef_t *)item->parent; - VectorSet4( parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f ); + VectorSet4(parent->disableColor, 0.5f, 0.5f, 0.5f, 1.0f); item->disabled = item->disabledHidden = qtrue; // Just in case it had focus item->window.flags &= ~WINDOW_MOUSEOVER; - Com_Printf( "Hiding eax_icon object because current platform does not support EAX.\n"); + Com_Printf("Hiding eax_icon object because current platform does not support EAX.\n"); } } #endif - + // Fix length of favorite address in createfavorite.menu - if ( item->type == ITEM_TYPE_EDITFIELD && item->cvar && !Q_stricmp( item->cvar, "ui_favoriteAddress" ) ) { + if (item->type == ITEM_TYPE_EDITFIELD && item->cvar && !Q_stricmp(item->cvar, "ui_favoriteAddress")) { editFieldDef_t *editField = item->typeData.edit; // enough to hold an IPv6 address plus null - if ( editField->maxChars < 48 ) { - Com_Printf( "Extended create favorite address edit field length to hold an IPv6 address\n" ); + if (editField->maxChars < 48) { + Com_Printf("Extended create favorite address edit field length to hold an IPv6 address\n"); editField->maxChars = 48; } } - if ( item->type == ITEM_TYPE_EDITFIELD && item->cvar && ( !Q_stricmp( item->cvar, "ui_Name" ) || !Q_stricmp( item->cvar, "ui_findplayer" ) ) ) { + if (item->type == ITEM_TYPE_EDITFIELD && item->cvar && (!Q_stricmp(item->cvar, "ui_Name") || !Q_stricmp(item->cvar, "ui_findplayer"))) { editFieldDef_t *editField = item->typeData.edit; // enough to hold a full player name - if ( editField->maxChars < MAX_NAME_LENGTH ) { - if ( editField->maxPaintChars > editField->maxChars ) { + if (editField->maxChars < MAX_NAME_LENGTH) { + if (editField->maxPaintChars > editField->maxChars) { editField->maxPaintChars = editField->maxChars; } - Com_Printf( "Extended player name field using cvar %s to %d characters\n", item->cvar, MAX_NAME_LENGTH ); + Com_Printf("Extended player name field using cvar %s to %d characters\n", item->cvar, MAX_NAME_LENGTH); editField->maxChars = MAX_NAME_LENGTH; } } - if ( item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp( item->window.name, "sound_quality") ) { + if (item->type == ITEM_TYPE_MULTI && item->window.name && !Q_stricmp(item->window.name, "sound_quality")) { multiDef_t *multiPtr = item->typeData.multi; int i; qboolean found = qfalse; - for( i = 0; i < multiPtr->count; i++ ) - { - if ( multiPtr->cvarValue[i] == 44 ) - { + for (i = 0; i < multiPtr->count; i++) { + if (multiPtr->cvarValue[i] == 44) { found = qtrue; break; } } - if ( !found && multiPtr->count < MAX_MULTI_CVARS ) - { + if (!found && multiPtr->count < MAX_MULTI_CVARS) { multiPtr->cvarList[multiPtr->count] = String_Alloc("@MENUS_VERY_HIGH"); multiPtr->cvarValue[multiPtr->count] = 44; multiPtr->count++; - Com_Printf( "Extended sound quality field to contain very high setting.\n"); + Com_Printf("Extended sound quality field to contain very high setting.\n"); } } } @@ -8545,14 +7687,13 @@ qboolean Item_Parse(int handle, itemDef_t *item) { pc_token_t token; keywordHash_t *key; - if (!trap->PC_ReadToken(handle, &token)) return qfalse; if (*token.string != '{') { return qfalse; } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) { PC_SourceError(handle, "end of file inside menu item"); return qfalse; @@ -8567,7 +7708,7 @@ qboolean Item_Parse(int handle, itemDef_t *item) { PC_SourceError(handle, "unknown menu item keyword %s", token.string); continue; } - if ( !key->func(item, handle) ) { + if (!key->func(item, handle)) { PC_SourceError(handle, "couldn't parse menu item keyword %s", token.string); return qfalse; } @@ -8575,16 +7716,15 @@ qboolean Item_Parse(int handle, itemDef_t *item) { return qfalse; } -static void Item_TextScroll_BuildLines ( itemDef_t* item ) -{ +static void Item_TextScroll_BuildLines(itemDef_t *item) { char text[2048]; #if 1 // new asian-aware line breaker... (pasted from elsewhere late @ night, hence aliasing-vars ;-) // - textScrollDef_t* scrollPtr = item->typeData.textscroll; - const char *psText = item->text; // for copy/paste ease + textScrollDef_t *scrollPtr = item->typeData.textscroll; + const char *psText = item->text; // for copy/paste ease int iBoxWidth = item->window.rect.w - SCROLLBAR_SIZE - 10; // this could probably be simplified now, but it was converted from something else I didn't originally write, @@ -8593,13 +7733,13 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) const char *psCurrentTextReadPos; const char *psReadPosAtLineStart; const char *psBestLineBreakSrcPos; - const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) + const char *psLastGood_s; // needed if we get a full screen of chars with no punctuation or space (see usage notes) qboolean bIsTrailingPunctuation; unsigned int uiLetter; - if (*psText == '@') // string reference + if (*psText == '@') // string reference { - trap->SE_GetStringTextString( &psText[1], text, sizeof(text)); + trap->SE_GetStringTextString(&psText[1], text, sizeof(text)); psText = text; } @@ -8608,18 +7748,16 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) psBestLineBreakSrcPos = psCurrentTextReadPos; scrollPtr->iLineCount = 0; - memset((char*)scrollPtr->pLines,0,sizeof(scrollPtr->pLines)); + memset((char *)scrollPtr->pLines, 0, sizeof(scrollPtr->pLines)); - while (*psCurrentTextReadPos && (scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES) ) - { - char sLineForDisplay[2048]; // ott + while (*psCurrentTextReadPos && (scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES)) { + char sLineForDisplay[2048]; // ott // construct a line... // psCurrentTextReadPos = psReadPosAtLineStart; sLineForDisplay[0] = '\0'; - while ( *psCurrentTextReadPos ) - { + while (*psCurrentTextReadPos) { int iAdvanceCount; psLastGood_s = psCurrentTextReadPos; @@ -8630,49 +7768,37 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) // concat onto string so far... // - if (uiLetter == 32 && sLineForDisplay[0] == '\0') - { + if (uiLetter == 32 && sLineForDisplay[0] == '\0') { psReadPosAtLineStart++; - continue; // unless it's a space at the start of a line, in which case ignore it. + continue; // unless it's a space at the start of a line, in which case ignore it. } - if (uiLetter > 255) - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c%c",uiLetter >> 8, uiLetter & 0xFF)); - } - else - { - Q_strcat(sLineForDisplay, sizeof(sLineForDisplay),va("%c",uiLetter & 0xFF)); + if (uiLetter > 255) { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c%c", uiLetter >> 8, uiLetter & 0xFF)); + } else { + Q_strcat(sLineForDisplay, sizeof(sLineForDisplay), va("%c", uiLetter & 0xFF)); } - if (uiLetter == '\n') - { + if (uiLetter == '\n') { // explicit new line... // - sLineForDisplay[ strlen(sLineForDisplay)-1 ] = '\0'; // kill the CR + sLineForDisplay[strlen(sLineForDisplay) - 1] = '\0'; // kill the CR psReadPosAtLineStart = psCurrentTextReadPos; psBestLineBreakSrcPos = psCurrentTextReadPos; // hack it to fit in with this code... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc ( sLineForDisplay ); - break; // print this line - } - else - if ( DC->textWidth( sLineForDisplay, item->textscale, item->iMenuFont ) >= iBoxWidth ) - { + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); + break; // print this line + } else if (DC->textWidth(sLineForDisplay, item->textscale, item->iMenuFont) >= iBoxWidth) { // reached screen edge, so cap off string at bytepos after last good position... // - if (uiLetter > 255 && bIsTrailingPunctuation && !trap->R_Language_UsesSpaces()) - { + if (uiLetter > 255 && bIsTrailingPunctuation && !trap->R_Language_UsesSpaces()) { // Special case, don't consider line breaking if you're on an asian punctuation char of // a language that doesn't use spaces... // - } - else - { - if (psBestLineBreakSrcPos == psReadPosAtLineStart) - { + } else { + if (psBestLineBreakSrcPos == psReadPosAtLineStart) { // aarrrggh!!!!! we'll only get here is someone has fed in a (probably) garbage string, // since it doesn't have a single space or punctuation mark right the way across one line // of the screen. So far, this has only happened in testing when I hardwired a taiwanese @@ -8680,34 +7806,32 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) // normally). On the other hand I suppose it's entirely possible that some taiwanese string // might have no punctuation at all, so... // - psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter + psBestLineBreakSrcPos = psLastGood_s; // force a break after last good letter } - sLineForDisplay[ psBestLineBreakSrcPos - psReadPosAtLineStart ] = '\0'; + sLineForDisplay[psBestLineBreakSrcPos - psReadPosAtLineStart] = '\0'; psReadPosAtLineStart = psCurrentTextReadPos = psBestLineBreakSrcPos; // hack it to fit in with this code... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc( sLineForDisplay ); - break; // print this line + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); + break; // print this line } } // record last-good linebreak pos... (ie if we've just concat'd a punctuation point (western or asian) or space) // - if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !trap->R_Language_UsesSpaces())) - { + if (bIsTrailingPunctuation || uiLetter == ' ' || (uiLetter > 255 && !trap->R_Language_UsesSpaces())) { psBestLineBreakSrcPos = psCurrentTextReadPos; } } /// arrgghh, this is gettng horrible now... // - if (scrollPtr->pLines[ scrollPtr->iLineCount ] == NULL && strlen(sLineForDisplay)) - { + if (scrollPtr->pLines[scrollPtr->iLineCount] == NULL && strlen(sLineForDisplay)) { // then this is the last line and we've just run out of text, no CR, no overflow etc... // - scrollPtr->pLines[ scrollPtr->iLineCount ] = String_Alloc( sLineForDisplay ); + scrollPtr->pLines[scrollPtr->iLineCount] = String_Alloc(sLineForDisplay); } scrollPtr->iLineCount++; @@ -8716,72 +7840,63 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) #else // old version... // - int width; - char* lineStart; - char* lineEnd; - float w; - float cw; + int width; + char *lineStart; + char *lineEnd; + float w; + float cw; - textScrollDef_t* scrollPtr = item->typeData.textscroll; + textScrollDef_t *scrollPtr = item->typeData.textscroll; scrollPtr->iLineCount = 0; width = scrollPtr->maxLineChars; - lineStart = (char*)item->text; - lineEnd = lineStart; - w = 0; + lineStart = (char *)item->text; + lineEnd = lineStart; + w = 0; // Keep going as long as there are more lines - while ( scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES ) - { + while (scrollPtr->iLineCount < MAX_TEXTSCROLL_LINES) { // End of the road - if ( *lineEnd == '\0') - { - if ( lineStart < lineEnd ) - { - scrollPtr->pLines[ scrollPtr->iLineCount++ ] = lineStart; + if (*lineEnd == '\0') { + if (lineStart < lineEnd) { + scrollPtr->pLines[scrollPtr->iLineCount++] = lineStart; } break; } // Force a line end if its a '\n' - else if ( *lineEnd == '\n' ) - { + else if (*lineEnd == '\n') { *lineEnd = '\0'; - scrollPtr->pLines[ scrollPtr->iLineCount++ ] = lineStart; + scrollPtr->pLines[scrollPtr->iLineCount++] = lineStart; lineStart = lineEnd + 1; - lineEnd = lineStart; + lineEnd = lineStart; w = 0; continue; } // Get the current character width - cw = DC->textWidth ( va("%c", *lineEnd), item->textscale, item->iMenuFont ); + cw = DC->textWidth(va("%c", *lineEnd), item->textscale, item->iMenuFont); // Past the end of the boundary? - if ( w + cw > (item->window.rect.w - SCROLLBAR_SIZE - 10) ) - { + if (w + cw > (item->window.rect.w - SCROLLBAR_SIZE - 10)) { // Past the end so backtrack to the word boundary - while ( *lineEnd != ' ' && *lineEnd != '\t' && lineEnd > lineStart ) - { + while (*lineEnd != ' ' && *lineEnd != '\t' && lineEnd > lineStart) { lineEnd--; } *lineEnd = '\0'; - scrollPtr->pLines[ scrollPtr->iLineCount++ ] = lineStart; + scrollPtr->pLines[scrollPtr->iLineCount++] = lineStart; // Skip any whitespaces lineEnd++; - while ( (*lineEnd == ' ' || *lineEnd == '\t') && *lineEnd ) - { + while ((*lineEnd == ' ' || *lineEnd == '\t') && *lineEnd) { lineEnd++; } lineStart = lineEnd; w = 0; - } - else - { + } else { w += cw; lineEnd++; } @@ -8791,19 +7906,15 @@ static void Item_TextScroll_BuildLines ( itemDef_t* item ) // Item_InitControls // init's special control types -void Item_InitControls(itemDef_t *item) -{ - if (item == NULL) - { +void Item_InitControls(itemDef_t *item) { + if (item == NULL) { return; } - if ( item->type == ITEM_TYPE_LISTBOX ) - { + if (item->type == ITEM_TYPE_LISTBOX) { listBoxDef_t *listPtr = item->typeData.listbox; item->cursorPos = 0; - if (listPtr) - { + if (listPtr) { listPtr->cursorPos = 0; listPtr->startPos = 0; listPtr->endPos = 0; @@ -8818,33 +7929,33 @@ Menu Keyword Parse functions =============== */ -qboolean MenuParse_font( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_font(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_String_Parse(handle, &menu->font)) { return qfalse; } if (!DC->Assets.fontRegistered) { - //DC->registerFont(menu->font, 48, &DC->Assets.textFont); + // DC->registerFont(menu->font, 48, &DC->Assets.textFont); DC->Assets.qhMediumFont = DC->RegisterFont(menu->font); DC->Assets.fontRegistered = qtrue; } return qtrue; } -qboolean MenuParse_name( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_name(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_String_Parse(handle, &menu->window.name)) { return qfalse; } if (Q_stricmp(menu->window.name, "main") == 0) { // default main as having focus - //menu->window.flags |= WINDOW_HASFOCUS; + // menu->window.flags |= WINDOW_HASFOCUS; } return qtrue; } -qboolean MenuParse_fullscreen( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fullscreen(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; byteAlias_t fullscreen; if (!PC_Int_Parse(handle, &fullscreen.i)) { return qfalse; @@ -8853,8 +7964,8 @@ qboolean MenuParse_fullscreen( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_rect( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_rect(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Rect_Parse(handle, &menu->window.rect)) { return qfalse; } @@ -8866,12 +7977,10 @@ qboolean MenuParse_rect( itemDef_t *item, int handle ) { MenuParse_style ================= */ -qboolean MenuParse_style( itemDef_t *item, int handle) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_style(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Int_Parse(handle, &menu->window.style)) - { + if (!PC_Int_Parse(handle, &menu->window.style)) { Com_Printf(S_COLOR_YELLOW "Unknown menu style value\n"); return qfalse; } @@ -8879,9 +7988,9 @@ qboolean MenuParse_style( itemDef_t *item, int handle) return qtrue; } -qboolean MenuParse_visible( itemDef_t *item, int handle ) { +qboolean MenuParse_visible(itemDef_t *item, int handle) { int i; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; if (!PC_Int_Parse(handle, &i)) { return qfalse; @@ -8892,75 +8001,71 @@ qboolean MenuParse_visible( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_onOpen( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onOpen(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Script_Parse(handle, &menu->onOpen)) { return qfalse; } return qtrue; } -qboolean MenuParse_onClose( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onClose(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Script_Parse(handle, &menu->onClose)) { return qfalse; } return qtrue; } -//JLFACCEPT MPMOVED +// JLFACCEPT MPMOVED /* ================= MenuParse_onAccept ================= */ -qboolean MenuParse_onAccept( itemDef_t *item, int handle ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onAccept(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Script_Parse(handle, &menu->onAccept)) - { + if (!PC_Script_Parse(handle, &menu->onAccept)) { return qfalse; } return qtrue; } -qboolean MenuParse_onESC( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_onESC(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Script_Parse(handle, &menu->onESC)) { return qfalse; } return qtrue; } - - -qboolean MenuParse_border( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_border(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Int_Parse(handle, &menu->window.border)) { return qfalse; } return qtrue; } -qboolean MenuParse_borderSize( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_borderSize(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Float_Parse(handle, &menu->window.borderSize)) { return qfalse; } return qtrue; } -qboolean MenuParse_backcolor( itemDef_t *item, int handle ) { +qboolean MenuParse_backcolor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; for (i = 0; i < 4; i++) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - menu->window.backColor[i] = f; + menu->window.backColor[i] = f; } return qtrue; } @@ -8970,12 +8075,10 @@ qboolean MenuParse_backcolor( itemDef_t *item, int handle ) { MenuParse_descAlignment ================= */ -qboolean MenuParse_descAlignment( itemDef_t *item, int handle ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descAlignment(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Int_Parse(handle, &menu->descAlignment)) - { + if (!PC_Int_Parse(handle, &menu->descAlignment)) { Com_Printf(S_COLOR_YELLOW "Unknown desc alignment value\n"); return qfalse; } @@ -8988,12 +8091,10 @@ qboolean MenuParse_descAlignment( itemDef_t *item, int handle ) MenuParse_descX ================= */ -qboolean MenuParse_descX( itemDef_t *item, int handle ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descX(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Int_Parse(handle, &menu->descX)) - { + if (!PC_Int_Parse(handle, &menu->descX)) { return qfalse; } return qtrue; @@ -9004,12 +8105,10 @@ qboolean MenuParse_descX( itemDef_t *item, int handle ) MenuParse_descY ================= */ -qboolean MenuParse_descY( itemDef_t *item, int handle ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descY(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Int_Parse(handle, &menu->descY)) - { + if (!PC_Int_Parse(handle, &menu->descY)) { return qfalse; } return qtrue; @@ -9020,12 +8119,10 @@ qboolean MenuParse_descY( itemDef_t *item, int handle ) MenuParse_descScale ================= */ -qboolean MenuParse_descScale( itemDef_t *item, int handle) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_descScale(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Float_Parse(handle, &menu->descScale)) - { + if (!PC_Float_Parse(handle, &menu->descScale)) { return qfalse; } return qtrue; @@ -9036,96 +8133,91 @@ qboolean MenuParse_descScale( itemDef_t *item, int handle) MenuParse_descColor ================= */ -qboolean MenuParse_descColor( itemDef_t *item, int handle) -{ +qboolean MenuParse_descColor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; - for (i = 0; i < 4; i++) - { - if (!PC_Float_Parse(handle, &f)) - { + for (i = 0; i < 4; i++) { + if (!PC_Float_Parse(handle, &f)) { return qfalse; } - menu->descColor[i] = f; + menu->descColor[i] = f; } return qtrue; } -qboolean MenuParse_forecolor( itemDef_t *item, int handle ) { +qboolean MenuParse_forecolor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; for (i = 0; i < 4; i++) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - if (f < 0) - { //special case for player color + if (f < 0) { // special case for player color menu->window.flags |= WINDOW_PLAYERCOLOR; return qtrue; } - menu->window.foreColor[i] = f; + menu->window.foreColor[i] = f; menu->window.flags |= WINDOW_FORECOLORSET; } return qtrue; } -qboolean MenuParse_bordercolor( itemDef_t *item, int handle ) { +qboolean MenuParse_bordercolor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; for (i = 0; i < 4; i++) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - menu->window.borderColor[i] = f; + menu->window.borderColor[i] = f; } return qtrue; } -qboolean MenuParse_focuscolor( itemDef_t *item, int handle ) { +qboolean MenuParse_focuscolor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; for (i = 0; i < 4; i++) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - menu->focusColor[i] = f; + menu->focusColor[i] = f; } return qtrue; } -qboolean MenuParse_disablecolor( itemDef_t *item, int handle ) { +qboolean MenuParse_disablecolor(itemDef_t *item, int handle) { int i; float f; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; for (i = 0; i < 4; i++) { if (!PC_Float_Parse(handle, &f)) { return qfalse; } - menu->disableColor[i] = f; + menu->disableColor[i] = f; } return qtrue; } - -qboolean MenuParse_outlinecolor( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; - if (!PC_Color_Parse(handle, &menu->window.outlineColor)){ +qboolean MenuParse_outlinecolor(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; + if (!PC_Color_Parse(handle, &menu->window.outlineColor)) { return qfalse; } return qtrue; } -qboolean MenuParse_background( itemDef_t *item, int handle ) { +qboolean MenuParse_background(itemDef_t *item, int handle) { pc_token_t token; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; if (!trap->PC_ReadToken(handle, &token)) { return qfalse; @@ -9134,8 +8226,8 @@ qboolean MenuParse_background( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_cinematic( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_cinematic(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_String_Parse(handle, &menu->window.cinematicName)) { return qfalse; @@ -9143,9 +8235,9 @@ qboolean MenuParse_cinematic( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_ownerdrawFlag( itemDef_t *item, int handle ) { +qboolean MenuParse_ownerdrawFlag(itemDef_t *item, int handle) { int i; - menuDef_t *menu = (menuDef_t*)item; + menuDef_t *menu = (menuDef_t *)item; if (!PC_Int_Parse(handle, &i)) { return qfalse; @@ -9154,8 +8246,8 @@ qboolean MenuParse_ownerdrawFlag( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_ownerdraw( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_ownerdraw(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Int_Parse(handle, &menu->window.ownerDraw)) { return qfalse; @@ -9163,24 +8255,22 @@ qboolean MenuParse_ownerdraw( itemDef_t *item, int handle ) { return qtrue; } - // decoration -qboolean MenuParse_popup( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_popup(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; menu->window.flags |= WINDOW_POPUP; return qtrue; } - -qboolean MenuParse_outOfBounds( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_outOfBounds(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; menu->window.flags |= WINDOW_OOB_CLICK; return qtrue; } -qboolean MenuParse_soundLoop( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_soundLoop(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_String_Parse(handle, &menu->soundName)) { return qfalse; @@ -9188,8 +8278,8 @@ qboolean MenuParse_soundLoop( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_fadeClamp( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeClamp(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Float_Parse(handle, &menu->fadeClamp)) { return qfalse; @@ -9197,8 +8287,8 @@ qboolean MenuParse_fadeClamp( itemDef_t *item, int handle ) { return qtrue; } -qboolean MenuParse_fadeAmount( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeAmount(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Float_Parse(handle, &menu->fadeAmount)) { return qfalse; @@ -9206,9 +8296,8 @@ qboolean MenuParse_fadeAmount( itemDef_t *item, int handle ) { return qtrue; } - -qboolean MenuParse_fadeCycle( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_fadeCycle(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (!PC_Int_Parse(handle, &menu->fadeCycle)) { return qfalse; @@ -9216,20 +8305,18 @@ qboolean MenuParse_fadeCycle( itemDef_t *item, int handle ) { return qtrue; } - -qboolean MenuParse_itemDef( itemDef_t *item, int handle ) { - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_itemDef(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; if (menu->itemCount < MAX_MENUITEMS) { - itemDef_t *newItem = menu->items[menu->itemCount] = (itemDef_t *) UI_Alloc(sizeof(itemDef_t)); + itemDef_t *newItem = menu->items[menu->itemCount] = (itemDef_t *)UI_Alloc(sizeof(itemDef_t)); Item_Init(newItem); - if (!Item_Parse(handle, newItem)) - { + if (!Item_Parse(handle, newItem)) { return qfalse; } - Item_InitControls( newItem ); + Item_InitControls(newItem); newItem->parent = menu->items[menu->itemCount]->parent = menu; menu->itemCount++; - Item_ApplyHacks( newItem ); + Item_ApplyHacks(newItem); } return qtrue; } @@ -9238,57 +8325,53 @@ qboolean MenuParse_itemDef( itemDef_t *item, int handle ) { MenuParse_focuscolor ================= */ -qboolean MenuParse_appearanceIncrement( itemDef_t *item, int handle ) -{ - menuDef_t *menu = (menuDef_t*)item; +qboolean MenuParse_appearanceIncrement(itemDef_t *item, int handle) { + menuDef_t *menu = (menuDef_t *)item; - if (!PC_Float_Parse(handle, &menu->appearanceIncrement)) - { + if (!PC_Float_Parse(handle, &menu->appearanceIncrement)) { return qfalse; } return qtrue; } -keywordHash_t menuParseKeywords[] = { - {"appearanceIncrement", MenuParse_appearanceIncrement, NULL }, - {"backcolor", MenuParse_backcolor, NULL }, - {"background", MenuParse_background, NULL }, - {"border", MenuParse_border, NULL }, - {"bordercolor", MenuParse_bordercolor, NULL }, - {"borderSize", MenuParse_borderSize, NULL }, - {"cinematic", MenuParse_cinematic, NULL }, - {"descAlignment", MenuParse_descAlignment,NULL }, - {"desccolor", MenuParse_descColor, NULL }, - {"descX", MenuParse_descX, NULL }, - {"descY", MenuParse_descY, NULL }, - {"descScale", MenuParse_descScale, NULL }, - {"disablecolor", MenuParse_disablecolor, NULL }, - {"fadeAmount", MenuParse_fadeAmount, NULL }, - {"fadeClamp", MenuParse_fadeClamp, NULL }, - {"fadeCycle", MenuParse_fadeCycle, NULL }, - {"focuscolor", MenuParse_focuscolor, NULL }, - {"font", MenuParse_font, NULL }, - {"forecolor", MenuParse_forecolor, NULL }, - {"fullscreen", MenuParse_fullscreen, NULL }, - {"itemDef", MenuParse_itemDef, NULL }, - {"name", MenuParse_name, NULL }, - {"onClose", MenuParse_onClose, NULL }, - //JLFACCEPT MPMOVED - {"onAccept", MenuParse_onAccept, NULL }, - - {"onESC", MenuParse_onESC, NULL }, - {"outOfBoundsClick", MenuParse_outOfBounds, NULL }, - {"onOpen", MenuParse_onOpen, NULL }, - {"outlinecolor", MenuParse_outlinecolor, NULL }, - {"ownerdraw", MenuParse_ownerdraw, NULL }, - {"ownerdrawFlag", MenuParse_ownerdrawFlag,NULL }, - {"popup", MenuParse_popup, NULL }, - {"rect", MenuParse_rect, NULL }, - {"soundLoop", MenuParse_soundLoop, NULL }, - {"style", MenuParse_style, NULL }, - {"visible", MenuParse_visible, NULL }, - {0, 0, 0 } -}; +keywordHash_t menuParseKeywords[] = {{"appearanceIncrement", MenuParse_appearanceIncrement, NULL}, + {"backcolor", MenuParse_backcolor, NULL}, + {"background", MenuParse_background, NULL}, + {"border", MenuParse_border, NULL}, + {"bordercolor", MenuParse_bordercolor, NULL}, + {"borderSize", MenuParse_borderSize, NULL}, + {"cinematic", MenuParse_cinematic, NULL}, + {"descAlignment", MenuParse_descAlignment, NULL}, + {"desccolor", MenuParse_descColor, NULL}, + {"descX", MenuParse_descX, NULL}, + {"descY", MenuParse_descY, NULL}, + {"descScale", MenuParse_descScale, NULL}, + {"disablecolor", MenuParse_disablecolor, NULL}, + {"fadeAmount", MenuParse_fadeAmount, NULL}, + {"fadeClamp", MenuParse_fadeClamp, NULL}, + {"fadeCycle", MenuParse_fadeCycle, NULL}, + {"focuscolor", MenuParse_focuscolor, NULL}, + {"font", MenuParse_font, NULL}, + {"forecolor", MenuParse_forecolor, NULL}, + {"fullscreen", MenuParse_fullscreen, NULL}, + {"itemDef", MenuParse_itemDef, NULL}, + {"name", MenuParse_name, NULL}, + {"onClose", MenuParse_onClose, NULL}, + // JLFACCEPT MPMOVED + {"onAccept", MenuParse_onAccept, NULL}, + + {"onESC", MenuParse_onESC, NULL}, + {"outOfBoundsClick", MenuParse_outOfBounds, NULL}, + {"onOpen", MenuParse_onOpen, NULL}, + {"outlinecolor", MenuParse_outlinecolor, NULL}, + {"ownerdraw", MenuParse_ownerdraw, NULL}, + {"ownerdrawFlag", MenuParse_ownerdrawFlag, NULL}, + {"popup", MenuParse_popup, NULL}, + {"rect", MenuParse_rect, NULL}, + {"soundLoop", MenuParse_soundLoop, NULL}, + {"style", MenuParse_style, NULL}, + {"visible", MenuParse_visible, NULL}, + {0, 0, 0}}; keywordHash_t *menuParseKeywordHash[KEYWORDHASH_SIZE]; @@ -9321,7 +8404,7 @@ qboolean Menu_Parse(int handle, menuDef_t *menu) { return qfalse; } - while ( 1 ) { + while (1) { if (!trap->PC_ReadToken(handle, &token)) { PC_SourceError(handle, "end of file inside menu"); return qfalse; @@ -9336,7 +8419,7 @@ qboolean Menu_Parse(int handle, menuDef_t *menu) { PC_SourceError(handle, "unknown menu keyword %s", token.string); continue; } - if ( !key->func((itemDef_t*)menu, handle) ) { + if (!key->func((itemDef_t *)menu, handle)) { PC_SourceError(handle, "couldn't parse menu keyword %s", token.string); return qfalse; } @@ -9361,9 +8444,7 @@ void Menu_New(int handle) { } } -int Menu_Count() { - return menuCount; -} +int Menu_Count() { return menuCount; } void Menu_PaintAll() { int i; @@ -9378,17 +8459,13 @@ void Menu_PaintAll() { if (debugMode) { vec4_t v = {1, 1, 1, 1}; DC->drawText(5, 25, .75, v, va("fps: %f", DC->FPS), 0, 0, 0, 0); - DC->drawText(5, 45, .75, v, va("x: %d y:%d", DC->cursorx,DC->cursory), 0, 0, 0, 0); + DC->drawText(5, 45, .75, v, va("x: %d y:%d", DC->cursorx, DC->cursory), 0, 0, 0, 0); } } -void Menu_Reset(void) { - menuCount = 0; -} +void Menu_Reset(void) { menuCount = 0; } -displayContextDef_t *Display_GetContext() { - return DC; -} +displayContextDef_t *Display_GetContext() { return DC; } void *Display_CaptureItem(int x, int y) { int i; @@ -9403,14 +8480,13 @@ void *Display_CaptureItem(int x, int y) { return NULL; } - // FIXME: qboolean Display_MouseMove(void *p, int x, int y) { int i; - menuDef_t *menu = (menuDef_t *) p; + menuDef_t *menu = (menuDef_t *)p; if (menu == NULL) { - menu = Menu_GetFocused(); + menu = Menu_GetFocused(); if (menu) { if (menu->window.flags & WINDOW_POPUP) { Menu_HandleMouseMove(menu, x, y); @@ -9425,8 +8501,7 @@ qboolean Display_MouseMove(void *p, int x, int y) { menu->window.rect.y += y; Menu_UpdatePosition(menu); } - return qtrue; - + return qtrue; } int Display_CursorType(int x, int y) { @@ -9443,14 +8518,13 @@ int Display_CursorType(int x, int y) { return CURSOR_ARROW; } - void Display_HandleKey(int key, qboolean down, int x, int y) { - menuDef_t *menu = (menuDef_t *) Display_CaptureItem(x, y); + menuDef_t *menu = (menuDef_t *)Display_CaptureItem(x, y); if (menu == NULL) { menu = Menu_GetFocused(); } if (menu) { - Menu_HandleKey(menu, key, down ); + Menu_HandleKey(menu, key, down); } } @@ -9463,12 +8537,10 @@ static void Window_CacheContents(windowDef_t *window) { } } - static void Item_CacheContents(itemDef_t *item) { if (item) { Window_CacheContents(&item->window); } - } static void Menu_CacheContents(menuDef_t *menu) { @@ -9483,7 +8555,6 @@ static void Menu_CacheContents(menuDef_t *menu) { DC->registerSound(menu->soundName); } } - } void Display_CacheAll() { @@ -9493,9 +8564,8 @@ void Display_CacheAll() { } } - static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) { - if (menu && menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED)) { + if (menu && menu->window.flags & (WINDOW_VISIBLE | WINDOW_FORCED)) { if (Rect_ContainsPoint(&menu->window.rect, x, y)) { int i; for (i = 0; i < menu->itemCount; i++) { @@ -9523,7 +8593,6 @@ static qboolean Menu_OverActiveItem(menuDef_t *menu, float x, float y) { } } } - } } return qfalse; diff --git a/codemp/ui/ui_syscalls.c b/codemp/ui/ui_syscalls.c index a2e4d8fd9c..dc41eb9558 100644 --- a/codemp/ui/ui_syscalls.c +++ b/codemp/ui/ui_syscalls.c @@ -25,423 +25,241 @@ along with this program; if not, see . // this file is only included when building a dll #include "ui_local.h" -static intptr_t (QDECL *Q_syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1; +static intptr_t(QDECL *Q_syscall)(intptr_t arg, ...) = (intptr_t(QDECL *)(intptr_t, ...)) - 1; -static void TranslateSyscalls( void ); +static void TranslateSyscalls(void); -Q_EXPORT void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) { +Q_EXPORT void dllEntry(intptr_t(QDECL *syscallptr)(intptr_t arg, ...)) { Q_syscall = syscallptr; TranslateSyscalls(); } -int PASSFLOAT( float x ) { +int PASSFLOAT(float x) { byteAlias_t fi; fi.f = x; return fi.i; } -void trap_Print( const char *string ) { - Q_syscall( UI_PRINT, string ); -} -NORETURN void trap_Error( const char *string ) { - Q_syscall( UI_ERROR, string ); +void trap_Print(const char *string) { Q_syscall(UI_PRINT, string); } +NORETURN void trap_Error(const char *string) { + Q_syscall(UI_ERROR, string); exit(1); } -int trap_Milliseconds( void ) { - return Q_syscall( UI_MILLISECONDS ); -} -void trap_Cvar_Register( vmCvar_t *cvar, const char *var_name, const char *value, uint32_t flags ) { - Q_syscall( UI_CVAR_REGISTER, cvar, var_name, value, flags ); -} -void trap_Cvar_Update( vmCvar_t *cvar ) { - Q_syscall( UI_CVAR_UPDATE, cvar ); -} -void trap_Cvar_Set( const char *var_name, const char *value ) { - Q_syscall( UI_CVAR_SET, var_name, value ); -} -float trap_Cvar_VariableValue( const char *var_name ) { +int trap_Milliseconds(void) { return Q_syscall(UI_MILLISECONDS); } +void trap_Cvar_Register(vmCvar_t *cvar, const char *var_name, const char *value, uint32_t flags) { Q_syscall(UI_CVAR_REGISTER, cvar, var_name, value, flags); } +void trap_Cvar_Update(vmCvar_t *cvar) { Q_syscall(UI_CVAR_UPDATE, cvar); } +void trap_Cvar_Set(const char *var_name, const char *value) { Q_syscall(UI_CVAR_SET, var_name, value); } +float trap_Cvar_VariableValue(const char *var_name) { byteAlias_t fi; - fi.i = Q_syscall( UI_CVAR_VARIABLEVALUE, var_name ); + fi.i = Q_syscall(UI_CVAR_VARIABLEVALUE, var_name); return fi.f; } -void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize ) { - Q_syscall( UI_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize ); -} -void trap_Cvar_SetValue( const char *var_name, float value ) { - Q_syscall( UI_CVAR_SETVALUE, var_name, PASSFLOAT( value ) ); -} -void trap_Cvar_Reset( const char *name ) { - Q_syscall( UI_CVAR_RESET, name ); -} -void trap_Cvar_Create( const char *var_name, const char *var_value, uint32_t flags ) { - Q_syscall( UI_CVAR_CREATE, var_name, var_value, flags ); -} -void trap_Cvar_InfoStringBuffer( int bit, char *buffer, int bufsize ) { - Q_syscall( UI_CVAR_INFOSTRINGBUFFER, bit, buffer, bufsize ); -} -int trap_Argc( void ) { - return Q_syscall( UI_ARGC ); -} -void trap_Argv( int n, char *buffer, int bufferLength ) { - Q_syscall( UI_ARGV, n, buffer, bufferLength ); -} -void trap_Cmd_ExecuteText( int exec_when, const char *text ) { - Q_syscall( UI_CMD_EXECUTETEXT, exec_when, text ); -} -int trap_FS_FOpenFile( const char *qpath, fileHandle_t *f, fsMode_t mode ) { - return Q_syscall( UI_FS_FOPENFILE, qpath, f, mode ); -} -void trap_FS_Read( void *buffer, int len, fileHandle_t f ) { - Q_syscall( UI_FS_READ, buffer, len, f ); -} -void trap_FS_Write( const void *buffer, int len, fileHandle_t f ) { - Q_syscall( UI_FS_WRITE, buffer, len, f ); -} -void trap_FS_FCloseFile( fileHandle_t f ) { - Q_syscall( UI_FS_FCLOSEFILE, f ); -} -int trap_FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) { - return Q_syscall( UI_FS_GETFILELIST, path, extension, listbuf, bufsize ); -} -qhandle_t trap_R_RegisterModel( const char *name ) { - return Q_syscall( UI_R_REGISTERMODEL, name ); -} -qhandle_t trap_R_RegisterSkin( const char *name ) { - return Q_syscall( UI_R_REGISTERSKIN, name ); -} -qhandle_t trap_R_RegisterFont( const char *fontName ) { - return Q_syscall( UI_R_REGISTERFONT, fontName); -} -int trap_R_Font_StrLenPixels(const char *text, const int iFontIndex, const float scale) { - //HACK! RE_Font_StrLenPixels works better with 1.0f scale - float width = (float)Q_syscall( UI_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); +void trap_Cvar_VariableStringBuffer(const char *var_name, char *buffer, int bufsize) { Q_syscall(UI_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize); } +void trap_Cvar_SetValue(const char *var_name, float value) { Q_syscall(UI_CVAR_SETVALUE, var_name, PASSFLOAT(value)); } +void trap_Cvar_Reset(const char *name) { Q_syscall(UI_CVAR_RESET, name); } +void trap_Cvar_Create(const char *var_name, const char *var_value, uint32_t flags) { Q_syscall(UI_CVAR_CREATE, var_name, var_value, flags); } +void trap_Cvar_InfoStringBuffer(int bit, char *buffer, int bufsize) { Q_syscall(UI_CVAR_INFOSTRINGBUFFER, bit, buffer, bufsize); } +int trap_Argc(void) { return Q_syscall(UI_ARGC); } +void trap_Argv(int n, char *buffer, int bufferLength) { Q_syscall(UI_ARGV, n, buffer, bufferLength); } +void trap_Cmd_ExecuteText(int exec_when, const char *text) { Q_syscall(UI_CMD_EXECUTETEXT, exec_when, text); } +int trap_FS_FOpenFile(const char *qpath, fileHandle_t *f, fsMode_t mode) { return Q_syscall(UI_FS_FOPENFILE, qpath, f, mode); } +void trap_FS_Read(void *buffer, int len, fileHandle_t f) { Q_syscall(UI_FS_READ, buffer, len, f); } +void trap_FS_Write(const void *buffer, int len, fileHandle_t f) { Q_syscall(UI_FS_WRITE, buffer, len, f); } +void trap_FS_FCloseFile(fileHandle_t f) { Q_syscall(UI_FS_FCLOSEFILE, f); } +int trap_FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize) { + return Q_syscall(UI_FS_GETFILELIST, path, extension, listbuf, bufsize); +} +qhandle_t trap_R_RegisterModel(const char *name) { return Q_syscall(UI_R_REGISTERMODEL, name); } +qhandle_t trap_R_RegisterSkin(const char *name) { return Q_syscall(UI_R_REGISTERSKIN, name); } +qhandle_t trap_R_RegisterFont(const char *fontName) { return Q_syscall(UI_R_REGISTERFONT, fontName); } +int trap_R_Font_StrLenPixels(const char *text, const int iFontIndex, const float scale) { + // HACK! RE_Font_StrLenPixels works better with 1.0f scale + float width = (float)Q_syscall(UI_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); return width * scale; } float trap_R_Font_StrLenPixelsFloat(const char *text, const int iFontIndex, const float scale) { - //HACK! RE_Font_StrLenPixels works better with 1.0f scale - float width = (float)Q_syscall( UI_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); + // HACK! RE_Font_StrLenPixels works better with 1.0f scale + float width = (float)Q_syscall(UI_R_FONT_STRLENPIXELS, text, iFontIndex, PASSFLOAT(1.0f)); return width * scale; } -int trap_R_Font_StrLenChars(const char *text) { - return Q_syscall( UI_R_FONT_STRLENCHARS, text); -} +int trap_R_Font_StrLenChars(const char *text) { return Q_syscall(UI_R_FONT_STRLENCHARS, text); } int trap_R_Font_HeightPixels(const int iFontIndex, const float scale) { - float height = (float)Q_syscall( UI_R_FONT_STRHEIGHTPIXELS, iFontIndex, PASSFLOAT( 1.0f ) ); + float height = (float)Q_syscall(UI_R_FONT_STRHEIGHTPIXELS, iFontIndex, PASSFLOAT(1.0f)); return height * scale; } void trap_R_Font_DrawString(int ox, int oy, const char *text, const float *rgba, const int setIndex, int iCharLimit, const float scale) { - Q_syscall( UI_R_FONT_DRAWSTRING, ox, oy, text, rgba, setIndex, iCharLimit, PASSFLOAT(scale)); -} -qboolean trap_Language_IsAsian(void) { - return Q_syscall( UI_LANGUAGE_ISASIAN ); + Q_syscall(UI_R_FONT_DRAWSTRING, ox, oy, text, rgba, setIndex, iCharLimit, PASSFLOAT(scale)); } -qboolean trap_Language_UsesSpaces(void) { - return Q_syscall( UI_LANGUAGE_USESSPACES ); +qboolean trap_Language_IsAsian(void) { return Q_syscall(UI_LANGUAGE_ISASIAN); } +qboolean trap_Language_UsesSpaces(void) { return Q_syscall(UI_LANGUAGE_USESSPACES); } +unsigned int trap_AnyLanguage_ReadCharFromString(const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation) { + return Q_syscall(UI_ANYLANGUAGE_READCHARFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation); } -unsigned int trap_AnyLanguage_ReadCharFromString( const char *psText, int *piAdvanceCount, qboolean *pbIsTrailingPunctuation ) { - return Q_syscall( UI_ANYLANGUAGE_READCHARFROMSTRING, psText, piAdvanceCount, pbIsTrailingPunctuation); -} -qhandle_t trap_R_RegisterShaderNoMip( const char *name ) { +qhandle_t trap_R_RegisterShaderNoMip(const char *name) { char buf[1024]; if (name[0] == '*') { - trap_Cvar_VariableStringBuffer(name+1, buf, sizeof(buf)); + trap_Cvar_VariableStringBuffer(name + 1, buf, sizeof(buf)); if (buf[0]) - return Q_syscall( UI_R_REGISTERSHADERNOMIP, &buf ); + return Q_syscall(UI_R_REGISTERSHADERNOMIP, &buf); } - return Q_syscall( UI_R_REGISTERSHADERNOMIP, name ); -} -void trap_R_ShaderNameFromIndex(char *name, int index) { - Q_syscall( UI_R_SHADERNAMEFROMINDEX, name, index ); -} -void trap_R_ClearScene( void ) { - Q_syscall( UI_R_CLEARSCENE ); -} -void trap_R_AddRefEntityToScene( const refEntity_t *re ) { - Q_syscall( UI_R_ADDREFENTITYTOSCENE, re ); -} -void trap_R_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts ) { - Q_syscall( UI_R_ADDPOLYTOSCENE, hShader, numVerts, verts ); -} -void trap_R_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { - Q_syscall( UI_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b) ); -} -void trap_R_RenderScene( const refdef_t *fd ) { - Q_syscall( UI_R_RENDERSCENE, fd ); -} -void trap_R_SetColor( const float *rgba ) { - Q_syscall( UI_R_SETCOLOR, rgba ); -} -void trap_R_DrawStretchPic( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ) { - Q_syscall( UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader ); -} -void trap_R_ModelBounds( clipHandle_t model, vec3_t mins, vec3_t maxs ) { - Q_syscall( UI_R_MODELBOUNDS, model, mins, maxs ); -} -void trap_UpdateScreen( void ) { - Q_syscall( UI_UPDATESCREEN ); -} -int trap_CM_LerpTag( orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName ) { - return Q_syscall( UI_CM_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName ); -} -void trap_S_StartLocalSound( sfxHandle_t sfx, int channelNum ) { - Q_syscall( UI_S_STARTLOCALSOUND, sfx, channelNum ); -} -sfxHandle_t trap_S_RegisterSound( const char *sample ) { - return Q_syscall( UI_S_REGISTERSOUND, sample ); -} -void trap_Key_KeynumToStringBuf( int keynum, char *buf, int buflen ) { - Q_syscall( UI_KEY_KEYNUMTOSTRINGBUF, keynum, buf, buflen ); -} -void trap_Key_GetBindingBuf( int keynum, char *buf, int buflen ) { - Q_syscall( UI_KEY_GETBINDINGBUF, keynum, buf, buflen ); -} -void trap_Key_SetBinding( int keynum, const char *binding ) { - Q_syscall( UI_KEY_SETBINDING, keynum, binding ); -} -qboolean trap_Key_IsDown( int keynum ) { - return Q_syscall( UI_KEY_ISDOWN, keynum ); -} -qboolean trap_Key_GetOverstrikeMode( void ) { - return Q_syscall( UI_KEY_GETOVERSTRIKEMODE ); -} -void trap_Key_SetOverstrikeMode( qboolean state ) { - Q_syscall( UI_KEY_SETOVERSTRIKEMODE, state ); -} -void trap_Key_ClearStates( void ) { - Q_syscall( UI_KEY_CLEARSTATES ); -} -int trap_Key_GetCatcher( void ) { - return Q_syscall( UI_KEY_GETCATCHER ); -} -void trap_Key_SetCatcher( int catcher ) { - Q_syscall( UI_KEY_SETCATCHER, catcher ); -} -void trap_GetClipboardData( char *buf, int bufsize ) { - Q_syscall( UI_GETCLIPBOARDDATA, buf, bufsize ); -} -void trap_GetClientState( uiClientState_t *state ) { - Q_syscall( UI_GETCLIENTSTATE, state ); -} -void trap_GetGlconfig( glconfig_t *glconfig ) { - Q_syscall( UI_GETGLCONFIG, glconfig ); -} -int trap_GetConfigString( int index, char* buff, int buffsize ) { - return Q_syscall( UI_GETCONFIGSTRING, index, buff, buffsize ); -} -int trap_LAN_GetServerCount( int source ) { - return Q_syscall( UI_LAN_GETSERVERCOUNT, source ); -} -void trap_LAN_GetServerAddressString( int source, int n, char *buf, int buflen ) { - Q_syscall( UI_LAN_GETSERVERADDRESSSTRING, source, n, buf, buflen ); -} -void trap_LAN_GetServerInfo( int source, int n, char *buf, int buflen ) { - Q_syscall( UI_LAN_GETSERVERINFO, source, n, buf, buflen ); -} -int trap_LAN_GetServerPing( int source, int n ) { - return Q_syscall( UI_LAN_GETSERVERPING, source, n ); -} -int trap_LAN_GetPingQueueCount( void ) { - return Q_syscall( UI_LAN_GETPINGQUEUECOUNT ); -} -int trap_LAN_ServerStatus( const char *serverAddress, char *serverStatus, int maxLen ) { - return Q_syscall( UI_LAN_SERVERSTATUS, serverAddress, serverStatus, maxLen ); -} -void trap_LAN_SaveCachedServers( void ) { - Q_syscall( UI_LAN_SAVECACHEDSERVERS ); -} -void trap_LAN_LoadCachedServers( void ) { - Q_syscall( UI_LAN_LOADCACHEDSERVERS ); -} -void trap_LAN_ResetPings(int n) { - Q_syscall( UI_LAN_RESETPINGS, n ); -} -void trap_LAN_ClearPing( int n ) { - Q_syscall( UI_LAN_CLEARPING, n ); -} -void trap_LAN_GetPing( int n, char *buf, int buflen, int *pingtime ) { - Q_syscall( UI_LAN_GETPING, n, buf, buflen, pingtime ); -} -void trap_LAN_GetPingInfo( int n, char *buf, int buflen ) { - Q_syscall( UI_LAN_GETPINGINFO, n, buf, buflen ); -} -void trap_LAN_MarkServerVisible( int source, int n, qboolean visible ) { - Q_syscall( UI_LAN_MARKSERVERVISIBLE, source, n, visible ); -} -int trap_LAN_ServerIsVisible( int source, int n) { - return Q_syscall( UI_LAN_SERVERISVISIBLE, source, n ); -} -qboolean trap_LAN_UpdateVisiblePings( int source ) { - return Q_syscall( UI_LAN_UPDATEVISIBLEPINGS, source ); -} -int trap_LAN_AddServer(int source, const char *name, const char *addr) { - return Q_syscall( UI_LAN_ADDSERVER, source, name, addr ); -} -void trap_LAN_RemoveServer(int source, const char *addr) { - Q_syscall( UI_LAN_REMOVESERVER, source, addr ); -} -int trap_LAN_CompareServers( int source, int sortKey, int sortDir, int s1, int s2 ) { - return Q_syscall( UI_LAN_COMPARESERVERS, source, sortKey, sortDir, s1, s2 ); -} -int trap_MemoryRemaining( void ) { - return Q_syscall( UI_MEMORY_REMAINING ); -} -int trap_PC_AddGlobalDefine( char *define ) { - return Q_syscall( UI_PC_ADD_GLOBAL_DEFINE, define ); -} -int trap_PC_LoadSource( const char *filename ) { - return Q_syscall( UI_PC_LOAD_SOURCE, filename ); -} -int trap_PC_FreeSource( int handle ) { - return Q_syscall( UI_PC_FREE_SOURCE, handle ); -} -int trap_PC_ReadToken( int handle, pc_token_t *pc_token ) { - return Q_syscall( UI_PC_READ_TOKEN, handle, pc_token ); -} -int trap_PC_SourceFileAndLine( int handle, char *filename, int *line ) { - return Q_syscall( UI_PC_SOURCE_FILE_AND_LINE, handle, filename, line ); -} -int trap_PC_LoadGlobalDefines ( const char* filename ) { - return Q_syscall ( UI_PC_LOAD_GLOBAL_DEFINES, filename ); -} -void trap_PC_RemoveAllGlobalDefines ( void ) { - Q_syscall ( UI_PC_REMOVE_ALL_GLOBAL_DEFINES ); -} -void trap_S_StopBackgroundTrack( void ) { - Q_syscall( UI_S_STOPBACKGROUNDTRACK ); -} -void trap_S_StartBackgroundTrack( const char *intro, const char *loop, qboolean bReturnWithoutStarting) { - Q_syscall( UI_S_STARTBACKGROUNDTRACK, intro, loop, bReturnWithoutStarting ); -} -int trap_RealTime(qtime_t *qtime) { - return Q_syscall( UI_REAL_TIME, qtime ); -} -int trap_CIN_PlayCinematic( const char *arg0, int xpos, int ypos, int width, int height, int bits) { - return Q_syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits); -} -e_status trap_CIN_StopCinematic(int handle) { - return Q_syscall(UI_CIN_STOPCINEMATIC, handle); -} -e_status trap_CIN_RunCinematic (int handle) { - return Q_syscall(UI_CIN_RUNCINEMATIC, handle); -} -void trap_CIN_DrawCinematic (int handle) { - Q_syscall(UI_CIN_DRAWCINEMATIC, handle); -} -void trap_CIN_SetExtents (int handle, int x, int y, int w, int h) { - Q_syscall(UI_CIN_SETEXTENTS, handle, x, y, w, h); -} -void trap_R_RemapShader( const char *oldShader, const char *newShader, const char *timeOffset ) { - Q_syscall( UI_R_REMAP_SHADER, oldShader, newShader, timeOffset ); -} -int trap_SP_GetNumLanguages( void ) { - return Q_syscall( UI_SP_GETNUMLANGUAGES ); -} -void trap_GetLanguageName( const int languageIndex, char *buffer ) { - Q_syscall( UI_SP_GETLANGUAGENAME, languageIndex, buffer); -} + return Q_syscall(UI_R_REGISTERSHADERNOMIP, name); +} +void trap_R_ShaderNameFromIndex(char *name, int index) { Q_syscall(UI_R_SHADERNAMEFROMINDEX, name, index); } +void trap_R_ClearScene(void) { Q_syscall(UI_R_CLEARSCENE); } +void trap_R_AddRefEntityToScene(const refEntity_t *re) { Q_syscall(UI_R_ADDREFENTITYTOSCENE, re); } +void trap_R_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts) { Q_syscall(UI_R_ADDPOLYTOSCENE, hShader, numVerts, verts); } +void trap_R_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) { + Q_syscall(UI_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b)); +} +void trap_R_RenderScene(const refdef_t *fd) { Q_syscall(UI_R_RENDERSCENE, fd); } +void trap_R_SetColor(const float *rgba) { Q_syscall(UI_R_SETCOLOR, rgba); } +void trap_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) { + Q_syscall(UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader); +} +void trap_R_ModelBounds(clipHandle_t model, vec3_t mins, vec3_t maxs) { Q_syscall(UI_R_MODELBOUNDS, model, mins, maxs); } +void trap_UpdateScreen(void) { Q_syscall(UI_UPDATESCREEN); } +int trap_CM_LerpTag(orientation_t *tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char *tagName) { + return Q_syscall(UI_CM_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName); +} +void trap_S_StartLocalSound(sfxHandle_t sfx, int channelNum) { Q_syscall(UI_S_STARTLOCALSOUND, sfx, channelNum); } +sfxHandle_t trap_S_RegisterSound(const char *sample) { return Q_syscall(UI_S_REGISTERSOUND, sample); } +void trap_Key_KeynumToStringBuf(int keynum, char *buf, int buflen) { Q_syscall(UI_KEY_KEYNUMTOSTRINGBUF, keynum, buf, buflen); } +void trap_Key_GetBindingBuf(int keynum, char *buf, int buflen) { Q_syscall(UI_KEY_GETBINDINGBUF, keynum, buf, buflen); } +void trap_Key_SetBinding(int keynum, const char *binding) { Q_syscall(UI_KEY_SETBINDING, keynum, binding); } +qboolean trap_Key_IsDown(int keynum) { return Q_syscall(UI_KEY_ISDOWN, keynum); } +qboolean trap_Key_GetOverstrikeMode(void) { return Q_syscall(UI_KEY_GETOVERSTRIKEMODE); } +void trap_Key_SetOverstrikeMode(qboolean state) { Q_syscall(UI_KEY_SETOVERSTRIKEMODE, state); } +void trap_Key_ClearStates(void) { Q_syscall(UI_KEY_CLEARSTATES); } +int trap_Key_GetCatcher(void) { return Q_syscall(UI_KEY_GETCATCHER); } +void trap_Key_SetCatcher(int catcher) { Q_syscall(UI_KEY_SETCATCHER, catcher); } +void trap_GetClipboardData(char *buf, int bufsize) { Q_syscall(UI_GETCLIPBOARDDATA, buf, bufsize); } +void trap_GetClientState(uiClientState_t *state) { Q_syscall(UI_GETCLIENTSTATE, state); } +void trap_GetGlconfig(glconfig_t *glconfig) { Q_syscall(UI_GETGLCONFIG, glconfig); } +int trap_GetConfigString(int index, char *buff, int buffsize) { return Q_syscall(UI_GETCONFIGSTRING, index, buff, buffsize); } +int trap_LAN_GetServerCount(int source) { return Q_syscall(UI_LAN_GETSERVERCOUNT, source); } +void trap_LAN_GetServerAddressString(int source, int n, char *buf, int buflen) { Q_syscall(UI_LAN_GETSERVERADDRESSSTRING, source, n, buf, buflen); } +void trap_LAN_GetServerInfo(int source, int n, char *buf, int buflen) { Q_syscall(UI_LAN_GETSERVERINFO, source, n, buf, buflen); } +int trap_LAN_GetServerPing(int source, int n) { return Q_syscall(UI_LAN_GETSERVERPING, source, n); } +int trap_LAN_GetPingQueueCount(void) { return Q_syscall(UI_LAN_GETPINGQUEUECOUNT); } +int trap_LAN_ServerStatus(const char *serverAddress, char *serverStatus, int maxLen) { + return Q_syscall(UI_LAN_SERVERSTATUS, serverAddress, serverStatus, maxLen); +} +void trap_LAN_SaveCachedServers(void) { Q_syscall(UI_LAN_SAVECACHEDSERVERS); } +void trap_LAN_LoadCachedServers(void) { Q_syscall(UI_LAN_LOADCACHEDSERVERS); } +void trap_LAN_ResetPings(int n) { Q_syscall(UI_LAN_RESETPINGS, n); } +void trap_LAN_ClearPing(int n) { Q_syscall(UI_LAN_CLEARPING, n); } +void trap_LAN_GetPing(int n, char *buf, int buflen, int *pingtime) { Q_syscall(UI_LAN_GETPING, n, buf, buflen, pingtime); } +void trap_LAN_GetPingInfo(int n, char *buf, int buflen) { Q_syscall(UI_LAN_GETPINGINFO, n, buf, buflen); } +void trap_LAN_MarkServerVisible(int source, int n, qboolean visible) { Q_syscall(UI_LAN_MARKSERVERVISIBLE, source, n, visible); } +int trap_LAN_ServerIsVisible(int source, int n) { return Q_syscall(UI_LAN_SERVERISVISIBLE, source, n); } +qboolean trap_LAN_UpdateVisiblePings(int source) { return Q_syscall(UI_LAN_UPDATEVISIBLEPINGS, source); } +int trap_LAN_AddServer(int source, const char *name, const char *addr) { return Q_syscall(UI_LAN_ADDSERVER, source, name, addr); } +void trap_LAN_RemoveServer(int source, const char *addr) { Q_syscall(UI_LAN_REMOVESERVER, source, addr); } +int trap_LAN_CompareServers(int source, int sortKey, int sortDir, int s1, int s2) { return Q_syscall(UI_LAN_COMPARESERVERS, source, sortKey, sortDir, s1, s2); } +int trap_MemoryRemaining(void) { return Q_syscall(UI_MEMORY_REMAINING); } +int trap_PC_AddGlobalDefine(char *define) { return Q_syscall(UI_PC_ADD_GLOBAL_DEFINE, define); } +int trap_PC_LoadSource(const char *filename) { return Q_syscall(UI_PC_LOAD_SOURCE, filename); } +int trap_PC_FreeSource(int handle) { return Q_syscall(UI_PC_FREE_SOURCE, handle); } +int trap_PC_ReadToken(int handle, pc_token_t *pc_token) { return Q_syscall(UI_PC_READ_TOKEN, handle, pc_token); } +int trap_PC_SourceFileAndLine(int handle, char *filename, int *line) { return Q_syscall(UI_PC_SOURCE_FILE_AND_LINE, handle, filename, line); } +int trap_PC_LoadGlobalDefines(const char *filename) { return Q_syscall(UI_PC_LOAD_GLOBAL_DEFINES, filename); } +void trap_PC_RemoveAllGlobalDefines(void) { Q_syscall(UI_PC_REMOVE_ALL_GLOBAL_DEFINES); } +void trap_S_StopBackgroundTrack(void) { Q_syscall(UI_S_STOPBACKGROUNDTRACK); } +void trap_S_StartBackgroundTrack(const char *intro, const char *loop, qboolean bReturnWithoutStarting) { + Q_syscall(UI_S_STARTBACKGROUNDTRACK, intro, loop, bReturnWithoutStarting); +} +int trap_RealTime(qtime_t *qtime) { return Q_syscall(UI_REAL_TIME, qtime); } +int trap_CIN_PlayCinematic(const char *arg0, int xpos, int ypos, int width, int height, int bits) { + return Q_syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits); +} +e_status trap_CIN_StopCinematic(int handle) { return Q_syscall(UI_CIN_STOPCINEMATIC, handle); } +e_status trap_CIN_RunCinematic(int handle) { return Q_syscall(UI_CIN_RUNCINEMATIC, handle); } +void trap_CIN_DrawCinematic(int handle) { Q_syscall(UI_CIN_DRAWCINEMATIC, handle); } +void trap_CIN_SetExtents(int handle, int x, int y, int w, int h) { Q_syscall(UI_CIN_SETEXTENTS, handle, x, y, w, h); } +void trap_R_RemapShader(const char *oldShader, const char *newShader, const char *timeOffset) { + Q_syscall(UI_R_REMAP_SHADER, oldShader, newShader, timeOffset); +} +int trap_SP_GetNumLanguages(void) { return Q_syscall(UI_SP_GETNUMLANGUAGES); } +void trap_GetLanguageName(const int languageIndex, char *buffer) { Q_syscall(UI_SP_GETLANGUAGENAME, languageIndex, buffer); } qboolean trap_SP_GetStringTextString(const char *text, char *buffer, int bufferLength) { - return Q_syscall( UI_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength ); -} -void trap_G2_ListModelSurfaces(void *ghlInfo) { - Q_syscall( UI_G2_LISTSURFACES, ghlInfo); -} -void trap_G2_ListModelBones(void *ghlInfo, int frame) { - Q_syscall( UI_G2_LISTBONES, ghlInfo, frame); -} -void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { - Q_syscall( UI_G2_SETMODELS, ghoul2, modelList, skinList); -} -qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { - return (qboolean)(Q_syscall(UI_G2_HAVEWEGHOULMODELS, ghoul2)); -} -qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { + return Q_syscall(UI_SP_GETSTRINGTEXTSTRING, text, buffer, bufferLength); +} +void trap_G2_ListModelSurfaces(void *ghlInfo) { Q_syscall(UI_G2_LISTSURFACES, ghlInfo); } +void trap_G2_ListModelBones(void *ghlInfo, int frame) { Q_syscall(UI_G2_LISTBONES, ghlInfo, frame); } +void trap_G2_SetGhoul2ModelIndexes(void *ghoul2, qhandle_t *modelList, qhandle_t *skinList) { Q_syscall(UI_G2_SETMODELS, ghoul2, modelList, skinList); } +qboolean trap_G2_HaveWeGhoul2Models(void *ghoul2) { return (qboolean)(Q_syscall(UI_G2_HAVEWEGHOULMODELS, ghoul2)); } +qboolean trap_G2API_GetBoltMatrix(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, + const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(UI_G2_GETBOLT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoReconstruct( void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale ) { +qboolean trap_G2API_GetBoltMatrix_NoReconstruct(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(UI_G2_GETBOLT_NOREC, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { +qboolean trap_G2API_GetBoltMatrix_NoRecNoRot(void *ghoul2, const int modelIndex, const int boltIndex, mdxaBone_t *matrix, const vec3_t angles, + const vec3_t position, const int frameNum, qhandle_t *modelList, vec3_t scale) { return (qboolean)(Q_syscall(UI_G2_GETBOLT_NOREC_NOROT, ghoul2, modelIndex, boltIndex, matrix, angles, position, frameNum, modelList, scale)); } -int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, int lodBias) { +int trap_G2API_InitGhoul2Model(void **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, qhandle_t customShader, int modelFlags, + int lodBias) { return Q_syscall(UI_G2_INITGHOUL2MODEL, ghoul2Ptr, fileName, modelIndex, customSkin, customShader, modelFlags, lodBias); } qboolean trap_G2API_SetSkin(void *ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) { return Q_syscall(UI_G2_SETSKIN, ghoul2, modelIndex, customSkin, renderSkin); } -void trap_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( UI_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); +void trap_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(UI_G2_COLLISIONDETECT, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, + PASSFLOAT(fRadius)); } -void trap_G2API_CollisionDetectCache( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius ) { - Q_syscall ( UI_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, PASSFLOAT(fRadius) ); +void trap_G2API_CollisionDetectCache(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + const vec3_t rayStart, const vec3_t rayEnd, const vec3_t scale, int traceFlags, int useLod, float fRadius) { + Q_syscall(UI_G2_COLLISIONDETECTCACHE, collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, + PASSFLOAT(fRadius)); } -void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { - Q_syscall(UI_G2_CLEANMODELS, ghoul2Ptr); -} -qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, const int forward, qhandle_t *modelList, int blendTime, int currentTime ) { +void trap_G2API_CleanGhoul2Models(void **ghoul2Ptr) { Q_syscall(UI_G2_CLEANMODELS, ghoul2Ptr); } +qboolean trap_G2API_SetBoneAngles(void *ghoul2, int modelIndex, const char *boneName, const vec3_t angles, const int flags, const int up, const int right, + const int forward, qhandle_t *modelList, int blendTime, int currentTime) { return (Q_syscall(UI_G2_ANGLEOVERRIDE, ghoul2, modelIndex, boneName, angles, flags, up, right, forward, modelList, blendTime, currentTime)); } -qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, const float animSpeed, const int currentTime, const float setFrame, const int blendTime ) { - return Q_syscall(UI_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), blendTime); +qboolean trap_G2API_SetBoneAnim(void *ghoul2, const int modelIndex, const char *boneName, const int startFrame, const int endFrame, const int flags, + const float animSpeed, const int currentTime, const float setFrame, const int blendTime) { + return Q_syscall(UI_G2_PLAYANIM, ghoul2, modelIndex, boneName, startFrame, endFrame, flags, PASSFLOAT(animSpeed), currentTime, PASSFLOAT(setFrame), + blendTime); } -qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList, const int modelIndex) { +qboolean trap_G2API_GetBoneAnim(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *startFrame, int *endFrame, int *flags, + float *animSpeed, int *modelList, const int modelIndex) { return Q_syscall(UI_G2_GETBONEANIM, ghoul2, boneName, currentTime, currentFrame, startFrame, endFrame, flags, animSpeed, modelList, modelIndex); } qboolean trap_G2API_GetBoneFrame(void *ghoul2, const char *boneName, const int currentTime, float *currentFrame, int *modelList, const int modelIndex) { return Q_syscall(UI_G2_GETBONEFRAME, ghoul2, boneName, currentTime, currentFrame, modelList, modelIndex); } -void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { - Q_syscall(UI_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); -} -int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { - return Q_syscall(UI_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); -} +void trap_G2API_GetGLAName(void *ghoul2, int modelIndex, char *fillBuf) { Q_syscall(UI_G2_GETGLANAME, ghoul2, modelIndex, fillBuf); } +int trap_G2API_CopyGhoul2Instance(void *g2From, void *g2To, int modelIndex) { return Q_syscall(UI_G2_COPYGHOUL2INSTANCE, g2From, g2To, modelIndex); } void trap_G2API_CopySpecificGhoul2Model(void *g2From, int modelFrom, void *g2To, int modelTo) { Q_syscall(UI_G2_COPYSPECIFICGHOUL2MODEL, g2From, modelFrom, g2To, modelTo); } -void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { - Q_syscall(UI_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); -} -qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { - return Q_syscall(UI_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); -} -qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { - return Q_syscall(UI_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); -} -int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { - return Q_syscall(UI_G2_ADDBOLT, ghoul2, modelIndex, boneName); -} -void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { - Q_syscall(UI_G2_SETBOLTON, ghoul2, modelIndex, boltInfo); -} +void trap_G2API_DuplicateGhoul2Instance(void *g2From, void **g2To) { Q_syscall(UI_G2_DUPLICATEGHOUL2INSTANCE, g2From, g2To); } +qboolean trap_G2API_HasGhoul2ModelOnIndex(void *ghlInfo, int modelIndex) { return Q_syscall(UI_G2_HASGHOUL2MODELONINDEX, ghlInfo, modelIndex); } +qboolean trap_G2API_RemoveGhoul2Model(void *ghlInfo, int modelIndex) { return Q_syscall(UI_G2_REMOVEGHOUL2MODEL, ghlInfo, modelIndex); } +int trap_G2API_AddBolt(void *ghoul2, int modelIndex, const char *boneName) { return Q_syscall(UI_G2_ADDBOLT, ghoul2, modelIndex, boneName); } +void trap_G2API_SetBoltInfo(void *ghoul2, int modelIndex, int boltInfo) { Q_syscall(UI_G2_SETBOLTON, ghoul2, modelIndex, boltInfo); } qboolean trap_G2API_SetRootSurface(void *ghoul2, const int modelIndex, const char *surfaceName) { return Q_syscall(UI_G2_SETROOTSURFACE, ghoul2, modelIndex, surfaceName); } qboolean trap_G2API_SetSurfaceOnOff(void *ghoul2, const char *surfaceName, const int flags) { return Q_syscall(UI_G2_SETSURFACEONOFF, ghoul2, surfaceName, flags); } -qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { - return Q_syscall(UI_G2_SETNEWORIGIN, ghoul2, boltIndex); -} -int trap_G2API_GetTime(void) { - return Q_syscall(UI_G2_GETTIME); -} -void trap_G2API_SetTime(int time, int clock) { - Q_syscall(UI_G2_SETTIME, time, clock); -} -void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { - Q_syscall(UI_G2_SETRAGDOLL, ghoul2, params); -} -void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { - Q_syscall(UI_G2_ANIMATEG2MODELS, ghoul2, time, params); -} +qboolean trap_G2API_SetNewOrigin(void *ghoul2, const int boltIndex) { return Q_syscall(UI_G2_SETNEWORIGIN, ghoul2, boltIndex); } +int trap_G2API_GetTime(void) { return Q_syscall(UI_G2_GETTIME); } +void trap_G2API_SetTime(int time, int clock) { Q_syscall(UI_G2_SETTIME, time, clock); } +void trap_G2API_SetRagDoll(void *ghoul2, sharedRagDollParams_t *params) { Q_syscall(UI_G2_SETRAGDOLL, ghoul2, params); } +void trap_G2API_AnimateG2Models(void *ghoul2, int time, sharedRagDollUpdateParams_t *params) { Q_syscall(UI_G2_ANIMATEG2MODELS, ghoul2, time, params); } qboolean trap_G2API_SetBoneIKState(void *ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) { return Q_syscall(UI_G2_SETBONEIKSTATE, ghoul2, time, boneName, ikState, params); } -qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { - return Q_syscall(UI_G2_IKMOVE, ghoul2, time, params); -} +qboolean trap_G2API_IKMove(void *ghoul2, int time, sharedIKMoveParams_t *params) { return Q_syscall(UI_G2_IKMOVE, ghoul2, time, params); } void trap_G2API_GetSurfaceName(void *ghoul2, int surfNumber, int modelIndex, char *fillBuf) { Q_syscall(UI_G2_GETSURFACENAME, ghoul2, surfNumber, modelIndex, fillBuf); } @@ -449,206 +267,212 @@ qboolean trap_G2API_AttachG2Model(void *ghoul2From, int modelIndexFrom, void *gh return Q_syscall(UI_G2_ATTACHG2MODEL, ghoul2From, modelIndexFrom, ghoul2To, toBoltIndex, toModel); } - // Translate import table funcptrs to syscalls -int UISyscall_FS_Read( void *buffer, int len, fileHandle_t f ) { trap_FS_Read( buffer, len, f ); return 0; } -int UISyscall_FS_Write( const void *buffer, int len, fileHandle_t f ) { trap_FS_Write( buffer, len, f ); return 0; } -void UISyscall_R_AddPolysToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int num ) { trap_R_AddPolyToScene( hShader, numVerts, verts ); } -void UISyscall_G2API_CollisionDetect( CollisionRecord_t *collRecMap, void* ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius ) { trap_G2API_CollisionDetect( collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, fRadius ); } +int UISyscall_FS_Read(void *buffer, int len, fileHandle_t f) { + trap_FS_Read(buffer, len, f); + return 0; +} +int UISyscall_FS_Write(const void *buffer, int len, fileHandle_t f) { + trap_FS_Write(buffer, len, f); + return 0; +} +void UISyscall_R_AddPolysToScene(qhandle_t hShader, int numVerts, const polyVert_t *verts, int num) { trap_R_AddPolyToScene(hShader, numVerts, verts); } +void UISyscall_G2API_CollisionDetect(CollisionRecord_t *collRecMap, void *ghoul2, const vec3_t angles, const vec3_t position, int frameNumber, int entNum, + vec3_t rayStart, vec3_t rayEnd, vec3_t scale, int traceFlags, int useLod, float fRadius) { + trap_G2API_CollisionDetect(collRecMap, ghoul2, angles, position, frameNumber, entNum, rayStart, rayEnd, scale, traceFlags, useLod, fRadius); +} -void UISyscall_AddCommand( const char *cmd_name ) -{ +void UISyscall_AddCommand(const char *cmd_name) { // TODO warn developer only - Com_Printf( S_COLOR_YELLOW "WARNING: trap->ext.AddCommand() is only supported with OpenJK mod API!\n" ); + Com_Printf(S_COLOR_YELLOW "WARNING: trap->ext.AddCommand() is only supported with OpenJK mod API!\n"); } -void UISyscall_RemoveCommand( const char *cmd_name ) -{ +void UISyscall_RemoveCommand(const char *cmd_name) { // TODO warn developer only - Com_Printf( S_COLOR_YELLOW "WARNING: trap->ext.RemoveCommand() is only supported with OpenJK mod API!\n" ); + Com_Printf(S_COLOR_YELLOW "WARNING: trap->ext.RemoveCommand() is only supported with OpenJK mod API!\n"); } -NORETURN void QDECL UI_Error( int level, const char *error, ... ) { +NORETURN void QDECL UI_Error(int level, const char *error, ...) { va_list argptr; char text[4096] = {0}; - va_start( argptr, error ); - Q_vsnprintf( text, sizeof( text ), error, argptr ); - va_end( argptr ); + va_start(argptr, error); + Q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); - trap_Error( text ); + trap_Error(text); } -void QDECL UI_Printf( const char *msg, ... ) { +void QDECL UI_Printf(const char *msg, ...) { va_list argptr; char text[4096] = {0}; int ret; - va_start( argptr, msg ); - ret = Q_vsnprintf( text, sizeof( text ), msg, argptr ); - va_end( argptr ); + va_start(argptr, msg); + ret = Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); - if ( ret == -1 ) - trap_Print( "UI_Printf: overflow of 4096 bytes buffer\n" ); + if (ret == -1) + trap_Print("UI_Printf: overflow of 4096 bytes buffer\n"); else - trap_Print( text ); + trap_Print(text); } -static void TranslateSyscalls( void ) { +static void TranslateSyscalls(void) { static uiImport_t import; - memset( &import, 0, sizeof( import ) ); + memset(&import, 0, sizeof(import)); trap = &import; - Com_Error = UI_Error; - Com_Printf = UI_Printf; - - trap->Print = UI_Printf; - trap->Error = UI_Error; - trap->Milliseconds = trap_Milliseconds; - trap->RealTime = trap_RealTime; - trap->MemoryRemaining = trap_MemoryRemaining; - - trap->Cvar_Create = trap_Cvar_Create; - trap->Cvar_InfoStringBuffer = trap_Cvar_InfoStringBuffer; - trap->Cvar_Register = trap_Cvar_Register; - trap->Cvar_Reset = trap_Cvar_Reset; - trap->Cvar_Set = trap_Cvar_Set; - trap->Cvar_SetValue = trap_Cvar_SetValue; - trap->Cvar_Update = trap_Cvar_Update; - trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; - trap->Cvar_VariableValue = trap_Cvar_VariableValue; - - trap->Cmd_Argc = trap_Argc; - trap->Cmd_Argv = trap_Argv; - trap->Cmd_ExecuteText = trap_Cmd_ExecuteText; - - trap->FS_Close = trap_FS_FCloseFile; - trap->FS_GetFileList = trap_FS_GetFileList; - trap->FS_Open = trap_FS_FOpenFile; - trap->FS_Read = UISyscall_FS_Read; - trap->FS_Write = UISyscall_FS_Write; - - trap->GetClientState = trap_GetClientState; - trap->GetClipboardData = trap_GetClipboardData; - trap->GetConfigString = trap_GetConfigString; - trap->GetGlconfig = trap_GetGlconfig; - trap->UpdateScreen = trap_UpdateScreen; - - trap->Key_ClearStates = trap_Key_ClearStates; - trap->Key_GetBindingBuf = trap_Key_GetBindingBuf; - trap->Key_IsDown = trap_Key_IsDown; - trap->Key_KeynumToStringBuf = trap_Key_KeynumToStringBuf; - trap->Key_SetBinding = trap_Key_SetBinding; - trap->Key_GetCatcher = trap_Key_GetCatcher; - trap->Key_GetOverstrikeMode = trap_Key_GetOverstrikeMode; - trap->Key_SetCatcher = trap_Key_SetCatcher; - trap->Key_SetOverstrikeMode = trap_Key_SetOverstrikeMode; - - trap->PC_AddGlobalDefine = trap_PC_AddGlobalDefine; - trap->PC_FreeSource = trap_PC_FreeSource; - trap->PC_LoadGlobalDefines = trap_PC_LoadGlobalDefines; - trap->PC_LoadSource = trap_PC_LoadSource; - trap->PC_ReadToken = trap_PC_ReadToken; - trap->PC_RemoveAllGlobalDefines = trap_PC_RemoveAllGlobalDefines; - trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; - - trap->CIN_DrawCinematic = trap_CIN_DrawCinematic; - trap->CIN_PlayCinematic = trap_CIN_PlayCinematic; - trap->CIN_RunCinematic = trap_CIN_RunCinematic; - trap->CIN_SetExtents = trap_CIN_SetExtents; - trap->CIN_StopCinematic = trap_CIN_StopCinematic; - - trap->LAN_AddServer = trap_LAN_AddServer; - trap->LAN_ClearPing = trap_LAN_ClearPing; - trap->LAN_CompareServers = trap_LAN_CompareServers; - trap->LAN_GetPing = trap_LAN_GetPing; - trap->LAN_GetPingInfo = trap_LAN_GetPingInfo; - trap->LAN_GetPingQueueCount = trap_LAN_GetPingQueueCount; - trap->LAN_GetServerAddressString = trap_LAN_GetServerAddressString; - trap->LAN_GetServerCount = trap_LAN_GetServerCount; - trap->LAN_GetServerInfo = trap_LAN_GetServerInfo; - trap->LAN_GetServerPing = trap_LAN_GetServerPing; - trap->LAN_LoadCachedServers = trap_LAN_LoadCachedServers; - trap->LAN_MarkServerVisible = trap_LAN_MarkServerVisible; - trap->LAN_RemoveServer = trap_LAN_RemoveServer; - trap->LAN_ResetPings = trap_LAN_ResetPings; - trap->LAN_SaveCachedServers = trap_LAN_SaveCachedServers; - trap->LAN_ServerIsVisible = trap_LAN_ServerIsVisible; - trap->LAN_ServerStatus = trap_LAN_ServerStatus; - trap->LAN_UpdateVisiblePings = trap_LAN_UpdateVisiblePings; - - trap->S_StartBackgroundTrack = trap_S_StartBackgroundTrack; - trap->S_StartLocalSound = trap_S_StartLocalSound; - trap->S_StopBackgroundTrack = trap_S_StopBackgroundTrack; - trap->S_RegisterSound = trap_S_RegisterSound; - - trap->SE_GetLanguageName = trap_GetLanguageName; - trap->SE_GetNumLanguages = trap_SP_GetNumLanguages; - trap->SE_GetStringTextString = trap_SP_GetStringTextString; - - trap->R_Language_IsAsian = trap_Language_IsAsian; - trap->R_Language_UsesSpaces = trap_Language_UsesSpaces; - trap->R_AnyLanguage_ReadCharFromString = trap_AnyLanguage_ReadCharFromString; - - trap->R_AddLightToScene = trap_R_AddLightToScene; - trap->R_AddPolysToScene = UISyscall_R_AddPolysToScene; - trap->R_AddRefEntityToScene = trap_R_AddRefEntityToScene; - trap->R_ClearScene = trap_R_ClearScene; - trap->R_DrawStretchPic = trap_R_DrawStretchPic; - trap->R_Font_DrawString = trap_R_Font_DrawString; - trap->R_Font_HeightPixels = trap_R_Font_HeightPixels; - trap->R_Font_StrLenChars = trap_R_Font_StrLenChars; - trap->R_Font_StrLenPixels = trap_R_Font_StrLenPixels; - trap->R_LerpTag = trap_CM_LerpTag; - trap->R_ModelBounds = trap_R_ModelBounds; - trap->R_RegisterFont = trap_R_RegisterFont; - trap->R_RegisterModel = trap_R_RegisterModel; - trap->R_RegisterShaderNoMip = trap_R_RegisterShaderNoMip; - trap->R_RegisterSkin = trap_R_RegisterSkin; - trap->R_RemapShader = trap_R_RemapShader; - trap->R_RenderScene = trap_R_RenderScene; - trap->R_SetColor = trap_R_SetColor; - trap->R_ShaderNameFromIndex = trap_R_ShaderNameFromIndex; - - trap->G2_ListModelSurfaces = trap_G2_ListModelSurfaces; - trap->G2_ListModelBones = trap_G2_ListModelBones; - trap->G2_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; - trap->G2_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; - trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; - trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; - trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; - trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; - trap->G2API_SetSkin = trap_G2API_SetSkin; - trap->G2API_CollisionDetect = UISyscall_G2API_CollisionDetect; - trap->G2API_CollisionDetectCache = UISyscall_G2API_CollisionDetect; - trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; - trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; - trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; - trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; - trap->G2API_GetBoneFrame = trap_G2API_GetBoneFrame; - trap->G2API_GetGLAName = trap_G2API_GetGLAName; - trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; - trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; - trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; - trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; - trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; - trap->G2API_AddBolt = trap_G2API_AddBolt; - trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; - trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; - trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; - trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; - trap->G2API_GetTime = trap_G2API_GetTime; - trap->G2API_SetTime = trap_G2API_SetTime; - trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; - trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; - trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; - trap->G2API_IKMove = trap_G2API_IKMove; - trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; - trap->G2API_AttachG2Model = trap_G2API_AttachG2Model; - - trap->ext.R_Font_StrLenPixels = trap_R_Font_StrLenPixelsFloat; - trap->ext.AddCommand = UISyscall_AddCommand; - trap->ext.RemoveCommand = UISyscall_RemoveCommand; + Com_Error = UI_Error; + Com_Printf = UI_Printf; + + trap->Print = UI_Printf; + trap->Error = UI_Error; + trap->Milliseconds = trap_Milliseconds; + trap->RealTime = trap_RealTime; + trap->MemoryRemaining = trap_MemoryRemaining; + + trap->Cvar_Create = trap_Cvar_Create; + trap->Cvar_InfoStringBuffer = trap_Cvar_InfoStringBuffer; + trap->Cvar_Register = trap_Cvar_Register; + trap->Cvar_Reset = trap_Cvar_Reset; + trap->Cvar_Set = trap_Cvar_Set; + trap->Cvar_SetValue = trap_Cvar_SetValue; + trap->Cvar_Update = trap_Cvar_Update; + trap->Cvar_VariableStringBuffer = trap_Cvar_VariableStringBuffer; + trap->Cvar_VariableValue = trap_Cvar_VariableValue; + + trap->Cmd_Argc = trap_Argc; + trap->Cmd_Argv = trap_Argv; + trap->Cmd_ExecuteText = trap_Cmd_ExecuteText; + + trap->FS_Close = trap_FS_FCloseFile; + trap->FS_GetFileList = trap_FS_GetFileList; + trap->FS_Open = trap_FS_FOpenFile; + trap->FS_Read = UISyscall_FS_Read; + trap->FS_Write = UISyscall_FS_Write; + + trap->GetClientState = trap_GetClientState; + trap->GetClipboardData = trap_GetClipboardData; + trap->GetConfigString = trap_GetConfigString; + trap->GetGlconfig = trap_GetGlconfig; + trap->UpdateScreen = trap_UpdateScreen; + + trap->Key_ClearStates = trap_Key_ClearStates; + trap->Key_GetBindingBuf = trap_Key_GetBindingBuf; + trap->Key_IsDown = trap_Key_IsDown; + trap->Key_KeynumToStringBuf = trap_Key_KeynumToStringBuf; + trap->Key_SetBinding = trap_Key_SetBinding; + trap->Key_GetCatcher = trap_Key_GetCatcher; + trap->Key_GetOverstrikeMode = trap_Key_GetOverstrikeMode; + trap->Key_SetCatcher = trap_Key_SetCatcher; + trap->Key_SetOverstrikeMode = trap_Key_SetOverstrikeMode; + + trap->PC_AddGlobalDefine = trap_PC_AddGlobalDefine; + trap->PC_FreeSource = trap_PC_FreeSource; + trap->PC_LoadGlobalDefines = trap_PC_LoadGlobalDefines; + trap->PC_LoadSource = trap_PC_LoadSource; + trap->PC_ReadToken = trap_PC_ReadToken; + trap->PC_RemoveAllGlobalDefines = trap_PC_RemoveAllGlobalDefines; + trap->PC_SourceFileAndLine = trap_PC_SourceFileAndLine; + + trap->CIN_DrawCinematic = trap_CIN_DrawCinematic; + trap->CIN_PlayCinematic = trap_CIN_PlayCinematic; + trap->CIN_RunCinematic = trap_CIN_RunCinematic; + trap->CIN_SetExtents = trap_CIN_SetExtents; + trap->CIN_StopCinematic = trap_CIN_StopCinematic; + + trap->LAN_AddServer = trap_LAN_AddServer; + trap->LAN_ClearPing = trap_LAN_ClearPing; + trap->LAN_CompareServers = trap_LAN_CompareServers; + trap->LAN_GetPing = trap_LAN_GetPing; + trap->LAN_GetPingInfo = trap_LAN_GetPingInfo; + trap->LAN_GetPingQueueCount = trap_LAN_GetPingQueueCount; + trap->LAN_GetServerAddressString = trap_LAN_GetServerAddressString; + trap->LAN_GetServerCount = trap_LAN_GetServerCount; + trap->LAN_GetServerInfo = trap_LAN_GetServerInfo; + trap->LAN_GetServerPing = trap_LAN_GetServerPing; + trap->LAN_LoadCachedServers = trap_LAN_LoadCachedServers; + trap->LAN_MarkServerVisible = trap_LAN_MarkServerVisible; + trap->LAN_RemoveServer = trap_LAN_RemoveServer; + trap->LAN_ResetPings = trap_LAN_ResetPings; + trap->LAN_SaveCachedServers = trap_LAN_SaveCachedServers; + trap->LAN_ServerIsVisible = trap_LAN_ServerIsVisible; + trap->LAN_ServerStatus = trap_LAN_ServerStatus; + trap->LAN_UpdateVisiblePings = trap_LAN_UpdateVisiblePings; + + trap->S_StartBackgroundTrack = trap_S_StartBackgroundTrack; + trap->S_StartLocalSound = trap_S_StartLocalSound; + trap->S_StopBackgroundTrack = trap_S_StopBackgroundTrack; + trap->S_RegisterSound = trap_S_RegisterSound; + + trap->SE_GetLanguageName = trap_GetLanguageName; + trap->SE_GetNumLanguages = trap_SP_GetNumLanguages; + trap->SE_GetStringTextString = trap_SP_GetStringTextString; + + trap->R_Language_IsAsian = trap_Language_IsAsian; + trap->R_Language_UsesSpaces = trap_Language_UsesSpaces; + trap->R_AnyLanguage_ReadCharFromString = trap_AnyLanguage_ReadCharFromString; + + trap->R_AddLightToScene = trap_R_AddLightToScene; + trap->R_AddPolysToScene = UISyscall_R_AddPolysToScene; + trap->R_AddRefEntityToScene = trap_R_AddRefEntityToScene; + trap->R_ClearScene = trap_R_ClearScene; + trap->R_DrawStretchPic = trap_R_DrawStretchPic; + trap->R_Font_DrawString = trap_R_Font_DrawString; + trap->R_Font_HeightPixels = trap_R_Font_HeightPixels; + trap->R_Font_StrLenChars = trap_R_Font_StrLenChars; + trap->R_Font_StrLenPixels = trap_R_Font_StrLenPixels; + trap->R_LerpTag = trap_CM_LerpTag; + trap->R_ModelBounds = trap_R_ModelBounds; + trap->R_RegisterFont = trap_R_RegisterFont; + trap->R_RegisterModel = trap_R_RegisterModel; + trap->R_RegisterShaderNoMip = trap_R_RegisterShaderNoMip; + trap->R_RegisterSkin = trap_R_RegisterSkin; + trap->R_RemapShader = trap_R_RemapShader; + trap->R_RenderScene = trap_R_RenderScene; + trap->R_SetColor = trap_R_SetColor; + trap->R_ShaderNameFromIndex = trap_R_ShaderNameFromIndex; + + trap->G2_ListModelSurfaces = trap_G2_ListModelSurfaces; + trap->G2_ListModelBones = trap_G2_ListModelBones; + trap->G2_SetGhoul2ModelIndexes = trap_G2_SetGhoul2ModelIndexes; + trap->G2_HaveWeGhoul2Models = trap_G2_HaveWeGhoul2Models; + trap->G2API_GetBoltMatrix = trap_G2API_GetBoltMatrix; + trap->G2API_GetBoltMatrix_NoReconstruct = trap_G2API_GetBoltMatrix_NoReconstruct; + trap->G2API_GetBoltMatrix_NoRecNoRot = trap_G2API_GetBoltMatrix_NoRecNoRot; + trap->G2API_InitGhoul2Model = trap_G2API_InitGhoul2Model; + trap->G2API_SetSkin = trap_G2API_SetSkin; + trap->G2API_CollisionDetect = UISyscall_G2API_CollisionDetect; + trap->G2API_CollisionDetectCache = UISyscall_G2API_CollisionDetect; + trap->G2API_CleanGhoul2Models = trap_G2API_CleanGhoul2Models; + trap->G2API_SetBoneAngles = trap_G2API_SetBoneAngles; + trap->G2API_SetBoneAnim = trap_G2API_SetBoneAnim; + trap->G2API_GetBoneAnim = trap_G2API_GetBoneAnim; + trap->G2API_GetBoneFrame = trap_G2API_GetBoneFrame; + trap->G2API_GetGLAName = trap_G2API_GetGLAName; + trap->G2API_CopyGhoul2Instance = trap_G2API_CopyGhoul2Instance; + trap->G2API_CopySpecificGhoul2Model = trap_G2API_CopySpecificGhoul2Model; + trap->G2API_DuplicateGhoul2Instance = trap_G2API_DuplicateGhoul2Instance; + trap->G2API_HasGhoul2ModelOnIndex = trap_G2API_HasGhoul2ModelOnIndex; + trap->G2API_RemoveGhoul2Model = trap_G2API_RemoveGhoul2Model; + trap->G2API_AddBolt = trap_G2API_AddBolt; + trap->G2API_SetBoltInfo = trap_G2API_SetBoltInfo; + trap->G2API_SetRootSurface = trap_G2API_SetRootSurface; + trap->G2API_SetSurfaceOnOff = trap_G2API_SetSurfaceOnOff; + trap->G2API_SetNewOrigin = trap_G2API_SetNewOrigin; + trap->G2API_GetTime = trap_G2API_GetTime; + trap->G2API_SetTime = trap_G2API_SetTime; + trap->G2API_SetRagDoll = trap_G2API_SetRagDoll; + trap->G2API_AnimateG2Models = trap_G2API_AnimateG2Models; + trap->G2API_SetBoneIKState = trap_G2API_SetBoneIKState; + trap->G2API_IKMove = trap_G2API_IKMove; + trap->G2API_GetSurfaceName = trap_G2API_GetSurfaceName; + trap->G2API_AttachG2Model = trap_G2API_AttachG2Model; + + trap->ext.R_Font_StrLenPixels = trap_R_Font_StrLenPixelsFloat; + trap->ext.AddCommand = UISyscall_AddCommand; + trap->ext.RemoveCommand = UISyscall_RemoveCommand; } diff --git a/scripts/format-code.sh b/scripts/format-code.sh new file mode 100755 index 0000000000..2a950cf5ab --- /dev/null +++ b/scripts/format-code.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -o errexit -o nounset -o pipefail + +cd "$(dirname "$0")/.." + +command -v "clang-format" >/dev/null || { + echo >&2 "âš ï¸ unable to locate clang-format" + exit 2 +} + +dirs=( + code + codeJK2 + codemp + shared +) +find "${dirs[@]}" -type f \( -iname "*.[ch]pp" -o -iname "*.c" \) -exec clang-format -i {} ';' diff --git a/shared/qcommon/q_color.c b/shared/qcommon/q_color.c index ac849b55db..6071279fd4 100644 --- a/shared/qcommon/q_color.c +++ b/shared/qcommon/q_color.c @@ -1,153 +1,152 @@ #include "q_color.h" -vec4_t colorBlack = {0, 0, 0, 1}; -vec4_t colorRed = {1, 0, 0, 1}; -vec4_t colorGreen = {0, 1, 0, 1}; -vec4_t colorBlue = {0, 0, 1, 1}; -vec4_t colorYellow = {1, 1, 0, 1}; -vec4_t colorOrange = {1, 0.5, 0, 1}; -vec4_t colorMagenta= {1, 0, 1, 1}; -vec4_t colorCyan = {0, 1, 1, 1}; -vec4_t colorWhite = {1, 1, 1, 1}; -vec4_t colorLtGrey = {0.75, 0.75, 0.75, 1}; -vec4_t colorMdGrey = {0.5, 0.5, 0.5, 1}; -vec4_t colorDkGrey = {0.25, 0.25, 0.25, 1}; - -vec4_t colorLtBlue = {0.367f, 0.261f, 0.722f, 1}; -vec4_t colorDkBlue = {0.199f, 0.0f, 0.398f, 1}; - -vec4_t g_color_table[Q_COLOR_BITS+1] = { - { 0.0, 0.0, 0.0, 1.0 }, // black - { 1.0, 0.0, 0.0, 1.0 }, // red - { 0.0, 1.0, 0.0, 1.0 }, // green - { 1.0, 1.0, 0.0, 1.0 }, // yellow - { 0.0, 0.0, 1.0, 1.0 }, // blue - { 0.0, 1.0, 1.0, 1.0 }, // cyan - { 1.0, 0.0, 1.0, 1.0 }, // magenta - { 1.0, 1.0, 1.0, 1.0 }, // white - { 1.0, 0.5, 0.0, 1.0 }, // orange - { 0.5, 0.5, 0.5, 1.0 }, // md.grey +vec4_t colorBlack = {0, 0, 0, 1}; +vec4_t colorRed = {1, 0, 0, 1}; +vec4_t colorGreen = {0, 1, 0, 1}; +vec4_t colorBlue = {0, 0, 1, 1}; +vec4_t colorYellow = {1, 1, 0, 1}; +vec4_t colorOrange = {1, 0.5, 0, 1}; +vec4_t colorMagenta = {1, 0, 1, 1}; +vec4_t colorCyan = {0, 1, 1, 1}; +vec4_t colorWhite = {1, 1, 1, 1}; +vec4_t colorLtGrey = {0.75, 0.75, 0.75, 1}; +vec4_t colorMdGrey = {0.5, 0.5, 0.5, 1}; +vec4_t colorDkGrey = {0.25, 0.25, 0.25, 1}; + +vec4_t colorLtBlue = {0.367f, 0.261f, 0.722f, 1}; +vec4_t colorDkBlue = {0.199f, 0.0f, 0.398f, 1}; + +vec4_t g_color_table[Q_COLOR_BITS + 1] = { + {0.0, 0.0, 0.0, 1.0}, // black + {1.0, 0.0, 0.0, 1.0}, // red + {0.0, 1.0, 0.0, 1.0}, // green + {1.0, 1.0, 0.0, 1.0}, // yellow + {0.0, 0.0, 1.0, 1.0}, // blue + {0.0, 1.0, 1.0, 1.0}, // cyan + {1.0, 0.0, 1.0, 1.0}, // magenta + {1.0, 1.0, 1.0, 1.0}, // white + {1.0, 0.5, 0.0, 1.0}, // orange + {0.5, 0.5, 0.5, 1.0}, // md.grey }; -vec4_t colorTable[CT_MAX] = -{ - {0, 0, 0, 0}, // CT_NONE - {0, 0, 0, 1}, // CT_BLACK - {1, 0, 0, 1}, // CT_RED - {0, 1, 0, 1}, // CT_GREEN - {0, 0, 1, 1}, // CT_BLUE - {1, 1, 0, 1}, // CT_YELLOW - {1, 0, 1, 1}, // CT_MAGENTA - {0, 1, 1, 1}, // CT_CYAN - {1, 1, 1, 1}, // CT_WHITE - {0.75f, 0.75f, 0.75f, 1}, // CT_LTGREY - {0.50f, 0.50f, 0.50f, 1}, // CT_MDGREY - {0.25f, 0.25f, 0.25f, 1}, // CT_DKGREY - {0.15f, 0.15f, 0.15f, 1}, // CT_DKGREY2 - - {0.992f, 0.652f, 0.0f, 1}, // CT_VLTORANGE -- needs values - {0.810f, 0.530f, 0.0f, 1}, // CT_LTORANGE - {0.610f, 0.330f, 0.0f, 1}, // CT_DKORANGE - {0.402f, 0.265f, 0.0f, 1}, // CT_VDKORANGE - - {0.503f, 0.375f, 0.996f, 1}, // CT_VLTBLUE1 - {0.367f, 0.261f, 0.722f, 1}, // CT_LTBLUE1 - {0.199f, 0.0f, 0.398f, 1}, // CT_DKBLUE1 - {0.160f, 0.117f, 0.324f, 1}, // CT_VDKBLUE1 - - {0.300f, 0.628f, 0.816f, 1}, // CT_VLTBLUE2 -- needs values - {0.300f, 0.628f, 0.816f, 1}, // CT_LTBLUE2 - {0.191f, 0.289f, 0.457f, 1}, // CT_DKBLUE2 - {0.125f, 0.250f, 0.324f, 1}, // CT_VDKBLUE2 - - {0.796f, 0.398f, 0.199f, 1}, // CT_VLTBROWN1 -- needs values - {0.796f, 0.398f, 0.199f, 1}, // CT_LTBROWN1 - {0.558f, 0.207f, 0.027f, 1}, // CT_DKBROWN1 - {0.328f, 0.125f, 0.035f, 1}, // CT_VDKBROWN1 - - {0.996f, 0.796f, 0.398f, 1}, // CT_VLTGOLD1 -- needs values - {0.996f, 0.796f, 0.398f, 1}, // CT_LTGOLD1 - {0.605f, 0.441f, 0.113f, 1}, // CT_DKGOLD1 - {0.386f, 0.308f, 0.148f, 1}, // CT_VDKGOLD1 - - {0.648f, 0.562f, 0.784f, 1}, // CT_VLTPURPLE1 -- needs values - {0.648f, 0.562f, 0.784f, 1}, // CT_LTPURPLE1 - {0.437f, 0.335f, 0.597f, 1}, // CT_DKPURPLE1 - {0.308f, 0.269f, 0.375f, 1}, // CT_VDKPURPLE1 - - {0.816f, 0.531f, 0.710f, 1}, // CT_VLTPURPLE2 -- needs values - {0.816f, 0.531f, 0.710f, 1}, // CT_LTPURPLE2 - {0.566f, 0.269f, 0.457f, 1}, // CT_DKPURPLE2 - {0.343f, 0.226f, 0.316f, 1}, // CT_VDKPURPLE2 - - {0.929f, 0.597f, 0.929f, 1}, // CT_VLTPURPLE3 - {0.570f, 0.371f, 0.570f, 1}, // CT_LTPURPLE3 - {0.355f, 0.199f, 0.355f, 1}, // CT_DKPURPLE3 - {0.285f, 0.136f, 0.230f, 1}, // CT_VDKPURPLE3 - - {0.953f, 0.378f, 0.250f, 1}, // CT_VLTRED1 - {0.953f, 0.378f, 0.250f, 1}, // CT_LTRED1 - {0.593f, 0.121f, 0.109f, 1}, // CT_DKRED1 - {0.429f, 0.171f, 0.113f, 1}, // CT_VDKRED1 - {.25f, 0, 0, 1}, // CT_VDKRED - {.70f, 0, 0, 1}, // CT_DKRED - - {0.717f, 0.902f, 1.0f, 1}, // CT_VLTAQUA - {0.574f, 0.722f, 0.804f, 1}, // CT_LTAQUA - {0.287f, 0.361f, 0.402f, 1}, // CT_DKAQUA - {0.143f, 0.180f, 0.201f, 1}, // CT_VDKAQUA - - {0.871f, 0.386f, 0.375f, 1}, // CT_LTPINK - {0.435f, 0.193f, 0.187f, 1}, // CT_DKPINK - { 0, .5f, .5f, 1}, // CT_LTCYAN - { 0, .25f, .25f, 1}, // CT_DKCYAN - { .179f, .51f, .92f, 1}, // CT_LTBLUE3 - { .199f, .71f, .92f, 1}, // CT_LTBLUE3 - { .5f, .05f, .4f, 1}, // CT_DKBLUE3 - - { 0.0f, .613f, .097f, 1}, // CT_HUD_GREEN - { 0.835f, .015f, .015f, 1}, // CT_HUD_RED - { .567f, .685f, 1.0f, .75f}, // CT_ICON_BLUE - { .515f, .406f, .507f, 1}, // CT_NO_AMMO_RED - - { 1.0f, .658f, .062f, 1}, // CT_HUD_ORANGE - { 0.549f, .854f, 1.0f, 1.0f}, // CT_TITLE +vec4_t colorTable[CT_MAX] = { + {0, 0, 0, 0}, // CT_NONE + {0, 0, 0, 1}, // CT_BLACK + {1, 0, 0, 1}, // CT_RED + {0, 1, 0, 1}, // CT_GREEN + {0, 0, 1, 1}, // CT_BLUE + {1, 1, 0, 1}, // CT_YELLOW + {1, 0, 1, 1}, // CT_MAGENTA + {0, 1, 1, 1}, // CT_CYAN + {1, 1, 1, 1}, // CT_WHITE + {0.75f, 0.75f, 0.75f, 1}, // CT_LTGREY + {0.50f, 0.50f, 0.50f, 1}, // CT_MDGREY + {0.25f, 0.25f, 0.25f, 1}, // CT_DKGREY + {0.15f, 0.15f, 0.15f, 1}, // CT_DKGREY2 + + {0.992f, 0.652f, 0.0f, 1}, // CT_VLTORANGE -- needs values + {0.810f, 0.530f, 0.0f, 1}, // CT_LTORANGE + {0.610f, 0.330f, 0.0f, 1}, // CT_DKORANGE + {0.402f, 0.265f, 0.0f, 1}, // CT_VDKORANGE + + {0.503f, 0.375f, 0.996f, 1}, // CT_VLTBLUE1 + {0.367f, 0.261f, 0.722f, 1}, // CT_LTBLUE1 + {0.199f, 0.0f, 0.398f, 1}, // CT_DKBLUE1 + {0.160f, 0.117f, 0.324f, 1}, // CT_VDKBLUE1 + + {0.300f, 0.628f, 0.816f, 1}, // CT_VLTBLUE2 -- needs values + {0.300f, 0.628f, 0.816f, 1}, // CT_LTBLUE2 + {0.191f, 0.289f, 0.457f, 1}, // CT_DKBLUE2 + {0.125f, 0.250f, 0.324f, 1}, // CT_VDKBLUE2 + + {0.796f, 0.398f, 0.199f, 1}, // CT_VLTBROWN1 -- needs values + {0.796f, 0.398f, 0.199f, 1}, // CT_LTBROWN1 + {0.558f, 0.207f, 0.027f, 1}, // CT_DKBROWN1 + {0.328f, 0.125f, 0.035f, 1}, // CT_VDKBROWN1 + + {0.996f, 0.796f, 0.398f, 1}, // CT_VLTGOLD1 -- needs values + {0.996f, 0.796f, 0.398f, 1}, // CT_LTGOLD1 + {0.605f, 0.441f, 0.113f, 1}, // CT_DKGOLD1 + {0.386f, 0.308f, 0.148f, 1}, // CT_VDKGOLD1 + + {0.648f, 0.562f, 0.784f, 1}, // CT_VLTPURPLE1 -- needs values + {0.648f, 0.562f, 0.784f, 1}, // CT_LTPURPLE1 + {0.437f, 0.335f, 0.597f, 1}, // CT_DKPURPLE1 + {0.308f, 0.269f, 0.375f, 1}, // CT_VDKPURPLE1 + + {0.816f, 0.531f, 0.710f, 1}, // CT_VLTPURPLE2 -- needs values + {0.816f, 0.531f, 0.710f, 1}, // CT_LTPURPLE2 + {0.566f, 0.269f, 0.457f, 1}, // CT_DKPURPLE2 + {0.343f, 0.226f, 0.316f, 1}, // CT_VDKPURPLE2 + + {0.929f, 0.597f, 0.929f, 1}, // CT_VLTPURPLE3 + {0.570f, 0.371f, 0.570f, 1}, // CT_LTPURPLE3 + {0.355f, 0.199f, 0.355f, 1}, // CT_DKPURPLE3 + {0.285f, 0.136f, 0.230f, 1}, // CT_VDKPURPLE3 + + {0.953f, 0.378f, 0.250f, 1}, // CT_VLTRED1 + {0.953f, 0.378f, 0.250f, 1}, // CT_LTRED1 + {0.593f, 0.121f, 0.109f, 1}, // CT_DKRED1 + {0.429f, 0.171f, 0.113f, 1}, // CT_VDKRED1 + {.25f, 0, 0, 1}, // CT_VDKRED + {.70f, 0, 0, 1}, // CT_DKRED + + {0.717f, 0.902f, 1.0f, 1}, // CT_VLTAQUA + {0.574f, 0.722f, 0.804f, 1}, // CT_LTAQUA + {0.287f, 0.361f, 0.402f, 1}, // CT_DKAQUA + {0.143f, 0.180f, 0.201f, 1}, // CT_VDKAQUA + + {0.871f, 0.386f, 0.375f, 1}, // CT_LTPINK + {0.435f, 0.193f, 0.187f, 1}, // CT_DKPINK + {0, .5f, .5f, 1}, // CT_LTCYAN + {0, .25f, .25f, 1}, // CT_DKCYAN + {.179f, .51f, .92f, 1}, // CT_LTBLUE3 + {.199f, .71f, .92f, 1}, // CT_LTBLUE3 + {.5f, .05f, .4f, 1}, // CT_DKBLUE3 + + {0.0f, .613f, .097f, 1}, // CT_HUD_GREEN + {0.835f, .015f, .015f, 1}, // CT_HUD_RED + {.567f, .685f, 1.0f, .75f}, // CT_ICON_BLUE + {.515f, .406f, .507f, 1}, // CT_NO_AMMO_RED + + {1.0f, .658f, .062f, 1}, // CT_HUD_ORANGE + {0.549f, .854f, 1.0f, 1.0f}, // CT_TITLE }; -unsigned ColorBytes3 (float r, float g, float b) { +unsigned ColorBytes3(float r, float g, float b) { unsigned i; - ( (byte *)&i )[0] = (byte)(r * 255); - ( (byte *)&i )[1] = (byte)(g * 255); - ( (byte *)&i )[2] = (byte)(b * 255); + ((byte *)&i)[0] = (byte)(r * 255); + ((byte *)&i)[1] = (byte)(g * 255); + ((byte *)&i)[2] = (byte)(b * 255); return i; } -unsigned ColorBytes4 (float r, float g, float b, float a) { +unsigned ColorBytes4(float r, float g, float b, float a) { unsigned i; - ( (byte *)&i )[0] = (byte)(r * 255); - ( (byte *)&i )[1] = (byte)(g * 255); - ( (byte *)&i )[2] = (byte)(b * 255); - ( (byte *)&i )[3] = (byte)(a * 255); + ((byte *)&i)[0] = (byte)(r * 255); + ((byte *)&i)[1] = (byte)(g * 255); + ((byte *)&i)[2] = (byte)(b * 255); + ((byte *)&i)[3] = (byte)(a * 255); return i; } -float NormalizeColor( const vec3_t in, vec3_t out ) { - float max; +float NormalizeColor(const vec3_t in, vec3_t out) { + float max; max = in[0]; - if ( in[1] > max ) { + if (in[1] > max) { max = in[1]; } - if ( in[2] > max ) { + if (in[2] > max) { max = in[2]; } - if ( !max ) { - VectorClear( out ); + if (!max) { + VectorClear(out); } else { out[0] = in[0] / max; out[1] = in[1] / max; diff --git a/shared/qcommon/q_math.c b/shared/qcommon/q_math.c index b15b3dbaf4..09edc5313e 100644 --- a/shared/qcommon/q_math.c +++ b/shared/qcommon/q_math.c @@ -27,115 +27,69 @@ along with this program; if not, see . #include #include - /////////////////////////////////////////////////////////////////////////// // // DIRECTION ENCODING // /////////////////////////////////////////////////////////////////////////// #define NUMVERTEXNORMALS 162 -static const vec3_t bytedirs[NUMVERTEXNORMALS] = -{ - {-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} -}; +static const vec3_t bytedirs[NUMVERTEXNORMALS] = { + {-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}}; // this isn't a real cheap function to call! -int DirToByte( vec3_t dir ) -{ - int i, best; - float d, bestd; +int DirToByte(vec3_t dir) { + int i, best; + float d, bestd; - if ( !dir ) { + if (!dir) { return 0; } bestd = 0; best = 0; - for (i=0 ; i bestd) - { + if (d > bestd) { bestd = d; best = i; } @@ -144,10 +98,9 @@ int DirToByte( vec3_t dir ) return best; } -void ByteToDir( int b, vec3_t dir ) -{ - if ( b < 0 || b >= NUMVERTEXNORMALS ) { - VectorCopy( vec3_origin, dir ); +void ByteToDir(int b, vec3_t dir) { + if (b < 0 || b >= NUMVERTEXNORMALS) { + VectorCopy(vec3_origin, dir); return; } VectorCopy(bytedirs[b], dir); @@ -161,35 +114,28 @@ void ByteToDir( int b, vec3_t dir ) ** Lng = 0 at (0,0,1) to 180 (0,0,-1), encoded in 8-bit sine table format ** */ -//rwwRMG - added -void NormalToLatLong( const vec3_t normal, byte bytes[2] ) -{ +// rwwRMG - added +void NormalToLatLong(const vec3_t normal, byte bytes[2]) { // check for singularities - if (!normal[0] && !normal[1]) - { - if ( normal[2] > 0.0f ) - { + if (!normal[0] && !normal[1]) { + if (normal[2] > 0.0f) { bytes[0] = 0; - bytes[1] = 0; // lat = 0, long = 0 - } - else - { + bytes[1] = 0; // lat = 0, long = 0 + } else { bytes[0] = 128; - bytes[1] = 0; // lat = 0, long = 128 + bytes[1] = 0; // lat = 0, long = 128 } - } - else - { - int a, b; + } else { + int a, b; - a = (int)(RAD2DEG( (float)atan2( normal[1], normal[0] ) ) * (255.0f / 360.0f )); + a = (int)(RAD2DEG((float)atan2(normal[1], normal[0])) * (255.0f / 360.0f)); a &= 0xff; - b = (int)(RAD2DEG( (float)acos( normal[2] ) ) * ( 255.0f / 360.0f )); + b = (int)(RAD2DEG((float)acos(normal[2])) * (255.0f / 360.0f)); b &= 0xff; - bytes[0] = b; // longitude - bytes[1] = a; // lattitude + bytes[0] = b; // longitude + bytes[1] = a; // lattitude } } @@ -198,21 +144,14 @@ void NormalToLatLong( const vec3_t normal, byte bytes[2] ) // RANDOM NUMBER GENERATION // /////////////////////////////////////////////////////////////////////////// -int Q_rand( int *seed ) -{ +int Q_rand(int *seed) { *seed = (69069 * *seed + 1); return *seed; } -float Q_random( int *seed ) -{ - return (Q_rand(seed) & 0xffff) / (float)0x10000; -} +float Q_random(int *seed) { return (Q_rand(seed) & 0xffff) / (float)0x10000; } -float Q_crandom( int *seed ) -{ - return 2.0f * (Q_random(seed) - 0.5f); -} +float Q_crandom(int *seed) { return 2.0f * (Q_random(seed) - 0.5f); } // This is the VC libc version of rand() without multiple seeds per thread or 12 levels // of subroutine calls. @@ -220,34 +159,26 @@ float Q_crandom( int *seed ) // conversions and the additional math required to get the desired value. // eg the typical tint = (rand() * 255) / 32768 // becomes tint = irand(0, 255) -static uint32_t holdrand = 0x89abcdef; +static uint32_t holdrand = 0x89abcdef; -void Rand_Init( int seed ) -{ - holdrand = seed; -} +void Rand_Init(int seed) { holdrand = seed; } // Returns a float min <= x < max (exclusive; will get max - 0.00001; but never max) -float flrand(float min, float max) -{ - float result; +float flrand(float min, float max) { + float result; holdrand = (holdrand * 214013L) + 2531011L; result = (float)(holdrand >> 17); // 0 - 32767 range result = ((result * (max - min)) / (float)QRAND_MAX) + min; - return(result); + return (result); } -float Q_flrand( float min, float max ) -{ - return flrand(min, max); -} +float Q_flrand(float min, float max) { return flrand(min, max); } // Returns an integer min <= x <= max (ie inclusive) -int irand( int min, int max ) -{ - int result; +int irand(int min, int max) { + int result; assert((max - min) < QRAND_MAX); @@ -259,10 +190,7 @@ int irand( int min, int max ) return result; } -int Q_irand( int value1, int value2 ) -{ - return irand(value1, value2); -} +int Q_irand(int value1, int value2) { return irand(value1, value2); } /* erandom @@ -270,113 +198,95 @@ erandom This function produces a random number with a exponential distribution and the specified mean value. */ -float erandom( float mean ) -{ - float r; +float erandom(float mean) { + float r; do { r = Q_flrand(0.0f, 1.0f); - } while ( r == 0.0 ); + } while (r == 0.0); - return -mean * logf( r ); + return -mean * logf(r); } - /////////////////////////////////////////////////////////////////////////// // // MATH UTILITIES // /////////////////////////////////////////////////////////////////////////// -signed char ClampChar( int i ) -{ - if ( i < -128 ) { +signed char ClampChar(int i) { + if (i < -128) { return -128; } - if ( i > 127 ) { + if (i > 127) { return 127; } return i; } -signed short ClampShort( int i ) -{ - if ( i < -32768 ) { +signed short ClampShort(int i) { + if (i < -32768) { return -32768; } - if ( i > 0x7fff ) { + if (i > 0x7fff) { return 0x7fff; } return i; } -int Com_Clampi( int min, int max, int value ) -{ - if ( value < min ) - { +int Com_Clampi(int min, int max, int value) { + if (value < min) { return min; } - if ( value > max ) - { + if (value > max) { return max; } return value; } -float Com_Clamp( float min, float max, float value ) { - if ( value < min ) { +float Com_Clamp(float min, float max, float value) { + if (value < min) { return min; } - if ( value > max ) { + if (value > max) { return max; } return value; } -int Com_AbsClampi( int min, int max, int value ) -{ - if( value < 0 ) - { - return Com_Clampi( -max, -min, value ); - } - else - { - return Com_Clampi( min, max, value ); +int Com_AbsClampi(int min, int max, int value) { + if (value < 0) { + return Com_Clampi(-max, -min, value); + } else { + return Com_Clampi(min, max, value); } } -float Com_AbsClamp( float min, float max, float value ) -{ - if( value < 0.0f ) - { - return Com_Clamp( -max, -min, value ); - } - else - { - return Com_Clamp( min, max, value ); +float Com_AbsClamp(float min, float max, float value) { + if (value < 0.0f) { + return Com_Clamp(-max, -min, value); + } else { + return Com_Clamp(min, max, value); } } - -float Q_rsqrt( float number ) -{ +float Q_rsqrt(float number) { byteAlias_t t; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; - y = number; - t.f = number; - t.i = 0x5f3759df - ( t.i >> 1 ); // what the fuck? - y = t.f; - y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration - // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed - - assert( !Q_isnan(y) ); + y = number; + t.f = number; + t.i = 0x5f3759df - (t.i >> 1); // what the fuck? + y = t.f; + y = y * (threehalfs - (x2 * y * y)); // 1st iteration + // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed + + assert(!Q_isnan(y)); return y; } -float Q_fabs( float f ) -{ +float Q_fabs(float f) { byteAlias_t fi; fi.f = f; fi.i &= 0x7FFFFFFF; @@ -411,8 +321,7 @@ float Q_acos(float c) { return angle; } -float Q_asin(float c) -{ +float Q_asin(float c) { float angle; angle = asinf(c); @@ -426,42 +335,38 @@ float Q_asin(float c) return angle; } -float Q_powf ( float x, int y ) -{ +float Q_powf(float x, int y) { float r = x; - for ( y--; y>0; y-- ) + for (y--; y > 0; y--) r *= x; return r; } -qboolean Q_isnan (float f) -{ +qboolean Q_isnan(float f) { #ifdef _MSC_VER - return (qboolean)(_isnan (f) != 0); + return (qboolean)(_isnan(f) != 0); #else - return (qboolean)(isnan (f) != 0); + return (qboolean)(isnan(f) != 0); #endif } -int Q_log2( int val ) -{ +int Q_log2(int val) { int answer; answer = 0; - while ( ( val>>=1 ) != 0 ) { + while ((val >>= 1) != 0) { answer++; } return answer; } -float LerpAngle(float from, float to, float frac) -{ - float a; +float LerpAngle(float from, float to, float frac) { + float a; - if ( to - from > 180 ) { + if (to - from > 180) { to -= 360; } - if ( to - from < -180 ) { + if (to - from < -180) { to += 360; } a = from + frac * (to - from); @@ -476,28 +381,28 @@ AngleSubtract Always returns a value from -180 to 180 ================= */ -float AngleSubtract( float a1, float a2 ) { - float a; +float AngleSubtract(float a1, float a2) { + float a; a = a1 - a2; - a=fmodf(a,360);//chop it down quickly, then level it out - while ( a > 180 ) { + a = fmodf(a, 360); // chop it down quickly, then level it out + while (a > 180) { a -= 360; } - while ( a < -180 ) { + while (a < -180) { a += 360; } return a; } -void AnglesSubtract( vec3_t v1, vec3_t v2, vec3_t v3 ) { - v3[0] = AngleSubtract( v1[0], v2[0] ); - v3[1] = AngleSubtract( v1[1], v2[1] ); - v3[2] = AngleSubtract( v1[2], v2[2] ); +void AnglesSubtract(vec3_t v1, vec3_t v2, vec3_t v3) { + v3[0] = AngleSubtract(v1[0], v2[0]); + v3[1] = AngleSubtract(v1[1], v2[1]); + v3[2] = AngleSubtract(v1[2], v2[2]); } float AngleMod(float a) { - a = (360.0f/65536) * ((int)(a*(65536/360.0f)) & 65535); + a = (360.0f / 65536) * ((int)(a * (65536 / 360.0f)) & 65535); return a; } @@ -508,9 +413,7 @@ AngleNormalize360 returns angle normalized to the range [0 <= angle < 360] ================= */ -float AngleNormalize360 ( float angle ) { - return (360.0f / 65536) * ((int)(angle * (65536 / 360.0f)) & 65535); -} +float AngleNormalize360(float angle) { return (360.0f / 65536) * ((int)(angle * (65536 / 360.0f)) & 65535); } /* ================= @@ -519,9 +422,9 @@ AngleNormalize180 returns angle normalized to the range [-180 < angle <= 180] ================= */ -float AngleNormalize180 ( float angle ) { - angle = AngleNormalize360( angle ); - if ( angle > 180.0 ) { +float AngleNormalize180(float angle) { + angle = AngleNormalize360(angle); + if (angle > 180.0) { angle -= 360.0; } return angle; @@ -534,10 +437,7 @@ AngleDelta returns the normalized delta from angle1 to angle2 ================= */ -float AngleDelta ( float angle1, float angle2 ) { - return AngleNormalize180( angle1 - angle2 ); -} - +float AngleDelta(float angle1, float angle2) { return AngleNormalize180(angle1 - angle2); } /////////////////////////////////////////////////////////////////////////// // @@ -552,17 +452,17 @@ Returns false if the triangle is degenrate. The normal will point out of the clock for clockwise ordered points ===================== */ -qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ) { - vec3_t d1, d2; +qboolean PlaneFromPoints(vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c) { + vec3_t d1, d2; - VectorSubtract( b, a, d1 ); - VectorSubtract( c, a, d2 ); - CrossProduct( d2, d1, plane ); - if ( VectorNormalize( plane ) == 0 ) { + VectorSubtract(b, a, d1); + VectorSubtract(c, a, d2); + CrossProduct(d2, d1, plane); + if (VectorNormalize(plane) == 0) { return qfalse; } - plane[3] = DotProduct( a, plane ); + plane[3] = DotProduct(a, plane); return qtrue; } @@ -573,76 +473,72 @@ RotatePointAroundVector From q3mme =============== */ -void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees ) { - float m[3][3]; - float c, s, t; +void RotatePointAroundVector(vec3_t dst, const vec3_t dir, const vec3_t point, float degrees) { + float m[3][3]; + float c, s, t; - degrees = -DEG2RAD( degrees ); - s = sinf( degrees ); - c = cosf( degrees ); + degrees = -DEG2RAD(degrees); + s = sinf(degrees); + c = cosf(degrees); t = 1 - c; - m[0][0] = t*dir[0]*dir[0] + c; - m[0][1] = t*dir[0]*dir[1] + s*dir[2]; - m[0][2] = t*dir[0]*dir[2] - s*dir[1]; + m[0][0] = t * dir[0] * dir[0] + c; + m[0][1] = t * dir[0] * dir[1] + s * dir[2]; + m[0][2] = t * dir[0] * dir[2] - s * dir[1]; - m[1][0] = t*dir[0]*dir[1] - s*dir[2]; - m[1][1] = t*dir[1]*dir[1] + c; - m[1][2] = t*dir[1]*dir[2] + s*dir[0]; + m[1][0] = t * dir[0] * dir[1] - s * dir[2]; + m[1][1] = t * dir[1] * dir[1] + c; + m[1][2] = t * dir[1] * dir[2] + s * dir[0]; - m[2][0] = t*dir[0]*dir[2] + s*dir[1]; - m[2][1] = t*dir[1]*dir[2] - s*dir[0]; - m[2][2] = t*dir[2]*dir[2] + c; - VectorRotate( point, m, dst ); + m[2][0] = t * dir[0] * dir[2] + s * dir[1]; + m[2][1] = t * dir[1] * dir[2] - s * dir[0]; + m[2][2] = t * dir[2] * dir[2] + c; + VectorRotate(point, m, dst); } -void RotateAroundDirection( matrix3_t axis, float yaw ) { +void RotateAroundDirection(matrix3_t axis, float yaw) { // create an arbitrary axis[1] - PerpendicularVector( axis[1], axis[0] ); + PerpendicularVector(axis[1], axis[0]); // rotate it around axis[0] by yaw - if ( yaw ) { - vec3_t temp; + if (yaw) { + vec3_t temp; - VectorCopy( axis[1], temp ); - RotatePointAroundVector( axis[1], axis[0], temp, yaw ); + VectorCopy(axis[1], temp); + RotatePointAroundVector(axis[1], axis[0], temp, yaw); } // cross to get axis[2] - CrossProduct( axis[0], axis[1], axis[2] ); + CrossProduct(axis[0], axis[1], axis[2]); } -void vectoangles( const vec3_t value1, vec3_t angles ) { - float forward; - float yaw, pitch; +void vectoangles(const vec3_t value1, vec3_t angles) { + float forward; + float yaw, pitch; - if ( value1[1] == 0 && value1[0] == 0 ) { + if (value1[1] == 0 && value1[0] == 0) { yaw = 0; - if ( value1[2] > 0 ) { + if (value1[2] > 0) { pitch = 90; - } - else { + } else { pitch = 270; } - } - else { - if ( value1[0] ) { - yaw = ( atan2f ( value1[1], value1[0] ) * 180 / M_PI ); - } - else if ( value1[1] > 0 ) { + } else { + if (value1[0]) { + yaw = (atan2f(value1[1], value1[0]) * 180 / M_PI); + } else if (value1[1] > 0) { yaw = 90; - } - else { + } else { yaw = 270; } - if ( yaw < 0 ) { + if (yaw < 0) { yaw += 360; } - forward = sqrtf ( value1[0]*value1[0] + value1[1]*value1[1] ); - pitch = ( atan2f(value1[2], forward) * 180 / M_PI ); - if ( pitch < 0 ) { + forward = sqrtf(value1[0] * value1[0] + value1[1] * value1[1]); + pitch = (atan2f(value1[2], forward) * 180 / M_PI); + if (pitch < 0) { pitch += 360; } } @@ -652,33 +548,32 @@ void vectoangles( const vec3_t value1, vec3_t angles ) { angles[ROLL] = 0; } -vec_t GetYawForDirection( const vec3_t p1, const vec3_t p2 ) { +vec_t GetYawForDirection(const vec3_t p1, const vec3_t p2) { vec3_t v, angles; - VectorSubtract( p2, p1, v ); - vectoangles( v, angles ); + VectorSubtract(p2, p1, v); + vectoangles(v, angles); return angles[YAW]; } -void GetAnglesForDirection( const vec3_t p1, const vec3_t p2, vec3_t out ) { +void GetAnglesForDirection(const vec3_t p1, const vec3_t p2, vec3_t out) { vec3_t v; - VectorSubtract( p2, p1, v ); - vectoangles( v, out ); + VectorSubtract(p2, p1, v); + vectoangles(v, out); } -void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) -{ +void ProjectPointOnPlane(vec3_t dst, const vec3_t p, const vec3_t normal) { float d; vec3_t n; float inv_denom; - inv_denom = DotProduct( normal, normal ); - assert( Q_fabs(inv_denom) != 0.0f ); + inv_denom = DotProduct(normal, normal); + assert(Q_fabs(inv_denom) != 0.0f); inv_denom = 1.0f / inv_denom; - d = DotProduct( normal, p ) * inv_denom; + d = DotProduct(normal, p) * inv_denom; n[0] = normal[0] * inv_denom; n[1] = normal[1] * inv_denom; @@ -689,59 +584,48 @@ void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) dst[2] = p[2] - d * n[2]; } -qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ) -{ - vec3_t vecStart2From, vecStart2End, vecEnd2Start, vecEnd2From; - float distEnd2From, distEnd2Result, theta, cos_theta, dot; +qboolean G_FindClosestPointOnLineSegment(const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result) { + vec3_t vecStart2From, vecStart2End, vecEnd2Start, vecEnd2From; + float distEnd2From, distEnd2Result, theta, cos_theta, dot; - //Find the perpendicular vector to vec from start to end - VectorSubtract( from, start, vecStart2From); - VectorSubtract( end, start, vecStart2End); + // Find the perpendicular vector to vec from start to end + VectorSubtract(from, start, vecStart2From); + VectorSubtract(end, start, vecStart2End); - dot = DotProductNormalize( vecStart2From, vecStart2End ); + dot = DotProductNormalize(vecStart2From, vecStart2End); - if ( dot <= 0 ) - { - //The perpendicular would be beyond or through the start point - VectorCopy( start, result ); + if (dot <= 0) { + // The perpendicular would be beyond or through the start point + VectorCopy(start, result); return qfalse; } - if ( dot == 1 ) - { - //parallel, closer of 2 points will be the target - if( (VectorLengthSquared( vecStart2From )) < (VectorLengthSquared( vecStart2End )) ) - { - VectorCopy( from, result ); - } - else - { - VectorCopy( end, result ); + if (dot == 1) { + // parallel, closer of 2 points will be the target + if ((VectorLengthSquared(vecStart2From)) < (VectorLengthSquared(vecStart2End))) { + VectorCopy(from, result); + } else { + VectorCopy(end, result); } return qfalse; } - //Try other end - VectorSubtract( from, end, vecEnd2From); - VectorSubtract( start, end, vecEnd2Start); + // Try other end + VectorSubtract(from, end, vecEnd2From); + VectorSubtract(start, end, vecEnd2Start); - dot = DotProductNormalize( vecEnd2From, vecEnd2Start ); + dot = DotProductNormalize(vecEnd2From, vecEnd2Start); - if ( dot <= 0 ) - {//The perpendicular would be beyond or through the start point - VectorCopy( end, result ); + if (dot <= 0) { // The perpendicular would be beyond or through the start point + VectorCopy(end, result); return qfalse; } - if ( dot == 1 ) - {//parallel, closer of 2 points will be the target - if( (VectorLengthSquared( vecEnd2From )) < (VectorLengthSquared( vecEnd2Start ))) - { - VectorCopy( from, result ); - } - else - { - VectorCopy( end, result ); + if (dot == 1) { // parallel, closer of 2 points will be the target + if ((VectorLengthSquared(vecEnd2From)) < (VectorLengthSquared(vecEnd2Start))) { + VectorCopy(from, result); + } else { + VectorCopy(end, result); } return qfalse; } @@ -751,66 +635,61 @@ qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, // / |a // theta /)__| // b - //cos(theta) = b / c - //solve for b - //b = cos(theta) * c + // cos(theta) = b / c + // solve for b + // b = cos(theta) * c - //angle between vecs end2from and end2start, should be between 0 and 90 - theta = 90 * (1 - dot);//theta + // angle between vecs end2from and end2start, should be between 0 and 90 + theta = 90 * (1 - dot); // theta - //Get length of side from End2Result using sine of theta - distEnd2From = VectorLength( vecEnd2From );//c - cos_theta = cosf(DEG2RAD(theta));//cos(theta) - distEnd2Result = cos_theta * distEnd2From;//b + // Get length of side from End2Result using sine of theta + distEnd2From = VectorLength(vecEnd2From); // c + cos_theta = cosf(DEG2RAD(theta)); // cos(theta) + distEnd2Result = cos_theta * distEnd2From; // b - //Extrapolate to find result - VectorNormalize( vecEnd2Start ); - VectorMA( end, distEnd2Result, vecEnd2Start, result ); + // Extrapolate to find result + VectorNormalize(vecEnd2Start); + VectorMA(end, distEnd2Result, vecEnd2Start, result); - //perpendicular intersection is between the 2 endpoints + // perpendicular intersection is between the 2 endpoints return qtrue; } -float G_PointDistFromLineSegment( const vec3_t start, const vec3_t end, const vec3_t from ) -{ - vec3_t vecStart2From, vecStart2End, vecEnd2Start, vecEnd2From, intersection; - float distEnd2From, distStart2From, distEnd2Result, theta, cos_theta, dot; +float G_PointDistFromLineSegment(const vec3_t start, const vec3_t end, const vec3_t from) { + vec3_t vecStart2From, vecStart2End, vecEnd2Start, vecEnd2From, intersection; + float distEnd2From, distStart2From, distEnd2Result, theta, cos_theta, dot; - //Find the perpendicular vector to vec from start to end - VectorSubtract( from, start, vecStart2From); - VectorSubtract( end, start, vecStart2End); - VectorSubtract( from, end, vecEnd2From); - VectorSubtract( start, end, vecEnd2Start); + // Find the perpendicular vector to vec from start to end + VectorSubtract(from, start, vecStart2From); + VectorSubtract(end, start, vecStart2End); + VectorSubtract(from, end, vecEnd2From); + VectorSubtract(start, end, vecEnd2Start); - dot = DotProductNormalize( vecStart2From, vecStart2End ); + dot = DotProductNormalize(vecStart2From, vecStart2End); - distStart2From = Distance( start, from ); - distEnd2From = Distance( end, from ); + distStart2From = Distance(start, from); + distEnd2From = Distance(end, from); - if ( dot <= 0 ) - { - //The perpendicular would be beyond or through the start point + if (dot <= 0) { + // The perpendicular would be beyond or through the start point return distStart2From; } - if ( dot == 1 ) - { - //parallel, closer of 2 points will be the target - return ((distStart2From b ? a : b; } - return VectorLength (corner); + return VectorLength(corner); } -void ClearBounds( vec3_t mins, vec3_t maxs ) { +void ClearBounds(vec3_t mins, vec3_t maxs) { mins[0] = mins[1] = mins[2] = 100000; maxs[0] = maxs[1] = maxs[2] = -100000; } -void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs ) { - if ( v[0] < mins[0] ) { +void AddPointToBounds(const vec3_t v, vec3_t mins, vec3_t maxs) { + if (v[0] < mins[0]) { mins[0] = v[0]; } - if ( v[0] > maxs[0]) { + if (v[0] > maxs[0]) { maxs[0] = v[0]; } - if ( v[1] < mins[1] ) { + if (v[1] < mins[1]) { mins[1] = v[1]; } - if ( v[1] > maxs[1]) { + if (v[1] > maxs[1]) { maxs[1] = v[1]; } - if ( v[2] < mins[2] ) { + if (v[2] < mins[2]) { mins[2] = v[2]; } - if ( v[2] > maxs[2]) { + if (v[2] > maxs[2]) { maxs[2] = v[2]; } } - /////////////////////////////////////////////////////////////////////////// // // PLANE // /////////////////////////////////////////////////////////////////////////// -void SetPlaneSignbits( cplane_t *out ) -{ - int bits, j; +void SetPlaneSignbits(cplane_t *out) { + int bits, j; // for fast box on planeside test bits = 0; - for (j=0 ; j<3 ; j++) { + for (j = 0; j < 3; j++) { if (out->normal[j] < 0) { - bits |= 1<signbits = bits; } -int PlaneTypeForNormal( vec3_t normal ) -{ - if ( normal[0] == 1.0 ) +int PlaneTypeForNormal(vec3_t normal) { + if (normal[0] == 1.0) return PLANE_X; - if ( normal[1] == 1.0 ) + if (normal[1] == 1.0) return PLANE_Y; - if ( normal[2] == 1.0 ) + if (normal[2] == 1.0) return PLANE_Z; return PLANE_NON_AXIAL; @@ -945,14 +811,12 @@ BoxOnPlaneSide Returns 1, 2, or 1 + 2 ================== */ -int BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, cplane_t *p) -{ - float dist[2]; - int sides, b, i; +int BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, cplane_t *p) { + float dist[2]; + int sides, b, i; // fast axial cases - if (p->type < 3) - { + if (p->type < 3) { if (p->dist <= emins[p->type]) return 1; if (p->dist >= emaxs[p->type]) @@ -964,11 +828,10 @@ int BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, cplane_t *p) dist[0] = dist[1] = 0; if (p->signbits < 8) // >= 8: default case is original code (dist[0]=dist[1]=0) { - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { b = (p->signbits >> i) & 1; - dist[ b] += p->normal[i]*emaxs[i]; - dist[!b] += p->normal[i]*emins[i]; + dist[b] += p->normal[i] * emaxs[i]; + dist[!b] += p->normal[i] * emins[i]; } } @@ -981,15 +844,14 @@ int BoxOnPlaneSide(vec3_t emins, vec3_t emaxs, cplane_t *p) return sides; } - /////////////////////////////////////////////////////////////////////////// // // AXIS // /////////////////////////////////////////////////////////////////////////// -matrix3_t axisDefault = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; +matrix3_t axisDefault = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; -void AxisClear( matrix3_t axis ) { +void AxisClear(matrix3_t axis) { axis[0][0] = 1; axis[0][1] = 0; axis[0][2] = 0; @@ -1001,169 +863,142 @@ void AxisClear( matrix3_t axis ) { axis[2][2] = 1; } -void AxisCopy( matrix3_t in, matrix3_t out ) { - VectorCopy( in[0], out[0] ); - VectorCopy( in[1], out[1] ); - VectorCopy( in[2], out[2] ); +void AxisCopy(matrix3_t in, matrix3_t out) { + VectorCopy(in[0], out[0]); + VectorCopy(in[1], out[1]); + VectorCopy(in[2], out[2]); } -void AnglesToAxis( const vec3_t angles, matrix3_t axis ) { +void AnglesToAxis(const vec3_t angles, matrix3_t axis) { vec3_t right; // angle vectors returns "right" instead of "y axis" - AngleVectors( angles, axis[0], right, axis[2] ); - VectorSubtract( vec3_origin, right, axis[1] ); + AngleVectors(angles, axis[0], right, axis[2]); + VectorSubtract(vec3_origin, right, axis[1]); } - /////////////////////////////////////////////////////////////////////////// // // VEC2 // /////////////////////////////////////////////////////////////////////////// -vec2_t vec2_zero = {0,0}; +vec2_t vec2_zero = {0, 0}; -void VectorAdd2( const vec2_t vec1, const vec2_t vec2, vec2_t vecOut ) -{ - vecOut[0] = vec1[0]+vec2[0]; - vecOut[1] = vec1[1]+vec2[1]; +void VectorAdd2(const vec2_t vec1, const vec2_t vec2, vec2_t vecOut) { + vecOut[0] = vec1[0] + vec2[0]; + vecOut[1] = vec1[1] + vec2[1]; } -void VectorSubtract2( const vec2_t vec1, const vec2_t vec2, vec2_t vecOut ) -{ - vecOut[0] = vec1[0]-vec2[0]; - vecOut[1] = vec1[1]-vec2[1]; +void VectorSubtract2(const vec2_t vec1, const vec2_t vec2, vec2_t vecOut) { + vecOut[0] = vec1[0] - vec2[0]; + vecOut[1] = vec1[1] - vec2[1]; } -void VectorScale2( const vec2_t vecIn, float scale, vec2_t vecOut ) -{ - vecOut[0] = vecIn[0]*scale; - vecOut[1] = vecIn[1]*scale; +void VectorScale2(const vec2_t vecIn, float scale, vec2_t vecOut) { + vecOut[0] = vecIn[0] * scale; + vecOut[1] = vecIn[1] * scale; } -void VectorMA2( const vec2_t vec1, float scale, const vec2_t vec2, vec2_t vecOut ) -{ - vecOut[0] = vec1[0] + scale*vec2[0]; - vecOut[1] = vec1[1] + scale*vec2[1]; +void VectorMA2(const vec2_t vec1, float scale, const vec2_t vec2, vec2_t vecOut) { + vecOut[0] = vec1[0] + scale * vec2[0]; + vecOut[1] = vec1[1] + scale * vec2[1]; } -void VectorSet2( vec2_t vec, float x, float y ) -{ - vec[0]=x; vec[1]=y; +void VectorSet2(vec2_t vec, float x, float y) { + vec[0] = x; + vec[1] = y; } -void VectorClear2( vec2_t vec ) -{ - vec[0] = vec[1] = 0.0f; -} +void VectorClear2(vec2_t vec) { vec[0] = vec[1] = 0.0f; } -void VectorCopy2( const vec2_t vecIn, vec2_t vecOut ) -{ +void VectorCopy2(const vec2_t vecIn, vec2_t vecOut) { vecOut[0] = vecIn[0]; vecOut[1] = vecIn[1]; } - /////////////////////////////////////////////////////////////////////////// // // VEC3 // /////////////////////////////////////////////////////////////////////////// -vec3_t vec3_origin = {0,0,0}; +vec3_t vec3_origin = {0, 0, 0}; -void VectorAdd( const vec3_t vec1, const vec3_t vec2, vec3_t vecOut ) -{ - vecOut[0] = vec1[0]+vec2[0]; - vecOut[1] = vec1[1]+vec2[1]; - vecOut[2] = vec1[2]+vec2[2]; +void VectorAdd(const vec3_t vec1, const vec3_t vec2, vec3_t vecOut) { + vecOut[0] = vec1[0] + vec2[0]; + vecOut[1] = vec1[1] + vec2[1]; + vecOut[2] = vec1[2] + vec2[2]; } -void VectorSubtract( const vec3_t vec1, const vec3_t vec2, vec3_t vecOut ) -{ - vecOut[0] = vec1[0]-vec2[0]; - vecOut[1] = vec1[1]-vec2[1]; - vecOut[2] = vec1[2]-vec2[2]; +void VectorSubtract(const vec3_t vec1, const vec3_t vec2, vec3_t vecOut) { + vecOut[0] = vec1[0] - vec2[0]; + vecOut[1] = vec1[1] - vec2[1]; + vecOut[2] = vec1[2] - vec2[2]; } -void VectorScale( const vec3_t vecIn, float scale, vec3_t vecOut ) -{ - vecOut[0] = vecIn[0]*scale; - vecOut[1] = vecIn[1]*scale; - vecOut[2] = vecIn[2]*scale; +void VectorScale(const vec3_t vecIn, float scale, vec3_t vecOut) { + vecOut[0] = vecIn[0] * scale; + vecOut[1] = vecIn[1] * scale; + vecOut[2] = vecIn[2] * scale; } -void VectorMA( const vec3_t vec1, float scale, const vec3_t vec2, vec3_t vecOut ) -{ - vecOut[0] = vec1[0] + scale*vec2[0]; - vecOut[1] = vec1[1] + scale*vec2[1]; - vecOut[2] = vec1[2] + scale*vec2[2]; +void VectorMA(const vec3_t vec1, float scale, const vec3_t vec2, vec3_t vecOut) { + vecOut[0] = vec1[0] + scale * vec2[0]; + vecOut[1] = vec1[1] + scale * vec2[1]; + vecOut[2] = vec1[2] + scale * vec2[2]; } -void VectorSet( vec3_t vec, float x, float y, float z ) -{ - vec[0]=x; vec[1]=y; vec[2]=z; +void VectorSet(vec3_t vec, float x, float y, float z) { + vec[0] = x; + vec[1] = y; + vec[2] = z; } -void VectorClear( vec3_t vec ) -{ - vec[0] = vec[1] = vec[2] = 0.0f; -} +void VectorClear(vec3_t vec) { vec[0] = vec[1] = vec[2] = 0.0f; } -void VectorCopy( const vec3_t vecIn, vec3_t vecOut ) -{ +void VectorCopy(const vec3_t vecIn, vec3_t vecOut) { vecOut[0] = vecIn[0]; vecOut[1] = vecIn[1]; vecOut[2] = vecIn[2]; } -float VectorLength( const vec3_t vec ) -{ - return (float)sqrt( vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2] ); -} +float VectorLength(const vec3_t vec) { return (float)sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); } -float VectorLengthSquared( const vec3_t vec ) -{ - return (vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]); -} +float VectorLengthSquared(const vec3_t vec) { return (vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); } -float Distance( const vec3_t p1, const vec3_t p2 ) -{ - vec3_t v; +float Distance(const vec3_t p1, const vec3_t p2) { + vec3_t v; - VectorSubtract( p2, p1, v ); - return VectorLength( v ); + VectorSubtract(p2, p1, v); + return VectorLength(v); } -float DistanceSquared( const vec3_t p1, const vec3_t p2 ) -{ - vec3_t v; +float DistanceSquared(const vec3_t p1, const vec3_t p2) { + vec3_t v; - VectorSubtract( p2, p1, v ); - return v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; + VectorSubtract(p2, p1, v); + return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; } // fast vector normalize routine that does not check to make sure // that length != 0, nor does it return length, uses rsqrt approximation -void VectorNormalizeFast( vec3_t vec ) -{ +void VectorNormalizeFast(vec3_t vec) { float ilength; - ilength = Q_rsqrt( DotProduct( vec, vec ) ); + ilength = Q_rsqrt(DotProduct(vec, vec)); vec[0] *= ilength; vec[1] *= ilength; vec[2] *= ilength; } -float VectorNormalize( vec3_t vec ) -{ - float length, ilength; +float VectorNormalize(vec3_t vec) { + float length, ilength; - length = vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]; - length = sqrtf( length ); + length = vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]; + length = sqrtf(length); - if ( length ) { - ilength = 1/length; + if (length) { + ilength = 1 / length; vec[0] *= ilength; vec[1] *= ilength; vec[2] *= ilength; @@ -1172,92 +1007,80 @@ float VectorNormalize( vec3_t vec ) return length; } -float VectorNormalize2( const vec3_t vec, vec3_t vecOut ) -{ - float length, ilength; +float VectorNormalize2(const vec3_t vec, vec3_t vecOut) { + float length, ilength; - length = vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]; - length = sqrtf( length ); + length = vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]; + length = sqrtf(length); - if ( length ) { - ilength = 1/length; - vecOut[0] = vec[0]*ilength; - vecOut[1] = vec[1]*ilength; - vecOut[2] = vec[2]*ilength; - } - else - VectorClear( vecOut ); + if (length) { + ilength = 1 / length; + vecOut[0] = vec[0] * ilength; + vecOut[1] = vec[1] * ilength; + vecOut[2] = vec[2] * ilength; + } else + VectorClear(vecOut); return length; } -void VectorAdvance( const vec3_t veca, const float scale, const vec3_t vecb, vec3_t vecc) -{ +void VectorAdvance(const vec3_t veca, const float scale, const vec3_t vecb, vec3_t vecc) { vecc[0] = veca[0] + (scale * (vecb[0] - veca[0])); vecc[1] = veca[1] + (scale * (vecb[1] - veca[1])); vecc[2] = veca[2] + (scale * (vecb[2] - veca[2])); } -void VectorInc( vec3_t vec ) { - vec[0] += 1.0f; vec[1] += 1.0f; vec[2] += 1.0f; +void VectorInc(vec3_t vec) { + vec[0] += 1.0f; + vec[1] += 1.0f; + vec[2] += 1.0f; } -void VectorDec( vec3_t vec ) { - vec[0] -= 1.0f; vec[1] -= 1.0f; vec[2] -= 1.0f; +void VectorDec(vec3_t vec) { + vec[0] -= 1.0f; + vec[1] -= 1.0f; + vec[2] -= 1.0f; } -void VectorInverse( vec3_t vec ) { - vec[0] = -vec[0]; vec[1] = -vec[1]; vec[2] = -vec[2]; +void VectorInverse(vec3_t vec) { + vec[0] = -vec[0]; + vec[1] = -vec[1]; + vec[2] = -vec[2]; } -void CrossProduct( const vec3_t vec1, const vec3_t vec2, vec3_t vecOut ) { - vecOut[0] = vec1[1]*vec2[2] - vec1[2]*vec2[1]; - vecOut[1] = vec1[2]*vec2[0] - vec1[0]*vec2[2]; - vecOut[2] = vec1[0]*vec2[1] - vec1[1]*vec2[0]; +void CrossProduct(const vec3_t vec1, const vec3_t vec2, vec3_t vecOut) { + vecOut[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1]; + vecOut[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2]; + vecOut[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0]; } -float DotProduct( const vec3_t vec1, const vec3_t vec2 ) { - return vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2]; -} +float DotProduct(const vec3_t vec1, const vec3_t vec2) { return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2]; } -qboolean VectorCompare( const vec3_t vec1, const vec3_t vec2 ) -{ - return (qboolean)(vec1[0] == vec2[0] && vec1[1] == vec2[1] && vec1[2] == vec2[2]); -} +qboolean VectorCompare(const vec3_t vec1, const vec3_t vec2) { return (qboolean)(vec1[0] == vec2[0] && vec1[1] == vec2[1] && vec1[2] == vec2[2]); } -qboolean VectorCompare2( const vec3_t v1, const vec3_t v2 ) -{ - if ( v1[0] > (v2[0] + 0.0001f) || v1[0] < (v2[0] - 0.0001f) || - v1[1] > (v2[1] + 0.0001f) || v1[1] < (v2[1] + 0.0001f) || - v1[2] > (v2[2] + 0.0001f) || v1[2] < (v2[2] + 0.0001f) ) - { +qboolean VectorCompare2(const vec3_t v1, const vec3_t v2) { + if (v1[0] > (v2[0] + 0.0001f) || v1[0] < (v2[0] - 0.0001f) || v1[1] > (v2[1] + 0.0001f) || v1[1] < (v2[1] + 0.0001f) || v1[2] > (v2[2] + 0.0001f) || + v1[2] < (v2[2] + 0.0001f)) { return qfalse; } return qtrue; } -void SnapVector( float *v ) -{ +void SnapVector(float *v) { #if defined(_MSC_VER) && !defined(idx64) // pitiful attempt to reduce _ftol2 calls -rww static int i; static float f; f = *v; - __asm fld f - __asm fistp i - *v = (float)i; + __asm fld f __asm fistp i *v = (float)i; v++; f = *v; - __asm fld f - __asm fistp i - *v = (float)i; + __asm fld f __asm fistp i *v = (float)i; v++; f = *v; - __asm fld f - __asm fistp i - *v = (float)i; + __asm fld f __asm fistp i *v = (float)i; #else // mac, linux, mingw v[0] = (int)v[0]; v[1] = (int)v[1]; @@ -1265,20 +1088,18 @@ void SnapVector( float *v ) #endif } -float DistanceHorizontal( const vec3_t p1, const vec3_t p2 ) -{ - vec3_t v; +float DistanceHorizontal(const vec3_t p1, const vec3_t p2) { + vec3_t v; - VectorSubtract( p2, p1, v ); - return sqrtf( v[0]*v[0] + v[1]*v[1] ); //Leave off the z component + VectorSubtract(p2, p1, v); + return sqrtf(v[0] * v[0] + v[1] * v[1]); // Leave off the z component } -float DistanceHorizontalSquared( const vec3_t p1, const vec3_t p2 ) -{ - vec3_t v; +float DistanceHorizontalSquared(const vec3_t p1, const vec3_t p2) { + vec3_t v; - VectorSubtract( p2, p1, v ); - return v[0]*v[0] + v[1]*v[1]; //Leave off the z component + VectorSubtract(p2, p1, v); + return v[0] * v[0] + v[1] * v[1]; // Leave off the z component } /* @@ -1289,8 +1110,8 @@ Given a normalized forward vector, create two other perpendicular vectors ================ */ -void MakeNormalVectors( const vec3_t forward, vec3_t right, vec3_t up) { - float d; +void MakeNormalVectors(const vec3_t forward, vec3_t right, vec3_t up) { + float d; // this rotate and negate guarantees a vector // not colinear with the original @@ -1300,58 +1121,53 @@ void MakeNormalVectors( const vec3_t forward, vec3_t right, vec3_t up) { d = DotProduct(right, forward); VectorMA(right, -d, forward, right); - VectorNormalize (right); - CrossProduct (right, forward, up); + VectorNormalize(right); + CrossProduct(right, forward, up); } -void VectorRotate( const vec3_t in, matrix3_t matrix, vec3_t out ) -{ - out[0] = DotProduct( in, matrix[0] ); - out[1] = DotProduct( in, matrix[1] ); - out[2] = DotProduct( in, matrix[2] ); +void VectorRotate(const vec3_t in, matrix3_t matrix, vec3_t out) { + out[0] = DotProduct(in, matrix[0]); + out[1] = DotProduct(in, matrix[1]); + out[2] = DotProduct(in, matrix[2]); } -void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { - float angle; - static float sr, sp, sy, cr, cp, cy; +void AngleVectors(const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { + float angle; + static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs - angle = angles[YAW] * (M_PI*2 / 360); + angle = angles[YAW] * (M_PI * 2 / 360); sy = sinf(angle); cy = cosf(angle); - angle = angles[PITCH] * (M_PI*2 / 360); + angle = angles[PITCH] * (M_PI * 2 / 360); sp = sinf(angle); cp = cosf(angle); - angle = angles[ROLL] * (M_PI*2 / 360); + angle = angles[ROLL] * (M_PI * 2 / 360); sr = sinf(angle); cr = cosf(angle); - if (forward) - { - forward[0] = cp*cy; - forward[1] = cp*sy; + if (forward) { + forward[0] = cp * cy; + forward[1] = cp * sy; forward[2] = -sp; } - if (right) - { - right[0] = (-1*sr*sp*cy+-1*cr*-sy); - right[1] = (-1*sr*sp*sy+-1*cr*cy); - right[2] = -1*sr*cp; + if (right) { + right[0] = (-1 * sr * sp * cy + -1 * cr * -sy); + right[1] = (-1 * sr * sp * sy + -1 * cr * cy); + right[2] = -1 * sr * cp; } - if (up) - { - up[0] = (cr*sp*cy+-sr*-sy); - up[1] = (cr*sp*sy+-sr*cy); - up[2] = cr*cp; + if (up) { + up[0] = (cr * sp * cy + -sr * -sy); + up[1] = (cr * sp * sy + -sr * cy); + up[2] = cr * cp; } } /* ** assumes "src" is normalized */ -void PerpendicularVector( vec3_t dst, const vec3_t src ) -{ - int pos; +void PerpendicularVector(vec3_t dst, const vec3_t src) { + int pos; int i; float minelem = 1.0F; vec3_t tempvec; @@ -1359,12 +1175,10 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) /* ** find the smallest magnitude axially aligned vector */ - for ( pos = 0, i = 0; i < 3; i++ ) - { - if ( fabs( src[i] ) < minelem ) - { + for (pos = 0, i = 0; i < 3; i++) { + if (fabs(src[i]) < minelem) { pos = i; - minelem = fabsf( src[i] ); + minelem = fabsf(src[i]); } } tempvec[0] = tempvec[1] = tempvec[2] = 0.0F; @@ -1373,61 +1187,60 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) /* ** project the point onto the plane defined by src */ - ProjectPointOnPlane( dst, tempvec, src ); + ProjectPointOnPlane(dst, tempvec, src); /* ** normalize the result */ - VectorNormalize( dst ); + VectorNormalize(dst); } -float DotProductNormalize( const vec3_t inVec1, const vec3_t inVec2 ) -{ - vec3_t v1, v2; +float DotProductNormalize(const vec3_t inVec1, const vec3_t inVec2) { + vec3_t v1, v2; - VectorNormalize2( inVec1, v1 ); - VectorNormalize2( inVec2, v2 ); + VectorNormalize2(inVec1, v1); + VectorNormalize2(inVec2, v2); return DotProduct(v1, v2); } - /////////////////////////////////////////////////////////////////////////// // // VEC4 // /////////////////////////////////////////////////////////////////////////// -void VectorScale4( const vec4_t vecIn, float scale, vec4_t vecOut ) -{ - vecOut[0] = vecIn[0]*scale; - vecOut[1] = vecIn[1]*scale; - vecOut[2] = vecIn[2]*scale; - vecOut[3] = vecIn[3]*scale; +void VectorScale4(const vec4_t vecIn, float scale, vec4_t vecOut) { + vecOut[0] = vecIn[0] * scale; + vecOut[1] = vecIn[1] * scale; + vecOut[2] = vecIn[2] * scale; + vecOut[3] = vecIn[3] * scale; } -void VectorCopy4( const vec4_t vecIn, vec4_t vecOut ) -{ +void VectorCopy4(const vec4_t vecIn, vec4_t vecOut) { vecOut[0] = vecIn[0]; vecOut[1] = vecIn[1]; vecOut[2] = vecIn[2]; vecOut[3] = vecIn[3]; } -void VectorSet4( vec4_t vec, float x, float y, float z, float w ) -{ - vec[0]=x; vec[1]=y; vec[2]=z; vec[3]=w; +void VectorSet4(vec4_t vec, float x, float y, float z, float w) { + vec[0] = x; + vec[1] = y; + vec[2] = z; + vec[3] = w; } -void VectorClear4( vec4_t vec ) -{ - vec[0] = vec[1] = vec[2] = vec[3] = 0; -} +void VectorClear4(vec4_t vec) { vec[0] = vec[1] = vec[2] = vec[3] = 0; } /////////////////////////////////////////////////////////////////////////// // // VEC5 // /////////////////////////////////////////////////////////////////////////// -void VectorSet5( vec5_t vec, float x, float y, float z, float w, float u ) { - vec[0]=x; vec[1]=y; vec[2]=z; vec[3]=w; vec[4]=u; +void VectorSet5(vec5_t vec, float x, float y, float z, float w, float u) { + vec[0] = x; + vec[1] = y; + vec[2] = z; + vec[3] = w; + vec[4] = u; } diff --git a/shared/qcommon/q_string.c b/shared/qcommon/q_string.c index 280de852ff..b3c408d9ba 100644 --- a/shared/qcommon/q_string.c +++ b/shared/qcommon/q_string.c @@ -11,83 +11,71 @@ #include "q_color.h" -int Q_isprint( int c ) -{ - if ( c >= 0x20 && c <= 0x7E ) - return ( 1 ); - return ( 0 ); +int Q_isprint(int c) { + if (c >= 0x20 && c <= 0x7E) + return (1); + return (0); } -int Q_isprintext( int c ) -{ - if ( c >= 0x20 && c <= 0x7E ) +int Q_isprintext(int c) { + if (c >= 0x20 && c <= 0x7E) return (1); - if ( c >= 0x80 && c <= 0xFE ) + if (c >= 0x80 && c <= 0xFE) return (1); return (0); } -int Q_isgraph( int c ) -{ - if ( c >= 0x21 && c <= 0x7E ) +int Q_isgraph(int c) { + if (c >= 0x21 && c <= 0x7E) return (1); - if ( c >= 0x80 && c <= 0xFE ) + if (c >= 0x80 && c <= 0xFE) return (1); return (0); } -int Q_islower( int c ) -{ +int Q_islower(int c) { if (c >= 'a' && c <= 'z') - return ( 1 ); - return ( 0 ); + return (1); + return (0); } -int Q_isupper( int c ) -{ +int Q_isupper(int c) { if (c >= 'A' && c <= 'Z') - return ( 1 ); - return ( 0 ); + return (1); + return (0); } -int Q_isalpha( int c ) -{ +int Q_isalpha(int c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) - return ( 1 ); - return ( 0 ); + return (1); + return (0); } -qboolean Q_isanumber( const char *s ) -{ +qboolean Q_isanumber(const char *s) { char *p; double ret; - if( *s == '\0' ) + if (*s == '\0') return qfalse; - ret = strtod( s, &p ); + ret = strtod(s, &p); - if ( ret == HUGE_VAL || errno == ERANGE ) + if (ret == HUGE_VAL || errno == ERANGE) return qfalse; return (qboolean)(*p == '\0'); } -qboolean Q_isintegral( float f ) -{ - return (qboolean)( (int)f == f ); -} +qboolean Q_isintegral(float f) { return (qboolean)((int)f == f); } -char* Q_strrchr( const char* string, int c ) -{ +char *Q_strrchr(const char *string, int c) { char cc = c; char *s; - char *sp=(char *)0; + char *sp = (char *)0; - s = (char*)string; + s = (char *)string; - while (*s) - { + while (*s) { if (*s == cc) sp = s; s++; @@ -105,25 +93,24 @@ Q_strncpyz Safe strncpy that ensures a trailing zero ============= */ -void Q_strncpyz( char *dest, const char *src, int destsize ) { +void Q_strncpyz(char *dest, const char *src, int destsize) { assert(src); assert(dest); assert(destsize); - - strncpy( dest, src, destsize-1 ); - dest[destsize-1] = 0; + + strncpy(dest, src, destsize - 1); + dest[destsize - 1] = 0; } -int Q_stricmpn (const char *s1, const char *s2, int n) { - int c1, c2; +int Q_stricmpn(const char *s1, const char *s2, int n) { + int c1, c2; - if ( s1 == NULL ) { - if ( s2 == NULL ) + if (s1 == NULL) { + if (s2 == NULL) return 0; else return -1; - } - else if ( s2==NULL ) + } else if (s2 == NULL) return 1; do { @@ -131,7 +118,7 @@ int Q_stricmpn (const char *s1, const char *s2, int n) { c2 = *s2++; if (!n--) { - return 0; // strings are equal until end point + return 0; // strings are equal until end point } if (c1 != c2) { @@ -147,22 +134,20 @@ int Q_stricmpn (const char *s1, const char *s2, int n) { } } while (c1); - return 0; // strings are equal + return 0; // strings are equal } -int Q_stricmp (const char *s1, const char *s2) { - return (s1 && s2) ? Q_stricmpn (s1, s2, 99999) : -1; -} +int Q_stricmp(const char *s1, const char *s2) { return (s1 && s2) ? Q_stricmpn(s1, s2, 99999) : -1; } -int Q_strncmp (const char *s1, const char *s2, int n) { - int c1, c2; +int Q_strncmp(const char *s1, const char *s2, int n) { + int c1, c2; do { c1 = *s1++; c2 = *s2++; if (!n--) { - return 0; // strings are equal until end point + return 0; // strings are equal until end point } if (c1 != c2) { @@ -170,25 +155,25 @@ int Q_strncmp (const char *s1, const char *s2, int n) { } } while (c1); - return 0; // strings are equal + return 0; // strings are equal } -char *Q_strlwr( char *s1 ) { - char *s; +char *Q_strlwr(char *s1) { + char *s; s = s1; - while ( *s ) { + while (*s) { *s = tolower(*s); s++; } return s1; } -char *Q_strupr( char *s1 ) { - char *s; +char *Q_strupr(char *s1) { + char *s; s = s1; - while ( *s ) { + while (*s) { *s = toupper(*s); s++; } @@ -196,45 +181,38 @@ char *Q_strupr( char *s1 ) { } // never goes past bounds or leaves without a terminating 0 -void Q_strcat( char *dest, int size, const char *src ) { - int l1; +void Q_strcat(char *dest, int size, const char *src) { + int l1; - l1 = strlen( dest ); - if ( l1 >= size ) { - //Com_Error( ERR_FATAL, "Q_strcat: already overflowed" ); + l1 = strlen(dest); + if (l1 >= size) { + // Com_Error( ERR_FATAL, "Q_strcat: already overflowed" ); return; } - if ( strlen(src)+1 > (size_t)(size - l1)) - { //do the error here instead of in Q_strncpyz to get a meaningful msg - //Com_Error(ERR_FATAL,"Q_strcat: cannot append \"%s\" to \"%s\"", src, dest); + if (strlen(src) + 1 > (size_t)(size - l1)) { // do the error here instead of in Q_strncpyz to get a meaningful msg + // Com_Error(ERR_FATAL,"Q_strcat: cannot append \"%s\" to \"%s\"", src, dest); return; } - Q_strncpyz( dest + l1, src, size - l1 ); + Q_strncpyz(dest + l1, src, size - l1); } /* -* Find the first occurrence of find in s. -*/ -const char *Q_stristr( const char *s, const char *find ) -{ + * Find the first occurrence of find in s. + */ +const char *Q_stristr(const char *s, const char *find) { char c, sc; size_t len; - if ((c = *find++) != 0) - { - if (c >= 'a' && c <= 'z') - { + if ((c = *find++) != 0) { + if (c >= 'a' && c <= 'z') { c -= ('a' - 'A'); } len = strlen(find); - do - { - do - { + do { + do { if ((sc = *s++) == 0) return NULL; - if (sc >= 'a' && sc <= 'z') - { + if (sc >= 'a' && sc <= 'z') { sc -= ('a' - 'A'); } } while (sc != c); @@ -244,18 +222,18 @@ const char *Q_stristr( const char *s, const char *find ) return s; } -int Q_PrintStrlen( const char *string ) { - int len; - const char *p; +int Q_PrintStrlen(const char *string) { + int len; + const char *p; - if( !string ) { + if (!string) { return 0; } len = 0; p = string; - while( *p ) { - if( Q_IsColorString( p ) ) { + while (*p) { + if (Q_IsColorString(p)) { p += 2; continue; } @@ -267,9 +245,9 @@ int Q_PrintStrlen( const char *string ) { } int Q_PrintStrLenTo(const char *str, int chars, char *color) { - int offset = 0; - char lastColor = 0; - int i; + int offset = 0; + char lastColor = 0; + int i; for (i = 0; i < chars && str[i]; i++) { if (Q_IsColorString(&str[i])) { @@ -287,19 +265,17 @@ int Q_PrintStrLenTo(const char *str, int chars, char *color) { return offset; } - -char *Q_CleanStr( char *string ) { - char* d; - char* s; - int c; +char *Q_CleanStr(char *string) { + char *d; + char *s; + int c; s = string; d = string; - while ((c = *s) != 0 ) { - if ( Q_IsColorString( s ) ) { + while ((c = *s) != 0) { + if (Q_IsColorString(s)) { s++; - } - else if ( c >= 0x20 && c <= 0x7E ) { + } else if (c >= 0x20 && c <= 0x7E) { *d++ = c; } s++; @@ -320,36 +296,28 @@ This function modifies INPUT (is mutable) (Also strips ^8 and ^9) ================== */ -void Q_StripColor(char *text) -{ +void Q_StripColor(char *text) { qboolean doPass = qtrue; char *read; char *write; - while ( doPass ) - { + while (doPass) { doPass = qfalse; read = write = text; - while ( *read ) - { - if ( Q_IsColorStringExt(read) ) - { + while (*read) { + if (Q_IsColorStringExt(read)) { doPass = qtrue; read += 2; - } - else - { + } else { // Avoid writing the same data over itself - if (write != read) - { + if (write != read) { *write = *read; } write++; read++; } } - if ( write < read ) - { + if (write < read) { // Add trailing NUL byte if string has shortened *write = '\0'; } @@ -368,29 +336,25 @@ Q_strstrip( "Bo\nb is h\rairy!!", "\n\r!", "12" ); // "Bo1b is h2airy" Q_strstrip( "Bo\nb is h\rairy!!", "\n\r!", NULL ); // "Bob is hairy" */ -void Q_strstrip( char *string, const char *strip, const char *repl ) -{ - char *out=string, *p=string, c; - const char *s=strip; - int replaceLen = repl?strlen( repl ):0, offset=0; - qboolean recordChar = qtrue; +void Q_strstrip(char *string, const char *strip, const char *repl) { + char *out = string, *p = string, c; + const char *s = strip; + int replaceLen = repl ? strlen(repl) : 0, offset = 0; + qboolean recordChar = qtrue; - while ( (c = *p++) != '\0' ) - { + while ((c = *p++) != '\0') { recordChar = qtrue; - for ( s=strip; *s; s++ ) - { - offset = s-strip; - if ( c == *s ) - { - if ( !repl || offset >= replaceLen ) + for (s = strip; *s; s++) { + offset = s - strip; + if (c == *s) { + if (!repl || offset >= replaceLen) recordChar = qfalse; else c = repl[offset]; break; } } - if ( recordChar ) + if (recordChar) *out++ = c; } *out = '\0'; @@ -405,15 +369,12 @@ Return: first instance of any characters found otherwise NULL */ -const char *Q_strchrs( const char *string, const char *search ) -{ +const char *Q_strchrs(const char *string, const char *search) { const char *p = string, *s = search; - while ( *p != '\0' ) - { - for ( s=search; *s; s++ ) - { - if ( *p == *s ) + while (*p != '\0') { + for (s = search; *s; s++) { + if (*p == *s) return p; } p++; @@ -432,14 +393,12 @@ MinGW comes with its own snprintf() which is not broken. ============= */ -int Q_vsnprintf(char *str, size_t size, const char *format, va_list ap) -{ +int Q_vsnprintf(char *str, size_t size, const char *format, va_list ap) { int retval; retval = _vsnprintf(str, size, format, ap); - if(retval < 0 || retval == size) - { + if (retval < 0 || retval == size) { // Microsoft doesn't adhere to the C99 standard of vsnprintf, // which states that the return value must be the number of // bytes written if the output string had sufficient length. diff --git a/shared/qcommon/safe/files.cpp b/shared/qcommon/safe/files.cpp index a753b6ee1e..2883d99187 100644 --- a/shared/qcommon/safe/files.cpp +++ b/shared/qcommon/safe/files.cpp @@ -1,117 +1,89 @@ #include "files.h" -#if defined( SP_GAME ) -# define GAME_INCLUDE // so centity_t is defined in g_shared.h (alternatively include g_public.h?) -# include "game/g_shared.h" // gi +#if defined(SP_GAME) +#define GAME_INCLUDE // so centity_t is defined in g_shared.h (alternatively include g_public.h?) +#include "game/g_shared.h" // gi #else -# include "qcommon/qcommon.h" +#include "qcommon/qcommon.h" #endif -namespace FS -{ - // FileBuffer +namespace FS { +// FileBuffer - static void freeFileBuffer( void* buffer ) - { - if( buffer ) - { -#if defined( SP_GAME ) - gi.FS_FreeFile( buffer ); +static void freeFileBuffer(void *buffer) { + if (buffer) { +#if defined(SP_GAME) + gi.FS_FreeFile(buffer); #else - FS_FreeFile( buffer ); + FS_FreeFile(buffer); #endif - } } +} - FileBuffer::FileBuffer( void* buffer, const long size ) NOEXCEPT - : _buffer( buffer ) - , _size( size ) - { - assert( buffer != nullptr || size == 0 ); - assert( size >= 0 ); - } +FileBuffer::FileBuffer(void *buffer, const long size) NOEXCEPT : _buffer(buffer), _size(size) { + assert(buffer != nullptr || size == 0); + assert(size >= 0); +} - FileBuffer::~FileBuffer() NOEXCEPT - { - freeFileBuffer( _buffer ); - } +FileBuffer::~FileBuffer() NOEXCEPT { freeFileBuffer(_buffer); } - FileBuffer::FileBuffer( FileBuffer&& rhs ) NOEXCEPT - : _buffer( rhs._buffer ) - , _size( rhs._size ) - { - rhs._buffer = nullptr; - rhs._size = 0; - } +FileBuffer::FileBuffer(FileBuffer &&rhs) NOEXCEPT : _buffer(rhs._buffer), _size(rhs._size) { + rhs._buffer = nullptr; + rhs._size = 0; +} - FileBuffer& FileBuffer::operator=( FileBuffer&& rhs ) NOEXCEPT - { - if( _buffer ) - { - freeFileBuffer( _buffer ); - } - _buffer = rhs._buffer; - rhs._buffer = nullptr; - _size = rhs._size; - rhs._size = 0; - return *this; +FileBuffer &FileBuffer::operator=(FileBuffer &&rhs) NOEXCEPT { + if (_buffer) { + freeFileBuffer(_buffer); } + _buffer = rhs._buffer; + rhs._buffer = nullptr; + _size = rhs._size; + rhs._size = 0; + return *this; +} - FileBuffer ReadFile( gsl::czstring path ) - { - void* buffer; -#if defined( SP_GAME ) - const long size = gi.FS_ReadFile( path, &buffer ); +FileBuffer ReadFile(gsl::czstring path) { + void *buffer; +#if defined(SP_GAME) + const long size = gi.FS_ReadFile(path, &buffer); #else - const long size = FS_ReadFile( path, &buffer ); + const long size = FS_ReadFile(path, &buffer); #endif - return size >= 0 ? FileBuffer{ buffer, size } : FileBuffer{}; - } + return size >= 0 ? FileBuffer{buffer, size} : FileBuffer{}; +} -#if !defined( SP_GAME ) - // FileList +#if !defined(SP_GAME) +// FileList - FileList::FileList( char** files, int numFiles ) NOEXCEPT - : _begin( files ) - , _end( files + numFiles ) - { - assert( numFiles >= 0 ); - } +FileList::FileList(char **files, int numFiles) NOEXCEPT : _begin(files), _end(files + numFiles) { assert(numFiles >= 0); } - FileList::~FileList() NOEXCEPT - { - if( _begin ) - { - FS_FreeFileList( _begin ); - } +FileList::~FileList() NOEXCEPT { + if (_begin) { + FS_FreeFileList(_begin); } +} - FileList::FileList( FileList&& rhs ) NOEXCEPT - : _begin( rhs._begin ) - , _end( rhs._end ) - { - rhs._begin = nullptr; - rhs._end = nullptr; - } +FileList::FileList(FileList &&rhs) NOEXCEPT : _begin(rhs._begin), _end(rhs._end) { + rhs._begin = nullptr; + rhs._end = nullptr; +} - FileList& FileList::operator=( FileList&& rhs ) NOEXCEPT - { - if( _begin != nullptr ) - { - FS_FreeFileList( _begin ); - } - _begin = rhs._begin; - rhs._begin = nullptr; - _end = rhs._end; - rhs._end = nullptr; - return *this; +FileList &FileList::operator=(FileList &&rhs) NOEXCEPT { + if (_begin != nullptr) { + FS_FreeFileList(_begin); } + _begin = rhs._begin; + rhs._begin = nullptr; + _end = rhs._end; + rhs._end = nullptr; + return *this; +} - FileList ListFiles( const char * directory, const char * extension ) - { - int numFiles{}; - auto files = FS_ListFiles( directory, extension, &numFiles ); - return FileList{ files, numFiles }; - } -#endif +FileList ListFiles(const char *directory, const char *extension) { + int numFiles{}; + auto files = FS_ListFiles(directory, extension, &numFiles); + return FileList{files, numFiles}; } +#endif +} // namespace FS diff --git a/shared/qcommon/safe/string.cpp b/shared/qcommon/safe/string.cpp index f097b731c5..62261bb359 100644 --- a/shared/qcommon/safe/string.cpp +++ b/shared/qcommon/safe/string.cpp @@ -4,64 +4,53 @@ #include #include -namespace Q -{ - Ordering stricmp( const gsl::cstring_span& lhs, const gsl::cstring_span& rhs ) NOEXCEPT - { - auto lIt = lhs.begin(); - auto rIt = rhs.begin(); - auto lEnd = lhs.end(); - auto rEnd = rhs.end(); - while( lIt != lEnd ) - { - if( rIt == rEnd ) - { - // rhs is prefix of lhs - return Ordering::GT; - } - if( std::tolower( *lIt ) < std::tolower( *rIt ) ) - { - return Ordering::LT; - } - if( std::tolower( *lIt ) > std::tolower( *rIt ) ) - { - return Ordering::GT; - } - ++lIt; - ++rIt; +namespace Q { +Ordering stricmp(const gsl::cstring_span &lhs, const gsl::cstring_span &rhs) NOEXCEPT { + auto lIt = lhs.begin(); + auto rIt = rhs.begin(); + auto lEnd = lhs.end(); + auto rEnd = rhs.end(); + while (lIt != lEnd) { + if (rIt == rEnd) { + // rhs is prefix of lhs + return Ordering::GT; } - if( rIt == rEnd ) - { - // lhs == rhs - return Ordering::EQ; + if (std::tolower(*lIt) < std::tolower(*rIt)) { + return Ordering::LT; } - // lhs is a prefix of rhs - return Ordering::LT; - } - - gsl::cstring_span substr( const gsl::cstring_span& lhs, const std::string::size_type pos, const std::string::size_type count ) - { - if( pos > lhs.size() ) - { - throw std::out_of_range( "Q::substr called with out-of-bounds pos parameter!" ); + if (std::tolower(*lIt) > std::tolower(*rIt)) { + return Ordering::GT; } - auto start = lhs.begin() + pos; - auto end = count == std::string::npos ? lhs.end() : std::min( start + count, lhs.end() ); - gsl::cstring_span result{ start, end }; - return result; + ++lIt; + ++rIt; } - - int svtoi( const gsl::cstring_span& view ) - { - int result = 0; - Q::sscanf( view, result ); - return result; + if (rIt == rEnd) { + // lhs == rhs + return Ordering::EQ; } + // lhs is a prefix of rhs + return Ordering::LT; +} - float svtof( const gsl::cstring_span& view ) - { - float result = 0.f; - Q::sscanf( view, result ); - return result; +gsl::cstring_span substr(const gsl::cstring_span &lhs, const std::string::size_type pos, const std::string::size_type count) { + if (pos > lhs.size()) { + throw std::out_of_range("Q::substr called with out-of-bounds pos parameter!"); } + auto start = lhs.begin() + pos; + auto end = count == std::string::npos ? lhs.end() : std::min(start + count, lhs.end()); + gsl::cstring_span result{start, end}; + return result; +} + +int svtoi(const gsl::cstring_span &view) { + int result = 0; + Q::sscanf(view, result); + return result; +} + +float svtof(const gsl::cstring_span &view) { + float result = 0.f; + Q::sscanf(view, result); + return result; } +} // namespace Q diff --git a/shared/sdl/sdl_input.cpp b/shared/sdl/sdl_input.cpp index 59e940613b..33aba00511 100644 --- a/shared/sdl/sdl_input.cpp +++ b/shared/sdl/sdl_input.cpp @@ -25,55 +25,64 @@ along with this program; if not, see . #include "client/client.h" #include "sys/sys_local.h" -static cvar_t *in_keyboardDebug = NULL; +static cvar_t *in_keyboardDebug = NULL; static SDL_Joystick *stick = NULL; static qboolean mouseAvailable = qfalse; static qboolean mouseActive = qfalse; -static cvar_t *in_mouse = NULL; +static cvar_t *in_mouse = NULL; static cvar_t *in_nograb; -cvar_t *in_joystick = NULL; +cvar_t *in_joystick = NULL; static cvar_t *in_joystickThreshold = NULL; -static cvar_t *in_joystickNo = NULL; +static cvar_t *in_joystickNo = NULL; static cvar_t *in_joystickUseAnalog = NULL; static SDL_Window *SDL_window = NULL; -#define CTRL(a) ((a)-'a'+1) +#define CTRL(a) ((a) - 'a' + 1) /* =============== IN_PrintKey =============== */ -static void IN_PrintKey( const SDL_Keysym *keysym, fakeAscii_t key, qboolean down ) -{ - if( down ) - Com_Printf( "+ " ); +static void IN_PrintKey(const SDL_Keysym *keysym, fakeAscii_t key, qboolean down) { + if (down) + Com_Printf("+ "); else - Com_Printf( " " ); - - Com_Printf( "Scancode: 0x%02x(%s) Sym: 0x%02x(%s)", - keysym->scancode, SDL_GetScancodeName( keysym->scancode ), - keysym->sym, SDL_GetKeyName( keysym->sym ) ); - - if( keysym->mod & KMOD_LSHIFT ) Com_Printf( " KMOD_LSHIFT" ); - if( keysym->mod & KMOD_RSHIFT ) Com_Printf( " KMOD_RSHIFT" ); - if( keysym->mod & KMOD_LCTRL ) Com_Printf( " KMOD_LCTRL" ); - if( keysym->mod & KMOD_RCTRL ) Com_Printf( " KMOD_RCTRL" ); - if( keysym->mod & KMOD_LALT ) Com_Printf( " KMOD_LALT" ); - if( keysym->mod & KMOD_RALT ) Com_Printf( " KMOD_RALT" ); - if( keysym->mod & KMOD_LGUI ) Com_Printf( " KMOD_LGUI" ); - if( keysym->mod & KMOD_RGUI ) Com_Printf( " KMOD_RGUI" ); - if( keysym->mod & KMOD_NUM ) Com_Printf( " KMOD_NUM" ); - if( keysym->mod & KMOD_CAPS ) Com_Printf( " KMOD_CAPS" ); - if( keysym->mod & KMOD_MODE ) Com_Printf( " KMOD_MODE" ); - if( keysym->mod & KMOD_RESERVED ) Com_Printf( " KMOD_RESERVED" ); - - Com_Printf( " Q:0x%02x(%s)\n", key, Key_KeynumToString( key ) ); + Com_Printf(" "); + + Com_Printf("Scancode: 0x%02x(%s) Sym: 0x%02x(%s)", keysym->scancode, SDL_GetScancodeName(keysym->scancode), keysym->sym, SDL_GetKeyName(keysym->sym)); + + if (keysym->mod & KMOD_LSHIFT) + Com_Printf(" KMOD_LSHIFT"); + if (keysym->mod & KMOD_RSHIFT) + Com_Printf(" KMOD_RSHIFT"); + if (keysym->mod & KMOD_LCTRL) + Com_Printf(" KMOD_LCTRL"); + if (keysym->mod & KMOD_RCTRL) + Com_Printf(" KMOD_RCTRL"); + if (keysym->mod & KMOD_LALT) + Com_Printf(" KMOD_LALT"); + if (keysym->mod & KMOD_RALT) + Com_Printf(" KMOD_RALT"); + if (keysym->mod & KMOD_LGUI) + Com_Printf(" KMOD_LGUI"); + if (keysym->mod & KMOD_RGUI) + Com_Printf(" KMOD_RGUI"); + if (keysym->mod & KMOD_NUM) + Com_Printf(" KMOD_NUM"); + if (keysym->mod & KMOD_CAPS) + Com_Printf(" KMOD_CAPS"); + if (keysym->mod & KMOD_MODE) + Com_Printf(" KMOD_MODE"); + if (keysym->mod & KMOD_RESERVED) + Com_Printf(" KMOD_RESERVED"); + + Com_Printf(" Q:0x%02x(%s)\n", key, Key_KeynumToString(key)); } #define MAX_CONSOLE_KEYS 16 @@ -83,65 +92,53 @@ static void IN_PrintKey( const SDL_Keysym *keysym, fakeAscii_t key, qboolean dow IN_IsConsoleKey TODO: If the SDL_Scancode situation improves, use it instead of - both of these methods + both of these methods =============== */ -static qboolean IN_IsConsoleKey( fakeAscii_t key, int character ) -{ - typedef struct consoleKey_s - { - enum - { - QUAKE_KEY, - CHARACTER - } type; - - union - { +static qboolean IN_IsConsoleKey(fakeAscii_t key, int character) { + typedef struct consoleKey_s { + enum { QUAKE_KEY, CHARACTER } type; + + union { fakeAscii_t key; int character; } u; } consoleKey_t; - static consoleKey_t consoleKeys[ MAX_CONSOLE_KEYS ]; + static consoleKey_t consoleKeys[MAX_CONSOLE_KEYS]; static int numConsoleKeys = 0; int i; // Only parse the variable when it changes - if( cl_consoleKeys->modified ) - { + if (cl_consoleKeys->modified) { const char *text_p; - char *token; + char *token; cl_consoleKeys->modified = qfalse; text_p = cl_consoleKeys->string; numConsoleKeys = 0; COM_BeginParseSession("cl_consoleKeys"); - while( numConsoleKeys < MAX_CONSOLE_KEYS ) - { - consoleKey_t *c = &consoleKeys[ numConsoleKeys ]; + while (numConsoleKeys < MAX_CONSOLE_KEYS) { + consoleKey_t *c = &consoleKeys[numConsoleKeys]; int charCode = 0; - token = COM_Parse( &text_p ); - if( !token[ 0 ] ) + token = COM_Parse(&text_p); + if (!token[0]) break; - if( strlen( token ) == 4 ) - charCode = Com_HexStrToInt( token ); + if (strlen(token) == 4) + charCode = Com_HexStrToInt(token); - if( charCode > 0 ) - { + if (charCode > 0) { c->type = consoleKey_t::CHARACTER; c->u.character = charCode; - } - else - { + } else { c->type = consoleKey_t::QUAKE_KEY; - c->u.key = (fakeAscii_t)Key_StringToKeynum( token ); + c->u.key = (fakeAscii_t)Key_StringToKeynum(token); // 0 isn't a key - if( c->u.key <= 0 ) + if (c->u.key <= 0) continue; } @@ -150,24 +147,22 @@ static qboolean IN_IsConsoleKey( fakeAscii_t key, int character ) } // If the character is the same as the key, prefer the character - if( key == character ) + if (key == character) key = A_NULL; - for( i = 0; i < numConsoleKeys; i++ ) - { - consoleKey_t *c = &consoleKeys[ i ]; + for (i = 0; i < numConsoleKeys; i++) { + consoleKey_t *c = &consoleKeys[i]; - switch( c->type ) - { - case consoleKey_t::QUAKE_KEY: - if( key && c->u.key == key ) - return qtrue; - break; + switch (c->type) { + case consoleKey_t::QUAKE_KEY: + if (key && c->u.key == key) + return qtrue; + break; - case consoleKey_t::CHARACTER: - if( c->u.character == character ) - return qtrue; - break; + case consoleKey_t::CHARACTER: + if (c->u.character == character) + return qtrue; + break; } } @@ -179,22 +174,18 @@ static qboolean IN_IsConsoleKey( fakeAscii_t key, int character ) #include #endif -static bool IN_NumLockEnabled( void ) -{ +static bool IN_NumLockEnabled(void) { #if defined(_WIN32) - return (GetKeyState( VK_NUMLOCK ) & 1) != 0; + return (GetKeyState(VK_NUMLOCK) & 1) != 0; #else // @fixme : doesn't give proper state if numlock is on before app startup return (SDL_GetModState() & KMOD_NUM) != 0; #endif } -static void IN_TranslateNumpad( SDL_Keysym *keysym, fakeAscii_t *key ) -{ - if ( IN_NumLockEnabled() ) - { - switch ( keysym->sym ) - { +static void IN_TranslateNumpad(SDL_Keysym *keysym, fakeAscii_t *key) { + if (IN_NumLockEnabled()) { + switch (keysym->sym) { case SDLK_KP_0: keysym->scancode = SDL_SCANCODE_0; keysym->sym = SDLK_0; @@ -256,12 +247,12 @@ static void IN_TranslateNumpad( SDL_Keysym *keysym, fakeAscii_t *key ) IN_ModTogglesConsole =============== */ -static qboolean IN_ModTogglesConsole( int mod ) { +static qboolean IN_ModTogglesConsole(int mod) { switch (cl_consoleShiftRequirement->integer) { case 0: return qtrue; case 2: - return (qboolean)!!(mod & KMOD_SHIFT); + return (qboolean) !!(mod & KMOD_SHIFT); case 1: default: return (qboolean)((mod & KMOD_SHIFT) || (Key_GetCatcher() & KEYCATCH_CONSOLE)); @@ -273,135 +264,292 @@ static qboolean IN_ModTogglesConsole( int mod ) { IN_TranslateSDLToJKKey =============== */ -static fakeAscii_t IN_TranslateSDLToJKKey( SDL_Keysym *keysym, qboolean down ) { +static fakeAscii_t IN_TranslateSDLToJKKey(SDL_Keysym *keysym, qboolean down) { fakeAscii_t key = A_NULL; - if ( keysym->sym >= A_LOW_A && keysym->sym <= A_LOW_Z ) + if (keysym->sym >= A_LOW_A && keysym->sym <= A_LOW_Z) key = (fakeAscii_t)(A_CAP_A + (keysym->sym - A_LOW_A)); - else if ( keysym->sym >= A_LOW_AGRAVE && keysym->sym <= A_LOW_THORN && keysym->sym != A_DIVIDE ) + else if (keysym->sym >= A_LOW_AGRAVE && keysym->sym <= A_LOW_THORN && keysym->sym != A_DIVIDE) key = (fakeAscii_t)(A_CAP_AGRAVE + (keysym->sym - A_LOW_AGRAVE)); - else if ( keysym->sym >= SDLK_SPACE && keysym->sym < SDLK_DELETE ) + else if (keysym->sym >= SDLK_SPACE && keysym->sym < SDLK_DELETE) key = (fakeAscii_t)keysym->sym; - else - { - IN_TranslateNumpad( keysym, &key ); - - switch( keysym->sym ) - { - case SDLK_PAGEUP: key = A_PAGE_UP; break; - case SDLK_KP_9: key = A_KP_9; break; - case SDLK_PAGEDOWN: key = A_PAGE_DOWN; break; - case SDLK_KP_3: key = A_KP_3; break; - case SDLK_KP_7: key = A_KP_7; break; - case SDLK_HOME: key = A_HOME; break; - case SDLK_KP_1: key = A_KP_1; break; - case SDLK_END: key = A_END; break; - case SDLK_KP_4: key = A_KP_4; break; - case SDLK_LEFT: key = A_CURSOR_LEFT; break; - case SDLK_KP_6: key = A_KP_6; break; - case SDLK_RIGHT: key = A_CURSOR_RIGHT; break; - case SDLK_KP_2: key = A_KP_2; break; - case SDLK_DOWN: key = A_CURSOR_DOWN; break; - case SDLK_KP_8: key = A_KP_8; break; - case SDLK_UP: key = A_CURSOR_UP; break; - case SDLK_ESCAPE: key = A_ESCAPE; break; - case SDLK_KP_ENTER: key = A_KP_ENTER; break; - case SDLK_RETURN: key = A_ENTER; break; - case SDLK_TAB: key = A_TAB; break; - case SDLK_F1: key = A_F1; break; - case SDLK_F2: key = A_F2; break; - case SDLK_F3: key = A_F3; break; - case SDLK_F4: key = A_F4; break; - case SDLK_F5: key = A_F5; break; - case SDLK_F6: key = A_F6; break; - case SDLK_F7: key = A_F7; break; - case SDLK_F8: key = A_F8; break; - case SDLK_F9: key = A_F9; break; - case SDLK_F10: key = A_F10; break; - case SDLK_F11: key = A_F11; break; - case SDLK_F12: key = A_F12; break; - - case SDLK_BACKSPACE: key = A_BACKSPACE; break; - case SDLK_KP_PERIOD: key = A_KP_PERIOD; break; - case SDLK_DELETE: key = A_DELETE; break; - case SDLK_PAUSE: key = A_PAUSE; break; - - case SDLK_LSHIFT: - case SDLK_RSHIFT: key = A_SHIFT; break; - - case SDLK_LCTRL: - case SDLK_RCTRL: key = A_CTRL; break; - - case SDLK_RALT: - case SDLK_LALT: key = A_ALT; break; - - case SDLK_KP_5: key = A_KP_5; break; - case SDLK_INSERT: key = A_INSERT; break; - case SDLK_KP_0: key = A_KP_0; break; - case SDLK_KP_MULTIPLY: key = A_STAR; break; - case SDLK_KP_PLUS: key = A_KP_PLUS; break; - case SDLK_KP_MINUS: key = A_KP_MINUS; break; - case SDLK_KP_DIVIDE: key = A_FORWARD_SLASH; break; - - case SDLK_SCROLLLOCK: key = A_SCROLLLOCK; break; - case SDLK_NUMLOCKCLEAR: key = A_NUMLOCK; break; - case SDLK_CAPSLOCK: key = A_CAPSLOCK; break; - - case L'\u00D7': key = A_MULTIPLY; break; - case L'\u00E0': key = A_LOW_AGRAVE; break; - case L'\u00E1': key = A_LOW_AACUTE; break; - case L'\u00E2': key = A_LOW_ACIRCUMFLEX; break; - case L'\u00E3': key = A_LOW_ATILDE; break; - case L'\u00E4': key = A_LOW_ADIERESIS; break; - case L'\u00E5': key = A_LOW_ARING; break; - case L'\u00E6': key = A_LOW_AE; break; - case L'\u00E7': key = A_LOW_CCEDILLA; break; - case L'\u00E8': key = A_LOW_EGRAVE; break; - case L'\u00E9': key = A_LOW_EACUTE; break; - case L'\u00EA': key = A_LOW_ECIRCUMFLEX; break; - case L'\u00EB': key = A_LOW_EDIERESIS; break; - case L'\u00EC': key = A_LOW_IGRAVE; break; - case L'\u00ED': key = A_LOW_IACUTE; break; - case L'\u00EE': key = A_LOW_ICIRCUMFLEX; break; - case L'\u00EF': key = A_LOW_IDIERESIS; break; - case L'\u00F0': key = A_LOW_ETH; break; - case L'\u00F1': key = A_LOW_NTILDE; break; - case L'\u00F2': key = A_LOW_OGRAVE; break; - case L'\u00F3': key = A_LOW_OACUTE; break; - case L'\u00F4': key = A_LOW_OCIRCUMFLEX; break; - case L'\u00F5': key = A_LOW_OTILDE; break; - case L'\u00F6': key = A_LOW_ODIERESIS; break; - case L'\u00F7': key = A_DIVIDE; break; - case L'\u00F8': key = A_LOW_OSLASH; break; - case L'\u00F9': key = A_LOW_UGRAVE; break; - case L'\u00FA': key = A_LOW_UACUTE; break; - case L'\u00FB': key = A_LOW_UCIRCUMFLEX; break; - case L'\u00FC': key = A_LOW_UDIERESIS; break; - case L'\u00FD': key = A_LOW_YACUTE; break; - case L'\u00FE': key = A_LOW_THORN; break; - case L'\u00FF': key = A_LOW_YDIERESIS; break; + else { + IN_TranslateNumpad(keysym, &key); - default: - break; + switch (keysym->sym) { + case SDLK_PAGEUP: + key = A_PAGE_UP; + break; + case SDLK_KP_9: + key = A_KP_9; + break; + case SDLK_PAGEDOWN: + key = A_PAGE_DOWN; + break; + case SDLK_KP_3: + key = A_KP_3; + break; + case SDLK_KP_7: + key = A_KP_7; + break; + case SDLK_HOME: + key = A_HOME; + break; + case SDLK_KP_1: + key = A_KP_1; + break; + case SDLK_END: + key = A_END; + break; + case SDLK_KP_4: + key = A_KP_4; + break; + case SDLK_LEFT: + key = A_CURSOR_LEFT; + break; + case SDLK_KP_6: + key = A_KP_6; + break; + case SDLK_RIGHT: + key = A_CURSOR_RIGHT; + break; + case SDLK_KP_2: + key = A_KP_2; + break; + case SDLK_DOWN: + key = A_CURSOR_DOWN; + break; + case SDLK_KP_8: + key = A_KP_8; + break; + case SDLK_UP: + key = A_CURSOR_UP; + break; + case SDLK_ESCAPE: + key = A_ESCAPE; + break; + case SDLK_KP_ENTER: + key = A_KP_ENTER; + break; + case SDLK_RETURN: + key = A_ENTER; + break; + case SDLK_TAB: + key = A_TAB; + break; + case SDLK_F1: + key = A_F1; + break; + case SDLK_F2: + key = A_F2; + break; + case SDLK_F3: + key = A_F3; + break; + case SDLK_F4: + key = A_F4; + break; + case SDLK_F5: + key = A_F5; + break; + case SDLK_F6: + key = A_F6; + break; + case SDLK_F7: + key = A_F7; + break; + case SDLK_F8: + key = A_F8; + break; + case SDLK_F9: + key = A_F9; + break; + case SDLK_F10: + key = A_F10; + break; + case SDLK_F11: + key = A_F11; + break; + case SDLK_F12: + key = A_F12; + break; + + case SDLK_BACKSPACE: + key = A_BACKSPACE; + break; + case SDLK_KP_PERIOD: + key = A_KP_PERIOD; + break; + case SDLK_DELETE: + key = A_DELETE; + break; + case SDLK_PAUSE: + key = A_PAUSE; + break; + + case SDLK_LSHIFT: + case SDLK_RSHIFT: + key = A_SHIFT; + break; + + case SDLK_LCTRL: + case SDLK_RCTRL: + key = A_CTRL; + break; + + case SDLK_RALT: + case SDLK_LALT: + key = A_ALT; + break; + + case SDLK_KP_5: + key = A_KP_5; + break; + case SDLK_INSERT: + key = A_INSERT; + break; + case SDLK_KP_0: + key = A_KP_0; + break; + case SDLK_KP_MULTIPLY: + key = A_STAR; + break; + case SDLK_KP_PLUS: + key = A_KP_PLUS; + break; + case SDLK_KP_MINUS: + key = A_KP_MINUS; + break; + case SDLK_KP_DIVIDE: + key = A_FORWARD_SLASH; + break; + + case SDLK_SCROLLLOCK: + key = A_SCROLLLOCK; + break; + case SDLK_NUMLOCKCLEAR: + key = A_NUMLOCK; + break; + case SDLK_CAPSLOCK: + key = A_CAPSLOCK; + break; + + case L'\u00D7': + key = A_MULTIPLY; + break; + case L'\u00E0': + key = A_LOW_AGRAVE; + break; + case L'\u00E1': + key = A_LOW_AACUTE; + break; + case L'\u00E2': + key = A_LOW_ACIRCUMFLEX; + break; + case L'\u00E3': + key = A_LOW_ATILDE; + break; + case L'\u00E4': + key = A_LOW_ADIERESIS; + break; + case L'\u00E5': + key = A_LOW_ARING; + break; + case L'\u00E6': + key = A_LOW_AE; + break; + case L'\u00E7': + key = A_LOW_CCEDILLA; + break; + case L'\u00E8': + key = A_LOW_EGRAVE; + break; + case L'\u00E9': + key = A_LOW_EACUTE; + break; + case L'\u00EA': + key = A_LOW_ECIRCUMFLEX; + break; + case L'\u00EB': + key = A_LOW_EDIERESIS; + break; + case L'\u00EC': + key = A_LOW_IGRAVE; + break; + case L'\u00ED': + key = A_LOW_IACUTE; + break; + case L'\u00EE': + key = A_LOW_ICIRCUMFLEX; + break; + case L'\u00EF': + key = A_LOW_IDIERESIS; + break; + case L'\u00F0': + key = A_LOW_ETH; + break; + case L'\u00F1': + key = A_LOW_NTILDE; + break; + case L'\u00F2': + key = A_LOW_OGRAVE; + break; + case L'\u00F3': + key = A_LOW_OACUTE; + break; + case L'\u00F4': + key = A_LOW_OCIRCUMFLEX; + break; + case L'\u00F5': + key = A_LOW_OTILDE; + break; + case L'\u00F6': + key = A_LOW_ODIERESIS; + break; + case L'\u00F7': + key = A_DIVIDE; + break; + case L'\u00F8': + key = A_LOW_OSLASH; + break; + case L'\u00F9': + key = A_LOW_UGRAVE; + break; + case L'\u00FA': + key = A_LOW_UACUTE; + break; + case L'\u00FB': + key = A_LOW_UCIRCUMFLEX; + break; + case L'\u00FC': + key = A_LOW_UDIERESIS; + break; + case L'\u00FD': + key = A_LOW_YACUTE; + break; + case L'\u00FE': + key = A_LOW_THORN; + break; + case L'\u00FF': + key = A_LOW_YDIERESIS; + break; + + default: + break; } } - if( in_keyboardDebug->integer ) - IN_PrintKey( keysym, key, down ); + if (in_keyboardDebug->integer) + IN_PrintKey(keysym, key, down); - if ( cl_consoleUseScanCode->integer ) - { - if ( keysym->scancode == SDL_SCANCODE_GRAVE ) - { - if ( IN_ModTogglesConsole(keysym->mod) ) { + if (cl_consoleUseScanCode->integer) { + if (keysym->scancode == SDL_SCANCODE_GRAVE) { + if (IN_ModTogglesConsole(keysym->mod)) { key = A_CONSOLE; } } - } - else - { - if ( IN_IsConsoleKey( key, 0 ) ) - { + } else { + if (IN_IsConsoleKey(key, 0)) { // Console keys can't be bound or generate characters key = A_CONSOLE; } @@ -415,18 +563,17 @@ static fakeAscii_t IN_TranslateSDLToJKKey( SDL_Keysym *keysym, qboolean down ) { IN_GobbleMotionEvents =============== */ -static void IN_GobbleMotionEvents( void ) -{ - SDL_Event dummy[ 1 ]; +static void IN_GobbleMotionEvents(void) { + SDL_Event dummy[1]; int val = 0; // Gobble any mouse motion events - SDL_PumpEvents( ); - while( ( val = SDL_PeepEvents( dummy, 1, SDL_GETEVENT, - SDL_MOUSEMOTION, SDL_MOUSEMOTION ) ) > 0 ) { } + SDL_PumpEvents(); + while ((val = SDL_PeepEvents(dummy, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION)) > 0) { + } - if ( val < 0 ) - Com_Printf( "IN_GobbleMotionEvents failed: %s\n", SDL_GetError( ) ); + if (val < 0) + Com_Printf("IN_GobbleMotionEvents failed: %s\n", SDL_GetError()); } /* @@ -434,28 +581,24 @@ static void IN_GobbleMotionEvents( void ) IN_ActivateMouse =============== */ -static void IN_ActivateMouse( void ) -{ - if (!mouseAvailable || !SDL_WasInit( SDL_INIT_VIDEO ) ) +static void IN_ActivateMouse(void) { + if (!mouseAvailable || !SDL_WasInit(SDL_INIT_VIDEO)) return; - if( !mouseActive ) - { - SDL_SetRelativeMouseMode( SDL_TRUE ); - SDL_SetWindowGrab( SDL_window, SDL_TRUE ); + if (!mouseActive) { + SDL_SetRelativeMouseMode(SDL_TRUE); + SDL_SetWindowGrab(SDL_window, SDL_TRUE); - IN_GobbleMotionEvents( ); + IN_GobbleMotionEvents(); } // in_nograb makes no sense in fullscreen mode - if( !Cvar_VariableIntegerValue("r_fullscreen") ) - { - if( in_nograb->modified || !mouseActive ) - { - if( in_nograb->integer ) - SDL_SetWindowGrab( SDL_window, SDL_FALSE ); + if (!Cvar_VariableIntegerValue("r_fullscreen")) { + if (in_nograb->modified || !mouseActive) { + if (in_nograb->integer) + SDL_SetWindowGrab(SDL_window, SDL_FALSE); else - SDL_SetWindowGrab( SDL_window, SDL_TRUE ); + SDL_SetWindowGrab(SDL_window, SDL_TRUE); in_nograb->modified = qfalse; } @@ -469,63 +612,43 @@ static void IN_ActivateMouse( void ) IN_DeactivateMouse =============== */ -static void IN_DeactivateMouse( void ) -{ - if( !SDL_WasInit( SDL_INIT_VIDEO ) ) +static void IN_DeactivateMouse(void) { + if (!SDL_WasInit(SDL_INIT_VIDEO)) return; // Always show the cursor when the mouse is disabled, // but not when fullscreen - if( !Cvar_VariableIntegerValue("r_fullscreen") ) - SDL_ShowCursor( 1 ); + if (!Cvar_VariableIntegerValue("r_fullscreen")) + SDL_ShowCursor(1); - if( !mouseAvailable ) + if (!mouseAvailable) return; - if( mouseActive ) - { - IN_GobbleMotionEvents( ); + if (mouseActive) { + IN_GobbleMotionEvents(); - SDL_SetWindowGrab( SDL_window, SDL_FALSE ); - SDL_SetRelativeMouseMode( SDL_FALSE ); + SDL_SetWindowGrab(SDL_window, SDL_FALSE); + SDL_SetRelativeMouseMode(SDL_FALSE); // Don't warp the mouse unless the cursor is within the window - if( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_MOUSE_FOCUS ) - SDL_WarpMouseInWindow( SDL_window, cls.glconfig.vidWidth / 2, cls.glconfig.vidHeight / 2 ); + if (SDL_GetWindowFlags(SDL_window) & SDL_WINDOW_MOUSE_FOCUS) + SDL_WarpMouseInWindow(SDL_window, cls.glconfig.vidWidth / 2, cls.glconfig.vidHeight / 2); mouseActive = qfalse; } } // We translate axes movement into keypresses -static int joy_keys[16] = { - A_CURSOR_LEFT, A_CURSOR_RIGHT, - A_CURSOR_UP, A_CURSOR_DOWN, - A_JOY16, A_JOY17, - A_JOY18, A_JOY19, - A_JOY20, A_JOY21, - A_JOY22, A_JOY23, - A_JOY24, A_JOY25, - A_JOY26, A_JOY27 -}; +static int joy_keys[16] = {A_CURSOR_LEFT, A_CURSOR_RIGHT, A_CURSOR_UP, A_CURSOR_DOWN, A_JOY16, A_JOY17, A_JOY18, A_JOY19, + A_JOY20, A_JOY21, A_JOY22, A_JOY23, A_JOY24, A_JOY25, A_JOY26, A_JOY27}; // translate hat events into keypresses // the 4 highest buttons are used for the first hat ... -static int hat_keys[16] = { - A_JOY28, A_JOY29, - A_JOY30, A_JOY31, - A_JOY24, A_JOY25, - A_JOY26, A_JOY27, - A_JOY20, A_JOY21, - A_JOY22, A_JOY23, - A_JOY16, A_JOY17, - A_JOY18, A_JOY19 -}; - - -struct stick_state_s -{ - qboolean buttons[16]; // !!! FIXME: these might be too many. +static int hat_keys[16] = {A_JOY28, A_JOY29, A_JOY30, A_JOY31, A_JOY24, A_JOY25, A_JOY26, A_JOY27, + A_JOY20, A_JOY21, A_JOY22, A_JOY23, A_JOY16, A_JOY17, A_JOY18, A_JOY19}; + +struct stick_state_s { + qboolean buttons[16]; // !!! FIXME: these might be too many. unsigned int oldaxes; int oldaaxes[MAX_JOYSTICK_AXIS]; unsigned int oldhats; @@ -536,8 +659,7 @@ struct stick_state_s IN_InitJoystick =============== */ -static void IN_InitJoystick( void ) -{ +static void IN_InitJoystick(void) { int i = 0; int total = 0; char buf[16384] = ""; @@ -546,13 +668,11 @@ static void IN_InitJoystick( void ) SDL_JoystickClose(stick); stick = NULL; - memset(&stick_state, '\0', sizeof (stick_state)); + memset(&stick_state, '\0', sizeof(stick_state)); - if (!SDL_WasInit(SDL_INIT_JOYSTICK)) - { + if (!SDL_WasInit(SDL_INIT_JOYSTICK)) { Com_DPrintf("Calling SDL_Init(SDL_INIT_JOYSTICK)...\n"); - if (SDL_Init(SDL_INIT_JOYSTICK) == -1) - { + if (SDL_Init(SDL_INIT_JOYSTICK) == -1) { Com_DPrintf("SDL_Init(SDL_INIT_JOYSTICK) failed: %s\n", SDL_GetError()); return; } @@ -563,244 +683,385 @@ static void IN_InitJoystick( void ) Com_DPrintf("%d possible joysticks\n", total); // Print list and build cvar to allow ui to select joystick. - for (i = 0; i < total; i++) - { + for (i = 0; i < total; i++) { Q_strcat(buf, sizeof(buf), SDL_JoystickNameForIndex(i)); Q_strcat(buf, sizeof(buf), "\n"); } - Cvar_Get( "in_availableJoysticks", buf, CVAR_ROM ); + Cvar_Get("in_availableJoysticks", buf, CVAR_ROM); - if( !in_joystick->integer ) { - Com_DPrintf( "Joystick is not active.\n" ); + if (!in_joystick->integer) { + Com_DPrintf("Joystick is not active.\n"); SDL_QuitSubSystem(SDL_INIT_JOYSTICK); return; } - in_joystickNo = Cvar_Get( "in_joystickNo", "0", CVAR_ARCHIVE_ND ); - if( in_joystickNo->integer < 0 || in_joystickNo->integer >= total ) - Cvar_Set( "in_joystickNo", "0" ); + in_joystickNo = Cvar_Get("in_joystickNo", "0", CVAR_ARCHIVE_ND); + if (in_joystickNo->integer < 0 || in_joystickNo->integer >= total) + Cvar_Set("in_joystickNo", "0"); - in_joystickUseAnalog = Cvar_Get( "in_joystickUseAnalog", "0", CVAR_ARCHIVE_ND ); + in_joystickUseAnalog = Cvar_Get("in_joystickUseAnalog", "0", CVAR_ARCHIVE_ND); - in_joystickThreshold = Cvar_Get( "joy_threshold", "0.15", CVAR_ARCHIVE_ND ); + in_joystickThreshold = Cvar_Get("joy_threshold", "0.15", CVAR_ARCHIVE_ND); - stick = SDL_JoystickOpen( in_joystickNo->integer ); + stick = SDL_JoystickOpen(in_joystickNo->integer); if (stick == NULL) { - Com_DPrintf( "No joystick opened.\n" ); + Com_DPrintf("No joystick opened.\n"); return; } - Com_DPrintf( "Joystick %d opened\n", in_joystickNo->integer ); - Com_DPrintf( "Name: %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer) ); - Com_DPrintf( "Axes: %d\n", SDL_JoystickNumAxes(stick) ); - Com_DPrintf( "Hats: %d\n", SDL_JoystickNumHats(stick) ); - Com_DPrintf( "Buttons: %d\n", SDL_JoystickNumButtons(stick) ); - Com_DPrintf( "Balls: %d\n", SDL_JoystickNumBalls(stick) ); - Com_DPrintf( "Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No" ); - Com_DPrintf( "Threshold: %f\n", in_joystickThreshold->value ); + Com_DPrintf("Joystick %d opened\n", in_joystickNo->integer); + Com_DPrintf("Name: %s\n", SDL_JoystickNameForIndex(in_joystickNo->integer)); + Com_DPrintf("Axes: %d\n", SDL_JoystickNumAxes(stick)); + Com_DPrintf("Hats: %d\n", SDL_JoystickNumHats(stick)); + Com_DPrintf("Buttons: %d\n", SDL_JoystickNumButtons(stick)); + Com_DPrintf("Balls: %d\n", SDL_JoystickNumBalls(stick)); + Com_DPrintf("Use Analog: %s\n", in_joystickUseAnalog->integer ? "Yes" : "No"); + Com_DPrintf("Threshold: %f\n", in_joystickThreshold->value); SDL_JoystickEventState(SDL_QUERY); } -void IN_Init( void *windowData ) -{ - if( !SDL_WasInit( SDL_INIT_VIDEO ) ) - { - Com_Error( ERR_FATAL, "IN_Init called before SDL_Init( SDL_INIT_VIDEO )" ); +void IN_Init(void *windowData) { + if (!SDL_WasInit(SDL_INIT_VIDEO)) { + Com_Error(ERR_FATAL, "IN_Init called before SDL_Init( SDL_INIT_VIDEO )"); return; } SDL_window = (SDL_Window *)windowData; - Com_DPrintf( "\n------- Input Initialization -------\n" ); + Com_DPrintf("\n------- Input Initialization -------\n"); // joystick variables - in_keyboardDebug = Cvar_Get( "in_keyboardDebug", "0", CVAR_ARCHIVE_ND ); + in_keyboardDebug = Cvar_Get("in_keyboardDebug", "0", CVAR_ARCHIVE_ND); - in_joystick = Cvar_Get( "in_joystick", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); + in_joystick = Cvar_Get("in_joystick", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); // mouse variables - in_mouse = Cvar_Get( "in_mouse", "1", CVAR_ARCHIVE ); - in_nograb = Cvar_Get( "in_nograb", "0", CVAR_ARCHIVE_ND ); - - SDL_StartTextInput( ); - - mouseAvailable = (qboolean)( in_mouse->value != 0 ); - if ( in_mouse->integer == 2 ) { - Com_DPrintf( "Not using raw mouse input\n" ); - SDL_SetHint( "SDL_MOUSE_RELATIVE_MODE_WARP", "1" ); + in_mouse = Cvar_Get("in_mouse", "1", CVAR_ARCHIVE); + in_nograb = Cvar_Get("in_nograb", "0", CVAR_ARCHIVE_ND); + + SDL_StartTextInput(); + + mouseAvailable = (qboolean)(in_mouse->value != 0); + if (in_mouse->integer == 2) { + Com_DPrintf("Not using raw mouse input\n"); + SDL_SetHint("SDL_MOUSE_RELATIVE_MODE_WARP", "1"); + } else { + Com_DPrintf("Using raw mouse input\n"); + SDL_SetHint("SDL_MOUSE_RELATIVE_MODE_WARP", "0"); } - else { - Com_DPrintf( "Using raw mouse input\n" ); - SDL_SetHint( "SDL_MOUSE_RELATIVE_MODE_WARP", "0" ); - } - IN_DeactivateMouse( ); + IN_DeactivateMouse(); - int appState = SDL_GetWindowFlags( SDL_window ); - Cvar_SetValue( "com_unfocused", ( appState & SDL_WINDOW_INPUT_FOCUS ) == 0 ); - Cvar_SetValue( "com_minimized", ( appState & SDL_WINDOW_MINIMIZED ) != 0 ); + int appState = SDL_GetWindowFlags(SDL_window); + Cvar_SetValue("com_unfocused", (appState & SDL_WINDOW_INPUT_FOCUS) == 0); + Cvar_SetValue("com_minimized", (appState & SDL_WINDOW_MINIMIZED) != 0); - IN_InitJoystick( ); - Com_DPrintf( "------------------------------------\n" ); + IN_InitJoystick(); + Com_DPrintf("------------------------------------\n"); } -uint8_t ConvertUTF32ToExpectedCharset( uint32_t utf32 ) -{ - switch ( utf32 ) - { - // Cyrillic characters - mapped to Windows-1251 encoding - case 0x0410: return 192; - case 0x0411: return 193; - case 0x0412: return 194; - case 0x0413: return 195; - case 0x0414: return 196; - case 0x0415: return 197; - case 0x0416: return 198; - case 0x0417: return 199; - case 0x0418: return 200; - case 0x0419: return 201; - case 0x041A: return 202; - case 0x041B: return 203; - case 0x041C: return 204; - case 0x041D: return 205; - case 0x041E: return 206; - case 0x041F: return 207; - case 0x0420: return 208; - case 0x0421: return 209; - case 0x0422: return 210; - case 0x0423: return 211; - case 0x0424: return 212; - case 0x0425: return 213; - case 0x0426: return 214; - case 0x0427: return 215; - case 0x0428: return 216; - case 0x0429: return 217; - case 0x042A: return 218; - case 0x042B: return 219; - case 0x042C: return 220; - case 0x042D: return 221; - case 0x042E: return 222; - case 0x042F: return 223; - case 0x0430: return 224; - case 0x0431: return 225; - case 0x0432: return 226; - case 0x0433: return 227; - case 0x0434: return 228; - case 0x0435: return 229; - case 0x0436: return 230; - case 0x0437: return 231; - case 0x0438: return 232; - case 0x0439: return 233; - case 0x043A: return 234; - case 0x043B: return 235; - case 0x043C: return 236; - case 0x043D: return 237; - case 0x043E: return 238; - case 0x043F: return 239; - case 0x0440: return 240; - case 0x0441: return 241; - case 0x0442: return 242; - case 0x0443: return 243; - case 0x0444: return 244; - case 0x0445: return 245; - case 0x0446: return 246; - case 0x0447: return 247; - case 0x0448: return 248; - case 0x0449: return 249; - case 0x044A: return 250; - case 0x044B: return 251; - case 0x044C: return 252; - case 0x044D: return 253; - case 0x044E: return 254; - case 0x044F: return 255; - - // Eastern european characters - polish, czech, etc use Windows-1250 encoding - case 0x0160: return 138; - case 0x015A: return 140; - case 0x0164: return 141; - case 0x017D: return 142; - case 0x0179: return 143; - case 0x0161: return 154; - case 0x015B: return 156; - case 0x0165: return 157; - case 0x017E: return 158; - case 0x017A: return 159; - case 0x0141: return 163; - case 0x0104: return 165; - case 0x015E: return 170; - case 0x017B: return 175; - case 0x0142: return 179; - case 0x0105: return 185; - case 0x015F: return 186; - case 0x013D: return 188; - case 0x013E: return 190; - case 0x017C: return 191; - case 0x0154: return 192; - case 0x00C1: return 193; - case 0x00C2: return 194; - case 0x0102: return 195; - case 0x00C4: return 196; - case 0x0139: return 197; - case 0x0106: return 198; - case 0x00C7: return 199; - case 0x010C: return 200; - case 0x00C9: return 201; - case 0x0118: return 202; - case 0x00CB: return 203; - case 0x011A: return 204; - case 0x00CD: return 205; - case 0x00CE: return 206; - case 0x010E: return 207; - case 0x0110: return 208; - case 0x0143: return 209; - case 0x0147: return 210; - case 0x00D3: return 211; - case 0x00D4: return 212; - case 0x0150: return 213; - case 0x00D6: return 214; - case 0x0158: return 216; - case 0x016E: return 217; - case 0x00DA: return 218; - case 0x0170: return 219; - case 0x00DC: return 220; - case 0x00DD: return 221; - case 0x0162: return 222; - case 0x00DF: return 223; - case 0x0155: return 224; - case 0x00E1: return 225; - case 0x00E2: return 226; - case 0x0103: return 227; - case 0x00E4: return 228; - case 0x013A: return 229; - case 0x0107: return 230; - case 0x00E7: return 231; - case 0x010D: return 232; - case 0x00E9: return 233; - case 0x0119: return 234; - case 0x00EB: return 235; - case 0x011B: return 236; - case 0x00ED: return 237; - case 0x00EE: return 238; - case 0x010F: return 239; - case 0x0111: return 240; - case 0x0144: return 241; - case 0x0148: return 242; - case 0x00F3: return 243; - case 0x00F4: return 244; - case 0x0151: return 245; - case 0x00F6: return 246; - case 0x0159: return 248; - case 0x016F: return 249; - case 0x00FA: return 250; - case 0x0171: return 251; - case 0x00FC: return 252; - case 0x00FD: return 253; - case 0x0163: return 254; - case 0x02D9: return 255; - - default: return (uint8_t)utf32; +uint8_t ConvertUTF32ToExpectedCharset(uint32_t utf32) { + switch (utf32) { + // Cyrillic characters - mapped to Windows-1251 encoding + case 0x0410: + return 192; + case 0x0411: + return 193; + case 0x0412: + return 194; + case 0x0413: + return 195; + case 0x0414: + return 196; + case 0x0415: + return 197; + case 0x0416: + return 198; + case 0x0417: + return 199; + case 0x0418: + return 200; + case 0x0419: + return 201; + case 0x041A: + return 202; + case 0x041B: + return 203; + case 0x041C: + return 204; + case 0x041D: + return 205; + case 0x041E: + return 206; + case 0x041F: + return 207; + case 0x0420: + return 208; + case 0x0421: + return 209; + case 0x0422: + return 210; + case 0x0423: + return 211; + case 0x0424: + return 212; + case 0x0425: + return 213; + case 0x0426: + return 214; + case 0x0427: + return 215; + case 0x0428: + return 216; + case 0x0429: + return 217; + case 0x042A: + return 218; + case 0x042B: + return 219; + case 0x042C: + return 220; + case 0x042D: + return 221; + case 0x042E: + return 222; + case 0x042F: + return 223; + case 0x0430: + return 224; + case 0x0431: + return 225; + case 0x0432: + return 226; + case 0x0433: + return 227; + case 0x0434: + return 228; + case 0x0435: + return 229; + case 0x0436: + return 230; + case 0x0437: + return 231; + case 0x0438: + return 232; + case 0x0439: + return 233; + case 0x043A: + return 234; + case 0x043B: + return 235; + case 0x043C: + return 236; + case 0x043D: + return 237; + case 0x043E: + return 238; + case 0x043F: + return 239; + case 0x0440: + return 240; + case 0x0441: + return 241; + case 0x0442: + return 242; + case 0x0443: + return 243; + case 0x0444: + return 244; + case 0x0445: + return 245; + case 0x0446: + return 246; + case 0x0447: + return 247; + case 0x0448: + return 248; + case 0x0449: + return 249; + case 0x044A: + return 250; + case 0x044B: + return 251; + case 0x044C: + return 252; + case 0x044D: + return 253; + case 0x044E: + return 254; + case 0x044F: + return 255; + + // Eastern european characters - polish, czech, etc use Windows-1250 encoding + case 0x0160: + return 138; + case 0x015A: + return 140; + case 0x0164: + return 141; + case 0x017D: + return 142; + case 0x0179: + return 143; + case 0x0161: + return 154; + case 0x015B: + return 156; + case 0x0165: + return 157; + case 0x017E: + return 158; + case 0x017A: + return 159; + case 0x0141: + return 163; + case 0x0104: + return 165; + case 0x015E: + return 170; + case 0x017B: + return 175; + case 0x0142: + return 179; + case 0x0105: + return 185; + case 0x015F: + return 186; + case 0x013D: + return 188; + case 0x013E: + return 190; + case 0x017C: + return 191; + case 0x0154: + return 192; + case 0x00C1: + return 193; + case 0x00C2: + return 194; + case 0x0102: + return 195; + case 0x00C4: + return 196; + case 0x0139: + return 197; + case 0x0106: + return 198; + case 0x00C7: + return 199; + case 0x010C: + return 200; + case 0x00C9: + return 201; + case 0x0118: + return 202; + case 0x00CB: + return 203; + case 0x011A: + return 204; + case 0x00CD: + return 205; + case 0x00CE: + return 206; + case 0x010E: + return 207; + case 0x0110: + return 208; + case 0x0143: + return 209; + case 0x0147: + return 210; + case 0x00D3: + return 211; + case 0x00D4: + return 212; + case 0x0150: + return 213; + case 0x00D6: + return 214; + case 0x0158: + return 216; + case 0x016E: + return 217; + case 0x00DA: + return 218; + case 0x0170: + return 219; + case 0x00DC: + return 220; + case 0x00DD: + return 221; + case 0x0162: + return 222; + case 0x00DF: + return 223; + case 0x0155: + return 224; + case 0x00E1: + return 225; + case 0x00E2: + return 226; + case 0x0103: + return 227; + case 0x00E4: + return 228; + case 0x013A: + return 229; + case 0x0107: + return 230; + case 0x00E7: + return 231; + case 0x010D: + return 232; + case 0x00E9: + return 233; + case 0x0119: + return 234; + case 0x00EB: + return 235; + case 0x011B: + return 236; + case 0x00ED: + return 237; + case 0x00EE: + return 238; + case 0x010F: + return 239; + case 0x0111: + return 240; + case 0x0144: + return 241; + case 0x0148: + return 242; + case 0x00F3: + return 243; + case 0x00F4: + return 244; + case 0x0151: + return 245; + case 0x00F6: + return 246; + case 0x0159: + return 248; + case 0x016F: + return 249; + case 0x00FA: + return 250; + case 0x0171: + return 251; + case 0x00FC: + return 252; + case 0x00FD: + return 253; + case 0x0163: + return 254; + case 0x02D9: + return 255; + + default: + return (uint8_t)utf32; } } @@ -809,135 +1070,131 @@ uint8_t ConvertUTF32ToExpectedCharset( uint32_t utf32 ) IN_ProcessEvents =============== */ -void SNDDMA_Activate( qboolean activate ); -static void IN_ProcessEvents( void ) -{ +void SNDDMA_Activate(qboolean activate); +static void IN_ProcessEvents(void) { SDL_Event e; fakeAscii_t key = A_NULL; static fakeAscii_t lastKeyDown = A_NULL; - if( !SDL_WasInit( SDL_INIT_VIDEO ) ) - return; + if (!SDL_WasInit(SDL_INIT_VIDEO)) + return; - while( SDL_PollEvent( &e ) ) - { - switch( e.type ) - { - case SDL_KEYDOWN: - key = IN_TranslateSDLToJKKey( &e.key.keysym, qtrue ); - if ( key != A_NULL ) - Sys_QueEvent( 0, SE_KEY, key, qtrue, 0, NULL ); - - if ( key == A_BACKSPACE ) - Sys_QueEvent( 0, SE_CHAR, CTRL('h'), qfalse, 0, NULL); - else if ( kg.keys[A_CTRL].down && key >= A_CAP_A && key <= A_CAP_Z ) - Sys_QueEvent( 0, SE_CHAR, CTRL(tolower(key)), qfalse, 0, NULL ); - - lastKeyDown = key; - break; + while (SDL_PollEvent(&e)) { + switch (e.type) { + case SDL_KEYDOWN: + key = IN_TranslateSDLToJKKey(&e.key.keysym, qtrue); + if (key != A_NULL) + Sys_QueEvent(0, SE_KEY, key, qtrue, 0, NULL); - case SDL_KEYUP: - key = IN_TranslateSDLToJKKey( &e.key.keysym, qfalse ); - if( key != A_NULL ) - Sys_QueEvent( 0, SE_KEY, key, qfalse, 0, NULL ); + if (key == A_BACKSPACE) + Sys_QueEvent(0, SE_CHAR, CTRL('h'), qfalse, 0, NULL); + else if (kg.keys[A_CTRL].down && key >= A_CAP_A && key <= A_CAP_Z) + Sys_QueEvent(0, SE_CHAR, CTRL(tolower(key)), qfalse, 0, NULL); - lastKeyDown = A_NULL; - break; + lastKeyDown = key; + break; + + case SDL_KEYUP: + key = IN_TranslateSDLToJKKey(&e.key.keysym, qfalse); + if (key != A_NULL) + Sys_QueEvent(0, SE_KEY, key, qfalse, 0, NULL); - case SDL_TEXTINPUT: - if( lastKeyDown != A_CONSOLE ) - { - char *c = e.text.text; - - // Quick and dirty UTF-8 to UTF-32 conversion - while( *c ) - { - uint32_t utf32 = ConvertUTF8ToUTF32( c, &c ); - if( utf32 != 0 ) - { - if( IN_IsConsoleKey( A_NULL, utf32 ) && !cl_consoleUseScanCode->integer ) - { - Sys_QueEvent( 0, SE_KEY, A_CONSOLE, qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, A_CONSOLE, qfalse, 0, NULL ); - } - else - { - uint8_t encoded = ConvertUTF32ToExpectedCharset( utf32 ); - Sys_QueEvent( 0, SE_CHAR, encoded, 0, 0, NULL ); - } + lastKeyDown = A_NULL; + break; + + case SDL_TEXTINPUT: + if (lastKeyDown != A_CONSOLE) { + char *c = e.text.text; + + // Quick and dirty UTF-8 to UTF-32 conversion + while (*c) { + uint32_t utf32 = ConvertUTF8ToUTF32(c, &c); + if (utf32 != 0) { + if (IN_IsConsoleKey(A_NULL, utf32) && !cl_consoleUseScanCode->integer) { + Sys_QueEvent(0, SE_KEY, A_CONSOLE, qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, A_CONSOLE, qfalse, 0, NULL); + } else { + uint8_t encoded = ConvertUTF32ToExpectedCharset(utf32); + Sys_QueEvent(0, SE_CHAR, encoded, 0, 0, NULL); } } } - break; + } + break; - case SDL_MOUSEMOTION: - if ( mouseActive ) - { - if ( !e.motion.xrel && !e.motion.yrel ) - break; - Sys_QueEvent( 0, SE_MOUSE, e.motion.xrel, e.motion.yrel, 0, NULL ); - } - break; + case SDL_MOUSEMOTION: + if (mouseActive) { + if (!e.motion.xrel && !e.motion.yrel) + break; + Sys_QueEvent(0, SE_MOUSE, e.motion.xrel, e.motion.yrel, 0, NULL); + } + break; - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - { - unsigned short b; - switch( e.button.button ) - { - case SDL_BUTTON_LEFT: b = A_MOUSE1; break; - case SDL_BUTTON_MIDDLE: b = A_MOUSE3; break; - case SDL_BUTTON_RIGHT: b = A_MOUSE2; break; - case SDL_BUTTON_X1: b = A_MOUSE4; break; - case SDL_BUTTON_X2: b = A_MOUSE5; break; - default: b = A_AUX0 + ( e.button.button - 6 ) % 32; break; - } - Sys_QueEvent( 0, SE_KEY, b, - ( e.type == SDL_MOUSEBUTTONDOWN ? qtrue : qfalse ), 0, NULL ); - } + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: { + unsigned short b; + switch (e.button.button) { + case SDL_BUTTON_LEFT: + b = A_MOUSE1; break; - - case SDL_MOUSEWHEEL: - if( e.wheel.y > 0 ) - { - Sys_QueEvent( 0, SE_KEY, A_MWHEELUP, qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, A_MWHEELUP, qfalse, 0, NULL ); - } - else if( e.wheel.y < 0 ) - { - Sys_QueEvent( 0, SE_KEY, A_MWHEELDOWN, qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, A_MWHEELDOWN, qfalse, 0, NULL ); - } + case SDL_BUTTON_MIDDLE: + b = A_MOUSE3; break; - - case SDL_QUIT: - Cbuf_ExecuteText(EXEC_NOW, "quit Closed window\n"); + case SDL_BUTTON_RIGHT: + b = A_MOUSE2; + break; + case SDL_BUTTON_X1: + b = A_MOUSE4; + break; + case SDL_BUTTON_X2: + b = A_MOUSE5; break; + default: + b = A_AUX0 + (e.button.button - 6) % 32; + break; + } + Sys_QueEvent(0, SE_KEY, b, (e.type == SDL_MOUSEBUTTONDOWN ? qtrue : qfalse), 0, NULL); + } break; + + case SDL_MOUSEWHEEL: + if (e.wheel.y > 0) { + Sys_QueEvent(0, SE_KEY, A_MWHEELUP, qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, A_MWHEELUP, qfalse, 0, NULL); + } else if (e.wheel.y < 0) { + Sys_QueEvent(0, SE_KEY, A_MWHEELDOWN, qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, A_MWHEELDOWN, qfalse, 0, NULL); + } + break; - case SDL_WINDOWEVENT: - switch( e.window.event ) - { - case SDL_WINDOWEVENT_MINIMIZED: Cvar_SetValue( "com_minimized", 1 ); break; - case SDL_WINDOWEVENT_RESTORED: - case SDL_WINDOWEVENT_MAXIMIZED: Cvar_SetValue( "com_minimized", 0 ); break; - case SDL_WINDOWEVENT_FOCUS_LOST: - { - Cvar_SetValue( "com_unfocused", 1 ); - SNDDMA_Activate( qfalse ); - break; - } + case SDL_QUIT: + Cbuf_ExecuteText(EXEC_NOW, "quit Closed window\n"); + break; - case SDL_WINDOWEVENT_FOCUS_GAINED: - { - Cvar_SetValue( "com_unfocused", 0 ); - SNDDMA_Activate( qtrue ); - break; - } - } + case SDL_WINDOWEVENT: + switch (e.window.event) { + case SDL_WINDOWEVENT_MINIMIZED: + Cvar_SetValue("com_minimized", 1); + break; + case SDL_WINDOWEVENT_RESTORED: + case SDL_WINDOWEVENT_MAXIMIZED: + Cvar_SetValue("com_minimized", 0); + break; + case SDL_WINDOWEVENT_FOCUS_LOST: { + Cvar_SetValue("com_unfocused", 1); + SNDDMA_Activate(qfalse); break; + } - default: + case SDL_WINDOWEVENT_FOCUS_GAINED: { + Cvar_SetValue("com_unfocused", 0); + SNDDMA_Activate(qtrue); break; + } + } + break; + + default: + break; } } } @@ -947,8 +1204,7 @@ static void IN_ProcessEvents( void ) IN_JoyMove =============== */ -static void IN_JoyMove( void ) -{ +static void IN_JoyMove(void) { unsigned int axes = 0; unsigned int hats = 0; int total = 0; @@ -961,42 +1217,36 @@ static void IN_JoyMove( void ) // update the ball state. total = SDL_JoystickNumBalls(stick); - if (total > 0) - { + if (total > 0) { int balldx = 0; int balldy = 0; - for (i = 0; i < total; i++) - { + for (i = 0; i < total; i++) { int dx = 0; int dy = 0; SDL_JoystickGetBall(stick, i, &dx, &dy); balldx += dx; balldy += dy; } - if (balldx || balldy) - { + if (balldx || balldy) { // !!! FIXME: is this good for stick balls, or just mice? // Scale like the mouse input... if (abs(balldx) > 1) balldx *= 2; if (abs(balldy) > 1) balldy *= 2; - Sys_QueEvent( 0, SE_MOUSE, balldx, balldy, 0, NULL ); + Sys_QueEvent(0, SE_MOUSE, balldx, balldy, 0, NULL); } } // now query the stick buttons... total = SDL_JoystickNumButtons(stick); - if (total > 0) - { + if (total > 0) { if (total > (int)ARRAY_LEN(stick_state.buttons)) total = ARRAY_LEN(stick_state.buttons); - for (i = 0; i < total; i++) - { + for (i = 0; i < total; i++) { qboolean pressed = (qboolean)(SDL_JoystickGetButton(stick, i) != 0); - if (pressed != stick_state.buttons[i]) - { - Sys_QueEvent( 0, SE_KEY, A_JOY1 + i, pressed, 0, NULL ); + if (pressed != stick_state.buttons[i]) { + Sys_QueEvent(0, SE_KEY, A_JOY1 + i, pressed, 0, NULL); stick_state.buttons[i] = pressed; } } @@ -1004,85 +1254,83 @@ static void IN_JoyMove( void ) // look at the hats... total = SDL_JoystickNumHats(stick); - if (total > 0) - { - if (total > 4) total = 4; - for (i = 0; i < total; i++) - { + if (total > 0) { + if (total > 4) + total = 4; + for (i = 0; i < total; i++) { ((Uint8 *)&hats)[i] = SDL_JoystickGetHat(stick, i); } } // update hat state - if (hats != stick_state.oldhats) - { - for( i = 0; i < 4; i++ ) { - if( ((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i] ) { + if (hats != stick_state.oldhats) { + for (i = 0; i < 4; i++) { + if (((Uint8 *)&hats)[i] != ((Uint8 *)&stick_state.oldhats)[i]) { // release event - switch( ((Uint8 *)&stick_state.oldhats)[i] ) { - case SDL_HAT_UP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); - break; - case SDL_HAT_RIGHT: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); - break; - case SDL_HAT_DOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); - break; - case SDL_HAT_LEFT: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); - break; - case SDL_HAT_RIGHTUP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); - break; - case SDL_HAT_RIGHTDOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qfalse, 0, NULL ); - break; - case SDL_HAT_LEFTUP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qfalse, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); - break; - case SDL_HAT_LEFTDOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qfalse, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qfalse, 0, NULL ); - break; - default: - break; + switch (((Uint8 *)&stick_state.oldhats)[i]) { + case SDL_HAT_UP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); + break; + case SDL_HAT_RIGHT: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); + break; + case SDL_HAT_DOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); + break; + case SDL_HAT_LEFT: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); + break; + case SDL_HAT_RIGHTUP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); + break; + case SDL_HAT_RIGHTDOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qfalse, 0, NULL); + break; + case SDL_HAT_LEFTUP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qfalse, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); + break; + case SDL_HAT_LEFTDOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qfalse, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qfalse, 0, NULL); + break; + default: + break; } // press event - switch( ((Uint8 *)&hats)[i] ) { - case SDL_HAT_UP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); - break; - case SDL_HAT_RIGHT: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); - break; - case SDL_HAT_DOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); - break; - case SDL_HAT_LEFT: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); - break; - case SDL_HAT_RIGHTUP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); - break; - case SDL_HAT_RIGHTDOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 1], qtrue, 0, NULL ); - break; - case SDL_HAT_LEFTUP: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 0], qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); - break; - case SDL_HAT_LEFTDOWN: - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 2], qtrue, 0, NULL ); - Sys_QueEvent( 0, SE_KEY, hat_keys[4*i + 3], qtrue, 0, NULL ); - break; - default: - break; + switch (((Uint8 *)&hats)[i]) { + case SDL_HAT_UP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); + break; + case SDL_HAT_RIGHT: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); + break; + case SDL_HAT_DOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); + break; + case SDL_HAT_LEFT: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); + break; + case SDL_HAT_RIGHTUP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); + break; + case SDL_HAT_RIGHTDOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 1], qtrue, 0, NULL); + break; + case SDL_HAT_LEFTUP: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 0], qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); + break; + case SDL_HAT_LEFTDOWN: + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 2], qtrue, 0, NULL); + Sys_QueEvent(0, SE_KEY, hat_keys[4 * i + 3], qtrue, 0, NULL); + break; + default: + break; } } } @@ -1093,51 +1341,46 @@ static void IN_JoyMove( void ) // finally, look at the axes... total = SDL_JoystickNumAxes(stick); - if (total > 0) - { - if (in_joystickUseAnalog->integer) - { - if (total > MAX_JOYSTICK_AXIS) total = MAX_JOYSTICK_AXIS; - for (i = 0; i < total; i++) - { + if (total > 0) { + if (in_joystickUseAnalog->integer) { + if (total > MAX_JOYSTICK_AXIS) + total = MAX_JOYSTICK_AXIS; + for (i = 0; i < total; i++) { Sint16 axis = SDL_JoystickGetAxis(stick, i); - float f = ( (float) abs(axis) ) / 32767.0f; + float f = ((float)abs(axis)) / 32767.0f; - if( f < in_joystickThreshold->value ) axis = 0; + if (f < in_joystickThreshold->value) + axis = 0; - if ( axis != stick_state.oldaaxes[i] ) - { - Sys_QueEvent( 0, SE_JOYSTICK_AXIS, i, axis, 0, NULL ); + if (axis != stick_state.oldaaxes[i]) { + Sys_QueEvent(0, SE_JOYSTICK_AXIS, i, axis, 0, NULL); stick_state.oldaaxes[i] = axis; } } - } - else - { - if (total > 16) total = 16; - for (i = 0; i < total; i++) - { + } else { + if (total > 16) + total = 16; + for (i = 0; i < total; i++) { Sint16 axis = SDL_JoystickGetAxis(stick, i); - float f = ( (float) axis ) / 32767.0f; - if( f < -in_joystickThreshold->value ) { - axes |= ( 1 << ( i * 2 ) ); - } else if( f > in_joystickThreshold->value ) { - axes |= ( 1 << ( ( i * 2 ) + 1 ) ); + float f = ((float)axis) / 32767.0f; + if (f < -in_joystickThreshold->value) { + axes |= (1 << (i * 2)); + } else if (f > in_joystickThreshold->value) { + axes |= (1 << ((i * 2) + 1)); } } } } /* Time to update axes state based on old vs. new. */ - if (axes != stick_state.oldaxes) - { - for( i = 0; i < 16; i++ ) { - if( ( axes & ( 1 << i ) ) && !( stick_state.oldaxes & ( 1 << i ) ) ) { - Sys_QueEvent( 0, SE_KEY, joy_keys[i], qtrue, 0, NULL ); + if (axes != stick_state.oldaxes) { + for (i = 0; i < 16; i++) { + if ((axes & (1 << i)) && !(stick_state.oldaxes & (1 << i))) { + Sys_QueEvent(0, SE_KEY, joy_keys[i], qtrue, 0, NULL); } - if( !( axes & ( 1 << i ) ) && ( stick_state.oldaxes & ( 1 << i ) ) ) { - Sys_QueEvent( 0, SE_KEY, joy_keys[i], qfalse, 0, NULL ); + if (!(axes & (1 << i)) && (stick_state.oldaxes & (1 << i))) { + Sys_QueEvent(0, SE_KEY, joy_keys[i], qfalse, 0, NULL); } } } @@ -1146,34 +1389,27 @@ static void IN_JoyMove( void ) stick_state.oldaxes = axes; } - -void IN_Frame (void) { +void IN_Frame(void) { qboolean loading; - IN_JoyMove( ); + IN_JoyMove(); // If not DISCONNECTED (main menu) or ACTIVE (in game), we're loading - loading = (qboolean)( cls.state != CA_DISCONNECTED && cls.state != CA_ACTIVE ); + loading = (qboolean)(cls.state != CA_DISCONNECTED && cls.state != CA_ACTIVE); - if( !cls.glconfig.isFullscreen && ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) ) - { + if (!cls.glconfig.isFullscreen && (Key_GetCatcher() & KEYCATCH_CONSOLE)) { // Console is down in windowed mode - IN_DeactivateMouse( ); - } - else if( !cls.glconfig.isFullscreen && loading ) - { + IN_DeactivateMouse(); + } else if (!cls.glconfig.isFullscreen && loading) { // Loading in windowed mode - IN_DeactivateMouse( ); - } - else if( !( SDL_GetWindowFlags( SDL_window ) & SDL_WINDOW_INPUT_FOCUS ) ) - { + IN_DeactivateMouse(); + } else if (!(SDL_GetWindowFlags(SDL_window) & SDL_WINDOW_INPUT_FOCUS)) { // Window not got focus - IN_DeactivateMouse( ); - } - else - IN_ActivateMouse( ); + IN_DeactivateMouse(); + } else + IN_ActivateMouse(); - IN_ProcessEvents( ); + IN_ProcessEvents(); } /* @@ -1181,13 +1417,11 @@ void IN_Frame (void) { IN_ShutdownJoystick =============== */ -static void IN_ShutdownJoystick( void ) -{ - if ( !SDL_WasInit( SDL_INIT_JOYSTICK ) ) +static void IN_ShutdownJoystick(void) { + if (!SDL_WasInit(SDL_INIT_JOYSTICK)) return; - if (stick) - { + if (stick) { SDL_JoystickClose(stick); stick = NULL; } @@ -1195,13 +1429,13 @@ static void IN_ShutdownJoystick( void ) SDL_QuitSubSystem(SDL_INIT_JOYSTICK); } -void IN_Shutdown( void ) { - SDL_StopTextInput( ); +void IN_Shutdown(void) { + SDL_StopTextInput(); - IN_DeactivateMouse( ); + IN_DeactivateMouse(); mouseAvailable = qfalse; - IN_ShutdownJoystick( ); + IN_ShutdownJoystick(); SDL_window = NULL; } @@ -1211,8 +1445,7 @@ void IN_Shutdown( void ) { IN_Restart =============== */ -void IN_Restart( void ) -{ - IN_ShutdownJoystick( ); - IN_Init( SDL_window ); +void IN_Restart(void) { + IN_ShutdownJoystick(); + IN_Init(SDL_window); } diff --git a/shared/sdl/sdl_sound.cpp b/shared/sdl/sdl_sound.cpp index 45e5a889cc..65da10d8b1 100644 --- a/shared/sdl/sdl_sound.cpp +++ b/shared/sdl/sdl_sound.cpp @@ -29,8 +29,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "client/client.h" #include "client/snd_local.h" -extern dma_t dma; -SDL_AudioDeviceID dev; +extern dma_t dma; +SDL_AudioDeviceID dev; qboolean snd_inited = qfalse; cvar_t *s_sdlBits; @@ -48,35 +48,31 @@ static int dmasize = 0; SNDDMA_AudioCallback =============== */ -static void SNDDMA_AudioCallback(void *userdata, Uint8 *stream, int len) -{ - int pos = (dmapos * (dma.samplebits/8)); +static void SNDDMA_AudioCallback(void *userdata, Uint8 *stream, int len) { + int pos = (dmapos * (dma.samplebits / 8)); if (pos >= dmasize) dmapos = pos = 0; - if (!snd_inited) /* shouldn't happen, but just in case... */ + if (!snd_inited) /* shouldn't happen, but just in case... */ { memset(stream, '\0', len); return; - } - else - { - int tobufend = dmasize - pos; /* bytes to buffer's end. */ + } else { + int tobufend = dmasize - pos; /* bytes to buffer's end. */ int len1 = len; int len2 = 0; - if (len1 > tobufend) - { + if (len1 > tobufend) { len1 = tobufend; len2 = len - len1; } memcpy(stream, dma.buffer + pos, len1); if (len2 <= 0) - dmapos += (len1 / (dma.samplebits/8)); - else /* wraparound? */ + dmapos += (len1 / (dma.samplebits / 8)); + else /* wraparound? */ { - memcpy(stream+len1, dma.buffer, len2); - dmapos = (len2 / (dma.samplebits/8)); + memcpy(stream + len1, dma.buffer, len2); + dmapos = (len2 / (dma.samplebits / 8)); } } @@ -84,62 +80,51 @@ static void SNDDMA_AudioCallback(void *userdata, Uint8 *stream, int len) dmapos = 0; } -static struct -{ - Uint16 enumFormat; - const char *stringFormat; -} formatToStringTable[ ] = -{ - { AUDIO_U8, "AUDIO_U8" }, - { AUDIO_S8, "AUDIO_S8" }, - { AUDIO_U16LSB, "AUDIO_U16LSB" }, - { AUDIO_S16LSB, "AUDIO_S16LSB" }, - { AUDIO_U16MSB, "AUDIO_U16MSB" }, - { AUDIO_S16MSB, "AUDIO_S16MSB" }, - { AUDIO_S32LSB, "AUDIO_S32LSB" }, - { AUDIO_S32MSB, "AUDIO_S32MSB" }, - { AUDIO_F32LSB, "AUDIO_F32LSB" }, - { AUDIO_F32MSB, "AUDIO_F32MSB" } -}; - -static const size_t formatToStringTableSize = ARRAY_LEN( formatToStringTable ); +static struct { + Uint16 enumFormat; + const char *stringFormat; +} formatToStringTable[] = {{AUDIO_U8, "AUDIO_U8"}, {AUDIO_S8, "AUDIO_S8"}, {AUDIO_U16LSB, "AUDIO_U16LSB"}, {AUDIO_S16LSB, "AUDIO_S16LSB"}, + {AUDIO_U16MSB, "AUDIO_U16MSB"}, {AUDIO_S16MSB, "AUDIO_S16MSB"}, {AUDIO_S32LSB, "AUDIO_S32LSB"}, {AUDIO_S32MSB, "AUDIO_S32MSB"}, + {AUDIO_F32LSB, "AUDIO_F32LSB"}, {AUDIO_F32MSB, "AUDIO_F32MSB"}}; + +static const size_t formatToStringTableSize = ARRAY_LEN(formatToStringTable); /* =============== SNDDMA_PrintAudiospec =============== */ -static void SNDDMA_PrintAudiospec(const char *str, const SDL_AudioSpec *spec) -{ - const char *fmt = NULL; +static void SNDDMA_PrintAudiospec(const char *str, const SDL_AudioSpec *spec) { + const char *fmt = NULL; - Com_Printf( "%s:\n", str ); + Com_Printf("%s:\n", str); - for( size_t i = 0; i < formatToStringTableSize; i++ ) { - if( spec->format == formatToStringTable[ i ].enumFormat ) { - fmt = formatToStringTable[ i ].stringFormat; + for (size_t i = 0; i < formatToStringTableSize; i++) { + if (spec->format == formatToStringTable[i].enumFormat) { + fmt = formatToStringTable[i].stringFormat; } } - if( fmt ) { - Com_Printf( " Format: %s\n", fmt ); + if (fmt) { + Com_Printf(" Format: %s\n", fmt); } else { - Com_Printf( " Format: " S_COLOR_RED "UNKNOWN (%d)\n", (int)spec->format); + Com_Printf(" Format: " S_COLOR_RED "UNKNOWN (%d)\n", (int)spec->format); } - Com_Printf( " Freq: %d\n", (int) spec->freq ); - Com_Printf( " Samples: %d\n", (int) spec->samples ); - Com_Printf( " Channels: %d\n", (int) spec->channels ); + Com_Printf(" Freq: %d\n", (int)spec->freq); + Com_Printf(" Samples: %d\n", (int)spec->samples); + Com_Printf(" Channels: %d\n", (int)spec->channels); } -static int SNDDMA_ExpandSampleFrequencyKHzToHz(int khz) -{ - switch (khz) - { - default: - case 44: return 44100; - case 22: return 22050; - case 11: return 11025; +static int SNDDMA_ExpandSampleFrequencyKHzToHz(int khz) { + switch (khz) { + default: + case 44: + return 44100; + case 22: + return 22050; + case 11: + return 11025; } } @@ -148,8 +133,7 @@ static int SNDDMA_ExpandSampleFrequencyKHzToHz(int khz) SNDDMA_Init =============== */ -qboolean SNDDMA_Init(int sampleFrequencyInKHz) -{ +qboolean SNDDMA_Init(int sampleFrequencyInKHz) { SDL_AudioSpec desired; SDL_AudioSpec obtained; int tmp; @@ -164,25 +148,23 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) s_sdlMixSamps = Cvar_Get("s_sdlMixSamps", "0", CVAR_ARCHIVE_ND); } - Com_Printf( "SDL_Init( SDL_INIT_AUDIO )... " ); + Com_Printf("SDL_Init( SDL_INIT_AUDIO )... "); - if (!SDL_WasInit(SDL_INIT_AUDIO)) - { - if (SDL_Init(SDL_INIT_AUDIO) == -1) - { - Com_Printf( "FAILED (%s)\n", SDL_GetError( ) ); + if (!SDL_WasInit(SDL_INIT_AUDIO)) { + if (SDL_Init(SDL_INIT_AUDIO) == -1) { + Com_Printf("FAILED (%s)\n", SDL_GetError()); return qfalse; } } - Com_Printf( "OK\n" ); + Com_Printf("OK\n"); - Com_Printf( "SDL audio driver is \"%s\".\n", SDL_GetCurrentAudioDriver( ) ); + Com_Printf("SDL audio driver is \"%s\".\n", SDL_GetCurrentAudioDriver()); - memset(&desired, '\0', sizeof (desired)); - memset(&obtained, '\0', sizeof (obtained)); + memset(&desired, '\0', sizeof(desired)); + memset(&obtained, '\0', sizeof(obtained)); - tmp = ((int) s_sdlBits->value); + tmp = ((int)s_sdlBits->value); if ((tmp != 16) && (tmp != 8)) tmp = 16; @@ -193,8 +175,7 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) // should probably check a cvar for this... if (s_sdlDevSamps->value) desired.samples = s_sdlDevSamps->value; - else - { + else { // just pick a sane default. if (desired.freq <= 11025) desired.samples = 256; @@ -203,15 +184,14 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) else if (desired.freq <= 44100) desired.samples = 1024; else - desired.samples = 2048; // (*shrug*) + desired.samples = 2048; // (*shrug*) } - desired.channels = (int) s_sdlChannels->value; + desired.channels = (int)s_sdlChannels->value; desired.callback = SNDDMA_AudioCallback; - dev = SDL_OpenAudioDevice( NULL, 0, &desired, &obtained, 0 ); - if ( !dev ) - { + dev = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, 0); + if (!dev) { Com_Printf("SDL_OpenAudioDevice() failed: %s\n", SDL_GetError()); SDL_QuitSubSystem(SDL_INIT_AUDIO); return qfalse; @@ -230,7 +210,7 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) if (!tmp) tmp = (obtained.samples * obtained.channels) * 10; - if (tmp & (tmp - 1)) // not a power of two? Seems to confuse something. + if (tmp & (tmp - 1)) // not a power of two? Seems to confuse something. { int val = 1; while (val < tmp) @@ -240,16 +220,16 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) } dmapos = 0; - dma.samplebits = obtained.format & 0xFF; // first byte of format is bits. + dma.samplebits = obtained.format & 0xFF; // first byte of format is bits. dma.channels = obtained.channels; dma.samples = tmp; dma.submission_chunk = 1; dma.speed = obtained.freq; - dmasize = (dma.samples * (dma.samplebits/8)); + dmasize = (dma.samples * (dma.samplebits / 8)); dma.buffer = (byte *)calloc(1, dmasize); Com_Printf("Starting SDL audio callback...\n"); - SDL_PauseAudioDevice(dev, 0); // start callback. + SDL_PauseAudioDevice(dev, 0); // start callback. Com_Printf("SDL audio initialized.\n"); snd_inited = qtrue; @@ -261,18 +241,14 @@ qboolean SNDDMA_Init(int sampleFrequencyInKHz) SNDDMA_GetDMAPos =============== */ -int SNDDMA_GetDMAPos(void) -{ - return dmapos; -} +int SNDDMA_GetDMAPos(void) { return dmapos; } /* =============== SNDDMA_Shutdown =============== */ -void SNDDMA_Shutdown(void) -{ +void SNDDMA_Shutdown(void) { Com_Printf("Closing SDL audio device...\n"); SDL_PauseAudioDevice(dev, 1); SDL_CloseAudioDevice(dev); @@ -291,39 +267,30 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) -{ - SDL_UnlockAudioDevice(dev); -} +void SNDDMA_Submit(void) { SDL_UnlockAudioDevice(dev); } /* =============== SNDDMA_BeginPainting =============== */ -void SNDDMA_BeginPainting (void) -{ - SDL_LockAudioDevice(dev); -} +void SNDDMA_BeginPainting(void) { SDL_LockAudioDevice(dev); } #ifdef USE_OPENAL extern int s_UseOpenAL; #endif // (De)activates sound playback -void SNDDMA_Activate( qboolean activate ) -{ +void SNDDMA_Activate(qboolean activate) { #ifdef USE_OPENAL - if ( s_UseOpenAL ) - { - S_AL_MuteAllSounds( (qboolean)!activate ); + if (s_UseOpenAL) { + S_AL_MuteAllSounds((qboolean)!activate); } #endif - if ( activate ) - { + if (activate) { S_ClearSoundBuffer(); } - SDL_PauseAudioDevice( dev, !activate ); + SDL_PauseAudioDevice(dev, !activate); } diff --git a/shared/sdl/sdl_window.cpp b/shared/sdl/sdl_window.cpp index 5fa0f8b623..70a7b53106 100644 --- a/shared/sdl/sdl_window.cpp +++ b/shared/sdl/sdl_window.cpp @@ -26,8 +26,7 @@ along with this program; if not, see . #include "sys/sys_local.h" #include "sdl_icon.h" -enum rserr_t -{ +enum rserr_t { RSERR_OK, RSERR_INVALID_FULLSCREEN, @@ -44,62 +43,59 @@ cvar_t *r_sdlDriver; cvar_t *r_allowSoftwareGL; // Window cvars -cvar_t *r_fullscreen = 0; -cvar_t *r_noborder; -cvar_t *r_centerWindow; -cvar_t *r_customwidth; -cvar_t *r_customheight; -cvar_t *r_swapInterval; -cvar_t *r_stereo; -cvar_t *r_mode; -cvar_t *r_displayRefresh; +cvar_t *r_fullscreen = 0; +cvar_t *r_noborder; +cvar_t *r_centerWindow; +cvar_t *r_customwidth; +cvar_t *r_customheight; +cvar_t *r_swapInterval; +cvar_t *r_stereo; +cvar_t *r_mode; +cvar_t *r_displayRefresh; // Window surface cvars -cvar_t *r_stencilbits; -cvar_t *r_depthbits; -cvar_t *r_colorbits; -cvar_t *r_ignorehwgamma; -cvar_t *r_ext_multisample; +cvar_t *r_stencilbits; +cvar_t *r_depthbits; +cvar_t *r_colorbits; +cvar_t *r_ignorehwgamma; +cvar_t *r_ext_multisample; /* ** R_GetModeInfo */ -typedef struct vidmode_s -{ - const char *description; - int width, height; +typedef struct vidmode_s { + const char *description; + int width, height; } vidmode_t; -const vidmode_t r_vidModes[] = { - { "Mode 0: 320x240", 320, 240 }, - { "Mode 1: 400x300", 400, 300 }, - { "Mode 2: 512x384", 512, 384 }, - { "Mode 3: 640x480", 640, 480 }, - { "Mode 4: 800x600", 800, 600 }, - { "Mode 5: 960x720", 960, 720 }, - { "Mode 6: 1024x768", 1024, 768 }, - { "Mode 7: 1152x864", 1152, 864 }, - { "Mode 8: 1280x1024", 1280, 1024 }, - { "Mode 9: 1600x1200", 1600, 1200 }, - { "Mode 10: 2048x1536", 2048, 1536 }, - { "Mode 11: 856x480 (wide)", 856, 480 }, - { "Mode 12: 2400x600(surround)",2400,600 } -}; -static const int s_numVidModes = ARRAY_LEN( r_vidModes ); +const vidmode_t r_vidModes[] = {{"Mode 0: 320x240", 320, 240}, + {"Mode 1: 400x300", 400, 300}, + {"Mode 2: 512x384", 512, 384}, + {"Mode 3: 640x480", 640, 480}, + {"Mode 4: 800x600", 800, 600}, + {"Mode 5: 960x720", 960, 720}, + {"Mode 6: 1024x768", 1024, 768}, + {"Mode 7: 1152x864", 1152, 864}, + {"Mode 8: 1280x1024", 1280, 1024}, + {"Mode 9: 1600x1200", 1600, 1200}, + {"Mode 10: 2048x1536", 2048, 1536}, + {"Mode 11: 856x480 (wide)", 856, 480}, + {"Mode 12: 2400x600(surround)", 2400, 600}}; +static const int s_numVidModes = ARRAY_LEN(r_vidModes); #define R_MODE_FALLBACK (4) // 640x480 -qboolean R_GetModeInfo( int *width, int *height, int mode ) { - const vidmode_t *vm; +qboolean R_GetModeInfo(int *width, int *height, int mode) { + const vidmode_t *vm; - if ( mode < -1 ) { - return qfalse; + if (mode < -1) { + return qfalse; } - if ( mode >= s_numVidModes ) { + if (mode >= s_numVidModes) { return qfalse; } - if ( mode == -1 ) { + if (mode == -1) { *width = r_customwidth->integer; *height = r_customheight->integer; return qtrue; @@ -107,27 +103,25 @@ qboolean R_GetModeInfo( int *width, int *height, int mode ) { vm = &r_vidModes[mode]; - *width = vm->width; - *height = vm->height; + *width = vm->width; + *height = vm->height; - return qtrue; + return qtrue; } /* ** R_ModeList_f */ -static void R_ModeList_f( void ) -{ +static void R_ModeList_f(void) { int i; - Com_Printf( "\n" ); - Com_Printf( "Mode -2: Use desktop resolution\n" ); - Com_Printf( "Mode -1: Use r_customWidth and r_customHeight variables\n" ); - for ( i = 0; i < s_numVidModes; i++ ) - { - Com_Printf( "%s\n", r_vidModes[i].description ); + Com_Printf("\n"); + Com_Printf("Mode -2: Use desktop resolution\n"); + Com_Printf("Mode -1: Use r_customWidth and r_customHeight variables\n"); + for (i = 0; i < s_numVidModes; i++) { + Com_Printf("%s\n", r_vidModes[i].description); } - Com_Printf( "\n" ); + Com_Printf("\n"); } /* @@ -137,53 +131,43 @@ GLimp_Minimize Minimize the game so that user is back at the desktop =============== */ -void GLimp_Minimize(void) -{ - SDL_MinimizeWindow( screen ); -} +void GLimp_Minimize(void) { SDL_MinimizeWindow(screen); } -void WIN_Present( window_t *window ) -{ - if ( window->api == GRAPHICS_API_OPENGL ) - { +void WIN_Present(window_t *window) { + if (window->api == GRAPHICS_API_OPENGL) { SDL_GL_SwapWindow(screen); - if ( r_swapInterval->modified ) - { + if (r_swapInterval->modified) { r_swapInterval->modified = qfalse; - if ( SDL_GL_SetSwapInterval( r_swapInterval->integer ) == -1 ) - { - Com_DPrintf( "SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError() ); + if (SDL_GL_SetSwapInterval(r_swapInterval->integer) == -1) { + Com_DPrintf("SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError()); } } } - if ( r_fullscreen->modified ) - { - bool fullscreen; - bool needToToggle; - bool sdlToggled = qfalse; + if (r_fullscreen->modified) { + bool fullscreen; + bool needToToggle; + bool sdlToggled = qfalse; // Find out the current state - fullscreen = (SDL_GetWindowFlags( screen ) & SDL_WINDOW_FULLSCREEN) != 0; + fullscreen = (SDL_GetWindowFlags(screen) & SDL_WINDOW_FULLSCREEN) != 0; - if ( r_fullscreen->integer && Cvar_VariableIntegerValue( "in_nograb" ) ) - { - Com_Printf( "Fullscreen not allowed with in_nograb 1\n" ); - Cvar_Set( "r_fullscreen", "0" ); + if (r_fullscreen->integer && Cvar_VariableIntegerValue("in_nograb")) { + Com_Printf("Fullscreen not allowed with in_nograb 1\n"); + Cvar_Set("r_fullscreen", "0"); r_fullscreen->modified = qfalse; } // Is the state we want different from the current state? needToToggle = !!r_fullscreen->integer != fullscreen; - if ( needToToggle ) - { - sdlToggled = SDL_SetWindowFullscreen( screen, r_fullscreen->integer ) >= 0; + if (needToToggle) { + sdlToggled = SDL_SetWindowFullscreen(screen, r_fullscreen->integer) >= 0; // SDL_WM_ToggleFullScreen didn't work, so do it the slow way - if ( !sdlToggled ) - Cbuf_AddText( "vid_restart\n" ); + if (!sdlToggled) + Cbuf_AddText("vid_restart\n"); IN_Restart(); } @@ -197,8 +181,7 @@ void WIN_Present( window_t *window ) GLimp_CompareModes =============== */ -static int GLimp_CompareModes( const void *a, const void *b ) -{ +static int GLimp_CompareModes(const void *a, const void *b) { const float ASPECT_EPSILON = 0.001f; SDL_Rect *modeA = (SDL_Rect *)a; SDL_Rect *modeB = (SDL_Rect *)b; @@ -206,13 +189,13 @@ static int GLimp_CompareModes( const void *a, const void *b ) float aspectB = (float)modeB->w / (float)modeB->h; int areaA = modeA->w * modeA->h; int areaB = modeB->w * modeB->h; - float aspectDiffA = fabs( aspectA - displayAspect ); - float aspectDiffB = fabs( aspectB - displayAspect ); + float aspectDiffA = fabs(aspectA - displayAspect); + float aspectDiffB = fabs(aspectB - displayAspect); float aspectDiffsDiff = aspectDiffA - aspectDiffB; - if( aspectDiffsDiff > ASPECT_EPSILON ) + if (aspectDiffsDiff > ASPECT_EPSILON) return 1; - else if( aspectDiffsDiff < -ASPECT_EPSILON ) + else if (aspectDiffsDiff < -ASPECT_EPSILON) return -1; else return areaA - areaB; @@ -223,90 +206,82 @@ static int GLimp_CompareModes( const void *a, const void *b ) GLimp_DetectAvailableModes =============== */ -static bool GLimp_DetectAvailableModes(void) -{ +static bool GLimp_DetectAvailableModes(void) { int i, j; - char buf[ MAX_STRING_CHARS ] = { 0 }; + char buf[MAX_STRING_CHARS] = {0}; SDL_Rect *modes; int numModes = 0; - int display = SDL_GetWindowDisplayIndex( screen ); - if ( display < 0 ) - { - Com_Printf( S_COLOR_YELLOW "WARNING: Couldn't get window display index, no resolutions detected: %s\n", SDL_GetError() ); + int display = SDL_GetWindowDisplayIndex(screen); + if (display < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: Couldn't get window display index, no resolutions detected: %s\n", SDL_GetError()); return false; } SDL_DisplayMode windowMode; - if( SDL_GetWindowDisplayMode( screen, &windowMode ) < 0 ) - { - Com_Printf( S_COLOR_YELLOW "WARNING: Couldn't get window display mode, no resolutions detected (%s).\n", SDL_GetError() ); + if (SDL_GetWindowDisplayMode(screen, &windowMode) < 0) { + Com_Printf(S_COLOR_YELLOW "WARNING: Couldn't get window display mode, no resolutions detected (%s).\n", SDL_GetError()); return false; } - int numDisplayModes = SDL_GetNumDisplayModes( display ); - if ( numDisplayModes < 0 ) - Com_Error( ERR_FATAL, "SDL_GetNumDisplayModes() FAILED (%s)", SDL_GetError() ); + int numDisplayModes = SDL_GetNumDisplayModes(display); + if (numDisplayModes < 0) + Com_Error(ERR_FATAL, "SDL_GetNumDisplayModes() FAILED (%s)", SDL_GetError()); - modes = (SDL_Rect *)SDL_calloc( (size_t)numDisplayModes, sizeof( SDL_Rect ) ); - if ( !modes ) - Com_Error( ERR_FATAL, "Out of memory" ); + modes = (SDL_Rect *)SDL_calloc((size_t)numDisplayModes, sizeof(SDL_Rect)); + if (!modes) + Com_Error(ERR_FATAL, "Out of memory"); - for( i = 0; i < numDisplayModes; i++ ) - { + for (i = 0; i < numDisplayModes; i++) { SDL_DisplayMode mode; - if( SDL_GetDisplayMode( display, i, &mode ) < 0 ) + if (SDL_GetDisplayMode(display, i, &mode) < 0) continue; - if( !mode.w || !mode.h ) - { - Com_Printf( "Display supports any resolution\n" ); - SDL_free( modes ); + if (!mode.w || !mode.h) { + Com_Printf("Display supports any resolution\n"); + SDL_free(modes); return true; } - if( windowMode.format != mode.format ) + if (windowMode.format != mode.format) continue; // SDL can give the same resolution with different refresh rates. // Only list resolution once. - for( j = 0; j < numModes; j++ ) - { - if( mode.w == modes[ j ].w && mode.h == modes[ j ].h ) + for (j = 0; j < numModes; j++) { + if (mode.w == modes[j].w && mode.h == modes[j].h) break; } - if( j != numModes ) + if (j != numModes) continue; - modes[ numModes ].w = mode.w; - modes[ numModes ].h = mode.h; + modes[numModes].w = mode.w; + modes[numModes].h = mode.h; numModes++; } - if( numModes > 1 ) - qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes ); + if (numModes > 1) + qsort(modes, numModes, sizeof(SDL_Rect), GLimp_CompareModes); - for( i = 0; i < numModes; i++ ) - { - const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h ); + for (i = 0; i < numModes; i++) { + const char *newModeString = va("%ux%u ", modes[i].w, modes[i].h); - if( strlen( newModeString ) < (int)sizeof( buf ) - strlen( buf ) ) - Q_strcat( buf, sizeof( buf ), newModeString ); + if (strlen(newModeString) < (int)sizeof(buf) - strlen(buf)) + Q_strcat(buf, sizeof(buf), newModeString); else - Com_Printf( "Skipping mode %ux%u, buffer too small\n", modes[ i ].w, modes[ i ].h ); + Com_Printf("Skipping mode %ux%u, buffer too small\n", modes[i].w, modes[i].h); } - if( *buf ) - { - buf[ strlen( buf ) - 1 ] = 0; - Com_Printf( "Available modes: '%s'\n", buf ); - Cvar_Set( "r_availableModes", buf ); + if (*buf) { + buf[strlen(buf) - 1] = 0; + Com_Printf("Available modes: '%s'\n", buf); + Cvar_Set("r_availableModes", buf); } - SDL_free( modes ); + SDL_free(modes); return true; } @@ -315,8 +290,7 @@ static bool GLimp_DetectAvailableModes(void) GLimp_SetMode =============== */ -static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDesc, const char *windowTitle, int mode, qboolean fullscreen, qboolean noborder) -{ +static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDesc, const char *windowTitle, int mode, qboolean fullscreen, qboolean noborder) { int perChannelColorBits; int colorBits, depthBits, stencilBits; int samples; @@ -327,106 +301,84 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes int display = 0; int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED; - if ( windowDesc->api == GRAPHICS_API_OPENGL ) - { + if (windowDesc->api == GRAPHICS_API_OPENGL) { flags |= SDL_WINDOW_OPENGL; } - Com_Printf( "Initializing display\n"); + Com_Printf("Initializing display\n"); - icon = SDL_CreateRGBSurfaceFrom( - (void *)CLIENT_WINDOW_ICON.pixel_data, - CLIENT_WINDOW_ICON.width, - CLIENT_WINDOW_ICON.height, - CLIENT_WINDOW_ICON.bytes_per_pixel * 8, - CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, + icon = SDL_CreateRGBSurfaceFrom((void *)CLIENT_WINDOW_ICON.pixel_data, CLIENT_WINDOW_ICON.width, CLIENT_WINDOW_ICON.height, + CLIENT_WINDOW_ICON.bytes_per_pixel * 8, CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width, #ifdef Q3_LITTLE_ENDIAN - 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 + 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF + 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif - ); + ); // If a window exists, note its display index - if ( screen != NULL ) - { - display = SDL_GetWindowDisplayIndex( screen ); - if ( display < 0 ) - { - Com_DPrintf( "SDL_GetWindowDisplayIndex() failed: %s\n", SDL_GetError() ); + if (screen != NULL) { + display = SDL_GetWindowDisplayIndex(screen); + if (display < 0) { + Com_DPrintf("SDL_GetWindowDisplayIndex() failed: %s\n", SDL_GetError()); } } - if( display >= 0 && SDL_GetDesktopDisplayMode( display, &desktopMode ) == 0 ) - { + if (display >= 0 && SDL_GetDesktopDisplayMode(display, &desktopMode) == 0) { displayAspect = (float)desktopMode.w / (float)desktopMode.h; - Com_Printf( "Display aspect: %.3f\n", displayAspect ); - } - else - { - Com_Memset( &desktopMode, 0, sizeof( SDL_DisplayMode ) ); + Com_Printf("Display aspect: %.3f\n", displayAspect); + } else { + Com_Memset(&desktopMode, 0, sizeof(SDL_DisplayMode)); - Com_Printf( "Cannot determine display aspect, assuming 1.333\n" ); + Com_Printf("Cannot determine display aspect, assuming 1.333\n"); } - Com_Printf( "...setting mode %d:", mode ); + Com_Printf("...setting mode %d:", mode); - if (mode == -2) - { + if (mode == -2) { // use desktop video resolution - if( desktopMode.h > 0 ) - { + if (desktopMode.h > 0) { glConfig->vidWidth = desktopMode.w; glConfig->vidHeight = desktopMode.h; - } - else - { + } else { glConfig->vidWidth = 640; glConfig->vidHeight = 480; - Com_Printf( "Cannot determine display resolution, assuming 640x480\n" ); + Com_Printf("Cannot determine display resolution, assuming 640x480\n"); } - //glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; - } - else if ( !R_GetModeInfo( &glConfig->vidWidth, &glConfig->vidHeight, /*&glConfig.windowAspect,*/ mode ) ) - { - Com_Printf( " invalid mode\n" ); - SDL_FreeSurface( icon ); + // glConfig.windowAspect = (float)glConfig.vidWidth / (float)glConfig.vidHeight; + } else if (!R_GetModeInfo(&glConfig->vidWidth, &glConfig->vidHeight, /*&glConfig.windowAspect,*/ mode)) { + Com_Printf(" invalid mode\n"); + SDL_FreeSurface(icon); return RSERR_INVALID_MODE; } - Com_Printf( " %d %d\n", glConfig->vidWidth, glConfig->vidHeight); + Com_Printf(" %d %d\n", glConfig->vidWidth, glConfig->vidHeight); // Center window - if( r_centerWindow->integer && !fullscreen ) - { - x = ( desktopMode.w / 2 ) - ( glConfig->vidWidth / 2 ); - y = ( desktopMode.h / 2 ) - ( glConfig->vidHeight / 2 ); + if (r_centerWindow->integer && !fullscreen) { + x = (desktopMode.w / 2) - (glConfig->vidWidth / 2); + y = (desktopMode.h / 2) - (glConfig->vidHeight / 2); } // Destroy existing state if it exists - if( opengl_context != NULL ) - { - SDL_GL_DeleteContext( opengl_context ); + if (opengl_context != NULL) { + SDL_GL_DeleteContext(opengl_context); opengl_context = NULL; } - if( screen != NULL ) - { - SDL_GetWindowPosition( screen, &x, &y ); - Com_DPrintf( "Existing window at %dx%d before being destroyed\n", x, y ); - SDL_DestroyWindow( screen ); + if (screen != NULL) { + SDL_GetWindowPosition(screen, &x, &y); + Com_DPrintf("Existing window at %dx%d before being destroyed\n", x, y); + SDL_DestroyWindow(screen); screen = NULL; } - if( fullscreen ) - { + if (fullscreen) { flags |= SDL_WINDOW_FULLSCREEN; glConfig->isFullscreen = qtrue; - } - else - { - if( noborder ) + } else { + if (noborder) flags |= SDL_WINDOW_BORDERLESS; glConfig->isFullscreen = qfalse; @@ -444,35 +396,31 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes stencilBits = r_stencilbits->integer; samples = r_ext_multisample->integer; - if ( windowDesc->api == GRAPHICS_API_OPENGL ) - { - for (i = 0; i < 16; i++) - { + if (windowDesc->api == GRAPHICS_API_OPENGL) { + for (i = 0; i < 16; i++) { int testColorBits, testDepthBits, testStencilBits; // 0 - default // 1 - minus colorBits // 2 - minus depthBits // 3 - minus stencil - if ((i % 4) == 0 && i) - { + if ((i % 4) == 0 && i) { // one pass, reduce - switch (i / 4) - { - case 2 : - if (colorBits == 24) - colorBits = 16; - break; - case 1 : - if (depthBits == 24) - depthBits = 16; - else if (depthBits == 16) - depthBits = 8; - case 3 : - if (stencilBits == 24) - stencilBits = 16; - else if (stencilBits == 16) - stencilBits = 8; + switch (i / 4) { + case 2: + if (colorBits == 24) + colorBits = 16; + break; + case 1: + if (depthBits == 24) + depthBits = 16; + else if (depthBits == 16) + depthBits = 8; + case 3: + if (stencilBits == 24) + stencilBits = 16; + else if (stencilBits == 16) + stencilBits = 8; } } @@ -480,22 +428,19 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes testDepthBits = depthBits; testStencilBits = stencilBits; - if ((i % 4) == 3) - { // reduce colorBits + if ((i % 4) == 3) { // reduce colorBits if (testColorBits == 24) testColorBits = 16; } - if ((i % 4) == 2) - { // reduce depthBits + if ((i % 4) == 2) { // reduce depthBits if (testDepthBits == 24) testDepthBits = 16; else if (testDepthBits == 16) testDepthBits = 8; } - if ((i % 4) == 1) - { // reduce stencilBits + if ((i % 4) == 1) { // reduce stencilBits if (testStencilBits == 24) testStencilBits = 16; else if (testStencilBits == 16) @@ -509,27 +454,24 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes else perChannelColorBits = 4; - SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits ); - SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits ); - SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits ); - SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, testDepthBits ); - SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, testStencilBits ); + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, perChannelColorBits); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, perChannelColorBits); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, perChannelColorBits); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, testDepthBits); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, testStencilBits); - SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0 ); - SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, samples ); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, samples ? 1 : 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples); - if ( windowDesc->gl.majorVersion ) - { + if (windowDesc->gl.majorVersion) { int compactVersion = windowDesc->gl.majorVersion * 100 + windowDesc->gl.minorVersion * 10; - SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, windowDesc->gl.majorVersion ); - SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, windowDesc->gl.minorVersion ); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, windowDesc->gl.majorVersion); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, windowDesc->gl.minorVersion); - if ( windowDesc->gl.profile == GLPROFILE_ES || compactVersion >= 320 ) - { + if (windowDesc->gl.profile == GLPROFILE_ES || compactVersion >= 320) { int profile; - switch ( windowDesc->gl.profile ) - { + switch (windowDesc->gl.profile) { default: case GLPROFILE_COMPATIBILITY: profile = SDL_GL_CONTEXT_PROFILE_COMPATIBILITY; @@ -544,49 +486,47 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes break; } - SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, profile ); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile); } } - if ( windowDesc->gl.contextFlags & GLCONTEXT_DEBUG ) - { - SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG ); + if (windowDesc->gl.contextFlags & GLCONTEXT_DEBUG) { + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); } - if(r_stereo->integer) - { + if (r_stereo->integer) { glConfig->stereoEnabled = qtrue; SDL_GL_SetAttribute(SDL_GL_STEREO, 1); - } - else - { + } else { glConfig->stereoEnabled = qfalse; SDL_GL_SetAttribute(SDL_GL_STEREO, 0); } - SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); - SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, !r_allowSoftwareGL->integer ); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, !r_allowSoftwareGL->integer); - if( ( screen = SDL_CreateWindow( windowTitle, x, y, - glConfig->vidWidth, glConfig->vidHeight, flags ) ) == NULL ) - { - Com_DPrintf( "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); + if ((screen = SDL_CreateWindow(windowTitle, x, y, glConfig->vidWidth, glConfig->vidHeight, flags)) == NULL) { + Com_DPrintf("SDL_CreateWindow failed: %s\n", SDL_GetError()); continue; } #ifndef MACOS_X - SDL_SetWindowIcon( screen, icon ); + SDL_SetWindowIcon(screen, icon); #endif - if( fullscreen ) - { + if (fullscreen) { SDL_DisplayMode mode; - switch( testColorBits ) - { - case 16: mode.format = SDL_PIXELFORMAT_RGB565; break; - case 24: mode.format = SDL_PIXELFORMAT_RGB24; break; - default: Com_DPrintf( "testColorBits is %d, can't fullscreen\n", testColorBits ); continue; + switch (testColorBits) { + case 16: + mode.format = SDL_PIXELFORMAT_RGB565; + break; + case 24: + mode.format = SDL_PIXELFORMAT_RGB24; + break; + default: + Com_DPrintf("testColorBits is %d, can't fullscreen\n", testColorBits); + continue; } mode.w = glConfig->vidWidth; @@ -594,30 +534,26 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes mode.refresh_rate = glConfig->displayFrequency = r_displayRefresh->integer; mode.driverdata = NULL; - if( SDL_SetWindowDisplayMode( screen, &mode ) < 0 ) - { - Com_DPrintf( "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) ); + if (SDL_SetWindowDisplayMode(screen, &mode) < 0) { + Com_DPrintf("SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError()); continue; } } - if( ( opengl_context = SDL_GL_CreateContext( screen ) ) == NULL ) - { - Com_Printf( "SDL_GL_CreateContext failed: %s\n", SDL_GetError( ) ); + if ((opengl_context = SDL_GL_CreateContext(screen)) == NULL) { + Com_Printf("SDL_GL_CreateContext failed: %s\n", SDL_GetError()); continue; } - if ( SDL_GL_SetSwapInterval( r_swapInterval->integer ) == -1 ) - { - Com_DPrintf( "SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError() ); + if (SDL_GL_SetSwapInterval(r_swapInterval->integer) == -1) { + Com_DPrintf("SDL_GL_SetSwapInterval failed: %s\n", SDL_GetError()); } glConfig->colorBits = testColorBits; glConfig->depthBits = testDepthBits; glConfig->stencilBits = testStencilBits; - Com_Printf( "Using %d color bits, %d depth, %d stencil display.\n", - glConfig->colorBits, glConfig->depthBits, glConfig->stencilBits ); + Com_Printf("Using %d color bits, %d depth, %d stencil display.\n", glConfig->colorBits, glConfig->depthBits, glConfig->stencilBits); break; } @@ -625,34 +561,25 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes SDL_FreeSurface(icon); return RSERR_UNKNOWN; } - } - else - { + } else { // Just create a regular window - if( ( screen = SDL_CreateWindow( windowTitle, x, y, - glConfig->vidWidth, glConfig->vidHeight, flags ) ) == NULL ) - { - Com_DPrintf( "SDL_CreateWindow failed: %s\n", SDL_GetError( ) ); - } - else - { + if ((screen = SDL_CreateWindow(windowTitle, x, y, glConfig->vidWidth, glConfig->vidHeight, flags)) == NULL) { + Com_DPrintf("SDL_CreateWindow failed: %s\n", SDL_GetError()); + } else { #ifndef MACOS_X - SDL_SetWindowIcon( screen, icon ); + SDL_SetWindowIcon(screen, icon); #endif - if( fullscreen ) - { - if( SDL_SetWindowDisplayMode( screen, NULL ) < 0 ) - { - Com_DPrintf( "SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError( ) ); + if (fullscreen) { + if (SDL_SetWindowDisplayMode(screen, NULL) < 0) { + Com_DPrintf("SDL_SetWindowDisplayMode failed: %s\n", SDL_GetError()); } } } } - SDL_FreeSurface( icon ); + SDL_FreeSurface(icon); - if (!GLimp_DetectAvailableModes()) - { + if (!GLimp_DetectAvailableModes()) { return RSERR_UNKNOWN; } @@ -664,114 +591,101 @@ static rserr_t GLimp_SetMode(glconfig_t *glConfig, const windowDesc_t *windowDes GLimp_StartDriverAndSetMode =============== */ -static qboolean GLimp_StartDriverAndSetMode(glconfig_t *glConfig, const windowDesc_t *windowDesc, int mode, qboolean fullscreen, qboolean noborder) -{ +static qboolean GLimp_StartDriverAndSetMode(glconfig_t *glConfig, const windowDesc_t *windowDesc, int mode, qboolean fullscreen, qboolean noborder) { rserr_t err; - if (!SDL_WasInit(SDL_INIT_VIDEO)) - { + if (!SDL_WasInit(SDL_INIT_VIDEO)) { const char *driverName; - if (SDL_Init(SDL_INIT_VIDEO) == -1) - { - Com_Printf( "SDL_Init( SDL_INIT_VIDEO ) FAILED (%s)\n", SDL_GetError()); + if (SDL_Init(SDL_INIT_VIDEO) == -1) { + Com_Printf("SDL_Init( SDL_INIT_VIDEO ) FAILED (%s)\n", SDL_GetError()); return qfalse; } driverName = SDL_GetCurrentVideoDriver(); - if (!driverName) - { - Com_Error( ERR_FATAL, "No video driver initialized" ); + if (!driverName) { + Com_Error(ERR_FATAL, "No video driver initialized"); return qfalse; } - Com_Printf( "SDL using driver \"%s\"\n", driverName ); - Cvar_Set( "r_sdlDriver", driverName ); + Com_Printf("SDL using driver \"%s\"\n", driverName); + Cvar_Set("r_sdlDriver", driverName); } - if (SDL_GetNumVideoDisplays() <= 0) - { - Com_Error( ERR_FATAL, "SDL_GetNumVideoDisplays() FAILED (%s)", SDL_GetError() ); + if (SDL_GetNumVideoDisplays() <= 0) { + Com_Error(ERR_FATAL, "SDL_GetNumVideoDisplays() FAILED (%s)", SDL_GetError()); } - if (fullscreen && Cvar_VariableIntegerValue( "in_nograb" ) ) - { - Com_Printf( "Fullscreen not allowed with in_nograb 1\n"); - Cvar_Set( "r_fullscreen", "0" ); + if (fullscreen && Cvar_VariableIntegerValue("in_nograb")) { + Com_Printf("Fullscreen not allowed with in_nograb 1\n"); + Cvar_Set("r_fullscreen", "0"); r_fullscreen->modified = qfalse; fullscreen = qfalse; } err = GLimp_SetMode(glConfig, windowDesc, CLIENT_WINDOW_TITLE, mode, fullscreen, noborder); - switch ( err ) - { - case RSERR_INVALID_FULLSCREEN: - Com_Printf( "...WARNING: fullscreen unavailable in this mode\n" ); - return qfalse; - case RSERR_INVALID_MODE: - Com_Printf( "...WARNING: could not set the given mode (%d)\n", mode ); - return qfalse; - case RSERR_UNKNOWN: - Com_Printf( "...ERROR: no display modes could be found.\n" ); - return qfalse; - default: - break; + switch (err) { + case RSERR_INVALID_FULLSCREEN: + Com_Printf("...WARNING: fullscreen unavailable in this mode\n"); + return qfalse; + case RSERR_INVALID_MODE: + Com_Printf("...WARNING: could not set the given mode (%d)\n", mode); + return qfalse; + case RSERR_UNKNOWN: + Com_Printf("...ERROR: no display modes could be found.\n"); + return qfalse; + default: + break; } return qtrue; } -window_t WIN_Init( const windowDesc_t *windowDesc, glconfig_t *glConfig ) -{ +window_t WIN_Init(const windowDesc_t *windowDesc, glconfig_t *glConfig) { Cmd_AddCommand("modelist", R_ModeList_f); Cmd_AddCommand("minimize", GLimp_Minimize); - r_sdlDriver = Cvar_Get( "r_sdlDriver", "", CVAR_ROM ); - r_allowSoftwareGL = Cvar_Get( "r_allowSoftwareGL", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); + r_sdlDriver = Cvar_Get("r_sdlDriver", "", CVAR_ROM); + r_allowSoftwareGL = Cvar_Get("r_allowSoftwareGL", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); // Window cvars - r_fullscreen = Cvar_Get( "r_fullscreen", "0", CVAR_ARCHIVE|CVAR_LATCH ); - r_noborder = Cvar_Get( "r_noborder", "0", CVAR_ARCHIVE|CVAR_LATCH ); - r_centerWindow = Cvar_Get( "r_centerWindow", "0", CVAR_ARCHIVE|CVAR_LATCH ); - r_customwidth = Cvar_Get( "r_customwidth", "1600", CVAR_ARCHIVE|CVAR_LATCH ); - r_customheight = Cvar_Get( "r_customheight", "1024", CVAR_ARCHIVE|CVAR_LATCH ); - r_swapInterval = Cvar_Get( "r_swapInterval", "0", CVAR_ARCHIVE_ND ); - r_stereo = Cvar_Get( "r_stereo", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_mode = Cvar_Get( "r_mode", "4", CVAR_ARCHIVE|CVAR_LATCH ); - r_displayRefresh = Cvar_Get( "r_displayRefresh", "0", CVAR_LATCH ); - Cvar_CheckRange( r_displayRefresh, 0, 240, qtrue ); + r_fullscreen = Cvar_Get("r_fullscreen", "0", CVAR_ARCHIVE | CVAR_LATCH); + r_noborder = Cvar_Get("r_noborder", "0", CVAR_ARCHIVE | CVAR_LATCH); + r_centerWindow = Cvar_Get("r_centerWindow", "0", CVAR_ARCHIVE | CVAR_LATCH); + r_customwidth = Cvar_Get("r_customwidth", "1600", CVAR_ARCHIVE | CVAR_LATCH); + r_customheight = Cvar_Get("r_customheight", "1024", CVAR_ARCHIVE | CVAR_LATCH); + r_swapInterval = Cvar_Get("r_swapInterval", "0", CVAR_ARCHIVE_ND); + r_stereo = Cvar_Get("r_stereo", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_mode = Cvar_Get("r_mode", "4", CVAR_ARCHIVE | CVAR_LATCH); + r_displayRefresh = Cvar_Get("r_displayRefresh", "0", CVAR_LATCH); + Cvar_CheckRange(r_displayRefresh, 0, 240, qtrue); // Window render surface cvars - r_stencilbits = Cvar_Get( "r_stencilbits", "8", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_depthbits = Cvar_Get( "r_depthbits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_colorbits = Cvar_Get( "r_colorbits", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_ignorehwgamma = Cvar_Get( "r_ignorehwgamma", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - r_ext_multisample = Cvar_Get( "r_ext_multisample", "0", CVAR_ARCHIVE_ND|CVAR_LATCH ); - Cvar_Get( "r_availableModes", "", CVAR_ROM ); + r_stencilbits = Cvar_Get("r_stencilbits", "8", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_depthbits = Cvar_Get("r_depthbits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_colorbits = Cvar_Get("r_colorbits", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ignorehwgamma = Cvar_Get("r_ignorehwgamma", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + r_ext_multisample = Cvar_Get("r_ext_multisample", "0", CVAR_ARCHIVE_ND | CVAR_LATCH); + Cvar_Get("r_availableModes", "", CVAR_ROM); // Create the window and set up the context - if(!GLimp_StartDriverAndSetMode( glConfig, windowDesc, r_mode->integer, - (qboolean)r_fullscreen->integer, (qboolean)r_noborder->integer )) - { - if( r_mode->integer != R_MODE_FALLBACK ) - { - Com_Printf( "Setting r_mode %d failed, falling back on r_mode %d\n", r_mode->integer, R_MODE_FALLBACK ); + if (!GLimp_StartDriverAndSetMode(glConfig, windowDesc, r_mode->integer, (qboolean)r_fullscreen->integer, (qboolean)r_noborder->integer)) { + if (r_mode->integer != R_MODE_FALLBACK) { + Com_Printf("Setting r_mode %d failed, falling back on r_mode %d\n", r_mode->integer, R_MODE_FALLBACK); - if (!GLimp_StartDriverAndSetMode( glConfig, windowDesc, R_MODE_FALLBACK, qfalse, qfalse )) - { + if (!GLimp_StartDriverAndSetMode(glConfig, windowDesc, R_MODE_FALLBACK, qfalse, qfalse)) { // Nothing worked, give up - Com_Error( ERR_FATAL, "GLimp_Init() - could not load OpenGL subsystem" ); + Com_Error(ERR_FATAL, "GLimp_Init() - could not load OpenGL subsystem"); } } } - glConfig->deviceSupportsGamma = - (qboolean)(!r_ignorehwgamma->integer && SDL_SetWindowBrightness( screen, 1.0f ) >= 0); + glConfig->deviceSupportsGamma = (qboolean)(!r_ignorehwgamma->integer && SDL_SetWindowBrightness(screen, 1.0f) >= 0); // This depends on SDL_INIT_VIDEO, hence having it here - IN_Init( screen ); + IN_Init(screen); // window_t is only really useful for Windows if the renderer wants to create a D3D context. window_t window = {}; @@ -782,15 +696,14 @@ window_t WIN_Init( const windowDesc_t *windowDesc, glconfig_t *glConfig ) SDL_SysWMinfo info; SDL_VERSION(&info.version); - if ( SDL_GetWindowWMInfo(screen, &info) ) - { - switch(info.subsystem) { - case SDL_SYSWM_WINDOWS: - window.handle = info.info.win.window; - break; + if (SDL_GetWindowWMInfo(screen, &info)) { + switch (info.subsystem) { + case SDL_SYSWM_WINDOWS: + window.handle = info.info.win.window; + break; - default: - break; + default: + break; } } #endif @@ -803,54 +716,44 @@ window_t WIN_Init( const windowDesc_t *windowDesc, glconfig_t *glConfig ) GLimp_Shutdown =============== */ -void WIN_Shutdown( void ) -{ +void WIN_Shutdown(void) { Cmd_RemoveCommand("modelist"); Cmd_RemoveCommand("minimize"); IN_Shutdown(); - SDL_QuitSubSystem( SDL_INIT_VIDEO ); + SDL_QuitSubSystem(SDL_INIT_VIDEO); screen = NULL; } -void GLimp_EnableLogging( qboolean enable ) -{ -} +void GLimp_EnableLogging(qboolean enable) {} -void GLimp_LogComment( char *comment ) -{ -} +void GLimp_LogComment(char *comment) {} -void WIN_SetGamma( glconfig_t *glConfig, byte red[256], byte green[256], byte blue[256] ) -{ +void WIN_SetGamma(glconfig_t *glConfig, byte red[256], byte green[256], byte blue[256]) { Uint16 table[3][256]; int i, j; - if( !glConfig->deviceSupportsGamma || r_ignorehwgamma->integer > 0 ) + if (!glConfig->deviceSupportsGamma || r_ignorehwgamma->integer > 0) return; - for (i = 0; i < 256; i++) - { - table[0][i] = ( ( ( Uint16 ) red[i] ) << 8 ) | red[i]; - table[1][i] = ( ( ( Uint16 ) green[i] ) << 8 ) | green[i]; - table[2][i] = ( ( ( Uint16 ) blue[i] ) << 8 ) | blue[i]; + for (i = 0; i < 256; i++) { + table[0][i] = (((Uint16)red[i]) << 8) | red[i]; + table[1][i] = (((Uint16)green[i]) << 8) | green[i]; + table[2][i] = (((Uint16)blue[i]) << 8) | blue[i]; } #if defined(_WIN32) // Win2K and newer put this odd restriction on gamma ramps... { - OSVERSIONINFO vinfo; - - vinfo.dwOSVersionInfoSize = sizeof( vinfo ); - GetVersionEx( &vinfo ); - if( vinfo.dwMajorVersion >= 5 && vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) - { - Com_DPrintf( "performing gamma clamp.\n" ); - for( j = 0 ; j < 3 ; j++ ) - { - for( i = 0 ; i < 128 ; i++ ) - { + OSVERSIONINFO vinfo; + + vinfo.dwOSVersionInfoSize = sizeof(vinfo); + GetVersionEx(&vinfo); + if (vinfo.dwMajorVersion >= 5 && vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { + Com_DPrintf("performing gamma clamp.\n"); + for (j = 0; j < 3; j++) { + for (i = 0; i < 128; i++) { table[j][i] = Q_min(table[j][i], (128 + i) << 8); } @@ -861,27 +764,18 @@ void WIN_SetGamma( glconfig_t *glConfig, byte red[256], byte green[256], byte bl #endif // enforce constantly increasing - for (j = 0; j < 3; j++) - { - for (i = 1; i < 256; i++) - { - if (table[j][i] < table[j][i-1]) - table[j][i] = table[j][i-1]; + for (j = 0; j < 3; j++) { + for (i = 1; i < 256; i++) { + if (table[j][i] < table[j][i - 1]) + table[j][i] = table[j][i - 1]; } } - if ( SDL_SetWindowGammaRamp( screen, table[0], table[1], table[2] ) < 0 ) - { - Com_DPrintf( "SDL_SetWindowGammaRamp() failed: %s\n", SDL_GetError() ); + if (SDL_SetWindowGammaRamp(screen, table[0], table[1], table[2]) < 0) { + Com_DPrintf("SDL_SetWindowGammaRamp() failed: %s\n", SDL_GetError()); } } -void *WIN_GL_GetProcAddress( const char *proc ) -{ - return SDL_GL_GetProcAddress( proc ); -} +void *WIN_GL_GetProcAddress(const char *proc) { return SDL_GL_GetProcAddress(proc); } -qboolean WIN_GL_ExtensionSupported( const char *extension ) -{ - return SDL_GL_ExtensionSupported( extension ) == SDL_TRUE ? qtrue : qfalse; -} +qboolean WIN_GL_ExtensionSupported(const char *extension) { return SDL_GL_ExtensionSupported(extension) == SDL_TRUE ? qtrue : qfalse; } diff --git a/shared/sys/con_log.cpp b/shared/sys/con_log.cpp index 0725bd4c8a..14301040df 100644 --- a/shared/sys/con_log.cpp +++ b/shared/sys/con_log.cpp @@ -23,7 +23,6 @@ along with this program; if not, see . #include #include - /* ======================================================================== @@ -33,8 +32,7 @@ CONSOLE LOG */ #define MAX_CONSOLE_LOG_SIZE (65535) -struct ConsoleLog -{ +struct ConsoleLog { // Cicular buffer of characters. Be careful, there is no null terminator. // You're expected to use the console log length to know where the end // of the string is. @@ -49,30 +47,24 @@ struct ConsoleLog static ConsoleLog consoleLog; -void ConsoleLogAppend( const char *string ) -{ - for ( int i = 0; string[i]; i++ ) - { +void ConsoleLogAppend(const char *string) { + for (int i = 0; string[i]; i++) { consoleLog.text[consoleLog.writeHead] = string[i]; consoleLog.writeHead = (consoleLog.writeHead + 1) % MAX_CONSOLE_LOG_SIZE; consoleLog.length++; - if ( consoleLog.length > MAX_CONSOLE_LOG_SIZE ) - { + if (consoleLog.length > MAX_CONSOLE_LOG_SIZE) { consoleLog.length = MAX_CONSOLE_LOG_SIZE; } } } -void ConsoleLogWriteOut( FILE *fp ) -{ - assert( fp ); +void ConsoleLogWriteOut(FILE *fp) { + assert(fp); - if ( consoleLog.length == MAX_CONSOLE_LOG_SIZE && - consoleLog.writeHead != MAX_CONSOLE_LOG_SIZE ) - { - fwrite( consoleLog.text + consoleLog.writeHead, MAX_CONSOLE_LOG_SIZE - consoleLog.writeHead, 1, fp ); + if (consoleLog.length == MAX_CONSOLE_LOG_SIZE && consoleLog.writeHead != MAX_CONSOLE_LOG_SIZE) { + fwrite(consoleLog.text + consoleLog.writeHead, MAX_CONSOLE_LOG_SIZE - consoleLog.writeHead, 1, fp); } - fwrite( consoleLog.text, consoleLog.writeHead, 1, fp ); + fwrite(consoleLog.text, consoleLog.writeHead, 1, fp); } diff --git a/shared/sys/con_passive.cpp b/shared/sys/con_passive.cpp index a5ac6ae1f2..2535ca1f5b 100644 --- a/shared/sys/con_passive.cpp +++ b/shared/sys/con_passive.cpp @@ -29,38 +29,30 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA CON_Shutdown ================== */ -void CON_Shutdown( void ) -{ -} +void CON_Shutdown(void) {} /* ================== CON_Init ================== */ -void CON_Init( void ) -{ -} +void CON_Init(void) {} /* ================== CON_Input ================== */ -char *CON_Input( void ) -{ - return NULL; -} +char *CON_Input(void) { return NULL; } /* ================== CON_Print ================== */ -void CON_Print( const char *msg ) -{ - char cmsg[MAXPRINTMSG] = { 0 }; - Q_strncpyz( cmsg, msg, sizeof( cmsg ) ); - Q_StripColor( cmsg ); - printf( "%s", cmsg ); +void CON_Print(const char *msg) { + char cmsg[MAXPRINTMSG] = {0}; + Q_strncpyz(cmsg, msg, sizeof(cmsg)); + Q_StripColor(cmsg); + printf("%s", cmsg); } diff --git a/shared/sys/con_tty.cpp b/shared/sys/con_tty.cpp index 812a7248d7..9bd28b498d 100644 --- a/shared/sys/con_tty.cpp +++ b/shared/sys/con_tty.cpp @@ -59,7 +59,7 @@ static field_t TTY_con; // This is somewhat of aduplicate of the graphical console history // but it's safer more modular to have our own here #define CON_HISTORY 32 -static field_t ttyEditLines[ CON_HISTORY ]; +static field_t ttyEditLines[CON_HISTORY]; static int hist_current = -1, hist_count = 0; #ifndef DEDICATED @@ -78,10 +78,10 @@ Flush stdin, I suspect some terminals are sending a LOT of shit FIXME relevant? ================== */ -static void CON_FlushIn( void ) -{ +static void CON_FlushIn(void) { char key; - while (read(STDIN_FILENO, &key, 1)!=-1); + while (read(STDIN_FILENO, &key, 1) != -1) + ; } /* @@ -95,8 +95,7 @@ send "\b \b" (FIXME there may be a way to find out if '\b' alone would work though) ================== */ -static void CON_Back( void ) -{ +static void CON_Back(void) { char key; size_t UNUSED_VAR size; @@ -116,20 +115,15 @@ Clear the display of the line currently edited bring cursor back to beginning of line ================== */ -static void CON_Hide( void ) -{ - if( ttycon_on ) - { +static void CON_Hide(void) { + if (ttycon_on) { int i; - if (ttycon_hide) - { + if (ttycon_hide) { ttycon_hide++; return; } - if (TTY_con.cursor>0) - { - for (i=0; i 0) { + for (i = 0; i < TTY_con.cursor; i++) { CON_Back(); } } @@ -149,23 +143,18 @@ Show the current line FIXME need to position the cursor if needed? ================== */ -static void CON_Show( void ) -{ - if( ttycon_on ) - { +static void CON_Show(void) { + if (ttycon_on) { int i; - assert(ttycon_hide>0); + assert(ttycon_hide > 0); ttycon_hide--; - if (ttycon_hide == 0) - { + if (ttycon_hide == 0) { size_t UNUSED_VAR size; size = write(STDOUT_FILENO, TTY_CONSOLE_PROMPT, strlen(TTY_CONSOLE_PROMPT)); - if (TTY_con.cursor) - { - for (i=0; i= -1); assert(hist_current <= hist_count); // make some room - for (i=CON_HISTORY-1; i>0; i--) - { - ttyEditLines[i] = ttyEditLines[i-1]; + for (i = CON_HISTORY - 1; i > 0; i--) { + ttyEditLines[i] = ttyEditLines[i - 1]; } ttyEditLines[0] = *field; - if (hist_count= 0); assert(hist_current >= -1); assert(hist_current <= hist_count); hist_prev = hist_current + 1; - if (hist_prev >= hist_count) - { + if (hist_prev >= hist_count) { return NULL; } hist_current++; @@ -247,18 +229,15 @@ field_t *Hist_Prev( void ) Hist_Next ================== */ -field_t *Hist_Next( void ) -{ +field_t *Hist_Next(void) { assert(hist_count <= CON_HISTORY); assert(hist_count >= 0); assert(hist_current >= -1); assert(hist_current <= hist_count); - if (hist_current >= 0) - { + if (hist_current >= 0) { hist_current--; } - if (hist_current == -1) - { + if (hist_current == -1) { return NULL; } return &(ttyEditLines[hist_current]); @@ -272,10 +251,7 @@ set attributes if user did CTRL+Z and then does fg again. ================== */ -void CON_SigCont(int signum) -{ - CON_Init(); -} +void CON_SigCont(int signum) { CON_Init(); } /* ================== @@ -284,8 +260,7 @@ CON_Init Initialize the console input (tty mode if possible) ================== */ -void CON_Init( void ) -{ +void CON_Init(void) { struct termios tc; // If the process is backgrounded (running non interactively) @@ -297,10 +272,9 @@ void CON_Init( void ) signal(SIGCONT, CON_SigCont); // Make stdin reads non-blocking - fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK ); + fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK); - if (!stdinIsATTY) - { + if (!stdinIsATTY) { Com_Printf("tty console mode disabled\n"); ttycon_on = qfalse; stdin_active = qtrue; @@ -308,7 +282,7 @@ void CON_Init( void ) } Field_Clear(&TTY_con); - tcgetattr (STDIN_FILENO, &TTY_tc); + tcgetattr(STDIN_FILENO, &TTY_tc); TTY_erase = TTY_tc.c_cc[VERASE]; TTY_eof = TTY_tc.c_cc[VEOF]; tc = TTY_tc; @@ -330,7 +304,7 @@ void CON_Init( void ) tc.c_iflag &= ~(ISTRIP | INPCK); tc.c_cc[VMIN] = 1; tc.c_cc[VTIME] = 0; - tcsetattr (STDIN_FILENO, TCSADRAIN, &tc); + tcsetattr(STDIN_FILENO, TCSADRAIN, &tc); ttycon_on = qtrue; ttycon_hide = 1; // Mark as hidden, so prompt is shown in CON_Show CON_Show(); @@ -341,8 +315,7 @@ void CON_Init( void ) CON_Input ================== */ -char *CON_Input( void ) -{ +char *CON_Input(void) { // we use this when sending back commands static char text[MAX_EDIT_LINE]; int avail; @@ -350,18 +323,14 @@ char *CON_Input( void ) field_t *history; size_t UNUSED_VAR size; - if(ttycon_on) - { + if (ttycon_on) { avail = read(STDIN_FILENO, &key, 1); - if (avail != -1) - { + if (avail != -1) { // we have something // backspace? // NOTE TTimo testing a lot of values .. seems it's the only way to get it to work everywhere - if ((key == TTY_erase) || (key == 127) || (key == 8)) - { - if (TTY_con.cursor > 0) - { + if ((key == TTY_erase) || (key == 127) || (key == 8)) { + if (TTY_con.cursor > 0) { TTY_con.cursor--; TTY_con.buffer[TTY_con.cursor] = '\0'; CON_Back(); @@ -369,10 +338,8 @@ char *CON_Input( void ) return NULL; } // check if this is a control char - if ((key) && (key) < ' ') - { - if (key == '\n') - { + if ((key) && (key) < ' ') { + if (key == '\n') { #ifndef DEDICATED if (TTY_con.buffer[0] == '/' || TTY_con.buffer[0] == '\\') { Q_strncpyz(text, TTY_con.buffer + 1, sizeof(text)); @@ -399,53 +366,45 @@ char *CON_Input( void ) #endif return text; } - if (key == '\t') - { + if (key == '\t') { CON_Hide(); - Field_AutoComplete( &TTY_con ); + Field_AutoComplete(&TTY_con); CON_Show(); return NULL; } avail = read(STDIN_FILENO, &key, 1); - if (avail != -1) - { + if (avail != -1) { // VT 100 keys - if (key == '[' || key == 'O') - { + if (key == '[' || key == 'O') { avail = read(STDIN_FILENO, &key, 1); - if (avail != -1) - { - switch (key) - { - case 'A': - history = Hist_Prev(); - if (history) - { - CON_Hide(); - TTY_con = *history; - CON_Show(); - } - CON_FlushIn(); - return NULL; - break; - case 'B': - history = Hist_Next(); + if (avail != -1) { + switch (key) { + case 'A': + history = Hist_Prev(); + if (history) { CON_Hide(); - if (history) - { - TTY_con = *history; - } else - { - Field_Clear(&TTY_con); - } + TTY_con = *history; CON_Show(); - CON_FlushIn(); - return NULL; - break; - case 'C': - return NULL; - case 'D': - return NULL; + } + CON_FlushIn(); + return NULL; + break; + case 'B': + history = Hist_Next(); + CON_Hide(); + if (history) { + TTY_con = *history; + } else { + Field_Clear(&TTY_con); + } + CON_Show(); + CON_FlushIn(); + return NULL; + break; + case 'C': + return NULL; + case 'D': + return NULL; } } } @@ -464,30 +423,27 @@ char *CON_Input( void ) } return NULL; - } - else if (stdin_active) - { - int len; - fd_set fdset; + } else if (stdin_active) { + int len; + fd_set fdset; struct timeval timeout; FD_ZERO(&fdset); FD_SET(STDIN_FILENO, &fdset); // stdin timeout.tv_sec = 0; timeout.tv_usec = 0; - if(select (STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(STDIN_FILENO, &fdset)) + if (select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(STDIN_FILENO, &fdset)) return NULL; len = read(STDIN_FILENO, text, sizeof(text)); - if (len == 0) - { // eof! + if (len == 0) { // eof! stdin_active = qfalse; return NULL; } if (len < 1) return NULL; - text[len-1] = 0; // rip off the /n and terminate + text[len - 1] = 0; // rip off the /n and terminate return text; } @@ -499,17 +455,16 @@ char *CON_Input( void ) CON_Print ================== */ -void CON_Print( const char *msg ) -{ +void CON_Print(const char *msg) { if (!msg[0]) return; - CON_Hide( ); + CON_Hide(); - if( com_ansiColor && com_ansiColor->integer ) - Sys_AnsiColorPrint( msg ); + if (com_ansiColor && com_ansiColor->integer) + Sys_AnsiColorPrint(msg); else - fputs( msg, stderr ); + fputs(msg, stderr); if (!ttycon_on) { // CON_Hide didn't do anything. @@ -526,9 +481,7 @@ void CON_Print( const char *msg ) CON_Show(); ttycon_show_overdue--; } - } - else - { + } else { // Defer calling CON_Show ttycon_show_overdue++; } diff --git a/shared/sys/con_win32.cpp b/shared/sys/con_win32.cpp index 30261a2a81..df9117e176 100644 --- a/shared/sys/con_win32.cpp +++ b/shared/sys/con_win32.cpp @@ -36,13 +36,13 @@ static DWORD qconsole_orig_mode; static CONSOLE_CURSOR_INFO qconsole_orig_cursorinfo; // cmd history -static char qconsole_history[ QCONSOLE_HISTORY ][ MAX_EDIT_LINE ]; +static char qconsole_history[QCONSOLE_HISTORY][MAX_EDIT_LINE]; static int qconsole_history_pos = -1; static int qconsole_history_lines = 0; static int qconsole_history_oldest = 0; // current edit buffer -static char qconsole_line[ MAX_EDIT_LINE ]; +static char qconsole_line[MAX_EDIT_LINE]; static int qconsole_linelen = 0; static bool qconsole_drawinput = true; static int qconsole_cursor; @@ -57,23 +57,18 @@ CON_ColorCharToAttrib Convert Quake color character to Windows text attrib ================== */ -static WORD CON_ColorCharToAttrib( char color ) { +static WORD CON_ColorCharToAttrib(char color) { WORD attrib; - if ( color == COLOR_WHITE ) - { + if (color == COLOR_WHITE) { // use console's foreground and background colors attrib = qconsole_attrib; - } - else - { - float *rgba = g_color_table[ ColorIndex( color ) ]; + } else { + float *rgba = g_color_table[ColorIndex(color)]; // set foreground color - attrib = ( rgba[0] >= 0.5 ? FOREGROUND_RED : 0 ) | - ( rgba[1] >= 0.5 ? FOREGROUND_GREEN : 0 ) | - ( rgba[2] >= 0.5 ? FOREGROUND_BLUE : 0 ) | - ( rgba[3] >= 0.5 ? FOREGROUND_INTENSITY : 0 ); + attrib = (rgba[0] >= 0.5 ? FOREGROUND_RED : 0) | (rgba[1] >= 0.5 ? FOREGROUND_GREEN : 0) | (rgba[2] >= 0.5 ? FOREGROUND_BLUE : 0) | + (rgba[3] >= 0.5 ? FOREGROUND_INTENSITY : 0); // use console's background color attrib |= qconsole_backgroundAttrib; @@ -94,9 +89,8 @@ Sys_SigHandler() with those numbers should be safe for generating unique shutdown messages. ================== */ -static BOOL WINAPI CON_CtrlHandler( DWORD sig ) -{ - Sys_SigHandler( sig ); +static BOOL WINAPI CON_CtrlHandler(DWORD sig) { + Sys_SigHandler(sig); return TRUE; } @@ -105,15 +99,13 @@ static BOOL WINAPI CON_CtrlHandler( DWORD sig ) CON_HistAdd ================== */ -static void CON_HistAdd( void ) -{ - Q_strncpyz( qconsole_history[ qconsole_history_oldest ], qconsole_line, - sizeof( qconsole_history[ qconsole_history_oldest ] ) ); +static void CON_HistAdd(void) { + Q_strncpyz(qconsole_history[qconsole_history_oldest], qconsole_line, sizeof(qconsole_history[qconsole_history_oldest])); - if( qconsole_history_lines < QCONSOLE_HISTORY ) + if (qconsole_history_lines < QCONSOLE_HISTORY) qconsole_history_lines++; - if( qconsole_history_oldest >= QCONSOLE_HISTORY - 1 ) + if (qconsole_history_oldest >= QCONSOLE_HISTORY - 1) qconsole_history_oldest = 0; else qconsole_history_oldest++; @@ -126,19 +118,18 @@ static void CON_HistAdd( void ) CON_HistPrev ================== */ -static void CON_HistPrev( void ) -{ +static void CON_HistPrev(void) { int pos; - pos = ( qconsole_history_pos < 1 ) ? ( QCONSOLE_HISTORY - 1 ) : ( qconsole_history_pos - 1 ); + pos = (qconsole_history_pos < 1) ? (QCONSOLE_HISTORY - 1) : (qconsole_history_pos - 1); // don' t allow looping through history - if( pos == qconsole_history_oldest || pos >= qconsole_history_lines ) + if (pos == qconsole_history_oldest || pos >= qconsole_history_lines) return; qconsole_history_pos = pos; - Q_strncpyz( qconsole_line, qconsole_history[ qconsole_history_pos ], sizeof( qconsole_line ) ); - qconsole_linelen = strlen( qconsole_line ); + Q_strncpyz(qconsole_line, qconsole_history[qconsole_history_pos], sizeof(qconsole_line)); + qconsole_linelen = strlen(qconsole_line); qconsole_cursor = qconsole_linelen; } @@ -147,53 +138,49 @@ static void CON_HistPrev( void ) CON_HistNext ================== */ -static void CON_HistNext( void ) -{ +static void CON_HistNext(void) { int pos; // don' t allow looping through history - if( qconsole_history_pos == qconsole_history_oldest ) + if (qconsole_history_pos == qconsole_history_oldest) return; - pos = ( qconsole_history_pos >= QCONSOLE_HISTORY - 1 ) ? 0 : ( qconsole_history_pos + 1 ); + pos = (qconsole_history_pos >= QCONSOLE_HISTORY - 1) ? 0 : (qconsole_history_pos + 1); // clear the edit buffer if they try to advance to a future command - if( pos == qconsole_history_oldest ) - { + if (pos == qconsole_history_oldest) { qconsole_history_pos = pos; - qconsole_line[ 0 ] = '\0'; + qconsole_line[0] = '\0'; qconsole_linelen = 0; qconsole_cursor = qconsole_linelen; return; } qconsole_history_pos = pos; - Q_strncpyz( qconsole_line, qconsole_history[ qconsole_history_pos ], sizeof( qconsole_line ) ); - qconsole_linelen = strlen( qconsole_line ); + Q_strncpyz(qconsole_line, qconsole_history[qconsole_history_pos], sizeof(qconsole_line)); + qconsole_linelen = strlen(qconsole_line); qconsole_cursor = qconsole_linelen; } - /* ================== CON_Show ================== */ -static void CON_Show( void ) -{ +static void CON_Show(void) { CONSOLE_SCREEN_BUFFER_INFO binfo; - COORD writeSize = { MAX_EDIT_LINE, 1 }; - COORD writePos = { 0, 0 }; - SMALL_RECT writeArea = { 0, 0, 0, 0 }; + COORD writeSize = {MAX_EDIT_LINE, 1}; + COORD writePos = {0, 0}; + SMALL_RECT writeArea = {0, 0, 0, 0}; COORD cursorPos; int i; - CHAR_INFO line[ MAX_EDIT_LINE ]; + CHAR_INFO line[MAX_EDIT_LINE]; WORD attrib; - GetConsoleScreenBufferInfo( qconsole_hout, &binfo ); + GetConsoleScreenBufferInfo(qconsole_hout, &binfo); // if we're in the middle of printf, don't bother writing the buffer - if( !qconsole_drawinput ) + if (!qconsole_drawinput) return; writeArea.Left = 0; @@ -202,45 +189,32 @@ static void CON_Show( void ) writeArea.Right = MAX_EDIT_LINE; // set color to white - attrib = CON_ColorCharToAttrib( COLOR_WHITE ); + attrib = CON_ColorCharToAttrib(COLOR_WHITE); // build a space-padded CHAR_INFO array - for( i = 0; i < MAX_EDIT_LINE; i++ ) - { - if( i < qconsole_linelen ) - { - if( i + 1 < qconsole_linelen && Q_IsColorString( qconsole_line + i ) ) - attrib = CON_ColorCharToAttrib( *( qconsole_line + i + 1 ) ); - - line[ i ].Char.AsciiChar = qconsole_line[ i ]; - } - else - line[ i ].Char.AsciiChar = ' '; + for (i = 0; i < MAX_EDIT_LINE; i++) { + if (i < qconsole_linelen) { + if (i + 1 < qconsole_linelen && Q_IsColorString(qconsole_line + i)) + attrib = CON_ColorCharToAttrib(*(qconsole_line + i + 1)); - line[ i ].Attributes = attrib; - } + line[i].Char.AsciiChar = qconsole_line[i]; + } else + line[i].Char.AsciiChar = ' '; - if( qconsole_linelen > binfo.srWindow.Right ) - { - WriteConsoleOutput( qconsole_hout, - line + (qconsole_linelen - binfo.srWindow.Right ), - writeSize, writePos, &writeArea ); + line[i].Attributes = attrib; } - else - { - WriteConsoleOutput( qconsole_hout, line, writeSize, - writePos, &writeArea ); + + if (qconsole_linelen > binfo.srWindow.Right) { + WriteConsoleOutput(qconsole_hout, line + (qconsole_linelen - binfo.srWindow.Right), writeSize, writePos, &writeArea); + } else { + WriteConsoleOutput(qconsole_hout, line, writeSize, writePos, &writeArea); } // set curor position cursorPos.Y = binfo.dwCursorPosition.Y; - cursorPos.X = qconsole_cursor < qconsole_linelen - ? qconsole_cursor - : qconsole_linelen > binfo.srWindow.Right - ? binfo.srWindow.Right - : qconsole_linelen; + cursorPos.X = qconsole_cursor < qconsole_linelen ? qconsole_cursor : qconsole_linelen > binfo.srWindow.Right ? binfo.srWindow.Right : qconsole_linelen; - SetConsoleCursorPosition( qconsole_hout, cursorPos ); + SetConsoleCursorPosition(qconsole_hout, cursorPos); } /* @@ -248,33 +222,30 @@ static void CON_Show( void ) CON_Hide ================== */ -static void CON_Hide( void ) -{ +static void CON_Hide(void) { int realLen; realLen = qconsole_linelen; // remove input line from console output buffer qconsole_linelen = 0; - CON_Show( ); + CON_Show(); qconsole_linelen = realLen; } - /* ================== CON_Shutdown ================== */ -void CON_Shutdown( void ) -{ - CON_Hide( ); - SetConsoleMode( qconsole_hin, qconsole_orig_mode ); - SetConsoleCursorInfo( qconsole_hout, &qconsole_orig_cursorinfo ); - SetConsoleTextAttribute( qconsole_hout, qconsole_attrib ); - CloseHandle( qconsole_hout ); - CloseHandle( qconsole_hin ); +void CON_Shutdown(void) { + CON_Hide(); + SetConsoleMode(qconsole_hin, qconsole_orig_mode); + SetConsoleCursorInfo(qconsole_hout, &qconsole_orig_cursorinfo); + SetConsoleTextAttribute(qconsole_hout, qconsole_attrib); + CloseHandle(qconsole_hout); + CloseHandle(qconsole_hin); } /* @@ -282,41 +253,40 @@ void CON_Shutdown( void ) CON_Init ================== */ -void CON_Init( void ) -{ +void CON_Init(void) { CONSOLE_SCREEN_BUFFER_INFO info; int i; // handle Ctrl-C or other console termination - SetConsoleCtrlHandler( CON_CtrlHandler, TRUE ); + SetConsoleCtrlHandler(CON_CtrlHandler, TRUE); - qconsole_hin = GetStdHandle( STD_INPUT_HANDLE ); - if( qconsole_hin == INVALID_HANDLE_VALUE ) + qconsole_hin = GetStdHandle(STD_INPUT_HANDLE); + if (qconsole_hin == INVALID_HANDLE_VALUE) return; - qconsole_hout = GetStdHandle( STD_OUTPUT_HANDLE ); - if( qconsole_hout == INVALID_HANDLE_VALUE ) + qconsole_hout = GetStdHandle(STD_OUTPUT_HANDLE); + if (qconsole_hout == INVALID_HANDLE_VALUE) return; - GetConsoleMode( qconsole_hin, &qconsole_orig_mode ); + GetConsoleMode(qconsole_hin, &qconsole_orig_mode); // allow mouse wheel scrolling - SetConsoleMode( qconsole_hin, qconsole_orig_mode & ~ENABLE_MOUSE_INPUT ); + SetConsoleMode(qconsole_hin, qconsole_orig_mode & ~ENABLE_MOUSE_INPUT); - FlushConsoleInputBuffer( qconsole_hin ); + FlushConsoleInputBuffer(qconsole_hin); - GetConsoleScreenBufferInfo( qconsole_hout, &info ); + GetConsoleScreenBufferInfo(qconsole_hout, &info); qconsole_attrib = info.wAttributes; - qconsole_backgroundAttrib = qconsole_attrib & (BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_RED|BACKGROUND_INTENSITY); + qconsole_backgroundAttrib = qconsole_attrib & (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY); SetConsoleTitle(CLIENT_WINDOW_TITLE " Dedicated Server Console"); // initialize history - for( i = 0; i < QCONSOLE_HISTORY; i++ ) - qconsole_history[ i ][ 0 ] = '\0'; + for (i = 0; i < QCONSOLE_HISTORY; i++) + qconsole_history[i][0] = '\0'; // set text color to white - SetConsoleTextAttribute( qconsole_hout, CON_ColorCharToAttrib( COLOR_WHITE ) ); + SetConsoleTextAttribute(qconsole_hout, CON_ColorCharToAttrib(COLOR_WHITE)); } /* @@ -324,151 +294,131 @@ void CON_Init( void ) CON_Input ================== */ -char *CON_Input( void ) -{ - INPUT_RECORD buff[ MAX_EDIT_LINE ]; +char *CON_Input(void) { + INPUT_RECORD buff[MAX_EDIT_LINE]; DWORD count = 0, events = 0; WORD key = 0; int i; int newlinepos = -1; - if( !GetNumberOfConsoleInputEvents( qconsole_hin, &events ) ) + if (!GetNumberOfConsoleInputEvents(qconsole_hin, &events)) return NULL; - if( events < 1 ) + if (events < 1) return NULL; // if we have overflowed, start dropping oldest input events - if( events >= MAX_EDIT_LINE ) - { - ReadConsoleInput( qconsole_hin, buff, 1, &events ); + if (events >= MAX_EDIT_LINE) { + ReadConsoleInput(qconsole_hin, buff, 1, &events); return NULL; } - if( !ReadConsoleInput( qconsole_hin, buff, events, &count ) ) + if (!ReadConsoleInput(qconsole_hin, buff, events, &count)) return NULL; - FlushConsoleInputBuffer( qconsole_hin ); + FlushConsoleInputBuffer(qconsole_hin); - for( i = 0; i < count; i++ ) - { - if( buff[ i ].EventType != KEY_EVENT ) + for (i = 0; i < count; i++) { + if (buff[i].EventType != KEY_EVENT) continue; - if( !buff[ i ].Event.KeyEvent.bKeyDown ) + if (!buff[i].Event.KeyEvent.bKeyDown) continue; - key = buff[ i ].Event.KeyEvent.wVirtualKeyCode; + key = buff[i].Event.KeyEvent.wVirtualKeyCode; bool keyHandled = true; - switch ( key ) - { - case VK_RETURN: - newlinepos = i; - qconsole_cursor = 0; - break; - - case VK_UP: - CON_HistPrev(); - break; - - case VK_DOWN: - CON_HistNext(); - break; + switch (key) { + case VK_RETURN: + newlinepos = i; + qconsole_cursor = 0; + break; - case VK_LEFT: - qconsole_cursor--; - if ( qconsole_cursor < 0 ) - { - qconsole_cursor = 0; - } - break; + case VK_UP: + CON_HistPrev(); + break; - case VK_RIGHT: - qconsole_cursor++; - if ( qconsole_cursor > qconsole_linelen ) - { - qconsole_cursor = qconsole_linelen; - } - break; + case VK_DOWN: + CON_HistNext(); + break; - case VK_HOME: + case VK_LEFT: + qconsole_cursor--; + if (qconsole_cursor < 0) { qconsole_cursor = 0; - break; + } + break; - case VK_END: + case VK_RIGHT: + qconsole_cursor++; + if (qconsole_cursor > qconsole_linelen) { qconsole_cursor = qconsole_linelen; - break; + } + break; - case VK_TAB: - { - field_t f; + case VK_HOME: + qconsole_cursor = 0; + break; - Q_strncpyz( f.buffer, qconsole_line, sizeof( f.buffer ) ); - Field_AutoComplete( &f ); - Q_strncpyz( qconsole_line, f.buffer, sizeof( qconsole_line ) ); - qconsole_linelen = strlen( qconsole_line ); - qconsole_cursor = qconsole_linelen; + case VK_END: + qconsole_cursor = qconsole_linelen; + break; - break; - } + case VK_TAB: { + field_t f; - default: - keyHandled = false; - break; + Q_strncpyz(f.buffer, qconsole_line, sizeof(f.buffer)); + Field_AutoComplete(&f); + Q_strncpyz(qconsole_line, f.buffer, sizeof(qconsole_line)); + qconsole_linelen = strlen(qconsole_line); + qconsole_cursor = qconsole_linelen; + + break; + } + + default: + keyHandled = false; + break; } - if ( keyHandled ) - { + if (keyHandled) { break; } - if( qconsole_linelen < sizeof( qconsole_line ) - 1 ) - { - char c = buff[ i ].Event.KeyEvent.uChar.AsciiChar; - - if( key == VK_BACK ) - { - if ( qconsole_cursor > 0 ) - { - int newlen = ( qconsole_linelen > 0 ) ? qconsole_linelen - 1 : 0; - if ( qconsole_cursor < qconsole_linelen ) - { - memmove( qconsole_line + qconsole_cursor - 1, - qconsole_line + qconsole_cursor, - qconsole_linelen - qconsole_cursor ); + if (qconsole_linelen < sizeof(qconsole_line) - 1) { + char c = buff[i].Event.KeyEvent.uChar.AsciiChar; + + if (key == VK_BACK) { + if (qconsole_cursor > 0) { + int newlen = (qconsole_linelen > 0) ? qconsole_linelen - 1 : 0; + if (qconsole_cursor < qconsole_linelen) { + memmove(qconsole_line + qconsole_cursor - 1, qconsole_line + qconsole_cursor, qconsole_linelen - qconsole_cursor); } - qconsole_line[ newlen ] = '\0'; + qconsole_line[newlen] = '\0'; qconsole_linelen = newlen; qconsole_cursor--; } - } - else if( c ) - { - if ( qconsole_linelen > qconsole_cursor ) - { - memmove( qconsole_line + qconsole_cursor + 1, - qconsole_line + qconsole_cursor, - qconsole_linelen - qconsole_cursor ); + } else if (c) { + if (qconsole_linelen > qconsole_cursor) { + memmove(qconsole_line + qconsole_cursor + 1, qconsole_line + qconsole_cursor, qconsole_linelen - qconsole_cursor); } - qconsole_line[ qconsole_cursor++ ] = c; + qconsole_line[qconsole_cursor++] = c; qconsole_linelen++; - qconsole_line[ qconsole_linelen ] = '\0'; + qconsole_line[qconsole_linelen] = '\0'; } } } - if( newlinepos < 0) { + if (newlinepos < 0) { CON_Show(); return NULL; } - if( !qconsole_linelen ) - { + if (!qconsole_linelen) { CON_Show(); - Com_Printf( "\n" ); + Com_Printf("\n"); return NULL; } @@ -476,7 +426,7 @@ char *CON_Input( void ) CON_Show(); CON_HistAdd(); - Com_Printf( "%s\n", qconsole_line ); + Com_Printf("%s\n", qconsole_line); return qconsole_line; } @@ -488,55 +438,45 @@ CON_WindowsColorPrint Set text colors based on Q3 color codes ================= */ -void CON_WindowsColorPrint( const char *msg ) -{ - static char buffer[ MAXPRINTMSG ]; - int length = 0; +void CON_WindowsColorPrint(const char *msg) { + static char buffer[MAXPRINTMSG]; + int length = 0; - while( *msg ) - { - qconsole_drawinput = ( *msg == '\n' ); + while (*msg) { + qconsole_drawinput = (*msg == '\n'); - if( Q_IsColorString( msg ) || *msg == '\n' ) - { + if (Q_IsColorString(msg) || *msg == '\n') { // First empty the buffer - if( length > 0 ) - { - buffer[ length ] = '\0'; - fputs( buffer, stderr ); + if (length > 0) { + buffer[length] = '\0'; + fputs(buffer, stderr); length = 0; } - if( *msg == '\n' ) - { + if (*msg == '\n') { // Reset color and then add the newline - SetConsoleTextAttribute( qconsole_hout, CON_ColorCharToAttrib( COLOR_WHITE ) ); - fputs( "\n", stderr ); + SetConsoleTextAttribute(qconsole_hout, CON_ColorCharToAttrib(COLOR_WHITE)); + fputs("\n", stderr); msg++; - } - else - { + } else { // Set the color - SetConsoleTextAttribute( qconsole_hout, CON_ColorCharToAttrib( *( msg + 1 ) ) ); + SetConsoleTextAttribute(qconsole_hout, CON_ColorCharToAttrib(*(msg + 1))); msg += 2; } - } - else - { - if( length >= MAXPRINTMSG - 1 ) + } else { + if (length >= MAXPRINTMSG - 1) break; - buffer[ length ] = *msg; + buffer[length] = *msg; length++; msg++; } } // Empty anything still left in the buffer - if( length > 0 ) - { - buffer[ length ] = '\0'; - fputs( buffer, stderr ); + if (length > 0) { + buffer[length] = '\0'; + fputs(buffer, stderr); } } @@ -545,11 +485,10 @@ void CON_WindowsColorPrint( const char *msg ) CON_Print ================== */ -void CON_Print( const char *msg ) -{ - CON_Hide( ); +void CON_Print(const char *msg) { + CON_Hide(); - CON_WindowsColorPrint( msg ); + CON_WindowsColorPrint(msg); - CON_Show( ); + CON_Show(); } diff --git a/shared/sys/snapvector.cpp b/shared/sys/snapvector.cpp index 2c547615b5..64423a7e83 100644 --- a/shared/sys/snapvector.cpp +++ b/shared/sys/snapvector.cpp @@ -23,22 +23,17 @@ along with this program; if not, see . #include #if _MSC_VER -# include -# pragma fenv_access (on) +#include +#pragma fenv_access(on) #else -# include +#include #endif #if _MSC_VER -static inline float roundfloat(float n) -{ - return (n < 0.0f) ? ceilf(n - 0.5f) : floorf(n + 0.5f); -} +static inline float roundfloat(float n) { return (n < 0.0f) ? ceilf(n - 0.5f) : floorf(n + 0.5f); } #endif -extern "C" -void Sys_SnapVector(float *v) -{ +extern "C" void Sys_SnapVector(float *v) { #if _MSC_VER unsigned int oldcontrol; unsigned int newcontrol; diff --git a/shared/sys/sys_event.cpp b/shared/sys/sys_event.cpp index 6bf884f42e..50ac86fd0e 100644 --- a/shared/sys/sys_event.cpp +++ b/shared/sys/sys_event.cpp @@ -34,62 +34,55 @@ EVENT LOOP ======================================================================== */ -#define MAX_QUED_EVENTS 256 -#define MASK_QUED_EVENTS ( MAX_QUED_EVENTS - 1 ) +#define MAX_QUED_EVENTS 256 +#define MASK_QUED_EVENTS (MAX_QUED_EVENTS - 1) -static sysEvent_t eventQue[MAX_QUED_EVENTS] = {}; -static sysEvent_t *lastEvent = nullptr; -static uint32_t eventHead = 0, eventTail = 0; +static sysEvent_t eventQue[MAX_QUED_EVENTS] = {}; +static sysEvent_t *lastEvent = nullptr; +static uint32_t eventHead = 0, eventTail = 0; -static const char *Sys_EventName( sysEventType_t evType ) { +static const char *Sys_EventName(sysEventType_t evType) { - static const char *evNames[SE_MAX] = { - "SE_NONE", - "SE_KEY", - "SE_CHAR", - "SE_MOUSE", - "SE_JOYSTICK_AXIS", - "SE_CONSOLE" - }; + static const char *evNames[SE_MAX] = {"SE_NONE", "SE_KEY", "SE_CHAR", "SE_MOUSE", "SE_JOYSTICK_AXIS", "SE_CONSOLE"}; - if ( evType >= SE_MAX ) { + if (evType >= SE_MAX) { return "SE_UNKNOWN"; } else { return evNames[evType]; } } -sysEvent_t Sys_GetEvent( void ) { - sysEvent_t ev; - char *s; +sysEvent_t Sys_GetEvent(void) { + sysEvent_t ev; + char *s; // return if we have data - if ( eventHead > eventTail ) { + if (eventHead > eventTail) { eventTail++; - return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ]; + return eventQue[(eventTail - 1) & MASK_QUED_EVENTS]; } // check for console commands s = Sys_ConsoleInput(); - if ( s ) { - char *b; - int len; - - len = strlen( s ) + 1; - b = (char *)Z_Malloc( len,TAG_EVENT,qfalse ); - strcpy( b, s ); - Sys_QueEvent( 0, SE_CONSOLE, 0, 0, len, b ); + if (s) { + char *b; + int len; + + len = strlen(s) + 1; + b = (char *)Z_Malloc(len, TAG_EVENT, qfalse); + strcpy(b, s); + Sys_QueEvent(0, SE_CONSOLE, 0, 0, len, b); } // return if we have data - if ( eventHead > eventTail ) { + if (eventHead > eventTail) { eventTail++; - return eventQue[ ( eventTail - 1 ) & MASK_QUED_EVENTS ]; + return eventQue[(eventTail - 1) & MASK_QUED_EVENTS]; } // create an empty event to return - memset( &ev, 0, sizeof( ev ) ); + memset(&ev, 0, sizeof(ev)); ev.evTime = Sys_Milliseconds(); return ev; @@ -104,17 +97,17 @@ Ptr should either be null, or point to a block of data that can be freed by the game later. ================ */ -void Sys_QueEvent( int evTime, sysEventType_t evType, int value, int value2, int ptrLength, void *ptr ) { - sysEvent_t *ev; +void Sys_QueEvent(int evTime, sysEventType_t evType, int value, int value2, int ptrLength, void *ptr) { + sysEvent_t *ev; - if ( evTime == 0 ) { + if (evTime == 0) { evTime = Sys_Milliseconds(); } // try to combine all sequential mouse moves in one event - if ( evType == SE_MOUSE && lastEvent && lastEvent->evType == SE_MOUSE ) { + if (evType == SE_MOUSE && lastEvent && lastEvent->evType == SE_MOUSE) { // try to reuse already processed item - if ( eventTail == eventHead ) { + if (eventTail == eventHead) { lastEvent->evValue = value; lastEvent->evValue2 = value2; eventTail--; @@ -126,13 +119,13 @@ void Sys_QueEvent( int evTime, sysEventType_t evType, int value, int value2, int return; } - ev = &eventQue[ eventHead & MASK_QUED_EVENTS ]; + ev = &eventQue[eventHead & MASK_QUED_EVENTS]; - if ( eventHead - eventTail >= MAX_QUED_EVENTS ) { - Com_Printf( "Sys_QueEvent(%s,time=%i): overflow\n", Sys_EventName(evType), evTime ); + if (eventHead - eventTail >= MAX_QUED_EVENTS) { + Com_Printf("Sys_QueEvent(%s,time=%i): overflow\n", Sys_EventName(evType), evTime); // we are discarding an event, but don't leak memory - if ( ev->evPtr ) { - Z_Free( ev->evPtr ); + if (ev->evPtr) { + Z_Free(ev->evPtr); } eventTail++; } diff --git a/shared/sys/sys_main.cpp b/shared/sys/sys_main.cpp index fd103e713f..d7d377efc6 100644 --- a/shared/sys/sys_main.cpp +++ b/shared/sys/sys_main.cpp @@ -32,8 +32,8 @@ along with this program; if not, see . #include "sys_public.h" #include "con_local.h" -static char binaryPath[ MAX_OSPATH ] = { 0 }; -static char installPath[ MAX_OSPATH ] = { 0 }; +static char binaryPath[MAX_OSPATH] = {0}; +static char installPath[MAX_OSPATH] = {0}; cvar_t *com_minimized; cvar_t *com_unfocused; @@ -46,38 +46,28 @@ cvar_t *com_maxfpsUnfocused; Sys_SetBinaryPath ================= */ -void Sys_SetBinaryPath(const char *path) -{ - Q_strncpyz(binaryPath, path, sizeof(binaryPath)); -} +void Sys_SetBinaryPath(const char *path) { Q_strncpyz(binaryPath, path, sizeof(binaryPath)); } /* ================= Sys_BinaryPath ================= */ -char *Sys_BinaryPath(void) -{ - return binaryPath; -} +char *Sys_BinaryPath(void) { return binaryPath; } /* ================= Sys_SetDefaultInstallPath ================= */ -void Sys_SetDefaultInstallPath(const char *path) -{ - Q_strncpyz(installPath, path, sizeof(installPath)); -} +void Sys_SetDefaultInstallPath(const char *path) { Q_strncpyz(installPath, path, sizeof(installPath)); } /* ================= Sys_DefaultInstallPath ================= */ -char *Sys_DefaultInstallPath(void) -{ +char *Sys_DefaultInstallPath(void) { if (*installPath) return installPath; else @@ -89,30 +79,27 @@ char *Sys_DefaultInstallPath(void) Sys_DefaultAppPath ================= */ -char *Sys_DefaultAppPath(void) -{ - return Sys_BinaryPath(); -} +char *Sys_DefaultAppPath(void) { return Sys_BinaryPath(); } /* ================== Sys_GetClipboardData ================== */ -char *Sys_GetClipboardData( void ) { +char *Sys_GetClipboardData(void) { #ifdef DEDICATED return NULL; #else - if ( !SDL_HasClipboardText() ) + if (!SDL_HasClipboardText()) return NULL; char *cbText = SDL_GetClipboardText(); - size_t len = strlen( cbText ) + 1; + size_t len = strlen(cbText) + 1; - char *buf = (char *)Z_Malloc( len, TAG_CLIPBOARD ); - Q_strncpyz( buf, cbText, len ); + char *buf = (char *)Z_Malloc(len, TAG_CLIPBOARD); + Q_strncpyz(buf, cbText, len); - SDL_free( cbText ); + SDL_free(cbText); return buf; #endif } @@ -124,22 +111,19 @@ Sys_ConsoleInput Handle new console input ================= */ -char *Sys_ConsoleInput(void) -{ - return CON_Input( ); -} +char *Sys_ConsoleInput(void) { return CON_Input(); } -void Sys_Print( const char *msg ) { +void Sys_Print(const char *msg) { // TTimo - prefix for text that shows up in console but not in notify // backported from RTCW - if ( !Q_strncmp( msg, "[skipnotify]", 12 ) ) { + if (!Q_strncmp(msg, "[skipnotify]", 12)) { msg += 12; } - if ( msg[0] == '*' ) { + if (msg[0] == '*') { msg += 1; } - ConsoleLogAppend( msg ); - CON_Print( msg ); + ConsoleLogAppend(msg); + CON_Print(msg); } /* @@ -150,23 +134,23 @@ Called after the common systems (cvars, files, etc) are initialized ================ */ -void Sys_Init( void ) { - Cmd_AddCommand ("in_restart", IN_Restart); - Cvar_Get( "arch", OS_STRING " " ARCH_STRING, CVAR_ROM ); - Cvar_Get( "username", Sys_GetCurrentUser(), CVAR_ROM ); +void Sys_Init(void) { + Cmd_AddCommand("in_restart", IN_Restart); + Cvar_Get("arch", OS_STRING " " ARCH_STRING, CVAR_ROM); + Cvar_Get("username", Sys_GetCurrentUser(), CVAR_ROM); - com_unfocused = Cvar_Get( "com_unfocused", "0", CVAR_ROM ); - com_minimized = Cvar_Get( "com_minimized", "0", CVAR_ROM ); + com_unfocused = Cvar_Get("com_unfocused", "0", CVAR_ROM); + com_minimized = Cvar_Get("com_minimized", "0", CVAR_ROM); #ifdef _JK2EXE - com_maxfps = Cvar_Get ("com_maxfps", "125", CVAR_ARCHIVE ); + com_maxfps = Cvar_Get("com_maxfps", "125", CVAR_ARCHIVE); #else - com_maxfps = Cvar_Get( "com_maxfps", "125", CVAR_ARCHIVE, "Maximum frames per second" ); + com_maxfps = Cvar_Get("com_maxfps", "125", CVAR_ARCHIVE, "Maximum frames per second"); #endif - com_maxfpsUnfocused = Cvar_Get( "com_maxfpsUnfocused", "0", CVAR_ARCHIVE_ND ); - com_maxfpsMinimized = Cvar_Get( "com_maxfpsMinimized", "50", CVAR_ARCHIVE_ND ); + com_maxfpsUnfocused = Cvar_Get("com_maxfpsUnfocused", "0", CVAR_ARCHIVE_ND); + com_maxfpsMinimized = Cvar_Get("com_maxfpsMinimized", "50", CVAR_ARCHIVE_ND); } -static void NORETURN Sys_Exit( int ex ) { +static void NORETURN Sys_Exit(int ex) { IN_Shutdown(); #ifndef DEDICATED SDL_Quit(); @@ -181,77 +165,67 @@ static void NORETURN Sys_Exit( int ex ) { CON_Shutdown(); - exit( ex ); + exit(ex); } #if !defined(DEDICATED) -static void Sys_ErrorDialog( const char *error ) -{ +static void Sys_ErrorDialog(const char *error) { time_t rawtime; char timeStr[32] = {}; // should really only reach ~19 chars char crashLogPath[MAX_OSPATH]; - time( &rawtime ); - strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime - Com_sprintf( crashLogPath, sizeof( crashLogPath ), - "%s%ccrashlog-%s.txt", - Sys_DefaultHomePath(), PATH_SEP, timeStr ); + time(&rawtime); + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d_%H-%M-%S", localtime(&rawtime)); // or gmtime + Com_sprintf(crashLogPath, sizeof(crashLogPath), "%s%ccrashlog-%s.txt", Sys_DefaultHomePath(), PATH_SEP, timeStr); - Sys_Mkdir( Sys_DefaultHomePath() ); + Sys_Mkdir(Sys_DefaultHomePath()); - FILE *fp = fopen( crashLogPath, "w" ); - if ( fp ) - { - ConsoleLogWriteOut( fp ); - fclose( fp ); + FILE *fp = fopen(crashLogPath, "w"); + if (fp) { + ConsoleLogWriteOut(fp); + fclose(fp); - const char *errorMessage = va( "%s\n\nThe crash log was written to %s", error, crashLogPath ); - if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 ) - { - fprintf( stderr, "%s", errorMessage ); + const char *errorMessage = va("%s\n\nThe crash log was written to %s", error, crashLogPath); + if (SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL) < 0) { + fprintf(stderr, "%s", errorMessage); } - } - else - { + } else { // Getting pretty desperate now - ConsoleLogWriteOut( stderr ); - fflush( stderr ); + ConsoleLogWriteOut(stderr); + fflush(stderr); - const char *errorMessage = va( "%s\nCould not write the crash log file, but we printed it to stderr.\n" - "Try running the game using a command line interface.", error ); - if ( SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL ) < 0 ) - { + const char *errorMessage = va("%s\nCould not write the crash log file, but we printed it to stderr.\n" + "Try running the game using a command line interface.", + error); + if (SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", errorMessage, NULL) < 0) { // We really have hit rock bottom here :( - fprintf( stderr, "%s", errorMessage ); + fprintf(stderr, "%s", errorMessage); } } } #endif -void NORETURN QDECL Sys_Error( const char *error, ... ) -{ +void NORETURN QDECL Sys_Error(const char *error, ...) { va_list argptr; - char string[1024]; + char string[1024]; - va_start (argptr,error); - Q_vsnprintf (string, sizeof(string), error, argptr); - va_end (argptr); + va_start(argptr, error); + Q_vsnprintf(string, sizeof(string), error, argptr); + va_end(argptr); - Sys_Print( string ); + Sys_Print(string); // Only print Sys_ErrorDialog for client binary. The dedicated // server binary is meant to be a command line program so you would // expect to see the error printed. #if !defined(DEDICATED) - Sys_ErrorDialog( string ); + Sys_ErrorDialog(string); #endif - Sys_Exit( 3 ); + Sys_Exit(3); } -void NORETURN Sys_Quit (void) { - Sys_Exit(0); -} +void NORETURN Sys_Quit(void) { Sys_Exit(0); } /* ============ @@ -260,11 +234,10 @@ Sys_FileTime returns -1 if not present ============ */ -time_t Sys_FileTime( const char *path ) -{ +time_t Sys_FileTime(const char *path) { struct stat buf; - if ( stat( path, &buf ) == -1 ) + if (stat(path, &buf) == -1) return -1; return buf.st_mtime; @@ -275,10 +248,8 @@ time_t Sys_FileTime( const char *path ) Sys_UnloadDll ================= */ -void Sys_UnloadDll( void *dllHandle ) -{ - if( !dllHandle ) - { +void Sys_UnloadDll(void *dllHandle) { + if (!dllHandle) { Com_Printf("Sys_UnloadDll(NULL)\n"); return; } @@ -294,275 +265,247 @@ First try to load library name from system library path, from executable path, then fs_basepath. ================= */ -void *Sys_LoadDll( const char *name, qboolean useSystemLib ) -{ +void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle = NULL; // Don't load any DLLs that end with the pk3 extension - if ( COM_CompareExtension( name, ".pk3" ) ) - { - Com_Printf( S_COLOR_YELLOW "WARNING: Rejecting DLL named \"%s\"", name ); + if (COM_CompareExtension(name, ".pk3")) { + Com_Printf(S_COLOR_YELLOW "WARNING: Rejecting DLL named \"%s\"", name); return NULL; } - if ( useSystemLib ) - { - Com_Printf( "Trying to load \"%s\"...\n", name ); + if (useSystemLib) { + Com_Printf("Trying to load \"%s\"...\n", name); - dllhandle = Sys_LoadLibrary( name ); - if ( dllhandle ) + dllhandle = Sys_LoadLibrary(name); + if (dllhandle) return dllhandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, name, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", __FUNCTION__, name, Sys_LibraryError()); } const char *binarypath = Sys_BinaryPath(); - const char *basepath = Cvar_VariableString( "fs_basepath" ); + const char *basepath = Cvar_VariableString("fs_basepath"); - if ( !*binarypath ) + if (!*binarypath) binarypath = "."; const char *searchPaths[] = { binarypath, basepath, }; - const size_t numPaths = ARRAY_LEN( searchPaths ); + const size_t numPaths = ARRAY_LEN(searchPaths); - for ( size_t i = 0; i < numPaths; i++ ) - { + for (size_t i = 0; i < numPaths; i++) { const char *libDir = searchPaths[i]; - if ( !libDir[0] ) + if (!libDir[0]) continue; - Com_Printf( "Trying to load \"%s\" from \"%s\"...\n", name, libDir ); - char *fn = va( "%s%c%s", libDir, PATH_SEP, name ); - dllhandle = Sys_LoadLibrary( fn ); - if ( dllhandle ) + Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, libDir); + char *fn = va("%s%c%s", libDir, PATH_SEP, name); + dllhandle = Sys_LoadLibrary(fn); + if (dllhandle) return dllhandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", __FUNCTION__, fn, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", __FUNCTION__, fn, Sys_LibraryError()); } return NULL; } #if defined(MACOS_X) && !defined(_JK2EXE) -void *Sys_LoadMachOBundle( const char *name ) -{ - if ( !FS_LoadMachOBundle(name) ) +void *Sys_LoadMachOBundle(const char *name) { + if (!FS_LoadMachOBundle(name)) return NULL; - char *homepath = Cvar_VariableString( "fs_homepath" ); - char *gamedir = Cvar_VariableString( "fs_game" ); + char *homepath = Cvar_VariableString("fs_homepath"); + char *gamedir = Cvar_VariableString("fs_game"); char dllName[MAX_QPATH]; - Com_sprintf( dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name ); + Com_sprintf(dllName, sizeof(dllName), "%s_pk3" DLL_EXT, name); - //load the unzipped library - char *fn = FS_BuildOSPath( homepath, gamedir, dllName ); + // load the unzipped library + char *fn = FS_BuildOSPath(homepath, gamedir, dllName); - void *libHandle = Sys_LoadLibrary( fn ); + void *libHandle = Sys_LoadLibrary(fn); - if ( libHandle != NULL ) { - Com_Printf( "Loaded pk3 bundle %s.\n", name ); + if (libHandle != NULL) { + Com_Printf("Loaded pk3 bundle %s.\n", name); } return libHandle; } #endif -enum SearchPathFlag -{ - SEARCH_PATH_MOD = 1 << 0, - SEARCH_PATH_BASE = 1 << 1, - SEARCH_PATH_OPENJK = 1 << 2, - SEARCH_PATH_ROOT = 1 << 3 -}; - -static void *Sys_LoadDllFromPaths( const char *filename, const char *gamedir, const char **searchPaths, - size_t numPaths, uint32_t searchFlags, const char *callerName ) -{ +enum SearchPathFlag { SEARCH_PATH_MOD = 1 << 0, SEARCH_PATH_BASE = 1 << 1, SEARCH_PATH_OPENJK = 1 << 2, SEARCH_PATH_ROOT = 1 << 3 }; + +static void *Sys_LoadDllFromPaths(const char *filename, const char *gamedir, const char **searchPaths, size_t numPaths, uint32_t searchFlags, + const char *callerName) { char *fn; void *libHandle; - if ( searchFlags & SEARCH_PATH_MOD ) - { - for ( size_t i = 0; i < numPaths; i++ ) - { + if (searchFlags & SEARCH_PATH_MOD) { + for (size_t i = 0; i < numPaths; i++) { const char *libDir = searchPaths[i]; - if ( !libDir[0] ) + if (!libDir[0]) continue; - fn = FS_BuildOSPath( libDir, gamedir, filename ); - libHandle = Sys_LoadLibrary( fn ); - if ( libHandle ) + fn = FS_BuildOSPath(libDir, gamedir, filename); + libHandle = Sys_LoadLibrary(fn); + if (libHandle) return libHandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError()); } } - if ( searchFlags & SEARCH_PATH_BASE ) - { - for ( size_t i = 0; i < numPaths; i++ ) - { + if (searchFlags & SEARCH_PATH_BASE) { + for (size_t i = 0; i < numPaths; i++) { const char *libDir = searchPaths[i]; - if ( !libDir[0] ) + if (!libDir[0]) continue; - fn = FS_BuildOSPath( libDir, BASEGAME, filename ); - libHandle = Sys_LoadLibrary( fn ); - if ( libHandle ) + fn = FS_BuildOSPath(libDir, BASEGAME, filename); + libHandle = Sys_LoadLibrary(fn); + if (libHandle) return libHandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError()); } } - if ( searchFlags & SEARCH_PATH_OPENJK ) - { - for ( size_t i = 0; i < numPaths; i++ ) - { + if (searchFlags & SEARCH_PATH_OPENJK) { + for (size_t i = 0; i < numPaths; i++) { const char *libDir = searchPaths[i]; - if ( !libDir[0] ) + if (!libDir[0]) continue; - fn = FS_BuildOSPath( libDir, OPENJKGAME, filename ); - libHandle = Sys_LoadLibrary( fn ); - if ( libHandle ) + fn = FS_BuildOSPath(libDir, OPENJKGAME, filename); + libHandle = Sys_LoadLibrary(fn); + if (libHandle) return libHandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError()); } } - if ( searchFlags & SEARCH_PATH_ROOT ) - { - for ( size_t i = 0; i < numPaths; i++ ) - { + if (searchFlags & SEARCH_PATH_ROOT) { + for (size_t i = 0; i < numPaths; i++) { const char *libDir = searchPaths[i]; - if ( !libDir[0] ) + if (!libDir[0]) continue; - fn = va( "%s%c%s", libDir, PATH_SEP, filename ); - libHandle = Sys_LoadLibrary( fn ); - if ( libHandle ) + fn = va("%s%c%s", libDir, PATH_SEP, filename); + libHandle = Sys_LoadLibrary(fn); + if (libHandle) return libHandle; - Com_Printf( "%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError() ); + Com_Printf("%s(%s) failed: \"%s\"\n", callerName, fn, Sys_LibraryError()); } } return NULL; } -static void FreeUnpackDLLResult(UnpackDLLResult *result) -{ - if ( result->tempDLLPath ) +static void FreeUnpackDLLResult(UnpackDLLResult *result) { + if (result->tempDLLPath) Z_Free((void *)result->tempDLLPath); } -void *Sys_LoadLegacyGameDll( const char *name, VMMainProc **vmMain, SystemCallProc *systemcalls ) -{ - void *libHandle = NULL; - char filename[MAX_OSPATH]; +void *Sys_LoadLegacyGameDll(const char *name, VMMainProc **vmMain, SystemCallProc *systemcalls) { + void *libHandle = NULL; + char filename[MAX_OSPATH]; - Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); + Com_sprintf(filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); #if defined(_DEBUG) - libHandle = Sys_LoadLibrary( filename ); - if ( !libHandle ) + libHandle = Sys_LoadLibrary(filename); + if (!libHandle) #endif { UnpackDLLResult unpackResult = Sys_UnpackDLL(filename); - if ( !unpackResult.succeeded ) - { - if ( Sys_DLLNeedsUnpacking() ) - { + if (!unpackResult.succeeded) { + if (Sys_DLLNeedsUnpacking()) { FreeUnpackDLLResult(&unpackResult); - Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename ); + Com_DPrintf("Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename); return NULL; } - } - else - { + } else { libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath); } FreeUnpackDLLResult(&unpackResult); - if ( !libHandle ) - { + if (!libHandle) { #if defined(MACOS_X) && !defined(_JK2EXE) - //First, look for the old-style mac .bundle that's inside a pk3 - //It's actually zipped, and the zipfile has the same name as 'name' - libHandle = Sys_LoadMachOBundle( name ); + // First, look for the old-style mac .bundle that's inside a pk3 + // It's actually zipped, and the zipfile has the same name as 'name' + libHandle = Sys_LoadMachOBundle(name); #endif if (!libHandle) { - char *basepath = Cvar_VariableString( "fs_basepath" ); - char *homepath = Cvar_VariableString( "fs_homepath" ); - char *cdpath = Cvar_VariableString( "fs_cdpath" ); - char *gamedir = Cvar_VariableString( "fs_game" ); - #ifdef MACOS_X - char *apppath = Cvar_VariableString( "fs_apppath" ); - #endif + char *basepath = Cvar_VariableString("fs_basepath"); + char *homepath = Cvar_VariableString("fs_homepath"); + char *cdpath = Cvar_VariableString("fs_cdpath"); + char *gamedir = Cvar_VariableString("fs_game"); +#ifdef MACOS_X + char *apppath = Cvar_VariableString("fs_apppath"); +#endif const char *searchPaths[] = { homepath, - #ifdef MACOS_X +#ifdef MACOS_X apppath, - #endif +#endif basepath, cdpath, }; - size_t numPaths = ARRAY_LEN( searchPaths ); + size_t numPaths = ARRAY_LEN(searchPaths); - libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ ); - if ( !libHandle ) + libHandle = Sys_LoadDllFromPaths(filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__); + if (!libHandle) return NULL; } } } - typedef void QDECL DllEntryProc( SystemCallProc *syscallptr ); + typedef void QDECL DllEntryProc(SystemCallProc * syscallptr); - DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction( libHandle, "dllEntry" ); - *vmMain = (VMMainProc *)Sys_LoadFunction( libHandle, "vmMain" ); + DllEntryProc *dllEntry = (DllEntryProc *)Sys_LoadFunction(libHandle, "dllEntry"); + *vmMain = (VMMainProc *)Sys_LoadFunction(libHandle, "vmMain"); - if ( !*vmMain || !dllEntry ) { - Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) failed to find vmMain function:\n...%s!\n", name, Sys_LibraryError() ); - Sys_UnloadLibrary( libHandle ); + if (!*vmMain || !dllEntry) { + Com_DPrintf("Sys_LoadLegacyGameDll(%s) failed to find vmMain function:\n...%s!\n", name, Sys_LibraryError()); + Sys_UnloadLibrary(libHandle); return NULL; } - Com_DPrintf ( "Sys_LoadLegacyGameDll(%s) found vmMain function at 0x%" PRIxPTR "\n", name, *vmMain ); - dllEntry( systemcalls ); + Com_DPrintf("Sys_LoadLegacyGameDll(%s) found vmMain function at 0x%" PRIxPTR "\n", name, *vmMain); + dllEntry(systemcalls); return libHandle; } -void *Sys_LoadSPGameDll( const char *name, GetGameAPIProc **GetGameAPI ) -{ - void *libHandle = NULL; - char filename[MAX_OSPATH]; +void *Sys_LoadSPGameDll(const char *name, GetGameAPIProc **GetGameAPI) { + void *libHandle = NULL; + char filename[MAX_OSPATH]; - assert( GetGameAPI ); + assert(GetGameAPI); - Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); + Com_sprintf(filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); #if defined(MACOS_X) && !defined(_JK2EXE) - //First, look for the old-style mac .bundle that's inside a pk3 - //It's actually zipped, and the zipfile has the same name as 'name' - libHandle = Sys_LoadMachOBundle( filename ); + // First, look for the old-style mac .bundle that's inside a pk3 + // It's actually zipped, and the zipfile has the same name as 'name' + libHandle = Sys_LoadMachOBundle(filename); #endif if (!libHandle) { - char *basepath = Cvar_VariableString( "fs_basepath" ); - char *homepath = Cvar_VariableString( "fs_homepath" ); - char *cdpath = Cvar_VariableString( "fs_cdpath" ); - char *gamedir = Cvar_VariableString( "fs_game" ); + char *basepath = Cvar_VariableString("fs_basepath"); + char *homepath = Cvar_VariableString("fs_homepath"); + char *cdpath = Cvar_VariableString("fs_cdpath"); + char *gamedir = Cvar_VariableString("fs_game"); #ifdef MACOS_X - char *apppath = Cvar_VariableString( "fs_apppath" ); + char *apppath = Cvar_VariableString("fs_apppath"); #endif const char *searchPaths[] = { @@ -573,69 +516,62 @@ void *Sys_LoadSPGameDll( const char *name, GetGameAPIProc **GetGameAPI ) basepath, cdpath, }; - size_t numPaths = ARRAY_LEN( searchPaths ); + size_t numPaths = ARRAY_LEN(searchPaths); - libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, - SEARCH_PATH_BASE | SEARCH_PATH_MOD | SEARCH_PATH_OPENJK | SEARCH_PATH_ROOT, - __FUNCTION__ ); - if ( !libHandle ) + libHandle = Sys_LoadDllFromPaths(filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD | SEARCH_PATH_OPENJK | SEARCH_PATH_ROOT, + __FUNCTION__); + if (!libHandle) return NULL; } - *GetGameAPI = (GetGameAPIProc *)Sys_LoadFunction( libHandle, "GetGameAPI" ); - if ( !*GetGameAPI ) { - Com_DPrintf ( "%s(%s) failed to find GetGameAPI function:\n...%s!\n", __FUNCTION__, name, Sys_LibraryError() ); - Sys_UnloadLibrary( libHandle ); + *GetGameAPI = (GetGameAPIProc *)Sys_LoadFunction(libHandle, "GetGameAPI"); + if (!*GetGameAPI) { + Com_DPrintf("%s(%s) failed to find GetGameAPI function:\n...%s!\n", __FUNCTION__, name, Sys_LibraryError()); + Sys_UnloadLibrary(libHandle); return NULL; } return libHandle; } -void *Sys_LoadGameDll( const char *name, GetModuleAPIProc **moduleAPI ) -{ - void *libHandle = NULL; - char filename[MAX_OSPATH]; +void *Sys_LoadGameDll(const char *name, GetModuleAPIProc **moduleAPI) { + void *libHandle = NULL; + char filename[MAX_OSPATH]; - Com_sprintf (filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); + Com_sprintf(filename, sizeof(filename), "%s" ARCH_STRING DLL_EXT, name); #if defined(_DEBUG) - libHandle = Sys_LoadLibrary( filename ); - if ( !libHandle ) + libHandle = Sys_LoadLibrary(filename); + if (!libHandle) #endif { UnpackDLLResult unpackResult = Sys_UnpackDLL(filename); - if ( !unpackResult.succeeded ) - { - if ( Sys_DLLNeedsUnpacking() ) - { + if (!unpackResult.succeeded) { + if (Sys_DLLNeedsUnpacking()) { FreeUnpackDLLResult(&unpackResult); - Com_DPrintf( "Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename ); + Com_DPrintf("Sys_LoadLegacyGameDll: Failed to unpack %s from PK3.\n", filename); return NULL; } - } - else - { + } else { libHandle = Sys_LoadLibrary(unpackResult.tempDLLPath); } FreeUnpackDLLResult(&unpackResult); - if ( !libHandle ) - { + if (!libHandle) { #if defined(MACOS_X) && !defined(_JK2EXE) - //First, look for the old-style mac .bundle that's inside a pk3 - //It's actually zipped, and the zipfile has the same name as 'name' - libHandle = Sys_LoadMachOBundle( name ); + // First, look for the old-style mac .bundle that's inside a pk3 + // It's actually zipped, and the zipfile has the same name as 'name' + libHandle = Sys_LoadMachOBundle(name); #endif if (!libHandle) { - char *basepath = Cvar_VariableString( "fs_basepath" ); - char *homepath = Cvar_VariableString( "fs_homepath" ); - char *cdpath = Cvar_VariableString( "fs_cdpath" ); - char *gamedir = Cvar_VariableString( "fs_game" ); + char *basepath = Cvar_VariableString("fs_basepath"); + char *homepath = Cvar_VariableString("fs_homepath"); + char *cdpath = Cvar_VariableString("fs_cdpath"); + char *gamedir = Cvar_VariableString("fs_game"); #ifdef MACOS_X - char *apppath = Cvar_VariableString( "fs_apppath" ); + char *apppath = Cvar_VariableString("fs_apppath"); #endif const char *searchPaths[] = { @@ -646,19 +582,19 @@ void *Sys_LoadGameDll( const char *name, GetModuleAPIProc **moduleAPI ) basepath, cdpath, }; - size_t numPaths = ARRAY_LEN( searchPaths ); + size_t numPaths = ARRAY_LEN(searchPaths); - libHandle = Sys_LoadDllFromPaths( filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__ ); - if ( !libHandle ) + libHandle = Sys_LoadDllFromPaths(filename, gamedir, searchPaths, numPaths, SEARCH_PATH_BASE | SEARCH_PATH_MOD, __FUNCTION__); + if (!libHandle) return NULL; } } } - *moduleAPI = (GetModuleAPIProc *)Sys_LoadFunction( libHandle, "GetModuleAPI" ); - if ( !*moduleAPI ) { - Com_DPrintf ( "Sys_LoadGameDll(%s) failed to find GetModuleAPI function:\n...%s!\n", name, Sys_LibraryError() ); - Sys_UnloadLibrary( libHandle ); + *moduleAPI = (GetModuleAPIProc *)Sys_LoadFunction(libHandle, "GetModuleAPI"); + if (!*moduleAPI) { + Com_DPrintf("Sys_LoadGameDll(%s) failed to find GetModuleAPI function:\n...%s!\n", name, Sys_LibraryError()); + Sys_UnloadLibrary(libHandle); return NULL; } @@ -670,31 +606,26 @@ void *Sys_LoadGameDll( const char *name, GetModuleAPIProc **moduleAPI ) Sys_SigHandler ================= */ -void Sys_SigHandler( int signal ) -{ +void Sys_SigHandler(int signal) { static qboolean signalcaught = qfalse; - if( signalcaught ) - { - fprintf( stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n", - signal ); - } - else - { + if (signalcaught) { + fprintf(stderr, "DOUBLE SIGNAL FAULT: Received signal %d, exiting...\n", signal); + } else { signalcaught = qtrue; - //VM_Forced_Unload_Start(); + // VM_Forced_Unload_Start(); #ifndef DEDICATED CL_Shutdown(); - //CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue); + // CL_Shutdown(va("Received signal %d", signal), qtrue, qtrue); #endif - SV_Shutdown(va("Received signal %d", signal) ); - //VM_Forced_Unload_Done(); + SV_Shutdown(va("Received signal %d", signal)); + // VM_Forced_Unload_Done(); } - if( signal == SIGTERM || signal == SIGINT ) - Sys_Exit( 1 ); + if (signal == SIGTERM || signal == SIGINT) + Sys_Exit(1); else - Sys_Exit( 2 ); + Sys_Exit(2); } #ifdef MACOS_X @@ -707,18 +638,17 @@ void Sys_SigHandler( int signal ) the result is returned. If not, dir is returned untouched. ================= */ -char *Sys_StripAppBundle( char *dir ) -{ +char *Sys_StripAppBundle(char *dir) { static char cwd[MAX_OSPATH]; Q_strncpyz(cwd, dir, sizeof(cwd)); - if(strcmp(Sys_Basename(cwd), "MacOS")) + if (strcmp(Sys_Basename(cwd), "MacOS")) return dir; Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd)); - if(strcmp(Sys_Basename(cwd), "Contents")) + if (strcmp(Sys_Basename(cwd), "Contents")) return dir; Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd)); - if(!strstr(Sys_Basename(cwd), ".app")) + if (!strstr(Sys_Basename(cwd), ".app")) return dir; Q_strncpyz(cwd, Sys_Dirname(cwd), sizeof(cwd)); return cwd; @@ -726,17 +656,16 @@ char *Sys_StripAppBundle( char *dir ) #endif #ifndef DEFAULT_BASEDIR -# ifdef MACOS_X -# define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath()) -# else -# define DEFAULT_BASEDIR Sys_BinaryPath() -# endif +#ifdef MACOS_X +#define DEFAULT_BASEDIR Sys_StripAppBundle(Sys_BinaryPath()) +#else +#define DEFAULT_BASEDIR Sys_BinaryPath() +#endif #endif -int main ( int argc, char* argv[] ) -{ - int i; - char commandLine[ MAX_STRING_CHARS ] = { 0 }; +int main(int argc, char *argv[]) { + int i; + char commandLine[MAX_STRING_CHARS] = {0}; Sys_PlatformInit(); CON_Init(); @@ -746,65 +675,59 @@ int main ( int argc, char* argv[] ) #ifdef MACOS_X // This is passed if we are launched by double-clicking - if ( argc >= 2 && Q_strncmp ( argv[1], "-psn", 4 ) == 0 ) + if (argc >= 2 && Q_strncmp(argv[1], "-psn", 4) == 0) argc = 1; #endif - Sys_SetBinaryPath( Sys_Dirname( argv[ 0 ] ) ); - Sys_SetDefaultInstallPath( DEFAULT_BASEDIR ); + Sys_SetBinaryPath(Sys_Dirname(argv[0])); + Sys_SetDefaultInstallPath(DEFAULT_BASEDIR); // Concatenate the command line for passing to Com_Init - for( i = 1; i < argc; i++ ) - { + for (i = 1; i < argc; i++) { const bool containsSpaces = (strchr(argv[i], ' ') != NULL); if (containsSpaces) - Q_strcat( commandLine, sizeof( commandLine ), "\"" ); + Q_strcat(commandLine, sizeof(commandLine), "\""); - Q_strcat( commandLine, sizeof( commandLine ), argv[ i ] ); + Q_strcat(commandLine, sizeof(commandLine), argv[i]); if (containsSpaces) - Q_strcat( commandLine, sizeof( commandLine ), "\"" ); + Q_strcat(commandLine, sizeof(commandLine), "\""); - Q_strcat( commandLine, sizeof( commandLine ), " " ); + Q_strcat(commandLine, sizeof(commandLine), " "); } - Com_Init (commandLine); + Com_Init(commandLine); #ifndef DEDICATED SDL_version compiled; SDL_version linked; - SDL_VERSION( &compiled ); - SDL_GetVersion( &linked ); + SDL_VERSION(&compiled); + SDL_GetVersion(&linked); - Com_Printf( "SDL Version Compiled: %d.%d.%d\n", compiled.major, compiled.minor, compiled.patch ); - Com_Printf( "SDL Version Linked: %d.%d.%d\n", linked.major, linked.minor, linked.patch ); + Com_Printf("SDL Version Compiled: %d.%d.%d\n", compiled.major, compiled.minor, compiled.patch); + Com_Printf("SDL Version Linked: %d.%d.%d\n", linked.major, linked.minor, linked.patch); #endif NET_Init(); // main game loop - while (1) - { - if ( com_busyWait->integer ) - { + while (1) { + if (com_busyWait->integer) { bool shouldSleep = false; #if !defined(_JK2EXE) - if ( com_dedicated->integer ) - { + if (com_dedicated->integer) { shouldSleep = true; } #endif - if ( com_minimized->integer ) - { + if (com_minimized->integer) { shouldSleep = true; } - if ( shouldSleep ) - { - Sys_Sleep( 5 ); + if (shouldSleep) { + Sys_Sleep(5); } } diff --git a/shared/sys/sys_unix.cpp b/shared/sys/sys_unix.cpp index e3149819fc..38c6763e2b 100644 --- a/shared/sys/sys_unix.cpp +++ b/shared/sys/sys_unix.cpp @@ -40,27 +40,24 @@ along with this program; if not, see . qboolean stdinIsATTY = qfalse; // Used to determine where to store user-specific files -static char homePath[ MAX_OSPATH ] = { 0 }; +static char homePath[MAX_OSPATH] = {0}; -void Sys_PlatformInit( void ) -{ - const char* term = getenv( "TERM" ); +void Sys_PlatformInit(void) { + const char *term = getenv("TERM"); - signal( SIGHUP, Sys_SigHandler ); - signal( SIGQUIT, Sys_SigHandler ); - signal( SIGTRAP, Sys_SigHandler ); - signal( SIGABRT, Sys_SigHandler ); - signal( SIGBUS, Sys_SigHandler ); + signal(SIGHUP, Sys_SigHandler); + signal(SIGQUIT, Sys_SigHandler); + signal(SIGTRAP, Sys_SigHandler); + signal(SIGABRT, Sys_SigHandler); + signal(SIGBUS, Sys_SigHandler); - if (isatty( STDIN_FILENO ) && !( term && ( !strcmp( term, "raw" ) || !strcmp( term, "dumb" ) ) )) + if (isatty(STDIN_FILENO) && !(term && (!strcmp(term, "raw") || !strcmp(term, "dumb")))) stdinIsATTY = qtrue; else stdinIsATTY = qfalse; } -void Sys_PlatformExit( void ) -{ -} +void Sys_PlatformExit(void) {} /* ================ @@ -73,60 +70,52 @@ Sys_Milliseconds unsigned long sys_timeBase = 0; /* current time in ms, using sys_timeBase as origin NOTE: sys_timeBase*1000 + curtime -> ms since the Epoch - 0x7fffffff ms - ~24 days + 0x7fffffff ms - ~24 days although timeval:tv_usec is an int, I'm not sure wether it is actually used as an unsigned int - (which would affect the wrap period) */ + (which would affect the wrap period) */ int curtime; -int Sys_Milliseconds (bool baseTime) -{ +int Sys_Milliseconds(bool baseTime) { struct timeval tp; gettimeofday(&tp, NULL); - if (!sys_timeBase) - { + if (!sys_timeBase) { sys_timeBase = tp.tv_sec; - return tp.tv_usec/1000; + return tp.tv_usec / 1000; } - curtime = (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000; + curtime = (tp.tv_sec - sys_timeBase) * 1000 + tp.tv_usec / 1000; - static int sys_timeBase = curtime; - if (!baseTime) - { + static int sys_timeBase = curtime; + if (!baseTime) { curtime -= sys_timeBase; } return curtime; } -int Sys_Milliseconds2( void ) -{ - return Sys_Milliseconds(false); -} +int Sys_Milliseconds2(void) { return Sys_Milliseconds(false); } /* ================== Sys_RandomBytes ================== */ -bool Sys_RandomBytes( byte *string, int len ) -{ +bool Sys_RandomBytes(byte *string, int len) { FILE *fp; - fp = fopen( "/dev/urandom", "r" ); - if( !fp ) + fp = fopen("/dev/urandom", "r"); + if (!fp) return false; - setvbuf( fp, NULL, _IONBF, 0 ); // don't buffer reads from /dev/urandom + setvbuf(fp, NULL, _IONBF, 0); // don't buffer reads from /dev/urandom - if( !fread( string, sizeof( byte ), len, fp ) ) - { - fclose( fp ); + if (!fread(string, sizeof(byte), len, fp)) { + fclose(fp); return false; } - fclose( fp ); + fclose(fp); return true; } @@ -135,17 +124,16 @@ bool Sys_RandomBytes( byte *string, int len ) Sys_GetCurrentUser ================== */ -char *Sys_GetCurrentUser( void ) -{ +char *Sys_GetCurrentUser(void) { struct passwd *p; - if ( (p = getpwuid( getuid() )) == NULL ) { + if ((p = getpwuid(getuid())) == NULL) { return "player"; } return p->pw_name; } -#define MEM_THRESHOLD 96*1024*1024 +#define MEM_THRESHOLD 96 * 1024 * 1024 /* ================== @@ -154,21 +142,17 @@ Sys_LowPhysicalMemory TODO ================== */ -qboolean Sys_LowPhysicalMemory( void ) -{ - return qfalse; -} +qboolean Sys_LowPhysicalMemory(void) { return qfalse; } /* ================== Sys_Basename ================== */ -const char *Sys_Basename( const char *path ) -{ - static char buf[ MAX_OSPATH ]; - Q_strncpyz( buf, path, sizeof(buf) ); - return basename( buf ); +const char *Sys_Basename(const char *path) { + static char buf[MAX_OSPATH]; + Q_strncpyz(buf, path, sizeof(buf)); + return basename(buf); } /* @@ -176,11 +160,10 @@ const char *Sys_Basename( const char *path ) Sys_Dirname ================== */ -const char *Sys_Dirname( const char *path ) -{ - static char buf[ MAX_OSPATH ]; - Q_strncpyz( buf, path, sizeof(buf) ); - return dirname( buf ); +const char *Sys_Dirname(const char *path) { + static char buf[MAX_OSPATH]; + Q_strncpyz(buf, path, sizeof(buf)); + return dirname(buf); } /* @@ -198,22 +181,21 @@ DIRECTORY SCANNING Sys_ListFiles ================== */ -void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **list, int *numfiles ) { - char search[MAX_OSPATH], newsubdirs[MAX_OSPATH]; - char filename[MAX_OSPATH]; - DIR *fdir; +void Sys_ListFilteredFiles(const char *basedir, char *subdirs, char *filter, char **list, int *numfiles) { + char search[MAX_OSPATH], newsubdirs[MAX_OSPATH]; + char filename[MAX_OSPATH]; + DIR *fdir; struct dirent *d; struct stat st; - if ( *numfiles >= MAX_FOUND_FILES - 1 ) { + if (*numfiles >= MAX_FOUND_FILES - 1) { return; } if (strlen(subdirs)) { - Com_sprintf( search, sizeof(search), "%s/%s", basedir, subdirs ); - } - else { - Com_sprintf( search, sizeof(search), "%s", basedir ); + Com_sprintf(search, sizeof(search), "%s/%s", basedir, subdirs); + } else { + Com_sprintf(search, sizeof(search), "%s", basedir); } if ((fdir = opendir(search)) == NULL) { @@ -228,52 +210,50 @@ void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, ch if (st.st_mode & S_IFDIR) { if (Q_stricmp(d->d_name, ".") && Q_stricmp(d->d_name, "..")) { if (strlen(subdirs)) { - Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name); + Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s/%s", subdirs, d->d_name); + } else { + Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s", d->d_name); } - else { - Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", d->d_name); - } - Sys_ListFilteredFiles( basedir, newsubdirs, filter, list, numfiles ); + Sys_ListFilteredFiles(basedir, newsubdirs, filter, list, numfiles); } } - if ( *numfiles >= MAX_FOUND_FILES - 1 ) { + if (*numfiles >= MAX_FOUND_FILES - 1) { break; } - Com_sprintf( filename, sizeof(filename), "%s/%s", subdirs, d->d_name ); - if (!Com_FilterPath( filter, filename, qfalse )) + Com_sprintf(filename, sizeof(filename), "%s/%s", subdirs, d->d_name); + if (!Com_FilterPath(filter, filename, qfalse)) continue; - list[ *numfiles ] = CopyString( filename ); + list[*numfiles] = CopyString(filename); (*numfiles)++; } closedir(fdir); } -char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs ) -{ +char **Sys_ListFiles(const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs) { struct dirent *d; - DIR *fdir; + DIR *fdir; qboolean dironly = wantsubs; - char search[MAX_OSPATH]; - int nfiles; - char **listCopy; - char *list[MAX_FOUND_FILES]; - int i; + char search[MAX_OSPATH]; + int nfiles; + char **listCopy; + char *list[MAX_FOUND_FILES]; + int i; struct stat st; if (filter) { nfiles = 0; - Sys_ListFilteredFiles( directory, "", filter, list, &nfiles ); + Sys_ListFilteredFiles(directory, "", filter, list, &nfiles); - list[ nfiles ] = 0; + list[nfiles] = 0; *numfiles = nfiles; if (!nfiles) return NULL; - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_LISTFILES, qfalse ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_LISTFILES, qfalse); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; @@ -281,15 +261,15 @@ char **Sys_ListFiles( const char *directory, const char *extension, char *filter return listCopy; } - if ( !extension) + if (!extension) extension = ""; - if ( extension[0] == '/' && extension[1] == 0 ) { + if (extension[0] == '/' && extension[1] == 0) { extension = ""; dironly = qtrue; } - size_t extLen = strlen( extension ); + size_t extLen = strlen(extension); // search nfiles = 0; @@ -303,38 +283,34 @@ char **Sys_ListFiles( const char *directory, const char *extension, char *filter Com_sprintf(search, sizeof(search), "%s/%s", directory, d->d_name); if (stat(search, &st) == -1) continue; - if ((dironly && !(st.st_mode & S_IFDIR)) || - (!dironly && (st.st_mode & S_IFDIR))) + if ((dironly && !(st.st_mode & S_IFDIR)) || (!dironly && (st.st_mode & S_IFDIR))) continue; if (*extension) { - if ( strlen( d->d_name ) < extLen || - Q_stricmp( - d->d_name + strlen( d->d_name ) - extLen, - extension ) ) { + if (strlen(d->d_name) < extLen || Q_stricmp(d->d_name + strlen(d->d_name) - extLen, extension)) { continue; // didn't match } } - if ( nfiles == MAX_FOUND_FILES - 1 ) + if (nfiles == MAX_FOUND_FILES - 1) break; - list[ nfiles ] = CopyString( d->d_name ); + list[nfiles] = CopyString(d->d_name); nfiles++; } - list[ nfiles ] = 0; + list[nfiles] = 0; closedir(fdir); // return a copy of the list *numfiles = nfiles; - if ( !nfiles ) { + if (!nfiles) { return NULL; } - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_LISTFILES, qfalse ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_LISTFILES, qfalse); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; @@ -342,18 +318,18 @@ char **Sys_ListFiles( const char *directory, const char *extension, char *filter return listCopy; } -void Sys_FreeFileList( char **fileList ) { - int i; +void Sys_FreeFileList(char **fileList) { + int i; - if ( !fileList ) { + if (!fileList) { return; } - for ( i = 0 ; fileList[i] ; i++ ) { - Z_Free( fileList[i] ); + for (i = 0; fileList[i]; i++) { + Z_Free(fileList[i]); } - Z_Free( fileList ); + Z_Free(fileList); } /* @@ -363,37 +339,30 @@ Sys_Sleep Block execution for msec or until input is recieved. ================== */ -void Sys_Sleep( int msec ) -{ - if( msec == 0 ) +void Sys_Sleep(int msec) { + if (msec == 0) return; - if( stdinIsATTY ) - { + if (stdinIsATTY) { fd_set fdset; FD_ZERO(&fdset); FD_SET(STDIN_FILENO, &fdset); - if( msec < 0 ) - { + if (msec < 0) { select(STDIN_FILENO + 1, &fdset, NULL, NULL, NULL); - } - else - { + } else { struct timeval timeout; - timeout.tv_sec = msec/1000; - timeout.tv_usec = (msec%1000)*1000; + timeout.tv_sec = msec / 1000; + timeout.tv_usec = (msec % 1000) * 1000; select(STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout); } - } - else - { + } else { // With nothing to select() on, we can't wait indefinitely - if( msec < 0 ) + if (msec < 0) msec = 10; - usleep( msec * 1000 ); + usleep(msec * 1000); } } @@ -402,24 +371,22 @@ void Sys_Sleep( int msec ) Sys_Mkdir ================== */ -qboolean Sys_Mkdir( const char *path ) -{ - int result = mkdir( path, 0750 ); +qboolean Sys_Mkdir(const char *path) { + int result = mkdir(path, 0750); - if( result != 0 ) + if (result != 0) return (qboolean)(errno == EEXIST); return qtrue; } -char *Sys_Cwd( void ) -{ +char *Sys_Cwd(void) { static char cwd[MAX_OSPATH]; - if ( getcwd( cwd, sizeof( cwd ) - 1 ) == NULL ) + if (getcwd(cwd, sizeof(cwd) - 1) == NULL) cwd[0] = '\0'; else - cwd[MAX_OSPATH-1] = '\0'; + cwd[MAX_OSPATH - 1] = '\0'; return cwd; } @@ -427,15 +394,13 @@ char *Sys_Cwd( void ) /* Resolves path names and determines if they are the same */ /* For use with full OS paths not quake paths */ /* Returns true if resulting paths are valid and the same, otherwise false */ -bool Sys_PathCmp( const char *path1, const char *path2 ) -{ +bool Sys_PathCmp(const char *path1, const char *path2) { char *r1, *r2; r1 = realpath(path1, NULL); r2 = realpath(path2, NULL); - if(r1 && r2 && !Q_stricmp(r1, r2)) - { + if (r1 && r2 && !Q_stricmp(r1, r2)) { free(r1); free(r2); return true; @@ -452,51 +417,44 @@ Sys_DefaultHomePath ================== */ #ifdef MACOS_X -char *Sys_DefaultHomePath(void) -{ +char *Sys_DefaultHomePath(void) { char *p; - if ( !homePath[0] ) - { - if ( (p = getenv( "HOME" )) != NULL ) - { - Com_sprintf( homePath, sizeof( homePath ), "%s%c", p, PATH_SEP ); - Q_strcat( homePath, sizeof( homePath ), "Library/Application Support/" ); + if (!homePath[0]) { + if ((p = getenv("HOME")) != NULL) { + Com_sprintf(homePath, sizeof(homePath), "%s%c", p, PATH_SEP); + Q_strcat(homePath, sizeof(homePath), "Library/Application Support/"); - if ( com_homepath && com_homepath->string[0] ) - Q_strcat( homePath, sizeof( homePath ), com_homepath->string ); + if (com_homepath && com_homepath->string[0]) + Q_strcat(homePath, sizeof(homePath), com_homepath->string); else - Q_strcat( homePath, sizeof( homePath ), HOMEPATH_NAME_MACOSX ); + Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_MACOSX); } } return homePath; } #else -char *Sys_DefaultHomePath(void) -{ +char *Sys_DefaultHomePath(void) { char *p; - if ( !homePath[0] ) - { - if ( (p = getenv( "XDG_DATA_HOME" )) != NULL ) - { - Com_sprintf( homePath, sizeof( homePath ), "%s%c", p, PATH_SEP ); - if ( com_homepath && com_homepath->string[0] ) - Q_strcat( homePath, sizeof( homePath ), com_homepath->string ); + if (!homePath[0]) { + if ((p = getenv("XDG_DATA_HOME")) != NULL) { + Com_sprintf(homePath, sizeof(homePath), "%s%c", p, PATH_SEP); + if (com_homepath && com_homepath->string[0]) + Q_strcat(homePath, sizeof(homePath), com_homepath->string); else - Q_strcat( homePath, sizeof( homePath ), HOMEPATH_NAME_UNIX ); + Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_UNIX); return homePath; } - if ( (p = getenv( "HOME" )) != NULL ) - { - Com_sprintf( homePath, sizeof( homePath ), "%s%c.local%cshare%c", p, PATH_SEP, PATH_SEP, PATH_SEP ); - if ( com_homepath && com_homepath->string[0] ) - Q_strcat( homePath, sizeof( homePath ), com_homepath->string ); + if ((p = getenv("HOME")) != NULL) { + Com_sprintf(homePath, sizeof(homePath), "%s%c.local%cshare%c", p, PATH_SEP, PATH_SEP, PATH_SEP); + if (com_homepath && com_homepath->string[0]) + Q_strcat(homePath, sizeof(homePath), com_homepath->string); else - Q_strcat( homePath, sizeof( homePath ), HOMEPATH_NAME_UNIX ); + Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_UNIX); return homePath; } @@ -506,41 +464,34 @@ char *Sys_DefaultHomePath(void) } #endif -void Sys_SetProcessorAffinity( void ) { +void Sys_SetProcessorAffinity(void) { #if defined(__linux__) uint32_t cores; - if ( sscanf( com_affinity->string, "%X", &cores ) != 1 ) + if (sscanf(com_affinity->string, "%X", &cores) != 1) cores = 1; // set to first core only - const long numCores = sysconf( _SC_NPROCESSORS_ONLN ); - if ( !cores ) + const long numCores = sysconf(_SC_NPROCESSORS_ONLN); + if (!cores) cores = (1 << numCores) - 1; // use all cores cpu_set_t set; - CPU_ZERO( &set ); - for ( int i = 0; i < numCores; i++ ) { - if ( cores & (1< 0 ) - { + if (length > 0) { buffer[length] = '\0'; - fputs( buffer, stderr ); + fputs(buffer, stderr); length = 0; } - if ( *msg == '\n' ) - { + if (*msg == '\n') { // Issue a reset and then the newline - fputs( "\033[0m\n", stderr ); + fputs("\033[0m\n", stderr); msg++; - } - else - { + } else { // Print the color code - Com_sprintf( buffer, sizeof( buffer ), "\033[%dm", - q3ToAnsi[ColorIndex( *(msg + 1) )] ); - fputs( buffer, stderr ); + Com_sprintf(buffer, sizeof(buffer), "\033[%dm", q3ToAnsi[ColorIndex(*(msg + 1))]); + fputs(buffer, stderr); msg += 2; } - } - else - { - if ( length >= MAXPRINTMSG - 1 ) + } else { + if (length >= MAXPRINTMSG - 1) break; buffer[length] = *msg; @@ -606,9 +546,8 @@ void Sys_AnsiColorPrint( const char *msg ) } // Empty anything still left in the buffer - if ( length > 0 ) - { + if (length > 0) { buffer[length] = '\0'; - fputs( buffer, stderr ); + fputs(buffer, stderr); } } diff --git a/shared/sys/sys_win32.cpp b/shared/sys/sys_win32.cpp index 4a8768130f..6e7a5cbf22 100644 --- a/shared/sys/sys_win32.cpp +++ b/shared/sys/sys_win32.cpp @@ -26,10 +26,10 @@ along with this program; if not, see . #include #include -#define MEM_THRESHOLD (128*1024*1024) +#define MEM_THRESHOLD (128 * 1024 * 1024) // Used to determine where to store user-specific files -static char homePath[ MAX_OSPATH ] = { 0 }; +static char homePath[MAX_OSPATH] = {0}; static UINT timerResolution = 0; @@ -38,27 +38,26 @@ static UINT timerResolution = 0; Sys_Basename ============== */ -const char *Sys_Basename( const char *path ) -{ - static char base[ MAX_OSPATH ] = { 0 }; +const char *Sys_Basename(const char *path) { + static char base[MAX_OSPATH] = {0}; int length; - length = strlen( path ) - 1; + length = strlen(path) - 1; // Skip trailing slashes - while( length > 0 && path[ length ] == '\\' ) + while (length > 0 && path[length] == '\\') length--; - while( length > 0 && path[ length - 1 ] != '\\' ) + while (length > 0 && path[length - 1] != '\\') length--; - Q_strncpyz( base, &path[ length ], sizeof( base ) ); + Q_strncpyz(base, &path[length], sizeof(base)); - length = strlen( base ) - 1; + length = strlen(base) - 1; // Strip trailing slashes - while( length > 0 && base[ length ] == '\\' ) - base[ length-- ] = '\0'; + while (length > 0 && base[length] == '\\') + base[length--] = '\0'; return base; } @@ -68,18 +67,17 @@ const char *Sys_Basename( const char *path ) Sys_Dirname ============== */ -const char *Sys_Dirname( const char *path ) -{ - static char dir[ MAX_OSPATH ] = { 0 }; +const char *Sys_Dirname(const char *path) { + static char dir[MAX_OSPATH] = {0}; int length; - Q_strncpyz( dir, path, sizeof( dir ) ); - length = strlen( dir ) - 1; + Q_strncpyz(dir, path, sizeof(dir)); + length = strlen(dir) - 1; - while( length > 0 && dir[ length ] != '\\' ) + while (length > 0 && dir[length] != '\\') length--; - dir[ length ] = '\0'; + dir[length] = '\0'; return dir; } @@ -89,45 +87,38 @@ const char *Sys_Dirname( const char *path ) Sys_Milliseconds ================ */ -int Sys_Milliseconds (bool baseTime) -{ +int Sys_Milliseconds(bool baseTime) { static int sys_timeBase = timeGetTime(); - int sys_curtime; + int sys_curtime; sys_curtime = timeGetTime(); - if(!baseTime) - { + if (!baseTime) { sys_curtime -= sys_timeBase; } return sys_curtime; } -int Sys_Milliseconds2( void ) -{ - return Sys_Milliseconds(false); -} +int Sys_Milliseconds2(void) { return Sys_Milliseconds(false); } /* ================ Sys_RandomBytes ================ */ -bool Sys_RandomBytes( byte *string, int len ) -{ - HCRYPTPROV prov; +bool Sys_RandomBytes(byte *string, int len) { + HCRYPTPROV prov; - if( !CryptAcquireContext( &prov, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) ) { + if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { return false; } - if( !CryptGenRandom( prov, len, (BYTE *)string ) ) { - CryptReleaseContext( prov, 0 ); + if (!CryptGenRandom(prov, len, (BYTE *)string)) { + CryptReleaseContext(prov, 0); return false; } - CryptReleaseContext( prov, 0 ); + CryptReleaseContext(prov, 0); return true; } @@ -136,87 +127,82 @@ bool Sys_RandomBytes( byte *string, int len ) Sys_GetCurrentUser ================== */ -char *Sys_GetCurrentUser( void ) -{ +char *Sys_GetCurrentUser(void) { static char s_userName[1024]; - DWORD size = sizeof( s_userName ); + DWORD size = sizeof(s_userName); - if ( !GetUserName( s_userName, &size ) ) - strcpy( s_userName, "player" ); + if (!GetUserName(s_userName, &size)) + strcpy(s_userName, "player"); - if ( !s_userName[0] ) - { - strcpy( s_userName, "player" ); + if (!s_userName[0]) { + strcpy(s_userName, "player"); } return s_userName; } /* -* Builds the path for the user's game directory -*/ -char *Sys_DefaultHomePath( void ) -{ + * Builds the path for the user's game directory + */ +char *Sys_DefaultHomePath(void) { #if defined(BUILD_PORTABLE) - Com_Printf( "Portable install requested, skipping homepath support\n" ); + Com_Printf("Portable install requested, skipping homepath support\n"); return NULL; #else - if ( !homePath[0] ) - { + if (!homePath[0]) { TCHAR homeDirectory[MAX_PATH]; - if( !SUCCEEDED( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, homeDirectory ) ) ) - { - Com_Printf( "Unable to determine your home directory.\n" ); + if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, homeDirectory))) { + Com_Printf("Unable to determine your home directory.\n"); return NULL; } - Com_sprintf( homePath, sizeof( homePath ), "%s%cMy Games%c", homeDirectory, PATH_SEP, PATH_SEP ); - if ( com_homepath && com_homepath->string[0] ) - Q_strcat( homePath, sizeof( homePath ), com_homepath->string ); + Com_sprintf(homePath, sizeof(homePath), "%s%cMy Games%c", homeDirectory, PATH_SEP, PATH_SEP); + if (com_homepath && com_homepath->string[0]) + Q_strcat(homePath, sizeof(homePath), com_homepath->string); else - Q_strcat( homePath, sizeof( homePath ), HOMEPATH_NAME_WIN ); + Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_WIN); } return homePath; #endif } -static const char *GetErrorString( DWORD error ) { +static const char *GetErrorString(DWORD error) { static char buf[MAX_STRING_CHARS]; buf[0] = '\0'; - if ( error ) { + if (error) { LPVOID lpMsgBuf; - DWORD bufLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPTSTR)&lpMsgBuf, 0, NULL ); - if ( bufLen ) { + DWORD bufLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); + if (bufLen) { LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf; - Q_strncpyz( buf, lpMsgStr, Q_min( (size_t)(lpMsgStr + bufLen), sizeof(buf) ) ); - LocalFree( lpMsgBuf ); + Q_strncpyz(buf, lpMsgStr, Q_min((size_t)(lpMsgStr + bufLen), sizeof(buf))); + LocalFree(lpMsgBuf); } } return buf; } -void Sys_SetProcessorAffinity( void ) { +void Sys_SetProcessorAffinity(void) { DWORD_PTR processMask, processAffinityMask, systemAffinityMask; HANDLE handle = GetCurrentProcess(); - if ( !GetProcessAffinityMask( handle, &processAffinityMask, &systemAffinityMask ) ) + if (!GetProcessAffinityMask(handle, &processAffinityMask, &systemAffinityMask)) return; - if ( sscanf( com_affinity->string, "%X", &processMask ) != 1 ) + if (sscanf(com_affinity->string, "%X", &processMask) != 1) processMask = 1; // set to first core only - if ( !processMask ) + if (!processMask) processMask = systemAffinityMask; // use all the cores available to the system - if ( processMask == processAffinityMask ) + if (processMask == processAffinityMask) return; // no change - if ( !SetProcessAffinityMask( handle, processMask ) ) - Com_DPrintf( "Setting affinity mask failed (%s)\n", GetErrorString( GetLastError() ) ); + if (!SetProcessAffinityMask(handle, processMask)) + Com_DPrintf("Setting affinity mask failed (%s)\n", GetErrorString(GetLastError())); } /* @@ -228,17 +214,16 @@ Sys_LowPhysicalMemory() qboolean Sys_LowPhysicalMemory(void) { static MEMORYSTATUSEX stat; static qboolean bAsked = qfalse; - static cvar_t* sys_lowmem = Cvar_Get( "sys_lowmem", "0", 0 ); + static cvar_t *sys_lowmem = Cvar_Get("sys_lowmem", "0", 0); - if (!bAsked) // just in case it takes a little time for GlobalMemoryStatusEx() to gather stats on - { // stuff we don't care about such as virtual mem etc. + if (!bAsked) // just in case it takes a little time for GlobalMemoryStatusEx() to gather stats on + { // stuff we don't care about such as virtual mem etc. bAsked = qtrue; - stat.dwLength = sizeof (stat); - GlobalMemoryStatusEx (&stat); + stat.dwLength = sizeof(stat); + GlobalMemoryStatusEx(&stat); } - if (sys_lowmem->integer) - { + if (sys_lowmem->integer) { return qtrue; } return (stat.ullTotalPhys <= MEM_THRESHOLD) ? qtrue : qfalse; @@ -249,10 +234,9 @@ qboolean Sys_LowPhysicalMemory(void) { Sys_Mkdir ============== */ -qboolean Sys_Mkdir( const char *path ) { - if( !CreateDirectory( path, NULL ) ) - { - if( GetLastError( ) != ERROR_ALREADY_EXISTS ) +qboolean Sys_Mkdir(const char *path) { + if (!CreateDirectory(path, NULL)) { + if (GetLastError() != ERROR_ALREADY_EXISTS) return qfalse; } return qtrue; @@ -263,11 +247,11 @@ qboolean Sys_Mkdir( const char *path ) { Sys_Cwd ============== */ -char *Sys_Cwd( void ) { +char *Sys_Cwd(void) { static char cwd[MAX_OSPATH]; - _getcwd( cwd, sizeof( cwd ) - 1 ); - cwd[MAX_OSPATH-1] = 0; + _getcwd(cwd, sizeof(cwd) - 1); + cwd[MAX_OSPATH - 1] = 0; return cwd; } @@ -275,14 +259,13 @@ char *Sys_Cwd( void ) { /* Resolves path names and determines if they are the same */ /* For use with full OS paths not quake paths */ /* Returns true if resulting paths are valid and the same, otherwise false */ -bool Sys_PathCmp( const char *path1, const char *path2 ) { +bool Sys_PathCmp(const char *path1, const char *path2) { char *r1, *r2; r1 = _fullpath(NULL, path1, MAX_OSPATH); r2 = _fullpath(NULL, path2, MAX_OSPATH); - if(r1 && r2 && !Q_stricmp(r1, r2)) - { + if (r1 && r2 && !Q_stricmp(r1, r2)) { free(r1); free(r2); return true; @@ -301,26 +284,25 @@ DIRECTORY SCANNING ============================================================== */ -#define MAX_FOUND_FILES 0x1000 +#define MAX_FOUND_FILES 0x1000 -void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, char **psList, int *numfiles ) { - char search[MAX_OSPATH], newsubdirs[MAX_OSPATH]; - char filename[MAX_OSPATH]; - intptr_t findhandle; +void Sys_ListFilteredFiles(const char *basedir, char *subdirs, char *filter, char **psList, int *numfiles) { + char search[MAX_OSPATH], newsubdirs[MAX_OSPATH]; + char filename[MAX_OSPATH]; + intptr_t findhandle; struct _finddata_t findinfo; - if ( *numfiles >= MAX_FOUND_FILES - 1 ) { + if (*numfiles >= MAX_FOUND_FILES - 1) { return; } if (strlen(subdirs)) { - Com_sprintf( search, sizeof(search), "%s\\%s\\*", basedir, subdirs ); - } - else { - Com_sprintf( search, sizeof(search), "%s\\*", basedir ); + Com_sprintf(search, sizeof(search), "%s\\%s\\*", basedir, subdirs); + } else { + Com_sprintf(search, sizeof(search), "%s\\*", basedir); } - findhandle = _findfirst (search, &findinfo); + findhandle = _findfirst(search, &findinfo); if (findhandle == -1) { return; } @@ -329,25 +311,24 @@ void Sys_ListFilteredFiles( const char *basedir, char *subdirs, char *filter, ch if (findinfo.attrib & _A_SUBDIR) { if (Q_stricmp(findinfo.name, ".") && Q_stricmp(findinfo.name, "..")) { if (strlen(subdirs)) { - Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s\\%s", subdirs, findinfo.name); + Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s\\%s", subdirs, findinfo.name); + } else { + Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s", findinfo.name); } - else { - Com_sprintf( newsubdirs, sizeof(newsubdirs), "%s", findinfo.name); - } - Sys_ListFilteredFiles( basedir, newsubdirs, filter, psList, numfiles ); + Sys_ListFilteredFiles(basedir, newsubdirs, filter, psList, numfiles); } } - if ( *numfiles >= MAX_FOUND_FILES - 1 ) { + if (*numfiles >= MAX_FOUND_FILES - 1) { break; } - Com_sprintf( filename, sizeof(filename), "%s\\%s", subdirs, findinfo.name ); - if (!Com_FilterPath( filter, filename, qfalse )) + Com_sprintf(filename, sizeof(filename), "%s\\%s", subdirs, findinfo.name); + if (!Com_FilterPath(filter, filename, qfalse)) continue; - psList[ *numfiles ] = CopyString( filename ); + psList[*numfiles] = CopyString(filename); (*numfiles)++; - } while ( _findnext (findhandle, &findinfo) != -1 ); + } while (_findnext(findhandle, &findinfo) != -1); - _findclose (findhandle); + _findclose(findhandle); } static qboolean strgtr(const char *s0, const char *s1) { @@ -356,11 +337,11 @@ static qboolean strgtr(const char *s0, const char *s1) { l0 = strlen(s0); l1 = strlen(s1); - if (l1 s0[i]) { return qtrue; } @@ -371,30 +352,30 @@ static qboolean strgtr(const char *s0, const char *s1) { return qfalse; } -char **Sys_ListFiles( const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs ) { - char search[MAX_OSPATH]; - int nfiles; - char **listCopy; - char *list[MAX_FOUND_FILES]; +char **Sys_ListFiles(const char *directory, const char *extension, char *filter, int *numfiles, qboolean wantsubs) { + char search[MAX_OSPATH]; + int nfiles; + char **listCopy; + char *list[MAX_FOUND_FILES]; struct _finddata_t findinfo; - intptr_t findhandle; - int flag; - int i; - int extLen; + intptr_t findhandle; + int flag; + int i; + int extLen; if (filter) { nfiles = 0; - Sys_ListFilteredFiles( directory, "", filter, list, &nfiles ); + Sys_ListFilteredFiles(directory, "", filter, list, &nfiles); - list[ nfiles ] = 0; + list[nfiles] = 0; *numfiles = nfiles; if (!nfiles) return NULL; - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_LISTFILES ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_LISTFILES); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; @@ -402,93 +383,90 @@ char **Sys_ListFiles( const char *directory, const char *extension, char *filter return listCopy; } - if ( !extension) { + if (!extension) { extension = ""; } // passing a slash as extension will find directories - if ( extension[0] == '/' && extension[1] == 0 ) { + if (extension[0] == '/' && extension[1] == 0) { extension = ""; flag = 0; } else { flag = _A_SUBDIR; } - extLen = strlen( extension ); + extLen = strlen(extension); - Com_sprintf( search, sizeof(search), "%s\\*%s", directory, extension ); + Com_sprintf(search, sizeof(search), "%s\\*%s", directory, extension); // search nfiles = 0; - findhandle = _findfirst (search, &findinfo); + findhandle = _findfirst(search, &findinfo); if (findhandle == -1) { *numfiles = 0; return NULL; } do { - if ( (!wantsubs && flag ^ ( findinfo.attrib & _A_SUBDIR )) || (wantsubs && findinfo.attrib & _A_SUBDIR) ) { + if ((!wantsubs && flag ^ (findinfo.attrib & _A_SUBDIR)) || (wantsubs && findinfo.attrib & _A_SUBDIR)) { if (*extension) { - if ( strlen( findinfo.name ) < extLen || - Q_stricmp( - findinfo.name + strlen( findinfo.name ) - extLen, - extension ) ) { + if (strlen(findinfo.name) < extLen || Q_stricmp(findinfo.name + strlen(findinfo.name) - extLen, extension)) { continue; // didn't match } } - if ( nfiles == MAX_FOUND_FILES - 1 ) { + if (nfiles == MAX_FOUND_FILES - 1) { break; } - list[ nfiles ] = CopyString( findinfo.name ); + list[nfiles] = CopyString(findinfo.name); nfiles++; } - } while ( _findnext (findhandle, &findinfo) != -1 ); + } while (_findnext(findhandle, &findinfo) != -1); - list[ nfiles ] = 0; + list[nfiles] = 0; - _findclose (findhandle); + _findclose(findhandle); // return a copy of the list *numfiles = nfiles; - if ( !nfiles ) { + if (!nfiles) { return NULL; } - listCopy = (char **)Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ), TAG_LISTFILES ); - for ( i = 0 ; i < nfiles ; i++ ) { + listCopy = (char **)Z_Malloc((nfiles + 1) * sizeof(*listCopy), TAG_LISTFILES); + for (i = 0; i < nfiles; i++) { listCopy[i] = list[i]; } listCopy[i] = NULL; do { flag = 0; - for(i=1; i= 1) - { - if (FS_FileIsInPAK(name, NULL) == 1) - { + if (len >= 1) { + if (FS_FileIsInPAK(name, NULL) == 1) { char *tempFileName; - if ( FS_WriteToTemporaryFile(data, len, &tempFileName) ) - { + if (FS_WriteToTemporaryFile(data, len, &tempFileName)) { result.tempDLLPath = tempFileName; result.succeeded = true; } @@ -526,8 +500,7 @@ UnpackDLLResult Sys_UnpackDLL(const char *name) return result; } -bool Sys_DLLNeedsUnpacking() -{ +bool Sys_DLLNeedsUnpacking() { #if defined(_JK2EXE) return false; #else @@ -542,21 +515,19 @@ Sys_PlatformInit Platform-specific initialization ================ */ -void Sys_PlatformInit( void ) { +void Sys_PlatformInit(void) { TIMECAPS ptc; - if ( timeGetDevCaps( &ptc, sizeof( ptc ) ) == MMSYSERR_NOERROR ) - { + if (timeGetDevCaps(&ptc, sizeof(ptc)) == MMSYSERR_NOERROR) { timerResolution = ptc.wPeriodMin; - if ( timerResolution > 1 ) - { - Com_Printf( "Warning: Minimum supported timer resolution is %ums " - "on this system, recommended resolution 1ms\n", timerResolution ); + if (timerResolution > 1) { + Com_Printf("Warning: Minimum supported timer resolution is %ums " + "on this system, recommended resolution 1ms\n", + timerResolution); } - timeBeginPeriod( timerResolution ); - } - else + timeBeginPeriod(timerResolution); + } else timerResolution = 0; } @@ -567,27 +538,25 @@ Sys_PlatformExit Platform-specific exit code ================ */ -void Sys_PlatformExit( void ) -{ - if ( timerResolution ) - timeEndPeriod( timerResolution ); +void Sys_PlatformExit(void) { + if (timerResolution) + timeEndPeriod(timerResolution); } -void Sys_Sleep( int msec ) -{ - if ( msec == 0 ) +void Sys_Sleep(int msec) { + if (msec == 0) return; #ifdef DEDICATED - if ( msec < 0 ) - WaitForSingleObject( GetStdHandle( STD_INPUT_HANDLE ), INFINITE ); + if (msec < 0) + WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), INFINITE); else - WaitForSingleObject( GetStdHandle( STD_INPUT_HANDLE ), msec ); + WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), msec); #else // Client Sys_Sleep doesn't support waiting on stdin - if ( msec < 0 ) + if (msec < 0) return; - Sleep( msec ); + Sleep(msec); #endif }